SET TERM ^ ;

CREATE OR ALTER TRIGGER VRHF_EMP_TCOLCON_BANCO_AIU0 FOR VRHF_EMP_TCOLCON_BANCO
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TADSAL_FIXO_BI0 FOR VRHF_EMP_TADSAL_FIXO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER trigger tdefestabdown_bu0 for tdefestabdown
active before update position 0
AS
begin
  /* Trigger text */

end^

create or alter function F_IR_ISENTO_ESTRANGEIRO (
    PRCODCLA integer, 
	PRTRIBUTACAOEXTERIOR integer)
returns boolean
as
begin
  IF ((PRCODCLA = 31) and (COALESCE(PRTRIBUTACAOEXTERIOR,0) IN (40, 41, 42, 43, 44, 50))) THEN
    RETURN TRUE;
  ELSE
    RETURN FALSE;
end^

CREATE OR ALTER TRIGGER VRHF_EMP_TADSAL_FIXO_BU0 FOR VRHF_EMP_TADSAL_FIXO
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end
^

create or alter procedure SP_VALIDA_CREDITO_RESCISAO (
    PRCODEMP varchar(32000),
    PRCODCOL varchar(32000),
    PRREFENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDDATARESCISAO date,
    BDDATABUSCA date,
    BDDATAATUAL date,
    BDEXISTECALCULO varchar(5))
as
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(32000);
declare variable WQTD integer;
begin
  /* Procedure Text */
  suspend;
end^

create or alter procedure SP_MARCARTODAS_DOWNLOAD (
    PROPCAO varchar(1),
    PRRAIZ varchar(50),
    PRFILTRO varchar(32000))
returns (
    BDNAOALTEROU integer)
as
begin
  /* Procedure Text */

  suspend;
end^

CREATE OR ALTER trigger vrh_emp_credito_trabalhador_rescisao_bi0 for vrh_emp_credito_trabalhador_rescisao
active before insert position 0
AS
begin
end
^
create or alter procedure SP_VRHF_DADOS_IR_FN_FICHA (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PREXPORTACAO integer = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBASE13 numeric(18,6),
    BDVALORDIFERENCADEDUCOES numeric(18,2),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDVALOR13 numeric(18,6),
    BDTIPODEDUCAOFOLHA integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
begin suspend; end^

create or alter procedure SP_VSUC_EXPORTA_LAN_SIS (
    PRNOMESIS varchar(100),
    PRCODCCSIS varchar(5),
    PRCODFILIALSIS varchar(5),
    PRCONTASSIS varchar(5),
    PREMPRESASSIS varchar(5),
    PRCODCLSIS varchar(5),
    PRCODTERSIS varchar(5),
    PRCODNACSIS varchar(5),
    PRCODTFUCSIS varchar(5),
    PRCODNIVELTFUCSIS varchar(5),
    PRCODVERBASIS varchar(5),
    PRCODTPOFOLSIS varchar(5),
    PRCODHISTSIS varchar(5),
    PRCODSISTPLA boolean,
    PRAGRUPARLAN boolean,
    PRWHERE varchar(2000),
    PRDATAINI date,
    PRDATAFIM date)
returns (
    BDCODSIS integer,
    BDCODEMP integer,
    BDCODEMPNOVO varchar(100),
    BDCODPLAPADRAO integer,
    BDDEBITO varchar(100),
    BDCREDITO varchar(100),
    BDDATA date,
    BDVALOR numeric(18,2),
    BDCHAVEON varchar(120),
    BDDCTO varchar(15),
    BDCODHIST integer,
    BDTIPOLAN integer,
    BDCODTPHI integer,
    BDDEBCRE integer,
    BDCONCD varchar(200),
    BDCODCENTRO integer,
    BDCCDEB varchar(100),
    BDCCCRED varchar(100),
    BDCOMPL varchar(200),
    BDNOMEHIST varchar(100),
    BDTRANSACAO integer,
    BDPERCRATEIO numeric(18,4),
    BDVALRATEIO numeric(18,2),
    BDCODTERCEIROD integer,
    BDCODTERCEIROC integer,
    BDCHAVEONLINE varchar(120),
    BDCOMPLEMENTO varchar(200))
as
declare variable WCODMAIORQMIL integer;
declare variable WSQL varchar(22480);
declare variable WDATAINI varchar(10);
declare variable WDATAFIM varchar(10);
begin
  suspend;
end^

create or alter procedure SP_VRHF_DADOS_IR_SOCIO (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXAFILIAIS integer = null,
    PRCODMATRIZ varchar(15000) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDDATAPGTO date,
    BDLUCROPJ DM_NUMERIC_15_2,
    BDCODTIPO integer)
as
begin suspend; end^

create or alter procedure SP_VRHF_DADOS_IR_INTFT13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRINSSANTES smallint = 1,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0,
    PRPORCC smallint = 1)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
BEGIN suspend; END^

create or alter procedure SP_VRHF_DADOS_IR_FICHA_INT13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRATUALIZAINFODESCSIMPLE boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
BEGIN suspend; END^

CREATE OR ALTER TRIGGER TEMP_VRHF_ATUALIZASINONIMOS_BI0 FOR TEMP_VRHF_ATUALIZASINONIMOS
ACTIVE BEFORE INSERT POSITION 0
as
 declare variable wnovocod integer;
 declare variable wordemexistente integer;
begin
end^

CREATE OR ALTER PROCEDURE SP_VRHF_ATUALIZA_DESC_CBOS
AS
declare variable WBDCODCBO integer;
declare variable WBDCODCBOTSIN integer;
declare variable WBDDESCCBO varchar(150);
declare variable WBDDESCCBO_ANT varchar(150);
declare variable WEHCBONOVO integer;
declare variable WBDDESCCBOUPPER varchar(150);
declare variable WSQL_BUSCA varchar(1000);
declare variable WMAX_SCORE integer;
declare variable W_DESC_BANCO varchar(150);
declare variable W_ORD_BANCO integer;
declare variable W_DESC_BANCO_LIMPA varchar(150);
declare variable W_RESTO varchar(150);
declare variable W_PALAVRA varchar(150);
declare variable W_POS_ESPACO integer;
declare variable W_PALAVRA_LIMPA varchar(150);
declare variable W_JA_FOI integer;
declare variable W_QTDE_PALAVRAS integer;
declare variable W_QTDE_TOTAL_PALAVRAS integer;
declare variable W_QTDE_MIN_ACEITA integer;
declare variable W_QTDE_ACERTOS integer;
declare variable WMSGLOG varchar(32700);
declare variable WMSGLOGAUX varchar(32700);
BEGIN
END^

create or alter procedure SP_VRHF_DADOS_IR_FCT_INT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PREXPORTACAO integer = 0,
    PRPORCC smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    WGCLASS varchar(13000),
    WDESCVER2 varchar(70),
    WI integer,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFFC integer,
    BDINCIDESOCIALFER integer,
    BDCODACCONV integer,
    BDCODFIR integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
BEGIN suspend; END^

create or alter procedure SP_VRHF_DADOS_IR_FICHAFCINT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ )
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFFC integer,
    BDINCIDESOCIALFER integer,
    BDCODACCONV integer,
    BDCODFIR integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
BEGIN suspend; END^

create or alter procedure SP_VRHF_DADOS_IR_FICHAFE (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRATUALIZAINFODESCSIMPLE boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDREFINIGOZO integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDCODFE integer,
    BDINIPERAQUIS date,
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
begin suspend; end^

create or alter procedure SP_VRHF_DADOS_IR_FICHAFC (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRVERCALCRRA integer = -1)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDREFIRRFESOCIAL integer,
    BDVERCALCRRA integer,
    BDTIPODEDUCAOFOLHA integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(15,2),
    BDCODACCONV integer,
    BDMESESRRA numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFFC integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDCODTIPO integer)
as
BEGIN suspend; END^

create or alter procedure SP_VRHF_DADOS_IR_FICHA (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PREXPORTACAO integer = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBASE13 numeric(18,6),
    BDVALORDIFERENCADEDUCOES numeric(18,2),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDVALOR13 numeric(18,6),
    BDTIPODEDUCAOFOLHA integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
begin suspend; end^

create or alter procedure SP_VERBAS_INCIDENCIAS
returns (
    BDCODVER integer,
    BDDESCVER varchar(300),
    BDREFVER integer,
    BDCODINCIDIRRF integer,
    BDDESCIRRF varchar(300),
    BDRENDISENTOIRVER varchar(5),
    BDINDRESC varchar(5),
    BDIMPISENTOS varchar(5),
    BDIMPINSSNORMAL varchar(5),
    BDIMPINSSFERIAS varchar(5),
    BDIMPINSS13 varchar(5),
    BDIMPINSSNAOINCIDE varchar(5),
    BDCODINCIDINSS integer,
    BDDESCINCINSS varchar(300),
    BDINSSSISTEMA integer,
    BDBASEGPS varchar(5))
as
begin
  /* Procedure Text */
  suspend;
end^

create or alter procedure SP_MATRIZ_E_FILIAIS (
    PRCODEMP varchar(30000))
returns (
    bdcodemp integer)
as
declare variable WSQL varchar(30000);
declare variable WSQL2 varchar(3000);
declare variable WMATRIZ integer;
begin
  suspend;
end^

create or alter procedure SP_VINCULO_ATUAL_NAO_COL(
    PRMATRIZ integer,
    PRCPF varchar(20),
    PRANO integer)
returns (
    BDCPF varchar(20),
    BDREF integer,
    BDORIGEM integer, 
    BDCODEMP integer
    )
as
begin
  suspend;
end^

CREATE OR ALTER procedure SP_BUSCA_DESCRICAO_EVENTO (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDDESCRICAO varchar(500))
as
begin
  suspend;
end^

CREATE OR ALTER procedure SP_VRH_EMPS_BANCO_AG_RHNET (
    PRCODBAN integer,
    PRCODAG integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDRHNET boolean,
    BDVINCCOL boolean)
as
begin
  suspend;
end^

create or alter procedure SP_REL_TOT_5002_RUBRICAS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRCODEMPORD integer,
    PRREFEMISSAO integer,
    PRAUTONOMO integer)
as
begin

end^

create or alter procedure SP_VERBAS_INCIDENCIAS_INSS (
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000),
    PRCODTER varchar(30000))
returns (
    BDCODVER integer,
    BDDESCVER varchar(300),
    BDREFVER integer,
    BDIMPINSSNORMAL varchar(5),
    BDIMPINSSFERIAS varchar(5),
    BDIMPINSS13 varchar(5),
    BDIMPINSSNAOINCIDE varchar(5),
    BDCODINCIDINSS integer,
    BDDESCINCINSS varchar(300),
    BDINSSSISTEMA integer,
    BDBASEGPS varchar(5),
    BDVALOR numeric(15,6),
    BDTIPOCALC varchar(100),
    BDCODEMP integer,
    BDCODCOL integer,
    BDCNPJEMP varchar(18),
    BDCODMATRIZ integer,
    BDOBSERVACAO varchar(32700),
    BDDESCINSSSISTEMA varchar(50),
    BDNOMCOL varchar(70),
    BDNOMEMP DM_BDNOMEMP)
as
BEGIN
  suspend;
END^

create or alter procedure SP_TFERIADOS_RHNET (
    PRANOMESI integer,
    PRANOMESF integer,
    PRCODSINTRAB integer = null)
returns (
    BDCODEMP integer,
    BDCODEMPRHNET integer,
    BDDATAFER date,
    BDDESCFER varchar(50),
    BDCODCID integer,
    BDCODUF integer,
    BDREFFER integer,
    BDCODSINTRAB integer,
    BDDATAFERI date,
    BDCODFERI integer,
    BDFERIBANC DM_BOOLEAN,
    BDANO integer)
as
BEGIN
  suspend;
END^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TRUBICA5002_BI0 FOR VRHF_TEMP_EMP_TRUBICA5002
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TRUBICA5002_BIU0 FOR VRHF_TEMP_EMP_TRUBICA5002
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
as
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TCOL_CALC_BIU0 FOR VRHF_EMP_TCOL_CALC
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TPREPSIT_PADRAO_BI0 FOR VRH_BASE_TPREPSIT_PADRAO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TPREPFN_AI0 FOR VRHF_EMP_TPREPFN
ACTIVE AFTER INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TPREPFN_AD0 FOR VRHF_EMP_TPREPFN
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

create or alter procedure SP_VRHF_TAB_IR_REDUCAO (
    PRCODIR integer,
    PRTIPOCALC integer,
    PRCOMPETENCIA integer)
returns (
    BDCODIR integer,
    BDCODIRRED integer,
    BDREFIR integer,
    BDCODFAIXA integer,
    BDVALORATE DM_NUMERIC_20MILHOES_2CASAS,
    BDLIMITEDED DM_NUMERIC_20MILHOES_2CASAS,
    BDINDICE numeric(15,6))
as
begin
  suspend;
end^

CREATE OR ALTER TRIGGER VRHF_TABELAS_TIRREDUCAO_BI0 FOR VRHF_TABELAS_TIRREDUCAO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_TABELAS_TIRREDFAIXAS_BI0 FOR VRHF_TABELAS_TIRREDFAIXAS
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_TABELAS_TIRREDITENS_BI0 FOR VRHF_TABELAS_TIRREDITENS
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER EMPRESAS_TSOCCOTAS_PGTO_BIU0 FOR EMPRESAS_TSOCCOTAS_PGTO
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TPREPFN_BU0 FOR VRHF_EMP_TPREPFN
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END
^

create or alter procedure SP_VINCULOS_DECLARACAO_DESTINO (
    prAno integer,
    prCPF varchar(30000),
    prAutCol integer)
returns (
    BDCODEMP_FILTRO integer,
    BDCODCOL_FILTRO integer,
    BDCODTER_FILTRO integer,
    BDTIPO integer, 
    BDCPF varchar(20),
    BDCODEMP_IMP integer,
    BDCODCOL_IMP integer,
    BDCODTER_IMP integer)
as
begin
  suspend;
end^

create or alter procedure SP_BUSCA_REDUCAO_NCM (
    PRNCM varchar(10),
    PRISNBS boolean,
    PRDATAFIM date)
returns (
    BDREDUCAO integer,
    BDCCLASSTRIB varchar(30),
    BDLC varchar(100),
    BDLINK_LC varchar(100),
    BDFUND_LEGAL varchar(100),
    BDCODCST integer,
    BDCODIS integer)
as
declare variable I integer;
declare variable WWHERE varchar(1000);
declare variable WSQL varchar(1000);
declare variable BDEXCECAO varchar(1000);
declare variable V_EXCECAO smallint;
BEGIN
  suspend;
END^

create or alter procedure SP_NCM_IS_EXCECAO (
    PRNCM varchar(10),
    PREXCECOES varchar(5000))
returns (
    ISEXCECAO smallint)
as
declare variable WSQL varchar(5000);
declare variable WITEM varchar(50);
declare variable WTEXTO varchar(5000);
declare variable WEXC varchar(20);
BEGIN
  suspend;
END^

create or alter procedure SP_VRHF_SOMENTE_RATEIO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFTOMADOR integer,
    BDCODVER integer,
    BDREFVFT DM_NUMERIC_20MILHOES_2CASAS,
    BDREFAUXVFT DM_NUMERIC_20MILHOES_2CASAS,
    BDVALVFT DM_NUMERIC_20MILHOES_2CASAS,
    BDIGNREFVFT DM_BOOLEAN,
    BDIGNVALVFT DM_BOOLEAN,
    BDVALVIFT DM_NUMERIC_20MILHOES_2CASAS,
    BDSALBASEFT DM_NUMERIC_20MILHOES_2CASAS,
    BDREFVFTMAX DM_NUMERIC_20MILHOES_2CASAS,
    BDREFAUXVFTMAX DM_NUMERIC_20MILHOES_2CASAS,
    BDORIGEMVERBA integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRH_GET_CODCOL_SWS (
    PRFILTRO varchar(30000))
returns (
    BDCODEMPORD integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCPFCOL varchar(14),
    BDSTATUS integer,
    BDEMAILCOL varchar(200),
    BDEMAIL2COL varchar(100),
    BDNOMCOL varchar(70))
as
declare variable WJOINEMP varchar(30000);
declare variable WSQL varchar(30000);
declare variable WEMPATU integer;
declare variable WCPFATU varchar(14);
BEGIN
  suspend;
END^

CREATE OR ALTER TRIGGER VRH_BASE_TTERC_TDEP_REF_AIU0 FOR VRH_BASE_TTERC_TDEP_REF
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TTERC_TDEP_AU0 FOR VRH_BASE_TTERC_TDEP
ACTIVE AFTER UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TDEP_AU0 FOR VRH_EMP_TDEP
ACTIVE AFTER UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TDEP_REF_AI0 FOR VRH_EMP_TDEP_REF
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TRRA5002_ADV_BI0 FOR VRHF_TEMP_EMP_TRRA5002_ADV
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VRH_EMP_TDIFERENCA5002_BI0 FOR VRH_EMP_TDIFERENCA5002
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TRRA5002_BI0 FOR VRHF_TEMP_EMP_TRRA5002
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

create or alter procedure SP_REL_TOT_5002_RRA (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRUNICO integer,
    PRTAGSTR varchar(100),
    PRDESCRICAOFOLHA varchar(1000),
    PRCODEMPORD integer,
    PRCODACCONV integer,
    PRQTDMESESRRA numeric(16,0))
as
declare variable WCODEMP integer;
declare variable WCPFCOL varchar(14);
declare variable WCODACCONV integer;
declare variable WTIPOPROCESSO integer;
declare variable WNUMPROCESSO varchar(21);
declare variable WDESCRRA varchar(50);
declare variable WTOTALDESPJDC numeric(18,6);
BEGIN

end^

create or alter procedure SP_VRH_DECLARACAO_RENDIMENTOS_7_PLANOSAUDE (
    PRCODEMP varchar(32000),
    PRCODCOL varchar(32000),
    PRANO integer,
    PREXPORTACAO integer = 0,
    PRPENSAORRA boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDTIPOCALCFIR integer,
    BDINFORMACAO varchar(250),
    BDVALOR numeric(18,6),
    BDCPFCOL varchar(14),
    BDCPFBENEF varchar(14),
    BDTIPOIMP integer,
    BDVALOR2 numeric(18,6),
    BDTITCOL varchar(100),
    BDTITCOL2 varchar(100))
as
BEGIN
  SUSPEND;
END^

create or alter procedure SP_VRH_DECLARACAO_RENDIMENTOS_7 (
    PRCODEMP varchar(32000),
    PRCODCOL varchar(32000),
    PRANO integer,
    PREXPORTACAO integer = 0,
    PRPENSAORRA boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDTIPOCALCFIR integer,
    BDINFORMACAO varchar(250),
    BDVALOR numeric(18,6),
    BDCPFCOL varchar(14),
    BDCPFBENEF varchar(14),
    BDTIPOIMP integer,
    BDVALOR2 numeric(18,6),
    BDTITCOL varchar(100),
    BDTITCOL2 varchar(100))
AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRH_GETCODRECEITA_5002 (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRTERCEIRO integer,
    PRTIPOFOLHA integer,
    PRTIPOCALCULO integer,
    PRCODCLATRI integer)
returns (
    BDCODREC varchar(6))
as
declare variable WCATEGESOCIAL integer;
declare variable WRRA boolean;
declare variable WRESIDEXT boolean;
declare variable WCLASSTRIB integer;
declare variable WCODPAIS integer;
declare variable WDATARESC date;
begin
  suspend;
end^

create or alter procedure SP_VRH_EXTRATO_DIRF (
    PRCODEMP varchar(30000),
    PRREF integer,
    PRFILTROCPF varchar(30000))
returns (
    BDCODEMPORD integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCOLTER integer,
    BDCONTRCOL integer,
    BDGRUPOCLA integer,
    BDNOMCOL varchar(70),
    BDCPFCOL varchar(18),
    BDCNPJEMP varchar(18),
    BDNOMEMP varchar(100),
    BDBASEIRRF numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDVALORINSS numeric(18,6),
    BDVALORINSS13 numeric(18,6),
    BDTIPO integer,
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDCATEGORIAESOCIAL integer,
    BDCODCLATRI integer,
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOCALCULO integer,
    BDAJCUSTOS numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDBOLSAMEDICO13 numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDUNICO integer,
    BDCODREC varchar(6))
as
declare variable WI integer;
declare variable WREF integer;
begin
 -- suspend;
end^


create or alter procedure SP_EMP_PUXAR_MATRIZ_FILIAIS (
    PRCODEMP integer)
returns (
    BDCODEMP integer)
as
declare variable BDCODMATRIZ integer;
declare variable BDCODFILIAL integer;
begin
 suspend;
end^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBA13_DET_BI0 FOR VRHF_EMP_TVERBA13_DET
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

create or alter procedure SP_CORRIGE_VINCULO_5002 (
    PREMPRESA varchar(30000),
    PRREFERENCIA integer)
as
begin
  --suspend;
end^

create or alter procedure VRH_SP_QUADRO_HORARIO (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRDATAINI date = null,
    PRDATAFIM date = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATA date,
    BDSEQUENCIAL integer,
    BDENTRADA time,
    BDSAIDA time,
    bdPrimeiroDiaFechamento integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRH_COLCON_RHNET_EXP (
    PRFILTRO varchar(32000),
    PRCOMPETENCIA integer,
    PRFILTROCOL smallint = 0,
    PRDADOSINICIAIS smallint = 0,
    PRSOMENTELEITURA smallint = 0)
returns (
    BDCODEMPRHNET integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDLOGRID integer,
    BDENDCOL DM_BDENDERECO,
    BDNUMCOL DM_NUMEND,
    BDCOMPLCOL DM_BDCOMPENDERECO,
    BDBAICOL DM_BDBAIRRO,
    BDCEPCOL varchar(9),
    BDCODCID integer,
    BDDDDCELCOL integer,
    BDCELCOL DM_BDTELEFONE,
    BDDDDCOL integer,
    BDFONECOL DM_BDTELEFONE,
    BDEMAILCOL DM_BDEMAIL,
    BDTIPOSANGUECOL integer,
    BDCORCOL integer,
    BDCABELOSCOL integer,
    BDOLHOSCOL integer,
    BDSEXOCOL integer,
    BDDEFFIS DM_BOOLEAN,
    BDDEFVIS DM_BOOLEAN,
    BDDEFAUD DM_BOOLEAN,
    BDDEFMEN DM_BOOLEAN,
    BDREAB DM_BOOLEAN,
    BDDEFINT DM_BOOLEAN,
    BDCOTADEF DM_BOOLEAN,
    BDDEFCOL DM_BOOLEAN,
    BDOBSDEFFISCOL varchar(300),
    BDNMSOCIAL DM_BDNOMCOL,
    BDALTURACOL DM_NUMERIC_20MILHOES_2CASAS,
    BDPESOCOL DM_NUMERIC_20MILHOES_2CASAS,
    BDSINAISCOL DM_BOOLEAN,
    BDCODCIDNASC integer,
    BDNOMCIDESTRANGEIRO varchar(40),
    BDCODPAIS integer,
    BDDATACHEBRASILCOL date,
    BDDATANASCCOL date,
    BDGRAUINSTCOL integer,
    BDESTCIVCOL integer,
    BDDATAADMCOL date,
    BDDATACADCOL date,
    BDRGCOL varchar(13),
    BDORGEMIRGCOL DM_ORGAOEMISSOR,
    BDDATAEMIRGCOL date,
    BDCODUFRG varchar(2),
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDDATAEMIPISCOL date,
    BDTITELEICOL varchar(13),
    BDZONAELEICOL integer,
    BDSECAOELEICOL integer,
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDATAEMICTPSCOL date,
    BDCODUF varchar(2),
    BDCNHCOL varchar(11),
    BDCATCNHCOL varchar(2),
    BDVENCCNHCOL date,
    BDRESERVISTACOL varchar(16),
    BDNOMPAICOL varchar(70),
    BDNOMMAECOL varchar(70),
    BDNOMCONJCOL varchar(70),
    BDDATANASCCONJCOL date,
    BDCODCLA integer,
    BDTIPOCOL integer,
    BDSALINICOL DM_NUMERIC_15_2,
    BDHORASMENSAISCOL numeric(15,6),
    BDHORASSEMANAISCOL numeric(15,6),
    BDHORASDIARIASCOL numeric(15,6),
    BDPERCINSALUBCOL numeric(15,6),
    BDINCIDINSALUBCOL integer,
    BDPERCPERCULCOL numeric(15,6),
    BDINCIDPERICULCOL integer,
    BDPERCNOTURNOCOL numeric(15,6),
    BDINCIDNOTURNOCOL integer,
    BDCALCVALREFCOL DM_BOOLEAN,
    BDDIASPRAZO1COL integer,
    BDDIASPRAZO2COL integer,
    BDOBSCOL blob sub_type 1 segment size 5000,
    BDDSERIECTPSCOL varchar(1),
    BDTIPOADMCOL integer,
    BDDESCCONTSINCOL DM_BOOLEAN,
    BDCODBAN integer,
    BDCTADEPCOL varchar(15),
    BDTIPOCTACOL integer,
    BDADIANTAMENTO integer,
    BDREGIMEPARCIALCOL DM_BOOLEAN,
    BDSINDICALIZADOCOL DM_BOOLEAN,
    BDCODSINTRAB integer,
    BDFICHAREGCOL varchar(12),
    BDLIVROREGCOL varchar(10),
    BDNROFOLHAREGCOL integer,
    BDDATAADICCOL date,
    BDNATUOCUPCOL integer,
    BDCODTIPOCONTRATO integer,
    BDDTAPOSENT date,
    BDNUMRICCOL varchar(14),
    BDORGAORICCOL varchar(20),
    BDDATAEMIRICCOL date,
    BDNUMRNECOL varchar(14),
    BDORGAORNECOL varchar(20),
    BDDATAEMIRNECOL date,
    BDNUMOCCOL varchar(14),
    BDORGAOOCCOL varchar(20),
    BDDATAEMIOCCOL date,
    BDCASADOBR DM_BOOLEAN,
    BDFILHOSBR DM_BOOLEAN,
    BDCODPAISRES integer,
    BDCODPOSTESTRCOL varchar(10),
    BDEMAIL2COL varchar(100),
    BDFOTOCOL_IMG blob sub_type 0 segment size 32700,
    BDCODAG integer,
    BDDATABAIXACOL date,
    BDDESLIGAMENTO date,
    BDDATAFIMPRAZO1COL date,
    BDDATAFIMPRAZO2COL date,
    BDDATAVALOCCOL date,
    BDSUS varchar(16),
    BDORGAOCNH varchar(20),
    BDDATAEMICNH date,
    BDDIGCTADEPCOL varchar(2),
    BDREGJORTRAB integer,
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDCODQH integer,
    BDCODPQUA integer,
    BDCALCVALTRANSCOL DM_BOOLEAN,
    BDFORMAPAGTOCOL integer,
    BDTIPOCERTCIVILCOL integer,
    BDTERMOCERTCIVILCOL varchar(32),
    BDCARTORIOCERTCIVILCOL varchar(120),
    BDLIVROCERTCIVILCOL varchar(8),
    BDFOLHACERTCIVILCOL varchar(4),
    BDCODCIDCERTCIVIL integer,
    BDDATACERTCIVILCOL date,
    BDCATEGORIAESOCIAL integer,
    BDOCORRENCIACOL integer,
    BDCTAFGTSCOL varchar(11),
    BDSEGDESCOL DM_BOOLEAN,
    BDCARTAOSALCOL varchar(7),
    BDVALORPREVPRIVNCOL DM_NUMERIC_15_2,
    BDVALORPREVPRIV13COL DM_NUMERIC_15_2,
    BDDATATRFCOL date,
    BDCPF_IMG blob sub_type 0 segment size 32700,
    BDRG_IMG blob sub_type 0 segment size 32700,
    BDPIS_IMG blob sub_type 0 segment size 32700,
    BDTITELEITOR_IMG blob sub_type 0 segment size 32700,
    BDCNH_IMG blob sub_type 0 segment size 32700,
    BDCTPS_IMG blob sub_type 0 segment size 32700,
    BDCONTRCOL varchar(12),
    BDSTATUSQC integer,
    BDCODPAISNAS integer,
    BDREGPREV integer,
    BDMODOPAGTOCOL integer,
    BDUFCNH varchar(2),
    BDDTPRIMCNH date,
    BDCODCIDNASCCONJ integer,
    BDREGPROF varchar(20),
    BDCNPJEMPANT varchar(20),
    BDTRANSONUS DM_BOOLEAN,
    BDCODCLE integer,
    BDCARTAOVA varchar(20),
    BDCARTAOVR varchar(20),
    BDCARTAOVT varchar(20),
    BDPERCADISAL DM_NUMERIC_15_2,
    BDTIPOJORNADA integer,
    BDCODCOLPREL integer,
    BDFICHAREGANT varchar(30),
    BDCONDICAOINGRESSO integer,
    BDTEMPORESIDENCIA integer,
    BDMATRICULA varchar(30),
    BDDESCTPJORNADA varchar(100),
    BDINDHORARIONOT integer,
    BDDTEFEITO date,
    BDDESCPAIS varchar(60),
    BDREGIMETRAB integer,
    BDIDRHNET integer,
    BDADMPRELIDRHNET integer)
as
begin
  suspend;
end^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TECONSIGNADO5003_BU0 FOR VRHF_TEMP_EMP_TECONSIGNADO5003
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end
^

create or alter procedure SP_VRHF_RECLAMATORIA_IDESEQPROC (
    PRCODEMP integer,
    PRCHAVE integer,
    PRREFPAGTO integer)
returns (
    BDCODEMP integer,
    BDCHAVE integer,
    BDREFPGTO integer,
    BDCPF varchar(14),
    BDIDESEQPROC integer,
    BDCAMPOCHAVE integer,
    BDNOMCOL varchar(100),
    BDINIPROC integer,
    BDFIMPROC integer,
    BDCODREPERCPROC integer)
as
declare variable WSQL varchar(3000);
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WREFPGTO integer;
declare variable WIDESEQPROC integer;
declare variable WCPF varchar(14);
declare variable WCAMPOCHAVE integer;
declare variable WNOMCOL varchar(300);
BEGIN
  suspend;
END^

CREATE OR ALTER PROCEDURE SP_VRHF_GERA_S2501_TESTE (
    PRCODEMP integer,
    PRQTDCADASTROS integer,
	PRCODRT integer)
AS
DECLARE VARIABLE WI INTEGER;
DECLARE VARIABLE WULTCHAVE INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;

DECLARE VARIABLE WBASENUM BIGINT;
DECLARE VARIABLE WBASECPF VARCHAR(9);
DECLARE VARIABLE WCPFFORMATADO VARCHAR(14);
DECLARE VARIABLE WNOME VARCHAR(100);

DECLARE VARIABLE WCPFOK INTEGER;
DECLARE VARIABLE WTENTATIVAS INTEGER;
BEGIN
END^

CREATE OR ALTER trigger vrh_tencargos_rt_bd0 for vrh_tencargos_rt
active before delete position 0
AS
begin
end^

create or alter procedure SP_GRAVANFPRODRURAL (
    PRSESSAO integer,
    PRULTCHAVE integer)
as
declare variable WCODEMP integer;
declare variable WCHAVEEF integer;
declare variable WDATAEMISSAO date;
declare variable WNUMDOC integer;
declare variable WREFNF varchar(6);
declare variable WRETINSS numeric(15,2);
declare variable WVLRNF numeric(15,2);
declare variable WCHAVERH integer;
declare variable WTPCOMERC integer;
declare variable WCNPJTER varchar(18);
declare variable WSERIE varchar(15);
declare variable WVLRFUNRURAL numeric(15,2);
declare variable BDVLRGILRAT numeric(15,2);
declare variable BDVLRSENAR numeric(15,2);
begin
end^

create or alter procedure SP_INATIVA_TERCEIROS_DUPLICADOS (
    P_TIPO_INATIVACAO integer,
    P_IGNORAR_ZERADOS DM_BOOLEAN,
    P_FILTRO_CODCNAE integer,
    P_FILTRO_PJPF varchar(20),
    P_FILTRO_CODCID integer,
    P_FILTRO_PRURAL DM_BOOLEAN,
    P_FILTRO_CGCTER varchar(18),
    P_FILTRO_CODUF integer,
    P_REFERENCIA integer)
returns (
    QNTINATIVOS integer)
as
declare variable WCODTERLIST varchar(10000);
declare variable WCODTER integer;
declare variable WCOUNT integer;
declare variable WCODPAIS integer;
declare variable WEXECUTE_STATEMENT integer;
declare variable VSQL varchar(32000);
declare variable VSQL_REF varchar(1000);
BEGIN
end^ 

create or alter procedure SP_TROCAGLOBAL_TERCEIROS (
    P_FILTRO_CODCNAE integer,
    P_FILTRO_PJPF varchar(20),
    P_FILTRO_CODCID integer,
    P_FILTRO_PRURAL DM_BOOLEAN,
    P_FILTRO_REF integer,
    P_FILTRO_CGCTER varchar(18),
    P_PRURAL_DE DM_BOOLEAN,
    P_PRURAL_PARA DM_BOOLEAN,
    P_CARAC_DE integer,
    P_CARAC_PARA integer,
    P_INATIVAR_REPETIDO DM_BOOLEAN,
    P_TIPO_INATIVACAO integer,
    P_IGNORAR_ZERADOS DM_BOOLEAN,
    P_FILTRO_CODUF integer)
returns (
    P_QTD_INATIVADOS integer)
as
declare variable W_QTD_INATIVADOS integer;
declare variable WSQL varchar(32000);
BEGIN
end^

create or alter procedure SP_VRH_VALORES_TOT_FGTS (
    PRCODEMP varchar(30000),
    PRREFARQ integer,
    PRTIPOEVT integer,
    PRVERSAO integer,
    PRCPF varchar(30000))
returns (
    BDCODIGO integer,
    BDREFARQ integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDXML blob sub_type 0 segment size 80,
    BDVERSAO integer)
as
BEGIN
  suspend;
END^

create or alter procedure SP_DET_CREDITO_TRABALHADOR_ADTO (
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDDESCVER varchar(40),
    BDCLAVER varchar(20),
    BDVALORVERBA numeric(15,6),
    BDTIPOFOLHA integer,
    BDTIPOCODVER integer,
    BDDATA date)
as
declare variable WSQL varchar(30000);
declare variable WREFERENCIA varchar(6);
declare variable WTIPOCODVER integer;
declare variable WCODCOLANT integer;
declare variable WCODEMPANT integer;
declare variable WTEMPARCELAMENTO integer;
declare variable WLISTACOLADIANTAMENTO varchar(20000);
declare variable WTESTE varchar(10);
begin
 suspend;
end^

create or alter procedure INC_REFERENCIA (
    PRREFERENCIA integer,
    PRMESES integer = 1)
returns (
    BDREFERENCIA integer)
as
BEGIN
  suspend;
END^

create or alter procedure SP_VRH_GR_PARCELAMENTOS (
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP DM_CNPJ_CPF,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL varchar(14),
    BDDSREF varchar(7),
    BDREFPI integer,
    BDDTREF date,
    BDDTREFSEG date,
    BDVALORPI DM_NUMERIC_15_2,
    BDVALORDESC DM_NUMERIC_15_2,
    BDDIFF DM_NUMERIC_15_2,
    BDNOMCID varchar(40),
    BDCONTRATOPAR varchar(30),
    BDCODBAN integer,
    BDNOMBAN varchar(300),
    BDCODFEBRABAN integer,
    BDTEMRESCISAO smallint,
    BDPAGTOPARCIAL smallint)
as
begin
  suspend;
end^

CREATE OR ALTER procedure SP_GENIMPORTACAO_SERVRPA
returns (
    BDLOTEIMPORTACAO integer)
as
declare variable WCONTINUARBUSCANDOGEN DM_BOOLEAN;
declare variable WLOTEIMPORTACAODOGEN integer;
declare variable WULTIMOLOTEIMPORTACAO integer;
BEGIN
  SUSPEND;
END^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TECONSIGNADO5003_BI0 FOR VRHF_TEMP_EMP_TECONSIGNADO5003
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE WEXISTEREGISTRO INTEGER;
DECLARE VARIABLE VCODIGO INTEGER;
begin
end
^

create or alter procedure SP_ADD_CONSIGNADO_5003 (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCPF varchar(14),
    PRREF integer,
    PRCODEMPORD integer,
    PRGRUPOCLA integer,
    PRCONTRCOL integer,
    PRCNPJEMP varchar(18),
    PRCATEGORIAESOCIAL integer)
as
declare variable WSQL varchar(1000);
declare variable WINSTITUICAOFINANC integer;
declare variable WNROCONTRATOECONSIGNADO varchar(30);
declare variable WVALOR numeric(18,6);
declare variable WEVT integer;
declare variable WEVTANT integer;
declare variable WEXISTEREGISTRO integer;
declare variable WTAGSTR varchar(100);
declare variable WCODPARC integer;
declare variable WMOTIVORESCISAO integer;
declare variable WEXPORTAGRRF integer;
declare variable WDATAPGTORESC date;
declare variable WRESCISORIO integer;
begin
end
^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_CREDITOTRAB_C_BI0 FOR VRH_ESOCIAL_CREDITOTRAB_C
ACTIVE BEFORE INSERT POSITION 0
as
declare variable VCODIGO integer;
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TPARCDETCALC_BI0 FOR VRHF_EMP_TPARCDETCALC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^


CREATE OR ALTER TRIGGER VRH_EMP_TPARCELAMENTOS_ITENS_BD0 FOR VRH_EMP_TPARCELAMENTOS_ITENS
ACTIVE BEFORE DELETE POSITION 0
AS
begin
end
^
CREATE OR ALTER TRIGGER TAVISOS_EXIBIDOS_BI0 FOR TAVISOS_EXIBIDOS
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TFAQ_WEB_BI0 FOR TFAQ_WEB
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER trigger tpedidos_bi_biu0 for tpedidos_bi
active before insert or update position 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TC195IVASP_AD0 FOR TOL_VEF_EMP_TC195IVASP
ACTIVE AFTER DELETE POSITION 0
AS
declare variable WCODIGO integer;
begin  
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TC195IVASP_BI0 FOR TOL_VEF_EMP_TC195IVASP
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin  
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TC197IVASP_AD0 FOR TOL_VEF_EMP_TC197IVASP
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END^

create or alter procedure SP_VRH_GR_PARCELAMENTOS (
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP DM_CNPJ_CPF,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL varchar(14),
    BDDSREF varchar(7),
    BDREFPI integer,
    BDDTREF date,
    BDDTREFSEG date,
    BDVALORPI DM_NUMERIC_15_2,
    BDVALORDESC DM_NUMERIC_15_2,
    BDDIFF DM_NUMERIC_15_2,
    BDNOMCID varchar(40),
    BDCONTRATOPAR varchar(30),
    BDCODBAN integer,
    BDNOMBAN varchar(300),
    BDCODFEBRABAN integer,
    BDTEMRESCISAO smallint,
    BDPAGTOPARCIAL smallint)
as
begin
  suspend;
end^

create or alter procedure SP_VRH_PARCELAMENTO_CREDTRAB_FERIAS (
    PRCODEMP varchar(32700),
    PRCODCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODPARC integer,
    BDPARCELAPI integer,
    BDVALORPI numeric(18,6),
    BDCODVER integer,
    BDREFPI integer,
    BDQTDMESESPAR integer,
    BDPROVDESCPAR integer,
    BDECONSIGNADO char(5),
    BDVALORDESC numeric(18,2),
    BDCODBAN integer,
    BDCONTRATOPAR varchar(30),
    BDNOMBAN varchar(60),
    BDVALORDESC_NOR numeric(18,2),
    BDDATAINI date,
    BDTOTALPAR integer,
    BDREFINIPAR integer,
    BDMENSAL varchar(5),
    BDRESCISORIO varchar(5),
    BDPERCENTUALGARANTIA numeric(18,2),
    BDVALORSALDODEVEDOR numeric(18,2))
as
declare variable WSQL varchar(32700);
declare variable WEXISTE_PROXIMO integer;
declare variable WPROXREF integer;
begin
  suspend;
end^

create or alter procedure SP_VERIFICA_USU_PLAFUC (
    PRCODEMP integer,
    PRPLANOFUC integer)
returns (
    BDEMUSO DM_BOOLEAN)
as
begin
  suspend;
end^

CREATE OR ALTER trigger vrh_imp_econsignado_bi0 for vrh_imp_econsignado
active before insert position 0
AS
begin
end
^

create or alter procedure SP_VERIFICA_USU_PLAHOR (
    PRCODEMP integer,
    PRPLANOHOR integer)
returns (
    BDEMUSO DM_BOOLEAN)
as
begin
  suspend;
end^

create or alter procedure SP_VEF_APURACAO_IRCSLL (
    PRCODEMP integer,
    PRANOAPU integer,
    PRCODQIRLP integer,
    PRRECEITAMESAPURACAO DM_NUMERIC_15_2)
returns (
    BDCODEMP integer,
    BDCODQIRLP integer,
    BDBASECALC_1_6 DM_NUMERIC_15_2,
    BDBASECALC_1_76 DM_NUMERIC_15_2,
    BDVALORIR_1_6 DM_NUMERIC_15_2,
    BDVALORIR_1_76 DM_NUMERIC_15_2,
    BDBASECALC_8 DM_NUMERIC_15_2,
    BDBASECALC_8_8 DM_NUMERIC_15_2,
    BDVALORIR_8 DM_NUMERIC_15_2,
    BDVALORIR_8_8 DM_NUMERIC_15_2,
    BDBASECALC_12 DM_NUMERIC_15_2,
    BDBASECALC_13_2 DM_NUMERIC_15_2,
    BDVALORIR_12 DM_NUMERIC_15_2,
    BDVALORIR_13_2 DM_NUMERIC_15_2,
    BDBASECALC_16 DM_NUMERIC_15_2,
    BDBASECALC_17_6 DM_NUMERIC_15_2,
    BDVALORIR_16 DM_NUMERIC_15_2,
    BDVALORIR_17_6 DM_NUMERIC_15_2,
    BDBASECALC_32 DM_NUMERIC_15_2,
    BDBASECALC_35_2 DM_NUMERIC_15_2,
    BDVALORIR_32 DM_NUMERIC_15_2,
    BDVALORIR_35_2 DM_NUMERIC_15_2,
    BDBASECALCIR DM_NUMERIC_15_2,
    BDVALORIRPJ DM_NUMERIC_15_2,
    BDVALORADICIONAL DM_NUMERIC_15_2,
    BDVALORTOTALDEDUCAO DM_NUMERIC_15_2)
as
declare variable WVALOR_TRIMESTRE numeric(15,10) = 0;
declare variable WVALOR_EXCEDENTE_TRIMESTRE numeric(15,10) = 0;
declare variable WVALOR_EXCEDENTETOTAL_TRIMESTRE numeric(15,10) = 0;
declare variable WEXCEDENTEDOTOTALANUAL numeric(15,10) = 0;
declare variable WRAZAO numeric(15,10) = 0;
declare variable WCALCRAZAO numeric(15,10) = 0;
declare variable WBASE_1_6 numeric(15,10) = 0;
declare variable WBASE_1_76 numeric(15,10) = 0;
declare variable WBASE_8 numeric(15,10) = 0;
declare variable WBASE_8_8 numeric(15,10) = 0;
declare variable WBASE_12 numeric(15,10) = 0;
declare variable WBASE_13_2 numeric(15,10) = 0;
declare variable WBASE_16 numeric(15,10) = 0;
declare variable WBASE_17_6 numeric(15,10) = 0;
declare variable WBASE_32 numeric(15,10) = 0;
declare variable WBASE_35_2 numeric(15,10) = 0;
declare variable BDVALORIRPJ_ANT numeric(15,10) = 0;
declare variable BDVALORADICIONAL_ANT numeric(15,10) = 0;
declare variable WNOVOVALORBASE numeric(15,10) = 0;
declare variable WPERCPROPORCIONALBASES numeric(15,10) = 0;
declare variable WPERCPROPORCIONALBASESEXCEDENTE numeric(15,10) = 0;
declare variable WTRIMESTRE integer = 0;
declare variable WDATAREGISTROEMP date;
declare variable WREFERENCIA integer;
declare variable WVALORREDUCAO numeric(15,10) = 0;
declare variable WMES01 integer = 0;
declare variable WMES12 integer = 0;
declare variable WDESCONTOLIMITEANUAL numeric(12,2) = 0;
BEGIN
  Suspend;
END
^

create or alter procedure SP_REL_TOT_5002_PREVIDCOMPL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRTAGSTR varchar(100),
    PRDESCRICAOFOLHA varchar(1000),
    PRUNICO integer,
    PRTIPCODREC integer,
    PRCODEMPORD integer,
    PRREFEMISSAO integer,
    PRCODREC varchar(6) = null)
as
begin
end
^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TPREVIDCOMPL5002_BU0 FOR VRHF_TEMP_EMP_TPREVIDCOMPL5002
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TPREVIDCOMPL5002_BI0 FOR VRHF_TEMP_EMP_TPREVIDCOMPL5002
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE WEXISTEREGISTRO INTEGER;
begin
end
^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TREEMBMED5002_BU0 FOR VRHF_TEMP_EMP_TREEMBMED5002
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TREEMBMED5002_BI0 FOR VRHF_TEMP_EMP_TREEMBMED5002
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

create or alter procedure SP_REL_TOT_5002_REEMBMED (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRUNICO integer,
    PRTAGSTR varchar(100),
    PRDESCRICAOFOLHA varchar(1000),
    PRCODEMPORD integer,
    PRREFEMISSAO integer)
as
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFIPENSAO_DEP_AIU0 FOR VRHF_EMP_TFIPENSAO_DEP
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
declare variable WTOTALPENSAODEP numeric(18,6);
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFIPENSAO_DEP_BIU0 FOR VRHF_EMP_TFIPENSAO_DEP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

create or alter procedure SP_REL_TOT_5002_PLANSAU (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRUNICO integer,
    PRTAGSTR varchar(100),
    PRDESCRICAOFOLHA varchar(1000),
    PRCODEMPORD integer,
    PRREFEMISSAO integer)
as
begin
end
^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TPLANSAU5002_BI0 FOR VRHF_TEMP_EMP_TPLANSAU5002
ACTIVE BEFORE INSERT POSITION 0
AS
declare variable WEXISTEREGISTRO INTEGER;
begin
end
^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TPLANSAU5002_BU0 FOR VRHF_TEMP_EMP_TPLANSAU5002
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end
^

create or alter procedure SP_REL_TOT_5002_CONSOLID (
    PRCODEMP varchar(30000),
    PRREF integer,
    PRREFFIM integer,
    PRFILTROCPF varchar(30000),
    PRAUTONOMO boolean = false,
    PRPRVEIODOTOTALIZADOR integer = 0,
    PRSEPARAFOLHAS integer = 0,
    PRRECTRAB integer = 0,
    PRGRAVACODIGORECEITA integer = 0)
returns (
    BDCODEMPORD integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCOLTER integer,
    BDREF integer,
    BDCONTRCOL integer,
    BDGRUPOCLA integer,
    BDNOMCOL varchar(70),
    BDCPFCOL varchar(18),
    BDCNPJEMP varchar(18),
    BDNOMEMP varchar(100),
    BDBASEIRRF numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDVALORINSS numeric(18,6),
    BDVRDEDDEP numeric(18,6),
    BDBASEPENSAO numeric(18,6),
    BDBASEPREV numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDVALORINSS13 numeric(18,6),
    BDVRDEDDEP13 numeric(18,6),
    BDBASEPENSAO13 numeric(18,6),
    BDBASEPREV13 numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDVALORINSSPLR numeric(18,6),
    BDVRDEDDEPPLR numeric(18,6),
    BDBASEPENSAOPLR numeric(18,6),
    BDBASEPREVPLR numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDVALORINSSRRA numeric(18,6),
    BDVRDEDDEPRRA numeric(18,6),
    BDBASEPENSAORRA numeric(18,6),
    BDBASEPREVRRA numeric(18,6),
    BDBASEIRRFES numeric(18,6),
    BDVALORIRRFES numeric(18,6),
    BDVALORINSSES numeric(18,6),
    BDVRDEDDEPES numeric(18,6),
    BDVRDEDDEPES13 numeric(18,6),
    BDBASEPENSAOES numeric(18,6),
    BDBASEPREVES numeric(18,6),
    BDBASEIRRF13ES numeric(18,6),
    BDVALORIRRF13ES numeric(18,6),
    BDVALORINSS13ES numeric(18,6),
    BDBASEPENSAO13ES numeric(18,6),
    BDBASEPREV13ES numeric(18,6),
    BDBASEIRRFPLRES numeric(18,6),
    BDVALORIRRFPLRES numeric(18,6),
    BDBASEPENSAOPLRES numeric(18,6),
    BDBASEIRRFRRAES numeric(18,6),
    BDVALORIRRFRRAES numeric(18,6),
    BDBASEPENSAORRAES numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSSES numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEINSS13ES numeric(18,6),
    BDVALORSALFAM numeric(18,6),
    BDVALORSALFAMES numeric(18,6),
    BDVALORSALMATEMP numeric(18,6),
    BDVALORSALMATEMPES numeric(18,6),
    BDVRCPSEG numeric(18,6),
    BDVALORIRRFFERIAS numeric(18,6),
    BDVALORIRRFFERIASES numeric(18,6),
    BDBASEIRRFFERIAS numeric(18,6),
    BDBASEIRRFFERIASES numeric(18,6),
    BDBASEFGTS numeric(18,6),
    BDBASEFGTSES numeric(18,6),
    BDVALORFGTS numeric(18,6),
    BDVALORFGTSES numeric(18,6),
    BDBASEFGTSRES numeric(18,6),
    BDBASEFGTSRESES numeric(18,6),
    BDVALORFGTSRES numeric(18,6),
    BDVALORFGTSRESES numeric(18,6),
    BDBASEAVPREV numeric(18,6),
    BDBASEAVPREVES numeric(18,6),
    BDVALORAVPREV numeric(18,6),
    BDVALORAVPREVES numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDBASEFGTS13ES numeric(18,6),
    BDVALORFGTS13 numeric(18,6),
    BDVALORFGTS13ES numeric(18,6),
    BDVRDEDDEPPLRES numeric(18,6),
    BDVRDEDDEPRRAES numeric(18,6),
    BDVALORINSSRRAES numeric(18,6),
    BDTIPO integer,
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDCATEGORIAESOCIAL integer,
    BDCODCLATRI integer,
    BDSEST integer,
    BDSENAT integer,
    BDSESTES integer,
    BDSENATES integer,
    BDCTS5001 integer,
    BDBASEFGTS13RESC numeric(9,2),
    BDBASEFGTS13RESCES numeric(9,2),
    BDVALORFGTS13RESC numeric(9,2),
    BDVALORFGTS13RESCES numeric(9,2),
    BDECONSIGNADO numeric(18,6),
    BDECONSIGNADORESC numeric(18,6),
    BDINSTITUICAOFINANC integer,
    BDNROCONTRATOECONSIGNADO varchar(30),
    BDINSTITUICAOFINANCES integer,
    BDNROCONTRATOECONSIGNADOES varchar(30),
    BDVALORECONSIGNADOES numeric(18,6),
    BDIND13PISES integer,
    BDTPVALORPISPASEPES integer,
    BDVALORPISPASEPES numeric(18,6),
    BDVALORPISPASEP13ES numeric(18,6),
    BDVALORPISPASEP numeric(18,6),
    BDVALORPISPASEP13 numeric(18,6),
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOCALCULO integer,
    BDAJCUSTOS numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDUNICO integer,
    BDCODREC varchar(6),
    BDTIPOFOLHA integer,
    BDCODCLA integer,
    BDTRIBUTACAOEXTERIOR integer)
as
begin
  suspend;
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TCOLCON_FGTSGPS_BIU0 FOR VRHF_EMP_TCOLCON_FGTSGPS
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TMP_VEF_EMP_TMOVEXP_TEMP_BU0 FOR TMP_VEF_EMP_TMOVEXP_TEMP
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TMP_VEF_EMP_TMOVEXPNFSAI_TEMP_AU0 FOR TMP_VEF_EMP_TMOVEXPNFSAI_TEMP
ACTIVE AFTER UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER trigger tmp_vef_emp_tmovdecrenddirf_temp_bi0 for tmp_vef_emp_tmovdecrenddirf_temp
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
end
^

CREATE OR ALTER trigger tmp_vef_emp_tmovdecrenddirf_temp_bu0 for tmp_vef_emp_tmovdecrenddirf_temp
active before update position 0
AS
begin
end
^

create or alter procedure SP_VRHF_IMPORTAFICHA5002 (
    PREMPRESAS varchar(32700),
    PRCPFS varchar(32700),
    PREMPCOMEVENTOS varchar(32700),
    PRREFINICIAL integer,
    PRREFFINAL integer,
    PRTIPORETORNO integer,
    PRPESQUISASOLETRADA integer,
    PRFILTROSOLETRADO varchar(32700))
returns (
    BDCODIGO integer,
    BDXML blob sub_type 0 segment size 80,
    BDREFARQ integer,
    BDCODEMP integer,
    BDNOMEMP varchar(200),
    BDCODCOL integer,
    BDCODTER integer,
    BDCPF varchar(14),
    BDNOME varchar(200))
as
declare variable WSQL varchar(32700);
declare variable WFILTROCPF varchar(32700);
begin
  suspend;
end^

create or alter procedure SP_VRHF_ADD_VAL_DEP_PEN_5002 (
    PRCODEMP integer,
    PRCODCOL integer,
    PRAUTONOMO integer,
    PRREF integer,
    PRDATACALC date,
    PRINTAUX integer,
    PRTIPOVAL integer,
    PRTIPOFOLHA integer,
    PRCODEMPPRINCIPAL integer,
    PRTAGSTR varchar(100),
    PRDESCRICAOFOLHA varchar(1000),
    PRINCIDESOCIAL integer,
    PRUNICO integer,
    PRTIPCODREC integer,
    PRREFFC integer,
    PRDATAPGTO date,
    PRREFPAG integer,
    PRFC integer,
    PRCODEMPORD integer,
    PRINCIDESOCIALFER integer,
    PRREFEMISSAO integer,
    PRCODREC varchar(6) = null)
as
declare variable WCPFCOL varchar(14);
declare variable WTIPO integer;
declare variable WCODVER integer;
declare variable WCODDEP integer;
declare variable WVALOR numeric(15,2);
declare variable WTABIREMP integer;
declare variable WCPFDEP varchar(20);
declare variable WNOMEDEP varchar(300);
declare variable WTIPODEP varchar(2);
declare variable WDESCDEP varchar(500);
declare variable WDATANAS date;
declare variable WEVT integer;
declare variable WEVTANT integer;
declare variable WTIPOREND integer;
declare variable WVALORFER numeric(15,2);
declare variable WTIPOREGISTRO integer;
declare variable WSQL varchar(1000);
declare variable WDEPIRRF varchar(1);
declare variable WREFIR integer;
declare variable WPODEGRAVAR integer;
declare variable WPARENESCODPN integer;
begin
  
end^


CREATE OR ALTER trigger vrhf_temp_emp_tval5002_bi0 for vrhf_temp_emp_tval5002
active before insert position 0
AS
begin
  /* Trigger text */
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TTRANSCOL_BI0 FOR VRH_EMP_TTRANSCOL
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^
CREATE OR ALTER TRIGGER VRH_BASE_TCONVSAUDE_BIU0 FOR VRH_BASE_TCONVSAUDE
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  /* Trigger text */
end
^

CREATE OR ALTER trigger vrhf_temp_emp_tval5002_bu0 for vrhf_temp_emp_tval5002
active before update position 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFICHAIRRF_AI0 FOR VRHF_EMP_TFICHAIRRF
ACTIVE AFTER INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_CALCDIA_BIU0 FOR VRH_EMP_TCOLCON_CALCDIA
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFIPENSAO_DEP_AIU0 FOR VRHF_EMP_TFIPENSAO_DEP
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFIPENSAO_DEP_BIU0 FOR VRHF_EMP_TFIPENSAO_DEP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_CONV_BI0 FOR VRH_EMP_TRECLAMATORIA_CONV
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE WCHAVE INTEGER;
BEGIN
END^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TGIAMGGER_070OCOMG_AD0 FOR TOL_VEF_EMP_TGIAMGGER_070OCOMG
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

create or alter procedure SP_VRH_SIT_MES_INT (
    PRCODEMP integer,
    PRCOMPETENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer)
as
begin
  suspend;
end^


create or alter procedure SP_ATUALIZAR_TMP_BLOCO1100 (
    PRSESSAO integer,
    PRULTCHAVE integer,
    PRIDTERMINAL integer)
as
declare variable WSESSAOPRO integer;
begin
end^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_RENDDIRF (
    PRSESSAO integer,
    PRULTCHAVE integer,
    PRIDTERMINAL integer)
as
declare variable WSESSAOPRO integer;
begin
end^

CREATE OR ALTER TRIGGER VRH_EMP_TTRANSCOL_BU0 FOR VRH_EMP_TTRANSCOL
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END^


CREATE OR ALTER TRIGGER TUSUARIO_AU0 FOR TUSUARIO
ACTIVE AFTER UPDATE POSITION 0
AS
begin
end
^

create or alter procedure SP_VRH_SIT_MES_INT (
    PRCODEMP integer,
    PRCOMPETENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer)
as
begin
  suspend;
end^

create or alter procedure SP_RECLAMATORIA_CONV (
    PRCODEMP integer,
    PRCHAVE integer)
returns (
    BDCODEMP integer,
    BDCHAVE integer,
    BDCODVINC integer,
    BDDATASERV date,
    BDHORASTRAB time,
    BDCONSIDERAHORAS DM_BOOLEAN)
as
declare variable WREFATU integer;
declare variable WREFFIM integer;
begin
    suspend;
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_CONSOLIDAPURMEN_C_BI0 FOR VRH_ESOCIAL_CONSOLIDAPURMEN_C
ACTIVE BEFORE INSERT POSITION 0
as
begin
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_CONSOLIDAPURMEN_C_TERC_BI0 FOR VRH_ESOCIAL_CONSOLIDAPURMEN_C_TERC
ACTIVE BEFORE INSERT POSITION 0
as
begin
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_CONSOLIDAPURMEN_C_TERC_BU0 FOR VRH_ESOCIAL_CONSOLIDAPURMEN_C_TERC
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_CONSOLIDAPURMEN_C_BU0 FOR VRH_ESOCIAL_CONSOLIDAPURMEN_C
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_INFOIRRF_DEP_BI0 FOR VRH_ESOCIAL_INFOIRRF_DEP
ACTIVE BEFORE INSERT POSITION 0
as
begin
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_INFOIRRF_DEP_TERC_BI0 FOR VRH_ESOCIAL_INFOIRRF_DEP_TERC
ACTIVE BEFORE INSERT POSITION 0
as
begin
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_INFOIRRF_PLANSAU_BI0 FOR VRH_ESOCIAL_INFOIRRF_PLANSAU
ACTIVE BEFORE INSERT POSITION 0
as
begin
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_INFOIRRF_PREVIDCOMPL_BI0 FOR VRH_ESOCIAL_INFOIRRF_PREVIDCOMPL
ACTIVE BEFORE INSERT POSITION 0
as
begin
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_INFOIRRF_REEMBMED_BI0 FOR VRH_ESOCIAL_INFOIRRF_REEMBMED
ACTIVE BEFORE INSERT POSITION 0
as
begin
end^

create or alter procedure VRH_SP_GET_DATA_ULTIMA_ALTERACAO_CARGO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRDATAMIN date,
    PRDATAMAX date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATAULTMOV date)
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER TRIGGER VRH_EMP_TTRANSCOL_BI0 FOR VRH_EMP_TTRANSCOL
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRH_EMP_TTRANSCOL_BU0 FOR VRH_EMP_TTRANSCOL
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END^

CREATE or alter trigger vrhf_emp_tconfverbas_reembolso_bi0 for vrhf_emp_tconfverbas_reembolso
active before insert position 0
AS
begin
end^

CREATE OR ALTER trigger planos_tpla_ecf_lalur_padrao_bi0 for planos_tpla_ecf_lalur_padrao
active before insert position 0
AS             
begin
end^

CREATE OR ALTER TRIGGER TPROCESSOSAUTOMATIZADOS_BI0 FOR TPROCESSOSAUTOMATIZADOS
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TTIPOPROCESSOSAUTOMATIZADOS_BI0 FOR TTIPOPROCESSOSAUTOMATIZADOS
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VSH_BASE_EMP_TEXECMANUAL_BI0 FOR VSH_BASE_EMP_TEXECMANUAL
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_CAMPO_TTABELA_BI0 FOR VRH_BASE_CAMPO_TTABELA
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

create or alter procedure VRH_SP_CONF_VER_REEMBOLSO
returns (
    BDCODEMP integer,
    BDOBS varchar(200),
    BDNOMEMP DM_BDNOMEMP,
    bdverbareembolsotitular integer,
    bdverbareembolsotitularrra integer,
    bdverbareembolsodependente integer,
    bdverbareembolsodependenterra integer,
    bddescverbatitular  varchar(200),
    bddescverbadep  varchar(200),
    bddescverbatitularrra  varchar(200),
    bddescverbadeprra  varchar(200)
                         )
as
begin
 suspend;
end^

create or alter procedure SP_VRH_GET_SOMA_GPS_IND (
    PRCODEMP integer,
    PRCHAVE integer)
returns (
    BDCHAVE integer,
    BDCODEMP integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDLIQUIDO numeric(15,2))
as
BEGIN
 suspend;
END^

create or alter procedure SP_VRHF_RETORNAHORAPLANQH
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATABATIDA date,
    BDQHHSSAI time,
    BDQHHSENT time,
    BDDIASEMQH integer,
    BDDATAQH date,
    BDCODPQUA integer,
    BDCODQH integer)
as
declare variable WSQL varchar(3000);
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETHORACOL_IMPBATIDA (
    PRCODEMP integer,
    PRCODCOL integer,
    PRDATA date)
returns (
    BDDIASEMQH integer,
    BDCODQHH integer,
    BDCODQHHS integer,
    BDQHHSENT time,
    BDQHHSSAI time,
    BDDATACOL date)
as
declare variable WDATACOL date;
declare variable WCODQH integer;
declare variable WCODPQUA integer;
begin
  suspend;
end^

create or alter procedure SP_GET_DESC_CAMPOS_DOWNLOAD (
    PRCODTABELA integer = 0)
returns (
    BDCODTABELA integer,
    BDTABELA varchar(100),
    BDCAMPO varchar(100),
    BDDESC varchar(1000))
as
BEGIN
 suspend;
END^

create or alter procedure SP_TEMPPARFED (
    PRCODEMP integer,
    PRREFEMP integer)
returns (
    BDCODEMP integer,
    BDREFEMP integer,
    BDCODCONFICMSSPED integer)
as
begin
    suspend;
end^

CREATE OR ALTER procedure SP_NOVA_AUTOMATIZACAO (
    PRSEQUENCIA integer)
as
begin
end^

CREATE OR ALTER TRIGGER VRH_RHNET_TSINDTRAB_BIU0 FOR VRH_RHNET_TSINDTRAB
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_RHNET_TBANCOS_AG_BIU0 FOR VRH_RHNET_TBANCOS_AG
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VSUC_TERCEIRO_INCON_MIGRACAO_BI0 FOR VSUC_TERCEIRO_INCON_MIGRACAO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TOL_VSUC_TDIST_LUCRO_TSOCCOTAS_PGTO_AD0 FOR TOL_VSUC_TDIST_LUCRO_TSOCCOTAS_PGTO
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VSUC_MIGRACAO_INCONSISTENCIAS_BI0 FOR VSUC_MIGRACAO_INCONSISTENCIAS
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VSH_TARQUIVO_SEQREL_BI0 FOR VSH_TARQUIVO_SEQREL
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^
CREATE OR ALTER trigger tusuario_ai0 for tusuario
active after insert position 0
AS
begin
end
^
create or alter procedure SP_VRH_EMPS_SIND_RHNET (
    PRCODSINTRAB integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDRHNET boolean,
    BDVINCCOL boolean)
as
begin
  suspend;
end^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_VINC_AI0 FOR VRH_EMP_TCOL_VINC
ACTIVE AFTER INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_VINC_AU0 FOR VRH_EMP_TCOL_VINC
ACTIVE AFTER UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TSINDTRAB_AD0 FOR VRH_BASE_TSINDTRAB
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER trigger tmp_vef_emp_tmovproent_temp_au0 for tmp_vef_emp_tmovproent_temp
inactive after update position 0
AS
begin
end
^

CREATE OR ALTER trigger tmp_vef_emp_tmovprosai_temp_au0 for tmp_vef_emp_tmovprosai_temp
inactive after update position 0
as
begin
end
^

create or alter procedure SP_EXPORTA_LOG_E113 (
    PRCODEMP integer,
    PRLOCAL varchar(255),
    PRREFERENCIA char(9))
returns (
    BDFILE varchar(255))
as
declare variable WCODIGO integer;
declare variable WORDEME111_ORI integer;
declare variable WORDEME113_ORI integer;
declare variable WORDEME111_GER integer;
declare variable WORDEME113_GER integer;
declare variable WDATAHORA timestamp;
declare variable WLINHA varchar(255);
begin
  SUSPEND;
end
^

CREATE OR ALTER procedure SP_E111_E113_AUTO_SPED (
    PRCODEMP integer,
    PRCODIGO integer,
    PRCODPERIODO integer,
    PRREFERENCIA integer,
    PRTOL boolean,
    prsemanal boolean,
    prdataaju varchar(10))
as
declare variable WSQL varchar(30000); /* Select da SP */
declare variable WSUM varchar(500); /* Concatena os  campos que serão somados */
declare variable WDEC varchar(500); /* Concatena os  campos que serão subtraidos */
declare variable WDATA varchar(25); /* Campo da data do tipo do lançamento */
declare variable WNEWORDEME111 integer; /* Ordem gerada para o E111 */
declare variable WLASTORDEME111 integer; /* Útima ordem do E111 na tabela física */
declare variable WLASTORDEME113 integer; /* Última ordem do E113 na tabela temporária */
declare variable WVALOR varchar(30); /* Tipo do cálculo do valor da combobox */
declare variable WCODAJUICMS integer; /* Código de ajuste do E111 */
declare variable WINSERTPROD char(10); /* Campo auxiliar do produto no insert */
declare variable WSELECTPROD char(12); /* Campo auxiliar do produto no select */
declare variable WSELECTVALOR varchar(30);
declare variable WCODEMP integer;
declare variable WCODIGO integer;
declare variable WORDEMCONFE111 integer;
declare variable WORDEMCONFE113 integer;
declare variable WTIPOMOVIMENTO char(3);
declare variable WTIPOPARTICIPANTE integer;
declare variable WMODELO integer;
declare variable WALIQICMS DM_NUMERIC_7_4_ALIQ;
declare variable WCODSITNF integer;
declare variable WAPLICAR DM_BOOLEAN; /* Aplica os filtros do E113 por produto */
declare variable WTIPOVALOR integer;
declare variable WPERCENTUAL DM_NUMERIC_7_4_ALIQ;
declare variable WTEMFILIAL DM_BOOLEAN;
declare variable WTEMCFOP DM_BOOLEAN;
declare variable WTEMCST DM_BOOLEAN;
declare variable WTEMPROD DM_BOOLEAN;
declare variable WTEMNCM DM_BOOLEAN;
declare variable WSUMVLRPROD DM_BOOLEAN;
declare variable WSUMSEGURO DM_BOOLEAN;
declare variable WSUMDESCONTO DM_BOOLEAN;
declare variable WSUMABAT DM_BOOLEAN;
declare variable WSUMDESPACESS DM_BOOLEAN;
declare variable WSUMVLRIPI DM_BOOLEAN;
declare variable WSUMBCICMS DM_BOOLEAN;
declare variable WSUMVLRSTRET DM_BOOLEAN;
declare variable WSUMVLRICMS DM_BOOLEAN;
declare variable WSUMFRETE DM_BOOLEAN;
declare variable WSUMVLRICMSST DM_BOOLEAN;
declare variable WSUMQTD DM_BOOLEAN;
declare variable WSUMVLRMONODIF DM_BOOLEAN;
declare variable WSUMVLRMONORETANT DM_BOOLEAN;
declare variable WDECVLRPROD DM_BOOLEAN;
declare variable WDECSEGURO DM_BOOLEAN;
declare variable WDECDESCONTO DM_BOOLEAN;
declare variable WDECABAT DM_BOOLEAN;
declare variable WDECDESPACESS DM_BOOLEAN;
declare variable WDECVLRIPI DM_BOOLEAN;
declare variable WDECBCICMS DM_BOOLEAN;
declare variable WDECVLRSTRET DM_BOOLEAN;
declare variable WDECVLRICMS DM_BOOLEAN;
declare variable WDECFRETE DM_BOOLEAN;
declare variable WDECVLRICMSST DM_BOOLEAN;
declare variable WDECQTD DM_BOOLEAN;
declare variable WDECVLRMONODIF DM_BOOLEAN;
declare variable WDECVLRMONORETANT DM_BOOLEAN;
declare variable WSUMANTICMS boolean;
declare variable WSUMDIFALIQ boolean;
declare variable WDECANTICMS boolean;
declare variable WDECDIFALIQ boolean;
DECLARE VARIABLE wDATAJU VARCHAR(20);
begin
end
^

create or alter procedure SP_DADOS_MENSAIS_HISTORICO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDGERARNMSOCIAL varchar(5),
    BDNMSOCIAL varchar(70),
    BDATUAL boolean)
as
declare variable WSQL varchar(1000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  suspend;
end^

create or alter procedure SP_DADOS_MENSAIS_CALCULO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDFORMAPAGTOCOL integer,
    BDTIPOCOL integer,
    BDHORASMENSAISCOL numeric(15,6),
    BDHORASSEMANAISCOL numeric(15,6),
    BDHORASDIARIASCOL numeric(15,6),
    BDBASEIRRFADCOL numeric(15,6),
    BDPERCADISAL numeric(15,6),
    BDCALCVALREFCOL varchar(5),
    BDCALCVALTRANSCOL varchar(5),
    BDIMPETIQUETACOL varchar(5),
    BDPERCINSALUBCOL numeric(15,6),
    BDINCIDINSALUBCOL integer,
    BDPERCPERCULCOL numeric(15,6),
    BDINCIDPERICULCOL integer,
    BDPERCNOTURNOCOL numeric(15,6),
    BDINCIDNOTURNOCOL integer,
    BDNRODEPSALFAMCOL integer,
    BDNRODEPIRCOL integer,
    BDVALORPREVPRIVNCOL numeric(15,6),
    BDVALORPREVPRIV13COL numeric(15,6),
    BDREGIMEPARCIALCOL DM_BOOLEAN,
    BDPERCGORJ numeric(15,6),
    BDCARTAOVA varchar(20),
    BDCARTAOVR varchar(20),
    BDCARTAOVT varchar(20),
    BDCONTSINDICAL DM_BOOLEAN,
    BDUTILIZADESCSIMPLIFICADO DM_BOOLEAN,
    BDATUAL boolean,
    BDAULISTA boolean)
as
declare variable WSQL varchar(5000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  suspend;
end^

create or alter procedure SP_DADOS_MENSAIS_BANCO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDCODBAN integer,
    BDNOMBAN varchar(60),
    BDCODAG integer,
    BDNOMAG varchar(40),
    BDCTADEPCOL varchar(15),
    BDDIGCTADEPCOL varchar(2),
    BDTIPOCTACOL integer,
    BDMODOPAGTOCOL integer,
    BDCARTAOSALCOL varchar(7),
    BDCONTRCOL integer,
    BDMODOPAGTOCOLPIXTPCH integer,
    BDMODOPAGTOCOLPIXCH varchar(200),
    BDATUAL boolean)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  suspend;
end^

create or alter procedure SP_DADOS_MENSAIS_ADMISSIONAIS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDVINCEMPCOL integer,
    BDSINDICALIZADOCOL varchar(5),
    BDALVARACOL DM_BOOLEAN,
    BDCODPROCESSO integer,
    BDNROPROCESSO varchar(21),
    BDATUAL boolean)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  suspend;
end^

create or alter procedure SP_DADOS_MENSAIS_DIRIGENTE (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDPLANOSEGREGACAO integer,
    BDTETORGPS integer,
    BDABONOPERMANENCIA integer,
    BDINICIOABONO date,
    BDATUAL boolean)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  suspend;
end^

create or alter procedure SP_DADOS_MENSAIS_FGTS_GPS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDCATEGORIACOL integer,
    BDDESCCATEGORIA varchar(300),
    BDOCORRENCIACOL integer,
    BDDATAOPCAOFGTSCOL date,
    BDCTAFGTSCOL varchar(11),
    BDPERCFGTSCOL numeric(15,6),
    BDPERCRATCOL numeric(15,6),
    BDPERCDESCFPASCOL numeric(15,6),
    BDCATEGORIAESOCIAL integer,
    BDDESCCATESOCIAL varchar(300),
    BDREGPREV integer,
    BDCODMULTVINC integer,
    BDDESCMULTVINC varchar(300),
    BDDESCOCORRENCIA varchar(80),
    BDATUAL boolean,
    BDREGIMETRAB integer)
as
begin
  suspend;
end^

create or alter procedure SP_DADOS_MENSAIS_VINCULOS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDCODCLA integer,
    BDDESCCLA varchar(40),
    BDCODTPCC integer,
    BDNOMSETOR varchar(100),
    BDCODSINTRAB integer,
    BDDESCSINTRAB varchar(60),
    BDCODSINTRABCLA integer,
    BDDESCSINTRABCLA varchar(60),
    BDATUAL boolean)
as
begin
  suspend;
end^

create or alter procedure SP_DADOS_MENSAIS_PARENTES (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDESTCIVCOL integer,
    BDATUAL boolean)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  suspend;
end^

create or alter procedure SP_DADOS_MENSAIS_FISICOS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDSEXOCOL integer,
    BDCORCOL integer,
    BDDEFCOL DM_BOOLEAN,
    BDDEFFIS DM_BOOLEAN,
    BDDEFVIS DM_BOOLEAN,
    BDDEFAUD DM_BOOLEAN,
    BDDEFMEN DM_BOOLEAN,
    BDDEFINT DM_BOOLEAN,
    BDREAB DM_BOOLEAN,
    BDCOTADEF integer,
    BDOBSDEFFISCOL varchar(300),
    BDATUAL boolean)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  suspend;
end^

create or alter procedure SP_DADOS_MENSAIS_DOC_AUXILIAR (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDNUMRICCOL varchar(14),
    BDORGAORICCOL DM_ORGAOEMISSOR,
    BDDATAEMIRICCOL date,
    BDCODCIDRIC integer,
    BDNOMCID varchar(40),
    BDNUMOCCOL varchar(14),
    BDORGAOOCCOL DM_ORGAOEMISSOR,
    BDDATAEMIOCCOL date,
    BDDATAVALOCCOL date,
    BDATUAL boolean)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  suspend;
end^

create or alter procedure SP_DADOS_MENSAIS_DOC_PRINCIPAL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDPISCOL varchar(14),
    BDDATAEMIPISCOL date,
    BDRGCOL varchar(13),
    BDORGEMIRGCOL DM_ORGAOEMISSOR,
    BDDATAEMIRGCOL date,
    BDUFRG varchar(2),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDDATAEMICTPSCOL date,
    BDUFCTPS varchar(2),
    BDCNHCOL varchar(11),
    BDVENCCNHCOL date,
    BDCATCNHCOL varchar(2),
    BDDATAEMICNH date,
    BDUFCNH varchar(2),
    BDATUAL boolean)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  suspend;
end^

create or alter procedure SP_DADOS_MENSAIS_ADM_HIST (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDGRAUINSTCOL integer,
    BDATUAL boolean)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
declare variable WWHERE varchar(500);
begin
  suspend;
end^

create or alter procedure SP_DADOS_MENSAIS_CADASTRAIS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCODPAISRES integer,
    BDDESCPAIS varchar(60),
    BDCEPCOL varchar(9),
    BDLOGRCOL DM_LOGRADOURO,
    BDENDCOL DM_BDENDERECO,
    BDNUMCOL DM_NUMEND,
    BDCOMPLCOL DM_BDCOMPENDERECO,
    BDBAICOL DM_BDBAIRRO,
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDDDDCOL integer,
    BDFONECOL varchar(15),
    BDDDDCELCOL integer,
    BDCELCOL DM_BDTELEFONE,
    BDEMAILCOL DM_BDEMAIL,
    BDGERARNMSOCIAL varchar(5),
    BDNMSOCIAL varchar(70),
    BDATUAL boolean)
as
declare variable WSQL varchar(10000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
declare variable WWHERE varchar(500);
begin
  suspend;
end^

create or alter procedure SP_DADOS_MENSAIS_ESTRANGEIRO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDDATACHEBRASILCOL date,
    BDDESCCLE varchar(300),
    BDCASADOBR DM_BOOLEAN,
    BDFILHOSBR DM_BOOLEAN,
    BDTEMPORESIDENCIA integer,
    BDCONDICAOINGRESSO integer,
    BDNUMRNECOL varchar(14),
    BDORGAORNECOL DM_ORGAOEMISSOR,
    BDDATAEMIRNECOL date,
    BDATUAL boolean)
as
declare variable WSQL varchar(10000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
declare variable WWHERE varchar(500);
begin
  suspend;
end^

create or alter procedure SP_CONSULTA_DADOS_DIARIOS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATACOL date,
    BDCODMAS integer,
    BDSALBASECOL numeric(18,6),
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDCODQH integer,
    BDREGJORTRAB integer,
    BDDESCMAS varchar(50),
    BDDESCTFUC varchar(40),
    BDDESCQH DM_BDDESCQH,
    BDDESCSALVAR varchar(255),
    BDTIPOJORNADA integer,
    BDDESCTPJORNADA varchar(100),
    BDINDHORARIONOT integer,
    BDACUMCARGO integer,
    BDCODTIPOCONTRATO varchar(300),
    BDDATAFIMPRAZO1COL date,
    BDDATAFIMPRAZO2COL date,
    BDDATAFIMPRAZO date,
    BDCODCARGOCOMIS integer,
    BDDESCTFUCCOMIS varchar(40),
    BDTIPOESCALA varchar(20),
    BDCODREVEZAMENTO integer,
    BDDESCRICAO varchar(100),
    BDDATAINICIALESCALA date,
    BDATUAL boolean,
    BDDTAINICIALFOLGA date)
as
declare variable WSQL varchar(30000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  suspend;
end^

CREATE OR ALTER procedure SP_PROCESSO_AUMENTO_SAL (
    PRCODEMP varchar(30000) not null,
    PRCODCOL varchar(30000) not null,
    PRREFEF integer,
    PRULTDIA varchar(12),
    PRDATAEFEITO varchar(12),
    PRCODSIND varchar(2000),
    PRCODCLA varchar(2000),
    PRCODFUC varchar(2000))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDSALBASECOL numeric(18,6),
    BDCALCFCNAFNEMP varchar(5),
    BDCODSINTRAB integer,
    BDCODCLA integer,
    BDCODTFUC integer,
    BDDATAADMCOL date)
as
begin
  suspend;
end^

create or alter trigger TTELA_SELECOPROCESSOSBASE_BI0 for TTELA_SELECOEPROCESSOSBASE
active before insert position 0
as
begin
end^

create or alter trigger TTELA_SELPROCESSOSBASE_BI0 for TTELA_SELPROCESSOSBASE
active before insert position 0
as
begin
end^


CREATE OR ALTER TRIGGER TR_VEF_EMP_TLANDESIFSER_DEL FOR VEF_EMP_TLANDESIFSER
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END^


CREATE OR ALTER TRIGGER VCT_BASE_PROCESSOS_BI0 FOR VCT_BASE_PROCESSOS
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VCT_ARQUIVOS_TAREFAS_BI0 FOR VCT_ARQUIVOS_TAREFAS ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END^
CREATE OR ALTER TRIGGER VCT_ARQUIVOS_TAREFAS_BU0 FOR VCT_ARQUIVOS_TAREFAS ACTIVE BEFORE UPDATE POSITION 0 AS begin end^

create or alter trigger VCT_BASE_PROCESSOS_AI0 for VCT_BASE_PROCESSOS
active after insert or update position 0
as
begin
end^

CREATE OR ALTER TRIGGER VCT_BASE_PROCESSOTAREFAS_BI0 FOR VCT_BASE_PROCESSOTAREFAS
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER TGRUPOUSUARIO_USUARIO_AD0 FOR TGRUPOUSUARIO_USUARIO
ACTIVE AFTER DELETE POSITION 1
AS
begin
end
^

CREATE OR ALTER TRIGGER TGRUPOUSUARIO_USUARIO_AI0 FOR TGRUPOUSUARIO_USUARIO
ACTIVE AFTER INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VCT_DEPARTAMENTO_BI0 FOR VCT_DEPARTAMENTO
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE vBDCODDEP INTEGER;
begin
end
^

CREATE OR ALTER TRIGGER VCT_DEPARTAMENTO_GRUPOS_AD0 FOR VCT_DEPARTAMENTO_GRUPOS
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VCT_DEPARTAMENTO_GRUPOS_AI0 FOR VCT_DEPARTAMENTO_GRUPOS
ACTIVE AFTER INSERT POSITION 0
AS
begin
end
^


create or alter procedure SP_SIT_DEC_RHNET (
    PREMP integer,
    PRCOL integer,
    PRDATAINISEFIP date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATAINISEFIP date,
    BDCODSITDEC integer,
    BDDESCSITDEC varchar(70),
    BDQTDDIASATESTADO integer,
    BDDATAINIATES date,
    BDDATAFIMATES date,
    BDIDRHNETDEC integer)
as
begin
  suspend;
end^
CREATE OR ALTER TRIGGER TAUTOMATIZACOES_BI FOR TAUTOMATIZACOES
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

create or alter procedure SP_VRHF_EXISTE_COMPLEMENTAR (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFCOMP integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOMP integer)
as
begin
suspend;
end^


create or alter procedure SP_VRHF_PROCESSO_AUMENTO (
    PREMP varchar(30000),
    PRCOL varchar(30000),
    PRDATAHAUM date,
    PRDATAEFEITO date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATAHAUM date,
    BDDATAEFEITOHAUM date,
    BDSALBASEAUMSAUM numeric(18,6),
    BDCODMAS integer,
    BDDESCMAS varchar(50),
    BDSALBASEDESCAUM numeric(18,6))
as
begin
  SUSPEND;
END^

create or alter procedure SP_RETORNA_BASE_ESOCIAL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PR13 integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBFGTSES numeric(18,6),
    BDBFGTS13ES numeric(18,6),
    BDBFGTSRESES numeric(18,6),
    BDBAVPREVES numeric(18,6),
    BDFGTSES numeric(18,6),
    BDFGTS13ES numeric(18,6),
    BDFGTSRESES numeric(18,6),
    BDAVPREVES numeric(18,6),
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDBASEFGTS13RESCES numeric(18,6),
    BDVALORFGTS13RESCES numeric(18,6),
    BDINSTITUICAOFINANCES integer,
    BDNROCONTRATOECONSIGNADOES varchar(30),
    BDVALORECONSIGNADOES numeric(15,6))
as
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WBFGTSES numeric(18,6);
declare variable WBFGTS13ES numeric(18,6);
declare variable WBFGTSRESES numeric(18,6);
declare variable WBAVPREVES numeric(18,6);
declare variable WFGTSES numeric(18,6);
declare variable WFGTS13ES numeric(18,6);
declare variable WFGTSRESES numeric(18,6);
declare variable WAVPREVES numeric(18,6);
declare variable WCODTIPO integer;
declare variable WTIPOVALOR integer;
declare variable WVALOR numeric(18,6);
declare variable WVALORDEP numeric(18,6);
declare variable WMOTIVODESLIG integer;
declare variable WSQL varchar(500);
declare variable WEXPORTAGRRF integer;
declare variable WREFFGTSDIGITAL integer;
declare variable WDATAFGTSDIGITAL date;
begin
  suspend;
end^

CREATE OR ALTER procedure DIGITOCPF (
    STR varchar(30))
returns (
    CPF varchar(14))
as
declare variable WSTR varchar(11);
declare variable I integer;
declare variable WCOUNT integer;
declare variable J integer;
declare variable X integer;
declare variable Y integer;
declare variable D1 integer;
declare variable D2 integer;
declare variable FATOR integer;
declare variable CALCULADO char(2);
declare variable DIGITADO char(2);
begin 
 --Preparação para cálculo do D1 
 wcount  = 1;
 wStr = '';
 while (wcount <= CHARACTER_LENGTH(str)) do
 begin
   if (Position(substring(str from wcount for 1), '0123456789') > 0) then
   begin
     wStr = wStr || substring(str from wcount for 1);
   end

   wcount = wcount + 1;
 end

 STR = wStr;
 if (character_length(STR) = 9) then
   str = str || '00';

 if (character_length(STR) <> 11) then
 begin
   CPF = '';
 end
 else
 begin
   STR = '000' || substring(STR from 4 for 8);

   I=character_length(STR); --tamanho da string
   X=I-2;
   J=1; FATOR=2; D1=0;
   while (J<=I-2)do
   begin
    D1=D1+cast(substring(STR from X for 1)as integer)*FATOR;
    J=J+1; X=X-1; FATOR=FATOR+1;
   end
   D1=11-(mod(D1,11));
   if (D1>=10) then D1=0;
   --Preparação para cálculo do D2
   J=3; D2=0; Y=I-2;
   while (J<=I)do
   begin
    D2=D2+cast(substring(STR from Y for 1)as integer)*J;
    J=J+1; Y=Y-1;
   end
   D2=D2+D1*2;
   D2=11-(mod(D2,11));
   if (D2>=10) then D2=0;
   --Preparação para validação do CPF
   CALCULADO=cast(D1 as char)||cast(D2 as char); --concatenar os D1 e D2
   DIGITADO=substring(STR from 10 for 1)||substring(STR from 11 for 1); --concatenar o dig. do CPF
   CPF=substring(STR from 1 for 3) || '.' || substring(STR from 4 for 3) || '.' || substring(STR from 7 for 3) || '-' || CALCULADO;
 end
 suspend;
end^

create or alter procedure SP_REL_PROVISAO13 (
    PRTABELAPRINCIPAL varchar(50),
    PRSEMAD13 integer,
    PRSITCOL integer,
    PRREF integer,
    PRDATAINI date,
    PRDATAFIM date,
    PREMP varchar(30000),
    PRCOL varchar(30000),
    PRCC varchar(10000) = null,
    PRCLASSE varchar(1000) = null,
    PRSINDICATO varchar(10000) = null,
    PRFUNCAO varchar(10000) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDLINHAP13 integer,
    BDREFP13 integer,
    BDORDEMCCP13 integer,
    BDPLANOCC integer,
    BDCODCENTRO integer,
    BDSALBASEP13 numeric(18,6),
    BDADICIONAISP13 numeric(18,6),
    BDMEDIASP13 numeric(18,6),
    BDOUTRASBASESP13 numeric(18,6),
    BDCODTPCC integer,
    BDVLR13SALP13 numeric(18,6),
    BDFGTSP13 numeric(18,6),
    BDINSSP13 numeric(18,6),
    BDTERCFPASP13 numeric(18,6),
    BDCNAERATP13 numeric(18,6),
    BDRATAPOP13 numeric(18,6),
    BDPISP13 numeric(18,6),
    BDBASEFGTSP13 numeric(18,6),
    BDBASEINSSP13 numeric(18,6),
    BDRESCISAOP13 varchar(5),
    BDBASEPISP13 numeric(18,6),
    BDPROPP13 integer,
    BDOBSERVACAO varchar(3000),
    BDTOTP13 numeric(18,6),
    BDPORTOMADORP13 varchar(5),
    BDORDEM varchar(5),
    BDNOMEMP DM_BDNOMEMP,
    BDTIPOEMIGUIAS integer,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDNOMCOL DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDDATARESCISAO date,
    BDCODCLA integer,
    BDCODSINTRAB integer,
    BDCODTFUC integer,
    BDNOMETOM varchar(70),
    BDCTALON varchar(20),
    BDNOMCTA varchar(40),
    BDCENTROTPCC varchar(10))
as
begin
  suspend;
end^

create or alter procedure SP_GET_CODEMP_DOWNLOAD
returns (
    BDCODEMP integer)
as
BEGIN
  suspend;
END^

create or alter procedure SP_VRHF_GETHORACOL_IMPBATIDA (
    PRCODEMP integer,
    PRCODCOL integer,
    PRDATA date)
returns (
    BDDIASEMQH integer,
    BDCODQHH integer,
    BDCODQHHS integer,
    BDQHHSENT time,
    BDQHHSSAI time,
    BDDATACOL date)
as
declare variable WDATACOL date;
declare variable WCODQH integer;
declare variable WCODPQUA integer;
begin
  for select BDDATACOL, BDCODPQUA, BDCODQH
      from VRH_EMP_TCOL_VINCDIA
      where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDDATACOL <= :prdata
      order by BDDATACOL DESC
  into :bddatacol, :wcodpqua, :wcodqh
  do
    begin
      for select TQH.BDDIASEMQH, TQH.BDCODQHH, HORAS.BDCODQHHS, HORAS.BDQHHSENT,
                 HORAS.BDQHHSSAI
          from VRH_BASE_TQH_DIAS TQH
          left outer join VRH_BASE_TQH_HORARIO HORARIO on (HORARIO.BDCODQHH = TQH.BDCODQHH)
          left outer join VRH_BASE_TQH_HORAS HORAS on (HORAS.BDCODQHH = TQH.BDCODQHH)
          where TQH.BDCODPQUA = :wcodpqua and TQH.BDCODQH = :wcodqh AND (HORAS.BDCODQHHS IS NOT NULL OR HORAS.BDQHHSENT IS NOT NULL)
      into :BDDIASEMQH, :BDCODQHH, :BDCODQHHS, :BDQHHSENT, :BDQHHSSAI
      do
        suspend;
    end
end^

create or alter procedure SP_VRHF_RETORNAHORAPLANQH
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATABATIDA date,
    BDQHHSSAI time,
    BDQHHSENT time,
    BDDIASEMQH integer,
    BDDATAQH date,
    BDCODPQUA integer,
    BDCODQH integer,
    BDQTDCOLUNASQH integer)
as
declare variable WSQL varchar(3000);
begin
      WSQL = ' select EMP.BDCODEMP, TAB.BDCODCOL, TAB.BDDATABATIDA, TAB.BDDATAQH, TAB.BDDIASEMQH, ' ||
                '    (select first 1 SPQH.BDQHHSSAI ' ||
                '    from SP_VRHF_GETHORACOL_IMPBATIDA(TAB.BDCODEMP, TAB.BDCODCOL, TAB.BDDATAQH) SPQH ' ||
                '    where SPQH.BDDIASEMQH = TAB.BDDIASEMQH and ' ||
                '      SPQH.BDDATACOL = TAB.BDDATAQH ' ||
                '      ORDER BY SPQH.BDCODQHHS) as BDQHHSSAI, ' ||
                '    (select first 1 SPQH2.BDQHHSENT ' ||
                '    from SP_VRHF_GETHORACOL_IMPBATIDA(TAB.BDCODEMP, TAB.BDCODCOL, TAB.BDDATAQH) SPQH2 ' ||
                '    where SPQH2.BDDIASEMQH = TAB.BDDIASEMQH and ' ||
                '      SPQH2.BDDATACOL = TAB.BDDATAQH ' ||
                '      ORDER BY SPQH2.BDCODQHHS DESC) as BDQHHSENT, ' ||
                '    (select first 1 COUNT(SPQH.BDCODQHHS) ' ||
                '    from SP_VRHF_GETHORACOL_IMPBATIDA(TAB.BDCODEMP, TAB.BDCODCOL, TAB.BDDATAQH) SPQH ' ||
                '    where SPQH.BDDIASEMQH = TAB.BDDIASEMQH and ' ||
                '      SPQH.BDDATACOL = TAB.BDDATAQH ' ||
                '      GROUP BY SPQH.BDDIASEMQH, SPQH.BDDATACOL) as BDQTDCOLUNASQH, VINCDIA.BDCODPQUA, VINCDIA.BDCODQH ' ||
             ' from TMP_TEMPRESAS EMP ' ||
             ' inner join(select TMP.BDCODEMP, TMP.BDCODCOL, TMP.BDDATABATIDA, ' ||
                            ' (select first 1 X.BDDATACOL ' ||
                               ' from VRH_EMP_TCOL_VINCDIA X ' ||
                               ' where X.BDCODEMP = TMP.BDCODEMP and ' ||
                               ' X.BDCODCOL = TMP.BDCODCOL and ' ||
                               ' X.BDDATACOL <= TMP.BDDATABATIDA ' ||
                               ' order by X.BDDATACOL desc) as BDDATAQH, ' ||
                            ' (select first 1 X.BDCODPQUA ' ||
                               ' from VRH_EMP_TCOL_VINCDIA X ' ||
                               ' where X.BDCODEMP = TMP.BDCODEMP and ' ||
                               ' X.BDCODCOL = TMP.BDCODCOL and ' ||
                               ' X.BDDATACOL <= TMP.BDDATABATIDA ' ||
                               ' order by X.BDDATACOL desc) as BDCODPQUA, ' ||
                           ' (select first 1 X.BDCODQH ' ||
                               ' from VRH_EMP_TCOL_VINCDIA X ' ||
                               ' where X.BDCODEMP = TMP.BDCODEMP and ' ||
                               ' X.BDCODCOL = TMP.BDCODCOL and ' ||
                               ' X.BDDATACOL <= TMP.BDDATABATIDA ' ||
                               ' order by X.BDDATACOL desc) as BDCODQH, TMP.BDDIASEMQH ' ||
             ' from TMP_VRHF_COLCON_PLANOQH TMP) TAB ON (TAB.BDCODEMP = EMP.BDCODEMP) ' ||
             ' join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.BDCODEMP = TAB.BDCODEMP and ' ||
                                                   ' VINCDIA.BDCODCOL = TAB.BDCODCOL and ' ||
                                                   ' VINCDIA.BDDATACOL = TAB.BDDATAQH) ' ||
             ' where TAB.BDCODEMP = EMP.BDCODEMP ';
    
  FOR EXECUTE STATEMENT wSQL
  INTO :BDCODEMP, :BDCODCOL, :BDDATABATIDA, :BDDATAQH, :BDDIASEMQH, :BDQHHSSAI, :BDQHHSENT, :BDQTDCOLUNASQH, :BDCODPQUA, :BDCODQH
  do
  
  suspend;
end^

CREATE OR ALTER procedure GET_BASE_ESTRUTURA_OK
returns (
    PRRETORNO varchar(10000))
as
declare variable WRETRATO_ENT varchar(10000);
declare variable WRETRATO_SAI varchar(10000);
declare variable WRETRATO_REDZ varchar(10000);
declare variable WATUAL_ENT varchar(10000);
declare variable WATUAL_SAI varchar(10000);
declare variable WATUAL_REDZ varchar(10000);
declare variable WSTRAUXILIAR varchar(10000);
declare variable WTABATUAL varchar(70);
begin
  --o retrato atual do que ele trata, note que isto aqui sempre vai ser fixo....
  -- se você precisar mudar algo, execute a função GET_TABS_DEPENDENTES para gerar um novo "retrato"
  wretrato_ent  = '|VEF_EMP_TMOVENTFUNRURAL;11|VEF_EMP_TMOVENTRET;40|VEF_EMP_TC100ENT;14|VEF_EMP_TC195ENT;7|VEF_EMP_TC197ENT;13|VEF_EMP_TMOVENTVINCC197;6|VEF_EMP_TC300350ENT;7|VEF_EMP_TC500ENT;39|VEF_EMP_TD100ENT;25|VEF_EMP_TD500ENT;24|VEF_EMP_TMOVENTINFCOM;5|VEF_EMP_TMOVENTCUPREF;9|VEF_EMP_TMOVENTDOCAREF;11|VEF_EMP_TMOVENTDOCFREF;13|VEF_EMP_TMOVENTPROREF;6|VEF_EMP_TMOVENTCUPOMREF;9|VEF_EMP_TMOVENTITENS;43|VEF_EMP_TMOVENTDCIP;7|VEF_EMP_TMOVENTDIFALIQ;8|VEF_EMP_TMOVENTIMPRETSP;5|VEF_EMP_TMOVENTOCOSP;4|VEF_EMP_TMOVENTSN;20|VEF_EMP_TMOVENTVARALIQ;11|VEF_EMP_TMOVENTVINCBEM;6|VEF_EMP_TMOVPROENT;77|VEF_EMP_TOPMEDENT;12|VEF_EMP_TMOVPROENTGRF;8|VEF_EMP_TMOVENTVINCC197;6|VEF_EMP_TC171ENT;7|VEF_EMP_TMOVPROENTC177;13|VEF_EMP_TMOVC180_1250;16|VEF_EMP_TMOVC181_1250;26|VEF_EMP_TMOVENT_IVA;15|VEF_EMP_TMOVCCENT;10|VEF_EMP_TMOVRATENT;13|VEF_EMP_TMOVRATCCENT;10|VEF_EMP_TD590TOTENT;12|VEF_EMP_TC590TOTENT;12|VEF_EMP_TC190ENT;15|VEF_EMP_TMOVENTANTIMP;20|VEF_EMP_TMOVENTPMPF;15|VEF_EMP_TMOVENTMVA;24|VEF_EMP_TMOVENTSTDAPI;7|VEF_EMP_TMOVENTITENSCTR;4|VEF_EMP_TMOVENTQ48;14|VEF_EMP_TMOVENTANTPR;8|VEF_EMP_TMOVENTDIFPR;13|VEF_EMP_TMOVMVASC;13|VEF_EMP_TMOVENTPR;9|VEF_EMP_TMOVMVAPR;9|VEF_EMP_TMOVENTOPIMP;8|VEF_EMP_TMOVENTSVA;3|VEF_EMP_TMOVENTTELCONV;13|VEF_EMP_TMOVENTGRF;13|VEF_EMP_TMOVEXPINDIRETA;14|VEF_EMP_TMOVENTPAR;20|VEF_EMP_TMOVENTPARPGTO;38|VEF_EMP_TMOVENTPARPGTO_PR;11|VEF_EMP_TMOVENTSTATUS;12|VEF_EMP_TD195ENT;6|VEF_EMP_TD197ENT;13|VEF_EMP_TMOVENTDED;29|VEF_EMP_TMOVSAIECREDAC;13|VEF_EMP_DARF_RET;7|VEF_EMP_TMOVPROENTIMPORI;50|';
  wretrato_sai  = '|VEF_EMP_TMOVSAIRET;42|VEF_EMP_TC100SAI;14|VEF_EMP_TC195SAI;7|VEF_EMP_TC197SAI;13|VEF_EMP_TMOVSAIVINCC197;6|VEF_EMP_TC300350SAI;7|VEF_EMP_TC500SAI;41|VEF_EMP_TD100SAI;24|VEF_EMP_TD110SAI;6|VEF_EMP_TD120COMPCON;8|VEF_EMP_TD130COMPCON;15|VEF_EMP_TD160CARGATRANS;14|VEF_EMP_TD162DOCFIS;14|VEF_EMP_TD500SAI;28|VEF_EMP_TD530SAI;9|VEF_EMP_TMOVSAIINFCOM;5|VEF_EMP_TMOVSAICUPREF;9|VEF_EMP_TMOVSAIDOCAREF;11|VEF_EMP_TMOVSAIDOCFREF;13|VEF_EMP_TMOVSAILOCCOL;9|VEF_EMP_TMOVSAIPROREF;6|VEF_EMP_TMOVSAICUPOMREF;9|VEF_EMP_TMOVSAIITENS;42|VEF_EMP_TMOVSAIVINCBEM;5|VEF_EMP_TMOVPROSAI;76|VEF_EMP_TMOVPROSAIGRF;8|VEF_EMP_TENEGAS;7|VEF_EMP_TENETELE;6|VEF_EMP_TMOVPROSAIC177;13|VEF_EMP_TMOVPROSAIC178;7|VEF_EMP_TOPMEDSAI;12|VEF_EMP_TMOVSTC176;31|VEF_EMP_TMOVSAIVINCC197;6|VEF_EMP_TMOVC185_1250;19|VEF_EMP_TMOVC380_1250;19|VEF_EMP_TMOVC186_1250;20|VEF_EMP_TMOVSAIEXPSP;4|VEF_EMP_TMOVSAIIMPRETSP;5|VEF_EMP_TMOVSAIOCOSP;4|VEF_EMP_TMOVSAISN;20|VEF_EMP_TMOVSAIVARALIQ;11|VEF_EMP_TMOVSAI_INF_NF_SP;5|VEF_EMP_TMOVCCSAI;10|VEF_EMP_TMOVRATSAI;13|VEF_EMP_TMOVRATCCSAI;10|VEF_EMP_TC190SAI;15|VEF_EMP_TMOVSAISTDAPI;7|VEF_EMP_TF500SAI;14|VEF_EMP_TMOVSAIITENSCTR;4|VEF_EMP_TPLANILHASNDEB;20|VEF_EMP_TPLASNDEBDARF;4|VEF_EMP_TMOVSAIQ48;14|VEF_EMP_TMOVSAIECREDAC;13|VEF_EMP_TC850SAI;10|VEF_EMP_TC590TOTSAI;12|VEF_EMP_TMOVSAIPR;9|VEF_EMP_TMOVSAIDIFALIQ;8|VEF_EMP_TMOVSAIDIFPR;12|VEF_EMP_TMOVSAIPAR;20|VEF_EMP_TMOVSAIPARPGTO;37|VEF_EMP_TMOVSAIPARPGTO_PR;11|VEF_EMP_TMOVSAISVA;4|VEF_EMP_TMOVSAIVLTRAN;8|VEF_EMP_TMOVSAITELCONV;13|VEF_EMP_TMOVSAICARTR;14|VEF_EMP_TMOVSAIEXP;19|VEF_EMP_TMOVSAIGRF;13|VEF_EMP_TMOVSAICTR;5|VEF_EMP_TMOVEXPNFSAI;10|VEF_EMP_TMOVEXPINDIRETA;14|VEF_EMP_TMOVSERPERDCOMP;9|VEF_EMP_TMOVSAISTATUS;12|VEF_EMP_TD195SAI;6|VEF_EMP_TD197SAI;13|VEF_EMP_TMOVSAIFUNRURAL;9|VEF_EMP_TMOVSAIDED;29|VEF_EMP_TD400SAI;26|VEF_EMP_TD420SAI;8|VEF_EMP_TD411SAI;4|VEF_EMP_TMOVPROSAIIMPORI;50|';
  wretrato_redZ = '|VEF_EMP_TREDZ60I;11|VEF_EMP_TDOCECF;13|VEF_EMP_TITEMDOCECF;28|VEF_EMP_TMOVC480_1250;20|VEF_EMP_TREDZC490;10|VEF_EMP_TREDZVARCFOP;25|VEF_EMP_TREDZSN;20|VEF_EMP_TMOVCCREDZ;13|VEF_EMP_TMOVRATREDZVARCFOP;13|VEF_EMP_TREDZDADOSSPED;20|VEF_EMP_TREDZVARALIQ;10|VEF_EMP_TREDZC425ALIQ;29|VEF_EMP_TREDZC425;28|VEF_EMP_TF500REDZ;13|VEF_EMP_TREDZSTATUS;12|VEF_EMP_TREDZVARALIQISS;10|VEF_EMP_TREDZC425ALIQISS;28|VEF_EMP_TREDZC425ISS;26|';

  WATUAL_ENT = replace(GET_TABS_DEPENDENTES('VEF_EMP_TMOVENT', 'VEF', 1), '||', '|');
  WATUAL_SAI = replace(GET_TABS_DEPENDENTES('VEF_EMP_TMOVSAI', 'VEF', 1), '||', '|');
  WATUAL_REDZ = replace(GET_TABS_DEPENDENTES('VEF_EMP_TREDZ', 'VEF', 1), '||', '|');

  PRRETORNO = '';

  --Algo aqui mudou, o que precisamos fazer neste caso é identificar o que houve
  if (wretrato_ent <> WATUAL_ENT) then
     begin
        WSTRAUXILIAR = :WATUAL_ENT;

        while (:WSTRAUXILIAR <> '|') do
           begin
              WTABATUAL = substring(:wstrauxiliar from 1 for position('|', :wstrauxiliar, 2));

              --tabela temos uma divergência aqui
              if (Position(:WTABATUAL, wretrato_ent) = 0) then
                 begin
                    WTABATUAL = substring(:WTABATUAL from 1 for position(';', :WTABATUAL));

                    if (position(wtabatual,  wretrato_ent) = 0) then
                       begin
                       PRRETORNO = :PRRETORNO || '|Movimento de entrada: ' || Substring(wtabatual from 2 for CHAR_LENGTH(wtabatual) - 2) || ' - tabela não tratada pela rotina.';
                       end
                    else
                       begin
                       PRRETORNO = :PRRETORNO || '|Movimento de entrada: ' || Substring(wtabatual from 2 for CHAR_LENGTH(wtabatual) - 2) || ' - estrutura da tabela não confere.';
                 end   end

              --vamos para a próxima tabela
              WSTRAUXILIAR = substring(:wstrauxiliar from position('|', :wstrauxiliar, 2));
           end
     end

   --Algo aqui mudou, o que precisamos fazer neste caso é identificar o que houve
   if (wretrato_sai <> WATUAL_SAI) then
     begin
        WSTRAUXILIAR = :WATUAL_SAI;

        while (:WSTRAUXILIAR <> '|') do
           begin
              WTABATUAL = substring(:wstrauxiliar from 1 for position('|', :wstrauxiliar, 2));

              --tabela temos uma divergência aqui
              if (Position(:WTABATUAL, wretrato_sai) = 0) then
                 begin
                    WTABATUAL = substring(:WTABATUAL from 1 for position(';', :WTABATUAL));

                    if (position(wtabatual,  wretrato_sai) = 0) then
                       begin
                       PRRETORNO = :PRRETORNO || '|Movimento de saída: ' || Substring(wtabatual from 2 for CHAR_LENGTH(wtabatual) - 2) || ' - tabela não tratada pela rotina.';
                       end
                    else
                       begin
                       PRRETORNO = :PRRETORNO || '|Movimento de saída: ' || Substring(wtabatual from 2 for CHAR_LENGTH(wtabatual) - 2) || ' - estrutura da tabela não confere.';
                 end   end

              --vamos para a próxima tabela
              WSTRAUXILIAR = substring(:wstrauxiliar from position('|', :wstrauxiliar, 2));
           end
     end

   --Algo aqui mudou, o que precisamos fazer neste caso é identificar o que houve
   if (wretrato_redz <> watual_redz) then
     begin
        WSTRAUXILIAR = :watual_redz;

        while (:WSTRAUXILIAR <> '|') do
           begin
              WTABATUAL = substring(:wstrauxiliar from 1 for position('|', :wstrauxiliar, 2));

              --tabela temos uma divergência aqui
              if (Position(:WTABATUAL, wretrato_redz) = 0) then
                 begin
                    WTABATUAL = substring(:WTABATUAL from 1 for position(';', :WTABATUAL));

                    if (position(wtabatual,  wretrato_redz) = 0) then
                       begin
                       PRRETORNO = :PRRETORNO || '|Movimento de redução Z: ' || Substring(wtabatual from 2 for CHAR_LENGTH(wtabatual) - 2) || ' - tabela não tratada pela rotina.';
                       end
                    else
                       begin
                       PRRETORNO = :PRRETORNO || '|Movimento de redução Z: ' || Substring(wtabatual from 2 for CHAR_LENGTH(wtabatual) - 2) || ' - estrutura da tabela não confere.';
                 end   end

              --vamos para a próxima tabela
              WSTRAUXILIAR = substring(:wstrauxiliar from position('|', :wstrauxiliar, 2));
           end
     end

   SUSPEND;

end^

CREATE OR ALTER trigger tintegracao_arq_cliente_log_bi0 for tintegracao_arq_cliente_log
active before insert position 0
AS
begin
  /* Trigger text */
  new.bdhora = current_time;
  new.bddata = current_date;
end^

CREATE OR ALTER trigger vrh_tassverb_biu0 for vrh_tassverb
active before insert or update position 0
AS
begin
end^

CREATE OR ALTER TRIGGER VSH_EMP_TCONF_TSEQREL_SEQ_BI FOR VSH_EMP_TCONF_TSEQREL_SEQ
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^
CREATE OR ALTER TRIGGER VRHF_EMP_TDADOSCALC_BAIXA_BD0 FOR VRHF_EMP_TDADOSCALC_BAIXA
ACTIVE BEFORE DELETE POSITION 0
AS
begin
end
^

create or alter procedure VRHF_EMP_VAL_GRRF (
    PREMPRESA integer,
    PRCOLABORADOR integer,
    PRANOMES integer,
    PRANOMESPAG integer,
    PRTIPOCALCULO integer,
    PRCODTIPOFC integer = null,
    PRCHAVEDARF integer = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDBFGTSMESANT numeric(15,6),
    BDFGTSMESANT numeric(15,6),
    BDBFGTSMES numeric(15,6),
    BDFGTSMES numeric(15,6),
    BDSALDO numeric(15,6),
    BDFGTS40 numeric(15,6),
    BDFGTS10 numeric(15,6),
    BDTOTAL numeric(15,6),
    BDFGTSIND numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDVALOR numeric(15,6),
    BDPERCMULTA40 numeric(15,2),
    BDPERCMULTA10 numeric(15,2),
    BDBFGTSIND numeric(18,2),
    BDBFGTSMESFN numeric(18,2),
    BDBFGTSMES13 numeric(18,2),
    BDPOSSUIDATAFGTSDIGITAL DM_BOOLEAN,
    BDFGTS13 numeric(18,2))
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_BD2 FOR VRH_EMP_TCOLCON
ACTIVE BEFORE DELETE POSITION 0
as
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_FD FOR VRH_EMP_TCOLCON
ACTIVE BEFORE DELETE POSITION 0
as
begin
end
^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_CC_AD0 FOR TCONF_CONTAS_ONLINE_CC
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_CC_AU0 FOR TCONF_CONTAS_ONLINE_CC
ACTIVE AFTER UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_CC_BI0 FOR TCONF_CONTAS_ONLINE_CC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_AD0 FOR TCONF_CONTAS_ONLINE
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_REF_AD0 FOR TCONF_CONTAS_ONLINE_REF
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBAS_AD0 FOR VRH_BASE_TVERBAS
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBAS_REF_AD0 FOR VRH_BASE_TVERBAS_REF
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBAS_REF_AU0 FOR VRH_BASE_TVERBAS_REF
ACTIVE AFTER UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_REF_AI0 FOR TCONF_CONTAS_ONLINE_REF
ACTIVE AFTER INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_BASE_TPERIODORRA_ADV_BI0 FOR VRHF_BASE_TPERIODORRA_ADV
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_BASE_TPERIODORRA_BI0 FOR VRHF_BASE_TPERIODORRA
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VSH_EMP_TRETORNO_IC_BI0 FOR VSH_EMP_TRETORNO_IC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TIMPOSTOS_IC_BI0 FOR VEF_EMP_TIMPOSTOS_IC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TID_DECLARACAO_SN_IC_BI0 FOR VEF_EMP_TID_DECLARACAO_SN_IC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TNUMERODAS_SN_IC_BI0 FOR VEF_EMP_TNUMERODAS_SN_IC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_VINCDIA_BU0 FOR VRH_EMP_TCOL_VINCDIA
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_ABONO_BI0 FOR VRH_EMP_TRECLAMATORIA_ABONO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER vrhf_emp_tfcpensao_dep_bi0 for vrhf_emp_tfcpensao_dep
active before insert position 0
AS
begin
end 
^

create or alter procedure SP_VRH_UPDATE_DATAIR_FN
as
begin
end
^

create or alter procedure SP_VRH_UPDATE_DATA_IR_13
as
begin
end
^

create or alter procedure SP_VRH_UPDATE_DATAIR_AD13
as
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHACOMP_BI0 FOR VRHF_EMP_TFOLHACOMP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLTOMCOMP_BU0 FOR VRHF_EMP_TFOLTOMCOMP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
BEGIN
END^

create or alter procedure SP_FGTS_DIGITAL_COMP (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRPUXAFILIAL boolean,
    PRANUAL boolean)
returns (
    BDNOME_MATRIZ varchar(200),
    BDCODFILIAL integer,
    BDCODEMP integer,
    BDNOMEMP varchar(200),
    BDCNPJEMP varchar(20),
    BDCOMP varchar(20),
    BDREF integer,
    BDNOMECOL varchar(200),
    BDCODCOL integer,
    BDCPFCOL varchar(20),
    BDMATCOL varchar(50),
    BDCATEGORIA integer,
    BDORIGEM varchar(50),
    BDBASE_FGTS_DIGITAL numeric(18,6),
    BDBASE_FGTS_DIGITAL_RES numeric(18,6),
    BDBASE_FGTS_DIGITAL_13 numeric(18,6),
    BDVALOR_FGTS_DIGITAL numeric(18,6),
    BDVALOR_FGTS_DIGITAL_RES numeric(18,6),
    BDVALOR_FGTS_DIGITAL_13 numeric(18,6),
    BDBASE_FGTS_UNICO numeric(18,6),
    BDBASE_FGTS_UNICO_RES numeric(18,6),
    BDBASE_FGTS_UNICO_13 numeric(18,6),
    BDVALOR_FGTS_UNICO numeric(18,6),
    BDVALOR_FGTS_UNICO_RES numeric(18,6),
    BDVALOR_FGTS_UNICO_13 numeric(18,6),
    BDBASE_MULTA_UNICO numeric(15,2),
    BDBASE_MULTA_FD numeric(15,2),
    BDVALOR_MULTA_UNICO numeric(15,2),
    BDVALOR_MULTA_FD numeric(15,2),
    BDEXISTEDIFERENCA smallint)
as  
BEGIN
  SUSPEND;
END
^

create or alter procedure FILTRO_DOWNLOAD_ESOCIAL (WFILTRO integer)
returns (
    BDNO varchar(100),
    BDCLASSIFICACAO varchar(30),
    BDCODEMP integer,
    BDRAIZ varchar(15),
    BDCODESTAB integer,
    BDTIPINSC integer,
    BDCNPJRESP varchar(15),
    BDCODCC integer,
    BDDESCRICAO varchar(100),
    BDMATRIZ varchar(15),
    BDCODMATRIZ integer,
    BDTIPO varchar(8),
    BDIMPORTA varchar(15),
    BDCAD varchar(15),
    BDESTABUNICO varchar(15),
    BDINSCRICAO varchar(20),
    BDESTAB varchar(15),
    BDLOTTRIB varchar(15),
    BDFUNCOES varchar(15),
    BDHORARIOS varchar(15),
    BDCOLMOV varchar(15),
    BDCONMOV varchar(15))
as  
BEGIN
  SUSPEND;
END
^

create or alter procedure SP_VRHF_PENSAO_MES (
    PRREFINI integer,
    PRREFFIM integer,
    PRTEMEMP smallint,
    PRFN smallint = 0,
    PRADSAL smallint = 0,
    PRFER smallint = 0,
    PRAD13 smallint = 0,
    PR13SAL smallint = 0,
    PRC13 smallint = 0,
    PRFA smallint = 0,
    PRFC smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDREF integer,
    BDREFPAGTO integer,
    BDTIPO integer,
    BDCODVER integer,
    BDDESCVER varchar(40),
    BDNOMBENEF varchar(70),
    BDCPFBENEF varchar(14),
    BDCTACORRETE varchar(15),
    BDDCTACORRETE varchar(2),
    BDCODBAN integer,
    BDCODAG integer,
    BDDATANASCBENEF date,
    BDNOMAG varchar(40),
    BDNOMBAN varchar(60),
    BDCODAGBAN varchar(5),
    BDCODAGBANDV varchar(2),
    BDVALPENSAO numeric(18,6),
    BDNOMBENEFUPPER varchar(70),
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDDATARESCISAO date,
    BDCPFCOL varchar(14),
    BDCODFEBRABAN varchar(4))
as
begin
  suspend;
end^

create or alter procedure SP_VRH_UPDATE_DATAIR_INICIAL
returns (
    RSTATUS boolean)
as
BEGIN suspend;
end^

create or alter procedure SP_VRH_UPDATE_DATAIRRFESOCIAL (
    PRCODEMP integer,
    PRCHAVE integer)
returns (
    RDATAIRRFESOCIAL date,
    RREFIRRFESOCIAL integer)
as
BEGIN suspend;
end^

CREATE OR ALTER PROCEDURE SP_VRHF_BASE_EMPGPS_ATUAL (PRCODEMP INTEGER, PRREF INTEGER)
RETURNS (
    BDRATEIO13SAL INTEGER
) AS
BEGIN SUSPEND;
END^

CREATE OR ALTER TRIGGER VRHF_EMP_TFAPENSAO_DEP_BIU0 FOR VRHF_EMP_TFAPENSAO_DEP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFEPENSAO_DEP_BIU0 FOR VRHF_EMP_TFEPENSAO_DEP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

create or alter procedure SP_ATU_DADOS_MV_ATU (
    PRCPF varchar(14),
    PRREFINI integer,
    PRREFIM integer)
as
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TADSALPENSAO_DEP_BIU0 FOR VRHF_EMP_TADSALPENSAO_DEP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^


create or alter procedure SP_VRHF_CODEMPREENDIMENTO (
    PREMP integer,
    PRREF integer,
    PRCODTPCC integer,
    PRPLANOCC integer = null)
returns (
    BDCODEMP integer,
    BDCODEMPREENDIMENTO integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRH_PREV_CONTRATO_EXP (
    PRTEMEMP smallint,
    PRFILTROATIVOS smallint,
    PRDATAINI date,
    PRDATAFIM date,
    PRCOMCC smallint = 0,
    PRMODELO smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDDATAFIMPRAZO1COL date,
    BDDIASPRAZO1COL integer,
    BDDATAFIMPRAZO2COL date,
    BDDIASPRAZO2COL integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDNOMCC DM_BDNOMEMP,
    BDCODSINTRAB integer)
as
declare variable WSQL varchar(10000);
declare variable WWHERE varchar(10000);
declare variable WREF integer;
declare variable WCODEMP integer;
declare variable WNOMEMP DM_BDNOMEMP;
begin
  suspend;
end^

/*#191959 | Título: S-1210 PELA BAIXA DE CALCULO em competencia posterior - Nathan de Faria */
create or alter procedure SP_ESOCIAL_TVINCULO_FOL_S1210 (
    PRBDMULTIEMP varchar(5000),
    PRBDCODEMP integer,
    PRBDCODCOL integer,
    PRBDCODTER integer,
    PRBDREF integer,
    PRCPF DM_CNPJ_CPF = null /* COLLATE WIN1252 - default */ ,
    PRIMPORTACAOFICHA boolean = false,
    PREXPORTACAOMANUAL boolean = false)
returns (
    BDCODTERINI integer,
    BDCODCOLINI integer,
    BDCODEMPINI integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODTER integer)
as
declare variable VBDCPFCOL varchar(15);
declare variable VBDCPFTER varchar(15);
declare variable VSQL varchar(30000);
declare variable VMEITER DM_BOOLEAN;
declare variable WPAGAMENTO integer;
declare variable WTRANSFERENCIA integer;
declare variable WDTPAG varchar(15);
declare variable WDTRESC varchar(15);
declare variable WTEMTRANS integer;
begin
  suspend;
end^

create or alter procedure VRH_SP_CALC_TERC (
    PRCODEMP varchar(10000),
    PRCPFTER varchar(14),
    PRREF integer)
returns (
    BDTIPO varchar(2),
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFAUXV numeric(18,6),
    BDREFVR numeric(18,6),
    BDVAL numeric(18,6),
    BDCLAVER varchar(20),
    BDTIPOREFVER integer,
    BDHEVER numeric(18,6),
    BDINSCLOTACAO varchar(50),
    BDMATRICULA varchar(50),
    BDCODLOTACAO varchar(50),
    BDTIPOESTAB integer,
    BDINDSIMPLES integer,
    BDCODCLATRI integer,
    BDREFDEMONSTRATIVO integer,
    BDDATASERV date,
    BDDATAFOLHA date,
    BDDATAINISERVTI date,
    BDCODSERV integer,
    BDCATEGORIAESOCIAL integer,
    BDGRAUEXP integer,
    BDNATOCUP integer,
    BDCODCONTTI integer,
    BDDATARESCISAO date,
    BDDOCPRINCIPAL varchar(50),
    BDDOCAUX varchar(50),
    BDTIPOCAEPF integer,
    BDCAEPF varchar(50))
as
declare variable WSQL varchar(32700);
declare variable WSQL2 varchar(32700);
declare variable WDIA integer;
declare variable WMES integer;
declare variable WANO integer;
declare variable WPRIDIA date;
declare variable WULTDIA date;
declare variable WCODTER integer;
begin
  suspend;
end^
CREATE OR ALTER procedure SP_VRHF_EMP_TCOLCON_MVINC_RFIM (
    PREMP varchar(32700),
    PRCOL varchar(32000),
    PRREF integer,
    PRREFFIM integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDBASEINSSNCOL numeric(18,6),
    BDBASEINSS13COL numeric(18,6))
as
declare variable WBASEINSSNCOL numeric(18,6);
declare variable WBASEINSS13COL numeric(18,6);
declare variable WDATEATU integer;
begin
  suspend;
end^


--#183582 - Anexar protocolo assinado - Julio Cesar 12/09/2023
CREATE OR ALTER TRIGGER VCT_EMPRESA_PROTOENTRAFILE_BI0 FOR VCT_EMPRESA_PROTOCOLOENTRAFILE
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

--#183582 - Anexar protocolo assinado - Julio Cesar 12/09/2023
CREATE OR ALTER TRIGGER VCT_EMPRESA_PROTOSAIDAFILE_BI0 FOR VCT_EMPRESA_PROTOCOLOSAIDAFILE
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VCT_TRIBUTARIO_EMPRESA_BI0 FOR VCT_TRIBUTARIO_EMPRESA
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
end^

CREATE OR ALTER trigger vct_tributario_empresa_bu0 for vct_tributario_empresa
active before insert or update or delete position 1
AS
begin
end^

CREATE OR ALTER trigger vct_tributario_empresa_bud0 for vct_tributario_empresa
active before delete position 2
AS
begin
end^

CREATE OR ALTER trigger tempresaimposto_biud0 for tempresaimposto
active before insert or update or delete position 0
AS
begin
end^

CREATE OR ALTER TRIGGER tempresaimposto_bi0 FOR tempresaimposto
ACTIVE BEFORE INSERT POSITION 1
AS
BEGIN
end^


CREATE OR ALTER TRIGGER VRH_BASE_TRELCONF_BI0 FOR  VRH_BASE_TRELCONF
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^


CREATE OR ALTER TRIGGER VRH_BASE_TRELCONF_ITENS_BI0 FOR  VRH_BASE_TRELCONF_ITENS
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

create or alter procedure SP_ATU_DADOS_MV_ATU (
    PRCPF varchar(14),
    PRREFINI integer,
    PRREFFIM integer)
as
begin
end^

create or alter procedure SP_VRHF_GETRESCISAOESTABRED (
    PREMP integer,
    PRCOL integer,
    PRLISTAANOS varchar(500))
returns (
    ANO integer,
    DATAINICIO date,
    DATAFIM date,
    SUSPENSAO DM_BOOLEAN,
    PERCREDUCAO numeric(18,6),
    DIASREDSUSP integer,
    BDDIASACORDOINI integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRH_RELATORIOCONFCOL_FN (
    PREMP varchar(10000),
    PRCOL varchar(20000),
    PRAUT varchar(10000),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPACC smallint = 0,
    PRCC varchar(10000) = null,
    PRAGRUPASETOR smallint = 0,
    PRSETOR varchar(10000) = null,
    PRCCPAGTOIR smallint = 0)
returns (
    BDCODEMP integer,
    BDCODFILIAL integer,
    BDREF integer,
    BDTIPOCOL integer,
    BDCODCOL integer,
    BDVALOR numeric(18,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCODCENTROSETOR integer,
    BDCODSETOR integer)
as
begin
  suspend;
end^
    


create or alter procedure SP_VRH_RELATORIOCONFIGURAVEL_COL (
    PREMP varchar(10000),
    PRCOL varchar(20000),
    PRAUT varchar(10000),
    PRCLA varchar(5000),
    PRSIND varchar(5000),
    PRFUC varchar(5000),
    PRREFINI integer,
    PRREFFIM integer,
    PRSITCOL smallint,
    PRAGRUPACC smallint = 0,
    PRCC varchar(10000) = null,
    PRAGRUPASETOR smallint = 0,
    PRSETOR varchar(10000) = null,
    PRPAGTOIR smallint = 0)
returns (
    BDCODEMP integer,
    BDREF integer,
    BDTIPOCOL integer,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDNOMTPCC DM_BDNOMEMP,
    BDCODFILIAL integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCENTROSETOR integer,
    BDCODSETOR integer,
    BDNOMSETOR DM_BDNOMEMP)

as
begin
  suspend;
end^

CREATE OR ALTER VIEW VW_VRH_SISQUAL_FUNCAO(
    BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^

CREATE OR ALTER VIEW VW_VRH_SISQUAL_CENTRO_CUSTO(
    BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^

CREATE OR ALTER VIEW VW_VRH_SISQUAL_COLABORADOR(
    BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^  

CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_CENTROCUSTO(
    BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^ 

CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_CONTRATO(
    BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^   

CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_EMP_SAL(
    BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^ 

CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_FER_ATUAIS(
    BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^   

CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_FUNCAO(
    BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^   

CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_HIST_AFAST(
    BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^     

CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_HIST_FER(
    BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^  

CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_SALDO_FER(
    BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^ 

CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_SINDICATO(
    BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^ 

CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_TPSAL_VINC(
    BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^
  
CREATE OR ALTER VIEW VW_VRH_SISQUAL_EMPRESA_SALARIO(
    BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^  

CREATE OR ALTER VIEW VW_VRH_SISQUAL_FERI_NACIONAL(
    BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^  
  
  
CREATE OR ALTER VIEW VWRH_UNION_FN_FT_MES_PGTO(BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^  

  
  
CREATE OR ALTER VIEW VW_VRHF_EMP_TFICHAINSS_UNION_ALL(
    BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^
  
  
CREATE OR ALTER VIEW VW_VRH_FUNCOES_TFUC_ATIVAS(BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^


CREATE OR ALTER VIEW VW_TPAIS_NASC_ATIVOS(BDCODEMP)
AS
select cast(0 as integer)
  from RDB$DATABASE^
  

create or alter procedure SP_VRHF_GETPISOSIND (
    PRCODSINTRAB integer,
    PRANOMES integer)
returns (
    BDCODSINTRAB integer,
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDREFPISO integer,
    BDSALPISO numeric(15,6))
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETFALTAS (
    PREMP integer,
    PRCOL integer,
    PRULTDIAMES date)
returns (
    BDREFFAL integer,
    BDDATAFAL date,
    BDTIPOFAL integer,
    BDHORASFAL numeric(18,6),
    BDTIPODSRFAL integer,
    BDTIPODESCFAL integer,
    BDCODTIPO integer,
    BDCODNOTIF integer,
    BDINDEVIDAFAL DM_BOOLEAN,
    BDDESCINDEVIDA varchar(100),
    BDNOFECHAMENTO DM_BOOLEAN)
as
begin
  suspend;
end^

create or alter procedure VRH_SP_REL_RECIBO_INT (
    PRCODEMP varchar(15000) = '',
    PRCODCOL varchar(15000) = '',
    PRCODCONTRATO varchar(1000) = '',
    PRDATAINICIAL varchar(10) = '',
    PRDATAFINAL varchar(10) = '',
    PRVERBASDEM smallint = 1,
    PRFILTROCOL varchar(500) = '',
    PRCODTPCC varchar(1000) = '',
    PRCODSINTRAB varchar(1000) = '',
    PRCODCLA varchar(500) = '',
    PRCODFUNCAO varchar(1000) = '',
    PREMISSAO smallint = 0,
    PRORDEM smallint = 0,
    PRIMPRIMICC smallint = 0,
    PRFOLHACOMP smallint = 0,
    PRDATAPGTOINICIAL varchar(10) = '',
    PRDATAPGTOFINAL varchar(10) = '')
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(18),
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDRGCOL varchar(13),
    BDCTPSCOL varchar(11),
    BDSERIECTPSCOL varchar(11),
    BDDSERIECTPSCOL varchar(1),
    BDCODCBO integer,
    BDDESCTFUC varchar(40),
    BDSALBASECOL numeric(18,6),
    BDCODCONTTI integer,
    BDDESCCONTRATOTI varchar(2000),
    BDDATACONVTI date,
    BDHORACONVTI time,
    BDDATAINISERVTI date,
    BDDATAFIMSERVTI date,
    BDDATAPAGTI date,
    BDLIQUIDO numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDDATAPGTOFN date,
    BDFGTSFN numeric(18,6),
    BDFGTS13FN numeric(18,6),
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFVFN numeric(18,6),
    BDREFAUXVFN numeric(18,6),
    BDVALVFN numeric(18,6),
    BDVALIFN numeric(18,6),
    BDDESCVER varchar(40),
    BDTIPOCODVER integer,
    BDORDEMVER integer,
    BDORDEMTIPOCODVER integer,
    BDCLAVER varchar(20),
    BDCONVRESCTI DM_BOOLEAN,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDNOMCTA varchar(40),
    BDCODTOM integer,
    BDNOMTOM varchar(70),
    BDTXTMENS varchar(2000))
as
begin
   suspend;
end^

create or alter procedure SP_RECLAMATORIA_PGMES (
    PREMP integer,
    PRCHAVE integer)
returns (
    BDCODEMP integer,
    BDCHAVE integer,
    BDCODVINC integer,
    BDANOMES integer,
    BDBINSS DM_NUMERIC_18_3,
    BDBINSS13 DM_NUMERIC_18_3,
    BDBFGTSNAODEC DM_NUMERIC_18_3,
    BDBFGTSDECSEFIP DM_NUMERIC_18_3,
    BDOCORRENCIA integer,
    BDBFGTSDECESOCIAL DM_NUMERIC_18_3)
as
begin
  suspend;
end^

CREATE OR ALTER TRIGGER TDIC_ESOCIAL_REL_TAB_BI0 FOR TDICIONARIO_ESOCIAL_REL_TAB
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TDIC_ESOCIAL_REL_FIXO_BI0 FOR TDICIONARIO_ESOCIAL_REL_FIXO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECL_CONTR_SUC_BI0 FOR VRH_EMP_TRECLAMA_CONTRATO_SUC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECL_CONTR_OBS_BI0 FOR VRH_EMP_TRECLAMA_CONTRATO_OBS
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMA_RESC_BI0 FOR VRH_EMP_TRECLAMA_RESC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

create or alter procedure SP_VRH_RECLAMATORIA_DEP (
    PREMPRESA integer,
    PRCHAVE integer)
returns (
    BDCODEMP integer,
    BDCHAVE integer,
    BDCODDEP integer,
    BDCPFDEP DM_CNPJ_CPF,
    BDNOMDEP varchar(68) collate WIN_PTBR,
    BDPARENESCODPN integer,
    BDDESCDEP varchar(30) collate WIN_PTBR)
as
begin
  suspend;
end^

create or alter procedure SP_VRH_RECLAMATORIA (
    PREMPRESA integer,
    PRCHAVE integer)
returns (
    BDCODEMP integer,
    BDCHAVE integer,
    BDRESPDIRETO DM_BOOLEAN,
    BDNOMRESPDIRETO DM_BDNOMRESPDIRETO,
    BDCNPJRESPDIRETO DM_CNPJ_CPF,
    BDCODRT integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL DM_CNPJ_CPF,
    BDDATANASCCOL date,
    BDCODCOL integer,
    BDTIPOPROCRT integer,
    BDNUMEROPROCESSO DM_BDNUMPROCJUD,
    BDDATASENTENCA date,
    BDCODCID integer,
    BDCODVARA integer,
    BDDATACONCILIACAO date,
    BDAMBITO integer,
    BDCNPJNINTER DM_CNPJ_CPF,
    BDCODSINTRAB integer,
    BDOBSERVACOES blob sub_type 1 segment size 80,
    BDCODIBGE integer,
    BDSIGLAUF varchar(2),
    BDMATRESPDIRETO varchar(30))
as
begin
  suspend;
end^

create or alter procedure SP_VRH_RECLAMA_RESC (
    PREMPRESA integer,
    PRCHAVE integer)
returns (
    BDCODEMP integer,
    BDCODVINC integer,
    BDCODCOL integer,
    BDCODPRES integer,
    BDDATARESCISAO date,
    BDDATAAVPREV date,
    BDCODMOTESRESC integer,
    BDINDPENALIM integer,
    BDVALFGTSRESC numeric(18,6),
    BDPERFGTSRESC numeric(18,6))
as
begin
  suspend;
end^

create or alter procedure SP_VRH_RECLAMA_CONTRATO (
    PREMPRESA integer,
    PRCHAVE integer)
returns (
    BDCODEMP integer,
    BDCODVINC integer,
    BDCODCOL integer,
    BDDATAADMCOL date,
    BDMATRICULA varchar(30) collate WIN_PTBR,
    BDCATEGORIAESOCIAL integer,
    BDCODCBO integer,
    BDNATATIV integer,
    BDREGTRAB integer,
    BDREGPREV integer,
    BDDURACAOCONTRATO integer,
    BDDATATERMINO date,
    BDTIPOCONTRPARC integer,
    BDOSERVACAO varchar(300) collate WIN_PTBR)
as
begin
  suspend;
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_TTIPO_ARQ_BI0 FOR VRH_ESOCIAL_TTIPO_ARQ
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_RESC_BI0 FOR VRH_EMP_TRECLAMATORIA_RESC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_ADM_BI0 FOR VRH_EMP_TRECLAMATORIA_ADM
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_REM_BI0 FOR VRH_EMP_TRECLAMATORIA_REM
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_PGMES_BI0 FOR VRH_EMP_TRECLAMATORIA_PGMES
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMA_IDPGTO_BI0 FOR VRH_EMP_TRECLAMATORIA_IDPGTO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMA_CONTRATO_BI0 FOR VRH_EMP_TRECLAMA_CONTRATO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TREPERCUSSAOPROC_BI0 FOR VRH_BASE_TREPERCUSSAOPROC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRT_VICCAT_BI0 FOR VRH_EMP_TRECLAMATORIA_VICCAT
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_TINFO_TEMP_RENDTRIBRRA_BU0 FOR VRHF_TINFO_TEMP_RENDTRIBRRA
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_VINC_BI0 FOR VRH_EMP_TRECLAMATORIA_VINC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_DEP_BI0 FOR VRH_EMP_TRECLAMATORIA_DEP
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TRECLAMATORIA_BI0 FOR VRH_BASE_TRECLAMATORIA
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_BI0 FOR VRH_EMP_TRECLAMATORIA
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

create or alter procedure SP_CONSULTA_PLANO_TROCA (
    PRCODEMP integer,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDREFEMP integer,
    BDCODPLATROCA integer,
    BDORDEM integer)
as
begin
  suspend;
end
^

create or alter procedure SP_CONSULTA_TERCEIROREF (
    PRREF integer,
    PRCODTER integer)
returns (
    BDCODTER integer,
    BDCGCTER varchar(18),
    BDREFEMP integer,
    BDAPELIDOTER varchar(20),
    BDNOMETER varchar(100),
    BDLOGRTER varchar(15),
    BDENDTER DM_BDENDERECO,
    BDNUMTER DM_NUMEND,
    BDCOMPTER DM_BDCOMPENDERECO,
    BDCEPTER varchar(9),
    BDBAITER varchar(60),
    BDDDDTER varchar(3),
    BDFONETER DM_BDTELEFONE,
    BDFAXTER DM_BDTELEFONE,
    BDEMAILTER DM_BDEMAIL,
    BDIETER varchar(20),
    BDDATACADTER date,
    BDIMTER varchar(16),
    BDPRURALTER varchar(5),
    BDENQSIMPLESFEDTER integer,
    BDINSCSUFRAMATER varchar(10),
    BDCODGPS integer,
    BDCODCID integer,
    BDCODPAIS integer,
    BDDESCPAIS varchar(60),
    BDDDDFAXTER varchar(3),
    BDCODUF integer,
    BDSIGLAUF varchar(2),
    BDNOMCID varchar(40),
    BDORGAOPUBLICO varchar(5),
    BDCODIBGE integer,
    BDCODAQUIRUR integer,
    BDPRODPF varchar(5),
    BDCPFPROD varchar(18))
as
begin
  suspend;
end^


create or alter procedure SP_CONSULTA_EFPARGER (
    PRREF integer)
returns (
    BDCODEMP integer,
    BDTIPOAPURACAORETIR integer,
    BDTIPOAPURACAORET integer,
    BDTIPOAPURACAORETIRTOM integer,
    BDTIPOAPURACAO integer)
as
begin
      suspend;
end^



create or alter procedure SP_CONSULTA_EMPRESA_REF (
    PRCODEMP integer,
    PRREFEMP integer)
returns (
    BDIEEMP varchar(20),
    BDCODEMP integer,
    BDREFEMP integer,
    BDNOMEMP varchar(255),
    BDCODCID integer,
    BDSITEMP varchar(5),
    BDIAT_PISCOF_SEM_ICMS DM_BOOLEAN,
    BDCARACTRIBUTARIA integer,
    BDSUBSTRIB integer,
    BDCODENQFED integer,
    BDFORMATRIBUTACAO integer,
    BDCNPJEMP varchar(18),
    BDCODCNAE integer,
    BDCODPLAPADRAO integer)
as
begin
  suspend;
end^

create or alter procedure SP_EMPRESA_UF (
    PRCODEMP integer,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDSIGLAUF char(2))
as
begin
  suspend;
end^

create or alter procedure SP_RET_REF_1010_1020_EXPORT (
    PRCODEMP varchar(2000),
    PRSAIDA varchar(5),
    PRDATAINI date,
    PRDATAFIM date,
    PRREG varchar(4))
returns (
    BDORDEMINDORIG integer,
    BDNUMPROC varchar(20),
    BDCHAVE integer,
    BDCODEMP integer,
    BDMOVIMENTO integer,
    BDREF integer,
    BDDATAINI date,
    BDDATAFIM date)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_PBM_GPS (
    PREMP varchar(30000),
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDREF integer,
    BDCODREC integer,
    BDPERC numeric(15,4),
    BDBASEPBM numeric(18,2),
    BDBASEFAT numeric(18,2))
as
begin
  suspend;
end^

create or alter procedure SP_CONS_FILA_RHNET (
 PRDATA varchar(10),
    PRANOMES integer)
returns (
    BDCODARQ integer,
    BDCHAVEARQIND varchar(40),
    BDNOMARQJSON varchar(500),
    BDJSONVALUE blob sub_type 0 segment size 80,
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDDATAHORA timestamp,
    BDORIGEM varchar(500),
    BDSTATUS integer,
    BDRETORNO blob sub_type 1 segment size 16384,
    BDQTDAGUARDANDO integer,
    BDQTDENVIADO integer,
    BDQTDERROENVIO integer,
    BDSTATUSEXP varchar(15),
    BDTIPOJSON varchar(25))
as
begin
  suspend;
end^


create or alter procedure SP_VRHF_GETCONTRSINDICAISNOANO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDCONTRSINDICAL DM_BOOLEAN,
    BDCONTRASSISTENCIAL DM_BOOLEAN)
as
begin
  suspend;
end^


create or alter procedure SP_VRHF_GETVERBFERIASREF (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDTIPOFE integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDCODVER integer,
    BDREFFE integer,
    BDREFVRFE DM_NUMERIC_15_2,
    BDREFAUXVRFE DM_NUMERIC_15_2,
    BDVALVRFE DM_NUMERIC_15_2,
    BDIGNREFVRFE DM_BOOLEAN,
    BDIGNVALVRFE DM_BOOLEAN,
    BDCODVERFN integer,
    BDDETALHERFE varchar(500),
    BDORDEMDETALHE integer,
    BDVALIRFE DM_NUMERIC_15_2,
    BDIGNREFAVRFE DM_BOOLEAN,
    BDCALCA13FE DM_BOOLEAN,
    BDTEMPOSERVFE integer,
    BDCLAVER varchar(20))
as
begin
  suspend;
end^

CREATE OR ALTER TRIGGER TFOLHAPGTOESOCIAL_AIU1 FOR TFOLHAPGTOESOCIAL
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VRH_CAD_TIPOREVEZAMENTO_BI0 FOR VRH_CAD_TIPOREVEZAMENTO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TTELA_SISTEMA_BI0 FOR TTELA_SISTEMA
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

-- Sol.183659 - Nathan de Faria - 02/08/2023
CREATE OR ALTER TRIGGER VRH_ESOCIAL_TARQUIVO_BI0 FOR VRH_ESOCIAL_TARQUIVO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^


CREATE OR ALTER TRIGGER VEF_EMP_TDIMEGERREGESP_AD0 FOR VEF_EMP_TDIMEGERREGESP
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER trigger TDEFESTABDOWN_BI10 for TDEFESTABDOWN
active before insert position 0
AS
begin
end^

CREATE OR ALTER trigger tdefestabdown_biu0 for tdefestabdown
active before insert or update position 0
as
begin
end^

CREATE OR ALTER trigger TDEFFUNCIONARIODOWN_BU0 for TDEFFUNCIONARIODOWN
active before update position 0
AS
begin
end^

CREATE OR ALTER trigger TDEFFUNCIONARIODOWN_BIU0 for TDEFFUNCIONARIODOWN
active before insert position 0
as
begin
end^

CREATE OR ALTER trigger TDEFLOTACAODOWN_AIU0 for TDEFLOTACAODOWN
active before insert or update position 0
as
begin
end^

CREATE OR ALTER trigger TDEFLOTACAODOWN_AIU1 for TDEFLOTACAODOWN
active after insert or update position 0
as
begin
end^

CREATE OR ALTER trigger TESTRUTURADOWN_BI0 for TESTRUTURADOWN
active before insert position 0
AS
begin
end^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVENT_BI0 FOR VEF_EMP_TMOVENT
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^


CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAI_BI0 FOR VEF_EMP_TMOVSAI
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VRHF_CUSTOS_TVNCUSTO_BIU0 FOR VRHF_CUSTOS_TVNCUSTO
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_BASE_TVNPRES_BIU0 FOR VRHF_BASE_TVNPRES
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_FUNCOES_TVNFUC_BIU0 FOR VRHF_FUNCOES_TVNFUC
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_BASE_TVNSIND_BIU0 FOR VRHF_BASE_TVNSIND
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVNEMP_BIU0 FOR VRHF_EMP_TVNEMP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVNCOL_BIU0 FOR VRHF_EMP_TVNCOL
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_CUSTOS_TVSCUSTO_BIU0 FOR VRHF_CUSTOS_TVSCUSTO
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_BASE_TVSPRES_BIU0 FOR VRHF_BASE_TVSPRES
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_FUNCOES_TVSFUC_BIU0 FOR VRHF_FUNCOES_TVSFUC
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_BASE_TVSSIND_BIU0 FOR VRHF_BASE_TVSSIND
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVSEMP_BIU0 FOR VRHF_EMP_TVSEMP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^

create or alter procedure SP_GET_MONTA_COMP_VERBA (
    PRDIA integer,
    PRMES integer,
    PRANO integer,
    PRINICIAL smallint = 0)
returns (
    BDCOMPETENCIA DM_COMP_8)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETBAIXAAUTOMATICA (
    PRCODPLANOONLINE integer,
    PRCODBAIXA integer,
    PRANOMES integer)
returns (
    BDCHAVEFN integer,
    BDCHAVEFC integer,
    BDCHAVESERV integer,
    BDCHAVEADSAL integer,
    BDCHAVEFER integer,
    BDCHAVEAD13 integer,
    BDCHAVE13 integer,
    BDCHAVECOMP13 integer,
    BDCHAVERESC integer,
    BDCHAVEFA integer,
    BDDESCRICAO varchar(200),
    BDCREDFN integer,
    BDCREDFC integer,
    BDCREDSERV integer,
    BDCREDADSAL integer,
    BDCREDFER integer,
    BDCREDAD13 integer,
    BDCRED13 integer,
    BDCREDCOMP13 integer,
    BDCREDRESC integer,
    BDCREDFA integer)
as
begin
  suspend;
end^


CREATE OR ALTER TRIGGER VRH_BASE_TVERBAS_BU0 FOR VRH_BASE_TVERBAS
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end
^

create or alter procedure SP_CONS_INTEGRACAO_ESOCIAL (
    PRCODEMP integer,
    PRCODCOL integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODIGO integer,
    BDDATACONS date,
    BDNOMCOL varchar(70),
    BDDATANASC date,
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDRECIBO varchar(30))
as
begin
 suspend;
end^


CREATE OR ALTER TRIGGER VRH_BASE_TLISTAJSONRHNET_BI0 FOR VRH_BASE_TLISTAJSONRHNET
ACTIVE BEFORE INSERT POSITION 0
AS
begin

end
^
create or alter procedure SP_EXCLUI_CHAVES_TOL_FOLHA (
    PREMPRESA integer,
    PRTABELATOL varchar(256))
as
begin
end^

CREATE OR ALTER procedure SP_VRHF_EMP_TVERBAFN_DET (
    WWHERE varchar(500))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDDATAINI date,
    BDDATAFIM date,
    BDDETALHE varchar(70) collate WIN_PTBR)
as
BEGIN
   SUSPEND;
END^

create or alter procedure SP_FILA_QUALIFICA_ESOCIAL (
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(100),
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDDATANASCCOL date,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP DM_CNPJ_CPF,
    BDTIPO integer,
    BDIDRHNETADMPRE integer)
as
begin
  suspend;
end^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TTABFUMDES FOR VEF_BASE_TTABFUMDES
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TTABTRIBNAC FOR VEF_BASE_TTABFUMDES
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_ESTADOS_TCONFDIMEQ_BI0 FOR VEF_ESTADOS_TCONFDIMEQ
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TTABFUNDOSOCIAL FOR VEF_BASE_TTABFUNDOSOCIAL
ACTIVE BEFORE INSERT POSITION 0
as
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TFILAQUALIFICA_BI0 FOR VRH_BASE_TFILAQUALIFICA
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER procedure SP_ANONIMIZA
as
begin
end^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_ADMPREL_AI0 FOR VRH_EMP_TCOL_ADMPREL
ACTIVE AFTER INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_TINFO_DESC_SIMPLES_BIU0 FOR VRHF_TINFO_DESC_SIMPLES
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
END^


CREATE OR ALTER TRIGGER VRH_EMP_TCOL_ADMPREL_AU0 FOR VRH_EMP_TCOL_ADMPREL
ACTIVE AFTER UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_BD1 FOR VRH_EMP_TCOLCON
ACTIVE BEFORE DELETE POSITION 0
AS
begin
end^

CREATE OR ALTER procedure SP_TOMADOR_COM_ENDERECO
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDREFENTRADA integer,
    BDDATAENTRADA date,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
    BDDESCUF varchar(40))
as
BEGIN
   SUSPEND;
END^

create or alter procedure SP_VRHF_MOVIMENTACAO_COL (
    PRREFINI integer,
    PRREFFIM integer,
    PRCODEMP varchar(1000),
    PRLISTACOLS integer = 0,
    prOrdem integer = 0,
    PRCODCOL varchar(1000) = '',
    PRCODCLASSE integer = 0,
    PRCODFUNCAO integer = 0,
    PRCODSINDICATO integer = 0)
returns (
    BDCODEMP integer,
    BDNOMEMP varchar(100),
    BDCODMOV integer,
    BDDESC varchar(100),
    BDQTDADE integer,
    BDREF integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDNOMCTA varchar(100),
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDDESCTFUC varchar(40),
    BDSIGLAUF varchar(2))
as
BEGIN
  suspend;
END^

CREATE OR ALTER procedure SP_VRH_EMP_TCOLCON_CAD (
    PRWHERE varchar(10000))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDTPCOL varchar(20),
    BDREFCOL integer,
    BDCONTRCOL integer,
    BDNOMCOL varchar(70),
    BDNOMCOLUPPER varchar(70),
    BDCODPAISRES integer,
    BDCEPCOL varchar(9),
    BDLOGRCOL DM_LOGRADOURO,
    BDENDCOL DM_BDENDERECO,
    BDNUMCOL DM_NUMEND,
    BDCOMPLCOL DM_BDCOMPENDERECO,
    BDBAICOL DM_BDBAIRRO,
    BDCODCID integer,
    BDDDDCOL integer,
    BDFONECOL DM_BDTELEFONE,
    BDDDDCELCOL integer,
    BDCELCOL DM_BDTELEFONE,
    BDEMAILCOL DM_BDEMAIL,
    BDEMAIL2COL varchar(100),
    BDGRAUINSTCOL integer,
    BDESTCIVCOL integer,
    BDSEXOCOL integer,
    BDDATACHEBRASILCOL date,
    BDCASADOBR DM_BOOLEAN,
    BDFILHOSBR DM_BOOLEAN,
    BDCODCLE integer,
    BDTEMPORESIDENCIA integer,
    BDCONDICAOINGRESSO integer,
    BDCPFCOL varchar(14))
as
begin
  suspend;
end^

create or alter procedure SP_FICHA_REGISTROS_SALARIOS2 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRREF integer,
    PRRETORNAVAZIO integer,
    PRTRAZERSALINI integer,
    PRHISTTRANSF integer,
    PRSALARIOFUNCAO integer,
    PRMOSTRADTALTERACAO integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDDATAADMCOL date,
    BDSALINICOL numeric(18,6),
    BDDATACOL date,
    BDSALBASECOL numeric(18,6),
    BDCODMAS integer,
    BDDESCMAS varchar(50),
    BDCODTFUC integer,
    BDDESCTFUC varchar(40),
    BDCODSHE integer,
    BDDESCSHE varchar(50),
    BDSALBASEANT numeric(18,6),
    BDDATAEFEITO date,
    BDSALREDUZIDO DM_BOOLEAN,
    BDCODEMPORIG integer,
    BDCODCOLORIG integer,
    BDTIPOCOL integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_CONS_AUMSAL (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRCODACCONV integer = 0,
    PRCODMAS integer = 0,
    PRDETALHE integer = 2)
returns (
    BDDETALHE smallint,
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDDATAHAUM date,
    BDCODMAS integer,
    BDDESCMAS varchar(50),
    BDDATAEFEITOHAUM date,
    BDSALBASEHAUM numeric(18,6),
    BDSALBASEANTHAUM numeric(18,6),
    BDCODACCONV integer,
    BDDTEFACCONV date,
    BDCONVCOLETIVA DM_BOOLEAN,
    BDDSCACCONV varchar(255),
    BDDESCTPACCONV varchar(100),
    BDCODHAUM integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETPLANLANC (
    PRCODEMP integer,
    PRCODCOL integer,
    PRDATAINI date,
    PRDATAFIM date)
returns (
    BDCODVER integer,
    BDDATALANC date,
    BDREFLANC numeric(18,2),
    BDVALLANC numeric(18,2),
    BDREFCONGLANC DM_BOOLEAN,
    BDVALCONGLANC DM_BOOLEAN,
    BDORIGEMLANC integer,
    BDCOMPLANC integer,
    BDCODTIPO integer,
    BDZERAR DM_BOOLEAN)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETBASEIRFN (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer,
    PRCOMPETENCIA integer)
returns (
    BDREFFIR integer,
    BDREFIRFIR integer,
    BDTIPOCALCFIR integer,
    BDBASEIRFIR numeric(18,2),
    BDVALINSSFIR numeric(18,2),
    BDVALIRFIR numeric(18,2),
    BDDESCBASEIRFIR numeric(18,2),
    BDPREVPRIVFIR numeric(18,2),
    BDDATAFIR date,
    BDDATAPROC date,
    BDHORAPROC time)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETESTORNOFGTS13 (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDMES integer,
    BDREF integer,
    BDTIPO integer,
    BDVALORFGTS numeric(18,2),
    BDCODTPCC integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETAPURACAOTRANSPORTE (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDCODITI integer,
    BDCOMPETENCIA integer,
    BDQUANTIDADE integer,
    BDTPAPURACAO integer,
    BDVALITI DM_NUMERIC_18_3)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETAPURACAOREFEICAO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDCODCONVREF integer,
    BDCOMPETENCIA integer,
    BDQUANTIDADE integer,
    BDTPAPURACAO integer,
    BDPERIODO varchar(16),
    BDINICIOAPURACAO date,
    BDFINALAPURACAO date,
    BDVALUNI DM_NUMERIC_15_2)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETINTERMITENTEQH (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCONTRATOINTERMITENTE integer)
returns (
    BDCODCONTTI integer,
    BDDATADTI date,
    BDCODQHH integer,
    BDCODQHHS integer,
    BDQHHSENT time,
    BDQHHSSAI time)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETCONTRATOINTERMITENTE (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCONTRATOINTERMITENTE integer)
returns (
    BDCODCONTTI integer,
    BDDESCCONTRATOTI varchar(2000),
    BDDATACONVTI date,
    BDHORACONVTI time,
    BDCOMUNICCONVTI varchar(500),
    BDDATAINISERVTI date,
    BDDATAFIMSERVTI date,
    BDDATAPAGTI date,
    BDTIPOHORARIOTI integer,
    BDCODQHH integer,
    BDLOCALTI integer,
    BDCEPTI DM_CEP,
    BDLOGRTI DM_LOGRADOURO,
    BDENDTI DM_BDENDERECO,
    BDNUMENDTI DM_BDENDERECO_NR,
    BDCOMPLTI DM_BDCOMPENDERECO,
    BDBAITI DM_BDBAIRRO,
    BDCODCID integer,
    BDDIADESCANSO integer,
    BDDIACOMPENSADO integer,
    BDAPENASRESCISAO DM_BOOLEAN,
    BDCONVRESCTI DM_BOOLEAN,
    BDCODCONTESOCIAL varchar(30),
    BDLANCSITUACAO DM_BOOLEAN)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETCOOPARTDEPFORMULAS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer,
    PRPLANOSAUDE integer)
returns (
    BDTIPO integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREF integer,
    BDCODDPN integer,
    BDNOME DM_BDNOMCOL,
    BDCPF varchar(14),
    BDVALORMENSALIDADE numeric(18,2),
    BDVALORCOPAR numeric(18,2),
    BDCODTIPOCONV integer,
    BDTIPOFAIXA integer,
    BDCODTIPO integer,
    BDMENSFORMULA DM_BOOLEAN,
    BDCODVERTITMENS integer,
    BDCODVERTITCOP integer,
    BDCODVERDEPMENS integer,
    BDCODVERDEPCOP integer,
    BDRAZAOSOCIAL varchar(80))
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETRESCISAO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRULTDIA date,
    PRPREVIA smallint = 0,
    PRTODASATEFIMMES smallint = 0)
returns (
    BDTIPOMOV integer,
    BDDATARESCISAO date,
    BDDIASINDENIZADOS integer,
    BDDIASTRABALHADOS integer,
    BDDATANOTIF date,
    BDPROJECAOAVISO date,
    BDCODPRES integer,
    BDDATAAVPREVIO date,
    BDDATAHOM date,
    BDDATAPAGRESCISAO date,
    BDSALDOFGTS numeric(18,2),
    BDCALCFGTSMESANT DM_BOOLEAN,
    BDMAIORREMUNERACAO numeric(18,2),
    BDDATAPAGGRFC date,
    BDREPOSICAOVAGA DM_BOOLEAN,
    BDDISSIDIO DM_BOOLEAN,
    BDDATADISSIDIO date,
    BDDESCANSOINDENIZADO DM_BOOLEAN,
    BDREFRESCISAO integer,
    BDDISPAVPREVRESC DM_BOOLEAN,
    BDNOVOEMPRESC DM_BOOLEAN,
    BDPERTRCTRESC numeric(18,2),
    BDPERFGTSRESC numeric(18,2),
    BDREFPROJECAOAVISO integer,
    BDCODMFG integer,
    BDCODSAQUE integer,
    BDCODMRAIS integer,
    BDCODMCAG integer,
    BDDESCPRES varchar(110),
    BDINIPRES integer,
    BDJCPRES DM_BOOLEAN,
    BDAVPREPRES integer,
    BDGRRFPRES integer,
    BDESTPRES DM_BOOLEAN,
    BDINDFER13 DM_BOOLEAN,
    BDTERMCONTRPRES DM_BOOLEAN,
    BDMULTAPRES DM_BOOLEAN,
    BDDIASAVPREPRES integer,
    BDDIASPAGPRES integer,
    BDCODHNET integer,
    BDMULTA10PRES DM_BOOLEAN,
    BDPERCMULTAFGTS numeric(18,2),
    BDPERCMULTAFGTSCS numeric(18,2),
    BDCODMOTESRESC integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETFERIASREFERENCIA (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDREFFE integer,
    BDDIASFERFE numeric(18,6),
    BDDIASABOFE numeric(18,6),
    BDDIASSINDFE numeric(18,6),
    BDDIASLICFE numeric(18,6),
    BDBASEINSSRFE numeric(18,6),
    BDALIQINSSRFE numeric(18,6),
    BDVALORINSSRFE numeric(18,6),
    BDBASEIRRFE numeric(18,6),
    BDALIQIRRFE numeric(18,6),
    BDVALORIRRFE numeric(18,6),
    BDDIASFERDOBRFE numeric(18,6),
    BDDIASABODOBRFE numeric(18,6),
    BDBASEIROUTRFE numeric(18,6),
    BDVALORIROUTRFE numeric(18,6),
    BDDEPIRRFE numeric(18,6),
    BDBASEPISRFE numeric(18,6),
    BDBRATAPORFE numeric(18,6),
    BDBASEFGTSRFE numeric(18,6),
    BDVALORFGTSRFE numeric(18,6),
    BDBFGTS13RFE numeric(18,6),
    BDFGTS13RFE numeric(18,6),
    BDINIPERGOZOFE date,
    BDFIMPERGOZOFE date,
    BDREFPAGABOFE integer,
    BDDATAPAGFE date,
    BDFIMPERAQUISFE date)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETFERIAS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer,
    PRDATAPREVRESC date = null)
returns (
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDINIPERGOZOFE date,
    BDFIMPERAQUISFE date,
    BDFIMPERGOZOFE date,
    BDDATAPAGFE date,
    BDQTDGOZOFE numeric(15,2),
    BDQTDABONOFE numeric(15,2),
    BDSALDOINIFE numeric(18,6),
    BDSALDOFIMFE numeric(18,6),
    BDBASEIRFE numeric(18,6),
    BDALIQIRFE numeric(18,6),
    BDVALORIRFE numeric(18,6),
    BDBASEINSSFE numeric(18,6),
    BDALIQINSSFE numeric(18,6),
    BDVALORINSSFE numeric(18,6),
    BDDEPFE numeric(18,6),
    BDSALBASEFE numeric(18,6),
    BDSALBASEHEFE numeric(18,6),
    BDDATABAIXAFE date,
    BDCOLETIVASFE DM_BOOLEAN,
    BDREFPAGABOFE numeric(18,6),
    BDFALTASFE numeric(18,6),
    BDFERIADOSFE integer,
    BDVALSALMINVIGENTE numeric(18,6),
    BDMIGRACAO DM_BOOLEAN,
    BDPAGO DM_BOOLEAN,
    BDCALCA13FE DM_BOOLEAN,
    BDTEMPOSERVFE integer)
as
begin
  suspend;
end
^

create or alter procedure SP_VRHF_GETAFASTAMENTOS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCOMPETENCIA integer,
    PRSITEMPTRANSF smallint = 0,
    PRPREVIARESC smallint = 0,
    PRCALC13INTEGRALMP963 smallint = 0)
returns (
    BDTIPOSIT integer,
    BDCODSIT integer,
    BDDATAINISEFIP date,
    BDDATAINISIT date,
    BDDATAFIMSIT date,
    BDDIASSIT integer,
    BDNBENEFICIOSIT varchar(20),
    BDDATAPERICIASIT date,
    BDDATAPARTOSIT date,
    BDDESCSIT varchar(70),
    BDGRUPOSIT integer,
    BDCODVER integer,
    BDCODMFGENT integer,
    BDCODMFGSAI integer,
    BDCARENSIT integer,
    BDCODVER15DIAS integer,
    BDTIPOPERDESIT integer,
    BDSALFAMSIT DM_BOOLEAN,
    BDCODSEFENT varchar(5),
    BDCODSEFSAI varchar(5),
    BDRELSIT integer,
    BDINSSINTSIT DM_BOOLEAN,
    BDDIASATESTADO integer,
    BDNAOPRORROGAFERIAS DM_BOOLEAN,
    BDCOVID19 DM_BOOLEAN,
    BDSUSPENSAO DM_BOOLEAN,
    BDNAOALTPERAQUIMP936 DM_BOOLEAN,
    BDBENEFDEFERIDO DM_BOOLEAN,
    BDDATAINIATESTADOAUX date,
    BDDATAFIMATESTADOAUX date,
    BDDATAINIAFASTAUX date,
    BDDATAFIMAFASTAUX date,
    BDDIASPERDEPERAQUI integer,
    BDDIASATESTADOAUX integer,
    BDCODSITAUX integer,
    BDSUBGRUPOSIT integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETCACHEEMPMEDIAS (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDREF integer,
    BDREFHOREMP DM_BOOLEAN)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETMEDIAS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDCODVER integer,
    BDREF integer,
    BDTIPO integer,
    BDCC integer,
    BDVREF numeric(18,6),
    BDVREFAUX numeric(18,6),
    BDVVAL numeric(18,6))
as
BEGIN
  suspend;
END^

create or alter procedure SP_APAGAVERBA_CONFMEDIAS (
    PRCODVER integer,
    PRCLAVER varchar(20),
    PRTABELACONFFICHA varchar(300))
as
begin
end^

create or alter procedure SP_INSEREVERBA_CONFMEDIAS (
    PRCODVER integer,
    PRCLAVER varchar(20),
    PRTABELACONFFICHA varchar(300),
    PRTIPOFICHA smallint)
as
begin
end^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_OUT_AD0 FOR VRH_BASE_TCONF_FICHA_OUT
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_OUT_AI0 FOR VRH_BASE_TCONF_FICHA_OUT
ACTIVE AFTER INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_HN_AD0 FOR VRH_BASE_TCONF_FICHA_HN
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_HN_AI0 FOR VRH_BASE_TCONF_FICHA_HN
ACTIVE AFTER INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_RV_AD0 FOR VRH_BASE_TCONF_FICHA_RV
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_RV_AI0 FOR VRH_BASE_TCONF_FICHA_RV
ACTIVE AFTER INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_HE_AD0 FOR VRH_BASE_TCONF_FICHA_HE
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_HE_AI0 FOR VRH_BASE_TCONF_FICHA_HE
ACTIVE AFTER INSERT POSITION 0
AS
begin
end
^

create or alter procedure SP_VRHF_GETVERBASSIM (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCODSIND integer,
    PRPLANOFUNCAO integer,
    PRCODPRES integer,
    PRPLANOCUSTOS integer,
    PRULTDIA date)
returns (
    BDTIPOVS integer,
    BDCODVER integer,
    BDANOINI integer,
    BDMESINI integer,
    BDDIAINI integer,
    BDANOFIM integer,
    BDMESFIM integer,
    BDDIAFIM integer,
    BDFORMULAREFAUX varchar(800),
    BDFORMULAREF varchar(800),
    BDFORMULAVAL varchar(800),
    BDDATAINI DM_COMP_8,
    BDDATAFIM DM_COMP_8,
    BDCODSINTRAB integer,
    BDCODTFUC integer,
    BDCODPRES integer,
    BDCODTPCC integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETVERBASNAO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRPLANOCC integer,
    PRPLANOFUNCAO integer,
    PRCODSINDICATO integer,
    PRCODPRES integer,
    PRULTDIA date)
returns (
    BDTIPOVN integer,
    BDCODVER integer,
    BDANOINI integer,
    BDMESINI integer,
    BDDIAINI integer,
    BDANOFIM integer,
    BDMESFIM integer,
    BDDIAFIM integer,
    BDFORMULAREF varchar(2000),
    BDFERIASVN DM_BOOLEAN,
    BD13VN DM_BOOLEAN,
    BDDATAINI DM_COMP_8,
    BDDATAFIM DM_COMP_8,
    BDCODSINTRAB integer,
    BDCODTPCC integer,
    BDCODTFUC integer,
    BDCODPRES integer,
    BDFORMULAVAL varchar(10))
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETVERBASESPELHO (
    PRLISTATIPOCALCULO varchar(200) = null)
returns (
    BDCODCTP integer,
    BDCODCIT integer,
    BDCODVER integer,
    BDCODVERCVE integer,
    BDFORMULABASECVE DM_BOOLEAN,
    BDFORMCIT varchar(350),
    BDCLASSCIT varchar(20))
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETVERBAS (
    PRANOMES integer)
returns (
    BDCODVER integer,
    BDCLAVER varchar(20),
    BDAPEVER varchar(20),
    BDDESCVER varchar(40),
    BDDESCREDVER varchar(20),
    BDORDEMVER integer,
    BDINATIVAVER DM_BOOLEAN,
    BDSITVER integer,
    BDSITMATVER DM_BOOLEAN,
    BDSITDOEVER DM_BOOLEAN,
    BDSITACITRABVER DM_BOOLEAN,
    BDSITMILITARVER DM_BOOLEAN,
    BDSITMATEMPVER DM_BOOLEAN,
    BDSITACITRAB15VER DM_BOOLEAN,
    BDSITDOETRABVER DM_BOOLEAN,
    BDSITLICVENCVER DM_BOOLEAN,
    BDSITDOE15VER DM_BOOLEAN,
    BDSITSINDICALVER DM_BOOLEAN,
    BDSITAPOINVVER DM_BOOLEAN,
    BDSITOUTRASVER DM_BOOLEAN,
    BDNIVELVER smallint,
    BDCHAVE integer,
    BDTIPOCODVER integer,
    BDINSSVER integer,
    BDIRVER integer,
    BDFGTSVER integer,
    BDTIPOREFVER integer,
    BDBASESFVER integer,
    BDPISVER DM_BOOLEAN,
    BDBASEHEVER DM_BOOLEAN,
    BDBASEMAIORVER DM_BOOLEAN,
    BDRAISVER DM_BOOLEAN,
    BDBASEGPSVER DM_BOOLEAN,
    BDMENORESVER DM_BOOLEAN,
    BDPROPVER DM_BOOLEAN,
    BDBASEVTVER DM_BOOLEAN,
    BDREEMBGPSVER DM_BOOLEAN,
    BDHEVER DM_NUMERIC_15_2,
    BDGRAVAFICHAHNVER DM_BOOLEAN,
    BDCCPRINCIPALVER DM_BOOLEAN,
    BDFORMREFVER varchar(5000),
    BDFORMVALVER varchar(5000),
    BDBASEDSRHEVER DM_BOOLEAN,
    BDBASEDSRRVVER DM_BOOLEAN,
    BDREFVER integer,
    BDFORMREFAUXVER varchar(5000),
    BDDEDFORMREFAUXVER DM_BOOLEAN,
    BDDEDFORMREFVER DM_BOOLEAN,
    BDGARANTIAMINVER DM_BOOLEAN,
    BDDEDFORMVALVER DM_BOOLEAN,
    BDRENDISENTOIRVER DM_BOOLEAN,
    BDFORMINTVER varchar(5000),
    BDPAGAESTOUROVER DM_BOOLEAN,
    BDNAOCONVHORASVER DM_BOOLEAN,
    BDBASEDSRHNVER DM_BOOLEAN,
    BDBASEDSROUVER DM_BOOLEAN,
    BDREMINTERMVER DM_BOOLEAN)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETTABSALFAM (
    PRANOMES integer)
returns (
    BDREFSF integer,
    BDBASESF DM_NUMERIC_15_2,
    BDVALSF DM_NUMERIC_15_2,
    BDORDEM integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETTABELAIR (
    PRCODIR integer,
    PRTIPOCALCIR integer,
    PRANOMES integer,
    PRANOMESSEGUINTE integer,
    PRCODTCA integer = 0)
returns (
    BDTIPOTABIR integer,
    BDREFIR integer,
    BDVALDEPIR DM_NUMERIC_15_2,
    BDDESCMINIR DM_NUMERIC_15_2,
    BDTIPOCALCFIR integer,
    BDCODTCA integer,
    BDORDEMIR integer,
    BDFAIXAIR DM_NUMERIC_15_2,
    BDALIQIR DM_NUMERIC_15_2,
    BDPARCDEDIR DM_NUMERIC_15_2,
    BDDESCONTOSIMPLIFICADO DM_NUMERIC_15_2)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETTABELAINSS (
    PRTABINSS integer,
    PRANOMES integer)
returns (
    BDMINGPSINSS DM_NUMERIC_15_2,
    BDORDEM integer,
    BDFAIXAINSS DM_NUMERIC_15_2,
    BDALIQINSS DM_NUMERIC_15_2,
    BDPARCELADEDUZIR DM_NUMERIC_15_2)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETSINDICATO (
    PRCODSINTRAB integer,
    PRANOMES integer)
returns (
    BDCODSINTRAB integer,
    BDDESCSINTRAB DM_BDDESCSINTRAB,
    BDMEDSITSINTRAB DM_BOOLEAN,
    BDMESESMEDSITSINTRAB integer,
    BDREFST integer,
    BDVERFERIST integer,
    BDVERMULRESST integer,
    BDCODPMS integer,
    BDPERABFERST DM_NUMERIC_15_2,
    BDDATBASEST integer,
    BDESTABST integer,
    BDPERCNOTST DM_NUMERIC_15_2,
    BDMESCSST integer,
    BDFERRESCST integer,
    BDFERDOBST integer,
    BDFERJCST integer,
    BDTIPODESCCONTRST integer,
    BDBASEADICST DM_NUMERIC_15_2,
    BDLIMITE13ST integer,
    BDPISOSAL DM_NUMERIC_15_2,
    BDSALMINGAR DM_NUMERIC_15_2,
    BDMESTXASST integer,
    BDTIPODESCTXASST integer,
    BDMESRESCMEDIASST DM_BOOLEAN,
    BDTIPOMESRESCMEDIASST integer,
    BDINIHORANOTST time,
    BDFIMHORANOTST time,
    BDLIMINARAVPREVST integer,
    BDQTDDIASANTPAG integer,
    BDINATIVO DM_BOOLEAN)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETSINDICALANO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDTIPOPGTOSIND integer,
    BDREFSIND integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETREFEICAO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDCODCONVREF integer,
    BDDIASEMCONVREF integer,
    BDREFCONVREF integer,
    BDQTDCONVREF integer,
    BDVALUNI DM_NUMERIC_15_2)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETREDUCAOSALARIAL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRDTINI date,
    PRDTFIM date)
returns (
    BDCODREDSAL integer,
    BDDATAINIREDSAL date,
    BDDATAFIMREDSAL date,
    BDCODMAS integer,
    BDPERCREDSAL DM_NUMERIC_15_2,
    BDREDSAL DM_BOOLEAN,
    BDREDJOR DM_BOOLEAN,
    BDMESREDSAL DM_NUMERIC_15_2,
    BDSEMREDSAL DM_NUMERIC_15_2,
    BDDIAREDSAL DM_NUMERIC_15_2,
    BDSALBASEREDUZIDO DM_NUMERIC_15_2,
    BDQTDDIASREDSAL integer,
    BDDIASACORDOINI integer,
    BDREFINIREDSAL integer,
    BDREFFIMREDSAL integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETPERIODOSFERIAS (
    PRCODEMP integer,
    PRCODCOL integer)
returns (
    BDINIPERAQUISFE date,
    BDFIMPERAQUISFE date,
    BDCODFE integer,
    BDINIPERGOZOFE date,
    BDFIMPERGOZOFE date,
    BDDATAPAGFE date,
    BDQTDGOZOFE numeric(18,6),
    BDQTDABONOFE numeric(18,6),
    BDSALDOINIFE numeric(18,6),
    BDSALDOFIMFE numeric(18,6),
    BDBASEIRFE numeric(18,6),
    BDALIQIRFE numeric(18,6),
    BDVALORIRFE numeric(18,6),
    BDBASEINSSFE numeric(18,6),
    BDALIQINSSFE numeric(18,6),
    BDVALORINSSFE numeric(18,6),
    BDDEPFE numeric(18,6),
    BDSALBASEFE numeric(18,6),
    BDSALBASEHEFE numeric(18,6),
    BDDATABAIXAFE date,
    BDCOLETIVASFE DM_BOOLEAN,
    BDREFPAGABOFE integer,
    BDBASEFGTSFE numeric(18,6),
    BDVALORFGTSFE numeric(18,6),
    BDVALORFGTSCSFE numeric(18,6),
    BDMAIORREMFE numeric(18,6),
    BDBSALFAMFE numeric(18,6),
    BDSALFAMFE numeric(18,6),
    BDCOMPETENCIAFE varchar(7),
    BDFALTASFE numeric(18,6),
    BDFERIADOSFE integer,
    BDBASEIROUTFE numeric(18,6),
    BDVALORIROUTFE numeric(18,6),
    BDDEPIROUTFE numeric(18,6),
    BDESTPROVFE numeric(18,6),
    BDBASEPISFE numeric(18,6),
    BDBRATAPOFE numeric(18,6),
    BDCREDITOFE numeric(18,6),
    BDDEBITOFE numeric(18,6),
    BDLIQUIDO numeric(18,6),
    BDREFINIFE integer,
    BDREFFIMFE integer,
    BDCALCA13FE DM_BOOLEAN,
    BDTIPOA13FE integer,
    BDPERCA13FE numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDDATAPROCFE date,
    BDHORAPROCFE time,
    BDORDEM integer,
    BDDATAAVISO date,
    BDSALDOFINALSINDFE numeric(18,6),
    BDDIASLICFE numeric(18,6),
    BDTEMPOSERVFE integer,
    BDVALSALMINVIGENTE numeric(18,6),
    BDENVIOUESOCIAL DM_BOOLEAN,
    BDENVIOUPGTOESOCIAL DM_BOOLEAN,
    BDIDDEMONSTRATIVO varchar(30),
    BDFOLHAAUTOMATICA DM_BOOLEAN,
    BDRECIBOESOCIAL varchar(30),
    BDCODEVT integer,
    BDCODEVTFIM integer,
    BDREFPAGFE integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETITINERARIO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDCODITI integer,
    BDDIASEMITF integer,
    BDREFITF integer,
    BDHORARIOITF time,
    BDQTDITF integer,
    BDVALITI DM_NUMERIC_15_2)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETINSSMULTVINC (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDDATATRF date,
    BDBINSS DM_NUMERIC_15_2,
    BDBINSSFEFOL DM_NUMERIC_15_2,
    BDINSSFEFOL DM_NUMERIC_15_2,
    BDINSS DM_NUMERIC_15_2,
    BDBIRRF DM_NUMERIC_15_2,
    BDIRRF DM_NUMERIC_15_2,
    BDDEP DM_NUMERIC_15_2,
    BDBINSS13 DM_NUMERIC_15_2,
    BDINSS13 DM_NUMERIC_15_2,
    BDCODPTRAN integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETHORARIOCOL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRULTDIA date)
returns (
    BDDATACOL date,
    BDDIASEMQH integer,
    BDTIPODSR integer,
    BDCODQHH integer,
    BDDESQHH varchar(50),
    BDCODQHHS integer,
    BDQHHSENT time,
    BDQHHSSAI time,
    BDHORFLEXIVEL integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETFUNCOESCOL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRDATAULTDIA date)
returns (
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDDATAINI date,
    BDDATAFIM date)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETFERIASSEMUMTERCORESC (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer,
    PRPREVIARESCISAO smallint = 0)
returns (
    BDTIPOFER integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDCODVER integer,
    BDREFAUXVFE DM_NUMERIC_15_2,
    BDREFVFE DM_NUMERIC_15_2,
    BDVALVFE DM_NUMERIC_15_2,
    BDVALIFE DM_NUMERIC_15_2,
    BDIGNREFAVFE DM_BOOLEAN,
    BDIGNREFVFE DM_BOOLEAN,
    BDIGNVALVFE DM_BOOLEAN,
    BDORVERBAFE integer,
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDCLAVER varchar(20))
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETFAIXASSAUDE (
    PRPLANOSAUDE integer,
    PRANOMES integer)
returns (
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDORDEM integer,
    BDIDADE integer,
    BDVALOR DM_NUMERIC_15_2)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETESTABILIDADE (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCODSINTRAB integer,
    PRANOMES integer,
    PRDATARESC date = null,
    PRPREVIADEDESCISAO smallint = 0)
returns (
    BDDATAETB date,
    BDDIASETB integer,
    BDGRUPOSITETB integer,
    BDCODVER integer,
    BDTIPOETB integer,
    BDDIASFERETB DM_BOOLEAN)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETFERIADOS (
    PRCODEMP integer,
    PRANOMESINI integer,
    PRANOMESFIM integer,
    PRFERIADOSBANCARIOS smallint = 0)
returns (
    BDCODUF integer,
    BDCODCID integer,
    BDDESCFERI varchar(50),
    BDMESDIAFERI varchar(4),
    BDCODSINTRAB integer,
    BDCODFERI integer,
    BDFERIBANC DM_BOOLEAN,
    BDDATAFERI date,
    BDDATAFER date,
    BDREFFER integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETCACHEANUAL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANO integer)
returns (
    BDREF integer,
    BDCATEGORIACOL integer,
    BDCATEGORIAESOCIAL integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETCOLABCONTR (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCOMPETENCIA integer,
    PRDATAULTIMODIAMES date)
returns (
    BDCODEMP integer,
    BDEXPINIESOCIAL DM_BOOLEAN,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDSALBASECOL DM_NUMERIC_15_2,
    BDFORMAPAGTOCOL integer,
    BDNRODEPIRCOL integer,
    BDBASEIRRFADCOL DM_NUMERIC_15_2,
    BDVALORPREVPRIVNCOL DM_NUMERIC_15_2,
    BDVALORPREVPRIV13COL DM_NUMERIC_15_2,
    BDCATEGORIACOL integer,
    BDCATEGORIAESOCIAL integer,
    BDPERCFGTSCOL DM_NUMERIC_15_2,
    BDOCORRENCIACOL integer,
    BDPERCRATCOL DM_NUMERIC_15_2,
    BDPERCDESCFPASCOL DM_NUMERIC_15_2,
    BDSEXOCOL integer,
    BDDATANASCCOL date,
    BDDATACADCOL date,
    BDDATAADMCOL date,
    BDDATAADICCOL date,
    BDESTCIVCOL integer,
    BDGRAUINSTCOL integer,
    BDCONTRCOL integer,
    BDGRUPOCLA integer,
    BDCODSINTRAB integer,
    BDTIPOCOL integer,
    BDHORASMENSAISCOL numeric(15,4),
    BDHORASSEMANAISCOL numeric(15,4),
    BDHORASDIARIASCOL numeric(15,4),
    BDPERCADISAL DM_NUMERIC_15_2,
    BDPERCINSALUBCOL DM_NUMERIC_15_2,
    BDINCIDINSALUBCOL integer,
    BDPERCPERCULCOL DM_NUMERIC_15_2,
    BDINCIDPERICULCOL integer,
    BDPERCNOTURNOCOL DM_NUMERIC_15_2,
    BDINCIDNOTURNOCOL integer,
    BDNRODEPSALFAMCOL integer,
    BDIGNORAFALTASFERCOL DM_BOOLEAN,
    BDCALCADIANTACOL DM_BOOLEAN,
    BDNAOARREDONDARCOL DM_BOOLEAN,
    BDIMPETIQUETACOL DM_BOOLEAN,
    BDCALCDSRRVCOL DM_BOOLEAN,
    BDCALCDSRHECOL DM_BOOLEAN,
    BDCALCDSRSALCOL DM_BOOLEAN,
    BDCALCVALTRANSCOL DM_BOOLEAN,
    BDCALCVALREFCOL DM_BOOLEAN,
    BDFICHAREGCOL varchar(12),
    BDTIPOADMCOL integer,
    BDNATUOCUPCOL integer,
    BDDATAINIAQUICOL date,
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDCODCBO integer,
    BDCODQH integer,
    BDDESCTFUC varchar(40),
    BDSALINICOL DM_NUMERIC_15_2,
    BDDIASPRAZO1COL integer,
    BDDATAFIMPRAZO1COL date,
    BDDIASPRAZO2COL integer,
    BDDATAFIMPRAZO2COL date,
    BDDESCCONTSINCOL DM_BOOLEAN,
    BDVINCEMPCOL integer,
    BDALVARACOL DM_BOOLEAN,
    BDSINDICALIZADOCOL DM_BOOLEAN,
    BDREGIMEPARCIALCOL DM_BOOLEAN,
    BDDESCCONTASSCOL DM_BOOLEAN,
    BDDATATRF date,
    BDDATAALTSAL date,
    BDSITEMP DM_BOOLEAN,
    BDINATIVO DM_BOOLEAN,
    BDPERCGORJ DM_NUMERIC_15_2,
    BDCODEMPRHNET integer,
    BDCODMULTVINC integer,
    BDCODPTRAN integer,
    BDDATACALC date,
    BDCODCENTROS integer,
    BDCODPQUA integer,
    BDCALCC13NAFNEMP DM_BOOLEAN,
    BDREFADMCOL integer)
as
declare variable WUSANOMESOCIAL DM_BOOLEAN;
declare variable WSIMPLES integer;
declare variable WDATA1 date;
declare variable WDATA2 date;
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETDEPENDENTE (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDCODDPN integer,
    BDREFDPN integer,
    BDNOMEDPN DM_BDNOMDPN,
    BDPARENESCODPN integer,
    BDDATANASCDPN date,
    BDCPFDPN varchar(14),
    BDINVALIDODPN DM_BOOLEAN,
    BDCONVMEDDPN DM_BOOLEAN,
    BDSALFAMDPN DM_BOOLEAN,
    BDDEPIRDPN DM_BOOLEAN,
    BDCODCID integer,
    BDCARTDPN varchar(20),
    BDREGDPN integer,
    BDLIVDPN varchar(10),
    BDFOLDPN varchar(10),
    BDDATAENTREDPN date,
    BDDATABAUXADPN date,
    BDDPN integer,
    BDREFIRDPN integer,
    BDMATRICULADPN varchar(200),
    BDCODTIPO integer,
    BDTIPODEPESOCIAL integer,
    BDUNIVERSITARIO varchar(35),
    BDIDRHNET integer,
    BDSTATUS_ES integer,
    BDDATA_ES date)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETDEPPENSAO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer,
    PRTIPOSCALC varchar(100))
returns (
    BDCODDPN integer,
    BDREFDEPP integer,
    BDCODCTP integer,
    BDCODVER integer,
    BDFORMREFDEPP varchar(1000),
    BDFORMREFAUXDEPP varchar(1000),
    BDFORMVALDEPP varchar(1000),
    BDNOMBENEF varchar(70),
    BDFIMBENEF integer,
    BDDEDREFAUXDEPP DM_BOOLEAN,
    BDDEDREFDEPP DM_BOOLEAN,
    BDDEDVALDEPP DM_BOOLEAN,
    BDPERCDEPP DM_NUMERIC_15_2,
    BDPERCDEPPTOT DM_NUMERIC_15_2)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_GETEMPRESA (
    PRCODEMP integer,
    PRANOMES integer)
returns (
    BDCODEMP integer,
    BDREFEMP integer,
    BDPAGEMP integer,
    BDFECHAMESEMP integer,
    BDFECHAVTEMP integer,
    BDARREMP integer,
    BDTIPOARREMP integer,
    BDTIPOFEREMP integer,
    BDSOMSALFEREMP DM_BOOLEAN,
    BDTIPOAD13EMP integer,
    BDSOMSALAD13EMP DM_BOOLEAN,
    BDPERCADSALEMP DM_NUMERIC_15_2,
    BDREFHOREMP DM_BOOLEAN,
    BDLICREMFEREMP DM_BOOLEAN,
    BDESTOUROEMP DM_BOOLEAN,
    BDESTOURORESEMP DM_BOOLEAN,
    BDFALFEREMP DM_BOOLEAN,
    BDFALHORFEREMP DM_BOOLEAN,
    BDDEPIRRESCEMP DM_BOOLEAN,
    BDCODSINPAT integer,
    BDCAPSOCEMP DM_NUMERIC_15_2,
    BDTAXSEREMP DM_NUMERIC_15_2,
    BDPROPADMEMP integer,
    BDPROPRESEMP integer,
    BDPROPFEREMP integer,
    BDPROPSITEMP integer,
    BDCALCMEDIASTEMP integer,
    BDMESDSREMP integer,
    BDNATESTEMP integer,
    BDDATABASEEMP integer,
    BDPATEMP DM_BOOLEAN,
    BDNROPROPEMP integer,
    BDSERPROPRIOPATEMP integer,
    BDPATREFCONVENIOEMP integer,
    BDPATCESTAALIMENTOEMP integer,
    BDPATADMCOZINHAEMP integer,
    BDPATREFTRANSPEMP integer,
    BDPATALICONVENIOEMP integer,
    BDSINDICALIZEMP DM_BOOLEAN,
    BDCODIR integer,
    BDCODINSS integer,
    BDCODMEN integer,
    BDCALCFCNAFNEMP DM_BOOLEAN,
    BDCALCC13NAFNEMP DM_BOOLEAN,
    BDPERTERC DM_NUMERIC_17_4,
    BDCODFPAS integer,
    BDPROPTOMEMP integer,
    BDANOSAVPREVIOIND integer,
    BDCODPLACONVSAU integer,
    BDDIASTRABADI integer,
    BDCODCENTROS integer,
    BDCODPLAFUC integer,
    BDCODUF integer,
    BDCODCID integer,
    BDTIPCALCFERCOLINF integer,
    BDTIPCALCFERCOLSUP integer,
    BDLIMINARAVPREVEMP integer,
    BDARREDONDAFN DM_BOOLEAN,
    BDARREDONDAFC DM_BOOLEAN,
    BDARREDONDAFE DM_BOOLEAN,
    BDARREDONDAA13 DM_BOOLEAN,
    BDARREDONDA13 DM_BOOLEAN,
    BDARREDONDAC13 DM_BOOLEAN,
    BDARREDONDAAD DM_BOOLEAN,
    BDARREDONDAAU DM_BOOLEAN,
    BDARREDONDAFA DM_BOOLEAN,
    BDARREDONDAFTINT DM_BOOLEAN,
    BDPAGEMPCONTR integer,
    BDDESCFALHORASDIAS DM_BOOLEAN,
    BDPERCLIMIDESCPAR DM_NUMERIC_15_2,
    BDCNPJEMP DM_CNPJ_CPF,
    BDOPCAOESOCIAL integer,
    BDCODNATJUR integer,
    BDCODMATRIZ integer,
    BDCODCLATRI integer,
    BDCALCC13FNNEGEMP DM_BOOLEAN,
    BDCATSEFIPEMP integer,
    BDDSRMEDATUSAL DM_BOOLEAN,
    BDIDADESAUDEEMP DM_BOOLEAN,
    BDCONTABILIZASCP DM_BOOLEAN,
    BDDESCCOMPL13NEG DM_BOOLEAN,
    BDDATAINITABELA date,
    BDDATAININAOPERIOD date,
    BDDATAINIPERIOD date,
    BDDATAINISST date,
    BDREFINITABELA integer,
    BDREFININAOPERIOD integer,
    BDREFINIPERIOD integer,
    BDREFINISST integer,
    BDGRUPO integer,
    BDREFINIDCTFWEB integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRH_EXP_DADOS_DA_FOLHA_SQL (
    PRCODEMP varchar(2000),
    PRCODCOL varchar(2000),
    PRCODSINDICATO varchar(1000),
    PRCODCLASSE varchar(1000),
    PRCOMPETENCIA integer,
    PRMODELO integer,
    PRTIPOFOLHA integer)
returns (
    BDSQL varchar(30000))
as
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(10000);
declare variable WORDERBY varchar(100);
declare variable WCOMPETENCIA varchar(10);
declare variable WCAMPOFILTROREF varchar(20);
declare variable WCAMPOVALV varchar(20);
declare variable WJOINTABELACALCVERBA varchar(10000);
declare variable WTABELACALC varchar(100);
declare variable WTABELAVERBA varchar(100);
declare variable WJOINAUX varchar(10000);
declare variable WTABELATOL varchar(50);
declare variable WJOINAUXTOL varchar(3000);
declare variable WTABELAPROV varchar(50);
declare variable WTABELATOLPROV varchar(50);
declare variable WJOINPROV varchar(10000);
declare variable WCALCFN varchar(50);
declare variable WCALCFT varchar(50);
declare variable WCALCFI varchar(50);
declare variable WCALCFTI varchar(50);
declare variable WVERBAFN varchar(50);
declare variable WVERBAFT varchar(50);
declare variable WVERBAFI varchar(50);
declare variable WVERBAFTI varchar(50);
declare variable WTOLFN varchar(50);
declare variable WTOLFT varchar(50);
declare variable WTOLFI varchar(50);
declare variable WTOLFTI varchar(50);
declare variable WCODCOLAUX varchar(1000);
declare variable WSQLIMPOSTOS varchar(10000);
declare variable WANO integer;
declare variable WDIA integer;
declare variable WMES integer;
declare variable WULTDIACOMP date;
declare variable WPRIDIACOMP date;
declare variable WCAMPOSIMPOSTOS varchar(10000);
declare variable WCAMPOSVALGPS varchar(4000);
declare variable WCAMPOSVALRAT varchar(4000);
declare variable WCAMPOSVALRATAPO varchar(4000);
declare variable WCAMPOSVALFPAS varchar(4000);
declare variable WTABELATOLCALC varchar(50);
declare variable WTOLCALCFN varchar(50);
declare variable WTOLCALCFT varchar(50);
declare variable WTOLCALCFI varchar(50);
declare variable WTOLCALCFTI varchar(50);
declare variable WCAMPOVALFGTS varchar(20);
declare variable WTABELATOLFGTS varchar(50);
declare variable WTOLFGTSFN varchar(50);
declare variable WTOLFGTSFT varchar(50);
declare variable WTOLFGTSFI varchar(50);
declare variable WTOLFGTSFTI varchar(50);
BEGIN
  suspend;
end^  

create or alter procedure SP_VRH_EXP_DADOS_DA_FOLHA (
    PRCODEMP varchar(2000),
    PRCODCOL varchar(2000),
    PRCODSINDICATO varchar(1000),
    PRCODCLASSE varchar(1000),
    PRCOMPETENCIA integer,
    PRMODELO integer,
    PRTIPOFOLHA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMECOL varchar(100),
    BDPERIODO varchar(10),
    BDFUNCAO varchar(100),
    BDCENTROCUSTO varchar(100),
    BDSALBASE numeric(15,2),
    BDDTADM date,
    BDCODVERBA integer,
    BDDESCVERBA varchar(200),
    BDTIPOREFVER integer,
    BDREFV numeric(15,2),
    BDREFVERBA varchar(20),
    BDREFVERBA2 varchar(100),
    BDREFVERBAPROV varchar(100),
    BDVALOR numeric(15,2),
    BDCONTADEB varchar(100),
    BDCONTACRE varchar(100),
    BDMODELOREL integer)
as
declare variable WSQL varchar(32000);
declare variable WCODCOLANT integer;
declare variable WCODTPLADEB integer;
declare variable WCTALONDEB varchar(100);
declare variable WNOMCTADEB varchar(100);
declare variable WCODTPLACRE integer;
declare variable WCTALONCRE varchar(100);
declare variable WNOMCTACRE varchar(100);
declare variable WREFP integer;
declare variable WFERIAS numeric(15,2);
declare variable WUMTERCO numeric(15,2);
declare variable W13SAL numeric(15,2);
declare variable WFGTS numeric(15,2);
declare variable WINSS numeric(15,2);
declare variable WFPAS numeric(15,2);
declare variable WCNAE numeric(15,2);
declare variable WRATAPO numeric(15,2);
declare variable WPIS numeric(15,2);
declare variable WLINHA integer;
declare variable WDESCLINHAPROVAUX varchar(100);
declare variable WDEBAUX varchar(100);
declare variable WCREDAUX varchar(100);
declare variable WANO integer;
declare variable WDIA integer;
declare variable WMES integer;
declare variable WULTDIACOMP date;
declare variable WCODCENTRO integer;
declare variable WCODTPCC integer;
declare variable WVALGPS numeric(15,2);
declare variable WVALRAT numeric(15,2);
declare variable WVALRATAPO numeric(15,2);
declare variable WVALFPAS numeric(15,2);
declare variable WCODTPCCCOL varchar(100);
declare variable WORDEMVER integer;
declare variable WCODCOLAUX integer;
declare variable WCODTPCCAUX integer;
declare variable WCODEMPAUX integer;
declare variable wTemCalc boolean;
declare variable wEhPBM boolean;
declare variable wDescVerbaAux varchar(100);
BEGIN
  suspend;
end^

CREATE OR ALTER TRIGGER VRHM_EMP_COPAR_COL_BI0 FOR VRHM_EMP_COPAR_COL
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VRH_RHNET_TTIPO_ARQ_BI0 FOR VRH_RHNET_TTIPO_ARQ
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHM_EMP_COPAR_COL_BU0 FOR VRHM_EMP_COPAR_COL
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VRHM_EMP_COPAR_DEP_BI0 FOR VRHM_EMP_COPAR_DEP
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VRHM_EMP_COPAR_DEP_BU0 FOR VRHM_EMP_COPAR_DEP
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end^

CREATE OR ALTER procedure SP_SELECT_POSTERIORES_AUDITOR (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODSINTRAB integer,
    BDINIHORANOTST time,
    BDFIMHORANOTST time,
    BDDATBASEST integer,
    BDDATACOL date)
as
declare variable WINIHORANOT time;
declare variable WINIHORANOT_ANT time;
declare variable WFIMHORANOT time;
declare variable WFIMHORANOT_ANT time;
declare variable WDATBASE integer;
declare variable WDATBASE_ANT integer;
declare variable WSQL varchar(30000);
declare variable WINICIOU boolean = false;
declare variable WCODSIND integer;
declare variable WCODSIND_ANT integer;
begin
  suspend;
end^

CREATE OR ALTER procedure SP_VRH_RELATORIOPLANOSAUDE_NOVO (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRCOMPETENCIA integer,
    PRCODTIPOCONV varchar(15000),
    PRSITUACAO integer,
    PRORDERBY varchar(30))
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDNOMEMP varchar(100),
    BDCODCOL integer,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDCODDPN integer,
    BDNOMDEP varchar(70),
    BDPARENTESCO varchar(500),
    BDDATANASC date,
    BDCPF varchar(14),
    BDDATAADMCOL varchar(10),
    BDDESCTFUC varchar(40),
    BDREFINI integer,
    BDREFFIM integer,
    BDCOPARTICIPACAO numeric(18,6),
    BDMENSALIDADE numeric(18,6),
    BDIDADE integer,
    BDVALORFAIXA numeric(18,6),
    BDREF integer,
    BDCODOPERADORA integer,
    BDOPERADORA varchar(200),
    BDCODCONVENIO integer,
    BDCONVENIO varchar(80),
    BDCODPLAN integer,
    BDPLANO varchar(200),
    BDCODTIPOCONV integer,
    BDTIPOCONVENIO varchar(200),
    BDCNPJ varchar(18),
    BDREGISTROANS integer)
as
declare variable WUMAEMP integer;
declare variable WSQL varchar(30000);
declare variable WDIA varchar(10);
declare variable WMES varchar(10);
declare variable WANO varchar(10);
declare variable WPRIDIA varchar(10);
declare variable WULTDIA varchar(10);
declare variable WPRCOL varchar(30000);
declare variable WPREMP varchar(30000);
begin
  suspend;
end^

CREATE OR ALTER procedure SP_VRH_SELECT_CALCULO13AD (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer,
    PRPROVISAO DM_BOOLEAN,
    PRAPENASTRANS DM_BOOLEAN = 'FALSE')
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFA13 integer,
    BDCODVER integer,
    BDREFVA13 numeric(15,6),
    BDREFAUXVA13 numeric(15,6),
    BDVALVA13 numeric(15,6),
    BDPERCA13 numeric(15,6),
    BDVALA13 numeric(15,6),
    BDTIPOPROPA13 integer,
    BDMESESPROPA13 integer,
    BDBASEIRA13 numeric(15,6),
    BDFGTSA13 numeric(15,6),
    BDFGTSCSA13 numeric(15,6),
    BDBASEFGTSA13 numeric(15,6),
    BDDATABAIXAA13 date,
    BDREFBAIXAA13 integer,
    BDPERCIRA13 numeric(15,6),
    BDVALORIRA13 numeric(15,6),
    BDBSALFAMA13 numeric(15,6),
    BDSALFAMA13 numeric(15,6),
    BDBRAISA13 numeric(15,6),
    BDDEPA13 numeric(15,6),
    BDSALBASEA13 numeric(15,6),
    BDARREPROVA13 numeric(15,6),
    BDARREDESCA13 numeric(15,6),
    BDANOA13 integer,
    BDESTPROVA13 numeric(15,6),
    BDBASEPISA13 numeric(15,6),
    BDCLAVER varchar(20),
    BDINSSVER integer,
    BDFGTSVER integer,
    BDIRVER integer)
as
declare variable WSQL varchar(30000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WSQL1 varchar(30000);
declare variable WSQL2 varchar(10000);
declare variable WWHERE varchar(1000);
begin
  suspend;
end^

create or alter procedure SP_TEMCPFCADASTRADO (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRCPF varchar(14))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDTPCOL varchar(20),
    BDNOMEMP DM_BDNOMEMP)
as
begin
  suspend;
end^

CREATE OR ALTER procedure SP_VRH_ALERTA_VENCIMENTOS (
    PRDATA varchar(10),
    PRCODPLANO integer = 0)
returns (
    BDCODEMP integer,
    BDCOLCON integer,
    BDTIPOALERTA integer,
    BDDATAVENC date,
    BDCAMINHO varchar(255),
    BDDESCRICAO varchar(680),
    BDCADASTRO integer,
    BDCHAVECAD varchar(50),
    BDCAMPO varchar(30),
    BDTIPO integer,
    BDFERIASPRIMEIROVENC DM_BOOLEAN,
    BDDIASFERIASPRIMEIROVENC integer,
    BDFERIASSEGUNDOVENC DM_BOOLEAN,
    BDDIASFERIASSEGUNDOVENC integer)
as
declare variable WSQL varchar(30000);
declare variable WCODPAV integer;
declare variable WDESCRICAOPAV varchar(65);
declare variable WASOSPERIODICOS DM_BOOLEAN;
declare variable WDIASASOSPERIODICOS integer;
declare variable WCONTRATODETERMINADO DM_BOOLEAN;
declare variable WDIASCONTRATODETERMINADO integer;
declare variable WCONTRATOEXPERIENCIAPRI DM_BOOLEAN;
declare variable WDIASCONTRATOEXPERIENCIAPRI integer;
declare variable WCONTRATOEXPERIENCIASEG DM_BOOLEAN;
declare variable WDIASCONTRATOEXPERIENCIASEG integer;
declare variable WCONTRATOAPRENDIZ DM_BOOLEAN;
declare variable WDIASCONTRATOAPRENDIZ integer;
declare variable WCONTRATOESTAGIO DM_BOOLEAN;
declare variable WDIASCONTRATOESTAGIO integer;
declare variable WATESTADOESCOLADEP DM_BOOLEAN;
declare variable WDIASATESTADOESCOLADEP integer;
declare variable WCNHCOLCON DM_BOOLEAN;
declare variable WDIASCNHCOLCON integer;
declare variable WCNHMOTORISTA DM_BOOLEAN;
declare variable WDIASCNHMOTORISTA integer;
declare variable WCARTAOVACINADEP DM_BOOLEAN;
declare variable WDIASCARTAOVACINADEP integer;
declare variable WAFASTAMENTOESTABILIDADE DM_BOOLEAN;
declare variable WDIASAFASTAMENTOESTABILIDADE integer;
declare variable WANIVERSARIANTES DM_BOOLEAN;
declare variable WDIASANIVERSARIANTES integer;
declare variable WANIVERSARIOEMPRESA DM_BOOLEAN;
declare variable WDIASANIVERSARIOEMPRESA integer;
declare variable WAVISOPREVIO DM_BOOLEAN;
declare variable WDIASAVISOPREVIO integer;
declare variable WCERTIFICADODIGITAL DM_BOOLEAN;
declare variable WDIASCERTIFICADODIGITAL integer;
declare variable WDISSIDIOCOLETIVO DM_BOOLEAN;
declare variable WDIASDISSIDIOCOLETIVO integer;
declare variable WFERIASPRIMEIROVENC DM_BOOLEAN;
declare variable WDIASFERIASPRIMEIROVENC integer;
declare variable WFERIASSEGUNDOVENC DM_BOOLEAN;
declare variable WDIASFERIASSEGUNDOVENC integer;
declare variable WSQL2 varchar(10000);
declare variable WSTR varchar(100);
declare variable WCODIGO integer;
declare variable WPAGAMENTOFERIAS DM_BOOLEAN;
declare variable WDIASPAGAMENTOFERIAS integer;
declare variable WPAGAMENTORESCISAO DM_BOOLEAN;
declare variable WDIASPAGAMENTORESCISAO integer;
declare variable WORGAOCLASSE DM_BOOLEAN;
declare variable WDIASORGAOCLASSE integer;
declare variable WHORAEXECUCAO varchar(5);
declare variable WCONTRATODETERMINADO2 DM_BOOLEAN;
declare variable WDIASCONTRATODETERMINADO2 integer;
declare variable WDATA varchar(10);
declare variable WDATAVENC varchar(10);
declare variable WCONTRCOL integer;
declare variable WDATAINICIAL varchar(12);
declare variable WINIPERAQUIFER varchar(10);
declare variable WFIMPERAQUIFER varchar(10);
declare variable WREF integer;
declare variable WTIPO integer;
declare variable WDATAEXECUCAO date;
declare variable WINATIVO DM_BOOLEAN;
declare variable WAVISOS DM_BOOLEAN;
declare variable WINFORMATIVOS DM_BOOLEAN;
declare variable WDATAPARAM date;
declare variable WNOMECOLCON varchar(100);
declare variable WSQLCOL varchar(10000);
declare variable WDATANASC date;
declare variable WANOBISEXTO integer;
begin
  suspend;
end^
  
create or alter procedure SP_CONTABILIZACAO_PROVISOES (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXAFILIAIS smallint = 0)
returns (
    BDCODEMP integer,
    BDCODEMPSUC integer,
    BDCHAVE integer,
    BDCODCOL integer,
    BDCODTER integer,
    BDREFFN integer,
    BDTIPOFOL integer,
    BDORDEM integer)
as
begin
  suspend;
end^

create or alter procedure SP_CONTABILIZACAO_FGTS (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXAFILIAIS smallint = 0)
returns (
    BDCODEMP integer,
    BDCODEMPSUC integer,
    BDCHAVE integer,
    BDCODCOL integer,
    BDCODTER integer,
    BDREFFN integer,
    BDTIPOFOL integer,
    BDORDEM integer)
as
begin
  suspend;
end^

create or alter procedure SP_CONTABILIZACAO_VERBAS (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXAFILIAIS smallint = 0)
returns (
    BDCODEMP integer,
    BDCODEMPSUC integer,
    BDCHAVE integer,
    BDCODCOL integer,
    BDCODTER integer,
    BDREFFN integer,
    BDTIPOFOL integer,
    BDORDEM integer,
    BDCODVER integer)
as
begin
  suspend;
end^

create or alter procedure SP_CONTABILIZACAO_CALCULOS (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXAFILIAIS smallint = 0)
returns (
    BDCODEMP integer,
    BDCODEMPSUC integer,
    BDCHAVE integer,
    BDCODCOL integer,
    BDCODTER integer,
    BDREFFN integer,
    BDTIPOFOL integer,
    BDORDEM integer)
as
begin
  suspend;
end^

create or alter procedure SP_QUALIFICA_ESOCIAL (
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(100),
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDDATANASCCOL date,
    BDCERTDIGITAL varchar(200))
as
begin
  suspend;
end^

create or alter procedure SP_VRH_BASE_TSALHORESP_COMP (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMPSHE integer,
    BDCODCOL integer,
    BDCODEMP integer,
    BDCODSHE integer,
    BDCODMAS integer,
    BDSALSHE numeric(18,6),
    BDDATASHE date,
    BDDATAEFEITOHE date,
    BDCODVER integer,
    BDSALINISHE numeric(18,6),
    BDDESCVERBASHE DM_BOOLEAN,
    BDDESCSHE varchar(50))
as
declare variable WSQL varchar(25000);
declare variable WSQLCOL varchar(32700);
declare variable WULTDAT date;
declare variable WULTDIA integer;
begin
  suspend;
end^

create or alter procedure SP_VRH_BASE_TSALHORESP (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMPSHE integer,
    BDCODCOL integer,
    BDCODEMP integer,
    BDCODSHE integer,
    BDCODMAS integer,
    BDSALSHE numeric(18,6),
    BDDATASHE date,
    BDCODVER integer,
    BDSALINISHE numeric(18,6),
    BDDESCVERBASHE DM_BOOLEAN,
    BDDESCSHE varchar(50))
as
declare variable WSQL varchar(25000);
declare variable WSQLCOL varchar(32700);
declare variable WULTDAT date;
declare variable WULTDIA integer;
begin
  suspend;
end^

create or alter procedure SP_VRHF_MV_VINCSEMCALC (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODMV integer,
    BDREFCOL integer,
    BDBASEINSSNCOL numeric(15,6),
    BDVALORINSSNCOL numeric(15,6),
    BDBASEIRRFNCOL numeric(15,6),
    BDVALORIRRFNCOL numeric(15,6),
    BDBASEINSS13COL numeric(15,6),
    BDVALORINSS13COL numeric(15,6),
    BDBASEIRRF13COL numeric(15,6),
    BDVALORIRRF13COL numeric(15,6),
    BDCNPJRESP DM_CNPJ_CPF,
    BDCATEGORIAESOCIAL integer,
    BDTIPOCALC integer,
    BDREFFIM integer,
    BDCODEMPVINC integer,
    BDCODCOLVINC integer,
    BDCODTERVINC integer)
as
declare variable WSQL varchar(32700);
declare variable WACHOU integer;
begin
  suspend;
end^


create or alter procedure SP_VRHM_EMP_VAL_TOD_OP_ATU2 (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer,
    PRPLANO integer = 0,
    PROPER integer = 0,
    PRCONV integer = 0)
returns (
    BDTIPO integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREF integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDNOME varchar(70),
    BDCPF varchar(14),
    BDVALORMENSALIDADE numeric(18,6),
    BDVALORCOPAR numeric(18,6),
    BDCODTIPOCONV integer,
    BDTIPOFAIXA integer,
    BDCODTIPO integer,
    BDMENSFORMULA DM_BOOLEAN,
    BDCODVERTITMENS integer,
    BDCODVERTITCOP integer,
    BDCODVERDEPMENS integer,
    BDCODVERDEPCOP integer)
as
declare variable WSQL varchar(32700);
begin
  suspend;
end^

create or alter procedure SP_VRH_CONS_NOVO_MV (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRTIPOCALC integer = 0)
returns (
    BDCODEMP varchar(20),
    BDCODCOL varchar(30),
    BDNOMEMP DM_BDNOMEMP,
    BDNOMCOL DM_BDNOMCOL,
    BDBINSSFN numeric(18,6),
    BDINSSFN numeric(18,6))
as
declare variable WEMP integer;
declare variable WCOL integer;
declare variable WTERC integer;
declare variable WBINSS numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WCNPJ DM_CNPJ_CPF;
begin
  suspend;
end^

create or alter procedure SP_VRH_CONS_NOVO_MV_FC (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRTIPOCALC integer = 0)
returns (
    BDCODEMP varchar(20),
    BDCODCOL varchar(30),
    BDNOMEMP DM_BDNOMEMP,
    BDNOMCOL DM_BDNOMCOL,
    BDBINSSFN numeric(18,6),
    BDINSSFN numeric(18,6))
as
declare variable WEMP integer;
declare variable WCOL integer;
declare variable WBINSS numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WCNPJ DM_CNPJ_CPF;
begin
  suspend;
end^

create or alter procedure VRH_SP_RATEIO_INTERMITENTE (
    PRREF integer,
    PREMPRESA varchar(32700),
    PRCOLABORADOR varchar(32700))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODCONTTI integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDDATAENTRADA date,
    BDHORAENTRADA time,
    BDTIPO integer,
    BDQTDTEMPO numeric(15,6),
    BDCTALON varchar(40),
    BDTIPCTA smallint,
    BDNOMCTA varchar(100),
    BDAPECTA varchar(20),
    BDFILTROGER varchar(20),
    BDCLANOM varchar(140),
    BDTEMPO integer,
    BDTEMPOFN integer,
    BDPERCFN numeric(15,6),
    BDLANCHORAS numeric(15,2),
    BDTOTHORAS numeric(15,2),
    BDTOTDSR numeric(15,2),
    BDLANCDSR numeric(15,2))
as
declare variable WSQLAUX varchar(32700);
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WULTDIA integer;
declare variable WANO integer;
declare variable WMES smallint;
declare variable WDIA integer;
declare variable WDATAINI varchar(10);
declare variable WDATAFIM varchar(10);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WCODCONTTI integer;
begin
suspend;
end^

CREATE OR ALTER TRIGGER VRH_BASE_TPLA_TCONTRATO_BI0 FOR VRH_BASE_TPLA_TCONTRATO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TPARCEIRO_BI0 FOR TPARCEIRO
active before insert position 0
AS
begin
end^

CREATE OR ALTER TRIGGER VRH_BASE_TPLA_TCONTRATO_BU0 FOR VRH_BASE_TPLA_TCONTRATO
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TAPVALREF_BI0 FOR VRHF_EMP_TAPVALREF
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VRHF_EMP_TAPVALREF_BU0 FOR VRHF_EMP_TAPVALREF
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end^

create or alter procedure SP_UNION_FN_FT_MES_BASES (
    PREMP varchar(25000),
    PRCOL varchar(25000),
    PRREF integer,
    PRFILTROCC varchar(15000),
    PRPUXAFILIAIS smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDDATABAIXA date,
    BDBFGTS numeric(18,2),
    BDFGTS numeric(18,2),
    BDFGTSCS numeric(18,2),
    BDBFGTS13 numeric(18,2),
    BDFGTS13 numeric(18,2),
    BDFGTS13CS numeric(18,2),
    BDMAIORREM numeric(18,2),
    BDBINSS numeric(18,2),
    BDALIQINSS numeric(18,2),
    BDINSS numeric(18,2),
    BDBIRRF numeric(18,2),
    BDALIQIRRF numeric(18,2),
    BDIRRF numeric(18,2),
    BDBINSS13 numeric(18,2),
    BDALIQINSS13 numeric(18,2),
    BDINSS13 numeric(18,2),
    BDBIRRF13 numeric(18,2),
    BDALIQIRRF13 numeric(18,2),
    BDIRRF13 numeric(18,2),
    BDBSALFAM numeric(18,2),
    BDSALFAM numeric(18,2),
    BDBRAIS numeric(18,2),
    BDSALBASE numeric(18,2),
    BDDEP numeric(18,2),
    BDBINSSFEFOL numeric(18,2),
    BDINSSFEFOL numeric(18,2),
    BDALIQINSSFEFOL numeric(18,2),
    BDCREDITO numeric(18,2),
    BDDEBITO numeric(18,2),
    BDBFGTSFEFOL numeric(18,2),
    BDFGTSFEFOL numeric(18,2),
    BDBIRRFFE numeric(18,2),
    BDIRRFFE numeric(18,2),
    BDLIQUIDO numeric(18,2),
    BDDATAPGTO date,
    BDCODEMPREENDIMENTO integer)
as
begin
  suspend;
end^

create or alter procedure SP_UNION_FC_FCT_MES_BASES (
    PREMP varchar(25000),
    PRCOL varchar(25000),
    PRREF integer,
    PRDATAPAGFC date,
    PRFILTROCC varchar(15000),
    PRPUXAFILIAIS smallint,
    PRCODADC integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFFC integer,
    BDREFCOMP integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDDATABAIXA date,
    BDBFGTS numeric(18,2),
    BDFGTS numeric(18,2),
    BDFGTSCS numeric(18,2),
    BDBFGTS13 numeric(18,2),
    BDFGTS13 numeric(18,2),
    BDFGTS13CS numeric(18,2),
    BDMAIORREM numeric(18,2),
    BDBINSS numeric(18,2),
    BDALIQINSS numeric(18,2),
    BDINSS numeric(18,2),
    BDBIRRF numeric(18,2),
    BDALIQIRRF numeric(18,2),
    BDIRRF numeric(18,2),
    BDBINSS13 numeric(18,2),
    BDALIQINSS13 numeric(18,2),
    BDINSS13 numeric(18,2),
    BDBIRRF13 numeric(18,2),
    BDALIQIRRF13 numeric(18,2),
    BDIRRF13 numeric(18,2),
    BDBSALFAM numeric(18,2),
    BDSALFAM numeric(18,2),
    BDBRAIS numeric(18,2),
    BDSALBASE numeric(18,2),
    BDDEP numeric(18,2),
    BDBINSSFEFOL numeric(18,2),
    BDINSSFEFOL numeric(18,2),
    BDALIQINSSFEFOL numeric(18,2),
    BDCREDITO numeric(18,2),
    BDDEBITO numeric(18,2),
    BDBFGTSFEFOL numeric(18,2),
    BDFGTSFEFOL numeric(18,2),
    BDLIQUIDO numeric(18,2),
    BDCODEMPREENDIMENTO integer,
    BDDATAPAGFC date)
as
begin
  suspend;
end^

create or alter procedure SP_UNION_FI_FTI_MES_BASES (
    PREMP varchar(25000),
    PRCOL varchar(25000),
    PRREF integer,
    PRDATAPGTO date,
    PRFILTROCC varchar(15000),
    PRPUXAFILIAIS integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODCONTTI integer,
    BDREFFN integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDDATABAIXA date,
    BDBFGTS numeric(18,2),
    BDFGTS numeric(18,2),
    BDFGTSCS numeric(18,2),
    BDBFGTS13 numeric(18,2),
    BDFGTS13 numeric(18,2),
    BDFGTS13CS numeric(18,2),
    BDMAIORREM numeric(18,2),
    BDBINSS numeric(18,2),
    BDALIQINSS numeric(18,2),
    BDINSS numeric(18,2),
    BDBIRRF numeric(18,2),
    BDALIQIRRF numeric(18,2),
    BDIRRF numeric(18,2),
    BDBINSS13 numeric(18,2),
    BDALIQINSS13 numeric(18,2),
    BDINSS13 numeric(18,2),
    BDBIRRF13 numeric(18,2),
    BDALIQIRRF13 numeric(18,2),
    BDIRRF13 numeric(18,2),
    BDBSALFAM numeric(18,2),
    BDSALFAM numeric(18,2),
    BDBRAIS numeric(18,2),
    BDSALBASE numeric(18,2),
    BDDEP numeric(18,2),
    BDBINSSFEFOL numeric(18,2),
    BDINSSFEFOL numeric(18,2),
    BDALIQINSSFEFOL numeric(18,2),
    BDCREDITO numeric(18,2),
    BDDEBITO numeric(18,2),
    BDBFGTSFEFOL numeric(18,2),
    BDFGTSFEFOL numeric(18,2),
    BDBIRRFFE numeric(18,2),
    BDIRRFFE numeric(18,2),
    BDLIQUIDO numeric(18,2),
    BDDATAPGTO date)
as
begin
  suspend;
end^

create or alter procedure SP_UNION_FCI_FCTI_MESFN_BASES (
    PREMP varchar(25000),
    PRCOL varchar(25000),
    PRREF integer,
    PRDATAPAGFC date,
    PRFILTROCC varchar(15000),
    PRPUXAFILIAIS smallint)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFFC integer,
    BDCODCONTTI integer,
    BDDATAGRRFFC date,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDDATABAIXA date,
    BDBFGTS numeric(18,2),
    BDFGTS numeric(18,2),
    BDFGTSCS numeric(18,2),
    BDBFGTS13 numeric(18,2),
    BDFGTS13 numeric(18,2),
    BDFGTS13CS numeric(18,2),
    BDMAIORREM numeric(18,2),
    BDBINSS numeric(18,2),
    BDALIQINSS numeric(18,2),
    BDINSS numeric(18,2),
    BDBIRRF numeric(18,2),
    BDALIQIRRF numeric(18,2),
    BDIRRF numeric(18,2),
    BDBINSS13 numeric(18,2),
    BDALIQINSS13 numeric(18,2),
    BDINSS13 numeric(18,2),
    BDBIRRF13 numeric(18,2),
    BDALIQIRRF13 numeric(18,2),
    BDIRRF13 numeric(18,2),
    BDBSALFAM numeric(18,2),
    BDSALFAM numeric(18,2),
    BDBRAIS numeric(18,2),
    BDSALBASE numeric(18,2),
    BDDEP numeric(18,2),
    BDBINSSFEFOL numeric(18,2),
    BDINSSFEFOL numeric(18,2),
    BDALIQINSSFEFOL numeric(18,2),
    BDCREDITO numeric(18,2),
    BDDEBITO numeric(18,2),
    BDBFGTSFEFOL numeric(18,2),
    BDFGTSFEFOL numeric(18,2),
    BDCODTIPOFC integer,
    BDBIRRFFE numeric(18,2),
    BDIRRFFE numeric(18,2),
    BDLIQUIDO numeric(18,2),
    BDBIRRFFEFOL numeric(18,2),
    BDIRRFFEFOL numeric(18,2),
    BDCODACCONV integer,
    BDDATAPAGFC date)
as
begin
  suspend;
end^

create or alter procedure SP_REL_CAGED_ESOCIAL (
    PREMPRESAS varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRSOMENTEMOV varchar(5),
    PRFILTROMOV integer)
returns (
    BDTIPODETALHE integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDNOMEMP varchar(100),
    BDCODFILIAL integer,
    BDATIVOSINIMES integer,
    BDATIVOSFIMMES integer,
    BDADMITIDOSMES integer,
    BDDEMITIDOSMES integer,
    BDDATAADMCOL date,
    BDDATARESCISAO date,
    BDCPFCOL varchar(14),
    BDDATAINTEGRACAO date,
    BDHORAINTEGRACAO time,
    BDPROTOCOLO varchar(50),
    BDRECIBO varchar(30),
    BDEVENTO varchar(10),
    BDMOTIVO varchar(10),
    BDPCD integer,
    BDNOMCOL varchar(70),
    BDMOVIMENTACAO varchar(5))
as
begin
  suspend;
end^

CREATE OR ALTER PROCEDURE SP_EXPORTACAO_VT_BLUMOB (
    PRCODEMP VARCHAR(10000),
    PRCODCOL VARCHAR(10000),
    PRREF INTEGER,
    PRCODCLA INTEGER = NULL,
    PRCODSINTRAB INTEGER = NULL)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDNOMEMP VARCHAR(100),
    BDCPFCOL VARCHAR(14),
    BDNOMCOL VARCHAR(70),
    BDVALORDIARIO NUMERIC(18,6),
    BDQUANTIDADE INTEGER)
AS
BEGIN
    SUSPEND;
END^

CREATE OR ALTER TRIGGER VRH_BASE_TEXPBENEFICIO_PAR_BI0 FOR VRH_BASE_TEXPBENEFICIO_PAR
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER PROCEDURE SP_SETA_USUARIO(PRCODUSUARIO INTEGER,
    PRATUALIZARLISTAEMP integer = 0)
 AS
 BEGIN EXIT; END
^

create or alter procedure SP_REMOVE_INDICE_SE_EXISTE (
    PRNOMEINDICE varchar(32) collate WIN_PTBR)
as
declare variable WEXISTE integer;
begin
end^

CREATE OR ALTER TRIGGER VRH_RHNET_TIMAGENS_EXP_BI0 FOR VRH_RHNET_TIMAGENS_EXP
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER vrh_esocial_infobasefgts_c_bi0 for vrh_esocial_infobasefgts_c
active before insert position 0
AS
begin
end^

create or alter procedure SP_VRHF_FGTSSEFIP_AGRUPA_CC_MES (
    PREMP varchar(30000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODTPCC integer,
    BDCODCENTRO integer,
    BDBASEFGTSFN numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDFGTSFN numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDINSSFN numeric(18,6),
    BDINSS13 numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSS13 numeric(18,6),
    BDBINSS13R numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDBINSSC13 numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSS13DT numeric(18,6),
    BDINSSC13 numeric(18,6),
    BDINSSMV numeric(18,6))
as
begin
  suspend;
end^

CREATE OR ALTER procedure SP_REPLICA_COMPETENCIAS (
    PRCODEMP integer,
    PRREFEMP integer,
    PRTABELA varchar(60) = 'TEMPRESAS_REF')
as
begin
end^

create or alter procedure SP_LISTA_COMPETENCIAS_QUEBRADAS (
    PRTABELA varchar(33) = 'TEMPRESAS_REF',
    PRAPENAS_ULTIMA_COMPETENCIA smallint = 1)
returns (
    BDCODEMP integer,
    BDREFEMP integer,
    BDTABELA varchar(33),
    BDDESCRIPTION varchar(256),
    BDDEPENDENCIES varchar(33))
as
begin
 suspend;
end^

CREATE OR ALTER procedure SP_VFIN_EMPRESACLIENTE_REF (
    PRCODEMP integer,
    PRNEWREFEMP integer)
as
declare variable VFIELDS varchar(1000);
declare variable VINSERT varchar(3000);
begin
end^

create or alter procedure SP_VRHF_FGTSSEFIP_AGRUPA_1 (
    PREMP varchar(30000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODTPCC integer,
    BDCODCENTRO integer,
    BDBASEFGTSFN numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDFGTSFN numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDINSSFN numeric(18,6),
    BDINSS13 numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSS13 numeric(18,6),
    BDBINSS13R numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDBINSSC13 numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSS13DT numeric(18,6),
    BDINSSC13 numeric(18,6),
    BDINSSMV numeric(18,6))
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_FGTSSEFIP_AGRUPA_3 (
    PREMP varchar(30000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODTPCC integer,
    BDCODCENTRO integer,
    BDBASEFGTSFN numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDFGTSFN numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDINSSFN numeric(18,6),
    BDINSS13 numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSS13 numeric(18,6),
    BDBINSS13R numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDBINSSC13 numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSS13DT numeric(18,6),
    BDINSSC13 numeric(18,6),
    BDINSSMV numeric(18,6))
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_FGTSSEFIP (
    PREMP varchar(30000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDSOMA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODTPCC integer,
    BDCODCENTRO integer,
    BDBASEFGTSFN numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDFGTSFN numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDINSSFN numeric(18,6),
    BDINSS13 numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSS13 numeric(18,6),
    BDBINSS13R numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDBINSSC13 numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSS13DT numeric(18,6),
    BDINSSC13 numeric(18,6),
    BDINSSMV numeric(18,6))
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_FGTSSEFIP_13 (
    PREMP varchar(30000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODTPCC integer,
    BDCODCENTRO integer,
    BDBASEFGTS13 numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDINSS13 numeric(18,6),
    BDBINSS13 numeric(18,6),
    BDBASEFGTSFN numeric(18,6),
    BDFGTSFN numeric(18,6),
    BDINSSFN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSS13R numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDBINSSC13 numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSS13DT numeric(18,6),
    BDINSSC13 numeric(18,6),
    BDINSSMV numeric(18,6))
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_FGTSSEFIP_13_CC (
    PREMP varchar(30000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODTPCC integer,
    BDCODCENTRO integer,
    BDBASEFGTSFN numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDFGTSFN numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDINSSFN numeric(18,6),
    BDINSS13 numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSS13 numeric(18,6),
    BDBINSS13R numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDBINSSC13 numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSS13DT numeric(18,6),
    BDINSSC13 numeric(18,6),
    BDINSSMV numeric(18,6))
as
begin
    suspend;
end^

create or alter procedure SP_VRHF_EMP_T13SAL_RAT_CC (
    PREMP varchar(30000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDREF13 integer,
    BDCHAVE integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDMESESPROP13 integer,
    BDBASEIR13 numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDFGTSCS13 numeric(18,6),
    BDDATABAIXA13 date,
    BDREFBAIXA13 integer,
    BDPERCIR13 numeric(18,6),
    BDVALORIR13 numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDPERCINSS13 numeric(18,6),
    BDVALORINSS13 numeric(18,6),
    BDBRAIS13 numeric(18,6),
    BDSALBASE13 numeric(18,6),
    BDDEP13 numeric(18,6),
    BDARREPROV13 numeric(18,6),
    BDARREDESC13 numeric(18,6),
    BDVAL13 numeric(18,6),
    BDBSALFAM13 numeric(18,6),
    BDSALFAM13 numeric(18,6),
    BDANO13 integer,
    BDBASEPIS13 numeric(18,6),
    BDBSALMATEMP13 numeric(18,6),
    BDSALMATEMP13 numeric(18,6),
    BDBRATAPO13 numeric(18,6),
    BDRATAPO13 numeric(18,6),
    BDESTPROV13 numeric(18,6),
    BDCREDITO13 numeric(18,6),
    BDDEBITO13 numeric(18,6),
    BDLIQUIDO numeric(18,6),
    BDDATAPGTO13 date,
    BDBINSSMV13 numeric(18,6),
    BDJAN DM_BOOLEAN,
    BDFEV DM_BOOLEAN,
    BDMAR DM_BOOLEAN,
    BDABR DM_BOOLEAN,
    BDMAI DM_BOOLEAN,
    BDJUN DM_BOOLEAN,
    BDJUL DM_BOOLEAN,
    BDAGO DM_BOOLEAN,
    BDSET DM_BOOLEAN,
    BDOUT DM_BOOLEAN,
    BDNOV DM_BOOLEAN,
    BDDEZ DM_BOOLEAN,
    BDDATAPROC13 date,
    BDHORAPROC13 time,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCODTOMADOR integer)
as
begin
  suspend;
end^

CREATE OR ALTER procedure VSUC_SP_BALANCO_MENSAL (
    PRCODEMP varchar(2048),
    PRDATAINI date,
    PRDATAFIN date,
    PRIGNZER integer,
    PRCTALONINI varchar(40),
    PRCTALONFIN varchar(40),
    PRCTALONPAS varchar(40),
    PRINDICE integer,
    PRLISTCC varchar(8192),
    PRNAOMOSTRACONTRAPART integer,
    PRREFEMP integer,
    PRCONSOLIDADA integer,
    PRDETALHAPART integer,
    PRCONCATENAPARTIC integer,
    PRNIVEISCONTAS varchar(50),
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLI integer,
    PRSEMCC integer)
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(20),
    BDCODPLAPADRAO integer,
    BDCODCTA integer,
    BDCTALON varchar(40),
    BDNOMCTA varchar(300),
    BDTIPCTA integer,
    BDSEQCTA varchar(40),
    BDCODCENTROS integer,
    BDCODTPCC integer,
    BDNOMTPCC varchar(80),
    BDSALANT numeric(15,2),
    BDSAL_ANT_DEB numeric(15,2),
    BDSAL_ANT_CRE numeric(15,2),
    BDSALMOV numeric(15,2),
    BDSALDO_DEB numeric(15,2),
    BDSALDO_CRE numeric(15,2),
    BDSALATU numeric(15,2),
    BDFORMULA varchar(1024),
    BDCODEMPFILIAL integer,
    BDGRPCTA integer,
    BDAPECTA varchar(20),
    BDPERTENCECONTA integer,
    BDREF integer)
as
declare variable WDATAATUAL date;
begin
 suspend;
end^

CREATE OR ALTER TRIGGER VINT_EMP_PROCESSOTROCA_BAL_BI0 FOR VINT_EMP_PROCESSOTROCA_BAL
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER  TRIGGER VSUC_EMP_TLAN_SPED_K300_BI0 for VSUC_EMP_TLAN_SPED_K300
active before insert position 0
AS
begin
end^



CREATE OR ALTER  TRIGGER VSUC_EMP_TLAN_SPED_K315_BI0 for VSUC_EMP_TLAN_SPED_K315
active before insert position 0
AS
begin
end^

CREATE OR ALTER trigger tol_vsuc_emp_tlan_auto_ad0 for tol_vsuc_emp_tlan_auto
active after delete position 0
AS
begin
end^

CREATE OR ALTER TRIGGER VSH_EMP_TCONF_LANAUTO_INC_BI0 FOR VSH_EMP_TCONF_LANAUTO_INC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER trigger tol_vsuc_tlan_autoparpgto_ad0 for tol_vsuc_emp_tlan_autoparpgto
active after delete position 0
AS
begin
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TSERINSS_AI0 FOR TOL_VEF_EMP_TSERINSS
ACTIVE AFTER INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VFIN_BASE_TLOGREMAPI_AI0 FOR VFIN_BASE_TLOGREMAPI
ACTIVE AFTER INSERT POSITION 0
as
begin
end^

CREATE OR ALTER TRIGGER VFIN_ESC_TLOGREM_BI0 FOR VFIN_ESC_TLOGREM
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VFIN_BASE_PLANOIMPORTCSV_BI0 FOR VFIN_BASE_PLANOIMPORTACAOCSV
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VFIN_ESC_TCABSERVICOFIXO_BI0 FOR VFIN_ESC_TCABSERVICOFIXO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VFIN_BASE_CONFIGIMPORTOCSV_BI0 FOR VFIN_BASE_CONFIGIMPORTACAOCSV
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE or alter  trigger vsuc_exporta_brgaap_bi0 for vsuc_exporta_brgaap
active before insert position 0
AS
begin
end^

CREATE OR ALTER TRIGGER vrhf_mvaut_bi0 FOR vrhf_mvaut
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER TPLANO_ORGANIZACIONAL_BI0 FOR TPLANO_ORGANIZACIONAL
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER TPLANO_ORGANIZACIONAL_ITENS_BI0 FOR TPLANO_ORGANIZACIONAL_ITENS
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VFIN_BASE_TCONFCOBSERV_BI0 FOR VFIN_BASE_TCONFCOBSERV
active before insert position 0
AS
begin
end^

CREATE OR ALTER TRIGGER VRH_ARQ_EXP_SEFIP_BI0 FOR VRH_ARQ_EXP_SEFIP
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VRH_EMP_ESOCIAL_BAIXAR_DATA_BI0 FOR VRH_EMP_ESOCIAL_BAIXAR_DATA
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VRH_EMP_ESOCIAL_BAIXAR_BI0 FOR VRH_EMP_ESOCIAL_BAIXAR
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE or ALTER trigger empresas_tmotivobai_bi0 for empresas_tmotivobai
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
END^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TPCC_ECD_I157 FOR CENTROS_TPCC_ECD_I157
active before insert position 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER TR_BF_INSERT_EMP_TPCC_I157 FOR EMPRESAS_TPCC_ECD_I157
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRHP_BASE_IMPPONTO_BI0 FOR VRHP_BASE_IMPPONTO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_REF_BU0 FOR TCONF_CONTAS_ONLINE_REF
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_REF_AU0 FOR TCONF_CONTAS_ONLINE_REF
ACTIVE AFTER UPDATE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_AI0 FOR TCONF_CONTAS_ONLINE
ACTIVE AFTER INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRHF_EMP_TNOTASFISCAIS_AD0 FOR VRHF_EMP_TNOTASFISCAIS
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END^

create or alter procedure SP_VRHF_RESUMO_ADSAL (
    PREMP varchar(20000),
    PRCOL varchar(32700),
    PRDATAINI date,
    PRDATAFIM date,
    PRFUCDET smallint = 0,
    PRPUXAFILIAL smallint = 0)
returns (
    GRUPO_CLASSE integer,
    CODIGO_EMPRESA integer,
    CODIGO_FILIAL integer,
    NOME_EMPRESA DM_BDNOMEMP,
    ENDERECO_EMPRESA DM_BDENDERECO,
    NUMERO_EMPRESA DM_NUMEND,
    BAIRRO_EMPRESA DM_BDBAIRRO,
    CEP_EMPRESA DM_CEP,
    CNPJ_EMPRESA DM_CNPJ_CPF,
    CODIGO_COLABORADOR integer,
    NOME_COLABORADOR DM_BDNOMCOL,
    ADMISSAO_COLABORADOR date,
    FUNCAO_COLABORADOR varchar(100),
    CPF_COLABORADOR varchar(14),
    PIS_COLABORADOR varchar(14),
    CODIGO_VERBA integer,
    DESCRICAO_VERBA varchar(40),
    REFERENCIA_VERBA numeric(18,6),
    REFERENCIA_AUXILIAR_VERBA numeric(18,6),
    BDTIPOCODVER integer,
    PROVENTOS_FOLHA numeric(18,6),
    DESCONTOS_FOLHA numeric(18,6),
    SALARIO_BASE numeric(18,6),
    BDCODENQFED integer,
    BDSIMPLESGPS integer,
    CTPS_COL DM_BDCTPS,
    SERIE_CTPS DM_SERIECTPS,
    CBO_COL integer,
    HORAS_MENSAIS numeric(18,6),
    RAT_APO_COL numeric(18,6),
    REFERENCIA_FOLHA integer,
    BDORDEM integer,
    IRRF_FOLHA numeric(18,6),
    REFERENCIAAUX varchar(8),
    DESCRICAO_RED_VERBA varchar(20),
    CIDADE_EMPRESA varchar(40),
    UF_EMPRESA varchar(2),
    COMPL_EMPRESA DM_BDCOMPENDERECO,
    PISVER DM_BOOLEAN,
    BDORDEMTIPOCODVER integer,
    CLASSIFICA_VERBA varchar(20),
    RESCISAO_COLABORADOR date,
    MOTIVO_RESCISAO varchar(110),
    TIPO_RESCISAO integer,
    BDTEMGRRF integer,
    BDORDEMVER integer,
    DATA_PAG_IR date,
    BDTIPOREFVER integer,
    BDREFHOREMP DM_BOOLEAN,
    BDCCATVCONCOM DM_BOOLEAN,
    BDCATEGORIAESOCIAL integer,
    DEPSF integer,
    DEPIR integer,
    BDCONTRCOL integer,
    DATA_AD date,
    DATA_PAGAMENTO_FOLHA date,
    BDCODCENTROS integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_RESUMO_AD13SAL (
    PREMP varchar(20000),
    PRCOL varchar(32700),
    PRREF integer,
    PRPROXIMAREF integer,
    PRULTDIA date,
    PRFUCDET smallint = 0,
    PRPUXAFILIAL smallint = 0)
returns (
    GRUPO_CLASSE integer,
    CODIGO_EMPRESA integer,
    CODIGO_FILIAL integer,
    NOME_EMPRESA DM_BDNOMEMP,
    ENDERECO_EMPRESA DM_BDENDERECO,
    NUMERO_EMPRESA DM_NUMEND,
    BAIRRO_EMPRESA DM_BDBAIRRO,
    CEP_EMPRESA DM_CEP,
    CNPJ_EMPRESA DM_CNPJ_CPF,
    CODIGO_COLABORADOR integer,
    NOME_COLABORADOR DM_BDNOMCOL,
    ADMISSAO_COLABORADOR date,
    FUNCAO_COLABORADOR varchar(100),
    CPF_COLABORADOR varchar(14),
    PIS_COLABORADOR varchar(14),
    CODIGO_VERBA integer,
    DESCRICAO_VERBA varchar(40),
    REFERENCIA_VERBA numeric(18,6),
    BDTIPOCODVER integer,
    PROVENTOS_FOLHA numeric(18,6),
    DESCONTOS_FOLHA numeric(18,6),
    SALARIO_BASE numeric(18,6),
    BDCODENQFED integer,
    BDSIMPLESGPS integer,
    CTPS_COL DM_BDCTPS,
    SERIE_CTPS DM_SERIECTPS,
    CBO_COL integer,
    HORAS_MENSAIS numeric(18,6),
    RAT_APO_COL numeric(18,6),
    REFERENCIA_FOLHA integer,
    BDORDEM integer,
    BASE_FGTS numeric(18,6),
    FGTS_FOLHA numeric(18,6),
    IRRF_FOLHA numeric(18,6),
    BASE_RAIS numeric(18,6),
    REFERENCIAAUX varchar(6),
    DESCRICAO_RED_VERBA varchar(20),
    CIDADE_EMPRESA varchar(40),
    UF_EMPRESA varchar(2),
    COMPL_EMPRESA DM_BDCOMPENDERECO,
    PISVER DM_BOOLEAN,
    BDORDEMTIPOCODVER integer,
    CLASSIFICA_VERBA varchar(20),
    RESCISAO_COLABORADOR date,
    MOTIVO_RESCISAO varchar(110),
    TIPO_RESCISAO integer,
    SALARIO_FAMILIA numeric(18,6),
    BDTEMGRRF integer,
    BDORDEMVER integer,
    DATA_PAG_IR date,
    BDTIPOREFVER integer,
    BDREFHOREMP DM_BOOLEAN,
    BFGTS_MESPOST numeric(18,6),
    FGTS_MESPOST numeric(18,6),
    BDCCATVCONCOM DM_BOOLEAN,
    BDCATEGORIAESOCIAL integer,
    DEPSF integer,
    DEPIR integer,
    BDCONTRCOL integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_RESUMO_13SAL (
    PREMP varchar(20000),
    PRCOL varchar(32700),
    PRREF integer,
    PRPROXIMAREF integer,
    PRULTDIA date,
    PREMISSAO integer = 0,
    PRFUCDET smallint = 0,
    PRPUXAFILIAL smallint = 0)
returns (
    GRUPO_CLASSE integer,
    CODIGO_EMPRESA integer,
    CODIGO_FILIAL integer,
    NOME_EMPRESA DM_BDNOMEMP,
    ENDERECO_EMPRESA DM_BDENDERECO,
    NUMERO_EMPRESA DM_NUMEND,
    BAIRRO_EMPRESA DM_BDBAIRRO,
    CEP_EMPRESA DM_CEP,
    CNPJ_EMPRESA DM_CNPJ_CPF,
    CODIGO_COLABORADOR integer,
    NOME_COLABORADOR DM_BDNOMCOL,
    ADMISSAO_COLABORADOR date,
    FUNCAO_COLABORADOR varchar(100),
    CPF_COLABORADOR varchar(14),
    PIS_COLABORADOR varchar(14),
    CODIGO_VERBA integer,
    DESCRICAO_VERBA varchar(40),
    REFERENCIA_VERBA numeric(18,6),
    BDTIPOCODVER integer,
    PROVENTOS_FOLHA numeric(18,6),
    DESCONTOS_FOLHA numeric(18,6),
    SALARIO_BASE numeric(18,6),
    BDCODENQFED integer,
    BDSIMPLESGPS integer,
    CTPS_COL DM_BDCTPS,
    SERIE_CTPS DM_SERIECTPS,
    CBO_COL integer,
    HORAS_MENSAIS numeric(18,6),
    RAT_APO_COL numeric(18,6),
    REFERENCIA_FOLHA integer,
    BDORDEM integer,
    BASE_INSS numeric(18,6),
    BASE_FGTS numeric(18,6),
    FGTS_FOLHA numeric(18,6),
    IRRF_FOLHA numeric(18,6),
    BASE_RAIS numeric(18,6),
    REFERENCIAAUX varchar(6),
    DESCRICAO_RED_VERBA varchar(20),
    CIDADE_EMPRESA varchar(40),
    UF_EMPRESA varchar(2),
    COMPL_EMPRESA DM_BDCOMPENDERECO,
    PISVER DM_BOOLEAN,
    BDORDEMTIPOCODVER integer,
    CLASSIFICA_VERBA varchar(20),
    RESCISAO_COLABORADOR date,
    MOTIVO_RESCISAO varchar(110),
    TIPO_RESCISAO integer,
    SALARIO_FAMILIA numeric(18,6),
    BDTEMGRRF integer,
    BDORDEMVER integer,
    DATA_PAG_IR date,
    BDTIPOREFVER integer,
    BDREFHOREMP DM_BOOLEAN,
    BFGTS_MESPOST numeric(18,6),
    FGTS_MESPOST numeric(18,6),
    BDCCATVCONCOM DM_BOOLEAN,
    BDCATEGORIAESOCIAL integer,
    DEPSF integer,
    DEPIR integer,
    BDCONTRCOL integer,
    BASE_INSS13_MULTVINC numeric(18,6),
    BASE_IR13_MULTVINC numeric(18,6),
    VALOR_INSS13_MULTVINC numeric(18,6),
    VALOR_IR13_MULTVINC numeric(18,6),
    VINSSFN numeric(18,6))
as
begin
  suspend;
end^

create or alter procedure RETORNA_DEPENDENCIAS_V_P_T (
    PRVIEW_PROC_TAB varchar(64))
returns (
    BDRETORNO varchar(64))
as
declare variable WAUX integer;
BEGIN
  for select distinct(TRIM(DEP))
    from (--Dependências de views/procedures/tabelas - RDB$DEPENDENCIES
    select RDB$DEPENDED_ON_NAME as DEP
    from RDB$DEPENDENCIES
    where trim(RDB$DEPENDENT_NAME) = :PRVIEW_PROC_TAB and
          RDB$DEPENDENT_TYPE in (0, 1, 5)
    union all
    --Dependências de campos e campos computados - RDB$DEPENDENCIES
    select RDB$RELATION_NAME as DEP
    from RDB$RELATION_FIELDS
    inner join(select RDB$FIELD_NAME
               from RDB$FIELDS
               inner join(select RDB$DEPENDED_ON_NAME, RDB$DEPENDENT_NAME
                          from RDB$DEPENDENCIES
                          where (upper(RDB$DEPENDENT_NAME) = upper(:PRVIEW_PROC_TAB)) and
                                (RDB$DEPENDENT_TYPE in (3, 9))) DEP on DEP.RDB$DEPENDED_ON_NAME = RDB$FIELDS.RDB$FIELD_NAME) F on F.RDB$FIELD_NAME = RDB$RELATION_FIELDS.RDB$FIELD_SOURCE
    union all
    --Dependências de FKs - RDB$RELATION_CONSTRAINTS
    select distinct(RC2.RDB$RELATION_NAME) as DEP
    from RDB$RELATION_CONSTRAINTS RC2
    inner join(select RDB$INDICES.*
               from RDB$INDICES
               inner join(select *
                          from RDB$RELATION_CONSTRAINTS
                          where RDB$RELATION_NAME = :PRVIEW_PROC_TAB and
                                RDB$CONSTRAINT_TYPE = 'FOREIGN KEY') RC on RDB$INDICES.RDB$INDEX_NAME = RC.RDB$INDEX_NAME) RI on RC2.RDB$INDEX_NAME = RI.RDB$FOREIGN_KEY)
    where TRIM(DEP) <> TRIM(:PRVIEW_PROC_TAB)
  INTO BDRETORNO do
    SUSPEND;
END^

create or alter procedure RETORNACAMPOSDEFK (
    PRFKNAME varchar(1000))
returns (
    BDRETORNO varchar(1000))
as
declare variable WAUX integer;
BEGIN
  select list(trim(I.rdb$field_name),',') from (select RDB$FIELD_NAME, RDB$FIELD_POSITION, RDB$INDEX_NAME from rdb$index_segments ORDER BY 1,2) I
  inner join rdb$relation_constraints on I.RDB$INDEX_NAME = rdb$relation_constraints.rdb$index_name
  WHERE rdb$relation_constraints.RDB$CONSTRAINT_NAME = :PRFKNAME
  INTO BDRETORNO;

  SUSPEND;
END^

create or alter procedure RETORNAFKPARACAMPO (
    PRTABELA varchar(1000),
    PRCAMPO varchar(1000))
returns (
    BDRETORNO varchar(1000))
as
declare variable WAUX integer;
BEGIN
  SELECT FIRST 1 RDB$RELATION_CONSTRAINTS.RDB$CONSTRAINT_NAME FROM RDB$RELATION_CONSTRAINTS
       INNER JOIN RDB$INDICES ON RDB$INDICES.RDB$FOREIGN_KEY = RDB$RELATION_CONSTRAINTS.RDB$CONSTRAINT_NAME
       WHERE RDB$INDICES.RDB$INDEX_NAME = 

       (select first 1 RDB$INDEX_SEGMENTS.RDB$INDEX_NAME  from RDB$INDEX_SEGMENTS
                          inner join(select RDB$INDEX_NAME
                                                 from RDB$RELATION_CONSTRAINTS RC
                                                 where RC.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' and RC.RDB$RELATION_NAME = TRIM(:PRTABELA)) RC1 on RC1.RDB$INDEX_NAME = RDB$INDEX_SEGMENTS.RDB$INDEX_NAME
                          where RDB$INDEX_SEGMENTS.RDB$FIELD_NAME = TRIM(:PRCAMPO))
                           
  INTO BDRETORNO;

  SUSPEND;
END^

create or alter procedure RETORNATABELAFKPARACAMPO (
    PRTABELA varchar(1000),
    PRCAMPO varchar(1000))
returns (
    BDRETORNO varchar(1000))
as
declare variable WAUX integer;
BEGIN


  SELECT FIRST 1 RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME FROM RDB$RELATION_CONSTRAINTS
       INNER JOIN RDB$INDICES ON RDB$INDICES.RDB$FOREIGN_KEY = RDB$RELATION_CONSTRAINTS.RDB$CONSTRAINT_NAME
       WHERE RDB$INDICES.RDB$INDEX_NAME = 
       (select first 1 RDB$INDEX_SEGMENTS.RDB$INDEX_NAME from RDB$INDEX_SEGMENTS
                          inner join(select RDB$INDEX_NAME
                                                 from RDB$RELATION_CONSTRAINTS RC
                                                 where RC.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' and RC.RDB$RELATION_NAME = :PRTABELA) RC1 on RC1.RDB$INDEX_NAME = RDB$INDEX_SEGMENTS.RDB$INDEX_NAME
                          where RDB$INDEX_SEGMENTS.RDB$FIELD_NAME = :PRCAMPO)
                           
  INTO BDRETORNO;

  SUSPEND;
END^

CREATE OR ALTER TRIGGER TMP_CAMPOS_TABELAS_FB_TEMP_BI0 FOR TMP_CAMPOS_TABELAS_FB_TEMP
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if ((position(ASCII_CHAR(10),NEW.bddescription) >0) or (position(ascii_char(13),new.bddescription)>0)) then
     begin
        if (position(ASCII_CHAR(10),NEW.bddescription) >0) then
           new.bddescricaogrid = substring(new.bddescription from 1 for position(ASCII_CHAR(10),NEW.bddescription)-1);
        else
           new.bddescricaogrid = substring(new.bddescription from 1 for position(ASCII_CHAR(13),NEW.bddescription)-1);
     end
  else
  begin
     new.bddescricaogrid = new.bddescription;
  end
end
^

create or alter procedure SP_VRH_CONSULTA_AUT_RPA (
    PRREF integer,
    PRRESULDADOS integer = null,
    PRSOLETRADO varchar(10000) = null)
returns (
    BDCODTER integer,
    BDCPFTER DM_CNPJ_CPF,
    BDNOMTER varchar(100),
    BDCPFMEITER varchar(14),
    BDPISTER varchar(14),
    BDSTATUSQC integer,
    BDENQSIMPLESFEDTER integer)
as
begin
 suspend;
end^

CREATE OR ALTER TRIGGER VSUC_EMPRESAS_TEXTRATOBAN_BI0 FOR VSUC_EMPRESAS_TEXTRATOBAN
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VRH_BASE_CONVENIO_OPER_BU0 FOR VRH_BASE_CONVENIO_OPERADORAS
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_EMP_TD400SAI FOR VEF_EMP_TD400SAI
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE VCHAVELAN INTEGER;
BEGIN
END
^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_TAJUICMSE115 (
    PRSESSAO integer,
    PRULTCHAVE integer)
as
BEGIN
end^

CREATE OR ALTER TRIGGER vrhf_emp_tverbafcint_biu0 for vrhf_emp_tverbafcint
active before insert or update position 0
AS
begin

end^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHACOMPINT_BI0 FOR VRHF_EMP_TFOLHACOMPINT
ACTIVE BEFORE INSERT POSITION 0
as
begin

end^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHACOMPINT_BU0 FOR VRHF_EMP_TFOLHACOMPINT
ACTIVE BEFORE UPDATE POSITION 0
as
begin

end^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLTOMCOMPINT_BIU0 FOR VRHF_EMP_TFOLTOMCOMPINT
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
as
begin

end^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLTOMCOMPINT_AU0 FOR VRHF_EMP_TFOLTOMCOMPINT
ACTIVE AFTER UPDATE POSITION 0
as
begin

end^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLTOMCOMPINT_AD0 FOR VRHF_EMP_TFOLTOMCOMPINT
ACTIVE AFTER DELETE POSITION 0
as
begin

end^

CREATE OR ALTER TRIGGER VRH_EMP_DCTFWEB_BIU0 FOR VRH_EMP_DCTFWEB
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
as
begin

end^

CREATE OR ALTER TRIGGER VRH_EMP_DCTFWEB_AD0 FOR VRH_EMP_DCTFWEB
ACTIVE AFTER DELETE POSITION 0
as
begin

end^

create or alter procedure VRHF_SP_TFOLHACOMPINT (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(28000),
    PRREFINICOMP integer,
    PRREFFIMCOMP integer,
    PRREFINIPAG integer,
    PRREFFIMPAG integer,
    PRAGRUPATOMADOR integer,
    PRTIPOFC integer = 0,
    PRSEPARCALC integer = 0,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(772) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDREFFN integer,
    BDREFFC integer,
    BDCODCONTTI integer,
    BDREFCOMP integer,
    BDDATAPAGFC date,
    BDDATABAIXAFC date,
    BDBFGTSFC numeric(15,6),
    BDFGTSFC numeric(15,6),
    BDFGTSCSFC numeric(15,6),
    BDBFGTS13FC numeric(15,6),
    BDFGTS13FC numeric(15,6),
    BDFGTS13CSFC numeric(15,6),
    BDMAIORREMFC numeric(15,6),
    BDBINSSFC numeric(15,6),
    BDALIQINSSFC numeric(15,6),
    BDINSSFC numeric(15,6),
    BDBIRRFFC numeric(15,6),
    BDALIQIRRFFC numeric(15,6),
    BDIRRFFC numeric(15,6),
    BDBINSS13FC numeric(15,6),
    BDALIQINSS13FC numeric(15,6),
    BDINSS13FC numeric(15,6),
    BDBIRRF13FC numeric(15,6),
    BDALIQIRRF13FC numeric(15,6),
    BDIRRF13FC numeric(15,6),
    BDBSALFAMFC numeric(15,6),
    BDSALFAMFC numeric(15,6),
    BDBRAISFC numeric(15,6),
    BDSALBASEFC numeric(15,6),
    BDDEPFC numeric(15,6),
    BDBASEPISFC numeric(15,6),
    BDBASEPISFEFC numeric(15,6),
    BDBASEPIS13FC numeric(15,6),
    BDBSALMATEMPFC numeric(15,6),
    BDSALMATEMPFC numeric(15,6),
    BDBRATAPOFC numeric(15,6),
    BDBRATAPOFEFC numeric(15,6),
    BDBRATAPO13FC numeric(15,6),
    BDBINSSFEFOLFC numeric(15,6),
    BDINSSFEFOLFC numeric(15,6),
    BDALIQINSSFEFOLFC numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDBFGTSFEFC numeric(15,6),
    BDFGTSFEFC numeric(15,6),
    BDCODTIPOFC integer,
    BDBINSSMVFC numeric(18,6),
    BDBINSSMV13FC numeric(18,6),
    BDINSSMVFC numeric(18,6),
    BDINSSMV13FC numeric(18,6),
    BDBINSSAPFC numeric(18,6),
    BDBINSS13APFC numeric(18,6),
    BDINSSAPFC numeric(18,6),
    BDINSS13APFC numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDINSSFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDLIQUIDOFC numeric(18,6),
    BDDATAGRRF date)
as
BEGIN
  SUSPEND;
END^

create or alter procedure VRHF_SP_TFOLHACOMP_INT (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(28000),
    PRREFINICOMP integer,
    PRREFFIMCOMP integer,
    PRREFINIPAG integer,
    PRREFFIMPAG integer,
    PRAGRUPATOMADOR integer,
    PRTIPOFC integer = 0,
    PRSEPARCALC integer = 0,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(772) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODCONTTI integer,
    BDORDEM integer,
    BDREFFN integer,
    BDREFFC integer,
    BDREFCOMP integer,
    BDDATAPAGFC date,
    BDDATABAIXAFC date,
    BDBFGTSFC numeric(15,6),
    BDFGTSFC numeric(15,6),
    BDFGTSCSFC numeric(15,6),
    BDBFGTS13FC numeric(15,6),
    BDFGTS13FC numeric(15,6),
    BDFGTS13CSFC numeric(15,6),
    BDMAIORREMFC numeric(15,6),
    BDBINSSFC numeric(15,6),
    BDALIQINSSFC numeric(15,6),
    BDINSSFC numeric(15,6),
    BDBIRRFFC numeric(15,6),
    BDALIQIRRFFC numeric(15,6),
    BDIRRFFC numeric(15,6),
    BDBINSS13FC numeric(15,6),
    BDALIQINSS13FC numeric(15,6),
    BDINSS13FC numeric(15,6),
    BDBIRRF13FC numeric(15,6),
    BDALIQIRRF13FC numeric(15,6),
    BDIRRF13FC numeric(15,6),
    BDBSALFAMFC numeric(15,6),
    BDSALFAMFC numeric(15,6),
    BDBRAISFC numeric(15,6),
    BDSALBASEFC numeric(15,6),
    BDDEPFC numeric(15,6),
    BDBASEPISFC numeric(15,6),
    BDBASEPISFEFC numeric(15,6),
    BDBASEPIS13FC numeric(15,6),
    BDBSALMATEMPFC numeric(15,6),
    BDSALMATEMPFC numeric(15,6),
    BDBRATAPOFC numeric(15,6),
    BDBRATAPOFEFC numeric(15,6),
    BDBRATAPO13FC numeric(15,6),
    BDBINSSFEFOLFC numeric(15,6),
    BDINSSFEFOLFC numeric(15,6),
    BDALIQINSSFEFOLFC numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDBFGTSFEFC numeric(15,6),
    BDFGTSFEFC numeric(15,6),
    BDCODTIPOFC integer,
    BDBINSSMVFC numeric(18,6),
    BDBINSSMV13FC numeric(18,6),
    BDINSSMVFC numeric(18,6),
    BDINSSMV13FC numeric(18,6),
    BDBINSSAPFC numeric(18,6),
    BDBINSS13APFC numeric(18,6),
    BDINSSAPFC numeric(18,6),
    BDINSS13APFC numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDINSSFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDLIQUIDOFC numeric(18,6),
    BDDATAGRRF date)
as
BEGIN
  SUSPEND;
end
^

CREATE OR ALTER trigger tol_vef_emp_tgiastger_ad0 for tol_vef_emp_tgiastger
ACTIVE AFTER DELETE POSITION 0
AS
begin

end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TPARIMP_AD0 FOR TOL_VEF_EMP_TPARIMP
ACTIVE AFTER DELETE POSITION 0
AS
begin

end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TCONTABAGRUPBAIXAPARC_AD0 FOR TOL_VEF_EMP_TCONTABAGRUPBAIXAPARC
ACTIVE AFTER DELETE POSITION 0
AS
begin
 
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TCONTABAGRUPBAIXAPARC_BI0 FOR TOL_VEF_EMP_TCONTABAGRUPBAIXAPARC
ACTIVE BEFORE INSERT POSITION 0
AS
begin

end^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVENTPARPGTO_AD0 FOR VEF_EMP_TMOVENTPARPGTO
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAIPARPGTO_AD0 FOR VEF_EMP_TMOVSAIPARPGTO
ACTIVE AFTER DELETE POSITION 0
AS
begin
  
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERPARPGTO_AD0 FOR VEF_EMP_TMOVSERPARPGTO
ACTIVE AFTER DELETE POSITION 0
AS
begin
  
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVF100PARPGTO_AD0 FOR VEF_EMP_TMOVF100PARPGTO
ACTIVE AFTER DELETE POSITION 0
AS
begin
  
end
^

CREATE OR ALTER trigger tol_vef_emp_tparimpenc_ad0 for tol_vef_emp_tparimpenc
active after delete position 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TPARIMPDARF_AD0 FOR TOL_VEF_EMP_TPARIMPDARF
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN

end^

CREATE OR ALTER TRIGGER TOL_TPARCELAIMPOSTOPGTO_AD0 FOR TOL_TPARCELAIMPOSTOPGTO
ACTIVE AFTER DELETE POSITION 0
AS
begin

end^


CREATE OR ALTER trigger tol_vef_emp_tmovent_ser_ad0 for tol_vef_emp_tmovent_ser
active after delete position 0
AS
BEGIN

END^

CREATE OR ALTER trigger tol_vsuc_emp_tapuracaocmv_ad0 for tol_vsuc_emp_tapuracaocmv
active after delete position 0
AS
begin
END^

CREATE OR ALTER TRIGGER VSUC_EMP_TPREPVARCAMBIAL_BI0 FOR VSUC_EMP_TPREPVARCAMBIAL
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN END^ 

CREATE OR ALTER TRIGGER TOL_VSUC_EMP_TVARCAMBIAL_AD0 FOR TOL_VSUC_EMP_TVARCAMBIAL
ACTIVE AFTER DELETE POSITION 0
AS BEGIN END^ 

CREATE OR ALTER trigger vfin_esc_tcobrancautomatica_bi0 for vfin_esc_tcobrancautomatica
active before insert position 0
AS
begin
end^

CREATE OR ALTER TRIGGER vef_base_tcadinfcom_bu0 FOR vef_base_tcadinfcom
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN

END^

CREATE OR ALTER TRIGGER tmp_vef_emp_tc500sai_temp_bu0 FOR tmp_vef_emp_tc500sai_temp
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER vef_base_tcadinfcom_bi0 FOR vef_base_tcadinfcom
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VEF_BASE_TCADINFCOM_BD0 FOR vef_base_tcadinfcom
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER vef_base_tcadinfcom_bu0 FOR vef_base_tcadinfcom
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER trigger VEF_EMP_TMOVOPIMOBI_F200_BI for VEF_EMP_TMOVOPIMOBILIARIA_F200
active before insert position 0
AS
BEGIN
END^

create or alter trigger VEF_EMP_TMOVEXP_BU0 for VEF_EMP_TMOVEXP
active before update position 0
AS
BEGIN
END^

create or alter trigger VEF_EMP_TMOVEXP_BI0 for VEF_EMP_TMOVEXP
active before insert position 0
AS
BEGIN
END^

create or alter trigger VEF_EMP_TMOVFINI100_BU0 for VEF_EMP_TMOVFINI100
active before update position 0
AS
BEGIN
END^

create or alter trigger VEF_EMP_TMOVFINI100_BI0 for VEF_EMP_TMOVFINI100
active before insert position 0
AS
BEGIN
END^

create or alter trigger VEF_EMP_TMOVOREC_BU0 for VEF_EMP_TMOVOREC
active before update position 0
AS
BEGIN
END^

create or alter trigger VEF_EMP_TMOVOPIMOBILIARIA_F200_BU0 for VEF_EMP_TMOVOPIMOBILIARIA_F200
active before update position 0
AS
BEGIN
END^

CREATE OR ALTER trigger tmp_vef_base_tlog_temp_bi0 for tmp_vef_base_tlog_temp
active before insert position 0
AS
begin
end^

CREATE OR ALTER TRIGGER VEF_EMP_TPARIMPPAR_BI0 FOR VEF_EMP_TPARIMPPAR
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN

END^

CREATE OR ALTER TRIGGER VEF_EMP_TPARIMPDARF_AD0 FOR VEF_EMP_TPARIMPDARF
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN

END^

CREATE OR ALTER TRIGGER VEF_EMP_TPARIMPDARF_AI0 FOR VEF_EMP_TPARIMPDARF
ACTIVE AFTER INSERT POSITION 0
AS
BEGIN

END^

CREATE OR ALTER TRIGGER TPARCELAIMPOSTOPGTO_AD0 FOR TPARCELAIMPOSTOPGTO
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN

END^

CREATE OR ALTER TRIGGER TPARCELAIMPOSTOPGTO_AI0 FOR TPARCELAIMPOSTOPGTO
ACTIVE AFTER INSERT POSITION 0
AS
BEGIN

END^

create or alter procedure SP_ATU_FGTS_CONT_FC_INT (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFERENCIA integer,
    PRREFCOMP integer,
    PRCODCONTTI integer,
    PRORDEM integer,
    PRVALOR numeric(15,6),
    PRFORMULA varchar(100),
    PRVALORANT numeric(15,6))
as
BEGIN

END^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHACOMPINT_AU0 FOR VRHF_EMP_TFOLHACOMPINT
ACTIVE AFTER UPDATE POSITION 0
AS
BEGIN

END^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHACOMPINT_AD0 FOR VRHF_EMP_TFOLHACOMPINT
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN

END^


CREATE OR ALTER TRIGGER VRHF_EMP_TFOLTOMCOMPINT_BIU0 FOR VRHF_EMP_TFOLTOMCOMPINT
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
BEGIN

END^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLTOMCOMPINT_AU0 FOR VRHF_EMP_TFOLTOMCOMPINT
ACTIVE AFTER UPDATE POSITION 0
AS
BEGIN

END^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLTOMCOMPINT_AD0 FOR VRHF_EMP_TFOLTOMCOMPINT
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN

END^

create or alter procedure SP_VRHF_RETORNA_TOMADOR (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDREFTOMADOR integer,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_RETORNA_TOMADOR_AUT (
    PREMP varchar(15000),
    PRAUT varchar(32000),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODTER integer,
    BDREF integer,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_RETORNA_TOMADOR_13 (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF13 integer,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_RETORNA_TOMADOR_INT (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODCONTTI integer,
    BDORDEM integer,
    BDREFTOMADOR integer,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_RETORNA_TOMADOR_A13 (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRREF integer,
    PRDATAINICIAL date = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFA13 integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_RETORNA_TOMADOR_FA (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRREF integer,
    PRDATAINICIAL date = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDCODTCA integer,
    BDDATAFA date,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_RETORNA_TOMADOR_FER (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRREF integer,
    PRDATAINICIAL date = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHF_RETORNA_TOMADOR_AD (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRREF integer,
    PRDATAINICIAL date = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDDATAAD date,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
begin
  suspend;
end^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIAST (
    PRCODEMP VARCHAR(10000),
    PRANOMESINICIAL INTEGER,
    PRANOMESFINAL INTEGER,
    PRCODPERIODO VARCHAR(1000),
    PRCODQUADRO INTEGER,
    PRUF INTEGER)
RETURNS (
    BDCODTIPO INTEGER,
    BDSIGLAUF VARCHAR(2),
    BDCODUF INTEGER,
    BDCLASSIFICACAO VARCHAR(10),
    BDNUMITEM INTEGER,
    BDVALOR NUMERIC(18,6),
    BDDESCQGIAST VARCHAR(150),
    BDCODQUADRO INTEGER,
    BDCODPERIODO INTEGER,
    BDREFERENCIA INTEGER,
    BDCODCONFGIAST INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCODEMP INTEGER,
    BDDESCFORM VARCHAR(150),
    BDNUMCAMPO INTEGER)
AS
DECLARE VARIABLE PRQUADROANT INTEGER;
DECLARE VARIABLE PRNUMCAMPO INTEGER;
DECLARE VARIABLE WVALOR NUMERIC(18,6);
DECLARE VARIABLE PRDESCFORM VARCHAR(150);
DECLARE VARIABLE WUFANT INTEGER;
DECLARE VARIABLE WREFANT INTEGER;
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
 SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_GIAST (
    PRCODEMP INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRARQUIVO VARCHAR(260))
AS
DECLARE VARIABLE WSQL VARCHAR(3100);
DECLARE VARIABLE WCFOP VARCHAR(200);
DECLARE VARIABLE WLINHA BLOB SUB_TYPE 1 SEGMENT SIZE 200 CHARACTER SET UTF8;
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_AJU_E111_E113_AUTO_PR (
    PRCODEMP INTEGER,
    PRORDEME111 INTEGER,
    PRREFLAN INTEGER,
    PRREFSIS INTEGER,
    PRCODPERIODO INTEGER)
AS
DECLARE VARIABLE WBDCREDPRESUMIDO VARCHAR(5);
DECLARE VARIABLE WOPINTERNA NUMERIC(7,4);
DECLARE VARIABLE WOPINTER12 NUMERIC(7,4);
DECLARE VARIABLE WOPINTER7 NUMERIC(7,4);
DECLARE VARIABLE WOPSP NUMERIC(7,4);
BEGIN
END^

CREATE OR ALTER TRIGGER vef_dashboard_info_enviados_bi0 FOR vef_dashboard_info_enviados
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER vef_dashboard_tincon_bi0 FOR vef_dashboard_tinconsistencia
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER vef_dashboard_tarquivo_bi0 FOR vef_dashboard_tarquivo
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER TPERSONALIZACAO_BD0 FOR TPERSONALIZACAO
ACTIVE BEFORE DELETE POSITION 0
AS
begin
end
^
create or alter  trigger vtpo_atividade_exe_qtd_bi0 for vtpo_atividade_exe_qtd
active before insert position 0
AS
begin
end^

CREATE OR ALTER TRIGGER TPERSONALIZACAO_BU0 FOR TPERSONALIZACAO
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER trigger tmensagens_email_bi0 for tmensagens_email
active before insert position 0
AS
begin
end^


CREATE OR ALTER trigger tol_vef_emp_tapue316_ad0 for tol_vef_emp_tapue316
active after delete position 0
AS
begin
end^

CREATE OR ALTER trigger tol_vef_emp_tapue250_ad0 for tol_vef_emp_tapue250
active after delete position 0
AS
begin
end^

CREATE OR ALTER TRIGGER TMP_VSUC_EMPRESAS_TLAN_TEMP_BU0 FOR TMP_VSUC_EMPRESAS_TLAN_TEMP
ACTIVE BEFORE UPDATE POSITION 0
AS  
begin
end
^

CREATE OR ALTER procedure SP_EXPORTAR_LOG_SCHIP (
    PRCODAGENDAMENTO integer,
    PRCODEMP integer,
    PRCODPLANOSCHIP integer,
    PRORDEMAGENDAMENTO integer,
    PRLOCAL varchar(255))
returns (
    BDFILE varchar(255))
as
begin
  SUSPEND;
end^

CREATE OR ALTER procedure SP_VTPO_ADD_ACESSO_TELA (
    PRCODEMP integer,
    PRUSUARIO integer,
    PRDATA date,
    PRSISTEMA integer,
    PRNOMETELA varchar(1000))
as
begin

end^

create or alter procedure VTIPO_IMPORTA_PLANILHA (
    PIMPORTARTIMEOUT boolean)
returns (
    CALCULATEDRELEASETIMEOUT integer,
    OLDBDCHAVE integer,
    NEWBDCHAVE integer)
as
declare variable VBDCHAVE integer;
declare variable VBDCODUSU integer;
declare variable VBDCODEMP integer;
declare variable VBDCODATI integer;
declare variable VBDDATAINI date;
declare variable VBDHORAINI time;
declare variable VBDDATAFIN date;
declare variable VBDHORAFIN time;
declare variable VBDOBSERVACAO varchar(1000);
declare variable VBDCODSIS integer;
declare variable VBDTIPOREGISTRO integer;
declare variable VBDTEMPO integer;
declare variable VCALCULATEDRELEASETIMEOUT integer;
declare variable VBDTIMEOUT smallint;
BEGIN
 suspend;
End^


create or alter procedure SP_COMMIT_IMP_LANC_CONTABIL (PRSESSAO integer)
as
begin
end^

create or alter procedure SP_ATUALIZAR_TMP_VSUC_TLAN(
    PRSESSAO integer,
    PREMPRESA integer,
    PRULTCHAVE integer,
    PRIDTERMINAL integer,
    PRVERIFICADUPLICADO integer)
as
begin
end^

create or alter procedure SP_ATU_TMP_VSUC_COMPL_ASTERISCO (
    PRSESSAO integer)
as
begin
end^

create or alter procedure SP_ATUALIZAR_TMP_VSUC_TLCC (
    PRSESSAO integer,
    PREMPRESA integer,
    PRULTCHAVE integer,
    PRIDTERMINAL integer)
as
begin
end^

create or alter procedure SP_ATUALIZAR_TMP_VSUC_TLPR (
    PRSESSAO integer,
    PREMPRESA integer,
    PRULTCHAVE integer,
    PRIDTERMINAL integer)
as
begin
end^

create or alter procedure SP_VRHF_REL_ACOMPANHAMENTO (
    PRCODEMP varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXAFILIAIS smallint = 0)
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDCOMPETENCIA integer,
    BDDATABASEEMP varchar(20),
    BDTRIBUTACAO varchar(200),
    BDTOTSAL numeric(18,2),
    BDTOTSALMENOR numeric(18,2),
    BDTOTSALPRO numeric(18,2),
    BDTOTSALSERV numeric(18,2),
    BDTOTARRED numeric(18,2),
    BDTOTDESC numeric(18,2),
    BDTOTDESCMENOR numeric(18,2),
    BDTOTDESCPRO numeric(18,2),
    BDTOTDESCSERV numeric(18,2),
    BDLIQFERIAS numeric(18,2),
    BDLIQRESC numeric(18,2),
    BDLIQSERV numeric(18,2),
    BDLIQUIDO numeric(18,2),
    BDFGTS numeric(18,2),
    BDFGTSMENOR numeric(18,2),
    BDGRRF numeric(18,2),
    BDGRRF40 numeric(18,2),
    BDGRRF20 numeric(18,2),
    BDGRRF10 numeric(18,2),
    BDCONTSIND numeric(18,2),
    BDCONTCONF numeric(18,2),
    BDMENSSALSIND numeric(18,2),
    BDTAXAASSIST numeric(18,2),
    BDREVERSAL numeric(18,2),
    BDSUBPAT numeric(18,2),
    BDSUBCONJ numeric(18,2),
    BDATIVOSMESANT integer,
    BDADMISSOES integer,
    BDRESCISOES integer,
    BDDATAMESANT date,
    BDULTDIAMES date)
as
begin
  SUSPEND;
end^

CREATE OR ALTER procedure VEF_SP_PLANO_TROCA_LISTA_CFOPS (
    PRPLANO integer,
    PRCHAVE integer)
returns (
   bdcodplatroca INTEGER,
   BDCHAVE INTEGER,
   BDCFOPS varchar(32765)
    )
as
BEGIN
  SUSPEND;

END^


CREATE OR ALTER TRIGGER VSH_BASE_TAGENDAMENTO_PLANO_AD0 FOR VSH_BASE_TAGENDAMENTO_PLANO
ACTIVE AFTER DELETE POSITION 0
AS
begin
end^


CREATE OR ALTER TRIGGER VSH_EMP_TARQ_PROC_COL_BU0 FOR VSH_EMP_TARQUIVO_PROCESSO_COL
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end^

CREATE OR ALTER procedure SP_STATUS_PLANO_SCHIP (
    PRIDPROC varchar(19) not null)
returns (
    BDSTATUS varchar(10))
as
begin
 suspend;
end^

CREATE OR ALTER TRIGGER vsh_emp_tconf_imp_arq_bi0 FOR vsh_emp_tconferencia_imp_arq
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER vsh_emp_tconf_imposto_inc_bi0 FOR vsh_emp_tconf_imposto_inco
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER vsh_emp_tconfia_imposto_bu0 FOR vsh_emp_tconferencia_imposto
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER vsh_emp_tconia_imposto_bi0 FOR vsh_emp_tconferencia_imposto
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VSH_BASE_TTHREAD_BI0 FOR VSH_BASE_TTHREAD
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^


CREATE OR ALTER TRIGGER VSH_BASE_TPLANO_THREAD_BI0 FOR VSH_BASE_TPLANO_THREAD
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^


CREATE OR ALTER TRIGGER VSH_BASE_TIPO_TPROCESSO_BI0 FOR VSH_BASE_TIPO_TPROCESSO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^


CREATE OR ALTER TRIGGER vsh_emp_tconfempresas_bu0 FOR vsh_emp_tconfempresas
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end^


CREATE OR ALTER TRIGGER vsh_emp_tconfempresas_bi0 FOR vsh_emp_tconfempresas
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER procedure SP_COPIAR_CONF_SCHIP (
    PRCODEMPORI integer,
    PRCODSISORI integer,
    PRCODEMPDEST integer)
as
begin
end^

CREATE OR ALTER procedure SP_GET_STATUS_NOTIFICACAO_SCHIP (
    PRCODEMP integer,
    PRCODSIS integer)
returns (
    BDCODSTATUS integer)
as
begin
 suspend;
end^

create or alter procedure GETPRIVILEGIOSEMPRESAS_SCHIP (
    PRCODEMP integer,
    PRPRIVILEGIO varchar(200),
    PRCODSIS integer)
returns (
    BDCODEMP integer,
    BDCODGRUPO integer,
    BDCODUSU integer,
    BDITEMPRIV varchar(200))
as
declare variable WCOUNT integer;
declare variable WSQL varchar(2000);
declare variable WCOUNTGRP integer;
declare variable WCOUNTUSU integer;
declare variable WSQLX varchar(2000);
BEGIN
  SUSPEND;
END^

CREATE OR ALTER TRIGGER vsh_base_tagendamento_bi0 FOR vsh_base_tagendamento
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VSH_BASE_TAGENDAMENTO_BD0 FOR VSH_BASE_TAGENDAMENTO
ACTIVE BEFORE DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VSH_BASE_TPLANO_BD0 FOR VSH_BASE_TPLANO
ACTIVE BEFORE DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TOL_VEF__TMOVRATREDZVARCFOP_AD0 FOR TOL_VEF_EMP_TMOVRATREDZVARCFOP
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VSH_EMP_TLOG_PROCESSO_BI0 FOR VSH_EMP_TLOG_PROCESSO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VSH_EMP_TCONFERENCIA_FOLHA_BI0 FOR VSH_EMP_TCONFERENCIA_FOLHA
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VSH_EMP_TCONFERENCIA_FOLHA_BU0 FOR VSH_EMP_TCONFERENCIA_FOLHA
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VRH_EMP_TOCORRENCIA_COL_BI0 FOR VRH_EMP_TOCORRENCIA_COL
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VSH_EMP_TARQUIVO_PROCESSO_BI FOR VSH_EMP_TARQUIVO_PROCESSO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VSH_EMP_TARQUIVO_PROCESSO_BU0 FOR VSH_EMP_TARQUIVO_PROCESSO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER procedure SP_GET_ORDEM_SEQ_PLANO_SCHIP (
    PRCODAGENDAMENTO integer,
    PRCODPLANOSCHIP integer)
returns (
    BDORDEMEXECUCAO integer)
as
begin
  SUSPEND;
end^

CREATE OR ALTER TRIGGER vsh_base_tagendamento_bu0 FOR vsh_base_tagendamento
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end^

CREATE OR ALTER trigger vef_emp_tajuicmsste316_bi0 for vef_emp_tajuicmsste316
active before insert position 0
AS
BEGIN
END
^

create or alter procedure SP_VSH_PODE_INICIAR_PROCESSO (
    PRCODAGENDAMENTO integer,
    PRCODPLANOSCHIP integer,
    PRREFPROC integer,
    PRCODAUTOTHREAD integer,
    PRCODEMP integer)
returns (
    BDPODEEXECUTAR DM_BOOLEAN)
as
begin
  suspend;
end^

CREATE OR ALTER procedure SP_FILA_PROCESSOS_SCHIP
as
begin

end^

create or alter procedure PADRONIZA_TEXTO (
    PRTEXTO varchar(100))
returns (
    BDRESULT varchar(100))
as
begin
 suspend;
end^

create or alter procedure SP_ATUALIZA_NOME_PARTICIPANTES (
    PRREFERENCIA integer,
    PRTIPO integer,
    PRTODASREF varchar(5))
as
begin

end^

CREATE OR ALTER procedure SP_PROX_DIA_DA_SEMANA (
    PRDATA date,
    PRWEEKDAY char(7))
returns (
    BDDATA date)
as
begin
  SUSPEND;
end^

CREATE OR ALTER procedure SP_INSERIR_TEMPO (
    PRTABELA_TEMP varchar(5),
    PRCODEMP integer = null,
    PRCODUSU integer = null,
    PRCODATI integer = null,
    PRDATAHORAINI timestamp = null,
    PRDATAHORAFIN timestamp = null,
    PRCODSIS integer = null,
    PRNOMETELA varchar(100) = null,
    PRCAPTION varchar(150) = null,
    PRTIPOREGISTRO integer = null)
as begin end^


CREATE OR ALTER procedure SP_CRIA_REFERENCIA_CLIENTES_REF (
    PRCODCLI integer,
    PRAAAAMM integer)
as
declare variable WTABELA varchar(300);
declare variable WSQL varchar(5000);
declare variable WCAMPOS_TAB varchar(3000);
declare variable WCAMPO varchar(300);
declare variable WREFCLI integer;
begin

end^

CREATE OR ALTER TRIGGER TMP_VTPO_ATIVIDADE_EXE_REG_BI0 FOR TMP_VTPO_ATIVIDADE_EXE_REGISTRO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

create or alter procedure SP_VAL_GPS_PROV_13 (
    PRREFERENCIA integer,
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000))
returns (
    BDREFERENCIA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODTER integer,
    BDTIPOIMPOSTO integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(15,6),
    BDTERCFN numeric(15,6),
    BDRATFN numeric(15,6),
    BDRATAPOFN numeric(15,6),
    BDINSS13 numeric(15,6),
    BDTERC13 numeric(15,6),
    BDRAT13 numeric(15,6),
    BDRATAPO13 numeric(15,6),
    BDINSS13IND numeric(15,6),
    BDTERC13IND numeric(15,6),
    BDRAT13IND numeric(15,6),
    BDRATAPO13IND numeric(15,6),
    BDINSSC13 numeric(15,6),
    BDTERCC13 numeric(15,6),
    BDRATC13 numeric(15,6),
    BDRATAPOC13 numeric(15,6),
    BDINSSPBM13 numeric(15,6))
as
BEGIN
  SUSPEND; 
END
^

CREATE OR ALTER procedure SP_CONVERTE_COD_VERB_DASHBOARD (
    BDCODVER integer,
    BDCLAVER varchar(20),
    BDGRUPOCLA integer)
returns (
    BDVERBA integer)
AS
BEGIN
  SUSPEND;
END^

create or alter procedure SP_VAL_GPS_PROV_FER (
    PRREFERENCIA integer,
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000))
returns (
    BDREFERENCIA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODTER integer,
    BDTIPOIMPOSTO integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(15,6),
    BDTERCFN numeric(15,6),
    BDRATFN numeric(15,6),
    BDRATAPOFN numeric(15,6),
    BDINSSPBMFN numeric(15,6),
    BDINSSREONERACAOFN numeric(15,6))
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER procedure SP_VFIN_GETSQL_COBRAR_SOBRE (
    BDCODCOBSERV integer,
    BDCODEMP integer,
    BDREFATUAL integer)
returns (
    WSQLAUX varchar(3000))
as
declare variable WDATAINI date;
declare variable WDATAFIN date;
declare variable WFILIAIS varchar(500);
begin
 suspend;
end^

CREATE OR ALTER procedure SP_VFIN_GERARCONFIGIMP
as
declare variable VCODESC integer;
declare variable VCODCLI integer;
declare variable VCHAVEFATURA integer;
declare variable VCODOBRSER integer;
declare variable VPERINSS numeric(15,4);
declare variable VUSARPERISS integer;
declare variable VRETIR varchar(5);
declare variable VRETCSLL varchar(5);
declare variable VRETCOF varchar(5);
declare variable VRETPIS varchar(5);
declare variable VRETIMP integer;
declare variable VDESTIR varchar(5);
declare variable VDESTCSLL varchar(5);
declare variable VDESTPIS varchar(5);
declare variable VDESTCOF varchar(5);
declare variable VCALCINSS varchar(5);
declare variable VPERCOF numeric(15,4);
declare variable VPERPIS numeric(15,4);
declare variable VPERCSLL numeric(15,4);
declare variable VPERIRRF numeric(15,4);
declare variable VDEDISS varchar(5);
declare variable VPERISS numeric(15,4);
declare variable VCODESCNEW integer;
declare variable VCODCLINEW integer;
declare variable VREFCONFIGNEW integer;
declare variable VDESTRETINSSNEW integer;
declare variable VPERINSSNEW numeric(15,4);
declare variable VDESTRETIRRFNEW integer;
declare variable VPERIRRFNEW numeric(15,4);
declare variable VDESTRETCSLLNEW integer;
declare variable VPERCSLLNEW numeric(15,4);
declare variable VDESTRETPISNEW integer;
declare variable VPERPISNEW numeric(15,4);
declare variable VDESTRETCOFINSNEW integer;
declare variable VPERCOFINSNEW numeric(15,4);
declare variable VDESTIBSESTADUALNEW integer;
declare variable VDESTIBSMUNICIPALNEW integer;
declare variable VDESTCBSNEW integer;
declare variable VDESTRETISSNEW integer;
begin
  
end^

CREATE OR ALTER procedure SP_VFIN_COBRAR_SOBRE (
    PREMPRESAS varchar(100),
    PRCLIENTES varchar(3000),
    PRCODSERV integer,
    PRREFINI integer,
    PRREFFIN integer)
as
declare variable WSQL varchar(10000);
declare variable WWHERE varchar(3000);
declare variable WSQLAUX varchar(2000);
declare variable WBDCODCLI integer;
declare variable WBDCODESC integer;
declare variable WBDCHAVESERFIX integer;
declare variable WBDORDEMSERFIX integer;
declare variable WBDREFINI integer;
declare variable WBDREFFIN integer;
declare variable WBDQTDSERFIX numeric(15,2);
declare variable WBDVLRUNITSERFIX numeric(15,2);
declare variable WBDCODCOBSERV integer;
declare variable WBDDESCSERFIX integer;
declare variable WBDTIPDESC integer;
declare variable WQTDSERVFIX numeric(15,2);
declare variable WREFATUAL integer;
declare variable WREFINI integer;
declare variable WCODESC_REF integer;
declare variable WCODCLI_REF integer;
declare variable WCHAVESERFIX_REF integer;
declare variable WORDEMSERFIX_REF integer;
declare variable WCHAVEREF_REF integer;
declare variable WVALOR_ATE numeric(15,2);
declare variable WVALOR_APOS numeric(15,2);
declare variable WLIMITE_LANC integer;
declare variable WCOBRAEXCED varchar(5);
declare variable WORDEM_FILHO integer;
declare variable WNOVA_ORDEM integer;
declare variable WCODEMP integer;
begin

end^

create or alter procedure SP_EMPRESAS_USU (
    PREMP integer = 0)
returns (
    BDCODEMP integer)
as
begin
  suspend;
end^

CREATE OR ALTER PROCEDURE SP_MUDA_TIPO_COLCON(
  premp INTEGER,
  prcol INTEGER,
  prcontrcol INTEGER)
AS
BEGIN

END^

CREATE OR ALTER procedure SP_SET_MASK (
    PRMASK varchar(50),
    PRSTR varchar(255))
returns (
    BDRESULT varchar(255))
as
begin
  SUSPEND;
END^

CREATE OR ALTER procedure SP_GRAVAR_DAO (
    PRSESSAO integer,
    PRTABLENAMEPHYSICIST varchar(64),
    PRTABLEINCON VARCHAR(64),
    PRKEYFIELD VARCHAR(64) = 'BDCHAVE')
returns (
    WSQL varchar(2555))
as
BEGIN
  SUSPEND;
END^

create or alter procedure SP_MEMCALCULO_PLANO_1250 (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer,
    PRCODUF integer = 23)
as
declare variable PRREFERENCIA integer;
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WCODPROD integer;
declare variable WVLRICMSOPPRESUMIDO DM_NUMERIC_15_2;
declare variable WVLRICMSSTPRESUMIDO DM_NUMERIC_15_2;
BEGIN
END^

create or alter procedure SP_DEVOLUCOES_PLANO_1250 (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer,
    PRCODUF integer = 23)
as
declare variable WREFERENCIA integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WORDEMPROD integer;
declare variable WBDREFLAN integer;
declare variable WVLRICMSOPPRESUMIDO DM_NUMERIC_15_2;
declare variable WVLRICMSSTPRESUMIDO DM_NUMERIC_15_2;
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_INSEREREG_PLANO_1250 (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WORDEMPRO integer;
declare variable WCODPROD integer;
declare variable WMOTIVO integer;
declare variable WQUANTIDADE integer;
declare variable WVLRUNIT DM_NUMERIC_15_2;
declare variable WVLRUNITICMSEFETIVO DM_NUMERIC_15_2;
declare variable WICMSOPPRESUMIDO DM_NUMERIC_15_2;
declare variable WICMSSTPRESUMIDO DM_NUMERIC_15_2;
declare variable WVLRRESTITUIR DM_NUMERIC_15_2;
declare variable WVLRCOMPLEMENTAR DM_NUMERIC_15_2;
declare variable WMODELO integer;
declare variable WSERIE integer;
declare variable WCHAVENFE integer;
declare variable WDTEMISSAO integer;
declare variable WNUMDOC integer;
declare variable WCHAVEC113 integer;
declare variable WCODUNIMED integer;
declare variable WVLRUNITFCPESTOQUE DM_NUMERIC_15_2;
declare variable WVLRUNITICMSOP DM_NUMERIC_15_2;
declare variable WVLRUNITFCPRESTITUIR DM_NUMERIC_15_2;
declare variable WVLRUNITFCPCOMPLEMENTAR DM_NUMERIC_15_2;
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_REGISTROS_PLANO_1250 (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_GRAVA_PLANO_1250 (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER,
    PRCODUF INTEGER = 23)
AS
BEGIN
END^

CREATE OR ALTER procedure SP_APLICA_PLANO_1250 (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer)
as
declare variable WBDCHAVE integer;
declare variable WPLANO integer;
declare variable WNAOEFETUARRECAL DM_BOOLEAN;
declare variable WGERARAJUE220E111 DM_BOOLEAN;
declare variable WLANCAE220 DM_BOOLEAN;
declare variable WBDMODELO integer;
declare variable WBDCONSUFINAL integer;
declare variable WBDVARIASCFOPS integer;
declare variable WVARIASCSTS integer;
declare variable WTIPOEMP integer;
declare variable WBDTABELA57 integer;
declare variable WSQL varchar(5000);
declare variable WCODEMP integer;
declare variable WREFERENCIA integer;
declare variable WMOTIVO integer;
declare variable WNEGATIVO varchar(5);
declare variable WORDEM integer;
declare variable WVALOR numeric(15,2);
declare variable WVLRCREDICMSPROPRIO DM_NUMERIC_15_2;
declare variable WVLRICMSSTRETITUIR DM_NUMERIC_15_2;
declare variable WVLRUNITFCPSTRESTITUIR DM_NUMERIC_15_2;
declare variable WVLRUNITICMSSTCOMPLEMENTAR DM_NUMERIC_15_2;
declare variable WVLRUNITFCPSTCOMPLEMENTAR DM_NUMERIC_15_2;
declare variable WCODUF integer;
declare variable WCAMPOAPU varchar(8);
BEGIN
END^

create or alter procedure SP_APLICA_PLANO_1900_REDZ (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer,
    WBDCODSUBAPU integer,
    WBDCODAJU integer,
    WBDCODNAT integer,
    WBDVARIASCFOPS integer,
    WBDCODCSTICMS integer,
    WBDVARIOSNCMS integer,
    WPLANO integer,
    WBDCHAVE integer,
    WBDVLRAJU integer,
    WBDDESCCOMP varchar(255))
as
declare variable WSQL varchar(5000);
begin
end^

CREATE OR ALTER procedure SP_APLICA_PLANO_1900 (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer)
as
BEGIN

END^

CREATE OR ALTER procedure SP_MODELOCORRESPONDENTE1923 (
    PRMODELO integer)
returns (
    BDMODELO1923 integer)
as
BEGIN
  suspend;
end^

create or alter procedure SP_COMMIT_PLANO_1900 (
    PRSESSAO integer,
    PRCODEMP integer,
    PRCHAVE1921 integer)
as
BEGIN

END^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_1926 (
    PRSESSAO integer,
    PRSTRULTCHAVE varchar(60))
as
BEGIN

END^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_1923 (
    PRSESSAO integer,
    PRSESSAOTER integer,
    PRSESSAOPRO integer)
as
begin

END^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_1921 (
    PRSESSAO integer,
    PRSTRULTCHAVE varchar(60))
as
begin

END^

CREATE OR ALTER procedure SP_CODRECEXP (
    PRCODRECOF varchar(6),
    PRCODUF_REC integer,
    PRCODUF_EMP integer)
returns (
    BDCODRECEXP varchar(10))
as
declare variable WCODUF integer;
begin
  SUSPEND;
END^

create or alter procedure SP_APLICA_PLANO_CC_AUTO (
    PRMOVIMENTO varchar(4),
    PRCODEMP integer,
    PRREF integer,
    PRAPENASVERIFICARCC integer,
    PRWHERE varchar(5000),
    PRHUGEFILE integer,
    PRARQUIVO varchar(260),
    PREXCLUIRMESMOSEMAPLICAR integer)
returns (
    BDAPLICOU DM_BOOLEAN)
as
begin
  Suspend;
end^

CREATE OR ALTER procedure SP_EXPORTA_BLOCO1900 (
    PRCODEMP integer not null,
    PRDATAINI date not null,
    PRDATAFIM date not null,
    PRVALIDAREXPORTACAO DM_BOOLEAN not null,
    PRARQUIVO varchar(260) not null)
as
BEGIN

END^

create or alter procedure SP_VALORES_1920 (
  PRCODEMP INTEGER,
  PRCODPERIODO INTEGER,
  PRREFINI INTEGER,
  PRREFFIM INTEGER)
returns (
    BDCODQICMSSPED integer ,
    BDCODEMP integer ,
    BDCODPERIODO integer ,
    BDREFERENCIA integer ,
    BDCODSUBAPU integer ,
    BDVL_TOT_TRANSF_DEBITOS_OA DM_NUMERIC_15_2,
    BDVL_TOT_AJ_DEBITOS_OA DM_NUMERIC_15_2,
    BDVL_ESTORNOS_CRED_OA DM_NUMERIC_15_2,
    BDVL_TOT_TRANSF_CREDITOS_OA DM_NUMERIC_15_2,
    BDVL_TOT_AJ_CREDITOS_OA DM_NUMERIC_15_2,
    BDVL_ESTORNOS_DEB_OA DM_NUMERIC_15_2,
    BDVL_SLD_CREDOR_ANT_OA DM_NUMERIC_15_2,
    BDVL_SLD_APURADO_OA DM_NUMERIC_15_2,
    BDVL_TOT_DED DM_NUMERIC_15_2,
    BDVL_ICMS_RECOLHER_OA DM_NUMERIC_15_2,
    BDVL_SLD_CREDOR_TRANSP_OA DM_NUMERIC_15_2,
    BDDEB_ESP_OA DM_NUMERIC_15_2)
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER procedure SP_VALIDA_CPF_CNPJ (
    PRDOC DM_CNPJ_CPF)
returns (
    BDISVALID DM_BOOLEAN)
as
begin
  SUSPEND;
end^

create or alter procedure SP_VALIDA_EMAIL (
    PREMAIL DM_BDEMAIL)
returns (
    BDISVALID DM_BOOLEAN)
as
begin
  SUSPEND;
end^

CREATE OR ALTER procedure VSUC_SP_REL_CTA_MOVIMENTADA (
    PRCODPLAPADRAO integer,
    PRCTALONINI varchar(40),
    PRCTALONFIM varchar(40),
    PRDATINI date,
    PRDATFIN date,
    PRCONTABILIZACAO integer,
    PRPARTINI integer,
    PRPARTFIM integer,
    PRPART integer)
returns (
    BDCODPLAPADRAO integer,
    BDNOMEPLANOPADRAO varchar(80),
    BDCODTPLA integer,
    BDCTALON varchar(40),
    BDNOMCTA varchar(100),
    BDCODEMP integer,
    BDNOMEMP varchar(100),
    BDCHAVE integer,
    BDDATA date,
    BDDEBITO integer,
    BDCREDITO integer,
    BDVALOR numeric(15,2),
    BDCOMPL varchar(200),
    BDNOMEHIST varchar(200),
    BDCOMPLEMENTO blob sub_type 1 segment size 32700,
    BDTRANSACAO integer,
    BDCODTER integer,
    BDNOMETER varchar(200),
    BDPARTICIPANTE integer)
as
begin
  SUSPEND;
end^

CREATE OR ALTER procedure SP_AUDITOR_FISCAL (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRAUDITORIAREINF DM_BOOLEAN,
    PRCODINCONFORMIDADE integer = 0,
    PRREGVALIDAR varchar(100) = '',
    PRAUDITORIADOCS DM_BOOLEAN = '')
as
begin

end^

CREATE OR ALTER procedure SP_AUDITORIA_REINF (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRCODUSU integer,
    PRCODINCONFORMIDADE integer,
    PRREGVALIDAR varchar(100) = '')
as
begin

end^

CREATE OR ALTER procedure SP_AUDITORIA_REINF_R1000 (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer)
as
begin

end^
CREATE OR ALTER procedure SP_AUDITORIA_REINF_R2050 (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer)
as
begin

end^
CREATE OR ALTER procedure SP_AUDITORIA_REINF_R2055 (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer)
as
begin

end^
CREATE OR ALTER procedure SP_AUDITORIA_REINF_R2060 (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer)
as
begin

end^
CREATE OR ALTER procedure SP_AUDITORIA_REINF_R2010_2020 (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer)
as
begin

end^

CREATE OR ALTER procedure SP_AUDITORIA_DOCUMENTOS (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRCODUSU integer,
    PRCODINCONFORMIDADE integer,
    PRREGVALIDAR varchar(100) = '')
as
begin

end^

CREATE OR ALTER procedure SP_AUDITORIA_DOCS_GERAL (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRCODUSU integer,
    PRCODINCONFORMIDADE integer,
    PRDOCENT integer,
    PRDOCSAI integer,
    PRREGVALIDAR varchar(100) = '')
as
begin

end^

CREATE OR ALTER procedure SP_AUDITORIA_DOCS_MOVENT (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRCODUSU integer,
    PRCODINCONFORMIDADE integer,
    PRREGVALIDAR varchar(100) = '')
as
begin

end^

CREATE OR ALTER procedure SP_AUDITORIA_DOCS_MOVSAI (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRCODUSU integer,
    PRCODINCONFORMIDADE integer,
    PRREGVALIDAR varchar(100) = '')
as
begin

end^

CREATE OR ALTER procedure SP_AUD_DESC_DETALHADA_INCON (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer)
as
begin

end^


create or alter procedure SP_VRH_FAIXAS_PLANO_SAUDE (
    PRCODEMP varchar(25000),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDORDEM integer,
    BDIDADE integer,
    BDVALOR numeric(18,6))
as
begin
  suspend;
end^

create or alter procedure SP_INS_VRH_ESOCIAL_TLOTE_ARQUIV (
    PRCODEMP integer,
    PRSTATUS integer,
    PRDESCSTATUS varchar(300),
    PRTEMPOESTIMADO integer,
    PRPROTOCOLO varchar(50))
returns (
    BDCODLOTE integer)
as
begin
  suspend;
end^

CREATE OR ALTER trigger vaud_intranet_inc_bi0 for vaud_intranet_inconformidade
active before insert or update position 0
as
BEGIN
END^

CREATE OR ALTER procedure SP_VAUD_INTRANET_INCONFORMIDADE (
    PRDESCRICAO varchar(5000))
returns (
    BDACAO varchar(5000),
    BDDESCRICAO varchar(5000))
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER procedure SP_VRH_QUADRO_NOTURNO(
    PRCODPQUA integer,
    PRCODQH integer,
    PRHORAININOT time,
    PRHORAFIMNOT time,
    PRFIRST1 type of DM_BOOLEAN = 'TRUE')
returns (
    BDCODPQUA integer,
    BDCODQH integer,
    BDCODQHH integer,
    BDQHHSENT time,
    BDQHHSSAI time)
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER procedure SP_VAUD_PREAUD_INDHORARIONOT(
    PREMP varchar(15000))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATACOL date,
    BDINDHORARIONOT integer)
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER procedure SP_VRH_SINDREF_INDHORARIONOT(
    PRSINTRAB varchar(15000),
    BDREFST integer,
    PRUPDATE type of DM_BOOLEAN,
    PRSOMENTEVAZIO type of DM_BOOLEAN)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATACOL date,
    BDINDHORARIONOTANT integer,
    BDINDHORARIONOT integer)
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER procedure SP_VAUD_PREAUD_VERBAPADRAO
returns (
    BDCODVER integer,
    BDREFVER integer)
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER procedure SP_VAUD_PREAUD_TIPOJORNADA(
    PREMP varchar(15000))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATACOL date,
    BDTIPOJORNADA integer,
    BDTIPOJORNADAANT integer)
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER procedure SP_VAUD_PREAUD_VERBASEMINCID_IR
returns (
    BDCODVER integer,
    BDREFVER integer,
    BDCODINCIDIRRFANT integer,
    BDCODINCIDIRRF integer)
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER procedure SP_VAUD_PREAUD_VERBA_INSSFGTS
returns (
    BDCODVER integer,
    BDREFVER integer,
    BDCODINCIDINSSANT integer,
    BDCODINCIDINSS integer,
    BDCODINCIDFGTSANT integer,
    BDCODINCIDFGTS integer)
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER procedure VRH_SP_SOMA_FERIAS_RECIBO(
    PREMPRESA varchar(15000),
    PRCOLABORADOR varchar(30000),
    PRDATAGOZOINI date = null,
    PRDATAGOZOFIM date = null,
    PRDATAPAGINI date = null,
    PRDATAPAGFIM date = null,
    PRCODFE integer = null)
returns (
    BDCODEMP integer not null,
    BDCODCOL integer not null,
    BDINIPERAQUISFE date not null,
    BDCODFE integer not null,
    BDINIPERGOZOFE date,
    BDFIMPERAQUISFE date,
    BDFIMPERGOZOFE date,
    BDDATAPAGFE date,
    BDQTDGOZOFE numeric(18,6),
    BDQTDABONOFE numeric(18,6),
    BDSALDOINIFE numeric(15,6),
    BDSALDOFIMFE numeric(15,6),
    BDBASEIRFE numeric(15,6),
    BDALIQIRFE numeric(15,6),
    BDVALORIRFE numeric(15,6),
    BDBASEINSSFE numeric(15,6),
    BDALIQINSSFE numeric(15,6),
    BDVALORINSSFE numeric(15,6),
    BDDEPFE numeric(15,6),
    BDSALBASEFE numeric(15,6),
    BDSALBASEHEFE numeric(15,6),
    BDDATABAIXAFE date,
    BDCOLETIVASFE varchar(5),
    BDREFPAGABOFE integer,
    BDBASEFGTSFE numeric(15,6),
    BDVALORFGTSFE numeric(15,6),
    BDVALORFGTSCSFE numeric(15,6),
    BDMAIORREMFE numeric(15,6),
    BDBSALFAMFE numeric(15,6),
    BDSALFAMFE numeric(15,6),
    BDCOMPETENCIAFE varchar(7),
    BDFALTASFE numeric(15,6),
    BDFERIADOSFE integer,
    BDBASEIROUTFE numeric(15,6),
    BDVALORIROUTFE numeric(15,6),
    BDDEPIROUTFE numeric(15,6),
    BDESTPROVFE numeric(15,6),
    BDBASEPISFE numeric(15,6),
    BDBRATAPOFE numeric(15,6),
    BDCREDITOFE numeric(15,6),
    BDDEBITOFE numeric(15,6),
    BDLIQUIDO numeric(18,6),
    BDREFINIFE integer,
    BDREFFIMFE integer,
    BDCALCA13FE varchar(5),
    BDTIPOA13FE integer,
    BDPERCA13FE numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDDATAPROCFE date,
    BDHORAPROCFE time,
    BDORDEM integer,
    BDDATAAVISO date,
    BDSALDOFINALSINDFE numeric(18,6),
    BDDIASLICFE numeric(18,6),
    BDTEMPOSERVFE integer,
    BDVALSALMINVIGENTE numeric(18,6),
    BDENVIOUESOCIAL varchar(5),
    BDENVIOUPGTOESOCIAL varchar(5),
    BDIDDEMONSTRATIVO varchar(30),
    BDFOLHAAUTOMATICA DM_BOOLEAN,
    BDRECIBOESOCIAL varchar(30),
    BDCODEVT integer,
    BDCODEVTFIM integer,
    BDREFPAGFE integer,
    BDLIQUIDOA13 numeric(18,6),
    BDINIGOZORECIBOFE date,
    BDFIMGOZORECIBOFE date,
    BDQTDGOZORECIBOFE numeric(18,6),
    BDREFFERIAS integer)
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER procedure VRH_SP_SOMA_VERBA_FERIAS_RECIBO(
    PREMPRESA varchar(15000),
    PRCOLABORADOR varchar(30000),
    PRDATAGOZOINI date = null,
    PRDATAGOZOFIM date = null,
    PRCODVER integer = 0,
    PRDATAPAGINI date = null,
    PRDATAPAGFIM date = null,
    PRCODFE integer = null)
returns (
    BDCODEMP integer not null,
    BDCODCOL integer not null,
    BDINIPERAQUISFE date not null,
    BDINIGOZORECIBOFE date,
    BDCODFE integer not null,
    BDCODVER integer not null,
    BDREFVFE numeric(15,6),
    BDVALVFE numeric(15,6),
    BDIGNREFVFE varchar(5),
    BDIGNVALVFE varchar(5),
    BDREFAUXVFE numeric(15,6),
    BDORVERBAFE integer,
    BDVALIFE numeric(18,6),
    BDIGNREFAVFE varchar(5),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000))
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER procedure SP_ESOCIAL_TVINCULO_FOLHA (
    PRBDMULTIEMP varchar(5000),
    PRBDCODEMP integer,
    PRBDCODCOL integer,
    PRBDCODTER integer,
    PRBDREF integer,
    PRBDCODTIPO varchar(10))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODTER integer)
as
begin
  SUSPEND;
end^

CREATE OR ALTER procedure SP_CRIA_INCONF_S1010 (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCODEVT integer,
    PRTIPOEVT integer,
    PRREFEVT integer,
    PRCODVER integer)
as
declare variable WSQL varchar(5000);
declare variable WMSG varchar(380);
declare variable WCODEVT integer;
declare variable WSIGLA varchar(6);
declare variable WACAO varchar(200);
declare variable WCODCOL integer;
declare variable WCODTER integer;
declare variable WCODCOLAUX integer;
declare variable WCODUSU integer;
declare variable WNUMINC integer;
declare variable WEVTEXCLUIDO integer;
declare variable WTIPOEVT integer;
declare variable WSQLAUX varchar(5000);
declare variable WCHAVECAD varchar(40);
declare variable WREFSTR varchar(10);
begin
end
^

CREATE OR ALTER procedure SP_RETORNA_QTDECOLATIVOS (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDCODEMP integer,
    BDREF integer,
    BDATIVOS integer,
    BDADMIT integer,
    BDTRANSF integer,
    BDREINT integer,
    BDTOTAL integer,
    BDMEDIA numeric(9,2))
as
declare variable WSQL varchar(5000);
declare variable WATIVOS integer;
declare variable WADMIT integer;
declare variable WTRANSF integer;
declare variable WREINT integer;
declare variable WPRIDIA varchar(10);
declare variable WULTDIA varchar(10);
declare variable WREFATU integer;
declare variable WDIA integer;
declare variable WMES integer;
declare variable WANO integer;
declare variable WDIASTR varchar(2);
declare variable WSOMA integer;
declare variable WQTDE integer;
begin
 suspend;
end
^

CREATE OR ALTER TRIGGER TAGENDABACKUP_BD0 FOR TAGENDABACKUP
ACTIVE BEFORE DELETE POSITION 0
AS
begin
end
^


/* Trigger: TAGENDABACKUP_BI0 */
CREATE OR ALTER TRIGGER TAGENDABACKUP_BI0 FOR TAGENDABACKUP
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^


/* Trigger: TAGENDABACKUP_BU0 */
CREATE OR ALTER TRIGGER TAGENDABACKUP_BU0 FOR TAGENDABACKUP
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER trigger tr_bf_insert_tescritorio for tescritorio
active before insert or update position 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER vsh_emp_tlista_processos_bu0 FOR vsh_emp_tlista_processos
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER TDARFGERPGTO_AD0 FOR TDARFGERPGTO
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TINTEGRACAO_ARQ_CLIENTE_FILA_AD0 FOR TINTEGRACAO_ARQ_CLIENTE_FILA
ACTIVE AFTER DELETE POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VRHF_EMP_TPGTO_RURAL_AI0 FOR VRHF_EMP_TPGTO_RURAL
ACTIVE AFTER INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TPGTO_RURAL_AU0 FOR VRHF_EMP_TPGTO_RURAL
ACTIVE AFTER UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER tdarfgerpgto_rural_ai0 for tdarfgerpgto_rural
active after insert position 0
AS
begin
end
^

CREATE OR ALTER TRIGGER tdarfgerpgto_rural_au0 for tdarfgerpgto_rural
active after update position 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TDICIONARIO_REL_ESOCIAL_BI0 FOR TDICIONARIO_REL_ESOCIAL
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_ADMPREL_BI0 FOR VRH_EMP_TCOL_ADMPREL
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN

END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TNFPRODRURAL_BU0 FOR VRHF_EMP_TNFPRODRURAL
ACTIVE BEFORE UPDATE POSITION 0
AS
begin

end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TNFPRODRURAL_AD0 FOR VRHF_EMP_TNFPRODRURAL
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

create or alter trigger VFIN_ESC_TVINC_PAG_SERVIC_BI0 for VFIN_ESC_TVINC_PAG_SERVIC
active before insert position 0
as
declare variable VCODIGO integer;
begin
  
end^

CREATE or ALTER trigger vfin_esc_tconf_conta_contab_bi0 for vfin_esc_tconf_conta_contabil
active before insert position 0
as
declare variable VCODIGO integer;
begin
 
end^

CREATE or alter trigger vfin_esc_tvinc_desp_movent_bi0 for vfin_esc_tvinc_desp_movent
active before insert position 0
as
declare variable VCODIGO integer;
begin
  
end^

CREATE OR ALTER TRIGGER VSUC_BANCOS_PDF_BI0 FOR VSUC_BANCOS_PDF
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE WCODIGO INTEGER;
BEGIN

END^

CREATE OR ALTER procedure SP_AJUSTE_ISE_OUT (
    PRCODEMP integer,
    PRCHAVE integer,
    PRORDEM integer,
    PRTIPOLAN char(3),
    PRLANCAREM integer)
returns (
    BDVALORISE DM_NUMERIC_15_2,
    BDVALOROUT DM_NUMERIC_15_2)
as
BEGIN
 suspend;
END^

create or alter procedure SP_VRHF_EMP_TCOLCON_MVINC (
    PREMP varchar(25000),
    PRCOL varchar(32000),
    PRREF integer,
    PRTIPOCALC integer = -1)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDBASEINSSNCOL numeric(18,6),
    BDVALORINSSNCOL numeric(18,6),
    BDBASEIRRFNCOL numeric(18,6),
    BDVALORIRRFNCOL numeric(18,6),
    BDBASEINSS13COL numeric(18,6),
    BDVALORINSS13COL numeric(18,6),
    BDBASEIRRF13COL numeric(18,6),
    BDVALORIRRF13COL numeric(18,6))
as
begin
  --Comentário apenas para teste.
  suspend;
end^

create or alter procedure SP_VRHF_EMP_TCOLCON_MVINC_CALC (
    PREMP varchar(25000),
    PRCOL varchar(32000),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDTIPOCALC integer,
    BDBASEINSS numeric(18,6),
    BDVALORINSS numeric(18,6),
    BDBASEIRRF numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDCALCMVNOVO DM_BOOLEAN,
    BDCNPJEMP DM_CNPJ_CPF,
    BDCNPJRESP DM_CNPJ_CPF,
    BDCATEGORIAESOCIAL integer)
as
begin
  SUSPEND;
end^

create or alter procedure SP_VRHF_BASE_TTERC_MVINC_CALC (
    PREMP varchar(25000),
    PRCOL varchar(32000),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDBASEINSS numeric(18,6),
    BDVALORINSS numeric(18,6),
    BDBASEIRRF numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDCALCMVNOVO DM_BOOLEAN,
    BDCNPJEMP DM_CNPJ_CPF,
    BDCNPJRESP DM_CNPJ_CPF,
    BDCATEGORIAESOCIAL integer)
as
begin
  SUSPEND;
end^

CREATE OR ALTER procedure SP_ULTIMA_SITFINANCLI (
    PRDATAMICRO varchar(10),
    PRFILTROCONSULTA varchar(3000),
    PRCODCLIENTE varchar(2000),
    PRSITATUAL varchar(5))
returns (
    BDCODCLI integer,
    BDNOMCLI varchar(100),
    BDCHAVESITCLI integer,
    BDCODSITCLI integer,
    BDDESCSITCLI varchar(100),
    BDDATASITCLI date,
    BDSITTEMP varchar(5),
    BDDIASSITTEMP integer,
    BDBLOQCLI varchar(5),
    BDSITATUAL varchar(5))
AS
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_RETIRAR_CARACTER_ESP (
    PRSTR VARCHAR(255))
RETURNS (
    BDSTR VARCHAR(255))
AS
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_ECREDRURAL (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRFINALIDADE integer,
    PRCODPROTRANS integer,
    PRCODPROTELECOM integer,
    PREXPPRODUTOUNICO DM_BOOLEAN)
AS
BEGIN

END^

CREATE OR ALTER procedure SP_GET_EVT_FILA_ESOCIAL_V2 (
    PRCODEMP integer,
    PREXCLUSAO integer)
returns (
    BDCODIGO integer,
    BDCODEMP integer,
    BDCHAVE varchar(60),
    BDXML blob sub_type 0 segment size 80,
    BDCODTIPO integer,
    BDSTATUS integer,
    BDDATAEVENTO date,
    BDMOTIVO varchar(100),
    BDGRUPO integer,
    BDDATAININAOPERIOD date,
    BDDATAINITABELA date,
    BDDATAINIPERIOD date,
    BDDATAINISST date,
    BDCODEMPMATRIZ integer,
    BDDATAGERADO date,
    BDHORAGERADO time,
    BDTENTATIVA integer,
    BDCODCOL integer,
    BDIDEVENTO varchar(100),
    BDCPFCOL varchar(14),
    BDEVENTOEXCLUSAO integer,
    BDCPFCOLEXCLUIDO varchar(14))
as
begin
  SUSPEND;
end^

CREATE OR ALTER procedure SP_GET_EVT_FILA_ESOCIAL (
    PRCODEMP integer,
    PREXCLUSAO integer)
returns (
    BDCODIGO integer,
    BDCODEMP integer,
    BDCHAVE varchar(60),
    BDXML blob sub_type 0 segment size 80,
    BDCODTIPO integer,
    BDSTATUS integer,
    BDDATAEVENTO date,
    BDMOTIVO varchar(100),
    BDGRUPO integer,
    BDDATAININAOPERIOD date,
    BDDATAINITABELA date,
    BDDATAINIPERIOD date,
    BDDATAINISST date,
    BDCODEMPMATRIZ integer,
    BDDATAGERADO date,
    BDHORAGERADO time,
    BDTENTATIVA integer,
    BDCODCOL integer,
    BDIDEVENTO varchar(100),
    BDCPFCOL varchar(14),
    BDEVENTOEXCLUSAO integer,
    BDCPFCOLEXCLUIDO varchar(14),
    BDORDEM_MAIOR_PRIORI_ENVIO integer,
    BDCONTRORDEMENVIOEVTS2500 integer)
as
begin
  SUSPEND;
end^

CREATE OR ALTER PROCEDURE SP_RETORNA_MAIOR_ZERO (
    PRVALOR NUMERIC(15,2))
RETURNS (
    BDVALOR NUMERIC(15,2))
AS
BEGIN
  SUSPEND;
END^

create or alter procedure SP_VRH_REL_MOVIMENTACAO (
    PRCODEMP varchar(25000),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDATIVOSANT integer,
    BDADM integer,
    BDDEM integer)
as
begin
  suspend;
end^

/* Restore proc. body: SP_CALC_IDADE */
CREATE OR ALTER PROCEDURE SP_CALC_IDADE(PRNASCIMENTO DATE,
PRDATAATUAL DATE)
 RETURNS(BDANOS INTEGER)
 AS
BEGIN
  SUSPEND;
END
^

CREATE OR ALTER PROCEDURE GET_ATIVIDADES_SN (
    PRCODEMP INTEGER,
    PRDATALAN DATE,
    prUMAUM DM_BOOLEAN)
RETURNS (
    BDATIVIDADES VARCHAR(11))
AS
BEGIN
  SUSPEND;
END
^

create or alter procedure SP_VRH_EMP_IDADE_COL (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDIDADE integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRH_EMP_IDADE_COL_DEP (
    PREMP varchar(15000),
    PRCOL varchar(32700),
    PRDEP varchar(10000),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDIDADE integer)
as
begin
  suspend;
end^


create or alter procedure SP_VRHM_EMP_COL_VAL_OP_SAU (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDIDADE integer,
    BDIDADEFAIXA integer,
    BDMENSALIDADE numeric(18,6),
    BDTIPO integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHM_EMP_VAL_COL_OP_ATU (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRPLANOSAUDE integer = 0,
    PROPER integer = 0,
    PRCONV integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREFVCS integer,
    BDVALORMENSALIDADEFUN numeric(18,6),
    BDVALORCOPARFUN numeric(18,6),
    BDTIPO integer,
    BDCODTIPO integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRH_EMP_SEM_VALORES_TCONV (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRPLANO integer = 0,
    PROPERADORA integer = 0,
    PRCONVENIO integer = 0)
returns (
    BDTIPO integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREF integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDNOME varchar(70),
    BDCPF varchar(14),
    BDVALORMENSALIDADE numeric(18,6),
    BDVALORCOPAR numeric(18,6))
as
begin
  suspend;
end^

create or alter procedure SP_VRHM_EMP_VAL_TOD_OP_ATU (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRPLANO integer = 0,
    PROPER integer = 0,
    PRCONV integer = 0)
returns (
    BDTIPO integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREF integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDNOME varchar(70),
    BDCPF varchar(14),
    BDVALORMENSALIDADE numeric(18,6),
    BDVALORCOPAR numeric(18,6),
    BDCODTIPOCONV integer,
    BDTIPOFAIXA integer,
    BDCODTIPO integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHM_EMP_COL_COP_OP_SAU (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRPLANO integer = 0,
    PROPER integer = 0,
    PRCONV integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREF integer,
    BDVALORCOPARFUN numeric(18,6),
    BDVALORMENSALIDADE numeric(18,6),
    BDNAOPAGAMENSALIDADE DM_BOOLEAN,
    BDCODTIPO integer)
as
begin
  suspend;
end^

create or alter procedure SP_VRHM_EMP_VINC_COL_CONV_ATU (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer,
    PROPER integer = 0,
    PRCONV integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREFINI integer,
    BDREFFIM integer,
    BDCODPLACONVSAU integer)
as
begin
  suspend;
end^

CREATE OR ALTER PROCEDURE LANCA_EXCEPTION (
    PRMESSAGE VARCHAR(500),
    PRSQLCODE CHAR(4),
    PRGDSCODE CHAR(9))
AS
BEGIN

END^

CREATE OR ALTER procedure SP_RAZAO_LANCAMENTO_BANC (
    PRCHAVEBAN varchar(1000) = '',
    PRDATAINI varchar(20) = '',
    PRDATAFIN varchar(20) = '',
    PRMODELO integer = 0)
returns (
    BDCODTIPO integer,
    BDSALDOATUAL numeric(15,2),
    BDSALDOANTERIOR numeric(15,2),
    BDVALORSAIDA numeric(15,2),
    BDVALORENTRADA numeric(15,2),
    BDDESCTIPOLAN varchar(100),
    BDDATALAN date,
    BDCODCLI integer,
    BDNOMCLI varchar(100),
    BDCODFOR integer,
    BDNOMEFOR varchar(100),
    BDCODDESP integer,
    BDDESCDESP varchar(100),
    BDCODOBRSER integer,
    BDDESCRICAO varchar(100),
    BDCHAVECTABAN integer,
    BDDESCCTABAN varchar(200),
    BDCHAVELAN integer,
    BDSTATUS integer,
    BDNOMESC varchar(100),
    BDNUMPAR varchar(100),
    BDORIGEM integer,
    BDSERIE varchar(6),
    BDREF varchar(20),
    BDTIPOMOV integer,
    BDCHAVECTAPAG integer,
    BDCODESC integer,
    BDVALORLANC numeric(15,2))
as BEGIN SUSPEND; END^


create or alter procedure SP_VRH_STANDBY_RHNET (
    PRFILTRO integer)
returns (
    BDCODSB integer,
    BDTIPOSB integer,
    BDDESCRICAOSB varchar(3000))
as
begin
  SUSPEND;
end^


create or alter procedure SP_VRH_EMAILS_RHNETSOCIAL (
    PREMP varchar(25000))
returns (
    BDCODEMPRHNET integer,
    BDCODEMP integer,
    BDCODTIPCTRL integer,
    BDEMAIL varchar(20000))
as
begin
  SUSPEND;
end^


CREATE OR ALTER PROCEDURE SP_INSERT_INCONSIS_CONTA_REDZ (
    PRSESSAO INTEGER,
    PRCODPLANOONLINE INTEGER,
    PRENQFED INTEGER)
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_INSERE_HIERARQUIA_CTX (
    PRTABLE VARCHAR(50))
AS
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_CONTEXTODB (
    PRFILE VARCHAR(1000))
AS
BEGIN
END^

create or alter procedure SP_CRIA_PRE_CONTABILIZACAO_REDZ (
    PRSESSAO integer,
    PRCODPLANOONLINE integer,
    PRENQFED integer,
    PRFORMATRIBUTACAO integer = 0)
as
BEGIN

END^



create or alter procedure SP_ATUALIZAR_TMP_TTERCEIRO (
    PRSESSAO integer not null,
    PRLANCAMENTOMANUAL DM_BOOLEAN not null,
    PRGERARINCONSISTENCIAS DM_BOOLEAN not null,
    PRATUALIZARDADOS DM_BOOLEAN not null,
    PRHUGEFILE DM_BOOLEAN not null,
    PRCODTIPO integer,
    PRTIPOVINCULO integer,
    PRVINCPORCNPJ_IE integer = 0)
AS BEGIN end^

CREATE OR ALTER PROCEDURE SP_IMPORTACAO_SEM_PART (
    PRSESSAO INTEGER,
    PRCODPARTDEFAULT INTEGER)
AS
BEGIN
end^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_DAPI (
    PRSESSAO INTEGER NOT NULL,
    PRTIPOLAN CHAR(3) NOT NULL)
AS
BEGIN
END^


CREATE OR ALTER PROCEDURE SP_CANCELAR_LAN (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRSESSAOLANCANC INTEGER,
    PRSESSAOLANINUT INTEGER)
AS BEGIN end^

CREATE OR ALTER PROCEDURE SP_TRANSFERENCIA_PARCELAS (
    PRID_TERMINAL INTEGER,
    PRTIPOLAN CHAR(3))
AS BEGIN end^


create or alter procedure SP_VRH_GERAREL_TRANSFERENCIA
returns (
    BDCODEMPORIG integer,
    BDCODCOLORIG integer,
    BDCODEMPDEST integer,
    BDCODCOLDEST integer,
    BDCODPTRAN integer,
    BDDATATRF date,
    BDCNPJEMPD DM_CNPJ_CPF,
    BDNOMEMPD DM_BDNOMEMP,
    BDAPEEMPD DM_BDAPEMP,
    BDENDEMPD DM_BDENDERECO,
    BDNUMEMPD DM_NUMEND,
    BDBAIEMPD DM_BDBAIRRO,
    BDCEPEMPD DM_CEP,
    BDDDDEMPD integer,
    BDFONEEMPD DM_BDTELEFONE,
    BDFAXEMPD DM_BDTELEFONE,
    BDEMAILEMPD DM_BDEMAIL,
    BDCOMPLEMPD DM_BDCOMPENDERECO,
    BDLOGREMPD DM_LOGRADOURO,
    BDNOMCIDD varchar(40),
    BDSIGLAUFEMPD varchar(2),
    BDCNPJEMPO DM_CNPJ_CPF,
    BDNOMEMPO DM_BDNOMEMP,
    BDAPEEMPO DM_BDAPEMP,
    BDENDEMPO DM_BDENDERECO,
    BDNUMEMPO DM_NUMEND,
    BDBAIEMPO DM_BDBAIRRO,
    BDCEPEMPO DM_CEP,
    BDDDDEMPO integer,
    BDFONEEMPO DM_BDTELEFONE,
    BDFAXEMPO DM_BDTELEFONE,
    BDEMAILEMPO DM_BDEMAIL,
    BDCOMPLEMPO DM_BDCOMPENDERECO,
    BDLOGREMPO DM_LOGRADOURO,
    BDNOMCIDO varchar(40),
    BDSIGLAUFEMPO varchar(2),
    BDNOMCOLD DM_BDNOMCOL,
    BDLOGRCOLD DM_LOGRADOURO,
    BDENDCOLD DM_BDENDERECO,
    BDNUMCOLD DM_NUMEND,
    BDCOMPLCOLD DM_BDCOMPENDERECO,
    BDBAICOLD DM_BDBAIRRO,
    BDCEPCOLD DM_CEP,
    BDDDDCOLD integer,
    BDFONECOLD DM_BDTELEFONE,
    BDEMAILCOLD DM_BDEMAIL,
    BDDATANASCCOLD date,
    BDDATAADMCOLD date,
    BDSIGLAUFD varchar(2),
    BDCTPSCOLD DM_BDCTPS,
    BDSERIECTPSCOLD DM_SERIECTPS,
    BDDSERIECTPSCOLD varchar(2),
    BDRGCOLD varchar(13),
    BDORGEMIRGCOLD DM_ORGAOEMISSOR,
    BDDATAEMIRGCOLD date,
    BDCPFCOLD varchar(14),
    BDNOMCIDCOD varchar(40),
    BDNOMCOLO DM_BDNOMCOL,
    BDLOGRCOLO DM_LOGRADOURO,
    BDENDCOLO DM_BDENDERECO,
    BDNUMCOLO DM_NUMEND,
    BDCOMPLCOLO DM_BDCOMPENDERECO,
    BDBAICOLO DM_BDBAIRRO,
    BDCEPCOLO DM_CEP,
    BDDDDCOLO integer,
    BDFONECOLO DM_BDTELEFONE,
    BDEMAILCOLO DM_BDEMAIL,
    BDDATANASCCOLO date,
    BDDATAADMCOLO date,
    BDSIGLAUFO varchar(2),
    BDCTPSCOLO DM_BDCTPS,
    BDSERIECTPSCOLO DM_SERIECTPS,
    BDDSERIECTPSCOLO varchar(2),
    BDRGCOLO varchar(13),
    BDORGEMIRGCOLO DM_ORGAOEMISSOR,
    BDDATAEMIRGCOLO date,
    BDCPFCOLO varchar(14),
    BDNOMCIDCOLO varchar(40))
as
begin
 suspend;
end
^

CREATE OR ALTER procedure SP_GET_ULTIMA_TRANSFERENCIA (
    PRCODCOL integer,
    PREMPRESA integer,
    PRREFERENCIA integer)
returns (
    BDCODCOL integer,
    BDCODEMP integer)
as
begin
 suspend;
end
^


CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_TCADINFCOM (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER,
    PRLANCAMENTOMANUAL DM_BOOLEAN)
AS
BEGIN
END
^


CREATE OR ALTER PROCEDURE SP_VRHF_MONTASALMES (PREMP    VARCHAR(20000),
                                               PRCOL    VARCHAR(32700),
                                               PRREFINI INTEGER       ,
                                               PRREFFIM INTEGER        )
RETURNS ( BDCODEMP     INTEGER,
          BDCODCOL     INTEGER,
          BDCODEMPORIG INTEGER,
          BDCODCOLORIG INTEGER,
          BDREF        INTEGER,
          BDSALBASECOL NUMERIC(18,6))
AS
DECLARE VARIABLE WSQL      VARCHAR(32700);
DECLARE VARIABLE WSQLAUX   VARCHAR(5000) ;
DECLARE VARIABLE WSQLTRANS VARCHAR(5000) ;
DECLARE VARIABLE WDATA     VARCHAR(10)   ;
DECLARE VARIABLE WDIA      INTEGER       ;
BEGIN
 suspend;
END^


CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOC_SAI_REG300 (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260),
    PRPERFIL INTEGER)
AS
BEGIN
END
^

create or alter procedure SP_EXPORTA_BLOCOC_ENT_SPEDCONTR (
    PRCODEMP integer,
    PRCODPLAPADRAOREF integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRBLOCO varchar(4),
    PREXPORTAPORSCP varchar(5),
    PREXBCPISCOF DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
BEGIN

END^

create or alter procedure SP_EXPORTA_BLOCOC_CONTRIBUICOES (
    PRCODEMP integer,
    PRCODPLAPADRAOREF integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PREXPORTAPORSCP varchar(5),
    PREXCLUSAOICMS DM_BOOLEAN,
    PRCODEMPSCP integer,
    PREXBCPISCOF DM_BOOLEAN)
as
BEGIN

END^

create or alter procedure SP_EXPORTA_C800_SAI_SPEDCONTR (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PREXPORTAPORSCP DM_BOOLEAN,
    PRCODPLAPADRAOREF integer,
    WEXPCONTACONTAB DM_BOOLEAN)
as
BEGIN

END^

create or alter procedure SP_EXPORTA_BLOCOC_SAI_SPEDCONTR (
    PRCODEMP integer,
    PRCODPLAPADRAOREF integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRBLOCO varchar(4),
    PREXPORTAPORSCP varchar(5),
    PREXCLUSAOICMS DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOD_SAI_SPEDCONTR (
    prCODEMP INTEGER,
    prCODPLAPADRAOREF INTEGER,
    prDTINI DATE,
    prDTFIM DATE,
    prARQUIVO VARCHAR(260))
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOD_CONTRIBUICOES (
    prCODEMP INTEGER,
    prCODPLAPADRAOREF INTEGER,
    prDTINI DATE,
    prDTFIM DATE,
    PRARQUIVO varchar(260),
    PREXPORTAPORSCP varchar(5),
    PRCODEMPSOCIA integer)
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOK290 (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOK300 (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
END
^

CREATE OR ALTER PROCEDURE SP_VALIDA_EXPORTACAO_SPEDCONTR (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(100),
    PRBLOCO CHAR(4))
AS
BEGIN

END^


create or alter procedure SP_VRHM_EMP_VINC_DEP_CONV_ATU (
    PREMP integer,
    PRREF integer,
    PRCOL integer = null,
    PRDEP integer = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREFINI integer,
    BDREFFIM integer,
    BDCODPLACONVSAU integer)
as
begin
  suspend;
end^


create or alter procedure SP_VRHM_EMP_DEP_VAL_OP_SAU (
    PREMP integer,
    PRREF integer,
    PRCOL integer = null,
    PRDEP integer = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDIDADE integer,
    BDIDADEFAIXA integer,
    BDMENSALIDADE numeric(18,2),
    BDTIPO integer)
as
begin
  suspend;
end^


create or alter procedure SP_VRHM_EMP_DEP_COP_OP_SAU (
    PREMP integer,
    PRREF integer,
    PRCOL integer = null,
    PRDEP integer = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREF integer,
    BDVALORCOPARDEP numeric(18,2),
    BDVALORMENSALIDADE numeric(18,2),
    BDNAOPAGAMENSALIDADE DM_BOOLEAN,
    BDCODTIPO integer)
as
begin
  suspend;
end^


create or alter procedure SP_VRHM_EMP_VAL_DEP_OP_ATU (
    PREMP integer,
    PRREF integer,
    PRCOL integer = null,
    PRDEP integer = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREFVCS integer,
    BDVALORMENSALIDADEDEP numeric(18,2),
    BDVALORCOPARDEP numeric(18,2),
    BDTIPO integer,
    BDCODTIPO integer)
as
begin
  suspend;
end^


create or alter procedure SP_VRH_CONVSAU_DIRF2 (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDTIPO integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREF integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDNOME DM_BDNOMCOL,
    BDCPF varchar(14),
    BDVALORMENSALIDADE numeric(18,2),
    BDVALORCOPAR numeric(18,2),
    BDCODTIPOCONV integer,
    BDTIPOFAIXA integer,
    BDDESCRICAO varchar(80),
    BDCNPJ DM_CNPJ_CPF,
    BDREGISTROANS integer,
    BDRAZAOSOCIAL varchar(80),
    BDPARENESCODPN integer,
    BDDATANASCDPN date)
as
begin
  suspend;
end^


create or alter procedure SP_VRH_CONVSAU_DIRF (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRPLASAUDE integer)
returns (
    BDTIPO integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREF integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDNOME DM_BDNOMCOL,
    BDCPF varchar(14),
    BDVALORMENSALIDADE numeric(18,2),
    BDVALORCOPAR numeric(18,2),
    BDCODTIPOCONV integer,
    BDTIPOFAIXA integer,
    BDDESCRICAO varchar(80),
    BDCNPJ DM_CNPJ_CPF,
    BDREGISTROANS integer,
    BDRAZAOSOCIAL varchar(80),
    BDPARENESCODPN integer,
    BDDATANASCDPN date)
as
begin
  suspend;
end^

CREATE OR ALTER PROCEDURE SP_CRIA_PRE_CONTAB_RET_APOSESP (
    PRSESSAO INTEGER,
    PRCODPLANOONLINE INTEGER,
    PRENQFED INTEGER,
    PRTIPOLAN VARCHAR(5))
RETURNS (
    BDSQL VARCHAR(5000))
AS
DECLARE VARIABLE WTABLEINCON VARCHAR(50);
DECLARE VARIABLE WEF INTEGER;
DECLARE VARIABLE WTABLE VARCHAR(50);
DECLARE VARIABLE WTIPLAN INTEGER;
DECLARE VARIABLE WTABLERATEIO VARCHAR(32);
DECLARE VARIABLE WTABLEITEM VARCHAR(50);
DECLARE VARIABLE WTABLEINSS VARCHAR(31);
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WSOMARET VARCHAR(200);
DECLARE VARIABLE WCODITEMINSS15 INTEGER;
DECLARE VARIABLE WCODITEMINSS20 INTEGER;
DECLARE VARIABLE WCODITEMINSS25 INTEGER;
BEGIN
  SUSPEND;
END^

CREATE OR ALTER procedure SP_NAOEXECUTA_TRIGGER_ESTAGIO (PREXECUTATRIGGER DM_BOOLEAN)
AS
BEGIN
END^

CREATE OR ALTER TRIGGER tr_bf_insert_EMPRESAS_ECD_I157 FOR EMPRESAS_ECD_I157
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER tr_bfin_EMP_CONTAS_ECD_I157 FOR EMPRESAS_CONTAS_ECD_I157
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TFPAS_ALIQ_TERC_BI0 FOR VRH_BASE_TFPAS_ALIQ_TERC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TFPAS_ALIQ_TERC_BU0 FOR VRH_BASE_TFPAS_ALIQ_TERC
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VFIN_ESC_TSERVICOFATCC_BI0 FOR VFIN_ESC_TSERVICOFATCC
ACTIVE BEFORE INSERT POSITION 0
 AS
BEGIN
END 
^

CREATE OR ALTER TRIGGER VFIN_BASE_TCONCIBAN_BI0 FOR VFIN_BASE_TCONCILIACAOBANCARIA
ACTIVE BEFORE INSERT POSITION 0
 AS
begin
end
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_EMP_TMOVENTDED FOR VEF_EMP_TMOVENTDED
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_EMP_TMOVSAIDED FOR VEF_EMP_TMOVSAIDED
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vrh_emp_tcolcon_estagio_biu0 for vrh_emp_tcolcon_estagio
active before insert or update position 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRH_RHNET_TSTANDBY_BI0 FOR VRH_RHNET_TSTANDBY
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBA_RELACAO_BI0 FOR VRH_BASE_TVERBA_RELACAO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHBASETVERBARELACAOITENS_BI0 FOR VRH_BASE_TVERBA_RELACAOITENS
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER vsuc_tdist_lucro_bi0 FOR vsuc_tdist_lucro
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VSUC_TJUROS_SOB_CAP_BI0 FOR VSUC_TJUROS_SOB_CAP
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TOL_VSUC_TJUROS_SOB_CAP_AD0 FOR TOL_VSUC_TJUROS_SOB_CAP
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER tol_vsuc_tdist_lucro_ad0 FOR tol_vsuc_tdist_lucro
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^


CREATE OR ALTER TRIGGER TOL_VEF_EMP_TCREDESTOQF150_AD0 FOR TOL_VEF_EMP_TCREDESTOQF150
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERTHEMA_BI0 FOR VEF_EMP_TMOVSERTHEMA
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVK291_BI0 FOR VEF_EMP_TMOVK291
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVK292_BI0 FOR VEF_EMP_TMOVK292
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVK301_BI0 FOR VEF_EMP_TMOVK301
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVK302_BI0 FOR VEF_EMP_TMOVK302
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRESCISAO_AI0 FOR VRH_EMP_TRESCISAO
ACTIVE AFTER INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHAINT_BI0 FOR VRHF_EMP_TFOLHAINT
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHAINT_BU0 FOR VRHF_EMP_TFOLHAINT
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHAINT_AD0 FOR VRHF_EMP_TFOLHAINT
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHATOMINT_BI0 FOR VRHF_EMP_TFOLHATOMINT
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHATOMINT_BU0 FOR VRHF_EMP_TFOLHATOMINT
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHATOMINT_AD0 FOR VRHF_EMP_TFOLHATOMINT
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAINT_DET_BI0 FOR VRHF_EMP_TVERBAINT_DET
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBATOMINT_BI0 FOR VRHF_EMP_TVERBATOMINT
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBATOMINT_BU0 FOR VRHF_EMP_TVERBATOMINT
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBATOMINT_DET_BI0 FOR VRHF_EMP_TVERBATOMINT_DET
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TCALC_INT_AD0 FOR TOL_VRHF_EMP_TCALC_INT
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TFGTS_INT_AD0 FOR TOL_VRHF_EMP_TFGTS_INT
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TVERBA_INT_AD0 FOR TOL_VRHF_EMP_TVERBA_INT
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TCALC_TOMINT_AD0 FOR TOL_VRHF_EMP_TCALC_TOMINT
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TFGTS_TOMINT_AD0 FOR TOL_VRHF_EMP_TFGTS_TOMINT
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TVERBA_TOMINT_AD0 FOR TOL_VRHF_EMP_TVERBA_TOMINT
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_EMP_CREDITO_TRABALHADOR_BI0 FOR VRH_EMP_CREDITO_TRABALHADOR
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_CREDITO_TRABALHADOR_BU0 FOR VRH_EMP_CREDITO_TRABALHADOR
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TEXPVSUP_BI0 FOR VRH_BASE_TEXPVSUP
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TINTERMITENTE_BI0 FOR VRH_EMP_TINTERMITENTE
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER vrh_emp_tinter_qhdias_bi0 for vrh_emp_tintermitente_qhdias
active before insert position 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TVERDE_AMARELO_BI0 FOR VRH_EMP_TVERDE_AMARELO
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end
^


CREATE OR ALTER TRIGGER VRH_EMP_TINTERMITENTE_AD0 FOR VRH_EMP_TINTERMITENTE
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TINTERMITENTE_AU0 FOR VRH_EMP_TINTERMITENTE
ACTIVE AFTER UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TINTERMITENTE_ACEI_BI0 FOR VRH_EMP_TINTERMITENTE_ACEI
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAIQ48_BI0 FOR VEF_EMP_TMOVSAIQ48
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVENTQ48_BI0 FOR VEF_EMP_TMOVENTQ48
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER trigger tlog_erro_rhnet_bi0 for tlog_erro_rhnet
active before insert position 0
AS
begin
end^

CREATE OR ALTER TRIGGER TARQ_STORAGESCI_BI0 FOR TARQ_STORAGESCI
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER VRH_BASE_TCALCVESP_PADRAO_BI0 FOR VRH_BASE_TCALCVESP_PADRAO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TCALCITENS_PADRAO_BI0 FOR VRH_BASE_TCALCITENS_PADRAO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_BASE_EMP_INSTESTADIC_BI0 FOR VRH_BASE_EMP_INSTESTAGIOADIC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TAPUE115_AD0 FOR TOL_VEF_EMP_TAPUE115
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TAJUENTM220620_AD0 FOR TOL_VEF_EMP_TAJUENTAPUPCM220620
ACTIVE AFTER DELETE POSITION 0
AS
begin   
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TAJUSTEIPIE531_BI0 FOR VEF_EMP_TAJUSTEIPIE531
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END ^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_IMG_BU0 FOR VRH_EMP_TCOLCON_IMG
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END ^

CREATE OR ALTER TRIGGER VRH_RHNET_TARQUIVO_EXP_BI0 FOR VRH_RHNET_TARQUIVO_EXP
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_DASHBOARD_TARQUIVO_BI0 FOR VRH_DASHBOARD_TARQUIVO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_DASHBOARD_INFO_ENVIADOS_BI0 FOR VRH_DASHBOARD_INFO_ENVIADOS
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_TCATEGORIA_BI0 FOR VRH_ESOCIAL_TCATEGORIA
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TPREPRESC_BU0 FOR VRH_BASE_TPREPRESC
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_ADM_BI0 FOR VRH_EMP_TCOL_ADM
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VEF_INT_TRETENCAO_BI0 FOR VEF_INT_TRETENCAO
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VEF_INT_TDIFALIQ_BI0 FOR VEF_INT_TDIFALIQ
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
END^

CREATE OR ALTER trigger vrh_emp_tcomercnfprodrural_bi0 for vrh_emp_tcomercnfprodrural
active before insert position 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRHF_EMP_TCOLCON_MVINC_BI0 FOR VRHF_EMP_TCOLCON_MVINC
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRHF_BASE_TTERC_MVINC_BI0 FOR VRHF_BASE_TTERC_MVINC
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER vfin_base_tescimposto_bi0 for vfin_base_tescimposto
active before insert position 0
AS
BEGIN
END^

/* Trigger: VLAL_CONF_TRIMESTRAL_BI0 */
CREATE OR ALTER TRIGGER VLAL_CONF_TRIMESTRAL_BI0 FOR VLAL_CONF_TRIMESTRAL
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VLAL_EMPRESAS_PREP_CONT_BI0 FOR VLAL_EMPRESAS_PREP_CONT
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VTPO_ATIVIDADE_EXE_BI0 FOR VTPO_ATIVIDADE_EXE
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VTPO_ATIVIDADE_EXE_REGISTRO_BI0 FOR VTPO_ATIVIDADE_EXE_REGISTRO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE or alter trigger vtpo_base_userhost_bi0 for vtpo_base_userhost
active before insert position 0
AS
begin
end^

create or alter procedure VTPO_GETHOSTID
as
begin
end^


CREATE OR ALTER TRIGGER TVALIDACAOSPED_AGENDAMENTOS_BI FOR TVALIDACAOSPED_AGENDAMENTOS
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER trigger vef_base_tplanoacoesconf1900_bi for vef_base_tplanoacoesconf1900
active before insert position 0
AS
  DECLARE VARIABLE wQtdeFil INTEGER;
BEGIN
end^

CREATE OR ALTER trigger vef_tplanoacoesconf1900_bu0 for vef_base_tplanoacoesconf1900
active before update position 0
AS
  DECLARE VARIABLE wQtdeFil INTEGER;
begin
end^  
  

CREATE OR ALTER trigger vef_base_tvinccodplano1900_ai0 for vef_base_tvinccodplano1900
active after insert position 0
As
BEGIN
end^

CREATE OR ALTER TRIGGER VEF_BASE_TVINCCODPLANO1200_AI0 FOR VEF_BASE_TVINCCODPLANO1250
ACTIVE AFTER INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER trigger vef_base_tvinccodplano1900_bi0 for vef_base_tvinccodplano1900
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
 BEGIN
end^

CREATE OR ALTER TRIGGER VEF_BASE_TVINCCODPLANO1200_BI0 FOR VEF_BASE_TVINCCODPLANO1250
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
end^

CREATE OR ALTER TRIGGER TOL_VEF_DRCST_TC197SAI_AD0 FOR TOL_VEF_DRCST_TC197SAI
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVDCOMP_AD0 FOR TOL_VEF_EMP_TMOVDCOMP
ACTIVE AFTER DELETE POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_DRCST_TE111_AD0 FOR TOL_VEF_EMP_DRCST_TE111
ACTIVE AFTER DELETE POSITION 0
AS
begin
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TICMSSPEDGER_E1_AD0 FOR TOL_VEF_EMP_TICMSSPEDGER_E111
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TICMSSPEDE116_AD0 FOR TOL_VEF_EMP_TICMSSPEDGER_E116
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TBLOCOPGER_CPRB_AD0 FOR TOL_VEF_EMP_TBLOCOPGER_CPRB
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TICMSSPED_C185_AD0 FOR TOL_VEF_EMP_TICMSSPED_C185
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN  
END^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TICMSSPED_C380_AD0 FOR TOL_VEF_EMP_TICMSSPED_C380
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN  
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TICMSSPED_C480_AD0 FOR TOL_VEF_EMP_TICMSSPED_C480
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN  
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TICMSSPED_C180_AD0 FOR TOL_VEF_EMP_TICMSSPED_C180
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN  
END^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TICMSSPED_C186_AD0 FOR TOL_VEF_EMP_TICMSSPED_C186
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER trigger TOL_VEF_EMP_TICMSSPED_C181_AD0 for TOL_VEF_EMP_TICMSSPED_C181
active after delete position 0
AS
BEGIN
END^

CREATE OR ALTER procedure SP_ATUALIZAR_VICCODPLANO1900 (
    BDCHAVE integer,
    BDCODPLANCONF1900 integer,
    BDCODCSTICMS integer,
    BDCODNAT integer)
as
begin 
end^



-- Solicita??o: 22602 Denicio 09/02/2018
create or alter procedure SP_VRH_EXCLUI_INCONFORMIDADE (
    PREMP integer,
    PREVENTO varchar(20),
    PRCADASTRO integer,
    PRCHAVECAD varchar(50),
    PRREF integer,
    PRCAMPO varchar(30))
as
begin
end^


CREATE OR ALTER PROCEDURE SP_VRHF_EXPORTACAO_CONTABIL (
    PREMP VARCHAR(25000),
    PRREF INTEGER,
    PRAGRUPACOL INTEGER = 0,
    PRFOLHANORMAL INTEGER = 0,
    PRFOLHACOMP INTEGER = 0,
    PRFERIAS INTEGER = 0,
    PRADTOSAL INTEGER = 0,
    PRADTO13 INTEGER = 0,
    PR13SAL INTEGER = 0,
    PRC13SAL INTEGER = 0,
    PRFOLHAAVULSA INTEGER = 0,
    PRPROVFER INTEGER = 0,
    PRPROV13 INTEGER = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDDATALAN DATE,
    BDCTADEB INTEGER,
    BDCODTPCCDEB INTEGER,
    BDCTACCDEB INTEGER,
    BDAPECCDEB VARCHAR(20),
    BDNOMCTACCDEB VARCHAR(40),
    BDCTACRED INTEGER,
    BDCODTPCCCRED INTEGER,
    BDCTACCCRED INTEGER,
    BDAPECCCRED VARCHAR(20),
    BDNOMCTACCCRED VARCHAR(40),
    BDVALORLANC NUMERIC(15,2),
    BDCOMPLHIST VARCHAR(200))
AS
BEGIN
  SUSPEND;
END
^

--#alt:16965. Ana - 30/11/2017
CREATE OR ALTER trigger tempresas_backup_online_bi0 for tempresas_backup_online
active before insert position 0
as
begin
end
^

create or alter procedure SP_COPIA_DADOS_EMPRESA (
    PRTABELA varchar(50),
    PRCODEMP integer,
    PRCODEMPBACKUP varchar(10),
    PRREFEMP integer)
returns (
    BDINSERIU DM_BOOLEAN)
as
begin
  SUSPEND;
end
^

create or alter procedure SP_CRIA_BACKUP_EMPRESA (
    PRCODEMP integer,
    PRREFEMP integer,
    PRCODPLANOONLINEDE integer,
    PRCODPLANOONLINEPARA integer,
    PRCODUSU integer,
    PRCODUSUINTRANET integer,
    PRNOMUSUINTRANET varchar(80),
    PRCODCONTABLALUR integer)
as
begin

end
^
--#alt:16965. fim

create or alter procedure VSUC_SP_CONTAS_CONC_EMP (
    PREMPRESAS varchar(3048),
    PRDATAINI date,
    PRDATAFIN date,
    PRCONTABILIZACAO integer)
returns (
    BDCODEMP integer,
    BDREF integer,
    BDCODUSU integer,
    BDNOMCOMPLUSU varchar(40),
    BDCODTPLA integer,
    BDCONCILIADO integer,
    BDENCPERIODO varchar(5),
    BDCODPLAPADRAO integer)
as
begin
  SUSPEND;
end
^

create or alter procedure SP_VRH_MONTAQUADROHORAS (
    PREMP varchar(25000),
    PRCODPQUA integer,
    PRCODQH integer,
    PREXPINICIAL smallint = 0,
    PRINATIVAR smallint = 0)
returns (
    BDCODEMPRHNET integer,
    BDCODEMP integer,
    BDCODPQUA integer,
    BDCODQH integer,
    BDDESCQH DM_BDDESCQH,
    BDDIASEMQH integer,
    BDHORA1 time,
    BDHORA2 time,
    BDHORA3 time,
    BDHORA4 time,
    BDHORA5 time,
    BDHORA6 time,
    BDHORA7 time,
    BDHORA8 time,
    BDHORFLEX integer,
    BDINATIVO DM_BOOLEAN,
    BDATIVO smallint)
as
BEGIN SUSPEND; END^

CREATE OR ALTER procedure SP_QUADRO_INTERMITENTE_CONTRATO (
    PREMPRESA integer not null,
    PRCOLABORADOR integer not null,
    PRCONTRATO integer not null)
returns (
    QUADRO varchar(1000))
as
BEGIN
    SUSPEND;
END^

CREATE OR ALTER procedure SP_ESTABILIDADE_COL (
    PROPCAOESTAB integer,
    PRBDCODEMP varchar(500),
    PRBDCODCOL varchar(500),
    PRBDREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDFIMCIPA date,
    BDINICIPA date,
    BDNOMCOL varchar(150),
    BDCODSINTRAB integer,
    BDDATAINISIT date,
    BDDATAFIMSIT date,
    BDCODSIT integer,
    BDDESCSIT varchar(100),
    BDFIMPERGOZOFE date,
    BDINIPERGOZOFE date,
    BDFIMPERAQUISFE date,
    BDINIPERAQUISFE date,
    BDDATAESTAB date)
as
BEGIN
    SUSPEND;
END^

CREATE OR ALTER procedure SP_CONS_CALC_INTERMITENTE (
    PRCODEMP integer = null,
    PRCODEMPMULT varchar(15000) = '',
    PRCODCOL integer = null,
    PRCODCOLMULT varchar(15000) = '',
    PRCODCONTRATO integer = null,
    PRDATAINICIAL date = null,
    PRDATAFINAL date = null,
    PRVERBASDEM smallint = 1)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(18),
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDRGCOL varchar(13),
    BDCODCONTTI integer,
    BDDESCCONTRATOTI varchar(2000),
    BDDATACONVTI date,
    BDHORACONVTI time,
    BDDATAINISERVTI date,
    BDDATAFIMSERVTI date,
    BDDATAPAGTI date,
    BDLIQUIDO numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDDATAPGTOFN date,
    BDFGTSFN numeric(18,6),
    BDFGTS13FN numeric(18,6),
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFVFN numeric(18,6),
    BDREFAUXVFN numeric(18,6),
    BDVALVFN numeric(18,6),
    BDVALIFN numeric(18,6),
    BDDESCVER varchar(40),
    BDTIPOCODVER integer,
    BDORDEMVER integer)
as
BEGIN
    SUSPEND;
END^
 
create or alter procedure SP_CONS_CALC_INTERMITENTE_COMP (
    PRCODEMP integer = null,
    PRCODEMPMULT varchar(15000) = '',
    PRCODCOL integer = null,
    PRCODCOLMULT varchar(15000) = '',
    PRCODCONTRATO integer = null,
    PRDATAINICIAL date = null,
    PRDATAFINAL date = null,
    PRDATAPGTOINICIAL date = null,
    PRDATAPGTOFINAL date = null,
    PRVERBASDEM smallint = 1)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(18),
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDRGCOL varchar(13),
    BDCODCONTTI integer,
    BDDESCCONTRATOTI varchar(2000),
    BDDATACONVTI date,
    BDHORACONVTI time,
    BDDATAINISERVTI date,
    BDDATAFIMSERVTI date,
    BDDATAPAGTI date,
    BDLIQUIDO numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDDATAPGTOFN date,
    BDFGTSFN numeric(18,6),
    BDFGTS13FN numeric(18,6),
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFVFN numeric(18,6),
    BDREFAUXVFN numeric(18,6),
    BDVALVFN numeric(18,6),
    BDVALIFN numeric(18,6),
    BDDESCVER varchar(40),
    BDTIPOCODVER integer,
    BDORDEMVER integer,
    BDORDEMTIPOCODVER integer)
as
begin
  SUSPEND;
end^

CREATE OR ALTER TRIGGER VRH_EMP_TDEP_IMG_BU0 FOR VRH_EMP_TDEP_IMG
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSEFIPSM_BI0 FOR VRH_BASE_TSEFIPSM
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^
CREATE OR ALTER TRIGGER TPROCESSO_JUDADM_INDSUSP_BI0 FOR TPROCESSO_JUDADM_INDSUSP
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TPROCESSO_JUDADM_AUTORIA_BI0 FOR TPROCESSO_JUDADM_AUTORIA
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TPROCESSO_JUDADM_INDMAT_BI0 FOR TPROCESSO_JUDADM_INDMAT
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TPROCESSO_JUDADM_BI0 FOR TPROCESSO_JUDADM
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TPROCESSO_JUDADM_ITEM_BI0 FOR TPROCESSO_JUDADM_ITEM
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TPROCESSO_JUDADM_ANEXO_BI0 FOR TPROCESSO_JUDADM_ANEXO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vrh_base_texpdynamics_bi0 FOR vrh_base_texpdynamics
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER TMANAD_GERAL_BI0 FOR TMANAD_GERAL
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vrh_base_tmotesocial_ent_bi0 FOR vrh_base_tmotesocial_ent
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^


CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAFC_DET_BI0 FOR VRHF_EMP_TVERBAFC_DET
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAFCTOMINT_BIU0 FOR VRHF_EMP_TVERBAFCTOMINT
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER vrh_esocial_inconformidades_au0 FOR vrh_esocial_inconformidades
ACTIVE AFTER UPDATE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRHP_EMP_PONTO_BIU0 FOR VRHP_EMP_PONTO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VAUD_EMP_NFE_BIU0 FOR VAUD_EMP_NFE
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER EMPRESAS_TSOC_BU0 FOR EMPRESAS_TSOC
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER empresas_tsoc_ref_aiu0 FOR empresas_tsoc_ref
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_VRHF_RELATORIOFF_VALOR (
    PREMP VARCHAR(20000),
    PRCOL VARCHAR(32700),
    PRAUT VARCHAR(12000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRFN SMALLINT = 0,
    PRFC SMALLINT = 0,
    PRADS SMALLINT = 0,
    PRAD13 SMALLINT = 0,
    PR13 SMALLINT = 0,
    PRC13 SMALLINT = 0,
    PRFA SMALLINT = 0,
    PRCODFA INTEGER = 0,
    PRSERV SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODTER INTEGER,
    BDREF INTEGER,
    BDCODVER INTEGER,
    BDVALOR NUMERIC(18,4),
    BDTIPO VARCHAR(5),
    BDDATARESCISAO DATE,
    BDDESCVER VARCHAR(40),
    BDCLAVER VARCHAR(20))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_RELATORIOFF_REF (
    PREMP VARCHAR(20000),
    PRCOL VARCHAR(32700),
    PRAUT VARCHAR(12000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRFN SMALLINT = 0,
    PRFC SMALLINT = 0,
    PRADS SMALLINT = 0,
    PRAD13 SMALLINT = 0,
    PR13 SMALLINT = 0,
    PRC13 SMALLINT = 0,
    PRFA SMALLINT = 0,
    PRCODFA INTEGER = 0,
    PRSERV SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODTER INTEGER,
    BDREF INTEGER,
    BDCODVER INTEGER,
    BDVALOR NUMERIC(18,4),
    BDTIPO VARCHAR(5),
    BDDATARESCISAO DATE,
    BDDESCVER VARCHAR(40),
    BDCLAVER VARCHAR(20))
AS
BEGIN SUSPEND; END
^


CREATE OR ALTER PROCEDURE SP_LANCA_AJUSTE_E115 (
    PRSESSAO INTEGER)
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vef_emp_tplanilhasndeb_bd0 FOR vef_emp_tplanilhasndeb
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAFCT_DET_BI0 FOR VRHF_EMP_TVERBAFCT_DET
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAFCTINT_DET_BI0 FOR VRHF_EMP_TVERBAFCTINT_DET
ACTIVE BEFORE INSERT POSITION 0
as
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAFCINT_DET_BI0 FOR VRHF_EMP_TVERBAFCINT_DET
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TTIPOFOLHACOMP_BI0 FOR VRH_BASE_TTIPOFOLHACOMP
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_BASE_CLASSTRIBUTARIA_BI0 FOR VRH_BASE_CLASSTRIBUTARIA
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TLOG_BU0 FOR TLOG
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VTPO_TCONF_BI FOR VTPO_TCONF
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_TARQUIVO_BU0 FOR VRH_ESOCIAL_TARQUIVO
ACTIVE BEFORE UPDATE POSITION 0
as
BEGIN
END^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_TARQUIVO_AU0 FOR VRH_ESOCIAL_TARQUIVO
ACTIVE AFTER UPDATE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_TARQUIVO_AD0 FOR VRH_ESOCIAL_TARQUIVO
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_TARQUIVO_BD0 FOR VRH_ESOCIAL_TARQUIVO
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER PLANOS_TPLA_BD0 FOR PLANOS_TPLA
ACTIVE BEFORE DELETE POSITION 0 
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_TARQUIVO_AI0 FOR VRH_ESOCIAL_TARQUIVO
ACTIVE AFTER INSERT POSITION 0
AS
BEGIN
END
^

--#alt:58948. Ana - 18/07/2018
CREATE OR ALTER TRIGGER VTPO_MOTIVO_INATIVIDADE_BI0 FOR VTPO_MOTIVO_INATIVIDADE
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^
--#alt:162662 Matheus C.S. 05/07/2022
CREATE OR ALTER TRIGGER VSST_EMP_TAUTODECLARACAO_BI0 FOR VSST_EMP_TAUTODECLARACAO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

--#alt:162662 Matheus C.S. 05/07/2022
CREATE OR ALTER TRIGGER VSST_EMP_TAUTO_DOC_BI0 FOR VSST_EMP_TAUTODECLARACAO_DOC
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER trigger JUSTIFICATIVA_INATIVIDADE_bi0 FOR VTPO_JUSTIFICATIVA_INATIVIDADE
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^
--#alt:58948. fim

--alt:11587 - 07/07/2015 - Nova trigger para controle da chave da tabela. Pedro
CREATE OR ALTER TRIGGER VSUC_EMPRESAS_TPRE_ECF_Y665_BI0 FOR VSUC_EMPRESAS_TPRE_ECF_Y665
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

--alt:11995 - 11/08/2015 - Criada trigger para deletar os lançamentos criados automaticamente pela integração do contábil para o lalur agora que não há mais a chave de ligação. Pedro
CREATE OR ALTER TRIGGER vlal_imp_contablalur_bd0 FOR vlal_empresas_imp_contablalur
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

--alt:4936 - 16/11/2015 - Criada trigger para controlar a chave da nova tabela. Pedro
CREATE OR ALTER TRIGGER TIDIOMAS_BI0 FOR TIDIOMAS
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vef_int_tdestda_bi0 FOR vef_int_tdestda
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TACESSOSITEGOV_BI0 FOR TACESSOSITEGOV
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TINDVAL_BIU0 FOR TINDVAL
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vef_emp_tmovccdemdocf100_bi0 FOR vef_emp_tmovccdemdocf100
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

--#alt:12280 - Nova trigger para controle da chave da tabela. Ana - 04/10/2016
CREATE OR ALTER TRIGGER tr_bf_insert_vsuc_tconfig_imp_c FOR vsuc_tconfig_imp_cta
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vfin_esc_tconfigvarobs_bi0 FOR vfin_esc_tconfigvarobs
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vfin_esc_tcontrato_au0 FOR vfin_esc_tcontrato
ACTIVE AFTER UPDATE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vfin_esc_tregprorrogsitcli_bi0 FOR vfin_esc_tregprorrogsitcli
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vfin_base_tplanositfin_bi0 FOR vfin_base_tplanositfin
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vfin_base_tplanoconciliado_bi0 for vfin_base_tplanoconciliado
active before insert position 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vfin_base_tgrupoeconomico_bi0 for vfin_base_tgrupoeconomico
active before insert position 0
AS
BEGIN
END
^


CREATE OR ALTER TRIGGER VFIN_BASE_TVINCPROCESSOCONC_AD0 FOR VFIN_BASE_TVINCPROCESSOCONCI
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VFIN_BASE_TSITCLIENTE_BI0 FOR VFIN_BASE_TSITCLIENTE
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER procedure SP_VFIN_ATUSITEMP (
    PRCODEMP integer)
as
begin
end^

CREATE OR ALTER trigger vfin_base_tsitcliente_ai0 for vfin_base_tsitcliente
active after insert position 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VFIN_BASE_TSITCLIENTE_AD0 FOR VFIN_BASE_TSITCLIENTE
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER vfin_base_tsitclienteobs_bi0 FOR vfin_base_tsitclienteobs
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vrh_base_taut_publica_bi0 FOR vrh_base_taut_publica
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE or alter TRIGGER vfin_esc_tnfse_servico_bi0 FOR vfin_esc_tnfse_servico
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

--Sol. 18507 - Criação da trigger para inserir as verbas salariais por empresa ao cadastrar uma empresa nova - Bruno L. R. - 17/07/2017
CREATE OR ALTER TRIGGER tr_af_insert_tempresas FOR tempresas
ACTIVE AFTER INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER tr_af_insert_tdarfpadrao FOR tdarfpadrao
ACTIVE AFTER INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TOL_VFIN_DESP_DARF_AD0 FOR TOL_VFIN_DESP_DARF
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_FECHAMENTO_BI0 FOR VRH_ESOCIAL_FECHAMENTO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_FECHAMENTO_BU0 FOR VRH_ESOCIAL_FECHAMENTO
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_FECHAMENTO_AD0 FOR VRH_ESOCIAL_FECHAMENTO
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_TFASEAMENTO_BI0 FOR VRH_ESOCIAL_TFASEAMENTO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^
^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_TFASEAMENTO_BU0 FOR VRH_ESOCIAL_TFASEAMENTO
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_VRH_RELATORIOABSENTISMO (
    PREMP VARCHAR(22000),
    PRCOL VARCHAR(32700),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRSITCOL INTEGER,
    PRFILTROCLA VARCHAR(5000) = NULL)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDREF INTEGER,
    BDCODCLA INTEGER,
    BDDESCCLA VARCHAR(40),
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDNOMTPCC DM_BDNOMEMP,
    BDHORASTRABDIA NUMERIC(18,6),
    BDDIASTRAB INTEGER,
    BDHORASFALTASMES NUMERIC(18,6),
    BDHORASTRABMES NUMERIC(18,6))
AS
BEGIN SUSPEND; END^


--#alt: 12280 - Criado novo procedimento para gerar novo código do plano de conta. Ana - 06/10/2016
CREATE OR ALTER PROCEDURE SP_VERIFICA_NOVO_CODIGO (
    PRCODPLAPADRAO INTEGER,
    PRCODTPLA INTEGER,
    PRCTALON VARCHAR(40))
RETURNS (
    BDCODIGO INTEGER)
AS
BEGIN
  SUSPEND;
END
^

CREATE OR ALTER PROCEDURE SP_GET_ACOES_INCONSISTENCIA (
    PRCODEMP INTEGER,
    PRREF INTEGER,
    PRSESSAO INTEGER = NULL)
RETURNS (
    BDCODPLANOINCONS INTEGER,
    BDNCMPROD INTEGER,
    BDSAICFOPNCAD INTEGER,
    BDENTCFOPCANC INTEGER,
    BDCODUNIMED INTEGER,
    BDENTCFOPNCAD INTEGER,
    BDSAICFOPCANC INTEGER,
    BDDESCRICAO VARCHAR(100),
    BDPLANODEFAULT DM_BOOLEAN,
    BDATUPROD DM_BOOLEAN,
    BDATUPART DM_BOOLEAN,
    BDATUUNIDMED DM_BOOLEAN,
    BDATUINFCOM DM_BOOLEAN,
    BDATUOBS DM_BOOLEAN,
    BDATUMAQREDZ DM_BOOLEAN,
    BDATUBICO DM_BOOLEAN,
    BDATUBOMBA DM_BOOLEAN,
    BDATUTANQUE DM_BOOLEAN,
    BDATUFATCONV DM_BOOLEAN,
    BDPARTIEISE DM_BOOLEAN,
    BDCADPROAUTO DM_BOOLEAN,
    BDENTAJUCFOP DM_BOOLEAN,
    BDENTIMPIPIDIF DM_BOOLEAN,
    BDENTIMPICMSDIF DM_BOOLEAN,
    BDSAIAJUCFOP DM_BOOLEAN,
    BDSAIIMPIPIDIF DM_BOOLEAN,
    BDSAIIMPICMSDIF DM_BOOLEAN,
    BDSERAJUCFOP DM_BOOLEAN,
    BDSERIMPISSDIF DM_BOOLEAN,
    BDPARTBUSCASITE DM_BOOLEAN,
    BDPRODNCMVAZIO DM_BOOLEAN,
    BDREDZCODTER INTEGER,
    BDESPECIEMRC VARCHAR(4),
    BDSERIEMRC VARCHAR(3),
    BDCONDPGTOMRC INTEGER,
    BDTIPOMAQMRC INTEGER,
    BDCODOBSMRC INTEGER,
    BDCODTERNFCE_CFE INTEGER,
    BDTIPCONTADUP INTEGER,
    BDCODTERSER INTEGER,
    BDSERIESER VARCHAR(6),
    BDESPECIESER VARCHAR(5),
    BDDTEMISSAOSER INTEGER,
    BDSUBSTITUIDUPLICATA DM_BOOLEAN,
    BDAPENASCODPRODSAI DM_BOOLEAN,
    BDVINCULOPART INTEGER,
    BDNUMERODOCUMENTOSER INTEGER,
    BDDATAVAZIASER VARCHAR(5),
    BDINDICADORISSSER INTEGER,
    BDDATAEXECUCAOSER INTEGER,    
    BDEXCECAONCM DM_BOOLEAN,
    BDTIPOITEM DM_BOOLEAN,
    BDCADPARTEXTNFSESP DM_BOOLEAN,
    BDNAOVERIFICAIEPART DM_BOOLEAN,
    BDATUEXISTLANCC DM_BOOLEAN,
    BDNAOATUALIZACSTENTRADA boolean,
    BDNAOATUALIZACSTSAIDA boolean,
    BDNAOIMPINFCOMP Boolean)
AS
BEGIN
  SUSPEND;
END^

create or alter procedure SP_VRH_RELATORIOCUSTOCOL_PROV (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRSITCOL smallint,
    PRAGRUPAFILIAIS smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDNOMCOL DM_BDNOMCOL,
    BDPROVFER DM_BOOLEAN,
    BDPROV13 DM_BOOLEAN)
as
BEGIN SUSPEND; END^

create or alter procedure SP_VRH_RELATORIOCUSTOCOL_FN (
    PREMP varchar(10000),
    PRCOL varchar(20000),
    PRAUT varchar(10000),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPA smallint = 0,
    PRCC varchar(10000) = null,
    PRAGRUPAFILIAIS smallint = 0)
returns (
    BDCODEMP integer,
    BDREF integer,
    BDTIPOCOL integer,
    BDCODCOL integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCODFILIAL integer,
    BDCODVER integer,
    BDVALOR numeric(18,6),
    BDCLAVER varchar(20))
as
BEGIN SUSPEND; END^

CREATE OR ALTER PROCEDURE SP_VRH_RELATORIOCUSTOCOL (
    PREMP VARCHAR(15000),
    PRCOL VARCHAR(30000),
    PRAUT VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRSITCOL SMALLINT,
    PRAGRUPA SMALLINT = 0,
    PRCC VARCHAR(10000) = NULL)
RETURNS (
    BDCODEMP INTEGER,
    BDREF INTEGER,
    BDTIPOCOL INTEGER,
    BDCODCOL INTEGER,
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDREMUNERACAO NUMERIC(18,6),
    BDENCREMUNERACAO NUMERIC(18,6),
    BDINSSPATRONAL NUMERIC(18,6),
    BDTERC NUMERIC(18,6),
    BDRAT NUMERIC(18,6),
    BDFGTS NUMERIC(18,6),
    BDRATAPO NUMERIC(18,6),
    BDPROV13 NUMERIC(18,6),
    BDENCPROV13 NUMERIC(18,6),
    BDPROVFER NUMERIC(18,6),
    BDENCPROVFER NUMERIC(18,6),
    BDBENIFICIOS NUMERIC(18,6),
    BDNOMTPCC DM_BDNOMEMP)
AS
BEGIN SUSPEND; END
^
create or alter procedure SP_VRH_REL_CUSTOCOL_7186_CALC (
    PREMP varchar(10000),
    PRCOL varchar(20000),
    PRAUT varchar(10000),
    PRREFINI integer,
    PRCC varchar(5000) = '')
returns (
    BDCODEMP integer,
    BDREFFN integer,
    BDTIPOCOL integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDVALVFN numeric(15,2),
    BDCODCENTRO integer, 
    BDCODTPCC integer,
    BDCODFILIAL integer,
    BDFGTS numeric(15,2),
    BDBASEPIS numeric(15,2))
as
BEGIN SUSPEND; END
^

create or alter procedure SP_VRH_REL_CUSTOCOL_RCONF_CALC (
    PREMP varchar(10000),
    PRCOL varchar(20000),
    PRAUT varchar(10000),
    PRREFINI integer,
    PRCC varchar(5000) = '')
returns (
    BDCODEMP integer,
    BDREFFN integer,
    BDTIPOCOL integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDVALVFN numeric(15,2),
    BDCODCENTRO integer, 
    BDCODTPCC integer,
    BDCODFILIAL integer,
    BDFGTS numeric(15,2),
    BDBASEPIS numeric(15,2))
as
BEGIN SUSPEND; END
^

CREATE OR ALTER procedure SP_VRH_RELATORIOCUSTOCOL_7186 (
    PREMP varchar(10000),
    PRCOL varchar(20000),
    PRAUT varchar(10000),
    PRCLA varchar(5000),
    PRSIND varchar(5000),
    PRFUC varchar(5000),
    PRREFINI integer,
    PRSITCOL smallint)
returns (
    BDREG varchar(4),
    BDCODEMP integer,
    BDREF integer,
    BDTIPOFOLHAID integer,
    BDCODCOL integer,
    BDTIPOCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDSALARIOBRUTO numeric(18,6),
    BDENCREMUNERACAO numeric(18,6),
    BDINSSPATRONAL numeric(18,6),
    BDTERC numeric(18,6),
    BDRAT numeric(18,6),
    BDFGTS numeric(18,6),
    BDRATAPO numeric(18,6),
    BDPROV13 numeric(18,6),
    BDENCPROV13 numeric(18,6),
    BDPROVFER numeric(18,6),
    BDENCPROVFER numeric(18,6),
    BDGRATIFICACOES numeric(18,6),
    BDNOMTPCC DM_BDNOMEMP,
    BDTOTAL numeric(18,6),
    BDCODSIT integer,
    BDDESCSIT varchar(70),
    BDCODFILIAL integer,
    BDNOMEMP DM_BDNOMEMP,
    BDVALORINSS numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDVALORHE numeric(18,6),
    BDOUTROSDESCONTOS numeric(18,6),
    BDSALLIQUIDO numeric(18,6),
    BDGPS numeric(18,6),
    BDPIS numeric(18,6),
    BDOBS varchar(255),
    BDDESCCARGO varchar(40),
    BDCPFCOL varchar(14),
    BDDATAADMCOL date,
    BDDATARESCISAO date,
    BDVALRESCISAO numeric(18,6),
    BDVAL13SALARIO numeric(18,6),
    BDVALFERIAS numeric(18,6),
    BDVALABONOFERIAS numeric(18,6),
    BDQTDHORAS numeric(18,6),
    BDVALUMTERCOABONO numeric(18,6),
    BDFAP numeric(18,6),
    BDMULTAFGTS numeric(18,6),
    BDMULTAFGTSCS numeric(18,6),
    BDFGTSRES numeric(18,6),
    BDINSSPATRONALCOL numeric(18,6),
    BDINSSPATRONALEMP numeric(18,6))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_RELATORIOPLANOSAUDE (
    PREMP VARCHAR(15000),
    PRCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRCODTIPOCONV INTEGER = 0,
    PRFILIAIS SMALLINT = 0,
    PREMPFILIAL VARCHAR(15000) = NULL,
    PRSITPLANO SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDCODMATRIZ INTEGER,
    BDREF INTEGER,
    BDCODCOL INTEGER,
    BDCODDPN INTEGER,
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDCODPLACONVSAU INTEGER,
    BDCODCONVENIO INTEGER,
    BDCODOPERADORA INTEGER,
    BDREFINI INTEGER,
    BDREFFIM INTEGER,
    BDCODTIPOCONV INTEGER,
    BDDESCTIPOCONV VARCHAR(200),
    BDDESCOPERADORA VARCHAR(80),
    BDSITUACAO VARCHAR(30))
AS
BEGIN SUSPEND; END
^


CREATE OR ALTER PROCEDURE SP_COLABORADOR_SEFIP RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDOCORRENCIA VARCHAR(1),
BDPIS VARCHAR(20),
BDADM VARCHAR(10),
BDCATEGORIA VARCHAR(10),
BDNOME VARCHAR(70),
BDMATRICULA VARCHAR(20),
BDCTPS VARCHAR(10),
BDSERIECT DM_SERIECTPS,
BDDATAOPCAO VARCHAR(10),
BDDATANASC VARCHAR(10),
BDCBO VARCHAR(10),
BDCODUF INTEGER,
BDCTAFGTSCOL VARCHAR(20),
BDDSERIECT VARCHAR(1),
BDCPF VARCHAR(14))
 AS
 BEGIN suspend; END
^

create or alter procedure SP_COMP_ACUMULADO_GPS (
    PRCODEMP integer,
    PRAGRUPADO integer,
    PRCODTPCC integer,
    PRANOMES integer,
    PRANOMESPAG integer,
    PRTIPOFOLHA integer,
    PRCHAVEDARF integer = 0,
    PRCODFC integer = 0)
returns (
    BDCOMPENSACAO numeric(15,6),
    BDINICOMP integer,
    BDFIMCOMP integer,
    BDACUMULADO numeric(15,6),
    BDACUMULADOTERC numeric(15,6))
as
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE DEC_REFERENCIA (
    PRREFERENCIA INTEGER,
    PRMESES INTEGER = 1)
RETURNS (
    BDREFERENCIA INTEGER)
AS
BEGIN
 suspend;
END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCST_INCONSISTENCIA (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRDTINV DATE,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCST_BLOCO9 (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRDTINV DATE,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCST_BLOCO0_AUX (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCST_BLOCO0 (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRFINALIDADE INTEGER,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCST_BLOCO2 (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRDTINV DATE,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCST_BLOCOH (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRDTINV DATE,
    PRMOTIVOINVENTARIO INTEGER,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCST (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRDTINV DATE,
    PRMOTIVOINVENTARIO INTEGER,
    PRFINALIDADE INTEGER,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
END
^

CREATE OR ALTER PROCEDURE SP_COPIA_PLANOCONFDRCST(
    PRCODIGOCOPIADO INTEGER,
    PRCODIGONOVO INTEGER)
AS
BEGIN
END
^

CREATE OR ALTER PROCEDURE SP_COPIA_PLANOCONFADRCST(
    PRCODIGOCOPIADO INTEGER,
    PRCODIGONOVO INTEGER)
AS
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_APURACAO_DRCST_APLICA_ACOES (
    PRSESSAO INTEGER,
    PRDATAINICIO DATE,
    PRDATAFIM DATE)
AS
BEGIN
END
^

create or alter procedure SP_APURACAO_DRCST_2113 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN
END
^

create or alter procedure SP_APURACAO_DRCST_2114 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN
END
^

create or alter procedure SP_APURACAO_DRCST_2115 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN
END
^

create or alter procedure SP_APURACAO_DRCST_2112 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN
END
^


create or alter procedure SP_APURACAO_DRCST_2121 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date,
    PRCODPLACONFDRCST integer)
as
declare variable WIGNORARCOMP DM_BOOLEAN;
BEGIN
END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_DRCST_2130_PROD_SAI (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRCODPROD INTEGER,
    PRQUANTIDADE INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCHAVE INTEGER,
    BDORDEM INTEGER,
    BDORDEMPRO INTEGER)
AS
BEGIN
 suspend;
END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_DRCST_2130_PROD_ENT (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRCODPROD INTEGER,
    PRQUANTIDADE INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCHAVE INTEGER,
    BDORDEM INTEGER,
    BDORDEMPRO INTEGER)
AS
declare variable WQTD_ATUAL numeric(15,2);
declare variable WQTD_TOTAL numeric(15,2);
BEGIN
 suspend;
END
^

create or alter procedure SP_APURACAO_DRCST_2130 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN
END
^

create or alter procedure SP_APURACAO_DRCST_2132 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN
END
^

create or alter procedure SP_APURACAO_DRCST_2133 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN
END
^
create or alter procedure SP_APURACAO_DRCST_2134 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN
END
^

create or alter procedure SP_APURACAO_DRCST_2120 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date,
    PRCODPLACONFDRCST integer)
as
begin
end
^

create or alter procedure SP_APURACAO_DRCST_2110 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date,
    PRCODPLACONFDRCST integer)
as
begin
END
^

create or alter procedure SP_APURACAO_DRCST_RESUMO (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
begin
end
^

create or alter procedure SP_APURACAO_DRCST_INCONS (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date,
    PRCODPLACONFDRCST integer)
as
BEGIN
END
^

create or alter procedure SP_APURACAO_DRCST_GRAVAR (
    PRSESSAO integer)
as
BEGIN
END
^

create or alter procedure SP_APURACAO_DRCST (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date,
    PRCODPLACONFDRCST integer)
as
declare variable WREFERENCIA integer;
BEGIN         
END
^

CREATE OR ALTER procedure SP_APURACAO_ADRCST_RESUMO (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN
END
^

create or alter procedure SP_APURACAO_ADRCST_PR_VERIF_ENT (
    PRSESSAO integer,
    PRDATAINI date,
    PRDATAFIM date)
as
declare variable WSQL varchar(20000);
declare variable WCODEMP integer;
declare variable WCODCHAVE integer;
declare variable WPARTENQFED DM_BOOLEAN;
declare variable WCODPLANODEV varchar(100);
declare variable WPLANO integer;
declare variable WCONSUFINAL integer;
declare variable WTODASCFOP DM_BOOLEAN;
declare variable WTODASNCM DM_BOOLEAN;
declare variable WTODOSTER DM_BOOLEAN;
declare variable WTODOSPROD DM_BOOLEAN;
declare variable WTODASCST DM_BOOLEAN;
declare variable WCHAVEDEV integer;
declare variable WREFERENCIA integer;
declare variable WBUSCAANT DM_BOOLEAN;
declare variable WQTDFALTANTE integer;
declare variable WREF12MESES integer;
declare variable WREFATUAL integer;
declare variable WQTDNOVA integer;
declare variable WCODPROD integer;
declare variable WIGNORARPROD DM_BOOLEAN;
BEGIN
END^

CREATE OR ALTER procedure SP_APURACAO_ADRCST_PR_1510_1520 (
    PRSESSAO integer,
    PRDATAINI date,
    PRDATAFIM date)
as
BEGIN         
END
^

create or alter procedure SP_APURACAO_ADRCST_PR_1410_1420 (
    PRSESSAO integer,
    PRDATAINI date,
    PRDATAFIM date)
as
BEGIN         
END
^

create or alter procedure SP_APURACAO_ADRCST_PR_1310_1320 (
    PRSESSAO integer,
    PRDATAINI date,
    PRDATAFIM date)
as
BEGIN         
END
^

create or alter procedure SP_APURACAO_ADRCST_PR_1210_1220 (
    PRSESSAO integer,
    PRDATAINI date,
    PRDATAFIM date)
as
BEGIN
END^

CREATE OR ALTER procedure SP_APURACAO_ADRCST_PR_1110_1120 (
    PRSESSAO integer,
    PRDATAINI date,
    PRDATAFIM date)
as
BEGIN
END^


CREATE OR ALTER procedure SP_APURACAO_ADRCST_PR_1000 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN
END^

create or alter procedure SP_APURACAO_ADRCST_PR_GRAVAR (PRSESSAO integer, PRCODPLACONFADRCST INTEGER)
as
BEGIN
END^

create or alter procedure SP_APURACAO_ADRCST_PR_INCONS (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN
END^

CREATE OR ALTER procedure SP_APURACAO_ADRCST_PR (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date,
    PRCODPLACONFADRCST integer)
as
declare variable WREFERENCIA integer;
BEGIN
END^

create or alter procedure SP_EXPORTA_ADRCST_BLOCO_0 (
    PRCODEMP integer,
    PRREFINI integer,
    PRFINALIDADE integer,
    PRARQUIVO varchar(260) character set WIN1252,
    PRA11R12 INTEGER,
    PRA12R13 INTEGER,
    PRA13R14 INTEGER,
    PRA14R15 INTEGER)
as
BEGIN
END^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_B (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
END^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_C (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
END^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_D (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
END^

create or alter procedure SP_EXPORTA_ADRCST_BLOCO_E (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260) character set WIN1252)
as
BEGIN
END^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_F (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
END^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_G (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
END^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_H (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
END^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_I (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
END^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_J (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
END^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_K (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
END^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_L (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
END^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_M (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
END^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_RESUMO (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
END^

create or alter procedure SP_EXPORTA_ADRCST (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRDTINV DATE,
    PRMOTIVOINVENTARIO INTEGER,
    PRFINALIDADE INTEGER,
    PRARQUIVO VARCHAR(260),
    PRA11R12 INTEGER,
    PRA12R13 INTEGER,
    PRA13R14 INTEGER,
    PRA14R15 INTEGER)
as
  declare variable wDtIni Integer;
  declare variable wDtFim Integer;
  declare variable wLinha blob sub_type 1 segment size 200;
    declare variable wArquivo varchar(260);
begin
END^

CREATE OR ALTER procedure SP_CARREGAFUNC_FOLHA_FISCAL (
    PRCODEMP integer,
    PRREF integer)
as
  declare variable WBDCHAVE integer;
  declare variable WBDNOME varchar(100);
  declare variable WBDCPF varchar(14);
  declare variable WBDESCOLARIDADE integer;
  declare variable WBDDATAADMISSAO date;
  declare variable WBDDATADESLIGAMENTO date;
  declare variable WBDTIPOLAN integer;
begin
end ^

CREATE OR ALTER PROCEDURE SP_COPIA_CONFIGURACAO(
    PRTABELA VARCHAR(64),
    PRCODIGOCOPIADO INTEGER,
    PRCODIGONOVO INTEGER,
    PRCAMPOCODIGO VARCHAR(64))
AS
BEGIN
END
^

create or alter procedure SP_APURACAO_BLOCOM (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PRCONTABILIZAFILIAL DM_BOOLEAN = 'FALSE')
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_M100_M500PAR (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRWHEREEMPRESAS VARCHAR(10000))
AS
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_M100_M500AUX (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRAJUSTESCP DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_M100M500 (
    PRCODQUADRO integer,
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRRETIFICADORA integer,
    PRTABELAREL integer,
    PRAJUSTESCP DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_M100 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRRETIFICADORA integer,
    PRTABELAREL integer)
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_M500 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRRETIFICADORA integer,
    PRTABELAREL integer)
AS
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_M100_M500 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PREXECREL DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_1100_1500 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PRCODEMPSO integer = 0)
as
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_F60013001700 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PRCODEMPSO integer = 0)
as
BEGIN

END
^


create or alter procedure SP_APURACAO_BLOCOM_M300_M700 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PRCODEMPSO integer = 0)
AS
BEGIN

END^


CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_M350 (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER)
AS
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_M400_M800P_2 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRAJUSTESCP varchar(5),
    PRCODEMPSO integer = 0)
AS
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_M400_M800PAR (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRAJUSTESCP varchar(5),
    PRCODEMPSO integer = 0)
AS
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_M400_M800AUX (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRAJUSTESCP DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_M400_M800 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PRCODEMPSO integer = 0)
as
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_M200_M600 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PRCONTABILIZAFILIAL DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_M210_M610 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PREXECREL DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_M210_M610_P2 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRAJUSTESCP DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_INSERT_M210_M610AUX (
    PRINCTRIB INTEGER,
    PRRETIFICADORA INTEGER,
    PRCODEMP INTEGER,
    PRTABELAREL INTEGER)
AS

BEGIN
END
^

create or alter procedure SP_APURACAO_BLOCOM_M210_M610AUX (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PREXECREL DM_BOOLEAN,
    PRCODEMPSO integer = 0)
AS
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_M215_M615 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRRETIFICADORA integer,
    PRAJUSTESCP DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_M220_M620 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PRCODEMPSO integer = 0)
as
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_M230_M630 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRRETIFICADORA integer,
    PRAJUSTESCP DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_M200 (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN)
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_M600 (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN)
AS
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_M200M600_P2 (
    PRCODQUADRO integer,
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRCODEMPSO integer,
    PRRETIFICADORA integer,
    PRVLRSLD numeric(15,2))
AS
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_M200M600 (
    PRCODQUADRO integer,
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRCODEMPSO integer,
    PRRETIFICADORA integer)
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_0110 (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER)
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_BLOCOM_DADOSFINAIS_M400_M800 (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRCODEMPPRINCIPALSCP INTEGER,
    PRRETIFICADORA INTEGER,
    PRAJUSTESCP DM_BOOLEAN)
AS
BEGIN

END
^

create or alter procedure SP_APURACAO_BLOCOM_DADOSFINAIS (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRRETIFICADORA integer,
    PRAJUSTESCP DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_AJUSTACONTAB (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRTIPO VARCHAR(3))
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER)
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_VALIDAONLINE (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRCODEMPPRINCIPALSCP INTEGER)
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER)
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRTIPO VARCHAR(6),
    PRDEBCRED VARCHAR(5) = '')
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRTIPO VARCHAR(6),
    PRDEBCRED VARCHAR(5) = '')
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CONSO (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER)
AS
BEGIN

END
^


CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRCODITEMONLINE INTEGER)
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_VALIDA_DETAL (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRCODCONFBLOCOM INTEGER,
    PRCODPLANOONLINE INTEGER,
    PRCODQUADRO INTEGER,
    PRCODNATBC INTEGER,
    PRVALOR NUMERIC(15,2),
    PRVALORRECEITAFIN numeric(15,2))
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APUR_BLCM_VALIDA_DETAL_CFOP(
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRCODCONFBLOCOM integer,
    PRCODPLANOONLINE integer,
    PRCODQUADRO integer,
    PRCODNAT integer,
    PRCONDPGTO integer,
  PRVALOR NUMERIC(15,2),
  PRCODEMPPRINCIPAL INTEGER)
as
BEGIN
  EXIT;
END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_DADOSCONTAS (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER)
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_CONTABILIZAR (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRULTCHAVE INTEGER,
    PRUSUARIO INTEGER,
    PRULTTRANSACAO INTEGER)
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_GERA_AJUSTES_M220 (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRWHEREEMPRESAS VARCHAR(10000),
    PRAJUSTESCP DM_BOOLEAN,
    PRCODEMPSO INTEGER = 0)
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_REGAUTO (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRRETIFICADORA INTEGER,
    PRULTCHAVEM220 INTEGER)
AS
BEGIN

END
^

CREATE OR ALTER procedure SP_ATU_ESTRUTURA_TEMP (
    PRTABELA varchar(63))
AS
begin
END
^
create or alter procedure SP_COPIA_ACOES_PLANOTROCA (
    PRCODPLANOTROCA integer,
    PRTIPOLANDE integer,
    PRTIPOLANPARA integer,
    PRAGRUPARPLANO varchar(5) = false,
    PRSESSAO integer = 0,
    PRCODPLANOCOPIADO integer = 0)
as
declare variable WSQL3 varchar(30000);
declare variable WCAMPOSCOMCOALESCE2 varchar(20000);
declare variable WCAMPOSPLANO varchar(20000);
declare variable WCODTPIMP integer;
declare variable WCAMPOSFILTROF11 varchar(20000);
declare variable WCOMPLEMENTAINSERT varchar(20000);
declare variable WCAMPOSINSERT varchar(20000);
declare variable WDESC varchar(5);
declare variable WCAMPOSSELECT varchar(20000);
declare variable WBASEISS varchar(5);
declare variable WREDBC varchar(5);
declare variable WST varchar(5);
declare variable WCAMPOSF11 varchar(20000);
declare variable WIPI varchar(5);
declare variable WFRETE varchar(5);
declare variable WDESPACE varchar(5);
declare variable WNFPROD varchar(5);
declare variable WCHAVETPIMP integer;
declare variable WSQL2 varchar(30000);
declare variable WCHAVEANT integer;
declare variable WCHAVE integer;
declare variable WSQL varchar(30000);
declare variable WCODNAT integer;
declare variable WCAMPOSCOMCOALESCE varchar(30000);
declare variable WCAMPOSSOMAESUB varchar(20000);
declare variable WTEXT blob sub_type 1 segment size 64000;
declare variable WCODNATEXIS integer;
BEGIN
END ^ 

create or alter procedure SP_AGRUPAR_NOVO_PLANO (
    PRSESSAO integer,
    PRCODPLANO integer,
    PRCODPLANOCOPIADO integer)
as
declare variable WCAMPOSNOTNULL varchar(10000);
declare variable WCAMPOLIST varchar(200);
declare variable WDESCPLANO varchar(100);
declare variable WQNTREGISTROS integer;
declare variable WAGRUPARPLANO integer;
declare variable WCAMPOSSELECT varchar(10000);
declare variable WCAMPOSINSERT varchar(10000);
declare variable WSQL varchar(10000);
begin
End ^


create or alter procedure SP_ATU_ESTRUTURA_COPIA_PLAN_TEMP (
    PRTABELA varchar(63))
as
declare variable WSQL varchar(10000);
declare variable W_ISNULL varchar(20);
declare variable W_COLUMNS varchar(10000);
declare variable W_SQL_CREATE varchar(10000);
declare variable W_COUNT integer;
begin
End ^ 

create or alter procedure SP_ZERA_CAMPOS_NUMERICOS (
    PRTABELA varchar(31),
    PRFILTROWHERE varchar(255),
    PRPREFIXO varchar(3),
    PRRECURSIVO char(1) = 'S' 
)
as
BEGIN
END ^

create or alter procedure SP_CANCELAR_LAN_BASE_SER
as
Begin
end ^

create or alter procedure SP_ATU_EST_TEMP_RECURSIVO (
    PRTABELA varchar(63),
    PRPREFIXO varchar(10))
AS
begin
END
^

CREATE OR ALTER procedure SP_CARREGA_TABTEMP (
    PRTABELA varchar(63),
    PRWHERE varchar(10000) not null,
    PREDITCHAVE varchar(63),
    PRSESSAO integer)
as
begin
END ^


CREATE OR ALTER procedure SP_CARREGA_TABTEMP_RECURSIVO (
    PRTABELA varchar(63),
    PRPREFIXO varchar(10),
    PRWHERE varchar(10000),
    PREDITCHAVE varchar(63),
    PRSESSAO integer,
    PRTAB_EXCLUIDAS varchar(10000))
as
begin
END ^

CREATE OR ALTER procedure SPCOMMITA_TEMP (
    PRTABELA varchar(63),
    PRSESSAO integer)
as
begin
END
^

CREATE OR ALTER procedure SPCOMMITA_TEMP_RECURSIVA (
    PRTABELA varchar(63),
    PRPREFIXO varchar(10),
    PRSESSAO integer,
    PRTAB_EXCLUIDAS varchar(10000))
as
begin
end
^

CREATE OR ALTER procedure SPLIMP_TEMP (
    PRTABELA varchar(63),
    PRSESSAO integer)
as
begin
end
^

create or alter procedure SPLIMP_TEMP_RECURSIVO (
    PRTABELA varchar(63),
    PRPREFIXO varchar(10),
    PRSESSAO integer)
as
begin
end
^

create or alter procedure SP_UPDATE_TABTEMP (
    PRTABELA varchar(63),
    PRUSING varchar(10000) not null,
    PRVINCULO varchar(10000) not null,
    PR_MATCHED varchar(10000) not null,
    PR_NOT_MATCHED varchar(10000) not null)
as
begin
end
^

create or alter procedure SP_UPDATE_TABTEMP_RECURSIVO (
    PRTABELA varchar(63),
    PRPREFIXO varchar(10),
    PRTAB_EXCLUIDAS varchar(10000),
    PRUSING varchar(10000) not null,
    PRVINCULO varchar(10000) not null,
    PR_MATCHED varchar(10000) not null,
    PR_NOT_MATCHED varchar(10000) not null,
    PR_AUTO_EXECUTE integer,
    PRSESSAO integer)
as
begin
end
^

create or alter procedure SP_FISCAL_RATEIA_CFOP_ECREDAC (
    PRSESSAO integer)
as
begin
end
^

create or alter procedure SP_FISCAL_RATEIA_CFOP_INF_NF_SP (
    PRSESSAO integer)
as
begin
end
^

create or alter procedure SP_FISCAL_RATEIA_CFOP_IVA (
    PRSESSAO integer)
as
begin
end
^

create or alter procedure SP_FISCAL_RATEIA_CFOP_MVASC (
    PRSESSAO integer)
as
begin 
end
^

create or alter procedure SP_FISCAL_RATEIA_CFOP_MVAPR (
    PRSESSAO integer)
as
begin 
end
^

create or alter procedure SP_FISCAL_RATEIA_CFOP_MVA (
    PRSESSAO integer)
as
begin 
end
^

create or alter procedure SP_FISCAL_RATEIA_PMPF (
    PRSESSAO integer)
as
begin 
end
^

create or alter procedure SP_FISCAL_RATEIA_CFOP_DCIP (
    PRSESSAO integer)
as
begin 
end
^

create or alter procedure SP_FISCAL_RATEIA_CFOP_ANTIMP (
    PRSESSAO integer)
as
begin
end
^

create or alter procedure SP_FISCAL_RATEIA_CFOP_ANTPR (
    PRSESSAO integer)
as
begin
end
^

create or alter procedure SP_FISCAL_RATEIA_CFOP_DAPI (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
begin
end
^

create or alter procedure SP_FISCAL_RATEIA_CFOP_SN (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
begin
end
^

create or alter procedure SP_FISCAL_RATEIA_CFOP_Q48 (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
begin
end
^

create or alter procedure SP_FISCAL_RATEIA_CFOP_PR (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
begin
end
^

create or alter procedure SP_FISCAL_RATEIA_OCOSP (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
begin
end
^

create or alter procedure SP_FISCAL_RATEIA_IMPRETSP (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
begin
end
^

create or alter procedure SP_FISCAL_RATEIA_CFOP_MOVCC (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
begin
end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_MOVRAT (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
Begin
end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_DIFPR (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
begin
end
^

create or alter procedure SP_FISCAL_RATEIA_CFOP_DIFALIQ (
    PRSESSAO integer not null,
    PRMOVIMENTO integer not null)
as
begin
end
^

CREATE OR ALTER procedure SP_FISCAL_RATEIA_CFOP (
    PRSESSAO integer not null,
    PRMOVIMENTO integer not null)
as
declare variable WMOV varchar(3);
declare variable WSQL varchar(30000);
begin
end
^

CREATE OR ALTER procedure SP_NOTAS_ENVIO_IMENDES (
    PRCODEMP varchar(5000),
    PRDATAINICIAL date,
    PRDATAFIM date,
    PRMOVENT DM_BOOLEAN,
    PRMOVSAI DM_BOOLEAN,
    PRMOVREDZ DM_BOOLEAN,
    PRCODTER varchar(5000),
    PRCODPROD varchar(5000),
    PRCODNAT varchar(5000),
    PRDOCUMENTO varchar(5000))
as
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_AUDITANOTAS_IMENDES_UPDT (
    PRCODEMP VARCHAR(30000),
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRSESSAO INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(5000);
BEGIN
END^

CREATE OR ALTER procedure SP_AUDITANOTAS_IMENDES_SAI (
    PRCODEMP varchar(30000),
    PRDATAINI date,
    PRDATAFIM date,
    PRSESSAO integer,
    PRREFERENCIA integer)
as
BEGIN
END^

CREATE OR ALTER procedure SP_AUDITANOTAS_IMENDES_ENT (
    PRCODEMP varchar(30000),
    PRDATAINI date,
    PRDATAFIM date,
    PRSESSAO integer,
    PRREFERENCIA integer)
as
BEGIN
END^

CREATE OR ALTER procedure SP_AUDITANOTAS_IMENDES_REDZ (
    PRCODEMP varchar(30000),
    PRDATAINI date,
    PRDATAFIM date,
    PRSESSAO integer)
as
BEGIN
END^

CREATE OR ALTER procedure SP_AUDITANOTAS_IMENDES (
    PRCODEMP varchar(30000),
    PRDATAINI date,
    PRDATAFIM date,
    PRSESSAO integer,
    PRCOMPARATIVO integer = -1,
    PRSOSELECT varchar(5) = 'FALSE')
as
BEGIN
END^

create or alter procedure SP_CARREGA_SIM_IM_REFTRIB (
    PRANO integer,
    PRSESSAO integer)
as
begin
end^

create or alter procedure SP_CARREGADADOS_SIM_IM_REFTRIB (
    PRCHAVE integer)
as
Begin
end^

create or alter procedure SP_SIM_IM_REFTRIB_LOAD_MOVPROD (
    PRCAMPODATA varchar(20),
    PRMOVIMENTO varchar(3),
    PRANO integer,
    PRCODMOV integer,
    PRCHAVE integer,
    PRMESES varchar(30))
as
begin
end^

create or alter procedure SP_SIM_IM_REFTRIB_LOAD_MOVSPROD (
    PRCAMPODATA varchar(20),
    PRMOVIMENTO varchar(3),
    PRANO integer,
    PRCODMOV integer,
    PRCHAVE integer)
as begin end^ 

-- Camilla M. Criado apuração do RET - Registro 1800 - Sped Contribuições

CREATE OR ALTER PROCEDURE SP_APURACAO_RET1800AUX (
    PRCODEMP integer,
    PRREFERENCIA integer,
    BDCODREC varchar(10),
    BDCAMPOREC varchar(25))
as
BEGIN
END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_RET1800 (
    PRCODEMP integer,
    PRREFERENCIA integer)
as
begin

end^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_RET1800 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN)
as
declare variable WOPTANTERET DM_BOOLEAN;
declare variable WEXISTEAPUR varchar(50);
declare variable WSQL varchar(32751);
BEGIN

END
^


CREATE OR ALTER TRIGGER TMP_VEF_EMP_APURET1800_TEMP_BI0 FOR TMP_VEF_EMP_APURET1800_TEMP
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end^

CREATE OR ALTER trigger tmp_vef_emp_tmova1923_pl_t_bu0 for tmp_vef_emp_tmovaju1923_pl_temp
active before update position 0
AS
begin
end^

create or alter procedure SP_COPIA_PLANOCONF1900 (
    PRCODIGOCOPIADO integer,
    PRCODIGONOVO integer)
as
begin

end^

create or alter procedure SP_BUSCAR_ENQ_FED_CAT42 (
    PRCHAVEMOV integer,
    PRCODPLACAT42SP integer,
    PRCHAVE integer,
    PRCODTER integer,
    PRCODPROD integer,
    PRCODNAT integer,
    PRCODCST integer,
    PRNCMPROD integer,
    PRMOV char(4))
returns (
    BDCODENQLEG integer)
as
begin
    suspend;
end^

CREATE OR ALTER procedure SP_APURAR_CAT42SP_1100_REFRESH (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer)
as
begin
end^

CREATE OR ALTER PROCEDURE SP_GET_VALOR_ICMS_SUP_ENT (
    PRCODEMP INTEGER,
    PRCHAVE INTEGER,
    PRORDEM INTEGER,
    PRORDEMPRO INTEGER,
    PRALIQINT DM_NUMERIC_7_4_ALIQ)
RETURNS (
    BDVL_ICMS_SUP_ENT DM_NUMERIC_15_2)
AS
DECLARE VARIABLE WOUTROS DM_NUMERIC_15_2;
DECLARE VARIABLE WVAL DM_NUMERIC_15_2;
DECLARE VARIABLE WVLRICMSEFET DM_NUMERIC_15_2;
DECLARE VARIABLE WALIQ DM_NUMERIC_7_4_ALIQ;
DECLARE VARIABLE WVLRIVA DM_NUMERIC_15_2;
BEGIN
  BDVL_ICMS_SUP_ENT = 0;

  SELECT COALESCE(P.BDFCPRETIDO, 0) +
         COALESCE(P.BDVLRFCP, 0) +
         COALESCE(P.BDVLRFCPSTRET, 0),
         IIF(COALESCE(P.BDBCST, 0) > 0, P.BDBCST,
         IIF(COALESCE(P.BDBCICMSSTRET, 0) > 0, P.BDBCICMSSTRET, 0)),
         COALESCE(P.BDVLRICMSEFET, 0),
         IIF(COALESCE(PRO.BDALIQICMS, 0) > 0, PRO.BDALIQICMS, :PRALIQINT) / 100,
         COALESCE(IVA.BDICMSRECOLHER, 0)
  FROM VEF_EMP_TMOVPROENT P
  JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
  LEFT OUTER JOIN (
                   SELECT IVA.BDCODEMP, IVA.BDCHAVE, IVA.BDORDEM, IVA.BDCODPROD, SUM(COALESCE(IVA.BDBASECALC * (IVA.BDALIQINTERNA / 100), 0)) BDICMSRECOLHER
                   FROM VEF_EMP_TMOVENT_IVA IVA
                   WHERE IVA.BDCODEMP = 900016
                   GROUP BY IVA.BDCODEMP, IVA.BDCHAVE, IVA.BDORDEM, IVA.BDCODPROD
                  ) IVA ON (IVA.BDCODEMP = P.BDCODEMP AND IVA.BDCHAVE = P.BDCHAVE AND IVA.BDORDEM = P.BDORDEM AND IVA.BDCODPROD = P.BDCODPROD)
  WHERE P.BDCODEMP = :PRCODEMP
  AND P.BDCHAVE = :PRCHAVE
  AND P.BDORDEM = :PRORDEM
  AND P.BDORDEMPRO = :PRORDEMPRO
  INTO :wOutros, :wVal, :wVlrICMSEfet,
       :wAliq, :wVlrIVA;

  BDVL_ICMS_SUP_ENT = :wOutros;
  IF (:wVal = 0) THEN
    BEGIN
      IF (:wVlrIVA = 0) THEN
        wVal = :wVlrICMSEfet;
      ELSE
        BDVL_ICMS_SUP_ENT = :BDVL_ICMS_SUP_ENT + :wVlrIVA;
    END

  IF (:wVal > 0) THEN
    BDVL_ICMS_SUP_ENT = :BDVL_ICMS_SUP_ENT + (:wVal * :wAliq);

  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_ESTOQUE_INICIAL_CAT42SP (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS
BEGIN
END^

CREATE OR ALTER procedure SP_APURAR_CAT42SP_1100 (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer)
as
BEGIN
END^

create or alter procedure SP_COPIA_PLANOCONF1250 (
    PRCODIGOCOPIADO integer,
    PRCODIGONOVO integer)
as
begin

end^

CREATE OR ALTER PROCEDURE SP_GERACODIGOS_CADPROD (
    PRSESSAO INTEGER,
    PRULTIMOCOD INTEGER)
AS
begin

end^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOC_ENT_AUX (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260),
    PRTIPOEXPCODPART INTEGER,
    PRPERFIL INTEGER,
    PRCODPLAPADRAOREF INTEGER,
    PRSESSAOSEGREG INTEGER)
as
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOC_ENT (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260),
    PRTIPOEXPCODPART INTEGER,
    PRPERFIL INTEGER,
    PRCODPLAPADRAOREF INTEGER,
    PRSESSAOSEGREG INTEGER)
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOC_SAI_AUX (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260),
    PRTIPOEXPCODPART INTEGER,
    PRPERFIL INTEGER,
    PRSESSAOSEGREG INTEGER)
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOC500 (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRCODPLAPADRAOREF integer,
    PRVALIDAREXPORTACAO boolean,
    PRARQUIVO varchar(260),
    PREXPSER varchar(5),
    PRSESSAOSEGREG integer,
    PRMOV integer,
    PREXPORTARC170EMISSAOPROPRIA varchar(5),
    PRCHAVENF integer)
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOC_SAI (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260),
    PRTIPOEXPCODPART INTEGER,
    PRPERFIL INTEGER,
    PRCODPLAPADRAOREF INTEGER,
    PRSESSAOSEGREG INTEGER)
AS
BEGIN

END
^

--Larissa - 18/03/2021 - Sped Fiscal - Notas de serviços #143666
CREATE OR ALTER procedure SP_EXPORTA_BLOCOC_SER (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRTIPOEXPCODPART integer, 
    PRCODPLAPADRAOREF integer)
AS
BEGIN

END
^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOD_SAI_D300 (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRPERFIL integer,
    PRCODPLAPADRAOREF integer)as
BEGIN

END^


CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOD_SAI_D400 (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260),
    PRTIPOEXPCODPART INTEGER,
    PRCODPLAPADRAOREF INTEGER,
    PRPERFIL INTEGER)
as
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOD_SAI_D700 (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260))
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOD_ENT_D700 (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260),
    PRTIPOEXPCODPART INTEGER)
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOD_D700 (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260))
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOD_SAI (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260),
    PRTIPOEXPCODPART INTEGER,
    PRCODPLAPADRAOREF INTEGER,
    PRPERFIL INTEGER)
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOD_ENT (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260),
    PRTIPOEXPCODPART INTEGER,
    PRCODPLAPADRAOREF INTEGER) 
AS
BEGIN

END^

create or alter procedure SP_BUSCAR_ENQ_FED_CAT42 (
    PRCHAVEMOV integer,
    PRCODPLACAT42SP integer,
    PRCHAVE integer,
    PRCODTER integer,
    PRCODPROD integer,
    PRCODNAT integer,
    PRCODCST integer,
    PRNCMPROD integer,
    PRMOV char(4))
returns (
    BDCODENQLEG integer)
as
begin
    suspend;
end^

CREATE OR ALTER procedure SP_APURAR_CAT42SP_1100_REFRESH (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer)
as
begin
end^

CREATE OR ALTER PROCEDURE SP_GET_VALOR_ICMS_SUP_ENT (
    PRCODEMP INTEGER,
    PRCHAVE INTEGER,
    PRORDEM INTEGER,
    PRORDEMPRO INTEGER,
    PRALIQINT DM_NUMERIC_7_4_ALIQ)
RETURNS (
    BDVL_ICMS_SUP_ENT DM_NUMERIC_15_2)
AS
DECLARE VARIABLE WOUTROS DM_NUMERIC_15_2;
DECLARE VARIABLE WVAL DM_NUMERIC_15_2;
DECLARE VARIABLE WVLRICMSEFET DM_NUMERIC_15_2;
DECLARE VARIABLE WALIQ DM_NUMERIC_7_4_ALIQ;
DECLARE VARIABLE WVLRIVA DM_NUMERIC_15_2;
BEGIN
  BDVL_ICMS_SUP_ENT = 0;

  SELECT COALESCE(P.BDFCPRETIDO, 0) +
         COALESCE(P.BDVLRFCP, 0) +
         COALESCE(P.BDVLRFCPSTRET, 0),
         IIF(COALESCE(P.BDBCST, 0) > 0, P.BDBCST,
         IIF(COALESCE(P.BDBCICMSSTRET, 0) > 0, P.BDBCICMSSTRET, 0)),
         COALESCE(P.BDVLRICMSEFET, 0),
         IIF(COALESCE(PRO.BDALIQICMS, 0) > 0, PRO.BDALIQICMS, :PRALIQINT) / 100,
         COALESCE(IVA.BDICMSRECOLHER, 0)
  FROM VEF_EMP_TMOVPROENT P
  JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
  LEFT OUTER JOIN (
                   SELECT IVA.BDCODEMP, IVA.BDCHAVE, IVA.BDORDEM, IVA.BDCODPROD, SUM(COALESCE(IVA.BDBASECALC * (IVA.BDALIQINTERNA / 100), 0)) BDICMSRECOLHER
                   FROM VEF_EMP_TMOVENT_IVA IVA
                   WHERE IVA.BDCODEMP = 900016
                   GROUP BY IVA.BDCODEMP, IVA.BDCHAVE, IVA.BDORDEM, IVA.BDCODPROD
                  ) IVA ON (IVA.BDCODEMP = P.BDCODEMP AND IVA.BDCHAVE = P.BDCHAVE AND IVA.BDORDEM = P.BDORDEM AND IVA.BDCODPROD = P.BDCODPROD)
  WHERE P.BDCODEMP = :PRCODEMP
  AND P.BDCHAVE = :PRCHAVE
  AND P.BDORDEM = :PRORDEM
  AND P.BDORDEMPRO = :PRORDEMPRO
  INTO :wOutros, :wVal, :wVlrICMSEfet,
       :wAliq, :wVlrIVA;

  BDVL_ICMS_SUP_ENT = :wOutros;
  IF (:wVal = 0) THEN
    BEGIN
      IF (:wVlrIVA = 0) THEN
        wVal = :wVlrICMSEfet;
      ELSE
        BDVL_ICMS_SUP_ENT = :BDVL_ICMS_SUP_ENT + :wVlrIVA;
    END

  IF (:wVal > 0) THEN
    BDVL_ICMS_SUP_ENT = :BDVL_ICMS_SUP_ENT + (:wVal * :wAliq);

  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_ESTOQUE_INICIAL_CAT42SP (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS
BEGIN
END^

CREATE OR ALTER procedure SP_APURAR_CAT42SP_1100 (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer)
as
BEGIN
END^

DROP EXTERNAL FUNCTION GETCONFIGURACAOSN ^

DECLARE EXTERNAL FUNCTION GETCONFIGURACAOSN
RETURNS CSTRING(32765) FREE_IT
ENTRY_POINT 'GETCONFIGURACAOSN' MODULE_NAME 'DllExternalFile.dll' ^

DROP EXTERNAL FUNCTION GETQUANTIDADEPRODUTO ^

DECLARE EXTERNAL FUNCTION GETQUANTIDADEPRODUTO CSTRING(50), CSTRING(25)
RETURNS CSTRING(25) FREE_IT ENTRY_POINT 'GETQUANTIDADEPRODUTO' MODULE_NAME 'DllExternalFile.dll'^

CREATE or alter trigger tlog_biu0 for tlog
active before insert or update position 0
AS
begin
end^

CREATE OR ALTER trigger vrh_emp_tferias_biu0 for vrh_emp_tferias
active before insert or update position 0
AS
begin
end^

--#191029 
CREATE OR ALTER TRIGGER VEF_REINF_EVT_BU0 FOR VEF_REINF_EVT
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END
^
--#191029 
CREATE OR ALTER TRIGGER VEF_REINF_EVT_BI0 FOR VEF_REINF_EVT
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER trigger vrh_esocial_tarquivo_xml_biu0 for vrh_esocial_tarquivo_xml
active before insert or update position 0
AS
begin
end^

CREATE OR ALTER TRIGGER VEF_BASE_TLOGJSONIMENDES_BI0 FOR VEF_BASE_TLOGJSONIMENDES
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TLOGERROIMENDES_BI0 FOR VEF_BASE_TLOGERROIMENDES
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN  
END^

CREATE OR ALTER trigger vrh_esocial_tlote_arquivos_biu0 for vrh_esocial_tlote_arquivos
active before insert or update position 0
AS
begin
end^

CREATE OR ALTER TRIGGER VFIN_ESC_TRECEBFATURAFILE_BI0 FOR VFIN_ESC_TRECEBIMENTOFATURAFILE ACTIVE BEFORE INSERT POSITION 0 AS begin end ^
CREATE OR ALTER TRIGGER VFIN_ESC_TRECEBFATURAFILE_AD0 FOR VFIN_ESC_TRECEBIMENTOFATURAFILE ACTIVE AFTER DELETE POSITION 0 AS begin end ^
CREATE OR ALTER TRIGGER VFIN_ESC_TPAGAMENTOSFILE_BI0 FOR VFIN_ESC_TPAGAMENTOSFILE ACTIVE BEFORE INSERT POSITION 0 AS begin end ^
CREATE OR ALTER TRIGGER VFIN_ESC_TPAGAMENTOSFILE_AD0 FOR VFIN_ESC_TPAGAMENTOSFILE ACTIVE AFTER DELETE POSITION 0 AS begin end ^

DROP EXTERNAL FUNCTION ZIPBLOB ^

DECLARE EXTERNAL FUNCTION ZIPBLOB
    BLOB,
    BLOB
RETURNS PARAMETER 2
ENTRY_POINT 'ZIPBLOB' MODULE_NAME 'DLLExternalFile.dll'^

DROP EXTERNAL FUNCTION UNZIPBLOB ^

DECLARE EXTERNAL FUNCTION UNZIPBLOB
    BLOB,
    BLOB
RETURNS PARAMETER 2
ENTRY_POINT 'UNZIPBLOB' MODULE_NAME 'DLLExternalFile.dll'^

DROP EXTERNAL FUNCTION SETQUANTIDADEPRODUTO ^

DECLARE EXTERNAL FUNCTION SETQUANTIDADEPRODUTO CSTRING(20)
RETURNS CSTRING(25) FREE_IT ENTRY_POINT 'SETQUANTIDADEPRODUTO' MODULE_NAME 'DllExternalFile.dll'^

create or alter procedure SP_EXPORTA_DIMOB (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRDECLRETIF varchar(5),
    PRNUMRECIBO varchar(10),
    PRSITUACAOESPECIAL varchar(5),
    PRDATAEVENTO date,
    PRSITEVENTO integer,
    PRCONSOLIDAR varchar(5),
    PREXPBAIXPAR varchar(5),
    PRVERORGAOPUBLICO varchar(5))
as
BEGIN

END^

DROP EXTERNAL FUNCTION SETORDEMSEQUENCIAL_STR ^

DROP EXTERNAL FUNCTION SETQUANTIDADEPRODUTO ^

DECLARE EXTERNAL FUNCTION SETQUANTIDADEPRODUTO CSTRING(20)
RETURNS CSTRING(25) FREE_IT ENTRY_POINT 'SETQUANTIDADEPRODUTO' MODULE_NAME 'DllExternalFile.dll'^

create or alter function F_IR_ISENTO_ESTRANGEIRO (
    PRCODCLA integer, 
	PRTRIBUTACAOEXTERIOR integer)
returns boolean
as
begin
  IF ((PRCODCLA = 31) and (COALESCE(PRTRIBUTACAOEXTERIOR,0) IN (40, 41, 42, 43, 44, 50))) THEN
    RETURN TRUE;
  ELSE
    RETURN FALSE;
end^

execute block
as
begin
  if ((SELECT COUNT(*) QTDE FROM RDB$FUNCTIONS WHERE RDB$FUNCTION_NAME='CURRENT_INSTANCE') = 0) then
  begin
    execute statement 'DECLARE EXTERNAL FUNCTION CURRENT_INSTANCE RETURNS INTEGER BY VALUE ENTRY_POINT '''||'CURRENT_INSTANCE'||''' MODULE_NAME '''||'DllExternalFile.dll'||''';';
  end
end^

execute block
as
begin
  if ((SELECT COUNT(*) QTDE FROM RDB$FUNCTIONS WHERE RDB$FUNCTION_NAME='SETORDEMSEQUENCIAL_STR') = 0) then
  begin
    execute statement 'DECLARE EXTERNAL FUNCTION SETORDEMSEQUENCIAL_STR INTEGER RETURNS INTEGER BY VALUE ENTRY_POINT '''||'SETORDEMSEQUENCIAL_STR'||''' MODULE_NAME '''||'DllExternalFile.dll'||''';';
  end
end^

execute block
as
begin
  if ((SELECT COUNT(*) QTDE FROM RDB$FUNCTIONS WHERE RDB$FUNCTION_NAME='GETORDEMSEQUENCIAL_STR') = 0) then
  begin
    execute statement 'DECLARE EXTERNAL FUNCTION GETORDEMSEQUENCIAL_STR CSTRING(200), INTEGER RETURNS INTEGER BY VALUE ENTRY_POINT '''||'GETORDEMSEQUENCIAL_STR'||''' MODULE_NAME '''||'DllExternalFile.dll'||''';';
  end
end^

CREATE OR ALTER PROCEDURE SP_GET_INSERT (
    PRTABLE VARCHAR(50) NOT NULL,
    PRAPELIDO VARCHAR(10),
    PRUPDATEORINSERT DM_BOOLEAN = 'FALSE')
RETURNS (
    BDINSERT VARCHAR(10000))
AS
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_SCRIPT_CONTAB (
    PRCODEMP INTEGER NOT NULL,
    PRDATAINI DATE NOT NULL,
    PRDATAFIM DATE NOT NULL,
    PRFILE VARCHAR(260),
    PRTIPOLAN CHAR(4))
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_CONTABILIZACAO (
    PRCODEMP INTEGER NOT NULL,
    PRDATAINI DATE NOT NULL,
    PRDATAFIM DATE NOT NULL,
    PRENT DM_BOOLEAN,
    PRSAI DM_BOOLEAN,
    PRSER DM_BOOLEAN,
    PRREDZ DM_BOOLEAN,
    PRDIRETORIO VARCHAR(150))
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE VCT_USUARIO_RESP_TAREFAS (
    PRCODSER integer,
    PRCODOBR integer,
    PRCODIMP integer)
AS 
BEGIN

END^

create or alter procedure VRH_SP_DADOS_PREPSITUACAO (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRDATINI date,
    PRDATFIM date,
    PRRETONARSITEMPORIG varchar(5) = 'FALSE')
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODSIT integer,
    BDDATAINISEFIP date,
    BDDATAINISIT date,
    BDDATAFIMSIT date,
    BDDIASSIT integer,
    BDNBENEFICIOSIT varchar(20),
    BDDATAPERICIASIT date,
    BDDATAPARTOSIT date,
    BDDESCSIT varchar(70),
    BDGRUPOSIT integer,
    BDCODVER integer,
    BDCODMFGENT integer,
    BDCODMFGSAI integer,
    BDCARENSIT integer,
    BDCODVER15DIAS integer,
    BDTIPOPERDESIT integer,
    BDSALFAMSIT varchar(5),
    BDCODSEFENT varchar(5),
    BDCODSEFSAI varchar(5),
    BDRELSIT integer,
    BDINSSINTSIT DM_BOOLEAN,
    BDDIASATESTADO integer,
    BDNAOPRORROGAFERIAS varchar(5))
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(15000);
declare variable WEMPORIG integer;
declare variable WCOLORIG integer;
declare variable WEMPX integer;
declare variable WCOLX integer;
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCSTSP_1200 (
    PRARQUIVO VARCHAR(260),
    PRCODEMP INTEGER,
    PRREFATU INTEGER,
    PRREFINI INTEGER)
AS
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCSTSP (
    PRCODEMP INTEGER,
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRMOTIVOINVENTARIO INTEGER,
    PRFINALIDADE INTEGER,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
END^

CREATE OR ALTER procedure SP_REMOVER_ACENTOS (
    PRTEXTO varchar(9999))
returns (
    BDRETORNO varchar(9999))
AS
BEGIN
  SUSPEND;
END^

CREATE OR ALTER TRIGGER VRH_EMP_TSITCOL_BIU0 FOR VRH_EMP_TSITCOL
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRH_EMP_TSITCOL_BIU0 FOR VRH_EMP_TSITCOL
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRH_EMP_TSITCOL_DEC_AI0 FOR VRH_EMP_TSITCOL_DEC
ACTIVE AFTER INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRH_EMP_TSITCOL_DEC_AD0 FOR VRH_EMP_TSITCOL_DEC
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END^

DROP PROCEDURE SP_VRHF_PROCESSO_AUMENTO^
DROP PROCEDURE SP_FGTS_DIGITAL_COMP^
DROP PROCEDURE SP_VRHF_EMP_TVERBAFN_DET^
DROP PROCEDURE SP_TOMADOR_COM_ENDERECO^
DROP PROCEDURE SP_VRH_EMP_TCOLCON_CAD^
DROP PROCEDURE SP_VRH_EXP_DADOS_DA_FOLHA^
DROP PROCEDURE SP_VRH_EXP_DADOS_DA_FOLHA_SQL^
DROP PROCEDURE SP_VRH_RELATORIOPLANOSAUDE_NOVO ^

DROP PROCEDURE VSUC_SP_REL_CTA_MOVIMENTADA^



DROP PROCEDURE SP_EXPORTA_ECREDRURAL ^

DROP PROCEDURE SP_EXPORTA_DRCST ^
DROP PROCEDURE SP_EXPORTA_DRCST_BLOCO0 ^
DROP PROCEDURE SP_EXPORTA_DRCST_BLOCO0_AUX ^
DROP PROCEDURE SP_EXPORTA_DRCST_BLOCO2 ^
DROP PROCEDURE SP_EXPORTA_DRCST_BLOCO9 ^
DROP PROCEDURE SP_EXPORTA_DRCST_BLOCOH ^
DROP PROCEDURE SP_EXPORTA_DRCST_INCONSISTENCIA ^
                                       
DROP PROCEDURE SP_COPIA_PLANOCONFDRCST ^
DROP PROCEDURE SP_COPIA_PLANOCONFADRCST ^          

DROP PROCEDURE SP_RETIRAR_CARACTER_ESP ^
                                       
DROP PROCEDURE SP_APURACAO_DRCST ^
DROP PROCEDURE SP_APURACAO_DRCST_2113 ^
DROP PROCEDURE SP_APURACAO_DRCST_2114 ^
DROP PROCEDURE SP_APURACAO_DRCST_2115 ^
DROP PROCEDURE SP_APURACAO_DRCST_2112 ^
DROP PROCEDURE SP_APURACAO_DRCST_2121 ^
DROP PROCEDURE SP_APURACAO_DRCST_2130 ^
DROP PROCEDURE SP_APURACAO_DRCST_2130_PROD_ENT ^
DROP PROCEDURE SP_APURACAO_DRCST_2130_PROD_SAI ^
DROP PROCEDURE SP_APURACAO_DRCST_2132 ^
DROP PROCEDURE SP_APURACAO_DRCST_2133 ^
DROP PROCEDURE SP_APURACAO_DRCST_2134 ^
DROP PROCEDURE SP_APURACAO_DRCST_2120 ^
DROP PROCEDURE SP_APURACAO_DRCST_2110 ^
DROP PROCEDURE SP_APURACAO_DRCST_RESUMO ^
DROP PROCEDURE SP_APURACAO_DRCST_INCONS ^
DROP PROCEDURE SP_APURACAO_DRCST_GRAVAR ^
DROP PROCEDURE SP_APURACAO_DRCST_APLICA_ACOES ^

DROP PROCEDURE SP_APURACAO_ADRCST_PR^
DROP PROCEDURE SP_APURACAO_ADRCST_PR_GRAVAR^
DROP PROCEDURE SP_APURACAO_ADRCST_PR_INCONS^
DROP PROCEDURE SP_APURACAO_ADRCST_PR_1110_1120^
DROP PROCEDURE SP_APURACAO_ADRCST_PR_1000^
DROP PROCEDURE SP_APURACAO_ADRCST_PR_1210_1220^
DROP PROCEDURE SP_APURACAO_ADRCST_PR_1310_1320^
DROP PROCEDURE SP_APURACAO_ADRCST_PR_1410_1420^
DROP PROCEDURE SP_APURACAO_ADRCST_PR_1510_1520^
DROP PROCEDURE SP_APURACAO_ADRCST_PR_VERIF_ENT^ 
DROP PROCEDURE SP_APURACAO_ADRCST_RESUMO^

DROP PROCEDURE SP_EXPORTA_ADRCST^
DROP PROCEDURE SP_EXPORTA_ADRCST_BLOCO_0^
DROP PROCEDURE SP_EXPORTA_ADRCST_BLOCO_B^
DROP PROCEDURE SP_EXPORTA_ADRCST_BLOCO_C^
DROP PROCEDURE SP_EXPORTA_ADRCST_BLOCO_D^
DROP PROCEDURE SP_EXPORTA_ADRCST_BLOCO_E^
DROP PROCEDURE SP_EXPORTA_ADRCST_BLOCO_F^
DROP PROCEDURE SP_EXPORTA_ADRCST_BLOCO_G^
DROP PROCEDURE SP_EXPORTA_ADRCST_BLOCO_H^
DROP PROCEDURE SP_EXPORTA_ADRCST_BLOCO_I^
DROP PROCEDURE SP_EXPORTA_ADRCST_BLOCO_J^
DROP PROCEDURE SP_EXPORTA_ADRCST_BLOCO_K^
DROP PROCEDURE SP_EXPORTA_ADRCST_BLOCO_L^
DROP PROCEDURE SP_EXPORTA_ADRCST_BLOCO_M^
DROP PROCEDURE SP_EXPORTA_ADRCST_BLOCO_RESUMO^

DROP PROCEDURE SP_CARREGAFUNC_FOLHA_FISCAL^

DROP PROCEDURE SP_COPIA_CONFIGURACAO ^

DROP PROCEDURE SP_APURACAO_BLOCOM ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M100_M500PAR ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M100_M500AUX ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M100_M500 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M100M500 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M100 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M500 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_1100_1500 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_F60013001700 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M300_M700 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M350 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M400_M800 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M400_M800P_2 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M400_M800PAR ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M400_M800AUX ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M200_M600 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M210_M610 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M210_M610_P2 ^
DROP PROCEDURE SP_APURACAO_INSERT_M210_M610AUX ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M210_M610AUX ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M215_M615 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M220_M620 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M230_M630 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M200 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M600 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M200M600_P2 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_M200M600 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_0110 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_DADOSFINAIS ^
DROP PROCEDURE SP_BLOCOM_DADOSFINAIS_M400_M800 ^
DROP PROCEDURE SP_APURACAO_BLOCOM_AJUSTACONTAB ^
DROP PROCEDURE SP_APURACAO_BLOCOM_ONLINE ^
DROP PROCEDURE SP_APURACAO_BLOCOM_VALIDAONLINE ^
DROP PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS ^
DROP PROCEDURE SP_APURACAO_BLOCOM_VALIDA_DETAL ^
DROP PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CONSO ^
DROP PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED ^
DROP PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB ^
DROP PROCEDURE SP_COPIA_ACOES_PLANOTROCA ^
DROP PROCEDURE SP_AGRUPAR_NOVO_PLANO ^
DROP PROCEDURE SP_ATU_ESTRUTURA_COPIA_PLAN_TEMP ^
DROP PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL ^
DROP PROCEDURE SP_APURACAO_BLOCOM_DADOSCONTAS ^
DROP PROCEDURE SP_APURACAO_BLOCOM_CONTABILIZAR ^
DROP PROCEDURE SP_APURACAO_BLOCOM_RET1800^
DROP PROCEDURE SP_ATU_ESTRUTURA_TEMP^
DROP PROCEDURE SP_ZERA_CAMPOS_NUMERICOS^
DROP PROCEDURE SP_CANCELAR_LAN_BASE_SER^
DROP PROCEDURE SP_CARREGA_TABTEMP_RECURSIVO^
DROP PROCEDURE SPCOMMITA_TEMP^
DROP PROCEDURE SPCOMMITA_TEMP_RECURSIVA^
DROP PROCEDURE SPLIMP_TEMP^
DROP PROCEDURE SPLIMP_TEMP_RECURSIVO^
DROP PROCEDURE SP_UPDATE_TABTEMP^
DROP PROCEDURE SP_UPDATE_TABTEMP_RECURSIVO^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP_ECREDAC^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP_INF_NF_SP^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP_IVA^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP_MVASC^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP_MVAPR^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP_MVA^
DROP PROCEDURE SP_FISCAL_RATEIA_PMPF^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP_DCIP^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP_ANTIMP^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP_ANTPR^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP_DAPI^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP_SN^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP_Q48^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP_PR^
DROP PROCEDURE SP_FISCAL_RATEIA_OCOSP^
DROP PROCEDURE SP_FISCAL_RATEIA_IMPRETSP^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP_MOVCC^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP_MOVRAT^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP_DIFPR^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP_DIFALIQ^
DROP PROCEDURE SP_FISCAL_RATEIA_CFOP^
DROP PROCEDURE SP_NOTAS_ENVIO_IMENDES^
DROP PROCEDURE SP_AUDITANOTAS_IMENDES^
DROP PROCEDURE SP_AUDITANOTAS_IMENDES_SAI^
DROP PROCEDURE SP_AUDITANOTAS_IMENDES_ENT^
DROP PROCEDURE SP_AUDITANOTAS_IMENDES_REDZ^
DROP PROCEDURE SP_AUDITANOTAS_IMENDES_UPDT^
DROP PROCEDURE SP_CARREGADADOS_SIM_IM_REFTRIB^
DROP PROCEDURE SP_SIM_IM_REFTRIB_LOAD_MOVPROD^
DROP PROCEDURE SP_SIM_IM_REFTRIB_LOAD_MOVSPROD^
DROP PROCEDURE SP_CARREGA_SIM_IM_REFTRIB^
DROP PROCEDURE SP_EXPORTA_CONTABILIZACAO ^
DROP PROCEDURE SP_EXPORTA_SCRIPT_CONTAB ^
DROP PROCEDURE SP_GET_INSERT ^
DROP PROCEDURE SP_VALIDA_EMAIL ^
DROP PROCEDURE SP_VALIDA_CPF_CNPJ ^
DROP PROCEDURE SP_AUDITOR_FISCAL ^
DROP PROCEDURE SP_AUDITORIA_REINF ^
DROP PROCEDURE SP_AUDITORIA_REINF_R1000 ^
DROP PROCEDURE SP_AUDITORIA_REINF_R2050 ^
DROP PROCEDURE SP_AUDITORIA_REINF_R2055 ^
DROP PROCEDURE SP_AUDITORIA_REINF_R2060 ^
DROP PROCEDURE SP_AUDITORIA_REINF_R2010_2020 ^
DROP PROCEDURE SP_AUD_DESC_DETALHADA_INCON ^
DROP PROCEDURE SP_EXPORTA_BLOCO1900^
DROP PROCEDURE SP_VALORES_1920^
DROP PROCEDURE SP_CODRECEXP^
DROP PROCEDURE SP_ATUALIZAR_TMP_1921^
DROP PROCEDURE SP_ATUALIZAR_TMP_1923^
DROP PROCEDURE SP_ATUALIZAR_TMP_1926^
DROP PROCEDURE SP_GRAVAR_DAO^
DROP PROCEDURE SP_SET_MASK^
DROP PROCEDURE SP_APLICA_PLANO_1900^
DROP PROCEDURE SP_APLICA_PLANO_1900_REDZ^
DROP PROCEDURE SP_COMMIT_PLANO_1900^
DROP PROCEDURE SP_APURACAO_RET1800AUX^
DROP PROCEDURE SP_APURACAO_RET1800^
DROP PROCEDURE SP_COMMIT_IMP_LANC_CONTABIL^
DROP PROCEDURE SP_ATUALIZAR_TMP_VSUC_TLAN^
DROP procedure SP_ATU_TMP_VSUC_COMPL_ASTERISCO^
DROP PROCEDURE SP_ATUALIZAR_TMP_VSUC_TLCC^
DROP PROCEDURE SP_ATUALIZAR_TMP_VSUC_TLPR^
DROP PROCEDURE SP_APLICA_PLANO_1250^
DROP PROCEDURE SP_GRAVA_PLANO_1250^
DROP PROCEDURE SP_REGISTROS_PLANO_1250^
DROP PROCEDURE SP_DEVOLUCOES_PLANO_1250^
DROP PROCEDURE SP_MEMCALCULO_PLANO_1250^
DROP PROCEDURE SP_INSEREREG_PLANO_1250^
DROP PROCEDURE SP_APLICA_PLANO_CC_AUTO^
DROP PROCEDURE FILTRO_DOWNLOAD_ESOCIAL^

CREATE OR ALTER PROCEDURE SP_TIRATODOSSINAIS (
    STR VARCHAR(32000))
RETURNS (
    RESULT VARCHAR(32000))
AS
BEGIN
  SUSPEND;
END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_ISS_RECIFE (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRTIPOLANC INTEGER,
    PRRETIFICADORA INTEGER,
    PRARQUIVO VARCHAR(260))
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_ISS_CURITIBA (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRTIPOLANC INTEGER,
    PRRETIFICADORA INTEGER,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_ISS_CURITIBA_REG_E_R (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRTIPOLANC INTEGER,
    PRRETIFICADORA INTEGER,
    PRARQUIVO VARCHAR(260),
    PRTIPOLANCEXP INTEGER)
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK210 (
    PRSESSAO INTEGER,
    PRSESSAOPRO INTEGER,
    PRULTCHAVE INTEGER)
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK260 (
    PRSESSAO INTEGER,
    PRULTCHAVE INTEGER)
AS
BEGIN

END^

DROP PROCEDURE SP_ATUALIZAR_TMP_BLOCOK210^
DROP PROCEDURE SP_ATUALIZAR_TMP_BLOCOK260^

CREATE OR ALTER PROCEDURE CLEAR_ALL_TEMPORARY_TABLE
AS
declare variable WTABELA varchar(250);
BEGIN
  /*
    Sol: 14207 Patrick T. Sá 24/04/2016. Implementada importação temporaria de participantes e lançamentos de saída.
    Tabelas que iniciam com TMP e terminam com TEMP devem ser limpas sempre que o servidor ligar/reiniciar.
    TMP - Tabelas temporárias(Global temporary table)
    TMP_TTABLE_TEMP - Tabelas temporárias sem ser global temporary table.
  */
  --22326
  FOR SELECT RDB$RELATION_NAME FROM RDB$RELATIONS
      WHERE RDB$SYSTEM_FLAG = 0
      AND RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
      ORDER BY RDB$RELATION_NAME
      INTO :wTabela
  DO
    EXECUTE STATEMENT 'DELETE FROM '||wTabela;
    
  /*
    Sol: 14207 Patrick T. Sá 03/05/2016. Deve apagar todos os registros das tabelas de inconsistencias existentes. ao ligar/reiniciar o servidor.
  */
  FOR SELECT RDB$RELATION_NAME FROM RDB$RELATIONS
      WHERE  RDB$RELATION_NAME LIKE 'VEF_INCON_%'
         or  RDB$RELATION_NAME LIKE 'VSUC_INCON_%'
      ORDER BY RDB$RELATION_NAME
      INTO :wTabela
  DO
    EXECUTE STATEMENT 'DELETE FROM '||wTabela; 

  /*Não é temporaria*/
  execute statement 'DELETE FROM TEXPORTACAO_SPED      WHERE BDID IS NOT NULL;';
  execute statement 'DELETE FROM TEXPORTACAO_SPED_INCO WHERE BDID IS NOT NULL;';
    
  execute statement 'DELETE FROM TCONTEXTO_DB;';
    
  execute statement 'DELETE FROM TMP_VEF_BASE_TOBSERVACAO;';

  execute statement 'DELETE FROM TMP_CHAVE_SEGREG_CFOP;';
END^

create or alter procedure SP_CARREGAR_TMP_TCADPRO (
    PRINICIALIZANDOSERVIDOR DM_BOOLEAN)
as
declare variable WBDCODPROD integer;
declare variable WNAOCARREGARTMP DM_BOOLEAN;
BEGIN
/*
    -Carregar as temporárias, na TPARAMETRO o parâmetro NAOCARREGARTEMPORARIAS afeta como rotina irá funcionar
    tanto o BDVALORSTR, quanto o BDVALORINT alteram o comportamento da rotina de suas formas

    BDVALORINT (Usado na rotina do uServidorMetodos):
    -Sem parâmetro (Padrão) (0 ou null):
       -No expediente: só carrega diferenças
       -Fora do expediente: carrega tudo
       -Reinício manual: carrega tudo
    -Com parâmetro
       -Se 1 (só diferenças)
          -No expediente: só carrega diferenças
          -Fora do expediente: só carrega diferenças
          -Reinício manual: só carrega diferenças
       -Se 2 (tudo)
          -No expediente: carrega tudo
          -Fora do expediente: carrega tudo
          -Reinício manual: carrega tudo
       -Se 3 (tudo no fim de semana)
         -No expediente: só carrega diferenças
         -Fora do expediente: só carrega diferenças na maioria dos dias, no sábado ele carrega tudo (Na MG é na sexta)
         -Reinício manual: só carrega diferenças na maioria dos dias, no sábado ele carrega tudo (Na MG é na sexta)
       Independente da opção, ele só carrega tudo uma vez a cada 23 horas

    BDVALORSTR (Usado pelas SPs, Exemplo: SP_CARREGAR_TMP_TCADPRO):
    NÃO MEXER NUNCA, NUNQUINHA, O FALSE NÃO FUNCIONA DIREITO, TEM ROTINA QUE CARREGA A MESMA COISA DUAS VEZES
    SEMPRE QUE MEXER AQUI FALAR COM O FISCAL
    -TRUE (Padrão, deve estar sempre com essa opção nos clientes):
      Carrega o que ainda não tem na tabela
    -FALSE:
      Carrega tudo, mesmo que já tenha na tabela
      
    No mundo ideal, esses parâmetros seriam unificados. 
    Nas Sps, deveria ter um parametro para dizer se está carregando tudo ou só as diferenças
    Quando carregar tudo, deveria executar como se o NAOCARREGARTEMPORARIAS estivesse false; e
    Quando carrega só as diferenças deveria executar como se o NAOCARREGARTEMPORARIAS estivesse true.
    Na teoria, mas sinceramente, passar como true sempre é bem melhor, não é lento suficiente pra ser um problema,
    além disso o FALSE é bugado. SE MEXER NISSO FALAR COM O FISCAL.
*/

  wNaoCarregarTMP = 'FALSE';
  select first 1 bdVALORSTR from TPARAMETRO where bdPARAM='NAOCARREGARTEMPORARIAS' into :wNaoCarregarTMP;


  execute statement 'DELETE FROM TMP_TCADPRO_A_VALIDAR;';


  SELECT FIRST 1 BDCODPROD FROM TMP_TCADPRO INTO :wBDCODPROD;

  IF ((:wBDCODPROD IS NULL) OR (:wBDCODPROD = 0) or ((:PRINICIALIZANDOSERVIDOR = 'TRUE') and (:wNaoCarregarTMP = 'TRUE'))) THEN
    BEGIN
      if (:wNaoCarregarTMP = 'TRUE') then
        begin
          execute statement          
    
              '/*Insert dos produtos unicos*/ '||
              'INSERT INTO TMP_TCADPRO (BDSESSAO, BDEDITCHAVE, BDCODPROD, BDAPELIDOUNICO, BDDESCRICAOUNICA, '||
              '                         BDCODIGOEAN, BDCODTIPO, BDCODGEN, BDCODSER, BDCODCOMBANP, '||
              '                         BDPRODINCENTIVADO,BDCODITEMGIAF,BDINCENTIVOTRANSP,BDOPEDIFIMPORTACAO) '||
              'SELECT 0 BDSESSAO, '||
              '       PRO.BDCODPROD BDEDITCHAVE, '||
              '       PRO.BDCODPROD, '||
              '       PRO.bdapelidounico bdAPELIDOUNICO, '||
              '       PRO.bddescricaounica BDDESCRICAOUNICA, '||
              '       PRO.bdcodigoean BDCODIGOEAN, '||
              '       COALESCE(PRO.BDCODTIPO,0) BDCODTIPO, '||
              '       COALESCE(PRO.BDCODGEN,0) BDCODGEN, '||
              '       COALESCE(PRO.BDCODSER,0) BDCODSER, '||
              '       COALESCE(PRO.BDCODCOMBANP,0) BDCODCOMBANP, '||
              '       PRO.BDPRODINCENTIVADO, PRO.BDCODITEMGIAF, '||
              '       PRO.BDINCENTIVOTRANSP,PRO.BDOPEDIFIMPORTACAO '||
              'FROM TCADPRO PRO '||
              'LEFT OUTER JOIN TMP_TCADPRO TMP ON (TMP.BDSESSAO = 0 AND TMP.bdcodprod = PRO.bdcodprod AND TMP.BDCODEMP IS NULL) '||
              'WHERE TMP.BDSESSAO IS NULL; ';

          execute statement
              '/*Insere os produtos por empresa*/ '||
              'INSERT INTO TMP_TCADPRO (BDSESSAO, BDEDITCHAVE, BDCODPROD, BDCODEMP, BDCODSAIDA, BDAPEPROD, BDDESCPROD, '||
              '                         BDAPELIDOUNICO, BDDESCRICAOUNICA, BDCODIGOEAN, BDCODTIPO, BDCODGEN, BDCODSER, '||
              '                         BDCODCOMBANP, BDCODUNIMED, BDNCMPROD, BDCODTABINCID, BDGRUPO, BDORDEMMARCA, '||
              '                         BDCODCSTIPISAI, BDCODCSTIPIENT, BDCODCSTICMS, BDCODCSTPISSAI, BDCODCSTPISENT, '||
              '                         BDCODCSTCOFENT, BDCODCSTCOFSAI,BDINATIVO, '||
              '                         BDPRODINCENTIVADO,BDCODITEMGIAF,BDINCENTIVOTRANSP,BDOPEDIFIMPORTACAO, BDALIQFCP,BDPERCMVA) '||
              'SELECT 0 BDSESSAO, '||
              '       PRO.BDCODPROD BDEDITCHAVE, '||
              '       PRO.BDCODPROD, '||
              '       PROV.BDCODEMP, '||
              '       COALESCE(PROV.bdcodsaida, '''') BDCODsaida, '||
              '       PROV.bdapeprod bdapeprod, '||
              '       PROV.bddescprod bddescproD, '||
              '       PRO.bdapelidounico bdAPELIDOUNICO, '||
              '       PRO.bddescricaounica BDDESCRICAOUNICA, '||
              '       PRO.bdcodigoean BDCODIGOEAN, '||
              '       COALESCE(PRO.BDCODTIPO,0) BDCODTIPO, '||
              '       COALESCE(PRO.BDCODGEN,0) BDCODGEN, '||
              '       COALESCE(PRO.BDCODSER,0) BDCODSER, '||
              '       COALESCE(PRO.BDCODCOMBANP,0) BDCODCOMBANP, '||
              '       COALESCE(PROV.BDCODUNIMED,0) BDCODUNIMED, '||
              '       COALESCE(PROV.BDNCMPROD,0) BDNCMPROD, '||
              '       COALESCE(PROV.bdcodtabincid,0) BDCODTABINCID, '||
              '       COALESCE(PROV.bdgrupo,0) BDGRUPO, '||
              '       COALESCE(PROV.bdordemmarca,0) BDORDEMMARCA, '||
              '       COALESCE(PROV.BDCODCSTIPISAI,0) BDCODCSTIPISAI, '||
              '       COALESCE(PROV.BDCODCSTIPIENT,0) BDCODCSTIPIENT, '||
              '       COALESCE(PROV.BDCODCSTICMS,0) BDCODCSTICMS, '||
              '       COALESCE(PROV.BDCODCSTPISSAI,0) BDCODCSTPISSAI, '||
              '       COALESCE(PROV.BDCODCSTPISENT,0) BDCODCSTPISENT, '||
              '       COALESCE(PROV.BDCODCSTCOFENT,0) BDCODCSTCOFENT, '||
              '       COALESCE(PROV.BDCODCSTCOFSAI,0) BDCODCSTCOFSAI, '||
              '       PROV.BDINATIVO,PROV.BDPRODINCENTIVADO,PROV.BDCODITEMGIAF, '||
              '       PROV.BDINCENTIVOTRANSP,PROV.BDOPEDIFIMPORTACAO, '||
              '       PROV.BDALIQFCP,PROV.BDPERCMVA '||
              'FROM TCADPRO PRO '||
              'LEFT OUTER JOIN tcadpro_vinc PROV ON PROV.BDCODPROD = PRO.BDCODPROD '||
              'LEFT OUTER JOIN TMP_TCADPRO TMP ON (TMP.BDSESSAO = 0 AND TMP.bdcodprod = PROV.bdcodprod AND TMP.BDCODEMP = PROV.BDCODEMP) '||
              'WHERE ((PROV.BDCODEMP IS NOT NULL) AND (PROV.BDCODEMP > 0)) '||
              '  and TMP.BDSESSAO IS NULL; ';

          execute statement
              '/* CARREGADO OS PRODUTOS POR PARTICIPANTE */ '||
              'INSERT INTO TMP_TCADPRO_PART (BDSESSAO,BDEDITCHAVE,BDCODPROD,BDCODTER,BDCODENTRADA,BDDESCPRODBUSCA, BDORDEM) '||
              'SELECT 0 BDSESSAO, P.BDCODPROD BDEDITCHAVE, P.BDCODPROD, P.bdcodter, COALESCE(P.bdcodentrada, ''''), COALESCE(P.bddescprodbusca, ''''), P.BDORDEM FROM TCADPRO_PART P '||
              'LEFT OUTER JOIN TMP_TCADPRO_PART TMP ON (TMP.BDSESSAO = 0 AND TMP.bdcodprod = P.bdcodprod AND TMP.bdordem = P.bdordem) '||
              'WHERE TMP.BDSESSAO IS NULL; ';
        END
      ELSE
    BEGIN
      execute statement
          '/*Insert dos produtos unicos*/ '||
          'INSERT INTO TMP_TCADPRO (BDSESSAO, BDEDITCHAVE, BDCODPROD, BDAPELIDOUNICO, BDDESCRICAOUNICA, '||
          '                         BDCODIGOEAN, BDCODTIPO, BDCODGEN, BDCODSER, BDCODCOMBANP, '||
          '                         BDPRODINCENTIVADO,BDCODITEMGIAF,BDINCENTIVOTRANSP,BDOPEDIFIMPORTACAO) '||
          'SELECT 0 BDSESSAO, '||
          '       PRO.BDCODPROD BDEDITCHAVE, '||
          '       PRO.BDCODPROD, '||
          '       PRO.bdapelidounico bdAPELIDOUNICO, '||
          '       PRO.bddescricaounica BDDESCRICAOUNICA, '||
          '       PRO.bdcodigoean BDCODIGOEAN, '||
          '       COALESCE(PRO.BDCODTIPO,0) BDCODTIPO, '||
          '       COALESCE(PRO.BDCODGEN,0) BDCODGEN, '||
          '       COALESCE(PRO.BDCODSER,0) BDCODSER, '||
          '       COALESCE(PRO.BDCODCOMBANP,0) BDCODCOMBANP, '||
          '       PRO.BDPRODINCENTIVADO, PRO.BDCODITEMGIAF, '||
          '       PRO.BDINCENTIVOTRANSP,PRO.BDOPEDIFIMPORTACAO '||
          'FROM TCADPRO PRO; ';

      execute statement
          '/*Insere os produtos por empresa*/ '||
          'INSERT INTO TMP_TCADPRO (BDSESSAO, BDEDITCHAVE, BDCODPROD, BDCODEMP, BDCODSAIDA, BDAPEPROD, BDDESCPROD, '||
          '                         BDAPELIDOUNICO, BDDESCRICAOUNICA, BDCODIGOEAN, BDCODTIPO, BDCODGEN, BDCODSER, '||
          '                         BDCODCOMBANP, BDCODUNIMED, BDNCMPROD, BDCODTABINCID, BDGRUPO, BDORDEMMARCA, '||
          '                         BDCODCSTIPISAI, BDCODCSTIPIENT, BDCODCSTICMS, BDCODCSTPISSAI, BDCODCSTPISENT, '||
          '                         BDCODCSTCOFENT, BDCODCSTCOFSAI,BDINATIVO, '||
          '                         BDPRODINCENTIVADO,BDCODITEMGIAF,BDINCENTIVOTRANSP,BDOPEDIFIMPORTACAO, BDALIQFCP,BDPERCMVA) '||
          'SELECT 0 BDSESSAO, '||
          '       PRO.BDCODPROD BDEDITCHAVE, '||
          '       PRO.BDCODPROD, '||
          '       PROV.BDCODEMP, '||
          '       COALESCE(PROV.bdcodsaida, '''') BDCODsaida, '||
          '       PROV.bdapeprod bdapeprod, '||
          '       PROV.bddescprod bddescproD, '||
          '       PRO.bdapelidounico bdAPELIDOUNICO, '||
          '       PRO.bddescricaounica BDDESCRICAOUNICA, '||
          '       PRO.bdcodigoean BDCODIGOEAN, '||
          '       COALESCE(PRO.BDCODTIPO,0) BDCODTIPO, '||
          '       COALESCE(PRO.BDCODGEN,0) BDCODGEN, '||
          '       COALESCE(PRO.BDCODSER,0) BDCODSER, '||
          '       COALESCE(PRO.BDCODCOMBANP,0) BDCODCOMBANP, '||
          '       COALESCE(PROV.BDCODUNIMED,0) BDCODUNIMED, '||
          '       COALESCE(PROV.BDNCMPROD,0) BDNCMPROD, '||
          '       COALESCE(PROV.bdcodtabincid,0) BDCODTABINCID, '||
          '       COALESCE(PROV.bdgrupo,0) BDGRUPO, '||
          '       COALESCE(PROV.bdordemmarca,0) BDORDEMMARCA, '||
          '       COALESCE(PROV.BDCODCSTIPISAI,0) BDCODCSTIPISAI, '||
          '       COALESCE(PROV.BDCODCSTIPIENT,0) BDCODCSTIPIENT, '||
          '       COALESCE(PROV.BDCODCSTICMS,0) BDCODCSTICMS, '||
          '       COALESCE(PROV.BDCODCSTPISSAI,0) BDCODCSTPISSAI, '||
          '       COALESCE(PROV.BDCODCSTPISENT,0) BDCODCSTPISENT, '||
          '       COALESCE(PROV.BDCODCSTCOFENT,0) BDCODCSTCOFENT, '||
          '       COALESCE(PROV.BDCODCSTCOFSAI,0) BDCODCSTCOFSAI, '||
          '       PROV.BDINATIVO,PROV.BDPRODINCENTIVADO,PROV.BDCODITEMGIAF, '||
          '       PROV.BDINCENTIVOTRANSP,PROV.BDOPEDIFIMPORTACAO, '||
          '       PROV.BDALIQFCP,PROV.BDPERCMVA '||
          'FROM TCADPRO PRO '||
          'LEFT OUTER JOIN tcadpro_vinc PROV ON PROV.BDCODPROD = PRO.BDCODPROD '||
          'WHERE ((PROV.BDCODEMP IS NOT NULL) AND (PROV.BDCODEMP > 0)); ';

      execute statement
          '/* CARREGADO OS PRODUTOS POR PARTICIPANTE */ '||
          'INSERT INTO TMP_TCADPRO_PART (BDSESSAO,BDEDITCHAVE,BDCODPROD,BDCODTER,BDCODENTRADA,BDDESCPRODBUSCA, BDORDEM) '||
          'SELECT 0 BDSESSAO, P.BDCODPROD BDEDITCHAVE, P.BDCODPROD, P.bdcodter, COALESCE(P.bdcodentrada, ''''), COALESCE(P.bddescprodbusca, ''''), P.BDORDEM FROM TCADPRO_PART P; ';

      execute statement
          '/* CARREGADO OS PRODUTOS POR PARTICIPANTE */ '||
          'INSERT INTO TMP_TCADPRO_PART (BDSESSAO,BDEDITCHAVE,BDCODPROD,BDCODTER,BDCODENTRADA,BDDESCPRODBUSCA, BDORDEM) '||
          'SELECT 0 BDSESSAO, P.BDCODPROD BDEDITCHAVE, P.BDCODPROD, P.bdcodter, COALESCE(P.bdcodentrada, ''''), COALESCE(P.bddescprodbusca, ''''), P.BDORDEM FROM TCADPRO_PART P; ';

    END  
    END
END^

create or alter procedure SP_CARREGAR_TMP_TTERCEIRO (
    PRINICIALIZANDOSERVIDOR DM_BOOLEAN)
as
declare variable WBDCODTER integer;
declare variable WNAOCARREGARTMP DM_BOOLEAN;
BEGIN
/*
    -Carregar as temporárias, na TPARAMETRO o parâmetro NAOCARREGARTEMPORARIAS afeta como rotina irá funcionar
    tanto o BDVALORSTR, quanto o BDVALORINT alteram o comportamento da rotina de suas formas

    BDVALORINT (Usado na rotina do uServidorMetodos):
    -Sem parâmetro (Padrão) (0 ou null):
       -No expediente: só carrega diferenças
       -Fora do expediente: carrega tudo
       -Reinício manual: carrega tudo
    -Com parâmetro
       -Se 1 (só diferenças)
          -No expediente: só carrega diferenças
          -Fora do expediente: só carrega diferenças
          -Reinício manual: só carrega diferenças
       -Se 2 (tudo)
          -No expediente: carrega tudo
          -Fora do expediente: carrega tudo
          -Reinício manual: carrega tudo
       -Se 3 (tudo no fim de semana)
         -No expediente: só carrega diferenças
         -Fora do expediente: só carrega diferenças na maioria dos dias, no sábado ele carrega tudo (Na MG é na sexta)
         -Reinício manual: só carrega diferenças na maioria dos dias, no sábado ele carrega tudo (Na MG é na sexta)
       Independente da opção, ele só carrega tudo uma vez a cada 23 horas

    BDVALORSTR (Usado pelas SPs, Exemplo: SP_CARREGAR_TMP_TCADPRO):
    NÃO MEXER NUNCA, NUNQUINHA, O FALSE NÃO FUNCIONA DIREITO, TEM ROTINA QUE CARREGA A MESMA COISA DUAS VEZES
    SEMPRE QUE MEXER AQUI FALAR COM O FISCAL
    -TRUE (Padrão, deve estar sempre com essa opção nos clientes):
      Carrega o que ainda não tem na tabela
    -FALSE:
      Carrega tudo, mesmo que já tenha na tabela
      
    No mundo ideal, esses parâmetros seriam unificados. 
    Nas Sps, deveria ter um parametro para dizer se está carregando tudo ou só as diferenças
    Quando carregar tudo, deveria executar como se o NAOCARREGARTEMPORARIAS estivesse false; e
    Quando carrega só as diferenças deveria executar como se o NAOCARREGARTEMPORARIAS estivesse true.
    Na teoria, mas sinceramente, passar como true sempre é bem melhor, não é lento suficiente pra ser um problema,
    além disso o FALSE é bugado. SE MEXER NISSO FALAR COM O FISCAL.
*/

  wNaoCarregarTMP = 'FALSE';
  select first 1 bdVALORSTR from TPARAMETRO where bdPARAM='NAOCARREGARTEMPORARIAS' into :wNaoCarregarTMP;

  SELECT FIRST 1 BDCODTER FROM TMP_TTERCEIRO INTO :wBDCODTER;

  IF ((:wBDCODTER IS NULL) OR (:wBDCODTER = 0) or ((:PRINICIALIZANDOSERVIDOR = 'TRUE') and (:wNaoCarregarTMP = 'TRUE'))) THEN
  BEGIN
    if (:wNaoCarregarTMP = 'TRUE') then
      begin
        execute statement
            'INSERT INTO TMP_TTERCEIRO (BDSESSAO, BDEDITCHAVE, BDCODTER, BDCGCTER, BDIETER, BDAPELIDOTER, '||
            '                           BDNOMETER, BDCODCID, BDCODPAIS, BDPARTEXIST, BDREF_MAX) '||
            'SELECT 0 BDSESSAO, '||
            '       X.BDCODTER BDEDITCHAVE, '||
            '       X.BDCODTER, '||
            '       COALESCE(TER.BDCGCTER, '''') BDCGCTER, '||
            '       COALESCE(REF.BDIETER, '''') BDIETER, '||
            '       COALESCE(REF.BDAPELIDOTER, '''') BDAPELIDOTER, '||
            '       COALESCE(REF.BDNOMETER, '''') BDNOMETER, '||
            '       COALESCE(REF.BDCODCID, 0) BDCODCID, '||
            '       COALESCE(REF.BDCODPAIS, 0) BDCODPAIS, '||
            '       '||'''TRUE'''||' BDPARTEXIST, '||
            '       REF.BDREFEMP '||
            'FROM (SELECT R.BDCODTER, MAX(R.BDREFEMP) BDREFEMP '||
            '      FROM TTERCEIRO_REF R '||
            '      GROUP BY R.BDCODTER) X '||
            'INNER JOIN TTERCEIRO TER ON TER.BDCODTER = X.BDCODTER '||
            '    INNER JOIN TTERCEIRO_REF REF ON REF.BDCODTER = X.BDCODTER AND REF.BDREFEMP = X.BDREFEMP '||
            '    LEFT OUTER JOIN TMP_TTERCEIRO TMP ON (TMP.BDSESSAO = 0 AND TMP.BDEDITCHAVE = X.BDCODTER) '||
            '    WHERE TMP.BDSESSAO IS NULL '||
            '      AND ((ter.bdINATIVO IS NULL) or (ter.bdINATIVO = ''FALSE'')); '; -- Alt.: #203025 - Nao deve carregar participantes inativos
      end
    else
      begin
        execute statement
            'INSERT INTO TMP_TTERCEIRO (BDSESSAO, BDEDITCHAVE, BDCODTER, BDCGCTER, BDIETER, BDAPELIDOTER, '||
            '                       BDNOMETER, BDCODCID, BDCODPAIS, BDPARTEXIST, BDREF_MAX) '||
            'SELECT 0 BDSESSAO, '||
            '       X.BDCODTER BDEDITCHAVE, '||
            '       X.BDCODTER, '||
            '       COALESCE(TER.BDCGCTER, '''') BDCGCTER, '||
            '       COALESCE(REF.BDIETER, '''') BDIETER, '||
            '       COALESCE(REF.BDAPELIDOTER, '''') BDAPELIDOTER, '||
            '       COALESCE(REF.BDNOMETER, '''') BDNOMETER, '||
            '       COALESCE(REF.BDCODCID, 0) BDCODCID, '||
            '       COALESCE(REF.BDCODPAIS, 0) BDCODPAIS, '||
            '       '||'''TRUE'''||' BDPARTEXIST, '||
            '       REF.BDREFEMP '||
            'FROM (SELECT R.BDCODTER, MAX(R.BDREFEMP) BDREFEMP '||
            '      FROM TTERCEIRO_REF R '||
            '      GROUP BY R.BDCODTER) X '||
            'INNER JOIN TTERCEIRO TER ON TER.BDCODTER = X.BDCODTER '||
            'INNER JOIN TTERCEIRO_REF REF ON REF.BDCODTER = X.BDCODTER AND REF.BDREFEMP = X.BDREFEMP '||
            'WHERE ((ter.bdINATIVO IS NULL) or (ter.bdINATIVO = ''FALSE'')); '; -- Alt.: #203025 - Nao deve carregar participantes inativos
      end
  END

END
^

CREATE OR ALTER PROCEDURE SP_VRHF_UNION_FN_FT_MES (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(32700),
    PRANOMES INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREFFN INTEGER,
    BDCODVER INTEGER,
    BDCOMPESP VARCHAR(300),
    BDFORMREFAUX VARCHAR(5000),
    BDFORMREF VARCHAR(5000),
    BDFORMVAL VARCHAR(5000),
    BDREFVFN_SUM NUMERIC(15,6),
    BDREFAUXVFN_SUM NUMERIC(15,6),
    BDREFVFN_MAX NUMERIC(15,6),
    BDREFAUXVFN_MAX NUMERIC(15,6),
    BDVALVFN NUMERIC(15,6),
    BDVALVIFN NUMERIC(15,6),
    BDIGNREFVFN DM_BOOLEAN,
    BDIGNREFAVFN DM_BOOLEAN,
    BDIGNVALVFN DM_BOOLEAN,
    BDORVERBA INTEGER,
    BDALTINT BOOLEAN)
AS
BEGIN
  SUSPEND;
END^


create or alter procedure SP_VRHF_UNION_INT_INTTOM_MES (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRCONTRATO integer,
    PRANOMES integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDCODCONTTI integer,
    BDCODVER integer,
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDREFVFN_SUM numeric(15,6),
    BDREFAUXVFN_SUM numeric(15,6),
    BDREFVFN_MAX numeric(15,6),
    BDREFAUXVFN_MAX numeric(15,6),
    BDVALVFN numeric(15,6),
    BDVALVIFN numeric(15,6),
    BDIGNREFVFN DM_BOOLEAN,
    BDIGNREFAVFN DM_BOOLEAN,
    BDIGNVALVFN DM_BOOLEAN,
    BDORVERBA integer,
    BDALTINT boolean)
as
BEGIN
  SUSPEND;
END^

create or alter procedure VTPO_INDICADOR_TEMPO (
    PRDATAINI date,
    PRDATAFIN date)
returns (
    BDCODEMP integer,
    BDTEMPO_LIQUIDO integer,
    BDTEMPO_SOBREPOSTO integer,
    BDDATAINI date,
    BDHORAINI time,
    BDDATAFIN date,
    BDHORAFIN time,
    BDTEMPO_BRUTO integer,
    BDCODUSU integer)
as
begin
  suspend;
end^

CREATE OR ALTER PROCEDURE VTPO_CONSULTA_TEMPOS (
    PREMPRESAS DM_LISTA,
    PRSISTEMAS DM_LISTA,
    PRUSUARIOS DM_LISTA,
    PRPROCESSOS DM_LISTA,
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRFIELDS VARCHAR(500),
    PRREPORT INTEGER,
    PRORDER INTEGER = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP VARCHAR(120),
    BDCODSIS INTEGER,
    BDORDEMSCI INTEGER,
    BDDESCSIS VARCHAR(60),
    BDCODUSU INTEGER,
    BDNOMCOMPLUSU VARCHAR(60),
    BDCODTELASIS INTEGER,
    BDCAPTIONTELA VARCHAR(170),
    BDQUANTIDADE INTEGER,
    BDTEMPOATIVO TIMESTAMP,
    BDTEMPOINATIVO TIMESTAMP,
    BDPERCENTUAL DOUBLE PRECISION,
    BDTEMPOMEDIO TIMESTAMP,
    BDTIPOREGISTRO INTEGER)
AS
BEGIN
 suspend;
END
^

CREATE OR ALTER PROCEDURE SP_SOCIOPROPRIETARIO (
    PRCODEMP VARCHAR(25000),
    PRANOMES INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNROPROPSOC INTEGER,
    BDNROPROPEMP INTEGER)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_COPIA_CONFIG_IDIOMAS (
    PRIDIOMA INTEGER,
    PRCODPLANO_DE INTEGER,
    PRCODPLANO_PARA INTEGER,
    PRPLANO INTEGER,
    PROPCAOTROCA INTEGER)
AS
BEGIN
END
^

CREATE OR ALTER PROCEDURE SP_TIPODESCIDIOMAS (
    PRABRIRPLANOS VARCHAR(5))
RETURNS (
    BDCODTIPODESCIDIOMA INTEGER,
    BDCLASSIFICACAO VARCHAR(100),
    BDCONFIGURA DM_BOOLEAN,
    BDPERMITEABREVIADO DM_BOOLEAN,
    BDPLANO INTEGER,
    BDNIVEL INTEGER,
    BDNIVEL1 VARCHAR(100),
    BDNIVEL2 VARCHAR(100),
    BDNIVEL3 VARCHAR(100),
    BDCONSTANTE VARCHAR(30),
    BDDESCRICAO VARCHAR(100))
AS
BEGIN
 suspend;
END
^

CREATE OR ALTER PROCEDURE VSUC_LANCAMENTOS_EF_AGRUPADOS(
    PRCODEMP VARCHAR(1024),
    PRTIPOLAN VARCHAR(100),
    PRCONTABILIZACAO INTEGER,
    PRDATA DATE,
    PRTRANSACAO INTEGER,
    PRCODTPCC VARCHAR(8192) = NULL)
RETURNS (
    BDCODEMP INTEGER,
    BDCHAVE INTEGER,
    BDCODPLAPADRAO INTEGER,
    BDCODHIST INTEGER,
    BDLOTE VARCHAR(10),
    BDDATA DATE,
    BDDEBITO INTEGER,
    BDCONCD VARCHAR(5),
    BDCREDITO INTEGER,
    BDCONCC VARCHAR(5),
    BDVALOR NUMERIC(15,2),
    BDDATALAN DATE,
    BDHORALAN TIME,
    BDDATALANALT DATE,
    BDHORALANALT TIME,
    BDCODUSU INTEGER,
    BDCODUSUALTERACAO INTEGER,
    BDCODTPHI INTEGER,
    BDNOMEHIST VARCHAR(100),
    BDCOMPL VARCHAR(200),
    BDDCTO VARCHAR(15),
    BDCODTERCEIROD INTEGER,
    BDCODTERCEIROC INTEGER,
    BDTIPLAN VARCHAR(100),
    BDTRANSFERIDO INTEGER,
    BDGRUPO INTEGER,
    BDTOTLAN INTEGER,
    BDAGRUPADOR INTEGER,
    BDTIPOLAN INTEGER,
    BDCHAVEONLINE VARCHAR(120),
    BDCODTPCC INTEGER,
    BDTRANSACAO INTEGER,
    BDTRANFECHADA VARCHAR(5),
    BDCONCILIACAOPENDENTE INTEGER,
    BDOBSERVACAODEB TYPE OF COLUMN VSUC_EMPRESAS_TOBS.BDOBSERVACAO,
    BDOBSERVACAOCRE TYPE OF COLUMN VSUC_EMPRESAS_TOBS.BDOBSERVACAO)
AS
BEGIN
 suspend;
END
^

CREATE OR ALTER PROCEDURE FK_MANUAL_INSERT (
    TABELA_DEST VARCHAR(64) NOT NULL,
    TABELA_ATUAL VARCHAR(64) NOT NULL,
    OLD1 INTEGER,
    OLD2 INTEGER,
    NEW1 INTEGER,
    NEW2 INTEGER,
    PRUSA2 SMALLINT NOT NULL)
AS
BEGIN
END
^

CREATE OR ALTER PROCEDURE FK_MANUAL_DELETE (
    TABELA VARCHAR(64),
    OLD1 INTEGER,
    OLD2 INTEGER)
AS
BEGIN
END
^

create or alter procedure VSUC_SP_EMP_TLAN_GROUP (
    PRSESSAO integer,
    PRCODIGO integer,
    PREMPRESAS varchar(1024),
    PRSQL varchar(32000),
    PRFOLHA integer,
    PRFISCAL integer,
    PRCHAVEONLINE varchar(120),
    PRDATAFOLHA date,
    PRDEBITO integer,
    PRCREDITO integer,
    PRDATAFISCAL date,
    PRTRANSACAO integer,
    PREXPORTTXT integer = 0)
returns (
    BDCHAVE integer,
    BDCHAVELCC integer,
    BDCODEMP integer,
    BDCODPLAPADRAO integer,
    BDCODHIST integer,
    BDLOTE varchar(10),
    BDDATA date,
    BDDEBITO integer,
    BDCODTERCEIROD integer,
    BDCONCD varchar(5),
    BDCREDITO integer,
    BDCODTERCEIROC integer,
    BDCONCC varchar(5),
    BDCONCILIACAOPENDENTE integer,
    BDVALOR numeric(18,2),
    BDCODTPHI integer,
    BDCOMPL varchar(200),
    BDDCTO varchar(15),
    BDTIPOLAN integer,
    BDDATALAN date,
    BDHORALAN time,
    BDCODUSU integer,
    BDCODUSUALTERACAO integer,
    BDDATALANALT date,
    BDHORALANALT time,
    BDRECLIXEIRA varchar(5),
    BDTIPLAN varchar(100),
    BDTIPOFCONT integer,
    BDFILIAL integer,
    BDTIPOLANCFILIAL integer,
    BDCONTABILIZACAO integer,
    BDTRANSACAO integer,
    BDTRANFECHADA varchar(5),
    BDOBSERVACAODEB varchar(255),
    BDOBSERVACAOCRE varchar(255),
    BDCOMPLEMENTOCOMPLETO blob sub_type 1 segment size 100,
    BDTRANSFERIDO integer,
    BDGRUPO integer,
    BDTOTLAN integer,
    BDAGRUPADOR integer,
    BDCHAVEONLINE varchar(120),
    BDLANCAEXTEMPORANEO varchar(5),
    BDCHECK varchar(5),
    BDDATAEXTEMPORANEO date,
    USULAN varchar(20),
    USUALT varchar(20),
    BDCODEMPREENDIMENTODEB integer,
    BDCODINUSIMOBDEB integer,
    BDCODEMPREENDIMENTOCRE integer,
    BDCODINUSIMOBCRE integer,
    BDLANORIGINAL integer,
    BDDESCLANORIG varchar(100),
    BDCGCTERC varchar(18),
    BDCGCTERD varchar(18))
as
BEGIN
 suspend;
END
^

create or alter procedure VSUC_SP_EMP_TLAN_RH_GROUP_NEW (
    PRCODEMP integer,
    PRCHAVEONLINE varchar(120),
    PRDATA date,
    PRDEBITO integer,
    PRCREDITO integer,
    PRWHERE varchar(8192) = null)
returns (
    BDCODEMP integer,
    BDCHAVE integer,
    BDCODPLAPADRAO integer,
    BDCODHIST integer,
    BDLOTE varchar(10),
    BDDATA date,
    BDDEBITO integer,
    BDCONCD varchar(5),
    BDCREDITO integer,
    BDCONCC varchar(5),
    BDVALOR numeric(15,2),
    BDDATALAN date,
    BDHORALAN time,
    BDDATALANALT date,
    BDHORALANALT time,
    BDCODUSU integer,
    BDCODUSUALTERACAO integer,
    BDCODTPHI integer,
    BDNOMEHIST varchar(100),
    BDCOMPL varchar(200),
    BDDCTO varchar(15),
    BDCODTERCEIROD integer,
    BDCODTERCEIROC integer,
    BDTIPLAN varchar(100),
    BDTRANSFERIDO integer,
    BDGRUPO integer,
    BDTOTLAN integer,
    BDAGRUPADOR integer,
    BDTIPOLAN integer,
    BDCHAVEONLINE varchar(120),
    BDCODTPCC integer,
    BDTRANSACAO integer,
    BDTRANFECHADA varchar(5),
    BDCONCILIACAOPENDENTE integer,
    BDOBSERVACAODEB type of column VSUC_EMPRESAS_TOBS.BDOBSERVACAO,
    BDOBSERVACAOCRE type of column VSUC_EMPRESAS_TOBS.BDOBSERVACAO)
as
BEGIN
 suspend;
END
^

create or alter procedure VSUC_SP_EMP_TLAN_EF_GROUP_NEW (
    PRCODEMP varchar(1024),
    PRTIPOLAN varchar(100),
    PRCONTABILIZACAO integer,
    PRDATA date,
    PRTRANSACAO integer,
    PRCODTPCC varchar(8192) = null,
    PRWHERE varchar(4000) = null)
returns (
    BDCODEMP integer,
    BDCHAVE integer,
    BDCODPLAPADRAO integer,
    BDCODHIST integer,
    BDLOTE varchar(10),
    BDDATA date,
    BDDEBITO integer,
    BDCONCD varchar(5),
    BDCREDITO integer,
    BDCONCC varchar(5),
    BDVALOR numeric(15,2),
    BDDATALAN date,
    BDHORALAN time,
    BDDATALANALT date,
    BDHORALANALT time,
    BDCODUSU integer,
    BDCODUSUALTERACAO integer,
    BDCODTPHI integer,
    BDNOMEHIST varchar(100),
    BDCOMPL varchar(200),
    BDDCTO varchar(15),
    BDCODTERCEIROD integer,
    BDCODTERCEIROC integer,
    BDTIPLAN varchar(100),
    BDTRANSFERIDO integer,
    BDGRUPO integer,
    BDTOTLAN integer,
    BDAGRUPADOR integer,
    BDTIPOLAN integer,
    BDCHAVEONLINE varchar(120),
    BDCODTPCC integer,
    BDTRANSACAO integer,
    BDTRANFECHADA varchar(5),
    BDCONCILIACAOPENDENTE integer,
    BDOBSERVACAODEB type of column VSUC_EMPRESAS_TOBS.BDOBSERVACAO,
    BDOBSERVACAOCRE type of column VSUC_EMPRESAS_TOBS.BDOBSERVACAO)
as
BEGIN
 suspend;
END
^

CREATE OR ALTER PROCEDURE VSUC_SP_CONCILIACAO (
    PRCODEMP VARCHAR(2000),
    PRCODPLAPADRAO INTEGER,
    PRCLASSINI VARCHAR(40), --#alt:15964 - Alterado tamanho do campo de 20 para 40. Ana - 07/10/2016
    PRTERCEIROINI INTEGER,
    PRCLASSFIM VARCHAR(40), --#alt:15964 - Alterado tamanho do campo de 20 para 40. Ana - 07/10/2016
    PRTERCEIROFIM INTEGER,
    PRDEBCRE INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRCOMPARANRDOC DM_BOOLEAN COLLATE WIN_PTBR,
    PRCONSIDERAZERO DM_BOOLEAN COLLATE WIN_PTBR,
    PRCOMPARADATA DM_BOOLEAN COLLATE WIN_PTBR,
    PRVALOREXATO DM_BOOLEAN COLLATE WIN_PTBR,
    PRRECONCILIAR DM_BOOLEAN COLLATE WIN_PTBR,
    PRAGRUPARPARTICIPANTECNPJ DM_BOOLEAN COLLATE WIN_PTBR,
    PRAGRUPARPARTICIPANTECPF DM_BOOLEAN COLLATE WIN_PTBR,
    PRNRODOCCOMPL boolean)
RETURNS (
    BDCODEMP INTEGER,
    BDCHAVE INTEGER,
    BDTIPOLANCFILIAL SMALLINT)
AS
BEGIN
 suspend;
END
^

CREATE OR ALTER PROCEDURE SP_INCLUICLASSECOL_ONLINE (
    PRGRUPOCLA INTEGER)
AS
BEGIN END
^

CREATE OR ALTER PROCEDURE SP_VRH_REORDENA_VERBAS (
    PRCLASSINI VARCHAR(20) = 0,
    PRCLASSFIM VARCHAR(20) = 9.999,
    PRORDEMINICIAL INTEGER = 1,
    PRLISTACLASS1 VARCHAR(100) = NULL,
    PRLISTACLASS2 VARCHAR(5000) = NULL,
    PRLISTACLASS3 VARCHAR(10000) = NULL) 
RETURNS (
    BDORDEMFINAL INTEGER,
    BDCLASS1 VARCHAR(100),
    BDCLASS2 VARCHAR(5000),
    BDCLASS3 VARCHAR(10000)) 
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CRIA_REFERENCIA_EMPRESAS_REF (
    PRAAAAMM INTEGER,
    PRWHERE VARCHAR(32000) = '')
AS
BEGIN END
^

CREATE OR ALTER PROCEDURE SP_CRIA_REFERENCIA_COLCON_REF (
    PRAAAAMM INTEGER,
    PRWHERE VARCHAR(32000) = '')
AS
BEGIN END
^

CREATE OR ALTER PROCEDURE SP_CRIA_REF_ESOCIAL_EMP_REF (
    PRAAAAMM INTEGER,
    PRWHERE VARCHAR(32000) = '')
AS
BEGIN END
^

create or alter procedure SP_CRIA_DATA_COLCON_DIA (
    PRDATA date,
    PRWHERE varchar(32700))
as
begin

end^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_SD_BI0 FOR VRH_EMP_TCOLCON_SD
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;

BEGIN
  IF ((NEW.bdcodsd IS NULL) OR (NEW.bdcodsd = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODSD) + 1, 1) FROM VRH_EMP_TCOLCON_SD WHERE BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol INTO :vcod;
       NEW.bdcodsd = vcod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TTERC_VINC_BI0 FOR VRH_BASE_TTERC_VINC
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (NEW.bdcodcla IS NULL) THEN
     NEW.bdcodcla = 2;
END
^

CREATE OR ALTER TRIGGER PLANOS_TPLA_ECF_BIU0 FOR PLANOS_TPLA_ECF
ACTIVE BEFORE INSERT /*OR UPDATE*/ POSITION 0 --#alt:18406 - Estava gerando erro quando executava o delete na alteração. Ana - 24/04/2017
AS
BEGIN
  --alt:11501 - Criada trigger para deletar os registros que ficariam vazios (sem grupo e conta referencial). Pedro
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTAB_SN_SERVICO_VI_BI FOR VEF_BASE_TTAB_SN_SERVICO_VI
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN END
^

CREATE OR ALTER PROCEDURE SP_VRH_REORDENA_TODAS_VERBAS 
AS
BEGIN
END
^

-- alt:14201 - 07/06/2016 - Trigger de auto incremento da tabela VRH_BASE_TAVISOPREVIO - Bruno L. R.
CREATE OR ALTER TRIGGER vrh_base_tavisoprevio_bi0 FOR vrh_base_tavisoprevio
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vsuc_planos_ctacurr_ecd_bi0 FOR vsuc_planos_ctacurr_ecd
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE wCodigo INTEGER;

BEGIN
  IF ((NEW.BDCODCTACURRECD IS NULL) OR (NEW.BDCODCTACURRECD = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODCTACURRECD) + 1, 1)
       FROM VSUC_PLANOS_CTACURR_ECD
       INTO :wCodigo;

       NEW.BDCODCTACURRECD = :wCodigo;
     END
END
^

CREATE OR ALTER TRIGGER vfin_base_tcadselcli_bi0 FOR vfin_base_tcadselcli
ACTIVE BEFORE INSERT POSITION 0
AS

BEGIN
  
END
^


CREATE OR ALTER TRIGGER vfin_base_tselcli_bi0 FOR vfin_base_tselcli
ACTIVE BEFORE INSERT POSITION 0
AS

BEGIN
  
END
^


CREATE OR ALTER PROCEDURE SP_EXCLUITEMPIMPORTA
RETURNS (
    BDTABELAEXC VARCHAR(255))
AS
DECLARE VARIABLE WSQL VARCHAR(500);
DECLARE VARIABLE WTABELA VARCHAR(255);
BEGIN
  wsql = '  select trim(RDB$RELATION_NAME) as bdTABELA ' ||
  'from ' ||
  '( ' ||
  '  select FLD.*, ' ||
  '  ( ' ||
  '    select count(*) - 1 ' ||
  '    from RDB$RELATION_FIELDS F ' ||
  '    where F.RDB$RELATION_NAME = FLD.RDB$RELATION_NAME ' ||
  '  ) as MAX_POS ' ||
  '  from RDB$RELATION_FIELDS FLD ' ||
  ') as BASE ' ||
  'where BASE.RDB$FIELD_NAME = ''XXSEQ'' and ' ||
  '      BASE.MAX_POS = BASE.RDB$FIELD_POSITION';

  FOR EXECUTE STATEMENT wsql INTO :wTabela DO
  BEGIN
    EXECUTE STATEMENT 'drop table ' || wTabela;
    BDTABELAEXC = wTabela;
    SUSPEND;
  END
END^

CREATE OR ALTER PROCEDURE VSUC_SP_COPIA_PREPARACAO_ECF (
    PRCODPLAPADRAOREF_DE INTEGER,
    PRCODPLAPADRAO_DE INTEGER,
    PRCODPLAPADRAOREF_PARA INTEGER,
    PRCODPLAPADRAO_PARA INTEGER,
    PRANO_DE INTEGER,
    PRANO_PARA INTEGER,
    PROPCAOTROCA INTEGER) 
RETURNS (
    BDCODPLAPADRAOREF INTEGER,
    BDCODTPLAREF INTEGER,
    BDCODPLAPADRAO INTEGER,
    BDCODTPLA INTEGER,
    BDANO INTEGER,
    BDCODGRUPOCTA INTEGER) 
AS
BEGIN
  --alt:11500 - Criada procedure para copiar a preparação da ECF. Pedro
  SUSPEND;
END
^
CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK270 (
    PRSESSAO INTEGER,
    PRULTCHAVE INTEGER,
    PRIDTERMINAL INTEGER)
AS
BEGIN
END^

DROP PROCEDURE SP_ATUALIZAR_TMP_BLOCOK270^

create or alter procedure VRHF_EMP_VAL_GRRF_FC (
    PREMPRESA integer,
    PRCOLABORADOR integer,
    PRANOMES integer,
    PRDATAPGTO date,
    PRCODTIPOFC integer = null,
    PRRELGRRF DM_BOOLEAN = 'FALSE' /* COLLATE WIN1252 - default */ )
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDBFGTSMESANT numeric(15,6),
    BDFGTSMESANT numeric(15,6),
    BDBFGTSMES numeric(15,6),
    BDFGTSMES numeric(15,6),
    BDSALDO numeric(15,6),
    BDFGTS40 numeric(15,6),
    BDFGTS10 numeric(15,6),
    BDTOTAL numeric(15,6),
    BDFGTSIND numeric(15,6),
    BDBFGTSMESSEFIP numeric(15,6),
    BDFGTSMESSEFIP numeric(15,6),
    BDPERCMULTA40 numeric(15,2),
    BDPERCMULTA10 numeric(15,2),
    BDBFGTSIND numeric(18,2),
    BDFGTS13 numeric(9,2),
    BDBASEFGTS13 numeric(9,2))
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE AAAAMM(PRDATA DATE)
 RETURNS(BDAAAAMM VARCHAR(6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE COMPARATEXTO(STR1 VARCHAR(1024),
STR2 VARCHAR(1024))
 RETURNS(RESULT VARCHAR(1024))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_SIMULACAO_SEGDESEMPREGO (
    PRCODEMP INTEGER,
    PRCODCOL INTEGER)
returns (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDQTDMESES INTEGER,
    BDMAIORREMUN NUMERIC(18,6))
AS
BEGIN
  SUSPEND;
END
^

CREATE OR ALTER PROCEDURE SP_VRHF_SEGDESEMPREGO3MESES (
    PRCODEMP INTEGER,
    PRCODCOL INTEGER,
    PRREF INTEGER = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREFFN INTEGER,
    BDMAIORREMUNERACAO NUMERIC(18,6),
    BDORIGEM SMALLINT) 
AS
BEGIN
  SUSPEND;
END
^

CREATE OR ALTER PROCEDURE DIA_SEGUINTE(PRDATA DATE)
 RETURNS(PRDIASEGUINTE DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE DIFERENCA_MESES(PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDMESES INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE EMPAUTSERV(PREMPRESA INTEGER,
PRAUTONOMO INTEGER,
PRSERVICO INTEGER)
 RETURNS(BDEMPAUTSERV VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VCT_ORCAMENTO_RELATORIO (
    PRCODEMP varchar(5000),
    PRREFINI integer)
returns (
    BDCODEMP integer,
    BDREFEMP integer)
as begin suspend; end^

CREATE OR ALTER PROCEDURE VCT_TAREFA_SEFIPSEMMOVIMENTO (
    PRCODEMP integer,
    PRDATA date)
RETURNS (
    BDRESULT varchar(5))
AS
BEGIN SUSPEND; END
^

create or alter procedure GET_VENCIMENTO_TAREFAS (
    PRDATA date,
    PRDIA integer,
    PRANTECIPA varchar(5),
    PRVENCE integer,
    PRAPURACAO integer,
    PRALERTA integer,
    PRENTREGA integer,
    PRMES integer = 0,
    PRCODEMP integer = 0)
returns (
    BDDATA date,
    BDALERTA date,
    BDENTREGA date)
as begin suspend; end^

create or alter procedure SP_REFERENCIA_TO_DATA (
    PRREFERENCIA integer,
    PRULTIMO_DIA boolean = false)
returns (BDDATA date)
as begin suspend; end^

CREATE OR ALTER PROCEDURE VCT_PROCESSOS_AUTOMATICOS(codemp INTEGER=0)RETURNS(total INTEGER)AS BEGIN SUSPEND;END^
CREATE OR ALTER trigger tgrupousuario_usuario_au0 for tgrupousuario_usuario active after insert or update or delete position 0 AS begin end^
CREATE OR ALTER trigger vct_empresa_usuario_imp_aiud0 for vct_empresa_usuario_imp active after insert or update or delete position 0 AS begin end^
CREATE OR ALTER trigger vct_empresa_usuario_obr_aiud0 for vct_empresa_usuario_obr active after insert or update or delete position 0 AS begin end^
CREATE OR ALTER trigger vct_empresa_usuario_ser_aiud0 for vct_empresa_usuario_ser active after insert or update or delete position 0 AS begin end^
CREATE OR ALTER procedure VCT_TAREFAS_EXEC_THREAD as begin end^
CREATE OR ALTER PROCEDURE VCT_TAREFAS_AUTOMATICAS_INSERT(codemp INTEGER=0)RETURNS(total INTEGER)AS BEGIN SUSPEND;END^
CREATE OR ALTER PROCEDURE VCT_TAREFAS_AUTOMATICAS_OBR(codemp INTEGER=0)RETURNS(total INTEGER)AS BEGIN SUSPEND;END^
CREATE OR ALTER PROCEDURE VCT_TAREFAS_AUTOMATICAS_SER(codemp INTEGER=0)RETURNS(total INTEGER)AS BEGIN SUSPEND;END^
CREATE OR ALTER PROCEDURE VCT_TAREFAS_AUTOMATICAS_IMP(codemp INTEGER=0)RETURNS(total INTEGER)AS BEGIN SUSPEND;END^
CREATE OR ALTER PROCEDURE VCT_TAREFAS_AUTOMATICAS(codemp INTEGER=0)RETURNS(total INTEGER)AS BEGIN SUSPEND;END^

create or alter procedure VCT_ORCADO_REALIZADO (
    PRDATAINICIAL date,
    PRDATAFINAL date,
    PRTIPOCALCULO integer,
    PRCODEMP integer = null,
    PRREF integer = null,
    PRORCAMENTO boolean = true)
returns (
    BDCODEMP integer,
    BDNOMEMP varchar(100),
    BDREFEMP integer,
    BDFORMATRIBUTA_REAL varchar(15),
    BDCODENQFED_ORC varchar(15),
    BDCODENQFED_REAL varchar(15),
    BDFORMATRIBUTA_ORC varchar(15),
    BDREFCALC integer,
    BDCODSIS integer,
    BDNOMSIS varchar(100),
    BDDATA date,
    BD_ORC integer,
    BD_REAL integer,
    BDMAX integer,
    BDREFORC integer,
    BDDESCORC varchar(200))
as
BEGIN
  suspend;
end^

create or alter procedure VCT_ORC_SETREFGERADOR (
    PRDATAINI date,
    PRDATAFIN date)
as
begin
end^

create or alter procedure VCT_TAREFAS_AUTORIZADAS (
    PRDATA date)
returns (
    BDAUTORIZADA boolean)
as begin suspend; end^

create or alter procedure VCT_TAREFAS_PROTOCOLADA (
    PRCODEMP integer,
    PRCODPTS integer,
    PRPORTADOR varchar(300),
    PRDATAEMISSAO date,
    PRHORAEMISSAO time,
    PRCLASSNAME varchar(256))
as begin  end^

create or alter procedure VCT_EMPRESA_BAIXATAREFA (PRCODEMP integer,PRCODST integer,PRAGUARDANDO integer,PRCODUSU integer,PRMENSAGEM varchar(500),PRCODBHS integer)as begin end^

CREATE OR ALTER TRIGGER VEF_REINF_EVT_AI1 FOR VEF_REINF_EVT ACTIVE AFTER INSERT POSITION 1 AS begin end^

CREATE OR ALTER PROCEDURE VCT_EMPRESA_THISTORICO_STATUS (
    codemp INTEGER = 0)
AS
BEGIN END
^

CREATE OR ALTER PROCEDURE MAXSCI(PRCAMPO VARCHAR(1024),
PRORDEM VARCHAR(1024),
PRCONDICAO VARCHAR(1024),
PRTABELA VARCHAR(1024))
 RETURNS(BDRESULT INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE PREENCHE_CLASSIFICACAOPRODUTO(PRSTRING VARCHAR(1000),
PRQTD INTEGER,
PRADICIONA VARCHAR(1000))
 RETURNS(BDRETORNO VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE RPOS(SUBSTR VARCHAR(100),
STR VARCHAR(100))
 RETURNS(BDRPOS INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SONUMEROS(PRTEXTO VARCHAR(100))
 RETURNS(BDRESULT SMALLINT)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_PRIMEIRO_NUMERO(PRTEXTO varchar(255))
 RETURNS(WNUMERODCTO VARCHAR(50))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SOLETRAS(PRTEXTO VARCHAR(100))
 RETURNS(BDRESULT SMALLINT)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_ALTERA_TIPO_COLCON(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRCONTRCOL INTEGER,
PRCODCLA INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_ATU_CAMPOS_GERADOR AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_ATU_CODREC(PRCODREC DM_CODRECOF)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_ATU_LANCAMENTOS_CONTABIL (
    PRCODPLANO INTEGER,
    PRCHAVE INTEGER,
    PRTIPOLAN INTEGER,
    PRDEBITO INTEGER,
    PRCREDITO INTEGER,
    PRHISTORICO INTEGER,
    PROLDDEBITO INTEGER,
    PROLDCREDITO INTEGER,
    PROLDHISTORICO INTEGER,
    PRCODPLANOPADRAO INTEGER,
    PRCODPLANOHIST INTEGER,
    PRREFERENCIA INTEGER = 0,
    PRNOVACHAVE INTEGER = 0,
    PRCOMPL INTEGER = NULL,
    PROLDCOMPL INTEGER = NULL)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_REMOVER_VAR_COMPLEMENTO (
    PRCOMPLEMENTO VARCHAR(200),
    PRREPLACE VARCHAR(10))
RETURNS (
    BDRESULT VARCHAR(200))
AS
begin
  suspend;
end
^

CREATE OR ALTER PROCEDURE SP_CALC_DEPRECIACAO(PRCODEMP INTEGER,
PRCODBEM INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRTIPO INTEGER,
PRCONTABILIZACAO INTEGER)
 RETURNS(PRVALORCORRIGIDOANTERIOR NUMERIC(15,2),
PRCORRECAOPERIODO NUMERIC(15,2),
PRVALORCORRIGIDOATUAL NUMERIC(15,2),
PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2),
PRDEPRECIACAOPERIODO NUMERIC(15,2),
PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6),
PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2),
PRVALORRESIDUALCONTABIL NUMERIC(15,2),
PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
PRTOTALMESESDEPRECIACAO INTEGER,
PRMESESDEPRECIADOS INTEGER,
PRMESESDEPRECIAR INTEGER,
PRTAXADEPRECIACAOANUAL NUMERIC(6,6),
PRDATATAXADEPRECIACAO DATE,
PRVALORBAIXA NUMERIC(15,2),
PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,2),
PRVALORBAIXAREAL NUMERIC(15,2),
PRVALORMOEDA NUMERIC(15,6),
PRDATABAIXA DATE,
PRVALORAQUISICAOMOEDA NUMERIC(15,6),
PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
PRVALORAQUISICAOORIGINAL NUMERIC(15,2),
PRCTADEBITODEPRE INTEGER,
PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CONS_CALC_DEP (
    PRCODEMP INTEGER,
    PRCODBEM INTEGER,
    PRDATAINICIAL DATE,
    PRDATAFINAL DATE,
    PRTIPO INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRDETALHARTAXADEP INTEGER = 0,
    prRelBaiPar INTEGER = 0)
RETURNS (
    PRVALORCORRIGIDOANTERIOR NUMERIC(15,2),
    PRCORRECAOPERIODO NUMERIC(15,2),
    PRVALORCORRIGIDOATUAL NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2),
    PRDEPRECIACAOPERIODO NUMERIC(15,2),
    PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,2),
    PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2),
    PRVALORRESIDUALCONTABIL NUMERIC(15,2),
    PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,2),
    PRTOTALMESESDEPRECIACAO INTEGER,
    PRMESESDEPRECIADOS INTEGER,
    PRMESESDEPRECIAR INTEGER,
    PRTAXADEPRECIACAOANUAL NUMERIC(6,2),
    PRDATATAXADEPRECIACAO DATE,
    PRVALORBAIXA NUMERIC(15,2),
    PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,2),
    PRVALORBAIXAREAL NUMERIC(15,2),
    PRVALORMOEDA NUMERIC(15,2),
    PRDATABAIXA DATE,
    PRVALORAQUISICAOMOEDA NUMERIC(15,2),
    PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,2),
    PRVALORAQUISICAOORIGINAL NUMERIC(15,2),
    PRCTADEBITODEPRE INTEGER,
    PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,2),
    BDCODEMP INTEGER,
    BDCODBEM INTEGER,
    PRSOMARDEPRECIACAO INTEGER,
    PRCOMPENSACAOBAIXAPERANTERIOR NUMERIC(15,2),
    BDVALORRESIDUAL NUMERIC(15,2),
    PRTAXADEPRECIACAOANUAL_ANT NUMERIC(6,2),
    PRDATAINICALC DATE,
    BDVALORCAPITAL NUMERIC(15,2))
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CONS_CALC_DEP_CORRECAO (
    PRCODEMP INTEGER,
    PRCODBEM INTEGER,
    PRDATAINICIAL DATE,
    PRDATAFINAL DATE,
    PRTIPO INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRVLRMOEDA NUMERIC(15,2),
    PRPOSSUIBAIXA VARCHAR(5),
    PRCODBEMORIGINAL INTEGER,
    PRVALORAQUISICAO NUMERIC(15,2),
    PRTAXADEPANUAL NUMERIC(6,2),
    PRDATAAQUISICAO DATE,
    PRDATAORIGAQUISICAO DATE,
    PRDEPDIA VARCHAR(5),
    PRDEPMENSAL VARCHAR(5),
    PRDEPMESBAIXA VARCHAR(5),
    PRDATAINICIOCALC DATE,
    PRDATAFIMCALC DATE,
    PRDATAULTIMOITEMDEP DATE,
    PRVALDEPACUMUBEM NUMERIC(15,2),
    PRCTADEBDEPRE INTEGER,
    PRNUMDIAS INTEGER,
    PRDEPDIADATA INTEGER,
    PRVALORBAIXABEM NUMERIC(15,2),
    PRMESESDEPRECIADOSOUTRATAXA INTEGER,
    PRVALORACUMULADOANTERIOR NUMERIC(15,2),
    PRVALORRESIDUAL NUMERIC(15,2) = 0,
    PRDEPDIABAIXA VARCHAR(5) = 'FALSE',
    PRTAXAANT NUMERIC(15,2) = 0,
    PRCONT INTEGER = 0,
    PRMESDEPRECIACAONOVATAXA INTEGER = 0,
    prRelBaiPar INTEGER = 0)
RETURNS (
    PRVALORCORRIGIDOANTERIOR NUMERIC(15,2),
    PRCORRECAOPERIODO NUMERIC(15,2),
    PRVALORCORRIGIDOATUAL NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2),
    PRDEPRECIACAOPERIODO NUMERIC(15,2),
    PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,2),
    PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2),
    PRVALORRESIDUALCONTABIL NUMERIC(15,2),
    PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,2),
    PRTOTALMESESDEPRECIACAO INTEGER,
    PRMESESDEPRECIADOS INTEGER,
    PRMESESDEPRECIAR INTEGER,
    PRTAXADEPRECIACAOANUAL NUMERIC(6,2),
    PRDATATAXADEPRECIACAO DATE,
    PRVALORBAIXA NUMERIC(15,2),
    PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,2),
    PRVALORBAIXAREAL NUMERIC(15,2),
    PRVALORMOEDA NUMERIC(15,2),
    PRDATABAIXA DATE,
    PRVALORAQUISICAOMOEDA NUMERIC(15,2),
    PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,2),
    PRVALORAQUISICAOORIGINAL NUMERIC(15,2),
    PRCTADEBITODEPRE INTEGER,
    PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,2),
    PRCOMPENSACAOBAIXAPERANTERIOR NUMERIC(15,2),
    BDVALORCAPITAL NUMERIC(15,2),
    PRMESNOVATAXA INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_LISTAPERAQUISFE (
    PREMP varchar(15000),
    PRCOL varchar(32700))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDCODEMPORIG integer,
    BDCODCOLORIG integer)
as
declare variable WSQL varchar(32700);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WEMPORIG integer;
declare variable WCOLORIG integer;
declare variable WACHOUPER integer;
begin
  suspend;
end^

CREATE OR ALTER PROCEDURE SP_CONS_FERIAS_PER_AQUIS_ESCALA(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER,
PRPRIDIA DATE,
PRULTDIA DATE,
PRAGENDAFERIAS INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDINIPERAQUISFE DATE,
BDCODFE INTEGER,
BDINIPERGOZOFE DATE,
BDFIMPERAQUISFE DATE,
BDFIMPERGOZOFE DATE,
BDDATAPAGFE DATE,
BDQTDABONOFE NUMERIC(18,6),
BDQTDGOZOFE NUMERIC(18,6),
BDSALDOINIFE NUMERIC(15,6),
BDSALDOFIMFE NUMERIC(15,6),
BDBASEIRFE NUMERIC(15,6),
BDALIQIRFE NUMERIC(15,6),
BDVALORIRFE NUMERIC(15,6),
BDBASEINSSFE NUMERIC(15,6),
BDALIQINSSFE NUMERIC(15,6),
BDVALORINSSFE NUMERIC(15,6),
BDDEPFE NUMERIC(15,6),
BDSALBASEFE NUMERIC(15,6),
BDSALBASEHEFE NUMERIC(15,6),
BDDATABAIXAFE DATE,
BDCOLETIVASFE VARCHAR(5),
BDREFPAGABOFE INTEGER,
BDFALTASFE NUMERIC(15,6),
BDNOMEMP VARCHAR(100),
BDNOMCOL VARCHAR(70),
BDSALDOFINALSINDFE NUMERIC(18,6),
BDFERIADOSFE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CONSULTA_COL_POR_REF(PREMP INTEGER,
PRCOL INTEGER,
PRREFMICRO INTEGER)
 RETURNS(BDREFCOL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CONSULTA_EMP_POR_REF(PREMP INTEGER,
PRREFMICRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_CONSULTA_PLANO_CONTAS (
    PRCODPLADARAO integer,
    PRTODASCONTAS integer,
    PRCONSOLIDADA varchar(8000),
    PRFILTRO varchar(1024),
    PREMPRESA integer = 0)
returns (
    BDCODPLAPADRAO integer,
    BDCODTPLA integer,
    BDCTALON varchar(40),
    BDTIPCTA smallint,
    BDNOMCTA varchar(100),
    BDAPECTA varchar(20),
    BDGRUPOCTA integer,
    BDRELCTA integer,
    BDFILTROGER varchar(20),
    BDFORMULA varchar(200),
    BDCONDICAO varchar(100),
    BDPARTICIPANTE integer,
    BDPERTENCECONTA integer,
    BDCLANOM varchar(140),
    BDCODSUBCONTA integer,
    BDGRUPOSUBCONTA varchar(10),
    BDCODNATSUBCONTA integer,
    BDCTAEMPREENDIMENTOSIMOB DM_BOOLEAN,
    BDCTAUNIDADEIMOB DM_BOOLEAN,
    BDCTACAIXAPR DM_BOOLEAN,
    BDCTABANCOPR DM_BOOLEAN,
    BDCTATRANSPR DM_BOOLEAN,
    BDCARNELEAO DM_BOOLEAN)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CONSULTA_TERCEIRO(PRCODTER INTEGER,
PRREF INTEGER,
PRWHERETER VARCHAR(20000))
 RETURNS(BDCODTER INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCGCTER VARCHAR(18),
BDREFEMP INTEGER,
BDAPELIDOTER VARCHAR(20),
BDNOMETER VARCHAR(100),
BDLOGRTER VARCHAR(15),
BDENDTER DM_BDENDERECO,
BDNUMTER DM_NUMEND,
BDCOMPTER DM_BDCOMPENDERECO,
BDCEPTER VARCHAR(9),
BDBAITER VARCHAR(60),
BDDDDTER VARCHAR(3),
BDFONETER DM_BDTELEFONE,
BDFAXTER DM_BDTELEFONE,
BDEMAILTER DM_BDEMAIL,
BDIETER VARCHAR(20),
BDDATACADTER DATE,
BDIMTER VARCHAR(16),
BDPRURALTER VARCHAR(5),
BDENQSIMPLESFEDTER INTEGER,
BDINSCSUFRAMATER VARCHAR(10),
BDCODGPS INTEGER,
BDCODCID INTEGER,
BDCODPAIS INTEGER,
BDDESCPAIS VARCHAR(60),
BDDDDFAXTER VARCHAR(3),
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2),
BDNOMCID VARCHAR(40),
BDORGAOPUBLICO VARCHAR(5),
BDCODTIPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CONSULTA_TERCEIRO_MATRIZ (
    PRCODTER INTEGER,
    PRCGCTER TYPE OF COLUMN TTERCEIRO.BDCGCTER)
RETURNS (
    BDCODTER INTEGER,
    BDCGCTER TYPE OF COLUMN TTERCEIRO.BDCGCTER)
AS
BEGIN
 suspend;
END
^

CREATE OR ALTER PROCEDURE SP_CONSULTAEMPRESAS (
    PRREFMICRO integer,
    PRCODEMP varchar(10240),
    PRINATIVAS smallint,
    PREXCLUIREMP integer = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDCODMATRIZ INTEGER,
    BDCNPJEMP VARCHAR(18),
    BDDATAINIATIVEMP DATE,
    BDORGAOEMP VARCHAR(8),
    BDDATAREGEMP DATE,
    BDDATACONSTEMP DATE,
    BDDESCCARTEMP VARCHAR(40),
    BDDATAFIMATIVEMP DATE,
    BDCODPLAPADRAO INTEGER,
    BDCODHIST INTEGER,
    BDCODCENTROS INTEGER,
    BDCODCID INTEGER,
    BDCODCONT INTEGER,
    BDCODNATJUR INTEGER,
    BDCODCNAE INTEGER,
    BDNOMEMP DM_BDNOMEMP collate WIN_PTBR,
    BDNOMREDUZEMP DM_BDNOMREDUZEMP,
    BDAPEEMP DM_BDAPEMP,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP VARCHAR(9),
    BDDDDEMP INTEGER,
    BDFONEEMP DM_BDTELEFONE,
    BDFAXEMP DM_BDTELEFONE,
    BDEMAILEMP DM_BDEMAIL,
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDLOGREMP VARCHAR(15),
    BDIEEMP VARCHAR(20),
    BDIMEMP VARCHAR(20),
    BDSITEMP VARCHAR(5),
    BDDDDFAXEMP INTEGER,
    BDNOMCID VARCHAR(40),
    BDCODUF INTEGER,
    BDNOMECONT VARCHAR(40),
    BDSIGLAUF VARCHAR(2),
    BDANTECIPICMS INTEGER,
 BDANTECIPICMSCT integer, 
    BDDESCUF VARCHAR(40),
    BDCODPLANOONLINE INTEGER,
    BDCODENQFED INTEGER,
    BDPERSONALIZACAO VARCHAR(120),
    BDCODCONTEF INTEGER,
    BDLIVRO VARCHAR(15),
    BDFOLHA VARCHAR(15),
    BDNOMECARTORIO VARCHAR(100),
    BDDATACADEMP DATE,
    BDTIPOAPURACAORET INTEGER,
    BDCODPLATRIB INTEGER,
    BDTRANMANUAL VARCHAR(5),
    BDTIPOAPURACAORETIR INTEGER,
    BDCODESC INTEGER,
    BDCODPLAPADRAOREF INTEGER,
    BDCODIBGE INTEGER,
    BDFORMATRIBUTACAO INTEGER,
    BDSTATUS_ES INTEGER,
    BDABRIRRATEIO DM_BOOLEAN,
    BDNAOPERMITERATEIOGRUPO DM_BOOLEAN,
    BDINTEGRANET DM_BOOLEAN,
    BDIGNORAREDISS DM_BOOLEAN,
    BDDATAINIESOCIAL DATE,
    BDOPCAOESOCIAL INTEGER,
    BDDDDCELULAREMP INTEGER,
    BDCELULAREMP DM_BDTELEFONE,
    BDCODCLI INTEGER,
    BDDATAOBRIGREINF DATE,
    BDNRTCE VARCHAR(20),
    BDSTATUSEMP integer,
    BDQTDBACKUPEMP integer,
    BDINCORPORADORAS DM_BOOLEAN,
    BDSCIREPORT DM_BOOLEAN,
    BDTIPOCAEPF INTEGER,
    BDCODTIPOCLI INTEGER,
    BDCODZONA integer,
    BDNOMEZONA varchar(40),
    BDCARNELEAO DM_BOOLEAN,
    BDCEIEMP DM_CNPJ_CPF,
    BDGRUPO integer,
    BDENVIOS2210 integer,
    BDENVIOS2220 integer,
    BDENVIOS2240 integer,
    BDDATAINICIALTR date,
    BDTIPOAPURACAORETIRTOM integer,
    BDIMENDES varchar(5),
    BDCARACTRIBUTARIA integer,
    BDFORMATRIBUTACAOVW integer,
    BDESTABFORABASE DM_BOOLEAN,
    BDDESCCNAE varchar(200),
    BDIAT_PISCOF_SEM_ICMS DM_BOOLEAN,
    BDEXIBEINFOCOLLAN varchar(5),
    BDSENHAIAT varchar(30),
 BDSENHAARQEMP integer,
    BDSENHAARQEMPSEP varchar(1),
    BDDOCAUXILIAR varchar(19),
    BDDATAINIPARALISADESIF date,
    BDDATAFIMPARALISADESIF date,
    BDTIPODEPENDENCIADESIF varchar(200) collate WIN_PTBR,
    BDCONTABPROPRIADESIF boolean,
    BDCODDEPENDENCIADESIF varchar(20) collate WIN_PTBR,
    BDCNPJDEPUNIFICADORADESIF integer,
    BDESOCIALRT varchar(5),
    BDCONTAAZUL DM_BOOLEAN,
    BDCONTABILIZASCP boolean)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CONSULTAEMPRESAS_SEARCH(PRREFMICRO INTEGER,
PRCODEMP INTEGER,
PRINATIVAS SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDAPEEMP VARCHAR(20),
BDIEEMP VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_ECREDAC (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260),
    PRFINALIDADE INTEGER,
    PRIEINTIMA VARCHAR(12))
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOB (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRVALIDAREXPORTACAO DM_BOOLEAN,
    PRARQUIVO VARCHAR(260))
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOC1250 (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260))
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOC (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRCODPLAPADRAOREF INTEGER,
    PRVALIDAREXPORTACAO DM_BOOLEAN,
    PRARQUIVO VARCHAR(260),
    PRSESSAOSEGREG INTEGER)
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOD (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRCODPLAPADRAOREF INTEGER,
    PRVALIDAREXPORTACAO DM_BOOLEAN,
    PRARQUIVO VARCHAR(260))
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOE (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260),
    PRPERIODOAPUR INTEGER)
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOK (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRVALIDAREXPORTACAO DM_BOOLEAN,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
END
^

--Larissa - 18/03/2021 - Sped Fiscal - Notas de serviços #143666
CREATE OR ALTER procedure SP_VALIDA_EXP_SER (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(100))
AS
BEGIN

END ^ 

CREATE OR ALTER PROCEDURE SP_VALIDA_EXPORTACAO_SPED (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(100))
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_GET_FCP (
    PRTIPOFCP INTEGER,
    PRVLRFCP NUMERIC(15,2),
    PRCSTICMS VARCHAR(3),
    PRCODNAT INTEGER)
RETURNS (
    BDRETORNO NUMERIC(15,2))
AS
BEGIN
  SUSPEND;
END^

create or alter procedure SP_ATUALIZAR_TMP_MOVCCREDZ (
    PRSESSAO integer,
    PRREF integer)
as
declare variable WNAOPERMITERATEIOGRUPO boolean;
declare variable WCODEMP integer;
begin
end^

CREATE OR ALTER PROCEDURE sp_atualizar_tmp_redzvarcfop (
    prsessao INTEGER,
    prcodplanoonline INTEGER,
    prsessaomaqmrc INTEGER,
    PRREF integer)
AS
DECLARE VARIABLE wcodnat INTEGER;
DECLARE VARIABLE wcondpgto INTEGER;
DECLARE VARIABLE wcompldefault VARCHAR(100);
DECLARE VARIABLE wcomplementohist BLOB SUB_TYPE 1 SEGMENT SIZE 1000;
DECLARE VARIABLE wespecie VARCHAR(5);
DECLARE VARIABLE wserie VARCHAR(5);
DECLARE VARIABLE wcodemp INTEGER;
DECLARE VARIABLE wchave INTEGER;
DECLARE VARIABLE wordemvarcfop INTEGER;
DECLARE VARIABLE wnrmaq INTEGER;
DECLARE VARIABLE wrefredz INTEGER;
DECLARE VARIABLE wdataini DATE;
DECLARE VARIABLE wdatafin DATE;
BEGIN

END^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_TMOVREDZ (
    PRSESSAO integer,
    PRSESSAOMAQMRC integer,
    PRSESSAOPRO integer,
    PRULTCHAVE integer,
    PRREF integer,
    PRGERALOG varchar(5))
as
BEGIN

END^

CREATE OR ALTER procedure SP_IMPORTA_RMD (
    PRSESSAO integer)
as
declare variable WCODEMPATU integer;
declare variable WCODEMP integer;
declare variable WEDITCHAVE integer;
declare variable WCODIGO integer;
begin

END^

create or alter procedure SP_ATUALIZA_TMP_TTERCEIRO_TEMP (
    PRSESSAO integer,
    PRATUALIZARDADOS DM_BOOLEAN,
    PRGERARINCONSISTENCIAS DM_BOOLEAN,
    PRREF integer,
    PRCODEMP integer,
    PRPUSH DM_BOOLEAN,
    PRTIPOVINCULO integer)
as
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_CADMAQMRC (
    PRSESSAO INTEGER,
    PRID_TERMINAL INTEGER,
    PRREF INTEGER,
    PRULTCHAVE INTEGER)
AS
begin

end^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_TOBSERVACAO (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER,
    PRLANCAMENTOMANUAL DM_BOOLEAN)
AS
begin

end^


CREATE OR ALTER PROCEDURE SP_INSERT_OR_UPDATE_TCADINFCOM (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS
begin

end^

create or alter procedure SP_UPD_CAM_INTEGRACAO_ARQ_INCO (
    PRCODEMP integer,
    PRCAMINHO varchar(2000),
    PRNOVOCAMINHO varchar(2000))
as
begin

end^

CREATE OR ALTER PROCEDURE SP_INSERT_OR_UPDATE_TOBSERVACAO (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS begin end^

CREATE OR ALTER VIEW VWRH_UNION_FCI_FCIT_CALC(
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDDTCOMP,
    BDCODVER,
    BDREFVFN_SUM,
    BDREFAUXVFN_SUM,
    BDREFVFN_MAX,
    BDREFAUXVFN_MAX,
    BDVALVFN,
    BDIGNREFVFN,
    BDIGNVALVFN)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDREFFC,
  BDCODVER,
  SUM(BDREFVFC),
  SUM(BDREFAUXVFC),
  MAX(BDREFVFC),
  MAX(BDREFAUXVFC),
  SUM(BDVALVFC),
  MAX(BDIGNREFVFC),
  MAX(BDIGNVALVFC)
FROM
  VRHF_EMP_TVERBAFCINT
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDREFFC,
  BDCODVER

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFTOMADOR,
  BDREFFC,
  BDCODVER,
  SUM(BDREFVFC),
  SUM(BDREFAUXVFC),
  MAX(BDREFVFC),
  MAX(BDREFAUXVFC),
  SUM(BDVALVFC),
  MAX(BDIGNREFVFC),
  MAX(BDIGNVALVFC)
FROM
  VRHF_EMP_TVERBAFCTOMINT
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFTOMADOR,
  BDREFFC,
  BDCODVER
^

CREATE OR ALTER VIEW VWRH_UNION_FCI_FCIT_MES_BASES(
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDREFFC,
    BDREFCOMP,
    BDCODCENTRO,
    BDCODTPCC,
    BDDATABAIXA,
    BDBFGTS,
    BDFGTS,
    BDFGTSCS,
    BDBFGTS13,
    BDFGTS13,
    BDFGTS13CS,
    BDMAIORREM,
    BDBINSS,
    BDALIQINSS,
    BDINSS,
    BDBIRRF,
    BDALIQIRRF,
    BDIRRF,
    BDBINSS13,
    BDALIQINSS13,
    BDINSS13,
    BDBIRRF13,
    BDALIQIRRF13,
    BDIRRF13,
    BDBSALFAM,
    BDSALFAM,
    BDBRAIS,
    BDSALBASE,
    BDDEP,
    BDBINSSFEFOL,
    BDINSSFEFOL,
    BDALIQINSSFEFOL,
    BDCREDITO,
    BDDEBITO,
    BDBFGTSFEFOL,
    BDFGTSFEFOL,
    BDLIQUIDO,
    BDCODEMPREENDIMENTO,
    BDDATAPAGFC)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDREFFC,
  BDREFCOMP,
  CAST(NULL AS INTEGER),
  CAST(NULL AS INTEGER),
  MAX(BDDATABAIXAFC),
  SUM(BDBFGTSFC),
  SUM(BDFGTSFC),
  SUM(BDFGTSCSFC),
  SUM(BDBFGTS13FC),
  SUM(BDFGTS13FC),
  SUM(BDFGTS13CSFC),
  MAX(BDMAIORREMFC),
  SUM(BDBINSSFC),
  MAX(BDALIQINSSFC),
  SUM(BDINSSFC),
  SUM(BDBIRRFFC),
  MAX(BDALIQIRRFFC),
  SUM(BDIRRFFC),
  SUM(BDBINSS13FC),
  MAX(BDALIQINSS13FC),
  SUM(BDINSS13FC),
  SUM(BDBIRRF13FC),
  MAX(BDALIQIRRF13FC),
  SUM(BDIRRF13FC),
  SUM(BDBSALFAMFC),
  SUM(BDSALFAMFC),
  SUM(BDBRAISFC),
  MAX(BDSALBASEFC),
  MAX(BDDEPFC),
  SUM(BDBINSSFEFOLFC),
  SUM(BDINSSFEFOLFC),
  MAX(BDALIQINSSFEFOLFC),
  SUM(BDCREDITOFC),
  SUM(BDDEBITOFC),
  SUM(BDBFGTSFEFC),
  SUM(BDFGTSFEFC),
  SUM(BDLIQUIDO),
  cast(null as integer),
  bddatapagfc
FROM
  VRHF_EMP_TFOLHACOMPINT
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDREFFC,
  BDREFCOMP,
  bddatapagfc

UNION

SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREFTOMADOR,
  X.BDREFFC,
  X.BDREFCOMP,
  MAX(Y.BDCODCENTRO),
  MAX(Y.BDCODTPCC),
  MAX(X.BDDATABAIXAFC),
  SUM(X.BDBFGTSFC),
  SUM(X.BDFGTSFC),
  SUM(X.BDFGTSCSFC),
  SUM(X.BDBFGTS13FC),
  SUM(X.BDFGTS13FC),
  SUM(X.BDFGTS13CSFC),
  MAX(X.BDMAIORREMFC),
  SUM(X.BDBINSSFC),
  MAX(X.BDALIQINSSFC),
  SUM(X.BDINSSFC),
  SUM(X.BDBIRRFFC),
  MAX(X.BDALIQIRRFFC),
  SUM(X.BDIRRFFC),
  SUM(X.BDBINSS13FC),
  MAX(X.BDALIQINSS13FC),
  SUM(X.BDINSS13FC),
  SUM(X.BDBIRRF13FC),
  MAX(X.BDALIQIRRF13FC),
  SUM(X.BDIRRF13FC),
  SUM(X.BDBSALFAMFC),
  SUM(X.BDSALFAMFC),
  SUM(X.BDBRAISFC),
  MAX(X.BDSALBASEFC),
  MAX(X.BDDEPFC),
  SUM(X.BDBINSSFEFOLFC),
  SUM(X.BDINSSFEFOLFC),
  MAX(X.BDALIQINSSFEFOLFC),
  SUM(X.BDCREDITOFC),
  SUM(X.BDDEBITOFC),
  SUM(X.BDBFGTSFEFC),
  SUM(X.BDFGTSFEFC),
  SUM(X.BDLIQUIDO),
  MAX(Z.BDCODEMPREENDIMENTO),
  x.bddatapagfc
FROM
  VRHF_EMP_TFOLTOMCOMPINT X
JOIN
  VRHF_EMP_TPREPFN Y on (Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDORDEM = X.BDORDEM)
LEFT OUTER JOIN
  VEF_EMP_TCADEMPREENDIMENTO Z on (Z.BDCODEMP = X.BDCODEMP and Z.BDCODCENTRO = Y.BDCODCENTRO and Z.BDCODTPCC = Y.BDCODTPCC)
GROUP BY
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREFTOMADOR,
  X.BDREFFC,
  X.BDREFCOMP,
  x.bddatapagfc
^

CREATE OR ALTER VIEW VW_TABELAS_FB(
    BDRELATION_NAME,
    BDRELATION_DESCRIPTION,
    BDDESCRICAOTABELA,
    BDDESCRICAOTELA,
    BDEXEMPLOSQL,
    BDSELECT,
    BDINSERT,
    BDUPDATE,
    BDDELETE,
    BDSP)
AS
select BDRELATION_NAME, BDRELATIONDESCRIPTION, BDDESCRICAO, BDDESCRICAOTELA, BDEXEMPLOSQL,
       case
         when exists(select first 1 RDB$PRIVILEGE
                     from RDB$USER_PRIVILEGES
                     where ((RDB$USER_PRIVILEGES.RDB$PRIVILEGE = 'A') or (RDB$USER_PRIVILEGES.RDB$PRIVILEGE = 'S') or (RDB$USER_PRIVILEGES.RDB$PRIVILEGE = 'X')) and
                           RDB$USER_PRIVILEGES.RDB$RELATION_NAME = RELS.BDRELATION_NAME and
                           RDB$USER_PRIVILEGES.RDB$USER = 'INTEGRACOES') then 'TRUE'
         else 'FALSE'
       end BDSELECT,
       case
         when exists(select first 1 RDB$PRIVILEGE
                     from RDB$USER_PRIVILEGES
                     where RDB$USER_PRIVILEGES.RDB$PRIVILEGE = 'A' and
                           RDB$USER_PRIVILEGES.RDB$RELATION_NAME = RELS.BDRELATION_NAME and
                           RDB$USER_PRIVILEGES.RDB$USER = 'INTEGRACOES') then 'TRUE'
         when exists(select first 1 RDB$PRIVILEGE
                     from RDB$USER_PRIVILEGES
                     where RDB$USER_PRIVILEGES.RDB$PRIVILEGE = 'I' and
                           RDB$USER_PRIVILEGES.RDB$RELATION_NAME = RELS.BDRELATION_NAME and
                           RDB$USER_PRIVILEGES.RDB$USER = 'INTEGRACOES') then 'TRUE'
         else 'FALSE'
       end BDINSERT,
       case
         when exists(select first 1 RDB$PRIVILEGE
                     from RDB$USER_PRIVILEGES
                     where RDB$USER_PRIVILEGES.RDB$PRIVILEGE = 'A' and
                           RDB$USER_PRIVILEGES.RDB$RELATION_NAME = RELS.BDRELATION_NAME and
                           RDB$USER_PRIVILEGES.RDB$USER = 'INTEGRACOES') then 'TRUE'
         when exists(select first 1 RDB$PRIVILEGE
                     from RDB$USER_PRIVILEGES
                     where RDB$USER_PRIVILEGES.RDB$PRIVILEGE = 'U' and
                           RDB$USER_PRIVILEGES.RDB$RELATION_NAME = RELS.BDRELATION_NAME and
                           RDB$USER_PRIVILEGES.RDB$USER = 'INTEGRACOES') then 'TRUE'
         else 'FALSE'
       end BDUPDATE,
       case
         when exists(select first 1 RDB$PRIVILEGE
                     from RDB$USER_PRIVILEGES
                     where RDB$USER_PRIVILEGES.RDB$PRIVILEGE = 'A' and
                           RDB$USER_PRIVILEGES.RDB$RELATION_NAME = RELS.BDRELATION_NAME and
                           RDB$USER_PRIVILEGES.RDB$USER = 'INTEGRACOES') then 'TRUE'
         when exists(select first 1 RDB$PRIVILEGE
                     from RDB$USER_PRIVILEGES
                     where RDB$USER_PRIVILEGES.RDB$PRIVILEGE = 'D' and
                           RDB$USER_PRIVILEGES.RDB$RELATION_NAME = RELS.BDRELATION_NAME and
                           RDB$USER_PRIVILEGES.RDB$USER = 'INTEGRACOES') then 'TRUE'
         else 'FALSE'
       end BDDELETE,
       BDSP
from (select trim(cast(R.RDB$RELATION_NAME as varchar(64) character set win1252)) as BDRELATION_NAME,
             trim(replace(replace(cast(R.RDB$DESCRIPTION as varchar(32000) character set win1252), '<DESCRIPTION>', ''), '</DESCRIPTION>', '')) as BDRELATIONDESCRIPTION,
             trim(B.BDDESCRICAO) as BDDESCRICAO, 
             trim(B.BDDESCRICAOTELA) as BDDESCRICAOTELA,
             trim(B.BDEXEMPLOSQL) as BDEXEMPLOSQL,
             'FALSE' as BDSP
      from RDB$RELATIONS R
      left join TDESC_TABLE_BANCO B on R.RDB$RELATION_NAME = B.BDTABLE
      where R.RDB$SYSTEM_FLAG = 0
      union all
      select trim(cast(P.RDB$PROCEDURE_NAME as varchar(64) character set win1252)) as BDRELATION_NAME,
             trim(replace(replace(cast(P.RDB$DESCRIPTION as varchar(32000) character set win1252), '<DESCRIPTION>', ''), '</DESCRIPTION>', '')) as BDRELATIONDESCRIPTION,
             '' as BDDESCRICAO, '' as BDDESCRICAOTELA, '' as BDEXEMPLOSQL, 'TRUE' as BDSP
      from RDB$PROCEDURES P
      where P.RDB$SYSTEM_FLAG = 0) RELS
left join(select distinct RDB$USER_PRIVILEGES.RDB$RELATION_NAME
          from RDB$USER_PRIVILEGES
          where RDB$USER_PRIVILEGES.RDB$USER = 'INTEGRACOES') P on RELS.BDRELATION_NAME = P.RDB$RELATION_NAME
where ((((select first 1 bdcodigo from tpersonalizacao) > 80000) and ((select first 1 bdcodigo from tpersonalizacao) < 90000)) and ((select first 1 bdcodigo from tpersonalizacao) <> 80210)) or (exists(select first 1 RDB$PRIVILEGE
                     from RDB$USER_PRIVILEGES
                     where RDB$USER_PRIVILEGES.RDB$RELATION_NAME = RELS.BDRELATION_NAME and
                           RDB$USER_PRIVILEGES.RDB$USER = 'INTEGRACOES'))
^

CREATE OR ALTER VIEW VW_CAMPOS_TABELAS_FB(
    BDRELATION_NAME,
    BDFIELD_NAME,
    BDTIPOFIELD,
    BDFIELD_SUB_TYPE,
    BDFIELD_LENGTH,
    BDCOLLATION_ID,
    BDDESCRIPTION,
    BDPK,
    BDFK,
    BDFOREIGN_KEY_TABLE,
    BDROREIGN_KEY_FIELDS,
    BDSP)
AS
select cast(BDRELATION_NAME as varchar(64) character set win1252) BDRELATION_NAME,
       cast(BDFIELDNAME as varchar(64) character set win1252) BDFIELDNAME,
       case
         when RF.RDB$FIELD_TYPE = 7 then 'SMALLINT'
         when RF.RDB$FIELD_TYPE = 8 then case
                                           when RF.RDB$FIELD_SUB_TYPE = 1 then 'NUMERIC'
                                           when RF.RDB$FIELD_SUB_TYPE = 2 then 'DECIMAL'
                                           else 'INTEGER'
                                         end
         when RF.RDB$FIELD_TYPE = 10 then 'FLOAT'
         when RF.RDB$FIELD_TYPE = 12 then 'DATE'
         when RF.RDB$FIELD_TYPE = 13 then 'TIME'
         when RF.RDB$FIELD_TYPE = 14 then 'CHAR'
         when RF.RDB$FIELD_TYPE = 16 then case
                                            when RF.RDB$FIELD_SUB_TYPE = 1 then 'NUMERIC'
                                            when RF.RDB$FIELD_SUB_TYPE = 2 then 'DECIMAL'
                                            else 'BIGINT'
                                          end
         when RF.RDB$FIELD_TYPE = 27 then 'DOUBLE PRECISION'
         when RF.RDB$FIELD_TYPE = 35 then 'TIMESTAMP'
         when RF.RDB$FIELD_TYPE = 37 then 'VARCHAR'
         when RF.RDB$FIELD_TYPE = 261 then 'BLOB'
       end BDTIPOFIELD,
       RF.RDB$FIELD_SUB_TYPE,
       case
         when (RF.RDB$FIELD_TYPE = 8) or (RF.RDB$FIELD_TYPE = 16) then case
                                                                         when RF.RDB$FIELD_SUB_TYPE = 0 then null
                                                                         else cast(RF.RDB$FIELD_PRECISION as varchar(2)) || '.' ||(cast((RF.RDB$FIELD_SCALE * -1) as varchar(2)))
                                                                       end
         when RF.RDB$FIELD_TYPE = 37 then RF.RDB$FIELD_LENGTH
         else null
       end FIELD_LENGTH,
       CL.RDB$COLLATION_NAME,
       case
          when BDSP = 'FALSE' then (select first 1 trim(cast(RDB$DESCRIPTION as varchar(32000))) from rdb$relation_fields where rdb$relation_fields.rdb$relation_name = base.bdrelation_name and rdb$relation_fields.rdb$field_name = base.bdfieldname)
       else
          (select first 1 trim(cast(RDB$DESCRIPTION as varchar(32000))) from RDB$PROCEDURE_PARAMETERS where RDB$PROCEDURE_PARAMETERS.RDB$PROCEDURE_NAME = base.bdrelation_name and RDB$PROCEDURE_PARAMETERS.RDB$PARAMETER_NAME = base.bdfieldname)
       end bddescription,

       BDPK, BDFK, BDFOREIGN_KEY_TABLE,
       null BDCAMPOSFK,
       BDSP
from (select R.RDB$RELATION_NAME BDRELATION_NAME, F.RDB$FIELD_NAME BDFIELDNAME, F.RDB$FIELD_SOURCE BDFIELDSOURCE,
             case
               when exists(select first 1 RDB$INDEX_SEGMENTS.RDB$FIELD_NAME  from RDB$INDEX_SEGMENTS
                          inner join(select RDB$INDEX_NAME
                                                 from RDB$RELATION_CONSTRAINTS RC
                                                 where RC.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY' and RC.RDB$RELATION_NAME = F.RDB$RELATION_NAME) RC1 on RC1.RDB$INDEX_NAME = RDB$INDEX_SEGMENTS.RDB$INDEX_NAME
                          where RDB$INDEX_SEGMENTS.RDB$FIELD_NAME = F.RDB$FIELD_NAME) then 'TRUE'
               else 'FALSE'
             end BDPK,

             case
               when exists(select first 1 RDB$INDEX_SEGMENTS.RDB$FIELD_NAME  from RDB$INDEX_SEGMENTS
                          inner join(select RDB$INDEX_NAME
                                                 from RDB$RELATION_CONSTRAINTS RC
                                                 where RC.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' and RC.RDB$RELATION_NAME = F.RDB$RELATION_NAME) RC1 on RC1.RDB$INDEX_NAME = RDB$INDEX_SEGMENTS.RDB$INDEX_NAME
                          where RDB$INDEX_SEGMENTS.RDB$FIELD_NAME = F.RDB$FIELD_NAME) then 'TRUE'
               else 'FALSE'
             end BDFK,
             null BDFOREIGN_KEY_TABLE,
             'FALSE' as BDSP,
             F.RDB$FIELD_POSITION BDFPOS

      from RDB$RELATION_FIELDS F
      inner join RDB$RELATIONS R on R.RDB$RELATION_NAME = F.RDB$RELATION_NAME
      where R.RDB$SYSTEM_FLAG = 0

      union all
      select P.RDB$PROCEDURE_NAME, P.RDB$PARAMETER_NAME, P.RDB$FIELD_SOURCE BDFIELDSOURCE, 'FALSE' BDPK,

             'FALSE' BDFK, null BDFOREIGN_KEY_TABLE, 'TRUE' BDSP,
             p.RDB$PARAMETER_NUMBER BDFPOS

      from RDB$PROCEDURE_PARAMETERS P
      where P.RDB$SYSTEM_FLAG = 0) BASE
inner join RDB$FIELDS RF on RF.RDB$FIELD_NAME = BASE.BDFIELDSOURCE
left join RDB$COLLATIONS CL on RF.RDB$COLLATION_ID = CL.RDB$COLLATION_ID and RF.RDB$CHARACTER_SET_ID = CL.RDB$CHARACTER_SET_ID
ORDER BY BDRELATION_NAME, BDFPOS
^

CREATE OR ALTER VIEW VW_CAMPOS_TABELAS_FB_SEARCH(
    BDRELATION_NAME,
    BDFIELD_NAME,
    BDDESCRIPTION,
    BDSP)
AS
select BDRELATION_NAME,
       BDFIELDNAME,
       case
          when BDSP = 'FALSE' then (select first 1 trim(cast(RDB$DESCRIPTION as varchar(32000))) from rdb$relation_fields where rdb$relation_fields.rdb$relation_name = base.bdrelation_name and rdb$relation_fields.rdb$field_name = base.bdfieldname)
       else
          (select first 1 trim(cast(RDB$DESCRIPTION as varchar(32000))) from RDB$PROCEDURE_PARAMETERS where RDB$PROCEDURE_PARAMETERS.RDB$PROCEDURE_NAME = base.bdrelation_name and RDB$PROCEDURE_PARAMETERS.RDB$PARAMETER_NAME = base.bdfieldname)
       end bddescription,
       BDSP
from (select R.RDB$RELATION_NAME BDRELATION_NAME, F.RDB$FIELD_NAME BDFIELDNAME, F.RDB$FIELD_SOURCE BDFIELDSOURCE ,
             'FALSE' as BDSP
      from RDB$RELATION_FIELDS F
      inner join RDB$RELATIONS R on R.RDB$RELATION_NAME = F.RDB$RELATION_NAME
      where R.RDB$SYSTEM_FLAG = 0

      union
      select P.RDB$PROCEDURE_NAME, P.RDB$PARAMETER_NAME, P.RDB$FIELD_SOURCE BDFIELDSOURCE,'TRUE' BDSP

      from RDB$PROCEDURE_PARAMETERS P
      where P.RDB$SYSTEM_FLAG = 0) BASE
inner join RDB$FIELDS RF on RF.RDB$FIELD_NAME = BASE.BDFIELDSOURCE
left join RDB$COLLATIONS CL on RF.RDB$COLLATION_ID = CL.RDB$COLLATION_ID and RF.RDB$CHARACTER_SET_ID = CL.RDB$CHARACTER_SET_ID
^

CREATE OR ALTER VIEW VW_INT_SPEDICMS_REF(
    BDCODEMP,
    BDCODIGO,
    BDREFERENCIA,
    BDTIPOEXPCODPART,
    BDEXP1400,
    BDTIPOEXPCONTA,
    BDREGD695,
    BDEXP1900,
    BDEXPINCENTFISCAIS,
    BDEXPSER,
    BDEXPE310,
    BDNAOEXPC173,
    BDEXP_REG_D300,
    BDGERARE115,
    BDGERAR1921,
 BDGERAR0221)
AS
SELECT
    c.bdcodemp,
    c.bdcodigo,
    c.bdreferencia,
    c.bdtipoexpcodpart,
    c.BDEXP1400,
    c.BDTIPOEXPCONTA,
    c.BDREGD695,
    c.BDEXP1900,
    c.BDEXPINCENTFISCAIS,
    c.BDEXPSER,
    c.BDEXPE310,
    c.BDNAOEXPC173,
    c.BDEXP_REG_D300,
    c.BDGERARE115,
    c.BDGERAR1921,
 c.BDGERAR0221
FROM
(SELECT p.bdcodemp,
        p.bdcodigo,
        p.bdreferencia,
        p.bdtipoexpcodpart,
        p.BDEXP1400,
        p.BDTIPOEXPCONTA,
        p.BDREGD695,
        p.BDEXP1900,
        p.BDEXPINCENTFISCAIS,
        P.BDEXPSER,
        P.BDEXPE310,
        P.BDNAOEXPC173,
        P.BDEXP_REG_D300,
        P.BDGERARE115,
        P.BDGERAR1921,
  P.BDGERAR0221
FROM vef_int_tspedicms p
WHERE p.bdreferencia = (SELECT FIRST 1 ref.bdreferencia
                        FROM vef_int_tspedicms ref
                        WHERE ref.bdcodemp = p.bdcodemp
                          AND ref.bdreferencia <= (COALESCE(
                                                      (SELECT MAX(r1.bdreferencia) FROM vef_int_tspedicms r1 WHERE r1.bdcodemp = p.bdcodemp AND r1.bdreferencia <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
                                                      (SELECT MIN(r2.bdreferencia) FROM vef_int_tspedicms r2 WHERE r2.bdcodemp = p.bdcodemp)
                                                  ))
                        ORDER BY ref.bdreferencia DESC)
GROUP BY p.bdcodemp, p.bdcodigo, p.bdreferencia,  p.bdtipoexpcodpart, p.BDEXP1400, p.BDTIPOEXPCONTA, p.BDREGD695, P.BDEXP1900, P.BDEXPINCENTFISCAIS, P.BDEXPSER, P.BDEXPE310, P.BDNAOEXPC173, P.BDEXP_REG_D300, P.BDGERARE115, P.BDGERAR1921, P.BDGERAR0221
) c
;^

CREATE OR ALTER VIEW VW_INT_SPEDICMSREF19_REF(
    BDCODEMP,
    BDREG,
    BDCODSUBAPU,
    BDVIGINICIAL,
    BDVIGFINAL)
AS
SELECT C.BDCODEMP, 'PE01' BDREG, C.BDCODSUBAPU, C.BDVIGINICIAL, C.BDVIGFINAL
FROM (
select ICMS.BDCODEMP,ICMS.BDCODIGO, ICMS.BDEXPINCENTFISCAIS
from VW_INT_SPEDICMS_REF ICMS
WHERE ICMS.BDEXPINCENTFISCAIS = 'TRUE'
) SPED
JOIN VEF_INT_TSPEDICMSCONF1960 C ON (C.BDCODEMP = SPED.BDCODEMP AND C.BDCODIGO = SPED.BDCODIGO)
UNION ALL
SELECT C.BDCODEMP,'PE03' BDREG, C.BDCODSUBAPU, C.BDVIGINICIAL, C.BDVIGFINAL
FROM (
select ICMS.BDCODEMP,ICMS.BDCODIGO, ICMS.BDEXPINCENTFISCAIS
from VW_INT_SPEDICMS_REF ICMS
WHERE ICMS.BDEXPINCENTFISCAIS = 'TRUE'
) SPED
JOIN VEF_INT_TSPEDICMSCONF1970 C ON (C.BDCODEMP = SPED.BDCODEMP AND C.BDCODIGO = SPED.BDCODIGO)
UNION ALL
SELECT C.BDCODEMP, 'PE04' BDREG, C.BDCODSUBAPU, C.BDVIGINICIAL, C.BDVIGFINAL
FROM (
select ICMS.BDCODEMP,ICMS.BDCODIGO, ICMS.BDEXPINCENTFISCAIS
from VW_INT_SPEDICMS_REF ICMS
WHERE ICMS.BDEXPINCENTFISCAIS = 'TRUE'
) SPED
JOIN VEF_INT_TSPEDICMSCONF1980 C ON (C.BDCODEMP = SPED.BDCODEMP AND C.BDCODIGO = SPED.BDCODIGO);
^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_C177_GIAF (
    PRSESSAO integer,
    PRSESSAOPROD integer,
    PRREFLAN integer)
as
declare variable PRCHAVE integer;
declare variable PRCODEMP integer;
declare variable PRCODITEMGIAF integer;
declare variable PRPRODINCENTIVADO DM_BOOLEAN;
declare variable PRINCENTIVOTRANSP DM_BOOLEAN;
declare variable PROPEDIFIMPORTACAO DM_BOOLEAN;
declare variable PRORDEM integer;
declare variable PRORDEMPROD integer;
declare variable PRDESCAD varchar(500);
begin
  /* Procedure Text */

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRREFLAN);

  FOR
   SELECT C.BDCODEMP,C.BDORDEM,C.BDORDEMPRO,C.BDCHAVE,PRO.BDPRODINCENTIVADO,PRO.BDCODITEMGIAF,
   PRO.BDINCENTIVOTRANSP,IIF((SUBSTRING(S.BDCSTICMS FROM 1 FOR 1) <> '0') AND (substring(A56.BDCODINFAD56 FROM 1 FOR 4) = 'PE03') AND  (SUBSTRING(S.BDCODNAT FROM 1 FOR 1) = '5'),PRO.BDOPEDIFIMPORTACAO, 'FALSE'),
   A56.BDDESCRICAO
   FROM TMP_VEF_EMP_TMOVPROSAIC177_TEMP C
   JOIN TMP_VEF_EMP_TMOVPROSAI_TEMP S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDCHAVE AND S.BDORDEM = C.BDORDEM AND S.BDORDEMPRO = C.BDORDEMPRO AND S.BDSESSAO = C.BDSESSAO)
   LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP SAI ON (SAI.BDCODEMP = S.BDCODEMP AND SAI.BDSESSAO = S.BDSESSAO AND SAI.BDCHAVE = S.BDCHAVE)
   LEFT OUTER JOIN TMP_TCADPRO_TEMP PRO ON (PRO.BDSESSAO = :PRSESSAOPROD AND PRO.BDCODEMP = S.BDCODEMP AND PRO.BDCODPROD = S.BDCODPROD AND PRO.BDCODPRODVINC = S.BDORDEMPRO)
   LEFT OUTER JOIN VEF_BASE_TTABINFAD56 A56 ON (A56.BDORDEM56 = PRO.BDCODITEMGIAF)
   JOIN VW_INT_SPEDICMSREF19_REF ICMS ON (ICMS.BDCODEMP = C.BDCODEMP AND ICMS.BDREG = substring(A56.BDCODINFAD56 FROM 1 FOR 4) AND ICMS.BDCODSUBAPU = substring(A56.BDCODINFAD56 FROM 5 FOR 2))
   WHERE C.BDSESSAO = :PRSESSAO
   AND COALESCE(C.BDCODTIPO,0) <> 152
   AND ICMS.BDVIGINICIAL <= SAI.BDREFLAN AND (ICMS.BDVIGFINAL >=  SAI.BDREFLAN OR (COALESCE(ICMS.BDVIGFINAL,0) = 0))
   INTO :PRCODEMP,:PRORDEM,:PRORDEMPROD,:PRCHAVE,:PRPRODINCENTIVADO,:PRCODITEMGIAF,:PRINCENTIVOTRANSP,:PROPEDIFIMPORTACAO,:PRDESCAD
  DO
   BEGIN
     UPDATE TMP_VEF_EMP_TMOVPROSAIC177_TEMP C SET
     C.BDOPEINCENTIVADA  = :PRPRODINCENTIVADO,
     C.BDCODINFAD        = :PRCODITEMGIAF,
     C.BDINCENTIVOTRANSP = :PRINCENTIVOTRANSP,
     C.BDSAIINCENTIVADAPORIMP = :PROPEDIFIMPORTACAO,
     C.BDVLRBASECREDPRESUMIDO = (IIF(COALESCE(:PROPEDIFIMPORTACAO,'FALSE') = 'FALSE',0,C.BDVLRBASECREDPRESUMIDO)),
     C.BDDESCCODINFAD =  :PRDESCAD
     WHERE C.BDCODEMP = :PRCODEMP
     AND C.BDSESSAO = :PRSESSAO
     AND C.BDCHAVE  = :PRCHAVE
     AND C.BDORDEM  = :PRORDEM
     AND C.BDORDEMPRO = :PRORDEMPROD;
   END
end^

CREATE OR ALTER VIEW VW_VRH_EMP_TCOL_ADM(
    BDCODEMP,
    BDCODCOL,
    BDTIPOADMCOL,
    BDNATUOCUPCOL,
    BDDATAINIAQUICOL,
    BDSALINICOL,
    BDDIASPRAZO1COL,
    BDDATAFIMPRAZO1COL,
    BDDIASPRAZO2COL,
    BDDATAFIMPRAZO2COL,
    BDDESCCONTSINCOL,
    BDALVARACOL,
    BDFICHAREGCOL,
    BDLIVROREGCOL,
    BDNROFOLHAREGCOL,
    BDCONTRCOL,
    BDDESCCONTASSCOL,
    BDREGTRAB,
    BDCODTIPOADMSOCIAL,
    BDCNPJEMPANT,
    BDFICHAREGANT,
    BDDATAADMANT,
    BDFIMCONTRATO,
    BDCATEGORIAESOCIALANT,
    BDREGJORTRAB,
    BDMOTCONTRAT,
    BDCOLSUBST,
    BDINDADMCOL,
    BDTRANSONUS,
    BDNAOTEMMATRICULA,
    BDINDCONTRACAO,
    BDDATATERMINOCONTFATO,
    BDCODTIPOPROV,
    BDNUMEROPROCESSORT,
    BDNOVADATAADMRT,
    BDMATRICULART)
AS
select
  ADM.BDCODEMP,
  ADM.BDCODCOL,
  ADM.BDTIPOADMCOL,
  ADM.BDNATUOCUPCOL,
  ADM.BDDATAINIAQUICOL,
  ADM.BDSALINICOL,
  ADM.BDDIASPRAZO1COL,
  case when coalesce(ADM.BDDIASPRAZO1COL, 0) > 0 then COL.BDDATAADMCOL + ADM.BDDIASPRAZO1COL - 1 else ADM.BDDATAFIMPRAZO1COL end,
  ADM.BDDIASPRAZO2COL,
  case when coalesce(ADM.BDDIASPRAZO2COL, 0) > 0 then COL.BDDATAADMCOL + coalesce(ADM.BDDIASPRAZO1COL, 0) + ADM.BDDIASPRAZO2COL - 1 else ADM.BDDATAFIMPRAZO2COL end,
  ADM.BDDESCCONTSINCOL,
  ADM.BDALVARACOL,
  ADM.BDFICHAREGCOL,
  ADM.BDLIVROREGCOL,
  ADM.BDNROFOLHAREGCOL,
  ADM.BDCONTRCOL,
  ADM.BDDESCCONTASSCOL,
  ADM.BDREGTRAB,
  ADM.BDCODTIPOADMSOCIAL,
  ADM.BDCNPJEMPANT,
  ADM.BDFICHAREGANT,
  ADM.BDDATAADMANT,
  ADM.BDFIMCONTRATO,
  ADM.BDCATEGORIAESOCIALANT,
  ADM.BDREGJORTRAB,
  ADM.BDMOTCONTRAT,
  ADM.BDCOLSUBST,
  ADM.BDINDADMCOL,
  ADM.BDTRANSONUS,
  ADM.BDNAOTEMMATRICULA,
  ADM.BDINDCONTRACAO,
  ADM.BDDATATERMINOCONTFATO,
  ADM.BDCODTIPOPROV,
  ADM.BDNUMEROPROCESSORT,
  ADM.BDNOVADATAADMRT,
  ADM.BDMATRICULART
from
  VRH_EMP_TCOL_ADM ADM
join
  VRH_EMP_TCOLCON COL on (COL.BDCODEMP = ADM.BDCODEMP and COL.BDCODCOL = ADM.BDCODCOL)
;^

-- Criado apenas para resolver o problema de bases que já tem dentro da empresa
CREATE OR ALTER VIEW VW_TTERCEIRO_SOLETRADO(
    BDCODEMP,
    BDCODCOL,
    BDNOMCOL,
    BDDTPCOL)
AS
SELECT
    0 as BDCODEMP,
    TER.BDCODTER ,
    null as BDNOMETER  ,
    'Terceiro' as BDDTPCOL
FROM tterceiro TER
;^

CREATE OR ALTER VIEW VW_USUARIO_EMPRESA(
    BDCODEMP,
    BDCODUSU)
AS
SELECT first 1 bdcodemp, bdcodusu FROM tempresa_usuario;^

CREATE OR ALTER procedure SP_CONSULTAEMPRESAS_SIS (
    PRREFMICRO integer,
    PRCODEMP integer,
    PRINATIVAS smallint)
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDCNPJEMP varchar(18),
    BDDATAINIATIVEMP date,
    BDORGAOEMP varchar(8),
    BDDATAREGEMP date,
    BDDATACONSTEMP date,
    BDDESCCARTEMP varchar(40),
    BDDATAFIMATIVEMP date,
    BDCODPLAPADRAO integer,
    BDCODHIST integer,
    BDCODCENTROS integer,
    BDCODCID integer,
    BDCODCONT integer,
    BDCODNATJUR integer,
    BDCODCNAE integer,
    BDNOMEMP DM_BDNOMEMP,
    BDNOMREDUZEMP DM_BDNOMREDUZEMP,
    BDAPEEMP DM_BDAPEMP,
    BDNOMFANEMP varchar(200),
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP varchar(9),
    BDDDDEMP integer,
    BDFONEEMP DM_BDTELEFONE,
    BDFAXEMP DM_BDTELEFONE,
    BDDDDCELULAREMP integer,
    BDCELULAREMP DM_BDTELEFONE,
    BDEMAILEMP DM_BDEMAIL,
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDLOGREMP varchar(15),
    BDIEEMP varchar(20),
    BDIMEMP varchar(20),
    BDSITEMP varchar(5),
    BDDDDFAXEMP integer,
    BDNOMCID varchar(40),
    BDCODUF integer,
    BDNOMECONT varchar(40),
    BDSIGLAUF varchar(2),
    BDANTECIPICMS INTEGER,
    BDANTECIPICMSCT integer,
    BDDESCUF varchar(40),
    BDRETINSS varchar(5),
    BDVLRMININSS numeric(15,2),
    BDCODCONFATIVO integer,
    BDSUFRAMA varchar(9),
    BDCODACESSOSN varchar(12),
    BDPERFILSPED integer,
    BDATIVIDADESPED integer,
    BDCODCONFIPI integer,
    BDCODCONFIRLP integer,
    BDCODCONFDIMESC integer,
    BDCODPORTEEMP integer,
    BDCODAPUCON integer,
    BDCODESCCONT integer,
    BDCODREGAPU integer,
    BDCONTPRODEC varchar(5),
    BDNRPARPRODEC integer,
    BDLANBCICMSVALCONT varchar(5),
    BDLANBCICMSISEOUT integer,
    BDLANCLISAISER varchar(5),
    BDLANPROENT varchar(5),
    BDLANPROSAI varchar(5),
    BDMOVSER varchar(5),
    BDPERCISS numeric(15,6),
    BDREDPERCISS numeric(15,6),
    BDMOVIRRF varchar(5),
    BDALIQIRRF numeric(15,6),
    BDISENTOIRRF numeric(15,6),
    BDEMPINATIVA varchar(5),
    BDEMPDIFPAPEL varchar(5),
    BDEMPBARREST varchar(5),
    BDVERIFICARNOTASJALAN integer,
    BDCODPLANOONLINE integer,
    BDLRISSSN numeric(15,6),
    BDCOMERCIO varchar(5),
    BDINDUSTRIA varchar(5),
    BDSERVICO varchar(5),
    BDANEXOIII varchar(5),
    BDANEXOIV varchar(5),
    BDANEXOV varchar(5),
    BDCODENQFED integer,
    BDSUBSTRIB integer,
    BDCODCONFDACON integer,
    BDCODCONFICMSSPED integer,
    BDCODCONFCIAP integer,
    BDREDBCICMSENT numeric(15,6),
    BDREDBCICMSSAI numeric(15,6),
    BDICMSMONO DM_BOOLEAN,
    BDCODCONFDASN integer,
    BDRETPARPIS varchar(5),
    BDRETPARCOFINS varchar(5),
    BDRETPARCSLL varchar(5),
    BDRETPARIRRF varchar(5),
    BDRETPARISSQN varchar(5),
    BDRETPARINSS varchar(5),
    BDRETPARFUNRURAL varchar(5),
    BDTIPOAPURACAO integer,
    BDSOMFREBASEICMS varchar(5),
    BDSOMFREVLRCONTAB varchar(5),
    BDCODPLATROCA integer,
    BDCODPLACFOP integer,
    BDCODCONFBLOCOP integer,
    BDCREDPRESUMIDO varchar(5),
    BDTERMOACEITE varchar(5),
    BDANTECIPAIMPOSTO varchar(5),
    BDTIPODECLARANTEDMED integer,
    BDREGISTROANSDMED integer,
    BDNUMEROCNESDMED integer,
    BDDTOBRIGSPEDCONT date,
    BDTIPOAPURACAORET integer,
    BDTIPOAPURACAORETIR integer,
    BDDTOBRIGSPEDICMS date,
    BDCODCONTEF integer,
    BDLIVRO varchar(15),
    BDFOLHA varchar(15),
    BDNOMECARTORIO varchar(100),
    BDLANCAPARCELAAUTO varchar(5),
    BDCODIGOPLA integer,
    BDINDATIV integer,
    BDTRANMANUAL varchar(5),
    BDIMPORTARVALORESICMSSN DM_BOOLEAN,
    BDDIFALIQ varchar(5),
    BDDIFALIQBASEEM integer,
    BDANEXOVI DM_BOOLEAN,
    BDCODPLATRIB integer,
    BDCODPLAPADRAOREF integer,
    BDINDNATPJ integer,
    BDCODIBGE integer,
    BDFORMATRIBUTACAO integer,
    BDSOMAPISCOFVLRCONT DM_BOOLEAN,
    BDSOMAIIVLRCONT DM_BOOLEAN,
    BDMANTERPARCELAS DM_BOOLEAN,
    BDCODPLANOINCONS integer,
    BDABRIRRATEIO DM_BOOLEAN,
    BDNAOPERMITERATEIOGRUPO DM_BOOLEAN,
    BDINTEGRANET DM_BOOLEAN,
    BDSOMAIPIPROD DM_BOOLEAN,
    BDSOMAICMSVLRCONT DM_BOOLEAN,
    BDCODPLAE115 integer,
    BDDATACADEMP date,
    BDCODCLATRI integer,
    BDDATAOBRIGREINF date,
    BDSOMASTPROD DM_BOOLEAN,
    BDCALCANTICMS varchar(5),
    BDCONSIPIBC varchar(5),
    BDIMPICMSST varchar(5),
    BDANEXOIII_2018 varchar(5),
    BDANEXOIV_2018 varchar(5),
    BDANEXOV_2018 varchar(5),
    BDSTATUSEMP integer,
    BDQTDBACKUPEMP integer,
    BDIMPORTARISS varchar(5),
    BDIMPORTARCTESAI DM_BOOLEAN,
    BDNAOVALIDACONTRATO DM_BOOLEAN,
    BDINCORPORADORAS DM_BOOLEAN,
    BDALIQINSS DM_NUMERIC_7_4_ALIQ,
    BDCODPLANOCONFSN integer,
    BDGERAC490 varchar(5),
    BDTIPOCAEPF integer,
    BDCODPLACATSP integer,
    BDOPTANTERET DM_BOOLEAN,
    BDMANTERC197CATSP varchar(5),
    BDCODCLASSESTAB integer,
    BDCODPLASEFSC integer,
    BDAPURAGIAST DM_BOOLEAN,
    BDCARNELEAO DM_BOOLEAN,
    BDEXPINCENTFISCAIS DM_BOOLEAN,
    BDCODCONFGIAFPE integer,
    BDVENDACOOP DM_BOOLEAN,
    BDDIFALIQ_NAOGERA_C197 BOOLEAN,
    BDCONTABILIZASCP boolean,
	BDUSARTAGVNF BOOLEAN)
 AS
BEGIN 
 SUSPEND; 
END^

CREATE OR ALTER PROCEDURE SP_COPIA_PROGRAMAS_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 RETURNS(WCODPLAPROG INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CRIA_DADOSCALC_BAIXA AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_CRIA_DETGPSSEFIP(PRCODEMP VARCHAR(32000),
PRANOMESPAG INTEGER,
PRTIPOGPS INTEGER,
PRTIPOEMISSAO INTEGER)
 RETURNS(BDOK INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXCLUI_VERBA_DE_TUDO(PRCODVER INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_EXCLUSAO_CBO_NAOUSADO(BDCODCBO INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_EXISTE_COLABORADOR_NOVO(PRCODEMP INTEGER,
PRCODCOL INTEGER)
 RETURNS(BDCODCOL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER procedure SP_EXISTE_COLABORADOR_DOWNLOAD(PRCODCOL integer,PRCODEMP integer)
returns (BDCODIGO integer)
as
BEGIN SUSPEND; END^

create or alter procedure SP_VATI_GERAR_INCON_TDEPAUTO (
    PRREFERENCIA integer,
    PRDATAINI date,
    PRDATAFIN date,
    PRDIAPROC integer = null)
 as
 BEGIN END
^

CREATE OR ALTER PROCEDURE SP_EXP_ATIVA_CONTABIL (
    PRCODEMP INTEGER,
    PRDATAINICIAL DATE,
    PRDATAFINAL DATE,
    PRCTALONINI VARCHAR(40),
    PRCTALONFIM VARCHAR(40),
    PRCODPLANOPADRAO INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRCONTABILIZADATABAIXA INTEGER = 0,
    PRBAIXAINDIVIDUAL INTEGER = 0,
    PRORDER VARCHAR(10) = 'ASC')
RETURNS (
    BDREF VARCHAR(10),
    BDREFINTEIRO INTEGER,
    BDCODTPLABEM INTEGER,
    BDCTALONBEM VARCHAR(40),
    BDNOMTPLABEM VARCHAR(100),
    BDCODNOMTPLABEM VARCHAR(110),
    BDCODBEM INTEGER,
    BDNOMBEM VARCHAR(200),
    BDCODNOMBEM VARCHAR(210),
    BDCODTPCC INTEGER,
    BDNOMTPCC VARCHAR(40),
    BDDEPRECIACAOPERIODO NUMERIC(18,6),
    BDVALORBAIXAPERIODO NUMERIC(18,6),
    BDDEPRECIACAOACUMULADA NUMERIC(18,6),
    BDTAXA NUMERIC(9,6),
    BDDATATAXADEP DATE,
    BDVALORRESIDUAL NUMERIC(18,6),
    BDCODPLAPADRAO INTEGER,
    BDCODHIST INTEGER,
    BDCTADEBITODEPRE INTEGER,
    BDCTACREDITODEPRE INTEGER,
    BDHISTORICODEPRE INTEGER,
    BDCTADEBITOBAIXA INTEGER,
    BDCTACREDITOBAIXA INTEGER,
    BDHISTORICOBAIXA INTEGER,
    BDCTADEBITODEPBAI INTEGER,
    BDCTACREDITODEPBAI INTEGER,
    BDHISTORICODEPBAI INTEGER,
    BDDATABAIXA DATE,
    BDCOMPLEMENTOBAIXA VARCHAR(200),
    BDCODBAIXA INTEGER,
    BDRESIDUALDEB INTEGER,
    BDRESIDUALCRE INTEGER,
    BDRESIDUALHIS INTEGER,
    BDVALORRESIDUALBAIXA NUMERIC(15,2),
    BDCAPITALDEB INTEGER,
    BDCAPITALCRE INTEGER,
    BDCAPITALHIS INTEGER,
    BDVALORCAPITAL NUMERIC(15,2),
    BDPERDACAPITALDEB INTEGER,
    BDPERDACAPITALCRE INTEGER,
    BDPERDACAPITALHIS INTEGER,
    BDVALORBAIXATOTAL NUMERIC(15,2),
    BDVALORAQUISICAO NUMERIC(15,2),
    BDDEPCCIBE DM_BOOLEAN,
    BDBAIDEPCCIBE DM_BOOLEAN,
    BDBAIAQUICCIBE DM_BOOLEAN,
    BDRESIDUALCCIBE DM_BOOLEAN,
    BDCAPITALCCIBE DM_BOOLEAN,
    BDPERDACAPITALCCIBE DM_BOOLEAN)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(10000),
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRDATARECFGTS DATE,
PRDATARECINSS DATE,
PRTIPOFOLHA INTEGER,
PRMODALIDADE VARCHAR(1),
PRINDRECFGST VARCHAR(1),
PRINDRECINSS VARCHAR(1))
 RETURNS(BDARQ INTEGER,
BDREG VARCHAR(360),
BDORDEM VARCHAR(70),
BDINC VARCHAR(32000),
BDCONTADOR INTEGER,
BDCODREC INTEGER,
BDMODALIDADE VARCHAR(1))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_EMP_TSITCOL_ESOCIAL (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(32700)) 
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDDATAINISEFIP DATE,
    BDTIPOACID INTEGER,
    BDOBSERVACAO VARCHAR(255),
    BDCODDOE INTEGER,
    BDDIASSIT INTEGER,
    BDCODMOTESSIT INTEGER,
    BDCODMED INTEGER,
    BDCODSINTRAB INTEGER) 
AS
BEGIN SUSPEND; END
^


create or alter procedure SP_EXP_SEFIP_MOVIMENTACAO_COL (
    PRREFINI integer = 0,
    PRREFFIM integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATA date,
    BDDATASTR varchar(10),
    BDMOTIVO varchar(5),
    BDINDFGTS integer,
    BDCODMFG integer,
    BDDATAFIM date,
    BDINSSINTSIT DM_BOOLEAN,
    BDDATAINICIOSIT date,
    BDMOTENTRADA varchar(5),
    BDBENEFDEFERIDO DM_BOOLEAN)
as
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_REG_00 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
 BEGIN suspend; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_REG_10(PRSALFAM NUMERIC(15,6),
PRMATERNIDADE NUMERIC(15,6))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_REG_12(BDDEDMAT13 NUMERIC(15,6),
BDRURALFISICA NUMERIC(15,6),
BDRURALJURIDICA NUMERIC(15,6),
BDCOMPENSACAO NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDACUMULA NUMERIC(15,6),
BDACUMULATERC NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_REG_20(BDSALFAM INTEGER,
BDNOTASFISCAIS INTEGER)
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_REG_21(BDCOMPENSACAO NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDACUMULA NUMERIC(15,6),
BDACUMULATERC NUMERIC(15,6))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_REG_30(PRAUTONOMO INTEGER,
PRREMSEM13 NUMERIC(15,6),
PRREM13 NUMERIC(15,6),
PRVALINSS NUMERIC(15,6),
PRBASEINSS NUMERIC(15,6),
PRBASEINSS13MES NUMERIC(15,6),
PRBASEINSS13 NUMERIC(15,6))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_REG_32(PRCODMOV VARCHAR(5),
PRDATAMOV VARCHAR(10),
PRINDFGTS VARCHAR(1))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_REG_90 RETURNS(BDREG VARCHAR(360),
BDORDEM VARCHAR(300))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_DATA_UTIL (
    PRCODEMP integer,
    PRDATA date)
returns (
    BDDATA date)
as
begin suspend; end
^

-- 132928 - Raphael Teodoro - 10/03/2020
CREATE OR ALTER procedure SP_VRHF_PAGAMENTO_FN (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFFN integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDPAGEMP integer,
    BDDATAPGTOFN date,
    BDDATAPGTOFNINT integer)
as
begin suspend; end
^

CREATE OR ALTER PROCEDURE SP_FERIADO_EMPRESA(PRCODEMP INTEGER,
PRDATA DATE,
PRREFERENCIA INTEGER = 0,
PRSINDICATO INTEGER = 0)
 RETURNS(BDFERIADO VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_FUNCAO_CBO_ESOCIAL(PREMPRESA INTEGER,
PRCBO INTEGER)
 RETURNS(BDCODFUNCAO VARCHAR(30))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_FUNCOES_PLANO_EMP (
    PRCODEMP integer,
    PRCODPLAFUC integer,
    PRREFERENCIA integer,
    PRRHNET smallint = 0,
    PRCODTFUC integer = 0)
returns (
    BDCODEMP integer,
    BDCODEMPRHNET integer,
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDCODCBO integer,
    BDDESCCBO varchar(150),
    BDDESCTFUC varchar(40),
    BDCODCBOTSIN integer,
    BDDESCFUNCDET varchar(999),
    BDINATIVA varchar(5))
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_GERA_ADVERTENCIAS AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_GETREFERENCIA(PRCODEMP INTEGER,
PRREFMICRO INTEGER)
 RETURNS(BDREFEMP INTEGER)
 AS
DECLARE VARIABLE wrefemp INTEGER;
BEGIN
  SELECT FIRST 1 tempresas_ref.bdrefemp FROM tempresas_ref
  WHERE tempresas_ref.bdcodemp = :prcodemp
  AND tempresas_ref.bdrefemp <= :prrefmicro
  ORDER BY tempresas_ref.bdcodemp DESC, tempresas_ref.bdrefemp DESC
  INTO :wrefemp;

  IF (wrefemp IS NULL) THEN
     SELECT FIRST 1 tempresas_ref.bdrefemp FROM tempresas_ref
     WHERE tempresas_ref.bdcodemp = :prcodemp
     ORDER BY tempresas_ref.bdcodemp, tempresas_ref.bdrefemp
     INTO : wrefemp;

  bdrefemp = wrefemp;
  SUSPEND;
END
^

CREATE OR ALTER PROCEDURE SP_IMPOSTO_EMPRESA(PRCODEMP INTEGER,
PRCODSIS INTEGER,
PRTIPORETENCAO INTEGER,
PRREF INTEGER,
PRQTD INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDREFFIMIMP INTEGER,
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(100),
BDDATACRIACAO DATE,
BDDATAEXTINTO DATE,
BDCOMPETENCIA INTEGER,
BDDOCARRECADACAO INTEGER,
BDPERAPURACAO INTEGER,
BDDIAVENCTO INTEGER,
BDANTECIPA VARCHAR(5),
BDMESVENCTO INTEGER,
BDJUROSDIA INTEGER,
BDVLRJUROS NUMERIC(15,6),
BDJUROSDIAMES INTEGER,
BDMULTADIA INTEGER,
BDVLRMULTA NUMERIC(15,6),
BDMULTADIAMES INTEGER,
BDVLRMAXMULTA NUMERIC(15,6),
BDALIQIMPOSTO NUMERIC(15,6),
BDLIMITEISENCAO NUMERIC(15,6),
BDTIPORETENCAO INTEGER,
BDCODREC INTEGER,
BDCODIND INTEGER,
BDRETBCCALCULOIMP VARCHAR(5),
BDDESCREC VARCHAR(150),
BDTIPOIMPOSTO INTEGER,
BDCODSIS INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_PBM_NO_ANO (
    PREMP VARCHAR(32700),
    PRANO INTEGER)
RETURNS (
    BDCODEMP INTEGER)
AS
BEGIN SUSPEND; END
^


CREATE OR ALTER PROCEDURE SP_INCLUI_VERBAS_NOVAS AS
 BEGIN EXIT; END
^

create or alter procedure SP_INCLUI_VERBASEMP (
    PRVERBA integer,
    PRCLASSECOL integer = -1,
    PRTIPOCOL integer = -1,
    PRCOMFGTS DM_BOOLEAN = 'FALSE',
    PRINTERMITENTE DM_BOOLEAN = 'FALSE')
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_INSERE_ADVERTENCIA(PRDESCRICAO VARCHAR(1024),
PRTIPO INTEGER = 1)
 AS
 BEGIN EXIT; END
^

create or alter procedure SP_GETCODIGO_TELA (
    PRNOMETELA varchar(100),
    PRCAPTIONTELA varchar(150))
returns (
    BDCODTELASIS integer)
as
begin
  exit;
end 
^

CREATE OR ALTER PROCEDURE SP_INSERIR_LOG_ATUALIZACAO (
    PRSISTEMA INTEGER,
    PRACAO BLOB SUB_TYPE 1 SEGMENT SIZE 80)
AS
BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_INSERIR_LOG(
    BDCODEMP INTEGER,
    BDCODTER INTEGER,
    BDCODUSU INTEGER,
    BDCODIMP INTEGER,
    BDCODSIS INTEGER,
    BDCODCOL INTEGER,
    BDDATASISTEMA DATE,
    BDHORAINICIAL TIME,
    BDACAO BLOB SUB_TYPE 1 SEGMENT SIZE 80,
    BDACESSOID INTEGER,
    BDTIPOACAO INTEGER,
    PRNOME_MICRO VARCHAR(80),
    PRIP_MICRO VARCHAR(15),
    PRNOMETELA VARCHAR(100),
    PRCAPTIONTELA VARCHAR(150),
    BDCODRESP INTEGER,
    PRTABELA VARCHAR(50),
    BDTIPOIMPRESSAO SMALLINT,
    BDERRO_PROCESSO VARCHAR(5),
    BDDATACOMPETENCIA DATE,
    BDCODUSUINTRANET INTEGER = NULL,
    BDNOMUSUINTRANET VARCHAR(80) = NULL)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_INSERT_ATIVIDADE_BLUMENAU AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_COPIA_ATIVIDADES_MUNICIPAIS
 (
  CODCIDNOVA INTEGER,
  CODCIDCOPIAR INTEGER
  )
AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_INSERT_FERIADO(PRDATA DATE,
PRDESC VARCHAR(40),
PRCID INTEGER,
PRUF INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_INSERT_FOLHAAVULSA_ONLINE(PRCODTCA INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_INSERT_NOVA_VERBA_ONLINE(PRCLASSIFICACAO VARCHAR(100),
PRVERBA INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_LISTAR_PLANOS_ONLINE(PRCODEMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDCODPLANOONLINE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_MANUTENCAO_TCALCVESP(PRTIPOCALC INTEGER,
PRCLASSITEM VARCHAR(20),
PRDESCITEM VARCHAR(40),
PRFORMULAITEM VARCHAR(350),
PRCODVERBASE INTEGER,
PRCODVERESP INTEGER,
PRFORMULADABASE VARCHAR(5))
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_MODELOS_GERADOR_REL AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_FILTRA_PART_TROCA (
    PRCODTER INTEGER)
RETURNS (
    BDVALID DM_BOOLEAN)
AS
DECLARE VARIABLE WCODTER INTEGER;
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_FILTER_TER_TROCA_GLOBAL (
    PRCODTER INTEGER)
RETURNS (
    BDFOUND DM_BOOLEAN)
AS
DECLARE VARIABLE WCODTER INTEGER;
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_FILTER_DOC_TROCA_GLOBAL (
    PRNUMDOCINI NUMERIC(15,0))
RETURNS (
    BDFOUND DM_BOOLEAN)
AS
DECLARE VARIABLE WNUMDOCINI NUMERIC(15,0);
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_FILTRA_PART_TROCA_PLANO (
    PRCODPLATROCA INTEGER,
    PRCHAVE INTEGER,
    PRCODTER INTEGER)
RETURNS (
    BDVALID DM_BOOLEAN)
AS
DECLARE VARIABLE WCODTER INTEGER;
BEGIN
  SUSPEND;
END^

CREATE OR ALTER procedure SP_GET_PART_TROCA_CONSULTA (
    PRCODPLATROCA integer,
    PRCHAVE integer)
returns (
    BDCODTER integer,
    BDNOMETER varchar(100))
as
declare variable WCODTER integer;
declare variable WNOMETER varchar(100);
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_NOME_TERCEIRO(PRREF INTEGER,
PRTER INTEGER)
 RETURNS(BDCODTER INTEGER,
BDNOME VARCHAR(200))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_PBM(PREMP INTEGER,
PRREF INTEGER)
 RETURNS(BDEMP INTEGER,
BDREF INTEGER,
BDOK INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_PRAZO_EXPERIENCIA_SITUACAO(
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000),
    PRDIASPRAZO1COL integer,
    PRDIASPRAZO2COL integer,
    PRULTDIAMES date = null,
    PRCODSIT integer = 0,
    PRTABLETEMP integer = 0,
    PRRETORNO boolean = false)
 RETURNS(
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDDATAFIMPRAZO1COL DATE,
    BDDATAFIMPRAZO2COL DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_REL_CONSULTA_CONFIGURAVEL2(
    PRNAOIMPRIMEZERADO varchar(5) = '',
    PRDECLARACAO varchar(5) = '') 
RETURNS(BDCODMATRIZ INTEGER,
BDCODEMP INTEGER,
BDCODPLANO INTEGER,
BDCODQUADRO INTEGER,
BDREF INTEGER,
BDMESEXTENSO VARCHAR(20),
BDCOL01 NUMERIC(15,2),
BDCOL02 NUMERIC(15,2),
BDCOL03 NUMERIC(15,2),
BDCOL04 NUMERIC(15,2),
BDCOL05 NUMERIC(15,2),
BDCOL06 NUMERIC(15,2),
BDCOL07 NUMERIC(15,2),
BDCOL08 NUMERIC(15,2),
BDLINHA INTEGER,
BDTITULOS VARCHAR(640),
BDMEDIA01 numeric(15,2),
BDMEDIA02 numeric(15,2),
BDMEDIA03 numeric(15,2),
BDMEDIA04 numeric(15,2),
BDMEDIA05 numeric(15,2),
BDMEDIA06 numeric(15,2),
BDMEDIA07 numeric(15,2),
BDMEDIA08 numeric(15,2))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_REL_CONSULTA_SIMULADOR_TRIB (
    PRTOTALTRIMESTRE DM_BOOLEAN = false /* COLLATE WIN1252 - default */ ,
    PRNAOIMPRIMEZERADO DM_BOOLEAN = false /* COLLATE WIN1252 - default */ )
returns (
    BDCODMATRIZ integer,
    BDCODEMP integer,
    BDCODPLANO integer,
    BDCODQUADRO integer,
    BDREF numeric(15,2),
    BDMESEXTENSO varchar(20),
    BDCOL01 numeric(15,2),
    BDCOL02 numeric(15,2),
    BDCOL03 numeric(15,2),
    BDCOL04 numeric(15,2),
    BDCOL05 numeric(15,2),
    BDCOL06 numeric(15,2),
    BDCOL07 numeric(15,2),
    BDCOL08 numeric(15,2),
    BDCOL09 numeric(15,2),
    BDCOL10 numeric(15,2),
    BDCOL11 numeric(15,2),
    BDCOL12 numeric(15,2),
    BDCOL13 numeric(15,2),
    BDCOL14 numeric(15,2),
    BDCOL15 numeric(15,2),
    BDCOL16 numeric(15,2),
    BDCOL17 numeric(15,2),
    BDCOL18 numeric(15,2),
    BDCOL19 numeric(15,2),
    BDCOL20 numeric(15,2),
    BDCOL21 numeric(15,2),
    BDCOL22 numeric(15,2),
    BDCOL23 numeric(15,2),
    BDCOL24 numeric(15,2),
    BDCOL25 numeric(15,2),
    BDCOL26 numeric(15,2),
    BDCOL27 numeric(15,2),
    BDCOL28 numeric(15,2),
    BDCOL29 numeric(15,2),
    BDCOL30 numeric(15,2),
    BDCOL31 numeric(15,2),
    BDCOL32 numeric(15,2),
    BDCOL33 numeric(15,2),
    BDCOL34 numeric(15,2),
    BDCOL35 numeric(15,2),
    BDCOL36 numeric(15,2),
    BDCOL37 numeric(15,2),
    BDCOL38 numeric(15,2),
    BDCOL39 numeric(15,2),
    BDCOL40 numeric(15,2),
    BDCOL41 numeric(15,2),
    BDCOL42 numeric(15,2),
    BDCOL43 numeric(15,2),
    BDCOL44 numeric(15,2),
    BDCOL45 numeric(15,2),
    BDCOL46 numeric(15,2),
    BDCOL47 numeric(15,2),
    BDCOL48 numeric(15,2),
    BDCOL49 numeric(15,2),
    BDCOL50 numeric(15,2),
    BDLINHA integer,
    BDTITULOS varchar(1500),
    BDTOTTRI DM_BOOLEAN,
    BDISTOT DM_BOOLEAN)
as
declare variable WVALOR numeric(15,2);
declare variable WCOLUNAATUAL integer;
declare variable WMES char(2);
declare variable WANO char(4);
declare variable WINDICE integer;
declare variable WNUMCOLUNAS integer;
declare variable WNUMLINHAS integer;
declare variable WLINHAATUAL integer;
declare variable WDESCRICAO varchar(80);
declare variable WORDEM integer;
declare variable WCODEMP integer;
declare variable WVALORACUMULADO numeric(15,2);
declare variable WVALTRIM01 numeric(15,2);
declare variable WVALTRIM02 numeric(15,2);
declare variable WVALTRIM03 numeric(15,2);
declare variable WVALTRIM04 numeric(15,2);
declare variable WVALTRIM05 numeric(15,2);
declare variable WVALTRIM06 numeric(15,2);
declare variable WVALTRIM07 numeric(15,2);
declare variable WVALTRIM08 numeric(15,2);
declare variable WVALTRIM09 numeric(15,2);
declare variable WVALTRIM10 numeric(15,2);
declare variable WVALTRIM11 numeric(15,2);
declare variable WVALTRIM12 numeric(15,2);
declare variable WVALTRIM13 numeric(15,2);
declare variable WVALTRIM14 numeric(15,2);
declare variable WVALTRIM15 numeric(15,2);
declare variable WVALTRIM16 numeric(15,2);
declare variable WVALTRIM17 numeric(15,2);
declare variable WVALTRIM18 numeric(15,2);
declare variable WVALTRIM19 numeric(15,2);
declare variable WVALTRIM20 numeric(15,2);
declare variable WVALTRIM21 numeric(15,2);
declare variable WVALTRIM22 numeric(15,2);
declare variable WVALTRIM23 numeric(15,2);
declare variable WVALTRIM24 numeric(15,2);
declare variable WVALTRIM25 numeric(15,2);
declare variable WVALTRIM26 numeric(15,2);
declare variable WVALTRIM27 numeric(15,2);
declare variable WVALTRIM28 numeric(15,2);
declare variable WVALTRIM29 numeric(15,2);
declare variable WVALTRIM30 numeric(15,2);
declare variable WVALTRIM31 numeric(15,2);
declare variable WVALTRIM32 numeric(15,2);
declare variable WVALTRIM33 numeric(15,2);
declare variable WVALTRIM34 numeric(15,2);
declare variable WVALTRIM35 numeric(15,2);
declare variable WVALTRIM36 numeric(15,2);
declare variable WVALTRIM37 numeric(15,2);
declare variable WVALTRIM38 numeric(15,2);
declare variable WVALTRIM39 numeric(15,2);
declare variable WVALTRIM40 numeric(15,2);
declare variable WVALTRIM41 numeric(15,2);
declare variable WVALTRIM42 numeric(15,2);
declare variable WVALTRIM43 numeric(15,2);
declare variable WVALTRIM44 numeric(15,2);
declare variable WVALTRIM45 numeric(15,2);
declare variable WVALTRIM46 numeric(15,2);
declare variable WVALTRIM47 numeric(15,2);
declare variable WVALTRIM48 numeric(15,2);
declare variable WVALTRIM49 numeric(15,2);
declare variable WVALTRIM50 numeric(15,2);
declare variable WCOUNTMESESTRI integer;
declare variable WTEMP integer;
declare variable WEMPANT integer;
declare variable WPLANOANT integer;
declare variable WQUADANT integer;
declare variable WPRIMEIRAVEZ DM_BOOLEAN;
declare variable WISSN DM_BOOLEAN;
begin
 SUSPEND;
END ^

CREATE OR ALTER PROCEDURE SP_REL_RESUMO_IMPOSTOS (
PRCODEMP varchar(10000),
PRCODIMP varchar(10000),
PRCODSIS varchar(10000),
PRREFINI integer,
PRREFFIN integer,
PRREFATUAL integer,
PRDTVCTOINI date,
PRDTVCTOFIM date)
returns (
BDCODEMP integer,
BDCHAVEDARF integer,
BDCODIMP integer,
BDDESCIMP varchar(200),
BDCODREC integer,
BDCODSIS integer,
BDCODPERIODO integer,
BDDESCPERIODO varchar(40),
BDORDEM integer,
BDREFERENCIA integer,
BDMESEXTENSO varchar(20),
BDQUOTA integer,
BDCODCOL integer,
BDCODEMPCOL integer,
BDCODCENTRO integer,
BDCODTPCC integer,
BDPERIODO date,
BDNUMREFDOC varchar(20),
BDDATAVCTO date,
BDVALOR numeric(15,6),
BDMULTA numeric(15,6),
BDJUROS numeric(15,6),
BDTOTAL numeric(15,6),
BDOBS blob sub_type 0 segment size 80,
BDORDEMCOMPL integer,
BDBASEIMP numeric(15,6),
BDALIQIMP numeric(15,6),
BDVLRIMPORIGINAL numeric(15,6),
BDVLRACUMULO numeric(15,6),
BDVLRMULTAJUROS numeric(15,6),
BDVLROUTENTIDADE numeric(15,6),
BDTIPOIMPOSTO integer,
BDCOMPENSACAO numeric(15,6),
BDVLRACUOUTENT numeric(15,6),
BDREFPAG integer,
BDDTPGTO date,
BDDOCARRECADACAO integer)
 AS
 BEGIN SUSPEND; END
^

/* Restore proc. body: SP_RESTAURA_VERBA_SE_PADRAO */
create or alter procedure SP_RESTAURA_VERBA_SE_PADRAO (
    PRCODEVER integer,
    PRCRIARSEEXISTIR varchar(5) = false)
as
begin EXIT; end^


create or alter procedure SP_RESTAURA_VERBA_PADRAO (
    PRCODVER integer,
    PRCODVERBANOVO integer = 0)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_RESTAURA_VERBA_PADRAO_CLASS(PRCLAVER VARCHAR(20) = NULL)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_DIFERENCAS_VSUC_TLAN(PRCODEMP VARCHAR(2048),
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRTRANSACAO INTEGER,
PRSEMPRE integer = 0)
 RETURNS(PREMPRESA INTEGER,
PRDATA DATE,
PRDEBITO NUMERIC(15,6),
PRCREDITO NUMERIC(15,6),
PRDIFERENCA NUMERIC(15,6),
PRTOTAL NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_EMPRESA_FILIAIS(PRCODEMP INTEGER,
PRREFEMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_SALDO_EMP(PRCODEMP INTEGER,
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
PRCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRPARTICIPANTE INTEGER = 0)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_SALDO_EMP_X(
    PRCODEMP integer,
    PRCONTA integer,
    PRDATAINI date,
    PRDATAFIM date,
    PRINDICE integer,
    PRIGNORAZERAMENTO smallint,
    PRCC varchar(8192),
    PRRELCTA integer,
    PRREFEMP integer,
    PRCONCILIADOS integer,
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRPARTICIPANTE integer = 0,
    PRPARTICIPANTEFINAL integer = 0,
    PREMPREENDIMENTO integer = 0,
    PRUNIDIMOB integer = 0,
    PRAPENASCONTABILIZACAOSEL integer = 0,
    PRCODEMPMATRIZ integer = 0,
    PRCONTABILIZACAOLALUR integer = 0,
    prlistapart varchar(10000) = '',
    PRFILTIPOLAN varchar(3200) = '',
    PRCODPLAHISTLALUR integer = 0)
RETURNS (
    SALDO_ANT_DEB NUMERIC(15,2),
    SALDO_ANT_CRE NUMERIC(15,2),
    SALDO_DEB NUMERIC(15,2),
    SALDO_CRE NUMERIC(15,2),
    MOVIMENTO NUMERIC(15,2),
    SALDO_ATUAL NUMERIC(15,2),
    SALDO_ANTERIOR NUMERIC(15,2),
    CODEMP INTEGER) 
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_CONTAS_EMPRESA (
    BDCODEMP INTEGER,
    BDCODPLANO INTEGER,
    BDCLASSIFICACAO VARCHAR(40))
RETURNS (
    BDCODPLAPADRAO INTEGER,
    BDCODTPLA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDTIPCTA INTEGER,
    BDCTAOBRIG DM_BOOLEAN,
    BDCTAEMP INTEGER)
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CONTAS_LANCADAS (
    BDCODEMP INTEGER,
    BDCODPLANO INTEGER,
    BDREFERENCIA INTEGER,
    BDFILIAIS INTEGER = 0)
RETURNS (
    BDCONTA INTEGER)
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_RETORNA_CONTAS_ONLINE (
    BDCODPLAONLINE INTEGER,
    BDCODPLAPADRAO INTEGER)
RETURNS (
    BDCONTA INTEGER)
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_SALDO_MATRIZFILIAL(PRCODEMP INTEGER,
PRMATRIZFILIAIS VARCHAR(2048),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
BDCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
MOVIMENTO NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_SALDO_MATRIZFILIAL_X(PRCODEMP INTEGER,
PRMATRIZFILIAIS VARCHAR(2048),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
BDCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRINTCONTABILLALUR INTEGER = 0,
PRCODTERCEIRO INTEGER = 0,
PRCONTABILIZACAOLALUR integer = 0,
PRCODTPHISTLALUR integer = 0)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
MOVIMENTO NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER,
CHAVELAN INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TEMPRESAIMPOSTO_REF(PRCODEMP VARCHAR(20000),
PRREFERENCIA INTEGER,
PRQUANTIDADE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDREFFIMIMP INTEGER,
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(100),
BDDATACRIACAO DATE,
BDDATAEXTINTO DATE,
BDCOMPETENCIA INTEGER,
BDDOCARRECADACAO INTEGER,
BDPERAPURACAO INTEGER,
BDDIAVENCTO INTEGER,
BDANTECIPA VARCHAR(5),
BDMESVENCTO INTEGER,
BDJUROSDIA INTEGER,
BDVLRJUROS NUMERIC(15,6),
BDJUROSDIAMES INTEGER,
BDMULTADIA INTEGER,
BDVLRMULTA NUMERIC(15,6),
BDMULTADIAMES INTEGER,
BDVLRMAXMULTA NUMERIC(15,6),
BDALIQIMPOSTO NUMERIC(15,6),
BDLIMITEISENCAO NUMERIC(15,6),
BDTIPORETENCAO INTEGER,
BDCODREC INTEGER,
BDCODIND INTEGER,
BDRETBCCALCULOIMP VARCHAR(5),
BDDESCREC VARCHAR(150),
BDTIPOIMPOSTO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TERCEIRO(PRCODTER INTEGER)
 RETURNS(BDCODTER INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCGCTER VARCHAR(18),
BDREFEMP INTEGER,
BDAPELIDOTER VARCHAR(20),
BDNOMETER VARCHAR(100),
BDLOGRTER VARCHAR(15),
BDENDTER DM_BDENDERECO,
BDNUMTER DM_NUMEND,
BDCOMPTER DM_BDCOMPENDERECO,
BDCEPTER VARCHAR(9),
BDBAITER DM_BDBAIRRO,
BDDDDTER VARCHAR(3),
BDFONETER DM_BDTELEFONE,
BDFAXTER DM_BDTELEFONE,
BDEMAILTER DM_BDEMAIL,
BDIETER VARCHAR(20),
BDDATACADTER DATE,
BDIMTER VARCHAR(16),
BDPRURALTER VARCHAR(5),
BDENQSIMPLESFEDTER INTEGER,
BDINSCSUFRAMATER VARCHAR(10),
BDCODGPS INTEGER,
BDCODCID INTEGER,
BDCODPAIS INTEGER,
BDDESCPAIS VARCHAR(60),
BDDDDFAXTER VARCHAR(3))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TREEVIEW_CONF_DEPARA_ONLINE(PRPLANO_DE INTEGER,
PRPLANO_PARA INTEGER,
PRCODINT INTEGER,
PRPLANOCONTASANT INTEGER,
PRPLANOCONTASATU INTEGER,
PRPLANOHISTANT INTEGER,
PRPLANOHISTATU INTEGER,
PRCLASSIFICACAO VARCHAR(100),
PRLENGTH INTEGER,
PRREF INTEGER,
PRCHAVE INTEGER,
PRAPENASNIVEL INTEGER,
PRFILTERCLASSIFICACAO DM_MAXVARCHAR = '',
PRCONFAUT INTEGER = 0)
 RETURNS(BDFORMULA VARCHAR(80),
BDFORMULAITEM VARCHAR(80),
BDCONFIGTIT DM_BOOLEAN,
BDCLASSIFICACAO VARCHAR(100),
BDDESCRICAO VARCHAR(500),
BDAPECTADV VARCHAR(20),
BDAPECTACV VARCHAR(20),
BDAPECTADO VARCHAR(20),
BDAPECTACO VARCHAR(20),
BDDESCONTADV VARCHAR(100),
BDDESCONTACV VARCHAR(100),
BDDESCONTADO VARCHAR(100),
BDDESCONTACO VARCHAR(100),
BDCODHISTPROV INTEGER,
BDCODHISTPGTO INTEGER,
BDCODTIPOCONTA INTEGER,
BDCODNAT INTEGER,
BDCODVER INTEGER,
BDDESCREDVER VARCHAR(20),
BDAPELIDOTER VARCHAR(20),
BDNOMENAT VARCHAR(335),
BDAPEHISTPROV VARCHAR(20),
BDAPEHISTPGTO VARCHAR(20),
BDCONTADEBPROV INTEGER,
BDCONTACREDPROV INTEGER,
BDCONTADEBPGTO INTEGER,
BDCONTACREDPGTO INTEGER,
BDCHAVE INTEGER,
BDCHAVEVINC INTEGER,
BDCODPLANOONLINE INTEGER,
BDDESCIMP VARCHAR(100),
BDDESCOREC VARCHAR(100),
BDCODOREC INTEGER,
BDCODIMP INTEGER,
BDCODTCA INTEGER,
BDCODGRUPOCLA INTEGER,
BDDESCGRUPOCLA VARCHAR(200),
BDTIPONAT INTEGER,
BDCLASSVER VARCHAR(20),
BDTIPOVER INTEGER,
BDCODITEMONLINE INTEGER,
BDAPECOMHISTPROV VARCHAR(20),
BDAPECOMHISTPGTO VARCHAR(20),
BDCODCOMPHISTPROV INTEGER,
BDCODCOMPHISTPGTO INTEGER,
BDCOMHISTPROV VARCHAR(1000),
BDCOMHISTPGTO VARCHAR(1000),
BDCONFIGPROV DM_BOOLEAN,
BDCONFIGDEBPROV DM_BOOLEAN,
BDCONFIGCREDPROV DM_BOOLEAN,
BDCONFIGPAG DM_BOOLEAN,
BDCONFIGDEBPAG DM_BOOLEAN,
BDCONFIGCREDPAG DM_BOOLEAN,
BDCONFIGHISTPROV DM_BOOLEAN,
BDCONFIGHISTPAG DM_BOOLEAN,
BDNAOCONTAB DM_BOOLEAN,
BDCODREC INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(42),
BDCODTPHIST INTEGER,
BDAPELIDOHIST VARCHAR(20),
BDCHAVE_PARA INTEGER,
BDCODMASTER INTEGER,
BDPODEEDITAR DM_BOOLEAN,
BDCLASSIFICACAOORI VARCHAR(100),
BDCODOBRSER INTEGER,
BDCHAVECTABAN INTEGER,
BDCODCLI INTEGER,
BDCODDESP INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TREEVIEW_CONS_ANUAL_CONF(PRSISTEMA INTEGER,
PRCODEMP VARCHAR(10000),
PRREF INTEGER,
PRCODQUADRO INTEGER,
PRDETALHAQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDREF INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDORDEM INTEGER,
BDDESCRICAO VARCHAR(80),
BDVALOR NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDJAN NUMERIC(15,6),
BDFEV NUMERIC(15,6),
BDMAR NUMERIC(15,6),
BDABR NUMERIC(15,6),
BDMAI NUMERIC(15,6),
BDJUN NUMERIC(15,6),
BDJUL NUMERIC(15,6),
BDAGO NUMERIC(15,6),
BDSET NUMERIC(15,6),
BDOUT NUMERIC(15,6),
BDNOV NUMERIC(15,6),
BDDEZ NUMERIC(15,6),
BDANOSWS VARCHAR(4))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TREEVIEW_CONS_CONF_ONLINE (
    PRPLANO INTEGER,
    PRCLASSIFICACAO VARCHAR(100),
    PRLENGTH INTEGER,
    PRREF INTEGER,
    PRCHAVE INTEGER,
    PRAPENASNIVEL INTEGER,
    PRFILTERCLASSIFICACAO DM_MAXVARCHAR = '',
    PRFILTRERTREEVIEW VARCHAR(200) = '',
    PRORDENACAO INTEGER = 0,
    PRCODIGO_TREEVIEW INTEGER = -1,
    PRFORCEDESCRICAO SMALLINT = 0,
    PRCONTAPREP integer = 0)
RETURNS (
    BDFORMULA VARCHAR(80),
    BDFORMULAITEM VARCHAR(80),
    BDCONFIGTIT VARCHAR(5),
    BDCLASSIFICACAO VARCHAR(100),
    BDDESCRICAO VARCHAR(500),
    BDAPECTADV VARCHAR(20),
    BDAPECTACV VARCHAR(20),
    BDAPECTADO VARCHAR(20),
    BDAPECTACO VARCHAR(20),
    BDDESCONTADV VARCHAR(100),
    BDDESCONTACV VARCHAR(100),
    BDDESCONTADO VARCHAR(100),
    BDDESCONTACO VARCHAR(100),
    BDCODHISTPROV INTEGER,
    BDCODHISTPGTO INTEGER,
    BDCODTIPOCONTA INTEGER,
    BDCODNAT INTEGER,
    BDCODVER INTEGER,
    BDDESCREDVER VARCHAR(20),
    BDAPELIDOTER VARCHAR(20),
    BDNOMENAT VARCHAR(335),
    BDAPEHISTPROV VARCHAR(20),
    BDAPEHISTPGTO VARCHAR(20),
    BDCONTADEBPROV INTEGER,
    BDCONTACREDPROV INTEGER,
    BDCONTADEBPGTO INTEGER,
    BDCONTACREDPGTO INTEGER,
    BDCHAVE INTEGER,
    BDCHAVEVINC INTEGER,
    BDCODPLANOONLINE INTEGER,
    BDDESCIMP VARCHAR(100),
    BDDESCOREC VARCHAR(100),
    BDCODOREC INTEGER,
    BDCODIMP INTEGER,
    BDCODTCA INTEGER,
    BDCODGRUPOCLA INTEGER,
    BDDESCGRUPOCLA VARCHAR(200),
    BDTIPONAT INTEGER,
    BDCLASSVER VARCHAR(20),
    BDTIPOVER INTEGER,
    BDCODITEMONLINE INTEGER,
    BDAPECOMHISTPROV VARCHAR(20),
    BDAPECOMHISTPGTO VARCHAR(20),
    BDCODCOMPHISTPROV INTEGER,
    BDCODCOMPHISTPGTO INTEGER,
    BDCOMHISTPROV VARCHAR(1000),
    BDCOMHISTPGTO VARCHAR(1000),
    BDCONFIGPROV VARCHAR(5),
    BDCONFIGDEBPROV VARCHAR(5),
    BDCONFIGCREDPROV VARCHAR(5),
    BDCONFIGPAG VARCHAR(5),
    BDCONFIGDEBPAG VARCHAR(5),
    BDCONFIGCREDPAG VARCHAR(5),
    BDCONFIGHISTPROV VARCHAR(5),
    BDCONFIGHISTPAG VARCHAR(5),
    BDNAOCONTAB VARCHAR(5),
    BDCODREC INTEGER,
    BDCONTABILIZA DM_BOOLEAN,
    BDATIVA DM_BOOLEAN,
    BDCODOBRSER INTEGER,
    BDTIPOSER INTEGER,
    BDSERDESCONTO DM_BOOLEAN,
    BDCHAVECTABAN INTEGER,
    BDCODCLI INTEGER,
    BDCODPLAPADRAO integer,
    BDCODDESP integer,
    BDDESCDESP varchar(100),
    BDTIPODESP integer,
    BDDESPDESCONTO varchar(5),
    bdrefcta INTEGER
)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TREEVIEW_PREP_CONTA (
  PRPLANOONLINE integer,
  PRREF integer,
  PRCONTA integer)
RETURNS (
  BDCLASSIFICACAO varchar(100),
  BDCONTADEBPROV integer,
  BDCONTACREDPROV integer,
  BDDESCRICAO varchar(100),
  BDCODVER integer,
  BDCHAVE integer  
)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TREEVIEW_CONS_FORM_PAD_EF(PRPLANO INTEGER,
PRCLASSQUADRO VARCHAR(10),
PRGRUPO INTEGER,
PRTPIMP VARCHAR(10))
 RETURNS(BDCODPLANO INTEGER,
BDDESCPLANO VARCHAR(150),
BDNUMITEM INTEGER,
BDDESCFORM VARCHAR(150),
BDFORMULA VARCHAR(10000),
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(150),
BDCLASSIFICACAO VARCHAR(10),
BDCODITEMONLINE INTEGER,
BDDESCCODITEMONLINE VARCHAR(200))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TREEVIEW_CONS_GIA_FORMULA(PRPLANO INTEGER,
PRCLASSQUADRO VARCHAR(10),
PRGRUPO INTEGER,
PRUF VARCHAR(2))
 RETURNS(BDCODPLANO INTEGER,
BDDESCPLANO VARCHAR(100),
BDNUMITEM INTEGER,
BDDESCFORM VARCHAR(100),
BDFORMULA VARCHAR(10000),
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(100),
BDCLASSIFICACAO VARCHAR(11),
BDCODITEMONLINE INTEGER,
BDDESCCODITEMONLINE VARCHAR(300))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TREEVIEW_CONS_IMP_EMITIDOS(PRONLINE VARCHAR(10000),
PRCODEMP VARCHAR(10000),
PRCODIMP VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PRGRUPO INTEGER,
PRDTVCTOINI DATE,
PRDTVCTOFIM DATE,
PRPERIODO INTEGER,
PRFILTRO INTEGER,
PRSICALCIC varchar(5))
 RETURNS(BDCODEMP INTEGER,
BDCHAVEDARF INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(200),
BDCODPERIODO INTEGER,
BDORDEM INTEGER,
BDREFERENCIA INTEGER,
BDQUOTA INTEGER,
BDCODTPCC INTEGER,
BDDATAVCTO DATE,
BDVALOR NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDJUROS NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDOBS BLOB,
BDORDEMCOMPL INTEGER,
BDBASEIMP NUMERIC(15,6),
BDALIQIMP NUMERIC(15,6),
BDVLRIMPORIGINAL NUMERIC(15,6),
BDVLRMULTAJUROS NUMERIC(15,6),
BDVLROUTENTIDADE NUMERIC(15,6),
BDDTPGTO DATE,
BDLIMITEISENCAO NUMERIC(15,6),
BDDOCARRECADACAO INTEGER,
BDFORMREL VARCHAR(1000),
BDCODREC INTEGER,
BDVLRRETENCAO NUMERIC(15,2),
BDDESCTIPOCALC VARCHAR(25),
BDFLAG VARCHAR(5),
BDVLRACUMULO NUMERIC(15,6),
BDCNPJDARF varchar(18),
BDCODEMPSCP integer,
BDCOMPENSACAODCOMP DM_NUMERIC_15_2)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_UPDATE_VERBA_ONLINE(PRCLAANT VARCHAR(1000),
PRCLANOVA VARCHAR(1000),
PRCODVER INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_VAL_HE_RAIS_FF(PREMP INTEGER,
PRCOL INTEGER,
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDHE NUMERIC(15,6),
BDCODVER INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VAL_RAIS_FF(PREMP INTEGER = 0,
PRCOL INTEGER = 0,
PRANO INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDAVPREV NUMERIC(15,6),
BDFERIND NUMERIC(15,6),
BDGRATIF NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDSINDICAL NUMERIC(15,6),
BDASSISTENCIAL NUMERIC(15,6),
BDCONFEDERATIVA NUMERIC(15,6),
BDBASEFN NUMERIC(15,6),
BDBASEA13 NUMERIC(15,6),
BDBASE13 NUMERIC(15,6),
BDBASEC13 NUMERIC(15,6),
BDORIGEM INTEGER,
BDMENSALIDADE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_ENT_FORMULAS_DAPI(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDCODNAT INTEGER,
BDCODOPDAPI INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDBASEICMS NUMERIC(15,2),
BDVLRICMS NUMERIC(15,2),
BDISENTASICMS NUMERIC(15,2),
BDVLRST NUMERIC(15,2),
BDIMPAPCREDDAPI NUMERIC(15,2),
BDISENTASDAPI NUMERIC(15,2),
BDNTRIBDAPI NUMERIC(15,2),
BDPARBCCREDDAPI NUMERIC(15,2),
BDDIFERIDASTDAPI NUMERIC(15,2),
BDSUSPENSASDAPI NUMERIC(15,2),
BDSTDAPI NUMERIC(15,2),
BDOUTRASDAPI NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VEF_DAS_TOTALIZADOR_UF (
    PREMP varchar(3000),
    PRDATAINI varchar(10),
    PRDATAFIM varchar(10),
    PRREF integer,
    PRREGIMECAIXA varchar(5))
returns (
    BDCODEMP integer,
    BDSIGLAUF varchar(2),
    BDNOMCID varchar(40),
    BDCODBASESN integer,
    BDVLRBASE numeric(18,2),
    BDCODFED integer,
    BDCODTIPOIMPPIS integer,
    BDCODTIPOIMPCOFINS integer,
    BDCODTIPOIMPCSLL integer,
    BDCODTIPOIMPICMS integer,
    BDCODTIPOIMPINSSCPP integer,
    BDCODTIPOIMPIRPJ integer,
    BDCODTIPOIMPIPI integer,
    BDCODTIPOIMPISS integer)
as
BEGIN SUSPEND; END
^

CREATE OR ALTER procedure SP_VEF_EXPREG30_GIASP (
    PRCODEMP varchar(10000),
    PRREFERENCIAINICIAL integer,
    PRREFERENCIAFINAL integer)
returns (
    BDCODEMP integer,
    BDREFERENCIA integer,
    BDCODEST integer,
    BDCODDIPAM varchar(3),
    BDVALOR numeric(18,6),
    BDCODCID integer,
    BDDIPAMB varchar(5))
as
begin
  SUSPEND;
end
^

CREATE OR ALTER PROCEDURE SP_VEF_FILTRO_NOTAS_NAO_LANCADA(PRCODEMP INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRNUMDOCINI INTEGER,
PRNUMDOCFIN INTEGER,
PRESPECIE VARCHAR(5),
PRSERIE VARCHAR(6),
PRSERVICO_SAIDA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNUMDOC INTEGER,
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_REL_APURACAO_GIAMG(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDREFERENCIA INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDNUMITEM INTEGER,
BDAREACONS VARCHAR(10),
BDESCCENTRAL VARCHAR(5),
BDTITULO VARCHAR(60),
BDREGISTRO VARCHAR(60),
BDSUBTITULO VARCHAR(80))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VEF_REL_RETENCOES (
    PRCODEMP varchar(10000),
    PRDATAINICIAL date,
    PRDATAFINAL date,
    PRTIPOMOV integer,
    PRCODTER integer,
    PRDETALHADO integer,
    PRTIPOLANSERV integer,
    PRTIPOAPURACAORETIR varchar(50),
    PRSOMAMATRIZFILIAL integer,
    PRVERORGAOPUBLICO varchar(5),
    PRCAMPODATA varchar(200))
returns (
    BDCODEMP integer,
    BDREF integer,
    BDMESEXTENSO varchar(20),
    BDCODTER integer,
    BDNOMETER varchar(100),
    BDCGCTER varchar(18),
    BDENDTER varchar(60),
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDVLRCONTAB numeric(15,2),
    BDVLRPIS numeric(15,2),
    BDVLRCOFINS numeric(15,2),
    BDVLRCSOCIAL numeric(15,2),
    BDVLRIR numeric(15,2),
    BDVLRINSS numeric(15,2),
    BDVLRISS numeric(15,2),
    BDVLRIRSER numeric(15,2),
    BDCONDPGTO integer)
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_RETORNA_SALDO_DIME(PRCODEMP VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRREFEMP INTEGER,
PRANO INTEGER,
PRCONTABILIZACAO INTEGER)
 RETURNS(BDCODMATRIZ INTEGER,
BDCODEMP INTEGER,
BDQUADRO VARCHAR(5),
BDCODEXP INTEGER,
BDSALDO NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_ANUAL_CON2(PRCODEMP VARCHAR(10000),
PRREF INTEGER,
PRCODQUADRO INTEGER,
PRDETALHAQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDREF INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDORDEM INTEGER,
BDDESCRICAO VARCHAR(80),
BDVALOR NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDJAN NUMERIC(15,6),
BDFEV NUMERIC(15,6),
BDMAR NUMERIC(15,6),
BDABR NUMERIC(15,6),
BDMAI NUMERIC(15,6),
BDJUN NUMERIC(15,6),
BDJUL NUMERIC(15,6),
BDAGO NUMERIC(15,6),
BDSET NUMERIC(15,6),
BDOUT NUMERIC(15,6),
BDNOV NUMERIC(15,6),
BDDEZ NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_BLOCOP(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO VARCHAR(1000),
PRCLASSIFICACAO VARCHAR(10),
PRGERAL INTEGER,
PREMPFIL INTEGER,
PRCODIGOAJUSTE VARCHAR(8))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP VARCHAR(100),
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM DM_BDNOMEMP,
BDVALOR NUMERIC(15,2),
BDANOMESINICIAL INTEGER,
BDANOMESFINAL INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDCODEMPFILIAL INTEGER,
BDORDENATVPREV INTEGER,
BDCODIGOATVPREV VARCHAR(8),
BDDESCPREV VARCHAR(550),
BDNOMEMPFIL VARCHAR(100),
BDCODTIPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_CALCATIVO(PRCODEMP VARCHAR(10000),
PRCODBEM VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PRGRUPO VARCHAR(30))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODBEM INTEGER,
BDNOMBEM VARCHAR(200),
BDREFERENCIA INTEGER,
BDFATOR NUMERIC(15,6),
BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_DACON(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO VARCHAR(1000),
PRCODQUADRO INTEGER,
PRGERAL INTEGER,
PRTIPO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(160),
BDDESCFORM VARCHAR(160),
BDVALOR NUMERIC(18,6),
BDVALOR2 NUMERIC(18,6),
BDVALOR3 NUMERIC(18,6),
BDNUMITEM INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDCODREC INTEGER,
BDTIPOCREDITO INTEGER,
BDTIPOCONFDACON INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_DIME(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCODQUADRO INTEGER,
PRCODQUADROPRINC INTEGER,
PRGERAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCODQUADROPRINC INTEGER,
BDCLASSIFICACAO VARCHAR(5),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,6),
BDCODTIPO INTEGER,
BDCODNAT INTEGER,
BDDATAREC DATE,
BDCLAVENDIMEGERQ12 INTEGER,
BDCODRECDIMEGERQ12 INTEGER,
BDORIGEMDIMEGERQ46 INTEGER,
BDNUMITEM INTEGER,
BDANOMESINICIAL INTEGER,
BDANOMESFINAL INTEGER,
BDNUMACORDOQ12 VARCHAR(15))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIAES(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER,
PRTIPOAPU INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDTIPO INTEGER,
BDNUMITEM INTEGER,
BDTIPOAPU INTEGER,
BDCODNAT INTEGER,
BDAUXCFOP INTEGER,
BDORDEMTTNAT INTEGER,
BDCLASSNATGRUP VARCHAR(20),
BDDESCTTNAT VARCHAR(20),
BDTITULOGRUPO VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIAMG(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDCODNAT INTEGER,
BDTIPO INTEGER,
BDNUMITEMORDEM varchar(5),
BDNUMITEM varchar(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIAPR(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER,
PRCODNAT INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDCODNAT INTEGER,
BDTIPO INTEGER,
BDNUMITEM INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIARJ (
    PRCODEMP VARCHAR(10000),
    PRANOMESINICIAL INTEGER,
    PRANOMESFINAL INTEGER,
    PRCODPERIODO INTEGER,
    PRCLASSIFICACAO VARCHAR(11),
    PRGERAL INTEGER,
    PRCODQUADRO INTEGER,
    PRCODNAT INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCONF INTEGER,
    BDREFERENCIA INTEGER,
    BDCODPERIODO INTEGER,
    BDNUMCAMPO INTEGER,
    BDCODQUADRO INTEGER,
    BDCLASSIFICACAO VARCHAR(10),
    BDDESCQUADRO VARCHAR(80),
    BDDESCFORM VARCHAR(150),
    BDVALOR NUMERIC(15,2),
    BDCODTIPO INTEGER,
    BDCODNAT INTEGER,
    BDTIPO INTEGER,
    BDNUMITEM INTEGER)
AS
  BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIATO (
    PRCODEMP VARCHAR(10000),
    PRANOMESINICIAL INTEGER,
    PRANOMESFINAL INTEGER,
    PRCODPERIODO INTEGER,
    PRCLASSIFICACAO VARCHAR(11),
    PRGERAL INTEGER,
    PRCODQUADRO INTEGER,
    PRCODNAT INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCONF INTEGER,
    BDREFERENCIA INTEGER,
    BDCODPERIODO INTEGER,
    BDNUMCAMPO INTEGER,
    BDCODQUADRO INTEGER,
    BDCLASSIFICACAO VARCHAR(10),
    BDDESCQUADRO VARCHAR(80),
    BDDESCFORM VARCHAR(150),
    BDVALOR NUMERIC(15,2),
    BDCODTIPO INTEGER,
    BDCODNAT INTEGER,
    BDTIPO INTEGER,
    BDNUMITEM INTEGER)
AS
  BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIARO(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDTIPO INTEGER,
BDNUMITEM INTEGER,
BDCODNAT INTEGER,
BDORDEMTTNAT INTEGER,
BDTITULOGRUPO VARCHAR(80))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIASP(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(10),
PRGERAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(5),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,6),
BDCODTIPO INTEGER,
BDCODNAT INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_ICMSSPED(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO VARCHAR(1000),
PRCODQUADRO INTEGER,
PRGERAL INTEGER,
PRUF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(150),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(18,6),
BDNUMITEM INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2),
BDCODTIPOVALAGRE INTEGER,
BDDESCRICAO VARCHAR(150),
BDCODTIPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_IMPOSTOS(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO VARCHAR(1000),
PRCODQUADRO INTEGER,
PRGERAL INTEGER,
PRSIGLAIMPOSTO VARCHAR(10))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(60),
BDVALOR NUMERIC(15,8),
BDANOMESINICIAL INTEGER,
BDANOMESFINAL INTEGER,
BDCLASSIFICACAO VARCHAR(10))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_IPI(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODQUADRO INTEGER,
PRGERAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(60),
BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_IRLP(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODQUADRO INTEGER,
PRGERAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(60),
BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONSUF_GIASP(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRNATENTSAI INTEGER,
PRPREFIXONAT INTEGER,
PRSIGLAUF VARCHAR(2))
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDNUMCAMPO INTEGER,
BDSIGLAUF VARCHAR(2),
BDPREFIXONAT INTEGER,
BDDESCRICAO VARCHAR(100),
BDVALOR NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VERIFICATODASVERBASEMPPADRAO AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_VRH_BASE_MTE_TCONFRESC RETURNS(BDCHAVECONF INTEGER,
BDDESCRICAO DM_BDDESCCONFMTE,
BDCLASSIFICACAO DM_BDCLASSCONFMTE,
BDIMPZERADO VARCHAR(5),
BDINCSUBGRUPO VARCHAR(5),
BDFIXA VARCHAR(5),
BDCODCOMPHIST INTEGER,
BDCLASSCONF DM_BDCLASSCONFMTE,
BDPADRAO VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_CC_DATA(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRDATA DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDDATAENTRADA DATE,
BDORDEM INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_DEC_REND_7_2(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODDPN INTEGER,
BDREF INTEGER,
BDNOME VARCHAR(70),
BDCPF VARCHAR(14),
BDCNPJ VARCHAR(18),
BDRAZAOSOCIAL VARCHAR(80),
BDVALOR NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_EMP_MULTVINC_PGTO(PREMPRESA VARCHAR(32000),
PRCOL VARCHAR(32000),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFCOL INTEGER,
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_FECHAMENTO(PREMPRESAS VARCHAR(32000),
PRREF INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDFECHAMENTO INTEGER,
BDDATA DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_ADSALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATA VARCHAR(6),
PRMESESANTERIORES SMALLINT,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDATAAD DATE,
BDREF INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_CALCAUT(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRMESESANTERIORES SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFFN INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_CALCULO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRMESESANTERIORES SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFFN INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRH_TREEVIEW_CONS_CALCINT (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRPORCONTRATO smallint,
    PRREFERENCIA integer,
    PRMESESANTERIORES smallint)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDREFFN integer,
    BDCODCONTTI integer)
as
BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_CONS_CALC_FOLHAINT (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRANOMES integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCODCONTTI integer,
    BDCODVER integer,
    BDDESCVER varchar(70),
    BDDESCREDVER varchar(35),
    BDREFV numeric(15,6),
    BDREFAUXV numeric(15,6),
    BDPROVENTO numeric(15,6),
    BDDESCONTO numeric(15,6),
    BDTIPOCODVER integer,
    BDORDEMTIPOCODVER integer,
    BDINSSVER integer,
    BDFGTSVER integer,
    BDIRVER integer,
    BDTIPOREFVER integer,
    BDBASESFVER integer,
    BDPISVER varchar(5),
    BDBASEHEVER varchar(5),
    BDBASEMAIORVER varchar(5),
    BDRAISVER varchar(5),
    BDBASEGPSVER varchar(5),
    BDIGNREFV varchar(5),
    BDIGNVALV varchar(5),
    BDCLAVER varchar(20),
    BDORDEMVER integer,
    BDREF integer,
    BDREFHOREMP varchar(5),
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDBFGTSFE numeric(15,6),
    BDFGTSFE numeric(15,6))
as
BEGIN SUSPEND; END
^


CREATE OR ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_FOLAVUL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATA VARCHAR(6),
PRMESESANTERIORES SMALLINT,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDATAFA DATE,
BDREF INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_VAL_RAIS_FF(PREMP VARCHAR(32000),
PRCOL VARCHAR(32000),
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDAVPREV NUMERIC(15,6),
BDFERIND NUMERIC(15,6),
BDGRATIF NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDSINDICAL NUMERIC(15,6),
BDASSISTENCIAL NUMERIC(15,6),
BDCONFEDERATIVA NUMERIC(15,6),
BDBASEFN NUMERIC(15,6),
BDBASEA13 NUMERIC(15,6),
BDBASE13 NUMERIC(15,6),
BDBASEC13 NUMERIC(15,6),
BDORIGEM INTEGER,
BDMENSALIDADE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_VAL_RAIS_FF_REF(PREMP VARCHAR(32000),
PRCOL VARCHAR(32000),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDAVPREV NUMERIC(15,6),
BDFERIND NUMERIC(15,6),
BDGRATIF NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDSINDICAL NUMERIC(15,6),
BDASSISTENCIAL NUMERIC(15,6),
BDCONFEDERATIVA NUMERIC(15,6),
BDBASEFN NUMERIC(15,6),
BDBASEA13 NUMERIC(15,6),
BDBASE13 NUMERIC(15,6),
BDBASEC13 NUMERIC(15,6),
BDORIGEM INTEGER,
BDMENSALIDADE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_VERIFICAVERBASEMP_PADRAO(PRCODEMP INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER procedure SP_INSS_IRRF_ESOCIAL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCODTER integer,
    PRCODTIPO integer,
    PRREFARQ integer)
returns (
    BDSISVALORTOTAL numeric(15,6))
as
begin

end^

create or alter procedure SP_VRHF_BASE_CALC_TERC (
    PRREF integer,
    PRGPSSEFIP integer = 0,
    PRCODEMP varchar(32000) = null,
    PRCODAUT varchar(32000) = null)
returns (
    BDCODEMP integer,
    BDREFSERV integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDVALORINSS numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASERATAPO numeric(18,6),
    BDVALOUTENTIDADES numeric(18,6),
    BDCODTER integer,
    BDGPSSEFIP integer,
    BDCATEGORIAESOCIAL integer)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_BASE_TVERBASEMP_CONS(PRCODEMP INTEGER,
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODIGOVEREMP INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(40),
BDTIPOCOLVEREMP INTEGER,
BDCLASSECOLVEREMP INTEGER,
BDCOMFGTS VARCHAR(5),
BDCODTCA INTEGER,
BDDESCTCA VARCHAR(50),
BDINTERMITENTE DM_BOOLEAN,
BDADICNOTVAR DM_BOOLEAN,
BDAULISTA BOOLEAN)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_INSS_13 (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRANOTODO smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF13 integer,
    BDVALORINSS13 numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDSALFAM13 numeric(18,6),
    BDSALMATEMP13 numeric(18,6),
    BDBINSSMV13 numeric(18,6),
    BDCHAVE integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCODTOMADOR integer,
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBRATAPO13 numeric(18,6),
    BDBASEPIS numeric(18,6))
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_INSS_C13 (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRANOTODO smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF13 integer,
    BDVALORINSS13 numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDSALFAM13 numeric(18,6),
    BDSALMATEMP13 numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBRATAPO13 numeric(18,6),
    BDSEMBASEGPS numeric(18,6),
    BDBASEPIS numeric(18,6))
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_INSS_FC (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRREFPAG integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS smallint = 0,
    PRREFFIM integer = 0,
    PRCOMPLEESOCIAL integer = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFCOMP integer,
    BDCODCENTROS integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDCODTIPOFC integer,
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEPIS numeric(18,6))
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_INSS_FC_ESOCIAL (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREFNEW integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS smallint = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFCOMP integer,
    BDCODCENTROS integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDCODTIPOFC integer,
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEPIS numeric(18,6))
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_ESOCIAL_DADOS_INSS_FN (
    PRCODEMP varchar(15000),
    PRREF integer,
    PRCONTRATO integer = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDCODCENTROS integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDPERCRATCOL numeric(18,6),
    BDPERCDESCFPASCOL numeric(18,6))
as
BEGIN
  SUSPEND;
END^

create or alter procedure SP_ESOCIAL_DADOS_INSS_FT (
    PRCODEMP varchar(15000),
    PRREF integer,
    PRCONTRATO integer = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDPERCRATCOL numeric(18,6),
    BDPERCDESCFPASCOL numeric(18,6))
as
BEGIN
  SUSPEND;
END^

create or alter procedure SP_VRHF_DADOS_INSS_FN (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS varchar(15000) = null,
    PRCONTRATO integer = 0,
    PRSEPARARFOLHAS DM_BOOLEAN = 'FALSE')
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDCODCENTROS integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDPERCRATCOL numeric(18,6),
    BDPERCDESCFPASCOL numeric(18,6),
    BDCNPJEMP DM_CNPJ_CPF,
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDCOVID19FN numeric(18,6),
    BDBASEPIS numeric(18,6),
    BDCATEGORIAESOCIAL integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_INSS_FT (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS varchar(15000) = null,
    PRCONTRATO integer = 0,
    PRORDEM integer = 0,
    PRSEPARARFOLHAS DM_BOOLEAN = 'FALSE')
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDPERCRATCOL numeric(18,6),
    BDPERCDESCFPASCOL numeric(18,6),
    BDCNPJEMP DM_CNPJ_CPF,
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDCOVID19FN numeric(18,6),
    BDBASEPIS numeric(15,2),
    BDBASEPIS13 numeric(15,2),
    BDCATEGORIAESOCIAL integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_INSS_FTC (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32000),
    PRREF integer,
    PRREFPAG integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS smallint = 0,
    PRREFFIM integer = 0,
    PRCOMPLEESOCIAL integer = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFCOMP integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDCODTIPOFC integer,
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEPIS numeric(18,6))
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_INSS_FTC_ESOCIAL (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32000),
    PRREFNEW integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS smallint = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFCOMP integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDCODTIPOFC integer,
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEPIS numeric(18,6))
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_AD13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ )
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
begin suspend; end^

create or alter procedure SP_VRHF_DADOS_IR_13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PR5002 boolean = false,
    PRVEIODOTOTALIZADOR integer = 0,
    PRPORCC smallint = 1,
    PRDECLARACAO integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,6),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_13FN (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0,
    PRPORCC smallint = 1)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,6),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_13FC (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRIRRFESOCIAL boolean = false,
    PRVERCALCRRA integer = -1,
    PRPORCC smallint = 1)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFFC integer,
    BDCODACCONV integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_13FC_INT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRIRRFESOCIAL boolean = false,
    PRPORCC smallint = 1)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODCONTTI integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_AD (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDTIPODEDUCAOFOLHA integer,
    BDVALORDESCONTOSIMPLIFICADO DM_NUMERIC_15_2,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL  integer,
    BDCODTIPO integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_C13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVERCALCRRA integer = 0,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDVERCALCRRA integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_IR_DARF(PRCODEMP varchar(20000),
PRCODCOL varchar(30000),
PRREFINI integer,
PRREFFIM integer,
PRPUXARFILIAIS integer = 0,
PRCODMATRIZ varchar(15000) = '',
PRPORCC smallint = 0,
PRSEMPLR smallint = 0,
PRIRRFESOCIAL boolean = false)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFIR INTEGER,
BDREFIRFIR INTEGER,
BDTIPOCALCFIR INTEGER,
BDCCFIR INTEGER,
BDCODFERFIR INTEGER,
BDCODTCA INTEGER,
BDBASEIRFIR NUMERIC(18,6),
BDVALINSSFIR NUMERIC(18,6),
BDVALIRFIR NUMERIC(18,6),
BDVALDEPFIR NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDDATAFIR DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_IR_5012 (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER = 0,
    PRCODMATRIZ VARCHAR(15000) = '',
    PRPORCC SMALLINT = 0,
    PRSEMPLR SMALLINT = 0,
    PRCALCAPURANUAL INTEGER = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREFFIR INTEGER,
    BDREFIRFIR INTEGER,
    BDTIPOCALCFIR INTEGER,
    BDCCFIR INTEGER,
    BDCODFERFIR INTEGER,
    BDCODTCA INTEGER,
    BDBASEIRFIR NUMERIC(18,6),
    BDVALINSSFIR NUMERIC(18,6),
    BDVALIRFIR NUMERIC(18,6),
    BDVALDEPFIR NUMERIC(18,6),
    BDPENJUD NUMERIC(18,6),
    BDPENALIM NUMERIC(18,6),
    BDDATAFIR DATE,
    BDCODAUTONOMO INTEGER,
    BDCONTRCOL INTEGER,
    BDCPFCOL VARCHAR(14),
    BDCODMATRIZ INTEGER,
    BDCNPJEMP VARCHAR(18),
    BDCODFILIAL INTEGER,
    BDREFEMP INTEGER,
    BDNOMEMP VARCHAR(100),
    BDCODCLA INTEGER,
    BDCODGRUPOCLA INTEGER,
    BDCODCLATRI INTEGER,
    BDCODESTAB VARCHAR(30),
    BDTIPOCAEPF INTEGER,
    BDESCOOPERATIVA INTEGER,
    BDESCONSTRUTORA VARCHAR(5),
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDTIPOTOM INTEGER,
    BDCODLOT INTEGER,
    BDCNPJTOM VARCHAR(18))
AS
 BEGIN SUSPEND; END
^
    
create or alter procedure SP_VRHF_DADOS_IR_FA (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRSOMENTEPLR smallint = 0,
    PRSEMPLR smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDCODTCA integer,
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_TEMRRAANO (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer)
as
BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_FC_RRA (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PREXPORTACAO integer = 0,
    PRPORCC smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRMESESRRATOTAL integer = 0,
    PRGRAVATABTEMP boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    WGCLASS varchar(1000),
    WDESCVER2 varchar(70),
    WI integer,
    BDORDEM integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDREFIRRFESOCIAL integer,
    BDVERCALCRRA integer,
    BDTIPODEDUCAOFOLHA integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(15,2),
    BDCODACCONV integer,
    BDTOTALDESPJDC numeric(18,6),
    BDMESESRRA numeric(18,6),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDREFFC integer,
    BDCODFIR integer,
    BDCODTIPO integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_RT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRGRAVATEMPRENDTRIB boolean = false,
    PRRELATORIO boolean = false,
    PRFILTRORECEITA integer = 0,
    PRSEMRENDISENTO boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCHAVE integer,
    BDREFPGTO integer,
    BDIRRFMENSAL numeric(18,6),
    BDIRRFDECIMOTERC numeric(18,6),
    BDPREVIDENCIAOFICIAL numeric(18,6),
    BDCODRECEITAESOC varchar(6),
    BDTOTALDESPJUDICIAL numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDRENDNAPTRIBUT numeric(18,6),
    BDQTDMESESRRA numeric(18,6),
    BDVALORPAGOADVOGADO numeric(18,6),
    BDCPFADVOGADO varchar(18),
    BDNOMCOL varchar(70),
    BDCPF varchar(18),
    BDDESCRRA varchar(50),
    BDDESCRENDNAOTRIBUT varchar(60),
    BDJUROSMORA numeric(18,6),
    BDQTDDEP integer,
    BDNUMPROCESSO varchar(25),
    BDVALDEP numeric(18,6),
    BDTOTALPENSAO numeric(18,6),
    BDPENSAOMENSAL numeric(18,6),
    BDPENSAO13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDPREVIDENCIAOFICIAL13 numeric(18,6),
    BDJUROSMORA13 numeric(18,6))
AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_FC_NORMAL (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PREXPORTACAO integer = 0,
    PRPORCC smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVERCALCRRA integer = -1,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    WGCLASS varchar(13000),
    WDESCVER2 varchar(70),
    WI integer,
    BDORDEM integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDREFIRRFESOCIAL integer,
    BDVERCALCRRA integer,
    BDTIPODEDUCAOFOLHA integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(15,2),
    BDCODACCONV integer,
    BDMESESRRA numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFFC integer,
    BDINCIDESOCIALFER integer,
    BDCODTIPO integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_FC (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PREXPORTACAO integer = 0,
    PRPORCC smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVERCALCRRA integer = -1,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    WGCLASS varchar(13000),
    WDESCVER2 varchar(70),
    WI integer,
    BDORDEM integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDREFIRRFESOCIAL integer,
    BDVERCALCRRA integer,
    BDTIPODEDUCAOFOLHA integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(15,2),
    BDCODACCONV integer,
    BDMESESRRA numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFFC integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDCODTIPO integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_FC_INT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PREXPORTACAO integer = 0,
    PRPORCC smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    WGCLASS varchar(13000),
    WDESCVER2 varchar(70),
    WI integer,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFFC integer,
    BDINCIDESOCIALFER integer,
    BDCODACCONV integer,
    BDCODFIR integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
BEGIN SUSPEND; END^

create or alter procedure SP_VRHF_DADOS_IR_FE (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PREXPORTACAO integer = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDREFINIGOZO integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDCODFE integer,
    BDINIPERAQUIS date,
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    bdrefirrfesocial integer,
    BDCODTIPO integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_FN_INT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PREXPORTACAO integer = 0,
    PRPORCC smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRFICHAFINANCEIRA smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDDEMDEV varchar(30),
    BDCODTIPO integer)
as
BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_FT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PREXPORTACAO integer = 0,
    PRPORCC smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBASE13 numeric(18,6),
    BDVALOR13 numeric(18,6),
    BDBOLSAESTUDOS numeric(18,6),
    BDTIPODEDUCAOFOLHA integer,
    BDVALORDIFERENCADEDUCOES numeric(9,2),
    BDVALORDESCONTOSIMPLIFICADO numeric(9,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_FN (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PREXPORTACAO integer = 0,
    PRPORCC smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0,
    PRFICHAFINANCEIRA smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBASE13 numeric(18,6),
    BDVALORDIFERENCADEDUCOES numeric(18,2),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDVALOR13 numeric(18,6),
    BDTIPODEDUCAOFOLHA integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_13_INT13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRIRRFESOCIAL boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDDEMDEV varchar(30),
    BDCODTIPO integer)
as
BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_INTFT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PRPORCC smallint = 0,
    PRINSSANTES smallint = 1,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    bdrefirrfesocial integer,
    BDCODTIPO integer)
as
BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_INT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PRPORCC smallint = 0,
    PRINSSANTES smallint = 1,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_INT13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRINSSANTES smallint = 1,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0,
    PRPORCC smallint = 1)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
BEGIN SUSPEND; END^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_IR_FN2 (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER = 0,
    PRCODMATRIZ VARCHAR(15000) = '',
    PRPREVIARESC SMALLINT = 0) 
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDREFPAG INTEGER,
    BDTIPO INTEGER,
    BDRENDTRIBUTAVEL NUMERIC(18,6),
    BDINSS NUMERIC(18,6),
    BDIR NUMERIC(18,6),
    BDDEP NUMERIC(18,6),
    BDLUCROPJ NUMERIC(18,6),
    BDDESPMED NUMERIC(18,6),
    BDAJCUSTOS NUMERIC(18,6),
    BDPENJUD NUMERIC(18,6),
    BDPENALIM NUMERIC(18,6),
    BDPREVPRIV NUMERIC(18,6),
    BDINDRESC NUMERIC(18,6),
    BDVALABO NUMERIC(18,6),
    BDRENDISENTOS NUMERIC(18,6),
    BDDRENDISENTOS VARCHAR(999),
    BDDATAPGTO DATE,
    BDINFADIC VARCHAR(300),
    BDDATAPROC DATE,
    BDHORAPROC TIME,
    BDORDEM INTEGER) 
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_FGTS_FN (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER,
    PRCODMATRIZ VARCHAR(15000))
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDBFGTS NUMERIC(18,6),
    BDFGTS NUMERIC(18,6),
    BDBFGTSRESC NUMERIC(18,6),
    BDFGTSRESC NUMERIC(18,6),
    BDBFGTS13 NUMERIC(18,6),
    BDFGTS13 NUMERIC(18,6),
    BDBFGTS13RESC NUMERIC(18,6),
    BDFGTS13RESC NUMERIC(18,6),
    BDDATAPROC DATE,
    BDHORAPROC TIME,
    BDORDEM INTEGER)
AS
BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_FGTS_FC (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer,
    PRCODMATRIZ varchar(15000),
    PRADC boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBFGTSRESC numeric(18,6),
    BDFGTSRESC numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDBFGTS13RESC numeric(18,6),
    BDFGTS13RESC numeric(18,6),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDTIPOEVT integer)
as
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_FGTS_13 (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER,
    PRCODMATRIZ VARCHAR(15000))
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDBFGTS NUMERIC(18,6),
    BDFGTS NUMERIC(18,6),
    BDDATAPROC DATE,
    BDHORAPROC TIME,
    BDORDEM INTEGER)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_FGTS_A13 (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER,
    PRCODMATRIZ VARCHAR(15000))
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDBFGTS NUMERIC(18,6),
    BDFGTS NUMERIC(18,6),
    BDORDEM INTEGER)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_FGTS_C13 (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER = 0,
    PRCODMATRIZ VARCHAR(15000) = '')
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDTIPO INTEGER,
    BDFGTS NUMERIC(18,6),
    BDBFGTS NUMERIC(18,6),
    BDDATAPROC DATE,
    BDHORAPROC TIME,
    BDORDEM INTEGER)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_FGTS_FER (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER,
    PRCODMATRIZ VARCHAR(15000))
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDBFGTS NUMERIC(18,6),
    BDFGTS NUMERIC(18,6),
    BDORDEM INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WUSARTMP_EMP_SELECT SMALLINT;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WREF INTEGER;
DECLARE VARIABLE WBASEFGTS NUMERIC(18,6);
DECLARE VARIABLE WVALORFGTS NUMERIC(18,6);
DECLARE VARIABLE WORDEM INTEGER;
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_PIS_13 (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER = 0,
    PRCODMATRIZ VARCHAR(15000) = '')
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDCODVER INTEGER,
    BDBASEPISFE NUMERIC(15,6),
    BDBASEPIS13 NUMERIC(15,6),
    BDBASEPISFN NUMERIC(15,6),
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDCTALON VARCHAR(20)) AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_PIS_C13 (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER = 0,
    PRCODMATRIZ VARCHAR(15000) = '')
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDCODVER INTEGER,
    BDBASEPISFE NUMERIC(15,6),
    BDBASEPIS13 NUMERIC(15,6),
    BDBASEPISFN NUMERIC(15,6),
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDCTALON VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_PIS_FC(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDBASEPISFE NUMERIC(15,6),
BDBASEPIS13 NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCTALON VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_PIS_FN(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDBASEPISFE NUMERIC(15,6),
BDBASEPIS13 NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCTALON VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_PIS_AD13 (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER = 0,
    PRCODMATRIZ VARCHAR(15000) = '')
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDCODVER INTEGER,
    BDBASEPISFE NUMERIC(15,6),
    BDBASEPIS13 NUMERIC(15,6),
    BDBASEPISFN NUMERIC(15,6),
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDCTALON VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^


CREATE OR ALTER PROCEDURE SP_VRHF_EMP_BASES_RESCISAO(PRCODEMP VARCHAR(25000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFAUXVFN NUMERIC(15,6),
BDREFVFN NUMERIC(15,6),
BDVALVFN NUMERIC(15,6),
BDIGNREFVFN VARCHAR(5),
BDIGNVALVFN VARCHAR(5),
BDSALBASEFN NUMERIC(15,6),
BDMAIORREMFN NUMERIC(15,6),
BDBFGTSFN NUMERIC(15,6),
BDFGTSFN NUMERIC(15,6),
BDFGTSCSFN NUMERIC(15,6),
BDBFGTS13FN NUMERIC(15,6),
BDFGTS13FN NUMERIC(15,6),
BDFGTS13CSFN NUMERIC(15,6),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDCNPJEMP VARCHAR(18),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDDDDFAXEMP INTEGER,
BDFAXEMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDNOMCOL DM_BDNOMCOL,
BDDATAADMCOL DATE,
BDDATANASCCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDDATAOPCAOFGTSCOL DATE,
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDSIGLAUFCTPS VARCHAR(2),
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAPAGRESCISAO DATE,
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCODPRES INTEGER,
BDSALDOFGTS NUMERIC(15,6),
BDDESCPRES VARCHAR(110))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_EMP_TFOLHANORMAL_ANT(PRREF INTEGER,
PRCODEMP VARCHAR(20000) = NULL,
PRCODCOL VARCHAR(32700) = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDDATABAIXAFN DATE,
BDBFGTSFN NUMERIC(15,6),
BDFGTSFN NUMERIC(15,6),
BDFGTSCSFN NUMERIC(15,6),
BDBFGTS13FN NUMERIC(15,6),
BDFGTS13FN NUMERIC(15,6),
BDFGTS13CSFN NUMERIC(15,6),
BDMAIORREMFN NUMERIC(15,6),
BDBINSSFN NUMERIC(15,6),
BDALIQINSSFN NUMERIC(15,6),
BDINSSFN NUMERIC(15,6),
BDBIRRFFN NUMERIC(15,6),
BDALIQIRRFFN NUMERIC(15,6),
BDIRRFFN NUMERIC(15,6),
BDBINSS13FN NUMERIC(15,6),
BDALIQINSS13FN NUMERIC(15,6),
BDINSS13FN NUMERIC(15,6),
BDBIRRF13FN NUMERIC(15,6),
BDALIQIRRF13FN NUMERIC(15,6),
BDIRRF13FN NUMERIC(15,6),
BDBSALFAMFN NUMERIC(15,6),
BDSALFAMFN NUMERIC(15,6),
BDBRAISFN NUMERIC(15,6),
BDSALBASEFN NUMERIC(15,6),
BDDEPFN NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6),
BDBASEPISFEFN NUMERIC(15,6),
BDBASEPIS13FN NUMERIC(15,6),
BDBSALMATEMPFN NUMERIC(15,6),
BDSALMATEMPFN NUMERIC(15,6),
BDBRATAPOFN NUMERIC(15,6),
BDBINSSFEFOLFN NUMERIC(15,6),
BDINSSFEFOLFN NUMERIC(15,6),
BDALIQINSSFEFOLFN NUMERIC(15,6),
BDDEBITOFN NUMERIC(15,6),
BDCREDITOFN NUMERIC(15,6),
BDBFGTSFEFN NUMERIC(15,6),
BDFGTSFEFN NUMERIC(15,6),
BDBRATAPOFEFN NUMERIC(15,6),
BDBRATAPO13FN NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_TCOL_VINC_REF(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFCOL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFCOL INTEGER,
BDCODSINTRAB INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_SAUDE (
    PREMP varchar(20000),
    PRCOL varchar(32000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPORCOMPETENCIA smallint = 0,
    PRPORFICHA smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDREF integer)
as
begin
  SUSPEND;
end^

create or alter procedure SP_VRHM_FF_OP_REF (
    PREMP varchar(32000) = '',
    PRCOL varchar(32000) = '',
    PRREFINI integer = 0,
    PRREFFIM integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDNOME varchar(70),
    BDTIPO integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDMENSALIDADE numeric(15,6),
    BDCOPARTICIPACAO numeric(15,6))
as
begin
  suspend;
end^

CREATE OR ALTER PROCEDURE SP_VRHM_FF_OP_ANO(PREMP varchar(32000) = '',
    PRCOL varchar(32000) = '',
    PRANO integer = 0,
    PROPER integer = 0,
    PRCONV integer = 0,
    PRREFPAG integer = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDNOME VARCHAR(70),
BDTIPO INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDMENSALIDADE NUMERIC(15,6),
BDCOPARTICIPACAO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHM_FF_OP_REF(PREMP VARCHAR(32000) = '',
PRCOL VARCHAR(32000) = '',
PRREFINI INTEGER = 0,
PRREFFIM INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDNOME VARCHAR(70),
BDTIPO INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDMENSALIDADE NUMERIC(15,6),
BDCOPARTICIPACAO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHM_VAL_PS_COL(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDREF INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDVALORMENSALIDADE NUMERIC(15,6),
BDVALLORCOPAR NUMERIC(15,6),
BDCODTIPOCONV INTEGER,
BDCODEMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHM_VAL_PS_DEP(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDREF INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDVALORMENSALIDADE NUMERIC(15,6),
BDVALLORCOPAR NUMERIC(15,6),
BDCODEMP INTEGER,
BDCODDPN INTEGER,
BDNOMDEP VARCHAR(70))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VSUC_COPIA_CT_PLANO_DFIS(CODIGOPLANOCOPIAR INTEGER,
ANOCOPIAR INTEGER,
ANONOVO INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_VSUC_COPIA_CT_PLANO_FCONT(CODIGOPLANOCOPIAR INTEGER,
ANOCOPIAR INTEGER,
ANONOVO INTEGER)
 AS
 BEGIN EXIT; END
^

create or alter procedure SP_DADOS_GPS_COMP (
    WEMP varchar(30000),
    WCOL varchar(30000),
    FANOMES integer,
    FANOMESFIM integer,
    FANOMESPAG integer,
    FPUXAFILIAIS integer,
    PRGPSSEFIP integer,
    PRCODIMP integer,
    TIPOFC integer,
    FJOINFILTROCOL varchar(5000) = '',
    FJOINEMPIMP varchar(5000) = '',
    FJOINFILTROSITCOL varchar(5000) = '',
    FCODCLA varchar(5000) = '',
    PRCOMPLEESOCIAL integer = 0)
returns (
    BDBASEFUNC13 numeric(15,2),
    BDBASEFUN13 numeric(15,2),
    BDBASERATAPOC13 numeric(15,2),
    BDBASERATAPO13 numeric(15,2),
    BDBASEFUNFN numeric(15,2),
    BDPERCDESCFPASCOL numeric(15,2),
    BDPERCRATCOL numeric(15,2),
    BDDESCENQFED varchar(10),
    BDISENFILEMP numeric(15,2),
    BDCATSEFIPEMP integer,
    BDCODENQFED integer,
    BDDATAINIPERIOD date,
    BDREFINIDCTFWEB integer,
    BDOPCAOESOCIAL integer,
    BDNOMEMP varchar(100),
    BDCNPJEMP varchar(18),
    BDDESONTOMAEMP varchar(10),
    BDCODTRIBRUR integer,
    BDBASEFUNFERFC numeric(15,2),
    BDBASEFUNFC numeric(15,2),
    BDBASEINSS13 numeric(15,2),
    BDBASEINSS numeric(15,2),
    BDBASERAT numeric(15,2),
    BDNOMETOM varchar(100),
    BDCNPJTOM varchar(18),
    BDBINSS13INDFN numeric(15,2),
    BDTIPOTOM integer,
    BDVALINDEVIDOSF numeric(15,2),
    BDVALINDEVIDO numeric(15,2),
    BDGPSSEFIP integer,
    BDSESCOOP numeric(15,2),
    BDSENAT numeric(15,2),
    BDSEST numeric(15,2),
    BDSENAR numeric(15,2),
    BDFUNAERO numeric(15,2),
    BDDPC numeric(15,2),
    BDSEBRAE numeric(15,2),
    BDSESC numeric(15,2),
    BDSENAC numeric(15,2),
    BDSESI numeric(15,2),
    BDSENAI numeric(15,2),
    BDINCRA numeric(15,2),
    BDSALEDU numeric(15,2),
    BDATUTAB varchar(10),
    BDDESONOBRA varchar(10),
    BDINDUSTRIA varchar(10),
    BDCOMERCIO varchar(10),
    BDANEXOVI varchar(10),
    BDANEXOV varchar(10),
    BDANEXOIII varchar(10),
    BDANEXOIV varchar(10),
    BDPERCFPAS numeric(15,2),
    BDPERCAUT numeric(15,2),
    BDPERCPRO numeric(15,2),
    BDPERCFUN numeric(15,2),
    BDSIMPLESGPS integer,
    BDCODEMP integer,
    BDREFPAG integer,
    BDREFFN integer,
    BDBASEFUN13RFN numeric(15,2),
    BDBASEFUNFERFN numeric(15,2),
    BDCCATVCONCOM varchar(10),
    BDBASEFUN13RFC numeric(15,2),
    BDINSS13FN numeric(15,2),
    BDINSSFEFOLFN numeric(15,2),
    BDINSSFN numeric(15,2),
    BDCODTPCC integer,
    BDCODFPAS integer,
    BDCODCENTRO integer,
    BDCODCOL integer,
    BDCODTOMADOR integer,
    BDBASERATAPO13RFN numeric(15,2),
    BDBASERATAPOFERFN numeric(15,2),
    BDBASERATAPOFN numeric(15,2),
    VALOUTENTIDADE integer,
    SALMATERNIDADE numeric(15,2),
    SALFAM numeric(15,2),
    BDGRUPOCLA integer,
    BDCODTER integer,
    BDBINSSMV13FN numeric(15,2),
    BDBINSSMVFN numeric(15,2),
    BDBASERATAPO13RFC numeric(15,2),
    BDBASERATAPOFERFC numeric(15,2),
    BDTIPO_TPCC integer,
    BDBASERATAPOFC numeric(15,2),
    BDCODMATRIZ integer,
    BDCODEMPCOL integer,
    BDREFPAGTC integer,
    BDPERCRAT numeric(15,4),
    BDPERCFAPCAD numeric(15,4),
    BDPERCRATCAD numeric(15,4),
    BDCODTIPOFC integer,
    BDBASEPIS numeric(18,6),
    BDCATEGORIAESOCIAL integer)
as
BEGIN SUSPEND; END
^

create or alter procedure SP_DADOS_REL_QTDFOLHAS (
    PREMPRESA varchar(20000),
    PRREFINICIAL varchar(15),
    PRREFFINAL varchar(15),
    PREMITIREMPSEMFOLHAS integer,
    PRTIPOCALCULO integer,
    PRTIPODEFOLHAAVULSA integer = -1)
returns (
    BDCODEMPRESA integer,
    BDNOMEEMPRESA varchar(1000),
    BDCNPJEMPRESA varchar(30),
    BD01 integer,
    BD02 integer,
    BD03 integer,
    BD04 integer,
    BD05 integer,
    BD06 integer,
    BD07 integer,
    BD08 integer,
    BD09 integer,
    BD10 integer,
    BD11 integer,
    BD12 integer,
    BDREF01 integer,
    BDREF02 integer,
    BDREF03 integer,
    BDREF04 integer,
    BDREF05 integer,
    BDREF06 integer,
    BDREF07 integer,
    BDREF08 integer,
    BDREF09 integer,
    BDREF10 integer,
    BDREF11 integer,
    BDREF12 integer,

    BD01Col integer,
    BD02Col integer,
    BD03Col integer,
    BD04Col integer,
    BD05Col integer,
    BD06Col integer,
    BD07Col integer,
    BD08Col integer,
    BD09Col integer,
    BD10Col integer,
    BD11Col integer,
    BD12Col integer,

    BD01Inter integer,
    BD02Inter integer,
    BD03Inter integer,
    BD04Inter integer,
    BD05Inter integer,
    BD06Inter integer,
    BD07Inter integer,
    BD08Inter integer,
    BD09Inter integer,
    BD10Inter integer,
    BD11Inter integer,
    BD12Inter integer,

    BD01Contr integer,
    BD02Contr integer,
    BD03Contr integer,
    BD04Contr integer,
    BD05Contr integer,
    BD06Contr integer,
    BD07Contr integer,
    BD08Contr integer,
    BD09Contr integer,
    BD10Contr integer,
    BD11Contr integer,
    BD12Contr integer,

    BD01Ter integer,
    BD02Ter integer,
    BD03Ter integer,
    BD04Ter integer,
    BD05Ter integer,
    BD06Ter integer,
    BD07Ter integer,
    BD08Ter integer,
    BD09Ter integer,
    BD10Ter integer,
    BD11Ter integer,
    BD12Ter integer)
as
BEGIN SUSPEND; END
^

create or alter procedure SP_BUSCA_VALOR_PIS_VERBAS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFFOLHA integer,
    PRTIPOFOLHA integer,
    PRDIFERENCIADORDATE date,
    PRDIFERENCIADORINTEGER integer)
returns (
    BDBDVALORPISPASEP numeric(18,6),
    BDVALORPISPASEP13 numeric(18,6))
as
declare variable WSQL varchar(30000);
declare variable WVALORVERBA numeric(18,6);
declare variable WINCIDENCIAPIS integer;
BEGIN SUSPEND; END
^

create or alter procedure SP_RETORNA_TAGSTR_TOTALIZADORES (
    PRCODEMPRESA integer,
    PRCODCOLABORADOR integer,
    PRREFFOLHA integer,
    PRTIPOFOLHA integer,
    PRDIFERENCIADORDATE date,
    PRDIFERENCIADORINTEGER integer,
    PRCONVERTTIPO integer = 0,
    PRINTERMITENTE integer = 0,
    PRORDEM integer = 0,
    PRFC integer = 0,
    PRREFDATAFC integer = 0)
returns (
    BDDESCRICAOCALCULO varchar(10000),
    BDTAGSTR varchar(10000))
as
declare variable WTIPO integer;
declare variable WTIPOPROPA13 integer;
declare variable WPERCA13 numeric(18,6);
declare variable WDESCRICAOFOLHA varchar(10000);
declare variable WTAGSTR varchar(10000);
declare variable WCODIGOADC integer;
declare variable WCODCONTRATO integer;
declare variable WREFFOLHA integer;
declare variable WDESCRICAOAVULSA varchar(10000);
BEGIN SUSPEND; END
^

create or alter procedure SP_HORARIOS_INTERMITENTES (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDDATA date,
    BDHORAINICIAL time,
    BDHORAFINAL time)
as
declare variable WDATAINI date;
declare variable WDATAFIM date;
declare variable WTIPO integer;
declare variable WCODHOR_CON_INT integer;
declare variable WCODCONTRATO integer;
BEGIN SUSPEND; END
^

create or alter procedure SP_HORARIO_INTERMITENTES_DIARIO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRDATA date)
returns (
    BDINICIO time,
    BDFIM time)
as
declare variable WPLANO integer;
declare variable WQUADRO integer;
declare variable WHORAS numeric(15,6);
declare variable WSTRHORA varchar(10);
declare variable WSTRMIN varchar(10);
begin SUSPEND; END
^

create or alter procedure SP_RH_UNION_FC_FCT_MES (
    PRCODEMP varchar(3000),
    PRCODCOL varchar(3000),
    PRCODADC integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRREFPAG date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFC integer,
    BDREFCOMP integer,
    BDCODVER integer,
    BDREFVFN_SUM numeric(15,2),
    BDREFAUXVFN_SUM numeric(15,2),
    BDREFVFN_MAX numeric(15,2),
    BDREFAUXVFN_MAX numeric(15,2),
    BDVALVFN numeric(15,2),
    BDVALIFN numeric(15,2),
    BDIGNREFAVFN varchar(3000),
    BDIGNREFVFN varchar(3000),
    BDIGNVALVFN varchar(3000),
    BDORVERBAFC integer,
    BDCOMPESP varchar(3000),
    BDFORMREFAUX varchar(3000),
    BDFORMREF varchar(3000),
    BDFORMVAL varchar(3000),
    BDDESCVER varchar(3000),
    BDTIPOCODVER integer,
    BDCLAVER varchar(3000),
    BDORDEMVER integer,
    BDTIPOREFVER integer,
    BDREFFN integer)
as
BEGIN suspend; end
^

create or alter procedure SPCODIMPGPSCOMPLEMENTAR (
    PRCODEMP varchar(32000),
    PRREF integer,
    PRREFPAG integer,
    PRREFFIM integer)
returns (
    BDCODEMP integer,
    BDCODTIPOFC integer,
    BDCODIMP integer,
    BDCODMATRIZ integer,
    BDEMPIMP integer,
    BDLIMITEISENCAO numeric(15,6))
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SPCODIMPGPSCOMPLEMENTAR_ESOCIAL(PRCODEMP VARCHAR(32000),
PRREFCOMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODTIPOFC INTEGER,
BDCODIMP INTEGER,
BDCODMATRIZ INTEGER,
BDEMPIMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SPCORRIGEACENTOS AS
 BEGIN EXIT; END
^

create or alter procedure SPRH_CALC_13SALARIO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFERENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFV_MAX numeric(15,6),
    BDREFV_SUM numeric(15,6),
    BDREFAUXV_MAX numeric(15,6),
    BDREFAUXV_SUM numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNREFAV varchar(5),
    BDIGNVALV varchar(5),
    BDORVERBA integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDALTINT boolean,
    BDBASEIR13BRUTARED DM_NUMERIC_15_2,
    BDVALORIR13BRUTARED DM_NUMERIC_15_2,
    BDVALOR13RED DM_NUMERIC_15_2)
as
BEGIN
  SUSPEND;
END^

create or alter procedure SPRH_CALC_AD13SALARIO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFERENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFV_MAX numeric(15,6),
    BDREFV_SUM numeric(15,6),
    BDREFAUXV_MAX numeric(15,6),
    BDREFAUXV_SUM numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNREFAV varchar(5),
    BDIGNVALV varchar(5),
    BDORVERBA integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDALTINT boolean)
AS
BEGIN
  SUSPEND;
END^

create or alter procedure SPRH_CALC_ADSAL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFERENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDDATAAD date,
    BDREFV_MAX numeric(15,6),
    BDREFV_SUM numeric(15,6),
    BDREFAUXV_MAX numeric(15,6),
    BDREFAUXV_SUM numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNREFAV varchar(5),
    BDIGNVALV varchar(5),
    BDORVERBA integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDALTINT boolean)
as
begin
  suspend;
end^

create or alter procedure SPRH_CALC_AUTONOMO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFERENCIA integer,
    PRCODSERV integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFV_MAX numeric(15,6),
    BDREFV_SUM numeric(15,6),
    BDREFAUXV_MAX numeric(15,6),
    BDREFAUXV_SUM numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNREFAV varchar(5),
    BDIGNVALV varchar(5),
    BDORVERBA integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDBASEINSSNMVNOVO numeric(18,6),
    BDINCIRVER integer,
    BDTIPOCODVER integer,
    BDBASEIRBRUTO numeric(17,4),
    BDALTINT boolean,
    BDBASEIRBRUTARED DM_NUMERIC_15_2,
    BDBASEIR13BRUTARED DM_NUMERIC_15_2,
    BDVALORIRBRUTARED DM_NUMERIC_15_2,
    BDVALORIR13BRUTARED DM_NUMERIC_15_2,
    BDVALORRED DM_NUMERIC_15_2,
    BDVALOR13RED DM_NUMERIC_15_2)
as
BEGIN
  SUSPEND;
END^

create or alter procedure SPRH_CALC_COMP13SALARIO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFERENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFV_MAX numeric(15,6),
    BDREFV_SUM numeric(15,6),
    BDREFAUXV_MAX numeric(15,6),
    BDREFAUXV_SUM numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNREFAV varchar(5),
    BDIGNVALV varchar(5),
    BDORVERBA integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDALTINT boolean,
    BDBASEIR13BRUTARED DM_NUMERIC_15_2,
    BDVALORIR13BRUTARED DM_NUMERIC_15_2,
    BDVALOR13RED DM_NUMERIC_15_2)
as
BEGIN
  SUSPEND;
END^

create or alter procedure SPRH_CALC_FERIAS (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRCODFE integer,
    PRINIPERAQUISFE date,
    PRREFERENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFV_MAX numeric(15,6),
    BDREFV_SUM numeric(15,6),
    BDREFAUXV_MAX numeric(15,6),
    BDREFAUXV_SUM numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNREFAV varchar(5),
    BDIGNVALV varchar(5),
    BDORVERBA integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDDETALHE varchar(255),
    BDREFFN integer,
    BDCODFE integer,
    BDINIPERAQUISFE date,
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDBASEIROUT numeric(15,6),
    BDVALORIROUT numeric(15,6),
    BDDEPIROUT numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDALTINT boolean,
    BDBASEIRBRUTARED DM_NUMERIC_15_2,
    BDVALORIRBRUTARED DM_NUMERIC_15_2,
    BDVALORRED DM_NUMERIC_15_2)
as
BEGIN
  SUSPEND;
END^
  
CREATE OR ALTER PROCEDURE SPRH_CALC_FOLHACOMP(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV_MAX NUMERIC(15,6),
BDREFV_SUM NUMERIC(15,6),
BDREFAUXV_MAX NUMERIC(15,6),
BDREFAUXV_SUM NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDORVERBA INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDETALHE VARCHAR(255),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SPRH_CONS_CALC_13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDMESESPROP13 INTEGER,
BDBASEIR13 NUMERIC(15,6),
BDBASEFGTS13 NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS13 NUMERIC(15,6),
BDDATABAIXA13 DATE,
BDREFBAIXA13 INTEGER,
BDPERCIR13 NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDPERCINSS13 NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SPRH_CONS_CALC_AD13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDPERC NUMERIC(15,6),
BDVAL NUMERIC(15,6),
BDTIPOPROP INTEGER,
BDMESESPROP INTEGER,
BDBASEIR NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBASEFGTS NUMERIC(15,6),
BDDATABAIXA DATE,
BDREFBAIXA INTEGER,
BDPERCIR NUMERIC(15,6),
BDVALORIR NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

--alt:13612 - 24/03/2016 - Parametro de entrada PRANO teve alterado o nome para PRMESESANTERIORES e o tipo para SMALLINT - Bruno L. R. 
CREATE OR ALTER PROCEDURE SPRH_TREEVIEW_CONS_13SAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRMESESANTERIORES SMALLINT,
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDREF13 INTEGER)
 AS
 BEGIN SUSPEND; END
^

--alt:13612 - 23/03/2016 - Parametro de entrada PRANO teve alterado o nome para PRMESESANTERIORES e o tipo para SMALLINT - Bruno L. R. 
CREATE OR ALTER PROCEDURE SPRH_TREEVIEW_CONS_AD13SAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRMESESANTERIORES SMALLINT,
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDREFA13 INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SPVAL_ITINERARIO(PRITI INTEGER,
PRREF INTEGER)
 RETURNS(BDITI INTEGER,
BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE STRTRAN(PRTEXTO VARCHAR(30000),
PRSUBSTR VARCHAR(1024),
PRSTR VARCHAR(1024))
 RETURNS(BDRESULT VARCHAR(30000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE STRZERO(PRSTR INTEGER,
PRTAM INTEGER)
 RETURNS(STR VARCHAR(50))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE ULTIMO_DIA_MES(PRMES SMALLINT,
PRANO INTEGER)
 RETURNS(ULTDIA INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VCT_SERVICO_SUBORDINADO(PRCODSER INTEGER,
PRCODSUB INTEGER)
 RETURNS(BDCODSER INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VCT_TAREFA_SUBORDINADA(PRCODST INTEGER,
PRCODSUB INTEGER)
 RETURNS(BDCODST INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_CONSULTA_VINCULOISS(PRCODCID INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDREFVINCISS INTEGER,
BDCODTIPOISS INTEGER,
BDDESTIPOISS VARCHAR(50),
BDCODTIPOISSEXP INTEGER,
BDDESTIPOISSEXP VARCHAR(50),
BDPERISS DM_NUMERIC_7_4_ALIQ,
BDVALORLIMISS DM_NUMERIC_15_2,
BDCODTIPORPS INTEGER,
BDDESTIPORPS VARCHAR(50),
BDCODIBGE INTEGER,
BDDEDISS varchar(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_JOINNATPREPONDERANTE (
    PRCODATIVSIMPNAC INTEGER,
    PRCODBASESN INTEGER,
    PRISSRET NUMERIC(15,2))
RETURNS (
    BDCODATIVSIMPNAC INTEGER,
    BDCODCID INTEGER,
    BDCODATVM INTEGER,
    BDCODCONFATVMSN INTEGER,
    BDCODNAT INTEGER,
    BDCODCONFSN INTEGER,
    BDCODBASESN INTEGER,
    BDCODIMPOSTO INTEGER,
    BDCODTIPOIMPOSTO INTEGER,
    BDPREPONDERANTE VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_JOINNATNAOPREPONDERANTE (
    PRCODATIVSIMPNAC INTEGER,
    PRCODBASESN INTEGER,
    PRISSRET NUMERIC(15,2))
RETURNS (
    BDCODATIVSIMPNAC INTEGER,
    BDCODCID INTEGER,
    BDCODATVM INTEGER,
    BDCODCONFATVMSN INTEGER,
    BDCODNAT INTEGER,
    BDCODCONFSN INTEGER,
    BDCODBASESN INTEGER,
    BDCODIMPOSTO INTEGER,
    BDCODTIPOIMPOSTO INTEGER,
    BDPREPONDERANTE VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^
CREATE OR ALTER PROCEDURE VEF_SP_JOINATVPREPONDERANTE (
    PRCODATIVSIMPNAC INTEGER,
    PRCODBASESN INTEGER,
    PRISSRET NUMERIC(15,2))
RETURNS (
    BDCODATIVSIMPNAC INTEGER,
    BDCODCID INTEGER,
    BDCODATVM INTEGER,
    BDCODMUNATVM INTEGER, 
    BDCODCONFATVMSN INTEGER,
    BDCODNAT INTEGER,
    BDCODCONFSN INTEGER,
    BDCODBASESN INTEGER,
    BDCODIMPOSTO INTEGER,
    BDCODTIPOIMPOSTO INTEGER,
    BDPREPONDERANTE VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^
CREATE OR ALTER PROCEDURE VEF_SP_JOINATVNAOPREPONDERANTE (
    PRCODATIVSIMPNAC INTEGER,
    PRCODBASESN INTEGER,
    PRISSRET NUMERIC(15,2))
RETURNS (
    BDCODATIVSIMPNAC INTEGER,
    BDCODCID INTEGER,
    BDCODATVM INTEGER,
    BDCODCONFATVMSN INTEGER,
    BDCODNAT INTEGER,
    BDCODCONFSN INTEGER,
    BDCODBASESN INTEGER,
    BDCODIMPOSTO INTEGER,
    BDCODTIPOIMPOSTO INTEGER,
    BDPREPONDERANTE VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_DADOS_ISS_EXP(PRWHEREISS VARCHAR(10000) = NULL,
PRWHERECID VARCHAR(10000) = NULL,
PRWHEREEMP VARCHAR(32000) = NULL,
PRREFINI INTEGER = 0,
PRREFFIN INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDCODCID INTEGER,
BDCODTIPOISSEXP INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_DIRF(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PREXPORTARNOTAS INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODRECIVSUP INTEGER,
BDREFLAN INTEGER,
BDCODTER INTEGER,
BDCNPJIVSUP VARCHAR(18),
BDNOMEEMPIVSUP VARCHAR(100),
BDIRJANIVSUP NUMERIC(18,6),
BDIRFEVIVSUP NUMERIC(18,6),
BDIRMARIVSUP NUMERIC(18,6),
BDIRABRIVSUP NUMERIC(18,6),
BDIRMAIIVSUP NUMERIC(18,6),
BDIRJUNIVSUP NUMERIC(18,6),
BDIRJULIVSUP NUMERIC(18,6),
BDIRAGOIVSUP NUMERIC(18,6),
BDIRSETIVSUP NUMERIC(18,6),
BDIROUTIVSUP NUMERIC(18,6),
BDIRNOVIVSUP NUMERIC(18,6),
BDIRDEZIVSUP NUMERIC(18,6),
BDRENJANIVSUP NUMERIC(18,6),
BDRENFEVIVSUP NUMERIC(18,6),
BDRENMARIVSUP NUMERIC(18,6),
BDRENABRIVSUP NUMERIC(18,6),
BDRENMAIIVSUP NUMERIC(18,6),
BDRENJUNIVSUP NUMERIC(18,6),
BDRENJULIVSUP NUMERIC(18,6),
BDRENAGOIVSUP NUMERIC(18,6),
BDRENSETIVSUP NUMERIC(18,6),
BDRENOUTIVSUP NUMERIC(18,6),
BDRENNOVIVSUP NUMERIC(18,6),
BDRENDEZIVSUP NUMERIC(18,6),
BDACREDEDUIRSERJAN NUMERIC(18,6),
BDACREDEDUIRSERFEV NUMERIC(18,6),
BDACREDEDUIRSERMAR NUMERIC(18,6),
BDACREDEDUIRSERABR NUMERIC(18,6),
BDACREDEDUIRSERMAIO NUMERIC(18,6),
BDACREDEDUIRSERJUN NUMERIC(18,6),
BDACREDEDUIRSERJUL NUMERIC(18,6),
BDACREDEDUIRSERAGO NUMERIC(18,6),
BDACREDEDUIRSERSET NUMERIC(18,6),
BDACREDEDUIRSEROUT NUMERIC(18,6),
BDACREDEDUIRSERNOV NUMERIC(18,6),
BDACREDEDUIRSERDEZ NUMERIC(18,6),
BDINDIMUNEISE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_DIRF_RTIRF(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODRECIVSUP INTEGER,
BDCODTER INTEGER,
BDCNPJIVSUP VARCHAR(18),
BDNOMEEMPIVSUP VARCHAR(100),
BDIRJANIVSUP NUMERIC(18,6),
BDIRFEVIVSUP NUMERIC(18,6),
BDIRMARIVSUP NUMERIC(18,6),
BDIRABRIVSUP NUMERIC(18,6),
BDIRMAIIVSUP NUMERIC(18,6),
BDIRJUNIVSUP NUMERIC(18,6),
BDIRJULIVSUP NUMERIC(18,6),
BDIRAGOIVSUP NUMERIC(18,6),
BDIRSETIVSUP NUMERIC(18,6),
BDIROUTIVSUP NUMERIC(18,6),
BDIRNOVIVSUP NUMERIC(18,6),
BDIRDEZIVSUP NUMERIC(18,6),
BDINDIMUNEISE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_DIRF_RTRT(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PREXPORTARNOTAS INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDRENJANIVSUP NUMERIC(18,6),
BDRENFEVIVSUP NUMERIC(18,6),
BDRENMARIVSUP NUMERIC(18,6),
BDRENABRIVSUP NUMERIC(18,6),
BDRENMAIIVSUP NUMERIC(18,6),
BDRENJUNIVSUP NUMERIC(18,6),
BDRENJULIVSUP NUMERIC(18,6),
BDRENAGOIVSUP NUMERIC(18,6),
BDRENSETIVSUP NUMERIC(18,6),
BDRENOUTIVSUP NUMERIC(18,6),
BDRENNOVIVSUP NUMERIC(18,6),
BDRENDEZIVSUP NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXCLUI_REDZVARCFOP_PLANO (
PRSQL   VARCHAR(4000),
PREMP   INTEGER,
PRCHAVE INTEGER) 
 AS
 BEGIN END
^

create or alter procedure VEF_SP_EXP_DIME (
    PRCODEMP varchar(10000),
PRREFERENCIAINICIAL INTEGER,
PRREFERENCIAFINAL INTEGER)
returns (
    BDCODEMP integer,
BDREFERENCIA INTEGER,
BDNUMCAMPO INTEGER,
BDCLASSIFICACAO VARCHAR(5),
BDDESCCAMPO VARCHAR(150),
BDVALOR NUMERIC(15,6),
BDCODCID INTEGER,
BDCODCIDTOT INTEGER,
BDCODNAT INTEGER,
BDDATAREC DATE,
BDCLAVENDIMEGERQ12 INTEGER,
BDCODRECDIMEGERQ12 INTEGER,
BDORIGEMDIMEGERQ46 INTEGER,
BDIDENTIFICACAOREGESP VARCHAR(15),
BDSIGLAUF VARCHAR(2),
BDVLRCONT NUMERIC(15,6),
BDVLRBC NUMERIC(15,6),
BDVLRIMPOSTO NUMERIC(15,6),
BDVLRISENTRIB NUMERIC(15,6),
BDVLROUTRAS NUMERIC(15,6),
BDVLRICMSSTPE NUMERIC(15,6),
BDVLRICMSSTOP NUMERIC(15,6),
BDVLRCONTCONT NUMERIC(15,6),
BDVLRBCCONT NUMERIC(15,6),
BDVLRICMSST NUMERIC(15,6),
BDNUMITEM INTEGER,
BDCODTIPO INTEGER,
BDBASEST NUMERIC(15,6),
BDICMSRETST NUMERIC(15,6),
BDDIFALIQENT NUMERIC(15,6),
BDALIMPREP VARCHAR(5),
BDCODEXP48 VARCHAR(3),
    BDNUMACORDOQ12 varchar(15),
    BDCODBENEFTTD integer,
    BDNUMCONCTTD varchar(20),
    BDCODTIPCRED integer,
    BDVLRBCICMS numeric(15,2),
    BDVLRICMSEXON numeric(15,2),
    BDORDEMFUMDES integer,
    BDVLRFUMDES numeric(15,2),
    BDORDEMFUNSOC integer,
    BDVLRFUNSOC numeric(15,2),
    BDVLRBCICMSDEV numeric(15,2),
    BDVLRICMSEXONDEV numeric(15,2),
    BDVLRFUMDESDEV numeric(15,2),
    BDVLRFUNSOCDEV numeric(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG1_18(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDNOMEMP DM_BDNOMEMP,
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDSIGLAUFEMP VARCHAR(2),
BDCODCIDEMP INTEGER,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDDDDFAXEMP INTEGER,
BDFAXEMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDNOMSOC VARCHAR(80),
BDDDDSOC INTEGER,
BDTELRESSOC VARCHAR(15),
BDDDDFAXSOC INTEGER,
BDFAXSOC VARCHAR(9),
BDCGCCEISOC VARCHAR(18),
BDEMAILSOC DM_BDEMAIL,
BDCODCONT INTEGER,
BDNOMECONT VARCHAR(40),
BDCRCCONT VARCHAR(15),
BDSIGLAUFCONT VARCHAR(2),
BDCPFCONT VARCHAR(14),
BDDDDCONT INTEGER,
BDFONECONT DM_BDTELEFONE,
BDDDDFAXCONT INTEGER,
BDFAXCONT DM_BDTELEFONE,
BDEMAILCONT DM_BDEMAIL,
BDVLRRECBRU1_6_IRLP NUMERIC(15,6),
BDVLRRECBRU8_IRLP NUMERIC(15,6),
BDVLRRECBRU16_IRLP NUMERIC(15,6),
BDVLRRECBRU32_IRLP NUMERIC(15,6),
BDVLRLUCROPRESUMIDO_IRLP NUMERIC(15,6),
BDVLRADICIONAL_IRLP NUMERIC(15,6),
BDVLRIMPOSTOPAGAR_IRLP NUMERIC(15,6),
BDVLRIMPOSTORETIDO_IRLP NUMERIC(15,6),
BDVLRALIQ15_IRLP NUMERIC(15,6),
BDVLRCSLLAPAGAR_IRLP NUMERIC(15,6),
BDVLRRECBRU12_IRLP NUMERIC(15,6),
BDVLRRECBRUAJUST_IRLP NUMERIC(15,6),
BDVLRCSLLAPURADA_IRLP NUMERIC(15,6),
BDVLRCSLLRETPJ NUMERIC(15,6),
BDREFERENCIA INTEGER,
BDTRIMESTRE INTEGER,
BDVLRRECBRU32_CSLL NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG1_3(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDNOMEMP DM_BDNOMEMP,
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDSIGLAUFEMP VARCHAR(2),
BDCODCIDEMP INTEGER,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDDDDFAXEMP INTEGER,
BDFAXEMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDNOMSOC VARCHAR(80),
BDDDDSOC INTEGER,
BDTELRESSOC VARCHAR(15),
BDDDDFAXSOC INTEGER,
BDFAXSOC VARCHAR(9),
BDCGCCEISOC VARCHAR(18),
BDEMAILSOC DM_BDEMAIL,
BDCODCONT INTEGER,
BDNOMECONT VARCHAR(40),
BDCRCCONT VARCHAR(15),
BDSIGLAUFCONT VARCHAR(2),
BDCPFCONT VARCHAR(14),
BDDDDCONT INTEGER,
BDFONECONT DM_BDTELEFONE,
BDDDDFAXCONT INTEGER,
BDFAXCONT DM_BDTELEFONE,
BDEMAILCONT DM_BDEMAIL,
BDVLRRECBRU1_6_IRLP NUMERIC(15,6),
BDVLRRECBRU8_IRLP NUMERIC(15,6),
BDVLRRECBRU16_IRLP NUMERIC(15,6),
BDVLRRECBRU32_IRLP NUMERIC(15,6),
BDVLRLUCROPRESUMIDO_IRLP NUMERIC(15,6),
BDVLRADICIONAL_IRLP NUMERIC(15,6),
BDVLRIMPOSTOPAGAR_IRLP NUMERIC(15,6),
BDVLRIMPOSTORETIDO_IRLP NUMERIC(15,6),
BDVLRALIQ15_IRLP NUMERIC(15,6),
BDVLRCSLLAPAGAR_IRLP NUMERIC(15,6),
BDVLRRECBRU12_IRLP NUMERIC(15,6),
BDVLRRECBRUAJUST_IRLP NUMERIC(15,6),
BDVLRCSLLAPURADA_IRLP NUMERIC(15,6),
BDVLRCSLLRETPJ NUMERIC(15,6),
BDREFERENCIA INTEGER,
BDTRIMESTRE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG20(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDEXISTEMOV INTEGER,
BDPERIODO INTEGER,
BDMES INTEGER,
BDVLRSALDOCREANT NUMERIC(15,6),
BDVLRDEBITO NUMERIC(15,6),
BDVLRCREDITO NUMERIC(15,6),
BDVLRSALDO NUMERIC(15,6),
BDCREDORDEVEDOR INTEGER,
BDSEQUENCIAL INTEGER,
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG21(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDVLRINSUMOSNACIONAL NUMERIC(15,6),
BDVLRMERCADORIASNACIONAL NUMERIC(15,6),
BDVLRINDUSTOUTRASEMPNACIONAL NUMERIC(15,6),
BDVLRDEVVENDASNACIONAL NUMERIC(15,6),
BDVLROUTRASENTNACIONAL NUMERIC(15,6),
BDVLRINSUMOSEXTERIOR NUMERIC(15,6),
BDVLRMERCADORIASEXTERIOR NUMERIC(15,6),
BDVLRDEVVENDASEXTERIOR NUMERIC(15,6),
BDVLROUTRASENTEXTERIOR NUMERIC(15,6),
BDCOLUNA INTEGER,
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG22(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDVLRPRODNACIONAL NUMERIC(15,6),
BDVLRMERCADORIASNACIONAL NUMERIC(15,6),
BDVLRINDUSTOUTRASEMPNACIONAL NUMERIC(15,6),
BDVLRDEVCOMPRASNACIONAL NUMERIC(15,6),
BDVLROUTRASSAINACIONAL NUMERIC(15,6),
BDVLRPRODEXTERIOR NUMERIC(15,6),
BDVLRMERCADORIASEXTERIOR NUMERIC(15,6),
BDVLRINDUSTOUTRASEMPEXTERIOR NUMERIC(15,6),
BDVLRDEVCOMPRASEXTERIOR NUMERIC(15,6),
BDVLROUTRASSAIEXTERIOR NUMERIC(15,6),
BDCOLUNA INTEGER,
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG23(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDCGCTER VARCHAR(18),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG24(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDNCMPROD INTEGER,
BDCODPROD INTEGER,
BDCODSAIDA VARCHAR(60),
BDCODIGOEAN VARCHAR(20),
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDDESCPROD VARCHAR(200),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG25(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDCGCTER VARCHAR(18),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG26(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDNCMPROD INTEGER,
BDCODPROD INTEGER,
BDCODSAIDA VARCHAR(60),
BDCODIGOEAN VARCHAR(20),
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDDESCPROD VARCHAR(200),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG60_61A(PREMPRESAS VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRCODPAISBRASIL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODFED INTEGER,
BDTIPOPESSOA INTEGER,
BDCGCCEISOC VARCHAR(18),
BDCODSOC INTEGER,
BDNOMSOC VARCHAR(200),
BDEXPQUALISOC INTEGER,
BDCAPTOTCOTA NUMERIC(15,6),
BDCAPVOLCOTA NUMERIC(15,6),
BDCPFRESPLEGALSOC VARCHAR(14),
BDEXPQUALIRESPSOC INTEGER,
BDREMTRACOTA NUMERIC(15,6),
BDRENISECOTA NUMERIC(15,6),
BDRENTRICOTA NUMERIC(15,6),
BDDEMRENCOTA NUMERIC(15,6),
BDIRFONTCOTA NUMERIC(15,6),
BDSEQUENCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_GIASP(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(5),
BDDESCFORM VARCHAR(150),
BDCODNAT INTEGER,
BDVALOR NUMERIC(18,6),
BDVLRCONT NUMERIC(18,6),
BDBASEICMS NUMERIC(18,6),
BDVLRICMS NUMERIC(18,6),
BDISENTASICMS NUMERIC(18,6),
BDOUTRASICMS NUMERIC(18,6),
BDVLRST NUMERIC(18,6),
BDIMPSUBSTITUTO NUMERIC(18,6),
BDIMPSUBSTITUIDO NUMERIC(18,6),
BDOUTROSIMPOSTOS NUMERIC(18,6),
BDUF_R14 VARCHAR(2),
BDVALOR_CONTABIL_1_R14 NUMERIC(18,6),
BDBASECALCULO_1_R14 NUMERIC(18,6),
BDVALOR_CONTABIL_2_R14 NUMERIC(18,6),
BDBASECALCULO_2_R14 NUMERIC(18,6),
BDIMPOSTO_R14 NUMERIC(18,6),
BDOUTRAS_R14 NUMERIC(18,6),
BDICMSCOBRADOST_R14 NUMERIC(18,6),
BDPETROLEOENERGIA_R14 NUMERIC(18,6),
BDOUTROS_PRODUTOS_R14 NUMERIC(18,6),
BDCODIGO_R20 INTEGER,
BDOPERACAO_R20 INTEGER,
BDFUNLEGAL_R20 VARCHAR(250),
BDDESCRICAO_R20 VARCHAR(250),
BDINSCESTREM_R25 VARCHAR(15),
BDCODAUTORIZACAO_R28 VARCHAR(14),
BDVLRCONT1 NUMERIC(18,6),
BDBASEICMS1 NUMERIC(18,6),
BDVLRCONT2 NUMERIC(18,6),
BDBASEICMS2 NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_GISSONLINE(PREMPRESAS VARCHAR(10000),
PRTIPOLANC SMALLINT,
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRIGNORACID varchar(5))
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDNOMEMP DM_BDNOMEMP,
BDCODCIDEMP INTEGER,
BDNUMDOCINI VARCHAR(15),
BDNUMDOCFIN VARCHAR(15),
BDSERIE VARCHAR(6),
BDDATAEMISSAO DATE,
BDVLRCONTAB NUMERIC(15,6),
BDCODMUNATVM VARCHAR(20),
BDCODLOCEXP VARCHAR(1),
BDCODTPNFEXP VARCHAR(2),
BDCODOBRA VARCHAR(10),
BDCONSTCIVIL VARCHAR(5),
BDCODTER INTEGER,
BDCGCTER VARCHAR(18),
BDNOMETER VARCHAR(100),
BDCEPTER VARCHAR(9),
BDLOGRTER DM_LOGRADOURO,
BDENDTER DM_BDENDERECO,
BDNUMTER DM_NUMEND,
BDCOMPTER DM_BDCOMPENDERECO,
BDBAITER VARCHAR(60),
BDCODCIDTER INTEGER,
BDIMTER VARCHAR(16),
BDIETER VARCHAR(20),
BDSIGLAUFTER VARCHAR(2),
BDNOMCIDTER VARCHAR(40),
BDCODENQFEDTER INTEGER,
BDTIPOREG CHAR,
BDTIPLAN VARCHAR(1),
BDCODSITNF INTEGER,
BDBCISSSER NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_TERCEIRO(PREMPRESA VARCHAR(2048),
PRCODTER INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRWHERETER VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCGCTER VARCHAR(18),
BDREFEMP INTEGER,
BDAPELIDOTER VARCHAR(20),
BDNOMETER VARCHAR(100),
BDLOGRTER DM_LOGRADOURO,
BDENDTER DM_BDENDERECO,
BDNUMTER DM_NUMEND,
BDCOMPTER DM_BDCOMPENDERECO,
BDCEPTER VARCHAR(9),
BDBAITER DM_BDBAIRRO,
BDDDDTER VARCHAR(3),
BDFONETER DM_BDTELEFONE,
BDFAXTER DM_BDTELEFONE,
BDEMAILTER DM_BDEMAIL,
BDIETER VARCHAR(20),
BDDATACADTER DATE,
BDIMTER VARCHAR(16),
BDPRURALTER VARCHAR(5),
BDENQSIMPLESFEDTER INTEGER,
BDINSCSUFRAMATER VARCHAR(10),
BDCODGPS INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDCODPAIS INTEGER,
BDDESCPAIS VARCHAR(60),
BDDDDFAXTER VARCHAR(3),
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_TNATOP(PREMPRESA VARCHAR(2048),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODNAT INTEGER,
BDNOMENAT VARCHAR(255))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_TPRODUTOS(PREMPRESA VARCHAR(2048),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODPROD INTEGER,
BDNOMEPROD VARCHAR(255))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_GET_VALOR_ISE_OUT (
    PRCODEMP INTEGER NOT NULL,
    PRREF INTEGER NOT NULL,
    PRCODNAT INTEGER NOT NULL,
    PRISE_OR_OUT CHAR(1) NOT NULL,
    PRVLRCONTAB DM_NUMERIC_15_2,
    PRBCISS DM_NUMERIC_15_2,
    PRVLRISE DM_NUMERIC_15_2,
    PRVLROUT DM_NUMERIC_15_2)
RETURNS (
    BDVLR DM_NUMERIC_15_2)
AS
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE VEF_SP_LANCAMENTOS(PRREFMICRO INTEGER,
PRCODEMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDPERCISS NUMERIC(15,6),
BDRETINSS VARCHAR(5),
BDVLRMININSS NUMERIC(15,2),
BDCODPLANOONLINE INTEGER,
BDLANPROENT VARCHAR(5),
BDLANPROSAI VARCHAR(5),
BDLANBCICMSISEOUT INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_REL_CONFERENCIA_ICMSST (
    PRCODEMP VARCHAR(2500),
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRTIPOLAN INTEGER,
    PRTOTAIS VARCHAR(5) = 'FALSE')
RETURNS (
    BDCODEMP INTEGER,
    BDCHAVE INTEGER,
    BDORDEM INTEGER,
    BDCODMOV INTEGER,
    BDMOVIMENTO VARCHAR(7),
    BDTIPOMOV VARCHAR(4),
    BDDATA DATE,
    BDDATAIMP VARCHAR(10),
    BDNUMDOCINI INTEGER,
    BDCODTER INTEGER,
    BDNOMETER VARCHAR(47),
    BDCODUFTER INTEGER,
    BDUFTER VARCHAR(2),
    BDCODNAT VARCHAR(9),
    BDVLRCONTAB NUMERIC(15,2),
    BDBASE NUMERIC(15,2),
    BDALIQ NUMERIC(7,4),
    BDVALOR NUMERIC(15,2),
    BDOUTRAS NUMERIC(15,2),
    BDVARALIQ VARCHAR(5),
    BDIMPLINHA VARCHAR(5))
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_RETORNA_DIME_Q47(PRCODEMP VARCHAR(2048),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRSIMPLIFICADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREF INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDVALOR NUMERIC(15,2),
BDCODCIDTOT INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_RETORNA_DIME_Q48(PRCODEMP VARCHAR(2048),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRSIMPLIFICADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREF INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDCODCIDTOT INTEGER,
BDALIMPREP VARCHAR(5),
BDCODEXP VARCHAR(3),
BDCODATIVQ48 VARCHAR(3),
BDVALOR NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_RETORNA_DIME_VENC_PRODEC(PRCODEMP INTEGER,
PRREF INTEGER)
 RETURNS(BDDATAVENC DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SPED_LAN_ENT_PRO(PRREF INTEGER,
PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDORDEMPRO INTEGER,
BDCODCTA INTEGER,
BDCODPROD INTEGER,
BDCODCSTCOF INTEGER,
BDCODCSTICMS INTEGER,
BDCODCSTPIS INTEGER,
BDCODCSTIPI INTEGER,
BDMOVFISICO VARCHAR(5),
BDQTDITEM NUMERIC(15,6),
BDVLRITEM NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRDESPACESSORIA NUMERIC(15,6),
BDREDBCICMS NUMERIC(15,6),
BDBCICMS NUMERIC(15,6),
BDBCPIS NUMERIC(15,6),
BDBCST NUMERIC(15,6),
BDBCIPI NUMERIC(15,6),
BDBCCOFINS NUMERIC(15,6),
BDBCISSQN NUMERIC(15,6),
BDALIQICMS NUMERIC(15,6),
BDALIQPIS NUMERIC(15,6),
BDALIQST NUMERIC(15,6),
BDALIQIPI NUMERIC(15,6),
BDALIQCOFINS NUMERIC(15,6),
BDALIQISSQN NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRPIS NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRCOFINS NUMERIC(15,6),
BDVLRISSQN NUMERIC(15,6),
BDDESCPROD VARCHAR(200),
BDCSTICMS VARCHAR(3),
BDCODEXPCSTIPI INTEGER,
BDAPEUNIMEDFAT VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SPED_LAN_SAI_PRO(PRREF INTEGER,
PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDORDEMPRO INTEGER,
BDCODCTA INTEGER,
BDCODPROD INTEGER,
BDCODCSTCOF INTEGER,
BDCODCSTICMS INTEGER,
BDCODCSTPIS INTEGER,
BDCODCSTIPI INTEGER,
BDMOVFISICO VARCHAR(5),
BDQTDITEM NUMERIC(15,6),
BDVLRITEM NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRDESPACESSORIA NUMERIC(15,6),
BDREDBCICMS NUMERIC(15,6),
BDBCICMS NUMERIC(15,6),
BDBCPIS NUMERIC(15,6),
BDBCST NUMERIC(15,6),
BDBCIPI NUMERIC(15,6),
BDBCCOFINS NUMERIC(15,6),
BDBCISSQN NUMERIC(15,6),
BDALIQICMS NUMERIC(15,6),
BDALIQPIS NUMERIC(15,6),
BDALIQST NUMERIC(15,6),
BDALIQIPI NUMERIC(15,6),
BDALIQCOFINS NUMERIC(15,6),
BDALIQISSQN NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRPIS NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRCOFINS NUMERIC(15,6),
BDVLRISSQN NUMERIC(15,6),
BDDESCPROD VARCHAR(200),
BDCSTICMS VARCHAR(3),
BDCODEXPCSTIPI INTEGER,
BDCODCLAENETEL INTEGER,
BDINDREC INTEGER,
BDCODCLAENETELGAS INTEGER,
BDINDRECGAS INTEGER,
BDCODSELOIPI INTEGER,
BDQTDSELOIPI INTEGER,
BDCODCLASSEIPI VARCHAR(5),
BDVLRUNIDADE NUMERIC(15,6),
BDQTDUNIDADE NUMERIC(15,6),
BDAPEUNIMEDFAT VARCHAR(5),
BDCODSAIDA VARCHAR(60))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_431(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRENTRADA VARCHAR(5),
PRSAIDA VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDMODELOAUX VARCHAR(15),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDORDEM INTEGER,
BDVLRCONTAB NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDIMPEXCLUIDAS NUMERIC(15,6),
BDOUTROSIMP NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDICMSRETENT NUMERIC(15,6),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRIPIPRO NUMERIC(15,6),
BDVLRICMSPRO NUMERIC(15,6),
BDVLRFRETEC100 NUMERIC(15,6),
BDVLRSEGUROC100 NUMERIC(15,6),
BDVLROUTDESPC100 NUMERIC(15,6),
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDVLRCSOCIAL NUMERIC(15,2),
BDVLRIR NUMERIC(15,2),
BDINSSRET NUMERIC(15,2),
BDCGCTER VARCHAR(18),
BDORDEMPRO INTEGER,
BDTIPOREG VARCHAR(10),
BDALIQPIS NUMERIC(5,2),
BDALIQCOFINS NUMERIC(5,2),
BDALIQIR NUMERIC(5,2),
BDALIQCSOCIAL NUMERIC(5,2),
BDBINSSRET NUMERIC(15,2),
BDRETVAZIO VARCHAR(1),
BDVLRCONTAB2 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SPED_D600 (
    PREMPRESA INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE)
RETURNS (
    BDCHAVES VARCHAR(20000),
    BDQUANTIDADE INTEGER,
    BDMODELO INTEGER,
    BDCODIBGE INTEGER,
    BDSERIE VARCHAR(6),
    BDSUBSERIE VARCHAR(6),
    BDCODEXP VARCHAR(2),
    BDDATAEMISSAO DATE,
    BDVALORNOTA NUMERIC(15,6),
    BDVLRSER NUMERIC(15,6),
    BDVLRSERNTRIB NUMERIC(15,6),
    BDVLRCOBTERC NUMERIC(15,6),
    BDVLROUTDESP NUMERIC(15,6))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SPED_D610 (
    PREMPRESA INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE)
RETURNS (
    BDCHAVES VARCHAR(20000),
    BDMODELO INTEGER,
    BDCODIBGE INTEGER,
    BDSERIE VARCHAR(6),
    BDSUBSERIE VARCHAR(6),
    BDCODEXP VARCHAR(2),
    BDDATAEMISSAO DATE,
    BDCODNAT VARCHAR(4),
    BDCODPROD INTEGER,
    BDCODSAIDA VARCHAR(60),
    BDCODCSTICMS INTEGER,
    BDALIQICMS NUMERIC(15,6),
    BDCLASSENETEL VARCHAR(4),
    BDQTDITEM INTEGER,
    BDAPEUNIMED VARCHAR(20),
    BDVLRITEM NUMERIC(15,6),
    BDVLRDESC NUMERIC(15,6),
    BDCSTICMS VARCHAR(3),
    BDBCICMS NUMERIC(15,6),
    BDVLRICMS NUMERIC(15,6),
    BDVLRPRODPIS NUMERIC(15,6),
    BDVLRPRODCOFINS NUMERIC(15,6),
    BDVLRDESPACESSORIA NUMERIC(15,6),
    BDBCST NUMERIC(15,6),
    BDVLRST NUMERIC(15,6))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SPED_D696 (
    PREMPRESA INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE)
RETURNS (
    BDCHAVES VARCHAR(10000),
    BDMODELO INTEGER,
    BDSERIE VARCHAR(6),
    BDCODNAT VARCHAR(4),
    BDCODCSTICMS INTEGER,
    BDALIQICMS NUMERIC(15,6),
    BDVLRITEM NUMERIC(15,6),
    BDCSTICMS VARCHAR(3),
    BDBCICMS NUMERIC(15,6),
    BDVLRICMS NUMERIC(15,6),
    BDBCST NUMERIC(15,6),
    BDVLRST NUMERIC(15,6))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_4310_TREDZ(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDDATAREDZ DATE,
BDCODPROD INTEGER,
BDQTDITEM NUMERIC(15,3),
BDALIQICMS NUMERIC(15,2),
BDCAMPO8 NUMERIC(15,2),
BDVLRTOTPRO NUMERIC(15,2),
BDALIQPIS NUMERIC(15,4),
BDVLRPIS NUMERIC(15,2),
BDALIQCOFINS NUMERIC(15,4),
BDVLRCOFINS NUMERIC(15,2),
BDNCMPROD INTEGER,
BDTIPOREG VARCHAR(10))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_432(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRENTRADA VARCHAR(5),
PRSAIDA VARCHAR(5),
PRODFRETE INTEGER,
PRODENERGIA INTEGER,
PRODAGUA INTEGER,
PRODTELECOM INTEGER,
PRODGENERICO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDORDEM INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDBASEICMS NUMERIC(15,2),
BDBASEIPI NUMERIC(15,2),
BDBASEST NUMERIC(15,2),
BDISENTASICMS NUMERIC(15,2),
BDISENTASIPI NUMERIC(15,2),
BDOUTRASICMS NUMERIC(15,2),
BDOUTRASIPI NUMERIC(15,2),
BDVLRICMS NUMERIC(15,2),
BDVLRIPI NUMERIC(15,2),
BDVLRST NUMERIC(15,2),
BDIMPEXCLUIDAS NUMERIC(15,2),
BDOUTROSIMP NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDICMSRETENT NUMERIC(15,2),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,2),
BDVLRDESC NUMERIC(15,2),
BDVLRIPIPRO NUMERIC(15,2),
BDVLRICMSPRO NUMERIC(15,2),
BDVLRFRETEC100 NUMERIC(15,2),
BDVLRSEGUROC100 NUMERIC(15,2),
BDVLROUTDESPC100 NUMERIC(15,2),
BDORDEMPRO INTEGER,
BDCODPROD INTEGER,
BDDESCPROD VARCHAR(200),
BDCODNAT INTEGER,
BDNCMPROD INTEGER,
BDQTDITEM NUMERIC(15,3),
BDAPEUNIMED VARCHAR(3),
BDALIQIPIPRO NUMERIC(15,2),
BDBCIPIPRO NUMERIC(15,2),
BDCODCSTICMS VARCHAR(3),
BDALIQICMSPRO NUMERIC(15,2),
BDBCICMSPRO NUMERIC(15,2),
BDBCSTPRO NUMERIC(15,2),
BDVLRSTMOVPRO NUMERIC(15,2),
BDMOVFISICO VARCHAR(5),
BDCODEXPCSTIPI INTEGER,
BDCODCSTPIS INTEGER,
BDALIQPIS NUMERIC(15,4),
BDBCPIS NUMERIC(15,3),
BDVLRPIS NUMERIC(15,2),
BDCODCSTCOF INTEGER,
BDALIQCOFINS NUMERIC(15,4),
BDBCCOFINS NUMERIC(15,3),
BDVLRCOFINS NUMERIC(15,2),
BDCSTPIS VARCHAR(3),
BDCSTCOF VARCHAR(3),
BDVLRUNITARIO NUMERIC(15,4),
BDVLRCOFINSEXP NUMERIC(15,2),
BDVLRCOFINSTRIBINT NUMERIC(15,2),
BDVLRCOFINSNTRIBINT NUMERIC(15,2),
BDVLRPISEXP NUMERIC(15,2),
BDVLRPISTRIBINT NUMERIC(15,2),
BDVLRPISNTRIBINT NUMERIC(15,2),
BDLANBCICMSISEOUT INTEGER,
BDTIPOREG VARCHAR(10),
BDPRODFRETE VARCHAR(5),
BDPRODENERGIA VARCHAR(5),
BDPRODAGUA VARCHAR(5),
BDPRODTELECOM VARCHAR(5),
BDPRODGENERICO VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_433(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDCGCTER VARCHAR(18),
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDVLRCONTAB NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDIMPEXCLUIDAS NUMERIC(15,6),
BDOUTROSIMP NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDICMSRETENT NUMERIC(15,6),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRDESPACESSORIAPRO NUMERIC(15,6),
BDVLRIPIPRO NUMERIC(15,6),
BDVLRICMSPRO NUMERIC(15,6),
BDTIPOREG VARCHAR(10),
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDVLRCSOCIAL NUMERIC(15,2),
BDALIQPIS NUMERIC(5,2),
BDALIQCOFINS NUMERIC(5,2),
BDALIQIR NUMERIC(5,2),
BDALIQCSOCIAL NUMERIC(5,2),
BDVLRIR NUMERIC(15,2),
BDINSSRET NUMERIC(15,2),
BDVLRPISRET NUMERIC(15,2),
BDVLRCOFINSRET NUMERIC(15,2),
BDVLRCSLLRET NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_434(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRODFRETE INTEGER,
PRODENERGIA INTEGER,
PRODAGUA INTEGER,
PRODTELECOM INTEGER,
PRODGENERICO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDORDEM INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDBASEICMS NUMERIC(15,2),
BDBASEIPI NUMERIC(15,2),
BDBASEST NUMERIC(15,2),
BDISENTASICMS NUMERIC(15,2),
BDISENTASIPI NUMERIC(15,2),
BDOUTRASICMS NUMERIC(15,2),
BDOUTRASIPI NUMERIC(15,2),
BDVLRICMS NUMERIC(15,2),
BDVLRIPI NUMERIC(15,2),
BDVLRST NUMERIC(15,2),
BDIMPEXCLUIDAS NUMERIC(15,2),
BDOUTROSIMP NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDICMSRETENT NUMERIC(15,2),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,2),
BDVLRDESC NUMERIC(15,2),
BDVLRIPIPRO NUMERIC(15,2),
BDVLRICMSPRO NUMERIC(15,2),
BDVLRFRETEC100 NUMERIC(15,2),
BDVLRSEGUROC100 NUMERIC(15,2),
BDVLROUTDESPC100 NUMERIC(15,2),
BDORDEMPRO INTEGER,
BDCODPROD INTEGER,
BDDESCPROD VARCHAR(200),
BDCODNAT INTEGER,
BDNCMPROD INTEGER,
BDQTDITEM NUMERIC(15,3),
BDAPEUNIMED VARCHAR(3),
BDALIQIPIPRO NUMERIC(15,2),
BDBCIPIPRO NUMERIC(15,2),
BDCODCSTICMS VARCHAR(3),
BDALIQICMSPRO NUMERIC(15,2),
BDBCICMSPRO NUMERIC(15,2),
BDBCSTPRO NUMERIC(15,2),
BDVLRSTMOVPRO NUMERIC(15,2),
BDMOVFISICO VARCHAR(5),
BDCODEXPCSTIPI INTEGER,
BDCODCSTPIS INTEGER,
BDALIQPIS NUMERIC(15,4),
BDBCPIS NUMERIC(15,3),
BDVLRPIS NUMERIC(15,2),
BDCODCSTCOF INTEGER,
BDALIQCOFINS NUMERIC(15,4),
BDBCCOFINS NUMERIC(15,3),
BDVLRCOFINS NUMERIC(15,2),
BDCGCTER VARCHAR(18),
BDCAMPO10 NUMERIC(15,2),
BDCAMPO11 NUMERIC(15,2),
BDCAMPO12 NUMERIC(15,2),
BDCAMPO17 NUMERIC(15,2),
BDCAMPO18 NUMERIC(15,2),
BDCAMPO19 NUMERIC(15,2),
BDVLRUNITARIO NUMERIC(15,4),
BDLANBCICMSISEOUT INTEGER,
BDTIPOREG VARCHAR(10),
BDPRODFRETE VARCHAR(5),
BDPRODENERGIA VARCHAR(5),
BDPRODAGUA VARCHAR(5),
BDPRODTELECOM VARCHAR(5),
BDPRODGENERICO VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_491(PREMPRESA VARCHAR(10000),
PRCODTER INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDDATACADTER DATE,
BDCODTER INTEGER,
BDCGCTER VARCHAR(18),
BDIETER VARCHAR(20),
BDIMTER VARCHAR(16),
BDNOMETER VARCHAR(100),
BDLOGRTER DM_LOGRADOURO,
BDENDTER DM_BDENDERECO,
BDENDEXPTER DM_BDENDERECO,
BDNUMTER DM_NUMEND,
BDCOMPTER DM_BDCOMPENDERECO,
BDBAITER VARCHAR(60),
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDCEPTER VARCHAR(9),
BDDESCPAIS VARCHAR(60),
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDCODCGCTER VARCHAR(18))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_494(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDCODNAT INTEGER,
BDNOMENAT VARCHAR(255),
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_495(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRPROD VARCHAR(10000))
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDCODPROD INTEGER,
BDNOMEPROD VARCHAR(255),
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_EXP_491(PREMPRESA VARCHAR(10000),
PRCODTER INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_EXP_494(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_EXP_495(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_EXP_CAD(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_SERVICOS_ITENS(PREMPRESA VARCHAR(10000),
PRTIPOLAN INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRODSERVICO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDCODCID INTEGER,
BDTIPOMOV VARCHAR(3),
BDDATAEMISSAO DATE,
BDCODTER INTEGER,
BDNUMDOC INTEGER,
BDTIPLAN VARCHAR(1),
BDESPECIE VARCHAR(6),
BDSERIE VARCHAR(5),
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDORDEM INTEGER,
BDCODNAT INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDALIQIRSER NUMERIC(15,2),
BDBCIRSER NUMERIC(15,2),
BDVLRIRSER NUMERIC(15,2),
BDVLRISSSER NUMERIC(15,2),
BDIDCFPS INTEGER,
BDCODREC INTEGER,
BDCODOBS INTEGER,
BDIDCST INTEGER,
BDCONDPGTO INTEGER,
BDCONDPGTOAUX VARCHAR(1),
BDALIQREDBCISSSER NUMERIC(15,2),
BDBCISSSER NUMERIC(15,2),
BDALIQREDISSSER NUMERIC(15,2),
BDISENTASISSSER NUMERIC(15,2),
BDOUTRASISSSER NUMERIC(15,2),
BDACREDEDUIRSER NUMERIC(15,2),
BDACRECFINSER NUMERIC(15,2),
BDDIGOPERNAT INTEGER,
BDPREFIXONAT INTEGER,
BDCODATVM INTEGER,
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDCAMPO10 VARCHAR(1),
BDTIPOREG VARCHAR(10),
BDCODCSTPIS VARCHAR(2),
BDALIQPIS NUMERIC(15,4),
BDBCPIS NUMERIC(15,3),
BDCODCSTCOF VARCHAR(2),
BDALIQCOFINS NUMERIC(15,4),
BDBCCOFINS NUMERIC(15,3),
BDCAMPO07_4106 NUMERIC(15,2),
BDCAMPO14_4106 NUMERIC(15,2),
BDVLRCONTAB_4106 NUMERIC(15,3),
BDCAMPO10_4106 NUMERIC(15,2),
BDCAMPO17_4106 NUMERIC(15,2),
BDDESCPROD VARCHAR(45),
BDPRODSERVICO VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_SERVICOS_MOV(PREMPRESA VARCHAR(10000),
PRTIPOLAN INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDDATAEMISSAO DATE,
BDCODTER INTEGER,
BDNUMDOC INTEGER,
BDTIPLAN VARCHAR(1),
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6),
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDVLRCONTAB NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDALIQIRSER NUMERIC(15,2),
BDBCIRSER NUMERIC(15,2),
BDVLRIRSER NUMERIC(15,2),
BDVLRISSSER NUMERIC(15,2),
BDIDCFPS INTEGER,
BDCODREC INTEGER,
BDIDCST INTEGER,
BDALIQREDBCISSSER NUMERIC(15,2),
BDBCISSSER NUMERIC(15,2),
BDALIQREDISSSER NUMERIC(15,2),
BDISENTASISSSER NUMERIC(15,2),
BDOUTRASISSSER NUMERIC(15,2),
BDACREDEDUIRSER NUMERIC(15,2),
BDACRECFINSER NUMERIC(15,2),
BDDIGOPERNAT INTEGER,
BDPREFIXONAT INTEGER,
BDCODATVM INTEGER,
BDCAMPO10 VARCHAR(1),
BDTIPOREG VARCHAR(10),
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDVLRCSOCIAL NUMERIC(15,2),
BDALIQPIS NUMERIC(5,2),
BDALIQCOFINS NUMERIC(5,2),
BDALIQCSOCIAL NUMERIC(5,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_TREEVIEW_CONS_ANUAL_CONF(PRCODEMP VARCHAR(10000),
PRREF INTEGER,
PRCODPLANO INTEGER,
PRCODQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDREF INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDORDEM INTEGER,
BDDESCRICAO VARCHAR(80),
BDVALOR NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDJAN NUMERIC(15,6),
BDFEV NUMERIC(15,6),
BDMAR NUMERIC(15,6),
BDABR NUMERIC(15,6),
BDMAI NUMERIC(15,6),
BDJUN NUMERIC(15,6),
BDJUL NUMERIC(15,6),
BDAGO NUMERIC(15,6),
BDSET NUMERIC(15,6),
BDOUT NUMERIC(15,6),
BDNOV NUMERIC(15,6),
BDDEZ NUMERIC(15,6),
BDCODMATRIZ INTEGER,
BDREGAUX INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CRIA_PRE_CONTABILIZACAODIFAL (
    PRSESSAO INTEGER,
    PRCODPLANOONLINE INTEGER,
    PRTIPOLAN VARCHAR(5),
    PREF INTEGER)
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_CRIA_PRE_CONTABILIZACAO_AUX (
    PRSESSAO INTEGER,
    PRCODPLANOONLINE INTEGER,
    prtipolan VARCHAR(4),
    prTipoIntDesc INTEGER)
AS
BEGIN

END^

create or alter procedure SP_CRIA_CONTAB_RET_FUNRURAL (
    PRSESSAO integer,
    PRCODPLANOONLINE integer,
    PRENQFED integer,
    PRTIPOLAN varchar(5),
    PRFORMATRIBUTACAO integer = 0)
as
BEGIN

END^

create or alter procedure SP_CRIA_PRE_CONTABILIZACAO_RET (
    PRSESSAO integer,
    PRCODPLANOONLINE integer,
    PRENQFED integer,
    PRTIPOLAN varchar(5),
    PRFORMATRIBUTACAO integer = 0)
as
BEGIN

END^

create or alter procedure SP_CRIA_PRE_CONTABILIZACAO (
    PRSESSAO integer,
    PRCODPLANOONLINE integer,
    PRENQFED integer,
    PRCODCONFIRLP integer,
    PRTIPOLAN varchar(5),
    PRCODCONFDIMESC integer = 0,
    PRFORMATRIBUTACAO integer = 0)
as
BEGIN

END^

CREATE OR ALTER PROCEDURE VLAL_COPIA_PARTEA_PLANO(APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VLAL_COPIA_PARTEB_PLANO(APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VLAL_SP_CONS_ACUM_PARTEA(PRCODEMP INTEGER,
PRCODLPA INTEGER,
PRCODTIPO INTEGER,
PRREFLANAN VARCHAR(10))
 RETURNS(BDREFLANAN INTEGER,
BDCODTHPI INTEGER,
BDNOME VARCHAR(40),
BDVALLANAN NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VLAL_SP_LAN_PARTEA(PREMPRESA INTEGER,
PRCODLLA INTEGER,
PRCODUSU INTEGER,
PRANOBASE INTEGER,
PRCODPARTEA INTEGER,
PRCODLPA INTEGER,
PRCODTPHI INTEGER,
PRANUALACUMULADO SMALLINT,
PRVALOR1 NUMERIC(15,2),
PRCOMPL1 VARCHAR(200),
PRVALOR2 NUMERIC(15,2),
PRCOMPL2 VARCHAR(200),
PRVALOR3 NUMERIC(15,2),
PRCOMPL3 VARCHAR(200),
PRVALOR4 NUMERIC(15,2),
PRCOMPL4 VARCHAR(200),
PRVALOR5 NUMERIC(15,2),
PRCOMPL5 VARCHAR(200),
PRVALOR6 NUMERIC(15,2),
PRCOMPL6 VARCHAR(200),
PRVALOR7 NUMERIC(15,2),
PRCOMPL7 VARCHAR(200),
PRVALOR8 NUMERIC(15,2),
PRCOMPL8 VARCHAR(200),
PRVALOR9 NUMERIC(15,2),
PRCOMPL9 VARCHAR(200),
PRVALOR10 NUMERIC(15,2),
PRCOMPL10 VARCHAR(200),
PRVALOR11 NUMERIC(15,2),
PRCOMPL11 VARCHAR(200),
PRVALOR12 NUMERIC(15,2),
PRCOMPL12 VARCHAR(200),
PRREFEMP INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VLAL_SP_RETORNA_INT_CONTABLALUR(PRCODEMP VARCHAR(2048),
PRMATRIZFILIAL VARCHAR(2048),
PRCODCONTABLALUR INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRACUMULADO INTEGER,
PRDATALANC DATE,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRTIPOLANC INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRREFERENCIA INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRINTCONTABILLALUR INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA VARCHAR(7),
BDMESANO INTEGER,
BDDATA DATE,
BDCONTA INTEGER,
BDVALOR NUMERIC(15,2),
BDTIPOLANC INTEGER,
BDCODTPLA INTEGER,
BDCHAVELAN INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VLAL_SP_DEMONSTRACAO_PARTEB (
    PRCODEMP INTEGER,
    PRDATAINICIALREL DATE,
    PRDATAINICIAL DATE,
    PRDATAFINAL DATE,
    PRMODELOREL INTEGER,
    PRREFERENCIA INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCODLLB INTEGER,
    BDCODPARTEB INTEGER,
    BDNOMPARTEB VARCHAR(40),
    BDINDICE INTEGER,
    BDDEBCODLPB INTEGER,
    BDCTALONLPBDEB VARCHAR(20),
    BDNOMLPBDEB VARCHAR(60),
    BDDEBVALLLB INTEGER,
    BDCRECODPLB INTEGER,
    BDCTALONLPBCRE VARCHAR(20),
    BDNOMLPBCRE VARCHAR(60),
    BDCREVALLLB INTEGER,
    BDCODLPB INTEGER,
    BDCTALONLPB VARCHAR(20),
    BDNOMLPB VARCHAR(60),
    BDDATLLB DATE,
    BDVALLLB NUMERIC(15,2),
    BDSALANT NUMERIC(15,2),
    BDSALATU NUMERIC(15,2),
    BDCOMPLLLB VARCHAR(200),
    BDCOMPENSACAO DM_BOOLEAN,
    BDMODELO VARCHAR(10))
AS
 BEGIN SUSPEND; END
^


CREATE OR ALTER PROCEDURE VRH_COPIA_FUNCOES_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VRH_COPIA_LAYOUT_PLALANC(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VRH_COPIA_VERBASBS_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VRH_INS_VERBA(PRCLASS VARCHAR(9))
 RETURNS(VERBATITULO INTEGER,
NOVAVERBA INTEGER,
NOVACLASS VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_ALTERACAOSALARIAL(PREMPRESA VARCHAR(15000),
PRCOLABORADOR VARCHAR(15000),
PRDATAINICIAL DATE,
PRDATAFINAL DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATACOL DATE,
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDDESCMAS VARCHAR(50),
BDCODTFUC INTEGER,
BDDESCTFUC VARCHAR(40),
BDCODCBO INTEGER,
BDTIPOCOL INTEGER,
BDSALINICOL NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_AUMENTOSALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDATAADMCOL DATE,
BDDATACOL DATE,
BDSALBASECOLANT NUMERIC(15,2),
BDSALBASECOLATU NUMERIC(15,2),
BDCODMAS INTEGER,
BDDESCMAS VARCHAR(50),
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDCODTFUC INTEGER,
BDDESCTFUC VARCHAR(40),
BDHORASMENSAISCOL NUMERIC(15,2),
BDTIPOCOL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_CAD_TERC(PRCODCOL VARCHAR(32700),
PRCODCLA VARCHAR(1000),
PRREF INTEGER,
PRCOLCON SMALLINT,
PRCOLCON_DOC SMALLINT,
PRCOLCON_VINC SMALLINT,
PRCOLCON_BANCO SMALLINT,
PRCOLCON_CALC SMALLINT,
PRCOLCON_FGTSGPS SMALLINT,
PRCOLCON_MVINC SMALLINT,
PRCOLCON_DIA SMALLINT)
 RETURNS(BDCODCOL INTEGER,
BDCODMCAG INTEGER,
BDCODCID INTEGER,
BDCODCSEG INTEGER,
BDREFCSEG INTEGER,
BDCODCIDNASC INTEGER,
BDCODUF INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDLOGRCOL VARCHAR(15),
BDENDCOL DM_BDENDERECO,
BDNUMCOL DM_NUMEND,
BDCOMPLCOL DM_BDCOMPENDERECO,
BDBAICOL DM_BDBAIRRO,
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL DM_BDTELEFONE,
BDCELCOL DM_BDTELEFONE,
BDEMAILCOL DM_BDEMAIL,
BDSEXOCOL INTEGER,
BDDATANASCCOL DATE,
BDDATACADCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDRGCOL VARCHAR(13),
BDORGEMIRGCOL DM_ORGAOEMISSOR,
BDDATAEMIRGCOL DATE,
BDCPFCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDCODUF_COL_DOC INTEGER,
BDTITELEICOL VARCHAR(13),
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDCATCNHCOL VARCHAR(2),
BDCODCID_HIST INTEGER,
BDCODPAIS INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDDATACHEBRASILCOL DATE,
BDCODCIDNASCCONJ INTEGER,
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCONJCOL DATE,
BDCORCOL INTEGER,
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDDEFFISICOCOL INTEGER,
BDTIPOSANGUECOL INTEGER,
BDNROCONSPROCOL VARCHAR(20),
BDSIGLACONSPROCOL VARCHAR(5),
BDCODCCMPROCOL VARCHAR(15),
BDCODCLA INTEGER,
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDCODSINTRAB INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOADMCOL INTEGER,
BDNATUOCUPCOL INTEGER,
BDDATAINIAQUICOL DATE,
BDSALINICOL NUMERIC(15,6),
BDDIASPRAZO1COL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDIASPRAZO2COL INTEGER,
BDDATAFIMPRAZO2COL DATE,
BDDESCCONTSINCOL VARCHAR(5),
BDVINCEMPCOL INTEGER,
BDALVARACOL VARCHAR(5),
BDSINDICALIZADOCOL VARCHAR(5),
BDREGIMEPARCIALCOL VARCHAR(5),
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDOBSCOL BLOB,
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODCBO INTEGER,
BDCODCBOTSIN INTEGER,
BDCODQH INTEGER,
BDCODPRES INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAHOM DATE,
BDDATAPAGRESCISAO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDCALCFGTSMESANT VARCHAR(5),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDATAPAGGRFC DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDDISSIDIO VARCHAR(5),
BDDATADISSIDIO DATE,
BDDESCANSOINDENIZADO VARCHAR(5),
BDCODMFGRESC INTEGER,
BDCODSAQUERESC INTEGER,
BDCODMRAISRESC INTEGER,
BDCODMCAGRESC INTEGER,
BDDESCPRES VARCHAR(110),
BDINIPRES INTEGER,
BDJCPRES VARCHAR(5),
BDAVPREPRES INTEGER,
BDGRRFPRES INTEGER,
BDESTPRES VARCHAR(5),
BDINDFER13 VARCHAR(5),
BDTERMCONTRPRES VARCHAR(5),
BDMULTAPRES VARCHAR(5),
BDDIASAVPREPRES INTEGER,
BDDIASPAGPRES INTEGER,
BDCODSEFMFGRESC VARCHAR(5),
BDDESCMFGRESC VARCHAR(255),
BDDESCSAQUERESC VARCHAR(60),
BDDESCMRAISRESC VARCHAR(255),
BDDESCMCAGEDRESC VARCHAR(255),
BDCODEMPDESTTRAN INTEGER,
BDCODPTRAN INTEGER,
BDCODCOLTRANS INTEGER,
BDDATATRANS DATE,
BDCODMCAGENTTRANS INTEGER,
BDCODMCAGSAITRANS INTEGER,
BDCODMFGTRANS INTEGER,
BDCODMRAISTRANS INTEGER,
BDDESCPTRANS VARCHAR(60),
BDCODSEFMFGTRANS VARCHAR(5),
BDDESCMFGTRANS VARCHAR(255),
BDDESCRAISTRANS VARCHAR(255),
BDDESCMCAGEDENTTRANS VARCHAR(255),
BDDESCMCAGEDSAITRANS VARCHAR(255))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_COLCON(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRCODSIN VARCHAR(1000),
PRCODCLA VARCHAR(1000),
PRCODFUC VARCHAR(1000),
PRREF INTEGER,
PRULTDIA DATE,
PRCOLCON SMALLINT,
PRCOLCON_DOC SMALLINT,
PRCOL_DOC SMALLINT,
PRCOL_HIST SMALLINT,
PRCOL_PARENT SMALLINT,
PRCOL_FIS SMALLINT,
PRCON_DOC SMALLINT,
PRCOLCON_VINC SMALLINT,
PRCOL_VINC SMALLINT,
PRCOLCON_BANCO SMALLINT,
PRCOLCON_CALC SMALLINT,
PRCOLCON_FGTSGPS SMALLINT,
PRCOLCON_MVINC SMALLINT,
PRCOL_ADM SMALLINT,
PRCOL_CALC SMALLINT,
PRCOL_HISTF SMALLINT,
PRCON_VINC SMALLINT,
PRCOLCON_DIA SMALLINT,
PRFILTRARESC SMALLINT,
PRFILTRATRANS SMALLINT,
PRFILTRASIT SMALLINT,
PRFILTRAFERIAS SMALLINT,
PRFILTRA13SALARIO SMALLINT,
PRFILTRAFOLHANORMAL SMALLINT,
PRREFFOLHANORMAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODMCAG INTEGER,
BDCODCID INTEGER,
BDCODCSEG INTEGER,
BDREFCSEG INTEGER,
BDCODCIDNASC INTEGER,
BDCODUF INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDLOGRCOL VARCHAR(15),
BDENDCOL DM_BDENDERECO,
BDNUMCOL DM_NUMEND,
BDCOMPLCOL DM_BDCOMPENDERECO,
BDBAICOL DM_BDBAIRRO,
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL DM_BDTELEFONE,
BDCELCOL DM_BDTELEFONE,
BDEMAILCOL DM_BDEMAIL,
BDSEXOCOL INTEGER,
BDDATANASCCOL DATE,
BDDATACADCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCONTRCOL INTEGER,
BDRGCOL VARCHAR(13),
BDORGEMIRGCOL DM_ORGAOEMISSOR,
BDDATAEMIRGCOL DATE,
BDCPFCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDCODUF_COL_DOC INTEGER,
BDTITELEICOL VARCHAR(13),
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDCATCNHCOL VARCHAR(2),
BDCODCID_HIST INTEGER,
BDCODPAIS INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDDATACHEBRASILCOL DATE,
BDCODCIDNASCCONJ INTEGER,
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCONJCOL DATE,
BDCORCOL INTEGER,
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDDEFFISICOCOL INTEGER,
BDTIPOSANGUECOL INTEGER,
BDNROCONSPROCOL VARCHAR(20),
BDSIGLACONSPROCOL VARCHAR(5),
BDCODCCMPROCOL VARCHAR(15),
BDCODCLA INTEGER,
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDCODSINTRAB INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOADMCOL INTEGER,
BDNATUOCUPCOL INTEGER,
BDDATAINIAQUICOL DATE,
BDSALINICOL NUMERIC(15,6),
BDDIASPRAZO1COL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDIASPRAZO2COL INTEGER,
BDDATAFIMPRAZO2COL DATE,
BDDESCCONTSINCOL VARCHAR(5),
BDVINCEMPCOL INTEGER,
BDALVARACOL VARCHAR(5),
BDSINDICALIZADOCOL VARCHAR(5),
BDREGIMEPARCIALCOL VARCHAR(5),
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDOBSCOL BLOB SUB_TYPE 1 SEGMENT SIZE 5000,
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(18,6),
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODQH INTEGER,
BDCODPRES INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAHOM DATE,
BDDATAPAGRESCISAO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDCALCFGTSMESANT VARCHAR(5),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDATAPAGGRFC DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDDISSIDIO VARCHAR(5),
BDDATADISSIDIO DATE,
BDDESCANSOINDENIZADO VARCHAR(5),
BDCODMFGRESC INTEGER,
BDCODSAQUERESC INTEGER,
BDCODMRAISRESC INTEGER,
BDCODMCAGRESC INTEGER,
BDDESCPRES VARCHAR(110),
BDINIPRES INTEGER,
BDJCPRES VARCHAR(5),
BDAVPREPRES INTEGER,
BDGRRFPRES INTEGER,
BDESTPRES VARCHAR(5),
BDINDFER13 VARCHAR(5),
BDTERMCONTRPRES VARCHAR(5),
BDMULTAPRES VARCHAR(5),
BDDIASAVPREPRES INTEGER,
BDDIASPAGPRES INTEGER,
BDCODSEFMFGRESC VARCHAR(5),
BDDESCMFGRESC VARCHAR(255),
BDDESCSAQUERESC VARCHAR(60),
BDDESCMRAISRESC VARCHAR(255),
BDDESCMCAGEDRESC VARCHAR(255),
BDCODEMPDESTTRAN INTEGER,
BDCODPTRAN INTEGER,
BDCODCOLTRANS INTEGER,
BDDATATRANS DATE,
BDCODMCAGENTTRANS INTEGER,
BDCODMCAGSAITRANS INTEGER,
BDCODMFGTRANS INTEGER,
BDCODMRAISTRANS INTEGER,
BDDESCPTRANS VARCHAR(60),
BDCODSEFMFGTRANS VARCHAR(5),
BDDESCMFGTRANS VARCHAR(255),
BDDESCRAISTRANS VARCHAR(255),
BDDESCMCAGEDENTTRANS VARCHAR(255),
BDDESCMCAGEDSAITRANS VARCHAR(255))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_COLCON_EDIT(BDCOL SMALLINT,
BDCON SMALLINT,
BDTER SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(100),
BDTIPO VARCHAR(15))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_CONS_CBO_SIN RETURNS(BDCODCBO INTEGER,
BDCODCBOTSIN INTEGER,
BDDESCCBO VARCHAR(70))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_CONS_COL(WREFERENCIA INTEGER,
WEMPRESA INTEGER,
WFILTRO VARCHAR(500),
PRULTDIAMES DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDCODCLA INTEGER,
BDDATAADMCOL DATE,
BDGRUPOCLA INTEGER,
BDTIPOCOL INTEGER,
BDDATARESCISAO DATE,
BDDESCCLA VARCHAR(40),
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDSALBASECOL NUMERIC(15,6),
BDCODSIT INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER procedure VRH_SP_CONS_COL_NOVO (
    WREFERENCIA integer,
    WEMPRESA integer,
    WFILTRO varchar(500),
    PRULTDIAMES date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDCODCLA integer,
    BDDATAADMCOL date,
    BDGRUPOCLA integer,
    BDTIPOCOL integer,
    BDDATARESCISAO date,
    BDDESCCLA varchar(40),
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDSALBASECOL numeric(15,6),
    BDCODSIT integer,
    BDCODPRES integer,
    BDDESCPRES varchar(110),
    BDCODTFUC integer,
    BDDESCTFUC varchar(40),
    BDSTATUSQC integer,
    BDSTATUS_ES integer,
    BDCODTIPO integer,
    BDINTESOCIAL integer,
    BDDATAEVENTO date,
    BDMATRICULA varchar(30),
    BDDATAENTRADA date,
    BDGERARNMSOCIAL varchar(5),
    BDNMSOCIAL varchar(100))
AS
BEGIN
    SUSPEND;
END
^

CREATE OR ALTER PROCEDURE VRH_SP_CONS_COLCON(WREFERENCIA INTEGER,
WEMPRESA INTEGER,
PRULTDIAMES DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADMCOL DATE,
BDTIPOCOL INTEGER,
BDCODCLA INTEGER,
BDDATARESCISAO DATE,
BDDESCCLA VARCHAR(40),
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDSALBASECOL NUMERIC(15,6),
BDCODSIT INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER procedure VRH_SP_CONS_CON (
    WREFERENCIA integer,
    WEMPRESA integer,
    WFILTRO varchar(500))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDDATAADMCOL date,
    BDCODCLA integer,
    BDGRUPOCLA integer,
    BDDESCCLA varchar(40),
    BDDATARESCISAO date,
    BDSALBASECOL numeric(18,6),
    BDCODPRES integer,
    BDDESCPRES varchar(110),
    BDSTATUSQC integer,
    BDSTATUS_ES integer,
    BDCODTIPO integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure VRH_SP_CONS_FERIAS_PER_AQUIS (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDINIPERGOZOFE date,
    BDFIMPERAQUISFE date,
    BDFIMPERGOZOFE date,
    BDDATAPAGFE date,
    BDQTDGOZOFE numeric(18,6),
    BDQTDABONOFE numeric(18,6),
    BDSALDOINIFE numeric(15,6),
    BDSALDOFIMFE numeric(15,6),
    BDBASEIRFE numeric(15,6),
    BDALIQIRFE numeric(15,6),
    BDVALORIRFE numeric(15,6),
    BDBASEINSSFE numeric(15,6),
    BDALIQINSSFE numeric(15,6),
    BDVALORINSSFE numeric(15,6),
    BDDEPFE numeric(15,6),
    BDSALBASEFE numeric(15,6),
    BDSALBASEHEFE numeric(15,6),
    BDDATABAIXAFE date,
    BDCOLETIVASFE varchar(5),
    BDREFPAGABOFE integer,
    BDFALTASFE numeric(15,6),
    BDNOMEMP DM_BDNOMEMP,
    BDNOMCOL DM_BDNOMCOL,
    BDSALDOFINALSINDFE numeric(18,6),
    BDCALCA13FE varchar(5),
    BDTIPOA13FE integer,
    BDPERCA13FE numeric(18,6),
    BDRECIBOESOCIAL varchar(30),
    BDINIGOZORECIBOFE date,
    BDFIMGOZORECIBOFE date,
    BDQTDGOZORECIBOFE numeric(18,6),
    BDISTRANSFERENCIA boolean)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_CONS_VERBAS(WREFERENCIA INTEGER,
WVERBAS VARCHAR(32700),
WTAMANHOCLASSE INTEGER)
 RETURNS(BDCODVER INTEGER,
BDCLAVER VARCHAR(20),
BDAPEVER VARCHAR(20),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDORDEMVER INTEGER,
BDINATIVAVER VARCHAR(5),
BDSITVER INTEGER,
BDTIPOVER INTEGER,
BDTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDIRVER INTEGER,
BDFGTSVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDMENORESVER VARCHAR(5),
BDPROPVER VARCHAR(5),
BDBASEVTVER VARCHAR(5),
BDREEMBGPSVER VARCHAR(5),
BDHEVER NUMERIC(15,6),
BDGRAVAFICHAHNVER VARCHAR(5),
BDCCPRINCIPALVER VARCHAR(5),
BDFORMREFVER VARCHAR(5000),
BDFORMVALVER VARCHAR(5000),
BDFORMINTVER VARCHAR(5000),
BDBASEDSRHEVER VARCHAR(5),
BDBASEDSRRVVER VARCHAR(5),
BDREFVER INTEGER,
BDFORMREFAUXVER VARCHAR(5000),
BDDEDFORMREFAUXVER VARCHAR(5),
BDDEDFORMREFVER VARCHAR(5),
BDDEDFORMVALVER VARCHAR(5),
BDRENDISENTOIRVER VARCHAR(5),
BDSITMATVER VARCHAR(5),
BDSITDOEVER VARCHAR(5),
BDSITACITRABVER VARCHAR(5),
BDSITMILITARVER VARCHAR(5),
BDSITMATEMPVER VARCHAR(5),
BDSITACITRAB15VER VARCHAR(5),
BDSITDOETRABVER VARCHAR(5),
BDSITLICVENCVER VARCHAR(5),
BDSITDOE15VER VARCHAR(5),
BDSITSINDICALVER VARCHAR(5),
BDSITAPOINVVER VARCHAR(5),
BDSITOUTRASVER VARCHAR(5),
BDPAGAESTOUROVER DM_BOOLEAN,
BDGARANTIAMINVER DM_BOOLEAN,
BDINDRESC DM_BOOLEAN,
BDNAOCONVHORASVER DM_BOOLEAN,
BDBASEDSRHNVER DM_BOOLEAN,
BDBASEDSROUVER DM_BOOLEAN)
 AS
 BEGIN SUSPEND; END
^

--Sol. 15188 - 22/09/2016 - Alterada a procedure VRH_SP_CONSULTA_SITUACAO para retornar todos os campos da tabela VRH_EMP_TSITCOL - Bruno L. R.
create or alter procedure VRH_SP_CONSULTA_SITUACAO (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCODSIT integer,
    BDDESCSIT varchar(70),
    BDDATAINISEFIP date,
    BDDATAINISIT date,
    BDDATAFIMSIT date,
    BDDIASSIT integer,
    BDNBENEFICIOSIT varchar(20),
    BDDATAPERICIASIT date,
    BDDATAPARTOSIT date,
    BDDATAESTAB date,
    BDCODDOE integer,
    BDDESCDOE varchar(300),
    BDTIPOACID varchar(50),
    BDCODMED integer,
    BDNOMMED varchar(60),
    BDCODSINTRAB integer,
    BDDESCSINTRAB varchar(60),
    BDOBSERVACAO varchar(255),
    BDGRUPOSIT integer,
    BDCODEVTINICIO integer,
    BDCODEVTFIM integer,
    BDRECIBOESOCIALINICIO char(30),
    BDRECIBOESOCIALFIM char(30),
    BDCOVID19 DM_BOOLEAN,
    BDBENEFDEFERIDO DM_BOOLEAN,
    BDCODSITAUX integer,
    BDDESCSITAUX varchar(70),
    BDGRUPOSITAUX integer,
    BDDATAINIATESTADOAUX date,
    BDDATAFIMATESTADOAUX date,
    BDDATAINIAFASTAUX date,
    BDDATAFIMAFASTAUX date,
    BDDIASDOCUMENTO integer,
    BDDIASATESTADOAUX integer,
    BDDIASAFASTAUX integer,
    BDAFASDECORRENTE boolean
    )
AS
BEGIN SUSPEND; END
^

create or alter procedure VRH_SP_EMPRESAS (
    PREMP varchar(10000),
    PRREF integer,
    PRPROVISAO smallint = 0)
returns (
    BDCODMATRIZ integer,
    BDCODEMP integer,
    BDCODCID integer,
    BDCODUF integer,
    BDCODPLAFUC integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCENTROS integer,
    BDPAGEMP integer,
    BDFECHAMESEMP integer,
    BDFECHAVTEMP integer,
    BDARREMP integer,
    BDTIPOARREMP integer,
    BDTIPOFEREMP integer,
    BDSOMSALFEREMP varchar(5),
    BDTIPOAD13EMP integer,
    BDSOMSALAD13EMP varchar(5),
    BDPERCADSALEMP numeric(15,6),
    BDREFHOREMP varchar(5),
    BDLICREMFEREMP varchar(5),
    BDESTOUROEMP varchar(5),
    BDESTOURORESEMP varchar(5),
    BDFALFEREMP varchar(5),
    BDFALHORFEREMP varchar(5),
    BDDEPIRRESCEMP varchar(5),
    BDCODGPS integer,
    BDCODTERC integer,
    BDCODFPAS integer,
    BDCNAERATEMP numeric(15,6),
    BDEMPEMP numeric(15,6),
    BDAUTEMP numeric(15,6),
    BDFUNEMP numeric(15,6),
    BDCODSINPAT integer,
    BDCAPSOCEMP numeric(15,6),
    BDETIQEMP varchar(5),
    BDTAXSEREMP numeric(15,6),
    BDREFCAGEDEMP integer,
    BDPROPADMEMP integer,
    BDPROPRESEMP integer,
    BDPROPFEREMP integer,
    BDPROPSITEMP integer,
    BDCALCMEDIASTEMP integer,
    BDNATESTEMP integer,
    BDDATABASEEMP integer,
    BDPATEMP varchar(5),
    BDNROPROPEMP integer,
    BDSERPROPRIOPATEMP integer,
    BDPATREFCONVENIOEMP integer,
    BDPATCESTAALIMENTOEMP integer,
    BDPATADMCOZINHAEMP integer,
    BDPATREFTRANSPEMP integer,
    BDPATALICONVENIOEMP integer,
    BDSINDICALIZEMP varchar(5),
    BDCODBAN integer,
    BDCODAG integer,
    BDIDENTEMP varchar(14),
    BDCATSEFIPEMP integer,
    BDISENFILEMP numeric(15,6),
    BDCETRTALIZAEMP integer,
    BDCODIR integer,
    BDCODINSS integer,
    BDCODMEN integer,
    BDCALCFCNAFNEMP varchar(5),
    BDCALCC13NAFNEMP varchar(5),
    BDTIPOCONTAB integer,
    BDTIPOEMIGUIAS integer,
    BDFAP numeric(15,6),
    BDTAXACNAEEMP numeric(15,6),
    BDPERTERC numeric(15,6),
    BDPERCPIS numeric(15,6),
    BDLIMINARAVPREVEMP integer,
    BDSIMPLESGPS integer,
    BDMESDSREMP integer,
    BDCODPLACONVSAU integer,
    BDARREDONDAFN DM_BOOLEAN,
    BDARREDONDAFC DM_BOOLEAN,
    BDARREDONDAFE DM_BOOLEAN,
    BDARREDONDAA13 DM_BOOLEAN,
    BDARREDONDA13 DM_BOOLEAN,
    BDARREDONDAC13 DM_BOOLEAN,
    BDARREDONDAAD DM_BOOLEAN,
    BDARREDONDAAU DM_BOOLEAN,
    BDARREDONDAFA DM_BOOLEAN,
    BDPAGEMPCONTR integer,
    BDDESCFALHORASDIAS DM_BOOLEAN,
    BDPERCLIMIDESCPAR numeric(15,6),
    BDCALCC13FNNEGEMP DM_BOOLEAN,
    BDDSRMEDATUSAL DM_BOOLEAN,
    BDDATAINITABELA     DATE,
    BDDATAININAOPERIOD  DATE,
    BDDATAINIPERIOD     DATE,
    BDDATAINISST        DATE,
    BDREFINITABELA      INTEGER,
    BDREFININAOPERIOD   INTEGER,
    BDREFINIPERIOD      INTEGER,
    BDREFINISST         INTEGER,
    BDOPCAOESOCIAL      INTEGER,
    BDGRUPO             INTEGER,
    BDREFINIDCTFWEB     INTEGER,
    BDDATAINIRT         DATE,
    BDDATAFGTSDIGITAL   DATE)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRH_SP_GRRF (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32700),
    PRANOMES integer,
    PRDATAPAGTO date,
    PRPRIDIA date,
    PRULTDIA date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODPRES integer,
    BDREFRESCISAO integer,
    BDDATARESCISAO date,
    BDDATAAVPREVIO date,
    BDREPOSICAOVAGA varchar(5),
    BDSALDOFGTS numeric(15,6),
    BDDATAHOM date,
    BDDATAPAGGRFC date,
    BDDATADISSIDIO date,
    BDAVPREPRES integer,
    BDCODSEFMFG varchar(5),
    BDCODSAQUE integer,
    BDBFGTS numeric(15,6),
    BDBFGTSMESANT numeric(15,6),
    BDVALINDEN numeric(15,6),
    BDCNPJEMP varchar(18),
BDNOMEMP DM_BDNOMEMP,
    BDLOGREMP varchar(15),
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP varchar(9),
    BDDDDEMP integer,
BDFONEEMP DM_BDTELEFONE,
    BDCODCNAE integer,
    BDCODCONT integer,
    BDSIMPLESGPS integer,
    BDCODFPAS integer,
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
BDNOMCOL DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDSEXOCOL integer,
    BDGRAUINSTCOL integer,
    BDDATANASCCOL date,
    BDCONTRCOL integer,
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDCATEGORIACOL integer,
    BDOCORRENCIACOL integer,
    BDDATAOPCAOFGTSCOL date,
    BDHORASSEMANAISCOL numeric(15,6),
    BDCODCBO varchar(4),
    BDTAMCNPJ integer,
    BDNOMREDUZEMP DM_BDNOMREDUZEMP,
    BDFGTSSEMIND numeric(15,6),
    BDSITEMP DM_BOOLEAN,
    BDBLOQUEIOGRRF DM_BOOLEAN)
as
 BEGIN SUSPEND; END
^

create or alter procedure VRH_SP_GRRF_FC (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32700),
    PRANOMES integer,
    PRDATAPAGTO date,
    PRCODTIPOFC integer = null,
    PRCHAVEDARF integer = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODPRES integer,
    BDDATARESCISAO date,
    BDDATAAVPREVIO date,
    BDREPOSICAOVAGA varchar(5),
    BDSALDOFGTS numeric(15,6),
    BDDATAHOM date,
    BDDATAPAGGRFC date,
    BDDATADISSIDIO date,
    BDAVPREPRES integer,
    BDCODSEFMFG varchar(5),
    BDCODSAQUE integer,
    BDBFGTS numeric(15,6),
    BDBFGTSMESANT numeric(15,6),
    BDVALINDEN numeric(15,6),
    BDCNPJEMP varchar(18),
BDNOMEMP DM_BDNOMEMP,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP varchar(9),
    BDDDDEMP integer,
BDFONEEMP DM_BDTELEFONE,
    BDCODCNAE integer,
    BDCODCONT integer,
    BDSIMPLESGPS integer,
    BDCODFPAS integer,
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
BDNOMCOL DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDSEXOCOL integer,
    BDGRAUINSTCOL integer,
    BDDATANASCCOL date,
    BDCONTRCOL integer,
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDCATEGORIACOL integer,
    BDOCORRENCIACOL integer,
    BDDATAOPCAOFGTSCOL date,
    BDHORASSEMANAISCOL numeric(15,6),
    BDCODCBO varchar(4),
    BDTAMCNPJ integer,
BDNOMREDUZEMP DM_BDNOMREDUZEMP,
    BDFGTSSEMIND numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDVALOR numeric(15,6),
    BDSITEMP DM_BOOLEAN,
    BDBLOQUEIOGRRF DM_BOOLEAN)
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_LISTAADM_RESC(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRANOMESINI INTEGER,
PRANOMESFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRFILTRAADM INTEGER,
PRFILTRARESC INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDATAADM DATE,
BDDATARESCISAO DATE,
BDDATATRF DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_LISTAADM_RESC_TOT_EMP(PRCODEMP VARCHAR(10000),
PRANOMESANT INTEGER,
PRANOMESATU INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRFILTRAADM INTEGER,
PRFILTRARESC INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCAMPOC INTEGER,
BDCAMPOD INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_UNION_FT_MES (
    PRCODEMP integer,
    PRANOMES integer,
    PRFILTROCC varchar(20000) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFTOMADOR integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCODVER integer,
    BDREFVFN_SUM numeric(15,6),
    BDREFAUXVFN_SUM numeric(15,6),
    BDREFVFN_MAX numeric(15,6),
    BDREFAUXVFN_MAX numeric(15,6),
    BDVALVFT numeric(15,6),
    BDORDEM integer)
as
BEGIN
  SUSPEND;
END
^

create or alter procedure VRH_SP_REL_RECIBO_FOLHA_NORMAL (
    PRCODEMP integer,
    PRREF integer,
    PRCODCLA varchar(10000),
    PRCODTPCC varchar(20000) = null /* COLLATE WIN1252 - default */ ,
    PRDATAINI date = null,
    PRDATAFIM date = null,
    PRSEMFERIAS smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFVFN_SUM numeric(15,6),
    BDREFVFN_MAX numeric(15,6),
    BDREFAUXVFN_SUM numeric(15,6),
    BDREFAUXVFN_MAX numeric(15,6),
    BDVALVFN numeric(15,6),
    BDDATAFN integer,
    BDSALBASE numeric(15,6),
    BDBINSS numeric(15,6),
    BDBINSSAP numeric(15,6),
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDCNPJEMP varchar(18),
    BDDESCVER varchar(40),
    BDDESCREDVER varchar(20),
    BDORDEMVER integer,
    BDNOMCOL varchar(70),
    BDDATAADMCOL date,
    BDPISCOL varchar(14),
    BDCPFCOL varchar(14),
    BDRG varchar(13),
    BDTIPOCODVER integer,
    BDORDEMTIPOCODVER integer,
    BDTIPOREFVER integer,
    BDCODBAN integer,
    BDCODAG integer,
    BDCTADEPCOL varchar(15),
    BDDIGCTADEPCOL varchar(2),
    BDMODOPAGTOCOL integer,
    BDCLAVER varchar(20),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDEMAILCOL varchar(400),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDQTDSALARIOHE integer,
    BDORDEM integer,
    BDNIVELORDEM integer,
    BDIMPCOD DM_BOOLEAN)
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER procedure VRH_SP_RELATORIO_CAT2 (
    PRCODEMP varchar(32000),
    PRCODCOL varchar(32000),
    PRCHAVE integer,
    PRULTIMODIA date,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCHAVE integer,
    BDCODCID integer,
    BDDATAACIDENTE date,
    BDDATAEMISSAO date,
    BDDATAULTIMODIA date,
    BDDATAOBITO date,
    BDEMITENTE integer,
    BDNRCAT varchar(25),
    BDCATORIGEM varchar(25),
    BDTIPOAFAST integer,
    BDREGPOLICIAL varchar(5),
    BDAFASTAMENTO varchar(5),
    BDHORAACIDENTE time,
    BDTIPOCAT integer,
    BDLOCALACIDENTE integer,
    BDESPLOCALACIDENTE varchar(255),
    BDOBJETOCAUSADORACID varchar(10000),
    BDDESCACIDENTE blob sub_type 1 segment size 210,
    BDPARTESATINGIDAS varchar(10000),
    BDAREAACIDENTE integer,
    BDHOUVEOBITO varchar(5),
    BDREMUNMENSAL integer,
    BDNOMEMP DM_BDNOMEMP,
    BDBAIEMP DM_BDBAIRRO,
    BDCODCNAE integer,
    BDNUMEMP DM_NUMEND,
    BDENDEMP DM_BDENDERECO,
    BDLOGREMP varchar(15),
    BDCEPEMP varchar(9),
    BDDDDEMP integer,
    BDFONEEMP DM_BDTELEFONE,
    BDCNPJEMP varchar(18),
    BDNOMCOL DM_BDNOMCOL,
    BDNOMMAECOL varchar(70),
    BDDATANASCCOL date,
    BDCPFCOL varchar(14),
    BDSEXOCOL integer,
    BDESTCIVCOL integer,
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDDATAEMICTPSCOL date,
    BDRGCOL varchar(13),
    BDDATAEMIRGCOL date,
    BDORGEMIRGCOL varchar(30),
    BDPISCOL varchar(14),
    BDLOGRCOL varchar(15),
    BDENDCOL DM_BDENDERECO,
    BDNUMCOL DM_NUMEND,
    BDBAICOL DM_BDBAIRRO,
    BDCEPCOL varchar(9),
    BDDDDCOL integer,
    BDFONECOL DM_BDTELEFONE,
    BDFILIACAOPREV integer,
    BDAPOSENTADO integer,
    BDNOMCIDACID varchar(40),
    BDUFACID varchar(2),
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
    BDNOMECIDCOL varchar(40),
    BDUFCOL varchar(2),
    BDUFCTPS varchar(2),
    BDDESCCBO varchar(150),
    BDCODCBO integer,
    BDSALBASECOL numeric(15,6),
    BDUFRG varchar(2),
    BDDDDCELCOL integer,
    BDCELCOL DM_BDTELEFONE,
    BDTIPOCOL integer,
    BDHORASMENSAISCOL numeric(15,6),
    BDDTAPOSENT date,
    BDDATARETORNO date,
    BDLATERALIDADE integer,
    BDINICIATIVA integer,
    BDEXCLUIDO DM_BOOLEAN,
    BDRECIBOESOC varchar(30),
    BDRECIBORETEXC varchar(30),
    BDSITUACAOGERADORA varchar(210))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_SERV_TERC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRSERV VARCHAR(1000),
PRCODCLA VARCHAR(1000),
PRREF INTEGER,
PRINICIO DATE,
PRFIM DATE,
PRCOLCON SMALLINT,
PRCOLCON_DOC SMALLINT,
PRCOLCON_VINC SMALLINT,
PRCOLCON_BANCO SMALLINT,
PRCOLCON_CALC SMALLINT,
PRCOLCON_FGTSGPS SMALLINT,
PRCOLCON_MVINC SMALLINT,
PRCOLCON_DIA SMALLINT)
 RETURNS(BDCODSERV INTEGER,
BDDATASERV DATE,
BDDATAPAGSERV DATE,
BDHORASERV TIME,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODMCAG INTEGER,
BDCODCID INTEGER,
BDCODCSEG INTEGER,
BDREFCSEG INTEGER,
BDCODCIDNASC INTEGER,
BDCODUF INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDLOGRCOL VARCHAR(15),
BDENDCOL DM_BDENDERECO,
BDNUMCOL DM_NUMEND,
BDCOMPLCOL DM_BDCOMPENDERECO,
BDBAICOL DM_BDBAIRRO,
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL DM_BDTELEFONE,
BDCELCOL DM_BDTELEFONE,
BDEMAILCOL DM_BDEMAIL,
BDSEXOCOL INTEGER,
BDDATANASCCOL DATE,
BDDATACADCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDRGCOL VARCHAR(13),
BDORGEMIRGCOL DM_ORGAOEMISSOR,
BDDATAEMIRGCOL DATE,
BDCPFCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDCODUF_COL_DOC INTEGER,
BDTITELEICOL VARCHAR(13),
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDCATCNHCOL VARCHAR(2),
BDCODCID_HIST INTEGER,
BDCODPAIS INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDDATACHEBRASILCOL DATE,
BDCODCIDNASCCONJ INTEGER,
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCONJCOL DATE,
BDCORCOL INTEGER,
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDDEFFISICOCOL INTEGER,
BDTIPOSANGUECOL INTEGER,
BDNROCONSPROCOL VARCHAR(20),
BDSIGLACONSPROCOL VARCHAR(5),
BDCODCCMPROCOL VARCHAR(15),
BDCODCLA INTEGER,
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDCODSINTRAB INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOADMCOL INTEGER,
BDNATUOCUPCOL INTEGER,
BDDATAINIAQUICOL DATE,
BDSALINICOL NUMERIC(15,6),
BDDIASPRAZO1COL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDIASPRAZO2COL INTEGER,
BDDATAFIMPRAZO2COL DATE,
BDDESCCONTSINCOL VARCHAR(5),
BDVINCEMPCOL INTEGER,
BDALVARACOL VARCHAR(5),
BDSINDICALIZADOCOL VARCHAR(5),
BDREGIMEPARCIALCOL VARCHAR(5),
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDOBSCOL BLOB,
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDCODCBO INTEGER,
BDCODQH INTEGER,
BDCODPRES INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAHOM DATE,
BDDATAPAGRESCISAO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDCALCFGTSMESANT VARCHAR(5),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDATAPAGGRFC DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDDISSIDIO VARCHAR(5),
BDDATADISSIDIO DATE,
BDDESCANSOINDENIZADO VARCHAR(5),
BDCODMFGRESC INTEGER,
BDCODSAQUERESC INTEGER,
BDCODMRAISRESC INTEGER,
BDCODMCAGRESC INTEGER,
BDDESCPRES VARCHAR(110),
BDINIPRES INTEGER,
BDJCPRES VARCHAR(5),
BDAVPREPRES INTEGER,
BDGRRFPRES INTEGER,
BDESTPRES VARCHAR(5),
BDINDFER13 VARCHAR(5),
BDTERMCONTRPRES VARCHAR(5),
BDMULTAPRES VARCHAR(5),
BDDIASAVPREPRES INTEGER,
BDDIASPAGPRES INTEGER,
BDCODSEFMFGRESC VARCHAR(5),
BDDESCMFGRESC VARCHAR(255),
BDDESCSAQUERESC VARCHAR(60),
BDDESCMRAISRESC VARCHAR(255),
BDDESCMCAGEDRESC VARCHAR(255),
BDCODEMPDESTTRAN INTEGER,
BDCODPTRAN INTEGER,
BDCODCOLTRANS INTEGER,
BDDATATRANS DATE,
BDCODMCAGENTTRANS INTEGER,
BDCODMCAGSAITRANS INTEGER,
BDCODMFGTRANS INTEGER,
BDCODMRAISTRANS INTEGER,
BDDESCPTRANS VARCHAR(60),
BDCODSEFMFGTRANS VARCHAR(5),
BDDESCMFGTRANS VARCHAR(255),
BDDESCRAISTRANS VARCHAR(255),
BDDESCMCAGEDENTTRANS VARCHAR(255),
BDDESCMCAGEDSAITRANS VARCHAR(255),
BDCONTRCOL INTEGER,
BDPERTRANSPINSSTER NUMERIC(15,6),
BDPERTRANSPIRTER NUMERIC(15,6),
BDACORDOINSSTERC DM_BOOLEAN,
BDPERCIRTERC NUMERIC(18,6),
BDPIRTERC DM_BOOLEAN,
BDCODMULTVINC INTEGER,
BDCATEGORIAESOCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_SERV_TERC_MANUAL(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRSERV INTEGER,
PRDATA DATE,
PRREF INTEGER,
PRDATAPAG DATE,
PRHORA VARCHAR(10),
PRVALOR NUMERIC(15,2))
 RETURNS(BDCODSERV INTEGER,
BDDATASERV DATE,
BDDATAPAGSERV DATE,
BDHORASERV TIME,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODMCAG INTEGER,
BDCODCID INTEGER,
BDCODCSEG INTEGER,
BDREFCSEG INTEGER,
BDCODCIDNASC INTEGER,
BDCODUF INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDLOGRCOL DM_LOGRADOURO,
BDENDCOL DM_BDENDERECO,
BDNUMCOL DM_NUMEND,
BDCOMPLCOL DM_BDCOMPENDERECO,
BDBAICOL DM_BDBAIRRO,
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL DM_BDTELEFONE,
BDCELCOL DM_BDTELEFONE,
BDEMAILCOL DM_BDEMAIL,
BDSEXOCOL INTEGER,
BDDATANASCCOL DATE,
BDDATACADCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDRGCOL VARCHAR(13),
BDORGEMIRGCOL DM_ORGAOEMISSOR,
BDDATAEMIRGCOL DATE,
BDCPFCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDCODUF_COL_DOC INTEGER,
BDTITELEICOL VARCHAR(13),
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDCATCNHCOL VARCHAR(2),
BDCODCID_HIST INTEGER,
BDCODPAIS INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDDATACHEBRASILCOL DATE,
BDCODCIDNASCCONJ INTEGER,
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCONJCOL DATE,
BDCORCOL INTEGER,
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDDEFFISICOCOL INTEGER,
BDTIPOSANGUECOL INTEGER,
BDNROCONSPROCOL VARCHAR(20),
BDSIGLACONSPROCOL VARCHAR(5),
BDCODCCMPROCOL VARCHAR(15),
BDCODCLA INTEGER,
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDCODSINTRAB INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOADMCOL INTEGER,
BDNATUOCUPCOL INTEGER,
BDDATAINIAQUICOL DATE,
BDSALINICOL NUMERIC(15,6),
BDDIASPRAZO1COL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDIASPRAZO2COL INTEGER,
BDDATAFIMPRAZO2COL DATE,
BDDESCCONTSINCOL VARCHAR(5),
BDVINCEMPCOL INTEGER,
BDALVARACOL VARCHAR(5),
BDSINDICALIZADOCOL VARCHAR(5),
BDREGIMEPARCIALCOL VARCHAR(5),
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDOBSCOL BLOB,
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDCODCBO INTEGER,
BDCODQH INTEGER,
BDCODPRES INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAHOM DATE,
BDDATAPAGRESCISAO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDCALCFGTSMESANT VARCHAR(5),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDATAPAGGRFC DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDDISSIDIO VARCHAR(5),
BDDATADISSIDIO DATE,
BDDESCANSOINDENIZADO VARCHAR(5),
BDCODMFGRESC INTEGER,
BDCODSAQUERESC INTEGER,
BDCODMRAISRESC INTEGER,
BDCODMCAGRESC INTEGER,
BDDESCPRES VARCHAR(110),
BDINIPRES INTEGER,
BDJCPRES VARCHAR(5),
BDAVPREPRES INTEGER,
BDGRRFPRES INTEGER,
BDESTPRES VARCHAR(5),
BDINDFER13 VARCHAR(5),
BDTERMCONTRPRES VARCHAR(5),
BDMULTAPRES VARCHAR(5),
BDDIASAVPREPRES INTEGER,
BDDIASPAGPRES INTEGER,
BDCODSEFMFGRESC VARCHAR(5),
BDDESCMFGRESC VARCHAR(255),
BDDESCSAQUERESC VARCHAR(60),
BDDESCMRAISRESC VARCHAR(255),
BDDESCMCAGEDRESC VARCHAR(255),
BDCODEMPDESTTRAN INTEGER,
BDCODPTRAN INTEGER,
BDCODCOLTRANS INTEGER,
BDDATATRANS DATE,
BDCODMCAGENTTRANS INTEGER,
BDCODMCAGSAITRANS INTEGER,
BDCODMFGTRANS INTEGER,
BDCODMRAISTRANS INTEGER,
BDDESCPTRANS VARCHAR(60),
BDCODSEFMFGTRANS VARCHAR(5),
BDDESCMFGTRANS VARCHAR(255),
BDDESCRAISTRANS VARCHAR(255),
BDDESCMCAGEDENTTRANS VARCHAR(255),
BDDESCMCAGEDSAITRANS VARCHAR(255),
BDCONTRCOL INTEGER,
BDPERTRANSPINSSTER NUMERIC(15,6),
BDPERTRANSPIRTER NUMERIC(15,6),
BDCODMULTVINC INTEGER,
BDCATEGORIAESOCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_ACU_GPS_FUNRURAL(PRCODIMP INTEGER,
PRCODEMP VARCHAR(32000),
PRTIPO INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDTIPO INTEGER,
BDVALACU NUMERIC(15,6),
BDVALACUTER NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_ARREDONDAMENTOS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRTIPOCALCULO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFARRE INTEGER,
BDVALARRE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_BANCO_HORAS(PREMPRESAS VARCHAR(30000),
PRCOLAB VARCHAR(30000),
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFERENCIA INTEGER,
BDSALDOINICIAL NUMERIC(15,2),
BDCREDITO NUMERIC(15,2),
BDDEBITO NUMERIC(15,2),
BDSALDOFINAL NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CALC_AUTONOMO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRSERVICO INTEGER,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS varchar(2788) = null,
PRCODTPCC VARCHAR(10000) = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDMENORESVER VARCHAR(5),
BDPROPVER VARCHAR(5),
BDBASEVTVER VARCHAR(5),
BDREEMBGPSVER VARCHAR(5),
BDHEVER NUMERIC(15,6),
BDGRAVAFICHAHNVER VARCHAR(5),
BDCCPRINCIPALVER VARCHAR(5),
BDFORMREFAUXVER VARCHAR(5000),
BDFORMREFVER VARCHAR(5000),
BDFORMVALVER VARCHAR(5000),
BDBASEDSRHEVER VARCHAR(5),
BDBASEDSRRVVER VARCHAR(5),
BDDEDFORMREFAUXVER VARCHAR(5),
BDDEDFORMREFVER VARCHAR(5),
BDDEDFORMVALVER VARCHAR(5),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDETALHE VARCHAR(255),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBINSSCALC NUMERIC(15,6),
BDBIRCALC NUMERIC(15,6),
BDDATAPGTO DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CALC_FOLHANORMAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRCODTPCC VARCHAR(20000) = NULL,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS varchar(2788) = null)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDMENORESVER VARCHAR(5),
BDPROPVER VARCHAR(5),
BDBASEVTVER VARCHAR(5),
BDREEMBGPSVER VARCHAR(5),
BDHEVER NUMERIC(15,6),
BDGRAVAFICHAHNVER VARCHAR(5),
BDCCPRINCIPALVER VARCHAR(5),
BDFORMREFAUXVER VARCHAR(800),
BDFORMREFVER VARCHAR(800),
BDFORMVALVER VARCHAR(5000),
BDBASEDSRHEVER VARCHAR(5),
BDBASEDSRRVVER VARCHAR(5),
BDDEDFORMREFAUXVER VARCHAR(5),
BDDEDFORMREFVER VARCHAR(5),
BDDEDFORMVALVER VARCHAR(5),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDETALHE VARCHAR(255),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFEFOL NUMERIC(15,6),
BDFGTSFEFOL NUMERIC(15,6),
BDDATAPGTO DATE,
BDBINSSAPFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CALC_GPS(PRCODIMP INTEGER,
PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRAPENASGPS INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER)
 RETURNS(BDTIPOREG INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDCODCENTRO INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDVALFUNEMP NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDVALPROEMP NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDVALAUTEMP NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDVALORFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALORRAT NUMERIC(15,6),
BDVALORBRUTO NUMERIC(15,6),
BDVALORLIQUIDO NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6),
BDCHAVE INTEGER,
BDVALCOMPENSADO NUMERIC(15,6),
BDVALACOMPENSAR NUMERIC(15,6),
BDVALORACUMULADO NUMERIC(15,6),
BDVALORACUMULADOUSADO NUMERIC(15,6),
BDVALORACUMUTERCEIRO NUMERIC(15,6),
BDVALORACUTERCEIROSUSADO NUMERIC(15,6),
BDCODEMPANT INTEGER,
BDCODIMPANT INTEGER,
BDCHAVEDARFANT INTEGER,
BDCODPERIODOANT INTEGER,
BDORDEMANT INTEGER,
BDREFERENCIAANT INTEGER,
BDQUOTAANT INTEGER,
BDDESCACUMDET VARCHAR(3000),
BDDESCACU VARCHAR(3000),
BDVALORCAMPO6 NUMERIC(15,6),
BDVALORNOTAS NUMERIC(15,6),
BDTOTVALORACUMULADO NUMERIC(15,6),
BDTOTVALORACUMULADOTERC NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDTOTCOMPENSACAO NUMERIC(15,6),
BDDESCNOTAS NUMERIC(15,6),
BDTOTDESCCOMP NUMERIC(15,6),
BDDESCSALFAM NUMERIC(15,6),
BDDESCDEDGPS NUMERIC(15,6),
BDVALOUTENTIDADES NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDVALFUNEMPFN NUMERIC(15,6),
BDVALFUNEMPFC NUMERIC(15,6),
BDVALFUNEMPFERFN NUMERIC(15,6),
BDVALFUNEMPFERFC NUMERIC(15,6),
BDVALFUNEMP13FN NUMERIC(15,6),
BDVALFUNEMP13FC NUMERIC(15,6),
BDVALFUNEMP13 NUMERIC(15,6),
BDVALFUNEMPC13 NUMERIC(15,6),
BDVALPROEMPFN NUMERIC(15,6),
BDVALPROEMPFC NUMERIC(15,6),
BDVALPROEMPFERFN NUMERIC(15,6),
BDVALPROEMPFERFC NUMERIC(15,6),
BDVALPROEMP13FN NUMERIC(15,6),
BDVALPROEMP13FC NUMERIC(15,6),
BDVALPROEMP13 NUMERIC(15,6),
BDVALPROEMPC13 NUMERIC(15,6),
BDVALAUTEMPFN NUMERIC(15,6),
BDVALAUTEMPFC NUMERIC(15,6),
BDVALAUTEMPFERFN NUMERIC(15,6),
BDVALAUTEMPFERFC NUMERIC(15,6),
BDVALAUTEMP13FN NUMERIC(15,6),
BDVALAUTEMP13FC NUMERIC(15,6),
BDVALAUTEMP13 NUMERIC(15,6),
BDVALAUTEMPC13 NUMERIC(15,6),
BDVALFPASEMPFN NUMERIC(15,6),
BDVALFPASEMPFC NUMERIC(15,6),
BDVALFPASEMPFERFN NUMERIC(15,6),
BDVALFPASEMPFERFC NUMERIC(15,6),
BDVALFPASEMP13FN NUMERIC(15,6),
BDVALFPASEMP13FC NUMERIC(15,6),
BDVALFPASEMP13 NUMERIC(15,6),
BDVALFPASEMPC13 NUMERIC(15,6),
BDVALRATEMPFN NUMERIC(15,6),
BDVALRATEMPFC NUMERIC(15,6),
BDVALRATEMPFERFN NUMERIC(15,6),
BDVALRATEMPFERFC NUMERIC(15,6),
BDVALRATEMP13FN NUMERIC(15,6),
BDVALRATEMP13FC NUMERIC(15,6),
BDVALRATEMP13 NUMERIC(15,6),
BDVALRATEMPC13 NUMERIC(15,6),
BDVALRATAPOEMPFN NUMERIC(15,6),
BDVALRATAPOEMPFC NUMERIC(15,6),
BDVALRATAPOEMPFERFN NUMERIC(15,6),
BDVALRATAPOEMPFERFC NUMERIC(15,6),
BDVALRATAPOEMP13FN NUMERIC(15,6),
BDVALRATAPOEMP13FC NUMERIC(15,6),
BDVALRATAPOEMP13 NUMERIC(15,6),
BDVALRATAPOEMPC13 NUMERIC(15,6),
BDCHAVEDARF INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CONS_CALC_AUTONOMOS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODSERV INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFE NUMERIC(15,6),
BDFGTSFE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CONS_CALC_FOLHANORMAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFE NUMERIC(15,6),
BDFGTSFE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CONS_CALC_FOLHANORMALPR(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDBFGTSFE NUMERIC(15,6),
BDFGTSFE NUMERIC(15,6),
BDDATARESCISAOPREV DATE)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_CONS_IR_TERCEIROS (
    PRCODEMP varchar(10000),
    PRCODTER varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRFICHADEC smallint = 0)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODTER integer,
    BDNOMTER varchar(100),
    BDCODSERV integer,
    BDDATASERV date,
    BDDATAPAGSERV date,
    BDREF varchar(6),
    BDBASEIR numeric(15,6),
    BDVALORIR numeric(15,6),
    BDVALORDEP numeric(15,6),
    BDBASEINSS numeric(15,6),
    BDVALORINSS numeric(15,6),
    BDCPFTER varchar(14),
    BDCODRECOF DM_CODRECOF,
    BDBASEIRTOT numeric(18,6),
    BDDESCIRTOT varchar(50),
    BDTIPO integer,
    BDINCIDESOCIAL integer,
    BDBASEIRBRUTA numeric(15,6),
    BDREFIRRFESOCIAL integer)
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_DADOS_CALC_GPS(PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRTIPOEMISSAO INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER,
PRAPENAGPS INTEGER)
 RETURNS(BDTIPO INTEGER,
BDCODEMP INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALOUTENTIDADE NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCODTOMADOR INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDBASEFUNFN NUMERIC(15,6),
BDBASEFUNFC NUMERIC(15,6),
BDBASEFUNFERFN NUMERIC(15,6),
BDBASEFUNFERFC NUMERIC(15,6),
BDBASEFUN13RFN NUMERIC(15,6),
BDBASEFUN13RFC NUMERIC(15,6),
BDBASEFUN13 NUMERIC(15,6),
BDBASEFUNC13 NUMERIC(15,6),
BDBASEPROFN NUMERIC(15,6),
BDBASEPROFC NUMERIC(15,6),
BDBASEPROFERFN NUMERIC(15,6),
BDBASEPROFERFC NUMERIC(15,6),
BDBASEPRO13RFN NUMERIC(15,6),
BDBASEPRO13RFC NUMERIC(15,6),
BDBASEPRO13 NUMERIC(15,6),
BDBASEPROC13 NUMERIC(15,6),
BDBASEAUTFN NUMERIC(15,6),
BDBASEAUTFC NUMERIC(15,6),
BDBASEAUTFERFN NUMERIC(15,6),
BDBASEAUTFERFC NUMERIC(15,6),
BDBASEAUT13RFN NUMERIC(15,6),
BDBASEAUT13RFC NUMERIC(15,6),
BDBASEAUT13 NUMERIC(15,6),
BDBASEAUTC13 NUMERIC(15,6),
BDBASEFPASFN NUMERIC(15,6),
BDBASEFPASFC NUMERIC(15,6),
BDBASEFPASFERFN NUMERIC(15,6),
BDBASEFPASFERFC NUMERIC(15,6),
BDBASEFPAS13RFN NUMERIC(15,6),
BDBASEFPAS13RFC NUMERIC(15,6),
BDBASEFPAS13 NUMERIC(15,6),
BDBASEFPASC13 NUMERIC(15,6),
BDBASERATAPOFN NUMERIC(15,6),
BDBASERATAPOFC NUMERIC(15,6),
BDBASERATAPOFERFN NUMERIC(15,6),
BDBASERATAPOFERFC NUMERIC(15,6),
BDBASERATAPO13RFN NUMERIC(15,6),
BDBASERATAPO13RFC NUMERIC(15,6),
BDBASERATAPO13 NUMERIC(15,6),
BDBASERATAPOC13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_DADOS_IND_CALC_GPS(PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRTIPOEMISSAO INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER,
PRAPENASGPS INTEGER)
 RETURNS(BDCODCENTRO INTEGER,
BDTIPO INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALOUTENTIDADE NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCODTOMADOR INTEGER,
BDBASEFUNFN NUMERIC(15,6),
BDBASEFUNFC NUMERIC(15,6),
BDBASEFUNFERFN NUMERIC(15,6),
BDBASEFUNFERFC NUMERIC(15,6),
BDBASEFUN13RFN NUMERIC(15,6),
BDBASEFUN13RFC NUMERIC(15,6),
BDBASEFUN13 NUMERIC(15,6),
BDBASEFUNC13 NUMERIC(15,6),
BDBASEPROFN NUMERIC(15,6),
BDBASEPROFC NUMERIC(15,6),
BDBASEPROFERFN NUMERIC(15,6),
BDBASEPROFERFC NUMERIC(15,6),
BDBASEPRO13RFN NUMERIC(15,6),
BDBASEPRO13RFC NUMERIC(15,6),
BDBASEPRO13 NUMERIC(15,6),
BDBASEPROC13 NUMERIC(15,6),
BDBASEAUTFN NUMERIC(15,6),
BDBASEAUTFC NUMERIC(15,6),
BDBASEAUTFERFN NUMERIC(15,6),
BDBASEAUTFERFC NUMERIC(15,6),
BDBASEAUT13RFN NUMERIC(15,6),
BDBASEAUT13RFC NUMERIC(15,6),
BDBASEAUT13 NUMERIC(15,6),
BDBASEAUTC13 NUMERIC(15,6),
BDBASEFPASFN NUMERIC(15,6),
BDBASEFPASFC NUMERIC(15,6),
BDBASEFPASFERFN NUMERIC(15,6),
BDBASEFPASFERFC NUMERIC(15,6),
BDBASEFPAS13RFN NUMERIC(15,6),
BDBASEFPAS13RFC NUMERIC(15,6),
BDBASEFPAS13 NUMERIC(15,6),
BDBASEFPASC13 NUMERIC(15,6),
BDBASERATAPOFN NUMERIC(15,6),
BDBASERATAPOFC NUMERIC(15,6),
BDBASERATAPOFERFN NUMERIC(15,6),
BDBASERATAPOFERFC NUMERIC(15,6),
BDBASERATAPO13RFN NUMERIC(15,6),
BDBASERATAPO13RFC NUMERIC(15,6),
BDBASERATAPO13 NUMERIC(15,6),
BDBASERATAPOC13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_ESTOUROS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRTIPOCALCULO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFEST INTEGER,
BDVALEST NUMERIC(15,6),
BDTIPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_EXTRATO_FGTS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(10000),
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATA INTEGER,
BDMOVIMENTACAO VARCHAR(200),
BDVALOR NUMERIC(15,6),
BDACUMULADO NUMERIC(15,6),
BDVALORJAM NUMERIC(15,6),
BDVALORDEPOSITO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_FICHA_REG_COLABORADOR (
    PREMPRESA varchar(15000),
    PRCOLABORADOR varchar(30000),
    PRMODELO integer,
    PRORDEMIMP integer,
    PRCLASSE integer,
    PRFUNCAO integer,
    PRCENTROCUSTO integer,
    PRSINDICATO integer,
    PRREFERENCIA integer,
    PRULTIMODIA date,
    PROBS integer,
    PRSITCOL integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(18),
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDBAIEMP DM_BDBAIRRO,
    BDCIDADEEMP varchar(40),
    BDUFEMP varchar(2),
    BDCEPEMP varchar(9),
    BDFONEEMP DM_BDTELEFONE,
    BDDDDEMP integer,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLORDEM DM_BDNOMCOL,
    BDNOMPAICOL varchar(70),
    BDNOMMAECOL varchar(70),
    BDNOMCONJCOL varchar(70),
    BDDATANASCCOL date,
    BDCORCOL integer,
    BDSEXOCOL integer,
    BDPAISCOL varchar(40),
    BDNACIONALIDADE varchar(30),
    BDDATACHEBRASILCOL date,
    BDCIDADENASCCOL varchar(40),
    BDUFNASCCOL varchar(2),
    BDTIPOSANGUECOL integer,
    BDCPFCOL varchar(14),
    BDRGCOL varchar(13),
    BDDATAEMIREGCOL date,
    BDORGEMIRGCOL DM_ORGAOEMISSOR,
    BDCNHCOL varchar(11),
    BDCATCNHCOL varchar(2),
    BDVENCNHCOL date,
    BDCTPSCOL DM_BDCTPS,
    BDSERIECOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDRESERVISTACOL varchar(20),
    BDTITELEICOL varchar(20),
    BDGRAUINSTCOL integer,
    BDZONAELEICOL integer,
    BDSECAOELEICOL integer,
    BDPISCOL varchar(14),
    BDDATAEMIPISCOL date,
    BDESTCIVCOL integer,
    BDLOGRCOL DM_LOGRADOURO,
    BDENDCOL DM_BDENDERECO,
    BDNUMCOL DM_NUMEND,
    BDCOMPLCOL DM_BDCOMPENDERECO,
    BDBAICOL DM_BDBAIRRO,
    BDCIDADECOL varchar(40),
    BDUFCOL varchar(2),
    BDCEPCOL varchar(9),
    BDFONECOL DM_BDTELEFONE,
    BDDDDCOL integer,
    BDEMAILCOL DM_BDEMAIL,
    BDCELCOL DM_BDTELEFONE,
    BDDATAADMCOL date,
    BDDATACADCOL date,
    BDSALINICOL numeric(15,2),
    BDFORMAPAGTOCOL integer,
    BDPERCINSALUBCOL numeric(15,6),
    BDPERCPERCULCOL numeric(15,2),
    BDCATEGORIACOL integer,
    BDCODSINTRAB integer,
    BDDESCSINTRAB varchar(60),
    BDDEFCOL DM_BOOLEAN,
    BDDEFFISICOCOL integer,
    BDREAB DM_BOOLEAN,
    BDTIPOCOL integer,
    BDCTAFGTSCOL varchar(20),
    BDDATAOPCAOFGTSCOL date,
    BDCTADEPCOL varchar(20),
    BDDIGCTADEPCOL varchar(2),
    BDCODTFUC integer,
    BDDESCTFUC varchar(40),
    BDCODCBO integer,
    BDDATARESCISAO date,
    BDDATAAVPREVIO date,
    BDSALDOFGTS numeric(15,6),
    BDMAIORREMUNERACAO numeric(15,6),
    BDDATAPAGGRFC date,
    BDCODPRES integer,
    BDDESCPRES varchar(110),
    BDFOTOCOL blob sub_type 0 segment size 80,
    BDFICHAREGCOL varchar(12),
    BDLIVROREGCOL varchar(10),
    BDNROFOLHAREGCOL integer,
    BDUFCTPS varchar(2),
    BDDESCCATEGORIA varchar(300),
    BDNOMBAN varchar(60),
    BDCODBAN integer,
    BDNOMAG varchar(40),
    BDCODAG integer,
    BDNATURALIZADOCOL varchar(5),
    BDCABELOSCOL integer,
    BDOLHOSCOL integer,
    BDALTURACOL numeric(15,6),
    BDPESOCOL numeric(15,6),
    BDSINAISCOL varchar(5),
    BDOBSCOL blob sub_type 1 segment size 5000,
    BDDDDCELCOL integer,
    BDSIGLAUFRG varchar(2),
    BDDIANASC varchar(2),
    BDMESNASC varchar(2),
    BDANONASC varchar(10),
    BDCONTRCOL integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDNOMTPCC DM_BDNOMEMP,
    BDNOMCIDTPCC varchar(40),
    BDUFTPCC varchar(2),
    BDCODCLA integer,
    BDTIPOESCALA integer)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_FICHAFGTS2 (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFFIM integer,
    PRCC varchar(15000) = null,
    PRCALCFERA smallint = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODIND integer,
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBFGTSFC numeric(18,6),
    BDFGTSFC numeric(18,6),
    BDBASEFGTSA13 numeric(18,6),
    BDFGTSA13 numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDBASEFGTSC13 numeric(18,6),
    BDFGTSC13 numeric(18,6),
    BDINDICEJAM numeric(18,6),
    BDSALDOANTFGTS numeric(18,6),
    BDVALORJAM numeric(18,6),
    BDSALDOFGTS numeric(18,6),
    BDSOMAFGTS numeric(18,6),
    BDPERCINDCOMP numeric(18,6),
    BDVALORINDCOMP numeric(18,6),
    BDTIPO integer)
as
BEGIN
END^

create or alter procedure VRHF_SP_UNIONFICHAFGTS2_UNION_ALL (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFFIM integer,
    PRCC varchar(15000) = null,
    PRCALCFERA smallint = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODIND integer,
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBFGTSFC numeric(18,6),
    BDFGTSFC numeric(18,6),
    BDBASEFGTSA13 numeric(18,6),
    BDFGTSA13 numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDBASEFGTSC13 numeric(18,6),
    BDFGTSC13 numeric(18,6),
    BDINDICEJAM numeric(18,6),
    BDSALDOANTFGTS numeric(18,6),
    BDVALORJAM numeric(18,6),
    BDSALDOFGTS numeric(18,6),
    BDSOMAFGTS numeric(18,6),
    BDPERCINDCOMP numeric(18,6),
    BDVALORINDCOMP numeric(18,6),
    BDTIPO integer)
as
BEGIN
END^


CREATE OR ALTER PROCEDURE VRHF_SP_FICHAINSS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF INTEGER,
BDBINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBASEINSSC13 NUMERIC(15,6),
BDINSSC13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_FICHAIR(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRTIPOCALC INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF VARCHAR(10),
BDTIPOCALC INTEGER,
BDBRUTO NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDVALIR NUMERIC(15,6),
BDVALINSS NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_FICHAIR_ANUAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOBASE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDDATAADMCOL DATE,
BDDATARESCISAO DATE,
BDREF VARCHAR(10),
BDRENDTRIB NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDALUGUEIS NUMERIC(15,6),
BDPRIVPRIVADA NUMERIC(15,6),
BDDESPMEDICAS NUMERIC(15,6),
BDPENSAOALIM NUMERIC(15,6),
BDPENSAOJUDICIAL NUMERIC(15,6),
BDAJUDACUSTO NUMERIC(15,6),
BDLUCROPJ NUMERIC(15,6),
BDAVISOPREV NUMERIC(15,6),
BDRENDTRIB13 NUMERIC(15,6),
BDDEP13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDPENSAOALIM13 NUMERIC(15,6),
BDDATA DATE,
BDGRUPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_FICHARAIS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF INTEGER,
BDBRAIS NUMERIC(15,6),
BDB13 NUMERIC(15,6),
BDBA13 NUMERIC(15,6),
BDBC13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_FICHARAIS_NOVO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF INTEGER,
BDBRAIS NUMERIC(15,6),
BDB13 NUMERIC(15,6),
BDBA13 NUMERIC(15,6),
BDBC13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_GPS(PRCODIMP INTEGER,
PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRTIPOEMISSAO INTEGER,
PRAPENASGPS INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER)
 RETURNS(BDTIPOREG INTEGER,
BDCODEMP INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDCODCENTRO INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDVALFUNEMP NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDVALPROEMP NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDVALAUTEMP NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDVALORFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALORRAT NUMERIC(15,6),
BDVALORBRUTO NUMERIC(15,6),
BDVALORLIQUIDO NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6),
BDCHAVE INTEGER,
BDVALCOMPENSADO NUMERIC(15,6),
BDVALACOMPENSAR NUMERIC(15,6),
BDVALORACUMULADO NUMERIC(15,6),
BDVALORACUMULADOUSADO NUMERIC(15,6),
BDVALORACUTERCEIROS NUMERIC(15,6),
BDVALORACUTERCEIROSUSADO NUMERIC(15,6),
BDCODEMPANT INTEGER,
BDCHAVEDARFANT INTEGER,
BDCODIMPANT INTEGER,
BDCODPERIODOANT INTEGER,
BDORDEMANT INTEGER,
BDREFERENCIAANT INTEGER,
BDQUOTAANT INTEGER,
BDDESCACUMDET VARCHAR(3000),
BDDESCACUM VARCHAR(3000),
BDVALORCAMPO6 NUMERIC(15,6),
BDVALNOTAS NUMERIC(15,6),
BDDESCNOTAS NUMERIC(15,6),
BDTOTDESCCOMP NUMERIC(15,6),
BDTOTVALORACUMULADO NUMERIC(15,6),
BDTOTVALORACUMULADOTERC NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDTOTCOMPENSACAO NUMERIC(15,6),
BDDESCSALFAM NUMERIC(15,6),
BDDESCDEDGPS NUMERIC(15,6),
BDVALOUTENTIDADE NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDVALFUNEMPFN NUMERIC(15,6),
BDVALFUNEMPFC NUMERIC(15,6),
BDVALFUNEMPFERFN NUMERIC(15,6),
BDVALFUNEMPFERFC NUMERIC(15,6),
BDVALFUNEMP13FN NUMERIC(15,6),
BDVALFUNEMP13FC NUMERIC(15,6),
BDVALFUNEMP13 NUMERIC(15,6),
BDVALFUNEMPC13 NUMERIC(15,6),
BDVALPROEMPFN NUMERIC(15,6),
BDVALPROEMPFC NUMERIC(15,6),
BDVALPROEMPFERFN NUMERIC(15,6),
BDVALPROEMPFERFC NUMERIC(15,6),
BDVALPROEMP13FN NUMERIC(15,6),
BDVALPROEMP13FC NUMERIC(15,6),
BDVALPROEMP13 NUMERIC(15,6),
BDVALPROEMPC13 NUMERIC(15,6),
BDVALAUTEMPFN NUMERIC(15,6),
BDVALAUTEMPFC NUMERIC(15,6),
BDVALAUTEMPFERFN NUMERIC(15,6),
BDVALAUTEMPFERFC NUMERIC(15,6),
BDVALAUTEMP13FN NUMERIC(15,6),
BDVALAUTEMP13FC NUMERIC(15,6),
BDVALAUTEMP13 NUMERIC(15,6),
BDVALAUTEMPC13 NUMERIC(15,6),
BDVALFPASEMPFN NUMERIC(15,6),
BDVALFPASEMPFC NUMERIC(15,6),
BDVALFPASEMPFERFN NUMERIC(15,6),
BDVALFPASEMPFERFC NUMERIC(15,6),
BDVALFPASEMP13FN NUMERIC(15,6),
BDVALFPASEMP13FC NUMERIC(15,6),
BDVALFPASEMP13 NUMERIC(15,6),
BDVALFPASEMPC13 NUMERIC(15,6),
BDVALRATEMPFN NUMERIC(15,6),
BDVALRATEMPFC NUMERIC(15,6),
BDVALRATEMPFERFN NUMERIC(15,6),
BDVALRATEMPFERFC NUMERIC(15,6),
BDVALRATEMP13FN NUMERIC(15,6),
BDVALRATEMP13FC NUMERIC(15,6),
BDVALRATEMP13 NUMERIC(15,6),
BDVALRATEMPC13 NUMERIC(15,6),
BDVALRATAPOEMPFN NUMERIC(15,6),
BDVALRATAPOEMPFC NUMERIC(15,6),
BDVALRATAPOEMPFERFN NUMERIC(15,6),
BDVALRATAPOEMPFERFC NUMERIC(15,6),
BDVALRATAPOEMP13FN NUMERIC(15,6),
BDVALRATAPOEMP13FC NUMERIC(15,6),
BDVALRATAPOEMP13 NUMERIC(15,6),
BDVALRATAPOEMPC13 NUMERIC(15,6),
BDCHAVEDARF INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_GPS_CONTRATANTE(PREMP INTEGER,
PRREF INTEGER,
PRTERC INTEGER,
PRTPCC INTEGER,
PRNRNF VARCHAR(15))
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_GPS_FUNRURAL(PREMP INTEGER,
PRREF INTEGER,
PRNRNF VARCHAR(15),
PRTIPOEMISSAO INTEGER,
PRCODIMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDVALOR NUMERIC(15,6),
BDVALTERC NUMERIC(15,6),
BDVALORACU NUMERIC(15,6),
BDVALACUTERC NUMERIC(15,6),
BDDESCNOTAS VARCHAR(5000),
BDBASECALC NUMERIC(18,6)) 
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_GPS_FUNRURAL_RESUMO (
    PREMP integer,
    PRREF integer,
    PRNRNF varchar(15),
    PRTIPOEMISSAO integer,
    PRCODIMP integer)
returns (
    BDCODEMP integer,
    BDVALOR numeric(18,6),
    BDVALTERC numeric(18,6),
    BDVALORACU numeric(18,6),
    BDVALACUTERC numeric(18,6),
    BDDESCNOTAS varchar(10000),
    BDBASECALC numeric(18,6),
    BDVALRAT numeric(18,6))
as
BEGIN
  suspend;
END^

create or alter procedure SP_VRHF_FUNRURAL (
    PREMP varchar(25000),
    PRREFINI integer,
    PRREFFIM integer,
    PRTIPONF integer = 0)
returns (
    BDCODEMP integer,
    BDTIPONF integer,
    BDREFNF integer,
    BDCODTER integer,
    BDCODAQUIRUR integer,
    BDDATAEMISSAONF date,
    BDCHAVENF integer,
    BDNRONF varchar(15),
    BDSERIENF varchar(5),
    BDVALNF numeric(18,6),
    BDPERCINSS numeric(18,6),
    BDPERCRAT numeric(18,6),
    BDPERCSENAR numeric(18,6),
    BDCNPJPRODRUR DM_CNPJ_CPF,
    BDDESCPRODRUR varchar(100),
    BDINSS numeric(18,6),
    BDRAT numeric(18,6),
    BDSENAR numeric(18,6),
    BDDESCAQUIRUR varchar(500),
    BDTOTALNF numeric(18,6))
as
begin suspend; end^


CREATE OR ALTER PROCEDURE VRHF_SP_GRCSCOLABORADOR(PREMPRESA VARCHAR(9999),
PRCOLABORADOR VARCHAR(9999),
PRSINDICATO INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODSIND INTEGER,
BDCODCNAE INTEGER,
BDSIGLAUF VARCHAR(2),
BDNOMCID VARCHAR(40),
BDSIGLAUFSIND VARCHAR(2),
BDNOMCIDSIND VARCHAR(40),
BDCNPJSIND VARCHAR(18),
BDCEPSIND VARCHAR(9),
BDBAISIND DM_BDBAIRRO,
BDCOMPLSIND DM_BDCOMPENDERECO COLLATE WIN_PTBR,
BDNUMSIND DM_NUMEND,
BDENTSIND VARCHAR(40),
BDDESCSIND VARCHAR(60),
BDLOGRSIND DM_LOGRADOURO,
BDENDSIND DM_BDENDERECO,
BDAGENCIA VARCHAR(5),
BDCEDENTE VARCHAR(20),
BDCNPJ VARCHAR(20),
BDBAI DM_BDBAIRRO,
BDCEP VARCHAR(9),
BDCOMPL DM_BDCOMPENDERECO COLLATE WIN_PTBR,
BDNUM DM_NUMEND,
BDLOGR DM_LOGRADOURO,
BDEND VARCHAR(80),
BDNOM DM_BDNOMEMP,
BDCAPSOC NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_GRCSEMPRESA(PRSINDICATO INTEGER,
PRREFEMP INTEGER,
PRCODEMP VARCHAR(10000),
PRULTIMODIA DATE)
 RETURNS(BDCODCNAE INTEGER,
BDVALORDOC NUMERIC(15,2),
BDSIGLAUF VARCHAR(2),
BDNOMCID VARCHAR(40),
BDBAI DM_BDBAIRRO,
BDCEP VARCHAR(9),
BDCOMPL DM_BDCOMPENDERECO,
BDNUM DM_NUMEND,
BDEND DM_BDENDERECO,
BDCNPJ VARCHAR(18),
BDNOM DM_BDNOMEMP,
BDSIGLAUFSIND VARCHAR(2),
BDNOMCIDSIND VARCHAR(40),
BDCNPJSIND VARCHAR(18),
BDCEPSIND VARCHAR(9),
BDBAISIND DM_BDBAIRRO,
BDCOMPLSIND DM_BDCOMPENDERECO,
BDNUMSIND DM_NUMEND,
BDENTSIND VARCHAR(20),
BDDESCSIND VARCHAR(60),
BDENDSIND DM_BDENDERECO,
BDCAPSOC NUMERIC(15,2),
BDTIPOEMP CHAR,
BDTIPOCOL CHAR,
BDAGENCIA VARCHAR(5),
BDCEDENTE VARCHAR(20),
BDSALBASE NUMERIC(15,2),
BDTOTCOLAPU INTEGER,
BDTOTCOLEMP INTEGER,
BDTOTREMU NUMERIC(15,2),
BDLOGRSIND DM_LOGRADOURO,
BDLOGR DM_LOGRADOURO)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_OUTRASINF_CALC(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDDESCMEN VARCHAR(15),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDNOMAG VARCHAR(40),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDSEXOCOL INTEGER,
BDEMAILCOL VARCHAR(200),
BDDATANASCCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDDEFFISICOCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE,
BDALVARACOL VARCHAR(5),
BDNOMCOL VARCHAR(70))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_OUTRASINF_CALC_ATIVOS(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDDESCMEN VARCHAR(15),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDNOMAG VARCHAR(40),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDSEXOCOL INTEGER,
BDEMAILCOL VARCHAR(200),
BDDATANASCCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDDEFFISICOCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE,
BDALVARACOL VARCHAR(5),
BDNOMCOL VARCHAR(70))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_OUTRASINF_CALC_AUT(PRCODCOL VARCHAR(32700),
PRREF INTEGER,
PREMPRESA INTEGER = 0)
 RETURNS(BDCODCOL INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDDESCMEN VARCHAR(15),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDNOMAG VARCHAR(40),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,2),
BDVALORPREVPRIVNCOL NUMERIC(15,2),
BDVALORPREVPRIV13COL NUMERIC(15,2),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,2),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,2),
BDPERCDESCFPASCOL NUMERIC(15,2),
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,2),
BDHORASSEMANAISCOL NUMERIC(15,2),
BDHORASDIARIASCOL NUMERIC(15,2),
BDPERCINSALUBCOL NUMERIC(15,2),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,2),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,2),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDSEXOCOL INTEGER,
BDEMAILCOL VARCHAR(200),
BDDATANASCCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCPFCOL VARCHAR(18),
BDPISCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDDEFFISICOCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE,
BDALVARACOL VARCHAR(5),
BDNOMCOL DM_BDNOMTER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_QUADROHORARIOS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRDIASEMANA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCIDADE VARCHAR(40),
BDUF VARCHAR(2),
BDBAIEMP DM_BDBAIRRO,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCEPEMP VARCHAR(9),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDPISCOL VARCHAR(14),
BDCODQH INTEGER,
BDDESQH DM_BDDESCQH,
BDDIA INTEGER,
BDHORAENT TIME,
BDHORASAI TIME)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_RECIBO_FERIAS (
    PREMPRESA varchar(15000),
    PRCOLABORADOR varchar(30000),
    PRORDEMIMP integer,
    PRCLASSE integer,
    PRFUNCAO integer,
    PRCENTROCUSTO integer,
    PRSINDICATO integer,
    PRDATAGOZOINI date,
    PRDATAGOZOFIM date,
    PRPERIODOAQUISITIVO date,
    PRCODIGOFERIAS integer,
    PRTIPOCODVER integer,
    PRREFERENCIA integer,
    PRULTIMODIA date,
    PRCOLETIVAS integer,
    PRAVISO integer = 0,
    PRIDADE21 integer = 2100,
    PRNOVORECIBO smallint = 0)
returns (
    BDTIPOESCALA integer,
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDBAIEMP DM_BDBAIRRO,
    BDNOMCIDEMP varchar(40),
    BDSIGLAUFEMP varchar(2),
    BDCNPJEMP varchar(18),
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCHAVE integer,
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDSIGLAUFCTPS varchar(2),
    BDDESCTFUC varchar(40),
    BDDATAADMCOL date,
    BDINIPERAQUISFE date,
    BDFIMPERAQUISFE date,
    BDCODFE integer,
    BDINIPERGOZOFE date,
    BDFIMPERGOZOFE date,
    BDFALTASFE numeric(15,6),
    BDSALBASEFE numeric(15,6),
    BDSALBASEHEFE numeric(15,6),
    BDQTDABONOFE numeric(18,6),
    BDDATAPAGFE date,
    BDCODVER integer,
    BDTIPOCODVER integer,
    BDORDEMVER integer,
    BDDESCVER varchar(80),
    BDDESCREDVER varchar(20),
    BDREFVFE numeric(15,6),
    BDVALVFE numeric(15,6),
    BDTIPOREFVER integer,
    BDREFPAGABOFE integer,
    BDINISWS date,
    BDFIMSWS date,
    BDVALLIQUIDO numeric(15,6),
    BDCALCA13FE varchar(5),
    BDSALINI numeric(15,6),
    BDDIASLICFE numeric(18,6),
    BDDATAAVISO date,
    BDCLASSVER varchar(20),
    BDREFAUXVER numeric(15,6),
    BDCOLETIVAS varchar(5),
    BDDEPIR integer,
    BDDIASFERFE numeric(18,6),
    BDLOGOEMP blob sub_type 0 segment size 32720,
    BDREFHOREMP DM_BOOLEAN,
    BDCPFCOL varchar(14),
    BDDATARELABONO date,
    BDORDEM integer,
    BDFERIADOSFE integer,
    BDREFERENCIA integer,
    BDDTAINICIALFOLGA date,
    BDCODQH integer,
    BDCODPQUA integer)
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_REL_DECLARA_RENDIMENTOS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDTOTALRENDIMENTOS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDVAL13 NUMERIC(15,6),
BDVALPENALI NUMERIC(15,6),
BDVALIND NUMERIC(15,6),
BDVALDIR NUMERIC(15,6),
BDVALDME NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DECLARACAO_DOMESTICO (
    PRCODEMP VARCHAR(300),
    PRCODCOL VARCHAR(300),
    PRANOBASE INTEGER,
    PRTOMADOR INTEGER,
    PRCODSIND INTEGER,
    PRCLASSE INTEGER,
    PRFUNCAO INTEGER,
    PRORDEM VARCHAR(50),
    PRDATAEMISSAO VARCHAR(10),
    PRSITUACAO INTEGER)
 AS
 BEGIN END
^

CREATE OR ALTER PROCEDURE VRHF_SP_REL_LIQUIDO_FOLHA(PRCODEMP VARCHAR(25000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRULTDIAMES DATE,
PRTABELA VARCHAR(300),
PRDATANULL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDCODAGBAN VARCHAR(5),
BDCODAGBANDV VARCHAR(2),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDDATAADMCOL DATE,
BDDESCTFUC VARCHAR(40),
BDREF INTEGER,
SALBASE NUMERIC(15,6),
PROVE NUMERIC(15,6),
DESCO NUMERIC(15,6),
LIQ NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_REL_PREVIA_RESC(PREMPRESA VARCHAR(10000),
PRCOLABORADOR VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDBAIEMP DM_BDBAIRRO,
BDNOMCID VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCEPEMP VARCHAR(9),
BDCODCNAE INTEGER,
BDPISCOL VARCHAR(14),
BDLOGRCOL VARCHAR(15),
BDENDCOL VARCHAR(60),
BDNUMCOL DM_NUMEND,
BDBAICOL VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDNOMCIDCOL VARCHAR(40),
BDSIGLAUFCOL VARCHAR(2),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDATANASCCOL DATE,
BDNOMMAECOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCATEGORIACOL INTEGER,
BDDATAAVPREVIO DATE,
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDESCPRES VARCHAR(110),
BDCODSAQUE INTEGER,
BDDATARESCISAO DATE,
BDDATAPAGRESCISAO DATE,
BDCAMPO29 NUMERIC(15,2),
BDCAMPO30 NUMERIC(15,2),
BDCAMPO30REF INTEGER,
BDCAMPO31 NUMERIC(15,2),
BDCAMPO31REF INTEGER,
BDCAMPO32 NUMERIC(15,2),
BDCAMPO32REF INTEGER,
BDCAMPO33 NUMERIC(15,2),
BDCAMPO33REF INTEGER,
BDCAMPO34 NUMERIC(15,2),
BDCAMPO34REF INTEGER,
BDCAMPO35 NUMERIC(15,2),
BDCAMPO35REF INTEGER,
BDCAMPO36 NUMERIC(15,2),
BDCAMPO36REF INTEGER,
BDCAMPO37 NUMERIC(15,2),
BDCAMPO38 NUMERIC(15,2),
BDCAMPO39 NUMERIC(15,2),
BDCAMPO40 NUMERIC(15,2),
BDCAMPO40REF INTEGER,
BDCAMPO41 NUMERIC(15,2),
BDCAMPO42 NUMERIC(15,2),
BDCAMPO43 NUMERIC(15,2),
BDCAMPO44 NUMERIC(15,2),
BDCAMPO45 NUMERIC(15,2),
BDCAMPO46BRUTO NUMERIC(15,2),
BDCAMPO47 NUMERIC(15,2),
BDCAMPO48 NUMERIC(15,2),
BDCAMPO49 NUMERIC(15,2),
BDCAMPO50 NUMERIC(15,2),
BDCAMPO51 NUMERIC(15,2),
BDCAMPO52 NUMERIC(15,2),
BDCAMPO53 NUMERIC(15,2),
BDCAMPO54TOTDED NUMERIC(15,2),
BDCAMPO55LIQREC NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_REL_PREVIA_RESC2(PREMPRESA VARCHAR(10000),
PRCOLABORADOR VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRTIPOFILTRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDBAIEMP DM_BDBAIRRO,
BDNOMCID VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCEPEMP VARCHAR(9),
BDCODCNAE INTEGER,
BDPISCOL VARCHAR(14),
BDLOGRCOL VARCHAR(15),
BDENDCOL VARCHAR(60),
BDNUMCOL DM_NUMEND,
BDBAICOL VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDNOMCIDCOL VARCHAR(40),
BDSIGLAUFCOL VARCHAR(2),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDATANASCCOL DATE,
BDNOMMAECOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCATEGORIACOL INTEGER,
BDDATAAVPREVIO DATE,
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDESCPRES VARCHAR(110),
BDCODSAQUE INTEGER,
BDDATARESCISAO DATE,
BDDATAPAGRESCISAO DATE,
BDREF INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDORDEMVER INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_REL_RECIBO_RESCISAO (
    PREMPRESA varchar(10000),
    PRCOLABORADOR varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRFUNCAO integer,
    PRSINDICATO integer,
    PRCLASSE integer,
    PRTIPOFOLHA integer,
    PRDATAINI integer,
    PRDATAFIM integer)
returns (
    BDMAIORREMUNERACAOANT numeric(18,6),
    BDCODTIPOCONTRATO integer,
    BDDESCTIPOCONTRATO varchar(150),
    BDCODSINTRAB integer,
    BDCODCEDENTETRAB varchar(20),
    BDCNPJSINTRAB varchar(18),
    BDDESCSINTRAB varchar(60),
    BDPERTRCTRESC numeric(15,6),
    BDPERFGTSRESC numeric(15,6),
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(18),
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL varchar(14),
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDBAIEMP DM_BDBAIRRO,
    BDNOMCID varchar(40),
    BDSIGLAUFEMP varchar(2),
    BDCEPEMP varchar(9),
    BDCODCNAE integer,
    BDPISCOL varchar(14),
    BDLOGRCOL varchar(15),
    BDENDCOL varchar(60),
    BDNUMCOL DM_NUMEND,
    BDBAICOL varchar(50),
    BDCEPCOL varchar(9),
    BDNOMCIDCOL varchar(40),
    BDSIGLAUFCOL varchar(2),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL DM_DIGSERIECTPS,
    BDDATANASCCOL date,
    BDNOMMAECOL varchar(70),
    BDDATAADMCOL date,
    BDCATEGORIACOL integer,
    BDDATAAVPREVIO date,
    BDCHAVEINDENTIFICACAO varchar(49),
    BDDESCPRES varchar(110),
    BDCODSAQUE integer,
    BDDATARESCISAO date,
    BDDATAPAGRESCISAO date,
    BDVINCEMPCOL integer,
    BDSIGLAUFCTPS varchar(2),
    BDSIGLAHNET varchar(3),
    BDDESCHNET varchar(200),
    BDDESCCATEGORIA varchar(300),
    BDSALBASE numeric(18,6),
    BDDATAOPCAOFGTS date,
    BDTIPOCOL integer,
    BDCNPJTOM varchar(18),
    BDREFRESCISAO integer,
    BDECONSIGNADO DM_BOOLEAN,
    BDREFRESCISAOPOST integer)
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE VRHF_SP_REL_RECIBO_RESCISAO2(PREMPRESA VARCHAR(10000),
PRCOLABORADOR VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRTIPOFILTRO INTEGER,
PRTIPOFOLHA INTEGER,
PRDTPGTO INTEGER,
PRDTPGTOFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDBAIEMP DM_BDBAIRRO,
BDNOMCID VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCEPEMP VARCHAR(9),
BDCODCNAE INTEGER,
BDPISCOL VARCHAR(14),
BDLOGRCOL VARCHAR(15),
BDENDCOL VARCHAR(60),
BDNUMCOL DM_NUMEND,
BDBAICOL VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDNOMCIDCOL VARCHAR(40),
BDSIGLAUFCOL VARCHAR(2),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL DM_DIGSERIECTPS,
BDDATANASCCOL DATE,
BDNOMMAECOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCATEGORIACOL INTEGER,
BDDATAAVPREVIO DATE,
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDREFRESCISAO INTEGER,
BDDESCPRES VARCHAR(110),
BDCODSAQUE INTEGER,
BDDATARESCISAO DATE,
BDDATAPAGRESCISAO DATE,
BDREF INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(18,6),
BDREFAUXV NUMERIC(18,6),
BDHEVER NUMERIC(18,6),
BDPROVENTO NUMERIC(18,6),
BDDESCONTO NUMERIC(18,6),
BDORDEMVER INTEGER,
BDCLAVER VARCHAR(20),
BDPERCINSALUBCOL NUMERIC(18,6),
BDPERCPERICULCOL NUMERIC(18,6),
BDPERCNOTURNOCOL NUMERIC(18,6),
BDHORASDIARIASCOL NUMERIC(18,6),
BDSIGLAUFCTPS VARCHAR(2),
BDTIPOREFVER INTEGER,
BDREFHOREMP VARCHAR(5),
BDCLAVERAUX VARCHAR(20),
BDDESCVERAUX VARCHAR(70),
BDPROVENTOOUTROS NUMERIC(18,6),
BDDESCONTOOUTROS NUMERIC(18,6),
BDTIPOCOL INTEGER,
BDCNPJTOM VARCHAR(18))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_RETORNAEMPRESA_GPS(PREMP INTEGER,
PRREF INTEGER)
 RETURNS(BDSIMPLESGPS INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_SALARIOS_CONTRIB(PREMPRESA VARCHAR(15000),
PRCOLABORADOR VARCHAR(30000),
PRORDEMIMP INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRCENTROCUSTO INTEGER,
PRSINDICATO INTEGER,
PRBANCO INTEGER,
PRAGENCIA INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDNOMCIDEMP VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDSIGLAUFCTPS VARCHAR(2),
BDDATARESCISAO DATE,
BDDATAINSS DATE,
BDREFINSS INTEGER,
BDBASEINSS NUMERIC(15,6),
BDVALORINSS NUMERIC(15,2),
BDCODEMPAUX INTEGER,
BDCODCOLAUX INTEGER,
BDDATAINSSAUX DATE,
BDVALORINSSAUX NUMERIC(15,6),
BDBASEINSSAUX NUMERIC(15,6),
BDREFINSSAUX INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TCOMPENSACAOGPS(PRCODIMP INTEGER,
PRCODEMP INTEGER,
PRTIPOGPS INTEGER,
PRTIPOEMISSAO INTEGER,
PRCODTPCC INTEGER,
PRRETORNACOMPENSACAO INTEGER)
 RETURNS(BDTIPOREG INTEGER,
BDCHAVE INTEGER,
BDVALOR NUMERIC(15,6),
BDPERC NUMERIC(15,6),
BDMESINI INTEGER,
BDMESFIM INTEGER,
BDVALORREAJUSTE NUMERIC(15,6),
BDVALORSEMREAJUSTE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_MEDIAS (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRREFINI INTEGER,
    PRREFFIM INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODVER INTEGER,
    BDREF INTEGER,
    BDTIPO INTEGER,
    BDCC INTEGER,
    BDVREF NUMERIC(18,6),
    BDVREFAUX NUMERIC(18,6),
    BDVVAL NUMERIC(18,6))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_HISTORICO_FAP (
    PREMP VARCHAR(32700))
RETURNS (
    BDCODEMP INTEGER,
    BDREFEMP INTEGER,
    BDFAPANTERIOR NUMERIC(18,6),
    BDFAPATUAL NUMERIC(18,6))
AS
BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_AGRUPAR_QH
returns (
    BDCODQHH integer,
    BDDESCRICAO varchar(300))
AS
BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_TFOLHA_NORMAL (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(2788) = null)
returns (
    BDGRUPOCLA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDREFFN integer,
    BDDATABAIXAFN date,
    BDBFGTSFN numeric(15,6),
    BDFGTSFN numeric(15,6),
    BDFGTSCSFN numeric(15,6),
    BDBFGTS13FN numeric(15,6),
    BDFGTS13FN numeric(15,6),
    BDFGTS13CSFN numeric(15,6),
    BDMAIORREMFN numeric(15,6),
    BDBINSSFN numeric(15,6),
    BDALIQINSSFN numeric(15,6),
    BDINSSFN numeric(15,6),
    BDBIRRFFN numeric(15,6),
    BDALIQIRRFFN numeric(15,6),
    BDIRRFFN numeric(15,6),
    BDBINSS13FN numeric(15,6),
    BDALIQINSS13FN numeric(15,6),
    BDINSS13FN numeric(15,6),
    BDBIRRF13FN numeric(15,6),
    BDALIQIRRF13FN numeric(15,6),
    BDIRRF13FN numeric(15,6),
    BDBSALFAMFN numeric(15,6),
    BDSALFAMFN numeric(15,6),
    BDBRAISFN numeric(15,6),
    BDSALBASEFN numeric(15,6),
    BDDEPFN numeric(15,6),
    BDBASEPISFN numeric(15,6),
    BDBASEPISFEFN numeric(15,6),
    BDBASEPIS13FN numeric(15,6),
    BDBSALMATEMPFN numeric(15,6),
    BDSALMATEMPFN numeric(15,6),
    BDBRATAPOFN numeric(15,6),
    BDBRATAPOFEFN numeric(15,6),
    BDBRATAPO13FN numeric(15,6),
    BDBINSSFEFOLFN numeric(15,6),
    BDINSSFEFOLFN numeric(15,6),
    BDALIQINSSFEFOLFN numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDCREDITOFN numeric(15,6),
    BDDEBITOFN numeric(15,6),
    BDBFGTSFEFN numeric(15,6),
    BDFGTSFEFN numeric(15,6),
    BDBMATEMPFNFN numeric(15,6),
    BDBMATEMP13FN numeric(15,6),
    BDVMATEMPFNFN numeric(15,6),
    BDVMATEMP13FN numeric(15,6),
    BDLIQUIDOFN numeric(18,6),
    BDDATAPGTO date,
    BDBINSSAPFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDCODCONTTI integer,
    BDBASEFGTSMESESOCIAL numeric(18,6),
    BDBASEFGTS13ESOCIAL numeric(18,6),
    BDVALORFGTSMESESOCIAL numeric(18,6),
    BDVALORFGTS13ESOCIAL numeric(18,6),
    BDVALORFGTSINDESOCIAL numeric(18,6),
    BDBASEFGTSINDESOCIAL numeric(18,6))
as
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_TFOLHA_INT (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(772) = null)
returns (
    BDGRUPOCLA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODCONTTI integer,
    BDORDEM integer,
    BDREFFN integer,
    BDDATABAIXAFN date,
    BDBFGTSFN numeric(15,6),
    BDFGTSFN numeric(15,6),
    BDFGTSCSFN numeric(15,6),
    BDBFGTS13FN numeric(15,6),
    BDFGTS13FN numeric(15,6),
    BDFGTS13CSFN numeric(15,6),
    BDMAIORREMFN numeric(15,6),
    BDBINSSFN numeric(15,6),
    BDALIQINSSFN numeric(15,6),
    BDINSSFN numeric(15,6),
    BDBIRRFFN numeric(15,6),
    BDALIQIRRFFN numeric(15,6),
    BDIRRFFN numeric(15,6),
    BDBINSS13FN numeric(15,6),
    BDALIQINSS13FN numeric(15,6),
    BDINSS13FN numeric(15,6),
    BDBIRRF13FN numeric(15,6),
    BDALIQIRRF13FN numeric(15,6),
    BDIRRF13FN numeric(15,6),
    BDBSALFAMFN numeric(15,6),
    BDSALFAMFN numeric(15,6),
    BDBRAISFN numeric(15,6),
    BDSALBASEFN numeric(15,6),
    BDDEPFN numeric(15,6),
    BDBASEPISFN numeric(15,6),
    BDBASEPISFEFN numeric(15,6),
    BDBASEPIS13FN numeric(15,6),
    BDBSALMATEMPFN numeric(15,6),
    BDSALMATEMPFN numeric(15,6),
    BDBRATAPOFN numeric(15,6),
    BDBRATAPOFEFN numeric(15,6),
    BDBRATAPO13FN numeric(15,6),
    BDBINSSFEFOLFN numeric(15,6),
    BDINSSFEFOLFN numeric(15,6),
    BDALIQINSSFEFOLFN numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDCREDITOFN numeric(15,6),
    BDDEBITOFN numeric(15,6),
    BDBFGTSFEFN numeric(15,6),
    BDFGTSFEFN numeric(15,6),
    BDBMATEMPFNFN numeric(15,6),
    BDBMATEMP13FN numeric(15,6),
    BDVMATEMPFNFN numeric(15,6),
    BDVMATEMP13FN numeric(15,6),
    BDLIQUIDOFN numeric(18,6),
    BDDATAPGTO date,
    BDBINSSAPFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSS13APFN numeric(18,6))
as
BEGIN
  SUSPEND;
END^


create or alter procedure VRHF_SP_TFOLHACOMP (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(28000),
    PRREFINICOMP integer,
    PRREFFIMCOMP integer,
    PRREFINIPAG integer,
    PRREFFIMPAG integer,
    PRAGRUPATOMADOR integer,
    PRTIPOFC integer = 0,
    PRSEPARCALC integer = 0,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(772) = null,
    PRINSSPATRONAL smallint = 0,
    PRCOMPLEESOCIAL integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDREFFN integer,
    BDREFFC integer,
    BDREFCOMP integer,
    BDDATAPAGFC date,
    BDDATABAIXAFC date,
    BDBFGTSFC numeric(15,6),
    BDFGTSFC numeric(15,6),
    BDFGTSCSFC numeric(15,6),
    BDBFGTS13FC numeric(15,6),
    BDFGTS13FC numeric(15,6),
    BDFGTS13CSFC numeric(15,6),
    BDMAIORREMFC numeric(15,6),
    BDBINSSFC numeric(15,6),
    BDALIQINSSFC numeric(15,6),
    BDINSSFC numeric(15,6),
    BDBIRRFFC numeric(15,6),
    BDALIQIRRFFC numeric(15,6),
    BDIRRFFC numeric(15,6),
    BDBINSS13FC numeric(15,6),
    BDALIQINSS13FC numeric(15,6),
    BDINSS13FC numeric(15,6),
    BDBIRRF13FC numeric(15,6),
    BDALIQIRRF13FC numeric(15,6),
    BDIRRF13FC numeric(15,6),
    BDBSALFAMFC numeric(15,6),
    BDSALFAMFC numeric(15,6),
    BDBRAISFC numeric(15,6),
    BDSALBASEFC numeric(15,6),
    BDDEPFC numeric(15,6),
    BDBASEPISFC numeric(15,6),
    BDBASEPISFEFC numeric(15,6),
    BDBASEPIS13FC numeric(15,6),
    BDBSALMATEMPFC numeric(15,6),
    BDSALMATEMPFC numeric(15,6),
    BDBRATAPOFC numeric(15,6),
    BDBRATAPOFEFC numeric(15,6),
    BDBRATAPO13FC numeric(15,6),
    BDBINSSFEFOLFC numeric(15,6),
    BDINSSFEFOLFC numeric(15,6),
    BDALIQINSSFEFOLFC numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDBFGTSFEFC numeric(15,6),
    BDFGTSFEFC numeric(15,6),
    BDCODTIPOFC integer,
    BDBINSSMVFC numeric(18,6),
    BDBINSSMV13FC numeric(18,6),
    BDINSSMVFC numeric(18,6),
    BDINSSMV13FC numeric(18,6),
    BDBINSSAPFC numeric(18,6),
    BDBINSS13APFC numeric(18,6),
    BDINSSAPFC numeric(18,6),
    BDINSS13APFC numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDINSSFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDLIQUIDOFC numeric(18,6),
    BDDATAGRRF date,
    BDCODCONTTI integer,
    BDREFVINCFN integer,
    BDSALFAM13GPS numeric(18,6),
    BDSALFAMFNGPS numeric(18,6),
    BDDTACCONV date,
    BDDTPGTOBRICONV date,
    BDCODACCONV integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_TIPO_TOMADOR_GPS (
    PRCENCUS integer,
    PRPLANOCUS integer,
    PRREF integer,
    PR13 smallint = 0)
returns (
    BDCODCENCUS integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCTALON varchar(40),
    BDTIPCTA smallint,
    BDNOMCTA varchar(40),
    BDAPECTA varchar(20),
    BDFILTROGER varchar(20),
    BDCLANOM varchar(80),
    BDTIPO integer,
    BDCNPJTOM varchar(18),
    BDTIPOTOM integer,
    BDTIPOFERTOM integer,
    BDSOMSALFERTOM varchar(5),
    BDTIPO13TOM integer,
    BDSOMSAL13TOM varchar(5),
    BDNOMETOM varchar(70),
    BDAPELIDO varchar(20),
    BDNOME varchar(40))
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TODAS_GPS(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(22000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRAPENASGPS INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER)
 RETURNS(BDTIPOREG INTEGER,
BDCODEMP INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDVALFUNEMP NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDVALPROEMP NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDVALAUTEMP NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDVALORFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALORRAT NUMERIC(15,6),
BDVALORBRUTO NUMERIC(15,6),
BDVALORLIQUIDO NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6),
BDCHAVE INTEGER,
BDVALCOMPENSADO NUMERIC(15,6),
BDVALACOMPENSAR NUMERIC(15,6),
BDVALORACUMULADO NUMERIC(15,6),
BDVALORACUMULADOUSADO NUMERIC(15,6),
BDVALORACUMUTERCEIRO NUMERIC(15,6),
BDVALORACUTERCEIROSUSADO NUMERIC(15,6),
BDCODEMPANT INTEGER,
BDCODIMPANT INTEGER,
BDCODPERIODOANT INTEGER,
BDORDEMANT INTEGER,
BDREFERENCIAANT INTEGER,
BDQUOTAANT INTEGER,
BDDESCACUMDET VARCHAR(3000),
BDDESCACU VARCHAR(3000),
BDVALORCAMPO6 NUMERIC(15,6),
BDVALORNOTAS NUMERIC(15,6),
BDTOTVALORACUMULADO NUMERIC(15,6),
BDTOTVALORACUMULADOTERC NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDTOTCOMPENSACAO NUMERIC(15,6),
BDDESCNOTAS NUMERIC(15,6),
BDTOTDESCCOMP NUMERIC(15,6),
BDDESCSALFAM NUMERIC(15,6),
BDDESCDEDGPS NUMERIC(15,6),
BDVALOUTENTIDADES NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCHAVEDARF INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TOMADOR(PRCENCUS INTEGER,
PRPLANOCUS INTEGER)
 RETURNS(BDCODCENCUS INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCTALON VARCHAR(40),
BDTIPCTA SMALLINT,
BDNOMCTA VARCHAR(40),
BDAPECTA VARCHAR(20),
BDFILTROGER VARCHAR(20),
BDCLANOM VARCHAR(80),
BDTIPO INTEGER,
BDCNPJTOM VARCHAR(18),
BDTIPOTOM INTEGER,
BDTIPOFERTOM INTEGER,
BDSOMSALFERTOM VARCHAR(5),
BDTIPO13TOM INTEGER,
BDSOMSAL13TOM VARCHAR(5),
BDNOMETOM VARCHAR(70),
BDAPELIDO VARCHAR(20),
BDNOME VARCHAR(40),
BDTIPODOCTOM INTEGER,
BDCODLOT integer,
BDCODLOTACAO varchar(30),
BDCODESTAB varchar(30))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TOTAL_COL_ATIVOS(PRCODEMP INTEGER,
PRREF INTEGER,
PRDATAADMISSAO DATE)
 RETURNS(TTATIVOS INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TPREPFB_CC RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDDATAENTRADA DATE,
BDHORAENTRADA TIME,
BDTIPO INTEGER,
BDQTDTEMPO NUMERIC(15,6),
BDCTALON VARCHAR(40),
BDTIPCTA SMALLINT,
BDNOMCTA VARCHAR(100),
BDAPECTA VARCHAR(20),
BDFILTROGER VARCHAR(20),
BDCLANOM VARCHAR(140))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_TPREPFN_CC_REF (
    PRREF integer,
    PREMPRESA varchar(32700),
    PRCOLABORADOR varchar(32700),
    PRTEMPO integer,
    PRDATAINI date,
    PRDATAFIM date,
    PRFERIAS smallint = 0,
    PRCALCULO DM_BOOLEAN = 'TRUE')
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDDATAENTRADA date,
    BDHORAENTRADA time,
    BDTIPO integer,
    BDQTDTEMPO numeric(15,6),
    BDCTALON varchar(40),
    BDTIPCTA smallint,
    BDNOMCTA varchar(100),
    BDAPECTA varchar(20),
    BDFILTROGER varchar(20),
    BDCLANOM varchar(140),
    BDTEMPO integer,
    BDTEMPOFN integer,
    BDPERCFN numeric(15,6),
    BDLANCHORAS numeric(15,2),
    BDTOTHORAS numeric(15,2),
    BDTOTDSR numeric(15,2),
    BDLANCDSR numeric(15,2))
as
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_TPREPFN_REF (
    PRREFERENCIA integer,
    PREMPRESA varchar(32700),
    PRCOLABORADOR varchar(32700),
    PRDATAINI date,
    PRDATAFIM date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDDATAENTRADA date,
    BDHORAENTRADA time,
    BDTIPO integer,
    BDQTDTEMPO numeric(15,6),
    BDPERCFN numeric(15,6),
    BDLANCHORAS numeric(15,2),
    BDTOTHORAS numeric(15,2),
    BDTOTDSR numeric(15,2),
    BDLANCDSR numeric(15,2))
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TTEMPOTRAB(PRCODEMP INTEGER,
PRCODFUN INTEGER,
PRDATAENT DATE,
PRHORAENT TIME,
PRDATASAI DATE,
PRHORASAI TIME)
 RETURNS(BDTEMPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_TVERBAFC (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(25000),
    PRREFINICOMP integer,
    PRREFFIMCOMP integer,
    PRREFINIPAG integer,
    PRREFFIMPAG integer,
    PRAGRUPATOMADOR integer,
    PRSEPARARCALC integer = 0,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(772) = null,
    PRCOMPLEESOCIAL integer = 0)
returns (
    BDCODVER integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFCOMP integer,
    BDREFVFC numeric(15,6),
    BDREFAUXVFC numeric(15,6),
    BDVALVFC numeric(15,6),
    BDIGNREFVFC varchar(5),
    BDIGNREFAVFC varchar(5),
    BDIGNVALVFC varchar(5),
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDREFFC integer,
    BDCODCONTTI integer)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_AGRUPA_VERBAS_FT (
    PRAGRUPADOR INTEGER,
    PRFILTRO VARCHAR(32700) = NULL,
    PRFILTROCC VARCHAR(20000) = NULL)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREFTOMADOR INTEGER,
    BDORDEM INTEGER,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDCODVER INTEGER,
    BDREFVFT_SUM NUMERIC(15,6),
    BDREFVFT_MAX NUMERIC(15,6),
    BDREFAUXVFT NUMERIC(15,6),
    BDVALVFT NUMERIC(15,6),
    BDIGNREFVFT DM_BOOLEAN,
    BDIGNREFAVFT DM_BOOLEAN,
    BDIGNVALVFT DM_BOOLEAN,
    BDTIPOREFVER INTEGER)
AS
BEGIN
  SUSPEND;
END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TVERBAFN(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRCODTPCC VARCHAR(20000) = NULL,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(2788) = NULL)
 RETURNS(BDCODVER INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDREFVFN NUMERIC(15,6),
BDREFAUXVFN NUMERIC(15,6),
BDVALVFN NUMERIC(15,6),
BDIGNREFVFN VARCHAR(5),
BDIGNREFAVFN VARCHAR(5),
BDIGNVALVFN VARCHAR(5),
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCALCTOMADOR VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_UNION_VERBAS_SIM_NAO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRCODSINTRAB VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRLOCAL VARCHAR(100),
PRSIMNAO VARCHAR(100))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODSIND INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(40),
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF BLOB,
BDFORMVAL BLOB,
BDDESCCOND BLOB,
BDLOCAL VARCHAR(10),
BDSIMNAO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_UNION_VERBAS_SIM_NAO_2(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRCODSINTRAB VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRLOCAL VARCHAR(100),
PRSIMNAO VARCHAR(100))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODSIND INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(40),
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000),
BDDESCCOND BLOB,
BDLOCAL VARCHAR(10),
BDSIMNAO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_VERBAS_FN_FC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRCLASSVERBAS VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF INTEGER,
BDCODVER INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDCLAVER VARCHAR(20),
BDIGNREFAV VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_VERBAS (
    PRANOMES INTEGER,
    PRNIVELCLASSIFICACAO SMALLINT = 0)
RETURNS (
    BDCODVER INTEGER NOT NULL,
    BDREFVER INTEGER NOT NULL,
    BDTIPOCODVER INTEGER,
    BDINSSVER INTEGER,
    BDFGTSVER INTEGER,
    BDIRVER INTEGER,
    BDTIPOREFVER INTEGER,
    BDBASESFVER INTEGER,
    BDPISVER VARCHAR(5),
    BDBASEHEVER VARCHAR(5),
    BDBASEMAIORVER VARCHAR(5),
    BDRAISVER VARCHAR(5),
    BDBASEGPSVER VARCHAR(5),
    BDMENORESVER VARCHAR(5),
    BDPROPVER VARCHAR(5),
    BDBASEVTVER VARCHAR(5),
    BDREEMBGPSVER VARCHAR(5),
    BDHEVER NUMERIC(15,6),
    BDGRAVAFICHAHNVER VARCHAR(5),
    BDCCPRINCIPALVER VARCHAR(5),
    BDFORMREFVER VARCHAR(5000),
    BDFORMVALVER VARCHAR(5000),
    BDBASEDSRHEVER VARCHAR(5),
    BDBASEDSRRVVER VARCHAR(5),
    BDFORMREFAUXVER VARCHAR(5000),
    BDDEDFORMREFAUXVER VARCHAR(5),
    BDDEDFORMREFVER VARCHAR(5),
    BDDEDFORMVALVER VARCHAR(5),
    BDRENDISENTOIRVER VARCHAR(5),
    BDFORMINTVER VARCHAR(5000),
    BDSIMPLESNACIONAL VARCHAR(5),
    BDBASE13HN VARCHAR(5),
    BDBASEFERHN VARCHAR(5),
    BDBASEAVHN VARCHAR(5),
    BDPAGAESTOUROVER VARCHAR(5),
    BDGARANTIAMINVER VARCHAR(5),
    BDINDRESC VARCHAR(5),
    BDNAOCONVHORASVER DM_BOOLEAN,
    BDAPEVER VARCHAR(20) NOT NULL,
    BDDESCVER VARCHAR(40),
    BDDESCREDVER VARCHAR(20),
    BDCLAVER VARCHAR(20),
    BDREADONLY VARCHAR(5),
    BDORDEMVER INTEGER,
    BDINATIVAVER VARCHAR(5),
    BDSITVER INTEGER,
    BDBASESALRAIS VARCHAR(5),
    BDSITMATVER VARCHAR(5),
    BDSITDOEVER VARCHAR(5),
    BDSITACITRABVER VARCHAR(5),
    BDSITMILITARVER VARCHAR(5),
    BDSITMATEMPVER VARCHAR(5),
    BDSITACITRAB15VER VARCHAR(5),
    BDSITDOETRABVER VARCHAR(5),
    BDSITLICVENCVER VARCHAR(5),
    BDSITDOE15VER VARCHAR(5),
    BDSITSINDICALVER VARCHAR(5),
    BDSITAPOINVVER VARCHAR(5),
    BDSITOUTRASVER VARCHAR(5),
    BDTIPOVER INTEGER,
    BDORDEMTIPOCODVER INTEGER)
AS
BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_VERBAS_FOL_NORMAL_AUT (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32000),
    PRCODAUT varchar(10000),
    PRTIPOCOL integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer,
    PRFILTRO varchar(2000),
    PRCODTPCC varchar(10000),
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(2788) = null /* COLLATE WIN1252 - default */ ,
    PRFUCDET smallint = 0,
    PRBASECALC smallint = 1)
returns (
    BDCODPLAFUC integer,
    BDCODSINTRAB integer,
    BDCODCLA integer,
    BDDESCENQFED varchar(10),
    BDTEMGRRF integer,
    BDBSALFAM numeric(18,6),
    BDDATARESCISAO date,
    BDDESCRICAOMOTRES varchar(300),
    BDTIPOMOV integer,
    BDTIPO_COL integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMEMP DM_BDNOMEMP,
    BDAPEEMP DM_BDAPEMP,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP varchar(9),
    BDCNPJEMP varchar(18),
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDNOMCOL DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDPERCRATCOL numeric(18,6),
    BDDESCTFUC varchar(150),
    BDCPFCOL varchar(18),
    BDPISCOL varchar(14),
    BDCODENQFED integer,
    BDSIMPLESGPS integer,
    BDCTPSCOL DM_BDCTPS,
    BDCODCBO integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDREFFN integer,
    BDCODSERV integer,
    BDCODVER integer,
    BDDESCVER varchar(80),
    BDREFV numeric(18,6),
    BDPROVENTO numeric(18,6),
    BDDESCONTO numeric(18,6),
    BDSALBASE numeric(18,6),
    BDBINSS numeric(18,6),
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBIRRF numeric(18,6),
    BDBRAIS numeric(18,6),
    BDDESCREDVER varchar(80),
    BDIRRF numeric(18,6),
    BDGRUPOCLA integer,
    BDBINSS13 numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDBIRRF13 numeric(18,6),
    BDVFGTS13 numeric(18,6),
    BDBINSSFEFOL numeric(18,6),
    BDVINSSFEFOL numeric(18,6),
    BDBFGTSFEFOL numeric(18,6),
    BDVFGTSFEFOL numeric(18,6),
    BDDESCCC varchar(80),
    BDPISVER varchar(5),
    BDCLAVER varchar(20),
    BDBFGTSMESANT numeric(18,6),
    BDFGTSMESANT numeric(18,6),
    BDBFGTSMES numeric(18,6),
    BDFGTSMES numeric(18,6),
    BDSALDO numeric(18,6),
    BDFGTS40 numeric(18,6),
    BDFGTS10 numeric(18,6),
    BDTOTALGRRF numeric(18,6),
    BDORDEMVER integer,
    BDORDEMTIPOCODVER integer,
    BDTIPOCODVER integer,
    BDCODTFUC integer,
    BDTIPOREFVER integer,
    BDREFHOREMP varchar(5),
    BDVALMVINSSTER numeric(15,6),
    BDREFAUXV numeric(15,6),
    BDDATAPGTO date,
    BDCCATVCONCOM DM_BOOLEAN,
    BDBFGTSMESPOST numeric(18,6),
    BDFGTSMESPOST numeric(18,6),
    BDINSSFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDMVINSSTER numeric(18,6),
    BDHORASMENSAISCOL numeric(18,6),
    BDFGTSIND numeric(18,6),
    BDDATAGRRF date,
    BDBASEINSSMV numeric(18,6),
    BDBASEIRRFMV numeric(18,6),
    BDVALORINSSMV numeric(18,6),
    BDVALORIRRFMV numeric(18,6),
    BDPERCMULTA40 numeric(15,2),
    BDPERCMULTA10 numeric(15,2),
    BDCODCONTTI integer,
    BDCATEGORIAESOCIAL integer,
    BDCODSERVB DM_BOOLEAN,
    BDSALFAM13GPS numeric(18,6),
    BDSALFAMFNGPS numeric(18,6),
    BDCONTRCOL integer,
    BDFGTSMES13 numeric(18,6),
    BDBASEPISFN numeric(18,6),
    BDBASEPISFEFN numeric(18,6),
    BDBASEPIS13FN numeric(18,6),
    BDCREDTRAB numeric(18,6),
    BDCREDTRABFERIAS numeric(18,6),
    BDCREDTRABCONTAB numeric(18,6),
    BDCREDTRABGUIAMENSAL boolean,
    BDGRRFPRES integer)
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_VERBAS_FOLHA(PREMPRESA VARCHAR(30000),
PRCOLABORADOR VARCHAR(30000),
PRORDEMIMPRESSAO INTEGER,
PRTIPOFOLHA INTEGER,
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRAGRUPARSINDICATO INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRCENTROCUSTO INTEGER,
PRSINDICATO INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDESCTFUC VARCHAR(40),
BDDATAADMCOL DATE,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDPISCOL VARCHAR(14),
BDSALBASECOL NUMERIC(15,6),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDLOGRSINTRAB VARCHAR(15),
BDENDSINTRAB VARCHAR(40),
BDBAISINTRAB VARCHAR(20),
BDNROSINTRAB DM_NUMEND,
BDCOMPLSINTRAB VARCHAR(20),
BDNOMCIDSINTRAB VARCHAR(40),
BDSIGLAUFSINTRAB VARCHAR(2),
BDCODVER INTEGER,
BDREFVER INTEGER,
BDDESCVER VARCHAR(40),
BDREFV NUMERIC(15,6),
BDVALV NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_VERBAS_PREV_RESC (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer,
    PRCODCC varchar(10000) = '' /* COLLATE WIN1252 - default */ )
returns (
    BDCODPLAFUC integer,
    BDCODSINTRAB integer,
    BDCODCLA integer,
    BDDESCENQFED varchar(10),
    BDTEMGRRF integer,
    BDBSALFAM numeric(18,6),
    BDDATARESCISAO date,
    BDDESCRICAOMOTRES varchar(300),
    BDTIPOMOV integer,
    BDTIPO_COL integer,
    BDCODMATRIZ integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMEMP DM_BDNOMEMP,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP varchar(9),
    BDCNPJEMP varchar(18),
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDNOMCOL DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDPERCRATCOL numeric(18,6),
    BDDESCTFUC varchar(80),
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDCODENQFED integer,
    BDSIMPLESGPS integer,
    BDCTPSCOL DM_BDCTPS,
    BDCODCBO integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDREFFN integer,
    BDCODSERV integer,
    BDCODVER integer,
    BDDESCVER varchar(80),
    BDREFV numeric(18,6),
    BDPROVENTO numeric(18,6),
    BDDESCONTO numeric(18,6),
    BDSALBASE numeric(18,6),
    BDBINSS numeric(18,6),
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBIRRF numeric(18,6),
    BDBRAIS numeric(18,6),
    BDDESCREDVER varchar(80),
    BDIRRF numeric(18,6),
    BDGRUPOCLA integer,
    BDBINSS13 numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDBIRRF13 numeric(18,6),
    BDVFGTS13 numeric(18,6),
    BDBINSSFEFOL numeric(18,6),
    BDVINSSFEFOL numeric(18,6),
    BDBFGTSFEFOL numeric(18,6),
    BDVFGTSFEFOL numeric(18,6),
    BDDESCCC varchar(80),
    BDPISVER varchar(5),
    BDCLAVER varchar(20),
    BDBFGTSMESANT numeric(18,6),
    BDFGTSMESANT numeric(18,6),
    BDBFGTSMES numeric(18,6),
    BDFGTSMES numeric(18,6),
    BDSALDO numeric(18,6),
    BDFGTS40 numeric(18,6),
    BDFGTS10 numeric(18,6),
    BDTOTALGRRF numeric(18,6),
    BDORDEMVER integer,
    BDORDEMTIPOCODVER integer,
    BDTIPOCODVER integer,
    BDTIPOREFVER integer,
    BDREFHOREMP varchar(5),
    BDDATAPGTO date,
    BDBFGTSMESPOST numeric(18,6),
    BDFGTSMESPOST numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSSFNPR numeric(18,6),
    BDINSS13FNPR numeric(18,6),
    BDCCATVCONCOM DM_BOOLEAN,
    BDREFAUXV numeric(18,6),
    BDFGTSIND numeric(18,6),
    BDDATAGRRF date,
    BDPERCMULTA40 numeric(15,2),
    BDPERCMULTA10 numeric(15,2),
    BDFGTSMES13 numeric(18,6),
    BDCREDTRAB numeric(18,6),
    BDCREDTRABFERIAS numeric(18,6),
    BDCREDTRABCONTAB numeric(18,6),
    BDCREDTRABGUIAMENSAL boolean,
    BDGRRFPRES integer)
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_VERBAS_SIM_COL_CALC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_VERBAS_SIM_PRES_CALC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODPRES INTEGER,
BDCODVER INTEGER,
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_BC_PROLAB_COLAB(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER,
PRTIPOCADASTRO INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_BC_PROLABORISTAS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_BC_RAT(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_BC_SEGURADOS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_BC_TERCEIROS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_PROLAB_COLAB(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER,
PRTIPOCADASTRO INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_RATAPO(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_SALFAM(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_SALMATERNIDADE(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_COPIA_CENTROS_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_COPIA_CONTAS_PLANO(APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_COPIA_CONTAS_PLANO_FCONT(APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_COPIA_CONTAS_PLANO_SPED(APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_COPIA_FORMULAS_PLANO(APELIDO_NOVO_PLANO VARCHAR(20),
    CODIGONOVO integer,
    CODIGOCOPIAR integer,
    DMPLCPC26 bigint = 0,
    PRRELATORIO integer = 0,
    prvinculotpla INTEGER = 0)
 AS
 BEGIN EXIT; END
^

--#alt:13583 - Criado procedimento para copia dos lançamentos da planilha. Ana - 01/03/2017
CREATE OR ALTER PROCEDURE VSUC_COPIA_PLANILHA_TLAN(
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_COPIA_HISTORICOS_PLANO(APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_COPIA_HORARIO_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_COPIA_MOEDAS_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_GETDEMONSTRATIVO (
    PRCODEMP VARCHAR(2048),
    PRIGNORAZERAMENTO INTEGER,
    PRDETALHAFILIAL INTEGER,
    PRSALDOANTERIOR INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRDATAINI DATE,
    PRDATAFIN DATE,
    PREXPORTACAOECF INTEGER,
    PRINDICE INTEGER,
    PRCC VARCHAR(8192),
    PRDETALHAR_CC INTEGER,
    PRLANCNOTCC INTEGER,
    PRDETALHAR_TERC INTEGER,
    PRNIVELCC INTEGER,
    PRDATEINIZER date = null,
    PRDATEFINZER date = null,
    PREMPRESAGRPECO integer = 0,
    PRGRPECO integer = 0,
    PRELIMINACOESK300K315 integer = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDCODPLAPADRAO INTEGER,
    BDCODTPLA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDAPECTA VARCHAR(20),
    BDTIPCTA INTEGER,
    BDGRUPOCTA INTEGER,
    BDRELCTA INTEGER,
    BDSALANT NUMERIC(15,2),
    BDSALDEB NUMERIC(15,2),
    BDSALCRE NUMERIC(15,2),
    BDMOVPER NUMERIC(15,2),
    BDSALATU NUMERIC(15,2),
    BDSALANT1 NUMERIC(15,2),
    BDSALDEB1 NUMERIC(15,2),
    BDSALCRE1 NUMERIC(15,2),
    BDMOVPER1 NUMERIC(15,2),
    BDSALATU1 NUMERIC(15,2),
    BDSALANT2 NUMERIC(15,2),
    BDSALDEB2 NUMERIC(15,2),
    BDSALCRE2 NUMERIC(15,2),
    BDMOVPER2 NUMERIC(15,2),
    BDSALATU2 NUMERIC(15,2),
    BDCODTPCC INTEGER,
    BDNOMTPCC VARCHAR(2048),
    BDCODTER INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_NRO_NOTA_COMPL(PRCOMPL VARCHAR(200),
PRZEROESQ SMALLINT)
 RETURNS(NRONF VARCHAR(50))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RESTAURA_LANC_LIXEIRA (
PRCODEMP            INTEGER,
PRCHAVE             INTEGER,
PRTRANSACAO         INTEGER,
PRMANTERCHAVE       INTEGER,
PRNOVACHAVE         INTEGER,
PRNOVATRANSACAO     INTEGER,
PRIGNORAR_N_PRA_N   INTEGER = 0,
PRUPDATE_LANCAMENTO INTEGER = 0)
AS
 BEGIN END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RESTAURA_LANCS_LIXEIRA (
PRWHERE          VARCHAR(20000),
PRLANCDUPLICADOS INTEGER,
PRMANTERCHAVE    INTEGER,
PRCODEMP         INTEGER,
PRULTCHAVE       INTEGER,
PRULTTRANSACAO   INTEGER)
AS
 BEGIN  END
^

CREATE OR ALTER PROCEDURE VSUC_SP_MOVE_LANC_LIXEIRA (
PRCODEMP            INTEGER,
PRCHAVE             INTEGER,
PRIGNORAR_N_PRA_N   INTEGER = 0,
PRUPDATE_LANCAMENTO INTEGER = 0)
AS
 BEGIN END
^

CREATE OR ALTER PROCEDURE VSUC_SP_BALANCETE_MENSAL (
    PRCODEMP VARCHAR(2048),
    PRDATINI DATE,
    PRDATFIN DATE,
    PRIGNORA_ZERAMENTO INTEGER,
    PRCTAINI INTEGER,
    PRCTAFIN INTEGER,
    PRINDICE INTEGER,
    PRCODTPCC VARCHAR(8192),
    PRREFEMP INTEGER,
    PRLANSEMCC INTEGER,
    PRNAOMOSTRACONTACOMP INTEGER,
    PRCONSOLIDADA INTEGER,
    PRDETALHARCTAPARTICIPANTE INTEGER,
    PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
    PRCONCATENACODPARTICIPANTE INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRNIVELCC INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA SMALLINT,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDSALDO_ANT_DEB NUMERIC(15,2),
BDSALDO_ANT_CRE NUMERIC(15,2),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALDO_ATUAL NUMERIC(15,2),
BDGRPCTA SMALLINT,
BDTPCCLON VARCHAR(20),
BDMOVIMENTO NUMERIC(15,2),
BDFORMULA VARCHAR(200),
BDRELCTA INTEGER,
BDCLANOM VARCHAR(140),
BDDATINI DATE,
BDDATFIN DATE,
BDAPECTA VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_CENTRAL_CONCILIACAO (
    PRSQL VARCHAR(32000),
    PRPLANO_CONTA INTEGER,
    PRCONTA INTEGER,
    PRPARTICIPANTE INTEGER,
    PRSALDO_ANTERIOR NUMERIC(18,2),
    PRCONCILIACAO VARCHAR(100))
RETURNS (
    BDCODEMP INTEGER,
    BDCHAVE INTEGER,
    BDDATA DATE,
    BDDCTO VARCHAR(15),
    BDDEBITO INTEGER,
    BDCODTERCEIROD INTEGER,
    BDCREDITO INTEGER,
    BDCODTERCEIROC INTEGER,
    BDCODTPHI INTEGER,
    BDCOMPL VARCHAR(200),
    BDTIPOLAN INTEGER,
    BDTRANSACAO INTEGER,
    BDVALOR NUMERIC(18,2),
    BDSALDO NUMERIC(18,2),
    BDGRUPOCTA INTEGER,
    BDVALORDEB NUMERIC(18,2),
    BDVALORCRE NUMERIC(18,2),
    BDCONCILIADO INTEGER,
    BDDEBCRE INTEGER,
    BDCONCILIADOBASE INTEGER,
    BDBLOQUEADO VARCHAR(5),
    BDTIPOCONC INTEGER,
    BDDCTOZEROESQ varchar(15),
    BDNRODOCCOMPL Varchar(255))
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_BALANCO_PATRIMONIAL (
PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCTALONINI VARCHAR(40),
PRCTALONFIN VARCHAR(40),
PRCTALONPAS VARCHAR(40),
PRINDICE INTEGER,
PRLISTACC VARCHAR(8192),
PRNAOMOSTRACONTACOMP INTEGER,
PRREFEMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRSEMCC INTEGER,
PRAGRUPARPARTICIPANTEPORCNPJ INTEGER = 0,
PRDETALHAREMPREENDIMENTO INTEGER = 0,
PRDETALHARUNIDIMOB INTEGER = 0,
PRMOSTRARPROP INTEGER = 0,
PRAGRUPARPARTICIPANTEPORCPF INTEGER = 0,
PRCTAINI integer = 0,
PRCTAFIN integer = 0,
PRPLANOGRPECO integer = 0,
PREMPRESAGRPECO integer = 0,
PRGRPECO integer = 0,
PRELIMINACOESK300K315 integer = 0)
RETURNS (
BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(300),
BDTIPCTA INTEGER,
BDSEQCTA VARCHAR(40),
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(80),
BDSALANT NUMERIC(15,2),
BDSAL_ANT_DEB NUMERIC(15,2),
BDSAL_ANT_CRE NUMERIC(15,2),
BDSALMOV NUMERIC(15,2),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDFORMULA VARCHAR(1024),
BDCODEMPFILIAL INTEGER,
BDGRPCTA INTEGER,
BDAPECTA VARCHAR(20),
BDPERTENCECONTA INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_CONSOLIDADA(PRCODPLAPADRAO INTEGER,
PRCTALON VARCHAR(40))
 RETURNS(BDRESULT SMALLINT)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_COPIA_CONTAS_FORMULAS(PRCODPFOR INTEGER,
PRCODPLAPADRAO INTEGER,
PRCLASS VARCHAR(30000))
 AS
 BEGIN EXIT; END
^

create or alter procedure VSUC_SP_COPY_PREPARACAO_FOR_ECF_Y520 (
    PRCODPLAPADRAOFORM integer,
    PRCODPLAPADRAO integer,
    PRCODPAIS integer,
    PRDE_ANO integer,
    PRPARA_ANO integer,
    PROPCAO integer,
    PRTIPOY520 integer,
    PRFORMAY520 integer)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_EXPORTA_SPED_I300 (
    PRCODEMP VARCHAR(2048),
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRIGNORA_ZERAMENTO INTEGER,
    PRCODTPCC VARCHAR(8192),
    PRREFEMP INTEGER,
    PRLANSEMCC INTEGER,
    PRCONTABILIZACAO INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP VARCHAR(18),
    BDCODMATRIZ INTEGER,
    BDCODPLAPADRAO INTEGER,
    BDDATA DATE,
    BDCODCTA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDDEBITO NUMERIC(15,2),
    BDCREDITO NUMERIC(15,2),
    BDCODTPCC INTEGER,
    BDNOMTPCC VARCHAR(40),
    BDCODCENTROS INTEGER,
    BDCTALONCC VARCHAR(40))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_IMPORTAFORMULA (
    PRCODPLAPADRAO INTEGER,
    PRCODFOR INTEGER,
    PRNIVELINI INTEGER,
    PRNIVELFIM INTEGER,
    PRCTALONINI VARCHAR(40),
    PRCTALONFIM VARCHAR(40),
    PRQUADRO INTEGER = 0)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_INSERT_ENCEX(PRCODEMP INTEGER,
PRCODPLANOS INTEGER,
PRCODTPLA INTEGER,
PRCODHIST INTEGER,
PRCODTPHI INTEGER,
PRCODUSU INTEGER,
PRDATAINIZER DATE,
PRDATAFIMZER DATE,
PRDATALANCZER DATE,
PRDATAZER DATE,
PRHORAZER TIMESTAMP)
 RETURNS(PRCHAVEZER INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_INSERT_LANC(PRCHAVE INTEGER,
PRCODEMP INTEGER,
PRCODPLAPADRAO INTEGER,
PRDEBITO INTEGER,
PRCREDITO INTEGER,
PRCODHIST INTEGER,
PRCODTPHI INTEGER,
PRUSUARIO INTEGER,
PRLOTE VARCHAR(10),
PRDATA DATE,
PRVALOR NUMERIC(15,2),
PRCOMPL VARCHAR(100),
PRDATALAN DATE,
PRHORALAN TIME,
PRTIPOLAN SMALLINT,
PRDCTO VARCHAR(5),
PRCONCD VARCHAR(5),
PRCONCC VARCHAR(5),
PRCHAVEZER INTEGER,
PRREFEMP INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_LISTA_CTA_RAZAO_VIDEO(PRCODEMP VARCHAR(2048),
PRCODPLAPADRAO INTEGER,
PRDATINI DATE,
PRDATFIM DATE,
PRCTALONINI VARCHAR(40),
PRCTALONFIM VARCHAR(40),
PRTIPORAZAO INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODTPLA INTEGER,
BDNOMCTA VARCHAR(100),
BDCTALON VARCHAR(40),
BDCODPARTICIPANTE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_LISTA_CTA_RAZAO_VIDEO_X(
    PRCODEMP VARCHAR(2048),
    PRCODPLAPADRAO INTEGER,
    PRDATINI DATE,
    PRDATFIM DATE,
    PRCTALONINI VARCHAR(40),
    PRCTALONFIM VARCHAR(40),
    PRTIPORAZAO VARCHAR(20),
    PRPARTINI INTEGER,
    PRPARTFIM INTEGER,
    PRDETALHARCTAPARTICIPANTE INTEGER,
    PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRDETALHARCC INTEGER,
    PRLCC VARCHAR(8192),
    PRLANCAMENTOSEMCC INTEGER,
    PRDETALHAREMPREENDIMENTO INTEGER = 0,
    PRDETALHARUNIDIMOB INTEGER = 0,
    PRMOSTRARPROPUNIDADE INTEGER = 0,
    PRAGRUPARPARTICIPANTEPORCPF INTEGER = 0,
    PRORDEM INTEGER = 0,
    PRTIPOLAN varchar(3200) = '')
RETURNS (
    BDCODTPLA INTEGER,
    BDNOMCTA VARCHAR(300),
    BDCTALON VARCHAR(40),
    BDCODPARTICIPANTE INTEGER,
    BDCNPJPART VARCHAR(20),
    BDEMPREENDIMENTO INTEGER,
    BDUNIDIMOB INTEGER,
    BDCODEMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_LISTA_TLAN_CONC_CLIFOR(PREMPRESA INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRCLIFOR SMALLINT,
PRLANCONC SMALLINT,
PRZEROESQ SMALLINT,
PRCODPLAPADRAO INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(CONCILIACAOOK SMALLINT)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_MOVIMENTO_MENSAL(
    PRCODEMP VARCHAR(1024),
    PRCONTA INTEGER,
    PRCC VARCHAR(8192),
    PRANOINICIAL INTEGER,
    PRANOFINAL INTEGER,
    PRREFEMP INTEGER,
    PRPARTICIPANTE INTEGER,
    PRIGNORAZERAMENTO INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER) 
RETURNS (
    BDDEB01 NUMERIC(15,2),
    BDDEB02 NUMERIC(15,2),
    BDDEB03 NUMERIC(15,2),
    BDDEB04 NUMERIC(15,2),
    BDDEB05 NUMERIC(15,2),
    BDDEB06 NUMERIC(15,2),
    BDDEB07 NUMERIC(15,2),
    BDDEB08 NUMERIC(15,2),
    BDDEB09 NUMERIC(15,2),
    BDDEB10 NUMERIC(15,2),
    BDDEB11 NUMERIC(15,2),
    BDDEB12 NUMERIC(15,2),
    BDCRE01 NUMERIC(15,2),
    BDCRE02 NUMERIC(15,2),
    BDCRE03 NUMERIC(15,2),
    BDCRE04 NUMERIC(15,2),
    BDCRE05 NUMERIC(15,2),
    BDCRE06 NUMERIC(15,2),
    BDCRE07 NUMERIC(15,2),
    BDCRE08 NUMERIC(15,2),
    BDCRE09 NUMERIC(15,2),
    BDCRE10 NUMERIC(15,2),
    BDCRE11 NUMERIC(15,2),
    BDCRE12 NUMERIC(15,2),
    BDMOV01 NUMERIC(15,2),
    BDMOV02 NUMERIC(15,2),
    BDMOV03 NUMERIC(15,2),
    BDMOV04 NUMERIC(15,2),
    BDMOV05 NUMERIC(15,2),
    BDMOV06 NUMERIC(15,2),
    BDMOV07 NUMERIC(15,2),
    BDMOV08 NUMERIC(15,2),
    BDMOV09 NUMERIC(15,2),
    BDMOV10 NUMERIC(15,2),
    BDMOV11 NUMERIC(15,2),
    BDMOV12 NUMERIC(15,2),
    BDSAL01 NUMERIC(15,2),
    BDSAL02 NUMERIC(15,2),
    BDSAL03 NUMERIC(15,2),
    BDSAL04 NUMERIC(15,2),
    BDSAL05 NUMERIC(15,2),
    BDSAL06 NUMERIC(15,2),
    BDSAL07 NUMERIC(15,2),
    BDSAL08 NUMERIC(15,2),
    BDSAL09 NUMERIC(15,2),
    BDSAL10 NUMERIC(15,2),
    BDSAL11 NUMERIC(15,2),
    BDSAL12 NUMERIC(15,2),
    BDSALTOTDEB NUMERIC(15,2),
    BDSALTOTCRE NUMERIC(15,2),
    BDSALTOTMOV NUMERIC(15,2),
    BDSALTOTATU NUMERIC(15,2),
    BDANO INTEGER,
    BDGRPCTA INTEGER,
    BDDEBANT NUMERIC(15,2),
    BDCREANT NUMERIC(15,2),
    BDMOVANT NUMERIC(15,2),
    BDSALANT NUMERIC(15,2)) 
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_NOMENCLATURA_CTA_PARTIC (
    PRCODTERCEIRO INTEGER,
    PRCLASSIFICACAO VARCHAR(40),
    PRCONCATENA INTEGER,
    PRREFEMP INTEGER) -- #149080 - Marcela - Razão/Diário/Balancete - Verificar data de emissão pra nome de contas de participante 12/07/2022
RETURNS (
    BDNOME VARCHAR(100),
    BDCLASSIFICACAO VARCHAR(100))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VSUC_SP_RETORNA_BALANCETE (
    PRCODEMP varchar(2048),
    PRDATINI date,
    PRDATFIN date,
    PRIGNORA_ZERAMENTO integer,
    PRCTAINI integer,
    PRCTAFIN integer,
    PRINDICE integer,
    PRCODTPCC varchar(32000),
    PRREFEMP integer,
    PRLANSEMCC integer,
    PRORDEM integer,
    PRNAOMOSTRACONTACOMP integer,
    PRCONSOLIDADA integer,
    PRDETALHARCTAPARTICIPANTE integer,
    PRAGRUPARPARTICIPANTEPORCNPJ integer,
    PRCONCATENACODPARTICIPANTE integer,
    PRNIVEISCONTA varchar(50),
    PRTODASASCONTAS integer,
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRDRE integer = 0,
    PRTODOPLANOCONTAS integer = 0,
    PRDETALHAREMPREENDIMENTO integer = 0,
    PRDETALHARUNIDIMOB integer = 0,
    PRMOSTRARPROP integer = 0,
    PRDADOSIMPRIMIR integer = 0,
    PRAGRUPARPARTICIPANTEPORCPF integer = 0,
    PRNIVELCC integer = 0,
    PRSOMENTEMOVIMENTO integer = 0,
    PREMPREENDIMENTO varchar(32000) = '',
    PRPLANOGRPECO integer = 0,
    PREMPRESAGRPECO integer = 0,
    PRGRPECO integer = 0,
    PRTODOSPART varchar(2048) = '',
    PRDETALHARCCEMPREEND integer = 0,
    PRIGNZERPERANT integer = 0,
    PRTIPOLAN varchar(3200) = '',
    PRELIMINACOESK300K315 integer = 0)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(18),
    BDCODMATRIZ integer,
    BDCODEMPFILIAL integer,
    BDCODPLAPADRAO integer,
    BDCODCTA integer,
    BDCTALON varchar(60),
    BDNOMCTA varchar(300),
    BDTIPCTA smallint,
    BDCODTPCC integer,
    BDNOMTPCC varchar(40),
    BDSALDO_ANTERIOR numeric(15,2),
    BDSALDO_ANT_DEB numeric(15,2),
    BDSALDO_ANT_CRE numeric(15,2),
    BDSALDO_DEB numeric(15,2),
    BDSALDO_CRE numeric(15,2),
    BDSALDO_ATUAL numeric(15,2),
    BDGRPCTA smallint,
    BDTPCCLON varchar(20),
    BDMOVIMENTO numeric(15,2),
    BDFORMULA varchar(200),
    BDRELCTA integer,
    BDCLANOM varchar(340),
    BDCODTER integer,
    BDAPECTA varchar(20),
    BDSALDO_ANTERIOR_DRE numeric(15,2),
    BDSALDO_ANT_DEB_DRE numeric(15,2),
    BDSALDO_ANT_CRE_DRE numeric(15,2),
    BDRAIZCNPJPARTICIPANTE varchar(10),
    BDRAIZCLASSIFICACAOCTA varchar(40),
    BDCODUNIDIMOB integer,
    BDCODEMPREENDIMENTO integer,
    BDAPEEMP DM_BDAPEMP,
    BDVALORCOMPFILIAIS numeric(15,2),
    BDSALDO_SEM_CONCILIACAO numeric(15,2),
    BDSALDO_ATUAL_REAL numeric(15,2),
    BDFILTROCC varchar(200),
    BDCODNE integer,
    BDCPFCNPJTER varchar(18),
    BDCTACOMP varchar(5),
    BDDATAULTLANC date,
    BDCODTARBANCARIA integer,
    BDVALORUNIT numeric(15,2),
    BDVALORPERCENT numeric(15,2))
as
 BEGIN SUSPEND; END
^

--#alt:23030. Ana - 15/03/2018
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDOS_CTAINCOR (
    PRCODEMP INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRDTINICIAL DATE,
    PRDTFINAL DATE,
    PRCONTA INTEGER,
    PRINDICE INTEGER,
    PRIGNORAZERAMENTO INTEGER,
    PRCONCILIADOS INTEGER,
    PREMPRESAS VARCHAR(2048),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRCTALONANT VARCHAR(40),
    PRCTATITULO INTEGER,
    PRRAIZCTASEMEMPREENDIMENTOANT VARCHAR(40),
    PRDETALHAREMPREENDIMENTO INTEGER,
    PRDETALHARUNIDIMOB INTEGER,
    PRMOSTRARPROP integer,
    PRCC integer = 0,
    PRLANCSEMCC integer = 0,
    PRDETALHARCC integer = 0)
RETURNS (
    BDCLASSIFICACAO VARCHAR(40),
    BDSALDO_DEB NUMERIC(15,2),
    BDSALDO_ANT_DEB NUMERIC(15,2),
    BDSALDO_CRE NUMERIC(15,2),
    BDSALDO_ANT_CRE NUMERIC(15,2),
    BDMOVIMENTO NUMERIC(15,2),
    BDSALDO_ATUAL NUMERIC(15,2),
    BDSALDO_ANTERIOR NUMERIC(15,2),
    BDRAIZCLASSIFICACAOCTA VARCHAR(40),
    BDCODEMPREENDIMENTO INTEGER,
    BDCODUNIDIMOB INTEGER,
    BDDESCEMPREENDIMENTO VARCHAR(500),
    BDDESCUNIDIMOB VARCHAR(500),
    BDRAIZCTASEMEMPREENDIMENTO VARCHAR(40))
AS
  BEGIN SUSPEND; END
^

--Carlos Machado - #alt:123617 - 19/08/2019
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDOS_INCORP_2 (
    PRCODEMP INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRDTINICIAL DATE,
    PRDTFINAL DATE,
    PRCONTA INTEGER,
    PRINDICE INTEGER,
    PRIGNORAZERAMENTO INTEGER,
    PRCONCILIADOS INTEGER,
    PREMPRESAS VARCHAR(2048),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRCTALONANT VARCHAR(40),
    PRCTATITULO INTEGER,
    PRRAIZCTASEMEMPREENDIMENTOANT VARCHAR(40),
    PRDETALHAREMPREENDIMENTO INTEGER,
    PRDETALHARUNIDIMOB INTEGER,
    PRMOSTRARPROP INTEGER,
    PRCC INTEGER = 0,
    PRLANCSEMCC INTEGER = 0,
    PRDETALHARCC INTEGER = 0,
    PRNIVELCC INTEGER = 0,
    PREMPREENDIMENTO varchar(32000) = '',
    PRDETALHARCCEMPREEND integer = 0,
    PRTIPOLAN varchar(3200) = '')

RETURNS (
    BDCLASSIFICACAO VARCHAR(40),
    BDSALDO_DEB NUMERIC(15,2),
    BDSALDO_ANT_DEB NUMERIC(15,2),
    BDSALDO_CRE NUMERIC(15,2),
    BDSALDO_ANT_CRE NUMERIC(15,2),
    BDMOVIMENTO NUMERIC(15,2),
    BDSALDO_ATUAL NUMERIC(15,2),
    BDSALDO_ANTERIOR NUMERIC(15,2),
    BDRAIZCLASSIFICACAOCTA VARCHAR(40),
    BDCODEMPREENDIMENTO INTEGER,
    BDCODUNIDIMOB INTEGER,
    BDDESCEMPREENDIMENTO VARCHAR(500),
    BDDESCUNIDIMOB VARCHAR(500),
    BDRAIZCTASEMEMPREENDIMENTO VARCHAR(40),
    BDDATAULTLANCAMENTO date,
    BDCODTPCC integer)
AS
  BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_RETORNA_CLA_INCORP (
    PRCODCTA INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRCODEMPREENDIMENTO INTEGER,
    PRUNIDIMOB INTEGER,
    PRNAODETALHAREMPREENDIMENTO integer = 0,
    PRNAODETALHARUNIDIMOB integer = 0,
    PREMPRESA integer = 0)
RETURNS (
    BDCLASSIFICACAO VARCHAR(40))
AS
  BEGIN SUSPEND; END
^
--#alt:23030. fim

CREATE OR ALTER PROCEDURE SP_REMOVE_CLASS_ZERADAS (
    PRCLASSIFICACAO VARCHAR(40),
    PRRETIRAZEROSFINAL DM_BOOLEAN = 'FALSE')
RETURNS (
    BDCLASSIFICACAO VARCHAR(40))
AS
BEGIN SUSPEND; END^

CREATE OR ALTER PROCEDURE VSUC_COPIA_PLANO_SECUNDARIO (
    PRAPELIDONOVO VARCHAR(20),
    PRCODIGONOVO INTEGER,
    PRCODIGOCOPIAR INTEGER)
AS
BEGIN END^

create or alter procedure VSUC_COPIA_PLANO_TROCA (
    CODIGONOVO integer,
    CODIGOCOPIAR integer)
AS
BEGIN END^

--#alt:18801. Alterei a estrutura da procedure. Ana - 18/05/2017
--#alt:15089. Ana - 15/03/2017
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_CONTAS_I157 (
    PRCODPLAPADRAO INTEGER,
    PRCODPLAPADRAOI157 INTEGER,
    PRMODELO integer = 0)
RETURNS (
    BDCODTPLAI157 INTEGER,
    BDCTALONI157 VARCHAR(40),
    BDNOMCTAI157 VARCHAR(100),
    BDTIPCTA INTEGER,
    BDCODTPLA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDCODTER INTEGER,
    BDNOMETER VARCHAR(100),
    BDCODEMPREENDIMENTO integer,
    BDCODIGOUNIIMOB integer,
    BDFILIAL integer,
    BDDEBCRE_ORIGINAL VARCHAR(1),
    BDVALOR_ORIGINAL NUMERIC(15,2),
    BDCTALON_FISICO VARCHAR(100),
    BDPARTICIPANTE integer)
AS
 BEGIN SUSPEND; END
^

DROP VIEW VWGR_SCI_EMPRESAS^
DROP VIEW VWGR_SCI_EMPRESAS_SOCIOS^

create or alter procedure SP_GR_SCI_EMPRESAS (
    PRTODOSSOCIOS integer = 0,
    PRLISTAEMPRESAS varchar(10000) = null,
    PRVERIFICACEI smallint = 0,
    PRTBTEMP smallint = 0)
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDCNPJEMP varchar(18),
    BDDATAINIATIVEMP date,
    BDORGAOEMP varchar(8),
    BDDATAREGEMP date,
    BDDATACONSTEMP date,
    BDDESCCARTEMP varchar(40),
    BDDATAFIMATIVEMP date,
    BDREFEMP integer,
    BDCODPLAPADRAO integer,
    BDCODHIST integer,
    BDCODCENTROS integer,
    BDCODPLATRIB integer,
    BDCODCID integer,
    BDCODCONT integer,
    BDCODNATJUR integer,
    BDCODCNAE integer,
    BDNOMEMP varchar(100),
    BDAPEEMP varchar(20),
    BDENDEMP varchar(60),
    BDNUMEMP DM_NUMEND,
    BDBAIEMP varchar(50),
    BDCEPEMP varchar(9),
    BDDDDEMP integer,
    BDFONEEMP varchar(15),
    BDFAXEMP varchar(15),
    BDEMAILEMP varchar(200),
    BDCOMPLEMP varchar(60),
    BDLOGREMP varchar(15),
    BDIEEMP varchar(20),
    BDIMEMP varchar(20),
    BDSITEMP varchar(5),
    BDCODPLANOONLINE integer,
    BDLOGOEMP blob sub_type 0 segment size 80,
    BDNOMESC varchar(100),
    BDINIATIVESC date,
    BDFIMATIVESC date,
    BDLOGOESC blob sub_type 0 segment size 80,
    BDLOGRESC varchar(15),
    BDENDESC varchar(60),
    BDNUMESC DM_NUMEND,
    BDBAIESC varchar(50),
    BDCEPESC varchar(9),
    BDCNPJESC varchar(18),
    BDDDDESC integer,
    BDFONEESC varchar(15),
    BDRAMALESC varchar(6),
    BDEMAILESC varchar(200),
    BDCONTTERCESC varchar(5),
    BDCOMPLESC varchar(60),
    BDFAXESC varchar(15),
    BDCODCIDESC integer,
    BDCRCESC varchar(15),
    BDAPEPLA varchar(20),
    BDNOMPLA varchar(80),
    BDNOMCID varchar(40),
    BDANIVCID varchar(4),
    BDSIGLAUF varchar(2),
    BDDESCUF varchar(40),
    BDNOMECONT varchar(40),
    BDCPFCONT varchar(14),
    BDCRCCONT varchar(15),
    BDENDCONT varchar(60),
    BDLOGRCONT varchar(15),
    BDNUMEROCONT DM_NUMEND,
    BDCOMPLCONT varchar(60),
    BDCEPCONT varchar(9),
    BDBAIRROCONT varchar(50),
    BDDDDCONT integer,
    BDFONECONT varchar(15),
    BDFAXCONT varchar(15),
    BDEMAILCONT varchar(200),
    BDCMCCONT varchar(14),
    BDESCOLARIDADECONT integer,
    BDTIPOCONTABILISTA integer,
    BDCODOCUPA integer,
    BDCODQUACONT integer,
    BDCODQUA varchar(100),
    BDREGJUN varchar(30),
    BDCODCIDSOC integer,
    BDNOMSOC varchar(80),
    BDENDSOC varchar(60),
    BDNUMSOC DM_NUMEND,
    BDCOMPLSOC varchar(60),
    BDBAISOC varchar(60),
    BDCEPSOC varchar(9),
    BDCGCCEISOC varchar(18),
    BDDDSOC integer,
    BDTELRESSOC varchar(15),
    BDTELCELSOC varchar(15),
    BDEMAILSOC varchar(200),
    BDLOGRSOC varchar(15),
    BDQUALIRESPLEGALSOC integer,
    BDEXTERIORSOC varchar(5),
    BDDATAENTSOC date,
    BDDATASAISOC date,
    BDCODPAISSOC integer,
    BDQUALIFICACAOSOC varchar(100),
    BDDESCQUALISOC varchar(100),
    BDRESPONSAVELSOC varchar(5),
    BDCPFRESPLEGALSOC varchar(14),
    BDPARAMREL integer,
    BDEXPQUALISOC integer,
    BDQUALISOCDIPJ varchar(100),
    BDDESCQUALISOCREP varchar(100),
    BDDESCQUALISOCSPED varchar(100),
    BDPERSONALIZACAO varchar(113),
    BDQTDCOTASOC numeric(15,2),
    BDVALCOTASOC numeric(15,2),
    BDPERCCOTASOC numeric(15,2),
    BDCODCONTEF integer,
    BDNOMECONTEF varchar(40),
    BDCPFCONTEF varchar(14),
    BDCRCCONTEF varchar(15),
    BDENDCONTEF varchar(60),
    BDLOGRCONTEF varchar(15),
    BDNUMEROCONTEF DM_NUMEND,
    BDCOMPLCONTEF varchar(60),
    BDCEPCONTEF varchar(9),
    BDBAIRROCONTEF varchar(50),
    BDDDDCONTEF integer,
    BDFONECONTEF varchar(15),
    BDFAXCONTEF varchar(15),
    BDEMAILCONTEF varchar(200),
    BDCMCCONTEF varchar(14),
    BDESCOLARIDADECONTEF integer,
    BDTIPOCONTABILISTAEF integer,
    BDCODOCUPAEF integer,
    BDCODCONTRH integer,
    BDNOMECONTRH varchar(40),
    BDCPFCONTRH varchar(14),
    BDCRCCONTRH varchar(15),
    BDENDCONTRH varchar(60),
    BDLOGRCONTRH varchar(15),
    BDNUMEROCONTRH DM_NUMEND,
    BDCOMPLCONTRH varchar(60),
    BDCEPCONTRH varchar(9),
    BDBAIRROCONTRH varchar(50),
    BDDDDCONTRH integer,
    BDFONECONTRH varchar(15),
    BDFAXCONTRH varchar(15),
    BDEMAILCONTRH varchar(200),
    BDCMCCONTRH varchar(14),
    BDESCOLARIDADECONTRH integer,
    BDTIPOCONTABILISTARH integer,
    BDCODOCUPARH integer,
    BDLIVRO varchar(15),
    BDFOLHA varchar(15),
    BDNOMECARTORIO varchar(100),
    BDRGSOC varchar(13),
    BDORGEMISOC varchar(20),
    BDSIGLAUFRG varchar(2),
    BDDESCUFRG varchar(40),
    BDESTCIVILSOC char(22),
    BDCODCBO integer,
    BDDESCCBO varchar(150),
    BDCODACESSOSN varchar(12),
    BDSECAOCNAE varchar(1),
    BDTIPOCNAE integer,
    BDCLASSIFICACAOCNAE varchar(20),
    BDDESCCNAE varchar(200),
    BDDESCCNAEADICIONAIS varchar(10000),
    BDNOMCIDESC varchar(40),
    BDSIGLAUFESC varchar(2),
    BDCODESC integer,
    BDCODSOC integer,
    BDCODFPAS integer,
    BDASSINATURACONTEF blob sub_type 0 segment size 80,
    BDASSINATURASOC blob sub_type 0 segment size 80,
    BDREGIMETRIBUTACAO varchar(100),
    BDTIPOAPURACAO varchar(40),
    BDCODZONA integer,
    BDNOMEZONA varchar(40),
    BDDESCNAT varchar(100),
    BDCEIEMP DM_CNPJ_CPF,
    BDCODIBGE integer,
    BDFORMATRIBUTACAO varchar(50),
    BDDESCATIVIDADE varchar(100),
    BDDESCANEXOS varchar(100),
    BDDESCANEXOS_2018 varchar(100),
    BDSOCREPRESENTANTE varchar(80),
    BDCODCLATRI integer,
    BDDATANASCSOC date,
    BDDESCENQFED varchar(6))
as
begin
  suspend;
end^


CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_BALANCETE_COMPA(PRCODEMP VARCHAR(2048),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRTIPCOMP INTEGER,
PRQTDCOMP INTEGER,
PRCODTPCC VARCHAR(8192),
PRIGNZER SMALLINT,
PRREFEMP INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDCODMATRIZ INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCENTROS INTEGER,
BDCODTPLA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDSALANT NUMERIC(15,2),
BDSALATU_01 NUMERIC(15,2),
BDSALMOV_01 NUMERIC(15,2),
BDSALATU_02 NUMERIC(15,2),
BDSALMOV_02 NUMERIC(15,2),
BDSALATU_03 NUMERIC(15,2),
BDSALMOV_03 NUMERIC(15,2),
BDSALATU_04 NUMERIC(15,2),
BDSALMOV_04 NUMERIC(15,2),
BDSALATU_05 NUMERIC(15,2),
BDSALMOV_05 NUMERIC(15,2),
BDSALATU_06 NUMERIC(15,2),
BDSALMOV_06 NUMERIC(15,2),
BDSALATU_07 NUMERIC(15,2),
BDSALMOV_07 NUMERIC(15,2),
BDSALATU_08 NUMERIC(15,2),
BDSALMOV_08 NUMERIC(15,2),
BDSALATU_09 NUMERIC(15,2),
BDSALMOV_09 NUMERIC(15,2),
BDSALATU_10 NUMERIC(15,2),
BDSALMOV_10 NUMERIC(15,2),
BDSALATU_11 NUMERIC(15,2),
BDSALMOV_11 NUMERIC(15,2),
BDSALATU_12 NUMERIC(15,2),
BDSALMOV_12 NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_BALANCO_PATRIMO (
    PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCTALONINI VARCHAR(40),
PRCTALONFIN VARCHAR(40),
PRCTALONPAS VARCHAR(40),
PRINDICE INTEGER,
PRLISTACC VARCHAR(8192),
PRNAOMOSTRACONTACOMP INTEGER,
PRCTASEMMOV INTEGER,
PRREFEMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRAGRUPARPARTICIPANTEPORCNPJ INTEGER = 0,
    PRAGRUPARPARTICIPANTEPORCPF INTEGER = 0)
RETURNS (
    BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDSEQCTA VARCHAR(40),
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(80),
BDSALANT NUMERIC(15,2),
BDSALMOV NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDANAVER NUMERIC(15,2),
BDFORMULA VARCHAR(1024),
BDGRPCTA INTEGER,
BDAPECTA VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_CADASTRO_BEM(PRCODEMP INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRCODPLAPADRAO INTEGER,
PRCONTABILIZACAO INTEGER,
PRMOSTRARDEPRECIADOS INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODBEM INTEGER,
BDDATATAXADEPRECIACAO DATE,
BDMESESDEPRECIADOS INTEGER,
BDDEPRECIACAOPERIODO NUMERIC(15,2),
BDDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
BDVALORRESIDUALCONTABIL NUMERIC(15,2),
BDVALORRESIDUALCONTABILMOEDA NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_CLASSGROUP(PRCODPLANOPADRAO INTEGER,
PRCAMPOPESQUISA VARCHAR(20),
PRCONTEUDO VARCHAR(40),
PRPESQUISAINICIO INTEGER)
 RETURNS(PRCLASSIFICACAO VARCHAR(40))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_COMPARATIVO(PREMPRESAS VARCHAR(1024),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRINDICE INTEGER,
PRTIPCOMP INTEGER,
PRCC VARCHAR(8192),
PRTIPOSALDO INTEGER,
PRREFEMP INTEGER,
PRIGNZER INTEGER,
PRLANSEMCC INTEGER,
PRAGRUPAEMPRESAFILIAIS INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(50),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDGRPCTA INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDQTDCOMP INTEGER,
BDSALDO01 NUMERIC(15,2),
BDMOVIMENTO01 NUMERIC(15,2),
BDSALDO02 NUMERIC(15,2),
BDMOVIMENTO02 NUMERIC(15,2),
BDSALDO03 NUMERIC(15,2),
BDMOVIMENTO03 NUMERIC(15,2),
BDSALDO04 NUMERIC(15,2),
BDMOVIMENTO04 NUMERIC(15,2),
BDSALDO05 NUMERIC(15,2),
BDMOVIMENTO05 NUMERIC(15,2),
BDSALDO06 NUMERIC(15,2),
BDMOVIMENTO06 NUMERIC(15,2),
BDSALDO07 NUMERIC(15,2),
BDMOVIMENTO07 NUMERIC(15,2),
BDSALDO08 NUMERIC(15,2),
BDMOVIMENTO08 NUMERIC(15,2),
BDSALDO09 NUMERIC(15,2),
BDMOVIMENTO09 NUMERIC(15,2),
BDSALDO10 NUMERIC(15,2),
BDMOVIMENTO10 NUMERIC(15,2),
BDSALDO11 NUMERIC(15,2),
BDMOVIMENTO11 NUMERIC(15,2),
BDSALDO12 NUMERIC(15,2),
BDMOVIMENTO12 NUMERIC(15,2),
BDFORMULA VARCHAR(1024))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VSUC_SP_RETORNA_COMPARATIVO_X (
    PRCODEMP varchar(2048),
    PRCTAINI integer,
    PRCTAFIN integer,
    PRDATAINI date,
    PRDATAFIN date,
    PRINDICE integer,
    PRCTASEMMOV integer,
    PRIMPRIMIRCOLUNASEXTRAS integer,
    PRTIPCOMP integer,
    PRCODTPCC varchar(32000),
    PRTIPOSALDO integer,
    PRREFEMP integer,
    PRIGNZER integer,
    PRLANSEMCC integer,
    PRAGRUPAEMPRESAFILIAIS integer,
    PRDETALHARCTAPARTICIPANTE integer,
    PRCONCATENACODPARTICIPANTE integer,
    PRNIVEISCONTA varchar(50),
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRCTACONSOLIDADA integer,
    PRFORMACALC integer = 0,
    PRAGRUPARPORCNPJ integer = 0,
    PRAGRUPARPORCPF integer = 0,
    PRTODASCTAS integer = 0)
returns (
    BDCODEMP integer,
    BDCODEMPFILIAL integer,
    BDNOMEMP varchar(100),
    BDCODMATRIZ integer,
    BDCNPJEMP varchar(18),
    BDCODPLAPADRAO integer,
    BDCODCTA integer,
    BDCTALON varchar(50),
    BDNOMCTA varchar(100),
    BDCLANOM varchar(150),
    BDTIPCTA integer,
    BDGRPCTA integer,
    BDCODTPCC integer,
    BDNOMTPCC varchar(40),
    BDQTDCOMP integer,
    BDFORMULA varchar(1024),
    BDSALDO01 numeric(15,2),
    BDMOVIMENTO01 numeric(15,2),
    BDSALDOREAL01 numeric(15,2),
    BDSALDO02 numeric(15,2),
    BDMOVIMENTO02 numeric(15,2),
    BDSALDOREAL02 numeric(15,2),
    BDSALDO03 numeric(15,2),
    BDMOVIMENTO03 numeric(15,2),
    BDSALDOREAL03 numeric(15,2),
    BDSALDO04 numeric(15,2),
    BDMOVIMENTO04 numeric(15,2),
    BDSALDOREAL04 numeric(15,2),
    BDSALDO05 numeric(15,2),
    BDMOVIMENTO05 numeric(15,2),
    BDSALDOREAL05 numeric(15,2),
    BDSALDO06 numeric(15,2),
    BDMOVIMENTO06 numeric(15,2),
    BDSALDOREAL06 numeric(15,2),
    BDSALDO07 numeric(15,2),
    BDMOVIMENTO07 numeric(15,2),
    BDSALDOREAL07 numeric(15,2),
    BDSALDO08 numeric(15,2),
    BDMOVIMENTO08 numeric(15,2),
    BDSALDOREAL08 numeric(15,2),
    BDSALDO09 numeric(15,2),
    BDMOVIMENTO09 numeric(15,2),
    BDSALDOREAL09 numeric(15,2),
    BDSALDO10 numeric(15,2),
    BDMOVIMENTO10 numeric(15,2),
    BDSALDOREAL10 numeric(15,2),
    BDSALDO11 numeric(15,2),
    BDMOVIMENTO11 numeric(15,2),
    BDSALDOREAL11 numeric(15,2),
    BDSALDO12 numeric(15,2),
    BDMOVIMENTO12 numeric(15,2),
    BDSALDOREAL12 numeric(15,2),
    BDMEDIASALDO numeric(15,2),
    BDTOTALSALDO numeric(15,2),
    BDMEDIAMOVIMENTO numeric(15,2),
    BDTOTALMOVIMENTO numeric(15,2))
AS
 BEGIN SUSPEND; END
^

create or alter procedure VSUC_SP_RETORNA_COMPARATIVO_Y (
    PRCODEMP varchar(2048),
    PRCTAINI integer,
    PRCTAFIN integer,
    PRDATAINI date,
    PRDATAFIN date,
    PRINDICE integer,
    PRCTASEMMOV integer,
    PRTIPCOMP integer,
    PRCODTPCC varchar(32000),
    PRTIPOSALDO integer,
    PRREFEMP integer,
    PRIGNZER integer,
    PRLANSEMCC integer,
    PRAGRUPAEMPRESAFILIAIS integer,
    PRDETALHARCTAPARTICIPANTE integer,
    PRNIVEISCONTA varchar(50),
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRCTACONSOLIDADA integer,
    PRAGRUPARPORCNPJ integer = 0,
    PRAGRUPARPORCPF integer = 0,
    PRTODASCTAS integer = 0)
returns (
    BDCODEMP integer,
    BDCODEMPFILIAL integer,
    BDNOMEMP varchar(100),
    BDCODMATRIZ integer,
    BDCNPJEMP varchar(18),
    BDCODPLAPADRAO integer,
    BDCODCTA integer,
    BDCTALON varchar(50),
    BDNOMCTA varchar(100),
    BDCLANOM varchar(150),
    BDTIPCTA integer,
    BDGRPCTA integer,
    BDCODTPCC integer,
    BDNOMTPCC varchar(40),
    BDQTDCOMP integer,
    BDFORMULA varchar(1024),
    BDSALDO01 numeric(15,2),
    BDMOVIMENTO01 numeric(15,2),
    BDSALDOREAL01 numeric(15,2),
    BDSALDO02 numeric(15,2),
    BDMOVIMENTO02 numeric(15,2),
    BDSALDOREAL02 numeric(15,2),
    BDSALDO03 numeric(15,2),
    BDMOVIMENTO03 numeric(15,2),
    BDSALDOREAL03 numeric(15,2),
    BDSALDO04 numeric(15,2),
    BDMOVIMENTO04 numeric(15,2),
    BDSALDOREAL04 numeric(15,2),
    BDSALDO05 numeric(15,2),
    BDMOVIMENTO05 numeric(15,2),
    BDSALDOREAL05 numeric(15,2),
    BDSALDO06 numeric(15,2),
    BDMOVIMENTO06 numeric(15,2),
    BDSALDOREAL06 numeric(15,2),
    BDSALDO07 numeric(15,2),
    BDMOVIMENTO07 numeric(15,2),
    BDSALDOREAL07 numeric(15,2),
    BDSALDO08 numeric(15,2),
    BDMOVIMENTO08 numeric(15,2),
    BDSALDOREAL08 numeric(15,2),
    BDSALDO09 numeric(15,2),
    BDMOVIMENTO09 numeric(15,2),
    BDSALDOREAL09 numeric(15,2),
    BDSALDO10 numeric(15,2),
    BDMOVIMENTO10 numeric(15,2),
    BDSALDOREAL10 numeric(15,2),
    BDSALDO11 numeric(15,2),
    BDMOVIMENTO11 numeric(15,2),
    BDSALDOREAL11 numeric(15,2),
    BDSALDO12 numeric(15,2),
    BDMOVIMENTO12 numeric(15,2),
    BDSALDOREAL12 numeric(15,2),
    BDMEDIASALDO numeric(15,2),
    BDTOTALSALDO numeric(15,2),
    BDMEDIAMOVIMENTO numeric(15,2),
    BDTOTALMOVIMENTO numeric(15,2))
AS
 BEGIN SUSPEND; END
^

create or alter procedure VSUC_SP_RETORNA_CONTR_PATRIMON (
    PRCODEMP varchar(2048),
    PRCTAINI integer,
    PRCTAFIN integer,
    PRDATINI date,
    PRDATFIN date,
    PRMODELO integer,
    PRTIPO integer,
    PRCODPLAPADRAO integer,
    PRREFEMP integer,
    PRMOSTRADEPRECIADOS integer,
    PRCONTABILIZACAO integer,
    PRDETALHARTAXADEP integer = 0,
    PRCODTPCC varchar(8192) = '',
    prRelBaiPar INTEGER = 0)
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDCODEMPFILIAL integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODBEM integer,
    BDNOMBEM varchar(200),
    BDCODTPLA integer,
    BDCTALON varchar(40),
    BDNOMTPLA varchar(100),
    BDCODFOR integer,
    BDNOMFOR varchar(100),
    BDCODCC integer,
    BDCTALONCC varchar(20),
    BDNOMCC varchar(40),
    BDVALORCORRIGIDOANTERIOR numeric(15,2),
    BDCORRECAOPERIODO numeric(15,2),
    BDVALORCORRIGIDOATUAL numeric(15,2),
    BDDEPRECIACAOACUMULADAANTERIOR numeric(15,2),
    BDDEPRECIACAOPERIODO numeric(15,2),
    BDDEPRECIACAOPERIODOMOEDA numeric(15,6),
    BDDEPRECIACAOACUMULADAATUAL numeric(15,2),
    BDDEPRECIACAOACUMULADAATUALMOE numeric(15,6),
    BDCORRECAOMONETARIADEPRECIACAO numeric(15,2),
    BDVALORRESIDUALCONTABIL numeric(15,2),
    BDVALORRESIDUALCONTABILMOEDA numeric(15,6),
    BDTOTALMESESDEPRECIACAO integer,
    BDMESESDEPRECIADOS integer,
    BDMESESDEPRECIAR integer,
    BDTAXADEPRECIACAOANUAL numeric(6,6),
    BDDATATAXADEPRECIACAO date,
    BDREFERENCIA varchar(7),
    BDNATBEM varchar(20),
    BDESPECIE varchar(20),
    BDDATAAQUISICAO date,
    BDVALORMOEDA numeric(15,6),
    BDVALORAQUISICAOMOEDA numeric(15,6),
    BDVALORCORRIGIDOANTERIORMOEDA numeric(15,6),
    BDVALORAQUISICAOORIGINAL numeric(15,2),
    BDVALORBAIXA numeric(15,2),
    BDSOMARDEPRECIACAO integer,
    BDCODORIGBEM integer,
    BDTIPOBEM integer,
    BDCLACOD varchar(21),
    BDULTIMOAGREGADO integer,
    BDVALORRESIDUAL numeric(15,6),
    BDCODBAI integer,
    BDBAIXAADICIONAL integer,
    BDDATAINICALC date,
    BDVALVENBAI numeric(15,6),
    BDCODMOT integer,
    BDDESCMOT varchar(50),
    BDSALDOQTD integer,
    BDQTDBAIXA integer,
    BDOBSBAIXA varchar(200),
    BDQUANTIDADEBEM integer,
    BDNRCHAPA varchar(20),
    BDVALAQUIBEMORIGINAL numeric(15,2),
    BDCGCTER varchar(18))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_CRITICA_LANC(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRCHAVEINI INTEGER,
PRCHAVEFIM INTEGER,
PRLOTEINI VARCHAR(10),
PRLOTEFIM VARCHAR(10),
PRTRANSINI INTEGER,
PRTRANSFIM INTEGER,
PRCOLUNAS INTEGER,
PRLCC VARCHAR(8192),
PRTOTDIA INTEGER,
PRTOTMES INTEGER,
PRTOTANO INTEGER,
PRTOTLOTE INTEGER,
PRDATAS VARCHAR(1024),
PRLANCSEMTRANS INTEGER,
PRREFEMP INTEGER,
PRCODTIPOLANC INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRSTATUSTRANSACAO INTEGER = 0)
 RETURNS(PRCHAVE INTEGER,
PRDATA DATE,
PRCODIGO_CREDITO INTEGER,
PRVALOR_CREDITO NUMERIC(15,2),
PRCODIGO_DEBITO INTEGER,
PRVALOR_DEBITO NUMERIC(15,2),
PRCOMPLEMENTO VARCHAR(200),
PRHISTORICO VARCHAR(200),
PREMPRESA INTEGER,
PRNOMEEMPRESA DM_BDNOMEMP,
PRCODTPCC INTEGER,
PRCNPJEMP VARCHAR(18),
PRLOTE VARCHAR(10),
PRDCTO VARCHAR(15),
PRCODMATRIZ INTEGER,
PRDEBCRE INTEGER,
PRVALOR NUMERIC(15,2),
PRVALORRAT NUMERIC(15,2),
PRQUEBRADIA DATE,
PRQUEBRAMES VARCHAR(7),
PRQUEBRARANO VARCHAR(4),
PRQUEBRALOTE VARCHAR(10),
PRSEQUENCIA INTEGER,
PRNOMECC VARCHAR(40),
PRCODEMPFILIAL INTEGER,
PRCONTAB INTEGER,
PRDESCTIPOLANC VARCHAR(100),
BDTRANSACAO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_DIARIO(PRCODEMP INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRMODELO INTEGER,
PRFILIAIS VARCHAR(1024),
PRLCC VARCHAR(8192),
PRDETALHARCTAPARTICIPANTE INTEGER,
PRREFEMP INTEGER,
PRAGRUPAR VARCHAR(1024),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARFILIAL INTEGER)
 RETURNS(PRCHAVE INTEGER,
PRDATA DATE,
PRCODIGO_CREDITO INTEGER,
PRCLASSI_CREDITO VARCHAR(40),
PRVALOR_CREDITO NUMERIC(15,2),
PRCODIGO_DEBITO INTEGER,
PRCLASSI_DEBITO VARCHAR(40),
PRVALOR_DEBITO NUMERIC(15,2),
PRCOMPLEMENTO VARCHAR(200),
PRHISTORICO VARCHAR(400),
PREMPRESA INTEGER,
PRNOMEEMPRESA DM_BDNOMEMP,
PRCODTPCC INTEGER,
PRCNPJEMP VARCHAR(18),
PRLOTE VARCHAR(10),
PRDCTO VARCHAR(15),
PRCODMATRIZ INTEGER,
PRDETALHE VARCHAR(250),
PREMPRESAFILIAL INTEGER,
PRCHAVEONLINE VARCHAR(120),
PRTRANSACAO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_MOV_DIARIO(PRCODEMP VARCHAR(1024),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRREFEMP INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRPARTICIPANTE INTEGER)
 RETURNS(DATA DATE,
DEB NUMERIC(15,2),
CRE NUMERIC(15,2),
SAL NUMERIC(15,2),
DEBANT NUMERIC(15,2),
CREANT NUMERIC(15,2),
SALANT NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_MOV_MENSAL(
    PRCODEMP INTEGER,
    PRCONTA INTEGER,
    PRCC VARCHAR(8192),
    PRANOINICIAL INTEGER,
    PRANOFINAL INTEGER,
    PRREFEMP INTEGER,
    PRPARTICIPANTE INTEGER,
    PRIGNORAZERAMENTO INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER) 
RETURNS (
    BDDEB01 NUMERIC(15,2),
    BDDEB02 NUMERIC(15,2),
    BDDEB03 NUMERIC(15,2),
    BDDEB04 NUMERIC(15,2),
    BDDEB05 NUMERIC(15,2),
    BDDEB06 NUMERIC(15,2),
    BDDEB07 NUMERIC(15,2),
    BDDEB08 NUMERIC(15,2),
    BDDEB09 NUMERIC(15,2),
    BDDEB10 NUMERIC(15,2),
    BDDEB11 NUMERIC(15,2),
    BDDEB12 NUMERIC(15,2),
    BDCRE01 NUMERIC(15,2),
    BDCRE02 NUMERIC(15,2),
    BDCRE03 NUMERIC(15,2),
    BDCRE04 NUMERIC(15,2),
    BDCRE05 NUMERIC(15,2),
    BDCRE06 NUMERIC(15,2),
    BDCRE07 NUMERIC(15,2),
    BDCRE08 NUMERIC(15,2),
    BDCRE09 NUMERIC(15,2),
    BDCRE10 NUMERIC(15,2),
    BDCRE11 NUMERIC(15,2),
    BDCRE12 NUMERIC(15,2),
    BDMOV01 NUMERIC(15,2),
    BDMOV02 NUMERIC(15,2),
    BDMOV03 NUMERIC(15,2),
    BDMOV04 NUMERIC(15,2),
    BDMOV05 NUMERIC(15,2),
    BDMOV06 NUMERIC(15,2),
    BDMOV07 NUMERIC(15,2),
    BDMOV08 NUMERIC(15,2),
    BDMOV09 NUMERIC(15,2),
    BDMOV10 NUMERIC(15,2),
    BDMOV11 NUMERIC(15,2),
    BDMOV12 NUMERIC(15,2),
    BDSAL01 NUMERIC(15,2),
    BDSAL02 NUMERIC(15,2),
    BDSAL03 NUMERIC(15,2),
    BDSAL04 NUMERIC(15,2),
    BDSAL05 NUMERIC(15,2),
    BDSAL06 NUMERIC(15,2),
    BDSAL07 NUMERIC(15,2),
    BDSAL08 NUMERIC(15,2),
    BDSAL09 NUMERIC(15,2),
    BDSAL10 NUMERIC(15,2),
    BDSAL11 NUMERIC(15,2),
    BDSAL12 NUMERIC(15,2),
    BDSALTOTDEB NUMERIC(15,2),
    BDSALTOTCRE NUMERIC(15,2),
    BDSALTOTMOV NUMERIC(15,2),
    BDSALTOTATU NUMERIC(15,2),
    BDANO INTEGER,
    BDDEBANT NUMERIC(15,2),
    BDCREANT NUMERIC(15,2),
    BDMOVANT NUMERIC(15,2),
    BDSALANT NUMERIC(15,2),
    BDGRPCTA INTEGER) 
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_PLANOS_TPLA(PRCODPLANOPADRAO INTEGER,
PRCAMPOPESQUISA VARCHAR(20),
PRCONTEUDO VARCHAR(20),
PRPESQUISAINICIO INTEGER)
 RETURNS(BDCODTPLA INTEGER,
BDCTALON VARCHAR(40),
BDTIPCTA INTEGER,
BDNOMCTA VARCHAR(100),
BDAPECTA VARCHAR(20),
BDRELCTA INTEGER,
BDFILTROGER VARCHAR(20),
BDFORMULA VARCHAR(200),
BDCONDICAO VARCHAR(200))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_CONTAS(PRCODEMP VARCHAR(1024),
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRLCC VARCHAR(8192),
PRORDEMPRESA INTEGER,
PRREFEMP INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARFILIAL INTEGER)
 RETURNS(PRHISTORICO VARCHAR(100),
PRDATA DATE,
PRCHAVE INTEGER,
PRCONTA INTEGER,
PRCONTRA INTEGER,
PRCREDITO NUMERIC(15,2),
PRDEBITO NUMERIC(15,2),
PRCONCILIADO VARCHAR(5),
PREMPRESA INTEGER,
PRNOMEEMPRESA DM_BDNOMEMP,
PRCC INTEGER,
PRNOME_CONTA VARCHAR(100),
PRCLASS_CONTA VARCHAR(40),
PRCLASS_CONTRA VARCHAR(40),
PRNOME_CONTA_CONTRA VARCHAR(100),
PRLOTE VARCHAR(10),
PRDCTO VARCHAR(15),
PRCOMPL VARCHAR(200),
PRCNPJEMP VARCHAR(18),
PRCODMATRIZ INTEGER,
PRGRPCTA INTEGER,
PRCODHIST INTEGER,
PRCODPLAPADRAO INTEGER,
PRCODTPHI INTEGER,
PRPARTICIPANTECONTA INTEGER,
PRPARTICIPANTECONTRA INTEGER,
PRCODTERCEIROCONTA INTEGER,
PRCODTERCEIROCONTRA INTEGER,
PRCODEMPFILIAL INTEGER,
PRTIPOLAN INTEGER,
PRCHAVEONLINE VARCHAR(120))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_CONTAS_X (
    PRCODEMP VARCHAR(1024),
    PRREFEMP INTEGER,
    PRCLASSIFICACAO_INICIAL VARCHAR(40),
    PRCLASSIFICACAO_FINAL VARCHAR(40),
    PRDATA_INICIAL DATE,
    PRDATA_FINAL DATE,
    PRINDICE INTEGER,
    PRDETALHARCC INTEGER,
    PRLCC DM_MAXVARCHAR,
    PRLANCAMENTOSEMCC INTEGER,
    PRDETALHARCTAPARTICIPANTE INTEGER,
    PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
    PRCONCATENACODPARTICIPANTE INTEGER,
    PRPARTINI INTEGER,
    PRPARTFIN INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRCONTASSEMMOVIMENTO INTEGER,
    PRIGNORAZERAMENTO INTEGER = 0,
    PRDETALHAREMPREENDIMENTO INTEGER = 0,
    PRDETALHARUNIDIMOB INTEGER = 0,
    PRPRMOSTRARPROPUNIDADE INTEGER = 0,
    PRPRODRURAL DM_BOOLEAN = 'FALSE',
    PRIMOVEIS VARCHAR(1024) = '',
    PRLISTAPART VARCHAR(10000) = '',
    PRAGRUPARPARTICIPANTEPORCPF INTEGER = 0,
    PRPLANO_SECUNDARIO INTEGER = 0,
    PRFILTRAREMPREENDIMENTO VARCHAR(1024) = '',
    PRFILTRARUNIDIMOBILIARIA VARCHAR(1024) = '',
    PRNAOMOSTRARLANCSEMDADOSRU DM_BOOLEAN = 'FALSE',
    PRFILTIPOLAN varchar(3200) = '')
RETURNS (
    PRHISTORICO VARCHAR(100),
    PRDATA DATE,
    PRCHAVE INTEGER,
    PRCONTA INTEGER,
    PRCONTRA INTEGER,
    PRCREDITO NUMERIC(18,2),
    PRDEBITO NUMERIC(18,2),
    PRCONCILIADO VARCHAR(5),
    PREMPRESA INTEGER,
    PRNOMEEMPRESA DM_BDNOMEMP,
    PRCC INTEGER,
    PRNOME_CONTA VARCHAR(300),
    PRNOME_CONTA_ORIGINAL VARCHAR(300),
    PRCLASS_CONTA VARCHAR(40),
    PRCLASS_CONTRA VARCHAR(40),
    PRNOME_CONTA_CONTRA VARCHAR(300),
    PRLOTE VARCHAR(10),
    PRDCTO VARCHAR(15),
    PRCOMPL VARCHAR(200),
    PRCNPJEMP VARCHAR(18),
    PRCODMATRIZ INTEGER,
    PRGRPCTA INTEGER,
    PRCODHIST INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRCODTPHI INTEGER,
    PRPARTICIPANTECONTA INTEGER,
    PRPARTICIPANTECONTRA INTEGER,
    PRCODTERCEIROCONTA INTEGER,
    PRCODTERCEIROCONTRA INTEGER,
    PRCGC_CONTA VARCHAR(18),
    PRCODEMPFILIAL INTEGER,
    PRTIPOLANCFILIAL INTEGER,
    PRTIPOLAN INTEGER,
    PRCHAVEONLINE VARCHAR(120),
    PRCODCENTRO INTEGER,
    PRTRANSACAO INTEGER,
    PRTRANFECHADA DM_BOOLEAN,
    PRCONCILIACAOPENDENTE INTEGER,
    PRCLANOM VARCHAR(355),
    PRDEBCRE INTEGER,
    PREMPREENDIMENTO INTEGER,
    PRUNIDIMOB INTEGER,
    PRNATUREZALAN INTEGER,
  PRCTALCDPR VARCHAR(6),
    PRPART_PR VARCHAR(18),
    PRCODPART_PR INTEGER,
    PRTIPLANPR VARCHAR(6),
    PRCODIMOVRUR INTEGER,
    PRTIPDOCPR INTEGER, 
    PRSALRELCONCILIACOES varchar(5))
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_SALDO(PRCODEMP VARCHAR(1024),
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRINDICE INTEGER,
PRLCC VARCHAR(8192),
PRORDEMPRESA INTEGER,
PRREFEMP INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
BDCONCILIADOS INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRAGRUPAR VARCHAR(1024),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARFILIAL INTEGER)
 RETURNS(BDHISTORICO VARCHAR(400),
BDDATA DATE,
BDCHAVE INTEGER,
BDCONTA INTEGER,
BDCONTRA INTEGER,
BDCREDITO NUMERIC(15,2),
BDDEBITO NUMERIC(15,2),
BDSALDO NUMERIC(15,2),
BDCONCILIADO VARCHAR(5),
BDEMPRESA INTEGER,
BDNOMEEMPRESA VARCHAR(100),
BDCODCENTRO INTEGER,
BDCC INTEGER,
BDNOME_CONTA VARCHAR(100),
BDCLASS_CONTA VARCHAR(40),
BDCOD_TERCEIRO_CONTA INTEGER,
BDCLASS_CONTRA VARCHAR(40),
BDNOME_CONTA_CONTRA VARCHAR(100),
BDCOD_TERCEIRO_CONTRA INTEGER,
BDVALOR NUMERIC(15,2),
BDORDSALDO INTEGER,
BDLOTE VARCHAR(10),
BDDCTO VARCHAR(15),
BDCOMPL VARCHAR(200),
BDCNPJEMP VARCHAR(18),
BDSALDOANTERIOR NUMERIC(15,2),
BDVALORSEMSINAL NUMERIC(15,2),
BDGRUPOCONTA INTEGER,
BDCODHIST INTEGER,
BDCODPLAPADRAO INTEGER,
BDREF VARCHAR(8),
BDCODTPHI INTEGER,
BDEMPRESAFILIAL INTEGER,
BDVLRCONCILIADO NUMERIC(15,2),
BDVLRACONCILIAR NUMERIC(15,2),
BDCHAVEONLINE VARCHAR(120))
 AS
 BEGIN SUSPEND; END
^
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CREDOR (
PRCODEMP         VARCHAR(1024),
PRDATINI         DATE,
PRDATFIN         DATE,
PRINDICE         INTEGER,
PRCONTABILIZACAO INTEGER,
PRCODPLAPADRAO   INTEGER,
PRCONTA          INTEGER,
PRREFEMP         INTEGER)
RETURNS (
BDCODEMP         INTEGER,
BDNOMEMP         DM_BDNOMEMP,
BDCONTA          INTEGER,
BDDATA           DATE,
BDCTALON         DM_CLASSCONTAS,
BDNOMCTA         VARCHAR(100),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDSALDO_DEB      NUMERIC(15,2),
BDSALDO_CRE      NUMERIC(15,2),
BDMOVIMENTO      NUMERIC(15,2),
BDSALDO_ATUAL    NUMERIC(15,2),
BDGRUPOCTA       INTEGER)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_SALDO_X(
    PRCODEMP VARCHAR(1024),
    PRCLASSIFICACAO_INICIAL VARCHAR(40),
    PRCLASSIFICACAO_FINAL VARCHAR(40),
    PRDATA_INICIAL DATE,
    PRDATA_FINAL DATE,
    PRINDICE INTEGER,
    PRDETALHARCC INTEGER,
    PRLCC DM_MAXVARCHAR,
    PRLANCAMENTOSEMCC INTEGER,
    PRORDEMPRESA INTEGER,
    PRREFEMP INTEGER,
    PRDETALHARCTAPARTICIPANTE INTEGER,
    PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
    PRCONCATENACODPARTICIPANTE INTEGER,
    BDCONCILIADOS VARCHAR(20),
    PRPARTINI INTEGER,
    PRPARTFIN INTEGER,
    PRAGRUPAR VARCHAR(1024),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRDCDOISLANCAMENTOS INTEGER,
    PRCONTASSEMMOVIMENTO INTEGER,
    PRIGNORAZERAMENTO INTEGER = 0,
    PRIGNORASALDOANTERIOR INTEGER = 0,
    PRDETALHARFILIAL INTEGER = 0,
    PRORDENACAO INTEGER = 0,
    PRDETALHAREMPREENDIMENTO INTEGER = 0,
    PRDETALHARUNIDIMOB INTEGER = 0,
    PRMOSTRARPROPUNIDADE INTEGER = 0,
    PRSOLANSEMEMPREE INTEGER = 0,
    PRORDENANATUREZA INTEGER = 0,
    PRPRODRURAL DM_BOOLEAN = 'FALSE',
    PRIMOVEIS VARCHAR(1024) = '',
    PRLISTAPART VARCHAR(10000) = '',
    PRAGRUPARPARTICIPANTEPORCPF INTEGER = 0,
    PRMOSTRARCC INTEGER = 0,
    PRPLANO_SECUNDARIO INTEGER = 0,
    PREMPREENDIMENTO VARCHAR(1024) = '',
    PRUNIDIMOBILIARIA VARCHAR(1024) = '',
    PRNAOMOSTRARLANCSEMDADOSRU DM_BOOLEAN = 'FALSE',
    PRFILTIPOLAN varchar(3200) = '')
RETURNS (
    BDHISTORICO VARCHAR(100),
    BDDATA DATE,
    BDCHAVE INTEGER,
    BDCONTA INTEGER,
    BDCONTRA INTEGER,
    BDCREDITO NUMERIC(15,2),
    BDDEBITO NUMERIC(15,2),
    BDSALDO NUMERIC(15,2),
    BDCONCILIADO VARCHAR(5),
    BDEMPRESA INTEGER,
    BDNOMEEMPRESA VARCHAR(100),
    BDCODCENTRO INTEGER,
    BDCC INTEGER,
    BDNOME_CONTA VARCHAR(300),
    BDNOME_CONTA_ORIGINAL VARCHAR(300),
    BDCLASS_CONTA VARCHAR(40),
    BDCOD_TERCEIRO_CONTA INTEGER,
    BDCGC_CONTA VARCHAR(18),
    BDCLASS_CONTRA VARCHAR(40),
    BDNOME_CONTA_CONTRA VARCHAR(300),
    BDCOD_TERCEIRO_CONTRA INTEGER,
    BDVALOR NUMERIC(15,2),
    BDORDSALDO INTEGER,
    BDLOTE VARCHAR(10),
    BDDCTO VARCHAR(15),
    BDCOMPL VARCHAR(200),
    BDCNPJEMP VARCHAR(18),
    BDSALDOANTERIOR NUMERIC(15,2),
    BDVALORSEMSINAL NUMERIC(15,2),
    BDGRUPOCONTA INTEGER,
    BDCODHIST INTEGER,
    BDCODPLAPADRAO INTEGER,
    BDREF VARCHAR(8),
    BDCODTPHI INTEGER,
    BDEMPRESAFILIAL INTEGER,
    BDTIPOLANCFILIAL INTEGER,
    BDVLRCONCILIADO NUMERIC(15,2),
    BDVLRACONCILIAR NUMERIC(15,2),
    BDCHAVEONLINE VARCHAR(120),
    BDTRANSACAO INTEGER,
    BDTRANFECHADA DM_BOOLEAN,
    BDTIPOLAN INTEGER,
    BDSEQCTA VARCHAR(7),
    BDCLANOM VARCHAR(355),
    BDCONCILIACAOPENDENTE INTEGER,
    BDCC_CONTRA INTEGER,
    BDEMPREENDIMENTO INTEGER,
    BDUNIDIMOB INTEGER,
    BDNATUREZALAN INTEGER,
    BDCTALCDPR VARCHAR(6),
    BDPART_PR VARCHAR(18),
    BDCODPART_PR INTEGER,
    BDTIPLANPR VARCHAR(6),
    BDCODIMOVRUR INTEGER,
    BDTIPDOCPR INTEGER,
    BDSALRELCONCILIACOES DM_BOOLEAN)
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_SALDO2(PRCODEMP VARCHAR(1024),
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRINDICE INTEGER,
PRLCC VARCHAR(8192),
PRORDEMPRESA INTEGER,
PRREFEMP INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
BDCONCILIADOS INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARFILIAL INTEGER)
 RETURNS(BDHISTORICO VARCHAR(400),
BDDATA DATE,
BDCHAVE INTEGER,
BDCONTA INTEGER,
BDCONTRA INTEGER,
BDCREDITO NUMERIC(15,2),
BDDEBITO NUMERIC(15,2),
BDSALDO NUMERIC(15,2),
BDCONCILIADO VARCHAR(5),
BDEMPRESA INTEGER,
BDNOMEEMPRESA VARCHAR(80),
BDCC INTEGER,
BDNOME_CONTA VARCHAR(100),
BDCLASS_CONTA VARCHAR(30),
BDCOD_TERCEIRO_CONTA INTEGER,
BDCLASS_CONTRA VARCHAR(20),
BDNOME_CONTA_CONTRA VARCHAR(100),
BDCOD_TERCEIRO_CONTRA INTEGER,
BDVALOR NUMERIC(15,2),
BDORDSALDO INTEGER,
BDLOTE VARCHAR(10),
BDDCTO VARCHAR(15),
BDCOMPL VARCHAR(200),
BDCNPJEMP VARCHAR(18),
BDSALDOANTERIOR NUMERIC(15,2),
BDVALORSEMSINAL NUMERIC(15,2),
BDGRUPOCONTA INTEGER,
BDCODHIST INTEGER,
BDCODPLAPADRAO INTEGER,
BDREF VARCHAR(8),
BDCODTPHI INTEGER,
BDEMPRESAFILIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_REL_ORCA (
    PRCODEMP VARCHAR(2048),
    PRDATINI DATE,
    PRDATFIN DATE,
    PRIGNORA_ZERAMENTO INTEGER,
    PRCTAINI INTEGER,
    PRCTAFIN INTEGER,
    PRINDICE INTEGER,
    PRCODTPCC VARCHAR(8192),
    PRREFEMP INTEGER,
    PRLANSEMCC INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP VARCHAR(18),
    BDCODMATRIZ INTEGER,
    BDCODPLAPADRAO INTEGER,
    BDCODCTA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDTIPCTA SMALLINT,
    BDCODTPCC INTEGER,
    BDNOMTPCC VARCHAR(40),
    BDSALDOREALIZADO NUMERIC(15,2),
    BDGRPCTA SMALLINT,
    BDTPCCLON VARCHAR(20),
    BDFORMULA VARCHAR(200),
    BDRELCTA INTEGER,
    BDNEGFOR VARCHAR(5),
    BDSUBLFOR VARCHAR(5),
    BDLINSEMVALFOR VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_RELESTATIST_GRA(PRCODEMP VARCHAR(10000),
PRCODUSU INTEGER,
PRTIPCOMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDTIPO VARCHAR(20),
BDMES VARCHAR(8),
BDMESVALOR INTEGER,
BDCOLOR VARCHAR(10))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_RELESTATISTGRA(PRCODEMP VARCHAR(2048),
PRTIPCOMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDTIPO VARCHAR(20),
BDMES01 INTEGER,
BDMES02 INTEGER,
BDMES03 INTEGER,
BDMES04 INTEGER,
BDMES05 INTEGER,
BDMES06 INTEGER,
BDMES07 INTEGER,
BDMES08 INTEGER,
BDMES09 INTEGER,
BDMES10 INTEGER,
BDMES11 INTEGER,
BDMES12 INTEGER,
BDTOTAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_RELESTATISTICA(PRCODEMP VARCHAR(10000),
PRCODUSU INTEGER,
PRTIPCOMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDTIPO VARCHAR(20),
BDMES01 INTEGER,
BDMES02 INTEGER,
BDMES03 INTEGER,
BDMES04 INTEGER,
BDMES05 INTEGER,
BDMES06 INTEGER,
BDMES07 INTEGER,
BDMES08 INTEGER,
BDMES09 INTEGER,
BDMES10 INTEGER,
BDMES11 INTEGER,
BDMES12 INTEGER,
BDTOTAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VSUC_SP_RETORNA_SALDO (
    PRCODEMP varchar(1024),
    PRCONTA integer,
    PRDATAINI date,
    PRDATAFIM date,
    PRIGNORAZERAMENTO smallint,
    PRCC integer,
    PRRELCTA integer,
    PRREFEMP integer,
    PRFORM varchar(10),
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer)
returns (
    MOVIMENTO_ANT_CRE numeric(15,2),
    SALDO_ANT_DEB numeric(15,2),
    SALDO_ANT_CRE numeric(15,2),
    SALDO_DEB numeric(15,2),
    SALDO_CRE numeric(15,2),
    SALDO_ATUAL numeric(15,2),
    SALDO_ANTERIOR numeric(15,2),
    MOVIMENTO_ANT_DEB numeric(15,2),
    SALDO_MOVIMENTO numeric(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONS_ORCA(PRCODEMP INTEGER,
PRCONTA INTEGER,
PRCODTPCC INTEGER,
PRANO INTEGER,
PRREFEMP INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDSAL01 NUMERIC(15,2),
BDSAL02 NUMERIC(15,2),
BDSAL03 NUMERIC(15,2),
BDSAL04 NUMERIC(15,2),
BDSAL05 NUMERIC(15,2),
BDSAL06 NUMERIC(15,2),
BDSAL07 NUMERIC(15,2),
BDSAL08 NUMERIC(15,2),
BDSAL09 NUMERIC(15,2),
BDSAL10 NUMERIC(15,2),
BDSAL11 NUMERIC(15,2),
BDSAL12 NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS(PRCODIGOEMP INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO INTEGER,
PRCC INTEGER,
PRCODPLAPADRAO INTEGER,
PRLANCSEMCC INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDATAHORA VARCHAR(30),
PRNIVEISCONTA VARCHAR(50),
PRTODASASCONTAS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(CODEMP INTEGER,
CODPLAPADRAO INTEGER,
CONTA INTEGER,
CLASSIFICACAO VARCHAR(40),
NOMECONTA VARCHAR(100),
GRUPOCONTA SMALLINT,
RELCONTA INTEGER,
CLANOM VARCHAR(140),
TIPCONTA SMALLINT,
SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
FORMULA VARCHAR(200),
PARTICIPANTE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS_CC(PRCODEMP INTEGER,
PRCODCTAINI INTEGER,
PRCODCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCODTPCC INTEGER,
PRCODPLAPADRAO INTEGER,
PRNAOMOSTRACONTACOMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDGRPCTA SMALLINT,
BDRELCTA INTEGER,
BDTIPCTA SMALLINT,
BDSALANTDEB NUMERIC(15,2),
BDSALANTCRE NUMERIC(15,2),
BDSALDEB NUMERIC(15,2),
BDSALCRE NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDSALANT NUMERIC(15,2),
BDFORMULA VARCHAR(200))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS_X (
    PRCODIGOEMP INTEGER,
    PRCONTAINICIAL INTEGER,
    PRCONTAFINAL INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRINDICE INTEGER,
    PRIGNORAZERAMENTO INTEGER,
    PRCC INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRLANCSEMCC INTEGER,
    PRNAOMOSTRACONTACOMP INTEGER,
    PRCONSOLIDADA INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PREMPRESAS VARCHAR(2048),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRDRE INTEGER = 0,
    PRTODOPLANOCONTAS INTEGER = 0,
    PRSOMENTEMOVIMENTO INTEGER = 0,
    PRPLANOGRPECO integer = 0,
    PREMPRESAGRPECO integer = 0,
    PRGRPECO integer = 0,
    PRIGNZERPERANT integer = 0,
    PRTIPOLAN varchar(3200) = '',
    PRELIMINACOESK300K315 integer = 0)
returns (
    CODEMP integer,
    CODPLAPADRAO integer,
    CONTA integer,
    CLASSIFICACAO varchar(40),
    NOMECONTA varchar(100),
    GRUPOCONTA smallint,
    RELCONTA integer,
    CLANOM varchar(140),
    TIPCONTA smallint,
    SALDO_ANT_DEB numeric(15,2),
    SALDO_ANT_CRE numeric(15,2),
    SALDO_DEB numeric(15,2),
    SALDO_CRE numeric(15,2),
    SALDO_ATUAL numeric(15,2),
    SALDO_ANTERIOR numeric(15,2),
    FORMULA varchar(200),
    PARTICIPANTE integer,
    APECTA varchar(20),
    PERTENCECONTA integer,
    SALDO_ANT_DEB_DRE numeric(15,2),
    SALDO_ANT_CRE_DRE numeric(15,2),
    SALDO_ANTERIOR_DRE numeric(15,2),
    SALDO_SEM_CONCILIACAO numeric(15,2),
    SALDO_ATUAL_REAL numeric(15,2),
    DATAULTLANCAMENTO date)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS_XZ (
    PRCODIGOEMP INTEGER,
    PRCONTAINICIAL INTEGER,
    PRCONTAFINAL INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRINDICE INTEGER,
    PRIGNORAZERAMENTO INTEGER,
    PRCC VARCHAR(32000),
    PRCODPLAPADRAO INTEGER,
    PRLANCSEMCC INTEGER,
    PRORDEM INTEGER,
    PRNAOMOSTRACONTACOMP INTEGER,
    PRCONSOLIDADA INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRDRE INTEGER = 0,
    PRNIVELCC INTEGER = 0,
    PRSOMENTEMOVIMENTO INTEGER = 0,
    PRDETALHARCCEMPREEND integer = 0,
    PRCODEMPREENDIMENTO varchar(32000) = '' /* COLLATE WIN1252 - default */ ,
    PRTIPOLAN varchar(3200) = '',
    PRELIMINACOESK300K315 integer = 0)
returns (
    BDCODEMP integer,
    BDCODPLAPADRAO integer,
    BDCONTA integer,
    BDCLASSIFICACAO varchar(40),
    BDNOMECONTA varchar(100),
    BDGRUPOCONTA smallint,
    BDRELCONTA integer,
    BDCLANOM varchar(140),
    BDTIPCONTA smallint,
    BDSALDO_ANT_DEB numeric(15,2),
    BDSALDO_ANT_CRE numeric(15,2),
    BDSALDO_DEB numeric(15,2),
    BDSALDO_CRE numeric(15,2),
    BDSALDO_ATUAL numeric(15,2),
    BDSALDO_ANTERIOR numeric(15,2),
    BDFORMULA varchar(200),
    BDPARTICIPANTE integer,
    BDAPECTA varchar(20),
    BDPERTENCECONTA integer,
    BDSALDO_ANT_DEB_DRE numeric(15,2),
    BDSALDO_ANT_CRE_DRE numeric(15,2),
    BDSALDO_ANTERIOR_DRE numeric(15,2),
    BDCODTPCC integer,
    BDNOMTPCC varchar(40),
    BDTPCCLON varchar(20),
    BDSALDO_ATUAL_REAL numeric(15,2),
    BDFILTROCC varchar(200),
    BDDATAULTLANC date)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_LANC(PRCODEMP INTEGER,
PRREFEMP INTEGER,
PRCONTA_DEB INTEGER,
PRCONTA_CRED INTEGER,
PRDATA DATE,
PRPARTICIPANTED INTEGER,
PRPARTICIPANTEC INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFIIALCONSOLIDADO INTEGER)
 RETURNS(ANT_AO_DIA_D NUMERIC(15,2),
DEB_DO_DIA_D NUMERIC(15,2),
CRED_DO_DIA_D NUMERIC(15,2),
ATUAL_DO_DIA_D NUMERIC(15,2),
ANT_AO_DIA_C NUMERIC(15,2),
DEB_DO_DIA_C NUMERIC(15,2),
CRED_DO_DIA_C NUMERIC(15,2),
ATUAL_DO_DIA_C NUMERIC(15,2),
ANT_AO_MES_C NUMERIC(15,2),
ATUAL_DO_MES_C NUMERIC(15,2),
ANT_AO_MES_D NUMERIC(15,2),
DEB_DO_MES_D NUMERIC(15,2),
CRED_DO_MES_D NUMERIC(15,2),
MOV_DO_MES_D NUMERIC(15,2),
ATUAL_DO_MES_D NUMERIC(15,2),
ANT_DO_MES_C NUMERIC(15,2),
DEB_DO_MES_C NUMERIC(15,2),
CRED_DO_MES_C NUMERIC(15,2),
MOV_DO_MES_C NUMERIC(15,2),
ATUTAL_DO_MES_C NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_ORCA (
    PRCODIGOEMP INTEGER,
    PRCONTAINICIAL INTEGER,
    PRCONTAFINAL INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRINDICE INTEGER,
    PRIGNORAZERAMENTO INTEGER,
    PRCC INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PRTODASASCONTAS INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRLANCSEMCC INTEGER = 0)
RETURNS (
    CODEMP INTEGER,
    CODPLAPADRAO INTEGER,
    CONTA INTEGER,
    CLASSIFICACAO VARCHAR(40),
    NOMECONTA VARCHAR(100),
    GRUPOCONTA SMALLINT,
    RELCONTA INTEGER,
    TIPCONTA SMALLINT,
    BDORCADO INTEGER,
    BDREALIZADO NUMERIC(15,2),
    FORMULA VARCHAR(200))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDOS_CTA_PART(PRCODEMP INTEGER,
PRCODPLAPADRAO INTEGER,
PRDTINICIAL DATE,
PRDTFINAL DATE,
PRCONTA INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRCODTERCEIRO INTEGER,
PRRETORNAAPENASCONTAS INTEGER,
PRCONCILIADOS INTEGER,
PREMPRESAS VARCHAR(2048),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDNOME VARCHAR(100),
BDCLASSIFICACAO VARCHAR(40),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_ANT_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALDO_ANT_CRE NUMERIC(15,2),
BDSALDO_ATUAL NUMERIC(15,2),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDCODPARTICIPANTE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_GET_CLASSIFICACAO_NIVEL (
    PRCLASSIFICACAO VARCHAR(100),
    PRNIVEL INTEGER)
RETURNS (
    BDCLASSIFICACAO VARCHAR(100))
AS
BEGIN
  SUSPEND;
END
^

create or alter procedure VSUC_SP_RETORNA_SALDOS_CTAPARTY (
    PRCODEMP integer,
    PRCODPLAPADRAO integer,
    PRDTINICIAL date,
    PRDTFINAL date,
    PRCONTA integer,
    PRINDICE integer,
    PRIGNORAZERAMENTO integer,
    PRCODTERCEIRO integer,
    PRCONCILIADOS varchar(20),
    PREMPRESAS varchar(2048),
    PRCONTABILIZACAO integer,
    PRAGRUPARPARTICIPANTEPORCNPJ integer = 0,
    PRCC DM_MAXVARCHAR = '',
    PRLANCSEMCC integer = 0,
    PRAGRUPARPARTICIPANTEPORCPF integer = 0,
    PRNIVELCC integer = 0,
    PRSOMENTEMOVIMENTO integer = 0,
    PRREFEMP integer = 0,
    PRTODOSPART varchar(2048) = '',
    PRTIPOLAN varchar(3200) = '' /* COLLATE WIN1252 - default */ ,
    PREMPRESAGRPECO integer = 0,
    PRGRPECO integer = 0,
    PRELIMINACOESK300K315 integer = 0)
returns (
    BDNOME varchar(100),
    BDCLASSIFICACAO varchar(40),
    BDSALDO_DEB numeric(15,2),
    BDSALDO_ANT_DEB numeric(15,2),
    BDSALDO_CRE numeric(15,2),
    BDSALDO_ANT_CRE numeric(15,2),
    BDMOVIMENTO numeric(15,2),
    BDSALDO_ATUAL numeric(15,2),
    BDSALDO_ANTERIOR numeric(15,2),
    BDCODPARTICIPANTE integer,
    BDRAIZCNPJPARTICIPANTE varchar(10),
    BDRAIZCLASSIFICACAOCTA varchar(40),
    BDCENTROCUSTO integer,
    BDNOMTPCC varchar(40),
    BDTPCCLON varchar(20),
    BDVALOR_NAO_CONCILIADO numeric(15,2),
    BDCGCTER varchar(18),
    BDDATAULTLANCAMENTO date)
as
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_TOTAIS_LANC(PRCODEMP VARCHAR(2048),
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRSTATUSTRANSACAO INTEGER = 0,
PRLANCSEMTRANS INTEGER = 1,
PRDATAS VARCHAR(1024) = '')
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDQTDLINHA INTEGER,
BDVALLINHA NUMERIC(15,2),
BDQTDDEB INTEGER,
BDVALDEB NUMERIC(15,2),
BDQTDCRE INTEGER,
BDVALCRE NUMERIC(15,2),
BDQTDGERAL INTEGER,
BDVALGERAL NUMERIC(15,2),
BDDIF NUMERIC(15,2),
BDCODEMPFILIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_TENC_EXERCICIO(PRCODEMP INTEGER,
PRCONTA VARCHAR(1024),
PRCTACONTRAPARTIDA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRDATALANC DATE,
PRLOTE VARCHAR(10),
PRCOMPLEMENTO VARCHAR(100),
PRCODTPHI INTEGER,
PRUSUARIO INTEGER,
PRCHAVEZERA INTEGER,
PRCODPLAPADRAO INTEGER,
PRCODHIST INTEGER,
PRREFEMP INTEGER,
PRLANCCONTRAPART INTEGER)
 RETURNS(PRCHAVEZERAMENTO INTEGER,
PRZEROUCONTAS INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_UPDATE_TLAN_CONC_BANC(PREMPRESA INTEGER,
PRDEBCRE INTEGER,
PRCONTA INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRCOMPL VARCHAR(200),
PRVALOR FLOAT,
PRCODPLAPADRAO INTEGER,
PRDCTO VARCHAR(15),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODPLAPADRAO INTEGER,
BDCHAVE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_UPDATE_TLAN_CONC_CLIFOR(PREMPRESA INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINICIAL VARCHAR(10),
PRDATAFINAL VARCHAR(10),
PRCLIFOR SMALLINT,
PRCODPLAPADRAO INTEGER)
 RETURNS(CONCILIACAOOK SMALLINT)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORIDADE (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRDATAATUAL DATE,
    PRAGRUPADOR SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMECC DM_BDNOMEMP,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDIDADE01 INTEGER,
    BDIDADE02 INTEGER,
    BDIDADE03 INTEGER,
    BDIDADE04 INTEGER,
    BDIDADE05 INTEGER,
    BDIDADE06 INTEGER,
    BDIDADE07 INTEGER,
    BDIDADE08 INTEGER,
    BDIDADE09 INTEGER,
    BDIDADE10 INTEGER,
    BDIDADE11 INTEGER,
    BDTOTAL INTEGER)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORTEMPO (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRDATAATUAL DATE,
    PRAGRUPADOR SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMECC DM_BDNOMEMP,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDTEMPO01 INTEGER,
    BDTEMPO02 INTEGER,
    BDTEMPO03 INTEGER,
    BDTEMPO04 INTEGER,
    BDTEMPO05 INTEGER,
    BDTEMPO06 INTEGER,
    BDTEMPO07 INTEGER,
    BDTEMPO08 INTEGER,
    BDTEMPO09 INTEGER,
    BDTEMPO10 INTEGER,
    BDTEMPO11 INTEGER,
    BDTOTAL INTEGER)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORFUNCAO (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRDATAATUAL DATE,
    PRAGRUPADOR SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMECC DM_BDNOMEMP,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDTEMPO01 INTEGER,
    BDTEMPO02 INTEGER,
    BDTEMPO03 INTEGER,
    BDTEMPO04 INTEGER,
    BDTEMPO05 INTEGER,
    BDTEMPO06 INTEGER,
    BDTEMPO07 INTEGER,
    BDTEMPO08 INTEGER,
    BDTEMPO09 INTEGER,
    BDTEMPO10 INTEGER,
    BDTEMPO11 INTEGER,
    BDTOTAL INTEGER)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORINST (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRDATAATUAL DATE,
    PRGRAUINST SMALLINT = 0,
    PRAGRUPADOR SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMECC DM_BDNOMEMP,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDINST01 INTEGER,
    BDINST02 INTEGER,
    BDINST03 INTEGER,
    BDINST04 INTEGER,
    BDINST05 INTEGER,
    BDINST06 INTEGER,
    BDINST07 INTEGER,
    BDINST08 INTEGER,
    BDINST09 INTEGER,
    BDINST10 INTEGER,
    BDINST11 INTEGER,
    BDINST12 INTEGER,
    BDINST13 INTEGER,
    BDTOTAL INTEGER)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORRESC (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRAGRUPADOR SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMECC DM_BDNOMEMP,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDREFRESCISAO INTEGER,
    BDINIEMP INTEGER,
    BDINICOL INTEGER,
    BDTOTALSAIDAS INTEGER)
AS
BEGIN SUSPEND; END
^

--alt:12049 - 14/10/2015 - Criada nova procedure para o Relatório de Análises. Pedro
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_BALANCO_PATRI_X (
    PRCODEMP VARCHAR(1024),
    PRDATINI DATE,
    PRDATFIN DATE,
    PRIGNZER INTEGER,
    PRCTALONINI VARCHAR(40),
    PRCTALONFIN VARCHAR(40),
    PRINDICE INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRNAOMOSTRACONTACOMP INTEGER,
    PRCTASEMMOV INTEGER,
    PRREFEMP INTEGER,
    PRCONSOLIDADA INTEGER,
    PRDETALHARCTAPARTICIPANTE INTEGER,
    PRCONCATENACODPARTICIPANTE INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRCONTATITULO INTEGER = NULL,
    PRSALDOCOMPARACAO INTEGER = 1)
RETURNS (
    BDCODEMP INTEGER,
    BDCODMATRIZ INTEGER,
    BDCODEMPFILIAL INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP VARCHAR(20),
    BDCODPLAPADRAO INTEGER,
    BDCODCTA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDTIPCTA INTEGER,
    BDSEQCTA VARCHAR(40),
    BDSALANT NUMERIC(15,2),
    BDSALMOV NUMERIC(15,2),
    BDSALATU NUMERIC(15,2),
    BDANAVER NUMERIC(15,2),
    BDANAHOR NUMERIC(15,2),
    BDFORMULA VARCHAR(1024),
    BDGRPCTA INTEGER,
    BDAPECTA VARCHAR(20),
    BDCONTATITULO INTEGER,
    BDSALDOCOMPARACAO NUMERIC(15,2))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_BI_FAT (
    EMPRESA INTEGER,
    PLANO INTEGER,
    QUADRO INTEGER,
    DATA_INICIAL DATE,
    DATA_FINAL DATE,
    SOMAMATRIZFILIAL SMALLINT)
RETURNS (
    BDCODEMP INTEGER,
    BDREF INTEGER,
    BDORDEM INTEGER,
    BDDESCRICAO VARCHAR(152),
    BDVALOR NUMERIC(15,6))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE GETINTEGERLIST("AINTEGERLIST" VARCHAR(32000))
returns (
  ID integer
)
as
begin SUSPEND; end
^

CREATE OR ALTER PROCEDURE GETINTEGERLIST(AINTEGERLIST blob sub_type 0 segment size 80)
returns (
  ID integer
)
as
begin SUSPEND; end
^

CREATE OR ALTER PROCEDURE SP_BI_FAT_TODAS(
    PLANO INTEGER,
    QUADRO INTEGER,
    DATA_INICIAL DATE,
    DATA_FINAL DATE,
    SOMAMATRIZFILIAL SMALLINT)
RETURNS (
    BDCODEMP INTEGER,
    BDREF INTEGER,
    BDORDEM INTEGER,
    BDDESCRICAO VARCHAR(152),
    BDVALOR NUMERIC(15,6))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_BI_CONF_FOLHA_TODAS (
    CODIGO_RELATORIO INTEGER,
    DATA_INICIAL DATE,
    DATA_FINAL DATE,
    AGRUPAR_POR SMALLINT)
RETURNS (
    BDCODEMP INTEGER,
    BDREF INTEGER,
    BDCODCOL INTEGER,
    BDCODTER INTEGER,
    BDORDEM INTEGER,
    BDDESCRICAO VARCHAR(152),
    BDVALOR NUMERIC(15,6),
    BDCODTPCC INTEGER)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_BI_CONF_FOLHA (
    EMPRESA INTEGER,
    CODIGO_RELATORIO INTEGER,
    DATA_INICIAL DATE,
    DATA_FINAL DATE,
    AGRUPAR_POR SMALLINT)
RETURNS (
    BDCODEMP INTEGER,
    BDREF INTEGER,
    BDCODCOL INTEGER,
    BDCODTER INTEGER,
    BDORDEM INTEGER,
    BDDESCRICAO VARCHAR(152),
    BDVALOR NUMERIC(15,6),
    BDCODTPCC INTEGER)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_BI_DRE (
    EMPRESA INTEGER,
    PLANO INTEGER,
    DATA_INICIAL DATE,
    DATA_FINAL DATE,
    TIPO_CONTABILIZACAO SMALLINT,
    IGNORA_ZERAMENTO SMALLINT,
    DETALHAR_FILIAIS SMALLINT)
RETURNS (
    BDCODEMP INTEGER,
    BDCODEMPFILIAL INTEGER,
    BDCODCONTA INTEGER,
    BDCLASSIFICACAO VARCHAR(40),
    BDTIPO_CONTA INTEGER,
    BDVALOR NUMERIC(15,6))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_BI_RELATORIOS(
    NOME_RELATORIO VARCHAR(80),
    CODIGO_EMPRESA INTEGER,
    PARAMS_REL VARCHAR(5000),
    TIPO_SAIDA INTEGER
) RETURNS (
    RETORNO VARCHAR(32000)
)
AS
BEGIN SUSPEND; END^

--#178007 - Djonathan
CREATE OR ALTER PROCEDURE SP_GET_HISTORICOCOMPLETO (
    HISTORICO VARCHAR(3000),
    COMPLEMENTO VARCHAR(3000),
    COMPLEMENTOCOMPLETO VARCHAR(3000))
RETURNS (WRESULT VARCHAR(3000))
AS 
BEGIN
END^

--#172717 - Djonathan
CREATE OR ALTER PROCEDURE SP_GET_CLASSIFICACAO_SEM_ZEROS (
    PRCLASSIFICACAO VARCHAR(20))
RETURNS (
    BDRESULT VARCHAR(20))
AS
BEGIN
END^

CREATE OR ALTER procedure VSUC_SP_COPY_PREPARACAO_FOR_ECF (
    PRCODPLAPADRAOFORM integer,
    PRCODPLAPADRAO integer,
    PRDE_ANO integer,
    PRPARA_ANO integer,
    PROPCAO integer)
as
begin
END^

CREATE OR ALTER procedure VSUC_SP_COPY_PREPARACAO_FOR_ECF_PAIS (
    PRCODPLAPADRAOFORM integer,
    PRCODPLAPADRAO integer,
    PRCODPAIS integer,
    PRDE_ANO integer,
    PRPARA_ANO integer,
    PROPCAO integer)
as
begin
END^

CREATE OR ALTER TRIGGER vfin_base_tescparfat_bi0 FOR vfin_base_tescparfat ACTIVE BEFORE INSERT OR UPDATE POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_base_tcliente_bi0 FOR vfin_base_tcliente ACTIVE BEFORE INSERT POSITION 0 AS begin END ^
CREATE OR ALTER TRIGGER vfin_base_tcliente_ref_bi0 FOR vfin_base_tcliente_ref ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER VFIN_BASE_TCLIENTEHIST_BI0 FOR VFIN_BASE_TCLIENTEHIST ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER VFIN_ESC_TRPSEMITIDO_BD0 FOR VFIN_ESC_TRPSEMITIDO ACTIVE BEFORE DELETE POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_base_tclicontato_bi0 FOR vfin_base_tclicontato ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_base_tclienderecamento_bi0 FOR vfin_base_tclienderecamento ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_base_tclienqfed_bi0 FOR vfin_base_tclienqfed ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_base_tclifininfor_bi0 FOR vfin_base_tclifininfor ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_base_tcliimposto_bi0 FOR vfin_base_tcliimposto ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_esc_tcontasban_bi0 FOR vfin_esc_tcontasban ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_base_tmensagens_bi0 FOR vfin_base_tmensagens ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_esc_tcontrato_bi0 FOR vfin_esc_tcontrato ACTIVE BEFORE INSERT POSITION 0 AS begin END ^
CREATE OR ALTER TRIGGER vfin_esc_tservparamcontrato_bi0 FOR vfin_esc_tservparamcontrato ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER VFIN_ESC_TSERVPARAMVALOR_BI0 FOR VFIN_ESC_TSERVPARAMVALOR ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER VFIN_ESC_TCHEQUERECEBIDO_BI0 FOR VFIN_ESC_TCHEQUERECEBIDO ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_esc_tservicofixo_bi0 FOR vfin_esc_tservicofixo ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_esc_tservicofixo_aiu0 FOR vfin_esc_tservicofixo ACTIVE AFTER INSERT OR UPDATE OR DELETE POSITION 0 AS BEGIN END^
CREATE or ALTER trigger vfin_esc_tservicofixo_ref_bi0 for vfin_esc_tservicofixo_ref active before insert position 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_esc_tservicofixoger_bi0 FOR vfin_esc_tservicofixoger ACTIVE BEFORE INSERT POSITION 0 AS begin END ^
CREATE OR ALTER TRIGGER vfin_esc_tfatura_bi0 FOR vfin_esc_tfatura ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_base_tlimitededret_bi0 FOR vfin_base_tlimitededret ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_esc_trecfatura_aiud0 FOR vfin_esc_trecebimentofatura ACTIVE AFTER INSERT OR UPDATE OR DELETE POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_esc_trecfaturaser_aiud0 FOR vfin_esc_trecfaturaservico ACTIVE AFTER INSERT OR UPDATE OR DELETE POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_esc_tservicofaturado_bi0 FOR vfin_esc_tservicofaturado ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END^
CREATE OR ALTER TRIGGER vfin_esc_tservico_gest_bi0 FOR vfin_esc_tservico_gest ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_esc_tbaixarapidafatura_ad0 FOR vfin_esc_tbaixarapidafatura ACTIVE AFTER DELETE POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_esc_tobrigacao_gest_bi0 FOR vfin_esc_tobrigacao_gest ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_esc_timposto_gest_bi0 FOR vfin_esc_timposto_gest ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_esc_tservicofixoobs_bi0 FOR vfin_esc_tservicofixoobs ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_base_tparnfse_bi0 FOR vfin_base_tparnfse ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_base_tconfclievent_bi0 FOR vfin_base_tconfclievent ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_esc_tvalservico_bi0 FOR vfin_esc_tvalservico ACTIVE BEFORE INSERT POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_esc_tacordo_ad0 FOR vfin_esc_tacordo ACTIVE AFTER DELETE POSITION 0 AS BEGIN END ^
CREATE OR ALTER trigger vfin_esc_tacordofatbenef_bd0 for vfin_esc_tacordofatbenef active before delete position 0 AS begin end ^
CREATE OR ALTER TRIGGER vfin_esc_tfatura_ad0 FOR vfin_esc_tfatura ACTIVE AFTER DELETE POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_esc_tfatura_bd0 FOR vfin_esc_tfatura ACTIVE BEFORE DELETE POSITION 0 AS BEGIN END ^
CREATE OR ALTER TRIGGER vfin_esc_tfatura_bu0 FOR vfin_esc_tfatura ACTIVE BEFORE UPDATE POSITION 0 AS begin end^

CREATE OR ALTER TRIGGER vct_base_servico_ref_bi0 FOR vct_base_servico_ref
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vfin_esc_tservicofaturado_ad0 for vfin_esc_tservicofaturado
active after delete position 0
as
begin
end
^

CREATE OR ALTER TRIGGER TAVISOS_BI0 FOR TAVISOS
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER empresas_tsoc_ref_bi0 FOR empresas_tsoc_ref
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER tol_vfin_esc_tserfat_ad0 FOR tol_vfin_esc_tserfat
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE or alter trigger tol_vfin_esc_tcontaspagdesp_ad0 for tol_vfin_esc_tcontaspagardesp
active after delete position 0
AS
begin
end^

CREATE or alter trigger tol_vfin_esc_tpagdesp_ad0 for tol_vfin_esc_tpagdesp
active after delete position 0
AS
begin
end^

CREATE or alter trigger tol_vfin_esc_tlancbancario_ad0 for tol_vfin_esc_tlancbancario
active after delete position 0
AS
begin
end^

CREATE OR ALTER TRIGGER vfin_esc_tpdf_email_bi0 FOR vfin_esc_tpdf_email
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VFIN_ESC_TCONTASBAN_AI0 FOR VFIN_ESC_TCONTASBAN
ACTIVE AFTER INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TGERADORDOCS_MOD_BI0 FOR TGERADORDOCS_MOD
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER tol_vfin_esc_trecfatura_ad0 FOR tol_vfin_esc_trecfatura
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vfin_base_tdespesa_bi0 FOR vfin_base_tdespesa
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vfin_base_tcategoriafin_bi0 for vfin_base_tcategoriafin
active before insert position 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vfin_base_tcategoriafin_bd0 for vfin_base_tcategoriafin
active before delete position 0
AS
begin
end
^

CREATE OR ALTER TRIGGER vfin_base_tdespesa_ref_bi0 FOR vfin_base_tdespesa_ref
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vfin_base_tfornecedor_bi0 FOR vfin_base_tfornecedor
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vfin_base_tfornecedor_ref_bi0 FOR vfin_base_tfornecedor_ref
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vfin_base_tfornecedor_ai0 for vfin_base_tfornecedor
active after insert position 0
AS
begin
end^

CREATE OR ALTER trigger vfin_base_tfornecedor_ref_ai0 for vfin_base_tfornecedor_ref
active after insert position 0
AS
begin
end^

CREATE OR ALTER TRIGGER VFIN_ESC_TCONTASPAGARDESP_BI0 FOR VFIN_ESC_TCONTASPAGARDESP
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VFIN_ESC_TPARCELAPAGAR_BI0 FOR VFIN_ESC_TPARCELAPAGAR
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VFIN_ESC_TRETPAGAR_BI0 FOR VFIN_ESC_TRETPAGAR
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vfin_esc_tcontaspagdespobs_bi0 FOR vfin_esc_tcontaspagardespobs
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^
CREATE OR ALTER TRIGGER VFIN_BASE_TFORMAPAGAMENTO_BI0 FOR VFIN_BASE_TFORMAPAGAMENTO
ACTIVE BEFORE INSERT POSITION 0
AS
begin 
end
^

CREATE OR ALTER TRIGGER vfin_esc_tpagamentosobs_bi0 FOR vfin_esc_tpagamentosobs
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VFIN_ESC_TPAGAMENTOS_BI0 FOR VFIN_ESC_TPAGAMENTOS
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vfin_esc_tpagamentos_aiud0 FOR vfin_esc_tpagamentos
ACTIVE AFTER INSERT OR UPDATE OR DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VFIN_ESC_TCONTASPAGARDESPCC_BI0 FOR VFIN_ESC_TCONTASPAGARDESPCC
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^


CREATE OR ALTER TRIGGER VFIN_ESC_TRECANTECIP_DEST_BIUD0 FOR VFIN_ESC_TRECANTECIP_DEST
ACTIVE BEFORE INSERT OR UPDATE OR DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vfin_base_tdespesa_bd0 FOR vfin_base_tdespesa
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VFIN_ESC_TCONTASPAGARDESP_AIUD0 FOR VFIN_ESC_TCONTASPAGARDESP
ACTIVE AFTER INSERT OR UPDATE OR DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vfin_esc_tcontaspagardesp_bd0 FOR vfin_esc_tcontaspagardesp
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vfin_esc_tpagdesp_aiud0 FOR vfin_esc_tpagdesp
ACTIVE AFTER INSERT OR UPDATE OR DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER vfin_base_tcliente_bd0 FOR vfin_base_tcliente
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VFIN_BASE_TCLIENTE_REF_BD0 FOR VFIN_BASE_TCLIENTE_REF
ACTIVE BEFORE DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER vfin_esc_tfaturadel_bi0 FOR vfin_esc_tfaturadel
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

--Sol. 19704 - Bruno L. R. - 27/07/2017
CREATE OR ALTER TRIGGER VRH_EMP_TCOL_EXAME_TOX_BI0 FOR VRH_EMP_TCOL_EXAME_TOX
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_EXAME_TOX_AI0 FOR VRH_EMP_TCOL_EXAME_TOX
ACTIVE AFTER INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_EXAME_TOX_AU0 FOR VRH_EMP_TCOL_EXAME_TOX
ACTIVE AFTER UPDATE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_EXAME_TOX_BU0 FOR VRH_EMP_TCOL_EXAME_TOX
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TREDUCAOCOL_BI0 FOR VRH_EMP_TREDUCAOCOL
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TREDUCAOCOL_BU0 FOR VRH_EMP_TREDUCAOCOL
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER trigger vrh_emp_tsitcol_bi0 for vrh_emp_tsitcol
active before insert position 0
AS
begin
end
^

CREATE OR ALTER trigger vrhf_emp_tvscol_au0 for vrhf_emp_tvscol
active after update position 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vrhf_emp_tvscol_ad0 for vrhf_emp_tvscol
active after delete position 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vrhf_emp_tvsemp_au0 for vrhf_emp_tvsemp
active after update position 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vrhf_emp_tvsemp_ad0 for vrhf_emp_tvsemp
active after delete position 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vrhf_funcoes_tvsfuc_au0 for vrhf_funcoes_tvsfuc
active after update position 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vrhf_funcoes_tvsfuc_ad0 for vrhf_funcoes_tvsfuc
active after delete position 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vrhf_custos_tvscusto_au0 for vrhf_custos_tvscusto
active after update position 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vrhf_custos_tvscusto_ad0 for vrhf_custos_tvscusto
active after delete position 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vrhf_base_tvssind_au0 for vrhf_base_tvssind
active after update position 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vrhf_base_tvssind_ad0 for vrhf_base_tvssind
active after delete position 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vrhf_base_tvspres_au0 for vrhf_base_tvspres
active after update position 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vrhf_base_tvspres_ad0 for vrhf_base_tvspres
active after delete position 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vrhf_base_tvster_au0 for vrhf_base_tvster
active after update position 0
AS
BEGIN
END
^

CREATE or alter trigger tmenu_novos_bi0 for tmenu_novos
active before insert position 0
AS
begin
end^

CREATE OR ALTER trigger tmenu_biu0 for tmenu
active before insert or update position 0
AS
begin
end^

CREATE OR ALTER trigger vrhf_base_tvster_ad0 for vrhf_base_tvster
active after delete position 0
AS
BEGIN
END
^


CREATE OR ALTER TRIGGER VRH_BASE_TRUBRICAES_VER_PD_AIU0 FOR VRH_BASE_TRUBRICAES_VER_PD
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
begin
end
^
CREATE OR ALTER trigger vrh_emp_tsitcol_ai0 for vrh_emp_tsitcol
active after insert position 0
as
declare variable WS varchar(300);
declare variable WCAT integer;
declare variable WCATES integer;
declare variable WHORA time;
declare variable WDATAINI date;
declare variable WDATAFIM date;
declare variable WDIASIT integer;
declare variable wSQLInt varchar(1000);
declare variable wSQLInt2 varchar(1000);
declare variable wdatafimant date;
declare variable wreffimsit integer;
declare variable wreffimcont integer;
declare variable winisefipstr varchar(10);
declare variable wdataaux date;
declare variable wlastcodcont integer;
declare variable wCodSit integer;
declare variable wDiaUtil integer;
declare variable wDataPagamento date;
declare variable wferiado varchar(5);
declare variable wPagEmp integer;
begin
end
^

CREATE OR ALTER trigger vrh_base_tconf_ficha_out_bi0 for vrh_base_tconf_ficha_out
active before insert position 0
AS
  DECLARE VARIABLE vclass VARCHAR(20);

BEGIN
END
^

CREATE OR ALTER trigger vrh_base_tconf_ficha_out_bu0 for vrh_base_tconf_ficha_out
active before update position 0
AS
  DECLARE VARIABLE vclass VARCHAR(20);

BEGIN
END
^

CREATE OR ALTER PROCEDURE SP_CONSULTACLIENTES (
    PRREFMICRO INTEGER,
    PRCODCLI VARCHAR(10240),
    PRCODSITCLI INTEGER)
RETURNS (
    BDCODCLI INTEGER,
    BDCODESC INTEGER,
    BDCODPRESER INTEGER,
    BDCODCLIMATRIZ INTEGER,
    BDCNPJCLI VARCHAR(18),
    BDDATAINIATIVCLI DATE,
    BDDATAFIMATIVCLI DATE,
    BDORGAOCLI VARCHAR(20),
    BDNUMREGCLI VARCHAR(40),
    BDNOMECARTORIO VARCHAR(100),
    BDDATAREGCLI DATE,
    BDLIVROREG VARCHAR(15),
    BDFOLHAREG VARCHAR(15),
    BDDOCAUXREG VARCHAR(18),
    BDCODTIPOCLI INTEGER,
    BDDATACADCLI DATE,
    BDCODCID INTEGER,
    BDCODCNAE INTEGER,
    BDCODNATJUR INTEGER,
    BDDESCPLASITFIN VARCHAR(50),
    BDCODPLASITFIN INTEGER,
    BDAPECLI DM_BDAPEMP,
    BDNOMCLI DM_BDNOMEMP,
    BDNOMREDUZCLI DM_BDNOMREDUZEMP,
    BDCEPCLI VARCHAR(9),
    BDLOGRCLI VARCHAR(15),
    BDENDCLI DM_BDENDERECO,
    BDNUMCLI DM_NUMEND,
    BDCOMPLCLI DM_BDCOMPENDERECO,
    BDBAICLI DM_BDBAIRRO,
    BDDDDCLI INTEGER,
    BDFONECLI DM_BDTELEFONE,
    BDDDDFAXCLI INTEGER,
    BDFONEFAXCLI DM_BDTELEFONE,
    BDDDDCELCLI INTEGER,
    BDCELCLI DM_BDTELEFONE,
    BDCXPCLI DM_CXPOSTAL,
    BDIECLI VARCHAR(20),
    BDIMCLI VARCHAR(20),
    BDEMAILCLI DM_BDEMAIL,
    BDEMAILFINCLI DM_BDEMAIL,
    BDCAPITALSOC DM_NUMERIC_15_2,
    BDORGAOPUBLICO DM_BOOLEAN,
    BDNOMCID VARCHAR(40),
    BDSIGLAUF VARCHAR(2),
    BDDESCCNAE VARCHAR(200),
    BDDESCNAT VARCHAR(100),
    BDNUMFUN INTEGER,
    BDCODPLATRIB INTEGER,
    BDINATIVO DM_BOOLEAN,
    BDDESCPLATRIB VARCHAR(50),
    BDCODIBGECID INTEGER,
    BDCODFEDCID INTEGER,
    BDCODSPEDPAIS INTEGER,
    BDCODPLANOONLINE INTEGER,
    BDCODPLAPADRAO INTEGER,
    BDCODHIST INTEGER,
    BDCODSITCLI INTEGER,
    BDCODZONA integer)
AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WPOS INTEGER;
BEGIN
  SUSPEND;
END
^

CREATE OR ALTER PROCEDURE SP_CONSULTACLIENTES_SIS (
    PRREFMICRO INTEGER,
    PRCODCLI INTEGER,
    PRCODSITCLI INTEGER)
RETURNS (
    BDCODCLI INTEGER,
    BDCODESC INTEGER,
    BDCODPRESER INTEGER,
    BDCODCLIMATRIZ INTEGER,
    BDCNPJCLI VARCHAR(18),
    BDDATAINIATIVCLI DATE,
    BDDATAFIMATIVCLI DATE,
    BDORGAOCLI VARCHAR(20),
    BDNUMREGCLI VARCHAR(40),
    BDNOMECARTORIO VARCHAR(100),
    BDDATAREGCLI DATE,
    BDLIVROREG VARCHAR(15),
    BDFOLHAREG VARCHAR(15),
    BDDOCAUXREG VARCHAR(18),
    BDCODTIPOCLI INTEGER,
    BDDATACADCLI DATE,
    BDCODCID INTEGER,
    BDCODCNAE INTEGER,
    BDCODNATJUR INTEGER,
    BDAPECLI DM_BDAPEMP,
    BDNOMCLI DM_BDNOMEMP,
    BDNOMREDUZCLI DM_BDNOMREDUZEMP,
    BDCEPCLI VARCHAR(9),
    BDLOGRCLI VARCHAR(15),
    BDENDCLI DM_BDENDERECO,
    BDNUMCLI DM_NUMEND,
    BDCOMPLCLI DM_BDCOMPENDERECO,
    BDBAICLI DM_BDBAIRRO,
    BDDDDCLI INTEGER,
    BDFONECLI DM_BDTELEFONE,
    BDDDDFAXCLI INTEGER,
    BDFONEFAXCLI DM_BDTELEFONE,
    BDDDDCELCLI INTEGER,
    BDCELCLI DM_BDTELEFONE,
    BDCXPCLI DM_CXPOSTAL,
    BDIECLI VARCHAR(20),
    BDIMCLI VARCHAR(20),
    BDEMAILCLI DM_BDEMAIL,
    BDEMAILFINCLI DM_BDEMAIL,
    BDCAPITALSOC DM_NUMERIC_15_2,
    BDORGAOPUBLICO DM_BOOLEAN,
    BDDATAENTRADA DATE,
    BDDATASAIDA DATE,
    BDCODCONT INTEGER,
    BDCONTATO VARCHAR(60),
    BDPROFISCONTATO VARCHAR(60),
    BDDATANASCCON DATE,
    BDCPFCON VARCHAR(18),
    BDCODCIDETI INTEGER,
    BDNOMENDETI DM_BDNOMEMP,
    BDLOGRETI VARCHAR(15),
    BDENDERECOETI DM_BDENDERECO,
    BDNUMEROETI INTEGER,
    BDCOMPLETI DM_BDCOMPENDERECO,
    BDBAIRROETI DM_BDBAIRRO,
    BDCEPETI VARCHAR(9),
    BDCXPETI DM_CXPOSTAL,
    BDNOMCIDETI VARCHAR(40),
    BDSIGLAUFETI VARCHAR(2),
    BDCODENQFED INTEGER,
    BDCOMERCIO DM_BOOLEAN,
    BDINDUSTRIA DM_BOOLEAN,
    BDSERVICO DM_BOOLEAN,
    BDANEXOIII DM_BOOLEAN,
    BDANEXOIV DM_BOOLEAN,
    BDANEXOV DM_BOOLEAN,
    BDANEXOVI DM_BOOLEAN,
    BDPERINSS DM_NUMERIC_7_4_ALIQ,
    BDDEDINSSNF DM_BOOLEAN,
    BDUSARPERISS INTEGER,
    BDRETIR DM_BOOLEAN,
    BDRETCSLL DM_BOOLEAN,
    BDRETCOF DM_BOOLEAN,
    BDRETPIS DM_BOOLEAN,
    BDNOMCID VARCHAR(40),
    BDSIGLAUF VARCHAR(2),
    BDDESCSITCLI VARCHAR(100),
    BDDESCCNAE VARCHAR(200),
    BDDESCNAT VARCHAR(100),
    BDNUMFUN INTEGER,
    BDINATIVO DM_BOOLEAN,
    BDCODPLATRIB INTEGER,
    BDDESCPLATRIB VARCHAR(50),
    BDCODIBGECID INTEGER,
    BDCODFEDCID INTEGER,
    BDCODSPEDPAIS INTEGER,
    BDINCENTCULT DM_BOOLEAN,
    BDCODIBGECIDETI INTEGER,
    BDCODFEDCIDETI INTEGER,
    BDCODPLANOONLINE INTEGER,
    BDCODPLAPADRAO INTEGER,
    BDCODSITESP INTEGER,
    BDCODPLASITFIN INTEGER,
    BDDESCPLASITFIN VARCHAR(50),
    BDCODHIST INTEGER,
    BDRETIMP INTEGER,
    BDDESTIR varchar(5),
    BDDESTCOF varchar(5),
    BDDESTPIS varchar(5),
    BDDESTCSLL varchar(5))
AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WPAR VARCHAR(50);
BEGIN
  SUSPEND;
END
^

CREATE OR ALTER PROCEDURE SP_CONSULTASERVICOS (
    PRREFSER INTEGER,
    PRCODOBRSER INTEGER)
RETURNS (
    BDCODOBRSER INTEGER,
    BDCHAVE INTEGER,
    BDCLASSIFICACAO VARCHAR(60),
    BDDESCRICAO VARCHAR(100),
    BDPERIODICIDADE INTEGER,
    BDDIA INTEGER,
    BDANTECIPAR VARCHAR(5),
    BDVENCE INTEGER,
    BDALERTA INTEGER,
    BDCRIACAO DATE,
    BDEXTINTO DATE,
    BDSITEGOVERNO VARCHAR(255),
    BDPREVHORAS VARCHAR(6),
    BDTIPO SMALLINT,
    BDPREVDIAS INTEGER,
    BDCODSIS INTEGER,
    BDMESVENCE INTEGER,
    BDENTREGA INTEGER,
    BDTEMPOESTIMADO INTEGER,
    BDSABDOMFER INTEGER,
    BDPERISS NUMERIC(15,4),
    BDPERIRRF NUMERIC(15,4),
    BDPERCSLL NUMERIC(15,4),
    BDPERCOF NUMERIC(15,4),
    BDPERPIS NUMERIC(15,4),
    BDDEDISS VARCHAR(5),
    BDDEDIRRF VARCHAR(5),
    BDDEDCSLL VARCHAR(5),
    BDDEDCOFINS VARCHAR(5),
    BDDEDPIS VARCHAR(5),
    BDTIPSERV INTEGER,
    BDCALCINSS VARCHAR(5),
    BDSOFREREAJ VARCHAR(5),
    BDDESCONTO VARCHAR(5),
    BDVALORPADRAO DM_NUMERIC_15_2,
    BDCODCOBSERV INTEGER,
    BDCODCAT integer,
    BDCONTABILIZAR VARCHAR(5))
AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
  SUSPEND;
END
^

/*Adilson Hasckel - Sol. 14282 - 05/05/2016 - SP do financeiro utilizados na ONLINE - automatismos dos serviços */
CREATE OR ALTER PROCEDURE VFIN_CLASSIFSERVICO_ONLINE (
    PRCLAANT VARCHAR(100),
    PRCLANOVA VARCHAR(100))
RETURNS (
    BDCLAANTSERVICO VARCHAR(100),
    BDCLANOVASERVICO VARCHAR(100))
AS
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WADD VARCHAR(10);
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VFIN_INSERT_NOVO_SERVICO_ONLINE (
    PRCLASSIFICACAO VARCHAR(100),
    PRCODOBRSER INTEGER)
AS
DECLARE VARIABLE WPLANO INTEGER;
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WCLASERONLINE VARCHAR(100);
DECLARE VARIABLE WFORMULA VARCHAR(100);
DECLARE VARIABLE WCODTIPOCONTA INTEGER;
BEGIN END
^

CREATE OR ALTER PROCEDURE VFIN_UPDATE_SERVICO_ONLINE (
    PRCLAANT VARCHAR(1000),
    PRCLANOVA VARCHAR(1000),
    PRCODOBRSER INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WCLAANT VARCHAR(100);
DECLARE VARIABLE WCLANOVA VARCHAR(100);
DECLARE VARIABLE WCODTIPOCONTA INTEGER;
BEGIN END
^

CREATE OR ALTER PROCEDURE VFIN_INSERT_CONTABAN_ONLINE (
    PRCHAVECTABAN INTEGER)
AS
DECLARE VARIABLE WPLANO INTEGER;
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WCLACONTABANONLINE VARCHAR(100);
DECLARE VARIABLE WFORMULA VARCHAR(100);
DECLARE VARIABLE WCODTIPOCONTA INTEGER;
BEGIN

END
^

CREATE OR ALTER PROCEDURE VFIN_INSERT_CLIENTE_ONLINE (PRCODCLI INTEGER)
AS
DECLARE VARIABLE WPLANO INTEGER;
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WCLACLIONLINE VARCHAR(100);
DECLARE VARIABLE WFORMULA VARCHAR(100);
DECLARE VARIABLE WCODTIPOCONTA INTEGER;
BEGIN

END
^


CREATE OR ALTER PROCEDURE SP_CONSULTADESPESAS (
    PRREFDESP INTEGER,
    PRCODDESP INTEGER)
RETURNS (
    BDCODDESP INTEGER,
    BDCLASSDESP DM_CLASSCONTAS,
    BDDESCDESP VARCHAR(100),
    BDSABDOMFER INTEGER,
    BDDIAVENC INTEGER,
    BDTIPODESP INTEGER,
    BDVALORDESP DM_NUMERIC_15_2,
    BDDESCONTO DM_BOOLEAN,
    BDCODCAT integer)
AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
  SUSPEND;
END
^

--SET TERM ^ ;

CREATE OR ALTER procedure VFIN_SP_CONSFORNECEDORES (
    PRCODFOR integer,
    PRREF integer,
    PRWHEREFOR varchar(20000))
returns (
    BDCODFOR integer,
    BDCNPJFOR varchar(18),
    BDREFFOR integer,
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
    BDCODPAIS integer,
    BDDESCPAIS varchar(60),
    BDNOMEFOR DM_BDNOMEMP,
    BDAPEFOR DM_BDAPEMP,
    BDCEPFOR varchar(9),
    BDLOGRFOR DM_LOGRADOURO,
    BDENDFOR DM_BDENDERECO,
    BDNUMENDFOR DM_BDENDERECO_NR,
    BDBAIFOR DM_BDBAIRRO,
    BDCOMPLENDFOR DM_BDCOMPENDERECO,
    BDIEFOR varchar(20),
    BDIMFOR varchar(20),
    BDDDDFONEFOR integer,
    BDFONEFOR DM_BDTELEFONE,
    BDDDDFAXFOR integer,
    BDFAXFOR DM_BDTELEFONE,
    BDEMAILFOR DM_BDEMAIL,
    BDDATACADFOR date,
    BDDDDCELFOR integer,
    BDCELFOR DM_BDTELEFONE,
    BDCODDESP integer,
    BDDESCDESP varchar(100))
as
declare variable WSQL varchar(10240);
declare variable WWHERE varchar(20000);
BEGIN
  SUSPEND;
END^

/* Drop Procedure... */

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_IMP_SERV_BI0 FOR VRH_BASE_TCONF_IMP_SERV
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE VCOD INTEGER;
BEGIN
    VCOD = 0;
END^

CREATE OR ALTER TRIGGER TR_BF_INS_VRH_BASE_TSERVTERC FOR VRH_BASE_TSERVTERC
ACTIVE BEFORE INSERT POSITION 0 
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VSUC_EMPRESAS_TLAN FOR VSUC_EMPRESAS_TLAN
ACTIVE BEFORE INSERT POSITION 0
AS
    DECLARE VARIABLE I INTEGER;
BEGIN
    I = 0;
END
^

CREATE OR ALTER TRIGGER VSUC_EMPRESAS_TLAN_BIU1 FOR VSUC_EMPRESAS_TLAN
ACTIVE BEFORE INSERT OR UPDATE POSITION 1
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TIPOS_LANCAMENTOS_PADRAO_BD0 FOR TIPOS_LANCAMENTOS_PADRAO
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAI_BIU1 FOR VEF_EMP_TMOVSAI
ACTIVE BEFORE INSERT OR UPDATE POSITION 1
AS
begin
end
^

CREATE OR ALTER trigger tmoedas_ad0 for tmoedas
active after delete position 0
AS
begin
end^

CREATE OR ALTER trigger vef_base_ttabinfad52_ad0 for vef_base_ttabinfad52
active after delete position 0
AS
begin
end^

CREATE OR ALTER trigger vef_emp_tmovsai_bd0 for vef_emp_tmovsai
active after delete position 0
AS
begin   
end^

CREATE or alter trigger vef_emp_tmovser_bd0 for vef_emp_tmovser
active before delete position 0
AS
begin   
end^

CREATE OR ALTER trigger vef_emp_tmovexp_bd0 for vef_emp_tmovexp
active before delete position 0
AS
begin   
end^

CREATE or alter trigger vef_emp_tredz_bd0 for vef_emp_tredz
active before delete position 0
AS
begin   
end^

CREATE or alter trigger vef_emp_tmovfini100_bd0 for vef_emp_tmovfini100
active before delete position 0
AS
begin   
end^

CREATE or alter trigger vef_emp_tmovinv_bd0 for vef_emp_tmovinv
active before delete position 0
AS
begin   
end^

CREATE OR ALTER trigger vef_emp_tmovorec_bd0 for vef_emp_tmovorec
active before delete position 0
AS
begin   
end^

CREATE OR ALTER trigger vef_emp_tmovopimobiliaria_f200_bd0 for vef_emp_tmovopimobiliaria_f200
active before delete position 0
AS
begin   
end^

CREATE or alter trigger vef_emp_tmovdemaisdoc_f100_bd0 for vef_emp_tmovdemaisdoc_f100
active before delete position 0
AS
begin   
end^

CREATE or alter trigger vef_emp_tmovent_bd0 for vef_emp_tmovent
active before delete position 0
AS
begin   
end^

CREATE OR ALTER trigger vef_emp_tmovprosaiimpori_biu0 for vef_emp_tmovprosaiimpori
active before insert or update position 0
AS
begin
end^

CREATE OR ALTER trigger vef_emp_tmovsaipar_bu0 for vef_emp_tmovsaipar
active before insert or update position 0
AS
begin
end^

CREATE OR ALTER trigger vef_emp_tc195sai_bu0 for vef_emp_tc195sai
active before insert or update position 0
AS
begin
end^

CREATE OR ALTER trigger vef_base_ttabinfrete_bd0 for vef_base_ttabinfrete
active before delete position 0
AS
begin
end^

CREATE OR ALTER trigger tcadpro_bd0 for tcadpro
active before delete position 0
AS
begin
end^

CREATE OR ALTER trigger tempresas_scp_bd0 for tempresas_scp
active before delete position 0
as
begin
end^

CREATE OR ALTER trigger tplano_pagamento_bd0 for tplano_pagamento
active before delete position 0
as
begin
end^

CREATE OR ALTER trigger vef_base_ttabcta_bd0 for vef_base_ttabcta
active before delete position 0
AS
begin
end^

CREATE OR ALTER trigger tunidademedida_bd0 for tunidademedida
active before delete position 0
AS
begin
end^

CREATE OR ALTER trigger tncm_bd0 for tncm
active before delete position 0
AS
begin
end^

CREATE OR ALTER trigger tterceiro_bd0 for tterceiro
active before delete position 0
AS
begin
end^

CREATE OR ALTER trigger vef_base_tequipasat_bd0 for vef_base_tequipasat
active before delete position 0
AS
begin
end
^

CREATE OR ALTER trigger vef_emp_tcadempreendimento_bd0 for vef_emp_tcadempreendimento
active before delete position 0
AS
begin
end
^

CREATE OR ALTER trigger vef_emp_tc100sai_bu0 for vef_emp_tc100sai
active before insert or update position 0
AS
begin
end^

CREATE or ALTER  trigger VEF_EMP_TMOVPROENT_ad0 for VEF_EMP_TMOVPROENT
active after delete position 0
AS
begin
end
^

CREATE or ALTER trigger VEF_EMP_TMOVPROSAI_ad0 for VEF_EMP_TMOVPROSAI
active after delete position 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVPROSAI_AIUD0 FOR VEF_EMP_TMOVPROSAI
ACTIVE AFTER INSERT OR UPDATE OR DELETE POSITION 0
AS
BEGIN
END
^

CREATE or ALTER trigger VEF_EMP_TREDZC425_ad0 for VEF_EMP_TREDZC425
active after delete position 0
AS
begin
end
^

CREATE or ALTER trigger VEF_EMP_TREDZC425ALIQ_ad0 for VEF_EMP_TREDZC425ALIQ
active after delete position 0
AS
begin
end
^

CREATE or ALTER trigger VEF_EMP_TREDZ60I_ad0 for VEF_EMP_TREDZ60I
active after delete position 0
AS
begin
end
^

CREATE or ALTER trigger VEF_EMP_TITEMDOCECF_ad0 for VEF_EMP_TITEMDOCECF
active after delete position 0
AS
begin
end
^

CREATE or ALTER trigger vef_emp_tmovprosai_biu_comprefnull for vef_emp_tmovprosai
active before insert or update position 0
AS
begin
end^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVPROSAI_BIU1 FOR VEF_EMP_TMOVPROSAI
ACTIVE BEFORE INSERT OR UPDATE POSITION 1
AS
begin
end
^

CREATE OR ALTER TRIGGER VEF_BASE_TPLANOACOESTROCA_BIU0 FOR VEF_BASE_TPLANOACOESTROCA
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
end
^
CREATE OR ALTER TRIGGER VEF_BASE_TTAB6_TIPOSER_BD0 FOR VEF_BASE_TTAB6_TIPOSER
ACTIVE BEFORE DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAIITENS_BIU1 FOR VEF_EMP_TMOVSAIITENS
ACTIVE BEFORE INSERT OR UPDATE POSITION 1
AS
begin
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TC190SAI_BIU1 FOR VEF_EMP_TC190SAI
ACTIVE BEFORE INSERT OR UPDATE POSITION 1
AS
begin
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TC197SAI_BIU1 FOR VEF_EMP_TC197SAI
ACTIVE BEFORE INSERT OR UPDATE POSITION 1
AS
begin
end
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABMODELOLAN_BD0 FOR VEF_BASE_TTABMODELOLAN
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TUSUARIO_BD0 FOR TUSUARIO
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER TCIDADE_BD0 FOR TCIDADE
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_BASE_STATUSLANC_BD0 FOR VEF_BASE_STATUSLANC
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABSITNF_BD0 FOR VEF_BASE_TTABSITNF
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^ 
   
CREATE OR ALTER TRIGGER TFATCONV_BD0 FOR TFATCONV
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABCSTIPI_BD0 FOR VEF_BASE_TTABCSTIPI
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABCSTPIS_BD0 FOR VEF_BASE_TTABCSTPIS
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABCSTCOF_BD0 FOR VEF_BASE_TTABCSTCOF
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTAB_NATREC_BD0 FOR VEF_BASE_TTAB_NATREC
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^               

CREATE OR ALTER TRIGGER VEF_BASE_TOBSERVACAO_BD0 FOR VEF_BASE_TOBSERVACAO
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABCSTICMS_BD0 FOR VEF_BASE_TTABCSTICMS
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TNATOP_BD0 FOR VEF_BASE_TNATOP
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABCODAJU_BD0 FOR VEF_BASE_TTABCODAJU
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABCODITEM1400_BD0 FOR VEF_BASE_TTABCODITEM1400
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSERVTERC_BU0 FOR VRH_BASE_TSERVTERC
ACTIVE BEFORE UPDATE POSITION 0 
AS
    DECLARE VARIABLE I INTEGER;
BEGIN
    I = 0;
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSERVTERC_AD0 FOR VRH_BASE_TSERVTERC
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TDADOSCALC_BAIXA_BI0 FOR VRHF_EMP_TDADOSCALC_BAIXA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHAAVULSA_BI0 FOR VRHF_EMP_TFOLHAAVULSA
ACTIVE BEFORE INSERT POSITION 0 
AS
    DECLARE VARIABLE I INTEGER;
BEGIN
    I = 0;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHAAVULSA_BU0 FOR VRHF_EMP_TFOLHAAVULSA
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSINDTRAB_PERC_BI0 FOR VRH_BASE_TSINDTRAB_PERC
 ACTIVE BEFORE INSERT POSITION 0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRESCISAO_AD0 FOR VRH_EMP_TRESCISAO
ACTIVE AFTER DELETE POSITION 0
AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_PARTIDA_AD0 FOR VRH_EMP_TCOLCON_PARTIDA
ACTIVE AFTER DELETE POSITION 0
AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_PARTIDA_BU0 FOR VRH_EMP_TCOLCON_PARTIDA
ACTIVE BEFORE UPDATE POSITION 0
AS
  DECLARE VARIABLE vcontrcol INTEGER;
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSINDTRAB_PERC_BU0 FOR VRH_BASE_TSINDTRAB_PERC
 ACTIVE BEFORE UPDATE POSITION 0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERRECIFE_BI0 FOR VEF_EMP_TMOVSERRECIFE
 ACTIVE BEFORE INSERT POSITION 0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERCABIPM_BI0 FOR VEF_EMP_TMOVSERCABIPM
 ACTIVE BEFORE UPDATE POSITION 0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

--14648 - 08/07/2016 - Criação da trigger (before insert) na tabela VRHF_BASE_TRUBRICAS_DOM_PADRAO para retornar o próximo código para o campo BDCODIGO - Bruno L. R.
CREATE OR ALTER TRIGGER vrhf_base_trubr_dom_pad_bi0 FOR vrhf_base_trubricas_dom_padrao
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

--Sol. 18256 - Bruno L. R. - 02/08/2017 - Criação da trigger para gravar novamente o lançamento da rescisão no momento que o processo de reintegração é excluído
CREATE OR ALTER TRIGGER vrh_emp_trescisao_reintegr_ad0 FOR vrh_emp_trescisao_reintegracao
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_REINTEGRACAO_AD0 FOR VRH_EMP_TCOL_REINTEGRACAO
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER trigger VEF_EMP_TMOVENTPR_BI0 for VEF_EMP_TMOVENTPR
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
  declare variable VORDEMLAN INTEGER;
BEGIN
END^ 

CREATE OR ALTER trigger VEF_EMP_TMOVSAIPR_BI0 for VEF_EMP_TMOVSAIPR
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
  DECLARE VARIABLE vORDEMLAN INTEGER;
BEGIN
END^

CREATE OR ALTER trigger VEF_EMP_TMOVSERPR_BI0 for VEF_EMP_TMOVSERPR
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
  DECLARE VARIABLE vORDEMLAN INTEGER;
BEGIN
END^ 

CREATE OR ALTER TRIGGER VEF_EMP_TMOVDEMAISDOCPR_BI0 FOR VEF_EMP_TMOVDEMAISDOCPR
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
END^

CREATE OR ALTER trigger VEF_EMP_TAJUAPUPCM220620_BI0 for VEF_EMP_TAJUAPUPCM220620
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
end^

CREATE OR ALTER TRIGGER VEF_EMP_TAJUAPUPCM220620_BU0 FOR VEF_EMP_TAJUAPUPCM220620
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
end
^

CREATE OR ALTER trigger TMP_VEF_EMP_TREDZVARCFOP_TMP_BI for TMP_VEF_EMP_TREDZVARCFOP_TEMP
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
end^

CREATE OR ALTER trigger TMP_VEF_EMP_TREDZVARALIQ_BI for TMP_VEF_EMP_TREDZVARALIQ_TEMP
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
end^

CREATE OR ALTER TRIGGER TMP_VEF_EMP_TREDZC425_BI FOR TMP_VEF_EMP_TREDZC425_TEMP
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
end^

CREATE OR ALTER TRIGGER VEF_EMP_TCREDITO_M220_M620_BD0 FOR VEF_EMP_TCREDITO_M220_M620
ACTIVE BEFORE DELETE POSITION 0
AS
  DECLARE VARIABLE WCONTROLCRED DM_BOOLEAN;
begin
end^

CREATE OR ALTER TRIGGER TFORMSEQREL_BI0 FOR TFORMSEQREL
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
end^

CREATE OR ALTER TRIGGER TTIPOSEQREL_BI0 FOR TTIPOSEQREL
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERITENS_BIU0 FOR VEF_EMP_TMOVSERITENS
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
END
^


CREATE OR ALTER trigger vef_emp_tmovser_ibscbs_biu0 for vef_emp_tmovser_ibscbs
active before insert or update position 0
AS
begin
END
^

CREATE or alter trigger tol_vef_emp_tcomercnfprodrural_ad0 for tol_vef_emp_tcomercnfprodrural
active after delete position 0
AS
begin
end^

SET TERM ; ^

CREATE OR ALTER VIEW VW_BI_VERBAS_CALCULO(
    TIPO_CALCULO,
    CODIGO_EMPRESA,
    CODIGO_COLABORADOR,
    COMPETENCIA,
    CODIGO_VERBA,
    REFERENCIA_AUXILIAR,
    REFERENCIA,
    VALOR,
    DATA_PAGAMENTO)
AS
select 'FOLHA_NORMAL' as BDDTIPOCALCULO, VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDREFFN, VFN.BDCODVER, VFN.BDREFAUXVFN, VFN.BDREFVFN, VFN.BDVALVFN, FN.BDDATAPGTOFN
  from VRHF_EMP_TVERBAFN VFN
  join VRHF_EMP_TFOLHANORMAL FN on (FN.BDCODEMP = VFN.BDCODEMP and FN.BDCODCOL = VFN.BDCODCOL and FN.BDREFFN = VFN.BDREFFN)
  union all
  select 'FOLHA_COMPLEMENTAR' as BDDTIPOCALCULO, VFC.BDCODEMP, VFC.BDCODCOL, VFC.BDREFCOMP, VFC.BDCODVER, VFC.BDREFAUXVFC, VFC.BDREFVFC, VFC.BDVALVFC, FC.BDDATAPAGFC
  from VRHF_EMP_TVERBAFC VFC
  join VRHF_EMP_TFOLHACOMP FC on (FC.BDCODEMP = VFC.BDCODEMP and FC.BDCODCOL = VFC.BDCODCOL and FC.BDREFFN = VFC.BDREFFN and FC.BDREFFC = VFC.BDREFFC)
  union all
  select 'ADTO_SALARIAL' as BDDTIPOCALCULO, BDCODEMP, BDCODCOL, CAST((SUBSTRING(CAST(BDDATAAD as VARCHAR(10)) from 1 for 4)||SUBSTRING(CAST(BDDATAAD as VARCHAR(10)) from 6 for 2)) AS INTEGER) BDREFAD, BDCODVER, BDREFAUXVAD, BDREFVAD, BDVALVAD, BDDATAAD
  from VRHF_EMP_TVERBAAD
  union all
  select 'FERIAS' as BDDTIPOCALCULO, VFER.BDCODEMP, VFER.BDCODCOL,
    case when FER.BDINIPERGOZOFE is not null then CAST((SUBSTRING(CAST(FER.BDINIPERGOZOFE as VARCHAR(10)) from 1 for 4)||SUBSTRING(CAST(FER.BDINIPERGOZOFE as VARCHAR(10)) from 6 for 2)) AS INTEGER)
         else FER.BDREFPAGABOFE
    end  BDREFFE, BDCODVER, VFER.BDREFAUXVFE, VFER.BDREFVFE, VFER.BDVALVFE, FER.BDDATAPAGFE
  from VRHF_EMP_TVERBAFE VFER
  join VRH_EMP_TFERIAS FER on (FER.BDCODEMP = VFER.BDCODEMP and FER.BDCODCOL = VFER.BDCODCOL and FER.BDINIPERAQUISFE = VFER.BDINIPERAQUISFE and FER.BDCODFE = VFER.BDCODFE)
  union all
  select 'ADTO_13SALARIO' as BDDTIPOCALCULO, VA13.BDCODEMP, VA13.BDCODCOL, VA13.BDREFA13, VA13.BDCODVER, VA13.BDREFAUXVA13, VA13.BDREFVA13, VA13.BDVALVA13, A13.BDDATAPGTOA13
  from VRHF_EMP_TVERBAA13 VA13
  join VRHF_EMP_TA13SAL A13 on (A13.BDCODEMP = VA13.BDCODEMP and A13.BDCODCOL = VA13.BDCODCOL and A13.BDREFA13 = VA13.BDREFA13)
  union all
  select '13SALARIO' as BDDTIPOCALCULO, VS13.BDCODEMP, VS13.BDCODCOL, VS13.BDREF13, VS13.BDCODVER, VS13.BDREFAUXV13, VS13.BDREFV13, VS13.BDVALV13, S13.BDDATAPGTO13
  from VRHF_EMP_TVERBA13 VS13
  join VRHF_EMP_T13SAL S13 on (S13.BDCODEMP = VS13.BDCODEMP and S13.BDCODCOL = VS13.BDCODCOL and S13.BDREF13 = VS13.BDREF13)
  union all
  select 'COMPL_13SALARIO' as BDDTIPOCALCULO, VC13.BDCODEMP, VC13.BDCODCOL, VC13.BDREFC13, VC13.BDCODVER, VC13.BDREFAUXVC13, VC13.BDREFVC13, VC13.BDVALVC13, C13.BDDATAPGTOC13
  from VRHF_EMP_TVERBAC13 VC13
  join VRHF_EMP_TC13SAL C13 on (C13.BDCODEMP = VC13.BDCODEMP and C13.BDCODCOL = VC13.BDCODCOL and C13.BDREF13 = VC13.BDREF13 and C13.BDREFC13 = VC13.BDREFC13)
  union all
  select 'FOLHA_AVULSA' as BDDTIPOCALCULO, BDCODEMP, BDCODCOL, CAST((SUBSTRING(CAST(BDDATAFA as VARCHAR(10)) from 1 for 4)||SUBSTRING(CAST(BDDATAFA as VARCHAR(10)) from 6 for 2)) AS INTEGER) BDREFFA, BDCODVER, BDREFAUXVFA, BDREFVFA, BDVALVFA, BDDATAFA
  from VRHF_EMP_TVERBAFA
  union all
  select 'FOLHA_INTERMITENTE' as BDDTIPOCALCULO, VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDREFFN, VFN.BDCODVER, VFN.BDREFAUXVFN, VFN.BDREFVFN, VFN.BDVALVFN, FN.BDDATAPGTOFN
  from VRHF_EMP_TVERBAINT VFN
  join VRHF_EMP_TFOLHAINT FN on (FN.BDCODEMP = VFN.BDCODEMP and FN.BDCODCOL = VFN.BDCODCOL and FN.BDREFFN = VFN.BDREFFN and FN.BDCODCONTTI = VFN.BDCODCONTTI)
  union all
  select 'FOLHA_COMPL_INTERMITENTE' as BDDTIPOCALCULO, VFC.BDCODEMP, VFC.BDCODCOL, VFC.BDREFCOMP, VFC.BDCODVER, VFC.BDREFAUXVFC, VFC.BDREFVFC, VFC.BDVALVFC, FC.BDDATAPAGFC
  from VRHF_EMP_TVERBAFCINT VFC
  join VRHF_EMP_TFOLHACOMPINT FC on (FC.BDCODEMP = VFC.BDCODEMP and FC.BDCODCOL = VFC.BDCODCOL and FC.BDREFFN = VFC.BDREFFN and FC.BDCODCONTTI = VFC.BDCODCONTTI and FC.BDREFFC = VFC.BDREFFC)

  -- Por Tomador
  union all
  select 'FOLHA_NORMAL_TOMADOR' as BDDTIPOCALCULO, VFT.BDCODEMP, VFT.BDCODCOL, VFT.BDREFTOMADOR, VFT.BDCODVER, VFT.BDREFAUXVFT, VFT.BDREFVFT, VFT.BDVALVFT, FT.BDDATAPGTOFT
  from VRHF_EMP_TVERBATOMADOR VFT
  join VRHF_EMP_TFOLHATOMADOR FT on (FT.BDCODEMP = VFT.BDCODEMP and FT.BDCODCOL = VFT.BDCODCOL and FT.BDREFTOMADOR = VFT.BDREFTOMADOR and FT.BDORDEM = VFT.BDORDEM)
  union all
  select 'FOLHA_COMPLEMENTAR_TOMADOR' as BDDTIPOCALCULO, VFTC.BDCODEMP, VFTC.BDCODCOL, VFTC.BDREFCOMP, VFTC.BDCODVER, VFTC.BDREFAUXVFC, VFTC.BDREFVFC, VFTC.BDVALVFC, FTC.BDDATAPAGFC
  from VRHF_EMP_TVERBAFCTOMADOR VFTC
  join VRHF_EMP_TFOLTOMCOMP FTC on (FTC.BDCODEMP = VFTC.BDCODEMP and FTC.BDCODCOL = VFTC.BDCODCOL and FTC.BDREFTOMADOR = VFTC.bdreftomador and FTC.BDREFFC = VFTC.BDREFFC and FTC.BDORDEM = VFTC.BDORDEM)
  union all
  select 'FOLHA_INTERMITENTE_TOMADOR' as BDDTIPOCALCULO, VFT.BDCODEMP, VFT.BDCODCOL, VFT.BDREFTOMADOR, VFT.BDCODVER, VFT.BDREFAUXVFT, VFT.BDREFVFT, VFT.BDVALVFT, FT.BDDATAPGTOFT
  from VRHF_EMP_TVERBATOMINT VFT
  join VRHF_EMP_TFOLHATOMINT FT on (FT.BDCODEMP = VFT.BDCODEMP and FT.BDCODCOL = VFT.BDCODCOL and FT.BDREFTOMADOR = VFT.BDREFTOMADOR and FT.BDCODCONTTI = VFT.BDCODCONTTI and FT.BDORDEM = VFT.BDORDEM)
  union all
  select 'FOLHA_COMPL_INTERMITENTE_TOMADOR' as BDDTIPOCALCULO, VFTC.BDCODEMP, VFTC.BDCODCOL, VFTC.BDREFCOMP, VFTC.BDCODVER, VFTC.BDREFAUXVFC, VFTC.BDREFVFC, VFTC.BDVALVFC, FTC.BDDATAPAGFC
  from VRHF_EMP_TVERBAFCTOMINT VFTC
  join VRHF_EMP_TFOLTOMCOMPINT FTC on (FTC.BDCODEMP = VFTC.BDCODEMP and FTC.BDCODCOL = VFTC.BDCODCOL and FTC.BDREFTOMADOR = VFTC.BDREFTOMADOR and FTC.BDCODCONTTI = VFTC.BDCODCONTTI and FTC.BDORDEM = VFTC.BDORDEM and FTC.BDREFFC = VFTC.BDREFFC)
;

CREATE OR ALTER VIEW VW_BI_PROVENTOS_DESCONTOS(
    TIPO_CALCULO,
    CODIGO_EMPRESA,
    CODIGO_COLABORADOR,
    COMPETENCIA,
    DATA_PAGAMENTO,
    PROVENTOS,
    DESCONTOS,
    CLASSIFICACAO_VERBA)
AS
select
    CALC.TIPO_CALCULO,
    CALC.CODIGO_EMPRESA,
    CALC.CODIGO_COLABORADOR,
    CALC.COMPETENCIA,
    CALC.DATA_PAGAMENTO,
    case
      when (select first 1 V.BDTIPOCODVER from VRH_BASE_TVERBAS_REF V where V.BDCODVER = CALC.CODIGO_VERBA and V.BDREFVER <= CALC.COMPETENCIA order by V.BDREFVER desc) = 0 then CALC.VALOR
      else 0
    end,
    case
      when (select first 1 V.BDTIPOCODVER from VRH_BASE_TVERBAS_REF V where V.BDCODVER = CALC.CODIGO_VERBA and V.BDREFVER <= CALC.COMPETENCIA order by V.BDREFVER desc) = 1 then CALC.VALOR
      else 0
    end,
    VER.BDCLAVER
from VW_BI_VERBAS_CALCULO CALC
join VRH_BASE_TVERBAS VER on (VER.BDCODVER = CALC.CODIGO_VERBA)
;

CREATE OR ALTER VIEW VW_BI_LIQUIDO_RESCISAO(
    CODIGO_EMPRESA,
    CODIGO_COLABORADOR,
    COMPETENCIA,
    COMPETENCIA_PAGAMENTO,
    LIQUIDO,
    DATA_RESCISAO,
    DATA_PAGAMENTO_RESCISAO)
AS
select CALC.BDCODEMP, CALC.BDCODCOL, CALC.BDREFFN, CALC.BDREFPAG, CALC.BDLIQUIDO, RESC.BDDATARESCISAO, RESC.BDDATAPAGRESCISAO
  from (
    select BDCODEMP, BDCODCOL, BDREFFN, BDREFFN BDREFPAG, BDLIQUIDO
    from VRHF_EMP_TFOLHANORMAL
    union all
    select BDCODEMP, BDCODCOL, BDREFTOMADOR, BDREFTOMADOR, BDLIQUIDO
    from VRHF_EMP_TFOLHATOMADOR
    union all
    select BDCODEMP, BDCODCOL, BDREFFN, BDREFFN, BDLIQUIDO
    from VRHF_EMP_TFOLHAINT
    union all
    select BDCODEMP, BDCODCOL, BDREFTOMADOR, BDREFTOMADOR, BDLIQUIDO
    from VRHF_EMP_TFOLHATOMINT
    union all
    select BDCODEMP, BDCODCOL, BDREFFN, BDREFCOMP, BDLIQUIDO
    from VRHF_EMP_TFOLHACOMP
    union all
    select BDCODEMP, BDCODCOL, BDREFTOMADOR, BDREFCOMP, BDLIQUIDO
    from VRHF_EMP_TFOLTOMCOMP
    union all
    select BDCODEMP, BDCODCOL, BDREFFN, BDREFCOMP, BDLIQUIDO
    from VRHF_EMP_TFOLHACOMPINT
    union all
    select BDCODEMP, BDCODCOL, BDREFTOMADOR, BDREFCOMP, BDLIQUIDO
    from VRHF_EMP_TFOLTOMCOMPINT
    ) CALC
  join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = CALC.BDCODEMP and RESC.BDCODCOL = CALC.BDCODCOL and RESC.BDREFRESCISAO = CALC.BDREFFN)
;

CREATE OR ALTER VIEW VW_TEMPPARESTMG_MAX_MIN(
    BDCODEMP,
    BDREFEMP)
AS
SELECT
emp.bdcodemp,
  COALESCE(

    (
      SELECT FIRST 1 x.bdrefemp FROM VEF_BASE_TEMPPARESTMG x
      WHERE x.bdcodemp = emp.bdcodemp AND
      X.BDREFEMP <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
      ORDER BY x.bdcodemp DESC, x.bdrefemp DESC
     )

    ,
     (SELECT FIRST 1 x.bdrefemp FROM VEF_BASE_TEMPPARESTMG x
       WHERE x.bdcodemp = emp.bdcodemp
       ORDER BY x.bdcodemp, x.bdrefemp
      )
    ) BDREFEMP

FROM tempresas emp
where((bdexcluiremp is null)or(upper(bdexcluiremp)<>'TRUE'))
;

CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_BANCO_REF(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDCODBAN,
    BDCODAG,
    BDCTADEPCOL,
    BDDIGCTADEPCOL,
    BDTIPOCTACOL,
    BDMODOPAGTOCOL,
    BDCARTAOSALCOL)
AS
SELECT BASE.bdcodemp, BASE.bdcodcol, BASE.bdrefcol,
REF.bdcodban,
REF.bdcodag,
REF.bdctadepcol,
REF.bddigctadepcol,
REF.bdtipoctacol,
REF.bdmodopagtocol,
REF.bdcartaosalcol
FROM
(
  SELECT
      X.bdcodemp,
      X.bdcodcol,
      COALESCE
  (
      (SELECT MAX(d2.bdrefcol) FROM vrhf_emp_tcolcon_banco d2 WHERE d2.bdcodemp = x.bdcodemp AND d2.bdcodcol = x.bdcodcol AND CAST(d2.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefcol) FROM vrhf_emp_tcolcon_banco d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol)
  ) AS bdrefcol
  FROM vrh_emp_tcolcon x
) AS BASE, vrhf_emp_tcolcon_banco REF
WHERE BASE.bdcodemp = REF.bdcodemp AND BASE.bdcodcol = REF.bdcodcol AND BASE.bdREFCOL = REF.bdREFCOL
;

/* !!!!!!!!! CUIDADO, TEM DOIS LUGARES COM ESSE SCRIPT !!!!!!!!!!!! */
/* CREATE OR ALTER VIEW: VW_INT_SPEDPISCOFINS_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_INT_SPEDPISCOFINS_REF(
    BDCODEMP,
    BDCODIGO,
    BDINCTRIB,
    BDMETODOAPRO,
    BDTPCONTAPU,
    BDSOMENTEBLOCOP,
    BDEXPNFCOMVALENT,
    BDEXPNFCOMVALSAI,
    BDCODCRIT,
    BDCODCRITEXP,
    BDREFERENCIA,
    BDNAOEXPORTARPF,
    BDDESONREDZPERFILB,
    BDRBNCUMTRIBMI,
    BDRBNCUMNTMI,
    BDRBNCUMEXP,
    BDRBCUM,
    BDRETPISCOFPERANT,
    BDCREDITOSPERANT,
    BDSEMDADOS,
    BDINFCOMP,
    BDCREDITODEV,
    BDF525RECEITAF500,
    BDF550TOTCST,
    BDCONTACONTABF120,
    BDEXPCONTACONTAB,
    BDNAOCRED5ANOS,
    BDEXPCPFCNPJA100,
    BDEXPORTAPORSCP,
    BDCONTROLCRED,
    BDCREDANTERIOR,
    BDABATERESSARCIM,
    BDORDENACRED,
    BDNAOUTILIZARCRE,
    BDNAOUTILIZARCRED_201_208)
AS
SELECT
    c.bdcodemp,
    i.bdcodigo,
    i.bdinctrib,
    i.bdmetodoapro,
    i.bdtpcontapu,
    i.bdsomenteblocop,
    i.bdexpnfcomvalent,
    i.bdexpnfcomvalsai,
    i.bdcodcrit,
    t.bdcodcritexp,
    c.bdreferencia,
    i.bdnaoexportarpf,
    i.bddesonredzperfilb,
    i.BDRBNCUMTRIBMI,
    i.BDRBNCUMNTMI,
    i.BDRBNCUMEXP,
    i.BDRBCUM,
    i.BDRETPISCOFPERANT,
    i.BDCREDITOSPERANT,
    i.BDSEMDADOS,
    i.BDINFCOMP,
    i.BDCREDITODEV,
    i.BDF525RECEITAF500,
    i.BDF550TOTCST,
    i.BDCONTACONTABF120   ,
    i.BDEXPCONTACONTAB    ,
    i.BDNAOCRED5ANOS,
    i.BDEXPCPFCNPJA100,
    i.BDEXPORTAPORSCP,
    i.BDCONTROLCRED,
    i.BDCREDANTERIOR,
    i.BDABATERESSARCIM,
    i.BDORDENACRED,
    i.BDNAOUTILIZARCRE,
    i.BDNAOUTILIZARCRED_201_208
FROM
(
SELECT p.bdcodemp,
       COALESCE
       (
           (SELECT MAX(r1.bdreferencia) FROM vef_int_tsped_pis_cofins r1 WHERE r1.bdcodemp = p.bdcodemp AND r1.bdreferencia <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
           (SELECT MIN(r2.bdreferencia) FROM vef_int_tsped_pis_cofins r2 WHERE r2.bdcodemp = p.bdcodemp)
       ) AS "BDREFERENCIA"
FROM vef_int_tsped_pis_cofins p
GROUP BY p.bdcodemp
) c
INNER JOIN vef_int_tsped_pis_cofins i ON i.bdcodemp = c.bdcodemp AND i.bdreferencia = c.bdreferencia
LEFT OUTER JOIN VEF_BASE_TTABCRITESCRIT t ON (t.bdcodcrit = i.bdcodcrit);

--21893 - ELIZEU - ControlMemory traz desordenado, e partimos pra views com variáveis de sessão "USER_SESSION"
CREATE OR ALTER VIEW VW_EXP_SPED_CONTRIBUICOES_SAI(
    BDCODMATRIZ,
    BDCODEMP,
    BDCNPJEMP,
    BDCHAVE,
    BDIND_OPER,
    BDEMITENTE,
    BDCODTER,
    BDESPECIE,
    BDMODELO,
    BDMODELOSTR,
    BDCODSITNF,
    BDSERIE,
    BDNUMDOCINI,
    BDNUMDOCFIM,
    BDCHAVENFE,
    BDDATAEMISSAO,
    BDVALORNOTA,
    BDCONDPGTO,
    BDINDFRETE,
    BDVLRFRETE,
    BDVLRSEGURO,
    BDVLROUTDESP,
    BDORDEM,
    BDCODNAT,
    BDSUBSERIE,
    BDVLRCONTAB,
    BDBASEICMS,
    BDVLRICMS,
    BDBASEST,
    BDVLRST,
    BDVLRIPI,
    BDVLRICMSPROD,
    BDVLRIPIPROD,
    BDVLRSTPROD,
    BDAPEUNIMED,
    BDDESCUNIMED,
    BDDESCPROD,
    BDCODSAIDA,
    BDCSTICMS,
    BDCODEXPCSTIPI,
    BDNATREC,
    BDCODCLAENETEL,
    BDINDREC,
    BDCODPROD,
    BDCODCSTICMS,
    BDCODCSTIPI,
    BDCODFATCON,
    BDMOVFISICO,
    BDQTDITEM,
    BDVLRITEM,
    BDVLRDESC,
    BDVLRDESPACESSORIA,
    BDREDBCICMS,
    BDBCICMS,
    BDBCPIS,
    BDBCST,
    BDBCIPI,
    BDBCCOFINS,
    BDBCISSQN,
    BDALIQICMS,
    BDALIQPIS,
    BDALIQST,
    BDALIQIPI,
    BDALIQCOFINS,
    BDALIQISSQN,
    BDVLRPIS,
    BDVLRCOFINS,
    BDVLRISSQN,
    BDVLRFRETEPROD,
    BDCODNATRECPROD,
    BDVLRPISPROD,
    BDVLRCOFINSPROD,
    BDVLRTOTPISPROD,
    BDVLRTOTCOFINSPROD,
    BDQTDEPROD,
    BDVLRTOTPIS,
    BDVLRTOTCOFINS,
    BDVLRABATNT,
    BDVLRTOTPISST,
    BDVLRTOTCOFINSST,
    BDDESCONTO,
    BDCODINFCOM,
    BDDESCINFCOM,
    BDCSTCOF,
    BDCSTPIS,
    BDISENTASICMS,
    BDOUTRASICMS,
    BDCGCTER,
    BDREFEMP,
    BDAPELIDOTER,
    BDNOMETER,
    BDLOGRTER,
    BDENDTER,
    BDNUMTER,
    BDCOMPTER,
    BDCEPTER,
    BDBAITER,
    BDDDDTER,
    BDFONETER,
    BDFAXTER,
    BDEMAILTER,
    BDIETER,
    BDDATACADTER,
    BDIMTER,
    BDPRURALTER,
    BDENQSIMPLESFEDTER,
    BDINSCSUFRAMATER,
    BDCODGPS,
    BDCODCID,
    BDCODPAIS,
    BDDDDFAXTER,
    BDNOMCID,
    BDSIGLAUF,
    BDCODSPED,
    BDCODTENSAO,
    BDORDEMINFCOM,
    BDCODCONS,
    BDVLRCONSFOR,
    BDVLRCOBTER,
    BDVLRDESPACE,
    BDTIPOLIGACAO,
    BDVL_BC_PIS,
    BDALIQ_PIS,
    BDVL_BC_COF,
    BDALIQ_COF,
    BDVLRPISD200,
    BDVLRCOFINSD200,
    BDVL_BC_PISD200,
    BDALIQ_PISD200,
    BDVL_BC_COFD200,
    BDALIQ_COFD200,
    BDCSTCOFD200,
    BDCSTPISD200,
    BDNATRECD200,
    BDNATRECD600,
    BDCODEXPTPREC,
    BDVLRCOBTERCD600,
    BDVLROUTDESPD600,
    BDVLRPISD600,
    BDVLRCOFINSD600,
    BDCODINFCOMD600,
    BDDESCINFCOMD600,
    BDALIQ_PISD600,
    BDCSTPISD600,
    BDVL_BC_PISD600,
    BDCSTCOFD600,
    BDVL_BC_COFD600,
    BDALIQ_COFD600,
    BDCODPAISTER,
    BDCODPLAPADRAO,
    BDORDEMPRO,
    BDCODCTA,
    BDDESCONTONOTA,
    BDCODCSTPIS,
    BDCODCSTCOF,
    BDCREDITOREF,
    BDCREDITOPLAPADRAOREF,
    BDCREDITO,
    BDANOCREDITO,
    BDCTALON,
    BDANOEMISSAO,
    BDCODTPLA,
    BDORDEMINDORIG,
    BDNUMPROC)
AS
SELECT Coalesce(a.BDCODEMPSCP,a.bdcodmatriz),Coalesce(a.BDCODEMPSCP,a.bdemp) bdcodemp, a.bdcnpjemp, a.bdchave, a.BDIND_OPER, a.bdemitente, a.bdter bdcodter, a.bdespecie, a.bdmodelo, a.bdmodelostr,
      a.BDCODSITNF, a.bdserie, a.bdnumdocini, a.bdnumdocfim, 
      a.bdchavenfe, a.bddataemissao, a.bdvalornota, a.bdcondpgto,a.BDINDFRETE,a.BDVLRFRETE,a.BDVLRSEGURO,a.BDVLROUTDESP,a.bdordem, a.bdcodnat, a.bdsubserie, a.BDVLRCONTAB, 
      a.bdbaseicms, a.bdvlricms, a.bdbasest, a.bdvlrst,a.bdvlripi,A.BDVLRICMSPROD,A.BDVLRIPIPROD,A.BDVLRSTPROD, 
      UM.BDAPEUNIMED, UM.BDDESCUNIMED, PRO.BDDESCPROD, PRO.BDCODSAIDA, CSTICMS.BDCSTICMS, NULL BDCODEXPCSTIPI, 
      NATREC.BDNATREC, D601_D605.BDCODCLAENETEL, D601_D605.BDINDREC, 
      A.BDCODPROD,  A.BDCODCSTICMS, A.BDCODCSTIPI, 
      A.BDCODFATCON, A.BDMOVFISICO, A.BDQTDITEM, A.BDVLRITEM,
      A.BDVLRDESC, A.BDVLRDESPACESSORIA, A.BDREDBCICMS, A.BDBCICMS, A.BDBCPIS, 
      A.BDBCST, A.BDBCIPI, A.BDBCCOFINS, A.BDBCISSQN, A.BDALIQICMS, A.BDALIQPIS, 
      A.BDALIQST, A.BDALIQIPI, A.BDALIQCOFINS, A.BDALIQISSQN,
      A.BDVLRPIS,  A.BDVLRCOFINS, A.BDVLRISSQN,
      A.BDVLRFRETEPROD,A.BDCODNATRECPROD,A.BDVLRPISPROD,A.BDVLRCOFINSPROD , 
      A.BDVLRTOTPISPROD,A.BDVLRTOTCOFINSPROD, A.BDQTDEPROD
      ,
      CASE WHEN (A.BDVLRTOTPIS = 0 OR A.BDVLRTOTPIS IS NULL) THEN 
        A.BDVLRTOTPISPROD 
      ELSE 
        A.BDVLRTOTPIS END BDVLRTOTPIS, 
      CASE WHEN (A.BDVLRTOTCOFINS = 0 OR A.BDVLRTOTCOFINS IS NULL) THEN 
        A.BDVLRTOTCOFINSPROD 
      ELSE 
        A.BDVLRTOTCOFINS END BDVLRTOTCOFINS, 
       A.BDVLRABATNT, a.BDVLRTOTPISST, a.BDVLRTOTCOFINSST, a.BDDESCONTO,a.bdcodinfcom, a.BDDESCINFCOM, a.bdcstcof, a.bdcstpis,
      a.bdisentasicms, a.bdoutrasicms, A.BDCGCTER, A.BDREFEMP, A.BDAPELIDOTER, A.BDNOMETER, A.BDLOGRTER, A.BDENDTER,A.BDNUMTER, A.BDCOMPTER, 
      A.BDCEPTER, A.BDBAITER,A.BDDDDTER, A.BDFONETER, A.BDFAXTER,A.BDEMAILTER, A.BDIETER, A.BDDATACADTER, A.BDIMTER,A.BDPRURALTER, A.BDENQSIMPLESFEDTER, 
      A.BDINSCSUFRAMATER,A.BDCODGPS, A.BDCODCID, A.BDCODPAIS, A.BDDDDFAXTER,a.bdnomcid, a.bdsiglauf, a.bdcodsped, 
      A.BDCODTENSAO, A.BDORDEMINFCOM, a.bdcodcons, A.BDVLRCONSFOR, A.BDVLRCOBTER, A.BDVLRDESPACE, A.BDTIPOLIGACAO, 
      COALESCE(A.BDVL_BC_PIS,0) BDVL_BC_PIS, COALESCE(A.BDALIQ_PIS,0) BDALIQ_PIS,
      COALESCE(A.BDVL_BC_COF,0) BDVL_BC_COF, COALESCE(A.BDALIQ_COF,0) BDALIQ_COF,
      COALESCE(A.BDVLRPISd200,0) BDVLRPISd200, COALESCE(A.BDVLRCOFINSd200,0) BDVLRCOFINSd200, COALESCE(A.BDVL_BC_PISd200,0) BDVL_BC_PISd200, 
      COALESCE(a.BDALIQ_PISd200,0) BDALIQ_PISd200, COALESCE(a.BDVL_BC_COFd200,0) BDVL_BC_COFd200, COALESCE(a.BDALIQ_COFd200,0) BDALIQ_COFd200, 
      a.bdcstcofd200, a.bdcstpisd200, a.BDNATRECd200, a.BDNATRECd600, a.BDCODEXPTPREC, 
      a.BDVLRCOBTERCD600, a.BDVLROUTDESPD600, a.BDVLRPISD600, a.BDVLRCOFINSD600,
      a.bdcodinfcomD600, a.BDDESCINFCOMD600, a.BDALIQ_PISD600, a.bdcstpisD600, a.BDVL_BC_PISD600, 
      a.bdcstcofD600, a.BDVL_BC_COFD600, a.BDALIQ_COFD600, a.BDCODPAISTER,  A.bdcodplapadrao,
      A.BDORDEMPRO, a.bdcodcta, a.bddescontonota, A.BDCODCSTPIS, A.BDCODCSTCOF, A.bdcreditoREF, A.BDCREDITOPLAPADRAOREF, A.BDCREDITO, A.BDANOCREDITO,
      A.BDCTALON, EXTRACT(YEAR FROM A.BDDATAEMISSAO) BDANOEMISSAO, A.BDCODTPLA, RE.BDORDEMINDORIG, RE.BDNUMPROC

 FROM ( 
SELECT 
      COALESCE(emp.bdcodmatriz,mov.bdcodemp) bdcodmatriz, mov.bdcodemp bdemp, emp.bdcnpjemp, mov.bdchave, 1 BDIND_OPER, mov.bdemitente, mov.bdcodter bdter, mov.bdespecie, mov.bdmodelo, modlan.bdmodelostr,
      mov.BDCODSITNF, mov.bdserie, mov.bdnumdocini, mov.bdnumdocfim, 
      mov.bdchavenfe, mov.bddataemissao, mov.bdvalornota, mov.bdcondpgto,tabifc100.BDCODEXPFRETE BDINDFRETE,c100.BDVLRFRETE,c100.BDVLRSEGURO,c100.BDVLROUTDESP,mov.bdordem, mov.bdcodnat, mov.bdsubserie, mov.BDVLRCONTAB, 
      mov.bdbaseicms, mov.bdvlricms, mov.bdbasest, mov.bdvlrst,mov.bdvlripi,MOV.BDVLRICMSPROD,MOV.BDVLRIPIPROD,MOV.BDVLRSTPROD, 
      mov.BDCODPROD,  mov.BDCODCSTICMS, mov.BDCODCSTIPI, 
      mov.BDCODFATCON, mov.BDMOVFISICO, mov.BDQTDITEM, mov.BDVLRITEM,
      mov.BDVLRDESC, mov.BDVLRDESPACESSORIA, mov.BDREDBCICMS, mov.BDBCICMS, mov.BDBCPIS, 
      mov.BDBCST, mov.BDBCIPI, mov.BDBCCOFINS, mov.BDBCISSQN, mov.BDALIQICMS, mov.BDALIQPIS, 
      mov.BDALIQST, mov.BDALIQIPI, mov.BDALIQCOFINS, mov.BDALIQISSQN, 
      mov.BDVLRPISPROD, mov.BDVLRCOFINSPROD, mov.BDVLRISSQN, mov.BDVLRFRETEPROD ,mov.BDCODNATRECPROD, 
      MOV.BDORDEMPRO, MOV.BDCODEMPSCP,
      (SELECT SUM(CAST(movpro.BDVLRPIS AS NUMERIC(15,2)))
      FROM vef_emp_tmovprosai movpro 
      WHERE (mov.bdcodemp = movpro.bdcodemp AND mov.bdchave = movpro.bdchave)) BDVLRTOTPISPROD, 
      (SELECT SUM(CAST(movpro.BDVLRCOFINS AS NUMERIC(15,2))) 
      FROM vef_emp_tmovprosai movpro 
      WHERE (mov.bdcodemp = movpro.bdcodemp AND mov.bdchave = movpro.bdchave)) BDVLRTOTCOFINSPROD, 
      (SELECT COUNT(movpro.bdCHAVE) BDQTDEPROD 
      FROM vef_emp_tmovprosai movpro 
      WHERE (mov.bdcodemp = movpro.bdcodemp AND mov.bdchave = movpro.bdchave)) AS BDQTDEPROD, 
      ((c100.BDVLRTOTPIS*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRTOTPIS,
      ((c100.BDVLRTOTCOFINS*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRTOTCOFINS, ((C100.BDVLRABATNT*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRABATNT,
      ((c100.BDVLRTOTPISST*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRTOTPISST, ((c100.BDVLRTOTCOFINSST*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRTOTCOFINSST, mov.BDDESCONTO,
      cadinf.bdcodinfcom, cadinf.BDDESCINFCOM, cstcof.bdcstcof, cstpis.bdcstpis, mov.bdisentasicms, mov.bdoutrasicms, 
      TER.BDCODTER, TER.BDCGCTER, TER.BDREFEMP, TER.BDAPELIDOTER, TER.BDNOMETER, TER.BDLOGRTER, TER.BDENDTER, 
      TER.BDNUMTER, TER.BDCOMPTER, TER.BDCEPTER, TER.BDBAITER,TER.BDDDDTER, TER.BDFONETER, TER.BDFAXTER, 
      TER.BDEMAILTER, TER.BDIETER, TER.BDDATACADTER, TER.BDIMTER,TER.BDPRURALTER, TER.BDENQSIMPLESFEDTER, TER.BDINSCSUFRAMATER, 
      TER.BDCODGPS, TER.BDCODCID, TER.BDCODPAIS, TER.BDDDDFAXTER,cid.bdnomcid, uf.bdsiglauf, paister.bdcodsped, 
      c500.BDCODTENSAO, c500.BDORDEMINFCOM, codcons.bdcodcons, c500.BDVLRCONSFOR, c500.BDVLRCOBTER, c500.BDVLRDESPACE,
      COALESCE(c500.BDVLRPIS, 0) BDVLRPIS, COALESCE(c500.BDVLRCOFINS, 0) BDVLRCOFINS, c500.BDTIPOLIGACAO,
      c500.BDCODCSTPIS BDCODCSTPISC500, COALESCE(c500.BDVL_BC_PIS, 0) BDVL_BC_PIS, c500.BDALIQ_PIS, c500.BDCODCSTCOF BDCODCSTCOFC500, --Larissa - 06/05/2021 - Alterado o campo BDVL_BC_PIS, BDVL_BC_COF, BDVLRPIS e BDVLRCOFINS- Sped Contribui????es - C500 mais de uma CFOP #149987
      COALESCE(c500.BDVL_BC_COF,0) BDVL_BC_COF, c500.BDALIQ_COF, c500.BDCODNATREC BDCODNATRECC500,
      ((d200.BDVLRPIS*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRPISd200, ((d200.BDVLRCOFINS*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRCOFINSd200,
      ((d200.BDVL_BC_PIS*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVL_BC_PISd200, d200.BDALIQ_PIS BDALIQ_PISd200,
      ((d200.BDVL_BC_COF*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVL_BC_COFd200, d200.BDALIQ_COF BDALIQ_COFd200,
      cstcofd200.bdcstcof bdcstcofd200, cstpisd200.bdcstpis bdcstpisd200, natrecd200.BDNATREC BDNATRECd200, natrecd600.BDNATREC BDNATRECd600, TPRECD600.BDCODEXPTPREC, 
      D600.BDVLRCOBTERC BDVLRCOBTERCD600, D600.BDVLROUTDESP BDVLROUTDESPD600, D600.BDVLRPIS BDVLRPISD600, D600.BDVLRCOFINS BDVLRCOFINSD600, D600.BDCODCLAENETEL, 
      cadinfD600.bdcodinfcom bdcodinfcomD600, cadinfD600.BDDESCINFCOM BDDESCINFCOMD600, D600.BDALIQ_PIS BDALIQ_PISD600, cstpisD600.bdcstpis bdcstpisD600, D600.BDVL_BC_PIS BDVL_BC_PISD600, 
      cstcofD600.bdcstcof bdcstcofD600, D600.BDVL_BC_COF BDVL_BC_COFD600, D600.BDALIQ_COF BDALIQ_COFD600, paisTer.BDCODPAIS AS BDCODPAISTER, mov.bdcodcta, mov.bddescontonota 
      , MOV.BDCODCSTCOF, MOV.BDCODCSTPIS, MOV.BDCREDITOREF, MOV.BDCREDITOPLAPADRAOREF, MOV.BDCREDITO, MOV.BDANOCREDITO, mov.bdcodplapadrao, MOV.BDCTALON, MOV.BDCODTPLA
      FROM ( 
            SELECT mov.*,MOVPRO.BDORDEMPRO, MOVPRO.BDCODCTA, 
                         MOVPRO.BDCODPROD, MOVPRO.BDCODCSTCOF, MOVPRO.BDCODCSTICMS, MOVPRO.BDCODCSTPIS, MOVPRO.BDCODCSTIPI, 
                         MOVPRO.BDCODFATCON, MOVPRO.BDMOVFISICO, MOVPRO.BDQTDITEM, MOVPRO.BDVLRITEM,
                         MOVPRO.BDVLRDESC, MOVPRO.BDVLRDESPACESSORIA, MOVPRO.BDREDBCICMS, MOVPRO.BDBCICMS, MOVPRO.BDBCPIS, 
                         MOVPRO.BDBCST, MOVPRO.BDBCIPI, MOVPRO.BDBCCOFINS, MOVPRO.BDBCISSQN, MOVPRO.BDALIQICMS, MOVPRO.BDALIQPIS, 
                         MOVPRO.BDALIQST, MOVPRO.BDALIQIPI, MOVPRO.BDALIQCOFINS, MOVPRO.BDALIQISSQN, MOVPRO.BDVLRICMS BDVLRICMSPROD, 
                         MOVPRO.BDVLRPIS BDVLRPISPROD, MOVPRO.BDVLRST BDVLRSTPROD, MOVPRO.BDVLRIPI BDVLRIPIPROD, MOVPRO.BDVLRCOFINS BDVLRCOFINSPROD, 
                         MOVPRO.BDVLRISSQN, MOVPRO.BDVLRFRETE BDVLRFRETEPROD,MOVPRO.BDCODNATREC BDCODNATRECPROD,
                         
                         COALESCE(MOVPRO.BDCODPLAPADRAO, IIF((d100.bdCODCTA IS NOT NULL OR c500.bdCODTPLA IS NOT NULL OR d500.bdCODCTA IS NOT NULL), ref.bdCODPLAPADRAO, NULL), COALESCE(lan.BDCODPLAPADRAO, LANRAT.BDCODPLAPADRAO), ref.bdCODPLAPADRAO) bdCODPLAPADRAO,
                         COALESCE(cclep.bdcodtplaref, ccderatp.bdcodtplaref) bdcreditoref,
                         COALESCE(ccl.bdCODTPLA,cclrat.bdCODTPLA,d100.bdCODCTA,d500.bdCODCTA) AS bdCREDITO,
                         COALESCE(COALESCE(ccle.bdano, ccderat.bdano), CAST(SUBSTRING(mov.bdreflan FROM 1 FOR 4) AS INTEGER)) bdanocredito,
                         COALESCE(cclep.BDCODPLAPADRAOREF, ccderatp.BDCODPLAPADRAOREF) bdcreditoplapadraoref, COALESCE(CCL.BDCTALON, CCLRAT.BDCTALON) BDCTALON, COALESCE(CCL.BDCODTPLA, CCLRAT.BDCODTPLA) AS BDCODTPLA
            FROM ( 
                  SELECT movaux.bdcodemp, movaux.bdreflan, movaux.bdchave, movaux.bdemitente, movaux.bdcodter, movaux.bdmodelo, movaux.BDCODSITNF, movaux.bdespecie, movaux.bdsubserie, movaux.bdserie, movaux.bdnumdocini, movaux.bdnumdocfim, 
                  movaux.bdchavenfe, movaux.bddataemissao, movaux.bdvalornota, movaux.bdcondpgto, movaux.BDDESCONTONOTA AS BDDESCONTOnota, 
                  itens.bdordem, itens.bdcodnat, itens.BDVLRCONTAB, itens.bdbaseicms, itens.bdvlricms, itens.bdbasest, itens.bdvlrst, itens.bdvlripi, itens.bdisentasicms, itens.bdoutrasicms, 
                  ITENS.BDCODOBS,ITENS.BDBASEIPI, ITENS.BDISENTASIPI, 
                  ITENS.BDOUTRASIPI, ITENS.BDIMPEXCLUIDAS, ITENS.BDOUTROSIMP,ITENS.BDDESCONTO, 
                  ITENS.BDICMSFRETESAI, ITENS.BDPREFIXONAT, ITENS.BDOBSERVACAO, EMPSCP.BDCODEMPSCP
                  FROM (SELECT movaux.bdcodemp, movaux.BDDESCONTONOTA, movaux.bdchave, movaux.bdemitente, movaux.bdcodter, movaux.bdespecie, movaux.bdmodelo, movaux.BDCODSITNF, movaux.bdserie, movaux.bdsubserie, movaux.bdnumdocini, MOVAUX.bdnumdocfim, 
                        movaux.bdchavenfe, movaux.bddataemissao, movaux.bdreflan, movaux.bddatasaida, movaux.bdvalornota, movaux.bdcondpgto 
                        FROM vef_emp_tmovsai movaux 
                        JOIN VW_INT_SPEDPISCOFINS_REF empaux ON (movaux.bdcodemp = empaux.bdcodemp AND empaux.bdsomenteblocop <> 'TRUE')
                        WHERE movaux.BDCODEMP = (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_CODEMP') FROM RDB$DATABASE)
                        AND movaux.bddataemissao BETWEEN (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_DT_INI') FROM RDB$DATABASE) AND (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_DT_FIM') FROM RDB$DATABASE)
                        AND MOVAUX.BDMODELO IN(2, 6, 28, 29, 7, 8, 9, 10, 11, 26, 27, 57, 67, 800, 21, 22, 63, 66, 62, 75)
                        AND EXISTS(SELECT *
                                   FROM VEF_EMP_TMOVSAIITENS i
                                   JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT AND ((nat.bdNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.bdNAOEXPEFDCONT)) = TRIM('FALSE'))) )
                                   WHERE i.bdCODEMP = movaux.bdCODEMP
                                     AND i.bdCHAVE  = movaux.bdCHAVE)
                        ) MOVAUX
                  JOIN VEF_EMP_TMOVSAIITENS itens ON (itens.BDCODEMP = movaux.BDCODEMP AND itens.BDCHAVE = movaux.BDCHAVE) 
                  JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = itens.BDCODNAT AND ((nat.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.BDNAOEXPEFDCONT)) <> TRIM('TRUE'))) ) 
                  JOIN VW_INT_SPEDPISCOFINS_REF empaux ON (movaux.bdcodemp = empaux.bdcodemp AND empaux.bdsomenteblocop <> 'TRUE')
                  LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON ((select RDB$GET_CONTEXT('USER_SESSION', 'W_EXPORTAPORSCP') from RDB$DATABASE) = 'TRUE') and (EMPSCP.BDCODEMP = itens.BDCODEMP) AND (EMPSCP.BDREFEMP = itens.BDREFSOC) AND (EMPSCP.BDCODSCP = itens.BDCODSCP)
                  ) mov 
                  LEFT OUTER JOIN VW_TEMPRESAS_REF ref ON (ref.bdCODEMP = mov.bdCODEMP)
                  LEFT OUTER JOIN VEF_EMP_TD100SAI d100 ON (d100.bdCODEMP = mov.bdCODEMP AND d100.bdCHAVE = mov.BDCHAVE)
                  LEFT OUTER JOIN VEF_EMP_TC500SAI c500 ON (c500.bdCODEMP = mov.bdCODEMP AND c500.bdCHAVE = mov.BDCHAVE)
                  LEFT OUTER JOIN VEF_EMP_TD500SAI d500 ON (d500.bdCODEMP = mov.bdCODEMP AND d500.bdCHAVE = mov.BDCHAVE)
                  LEFT OUTER JOIN VEF_EMP_TMOVPROSAI MOVPRO ON (MOVPRO.BDCODEMP = mov.BDCODEMP AND MOVPRO.BDCHAVE = mov.BDCHAVE AND MOVPRO.BDORDEM = mov.BDORDEM)
                  LEFT OUTER JOIN  (SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) BDCHAVE, BDCODEMPSUC FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM,BDCODEMPSUC) tol
                       ON (tol.bdcodemp = mov.bdcodemp AND tol.bdchavesai = mov.bdchave AND tol.bdordem = mov.bdordem) 
                  LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.BDCODEMP = tol.BDCODEMPSUC AND lan.bdchave = tol.BDCHAVE)
                  LEFT OUTER JOIN PLANOS_TPLA ccl ON (COALESCE(movpro.bdCODPLAPADRAO,lan.bdCODPLAPADRAO,d100.bdCODPLAPADRAO,c500.bdCODPLAPADRAO,d500.bdCODPLAPADRAO) = ccl.bdCODPLAPADRAO AND COALESCE(movpro.bdCODTPLA,lan.bdCREDITO,d100.bdCODTPLA,c500.bdCODTPLA,d500.bdCODTPLA) = ccl.bdCODTPLA)
                  LEFT OUTER JOIN PLANOS_TPLA_ECF ccle ON (ccle.bdcodplapadraoref = (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_CODPLAPADRAOREF') FROM RDB$DATABASE) AND
                                                           ccle.bdano = (SELECT FIRST 1 BDANO 
                                                                         FROM PLANOS_TPLA_ECF 
                                                                         WHERE CAST(BDANO || '01' AS INTEGER) <= mov.bdreflan AND 
                                                                           BDCODTPLAREF IS NOT NULL AND 
                                                                           CCLE.BDCODPLAPADRAO = BDCODPLAPADRAO AND 
                                                                           CCLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF AND 
                                                                           CCLE.BDCODTPLA = BDCODTPLA 
                                                                         ORDER BY BDANO DESC 
                                                                         ) AND 
                                                           ccle.bdcodplapadrao = ccl.bdcodplapadrao AND ccle.bdcodtpla = ccl.bdcodtpla) 
                  LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO cclep ON (ccle.BDCODPLAPADRAOREF = cclep.BDCODPLAPADRAOREF AND CCLE.BDCODTPLAREF = cclep.BDCODTPLAREF) 
                  LEFT OUTER JOIN  (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) BDCHAVE,BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM,BDCODEMPSUC) tolrat
                       ON (tolrat.bdcodemp = mov.bdcodemp AND tolrat.bdchavelan = mov.bdchave AND tolrat.bdordem = mov.bdordem) 
                  LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat ON (lanrat.BDCODEMP = tolrat.BDCODEMPSUC AND lanrat.bdchave = tolrat.BDCHAVE)
                  LEFT OUTER JOIN planos_tpla cclrat ON (COALESCE(MOVPRO.BDCODPLAPADRAO,lanrat.BDCODPLAPADRAO) = cclrat.bdcodplapadrao AND COALESCE(MOVPRO.BDCODTPLA,lanrat.bdcredito) = cclrat.bdcodtpla) 
                  LEFT OUTER JOIN PLANOS_TPLA_ECF ccderat ON  (ccderat.bdcodplapadraoref = (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_CODPLAPADRAOREF') FROM RDB$DATABASE) AND
                                                               ccderat.bdano = (SELECT FIRST 1 BDANO 
                                                                                FROM PLANOS_TPLA_ECF 
                                                                                WHERE CAST(BDANO || '01' AS INTEGER) <= lanrat.bdreferencia AND 
                                                                                  BDCODTPLAREF IS NOT NULL AND 
                                                                                  ccderat.BDCODPLAPADRAO = BDCODPLAPADRAO AND 
                                                                                  ccderat.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF AND 
                                                                                  ccderat.BDCODTPLA = BDCODTPLA 
                                                                                ORDER BY BDANO DESC 
                                                                                ) AND 
                                                               ccderat.bdcodplapadrao = cclrat.bdcodplapadrao AND ccderat.bdcodtpla = cclrat.bdcodtpla) 
                  LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO ccderatp ON (CCDERAT.BDCODPLAPADRAOREF = ccderatp.BDCODPLAPADRAOREF AND CCDERAT.BDCODTPLAREF = ccderatp.BDCODTPLAREF) 
 ) mov
     JOIN tempresas emp ON (MOV.BDCODEMP = emp.bdcodemp)
     LEFT OUTER JOIN VEF_EMP_TC100SAI c100 ON (mov.bdcodemp = c100.bdcodemp AND mov.bdchave = c100.bdchave) 
     LEFT OUTER JOIN VEF_EMP_TC500SAI c500 ON (mov.bdcodemp = c500.bdcodemp AND mov.bdchave = c500.bdchave) 
     LEFT OUTER JOIN VEF_BASE_TTABCODCONS codcons ON (c500.BDORDEMCONS = codcons.BDORDEMCONS) 
     LEFT OUTER JOIN VEF_BASE_TCADINFCOM cadinf ON (c500.bdordeminfcom = cadinf.bdordeminfcom) 
     LEFT OUTER JOIN vef_base_ttabcstcof cstcof ON (MOV.bdcodcstCOF = cstcof.bdcodcstcof) 
     LEFT OUTER JOIN vef_base_ttabcstpis cstpis ON (MOV.bdcodcstpis = cstpis.bdcodcstpis)
     JOIN TTERCEIRO_REF TER on (TER.BDCODTER = MOV.BDCODTER and TER.BDREFEMP = coalesce((select max(RF2.BDREFEMP)
                                                                                                     from TTERCEIRO_REF RF2
                                                                                                     where RF2.BDCODTER = TER.BDCODTER and
                                                                                                           RF2.BDREFEMP <= (select BDDATA
                                                                                 from SP_PARSE_DATE(cast((select RDB$GET_CONTEXT('USER_SESSION', 'W_DT_INI')
                                                                                                                                         from RDB$DATABASE) as date), 'YYYYMM'))), 
                                                                                         (select min(RF2.BDREFEMP)
                                                                                                                                 from TTERCEIRO_REF RF2
                                                                                                                                  where RF2.BDCODTER = TER.BDCODTER))) 


     LEFT OUTER JOIN tcidade CID ON (TER.BDCODCID = CID.bdCODCID) 
     LEFT OUTER JOIN tuf UF ON (CID.BDCODUF = UF.bdCODUF) 
     LEFT OUTER JOIN VEF_EMP_TD100SAI d200 ON (mov.bdcodemp = d200.bdcodemp AND mov.bdchave = d200.bdchave) 
     LEFT OUTER JOIN vef_base_ttabcstcof cstcofd200 ON (d200.bdcodcstCOF = cstcofd200.bdcodcstcof) 
     LEFT OUTER JOIN vef_base_ttabcstpis cstpisd200 ON (d200.bdcodcstpis = cstpisd200.bdcodcstpis) 
     LEFT OUTER JOIN VEF_BASE_TTAB_NATREC natrecd200 ON (d200.BDCODNATREC = natrecd200.BDCODNATREC) 
     LEFT OUTER JOIN VEF_EMP_TD500SAI D600 ON (mov.bdcodemp = D600.bdcodemp AND mov.bdchave = D600.bdchave) 
     LEFT OUTER JOIN VEF_BASE_TTAB_NATREC natrecd600 ON (d600.BDCODNATREC = natrecd600.BDCODNATREC) 
     LEFT OUTER JOIN VEF_BASE_TTABTPREC TPRECD600 ON (d600.BDCODTPREC = TPRECD600.BDCODTPREC) 
     LEFT OUTER JOIN VEF_BASE_TCADINFCOM cadinfd600 ON (cadinfd600.bdordeminfcom = d600.bdordeminfcom) 
     LEFT OUTER JOIN vef_base_ttabcstpis cstpisd600 ON (d600.bdcodcstpis = cstpisd600.bdcodcstpis) 
     LEFT OUTER JOIN vef_base_ttabcstcof cstcofd600 ON (d600.bdcodcstCOF = cstcofd600.bdcodcstcof) 
     LEFT OUTER JOIN VEF_BASE_TTABINFRETE tabifc100 ON (c100.BDINDFRETE = tabifc100.BDORDEMFRETE) 
     LEFT OUTER JOIN vef_base_ttabmodelolan modlan ON (modlan.bdmodelo = mov.bdmodelo) 
     LEFT OUTER JOIN tpais paisTer ON (paisTer.BDCODPAIS = ter.bdCODPAIS) 
   )A 
    LEFT OUTER JOIN TCADPRO_VINC PRO ON (A.bdemp = PRO.BDCODEMP AND A.BDCODPROD = PRO.BDCODPROD) 
    LEFT OUTER JOIN TUNIDADEMEDIDA UM ON (PRO.BDCODUNIMED = UM.BDCODUNIMED) 
    LEFT OUTER JOIN VEF_BASE_TTABCSTICMS CSTICMS ON (CSTICMS.BDCODCSTICMS = A.BDCODCSTICMS) 
    LEFT OUTER JOIN VEF_BASE_TTABCSTIPI CSTIPI ON (CSTIPI.BDCODCSTIPI = A.BDCODCSTIPI) 
    LEFT OUTER JOIN VEF_BASE_TTAB_NATREC NATREC ON (NATREC.BDCODNATREC = A.BDCODNATRECPROD) 
    LEFT OUTER JOIN VEF_EMP_TENETELE D601_D605 ON (A.bdemp = D601_D605.BDCODEMP AND A.BDCHAVE = D601_D605.BDCHAVE AND A.BDORDEM = D601_D605.BDORDEM AND A.BDORDEMPRO = D601_D605.BDORDEMPRO)
    LEFT OUTER JOIN (select distinct *  from SP_RET_REF_1010_1020_EXPORT
                                        ('(mov.BDCODEMP in ('||(SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_CODEMP') FROM RDB$DATABASE)||')) and',
                                        null,
                                        (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_DT_INI') FROM RDB$DATABASE),
                                        (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_DT_FIM') FROM RDB$DATABASE),
                                         'C609'))
    RE ON (RE.BDCODEMP = A.bdemp AND RE.BDCHAVE = A.bdchave)

  ORDER BY  A.bdcodmatriz, A.bdemp, A.bdchave, A.bdordem, A.BDORDEMPRO;

-- 15128 Denicio 28/07/2016 - Nova view para o cálculo das provisões 
CREATE OR ALTER VIEW VW_UNION_FC_TOMADOR(
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDREFCOMP,
    BDDATABAIXAFN,
    BDBFGTSFN,
    BDFGTSFN,
    BDFGTSCSFN,
    BDBFGTS13FN,
    BDFGTS13FN,
    BDFGTS13CSFN,
    BDMAIORREMFN,
    BDBINSSFN,
    BDALIQINSSFN,
    BDINSSFN,
    BDBIRRFFN,
    BDALIQIRRFFN,
    BDIRRFFN,
    BDBINSS13FN,
    BDALIQINSS13FN,
    BDINSS13FN,
    BDBIRRF13FN,
    BDALIQIRRF13FN,
    BDIRRF13FN,
    BDBSALFAMFN,
    BDSALFAMFN,
    BDBRAISFN,
    BDSALBASEFN,
    BDDEPFN,
    BDBASEPISFN,
    BDBASEPISFEFN,
    BDBASEPIS13FN,
    BDBSALMATEMPFN,
    BDSALMATEMPFN,
    BDBRATAPOFN,
    BDBRATAPOFEFN,
    BDBRATAPO13FN,
    BDBINSSFEFOLFN,
    BDINSSFEFOLFN,
    BDALIQINSSFEFOLFN,
    BDCREDITFN,
    BDDEBITOFN,
    BDBFGTSFEFN,
    BDFGTSFEFN,
    BDREFFC)
AS
SELECT
  FC.BDCODEMP,
  FC.BDCODCOL,
  FC.BDREFFN,
  FC.BDREFCOMP,
  FC.bddatabaixafc,
  FC.bdbfgtsfc,
  FC.bdfgtsfc,
  FC.bdfgtscsfc,
  FC.bdbfgts13fc,
  FC.bdfgts13fc,
  FC.bdfgts13csfc,
  FC.bdmaiorremfc,
  FC.bdbinssfc,
  FC.bdaliqinssfc,
  FC.bdinssfc,
  FC.bdbirrffc,
  FC.bdaliqirrffc,
  FC.bdirrffc,
  FC.bdbinss13fc,
  FC.bdaliqinss13fc,
  FC.bdinss13fc,
  FC.bdbirrf13fc,
  FC.bdaliqirrf13fc,
  FC.bdirrf13fc,
  FC.bdbsalfamfc,
  FC.bdsalfamfc,
  FC.bdbraisfc,
  FC.bdsalbasefc,
  FC.bddepfc,
  FC.bdbasepisfc,
  FC.bdbasepisfefc,
  FC.bdbasepis13fc,
  FC.bdbsalmatempfc,
  FC.bdsalmatempfc,
  FC.bdbratapofc,
  FC.bdbratapofefc,
  FC.bdbratapo13fc,
  FC.bdbinssfefolfc,
  FC.bdinssfefolfc,
  FC.bdaliqinssfefolfc,
  FC.bdcreditofc,
  FC.bddebitofc,
  FC.bdbfgtsfefc,
  FC.bdfgtsfefc,
  FC.bdreffc
FROM VRHF_EMP_TFOLHACOMP FC

UNION

SELECT
  FCT.BDCODEMP,
  FCT.BDCODCOL,
  FCT.BDREFTOMADOR,
  FCT.BDREFCOMP,
  FCT.bddatabaixafc,
  FCT.bdbfgtsfc,
  FCT.bdfgtsfc,
  FCT.bdfgtscsfc,
  FCT.bdbfgts13fc,
  FCT.bdfgts13fc,
  FCT.bdfgts13csfc,
  FCT.bdmaiorremfc,
  FCT.bdbinssfc,
  FCT.bdaliqinssfc,
  FCT.bdinssfc,
  FCT.bdbirrffc,
  FCT.bdaliqirrffc,
  FCT.bdirrffc,
  FCT.bdbinss13fc,
  FCT.bdaliqinss13fc,
  FCT.bdinss13fc,
  FCT.bdbirrf13fc,
  FCT.bdaliqirrf13fc,
  FCT.bdirrf13fc,
  FCT.bdbsalfamfc,
  FCT.bdsalfamfc,
  FCT.bdbraisfc,
  FCT.bdsalbasefc,
  FCT.bddepfc,
  FCT.bdbasepisfc,
  FCT.bdbasepisfefc,
  FCT.bdbasepis13fc,
  FCT.bdbsalmatempfc,
  FCT.bdsalmatempfc,
  FCT.bdbratapofc,
  FCT.bdbratapofefc,
  FCT.bdbratapo13fc,
  FCT.bdbinssfefolfc,
  FCT.bdinssfefolfc,
  FCT.bdaliqinssfefolfc,
  FCT.bdcreditofc,
  FCT.bddebitofc,
  FCT.bdbfgtsfefc,
  FCT.bdfgtsfefc,
  FCT.bdreffc
FROM VRHF_EMP_TFOLTOMCOMP FCT
;

/* View: VW_UNION_FC_TOMADOR_VERBAS */
CREATE OR ALTER VIEW VW_UNION_FC_TOMADOR_VERBAS(
    BDCODVER,
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDREFCOMP,
    BDREFVFN,
    BDREFAUXVFN,
    BDVALVFN,
    BDIGNREFVFN,
    BDIGNVALVFN,
    BDREFFC)
AS
SELECT
  FC.BDCODVER,
  FC.BDCODEMP,
  FC.BDCODCOL,
  FC.BDREFFN,
  FC.BDREFCOMP,
  FC.bdrefvfc,
  FC.bdrefauxvfc,
  FC.bdvalvfc,
  FC.bdignrefvfc,
  FC.bdignvalvfc,
  FC.bdreffc
FROM VRHF_EMP_TVERBAFC FC

UNION

SELECT
  FCT.BDCODVER,
  FCT.BDCODEMP,
  FCT.BDCODCOL,
  FCT.BDREFTOMADOR,
  FCT.BDREFCOMP,
  FCT.bdrefvfc,
  FCT.bdrefauxvfc,
  FCT.bdvalvfc,
  FCT.bdignrefvfc,
  FCT.bdignvalvfc,
  FCT.bdreffc
FROM vrhf_emp_tverbafctomador FCT
;

CREATE OR ALTER VIEW VW_UNION_FC_TOMADOR_VERBAS_DET(
    BDCODVER,
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDREFFC,
    BDREFVFN,
    BDREFAUXVFN,
    BDVALVFN,
    BDIGNREFVFN,
    BDIGNVALVFN,
    BDORDEMDETALHE)
AS
SELECT
  FC.BDCODVER,
  FC.BDCODEMP,
  FC.BDCODCOL,
  FC.BDREFFN,
  FC.BDREFFC,
  FC.bdrefvfcd,
  FC.bdrefauxvfcd,
  FC.bdvalvfcd,
  FC.bdignrefvfcd,
  FC.bdignvalvfcd,
  FC.bdordemdetalhe
FROM VRHF_EMP_TVERBAFC_DET FC

UNION

SELECT
  FCT.BDCODVER,
  FCT.BDCODEMP,
  FCT.BDCODCOL,
  FCT.BDREFTOMADOR,
  FCT.BDREFFC,
  FCT.bdrefvfctd,
  FCT.bdrefauxvfctd,
  FCT.bdvalvfctd,
  FCT.bdignrefvfctd,
  FCT.bdignvalvfctd,
  FCT.bdordemdetalhe
FROM VRHF_EMP_TVERBAFCT_DET FCT
;

CREATE OR ALTER VIEW VW_VEF_BASE_TEMPCADATV(
    BDCODEMP,
    BDREFEMP,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO)
AS
SELECT
    x.bdcodemp,
    x.bdrefemp,
    x.bdcomercio,
    x.bdindustria,
    x.bdservico
FROM vef_base_tempcadatv x
WHERE X.BDREFEMP =
      (
       SELECT MAX(Y.BDREFEMP)
       FROM VEF_BASE_TEMPCADATV Y
       WHERE Y.BDCODEMP = X.BDCODEMP AND
             Y.BDREFEMP <=
                (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER)
                 FROM rdb$database
                )
      )
;

CREATE OR ALTER VIEW VW_VEF_BASE_TNBS_DADOS_MAXMIN(
    BDCOD_NBS,
    BDREF_DADOS)
AS
select BDCOD_NBS, COALESCE((SELECT FIRST 1 r.BDREF_DADOS FROM VEF_BASE_TNBS_DADOS r
                 WHERE r.BDCOD_NBS = nbsd.BDCOD_NBS AND
                 CAST(r.BDREF_DADOS AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
                 ORDER BY r.BDREF_DADOS DESC),
                 (SELECT FIRST 1 r.BDREF_DADOS FROM VEF_BASE_TNBS_DADOS r
                  WHERE r.BDCOD_NBS = nbsd.BDCOD_NBS
                  ORDER BY r.BDREF_DADOS
                 )
                ) BDREF_DADOS
from VEF_BASE_TNBS_DADOS nbsd
group by BDCOD_NBS, BDREF_DADOS
;

CREATE OR ALTER VIEW VW_VEF_BASE_TNBS_DADOS(
    BDCOD_NBS,
    BDCHAVE_DADOS,
    BDREF_DADOS,
    BDCOD_CCLASSTRIB,
    BDCOD_CST,
    BDREDUCAOIBS_DADOS,
    BDALIQCBS_DADOS,
    BDREDUCAOCBS_DADOS,
    BDINDOP)
AS
select
    nbsd.BDCOD_NBS,
    nbsd.BDCHAVE_DADOS,
    nbsd.BDREF_DADOS,
    nbsd.BDCOD_CCLASSTRIB,
    nbsd.BDCOD_CST,
    nbsd.BDREDUCAOIBS_DADOS,
    nbsd.BDALIQCBS_DADOS,
    nbsd.BDREDUCAOCBS_DADOS,
    nbsd.BDINDOP
from VEF_BASE_TNBS_DADOS nbsd
join VW_VEF_BASE_TNBS_DADOS_MAXMIN mm on (mm.BDCOD_NBS = nbsd.BDCOD_NBS and mm.BDREF_DADOS = nbsd.BDREF_DADOS)
;

/* CREATE OR ALTER VIEW: VW_SN_VERBAS_CALCULOS_RH_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_SN_VERBAS_CALCULOS_RH_REF(
BDCODEMP,
BDCODVER,
BDREF,
BDVALFN,
BDVALFC,
BDVALAD,
BDVALFE,
BDVALAD13,
BDVAL13,
BDVALC13)
 AS 
SELECT bdcodemp,bdcodver,bdreffn bdref,SUM(bdvalvfn) bdvalfn, SUM(bdvalfc) bdvalfc,
                                       SUM(bdvalad) bdvalad, SUM(bdvalfe) bdvalfe,
                                       SUM(bdvalad13) bdvalad13, SUM(bdval13) bdval13,
                                       SUM(bdvalc13) bdvalc13 FROM (

SELECT ter.bdcodemp,ter.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(cter.bddataserv)) AS INTEGER) bdreffn,ter.bdvalor bdvalvfn,0 bdvalfc,0 bdvalad,0 bdvalfe,0 bdvalad13,0 bdval13,0 bdvalc13
FROM vrhf_base_items_calcterc ter, vrhf_base_calc_terc cter
WHERE cter.bdcodter = ter.bdcodter AND cter.bdcodemp = ter.bdcodter AND cter.bdcodserv = ter.bdcodserv
UNION
SELECT fn.bdcodemp,fn.bdcodver,fn.bdreffn,fn.bdvalvfn,0 bdvalfc,0 bdvalad,0 bdvalfe,0 bdvalad13,0 bdval13,0 bdvalc13 FROM vrhf_emp_tverbafn fn
UNION
SELECT fnt.bdcodemp,fnt.bdcodver,fnt.bdreftomador,fnt.bdvalvft,0,0,0,0,0,0 FROM vrhf_emp_tverbatomador fnt
UNION
SELECT fc.bdcodemp,fc.bdcodver,fc.bdrefcomp,0,fc.bdvalvfc,0,0,0,0,0 FROM vrhf_emp_tverbafc fc
UNION
SELECT fct.bdcodemp,fct.bdcodver,fct.bdrefcomp,0,fct.bdvalvfc,0,0,0,0,0 FROM vrhf_emp_tverbafctomador fct
UNION
SELECT ad.bdcodemp,ad.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(ad.bddataad)) AS INTEGER),0,0,ad.bdvalvad,0,0,0,0 FROM vrhf_emp_tverbaad ad
UNION
SELECT fe.bdcodemp,fe.bdcodver, CASE WHEN fer.bdinipergozofe IS NULL THEN fer.bdrefpagabofe
                                     WHEN fer.bdinipergozofe IS NOT NULL THEN CAST((SELECT bdaaaamm FROM aaaamm(fer.bdinipergozofe)) AS INTEGER)
                                END,0,0,0,fe.bdvalvfe,0,0,0 FROM vrhf_emp_tverbafe fe, vrh_emp_tferias fer
       WHERE fer.bdcodemp = fe.bdcodemp AND fer.bdcodcol = fe.bdcodcol AND fer.bdiniperaquisfe = fe.bdiniperaquisfe AND fer.bdcodfe = fe.bdcodfe
UNION
SELECT adt.bdcodemp,adt.bdcodver,adt.bdrefa13,0,0,0,0,adt.bdvalva13,0,0 FROM vrhf_emp_tverbaa13 adt
UNION
SELECT dt.bdcodemp,dt.bdcodver,dt.bdref13,0,0,0,0,0,dt.bdvalv13,0 FROM vrhf_emp_tverba13 dt
UNION
SELECT cdt.bdcodemp,cdt.bdcodver,cdt.bdrefc13,0,0,0,0,0,0,cdt.bdvalvc13 FROM vrhf_emp_tverbac13 cdt
)
GROUP BY bdcodemp,bdcodver,bdreffn
;

CREATE OR ALTER VIEW VW_SN_VERBAS_CALCULOS_RH_PGTO(
BDCODEMP,
BDCODVER,
BDREF,
BDVALFN,
BDVALFC,
BDVALAD,
BDVALFE,
BDVALAD13,
BDVAL13,
BDVALC13)
 AS 
SELECT bdcodemp,bdcodver,bdreffn bdref,SUM(bdvalvfn) bdvalfn, SUM(bdvalfc) bdvalfc,
                                       SUM(bdvalad) bdvalad, SUM(bdvalfe) bdvalfe,
                                       SUM(bdvalad13) bdvalad13, SUM(bdval13) bdval13,
                                       SUM(bdvalc13) bdvalc13 FROM (

SELECT ter.bdcodemp,ter.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) AS INTEGER) bdreffn,ter.bdvalor bdvalvfn,0 bdvalfc,0 bdvalad,0 bdvalfe,0 bdvalad13,0 bdval13,0 bdvalc13
FROM vrhf_base_items_calcterc ter
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (ter.bdcodemp = baixa.bdcodemp AND ter.bdcodter = baixa.bdcodter AND ter.bdcodserv = baixa.bdcodserv AND baixa.bdtipocalc = 1)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT fn.bdcodemp,fn.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) AS INTEGER) bdreffn,
        fn.bdvalvfn,0 bdvalfc,0 bdvalad,0 bdvalfe,0 bdvalad13,0 bdval13,0 bdvalc13 FROM vrhf_emp_tverbafn fn
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (fn.bdcodemp = baixa.bdcodemp AND fn.bdcodcol = baixa.bdcodcol AND fn.bdreffn = baixa.bdreferencia AND baixa.bdtipocalc = 6)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT fnt.bdcodemp,fnt.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) AS INTEGER),fnt.bdvalvft,0,0,0,0,0,0 FROM vrhf_emp_tverbatomador fnt
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (fnt.bdcodemp = baixa.bdcodemp AND fnt.bdcodcol = baixa.bdcodcol AND fnt.bdreftomador = baixa.bdreferencia AND baixa.bdtipocalc = 7)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT fc.bdcodemp,fc.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) AS INTEGER),0,fc.bdvalvfc,0,0,0,0,0 FROM vrhf_emp_tverbafc fc
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (fc.bdcodemp = baixa.bdcodemp AND fc.bdcodcol = baixa.bdcodcol AND fc.bdreffn = baixa.bdreferencia AND fc.bdrefcomp = baixa.bdrefcomp  AND baixa.bdtipocalc = 8)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT fct.bdcodemp,fct.bdcodver,fct.bdrefcomp,0,fct.bdvalvfc,0,0,0,0,0 FROM vrhf_emp_tverbafctomador fct
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (fct.bdcodemp = baixa.bdcodemp AND fct.bdcodcol = baixa.bdcodcol AND fct.bdreftomador = baixa.bdreferencia AND fct.bdrefcomp = baixa.bdrefcomp  AND baixa.bdtipocalc = 9)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT ad.bdcodemp,ad.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) AS INTEGER),0,0,ad.bdvalvad,0,0,0,0 FROM vrhf_emp_tverbaad ad
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (ad.bdcodemp = baixa.bdcodemp AND ad.bdcodcol = baixa.bdcodcol AND ad.bddataad = baixa.bddata AND baixa.bdtipocalc = 4)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT fe.bdcodemp,fe.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) AS INTEGER),0,0,0,fe.bdvalvfe,0,0,0 FROM vrhf_emp_tverbafe fe
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (fe.bdcodemp = baixa.bdcodemp AND fe.bdcodcol = baixa.bdcodcol AND fe.bdiniperaquisfe = baixa.bdiniperaqui AND fe.bdcodfe = baixa.bdcodfer AND baixa.bdtipocalc = 10)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT adt.bdcodemp,adt.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) AS INTEGER),0,0,0,0,adt.bdvalva13,0,0 FROM vrhf_emp_tverbaa13 adt
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (adt.bdcodemp = baixa.bdcodemp AND adt.bdcodcol = baixa.bdcodcol AND adt.bdrefa13 = baixa.bdreferencia AND baixa.bdtipocalc = 3)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT dt.bdcodemp,dt.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto))  AS INTEGER),0,0,0,0,0,dt.bdvalv13,0 FROM vrhf_emp_tverba13 dt
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (dt.bdcodemp = baixa.bdcodemp AND dt.bdcodcol = baixa.bdcodcol AND dt.bdref13 = baixa.bdreferencia AND baixa.bdtipocalc = 2)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT cdt.bdcodemp,cdt.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) AS INTEGER),0,0,0,0,0,0,cdt.bdvalvc13 FROM vrhf_emp_tverbac13 cdt
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (cdt.bdcodemp = baixa.bdcodemp AND cdt.bdcodcol = baixa.bdcodcol AND cdt.bdref13 = baixa.bdreferencia AND cdt.bdrefc13 = baixa.bdrefcomp AND baixa.bdtipocalc = 5)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
)
GROUP BY bdcodemp,bdcodver,bdreffn
;

/* CREATE OR ALTER VIEW: VW_SN_IMPOSTOS_PGTO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_SN_IMPOSTOS_PGTO(
BDCODEMP,
BDCODMATRIZ,
BDCODIMP,
BDREFERENCIA,
BDVALOR,
BDMULTA,
BDJUROS,
BDTOTAL,
BDVALEMPGPS,
BDVALSEGGPS)
 AS 
SELECT bdcodemp,
       BDCODMATRIZ,
       bdcodimp,
       bdreferencia,
       SUM(CASE WHEN ((bdvalempgps <> 0) OR (bdvalseggps <> 0)) THEN
               0
            WHEN (bdcodemp IS NOT NULL) THEN
               COALESCE(bdvalor,0)
       END) bdvalor,
       SUM(bdmulta) bdmulta,
       SUM(bdjuros) bdjuros,
       SUM(bdtotal) bdtotal,
       SUM(bdvalempgps) bdvalempgps,
       SUM(bdvalseggps) bdvalseggps FROM (
SELECT imp.bdcodemp,COALESCE(E.bdcodmatriz,IMP.bdcodemp) bdcodmatriz,imp.bdcodimp,(SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) bdreferencia,imp.bdvalor bdvalor,imp.bdmulta bdmulta,imp.bdjuros bdjuros,imp.bdtotal bdtotal,
       gps.bdvalemp bdvalempgps, gps.bdvalseg bdvalseggps
FROM tdarfpadrao imp
JOIN tempresas e ON (imp.bdcodemp = e.bdcodemp)
LEFT OUTER JOIN (SELECT gpsx.bdcodemp,gpsx.bdchavedarf,SUM(gpsx.bdvalemp) bdvalemp,SUM(gpsx.bdvalseg) bdvalseg FROM VW_VRHF_EMP_GPS_IND gpsx
                 GROUP BY gpsx.bdcodemp,gpsx.bdchavedarf) gps
                 ON (imp.bdcodemp = gps.bdcodemp AND imp.bdchavedarf = gps.bdchavedarf)
JOIN tdarfgerpgto pgto ON (imp.bdcodemp = pgto.bdcodemp AND imp.bdchavedarf = pgto.bdchavedarf)
)
GROUP BY bdcodemp,BDCODMATRIZ,bdcodimp,bdreferencia
;

CREATE OR ALTER VIEW VW_VRH_EMP_TTRANSCOL_DESTINO(
    BDCODEMPORIG,
    BDCODCOLORIG,
    BDCODEMP,
    BDCODPTRAN,
    BDDATATRF,
    BDCODCOL)
AS
SELECT
    bdcodemporig,
    bdcodcolorig,
    bdcodempdest,
    bdcodptran,
    bddatatrf,
    bdcodcoldest
FROM vrh_emp_ttranscol
;

CREATE OR ALTER VIEW VW_SN_ENCARGOS_SALARIOS_SEMGRRF(
    BDCODEMP,
    BDREF,
    BDTIPOCODVER,
    BDSALARIO)
AS
SELECT bdcodemp,bdref,bdtipocodver,SUM(bdsalario) bdsalario FROM (


SELECT vfn.bdcodemp,vfn.bdreffn bdref,v.bdtipocodver, vfn.bdvalvfn bdsalario FROM vrhf_emp_tverbafn vfn
JOIN vw_verbas_ref_atual v ON (vfn.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vfT.bdcodemp,vfT.bdreftomador bdref,v.bdtipocodver,vfT.bdvalvfT bdsalario FROM vrhf_emp_tverbatomador vfT
JOIN vw_verbas_ref_atual v ON (vfT.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vfC.bdcodemp,vfC.bdreffn bdref,v.bdtipocodver,vfC.bdvalvfc bdsalario FROM vrhf_emp_tverbafc vfC
JOIN vw_verbas_ref_atual v ON (vfC.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vfCt.bdcodemp,vfCt.bdreftomador bdref,v.bdtipocodver,vfCt.bdvalvfc bdsalario FROM vrhf_emp_tverbafctomador vfCt
JOIN vw_verbas_ref_atual v ON (vfCt.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vaut.bdcodemp,serv.BDREFSERV bdref,v.bdtipocodver,vaut.bdvalor bdsalario FROM VRHF_BASE_ITEMS_CALCTERC vaut
JOIN vw_verbas_ref_atual v ON (vaut.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
JOIN vrh_base_tservterc serv ON (serv.bdcodter = vaut.bdcodter AND vaut.bdcodemp = serv.bdcodemp AND vaut.bdcodserv = serv.bdcodserv)
UNION ALL

SELECT vad.bdcodemp,ad.BDREFAD bdref,v.bdtipocodver,vad.bdvalvad bdsalario FROM vrhf_emp_tverbaad vad
JOIN vw_verbas_ref_atual v ON (vad.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
JOIN vrhf_emp_tadsal ad ON (vad.bdcodemp = ad.bdcodemp AND vad.bdcodcol = ad.bdcodcol AND vad.bddataad = ad.bddataad)
UNION ALL

SELECT va13.bdcodemp,va13.bdrefa13 bdref,v.bdtipocodver,va13.bdvalva13 bdsalario FROM vrhf_emp_tverbaa13 va13
JOIN vw_verbas_ref_atual v ON (va13.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT v13.bdcodemp,v13.bdref13 bdref,v.bdtipocodver,v13.bdvalv13 bdsalario FROM vrhf_emp_tverba13 v13
JOIN vw_verbas_ref_atual v ON (v13.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vc13.bdcodemp,vc13.bdrefc13 bdref,v.bdtipocodver,vc13.bdvalvc13 bdsalario FROM vrhf_emp_tverbac13 vc13
JOIN vw_verbas_ref_atual v ON (vc13.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vimp.bdcodemp, vimp.bdreferencia, 0 bdtipocodver, CASE WHEN imp.bddocarrecadacao = 12 THEN vimp.bdvalempgps ELSE vimp.bdtotal END
FROM vw_sn_impostos_ref vimp
JOIN timposto imp ON ((vimp.bdcodimp = imp.bdcodimp) AND
                      (imp.bdcodsis = 2) AND
                      ((imp.bddocarrecadacao IN (19,12)) OR ((imp.bddocarrecadacao IN (1)) AND (imp.bdtiporetencao = 1))))

)

GROUP BY bdcodemp, bdref, bdtipocodver
;

CREATE OR ALTER VIEW VW_TCONF_CTAS_REF_MAX_MIN(
    BDCODPLANOONLINE,
    BDCHAVE,
    BDREFCTA)
AS
SELECT
cta.BDCODPLANOONLINE,
cta.BDCHAVE,
(
  SELECT FIRST 1 x.BDREFCTA FROM TCONF_CONTAS_ONLINE_REF x
  WHERE x.BDCODPLANOONLINE = CTA.BDCODPLANOONLINE AND
  x.BDCHAVE = coalesce(CTA.BDCHAVEVINC, CTA.BDCHAVE) AND
  X.BDREFCTA <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
  ORDER BY x.BDCODPLANOONLINE DESC, X.BDCHAVE DESC, x.BDREFCTA DESC
) BDREFCTA

FROM TCONF_CONTAS_ONLINE CTA
;

CREATE OR ALTER VIEW VW_TCONF_CONTAS_REF(
    BDCODPLANOONLINE,
    BDCHAVE,
    BDREFCTA,
    BDCODTIPOCONTA,
    BDCODNAT,
    BDCODVER,
    BDCONTADEBPROV,
    BDCONTACREDPROV,
    BDCODPLAPADRAO,
    BDCONTADEBPGTO,
    BDCONTACREDPGTO,
    BDCODHISTPROV,
    BDCODHISTPGTO,
    BDCODTPHI,
    BDCODCENTRO,
    BDCODTPCC,
    BDCODOREC,
    BDCODIMP,
    BDCHAVEVINC,
    BDCODGRUPOCLA,
    BDFORMULA,
    BDCLASSIFICACAO,
    BDCODITEMONLINE,
    BDCODCONFIRLP,
    BDCODCONFIPI,
    BDCODCONFDIMESC,
    BDCODCONFSP,
    BDCODUF,
    BDCODCOMPHISTPGTO,
    BDCODCOMPHISTPROV,
    BDCODCONFDACON,
    BDCODTCA,
    BDNAOCONTAB,
    BDCODCONFGIAMG,
    BDCODTIPODOC,
    BDCODREC,
    BDCOPYTITULO,
    BDCODCONFGIAES,
    BDCODCONFGIARO,
    BDCODCONFGIAPR,
    BDTIPOOPERIMOB,
    BDATIVA,
    BDCODOBRSER,
    BDCHAVECTABAN,
    BDCODCLI,
    BDCODCONFCIAP,
    BDCODCONFGIARJ,
    BDCODCONFBLOCOM,
    BDCODCONFICMSSPED,
    BDCODDESP,
    BDCODCONFGIAST,
    BDCODCONFGIATO)
AS
SELECT ctas.bdcodplanoonline, ctas.bdchave, tref.bdrefcta, ctas.bdcodtipoconta, ctas.bdcodnat, ctas.bdcodver, tref.bdcontadebprov,
       tref.bdcontacredprov, tref.bdcodplapadrao, tref.bdcontadebpgto, tref.bdcontacredpgto, tref.bdcodhistprov,
       tref.bdcodhistpgto, tref.bdcodtphi, ctas.bdcodcentro, ctas.bdcodtpcc, ctas.bdcodorec, ctas.bdcodimp,
       ctas.bdchavevinc, ctas.bdcodgrupocla, ctas.bdformula, ctas.bdclassificacao, ctas.bdcoditemonline,
       ctas.bdcodconfirlp, ctas.bdcodconfipi, ctas.bdcodconfdimesc, ctas.bdcodconfsp, ctas.bdcoduf,
       tref.bdcodcomphistpgto, tref.bdcodcomphistprov, ctas.bdcodconfdacon, ctas.bdcodtca, ctas.bdnaocontab,
       ctas.bdcodconfgiamg, ctas.bdcodtipodoc, ctas.bdcodrec, ctas.bdcopytitulo, ctas.bdcodconfgiaes,
       ctas.bdcodconfgiaro, ctas.bdcodconfgiapr, ctas.bdtipooperimob, ctas.bdativa, ctas.bdcodobrser,
       ctas.bdchavectaban, ctas.bdcodcli, ctas.bdcodconfciap, ctas.bdcodconfgiarj, ctas.bdcodconfblocom,
       ctas.bdcodconficmssped, ctas.bdcoddesp, ctas.bdcodconfgiast, ctas.BDCODCONFGIATO
FROM tconf_contas_online ctas
LEFT OUTER JOIN vw_tconf_ctas_ref_max_min max_min ON (max_min.bdcodplanoonline = ctas.bdcodplanoonline AND max_min.bdchave = ctas.bdchave)
LEFT OUTER JOIN tconf_contas_online_ref tref ON (tref.bdcodplanoonline = ctas.bdcodplanoonline AND tref.bdchave = ctas.bdchave AND tref.bdrefcta = max_min.bdrefcta)
;

CREATE OR ALTER VIEW VW_TCONF_CTAS_REF_TEMP_MAX_MIN(
    BDCODPLANOONLINE,
    BDCHAVE,
    BDREFCTA)
AS
SELECT
cta.BDCODPLANOONLINE,
cta.BDCHAVE,
(
  SELECT FIRST 1 x.BDREFCTA FROM TMP_TCONF_CONTAS_ONLINE_REF x
  WHERE
  X.BDSESSAO = (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_TV_CONTAS')) FROM rdb$database) AND
  x.BDCODPLANOONLINE = CTA.BDCODPLANOONLINE AND
  x.BDCHAVE = coalesce(CTA.BDCHAVEVINC, CTA.BDCHAVE) AND
  X.BDREFCTA <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
  ORDER BY x.BDCODPLANOONLINE DESC, X.BDCHAVE DESC, x.BDREFCTA DESC
) BDREFCTA

FROM TCONF_CONTAS_ONLINE CTA
;

CREATE OR ALTER VIEW VW_TCONF_CONTAS_TODAS_REF(
    BDCODPLANOONLINE,
    BDCHAVE,
    BDREFCTA,
    BDCODPLAPADRAO,
    BDCODTPHI,
    BDCONTADEBPROV,
    BDCONTACREDPROV,
    BDCODHISTPROV,
    BDCODCOMPHISTPROV,
    BDCONTADEBPGTO,
    BDCONTACREDPGTO,
    BDCODHISTPGTO,
    BDCODCOMPHISTPGTO,
    BDCOPYTITULO,
    BDCHAVEVINC)
AS
SELECT ONL.BDCODPLANOONLINE, ONL.BDCHAVE, REF_PAI.BDREFCTA, REF.BDCODPLAPADRAO, REF.BDCODTPHI, REF.BDCONTADEBPROV,
       REF.BDCONTACREDPROV, REF.BDCODHISTPROV, REF.BDCODCOMPHISTPROV, REF.BDCONTADEBPGTO, REF.BDCONTACREDPGTO,
       REF.BDCODHISTPGTO, REF.BDCODCOMPHISTPGTO, REF.BDCOPYTITULO, ONL.BDCHAVEVINC
FROM TCONF_CONTAS_ONLINE ONL
LEFT OUTER JOIN TCONF_CONTAS_ONLINE_REF REF_PAI ON (ONL.BDCODPLANOONLINE = REF_PAI.BDCODPLANOONLINE AND REF_PAI.BDCHAVE = COALESCE(ONL.bdchavevinc, ONL.BDCHAVE))
LEFT OUTER JOIN TCONF_CONTAS_ONLINE_REF REF ON (ONL.BDCODPLANOONLINE = REF.BDCODPLANOONLINE AND ONL.BDCHAVE = REF.BDCHAVE AND REF_PAI.BDREFCTA = REF.BDREFCTA)
;

CREATE OR ALTER VIEW VW_TCONF_CONTAS_REF_TEMP(
    BDCODPLANOONLINE,
    BDCHAVE,
    BDREFCTA,
    BDCODTIPOCONTA,
    BDCODNAT,
    BDCODVER,
    BDCONTADEBPROV,
    BDCONTACREDPROV,
    BDCODPLAPADRAO,
    BDCONTADEBPGTO,
    BDCONTACREDPGTO,
    BDCODHISTPROV,
    BDCODHISTPGTO,
    BDCODTPHI,
    BDCODCENTRO,
    BDCODTPCC,
    BDCODOREC,
    BDCODIMP,
    BDCHAVEVINC,
    BDCODGRUPOCLA,
    BDFORMULA,
    BDCLASSIFICACAO,
    BDCODITEMONLINE,
    BDCODCONFIRLP,
    BDCODCONFIPI,
    BDCODCONFDIMESC,
    BDCODCONFSP,
    BDCODUF,
    BDCODCOMPHISTPGTO,
    BDCODCOMPHISTPROV,
    BDCODCONFDACON,
    BDCODTCA,
    BDNAOCONTAB,
    BDCODCONFGIAMG,
    BDCODTIPODOC,
    BDCODREC,
    BDCOPYTITULO,
    BDCODCONFGIAES,
    BDCODCONFGIARO,
    BDCODCONFGIAPR,
    BDTIPOOPERIMOB,
    BDATIVA,
    BDCODOBRSER,
    BDCHAVECTABAN,
    BDCODCLI,
    BDCODCONFCIAP,
    BDCODCONFGIARJ,
    BDCODCONFBLOCOM,
    BDCODCONFICMSSPED,
    BDCODDESP,
    BDCODCONFGIAST,
    BDCODCONFGIATO)
AS
SELECT ctas.bdcodplanoonline, ctas.bdchave, COALESCE(tref.bdrefcta, ctas.bdrefcta), ctas.bdcodtipoconta, ctas.bdcodnat, ctas.bdcodver,
       iif(tref.bdrefcta is not null, tref.bdcontadebprov, ctas.bdcontadebprov), iif(tref.bdrefcta is not null, tref.bdcontacredprov, ctas.bdcontacredprov),
       iif(tref.bdrefcta is not null, tref.bdcodplapadrao, ctas.bdcodplapadrao), iif(tref.bdrefcta is not null, tref.bdcontadebpgto, ctas.bdcontadebpgto),
       iif(tref.bdrefcta is not null, tref.bdcontacredpgto, ctas.bdcontacredpgto), iif(tref.bdrefcta is not null, tref.bdcodhistprov, ctas.bdcodhistprov),
       iif(tref.bdrefcta is not null, tref.bdcodhistpgto, ctas.bdcodhistpgto), iif(tref.bdrefcta is not null, tref.bdcodtphi, ctas.bdcodtphi), ctas.bdcodcentro,
       ctas.bdcodtpcc, ctas.bdcodorec, ctas.bdcodimp, ctas.bdchavevinc, ctas.bdcodgrupocla, ctas.bdformula,
       ctas.bdclassificacao, ctas.bdcoditemonline, ctas.bdcodconfirlp, ctas.bdcodconfipi, ctas.bdcodconfdimesc,
       ctas.bdcodconfsp, ctas.bdcoduf, iif(tref.bdrefcta is not null, tref.bdcodcomphistpgto, ctas.bdcodcomphistpgto),
       iif(tref.bdrefcta is not null, tref.bdcodcomphistprov, ctas.bdcodcomphistprov), ctas.bdcodconfdacon, ctas.bdcodtca, ctas.bdnaocontab,
       ctas.bdcodconfgiamg, ctas.bdcodtipodoc, ctas.bdcodrec, ctas.bdcopytitulo, ctas.bdcodconfgiaes,
       ctas.bdcodconfgiaro, ctas.bdcodconfgiapr, ctas.bdtipooperimob, ctas.bdativa, ctas.bdcodobrser,
       ctas.bdchavectaban, ctas.bdcodcli, ctas.bdcodconfciap, ctas.bdcodconfgiarj, ctas.bdcodconfblocom,
       ctas.bdcodconficmssped, ctas.bdcoddesp, ctas.bdcodconfgiast, ctas.BDCODCONFGIATO
FROM VW_TCONF_CONTAS_REF ctas
LEFT OUTER JOIN VW_TCONF_CTAS_REF_TEMP_MAX_MIN max_min ON (max_min.bdcodplanoonline = ctas.bdcodplanoonline AND max_min.bdchave = ctas.bdchave)
LEFT OUTER JOIN TMP_TCONF_CONTAS_ONLINE_REF tref ON (tref.BDSESSAO = (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_TV_CONTAS')) FROM rdb$database) and tref.bdcodplanoonline = ctas.bdcodplanoonline AND tref.bdchave = ctas.bdchave AND tref.bdrefcta = max_min.bdrefcta)
;

CREATE OR ALTER VIEW VW_TCONF_VARIAS_CONTAS_REF_TEMP(
    BDCODPLANOONLINE,
    BDCHAVE,
    BDREFCTA,
    BDCODTIPOCONTA,
    BDCODNAT,
    BDCODVER,
    BDCONTADEBPROV,
    BDCONTACREDPROV,
    BDCODPLAPADRAO,
    BDCONTADEBPGTO,
    BDCONTACREDPGTO,
    BDCODHISTPROV,
    BDCODHISTPGTO,
    BDCODTPHI,
    BDCODCENTRO,
    BDCODTPCC,
    BDCODOREC,
    BDCODIMP,
    BDCHAVEVINC,
    BDCODGRUPOCLA,
    BDFORMULA,
    BDCLASSIFICACAO,
    BDCODITEMONLINE,
    BDCODCONFIRLP,
    BDCODCONFIPI,
    BDCODCONFDIMESC,
    BDCODCONFSP,
    BDCODUF,
    BDCODCOMPHISTPGTO,
    BDCODCOMPHISTPROV,
    BDCODCONFDACON,
    BDCODTCA,
    BDNAOCONTAB,
    BDCODCONFGIAMG,
    BDCODTIPODOC,
    BDCODREC,
    BDCOPYTITULO,
    BDCODCONFGIAES,
    BDCODCONFGIARO,
    BDCODCONFGIAPR,
    BDTIPOOPERIMOB,
    BDATIVA,
    BDCODOBRSER,
    BDCHAVECTABAN,
    BDCODCLI,
    BDCODCONFCIAP,
    BDCODCONFGIARJ,
    BDCODCONFBLOCOM,
    BDCODCONFICMSSPED,
    BDCODDESP,
    BDCODCONFGIAST,
    BDCODCONFGIATO)
AS
SELECT ref_max_min.bdcodplanoonline, ref_max_min.bdchave, tref_pai.bdrefcta, ctas.bdcodtipoconta, ctas.bdcodnat, ctas.bdcodver,
       tref.bdcontadebprov, tref.bdcontacredprov,
       tref.bdcodplapadrao, tref.bdcontadebpgto,
       tref.bdcontacredpgto,  tref.bdcodhistprov,
       tref.bdcodhistpgto, tref.bdcodtphi, ctas.bdcodcentro,
       ctas.bdcodtpcc, ctas.bdcodorec, ctas.bdcodimp, ref_max_min.bdchavevinc, ctas.bdcodgrupocla, ctas.bdformula,
       ctas.bdclassificacao, ctas.bdcoditemonline, ctas.bdcodconfirlp, ctas.bdcodconfipi, ctas.bdcodconfdimesc,
       ctas.bdcodconfsp, ctas.bdcoduf, tref.bdcodcomphistpgto,
       tref.bdcodcomphistprov, ctas.bdcodconfdacon, ctas.bdcodtca, ctas.bdnaocontab,
       ctas.bdcodconfgiamg, ctas.bdcodtipodoc, ctas.bdcodrec, ctas.bdcopytitulo, ctas.bdcodconfgiaes,
       ctas.bdcodconfgiaro, ctas.bdcodconfgiapr, ctas.bdtipooperimob, ctas.bdativa, ctas.bdcodobrser,
       ctas.bdchavectaban, ctas.bdcodcli, ctas.bdcodconfciap, ctas.bdcodconfgiarj, ctas.bdcodconfblocom,
       ctas.bdcodconficmssped, ctas.bdcoddesp, ctas.bdcodconfgiast, ctas.BDCODCONFGIATO
FROM (SELECT ref.bdsessao, ref.bdcodplanoonline, ref.bdchave, ref.bdchavevinc, MAX(ref.bdrefcta) AS bdrefcta
      FROM tmp_tconf_contas_online_ref ref
      WHERE bdsessao = (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_TV_CONTAS'))
                        FROM rdb$database)
      GROUP BY ref.bdsessao, ref.bdcodplanoonline, ref.bdchave, ref.bdchavevinc) ref_max_min
LEFT OUTER JOIN tconf_contas_online ctas ON (ctas.bdcodplanoonline = ref_max_min.bdcodplanoonline AND ctas.bdchave = COALESCE(ref_max_min.bdchavevinc, ref_max_min.bdchave))
LEFT OUTER JOIN VW_TCONF_CTAS_REF_TEMP_MAX_MIN tref_pai on (tref_pai.bdcodplanoonline = ref_max_min.bdcodplanoonline AND tref_pai.bdchave = COALESCE(ref_max_min.bdchavevinc, ref_max_min.bdchave))
inner JOIN tmp_tconf_contas_online_ref tref ON (tref.bdsessao = ref_max_min.bdsessao AND tref.bdcodplanoonline = ctas.bdcodplanoonline AND tref.bdchave = ref_max_min.bdchave AND tref.bdrefcta = tref_pai.bdrefcta)
;

/* Início sol: 16067 Morgana */
CREATE OR ALTER TRIGGER vfin_esc_tcontrato_au0 FOR vfin_esc_tcontrato
ACTIVE AFTER UPDATE POSITION 0
AS
  
BEGIN
 
END
;

CREATE OR ALTER TRIGGER VRH_BASE_TRETORNO_QC_BI0 FOR VRH_BASE_TRETORNO_QC
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
;

DROP TRIGGER VFIN_BASE_TLOGREMAPI_AI0;

DROP TRIGGER VFIN_ESC_TLOGREM_BI0;

DROP TRIGGER VFIN_BASE_PLANOIMPORTCSV_BI0;

DROP TRIGGER VFIN_ESC_TCABSERVICOFIXO_BI0;

DROP TRIGGER VFIN_BASE_CONFIGIMPORTOCSV_BI0;

create or alter procedure SP_EXPORTA_DRCSTSP (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRFINALIDADE integer,
    PRARQUIVO varchar(260))
as
begin
end;

CREATE OR ALTER PROCEDURE SP_EXPORTA_NF_GAUCHA (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRRETIFICADORA INTEGER,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
END;

SET TERM ^;

DROP EXTERNAL FUNCTION CLOSEARQ^
DROP EXTERNAL FUNCTION OPENARQ^
DROP EXTERNAL FUNCTION WRITELNOA^
DROP EXTERNAL FUNCTION NEWFILE^
DROP EXTERNAL FUNCTION NEWFILE_UTF8^
DROP EXTERNAL FUNCTION WRITELN_UTF8^

DECLARE EXTERNAL FUNCTION CLOSEARQ CSTRING(260),INTEGER RETURNS INTEGER BY VALUE ENTRY_POINT 'CLOSEARQ' MODULE_NAME 'DllExternalFile.dll'^
DECLARE EXTERNAL FUNCTION OPENARQ CSTRING(260),INTEGER RETURNS INTEGER BY VALUE ENTRY_POINT 'OPENARQ' MODULE_NAME 'DllExternalFile.dll'^
DECLARE EXTERNAL FUNCTION WRITELNOA CSTRING(10000),INTEGER RETURNS INTEGER BY VALUE ENTRY_POINT 'WRITELNOA' MODULE_NAME 'DllExternalFile.dll'^
DECLARE EXTERNAL FUNCTION WRITELN_UTF8 CSTRING(260),CSTRING(1024) RETURNS INTEGER BY VALUE ENTRY_POINT 'WRITELN_UTF8' MODULE_NAME 'DllExternalFile.dll'^
DECLARE EXTERNAL FUNCTION NEWFILE CSTRING(260) RETURNS INTEGER BY VALUE ENTRY_POINT 'NEWFILE' MODULE_NAME 'DllExternalFile.dll'^
DECLARE EXTERNAL FUNCTION NEWFILE_UTF8 CSTRING(260) RETURNS INTEGER BY VALUE ENTRY_POINT 'NEWFILE_UTF8' MODULE_NAME 'DllExternalFile.dll'^

SET TERM ;^

DROP TRIGGER VRHF_BASE_TPERIODORRA_ADV_BI0;

DROP TRIGGER VRHF_BASE_TPERIODORRA_BI0;

DROP TRIGGER VRH_EMP_TRECLAMATORIA_ABONO_BI0;

DROP TRIGGER tol_vef_emp_tgiastger_ad0;

DROP TRIGGER TOL_VEF_EMP_TPARIMPENC_AD0;

DROP TRIGGER TOL_VEF_EMP_TPARIMP_AD0;

DROP TRIGGER TOL_VEF_EMP_TPARIMPDARF_AD0;

DROP TRIGGER TOL_TPARCELAIMPOSTOPGTO_AD0;

DROP TRIGGER tol_vef_emp_tmovent_ser_ad0;

DROP TRIGGER vfin_esc_tcobrancautomatica_bi0;

DROP TRIGGER VEF_BASE_TCADINFCOM_BI0;

DROP TRIGGER VEF_BASE_TCADINFCOM_BD0;

DROP TRIGGER vef_dashboard_info_enviados_bi0;

DROP TRIGGER vef_dashboard_tincon_bi0;

DROP TRIGGER vef_dashboard_tarquivo_bi0;

DROP TRIGGER tmp_vef_emp_tc500sai_temp_bu0;

DROP TRIGGER VEF_EMP_TMOVOPIMOBI_F200_BI;

DROP TRIGGER VEF_EMP_TMOVEXP_BU0;

DROP TRIGGER VEF_EMP_TMOVEXP_BI0;

DROP TRIGGER VEF_EMP_TMOVFINI100_BU0;

DROP TRIGGER VEF_EMP_TMOVFINI100_BI0;

DROP TRIGGER VEF_EMP_TMOVOREC_BU0;

DROP TRIGGER VEF_EMP_TMOVOPIMOBILIARIA_F200_BU0;

DROP TRIGGER tmoedas_ad0;

DROP TRIGGER vef_base_ttabinfad52_ad0;

DROP TRIGGER vef_emp_tmovsai_bd0;

DROP TRIGGER vef_emp_tmovser_bd0;

DROP TRIGGER vef_emp_tmovexp_bd0;

DROP TRIGGER vef_emp_tredz_bd0;

DROP TRIGGER vef_emp_tmovfini100_bd0;

DROP TRIGGER vef_emp_tmovinv_bd0;

DROP TRIGGER vef_emp_tmovorec_bd0;

DROP TRIGGER vef_emp_tmovopimobiliaria_f200_bd0;

DROP TRIGGER vef_emp_tmovdemaisdoc_f100_bd0;

DROP TRIGGER vef_emp_tmovent_bd0;

DROP TRIGGER vef_emp_tmovprosaiimpori_biu0;

DROP TRIGGER vef_emp_tmovsaipar_bu0;

DROP TRIGGER vef_emp_tc195sai_bu0;

DROP TRIGGER vef_base_ttabinfrete_bd0;

DROP TRIGGER tcadpro_bd0;

DROP TRIGGER tempresas_scp_bd0;

DROP TRIGGER tplano_pagamento_bd0;

DROP TRIGGER vef_base_ttabcta_bd0;

DROP TRIGGER tunidademedida_bd0;

DROP TRIGGER tncm_bd0;

DROP TRIGGER tterceiro_bd0;

DROP TRIGGER vef_base_tequipasat_bd0;

DROP TRIGGER vef_emp_tcadempreendimento_bd0;

DROP TRIGGER vef_emp_tc100sai_bu0;

DROP TRIGGER tmp_vef_base_tlog_temp_bi0;

DROP TRIGGER VEF_EMP_TPARIMPPAR_BI0;

DROP TRIGGER VEF_EMP_TDIMEGERREGESP_AD0;

DROP TRIGGER VEF_EMP_TPARIMPDARF_AI0;

DROP TRIGGER VEF_EMP_TPARIMPDARF_AD0;

DROP TRIGGER TPARCELAIMPOSTOPGTO_AD0;

DROP TRIGGER TPARCELAIMPOSTOPGTO_AI0;

DROP TRIGGER vsh_emp_tconf_imp_arq_bi0;

DROP TRIGGER vsh_emp_tconf_imposto_inc_bi0;

DROP TRIGGER vsh_emp_tconfia_imposto_bu0;

DROP TRIGGER vsh_emp_tconia_imposto_bi0;

DROP TRIGGER vsh_base_tagendamento_bi0;

DROP TRIGGER VSH_BASE_TAGENDAMENTO_BD0;

DROP TRIGGER VSH_BASE_TPLANO_BD0;

DROP TRIGGER vsh_emp_tconfempresas_bu0;

DROP TRIGGER vsh_emp_tconfempresas_bi0;

DROP TRIGGER TOL_VEF__TMOVRATREDZVARCFOP_AD0;

DROP TRIGGER VSH_EMP_TLOG_PROCESSO_BI0;

DROP TRIGGER VSH_EMP_TCONFERENCIA_FOLHA_BI0;

DROP TRIGGER VSH_EMP_TCONFERENCIA_FOLHA_BU0;

DROP TRIGGER VRH_EMP_TOCORRENCIA_COL_BI0;

DROP TRIGGER VSH_EMP_TARQUIVO_PROCESSO_BI;

DROP TRIGGER VSH_EMP_TARQUIVO_PROCESSO_BU0;

DROP TRIGGER vsh_base_tagendamento_bu0;

DROP TRIGGER tol_vef_emp_tapue316_ad0;

DROP TRIGGER tol_vef_emp_tapue250_ad0;

DROP TRIGGER TMP_VSUC_EMPRESAS_TLAN_TEMP_BU0;

DROP TRIGGER vsh_emp_tlista_processos_bu0;

DROP TRIGGER TDARFGERPGTO_AD0;

DROP TRIGGER TINTEGRACAO_ARQ_CLIENTE_FILA_AD0;

DROP TRIGGER vfin_esc_tcontrato_au0;
/* Fim sol: 16067 Morgana */

DROP TRIGGER VRH_BASE_TCONF_IMP_SERV_BI0;

DROP TRIGGER TARQ_STORAGESCI_BI0;

DROP TRIGGER tmanad_geral_bi0;

DROP TRIGGER VRH_BASE_TRETORNO_QC_BI0;

DROP VIEW VW_SN_ENCARGOS_SALARIOS_SEMGRRF;

DROP VIEW VW_VRH_EMP_TTRANSCOL_DESTINO;

DROP VIEW VW_SN_IMPOSTOS_PGTO;

DROP VIEW VW_SN_VERBAS_CALCULOS_RH_PGTO;

DROP VIEW VW_UNION_FC_TOMADOR;

DROP VIEW VW_UNION_FC_TOMADOR_VERBAS;

DROP VIEW VW_UNION_FC_TOMADOR_VERBAS_DET;

DROP VIEW VW_VEF_BASE_TEMPCADATV;

DROP VIEW VW_SN_VERBAS_CALCULOS_RH_REF;

DROP VIEW VW_TCONF_VARIAS_CONTAS_REF_TEMP;

DROP VIEW VW_TCONF_CONTAS_REF_TEMP;

DROP VIEW VW_TCONF_CONTAS_REF;

DROP VIEW VW_TCONF_CTAS_REF_TEMP_MAX_MIN;

DROP VIEW VW_TCONF_CTAS_REF_MAX_MIN;

DROP PROCEDURE SP_VRHF_UNION_FN_FT_MES;

DROP procedure VTPO_INDICADOR_TEMPO;

DROP PROCEDURE VTPO_CONSULTA_TEMPOS;

DROP PROCEDURE SP_SOCIOPROPRIETARIO;

DROP PROCEDURE VSUC_SP_COPIA_CONFIG_IDIOMAS;

DROP PROCEDURE SP_TIPODESCIDIOMAS;

DROP PROCEDURE VSUC_LANCAMENTOS_EF_AGRUPADOS;

DROP PROCEDURE VSUC_SP_EMP_TLAN_GROUP;

DROP PROCEDURE FK_MANUAL_INSERT;
DROP PROCEDURE FK_MANUAL_DELETE;

DROP PROCEDURE VSUC_SP_EMP_TLAN_RH_GROUP_NEW;

DROP PROCEDURE VSUC_SP_EMP_TLAN_EF_GROUP_NEW;

DROP PROCEDURE VSUC_SP_CONCILIACAO;

DROP PROCEDURE SP_VRH_REORDENA_TODAS_VERBAS;

DROP PROCEDURE SP_INCLUICLASSECOL_ONLINE;

DROP PROCEDURE SP_VRH_REORDENA_VERBAS;

DROP PROCEDURE SP_CRIA_REFERENCIA_EMPRESAS_REF;

DROP PROCEDURE SP_CRIA_REFERENCIA_COLCON_REF;

DROP PROCEDURE SP_CRIA_REF_ESOCIAL_EMP_REF;

DROP PROCEDURE SP_CRIA_DATA_COLCON_DIA;

DROP PROCEDURE VRHF_EMP_VAL_GRRF_FC;

--DROP PROCEDURE AAAAMM;

DROP PROCEDURE COMPARATEXTO;

--DROP PROCEDURE CONTAR_CHAR;

DROP PROCEDURE DIA_SEGUINTE;

DROP PROCEDURE SP_AJUSTE_ISE_OUT;

DROP PROCEDURE EMPAUTSERV;

--DROP PROCEDURE SP_CRIA_INCONF_S1010;

DROP PROCEDURE SP_RETORNA_QTDECOLATIVOS;

DROP TRIGGER TAVISOS_BI0;

DROP TRIGGER empresas_tsoc_ref_bi0;

DROP TRIGGER VEF_EMP_TMOVENT_BI0;

DROP TRIGGER TOL_VEF_REINF_EVT_DEMAISDOC_AD0;

DROP TRIGGER VEF_EMP_TMOVSAI_BI0;

DROP TRIGGER VRHF_EMP_TVSCOL_AU0;

DROP TRIGGER VRHF_EMP_TVSCOL_AD0;

DROP TRIGGER VRHF_EMP_TVSEMP_AU0;

DROP TRIGGER VRHF_EMP_TVSEMP_AD0;

DROP TRIGGER VRHF_FUNCOES_TVSFUC_AU0;

DROP TRIGGER VRHF_FUNCOES_TVSFUC_AD0;

DROP TRIGGER VRHF_CUSTOS_TVSCUSTO_AU0;

DROP TRIGGER VRHF_CUSTOS_TVSCUSTO_AD0;

DROP TRIGGER VRHF_BASE_TVSSIND_AU0;

DROP TRIGGER VRHF_BASE_TVSSIND_AD0;

DROP TRIGGER VRHF_BASE_TVSPRES_AU0;

DROP TRIGGER VRHF_BASE_TVSPRES_AD0;

DROP TRIGGER VRHF_BASE_TVSTER_AU0;

DROP TRIGGER VRHF_BASE_TVSTER_AD0;

DROP TRIGGER tmenu_novos_bi0;

DROP TRIGGER tmenu_biu0;

DROP TRIGGER VRH_BASE_TRUBRICAES_VER_PD_AIU0;


SET TERM ^ ;

CREATE OR ALTER TRIGGER TTELA_SISTEMA_BI0 FOR TTELA_SISTEMA
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
    NEW.BDCODTELASIS = Gen_Id(gen_ttela_sistema,1);
end
^

CREATE OR ALTER trigger vef_emp_tmovent_bi0 for vef_emp_tmovent
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.BDDATAINCLUSAO IS NULL) AND (NEW.BDHORAINCLUSAO IS NULL)) THEN
      EXCEPTION EX_LAN_SEM_DATA_HORA;
  end
end^

CREATE OR ALTER trigger vef_emp_tmovsai_bi0 for vef_emp_tmovsai
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.BDDATAINCLUSAO IS NULL) AND (NEW.BDHORAINCLUSAO IS NULL)) THEN
      EXCEPTION EX_LAN_SEM_DATA_HORA;
  end
end^

CREATE OR ALTER TRIGGER TEMPRESAS_BD0 FOR TEMPRESAS
ACTIVE BEFORE DELETE POSITION 0 
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER TMANAD_GERAL_BI0 FOR TMANAD_GERAL
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE vcod INTEGER;
BEGIN
  NEW.bdcodmanad = GEN_ID(gen_manad, 1);
END
^

CREATE OR ALTER TRIGGER TASSINATURA_BI0 FOR TASSINATURA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
END
^

ALTER TRIGGER TEMP_SPED_FCONT_REF_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TEMPRESAS_IMG_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TR_BF_INSERT_VEF_BASE_TCFPS
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TR_BF_INSERT_VLAL_BASE_TEMP
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VEF_EMP_TAJUSTEEFDC_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VEF_EMP_TAJUSTEIPIE530_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VEF_EMP_TMOV_OCORR_DCIP_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VEF_EMP_TMOVOCO_GIASP_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VEF_EMP_TOCODEBCREMG_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VEF_EMP_TOCOGIAES_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VEF_EMP_TOCOGIARO_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VEF_EMP_TOCOMG_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VRHF_EMP_GPS_IND_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VSUC_EMPRESAS_TLANFORM_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VSUC_EMPRESAS_TLANNE_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VSUC_EMPRESAS_TLCC_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VSUC_EMPRESAS_TORC_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

SET TERM ; ^

DROP PROCEDURE MAXSCI;

SET TERM ^ ;

ALTER TRIGGER VEF_BASE_TCONFBLOCOPQ_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VEF_BASE_TCONFBLOCOPQ_BU0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VEF_BASE_TCONFCIAPQ_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VEF_BASE_TCONFCIAPQ_BU0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VEF_BASE_TCONFDACONQ_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VEF_BASE_TCONFDACONQ_BU0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VEF_BASE_TCONFICMSSPEDQ_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VEF_BASE_TCONFICMSSPEDQ_BU0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VEF_ESTADOS_TCONFDIMEQ_BU0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

SET TERM ; ^

DROP PROCEDURE PREENCHE_CLASSIFICACAOPRODUTO;

SET TERM ^ ;

ALTER TRIGGER PLANOS_TPLA_BU0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TR_BF_INSERT_PLANOS_TPLA
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TR_BF_INSERT_VSUC_BASE_TFTFPO
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;  
  DECLARE VARIABLE wNivel INTEGER;
BEGIN
  vcodigo = 0;
END
^

CREATE OR ALTER PROCEDURE SP_GERAR_INCON_TERCEIRO (
    PRSESSAO INTEGER,
    PRREF INTEGER,
    PRCODEMP INTEGER,
    PRPUSH DM_BOOLEAN)
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_VALIDA_CNPJ (
    PRCNPJ VARCHAR(18))
RETURNS (
    BDISVALID VARCHAR(5))
AS
BEGIN
  BDISVALID = 'FALSE';
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_VALIDA_CPF (
    PRCPF VARCHAR(14))
RETURNS (
    BDISVALID VARCHAR(5))
AS
BEGIN
  BDISVALID = 'FALSE';
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_PRE_VALIDA_CONTA_ONLINE_TEMP (
    PRCODPLANOONLINE INTEGER,
    PRSESSAO INTEGER,
    PRENQFED INTEGER,
    PRCODCONFIRLP INTEGER,
    PRTIPOLAN VARCHAR(4))
AS
BEGIN

END^

create or alter procedure SP_VALIDA_CONTA_ONLINE_TEMP (
    PRCODPLANOONLINE integer,
    PRSESSAO integer,
    PRENQFED integer,
    PRCODCONFIRLP integer,
    PRTIPOLAN varchar(4),
    PRFORMATRIB integer = 0)
as
BEGIN

END^

create or alter procedure SP_ATUALIZAR_TMP_MOVCCSAI (
    PRSESSAO integer,
    PRREF integer)
as
declare variable WNAOPERMITERATEIOGRUPO boolean;
declare variable WCODEMP integer;
begin
end^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_TMOVSAIITENS (
    PRCODPLANOONLINE INTEGER,
    PRSESSAO INTEGER,
    PRCODPLANOINCON INTEGER,
    PRUFEMP VARCHAR(2),
    PRVALIDARCSTMOVPRO VARCHAR(5),
    PRSESSAOPRO integer,
    PRREF integer)
AS
DECLARE VARIABLE WIMPVLRCONTABDIFIPI VARCHAR(5);
DECLARE VARIABLE WIMPVLRCONTABDIF VARCHAR(5);
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_TMOVSAI (
    PRSESSAO INTEGER,
    PRREF INTEGER,
    PRCHAVEFIMBASE INTEGER,
    PRCODEMP INTEGER,
    PRVALIDARCSTMOVPRO VARCHAR(5),
    PRSESSAOPRO INTEGER,
    PRSESSAOTER INTEGER,
    PRSESSAOEQUIPSAT INTEGER,
    PRGERALOG varchar(5))
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_COMMIT_UNIDADEMEDIDA (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_INSERT_OR_UPDATE_TCADPRO (
    PRCODEMP integer,
    PRSESSAO INTEGER,
    PRREF INTEGER)
AS
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_INSERT_OR_UPDATE_TTERCEIRO (
    PRSESSAO INTEGER,
    PRREFEMP INTEGER,
    PRCODEMP INTEGER)
AS
BEGIN
END^

create or alter procedure SP_TOTSERDESPPERIODO (
    PRCODESC varchar(500),
    PRDATAINICIAL varchar(10),
    PRDATAFINAL varchar(10),
    PRCHAVECTABAN varchar(500),
    PRTIPOSERDESP integer,
    PRCODSERDESP integer,
    PRCODCLI varchar(10240),
    PRCODFOR varchar(10240),
    PRDEMLANCREEMBOLSO DM_BOOLEAN,
    PRDEMTRANSFBANCARIAS DM_BOOLEAN,
    PRMODELO integer,
    PRCLASSSERDESP varchar(60),
    PRDESCONTO varchar(5),
    PRNUMPERATU integer,
    PRDESCPERIODO varchar(12))
returns (
    BDTOTSERDESPPERIODO numeric(15,2))
as
declare variable VSQL varchar(20000);
declare variable VCODCLIFOR integer;
declare variable VTOTALPERIODOSEL numeric(15,2);
declare variable VSQLTOTALPERIODO varchar(500);
declare variable VTOTALGERAL numeric(15,2);
BEGIN
END^

CREATE OR ALTER procedure SP_TOTDESPPREVPERIODO (
    PRCODESC varchar(500),
    PRREFINI varchar(6),
    PRREFFIM varchar(6),
    PRCHAVECTABAN varchar(500),
    PRCODDESP integer,
    PRCODFOR varchar(10240),
    PRCLASSIFICACAO varchar(60),
    PRDESCONTO varchar(5),
    PRNUMPERATU integer,
    PRDESCPERIODO varchar(12),
    PRMODELO integer)
as
declare variable VSQL varchar(1000);
declare variable VSQLTOTALPERIODO varchar(500);
declare variable VCODFOR integer;
declare variable VTOTALPERIODOSEL numeric(15,2);
declare variable VTOTALGERAL numeric(15,2);
BEGIN
END^

CREATE OR ALTER procedure SP_TOTSERPREVPERIODO (
    PRREFINI varchar(6),
    PRREFFIM varchar(6),
    PRCODSER integer,
    PRCLASSIFICACAO varchar(60),
    PRDESCONTO varchar(5),
    PRNUMPERATU integer,
    PRDESCPERIODO varchar(12),
    PRMODELO integer,
    PRFLAGPROC integer)
as
declare variable VSQL varchar(1000);
declare variable VSQLTOTALPERIODO varchar(500);
declare variable VCODCLI integer;
declare variable VTOTALPERIODOSEL numeric(15,2);
declare variable VTOTALGERAL numeric(15,2);
BEGIN
END^

CREATE OR ALTER procedure SP_REF_TO_PERIODO (
    PRREF integer,
    PRTIPO char(3))
returns (
    BDPERIODO integer)
as
declare variable WANO integer;
declare variable WMES integer;
declare variable WBIM integer;
declare variable WTRI integer;
declare variable WSEM integer;
begin
end^

create or alter procedure SP_RETORNA_BASE_FGTS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRCATEGORIAESOCIAL integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBFGTS numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDBFGTSRES numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDFGTS numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDFGTSRES numeric(18,6),
    BDAVPREV numeric(18,6),
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDTIPOFOLHA integer,
    BDBASEFGTS13RESC numeric(18,6),
    BDFGTS13RESC numeric(18,6))
as
declare variable WSQL varchar(500);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WDATARESC date;
declare variable WBASEFGTS numeric(18,6);
declare variable WBASEFGTS13 numeric(18,6);
declare variable WVALOR numeric(18,6);
declare variable WCLAVER varchar(30000);
declare variable WBINSSAPFN numeric(18,6);
declare variable WFGTSFN numeric(18,6);
declare variable WFGTS13FN numeric(18,6);
declare variable WBASEFGTSFN numeric(18,6);
declare variable WCALCULOS integer;
declare variable WCALCAFER integer;
declare variable WREFRESC integer;
declare variable WREFFER integer;
declare variable WANORESC integer;
declare variable WREFA13 integer;
declare variable WCOUNT integer;
declare variable WMOTIVORESCISAO integer;
declare variable WEXPORTAGRRF integer;
declare variable WREFFGTSDIGITAL integer;
declare variable WSQLVERBAS varchar(800);
begin
end^

create or alter procedure SP_SEPARARBASEFGTS_LOTACAO_5003 (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDLOTACAO varchar(50),
    BDBFGTS numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDBFGTSRES numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDBASEFGTS13RESC numeric(18,6),
    BDCALCULOS integer,
    BDECONSIGNADO numeric(18,6),
    BDECONSIGNADORESC numeric(18,6))
as
declare variable WSQL varchar(30000);
declare variable WDATARESC date;
declare variable WMOTIVORESCISAO integer;
declare variable WEXPORTAGRRF integer;
declare variable WDATAPGTORESC date;
declare variable WBFGTS numeric(15,2);
declare variable WBFGTSRESC numeric(15,2);
declare variable WBFGTS13 numeric(15,2);
declare variable WBFGTS13RESC numeric(15,2);
declare variable WBAVISO numeric(15,2);
declare variable WVALOR numeric(15,2);
declare variable WDATAPGTORESCSTR varchar(50);
declare variable WMOTIVORESCISAOSTR varchar(50);
declare variable WEXPORTAGRRFSTR varchar(50);
begin
  suspend;
end^

create or alter procedure SP_RETORNA_BASE_FGTS_2 (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRCATEGORIAESOCIAL integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBFGTS numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDBFGTSRES numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDFGTS numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDFGTSRES numeric(18,6),
    BDAVPREV numeric(18,6),
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDTIPOFOLHA integer,
    BDBASEFGTS13RESC numeric(18,6),
    BDFGTS13RESC numeric(18,6),
    BDECONSIGNADO numeric(18,6),
    BDECONSIGNADORESC numeric(18,6))
as
declare variable WSQL varchar(30000);
declare variable WDATARESC date;
declare variable WMOTIVORESCISAO integer;
declare variable WEXPORTAGRRF integer;
declare variable WDATAPGTORESC date;
declare variable WBFGTS numeric(15,2);
declare variable WBFGTSRESC numeric(15,2);
declare variable WBFGTS13 numeric(15,2);
declare variable WBFGTS13RESC numeric(15,2);
declare variable WBAVISO numeric(15,2);
declare variable WVALOR numeric(15,2);
declare variable WBDCODEMP integer;
declare variable WBDCODCOL integer;
declare variable WBDREF integer;
declare variable WBDLOTACAO varchar(50);
declare variable WBDBFGTS numeric(18,6);
declare variable WBDBFGTS13 numeric(18,6);
declare variable WBDBFGTSRES numeric(18,6);
declare variable WBDBAVPREV numeric(18,6);
declare variable WBDBASEFGTS13RESC numeric(18,6);
declare variable WTOTBDBFGTS numeric(18,6);
declare variable WTOTBDBFGTS13 numeric(18,6);
declare variable WTOTBDBFGTSRES numeric(18,6);
declare variable WTOTBDBAVPREV numeric(18,6);
declare variable WTOTBDBASEFGTS13RESC numeric(18,6);
declare variable WLOTANT varchar(50);
begin

  suspend;
end^

create or alter procedure SP_VRH_SEPARABASES_FGTS_5003 (
    PRSQL varchar(10000),
    PRDATAPGTRESC date,
    PRMOTIVORESCICAO integer,
    PREXPORTAGRRF integer)
returns (
    BDLOTACAO varchar(50),
    BDBASEFGTS numeric(15,6),
    BDBFGTSRES numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDBASEFGTS13RESC numeric(15,6),
    BDBAVPREV numeric(15,6),
    BDCALCULOS integer,
    BDECONSIGNADO numeric(15,6),
    BDECONSIGNADORESC numeric(15,6))
as
declare variable WSQL varchar(30000);
declare variable WCLAVER varchar(50);
declare variable WVALOR numeric(15,6);
declare variable WTIPVER integer;
declare variable WINCFGTS integer;
declare variable WRESCISORIO integer;
declare variable WDATAPGTOCALC date;
declare variable WLOTANT varchar(50);
declare variable WLOT varchar(50);
begin
  /* Procedure Text */
  suspend;
end^

create or alter procedure SP_RETORNA_BASE_INSS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRTEMCONFIGIMPOSTO integer,
    PRSEPARAFOLHAS integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBINSS numeric(18,6),
    BDBINSSFEFOL numeric(18,6),
    BDBINSS13 numeric(18,6),
    BDINSS numeric(18,6),
    BDINSS13 numeric(18,6),
    BDINSSFEFOL numeric(18,6),
    BDVALORSALFAM numeric(18,6),
    BDVALORSALMATEMP numeric(18,6),
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDVALORPISPASEP numeric(18,6),
    BDVALORPISPASEP13 numeric(18,6),
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOCALCULO integer)
as
declare variable WSQL varchar(500);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WBINSS numeric(18,6);
declare variable WBINSSFEFOL numeric(18,6);
declare variable WBINSS13 numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WINSSFEFOL numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WVALORSALFAM numeric(18,6);
declare variable WVALORSALMATEMP numeric(18,6);
declare variable WCALCULOS integer;
declare variable WCOUNTFC integer;
declare variable WVALOR numeric(18,6);
declare variable WTIPOFOL integer;
declare variable WVALORPISPASEP numeric(18,6);
declare variable WVALORPISPASEP13 numeric(18,6);
declare variable WTAGSTR varchar(10000);
declare variable WDIFERENCIADORDATE date;
declare variable WDIFERENCIADORINTEGER integer;
declare variable WDESCRICAOFOLHA varchar(10000);
begin
end^

create or alter procedure SP_RETORNA_BASE_INSS_ES (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PR13 integer,
    PRCPFCOL varchar(18))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDBASEINSSES numeric(18,6),
    BDBASEINSS13ES numeric(18,6),
    BDVALORINSSES numeric(18,6),
    BDVALORINSS13ES numeric(18,6),
    BDVALORSALFAMES numeric(18,6),
    BDVALORSALMATEMPES numeric(18,6),
    BDVRCPSEG numeric(18,6),
    BDIND13PIS integer,
    BDTPVALORPISPASEP integer,
    BDVALORPISPASEP numeric(18,6),
    BDVERSAOLAYOUTESOCIAL varchar(10),
    BDVALORPISPASEP13 numeric(18,6))
as
declare variable WBASEINSSES numeric(18,6);
declare variable WBASEINSS13ES numeric(18,6);
declare variable WVALORINSSES numeric(18,6);
declare variable WVALORINSS13ES numeric(18,6);
declare variable WVALORSALFAMES numeric(18,6);
declare variable WVALORSALFAM13ES numeric(18,6);
declare variable WVALORSALMATEMPES numeric(18,6);
declare variable WVALORSALMATEMP13ES numeric(18,6);
declare variable WVRCPSEG numeric(18,6);
declare variable WVRCPSEG13 numeric(18,6);
declare variable WCODEVT integer;
declare variable WIND13PIS integer;
declare variable WTPVALORPISPASEP integer;
declare variable WVALORPISPASEP numeric(18,6);
declare variable WVERSAOLAYOUTESOCIAL varchar(10);
declare variable WVALORPISPASEP13 numeric(18,6);
begin
end^

create or alter procedure SP_RETORNA_BASE_IRRF_ES (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRTERCEIRO varchar(5))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDINSSMENSALES numeric(18,6),
    BDINSS13ES numeric(18,6),
    BDDEPES numeric(18,6),
    BDDEP13ES numeric(18,6),
    BDBASEIRRFMENSALES numeric(18,6),
    BDBASEIRRF13ES numeric(18,6),
    BDBASEIRRFPLRES numeric(18,6),
    BDBASEIRRFRRAES numeric(18,6),
    BDPREVMENSALES numeric(18,6),
    BDPREV13ES numeric(18,6),
    BDPENSAOMENSALES numeric(18,6),
    BDPENSAO13ES numeric(18,6),
    BDPENSAOPLRES numeric(18,6),
    BDPENSAORRAES numeric(18,6),
    BDVALORIRRFMENSALES numeric(18,6),
    BDVALORIRRF13ES numeric(18,6),
    BDVALORIRRFPLRES numeric(18,6),
    BDVALORIRRFRRAES numeric(18,6),
    BDDEPES13 numeric(18,6),
    BDDEPPLRES numeric(18,6),
    BDDEPRRAES numeric(18,6),
    BDINSSRRAES numeric(18,6),
    BDTEMEVENTO integer)
as
declare variable WSQL varchar(1000);
declare variable WVALOR numeric(18,3);
declare variable WTPVALOR numeric(18,3);
declare variable WVLRDEP numeric(18,3);
declare variable WEVT integer;
declare variable WEVTANT integer;
begin
end^

create or alter procedure SP_RETORNA_BASE_IRRF (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRTIPO integer,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBASEIRRFMENSAL numeric(18,6),
    BDVALORIRRFMENSAL numeric(18,6),
    BDINSSMENSAL numeric(18,6),
    BDDEPMENSAL numeric(18,6),
    BDPENSAOMENSAL numeric(18,6),
    BDPREVMENSAL numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDINSS13 numeric(18,6),
    BDDEP13 numeric(18,6),
    BDPENSAO13 numeric(18,6),
    BDPREV13 numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDINSSPLR numeric(18,6),
    BDDEPPLR numeric(18,6),
    BDPENSAOPLR numeric(18,6),
    BDPREVPLR numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDINSSRRA numeric(18,6),
    BDDEPRRA numeric(18,6),
    BDPENSAORRA numeric(18,6),
    BDPREVRRA numeric(18,6),
    BDCALCULOS integer)
as
declare variable WBASEIRRFMENSAL numeric(18,6);
declare variable WVALORIRRFMENSAL numeric(18,6);
declare variable WINSSMENSAL numeric(18,6);
declare variable WDEPMENSAL numeric(18,6);
declare variable WPENSAOMENSAL numeric(18,6);
declare variable WPREVMENSAL numeric(18,6);
declare variable WBASEIRRF13 numeric(18,6);
declare variable WVALORIRRF13 numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WDEP13 numeric(18,6);
declare variable WPENSAO13 numeric(18,6);
declare variable WPREV13 numeric(18,6);
declare variable WBASEIRRFPLR numeric(18,6);
declare variable WVALORIRRFPLR numeric(18,6);
declare variable WINSSPLR numeric(18,6);
declare variable WDEPPLR numeric(18,6);
declare variable WPENSAOPLR numeric(18,6);
declare variable WPREVPLR numeric(18,6);
declare variable WBASEIRRFRRA numeric(18,6);
declare variable WVALORIRRFRRA numeric(18,6);
declare variable WINSSRRA numeric(18,6);
declare variable WDEPRRA numeric(18,6);
declare variable WPENSAORRA numeric(18,6);
declare variable WPREVRRA numeric(18,6);
declare variable WCALCULOS integer;
begin
end^


create or alter procedure SP_REL_TOT_5001 (
    PRCODEMP varchar(30000),
    PRREF integer,
    PR13 integer,
    PRFILTROCPF varchar(30000),
    PRSEPARARFOLHAS integer)
returns (
    BDCODEMPORD integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCOLTER integer,
    BDCONTRCOL integer,
    BDGRUPOCLA integer,
    BDNOMCOL varchar(70),
    BDCPFCOL varchar(14),
    BDCNPJEMP varchar(18),
    BDNOMEMP varchar(100),
    BDBASEINSS numeric(18,6),
    BDBASEINSSES numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEINSS13ES numeric(18,6),
    BDVALORINSS numeric(18,6),
    BDVALORINSSES numeric(18,6),
    BDVALORINSS13 numeric(18,6),
    BDVALORINSS13ES numeric(18,6),
    BDVALORSALFAM numeric(18,6),
    BDVALORSALFAMES numeric(18,6),
    BDVALORSALMATEMP numeric(18,6),
    BDVALORSALMATEMPES numeric(18,6),
    BDVRCPSEG numeric(18,6),
    BDVRDEDDEP numeric(18,6),
    BDVRDEDDEPES numeric(18,6),
    BDBASEPENSAO numeric(18,6),
    BDBASEPENSAOES numeric(18,6),
    BDBASEIRRF numeric(18,6),
    BDBASEIRRFES numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDBASEIRRF13ES numeric(18,6),
    BDBASEIRRFFERIAS numeric(18,6),
    BDBASEIRRFFERIASES numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDBASEIRRFPLRES numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDVALORIRRFES numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDVALORIRRF13ES numeric(18,6),
    BDVALORIRRFFERIAS numeric(18,6),
    BDVALORIRRFFERIASES numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDVALORIRRFPLRES numeric(18,6),
    BDBASEFGTS numeric(18,6),
    BDBASEFGTSES numeric(18,6),
    BDVALORFGTS numeric(18,6),
    BDVALORFGTSES numeric(18,6),
    BDBASEFGTSRES numeric(18,6),
    BDBASEFGTSRESES numeric(18,6),
    BDVALORFGTSRES numeric(18,6),
    BDVALORFGTSRESES numeric(18,6),
    BDBASEAVPREV numeric(18,6),
    BDBASEAVPREVES numeric(18,6),
    BDVALORAVPREV numeric(18,6),
    BDVALORAVPREVES numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDBASEFGTS13ES numeric(18,6),
    BDVALORFGTS13 numeric(18,6),
    BDVALORFGTS13ES numeric(18,6),
    BDVALORINSSPLR numeric(18,6),
    BDVALORINSSRRA numeric(18,6),
    BDVRDEDDEP13 numeric(18,6),
    BDVRDEDDEPES13 numeric(18,6),
    BDVRDEDDEPPLR numeric(18,6),
    BDVRDEDDEPRRA numeric(18,6),
    BDBASEPENSAO13 numeric(18,6),
    BDBASEPENSAO13ES numeric(18,6),
    BDBASEPENSAOPLR numeric(18,6),
    BDBASEPENSAOPLRES numeric(18,6),
    BDBASEPENSAORRA numeric(18,6),
    BDBASEPENSAORRAES numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDBASEIRRFRRAES numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDVALORIRRFRRAES numeric(18,6),
    BDVRDEDDEPPLRES numeric(18,6),
    BDVRDEDDEPRRAES numeric(18,6),
    BDVALORINSSRRAES numeric(18,6),
    BDBASEPREV numeric(18,6),
    BDBASEPREV13 numeric(18,6),
    BDBASEPREVPLR numeric(18,6),
    BDBASEPREVRRA numeric(18,6),
    BDBASEPREVES numeric(18,6),
    BDBASEPREV13ES numeric(18,6),
    BDTIPO integer,
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDCATEGORIAESOCIAL integer,
    BDCODCLATRI integer,
    BDSEST numeric(18,6),
    BDSENAT numeric(18,6),
    BDSESTES numeric(18,6),
    BDSENATES numeric(18,6),
    BDCTS5001 integer,
    BDBASEFGTS13RESC numeric(9,2),
    BDVALORFGTS13RESC numeric(9,2),
    BDBASEFGTS13RESCES numeric(9,2),
    BDVALORFGTS13RESCES numeric(9,2),
    BDECONSIGNADO numeric(18,6),
    BDECONSIGNADORESC numeric(18,6),
    BDINSTITUICAOFINANC integer,
    BDNROCONTRATOECONSIGNADO varchar(30),
    BDINSTITUICAOFINANCES integer,
    BDNROCONTRATOECONSIGNADOES varchar(30),
    BDVALORECONSIGNADOES numeric(18,6),
    BDIND13PISES integer,
    BDTPVALORPISPASEPES integer,
    BDVALORPISPASEPES numeric(18,6),
    BDVALORPISPASEP13ES numeric(18,6),
    BDVALORPISPASEP numeric(18,6),
    BDVALORPISPASEP13 numeric(18,6),
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000))
as
declare variable WSQLPRINCIPAL varchar(30000);
declare variable WLISTAEMP varchar(30000);
declare variable WCPFANTERIOR varchar(14);
declare variable WULTDIA varchar(2);
declare variable WMES smallint;
declare variable WANO integer;
declare variable WCALCULOS integer;
declare variable WTEMEVENTO integer;
declare variable WTEMCALCFN integer;
declare variable WTEMCALCFT integer;
declare variable WSQL2 varchar(30000);
declare variable WTPADM integer;
declare variable WTEMCONFIGIMPOSTO integer;
declare variable WVERSAOLAYOUTESOCIAL varchar(10);
declare variable WCONTROLESUSPEND integer;
declare variable WEMPANTERIOR integer;
declare variable WVALVERBA13 numeric(18,6);
declare variable WINCIDENCIAPIS integer;
declare variable WCONTRATOTERC integer;
begin
end^

create or alter procedure SP_RETORNA_INSS_ES_AUT (
    PRCODEMP integer,
    PRCODTER integer,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODTER integer,
    BDBASEINSSES numeric(18,2),
    BDVALORINSSES numeric(18,2),
    BDVRCPSEG numeric(18,2),
    BDSESTES numeric(18,2),
    BDSENATES numeric(18,2),
    BDCTS5001 integer,
    BDIND13PIS integer,
    BDTPVALORPISPASEP integer,
    BDVALORPISPASEP numeric(18,6),
    BDVALORPISPASEP13 numeric(18,6),
    BDVERSAOLAYOUTESOCIAL varchar(10))
as
declare variable WSQL varchar(8000);
declare variable WVALOR numeric(18,2);
declare variable WTPVALOR integer;
declare variable WIND13PIS integer;
declare variable WTPVALORPISPASEP integer;
declare variable WVALORPISPASEP numeric(18,6);
declare variable WVERSAOLAYOUTESOCIAL varchar(10);
begin
  suspend;
end^

create or alter procedure SP_REL_TOT_5002_DIRF (
    PRCODEMP varchar(30000),
    PRREF integer,
    PRFILTROCPF varchar(30000),
    PRPRVEIODOTOTALIZADOR integer = 0,
    PRSEPARAFOLHAS integer = 0,
    PRRECTRAB integer = 0,
    PRGRAVACODIGORECEITA integer = 0,
    PRREFFIM integer = 0)
returns (
    BDCODEMPORD integer,
    BDREF integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCOLTER integer,
    BDCONTRCOL integer,
    BDGRUPOCLA integer,
    BDNOMCOL varchar(70),
    BDCPFCOL varchar(18),
    BDCNPJEMP varchar(18),
    BDNOMEMP varchar(100),
    BDBASEIRRF numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDVALORINSS numeric(18,6),
    BDTIPO integer,
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDCATEGORIAESOCIAL integer,
    BDCODCLATRI integer,
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOCALCULO integer,
    BDAJCUSTOS numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDUNICO integer,
    BDCODREC varchar(6))
as
declare variable WFILTROCPFAUTONOMO varchar(30000);
begin
  suspend;
end^

create or alter procedure SP_RETORNA_BASE_IRRF_CONSOLID_13 (
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRREFFIM integer,
    PRTIPO integer,
    PRVEIODOTOTALIZADOR integer,
    PRSEPARAFOLHAS integer,
    PRGRAVACODIGORECEITA integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBASEIRRFMENSAL numeric(18,6),
    BDVALORIRRFMENSAL numeric(18,6),
    BDINSSMENSAL numeric(18,6),
    BDAJCUSTOSMENSAL numeric(18,6),
    BDINDRESCMENSAL numeric(18,6),
    BDVALABOMENSAL numeric(18,6),
    BDRENDISENTOSMENSAL numeric(18,6),
    BDDRENDISENTOSMENSAL varchar(999),
    BDAUXILIOMORADIAMENSAL numeric(18,6),
    BDDIARIAMENSAL numeric(18,6),
    BDBOLSAMEDICOMENSAL numeric(18,6),
    BDJUROSMORAMENSAL numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDINSS13 numeric(18,6),
    BDAJCUSTOS13 numeric(18,6),
    BDINDRESC13 numeric(18,6),
    BDVALABO13 numeric(18,6),
    BDRENDISENTOS13 numeric(18,6),
    BDDRENDISENTOS13 varchar(999),
    BDAUXILIOMORADIA13 numeric(18,6),
    BDDIARIA13 numeric(18,6),
    BDBOLSAMEDICO13 numeric(18,6),
    BDJUROSMORA13 numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDINSSPLR numeric(18,6),
    BDAJCUSTOSPLR numeric(18,6),
    BDINDRESCPLR numeric(18,6),
    BDVALABOPLR numeric(18,6),
    BDRENDISENTOSPLR numeric(18,6),
    BDDRENDISENTOSPLR varchar(999),
    BDAUXILIOMORADIAPLR numeric(18,6),
    BDDIARIAPLR numeric(18,6),
    BDBOLSAMEDICOPLR numeric(18,6),
    BDJUROSMORAPLR numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDINSSRRA numeric(18,6),
    BDAJCUSTOSRRA numeric(18,6),
    BDINDRESCRRA numeric(18,6),
    BDVALABORRA numeric(18,6),
    BDRENDISENTOSRRA numeric(18,6),
    BDDRENDISENTOSRRA varchar(999),
    BDAUXILIOMORADIARRA numeric(18,6),
    BDDIARIARRA numeric(18,6),
    BDBOLSAMEDICORRA numeric(18,6),
    BDJUROSMORARRA numeric(18,6),
    BDCALCULOS integer,
    BDTIPOCALCULO integer,
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOFOLHA integer,
    BDCODREC varchar(6))
as
begin
  suspend;
end^

create or alter procedure SP_RETORNA_BASE_IRRF_CONSOLID_PLR (
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRREFFIM integer,
    PRTIPO integer,
    PRVEIODOTOTALIZADOR integer,
    PRSEPARAFOLHAS integer,
    PRGRAVACODIGORECEITA integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBASEIRRFMENSAL numeric(18,6),
    BDVALORIRRFMENSAL numeric(18,6),
    BDINSSMENSAL numeric(18,6),
    BDAJCUSTOSMENSAL numeric(18,6),
    BDINDRESCMENSAL numeric(18,6),
    BDVALABOMENSAL numeric(18,6),
    BDRENDISENTOSMENSAL numeric(18,6),
    BDDRENDISENTOSMENSAL varchar(999),
    BDAUXILIOMORADIAMENSAL numeric(18,6),
    BDDIARIAMENSAL numeric(18,6),
    BDBOLSAMEDICOMENSAL numeric(18,6),
    BDJUROSMORAMENSAL numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDINSS13 numeric(18,6),
    BDAJCUSTOS13 numeric(18,6),
    BDINDRESC13 numeric(18,6),
    BDVALABO13 numeric(18,6),
    BDRENDISENTOS13 numeric(18,6),
    BDDRENDISENTOS13 varchar(999),
    BDAUXILIOMORADIA13 numeric(18,6),
    BDDIARIA13 numeric(18,6),
    BDBOLSAMEDICO13 numeric(18,6),
    BDJUROSMORA13 numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDINSSPLR numeric(18,6),
    BDAJCUSTOSPLR numeric(18,6),
    BDINDRESCPLR numeric(18,6),
    BDVALABOPLR numeric(18,6),
    BDRENDISENTOSPLR numeric(18,6),
    BDDRENDISENTOSPLR varchar(999),
    BDAUXILIOMORADIAPLR numeric(18,6),
    BDDIARIAPLR numeric(18,6),
    BDBOLSAMEDICOPLR numeric(18,6),
    BDJUROSMORAPLR numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDINSSRRA numeric(18,6),
    BDAJCUSTOSRRA numeric(18,6),
    BDINDRESCRRA numeric(18,6),
    BDVALABORRA numeric(18,6),
    BDRENDISENTOSRRA numeric(18,6),
    BDDRENDISENTOSRRA varchar(999),
    BDAUXILIOMORADIARRA numeric(18,6),
    BDDIARIARRA numeric(18,6),
    BDBOLSAMEDICORRA numeric(18,6),
    BDJUROSMORARRA numeric(18,6),
    BDCALCULOS integer,
    BDTIPOCALCULO integer,
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOFOLHA integer,
    BDCODREC varchar(6))
as
begin
  suspend;
end^

create or alter procedure SP_RETORNA_BASE_IRRF_CONSOLID_RRA (
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRREFFIM integer,
    PRTIPO integer,
    PRVEIODOTOTALIZADOR integer,
    PRSEPARAFOLHAS integer,
    PRGRAVACODIGORECEITA integer = 0,
    PRSEPARAISENTOS integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBASEIRRFMENSAL numeric(18,6),
    BDVALORIRRFMENSAL numeric(18,6),
    BDINSSMENSAL numeric(18,6),
    BDAJCUSTOSMENSAL numeric(18,6),
    BDINDRESCMENSAL numeric(18,6),
    BDVALABOMENSAL numeric(18,6),
    BDRENDISENTOSMENSAL numeric(18,6),
    BDDRENDISENTOSMENSAL varchar(999),
    BDAUXILIOMORADIAMENSAL numeric(18,6),
    BDDIARIAMENSAL numeric(18,6),
    BDBOLSAMEDICOMENSAL numeric(18,6),
    BDJUROSMORAMENSAL numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDINSS13 numeric(18,6),
    BDAJCUSTOS13 numeric(18,6),
    BDINDRESC13 numeric(18,6),
    BDVALABO13 numeric(18,6),
    BDRENDISENTOS13 numeric(18,6),
    BDDRENDISENTOS13 varchar(999),
    BDAUXILIOMORADIA13 numeric(18,6),
    BDDIARIA13 numeric(18,6),
    BDBOLSAMEDICO13 numeric(18,6),
    BDJUROSMORA13 numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDINSSPLR numeric(18,6),
    BDAJCUSTOSPLR numeric(18,6),
    BDINDRESCPLR numeric(18,6),
    BDVALABOPLR numeric(18,6),
    BDRENDISENTOSPLR numeric(18,6),
    BDDRENDISENTOSPLR varchar(999),
    BDAUXILIOMORADIAPLR numeric(18,6),
    BDDIARIAPLR numeric(18,6),
    BDBOLSAMEDICOPLR numeric(18,6),
    BDJUROSMORAPLR numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDINSSRRA numeric(18,6),
    BDAJCUSTOSRRA numeric(18,6),
    BDINDRESCRRA numeric(18,6),
    BDVALABORRA numeric(18,6),
    BDRENDISENTOSRRA numeric(18,6),
    BDDRENDISENTOSRRA varchar(999),
    BDAUXILIOMORADIARRA numeric(18,6),
    BDDIARIARRA numeric(18,6),
    BDBOLSAMEDICORRA numeric(18,6),
    BDJUROSMORARRA numeric(18,6),
    BDCALCULOS integer,
    BDTIPOCALCULO integer,
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOFOLHA integer,
    BDCODREC varchar(6))
as
begin
  suspend;
end
^

create or alter procedure SP_RETORNA_BASE_IRRF_CONSOLID_MENSAL (
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRREFFIM integer,
    PRTIPO integer,
    PRVEIODOTOTALIZADOR integer,
    PRSEPARAFOLHAS integer,
    PRGRAVACODIGORECEITA integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBASEIRRFMENSAL numeric(18,6),
    BDVALORIRRFMENSAL numeric(18,6),
    BDINSSMENSAL numeric(18,6),
    BDAJCUSTOSMENSAL numeric(18,6),
    BDINDRESCMENSAL numeric(18,6),
    BDVALABOMENSAL numeric(18,6),
    BDRENDISENTOSMENSAL numeric(18,6),
    BDDRENDISENTOSMENSAL varchar(999),
    BDAUXILIOMORADIAMENSAL numeric(18,6),
    BDDIARIAMENSAL numeric(18,6),
    BDBOLSAMEDICOMENSAL numeric(18,6),
    BDJUROSMORAMENSAL numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDINSS13 numeric(18,6),
    BDAJCUSTOS13 numeric(18,6),
    BDINDRESC13 numeric(18,6),
    BDVALABO13 numeric(18,6),
    BDRENDISENTOS13 numeric(18,6),
    BDDRENDISENTOS13 varchar(999),
    BDAUXILIOMORADIA13 numeric(18,6),
    BDDIARIA13 numeric(18,6),
    BDBOLSAMEDICO13 numeric(18,6),
    BDJUROSMORA13 numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDINSSPLR numeric(18,6),
    BDAJCUSTOSPLR numeric(18,6),
    BDINDRESCPLR numeric(18,6),
    BDVALABOPLR numeric(18,6),
    BDRENDISENTOSPLR numeric(18,6),
    BDDRENDISENTOSPLR varchar(999),
    BDAUXILIOMORADIAPLR numeric(18,6),
    BDDIARIAPLR numeric(18,6),
    BDBOLSAMEDICOPLR numeric(18,6),
    BDJUROSMORAPLR numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDINSSRRA numeric(18,6),
    BDAJCUSTOSRRA numeric(18,6),
    BDINDRESCRRA numeric(18,6),
    BDVALABORRA numeric(18,6),
    BDRENDISENTOSRRA numeric(18,6),
    BDDRENDISENTOSRRA varchar(999),
    BDAUXILIOMORADIARRA numeric(18,6),
    BDDIARIARRA numeric(18,6),
    BDBOLSAMEDICORRA numeric(18,6),
    BDJUROSMORARRA numeric(18,6),
    BDCALCULOS integer,
    BDTIPOCALCULO integer,
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOFOLHA integer,
    BDCODREC varchar(6))
as
begin
  suspend;
end^

create or alter procedure SP_RETORNA_BASE_IRRF_CONSOLID (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRTIPO integer,
    PRVEIODOTOTALIZADOR integer,
    PRSEPARAFOLHAS integer,
    PRCODEMPORD integer,
    PRCODCLATRI integer = 0,
    PRGRAVACODIGORECEITA integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBASEIRRFMENSAL numeric(18,6),
    BDVALORIRRFMENSAL numeric(18,6),
    BDINSSMENSAL numeric(18,6),
    BDAJCUSTOSMENSAL numeric(18,6),
    BDINDRESCMENSAL numeric(18,6),
    BDVALABOMENSAL numeric(18,6),
    BDRENDISENTOSMENSAL numeric(18,6),
    BDDRENDISENTOSMENSAL varchar(999),
    BDAUXILIOMORADIAMENSAL numeric(18,6),
    BDDIARIAMENSAL numeric(18,6),
    BDBOLSAMEDICOMENSAL numeric(18,6),
    BDJUROSMORAMENSAL numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDINSS13 numeric(18,6),
    BDAJCUSTOS13 numeric(18,6),
    BDINDRESC13 numeric(18,6),
    BDVALABO13 numeric(18,6),
    BDRENDISENTOS13 numeric(18,6),
    BDDRENDISENTOS13 varchar(999),
    BDAUXILIOMORADIA13 numeric(18,6),
    BDDIARIA13 numeric(18,6),
    BDBOLSAMEDICO13 numeric(18,6),
    BDJUROSMORA13 numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDINSSPLR numeric(18,6),
    BDAJCUSTOSPLR numeric(18,6),
    BDINDRESCPLR numeric(18,6),
    BDVALABOPLR numeric(18,6),
    BDRENDISENTOSPLR numeric(18,6),
    BDDRENDISENTOSPLR varchar(999),
    BDAUXILIOMORADIAPLR numeric(18,6),
    BDDIARIAPLR numeric(18,6),
    BDBOLSAMEDICOPLR numeric(18,6),
    BDJUROSMORAPLR numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDINSSRRA numeric(18,6),
    BDAJCUSTOSRRA numeric(18,6),
    BDINDRESCRRA numeric(18,6),
    BDVALABORRA numeric(18,6),
    BDRENDISENTOSRRA numeric(18,6),
    BDDRENDISENTOSRRA varchar(999),
    BDAUXILIOMORADIARRA numeric(18,6),
    BDDIARIARRA numeric(18,6),
    BDBOLSAMEDICORRA numeric(18,6),
    BDJUROSMORARRA numeric(18,6),
    BDCALCULOS integer,
    BDTIPOCALCULO integer,
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOFOLHA integer,
    BDCODREC varchar(6))
as
declare variable WBASEIRRF numeric(18,6);
declare variable WVALORIRRF numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WAJCUSTOS numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDISENTOS numeric(18,6);
declare variable WDRENDISENTOS varchar(999);
declare variable WAUXILIOMORADIA numeric(18,6);
declare variable WDIARIA numeric(18,6);
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WJUROSMORA numeric(18,6);
declare variable WCALCULOS integer;
declare variable WTEMINFOCALCULO integer;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREFREEMBMED integer;
declare variable WTIPOFOL integer;
declare variable WDIFERENCIADORDATE date;
declare variable WDIFERENCIADORINTEGER integer;
declare variable WINTERMITENTE integer;
declare variable WINCIDESOCIAL integer;
declare variable WREFFC integer;
declare variable WDATAPGTO date;
declare variable WFC integer;
declare variable WREFPAG integer;
declare variable WREFREEMBMEDANT integer;
declare variable WORDEM integer;
declare variable WCODACCONV integer;
declare variable WCODACCONVANT integer;
declare variable WPRIMEIROREGADC integer;
declare variable WINCIDESOCIALFER integer;
declare variable WREFPLANSAU integer;
declare variable WREFPLANSAUANT integer;
declare variable WREFPREVIDCOMPL integer;
declare variable WREFPREVIDCOMPLANT integer;
declare variable WREF integer;
declare variable WCODFIR integer;
begin
  suspend;
end^

create or alter procedure SP_RETORNA_BASE_IRRF_CONSOLID_ES (
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRREFFIM integer,
    PRTERCEIRO varchar(5),
    PRGRAVACODIGORECEITA integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDINSSMENSALES numeric(18,6),
    BDBASEIRRFMENSALES numeric(18,6),
    BDVALORIRRFMENSALES numeric(18,6),
    BDAJCUSTOSMENSALES numeric(18,6),
    BDINDRESCMENSALES numeric(18,6),
    BDVALABOMENSALES numeric(18,6),
    BDRENDISENTOSMENSALES numeric(18,6),
    BDDRENDISENTOSMENSALES varchar(999),
    BDAUXILIOMORADIAMENSALES numeric(18,6),
    BDDIARIAMENSALES numeric(18,6),
    BDBOLSAMEDICOMENSALES numeric(18,6),
    BDJUROSMORAMENSALES numeric(18,6),
    BDTEMEVENTO integer,
    BDTIPOCALCULO integer)
as
declare variable WSQL varchar(1000);
declare variable WEVT integer;
declare variable WEVTANT integer;
declare variable WTIPOCALCFIR integer;
declare variable WCRMEN varchar(6);
declare variable WBASEIRFIR numeric(18,6);
declare variable WVALINSSFIR numeric(18,6);
declare variable WVALIRFIR numeric(18,6);
declare variable WVALINDFIR numeric(18,6);
declare variable WAJUDACUSTOFIR numeric(18,6);
declare variable WRENDISENTOSFIR numeric(18,6);
declare variable WDESCRENDISENTOSFIR varchar(999);
declare variable WVALABOFIR numeric(18,6);
declare variable WAUXILIOMORADIAFIR numeric(18,6);
declare variable WDIARIAFIR numeric(18,6);
declare variable WBOLSAMEDICOFIR numeric(18,6);
declare variable WJUROSMORAFIR numeric(18,6);
declare variable WTIPOCALCULO integer;
declare variable WTIPOCALCULOANT integer;
declare variable WTEMTIPOCALCULO1 integer;
declare variable WTEMTIPOCALCULO2 integer;
declare variable WTEMTIPOCALCULO3 integer;
declare variable WTEMTIPOCALCULO4 integer;
begin
  suspend;
end^

create or alter procedure SP_REL_TOT_5002 (
    PRCODEMP varchar(30000),
    PRREF integer,
    PRFILTROCPF varchar(30000),
    PRAUTONOMO boolean = false,
    PRPRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMPORD integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCOLTER integer,
    BDCONTRCOL integer,
    BDGRUPOCLA integer,
    BDNOMCOL varchar(70),
    BDCPFCOL varchar(18),
    BDCNPJEMP varchar(18),
    BDNOMEMP varchar(100),
    BDBASEIRRF numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDVALORINSS numeric(18,6),
    BDVRDEDDEP numeric(18,6),
    BDBASEPENSAO numeric(18,6),
    BDBASEPREV numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDVALORINSS13 numeric(18,6),
    BDVRDEDDEP13 numeric(18,6),
    BDBASEPENSAO13 numeric(18,6),
    BDBASEPREV13 numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDVALORINSSPLR numeric(18,6),
    BDVRDEDDEPPLR numeric(18,6),
    BDBASEPENSAOPLR numeric(18,6),
    BDBASEPREVPLR numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDVALORINSSRRA numeric(18,6),
    BDVRDEDDEPRRA numeric(18,6),
    BDBASEPENSAORRA numeric(18,6),
    BDBASEPREVRRA numeric(18,6),
    BDBASEIRRFES numeric(18,6),
    BDVALORIRRFES numeric(18,6),
    BDVALORINSSES numeric(18,6),
    BDVRDEDDEPES numeric(18,6),
    BDVRDEDDEPES13 numeric(18,6),
    BDBASEPENSAOES numeric(18,6),
    BDBASEPREVES numeric(18,6),
    BDBASEIRRF13ES numeric(18,6),
    BDVALORIRRF13ES numeric(18,6),
    BDVALORINSS13ES numeric(18,6),
    BDBASEPENSAO13ES numeric(18,6),
    BDBASEPREV13ES numeric(18,6),
    BDBASEIRRFPLRES numeric(18,6),
    BDVALORIRRFPLRES numeric(18,6),
    BDBASEPENSAOPLRES numeric(18,6),
    BDBASEIRRFRRAES numeric(18,6),
    BDVALORIRRFRRAES numeric(18,6),
    BDBASEPENSAORRAES numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSSES numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEINSS13ES numeric(18,6),
    BDVALORSALFAM numeric(18,6),
    BDVALORSALFAMES numeric(18,6),
    BDVALORSALMATEMP numeric(18,6),
    BDVALORSALMATEMPES numeric(18,6),
    BDVRCPSEG numeric(18,6),
    BDVALORIRRFFERIAS numeric(18,6),
    BDVALORIRRFFERIASES numeric(18,6),
    BDBASEIRRFFERIAS numeric(18,6),
    BDBASEIRRFFERIASES numeric(18,6),
    BDBASEFGTS numeric(18,6),
    BDBASEFGTSES numeric(18,6),
    BDVALORFGTS numeric(18,6),
    BDVALORFGTSES numeric(18,6),
    BDBASEFGTSRES numeric(18,6),
    BDBASEFGTSRESES numeric(18,6),
    BDVALORFGTSRES numeric(18,6),
    BDVALORFGTSRESES numeric(18,6),
    BDBASEAVPREV numeric(18,6),
    BDBASEAVPREVES numeric(18,6),
    BDVALORAVPREV numeric(18,6),
    BDVALORAVPREVES numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDBASEFGTS13ES numeric(18,6),
    BDVALORFGTS13 numeric(18,6),
    BDVALORFGTS13ES numeric(18,6),
    BDVRDEDDEPPLRES numeric(18,6),
    BDVRDEDDEPRRAES numeric(18,6),
    BDVALORINSSRRAES numeric(18,6),
    BDTIPO integer,
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDCATEGORIAESOCIAL integer,
    BDCODCLATRI integer,
    BDSEST integer,
    BDSENAT integer,
    BDSESTES integer,
    BDSENATES integer,
    BDCTS5001 integer,
    BDBASEFGTS13RESC numeric(9,2),
    BDBASEFGTS13RESCES numeric(9,2),
    BDVALORFGTS13RESC numeric(9,2),
    BDVALORFGTS13RESCES numeric(9,2),
    BDECONSIGNADO numeric(18,6),
    BDECONSIGNADORESC numeric(18,6),
    BDINSTITUICAOFINANC integer,
    BDNROCONTRATOECONSIGNADO varchar(30),
    BDINSTITUICAOFINANCES integer,
    BDNROCONTRATOECONSIGNADOES varchar(30),
    BDVALORECONSIGNADOES numeric(18,6),
    BDIND13PISES integer,
    BDTPVALORPISPASEPES integer,
    BDVALORPISPASEPES numeric(18,6),
    BDVALORPISPASEP13ES numeric(18,6),
    BDVALORPISPASEP numeric(18,6),
    BDVALORPISPASEP13 numeric(18,6),
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000))
as
declare variable WSQLPRINCIPAL varchar(30000);
declare variable WEMPCARREGADA integer;
declare variable WCPFANTERIOR varchar(18);
declare variable WCODMATRIZ integer;
declare variable WCNPJEMP varchar(18);
declare variable WCODEMP integer;
declare variable WLISTAEMP varchar(30000);
declare variable WNOMEMP varchar(100);
declare variable WCODCOL integer;
declare variable WNOMCOL varchar(100);
declare variable WCPFCOL varchar(18);
declare variable WCONTRCOL integer;
declare variable WULTDIA varchar(2);
declare variable WMES smallint;
declare variable WANO integer;
declare variable WCATESOCIAL integer;
declare variable WCODCLATRI integer;
declare variable WGRUPOCLA integer;
declare variable WVALORINSSES numeric(18,6);
declare variable WVALORINSS13ES numeric(18,6);
declare variable WVRDEDDEPES numeric(18,6);
declare variable WVRDEDDEP13ES numeric(18,6);
declare variable WBASEIRRFES numeric(18,6);
declare variable WBASEIRRF13ES numeric(18,6);
declare variable WBASEIRRFPLRES numeric(18,6);
declare variable WBASEIRRFRRAES numeric(18,6);
declare variable WBASEPREVES numeric(18,6);
declare variable WBASEPREV13ES numeric(18,6);
declare variable WBASEPENSAOES numeric(18,6);
declare variable WBASEPENSAO13ES numeric(18,6);
declare variable WBASEPENSAOPLRES numeric(18,6);
declare variable WBASEPENSAORRAES numeric(18,6);
declare variable WVALORIRRFES numeric(18,6);
declare variable WVALORIRRF13ES numeric(18,6);
declare variable WVALORIRRFPLRES numeric(18,6);
declare variable WVALORIRRFRRAES numeric(18,6);
declare variable WBASEIRRF numeric(18,6);
declare variable WVALORIRRF numeric(18,6);
declare variable WVALORINSS numeric(18,6);
declare variable WVRDEDDEP numeric(18,6);
declare variable WBASEPENSAO numeric(18,6);
declare variable WBASEPREV numeric(18,6);
declare variable WBASEIRRF13 numeric(18,6);
declare variable WVALORIRRF13 numeric(18,6);
declare variable WVALORINSS13 numeric(18,6);
declare variable WVRDEDDEP13 numeric(18,6);
declare variable WBASEPENSAO13 numeric(18,6);
declare variable WBASEPREV13 numeric(18,6);
declare variable WBASEIRRFPLR numeric(18,6);
declare variable WVALORIRRFPLR numeric(18,6);
declare variable WVALORINSSPLR numeric(18,6);
declare variable WVRDEDDEPPLR numeric(18,6);
declare variable WBASEPENSAOPLR numeric(18,6);
declare variable WBASEPREVPLR numeric(18,6);
declare variable WBASEIRRFRRA numeric(18,6);
declare variable WVALORIRRFRRA numeric(18,6);
declare variable WVALORINSSRRA numeric(18,6);
declare variable WVRDEDDEPRRA numeric(18,6);
declare variable WBASEPENSAORRA numeric(18,6);
declare variable WBASEPREVRRA numeric(18,6);
declare variable WVRDEDDEPPLRES numeric(18,6);
declare variable WVRDEDDEPRRAES numeric(18,6);
declare variable WVALORINSSRRAES numeric(18,6);
declare variable WTEMEVENTO integer;
declare variable WTEMCALCFN integer;
declare variable WCALCULOS integer;
declare variable WTEMCALCFT integer;
declare variable WCODCOLANT integer;
declare variable WREFEMP integer;
begin
end
^

create or alter procedure SP_VALIDA_VALORES_1_3_FERIAS (
    PRCODIGOEMP varchar(200),
    PRCODIGOCOL varchar(200),
    PRANOCALCULO varchar(4))
returns (
    BDAPRESENTAMENSAGEM varchar(5),
    BDCODEMP integer,
    BDCODCOL integer)
as
declare variable WCODIGOEMP integer;
declare variable WCODIGOCOL integer;
declare variable WSQL varchar(1000);
begin
end
^

create or alter procedure SP_REL_TOT_5003 (
    PRCODEMP varchar(30000),
    PRREF integer,
    PR13 integer,
    PRFILTROCPF varchar(30000))
returns (
    BDCODEMPORD integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCOLTER integer,
    BDCONTRCOL integer,
    BDGRUPOCLA integer,
    BDNOMCOL varchar(70),
    BDCPFCOL varchar(14),
    BDCNPJEMP varchar(18),
    BDNOMEMP varchar(100),
    BDBASEINSS numeric(18,6),
    BDBASEINSSES numeric(18,6),
    BDVALORINSS numeric(18,6),
    BDVALORINSSES numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEINSS13ES numeric(18,6),
    BDVALORINSS13 numeric(18,6),
    BDVALORINSS13ES numeric(18,6),
    BDVALORSALFAM numeric(18,6),
    BDVALORSALFAMES numeric(18,6),
    BDVALORSALMATEMP numeric(18,6),
    BDVALORSALMATEMPES numeric(18,6),
    BDVRCPSEG numeric(18,6),
    BDVRDEDDEP numeric(18,6),
    BDVRDEDDEPES numeric(18,6),
    BDBASEPENSAO numeric(18,6),
    BDBASEPENSAOES numeric(18,6),
    BDBASEIRRF numeric(18,6),
    BDBASEIRRFES numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDBASEIRRF13ES numeric(18,6),
    BDBASEIRRFFERIAS numeric(18,6),
    BDBASEIRRFFERIASES numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDBASEIRRFPLRES numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDVALORIRRFES numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDVALORIRRF13ES numeric(18,6),
    BDVALORIRRFFERIAS numeric(18,6),
    BDVALORIRRFFERIASES numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDVALORIRRFPLRES numeric(18,6),
    BDBASEFGTS numeric(18,6),
    BDBASEFGTSES numeric(18,6),
    BDVALORFGTS numeric(18,6),
    BDVALORFGTSES numeric(18,6),
    BDBASEFGTSRES numeric(18,6),
    BDBASEFGTSRESES numeric(18,6),
    BDVALORFGTSRES numeric(18,6),
    BDVALORFGTSRESES numeric(18,6),
    BDBASEAVPREV numeric(18,6),
    BDBASEAVPREVES numeric(18,6),
    BDVALORAVPREV numeric(18,6),
    BDVALORAVPREVES numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDBASEFGTS13ES numeric(18,6),
    BDVALORFGTS13 numeric(18,6),
    BDVALORFGTS13ES numeric(18,6),
    BDVALORINSSPLR numeric(18,6),
    BDVALORINSSRRA numeric(18,6),
    BDVRDEDDEP13 numeric(18,6),
    BDVRDEDDEPES13 numeric(18,6),
    BDVRDEDDEPPLR numeric(18,6),
    BDVRDEDDEPRRA numeric(18,6),
    BDBASEPENSAO13 numeric(18,6),
    BDBASEPENSAO13ES numeric(18,6),
    BDBASEPENSAOPLR numeric(18,6),
    BDBASEPENSAOPLRES numeric(18,6),
    BDBASEPENSAORRA numeric(18,6),
    BDBASEPENSAORRAES numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDBASEIRRFRRAES numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDVALORIRRFRRAES numeric(18,6),
    BDVRDEDDEPPLRES numeric(18,6),
    BDVRDEDDEPRRAES numeric(18,6),
    BDVALORINSSRRAES numeric(18,6),
    BDBASEPREV numeric(18,6),
    BDBASEPREV13 numeric(18,6),
    BDBASEPREVPLR numeric(18,6),
    BDBASEPREVRRA numeric(18,6),
    BDBASEPREVES numeric(18,6),
    BDBASEPREV13ES numeric(18,6),
    BDTIPO integer,
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDCATEGORIAESOCIAL integer,
    BDCODCLATRI integer,
    BDSEST integer,
    BDSENAT integer,
    BDSESTES integer,
    BDSENATES integer,
    BDCTS5001 integer,
    BDBASEFGTS13RESCES numeric(18,6),
    BDVALORFGTS13RESCES numeric(18,6),
    BDBASEFGTS13RESC numeric(18,6),
    BDVALORFGTS13RESC numeric(18,6),
    BDECONSIGNADO numeric(18,6),
    BDECONSIGNADORESC numeric(18,6),
    BDINSTITUICAOFINANC integer,
    BDNROCONTRATOECONSIGNADO varchar(30),
    BDINSTITUICAOFINANCES integer,
    BDNROCONTRATOECONSIGNADOES varchar(30),
    BDVALORECONSIGNADOES numeric(18,6),
    BDIND13PISES integer,
    BDTPVALORPISPASEPES integer,
    BDVALORPISPASEPES numeric(18,6),
    BDVALORPISPASEP13ES numeric(18,6),
    BDVALORPISPASEP numeric(18,6),
    BDVALORPISPASEP13 numeric(18,6),
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000))
as
declare variable WSQLPRINCIPAL varchar(30000);
declare variable WEMPCARREGADA integer;
declare variable WCPFANTERIOR varchar(14);
declare variable WCODMATRIZ integer;
declare variable WCNPJEMP varchar(18);
declare variable WCODEMP integer;
declare variable WLISTAEMP varchar(30000);
declare variable WNOMEMP varchar(100);
declare variable WCODCOL integer;
declare variable WNOMCOL varchar(100);
declare variable WCPFCOL varchar(14);
declare variable WCONTRCOL integer;
declare variable WULTDIA varchar(2);
declare variable WMES smallint;
declare variable WANO integer;
declare variable WCATESOCIAL integer;
declare variable WCODCLATRI integer;
declare variable WGRUPOCLA integer;
declare variable WBASEFGTS numeric(18,6);
declare variable WBASEFGTS13 numeric(18,6);
declare variable WBASEFGTSRES numeric(18,6);
declare variable WBASEAVPREV numeric(18,6);
declare variable WVALORFGTS numeric(18,6);
declare variable WVALORFGTS13 numeric(18,6);
declare variable WVALORFGTSRES numeric(18,6);
declare variable WVALORAVPREV numeric(18,6);
declare variable WBASEFGTSES numeric(18,6);
declare variable WBASEFGTS13ES numeric(18,6);
declare variable WBASEFGTSRESES numeric(18,6);
declare variable WBASEAVPREVES numeric(18,6);
declare variable WVALORFGTSES numeric(18,6);
declare variable WVALORFGTS13ES numeric(18,6);
declare variable WVALORFGTSRESES numeric(18,6);
declare variable WVALORAVPREVES numeric(18,6);
declare variable WCALCULOS integer;
declare variable WTEMEVENTO integer;
declare variable WTEMCALCFN integer;
declare variable WTEMCALCFT integer;
declare variable WSQL2 varchar(30000);
declare variable WCATEGORIAESOCIAL integer;
declare variable WCATESOCIALCARREGADA integer;
declare variable WMATRICULAATUAL varchar(30);
declare variable WMATRICULAANTERIOR varchar(30);
declare variable WBASEFGTS13RESC numeric(18,6);
declare variable WVALORFGTS13RESC numeric(18,6);
declare variable WBASEFGTS13RESCES numeric(18,6);
declare variable WVALORFGTS13RESCES numeric(18,6);
begin
end^

create or alter procedure VRH_SP_ATUALIZA_IR_EVENTO
returns(
BDCODEMP integer,
BDCODEVTATUALIZADO integer
)
as
declare variable WSQL varchar(10000);
declare variable WCODEVT integer;
declare variable WCODEMP integer;
declare variable WVALOR numeric(18,2);
declare variable WXML varchar(30000);
declare variable WSTR varchar (30000);
begin
end^

create or alter procedure SP_VRH_ATU_REGTRAB
returns(
BDCODEMP integer,
BDCODCOL integer,
BDREF integer
)
as
declare variable WSQL varchar(10000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WREGTRAB integer;
declare variable WCATESOCIAL integer;
begin
end^

create or alter procedure SP_ATU_PARAMCONTCC
as
declare variable WCODMAT integer;
declare variable WCODEMP integer;
declare variable WREFEMP integer;
declare variable WNAOCONTCENTROCUSTO VARCHAR(5);
begin
end^



CREATE OR ALTER procedure SP_RELDEMRECDESP (
    PRCODESC varchar(500),
    PRTIPODEM integer,
    PRDATAINICIAL varchar(10),
    PRDATAFINAL varchar(10),
    PRCHAVECTABAN varchar(500),
    PRCODOBRSER varchar(10240),
    PRCODDESP varchar(10240),
    PRNIVEL integer,
    PRTIPORECDESP integer,
    PRDEMLANCREEMBOLSO DM_BOOLEAN,
    PRDEMTRANSFBANCARIAS DM_BOOLEAN,
    PRCODCLI varchar(10240),
    PRCODFOR varchar(10240),
    PRMODELO integer)
as
declare variable VULTDIAMES integer;
declare variable VPERIODOFINAL varchar(10);
declare variable VPERIODOINICIAL varchar(10);
declare variable VPOSICAOPONTO integer;
declare variable VSQLSERDESP varchar(10240);
declare variable VSQL varchar(10240);
declare variable VSTOP varchar(5);
declare variable VCLASSAUX varchar(60);
declare variable VCODSERDESPAUX integer;
declare variable VGUARDASERDESP varchar(10240);
declare variable VTIPOSERDESP integer;
declare variable VDESCSERDESP varchar(100);
declare variable VCLASSSERDESP varchar(60);
declare variable VCODSERDESP integer;
declare variable VNUMPERIODO integer;
declare variable VPERIODO01 varchar(12);
declare variable VVLRPERIODO01 numeric(15,2);
declare variable VPERIODO02 varchar(12);
declare variable VVLRPERIODO02 numeric(15,2);
declare variable VPERIODO03 varchar(12);
declare variable VVLRPERIODO03 numeric(15,2);
declare variable VPERIODO04 varchar(12);
declare variable VVLRPERIODO04 numeric(15,2);
declare variable VPERIODO05 varchar(12);
declare variable VVLRPERIODO05 numeric(15,2);
declare variable VPERIODO06 varchar(12);
declare variable VVLRPERIODO06 numeric(15,2);
declare variable VPERIODO07 varchar(12);
declare variable VVLRPERIODO07 numeric(15,2);
declare variable VPERIODO08 varchar(12);
declare variable VVLRPERIODO08 numeric(15,2);
declare variable VPERIODO09 varchar(12);
declare variable VVLRPERIODO09 numeric(15,2);
declare variable VPERIODO10 varchar(12);
declare variable VVLRPERIODO10 numeric(15,2);
declare variable VPERIODO11 varchar(12);
declare variable VVLRPERIODO11 numeric(15,2);
declare variable VPERIODO12 varchar(12);
declare variable VVLRPERIODO12 numeric(15,2);
declare variable VVLRTOTPERIODO numeric(15,2);
declare variable VDESCONTO varchar(5);
declare variable VSQLCLIFOR varchar(20000);
declare variable VCODCLIFORATUAL integer;
declare variable VCOUNT integer;
begin
END^

create or alter procedure SP_FLUXOCAIXA (
    PRCHAVECTABAN varchar(10000),
    PRDATAINI varchar(10),
    PRDATAFIN varchar(10),
    PRFLAGPROC integer)
returns (
    BDTIPO integer,
    BDCODCLI integer,
    BDNOMCLI varchar(100),
    BDSERIE varchar(6),
    BDREFFAT integer,
    BDCHAVECTABAN integer,
    BDDATAVENC date,
    BDDESCCTABAN varchar(200),
    BDVALORPREV numeric(15,2),
    BDVALORREAL numeric(15,2),
    BDSALDOANT numeric(15,2),
    BDSALDOATUAL numeric(15,2),
    BDCODFOR integer,
    BDNOMEFOR varchar(100),
    BDCHAVECTAPAG integer,
    BDNUMPARC varchar(50),
    BDREFLANC integer,
    BDOBS varchar(1024),
    BDDATARECPAG date)
as
declare variable WCHAVECTABAN integer;
declare variable WSQL varchar(15000);
declare variable WREF varchar(6);
declare variable WSALDOANT numeric(15,2);
begin
end^

CREATE OR ALTER procedure SP_RELDEMRECDESP_RECPREV (
    PRTIPODEM integer,
    PRNIVEL integer,
    PRREFINI varchar(6),
    PRREFFIM varchar(6),
    PRCODOBRSER varchar(10240),
    PRCODCLI varchar(10240),
    PRMODELO integer,
    PRFLAGPROC integer)
as
declare variable VREFINI varchar(6);
declare variable VREFFIM varchar(6);
declare variable VPOSICAOPONTO integer;
declare variable VSQLSER varchar(10240);
declare variable VSQL varchar(10240);
declare variable VSTOP varchar(5);
declare variable VCLASSAUX varchar(60);
declare variable VCODSERDESPAUX integer;
declare variable VGUARDASERDESP varchar(10240);
declare variable VTIPOSERDESP integer;
declare variable VDESCSERDESP varchar(100);
declare variable VCLASSSERDESP varchar(60);
declare variable VCODSER integer;
declare variable VNUMPERIODO integer;
declare variable VPERIODO01 varchar(12);
declare variable VVLRPERIODO01 numeric(15,2);
declare variable VPERIODO02 varchar(12);
declare variable VVLRPERIODO02 numeric(15,2);
declare variable VPERIODO03 varchar(12);
declare variable VVLRPERIODO03 numeric(15,2);
declare variable VPERIODO04 varchar(12);
declare variable VVLRPERIODO04 numeric(15,2);
declare variable VPERIODO05 varchar(12);
declare variable VVLRPERIODO05 numeric(15,2);
declare variable VPERIODO06 varchar(12);
declare variable VVLRPERIODO06 numeric(15,2);
declare variable VPERIODO07 varchar(12);
declare variable VVLRPERIODO07 numeric(15,2);
declare variable VPERIODO08 varchar(12);
declare variable VVLRPERIODO08 numeric(15,2);
declare variable VPERIODO09 varchar(12);
declare variable VVLRPERIODO09 numeric(15,2);
declare variable VPERIODO10 varchar(12);
declare variable VVLRPERIODO10 numeric(15,2);
declare variable VPERIODO11 varchar(12);
declare variable VVLRPERIODO11 numeric(15,2);
declare variable VPERIODO12 varchar(12);
declare variable VVLRPERIODO12 numeric(15,2);
declare variable VVLRTOTPERIODO numeric(15,2);
declare variable VDESCONTO varchar(5);
declare variable VDATAREF varchar(10);
declare variable VSQLCLIENTES varchar(20000);
declare variable VCODCLIATUAL integer;
begin
END^

CREATE OR ALTER procedure SP_RELDEMRECDESP_DESPPREV (
    PRCODESC varchar(500),
    PRTIPODEM integer,
    PRREFINI varchar(6),
    PRREFFIM varchar(6),
    PRCHAVECTABAN varchar(500),
    PRCODDESP varchar(10240),
    PRNIVEL integer,
    PRCODFOR varchar(10240),
    PRMODELO integer)
as
declare variable VREFINI varchar(6);
declare variable VREFFIM varchar(6);
declare variable VPOSICAOPONTO integer;
declare variable VSQLSERDESP varchar(10240);
declare variable VSQL varchar(10240);
declare variable VSTOP varchar(5);
declare variable VCLASSAUX varchar(60);
declare variable VCODSERDESPAUX integer;
declare variable VGUARDASERDESP varchar(10240);
declare variable VTIPOSERDESP integer;
declare variable VDESCSERDESP varchar(100);
declare variable VCLASSSERDESP varchar(60);
declare variable VCODDESP integer;
declare variable VNUMPERIODO integer;
declare variable VPERIODO01 varchar(12);
declare variable VVLRPERIODO01 numeric(15,2);
declare variable VPERIODO02 varchar(12);
declare variable VVLRPERIODO02 numeric(15,2);
declare variable VPERIODO03 varchar(12);
declare variable VVLRPERIODO03 numeric(15,2);
declare variable VPERIODO04 varchar(12);
declare variable VVLRPERIODO04 numeric(15,2);
declare variable VPERIODO05 varchar(12);
declare variable VVLRPERIODO05 numeric(15,2);
declare variable VPERIODO06 varchar(12);
declare variable VVLRPERIODO06 numeric(15,2);
declare variable VPERIODO07 varchar(12);
declare variable VVLRPERIODO07 numeric(15,2);
declare variable VPERIODO08 varchar(12);
declare variable VVLRPERIODO08 numeric(15,2);
declare variable VPERIODO09 varchar(12);
declare variable VVLRPERIODO09 numeric(15,2);
declare variable VPERIODO10 varchar(12);
declare variable VVLRPERIODO10 numeric(15,2);
declare variable VPERIODO11 varchar(12);
declare variable VVLRPERIODO11 numeric(15,2);
declare variable VPERIODO12 varchar(12);
declare variable VVLRPERIODO12 numeric(15,2);
declare variable VVLRTOTPERIODO numeric(15,2);
declare variable VDESCONTO varchar(5);
declare variable VDATAREF varchar(10);
declare variable VSQLFORNECEDORES varchar(2000);
declare variable VCODFORATUAL integer;
begin
END^


CREATE OR ALTER PROCEDURE SP_INSERIR_OBS_FINANCEIRA (
    PRCODESC INTEGER)
AS
BEGIN
END^

SET TERM ; ^

DROP TRIGGER vef_base_tcadinfcom_bu0;

DROP VIEW VW_VRHF_EMP_TPROVISAOFERIAS_CC;

DROP PROCEDURE SP_VALIDA_CNPJ;

DROP PROCEDURE SP_VALIDA_CPF;

DROP PROCEDURE SP_ATUALIZAR_TMP_TMOVSAI;

DROP PROCEDURE SP_ATUALIZAR_TMP_TMOVSAIITENS;

DROP PROCEDURE SP_ATUALIZAR_TMP_MOVCCSAI;

DROP PROCEDURE SP_COMMIT_UNIDADEMEDIDA;

DROP PROCEDURE SP_INSERT_OR_UPDATE_TCADPRO;

DROP PROCEDURE SP_INSERT_OR_UPDATE_TTERCEIRO;

DROP PROCEDURE REF_SEGUINTE;

DROP PROCEDURE RETIRA_ACENTO;

DROP PROCEDURE RETIRA_CHAR_ESPECIAL;


SET TERM ^ ;

ALTER TRIGGER VEF_ESTADOS_TCONFGIAMGQ_BU0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

SET TERM ; ^

DROP PROCEDURE RPOS;

DROP PROCEDURE SONUMEROS;

DROP PROCEDURE SOLETRAS;

DROP PROCEDURE SP_AFASTADOS;

DROP PROCEDURE SP_AFASTADOS_MES_INTEIRO;

DROP PROCEDURE SP_ALTERA_TIPO_COLCON;

DROP PROCEDURE SP_ATI_SEM_AFAST_MES_INT;

DROP PROCEDURE SP_ATI_SEM_DEM_COM_TRANSF;

DROP PROCEDURE SP_ATIVOS_SEM_DEMITIDOS_MES;

DROP PROCEDURE SP_ATU_CAMPOS_GERADOR;

DROP PROCEDURE SP_ATU_CATEGORIA;

DROP PROCEDURE SP_ATU_CODREC;

DROP PROCEDURE SP_FLUXOCAIXA;

SET TERM ^ ;

ALTER TRIGGER VRHF_EMP_T13SAL_AU0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

SET TERM ; ^

DROP PROCEDURE SP_ATU_FGTS_CONT_13;

SET TERM ^ ;

ALTER TRIGGER VRHF_EMP_TA13SAL_AU0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TA13SAL_BI0 FOR VRHF_EMP_TA13SAL
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END
^

SET TERM ; ^

DROP PROCEDURE SP_ATU_FGTS_CONT_A13;

SET TERM ^ ;

ALTER TRIGGER VRHF_EMP_TC13SAL_AU0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

SET TERM ; ^

DROP PROCEDURE SP_ATU_FGTS_CONT_C13;

DROP PROCEDURE SP_ATU_FGTS_CONT_FA;

SET TERM ^ ;

ALTER TRIGGER VRHF_EMP_TFOLHACOMP_AU0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VRHF_EMP_TFOLTOMCOMP_AU0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

SET TERM ; ^

DROP PROCEDURE SP_ATU_FGTS_CONT_FC;

DROP PROCEDURE SP_ATU_FGTS_CONT_FN;

SET TERM ^ ;

ALTER TRIGGER TCONF_CONTAS_ONLINE_AU0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

SET TERM ; ^

DROP PROCEDURE SP_ATU_LANCAMENTOS_CONTABIL;

DROP PROCEDURE SP_REMOVER_VAR_COMPLEMENTO;

SET TERM ^ ;

ALTER TRIGGER TEMPRESAS_REF_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TEMPRESAS_REF_AI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER PROCEDURE SP_IMPORTACAO_SEM_PART (
    PRSESSAO INTEGER)
AS
BEGIN

END^

create or alter procedure SP_CANCELAR_LAN_BASE_ENT (
    PRSESSAO integer,
    PRCODEMP integer,
    PREXCLUIRLAN DM_BOOLEAN)
as
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_TCADPRO (
    PRSESSAO integer not null,
    PRLANCAMENTOMANUAL DM_BOOLEAN not null,
    PRGERARINCONSISTENCIAS DM_BOOLEAN not null,
    PRREF integer,
    PRCODEMP integer,
    PRIDTERMINAL integer,
    PRALTERARSIT DM_BOOLEAN,
    PRALTERACST DM_BOOLEAN,
    PRISSEGREG DM_BOOLEAN)
AS
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_INS_UPT_TMP_TCADPRO (
    PRSESSAO INTEGER,
    PRREF INTEGER,
    PRCODSAIDA VARCHAR(60),
    PRCODENTRADA VARCHAR(60),
    PRCODPROD INTEGER,
    PRCODEMP INTEGER,
    PRCODTER INTEGER,
    PRCNPJTER VARCHAR(20),
    PRIETER VARCHAR(20),
    PRDESCPROD VARCHAR(200),
    PRORIGEMPROD INTEGER,
    PROPERATION VARCHAR(4),
    PRSEQ_PART INTEGER,
    PRINS_PROUNICO DM_BOOLEAN)
AS
BEGIN
END
^

create or alter procedure SP_GET_PRODUTO_IMP (
    PRCODEMP integer,
    PRSESSAO integer,
    PRSESSAOTER integer,
    PRCODPRODARQ varchar(60),
    PRCNPJTER varchar(18),
    PRIETER varchar(20),
    PRDESCPROD varchar(200),
    PRNOMETER varchar(100),
    PRVER_ENT_E_SAI varchar(5),
    PRCODTER integer,
    PRCODPRODVINC integer)
RETURNS (
    BDCODPROD INTEGER,
    BDDESCPROD VARCHAR(200))
AS
BEGIN
END
^

CREATE OR ALTER PROCEDURE SP_GERAR_INCON_TCADPRO (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRCODPLANOINCO INTEGER,
    PRREF INTEGER,
    PRIDTERMINAL INTEGER)
AS
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_PREPARA_PLANOTROCA_IMP (
    PRSESSAO INTEGER,
    PRTIPOMOV VARCHAR(3),
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_GERAR_PARCELAS_AUT (
    PRSESSAO INTEGER,
    PRTIPOMOV VARCHAR(3),
    PRCODEMP INTEGER,
    PRREF INTEGER,
    PRPLANOTROCA VARCHAR(5) = 'FALSE')
AS
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_REFAZER_PARCELAMENTO (
    PRCODEMP INTEGER NOT NULL,
    PRCHAVE INTEGER NOT NULL,
    PRORDEMPARALT INTEGER NOT NULL,
    PRNOVOVALOR DM_NUMERIC_15_2 NOT NULL,
    PRREF INTEGER,
    PRTIPOLAN CHAR(3))
RETURNS (
    BDORDEMPAR INTEGER,
    BDVALORPAR DM_NUMERIC_15_2,
    BDVALORRETPIS DM_NUMERIC_15_2,
    BDVALORRETCOFINS DM_NUMERIC_15_2,
    BDVALORRETCSLL DM_NUMERIC_15_2,
    BDVALORRETIRRF DM_NUMERIC_15_2,
    BDVALORRETISSQN DM_NUMERIC_15_2,
    BDVALORRETINSS DM_NUMERIC_15_2)
AS
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_VALIDAR_TRANSFERENCIA (
    PRID_TERMINAL INTEGER,
    PRCODEMPORI INTEGER,
    PRCODEMPDEST INTEGER,
    PRREFTRANS INTEGER,
    PRTIPOLAN CHAR(3))
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_TRANSFERENCIA_LAN (
    PRID_TERMINAL INTEGER,
    PRCODEMPORI INTEGER,
    PRCODEMPDEST INTEGER,
    PRREFTRANS INTEGER,
    PRTIPOLAN CHAR(3))
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_TRANSFERENCIA_PRODUTOS (
    PRID_TERMINAL INTEGER,
    PRCODEMPORI INTEGER,
    PRCODEMPDEST INTEGER,
    PRREFTRANS INTEGER,
    PRTIPOLAN CHAR(3))
AS
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_TRANSFERENCIA_RATEIO (
    PRID_TERMINAL INTEGER,
    PRCODEMPORI INTEGER,
    PRCODEMPDEST INTEGER,
    PRREFTRANS INTEGER,
    PRTIPOLAN CHAR(3))
AS
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_GRAVAR_LAN (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRTIPOLAN CHAR(3))
AS BEGIN  END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_REDZC425 (
    PRSESSAO INTEGER,
    PRSESSAOPRO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_TREDZC425ALIQ (
    PRSESSAO INTEGER,
    PRSESSAOPRO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS
BEGIN

END^


CREATE OR ALTER procedure SP_ATUALIZAR_TMP_TREDZC425AQISS (
    PRSESSAO integer,
    PRSESSAOPRO integer,
    PRCODEMP integer,
    PRREF integer)
AS
BEGIN

END^

CREATE OR ALTER trigger vrh_emp_tcol_she_bi0 for vrh_emp_tcol_she
active before insert position 0
AS
BEGIN

END
^

CREATE OR ALTER trigger vrh_emp_tcol_she_bu0 for vrh_emp_tcol_she
active before update position 0
AS
BEGIN

END
^

CREATE OR ALTER trigger vrh_emp_tcolcon_calcdia_bu0 for vrh_emp_tcol_she
active before insert position 0
AS
BEGIN

END
^

CREATE OR ALTER procedure SP_EXPORTA_DRCSTSP_0150 (
    PRCODEMP integer,
    PRREF integer,
    PRREFINI integer,
    PRFINALIDADE integer,
    PRARQUIVO varchar(260))
as
begin
end^

SET TERM ; ^

DROP PROCEDURE SP_ATUALIZAR_TMP_TCADPRO;

DROP PROCEDURE SP_INS_UPT_TMP_TCADPRO;

DROP PROCEDURE SP_GET_PRODUTO_IMP;

DROP PROCEDURE SP_GERAR_INCON_TCADPRO;

DROP PROCEDURE SP_PREPARA_PLANOTROCA_IMP;

DROP PROCEDURE SP_GERAR_PARCELAS_AUT;

DROP PROCEDURE SP_AUTONOMO_SEFIP;

DROP PROCEDURE SP_BENEFICIARIOS_COLABORADOR;

DROP PROCEDURE SP_CALC_DEPRECIACAO;

DROP PROCEDURE DIFERENCA_MESES;

DROP PROCEDURE SP_CALC_EXP_SEFIP;

DROP PROCEDURE SP_CALC_EXP_SEFIP_COMPLEMENTAR;

DROP PROCEDURE SP_IMPORTACAO_SEM_PART;

DROP PROCEDURE SP_CANCELAR_LAN_BASE_ENT;

--DROP VIEW VW_VRH_EMP_SEM_VALORES_TCONV;

--DROP VIEW VW_VRHM_EMP_VAL_TOD_OP_ATU;

--DROP VIEW VW_VRHM_EMP_VAL_COL_OP_ATU;

--DROP VIEW VW_VRHM_EMP_COL_VAL_OP_SAU;

--DROP VIEW VW_VRH_EMP_IDADE_COL;

--DROP VIEW VW_VRHM_EMP_VAL_DEP_OP_ATU;

--DROP VIEW VW_VRHM_EMP_DEP_VAL_OP_SAU;

--DROP VIEW VW_VRH_EMP_IDADE_COL_DEP;

--DROP PROCEDURE SP_CALC_IDADE;

DROP PROCEDURE SP_RETORNA_MAIOR_ZERO;

DROP PROCEDURE SP_COLABORADOR_SEFIP;

DROP PROCEDURE SP_COMP_ACUMULADO_GPS;

DROP PROCEDURE SP_COMPOSICAO_RECURSOS_HUMANOS;

DROP PROCEDURE SP_CONS_CALC_DEP;

DROP PROCEDURE SP_CONS_CALC_DEP_CORRECAO;

DROP PROCEDURE SP_CONS_FERIAS_PER_AQUIS_ESCALA;

DROP PROCEDURE SP_VRHF_LISTAPERAQUISFE;

DROP PROCEDURE SP_CONSULTA_COL_POR_REF;

DROP PROCEDURE SP_CONSULTA_EMP_POR_REF;

DROP PROCEDURE SP_CONSULTA_PLANO_CONTAS;

DROP PROCEDURE SP_CONSULTA_TERCEIRO;

DROP PROCEDURE SP_CONSULTA_TERCEIRO_MATRIZ;

DROP PROCEDURE SP_CONSULTACIDADE;

DROP PROCEDURE SP_CONSULTAEMPRESAS;

DROP PROCEDURE SP_CONSULTAEMPRESAS_SEARCH;

DROP PROCEDURE SP_EXPORTA_ECREDAC;

DROP PROCEDURE SP_EXPORTA_DIMOB;
DROP PROCEDURE SP_VALIDA_EXPORTACAO_SPED;
DROP PROCEDURE SP_VALIDA_EXP_SER;
DROP PROCEDURE SP_GET_FCP;
DROP PROCEDURE SP_EXPORTA_BLOCOC_ENT;
DROP PROCEDURE SP_EXPORTA_BLOCOC_ENT_AUX;
DROP PROCEDURE SP_EXPORTA_BLOCOC_SAI;
DROP PROCEDURE SP_EXPORTA_BLOCOC_SAI_AUX;
DROP PROCEDURE SP_EXPORTA_BLOCOC500;
DROP PROCEDURE SP_EXPORTA_BLOCOC_SER;
DROP PROCEDURE SP_EXPORTA_BLOCOC;
DROP PROCEDURE SP_EXPORTA_BLOCOC1250;
DROP PROCEDURE SP_EXPORTA_BLOCOD_ENT;
DROP PROCEDURE SP_EXPORTA_BLOCOD_SAI;
DROP PROCEDURE SP_EXPORTA_BLOCOD_SAI_D700;
DROP PROCEDURE SP_EXPORTA_BLOCOD_ENT_D700;
DROP PROCEDURE SP_EXPORTA_BLOCOD_D700;
DROP PROCEDURE SP_EXPORTA_BLOCOD;

DROP PROCEDURE SP_EXPORTA_BLOCOE;

DROP PROCEDURE SP_EXPORTA_BLOCOK290;
DROP PROCEDURE SP_EXPORTA_BLOCOK300;
DROP PROCEDURE SP_EXPORTA_BLOCOK;

DROP PROCEDURE SP_ATUALIZAR_TMP_TMOVREDZ;
DROP PROCEDURE SP_ATUALIZAR_TMP_REDZVARCFOP;
DROP PROCEDURE SP_ATUALIZAR_TMP_MOVCCREDZ;
DROP PROCEDURE SP_IMPORTA_RMD;
DROP PROCEDURE SP_ATUALIZA_TMP_TTERCEIRO_TEMP;
DROP PROCEDURE SP_GERAR_INCON_TERCEIRO;
DROP PROCEDURE SP_ATUALIZAR_TMP_CADMAQMRC;
DROP PROCEDURE SP_ATUALIZAR_TMP_TOBSERVACAO;
DROP PROCEDURE SP_INSERT_OR_UPDATE_TCADINFCOM;
DROP PROCEDURE SP_UPD_CAM_INTEGRACAO_ARQ_INCO;
DROP PROCEDURE SP_INSERT_OR_UPDATE_TOBSERVACAO;
DROP VIEW VW_USUARIO_EMPRESA;
DROP PROCEDURE SP_GET_ACOES_INCONSISTENCIA;
DROP PROCEDURE SP_GRAVAR_LAN;
DROP PROCEDURE SP_TRANSFERENCIA_LAN;
DROP PROCEDURE SP_TRANSFERENCIA_PRODUTOS;
DROP PROCEDURE SP_TRANSFERENCIA_RATEIO;
DROP PROCEDURE SP_VALIDAR_TRANSFERENCIA;
DROP PROCEDURE SP_CONSULTAEMPRESAS_SIS;

DROP PROCEDURE SP_CONTAS_SEARCHCOMPONENT;

DROP PROCEDURE SP_COPIA_PROGRAMAS_PLANO;

DROP PROCEDURE SP_COPIA_PLANOCONF1900;

DROP PROCEDURE SP_COPIA_PLANOCONF1250;

DROP PROCEDURE SP_CRIA_DADOSCALC_BAIXA;

DROP PROCEDURE SP_CRIA_DETGPSSEFIP;

DROP PROCEDURE SP_DADOS_EMP_REF;

DROP PROCEDURE SP_EMPPRESA_IMP;

SET TERM ^ ;

CREATE OR ALTER PROCEDURE SP_GERAR_INCON_TERCEIRO (
    PRSESSAO INTEGER,
    PRREF INTEGER,
    PRCODEMP INTEGER,
    PRPUSH DM_BOOLEAN)
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_GET_ACOES_INCONSISTENCIA (
    PRCODEMP INTEGER,
    PRREF INTEGER,
    PRSESSAO INTEGER = NULL)
RETURNS (
    BDCODPLANOINCONS INTEGER,
    BDNCMPROD INTEGER,
    BDSAICFOPNCAD INTEGER,
    BDENTCFOPCANC INTEGER,
    BDCODUNIMED INTEGER,
    BDENTCFOPNCAD INTEGER,
    BDSAICFOPCANC INTEGER,
    BDDESCRICAO VARCHAR(100),
    BDPLANODEFAULT DM_BOOLEAN,
    BDATUPROD DM_BOOLEAN,
    BDATUPART DM_BOOLEAN,
    BDATUUNIDMED DM_BOOLEAN,
    BDATUINFCOM DM_BOOLEAN,
    BDATUOBS DM_BOOLEAN,
    BDATUMAQREDZ DM_BOOLEAN,
    BDATUBICO DM_BOOLEAN,
    BDATUBOMBA DM_BOOLEAN,
    BDATUTANQUE DM_BOOLEAN,
    BDATUFATCONV DM_BOOLEAN,
    BDPARTIEISE DM_BOOLEAN,
    BDCADPROAUTO DM_BOOLEAN,
    BDENTAJUCFOP DM_BOOLEAN,
    BDENTIMPIPIDIF DM_BOOLEAN,
    BDENTIMPICMSDIF DM_BOOLEAN,
    BDSAIAJUCFOP DM_BOOLEAN,
    BDSAIIMPIPIDIF DM_BOOLEAN,
    BDSAIIMPICMSDIF DM_BOOLEAN,
    BDSERAJUCFOP DM_BOOLEAN,
    BDSERIMPISSDIF DM_BOOLEAN,
    BDPARTBUSCASITE DM_BOOLEAN,
    BDPRODNCMVAZIO DM_BOOLEAN,
    BDREDZCODTER INTEGER,
    BDESPECIEMRC VARCHAR(4),
    BDSERIEMRC VARCHAR(3),
    BDCONDPGTOMRC INTEGER,
    BDTIPOMAQMRC INTEGER,
    BDCODOBSMRC INTEGER,
    BDCODTERNFCE_CFE INTEGER,
    BDTIPCONTADUP INTEGER,
    BDCODTERSER INTEGER,
    BDSERIESER VARCHAR(6),
    BDESPECIESER VARCHAR(5),
    BDDTEMISSAOSER INTEGER,
    BDSUBSTITUIDUPLICATA DM_BOOLEAN,
    BDAPENASCODPRODSAI DM_BOOLEAN,
    BDVINCULOPART INTEGER,
    BDNUMERODOCUMENTOSER INTEGER,
    BDDATAVAZIASER VARCHAR(5),
    BDINDICADORISSSER INTEGER,
    BDDATAEXECUCAOSER INTEGER,
    BDEXCECAONCM DM_BOOLEAN,
    BDTIPOITEM DM_BOOLEAN,
    BDCADPARTEXTNFSESP DM_BOOLEAN,
    BDNAOVERIFICAIEPART DM_BOOLEAN,
    BDATUEXISTLANCC DM_BOOLEAN,
    BDNAOATUALIZACSTENTRADA boolean,
    BDNAOATUALIZACSTSAIDA boolean,
    BDNAOIMPINFCOMP Boolean)
AS
DECLARE VARIABLE WCODPLANOINCO INTEGER;
BEGIN
  SUSPEND;
END^

ALTER TRIGGER TOL_UNICO_PAG_DARF_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

--#alt:83227. Ana - 14/06/2018
CREATE OR ALTER TRIGGER TOL_UNICO_APURACAO_LALUR_AD0 FOR TOL_UNICO_APURACAO_LALUR
ACTIVE AFTER DELETE POSITION 0                                             
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_UNICO_PROV_DARF_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER TOL_VSUC_EMPRESAS_TPROCEVOLUCOBRA_AD0 FOR TOL_VSUC_EMPRESAS_TPROCEVOLUCOBRA
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TOL_VATI_EMPRESAS_IMP_ATIVACONTAB_AD FOR TOL_VATI_EMPRESAS_IMP_ATIVACONTAB
ACTIVE AFTER DELETE POSITION 0
as
begin
end
^

CREATE OR ALTER TRIGGER TOL_VSUC_EMPRESAS_TTRANSFCUSTOINCOR_AD FOR TOL_VSUC_EMPRESAS_TTRANSFCUSTOINCOR
ACTIVE AFTER DELETE POSITION 0
as
begin
end
^

CREATE OR ALTER TRIGGER TOL_VSUC_EMPRESAS_VALORPRESENTE_AD FOR TOL_VSUC_EMPRESAS_VALORPRESENTE
ACTIVE AFTER DELETE POSITION 0
as
begin
end
^

CREATE OR ALTER TRIGGER TOL_EMPRESAS_TBEM_TRANSFERENCIA_AD FOR TOL_EMPRESAS_TBEM_TRANSFERENCIA
ACTIVE AFTER DELETE POSITION 0
as
begin
end
^

CREATE OR ALTER TRIGGER TOL_EMPRESAS_TBEM_TRANSF_CONTA_AD FOR TOL_EMPRESAS_TBEM_TRANSF_CONTA
ACTIVE AFTER DELETE POSITION 0
as
begin
end
^

ALTER TRIGGER TOL_VEF_EMP_TDACONGER_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TBLOCOMGER_M220_AD0 FOR TOL_VEF_EMP_TBLOCOMGER_M220
ACTIVE AFTER DELETE POSITION 0
AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TBLOCOMGER_AD0 FOR TOL_VEF_EMP_TBLOCOMGER
ACTIVE AFTER DELETE POSITION 0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TICMSSPEDGER_AD0 FOR TOL_VEF_EMP_TICMSSPEDGER
ACTIVE AFTER DELETE POSITION 0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VEF_EMP_TDIMESCGER_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VEF_EMP_TGIAESGER_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TGIAPRGER_AD0 FOR TOL_VEF_EMP_TGIAPRGER
ACTIVE AFTER DELETE POSITION 0
AS DECLARE VARIABLE I INTEGER;
BEGIN
  I = 0;
END
^
CREATE OR ALTER TRIGGER tol_f200_delete FOR tol_vef_emp_tmovopimob_f200
ACTIVE AFTER DELETE POSITION 0
AS DECLARE VARIABLE I INTEGER;
BEGIN
  I = 0;
END^

CREATE OR ALTER TRIGGER tol_f200_pgto_delete FOR tol_vef_emp_tmovopimobi_f200_pg
ACTIVE AFTER DELETE POSITION 0
AS DECLARE VARIABLE I INTEGER;
BEGIN
  I = 0;
END^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TGIARJGER_AD0 FOR TOL_VEF_EMP_TGIARJGER
ACTIVE AFTER DELETE POSITION 0
AS DECLARE VARIABLE I INTEGER;
BEGIN
  I = 0;
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TGIATOGER_AD0 FOR TOL_VEF_EMP_TGIATOGER
ACTIVE AFTER DELETE POSITION 0
AS DECLARE VARIABLE I INTEGER;
BEGIN
  I = 0;
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TGIAROGER_AD0 FOR TOL_VEF_EMP_TGIAROGER
ACTIVE AFTER DELETE POSITION 0
AS DECLARE VARIABLE I INTEGER;
BEGIN
  I = 0;
END
^

ALTER TRIGGER TOL_VEF_EMP_TGIAMGGER_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VEF_EMP_TGIASPGER_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VEF_EMP_TIPIGER_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TCIAPGER_AD0 FOR TOL_VEF_EMP_TCIAPGER
ACTIVE AFTER DELETE POSITION 0
AS DECLARE VARIABLE I INTEGER;
BEGIN
  I = 0;
END
^

ALTER TRIGGER TOL_VEF_EMP_TIRLPGER_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VEF_EMP_TMOVDEMAISDOC_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VEF_EMP_TMOVENT_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VEF_EMP_TMOVENTPARPGTO_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VEF_EMP_TMOVOREC_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VEF_EMP_TMOVRATENT_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VEF_EMP_TMOVRATSAI_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VEF_EMP_TMOVRATSER_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER TOL_VEF__TMOVRATREDZVARCFOP_AD0 FOR TOL_VEF_EMP_TMOVRATREDZVARCFOP
ACTIVE AFTER DELETE POSITION 0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVRATOPEIMOBPG_AD FOR TOL_VEF_EMP_TMOVRATOPEIMOBIPGTO
ACTIVE AFTER DELETE POSITION 0
AS
begin  
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVRATOPEIMOBP_BI0 FOR TOL_VEF_EMP_TMOVRATOPEIMOBIPGTO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVRATOPEIMOBI_AD0 FOR TOL_VEF_EMP_TMOVRATOPEIMOBI
ACTIVE AFTER DELETE POSITION 0
AS
begin  
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVRATDEMDOC_AD0 FOR TOL_VEF_EMP_TMOVRATDEMDOC
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVRATOPEIMOBI_BI0 FOR TOL_VEF_EMP_TMOVRATOPEIMOBI
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^


CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVRATDEMDOC_BI0 FOR TOL_VEF_EMP_TMOVRATDEMDOC
ACTIVE BEFORE INSERT POSITION 0
AS
begin 
end
^


ALTER TRIGGER TOL_VEF_EMP_TMOVSAI_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TDIMEGERREGESP_AD0 FOR TOL_VEF_EMP_TDIMEGERREGESP
ACTIVE AFTER DELETE POSITION 0
AS
begin
end
^

ALTER TRIGGER TOL_VEF_EMP_TMOVSAIPARPGTO_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVF100PARPGTO_AD0 FOR TOL_VEF_EMP_TMOVF100PARPGTO
ACTIVE AFTER DELETE POSITION 0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VEF_EMP_TMOVSER_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VEF_EMP_TMOVSERPARPGTO_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VEF_EMP_TREDZVARCFOP_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TCALC_13_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TCALC_A13_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TCALC_AD_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TCALC_AUT_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TCALC_C13_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TCALC_FA_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TCALC_FER_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TCALC_FN_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TCALC_FN_FC_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TCALC_FT_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TCALC_FT_FC_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TCOMPGP_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_NF_AD0 FOR TOL_VRHF_EMP_NF
ACTIVE AFTER DELETE POSITION 0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER trigger TOL_VRHF_TVERBA_FT_FC_INT_ad0 for TOL_VRHF_EMP_TVERBA_FT_FC_INT
active after delete position 0
AS
BEGIN  
END
^

CREATE OR ALTER trigger TOL_VRHF_EMP_TVERBA_FCINT_ad0 for TOL_VRHF_EMP_TVERBA_FCINT
active after delete position 0
AS
BEGIN  
END
^

CREATE OR ALTER trigger TOL_VRHF_TFGTS_FT_FC_INT_ad0 for TOL_VRHF_EMP_TFGTS_FT_FC_INT
active after delete position 0
AS
BEGIN  
END
^

CREATE OR ALTER trigger TOL_VRHF_EMP_TFGTS_FC_INT_ad0 for TOL_VRHF_EMP_TFGTS_FC_INT
active after delete position 0
AS
BEGIN  
END
^

CREATE OR ALTER trigger TOL_VRHF_TCALC_FT_FC_INT_ad0 for TOL_VRHF_EMP_TCALC_FT_FC_INT
active after delete position 0
AS
BEGIN 
END
^

CREATE OR ALTER trigger TOL_VRHF_TCALC_FN_FC_INT_ad0 for TOL_VRHF_EMP_TCALC_FN_FC_INT
active after delete position 0
AS
BEGIN
END
^

ALTER TRIGGER TOL_VRHF_EMP_TFGTS_13_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TFGTS_A13_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TFGTS_C13_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TFGTS_FA_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TFGTS_FC_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TFGTS_FN_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TFGTS_FT_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TFGTS_FT_FC_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TPGTO_CALC_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TPROV13_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TPROV13_DET_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TPROVFER_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TPROVFER_DET_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TVERBA_13_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TVERBA_A13_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TVERBA_AD_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TVERBA_AUT_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TVERBA_C13_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TVERBA_FA_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TVERBA_FER_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TVERBA_FN_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TVERBA_FN_FC_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TVERBA_FT_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TOL_VRHF_EMP_TVERBA_FT_FC_AD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAIECREDAC_BI0 FOR VEF_EMP_TMOVSAIECREDAC
ACTIVE BEFORE INSERT POSITION 0
AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

SET TERM ; ^

DROP PROCEDURE SP_EXCLUI_ONLINE;

DROP PROCEDURE SP_EXCLUI_ONLINE_CC;

DROP PROCEDURE SP_EXCLUSAO_CBO_NAOUSADO;

SET TERM ^ ;

ALTER TRIGGER VRH_EMP_TCOLCON_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER PROCEDURE SP_DATA_UTIL (
    PRCODEMP INTEGER,
    PRDATA DATE)
RETURNS (
    BDDATA DATE)
AS
BEGIN
  SUSPEND;
END^

SET TERM ; ^

DROP PROCEDURE SP_EXISTE_COLABORADOR_DOWNLOAD;

DROP PROCEDURE SP_EXISTE_COLABORADOR_NOVO;

DROP PROCEDURE SP_VATI_GERAR_INCON_TDEPAUTO;

DROP PROCEDURE SP_EXP_ATIVA_CONTABIL;

DROP PROCEDURE SP_EXP_SEFIP;

DROP PROCEDURE SP_EXP_SEFIP_ARQ;

DROP PROCEDURE SP_EXP_SEFIP_CODREC;

DROP PROCEDURE SP_VRH_EMP_TSITCOL_ESOCIAL;

DROP PROCEDURE SP_EXP_SEFIP_REG_00;

DROP PROCEDURE SP_EXP_SEFIP_REG_10;

DROP PROCEDURE SP_EXP_SEFIP_REG_12;

DROP PROCEDURE SP_EXP_SEFIP_REG_20;

DROP PROCEDURE SP_EXP_SEFIP_REG_21;

DROP PROCEDURE SP_EXP_SEFIP_REG_30;

DROP PROCEDURE SP_EXP_SEFIP_REG_32;

DROP PROCEDURE SP_EXP_SEFIP_REG_90;

DROP PROCEDURE SP_EXP_SEFIP_RESC_SEGUINTE_COL;


DROP PROCEDURE SP_FERIAS_PROVISAO;

DROP PROCEDURE SP_FERIAS_PROVISAO_REF;

DROP PROCEDURE SP_FICHA_REGISTROS_CARGOS;

DROP PROCEDURE SP_FICHA_REGISTROS_HORARIOS;

DROP PROCEDURE SP_FICHA_REGISTROS_SALARIOS;

DROP PROCEDURE SP_FUNCAO_CBO_ESOCIAL;

SET TERM ^ ;

ALTER TRIGGER VRH_EMP_TCOL_VINCDIA_BI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

SET TERM ; ^

DROP PROCEDURE SP_FUNCOES_PLANO_EMP;

DROP PROCEDURE SP_GERA_ADVERTENCIAS;

SET TERM ^ ;

ALTER TRIGGER VSUC_EMPRESAS_TLAN_BD0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TEMPRESAS_AU0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TEMPRESAS_BU0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER TIMPOSTO_AI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VCT_BASE_OBRIGACAO_AI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

ALTER TRIGGER VCT_BASE_SERVICO_AI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER TTERCEIRO_REF_AUD0 FOR TTERCEIRO_REF
ACTIVE AFTER UPDATE POSITION 0
 AS DECLARE VARIABLE I INTEGER;
BEGIN
I = 0;
END
^

CREATE OR ALTER TRIGGER EMPRESAS_TSOC_REF_AUD0 FOR EMPRESAS_TSOC_REF
ACTIVE AFTER UPDATE POSITION 0
 AS DECLARE VARIABLE I INTEGER;
BEGIN
I = 0;
END
^


CREATE OR ALTER TRIGGER VCT_BASE_SERVICO_AU0 FOR VCT_BASE_SERVICO
ACTIVE AFTER UPDATE POSITION 0
AS
BEGIN
END
^

CREATE OR ALTER trigger vct_empresa_docsgerados_bd0 for vct_empresa_docsgerados
active before delete position 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VCT_EMPRESA_TSOLICITATAREFA_BI0 for VCT_EMPRESA_TSOLICITATAREFA
ACTIVE BEFORE INSERT POSITION 0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER VCT_EMPRESA_TSOLICITATAREFA_BI1 FOR VCT_EMPRESA_TSOLICITATAREFA
ACTIVE BEFORE INSERT POSITION 0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER vct_empresa_protocolosaida_bd0 FOR vct_empresa_protocolosaida
ACTIVE BEFORE DELETE POSITION 0
AS
  DECLARE VARIABLE vcodst INTEGER;
BEGIN vcodst = 0; END
^

CREATE OR ALTER TRIGGER vrh_emp_tcolcon_qc_bi0 FOR vrh_emp_tcolcon_qc
ACTIVE BEFORE INSERT POSITION 0
AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER vrh_base_tterc_qc_bi0 FOR vrh_base_tterc_qc
ACTIVE BEFORE INSERT POSITION 0
    AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER PROCEDURE SP_GET_USUARIO RETURNS(BDCODUSU INTEGER)
 AS
DECLARE VARIABLE wcodusu VARCHAR(10);
BEGIN
  -- Gilberto - 21/01/2026 - Variável de sessão mantém apenas um valor, não há necessidade do laço
--  FOR SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_USUARIO'))) AS INTEGER)
--      FROM rdb$database
--  INTO
--    :BDCODUSU
--  DO

  SELECT first 1 CAST((TRIM(rdb$get_context('USER_SESSION', 'W_USUARIO'))) AS INTEGER)
  FROM rdb$database INTO :BDCODUSU;

  SUSPEND;
END
^

create or ALTER view vw_get_processo (BDNOMETELA, BDCAPTIONTELA) as SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_NOMETELA'))) AS varchar(100)), CAST((TRIM(rdb$get_context('USER_SESSION', 'W_CAPTIONTELA'))) AS varchar(150)) FROM rdb$database;^


CREATE OR ALTER TRIGGER VRH_BASE_TAMBIENTETRABALHO_BI0 FOR VRH_BASE_TAMBIENTETRABALHO
ACTIVE BEFORE INSERT POSITION 0
    AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER VRH_BASE_TAMBTRAB_FR_BI0 FOR VRH_BASE_TAMBTRAB_FR
ACTIVE BEFORE INSERT POSITION 0
    AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_NF_GAUCHA (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRRETIFICADORA INTEGER,
    PRARQUIVO VARCHAR(260))
AS
DECLARE VARIABLE WLINHA BLOB SUB_TYPE 1 SEGMENT SIZE 200 CHARACTER SET UTF8;
DECLARE VARIABLE WHASH VARCHAR(256);
DECLARE VARIABLE WLINHAAUX VARCHAR(300);
BEGIN END
^

CREATE OR ALTER TRIGGER VRH_EMP_TTRABAVULSO_BI0 FOR VRH_EMP_TTRABAVULSO
ACTIVE BEFORE INSERT POSITION 0
AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^



SET TERM ; ^

DROP VIEW VWGR_EF_DARESC;

DROP VIEW VWGR_EF_EXP_DCTF;

DROP VIEW VWGR_EF_EXP_DNF;

DROP VIEW VW_VRH_EMP_CAT;

DROP TRIGGER VCT_EMPRESA_PROTOCOLOSAIDA_BD0;

DROP VIEW VW_EMPRESAS_REF_ATUAL;

DROP VIEW vw_empresas_grupo_usuario;

DROP VIEW VW_EMPRESAS_USU;

DROP VIEW VW_PRIVILEGIO_EMPRESA;

--DROP VIEW VW_USUARIO_EMPRESA;

DROP PROCEDURE SP_IMPOSTO_EMPRESA;

DROP PROCEDURE SP_INCLUI_VERBAS_NOVAS;

DROP PROCEDURE SP_VRHF_PBM_NO_ANO;

DROP PROCEDURE SP_INCLUI_VERBASEMP;

DROP PROCEDURE SP_INDICES_ACUMULADOS;

DROP PROCEDURE SP_INSERE_ADVERTENCIA;

DROP PROCEDURE SP_INSERIR_LOG_ATUALIZACAO;

DROP PROCEDURE SP_CRIA_BACKUP_EMPRESA;

DROP PROCEDURE VCT_EMPRESA_THISTORICO_STATUS;

--DROP PROCEDURE VCT_TAREFAS_AUTOMATICAS;

drop procedure GET_VENCIMENTO_TAREFAS;

DROP PROCEDURE VCT_ORCAMENTO_RELATORIO;

DROP PROCEDURE VCT_TAREFA_SEFIPSEMMOVIMENTO;

DROP PROCEDURE SP_INSERIR_LOG;

drop procedure sp_getcodigo_tela;

DROP PROCEDURE SP_INSERT_ATIVIDADE_BLUMENAU;

DROP PROCEDURE SP_COPIA_ATIVIDADES_MUNICIPAIS;
 
DROP PROCEDURE SP_INSERT_FERIADO;

SET TERM ^ ;

ALTER TRIGGER VRH_BASE_TTIPOCALCAVUL_AI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

SET TERM ; ^

DROP PROCEDURE SP_INSERT_FOLHAAVULSA_ONLINE;

SET TERM ^ ;

ALTER TRIGGER VRH_BASE_TVERBAS_AI0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

-- alt:15432 - Gilberto - 05/09/2016 - Adicionado porque excluia as trigger's antes que elas existissem
CREATE OR ALTER TRIGGER TR_BF_INSERT_TTERCEIRO FOR tterceiro
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN END^
CREATE OR ALTER TRIGGER TR_BF_UPDATE_TTERCEIRO FOR tterceiro
ACTIVE BEFORE UPDATE POSITION 0
AS BEGIN END^
CREATE OR ALTER TRIGGER TR_BF_INSERT_TTERCEIRO_REF FOR TTERCEIRO_REF
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN END^
CREATE OR ALTER TRIGGER TR_BF_UPDATE_TTERCEIRO_REF FOR tterceiro_ref
ACTIVE BEFORE UPDATE POSITION 0
AS BEGIN END^
-- alt:15432

-- 144124 - Raphael Teodoro - 04/12/2020
CREATE OR ALTER TRIGGER vrh_emp_tcolcon_bi0 FOR vrh_emp_tcolcon
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN END^

CREATE OR ALTER TRIGGER TCIDADE_BU0 FOR TCIDADE
ACTIVE BEFORE UPDATE POSITION 0
AS BEGIN END^ 

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_CAD_BI0 FOR VRH_EMP_TCOLCON_CAD
ACTIVE BEFORE INSERT POSITION 0
    AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_CAD_BU0 FOR VRH_EMP_TCOLCON_CAD
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN

END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_DOCREF_BI0 FOR VRH_EMP_TCOLCON_DOCREF
ACTIVE BEFORE INSERT POSITION 0
    AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_ADMREF_BI0 FOR VRH_EMP_TCOL_ADMREF
ACTIVE BEFORE INSERT POSITION 0
    AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER VRH_EMP_TEMPRESASSST_BI0 FOR VRH_EMP_TEMPRESASSST
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;
BEGIN END^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_ADMREF_BU0 FOR VRH_EMP_TCOL_ADMREF
ACTIVE BEFORE UPDATE POSITION 0
AS
begin end^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_FIS_BI0 FOR VRH_EMP_TCOLCON_FIS
ACTIVE BEFORE INSERT POSITION 0
    AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

CREATE OR ALTER TRIGGER empresas_tvalorresidual_bi0 FOR empresas_tvalorresidual
ACTIVE BEFORE UPDATE POSITION 0
AS
begin end^

CREATE OR ALTER TRIGGER tr_bf_insert_empresas_timovrur for empresas_timovrur
ACTIVE BEFORE UPDATE POSITION 0
AS BEGIN END^ 

CREATE OR ALTER TRIGGER tr_bf_insert_emp_texplocontrat FOR empresas_texplocontrat
ACTIVE BEFORE UPDATE POSITION 0
AS BEGIN END^ 

CREATE OR ALTER TRIGGER VSUC_BASE_EXT_TBANDEIRAS_BI0 FOR VSUC_BASE_EXT_TBANDEIRAS
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN END^ 

CREATE OR ALTER TRIGGER VSUC_BASE_EXT_TOPERADORAS_BI0 FOR VSUC_BASE_EXT_TOPERADORAS
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN END^ 

CREATE OR ALTER TRIGGER VSUC_BASE_TFORMULA_AUTO_BI0 FOR VSUC_BASE_TFORMULA_AUTO
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN END^ 

CREATE OR ALTER TRIGGER VSUC_BASE_TFORMULA_TPFO_BU0 FOR VSUC_BASE_TFORMULA_TPFO
ACTIVE BEFORE UPDATE POSITION 0
AS BEGIN END^ 

CREATE OR ALTER TRIGGER TR_BF_INSERT_VSUC_BASE_TFORMULA FOR VSUC_BASE_TFORMULA
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN END^ 

CREATE OR ALTER TRIGGER VSUC_EMP_EXT_CARTAOCREDITO_BI0 FOR VSUC_EMP_EXT_CARTAOCREDITO
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN END^ 

CREATE OR ALTER trigger planos_tpla_carne_leao_ref_bi0 for planos_tpla_carne_leao_ref
active before insert position 0
AS BEGIN END^ 

CREATE OR ALTER trigger planos_tpla_carne_leao_pad_bi0 for planos_tpla_carne_leao_padrao
active before insert position 0
AS BEGIN END^ 

CREATE OR ALTER trigger vsuc_tconfig_imp_lanc_plan_bi0 for vsuc_tconfig_imp_lanc_plan
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN END^ 

CREATE OR ALTER TRIGGER VSUC_BASE_FORMULA_TMENSAL_BI0 FOR VSUC_BASE_FORMULA_TMENSAL
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN END^ 

CREATE OR ALTER TRIGGER VSUC_EMP_ECF_TARQECD_CTAZER_BI0 FOR VSUC_EMP_ECF_TARQUIVOECD_CTAZER
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN END^

CREATE OR ALTER TRIGGER VSUC_EMP_ECF_TARQUIVOECD_BI0 FOR VSUC_EMP_ECF_TARQUIVOECD
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN END^

CREATE OR ALTER TRIGGER VSUC_EMPRESAS_TGRPECO_BI0 FOR VSUC_EMPRESAS_TGRPECO
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN END^

CREATE OR ALTER TRIGGER TDEPENDENTE_CARNE_LEAO_BI0 FOR TDEPENDENTE_CARNE_LEAO
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN END^

CREATE OR ALTER TRIGGER PLANOS_TPLA_SECUNDARIO_BI0 FOR PLANOS_TPLA_SECUNDARIO
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN END^

CREATE OR ALTER TRIGGER PLANOS_TPLA_SECUNDARIO_BU0 FOR PLANOS_TPLA_SECUNDARIO
ACTIVE BEFORE UPDATE POSITION 0
AS BEGIN END^

CREATE OR ALTER trigger planos_tpla_secundario_bd0 for planos_tpla_secundario
active before delete position 0
AS BEGIN END^

CREATE OR ALTER trigger tsmtp_sci_au0 for tsmtp_sci
active after update or delete position 0
AS BEGIN END^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TPLANO_SECUNDARIO FOR TPLANO_SECUNDARIO
ACTIVE BEFORE INSERT POSITION 0
AS BEGIN END^

CREATE OR ALTER TRIGGER vrh_emp_tcol_hist_au0 FOR vrh_emp_tcol_hist ACTIVE AFTER UPDATE POSITION 0 AS BEGIN END^
CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_CAD_AU0 FOR VRH_EMP_TCOLCON_CAD ACTIVE AFTER UPDATE POSITION 0 AS BEGIN END^

CREATE OR ALTER PROCEDURE SP_VRHF_13SALARIO_ANO_SIT (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(32700),
    PRANO INTEGER) 
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF13 INTEGER,
    BDANO13 INTEGER,
    BDBSALMAT13 NUMERIC(18,6),
    BDBACITRAB13 NUMERIC(18,6),
    BDBAUXDOE13 NUMERIC(18,6)) 
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_VRHF_A13SALARIO_ANO_SIT (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(32700),
    PRANO INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREFA13 INTEGER,
    BDBSALMATA13 NUMERIC(18,6),
    BDBACITRABA13 NUMERIC(18,6),
    BDBAUXDOEA13 NUMERIC(18,6))
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_VRHF_C13SALARIO_ANO (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(32700),
    PRANO INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF13 INTEGER,
    BDVAL13 NUMERIC(15,6),
    BDMESESPROP13 INTEGER,
    BDBASEIR13 NUMERIC(15,6),
    BDFGTS13 NUMERIC(15,6),
    BDFGTSCS13 NUMERIC(15,6),
    BDBASEFGTS13 NUMERIC(15,6),
    BDDATABAIXA13 DATE,
    BDREFBAIXA13 INTEGER,
    BDPERCIR13 NUMERIC(15,6),
    BDVALORIR13 NUMERIC(15,6),
    BDBRAIS13 NUMERIC(15,6),
    BDDEP13 NUMERIC(15,6),
    BDSALBASE13 NUMERIC(15,6),
    BDARREPROV13 NUMERIC(15,6),
    BDARREDESC13 NUMERIC(15,6),
    BDBASEINSS13 NUMERIC(15,6),
    BDPERCINSS13 NUMERIC(15,6),
    BDVALORINSS13 NUMERIC(15,6),
    BDANO13 INTEGER,
    BDESTPROV13 NUMERIC(15,6),
    BDBASEPIS13 NUMERIC(15,6),
    BDBRATAPO13 NUMERIC(15,6),
    BDBSALFAM13 NUMERIC(18,6),
    BDBSALMAT13 NUMERIC(18,6),
    BDSALMATEMP13 NUMERIC(18,6),
    BDPREVPRIV13 NUMERIC(18,6),
    BDRATAPO13 NUMERIC(18,6),
    BDSALFAM13 NUMERIC(18,6))
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_SOMENTE_ATIVOS_RAIS (
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRCODEMP INTEGER = NULL)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER)
AS
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_TIPOS_CONTR_SIND (
    PRCODEMP INTEGER,
    PRCODCOL INTEGER,
    PRREF INTEGER,
    PRRETMEN INTEGER,
    PRRETSIND INTEGER,
    PRRETCONF INTEGER,
    PRRETTAXAS INTEGER,
    PRRETREV INTEGER) 
RETURNS (
    BDMENSALIDADE NUMERIC(15,6),
    BDCONTSIND NUMERIC(15,6),
    BDCONTCONF NUMERIC(15,6),
    BDTAXAS NUMERIC(15,6),
    BDREVERSAO NUMERIC(15,6)) 
AS
BEGIN

END
^

--Sol. 16745 - Bruno L. R. - 05/06/2017 - Procedure para buscar os dados dos Vales transporte apurados
CREATE OR ALTER PROCEDURE SP_APURADOS_VALTRANS (
    PRCODEMP VARCHAR(25000),
    PRCOLABORADOR VARCHAR(32700),
    PRCOMPETENCIA INTEGER,
    PRNRVIAS INTEGER)
RETURNS (
    BDNRVIA INTEGER,
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODITI INTEGER,
    BDCOMPETENCIA INTEGER,
    BDQUANTIDADE INTEGER,
    BDTPAPURACAO INTEGER,
    BDDTINICIAL DATE,
    BDDTFINAL DATE,
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDRGCOL VARCHAR(20),
    BDCPFCOL VARCHAR(14),
    BDDESCITI VARCHAR(40),
    BDLINHAITI VARCHAR(20),
    BDVALUNI NUMERIC(18,6),
    BDVALCUSTOEMP NUMERIC(18,6),
    BDVALDESCONTO NUMERIC(18,6),
    BDQTDITINERARIOS INTEGER)
AS
BEGIN

END
^

--Sol. 16745 - Bruno L. R. - 05/06/2017 - Procedure para buscar os dados dos Vales refeição apurados
CREATE OR ALTER PROCEDURE SP_APURADOS_VALREF (
    PRCODEMP varchar(6000),
    PRCOLABORADOR varchar(6000),
    PRCOMPETENCIA integer,
    PRNRVIAS integer,
    PRDATAINICIAL date = null,
    PRDATAFINAL date = null)
RETURNS (
    BDNRVIA INTEGER,
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODCONVREF INTEGER,
    BDCOMPETENCIA INTEGER,
    BDQUANTIDADE INTEGER,
    BDTPAPURACAO INTEGER,
    BDDTINICIAL DATE,
    BDDTFINAL DATE,
    BDDESCCONVREF VARCHAR(50),
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDRGCOL VARCHAR(20),
    BDCPFCOL VARCHAR(14),
    BDVALUNI NUMERIC(18,6),
    BDVALCUSTOEMP NUMERIC(18,6),
    BDVALDESCONTO NUMERIC(18,6),
    BDQTDCONVENIOREF INTEGER)
AS
BEGIN

END
^

--Sol. 18845 - Bruno L. R. - 10/06/2017 - Criação da procedure para retornar as informações de percentual de gorjeta do cadastro do colaborador
CREATE OR ALTER PROCEDURE SP_PERC_GORJETA (
    PRCODEMP varchar(2000),
    PRCODCOL varchar(2000),
    PRREF integer,
    PRHISTTRANSF integer = 0,
    PRPODE integer = 1)
RETURNS (
    BDREFCOL VARCHAR(10),
    BDPERCGORJ NUMERIC(18,6),
    BDNOMCOL VARCHAR(200),
    BDCODCOL INTEGER,
    BDCODEMP INTEGER)
AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WNOMCOL VARCHAR(200);
DECLARE VARIABLE WPERCGORJ NUMERIC(18,6);
DECLARE VARIABLE WREFCOL INTEGER;
DECLARE VARIABLE WSQL VARCHAR(20000);
DECLARE VARIABLE WSQL2 VARCHAR(20000);
DECLARE VARIABLE WCOUNT INTEGER;
BEGIN

END
^

-- Sol. 18932 - Marcelo B. M. - Alt:20/07/2017 - Retorna os dados de INSS das tabelas de prévia de rescisão da folha normal 
CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_INSS_FN_PREV_RESC (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(30000),
    PRREF INTEGER,
    PRGPSSEFIP SMALLINT = 0,
    PRFILIAIS VARCHAR(15000) = NULL)
RETURNS (
    BDGPSSEFIP INTEGER,
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREFFN INTEGER,
    BDCODCENTROS INTEGER,
    BDCODTPCC INTEGER,
    BDINSSFNPR NUMERIC(18,6),
    BDINSSFEFOLFNPR NUMERIC(18,6),
    BDINSS13FNPR NUMERIC(18,6),
    BDBINSSFNPR NUMERIC(18,6),
    BDBINSSFEFOLFNPR NUMERIC(18,6),
    BDBINSS13FNPR NUMERIC(18,6),
    BDBRATAPOFNPR NUMERIC(18,6),
    BDBRATAPOFEFNPR NUMERIC(18,6),
    BDBRATAPO13FNPR NUMERIC(18,6),
    BDSALFAMFNPR NUMERIC(18,6),
    BDSALMATEMPFNPR NUMERIC(18,6),
    BDBINSS13INDFNPR NUMERIC(18,6),
    BDBINSSAPFNPR NUMERIC(18,6),
    BDBINSS13APFNPR NUMERIC(18,6),
    BDINSSAPFNPR NUMERIC(18,6),
    BDINSS13APFNPR NUMERIC(18,6),
    BDVALREEMBOLSO NUMERIC(18,6),
    BDVALINDEVIDO NUMERIC(18,6),
    BDVALINDEVIDOSF NUMERIC(18,6),
    BDBAVPREV NUMERIC(18,6),
    BDPERCRATCOL NUMERIC(18,6),
    BDPERCDESCFPASCOL NUMERIC(18,6))
AS BEGIN SUSPEND; END

^

-- Sol. 18932 - Marcelo B. M. - Alt:20/07/2017 - Retorna os dados de INSS das tabelas de prévia de rescisão da folha por tomador
CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_INSS_FT_PREV_RESC (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(30000),
    PRREF INTEGER,
    PRGPSSEFIP SMALLINT = 0,
    PRFILIAIS VARCHAR(15000) = NULL)
RETURNS (
    BDGPSSEFIP INTEGER,
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREFFN INTEGER,
    BDORDEM INTEGER,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDINSSFTPR NUMERIC(18,6),
    BDINSSFEFOLFTPR NUMERIC(18,6),
    BDINSS13FTPR NUMERIC(18,6),
    BDBINSSFTPR NUMERIC(18,6),
    BDBINSSFEFOLFTPR NUMERIC(18,6),
    BDBINSS13FTPR NUMERIC(18,6),
    BDBRATAPOFTPR NUMERIC(18,6),
    BDBRATAPOFEFTPR NUMERIC(18,6),
    BDBRATAPO13FTPR NUMERIC(18,6),
    BDSALFAMFTPR NUMERIC(18,6),
    BDSALMATEMPFTPR NUMERIC(18,6),
    BDBINSSAPFTPR NUMERIC(18,6),
    BDBINSS13INDFTPR NUMERIC(18,6),
    BDBINSS13APFTPR NUMERIC(18,6),
    BDINSSAPFTPR NUMERIC(18,6),
    BDINSS13APFTPR NUMERIC(18,6),
    BDVALREEMBOLSO NUMERIC(18,6),
    BDVALINDEVIDO NUMERIC(18,6),
    BDVALINDEVIDOSF NUMERIC(18,6),
    BDBAVPREV NUMERIC(18,6),
    BDPERCRATCOL NUMERIC(18,6),
    BDPERCDESCFPASCOL NUMERIC(18,6))
AS
BEGIN SUSPEND; END

^

CREATE OR ALTER PROCEDURE SP_GET_CODPARTICIPANTEEXP (
    PRTIPOEXPCODPART INTEGER,
    PRCODTER INTEGER,
    PRCGCTER VARCHAR(18),
    PRIETER VARCHAR(20),
    PRCODIGOARQUIVO VARCHAR(60))
RETURNS (
    BDRETORNO VARCHAR(60))
AS
BEGIN

  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_VALIDACHAVE_NFE (
    PRCHAVENFE VARCHAR(60))
RETURNS (
    BDISVALID DM_BOOLEAN)
AS
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_VALIDACHAVE_NFE_CTE (
    PRCHAVENFE DM_CHAVENFE)
RETURNS (
    BDISVALID VARCHAR(5))
AS
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCCOL (
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
END^


CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCPROLAB(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
END^



CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCESTAG(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
END^



CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCRESC(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
END^


CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCAUT(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
END^


CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCFERCOL(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCFERIND(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
END^


CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCADISAL(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
END^


CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCFOLCOMP(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
END^


CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCPLR(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCADI13(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALC13(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCCOMP13(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
END^

create or alter procedure VSUC_SP_MONTA_CONCILIACAO (
    PRCONCILIADOS varchar(40),
    PRCONC varchar(40),
    PRCONCPENDENTE varchar(40),
    PRDEBCRED varchar(40))
returns (
    BDSQLCONCILIADO varchar(1000))
 AS
 BEGIN SUSPEND; END
^

Create or alter procedure SP_TCOLCON_VINCDIA_ADM (
    PRCODEMP integer,
    PRCODCOL integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATACOL date,
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDCODPQUA integer,
    BDDATAINICIALESCALA date,
    BDCODREVEZAMENTO integer,
    BDTIPOESCALA integer,
    BDCODQH integer)
as
begin  
end^

CREATE OR ALTER procedure SP_VRH_EMP_TSITCOLDEC_RECURSIVO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRDATAINISEFIP date,
    PRANTERIORES DM_BOOLEAN,
    PRRECURSIVIDADE smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATAINISEFIP date,
    BDCODEMPDEC integer,
    BDCODCOLDEC integer,
    BDDATAINISEFIPDEC date)
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER procedure SP_VRH_EMP_TSITCOL_VINCULADOS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRDATAINISEFIP date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATAINISEFIP date)
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER TRIGGER VRH_EMP_THIST_AUMHE_BI0 FOR VRH_EMP_THIST_AUMHE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vStatus INTEGER;
  DECLARE VARIABLE vCodHAumHe INTEGER;

BEGIN
END^

CREATE OR ALTER TRIGGER VEF_EMP_TBASELEGALISS_BI0 FOR VEF_EMP_TBASELEGALISS
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE wOrdem INTEGER;
  DECLARE VARIABLE wChave INTEGER;
BEGIN
END^

CREATE or alter trigger vef_emp_tmovserdsf_bi0 for vef_emp_tmovserdsf
active before insert position 0
as
  declare variable WORDEM integer;
  declare variable WCHAVE integer;
begin
end^

CREATE OR ALTER TRIGGER VRHP_BASE_CONF_DET_BI0 FOR VRHP_BASE_CONF_DET
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRHP_BASE_CONF_DET_BU0 FOR VRHP_BASE_CONF_DET
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRHP_BASE_CONF_DET_REF_BI0 FOR VRHP_BASE_CONF_DET_REF
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VRHP_BASE_CONF_DET_REF_BU0 FOR VRHP_BASE_CONF_DET_REF
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END^

CREATE OR ALTER TRIGGER VEF_BASE_TEMPPARESTPE_BI0 FOR VEF_BASE_TEMPPARESTPE
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
END^

create or alter procedure SP_VALIDAR_CAT42SP (
    PRREFINI integer,
    PRREFFIM integer)
as
begin
end^

create or alter procedure SP_APURAR_CAT42SP (
    PRSESSAO integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRCODCONT integer)
as
begin
end^

create or alter procedure SP_GET_VALOR_CONFRONTO_SAIDA (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRCODPROD integer,
    PRORDEM integer,
    PRCODENQLEG integer,
    PRDATAMOV date,
    PRQTDITEM numeric(15,6),
    PRTIPOMOV char(4))
returns (
    BDVLRCONFRONTO DM_NUMERIC_15_2)
as
begin
end^

CREATE OR ALTER PROCEDURE SP_COPIA_PLANOCPRBREINF (
    PRCODPLANO INTEGER,
    PRCODPLANOCOPIADO INTEGER)
AS
DECLARE VARIABLE WCAMPO VARCHAR(32);
DECLARE VARIABLE WCAMPOSINSERT VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(10000);
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_FGTS_DIGITAL_COMP (
    PRCODEMP INTEGER,
    PRCODCOL INTEGER,
    PRREF INTEGER,
    PRPUXAFILIAL BOOLEAN,
    PRANUAL BOOLEAN)
RETURNS (
    BDNOME_MATRIZ VARCHAR(200),
    BDCODFILIAL INTEGER,
    BDCODEMP INTEGER,
    BDNOMEMP VARCHAR(200),
    BDCNPJEMP VARCHAR(20),
    BDCOMP VARCHAR(20),
    BDREF INTEGER,
    BDNOMECOL VARCHAR(200),
    BDCODCOL INTEGER,
    BDCPFCOL VARCHAR(20),
    BDMATCOL VARCHAR(50),
    BDCATEGORIA INTEGER,
    BDORIGEM VARCHAR(50),
    BDBASE_FGTS_DIGITAL NUMERIC(18,6),
    BDBASE_FGTS_DIGITAL_RES NUMERIC(18,6),
    BDBASE_FGTS_DIGITAL_13 NUMERIC(18,6),
    BDVALOR_FGTS_DIGITAL NUMERIC(18,6),
    BDVALOR_FGTS_DIGITAL_RES NUMERIC(18,6),
    BDVALOR_FGTS_DIGITAL_13 NUMERIC(18,6),
    BDBASE_FGTS_UNICO NUMERIC(18,6),
    BDBASE_FGTS_UNICO_RES NUMERIC(18,6),
    BDBASE_FGTS_UNICO_13 NUMERIC(18,6),
    BDVALOR_FGTS_UNICO NUMERIC(18,6),
    BDVALOR_FGTS_UNICO_RES NUMERIC(18,6),
    BDVALOR_FGTS_UNICO_13 numeric(18,6),
    BDBASE_MULTA_UNICO numeric(15,2),
    BDBASE_MULTA_FD numeric(15,2),
    BDVALOR_MULTA_UNICO numeric(15,2),
    BDVALOR_MULTA_FD numeric(15,2),
    BDEXISTEDIFERENCA smallint)
AS
DECLARE VARIABLE WSQLLISTA VARCHAR(30000);
DECLARE VARIABLE WSQLFD VARCHAR(30000);
DECLARE VARIABLE WORIGEM VARCHAR(50);
DECLARE VARIABLE WBASE_FGTS_DIGITAL NUMERIC(18,6);
DECLARE VARIABLE WBASE_FGTS_DIGITAL_RES NUMERIC(18,6);
DECLARE VARIABLE WBASE_FGTS_DIGITAL_13 NUMERIC(18,6);
DECLARE VARIABLE WVALOR_FGTS_DIGITAL NUMERIC(18,6);
DECLARE VARIABLE WVALOR_FGTS_DIGITAL_RES NUMERIC(18,6);
DECLARE VARIABLE WVALOR_FGTS_DIGITAL_13 NUMERIC(18,6);
DECLARE VARIABLE WBASE_FGTS_UNICO NUMERIC(18,6);
DECLARE VARIABLE WBASE_FGTS_UNICO_RES NUMERIC(18,6);
DECLARE VARIABLE WBASE_FGTS_UNICO_13 NUMERIC(18,6);
DECLARE VARIABLE WVALOR_FGTS_UNICO NUMERIC(18,6);
DECLARE VARIABLE WVALOR_FGTS_UNICO_RES NUMERIC(18,6);
DECLARE VARIABLE WVALOR_FGTS_UNICO_13 NUMERIC(18,6);
declare variable WTEMRESCISAO integer;
declare variable WBASE_MULTA numeric(15,2);
declare variable WVALOR_MULTA numeric(15,2);
declare variable WBASE_MULTA_FD numeric(15,2);
declare variable WVALOR_MULTA_FD numeric(15,2);
declare variable WGRRFPRES smallint;
declare variable WBASE_FGTS_GRRF numeric(15,2);
declare variable WVALOR_FGTS_GRRF numeric(15,2);
declare variable WTIPOEVT integer;
declare variable WCODPRES integer;
BEGIN
END^

SET TERM ; ^

DROP procedure SP_REMOVE_INDICE_SE_EXISTE;

DROP PROCEDURE SP_GET_CODPARTICIPANTEEXP;

DROP PROCEDURE SP_VALIDACHAVE_NFE;

DROP PROCEDURE SP_INSERT_NOVA_VERBA_ONLINE;

DROP PROCEDURE SP_INSERTS;

DROP PROCEDURE SP_LISTAR_PLANOS_ONLINE;

DROP PROCEDURE SP_LISTAR_PLANOS_POR_REF;

DROP PROCEDURE SP_MANUTENCAO_TCALCVESP;

DROP PROCEDURE SP_MASCARA_CODNAT;

DROP PROCEDURE SP_MODELOS_GERADOR_REL;

DROP PROCEDURE SP_FILTRA_PART_TROCA;

DROP PROCEDURE SP_FILTER_TER_TROCA_GLOBAL;

DROP PROCEDURE SP_FILTER_DOC_TROCA_GLOBAL;

DROP PROCEDURE SP_FILTRA_PART_TROCA_PLANO;

DROP PROCEDURE SP_GET_PART_TROCA_CONSULTA;

DROP PROCEDURE SP_NOME_TERCEIRO;

DROP PROCEDURE SP_PBM;

DROP PROCEDURE SP_PRAZO_EXPERIENCIA_SITUACAO;

DROP PROCEDURE SP_PROPORC_VALORES;

DROP PROCEDURE SP_REF_TRIMESTRE;

DROP PROCEDURE SP_REL_CONSULTA_CONFIGURAVEL;

DROP PROCEDURE SP_REL_CONSULTA_CONFIGURAVEL2;

DROP PROCEDURE SP_REL_CONSULTA_SIMULADOR_TRIB;

DROP PROCEDURE SP_REL_CTRPAT_ANALILITIC_SINT;

DROP PROCEDURE SP_REL_RESUMO_IMPOSTOS;

DROP PROCEDURE SP_RETORNA_DIFERENCAS_VSUC_TLAN;

DROP PROCEDURE SP_RETORNA_EMPRESA_FILIAIS;

DROP PROCEDURE SP_RETORNA_MESANO_EXTENSO;

DROP PROCEDURE SP_RETORNA_NUMEROS;

DROP PROCEDURE SP_RETORNA_SALDO_EMP;

DROP PROCEDURE SP_RETORNA_SALDO_EMP_X;

DROP PROCEDURE SP_RETORNA_CONTAS_EMPRESA;

DROP PROCEDURE SP_CONTAS_LANCADAS;

DROP PROCEDURE VSUC_RETORNA_CONTAS_ONLINE;

DROP PROCEDURE SP_RETORNA_SALDO_MATRIZFILIAL;

DROP PROCEDURE SP_RETORNA_SALDO_MATRIZFILIAL_X;

DROP PROCEDURE SP_RETORNA_SALDO_NATUREZA_CONTA;

DROP PROCEDURE SP_SELECAO_TOMADOR;

DROP PROCEDURE SP_SETA_RECONTABILIZA;

DROP PROCEDURE SP_SETA_USUARIO;

DROP PROCEDURE SP_SETA_VARIAVEIS_SESSAO_BANCO;

DROP PROCEDURE SP_SOMENTE_ADMITIDOS_MES;

DROP PROCEDURE SP_SOMENTE_ATIVOS;

DROP PROCEDURE SP_SOMENTE_ATIVOS_RAIS;

DROP PROCEDURE SP_SOMENTE_ATIVOS_CAGED;

DROP PROCEDURE SP_SOMENTE_DEMITIDOS;

DROP PROCEDURE SP_SOMENTE_DEMITIDOS_MES;

DROP PROCEDURE SP_TEMPRESAIMPOSTO_REF;

DROP PROCEDURE SP_TEMPRESAS_REF;

DROP VIEW VWGR_VSUC_LANCAMENTO;

DROP PROCEDURE SP_TERCEIRO;

DROP PROCEDURE SP_TIPO_INS_SEFIP;

DROP PROCEDURE SP_TOL_VSUC_EMPRESAS_TLAN;

DROP PROCEDURE SP_TOMADOR_SEFIP;

DROP PROCEDURE SP_TREEVIEW_CONF_DEPARA_ONLINE;

DROP PROCEDURE SP_TREEVIEW_CONS_ANUAL_CONF;

DROP PROCEDURE SP_TREEVIEW_CONS_CONF_ONLINE;

DROP PROCEDURE SP_TREEVIEW_CONS_FORM_PAD_EF;

DROP PROCEDURE SP_TREEVIEW_CONS_GIA_FORMULA;

DROP PROCEDURE SP_TREEVIEW_CONS_IMP_EMITIDOS;

DROP PROCEDURE SP_UNION_FN_FC;

DROP PROCEDURE SP_TREEVIEW_PREP_CONTA;

SET TERM ^ ;

ALTER TRIGGER VRH_BASE_TVERBAS_AU0
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

SET TERM ; ^

DROP PROCEDURE SP_STATUS_PLANO_SCHIP;

DROP PROCEDURE SP_UPDATE_VERBA_ONLINE;

DROP PROCEDURE SP_COPIAR_CONF_SCHIP;

DROP PROCEDURE SP_GET_STATUS_NOTIFICACAO_SCHIP;

DROP PROCEDURE GETPRIVILEGIOSEMPRESAS_SCHIP;

DROP PROCEDURE SP_GET_ORDEM_SEQ_PLANO_SCHIP;

DROP PROCEDURE SP_FILA_PROCESSOS_SCHIP;

DROP PROCEDURE SP_ATUALIZA_NOME_PARTICIPANTES;

DROP PROCEDURE PADRONIZA_TEXTO;

DROP PROCEDURE SP_VSH_PODE_INICIAR_PROCESSO;

DROP PROCEDURE SP_PROX_DIA_DA_SEMANA;

DROP PROCEDURE SP_VAL_GPS_PROV_13;

DROP PROCEDURE SP_CONVERTE_COD_VERB_DASHBOARD;

DROP PROCEDURE SP_VAL_GPS_PROV_FER;

DROP PROCEDURE SP_VAL_HE_RAIS_FF;

DROP PROCEDURE SP_VAL_RAIS_FF;

DROP PROCEDURE SP_VEF_BASE_TCONFDACOM1424;

DROP PROCEDURE SP_VEF_EMP_PODEEXCLUIRVINCPROD;

DROP PROCEDURE SP_VEF_ENT_FORMULAS_DAPI;

DROP PROCEDURE SP_VEF_DAS_TOTALIZADOR_UF;
    
DROP PROCEDURE SP_VEF_EXPREG30_GIASP;

DROP PROCEDURE SP_VEF_FILTRO_NOTAS_NAO_LANCADA;

DROP PROCEDURE SP_VEF_LIVROENTRADA;

DROP PROCEDURE SP_VEF_LIVROSAIDA;

DROP PROCEDURE CLEARALLGLOBALTEMPORARYTABLE;

DROP PROCEDURE SP_VEF_REL_APURACAO_GIAMG;

DROP PROCEDURE SP_VEF_REL_RETENCOES;

DROP PROCEDURE SP_VEF_RETORNA_SALDO_DIME;

DROP PROCEDURE SP_VEF_TREEVIEW_CONS_ANUAL_CON2;

DROP PROCEDURE SP_VEF_TREEVIEW_CONS_BLOCOP;

DROP PROCEDURE SP_VEF_TREEVIEW_CONS_CALCATIVO;

DROP PROCEDURE SP_VEF_TREEVIEW_CONS_DACON;

DROP PROCEDURE SP_VEF_TREEVIEW_CONS_DIME;

DROP PROCEDURE SP_VEF_TREEVIEW_CONS_GIAES;

DROP PROCEDURE SP_VEF_TREEVIEW_CONS_GIAMG;

DROP PROCEDURE SP_VEF_TREEVIEW_CONS_GIAPR;

DROP PROCEDURE SP_VEF_TREEVIEW_CONS_GIARJ;

DROP PROCEDURE SP_VEF_TREEVIEW_CONS_GIARO;

DROP PROCEDURE SP_VEF_TREEVIEW_CONS_GIASP;

DROP PROCEDURE SP_VEF_TREEVIEW_CONS_ICMSSPED;

DROP PROCEDURE SP_VEF_TREEVIEW_CONS_IMPOSTOS;

DROP PROCEDURE SP_VEF_TREEVIEW_CONS_IPI;

DROP PROCEDURE SP_VEF_TREEVIEW_CONS_IRLP;

DROP PROCEDURE SP_VEF_TREEVIEW_CONSUF_GIASP;

DROP PROCEDURE SP_VERIFICATODASVERBASEMPPADRAO;

DROP PROCEDURE SP_VRH_APAGACALCULOS;

DROP PROCEDURE SP_VRH_BASE_MTE_TCONFRESC;

DROP PROCEDURE SP_VRH_BASE_TRESPEMP_PRINCIPAL;

DROP VIEW VW_VRHF_FGTSSEFIP_AGRUPA_CC_MES;

DROP PROCEDURE SP_VRH_CC_DATA;

DROP PROCEDURE SP_VRH_EMP_MULTVINC_PGTO;

DROP PROCEDURE SP_VRH_EMP_TCOLCON_VINC;

DROP PROCEDURE SP_VRH_FECHAMENTO;

DROP PROCEDURE SP_VRH_RETORNA_CONTR_SIND;

DROP PROCEDURE SP_RETORNA_TIPOS_CONTR_SIND;

DROP PROCEDURE SP_VRH_TREEVIEW_CONS_ADSALARIO;

DROP PROCEDURE SP_VRH_TREEVIEW_CONS_CALCAUT;

DROP PROCEDURE SP_VRH_TREEVIEW_CONS_CALCULO;

DROP PROCEDURE SP_VRH_TREEVIEW_CONS_CALCULOFC;

DROP PROCEDURE SP_VRH_TREEVIEW_CONS_CALCULOPR;

DROP PROCEDURE SP_VRH_TREEVIEW_CONS_COMP13SAL;

DROP PROCEDURE SP_VRH_TREEVIEW_CONS_FOLAVUL;

DROP PROCEDURE SP_VRH_TVERBAS_REF;

DROP PROCEDURE SP_VRH_VAL_RAIS_FF;

DROP PROCEDURE SP_VRH_VAL_RAIS_FF_REF;

SET TERM ^ ;

ALTER TRIGGER VRH_BASE_TEMPVINC_BIO
 AS DECLARE VARIABLE I INTEGER;
BEGIN I = 0; END
^

SET TERM ; ^

DROP PROCEDURE SP_EXPORTAR_LOG_SCHIP;

DROP PROCEDURE SP_VRHF_13SALARIO_ANO;

DROP PROCEDURE SP_VRHF_C13SALARIO_ANO;

DROP PROCEDURE SP_VRHF_13SALARIO_ANO_RESC;

DROP PROCEDURE SP_VRHF_13SALARIO_MAIORIGUALREF;

DROP PROCEDURE SP_VRHF_AD13SAL_ANO;

DROP PROCEDURE SP_VRHF_AD13SAL_ANO_RESC;

DROP PROCEDURE SP_VRHF_AD13SAL_MAIORREF;

DROP PROCEDURE SP_VRHF_BASE_CALC_TERC;

DROP PROCEDURE SP_VRHF_BASE_TVERBASEMP_CONS;

DROP PROCEDURE SP_VRHF_CONS_BASES_AD;

DROP PROCEDURE SP_VRHF_CONS_BASES_FN;

DROP PROCEDURE SP_VRHF_DADOS_INSS_13;

DROP PROCEDURE SP_VRHF_DADOS_INSS_C13;

DROP PROCEDURE SP_VRHF_DADOS_INSS_FC;

DROP PROCEDURE SP_VRHF_DADOS_INSS_FC_ESOCIAL;

DROP PROCEDURE SP_ESOCIAL_DADOS_INSS_FN;

DROP PROCEDURE SP_ESOCIAL_DADOS_INSS_FT;

DROP PROCEDURE SP_VRHF_DADOS_INSS_FN;

DROP PROCEDURE SP_VRHF_DADOS_INSS_FT;

DROP PROCEDURE SP_VRHF_DADOS_INSS_FTC;

DROP PROCEDURE SP_VRHF_DADOS_INSS_FTC_ESOCIAL;

DROP PROCEDURE SP_VRHF_DADOS_IR_DARF;

DROP PROCEDURE SP_VRHF_DADOS_IR_5012;

DROP PROCEDURE SP_VRHF_DADOS_IR_DIRF;

DROP PROCEDURE SP_VRHF_DADOS_IR_RT;

DROP PROCEDURE SP_VRHF_DADOS_IR_TEMRRAANO;

DROP PROCEDURE SP_VRHF_DADOS_IR_FN2;

DROP PROCEDURE SP_FGTS_DIGITAL_COMP;

DROP PROCEDURE SP_VRHF_DADOS_FGTS_FN;

DROP PROCEDURE SP_VRHF_DADOS_FGTS_FC;

DROP PROCEDURE SP_VRHF_DADOS_FGTS_13;

DROP PROCEDURE SP_VRHF_DADOS_FGTS_A13;

DROP PROCEDURE SP_VRHF_DADOS_FGTS_C13;

DROP PROCEDURE SP_VRHF_DADOS_FGTS_FER;

DROP PROCEDURE SP_VRHF_DADOS_PIS_13;

DROP PROCEDURE SP_VRHF_DADOS_PIS_C13;

DROP PROCEDURE SP_VRHF_DADOS_PIS_FC;

DROP PROCEDURE SP_VRHF_DADOS_PIS_FN;

DROP PROCEDURE SP_VRHF_DADOS_PIS_AD13;

DROP PROCEDURE SP_VRHF_EMP_BASES_RESCISAO;

DROP PROCEDURE SP_VRHF_EMP_TFOLHANORMAL_ANT;

DROP PROCEDURE SP_VRHF_EMP_TPROVISAO13;

DROP PROCEDURE SP_VRHF_EMP_TPROVISAOFERIAS;

DROP PROCEDURE SP_VRHF_FC_VALORES_INDENIZADOS;

DROP PROCEDURE SP_VRHF_FN_VALORES_INDENIZADOS;

DROP PROCEDURE SP_VRHF_FOLHACOMPLEMENTAR;

DROP PROCEDURE SP_VRHF_FOLHANORMAL;

DROP PROCEDURE SP_VRHF_TCOL_VINC_REF;

DROP PROCEDURE SP_VRHF_VERBAS_AGRUPADAS_FN;

DROP PROCEDURE SP_VRHF_VERBAS_FN_FC;

DROP PROCEDURE SP_VRHM_FF_OP_ANO;

DROP PROCEDURE SP_VRHF_DADOS_SAUDE;

DROP PROCEDURE SP_VRHM_FF_OP_REF;

DROP PROCEDURE SP_VRHM_VAL_PS_COL;

DROP PROCEDURE SP_VRHM_VAL_PS_DEP;

DROP PROCEDURE SP_VSUC_COPIA_CT_PLANO_DFIS;

DROP PROCEDURE SP_VSUC_COPIA_CT_PLANO_FCONT;

DROP PROCEDURE SPCLASSVERBAONLINE;

DROP PROCEDURE SP_DADOS_GPS_COMP;

DROP PROCEDURE SP_DADOS_REL_QTDFOLHAS;

DROP PROCEDURE SP_BUSCA_VALOR_PIS_VERBAS;

DROP PROCEDURE SP_RETORNA_TAGSTR_TOTALIZADORES;

DROP PROCEDURE SP_HORARIOS_INTERMITENTES;

DROP PROCEDURE SP_HORARIO_INTERMITENTES_DIARIO;

DROP PROCEDURE SP_RH_UNION_FC_FCT_MES;

DROP PROCEDURE SPCODIMPGPSCOMPLEMENTAR;

DROP PROCEDURE SPCODIMPGPSCOMPLEMENTAR_ESOCIAL;

DROP PROCEDURE SPCORACENTOS;

DROP PROCEDURE SPCORRIGEACENTOS;

DROP PROCEDURE SPRH_CALC_13SALARIO;

DROP PROCEDURE SPRH_CALC_AD13SALARIO;

DROP PROCEDURE SPRH_CALC_ADSAL;

DROP PROCEDURE SPRH_CALC_AUTONOMO;

DROP PROCEDURE SPRH_CALC_FERIAS;

DROP PROCEDURE SPRH_CALC_FOLHACOMP;

DROP PROCEDURE SPRH_CONS_CALC_13SALARIO;

DROP PROCEDURE SPRH_CONS_CALC_AD13SALARIO;

DROP PROCEDURE SPRH_MENSAGENS_RECIBO;

DROP PROCEDURE SPRH_TREEVIEW_CONS_13SAL;

DROP PROCEDURE SPRH_TREEVIEW_CONS_AD13SAL;

DROP PROCEDURE SPVAL_ITINERARIO;

DROP PROCEDURE VRHF_SP_TFOLHA_NORMAL_PREV_RESC;

DROP PROCEDURE STRZERO;

DROP PROCEDURE TRUNCAR;

DROP PROCEDURE SP_VRHF_REL_ACOMPANHAMENTO;

DROP PROCEDURE ULTIMO_DIA_MES;

DROP PROCEDURE VCT_SERVICO_SUBORDINADO;

DROP PROCEDURE VCT_TAREFA_SUBORDINADA;

DROP PROCEDURE VEF_COPIA_PLANO_BLOCOP;

DROP PROCEDURE VEF_COPIA_PLANO_DACON;

DROP PROCEDURE VEF_COPIA_PLANO_DIME;

DROP PROCEDURE VEF_COPIA_PLANO_GIA;

DROP PROCEDURE VEF_COPIA_PLANO_IMPOSTOS;

DROP PROCEDURE VEF_SP_BASE_CONFBASESN;

DROP PROCEDURE VEF_SP_BASE_CONFBASESNATVM;

DROP PROCEDURE VEF_SP_BASE_CONFBASESNNATOP;

DROP PROCEDURE VEF_SP_CONSULTA_CONFATIVA;

DROP PROCEDURE VEF_SP_CONSULTA_VINCULOISS;

DROP PROCEDURE VEF_SP_JOINNATPREPONDERANTE;

DROP PROCEDURE VEF_SP_JOINNATNAOPREPONDERANTE;

DROP PROCEDURE VEF_SP_JOINATVPREPONDERANTE;

DROP PROCEDURE VEF_SP_JOINATVNAOPREPONDERANTE;

DROP PROCEDURE VEF_SP_CONSULTALAN_ENT;

DROP PROCEDURE VEF_SP_CONSULTALAN_SAI;

DROP PROCEDURE VEF_SP_DADOS_ISS_EXP;

DROP PROCEDURE VEF_SP_DADOSQ46;

DROP VIEW VW_VEF_EMP_TDIMEGERUNION;

DROP PROCEDURE VEF_SP_DIMEQ46;

DROP PROCEDURE VEF_SP_DIRF;

DROP PROCEDURE VEF_SP_DIRF_RTIRF;

DROP PROCEDURE VEF_SP_DIRF_RTRT;

DROP PROCEDURE VEF_SP_EXCLUI_REDZVARCFOP_PLANO;

DROP PROCEDURE VEF_SP_EXP_DIME;

DROP PROCEDURE VEF_SP_EXP_DIPJ_REG1_18;

DROP PROCEDURE VEF_SP_EXP_DIPJ_REG1_3;

DROP PROCEDURE VEF_SP_EXP_DIPJ_REG19;

DROP PROCEDURE VEF_SP_EXP_DIPJ_REG20;

DROP PROCEDURE VEF_SP_EXP_DIPJ_REG21;

DROP PROCEDURE VEF_SP_EXP_DIPJ_REG22;

DROP PROCEDURE VEF_SP_EXP_DIPJ_REG23;

DROP PROCEDURE VEF_SP_EXP_DIPJ_REG24;

DROP PROCEDURE VEF_SP_EXP_DIPJ_REG25;

DROP PROCEDURE VEF_SP_EXP_DIPJ_REG26;

DROP PROCEDURE VEF_SP_EXP_DIPJ_REG54;

DROP PROCEDURE VEF_SP_EXP_DIPJ_REG59;

DROP PROCEDURE VEF_SP_EXP_DIPJ_REG60_61A;

DROP PROCEDURE VEF_SP_EXP_GIASP;

DROP PROCEDURE VEF_SP_EXP_GISSONLINE;

DROP PROCEDURE VEF_SP_EXP_SPEDCONTRIBUICAO;

DROP PROCEDURE VEF_SP_EXP_TERCEIRO;

DROP PROCEDURE VEF_SP_EXP_TNATOP;

DROP PROCEDURE VEF_SP_EXP_TPRODUTOS;

DROP PROCEDURE SP_GET_VALOR_ISE_OUT;

DROP PROCEDURE VEF_SP_LANCAMENTOS;

DROP PROCEDURE VEF_SP_REL_CONFERENCIA_ICMSST;

DROP PROCEDURE VEF_SP_RET_TOT_NAT_ENT;

DROP PROCEDURE VEF_SP_RET_TOT_NAT_SAI;

DROP PROCEDURE VEF_SP_RETORNA_DIME_Q47;

DROP PROCEDURE VEF_SP_RETORNA_DIME_Q48;

DROP PROCEDURE VEF_SP_RETORNA_DIME_VENC_PRODEC;

DROP PROCEDURE VEF_SP_RETVLRSTSP;

DROP PROCEDURE VEF_SP_SPED_LAN_ENT;

DROP PROCEDURE VEF_SP_SPED_LAN_ENT_PRO;

DROP PROCEDURE VEF_SP_SPED_LAN_SAI;

DROP PROCEDURE VEF_SP_SPED_LAN_SAI_PRO;

DROP PROCEDURE VEF_SP_SPED_TERCEIRO;

DROP PROCEDURE VEF_SP_SVA_431;

DROP PROCEDURE VEF_SP_SPED_D600;

DROP PROCEDURE VEF_SP_SPED_D610;

DROP PROCEDURE VEF_SP_SPED_D696;

DROP PROCEDURE VEF_SP_SVA_4310_TREDZ;

DROP PROCEDURE VEF_SP_SVA_432;

DROP PROCEDURE VEF_SP_SVA_433;

DROP PROCEDURE VEF_SP_SVA_434;

DROP PROCEDURE VEF_SP_SVA_491;

DROP PROCEDURE VEF_SP_SVA_494;

DROP PROCEDURE VEF_SP_SVA_495;

DROP PROCEDURE VEF_SP_SVA_EXP_491;

DROP PROCEDURE VEF_SP_SVA_EXP_494;

DROP PROCEDURE VEF_SP_SVA_EXP_495;

DROP PROCEDURE VEF_SP_SVA_EXP_CAD;

DROP PROCEDURE VEF_SP_SVA_SERVICOS_ITENS;

DROP PROCEDURE VEF_SP_SVA_SERVICOS_MOV;

DROP PROCEDURE VEF_SP_TREEVIEW_CONS_ANUAL_CONF;

DROP PROCEDURE VLAL_CONSULTA_APU_TREEWIEW;

DROP PROCEDURE VLAL_COPIA_PARTEA_PLANO;

DROP PROCEDURE VLAL_COPIA_PARTEB_PLANO;

DROP PROCEDURE VLAL_SP_CONS_ACUM_PARTEA;

DROP PROCEDURE VLAL_SP_LAN_PARTEA;

DROP PROCEDURE VLAL_SP_RETORNA_INT_CONTABLALUR;

DROP PROCEDURE VLAL_SP_DEMONSTRACAO_PARTEB;

DROP PROCEDURE VRH_COPIA_FUNCOES_PLANO;

DROP PROCEDURE VRH_COPIA_LAYOUT_PLALANC;

DROP PROCEDURE VRH_COPIA_VERBASBS_PLANO;

DROP PROCEDURE VRH_INS_VERBA;

DROP PROCEDURE VRH_SP_ADMITIDOS_NO_MES;

DROP PROCEDURE VRH_SP_ALTERACAOSALARIAL;

DROP PROCEDURE VRH_SP_ATIVOS_NO_MES;

DROP PROCEDURE VRH_SP_AUMENTOSALARIO;

DROP PROCEDURE VRH_SP_CAD_TERC;

DROP PROCEDURE VRH_SP_COLCON;

DROP PROCEDURE VRH_SP_COLCON_DIA;

DROP PROCEDURE VRH_SP_COLCON_EDIT;

DROP PROCEDURE VRH_SP_COLCON_VERBAS_ASS;

DROP PROCEDURE VRH_SP_CONS_CBO_SIN;

DROP PROCEDURE VRH_SP_CONS_COL;

DROP PROCEDURE VRH_SP_CONS_COL_NOVO;

DROP PROCEDURE VRH_SP_CONS_COLCON;

DROP PROCEDURE VRH_SP_CONS_CON;

DROP PROCEDURE VRH_SP_CONS_FERIAS_PER_AQUIS;

DROP PROCEDURE VRH_SP_CONS_VERBAS;

DROP PROCEDURE VRH_SP_CONSULTA_SITUACAO;

DROP PROCEDURE VRH_SP_DADOS_FALTAS;

DROP PROCEDURE VRH_SP_DADOS_FERIAS;

DROP PROCEDURE VRH_SP_DADOS_FERIAS_RESCISAO;

DROP PROCEDURE VRH_SP_DADOS_SITUACAO;

DROP PROCEDURE VRH_SP_DADOS_SITUACAO_RESCISAO;

DROP PROCEDURE VRH_SP_DADOS_SITUACAO2;

DROP PROCEDURE VRH_SP_DEMITIDOS_NO_MES;

DROP PROCEDURE VRH_SP_EMPRESAS;

DROP PROCEDURE VRH_SP_FERIAS_PER_AQUIS;

DROP PROCEDURE VRH_SP_FERIAS_PER_AQUIS_RESC;

DROP PROCEDURE VRH_SP_GRRF;

DROP PROCEDURE VRH_SP_GRRF_FC;

DROP PROCEDURE VRH_SP_LISTAADM_RESC;

DROP PROCEDURE VRH_SP_LISTAADM_RESC_TOT_EMP;

DROP PROCEDURE VRH_SP_REL_RECIBO_13SAL;

DROP PROCEDURE VRH_SP_REL_RECIBO_AD13;

DROP PROCEDURE VRH_SP_REL_RECIBO_ADIANTAMENTO;

DROP PROCEDURE VRH_SP_REL_RECIBO_C13SAL;

DROP PROCEDURE VRH_SP_REL_RECIBO_FOLCOMP;

DROP PROCEDURE VRH_SP_REL_RECIBO_FOLHA_AVULSA;

DROP PROCEDURE SP_VRHF_UNION_FT_MES;

DROP PROCEDURE VRH_SP_RELATORIO_CAT_AGCAUSA;

DROP PROCEDURE VRH_SP_RELATORIO_CAT_PCORPO;

DROP PROCEDURE VRH_SP_RELATORIO_CAT2;

DROP PROCEDURE VRH_SP_SERV_TERC;

DROP PROCEDURE VRH_SP_SERV_TERC_MANUAL;

DROP PROCEDURE VRH_SP_SINDTRAB;

DROP PROCEDURE VRH_SP_TSITCOL;

DROP PROCEDURE VRH_SP_VERBA_ASSOC_TAB;

DROP PROCEDURE VRH_SP_VERBA_ASSOC_TAB_PREP;

DROP PROCEDURE VRHF_EMP_VAL_GRRF;

DROP PROCEDURE VRHF_MEDIAS;

DROP PROCEDURE VRHF_SP_ARREDONDAMENTOS;

DROP PROCEDURE VRHF_SP_BANCO_HORAS;

DROP PROCEDURE VRHF_SP_CALC_AUTONOMO;

DROP PROCEDURE VRHF_SP_CALC_FN_AUT;

DROP PROCEDURE VRHF_SP_CALC_FN_AUT_PREV;

DROP PROCEDURE VRHF_SP_CALC_FOLHANORMAL;

DROP PROCEDURE VRHF_SP_CALC_GPS;

DROP PROCEDURE VRHF_SP_CONS_13SALARIO;

DROP PROCEDURE VRHF_SP_CONS_AD13SALARIO;

DROP PROCEDURE VRHF_SP_CONS_ADIANTA_SAL;

DROP PROCEDURE VRHF_SP_CONS_CALC_13SALARIO;

DROP PROCEDURE VRHF_SP_CONS_CALC_AUTONOMOS;

DROP PROCEDURE VRHF_SP_CONS_CALC_COMP13SALARIO;

DROP PROCEDURE VRHF_SP_CONS_CALC_FERIAS;

DROP PROCEDURE VRHF_SP_CONS_CALC_FOLHACOMP;

DROP PROCEDURE VRHF_SP_CONS_CALC_FOLHANORMAL;

DROP PROCEDURE VRHF_SP_CONS_CALC_FOLHANORMALPR;

DROP PROCEDURE VRHF_SP_CONS_CALCTERC;

DROP PROCEDURE VRHF_SP_CONS_COMP13SALARIO;

DROP PROCEDURE VRHF_SP_CONS_FOLHANORMAL;

DROP PROCEDURE VRHF_SP_DADOS_BAIXA_CALCULO;

DROP PROCEDURE VRHF_SP_DADOS_CALC_GPS;

DROP PROCEDURE VRHF_SP_DADOS_IND_CALC_GPS;

DROP PROCEDURE VRHF_SP_ESTOUROS;

DROP PROCEDURE VRHF_SP_EXTRATO_FGTS;

DROP PROCEDURE VRHF_SP_FICHA_REG_COLABORADOR;

DROP PROCEDURE VRHF_SP_FICHAFGTS2;

DROP PROCEDURE VRHF_SP_FICHAINSS;

DROP PROCEDURE VRHF_SP_FICHAIR;

DROP PROCEDURE VRHF_SP_FICHAIR_ANUAL;

DROP PROCEDURE VRHF_SP_FICHARAIS;

DROP PROCEDURE VRHF_SP_FICHARAIS_NOVO;

DROP PROCEDURE VRHF_SP_FN_FC_13_C13_VERBAS;

DROP PROCEDURE VRHF_SP_GPS;

DROP PROCEDURE VRHF_SP_GPS_CONTRATANTE;

DROP PROCEDURE VRHF_SP_GPS_FUNRURAL;

DROP PROCEDURE VRHF_SP_GPS_FUNRURAL_RESUMO;

DROP PROCEDURE SP_VRHF_FUNRURAL;

DROP PROCEDURE VRHF_SP_ACU_GPS_FUNRURAL;

DROP PROCEDURE VRHF_SP_GRCSCOLABORADOR;

DROP PROCEDURE VRHF_SP_GRCSEMPRESA;

DROP PROCEDURE VRHF_SP_HIST_ACUMU_GPS;

DROP PROCEDURE VRHF_SP_OUTRASINF_CALC;

DROP PROCEDURE VRHF_SP_OUTRASINF_CALC_ATIVOS;

DROP PROCEDURE VRHF_SP_OUTRASINF_CALC_AUT;

DROP PROCEDURE VRHF_SP_QUADROHORARIOS;

DROP PROCEDURE VRHF_SP_RECIBO_FERIAS;

DROP PROCEDURE VRHF_SP_REL_DECLARA_RENDIMENTOS;

DROP PROCEDURE SP_VRHF_DECLARACAO_DOMESTICO;

DROP PROCEDURE VRHF_SP_REL_LIQUIDO_FOLHA;

DROP PROCEDURE VRHF_SP_REL_PREVIA_RESC;

DROP PROCEDURE VRHF_SP_REL_PREVIA_RESC2;

DROP PROCEDURE VRHF_SP_REL_RECIBO_RESCISAO;

DROP PROCEDURE VRHF_SP_REL_RECIBO_RESCISAO2;

DROP PROCEDURE VRHF_SP_RETORNAEMPRESA_GPS;

DROP PROCEDURE VRHF_SP_SALARIOS_CONTRIB;

DROP PROCEDURE VRHF_SP_TCALC_AUTONOMO;

DROP PROCEDURE VRHF_SP_TCOMPENSACAOGPS;

DROP PROCEDURE SP_VRHF_MEDIAS;

DROP VIEW VW_FGTS_TOMADOR_FN_FC;

DROP PROCEDURE SP_VRHF_HISTORICO_FAP;

DROP PROCEDURE SP_VRHF_AGRUPAR_QH;

DROP PROCEDURE VRHF_SP_TFOLHA_NORMAL;

DROP PROCEDURE VRHF_SP_TFOLHA_INT;

DROP PROCEDURE VRHF_SP_TFOLHACOMP;

DROP PROCEDURE VRHF_SP_TIPO_TOMADOR_GPS;

DROP PROCEDURE VRHF_SP_TNFCOOP;

DROP PROCEDURE VRHF_SP_TODAS_GPS;

DROP VIEW VW_VRHF_FGTSSEFIP_13_CC;

DROP VIEW VW_VRHF_EMP_T13SAL_RAT_CC;

DROP VIEW VW_VRHF_EMP_T13SAL_RAT_TOM;

DROP VIEW VW_VRHF_EMP_TPREPFN_ATU;

DROP VIEW VW_VRHF_EMP_TVERBA_13_RAT_CC;

DROP VIEW VW_VRHF_EMP_TVERBA_13_RAT_TOM;

DROP VIEW VW_VRHF_FGTSSEFIP_AGRUPA_3;

DROP PROCEDURE VRHF_SP_TOMADOR;

DROP PROCEDURE VRHF_SP_TOTAL_COL_ATIVOS;

DROP PROCEDURE VRHF_SP_TOTPRO_TOTDESC;

DROP PROCEDURE VRHF_SP_TOTPRO_TOTDESC_ADSAL;

DROP PROCEDURE VRHF_SP_TPREPFB_CC;

DROP PROCEDURE VRHF_SP_TPREPFN_CC_REF;

DROP PROCEDURE VRHF_SP_TPREPFN_REF;

DROP PROCEDURE VRHF_SP_TTEMPOTRAB;

DROP PROCEDURE VRHF_SP_TVERBAFC;

DROP PROCEDURE VRHF_SP_TVERBAFN;

DROP PROCEDURE SP_VRHF_AGRUPA_VERBAS_FT;

DROP PROCEDURE VRHF_SP_TVERBAFN_PREV_RESC;

DROP PROCEDURE VRHF_SP_UNION_VERBAS_SIM_NAO;

DROP PROCEDURE VRHF_SP_UNION_VERBAS_SIM_NAO_2;

DROP PROCEDURE VRHF_SP_UNIONCALCDETALHE;

DROP PROCEDURE VRHF_SP_VALORES_CONTRIB_SINDICA;

DROP PROCEDURE VRHF_SP_VERBAS_FN_FC;

DROP PROCEDURE VRHF_SP_VERBAS_FOL_NORMAL_AUT;

DROP PROCEDURE SP_VRH_VERBAS;

DROP PROCEDURE VRHF_SP_VERBAS_FOLHA;

DROP PROCEDURE VRHF_SP_VERBAS_PREV_RESC;

DROP PROCEDURE VRHF_SP_VERBAS_SIM_COL_CALC;

DROP PROCEDURE VRHF_SP_VERBAS_SIM_PRES_CALC;

DROP PROCEDURE VRHF_SPF_BC_PROLAB_COLAB;

DROP PROCEDURE VRHF_SPF_BC_PROLABORISTAS;

DROP PROCEDURE VRHF_SPF_BC_RAT;

DROP PROCEDURE VRHF_SPF_BC_SEGURADOS;

DROP PROCEDURE VRHF_SPF_BC_TERCEIROS;

DROP PROCEDURE VRHF_SPF_PROLAB_COLAB;

DROP PROCEDURE VRHF_SPF_PROLABORISTAS;

DROP PROCEDURE VRHF_SPF_RATAPO;

DROP PROCEDURE VRHF_SPF_SALFAM;

DROP PROCEDURE VRHF_SPF_SALMATERNIDADE;

DROP PROCEDURE VRHF_SPF_SEGURADOS;

DROP PROCEDURE VRHF_SPF_VALNOTAFISCAL;

DROP PROCEDURE VSUC_COPIA_CENTROS_PLANO;

DROP PROCEDURE VSUC_COPIA_CONTAS_PLANO;

DROP PROCEDURE VSUC_COPIA_CONTAS_PLANO_FCONT;

DROP PROCEDURE VSUC_COPIA_CONTAS_PLANO_SPED;

DROP PROCEDURE VSUC_COPIA_FORMULAS_PLANO;

DROP PROCEDURE VSUC_COPIA_PLANILHA_TLAN;

DROP PROCEDURE VSUC_COPIA_HISTORICOS_PLANO;

DROP PROCEDURE VSUC_COPIA_HORARIO_PLANO;

DROP PROCEDURE VSUC_COPIA_MOEDAS_PLANO;

DROP PROCEDURE VSUC_GETDEMONSTRATIVO;

DROP PROCEDURE VSUC_LANCAMENTOS_AGRUPADOS;

DROP PROCEDURE VSUC_NRO_NOTA_COMPL;

DROP PROCEDURE VSUC_SP_ALTERA_LANCAMENTOS;

DROP PROCEDURE VSUC_SP_RESTAURA_LANCS_LIXEIRA;

DROP PROCEDURE VSUC_SP_MOVE_LANC_LIXEIRA;

DROP PROCEDURE VSUC_SP_RESTAURA_LANC_LIXEIRA;

DROP PROCEDURE VSUC_SP_BALANCETE_MENSAL;

DROP PROCEDURE VSUC_SP_CENTRAL_CONCILIACAO;

DROP PROCEDURE VSUC_SP_BALANCO_MENSAL;

DROP PROCEDURE VSUC_SP_BALANCO_PATRIMONIAL;

DROP PROCEDURE VSUC_SP_CONCILIACAO_AUTOMATICA;

DROP PROCEDURE VSUC_SP_CONSOLIDADA;

DROP PROCEDURE VSUC_SP_COPIA_CONTAS_FORMULAS;

DROP PROCEDURE VSUC_SP_COPY_PREPARACAO_FOR_ECF_Y520;

DROP PROCEDURE VSUC_SP_EXPORTA_SPED_I300;

DROP PROCEDURE VSUC_SP_IMPORTAFORMULA;

DROP PROCEDURE VSUC_SP_INSERT_ENCEX;

DROP PROCEDURE VSUC_SP_INSERT_LANC;

DROP PROCEDURE VSUC_SP_LISTA_CTA_RAZAO_VIDEO;

DROP PROCEDURE VSUC_SP_LISTA_CTA_RAZAO_VIDEO_X;

DROP PROCEDURE VSUC_SP_LISTA_TLAN_CONC_CLIFOR;

DROP PROCEDURE VSUC_SP_MOVIMENTO_MENSAL;

DROP PROCEDURE VSUC_SP_NOMENCLATURA_CTA_PARTIC;

DROP PROCEDURE VSUC_SP_PERMITECALCSALDOLANCMF;

DROP PROCEDURE VSUC_SP_RETORNA_BALANCETE;

DROP PROCEDURE VSUC_SP_RETORNA_SALDOS_CTAINCOR;

DROP PROCEDURE VSUC_SP_RETORNA_SALDOS_INCORP_2;

DROP PROCEDURE VSUC_RETORNA_CLA_INCORP;

DROP PROCEDURE VSUC_COPIA_PLANO_TROCA;

DROP PROCEDURE SP_REMOVE_CLASS_ZERADAS;

DROP PROCEDURE VSUC_COPIA_PLANO_SECUNDARIO;

DROP PROCEDURE VSUC_SP_RETORNA_CONTAS_I157;

DROP PROCEDURE VSUC_SP_RETORNA_BALANCETE_COMPA;

DROP PROCEDURE VSUC_SP_RETORNA_BALANCO_PATRIMO;

DROP PROCEDURE VSUC_SP_RETORNA_CADASTRO_BEM;

DROP PROCEDURE VSUC_SP_RETORNA_CLASSGROUP;

DROP PROCEDURE VSUC_SP_RETORNA_COMPARATIVO;

DROP PROCEDURE VSUC_SP_RETORNA_COMPARATIVO_X;

DROP PROCEDURE VSUC_SP_RETORNA_COMPARATIVO_Y;

DROP PROCEDURE VSUC_SP_RETORNA_CONTAS_USADAS;

DROP PROCEDURE VSUC_SP_RETORNA_CONTR_PATRIMON;

DROP PROCEDURE VSUC_SP_RETORNA_CRITICA_LANC;

DROP PROCEDURE VSUC_SP_RETORNA_DIARIO;

DROP PROCEDURE VSUC_SP_RETORNA_MOV_DIARIO;

DROP PROCEDURE VSUC_SP_RETORNA_MOV_MENSAL;

DROP PROCEDURE VSUC_SP_RETORNA_PLANOS_TPLA;

DROP PROCEDURE VSUC_SP_RETORNA_RAZAO_CONTAS;

DROP PROCEDURE VSUC_SP_RETORNA_RAZAO_CONTAS_X;

DROP PROCEDURE VSUC_SP_RETORNA_RAZAO_SALDO;

DROP PROCEDURE VSUC_SP_RETORNA_SALDO_CREDOR;

DROP PROCEDURE VSUC_SP_RETORNA_RAZAO_SALDO_X;

DROP PROCEDURE VSUC_SP_RETORNA_RAZAO_SALDO2;

DROP PROCEDURE VSUC_SP_RETORNA_REL_ORCA;

DROP PROCEDURE VSUC_SP_RETORNA_RELESTATIST_GRA;

DROP PROCEDURE VSUC_SP_RETORNA_RELESTATISTGRA;

DROP PROCEDURE VSUC_SP_RETORNA_RELESTATISTICA;

DROP PROCEDURE VSUC_SP_RETORNA_SALDO;

DROP PROCEDURE VSUC_SP_RETORNA_SALDO_CONS_ORCA;

DROP PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS;

DROP PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS_CC;

DROP PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS_X;

DROP PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS_XZ;

DROP PROCEDURE VSUC_SP_RETORNA_SALDO_LANC;

DROP PROCEDURE VSUC_SP_RETORNA_SALDO_ORCA;

DROP PROCEDURE VSUC_SP_RETORNA_SALDOS_CTA_PART;

DROP PROCEDURE VSUC_SP_RETORNA_SALDOS_CTAPARTY;

DROP PROCEDURE SP_GET_CLASSIFICACAO_NIVEL;

DROP PROCEDURE VSUC_SP_MONTA_CONCILIACAO;

DROP PROCEDURE VSUC_SP_RETORNA_TOTAIS_LANC;

DROP PROCEDURE VSUC_SP_TENC_EXERCICIO;

DROP PROCEDURE VSUC_SP_UPDATE_TLAN_CONC_BANC;

DROP PROCEDURE VSUC_SP_UPDATE_TLAN_CONC_CLIFOR;

DROP PROCEDURE SP_VRH_EMP_GERENCIAL_PORIDADE;

DROP PROCEDURE SP_VRH_EMP_GERENCIAL_PORTEMPO;

DROP PROCEDURE SP_VRH_EMP_GERENCIAL_PORFUNCAO;

DROP PROCEDURE SP_VRH_EMP_GERENCIAL_PORINST;

DROP PROCEDURE SP_VRH_EMP_GERENCIAL_PORRESC;

DROP PROCEDURE VSUC_SP_RETORNA_BALANCO_PATRI_X;

DROP PROCEDURE SP_LANCA_AJUSTE_E115;

DROP PROCEDURE SP_VRHF_DADOS_INSS_FN_PREV_RESC;
 
DROP PROCEDURE SP_VRHF_DADOS_INSS_FT_PREV_RESC;

DROP PROCEDURE VRH_SP_DADOS_PREPSITUACAO;

DROP PROCEDURE SP_CRIA_PRE_CONTABILIZACAODIFAL;

DROP PROCEDURE SP_CRIA_PRE_CONTABILIZACAO_AUX;

DROP PROCEDURE SP_CRIA_CONTAB_RET_FUNRURAL;

DROP PROCEDURE SP_CRIA_PRE_CONTABILIZACAO_RET;

DROP PROCEDURE SP_CRIA_PRE_CONTABILIZACAO;

DROP PROCEDURE SP_GET_HISTORICOCOMPLETO;

DROP PROCEDURE SP_BI_DRE;

DROP PROCEDURE SP_BI_FAT;

DROP PROCEDURE SP_BI_FAT_TODAS;

DROP PROCEDURE SP_BI_CONF_FOLHA;

DROP PROCEDURE SP_BI_CONF_FOLHA_TODAS;

DROP PROCEDURE GETINTEGERLIST;

DROP PROCEDURE SP_BI_RELATORIOS;

DROP PROCEDURE SP_GET_CLASSIFICACAO_SEM_ZEROS;

DROP procedure VSUC_SP_COPY_PREPARACAO_FOR_ECF;

DROP procedure VSUC_SP_COPY_PREPARACAO_FOR_ECF_PAIS;

DROP PROCEDURE SP_PRIMEIRO_NUMERO;

/* Drop Trigger... */
DROP TRIGGER VRHF_EMP_TVERBAFC_DET_BI0;

DROP TRIGGER TOL_VEF_EMP_TMOVDCOMP_AD0;

DROP TRIGGER VEF_EMP_TMOVSERTHEMA_BI0;

DROP TRIGGER vef_emp_tplanilhasndeb_bd0;

DROP TRIGGER VRHF_EMP_TVERBAFCT_DET_BI0;

DROP TRIGGER VRHF_EMP_TVERBAFCTINT_DET_BI0;

DROP TRIGGER VRHF_EMP_TVERBAFCINT_DET_BI0;

DROP TRIGGER VRH_BASE_TTIPOFOLHACOMP_BI0;

DROP TRIGGER VRH_BASE_CLASSTRIBUTARIA_BI0;

DROP TRIGGER TLOG_BU0;

DROP TRIGGER VTPO_TCONF_BI;

DROP TRIGGER VTPO_MOTIVO_INATIVIDADE_BI0;

DROP TRIGGER VSST_EMP_TAUTODECLARACAO_BI0;

DROP TRIGGER VSST_EMP_TAUTO_DOC_BI0;

DROP TRIGGER JUSTIFICATIVA_INATIVIDADE_bi0;

DROP TRIGGER VRH_ESOCIAL_TARQUIVO_BU0;

DROP TRIGGER VRH_ESOCIAL_TARQUIVO_AU0;

DROP TRIGGER VRH_ESOCIAL_TARQUIVO_AD0;

DROP TRIGGER VRH_ESOCIAL_TARQUIVO_BD0;

DROP TRIGGER VRH_ESOCIAL_TARQUIVO_AI0;

DROP TRIGGER VSUC_EMPRESAS_TPRE_ECF_Y665_BI0;

DROP TRIGGER tr_bf_insert_vsuc_tconfig_imp_c;

DROP TRIGGER TIDIOMAS_BI0;

DROP TRIGGER TACESSOSITEGOV_BI0;

DROP TRIGGER TINDVAL_BIU0;

DROP TRIGGER vlal_imp_contablalur_bd0;

DROP TRIGGER vef_emp_tmovccdemdocf100_bi0;

DROP TRIGGER CENTROS_TPCC_BD0;

DROP TRIGGER EMPRESAS_TDEPRECIACAO_BI0;

DROP trigger empresas_tvalorresidual_bi0;

DROP TRIGGER EMPRESAS_TSOC_BU0;

DROP TRIGGER PLANOS_TPLA_BD0;

DROP TRIGGER PLANOS_TPLA_BU0;

DROP TRIGGER PLANOS_TPLA_FCONT_PADRAO_BI0;

DROP TRIGGER PLANOS_TPLA_SPED_PADRAO_BI0;

DROP TRIGGER TASSINATURA_BI0;

DROP TRIGGER TBANCOS_BI0;

DROP TRIGGER TBANCOS_FEBRABAN_BI0;

DROP TRIGGER TBLOQLAN_BI0;

DROP TRIGGER TBLOQLAN_EMPRESA_AI0;

DROP TRIGGER TBLOQLAN_EMPRESA_BD0;

DROP TRIGGER TBLOQLAN_EMPRESA_BI0;

DROP TRIGGER TCADPRO_ATVCONPREV_BI0;

DROP TRIGGER TCADPRO_BI0;

DROP TRIGGER TCAMPOSGERADOR_BI0;

DROP TRIGGER TCAT_AGENTECAUSADOR_BI0;

DROP TRIGGER TCAT_PCORPOATINGIDA_BI0;

DROP TRIGGER TCAT_SITGERACTRAB_BI0;

DROP TRIGGER TCLASSE_VENCIMENTO_BI0;

DROP TRIGGER TCNAE_BI0;

DROP TRIGGER TCNAE_REF_BI0;

DROP TRIGGER TCODIGO_SERVICO_BI0;

DROP TRIGGER TCOMPLEMENTO_HIST_BI0;

DROP TRIGGER TCOMPLEMENTO_HIST_ESP_BI0;

DROP TRIGGER TCOMPONENTES_ETIQUETA_BI0;

DROP TRIGGER TCONF_CONTAS_ONLINE_AU0;

DROP TRIGGER TCONF_CONTAS_ONLINE_BI0;

DROP TRIGGER TCONF_CONTAS_ONLINE_BU0;

DROP TRIGGER TCONF_HISTCONTAS_BI0;

DROP TRIGGER TCONFCONSFORM_BI0;

DROP TRIGGER TCONFIG_RELATORIOS_BI0;

DROP TRIGGER TDETGPSSEFIP_INS;

DROP TRIGGER TDIFERENCA_IMP_BI0;

DROP TRIGGER TDOCARRECADACAO_BI0;

DROP TRIGGER TEMISSAOIMPOSTO_BI0;

DROP TRIGGER TEMP_SPED_FCONT_REF_BI0;

DROP TRIGGER TEMPRESAS_AU0;

DROP TRIGGER TEMPRESAS_BD0;

DROP TRIGGER TEMPRESAS_BU0;

DROP TRIGGER TTERCEIRO_REF_AUD0;

DROP TRIGGER EMPRESAS_TSOC_REF_AUD0;

DROP TRIGGER TEMPRESAS_CTACORRENTE_BI0;

DROP TRIGGER TEMPRESAS_HIST_BI0;

DROP TRIGGER TEMPRESAS_IMG_BI0;

DROP TRIGGER TEMPRESAS_ISENCOES_BI0;

DROP TRIGGER TEMPRESAS_REF_AD0;

DROP TRIGGER TEMPRESAS_REF_AI0;

DROP TRIGGER TEMPRESAS_REF_AI1;

DROP TRIGGER TEMPRESAS_REF_BI0;

DROP PROCEDURE SP_ATUALIZA_APELIDO_IE_EMP;

DROP TRIGGER TEMPRESAS_REN_ISENCOES_BI0;

DROP TRIGGER TEMPRESAS_SCP_BI;

DROP TRIGGER TENQFED_BIO;

DROP TRIGGER TEXPORTACAO_IMPOSTOS_BI0;

DROP TRIGGER TFATCONV_BI0;

DROP TRIGGER TFERIADOSNOVO_BI0;

DROP TRIGGER TFICHA_DIPJ_BI;

DROP TRIGGER TFICHA_ITENS_DIPJ_BI;

DROP TRIGGER TFORMULA_BIO;

DROP TRIGGER THIST_CONTAS_BI0;

DROP TRIGGER TIMPORTACAO_VSUP_BI0;

DROP TRIGGER TIMPOSTO_AI0;

DROP TRIGGER TINDICES_BI0;

DROP TRIGGER TITEM_REPOSITORIO_BI0;

DROP TRIGGER TITEM_REPOSITORIO_BU0;

DROP TRIGGER TITEMCONFIGONLINE_BI0;

DROP TRIGGER TLOG_BI0;

DROP TRIGGER TLOGRADOURO_BI0;

DROP TRIGGER TLOGRADOURO_BU0;

DROP TRIGGER TMENU_SPEED_BI0;

DROP TRIGGER TMODELO_ETIQUETA_BI0;

DROP TRIGGER TMODELO_REL_BI0;

DROP TRIGGER TNCM_BI0;

DROP TRIGGER TNOTAS_BI0;

DROP TRIGGER TOL_PBM_TBLOCOP_AD0;

DROP TRIGGER TOL_UNICO_PAG_DARF_AD0;

DROP TRIGGER TOL_UNICO_PROV_DARF_AD0;

DROP TRIGGER TOL_VSUC_EMPRESAS_TPROCEVOLUCOBRA_AD0;

DROP TRIGGER TOL_VATI_EMPRESAS_IMP_ATIVACONTAB_AD;
DROP TRIGGER TOL_VSUC_EMPRESAS_TTRANSFCUSTOINCOR_AD;
DROP TRIGGER TOL_VSUC_EMPRESAS_VALORPRESENTE_AD;
DROP TRIGGER TOL_EMPRESAS_TBEM_TRANSFERENCIA_AD;
DROP TRIGGER TOL_EMPRESAS_TBEM_TRANSF_CONTA_AD;

DROP TRIGGER TOL_UNICO_APURACAO_LALUR_AD0;

DROP TRIGGER TOL_UPDATE_CONTA_BI0;

DROP TRIGGER TOL_VEF_EMP_TDACONGER_AD0;

DROP TRIGGER TOL_VEF_EMP_TBLOCOMGER_M220_AD0;

DROP TRIGGER TOL_VEF_EMP_TBLOCOMGER_AD0;

DROP TRIGGER TOL_VEF_EMP_TICMSSPEDGER_AD0;

DROP TRIGGER TOL_VEF_EMP_TDIMESCGER_AD0;

DROP TRIGGER TOL_VEF_EMP_TGIAESGER_AD0;

DROP TRIGGER TOL_VEF_EMP_TGIAPRGER_AD0;
DROP TRIGGER TOL_VEF_EMP_TGIARJGER_AD0;
DROP TRIGGER TOL_VEF_EMP_TGIAROGER_AD0;
DROP TRIGGER tol_f200_delete;
DROP TRIGGER tol_f200_pgto_delete;


DROP TRIGGER TOL_VEF_DRCST_TC197SAI_AD0;  
DROP TRIGGER TOL_VEF_EMP_DRCST_TE111_AD0;
DROP TRIGGER TOL_VEF_EMP_TICMSSPEDGER_E1_AD0;

DROP TRIGGER TOL_VEF_EMP_TICMSSPEDE116_AD0;

DROP TRIGGER TOL_VEF_EMP_TGIAMGGER_AD0;

DROP TRIGGER TOL_VEF_EMP_TGIASPGER_AD0;

DROP TRIGGER TOL_VEF_EMP_TIPIGER_AD0;

DROP TRIGGER TOL_VEF_EMP_TCIAPGER_AD0;

DROP TRIGGER TOL_VEF_EMP_TIRLPGER_AD0;

DROP TRIGGER TOL_VEF_EMP_TMOVDEMAISDOC_AD0;

DROP TRIGGER TOL_VEF_EMP_TMOVENT_AD0;

DROP TRIGGER TOL_VEF_EMP_TMOVENTPARPGTO_AD0;

DROP TRIGGER TOL_VEF_EMP_TMOVOREC_AD0;

DROP TRIGGER TOL_VEF_EMP_TMOVRATENT_AD0;

DROP TRIGGER TOL_VEF_EMP_TMOVRATSAI_AD0;

DROP TRIGGER TOL_VEF_EMP_TMOVRATSER_AD0;

DROP TRIGGER TOL_VEF_EMP_TMOVRATOPEIMOBI_AD0;

DROP TRIGGER TOL_VEF_EMP_TMOVRATDEMDOC_AD0;

DROP TRIGGER TOL_VEF_EMP_TMOVRATDEMDOC_BI0;

DROP TRIGGER TOL_VEF_EMP_TMOVRATOPEIMOBPG_AD;

DROP TRIGGER TOL_VEF_EMP_TDIMEGERREGESP_AD0;

DROP TRIGGER TOL_VEF_EMP_TMOVSAI_AD0;

DROP TRIGGER TOL_VEF_EMP_TMOVSAIPARPGTO_AD0;

DROP TRIGGER TOL_VEF_EMP_TMOVF100PARPGTO_AD0;

DROP TRIGGER TOL_VEF_EMP_TMOVSER_AD0;

DROP TRIGGER TOL_VEF_EMP_TMOVSERPARPGTO_AD0;

DROP TRIGGER TOL_VEF_EMP_TREDZVARCFOP_AD0;

DROP TRIGGER TOL_VEF_EMP_TSERAUTOFOLHA_AD0;

DROP TRIGGER TOL_VEF_EMP_TSERINSS_AD0;

DROP TRIGGER TOL_VEF_EMP_TSERINSSCONT_AD0;

DROP TRIGGER TOL_VRHF_EMP_TCALC_13_AD0;

DROP TRIGGER TOL_VRHF_EMP_TCALC_A13_AD0;

DROP TRIGGER TOL_VRHF_EMP_TCALC_AD_AD0;

DROP TRIGGER TOL_VRHF_EMP_TCALC_AUT_AD0;

DROP TRIGGER TOL_VRHF_EMP_TCALC_C13_AD0;

DROP TRIGGER TOL_VRHF_EMP_TCALC_FA_AD0;

DROP TRIGGER TOL_VRHF_EMP_TCALC_FER_AD0;

DROP TRIGGER TOL_VRHF_EMP_TCALC_FN_AD0;

DROP TRIGGER TOL_VRHF_EMP_TCALC_FN_FC_AD0;

DROP TRIGGER TOL_VRHF_EMP_TCALC_FT_AD0;

DROP TRIGGER TOL_VRHF_EMP_TCALC_FT_FC_AD0;

DROP TRIGGER TOL_VRHF_EMP_TCOMPGP_AD0;

DROP TRIGGER TOL_VRHF_EMP_NF_AD0;

DROP TRIGGER TOL_VRHF_TCALC_FN_FC_INT_ad0;

DROP TRIGGER TOL_VRHF_TCALC_FT_FC_INT_ad0;

DROP TRIGGER TOL_VRHF_EMP_TFGTS_FC_INT_ad0;

DROP TRIGGER TOL_VRHF_TFGTS_FT_FC_INT_ad0;

DROP TRIGGER TOL_VRHF_EMP_TVERBA_FCINT_ad0;

DROP TRIGGER TOL_VRHF_TVERBA_FT_FC_INT_ad0;

DROP TRIGGER TOL_VRHF_EMP_TFGTS_13_AD0;

DROP TRIGGER TOL_VRHF_EMP_TFGTS_A13_AD0;

DROP TRIGGER TOL_VRHF_EMP_TFGTS_C13_AD0;

DROP TRIGGER TOL_VRHF_EMP_TFGTS_FA_AD0;

DROP TRIGGER TOL_VRHF_EMP_TFGTS_FC_AD0;

DROP TRIGGER TOL_VRHF_EMP_TFGTS_FN_AD0;

DROP TRIGGER TOL_VRHF_EMP_TFGTS_FT_AD0;

DROP TRIGGER TOL_VRHF_EMP_TFGTS_FT_FC_AD0;

DROP TRIGGER TOL_VRHF_EMP_TPGTO_CALC_AD0;

DROP TRIGGER TOL_VRHF_EMP_TPROV13_AD0;

DROP TRIGGER TOL_VRHF_EMP_TPROV13_DET_AD0;

DROP TRIGGER TOL_VRHF_EMP_TPROVFER_AD0;

DROP TRIGGER TOL_VRHF_EMP_TPROVFER_DET_AD0;

DROP TRIGGER TOL_VRHF_EMP_TVERBA_13_AD0;

DROP TRIGGER TOL_VRHF_EMP_TVERBA_A13_AD0;

DROP TRIGGER TOL_VRHF_EMP_TVERBA_AD_AD0;

DROP TRIGGER TOL_VRHF_EMP_TVERBA_AUT_AD0;

DROP TRIGGER TOL_VRHF_EMP_TVERBA_C13_AD0;

DROP TRIGGER TOL_VRHF_EMP_TVERBA_FA_AD0;

DROP TRIGGER TOL_VRHF_EMP_TVERBA_FER_AD0;

DROP TRIGGER TOL_VRHF_EMP_TVERBA_FN_AD0;

DROP TRIGGER TOL_VRHF_EMP_TVERBA_FN_FC_AD0;

DROP TRIGGER TOL_VRHF_EMP_TVERBA_FT_AD0;

DROP TRIGGER TOL_VRHF_EMP_TVERBA_FT_FC_AD0;

DROP TRIGGER VEF_EMP_TMOVSAIECREDAC_BI0;

DROP TRIGGER TORDEMREL_BI0;

DROP TRIGGER TORGAO_RESP_ESOCIAL_BI0;

DROP TRIGGER TPIS_ESTRUTURA_BI0;

DROP TRIGGER TPIS_ESTRUTURACAMPOS_BI0;

DROP TRIGGER TPIS_MENSAGEMRETORNO_BI0;

DROP TRIGGER TPIS_MENSAGEMRETORNO_BU0;

DROP TRIGGER TPIS_ORGAOEMISSAO_BI0;

DROP TRIGGER TPIS_ORGAOEMISSAO_BU0;

DROP TRIGGER TPLANO_CONF_ONLINE_BI0;

DROP TRIGGER TPLANO_PROGRAMAS_BI0;

DROP TRIGGER TPLANOCONSCONF_BI0;

DROP TRIGGER TPLANOCONSCONF_Q_BI0;

DROP TRIGGER TPROGRAMAS_BI0;

DROP TRIGGER TPROPERTY_ETIQUETA_BI0;

DROP TRIGGER TQUADRO_ITENS_DIME_BI;

DROP TRIGGER TQUALIFICACAO_BI0;

DROP TRIGGER TQUALIFICACAOSOC_BI0;

DROP TRIGGER TR_BF_DELETE_TDARFPADRAO;

DROP TRIGGER TR_BF_I_VRH_BASE_TTERC_TDEP_IMG;

DROP TRIGGER TR_BF_IN_TDARFGERPGTO_BI0;

DROP TRIGGER TR_BF_IN_VEF_EMP_TMOVENTPAR;

DROP TRIGGER TR_BF_IN_VEF_EMP_TMOVENTPARPAG;

DROP TRIGGER TR_BF_IN_VEF_EMP_TMOVENTVARALIQ;

DROP TRIGGER TR_BF_IN_VEF_EMP_TMOVF100PARPGT;

DROP TRIGGER TR_BF_IN_VEF_EMP_TMOVSAIPAR;

DROP TRIGGER TR_BF_IN_VEF_EMP_TMOVSAIPARPAG;

DROP TRIGGER TOL_VEF_EMP_TCONTABAGRUPBAIXAPARC_AD0;

DROP TRIGGER TOL_VEF_EMP_TCONTABAGRUPBAIXAPARC_BI0;

DROP TRIGGER VEF_EMP_TMOVENTPARPGTO_AD0;

DROP TRIGGER VEF_EMP_TMOVSAIPARPGTO_AD0;

DROP TRIGGER VEF_EMP_TMOVSERPARPGTO_AD0;

DROP TRIGGER VEF_EMP_TMOVF100PARPGTO_AD0;

DROP TRIGGER TR_BF_IN_VEF_EMP_TMOVSAIVARALIQ;

DROP TRIGGER TR_BF_IN_VEF_EMP_TMOVSERPAR;

DROP TRIGGER TR_BF_IN_VEF_EMP_TMOVSERPARPAG;

DROP TRIGGER TR_BF_IN_VEF_EMP_TMOVSERVARALIQ;

DROP TRIGGER TR_BF_IN_VRH_BASE_TSERV_PERIODO;

DROP TRIGGER TR_BF_INERT_VRH_EMP_TCAT_TES;

DROP TRIGGER TR_BF_INS_VRH_BASE_TSERVTERC;

DROP TRIGGER VEF_BASE_TTAB_SN_SERVICO_VI_BI;

DROP TRIGGER TR_BF_INS_VRH_BASE_TTERC_TDEP;

DROP TRIGGER TR_BF_INS_VRHF_BASE_TVNTER;

DROP TRIGGER TR_BF_INS_VRHF_BASE_TVSTER;

DROP TRIGGER TR_BF_INS_VRHF_EMP_TPREPFN;

DROP TRIGGER TR_BF_INSERT_CENTROS_TPCC;

DROP TRIGGER TR_BF_INSERT_EMPRESAS_TBAI;

DROP TRIGGER TR_BF_INSERT_EMPRESAS_TBEM;

DROP TRIGGER TR_BF_INSERT_EMPRESAS_TBEM_ITEN;

DROP TRIGGER TR_BF_INSERT_EMPRESAS_TIBE;

DROP TRIGGER TR_BF_INSERT_EMPRESAS_TSOC;

DROP TRIGGER TR_BF_INSERT_HIST_TPHI;

DROP TRIGGER TR_BF_INSERT_MOEDAS_TMOE;

DROP TRIGGER TR_BF_INSERT_PLANOS_TPLA;

DROP trigger VSUC_BASE_TFORMULA_TPFO_BU0;

DROP trigger TR_BF_INSERT_VSUC_BASE_TFORMULA;

DROP TRIGGER vrh_base_tmotesocial_ent_bi0; 

DROP TRIGGER VLAL_CONF_TRIMESTRAL_BI0;

DROP TRIGGER VLAL_EMPRESAS_PREP_CONT_BI0;

DROP TRIGGER VTPO_ATIVIDADE_EXE_BI0;

DROP TRIGGER VTPO_ATIVIDADE_EXE_REGISTRO_BI0;

DROP TRIGGER TVALIDACAOSPED_AGENDAMENTOS_BI;

DROP PROCEDURE CONTAR_CHAR;

--Sol. 16745 - Bruno L. R. - 05/06/2017
DROP PROCEDURE SP_APURADOS_VALTRANS;

--Sol. 16745 - Bruno L. R. - 05/06/2017
DROP PROCEDURE SP_APURADOS_VALREF;

--Sol. 18845 - Bruno L. R. - 09/06/2017
DROP PROCEDURE SP_PERC_GORJETA;

DROP TRIGGER TR_BF_INSERT_TATIVO_EXTERIOR;

DROP TRIGGER TR_BF_INSERT_TATIVO_TAXA;

DROP TRIGGER TR_BF_INSERT_TATVESTADUAL;

DROP TRIGGER TR_BF_INSERT_TATVMUNICIPAL;

DROP TRIGGER TR_BF_INSERT_TBANCOS_AG;

DROP TRIGGER TR_BF_INSERT_TCENTROS;

DROP TRIGGER TR_BF_INSERT_TCIDADE;

DROP TRIGGER TR_BF_INSERT_TCODREC;

DROP TRIGGER VEF_ESTADOS_TCONFDIMEQ_BI0;

DROP TRIGGER TR_BF_INSERT_TTABFUNDOSOCIAL;

DROP TRIGGER TR_BF_INSERT_TTABFUMDES;

DROP TRIGGER TR_BF_INSERT_TTABTRIBNAC;

DROP TRIGGER TR_BF_INSERT_TCONTADOR_PADRAO;

DROP TRIGGER TR_BF_INSERT_TDARFPADRAO;

DROP TRIGGER TR_BF_INSERT_TEMPRESAS;

DROP TRIGGER TR_BF_INSERT_TESCRITORIO;

DROP TRIGGER TR_BF_INSERT_TGRUPOCENTROS;

DROP TRIGGER TR_BF_INSERT_TGRUPOCONTAS;

DROP TRIGGER TR_BF_INSERT_TGRUPOUSUARIO;

DROP TRIGGER TR_BF_INSERT_THIST;

DROP TRIGGER TR_BF_INSERT_TIMPOSTO;

DROP TRIGGER TR_BF_INSERT_TMOEDAS;

DROP TRIGGER TR_BF_INSERT_TNATJUR;

DROP TRIGGER TR_BF_INSERT_TOCUPACAO;

DROP TRIGGER TR_BF_INSERT_TPAIS;

DROP TRIGGER TR_BF_INSERT_TPLANO_PADRAO;

DROP TRIGGER TR_BF_INSERT_TPLANO_PAGAMENTO;

DROP TRIGGER TR_BF_INSERT_TTIPOSERVICO;

DROP TRIGGER TR_BF_INSERT_TUSUARIO;

DROP TRIGGER TUSUARIO_AI0;

DROP TRIGGER TR_BF_INSERT_VEF_BASE_TCFPS;

DROP TRIGGER TR_BF_INSERT_VEF_BASE_TCST;

DROP TRIGGER TR_BF_INSERT_VEF_BASE_TGRAFICA;

DROP TRIGGER TR_BF_INSERT_VEF_BASE_TNATOP;

DROP TRIGGER TR_BF_INSERT_VEF_BASE_TNBM;

DROP TRIGGER TR_BF_INSERT_VEF_BASE_TOBSERVAC;

DROP TRIGGER TR_BF_INSERT_VEF_BASE_TTABCODC;

DROP TRIGGER TR_BF_INSERT_VEF_BASE_TTABCTA;

DROP TRIGGER TR_BF_INSERT_VEF_BASE_TTBDOCFIS;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TC100SAI;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TC500ENT;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TC500SAI;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TD400SAI;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TD500SAI;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TD530SAI;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TMOVENT;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TMOVENTITE;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TMOVENTRET;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TMOVSAI;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TMOVSAIITE;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TMOVSAIRET;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TMOVSER;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TMOVENTDED;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TMOVSAIDED;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TMOVSERDED;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TMOVSERITE;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TMOVSERRET;

DROP TRIGGER TR_BF_INSERT_VEF_EMP_TMSVLTRAN;

DROP TRIGGER TR_BF_INSERT_VEF_INT_TSPEDICMS;

DROP TRIGGER TR_BF_INSERT_VLAL_BASE_TEMP;

DROP TRIGGER TR_BF_INSERT_VLAL_BASE_TRIBUT;

DROP TRIGGER TR_BF_INSERT_VLAL_EMPRESAS_TLLB;

DROP TRIGGER TR_BF_INSERT_VLAL_EMPRESAS_TLLE;

DROP TRIGGER TR_BF_INSERT_VLAL_LALUR_PARTEA;

DROP TRIGGER TR_BF_INSERT_VLAL_PLANOS_TLPA;

DROP TRIGGER TR_BF_INSERT_VLAL_PLANOS_TLPB;

DROP TRIGGER TR_BF_INSERT_VLAL_PLANOS_TLTR;

DROP TRIGGER TR_BF_INSERT_VRH_BASE_TRESPEMP;

DROP TRIGGER TR_BF_INSERT_VRH_EMP_TCAT;

DROP TRIGGER TR_BF_INSERT_VSUC_BASE_TEMP;

DROP TRIGGER TR_BF_INSERT_VSUC_BASE_TFTFPO;

DROP TRIGGER TR_BF_INSERT_VSUC_BASE_TPLANILH;

DROP TRIGGER TR_BF_INSERT_VSUC_EMPRESAS_TCON;

DROP TRIGGER TR_BF_INSERT_VSUC_EMPRESAS_TCTT;

DROP TRIGGER TR_BF_INSERT_VSUC_EMPRESAS_TENC;

DROP TRIGGER TR_BF_INSERT_VSUC_EMPRESAS_TLAN;

DROP TRIGGER VSUC_EMPRESAS_TLAN_BIU1;

DROP TRIGGER TIPOS_LANCAMENTOS_PADRAO_BD0;

DROP TRIGGER VEF_EMP_TMOVSAI_BIU1;

DROP TRIGGER VEF_EMP_TMOVPROENT_ad0;

DROP TRIGGER VEF_EMP_TMOVPROSAI_ad0;

DROP TRIGGER VEF_EMP_TMOVPROSAI_AIUD0;

DROP TRIGGER VEF_EMP_TREDZC425_ad0;

DROP TRIGGER VEF_EMP_TREDZC425ALIQ_ad0;

DROP TRIGGER VEF_EMP_TREDZ60I_ad0;

DROP TRIGGER VEF_EMP_TITEMDOCECF_ad0;

DROP TRIGGER VEF_EMP_TMOVPROSAI_BIU_COMPREFNULL;

DROP TRIGGER VEF_EMP_TMOVPROSAI_BIU1;

DROP TRIGGER VEF_BASE_TPLANOACOESTROCA_BIU0;

DROP TRIGGER VEF_BASE_TTAB6_TIPOSER_BD0;
            
DROP TRIGGER VEF_EMP_TMOVSAIITENS_BIU1;

DROP TRIGGER VEF_EMP_TC190SAI_BIU1;

DROP TRIGGER VEF_EMP_TC197SAI_BIU1;

DROP TRIGGER VEF_BASE_TTABMODELOLAN_BD0;

DROP TRIGGER TUSUARIO_BD0;

DROP TRIGGER TCIDADE_BD0;

DROP TRIGGER VEF_BASE_STATUSLANC_BD0;

DROP TRIGGER VEF_BASE_TTABSITNF_BD0;

DROP TRIGGER TFATCONV_BD0;

DROP TRIGGER VEF_BASE_TTABCSTIPI_BD0;

DROP TRIGGER VEF_BASE_TTABCSTPIS_BD0;

DROP TRIGGER VEF_BASE_TTABCSTCOF_BD0;

DROP TRIGGER VEF_BASE_TTAB_NATREC_BD0;

DROP TRIGGER VEF_BASE_TOBSERVACAO_BD0;

DROP TRIGGER VEF_BASE_TTABCSTICMS_BD0;

DROP TRIGGER VEF_BASE_TNATOP_BD0;

DROP TRIGGER VEF_BASE_TTABCODAJU_BD0;

DROP TRIGGER VEF_BASE_TTABCODITEM1400_BD0;

DROP TRIGGER TR_BF_INSERT_VSUC_EMPRESAS_TTRF;

DROP TRIGGER TR_BF_INSERT_VSUC_PLANILHAS_TLA;

DROP TRIGGER TR_BF_INSERT_VSUC_PLANILHAS_TLC;

DROP TRIGGER TR_BF_INSERTVEF_BASE_TTABCODSER;

DROP TRIGGER TR_BF_ISERT_VEF_BASE_TCONFIPI;

DROP TRIGGER TR_BF_ISERT_VEF_BASE_TCONFIRLP;

DROP TRIGGER TR_BF_ISERT_VEF_BASE_TCONFQIPI;

DROP TRIGGER TR_BF_ISERT_VEF_BASE_TCONFQIRLP;

DROP TRIGGER "TR_BF-INSERT_VLAL_LALUR_PARTEB";

DROP TRIGGER TR_BF_INSERT_TTERCEIRO_REF;

--#alt:15432. Novas triggers que atribuem o valor para o campo BDTIPOTER. Ana - 30/08/2016
DROP TRIGGER TR_BF_UPDATE_TTERCEIRO_REF;

DROP TRIGGER TR_BF_UPDATE_TTERCEIRO;

DROP TRIGGER TR_BF_INSERT_TTERCEIRO;
--#alt:15432. fim

DROP TRIGGER TCIDADE_BU0;

DROP TRIGGER TRELATORIOS_PERSONALIZADOS_BI0;

DROP TRIGGER TREPOSITORIO_BI0;

DROP TRIGGER TSELECOESEMP_BI0;

DROP TRIGGER TSELEMP_BI0;

DROP TRIGGER TSOFTWAREHOUSE_BI0;

DROP TRIGGER TSWS_TFORMREL_BI0;

DROP TRIGGER TSWS_TITEMRELATORIO_BI0;

DROP TRIGGER TSWS_TQUEBRASGERADOR_BI0;

DROP TRIGGER TSWS_TQUEBRASREL_BI0;

DROP TRIGGER TSWS_TRELATORIOS_BI0;

DROP TRIGGER TSWS_TRELATORIOS_EMP_BI0;

DROP TRIGGER TSWS_TTAGPOSSIVEIS_BI0;

DROP TRIGGER TTABELAGERADOR_BI0;

DROP TRIGGER TTABELAGERADOR_BU0;

DROP TRIGGER TTABVENCIMENTOS_BI0;

DROP TRIGGER TTIPO_DECLARANTE_DIRF_BI0;

DROP TRIGGER TTIPOCONTAONLINE_BI0;

DROP TRIGGER TTST_AUTO_BI0;

DROP TRIGGER TTST_AUTO_BLOB_BI0;

DROP TRIGGER TTST_AUTO_ITEM_BI0;

DROP TRIGGER TUF_ALIQEXT_BI0;

DROP TRIGGER TUNIDADEMEDIDA_BI0;

DROP TRIGGER TVARIACAO_RECEITA_BI0;

DROP TRIGGER TVARIAVEIS_COMP_HIST_BI0;

DROP TRIGGER VCT_BASE_DOCUMENTO_BI0;

DROP TRIGGER VCT_BASE_OBRIGACAO_AI0;

DROP TRIGGER VCT_BASE_OBRIGACAO_BI0;

DROP TRIGGER VCT_BASE_SERVICO_AI0;

DROP TRIGGER VCT_BASE_SERVICO_BI0;

--DROP TRIGGER VCT_CONFIG_TELA_BI0;

--DROP TRIGGER VCT_CONFIG_TELAOBRSER_BI0;

DROP TRIGGER VCT_EMPRESA_DOCSGERADOS_BI0;

DROP TRIGGER VCT_EMPRESA_PROTOCOLOSAIDA_AU0;

DROP TRIGGER VCT_EMPRESA_PROTODOCENT_BI0;

DROP TRIGGER VCT_EMPRESA_PROTODOCENTRADA_AU0;

DROP TRIGGER VCT_EMPRESA_PROTODOCSAIDA_AU0;

DROP TRIGGER VCT_EMPRESA_PROTODOCSAIDA_BI0;

DROP TRIGGER VCT_EMPRESA_PROTOENT_BI0;

DROP TRIGGER VCT_EMPRESA_PROTOSAI_BI0;

DROP TRIGGER VCT_EMPRESA_TAREFASWEBOBS_BI0;

DROP TRIGGER VCT_EMPRESA_THISTTAREFA_BI0;

DROP TRIGGER VCT_EMPRESA_TOBSTAREFA_BI0;

DROP TRIGGER VCT_EMPRESA_TSOLICITATAREFA_AI0;

DROP TRIGGER VCT_EMPRESA_TSOLICITATAREFA_BI0;

DROP TRIGGER VCT_ARQUIVOS_TAREFAS_BI0;
DROP TRIGGER VCT_ARQUIVOS_TAREFAS_BU0;

DROP TRIGGER VCT_PLANO_TRIBUTARIO_AI0;

DROP TRIGGER VCT_PLANO_TRIBUTARIO_BI0;

DROP TRIGGER VCT_TRIBUTARIO_EMPRESA_BI0;

DROP TRIGGER vct_tributario_empresa_bu0;

DROP TRIGGER tempresaimposto_bi0;

DROP TRIGGER tempresaimposto_biud0;

DROP TRIGGER VCT_TRIBUTOS_PLANO_TRIB_AI0;

DROP TRIGGER VCT_TRIBUTOS_PLANO_TRIBUT_BI0;

DROP TRIGGER VEF_BASE_TCADIMPOSTOSN_BI0;

DROP TRIGGER VEF_BASE_TCADMAQMRC_BI0;

DROP TRIGGER VEF_BASE_TCADOREC_BI0;

DROP TRIGGER VEF_BASE_TCADTIPODEMDOC_BI0;

DROP TRIGGER VEF_BASE_TCADTIPOIMPOSTO_BI0;

DROP TRIGGER VEF_BASE_TCONF_SN_BI0;

DROP TRIGGER VEF_BASE_TCONF_SN_FORM_BI0;

DROP TRIGGER VEF_BASE_TCONF_SN_Q_BI0;

DROP TRIGGER VEF_BASE_TCONFATIVA_BI0;

DROP TRIGGER VEF_BASE_TCONFATIVAFORM_BI0;

DROP TRIGGER VEF_BASE_TCONFBLOCOP_BI0;

DROP TRIGGER VEF_BASE_TCONFBLOCOPFORM_BI0;

DROP TRIGGER VEF_BASE_TCONFBLOCOPQ_BI0;

DROP TRIGGER VEF_BASE_TCONFBLOCOPQ_BU0;

DROP TRIGGER VEF_BASE_TCONFCIAP_BI0;

DROP TRIGGER VEF_BASE_TCONFCIAPFORM_BI0;

DROP TRIGGER VEF_BASE_TCONFCIAPQ_BI0;

DROP TRIGGER VEF_BASE_TCONFCIAPQ_BU0;

DROP TRIGGER VEF_BASE_TCONFDACON_BI0;

DROP TRIGGER VEF_BASE_TCONFDACONFORM_BI0;

DROP TRIGGER VEF_BASE_TCONFDACONQ_BI0;

DROP TRIGGER VEF_BASE_TCONFDACONQ_BU0;

DROP TRIGGER VEF_BASE_TCONFDAMEF_BI0;

DROP TRIGGER VEF_BASE_TCONFDAMEFFORM_BI0;

DROP TRIGGER VEF_BASE_TCONFDAMEFQ_BI0;

DROP TRIGGER VEF_BASE_TCONFDASN_BI0;

DROP TRIGGER VEF_BASE_TCONFDASNFORM_BI0;

DROP TRIGGER VEF_BASE_TCONFDASNQ_BI0;

DROP TRIGGER VEF_BASE_TCONFICMSSPED_BI0;

DROP TRIGGER VEF_BASE_TCONFICMSSPEDFORM_BI0;

DROP TRIGGER VEF_BASE_TCONFICMSSPEDQ_BI0;

DROP TRIGGER VEF_BASE_TCONFICMSSPEDQ_BU0;

DROP TRIGGER VEF_BASE_TCONFIPIFORM_BI0;

DROP TRIGGER VEF_BASE_TCONFIRLPFORM_BI0;

DROP TRIGGER VEF_BASE_TEMPCADATV_BI0;

DROP TRIGGER VEF_BASE_TEMPITEMSATV_BI0;

DROP TRIGGER VEF_BASE_TEMPPAREST_BIO;

DROP TRIGGER VEF_BASE_TEMPPARESTES_BI0;

DROP TRIGGER VEF_BASE_TEMPPARESTMG_BI0;

DROP TRIGGER VEF_BASE_TEMPPARESTPR_BI0;

DROP TRIGGER VEF_BASE_TEMPPARESTRO_BI0;

DROP TRIGGER VEF_BASE_TEMPPARESTSC_BIO;

DROP TRIGGER VEF_BASE_TEMPPARESTSP_BI0;

DROP TRIGGER VEF_BASE_TEMPPARESTPE_BI0;

DROP TRIGGER VEF_BASE_TEMPPARFED_BIO;

DROP TRIGGER VEF_BASE_TEMPPARFEDPORATV_BI0;

DROP TRIGGER VEF_BASE_TEMPPARGER_BIO;

DROP TRIGGER VEF_BASE_TEMPPARINTEG_BI0;

DROP TRIGGER VEF_BASE_TNATBCPISCOFINS_BI0;

DROP TRIGGER VEF_BASE_TNATOP_BU0;

DROP TRIGGER VEF_BASE_TTAB_NATREC_BI0;

DROP TRIGGER VEF_BASE_TTAB_OR_CRED_DACON_BI0;

DROP TRIGGER VEF_BASE_TTAB_R_SERSN_BI0;

DROP TRIGGER VEF_BASE_TTAB_SN_COMERCIO_BI0;

DROP TRIGGER VEF_BASE_TTAB_SN_INDUSTRIA_BI0;

DROP TRIGGER VEF_BASE_TTAB_SN_SERIII_BI0;

DROP TRIGGER VEF_BASE_TTAB_SN_SERVICO_IV_BI0;

DROP TRIGGER VEF_BASE_TTAB_SN_SERVICO_V_BI0;

DROP TRIGGER VEF_BASE_TTAB_TP_CRED_DACON_BI0;

DROP TRIGGER VEF_BASE_TTABAJUICMS_BI0;

DROP TRIGGER VEF_BASE_TTABAJUICMS_BU0;

DROP TRIGGER VEF_BASE_TTABAJUICMSST_BI0;

DROP TRIGGER VEF_BASE_TTABAJUICMSST_BU0;

DROP TRIGGER VEF_BASE_TTABCODAJU_BI0;

DROP TRIGGER VEF_BASE_TTABCODAJU_BU0;

DROP TRIGGER VEF_BASE_TTABCSTCOF_BI0;

DROP TRIGGER VEF_BASE_TTABCSTICMS_BI0;

DROP TRIGGER VEF_BASE_TTABCSTPIS_BI0;

DROP TRIGGER VEF_BASE_TTABSITNFISS_BI0;

DROP TRIGGER VEF_BASE_TTABTOTPAR_BI0;

DROP TRIGGER VEF_BASE_TTABTPNF_BI0;

DROP TRIGGER VEF_BASE_TTABVAL_R_SERSN_BI0;

DROP TRIGGER VEF_EMP_TA110_BI0;

DROP TRIGGER VEF_EMP_TA120_BI0;

DROP TRIGGER VEF_EMP_TA170_BI0;

DROP TRIGGER VEF_EMP_TAJUICMSE111_BI0;

DROP TRIGGER VEF_EMP_TAJUICMSE112_BI0;

DROP TRIGGER VEF_EMP_TAJUICMSE113_BI0;

DROP TRIGGER VEF_EMP_TAJUICMSE115_BI0;

DROP TRIGGER VEF_EMP_TID_DECLARACAO_SN_IC_BI0;

DROP TRIGGER VEF_EMP_TNUMERODAS_SN_IC_BI0;

DROP TRIGGER VEF_EMP_TAJUICMSE116_BI0;

DROP TRIGGER vef_emp_tajuicmsste316_bi0;

DROP TRIGGER VEF_EMP_TAJUICMSSTE220_BI0;

DROP TRIGGER VEF_EMP_TAJUICMSSTE230_BI0;

DROP TRIGGER VEF_EMP_TAJUICMSSTE240_BI0;

DROP TRIGGER VEF_EMP_TAJUICMSSTE250_BI0;

DROP TRIGGER VEF_EMP_TAJUSTEEFDC_BI0;

DROP TRIGGER VEF_EMP_TAJUSTEEXCLUSAO_BI0;

DROP TRIGGER VEF_EMP_TAJUSTEIPIE530_BI0;

DROP TRIGGER VEF_EMP_TBEM_BI0;

DROP TRIGGER VEF_EMP_TC100ENT_BI0;

DROP TRIGGER VEF_EMP_TC190ENT_BI0;

DROP TRIGGER VEF_EMP_TC190SAI_BI0;

DROP TRIGGER VEF_EMP_TC195ENT_BI0;

DROP TRIGGER VEF_EMP_TC195SAI_BI0;

DROP TRIGGER VEF_EMP_TC197ENT_BI0;

DROP TRIGGER VEF_EMP_TC197SAI_BI0;

DROP TRIGGER VEF_EMP_TC300350ENT_BI0;

DROP TRIGGER VEF_EMP_TC300350SAI_BI0;

DROP TRIGGER VEF_EMP_TC590TOTENT_BI0;

DROP TRIGGER VEF_EMP_TCADBICO_BI0;

DROP TRIGGER VEF_EMP_TCADBOMBA_BI0;

DROP TRIGGER VEF_EMP_TCADTANQUE_BI0;

DROP TRIGGER VEF_EMP_TCAT44_BI0;

DROP TRIGGER VEF_EMP_TCONSUB_BI0;

DROP TRIGGER VEF_EMP_TD100ENT_BI0;

DROP TRIGGER VEF_EMP_TD100SAI_BI0;

DROP TRIGGER VEF_EMP_TD110SAI_BI0;

DROP TRIGGER VEF_EMP_TD120COMPCON_BI0;

DROP TRIGGER VEF_EMP_TD130COMPCON_BI0;

DROP TRIGGER VEF_EMP_TD160CARGATRANS_BI0;

DROP TRIGGER VEF_EMP_TD162DOCFIS_BI0;

DROP TRIGGER VEF_EMP_TD195ENT_BI0;

DROP TRIGGER VEF_EMP_TD195SAI_BI0;

DROP TRIGGER VEF_EMP_TD197ENT_BI0;

DROP TRIGGER VEF_EMP_TD197SAI_BI0;

DROP TRIGGER VEF_EMP_TD500ENT_BI0;

DROP TRIGGER VEF_EMP_TD590TOTENT_BI0;

DROP TRIGGER VEF_EMP_TDIMEGERDEBESP_BI0;

DROP TRIGGER VEF_EMP_TDIMEGERNAT_BI0;

DROP TRIGGER VEF_EMP_TDIMEGERNAT_BU0;

DROP TRIGGER VEF_EMP_TDIMEGERPAGTOIMP_BI0;

DROP TRIGGER VEF_EMP_TDIMEGERQ47_BI0;

DROP TRIGGER VEF_EMP_TDIMEGERQ48_BI0;

DROP TRIGGER VEF_EMP_TDIMEGERQ49_BI0;

DROP TRIGGER VEF_EMP_TDIMEGERQ50_BI0;

DROP TRIGGER VEF_EMP_TDIMEGERREGESP_BI0;

DROP TRIGGER VEF_EMP_TDOCECF_BI0;

DROP TRIGGER VEF_EMP_TENEGAS_BI0;

DROP TRIGGER VEF_EMP_TENETELE_BI0;

DROP TRIGGER VEF_EMP_TF1323A_DACON_BI0;

DROP TRIGGER VEF_EMP_TF500REDZ_BI0;

DROP TRIGGER VEF_EMP_TF500SAI_BI0;

DROP TRIGGER VEF_EMP_TGIAESGERNAT_BI0;

DROP TRIGGER VEF_EMP_TGIAESGERNAT_BU0;

DROP TRIGGER VEF_EMP_TGIAMGGERNAT_BI0;

DROP TRIGGER VEF_EMP_TGIAMGGERNAT_BU0;

DROP TRIGGER VEF_EMP_TGIAPRGERNAT_BI;

DROP TRIGGER VEF_EMP_TGIAPRGERNAT_BU;

DROP TRIGGER VEF_EMP_TGIAROGERNAT_BI0;

DROP TRIGGER VEF_EMP_TGIAROGERNAT_BU0;

DROP TRIGGER VEF_EMP_TGIASPGERNAT_BI0;

DROP TRIGGER VEF_EMP_TGIASPGERNAT_BU0;

DROP TRIGGER VEF_EMP_TITEMDOCECF_BI0;

DROP TRIGGER VEF_EMP_TMOV_OCORR_DCIP_BI0;

DROP TRIGGER VEF_EMP_TMOVCCENT_BI0;

DROP TRIGGER VEF_EMP_TMOVCCREDZ_BI0;

DROP TRIGGER VEF_EMP_TMOVCCSAI_BI0;

DROP TRIGGER VEF_EMP_TMOVCCSER_BI0;

DROP TRIGGER VEF_EMP_TMOVCOMB_BI0;

DROP TRIGGER VEF_EMP_TMOVCOMBVENDAS_BI0;

DROP TRIGGER VEF_EMP_TMOVDEMAISDOC_F100_BI0;

DROP TRIGGER VEF_EMP_TMOVDEMAISDOC_F100_BU0;

DROP TRIGGER VEF_EMP_TMOVDEMRET_BI0;

DROP TRIGGER VEF_EMP_TMOVENT_BU0;

DROP TRIGGER VEF_EMP_TMOVENT_IVA_BI0;

DROP TRIGGER VEF_EMP_TMOVENTANTIMP_BI0;

DROP TRIGGER VEF_EMP_TMOVENTCUPREF_BI0;

DROP TRIGGER VEF_EMP_TMOVENTDCIP_BI0;

DROP TRIGGER VEF_EMP_TMOVENTDIFALIQ_BI0;

DROP TRIGGER VEF_EMP_TMOVENTDOCAREF_BI0;

DROP TRIGGER VEF_EMP_TMOVENTDOCFREF_BI0;

DROP TRIGGER VEF_EMP_TMOVENTFUNRURAL_BI0;

DROP TRIGGER VEF_EMP_TMOVENTGRF_BI0;

DROP TRIGGER VEF_EMP_TMOVENTIMPRETSP_BI0;

DROP TRIGGER VEF_EMP_TMOVENTINFCOM_BI0;

DROP TRIGGER VEF_EMP_TMOVENTITENS_BU0;

DROP TRIGGER VEF_EMP_TMOVENTMVA_BI0;

DROP TRIGGER VEF_EMP_TMOVENTOCOSP_BI0;

DROP TRIGGER VEF_EMP_TMOVENTOPIMP_BI0;

DROP TRIGGER VEF_EMP_TMOVENTPMPF_BI0;

DROP TRIGGER VEF_EMP_TMOVENTPROREF_BI0;

DROP TRIGGER VEF_EMP_TMOVENTSN_BI0;

DROP TRIGGER VEF_EMP_TMOVENTSTDAPI_BI0;

DROP TRIGGER VEF_EMP_TMOVENTSVA_BI0;

DROP TRIGGER VEF_EMP_TMOVENTTELCONV_BI0;

DROP TRIGGER VEF_EMP_TMOVENTVINCBEM_BI0;

DROP TRIGGER VEF_EMP_TMOVEXPINDIRETA_BI0;

DROP TRIGGER VEF_EMP_TMOVF111_BI0;

DROP TRIGGER VEF_EMP_TMOVINV_BI0;

DROP TRIGGER VEF_EMP_TMOVOCO_GIASP_BI0;

DROP TRIGGER VEF_EMP_TMOVOPECARTAO_BI0;

--Gilberto - 21/10/2024 - dá erro, trigger não existe
--DROP TRIGGER VEF_EMP_TMOVOREC_BI0;

DROP TRIGGER VEF_EMP_TMOVOUTCREDCIAP_BI0;

DROP TRIGGER VEF_EMP_TMOVPROENT_BI0;

DROP TRIGGER VEF_EMP_TMOVPROENTGRF_BI0;

DROP TRIGGER VEF_EMP_TMOVPROSAI_BI0;

DROP TRIGGER VEF_EMP_TMOVPROSAIC177_BI0;

DROP TRIGGER VEF_EMP_TMOVPROSAIC178_BI0;

DROP TRIGGER VEF_EMP_TMOVPROSAIGRF_BI0;

DROP TRIGGER VEF_EMP_TMOVRATENT_BI0;

DROP TRIGGER VEF_EMP_TMOVRATSAI_BI0;

DROP TRIGGER VEF_EMP_TMOVRATSER_BI0;

DROP TRIGGER VEF_EMP_TMOVSAI_BU0;

DROP TRIGGER VEF_EMP_TMOVSAI_INF_NF_SP_BI0;

DROP TRIGGER VEF_EMP_TMOVSAICARTR_BI0;

DROP TRIGGER VEF_EMP_TMOVSAICTR_BI0;

DROP TRIGGER VEF_EMP_TMOVSAICUPREF_BI0;

DROP TRIGGER VEF_EMP_TMOVSAIDOCAREF_BI0;

DROP TRIGGER VEF_EMP_TMOVSAIDOCFREF_BI0;

DROP TRIGGER VEF_EMP_TMOVSAIEXP_BI0;

DROP TRIGGER VEF_EMP_TMOVSAIEXPSP_BI0;

DROP TRIGGER VEF_EMP_TMOVSAIGRF_BI0;

DROP TRIGGER VEF_EMP_TMOVSAIIMPRETSP_BI0;

DROP TRIGGER VEF_EMP_TMOVSAIINFCOM_BI0;

DROP TRIGGER VEF_EMP_TMOVSAIITENS_BU0;

DROP TRIGGER VEF_EMP_TMOVSAIITENSCTR_BI0;

DROP TRIGGER VEF_EMP_TMOVSAILOCCOL_BI0;

DROP TRIGGER VEF_EMP_TMOVSAIOCOSP_BI0;

DROP TRIGGER VEF_EMP_TMOVSAIPROREF_BI0;

DROP TRIGGER VEF_EMP_TMOVSAISN_BI0;

DROP TRIGGER VEF_EMP_TMOVSAISTDAPI_BI0;

DROP TRIGGER VEF_EMP_TMOVSAISVA_BI0;

DROP TRIGGER VEF_EMP_TMOVSAITELCONV_BI0;

DROP TRIGGER VEF_EMP_TMOVSAIVINCBEM_BI0;

DROP TRIGGER VEF_EMP_TMOVSER_AJISSFLO_BI0;

DROP TRIGGER VEF_EMP_TMOVSER_BU0;

DROP TRIGGER VEF_EMP_TMOVSERBHISS_BI0;

DROP TRIGGER VEF_EMP_TMOVSERDEDISS_BI0;

DROP TRIGGER VEF_EMP_TMOVSERDEISS_BI0;

DROP TRIGGER VEF_EMP_TMOVSERDMED_BI0;

DROP TRIGGER VEF_EMP_TMOVSERGISSONLINE_BI0;

DROP TRIGGER VEF_EMP_TMOVSERINDISS_BI0;

DROP TRIGGER VEF_EMP_TMOVSERIPM_BI0;

DROP TRIGGER VEF_EMP_TMOVSERISS_BI0;

DROP TRIGGER VEF_EMP_TMOVSERITENS_BU0;

DROP TRIGGER VEF_EMP_TMOVSERMATBETHA_BI0;

DROP TRIGGER VEF_EMP_TMOVSERPERDCOMP_BI0;

DROP TRIGGER VEF_EMP_TMOVSERSN_BI0;

DROP TRIGGER VEF_EMP_TMOVTALONSAI_BI0;

DROP TRIGGER VEF_EMP_TMOVTALONSER_BI0;

DROP TRIGGER VEF_EMP_TNUMFUNC_BI0;

DROP TRIGGER VEF_EMP_TOCODEBCREMG_BI0;

DROP TRIGGER VEF_EMP_TOCOGIAES_BI0;

DROP TRIGGER VEF_EMP_TOCOGIARO_BI0;

DROP TRIGGER VEF_EMP_TOCOMG_BI0;

DROP TRIGGER VEF_EMP_TOCOMG070_BI0;

DROP TRIGGER VEF_EMP_TOCOMG090_BI0;

DROP TRIGGER VEF_EMP_TOCOMG095_BI0;

DROP TRIGGER VEF_EMP_TOPMEDENT_BI0;

DROP TRIGGER VEF_EMP_TOPMEDSAI_BI0;

DROP TRIGGER VEF_EMP_TREDZ_BI0;

DROP TRIGGER VEF_EMP_TREDZ_BU0;

DROP TRIGGER VEF_EMP_TREDZC425_BI0;

DROP TRIGGER VEF_EMP_TREDZC425ALIQ_BI0;

DROP TRIGGER VEF_EMP_TREDZC490_BI0;

DROP TRIGGER VEF_EMP_TREDZDADOSSPED_BI0;

DROP TRIGGER VEF_EMP_TREDZSN_BI0;

DROP TRIGGER VEF_EMP_TREDZVARALIQ_BI0;

DROP TRIGGER VEF_EMP_TREDZVARCFOP_BI0;

DROP TRIGGER VEF_EMP_TSALDOSN_BI0;

DROP TRIGGER VEF_EMP_TSIMPLESNACIONAL_BI0;

DROP TRIGGER VEF_ESTADOS_TCONFDIMEFORM_BI0;

DROP TRIGGER VEF_ESTADOS_TCONFDIMEFQ12_BI0;

DROP TRIGGER VEF_ESTADOS_TCONFDIMEFQ46_BI0;

DROP TRIGGER VEF_ESTADOS_TCONFDIMEQ_BU0;

DROP TRIGGER VEF_ESTADOS_TCONFGIAESFORM_BI0;

DROP TRIGGER VEF_ESTADOS_TCONFGIAMGFORM_BI0;

DROP TRIGGER VEF_ESTADOS_TCONFGIAMGIX_BI0;

DROP TRIGGER VEF_ESTADOS_TCONFGIAMGQ_BU0;

DROP TRIGGER VEF_ESTADOS_TCONFGIASPFORM_BI0;

DROP TRIGGER VEF_INT_TDACON_BI0;

DROP TRIGGER VEF_INT_TDESTDA_BI0;

DROP TRIGGER VEF_INT_TDCTF_BI0;

DROP TRIGGER VEF_INT_TRETENCAO_BI0;

DROP TRIGGER VEF_INT_TDIFALIQ_BI0;

DROP TRIGGER VEF_INT_TSPED_PIS_COFINS_BI0;

DROP TRIGGER VEF_TABELAS_TREDICMSFXSSN_BI0;

DROP TRIGGER VEF_TABELAS_TREDICMSSN_BI0;

DROP TRIGGER VEF_TABELAS_TREDISSFXSN_BI0;

DROP TRIGGER VEF_TABELAS_TREDISSSN_BI0;

DROP TRIGGER VEF_TIPOOCO_GIA_BI0;

DROP TRIGGER VEFLISTAOCO_GIASP_BI0;

DROP TRIGGER VINT_EMP_PROCESSOTROCA_BI0;

DROP TRIGGER VLAL_BASE_TCONF_CONT_LAU_BI0;

DROP TRIGGER VLAL_EMPRESAS_APURACAO_BI0;

DROP TRIGGER VLAL_EMPRESAS_IMP_CONTABLAL_BI0;

DROP TRIGGER VLAL_EMPRESAS_TLLA_ANUAL_BI0;

DROP TRIGGER VRH_BASE_BAIXA_CALC_AUTO_BI0;

DROP TRIGGER VRH_BASE_CBO_TSIN_BI0;

DROP TRIGGER VRH_BASE_CBO_TSIN_SCI_BI0;

DROP TRIGGER VRH_BASE_CONVENIO_OPER_BI0;

DROP TRIGGER VRH_BASE_CONVENIO_OPER_BU0;

DROP TRIGGER VRH_BASE_FAIXAS_CONVENIOS_BI0;

DROP TRIGGER VRH_BASE_ITEMS_MEDIASSIND_BI0;

DROP TRIGGER VRH_BASE_ITEMS_MEDIASSIND_BU0;

DROP TRIGGER VRH_BASE_MTE_TCONFRESC_BI0;

DROP TRIGGER VRH_BASE_MTE_TVERBASCONF_BI0;

DROP TRIGGER VRH_BASE_PLANO_MEDIAS_SIND_BI0;

DROP TRIGGER VRH_BASE_TAGENTE_ESTAGIO_BI0;

DROP TRIGGER VRH_BASE_TCALCITENS_BI0;

DROP TRIGGER VRH_BASE_TCALCVESP_BI0;

DROP TRIGGER VRH_BASE_TCBO_BI0;

DROP TRIGGER VRH_BASE_TCBO_SCI_BI0;

DROP TRIGGER VRH_BASE_TCLASSE_BI0;

DROP TRIGGER VRH_BASE_TCONF_FICHA_HE_BI0;

DROP TRIGGER VRH_BASE_TCONF_FICHA_HE_BU0;

DROP TRIGGER VRH_BASE_TCONF_FICHA_HN_BI0;

DROP TRIGGER VRH_BASE_TCONF_FICHA_HN_BU0;

DROP TRIGGER VRH_BASE_TCONF_FICHA_RV_BI0;

DROP TRIGGER VRH_BASE_TCONF_FICHA_RV_BU0;

DROP TRIGGER VRH_BASE_TCONF_FICHA_OUT_BI0;

DROP TRIGGER VRH_BASE_TCONF_FICHA_OUT_BU0;

DROP TRIGGER VRH_BASE_TCONVSAUDE_BI0;

DROP TRIGGER VRH_BASE_TDOENCAS_BI0;

DROP TRIGGER VRH_BASE_TEMPVINC_BIO;

DROP TRIGGER VRH_BASE_TFPAS_BI0;

DROP TRIGGER VRH_BASE_TFPAS_TERCEIROS_BI0;

DROP TRIGGER VRH_BASE_TFUNCOES_BI0;

DROP TRIGGER VRH_BASE_THOMOLOGANET_BI0;

DROP TRIGGER VRH_BASE_TINST_ESTAGIO_BI0;

DROP TRIGGER VRH_BASE_TIPO_MEDIASSIND_BI0;

DROP TRIGGER VRH_BASE_TMEDICOS_BI0;

DROP TRIGGER VRH_BASE_TMENSAGENS_BI0;

DROP TRIGGER VRH_BASE_TMOTAUMSAL_BI0;

DROP TRIGGER VRH_BASE_TMOTCAGED_BI0;

DROP TRIGGER VRH_BASE_TMOTESOCIAL_RESC_BI0;

DROP TRIGGER VRH_BASE_TMOTESOCIAL_SIT_BI0;

DROP TRIGGER VRH_BASE_TMOTFGTS_BI0;

DROP TRIGGER VRH_BASE_TMOTRAIS_BI0;

DROP TRIGGER VRH_BASE_TMOTRAIS_SIT_BI0;

DROP TRIGGER VRH_BASE_TMS_CLASS_BI0;

DROP TRIGGER VRH_BASE_TNATUREZA_VERBAS_BI0;

DROP TRIGGER VRH_BASE_TNOMESELTERC_BI0;

DROP TRIGGER VRH_BASE_TPLACONFVERPTITEM_BI0;

DROP TRIGGER VRH_BASE_TPLANO_CONVSAUDE_BI0;

DROP TRIGGER VRH_BASE_TPLANO_LPL_BI0;

DROP TRIGGER VRH_BASE_TPLANO_QUADRO_BI0;

DROP TRIGGER VRH_BASE_TPLANOBLUESOFT_BI0;

DROP TRIGGER VRH_BASE_TPREPRESC_BI0;

DROP TRIGGER VRH_BASE_TPREPRESC_BU0;

DROP TRIGGER VRH_BASE_TPREPSIT_BI0;

DROP TRIGGER VRH_BASE_TQH_BI0;

DROP TRIGGER VRH_BASE_TQH_DIAS_BI0;

DROP TRIGGER VRH_BASE_TQH_DIAS_BU0;

DROP TRIGGER VRH_BASE_TQH_HORARIO_BI0;

DROP TRIGGER VRH_BASE_TQH_HORAS_BI0;

DROP TRIGGER VRH_BASE_TROCUPACIONAL_BI0;

DROP TRIGGER VRH_BASE_TRUBRICAS_BI0;

DROP TRIGGER VRH_BASE_TRUBRICAS_VERBA_BI0;

DROP TRIGGER VRH_BASE_TSALHORESP_BI0;

DROP TRIGGER VRH_BASE_TSELCOL_BI0;

DROP TRIGGER VRH_BASE_TSELECOESCOL_BI0;

DROP TRIGGER VRH_BASE_TSELTERC_BI0;

DROP TRIGGER VRH_BASE_TSERVTERC_BU0;

DROP TRIGGER VRH_BASE_TSERVTERC_AD0;

DROP TRIGGER VRH_BASE_TSIND_AVPREV_BI0;

DROP TRIGGER VRH_BASE_TSIND_FERIAS_BI0;

DROP TRIGGER VRH_BASE_TSINDTRAB_AI0;

DROP TRIGGER VRH_BASE_TSINDTRAB_BI0;

DROP TRIGGER VRH_BASE_TSINDTRAB_DOC_BI0;

DROP TRIGGER VRH_BASE_TSINDTRAB_INDICES_BI0;

DROP TRIGGER VRH_BASE_TSINDTREF_BI0;

DROP TRIGGER VRH_BASE_TTABSD_FAIXAS_BI0;

DROP TRIGGER VRH_BASE_TTABSD_FORMULA_BI0;

DROP TRIGGER VRH_BASE_TTABSD_PARCELA_BI0;

DROP TRIGGER VRH_BASE_TTERC_DOC_AI0;

DROP TRIGGER VRH_BASE_TTERCEIROS_BI0;

DROP TRIGGER VRH_BASE_TTIPOCALCAVUL_AI0;

DROP TRIGGER VRH_BASE_TTIPOCALCAVUL_BI0;

DROP TRIGGER VRH_BASE_TVERBAS_AI0;

--DROP TRIGGER VRH_BASE_TVERBAS_AU0;

DROP TRIGGER VRH_BASE_TVERBAS_BI0;

DROP TRIGGER VRH_BASE_TVERBAS_PADRAO_BI0;

DROP TRIGGER VRH_BASE_TVERBAS_PADRAO_BU0;

DROP TRIGGER VRH_BASE_TVERBAS_REF_BI0;

DROP TRIGGER VRH_BASE_TVERBASBLUESOFT_BI0;

DROP TRIGGER VRH_BASE_TVERBASBLUESOFT_BU0;

DROP TRIGGER VRH_BASE_TVERBASEMP_PADRAO_BI0;

DROP TRIGGER VRH_BASE_TVERBASEMP_PADRAO_BU0;

DROP TRIGGER VRH_EMP_CONTAB_GPS_BI0;

DROP TRIGGER VRH_EMP_HRCOMP_BI0;

DROP TRIGGER VRH_EMP_HRDED_BI0;

DROP TRIGGER VRH_EMP_HRNF_BI0;

DROP TRIGGER VRH_EMP_RCOMP_BI0;

DROP TRIGGER VRH_EMP_RNF_BI0;

DROP TRIGGER VRH_EMP_TACERTOCAGED_BI0;

DROP TRIGGER VRH_EMP_TBENEFINCAPACIDADE_BI0;

DROP TRIGGER VRH_EMP_TCAT_AGCAUSADOR_BI0;

DROP TRIGGER VRH_EMP_TCAT_ATESTADO_BI0;

DROP TRIGGER VRH_EMP_TCAT_BU0;

DROP TRIGGER VRH_EMP_TCAT_PATINGIDAS_BI0;

DROP TRIGGER VRH_EMP_TCOL_ADM_BI0;

DROP TRIGGER VRH_EMP_TCOL_ASO_BI0;

DROP TRIGGER VRH_EMP_TCOL_ASO_EXAME_BI0;

DROP TRIGGER VRH_EMP_TCOL_ASO_MONITBIO_BI0;

DROP TRIGGER VRH_EMP_TCOL_DOC_BI0;

DROP TRIGGER VRH_EMP_TCOL_FIS_BI0;

DROP TRIGGER VRH_EMP_TCOL_HIST_BI0;

DROP TRIGGER vrh_emp_tcol_hist_au0;

DROP TRIGGER VRH_EMP_TCOLCON_CAD_AU0;

DROP TRIGGER VRH_EMP_TCOL_PARENT_BI0;

DROP TRIGGER VRH_EMP_TCOL_VINC_BI0;

DROP TRIGGER VRH_EMP_TCOL_VINC_BU0;

DROP TRIGGER VRH_EMP_TCOL_VINCDIA_BI0;

DROP TRIGGER VRH_EMP_TCOLCON_AI0;

DROP TRIGGER VRH_EMP_TCOLCON_BD0;

DROP TRIGGER VRH_EMP_TCOLCON_BENEF_BI0;

DROP TRIGGER VRH_EMP_TCOLCON_BI0;

DROP TRIGGER VRH_EMP_TCOLCON_BU0;

DROP TRIGGER VRH_EMP_TCOLCON_CALCDIA_BI0;

DROP TRIGGER VRH_EMP_TCOLCON_DIA_BI0;

DROP TRIGGER VRH_EMP_TCOLCON_DOC_BI0;

DROP TRIGGER VRH_EMP_TCOLCON_ESTAGIO_BI0;

DROP TRIGGER VRH_EMP_TCOLCON_IMG_BI0;

DROP TRIGGER VRH_EMP_TCOLCON_PARTIDA_BI0;

DROP TRIGGER VRH_EMP_TCOLCON_PARTIDA_BU0;

DROP TRIGGER VRH_EMP_TCOLCON_REF_BI0;

DROP TRIGGER VRH_EMP_TCOLCON_VINC_BI0;

DROP TRIGGER VRH_EMP_TCON_DOC_BI0;

DROP TRIGGER VRH_EMP_TCON_DOC_BU0;

DROP TRIGGER VRH_EMP_TCONDDIFTRAB_BI0;

DROP TRIGGER VRH_EMP_TDEP_BI0;

DROP TRIGGER VRH_EMP_TDEP_BU0;

DROP TRIGGER VRH_EMP_TDEP_IMG_BI0;

DROP TRIGGER VRH_EMP_TDEP_IMG_BU0;

DROP TRIGGER VRH_EMP_TESTABILIDADE_BI0;

DROP TRIGGER VRH_EMP_TFERIAS_AD0;

DROP TRIGGER VRH_EMP_TFERIAS_AI0;

DROP TRIGGER VRH_EMP_TFERIAS_BI0;

DROP TRIGGER VRH_EMP_TFERIAS_BU0;

DROP TRIGGER VRH_EMP_TFERIAS_COLETIVAS_AD0;

DROP TRIGGER VRH_EMP_THIST_AUM_AD0;

DROP TRIGGER VRH_EMP_THIST_AUM_BI0;

DROP TRIGGER VRH_EMP_THIST_AUMHE_AD0;

DROP TRIGGER VRH_EMP_THIST_AUMHE_BI0;

DROP TRIGGER VRH_EMP_TCOL_SHE_BI0;

DROP TRIGGER vrh_emp_tcolcon_calcdia_bu0;

DROP TRIGGER VRH_EMP_TCOL_SHE_BU0;

DROP TRIGGER VRH_EMP_TLANFATRISCO_BI0;

DROP TRIGGER VRH_EMP_TLANFATRISCO_EPI_BI0;

DROP TRIGGER VRH_EMP_TLANMENSAGENS_BI0;

DROP TRIGGER VRH_EMP_TMANDCIPA_BI0;

DROP TRIGGER VRH_EMP_TNOTIFICACOES_AD0;

DROP TRIGGER VRH_EMP_TNOTIFICACOES_BI0;

DROP TRIGGER VRH_EMP_TNOTIFICACOES_BU0;

DROP TRIGGER VRH_EMP_TNOTIFICACOES_TE_BI0;

DROP TRIGGER VRH_EMP_TPARCELAMENTOS_BI0;

DROP TRIGGER VRH_EMP_TPBM_REC_BI0;

DROP TRIGGER VRH_EMP_TPROCESSO_DIRF_BI0;

DROP TRIGGER VRH_EMP_TPROCESSO_DIRF_ITEM_BI0;

DROP TRIGGER VRH_EMP_TPROCESSOS_AU0;

DROP TRIGGER VRH_EMP_TPROCESSOS_BI0;

DROP TRIGGER VRH_EMP_TRDE_BI0;

DROP TRIGGER VRH_EMP_TRDE_SECAO_2_BI0;

DROP TRIGGER VRH_EMP_TRDE_SECAO_3_BI0;

DROP TRIGGER VRH_EMP_TRDE_SECAO_31_DE_BI0;

DROP TRIGGER VRH_EMP_TRDE_SECAO_31_PARA_BI0;

DROP TRIGGER VRH_EMP_TRDE_SECAO_4_BI0;

DROP TRIGGER VRH_EMP_TRDE_SECAO_5_BI0;

DROP TRIGGER VRH_EMP_TRDT_BI0;

DROP TRIGGER VRH_EMP_TRDT_SECAO_3_BI0;

DROP TRIGGER VRH_EMP_TRDT_SECAO_4_BI0;

DROP TRIGGER VRH_EMP_TRDT_SECAO_5_BI0;

DROP TRIGGER VRH_EMP_TRDT_SECAO_6_BI0;

DROP TRIGGER VRH_EMP_TRDT_SECAO_7_BI0;

DROP TRIGGER VRH_EMP_TREEMBOLSO_BI0;

DROP TRIGGER VRH_EMP_TRESCISAO_BI0;

DROP TRIGGER VRH_EMP_TRESCISAO_BU0;

DROP TRIGGER VRH_EMP_TRESCISAO_PREVIA_BI0;

DROP TRIGGER VRH_EMP_TRESCISAO_PREVIA_BU0;

DROP TRIGGER VRH_EMP_TTRANSCOL_AD0;

DROP TRIGGER VRH_FUNCOES_TFUC_BI0;

DROP TRIGGER VRH_LISTACOL_IMPOSTO_BI0;

DROP TRIGGER VRH_RHNET_TARQUIVO_BI0;

DROP TRIGGER VRH_RHNET_TREGISTRO_BI0;

DROP TRIGGER VRH_SN_CONF_RH_BI0;

DROP TRIGGER VRHF_BASE_CALC_TERC_AD0;

DROP TRIGGER VRHF_BASE_CALC_TERC_AI0;

DROP TRIGGER VRHF_BASE_CALC_TERC_BI0;

DROP TRIGGER VRHF_BASE_CALC_TERC_BU0;

DROP TRIGGER VRHF_BASE_TCOLCON_ESMOV_BI0;

DROP TRIGGER VRHF_BASE_TCOLCON_EXPSEFIP_BI0;

DROP TRIGGER VRHF_BASE_TCONVREFEICAO_REF_BI0;

DROP TRIGGER VRHF_BASE_TEMP_EXPSEFIP_BI0;

DROP TRIGGER VRHF_BASE_TEMPCALC_BI0;

DROP TRIGGER VRHF_BASE_TEMPDIRF_BI0;

DROP TRIGGER VRHF_BASE_TEMPESOCIAL_BI0;

DROP TRIGGER VRHF_BASE_TEMPGPS_BI0;

DROP TRIGGER VRHF_BASE_TEMPGRCS_BI0;

DROP TRIGGER VRHF_BASE_TEMPPAR_BI0;

DROP TRIGGER VRHF_BASE_TEMPPROP_BI0;

DROP TRIGGER VRHF_BASE_TEMPRAIS_BI0;

DROP TRIGGER VRHF_BASE_TEMPSEFIP_BI0;

DROP TRIGGER VRHF_BASE_TEMPVINC_BI0;

DROP TRIGGER VRHF_BASE_TFERISIND_BI0;

DROP TRIGGER VRHF_BASE_TFERISIND_BU0;

DROP TRIGGER VRHF_BASE_TITINERARIO_REF_BI0;

DROP TRIGGER VRHF_BASE_TITINERARIOS_BI0;

DROP TRIGGER VRHF_BASE_TSINDPATRONAL_BI0;

DROP TRIGGER VRHF_BASE_TVERBASEMP_BI0;

DROP TRIGGER VRHF_BASE_TVERBASEMP_BU0;

DROP TRIGGER VRHF_EMP_DARF_PIS_IND_BI0;

DROP TRIGGER VRHF_EMP_DARF_TNFCONT_BI0;

DROP TRIGGER VRHF_EMP_GPS_IND_BI0;

DROP TRIGGER VRHF_EMP_T13SAL_AD0;

DROP TRIGGER VRHF_EMP_T13SAL_AI0;

DROP TRIGGER VRHF_EMP_T13SAL_AU0;

DROP TRIGGER VRHF_EMP_T13SAL_BI0;

DROP TRIGGER VRHF_EMP_TA13SAL_AD0;

DROP TRIGGER VRHF_EMP_TA13SAL_AU0;

DROP TRIGGER VRHF_EMP_TA13SAL_BI0;

DROP TRIGGER VRHF_EMP_TADSAL_AD0;

DROP TRIGGER VRHF_EMP_TADSAL_AI0;

DROP TRIGGER VRHF_EMP_TADSAL_BI0;

DROP TRIGGER VRHF_EMP_TC13SAL_AD0;

DROP TRIGGER VRHF_EMP_TC13SAL_AI0;

DROP TRIGGER VRHF_EMP_TC13SAL_AU0;

DROP TRIGGER VRHF_EMP_TC13SAL_BI0;

DROP TRIGGER VRHF_EMP_TCOL_ANO_BI0;

DROP TRIGGER VRHF_EMP_TCOL_CALC_BI0;

DROP TRIGGER VRHF_EMP_TCOL_HIST_BI0;

DROP TRIGGER VRHF_EMP_TCOLCON_BANCO_BI0;

DROP TRIGGER VRHF_EMP_TCOLCON_CALC_BI0;

DROP TRIGGER VRHF_EMP_TCOLCON_FGTSGPS_BI0;

DROP TRIGGER VRHF_EMP_TCOMPGPS_BI0;

DROP TRIGGER VRHF_EMP_TCON_VINC_BI0;

DROP TRIGGER VRHF_EMP_TDADOSCALC_BAIXA_BI0;

DROP TRIGGER VRHF_EMP_TDADOSCALC_BAIXA_BD0;

DROP TRIGGER VRHF_EMP_TFICHAIRRF_AD0;

DROP TRIGGER VRHF_EMP_TFICHAIRRF_BI0;

DROP TRIGGER VRHF_EMP_TFICHAIRRF_BU0;

DROP TRIGGER VRHF_EMP_TFOLHAAVULSA_AD0;

DROP TRIGGER VRHF_EMP_TFOLHAAVULSA_BI0;

DROP TRIGGER VRHF_EMP_TFOLHAAVULSA_BU0;

DROP TRIGGER VRHF_EMP_TFOLHACOMP_AD0;

DROP TRIGGER VRHF_EMP_TFOLHACOMP_AI0;

DROP TRIGGER VRHF_EMP_TFOLHACOMP_AU0;

DROP TRIGGER VRHF_EMP_TFOLHACOMP_BI0;

DROP TRIGGER VRHF_EMP_TFOLHANORMAL_AD0;

DROP TRIGGER VRHF_EMP_TFOLHANORMAL_BI0;

DROP TRIGGER VRHF_EMP_TFOLHATOMADOR_AD0;

DROP TRIGGER VRHF_EMP_TFOLHATOMADOR_BI0;

DROP TRIGGER VRHF_EMP_TFOLTOMCOMP_AD0;

DROP TRIGGER VRHF_EMP_TFOLTOMCOMP_AI0;

DROP TRIGGER VRHF_EMP_TFOLTOMCOMP_AU0;

DROP TRIGGER VRHF_EMP_TFOLTOMCOMP_BU0;

DROP TRIGGER VRHF_EMP_THIST_FOLHACOMP_BI0;

DROP TRIGGER VRHF_EMP_THIST_FOLHACOMP_BU0;

DROP TRIGGER VRHF_EMP_THISTCOMP_BI0;

DROP TRIGGER VRHF_EMP_THISTNF_BI0;

DROP TRIGGER VRHF_EMP_THISTORICOGPS_INS;

DROP TRIGGER VRHF_EMP_TNFCONT_BI0;

DROP TRIGGER VRHF_EMP_TNFCONT_BU0;

DROP TRIGGER VRHF_EMP_TNFCOOP_BI0;

DROP TRIGGER VRHF_EMP_TNFPRODRURAL_BI0;

DROP TRIGGER VRHF_EMP_TNFPRODRURAL_BU0;

DROP TRIGGER VRHF_EMP_TNFPRODRURAL_AD0;

DROP TRIGGER VRHF_EMP_TNOTASFISCAIS_BI0;

DROP TRIGGER VRHF_EMP_TPLANLANC_ADSAL_BI0;

DROP TRIGGER VRHF_EMP_TPLANLANC_ADSAL_BU0;

DROP TRIGGER VRHF_EMP_TPLANLANC_BI0;

DROP TRIGGER VRHF_EMP_TPLANLANC_BU0;

DROP TRIGGER VRHF_EMP_TPLANLANC_FA_BI0;

DROP TRIGGER VRHF_EMP_TPLANLANC_FA_BU0;

DROP TRIGGER VRHF_EMP_TRATEIO_VERBAS_BI0;

DROP TRIGGER VRHF_EMP_TVERBAFC_BI0;

DROP TRIGGER VRHF_EMP_TVERBAFC_BU0;

DROP TRIGGER VRHF_EMP_TVERBAFCTOMADOR_BI0;

DROP TRIGGER VRHF_EMP_TVERBAFCTOMADOR_BU0;

DROP TRIGGER VRHF_EMP_TVERBAFCTOMINT_BIU0;

DROP TRIGGER VRHF_EMP_TVERBAFN_DET_BI0;

DROP TRIGGER VRHF_EMP_TVERBAFT_DET_BI0;

DROP TRIGGER VRHF_EMP_TVERBARFE_BI0;

DROP TRIGGER VRHF_EMP_TVERBARFE_BU0;

DROP TRIGGER VRHF_EMP_TVERBATOMADOR_BI0;

DROP TRIGGER VRHF_EMP_TVERBATOMADOR_BU0;

DROP TRIGGER VRHF_EMP_TVSCOL_BI0;

DROP TRIGGER VRHF_TABELAS_TCONTRSIND_BI0;

DROP TRIGGER VRHF_TABELAS_TINSS_BI0;

DROP TRIGGER VRHF_TABELAS_TINSSFAIXAS_BI0;

DROP TRIGGER VRHF_TABELAS_TIR_BI0;

DROP TRIGGER VRHF_TABELAS_TIRDADOS_BI0;

DROP TRIGGER VRHF_TABELAS_TIRFAIXAS_BI0;

DROP TRIGGER VRHF_TABELAS_TSALFAMFAIXAS_BI0;

DROP TRIGGER VRHM_BASE_TTIPOCONVENIO_BI0;

DROP TRIGGER VSUC_BASE_TNOTAEXPLICATIVA_BI0;

DROP TRIGGER VSUC_EMP_TLAN_SPED_I012_BI0;

DROP TRIGGER VSUC_EMP_TLAN_SPED_I015_BI0;

DROP TRIGGER VSUC_EMP_TVINCTRAN_BD0;

DROP TRIGGER VSUC_EMPRESAS_TENCEXE_BD0;

DROP TRIGGER VSUC_EMPRESAS_TLAN_BD0;

DROP TRIGGER VSUC_EMPRESAS_TLANFORM_BI0;

DROP TRIGGER VSUC_EMPRESAS_TLANNE_BI0;

DROP TRIGGER VSUC_EMPRESAS_TLCC_BI0;

DROP TRIGGER VSUC_EMPRESAS_TNOT_EXPLIC_BI0;

DROP TRIGGER VSUC_EMPRESAS_TORC_BI0;

DROP TRIGGER VSUC_EMPRESAS_TPRE_EXT_BAN_BI0;

DROP TRIGGER VSUC_TCONFIG_IMP_CC_BI0;

DROP TRIGGER VSUC_TCONFIG_IMP_EXT_BIO;

DROP TRIGGER VSUC_TCONFIG_IMP_LANC_BIO;

DROP TRIGGER VEF_EMP_TMOVSERRECIFE_BI0; 

DROP TRIGGER VEF_EMP_TMOVSERCABIPM_BI0; 

DROP TRIGGER VRH_BASE_TAMBIENTETRABALHO_BI0;

DROP TRIGGER VRH_BASE_TAMBTRAB_FR_BI0;

DROP TRIGGER VRH_EMP_TTRABAVULSO_BI0;

--Sol. 18507 - Bruno L. R. - Início
DROP TRIGGER TR_AF_INSERT_TEMPRESAS;

DROP TRIGGER TR_AF_INSERT_TDARFPADRAO;

DROP TRIGGER TOL_VFIN_DESP_DARF_AD0;

DROP PROCEDURE SP_VRH_VERIFICAVERBASEMP_PADRAO;

DROP PROCEDURE SP_INSS_IRRF_ESOCIAL;
--Sol. 18507 - Bruno L. R. - Fim

--Sol. 19704 - Bruno L. R. - 27/07/2017
DROP TRIGGER VRH_EMP_TCOL_EXAME_TOX_BI0;

DROP TRIGGER VRH_EMP_TCOL_EXAME_TOX_AU0;

DROP TRIGGER VRH_EMP_TCOL_EXAME_TOX_AI0;

DROP TRIGGER VRH_EMP_TCOL_EXAME_TOX_BU0;

DROP TRIGGER VRH_EMP_TREDUCAOCOL_BI0;

DROP TRIGGER vrh_emp_tsitcol_bi0;

DROP TRIGGER vrh_emp_tsitcol_ai0;

--Sol. 18256 - Bruno L. R. - 02/08/2017
DROP TRIGGER vrh_emp_trescisao_reintegr_ad0;

DROP TRIGGER VRH_EMP_TCOL_REINTEGRACAO_AD0;

DROP TRIGGER VRH_ESOCIAL_FECHAMENTO_BI0;

DROP TRIGGER VRH_ESOCIAL_FECHAMENTO_BU0;

DROP TRIGGER VRH_ESOCIAL_FECHAMENTO_AD0;

DROP TRIGGER VRH_EMP_TCOLCON_CAD_BI0;

DROP TRIGGER VRH_EMP_TCOLCON_CAD_BU0;

DROP TRIGGER VRH_EMP_TCOLCON_DOCREF_BI0;

DROP TRIGGER VRH_EMP_TCOL_ADMREF_BI0;

DROP TRIGGER VRH_EMP_TEMPRESASSST_BI0;

DROP TRIGGER VRH_EMP_TCOL_ADMREF_BU0;

DROP TRIGGER VRH_EMP_TCOLCON_FIS_BI0;

DROP trigger vrh_emp_tcomercnfprodrural_bi0;

DROP trigger TR_BF_INSERT_EMPRESAS_TIMOVRUR;

DROP trigger tr_bf_insert_emp_texplocontrat;

DROP trigger VSUC_BASE_EXT_TBANDEIRAS_BI0;

DROP trigger VSUC_BASE_EXT_TOPERADORAS_BI0;

DROP trigger VSUC_BASE_TFORMULA_AUTO_BI0;

DROP trigger VSUC_EMP_EXT_CARTAOCREDITO_BI0;

DROP trigger planos_tpla_carne_leao_ref_bi0;

DROP trigger planos_tpla_carne_leao_pad_bi0;

DROP trigger VSUC_TCONFIG_IMP_LANC_PLAN_BI0;

DROP trigger VSUC_EMP_TPREPVARCAMBIAL_BI0;

DROP trigger TOL_VSUC_EMP_TVARCAMBIAL_AD0;

DROP trigger VSUC_EMP_ECF_TARQECD_CTAZER_BI0;

DROP trigger VSUC_EMP_ECF_TARQUIVOECD_BI0;

DROP trigger VSUC_BASE_FORMULA_TMENSAL_BI0;

DROP trigger VSUC_EMPRESAS_TGRPECO_BI0;

DROP TRIGGER VEF_EMP_TMOVENTPR_BI0;

DROP TRIGGER VEF_EMP_TMOVSAIPR_BI0;

DROP TRIGGER VEF_EMP_TMOVSERPR_BI0;

DROP TRIGGER VEF_EMP_TMOVDEMAISDOCPR_BI0;

DROP TRIGGER TDEPENDENTE_CARNE_LEAO_BI0;

DROP TRIGGER TR_BF_INSERT_TPLANO_SECUNDARIO;

DROP TRIGGER PLANOS_TPLA_SECUNDARIO_BI0;

DROP TRIGGER PLANOS_TPLA_SECUNDARIO_BU0;

DROP TRIGGER PLANOS_TPLA_SECUNDARIO_BD0;

DROP TRIGGER tsmtp_sci_au0;

DROP TRIGGER VEF_EMP_TAJUAPUPCM220620_BI0;

DROP TRIGGER VEF_EMP_TAJUAPUPCM220620_BU0;

DROP TRIGGER TMP_VEF_EMP_TREDZVARCFOP_TMP_BI;

DROP TRIGGER TMP_VEF_EMP_TREDZVARALIQ_BI;

DROP TRIGGER TMP_VEF_EMP_TREDZC425_BI;

DROP TRIGGER VEF_EMP_TCREDITO_M220_M620_BD0;

DROP TRIGGER TFORMSEQREL_BI0;

DROP TRIGGER TTIPOSEQREL_BI0;

DROP TRIGGER vef_emp_tmovser_ibscbs_biu0;

DROP TRIGGER VEF_EMP_TMOVSERITENS_BIU0;

DROP TRIGGER VSUC_BANCOS_PDF_BI0;

/* Drop View... */
DROP VIEW VW_CALCVESP;

DROP VIEW VW_CLASS_00400;

DROP VIEW VW_CLASS_00401;

DROP VIEW VW_CLASS_00402;

DROP VIEW VW_CLASS_00403;

DROP VIEW VW_CLASS_00404;

DROP VIEW VW_COLABORADORES;

DROP VIEW VW_VRH_EMP_TCOLCON_FIS;

DROP VIEW VW_COLABORADORES_REF_ADM;

DROP VIEW VW_COLABORADORES_REF_ATUAL;

DROP VIEW VW_CONSULTA_RDE;

DROP VIEW VW_CONSULTA_RDT;

DROP VIEW VW_DEMITIDOS;

drop procedure SP_TRANSFERENCIA_PARCELAS;

DROP VIEW VW_EMP_REF_TOTAL;

DROP VIEW VW_EMPRESAS_REF_ATUAL_SEARCH;

DROP VIEW VW_EMPRESAS_TBEM;

DROP VIEW VW_EMPRESAS_TSOCCOTAS;

DROP VIEW VW_UNION_FGTS;

DROP VIEW VW_FGTS_13S;

DROP VIEW VW_FGTS_A13;

DROP VIEW VW_FGTS_AVULSA;

DROP VIEW VW_FGTS_C13;

DROP VIEW VW_FGTS_FOL_COMPLEMENTAR;

DROP VIEW VW_FGTS_FOL_COMPLEMENTAR_INT;

DROP VIEW VW_FGTS_FOL_NORMAL;

DROP VIEW VW_FGTS_FOLHA_TOMADOR_AGR;

DROP VIEW VW_UNION_FGTS_CC;

DROP VIEW VW_FGTS_FOLHA_TOMADOR;

DROP VIEW VW_FICHA_FGTS;

DROP VIEW VW_UNION_INSS;

DROP VIEW VW_FICHA_INSS;

DROP VIEW VW_UNION_IR;

DROP VIEW VW_FICHA_IR;

DROP VIEW VW_UNION_RAIS;

DROP VIEW VW_VRHF_EMP_TFICHARAIS;

DROP VIEW VW_VRHF_EMP_TFICHARAIS_DETR;

DROP VIEW VW_FICHA_RAIS;

DROP VIEW VW_HIST_AUM_SAL;

DROP VIEW VW_HIST_AUMHE_SAL;

DROP VIEW VW_INSS_13S;

DROP VIEW VW_INSS_C13;

DROP VIEW VW_INSS_FOL_COMPLEMENTAR;

DROP VIEW VW_INSS_FOL_NORMAL;

DROP PROCEDURE SP_ATUALIZAR_TMP_C177_GIAF;

DROP VIEW VW_INT_SPEDICMSREF19_REF;

DROP VIEW VW_INT_SPEDICMS_REF;

--21893 - ELIZEU - ControlMemory traz desordenado, e partimos pra views com variáveis de sessão "USER_SESSION"
DROP PROCEDURE SP_EXPORTA_BLOCOC_CONTRIBUICOES;

DROP PROCEDURE SP_EXPORTA_BLOCOC_SAI_SPEDCONTR;
DROP PROCEDURE SP_EXPORTA_C800_SAI_SPEDCONTR;

--21893 - ELIZEU - ControlMemory traz desordenado, e partimos pra views com variáveis de sessão "USER_SESSION"
DROP VIEW VW_EXP_SPED_CONTRIBUICOES_ENT;
DROP VIEW VW_EXP_SPED_CONTRIBUICOES_SAI;

DROP PROCEDURE SP_RET_REF_1010_1020_EXPORT;  

DROP VIEW VW_INT_SPEDPISCOFINS_REF;

DROP VIEW VW_IR_13_FOL_NORMAL;

DROP VIEW VW_UNION_BASES_IR;

DROP VIEW VW_IR_13S;

DROP VIEW VW_IR_AD_SALARIO;

DROP VIEW VW_IR_C13;

DROP VIEW VW_IR_FERIAS;

DROP VIEW VW_IR_FOL_COMPLEMENTAR;

DROP VIEW VW_IR_FOL_NORMAL;

DROP VIEW VW_RAIS_13S;

DROP VIEW VW_RAIS_A13;

DROP VIEW VW_RAIS_C13;

DROP VIEW VW_RAIS_FOL_AVULSA;

DROP VIEW VW_RAIS_FOL_COMPLEMENTAR;

DROP VIEW VW_RAIS_FOL_COMPLEMENTAR_DETR;

DROP VIEW VW_RAIS_FOL_NORMAL;

DROP VIEW VW_RAIS_FOL_NORMAL_DETR;

DROP VIEW VW_RELACIONAMENTO_GERADOR;

DROP VIEW VW_RESCISAO;

DROP VIEW VW_RESCISAO_PREVIA;

DROP VIEW VW_SN_ENCARGOS_SALARIOS;

DROP VIEW VW_SN_IMPOSTOS_REF;

DROP VIEW VW_SWS_EMP_SCIREPORT;

DROP VIEW VW_TATVMUNICIPAL;

DROP VIEW VW_TCADPRO;

DROP VIEW VW_TCADPRO_ATUAL;

DROP VIEW VW_TCADPRO_EXISTENTES;

DROP VIEW VW_TCADPRO_SIMPLES;

DROP VIEW VW_TCIDADE_GOOGLE;

DROP VIEW VW_TCNAE_REF;

DROP VIEW VW_TCOLCON_CALCDIA;

DROP VIEW VW_TCOLCON_DIA_ATUAL;

DROP VIEW VW_TCOLCON_REF_ATUAL;

DROP VIEW VW_TCOLCON_VINCDIA;

DROP VIEW VW_TEMP_SPED_FCONT_REF;

DROP VIEW VW_UNION_DADOS_CC;

DROP VIEW VWRH_DADOS_RDE_RELATORIO;

DROP VIEW VWRH_DADOS_RDE;

DROP VIEW VWRH_DADOS_RDT_RELATORIO;

DROP VIEW VWRH_DADOS_RDT;

DROP VIEW VWRH_PESQUISA_COLCON_PIS_CPF;

DROP VIEW VWSCI_DADOS_DARFIMP_RELATORIO;

DROP VIEW VWSCI_DADOS_DARFIMP;

DROP VIEW VW_TEMPRESAS_REF;

DROP VIEW VW_TEMPRESAS_REF_ATUAL;

DROP VIEW VW_TEMPRESAS_REF_JOIN;

DROP VIEW VW_TEMPRESAS_REF_MAX;

DROP VIEW VWGR_VSUC_CENTROS;

DROP VIEW VWGR_VSUC_HISTORICOS;

DROP VIEW VWGR_VSUC_PLANOCONTAS;

Drop VIEW VWGR_FIN_ESCRITORIO;

DROP VIEW VW_TEMPRESAS_REF_MAX_MIN;

DROP VIEW VW_TEMPRESAS_REF_SEM_USU;

DROP VIEW VW_TEMPRESAS_REF_MAX_MIN_USU;

DROP VIEW VW_TEMPRESAS_REF_MIN;

DROP VIEW VW_TENQFED;

DROP VIEW VW_TFERIADOS;

DROP VIEW VW_TINDVAL;

DROP VIEW VW_TMENURAPIDO;

DROP VIEW VW_TOMADORES;

DROP VIEW VW_TOMADORES_REF;

DROP VIEW VW_TOMADORES_REF_ATU;

DROP VIEW VW_TOT_VRHF_EMP_TPGTO_CALC;

DROP VIEW VW_TOTAL_FN_FC;

DROP VIEW VW_TRANSF;

DROP VIEW VW_TRANSFERIDOS;

DROP VIEW VW_VEF_TOT_CID_ENT;

DROP VIEW VW_VEF_TOT_CID_SAI;

DROP VIEW VW_VEF_TOT_NAT_ENT_UF;

DROP VIEW VW_VEF_TOT_NAT_SAI_UF;

DROP VIEW VW_VEF_TOT_UF_ENT;

DROP VIEW VW_VEF_TOT_UF_SAI;

DROP VIEW VW_VEF_TOTEXP_UF_ENT_GIASP;

DROP VIEW VW_VEF_TOTEXP_UF_GIASP;

DROP VIEW VW_VEF_TOTEXP_UF_SAI_GIASP;

DROP VIEW VW_TTERCEIRO;

DROP VIEW VW_VEF_CONSULTA_LAN_ENTRADA;

DROP VIEW VW_VEF_CONSULTA_LAN_SAIDA;

DROP VIEW VW_VEF_CONSULTA_LAN_SERVICO;

DROP VIEW VW_TTERCEIRO_SIMPLES;

DROP VIEW VW_TTERCEIRO_SOLETRADO;

DROP VIEW VW_TTERCEIRO_REF_MAX_MIN;

DROP VIEW VW_TTERCEIRO_VSUC;

DROP VIEW VW_UNION_FN_TOMADOR_REF;

DROP VIEW VW_UNION_FNINT_TOMINT_REF;

DROP VIEW VWRH_AGRUPADADOSADSAL;

DROP VIEW VWRH_AGRUPADADOSFOLAVUL;

DROP VIEW VWRH_RELATORIORECIBO13SAL01;

DROP VIEW VWRH_RELATORIORECIBOAD1301;

DROP VIEW VWRH_RELATORIORECIBOADSAL01;

DROP VIEW VWRH_RELATORIORECIBOC13SAL01;

DROP VIEW VWRH_RELATORIORECIBOFOLCOM01;

DROP VIEW VWRH_RELATORIORECIBOFOLHA01;

DROP VIEW VW_TVERBAS_REF;

DROP VIEW VW_TVERBAS;

DROP VIEW VW_TVERBAS_EDIT;

DROP VIEW VW_UNION_BASES_FN_FC;

DROP VIEW VW_UNION_CONS_CONTAB_AD;

DROP VIEW VW_UNION_CONS_CONTAB_AUT;

DROP VIEW VW_UNION_CONS_CONTABILIZACA_A13;

DROP VIEW VW_UNION_CONS_CONTABILIZACA_C13;

DROP VIEW VW_UNION_CONS_CONTABILIZACAO_13;

DROP VIEW VW_UNION_CONS_CONTABILIZACAO_AD;

DROP VIEW VW_UNION_CONS_CONTABILIZACAO_AU;

DROP VIEW VW_UNION_CONS_CONTABILIZACAO_FA;

DROP VIEW VW_UNION_CONS_CONTABILIZACAO_FC;

DROP VIEW VW_UNION_CONS_CONTABILIZACAO_FE;

DROP VIEW VW_UNION_CONS_CONTABILIZACAO_FN;

DROP VIEW VW_UNION_PL_VERBAS_FF;

DROP VIEW VW_VERBAS_FF;

DROP VIEW VW_UNION_FF_HE_RV_HN;

DROP VIEW VW_UNION_FICHASFINANCEIRAS;

DROP VIEW VW_UNION_FN_TOMADOR;

DROP VIEW VW_UNION_FN_TOMADOR_VERBAS;

DROP VIEW VW_UNION_FN_TOMADOR_VERBAS_DET;

DROP VIEW VW_UNION_MOVIMENTACOES;

DROP VIEW VW_VALOR_MES_RENDIMENTO_ISENTO;

DROP VIEW VW_UNION_RENDIMENTO_ISENTO;

DROP VIEW VW_VEF_RETENCOES_ENT_SAI_SER;

DROP VIEW VW_UNION_VEF_SER_RET;

DROP VIEW VW_UNION_VERBAS_SIM_NAO;

DROP VIEW VW_REC_IR_PIS_COFINS_CSLL_AUX;

DROP VIEW VW_UNIONREC_IR_PIS_COFINS_CSLL;

DROP VIEW VW_VALOR_MES_DESPESAS_MEDICAS;

DROP VIEW VW_VALOR_MES_DIARIAS_ACUSTOS;

DROP VIEW VW_VALOR_MES_INDENIZACAO;

DROP VIEW VW_VALOR_MES_PENSAO_ALIMENTICIA;

DROP VIEW VW_VEF_BASE_LIVROICMSUF;

DROP VIEW VW_VEF_BASE_TCONFATIVA;

DROP PROCEDURE GET_ATIVIDADES_SN;

DROP VIEW VW_VEF_BASE_TEMPITEMSATV;

DROP VIEW VW_VEF_BASE_TEMPPAREST;

DROP VIEW VW_VEF_BASE_TEMPPARESTES;

DROP VIEW VW_VEF_BASE_TEMPPARESTMG;

DROP VIEW VW_VEF_BASE_TEMPPARESTPR;

DROP VIEW VW_VEF_BASE_TEMPPARESTRO;

DROP VIEW VW_VEF_BASE_TEMPPARESTSC;

DROP VIEW VW_VEF_BASE_TEMPPARESTSP;

DROP VIEW VW_VEF_BASE_TEMPPARFED;

DROP VIEW VW_VEF_BASE_TEMPPARFEDPORATV;

DROP VIEW VW_VEF_BASE_TEMPPARGER;

DROP VIEW VW_VEF_BASE_TEMPPARGER_MAX_MIN;

DROP VIEW VW_VEF_BASE_TEMPPARINTEG;

DROP VIEW VW_VEF_BASE_TTABSIMPLESN;

DROP VIEW VW_VEF_BASE_TVINCULOISS;

DROP VIEW VW_VEF_EMP_SIMPLESNACIONAL;

DROP VIEW VW_VEF_EMP_TDACONGERUNION;

DROP VIEW VW_VEF_EMP_TDACONGERF1323;

DROP VIEW VW_VEF_EMP_TGIAESGERUNION;

DROP VIEW VW_VEF_EMP_TGIAMGGERUNION;

DROP VIEW VW_VEF_EMP_TGIAROGERUNION;

DROP VIEW VW_VEF_EMP_TGIASPGERUNION;

DROP VIEW VW_VEF_EMP_TICMSSPEDGERUNION;

DROP VIEW VW_VEF_EMP_TMOVENT;

DROP VIEW VW_VEF_EMP_TMOVENT_E_ITENS;

DROP VIEW VW_VEF_EMP_TMOVENT_EXP_SVA;

DROP VIEW VW_VEF_EMP_TMOVENT_ITENS;

DROP VIEW VW_VEF_EMP_TMOVENT_PRO_CST;

DROP VIEW VW_VEF_EMP_TMOVENT_PRO_EXPNFP;

DROP VIEW VW_VEF_EMP_TMOVSAI;

DROP VIEW VW_VEF_EMP_TMOVSAI_E_ITENS;

DROP VIEW VW_VEF_EMP_TMOVSAI_EXP_SVA;

DROP VIEW VW_VEF_EMP_TMOVSAI_ITENS;

DROP VIEW VW_VEF_EMP_TMOVSAI_PRO_CST;

DROP VIEW VW_VEF_EMP_TMOVSAI_PRO_EXPNFP;

DROP VIEW VW_VEF_EMP_TMOVSER_E_ITENS;

DROP VIEW VW_VEF_EMP_TMOVSER_EXP_SVA;

DROP VIEW VW_VEF_EMP_TREDZ_E_VARCFOP;

DROP VIEW VW_VEF_EMP_TREDZ_EXP_SVA;

DROP VIEW VW_VEF_EMP_TREDZC425;

DROP VIEW VW_VEF_SER_RET;

DROP VIEW VW_VEF_TABELAS_TREDICMSSN;

DROP VIEW VW_VEF_TABELAS_TREDISSSN;

DROP VIEW VW_VEF_TOT_NAT_ENT;

DROP VIEW VW_VEF_TMOVENTDIFALIQ;

DROP VIEW VW_VEF_TOT_NAT_ENT_DATE;

DROP VIEW VW_VEF_TOT_NAT_ENT_DATE_PROD;

DROP VIEW VW_VEF_TOT_NAT_ENT_DATE_REGCX;

DROP VIEW VW_VEF_TOT_NAT_ENT_DATE_TERC;

DROP VIEW VW_VEF_TOT_NAT_ENT_REGCAIXA;

DROP VIEW VW_VEF_TOT_NAT_SAI;

DROP VIEW VW_VEF_TOT_NAT_SAI_DATE;

DROP VIEW VW_VEF_TOT_NAT_SAI_DATE_PROD;

DROP VIEW VW_VEF_TOT_NAT_SAI_DATE_REGCX;

DROP VIEW VW_VEF_TOT_NAT_SAI_DATE_TERC;

DROP VIEW VW_VEF_TOT_NAT_SAI_REGCAIXA;

DROP VIEW VW_VEF_TOT_NAT_SER;

DROP VIEW VW_VEF_TOT_NAT_SER_ATVM;

DROP VIEW VW_VEF_TOT_NAT_SER_ATVM_REGCX;

DROP VIEW VW_VEF_TOT_NAT_SER_DATE;

DROP VIEW VW_VEF_TOT_NAT_SER_DATE_REGCX;

DROP VIEW VW_VEF_TOT_NAT_SER_REGCAIXA;

DROP VIEW VW_TEMPPARESTMG_MAX_MIN;

DROP VIEW VW_VERBAS_NAO_COL_ATUAL;

DROP VIEW VW_VERBAS_NAO_CUSTO_ATUAL;

DROP VIEW VW_VERBAS_NAO_EMP_ATUAL;

DROP VIEW VW_VERBAS_NAO_FUNCOES_ATUAL;

DROP VIEW VW_VERBAS_NAO_PRESC_ATUAL;

DROP VIEW VW_VERBAS_NAO_SIND_ATUAL;

DROP VIEW VW_VRHF_EMP_TVERBA_13_RAT_AGRU;

DROP VIEW VWRH_MAIORREMUNERACAO_DEMITIDOS;

DROP VIEW VWRH_MAIORREMUNERACAO_VERBAS;

DROP VIEW VW_VERBAS_REF_ATUAL;

DROP VIEW VW_VERBAS_REF_ATUAL_MAX;

DROP VIEW VW_VERBAS_REF_ATUAL_MIN;

DROP VIEW VW_VERBAS_SIM_COL_ATUAL;

DROP VIEW VW_VERBAS_SIM_CUSTO_ATUAL;

DROP VIEW VW_VERBAS_SIM_EMP_ATUAL;

DROP VIEW VW_VERBAS_SIM_FUNCOES_ATUAL;

DROP VIEW VW_VERBAS_SIM_PRESC_ATUAL;

DROP VIEW VW_VERBAS_SIM_SIND_ATUAL;

DROP VIEW VW_VERBASFC;

DROP VIEW VW_VERBASFN;

DROP VIEW VW_VRH_BASE_AUMENTOFAIXASCONV;

DROP VIEW VW_VRH_BASE_TCUSTOM_END;

DROP VIEW VW_VRH_BASE_TCUSTOM_GPS;

DROP VIEW VW_VRH_BASE_TEMPVINC;

DROP VIEW VW_VRH_BASE_TEMPVINC_MAX;

DROP VIEW VW_VRH_BASE_TEMPVINC_MIN;

DROP VIEW VW_VRH_BASE_TRESPEMP_FIRST;

DROP VIEW VW_VRH_BASE_TSINDTREF;

DROP VIEW VW_VRH_BASE_TSINDTREF_MAX;

DROP VIEW VW_VRH_BASE_TSINDTREF_MIN;

DROP VIEW VW_VRH_BASE_TSINDTREF_MINREF;

DROP VIEW VW_VRHF_EMP_TFICHAOUTRAS;

DROP VIEW VW_VRH_BASE_TVERBAS_REF;

DROP VIEW VW_VRH_BASE_TVERBAS;

DROP VIEW VW_VRHF_EMP_TFICHAHE;

DROP VIEW VW_VRHF_EMP_TFICHAHE_DETR;

DROP VIEW VW_VRH_BASE_TVERBAS_FICHA_HE;

DROP VIEW VW_VRHF_EMP_TFICHAHN;

DROP VIEW VW_VRH_BASE_TVERBAS_FICHA_HN;

DROP VIEW VW_VRHF_EMP_TFICHARV;

DROP VIEW VW_VRH_BASE_TVERBAS_FICHA_RV;

DROP VIEW VW_VRH_EMP_CONSCOLCON;

DROP VIEW VW_VRH_EMP_TAVISOFERIAS;

DROP VIEW VW_VRH_EMP_TCOL_ASO_PERI_ATUAL;

DROP VIEW VW_VRH_EMP_TCOL_HIST_COMPLETA;

DROP VIEW VW_VRH_EMP_TCOL_SHE;

DROP VIEW VW_VRH_EMP_TCOL_VDIA_COMPLETA;

DROP VIEW VWRH_COL_CALCULO;

DROP VIEW VW_VRH_EMP_TCOL_VINC;

DROP VIEW VW_VRH_EMP_TCOL_VINC_ADM;

DROP VIEW VW_VRH_EMP_TCOL_VINC_MAX;

DROP VIEW VW_VRH_EMP_TCOL_VINC_MIN;

DROP VIEW VW_VRH_EMP_TCOL_VINCDIA;

DROP VIEW VW_VRH_EMP_TCOL_VINCDIA_MAX;

DROP VIEW VW_VRH_EMP_TCOL_VINCDIA_NOVO;

DROP VIEW VW_VRH_EMP_TCOL_VINCDIA_MAX_MIN;

DROP VIEW VW_VRH_EMP_TCOL_VINCDIA_MIN;

DROP VIEW VWRH_COLCON_CALCULO;

DROP VIEW VW_VRH_EMP_TCOLCON_CALCDIA;

DROP VIEW VW_VRH_EMP_TCOLCON_CALCDIA_MAX;

DROP VIEW VW_VRH_EMP_TCOLCON_CALCDIA_MIN;

DROP VIEW VW_VRH_EMP_TCOLCON_CALCDIA_NOVO;

DROP VIEW VW_VRH_EMP_TCOLCON_CALCDIA_MMIN;

DROP VIEW VW_VRH_EMP_TCOLCON_ESTAG_ATUAL;

DROP VIEW VW_VRH_EMP_TCOLCON_REF;

DROP VIEW VW_VRH_EMP_TCOLCON_REF_MAX;

DROP VIEW VW_VRH_EMP_TCOLCON_REF_MIN;

DROP VIEW VW_VRH_EMP_TCOLCON_VINC;

DROP VIEW VW_VRH_EMP_TCOLCON_VINC_ADM;

DROP VIEW VW_VRH_EMP_TCOLCON_VINC_MAX;

DROP VIEW VW_VRH_EMP_TCOLCON_VINC_MIN;

DROP VIEW VW_VRH_EMP_TREEMBOLSO;

DROP VIEW VW_VRH_FUNCOES_TFUC;

DROP VIEW VW_VRH_TEMPRESAS_REF;

DROP VIEW VW_VRHF_13SAL;

DROP VIEW VW_VRHF_A13SAL;

DROP VIEW VW_VRHF_ADIANTAMENTO_SAL;

DROP VIEW VW_VRHF_BASE_TCONVREFEICAO_REF;

DROP VIEW VW_VRHF_EMPRESAS_REF_ATUAL;

DROP VIEW VW_VRHF_BASE_TEMPCALC;

DROP VIEW VW_VRHF_BASE_TEMPCALC_MAXREF;

DROP VIEW VW_VRHF_BASE_TEMPCALC_MINREF;

DROP VIEW VW_VRHF_BASE_TEMPDIRF;

DROP VIEW VW_VRHF_BASE_TEMPESOCIAL;

DROP VIEW VW_VRHF_BASE_TEMPGPS;

DROP VIEW VW_VRHF_BASE_TEMPGPS_JOIN;

DROP VIEW VW_VRHF_BASE_TEMPGPS_MAXREF;

DROP VIEW VW_VRHF_BASE_TEMPGPS_MINREF;

DROP VIEW VW_VRHF_BASE_TEMPGRCS;

DROP VIEW VW_VRHF_BASE_TEMPGRCS_MAXREF;

DROP VIEW VW_VRHF_BASE_TEMPGRCS_MINREF;

DROP VIEW VW_VRHF_BASE_TEMPPAR;

DROP VIEW VW_VRHF_BASE_TEMPPAR_MAXREF;

DROP VIEW VW_VRHF_BASE_TEMPPAR_MINREF;

DROP VIEW VW_VRHF_BASE_TEMPPROP;

DROP VIEW VW_VRHF_BASE_TEMPPROP_MAXREF;

DROP VIEW VW_VRHF_BASE_TEMPPROP_MINREF;

DROP VIEW VW_VRHF_BASE_TEMPRAIS;

DROP VIEW VW_VRHF_BASE_TEMPRAIS_MAXREF;

DROP VIEW VW_VRHF_BASE_TEMPRAIS_MINREF;

DROP VIEW VW_VRHF_BASE_TEMPSEFIP;

DROP VIEW VW_VRHF_BASE_TEMPSEFIP_MAXREF;

DROP VIEW VW_VRHF_BASE_TEMPSEFIP_MINREF;

DROP VIEW VW_VRHF_BASE_TEMPVINC;

DROP VIEW VW_VRHF_BASE_TEMPVINC_MAXREF;

DROP VIEW VW_VRHF_BASE_TEMPVINC_MINREF;

DROP VIEW VW_VRHF_BASE_TITINERARIOS_REF;

DROP VIEW VW_VRHF_BASE_TITI_REF_MAXMIN;

DROP VIEW VW_VRHF_BASE_TREF_REF_MAXMIN;

DROP VIEW VW_VRHF_BASE_TTERC_MVINC;

DROP VIEW VW_VRHF_C13SAL;

DROP VIEW VW_VRHF_CONS_CALC_FOLHA_VERBAS;

DROP VIEW VW_VRHF_EMP_FERIAS;

DROP VIEW VW_VRHF_EMP_GPS_IND;

DROP VIEW VW_VRHF_EMP_T13SAL_RAT_AGRU;

DROP VIEW VW_VRHF_EMP_TADSAL_FIXO;

DROP VIEW VW_VRHF_EMP_TCOLCON_BANCO;

DROP VIEW VW_VRHF_EMP_TCOLCON_BANCO_REF;

DROP VIEW VW_VRHF_EMP_TCOLCON_BANCO_ADM;

DROP VIEW VW_VRHF_EMP_TCOLCON_BANCO_MAX;

DROP VIEW VW_VRHF_EMP_TCOLCON_BANCO_MIN;

DROP VIEW VW_VRHF_EMP_TCOLCON_CALC;

DROP VIEW VW_VRHF_EMP_TCOLCON_CALC_ADM;

DROP VIEW VW_VRHF_EMP_TCOLCON_CALC_MAX;

DROP VIEW VW_VRHF_EMP_TCOLCON_CALC_NOVO;

DROP VIEW VW_VRHF_EMP_TCOLCON_CALC_MAXMIN;

DROP VIEW VW_VRHF_EMP_TCOLCON_CALC_MIN;

DROP VIEW VW_VRHF_EMP_TCOLCON_FGTS_JOIN;

DROP VIEW VWRH_DADOS_REL_GRRF;

DROP VIEW VWRH_DADOS_REL_GRRF_FC;

DROP VIEW VWRH_DADOS_REL_GRRF_PREVIA;

DROP VIEW VW_VRH_EMP_TCOLCON_DOCREF;

DROP VIEW VWRH_TRESCISAO_ADM_COL;

DROP VIEW VW_VRH_EMP_TCOL_ADM;

DROP VIEW VW_VRHF_EMP_TCOL_CALC;

DROP VIEW VW_VRHF_EMP_TCOL_CALC_ADM;

DROP VIEW VW_VRHF_EMP_TCOL_CALC_MAX;

DROP VIEW VW_VRHF_EMP_TCOL_CALC_MIN;

DROP VIEW VW_VRHF_EMP_TCOLCON_FGTSGPS;

DROP VIEW VW_VRHF_EMP_TCOLCON_FGTSGPS_ADM;

DROP VIEW VW_VRHF_EMP_TCOLCON_FGTSGPS_ATU;

DROP VIEW VW_VRHF_EMP_TCOLCON_FGTSGPS_MAX;

DROP VIEW VW_VRHF_EMP_TCOLCON_FGTSGPS_MIN;

DROP VIEW VW_VRHF_EMP_TCOLCON_FGTSGPS_REF;

DROP VIEW VW_VRHF_EMP_TCOLCON_MVINC;

DROP VIEW VW_VRHF_EMP_TCOLCON_MVINC_ADM;

DROP VIEW VW_VRHF_EMP_TCOLCON_MVINC_MAX;

DROP VIEW VW_VRHF_EMP_TCON_VINC;

DROP VIEW VW_VRHF_EMP_TCON_VINC_ADM;

DROP VIEW VW_VRHF_EMP_TCON_VINC_MAX;

DROP VIEW VW_VRHF_EMP_TCON_VINC_MIN;

DROP VIEW VW_VRHF_EMP_TCONVREFCOL;

DROP VIEW VW_VRHF_EMP_TFICHAINSS;

DROP VIEW VW_VRHF_EMP_TITICOL;

DROP VIEW VW_VRHF_EMP_TNOTASFISCAIS;

DROP VIEW VW_VRHF_EMP_TPREPFN;

DROP VIEW VW_VRHF_EMP_TPREPFN_MAX_NOVO;

DROP VIEW VW_VRHF_EMP_TPROVISAO13_CC;

DROP VIEW VW_VRHF_EMP_TVERBAAD;

DROP VIEW VW_VRHF_EMP_TVERBAFN_DET;

DROP VIEW VW_VRHF_FERIAS;

DROP VIEW VW_VRHF_FGTS_INDIVIDUALIZACAO;

DROP VIEW VW_VRHF_FGTSSEFIP_AGRUPA_1;

DROP VIEW VW_VRHF_FGTSSEFIP;

DROP VIEW VW_VRHF_FGTSSEFIP_13;

DROP VIEW VW_VRHF_FICHAHE;

DROP VIEW VW_VRHF_FICHAHN;

DROP VIEW VW_VRHF_FICHARV;

DROP VIEW VW_VRHF_FN_FC_13_C13_VERBAS;

DROP VIEW VW_VRHF_FOLHAAD;

DROP VIEW VW_VRHF_SS_COMP_13;

DROP VIEW VW_VRHF_SS_COMP_A13;

DROP VIEW VW_VRHF_SS_COMP_ADSAL;

DROP VIEW VW_VRHF_SS_COMP_C13;

DROP VIEW VW_VRHF_SS_COMP_FC;

DROP VIEW VW_VRHF_SS_COMP_FER;

DROP VIEW VW_VRHF_SS_COMP_FN;

DROP VIEW VW_VRHF_SS_PGTO_13;

DROP VIEW VW_VRHF_SS_PGTO_A13;

DROP VIEW VW_VRHF_SS_PGTO_ADSAL;

DROP VIEW VW_VRHF_SS_PGTO_C13;

DROP VIEW VW_VRHF_SS_PGTO_FC;

DROP VIEW VW_VRHF_SS_PGTO_FER;

DROP VIEW VW_VRHF_SS_PGTO_FN;

DROP VIEW VW_VRHF_TABELAS_TCONTRSINDFAIX;

--DROP VIEW VW_VRHM_EMP_COL_COP_OP_SAU;

--DROP VIEW VW_VRHM_EMP_DEP_COP_OP_SAU;

--DROP VIEW VW_VRHM_EMP_VINC_COL_CONV_ATU;

--DROP VIEW VW_VRHM_EMP_VINC_DEP_CONV_ATU;

DROP VIEW VW_VRHM_FAIXA_CONV_OP_SAU_ATU;

DROP VIEW VW_VRHM_FAIXA_CONV_OP_SAU_MAX;

DROP VIEW VW_VSUC_TLAN_CONTAS_USADAS;

DROP VIEW VW_VSUC_TLAN_CONTAS_USADAS_CRE;

DROP VIEW VW_VSUC_TLAN_CONTAS_USADAS_DEB;

DROP VIEW VWEF_EMPMENSAL_ABA_FEDE_REF;

DROP VIEW VWEF_EMPMENSAL_ABA_FEDE;

DROP VIEW VWEF_EMPMENSAL_ABA_PARA;

DROP VIEW VWEF_EMPMENSAL_ABA_PGER;

DROP VIEW VWEF_EMPMENSAL_ABA_UFSC;

DROP VIEW VWGR_EF_EXP_DCIP;

DROP VIEW VWRH_EMP_TPARCELAMENTO;

DROP VIEW VWRH_EMPMENSAL_ABA_GPS;

DROP VIEW VWRH_EMPMENSAL_ABA_GRCS;

DROP VIEW VWRH_EMPMENSAL_ABA_PCALC;

DROP VIEW VWRH_EMPMENSAL_ABA_PGER;

DROP VIEW VWRH_EMPMENSAL_ABA_PGERA;

DROP VIEW VWRH_EMPMENSAL_ABA_PROP;

DROP VIEW VWRH_EMPMENSAL_ABA_RAIS;

DROP VIEW VWRH_EMPMENSAL_ABA_SEFIP;

DROP VIEW VWRH_PENSAO_DEP;

DROP VIEW VWRH_TVERBAS_REF_MAX_MIN;

DROP VIEW VWRH_UNION_FC_FCT_CALC;

DROP VIEW VWRH_UNION_MES_VERBAS;

DROP VIEW VWRH_UNION_FC_FCT_MES;

DROP VIEW VWRH_UNION_FCI_FCTI_MES;

DROP VIEW VWRH_UNION_FICHAHE_TREEVIEW;

DROP VIEW VWRH_UNION_FICHAOT_TREEVIEW;

DROP VIEW VWRH_UNION_MES_BASES;

DROP VIEW VWRH_UNION_FC_FCT_MES_BASES;

DROP VIEW VWRH_UNION_FC_FCT_MESFN;

DROP VIEW VWRH_UNION_FC_FCT_MESFN_BASES;

DROP VIEW VWRH_UNION_FCI_FCTI_MESFN_BASES;

DROP VIEW VWRH_UNION_FICHAHN_TREEVIEW;

DROP VIEW VWRH_UNION_FICHARV_TREEVIEW;

DROP VIEW VWRH_UNION_FN_FT_LIQ_MES;

DROP VIEW VWRH_UNION_FN_FT_MES_BASES;

DROP VIEW VWRH_UNION_FNPR_FTPR_MES;

DROP VIEW VWRH_UNION_FNPR_FTPR_MES_BASES;

DROP VIEW VWSCI_EMPMENSAL_ABA_ADIC;

DROP VIEW VWSCI_EMPMENSAL_ABA_ESOCIAL;

DROP VIEW VWSCI_EMPMENSAL_ABA_LALUR;

DROP VIEW VWSCI_EMPMENSAL_ABA_PLA;

DROP PROCEDURE SP_PRE_VALIDA_CONTA_ONLINE_TEMP;

DROP PROCEDURE sp_valida_conta_online_temp;

DROP VIEW VW_TCONF_CONTAS_TODAS_REF;

DROP PROCEDURE SP_FERIADO_EMPRESA;

DROP PROCEDURE SP_VEF_TREEVIEW_CONS_GIAST;

DROP PROCEDURE SP_EXPORTA_GIAST;

DROP PROCEDURE SP_AJU_E111_E113_AUTO_PR;

DROP PROCEDURE SP_COPIA_PLANOCPRBREINF;

DROP VIEW VW_VRH_SISQUAL_FUNCAO;
DROP VIEW VW_VRH_SISQUAL_CENTRO_CUSTO;
DROP VIEW VW_VRH_SISQUAL_COLABORADOR;
DROP VIEW VW_VRH_SISQUAL_COL_CENTROCUSTO;
DROP VIEW VW_VRH_SISQUAL_COL_CONTRATO;
DROP VIEW VW_VRH_SISQUAL_COL_EMP_SAL;
DROP VIEW VW_VRH_SISQUAL_COL_FER_ATUAIS;
DROP VIEW VW_VRH_SISQUAL_COL_FUNCAO;
DROP VIEW VW_VRH_SISQUAL_COL_HIST_AFAST;
DROP VIEW VW_VRH_SISQUAL_COL_HIST_FER;
DROP VIEW VW_VRH_SISQUAL_COL_SALDO_FER;
DROP VIEW VW_VRH_SISQUAL_COL_SINDICATO;
DROP VIEW VW_VRH_SISQUAL_COL_TPSAL_VINC;
DROP VIEW VW_VRH_SISQUAL_EMPRESA_SALARIO;
DROP VIEW VW_VRH_SISQUAL_FERI_NACIONAL;

/* CREATE OR ALTER PROCEDURE... */
SET TERM ^ ;

CREATE OR ALTER procedure SP_TFERIADOS (
    PRANOMESI integer,
    PRANOMESF integer)
returns (
    BDDATAFER date,
    BDDESCFER varchar(50),
    BDCODCID integer,
    BDCODUF integer,
    BDREFFER integer,
    BDCODSINTRAB integer,
    BDDATAFERI date,
    BDCODFERI integer,
    BDFERIBANC DM_BOOLEAN)
as
declare variable WANOI integer;
declare variable WANOF integer;
declare variable WSQL varchar(5000);
declare variable WMESDIA varchar(4);
BEGIN
  wanoi = CAST((SUBSTRING(pranomesi FROM 1 FOR 4)) AS INTEGER);
  wanof = CAST((SUBSTRING(pranomesf FROM 1 FOR 4)) AS INTEGER);

  WHILE (wanoi <= wanof) DO
    BEGIN                                                                                         -- Data variável
      wsql = 'select BDCODUF, BDCODCID, BDDESCFERI, BDMESDIAFERI, BDCODSINTRAB, BDCODFERI, BDFERIBANC from TFERIADOSNOVO where BDTIPOFERI = 0'; --tcfFixo - Regra antes era <> 1
      FOR EXECUTE STATEMENT wsql INTO :bdcoduf, :bdcodcid, :bddescfer, :wmesdia, :bdcodsintrab, :bdcodferi, :bdferibanc DO
        BEGIN
          IF (CAST((wanoi||SUBSTRING(wmesdia FROM 3 FOR 2)) AS INTEGER) >= pranomesi AND CAST((wanoi||SUBSTRING(wmesdia FROM 3 FOR 2)) AS INTEGER) <= pranomesf) THEN
             BEGIN
               bddatafer  = CAST((SUBSTRING(wmesdia FROM 3 FOR 2)||'-'||SUBSTRING(wmesdia FROM 1 FOR 2)||'-'||wanoi) AS DATE);
               bddataferi = CAST((SUBSTRING(wmesdia FROM 3 FOR 2)||'-'||SUBSTRING(wmesdia FROM 1 FOR 2)||'-'||wanoi) AS DATE);
               bdreffer = CAST((wanoi||SUBSTRING(wmesdia FROM 1 FOR 2)) AS INTEGER);
               SUSPEND;
             END
        END
                                                                                                                             --tcfVariavel
      wsql = 'select BDCODUF, BDCODCID, BDDESCFERI, BDDATAFERI, BDCODSINTRAB, BDCODFERI, BDFERIBANC from TFERIADOSNOVO where BDTIPOFERI = 1 and BDDATAFERI >= '''||'01-01-'||wanoi||''' and BDDATAFERI <= '''||'12-31-'||wanoI||'''';
      FOR EXECUTE STATEMENT wsql INTO :bdcoduf, :bdcodcid, :bddescfer, :bddatafer, :bdcodsintrab, :bdcodferi, :bdferibanc DO
        BEGIN
          wmesdia = SUBSTRING(CAST(bddatafer AS VARCHAR(10)) FROM 6 FOR 2)||SUBSTRING(CAST(bddatafer AS VARCHAR(10)) FROM 9 FOR 2);
          IF (CAST((wanoi||SUBSTRING(wmesdia FROM 1 FOR 2)) AS INTEGER) >= pranomesi AND CAST((wanoi||SUBSTRING(wmesdia FROM 1 FOR 2)) AS INTEGER) <= pranomesf) THEN
             BEGIN
               bddataferi = bddatafer;
               bdreffer = CAST((SUBSTRING((CAST(bddatafer AS VARCHAR(10))) FROM 1 FOR 4)||SUBSTRING((CAST(bddatafer AS VARCHAR(10))) FROM 6 FOR 2)) AS INTEGER);
               SUSPEND;
             END
        END
      wanoi = wanoi + 1;
    END

END^

CREATE OR ALTER PROCEDURE ADD_MESES(PRDATA DATE,
PRADDMESES INTEGER)
 RETURNS(BDNOVADATA DATE)
 AS
DECLARE VARIABLE WI INTEGER;
DECLARE VARIABLE MES INTEGER;
DECLARE VARIABLE ANO INTEGER;
BEGIN

  mes = CAST(SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  ano = CAST(SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);

  /* Criado giovanni */

  wi = 0;

  WHILE  (wi < praddmeses)  DO
    BEGIN
      IF (mes = 12) THEN
         BEGIN
           mes = 1;
           ano = ano + 1;
         END
      ELSE
         BEGIN
           mes = mes + 1;
           ano = ano;
         END

      wi = (wi + 1);

    END

  bdnovadata = :mes||'/'||'01'||'/'||:ano;

  SUSPEND;

END
^

CREATE OR ALTER PROCEDURE ANO_BISEXTO(PRANO INTEGER)
 RETURNS(PRBISEXTO SMALLINT)
 AS
DECLARE VARIABLE wvar INTEGER;
BEGIN

  wvar = (prano / 4 * 4);

  IF (wvar = prAno) THEN
     begin
       wvar = (prano / 100 * 100);
       if (wvar = prAno) then
          begin
             wvar = (prano / 400 * 400);
             if (wvar = prAno) then
     prbisexto = 1; -- é ano bisexto
             else
                prbisexto = 0; -- não é ano bisexto
          end
       else
          prbisexto = 1; -- é ano bisexto
     end
  ELSE
     prbisexto = 0; -- não é ano bisexto

  SUSPEND;

END
^

CREATE OR ALTER PROCEDURE CHAR_ACENTUADO RETURNS(BDACENTO VARCHAR(10),
BDSEMACENTO VARCHAR(10))
 AS
DECLARE VARIABLE wacento VARCHAR(1000);
DECLARE VARIABLE wsemacento VARCHAR(1000);
DECLARE VARIABLE charac VARCHAR(10);
DECLARE VARIABLE characc VARCHAR(10);
DECLARE VARIABLE terminado SMALLINT;
BEGIN
    bdacento = 'á';
    bdsemacento = 'a';
    SUSPEND;
    bdsemacento = 'e';
    bdacento = 'é';
    SUSPEND;
    bdsemacento = 'i';
    bdacento = 'í';
    SUSPEND;
    bdsemacento = 'o';
    bdacento = 'ó';
    SUSPEND;
    bdsemacento = 'u';
    bdacento = 'ú';
    SUSPEND;
    bdsemacento = 'A';
    bdacento = 'Á';
    SUSPEND;
    bdsemacento = 'E';
    bdacento = 'É';
    SUSPEND;
    bdsemacento = 'I';
    bdacento = 'Í';
    SUSPEND;
    bdsemacento = 'O';
    bdacento = 'Ó';
    SUSPEND;
    bdsemacento = 'U';
    bdacento = 'Ú';
    SUSPEND;
    bdsemacento = 'c';
    bdacento = 'ç';
    SUSPEND;
    bdacento = 'Ç';
    bdsemacento = 'C';
    SUSPEND;
    bdacento = 'ã';
    bdsemacento = 'a';
    SUSPEND;
    bdacento = 'õ';
    bdsemacento = 'o';
    SUSPEND;
    bdacento = 'Ã';
    bdsemacento = 'A';
    SUSPEND;
    bdacento = 'Õ';
    bdsemacento = 'O';
    SUSPEND;
    bdacento = 'â';
    bdsemacento = 'a';
    SUSPEND;
    bdacento = 'ê';
    bdsemacento = 'e';
    SUSPEND;
    bdacento = 'ô';
    bdsemacento = 'o';
    SUSPEND;
    bdacento = 'Â';
    bdsemacento = 'A';
    SUSPEND;
    bdacento = 'Ê';
    bdsemacento = 'E';
    SUSPEND;
    bdacento = 'Ô';
    bdsemacento = 'O';
    SUSPEND;
    bdacento = 'à';
    bdsemacento = 'a';
    SUSPEND;
    bdacento = 'è';
    bdsemacento = 'e';
    SUSPEND;
    bdacento = 'ì';
    bdsemacento = 'i';
    SUSPEND;
    bdacento = 'ò';
    bdsemacento = 'o';
    SUSPEND;
    bdacento = 'ù';
    bdsemacento = 'u';
    SUSPEND;
    bdacento = 'À';
    bdsemacento = 'A';
    SUSPEND;
    bdacento = 'È';
    bdsemacento = 'E';
    SUSPEND;
    bdacento = 'Ì';
    bdsemacento = 'I';
    SUSPEND;
    bdacento = 'Ò';
    bdsemacento = 'O';
    SUSPEND;
    bdacento = 'Ù';
    bdsemacento = 'U';
    SUSPEND;
    bdacento = 'º';
    bdsemacento = 'o';
    SUSPEND;
    bdacento = '°';
    bdsemacento = 'o';
    SUSPEND;
    bdacento = 'ª';
    bdsemacento = 'a';
    SUSPEND;
    bdacento = 'ä';
    bdsemacento = 'a';
    SUSPEND;
    bdacento = 'Ä';
    bdsemacento = 'A';
    SUSPEND;
    bdacento = 'ö';
    bdsemacento = 'o';
    SUSPEND;
    bdacento = 'Ö';
    bdsemacento = 'O';
    SUSPEND;
END
^

CREATE OR ALTER PROCEDURE COMPARATEXTO(STR1 VARCHAR(1024),
STR2 VARCHAR(1024))
 RETURNS(RESULT VARCHAR(1024))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE CONTAR_CHAR(PRSTR VARCHAR(200),
PRSTR_BUSCA VARCHAR(1))
 RETURNS(CONTAR_CHAR INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE DDMMAAAA(PRDATA DATE)
 RETURNS(BDDDMMAAAA VARCHAR(10))
 AS
BEGIN
  /* Procedure Text */
  bdddmmaaaa =  SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
                SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
                SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 1 FOR 4);

  SUSPEND;
END
^

CREATE OR ALTER PROCEDURE DIA_SEGUINTE(PRDATA DATE)
 RETURNS(PRDIASEGUINTE DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE DIFERENCA_MESES(PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDMESES INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE DIMINUI_MESES(PRDATA DATE,
PRDIMINUIMESES INTEGER)
 RETURNS(BDNOVADATA DATE)
 AS
DECLARE VARIABLE WI INTEGER;
DECLARE VARIABLE MES INTEGER;
DECLARE VARIABLE ANO INTEGER;
BEGIN

  mes = CAST(SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  ano = CAST(SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);

  /* Criado giovanni */

  wi = 0;

  WHILE  (wi < prdiminuimeses)  DO
    BEGIN
      IF (mes = 1) THEN
         BEGIN
           mes = 12;
           ano = ano - 1;
         END
      ELSE
         BEGIN
           mes = mes - 1;
           ano = ano;
         END

      wi = (wi + 1);

    END

  bdnovadata = :mes||'/'||'01'||'/'||:ano;

  SUSPEND;

END
^

CREATE OR ALTER PROCEDURE EMPAUTSERV(PREMPRESA INTEGER,
PRAUTONOMO INTEGER,
PRSERVICO INTEGER)
 RETURNS(BDEMPAUTSERV VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE EXCLUIREG_INTERMEDIARIOS_ONLINE(PRCODEMP INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(20000);
DECLARE VARIABLE WTABLE VARCHAR(2000);
BEGIN
  /* Procedure Text */
--  suspend;
 FOR SELECT DISTINCT y.RDB$RELATION_NAME FROM RDB$relations y
    JOIN RDB$relation_fields x ON (y.RDB$RELATION_NAME = x.RDB$RELATION_NAME)
    WHERE UPPER(y.RDB$RELATION_NAME) LIKE 'TOL_%' AND (x.RDB$FIELD_NAME) = 'BDCODEMP'
  INTO wtable DO
   BEGIN
     wsql = 'delete from '||wtable||' where bdcodemp = '||prcodemp;
     EXECUTE STATEMENT wsql;
   END

END
^

create or alter procedure SP_GET_PRODUTO_IMP (
    PRCODEMP integer,
    PRSESSAO integer,
    PRSESSAOTER integer,
    PRCODPRODARQ varchar(60),
    PRCNPJTER varchar(18),
    PRIETER varchar(20),
    PRDESCPROD varchar(200),
    PRNOMETER varchar(100),
    PRVER_ENT_E_SAI varchar(5),
    PRCODTER integer,
    PRCODPRODVINC integer)
RETURNS (
    BDCODPROD INTEGER,
    BDDESCPROD VARCHAR(200))
AS
DECLARE VARIABLE WREF INTEGER;
DECLARE VARIABLE WVINCULOPART INTEGER;
DECLARE VARIABLE WORD INTEGER;
DECLARE VARIABLE WTER INTEGER;
BEGIN
  SUSPEND;
END
^


CREATE OR ALTER PROCEDURE SP_INS_UPT_TMP_TCADPRO (
    PRSESSAO INTEGER,
    PRREF INTEGER,
    PRCODSAIDA VARCHAR(60),
    PRCODENTRADA VARCHAR(60),
    PRCODPROD INTEGER,
    PRCODEMP INTEGER,
    PRCODTER INTEGER,
    PRCNPJTER VARCHAR(20),
    PRIETER VARCHAR(20),
    PRDESCPROD VARCHAR(200),
    PRORIGEMPROD INTEGER,
    PROPERATION VARCHAR(4),
    PRSEQ_PART INTEGER,
    PRINS_PROUNICO DM_BOOLEAN)
AS
DECLARE VARIABLE WORIGEMPROD INTEGER;
DECLARE VARIABLE WCODTERLAYOUT INTEGER;
DECLARE VARIABLE WCNPJTERLAYOUT VARCHAR(18);
DECLARE VARIABLE WIETERLAYOUT VARCHAR(20);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODSAIDA VARCHAR(60) COLLATE WIN_PTBR;
DECLARE VARIABLE WAPEPROD VARCHAR(30) COLLATE WIN_PTBR;
DECLARE VARIABLE WDESCPROD VARCHAR(200) COLLATE WIN_PTBR;
DECLARE VARIABLE WAPELIDOUNICO VARCHAR(30) COLLATE WIN_PTBR;
DECLARE VARIABLE WDESCRICAOUNICA VARCHAR(200) COLLATE WIN_PTBR;
DECLARE VARIABLE WCODIGOEAN VARCHAR(20) COLLATE WIN_PTBR;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WCODENTRADA VARCHAR(60) COLLATE WIN_PTBR;
DECLARE VARIABLE WCODTIPO INTEGER;
DECLARE VARIABLE WCODGEN INTEGER;
DECLARE VARIABLE WCODSER INTEGER;
DECLARE VARIABLE WCODCOMBANP INTEGER;
DECLARE VARIABLE WCODUNIMED INTEGER;
DECLARE VARIABLE WAPEUNIMED VARCHAR(5) COLLATE WIN_PTBR;
DECLARE VARIABLE WNCMPROD INTEGER;
DECLARE VARIABLE WCODTABINCID INTEGER;
DECLARE VARIABLE WGRUPO INTEGER;
DECLARE VARIABLE WORDEMMARCA INTEGER;
DECLARE VARIABLE WCODCSTIPISAI INTEGER;
DECLARE VARIABLE WCODCSTIPIENT INTEGER;
DECLARE VARIABLE WCODCSTICMS INTEGER;
DECLARE VARIABLE WCODCSTPISSAI INTEGER;
DECLARE VARIABLE WCODCSTPISENT INTEGER;
DECLARE VARIABLE WCODCSTCOFENT INTEGER;
DECLARE VARIABLE WCODCSTCOFSAI INTEGER;
DECLARE VARIABLE WVINCULOPART INTEGER;
DECLARE VARIABLE WALIQFCP DM_NUMERIC_7_4_ALIQ;
BEGIN

END
^

CREATE OR ALTER PROCEDURE SP_GERAR_INCON_TCADPRO (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRCODPLANOINCO INTEGER,
    PRREF INTEGER,
    PRSESSAOIMP INTEGER)
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_FATCONV_TEMP (
    PRSESSAO INTEGER,
    PRATUALIZARDADOS DM_BOOLEAN,
    PRGERARINCONSISTENCIAS DM_BOOLEAN)
AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODPROD INTEGER;
DECLARE VARIABLE WCODUNIMED INTEGER;
DECLARE VARIABLE WCODFATCON INTEGER;
DECLARE VARIABLE WFATORCONVER NUMERIC(15,6);
BEGIN     
  PRATUALIZARDADOS      = UPPER(:PRATUALIZARDADOS);
  PRGERARINCONSISTENCIAS= UPPER(:PRGERARINCONSISTENCIAS);

  UPDATE TMP_TFATCONV_TEMP FC
  SET BDALTCODFATCON = NULL 
  WHERE FC.BDSESSAO = :PRSESSAO;

  UPDATE TMP_TFATCONV_TEMP FC
  SET BDALTCODFATCON = (SELECT MIN(F.BDCODFATCON) FROM TFATCONV F WHERE F.BDCODEMP = FC.BDCODEMP AND F.BDCODPROD = FC.BDCODPROD AND F.BDCODUNIMED = FC.BDCODUNIMED)
  WHERE FC.BDSESSAO = :PRSESSAO;

  UPDATE TMP_TFATCONV_TEMP FC
  SET BDALTCODFATCON = FC.BDCODFATCON + (SELECT COALESCE(MAX(BDCODFATCON),0) FROM TFATCONV WHERE BDCODEMP = FC.BDCODEMP AND BDCODPROD = FC.BDCODPROD)
  WHERE FC.BDSESSAO = :PRSESSAO AND FC.BDALTCODFATCON IS NULL;

  /*IF (:PRATUALIZARDADOS = 'FALSE') THEN
    BEGIN
    --  Se não é pra atualizar, joga os dados da tabela TFATCONV pra tabela TEMP, assim quando ficar o insert or update não vai alterar os registros
      FOR SELECT IT.BDCODEMP, IT.BDCODPROD, IT.BDCODUNIMED, IT.BDCODFATCON, CI.BDFATORCONVER
          FROM TMP_TFATCONV_TEMP IT
          LEFT OUTER JOIN TCADPRO_VINC P ON(P.BDCODEMP = IT.BDCODEMP AND P.BDCODPROD = IT.BDCODPROD)
          JOIN TFATCONV CI ON(CI.BDCODEMP = IT.BDCODEMP AND CI.BDCODPROD = IT.BDCODPROD AND CI.bdcodunimed = IT.bdcodunimed)
          WHERE IT.BDSESSAO = :PRSESSAO
          INTO :WCODEMP, :WCODPROD, :WCODUNIMED, :WCODFATCON, :WFATORCONVER
      DO
        BEGIN
          IF ((:WCODPROD IS NOT NULL) OR (:WCODPROD > 0)) THEN
            BEGIN
              UPDATE TMP_TFATCONV_TEMP IT SET IT.BDFATORCONVER = :WFATORCONVER
              WHERE IT.BDSESSAO    = :PRSESSAO
              AND IT.BDCODEMP      = :WCODEMP
              AND IT.BDCODPROD     = :WCODPROD
              AND IT.BDCODUNIMED   = :WCODUNIMED
              AND IT.BDCODFATCON   = :WCODFATCON;
            END
        END
    END      */
END^

CREATE OR ALTER PROCEDURE SP_VINCULAR_FATCONV (
    PRSESSAO INTEGER,
    PRID_TERMINAL INTEGER)
AS
DECLARE VARIABLE WTABLE VARCHAR(50);
DECLARE VARIABLE WSESSAOATU INTEGER;
DECLARE VARIABLE WSQL VARCHAR(600);
BEGIN
  FOR SELECT TRIM(UPPER(T.RDB$RELATION_NAME)) BDTABLE
      FROM RDB$RELATION_FIELDS T
      WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
      AND RDB$FIELD_NAME = 'BDALTCODFATCON'
      AND TRIM(UPPER(T.RDB$RELATION_NAME)) <> 'TMP_TFATCONV_TEMP'
      AND EXISTS(
                 SELECT F.RDB$RELATION_NAME BDTABLE
                 FROM RDB$RELATION_FIELDS F
                 WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
                 AND (RDB$FIELD_NAME = 'BDCODFATCON')
                 AND T.RDB$RELATION_NAME = F.RDB$RELATION_NAME
                 GROUP BY F.RDB$RELATION_NAME
                )
      INTO :wTable
  DO
    BEGIN
      wSessaoAtu = NULL;

      SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = :wTable INTO :wSessaoAtu;
      IF (:wSessaoAtu IS NOT NULL) THEN
        BEGIN
          --#214954 Otimização na Importação do sped fiscal- fator de conversão
          wSql = 'UPDATE '||:wTable||' T SET T.BDALTCODFATCON = NULL WHERE T.BDSESSAO = '||:wSessaoAtu||' AND T.BDALTCODFATCON IS NOT NULL ';
          EXECUTE STATEMENT :wSql;

          wSql = 'UPDATE '||:wTable||' T SET T.BDALTCODFATCON = (SELECT FIRST 1 F.BDALTCODFATCON FROM TMP_TFATCONV_TEMP F WHERE F.BDSESSAO = '||:PRSESSAO||' AND F.BDCODEMP = T.BDCODEMP AND F.BDCODPROD = T.BDCODPROD AND F.BDCODFATCON = T.BDCODFATCON) ';
          wSql = :wSql || 'WHERE T.BDSESSAO = '||:wSessaoAtu;
          wSql = :wSql || ' AND ((T.BDCODFATCON IS NOT NULL) AND (T.BDCODFATCON > 0))';
          EXECUTE STATEMENT :wSql;

          wSql =          ' UPDATE '||:wTable||' T SET T.BDCODFATCON = T.BDALTCODFATCON ';
          wSql = :wSql || ' WHERE T.BDSESSAO = '||:wSessaoAtu;
          wSql = :wSql || ' AND T.BDALTCODFATCON IS NOT NULL';
          EXECUTE STATEMENT :wSql;
        END
    END

END^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_PROD_GIAF (
    PRSESSAO integer)
as
--declare variable PRCODPROD integer;
--declare variable PRCODEMP integer;
--declare variable PRCODITEMGIAF integer;
--declare variable PRPRODINCENTIVADO DM_BOOLEAN;
--declare variable PRINCENTIVOTRANSP DM_BOOLEAN;
--declare variable PROPEDIFIMPORTACAO DM_BOOLEAN;
--declare variable PRCODSAIDA varchar(60);
--declare variable PRCODENT varchar(60);
begin
  /* Procedure Text */
     UPDATE TMP_TCADPRO_TEMP tp SET tp.BDPRODINCENTIVADO = (SELECT FIRST 1 P.BDPRODINCENTIVADO
                                                              FROM TMP_TCADPRO p
                                                              WHERE P.BDCODEMP = TP.BDCODEMP
                                                                AND P.BDCODSAIDA = TP.BDCODSAIDA
                                                                and p.BDCODPROD = tp.BDCODPROD),
                                    tp.BDCODITEMGIAF = (SELECT FIRST 1 P.BDCODITEMGIAF
                                                              FROM TMP_TCADPRO p
                                                              WHERE P.BDCODEMP = TP.BDCODEMP
                                                                AND P.BDCODSAIDA = TP.BDCODSAIDA
                                                                and p.BDCODPROD = tp.BDCODPROD),
                                   tp.BDINCENTIVOTRANSP = (SELECT FIRST 1 P.BDINCENTIVOTRANSP
                                                              FROM TMP_TCADPRO p
                                                              WHERE P.BDCODEMP = TP.BDCODEMP
                                                                AND P.BDCODSAIDA = TP.BDCODSAIDA
                                                                and p.BDCODPROD = tp.BDCODPROD),
                                   tp.BDOPEDIFIMPORTACAO = (SELECT FIRST 1 P.BDOPEDIFIMPORTACAO
                                                              FROM TMP_TCADPRO p
                                                              WHERE P.BDCODEMP = TP.BDCODEMP
                                                                AND P.BDCODSAIDA = TP.BDCODSAIDA
                                                                and p.BDCODPROD = tp.BDCODPROD)
   WHERE tp.BDSESSAO = :PRSESSAO
   AND tp.BDPRODEXISTEBASE = 'TRUE';
--  FOR
--   SELECT PRO.BDCODEMP,PRO.BDCODPROD,PRO.BDCODSAIDA,PRO.BDCODENTRADA,P.BDPRODINCENTIVADO,P.BDCODITEMGIAF, P.BDINCENTIVOTRANSP, P.BDOPEDIFIMPORTACAO
--   FROM TMP_TCADPRO_TEMP PRO
--   JOIN TMP_TCADPRO P ON (P.BDCODEMP =  PRO.BDCODEMP AND P.BDCODPROD = PRO.BDCODPROD AND COALESCE(P.BDCODSAIDA,P.BDCODPROD) = PRO.BDCODSAIDA)
--   WHERE PRO.BDSESSAO = :PRSESSAO
--   AND PRO.BDPRODEXISTEBASE = 'TRUE'
--   INTO :PRCODEMP, :PRCODPROD,:PRCODSAIDA,:PRCODENT, :PRPRODINCENTIVADO,:PRCODITEMGIAF,:PRINCENTIVOTRANSP,:PROPEDIFIMPORTACAO
--  DO
--   BEGIN
--     UPDATE TMP_TCADPRO_TEMP PRO SET
--     PRO.BDPRODINCENTIVADO = :PRPRODINCENTIVADO,
--     PRO.BDCODITEMGIAF = :PRCODITEMGIAF,
--     PRO.BDINCENTIVOTRANSP = :PRINCENTIVOTRANSP,
--     PRO.BDOPEDIFIMPORTACAO = :PROPEDIFIMPORTACAO
--     WHERE PRO.BDSESSAO = :PRSESSAO
--     AND PRO.BDCODSAIDA = :PRCODSAIDA
--     and PRO.BDCODEMP = :PRCODEMP
--     AND PRO.BDCODPROD = :PRCODPROD;
--   END
end
^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_INSUMO_TEMP (
    PRSESSAO INTEGER,
    PRATUALIZARDADOS DM_BOOLEAN,
    PRGERARINCONSISTENCIAS DM_BOOLEAN)
AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WORDEM INTEGER;
DECLARE VARIABLE WCODSAIDA VARCHAR(60);
DECLARE VARIABLE WCODPROD INTEGER;
DECLARE VARIABLE WQTDCONSUMO NUMERIC(17,6);
DECLARE VARIABLE WPERDA DM_NUMERIC_7_4_ALIQ;
BEGIN
  PRATUALIZARDADOS      = UPPER(:PRATUALIZARDADOS);
  PRGERARINCONSISTENCIAS= UPPER(:PRGERARINCONSISTENCIAS);

  UPDATE TMP_TCADPRO_INSUMOS_TEMP INS SET BDALTORDEM = NULL WHERE INS.BDSESSAO = :PRSESSAO;

  UPDATE TMP_TCADPRO_INSUMOS_TEMP INS
--  SET BDALTORDEM = (SELECT BDORDEM FROM TCADPRO_INSUMOS WHERE BDCODEMP = INS.BDCODEMP AND BDCODPROD = INS.BDCODPROD AND BDCODPROINSUMO = INS.BDCODPROINSUMO)
  SET BDALTORDEM = (SELECT FIRST 1 BDORDEM FROM TCADPRO_INSUMOS
                    WHERE BDCODEMP = INS.BDCODEMP
                      AND BDCODPROD = INS.BDCODPROD
                      AND BDCODPROINSUMO = INS.BDCODPROINSUMO
                    ORDER BY BDCODEMP,BDCODPROD,BDCODPROINSUMO,BDORDEM desc)
  WHERE INS.BDSESSAO = :PRSESSAO;

  UPDATE TMP_TCADPRO_INSUMOS_TEMP INS
  SET BDALTORDEM = INS.BDORDEM + (SELECT COALESCE(MAX(BDORDEM),0) FROM TCADPRO_INSUMOS
                                  WHERE BDCODEMP = INS.BDCODEMP AND BDCODPROD = INS.BDCODPROD)
  WHERE INS.BDSESSAO = :PRSESSAO AND INS.BDALTORDEM IS NULL;

  IF (:PRATUALIZARDADOS = 'FALSE') THEN
    BEGIN
      /*Se não é pra atualizar, joga os dados da tabela TCADPRO_INSUMOS pra tabela TEMP, assim quando ficar o insert or update não vai alterar o registros da tabela de insumos*/
      FOR SELECT IT.BDCODEMP, IT.BDCODSAIDA, IT.BDORDEM,
                 CI.BDCODPROINSUMO, CI.BDQTDCONSUMO, CI.BDPERDA
          FROM TMP_TCADPRO_INSUMOS_TEMP IT
          LEFT OUTER JOIN TCADPRO_VINC P ON(P.BDCODEMP = IT.BDCODEMP AND P.BDCODPROD = IT.BDCODPROD)
          JOIN TCADPRO_INSUMOS CI ON(CI.BDCODEMP = IT.BDCODEMP AND CI.BDCODPROD = IT.BDCODPROD AND CI.BDREFERENCIA = IT.BDREFERENCIA AND CI.BDQTDCONSUMO = IT.BDQTDCONSUMO AND CI.BDPERDA = IT.BDPERDA)
          WHERE IT.BDSESSAO = :PRSESSAO
          AND IT.BDCODSAIDAPROD = P.BDCODSAIDA
          INTO :WCODEMP, :WCODSAIDA, :WORDEM, :WCODPROD,
               :WQTDCONSUMO, :WPERDA
      DO
        BEGIN
          IF ((:WCODPROD IS NOT NULL) OR (:WCODPROD > 0)) THEN
            BEGIN
              UPDATE TMP_TCADPRO_INSUMOS_TEMP IT SET IT.BDCODPROINSUMO = :WCODPROD, IT.BDQTDCONSUMO = :WQTDCONSUMO, IT.BDPERDA = :WPERDA
              WHERE IT.BDSESSAO    = :PRSESSAO
              AND IT.BDCODEMP      = :WCODEMP
              AND IT.BDCODSAIDAPROD= :WCODSAIDA
              AND IT.BDORDEM       = :WORDEM;
            END
        END
    END

  IF (:PRGERARINCONSISTENCIAS = 'TRUE') THEN
    BEGIN
      DELETE FROM VEF_INCON_TCADPRO_INSUMO D WHERE D.BDSESSAO = :PRSESSAO;

      /*70 - Produto do insumo inconsistente.*/
      /*Quando o produto é inconsistente torna o insumo inconsistente*/
      INSERT INTO VEF_INCON_TCADPRO_INSUMO(bdcodinconsistencia, bdsessao, bdcodsaida, bdcodemp, bdordem, BDCODPROD)
      SELECT 70 BDCODINCONSISTENCIA, IT.BDSESSAO, IT.BDCODSAIDA, IT.BDCODEMP, IT.BDORDEM, IT.BDALTCODPROD
      FROM TMP_TCADPRO_INSUMOS_TEMP IT
      WHERE IT.BDSESSAO = :PRSESSAO
        AND EXISTS(SELECT FIRST 1 IP.BDSESSAO
                   FROM VEF_INCON_TCADPRO IP                                                                                      
                   WHERE (IP.BDSESSAO = IT.BDSESSAO AND IP.BDCODPROD = IT.BDCODPROD));
                   --WHERE (IP.BDSESSAO = IT.BDSESSAO AND ((IP.BDCODPROD = IT.BDCODPROD) OR (IP.BDCODPROD = IT.bdcodproinsumo))));

      /*67 - Código do produto insumo não informado!*/
      /*Não existe produto no insumo, é obrigatório*/
      INSERT INTO VEF_INCON_TCADPRO_INSUMO(bdcodinconsistencia, bdsessao, bdcodsaida, bdcodemp, bdordem, BDCODPROD)
      SELECT 67 BDCODINCONSISTENCIA, I.BDSESSAO, I.BDCODSAIDA, I.BDCODEMP, I.BDORDEM, I.BDALTCODPROD
      FROM TMP_TCADPRO_INSUMOS_TEMP I
      WHERE I.BDSESSAO = :PRSESSAO
      AND ((I.BDCODSAIDAPROD IS NULL) OR (I.BDCODSAIDAPROD = ''));

      /*68 - Produto do insumo deve ter o tipo item como 00, 01, 02, 03, 04, 05 ou 10.*/
      /*O produto do insumo tem que ter o tipo item como 00, 01, 02, 03, 04, 05 ou 10*/
      INSERT INTO VEF_INCON_TCADPRO_INSUMO(bdcodinconsistencia, bdsessao, bdcodsaida, bdcodemp, bdordem, BDCODPROD)
      SELECT 68 BDCODINCONSISTENCIA, I.BDSESSAO, I.BDCODSAIDA, I.BDCODEMP, I.BDORDEM, I.BDALTCODPROD
      FROM TMP_TCADPRO_INSUMOS_TEMP I
      WHERE I.BDSESSAO = :PRSESSAO
      AND I.BDTIPOITEM NOT IN (1, 2, 3, 4, 5, 6, 11);

      /*69 - A quantidade de consumo não foi informada*/
      /*O insumo tem que ter quantidade de consumo, é obrigatório*/
      INSERT INTO VEF_INCON_TCADPRO_INSUMO(bdcodinconsistencia, bdsessao, bdcodsaida, bdcodemp, bdordem, BDCODPROD)
      SELECT 69 BDCODINCONSISTENCIA, I.BDSESSAO, I.BDCODSAIDA, I.BDCODEMP, I.BDORDEM, I.BDALTCODPROD
      FROM TMP_TCADPRO_INSUMOS_TEMP I
      WHERE I.BDSESSAO = :PRSESSAO
      AND ((I.BDQTDCONSUMO IS NULL) OR (I.BDQTDCONSUMO <= 0));

      /*183 - Insumo não existente na base*/
      /*Existe o registro de insumo no arquivo SPED, porém não existe um 0200 correspondente ao insumo*/
      INSERT INTO VEF_INCON_TCADPRO_INSUMO(bdcodinconsistencia, bdsessao, bdcodsaida, bdcodemp, bdordem, BDCODPROD)
      SELECT 183 BDCODINCONSISTENCIA, I.BDSESSAO, I.BDCODSAIDA, I.BDCODEMP, I.BDORDEM, I.BDALTCODPROD
      FROM TMP_TCADPRO_INSUMOS_TEMP I
      WHERE I.BDSESSAO = :PRSESSAO
        AND I.BDCODPROINSUMO IS NULL;

      /*71 - Insumo inconsistente.*/
      /*Se o produto do insumo é inconsistente o insumo e o produto tambem devem ser.*/
      INSERT INTO VEF_INCON_TCADPRO_INSUMO(bdcodinconsistencia, bdsessao, bdcodsaida, bdcodemp, bdordem, BDCODPROD)
      SELECT 71 BDCODINCONSISTENCIA, I.BDSESSAO, I.BDCODSAIDA, I.BDCODEMP, I.BDORDEM, I.BDALTCODPROD
      FROM TMP_TCADPRO_INSUMOS_TEMP I
      JOIN VEF_INCON_TCADPRO IC ON(IC.BDSESSAO = I.BDSESSAO AND IC.BDCODPROD = I.BDCODPROINSUMO)
      WHERE I.BDSESSAO = :PRSESSAO;

      /*71 - Insumo inconsistente.*/
      /*Se o insumo tem um insumo inconsistente.*/
      INSERT INTO VEF_INCON_TCADPRO_INSUMO(bdcodinconsistencia, bdsessao, bdcodsaida, bdcodemp, bdordem, BDCODPROD)
      SELECT 71 BDCODINCONSISTENCIA, I.BDSESSAO, I.BDCODSAIDA, I.BDCODEMP, I.BDORDEM, I.BDALTCODPROD
      FROM TMP_TCADPRO_INSUMOS_TEMP I
      JOIN VEF_INCON_TCADPRO_INSUMO INS ON (INS.BDSESSAO = I.BDSESSAO AND INS.BDCODSAIDA = I.BDCODSAIDAPROD)
--      LEFT OUTER JOIN VEF_INCON_TCADPRO IC ON(IC.BDSESSAO = I.BDSESSAO AND IC.BDCODPROD = I.BDCODPROINSUMO)
      WHERE I.BDSESSAO = :PRSESSAO /*AND IC.BDSESSAO IS NULL*/;

      /*71 - Insumo inconsistente. #148200 Ocorria erro em casos de insumo do insumo estando inconsistente*/
      /*Se o insumo tem um insumo inconsistente.*/
      INSERT INTO VEF_INCON_TCADPRO_INSUMO(bdcodinconsistencia, bdsessao, bdcodsaida, bdcodemp, bdordem, BDCODPROD)
      SELECT 71 BDCODINCONSISTENCIA, I.BDSESSAO, I.BDCODSAIDA, I.BDCODEMP, I.BDORDEM, I.BDALTCODPROD
      FROM TMP_TCADPRO_INSUMOS_TEMP I
      JOIN VEF_INCON_TCADPRO_INSUMO INS ON (INS.BDSESSAO = I.BDSESSAO AND INS.BDCODSAIDA = I.BDCODSAIDAPROD)
--      LEFT OUTER JOIN VEF_INCON_TCADPRO IC ON(IC.BDSESSAO = I.BDSESSAO AND IC.BDCODPROD = I.BDCODPROINSUMO)
      WHERE I.BDSESSAO = :PRSESSAO /*AND IC.BDSESSAO IS NULL*/;

      /*72 - Produto inconsistente devido ao insumo ser inconsistente.*/
      /*Se o insumo é inconsistente, torna o produto inconsistente*/
      FOR SELECT P.BDEDITCHAVE BDCODPROD, IP.BDCODEMP
          FROM VEF_INCON_TCADPRO_INSUMO IP
          JOIN TMP_TCADPRO_TEMP P ON(P.BDSESSAO = IP.BDSESSAO AND P.BDCODSAIDA = IP.BDCODSAIDA)
          WHERE IP.BDSESSAO = :PRSESSAO
          GROUP BY P.BDEDITCHAVE, IP.BDCODEMP
          INTO :WCODPROD, :wCodEmp
      DO
        BEGIN
          INSERT INTO VEF_INCON_TCADPRO (BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP) VALUES (72, :PRSESSAO, :WCODPROD, :WCODEMP);
        END

    END
END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_CST_PROD (
    PRSESSAO INTEGER,
    PRALTERARCST DM_BOOLEAN)
AS
BEGIN
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_CST_PROD','1');
  /*Importação de cadastro de produtos Layout SCI não deve alterar as CSTs*/
  if ((:PRALTERARCST is null) or (Upper(:PRALTERARCST) = 'TRUE')) then
    BEGIN
      /*Atualiza as CST's*/
      /*IPI - Entrada*/
      UPDATE TMP_TCADPRO_TEMP P SET P.BDCODCSTIPIENT = (SELECT FIRST 1 IPI.BDCODCSTIPIENT FROM VEF_BASE_TCSTIPICORENTSAI IPI WHERE IPI.BDCODCSTIPISAI = P.BDCODCSTIPISAI)
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDCODCSTIPISAI > 7
      AND P.BDORIGEMPROD = 1; -- Para não trocar duas vezes os mesmos produtos (tanto entrada como saída, dava problema)

      /*IPI - Saída*/
      UPDATE TMP_TCADPRO_TEMP P SET P.BDCODCSTIPISAI = (SELECT FIRST 1 IPI.BDCODCSTIPISAI FROM VEF_BASE_TCSTIPICORENTSAI IPI WHERE IPI.BDCODCSTIPIENT = P.BDCODCSTIPIENT)
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDCODCSTIPIENT <= 7
      AND P.BDORIGEMPROD = 0; -- Para não trocar duas vezes os mesmos produtos (tanto entrada como saída, dava problema)
        
      /*COFINS - Entrada*/
      UPDATE TMP_TCADPRO_TEMP P SET P.BDCODCSTCOFENT = (SELECT FIRST 1 COF.BDCODCSTCOFENT FROM VEF_BASE_TCSTCOFCORENTSAI COF WHERE COF.BDCODCSTCOFSAI = P.BDCODCSTCOFSAI)
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDCODCSTCOFSAI < 49
      AND P.BDORIGEMPROD = 1; -- Para não trocar duas vezes os mesmos produtos (tanto entrada como saída, dava problema)

      /*COFINS - Saída*/
      UPDATE TMP_TCADPRO_TEMP P SET P.BDCODCSTCOFSAI = (SELECT FIRST 1 COF.BDCODCSTCOFSAI FROM VEF_BASE_TCSTCOFCORENTSAI COF WHERE COF.BDCODCSTCOFENT = P.BDCODCSTCOFENT)
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDCODCSTCOFENT >= 50
      AND P.BDORIGEMPROD = 0; -- Para não trocar duas vezes os mesmos produtos (tanto entrada como saída, dava problema)
        
      /*PIS - Entrada*/
      UPDATE TMP_TCADPRO_TEMP P SET P.BDCODCSTPISENT = (SELECT FIRST 1 PIS.BDCODCSTPISENT FROM VEF_BASE_TCSTPISCORENTSAI PIS WHERE PIS.BDCODCSTPISSAI = P.BDCODCSTPISSAI)
      WHERE P.BDSESSAO = :PRSESSAO
      AND ((P.BDCODCSTPISSAI <= 49) OR (P.BDCODCSTPISSAI = 99))
      AND P.BDORIGEMPROD = 1; -- Para não trocar duas vezes os mesmos produtos (tanto entrada como saída, dava problema)

      /*PIS - Saída*/
      UPDATE TMP_TCADPRO_TEMP P SET P.BDCODCSTPISSAI = (SELECT FIRST 1 PIS.BDCODCSTPISSAI FROM VEF_BASE_TCSTPISCORENTSAI PIS WHERE PIS.BDCODCSTPISENT = P.BDCODCSTPISENT)
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDCODCSTPISENT >= 50
      AND P.BDORIGEMPROD = 0; -- Para não trocar duas vezes os mesmos produtos (tanto entrada como saída, dava problema)
    END
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_CST_PROD','2');

  UPDATE TMP_TCADPRO TP SET TP.BDCODCSTIPIENT = (SELECT FIRST 1 P.BDCODCSTIPIENT FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :PRSESSAO AND P.BDCODENTRADA = TP.BDCODENTRADA AND P.BDCODSAIDA = TP.BDCODSAIDA),
                            TP.BDCODCSTIPISAI = (SELECT FIRST 1 P.BDCODCSTIPISAI FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :PRSESSAO AND P.BDCODENTRADA = TP.BDCODENTRADA AND P.BDCODSAIDA = TP.BDCODSAIDA),
                            TP.BDCODCSTCOFENT = (SELECT FIRST 1 P.BDCODCSTCOFENT FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :PRSESSAO AND P.BDCODENTRADA = TP.BDCODENTRADA AND P.BDCODSAIDA = TP.BDCODSAIDA),
                            TP.BDCODCSTCOFSAI = (SELECT FIRST 1 P.BDCODCSTCOFSAI FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :PRSESSAO AND P.BDCODENTRADA = TP.BDCODENTRADA AND P.BDCODSAIDA = TP.BDCODSAIDA),
                            TP.BDCODCSTPISENT = (SELECT FIRST 1 P.BDCODCSTPISENT FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :PRSESSAO AND P.BDCODENTRADA = TP.BDCODENTRADA AND P.BDCODSAIDA = TP.BDCODSAIDA),
                            TP.BDCODCSTPISSAI = (SELECT FIRST 1 P.BDCODCSTPISSAI FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :PRSESSAO AND P.BDCODENTRADA = TP.BDCODENTRADA AND P.BDCODSAIDA = TP.BDCODSAIDA)
  WHERE TP.BDSESSAO = :PRSESSAO;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_CST_PROD','3');
END^

CREATE OR ALTER PROCEDURE SP_GERACODIGOS_CADPROD (
    PRSESSAO INTEGER,
    PRULTIMOCOD INTEGER)
AS

DECLARE VARIABLE FDESCRICAO VARCHAR(200);
DECLARE VARIABLE FCODSAIDA VARCHAR(60) COLLATE WIN_PTBR;
DECLARE VARIABLE FCODENTRADA VARCHAR(60) COLLATE WIN_PTBR;
DECLARE VARIABLE FORIGEMPROD INTEGER;
DECLARE VARIABLE FCODTER INTEGER;
BEGIN
  FOR SELECT P.bdCODSAIDA, P.BDCODENTRADA, P.BDDESCPROD, P.BDCODTERLAYOUT, P.BDORIGEMPROD
      FROM TMP_TCADPRO_TEMP P
      WHERE (P.BDSESSAO = :prsessao) AND ((P.BDEDITCHAVE = 0) OR (P.BDEDITCHAVE IS NULL))
      INTO :FCODSAIDA, :FCODENTRADA, :FDESCRICAO, :FCODTER, :FORIGEMPROD  DO
    BEGIN
      IF (:FORIGEMPROD = 1) THEN
        BEGIN
          UPDATE TMP_TCADPRO P SET P.BDCODPROD = :PRULTIMOCOD WHERE P.bdSESSAO = :PRSESSAO AND P.bdCODSAIDA = :FCODSAIDA AND P.BDCODENTRADA = :FCODENTRADA;
          UPDATE TMP_TCADPRO_TEMP P SET P.BDCODPROD = :PRULTIMOCOD WHERE P.bdSESSAO = :PRSESSAO AND P.bdCODSAIDA = :FCODSAIDA AND P.BDCODENTRADA = :FCODENTRADA;
        END
      ELSE
        BEGIN
          UPDATE TMP_TCADPRO P SET P.BDCODPROD = :PRULTIMOCOD
          WHERE P.bdSESSAO = :PRSESSAO
          AND P.bdCODSAIDA = :FCODSAIDA
          AND P.BDCODENTRADA = :FCODENTRADA
          AND P.BDDESCPROD = :FDESCRICAO
          AND P.BDCODTERLAYOUT = :FCODTER;
          UPDATE TMP_TCADPRO_TEMP P SET P.BDCODPROD = :PRULTIMOCOD
          WHERE P.bdSESSAO = :PRSESSAO
          AND P.bdCODSAIDA = :FCODSAIDA
          AND P.BDCODENTRADA = :FCODENTRADA
          AND P.BDDESCPROD = :FDESCRICAO
          AND P.BDCODTERLAYOUT = :FCODTER;
          UPDATE TMP_TCADPRO_PART P SET P.BDCODPROD = :PRULTIMOCOD
          WHERE (P.bdSESSAO = :PRSESSAO)
          AND P.BDCODENTRADA = :FCODENTRADA
          AND P.BDDESCPRODBUSCA = :FDESCRICAO
          AND P.BDCODTER = :FCODTER;
        END
      PRULTIMOCOD = :PRULTIMOCOD + 1;
      FCODSAIDA   = '';
      fcodentrada = '';
    END
  UPDATE TMP_TCADPRO      SET BDEDITCHAVE = BDCODPROD WHERE (bdSESSAO = :prsessao) AND ((BDEDITCHAVE = 0) OR (BDEDITCHAVE IS NULL));
  UPDATE TMP_TCADPRO_TEMP SET BDEDITCHAVE = BDCODPROD WHERE (bdSESSAO = :prsessao) AND ((BDEDITCHAVE = 0) OR (BDEDITCHAVE IS NULL));
  UPDATE TMP_TCADPRO_PART SET BDEDITCHAVE = BDCODPROD WHERE (bdSESSAO = :prsessao) AND ((BDEDITCHAVE = 0) OR (BDEDITCHAVE IS NULL));
  /*Define a ordem para o produto por participante, para que fique sincronizado a TMP_TCADPRO_PART e a TCADPRO_PART*/   
  SETORDEMSEQUENCIAL_STR(0);
  UPDATE TMP_TCADPRO_TEMP PP
  SET PP.BDORDEM = (
                    COALESCE((SELECT MAX(P.BDORDEM)+GETORDEMSEQUENCIAL_STR(:prsessao||'_'||PP.BDEDITCHAVE, 0) FROM TCADPRO_PART P
                              WHERE P.BDCODPROD = PP.BDCODPROD), GETORDEMSEQUENCIAL_STR(:prsessao||'_'||PP.BDEDITCHAVE, 0))
                   )
  WHERE PP.BDSESSAO = :PRSESSAO;
--  UPDATE TMP_TCADPRO_PART PP
--  SET PP.BDORDEM = (
--                    COALESCE((SELECT MAX(P.BDORDEM)+GETORDEMSEQUENCIAL_STR(:prsessao||'_'||PP.BDEDITCHAVE, 0) FROM TMP_TCADPRO_PART P
--                              WHERE P.BDEDITCHAVE = PP.BDEDITCHAVE), GETORDEMSEQUENCIAL_STR(:prsessao||'_'||PP.BDEDITCHAVE, 0))
--                   )
--  WHERE PP.BDSESSAO = :PRSESSAO;
  --WHERE PP.BDSEQ_PART IS NOT NULL
  --AND PP.BDORDEM IS NULL;
                                                                 
--  SETORDEMSEQUENCIAL_STR(0);       
--  UPDATE TMP_TCADPRO_TEMP TP
--  SET TP.BDORDEM = Coalesce((SELECT (MAX(PP.BDORDEM) + GETORDEMSEQUENCIAL_STR(:prsessao||'_'||TP.BDEDITCHAVE, 0))
--                              FROM TMP_TCADPRO_PART PP
--                              WHERE PP.BDEDITCHAVE = TP.BDEDITCHAVE
--                              --AND PP.BDCODENTRADA = TP.BDCODENTRADA
--                              --AND PP.BDDESCPRODBUSCA = TP.BDDESCORIGINAL
--                              --AND PP.BDCODTER = TP.BDCODTERLAYOUT
--                    ), GETORDEMSEQUENCIAL_STR(:prsessao||'_'||TP.BDEDITCHAVE, 0)) -- #121823 - Estava tentado inserir com ordem nula
--  WHERE TP.BDSESSAO = :PRSESSAO and
--        TP.BDORDEM IS NULL and
--        TP.BDORIGEMPROD = 0;   
--                              
  SETORDEMSEQUENCIAL_STR(0);    
--  UPDATE TMP_TCADPRO_TEMP TP
--  SET TP.BDORDEM = Coalesce((SELECT FIRST 1 PP.BDORDEM
--                              FROM TMP_TCADPRO_PART PP
--                              WHERE PP.BDEDITCHAVE = TP.BDEDITCHAVE
--                              AND PP.BDCODENTRADA = TP.BDCODENTRADA
--                    AND PP.BDDESCPRODBUSCA = TP.BDDESCORIGINAL
--                              AND PP.BDCODTER = TP.BDCODTERLAYOUT
--                    ORDER BY PP.BDORDEM DESC), Coalesce((SELECT MAX(P.BDORDEM) + 1
--                                                         FROM TMP_TCADPRO_TEMP P
--                                                         WHERE P.BDEDITCHAVE = TP.BDEDITCHAVE),
--                                                            Coalesce((SELECT MAX(P.BDORDEM) + 1
--                                                            FROM TCADPRO_PART P
--                                                            WHERE P.BDCODPROD = TP.BDEDITCHAVE),1))) -- #121823 - Estava tentado inserir com ordem nula
--  WHERE TP.BDSESSAO = :PRSESSAO and
--        TP.BDORDEM IS NULL and
--        TP.BDORIGEMPROD = 0;
END^

CREATE OR ALTER PROCEDURE GET_RECONTABILIZA RETURNS(BDRECONTABILIZA DM_BOOLEAN)
 AS
BEGIN
  /* Procedure Text */
  FOR SELECT UPPER(TRIM(rdb$get_context('USER_SESSION', 'W_RECONTABILIZA'))) FROM rdb$database
  INTO
    :BDRECONTABILIZA
  DO
  SUSPEND;
END
^

create or alter procedure GET_VENCIMENTO (
    PRDATA date,
    PRDIA integer,
    PRANTECIPA varchar(5),
    PRVENCE integer,
    PRAPURACAO integer,
    PRALERTA integer,
    PRCIDADE integer,
    PRMES integer = 0,
    PRCODEMP integer = 0)
returns (
    BDDATA date)
as
declare variable WDIA integer;
declare variable WMES integer;
declare variable WANO integer;
declare variable WDATA date;
declare variable WCOUNT integer;
declare variable WCOUNTX integer;
BEGIN
  /*
  PRDIA = dia de vencimento do mês
  PRANTECIPA = 1 - antecipa domingos e feriados
  PRVENCE = 0 - No mês do movimento
            1 - No mês seguinte
            2 - No mês subsequente
            3 - Dias úteis
  PRAPURACAO =  0 - Semanal
                1 - 1º Decendio
                2 - 2º Decendio
                3 - 3º Decendio
                4 - 1ª Quinzena
                5 - 2ª Quinzena
                6 - Mensal
                7 - Trimestral
                8 - Trimestral parcelado
                9 - Trimestral antecipado
               10 - Anual
               11 - Indefinido
  */


  IF (PRDATA IS NULL) THEN
     EXIT;

  /* inicializa variáveis */
  IF (prvence <> 3) THEN
     wdia = prdia;
  ELSE
     wdia = SUBSTRING(prdata FROM 9 FOR 2);
  IF ((prdia = 0) OR (prdia IS NULL)) THEN
     wdia = 1;
  IF ((prmes IS NOT NULL) AND (prmes <> 0) AND (PRAPURACAO = 10)) THEN
     wmes = prmes;
  ELSE
     wmes = SUBSTRING(prdata FROM 6 FOR 2);
  wano = SUBSTRING(prdata FROM 1 FOR 4);

  IF (prvence = 4) THEN
     BEGIN
       SELECT bddatainiativemp FROM tempresas WHERE bdcodemp = :prcodemp INTO :wdata;
--       1991-02-27
       wdia = SUBSTRING(wdata FROM 9 FOR 2);
       wmes = SUBSTRING(wdata FROM 6 FOR 2);
     END
  ELSE
     wdata = prdata;

  /* apuração */
  IF (prapuracao =  0) THEN -- 0 - Semanal
     BEGIN
       wdata = prdata;
     END
  ELSE
  IF (prapuracao =  1) THEN -- 1 - 1º Decendio
     BEGIN
       wdia = 11;
     END
  ELSE
  IF (prapuracao =  2) THEN -- 2 - 2º Decendio
     BEGIN
       wdia = 21;
     END
  ELSE
  IF (prapuracao =  3) THEN -- 3 - 3º Decendio
     BEGIN
       wdia = 31; -- não há necessidade de verificar mês e ano bisexto, pois isso acontecerá no processo "add dia"
     END
  ELSE
  IF (prapuracao =  4) THEN -- 4 - 1ª Quinzena
     BEGIN
       IF (prdia IS NULL) THEN
          wdia = SUBSTRING(prdata FROM 9 FOR 2);
       ELSE
          wdia = prdia;
     END
  ELSE
  IF (prapuracao =  5) THEN -- 5 - 2ª Quinzena
     BEGIN
       IF (prdia IS NULL) THEN
          wdia = SUBSTRING(prdata FROM 9 FOR 2);
       ELSE
          wdia = prdia;
     END
  ELSE
  IF (prapuracao =  6) THEN -- 6 - Mensal
     BEGIN
       wdata = prdata;
     END
  ELSE
  --Leonardo Pereira - sol. 20777 - prvence 0 e 3 não é tratado mais a frente, apenas prvence 1 e 2.
  IF (prapuracao =  7) THEN -- 7 - Trimestral
     BEGIN
       IF (wmes IN (1,2,3)) THEN
          if (prvence = 3) then
              wmes = 4;
          ELSE
            wmes = 3;
       ELSE
       IF (wmes IN (4,5,6)) THEN
          if (prvence = 3) then
             wmes = 7;
          ELSE
            wmes = 6;
       ELSE
       IF (wmes IN (7,8,9)) THEN
          if (prvence = 3) then
              wmes = 10;
          ELSE
            wmes = 9;
       ELSE
       IF (wmes IN (10,11,12)) THEN
          BEGIN
            if (prvence = 3) then
               BEGIN
                 wmes = 1;
                 wano = wano+1;
               END
             ELSE
               wmes = 12;
          END
     END
  ELSE
  IF (prapuracao =  8) THEN -- 8 - Trimestral parcelado
     BEGIN
       IF (wmes IN (1,2,3)) THEN
          wmes = 4;
       ELSE
       IF (wmes IN (4,5,6)) THEN
          wmes = 7;
       ELSE
       IF (wmes IN (7,8,9)) THEN
          wmes = 10;
       ELSE
       IF (wmes IN (10,11,12)) THEN
          BEGIN
            wmes = 1;
            wano = wano + 1;
          END
     END
  ELSE
  IF (prapuracao =  9) THEN -- 9 - Trimestral antecipado
     BEGIN
/* gilberto - 30/10/2014 - retirado pois incrementa 2 meses quando opção mês seguinte estiver habilitada
       if (wmes < 12) then
          wmes = wmes + 1;
       else
          begin
            wmes = 1;
            wano = wano + 1;
          end
*/
     END
  ELSE
  IF (prapuracao = 10) THEN -- 10 - Anual
     BEGIN
       if (prvence in (0,1,2)) then
       begin
         -- Gilberto - 15/07/2020 - já retorna com o dia a mês correto, para mês seguinte e subsequente é tratado abaixo
       end
       else
       IF (prvence <> 4) THEN
          BEGIN
            wdia = 31;
            wmes = 12;
          END
     END
  ELSE
  IF (prapuracao = 11) THEN -- 11 - Indefinido
     BEGIN
       wdata = prdata;
     END

  /* add mês e ano */
  IF (prvence = 1) THEN
     BEGIN
       wmes = wmes + prvence;
       IF (wmes > 12) THEN
          BEGIN
            wmes = 1;
            wano = wano + 1;
          END
     END
  ELSE
  IF (prvence = 2) THEN
     BEGIN
       wmes = wmes + prvence;
       IF (wmes > 12) THEN
          BEGIN
            wmes = wmes - 12;
            wano = wano + 1;
          END
     END

  /* add dia */
  IF (wmes = 2) THEN
     BEGIN
       IF ((wano / 4 * 4) = wano) THEN
          BEGIN
            IF (wdia > 29) THEN
               wdia = 29;
          END
       ELSE
          BEGIN
            IF (wdia > 28) THEN
               wdia = 28;
          END
     END
  ELSE
  IF (wmes IN (1,3,5,7,8,10,12)) THEN
     BEGIN
       IF (wdia > 31) THEN
          wdia = 31;
     END
  ELSE
  IF (wmes IN (4,6,9,11)) THEN
     BEGIN
       IF (wdia > 30) THEN
          wdia = 30;
     END

  /* monta data atual */
  wdata = CAST(wano||'/'||wmes||'/'||wdia AS DATE);

  /* dias úteis */
  IF (prvence = 3) THEN
     BEGIN
       wcount = 0;
       WHILE (wcount < prdia) DO
         BEGIN
           wdata = addday(wdata, 1);
           wcount = wcount + 1;

           SELECT FIRST 1 fer.bdcodferi
           FROM tferiadosnovo fer
           WHERE ((fer.bddataferi = :wdata)
           OR (fer.bdmesdiaferi = CAST(SUBSTRING(:wdata FROM 9 FOR 2)||SUBSTRING(:wdata FROM 6 FOR 2) AS VARCHAR(4))))
           AND fer.bdcodcid IS NULL
           INTO :wdia;
           IF ((wdia IS NOT NULL) AND (wDia <> 0)) THEN
              wdata = addday(wdata, 1);

           IF ((UPPER(sdow(wdata)) = 'SÁB') OR
               (UPPER(sdow(wdata)) = 'SUN')) THEN
              wdata = addday(wdata, 1);

           IF ((UPPER(sdow(wdata)) = 'DOM') OR
               (UPPER(sdow(wdata)) = 'WES')) THEN
              wdata = addday(wdata, 1);
         END
     END

  /* antecipa vencimento */
  IF ((UPPER(prantecipa) = 'TRUE') OR (UPPER(prantecipa) = '1')) THEN
     BEGIN
       IF (((prvence = 3) AND (wdata - prdata > 0)) OR (prvence <> 3))  THEN
          BEGIN
            wcount = 0;
            wDia = 0;
            WHILE ((wcount = 0) OR
                   (((wdia IS NOT NULL) AND (wdia <> 0)) OR
                   ((UPPER(sdow(wdata)) = 'DOM') OR (UPPER(sdow(wdata)) = 'WES')) OR
                   ((UPPER(sdow(wdata)) = 'SÁB') OR (UPPER(sdow(wdata)) = 'SUN')))) DO
              BEGIN
                wdia = 0;
                SELECT FIRST 1 fer.bdcodferi
                FROM tferiadosnovo fer
                WHERE (fer.bddataferi = :wdata)
--                or (fer.bdmesdiaferi = cast(substring(:wdata from 9 for 2)||substring(:wdata from 6 for 2) as varchar(4))))
                AND fer.bdcodcid IS NULL
                INTO :wdia;
                IF (((wdia IS NOT NULL) AND (wdia <> 0)) OR
                   ((UPPER(sdow(wdata)) = 'DOM') OR (UPPER(sdow(wdata)) = 'WES')) OR
                   ((UPPER(sdow(wdata)) = 'SÁB') OR (UPPER(sdow(wdata)) = 'SUN'))) THEN
                   wcount = 0;
                ELSE
                   wcount = 1;
     
                IF (wcount = 0) THEN
                   wdata = addday(wdata, -1);
              END
          END
     END
  ELSE
  /* posterga vencimento */
     BEGIN
       IF (((prvence = 3) AND (wdata - prdata > 0)) OR (prvence <> 3))  THEN
          BEGIN
            wcount = 0;
            wDia = 0;
            WHILE ((wcount = 0) OR
                   (((wDia IS NOT NULL) AND (wdia <> 0)) OR
                   ((UPPER(sdow(wdata)) = 'DOM') OR (UPPER(sdow(wdata)) = 'WES')) OR
                   ((UPPER(sdow(wdata)) = 'SÁB') OR (UPPER(sdow(wdata)) = 'SUN')))) DO
              BEGIN
                wdia = 0;
                SELECT FIRST 1 fer.bdcodferi
                FROM tferiadosnovo fer
                WHERE (fer.bddataferi = :wdata)
--                or (fer.bdmesdiaferi = cast(substring(:wdata from 9 for 2)||substring(:wdata from 6 for 2) as varchar(4))))
                AND fer.bdcodcid IS NULL
                INTO :wdia;
                IF (((wdia IS NOT NULL) AND (wdia <> 0)) OR
                   ((UPPER(sdow(wdata)) = 'DOM') OR (UPPER(sdow(wdata)) = 'WES')) OR
                   ((UPPER(sdow(wdata)) = 'SÁB') OR (UPPER(sdow(wdata)) = 'SUN'))) THEN
                   wcount = 0;
                ELSE
                   wcount = 1;
     
                IF (wcount = 0) THEN
                   wdata = addday(wdata, 1);
              END
          END
     END

  /* alreta */
  IF ((pralerta IS NOT NULL) AND (pralerta > 0)) THEN
     BEGIN
       wcount = 1;
       wcountx = 0;
       wDia = 0;
       WHILE ((wcount <= pralerta) OR
              ((((wDia IS NOT NULL) AND (wdia <> 0)) OR
               ((UPPER(sdow(wdata)) = 'DOM') OR (UPPER(sdow(wdata)) = 'WES')) OR
               ((UPPER(sdow(wdata)) = 'SÁB') OR (UPPER(sdow(wdata)) = 'SUN'))))) DO
         BEGIN
           wdia = 0;
           SELECT FIRST 1 fer.bdcodferi
           FROM tferiadosnovo fer
           WHERE (fer.bddataferi = :wdata)
--           or (fer.bdmesdiaferi = cast(substring(:wdata from 9 for 2)||substring(:wdata from 6 for 2) as varchar(4))))
           AND fer.bdcodcid IS NULL
           INTO :wdia;
           IF (((wdia IS NOT NULL) AND (wdia <> 0)) OR
              ((UPPER(sdow(wdata)) = 'DOM') OR (UPPER(sdow(wdata)) = 'WES')) OR
              ((UPPER(sdow(wdata)) = 'SÁB') OR (UPPER(sdow(wdata)) = 'SUN'))) THEN
              wdata = addday(wdata, -1);
           ELSE
              wcount = wcount + 1;

           wdata = addday(wdata, -1);
         END
     END

--  bddata = wdata;-- gilberto - alterado para não gerar tarefa em meses anteriores a execução da geração de tarefas automáticas
/* gilberto - 04/04/2016
  IF ((SUBSTRING(wdata FROM 1 FOR 4)||SUBSTRING(wdata FROM 6 FOR 2)) < (SUBSTRING(prdata FROM 1 FOR 4)||SUBSTRING(prdata FROM 6 FOR 2))) THEN
     bddata = addyear(wdata, 1);
  ELSE*/
     bddata = wdata;
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE GETPRIVILEGIOSEMPRESAS(PRCODEMP INTEGER,
PRPRIVILEGIO VARCHAR(200))
 RETURNS(BDCODEMP INTEGER,
BDCODGRUPO INTEGER,
BDCODUSU INTEGER,
BDITEMPRIV VARCHAR(200))
 AS
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(2000);
DECLARE VARIABLE WCOUNTGRP INTEGER;
DECLARE VARIABLE WCOUNTUSU INTEGER;
DECLARE VARIABLE WSQLX VARCHAR(2000);
BEGIN
  -- verifica se o usuario pertence aos grupos 1 ou 2
  SELECT COUNT(bdcodgrupo) FROM tgrupousuario_usuario
  WHERE bdcodusu = (SELECT bdcodusu FROM sp_get_usuario)
  AND bdcodgrupo IN (1,2)
  INTO :wcount;
  IF (wcount > 0) THEN
     BEGIN
       -- carrega todas as empresas e privilegios
       wsql = 'select bdcodemp from tempresas ';
       IF ((prcodemp <> 0) OR (prcodemp IS NOT NULL)) THEN
          wsql = wsql||'where bdcodemp = '||prcodemp;
       wsql = wsql||' order by bdcodemp';
       FOR EXECUTE STATEMENT wsql INTO :bdcodemp DO
           BEGIN
             -- retorna todos os privilegios do ususario se não houver empresa configurada
             wsqlx = 'select distinct 1 as bdcodgrupo, (select bdcodusu from sp_get_usuario) bdcodusu, tpriv.bditempriv ';
             wsqlx = wsqlx||'from tprivilegio_grupousuario tpriv ';
             IF ((prprivilegio IS NOT NULL) AND (TRIM(prprivilegio) <> '')) THEN
                wsqlx = wsqlx||'where upper(tpriv.bditempriv) containing upper('''||TRIM(prprivilegio)||''') ';
             wsqlx = wsqlx||'order by tpriv.bditempriv ';
             FOR EXECUTE STATEMENT wsqlx INTO :bdcodgrupo, :bdcodusu, :bditempriv DO
                 SUSPEND;
           END
     END
  ELSE
     BEGIN
       -- verifica se há empresas no grupo de usuários
       wsql = 'select count(bdcodemp) from tempresa_grupousuario tegu ';
       wsql = wsql||'inner join tgrupousuario_usuario tgrp on(tgrp.bdcodgrupo = tegu.bdcodgrupo and tgrp.bdcodusu = (select bdcodusu from sp_get_usuario)) ';
       EXECUTE STATEMENT wsql INTO :wcountgrp;
       -- verifica as empresas por usuário
       wsql = 'select count(bdcodemp) from tempresa_usuario where bdcodusu = (select bdcodusu from sp_get_usuario) ';
       EXECUTE STATEMENT wsql INTO :wcountusu;

       -- verifica se tem empresa configurada para usuario ou grupo de usuario
       wsql = 'select count(temp.bdcodemp) ';--  select temp.bdcodemp, temp.bdcodgrupo, tgrp.bdcodusu
       wsql = wsql||'from tempresa_grupousuario temp ';
       wsql = wsql||'inner join tgrupousuario_usuario tgrp on (tgrp.bdcodgrupo = temp.bdcodgrupo and tgrp.bdcodusu = (select x.bdcodusu from sp_get_usuario x)) ';
       IF (wcountusu > 0) THEN
          wsql = wsql||'inner join tempresa_usuario teu on (teu.bdcodemp = temp.bdcodemp and teu.bdcodusu = tgrp.bdcodusu) ';
       IF ((prcodemp <> 0) OR (prcodemp IS NOT NULL)) THEN
          wsql = wsql||'and temp.bdcodemp = '||prcodemp;
       EXECUTE STATEMENT wsql INTO :wcount;
     
       IF (wcount = 0) THEN
          BEGIN
/*            -- verifica se ha grupos sem escritorio
            select count(tgrp.bdcodgrupo) from tgrupousuario tgrp
            inner join tgrupousuario_usuario tusu on (tusu.bdcodgrupo = tgrp.bdcodgrupo and tusu.bdcodusu = (select bdcodusu from sp_get_usuario))
            where tgrp.bdcodesc is null
            into :wcount;
            
            if (wcount > 0) then
               begin
                 -- retorna todas as empresas
                 wsql = 'select distinct temp.bdcodemp from tempresas temp ';
                 wsql = wsql||'inner join tgrupousuario_usuario tusu on (tusu.bdcodusu = (select bdcodusu from sp_get_usuario)) ';
                 wsql = wsql||'inner join tgrupousuario tgrp on (tgrp.bdcodgrupo = tusu.bdcodgrupo and tgrp.bdcodesc = temp.bdcodesc) ';
                 if (wcountgrp > 0) then
                    wsql = wsql||'inner join tempresa_grupousuario tegu on (tegu.bdcodemp = temp.bdcodemp and tegu.bdcodgrupo =  tgrp.bdcodgrupo) ';
                 if (wcountusu > 0) then
                    wsql = wsql||'inner join tempresa_usuario teu on (teu.bdcodemp = temp.bdcodemp and teu.bdcodusu = tusu.bdcodusu) ';
                 if ((prcodemp <> 0) or (prcodemp is not null)) then
                    wsql = wsql||'where bdcodemp = '||prcodemp;
                 wsql = wsql||' order by temp.bdcodemp';
                 for execute statement wsql into :bdcodemp do
                     begin
                       -- retorna todos os privilegios do ususario se não houver empresa configurada
                       wsqlx = 'select tpriv.bdcodgrupo, tgrp.bdcodusu, tpriv.bditempriv ';
                       wsqlx = wsqlx||'from tprivilegio_grupousuario tpriv ';
                       wsqlx = wsqlx||'inner join tgrupousuario_usuario tgrp on (tgrp.bdcodgrupo = tpriv.bdcodgrupo and tgrp.bdcodusu = (select bdcodusu from sp_get_usuario)) ';
                       if ((prprivilegio is not null) and (trim(prprivilegio) <> '')) then
                          wsqlx = wsqlx||'where upper(tpriv.bditempriv) containing upper('''||trim(prprivilegio)||''') ';
                       for execute statement wsqlx into :bdcodgrupo, :bdcodusu, :bditempriv do
                           suspend;
                     end
               end
            else*/
               BEGIN
                 -- retorna empresas por escritorio
                 wsql = 'select distinct temp.bdcodemp from tempresas temp ';
                 IF (wcountgrp > 0) THEN
                    BEGIN
                      wsql = wsql||'inner join tgrupousuario_usuario tusu on (tusu.bdcodusu = (select bdcodusu from sp_get_usuario)) ';
                      wsql = wsql||'inner join tgrupousuario tgrp on (tgrp.bdcodgrupo = tusu.bdcodgrupo and tgrp.bdcodesc = temp.bdcodesc) ';
                      wsql = wsql||'inner join tempresa_grupousuario tegu on (tegu.bdcodemp = temp.bdcodemp and tegu.bdcodgrupo =  tgrp.bdcodgrupo) ';
                    END
                 IF (wcountusu > 0) THEN
                    wsql = wsql||'inner join tempresa_usuario teu on (teu.bdcodemp = temp.bdcodemp and teu.bdcodusu = (select bdcodusu from sp_get_usuario)) ';
                 IF ((prcodemp <> 0) OR (prcodemp IS NOT NULL)) THEN
                    wsql = wsql||' where temp.bdcodemp = '||prcodemp;
                 wsql = wsql||' order by temp.bdcodemp';
                 FOR EXECUTE STATEMENT wsql INTO :bdcodemp DO
                     BEGIN
                       -- retorna todos os privilegios do ususario se não houver empresa configurada
                       wsqlx = 'select tpriv.bdcodgrupo, tgrp.bdcodusu, tpriv.bditempriv ';
                       wsqlx = wsqlx||'from tprivilegio_grupousuario tpriv ';
                       wsqlx = wsqlx||'inner join tgrupousuario_usuario tgrp on (tgrp.bdcodgrupo = tpriv.bdcodgrupo and tgrp.bdcodusu = (select bdcodusu from sp_get_usuario)) ';
                       IF ((prprivilegio IS NOT NULL) AND (TRIM(prprivilegio) <> '')) THEN
                          wsqlx = wsqlx||'where upper(tpriv.bditempriv) containing upper('''||TRIM(prprivilegio)||''') ';
                       wsqlx = wsqlx||'order by tpriv.bdcodgrupo, tpriv.bditempriv ';
                       FOR EXECUTE STATEMENT wsqlx INTO :bdcodgrupo, :bdcodusu, :bditempriv DO
                           SUSPEND;
                     END
               END
          END
       ELSE
          BEGIN
            -- retorna privilegios do usuario com empresa configurada
            wsql = 'select temp.bdcodemp, temp.bdcodgrupo, tgrp.bdcodusu, tpriv.bditempriv ';
            wsql = wsql||'from tempresa_grupousuario temp ';
            wsql = wsql||'inner join tgrupousuario_usuario tgrp on (tgrp.bdcodgrupo = temp.bdcodgrupo and tgrp.bdcodusu = (select x.bdcodusu from sp_get_usuario x)) ';

            IF ((prprivilegio IS NOT NULL) AND (TRIM(prprivilegio) <> '')) THEN
               wsql = wsql||'inner join tprivilegio_grupousuario tpriv on (tpriv.bdcodgrupo = tgrp.bdcodgrupo and (upper(tpriv.bditempriv) containing upper('''||TRIM(prprivilegio)||'''))) ';
            ELSE
               wsql = wsql||'inner join tprivilegio_grupousuario tpriv on (tpriv.bdcodgrupo = tgrp.bdcodgrupo ) ';
            IF (wcountusu > 0) THEN
               wsql = wsql||'inner join tempresa_usuario tusu on (tusu.bdcodemp = temp.bdcodemp and tusu.bdcodusu = tgrp.bdcodusu) ';
            IF ((prcodemp <> 0) OR (prcodemp IS NOT NULL)) THEN
               wsql = wsql||'where temp.bdcodemp = '||prcodemp;
            FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodgrupo, :bdcodusu, :bditempriv DO
               SUSPEND;
          END
     END
END
^

CREATE OR ALTER PROCEDURE MAXSCI(PRCAMPO VARCHAR(1024),
PRORDEM VARCHAR(1024),
PRCONDICAO VARCHAR(1024),
PRTABELA VARCHAR(1024))
 RETURNS(BDRESULT INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE MMDDAAAA(PRDATA DATE)
 RETURNS(BDMMDDAAAA VARCHAR(10))
 AS
BEGIN
  /* Procedure Text */
  BDMMDDAAAA =  SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
                SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
                SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 1 FOR 4);

  SUSPEND;
END
^

CREATE OR ALTER PROCEDURE POS(SUBSTR VARCHAR(32000),
STR VARCHAR(32000))
 RETURNS(POS INTEGER)
 AS
DECLARE VARIABLE CONTA INTEGER;
BEGIN
  IF (SubStr IS NULL OR Str IS NULL)
  THEN BEGIN Pos = NULL; EXIT; END

  conta = 1;
  pos = 0;

  WHILE (conta <= strlen(str)) DO
    BEGIN

      IF (SUBSTRING(str FROM conta FOR strlen(substr)) = substr) THEN
         BEGIN
           pos = conta;
           BREAK;
         END

      conta = conta + 1;

    END

  SUSPEND;

/*
  SubStr2 = SubStr || '%';
  Tmp = '';
  Pos = 1;
  WHILE (Str NOT LIKE SubStr2 AND Str NOT LIKE Tmp) DO BEGIN
    SubStr2 = '_' || SubStr2;
    Tmp = Tmp || '_';
    Pos = Pos + 1;
  END


  IF (Str LIKE Tmp) THEN Pos = 0;

  suspend;
*/

END
^

CREATE OR ALTER PROCEDURE PREENCHE_CLASSIFICACAOPRODUTO(PRSTRING VARCHAR(1000),
PRQTD INTEGER,
PRADICIONA VARCHAR(1000))
 RETURNS(BDRETORNO VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE PREENCHE_DIREITA(PRSTRING VARCHAR(1000),
PRQTD INTEGER,
PRADICIONA VARCHAR(1000))
 RETURNS(BDRETORNO VARCHAR(1000))
 AS
DECLARE VARIABLE waux INTEGER;
BEGIN
  /* Procedure Text */
  waux = CHARACTER_LENGTH(:prstring);
  IF (CHARACTER_LENGTH(:prstring) > prqtd) THEN
     prstring = SUBSTRING(prstring FROM 1 FOR prqtd);
  WHILE (waux < prqtd) DO
    BEGIN
      prstring = prstring||pradiciona;

      waux = CHARACTER_LENGTH(:prstring);
    END

  bdretorno = prstring;
  SUSPEND;
END
^

CREATE OR ALTER PROCEDURE PREENCHE_ESQUERDA(PRSTRING VARCHAR(1000),
PRQTD INTEGER,
PRADICIONA VARCHAR(1000))
 RETURNS(BDRETORNO VARCHAR(1000))
 AS
DECLARE VARIABLE waux INTEGER;
BEGIN
  /* Procedure Text */
  waux = CHARACTER_LENGTH(:prstring);
  IF (CHARACTER_LENGTH(:prstring) > prqtd) THEN
     prstring = SUBSTRING(prstring FROM 1 FOR prqtd);
  WHILE (waux < prqtd) DO
    BEGIN
      prstring = pradiciona||prstring;

      waux = CHARACTER_LENGTH(:prstring);
    END

  bdretorno = prstring;
  SUSPEND;
END
^

CREATE OR ALTER PROCEDURE REF_SEGUINTE(PRMES SMALLINT,
PRANO INTEGER)
 RETURNS(MES SMALLINT,
ANO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE RETIRA_ACENTO(PRSTRING VARCHAR(1000))
 RETURNS(BDRETORNO VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE RETIRA_CHAR_ESPECIAL(PRSTRING VARCHAR(1000))
 RETURNS(BDRETORNO VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE RPOS(SUBSTR VARCHAR(100),
STR VARCHAR(100))
 RETURNS(BDRPOS INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SONUMEROS(PRTEXTO VARCHAR(100))
 RETURNS(BDRESULT SMALLINT)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SOLETRAS(PRTEXTO VARCHAR(100))
 RETURNS(BDRESULT SMALLINT)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_AFASTADOS(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODSIT INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_AFASTADOS_MES_INTEIRO (
    PRDATAINI date,
    PRDATAFIM date,
    PRTBTEMP smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer)
as
BEGIN
  suspend;
END^


CREATE OR ALTER PROCEDURE SP_ALTERA_TIPO_COLCON(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRCONTRCOL INTEGER,
PRCODCLA INTEGER)
 AS
 BEGIN EXIT; END
^

create or alter procedure SP_ATI_SEM_AFAST_MES_INT (
    PRDATAINI date,
    PRDATAFIM date,
    PRTBTEMP smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer)
as
BEGIN
  suspend;
END^

create or alter procedure SP_ATI_SEM_DEM_COM_TRANSF (
    PRDATAINI date,
    PRDATAFIM date,
    PREMP varchar(32700) = null,
    PRTBTEMP smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer)
as
begin
  suspend;
end^

CREATE OR ALTER PROCEDURE SP_ATIVOS_SEM_DEMITIDOS_MES(PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_ATU_CAMPOS_GERADOR AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_ATU_CATEGORIA AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_ATU_CODREC(PRCODREC DM_CODRECOF)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_ATU_FGTS_CONT_13(PRVALOR NUMERIC(15,6),
PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER,
PRVALORANT NUMERIC(15,6))
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_ATU_FGTS_CONT_A13(PRVALOR NUMERIC(15,6),
PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER,
PRVALORANT NUMERIC(15,6))
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_ATU_FGTS_CONT_C13(PRVALOR NUMERIC(15,6),
PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREF13 INTEGER,
PRREFERENCIA INTEGER,
PRVALORANT INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_ATU_FGTS_CONT_FA(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRCODTCA INTEGER,
PRDATA DATE,
PRVALOR NUMERIC(15,6),
PRFORMULA VARCHAR(100),
PRVALORANT NUMERIC(15,6))
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_ATU_FGTS_CONT_FC(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER,
PRREFCOMP INTEGER,
PRORDEM INTEGER,
PRVALOR NUMERIC(15,6),
PRFORMULA VARCHAR(100),
PRVALORANT NUMERIC(15,6))
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_ATU_FGTS_CONT_FN(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER,
PRORDEM INTEGER,
PRVALOR NUMERIC(15,6),
PRFORMULA VARCHAR(100),
PRVALORANT NUMERIC(15,6))
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_ATU_LANCAMENTOS_CONTABIL (
    PRCODPLANO INTEGER,
    PRCHAVE INTEGER,
    PRTIPOLAN INTEGER,
    PRDEBITO INTEGER,
    PRCREDITO INTEGER,
    PRHISTORICO INTEGER,
    PROLDDEBITO INTEGER,
    PROLDCREDITO INTEGER,
    PROLDHISTORICO INTEGER,
    PRCODPLANOPADRAO INTEGER,
    PRCODPLANOHIST INTEGER,
    PRREFERENCIA INTEGER = 0,
    PRNOVACHAVE INTEGER = 0,
    PRCOMPL INTEGER = NULL,
    PROLDCOMPL INTEGER = NULL)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_REMOVER_VAR_COMPLEMENTO (
    PRCOMPLEMENTO VARCHAR(200),
    PRREPLACE VARCHAR(10))
RETURNS (
    BDRESULT VARCHAR(200))
AS
begin
  suspend;
end
^

CREATE OR ALTER PROCEDURE SP_ATUALIZA_APELIDO_IE_EMP(PRCODEMP INTEGER,
PRREF INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_AUTONOMO_SEFIP RETURNS(BDCODCOL INTEGER,
BDOCORRENCIA VARCHAR(1),
BDPIS VARCHAR(20),
BDADM VARCHAR(10),
BDCATEGORIA VARCHAR(10),
BDNOME VARCHAR(100),
BDMATRICULA VARCHAR(20),
BDCTPS VARCHAR(10),
BDSERIECT DM_SERIECTPS,
BDDATAOPCAO VARCHAR(10),
BDDATANASC VARCHAR(10),
BDCBO VARCHAR(10),
BDCPF VARCHAR(14))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_BENEFICIARIOS_COLABORADOR(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRULTDIAMES DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDBENEFICIARIOS VARCHAR(2000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CALC_DEPRECIACAO(PRCODEMP INTEGER,
PRCODBEM INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRTIPO INTEGER,
PRCONTABILIZACAO INTEGER)
 RETURNS(PRVALORCORRIGIDOANTERIOR NUMERIC(15,2),
PRCORRECAOPERIODO NUMERIC(15,2),
PRVALORCORRIGIDOATUAL NUMERIC(15,2),
PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2),
PRDEPRECIACAOPERIODO NUMERIC(15,2),
PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6),
PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2),
PRVALORRESIDUALCONTABIL NUMERIC(15,2),
PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
PRTOTALMESESDEPRECIACAO INTEGER,
PRMESESDEPRECIADOS INTEGER,
PRMESESDEPRECIAR INTEGER,
PRTAXADEPRECIACAOANUAL NUMERIC(6,6),
PRDATATAXADEPRECIACAO DATE,
PRVALORBAIXA NUMERIC(15,2),
PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,2),
PRVALORBAIXAREAL NUMERIC(15,2),
PRVALORMOEDA NUMERIC(15,6),
PRDATABAIXA DATE,
PRVALORAQUISICAOMOEDA NUMERIC(15,6),
PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
PRVALORAQUISICAOORIGINAL NUMERIC(15,2),
PRCTADEBITODEPRE INTEGER,
PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CALC_EXP_SEFIP(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(20000),
PRCODAUT VARCHAR(20000),
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRAGRUPAR INTEGER,
PRVERIFICARBASE INTEGER = 1)
 RETURNS(BDMODALIDADE VARCHAR(1),
BDTERC INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODTPCC INTEGER,
BDCODCENTRO INTEGER,
BDANOMESRESC INTEGER,
BDGRRFPRES INTEGER,
BDCALCFGTSMESANT VARCHAR(5),
BDBASEFGTSFOL NUMERIC(18,6),
BDBASEFGTS13 NUMERIC(18,6),
BDVALINSS NUMERIC(18,6),
BDVALINSS13 NUMERIC(18,6),
BDVALINSSC13 NUMERIC(18,6),
BDBASEINSS NUMERIC(18,6),
BDBASEINSSCALC13 NUMERIC(18,6),
BDBASEINSS13 NUMERIC(18,6),
BDSALFAM NUMERIC(18,6),
BDVALFGTS NUMERIC(18,6),
BDVALFGTS13 NUMERIC(18,6),
BDPERCFGTSCOL NUMERIC(18,6),
BDBINSSC13 NUMERIC(18,6),
BDBINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6),
BDINSS13DT NUMERIC(18,6),
BDCONTRCOL INTEGER,
BDMVCC DM_BOOLEAN,
BDTEMMODALIDADE0 DM_BOOLEAN,
BDMOVRESCSEFIP VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_CALC_EXP_SEFIP_COMPLEMENTAR (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRCODAUT varchar(20000),
    PRANOMES integer,
    PRANOMESFIM integer,
    PRANOMESPAG integer,
    PRAGRUPAR integer,
    PRTIPOFC integer = 1,
    PRCODREC integer = 0)
returns (
    BDMODALIDADE varchar(20),
    BDTERC integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODTPCC integer,
    BDCODCENTRO integer,
    BDANOMESRESC integer,
    BDGRRFPRES integer,
    BDCALCFGTSMESANT varchar(5),
    BDBASEFGTSFOL numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDVALINSS numeric(18,6),
    BDVALINSS13 numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSSCALC13 numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDSALFAM numeric(18,6),
    BDVALFGTS numeric(18,6),
    BDVALFGTS13 numeric(18,6),
    BDPERCFGTSCOL numeric(18,6),
    BDVALINSSFC numeric(18,6),
    BDVALINSS13FC numeric(18,6),
    BDBINSSC13 numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSS13DT numeric(18,6),
    BDVALINSSC13 numeric(18,6),
BDTEMMODALIDADE0 DM_BOOLEAN,
    BDMOVRESCSEFIP varchar(5),
    BDPISCOL varchar(14),
    BDPISTERC varchar(14),
    BDOCORRENCIACOL integer,
    BDCATEGORIA integer,
    BDDATAADMCOL date,
    BDDIASTRABMES integer,
    BDTIPOMOV integer,
    BDTIPOFOL integer,
    BDDTACCONV date,
    BDREFFN integer)
as
 BEGIN SUSPEND; END
^


CREATE OR ALTER PROCEDURE SP_COMPOSICAO_RECURSOS_HUMANOS(PREMPRESAS VARCHAR(30000),
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDANOATUAL INTEGER,
BDANOANTERIOR INTEGER,
BDTOTCOLFIMANO INTEGER,
BDTOTADMANO INTEGER,
BDTOTDEMANO INTEGER,
BDTOTCOLMASC INTEGER,
BDTOTCOLFEM INTEGER,
BDTOTPRESSERVPJ INTEGER,
BDTOTPRESSERVPF INTEGER,
BDTOTCOLIDADE18A35 INTEGER,
BDTOTCOLIDADE36A60 INTEGER,
BDTOTCOLIDADESUP60 INTEGER,
BDTOTCOLFIMANO_ANOANT INTEGER,
BDTOTADMANO_ANOANT INTEGER,
BDTOTDEMANO_ANOANT INTEGER,
BDTOTCOLMASC_ANOANT INTEGER,
BDTOTCOLFEM_ANOANT INTEGER,
BDTOTPRESSERVPJ_ANOANT INTEGER,
BDTOTPRESSERVPF_ANOANT INTEGER,
BDTOTCOLIDADE18A35_ANOANT INTEGER,
BDTOTCOLIDADE36A60_ANOANT INTEGER,
BDTOTCOLIDADESUP60_ANOANT INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CONS_CALC_DEP (
    PRCODEMP INTEGER,
    PRCODBEM INTEGER,
    PRDATAINICIAL DATE,
    PRDATAFINAL DATE,
    PRTIPO INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRDETALHARTAXADEP INTEGER = 0,
    prRelBaiPar INTEGER = 0)
RETURNS (
    PRVALORCORRIGIDOANTERIOR NUMERIC(15,2),
    PRCORRECAOPERIODO NUMERIC(15,2),
    PRVALORCORRIGIDOATUAL NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2),
    PRDEPRECIACAOPERIODO NUMERIC(15,2),
    PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,2),
    PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2),
    PRVALORRESIDUALCONTABIL NUMERIC(15,2),
    PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,2),
    PRTOTALMESESDEPRECIACAO INTEGER,
    PRMESESDEPRECIADOS INTEGER,
    PRMESESDEPRECIAR INTEGER,
    PRTAXADEPRECIACAOANUAL NUMERIC(6,2),
    PRDATATAXADEPRECIACAO DATE,
    PRVALORBAIXA NUMERIC(15,2),
    PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,2),
    PRVALORBAIXAREAL NUMERIC(15,2),
    PRVALORMOEDA NUMERIC(15,2),
    PRDATABAIXA DATE,
    PRVALORAQUISICAOMOEDA NUMERIC(15,2),
    PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,2),
    PRVALORAQUISICAOORIGINAL NUMERIC(15,2),
    PRCTADEBITODEPRE INTEGER,
    PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,2),
    BDCODEMP INTEGER,
    BDCODBEM INTEGER,
    PRSOMARDEPRECIACAO INTEGER,
    PRCOMPENSACAOBAIXAPERANTERIOR NUMERIC(15,2),
    BDVALORRESIDUAL NUMERIC(15,2),
    PRTAXADEPRECIACAOANUAL_ANT NUMERIC(6,2),
    PRDATAINICALC DATE,
    BDVALORCAPITAL NUMERIC(15,2))
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CONS_CALC_DEP_CORRECAO (
    PRCODEMP INTEGER,
    PRCODBEM INTEGER,
    PRDATAINICIAL DATE,
    PRDATAFINAL DATE,
    PRTIPO INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRVLRMOEDA NUMERIC(15,2),
    PRPOSSUIBAIXA VARCHAR(5),
    PRCODBEMORIGINAL INTEGER,
    PRVALORAQUISICAO NUMERIC(15,2),
    PRTAXADEPANUAL NUMERIC(6,2),
    PRDATAAQUISICAO DATE,
    PRDATAORIGAQUISICAO DATE,
    PRDEPDIA VARCHAR(5),
    PRDEPMENSAL VARCHAR(5),
    PRDEPMESBAIXA VARCHAR(5),
    PRDATAINICIOCALC DATE,
    PRDATAFIMCALC DATE,
    PRDATAULTIMOITEMDEP DATE,
    PRVALDEPACUMUBEM NUMERIC(15,2),
    PRCTADEBDEPRE INTEGER,
    PRNUMDIAS INTEGER,
    PRDEPDIADATA INTEGER,
    PRVALORBAIXABEM NUMERIC(15,2),
    PRMESESDEPRECIADOSOUTRATAXA INTEGER,
    PRVALORACUMULADOANTERIOR NUMERIC(15,2),
    PRVALORRESIDUAL NUMERIC(15,2) = 0,
    PRDEPDIABAIXA VARCHAR(5) = 'FALSE',
    PRTAXAANT NUMERIC(15,2) = 0,
    PRCONT INTEGER = 0,
    PRMESDEPRECIACAONOVATAXA INTEGER = 0,
    prRelBaiPar INTEGER = 0)
RETURNS (
    PRVALORCORRIGIDOANTERIOR NUMERIC(15,2),
    PRCORRECAOPERIODO NUMERIC(15,2),
    PRVALORCORRIGIDOATUAL NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2),
    PRDEPRECIACAOPERIODO NUMERIC(15,2),
    PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,2),
    PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2),
    PRVALORRESIDUALCONTABIL NUMERIC(15,2),
    PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,2),
    PRTOTALMESESDEPRECIACAO INTEGER,
    PRMESESDEPRECIADOS INTEGER,
    PRMESESDEPRECIAR INTEGER,
    PRTAXADEPRECIACAOANUAL NUMERIC(6,2),
    PRDATATAXADEPRECIACAO DATE,
    PRVALORBAIXA NUMERIC(15,2),
    PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,2),
    PRVALORBAIXAREAL NUMERIC(15,2),
    PRVALORMOEDA NUMERIC(15,2),
    PRDATABAIXA DATE,
    PRVALORAQUISICAOMOEDA NUMERIC(15,2),
    PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,2),
    PRVALORAQUISICAOORIGINAL NUMERIC(15,2),
    PRCTADEBITODEPRE INTEGER,
    PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,2),
    PRCOMPENSACAOBAIXAPERANTERIOR NUMERIC(15,2),
    BDVALORCAPITAL NUMERIC(15,2),
    PRMESNOVATAXA INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_LISTAPERAQUISFE (
    PREMP varchar(15000),
    PRCOL varchar(32700))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDCODEMPORIG integer,
    BDCODCOLORIG integer)
as
declare variable WSQL varchar(32700);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WEMPORIG integer;
declare variable WCOLORIG integer;
declare variable WACHOUPER integer;
begin
  suspend;
end^

CREATE OR ALTER PROCEDURE SP_CONS_FERIAS_PER_AQUIS_ESCALA(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER,
PRPRIDIA DATE,
PRULTDIA DATE,
PRAGENDAFERIAS INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDINIPERAQUISFE DATE,
BDCODFE INTEGER,
BDINIPERGOZOFE DATE,
BDFIMPERAQUISFE DATE,
BDFIMPERGOZOFE DATE,
BDDATAPAGFE DATE,
BDQTDABONOFE NUMERIC(18,6),
BDQTDGOZOFE NUMERIC(18,6),
BDSALDOINIFE NUMERIC(15,6),
BDSALDOFIMFE NUMERIC(15,6),
BDBASEIRFE NUMERIC(15,6),
BDALIQIRFE NUMERIC(15,6),
BDVALORIRFE NUMERIC(15,6),
BDBASEINSSFE NUMERIC(15,6),
BDALIQINSSFE NUMERIC(15,6),
BDVALORINSSFE NUMERIC(15,6),
BDDEPFE NUMERIC(15,6),
BDSALBASEFE NUMERIC(15,6),
BDSALBASEHEFE NUMERIC(15,6),
BDDATABAIXAFE DATE,
BDCOLETIVASFE VARCHAR(5),
BDREFPAGABOFE INTEGER,
BDFALTASFE NUMERIC(15,6),
BDNOMEMP VARCHAR(100),
BDNOMCOL VARCHAR(70),
BDSALDOFINALSINDFE NUMERIC(18,6),
BDFERIADOSFE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CONSULTA_COL_POR_REF(PREMP INTEGER,
PRCOL INTEGER,
PRREFMICRO INTEGER)
 RETURNS(BDREFCOL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CONSULTA_EMP_POR_REF(PREMP INTEGER,
PRREFMICRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_CONSULTA_PLANO_CONTAS (
    PRCODPLADARAO integer,
    PRTODASCONTAS integer,
    PRCONSOLIDADA varchar(8000),
    PRFILTRO varchar(1024),
    PREMPRESA integer = 0)
returns (
    BDCODPLAPADRAO integer,
    BDCODTPLA integer,
    BDCTALON varchar(40),
    BDTIPCTA smallint,
    BDNOMCTA varchar(100),
    BDAPECTA varchar(20),
    BDGRUPOCTA integer,
    BDRELCTA integer,
    BDFILTROGER varchar(20),
    BDFORMULA varchar(200),
    BDCONDICAO varchar(100),
    BDPARTICIPANTE integer,
    BDPERTENCECONTA integer,
    BDCLANOM varchar(140),
    BDCODSUBCONTA integer,
    BDGRUPOSUBCONTA varchar(10),
    BDCODNATSUBCONTA integer,
    BDCTAEMPREENDIMENTOSIMOB DM_BOOLEAN,
    BDCTAUNIDADEIMOB DM_BOOLEAN,
    BDCTACAIXAPR DM_BOOLEAN,
    BDCTABANCOPR DM_BOOLEAN,
    BDCTATRANSPR DM_BOOLEAN,
    BDCARNELEAO DM_BOOLEAN)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CONSULTA_TERCEIRO(PRCODTER INTEGER,
PRREF INTEGER,
PRWHERETER VARCHAR(20000))
 RETURNS(BDCODTER INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCGCTER VARCHAR(18),
BDREFEMP INTEGER,
BDAPELIDOTER VARCHAR(20),
BDNOMETER VARCHAR(100),
BDLOGRTER VARCHAR(15),
BDENDTER DM_BDENDERECO,
BDNUMTER DM_NUMEND,
BDCOMPTER DM_BDCOMPENDERECO,
BDCEPTER VARCHAR(9),
BDBAITER VARCHAR(60),
BDDDDTER VARCHAR(3),
BDFONETER DM_BDTELEFONE,
BDFAXTER DM_BDTELEFONE,
BDEMAILTER DM_BDEMAIL,
BDIETER VARCHAR(20),
BDDATACADTER DATE,
BDIMTER VARCHAR(16),
BDPRURALTER VARCHAR(5),
BDENQSIMPLESFEDTER INTEGER,
BDINSCSUFRAMATER VARCHAR(10),
BDCODGPS INTEGER,
BDCODCID INTEGER,
BDCODPAIS INTEGER,
BDDESCPAIS VARCHAR(60),
BDDDDFAXTER VARCHAR(3),
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2),
BDNOMCID VARCHAR(40),
BDORGAOPUBLICO VARCHAR(5),
BDCODTIPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CONSULTA_TERCEIRO_MATRIZ (
    PRCODTER INTEGER,
    PRCGCTER TYPE OF COLUMN TTERCEIRO.BDCGCTER)
RETURNS (
    BDCODTER INTEGER,
    BDCGCTER TYPE OF COLUMN TTERCEIRO.BDCGCTER)
AS
BEGIN
END
^

CREATE OR ALTER PROCEDURE SP_CONSULTACIDADE(PRCIDADE INTEGER)
 RETURNS(BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDANIVCID VARCHAR(4),
BDDDD INTEGER,
BDCODEST INTEGER,
BDCODIBGE INTEGER,
BDCODFED INTEGER,
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2),
BDDESCUF VARCHAR(40))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CONSULTAEMPRESAS (
    PRREFMICRO integer,
    PRCODEMP varchar(10240),
    PRINATIVAS smallint,
    PREXCLUIREMP integer = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDCODMATRIZ INTEGER,
    BDCNPJEMP VARCHAR(18),
    BDDATAINIATIVEMP DATE,
    BDORGAOEMP VARCHAR(8),
    BDDATAREGEMP DATE,
    BDDATACONSTEMP DATE,
    BDDESCCARTEMP VARCHAR(40),
    BDDATAFIMATIVEMP DATE,
    BDCODPLAPADRAO INTEGER,
    BDCODHIST INTEGER,
    BDCODCENTROS INTEGER,
    BDCODCID INTEGER,
    BDCODCONT INTEGER,
    BDCODNATJUR INTEGER,
    BDCODCNAE INTEGER,
    BDNOMEMP DM_BDNOMEMP collate WIN_PTBR,
    BDNOMREDUZEMP DM_BDNOMREDUZEMP,
    BDAPEEMP DM_BDAPEMP,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP VARCHAR(9),
    BDDDDEMP INTEGER,
    BDFONEEMP DM_BDTELEFONE,
    BDFAXEMP DM_BDTELEFONE,
    BDEMAILEMP DM_BDEMAIL,
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDLOGREMP VARCHAR(15),
    BDIEEMP VARCHAR(20),
    BDIMEMP VARCHAR(20),
    BDSITEMP VARCHAR(5),
    BDDDDFAXEMP INTEGER,
    BDNOMCID VARCHAR(40),
    BDCODUF INTEGER,
    BDNOMECONT VARCHAR(40),
    BDSIGLAUF VARCHAR(2),
    BDANTECIPICMS INTEGER,
 BDANTECIPICMSCT integer,
    BDDESCUF VARCHAR(40),
    BDCODPLANOONLINE INTEGER,
    BDCODENQFED INTEGER,
    BDPERSONALIZACAO VARCHAR(120),
    BDCODCONTEF INTEGER,
    BDLIVRO VARCHAR(15),
    BDFOLHA VARCHAR(15),
    BDNOMECARTORIO VARCHAR(100),
    BDDATACADEMP DATE,
    BDTIPOAPURACAORET INTEGER,
    BDCODPLATRIB INTEGER,
    BDTRANMANUAL VARCHAR(5),
    BDTIPOAPURACAORETIR INTEGER,
    BDCODESC INTEGER,
    BDCODPLAPADRAOREF INTEGER,
    BDCODIBGE INTEGER,
    BDFORMATRIBUTACAO INTEGER,
    BDSTATUS_ES INTEGER,
    BDABRIRRATEIO DM_BOOLEAN,
    BDNAOPERMITERATEIOGRUPO DM_BOOLEAN,
    BDINTEGRANET DM_BOOLEAN,
    BDIGNORAREDISS DM_BOOLEAN,
    BDDATAINIESOCIAL DATE,
    BDOPCAOESOCIAL INTEGER,
    BDDDDCELULAREMP INTEGER,
    BDCELULAREMP DM_BDTELEFONE,
    BDCODCLI INTEGER,
    BDDATAOBRIGREINF DATE,
    BDNRTCE VARCHAR(20),
    BDSTATUSEMP integer,
    BDQTDBACKUPEMP integer,
    BDCODGIARS INTEGER,
    BDINCORPORADORAS DM_BOOLEAN,
    BDSCIREPORT DM_BOOLEAN,
    BDTIPOCAEPF INTEGER,
    BDCODTIPOCLI INTEGER,
    BDCODZONA integer,
    BDNOMEZONA varchar(40),
    BDCARNELEAO DM_BOOLEAN,
    BDDESCCNAE varchar(200),
    BDIAT_PISCOF_SEM_ICMS DM_BOOLEAN,
    BDEXIBEINFOCOLLAN varchar(5),
    BDSENHAIAT varchar(30),
    BDSENHAARQEMP integer,
    BDSENHAARQEMPSEP varchar(1),
    BDDOCAUXILIAR varchar(19),
    BDDATAINIPARALISADESIF date,
    BDDATAFIMPARALISADESIF date,
    BDTIPODEPENDENCIADESIF varchar(200) collate WIN_PTBR,
    BDCONTABPROPRIADESIF boolean,
    BDCODDEPENDENCIADESIF varchar(20) collate WIN_PTBR,
    BDCNPJDEPUNIFICADORADESIF integer,
    BDESOCIALRT varchar(5),
    BDCONTAAZUL DM_BOOLEAN,
    BDCONTABILIZASCP boolean)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CONSULTAEMPRESAS_SEARCH(PRREFMICRO INTEGER,
PRCODEMP INTEGER,
PRINATIVAS SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDAPEEMP VARCHAR(20),
BDIEEMP VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^
CREATE OR ALTER procedure SP_CONSULTAEMPRESAS_SIS (
    PRREFMICRO integer,
    PRCODEMP integer,
    PRINATIVAS smallint)
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDCNPJEMP varchar(18),
    BDDATAINIATIVEMP date,
    BDORGAOEMP varchar(8),
    BDDATAREGEMP date,
    BDDATACONSTEMP date,
    BDDESCCARTEMP varchar(40),
    BDDATAFIMATIVEMP date,
    BDCODPLAPADRAO integer,
    BDCODHIST integer,
    BDCODCENTROS integer,
    BDCODCID integer,
    BDCODCONT integer,
    BDCODNATJUR integer,
    BDCODCNAE integer,
    BDNOMEMP DM_BDNOMEMP,
    BDNOMREDUZEMP DM_BDNOMREDUZEMP,
    BDAPEEMP DM_BDAPEMP,
    BDNOMFANEMP varchar(200),
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP varchar(9),
    BDDDDEMP integer,
    BDFONEEMP DM_BDTELEFONE,
    BDFAXEMP DM_BDTELEFONE,
    BDDDDCELULAREMP integer,
    BDCELULAREMP DM_BDTELEFONE,
    BDEMAILEMP DM_BDEMAIL,
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDLOGREMP varchar(15),
    BDIEEMP varchar(20),
    BDIMEMP varchar(20),
    BDSITEMP varchar(5),
    BDDDDFAXEMP integer,
    BDNOMCID varchar(40),
    BDCODUF integer,
    BDNOMECONT varchar(40),
    BDSIGLAUF varchar(2),
    BDANTECIPICMS integer,
    BDANTECIPICMSCT integer,
    BDDESCUF varchar(40),
    BDRETINSS varchar(5),
    BDVLRMININSS numeric(15,2),
    BDCODCONFATIVO integer,
    BDSUFRAMA varchar(9),
    BDCODACESSOSN varchar(12),
    BDPERFILSPED integer,
    BDATIVIDADESPED integer,
    BDCODCONFIPI integer,
    BDCODCONFIRLP integer,
    BDCODCONFDIMESC integer,
    BDCODPORTEEMP integer,
    BDCODAPUCON integer,
    BDCODESCCONT integer,
    BDCODREGAPU integer,
    BDCONTPRODEC varchar(5),
    BDNRPARPRODEC integer,
    BDLANBCICMSVALCONT varchar(5),
    BDLANBCICMSISEOUT integer,
    BDLANCLISAISER varchar(5),
    BDLANPROENT varchar(5),
    BDLANPROSAI varchar(5),
    BDMOVSER varchar(5),
    BDPERCISS numeric(15,6),
    BDREDPERCISS numeric(15,6),
    BDMOVIRRF varchar(5),
    BDALIQIRRF numeric(15,6),
    BDISENTOIRRF numeric(15,6),
    BDEMPINATIVA varchar(5),
    BDEMPDIFPAPEL varchar(5),
    BDEMPBARREST varchar(5),
    BDVERIFICARNOTASJALAN integer,
    BDCODPLANOONLINE integer,
    BDLRISSSN numeric(15,6),
    BDCOMERCIO varchar(5),
    BDINDUSTRIA varchar(5),
    BDSERVICO varchar(5),
    BDANEXOIII varchar(5),
    BDANEXOIV varchar(5),
    BDANEXOV varchar(5),
    BDCODENQFED integer,
    BDSUBSTRIB integer,
    BDCODCONFDACON integer,
    BDCODCONFICMSSPED integer,
    BDCODCONFCIAP integer,
    BDREDBCICMSENT numeric(15,6),
    BDREDBCICMSSAI numeric(15,6),
    BDICMSMONO DM_BOOLEAN,
    BDCODCONFDASN integer,
    BDRETPARPIS varchar(5),
    BDRETPARCOFINS varchar(5),
    BDRETPARCSLL varchar(5),
    BDRETPARIRRF varchar(5),
    BDRETPARISSQN varchar(5),
    BDRETPARINSS varchar(5),
    BDRETPARFUNRURAL varchar(5),
    BDTIPOAPURACAO integer,
    BDSOMFREBASEICMS varchar(5),
    BDSOMFREVLRCONTAB varchar(5),
    BDCODPLATROCA integer,
    BDCODPLACFOP integer,
    BDCODCONFBLOCOP integer,
    BDCREDPRESUMIDO varchar(5),
    BDTERMOACEITE varchar(5),
    BDANTECIPAIMPOSTO varchar(5),
    BDTIPODECLARANTEDMED integer,
    BDREGISTROANSDMED integer,
    BDNUMEROCNESDMED integer,
    BDDTOBRIGSPEDCONT date,
    BDTIPOAPURACAORET integer,
    BDTIPOAPURACAORETIR integer,
    BDDTOBRIGSPEDICMS date,
    BDCODCONTEF integer,
    BDLIVRO varchar(15),
    BDFOLHA varchar(15),
    BDNOMECARTORIO varchar(100),
    BDLANCAPARCELAAUTO varchar(5),
    BDCODIGOPLA integer,
    BDINDATIV integer,
    BDTRANMANUAL varchar(5),
    BDIMPORTARVALORESICMSSN DM_BOOLEAN,
    BDDIFALIQ varchar(5),
    BDDIFALIQBASEEM integer,
    BDANEXOVI DM_BOOLEAN,
    BDCODPLATRIB integer,
    BDCODPLAPADRAOREF integer,
    BDINDNATPJ integer,
    BDCODIBGE integer,
    BDFORMATRIBUTACAO integer,
    BDSOMAPISCOFVLRCONT DM_BOOLEAN,
    BDSOMAIIVLRCONT DM_BOOLEAN,
    BDMANTERPARCELAS DM_BOOLEAN,
    BDCODPLANOINCONS integer,
    BDABRIRRATEIO DM_BOOLEAN,
    BDNAOPERMITERATEIOGRUPO DM_BOOLEAN,
    BDINTEGRANET DM_BOOLEAN,
    BDSOMAIPIPROD DM_BOOLEAN,
    BDSOMAICMSVLRCONT DM_BOOLEAN,
    BDCODPLAE115 integer,
    BDDATACADEMP date,
    BDCODCLATRI integer,
    BDDATAOBRIGREINF date,
    BDSOMASTPROD DM_BOOLEAN,
    BDCALCANTICMS varchar(5),
    BDCONSIPIBC varchar(5),
    BDIMPICMSST varchar(5),
    BDANEXOIII_2018 varchar(5),
    BDANEXOIV_2018 varchar(5),
    BDANEXOV_2018 varchar(5),
    BDSTATUSEMP integer,
    BDQTDBACKUPEMP integer,
    BDIMPORTARISS varchar(5),
    BDIMPORTARCTESAI DM_BOOLEAN,
    BDNAOVALIDACONTRATO DM_BOOLEAN,
    BDINCORPORADORAS DM_BOOLEAN,
    BDALIQINSS DM_NUMERIC_7_4_ALIQ,
    BDCODPLANOCONFSN integer,
    BDGERAC490 varchar(5),
    BDTIPOCAEPF integer,
    BDCODPLACATSP integer,
    BDOPTANTERET DM_BOOLEAN,
    BDMANTERC197CATSP varchar(5),
    BDCODCLASSESTAB integer,
    BDCODPLASEFSC integer,
    BDAPURAGIAST DM_BOOLEAN,
    BDCARNELEAO DM_BOOLEAN,
    BDEXPINCENTFISCAIS DM_BOOLEAN,
    BDCODCONFGIAFPE integer,
    BDCALCSTIMPSUB DM_BOOLEAN,
    BDSTRET DM_NUMERIC_7_4_ALIQ,
    BDTIPOAPURACAORETIRTOM integer,
    BDSCIREPORT DM_BOOLEAN,
    BDCONTPISCOFCAIXA DM_BOOLEAN,
    BDDIFALIQ_NAOGERA_C197 BOOLEAN,
    BDCONTABILIZASCP boolean,
	BDUSARTAGVNF BOOLEAN)
as
BEGIN 
 SUSPEND; 
END^

create or alter procedure SP_CONTAS_SEARCHCOMPONENT (
    PRCODPLAPADRAO integer,
    PRTEXT varchar(100),
    PREMPRESA integer = 0)
returns (
    BDCODTPLA integer,
    BDAPECTA varchar(20),
    BDCTALON varchar(40),
    BDNOMCTA varchar(100),
    BDTIPCTA integer)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_COPIA_PROGRAMAS_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 RETURNS(WCODPLAPROG INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CRIA_DADOSCALC_BAIXA AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_CRIA_DETGPSSEFIP(PRCODEMP VARCHAR(32000),
PRANOMESPAG INTEGER,
PRTIPOGPS INTEGER,
PRTIPOEMISSAO INTEGER)
 RETURNS(BDOK INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_DADOS_EMP_REF(PRWHEREEMP VARCHAR(32000),
PRREFINICIAL INTEGER,
PRREFFINAL INTEGER)
 RETURNS(BDCODMATRIZ INTEGER,
BDCODEMP INTEGER,
BDREFATU INTEGER,
BDREFEMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EMPPRESA_IMP(PRCODIMP INTEGER,
PRREF INTEGER,
PRCODEMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDEMPIMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXCLUI_ONLINE(PREMPRESA INTEGER,
PRCHAVE INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_EXCLUI_ONLINE_CC(PREMPRESA INTEGER,
PRCHAVE INTEGER,
PRCODCENTRO INTEGER,
PRCODTPCC INTEGER,
PRDEBCRE INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_EXCLUSAO_CBO_NAOUSADO(BDCODCBO INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_EXISTE_COLABORADOR_NOVO(PRCODEMP INTEGER,
PRCODCOL INTEGER)
 RETURNS(BDCODCOL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER procedure SP_EXISTE_COLABORADOR_DOWNLOAD(PRCODCOL integer,PRCODEMP integer)
returns (BDCODIGO integer)
as
BEGIN SUSPEND; END^

create or alter procedure SP_EXP_ATIVA_CONTABIL (
    PRCODEMP integer,
    PRDATAINICIAL date,
    PRDATAFINAL date,
    PRCTALONINI varchar(40),
    PRCTALONFIM varchar(40),
    PRCODPLANOPADRAO integer,
    PRCONTABILIZACAO integer,
    PRCONTABILIZADATABAIXA integer = 0,
    PRBAIXAINDIVIDUAL integer = 0,
    PRORDER varchar(10) = 'ASC')
returns (
    BDREF varchar(10),
    BDREFINTEIRO integer,
    BDCODTPLABEM integer,
    BDCTALONBEM varchar(40),
    BDNOMTPLABEM varchar(100),
    BDCODNOMTPLABEM varchar(110),
    BDCODBEM integer,
    BDNOMBEM varchar(200),
    BDCODNOMBEM varchar(210),
    BDCODTPCC integer,
    BDNOMTPCC varchar(40),
    BDDEPRECIACAOPERIODO numeric(18,6),
    BDVALORBAIXAPERIODO numeric(18,6),
    BDDEPRECIACAOACUMULADA numeric(18,6),
    BDTAXA numeric(9,6),
    BDDATATAXADEP date,
    BDVALORRESIDUAL numeric(18,6),
    BDCODPLAPADRAO integer,
    BDCODHIST integer,
    BDCTADEBITODEPRE integer,
    BDCTACREDITODEPRE integer,
    BDHISTORICODEPRE integer,
    BDCTADEBITOBAIXA integer,
    BDCTACREDITOBAIXA integer,
    BDHISTORICOBAIXA integer,
    BDCTADEBITODEPBAI integer,
    BDCTACREDITODEPBAI integer,
    BDHISTORICODEPBAI integer,
    BDDATABAIXA date,
    BDCOMPLEMENTOBAIXA varchar(200),
    BDCODBAIXA integer,
    BDRESIDUALDEB integer,
    BDRESIDUALCRE integer,
    BDRESIDUALHIS integer,
    BDVALORRESIDUALBAIXA numeric(15,2),
    BDCAPITALDEB integer,
    BDCAPITALCRE integer,
    BDCAPITALHIS integer,
    BDVALORCAPITAL numeric(15,2),
    BDPERDACAPITALDEB integer,
    BDPERDACAPITALCRE integer,
    BDPERDACAPITALHIS integer,
    BDVALORBAIXATOTAL numeric(15,2),
    BDVALORAQUISICAO numeric(15,2),
    BDDEPCCIBE DM_BOOLEAN,
    BDBAIDEPCCIBE DM_BOOLEAN,
    BDBAIAQUICCIBE DM_BOOLEAN,
    BDRESIDUALCCIBE DM_BOOLEAN,
    BDCAPITALCCIBE DM_BOOLEAN,
    BDPERDACAPITALCCIBE DM_BOOLEAN)
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VATI_GERAR_INCON_TDEPAUTO (
    PRREFERENCIA integer,
    PRDATAINI date,
    PRDATAFIN date)
as
 BEGIN END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(10000),
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRDATARECFGTS DATE,
PRDATARECINSS DATE,
PRTIPOFOLHA INTEGER,
PRMODALIDADE VARCHAR(1),
PRINDRECFGST VARCHAR(1),
PRINDRECINSS VARCHAR(1))
 RETURNS(BDARQ INTEGER,
BDREG VARCHAR(360),
BDORDEM VARCHAR(70),
BDINC VARCHAR(32000),
BDCONTADOR INTEGER,
BDCODREC INTEGER,
BDMODALIDADE VARCHAR(1))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_ARQ(PRCODREC INTEGER,
PRMODALIDADE VARCHAR(1))
 RETURNS(BDARQ INTEGER,
BDREG00 INTEGER,
BDREG10 INTEGER,
BDREG20 INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_CODREC(PRWHEREEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRCODREC INTEGER)
 RETURNS(BDARQ INTEGER,
BDMODALIDADE VARCHAR(1),
BDCONTADOR INTEGER,
BDCODREC INTEGER,
BDREG VARCHAR(360),
BDORDEM VARCHAR(70),
BDINC VARCHAR(32000),
BDQTDCHAR INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_EMP_TSITCOL_ESOCIAL (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(32700)) 
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDDATAINISEFIP DATE,
    BDTIPOACID INTEGER,
    BDOBSERVACAO VARCHAR(255),
    BDCODDOE INTEGER,
    BDDIASSIT INTEGER,
    BDCODMOTESSIT INTEGER,
    BDCODMED INTEGER,
    BDCODSINTRAB INTEGER) 
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_REG_00 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_REG_10(PRSALFAM NUMERIC(15,6),
PRMATERNIDADE NUMERIC(15,6))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_REG_12(BDDEDMAT13 NUMERIC(15,6),
BDRURALFISICA NUMERIC(15,6),
BDRURALJURIDICA NUMERIC(15,6),
BDCOMPENSACAO NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDACUMULA NUMERIC(15,6),
BDACUMULATERC NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_REG_20(BDSALFAM INTEGER,
BDNOTASFISCAIS INTEGER)
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_REG_21(BDCOMPENSACAO NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDACUMULA NUMERIC(15,6),
BDACUMULATERC NUMERIC(15,6))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_REG_30(PRAUTONOMO INTEGER,
PRREMSEM13 NUMERIC(15,6),
PRREM13 NUMERIC(15,6),
PRVALINSS NUMERIC(15,6),
PRBASEINSS NUMERIC(15,6),
PRBASEINSS13MES NUMERIC(15,6),
PRBASEINSS13 NUMERIC(15,6))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_REG_32(PRCODMOV VARCHAR(5),
PRDATAMOV VARCHAR(10),
PRINDFGTS VARCHAR(1))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_REG_90 RETURNS(BDREG VARCHAR(360),
BDORDEM VARCHAR(300))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_RESC_SEGUINTE_COL(PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATA DATE,
BDDATASTR VARCHAR(10),
BDMOTIVO VARCHAR(5),
BDINDFGTS INTEGER,
BDCODMFG INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_FERIADO_EMPRESA(PRCODEMP INTEGER,
PRDATA DATE,
PRREFERENCIA INTEGER = 0,
PRSINDICATO INTEGER = 0)
 RETURNS(BDFERIADO VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_FERIAS_PROVISAO(PRCODEMP VARCHAR(25000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDINIPERAQUISFE DATE,
BDCODFE INTEGER,
BDREFFE INTEGER,
BDCODVER INTEGER,
BDREFVRFE NUMERIC(15,6),
BDVALVRFE NUMERIC(15,6),
BDREFAUXVRFE NUMERIC(15,6),
BDCLAVER VARCHAR(20),
BDTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_FERIAS_PROVISAO_REF(PRCODEMP VARCHAR(25000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDINIPERAQUISFE DATE,
BDCODFE INTEGER,
BDREFFE INTEGER,
BDBASEINSSRFE NUMERIC(15,6),
BDBASEPISRFE NUMERIC(15,6),
BDBASEFGTSRFE NUMERIC(15,6),
BDVALORFGTSRFE NUMERIC(15,6),
BDBRATAPORFE NUMERIC(15,6),
BDDIASFERFE NUMERIC(18,6),
BDDIASABOFE NUMERIC(18,6),
BDREFFIMFE INTEGER,
BDINIPERGOZOFE DATE,
BDFIMPERGOZOFE DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_FICHA_REGISTROS_CARGOS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(20000),
PRULTDIA DATE,
PRRETORNAVAZIO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATACOL DATE,
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDDESCTFUC VARCHAR(40),
BDCODCBO INTEGER,
BDNOMCOL VARCHAR(70),
BDCODMAS INTEGER,
BDDESCMAS VARCHAR(50))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_FICHA_REGISTROS_HORARIOS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(20000),
PRULTDIA DATE,
PRRETORNAVAZIO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATACOL DATE,
BDCODPQUA INTEGER,
BDCODQH INTEGER,
BDDESCQH DM_BDDESCQH,
BDNOMCOL DM_BDNOMCOL,
BDCODMAS INTEGER,
BDDESCMAS VARCHAR(50))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER procedure SP_FICHA_REGISTROS_SALARIOS (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRREF integer,
    PRRETORNAVAZIO integer,
    PRTRAZERSALINI integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDDATAADMCOL date,
    BDSALINICOL numeric(18,6),
    BDDATACOL date,
    BDSALBASECOL numeric(18,6),
    BDCODMAS integer,
    BDDESCMAS varchar(50),
    BDCODTFUC integer,
    BDCODSHE integer,
    BDDESCSHE varchar(50),
    BDSALBASEANT numeric(18,6),
    BDDATAEFEITO date)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_FUNCAO_CBO_ESOCIAL(PREMPRESA INTEGER,
PRCBO INTEGER)
 RETURNS(BDCODFUNCAO VARCHAR(30))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_FUNCOES_PLANO_EMP (
    PRCODEMP integer,
    PRCODPLAFUC integer,
    PRREFERENCIA integer,
    PRRHNET smallint = 0,
    PRCODTFUC integer = 0)
returns (
    BDCODEMP integer,
    BDCODEMPRHNET integer,
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDCODCBO integer,
    BDDESCCBO varchar(150),
    BDDESCTFUC varchar(40),
    BDCODCBOTSIN integer,
    BDDESCFUNCDET varchar(999),
    BDINATIVA varchar(5))
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_GERA_ADVERTENCIAS AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_IMPOSTO_EMPRESA(PRCODEMP INTEGER,
PRCODSIS INTEGER,
PRTIPORETENCAO INTEGER,
PRREF INTEGER,
PRQTD INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDREFFIMIMP INTEGER,
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(100),
BDDATACRIACAO DATE,
BDDATAEXTINTO DATE,
BDCOMPETENCIA INTEGER,
BDDOCARRECADACAO INTEGER,
BDPERAPURACAO INTEGER,
BDDIAVENCTO INTEGER,
BDANTECIPA VARCHAR(5),
BDMESVENCTO INTEGER,
BDJUROSDIA INTEGER,
BDVLRJUROS NUMERIC(15,6),
BDJUROSDIAMES INTEGER,
BDMULTADIA INTEGER,
BDVLRMULTA NUMERIC(15,6),
BDMULTADIAMES INTEGER,
BDVLRMAXMULTA NUMERIC(15,6),
BDALIQIMPOSTO NUMERIC(15,6),
BDLIMITEISENCAO NUMERIC(15,6),
BDTIPORETENCAO INTEGER,
BDCODREC INTEGER,
BDCODIND INTEGER,
BDRETBCCALCULOIMP VARCHAR(5),
BDDESCREC VARCHAR(150),
BDTIPOIMPOSTO INTEGER,
BDCODSIS INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_INCLUI_VERBAS_NOVAS AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_PBM_NO_ANO (
    PREMP VARCHAR(32700),
    PRANO INTEGER)
RETURNS (
    BDCODEMP INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WSQL2 VARCHAR(1000);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WREFINI INTEGER;
DECLARE VARIABLE WREFFIM INTEGER;
DECLARE VARIABLE WCODBLOCOP INTEGER;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES VARCHAR(2);
BEGIN SUSPEND; END
^

create or alter procedure SP_INCLUI_VERBASEMP (
    PRVERBA integer,
    PRCLASSECOL integer = -1,
    PRTIPOCOL integer = -1,
    PRCOMFGTS DM_BOOLEAN = 'FALSE',
    PRINTERMITENTE DM_BOOLEAN = 'FALSE')
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_INDICES_ACUMULADOS(PRCODIND INTEGER)
 RETURNS(BDANO INTEGER,
BDJAN NUMERIC(15,6),
BDFEV NUMERIC(15,6),
BDMAR NUMERIC(15,6),
BDABR NUMERIC(15,6),
BDMAI NUMERIC(15,6),
BDJUN NUMERIC(15,6),
BDJUL NUMERIC(15,6),
BDAGO NUMERIC(15,6),
BDSET NUMERIC(15,6),
BDOUT NUMERIC(15,6),
BDNOV NUMERIC(15,6),
BDDEZ NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_INSERE_ADVERTENCIA(PRDESCRICAO VARCHAR(1024),
PRTIPO INTEGER = 1)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_INSERIR_LOG_ATUALIZACAO (
    PRSISTEMA INTEGER,
    PRACAO BLOB SUB_TYPE 1 SEGMENT SIZE 80)
AS
BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_INSERIR_LOG(
    BDCODEMP INTEGER,
    BDCODTER INTEGER,
    BDCODUSU INTEGER,
    BDCODIMP INTEGER,
    BDCODSIS INTEGER,
    BDCODCOL INTEGER,
    BDDATASISTEMA DATE,
    BDHORAINICIAL TIME,
    BDACAO BLOB SUB_TYPE 1 SEGMENT SIZE 80,
    BDACESSOID INTEGER,
    BDTIPOACAO INTEGER,
    PRNOME_MICRO VARCHAR(80),
    PRIP_MICRO VARCHAR(15),
    PRNOMETELA VARCHAR(100),
    PRCAPTIONTELA VARCHAR(150),
    BDCODRESP INTEGER,
    PRTABELA VARCHAR(50),
    BDTIPOIMPRESSAO SMALLINT,
    BDERRO_PROCESSO VARCHAR(5),
    BDDATACOMPETENCIA DATE,
    BDCODUSUINTRANET INTEGER = NULL,
    BDNOMUSUINTRANET VARCHAR(80) = NULL)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_INSERT_ATIVIDADE_BLUMENAU AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_COPIA_ATIVIDADES_MUNICIPAIS
 (
  CODCIDNOVA INTEGER,
  CODCIDCOPIAR INTEGER
  )
AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_INSERT_FERIADO(PRDATA DATE,
PRDESC VARCHAR(40),
PRCID INTEGER,
PRUF INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_INSERT_FOLHAAVULSA_ONLINE(PRCODTCA INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_INSERT_NOVA_VERBA_ONLINE(PRCLASSIFICACAO VARCHAR(100),
PRVERBA INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_INSERTS(TABELA VARCHAR(50),
CAMPOS VARCHAR(1024),
VALORES VARCHAR(32750))
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_LISTAR_PLANOS_ONLINE(PRCODEMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDCODPLANOONLINE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_LISTAR_PLANOS_POR_REF(PRWHEREEMP VARCHAR(32000),
PRREFINI INTEGER,
PRREFFIN INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDREFEMP INTEGER,
BDCODPLANOONLINE INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_MANUTENCAO_TCALCVESP(PRTIPOCALC INTEGER,
PRCLASSITEM VARCHAR(20),
PRDESCITEM VARCHAR(40),
PRFORMULAITEM VARCHAR(350),
PRCODVERBASE INTEGER,
PRCODVERESP INTEGER,
PRFORMULADABASE VARCHAR(5))
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_MASCARA_CODNAT(PRCODNAT INTEGER)
 RETURNS(BDNATUREZA VARCHAR(9),
BDCODNAT INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_MODELOS_GERADOR_REL AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_NOME_TERCEIRO(PRREF INTEGER,
PRTER INTEGER)
 RETURNS(BDCODTER INTEGER,
BDNOME VARCHAR(200))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_PBM(PREMP INTEGER,
PRREF INTEGER)
 RETURNS(BDEMP INTEGER,
BDREF INTEGER,
BDOK INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_PRAZO_EXPERIENCIA_SITUACAO(
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000),
    PRDIASPRAZO1COL integer,
    PRDIASPRAZO2COL integer,
    PRULTDIAMES date = null,
    PRCODSIT integer = 0,
    PRTABLETEMP integer = 0,
    PRRETORNO boolean = false)
 RETURNS(
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDDATAFIMPRAZO1COL DATE,
    BDDATAFIMPRAZO2COL DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_PROPORC_VALORES(PRBASETOTAL NUMERIC(15,6),
PRVALOR NUMERIC(15,6),
PRBASE01 NUMERIC(15,6),
PRBASE02 NUMERIC(15,6),
PRBASE03 NUMERIC(15,6),
PRBASE04 NUMERIC(15,6),
PRBASE05 NUMERIC(15,6),
PRBASE06 NUMERIC(15,6),
PRBASE07 NUMERIC(15,6),
PRBASE08 NUMERIC(15,6))
 RETURNS(BDVALOR01 NUMERIC(15,6),
BDVALOR02 NUMERIC(15,6),
BDVALOR03 NUMERIC(15,6),
BDVALOR04 NUMERIC(15,6),
BDVALOR05 NUMERIC(15,6),
BDVALOR06 NUMERIC(15,6),
BDVALOR07 NUMERIC(15,6),
BDVALOR08 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_REF_TRIMESTRE(PRREF INTEGER)
 RETURNS(BDTRIMESTRE INTEGER,
BDREF INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_REL_CONSULTA_CONFIGURAVEL(PRCOLUNAS INTEGER,
PRMATRIZ INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREF INTEGER,
BDMESEXTENSO VARCHAR(20),
BDCOL01 NUMERIC(15,2),
BDCOL02 NUMERIC(15,2),
BDCOL03 NUMERIC(15,2),
BDCOL04 NUMERIC(15,2),
BDCOL05 NUMERIC(15,2),
BDCOL06 NUMERIC(15,2),
BDCOL07 NUMERIC(15,2),
BDCOL08 NUMERIC(15,2),
BDCODMATRIZ INTEGER,
BDQUEBRAQUADRO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_REL_CONSULTA_CONFIGURAVEL2 (
    PRNAOIMPRIMEZERADO varchar(5) = '',
    PRDECLARACAO varchar(5) = '')
RETURNS(BDCODMATRIZ INTEGER,
BDCODEMP INTEGER,
BDCODPLANO INTEGER,
BDCODQUADRO INTEGER,
BDREF INTEGER,
BDMESEXTENSO VARCHAR(20),
BDCOL01 NUMERIC(15,2),
BDCOL02 NUMERIC(15,2),
BDCOL03 NUMERIC(15,2),
BDCOL04 NUMERIC(15,2),
BDCOL05 NUMERIC(15,2),
BDCOL06 NUMERIC(15,2),
BDCOL07 NUMERIC(15,2),
BDCOL08 NUMERIC(15,2),
BDLINHA INTEGER,
BDTITULOS VARCHAR(640),
BDMEDIA01 numeric(15,2),
BDMEDIA02 numeric(15,2),
BDMEDIA03 numeric(15,2),
BDMEDIA04 numeric(15,2),
BDMEDIA05 numeric(15,2),
BDMEDIA06 numeric(15,2),
BDMEDIA07 numeric(15,2),
BDMEDIA08 numeric(15,2))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_REL_CONSULTA_SIMULADOR_TRIB (
    PRTOTALTRIMESTRE DM_BOOLEAN = false,
    PRNAOIMPRIMEZERADO DM_BOOLEAN = false)
returns (
    BDCODMATRIZ integer,
    BDCODEMP integer,
    BDCODPLANO integer,
    BDCODQUADRO integer,
    BDREF numeric(15,2),
    BDMESEXTENSO varchar(20),
    BDCOL01 numeric(15,2),
    BDCOL02 numeric(15,2),
    BDCOL03 numeric(15,2),
    BDCOL04 numeric(15,2),
    BDCOL05 numeric(15,2),
    BDCOL06 numeric(15,2),
    BDCOL07 numeric(15,2),
    BDCOL08 numeric(15,2),
    BDCOL09 numeric(15,2),
    BDCOL10 numeric(15,2),
    BDCOL11 numeric(15,2),
    BDCOL12 numeric(15,2),
    BDCOL13 numeric(15,2),
    BDCOL14 numeric(15,2),
    BDCOL15 numeric(15,2),
    BDCOL16 numeric(15,2),
    BDCOL17 numeric(15,2),
    BDCOL18 numeric(15,2),
    BDCOL19 numeric(15,2),
    BDCOL20 numeric(15,2),
    BDLINHA integer,
    BDTITULOS varchar(1500),
    BDTOTTRI DM_BOOLEAN,
    BDISTOT DM_BOOLEAN)
as
BEGIN 
 SUSPEND; 
END ^

CREATE OR ALTER PROCEDURE SP_REL_CTRPAT_ANALILITIC_SINT AS
 BEGIN EXIT; END
^

CREATE OR ALTER procedure SP_REL_RESUMO_IMPOSTOS (
PRCODEMP varchar(10000),
PRCODIMP varchar(10000),
PRCODSIS varchar(10000),
PRREFINI integer,
PRREFFIN integer,
PRREFATUAL integer,
PRDTVCTOINI date,
PRDTVCTOFIM date)
returns (
BDCODEMP integer,
BDCHAVEDARF integer,
BDCODIMP integer,
BDDESCIMP varchar(200),
BDCODREC integer,
BDCODSIS integer,
BDCODPERIODO integer,
BDDESCPERIODO varchar(40),
BDORDEM integer,
BDREFERENCIA integer,
BDMESEXTENSO varchar(20),
BDQUOTA integer,
BDCODCOL integer,
BDCODEMPCOL integer,
BDCODCENTRO integer,
BDCODTPCC integer,
BDPERIODO date,
BDNUMREFDOC varchar(20),
BDDATAVCTO date,
BDVALOR numeric(15,6),
BDMULTA numeric(15,6),
BDJUROS numeric(15,6),
BDTOTAL numeric(15,6),
BDOBS blob sub_type 0 segment size 80,
BDORDEMCOMPL integer,
BDBASEIMP numeric(15,6),
BDALIQIMP numeric(15,6),
BDVLRIMPORIGINAL numeric(15,6),
BDVLRACUMULO numeric(15,6),
BDVLRMULTAJUROS numeric(15,6),
BDVLROUTENTIDADE numeric(15,6),
BDTIPOIMPOSTO integer,
BDCOMPENSACAO numeric(15,6),
BDVLRACUOUTENT numeric(15,6),
BDREFPAG integer,
BDDTPGTO date,
BDDOCARRECADACAO integer)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_RESTAURA_VERBA_PADRAO (
    PRCODVER integer,
    PRCODVERBANOVO integer = 0)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_RESTAURA_VERBA_PADRAO_CLASS(PRCLAVER VARCHAR(20) = NULL)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_DIFERENCAS_VSUC_TLAN(PRCODEMP VARCHAR(2048),
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRTRANSACAO INTEGER,
PRSEMPRE integer = 0)
 RETURNS(PREMPRESA INTEGER,
PRDATA DATE,
PRDEBITO NUMERIC(15,6),
PRCREDITO NUMERIC(15,6),
PRDIFERENCA NUMERIC(15,6),
PRTOTAL NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_EMPRESA_FILIAIS(PRCODEMP INTEGER,
PRREFEMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_MESANO_EXTENSO(PRMES VARCHAR(2),
PRANO VARCHAR(4),
PRSEPARADOR VARCHAR(1) = '/')
 RETURNS(BDANOMES VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_NUMEROS(PRSTR VARCHAR(1000),
PRTAMANHO INTEGER = 0)
 RETURNS(BDNUMERO VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_PRIMEIRO_NUMERO(PRTEXTO varchar(255))
 RETURNS(WNUMERODCTO VARCHAR(50))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_ALFANUMERICO(PRSTR VARCHAR(1000),
PRTAMANHO INTEGER = 0)
 RETURNS(BDNUMERO VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_SALDO_EMP(PRCODEMP INTEGER,
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
PRCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRPARTICIPANTE INTEGER = 0)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_SALDO_EMP_X(
    PRCODEMP integer,
    PRCONTA integer,
    PRDATAINI date,
    PRDATAFIM date,
    PRINDICE integer,
    PRIGNORAZERAMENTO smallint,
    PRCC varchar(8192),
    PRRELCTA integer,
    PRREFEMP integer,
    PRCONCILIADOS integer,
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRPARTICIPANTE integer = 0,
    PRPARTICIPANTEFINAL integer = 0,
    PREMPREENDIMENTO integer = 0,
    PRUNIDIMOB integer = 0,
    PRAPENASCONTABILIZACAOSEL integer = 0,
    PRCODEMPMATRIZ integer = 0,
    PRCONTABILIZACAOLALUR integer = 0,
    prlistapart varchar(10000) = '',
    PRFILTIPOLAN varchar(3200) = '',
    PRCODPLAHISTLALUR integer = 0)
RETURNS (
    SALDO_ANT_DEB NUMERIC(15,2),
    SALDO_ANT_CRE NUMERIC(15,2),
    SALDO_DEB NUMERIC(15,2),
    SALDO_CRE NUMERIC(15,2),
    MOVIMENTO NUMERIC(15,2),
    SALDO_ATUAL NUMERIC(15,2),
    SALDO_ANTERIOR NUMERIC(15,2),
    CODEMP INTEGER) 
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_CONTAS_EMPRESA (
    BDCODEMP INTEGER,
    BDCODPLANO INTEGER,
    BDCLASSIFICACAO VARCHAR(40))
RETURNS (
    BDCODPLAPADRAO INTEGER,
    BDCODTPLA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDTIPCTA INTEGER,
    BDCTAOBRIG DM_BOOLEAN,
    BDCTAEMP INTEGER)
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_CONTAS_LANCADAS (
    BDCODEMP INTEGER,
    BDCODPLANO INTEGER,
    BDREFERENCIA INTEGER,
    BDFILIAIS INTEGER = 0)
RETURNS (
    BDCONTA INTEGER)
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_RETORNA_CONTAS_ONLINE (
    BDCODPLAONLINE INTEGER,
    BDCODPLAPADRAO INTEGER)
RETURNS (
    BDCONTA INTEGER)
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_SALDO_MATRIZFILIAL(PRCODEMP INTEGER,
PRMATRIZFILIAIS VARCHAR(2048),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
BDCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
MOVIMENTO NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_SALDO_MATRIZFILIAL_X(PRCODEMP INTEGER,
PRMATRIZFILIAIS VARCHAR(2048),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
BDCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRINTCONTABILLALUR INTEGER = 0,
PRCODTERCEIRO INTEGER = 0,
PRCONTABILIZACAOLALUR integer = 0,
PRCODTPHISTLALUR integer = 0)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
MOVIMENTO NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER,
CHAVELAN INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_SALDO_NATUREZA_CONTA(PRVALOR NUMERIC(15,2),
PRGRUPO INTEGER,
PRCREDITA INTEGER)
 RETURNS(BDRESULT INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_SELECAO_TOMADOR(PRPLANO INTEGER,
PREMPRESA INTEGER)
 RETURNS(BDCODIGO INTEGER,
BDDESCRICAO DM_BDNOMEMP)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER procedure SP_VRH_SETA_ORIGEM_CALC (
    PRORIGEM integer)
as
begin
  /* Procedure Text */
  -- W_VRHIMPORTACAO
  rdb$set_context('USER_SESSION', 'W_VRHIMPORTACAO', CAST(PRORIGEM AS VARCHAR(3)));
end^

create or alter procedure SP_VRH_GET_ORIGEM_CALC
returns (
    BDORIGEM integer)
as
declare variable WVAL integer;
begin
  /* Procedure Text */
  SELECT cast(TRIM(rdb$get_context('USER_SESSION', 'W_VRHIMPORTACAO')) as integer) FROM rdb$database into :wval;

  if (coalesce(wval,0) = 0) then
     wval = 201;

  bdorigem = wval;

  suspend;
end^

/* Restore proc. body: SP_SETA_COMPETENCIA */
CREATE OR ALTER PROCEDURE SP_SETA_COMPETENCIA(PRANOMES INTEGER,
PRDATAPRIDIAMES DATE = NULL,
PRDATAULTDIAMES DATE = NULL)
 AS
DECLARE VARIABLE WREF VARCHAR(6);
BEGIN
  /*
    Seta 3 variáveis de contexto, na seção do usuário.
    Essas variáveis devem conter a competência atual.
    Essas variáveis são utilizadas como uma forma de passagem de parâmetro para view's.

    Para ler o conteudo da variável de contexto utilize a seguinte sintaxe:
      select rdb$get_context('USER_SESSION', 'W_ANOMES')
      from rdb$database
  */

  IF (PRANOMES IS NOT NULL) THEN
     BEGIN
       IF (PRANOMES = 0) THEN
          BEGIN
            -- Gilberto - 20/10/2014 - Não há necessidade de executar um sql nesse caso, alterei porque dava erro na execução do script "Procedures_and_views_and_trigger"
            --select SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) from 1 for 4)||SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) from 6 for 2) from RDB$DATABASE into :wref;
            wRef = SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 6 FOR 2);
          END
       ELSE
          wref = CAST(PRANOMES AS VARCHAR(6));

       rdb$set_context('USER_SESSION', 'W_ANOMES', wref);
     END
--  else
--     rdb$set_context('USER_SESSION', 'W_ANOMES', null);

  IF (PRDATAPRIDIAMES IS NOT NULL) THEN
     rdb$set_context('USER_SESSION', 'W_PRIDIAMES', CAST(PRDATAPRIDIAMES AS VARCHAR(10)));
--  else
--     rdb$set_context('USER_SESSION', 'W_PRIDIAMES', null);

  IF (PRDATAULTDIAMES IS NOT NULL) THEN
     rdb$set_context('USER_SESSION', 'W_ULTDIAMES', CAST(PRDATAULTDIAMES AS VARCHAR(10)));
--  else
--     rdb$set_context('USER_SESSION', 'W_ULTDIAMES', null);

END
^

/* Restore proc. body: SP_SETA_COMPETENCIA_PGTO */
create or alter procedure SP_SETA_COMPETENCIA_PGTO (
    PRANOMES integer,
    PRDATAPRIDIAMES date = null,
    PRDATAULTDIAMES date = null)
as
declare variable WREF varchar(6);
BEGIN
  /*
    Seta 3 variáveis de contexto, na seção do usuário.
    Essas variáveis devem conter a competência atual.
    Essas variáveis são utilizadas como uma forma de passagem de parâmetro para view's.

    Para ler o conteudo da variável de contexto utilize a seguinte sintaxe:
      select rdb$get_context('USER_SESSION', 'W_ANOMESPGTO')
      from rdb$database
  */

  IF (PRANOMES IS NOT NULL) THEN
     BEGIN
       IF (PRANOMES = 0) THEN
          BEGIN
            wRef = SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 6 FOR 2);
          END
       ELSE
          wref = CAST(PRANOMES AS VARCHAR(6));

       rdb$set_context('USER_SESSION', 'W_ANOMESPGTO', wref);
     END

  IF (PRDATAPRIDIAMES IS NOT NULL) THEN
     rdb$set_context('USER_SESSION', 'W_PRIDIAMESPGTO', CAST(PRDATAPRIDIAMES AS VARCHAR(10)));

  IF (PRDATAULTDIAMES IS NOT NULL) THEN
     rdb$set_context('USER_SESSION', 'W_ULTDIAMESPGTO', CAST(PRDATAULTDIAMES AS VARCHAR(10)));
END^


CREATE OR ALTER PROCEDURE SP_SETA_RECONTABILIZA(PRVALUE DM_BOOLEAN)
 AS
 BEGIN EXIT; END
^

create or alter procedure SP_SET_USUARIO_INTRANET (BDCODUSU integer, BDNOMUSU varchar(100))
as
begin exit; end
^

create or alter procedure SP_SET_MODULO (PRCODSIS integer)
as
begin
  exit;
end^

CREATE OR ALTER PROCEDURE SP_SETA_VARIAVEIS_SESSAO_BANCO(PRCODUSU INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_SOMENTE_ADMITIDOS_MES(PRDATAINI DATE,
PRDATAFIM DATE,
PRCODEMP INTEGER = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_SOMENTE_ATIVOS(PRDATAINI DATE,
PRDATAFIM DATE,
PRCODEMP INTEGER = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_SOMENTE_ATIVOS_RAIS (
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRCODEMP INTEGER = NULL)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_SOMENTE_ATIVOS_CAGED(PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_SOMENTE_DEMITIDOS(PRDATAFIM DATE,
PRCODEMP INTEGER = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_SOMENTE_DEMITIDOS_MES(PRDATAINI DATE,
PRDATAFIM DATE,
PRCODEMP INTEGER = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TEMPRESAIMPOSTO_REF(PRCODEMP VARCHAR(20000),
PRREFERENCIA INTEGER,
PRQUANTIDADE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDREFFIMIMP INTEGER,
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(100),
BDDATACRIACAO DATE,
BDDATAEXTINTO DATE,
BDCOMPETENCIA INTEGER,
BDDOCARRECADACAO INTEGER,
BDPERAPURACAO INTEGER,
BDDIAVENCTO INTEGER,
BDANTECIPA VARCHAR(5),
BDMESVENCTO INTEGER,
BDJUROSDIA INTEGER,
BDVLRJUROS NUMERIC(15,6),
BDJUROSDIAMES INTEGER,
BDMULTADIA INTEGER,
BDVLRMULTA NUMERIC(15,6),
BDMULTADIAMES INTEGER,
BDVLRMAXMULTA NUMERIC(15,6),
BDALIQIMPOSTO NUMERIC(15,6),
BDLIMITEISENCAO NUMERIC(15,6),
BDTIPORETENCAO INTEGER,
BDCODREC INTEGER,
BDCODIND INTEGER,
BDRETBCCALCULOIMP VARCHAR(5),
BDDESCREC VARCHAR(150),
BDTIPOIMPOSTO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TEMPRESAS_REF(PRAAAAMM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER,
BDCODCENTROS INTEGER,
BDCODCID INTEGER,
BDCODCONT INTEGER,
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDCNAEPREP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDAPEEMP DM_BDAPEMP,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDBAIEMP DM_BDBAIRRO,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDFAXEMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDLOGREMP VARCHAR(15),
BDIEEMP VARCHAR(20),
BDIMEMP VARCHAR(20),
BDSITEMP VARCHAR(5),
BDDDDFAXEMP INTEGER,
BDDOCAUXILIAR VARCHAR(18),
BDSUFRAMA VARCHAR(9))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TERCEIRO(PRCODTER INTEGER)
 RETURNS(BDCODTER INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCGCTER VARCHAR(18),
BDREFEMP INTEGER,
BDAPELIDOTER VARCHAR(20),
BDNOMETER VARCHAR(100),
BDLOGRTER VARCHAR(15),
BDENDTER DM_BDENDERECO,
BDNUMTER DM_NUMEND,
BDCOMPTER DM_BDCOMPENDERECO,
BDCEPTER VARCHAR(9),
BDBAITER DM_BDBAIRRO,
BDDDDTER VARCHAR(3),
BDFONETER DM_BDTELEFONE,
BDFAXTER DM_BDTELEFONE,
BDEMAILTER DM_BDEMAIL,
BDIETER VARCHAR(20),
BDDATACADTER DATE,
BDIMTER VARCHAR(16),
BDPRURALTER VARCHAR(5),
BDENQSIMPLESFEDTER INTEGER,
BDINSCSUFRAMATER VARCHAR(10),
BDCODGPS INTEGER,
BDCODCID INTEGER,
BDCODPAIS INTEGER,
BDDESCPAIS VARCHAR(60),
BDDDDFAXTER VARCHAR(3))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TIPO_INS_SEFIP(PRINSC VARCHAR(18))
 RETURNS(BDTIPOINS VARCHAR(1))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TOL_VSUC_EMPRESAS_TLAN(PRCHAVE INTEGER,
PRCHAVETITULO INTEGER,
PRTIPOLAN INTEGER,
PRPLANOONLINE INTEGER,
PRVALOR VARCHAR(50))
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_TOMADOR_SEFIP RETURNS(BDCNPJ VARCHAR(20),
BDNOME DM_BDNOMEMP,
BDENDERECO DM_BDENDERECO,
BDBAIRRO DM_BDBAIRRO,
BDCEP VARCHAR(9),
BDCIDADE VARCHAR(40),
BDUF VARCHAR(2),
BDCODGPS VARCHAR(4))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TREEVIEW_CONF_DEPARA_ONLINE(PRPLANO_DE INTEGER,
PRPLANO_PARA INTEGER,
PRCODINT INTEGER,
PRPLANOCONTASANT INTEGER,
PRPLANOCONTASATU INTEGER,
PRPLANOHISTANT INTEGER,
PRPLANOHISTATU INTEGER,
PRCLASSIFICACAO VARCHAR(100),
PRLENGTH INTEGER,
PRREF INTEGER,
PRCHAVE INTEGER,
PRAPENASNIVEL INTEGER,
PRFILTERCLASSIFICACAO DM_MAXVARCHAR = '',
PRCONFAUT INTEGER = 0)
 RETURNS(BDFORMULA VARCHAR(80),
BDFORMULAITEM VARCHAR(80),
BDCONFIGTIT DM_BOOLEAN,
BDCLASSIFICACAO VARCHAR(100),
BDDESCRICAO VARCHAR(500),
BDAPECTADV VARCHAR(20),
BDAPECTACV VARCHAR(20),
BDAPECTADO VARCHAR(20),
BDAPECTACO VARCHAR(20),
BDDESCONTADV VARCHAR(100),
BDDESCONTACV VARCHAR(100),
BDDESCONTADO VARCHAR(100),
BDDESCONTACO VARCHAR(100),
BDCODHISTPROV INTEGER,
BDCODHISTPGTO INTEGER,
BDCODTIPOCONTA INTEGER,
BDCODNAT INTEGER,
BDCODVER INTEGER,
BDDESCREDVER VARCHAR(20),
BDAPELIDOTER VARCHAR(20),
BDNOMENAT VARCHAR(335),
BDAPEHISTPROV VARCHAR(20),
BDAPEHISTPGTO VARCHAR(20),
BDCONTADEBPROV INTEGER,
BDCONTACREDPROV INTEGER,
BDCONTADEBPGTO INTEGER,
BDCONTACREDPGTO INTEGER,
BDCHAVE INTEGER,
BDCHAVEVINC INTEGER,
BDCODPLANOONLINE INTEGER,
BDDESCIMP VARCHAR(100),
BDDESCOREC VARCHAR(100),
BDCODOREC INTEGER,
BDCODIMP INTEGER,
BDCODTCA INTEGER,
BDCODGRUPOCLA INTEGER,
BDDESCGRUPOCLA VARCHAR(200),
BDTIPONAT INTEGER,
BDCLASSVER VARCHAR(20),
BDTIPOVER INTEGER,
BDCODITEMONLINE INTEGER,
BDAPECOMHISTPROV VARCHAR(20),
BDAPECOMHISTPGTO VARCHAR(20),
BDCODCOMPHISTPROV INTEGER,
BDCODCOMPHISTPGTO INTEGER,
BDCOMHISTPROV VARCHAR(1000),
BDCOMHISTPGTO VARCHAR(1000),
BDCONFIGPROV DM_BOOLEAN,
BDCONFIGDEBPROV DM_BOOLEAN,
BDCONFIGCREDPROV DM_BOOLEAN,
BDCONFIGPAG DM_BOOLEAN,
BDCONFIGDEBPAG DM_BOOLEAN,
BDCONFIGCREDPAG DM_BOOLEAN,
BDCONFIGHISTPROV DM_BOOLEAN,
BDCONFIGHISTPAG DM_BOOLEAN,
BDNAOCONTAB DM_BOOLEAN,
BDCODREC INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(42),
BDCODTPHIST INTEGER,
BDAPELIDOHIST VARCHAR(20),
BDCHAVE_PARA INTEGER,
BDCODMASTER INTEGER,
BDPODEEDITAR DM_BOOLEAN,
BDCLASSIFICACAOORI VARCHAR(100),
BDCODOBRSER INTEGER,
BDCHAVECTABAN INTEGER,
BDCODCLI INTEGER,
BDCODDESP INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TREEVIEW_CONS_ANUAL_CONF(PRSISTEMA INTEGER,
PRCODEMP VARCHAR(10000),
PRREF INTEGER,
PRCODQUADRO INTEGER,
PRDETALHAQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDREF INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDORDEM INTEGER,
BDDESCRICAO VARCHAR(80),
BDVALOR NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDJAN NUMERIC(15,6),
BDFEV NUMERIC(15,6),
BDMAR NUMERIC(15,6),
BDABR NUMERIC(15,6),
BDMAI NUMERIC(15,6),
BDJUN NUMERIC(15,6),
BDJUL NUMERIC(15,6),
BDAGO NUMERIC(15,6),
BDSET NUMERIC(15,6),
BDOUT NUMERIC(15,6),
BDNOV NUMERIC(15,6),
BDDEZ NUMERIC(15,6),
BDANOSWS VARCHAR(4))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TREEVIEW_CONS_CONF_ONLINE (
    PRPLANO INTEGER,
    PRCLASSIFICACAO VARCHAR(100),
    PRLENGTH INTEGER,
    PRREF INTEGER,
    PRCHAVE INTEGER,
    PRAPENASNIVEL INTEGER,
    PRFILTERCLASSIFICACAO DM_MAXVARCHAR = '',
    PRFILTRERTREEVIEW VARCHAR(200) = '',
    PRORDENACAO INTEGER = 0,
    PRCODIGO_TREEVIEW INTEGER = -1,
    PRFORCEDESCRICAO SMALLINT = 0,
    PRCONTAPREP integer = 0)
RETURNS (
    BDFORMULA VARCHAR(80),
    BDFORMULAITEM VARCHAR(80),
    BDCONFIGTIT VARCHAR(5),
    BDCLASSIFICACAO VARCHAR(100),
    BDDESCRICAO VARCHAR(500),
    BDAPECTADV VARCHAR(20),
    BDAPECTACV VARCHAR(20),
    BDAPECTADO VARCHAR(20),
    BDAPECTACO VARCHAR(20),
    BDDESCONTADV VARCHAR(100),
    BDDESCONTACV VARCHAR(100),
    BDDESCONTADO VARCHAR(100),
    BDDESCONTACO VARCHAR(100),
    BDCODHISTPROV INTEGER,
    BDCODHISTPGTO INTEGER,
    BDCODTIPOCONTA INTEGER,
    BDCODNAT INTEGER,
    BDCODVER INTEGER,
    BDDESCREDVER VARCHAR(20),
    BDAPELIDOTER VARCHAR(20),
    BDNOMENAT VARCHAR(335),
    BDAPEHISTPROV VARCHAR(20),
    BDAPEHISTPGTO VARCHAR(20),
    BDCONTADEBPROV INTEGER,
    BDCONTACREDPROV INTEGER,
    BDCONTADEBPGTO INTEGER,
    BDCONTACREDPGTO INTEGER,
    BDCHAVE INTEGER,
    BDCHAVEVINC INTEGER,
    BDCODPLANOONLINE INTEGER,
    BDDESCIMP VARCHAR(100),
    BDDESCOREC VARCHAR(100),
    BDCODOREC INTEGER,
    BDCODIMP INTEGER,
    BDCODTCA INTEGER,
    BDCODGRUPOCLA INTEGER,
    BDDESCGRUPOCLA VARCHAR(200),
    BDTIPONAT INTEGER,
    BDCLASSVER VARCHAR(20),
    BDTIPOVER INTEGER,
    BDCODITEMONLINE INTEGER,
    BDAPECOMHISTPROV VARCHAR(20),
    BDAPECOMHISTPGTO VARCHAR(20),
    BDCODCOMPHISTPROV INTEGER,
    BDCODCOMPHISTPGTO INTEGER,
    BDCOMHISTPROV VARCHAR(1000),
    BDCOMHISTPGTO VARCHAR(1000),
    BDCONFIGPROV VARCHAR(5),
    BDCONFIGDEBPROV VARCHAR(5),
    BDCONFIGCREDPROV VARCHAR(5),
    BDCONFIGPAG VARCHAR(5),
    BDCONFIGDEBPAG VARCHAR(5),
    BDCONFIGCREDPAG VARCHAR(5),
    BDCONFIGHISTPROV VARCHAR(5),
    BDCONFIGHISTPAG VARCHAR(5),
    BDNAOCONTAB VARCHAR(5),
    BDCODREC INTEGER,
    BDCONTABILIZA DM_BOOLEAN,
    BDATIVA DM_BOOLEAN,
    BDCODOBRSER INTEGER,
    BDTIPOSER INTEGER,
    BDSERDESCONTO DM_BOOLEAN,
    BDCHAVECTABAN INTEGER,
    BDCODCLI INTEGER,
    BDCODPLAPADRAO integer,
    BDCODDESP integer,
    BDDESCDESP varchar(100),
    BDTIPODESP integer,
    BDDESPDESCONTO varchar(5),
    bdrefcta INTEGER
)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TREEVIEW_PREP_CONTA (
    PRPLANOONLINE integer,
    PRREF integer,
    PRCONTA integer)
RETURNS (
    BDCLASSIFICACAO varchar(100),
    BDCONTADEBPROV integer,
    BDCONTACREDPROV integer,
    BDDESCRICAO varchar(100),
    BDCODVER integer,
    BDCHAVE integer
)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TREEVIEW_CONS_FORM_PAD_EF(PRPLANO INTEGER,
PRCLASSQUADRO VARCHAR(10),
PRGRUPO INTEGER,
PRTPIMP VARCHAR(10))
 RETURNS(BDCODPLANO INTEGER,
BDDESCPLANO VARCHAR(150),
BDNUMITEM INTEGER,
BDDESCFORM VARCHAR(150),
BDFORMULA VARCHAR(10000),
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(150),
BDCLASSIFICACAO VARCHAR(10),
BDCODITEMONLINE INTEGER,
BDDESCCODITEMONLINE VARCHAR(200))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TREEVIEW_CONS_GIA_FORMULA(PRPLANO INTEGER,
PRCLASSQUADRO VARCHAR(10),
PRGRUPO INTEGER,
PRUF VARCHAR(2))
 RETURNS(BDCODPLANO INTEGER,
BDDESCPLANO VARCHAR(100),
BDNUMITEM INTEGER,
BDDESCFORM VARCHAR(100),
BDFORMULA VARCHAR(10000),
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(100),
BDCLASSIFICACAO VARCHAR(11),
BDCODITEMONLINE INTEGER,
BDDESCCODITEMONLINE VARCHAR(300))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TREEVIEW_CONS_IMP_EMITIDOS(PRONLINE VARCHAR(10000),
PRCODEMP VARCHAR(10000),
PRCODIMP VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PRGRUPO INTEGER,
PRDTVCTOINI DATE,
PRDTVCTOFIM DATE,
PRPERIODO INTEGER,
PRFILTRO INTEGER,
PRSICALCIC varchar(5))
 RETURNS(BDCODEMP INTEGER,
BDCHAVEDARF INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(200),
BDCODPERIODO INTEGER,
BDORDEM INTEGER,
BDREFERENCIA INTEGER,
BDQUOTA INTEGER,
BDCODTPCC INTEGER,
BDDATAVCTO DATE,
BDVALOR NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDJUROS NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDOBS BLOB,
BDORDEMCOMPL INTEGER,
BDBASEIMP NUMERIC(15,6),
BDALIQIMP NUMERIC(15,6),
BDVLRIMPORIGINAL NUMERIC(15,6),
BDVLRMULTAJUROS NUMERIC(15,6),
BDVLROUTENTIDADE NUMERIC(15,6),
BDDTPGTO DATE,
BDLIMITEISENCAO NUMERIC(15,6),
BDDOCARRECADACAO INTEGER,
BDFORMREL VARCHAR(1000),
BDCODREC INTEGER,
BDVLRRETENCAO NUMERIC(15,2),
BDDESCTIPOCALC VARCHAR(25),
BDFLAG VARCHAR(5),
BDVLRACUMULO NUMERIC(15,6),
BDCNPJDARF varchar(18),
BDCODEMPSCP integer,
BDCOMPENSACAODCOMP DM_NUMERIC_15_2)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_UNION_FN_FC RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDCODVER INTEGER,
BDREFVFN NUMERIC(15,6),
BDREFAUXVFN NUMERIC(15,6),
BDVALVFN NUMERIC(15,6),
BDBFGTSFN NUMERIC(15,6),
BDFGTSFN NUMERIC(15,6),
BDFGTSCSFN NUMERIC(15,6),
BDBFGTS13FN NUMERIC(15,6),
BDFGTS13FN NUMERIC(15,6),
BDFGTS13CSFN NUMERIC(15,6),
BDMAIORREMFN NUMERIC(15,6),
BDBINSSFN NUMERIC(15,6),
BDALIQINSSFN NUMERIC(15,6),
BDINSSFN NUMERIC(15,6),
BDBIRRFFN NUMERIC(15,6),
BDALIQIRRFFN NUMERIC(15,6),
BDIRRFFN NUMERIC(15,6),
BDBINSS13FN NUMERIC(15,6),
BDALIQINSS13FN NUMERIC(15,6),
BDINSS13FN NUMERIC(15,6),
BDBIRRF13FN NUMERIC(15,6),
BDALIQIRRF13FN NUMERIC(15,6),
BDIRRF13FN NUMERIC(15,6),
BDBSALFAMFN NUMERIC(15,6),
BDSALFAMFN NUMERIC(15,6),
BDBRAISFN NUMERIC(15,6),
BDSALBASEFN NUMERIC(15,6),
BDDEPFN NUMERIC(15,6),
BDIGNREFVFN VARCHAR(5),
BDIGNREFAVFN VARCHAR(5),
BDIGNVALVFN VARCHAR(5),
BDTIPO INTEGER,
BDBFGTSFEFN NUMERIC(15,6),
BDFGTSFEFN NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_UPDATE_VERBA_ONLINE(PRCLAANT VARCHAR(1000),
PRCLANOVA VARCHAR(1000),
PRCODVER INTEGER)
 AS
 BEGIN EXIT; END
^

create or alter procedure SP_VAL_GPS_PROV_13 (
    PRREFERENCIA integer,
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000))
returns (
    BDREFERENCIA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODTER integer,
    BDTIPOIMPOSTO integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(15,6),
    BDTERCFN numeric(15,6),
    BDRATFN numeric(15,6),
    BDRATAPOFN numeric(15,6),
    BDINSS13 numeric(15,6),
    BDTERC13 numeric(15,6),
    BDRAT13 numeric(15,6),
    BDRATAPO13 numeric(15,6),
    BDINSS13IND numeric(15,6),
    BDTERC13IND numeric(15,6),
    BDRAT13IND numeric(15,6),
    BDRATAPO13IND numeric(15,6),
    BDINSSC13 numeric(15,6),
    BDTERCC13 numeric(15,6),
    BDRATC13 numeric(15,6),
    BDRATAPOC13 numeric(15,6),
    BDINSSPBM13 numeric(15,6))
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VAL_GPS_PROV_FER (
    PRREFERENCIA integer,
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000))
returns (
    BDREFERENCIA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODTER integer,
    BDTIPOIMPOSTO integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(15,6),
    BDTERCFN numeric(15,6),
    BDRATFN numeric(15,6),
    BDRATAPOFN numeric(15,6),
    BDINSSPBMFN numeric(15,6),
    BDINSSREONERACAOFN numeric(15,6))
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VAL_HE_RAIS_FF(PREMP INTEGER,
PRCOL INTEGER,
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDHE NUMERIC(15,6),
BDCODVER INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VAL_RAIS_FF(PREMP INTEGER = 0,
PRCOL INTEGER = 0,
PRANO INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDAVPREV NUMERIC(15,6),
BDFERIND NUMERIC(15,6),
BDGRATIF NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDSINDICAL NUMERIC(15,6),
BDASSISTENCIAL NUMERIC(15,6),
BDCONFEDERATIVA NUMERIC(15,6),
BDBASEFN NUMERIC(15,6),
BDBASEA13 NUMERIC(15,6),
BDBASE13 NUMERIC(15,6),
BDBASEC13 NUMERIC(15,6),
BDORIGEM INTEGER,
BDMENSALIDADE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_BASE_TCONFDACOM1424(PRCODCONF INTEGER)
 RETURNS(BDCODCONFDACON INTEGER,
BDCODQDACON INTEGER,
BDCODTIPOCRE INTEGER,
BDNUMCAMPODACON INTEGER,
BDNUMITEM INTEGER,
BDDESCFORMDACON VARCHAR(150),
BDFORMULADACON VARCHAR(15000),
BDFORMULADACON2 VARCHAR(15000),
BDFORMULADACON3 VARCHAR(15000),
BDCODTIPO INTEGER,
BDCAMPOINATIVO VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_EMP_PODEEXCLUIRVINCPROD(PRCODEMP INTEGER,
PRCODPROD INTEGER)
 RETURNS(BDTABELA_VINCULADA VARCHAR(100))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_ENT_FORMULAS_DAPI(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDCODNAT INTEGER,
BDCODOPDAPI INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDBASEICMS NUMERIC(15,2),
BDVLRICMS NUMERIC(15,2),
BDISENTASICMS NUMERIC(15,2),
BDVLRST NUMERIC(15,2),
BDIMPAPCREDDAPI NUMERIC(15,2),
BDISENTASDAPI NUMERIC(15,2),
BDNTRIBDAPI NUMERIC(15,2),
BDPARBCCREDDAPI NUMERIC(15,2),
BDDIFERIDASTDAPI NUMERIC(15,2),
BDSUSPENSASDAPI NUMERIC(15,2),
BDSTDAPI NUMERIC(15,2),
BDOUTRASDAPI NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VEF_DAS_TOTALIZADOR_UF (
    PREMP varchar(3000),
    PRDATAINI varchar(10),
    PRDATAFIM varchar(10),
    PRREF integer,
    PRREGIMECAIXA varchar(5))
returns (
    BDCODEMP integer,
    BDSIGLAUF varchar(2),
    BDNOMCID varchar(40),
    BDCODBASESN integer,
    BDVLRBASE numeric(18,2),
    BDCODFED integer,
    BDCODTIPOIMPPIS integer,
    BDCODTIPOIMPCOFINS integer,
    BDCODTIPOIMPCSLL integer,
    BDCODTIPOIMPICMS integer,
    BDCODTIPOIMPINSSCPP integer,
    BDCODTIPOIMPIRPJ integer,
    BDCODTIPOIMPIPI integer,
    BDCODTIPOIMPISS integer)
as
  BEGIN SUSPEND; END
^

CREATE OR ALTER procedure SP_VEF_EXPREG30_GIASP (
    PRCODEMP varchar(10000),
    PRREFERENCIAINICIAL integer,
    PRREFERENCIAFINAL integer)
returns (
    BDCODEMP integer,
    BDREFERENCIA integer,
    BDCODEST integer,
    BDCODDIPAM varchar(3),
    BDVALOR numeric(18,6),
    BDCODCID integer,
    BDDIPAMB varchar(5))
as
begin
  SUSPEND;
end
^

CREATE OR ALTER PROCEDURE SP_VEF_FILTRO_NOTAS_NAO_LANCADA(PRCODEMP INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRNUMDOCINI INTEGER,
PRNUMDOCFIN INTEGER,
PRESPECIE VARCHAR(5),
PRSERIE VARCHAR(6),
PRSERVICO_SAIDA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNUMDOC INTEGER,
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_LIVROENTRADA(PRCODEMP VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRIMPSUFIXONAT INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDDATAENTRADAENT DATE,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDCODTER INTEGER,
BDCODCID INTEGER,
BDNOMETER VARCHAR(100),
BDCGCTER VARCHAR(18),
BDIETER VARCHAR(20),
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(12),
BDNUMDOCINI INTEGER,
BDDATAEMISSAO DATE,
BDSIGLAUF VARCHAR(2),
BDCODSITNF INTEGER,
BDVLRCONTAB NUMERIC(18,6),
BDPREFIXONAT INTEGER,
BDBASEICMS NUMERIC(18,6),
BDBASEICMSVARALIQ NUMERIC(18,6),
BDALIQICMS NUMERIC(18,6),
BDVLRICMS NUMERIC(18,6),
BDISENTASICMS NUMERIC(18,6),
BDOUTRASICMS NUMERIC(18,6),
BDBASEIPI NUMERIC(18,6),
BDDIFALIQENT NUMERIC(18,6),
BDVLRIPI NUMERIC(18,6),
BDISENTASIPI NUMERIC(18,6),
BDOUTRASIPI NUMERIC(18,6),
BDBASEST NUMERIC(18,6),
BDVLRST NUMERIC(18,6),
BDNOMEOBS VARCHAR(100),
BDLINHABRANCO VARCHAR(1),
BDLANCVARALIQ INTEGER,
BDVALNTRIBST NUMERIC(18,6),
BDICMSRETENT NUMERIC(18,6),
BDBCSTNAORET NUMERIC(18,6),
BDVLRSTNAORET NUMERIC(18,6),
BDBCSTNAORETRE NUMERIC(18,6),
BDVLRSTNAORETRE NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_LIVROSAIDA(PRCODEMP VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRIMPSUFIXONAT integer,
PRDEDUZIPIICMSOUTRAS varchar(5))
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDDATAEMISSAO DATE,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDCODTER INTEGER,
BDCODCID INTEGER,
BDNOMETER VARCHAR(100),
BDCGCTER VARCHAR(18),
BDIETER VARCHAR(20),
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6),
BDNUMDOCINI INTEGER,
BDNUMDOCFIM INTEGER,
BDCODSITNF INTEGER,
BDSIGLAUF VARCHAR(2),
BDVLRCONTAB NUMERIC(18,6),
BDPREFIXONAT INTEGER,
BDBASEICMS NUMERIC(18,6),
BDALIQICMS NUMERIC(18,6),
BDVLRICMS NUMERIC(18,6),
BDISENTASICMS NUMERIC(18,6),
BDOUTRASICMS NUMERIC(18,6),
BDBASEIPI NUMERIC(18,6),
BDVLRIPI NUMERIC(18,6),
BDISENTASIPI NUMERIC(18,6),
BDOUTRASIPI NUMERIC(18,6),
BDBASEST NUMERIC(18,6),
BDVLRST NUMERIC(18,6),
BDNOMEOBS VARCHAR(100),
BDLINHABRANCO VARCHAR(1),
BDIMPSOMENTECFOP VARCHAR(1),
BDVLRCONTABTOT NUMERIC(18,6),
BDLANCVARALIQ INTEGER,
BDSAIREDZ VARCHAR(1))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE CLEARALLGLOBALTEMPORARYTABLE
AS
DECLARE VARIABLE wtabela VARCHAR(64);
BEGIN
  FOR SELECT RDB$RELATION_NAME FROM RDB$RELATIONS
             WHERE RDB$RELATION_TYPE IN (4,5)
             ORDER BY RDB$RELATION_NAME
      INTO :wtabela DO
      EXECUTE STATEMENT 'delete from '||wtabela;

END
^

CREATE OR ALTER PROCEDURE SP_VEF_REL_APURACAO_GIAMG(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDREFERENCIA INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDNUMITEM INTEGER,
BDAREACONS VARCHAR(10),
BDESCCENTRAL VARCHAR(5),
BDTITULO VARCHAR(60),
BDREGISTRO VARCHAR(60),
BDSUBTITULO VARCHAR(80))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VEF_REL_RETENCOES (
    PRCODEMP varchar(10000),
    PRDATAINICIAL date,
    PRDATAFINAL date,
    PRTIPOMOV integer,
    PRCODTER integer,
    PRDETALHADO integer,
    PRTIPOLANSERV integer,
    PRTIPOAPURACAORETIR varchar(50),
    PRSOMAMATRIZFILIAL integer,
    PRVERORGAOPUBLICO varchar(5),
    PRCAMPODATA varchar(200))
returns (
    BDCODEMP integer,
    BDREF integer,
    BDMESEXTENSO varchar(20),
    BDCODTER integer,
    BDNOMETER varchar(100),
    BDCGCTER varchar(18),
    BDENDTER varchar(60),
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDVLRCONTAB numeric(15,2),
    BDVLRPIS numeric(15,2),
    BDVLRCOFINS numeric(15,2),
    BDVLRCSOCIAL numeric(15,2),
    BDVLRIR numeric(15,2),
    BDVLRINSS numeric(15,2),
    BDVLRISS numeric(15,2),
    BDVLRIRSER numeric(15,2),
    BDCONDPGTO integer)
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_RETORNA_SALDO_DIME(PRCODEMP VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRREFEMP INTEGER,
PRANO INTEGER,
PRCONTABILIZACAO INTEGER)
 RETURNS(BDCODMATRIZ INTEGER,
BDCODEMP INTEGER,
BDQUADRO VARCHAR(5),
BDCODEXP INTEGER,
BDSALDO NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_ANUAL_CON2(PRCODEMP VARCHAR(10000),
PRREF INTEGER,
PRCODQUADRO INTEGER,
PRDETALHAQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDREF INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDORDEM INTEGER,
BDDESCRICAO VARCHAR(80),
BDVALOR NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDJAN NUMERIC(15,6),
BDFEV NUMERIC(15,6),
BDMAR NUMERIC(15,6),
BDABR NUMERIC(15,6),
BDMAI NUMERIC(15,6),
BDJUN NUMERIC(15,6),
BDJUL NUMERIC(15,6),
BDAGO NUMERIC(15,6),
BDSET NUMERIC(15,6),
BDOUT NUMERIC(15,6),
BDNOV NUMERIC(15,6),
BDDEZ NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_BLOCOP(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO VARCHAR(1000),
PRCLASSIFICACAO VARCHAR(10),
PRGERAL INTEGER,
PREMPFIL INTEGER,
PRCODIGOAJUSTE VARCHAR(8))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP VARCHAR(100),
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM DM_BDNOMEMP,
BDVALOR NUMERIC(15,2),
BDANOMESINICIAL INTEGER,
BDANOMESFINAL INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDCODEMPFILIAL INTEGER,
BDORDENATVPREV INTEGER,
BDCODIGOATVPREV VARCHAR(8),
BDDESCPREV VARCHAR(550),
BDNOMEMPFIL VARCHAR(100),
BDCODTIPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_CALCATIVO(PRCODEMP VARCHAR(10000),
PRCODBEM VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PRGRUPO VARCHAR(30))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODBEM INTEGER,
BDNOMBEM VARCHAR(200),
BDREFERENCIA INTEGER,
BDFATOR NUMERIC(15,6),
BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_DACON(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO VARCHAR(1000),
PRCODQUADRO INTEGER,
PRGERAL INTEGER,
PRTIPO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(160),
BDDESCFORM VARCHAR(160),
BDVALOR NUMERIC(18,6),
BDVALOR2 NUMERIC(18,6),
BDVALOR3 NUMERIC(18,6),
BDNUMITEM INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDCODREC INTEGER,
BDTIPOCREDITO INTEGER,
BDTIPOCONFDACON INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_DIME(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCODQUADRO INTEGER,
PRCODQUADROPRINC INTEGER,
PRGERAL INTEGER)
returns (
BDCODEMP integer,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCODQUADROPRINC INTEGER,
BDCLASSIFICACAO VARCHAR(5),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,6),
BDCODTIPO INTEGER,
BDCODNAT INTEGER,
BDDATAREC DATE,
BDCLAVENDIMEGERQ12 INTEGER,
BDCODRECDIMEGERQ12 INTEGER,
BDORIGEMDIMEGERQ46 INTEGER,
BDNUMITEM INTEGER,
BDANOMESINICIAL INTEGER,
BDANOMESFINAL INTEGER,
BDNUMACORDOQ12 varchar(15),
BDCODBENEFTTD integer,
BDVLRBCICMS numeric(15,2),
BDVLRICMSEXON numeric(15,2),
BDORDEMFUMDES integer,
BDVLRFUMDES numeric(15,2),
BDVLRFUMDESDEV numeric(15,2),
BDORDEMFUNSOC integer,
BDVLRFUNSOC numeric(15,2),
BDVLRFUNSOCDEV numeric(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIAES(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER,
PRTIPOAPU INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDTIPO INTEGER,
BDNUMITEM INTEGER,
BDTIPOAPU INTEGER,
BDCODNAT INTEGER,
BDAUXCFOP INTEGER,
BDORDEMTTNAT INTEGER,
BDCLASSNATGRUP VARCHAR(20),
BDDESCTTNAT VARCHAR(20),
BDTITULOGRUPO VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIAMG(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDCODNAT INTEGER,
BDTIPO INTEGER,
BDNUMITEMORDEM varchar(5),
BDNUMITEM varchar(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIAPR(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER,
PRCODNAT INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDCODNAT INTEGER,
BDTIPO INTEGER,
BDNUMITEM INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIARJ (
    PRCODEMP VARCHAR(10000),
    PRANOMESINICIAL INTEGER,
    PRANOMESFINAL INTEGER,
    PRCODPERIODO INTEGER,
    PRCLASSIFICACAO VARCHAR(11),
    PRGERAL INTEGER,
    PRCODQUADRO INTEGER,
    PRCODNAT INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCONF INTEGER,
    BDREFERENCIA INTEGER,
    BDCODPERIODO INTEGER,
    BDNUMCAMPO INTEGER,
    BDCODQUADRO INTEGER,
    BDCLASSIFICACAO VARCHAR(10),
    BDDESCQUADRO VARCHAR(80),
    BDDESCFORM VARCHAR(150),
    BDVALOR NUMERIC(15,2),
    BDCODTIPO INTEGER,
    BDCODNAT INTEGER,
    BDTIPO INTEGER,
    BDNUMITEM INTEGER)
AS
  BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIATO (
    PRCODEMP VARCHAR(10000),
    PRANOMESINICIAL INTEGER,
    PRANOMESFINAL INTEGER,
    PRCODPERIODO INTEGER,
    PRCLASSIFICACAO VARCHAR(11),
    PRGERAL INTEGER,
    PRCODQUADRO INTEGER,
    PRCODNAT INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCONF INTEGER,
    BDREFERENCIA INTEGER,
    BDCODPERIODO INTEGER,
    BDNUMCAMPO INTEGER,
    BDCODQUADRO INTEGER,
    BDCLASSIFICACAO VARCHAR(10),
    BDDESCQUADRO VARCHAR(80),
    BDDESCFORM VARCHAR(150),
    BDVALOR NUMERIC(15,2),
    BDCODTIPO INTEGER,
    BDCODNAT INTEGER,
    BDTIPO INTEGER,
    BDNUMITEM INTEGER)
AS
  BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIARO(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDTIPO INTEGER,
BDNUMITEM INTEGER,
BDCODNAT INTEGER,
BDORDEMTTNAT INTEGER,
BDTITULOGRUPO VARCHAR(80))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIASP(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(10),
PRGERAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(5),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,6),
BDCODTIPO INTEGER,
BDCODNAT INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_ICMSSPED(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO VARCHAR(1000),
PRCODQUADRO INTEGER,
PRGERAL INTEGER,
PRUF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(150),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(18,6),
BDNUMITEM INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2),
BDCODTIPOVALAGRE INTEGER,
BDDESCRICAO VARCHAR(150),
BDCODTIPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_IMPOSTOS(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO VARCHAR(1000),
PRCODQUADRO INTEGER,
PRGERAL INTEGER,
PRSIGLAIMPOSTO VARCHAR(10))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(60),
BDVALOR NUMERIC(15,8),
BDANOMESINICIAL INTEGER,
BDANOMESFINAL INTEGER,
BDCLASSIFICACAO VARCHAR(10))
 AS
 BEGIN SUSPEND; 
END^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_IPI(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODQUADRO INTEGER,
PRGERAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(60),
BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_IRLP(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODQUADRO INTEGER,
PRGERAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(60),
BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONSUF_GIASP(PRCODEMP INTEGER,
PRREFERENCIA INTEGER,
PRNATENTSAI INTEGER,
PRPREFIXONAT INTEGER,
PRSIGLAUF VARCHAR(2))
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDNUMCAMPO INTEGER,
BDSIGLAUF VARCHAR(2),
BDPREFIXONAT INTEGER,
BDDESCRICAO VARCHAR(100),
BDVALOR NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VERIFICATODASVERBASEMPPADRAO AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_VRH_APAGACALCULOS(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRCODAUT INTEGER,
PRREF INTEGER,
PRREFPAG INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_VRH_BASE_MTE_TCONFRESC RETURNS(BDCHAVECONF INTEGER,
BDDESCRICAO DM_BDDESCCONFMTE,
BDCLASSIFICACAO DM_BDCLASSCONFMTE,
BDIMPZERADO VARCHAR(5),
BDINCSUBGRUPO VARCHAR(5),
BDFIXA VARCHAR(5),
BDCODCOMPHIST INTEGER,
BDCLASSCONF DM_BDCLASSCONFMTE,
BDPADRAO VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_BASE_TRESPEMP_PRINCIPAL(PRCODEMP VARCHAR(25000),
PRCODRESP VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCODRESP INTEGER,
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDNOMERESP VARCHAR(40),
BDCPFRESP VARCHAR(14),
BDNITRESP VARCHAR(14),
BDDDDRESP INTEGER,
BDFONERESP DM_BDTELEFONE,
BDRAMALRESP INTEGER,
BDRGRESP VARCHAR(13),
BDPADRAORESP VARCHAR(5),
BDEMAILRESP DM_BDEMAIL)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_CC_DATA(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRDATA DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDDATAENTRADA DATE,
BDORDEM INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_DECLARARENDPLANSAU_SOCIO (
    PRCODEMP VARCHAR(32000),
    PRCODCOL VARCHAR(32000),
    PRANOBASE INTEGER,
    PRSOMENTESOCIOS VARCHAR(5) = '',
    PRWHERENOTCODEMP VARCHAR(32000) = '',
    PRWHERENOTSOCIOS VARCHAR(32000) = '',
    PRWHERENOTCONVENIO VARCHAR(32000) = '',
    PRCODDEP INTEGER = NULL,
    PRCNPJCONVENIO VARCHAR(18) = '',
    PRCPFSOCIO VARCHAR(14) = '')
RETURNS (
    BDCODEMP INTEGER,
    BDCODSOC INTEGER,
    BDCNPJ VARCHAR(18),
    BDRAZAOSOCIAL VARCHAR(80),
    BDCODDEP INTEGER,
    BDNOME VARCHAR(70),
    BDCPF VARCHAR(14),
    BDVALORPLANO INTEGER,
    BDCODCONVENIO INTEGER,
    BDCODCOL INTEGER)
AS
BEGIN SUSPEND; END   
^

CREATE OR ALTER PROCEDURE SP_VRH_EMP_MULTVINC_PGTO(PREMPRESA VARCHAR(32000),
PRCOL VARCHAR(32000),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFCOL INTEGER,
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_EMP_TCOLCON_VINC(PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDGRUPOCLA INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_FECHAMENTO(PREMPRESAS VARCHAR(32000),
PRREF INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDFECHAMENTO INTEGER,
BDDATA DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_RETORNA_CONTR_SIND (
    PREMPRESA VARCHAR(15000),
    PRCOLABORADOR VARCHAR(30000),
    PRREF INTEGER,
    PRMENSIND INTEGER,
    PRCONTSIND INTEGER,
    PRCONTCONF INTEGER,
    PRTAXAASSIS INTEGER,
    PRREVSAL INTEGER) 
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDNOMCOL VARCHAR(70),
    BDREF INTEGER,
    MENSALIDADE NUMERIC(15,6),
    CONTSIND NUMERIC(15,6),
    CONTCONF NUMERIC(15,6),
    TAXAS NUMERIC(15,6),
    REVERSAO NUMERIC(15,6),
    BDCODSINTRAB INTEGER,
    BDDESCSINTRAB VARCHAR(60)) 
AS BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_ADSALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATA VARCHAR(6),
PRMESESANTERIORES SMALLINT,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDATAAD DATE,
BDREF INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_CALCAUT(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRMESESANTERIORES SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFFN INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_CALCULO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRMESESANTERIORES SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFFN INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_CALCULOFC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRMESESANTERIORES SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFCOMP INTEGER,
BDDATAPAGFC DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_CALCULOPR(PRMESESANTERIORES SMALLINT, PRANOMES INTEGER, PRCODEMP VARCHAR(10000), PRCODCOL VARCHAR(32700))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFFNPR INTEGER,
BDDATARESCISAOPREV DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_COMP13SAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRMESESANTERIORES SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFC13 INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_FOLAVUL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATA VARCHAR(6),
PRMESESANTERIORES SMALLINT,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDATAFA DATE,
BDREF INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_TVERBAS_REF(PRANOMES INTEGER)
 RETURNS(BDCODVER INTEGER,
BDREFVER INTEGER,
BDTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDMENORESVER VARCHAR(5),
BDPROPVER VARCHAR(5),
BDBASEVTVER VARCHAR(5),
BDREEMBGPSVER VARCHAR(5),
BDHEVER NUMERIC(15,6),
BDGRAVAFICHAHNVER VARCHAR(5),
BDCCPRINCIPALVER VARCHAR(5),
BDFORMREFVER VARCHAR(5000),
BDFORMREFAUXVER VARCHAR(5000),
BDFORMVALVER VARCHAR(5000),
BDFORMINTVER VARCHAR(5000),
BDBASEDSRHEVER VARCHAR(5),
BDBASEDSRRVVER VARCHAR(5),
BDDEDFORMREFVER VARCHAR(5),
BDDEDFORMREFAUXVER VARCHAR(5),
BDDEDFORMVALVER VARCHAR(5),
BDRENDISENTOIRVER VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_VAL_RAIS_FF(PREMP VARCHAR(32000),
PRCOL VARCHAR(32000),
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDAVPREV NUMERIC(15,6),
BDFERIND NUMERIC(15,6),
BDGRATIF NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDSINDICAL NUMERIC(15,6),
BDASSISTENCIAL NUMERIC(15,6),
BDCONFEDERATIVA NUMERIC(15,6),
BDBASEFN NUMERIC(15,6),
BDBASEA13 NUMERIC(15,6),
BDBASE13 NUMERIC(15,6),
BDBASEC13 NUMERIC(15,6),
BDORIGEM INTEGER,
BDMENSALIDADE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_VAL_RAIS_FF_REF(PREMP VARCHAR(32000),
PRCOL VARCHAR(32000),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDAVPREV NUMERIC(15,6),
BDFERIND NUMERIC(15,6),
BDGRATIF NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDSINDICAL NUMERIC(15,6),
BDASSISTENCIAL NUMERIC(15,6),
BDCONFEDERATIVA NUMERIC(15,6),
BDBASEFN NUMERIC(15,6),
BDBASEA13 NUMERIC(15,6),
BDBASE13 NUMERIC(15,6),
BDBASEC13 NUMERIC(15,6),
BDORIGEM INTEGER,
BDMENSALIDADE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_VERIFICAVERBASEMP_PADRAO(PRCODEMP INTEGER)
 AS
 BEGIN EXIT; END
^

--Sol. 11965 - Inserido retorno dos campos de valor, dos campos de base: BDBRATAPO13, BDBSALFAM13 e BDBSALMAT13 - Bruno L. R. - 01/02/2017
CREATE OR ALTER PROCEDURE SP_VRHF_13SALARIO_ANO (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(32700),
    PRANO INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF13 INTEGER,
    BDVAL13 NUMERIC(15,6),
    BDMESESPROP13 INTEGER,
    BDBASEIR13 NUMERIC(15,6),
    BDFGTS13 NUMERIC(15,6),
    BDFGTSCS13 NUMERIC(15,6),
    BDBASEFGTS13 NUMERIC(15,6),
    BDDATABAIXA13 DATE,
    BDREFBAIXA13 INTEGER,
    BDPERCIR13 NUMERIC(15,6),
    BDVALORIR13 NUMERIC(15,6),
    BDBRAIS13 NUMERIC(15,6),
    BDDEP13 NUMERIC(15,6),
    BDSALBASE13 NUMERIC(15,6),
    BDARREPROV13 NUMERIC(15,6),
    BDARREDESC13 NUMERIC(15,6),
    BDBASEINSS13 NUMERIC(15,6),
    BDPERCINSS13 NUMERIC(15,6),
    BDVALORINSS13 NUMERIC(15,6),
    BDANO13 INTEGER,
    BDESTPROV13 NUMERIC(15,6),
    BDBASEPIS13 NUMERIC(15,6),
    BDBRATAPO13 NUMERIC(15,6),
    BDBSALFAM13 NUMERIC(18,6),
    BDBSALMAT13 NUMERIC(15,6),
    BDPREVPRIV13 NUMERIC(18,6),
    BDRATAPO13 NUMERIC(15,6),
    BDSALFAM13 NUMERIC(18,6),
    BDSALMATEMP13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_C13SALARIO_ANO (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(32700),
    PRANO INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF13 INTEGER,
    BDVAL13 NUMERIC(15,6),
    BDMESESPROP13 INTEGER,
    BDBASEIR13 NUMERIC(15,6),
    BDFGTS13 NUMERIC(15,6),
    BDFGTSCS13 NUMERIC(15,6),
    BDBASEFGTS13 NUMERIC(15,6),
    BDDATABAIXA13 DATE,
    BDREFBAIXA13 INTEGER,
    BDPERCIR13 NUMERIC(15,6),
    BDVALORIR13 NUMERIC(15,6),
    BDBRAIS13 NUMERIC(15,6),
    BDDEP13 NUMERIC(15,6),
    BDSALBASE13 NUMERIC(15,6),
    BDARREPROV13 NUMERIC(15,6),
    BDARREDESC13 NUMERIC(15,6),
    BDBASEINSS13 NUMERIC(15,6),
    BDPERCINSS13 NUMERIC(15,6),
    BDVALORINSS13 NUMERIC(15,6),
    BDANO13 INTEGER,
    BDESTPROV13 NUMERIC(15,6),
    BDBASEPIS13 NUMERIC(15,6),
    BDBRATAPO13 NUMERIC(15,6),
    BDBSALFAM13 NUMERIC(18,6),
    BDBSALMAT13 NUMERIC(18,6),
    BDSALMATEMP13 NUMERIC(18,6),
    BDPREVPRIV13 NUMERIC(18,6),
    BDRATAPO13 NUMERIC(18,6),
    BDSALFAM13 NUMERIC(18,6))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_13SALARIO_ANO_RESC(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRMES INTEGER,
PRANO INTEGER,
PRPREVIA SMALLINT = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF13 INTEGER,
BDVAL13 NUMERIC(15,6),
BDMESESPROP13 INTEGER,
BDBASEIR13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTSCS13 NUMERIC(15,6),
BDBASEFGTS13 NUMERIC(15,6),
BDDATABAIXA13 DATE,
BDREFBAIXA13 INTEGER,
BDPERCIR13 NUMERIC(15,6),
BDVALORIR13 NUMERIC(15,6),
BDBRAIS13 NUMERIC(15,6),
BDDEP13 NUMERIC(15,6),
BDSALBASE13 NUMERIC(15,6),
BDARREPROV13 NUMERIC(15,6),
BDARREDESC13 NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDPERCINSS13 NUMERIC(15,6),
BDVALORINSS13 NUMERIC(15,6),
BDANO13 INTEGER,
BDESTPROV13 NUMERIC(15,6),
BDSALMATEMP13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_13SALARIO_MAIORIGUALREF(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF13 INTEGER,
BDVAL13 NUMERIC(15,6),
BDMESESPROP13 INTEGER,
BDBASEIR13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTSCS13 NUMERIC(15,6),
BDBASEFGTS13 NUMERIC(15,6),
BDDATABAIXA13 DATE,
BDREFBAIXA13 INTEGER,
BDPERCIR13 NUMERIC(15,6),
BDVALORIR13 NUMERIC(15,6),
BDBRAIS13 NUMERIC(15,6),
BDDEP13 NUMERIC(15,6),
BDSALBASE13 NUMERIC(15,6),
BDARREPROV13 NUMERIC(15,6),
BDARREDESC13 NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDPERCINSS13 NUMERIC(15,6),
BDVALORINSS13 NUMERIC(15,6),
BDANO13 INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_AD13SAL_ANO(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFA13 INTEGER,
BDPERCA13 NUMERIC(15,6),
BDVALA13 NUMERIC(15,6),
BDTIPOPROPA13 INTEGER,
BDMESESPROPA13 INTEGER,
BDBASEIRA13 NUMERIC(15,6),
BDFGTSA13 NUMERIC(15,6),
BDFGTSCSA13 NUMERIC(15,6),
BDBASEFGTSA13 NUMERIC(15,6),
BDDATABAIXAA13 DATE,
BDREFBAIXAA13 INTEGER,
BDPERCIRA13 NUMERIC(15,6),
BDVALORIRA13 NUMERIC(15,6),
BDBSALFAMA13 NUMERIC(15,6),
BDSALFAMA13 NUMERIC(15,6),
BDBRAISA13 NUMERIC(15,6),
BDDEPA13 NUMERIC(15,6),
BDSALBASEA13 NUMERIC(15,6),
BDARREPROVA13 NUMERIC(15,6),
BDARREDESCA13 NUMERIC(15,6),
BDANOA13 INTEGER,
BDESTPROVA13 NUMERIC(15,6),
BDCALCFERA13 VARCHAR(5),
BDCODEMPORIG INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_AD13SAL_ANO_RESC(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRMES INTEGER,
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFA13 INTEGER,
BDPERCA13 NUMERIC(15,6),
BDVALA13 NUMERIC(15,6),
BDTIPOPROPA13 INTEGER,
BDMESESPROPA13 INTEGER,
BDBASEIRA13 NUMERIC(15,6),
BDFGTSA13 NUMERIC(15,6),
BDFGTSCSA13 NUMERIC(15,6),
BDBASEFGTSA13 NUMERIC(15,6),
BDDATABAIXAA13 DATE,
BDREFBAIXAA13 INTEGER,
BDPERCIRA13 NUMERIC(15,6),
BDVALORIRA13 NUMERIC(15,6),
BDBSALFAMA13 NUMERIC(15,6),
BDSALFAMA13 NUMERIC(15,6),
BDBRAISA13 NUMERIC(15,6),
BDDEPA13 NUMERIC(15,6),
BDSALBASEA13 NUMERIC(15,6),
BDARREPROVA13 NUMERIC(15,6),
BDARREDESCA13 NUMERIC(15,6),
BDANOA13 INTEGER,
BDESTPROVA13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_AD13SAL_MAIORREF(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFA13 INTEGER,
BDPERCA13 NUMERIC(15,6),
BDVALA13 NUMERIC(15,6),
BDTIPOPROPA13 INTEGER,
BDMESESPROPA13 INTEGER,
BDBASEIRA13 NUMERIC(15,6),
BDFGTSA13 NUMERIC(15,6),
BDFGTSCSA13 NUMERIC(15,6),
BDBASEFGTSA13 NUMERIC(15,6),
BDDATABAIXAA13 DATE,
BDREFBAIXAA13 INTEGER,
BDPERCIRA13 NUMERIC(15,6),
BDVALORIRA13 NUMERIC(15,6),
BDBSALFAMA13 NUMERIC(15,6),
BDSALFAMA13 NUMERIC(15,6),
BDBRAISA13 NUMERIC(15,6),
BDDEPA13 NUMERIC(15,6),
BDSALBASEA13 NUMERIC(15,6),
BDARREPROVA13 NUMERIC(15,6),
BDARREDESCA13 NUMERIC(15,6),
BDANOA13 INTEGER,
BDESTPROVA13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_BASE_CALC_TERC (
    PRREF integer,
    PRGPSSEFIP integer = 0,
    PRCODEMP varchar(32000) = null,
    PRCODAUT varchar(32000) = null)
returns (
    BDCODEMP integer,
    BDREFSERV integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDVALORINSS numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASERATAPO numeric(18,6),
    BDVALOUTENTIDADES numeric(18,6),
    BDCODTER integer,
    BDGPSSEFIP integer,
    BDCATEGORIAESOCIAL integer)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_BASE_TVERBASEMP_CONS(PRCODEMP INTEGER,
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODIGOVEREMP INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(40),
BDTIPOCOLVEREMP INTEGER,
BDCLASSECOLVEREMP INTEGER,
BDCOMFGTS VARCHAR(5),
BDCODTCA INTEGER,
BDDESCTCA VARCHAR(50),
BDINTERMITENTE DM_BOOLEAN,
BDADICNOTVAR DM_BOOLEAN,
BDAULISTA BOOLEAN)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_CONS_BASES_AD(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREF INTEGER,
PRDATAPGTO DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFIR INTEGER,
BDREFIRFIR INTEGER,
BDTIPOCALCFIR INTEGER,
BDBASEIRFIR NUMERIC(18,6),
BDVALINSSFIR NUMERIC(18,6),
BDVALIRFIR NUMERIC(18,6),
BDDESCBASEIRFIR NUMERIC(18,6),
BDDATAFIR DATE,
BDDATAPROC DATE,
BDHORAPROC TIME)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_CONS_BASES_FN(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREF INTEGER,
PRDATAPGTO DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFIR INTEGER,
BDREFIRFIR INTEGER,
BDTIPOCALCFIR INTEGER,
BDBASEIRFIR NUMERIC(18,6),
BDVALINSSFIR NUMERIC(18,6),
BDVALIRFIR NUMERIC(18,6),
BDDESCBASEIRFIR NUMERIC(18,6),
BDDATAFIR DATE,
BDDATAPROC DATE,
BDHORAPROC TIME)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_INSS_13 (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRANOTODO smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF13 integer,
    BDVALORINSS13 numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDSALFAM13 numeric(18,6),
    BDSALMATEMP13 numeric(18,6),
    BDBINSSMV13 numeric(18,6),
    BDCHAVE integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCODTOMADOR integer,
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBRATAPO13 numeric(18,6),
    BDBASEPIS numeric(18,6))
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_INSS_C13 (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRANOTODO smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF13 integer,
    BDVALORINSS13 numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDSALFAM13 numeric(18,6),
    BDSALMATEMP13 numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBRATAPO13 numeric(18,6),
    BDSEMBASEGPS numeric(18,6),
    BDBASEPIS numeric(18,6))
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_INSS_FC (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRREFPAG integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS smallint = 0,
    PRREFFIM integer = 0,
    PRCOMPLEESOCIAL integer = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFCOMP integer,
    BDCODCENTROS integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDCODTIPOFC integer,
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEPIS numeric(18,6))
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_INSS_FC_ESOCIAL (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREFNEW integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS smallint = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFCOMP integer,
    BDCODCENTROS integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDCODTIPOFC integer,
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEPIS numeric(18,6))
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_ESOCIAL_DADOS_INSS_FN (
    PRCODEMP varchar(15000),
    PRREF integer,
    PRCONTRATO integer = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDCODCENTROS integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDPERCRATCOL numeric(18,6),
    BDPERCDESCFPASCOL numeric(18,6))
as
BEGIN
  SUSPEND;
END^

create or alter procedure SP_ESOCIAL_DADOS_INSS_FT (
    PRCODEMP varchar(15000),
    PRREF integer,
    PRCONTRATO integer = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDPERCRATCOL numeric(18,6),
    BDPERCDESCFPASCOL numeric(18,6))
as
BEGIN
  SUSPEND;
END^

create or alter procedure SP_VRHF_DADOS_INSS_FN (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS varchar(15000) = null,
    PRCONTRATO integer = 0,
    PRSEPARARFOLHAS DM_BOOLEAN = 'FALSE')
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDCODCENTROS integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDPERCRATCOL numeric(18,6),
    BDPERCDESCFPASCOL numeric(18,6),
    BDCNPJEMP DM_CNPJ_CPF,
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDCOVID19FN numeric(18,6),
    BDBASEPIS numeric(18,6),
    BDCATEGORIAESOCIAL integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_INSS_FT (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS varchar(15000) = null,
    PRCONTRATO integer = 0,
    PRORDEM integer = 0,
    PRSEPARARFOLHAS DM_BOOLEAN = 'FALSE')
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDPERCRATCOL numeric(18,6),
    BDPERCDESCFPASCOL numeric(18,6),
    BDCNPJEMP DM_CNPJ_CPF,
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDCOVID19FN numeric(18,6),
    BDBASEPIS numeric(15,2),
    BDBASEPIS13 numeric(15,2),
    BDCATEGORIAESOCIAL integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_INSS_FTC (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32000),
    PRREF integer,
    PRREFPAG integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS smallint = 0,
    PRREFFIM integer = 0,
    PRCOMPLEESOCIAL integer = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFCOMP integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDCODTIPOFC integer,
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEPIS numeric(18,6))
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_INSS_FTC_ESOCIAL (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32000),
    PRREFNEW integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS smallint = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFCOMP integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDCODTIPOFC integer,
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEPIS numeric(18,6))
as
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_13FC (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRIRRFESOCIAL boolean = false,
    PRVERCALCRRA integer = -1,
    PRPORCC smallint = 1)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFFC integer,
    BDCODACCONV integer,
    BDREFIRRFESOCIAL integer)
as
BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_13FC_INT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRIRRFESOCIAL boolean = false,
    PRPORCC smallint = 1)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODCONTTI integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFIRRFESOCIAL integer)
as
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_IR_DARF(PRCODEMP varchar(20000),
PRCODCOL varchar(30000),
PRREFINI integer,
PRREFFIM integer,
PRPUXARFILIAIS integer = 0,
PRCODMATRIZ varchar(15000) = '',
PRPORCC smallint = 0,
PRSEMPLR smallint = 0,
PRIRRFESOCIAL boolean = false)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFIR INTEGER,
BDREFIRFIR INTEGER,
BDTIPOCALCFIR INTEGER,
BDCCFIR INTEGER,
BDCODFERFIR INTEGER,
BDCODTCA INTEGER,
BDBASEIRFIR NUMERIC(18,6),
BDVALINSSFIR NUMERIC(18,6),
BDVALIRFIR NUMERIC(18,6),
BDVALDEPFIR NUMERIC(18,6),
BDPENJUD NUMERIC(18,6),
BDPENALIM NUMERIC(18,6),
BDDATAFIR DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_IR_5012 (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER = 0,
    PRCODMATRIZ VARCHAR(15000) = '',
    PRPORCC SMALLINT = 0,
    PRSEMPLR SMALLINT = 0,
    PRCALCAPURANUAL INTEGER = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREFFIR INTEGER,
    BDREFIRFIR INTEGER,
    BDTIPOCALCFIR INTEGER,
    BDCCFIR INTEGER,
    BDCODFERFIR INTEGER,
    BDCODTCA INTEGER,
    BDBASEIRFIR NUMERIC(18,6),
    BDVALINSSFIR NUMERIC(18,6),
    BDVALIRFIR NUMERIC(18,6),
    BDVALDEPFIR NUMERIC(18,6),
    BDPENJUD NUMERIC(18,6),
    BDPENALIM NUMERIC(18,6),
    BDDATAFIR DATE,
    BDCODAUTONOMO INTEGER,
    BDCONTRCOL INTEGER,
    BDCPFCOL VARCHAR(14),
    BDCODMATRIZ INTEGER,
    BDCNPJEMP VARCHAR(18),
    BDCODFILIAL INTEGER,
    BDREFEMP INTEGER,
    BDNOMEMP VARCHAR(100),
    BDCODCLA INTEGER,
    BDCODGRUPOCLA INTEGER,
    BDCODCLATRI INTEGER,
    BDCODESTAB VARCHAR(30),
    BDTIPOCAEPF INTEGER,
    BDESCOOPERATIVA INTEGER,
    BDESCONSTRUTORA VARCHAR(5),
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDTIPOTOM INTEGER,
    BDCODLOT INTEGER,
    BDCNPJTOM VARCHAR(18))
AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_DIRF (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '',
    PREXPORTACAO integer = 0,
    PRSEMPLR smallint = 0,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRTABTEMPRRA boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDCODTCA integer,
    BDBOLSAESTUDOS numeric(18,6))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_IR_RT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRGRAVATEMPRENDTRIB boolean = false,
    PRRELATORIO boolean = false,
    PRFILTRORECEITA integer = 0,
    PRSEMRENDISENTO boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCHAVE integer,
    BDREFPGTO integer,
    BDIRRFMENSAL numeric(18,6),
    BDIRRFDECIMOTERC numeric(18,6),
    BDPREVIDENCIAOFICIAL numeric(18,6),
    BDCODRECEITAESOC varchar(6),
    BDTOTALDESPJUDICIAL numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDRENDNAPTRIBUT numeric(18,6),
    BDQTDMESESRRA numeric(18,6),
    BDVALORPAGOADVOGADO numeric(18,6),
    BDCPFADVOGADO varchar(18),
    BDNOMCOL varchar(70),
    BDCPF varchar(18),
    BDDESCRRA varchar(50),
    BDDESCRENDNAOTRIBUT varchar(60),
    BDJUROSMORA numeric(18,6),
    BDQTDDEP integer,
    BDNUMPROCESSO varchar(25),
    BDVALDEP numeric(18,6),
    BDTOTALPENSAO numeric(18,6),
    BDPENSAOMENSAL numeric(18,6),
    BDPENSAO13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDPREVIDENCIAOFICIAL13 numeric(18,6),
    BDJUROSMORA13 numeric(18,6))
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_IR_FN2 (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER = 0,
    PRCODMATRIZ VARCHAR(15000) = '',
    PRPREVIARESC SMALLINT = 0) 
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDREFPAG INTEGER,
    BDTIPO INTEGER,
    BDRENDTRIBUTAVEL NUMERIC(18,6),
    BDINSS NUMERIC(18,6),
    BDIR NUMERIC(18,6),
    BDDEP NUMERIC(18,6),
    BDLUCROPJ NUMERIC(18,6),
    BDDESPMED NUMERIC(18,6),
    BDAJCUSTOS NUMERIC(18,6),
    BDPENJUD NUMERIC(18,6),
    BDPENALIM NUMERIC(18,6),
    BDPREVPRIV NUMERIC(18,6),
    BDINDRESC NUMERIC(18,6),
    BDVALABO NUMERIC(18,6),
    BDRENDISENTOS NUMERIC(18,6),
    BDDRENDISENTOS VARCHAR(999),
    BDDATAPGTO DATE,
    BDINFADIC VARCHAR(300),
    BDDATAPROC DATE,
    BDHORAPROC TIME,
    BDORDEM INTEGER) 
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER procedure SP_VRHF_DADOS_FGTS_FN (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer,
    PRCODMATRIZ varchar(15000))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBFGTSRESC numeric(18,6),
    BDFGTSRESC numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDBFGTS13RESC numeric(18,6),
    BDFGTS13RESC numeric(18,6),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer)
as
BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_FGTS_FC (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer,
    PRCODMATRIZ varchar(15000),
    PRADC boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBFGTSRESC numeric(18,6),
    BDFGTSRESC numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDBFGTS13RESC numeric(18,6),
    BDFGTS13RESC numeric(18,6),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDTIPOEVT integer)
as
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_FGTS_13 (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER,
    PRCODMATRIZ VARCHAR(15000))
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDBFGTS NUMERIC(18,6),
    BDFGTS NUMERIC(18,6),
    BDDATAPROC DATE,
    BDHORAPROC TIME,
    BDORDEM INTEGER)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_FGTS_A13 (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER,
    PRCODMATRIZ VARCHAR(15000))
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDBFGTS NUMERIC(18,6),
    BDFGTS NUMERIC(18,6),
    BDORDEM INTEGER)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_FGTS_C13 (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER = 0,
    PRCODMATRIZ VARCHAR(15000) = '')
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDTIPO INTEGER,
    BDFGTS NUMERIC(18,6),
    BDBFGTS NUMERIC(18,6),
    BDDATAPROC DATE,
    BDHORAPROC TIME,
    BDORDEM INTEGER)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_FGTS_FER (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER,
    PRCODMATRIZ VARCHAR(15000))
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDBFGTS NUMERIC(18,6),
    BDFGTS NUMERIC(18,6),
    BDORDEM INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WUSARTMP_EMP_SELECT SMALLINT;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WREF INTEGER;
DECLARE VARIABLE WBASEFGTS NUMERIC(18,6);
DECLARE VARIABLE WVALORFGTS NUMERIC(18,6);
DECLARE VARIABLE WORDEM INTEGER;
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_PIS_13 (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER = 0,
    PRCODMATRIZ VARCHAR(15000) = '')
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDCODVER INTEGER,
    BDBASEPISFE NUMERIC(15,6),
    BDBASEPIS13 NUMERIC(15,6),
    BDBASEPISFN NUMERIC(15,6),
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDCTALON VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_PIS_C13 (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER = 0,
    PRCODMATRIZ VARCHAR(15000) = '')
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDCODVER INTEGER,
    BDBASEPISFE NUMERIC(15,6),
    BDBASEPIS13 NUMERIC(15,6),
    BDBASEPISFN NUMERIC(15,6),
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDCTALON VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_PIS_FC(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDBASEPISFE NUMERIC(15,6),
BDBASEPIS13 NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCTALON VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_PIS_FN(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(30000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRPUXARFILIAIS INTEGER = 0,
PRCODMATRIZ VARCHAR(15000) = '')
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDBASEPISFE NUMERIC(15,6),
BDBASEPIS13 NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCTALON VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_PIS_AD13 (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER = 0,
    PRCODMATRIZ VARCHAR(15000) = '')
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDCODVER INTEGER,
    BDBASEPISFE NUMERIC(15,6),
    BDBASEPIS13 NUMERIC(15,6),
    BDBASEPISFN NUMERIC(15,6),
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDCTALON VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_EMP_BASES_RESCISAO(PRCODEMP VARCHAR(25000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFAUXVFN NUMERIC(15,6),
BDREFVFN NUMERIC(15,6),
BDVALVFN NUMERIC(15,6),
BDIGNREFVFN VARCHAR(5),
BDIGNVALVFN VARCHAR(5),
BDSALBASEFN NUMERIC(15,6),
BDMAIORREMFN NUMERIC(15,6),
BDBFGTSFN NUMERIC(15,6),
BDFGTSFN NUMERIC(15,6),
BDFGTSCSFN NUMERIC(15,6),
BDBFGTS13FN NUMERIC(15,6),
BDFGTS13FN NUMERIC(15,6),
BDFGTS13CSFN NUMERIC(15,6),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDCNPJEMP VARCHAR(18),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDDDDFAXEMP INTEGER,
BDFAXEMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDNOMCOL DM_BDNOMCOL,
BDDATAADMCOL DATE,
BDDATANASCCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL VARCHAR(10),
BDDSERIECTPSCOL VARCHAR(1),
BDDATAOPCAOFGTSCOL DATE,
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDSIGLAUFCTPS VARCHAR(2),
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAPAGRESCISAO DATE,
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCODPRES INTEGER,
BDSALDOFGTS NUMERIC(15,6),
BDDESCPRES VARCHAR(110))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_EMP_TFOLHANORMAL_ANT(PRREF INTEGER,
PRCODEMP VARCHAR(20000) = NULL,
PRCODCOL VARCHAR(32700) = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDDATABAIXAFN DATE,
BDBFGTSFN NUMERIC(15,6),
BDFGTSFN NUMERIC(15,6),
BDFGTSCSFN NUMERIC(15,6),
BDBFGTS13FN NUMERIC(15,6),
BDFGTS13FN NUMERIC(15,6),
BDFGTS13CSFN NUMERIC(15,6),
BDMAIORREMFN NUMERIC(15,6),
BDBINSSFN NUMERIC(15,6),
BDALIQINSSFN NUMERIC(15,6),
BDINSSFN NUMERIC(15,6),
BDBIRRFFN NUMERIC(15,6),
BDALIQIRRFFN NUMERIC(15,6),
BDIRRFFN NUMERIC(15,6),
BDBINSS13FN NUMERIC(15,6),
BDALIQINSS13FN NUMERIC(15,6),
BDINSS13FN NUMERIC(15,6),
BDBIRRF13FN NUMERIC(15,6),
BDALIQIRRF13FN NUMERIC(15,6),
BDIRRF13FN NUMERIC(15,6),
BDBSALFAMFN NUMERIC(15,6),
BDSALFAMFN NUMERIC(15,6),
BDBRAISFN NUMERIC(15,6),
BDSALBASEFN NUMERIC(15,6),
BDDEPFN NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6),
BDBASEPISFEFN NUMERIC(15,6),
BDBASEPIS13FN NUMERIC(15,6),
BDBSALMATEMPFN NUMERIC(15,6),
BDSALMATEMPFN NUMERIC(15,6),
BDBRATAPOFN NUMERIC(15,6),
BDBINSSFEFOLFN NUMERIC(15,6),
BDINSSFEFOLFN NUMERIC(15,6),
BDALIQINSSFEFOLFN NUMERIC(15,6),
BDDEBITOFN NUMERIC(15,6),
BDCREDITOFN NUMERIC(15,6),
BDBFGTSFEFN NUMERIC(15,6),
BDFGTSFEFN NUMERIC(15,6),
BDBRATAPOFEFN NUMERIC(15,6),
BDBRATAPO13FN NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_EMP_TPROVISAO13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32700),
    PRANOMES integer,
    PRTIPOPROV integer,
    PRDESCAD13 smallint = 0,
    PRMESATUAL smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFP13 integer,
    BDLINHAP13 integer,
    BDPROPP13 integer,
    BDADICIONAISP13 numeric(15,6),
    BDMEDIASP13 numeric(15,6),
    BDSALBASEP13 numeric(15,6),
    BDPLANOCC integer,
    BDORDEMCCP13 integer,
    BDVLR13SALP13 numeric(15,6),
    BDFGTSP13 numeric(15,6),
    BDINSSP13 numeric(15,6),
    BDTERCFPASP13 numeric(15,6),
    BDCNAERATP13 numeric(15,6),
    BDRATAPOP13 numeric(15,6),
    BDPISP13 numeric(15,6),
    BDTOTP13 numeric(15,6))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_EMP_TPROVISAOFERIAS (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32700),
    PRANOMES integer,
    PRTIPOPROV integer,
    PRMESATUAL smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDLINHAPFER integer,
    BDINIPERAQUISPFER date,
    BDORDEMCCPFER integer,
    BDPLANOCC integer,
    BDREFPFER integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDSALBASEPFER numeric(15,6),
    BDADICIONAISPFER numeric(15,6),
    BDMEDIASPFER numeric(15,6),
    BDOUTRASBASESPFER numeric(15,6),
    BDFERIASPFER numeric(15,6),
    BDUMTERCOPFER numeric(15,6),
    BDFGTSPFER numeric(15,6),
    BDINSSPFER numeric(15,6),
    BDTERCFPASPFER numeric(15,6),
    BDCNAERATPFER numeric(15,6),
    BDRATAPOPFER numeric(15,6),
    BDPISPFER numeric(15,6),
    BDTOTPFER numeric(15,6),
    BDPROPPFER numeric(15,6),
    BDBASEFGTSPFER numeric(15,6),
    BDBASEINSSPFER numeric(15,6),
    BDBASEPISPFER numeric(15,6),
    BDRESCISAOPFER varchar(5),
    BDPORTOMADORPFER varchar(5),
    BDFALTASPFER numeric(15,6),
    BDDATAVENCPFER date,
    BDMVPFER numeric(15,6),
    BDPRPFER numeric(15,6),
    BDSDPFER numeric(15,6))
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_FC_VALORES_INDENIZADOS (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRANOMES INTEGER,
    PRDATAGRRF DATE)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREFFN INTEGER,
    BDDATAGRRFFC DATE,
    BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_FN_VALORES_INDENIZADOS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_FOLHACOMPLEMENTAR RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPO INTEGER,
BDBFGTSFEFC NUMERIC(15,6),
BDFGTSFEFC NUMERIC(15,6),
BDDATAPAGFC date)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_FOLHANORMAL RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPO INTEGER,
BDBFGTSFEFN NUMERIC(15,6),
BDFGTSFEFN NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_TCOL_VINC_REF(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFCOL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFCOL INTEGER,
BDCODSINTRAB INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_VERBAS_AGRUPADAS_FN(PRCODEMP VARCHAR(32700),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRAGRUPACC INTEGER)
 RETURNS(BDCODVER INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDREFVFN NUMERIC(18,6),
BDREFAUXVFN NUMERIC(18,6),
BDVALVFN NUMERIC(18,6),
BDIGNREFVFN DM_BOOLEAN,
BDIGNVALVFN DM_BOOLEAN,
BDORVERBAFN INTEGER,
BDVALVIFN NUMERIC(18,6),
BDIGNREFAVFN DM_BOOLEAN,
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_VERBAS_FN_FC RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDIGNREFAV VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_DADOS_SAUDE (
    PREMP varchar(20000),
    PRCOL varchar(32000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPORCOMPETENCIA smallint = 0,
    PRPORFICHA smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDREF integer)
as
begin
  SUSPEND;
end^

CREATE OR ALTER PROCEDURE SP_VRHM_FF_OP_ANO(PREMP varchar(32000) = '',
    PRCOL varchar(32000) = '',
    PRANO integer = 0,
    PROPER integer = 0,
    PRCONV integer = 0,
    PRREFPAG integer = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDNOME VARCHAR(70),
BDTIPO INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDMENSALIDADE NUMERIC(15,6),
BDCOPARTICIPACAO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHM_FF_OP_REF(PREMP VARCHAR(32000) = '',
PRCOL VARCHAR(32000) = '',
PRREFINI INTEGER = 0,
PRREFFIM INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDNOME VARCHAR(70),
BDTIPO INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDMENSALIDADE NUMERIC(15,6),
BDCOPARTICIPACAO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHM_VAL_PS_COL(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDREF INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDVALORMENSALIDADE NUMERIC(15,6),
BDVALLORCOPAR NUMERIC(15,6),
BDCODTIPOCONV INTEGER,
BDCODEMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VSUC_COPIA_CT_PLANO_DFIS(CODIGOPLANOCOPIAR INTEGER,
ANOCOPIAR INTEGER,
ANONOVO INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SP_VSUC_COPIA_CT_PLANO_FCONT(CODIGOPLANOCOPIAR INTEGER,
ANOCOPIAR INTEGER,
ANONOVO INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE SPCLASSVERBAONLINE(PRCLAANT VARCHAR(100),
PRCLANOVA VARCHAR(100))
 RETURNS(BDCLAANTVERBA VARCHAR(100),
BDCLAANTVERBARESC VARCHAR(100),
BDCLANOVAVERBA VARCHAR(100),
BDCLANOVAVERBARESC VARCHAR(100))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_DADOS_GPS_COMP (
    WEMP varchar(30000),
    WCOL varchar(30000),
    FANOMES integer,
    FANOMESFIM integer,
    FANOMESPAG integer,
    FPUXAFILIAIS integer,
    PRGPSSEFIP integer,
    PRCODIMP integer,
    TIPOFC integer,
    FJOINFILTROCOL varchar(5000) = '',
    FJOINEMPIMP varchar(5000) = '',
    FJOINFILTROSITCOL varchar(5000) = '',
    FCODCLA varchar(5000) = '',
    PRCOMPLEESOCIAL integer = 0)
returns (
    BDBASEFUNC13 numeric(15,2),
    BDBASEFUN13 numeric(15,2),
    BDBASERATAPOC13 numeric(15,2),
    BDBASERATAPO13 numeric(15,2),
    BDBASEFUNFN numeric(15,2),
    BDPERCDESCFPASCOL numeric(15,2),
    BDPERCRATCOL numeric(15,2),
    BDDESCENQFED varchar(10),
    BDISENFILEMP numeric(15,2),
    BDCATSEFIPEMP integer,
    BDCODENQFED integer,
    BDDATAINIPERIOD date,
    BDREFINIDCTFWEB integer,
    BDOPCAOESOCIAL integer,
    BDNOMEMP varchar(100),
    BDCNPJEMP varchar(18),
    BDDESONTOMAEMP varchar(10),
    BDCODTRIBRUR integer,
    BDBASEFUNFERFC numeric(15,2),
    BDBASEFUNFC numeric(15,2),
    BDBASEINSS13 numeric(15,2),
    BDBASEINSS numeric(15,2),
    BDBASERAT numeric(15,2),
    BDNOMETOM varchar(100),
    BDCNPJTOM varchar(18),
    BDBINSS13INDFN numeric(15,2),
    BDTIPOTOM integer,
    BDVALINDEVIDOSF numeric(15,2),
    BDVALINDEVIDO numeric(15,2),
    BDGPSSEFIP integer,
    BDSESCOOP numeric(15,2),
    BDSENAT numeric(15,2),
    BDSEST numeric(15,2),
    BDSENAR numeric(15,2),
    BDFUNAERO numeric(15,2),
    BDDPC numeric(15,2),
    BDSEBRAE numeric(15,2),
    BDSESC numeric(15,2),
    BDSENAC numeric(15,2),
    BDSESI numeric(15,2),
    BDSENAI numeric(15,2),
    BDINCRA numeric(15,2),
    BDSALEDU numeric(15,2),
    BDATUTAB varchar(10),
    BDDESONOBRA varchar(10),
    BDINDUSTRIA varchar(10),
    BDCOMERCIO varchar(10),
    BDANEXOVI varchar(10),
    BDANEXOV varchar(10),
    BDANEXOIII varchar(10),
    BDANEXOIV varchar(10),
    BDPERCFPAS numeric(15,2),
    BDPERCAUT numeric(15,2),
    BDPERCPRO numeric(15,2),
    BDPERCFUN numeric(15,2),
    BDSIMPLESGPS integer,
    BDCODEMP integer,
    BDREFPAG integer,
    BDREFFN integer,
    BDBASEFUN13RFN numeric(15,2),
    BDBASEFUNFERFN numeric(15,2),
    BDCCATVCONCOM varchar(10),
    BDBASEFUN13RFC numeric(15,2),
    BDINSS13FN numeric(15,2),
    BDINSSFEFOLFN numeric(15,2),
    BDINSSFN numeric(15,2),
    BDCODTPCC integer,
    BDCODFPAS integer,
    BDCODCENTRO integer,
    BDCODCOL integer,
    BDCODTOMADOR integer,
    BDBASERATAPO13RFN numeric(15,2),
    BDBASERATAPOFERFN numeric(15,2),
    BDBASERATAPOFN numeric(15,2),
    VALOUTENTIDADE integer,
    SALMATERNIDADE numeric(15,2),
    SALFAM numeric(15,2),
    BDGRUPOCLA integer,
    BDCODTER integer,
    BDBINSSMV13FN numeric(15,2),
    BDBINSSMVFN numeric(15,2),
    BDBASERATAPO13RFC numeric(15,2),
    BDBASERATAPOFERFC numeric(15,2),
    BDTIPO_TPCC integer,
    BDBASERATAPOFC numeric(15,2),
    BDCODMATRIZ integer,
    BDCODEMPCOL integer,
    BDREFPAGTC integer,
    BDPERCRAT numeric(15,4),
    BDPERCFAPCAD numeric(15,4),
    BDPERCRATCAD numeric(15,4),
    BDCODTIPOFC integer,
    BDBASEPIS numeric(18,6),
    BDCATEGORIAESOCIAL integer)
as
BEGIN SUSPEND; END
^

create or alter procedure SP_DADOS_REL_QTDFOLHAS (
    PREMPRESA varchar(20000),
    PRREFINICIAL varchar(15),
    PRREFFINAL varchar(15),
    PREMITIREMPSEMFOLHAS integer,
    PRTIPOCALCULO integer,
    PRTIPODEFOLHAAVULSA integer = -1,
    PRFILTROSITUACAO integer = -1,
    PRCENTROCUSTO varchar(20000) = '' /* COLLATE WIN1252 - default */ ,
    PRCLASSECOLABORADOR varchar(20000) = '' /* COLLATE WIN1252 - default */ ,
    PRSINDICATOCOLABORADOR varchar(20000) = '' /* COLLATE WIN1252 - default */ ,
    PRFUNCAOCOLABORADOR varchar(20000) = '' /* COLLATE WIN1252 - default */ )
returns (
    BDCODEMPRESA integer,
    BDNOMEEMPRESA varchar(1000),
    BDCNPJEMPRESA varchar(30),
    BD01 integer,
    BD02 integer,
    BD03 integer,
    BD04 integer,
    BD05 integer,
    BD06 integer,
    BD07 integer,
    BD08 integer,
    BD09 integer,
    BD10 integer,
    BD11 integer,
    BD12 integer,
    BDREF01 integer,
    BDREF02 integer,
    BDREF03 integer,
    BDREF04 integer,
    BDREF05 integer,
    BDREF06 integer,
    BDREF07 integer,
    BDREF08 integer,
    BDREF09 integer,
    BDREF10 integer,
    BDREF11 integer,
    BDREF12 integer,

    BD01Col integer,
    BD02Col integer,
    BD03Col integer,
    BD04Col integer,
    BD05Col integer,
    BD06Col integer,
    BD07Col integer,
    BD08Col integer,
    BD09Col integer,
    BD10Col integer,
    BD11Col integer,
    BD12Col integer,

    BD01Inter integer,
    BD02Inter integer,
    BD03Inter integer,
    BD04Inter integer,
    BD05Inter integer,
    BD06Inter integer,
    BD07Inter integer,
    BD08Inter integer,
    BD09Inter integer,
    BD10Inter integer,
    BD11Inter integer,
    BD12Inter integer,

    BD01Contr integer,
    BD02Contr integer,
    BD03Contr integer,
    BD04Contr integer,
    BD05Contr integer,
    BD06Contr integer,
    BD07Contr integer,
    BD08Contr integer,
    BD09Contr integer,
    BD10Contr integer,
    BD11Contr integer,
    BD12Contr integer,

    BD01Ter integer,
    BD02Ter integer,
    BD03Ter integer,
    BD04Ter integer,
    BD05Ter integer,
    BD06Ter integer,
    BD07Ter integer,
    BD08Ter integer,
    BD09Ter integer,
    BD10Ter integer,
    BD11Ter integer,
    BD12Ter integer)
as
BEGIN SUSPEND; END
^

create or alter procedure SP_BUSCA_VALOR_PIS_VERBAS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFFOLHA integer,
    PRTIPOFOLHA integer,
    PRDIFERENCIADORDATE date,
    PRDIFERENCIADORINTEGER integer)
returns (
    BDBDVALORPISPASEP numeric(18,6),
    BDVALORPISPASEP13 numeric(18,6))
as
declare variable WSQL varchar(30000);
declare variable WVALORVERBA numeric(18,6);
declare variable WINCIDENCIAPIS integer;
begin suspend; END
^

create or alter procedure SP_RETORNA_TAGSTR_TOTALIZADORES (
    PRCODEMPRESA integer,
    PRCODCOLABORADOR integer,
    PRREFFOLHA integer,
    PRTIPOFOLHA integer,
    PRDIFERENCIADORDATE date,
    PRDIFERENCIADORINTEGER integer,
    PRCONVERTTIPO integer = 0,
    PRINTERMITENTE integer = 0,
    PRORDEM integer = 0,
    PRFC integer = 0,
    PRREFDATAFC integer = 0)
returns (
    BDDESCRICAOCALCULO varchar(10000),
    BDTAGSTR varchar(10000))
as
declare variable WTIPO integer;
declare variable WTIPOPROPA13 integer;
declare variable WPERCA13 numeric(18,6);
declare variable WDESCRICAOFOLHA varchar(10000);
declare variable WTAGSTR varchar(10000);
declare variable WCODIGOADC integer;
declare variable WCODCONTRATO integer;
declare variable WREFFOLHA integer;
declare variable WDESCRICAOAVULSA varchar(10000);
BEGIN SUSPEND; END
^

create or alter procedure SP_HORARIOS_INTERMITENTES (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDDATA date,
    BDHORAINICIAL time,
    BDHORAFINAL time)
as
declare variable WDATAINI date;
declare variable WDATAFIM date;
declare variable WTIPO integer;
declare variable WCODHOR_CON_INT integer;
declare variable WCODCONTRATO integer;
begin suspend; End
^

create or alter procedure SP_HORARIO_INTERMITENTES_DIARIO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRDATA date)
returns (
    BDINICIO time,
    BDFIM time)
as
declare variable WPLANO integer;
declare variable WQUADRO integer;
declare variable WHORAS numeric(15,6);
declare variable WSTRHORA varchar(10);
declare variable WSTRMIN varchar(10);
begin suspend; End
^


create or alter procedure SP_RH_UNION_FC_FCT_MES (
    PRCODEMP varchar(3000),
    PRCODCOL varchar(3000),
    PRCODADC integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRREFPAG date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFC integer,
    BDREFCOMP integer,
    BDCODVER integer,
    BDREFVFN_SUM numeric(15,2),
    BDREFAUXVFN_SUM numeric(15,2),
    BDREFVFN_MAX numeric(15,2),
    BDREFAUXVFN_MAX numeric(15,2),
    BDVALVFN numeric(15,2),
    BDVALIFN numeric(15,2),
    BDIGNREFAVFN varchar(3000),
    BDIGNREFVFN varchar(3000),
    BDIGNVALVFN varchar(3000),
    BDORVERBAFC integer,
    BDCOMPESP varchar(3000),
    BDFORMREFAUX varchar(3000),
    BDFORMREF varchar(3000),
    BDFORMVAL varchar(3000),
    BDDESCVER varchar(3000),
    BDTIPOCODVER integer,
    BDCLAVER varchar(3000),
    BDORDEMVER integer,
    BDTIPOREFVER integer,
    BDREFFN integer)
as
BEGIN SUSPEND; END
^

create or alter procedure SPCODIMPGPSCOMPLEMENTAR (
    PRCODEMP varchar(32000),
    PRREF integer,
    PRREFPAG integer,
    PRREFFIM integer)
returns (
    BDCODEMP integer,
    BDCODTIPOFC integer,
    BDCODIMP integer,
    BDCODMATRIZ integer,
    BDEMPIMP integer,
    BDLIMITEISENCAO numeric(15,6))
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SPCODIMPGPSCOMPLEMENTAR_ESOCIAL(PRCODEMP VARCHAR(32000),
PRREFCOMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODTIPOFC INTEGER,
BDCODIMP INTEGER,
BDCODMATRIZ INTEGER,
BDEMPIMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SPCORACENTOS(PRTXT VARCHAR(1000))
 RETURNS(BDTXT VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SPCORRIGEACENTOS AS
 BEGIN EXIT; END
^

create or alter procedure SPRH_CALC_13SALARIO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFERENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFV_MAX numeric(15,6),
    BDREFV_SUM numeric(15,6),
    BDREFAUXV_MAX numeric(15,6),
    BDREFAUXV_SUM numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNREFAV varchar(5),
    BDIGNVALV varchar(5),
    BDORVERBA integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDALTINT boolean,
    BDBASEIR13BRUTARED DM_NUMERIC_15_2,
    BDVALORIR13BRUTARED DM_NUMERIC_15_2,
    BDVALOR13RED DM_NUMERIC_15_2)
as
BEGIN
  SUSPEND;
END^

create or alter procedure SPRH_CALC_AD13SALARIO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFERENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFV_MAX numeric(15,6),
    BDREFV_SUM numeric(15,6),
    BDREFAUXV_MAX numeric(15,6),
    BDREFAUXV_SUM numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNREFAV varchar(5),
    BDIGNVALV varchar(5),
    BDORVERBA integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDALTINT boolean)
AS
BEGIN
  SUSPEND;
END^

create or alter procedure SPRH_CALC_ADSAL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFERENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDDATAAD date,
    BDREFV_MAX numeric(15,6),
    BDREFV_SUM numeric(15,6),
    BDREFAUXV_MAX numeric(15,6),
    BDREFAUXV_SUM numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNREFAV varchar(5),
    BDIGNVALV varchar(5),
    BDORVERBA integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDALTINT boolean)
as
begin
  suspend;
end^

create or alter procedure SPRH_CALC_AUTONOMO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFERENCIA integer,
    PRCODSERV integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFV_MAX numeric(15,6),
    BDREFV_SUM numeric(15,6),
    BDREFAUXV_MAX numeric(15,6),
    BDREFAUXV_SUM numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNREFAV varchar(5),
    BDIGNVALV varchar(5),
    BDORVERBA integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDBASEINSSNMVNOVO numeric(18,6),
    BDINCIRVER integer,
    BDTIPOCODVER integer,
    BDBASEIRBRUTO numeric(17,4),
    BDALTINT boolean,
    BDBASEIRBRUTARED DM_NUMERIC_15_2,
    BDBASEIR13BRUTARED DM_NUMERIC_15_2,
    BDVALORIRBRUTARED DM_NUMERIC_15_2,
    BDVALORIR13BRUTARED DM_NUMERIC_15_2,
    BDVALORRED DM_NUMERIC_15_2,
    BDVALOR13RED DM_NUMERIC_15_2)
as
BEGIN
  SUSPEND;
END^

create or alter procedure SPRH_CALC_FERIAS (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRCODFE integer,
    PRINIPERAQUISFE date,
    PRREFERENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFV_MAX numeric(15,6),
    BDREFV_SUM numeric(15,6),
    BDREFAUXV_MAX numeric(15,6),
    BDREFAUXV_SUM numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNREFAV varchar(5),
    BDIGNVALV varchar(5),
    BDORVERBA integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDDETALHE varchar(255),
    BDREFFN integer,
    BDCODFE integer,
    BDINIPERAQUISFE date,
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDBASEIROUT numeric(15,6),
    BDVALORIROUT numeric(15,6),
    BDDEPIROUT numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDALTINT boolean,
    BDBASEIRBRUTARED DM_NUMERIC_15_2,
    BDVALORIRBRUTARED DM_NUMERIC_15_2,
    BDVALORRED DM_NUMERIC_15_2)
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SPRH_CALC_FOLHACOMP(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV_MAX NUMERIC(15,6),
BDREFV_SUM NUMERIC(15,6),
BDREFAUXV_MAX NUMERIC(15,6),
BDREFAUXV_SUM NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDORVERBA INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDETALHE VARCHAR(255),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SPRH_CONS_CALC_13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDMESESPROP13 INTEGER,
BDBASEIR13 NUMERIC(15,6),
BDBASEFGTS13 NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS13 NUMERIC(15,6),
BDDATABAIXA13 DATE,
BDREFBAIXA13 INTEGER,
BDPERCIR13 NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDPERCINSS13 NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SPRH_CONS_CALC_AD13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDPERC NUMERIC(15,6),
BDVAL NUMERIC(15,6),
BDTIPOPROP INTEGER,
BDMESESPROP INTEGER,
BDBASEIR NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBASEFGTS NUMERIC(15,6),
BDDATABAIXA DATE,
BDREFBAIXA INTEGER,
BDPERCIR NUMERIC(15,6),
BDVALORIR NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SPRH_MENSAGENS_RECIBO(
PRREF INTEGER,
PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(10000))
RETURNS(
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDTXTMEN VARCHAR(2000))
 AS
 BEGIN SUSPEND; END
^

--alt:13612 - 24/03/2016 - Parametro de entrada PRANO teve alterado o nome para PRMESESANTERIORES e o tipo para SMALLINT - Bruno L. R. 
CREATE OR ALTER PROCEDURE SPRH_TREEVIEW_CONS_13SAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRMESESANTERIORES SMALLINT,
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDREF13 INTEGER)
 AS
 BEGIN SUSPEND; END
^

--alt:13612 - 23/03/2016 - Parametro de entrada PRANO teve alterado o nome para PRMESESANTERIORES e o tipo para SMALLINT - Bruno L. R. 
CREATE OR ALTER PROCEDURE SPRH_TREEVIEW_CONS_AD13SAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRMESESANTERIORES SMALLINT,
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDREFA13 INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SPVAL_ITINERARIO(PRITI INTEGER,
PRREF INTEGER)
 RETURNS(BDITI INTEGER,
BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE STRTRAN(PRTEXTO VARCHAR(30000),
PRSUBSTR VARCHAR(1024),
PRSTR VARCHAR(1024))
 RETURNS(BDRESULT VARCHAR(30000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE STRZERO(PRSTR INTEGER,
PRTAM INTEGER)
 RETURNS(STR VARCHAR(50))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE TRUNCAR(PRVALOR NUMERIC(15,6),
PRCASAS SMALLINT)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE ULTIMO_DIA_MES(PRMES SMALLINT,
PRANO INTEGER)
 RETURNS(ULTDIA INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VCT_SERVICO_SUBORDINADO(PRCODSER INTEGER,
PRCODSUB INTEGER)
 RETURNS(BDCODSER INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VCT_TAREFA_SUBORDINADA(PRCODST INTEGER,
PRCODSUB INTEGER)
 RETURNS(BDCODST INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_COPIA_PLANO_BLOCOP(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VEF_COPIA_PLANO_DACON(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER,
COPIARFORMULA INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VEF_COPIA_PLANO_DIME(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VEF_COPIA_PLANO_GIA(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER,
TIPOGIA VARCHAR(10))
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VEF_COPIA_PLANO_IMPOSTOS(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER,
TIPOIMP VARCHAR(10))
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VEF_COPIA_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER,
IMPOSTO VARCHAR(10))
RETURNS (CODIGONOVORETORNO INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VEF_SP_BASE_CONFBASESN(PRATV VARCHAR(15),
PRNAT INTEGER,
PRCID INTEGER,
PRATVM INTEGER)
 RETURNS(BDCODCONFSN INTEGER,
BDDESCIMP VARCHAR(200),
BDDESCTIPOIMP VARCHAR(200),
BDDESC VARCHAR(500),
BDCODNAT INTEGER,
BDCODATIVSIMPNAC INTEGER,
BDCODCONFSNREAL INTEGER,
BDATIVIDADE INTEGER,
BDCODIMPOSTO INTEGER,
BDCODTIPOIMPOSTO INTEGER,
BDCODBASESN INTEGER,
BDCODCONFATVMSN INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_BASE_CONFBASESNATVM(PRATV VARCHAR(15),
PRNAT INTEGER,
PRCID INTEGER,
PRATVM INTEGER)
 RETURNS(BDCODCONFSN INTEGER,
BDDESCIMP VARCHAR(200),
BDDESCTIPOIMP VARCHAR(200),
BDDESC VARCHAR(500),
BDCODNAT INTEGER,
BDCODATIVSIMPNAC INTEGER,
BDCODCONFSNREAL INTEGER,
BDATIVIDADE INTEGER,
BDCODIMPOSTO INTEGER,
BDCODTIPOIMPOSTO INTEGER,
BDCODBASESN INTEGER,
BDCODCONFATVMSN INTEGER,
BDPREPONDERANTE VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_BASE_CONFBASESNNATOP(PRATV VARCHAR(15),
PRNAT INTEGER,
PRFORMASEQUENCIA INTEGER)
 RETURNS(BDCODCONFSN INTEGER,
BDDESCIMP VARCHAR(200),
BDDESCTIPOIMP VARCHAR(200),
BDDESC VARCHAR(500),
BDCODNAT INTEGER,
BDCODATIVSIMPNAC INTEGER,
BDCODCONFSNREAL INTEGER,
BDATIVIDADE INTEGER,
BDCODIMPOSTO INTEGER,
BDCODTIPOIMPOSTO INTEGER,
BDCODBASESN INTEGER,
BDCODCONFATVMSN INTEGER,
BDPREPONDERANTE VARCHAR(5),
BDCODCONFSNTAB INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_CONSULTA_CONFATIVA(PRCODCONFATIVO INTEGER,
PRNUMCAMPO INTEGER,
PRWHERE VARCHAR(5000))
 RETURNS(BDCODCONFATIVO INTEGER,
BDDESCCONF VARCHAR(100),
BDNUMCAMPO INTEGER,
BDNUMITEM INTEGER,
BDDESCFORM VARCHAR(100),
BDFORMULA VARCHAR(30000),
BDINATIVO VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_CONSULTA_VINCULOISS(PRCODCID INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDREFVINCISS INTEGER,
BDCODTIPOISS INTEGER,
BDDESTIPOISS VARCHAR(50),
BDCODTIPOISSEXP INTEGER,
BDDESTIPOISSEXP VARCHAR(50),
BDPERISS DM_NUMERIC_7_4_ALIQ,
BDVALORLIMISS DM_NUMERIC_15_2,
BDCODTIPORPS INTEGER,
BDDESTIPORPS VARCHAR(50),
BDCODIBGE INTEGER,
BDDEDISS varchar(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_JOINNATPREPONDERANTE (
    PRCODATIVSIMPNAC INTEGER,
    PRCODBASESN INTEGER,
    PRISSRET NUMERIC(15,2))
RETURNS (
    BDCODATIVSIMPNAC INTEGER,
    BDCODCID INTEGER,
    BDCODATVM INTEGER,
    BDCODCONFATVMSN INTEGER,
    BDCODNAT INTEGER,
    BDCODCONFSN INTEGER,
    BDCODBASESN INTEGER,
    BDCODIMPOSTO INTEGER,
    BDCODTIPOIMPOSTO INTEGER,
    BDPREPONDERANTE VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_JOINNATNAOPREPONDERANTE (
    PRCODATIVSIMPNAC INTEGER,
    PRCODBASESN INTEGER,
    PRISSRET NUMERIC(15,2))
RETURNS (
    BDCODATIVSIMPNAC INTEGER,
    BDCODCID INTEGER,
    BDCODATVM INTEGER,
    BDCODCONFATVMSN INTEGER,
    BDCODNAT INTEGER,
    BDCODCONFSN INTEGER,
    BDCODBASESN INTEGER,
    BDCODIMPOSTO INTEGER,
    BDCODTIPOIMPOSTO INTEGER,
    BDPREPONDERANTE VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^
CREATE OR ALTER PROCEDURE VEF_SP_JOINATVPREPONDERANTE (
    PRCODATIVSIMPNAC INTEGER,
    PRCODBASESN INTEGER,
    PRISSRET NUMERIC(15,2))
RETURNS (
    BDCODATIVSIMPNAC INTEGER,
    BDCODCID INTEGER,
    BDCODATVM INTEGER,
    BDCODMUNATVM INTEGER, 
    BDCODCONFATVMSN INTEGER,
    BDCODNAT INTEGER,
    BDCODCONFSN INTEGER,
    BDCODBASESN INTEGER,
    BDCODIMPOSTO INTEGER,
    BDCODTIPOIMPOSTO INTEGER,
    BDPREPONDERANTE VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^
CREATE OR ALTER PROCEDURE VEF_SP_JOINATVNAOPREPONDERANTE (
    PRCODATIVSIMPNAC INTEGER,
    PRCODBASESN INTEGER,
    PRISSRET NUMERIC(15,2))
RETURNS (
    BDCODATIVSIMPNAC INTEGER,
    BDCODCID INTEGER,
    BDCODATVM INTEGER,
    BDCODCONFATVMSN INTEGER,
    BDCODNAT INTEGER,
    BDCODCONFSN INTEGER,
    BDCODBASESN INTEGER,
    BDCODIMPOSTO INTEGER,
    BDCODTIPOIMPOSTO INTEGER,
    BDPREPONDERANTE VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_CONSULTALAN_ENT(PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
 RETURNS(BDCODTER INTEGER,
BDNUMDOCINI INTEGER,
BDDATAEMISSAO DATE,
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6),
BDNUMDOCFIM INTEGER,
BDMODELO INTEGER,
BDEMITENTE INTEGER,
BDDATAENTRADAENT DATE,
BDCODSITNF INTEGER,
BDORDEMINFCOM_D500 INTEGER,
BDCODCTA INTEGER,
BDTIPOASSINANTE INTEGER,
BDVLRSER NUMERIC(15,6),
BDVLRSERNTRIB NUMERIC(15,6),
BDVLRCOBTERC NUMERIC(15,6),
BDVLROUTDESP_D500 NUMERIC(15,6),
BDVLRPIS_D500 NUMERIC(15,6),
BDVLRCOFINS_D500 NUMERIC(15,6),
BDCODTENSAO INTEGER,
BDORDEMINFCOM_C500 INTEGER,
BDORDEMCONS INTEGER,
BDVLRCONSFOR NUMERIC(15,6),
BDVLRCOBTER NUMERIC(15,6),
BDVLRDESPACE NUMERIC(15,6),
BDVLRPIS_C500 NUMERIC(15,6),
BDVLRCOFINS_C500 NUMERIC(15,6),
BDTIPOLIGACAO INTEGER,
BDCHAVENFE VARCHAR(44),
BDINDFRETE INTEGER,
BDVLRFRETE NUMERIC(15,6),
BDVLRSEGURO NUMERIC(15,6),
BDVLROUTDESP_C100 NUMERIC(15,6),
BDVLRTOTPIS NUMERIC(15,6),
BDVLRTOTCOFINS NUMERIC(15,6),
BDVLRTOTPISST NUMERIC(15,6),
BDVLRTOTCOFINSST NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_CONSULTALAN_SAI(PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
 RETURNS(BDCODTER INTEGER,
BDNUMDOCINI INTEGER,
BDDATAEMISSAO DATE,
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6),
BDNUMDOCFIM INTEGER,
BDMODELO INTEGER,
BDEMITENTE INTEGER,
BDDATASAIDA DATE,
BDCODSITNF INTEGER,
BDORDEMINFCOM_D500 INTEGER,
BDCODCTA INTEGER,
BDTIPOASSINANTE INTEGER,
BDVLRSER NUMERIC(15,6),
BDVLRSERNTRIB NUMERIC(15,6),
BDVLRCOBTERC NUMERIC(15,6),
BDVLROUTDESP_D500 NUMERIC(15,6),
BDVLRPIS_D500 NUMERIC(15,6),
BDVLRCOFINS_D500 NUMERIC(15,6),
BDCODTENSAO INTEGER,
BDORDEMINFCOM_C500 INTEGER,
BDORDEMCONS INTEGER,
BDVLRCONSFOR NUMERIC(15,6),
BDVLRCOBTER NUMERIC(15,6),
BDVLRDESPACE NUMERIC(15,6),
BDVLRPIS_C500 NUMERIC(15,6),
BDVLRCOFINS_C500 NUMERIC(15,6),
BDTIPOLIGACAO INTEGER,
BDCHAVENFE VARCHAR(44),
BDINDFRETE INTEGER,
BDVLRFRETE NUMERIC(15,6),
BDVLRSEGURO NUMERIC(15,6),
BDVLROUTDESP_C100 NUMERIC(15,6),
BDVLRTOTPIS NUMERIC(15,6),
BDVLRTOTCOFINS NUMERIC(15,6),
BDVLRTOTPISST NUMERIC(15,6),
BDVLRTOTCOFINSST NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_DADOS_ISS_EXP(PRWHEREISS VARCHAR(10000) = NULL,
PRWHERECID VARCHAR(10000) = NULL,
PRWHEREEMP VARCHAR(32000) = NULL,
PRREFINI INTEGER = 0,
PRREFFIN INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDCODCID INTEGER,
BDCODTIPOISSEXP INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_DADOSQ46 RETURNS(BDCODPERIODO INTEGER,
BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDCODQDIME INTEGER,
BDNUMCAMPO INTEGER,
BDCODNAT INTEGER,
BDVALOR NUMERIC(18,6),
BDCODCID INTEGER,
BDCODCIDTOT INTEGER,
BDCODUF INTEGER,
BDDATAREC DATE,
BDCLAVENDIMEGERQ12 INTEGER,
BDCODRECDIMEGERQ12 INTEGER,
BDORIGEMDIMEGERQ46 INTEGER,
BDIDENTIFICACAOREGESP VARCHAR(15),
BDQ12 VARCHAR(5),
BDQ46 VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_DIMEQ46 RETURNS(BDCODPERIODO INTEGER,
BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDCODQDIME INTEGER,
BDNUMCAMPO INTEGER,
BDCODNAT INTEGER,
BDVALOR NUMERIC(18,6),
BDCODCID INTEGER,
BDCODCIDTOT INTEGER,
BDCODUF INTEGER,
BDDATAREC DATE,
BDCLAVENDIMEGERQ12 INTEGER,
BDCODRECDIMEGERQ12 INTEGER,
BDORIGEMDIMEGERQ46 INTEGER,
BDIDENTIFICACAOREGESP VARCHAR(15),
BDQ12 VARCHAR(5),
BDQ46 VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_DIRF(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PREXPORTARNOTAS INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODRECIVSUP INTEGER,
BDREFLAN INTEGER,
BDCODTER INTEGER,
BDCNPJIVSUP VARCHAR(18),
BDNOMEEMPIVSUP VARCHAR(100),
BDIRJANIVSUP NUMERIC(18,6),
BDIRFEVIVSUP NUMERIC(18,6),
BDIRMARIVSUP NUMERIC(18,6),
BDIRABRIVSUP NUMERIC(18,6),
BDIRMAIIVSUP NUMERIC(18,6),
BDIRJUNIVSUP NUMERIC(18,6),
BDIRJULIVSUP NUMERIC(18,6),
BDIRAGOIVSUP NUMERIC(18,6),
BDIRSETIVSUP NUMERIC(18,6),
BDIROUTIVSUP NUMERIC(18,6),
BDIRNOVIVSUP NUMERIC(18,6),
BDIRDEZIVSUP NUMERIC(18,6),
BDRENJANIVSUP NUMERIC(18,6),
BDRENFEVIVSUP NUMERIC(18,6),
BDRENMARIVSUP NUMERIC(18,6),
BDRENABRIVSUP NUMERIC(18,6),
BDRENMAIIVSUP NUMERIC(18,6),
BDRENJUNIVSUP NUMERIC(18,6),
BDRENJULIVSUP NUMERIC(18,6),
BDRENAGOIVSUP NUMERIC(18,6),
BDRENSETIVSUP NUMERIC(18,6),
BDRENOUTIVSUP NUMERIC(18,6),
BDRENNOVIVSUP NUMERIC(18,6),
BDRENDEZIVSUP NUMERIC(18,6),
BDACREDEDUIRSERJAN NUMERIC(18,6),
BDACREDEDUIRSERFEV NUMERIC(18,6),
BDACREDEDUIRSERMAR NUMERIC(18,6),
BDACREDEDUIRSERABR NUMERIC(18,6),
BDACREDEDUIRSERMAIO NUMERIC(18,6),
BDACREDEDUIRSERJUN NUMERIC(18,6),
BDACREDEDUIRSERJUL NUMERIC(18,6),
BDACREDEDUIRSERAGO NUMERIC(18,6),
BDACREDEDUIRSERSET NUMERIC(18,6),
BDACREDEDUIRSEROUT NUMERIC(18,6),
BDACREDEDUIRSERNOV NUMERIC(18,6),
BDACREDEDUIRSERDEZ NUMERIC(18,6),
BDINDIMUNEISE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_DIRF_RTIRF(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODRECIVSUP INTEGER,
BDCODTER INTEGER,
BDCNPJIVSUP VARCHAR(18),
BDNOMEEMPIVSUP VARCHAR(100),
BDIRJANIVSUP NUMERIC(18,6),
BDIRFEVIVSUP NUMERIC(18,6),
BDIRMARIVSUP NUMERIC(18,6),
BDIRABRIVSUP NUMERIC(18,6),
BDIRMAIIVSUP NUMERIC(18,6),
BDIRJUNIVSUP NUMERIC(18,6),
BDIRJULIVSUP NUMERIC(18,6),
BDIRAGOIVSUP NUMERIC(18,6),
BDIRSETIVSUP NUMERIC(18,6),
BDIROUTIVSUP NUMERIC(18,6),
BDIRNOVIVSUP NUMERIC(18,6),
BDIRDEZIVSUP NUMERIC(18,6),
BDINDIMUNEISE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_DIRF_RTRT(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PREXPORTARNOTAS INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDRENJANIVSUP NUMERIC(18,6),
BDRENFEVIVSUP NUMERIC(18,6),
BDRENMARIVSUP NUMERIC(18,6),
BDRENABRIVSUP NUMERIC(18,6),
BDRENMAIIVSUP NUMERIC(18,6),
BDRENJUNIVSUP NUMERIC(18,6),
BDRENJULIVSUP NUMERIC(18,6),
BDRENAGOIVSUP NUMERIC(18,6),
BDRENSETIVSUP NUMERIC(18,6),
BDRENOUTIVSUP NUMERIC(18,6),
BDRENNOVIVSUP NUMERIC(18,6),
BDRENDEZIVSUP NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXCLUI_REDZVARCFOP_PLANO (
PRSQL   VARCHAR(4000),
PREMP   INTEGER,
PRCHAVE INTEGER) 
 AS
 BEGIN END
^

create or alter procedure VEF_SP_EXP_DIME (
    PRCODEMP varchar(10000),
PRREFERENCIAINICIAL INTEGER,
PRREFERENCIAFINAL INTEGER)
returns (
    BDCODEMP integer,
BDREFERENCIA INTEGER,
BDNUMCAMPO INTEGER,
BDCLASSIFICACAO VARCHAR(5),
BDDESCCAMPO VARCHAR(150),
BDVALOR NUMERIC(15,6),
BDCODCID INTEGER,
BDCODCIDTOT INTEGER,
BDCODNAT INTEGER,
BDDATAREC DATE,
BDCLAVENDIMEGERQ12 INTEGER,
BDCODRECDIMEGERQ12 INTEGER,
BDORIGEMDIMEGERQ46 INTEGER,
BDIDENTIFICACAOREGESP VARCHAR(15),
BDSIGLAUF VARCHAR(2),
BDVLRCONT NUMERIC(15,6),
BDVLRBC NUMERIC(15,6),
BDVLRIMPOSTO NUMERIC(15,6),
BDVLRISENTRIB NUMERIC(15,6),
BDVLROUTRAS NUMERIC(15,6),
BDVLRICMSSTPE NUMERIC(15,6),
BDVLRICMSSTOP NUMERIC(15,6),
BDVLRCONTCONT NUMERIC(15,6),
BDVLRBCCONT NUMERIC(15,6),
BDVLRICMSST NUMERIC(15,6),
BDNUMITEM INTEGER,
BDCODTIPO INTEGER,
BDBASEST NUMERIC(15,6),
BDICMSRETST NUMERIC(15,6),
BDDIFALIQENT NUMERIC(15,6),
BDALIMPREP VARCHAR(5),
BDCODEXP48 VARCHAR(3),
    BDNUMACORDOQ12 varchar(15),
    BDCODBENEFTTD integer,
    BDNUMCONCTTD varchar(20),
    BDCODTIPCRED integer,
    BDVLRBCICMS numeric(15,2),
    BDVLRICMSEXON numeric(15,2),
    BDORDEMFUMDES integer,
    BDVLRFUMDES numeric(15,2),
    BDORDEMFUNSOC integer,
    BDVLRFUNSOC numeric(15,2),
    BDVLRBCICMSDEV numeric(15,2),
    BDVLRICMSEXONDEV numeric(15,2),
    BDVLRFUMDESDEV numeric(15,2),
    BDVLRFUNSOCDEV numeric(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG1_18(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDNOMEMP DM_BDNOMEMP,
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDSIGLAUFEMP VARCHAR(2),
BDCODCIDEMP INTEGER,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDDDDFAXEMP INTEGER,
BDFAXEMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDNOMSOC VARCHAR(80),
BDDDDSOC INTEGER,
BDTELRESSOC VARCHAR(15),
BDDDDFAXSOC INTEGER,
BDFAXSOC VARCHAR(9),
BDCGCCEISOC VARCHAR(18),
BDEMAILSOC DM_BDEMAIL,
BDCODCONT INTEGER,
BDNOMECONT VARCHAR(40),
BDCRCCONT VARCHAR(15),
BDSIGLAUFCONT VARCHAR(2),
BDCPFCONT VARCHAR(14),
BDDDDCONT INTEGER,
BDFONECONT DM_BDTELEFONE,
BDDDDFAXCONT INTEGER,
BDFAXCONT DM_BDTELEFONE,
BDEMAILCONT DM_BDEMAIL,
BDVLRRECBRU1_6_IRLP NUMERIC(15,6),
BDVLRRECBRU8_IRLP NUMERIC(15,6),
BDVLRRECBRU16_IRLP NUMERIC(15,6),
BDVLRRECBRU32_IRLP NUMERIC(15,6),
BDVLRLUCROPRESUMIDO_IRLP NUMERIC(15,6),
BDVLRADICIONAL_IRLP NUMERIC(15,6),
BDVLRIMPOSTOPAGAR_IRLP NUMERIC(15,6),
BDVLRIMPOSTORETIDO_IRLP NUMERIC(15,6),
BDVLRALIQ15_IRLP NUMERIC(15,6),
BDVLRCSLLAPAGAR_IRLP NUMERIC(15,6),
BDVLRRECBRU12_IRLP NUMERIC(15,6),
BDVLRRECBRUAJUST_IRLP NUMERIC(15,6),
BDVLRCSLLAPURADA_IRLP NUMERIC(15,6),
BDVLRCSLLRETPJ NUMERIC(15,6),
BDREFERENCIA INTEGER,
BDTRIMESTRE INTEGER,
BDVLRRECBRU32_CSLL NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG1_3(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDNOMEMP DM_BDNOMEMP,
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDSIGLAUFEMP VARCHAR(2),
BDCODCIDEMP INTEGER,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDDDDFAXEMP INTEGER,
BDFAXEMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDNOMSOC VARCHAR(80),
BDDDDSOC INTEGER,
BDTELRESSOC VARCHAR(15),
BDDDDFAXSOC INTEGER,
BDFAXSOC VARCHAR(9),
BDCGCCEISOC VARCHAR(18),
BDEMAILSOC DM_BDEMAIL,
BDCODCONT INTEGER,
BDNOMECONT VARCHAR(40),
BDCRCCONT VARCHAR(15),
BDSIGLAUFCONT VARCHAR(2),
BDCPFCONT VARCHAR(14),
BDDDDCONT INTEGER,
BDFONECONT DM_BDTELEFONE,
BDDDDFAXCONT INTEGER,
BDFAXCONT DM_BDTELEFONE,
BDEMAILCONT DM_BDEMAIL,
BDVLRRECBRU1_6_IRLP NUMERIC(15,6),
BDVLRRECBRU8_IRLP NUMERIC(15,6),
BDVLRRECBRU16_IRLP NUMERIC(15,6),
BDVLRRECBRU32_IRLP NUMERIC(15,6),
BDVLRLUCROPRESUMIDO_IRLP NUMERIC(15,6),
BDVLRADICIONAL_IRLP NUMERIC(15,6),
BDVLRIMPOSTOPAGAR_IRLP NUMERIC(15,6),
BDVLRIMPOSTORETIDO_IRLP NUMERIC(15,6),
BDVLRALIQ15_IRLP NUMERIC(15,6),
BDVLRCSLLAPAGAR_IRLP NUMERIC(15,6),
BDVLRRECBRU12_IRLP NUMERIC(15,6),
BDVLRRECBRUAJUST_IRLP NUMERIC(15,6),
BDVLRCSLLAPURADA_IRLP NUMERIC(15,6),
BDVLRCSLLRETPJ NUMERIC(15,6),
BDREFERENCIA INTEGER,
BDTRIMESTRE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG19(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18))
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL SMALLINT)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG20(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDEXISTEMOV INTEGER,
BDPERIODO INTEGER,
BDMES INTEGER,
BDVLRSALDOCREANT NUMERIC(15,6),
BDVLRDEBITO NUMERIC(15,6),
BDVLRCREDITO NUMERIC(15,6),
BDVLRSALDO NUMERIC(15,6),
BDCREDORDEVEDOR INTEGER,
BDSEQUENCIAL INTEGER,
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG21(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDVLRINSUMOSNACIONAL NUMERIC(15,6),
BDVLRMERCADORIASNACIONAL NUMERIC(15,6),
BDVLRINDUSTOUTRASEMPNACIONAL NUMERIC(15,6),
BDVLRDEVVENDASNACIONAL NUMERIC(15,6),
BDVLROUTRASENTNACIONAL NUMERIC(15,6),
BDVLRINSUMOSEXTERIOR NUMERIC(15,6),
BDVLRMERCADORIASEXTERIOR NUMERIC(15,6),
BDVLRDEVVENDASEXTERIOR NUMERIC(15,6),
BDVLROUTRASENTEXTERIOR NUMERIC(15,6),
BDCOLUNA INTEGER,
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG22(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDVLRPRODNACIONAL NUMERIC(15,6),
BDVLRMERCADORIASNACIONAL NUMERIC(15,6),
BDVLRINDUSTOUTRASEMPNACIONAL NUMERIC(15,6),
BDVLRDEVCOMPRASNACIONAL NUMERIC(15,6),
BDVLROUTRASSAINACIONAL NUMERIC(15,6),
BDVLRPRODEXTERIOR NUMERIC(15,6),
BDVLRMERCADORIASEXTERIOR NUMERIC(15,6),
BDVLRINDUSTOUTRASEMPEXTERIOR NUMERIC(15,6),
BDVLRDEVCOMPRASEXTERIOR NUMERIC(15,6),
BDVLROUTRASSAIEXTERIOR NUMERIC(15,6),
BDCOLUNA INTEGER,
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG23(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDCGCTER VARCHAR(18),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG24(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDNCMPROD INTEGER,
BDCODPROD INTEGER,
BDCODSAIDA VARCHAR(60),
BDCODIGOEAN VARCHAR(20),
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDDESCPROD VARCHAR(200),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG25(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDCGCTER VARCHAR(18),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG26(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDNCMPROD INTEGER,
BDCODPROD INTEGER,
BDCODSAIDA VARCHAR(60),
BDCODIGOEAN VARCHAR(20),
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDDESCPROD VARCHAR(200),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG54(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRREFERENCIA INTEGER,
PRREFINI INTEGER = 0,
PRREFFIN INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDCNAEPREP INTEGER,
BDTIPOMATRIZFILIAL INTEGER,
BDRECEITA NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG59(PREMPRESAS VARCHAR(10000),
PRCODPAISBRASIL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODBEM INTEGER,
BDNOMBEM VARCHAR(200),
BDCODATVEXT INTEGER,
BDCODFED INTEGER,
BDVALAQUIBEMINI NUMERIC(15,6),
BDVALAQUIBEMFIN NUMERIC(15,6),
BDSEQUENCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG60_61A(PREMPRESAS VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRCODPAISBRASIL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODFED INTEGER,
BDTIPOPESSOA INTEGER,
BDCGCCEISOC VARCHAR(18),
BDCODSOC INTEGER,
BDNOMSOC VARCHAR(200),
BDEXPQUALISOC INTEGER,
BDCAPTOTCOTA NUMERIC(15,6),
BDCAPVOLCOTA NUMERIC(15,6),
BDCPFRESPLEGALSOC VARCHAR(14),
BDEXPQUALIRESPSOC INTEGER,
BDREMTRACOTA NUMERIC(15,6),
BDRENISECOTA NUMERIC(15,6),
BDRENTRICOTA NUMERIC(15,6),
BDDEMRENCOTA NUMERIC(15,6),
BDIRFONTCOTA NUMERIC(15,6),
BDSEQUENCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_GIASP(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(5),
BDDESCFORM VARCHAR(150),
BDCODNAT INTEGER,
BDVALOR NUMERIC(18,6),
BDVLRCONT NUMERIC(18,6),
BDBASEICMS NUMERIC(18,6),
BDVLRICMS NUMERIC(18,6),
BDISENTASICMS NUMERIC(18,6),
BDOUTRASICMS NUMERIC(18,6),
BDVLRST NUMERIC(18,6),
BDIMPSUBSTITUTO NUMERIC(18,6),
BDIMPSUBSTITUIDO NUMERIC(18,6),
BDOUTROSIMPOSTOS NUMERIC(18,6),
BDUF_R14 VARCHAR(2),
BDVALOR_CONTABIL_1_R14 NUMERIC(18,6),
BDBASECALCULO_1_R14 NUMERIC(18,6),
BDVALOR_CONTABIL_2_R14 NUMERIC(18,6),
BDBASECALCULO_2_R14 NUMERIC(18,6),
BDIMPOSTO_R14 NUMERIC(18,6),
BDOUTRAS_R14 NUMERIC(18,6),
BDICMSCOBRADOST_R14 NUMERIC(18,6),
BDPETROLEOENERGIA_R14 NUMERIC(18,6),
BDOUTROS_PRODUTOS_R14 NUMERIC(18,6),
BDCODIGO_R20 INTEGER,
BDOPERACAO_R20 INTEGER,
BDFUNLEGAL_R20 VARCHAR(150),
BDDESCRICAO_R20 VARCHAR(250),
BDINSCESTREM_R25 VARCHAR(15),
BDCODAUTORIZACAO_R28 VARCHAR(14),
BDVLRCONT1 NUMERIC(18,6),
BDBASEICMS1 NUMERIC(18,6),
BDVLRCONT2 NUMERIC(18,6),
BDBASEICMS2 NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_GISSONLINE(PREMPRESAS VARCHAR(10000),
PRTIPOLANC SMALLINT,
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRIGNORACID varchar(5))
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDNOMEMP DM_BDNOMEMP,
BDCODCIDEMP INTEGER,
BDNUMDOCINI VARCHAR(15),
BDNUMDOCFIN VARCHAR(15),
BDSERIE VARCHAR(6),
BDDATAEMISSAO DATE,
BDVLRCONTAB NUMERIC(15,6),
BDCODMUNATVM VARCHAR(20),
BDCODLOCEXP VARCHAR(1),
BDCODTPNFEXP VARCHAR(2),
BDCODOBRA VARCHAR(10),
BDCONSTCIVIL VARCHAR(5),
BDCODTER INTEGER,
BDCGCTER VARCHAR(18),
BDNOMETER VARCHAR(100),
BDCEPTER VARCHAR(9),
BDLOGRTER DM_LOGRADOURO,
BDENDTER DM_BDENDERECO,
BDNUMTER DM_NUMEND,
BDCOMPTER DM_BDCOMPENDERECO,
BDBAITER VARCHAR(60),
BDCODCIDTER INTEGER,
BDIMTER VARCHAR(16),
BDIETER VARCHAR(20),
BDSIGLAUFTER VARCHAR(2),
BDNOMCIDTER VARCHAR(40),
BDCODENQFEDTER INTEGER,
BDTIPOREG VARCHAR(1),
BDTIPLAN VARCHAR(1),
BDCODSITNF INTEGER,
BDBCISSSER NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_SPEDCONTRIBUICAO(PRCODEMP VARCHAR(10000),
    PRDATAINI DATE,
    PRDATAFIN DATE)
returns (
    BDCODEMP integer,
    BDCNPJEMP varchar(18),
    BDCODBEM integer,
    NAT_BC_CRED varchar(2),
    IDENT_BEM_IMOB varchar(2),
    IND_ORIG_CRED integer,
    IND_UTIL_BEM_IMOB integer,
    MES_OPER_AQUIS varchar(6),
    VL_OPER_AQUIS numeric(18,2),
    VL_OPER_DEP numeric(18,2),
    PARC_OPER_NAO_BC_CRED numeric(18,2),
    VL_BC_CRED numeric(18,2),
    IND_NR_PARC integer,
    CST_PIS varchar(2),
    VL_BC_PIS numeric(18,2),
    ALIQ_PIS numeric(18,4),
    VL_PIS numeric(18,2),
    CST_COFINS varchar(2),
    VL_BC_COFINS numeric(18,2),
    ALIQ_COFINS numeric(18,4),
    VL_COFINS numeric(18,2),
    COD_CTA varchar(255),
    COD_PLAPADRAO integer,
    ANO integer,
    COD_CCUS varchar(1000),
    DESC_BEM_IMOB varchar(300),
    BDDATABAIXA date,
    BDDATORIAQUIBEM date,
    COD_CTA_REF varchar(60),
    COD_PLAPADRAOREF integer,
    NUMPARC integer,
    BDCODCCSPED integer,
    BDDEPDIARIA varchar(5),
    BDNUMDIAS integer,
    BDDEPDIADATA integer,
    BDDEPMESBAIXABEM varchar(5),
    BDCALCPATRIMONIO varchar(5),
    BDCTALON varchar(40),
    BDCODCTA integer,
  BDCODMATRIZ integer,
    BDCODEMPDEPRE integer)
    --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a versão com a alteração abaixo corretamente.
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_TERCEIRO(PREMPRESA VARCHAR(2048),
PRCODTER INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRWHERETER VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCGCTER VARCHAR(18),
BDREFEMP INTEGER,
BDAPELIDOTER VARCHAR(20),
BDNOMETER VARCHAR(100),
BDLOGRTER DM_LOGRADOURO,
BDENDTER DM_BDENDERECO,
BDNUMTER DM_NUMEND,
BDCOMPTER DM_BDCOMPENDERECO,
BDCEPTER VARCHAR(9),
BDBAITER DM_BDBAIRRO,
BDDDDTER VARCHAR(3),
BDFONETER DM_BDTELEFONE,
BDFAXTER DM_BDTELEFONE,
BDEMAILTER DM_BDEMAIL,
BDIETER VARCHAR(20),
BDDATACADTER DATE,
BDIMTER VARCHAR(16),
BDPRURALTER VARCHAR(5),
BDENQSIMPLESFEDTER INTEGER,
BDINSCSUFRAMATER VARCHAR(10),
BDCODGPS INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDCODPAIS INTEGER,
BDDESCPAIS VARCHAR(60),
BDDDDFAXTER VARCHAR(3),
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure SP_GET_R1050_ENVIADO (
    PRCODEMP integer,
    PRREFFIM integer,
    PRBDCNPJSCP varchar(21))
returns (
    BDEXISTE DM_BOOLEAN)
as
declare variable WCODEVT integer;
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_TNATOP(PREMPRESA VARCHAR(2048),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODNAT INTEGER,
BDNOMENAT VARCHAR(255))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_EXP_TPRODUTOS(PREMPRESA VARCHAR(2048),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODPROD INTEGER,
BDNOMEPROD VARCHAR(255))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_LANCAMENTOS(PRREFMICRO INTEGER,
PRCODEMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDPERCISS NUMERIC(15,6),
BDRETINSS VARCHAR(5),
BDVLRMININSS NUMERIC(15,2),
BDCODPLANOONLINE INTEGER,
BDLANPROENT VARCHAR(5),
BDLANPROSAI VARCHAR(5),
BDLANBCICMSISEOUT INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_RET_TOT_NAT_ENT(PRREF INTEGER,
PREMP INTEGER,
PRWHERE VARCHAR(20000))
 RETURNS(BDREFLAN INTEGER,
BDCODEMP INTEGER,
BDCODNAT INTEGER,
BDVLRCONTAB NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDIMPEXCLUIDAS NUMERIC(15,6),
BDOUTROSIMP NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDICMSRETENT NUMERIC(15,6),
BDDIFALIQENT NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_RET_TOT_NAT_SAI(PRREF INTEGER,
PREMP INTEGER,
PRWHERE VARCHAR(20000))
 RETURNS(BDREFLAN INTEGER,
BDCODEMP INTEGER,
BDCODNAT INTEGER,
BDVLRCONTAB NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDIMPEXCLUIDAS NUMERIC(15,6),
BDOUTROSIMP NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDICMSFRETESAI NUMERIC(15,6),
BDACRECFINSAI NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_RETORNA_DIME_Q47(PRCODEMP VARCHAR(2048),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRSIMPLIFICADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREF INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDVALOR NUMERIC(15,2),
BDCODCIDTOT INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_RETORNA_DIME_Q48(PRCODEMP VARCHAR(2048),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRSIMPLIFICADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREF INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDCODCIDTOT INTEGER,
BDALIMPREP VARCHAR(5),
BDCODEXP VARCHAR(3),
BDCODATIVQ48 VARCHAR(3),
BDVALOR NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_RETORNA_DIME_VENC_PRODEC(PRCODEMP INTEGER,
PRREF INTEGER)
 RETURNS(BDDATAVENC DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_RETVLRSTSP(PRCODEMP VARCHAR(30000),
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDVLRSTSAI NUMERIC(15,2),
BDVLRSTENT NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SPED_LAN_ENT(PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDCODTER INTEGER,
BDNUMDOCINI INTEGER,
BDDATAEMISSAO DATE,
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6),
BDSUBSERIE VARCHAR(3),
BDNUMDOCFIM INTEGER,
BDMODELO INTEGER,
BDEMITENTE INTEGER,
BDDATAENTRADAENT DATE,
BDCODSITNF INTEGER,
BDCODCTA INTEGER,
BDTIPOASSINANTE INTEGER,
BDVLRSER NUMERIC(15,6),
BDVLRSERNTRIB NUMERIC(15,6),
BDVLRCOBTERC NUMERIC(15,6),
BDVLROUTDESP_D500 NUMERIC(15,6),
BDVLRPIS_D500 NUMERIC(15,6),
BDVLRCOFINS_D500 NUMERIC(15,6),
BDCODTENSAO INTEGER,
BDVLRCONSFOR NUMERIC(15,6),
BDVLRCOBTER NUMERIC(15,6),
BDVLRDESPACE NUMERIC(15,6),
BDVLRPIS_C500 NUMERIC(15,6),
BDVLRCOFINS_C500 NUMERIC(15,6),
BDTIPOLIGACAO INTEGER,
BDCHAVENFE VARCHAR(60),
BDINDFRETE INTEGER,
BDVLRFRETE NUMERIC(15,6),
BDVLRSEGURO NUMERIC(15,6),
BDVLROUTDESP_C100 NUMERIC(15,6),
BDVLRTOTPIS NUMERIC(15,6),
BDVLRTOTCOFINS NUMERIC(15,6),
BDVLRTOTPISST NUMERIC(15,6),
BDVLRTOTCOFINSST NUMERIC(15,6),
BDCODOBS INTEGER,
BDCODNAT INTEGER,
BDALIQICMS NUMERIC(15,6),
BDALIQST NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDIMPEXCLUIDAS NUMERIC(15,6),
BDOUTROSIMP NUMERIC(15,6),
BDREDBCICMS NUMERIC(15,6),
BDVLRCONTAB NUMERIC(15,6),
BDCONDPGTO INTEGER,
BDDESCONTO NUMERIC(15,6),
BDTIPOLANENT VARCHAR(1),
BDICMSRETENT NUMERIC(15,6),
BDTIPORETENT INTEGER,
BDDIFALIQENT NUMERIC(15,6),
BDVLRPISRET NUMERIC(15,6),
BDVLRCOFINSRET NUMERIC(15,6),
BDVLRCSOCIALRET NUMERIC(15,6),
BDIMPSUBSTITUIDORET NUMERIC(15,6),
BDIMPSUBSTITUTORET NUMERIC(15,6),
BDCODCTA_C300 INTEGER,
BDVLRTOTPIS_C300 NUMERIC(15,6),
BDVLRTOTCOFINS_C300 NUMERIC(15,6),
BDCODCONS INTEGER,
BDCODINFCOM_C500 VARCHAR(6),
BDCODINFCOM_D500 VARCHAR(6),
BDCODCTA_D100 INTEGER,
BDORDEMINFCOM_D100 VARCHAR(6),
BDCHAVECTE_D100 VARCHAR(44),
BDTIPOCTE_D100 INTEGER,
BDCHAVECTEREF_D100 VARCHAR(44),
BDINDFRETE_D100 INTEGER,
BDCSTICMS VARCHAR(3),
BDPREFIXONAT INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SPED_LAN_ENT_PRO(PRREF INTEGER,
PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDORDEMPRO INTEGER,
BDCODCTA INTEGER,
BDCODPROD INTEGER,
BDCODCSTCOF INTEGER,
BDCODCSTICMS INTEGER,
BDCODCSTPIS INTEGER,
BDCODCSTIPI INTEGER,
BDMOVFISICO VARCHAR(5),
BDQTDITEM NUMERIC(15,6),
BDVLRITEM NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRDESPACESSORIA NUMERIC(15,6),
BDREDBCICMS NUMERIC(15,6),
BDBCICMS NUMERIC(15,6),
BDBCPIS NUMERIC(15,6),
BDBCST NUMERIC(15,6),
BDBCIPI NUMERIC(15,6),
BDBCCOFINS NUMERIC(15,6),
BDBCISSQN NUMERIC(15,6),
BDALIQICMS NUMERIC(15,6),
BDALIQPIS NUMERIC(15,6),
BDALIQST NUMERIC(15,6),
BDALIQIPI NUMERIC(15,6),
BDALIQCOFINS NUMERIC(15,6),
BDALIQISSQN NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRPIS NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRCOFINS NUMERIC(15,6),
BDVLRISSQN NUMERIC(15,6),
BDDESCPROD VARCHAR(200),
BDCSTICMS VARCHAR(3),
BDCODEXPCSTIPI INTEGER,
BDAPEUNIMEDFAT VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SPED_LAN_SAI(PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDCODTER INTEGER,
BDNUMDOCINI INTEGER,
BDDATAEMISSAO DATE,
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6),
BDSUBSERIE VARCHAR(3),
BDNUMDOCFIM INTEGER,
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDEMITENTE INTEGER,
BDDATASAIDA DATE,
BDCODSITNF INTEGER,
BDCODCTA INTEGER,
BDTIPOASSINANTE INTEGER,
BDVLRSER NUMERIC(15,6),
BDVLRSERNTRIB NUMERIC(15,6),
BDVLRCOBTERC NUMERIC(15,6),
BDVLROUTDESP_D500 NUMERIC(15,6),
BDVLRPIS_D500 NUMERIC(15,6),
BDVLRCOFINS_D500 NUMERIC(15,6),
BDCODTENSAO INTEGER,
BDVLRCONSFOR NUMERIC(15,6),
BDVLRCOBTER NUMERIC(15,6),
BDVLRDESPACE NUMERIC(15,6),
BDVLRPIS_C500 NUMERIC(15,6),
BDVLRCOFINS_C500 NUMERIC(15,6),
BDTIPOLIGACAO INTEGER,
BDCHAVENFE VARCHAR(60),
BDINDFRETE INTEGER,
BDVLRFRETE NUMERIC(15,6),
BDVLRSEGURO NUMERIC(15,6),
BDVLROUTDESP_C100 NUMERIC(15,6),
BDVLRTOTPIS NUMERIC(15,6),
BDVLRTOTCOFINS NUMERIC(15,6),
BDVLRTOTPISST NUMERIC(15,6),
BDVLRTOTCOFINSST NUMERIC(15,6),
BDCODTER_VLTRAN INTEGER,
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2),
BDQTDVOLTRAN NUMERIC(15,6),
BDPESOBRUTO NUMERIC(15,6),
BDPESOLIQUIDO NUMERIC(15,6),
BDPLACAID VARCHAR(8),
BDCODOBS INTEGER,
BDCODNAT INTEGER,
BDALIQICMS NUMERIC(15,6),
BDALIQST NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDIMPEXCLUIDAS NUMERIC(15,6),
BDOUTROSIMP NUMERIC(15,6),
BDREDBCICMS NUMERIC(15,6),
BDVLRCONTAB NUMERIC(15,6),
BDCONDPGTO INTEGER,
BDDESCONTO NUMERIC(15,6),
BDICMSFRETESAI NUMERIC(15,6),
BDACRECFINSAI NUMERIC(15,6),
BDREGEXPSAI VARCHAR(16),
BDVLRPISRET NUMERIC(15,6),
BDVLRCOFINSRET NUMERIC(15,6),
BDVLRCSOCIALRET NUMERIC(15,6),
BDIMPSUBSTITUIDORET NUMERIC(15,6),
BDIMPSUBSTITUTORET NUMERIC(15,6),
BDVLRIRRET NUMERIC(15,6),
BDINSSRET NUMERIC(15,6),
BDISSRET NUMERIC(15,6),
BDCGCTER VARCHAR(18),
BDCODCTA_C300 INTEGER,
BDVLRTOTPIS_C300 NUMERIC(15,6),
BDVLRTOTCOFINS_C300 NUMERIC(15,6),
BDCODCONS INTEGER,
BDCODINFCOM_C500 VARCHAR(6),
BDCODINFCOM_D500 VARCHAR(6),
BDCODCTA_D100 INTEGER,
BDORDEMINFCOM_D100 VARCHAR(6),
BDCHAVECTE_D100 VARCHAR(44),
BDTIPOCTE_D100 INTEGER,
BDCHAVECTEREF_D100 VARCHAR(44),
BDINDFRETE_D100 INTEGER,
BDCSTICMS VARCHAR(3),
BDPREFIXONAT INTEGER,
BDVALORTOTALNOTA NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SPED_LAN_SAI_PRO(PRREF INTEGER,
PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDORDEMPRO INTEGER,
BDCODCTA INTEGER,
BDCODPROD INTEGER,
BDCODCSTCOF INTEGER,
BDCODCSTICMS INTEGER,
BDCODCSTPIS INTEGER,
BDCODCSTIPI INTEGER,
BDMOVFISICO VARCHAR(5),
BDQTDITEM NUMERIC(15,6),
BDVLRITEM NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRDESPACESSORIA NUMERIC(15,6),
BDREDBCICMS NUMERIC(15,6),
BDBCICMS NUMERIC(15,6),
BDBCPIS NUMERIC(15,6),
BDBCST NUMERIC(15,6),
BDBCIPI NUMERIC(15,6),
BDBCCOFINS NUMERIC(15,6),
BDBCISSQN NUMERIC(15,6),
BDALIQICMS NUMERIC(15,6),
BDALIQPIS NUMERIC(15,6),
BDALIQST NUMERIC(15,6),
BDALIQIPI NUMERIC(15,6),
BDALIQCOFINS NUMERIC(15,6),
BDALIQISSQN NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRPIS NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRCOFINS NUMERIC(15,6),
BDVLRISSQN NUMERIC(15,6),
BDDESCPROD VARCHAR(200),
BDCSTICMS VARCHAR(3),
BDCODEXPCSTIPI INTEGER,
BDCODCLAENETEL INTEGER,
BDINDREC INTEGER,
BDCODCLAENETELGAS INTEGER,
BDINDRECGAS INTEGER,
BDCODSELOIPI INTEGER,
BDQTDSELOIPI INTEGER,
BDCODCLASSEIPI VARCHAR(5),
BDVLRUNIDADE NUMERIC(15,6),
BDQTDUNIDADE NUMERIC(15,6),
BDAPEUNIMEDFAT VARCHAR(5),
BDCODSAIDA VARCHAR(60))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SPED_TERCEIRO(PRCODTER INTEGER,
PRREF INTEGER,
PRWHERETER VARCHAR(20000))
 RETURNS(BDCODTER INTEGER,
BDCGCTER VARCHAR(18),
BDREFEMP INTEGER,
BDAPELIDOTER VARCHAR(20),
BDNOMETER VARCHAR(100),
BDLOGRTER DM_LOGRADOURO,
BDENDTER DM_BDENDERECO,
BDNUMTER DM_NUMEND,
BDCOMPTER DM_BDCOMPENDERECO,
BDCEPTER VARCHAR(9),
BDBAITER DM_BDBAIRRO,
BDDDDTER VARCHAR(3),
BDFONETER DM_BDTELEFONE,
BDFAXTER DM_BDTELEFONE,
BDEMAILTER DM_BDEMAIL,
BDIETER VARCHAR(20),
BDDATACADTER DATE,
BDIMTER VARCHAR(16),
BDPRURALTER VARCHAR(5),
BDENQSIMPLESFEDTER INTEGER,
BDINSCSUFRAMATER VARCHAR(10),
BDCODGPS INTEGER,
BDCODCID INTEGER,
BDCODPAIS INTEGER,
BDDDDFAXTER VARCHAR(3),
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2),
BDCODSPED INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_431(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRENTRADA VARCHAR(5),
PRSAIDA VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDMODELOAUX VARCHAR(15),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDORDEM INTEGER,
BDVLRCONTAB NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDIMPEXCLUIDAS NUMERIC(15,6),
BDOUTROSIMP NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDICMSRETENT NUMERIC(15,6),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRIPIPRO NUMERIC(15,6),
BDVLRICMSPRO NUMERIC(15,6),
BDVLRFRETEC100 NUMERIC(15,6),
BDVLRSEGUROC100 NUMERIC(15,6),
BDVLROUTDESPC100 NUMERIC(15,6),
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDVLRCSOCIAL NUMERIC(15,2),
BDVLRIR NUMERIC(15,2),
BDINSSRET NUMERIC(15,2),
BDCGCTER VARCHAR(18),
BDORDEMPRO INTEGER,
BDTIPOREG VARCHAR(10),
BDALIQPIS NUMERIC(5,2),
BDALIQCOFINS NUMERIC(5,2),
BDALIQIR NUMERIC(5,2),
BDALIQCSOCIAL NUMERIC(5,2),
BDBINSSRET NUMERIC(15,2),
BDRETVAZIO VARCHAR(1),
BDVLRCONTAB2 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SPED_D600 (
    PREMPRESA INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE)
RETURNS (
    BDCHAVES VARCHAR(20000),
    BDQUANTIDADE INTEGER,
    BDMODELO INTEGER,
    BDCODIBGE INTEGER,
    BDSERIE VARCHAR(6),
    BDSUBSERIE VARCHAR(6),
    BDCODEXP VARCHAR(2),
    BDDATAEMISSAO DATE,
    BDVALORNOTA NUMERIC(15,6),
    BDVLRSER NUMERIC(15,6),
    BDVLRSERNTRIB NUMERIC(15,6),
    BDVLRCOBTERC NUMERIC(15,6),
    BDVLROUTDESP NUMERIC(15,6))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SPED_D610 (
    PREMPRESA INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE)
RETURNS (
    BDCHAVES VARCHAR(20000),
    BDMODELO INTEGER,
    BDCODIBGE INTEGER,
    BDSERIE VARCHAR(6),
    BDSUBSERIE VARCHAR(6),
    BDCODEXP VARCHAR(2),
    BDDATAEMISSAO DATE,
    BDCODNAT VARCHAR(4),
    BDCODPROD INTEGER,
    BDCODSAIDA VARCHAR(60),
    BDCODCSTICMS INTEGER,
    BDALIQICMS NUMERIC(15,6),
    BDCLASSENETEL VARCHAR(4),
    BDQTDITEM INTEGER,
    BDAPEUNIMED VARCHAR(20),
    BDVLRITEM NUMERIC(15,6),
    BDVLRDESC NUMERIC(15,6),
    BDCSTICMS VARCHAR(3),
    BDBCICMS NUMERIC(15,6),
    BDVLRICMS NUMERIC(15,6),
    BDVLRPRODPIS NUMERIC(15,6),
    BDVLRPRODCOFINS NUMERIC(15,6),
    BDVLRDESPACESSORIA NUMERIC(15,6),
    BDBCST NUMERIC(15,6),
    BDVLRST NUMERIC(15,6))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SPED_D696 (
    PREMPRESA INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE)
RETURNS (
    BDCHAVES VARCHAR(10000),
    BDMODELO INTEGER,
    BDSERIE VARCHAR(6),
    BDCODNAT VARCHAR(4),
    BDCODCSTICMS INTEGER,
    BDALIQICMS NUMERIC(15,6),
    BDVLRITEM NUMERIC(15,6),
    BDCSTICMS VARCHAR(3),
    BDBCICMS NUMERIC(15,6),
    BDVLRICMS NUMERIC(15,6),
    BDBCST NUMERIC(15,6),
    BDVLRST NUMERIC(15,6))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_4310_TREDZ(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDDATAREDZ DATE,
BDCODPROD INTEGER,
BDQTDITEM NUMERIC(15,3),
BDALIQICMS NUMERIC(15,2),
BDCAMPO8 NUMERIC(15,2),
BDVLRTOTPRO NUMERIC(15,2),
BDALIQPIS NUMERIC(15,4),
BDVLRPIS NUMERIC(15,2),
BDALIQCOFINS NUMERIC(15,4),
BDVLRCOFINS NUMERIC(15,2),
BDNCMPROD INTEGER,
BDTIPOREG VARCHAR(10))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_432(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRENTRADA VARCHAR(5),
PRSAIDA VARCHAR(5),
PRODFRETE INTEGER,
PRODENERGIA INTEGER,
PRODAGUA INTEGER,
PRODTELECOM INTEGER,
PRODGENERICO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDORDEM INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDBASEICMS NUMERIC(15,2),
BDBASEIPI NUMERIC(15,2),
BDBASEST NUMERIC(15,2),
BDISENTASICMS NUMERIC(15,2),
BDISENTASIPI NUMERIC(15,2),
BDOUTRASICMS NUMERIC(15,2),
BDOUTRASIPI NUMERIC(15,2),
BDVLRICMS NUMERIC(15,2),
BDVLRIPI NUMERIC(15,2),
BDVLRST NUMERIC(15,2),
BDIMPEXCLUIDAS NUMERIC(15,2),
BDOUTROSIMP NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDICMSRETENT NUMERIC(15,2),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,2),
BDVLRDESC NUMERIC(15,2),
BDVLRIPIPRO NUMERIC(15,2),
BDVLRICMSPRO NUMERIC(15,2),
BDVLRFRETEC100 NUMERIC(15,2),
BDVLRSEGUROC100 NUMERIC(15,2),
BDVLROUTDESPC100 NUMERIC(15,2),
BDORDEMPRO INTEGER,
BDCODPROD INTEGER,
BDDESCPROD VARCHAR(200),
BDCODNAT INTEGER,
BDNCMPROD INTEGER,
BDQTDITEM NUMERIC(15,3),
BDAPEUNIMED VARCHAR(3),
BDALIQIPIPRO NUMERIC(15,2),
BDBCIPIPRO NUMERIC(15,2),
BDCODCSTICMS VARCHAR(3),
BDALIQICMSPRO NUMERIC(15,2),
BDBCICMSPRO NUMERIC(15,2),
BDBCSTPRO NUMERIC(15,2),
BDVLRSTMOVPRO NUMERIC(15,2),
BDMOVFISICO VARCHAR(5),
BDCODEXPCSTIPI INTEGER,
BDCODCSTPIS INTEGER,
BDALIQPIS NUMERIC(15,4),
BDBCPIS NUMERIC(15,3),
BDVLRPIS NUMERIC(15,2),
BDCODCSTCOF INTEGER,
BDALIQCOFINS NUMERIC(15,4),
BDBCCOFINS NUMERIC(15,3),
BDVLRCOFINS NUMERIC(15,2),
BDCSTPIS VARCHAR(3),
BDCSTCOF VARCHAR(3),
BDVLRUNITARIO NUMERIC(15,4),
BDVLRCOFINSEXP NUMERIC(15,2),
BDVLRCOFINSTRIBINT NUMERIC(15,2),
BDVLRCOFINSNTRIBINT NUMERIC(15,2),
BDVLRPISEXP NUMERIC(15,2),
BDVLRPISTRIBINT NUMERIC(15,2),
BDVLRPISNTRIBINT NUMERIC(15,2),
BDLANBCICMSISEOUT INTEGER,
BDTIPOREG VARCHAR(10),
BDPRODFRETE VARCHAR(5),
BDPRODENERGIA VARCHAR(5),
BDPRODAGUA VARCHAR(5),
BDPRODTELECOM VARCHAR(5),
BDPRODGENERICO VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_433(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDCGCTER VARCHAR(18),
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDVLRCONTAB NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDIMPEXCLUIDAS NUMERIC(15,6),
BDOUTROSIMP NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDICMSRETENT NUMERIC(15,6),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRDESPACESSORIAPRO NUMERIC(15,6),
BDVLRIPIPRO NUMERIC(15,6),
BDVLRICMSPRO NUMERIC(15,6),
BDTIPOREG VARCHAR(10),
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDVLRCSOCIAL NUMERIC(15,2),
BDALIQPIS NUMERIC(5,2),
BDALIQCOFINS NUMERIC(5,2),
BDALIQIR NUMERIC(5,2),
BDALIQCSOCIAL NUMERIC(5,2),
BDVLRIR NUMERIC(15,2),
BDINSSRET NUMERIC(15,2),
BDVLRPISRET NUMERIC(15,2),
BDVLRCOFINSRET NUMERIC(15,2),
BDVLRCSLLRET NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_434(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRODFRETE INTEGER,
PRODENERGIA INTEGER,
PRODAGUA INTEGER,
PRODTELECOM INTEGER,
PRODGENERICO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDORDEM INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDBASEICMS NUMERIC(15,2),
BDBASEIPI NUMERIC(15,2),
BDBASEST NUMERIC(15,2),
BDISENTASICMS NUMERIC(15,2),
BDISENTASIPI NUMERIC(15,2),
BDOUTRASICMS NUMERIC(15,2),
BDOUTRASIPI NUMERIC(15,2),
BDVLRICMS NUMERIC(15,2),
BDVLRIPI NUMERIC(15,2),
BDVLRST NUMERIC(15,2),
BDIMPEXCLUIDAS NUMERIC(15,2),
BDOUTROSIMP NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDICMSRETENT NUMERIC(15,2),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,2),
BDVLRDESC NUMERIC(15,2),
BDVLRIPIPRO NUMERIC(15,2),
BDVLRICMSPRO NUMERIC(15,2),
BDVLRFRETEC100 NUMERIC(15,2),
BDVLRSEGUROC100 NUMERIC(15,2),
BDVLROUTDESPC100 NUMERIC(15,2),
BDORDEMPRO INTEGER,
BDCODPROD INTEGER,
BDDESCPROD VARCHAR(200),
BDCODNAT INTEGER,
BDNCMPROD INTEGER,
BDQTDITEM NUMERIC(15,3),
BDAPEUNIMED VARCHAR(3),
BDALIQIPIPRO NUMERIC(15,2),
BDBCIPIPRO NUMERIC(15,2),
BDCODCSTICMS VARCHAR(3),
BDALIQICMSPRO NUMERIC(15,2),
BDBCICMSPRO NUMERIC(15,2),
BDBCSTPRO NUMERIC(15,2),
BDVLRSTMOVPRO NUMERIC(15,2),
BDMOVFISICO VARCHAR(5),
BDCODEXPCSTIPI INTEGER,
BDCODCSTPIS INTEGER,
BDALIQPIS NUMERIC(15,4),
BDBCPIS NUMERIC(15,3),
BDVLRPIS NUMERIC(15,2),
BDCODCSTCOF INTEGER,
BDALIQCOFINS NUMERIC(15,4),
BDBCCOFINS NUMERIC(15,3),
BDVLRCOFINS NUMERIC(15,2),
BDCGCTER VARCHAR(18),
BDCAMPO10 NUMERIC(15,2),
BDCAMPO11 NUMERIC(15,2),
BDCAMPO12 NUMERIC(15,2),
BDCAMPO17 NUMERIC(15,2),
BDCAMPO18 NUMERIC(15,2),
BDCAMPO19 NUMERIC(15,2),
BDVLRUNITARIO NUMERIC(15,4),
BDLANBCICMSISEOUT INTEGER,
BDTIPOREG VARCHAR(10),
BDPRODFRETE VARCHAR(5),
BDPRODENERGIA VARCHAR(5),
BDPRODAGUA VARCHAR(5),
BDPRODTELECOM VARCHAR(5),
BDPRODGENERICO VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_491(PREMPRESA VARCHAR(10000),
PRCODTER INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDDATACADTER DATE,
BDCODTER INTEGER,
BDCGCTER VARCHAR(18),
BDIETER VARCHAR(20),
BDIMTER VARCHAR(16),
BDNOMETER VARCHAR(100),
BDLOGRTER DM_LOGRADOURO,
BDENDTER DM_BDENDERECO,
BDENDEXPTER DM_BDENDERECO,
BDNUMTER DM_NUMEND,
BDCOMPTER DM_BDCOMPENDERECO,
BDBAITER VARCHAR(60),
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDCEPTER VARCHAR(9),
BDDESCPAIS VARCHAR(60),
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDCODCGCTER VARCHAR(18))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_494(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDCODNAT INTEGER,
BDNOMENAT VARCHAR(255),
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_495(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRPROD VARCHAR(10000))
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDCODPROD INTEGER,
BDNOMEPROD VARCHAR(255),
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_EXP_491(PREMPRESA VARCHAR(10000),
PRCODTER INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_EXP_494(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_EXP_495(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_EXP_CAD(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_SERVICOS_ITENS(PREMPRESA VARCHAR(10000),
PRTIPOLAN INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRODSERVICO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDCODCID INTEGER,
BDTIPOMOV VARCHAR(3),
BDDATAEMISSAO DATE,
BDCODTER INTEGER,
BDNUMDOC INTEGER,
BDTIPLAN VARCHAR(1),
BDESPECIE VARCHAR(6),
BDSERIE VARCHAR(5),
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDORDEM INTEGER,
BDCODNAT INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDALIQIRSER NUMERIC(15,2),
BDBCIRSER NUMERIC(15,2),
BDVLRIRSER NUMERIC(15,2),
BDVLRISSSER NUMERIC(15,2),
BDIDCFPS INTEGER,
BDCODREC INTEGER,
BDCODOBS INTEGER,
BDIDCST INTEGER,
BDCONDPGTO INTEGER,
BDCONDPGTOAUX VARCHAR(1),
BDALIQREDBCISSSER NUMERIC(15,2),
BDBCISSSER NUMERIC(15,2),
BDALIQREDISSSER NUMERIC(15,2),
BDISENTASISSSER NUMERIC(15,2),
BDOUTRASISSSER NUMERIC(15,2),
BDACREDEDUIRSER NUMERIC(15,2),
BDACRECFINSER NUMERIC(15,2),
BDDIGOPERNAT INTEGER,
BDPREFIXONAT INTEGER,
BDCODATVM INTEGER,
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDCAMPO10 VARCHAR(1),
BDTIPOREG VARCHAR(10),
BDCODCSTPIS VARCHAR(2),
BDALIQPIS NUMERIC(15,4),
BDBCPIS NUMERIC(15,3),
BDCODCSTCOF VARCHAR(2),
BDALIQCOFINS NUMERIC(15,4),
BDBCCOFINS NUMERIC(15,3),
BDCAMPO07_4106 NUMERIC(15,2),
BDCAMPO14_4106 NUMERIC(15,2),
BDVLRCONTAB_4106 NUMERIC(15,3),
BDCAMPO10_4106 NUMERIC(15,2),
BDCAMPO17_4106 NUMERIC(15,2),
BDDESCPROD VARCHAR(45),
BDPRODSERVICO VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_SVA_SERVICOS_MOV(PREMPRESA VARCHAR(10000),
PRTIPOLAN INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDDATAEMISSAO DATE,
BDCODTER INTEGER,
BDNUMDOC INTEGER,
BDTIPLAN VARCHAR(1),
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6),
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDVLRCONTAB NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDALIQIRSER NUMERIC(15,2),
BDBCIRSER NUMERIC(15,2),
BDVLRIRSER NUMERIC(15,2),
BDVLRISSSER NUMERIC(15,2),
BDIDCFPS INTEGER,
BDCODREC INTEGER,
BDIDCST INTEGER,
BDALIQREDBCISSSER NUMERIC(15,2),
BDBCISSSER NUMERIC(15,2),
BDALIQREDISSSER NUMERIC(15,2),
BDISENTASISSSER NUMERIC(15,2),
BDOUTRASISSSER NUMERIC(15,2),
BDACREDEDUIRSER NUMERIC(15,2),
BDACRECFINSER NUMERIC(15,2),
BDDIGOPERNAT INTEGER,
BDPREFIXONAT INTEGER,
BDCODATVM INTEGER,
BDCAMPO10 VARCHAR(1),
BDTIPOREG VARCHAR(10),
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDVLRCSOCIAL NUMERIC(15,2),
BDALIQPIS NUMERIC(5,2),
BDALIQCOFINS NUMERIC(5,2),
BDALIQCSOCIAL NUMERIC(5,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VEF_SP_TREEVIEW_CONS_ANUAL_CONF(PRCODEMP VARCHAR(10000),
PRREF INTEGER,
PRCODPLANO INTEGER,
PRCODQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDREF INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDORDEM INTEGER,
BDDESCRICAO VARCHAR(80),
BDVALOR NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDJAN NUMERIC(15,6),
BDFEV NUMERIC(15,6),
BDMAR NUMERIC(15,6),
BDABR NUMERIC(15,6),
BDMAI NUMERIC(15,6),
BDJUN NUMERIC(15,6),
BDJUL NUMERIC(15,6),
BDAGO NUMERIC(15,6),
BDSET NUMERIC(15,6),
BDOUT NUMERIC(15,6),
BDNOV NUMERIC(15,6),
BDDEZ NUMERIC(15,6),
BDCODMATRIZ INTEGER,
BDREGAUX INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VLAL_CONSULTA_APU_TREEWIEW(PRCODEMP VARCHAR(2048),
PRDATAINI DATE,
PRDATAFIM DATE,
PRPERAPU INTEGER)
 RETURNS(BDDATA VARCHAR(10),
BDSAIDA VARCHAR(30))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VLAL_COPIA_PARTEA_PLANO(APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VLAL_COPIA_PARTEB_PLANO(APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VLAL_SP_CONS_ACUM_PARTEA(PRCODEMP INTEGER,
PRCODLPA INTEGER,
PRCODTIPO INTEGER,
PRREFLANAN VARCHAR(10))
 RETURNS(BDREFLANAN INTEGER,
BDCODTHPI INTEGER,
BDNOME VARCHAR(40),
BDVALLANAN NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VLAL_SP_LAN_PARTEA(PREMPRESA INTEGER,
PRCODLLA INTEGER,
PRCODUSU INTEGER,
PRANOBASE INTEGER,
PRCODPARTEA INTEGER,
PRCODLPA INTEGER,
PRCODTPHI INTEGER,
PRANUALACUMULADO SMALLINT,
PRVALOR1 NUMERIC(15,2),
PRCOMPL1 VARCHAR(200),
PRVALOR2 NUMERIC(15,2),
PRCOMPL2 VARCHAR(200),
PRVALOR3 NUMERIC(15,2),
PRCOMPL3 VARCHAR(200),
PRVALOR4 NUMERIC(15,2),
PRCOMPL4 VARCHAR(200),
PRVALOR5 NUMERIC(15,2),
PRCOMPL5 VARCHAR(200),
PRVALOR6 NUMERIC(15,2),
PRCOMPL6 VARCHAR(200),
PRVALOR7 NUMERIC(15,2),
PRCOMPL7 VARCHAR(200),
PRVALOR8 NUMERIC(15,2),
PRCOMPL8 VARCHAR(200),
PRVALOR9 NUMERIC(15,2),
PRCOMPL9 VARCHAR(200),
PRVALOR10 NUMERIC(15,2),
PRCOMPL10 VARCHAR(200),
PRVALOR11 NUMERIC(15,2),
PRCOMPL11 VARCHAR(200),
PRVALOR12 NUMERIC(15,2),
PRCOMPL12 VARCHAR(200),
PRREFEMP INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VLAL_SP_RETORNA_INT_CONTABLALUR(PRCODEMP VARCHAR(2048),
PRMATRIZFILIAL VARCHAR(2048),
PRCODCONTABLALUR INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRACUMULADO INTEGER,
PRDATALANC DATE,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRTIPOLANC INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRREFERENCIA INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRINTCONTABILLALUR INTEGER = 0,
PRCODPLAHISTLALUR INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA VARCHAR(7),
BDMESANO INTEGER,
BDDATA DATE,
BDCONTA INTEGER,
BDVALOR NUMERIC(15,2),
BDTIPOLANC INTEGER,
BDCODTPLA INTEGER,
BDCHAVELAN INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VLAL_SP_DEMONSTRACAO_PARTEB (
    PRCODEMP INTEGER,
    PRDATAINICIALREL DATE,
    PRDATAINICIAL DATE,
    PRDATAFINAL DATE,
    PRMODELOREL INTEGER,
    PRREFERENCIA INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCODLLB INTEGER,
    BDCODPARTEB INTEGER,
    BDNOMPARTEB VARCHAR(40),
    BDINDICE INTEGER,
    BDDEBCODLPB INTEGER,
    BDCTALONLPBDEB VARCHAR(20),
    BDNOMLPBDEB VARCHAR(60),
    BDDEBVALLLB INTEGER,
    BDCRECODPLB INTEGER,
    BDCTALONLPBCRE VARCHAR(20),
    BDNOMLPBCRE VARCHAR(60),
    BDCREVALLLB INTEGER,
    BDCODLPB INTEGER,
    BDCTALONLPB VARCHAR(20),
    BDNOMLPB VARCHAR(60),
    BDDATLLB DATE,
    BDVALLLB NUMERIC(15,2),
    BDSALANT NUMERIC(15,2),
    BDSALATU NUMERIC(15,2),
    BDCOMPLLLB VARCHAR(200),
    BDCOMPENSACAO DM_BOOLEAN,
    BDMODELO VARCHAR(10))
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_COPIA_FUNCOES_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VRH_COPIA_LAYOUT_PLALANC(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VRH_COPIA_VERBASBS_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VRH_INS_VERBA(PRCLASS VARCHAR(9))
 RETURNS(VERBATITULO INTEGER,
NOVAVERBA INTEGER,
NOVACLASS VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_ADMITIDOS_NO_MES(PRCODEMP VARCHAR(15000),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDADMITIDOS INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_ALTERACAOSALARIAL(PREMPRESA VARCHAR(15000),
PRCOLABORADOR VARCHAR(15000),
PRDATAINICIAL DATE,
PRDATAFINAL DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATACOL DATE,
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDDESCMAS VARCHAR(50),
BDCODTFUC INTEGER,
BDDESCTFUC VARCHAR(40),
BDCODCBO INTEGER,
BDTIPOCOL INTEGER,
BDSALINICOL NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_ATIVOS_NO_MES(PRCODEMP VARCHAR(15000),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDATIVOS INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_AUMENTOSALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDATAADMCOL DATE,
BDDATACOL DATE,
BDSALBASECOLANT NUMERIC(15,2),
BDSALBASECOLATU NUMERIC(15,2),
BDCODMAS INTEGER,
BDDESCMAS VARCHAR(50),
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDCODTFUC INTEGER,
BDDESCTFUC VARCHAR(40),
BDHORASMENSAISCOL NUMERIC(15,2),
BDTIPOCOL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_CAD_TERC(PRCODCOL VARCHAR(32700),
PRCODCLA VARCHAR(1000),
PRREF INTEGER,
PRCOLCON SMALLINT,
PRCOLCON_DOC SMALLINT,
PRCOLCON_VINC SMALLINT,
PRCOLCON_BANCO SMALLINT,
PRCOLCON_CALC SMALLINT,
PRCOLCON_FGTSGPS SMALLINT,
PRCOLCON_MVINC SMALLINT,
PRCOLCON_DIA SMALLINT)
 RETURNS(BDCODCOL INTEGER,
BDCODMCAG INTEGER,
BDCODCID INTEGER,
BDCODCSEG INTEGER,
BDREFCSEG INTEGER,
BDCODCIDNASC INTEGER,
BDCODUF INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDLOGRCOL VARCHAR(15),
BDENDCOL DM_BDENDERECO,
BDNUMCOL DM_NUMEND,
BDCOMPLCOL DM_BDCOMPENDERECO,
BDBAICOL DM_BDBAIRRO,
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL DM_BDTELEFONE,
BDCELCOL DM_BDTELEFONE,
BDEMAILCOL DM_BDEMAIL,
BDSEXOCOL INTEGER,
BDDATANASCCOL DATE,
BDDATACADCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDRGCOL VARCHAR(13),
BDORGEMIRGCOL DM_ORGAOEMISSOR,
BDDATAEMIRGCOL DATE,
BDCPFCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDCODUF_COL_DOC INTEGER,
BDTITELEICOL VARCHAR(13),
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDCATCNHCOL VARCHAR(2),
BDCODCID_HIST INTEGER,
BDCODPAIS INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDDATACHEBRASILCOL DATE,
BDCODCIDNASCCONJ INTEGER,
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCONJCOL DATE,
BDCORCOL INTEGER,
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDDEFFISICOCOL INTEGER,
BDTIPOSANGUECOL INTEGER,
BDNROCONSPROCOL VARCHAR(20),
BDSIGLACONSPROCOL VARCHAR(5),
BDCODCCMPROCOL VARCHAR(15),
BDCODCLA INTEGER,
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDCODSINTRAB INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOADMCOL INTEGER,
BDNATUOCUPCOL INTEGER,
BDDATAINIAQUICOL DATE,
BDSALINICOL NUMERIC(15,6),
BDDIASPRAZO1COL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDIASPRAZO2COL INTEGER,
BDDATAFIMPRAZO2COL DATE,
BDDESCCONTSINCOL VARCHAR(5),
BDVINCEMPCOL INTEGER,
BDALVARACOL VARCHAR(5),
BDSINDICALIZADOCOL VARCHAR(5),
BDREGIMEPARCIALCOL VARCHAR(5),
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDOBSCOL BLOB,
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODCBO INTEGER,
BDCODCBOTSIN INTEGER,
BDCODQH INTEGER,
BDCODPRES INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAHOM DATE,
BDDATAPAGRESCISAO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDCALCFGTSMESANT VARCHAR(5),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDATAPAGGRFC DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDDISSIDIO VARCHAR(5),
BDDATADISSIDIO DATE,
BDDESCANSOINDENIZADO VARCHAR(5),
BDCODMFGRESC INTEGER,
BDCODSAQUERESC INTEGER,
BDCODMRAISRESC INTEGER,
BDCODMCAGRESC INTEGER,
BDDESCPRES VARCHAR(110),
BDINIPRES INTEGER,
BDJCPRES VARCHAR(5),
BDAVPREPRES INTEGER,
BDGRRFPRES INTEGER,
BDESTPRES VARCHAR(5),
BDINDFER13 VARCHAR(5),
BDTERMCONTRPRES VARCHAR(5),
BDMULTAPRES VARCHAR(5),
BDDIASAVPREPRES INTEGER,
BDDIASPAGPRES INTEGER,
BDCODSEFMFGRESC VARCHAR(5),
BDDESCMFGRESC VARCHAR(255),
BDDESCSAQUERESC VARCHAR(60),
BDDESCMRAISRESC VARCHAR(255),
BDDESCMCAGEDRESC VARCHAR(255),
BDCODEMPDESTTRAN INTEGER,
BDCODPTRAN INTEGER,
BDCODCOLTRANS INTEGER,
BDDATATRANS DATE,
BDCODMCAGENTTRANS INTEGER,
BDCODMCAGSAITRANS INTEGER,
BDCODMFGTRANS INTEGER,
BDCODMRAISTRANS INTEGER,
BDDESCPTRANS VARCHAR(60),
BDCODSEFMFGTRANS VARCHAR(5),
BDDESCMFGTRANS VARCHAR(255),
BDDESCRAISTRANS VARCHAR(255),
BDDESCMCAGEDENTTRANS VARCHAR(255),
BDDESCMCAGEDSAITRANS VARCHAR(255))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_COLCON(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRCODSIN VARCHAR(1000),
PRCODCLA VARCHAR(1000),
PRCODFUC VARCHAR(1000),
PRREF INTEGER,
PRULTDIA DATE,
PRCOLCON SMALLINT,
PRCOLCON_DOC SMALLINT,
PRCOL_DOC SMALLINT,
PRCOL_HIST SMALLINT,
PRCOL_PARENT SMALLINT,
PRCOL_FIS SMALLINT,
PRCON_DOC SMALLINT,
PRCOLCON_VINC SMALLINT,
PRCOL_VINC SMALLINT,
PRCOLCON_BANCO SMALLINT,
PRCOLCON_CALC SMALLINT,
PRCOLCON_FGTSGPS SMALLINT,
PRCOLCON_MVINC SMALLINT,
PRCOL_ADM SMALLINT,
PRCOL_CALC SMALLINT,
PRCOL_HISTF SMALLINT,
PRCON_VINC SMALLINT,
PRCOLCON_DIA SMALLINT,
PRFILTRARESC SMALLINT,
PRFILTRATRANS SMALLINT,
PRFILTRASIT SMALLINT,
PRFILTRAFERIAS SMALLINT,
PRFILTRA13SALARIO SMALLINT,
PRFILTRAFOLHANORMAL SMALLINT,
PRREFFOLHANORMAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODMCAG INTEGER,
BDCODCID INTEGER,
BDCODCSEG INTEGER,
BDREFCSEG INTEGER,
BDCODCIDNASC INTEGER,
BDCODUF INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDLOGRCOL VARCHAR(15),
BDENDCOL DM_BDENDERECO,
BDNUMCOL DM_NUMEND,
BDCOMPLCOL DM_BDCOMPENDERECO,
BDBAICOL DM_BDBAIRRO,
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL DM_BDTELEFONE,
BDCELCOL DM_BDTELEFONE,
BDEMAILCOL DM_BDEMAIL,
BDSEXOCOL INTEGER,
BDDATANASCCOL DATE,
BDDATACADCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCONTRCOL INTEGER,
BDRGCOL VARCHAR(13),
BDORGEMIRGCOL DM_ORGAOEMISSOR,
BDDATAEMIRGCOL DATE,
BDCPFCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDCODUF_COL_DOC INTEGER,
BDTITELEICOL VARCHAR(13),
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDCATCNHCOL VARCHAR(2),
BDCODCID_HIST INTEGER,
BDCODPAIS INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDDATACHEBRASILCOL DATE,
BDCODCIDNASCCONJ INTEGER,
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCONJCOL DATE,
BDCORCOL INTEGER,
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDDEFFISICOCOL INTEGER,
BDTIPOSANGUECOL INTEGER,
BDNROCONSPROCOL VARCHAR(20),
BDSIGLACONSPROCOL VARCHAR(5),
BDCODCCMPROCOL VARCHAR(15),
BDCODCLA INTEGER,
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDCODSINTRAB INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOADMCOL INTEGER,
BDNATUOCUPCOL INTEGER,
BDDATAINIAQUICOL DATE,
BDSALINICOL NUMERIC(15,6),
BDDIASPRAZO1COL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDIASPRAZO2COL INTEGER,
BDDATAFIMPRAZO2COL DATE,
BDDESCCONTSINCOL VARCHAR(5),
BDVINCEMPCOL INTEGER,
BDALVARACOL VARCHAR(5),
BDSINDICALIZADOCOL VARCHAR(5),
BDREGIMEPARCIALCOL VARCHAR(5),
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDOBSCOL BLOB SUB_TYPE 1 SEGMENT SIZE 5000,
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(18,6),
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODQH INTEGER,
BDCODPRES INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAHOM DATE,
BDDATAPAGRESCISAO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDCALCFGTSMESANT VARCHAR(5),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDATAPAGGRFC DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDDISSIDIO VARCHAR(5),
BDDATADISSIDIO DATE,
BDDESCANSOINDENIZADO VARCHAR(5),
BDCODMFGRESC INTEGER,
BDCODSAQUERESC INTEGER,
BDCODMRAISRESC INTEGER,
BDCODMCAGRESC INTEGER,
BDDESCPRES VARCHAR(110),
BDINIPRES INTEGER,
BDJCPRES VARCHAR(5),
BDAVPREPRES INTEGER,
BDGRRFPRES INTEGER,
BDESTPRES VARCHAR(5),
BDINDFER13 VARCHAR(5),
BDTERMCONTRPRES VARCHAR(5),
BDMULTAPRES VARCHAR(5),
BDDIASAVPREPRES INTEGER,
BDDIASPAGPRES INTEGER,
BDCODSEFMFGRESC VARCHAR(5),
BDDESCMFGRESC VARCHAR(255),
BDDESCSAQUERESC VARCHAR(60),
BDDESCMRAISRESC VARCHAR(255),
BDDESCMCAGEDRESC VARCHAR(255),
BDCODEMPDESTTRAN INTEGER,
BDCODPTRAN INTEGER,
BDCODCOLTRANS INTEGER,
BDDATATRANS DATE,
BDCODMCAGENTTRANS INTEGER,
BDCODMCAGSAITRANS INTEGER,
BDCODMFGTRANS INTEGER,
BDCODMRAISTRANS INTEGER,
BDDESCPTRANS VARCHAR(60),
BDCODSEFMFGTRANS VARCHAR(5),
BDDESCMFGTRANS VARCHAR(255),
BDDESCRAISTRANS VARCHAR(255),
BDDESCMCAGEDENTTRANS VARCHAR(255),
BDDESCMCAGEDSAITRANS VARCHAR(255))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_COLCON_DIA(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRDATINI DATE,
PRDATFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATACOL DATE,
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODQH INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_COLCON_EDIT(BDCOL SMALLINT,
BDCON SMALLINT,
BDTER SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(100),
BDTIPO VARCHAR(15))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_COLCON_VERBAS_ASS(PRDIAINI INTEGER,
PRMESINI INTEGER,
PRANOINI INTEGER,
PRDIAFIM INTEGER,
PRMESFIM INTEGER,
PRANOFIM INTEGER)
 RETURNS(BDDIAINI INTEGER,
BDMESINI INTEGER,
BDANOINI INTEGER,
BDDIAFIM INTEGER,
BDMESFIM INTEGER,
BDANOFIM INTEGER,
BDCODVER INTEGER,
BDFORMREF BLOB,
BDFORMVAL BLOB)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_CONS_CBO_SIN RETURNS(BDCODCBO INTEGER,
BDCODCBOTSIN INTEGER,
BDDESCCBO VARCHAR(70))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_CONS_COL(WREFERENCIA INTEGER,
WEMPRESA INTEGER,
WFILTRO VARCHAR(500),
PRULTDIAMES DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDCODCLA INTEGER,
BDDATAADMCOL DATE,
BDGRUPOCLA INTEGER,
BDTIPOCOL INTEGER,
BDDATARESCISAO DATE,
BDDESCCLA VARCHAR(40),
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDSALBASECOL NUMERIC(15,6),
BDCODSIT INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_CONS_COL_NOVO (
    WREFERENCIA integer,
    WEMPRESA integer,
    WFILTRO varchar(500),
    PRULTDIAMES date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDCODCLA integer,
    BDDATAADMCOL date,
    BDGRUPOCLA integer,
    BDTIPOCOL integer,
    BDDATARESCISAO date,
    BDDESCCLA varchar(40),
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDSALBASECOL numeric(15,6),
    BDCODSIT integer,
    BDCODPRES integer,
    BDDESCPRES varchar(110),
    BDCODTFUC integer,
    BDDESCTFUC varchar(40),
    BDSTATUSQC integer,
    BDSTATUS_ES integer,
    BDCODTIPO integer,
    BDINTESOCIAL integer,
    BDDATAEVENTO date,
    BDMATRICULA varchar(30),
    BDDATAENTRADA date,
    BDNOVADATAADMRT date,
    BDNOVADATARESCISAO date,
    BDNOVOCODPRES integer)
as
BEGIN
    SUSPEND;
END
^

CREATE OR ALTER PROCEDURE VRH_SP_CONS_COLCON(WREFERENCIA INTEGER,
WEMPRESA INTEGER,
PRULTDIAMES DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADMCOL DATE,
BDTIPOCOL INTEGER,
BDCODCLA INTEGER,
BDDATARESCISAO DATE,
BDDESCCLA VARCHAR(40),
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDSALBASECOL NUMERIC(15,6),
BDCODSIT INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_CONS_CON (
    WREFERENCIA INTEGER,
    WEMPRESA INTEGER,
    WFILTRO VARCHAR(500))
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDNOMCOL VARCHAR(70),
    BDDATAADMCOL DATE,
    BDCODCLA INTEGER,
    BDGRUPOCLA INTEGER,
    BDDESCCLA VARCHAR(40),
    BDDATARESCISAO DATE,
    BDSALBASECOL NUMERIC(18,6),
    BDCODPRES INTEGER,
    BDDESCPRES VARCHAR(110),
    BDSTATUSQC INTEGER,
    BDSTATUS_ES INTEGER,
    BDCODTIPO INTEGER)
AS
 BEGIN SUSPEND; END
^

create or alter procedure VRH_SP_CONS_FERIAS_PER_AQUIS (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDINIPERGOZOFE date,
    BDFIMPERAQUISFE date,
    BDFIMPERGOZOFE date,
    BDDATAPAGFE date,
    BDQTDGOZOFE numeric(18,6),
    BDQTDABONOFE numeric(18,6),
    BDSALDOINIFE numeric(15,6),
    BDSALDOFIMFE numeric(15,6),
    BDBASEIRFE numeric(15,6),
    BDALIQIRFE numeric(15,6),
    BDVALORIRFE numeric(15,6),
    BDBASEINSSFE numeric(15,6),
    BDALIQINSSFE numeric(15,6),
    BDVALORINSSFE numeric(15,6),
    BDDEPFE numeric(15,6),
    BDSALBASEFE numeric(15,6),
    BDSALBASEHEFE numeric(15,6),
    BDDATABAIXAFE date,
    BDCOLETIVASFE varchar(5),
    BDREFPAGABOFE integer,
    BDFALTASFE numeric(15,6),
    BDNOMEMP DM_BDNOMEMP,
    BDNOMCOL DM_BDNOMCOL,
    BDSALDOFINALSINDFE numeric(18,6),
    BDCALCA13FE varchar(5),
    BDTIPOA13FE integer,
    BDPERCA13FE numeric(18,6),
    BDRECIBOESOCIAL varchar(30),
    BDINIGOZORECIBOFE date,
    BDFIMGOZORECIBOFE date,
    BDQTDGOZORECIBOFE numeric(18,6),
    BDISTRANSFERENCIA boolean)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_CONS_VERBAS(WREFERENCIA INTEGER,
WVERBAS VARCHAR(32700),
WTAMANHOCLASSE INTEGER)
 RETURNS(BDCODVER INTEGER,
BDCLAVER VARCHAR(20),
BDAPEVER VARCHAR(20),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDORDEMVER INTEGER,
BDINATIVAVER VARCHAR(5),
BDSITVER INTEGER,
BDTIPOVER INTEGER,
BDTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDIRVER INTEGER,
BDFGTSVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDMENORESVER VARCHAR(5),
BDPROPVER VARCHAR(5),
BDBASEVTVER VARCHAR(5),
BDREEMBGPSVER VARCHAR(5),
BDHEVER NUMERIC(15,6),
BDGRAVAFICHAHNVER VARCHAR(5),
BDCCPRINCIPALVER VARCHAR(5),
BDFORMREFVER VARCHAR(5000),
BDFORMVALVER VARCHAR(5000),
BDFORMINTVER VARCHAR(5000),
BDBASEDSRHEVER VARCHAR(5),
BDBASEDSRRVVER VARCHAR(5),
BDREFVER INTEGER,
BDFORMREFAUXVER VARCHAR(5000),
BDDEDFORMREFAUXVER VARCHAR(5),
BDDEDFORMREFVER VARCHAR(5),
BDDEDFORMVALVER VARCHAR(5),
BDRENDISENTOIRVER VARCHAR(5),
BDSITMATVER VARCHAR(5),
BDSITDOEVER VARCHAR(5),
BDSITACITRABVER VARCHAR(5),
BDSITMILITARVER VARCHAR(5),
BDSITMATEMPVER VARCHAR(5),
BDSITACITRAB15VER VARCHAR(5),
BDSITDOETRABVER VARCHAR(5),
BDSITLICVENCVER VARCHAR(5),
BDSITDOE15VER VARCHAR(5),
BDSITSINDICALVER VARCHAR(5),
BDSITAPOINVVER VARCHAR(5),
BDSITOUTRASVER VARCHAR(5),
BDPAGAESTOUROVER DM_BOOLEAN,
BDGARANTIAMINVER DM_BOOLEAN,
BDINDRESC DM_BOOLEAN,
BDNAOCONVHORASVER DM_BOOLEAN,
BDBASEDSRHNVER DM_BOOLEAN,
BDBASEDSROUVER DM_BOOLEAN)
 AS
 BEGIN SUSPEND; END
^

--Sol. 15188 - 22/09/2016 - Alterada a procedure VRH_SP_CONSULTA_SITUACAO para retornar todos os campos da tabela VRH_EMP_TSITCOL corretamente - Bruno L. R.
create or alter procedure VRH_SP_CONSULTA_SITUACAO (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCODSIT integer,
    BDDESCSIT varchar(70),
    BDDATAINISEFIP date,
    BDDATAINISIT date,
    BDDATAFIMSIT date,
    BDDIASSIT integer,
    BDNBENEFICIOSIT varchar(20),
    BDDATAPERICIASIT date,
    BDDATAPARTOSIT date,
    BDDATAESTAB date,
    BDCODDOE integer,
    BDDESCDOE varchar(300),
    BDTIPOACID varchar(50),
    BDCODMED integer,
    BDNOMMED varchar(60),
    BDCODSINTRAB integer,
    BDDESCSINTRAB varchar(60),
    BDOBSERVACAO varchar(255),
    BDGRUPOSIT integer,
    BDCODEVTINICIO integer,
    BDCODEVTFIM integer,
    BDRECIBOESOCIALINICIO char(30),
    BDRECIBOESOCIALFIM char(30),
    BDCOVID19 DM_BOOLEAN,
    BDBENEFDEFERIDO DM_BOOLEAN,
    BDCODSITAUX integer,
    BDDESCSITAUX varchar(70),
    BDGRUPOSITAUX integer,
    BDDATAINIATESTADOAUX date,
    BDDATAFIMATESTADOAUX date,
    BDDATAINIAFASTAUX date,
    BDDATAFIMAFASTAUX date,
    BDDIASDOCUMENTO integer,
    BDDIASATESTADOAUX integer,
    BDDIASAFASTAUX integer,
    BDAFASDECORRENTE boolean
    )
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_DADOS_FALTAS(PRCODEMP VARCHAR(1000),
PRCODCOL VARCHAR(32700),
PRDATINI DATE,
PRDATFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFAL INTEGER,
BDDATAFAL DATE,
BDTIPOFAL INTEGER,
BDHORASFAL NUMERIC(15,6),
BDCODVERFAL INTEGER,
BDCODVERDSRFAL INTEGER,
BDTIPOVERFAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_DADOS_FERIAS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATINI DATE,
PRDATFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDINIPERAQUISFE DATE,
BDCODFE INTEGER,
BDINIPERGOZOFE DATE,
BDFIMPERAQUISFE DATE,
BDFIMPERGOZOFE DATE,
BDDATAPAGFE DATE,
BDQTDGOZOFE INTEGER,
BDQTDABONOFE INTEGER,
BDSALDOINIFE NUMERIC(15,6),
BDSALDOFIMFE NUMERIC(15,6),
BDBASEIRFE NUMERIC(15,6),
BDALIQIRFE NUMERIC(15,6),
BDVALORIRFE NUMERIC(15,6),
BDBASEINSSFE NUMERIC(15,6),
BDALIQINSSFE NUMERIC(15,6),
BDVALORINSSFE NUMERIC(15,6),
BDDEPFE NUMERIC(15,6),
BDSALBASEFE NUMERIC(15,6),
BDSALBASEHEFE NUMERIC(15,6),
BDDATABAIXAFE DATE,
BDCOLETIVASFE VARCHAR(5),
BDREFPAGABOFE INTEGER,
BDFALTASFE NUMERIC(15,6),
BDSALDOFINALSINDFE NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_DADOS_FERIAS_RESCISAO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATARESC DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDINIPERAQUISFE DATE,
BDCODFE INTEGER,
BDINIPERGOZOFE DATE,
BDFIMPERAQUISFE DATE,
BDFIMPERGOZOFE DATE,
BDDATAPAGFE DATE,  
BDQTDGOZOFE NUMERIC(18,6),
BDQTDABONOFE NUMERIC(18,6),
BDREFPAGABOFE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER procedure VRH_SP_DADOS_SITUACAO(
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRDATINI date,
    PRDATFIM date,
    PRRETONARSITEMPORIG varchar(5) = 'FALSE',
    PRPREVRESC varchar(5) = 'FALSE')
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODSIT integer,
    BDDATAINISEFIP date,
    BDDATAINISIT date,
    BDDATAFIMSIT date,
    BDDIASSIT integer,
    BDNBENEFICIOSIT varchar(20),
    BDDATAPERICIASIT date,
    BDDATAPARTOSIT date,
    BDDESCSIT varchar(70),
    BDGRUPOSIT integer,
    BDCODVER integer,
    BDCODMFGENT integer,
    BDCODMFGSAI integer,
    BDCARENSIT integer,
    BDCODVER15DIAS integer,
    BDTIPOPERDESIT integer,
    BDSALFAMSIT varchar(5),
    BDCODSEFENT varchar(5),
    BDCODSEFSAI varchar(5),
    BDRELSIT integer,
    BDINSSINTSIT DM_BOOLEAN,
    BDDIASATESTADO integer,
    BDNAOPRORROGAFERIAS varchar(5),
    BDCOVID19 DM_BOOLEAN,
    BDSUSPENSAO DM_BOOLEAN,
    BDNAOALTPERAQUIMP936 DM_BOOLEAN,
    BDBENEFDEFERIDO DM_BOOLEAN,
    BDDATAINIATESTADOAUX date,
    BDDATAFIMATESTADOAUX date,
    BDDATAINIAFASTAUX date,
    BDDATAFIMAFASTAUX date,
    BDDIASATESTADOAUX integer,   /*158332 - André Cursino - Relatório de afastamentos*/
    BDCODSITAUX integer,         /*158332 - André Cursino*/
    BDSUBGRUPOSIT integer)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRH_SP_DADOS_SITUACAO_RESCISAO (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRDATARESC date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODSIT integer,
    BDDATAINISEFIP date,
    BDDATAINISIT date,
    BDDATAFIMSIT date,
    BDDIASSIT integer,
    BDNBENEFICIOSIT varchar(20),
    BDDATAPERICIASIT date,
    BDDATAPARTOSIT date,
    BDDESCSIT varchar(70),
    BDGRUPOSIT integer,
    BDCODVER integer,
    BDCARENSIT integer,
    BDTIPOPERDESIT integer,
    BDDIASATESTADO integer,
    BDNAOPRORROGAFERIAS varchar(5),
    BDSUSPMP DM_BOOLEAN,
    BDNAOALTPERAQUIMP936 DM_BOOLEAN,
BDBENEFDEFERIDO DM_BOOLEAN,
BDDATAINIATESTADOAUX date,
BDDATAFIMATESTADOAUX date,
BDDATAINIAFASTAUX date,
    BDDATAFIMAFASTAUX date,
    BDDIASPERDEPERAQUI integer,
    BDSUBGRUPOSIT integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure VRH_SP_DADOS_SITUACAO2 (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRREFERENCIA integer,
    PRPREVIARESCISAO integer = 0,
    PRRETONARSITEMPORIG varchar(5) = 'FALSE' /* COLLATE WIN1252 - default */ )
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODSIT integer,
    BDDATAINISEFIP date,
    BDDATAINISIT date,
    BDDATAFIMSIT date,
    BDDIASSIT integer,
    BDNBENEFICIOSIT varchar(20),
    BDDATAPERICIASIT date,
    BDDATAPARTOSIT date,
    BDDESCSIT varchar(70),
    BDGRUPOSIT integer,
    BDCODVER integer,
    BDCODMFGENT integer,
    BDCODMFGSAI integer,
    BDCARENSIT integer,
    BDCODVER15DIAS integer,
    BDTIPOPERDESIT integer,
    BDINSSINTSIT DM_BOOLEAN,
    BDDIASATESTADO integer,
    BDNAOPRORROGAFERIAS varchar(5),
    BDSUSPENSAO DM_BOOLEAN,
    BDNAOALTPERAQUIMP936 DM_BOOLEAN,
    BDBENEFDEFERIDO DM_BOOLEAN,
    BDDATAINIATESTADOAUX date,
    BDDATAFIMATESTADOAUX date,
    BDDATAINIAFASTAUX date,
    BDDATAFIMAFASTAUX date,
    BDDIASPERDEPERAQUI integer,
    BDSUBGRUPOSIT integer)
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_DEMITIDOS_NO_MES(PRCODEMP VARCHAR(15000),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDDEMITIDOS INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRH_SP_EMPRESAS (
    PREMP varchar(10000),
    PRREF integer,
    PRPROVISAO smallint = 0)
returns (
    BDCODMATRIZ integer,
    BDCODEMP integer,
    BDCODCID integer,
    BDCODUF integer,
    BDCODPLAFUC integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCENTROS integer,
    BDPAGEMP integer,
    BDFECHAMESEMP integer,
    BDFECHAVTEMP integer,
    BDARREMP integer,
    BDTIPOARREMP integer,
    BDTIPOFEREMP integer,
    BDSOMSALFEREMP varchar(5),
    BDTIPOAD13EMP integer,
    BDSOMSALAD13EMP varchar(5),
    BDPERCADSALEMP numeric(15,6),
    BDREFHOREMP varchar(5),
    BDLICREMFEREMP varchar(5),
    BDESTOUROEMP varchar(5),
    BDESTOURORESEMP varchar(5),
    BDFALFEREMP varchar(5),
    BDFALHORFEREMP varchar(5),
    BDDEPIRRESCEMP varchar(5),
    BDCODGPS integer,
    BDCODTERC integer,
    BDCODFPAS integer,
    BDCNAERATEMP numeric(15,6),
    BDEMPEMP numeric(15,6),
    BDAUTEMP numeric(15,6),
    BDFUNEMP numeric(15,6),
    BDCODSINPAT integer,
    BDCAPSOCEMP numeric(15,6),
    BDETIQEMP varchar(5),
    BDTAXSEREMP numeric(15,6),
    BDREFCAGEDEMP integer,
    BDPROPADMEMP integer,
    BDPROPRESEMP integer,
    BDPROPFEREMP integer,
    BDPROPSITEMP integer,
    BDCALCMEDIASTEMP integer,
    BDNATESTEMP integer,
    BDDATABASEEMP integer,
    BDPATEMP varchar(5),
    BDNROPROPEMP integer,
    BDSERPROPRIOPATEMP integer,
    BDPATREFCONVENIOEMP integer,
    BDPATCESTAALIMENTOEMP integer,
    BDPATADMCOZINHAEMP integer,
    BDPATREFTRANSPEMP integer,
    BDPATALICONVENIOEMP integer,
    BDSINDICALIZEMP varchar(5),
    BDCODBAN integer,
    BDCODAG integer,
    BDIDENTEMP varchar(14),
    BDCATSEFIPEMP integer,
    BDISENFILEMP numeric(15,6),
    BDCETRTALIZAEMP integer,
    BDCODIR integer,
    BDCODINSS integer,
    BDCODMEN integer,
    BDCALCFCNAFNEMP varchar(5),
    BDCALCC13NAFNEMP varchar(5),
    BDTIPOCONTAB integer,
    BDTIPOEMIGUIAS integer,
    BDFAP numeric(15,6),
    BDTAXACNAEEMP numeric(15,6),
    BDPERTERC numeric(15,6),
    BDPERCPIS numeric(15,6),
    BDLIMINARAVPREVEMP integer,
    BDSIMPLESGPS integer,
    BDMESDSREMP integer,
    BDCODPLACONVSAU integer,
    BDARREDONDAFN DM_BOOLEAN,
    BDARREDONDAFC DM_BOOLEAN,
    BDARREDONDAFE DM_BOOLEAN,
    BDARREDONDAA13 DM_BOOLEAN,
    BDARREDONDA13 DM_BOOLEAN,
    BDARREDONDAC13 DM_BOOLEAN,
    BDARREDONDAAD DM_BOOLEAN,
    BDARREDONDAAU DM_BOOLEAN,
    BDARREDONDAFA DM_BOOLEAN,
    BDPAGEMPCONTR integer,
    BDDESCFALHORASDIAS DM_BOOLEAN,
    BDPERCLIMIDESCPAR numeric(15,6),
    BDCALCC13FNNEGEMP DM_BOOLEAN,
    BDDSRMEDATUSAL DM_BOOLEAN,
    BDDATAINITABELA date,
    BDDATAININAOPERIOD date,
    BDDATAINIPERIOD date,
    BDDATAINISST date,
    BDREFINITABELA integer,
    BDREFININAOPERIOD integer,
    BDREFINIPERIOD integer,
    BDREFINISST integer,
    BDOPCAOESOCIAL integer,
    BDGRUPO integer,
    BDREFINIDCTFWEB integer,
    BDDATAINIRT date,
    BDDATAFGTSDIGITAL date,
    BDCODCLATRI integer,
    BDCONSIDERAFERICIDADETOM boolean)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_FERIAS_PER_AQUIS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDINIPERAQUISFE DATE,
BDCODFE INTEGER,
BDINIPERGOZOFE DATE,
BDFIMPERAQUISFE DATE,
BDFIMPERGOZOFE DATE,
BDDATAPAGFE DATE,
BDQTDGOZOFE NUMERIC(18,6),
BDQTDABONOFE NUMERIC(18,6),
BDSALDOINIFE NUMERIC(15,6),
BDSALDOFIMFE NUMERIC(15,6),
BDBASEIRFE NUMERIC(15,6),
BDALIQIRFE NUMERIC(15,6),
BDVALORIRFE NUMERIC(15,6),
BDBASEINSSFE NUMERIC(15,6),
BDALIQINSSFE NUMERIC(15,6),
BDVALORINSSFE NUMERIC(15,6),
BDDEPFE NUMERIC(15,6),
BDSALBASEFE NUMERIC(15,6),
BDSALBASEHEFE NUMERIC(15,6),
BDDATABAIXAFE DATE,
BDCOLETIVASFE VARCHAR(5),
BDREFPAGABOFE INTEGER,
BDFALTASFE NUMERIC(15,6),
BDFERIADOSFE INTEGER,
BDSALDOFINALSINDFE NUMERIC(18,6),
BDVALSALMINVIGENTE NUMERIC(18,6),   --Sol. 17580 - Bruno L. R. - 17/07/2017 
BDMIGRACAO DM_BOOLEAN,
BDPAGO DM_BOOLEAN,
BDQTDGOZORECIBOFE NUMERIC(18,6),
BDISTRANSFERENCIA BOOLEAN)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_FERIAS_PER_AQUIS_RESC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER,
PRPROVISAO INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDINIPERAQUISFE DATE,
BDCODFE INTEGER,
BDINIPERGOZOFE DATE,
BDFIMPERAQUISFE DATE,
BDFIMPERGOZOFE DATE,
BDDATAPAGFE DATE,
BDQTDGOZOFE NUMERIC(18,6),
BDQTDABONOFE NUMERIC(18,6),
BDSALDOINIFE NUMERIC(15,6),
BDSALDOFIMFE NUMERIC(15,6),
BDBASEIRFE NUMERIC(15,6),
BDALIQIRFE NUMERIC(15,6),
BDVALORIRFE NUMERIC(15,6),
BDBASEINSSFE NUMERIC(15,6),
BDALIQINSSFE NUMERIC(15,6),
BDVALORINSSFE NUMERIC(15,6),
BDDEPFE NUMERIC(15,6),
BDSALBASEFE NUMERIC(15,6),
BDSALBASEHEFE NUMERIC(15,6),
BDDATABAIXAFE DATE,
BDCOLETIVASFE VARCHAR(5),
BDREFPAGABOFE INTEGER,
BDFALTASFE NUMERIC(15,6),
BDFERIADOSFE INTEGER,
BDSALDOFINALSINDFE NUMERIC(18,6),
BDVALSALMINVIGENTE NUMERIC(18,6),
BDMIGRACAO DM_BOOLEAN,
BDPAGO DM_BOOLEAN,
BDFERIASMES NUMERIC(15,6),
BDQTDGOZORECIBOFE NUMERIC(18,6),
BDISTRANSFERENCIA BOOLEAN)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRH_SP_GRRF (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32700),
    PRANOMES integer,
    PRDATAPAGTO date,
    PRPRIDIA date,
    PRULTDIA date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODPRES integer,
    BDREFRESCISAO integer,
    BDDATARESCISAO date,
    BDDATAAVPREVIO date,
    BDREPOSICAOVAGA varchar(5),
    BDSALDOFGTS numeric(15,6),
    BDDATAHOM date,
    BDDATAPAGGRFC date,
    BDDATADISSIDIO date,
    BDAVPREPRES integer,
    BDCODSEFMFG varchar(5),
    BDCODSAQUE integer,
    BDBFGTS numeric(15,6),
    BDBFGTSMESANT numeric(15,6),
    BDVALINDEN numeric(15,6),
    BDCNPJEMP varchar(18),
BDNOMEMP DM_BDNOMEMP,
    BDLOGREMP varchar(15),
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP varchar(9),
    BDDDDEMP integer,
BDFONEEMP DM_BDTELEFONE,
    BDCODCNAE integer,
    BDCODCONT integer,
    BDSIMPLESGPS integer,
    BDCODFPAS integer,
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
BDNOMCOL DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDSEXOCOL integer,
    BDGRAUINSTCOL integer,
    BDDATANASCCOL date,
    BDCONTRCOL integer,
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDCATEGORIACOL integer,
    BDOCORRENCIACOL integer,
    BDDATAOPCAOFGTSCOL date,
    BDHORASSEMANAISCOL numeric(15,6),
    BDCODCBO varchar(4),
    BDTAMCNPJ integer,
    BDNOMREDUZEMP DM_BDNOMREDUZEMP,
    BDFGTSSEMIND numeric(15,6),
    BDSITEMP DM_BOOLEAN,
    BDBLOQUEIOGRRF DM_BOOLEAN)
as
 BEGIN SUSPEND; END
^

create or alter procedure VRH_SP_GRRF (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32700),
    PRANOMES integer,
    PRDATAPAGTO date,
    PRPRIDIA date,
    PRULTDIA date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODPRES integer,
    BDREFRESCISAO integer,
    BDDATARESCISAO date,
    BDDATAAVPREVIO date,
    BDREPOSICAOVAGA varchar(5),
    BDSALDOFGTS numeric(15,6),
    BDDATAHOM date,
    BDDATAPAGGRFC date,
    BDDATADISSIDIO date,
    BDAVPREPRES integer,
    BDCODSEFMFG varchar(5),
    BDCODSAQUE integer,
    BDBFGTS numeric(15,6),
    BDBFGTSMESANT numeric(15,6),
    BDVALINDEN numeric(15,6),
    BDCNPJEMP varchar(18),
BDNOMEMP DM_BDNOMEMP,
    BDLOGREMP varchar(15),
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP varchar(9),
    BDDDDEMP integer,
BDFONEEMP DM_BDTELEFONE,
    BDCODCNAE integer,
    BDCODCONT integer,
    BDSIMPLESGPS integer,
    BDCODFPAS integer,
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
BDNOMCOL DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDSEXOCOL integer,
    BDGRAUINSTCOL integer,
    BDDATANASCCOL date,
    BDCONTRCOL integer,
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDCATEGORIACOL integer,
    BDOCORRENCIACOL integer,
    BDDATAOPCAOFGTSCOL date,
    BDHORASSEMANAISCOL numeric(15,6),
    BDCODCBO varchar(4),
    BDTAMCNPJ integer,
BDNOMREDUZEMP DM_BDNOMREDUZEMP,
    BDFGTSSEMIND numeric(15,6),
    BDSITEMP DM_BOOLEAN,
    BDBLOQUEIOGRRF DM_BOOLEAN)
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_LISTAADM_RESC(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRANOMESINI INTEGER,
PRANOMESFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRFILTRAADM INTEGER,
PRFILTRARESC INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDATAADM DATE,
BDDATARESCISAO DATE,
BDDATATRF DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_LISTAADM_RESC_TOT_EMP(PRCODEMP VARCHAR(10000),
PRANOMESANT INTEGER,
PRANOMESATU INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRFILTRAADM INTEGER,
PRFILTRARESC INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCAMPOC INTEGER,
BDCAMPOD INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_REL_RECIBO_13SAL (PRCODEMP INTEGER,
    PRREF INTEGER,
    PRCODCLA VARCHAR(10000),
    PRCODTPCC VARCHAR(10000) = NULL)
RETURNS (BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODVER INTEGER,
    BDREFFN INTEGER,
    BDREFV13 NUMERIC(15,6),
    BDREFAUXV13 NUMERIC(15,6),
    BDVALV13 NUMERIC(15,6),
    BDDATAFN INTEGER,
    BDSALBASE NUMERIC(15,6),
    BDBINSS NUMERIC(15,6),
    BDBFGTS NUMERIC(15,6),
    BDFGTS NUMERIC(15,6),
    BDBIRRF NUMERIC(15,6),
    BDCNPJEMP VARCHAR(18),
    BDDESCVER VARCHAR(40),
    BDDESCREDVER VARCHAR(20),
    BDORDEMVER INTEGER,
    BDNOMCOL VARCHAR(70),
    BDDATAADMCOL DATE,
    BDPISCOL VARCHAR(14),
    BDCPFCOL VARCHAR(14),
    BDRG VARCHAR(13),
    BDTIPOCODVER INTEGER,
    BDORDEMTIPOCODVER INTEGER,
    BDTIPOREFVER INTEGER,
    BDCODBAN INTEGER,
    BDCODAG INTEGER,
    BDCTADEPCOL VARCHAR(15),
    BDDIGCTADEPCOL VARCHAR(2),
    BDMODOPAGTOCOL INTEGER,
    BDCLAVER VARCHAR(20),
    BDEMAILCOL VARCHAR(400),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL VARCHAR(1),
    BDQTDSALARIOHE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_REL_RECIBO_AD13 (PRCODEMP INTEGER,
    PRREF INTEGER,
    PRCODCLA VARCHAR(10000),
    PRCODTPCC VARCHAR(10000) = NULL,
    PR13FERIAS SMALLINT = 0)
RETURNS (BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODVER INTEGER,
    BDREFFN INTEGER,
    BDREFVA13 NUMERIC(18,6),
    BDREFAUXVA13 NUMERIC(18,6),
    BDVALVA13 NUMERIC(18,6),
    BDDATAFN INTEGER,
    BDSALBASE NUMERIC(18,6),
    BDBINSS NUMERIC(18,4),
    BDBFGTS NUMERIC(18,6),
    BDFGTS NUMERIC(18,6),
    BDBIRRF NUMERIC(18,6),
    BDCALCFERA13 VARCHAR(5),
    BDCNPJEMP VARCHAR(18),
    BDDESCVER VARCHAR(40),
    BDDESCREDVER VARCHAR(20),
    BDORDEMVER INTEGER,
    BDNOMCOL VARCHAR(70),
    BDDATAADMCOL DATE,
    BDPISCOL VARCHAR(14),
    BDCPFCOL VARCHAR(14),
    BDRG VARCHAR(13),
    BDTIPOCODVER INTEGER,
    BDORDEMTIPOCODVER INTEGER,
    BDTIPOREFVER INTEGER,
    BDCODBAN INTEGER,
    BDCODAG INTEGER,
    BDCTADEPCOL VARCHAR(15),
    BDDIGCTADEPCOL VARCHAR(2),
    BDMODOPAGTOCOL INTEGER,
    BDCLAVER VARCHAR(20),
    BDEMAILCOL VARCHAR(400),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL VARCHAR(1),
    BDQTDSALARIOHE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_REL_RECIBO_ADIANTAMENTO (PRCODEMP INTEGER,
    PRDATAINI VARCHAR(10),
    PRDATAFIM VARCHAR(10),
    PRCODCLA VARCHAR(10000),
    PRCODTPCC VARCHAR(10000) = NULL)
RETURNS (BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODVER INTEGER,
    BDREFFN INTEGER,
    BDDATA DATE,
    BDREFVAD NUMERIC(15,6),
    BDREFAUXVAD NUMERIC(15,6),
    BDVALVAD NUMERIC(15,6),
    BDDATAFN DATE,
    BDBINSS NUMERIC(15,2),
    BDBFGTS NUMERIC(15,2),
    BDFGTS NUMERIC(15,2),
    BDBIRRF NUMERIC(15,6),
    BDCNPJEMP VARCHAR(18),
    BDDESCVER VARCHAR(40),
    BDDESCREDVER VARCHAR(20),
    BDORDEMVER INTEGER,
    BDNOMCOL VARCHAR(70),
    BDDATAADMCOL DATE,
    BDPISCOL VARCHAR(14),
    BDCPFCOL VARCHAR(14),
    BDRG VARCHAR(13),
    BDTIPOCODVER INTEGER,
    BDORDEMTIPOCODVER INTEGER,
    BDTIPOREFVER INTEGER,
    BDCODBAN INTEGER,
    BDCODAG INTEGER,
    BDCTADEPCOL VARCHAR(15),
    BDDIGCTADEPCOL VARCHAR(2),
    BDMODOPAGTOCOL INTEGER,
    BDSALBASE NUMERIC(15,6),
    BDCLAVER VARCHAR(20),
    BDEMAILCOL VARCHAR(400),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL VARCHAR(1),
    BDQTDSALARIOHE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_REL_RECIBO_C13SAL (PRCODEMP INTEGER,
    PRREF INTEGER,
    PRCODCLA VARCHAR(10000),
    PRCODTPCC VARCHAR(10000) = NULL)
RETURNS (BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODVER INTEGER,
    BDREFFN INTEGER,
    BDREFVC13 NUMERIC(18,6),
    BDREFAUXVC13 NUMERIC(18,6),
    BDVALVC13 NUMERIC(18,6),
    BDDATAFN INTEGER,
    BDSALBASE NUMERIC(18,6),
    BDBINSS NUMERIC(18,6),
    BDBFGTS NUMERIC(18,6),
    BDFGTS NUMERIC(18,6),
    BDBIRRF NUMERIC(18,6),
    BDCNPJEMP VARCHAR(18),
    BDDESCVER VARCHAR(40),
    BDDESCREDVER VARCHAR(20),
    BDORDEMVER INTEGER,
    BDNOMCOL VARCHAR(70),
    BDDATAADMCOL DATE,
    BDPISCOL VARCHAR(14),
    BDCPFCOL VARCHAR(14),
    BDRG VARCHAR(13),
    BDTIPOCODVER INTEGER,
    BDORDEMTIPOCODVER INTEGER,
    BDTIPOREFVER INTEGER,
    BDCODBAN INTEGER,
    BDCODAG INTEGER,
    BDCTADEPCOL VARCHAR(15),
    BDDIGCTADEPCOL VARCHAR(2),
    BDMODOPAGTOCOL INTEGER,
    BDCLAVER VARCHAR(20),
    BDEMAILCOL VARCHAR(400),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL VARCHAR(1),
    BDQTDSALARIOHE INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRH_SP_REL_RECIBO_FOLCOMP (
    PRCODEMP integer,
    PRREF integer,
    PRREFPAG integer,
    PRCODCLA varchar(10000),
    PRCODTPCC varchar(20000) = null /* COLLATE WIN1252 - default */ ,
    PRSITCOL smallint = 1,
    PRVINCFN integer = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFFC integer,
    BDREFVFN_SUM numeric(18,6),
    BDREFVFN_MAX numeric(18,6),
    BDREFAUXVFN_SUM numeric(18,6),
    BDREFAUXVFN_MAX numeric(18,6),
    BDVALVFN numeric(18,6),
    BDDATAFN integer,
    BDSALBASE numeric(18,6),
    BDBINSS numeric(18,6),
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBIRRF numeric(18,6),
    BDCNPJEMP varchar(18),
    BDDESCVER varchar(40),
    BDDESCREDVER varchar(20),
    BDORDEMVER integer,
    BDNOMCOL varchar(70),
    BDDATAADMCOL date,
    BDPISCOL varchar(14),
    BDCPFCOL varchar(14),
    BDRG varchar(13),
    BDTIPOCODVER integer,
    BDORDEMTIPOCODVER integer,
    BDTIPOREFVER integer,
    BDCODBAN integer,
    BDCODAG integer,
    BDCTADEPCOL varchar(15),
    BDDIGCTADEPCOL varchar(2),
    BDMODOPAGTOCOL integer,
    BDCLAVER varchar(20),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDEMAILCOL varchar(400),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDQTDSALARIOHE integer,
    BDVERCALCRRA integer,
    BDBASETOTAL DM_BOOLEAN,
    BDORDEM integer)
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_REL_RECIBO_FOLHA_AVULSA (PRCODEMP INTEGER,
    PRCODTCA VARCHAR(20000),
    PRDATAINI VARCHAR(10),
    PRDATAFIM VARCHAR(10),
    PRCODCLA VARCHAR(10000),
    PRCODTPCC VARCHAR(10000) = NULL) -- alt:15921 - 19/10/2016 - novo campo filtro por centro de custo - Marcelo B. M.
RETURNS (BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODTCA INTEGER,
    BDCODVER INTEGER,
    BDREFFN INTEGER,
    BDDATA DATE,
    BDREFVAD NUMERIC(15,6),
    BDREFAUXVAD NUMERIC(15,6),
    BDVALVAD NUMERIC(15,6),
    BDDATAFN DATE,
    BDBINSS NUMERIC(15,2),
    BDBFGTS NUMERIC(15,2),
    BDFGTS NUMERIC(15,2),
    BDBIRRF NUMERIC(15,6),
    BDCNPJEMP VARCHAR(18),
    BDDESCVER VARCHAR(40),
    BDDESCREDVER VARCHAR(20),
    BDORDEMVER INTEGER,
    BDNOMCOL VARCHAR(70),
    BDDATAADMCOL DATE,
    BDPISCOL VARCHAR(14),
    BDCPFCOL VARCHAR(14),
    BDRG VARCHAR(13),
    BDTIPOCODVER INTEGER,
    BDORDEMTIPOCODVER INTEGER,
    BDTIPOREFVER INTEGER,
    BDCODBAN INTEGER,
    BDCODAG INTEGER,
    BDCTADEPCOL VARCHAR(15),
    BDDIGCTADEPCOL VARCHAR(2),
    BDMODOPAGTOCOL INTEGER,
    BDSALBASE NUMERIC(15,6),
    BDDESCTCA VARCHAR(50),
    BDCLAVER VARCHAR(20),
    BDEMAILCOL VARCHAR(400),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL VARCHAR(1),
    BDQTDSALARIOHE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_RELATORIO_CAT_AGCAUSA(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRCHAVE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCHAVE INTEGER,
BDOBJETOCAUSADORACID VARCHAR(300))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_RELATORIO_CAT_PCORPO(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRCHAVE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCHAVE INTEGER,
BDPARTESATINGIDAS VARCHAR(400))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER procedure VRH_SP_RELATORIO_CAT2 (
    PRCODEMP varchar(32000),
    PRCODCOL varchar(32000),
    PRCHAVE integer,
    PRULTIMODIA date,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCHAVE integer,
    BDCODCID integer,
    BDDATAACIDENTE date,
    BDDATAEMISSAO date,
    BDDATAULTIMODIA date,
    BDDATAOBITO date,
    BDEMITENTE integer,
    BDNRCAT varchar(25),
    BDCATORIGEM varchar(25),
    BDTIPOAFAST integer,
    BDREGPOLICIAL varchar(5),
    BDAFASTAMENTO varchar(5),
    BDHORAACIDENTE time,
    BDTIPOCAT integer,
    BDLOCALACIDENTE integer,
    BDESPLOCALACIDENTE varchar(255),
    BDOBJETOCAUSADORACID varchar(10000),
    BDDESCACIDENTE blob sub_type 1 segment size 210,
    BDPARTESATINGIDAS varchar(10000),
    BDAREAACIDENTE integer,
    BDHOUVEOBITO varchar(5),
    BDREMUNMENSAL integer,
    BDNOMEMP DM_BDNOMEMP,
    BDBAIEMP DM_BDBAIRRO,
    BDCODCNAE integer,
    BDNUMEMP DM_NUMEND,
    BDENDEMP DM_BDENDERECO,
    BDLOGREMP varchar(15),
    BDCEPEMP varchar(9),
    BDDDDEMP integer,
    BDFONEEMP DM_BDTELEFONE,
    BDCNPJEMP varchar(18),
    BDNOMCOL DM_BDNOMCOL,
    BDNOMMAECOL varchar(70),
    BDDATANASCCOL date,
    BDCPFCOL varchar(14),
    BDSEXOCOL integer,
    BDESTCIVCOL integer,
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDDATAEMICTPSCOL date,
    BDRGCOL varchar(13),
    BDDATAEMIRGCOL date,
    BDORGEMIRGCOL varchar(30),
    BDPISCOL varchar(14),
    BDLOGRCOL varchar(15),
    BDENDCOL DM_BDENDERECO,
    BDNUMCOL DM_NUMEND,
    BDBAICOL DM_BDBAIRRO,
    BDCEPCOL varchar(9),
    BDDDDCOL integer,
    BDFONECOL DM_BDTELEFONE,
    BDFILIACAOPREV integer,
    BDAPOSENTADO integer,
    BDNOMCIDACID varchar(40),
    BDUFACID varchar(2),
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
    BDNOMECIDCOL varchar(40),
    BDUFCOL varchar(2),
    BDUFCTPS varchar(2),
    BDDESCCBO varchar(150),
    BDCODCBO integer,
    BDSALBASECOL numeric(15,6),
    BDUFRG varchar(2),
    BDDDDCELCOL integer,
    BDCELCOL DM_BDTELEFONE,
    BDTIPOCOL integer,
    BDHORASMENSAISCOL numeric(15,6),
    BDDTAPOSENT date,
    BDDATARETORNO date,
    BDLATERALIDADE integer,
    BDINICIATIVA integer,
    BDEXCLUIDO DM_BOOLEAN,
    BDRECIBOESOC varchar(30),
    BDRECIBORETEXC varchar(30),
    BDSITUACAOGERADORA varchar(210))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_SERV_TERC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRSERV VARCHAR(1000),
PRCODCLA VARCHAR(1000),
PRREF INTEGER,
PRINICIO DATE,
PRFIM DATE,
PRCOLCON SMALLINT,
PRCOLCON_DOC SMALLINT,
PRCOLCON_VINC SMALLINT,
PRCOLCON_BANCO SMALLINT,
PRCOLCON_CALC SMALLINT,
PRCOLCON_FGTSGPS SMALLINT,
PRCOLCON_MVINC SMALLINT,
PRCOLCON_DIA SMALLINT)
 RETURNS(BDCODSERV INTEGER,
BDDATASERV DATE,
BDDATAPAGSERV DATE,
BDHORASERV TIME,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODMCAG INTEGER,
BDCODCID INTEGER,
BDCODCSEG INTEGER,
BDREFCSEG INTEGER,
BDCODCIDNASC INTEGER,
BDCODUF INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDLOGRCOL VARCHAR(15),
BDENDCOL DM_BDENDERECO,
BDNUMCOL DM_NUMEND,
BDCOMPLCOL DM_BDCOMPENDERECO,
BDBAICOL DM_BDBAIRRO,
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL DM_BDTELEFONE,
BDCELCOL DM_BDTELEFONE,
BDEMAILCOL DM_BDEMAIL,
BDSEXOCOL INTEGER,
BDDATANASCCOL DATE,
BDDATACADCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDRGCOL VARCHAR(13),
BDORGEMIRGCOL DM_ORGAOEMISSOR,
BDDATAEMIRGCOL DATE,
BDCPFCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDCODUF_COL_DOC INTEGER,
BDTITELEICOL VARCHAR(13),
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDCATCNHCOL VARCHAR(2),
BDCODCID_HIST INTEGER,
BDCODPAIS INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDDATACHEBRASILCOL DATE,
BDCODCIDNASCCONJ INTEGER,
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCONJCOL DATE,
BDCORCOL INTEGER,
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDDEFFISICOCOL INTEGER,
BDTIPOSANGUECOL INTEGER,
BDNROCONSPROCOL VARCHAR(20),
BDSIGLACONSPROCOL VARCHAR(5),
BDCODCCMPROCOL VARCHAR(15),
BDCODCLA INTEGER,
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDCODSINTRAB INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOADMCOL INTEGER,
BDNATUOCUPCOL INTEGER,
BDDATAINIAQUICOL DATE,
BDSALINICOL NUMERIC(15,6),
BDDIASPRAZO1COL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDIASPRAZO2COL INTEGER,
BDDATAFIMPRAZO2COL DATE,
BDDESCCONTSINCOL VARCHAR(5),
BDVINCEMPCOL INTEGER,
BDALVARACOL VARCHAR(5),
BDSINDICALIZADOCOL VARCHAR(5),
BDREGIMEPARCIALCOL VARCHAR(5),
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDOBSCOL BLOB,
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDCODCBO INTEGER,
BDCODQH INTEGER,
BDCODPRES INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAHOM DATE,
BDDATAPAGRESCISAO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDCALCFGTSMESANT VARCHAR(5),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDATAPAGGRFC DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDDISSIDIO VARCHAR(5),
BDDATADISSIDIO DATE,
BDDESCANSOINDENIZADO VARCHAR(5),
BDCODMFGRESC INTEGER,
BDCODSAQUERESC INTEGER,
BDCODMRAISRESC INTEGER,
BDCODMCAGRESC INTEGER,
BDDESCPRES VARCHAR(110),
BDINIPRES INTEGER,
BDJCPRES VARCHAR(5),
BDAVPREPRES INTEGER,
BDGRRFPRES INTEGER,
BDESTPRES VARCHAR(5),
BDINDFER13 VARCHAR(5),
BDTERMCONTRPRES VARCHAR(5),
BDMULTAPRES VARCHAR(5),
BDDIASAVPREPRES INTEGER,
BDDIASPAGPRES INTEGER,
BDCODSEFMFGRESC VARCHAR(5),
BDDESCMFGRESC VARCHAR(255),
BDDESCSAQUERESC VARCHAR(60),
BDDESCMRAISRESC VARCHAR(255),
BDDESCMCAGEDRESC VARCHAR(255),
BDCODEMPDESTTRAN INTEGER,
BDCODPTRAN INTEGER,
BDCODCOLTRANS INTEGER,
BDDATATRANS DATE,
BDCODMCAGENTTRANS INTEGER,
BDCODMCAGSAITRANS INTEGER,
BDCODMFGTRANS INTEGER,
BDCODMRAISTRANS INTEGER,
BDDESCPTRANS VARCHAR(60),
BDCODSEFMFGTRANS VARCHAR(5),
BDDESCMFGTRANS VARCHAR(255),
BDDESCRAISTRANS VARCHAR(255),
BDDESCMCAGEDENTTRANS VARCHAR(255),
BDDESCMCAGEDSAITRANS VARCHAR(255),
BDCONTRCOL INTEGER,
BDPERTRANSPINSSTER NUMERIC(15,6),
BDPERTRANSPIRTER NUMERIC(15,6),
BDACORDOINSSTERC DM_BOOLEAN,
BDPERCIRTERC NUMERIC(18,6),
BDPIRTERC DM_BOOLEAN,
BDCODMULTVINC INTEGER,
BDCATEGORIAESOCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_SERV_TERC_MANUAL(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRSERV INTEGER,
PRDATA DATE,
PRREF INTEGER,
PRDATAPAG DATE,
PRHORA VARCHAR(10),
PRVALOR NUMERIC(15,2))
 RETURNS(BDCODSERV INTEGER,
BDDATASERV DATE,
BDDATAPAGSERV DATE,
BDHORASERV TIME,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODMCAG INTEGER,
BDCODCID INTEGER,
BDCODCSEG INTEGER,
BDREFCSEG INTEGER,
BDCODCIDNASC INTEGER,
BDCODUF INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDLOGRCOL DM_LOGRADOURO,
BDENDCOL DM_BDENDERECO,
BDNUMCOL DM_NUMEND,
BDCOMPLCOL DM_BDCOMPENDERECO,
BDBAICOL DM_BDBAIRRO,
BDCEPCOL VARCHAR(9),
BDDDDCOL INTEGER,
BDFONECOL DM_BDTELEFONE,
BDCELCOL DM_BDTELEFONE,
BDEMAILCOL DM_BDEMAIL,
BDSEXOCOL INTEGER,
BDDATANASCCOL DATE,
BDDATACADCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDRGCOL VARCHAR(13),
BDORGEMIRGCOL DM_ORGAOEMISSOR,
BDDATAEMIRGCOL DATE,
BDCPFCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDPISCOL VARCHAR(14),
BDDATAEMIPISCOL DATE,
BDCODUF_COL_DOC INTEGER,
BDTITELEICOL VARCHAR(13),
BDZONAELEICOL INTEGER,
BDSECAOELEICOL INTEGER,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDDATAEMICTPSCOL DATE,
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDCATCNHCOL VARCHAR(2),
BDCODCID_HIST INTEGER,
BDCODPAIS INTEGER,
BDNATURALIZADOCOL VARCHAR(5),
BDDATACHEBRASILCOL DATE,
BDCODCIDNASCCONJ INTEGER,
BDNOMPAICOL VARCHAR(70),
BDNOMMAECOL VARCHAR(70),
BDNOMCONJCOL VARCHAR(70),
BDDATANASCCONJCOL DATE,
BDCORCOL INTEGER,
BDCABELOSCOL INTEGER,
BDOLHOSCOL INTEGER,
BDALTURACOL NUMERIC(15,6),
BDPESOCOL NUMERIC(15,6),
BDSINAISCOL VARCHAR(5),
BDDEFFISICOCOL INTEGER,
BDTIPOSANGUECOL INTEGER,
BDNROCONSPROCOL VARCHAR(20),
BDSIGLACONSPROCOL VARCHAR(5),
BDCODCCMPROCOL VARCHAR(15),
BDCODCLA INTEGER,
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDCODSINTRAB INTEGER,
BDCODBAN INTEGER,
BDCODAG INTEGER,
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOADMCOL INTEGER,
BDNATUOCUPCOL INTEGER,
BDDATAINIAQUICOL DATE,
BDSALINICOL NUMERIC(15,6),
BDDIASPRAZO1COL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDIASPRAZO2COL INTEGER,
BDDATAFIMPRAZO2COL DATE,
BDDESCCONTSINCOL VARCHAR(5),
BDVINCEMPCOL INTEGER,
BDALVARACOL VARCHAR(5),
BDSINDICALIZADOCOL VARCHAR(5),
BDREGIMEPARCIALCOL VARCHAR(5),
BDFICHAREGCOL VARCHAR(12),
BDLIVROREGCOL VARCHAR(10),
BDNROFOLHAREGCOL INTEGER,
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDOBSCOL BLOB,
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDCODMAS INTEGER,
BDSALBASECOL NUMERIC(15,6),
BDCODCBO INTEGER,
BDCODQH INTEGER,
BDCODPRES INTEGER,
BDDATARESCISAO DATE,
BDDATAAVPREVIO DATE,
BDDATAHOM DATE,
BDDATAPAGRESCISAO DATE,
BDSALDOFGTS NUMERIC(15,6),
BDCALCFGTSMESANT VARCHAR(5),
BDMAIORREMUNERACAO NUMERIC(15,6),
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDATAPAGGRFC DATE,
BDREPOSICAOVAGA VARCHAR(5),
BDDISSIDIO VARCHAR(5),
BDDATADISSIDIO DATE,
BDDESCANSOINDENIZADO VARCHAR(5),
BDCODMFGRESC INTEGER,
BDCODSAQUERESC INTEGER,
BDCODMRAISRESC INTEGER,
BDCODMCAGRESC INTEGER,
BDDESCPRES VARCHAR(110),
BDINIPRES INTEGER,
BDJCPRES VARCHAR(5),
BDAVPREPRES INTEGER,
BDGRRFPRES INTEGER,
BDESTPRES VARCHAR(5),
BDINDFER13 VARCHAR(5),
BDTERMCONTRPRES VARCHAR(5),
BDMULTAPRES VARCHAR(5),
BDDIASAVPREPRES INTEGER,
BDDIASPAGPRES INTEGER,
BDCODSEFMFGRESC VARCHAR(5),
BDDESCMFGRESC VARCHAR(255),
BDDESCSAQUERESC VARCHAR(60),
BDDESCMRAISRESC VARCHAR(255),
BDDESCMCAGEDRESC VARCHAR(255),
BDCODEMPDESTTRAN INTEGER,
BDCODPTRAN INTEGER,
BDCODCOLTRANS INTEGER,
BDDATATRANS DATE,
BDCODMCAGENTTRANS INTEGER,
BDCODMCAGSAITRANS INTEGER,
BDCODMFGTRANS INTEGER,
BDCODMRAISTRANS INTEGER,
BDDESCPTRANS VARCHAR(60),
BDCODSEFMFGTRANS VARCHAR(5),
BDDESCMFGTRANS VARCHAR(255),
BDDESCRAISTRANS VARCHAR(255),
BDDESCMCAGEDENTTRANS VARCHAR(255),
BDDESCMCAGEDSAITRANS VARCHAR(255),
BDCONTRCOL INTEGER,
BDPERTRANSPINSSTER NUMERIC(15,6),
BDPERTRANSPIRTER NUMERIC(15,6),
BDCODMULTVINC INTEGER,
BDCATEGORIAESOCIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_SINDTRAB(PRSIND VARCHAR(10000),
PRREF INTEGER)
 RETURNS(BDCODSINTRAB INTEGER,
BDCODCID INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDAPESINTRAB VARCHAR(15),
BDENTSINTRAB VARCHAR(15),
BDLOGRSINTRAB DM_LOGRADOURO,
BDENDSINTRAB DM_BDENDERECO,
BDNROSINTRAB DM_NUMEND,
BDCOMPLSINTRAB DM_BDCOMPENDERECO,
BDBAISINTRAB DM_BDBAIRRO,
BDDDDSINTRAB INTEGER,
BDFONESINTRAB DM_BDTELEFONE,
BDCNPJSINTRAB VARCHAR(18),
BDCEPSINTRAB VARCHAR(9),
BDREFST INTEGER,
BDCODIND INTEGER,
BDVERFERIST INTEGER,
BDVERMULRESST INTEGER,
BDCODPMS INTEGER,
BDPERABFERST NUMERIC(15,6),
BDDATBASEST INTEGER,
BDESTABST INTEGER,
BDPERCNOTST NUMERIC(15,6),
BDMESCSST INTEGER,
BDFERRESCST INTEGER,
BDFERDOBST INTEGER,
BDFERJCST INTEGER,
BDLIMITE13ST INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_TSITCOL(PREMPRESA VARCHAR(15000),
PRCOLABORADOR VARCHAR(30000),
PRULTDIA VARCHAR(10))
 RETURNS(BDCODSIT INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATAINISEFIP DATE,
BDDATAINISIT DATE,
BDDATAFIMSIT DATE,
BDDIASSIT INTEGER,
BDNBENEFICIOSIT VARCHAR(20),
BDDATAPERICIASIT DATE,
BDDATAPARTOSIT DATE,
BDDESCSIT VARCHAR(70))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_VERBA_ASSOC_TAB(PRDIAINI INTEGER,
PRMESINI INTEGER,
PRANOINI INTEGER,
PRDIAFIM INTEGER,
PRMESFIM INTEGER,
PRANOFIM INTEGER,
PRCHAVE VARCHAR(100),
PRWHERE VARCHAR(5000),
PRPRE VARCHAR(5),
PRPRETAB VARCHAR(5),
PRSIMNAO VARCHAR(1))
 RETURNS(BDMASTER INTEGER,
BDDETAIL INTEGER,
BDDIAINI INTEGER,
BDMESINI INTEGER,
BDANOINI INTEGER,
BDDIAFIM INTEGER,
BDMESFIM INTEGER,
BDANOFIM INTEGER,
BDCODVER INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000),
BDFORMREFAUX VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRH_SP_VERBA_ASSOC_TAB_PREP(PRANOINI INTEGER,
PRANOFIM INTEGER,
PRCHAVE VARCHAR(100),
PRWHERE VARCHAR(32700),
PRPRE VARCHAR(5),
PRPRETAB VARCHAR(5),
PRSIMNAO VARCHAR(1))
 RETURNS(BDMASTER INTEGER,
BDDETAIL INTEGER,
BDDATAINI VARCHAR(8),
BDDATAFIM VARCHAR(8),
BDDIAINI INTEGER,
BDMESINI INTEGER,
BDANOINI INTEGER,
BDDIAFIM INTEGER,
BDMESFIM INTEGER,
BDANOFIM INTEGER,
BDCODVER INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000),
BDFORMREFAUX VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_EMP_VAL_GRRF (
    PREMPRESA integer,
    PRCOLABORADOR integer,
    PRANOMES integer,
    PRANOMESPAG integer,
    PRTIPOCALCULO integer,
    PRCODTIPOFC integer = null,
    PRCHAVEDARF integer = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDBFGTSMESANT numeric(15,6),
    BDFGTSMESANT numeric(15,6),
    BDBFGTSMES numeric(15,6),
    BDFGTSMES numeric(15,6),
    BDSALDO numeric(15,6),
    BDFGTS40 numeric(15,6),
    BDFGTS10 numeric(15,6),
    BDTOTAL numeric(15,6),
    BDFGTSIND numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDVALOR numeric(15,6),
    BDPERCMULTA40 numeric(15,2),
    BDPERCMULTA10 numeric(15,2),
    BDBFGTSIND numeric(18,2),
    BDBFGTSMESFN numeric(18,2),
    BDBFGTSMES13 numeric(18,2),
    BDPOSSUIDATAFGTSDIGITAL DM_BOOLEAN,
    BDFGTS13 numeric(18,2))
as
declare variable WSQL varchar(6000);
declare variable WSQLAUX varchar(6000);
declare variable WFGTSMESANT varchar(5);
declare variable WANOMES integer;
declare variable WPERCFGTSCOL numeric(15,6);
declare variable WFGTSIND numeric(15,6);
declare variable WCHAVEDARF varchar(3000);
declare variable WCONDICAOCHAVEDARF varchar(3000);
declare variable WBFGTSIND13 numeric(18,6);
declare variable WBFGTS13 numeric(18,6);
declare variable WFGTS13 numeric(18,6);
declare variable WDATAFGTSDIGITAL date;
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_MEDIAS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATAINICIO DATE,
PRDATAFINAL DATE,
PRFILTROCLASS VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDDATALANC DATE,
BDREFLANC NUMERIC(15,6),
BDVALLANC NUMERIC(15,6),
BDREFCONGLANC VARCHAR(5),
BDVALCONGLANC VARCHAR(5),
BDORIGEMLANC INTEGER,
BDCOMPLANC INTEGER,
BDCLAVER VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_ACU_GPS_FUNRURAL(PRCODIMP INTEGER,
PRCODEMP VARCHAR(32000),
PRTIPO INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDTIPO INTEGER,
BDVALACU NUMERIC(15,6),
BDVALACUTER NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_ARREDONDAMENTOS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRTIPOCALCULO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFARRE INTEGER,
BDVALARRE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_BANCO_HORAS(PREMPRESAS VARCHAR(30000),
PRCOLAB VARCHAR(30000),
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFERENCIA INTEGER,
BDSALDOINICIAL NUMERIC(15,2),
BDCREDITO NUMERIC(15,2),
BDDEBITO NUMERIC(15,2),
BDSALDOFINAL NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CALC_AUTONOMO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRSERVICO INTEGER,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS varchar(2788) = null,
PRCODTPCC VARCHAR(10000) = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDMENORESVER VARCHAR(5),
BDPROPVER VARCHAR(5),
BDBASEVTVER VARCHAR(5),
BDREEMBGPSVER VARCHAR(5),
BDHEVER NUMERIC(15,6),
BDGRAVAFICHAHNVER VARCHAR(5),
BDCCPRINCIPALVER VARCHAR(5),
BDFORMREFAUXVER VARCHAR(5000),
BDFORMREFVER VARCHAR(5000),
BDFORMVALVER VARCHAR(5000),
BDBASEDSRHEVER VARCHAR(5),
BDBASEDSRRVVER VARCHAR(5),
BDDEDFORMREFAUXVER VARCHAR(5),
BDDEDFORMREFVER VARCHAR(5),
BDDEDFORMVALVER VARCHAR(5),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDETALHE VARCHAR(255),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBINSSCALC NUMERIC(15,6),
BDBIRCALC NUMERIC(15,6),
BDDATAPGTO DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CALC_FN_AUT(PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRTIPOCOL INTEGER,
PRCODAUT VARCHAR(10000))
 RETURNS(BDGRUPOCLA INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDORDEM INTEGER,
BDCODSERV INTEGER,
BDREFFN INTEGER,
BDBFGTSFN NUMERIC(15,6),
BDFGTSFN NUMERIC(15,6),
BDFGTSCSFN NUMERIC(15,6),
BDBFGTS13FN NUMERIC(15,6),
BDFGTS13FN NUMERIC(15,6),
BDFGTS13CSFN NUMERIC(15,6),
BDMAIORREMFN NUMERIC(15,6),
BDBINSSFN NUMERIC(15,6),
BDALIQINSSFN NUMERIC(15,6),
BDINSSFN NUMERIC(15,6),
BDBIRRFFN NUMERIC(15,6),
BDALIQIRRFFN NUMERIC(15,6),
BDIRRFFN NUMERIC(15,6),
BDBINSS13FN NUMERIC(15,6),
BDALIQINSS13FN NUMERIC(15,6),
BDINSS13FN NUMERIC(15,6),
BDBIRRF13FN NUMERIC(15,6),
BDALIQIRRF13FN NUMERIC(15,6),
BDIRRF13FN NUMERIC(15,6),
BDBSALFAMFN NUMERIC(15,6),
BDSALFAMFN NUMERIC(15,6),
BDBRAISFN NUMERIC(15,6),
BDSALBASEFN NUMERIC(15,6),
BDDEPFN NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6),
BDBASEPISFEFN NUMERIC(15,6),
BDBASEPIS13FN NUMERIC(15,6),
BDBSALMATEMPFN NUMERIC(15,6),
BDSALMATEMPFN NUMERIC(15,6),
BDBRATAPOFN NUMERIC(15,6),
BDBRATAPOFEFN NUMERIC(15,6),
BDBRATAPO13FN NUMERIC(15,6),
BDBINSSFEFOLFN NUMERIC(15,6),
BDINSSFEFOLFN NUMERIC(15,6),
BDALIQINSSFEFOLFN NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCALCTOMADOR VARCHAR(5),
BDCALCAUTONOMO VARCHAR(5),
BDVALOUTENTIDADE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CALC_FN_AUT_PREV(PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRTIPOCOL INTEGER,
PRCODAUT VARCHAR(10000))
 RETURNS(BDGRUPOCLA INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDORDEM INTEGER,
BDCODSERV INTEGER,
BDREFFN INTEGER,
BDBFGTSFN NUMERIC(18,6),
BDFGTSFN NUMERIC(18,6),
BDFGTSCSFN NUMERIC(18,6),
BDBFGTS13FN NUMERIC(18,6),
BDFGTS13FN NUMERIC(18,6),
BDFGTS13CSFN NUMERIC(18,6),
BDMAIORREMFN NUMERIC(18,6),
BDBINSSFN NUMERIC(18,6),
BDALIQINSSFN NUMERIC(18,6),
BDINSSFN NUMERIC(18,6),
BDBIRRFFN NUMERIC(18,6),
BDALIQIRRFFN NUMERIC(18,6),
BDIRRFFN NUMERIC(18,6),
BDBINSS13FN NUMERIC(18,6),
BDALIQINSS13FN NUMERIC(18,6),
BDINSS13FN NUMERIC(18,6),
BDBIRRF13FN NUMERIC(18,6),
BDALIQIRRF13FN NUMERIC(18,6),
BDIRRF13FN NUMERIC(18,6),
BDBSALFAMFN NUMERIC(18,6),
BDSALFAMFN NUMERIC(18,6),
BDBRAISFN NUMERIC(18,6),
BDSALBASEFN NUMERIC(18,6),
BDDEPFN NUMERIC(18,6),
BDBASEPISFN NUMERIC(18,6),
BDBASEPISFEFN NUMERIC(18,6),
BDBASEPIS13FN NUMERIC(18,6),
BDBSALMATEMPFN NUMERIC(18,6),
BDSALMATEMPFN NUMERIC(18,6),
BDBRATAPOFN NUMERIC(18,6),
BDBRATAPOFEFN NUMERIC(18,6),
BDBRATAPO13FN NUMERIC(18,6),
BDBINSSFEFOLFN NUMERIC(18,6),
BDINSSFEFOLFN NUMERIC(18,6),
BDALIQINSSFEFOLFN NUMERIC(18,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCALCTOMADOR VARCHAR(5),
BDCALCAUTONOMO VARCHAR(5),
BDVALOUTENTIDADE NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CALC_FOLHANORMAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRCODTPCC VARCHAR(20000) = NULL,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS varchar(2788) = null)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDMENORESVER VARCHAR(5),
BDPROPVER VARCHAR(5),
BDBASEVTVER VARCHAR(5),
BDREEMBGPSVER VARCHAR(5),
BDHEVER NUMERIC(15,6),
BDGRAVAFICHAHNVER VARCHAR(5),
BDCCPRINCIPALVER VARCHAR(5),
BDFORMREFAUXVER VARCHAR(800),
BDFORMREFVER VARCHAR(800),
BDFORMVALVER VARCHAR(5000),
BDBASEDSRHEVER VARCHAR(5),
BDBASEDSRRVVER VARCHAR(5),
BDDEDFORMREFAUXVER VARCHAR(5),
BDDEDFORMREFVER VARCHAR(5),
BDDEDFORMVALVER VARCHAR(5),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDETALHE VARCHAR(255),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFEFOL NUMERIC(15,6),
BDFGTSFEFOL NUMERIC(15,6),
BDDATAPGTO DATE,
BDBINSSAPFN NUMERIC(18,6),
BDINSSAPFN NUMERIC(18,6),
BDBINSS13APFN NUMERIC(18,6),
BDINSS13APFN NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CALC_GPS(PRCODIMP INTEGER,
PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRAPENASGPS INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER)
 RETURNS(BDTIPOREG INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDCODCENTRO INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDVALFUNEMP NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDVALPROEMP NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDVALAUTEMP NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDVALORFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALORRAT NUMERIC(15,6),
BDVALORBRUTO NUMERIC(15,6),
BDVALORLIQUIDO NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6),
BDCHAVE INTEGER,
BDVALCOMPENSADO NUMERIC(15,6),
BDVALACOMPENSAR NUMERIC(15,6),
BDVALORACUMULADO NUMERIC(15,6),
BDVALORACUMULADOUSADO NUMERIC(15,6),
BDVALORACUMUTERCEIRO NUMERIC(15,6),
BDVALORACUTERCEIROSUSADO NUMERIC(15,6),
BDCODEMPANT INTEGER,
BDCODIMPANT INTEGER,
BDCHAVEDARFANT INTEGER,
BDCODPERIODOANT INTEGER,
BDORDEMANT INTEGER,
BDREFERENCIAANT INTEGER,
BDQUOTAANT INTEGER,
BDDESCACUMDET VARCHAR(3000),
BDDESCACU VARCHAR(3000),
BDVALORCAMPO6 NUMERIC(15,6),
BDVALORNOTAS NUMERIC(15,6),
BDTOTVALORACUMULADO NUMERIC(15,6),
BDTOTVALORACUMULADOTERC NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDTOTCOMPENSACAO NUMERIC(15,6),
BDDESCNOTAS NUMERIC(15,6),
BDTOTDESCCOMP NUMERIC(15,6),
BDDESCSALFAM NUMERIC(15,6),
BDDESCDEDGPS NUMERIC(15,6),
BDVALOUTENTIDADES NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDVALFUNEMPFN NUMERIC(15,6),
BDVALFUNEMPFC NUMERIC(15,6),
BDVALFUNEMPFERFN NUMERIC(15,6),
BDVALFUNEMPFERFC NUMERIC(15,6),
BDVALFUNEMP13FN NUMERIC(15,6),
BDVALFUNEMP13FC NUMERIC(15,6),
BDVALFUNEMP13 NUMERIC(15,6),
BDVALFUNEMPC13 NUMERIC(15,6),
BDVALPROEMPFN NUMERIC(15,6),
BDVALPROEMPFC NUMERIC(15,6),
BDVALPROEMPFERFN NUMERIC(15,6),
BDVALPROEMPFERFC NUMERIC(15,6),
BDVALPROEMP13FN NUMERIC(15,6),
BDVALPROEMP13FC NUMERIC(15,6),
BDVALPROEMP13 NUMERIC(15,6),
BDVALPROEMPC13 NUMERIC(15,6),
BDVALAUTEMPFN NUMERIC(15,6),
BDVALAUTEMPFC NUMERIC(15,6),
BDVALAUTEMPFERFN NUMERIC(15,6),
BDVALAUTEMPFERFC NUMERIC(15,6),
BDVALAUTEMP13FN NUMERIC(15,6),
BDVALAUTEMP13FC NUMERIC(15,6),
BDVALAUTEMP13 NUMERIC(15,6),
BDVALAUTEMPC13 NUMERIC(15,6),
BDVALFPASEMPFN NUMERIC(15,6),
BDVALFPASEMPFC NUMERIC(15,6),
BDVALFPASEMPFERFN NUMERIC(15,6),
BDVALFPASEMPFERFC NUMERIC(15,6),
BDVALFPASEMP13FN NUMERIC(15,6),
BDVALFPASEMP13FC NUMERIC(15,6),
BDVALFPASEMP13 NUMERIC(15,6),
BDVALFPASEMPC13 NUMERIC(15,6),
BDVALRATEMPFN NUMERIC(15,6),
BDVALRATEMPFC NUMERIC(15,6),
BDVALRATEMPFERFN NUMERIC(15,6),
BDVALRATEMPFERFC NUMERIC(15,6),
BDVALRATEMP13FN NUMERIC(15,6),
BDVALRATEMP13FC NUMERIC(15,6),
BDVALRATEMP13 NUMERIC(15,6),
BDVALRATEMPC13 NUMERIC(15,6),
BDVALRATAPOEMPFN NUMERIC(15,6),
BDVALRATAPOEMPFC NUMERIC(15,6),
BDVALRATAPOEMPFERFN NUMERIC(15,6),
BDVALRATAPOEMPFERFC NUMERIC(15,6),
BDVALRATAPOEMP13FN NUMERIC(15,6),
BDVALRATAPOEMP13FC NUMERIC(15,6),
BDVALRATAPOEMP13 NUMERIC(15,6),
BDVALRATAPOEMPC13 NUMERIC(15,6),
BDCHAVEDARF INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CONS_13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF13 INTEGER,
BDMESESPROP13 INTEGER,
BDBASEIR13 NUMERIC(15,6),
BDBASEFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTSCS13 NUMERIC(15,6),
BDPERCIR13 NUMERIC(15,6),
BDVALORIR13 NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDPERCINSS13 NUMERIC(15,6),
BDVALORINSS13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CONS_AD13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFA13 INTEGER,
BDPERCA13 NUMERIC(15,6),
BDVALA13 NUMERIC(15,6),
BDBASEIRA13 NUMERIC(15,6),
BDFGTSA13 NUMERIC(15,6),
BDFGTSCSA13 NUMERIC(15,6),
BDBASEFGTSA13 NUMERIC(15,6),
BDPERCIRA13 NUMERIC(15,6),
BDVALORIRA13 NUMERIC(15,6),
BDREF INTEGER,
BDSALBASE NUMERIC(15,6),
BDPROVENTO INTEGER,
BDDESCONTO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CONS_ADIANTA_SAL(PRCODEMP VARCHAR(32700),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFAD INTEGER,
BDCODVER INTEGER,
BDREFVAD NUMERIC(15,6),
BDREFAUXVAD NUMERIC(15,6),
BDVALVAD NUMERIC(15,6),
BDIGNREFAVAD VARCHAR(5),
BDIGNREFVAD VARCHAR(5),
BDIGNVALVAD VARCHAR(5),
BDDATAAD DATE,
BDBASEAD INTEGER,
BDTIPOAD INTEGER,
BDVALPERCAD NUMERIC(15,6),
BDBASEIRAD NUMERIC(15,6),
BDDATABAIXAAD DATE,
BDREFBAIXAAD INTEGER,
BDVALORIRAD NUMERIC(15,6),
BDPERCIRAD NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CONS_CALC_13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDMESESPROP13 INTEGER,
BDBASEIR13 NUMERIC(15,6),
BDBASEFGTS13 NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS13 NUMERIC(15,6),
BDDATABAIXA13 DATE,
BDREFBAIXA13 INTEGER,
BDPERCIR13 NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDPERCINSS13 NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CONS_CALC_AUTONOMOS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODSERV INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFE NUMERIC(15,6),
BDFGTSFE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CONS_CALC_COMP13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBASEIRC13 NUMERIC(15,6),
BDBASEINSSC13 NUMERIC(15,6),
BDBASEFGTSC13 NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCSC13 NUMERIC(15,6),
BDDATABAIXAC13 DATE,
BDREFBAIXAC13 INTEGER,
BDPERCIRC13 NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDPERCINSSC13 NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CONS_CALC_FERIAS(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDINIPERAQUISFE DATE,
BDCODFE INTEGER,
BDINIPERGOZOFE DATE,
BDFIMPERAQUISFE DATE,
BDFIMPERGOZOFE DATE,
BDDATAPAGFE DATE,
BDQTDGOZOFE INTEGER,
BDQTDABONOFE INTEGER,
BDSALDOINIFE NUMERIC(15,6),
BDSALDOFIMFE NUMERIC(15,6),
BDBASEIRFE NUMERIC(15,6),
BDALIQIRFE NUMERIC(15,6),
BDVALORIRFE NUMERIC(15,6),
BDBASEINSSFE NUMERIC(15,6),
BDALIQINSSFE NUMERIC(15,6),
BDVALORINSSFE NUMERIC(15,6),
BDDEPFE NUMERIC(15,6),
BDSALBASEFE NUMERIC(15,6),
BDSALBASEHEFE NUMERIC(15,6),
BDDATABAIXAFE DATE,
BDCOLETIVASFE VARCHAR(5),
BDREFPAGABOFE INTEGER,
BDCODVER INTEGER,
BDREFVFE NUMERIC(15,6),
BDREFAUXVFE NUMERIC(15,6),
BDVALVFE NUMERIC(15,6),
BDIGNREFAVFE VARCHAR(5),
BDIGNREFVFE VARCHAR(5),
BDIGNVALVFE VARCHAR(5),
BDSALDOFINALSINDFE NUMERIC(18,6),
BDINIGOZORECIBOFE DATE,
BDFIMGOZORECIBOFE DATE,
BDQTDGOZORECIBOFE NUMERIC(18,6),
BDMIGRACAO DM_BOOLEAN)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CONS_CALC_FOLHACOMP(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCREDITO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CONS_CALC_FOLHANORMAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFE NUMERIC(15,6),
BDFGTSFE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CONS_CALC_FOLHANORMALPR(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDBFGTSFE NUMERIC(15,6),
BDFGTSFE NUMERIC(15,6),
BDDATARESCISAOPREV DATE)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CONS_CALCTERC(PRCODEMP VARCHAR(10000),
PRCODSERV VARCHAR(500),
PRCODTER VARCHAR(32700),
PRDATAINI DATE,
PRDATAFIM DATE,
PRCODCC varchar(500))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(100),
BDLOGEMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCODCID INTEGER,
BDNOMCID VARCHAR(100),
BDCODTER INTEGER,
BDNOMTER VARCHAR(100),
BDCPFTER VARCHAR(100),
BDPISTER VARCHAR(100),
BDRGTER VARCHAR(100),
BDNROCONSPROTER VARCHAR(100),
BDCODSERV INTEGER,
BDDATASERV DATE,
BDCODVER INTEGER,
BDDESCVER VARCHAR(100),
BDREFERENCIA NUMERIC(18,6),
BDDESCTIPOSERV VARCHAR(500),
BDPROVENTO NUMERIC(18,6),
BDDESCONTO NUMERIC(18,6),
BDCODCENTRO integer,
BDCODTPCC integer,
BDNOMCTACC varchar(100),
BDAPECTACC varchar(20),
BDLOGRTER DM_LOGRADOURO,
BDENDTER DM_BDENDERECO,
BDNUMTER DM_NUMEND,
BDCOMPLTER DM_BDCOMPENDERECO,
BDBAITER varchar(60),
BDCEPTER varchar(9),
BDCODCIDTER integer,
BDNOMCIDTER varchar(100),
BDUFTER varchar(2),
BDINFPROVENTO numeric(18,6),
BDINFDESCONTO numeric(18,6),
BDORDEM integer)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CONS_COMP13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFC13 INTEGER,
BDBASEIRC13 NUMERIC(15,6),
BDBASEINSSC13 NUMERIC(15,6),
BDBASEFGTSC13 NUMERIC(15,6),
BDFGTSC13 NUMERIC(15,6),
BDFGTSCSC13 NUMERIC(15,6),
BDPERCIRC13 NUMERIC(15,6),
BDVALORIRC13 NUMERIC(15,6),
BDPERCINSSC13 NUMERIC(15,6),
BDVALORINSSC13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_CONS_FOLHANORMAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDBFGTSFN NUMERIC(15,6),
BDFGTSFN NUMERIC(15,6),
BDFGTSCSFN NUMERIC(15,6),
BDBFGTS13FN NUMERIC(15,6),
BDFGTS13FN NUMERIC(15,6),
BDFGTS13CSFN NUMERIC(15,6),
BDMAIORREMFN NUMERIC(15,6),
BDBINSSFN NUMERIC(15,6),
BDALIQINSSFN NUMERIC(15,6),
BDINSSFN NUMERIC(15,6),
BDBIRRFFN NUMERIC(15,6),
BDALIQIRRFFN NUMERIC(15,6),
BDIRRFFN NUMERIC(15,6),
BDBINSS13FN NUMERIC(15,6),
BDALIQINSS13FN NUMERIC(15,6),
BDINSS13FN NUMERIC(15,6),
BDBIRRF13FN NUMERIC(15,6),
BDALIQIRRF13FN NUMERIC(15,6),
BDIRRF13FN NUMERIC(15,6),
BDBSALFAMFN NUMERIC(15,6),
BDSALFAMFN NUMERIC(15,6),
BDBRAISFN NUMERIC(15,6),
BDSALBASEFN NUMERIC(15,6),
BDDEPFN NUMERIC(15,6),
BDCREDITOFN NUMERIC(15,6),
BDDEBITOFN NUMERIC(15,6),
BDBFGTSFEFN NUMERIC(15,6),
BDFGTSFEFN NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_DADOS_BAIXA_CALCULO(PRCODEMP INTEGER,
PRCODTER INTEGER,
PRCODSERV INTEGER,
PRCODCOL INTEGER,
PRTIPOCALC INTEGER,
PRREFERENCIA INTEGER,
PRDATA DATE,
PRREFCOMP INTEGER,
PRINIPERAQUI DATE,
PRCODFER INTEGER,
PRLIQUIDO NUMERIC(18,6),
PRINIGOZO DATE,
PRREFABONO INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_DADOS_CALC_GPS(PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRTIPOEMISSAO INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER,
PRAPENAGPS INTEGER)
 RETURNS(BDTIPO INTEGER,
BDCODEMP INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALOUTENTIDADE NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCODTOMADOR INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDBASEFUNFN NUMERIC(15,6),
BDBASEFUNFC NUMERIC(15,6),
BDBASEFUNFERFN NUMERIC(15,6),
BDBASEFUNFERFC NUMERIC(15,6),
BDBASEFUN13RFN NUMERIC(15,6),
BDBASEFUN13RFC NUMERIC(15,6),
BDBASEFUN13 NUMERIC(15,6),
BDBASEFUNC13 NUMERIC(15,6),
BDBASEPROFN NUMERIC(15,6),
BDBASEPROFC NUMERIC(15,6),
BDBASEPROFERFN NUMERIC(15,6),
BDBASEPROFERFC NUMERIC(15,6),
BDBASEPRO13RFN NUMERIC(15,6),
BDBASEPRO13RFC NUMERIC(15,6),
BDBASEPRO13 NUMERIC(15,6),
BDBASEPROC13 NUMERIC(15,6),
BDBASEAUTFN NUMERIC(15,6),
BDBASEAUTFC NUMERIC(15,6),
BDBASEAUTFERFN NUMERIC(15,6),
BDBASEAUTFERFC NUMERIC(15,6),
BDBASEAUT13RFN NUMERIC(15,6),
BDBASEAUT13RFC NUMERIC(15,6),
BDBASEAUT13 NUMERIC(15,6),
BDBASEAUTC13 NUMERIC(15,6),
BDBASEFPASFN NUMERIC(15,6),
BDBASEFPASFC NUMERIC(15,6),
BDBASEFPASFERFN NUMERIC(15,6),
BDBASEFPASFERFC NUMERIC(15,6),
BDBASEFPAS13RFN NUMERIC(15,6),
BDBASEFPAS13RFC NUMERIC(15,6),
BDBASEFPAS13 NUMERIC(15,6),
BDBASEFPASC13 NUMERIC(15,6),
BDBASERATAPOFN NUMERIC(15,6),
BDBASERATAPOFC NUMERIC(15,6),
BDBASERATAPOFERFN NUMERIC(15,6),
BDBASERATAPOFERFC NUMERIC(15,6),
BDBASERATAPO13RFN NUMERIC(15,6),
BDBASERATAPO13RFC NUMERIC(15,6),
BDBASERATAPO13 NUMERIC(15,6),
BDBASERATAPOC13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_DADOS_IND_CALC_GPS(PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRTIPOEMISSAO INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER,
PRAPENASGPS INTEGER)
 RETURNS(BDCODCENTRO INTEGER,
BDTIPO INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALOUTENTIDADE NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCODTOMADOR INTEGER,
BDBASEFUNFN NUMERIC(15,6),
BDBASEFUNFC NUMERIC(15,6),
BDBASEFUNFERFN NUMERIC(15,6),
BDBASEFUNFERFC NUMERIC(15,6),
BDBASEFUN13RFN NUMERIC(15,6),
BDBASEFUN13RFC NUMERIC(15,6),
BDBASEFUN13 NUMERIC(15,6),
BDBASEFUNC13 NUMERIC(15,6),
BDBASEPROFN NUMERIC(15,6),
BDBASEPROFC NUMERIC(15,6),
BDBASEPROFERFN NUMERIC(15,6),
BDBASEPROFERFC NUMERIC(15,6),
BDBASEPRO13RFN NUMERIC(15,6),
BDBASEPRO13RFC NUMERIC(15,6),
BDBASEPRO13 NUMERIC(15,6),
BDBASEPROC13 NUMERIC(15,6),
BDBASEAUTFN NUMERIC(15,6),
BDBASEAUTFC NUMERIC(15,6),
BDBASEAUTFERFN NUMERIC(15,6),
BDBASEAUTFERFC NUMERIC(15,6),
BDBASEAUT13RFN NUMERIC(15,6),
BDBASEAUT13RFC NUMERIC(15,6),
BDBASEAUT13 NUMERIC(15,6),
BDBASEAUTC13 NUMERIC(15,6),
BDBASEFPASFN NUMERIC(15,6),
BDBASEFPASFC NUMERIC(15,6),
BDBASEFPASFERFN NUMERIC(15,6),
BDBASEFPASFERFC NUMERIC(15,6),
BDBASEFPAS13RFN NUMERIC(15,6),
BDBASEFPAS13RFC NUMERIC(15,6),
BDBASEFPAS13 NUMERIC(15,6),
BDBASEFPASC13 NUMERIC(15,6),
BDBASERATAPOFN NUMERIC(15,6),
BDBASERATAPOFC NUMERIC(15,6),
BDBASERATAPOFERFN NUMERIC(15,6),
BDBASERATAPOFERFC NUMERIC(15,6),
BDBASERATAPO13RFN NUMERIC(15,6),
BDBASERATAPO13RFC NUMERIC(15,6),
BDBASERATAPO13 NUMERIC(15,6),
BDBASERATAPOC13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_ESTOUROS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRTIPOCALCULO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFEST INTEGER,
BDVALEST NUMERIC(15,6),
BDTIPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_EXTRATO_FGTS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(10000),
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATA INTEGER,
BDMOVIMENTACAO VARCHAR(200),
BDVALOR NUMERIC(15,6),
BDACUMULADO NUMERIC(15,6),
BDVALORJAM NUMERIC(15,6),
BDVALORDEPOSITO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_FICHA_REG_COLABORADOR (
    PREMPRESA varchar(15000),
    PRCOLABORADOR varchar(30000),
    PRMODELO integer,
    PRORDEMIMP integer,
    PRCLASSE integer,
    PRFUNCAO integer,
    PRCENTROCUSTO integer,
    PRSINDICATO integer,
    PRREFERENCIA integer,
    PRULTIMODIA date,
    PROBS integer,
    PRSITCOL integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(18),
    BDTIPOESCALA integer,
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDBAIEMP DM_BDBAIRRO,
    BDCIDADEEMP varchar(40),
    BDUFEMP varchar(2),
    BDCEPEMP varchar(9),
    BDFONEEMP DM_BDTELEFONE,
    BDDDDEMP integer,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLORDEM DM_BDNOMCOL,
    BDNOMPAICOL varchar(70),
    BDNOMMAECOL varchar(70),
    BDNOMCONJCOL varchar(70),
    BDDATANASCCOL date,
    BDCORCOL integer,
    BDSEXOCOL integer,
    BDPAISCOL varchar(40),
    BDNACIONALIDADE varchar(30),
    BDDATACHEBRASILCOL date,
    BDCIDADENASCCOL varchar(40),
    BDUFNASCCOL varchar(2),
    BDTIPOSANGUECOL integer,
    BDCPFCOL varchar(14),
    BDRGCOL varchar(13),
    BDDATAEMIREGCOL date,
    BDORGEMIRGCOL DM_ORGAOEMISSOR,
    BDCNHCOL varchar(11),
    BDCATCNHCOL varchar(2),
    BDVENCNHCOL date,
    BDCTPSCOL DM_BDCTPS,
    BDSERIECOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDRESERVISTACOL varchar(20),
    BDTITELEICOL varchar(20),
    BDGRAUINSTCOL integer,
    BDZONAELEICOL integer,
    BDSECAOELEICOL integer,
    BDPISCOL varchar(14),
    BDDATAEMIPISCOL date,
    BDESTCIVCOL integer,
    BDLOGRCOL DM_LOGRADOURO,
    BDENDCOL DM_BDENDERECO,
    BDNUMCOL DM_NUMEND,
    BDCOMPLCOL DM_BDCOMPENDERECO,
    BDBAICOL DM_BDBAIRRO,
    BDCIDADECOL varchar(40),
    BDUFCOL varchar(2),
    BDCEPCOL varchar(9),
    BDFONECOL DM_BDTELEFONE,
    BDDDDCOL integer,
    BDEMAILCOL DM_BDEMAIL,
    BDCELCOL DM_BDTELEFONE,
    BDDATAADMCOL date,
    BDDATACADCOL date,
    BDSALINICOL numeric(15,2),
    BDFORMAPAGTOCOL integer,
    BDPERCINSALUBCOL numeric(15,6),
    BDPERCPERCULCOL numeric(15,2),
    BDCATEGORIACOL integer,
    BDCODSINTRAB integer,
    BDDESCSINTRAB varchar(60),
    BDDEFCOL DM_BOOLEAN,
    BDDEFFISICOCOL integer,
    BDREAB DM_BOOLEAN,
    BDTIPOCOL integer,
    BDCTAFGTSCOL varchar(20),
    BDDATAOPCAOFGTSCOL date,
    BDCTADEPCOL varchar(20),
    BDDIGCTADEPCOL varchar(2),
    BDCODTFUC integer,
    BDDESCTFUC varchar(40),
    BDCODCBO integer,
    BDDATARESCISAO date,
    BDDATAAVPREVIO date,
    BDSALDOFGTS numeric(15,6),
    BDMAIORREMUNERACAO numeric(15,6),
    BDDATAPAGGRFC date,
    BDCODPRES integer,
    BDDESCPRES varchar(110),
    BDFOTOCOL blob sub_type 0 segment size 80,
    BDFICHAREGCOL varchar(12),
    BDLIVROREGCOL varchar(10),
    BDNROFOLHAREGCOL integer,
    BDUFCTPS varchar(2),
    BDDESCCATEGORIA varchar(300),
    BDNOMBAN varchar(60),
    BDCODBAN integer,
    BDNOMAG varchar(40),
    BDCODAG integer,
    BDNATURALIZADOCOL varchar(5),
    BDCABELOSCOL integer,
    BDOLHOSCOL integer,
    BDALTURACOL numeric(15,6),
    BDPESOCOL numeric(15,6),
    BDSINAISCOL varchar(5),
    BDOBSCOL blob sub_type 1 segment size 5000,
    BDDDDCELCOL integer,
    BDSIGLAUFRG varchar(2),
    BDDIANASC varchar(2),
    BDMESNASC varchar(2),
    BDANONASC varchar(10),
    BDCONTRCOL integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDNOMTPCC DM_BDNOMEMP,
    BDNOMCIDTPCC varchar(40),
    BDUFTPCC varchar(2),
    BDCODCLA integer)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_FICHAINSS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF INTEGER,
BDBINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBASEINSSC13 NUMERIC(15,6),
BDINSSC13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_FICHAIR(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRTIPOCALC INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF VARCHAR(10),
BDTIPOCALC INTEGER,
BDBRUTO NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDVALIR NUMERIC(15,6),
BDVALINSS NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_FICHAIR_ANUAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOBASE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDDATAADMCOL DATE,
BDDATARESCISAO DATE,
BDREF VARCHAR(10),
BDRENDTRIB NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDALUGUEIS NUMERIC(15,6),
BDPRIVPRIVADA NUMERIC(15,6),
BDDESPMEDICAS NUMERIC(15,6),
BDPENSAOALIM NUMERIC(15,6),
BDPENSAOJUDICIAL NUMERIC(15,6),
BDAJUDACUSTO NUMERIC(15,6),
BDLUCROPJ NUMERIC(15,6),
BDAVISOPREV NUMERIC(15,6),
BDRENDTRIB13 NUMERIC(15,6),
BDDEP13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDPENSAOALIM13 NUMERIC(15,6),
BDDATA DATE,
BDGRUPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_FICHARAIS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF INTEGER,
BDBRAIS NUMERIC(15,6),
BDB13 NUMERIC(15,6),
BDBA13 NUMERIC(15,6),
BDBC13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_FICHARAIS_NOVO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF INTEGER,
BDBRAIS NUMERIC(15,6),
BDB13 NUMERIC(15,6),
BDBA13 NUMERIC(15,6),
BDBC13 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_FN_FC_13_C13_VERBAS(PREMPRESA VARCHAR(15000),
PRCOLABORADOR VARCHAR(30000),
PRREFERENCIA INTEGER,
PRTIPOPARCELA SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF INTEGER,
BDSUMVALV NUMERIC(18,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_GPS(PRCODIMP INTEGER,
PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRTIPOEMISSAO INTEGER,
PRAPENASGPS INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER)
 RETURNS(BDTIPOREG INTEGER,
BDCODEMP INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDCODCENTRO INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDVALFUNEMP NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDVALPROEMP NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDVALAUTEMP NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDVALORFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALORRAT NUMERIC(15,6),
BDVALORBRUTO NUMERIC(15,6),
BDVALORLIQUIDO NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6),
BDCHAVE INTEGER,
BDVALCOMPENSADO NUMERIC(15,6),
BDVALACOMPENSAR NUMERIC(15,6),
BDVALORACUMULADO NUMERIC(15,6),
BDVALORACUMULADOUSADO NUMERIC(15,6),
BDVALORACUTERCEIROS NUMERIC(15,6),
BDVALORACUTERCEIROSUSADO NUMERIC(15,6),
BDCODEMPANT INTEGER,
BDCHAVEDARFANT INTEGER,
BDCODIMPANT INTEGER,
BDCODPERIODOANT INTEGER,
BDORDEMANT INTEGER,
BDREFERENCIAANT INTEGER,
BDQUOTAANT INTEGER,
BDDESCACUMDET VARCHAR(3000),
BDDESCACUM VARCHAR(3000),
BDVALORCAMPO6 NUMERIC(15,6),
BDVALNOTAS NUMERIC(15,6),
BDDESCNOTAS NUMERIC(15,6),
BDTOTDESCCOMP NUMERIC(15,6),
BDTOTVALORACUMULADO NUMERIC(15,6),
BDTOTVALORACUMULADOTERC NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDTOTCOMPENSACAO NUMERIC(15,6),
BDDESCSALFAM NUMERIC(15,6),
BDDESCDEDGPS NUMERIC(15,6),
BDVALOUTENTIDADE NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDVALFUNEMPFN NUMERIC(15,6),
BDVALFUNEMPFC NUMERIC(15,6),
BDVALFUNEMPFERFN NUMERIC(15,6),
BDVALFUNEMPFERFC NUMERIC(15,6),
BDVALFUNEMP13FN NUMERIC(15,6),
BDVALFUNEMP13FC NUMERIC(15,6),
BDVALFUNEMP13 NUMERIC(15,6),
BDVALFUNEMPC13 NUMERIC(15,6),
BDVALPROEMPFN NUMERIC(15,6),
BDVALPROEMPFC NUMERIC(15,6),
BDVALPROEMPFERFN NUMERIC(15,6),
BDVALPROEMPFERFC NUMERIC(15,6),
BDVALPROEMP13FN NUMERIC(15,6),
BDVALPROEMP13FC NUMERIC(15,6),
BDVALPROEMP13 NUMERIC(15,6),
BDVALPROEMPC13 NUMERIC(15,6),
BDVALAUTEMPFN NUMERIC(15,6),
BDVALAUTEMPFC NUMERIC(15,6),
BDVALAUTEMPFERFN NUMERIC(15,6),
BDVALAUTEMPFERFC NUMERIC(15,6),
BDVALAUTEMP13FN NUMERIC(15,6),
BDVALAUTEMP13FC NUMERIC(15,6),
BDVALAUTEMP13 NUMERIC(15,6),
BDVALAUTEMPC13 NUMERIC(15,6),
BDVALFPASEMPFN NUMERIC(15,6),
BDVALFPASEMPFC NUMERIC(15,6),
BDVALFPASEMPFERFN NUMERIC(15,6),
BDVALFPASEMPFERFC NUMERIC(15,6),
BDVALFPASEMP13FN NUMERIC(15,6),
BDVALFPASEMP13FC NUMERIC(15,6),
BDVALFPASEMP13 NUMERIC(15,6),
BDVALFPASEMPC13 NUMERIC(15,6),
BDVALRATEMPFN NUMERIC(15,6),
BDVALRATEMPFC NUMERIC(15,6),
BDVALRATEMPFERFN NUMERIC(15,6),
BDVALRATEMPFERFC NUMERIC(15,6),
BDVALRATEMP13FN NUMERIC(15,6),
BDVALRATEMP13FC NUMERIC(15,6),
BDVALRATEMP13 NUMERIC(15,6),
BDVALRATEMPC13 NUMERIC(15,6),
BDVALRATAPOEMPFN NUMERIC(15,6),
BDVALRATAPOEMPFC NUMERIC(15,6),
BDVALRATAPOEMPFERFN NUMERIC(15,6),
BDVALRATAPOEMPFERFC NUMERIC(15,6),
BDVALRATAPOEMP13FN NUMERIC(15,6),
BDVALRATAPOEMP13FC NUMERIC(15,6),
BDVALRATAPOEMP13 NUMERIC(15,6),
BDVALRATAPOEMPC13 NUMERIC(15,6),
BDCHAVEDARF INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_GPS_CONTRATANTE(PREMP INTEGER,
PRREF INTEGER,
PRTERC INTEGER,
PRTPCC INTEGER,
PRNRNF VARCHAR(15))
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_GPS_FUNRURAL(PREMP INTEGER,
PRREF INTEGER,
PRNRNF VARCHAR(15),
PRTIPOEMISSAO INTEGER,
PRCODIMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDVALOR NUMERIC(15,6),
BDVALTERC NUMERIC(15,6),
BDVALORACU NUMERIC(15,6),
BDVALACUTERC NUMERIC(15,6),
BDDESCNOTAS VARCHAR(5000),
BDBASECALC NUMERIC(18,6)) 
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_GPS_FUNRURAL_RESUMO (
    PREMP integer,
    PRREF integer,
    PRNRNF varchar(15),
    PRTIPOEMISSAO integer,
    PRCODIMP integer)
returns (
    BDCODEMP integer,
    BDVALOR numeric(18,6),
    BDVALTERC numeric(18,6),
    BDVALORACU numeric(18,6),
    BDVALACUTERC numeric(18,6),
    BDDESCNOTAS varchar(10000),
    BDBASECALC numeric(18,6),
    BDVALRAT numeric(18,6))
as
BEGIN
  suspend;
END^

create or alter procedure SP_VRHF_FUNRURAL (
    PREMP varchar(25000),
    PRREFINI integer,
    PRREFFIM integer,
    PRTIPONF integer = 0)
returns (
    BDCODEMP integer,
    BDTIPONF integer,
    BDREFNF integer,
    BDCODTER integer,
    BDCODAQUIRUR integer,
    BDDATAEMISSAONF date,
    BDCHAVENF integer,
    BDNRONF varchar(15),
    BDSERIENF varchar(5),
    BDVALNF numeric(18,6),
    BDPERCINSS numeric(18,6),
    BDPERCRAT numeric(18,6),
    BDPERCSENAR numeric(18,6),
    BDCNPJPRODRUR DM_CNPJ_CPF,
    BDDESCPRODRUR varchar(100),
    BDINSS numeric(18,6),
    BDRAT numeric(18,6),
    BDSENAR numeric(18,6),
    BDDESCAQUIRUR varchar(500),
    BDTOTALNF numeric(18,6))
as
begin suspend; end^

CREATE OR ALTER PROCEDURE VRHF_SP_GRCSCOLABORADOR(PREMPRESA VARCHAR(9999),
PRCOLABORADOR VARCHAR(9999),
PRSINDICATO INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODSIND INTEGER,
BDCODCNAE INTEGER,
BDSIGLAUF VARCHAR(2),
BDNOMCID VARCHAR(40),
BDSIGLAUFSIND VARCHAR(2),
BDNOMCIDSIND VARCHAR(40),
BDCNPJSIND VARCHAR(18),
BDCEPSIND VARCHAR(9),
BDBAISIND DM_BDBAIRRO,
BDCOMPLSIND DM_BDCOMPENDERECO COLLATE WIN_PTBR,
BDNUMSIND DM_NUMEND,
BDENTSIND VARCHAR(40),
BDDESCSIND VARCHAR(60),
BDLOGRSIND DM_LOGRADOURO,
BDENDSIND DM_BDENDERECO,
BDAGENCIA VARCHAR(5),
BDCEDENTE VARCHAR(20),
BDCNPJ VARCHAR(20),
BDBAI DM_BDBAIRRO,
BDCEP VARCHAR(9),
BDCOMPL DM_BDCOMPENDERECO COLLATE WIN_PTBR,
BDNUM DM_NUMEND,
BDLOGR DM_LOGRADOURO,
BDEND VARCHAR(80),
BDNOM DM_BDNOMEMP,
BDCAPSOC NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_GRCSEMPRESA(PRSINDICATO INTEGER,
PRREFEMP INTEGER,
PRCODEMP VARCHAR(10000),
PRULTIMODIA DATE)
 RETURNS(BDCODCNAE INTEGER,
BDVALORDOC NUMERIC(15,2),
BDSIGLAUF VARCHAR(2),
BDNOMCID VARCHAR(40),
BDBAI DM_BDBAIRRO,
BDCEP VARCHAR(9),
BDCOMPL DM_BDCOMPENDERECO,
BDNUM DM_NUMEND,
BDEND DM_BDENDERECO,
BDCNPJ VARCHAR(18),
BDNOM DM_BDNOMEMP,
BDSIGLAUFSIND VARCHAR(2),
BDNOMCIDSIND VARCHAR(40),
BDCNPJSIND VARCHAR(18),
BDCEPSIND VARCHAR(9),
BDBAISIND DM_BDBAIRRO,
BDCOMPLSIND DM_BDCOMPENDERECO,
BDNUMSIND DM_NUMEND,
BDENTSIND VARCHAR(20),
BDDESCSIND VARCHAR(60),
BDENDSIND DM_BDENDERECO,
BDCAPSOC NUMERIC(15,2),
BDTIPOEMP CHAR,
BDTIPOCOL CHAR,
BDAGENCIA VARCHAR(5),
BDCEDENTE VARCHAR(20),
BDSALBASE NUMERIC(15,2),
BDTOTCOLAPU INTEGER,
BDTOTCOLEMP INTEGER,
BDTOTREMU NUMERIC(15,2),
BDLOGRSIND DM_LOGRADOURO,
BDLOGR DM_LOGRADOURO)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_HIST_ACUMU_GPS(PRWHERECHAVE VARCHAR(3000))
 RETURNS(BDCODEMP INTEGER,
BDCHAVEDARF INTEGER,
BDCODIMP INTEGER,
BDCODPERIODO INTEGER,
BDORDEM INTEGER,
BDREFERENCIA INTEGER,
BDQUOTA INTEGER,
BDVALCAMPO6 NUMERIC(15,6),
BDVALCAMPO9 NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_HIST_ACUMU_GPS2 (
    PRWHERECHAVE varchar(3000))
returns (
    BDCODEMP integer,
    BDCHAVEDARF integer,
    BDCODIMP integer,
    BDCODPERIODO integer,
    BDORDEM integer,
    BDREFERENCIA integer,
    BDQUOTA integer,
    BDVALCAMPO6 numeric(15,6),
    BDVALCAMPO9 numeric(15,6),
    BDCHAVEDARFANT integer)
as
BEGIN SUSPEND; END^


CREATE OR ALTER PROCEDURE VRHF_SP_OUTRASINF_CALC(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDDESCMEN VARCHAR(15),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDNOMAG VARCHAR(40),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDSEXOCOL INTEGER,
BDEMAILCOL VARCHAR(200),
BDDATANASCCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDDEFFISICOCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE,
BDALVARACOL VARCHAR(5),
BDNOMCOL VARCHAR(70))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_OUTRASINF_CALC_ATIVOS(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDDESCMEN VARCHAR(15),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDNOMAG VARCHAR(40),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDSEXOCOL INTEGER,
BDEMAILCOL VARCHAR(200),
BDDATANASCCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDDEFFISICOCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE,
BDALVARACOL VARCHAR(5),
BDNOMCOL VARCHAR(70))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_OUTRASINF_CALC_AUT(PRCODCOL VARCHAR(32700),
PRREF INTEGER,
PREMPRESA INTEGER = 0)
 RETURNS(BDCODCOL INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDDESCMEN VARCHAR(15),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDNOMAG VARCHAR(40),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,2),
BDVALORPREVPRIVNCOL NUMERIC(15,2),
BDVALORPREVPRIV13COL NUMERIC(15,2),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,2),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,2),
BDPERCDESCFPASCOL NUMERIC(15,2),
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,2),
BDHORASSEMANAISCOL NUMERIC(15,2),
BDHORASDIARIASCOL NUMERIC(15,2),
BDPERCINSALUBCOL NUMERIC(15,2),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,2),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,2),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDSEXOCOL INTEGER,
BDEMAILCOL VARCHAR(200),
BDDATANASCCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCPFCOL VARCHAR(18),
BDPISCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDDEFFISICOCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE,
BDALVARACOL VARCHAR(5),
BDNOMCOL DM_BDNOMTER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_QUADROHORARIOS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRDIASEMANA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCIDADE VARCHAR(40),
BDUF VARCHAR(2),
BDBAIEMP DM_BDBAIRRO,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCEPEMP VARCHAR(9),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDPISCOL VARCHAR(14),
BDCODQH INTEGER,
BDDESQH DM_BDDESCQH,
BDDIA INTEGER,
BDHORAENT TIME,
BDHORASAI TIME)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_VALORES_TOT_IRRF (
    PRCODEMP varchar(30000),
   PRREFARQ integer,
    PRTIPOEVT integer,
    PRVERSAO integer,
    PRCPF varchar(30000))
returns (
   BDCODIGO integer,
   BDREFARQ integer,
   BDCODEMP integer,
   BDCODTER integer,
   BDCODCOL integer,
    BDXML blob sub_type 0 segment size 80,
    BDVERSAO integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_RECIBO_FERIAS (
    PREMPRESA varchar(15000),
    PRCOLABORADOR varchar(30000),
    PRORDEMIMP integer,
    PRCLASSE integer,
    PRFUNCAO integer,
    PRCENTROCUSTO integer,
    PRSINDICATO integer,
    PRDATAGOZOINI date,
    PRDATAGOZOFIM date,
    PRPERIODOAQUISITIVO date,
    PRCODIGOFERIAS integer,
    PRTIPOCODVER integer,
    PRREFERENCIA integer,
    PRULTIMODIA date,
    PRCOLETIVAS integer,
    PRAVISO integer = 0,
    PRIDADE21 integer = 2100,
    PRNOVORECIBO smallint = 0)
returns (
    BDTIPOESCALA integer,
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDBAIEMP DM_BDBAIRRO,
    BDNOMCIDEMP varchar(40),
    BDSIGLAUFEMP varchar(2),
    BDCNPJEMP varchar(18),
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCHAVE integer,
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDSIGLAUFCTPS varchar(2),
    BDDESCTFUC varchar(40),
    BDDATAADMCOL date,
    BDINIPERAQUISFE date,
    BDFIMPERAQUISFE date,
    BDCODFE integer,
    BDINIPERGOZOFE date,
    BDFIMPERGOZOFE date,
    BDFALTASFE numeric(15,6),
    BDSALBASEFE numeric(15,6),
    BDSALBASEHEFE numeric(15,6),
    BDQTDABONOFE numeric(18,6),
    BDDATAPAGFE date,
    BDCODVER integer,
    BDTIPOCODVER integer,
    BDORDEMVER integer,
    BDDESCVER varchar(80),
    BDDESCREDVER varchar(20),
    BDREFVFE numeric(15,6),
    BDVALVFE numeric(15,6),
    BDTIPOREFVER integer,
    BDREFPAGABOFE integer,
    BDINISWS date,
    BDFIMSWS date,
    BDVALLIQUIDO numeric(15,6),
    BDCALCA13FE varchar(5),
    BDSALINI numeric(15,6),
    BDDIASLICFE numeric(18,6),
    BDDATAAVISO date,
    BDCLASSVER varchar(20),
    BDREFAUXVER numeric(15,6),
    BDCOLETIVAS varchar(5),
    BDDEPIR integer,
    BDDIASFERFE numeric(18,6),
    BDLOGOEMP blob sub_type 0 segment size 32720,
    BDREFHOREMP DM_BOOLEAN,
    BDCPFCOL varchar(14),
    BDDATARELABONO date,
    BDORDEM integer,
    BDFERIADOSFE integer,
    BDREFERENCIA integer,
    BDDTAINICIALFOLGA date,
    BDCODQH integer,
    BDCODPQUA integer)
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_REL_DECLARA_RENDIMENTOS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDTOTALRENDIMENTOS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDVAL13 NUMERIC(15,6),
BDVALPENALI NUMERIC(15,6),
BDVALIND NUMERIC(15,6),
BDVALDIR NUMERIC(15,6),
BDVALDME NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DECLARACAO_DOMESTICO (
PRCODEMP VARCHAR(300),
PRCODCOL VARCHAR(300),
PRANOBASE INTEGER,
PRTOMADOR INTEGER,
PRCODSIND INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRORDEM VARCHAR(50),
PRDATAEMISSAO VARCHAR(10),
PRSITUACAO INTEGER)
  RETURNS (
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADM DATE,
BDDATARESCISAO DATE,
BDPIS VARCHAR(14),
BDCPF VARCHAR(14),
BDCOMPETENCIA INTEGER,
BDSALMIN NUMERIC(15,6),
BDBINSSN NUMERIC(15,6),
BDBINSSFE NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDREMUNERACAO NUMERIC(18,6),
BDINSSPATRONAL NUMERIC(15,6),
BDDIFERENCAINSS NUMERIC(15,6),
BDTOTALCONTRPATRONAL NUMERIC(15,6),
BDPARCELANAODEDUTIVEL NUMERIC(15,6),
BDINF VARCHAR(20),
BDORDEM VARCHAR(50),
BDDATAEMISSAO VARCHAR(10),
BDANOBASE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_REL_LIQUIDO_FOLHA(PRCODEMP VARCHAR(25000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRULTDIAMES DATE,
PRTABELA VARCHAR(300),
PRDATANULL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDCODAGBAN VARCHAR(5),
BDCODAGBANDV VARCHAR(2),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDDATAADMCOL DATE,
BDDESCTFUC VARCHAR(40),
BDREF INTEGER,
SALBASE NUMERIC(15,6),
PROVE NUMERIC(15,6),
DESCO NUMERIC(15,6),
LIQ NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_REL_PREVIA_RESC(PREMPRESA VARCHAR(10000),
PRCOLABORADOR VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDBAIEMP DM_BDBAIRRO,
BDNOMCID VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCEPEMP VARCHAR(9),
BDCODCNAE INTEGER,
BDPISCOL VARCHAR(14),
BDLOGRCOL VARCHAR(15),
BDENDCOL VARCHAR(60),
BDNUMCOL DM_NUMEND,
BDBAICOL VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDNOMCIDCOL VARCHAR(40),
BDSIGLAUFCOL VARCHAR(2),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDATANASCCOL DATE,
BDNOMMAECOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCATEGORIACOL INTEGER,
BDDATAAVPREVIO DATE,
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDESCPRES VARCHAR(110),
BDCODSAQUE INTEGER,
BDDATARESCISAO DATE,
BDDATAPAGRESCISAO DATE,
BDCAMPO29 NUMERIC(15,2),
BDCAMPO30 NUMERIC(15,2),
BDCAMPO30REF INTEGER,
BDCAMPO31 NUMERIC(15,2),
BDCAMPO31REF INTEGER,
BDCAMPO32 NUMERIC(15,2),
BDCAMPO32REF INTEGER,
BDCAMPO33 NUMERIC(15,2),
BDCAMPO33REF INTEGER,
BDCAMPO34 NUMERIC(15,2),
BDCAMPO34REF INTEGER,
BDCAMPO35 NUMERIC(15,2),
BDCAMPO35REF INTEGER,
BDCAMPO36 NUMERIC(15,2),
BDCAMPO36REF INTEGER,
BDCAMPO37 NUMERIC(15,2),
BDCAMPO38 NUMERIC(15,2),
BDCAMPO39 NUMERIC(15,2),
BDCAMPO40 NUMERIC(15,2),
BDCAMPO40REF INTEGER,
BDCAMPO41 NUMERIC(15,2),
BDCAMPO42 NUMERIC(15,2),
BDCAMPO43 NUMERIC(15,2),
BDCAMPO44 NUMERIC(15,2),
BDCAMPO45 NUMERIC(15,2),
BDCAMPO46BRUTO NUMERIC(15,2),
BDCAMPO47 NUMERIC(15,2),
BDCAMPO48 NUMERIC(15,2),
BDCAMPO49 NUMERIC(15,2),
BDCAMPO50 NUMERIC(15,2),
BDCAMPO51 NUMERIC(15,2),
BDCAMPO52 NUMERIC(15,2),
BDCAMPO53 NUMERIC(15,2),
BDCAMPO54TOTDED NUMERIC(15,2),
BDCAMPO55LIQREC NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_REL_PREVIA_RESC2(PREMPRESA VARCHAR(10000),
PRCOLABORADOR VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRTIPOFILTRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDBAIEMP DM_BDBAIRRO,
BDNOMCID VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCEPEMP VARCHAR(9),
BDCODCNAE INTEGER,
BDPISCOL VARCHAR(14),
BDLOGRCOL VARCHAR(15),
BDENDCOL VARCHAR(60),
BDNUMCOL DM_NUMEND,
BDBAICOL VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDNOMCIDCOL VARCHAR(40),
BDSIGLAUFCOL VARCHAR(2),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDATANASCCOL DATE,
BDNOMMAECOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCATEGORIACOL INTEGER,
BDDATAAVPREVIO DATE,
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDESCPRES VARCHAR(110),
BDCODSAQUE INTEGER,
BDDATARESCISAO DATE,
BDDATAPAGRESCISAO DATE,
BDREF INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDORDEMVER INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_REL_RECIBO_RESCISAO (
    PREMPRESA varchar(10000),
    PRCOLABORADOR varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRFUNCAO integer,
    PRSINDICATO integer,
    PRCLASSE integer,
    PRTIPOFOLHA integer,
    PRDATAINI integer,
    PRDATAFIM integer)
returns (
    BDMAIORREMUNERACAOANT numeric(18,6),
    BDCODTIPOCONTRATO integer,
    BDDESCTIPOCONTRATO varchar(150),
    BDCODSINTRAB integer,
    BDCODCEDENTETRAB varchar(20),
    BDCNPJSINTRAB varchar(18),
    BDDESCSINTRAB varchar(60),
    BDPERTRCTRESC numeric(15,6),
    BDPERFGTSRESC numeric(15,6),
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(18),
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL varchar(14),
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDBAIEMP DM_BDBAIRRO,
    BDNOMCID varchar(40),
    BDSIGLAUFEMP varchar(2),
    BDCEPEMP varchar(9),
    BDCODCNAE integer,
    BDPISCOL varchar(14),
    BDLOGRCOL varchar(15),
    BDENDCOL varchar(60),
    BDNUMCOL DM_NUMEND,
    BDBAICOL varchar(50),
    BDCEPCOL varchar(9),
    BDNOMCIDCOL varchar(40),
    BDSIGLAUFCOL varchar(2),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL DM_DIGSERIECTPS,
    BDDATANASCCOL date,
    BDNOMMAECOL varchar(70),
    BDDATAADMCOL date,
    BDCATEGORIACOL integer,
    BDDATAAVPREVIO date,
    BDCHAVEINDENTIFICACAO varchar(49),
    BDDESCPRES varchar(110),
    BDCODSAQUE integer,
    BDDATARESCISAO date,
    BDDATAPAGRESCISAO date,
    BDVINCEMPCOL integer,
    BDSIGLAUFCTPS varchar(2),
    BDSIGLAHNET varchar(3),
    BDDESCHNET varchar(200),
    BDDESCCATEGORIA varchar(300),
    BDSALBASE numeric(18,6),
    BDDATAOPCAOFGTS date,
    BDTIPOCOL integer,
    BDCNPJTOM varchar(18),
    BDREFRESCISAO integer,
    BDECONSIGNADO DM_BOOLEAN,
    BDREFRESCISAOPOST integer)
as
BEGIN
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE VRHF_SP_REL_RECIBO_RESCISAO2(PREMPRESA VARCHAR(10000),
PRCOLABORADOR VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRTIPOFILTRO INTEGER,
PRTIPOFOLHA INTEGER,
PRDTPGTO INTEGER,
PRDTPGTOFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDBAIEMP DM_BDBAIRRO,
BDNOMCID VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCEPEMP VARCHAR(9),
BDCODCNAE INTEGER,
BDPISCOL VARCHAR(14),
BDLOGRCOL VARCHAR(15),
BDENDCOL VARCHAR(60),
BDNUMCOL DM_NUMEND,
BDBAICOL VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDNOMCIDCOL VARCHAR(40),
BDSIGLAUFCOL VARCHAR(2),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL DM_DIGSERIECTPS,
BDDATANASCCOL DATE,
BDNOMMAECOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCATEGORIACOL INTEGER,
BDDATAAVPREVIO DATE,
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDREFRESCISAO INTEGER,
BDDESCPRES VARCHAR(110),
BDCODSAQUE INTEGER,
BDDATARESCISAO DATE,
BDDATAPAGRESCISAO DATE,
BDREF INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(18,6),
BDREFAUXV NUMERIC(18,6),
BDHEVER NUMERIC(18,6),
BDPROVENTO NUMERIC(18,6),
BDDESCONTO NUMERIC(18,6),
BDORDEMVER INTEGER,
BDCLAVER VARCHAR(20),
BDPERCINSALUBCOL NUMERIC(18,6),
BDPERCPERICULCOL NUMERIC(18,6),
BDPERCNOTURNOCOL NUMERIC(18,6),
BDHORASDIARIASCOL NUMERIC(18,6),
BDSIGLAUFCTPS VARCHAR(2),
BDTIPOREFVER INTEGER,
BDREFHOREMP VARCHAR(5),
BDCLAVERAUX VARCHAR(20),
BDDESCVERAUX VARCHAR(70),
BDPROVENTOOUTROS NUMERIC(18,6),
BDDESCONTOOUTROS NUMERIC(18,6),
BDTIPOCOL INTEGER,
BDCNPJTOM VARCHAR(18))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_RETORNAEMPRESA_GPS(PREMP INTEGER,
PRREF INTEGER)
 RETURNS(BDSIMPLESGPS INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_SALARIOS_CONTRIB(PREMPRESA VARCHAR(15000),
PRCOLABORADOR VARCHAR(30000),
PRORDEMIMP INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRCENTROCUSTO INTEGER,
PRSINDICATO INTEGER,
PRBANCO INTEGER,
PRAGENCIA INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDNOMCIDEMP VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDSIGLAUFCTPS VARCHAR(2),
BDDATARESCISAO DATE,
BDDATAINSS DATE,
BDREFINSS INTEGER,
BDBASEINSS NUMERIC(15,6),
BDVALORINSS NUMERIC(15,2),
BDCODEMPAUX INTEGER,
BDCODCOLAUX INTEGER,
BDDATAINSSAUX DATE,
BDVALORINSSAUX NUMERIC(15,6),
BDBASEINSSAUX NUMERIC(15,6),
BDREFINSSAUX INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TCALC_AUTONOMO(PRCODEMP VARCHAR(32700),
PRCODTER VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER)
 RETURNS(BDGRUPOCLA INTEGER,
BDCODTER INTEGER,
BDCODEMP INTEGER,
BDCODSERV INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDANOMES INTEGER,
BDBASEIR NUMERIC(15,6),
BDFAIXAIR NUMERIC(15,6),
BDVALORIR NUMERIC(15,6),
BDBASEINSS NUMERIC(15,6),
BDFAIXAINSS NUMERIC(15,6),
BDVALORINSS NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDVALORDEP NUMERIC(15,6),
BDVALOUTENTIDADES NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TCOMPENSACAOGPS(PRCODIMP INTEGER,
PRCODEMP INTEGER,
PRTIPOGPS INTEGER,
PRTIPOEMISSAO INTEGER,
PRCODTPCC INTEGER,
PRRETORNACOMPENSACAO INTEGER)
 RETURNS(BDTIPOREG INTEGER,
BDCHAVE INTEGER,
BDVALOR NUMERIC(15,6),
BDPERC NUMERIC(15,6),
BDMESINI INTEGER,
BDMESFIM INTEGER,
BDVALORREAJUSTE NUMERIC(15,6),
BDVALORSEMREAJUSTE NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_MEDIAS (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRREFINI INTEGER,
    PRREFFIM INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODVER INTEGER,
    BDREF INTEGER,
    BDTIPO INTEGER,
    BDCC INTEGER,
    BDVREF NUMERIC(18,6),
    BDVREFAUX NUMERIC(18,6),
    BDVVAL NUMERIC(18,6))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_HISTORICO_FAP (
    PREMP VARCHAR(32700))
RETURNS (
    BDCODEMP INTEGER,
    BDREFEMP INTEGER,
    BDFAPANTERIOR NUMERIC(18,6),
    BDFAPATUAL NUMERIC(18,6))
AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WREFEMP INTEGER;
DECLARE VARIABLE WFAP NUMERIC(18,6);
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WFAPATU NUMERIC(18,6);
BEGIN SUSPEND; END
^

create or alter procedure SP_VRHF_AGRUPAR_QH
returns (
    BDCODQHH integer,
    BDDESCRICAO varchar(300))
as
declare variable WSQL varchar(300);
declare variable WSQL2 varchar(300);
declare variable WDESCRICAO varchar(300);
declare variable WCODQHH integer;
declare variable WCODQHHS integer;
declare variable WQHHSSAI varchar(50);
declare variable WQHHSENT varchar(50);
declare variable WCODQHHSMAX integer;
declare variable WULTIMOCODQHH integer;
declare variable WHORASTRABALHOFLEXIVEL varchar(50);
declare variable WHORAINTERVALOFLEXIVEL varchar(50);
BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_TFOLHA_NORMAL (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(2788) = null)
returns (
    BDGRUPOCLA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDREFFN integer,
    BDDATABAIXAFN date,
    BDBFGTSFN numeric(15,6),
    BDFGTSFN numeric(15,6),
    BDFGTSCSFN numeric(15,6),
    BDBFGTS13FN numeric(15,6),
    BDFGTS13FN numeric(15,6),
    BDFGTS13CSFN numeric(15,6),
    BDMAIORREMFN numeric(15,6),
    BDBINSSFN numeric(15,6),
    BDALIQINSSFN numeric(15,6),
    BDINSSFN numeric(15,6),
    BDBIRRFFN numeric(15,6),
    BDALIQIRRFFN numeric(15,6),
    BDIRRFFN numeric(15,6),
    BDBINSS13FN numeric(15,6),
    BDALIQINSS13FN numeric(15,6),
    BDINSS13FN numeric(15,6),
    BDBIRRF13FN numeric(15,6),
    BDALIQIRRF13FN numeric(15,6),
    BDIRRF13FN numeric(15,6),
    BDBSALFAMFN numeric(15,6),
    BDSALFAMFN numeric(15,6),
    BDBRAISFN numeric(15,6),
    BDSALBASEFN numeric(15,6),
    BDDEPFN numeric(15,6),
    BDBASEPISFN numeric(15,6),
    BDBASEPISFEFN numeric(15,6),
    BDBASEPIS13FN numeric(15,6),
    BDBSALMATEMPFN numeric(15,6),
    BDSALMATEMPFN numeric(15,6),
    BDBRATAPOFN numeric(15,6),
    BDBRATAPOFEFN numeric(15,6),
    BDBRATAPO13FN numeric(15,6),
    BDBINSSFEFOLFN numeric(15,6),
    BDINSSFEFOLFN numeric(15,6),
    BDALIQINSSFEFOLFN numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDCREDITOFN numeric(15,6),
    BDDEBITOFN numeric(15,6),
    BDBFGTSFEFN numeric(15,6),
    BDFGTSFEFN numeric(15,6),
    BDBMATEMPFNFN numeric(15,6),
    BDBMATEMP13FN numeric(15,6),
    BDVMATEMPFNFN numeric(15,6),
    BDVMATEMP13FN numeric(15,6),
    BDLIQUIDOFN numeric(18,6),
    BDDATAPGTO date,
    BDBINSSAPFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDCODCONTTI integer,
    BDBASEFGTSMESESOCIAL numeric(18,6),
    BDBASEFGTS13ESOCIAL numeric(18,6),
    BDVALORFGTSMESESOCIAL numeric(18,6),
    BDVALORFGTS13ESOCIAL numeric(18,6),
    BDVALORFGTSINDESOCIAL numeric(18,6),
    BDBASEFGTSINDESOCIAL numeric(18,6))
as
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_TFOLHA_INT (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(772) = null)
returns (
    BDGRUPOCLA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODCONTTI integer,
    BDORDEM integer,
    BDREFFN integer,
    BDDATABAIXAFN date,
    BDBFGTSFN numeric(15,6),
    BDFGTSFN numeric(15,6),
    BDFGTSCSFN numeric(15,6),
    BDBFGTS13FN numeric(15,6),
    BDFGTS13FN numeric(15,6),
    BDFGTS13CSFN numeric(15,6),
    BDMAIORREMFN numeric(15,6),
    BDBINSSFN numeric(15,6),
    BDALIQINSSFN numeric(15,6),
    BDINSSFN numeric(15,6),
    BDBIRRFFN numeric(15,6),
    BDALIQIRRFFN numeric(15,6),
    BDIRRFFN numeric(15,6),
    BDBINSS13FN numeric(15,6),
    BDALIQINSS13FN numeric(15,6),
    BDINSS13FN numeric(15,6),
    BDBIRRF13FN numeric(15,6),
    BDALIQIRRF13FN numeric(15,6),
    BDIRRF13FN numeric(15,6),
    BDBSALFAMFN numeric(15,6),
    BDSALFAMFN numeric(15,6),
    BDBRAISFN numeric(15,6),
    BDSALBASEFN numeric(15,6),
    BDDEPFN numeric(15,6),
    BDBASEPISFN numeric(15,6),
    BDBASEPISFEFN numeric(15,6),
    BDBASEPIS13FN numeric(15,6),
    BDBSALMATEMPFN numeric(15,6),
    BDSALMATEMPFN numeric(15,6),
    BDBRATAPOFN numeric(15,6),
    BDBRATAPOFEFN numeric(15,6),
    BDBRATAPO13FN numeric(15,6),
    BDBINSSFEFOLFN numeric(15,6),
    BDINSSFEFOLFN numeric(15,6),
    BDALIQINSSFEFOLFN numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDCREDITOFN numeric(15,6),
    BDDEBITOFN numeric(15,6),
    BDBFGTSFEFN numeric(15,6),
    BDFGTSFEFN numeric(15,6),
    BDBMATEMPFNFN numeric(15,6),
    BDBMATEMP13FN numeric(15,6),
    BDVMATEMPFNFN numeric(15,6),
    BDVMATEMP13FN numeric(15,6),
    BDLIQUIDOFN numeric(18,6),
    BDDATAPGTO date,
    BDBINSSAPFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSS13APFN numeric(18,6))
as
BEGIN
  SUSPEND;
END^

create or alter procedure VRHF_SP_TFOLHA_NORMAL (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(2788) = null)
returns (
    BDGRUPOCLA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDREFFN integer,
    BDDATABAIXAFN date,
    BDBFGTSFN numeric(15,6),
    BDFGTSFN numeric(15,6),
    BDFGTSCSFN numeric(15,6),
    BDBFGTS13FN numeric(15,6),
    BDFGTS13FN numeric(15,6),
    BDFGTS13CSFN numeric(15,6),
    BDMAIORREMFN numeric(15,6),
    BDBINSSFN numeric(15,6),
    BDALIQINSSFN numeric(15,6),
    BDINSSFN numeric(15,6),
    BDBIRRFFN numeric(15,6),
    BDALIQIRRFFN numeric(15,6),
    BDIRRFFN numeric(15,6),
    BDBINSS13FN numeric(15,6),
    BDALIQINSS13FN numeric(15,6),
    BDINSS13FN numeric(15,6),
    BDBIRRF13FN numeric(15,6),
    BDALIQIRRF13FN numeric(15,6),
    BDIRRF13FN numeric(15,6),
    BDBSALFAMFN numeric(15,6),
    BDSALFAMFN numeric(15,6),
    BDBRAISFN numeric(15,6),
    BDSALBASEFN numeric(15,6),
    BDDEPFN numeric(15,6),
    BDBASEPISFN numeric(15,6),
    BDBASEPISFEFN numeric(15,6),
    BDBASEPIS13FN numeric(15,6),
    BDBSALMATEMPFN numeric(15,6),
    BDSALMATEMPFN numeric(15,6),
    BDBRATAPOFN numeric(15,6),
    BDBRATAPOFEFN numeric(15,6),
    BDBRATAPO13FN numeric(15,6),
    BDBINSSFEFOLFN numeric(15,6),
    BDINSSFEFOLFN numeric(15,6),
    BDALIQINSSFEFOLFN numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDCREDITOFN numeric(15,6),
    BDDEBITOFN numeric(15,6),
    BDBFGTSFEFN numeric(15,6),
    BDFGTSFEFN numeric(15,6),
    BDBMATEMPFNFN numeric(15,6),
    BDBMATEMP13FN numeric(15,6),
    BDVMATEMPFNFN numeric(15,6),
    BDVMATEMP13FN numeric(15,6),
    BDLIQUIDOFN numeric(18,6),
    BDDATAPGTO date,
    BDBINSSAPFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDCODCONTTI integer,
    BDBASEFGTSMESESOCIAL numeric(18,6),
    BDBASEFGTS13ESOCIAL numeric(18,6),
    BDVALORFGTSMESESOCIAL numeric(18,6),
    BDVALORFGTS13ESOCIAL numeric(18,6),
    BDVALORFGTSINDESOCIAL numeric(18,6),
    BDBASEFGTSINDESOCIAL numeric(18,6))
as
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_TFOLHACOMP (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(28000),
    PRREFINICOMP integer,
    PRREFFIMCOMP integer,
    PRREFINIPAG integer,
    PRREFFIMPAG integer,
    PRAGRUPATOMADOR integer,
    PRTIPOFC integer = 0,
    PRSEPARCALC integer = 0,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(772) = null,
    PRINSSPATRONAL smallint = 0,
    PRCOMPLEESOCIAL integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDREFFN integer,
    BDREFFC integer,
    BDREFCOMP integer,
    BDDATAPAGFC date,
    BDDATABAIXAFC date,
    BDBFGTSFC numeric(15,6),
    BDFGTSFC numeric(15,6),
    BDFGTSCSFC numeric(15,6),
    BDBFGTS13FC numeric(15,6),
    BDFGTS13FC numeric(15,6),
    BDFGTS13CSFC numeric(15,6),
    BDMAIORREMFC numeric(15,6),
    BDBINSSFC numeric(15,6),
    BDALIQINSSFC numeric(15,6),
    BDINSSFC numeric(15,6),
    BDBIRRFFC numeric(15,6),
    BDALIQIRRFFC numeric(15,6),
    BDIRRFFC numeric(15,6),
    BDBINSS13FC numeric(15,6),
    BDALIQINSS13FC numeric(15,6),
    BDINSS13FC numeric(15,6),
    BDBIRRF13FC numeric(15,6),
    BDALIQIRRF13FC numeric(15,6),
    BDIRRF13FC numeric(15,6),
    BDBSALFAMFC numeric(15,6),
    BDSALFAMFC numeric(15,6),
    BDBRAISFC numeric(15,6),
    BDSALBASEFC numeric(15,6),
    BDDEPFC numeric(15,6),
    BDBASEPISFC numeric(15,6),
    BDBASEPISFEFC numeric(15,6),
    BDBASEPIS13FC numeric(15,6),
    BDBSALMATEMPFC numeric(15,6),
    BDSALMATEMPFC numeric(15,6),
    BDBRATAPOFC numeric(15,6),
    BDBRATAPOFEFC numeric(15,6),
    BDBRATAPO13FC numeric(15,6),
    BDBINSSFEFOLFC numeric(15,6),
    BDINSSFEFOLFC numeric(15,6),
    BDALIQINSSFEFOLFC numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDBFGTSFEFC numeric(15,6),
    BDFGTSFEFC numeric(15,6),
    BDCODTIPOFC integer,
    BDBINSSMVFC numeric(18,6),
    BDBINSSMV13FC numeric(18,6),
    BDINSSMVFC numeric(18,6),
    BDINSSMV13FC numeric(18,6),
    BDBINSSAPFC numeric(18,6),
    BDBINSS13APFC numeric(18,6),
    BDINSSAPFC numeric(18,6),
    BDINSS13APFC numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDINSSFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDLIQUIDOFC numeric(18,6),
    BDDATAGRRF date,
    BDCODCONTTI integer,
    BDREFVINCFN integer,
    BDSALFAM13GPS numeric(18,6),
    BDSALFAMFNGPS numeric(18,6),
    BDDTACCONV date,
    BDDTPGTOBRICONV date,
    BDCODACCONV integer)
as
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_TIPO_TOMADOR_GPS (
    PRCENCUS integer,
    PRPLANOCUS integer,
    PRREF integer,
    PR13 smallint = 0)
returns (
    BDCODCENCUS integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCTALON varchar(40),
    BDTIPCTA smallint,
    BDNOMCTA varchar(40),
    BDAPECTA varchar(20),
    BDFILTROGER varchar(20),
    BDCLANOM varchar(80),
    BDTIPO integer,
    BDCNPJTOM varchar(18),
    BDTIPOTOM integer,
    BDTIPOFERTOM integer,
    BDSOMSALFERTOM varchar(5),
    BDTIPO13TOM integer,
    BDSOMSAL13TOM varchar(5),
    BDNOMETOM varchar(70),
    BDAPELIDO varchar(20),
    BDNOME varchar(40))
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TNFCOOP(PRCODEMP VARCHAR(32000),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRPUXAFILIAIS INTEGER,
PRCODIMP INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDREFNF INTEGER,
BDNOTAFISCAL VARCHAR(15),
BDDATAEMINF DATE,
BDVALLIQNF NUMERIC(15,6),
BDVALNF NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TODAS_GPS(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(22000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRAPENASGPS INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER)
 RETURNS(BDTIPOREG INTEGER,
BDCODEMP INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDVALFUNEMP NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDVALPROEMP NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDVALAUTEMP NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDVALORFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALORRAT NUMERIC(15,6),
BDVALORBRUTO NUMERIC(15,6),
BDVALORLIQUIDO NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6),
BDCHAVE INTEGER,
BDVALCOMPENSADO NUMERIC(15,6),
BDVALACOMPENSAR NUMERIC(15,6),
BDVALORACUMULADO NUMERIC(15,6),
BDVALORACUMULADOUSADO NUMERIC(15,6),
BDVALORACUMUTERCEIRO NUMERIC(15,6),
BDVALORACUTERCEIROSUSADO NUMERIC(15,6),
BDCODEMPANT INTEGER,
BDCODIMPANT INTEGER,
BDCODPERIODOANT INTEGER,
BDORDEMANT INTEGER,
BDREFERENCIAANT INTEGER,
BDQUOTAANT INTEGER,
BDDESCACUMDET VARCHAR(3000),
BDDESCACU VARCHAR(3000),
BDVALORCAMPO6 NUMERIC(15,6),
BDVALORNOTAS NUMERIC(15,6),
BDTOTVALORACUMULADO NUMERIC(15,6),
BDTOTVALORACUMULADOTERC NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDTOTCOMPENSACAO NUMERIC(15,6),
BDDESCNOTAS NUMERIC(15,6),
BDTOTDESCCOMP NUMERIC(15,6),
BDDESCSALFAM NUMERIC(15,6),
BDDESCDEDGPS NUMERIC(15,6),
BDVALOUTENTIDADES NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCHAVEDARF INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TOMADOR(PRCENCUS INTEGER,
PRPLANOCUS INTEGER)
 RETURNS(BDCODCENCUS INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCTALON VARCHAR(40),
BDTIPCTA SMALLINT,
BDNOMCTA VARCHAR(40),
BDAPECTA VARCHAR(20),
BDFILTROGER VARCHAR(20),
BDCLANOM VARCHAR(80),
BDTIPO INTEGER,
BDCNPJTOM VARCHAR(18),
BDTIPOTOM INTEGER,
BDTIPOFERTOM INTEGER,
BDSOMSALFERTOM VARCHAR(5),
BDTIPO13TOM INTEGER,
BDSOMSAL13TOM VARCHAR(5),
BDNOMETOM VARCHAR(70),
BDAPELIDO VARCHAR(20),
BDNOME VARCHAR(40),
BDTIPODOCTOM INTEGER,
BDCODLOT integer,
BDCODLOTACAO varchar(30),
BDCODESTAB varchar(30))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TOTAL_COL_ATIVOS(PRCODEMP INTEGER,
PRREF INTEGER,
PRDATAADMISSAO DATE)
 RETURNS(TTATIVOS INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TOTPRO_TOTDESC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPADOR INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODTPCC INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDLIQUIDO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TOTPRO_TOTDESC_ADSAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDLIQUIDO NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TPREPFB_CC RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDDATAENTRADA DATE,
BDHORAENTRADA TIME,
BDTIPO INTEGER,
BDQTDTEMPO NUMERIC(15,6),
BDCTALON VARCHAR(40),
BDTIPCTA SMALLINT,
BDNOMCTA VARCHAR(100),
BDAPECTA VARCHAR(20),
BDFILTROGER VARCHAR(20),
BDCLANOM VARCHAR(140))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_TPREPFN_CC_REF (
    PRREF integer,
    PREMPRESA varchar(32700),
    PRCOLABORADOR varchar(32700),
    PRTEMPO integer,
    PRDATAINI date,
    PRDATAFIM date,
    PRFERIAS smallint = 0,
    PRCALCULO DM_BOOLEAN = 'TRUE')
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDDATAENTRADA date,
    BDHORAENTRADA time,
    BDTIPO integer,
    BDQTDTEMPO numeric(15,6),
    BDCTALON varchar(40),
    BDTIPCTA smallint,
    BDNOMCTA varchar(100),
    BDAPECTA varchar(20),
    BDFILTROGER varchar(20),
    BDCLANOM varchar(140),
    BDTEMPO integer,
    BDTEMPOFN integer,
    BDPERCFN numeric(15,6),
    BDLANCHORAS numeric(15,2),
    BDTOTHORAS numeric(15,2),
    BDTOTDSR numeric(15,2),
    BDLANCDSR numeric(15,2))
as
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_TPREPFN_REF (
    PRREFERENCIA integer,
    PREMPRESA varchar(32700),
    PRCOLABORADOR varchar(32700),
    PRDATAINI date,
    PRDATAFIM date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDDATAENTRADA date,
    BDHORAENTRADA time,
    BDTIPO integer,
    BDQTDTEMPO numeric(15,6),
    BDPERCFN numeric(15,6),
    BDLANCHORAS numeric(15,2),
    BDTOTHORAS numeric(15,2),
    BDTOTDSR numeric(15,2),
    BDLANCDSR numeric(15,2))
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TTEMPOTRAB(PRCODEMP INTEGER,
PRCODFUN INTEGER,
PRDATAENT DATE,
PRHORAENT TIME,
PRDATASAI DATE,
PRHORASAI TIME)
 RETURNS(BDTEMPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_TVERBAFC (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(25000),
    PRREFINICOMP integer,
    PRREFFIMCOMP integer,
    PRREFINIPAG integer,
    PRREFFIMPAG integer,
    PRAGRUPATOMADOR integer,
    PRSEPARARCALC integer = 0,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(772) = null,
    PRCOMPLEESOCIAL integer = 0)
returns (
    BDCODVER integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFCOMP integer,
    BDREFVFC numeric(15,6),
    BDREFAUXVFC numeric(15,6),
    BDVALVFC numeric(15,6),
    BDIGNREFVFC varchar(5),
    BDIGNREFAVFC varchar(5),
    BDIGNVALVFC varchar(5),
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDREFFC integer,
    BDCODCONTTI integer)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_AGRUPA_VERBAS_FT (
    PRAGRUPADOR INTEGER,
    PRFILTRO VARCHAR(32700) = NULL,
    PRFILTROCC VARCHAR(20000) = NULL)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREFTOMADOR INTEGER,
    BDORDEM INTEGER,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDCODVER INTEGER,
    BDREFVFT_SUM NUMERIC(15,6),
    BDREFVFT_MAX NUMERIC(15,6),
    BDREFAUXVFT NUMERIC(15,6),
    BDVALVFT NUMERIC(15,6),
    BDIGNREFVFT DM_BOOLEAN,
    BDIGNREFAVFT DM_BOOLEAN,
    BDIGNVALVFT DM_BOOLEAN,
    BDTIPOREFVER INTEGER)
AS
BEGIN
   SUSPEND;
END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TVERBAFN(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRCODTPCC VARCHAR(20000) = NULL,
PRPUXAFILIAIS INTEGER = 0,
PRFILIAIS VARCHAR(2788) = NULL)
 RETURNS(BDCODVER INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDREFVFN NUMERIC(15,6),
BDREFAUXVFN NUMERIC(15,6),
BDVALVFN NUMERIC(15,6),
BDIGNREFVFN VARCHAR(5),
BDIGNREFAVFN VARCHAR(5),
BDIGNVALVFN VARCHAR(5),
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCALCTOMADOR VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_TVERBAFN_PREV_RESC(PRCODEMP VARCHAR(32700),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER)
 RETURNS(BDCODVER INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFNPR INTEGER,
BDREFVFNPR NUMERIC(15,6),
BDREFAUXVFNPR NUMERIC(15,6),
BDVALVFNPR NUMERIC(15,6),
BDIGNREFVFNPR VARCHAR(5),
BDIGNVALVFNPR VARCHAR(5),
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCALCTOMADOR VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_UNION_VERBAS_SIM_NAO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRCODSINTRAB VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRLOCAL VARCHAR(100),
PRSIMNAO VARCHAR(100))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODSIND INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(40),
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF BLOB,
BDFORMVAL BLOB,
BDDESCCOND BLOB,
BDLOCAL VARCHAR(10),
BDSIMNAO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_UNION_VERBAS_SIM_NAO_2(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRCODSINTRAB VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRLOCAL VARCHAR(100),
PRSIMNAO VARCHAR(100))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODSIND INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(40),
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000),
BDDESCCOND BLOB,
BDLOCAL VARCHAR(10),
BDSIMNAO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_UNIONCALCDETALHE RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDREFCOMP INTEGER,
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDETALHE VARCHAR(1000),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDTIPODET INTEGER,
BDORDEMDETALHE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_VALORES_CONTRIB_SINDICA(PRTIPOFOLHA INTEGER,
PREMPRESA VARCHAR(30000),
PRCODCOL VARCHAR(30000),
PRREFERENCIA INTEGER,
PRSIND INTEGER)
 RETURNS(BDTIPOFOLHA INTEGER,
BDREF INTEGER,
BDSIND INTEGER,
BDCODEMP INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDGRUPOCLA VARCHAR(100),
BDVALOR NUMERIC(15,6),
BDCODCOL INTEGER,
BDSALBASE NUMERIC(15,6),
BDQTD INTEGER,
BDCODVER INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_VERBAS_FN_FC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRCLASSVERBAS VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF INTEGER,
BDCODVER INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDCLAVER VARCHAR(20),
BDIGNREFAV VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_VERBAS (
    PRANOMES INTEGER,
    PRNIVELCLASSIFICACAO SMALLINT = 0)
RETURNS (
    BDCODVER INTEGER NOT NULL,
    BDREFVER INTEGER NOT NULL,
    BDTIPOCODVER INTEGER,
    BDINSSVER INTEGER,
    BDFGTSVER INTEGER,
    BDIRVER INTEGER,
    BDTIPOREFVER INTEGER,
    BDBASESFVER INTEGER,
    BDPISVER VARCHAR(5),
    BDBASEHEVER VARCHAR(5),
    BDBASEMAIORVER VARCHAR(5),
    BDRAISVER VARCHAR(5),
    BDBASEGPSVER VARCHAR(5),
    BDMENORESVER VARCHAR(5),
    BDPROPVER VARCHAR(5),
    BDBASEVTVER VARCHAR(5),
    BDREEMBGPSVER VARCHAR(5),
    BDHEVER NUMERIC(15,6),
    BDGRAVAFICHAHNVER VARCHAR(5),
    BDCCPRINCIPALVER VARCHAR(5),
    BDFORMREFVER VARCHAR(5000),
    BDFORMVALVER VARCHAR(5000),
    BDBASEDSRHEVER VARCHAR(5),
    BDBASEDSRRVVER VARCHAR(5),
    BDFORMREFAUXVER VARCHAR(5000),
    BDDEDFORMREFAUXVER VARCHAR(5),
    BDDEDFORMREFVER VARCHAR(5),
    BDDEDFORMVALVER VARCHAR(5),
    BDRENDISENTOIRVER VARCHAR(5),
    BDFORMINTVER VARCHAR(5000),
    BDSIMPLESNACIONAL VARCHAR(5),
    BDBASE13HN VARCHAR(5),
    BDBASEFERHN VARCHAR(5),
    BDBASEAVHN VARCHAR(5),
    BDPAGAESTOUROVER VARCHAR(5),
    BDGARANTIAMINVER VARCHAR(5),
    BDINDRESC VARCHAR(5),
    BDNAOCONVHORASVER DM_BOOLEAN,
    BDAPEVER VARCHAR(20) NOT NULL,
    BDDESCVER VARCHAR(40),
    BDDESCREDVER VARCHAR(20),
    BDCLAVER VARCHAR(20),
    BDREADONLY VARCHAR(5),
    BDORDEMVER INTEGER,
    BDINATIVAVER VARCHAR(5),
    BDSITVER INTEGER,
    BDBASESALRAIS VARCHAR(5),
    BDSITMATVER VARCHAR(5),
    BDSITDOEVER VARCHAR(5),
    BDSITACITRABVER VARCHAR(5),
    BDSITMILITARVER VARCHAR(5),
    BDSITMATEMPVER VARCHAR(5),
    BDSITACITRAB15VER VARCHAR(5),
    BDSITDOETRABVER VARCHAR(5),
    BDSITLICVENCVER VARCHAR(5),
    BDSITDOE15VER VARCHAR(5),
    BDSITSINDICALVER VARCHAR(5),
    BDSITAPOINVVER VARCHAR(5),
    BDSITOUTRASVER VARCHAR(5),
    BDTIPOVER INTEGER,
    BDORDEMTIPOCODVER INTEGER)
AS
BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_VERBAS_FOL_NORMAL_AUT (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32000),
    PRCODAUT varchar(10000),
    PRTIPOCOL integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer,
    PRFILTRO varchar(2000),
    PRCODTPCC varchar(10000),
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(2788) = null /* COLLATE WIN1252 - default */ ,
    PRFUCDET smallint = 0,
    PRBASECALC smallint = 1)
returns (
    BDCODPLAFUC integer,
    BDCODSINTRAB integer,
    BDCODCLA integer,
    BDDESCENQFED varchar(10),
    BDTEMGRRF integer,
    BDBSALFAM numeric(18,6),
    BDDATARESCISAO date,
    BDDESCRICAOMOTRES varchar(300),
    BDTIPOMOV integer,
    BDTIPO_COL integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMEMP DM_BDNOMEMP,
    BDAPEEMP DM_BDAPEMP,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP varchar(9),
    BDCNPJEMP varchar(18),
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDNOMCOL DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDPERCRATCOL numeric(18,6),
    BDDESCTFUC varchar(150),
    BDCPFCOL varchar(18),
    BDPISCOL varchar(14),
    BDCODENQFED integer,
    BDSIMPLESGPS integer,
    BDCTPSCOL DM_BDCTPS,
    BDCODCBO integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDREFFN integer,
    BDCODSERV integer,
    BDCODVER integer,
    BDDESCVER varchar(80),
    BDREFV numeric(18,6),
    BDPROVENTO numeric(18,6),
    BDDESCONTO numeric(18,6),
    BDSALBASE numeric(18,6),
    BDBINSS numeric(18,6),
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBIRRF numeric(18,6),
    BDBRAIS numeric(18,6),
    BDDESCREDVER varchar(80),
    BDIRRF numeric(18,6),
    BDGRUPOCLA integer,
    BDBINSS13 numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDBIRRF13 numeric(18,6),
    BDVFGTS13 numeric(18,6),
    BDBINSSFEFOL numeric(18,6),
    BDVINSSFEFOL numeric(18,6),
    BDBFGTSFEFOL numeric(18,6),
    BDVFGTSFEFOL numeric(18,6),
    BDDESCCC varchar(80),
    BDPISVER varchar(5),
    BDCLAVER varchar(20),
    BDBFGTSMESANT numeric(18,6),
    BDFGTSMESANT numeric(18,6),
    BDBFGTSMES numeric(18,6),
    BDFGTSMES numeric(18,6),
    BDSALDO numeric(18,6),
    BDFGTS40 numeric(18,6),
    BDFGTS10 numeric(18,6),
    BDTOTALGRRF numeric(18,6),
    BDORDEMVER integer,
    BDORDEMTIPOCODVER integer,
    BDTIPOCODVER integer,
    BDCODTFUC integer,
    BDTIPOREFVER integer,
    BDREFHOREMP varchar(5),
    BDVALMVINSSTER numeric(15,6),
    BDREFAUXV numeric(15,6),
    BDDATAPGTO date,
    BDCCATVCONCOM DM_BOOLEAN,
    BDBFGTSMESPOST numeric(18,6),
    BDFGTSMESPOST numeric(18,6),
    BDINSSFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDMVINSSTER numeric(18,6),
    BDHORASMENSAISCOL numeric(18,6),
    BDFGTSIND numeric(18,6),
    BDDATAGRRF date,
    BDBASEINSSMV numeric(18,6),
    BDBASEIRRFMV numeric(18,6),
    BDVALORINSSMV numeric(18,6),
    BDVALORIRRFMV numeric(18,6),
    BDPERCMULTA40 numeric(15,2),
    BDPERCMULTA10 numeric(15,2),
    BDCODCONTTI integer,
    BDCATEGORIAESOCIAL integer,
    BDCODSERVB DM_BOOLEAN,
    BDSALFAM13GPS numeric(18,6),
    BDSALFAMFNGPS numeric(18,6),
    BDCONTRCOL integer,
    BDFGTSMES13 numeric(18,6),
    BDBASEPISFN numeric(18,6),
    BDBASEPISFEFN numeric(18,6),
    BDBASEPIS13FN numeric(18,6),
    BDCREDTRAB numeric(18,6),
    BDCREDTRABFERIAS numeric(18,6),
    BDCREDTRABCONTAB numeric(18,6),
    BDCREDTRABGUIAMENSAL boolean,
    BDGRRFPRES integer)
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_VERBAS_FOLHA(PREMPRESA VARCHAR(30000),
PRCOLABORADOR VARCHAR(30000),
PRORDEMIMPRESSAO INTEGER,
PRTIPOFOLHA INTEGER,
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRAGRUPARSINDICATO INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRCENTROCUSTO INTEGER,
PRSINDICATO INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDESCTFUC VARCHAR(40),
BDDATAADMCOL DATE,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDPISCOL VARCHAR(14),
BDSALBASECOL NUMERIC(15,6),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDLOGRSINTRAB VARCHAR(15),
BDENDSINTRAB VARCHAR(40),
BDBAISINTRAB VARCHAR(20),
BDNROSINTRAB DM_NUMEND,
BDCOMPLSINTRAB VARCHAR(20),
BDNOMCIDSINTRAB VARCHAR(40),
BDSIGLAUFSINTRAB VARCHAR(2),
BDCODVER INTEGER,
BDREFVER INTEGER,
BDDESCVER VARCHAR(40),
BDREFV NUMERIC(15,6),
BDVALV NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VRHF_SP_VERBAS_PREV_RESC (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer,
    PRCODCC varchar(10000) = '' /* COLLATE WIN1252 - default */ )
returns (
    BDCODPLAFUC integer,
    BDCODSINTRAB integer,
    BDCODCLA integer,
    BDDESCENQFED varchar(10),
    BDTEMGRRF integer,
    BDBSALFAM numeric(18,6),
    BDDATARESCISAO date,
    BDDESCRICAOMOTRES varchar(300),
    BDTIPOMOV integer,
    BDTIPO_COL integer,
    BDCODMATRIZ integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMEMP DM_BDNOMEMP,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP varchar(9),
    BDCNPJEMP varchar(18),
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDNOMCOL DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDPERCRATCOL numeric(18,6),
    BDDESCTFUC varchar(80),
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDCODENQFED integer,
    BDSIMPLESGPS integer,
    BDCTPSCOL DM_BDCTPS,
    BDCODCBO integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDREFFN integer,
    BDCODSERV integer,
    BDCODVER integer,
    BDDESCVER varchar(80),
    BDREFV numeric(18,6),
    BDPROVENTO numeric(18,6),
    BDDESCONTO numeric(18,6),
    BDSALBASE numeric(18,6),
    BDBINSS numeric(18,6),
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBIRRF numeric(18,6),
    BDBRAIS numeric(18,6),
    BDDESCREDVER varchar(80),
    BDIRRF numeric(18,6),
    BDGRUPOCLA integer,
    BDBINSS13 numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDBIRRF13 numeric(18,6),
    BDVFGTS13 numeric(18,6),
    BDBINSSFEFOL numeric(18,6),
    BDVINSSFEFOL numeric(18,6),
    BDBFGTSFEFOL numeric(18,6),
    BDVFGTSFEFOL numeric(18,6),
    BDDESCCC varchar(80),
    BDPISVER varchar(5),
    BDCLAVER varchar(20),
    BDBFGTSMESANT numeric(18,6),
    BDFGTSMESANT numeric(18,6),
    BDBFGTSMES numeric(18,6),
    BDFGTSMES numeric(18,6),
    BDSALDO numeric(18,6),
    BDFGTS40 numeric(18,6),
    BDFGTS10 numeric(18,6),
    BDTOTALGRRF numeric(18,6),
    BDORDEMVER integer,
    BDORDEMTIPOCODVER integer,
    BDTIPOCODVER integer,
    BDTIPOREFVER integer,
    BDREFHOREMP varchar(5),
    BDDATAPGTO date,
    BDBFGTSMESPOST numeric(18,6),
    BDFGTSMESPOST numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSSFNPR numeric(18,6),
    BDINSS13FNPR numeric(18,6),
    BDCCATVCONCOM DM_BOOLEAN,
    BDREFAUXV numeric(18,6),
    BDFGTSIND numeric(18,6),
    BDDATAGRRF date,
    BDPERCMULTA40 numeric(15,2),
    BDPERCMULTA10 numeric(15,2),
    BDFGTSMES13 numeric(18,6),
    BDCREDTRAB numeric(18,6),
    BDCREDTRABFERIAS numeric(18,6),
    BDCREDTRABCONTAB numeric(18,6),
    BDCREDTRABGUIAMENSAL boolean,
    BDGRRFPRES integer)
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_VERBAS_SIM_COL_CALC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SP_VERBAS_SIM_PRES_CALC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODPRES INTEGER,
BDCODVER INTEGER,
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_BC_PROLAB_COLAB(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER,
PRTIPOCADASTRO INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_BC_PROLABORISTAS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_BC_RAT(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_BC_SEGURADOS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_BC_TERCEIROS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_PROLAB_COLAB(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER,
PRTIPOCADASTRO INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_PROLABORISTAS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_RATAPO(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_SALFAM(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_SALMATERNIDADE(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_SEGURADOS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VRHF_SPF_VALNOTAFISCAL(PREMP INTEGER,
PRREF INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_COPIA_CENTROS_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_COPIA_CONTAS_PLANO(APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_COPIA_CONTAS_PLANO_FCONT(APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_COPIA_CONTAS_PLANO_SPED(APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_COPIA_FORMULAS_PLANO(APELIDO_NOVO_PLANO VARCHAR(20),
    CODIGONOVO integer,
    CODIGOCOPIAR integer,
    DMPLCPC26 bigint = 0,
    PRRELATORIO integer = 0,
    prvinculotpla INTEGER = 0)
 AS
 BEGIN EXIT; END
^

--#alt:13583 - Criado procedimento para copia dos lançamentos da planilha. Ana - 01/03/2017
CREATE OR ALTER PROCEDURE VSUC_COPIA_PLANILHA_TLAN(
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_COPIA_HISTORICOS_PLANO(APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_COPIA_HORARIO_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_COPIA_MOEDAS_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_GETDEMONSTRATIVO (
    PRCODEMP VARCHAR(2048),
    PRIGNORAZERAMENTO INTEGER,
    PRDETALHAFILIAL INTEGER,
    PRSALDOANTERIOR INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRDATAINI DATE,
    PRDATAFIN DATE,
    PREXPORTACAOECF INTEGER,
    PRINDICE INTEGER,
    PRCC VARCHAR(8192),
    PRDETALHAR_CC INTEGER,
    PRLANCNOTCC INTEGER,
    PRDETALHAR_TERC INTEGER,
    PRNIVELCC INTEGER,
    PRDATEINIZER date = null,
    PRDATEFINZER date = null,
    PREMPRESAGRPECO integer = 0,
    PRGRPECO integer = 0,
    PRELIMINACOESK300K315 integer = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDCODPLAPADRAO INTEGER,
    BDCODTPLA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDAPECTA VARCHAR(20),
    BDTIPCTA INTEGER,
    BDGRUPOCTA INTEGER,
    BDRELCTA INTEGER,
    BDSALANT NUMERIC(15,2),
    BDSALDEB NUMERIC(15,2),
    BDSALCRE NUMERIC(15,2),
    BDMOVPER NUMERIC(15,2),
    BDSALATU NUMERIC(15,2),
    BDSALANT1 NUMERIC(15,2),
    BDSALDEB1 NUMERIC(15,2),
    BDSALCRE1 NUMERIC(15,2),
    BDMOVPER1 NUMERIC(15,2),
    BDSALATU1 NUMERIC(15,2),
    BDSALANT2 NUMERIC(15,2),
    BDSALDEB2 NUMERIC(15,2),
    BDSALCRE2 NUMERIC(15,2),
    BDMOVPER2 NUMERIC(15,2),
    BDSALATU2 NUMERIC(15,2),
    BDCODTPCC INTEGER,
    BDNOMTPCC VARCHAR(2048),
    BDCODTER INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_LANCAMENTOS_AGRUPADOS(PRCODEMP VARCHAR(1024),
PRTIPOLAN VARCHAR(100),
PRCHAVEONLINE VARCHAR(120),
PRDATA DATE,
PRCONTABILIZACAO INTEGER,
PRDEBITO INTEGER,
PRCREDITO INTEGER,
PRCOMPL SMALLINT = NULL,
PRCODTPCC VARCHAR(8192) = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER,
BDLOTE VARCHAR(10),
BDDATA DATE,
BDDEBITO INTEGER,
BDCONCD VARCHAR(5),
BDCREDITO INTEGER,
BDCONCC VARCHAR(5),
BDVALOR NUMERIC(15,2),
BDDATALAN DATE,
BDHORALAN TIME,
BDDATALANALT DATE,
BDHORALANALT TIME,
BDCODUSU INTEGER,
BDCODUSUALTERACAO INTEGER,
BDCODTPHI INTEGER,
BDNOMEHIST VARCHAR(100),
BDCOMPL VARCHAR(200),
BDDCTO VARCHAR(15),
BDCODTERCEIROD INTEGER,
BDCODTERCEIROC INTEGER,
BDTIPLAN VARCHAR(100),
BDTRANSFERIDO INTEGER,
BDGRUPO INTEGER,
BDTOTLAN INTEGER,
BDAGRUPADOR INTEGER,
BDTIPOLAN INTEGER,
BDCHAVEONLINE VARCHAR(120),
BDCODTPCC INTEGER,
BDTRANSACAO INTEGER,
BDTRANFECHADA VARCHAR(5),
BDCONCILIACAOPENDENTE INTEGER,
BDOBSERVACAODEB TYPE OF COLUMN VSUC_EMPRESAS_TOBS.BDOBSERVACAO,
BDOBSERVACAOCRE TYPE OF COLUMN VSUC_EMPRESAS_TOBS.BDOBSERVACAO)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_NRO_NOTA_COMPL(PRCOMPL VARCHAR(200),
PRZEROESQ SMALLINT)
 RETURNS(NRONF VARCHAR(50))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_ALTERA_LANCAMENTOS AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RESTAURA_LANC_LIXEIRA (
PRCODEMP            INTEGER,
PRCHAVE             INTEGER,
PRTRANSACAO         INTEGER,
PRMANTERCHAVE       INTEGER,
PRNOVACHAVE         INTEGER,
PRNOVATRANSACAO     INTEGER,
PRIGNORAR_N_PRA_N   INTEGER = 0,
PRUPDATE_LANCAMENTO INTEGER = 0)
AS
 BEGIN END
^

CREATE OR ALTER PROCEDURE VSUC_SP_MOVE_LANC_LIXEIRA (
PRCODEMP            INTEGER,
PRCHAVE             INTEGER,
PRIGNORAR_N_PRA_N   INTEGER = 0,
PRUPDATE_LANCAMENTO INTEGER = 0)
AS
 BEGIN END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RESTAURA_LANCS_LIXEIRA (
PRWHERE          VARCHAR(20000),
PRLANCDUPLICADOS INTEGER,
PRMANTERCHAVE    INTEGER,
PRCODEMP         INTEGER,
PRULTCHAVE       INTEGER,
PRULTTRANSACAO   INTEGER)
AS
 BEGIN END
^

CREATE OR ALTER PROCEDURE VSUC_SP_BALANCETE_MENSAL (
    PRCODEMP VARCHAR(2048),
    PRDATINI DATE,
    PRDATFIN DATE,
    PRIGNORA_ZERAMENTO INTEGER,
    PRCTAINI INTEGER,
    PRCTAFIN INTEGER,
    PRINDICE INTEGER,
    PRCODTPCC VARCHAR(8192),
    PRREFEMP INTEGER,
    PRLANSEMCC INTEGER,
    PRNAOMOSTRACONTACOMP INTEGER,
    PRCONSOLIDADA INTEGER,
    PRDETALHARCTAPARTICIPANTE INTEGER,
    PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
    PRCONCATENACODPARTICIPANTE INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRNIVELCC INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA SMALLINT,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDSALDO_ANT_DEB NUMERIC(15,2),
BDSALDO_ANT_CRE NUMERIC(15,2),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALDO_ATUAL NUMERIC(15,2),
BDGRPCTA SMALLINT,
BDTPCCLON VARCHAR(20),
BDMOVIMENTO NUMERIC(15,2),
BDFORMULA VARCHAR(200),
BDRELCTA INTEGER,
BDCLANOM VARCHAR(140),
BDDATINI DATE,
BDDATFIN DATE,
BDAPECTA VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_CENTRAL_CONCILIACAO (
    PRSQL VARCHAR(32000),
    PRPLANO_CONTA INTEGER,
    PRCONTA INTEGER,
    PRPARTICIPANTE INTEGER,
    PRSALDO_ANTERIOR NUMERIC(18,2),
    PRCONCILIACAO VARCHAR(100))
RETURNS (
    BDCODEMP INTEGER,
    BDCHAVE INTEGER,
    BDDATA DATE,
    BDDCTO VARCHAR(15),
    BDDEBITO INTEGER,
    BDCODTERCEIROD INTEGER,
    BDCREDITO INTEGER,
    BDCODTERCEIROC INTEGER,
    BDCODTPHI INTEGER,
    BDCOMPL VARCHAR(200),
    BDTIPOLAN INTEGER,
    BDTRANSACAO INTEGER,
    BDVALOR NUMERIC(18,2),
    BDSALDO NUMERIC(18,2),
    BDGRUPOCTA INTEGER,
    BDVALORDEB NUMERIC(18,2),
    BDVALORCRE NUMERIC(18,2),
    BDCONCILIADO INTEGER,
    BDDEBCRE INTEGER,
    BDCONCILIADOBASE INTEGER,
    BDBLOQUEADO VARCHAR(5),
    BDTIPOCONC INTEGER,
    BDDCTOZEROESQ varchar(15),
    BDNRODOCCOMPL Varchar(255))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_BALANCO_PATRIMONIAL (
    PRCODEMP VARCHAR(2048),
    PRDATINI DATE,
    PRDATFIN DATE,
    PRIGNZER INTEGER,
    PRCTALONINI VARCHAR(40),
    PRCTALONFIN VARCHAR(40),
    PRCTALONPAS VARCHAR(40),
    PRINDICE INTEGER,
    PRLISTACC VARCHAR(8192),
    PRNAOMOSTRACONTACOMP INTEGER,
    PRREFEMP INTEGER,
    PRCONSOLIDADA INTEGER,
    PRDETALHARCTAPARTICIPANTE INTEGER,
    PRCONCATENACODPARTICIPANTE INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRSEMCC INTEGER,
    PRAGRUPARPARTICIPANTEPORCNPJ INTEGER = 0,
    PRDETALHAREMPREENDIMENTO INTEGER = 0,
    PRDETALHARUNIDIMOB INTEGER = 0,
    PRMOSTRARPROP INTEGER = 0,
    PRAGRUPARPARTICIPANTEPORCPF INTEGER = 0,
    PRCTAINI integer = 0,
    PRCTAFIN integer = 0,
    PRPLANOGRPECO integer = 0,
    PREMPRESAGRPECO integer = 0,
    PRGRPECO integer = 0,
    PRELIMINACOESK300K315 integer = 0)
RETURNS (
    BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(300),
BDTIPCTA INTEGER,
BDSEQCTA VARCHAR(40),
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(80),
BDSALANT NUMERIC(15,2),
BDSAL_ANT_DEB NUMERIC(15,2),
BDSAL_ANT_CRE NUMERIC(15,2),
BDSALMOV NUMERIC(15,2),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDFORMULA VARCHAR(1024),
BDCODEMPFILIAL INTEGER,
BDGRPCTA INTEGER,
BDAPECTA VARCHAR(20),
BDPERTENCECONTA INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_CONCILIACAO_AUTOMATICA(PRCODEMP INTEGER,
PRCODCTA INTEGER,
PRCODCLIFOR INTEGER,
PRCODPLAPADRAO INTEGER,
PRDOCTO VARCHAR(15),
PRCONTABILIZACAO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDCODPLAPADRAO INTEGER,
BDDEBITO INTEGER,
BDCODTERCEIROD INTEGER,
BDCONCD VARCHAR(5),
BDCREDITO INTEGER,
BDCODTERCEIROC INTEGER,
BDCONCC VARCHAR(5),
BDVALOR NUMERIC(15,2),
BDLOTE VARCHAR(10),
BDCOMPL VARCHAR(200),
BDDCTO VARCHAR(15))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_CONSOLIDADA(PRCODPLAPADRAO INTEGER,
PRCTALON VARCHAR(40))
 RETURNS(BDRESULT SMALLINT)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_COPIA_CONTAS_FORMULAS(PRCODPFOR INTEGER,
PRCODPLAPADRAO INTEGER,
PRCLASS VARCHAR(30000))
 AS
 BEGIN EXIT; END
^

create or alter procedure VSUC_SP_COPY_PREPARACAO_FOR_ECF_Y520 (
    PRCODPLAPADRAOFORM integer,
    PRCODPLAPADRAO integer,
    PRCODPAIS integer,
    PRDE_ANO integer,
    PRPARA_ANO integer,
    PROPCAO integer,
    PRTIPOY520 integer,
    PRFORMAY520 integer)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_EXPORTA_SPED_I300 (
    PRCODEMP VARCHAR(2048),
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRIGNORA_ZERAMENTO INTEGER,
    PRCODTPCC VARCHAR(8192),
    PRREFEMP INTEGER,
    PRLANSEMCC INTEGER,
    PRCONTABILIZACAO INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP VARCHAR(18),
    BDCODMATRIZ INTEGER,
    BDCODPLAPADRAO INTEGER,
    BDDATA DATE,
    BDCODCTA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDDEBITO NUMERIC(15,2),
    BDCREDITO NUMERIC(15,2),
    BDCODTPCC INTEGER,
    BDNOMTPCC VARCHAR(40),
    BDCODCENTROS INTEGER,
    BDCTALONCC VARCHAR(40))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_IMPORTAFORMULA (
    PRCODPLAPADRAO INTEGER,
    PRCODFOR INTEGER,
    PRNIVELINI INTEGER,
    PRNIVELFIM INTEGER,
    PRCTALONINI VARCHAR(40),
    PRCTALONFIM VARCHAR(40),
    PRQUADRO INTEGER = 0)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_INSERT_ENCEX(PRCODEMP INTEGER,
PRCODPLANOS INTEGER,
PRCODTPLA INTEGER,
PRCODHIST INTEGER,
PRCODTPHI INTEGER,
PRCODUSU INTEGER,
PRDATAINIZER DATE,
PRDATAFIMZER DATE,
PRDATALANCZER DATE,
PRDATAZER DATE,
PRHORAZER TIMESTAMP)
 RETURNS(PRCHAVEZER INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_INSERT_LANC(PRCHAVE INTEGER,
PRCODEMP INTEGER,
PRCODPLAPADRAO INTEGER,
PRDEBITO INTEGER,
PRCREDITO INTEGER,
PRCODHIST INTEGER,
PRCODTPHI INTEGER,
PRUSUARIO INTEGER,
PRLOTE VARCHAR(10),
PRDATA DATE,
PRVALOR NUMERIC(15,2),
PRCOMPL VARCHAR(100),
PRDATALAN DATE,
PRHORALAN TIME,
PRTIPOLAN SMALLINT,
PRDCTO VARCHAR(5),
PRCONCD VARCHAR(5),
PRCONCC VARCHAR(5),
PRCHAVEZER INTEGER,
PRREFEMP INTEGER)
 AS
 BEGIN EXIT; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_LISTA_CTA_RAZAO_VIDEO(PRCODEMP VARCHAR(2048),
PRCODPLAPADRAO INTEGER,
PRDATINI DATE,
PRDATFIM DATE,
PRCTALONINI VARCHAR(40),
PRCTALONFIM VARCHAR(40),
PRTIPORAZAO INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODTPLA INTEGER,
BDNOMCTA VARCHAR(100),
BDCTALON VARCHAR(40),
BDCODPARTICIPANTE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_LISTA_CTA_RAZAO_VIDEO_X(
    PRCODEMP VARCHAR(2048),
    PRCODPLAPADRAO INTEGER,
    PRDATINI DATE,
    PRDATFIM DATE,
    PRCTALONINI VARCHAR(40),
    PRCTALONFIM VARCHAR(40),
    PRTIPORAZAO VARCHAR(20),
    PRPARTINI INTEGER,
    PRPARTFIM INTEGER,
    PRDETALHARCTAPARTICIPANTE INTEGER,
    PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRDETALHARCC INTEGER,
    PRLCC VARCHAR(8192),
    PRLANCAMENTOSEMCC INTEGER,
    PRDETALHAREMPREENDIMENTO INTEGER = 0,
    PRDETALHARUNIDIMOB INTEGER = 0,
    PRMOSTRARPROPUNIDADE INTEGER = 0,
    PRAGRUPARPARTICIPANTEPORCPF INTEGER = 0,
    PRORDEM INTEGER = 0,
    PRTIPOLAN varchar(3200) = '')
RETURNS (
    BDCODTPLA INTEGER,
    BDNOMCTA VARCHAR(300),
    BDCTALON VARCHAR(40),
    BDCODPARTICIPANTE INTEGER,
    BDCNPJPART VARCHAR(20),
    BDEMPREENDIMENTO INTEGER,
    BDUNIDIMOB INTEGER,
    BDCODEMP INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_LISTA_TLAN_CONC_CLIFOR(PREMPRESA INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRCLIFOR SMALLINT,
PRLANCONC SMALLINT,
PRZEROESQ SMALLINT,
PRCODPLAPADRAO INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(CONCILIACAOOK SMALLINT)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_MOVIMENTO_MENSAL(
    PRCODEMP VARCHAR(1024),
    PRCONTA INTEGER,
    PRCC VARCHAR(8192),
    PRANOINICIAL INTEGER,
    PRANOFINAL INTEGER,
    PRREFEMP INTEGER,
    PRPARTICIPANTE INTEGER,
    PRIGNORAZERAMENTO INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER) 
RETURNS (
    BDDEB01 NUMERIC(15,2),
    BDDEB02 NUMERIC(15,2),
    BDDEB03 NUMERIC(15,2),
    BDDEB04 NUMERIC(15,2),
    BDDEB05 NUMERIC(15,2),
    BDDEB06 NUMERIC(15,2),
    BDDEB07 NUMERIC(15,2),
    BDDEB08 NUMERIC(15,2),
    BDDEB09 NUMERIC(15,2),
    BDDEB10 NUMERIC(15,2),
    BDDEB11 NUMERIC(15,2),
    BDDEB12 NUMERIC(15,2),
    BDCRE01 NUMERIC(15,2),
    BDCRE02 NUMERIC(15,2),
    BDCRE03 NUMERIC(15,2),
    BDCRE04 NUMERIC(15,2),
    BDCRE05 NUMERIC(15,2),
    BDCRE06 NUMERIC(15,2),
    BDCRE07 NUMERIC(15,2),
    BDCRE08 NUMERIC(15,2),
    BDCRE09 NUMERIC(15,2),
    BDCRE10 NUMERIC(15,2),
    BDCRE11 NUMERIC(15,2),
    BDCRE12 NUMERIC(15,2),
    BDMOV01 NUMERIC(15,2),
    BDMOV02 NUMERIC(15,2),
    BDMOV03 NUMERIC(15,2),
    BDMOV04 NUMERIC(15,2),
    BDMOV05 NUMERIC(15,2),
    BDMOV06 NUMERIC(15,2),
    BDMOV07 NUMERIC(15,2),
    BDMOV08 NUMERIC(15,2),
    BDMOV09 NUMERIC(15,2),
    BDMOV10 NUMERIC(15,2),
    BDMOV11 NUMERIC(15,2),
    BDMOV12 NUMERIC(15,2),
    BDSAL01 NUMERIC(15,2),
    BDSAL02 NUMERIC(15,2),
    BDSAL03 NUMERIC(15,2),
    BDSAL04 NUMERIC(15,2),
    BDSAL05 NUMERIC(15,2),
    BDSAL06 NUMERIC(15,2),
    BDSAL07 NUMERIC(15,2),
    BDSAL08 NUMERIC(15,2),
    BDSAL09 NUMERIC(15,2),
    BDSAL10 NUMERIC(15,2),
    BDSAL11 NUMERIC(15,2),
    BDSAL12 NUMERIC(15,2),
    BDSALTOTDEB NUMERIC(15,2),
    BDSALTOTCRE NUMERIC(15,2),
    BDSALTOTMOV NUMERIC(15,2),
    BDSALTOTATU NUMERIC(15,2),
    BDANO INTEGER,
    BDGRPCTA INTEGER,
    BDDEBANT NUMERIC(15,2),
    BDCREANT NUMERIC(15,2),
    BDMOVANT NUMERIC(15,2),
    BDSALANT NUMERIC(15,2)) 
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_NOMENCLATURA_CTA_PARTIC (
    PRCODTERCEIRO INTEGER,
    PRCLASSIFICACAO VARCHAR(40),
    PRCONCATENA INTEGER,
    PRREFEMP INTEGER) -- #149080 - Marcela - Razão/Diário/Balancete - Verificar data de emissão pra nome de contas de participante 12/07/2022
RETURNS (
    BDNOME VARCHAR(100),
    BDCLASSIFICACAO VARCHAR(100))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_PERMITECALCSALDOLANCMF(PRCAMPO INTEGER,
PRCODEMPMASTER INTEGER,
PRCODEMP INTEGER,
PRFILIAL INTEGER,
PRTIPOLANCFILIAL INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PREMPRESAS VARCHAR(2048))
 RETURNS(BDPERMITE SMALLINT)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VSUC_SP_RETORNA_BALANCETE (
    PRCODEMP varchar(2048),
    PRDATINI date,
    PRDATFIN date,
    PRIGNORA_ZERAMENTO integer,
    PRCTAINI integer,
    PRCTAFIN integer,
    PRINDICE integer,
    PRCODTPCC varchar(32000),
    PRREFEMP integer,
    PRLANSEMCC integer,
    PRORDEM integer,
    PRNAOMOSTRACONTACOMP integer,
    PRCONSOLIDADA integer,
    PRDETALHARCTAPARTICIPANTE integer,
    PRAGRUPARPARTICIPANTEPORCNPJ integer,
    PRCONCATENACODPARTICIPANTE integer,
    PRNIVEISCONTA varchar(50),
    PRTODASASCONTAS integer,
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRDRE integer = 0,
    PRTODOPLANOCONTAS integer = 0,
    PRDETALHAREMPREENDIMENTO integer = 0,
    PRDETALHARUNIDIMOB integer = 0,
    PRMOSTRARPROP integer = 0,
    PRDADOSIMPRIMIR integer = 0,
    PRAGRUPARPARTICIPANTEPORCPF integer = 0,
    PRNIVELCC integer = 0,
    PRSOMENTEMOVIMENTO integer = 0,
    PREMPREENDIMENTO varchar(32000) = '',
    PRPLANOGRPECO integer = 0,
    PREMPRESAGRPECO integer = 0,
    PRGRPECO integer = 0,
    PRTODOSPART varchar(2048) = '',
    PRDETALHARCCEMPREEND integer = 0,
    PRIGNZERPERANT integer = 0,
    PRTIPOLAN varchar(3200) = '',
    PRELIMINACOESK300K315 integer = 0)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(18),
    BDCODMATRIZ integer,
    BDCODEMPFILIAL integer,
    BDCODPLAPADRAO integer,
    BDCODCTA integer,
    BDCTALON varchar(60),
    BDNOMCTA varchar(300),
    BDTIPCTA smallint,
    BDCODTPCC integer,
    BDNOMTPCC varchar(40),
    BDSALDO_ANTERIOR numeric(15,2),
    BDSALDO_ANT_DEB numeric(15,2),
    BDSALDO_ANT_CRE numeric(15,2),
    BDSALDO_DEB numeric(15,2),
    BDSALDO_CRE numeric(15,2),
    BDSALDO_ATUAL numeric(15,2),
    BDGRPCTA smallint,
    BDTPCCLON varchar(20),
    BDMOVIMENTO numeric(15,2),
    BDFORMULA varchar(200),
    BDRELCTA integer,
    BDCLANOM varchar(340),
    BDCODTER integer,
    BDAPECTA varchar(20),
    BDSALDO_ANTERIOR_DRE numeric(15,2),
    BDSALDO_ANT_DEB_DRE numeric(15,2),
    BDSALDO_ANT_CRE_DRE numeric(15,2),
    BDRAIZCNPJPARTICIPANTE varchar(10),
    BDRAIZCLASSIFICACAOCTA varchar(40),
    BDCODUNIDIMOB integer,
    BDCODEMPREENDIMENTO integer,
    BDAPEEMP DM_BDAPEMP,
    BDVALORCOMPFILIAIS numeric(15,2),
    BDSALDO_SEM_CONCILIACAO numeric(15,2),
    BDSALDO_ATUAL_REAL numeric(15,2),
    BDFILTROCC varchar(200),
    BDCODNE integer,
    BDCPFCNPJTER varchar(18),
    BDCTACOMP varchar(5),
    BDDATAULTLANC date,
    BDCODTARBANCARIA integer,
    BDVALORUNIT numeric(15,2),
    BDVALORPERCENT numeric(15,2))
as
 BEGIN SUSPEND; END
^

--#alt:23030. Ana - 15/03/2018
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDOS_CTAINCOR (
    PRCODEMP integer,
    PRCODPLAPADRAO integer,
    PRDTINICIAL date,
    PRDTFINAL date,
    PRCONTA integer,
    PRINDICE integer,
    PRIGNORAZERAMENTO integer,
    PRCONCILIADOS integer,
    PREMPRESAS varchar(2048),
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRCTALONANT varchar(40),
    PRCTATITULO integer,
    PRRAIZCTASEMEMPREENDIMENTOANT varchar(40),
    PRDETALHAREMPREENDIMENTO integer,
    PRDETALHARUNIDIMOB integer,
    PRMOSTRARPROP integer,
    PRCC integer = 0,
    PRLANCSEMCC integer = 0,
    PRDETALHARCC integer = 0)
returns (
    BDCLASSIFICACAO varchar(40),
    BDSALDO_DEB numeric(15,2),
    BDSALDO_ANT_DEB numeric(15,2),
    BDSALDO_CRE numeric(15,2),
    BDSALDO_ANT_CRE numeric(15,2),
    BDMOVIMENTO numeric(15,2),
    BDSALDO_ATUAL numeric(15,2),
    BDSALDO_ANTERIOR numeric(15,2),
    BDRAIZCLASSIFICACAOCTA varchar(40),
    BDCODEMPREENDIMENTO integer,
    BDCODUNIDIMOB integer,
    BDDESCEMPREENDIMENTO varchar(500),
    BDDESCUNIDIMOB varchar(500),
    BDRAIZCTASEMEMPREENDIMENTO varchar(40))
AS
  BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDOS_INCORP_2 (
    PRCODEMP INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRDTINICIAL DATE,
    PRDTFINAL DATE,
    PRCONTA INTEGER,
    PRINDICE INTEGER,
    PRIGNORAZERAMENTO INTEGER,
    PRCONCILIADOS INTEGER,
    PREMPRESAS VARCHAR(2048),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRCTALONANT VARCHAR(40),
    PRCTATITULO INTEGER,
    PRRAIZCTASEMEMPREENDIMENTOANT VARCHAR(40),
    PRDETALHAREMPREENDIMENTO INTEGER,
    PRDETALHARUNIDIMOB INTEGER,
    PRMOSTRARPROP INTEGER,
    PRCC INTEGER = 0,
    PRLANCSEMCC INTEGER = 0,
    PRDETALHARCC INTEGER = 0,
    PRNIVELCC INTEGER = 0,
    PREMPREENDIMENTO varchar(32000) = '',
    PRDETALHARCCEMPREEND integer = 0,
    PRTIPOLAN varchar(3200) = '')
returns (
    BDCLASSIFICACAO varchar(80),
    BDSALDO_DEB numeric(15,2),
    BDSALDO_ANT_DEB numeric(15,2),
    BDSALDO_CRE numeric(15,2),
    BDSALDO_ANT_CRE numeric(15,2),
    BDMOVIMENTO numeric(15,2),
    BDSALDO_ATUAL numeric(15,2),
    BDSALDO_ANTERIOR numeric(15,2),
    BDRAIZCLASSIFICACAOCTA varchar(40),
    BDCODEMPREENDIMENTO integer,
    BDCODUNIDIMOB integer,
    BDDESCEMPREENDIMENTO varchar(500),
    BDDESCUNIDIMOB varchar(500),
    BDRAIZCTASEMEMPREENDIMENTO varchar(40),
    BDDATAULTLANCAMENTO date,
    BDCODTPCC integer)
AS
  BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_RETORNA_CLA_INCORP (
    PRCODCTA INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRCODEMPREENDIMENTO INTEGER,
    PRUNIDIMOB INTEGER,
    PRNAODETALHAREMPREENDIMENTO integer = 0,
    PRNAODETALHARUNIDIMOB integer = 0,
    PREMPRESA integer = 0)
RETURNS (
    BDCLASSIFICACAO VARCHAR(40))
AS
  BEGIN SUSPEND; END
^
--#alt:23030. fim

create or alter procedure VSUC_COPIA_PLANO_TROCA (
    CODIGONOVO integer,
    CODIGOCOPIAR integer)
AS
BEGIN
END^

CREATE OR ALTER PROCEDURE SP_REMOVE_CLASS_ZERADAS (
    PRCLASSIFICACAO VARCHAR(40),
    PRRETIRAZEROSFINAL DM_BOOLEAN = 'FALSE')
RETURNS (
    BDCLASSIFICACAO VARCHAR(40))
AS
BEGIN
END^

CREATE OR ALTER PROCEDURE VSUC_COPIA_PLANO_SECUNDARIO (
    PRAPELIDONOVO VARCHAR(20),
    PRCODIGONOVO INTEGER,
    PRCODIGOCOPIAR INTEGER)
AS
BEGIN
END^

--#alt:18801. Alterei a estrutura da procedure. Ana - 18/05/2017
--#alt:15089. Ana - 15/03/2017
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_CONTAS_I157 (
    PRCODPLAPADRAO INTEGER,
    PRCODPLAPADRAOI157 INTEGER,
    PRMODELO integer = 0)
RETURNS (
    BDCODTPLAI157 INTEGER,
    BDCTALONI157 VARCHAR(40),
    BDNOMCTAI157 VARCHAR(100),
    BDTIPCTA INTEGER,
    BDCODTPLA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDCODTER INTEGER,
    BDNOMETER VARCHAR(100),
    BDCODEMPREENDIMENTO integer,
    BDCODIGOUNIIMOB integer,
    BDFILIAL integer,
    BDDEBCRE_ORIGINAL VARCHAR(1),
    BDVALOR_ORIGINAL NUMERIC(15,2),
    BDCTALON_FISICO VARCHAR(100),
    BDPARTICIPANTE integer)
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_BALANCETE_COMPA(PRCODEMP VARCHAR(2048),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRTIPCOMP INTEGER,
PRQTDCOMP INTEGER,
PRCODTPCC VARCHAR(8192),
PRIGNZER SMALLINT,
PRREFEMP INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDCODMATRIZ INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCENTROS INTEGER,
BDCODTPLA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDSALANT NUMERIC(15,2),
BDSALATU_01 NUMERIC(15,2),
BDSALMOV_01 NUMERIC(15,2),
BDSALATU_02 NUMERIC(15,2),
BDSALMOV_02 NUMERIC(15,2),
BDSALATU_03 NUMERIC(15,2),
BDSALMOV_03 NUMERIC(15,2),
BDSALATU_04 NUMERIC(15,2),
BDSALMOV_04 NUMERIC(15,2),
BDSALATU_05 NUMERIC(15,2),
BDSALMOV_05 NUMERIC(15,2),
BDSALATU_06 NUMERIC(15,2),
BDSALMOV_06 NUMERIC(15,2),
BDSALATU_07 NUMERIC(15,2),
BDSALMOV_07 NUMERIC(15,2),
BDSALATU_08 NUMERIC(15,2),
BDSALMOV_08 NUMERIC(15,2),
BDSALATU_09 NUMERIC(15,2),
BDSALMOV_09 NUMERIC(15,2),
BDSALATU_10 NUMERIC(15,2),
BDSALMOV_10 NUMERIC(15,2),
BDSALATU_11 NUMERIC(15,2),
BDSALMOV_11 NUMERIC(15,2),
BDSALATU_12 NUMERIC(15,2),
BDSALMOV_12 NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_BALANCO_PATRIMO (
    PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCTALONINI VARCHAR(40),
PRCTALONFIN VARCHAR(40),
PRCTALONPAS VARCHAR(40),
PRINDICE INTEGER,
PRLISTACC VARCHAR(8192),
PRNAOMOSTRACONTACOMP INTEGER,
PRCTASEMMOV INTEGER,
PRREFEMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRAGRUPARPARTICIPANTEPORCNPJ INTEGER = 0,
    PRAGRUPARPARTICIPANTEPORCPF INTEGER = 0)
RETURNS (
    BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDSEQCTA VARCHAR(40),
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(80),
BDSALANT NUMERIC(15,2),
BDSALMOV NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDANAVER NUMERIC(15,2),
BDFORMULA VARCHAR(1024),
BDGRPCTA INTEGER,
BDAPECTA VARCHAR(20))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_CADASTRO_BEM(PRCODEMP INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRCODPLAPADRAO INTEGER,
PRCONTABILIZACAO INTEGER,
PRMOSTRARDEPRECIADOS INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODBEM INTEGER,
BDDATATAXADEPRECIACAO DATE,
BDMESESDEPRECIADOS INTEGER,
BDDEPRECIACAOPERIODO NUMERIC(15,2),
BDDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
BDVALORRESIDUALCONTABIL NUMERIC(15,2),
BDVALORRESIDUALCONTABILMOEDA NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_CLASSGROUP(PRCODPLANOPADRAO INTEGER,
PRCAMPOPESQUISA VARCHAR(20),
PRCONTEUDO VARCHAR(40),
PRPESQUISAINICIO INTEGER)
 RETURNS(PRCLASSIFICACAO VARCHAR(40))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_COMPARATIVO(PREMPRESAS VARCHAR(1024),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRINDICE INTEGER,
PRTIPCOMP INTEGER,
PRCC VARCHAR(8192),
PRTIPOSALDO INTEGER,
PRREFEMP INTEGER,
PRIGNZER INTEGER,
PRLANSEMCC INTEGER,
PRAGRUPAEMPRESAFILIAIS INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(50),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDGRPCTA INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDQTDCOMP INTEGER,
BDSALDO01 NUMERIC(15,2),
BDMOVIMENTO01 NUMERIC(15,2),
BDSALDO02 NUMERIC(15,2),
BDMOVIMENTO02 NUMERIC(15,2),
BDSALDO03 NUMERIC(15,2),
BDMOVIMENTO03 NUMERIC(15,2),
BDSALDO04 NUMERIC(15,2),
BDMOVIMENTO04 NUMERIC(15,2),
BDSALDO05 NUMERIC(15,2),
BDMOVIMENTO05 NUMERIC(15,2),
BDSALDO06 NUMERIC(15,2),
BDMOVIMENTO06 NUMERIC(15,2),
BDSALDO07 NUMERIC(15,2),
BDMOVIMENTO07 NUMERIC(15,2),
BDSALDO08 NUMERIC(15,2),
BDMOVIMENTO08 NUMERIC(15,2),
BDSALDO09 NUMERIC(15,2),
BDMOVIMENTO09 NUMERIC(15,2),
BDSALDO10 NUMERIC(15,2),
BDMOVIMENTO10 NUMERIC(15,2),
BDSALDO11 NUMERIC(15,2),
BDMOVIMENTO11 NUMERIC(15,2),
BDSALDO12 NUMERIC(15,2),
BDMOVIMENTO12 NUMERIC(15,2),
BDFORMULA VARCHAR(1024))
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VSUC_SP_RETORNA_COMPARATIVO_X (
    PRCODEMP varchar(2048),
    PRCTAINI integer,
    PRCTAFIN integer,
    PRDATAINI date,
    PRDATAFIN date,
    PRINDICE integer,
    PRCTASEMMOV integer,
    PRIMPRIMIRCOLUNASEXTRAS integer,
    PRTIPCOMP integer,
    PRCODTPCC varchar(32000),
    PRTIPOSALDO integer,
    PRREFEMP integer,
    PRIGNZER integer,
    PRLANSEMCC integer,
    PRAGRUPAEMPRESAFILIAIS integer,
    PRDETALHARCTAPARTICIPANTE integer,
    PRCONCATENACODPARTICIPANTE integer,
    PRNIVEISCONTA varchar(50),
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRCTACONSOLIDADA integer,
    PRFORMACALC integer = 0,
    PRAGRUPARPORCNPJ integer = 0,
    PRAGRUPARPORCPF integer = 0,
    PRTODASCTAS integer = 0)
returns (
    BDCODEMP integer,
    BDCODEMPFILIAL integer,
    BDNOMEMP varchar(100),
    BDCODMATRIZ integer,
    BDCNPJEMP varchar(18),
    BDCODPLAPADRAO integer,
    BDCODCTA integer,
    BDCTALON varchar(50),
    BDNOMCTA varchar(100),
    BDCLANOM varchar(150),
    BDTIPCTA integer,
    BDGRPCTA integer,
    BDCODTPCC integer,
    BDNOMTPCC varchar(40),
    BDQTDCOMP integer,
    BDFORMULA varchar(1024),
    BDSALDO01 numeric(15,2),
    BDMOVIMENTO01 numeric(15,2),
    BDSALDOREAL01 numeric(15,2),
    BDSALDO02 numeric(15,2),
    BDMOVIMENTO02 numeric(15,2),
    BDSALDOREAL02 numeric(15,2),
    BDSALDO03 numeric(15,2),
    BDMOVIMENTO03 numeric(15,2),
    BDSALDOREAL03 numeric(15,2),
    BDSALDO04 numeric(15,2),
    BDMOVIMENTO04 numeric(15,2),
    BDSALDOREAL04 numeric(15,2),
    BDSALDO05 numeric(15,2),
    BDMOVIMENTO05 numeric(15,2),
    BDSALDOREAL05 numeric(15,2),
    BDSALDO06 numeric(15,2),
    BDMOVIMENTO06 numeric(15,2),
    BDSALDOREAL06 numeric(15,2),
    BDSALDO07 numeric(15,2),
    BDMOVIMENTO07 numeric(15,2),
    BDSALDOREAL07 numeric(15,2),
    BDSALDO08 numeric(15,2),
    BDMOVIMENTO08 numeric(15,2),
    BDSALDOREAL08 numeric(15,2),
    BDSALDO09 numeric(15,2),
    BDMOVIMENTO09 numeric(15,2),
    BDSALDOREAL09 numeric(15,2),
    BDSALDO10 numeric(15,2),
    BDMOVIMENTO10 numeric(15,2),
    BDSALDOREAL10 numeric(15,2),
    BDSALDO11 numeric(15,2),
    BDMOVIMENTO11 numeric(15,2),
    BDSALDOREAL11 numeric(15,2),
    BDSALDO12 numeric(15,2),
    BDMOVIMENTO12 numeric(15,2),
    BDSALDOREAL12 numeric(15,2),
    BDMEDIASALDO numeric(15,2),
    BDTOTALSALDO numeric(15,2),
    BDMEDIAMOVIMENTO numeric(15,2),
    BDTOTALMOVIMENTO numeric(15,2))
AS
 BEGIN SUSPEND; END
^

create or alter procedure VSUC_SP_RETORNA_COMPARATIVO_Y (
    PRCODEMP varchar(2048),
    PRCTAINI integer,
    PRCTAFIN integer,
    PRDATAINI date,
    PRDATAFIN date,
    PRINDICE integer,
    PRCTASEMMOV integer,
    PRTIPCOMP integer,
    PRCODTPCC varchar(32000),
    PRTIPOSALDO integer,
    PRREFEMP integer,
    PRIGNZER integer,
    PRLANSEMCC integer,
    PRAGRUPAEMPRESAFILIAIS integer,
    PRDETALHARCTAPARTICIPANTE integer,
    PRNIVEISCONTA varchar(50),
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRCTACONSOLIDADA integer,
    PRAGRUPARPORCNPJ integer = 0,
    PRAGRUPARPORCPF integer = 0,
    PRTODASCTAS integer = 0)
returns (
    BDCODEMP integer,
    BDCODEMPFILIAL integer,
    BDNOMEMP varchar(100),
    BDCODMATRIZ integer,
    BDCNPJEMP varchar(18),
    BDCODPLAPADRAO integer,
    BDCODCTA integer,
    BDCTALON varchar(50),
    BDNOMCTA varchar(100),
    BDCLANOM varchar(150),
    BDTIPCTA integer,
    BDGRPCTA integer,
    BDCODTPCC integer,
    BDNOMTPCC varchar(40),
    BDQTDCOMP integer,
    BDFORMULA varchar(1024),
    BDSALDO01 numeric(15,2),
    BDMOVIMENTO01 numeric(15,2),
    BDSALDOREAL01 numeric(15,2),
    BDSALDO02 numeric(15,2),
    BDMOVIMENTO02 numeric(15,2),
    BDSALDOREAL02 numeric(15,2),
    BDSALDO03 numeric(15,2),
    BDMOVIMENTO03 numeric(15,2),
    BDSALDOREAL03 numeric(15,2),
    BDSALDO04 numeric(15,2),
    BDMOVIMENTO04 numeric(15,2),
    BDSALDOREAL04 numeric(15,2),
    BDSALDO05 numeric(15,2),
    BDMOVIMENTO05 numeric(15,2),
    BDSALDOREAL05 numeric(15,2),
    BDSALDO06 numeric(15,2),
    BDMOVIMENTO06 numeric(15,2),
    BDSALDOREAL06 numeric(15,2),
    BDSALDO07 numeric(15,2),
    BDMOVIMENTO07 numeric(15,2),
    BDSALDOREAL07 numeric(15,2),
    BDSALDO08 numeric(15,2),
    BDMOVIMENTO08 numeric(15,2),
    BDSALDOREAL08 numeric(15,2),
    BDSALDO09 numeric(15,2),
    BDMOVIMENTO09 numeric(15,2),
    BDSALDOREAL09 numeric(15,2),
    BDSALDO10 numeric(15,2),
    BDMOVIMENTO10 numeric(15,2),
    BDSALDOREAL10 numeric(15,2),
    BDSALDO11 numeric(15,2),
    BDMOVIMENTO11 numeric(15,2),
    BDSALDOREAL11 numeric(15,2),
    BDSALDO12 numeric(15,2),
    BDMOVIMENTO12 numeric(15,2),
    BDSALDOREAL12 numeric(15,2),
    BDMEDIASALDO numeric(15,2),
    BDTOTALSALDO numeric(15,2),
    BDMEDIAMOVIMENTO numeric(15,2),
    BDTOTALMOVIMENTO numeric(15,2))
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_CONTAS_USADAS(PREMPRESAS VARCHAR(1024),
PRCODPLAPADRAO INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRTITULOS INTEGER,
PRORCAMENTO INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRTIPOCONCILIACAO INTEGER,
PRTODASASCONTAS INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDAPECTA VARCHAR(20),
BDTIPCTA SMALLINT,
BDRELCTA INTEGER,
BDINVERTESINAL VARCHAR(5),
BDFILTROGER VARCHAR(20),
BDCLANOM VARCHAR(140),
BDFORMULA VARCHAR(200),
BDCONDICAO VARCHAR(100),
BDCONCILIAAUTOMATICA VARCHAR(5),
BDGRUPOCTA INTEGER,
BDPARTICIPANTE INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VSUC_SP_RETORNA_CONTR_PATRIMON (
    PRCODEMP varchar(2048),
    PRCTAINI integer,
    PRCTAFIN integer,
    PRDATINI date,
    PRDATFIN date,
    PRMODELO integer,
    PRTIPO integer,
    PRCODPLAPADRAO integer,
    PRREFEMP integer,
    PRMOSTRADEPRECIADOS integer,
    PRCONTABILIZACAO integer,
    PRDETALHARTAXADEP integer = 0,
    PRCODTPCC varchar(8192) = '',
    prRelBaiPar INTEGER = 0)
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDCODEMPFILIAL integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODBEM integer,
    BDNOMBEM varchar(200),
    BDCODTPLA integer,
    BDCTALON varchar(40),
    BDNOMTPLA varchar(100),
    BDCODFOR integer,
    BDNOMFOR varchar(100),
    BDCODCC integer,
    BDCTALONCC varchar(20),
    BDNOMCC varchar(40),
    BDVALORCORRIGIDOANTERIOR numeric(15,2),
    BDCORRECAOPERIODO numeric(15,2),
    BDVALORCORRIGIDOATUAL numeric(15,2),
    BDDEPRECIACAOACUMULADAANTERIOR numeric(15,2),
    BDDEPRECIACAOPERIODO numeric(15,2),
    BDDEPRECIACAOPERIODOMOEDA numeric(15,6),
    BDDEPRECIACAOACUMULADAATUAL numeric(15,2),
    BDDEPRECIACAOACUMULADAATUALMOE numeric(15,6),
    BDCORRECAOMONETARIADEPRECIACAO numeric(15,2),
    BDVALORRESIDUALCONTABIL numeric(15,2),
    BDVALORRESIDUALCONTABILMOEDA numeric(15,6),
    BDTOTALMESESDEPRECIACAO integer,
    BDMESESDEPRECIADOS integer,
    BDMESESDEPRECIAR integer,
    BDTAXADEPRECIACAOANUAL numeric(6,6),
    BDDATATAXADEPRECIACAO date,
    BDREFERENCIA varchar(7),
    BDNATBEM varchar(20),
    BDESPECIE varchar(20),
    BDDATAAQUISICAO date,
    BDVALORMOEDA numeric(15,6),
    BDVALORAQUISICAOMOEDA numeric(15,6),
    BDVALORCORRIGIDOANTERIORMOEDA numeric(15,6),
    BDVALORAQUISICAOORIGINAL numeric(15,2),
    BDVALORBAIXA numeric(15,2),
    BDSOMARDEPRECIACAO integer,
    BDCODORIGBEM integer,
    BDTIPOBEM integer,
    BDCLACOD varchar(21),
    BDULTIMOAGREGADO integer,
    BDVALORRESIDUAL numeric(15,6),
    BDCODBAI integer,
    BDBAIXAADICIONAL integer,
    BDDATAINICALC date,
    BDVALVENBAI numeric(15,6),
    BDCODMOT integer,
    BDDESCMOT varchar(50),
    BDSALDOQTD integer,
    BDQTDBAIXA integer,
    BDOBSBAIXA varchar(200),
    BDQUANTIDADEBEM integer,
    BDNRCHAPA varchar(20),
    BDVALAQUIBEMORIGINAL numeric(15,2),
    BDCGCTER varchar(18))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_CRITICA_LANC(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRCHAVEINI INTEGER,
PRCHAVEFIM INTEGER,
PRLOTEINI VARCHAR(10),
PRLOTEFIM VARCHAR(10),
PRTRANSINI INTEGER,
PRTRANSFIM INTEGER,
PRCOLUNAS INTEGER,
PRLCC VARCHAR(8192),
PRTOTDIA INTEGER,
PRTOTMES INTEGER,
PRTOTANO INTEGER,
PRTOTLOTE INTEGER,
PRDATAS VARCHAR(1024),
PRLANCSEMTRANS INTEGER,
PRREFEMP INTEGER,
PRCODTIPOLANC INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRSTATUSTRANSACAO INTEGER = 0)
 RETURNS(PRCHAVE INTEGER,
PRDATA DATE,
PRCODIGO_CREDITO INTEGER,
PRVALOR_CREDITO NUMERIC(15,2),
PRCODIGO_DEBITO INTEGER,
PRVALOR_DEBITO NUMERIC(15,2),
PRCOMPLEMENTO VARCHAR(200),
PRHISTORICO VARCHAR(200),
PREMPRESA INTEGER,
PRNOMEEMPRESA DM_BDNOMEMP,
PRCODTPCC INTEGER,
PRCNPJEMP VARCHAR(18),
PRLOTE VARCHAR(10),
PRDCTO VARCHAR(15),
PRCODMATRIZ INTEGER,
PRDEBCRE INTEGER,
PRVALOR NUMERIC(15,2),
PRVALORRAT NUMERIC(15,2),
PRQUEBRADIA DATE,
PRQUEBRAMES VARCHAR(7),
PRQUEBRARANO VARCHAR(4),
PRQUEBRALOTE VARCHAR(10),
PRSEQUENCIA INTEGER,
PRNOMECC VARCHAR(40),
PRCODEMPFILIAL INTEGER,
PRCONTAB INTEGER,
PRDESCTIPOLANC VARCHAR(100),
BDTRANSACAO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_DIARIO(PRCODEMP INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRMODELO INTEGER,
PRFILIAIS VARCHAR(1024),
PRLCC VARCHAR(8192),
PRDETALHARCTAPARTICIPANTE INTEGER,
PRREFEMP INTEGER,
PRAGRUPAR VARCHAR(1024),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARFILIAL INTEGER)
 RETURNS(PRCHAVE INTEGER,
PRDATA DATE,
PRCODIGO_CREDITO INTEGER,
PRCLASSI_CREDITO VARCHAR(40),
PRVALOR_CREDITO NUMERIC(15,2),
PRCODIGO_DEBITO INTEGER,
PRCLASSI_DEBITO VARCHAR(40),
PRVALOR_DEBITO NUMERIC(15,2),
PRCOMPLEMENTO VARCHAR(200),
PRHISTORICO VARCHAR(400),
PREMPRESA INTEGER,
PRNOMEEMPRESA DM_BDNOMEMP,
PRCODTPCC INTEGER,
PRCNPJEMP VARCHAR(18),
PRLOTE VARCHAR(10),
PRDCTO VARCHAR(15),
PRCODMATRIZ INTEGER,
PRDETALHE VARCHAR(250),
PREMPRESAFILIAL INTEGER,
PRCHAVEONLINE VARCHAR(120),
PRTRANSACAO INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_MOV_DIARIO(PRCODEMP VARCHAR(1024),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRREFEMP INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(DATA DATE,
DEB NUMERIC(15,2),
CRE NUMERIC(15,2),
SAL NUMERIC(15,2),
DEBANT NUMERIC(15,2),
CREANT NUMERIC(15,2),
SALANT NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_MOV_MENSAL(
    PRCODEMP INTEGER,
    PRCONTA INTEGER,
    PRCC VARCHAR(8192),
    PRANOINICIAL INTEGER,
    PRANOFINAL INTEGER,
    PRREFEMP INTEGER,
    PRPARTICIPANTE INTEGER,
    PRIGNORAZERAMENTO INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER) 
RETURNS (
    BDDEB01 NUMERIC(15,2),
    BDDEB02 NUMERIC(15,2),
    BDDEB03 NUMERIC(15,2),
    BDDEB04 NUMERIC(15,2),
    BDDEB05 NUMERIC(15,2),
    BDDEB06 NUMERIC(15,2),
    BDDEB07 NUMERIC(15,2),
    BDDEB08 NUMERIC(15,2),
    BDDEB09 NUMERIC(15,2),
    BDDEB10 NUMERIC(15,2),
    BDDEB11 NUMERIC(15,2),
    BDDEB12 NUMERIC(15,2),
    BDCRE01 NUMERIC(15,2),
    BDCRE02 NUMERIC(15,2),
    BDCRE03 NUMERIC(15,2),
    BDCRE04 NUMERIC(15,2),
    BDCRE05 NUMERIC(15,2),
    BDCRE06 NUMERIC(15,2),
    BDCRE07 NUMERIC(15,2),
    BDCRE08 NUMERIC(15,2),
    BDCRE09 NUMERIC(15,2),
    BDCRE10 NUMERIC(15,2),
    BDCRE11 NUMERIC(15,2),
    BDCRE12 NUMERIC(15,2),
    BDMOV01 NUMERIC(15,2),
    BDMOV02 NUMERIC(15,2),
    BDMOV03 NUMERIC(15,2),
    BDMOV04 NUMERIC(15,2),
    BDMOV05 NUMERIC(15,2),
    BDMOV06 NUMERIC(15,2),
    BDMOV07 NUMERIC(15,2),
    BDMOV08 NUMERIC(15,2),
    BDMOV09 NUMERIC(15,2),
    BDMOV10 NUMERIC(15,2),
    BDMOV11 NUMERIC(15,2),
    BDMOV12 NUMERIC(15,2),
    BDSAL01 NUMERIC(15,2),
    BDSAL02 NUMERIC(15,2),
    BDSAL03 NUMERIC(15,2),
    BDSAL04 NUMERIC(15,2),
    BDSAL05 NUMERIC(15,2),
    BDSAL06 NUMERIC(15,2),
    BDSAL07 NUMERIC(15,2),
    BDSAL08 NUMERIC(15,2),
    BDSAL09 NUMERIC(15,2),
    BDSAL10 NUMERIC(15,2),
    BDSAL11 NUMERIC(15,2),
    BDSAL12 NUMERIC(15,2),
    BDSALTOTDEB NUMERIC(15,2),
    BDSALTOTCRE NUMERIC(15,2),
    BDSALTOTMOV NUMERIC(15,2),
    BDSALTOTATU NUMERIC(15,2),
    BDANO INTEGER,
    BDDEBANT NUMERIC(15,2),
    BDCREANT NUMERIC(15,2),
    BDMOVANT NUMERIC(15,2),
    BDSALANT NUMERIC(15,2),
    BDGRPCTA INTEGER) 
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_PLANOS_TPLA(PRCODPLANOPADRAO INTEGER,
PRCAMPOPESQUISA VARCHAR(20),
PRCONTEUDO VARCHAR(20),
PRPESQUISAINICIO INTEGER)
 RETURNS(BDCODTPLA INTEGER,
BDCTALON VARCHAR(40),
BDTIPCTA INTEGER,
BDNOMCTA VARCHAR(100),
BDAPECTA VARCHAR(20),
BDRELCTA INTEGER,
BDFILTROGER VARCHAR(20),
BDFORMULA VARCHAR(200),
BDCONDICAO VARCHAR(200))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_CONTAS(PRCODEMP VARCHAR(1024),
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRLCC VARCHAR(8192),
PRORDEMPRESA INTEGER,
PRREFEMP INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARFILIAL INTEGER)
 RETURNS(PRHISTORICO VARCHAR(100),
PRDATA DATE,
PRCHAVE INTEGER,
PRCONTA INTEGER,
PRCONTRA INTEGER,
PRCREDITO NUMERIC(15,2),
PRDEBITO NUMERIC(15,2),
PRCONCILIADO VARCHAR(5),
PREMPRESA INTEGER,
PRNOMEEMPRESA DM_BDNOMEMP,
PRCC INTEGER,
PRNOME_CONTA VARCHAR(100),
PRCLASS_CONTA VARCHAR(40),
PRCLASS_CONTRA VARCHAR(40),
PRNOME_CONTA_CONTRA VARCHAR(100),
PRLOTE VARCHAR(10),
PRDCTO VARCHAR(15),
PRCOMPL VARCHAR(200),
PRCNPJEMP VARCHAR(18),
PRCODMATRIZ INTEGER,
PRGRPCTA INTEGER,
PRCODHIST INTEGER,
PRCODPLAPADRAO INTEGER,
PRCODTPHI INTEGER,
PRPARTICIPANTECONTA INTEGER,
PRPARTICIPANTECONTRA INTEGER,
PRCODTERCEIROCONTA INTEGER,
PRCODTERCEIROCONTRA INTEGER,
PRCODEMPFILIAL INTEGER,
PRTIPOLAN INTEGER,
PRCHAVEONLINE VARCHAR(120))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_CONTAS_X (
    PRCODEMP VARCHAR(1024),
    PRREFEMP INTEGER,
    PRCLASSIFICACAO_INICIAL VARCHAR(40),
    PRCLASSIFICACAO_FINAL VARCHAR(40),
    PRDATA_INICIAL DATE,
    PRDATA_FINAL DATE,
    PRINDICE INTEGER,
    PRDETALHARCC INTEGER,
    PRLCC DM_MAXVARCHAR,
    PRLANCAMENTOSEMCC INTEGER,
    PRDETALHARCTAPARTICIPANTE INTEGER,
    PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
    PRCONCATENACODPARTICIPANTE INTEGER,
    PRPARTINI INTEGER,
    PRPARTFIN INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRCONTASSEMMOVIMENTO INTEGER,
    PRIGNORAZERAMENTO INTEGER = 0,
    PRDETALHAREMPREENDIMENTO INTEGER = 0,
    PRDETALHARUNIDIMOB INTEGER = 0,
    PRPRMOSTRARPROPUNIDADE INTEGER = 0,
    PRPRODRURAL DM_BOOLEAN = 'FALSE',
    PRIMOVEIS VARCHAR(1024) = '',
    PRLISTAPART VARCHAR(10000) = '',
    PRAGRUPARPARTICIPANTEPORCPF INTEGER = 0,
    PRPLANO_SECUNDARIO INTEGER = 0,
    PRFILTRAREMPREENDIMENTO VARCHAR(1024) = '',
    PRFILTRARUNIDIMOBILIARIA VARCHAR(1024) = '',
    PRNAOMOSTRARLANCSEMDADOSRU DM_BOOLEAN = 'FALSE',
    PRFILTIPOLAN varchar(3200) = '')
RETURNS (
    PRHISTORICO VARCHAR(100),
    PRDATA DATE,
    PRCHAVE INTEGER,
    PRCONTA INTEGER,
    PRCONTRA INTEGER,
    PRCREDITO NUMERIC(18,2),
    PRDEBITO NUMERIC(18,2),
    PRCONCILIADO VARCHAR(5),
    PREMPRESA INTEGER,
    PRNOMEEMPRESA DM_BDNOMEMP,
    PRCC INTEGER,
    PRNOME_CONTA VARCHAR(300),
    PRNOME_CONTA_ORIGINAL VARCHAR(300),
    PRCLASS_CONTA VARCHAR(40),
    PRCLASS_CONTRA VARCHAR(40),
    PRNOME_CONTA_CONTRA VARCHAR(300),
    PRLOTE VARCHAR(10),
    PRDCTO VARCHAR(15),
    PRCOMPL VARCHAR(200),
    PRCNPJEMP VARCHAR(18),
    PRCODMATRIZ INTEGER,
    PRGRPCTA INTEGER,
    PRCODHIST INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRCODTPHI INTEGER,
    PRPARTICIPANTECONTA INTEGER,
    PRPARTICIPANTECONTRA INTEGER,
    PRCODTERCEIROCONTA INTEGER,
    PRCODTERCEIROCONTRA INTEGER,
    PRCGC_CONTA VARCHAR(18),
    PRCODEMPFILIAL INTEGER,
    PRTIPOLANCFILIAL INTEGER,
    PRTIPOLAN INTEGER,
    PRCHAVEONLINE VARCHAR(120),
    PRCODCENTRO INTEGER,
    PRTRANSACAO INTEGER,
    PRTRANFECHADA DM_BOOLEAN,
    PRCONCILIACAOPENDENTE INTEGER,
    PRCLANOM VARCHAR(355),
    PRDEBCRE INTEGER,
    PREMPREENDIMENTO INTEGER,
    PRUNIDIMOB INTEGER,
    PRNATUREZALAN INTEGER,
  PRCTALCDPR VARCHAR(6),
    PRPART_PR VARCHAR(18),
    PRCODPART_PR INTEGER,
    PRTIPLANPR VARCHAR(6),
    PRCODIMOVRUR INTEGER,
    PRTIPDOCPR INTEGER,
    PRSALRELCONCILIACOES varchar(5))
AS
 BEGIN SUSPEND; END
^
create or alter procedure SP_COMMIT_IMP_LANC_CONTABIL (
    PRSESSAO integer)
AS
BEGIN 
END^

create or alter procedure SP_ATUALIZAR_TMP_VSUC_TLAN(
    PRSESSAO integer,
    PREMPRESA integer,
    PRULTCHAVE integer,
    PRIDTERMINAL integer,
    PRVERIFICADUPLICADO integer)
as
BEGIN 
END^

create or alter procedure SP_ATU_TMP_VSUC_COMPL_ASTERISCO (
    PRSESSAO integer)
as
BEGIN 
END^

create or alter procedure SP_ATUALIZAR_TMP_VSUC_TLCC (
    PRSESSAO integer,
    PREMPRESA integer,
    PRULTCHAVE integer,
    PRIDTERMINAL integer)
as
begin
END^

create or alter procedure SP_ATUALIZAR_TMP_VSUC_TLPR (
    PRSESSAO integer,
    PREMPRESA integer,
    PRULTCHAVE integer,
    PRIDTERMINAL integer)
as
begin
END^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_SALDO(PRCODEMP VARCHAR(1024),
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRINDICE INTEGER,
PRLCC VARCHAR(8192),
PRORDEMPRESA INTEGER,
PRREFEMP INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
BDCONCILIADOS INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRAGRUPAR VARCHAR(1024),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARFILIAL INTEGER)
 RETURNS(BDHISTORICO VARCHAR(400),
BDDATA DATE,
BDCHAVE INTEGER,
BDCONTA INTEGER,
BDCONTRA INTEGER,
BDCREDITO NUMERIC(15,2),
BDDEBITO NUMERIC(15,2),
BDSALDO NUMERIC(15,2),
BDCONCILIADO VARCHAR(5),
BDEMPRESA INTEGER,
BDNOMEEMPRESA VARCHAR(100),
BDCODCENTRO INTEGER,
BDCC INTEGER,
BDNOME_CONTA VARCHAR(100),
BDCLASS_CONTA VARCHAR(40),
BDCOD_TERCEIRO_CONTA INTEGER,
BDCLASS_CONTRA VARCHAR(40),
BDNOME_CONTA_CONTRA VARCHAR(100),
BDCOD_TERCEIRO_CONTRA INTEGER,
BDVALOR NUMERIC(15,2),
BDORDSALDO INTEGER,
BDLOTE VARCHAR(10),
BDDCTO VARCHAR(15),
BDCOMPL VARCHAR(200),
BDCNPJEMP VARCHAR(18),
BDSALDOANTERIOR NUMERIC(15,2),
BDVALORSEMSINAL NUMERIC(15,2),
BDGRUPOCONTA INTEGER,
BDCODHIST INTEGER,
BDCODPLAPADRAO INTEGER,
BDREF VARCHAR(8),
BDCODTPHI INTEGER,
BDEMPRESAFILIAL INTEGER,
BDVLRCONCILIADO NUMERIC(15,2),
BDVLRACONCILIAR NUMERIC(15,2),
BDCHAVEONLINE VARCHAR(120))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CREDOR (
PRCODEMP         VARCHAR(1024),
PRDATINI         DATE,
PRDATFIN         DATE,
PRINDICE         INTEGER,
PRCONTABILIZACAO INTEGER,
PRCODPLAPADRAO   INTEGER,
PRCONTA          INTEGER,
PRREFEMP         INTEGER)
RETURNS (
BDCODEMP         INTEGER,
BDNOMEMP         DM_BDNOMEMP,
BDCONTA          INTEGER,
BDDATA           DATE,
BDCTALON         DM_CLASSCONTAS,
BDNOMCTA         VARCHAR(100),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDSALDO_DEB      NUMERIC(15,2),
BDSALDO_CRE      NUMERIC(15,2),
BDMOVIMENTO      NUMERIC(15,2),
BDSALDO_ATUAL    NUMERIC(15,2),
BDGRUPOCTA       INTEGER)
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_SALDO_X(
    PRCODEMP VARCHAR(1024),
    PRCLASSIFICACAO_INICIAL VARCHAR(40),
    PRCLASSIFICACAO_FINAL VARCHAR(40),
    PRDATA_INICIAL DATE,
    PRDATA_FINAL DATE,
    PRINDICE INTEGER,
    PRDETALHARCC INTEGER,
    PRLCC DM_MAXVARCHAR,
    PRLANCAMENTOSEMCC INTEGER,
    PRORDEMPRESA INTEGER,
    PRREFEMP INTEGER,
    PRDETALHARCTAPARTICIPANTE INTEGER,
    PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
    PRCONCATENACODPARTICIPANTE INTEGER,
    BDCONCILIADOS VARCHAR(20),
    PRPARTINI INTEGER,
    PRPARTFIN INTEGER,
    PRAGRUPAR VARCHAR(1024),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRDCDOISLANCAMENTOS INTEGER,
    PRCONTASSEMMOVIMENTO INTEGER,
    PRIGNORAZERAMENTO INTEGER = 0,
    PRIGNORASALDOANTERIOR INTEGER = 0,
    PRDETALHARFILIAL INTEGER = 0,
    PRORDENACAO INTEGER = 0,
    PRDETALHAREMPREENDIMENTO INTEGER = 0,
    PRDETALHARUNIDIMOB INTEGER = 0,
    PRMOSTRARPROPUNIDADE INTEGER = 0,
    PRSOLANSEMEMPREE INTEGER = 0,
    PRORDENANATUREZA INTEGER = 0,
    PRPRODRURAL DM_BOOLEAN = 'FALSE',
    PRIMOVEIS VARCHAR(1024) = '',
    PRLISTAPART VARCHAR(10000) = '',
    PRAGRUPARPARTICIPANTEPORCPF INTEGER = 0,
    PRMOSTRARCC INTEGER = 0,
    PRPLANO_SECUNDARIO INTEGER = 0,
    PREMPREENDIMENTO VARCHAR(1024) = '',
    PRUNIDIMOBILIARIA VARCHAR(1024) = '',
    PRNAOMOSTRARLANCSEMDADOSRU DM_BOOLEAN = 'FALSE',
    PRFILTIPOLAN varchar(3200) = '')
RETURNS (
    BDHISTORICO VARCHAR(100),
    BDDATA DATE,
    BDCHAVE INTEGER,
    BDCONTA INTEGER,
    BDCONTRA INTEGER,
    BDCREDITO NUMERIC(15,2),
    BDDEBITO NUMERIC(15,2),
    BDSALDO NUMERIC(15,2),
    BDCONCILIADO VARCHAR(5),
    BDEMPRESA INTEGER,
    BDNOMEEMPRESA VARCHAR(100),
    BDCODCENTRO INTEGER,
    BDCC INTEGER,
    BDNOME_CONTA VARCHAR(300),
    BDNOME_CONTA_ORIGINAL VARCHAR(300),
    BDCLASS_CONTA VARCHAR(40),
    BDCOD_TERCEIRO_CONTA INTEGER,
    BDCGC_CONTA VARCHAR(18),
    BDCLASS_CONTRA VARCHAR(40),
    BDNOME_CONTA_CONTRA VARCHAR(300),
    BDCOD_TERCEIRO_CONTRA INTEGER,
    BDVALOR NUMERIC(15,2),
    BDORDSALDO INTEGER,
    BDLOTE VARCHAR(10),
    BDDCTO VARCHAR(15),
    BDCOMPL VARCHAR(200),
    BDCNPJEMP VARCHAR(18),
    BDSALDOANTERIOR NUMERIC(15,2),
    BDVALORSEMSINAL NUMERIC(15,2),
    BDGRUPOCONTA INTEGER,
    BDCODHIST INTEGER,
    BDCODPLAPADRAO INTEGER,
    BDREF VARCHAR(8),
    BDCODTPHI INTEGER,
    BDEMPRESAFILIAL INTEGER,
    BDTIPOLANCFILIAL INTEGER,
    BDVLRCONCILIADO NUMERIC(15,2),
    BDVLRACONCILIAR NUMERIC(15,2),
    BDCHAVEONLINE VARCHAR(120),
    BDTRANSACAO INTEGER,
    BDTRANFECHADA DM_BOOLEAN,
    BDTIPOLAN INTEGER,
    BDSEQCTA VARCHAR(7),
    BDCLANOM VARCHAR(355),
    BDCONCILIACAOPENDENTE INTEGER,
    BDCC_CONTRA INTEGER,
    BDEMPREENDIMENTO INTEGER,
    BDUNIDIMOB INTEGER,
    BDNATUREZALAN INTEGER,
    BDCTALCDPR VARCHAR(6),
    BDPART_PR VARCHAR(18),
    BDCODPART_PR INTEGER,
    BDTIPLANPR VARCHAR(6),
    BDCODIMOVRUR INTEGER,
    BDTIPDOCPR INTEGER,
    BDSALRELCONCILIACOES DM_BOOLEAN)
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_SALDO2(PRCODEMP VARCHAR(1024),
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRINDICE INTEGER,
PRLCC VARCHAR(8192),
PRORDEMPRESA INTEGER,
PRREFEMP INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
BDCONCILIADOS INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARFILIAL INTEGER)
 RETURNS(BDHISTORICO VARCHAR(400),
BDDATA DATE,
BDCHAVE INTEGER,
BDCONTA INTEGER,
BDCONTRA INTEGER,
BDCREDITO NUMERIC(15,2),
BDDEBITO NUMERIC(15,2),
BDSALDO NUMERIC(15,2),
BDCONCILIADO VARCHAR(5),
BDEMPRESA INTEGER,
BDNOMEEMPRESA VARCHAR(80),
BDCC INTEGER,
BDNOME_CONTA VARCHAR(100),
BDCLASS_CONTA VARCHAR(30),
BDCOD_TERCEIRO_CONTA INTEGER,
BDCLASS_CONTRA VARCHAR(20),
BDNOME_CONTA_CONTRA VARCHAR(100),
BDCOD_TERCEIRO_CONTRA INTEGER,
BDVALOR NUMERIC(15,2),
BDORDSALDO INTEGER,
BDLOTE VARCHAR(10),
BDDCTO VARCHAR(15),
BDCOMPL VARCHAR(200),
BDCNPJEMP VARCHAR(18),
BDSALDOANTERIOR NUMERIC(15,2),
BDVALORSEMSINAL NUMERIC(15,2),
BDGRUPOCONTA INTEGER,
BDCODHIST INTEGER,
BDCODPLAPADRAO INTEGER,
BDREF VARCHAR(8),
BDCODTPHI INTEGER,
BDEMPRESAFILIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_REL_ORCA (
    PRCODEMP VARCHAR(2048),
    PRDATINI DATE,
    PRDATFIN DATE,
    PRIGNORA_ZERAMENTO INTEGER,
    PRCTAINI INTEGER,
    PRCTAFIN INTEGER,
    PRINDICE INTEGER,
    PRCODTPCC VARCHAR(8192),
    PRREFEMP INTEGER,
    PRLANSEMCC INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP VARCHAR(18),
    BDCODMATRIZ INTEGER,
    BDCODPLAPADRAO INTEGER,
    BDCODCTA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDTIPCTA SMALLINT,
    BDCODTPCC INTEGER,
    BDNOMTPCC VARCHAR(40),
    BDSALDOREALIZADO NUMERIC(15,2),
    BDGRPCTA SMALLINT,
    BDTPCCLON VARCHAR(20),
    BDFORMULA VARCHAR(200),
    BDRELCTA INTEGER,
    BDNEGFOR VARCHAR(5),
    BDSUBLFOR VARCHAR(5),
    BDLINSEMVALFOR VARCHAR(5))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_RELESTATIST_GRA(PRCODEMP VARCHAR(10000),
PRCODUSU INTEGER,
PRTIPCOMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDTIPO VARCHAR(20),
BDMES VARCHAR(8),
BDMESVALOR INTEGER,
BDCOLOR VARCHAR(10))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_RELESTATISTGRA(PRCODEMP VARCHAR(2048),
PRTIPCOMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDTIPO VARCHAR(20),
BDMES01 INTEGER,
BDMES02 INTEGER,
BDMES03 INTEGER,
BDMES04 INTEGER,
BDMES05 INTEGER,
BDMES06 INTEGER,
BDMES07 INTEGER,
BDMES08 INTEGER,
BDMES09 INTEGER,
BDMES10 INTEGER,
BDMES11 INTEGER,
BDMES12 INTEGER,
BDTOTAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_RELESTATISTICA(PRCODEMP VARCHAR(10000),
PRCODUSU INTEGER,
PRTIPCOMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDTIPO VARCHAR(20),
BDMES01 INTEGER,
BDMES02 INTEGER,
BDMES03 INTEGER,
BDMES04 INTEGER,
BDMES05 INTEGER,
BDMES06 INTEGER,
BDMES07 INTEGER,
BDMES08 INTEGER,
BDMES09 INTEGER,
BDMES10 INTEGER,
BDMES11 INTEGER,
BDMES12 INTEGER,
BDTOTAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

create or alter procedure VSUC_SP_RETORNA_SALDO (
    PRCODEMP varchar(1024),
    PRCONTA integer,
    PRDATAINI date,
    PRDATAFIM date,
    PRIGNORAZERAMENTO smallint,
    PRCC integer,
    PRRELCTA integer,
    PRREFEMP integer,
    PRFORM varchar(10),
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer)
returns (
    MOVIMENTO_ANT_CRE numeric(15,2),
    SALDO_ANT_DEB numeric(15,2),
    SALDO_ANT_CRE numeric(15,2),
    SALDO_DEB numeric(15,2),
    SALDO_CRE numeric(15,2),
    SALDO_ATUAL numeric(15,2),
    SALDO_ANTERIOR numeric(15,2),
    MOVIMENTO_ANT_DEB numeric(15,2),
    SALDO_MOVIMENTO numeric(15,2))
 AS
 BEGIN SUSPEND; END
^


CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONS_ORCA(PRCODEMP INTEGER,
PRCONTA INTEGER,
PRCODTPCC INTEGER,
PRANO INTEGER,
PRREFEMP INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDSAL01 NUMERIC(15,2),
BDSAL02 NUMERIC(15,2),
BDSAL03 NUMERIC(15,2),
BDSAL04 NUMERIC(15,2),
BDSAL05 NUMERIC(15,2),
BDSAL06 NUMERIC(15,2),
BDSAL07 NUMERIC(15,2),
BDSAL08 NUMERIC(15,2),
BDSAL09 NUMERIC(15,2),
BDSAL10 NUMERIC(15,2),
BDSAL11 NUMERIC(15,2),
BDSAL12 NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS(PRCODIGOEMP INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO INTEGER,
PRCC INTEGER,
PRCODPLAPADRAO INTEGER,
PRLANCSEMCC INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDATAHORA VARCHAR(30),
PRNIVEISCONTA VARCHAR(50),
PRTODASASCONTAS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(CODEMP INTEGER,
CODPLAPADRAO INTEGER,
CONTA INTEGER,
CLASSIFICACAO VARCHAR(40),
NOMECONTA VARCHAR(100),
GRUPOCONTA SMALLINT,
RELCONTA INTEGER,
CLANOM VARCHAR(140),
TIPCONTA SMALLINT,
SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
FORMULA VARCHAR(200),
PARTICIPANTE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS_CC(PRCODEMP INTEGER,
PRCODCTAINI INTEGER,
PRCODCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCODTPCC INTEGER,
PRCODPLAPADRAO INTEGER,
PRNAOMOSTRACONTACOMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDGRPCTA SMALLINT,
BDRELCTA INTEGER,
BDTIPCTA SMALLINT,
BDSALANTDEB NUMERIC(15,2),
BDSALANTCRE NUMERIC(15,2),
BDSALDEB NUMERIC(15,2),
BDSALCRE NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDSALANT NUMERIC(15,2),
BDFORMULA VARCHAR(200))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS_X (
    PRCODIGOEMP INTEGER,
    PRCONTAINICIAL INTEGER,
    PRCONTAFINAL INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRINDICE INTEGER,
    PRIGNORAZERAMENTO INTEGER,
    PRCC INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRLANCSEMCC INTEGER,
    PRNAOMOSTRACONTACOMP INTEGER,
    PRCONSOLIDADA INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PREMPRESAS VARCHAR(2048),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRDRE INTEGER = 0,
    PRTODOPLANOCONTAS INTEGER = 0,
    PRSOMENTEMOVIMENTO INTEGER = 0,
    PRPLANOGRPECO integer = 0,
    PREMPRESAGRPECO integer = 0,
    PRGRPECO integer = 0,
    PRIGNZERPERANT integer = 0,
    PRTIPOLAN varchar(3200) = '',
    PRELIMINACOESK300K315 integer = 0)
returns (
    CODEMP integer,
    CODPLAPADRAO integer,
    CONTA integer,
    CLASSIFICACAO varchar(40),
    NOMECONTA varchar(100),
    GRUPOCONTA smallint,
    RELCONTA integer,
    CLANOM varchar(140),
    TIPCONTA smallint,
    SALDO_ANT_DEB numeric(15,2),
    SALDO_ANT_CRE numeric(15,2),
    SALDO_DEB numeric(15,2),
    SALDO_CRE numeric(15,2),
    SALDO_ATUAL numeric(15,2),
    SALDO_ANTERIOR numeric(15,2),
    FORMULA varchar(200),
    PARTICIPANTE integer,
    APECTA varchar(20),
    PERTENCECONTA integer,
    SALDO_ANT_DEB_DRE numeric(15,2),
    SALDO_ANT_CRE_DRE numeric(15,2),
    SALDO_ANTERIOR_DRE numeric(15,2),
    SALDO_SEM_CONCILIACAO numeric(15,2),
    SALDO_ATUAL_REAL numeric(15,2),
    DATAULTLANCAMENTO date)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS_XZ (
    PRCODIGOEMP INTEGER,
    PRCONTAINICIAL INTEGER,
    PRCONTAFINAL INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRINDICE INTEGER,
    PRIGNORAZERAMENTO INTEGER,
    PRCC VARCHAR(32000),
    PRCODPLAPADRAO INTEGER,
    PRLANCSEMCC INTEGER,
    PRORDEM INTEGER,
    PRNAOMOSTRACONTACOMP INTEGER,
    PRCONSOLIDADA INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRDRE INTEGER = 0,
    PRNIVELCC INTEGER = 0,
    PRSOMENTEMOVIMENTO INTEGER = 0,
    PRDETALHARCCEMPREEND integer = 0,
    PRCODEMPREENDIMENTO varchar(32000) = '' /* COLLATE WIN1252 - default */ ,
    PRTIPOLAN varchar(3200) = '',
    PRELIMINACOESK300K315 integer = 0)
returns (
    BDCODEMP integer,
    BDCODPLAPADRAO integer,
    BDCONTA integer,
    BDCLASSIFICACAO varchar(40),
    BDNOMECONTA varchar(100),
    BDGRUPOCONTA smallint,
    BDRELCONTA integer,
    BDCLANOM varchar(140),
    BDTIPCONTA smallint,
    BDSALDO_ANT_DEB numeric(15,2),
    BDSALDO_ANT_CRE numeric(15,2),
    BDSALDO_DEB numeric(15,2),
    BDSALDO_CRE numeric(15,2),
    BDSALDO_ATUAL numeric(15,2),
    BDSALDO_ANTERIOR numeric(15,2),
    BDFORMULA varchar(200),
    BDPARTICIPANTE integer,
    BDAPECTA varchar(20),
    BDPERTENCECONTA integer,
    BDSALDO_ANT_DEB_DRE numeric(15,2),
    BDSALDO_ANT_CRE_DRE numeric(15,2),
    BDSALDO_ANTERIOR_DRE numeric(15,2),
    BDCODTPCC integer,
    BDNOMTPCC varchar(40),
    BDTPCCLON varchar(20),
    BDSALDO_ATUAL_REAL numeric(15,2),
    BDFILTROCC varchar(200),
    BDDATAULTLANC date)

 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_LANC(PRCODEMP INTEGER,
PRREFEMP INTEGER,
PRCONTA_DEB INTEGER,
PRCONTA_CRED INTEGER,
PRDATA DATE,
PRPARTICIPANTED INTEGER,
PRPARTICIPANTEC INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFIIALCONSOLIDADO INTEGER)
 RETURNS(ANT_AO_DIA_D NUMERIC(15,2),
DEB_DO_DIA_D NUMERIC(15,2),
CRED_DO_DIA_D NUMERIC(15,2),
ATUAL_DO_DIA_D NUMERIC(15,2),
ANT_AO_DIA_C NUMERIC(15,2),
DEB_DO_DIA_C NUMERIC(15,2),
CRED_DO_DIA_C NUMERIC(15,2),
ATUAL_DO_DIA_C NUMERIC(15,2),
ANT_AO_MES_C NUMERIC(15,2),
ATUAL_DO_MES_C NUMERIC(15,2),
ANT_AO_MES_D NUMERIC(15,2),
DEB_DO_MES_D NUMERIC(15,2),
CRED_DO_MES_D NUMERIC(15,2),
MOV_DO_MES_D NUMERIC(15,2),
ATUAL_DO_MES_D NUMERIC(15,2),
ANT_DO_MES_C NUMERIC(15,2),
DEB_DO_MES_C NUMERIC(15,2),
CRED_DO_MES_C NUMERIC(15,2),
MOV_DO_MES_C NUMERIC(15,2),
ATUTAL_DO_MES_C NUMERIC(15,2))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_ORCA (
    PRCODIGOEMP INTEGER,
    PRCONTAINICIAL INTEGER,
    PRCONTAFINAL INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRINDICE INTEGER,
    PRIGNORAZERAMENTO INTEGER,
    PRCC INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PRTODASASCONTAS INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRLANCSEMCC INTEGER = 0)
RETURNS (
    CODEMP INTEGER,
    CODPLAPADRAO INTEGER,
    CONTA INTEGER,
    CLASSIFICACAO VARCHAR(40),
    NOMECONTA VARCHAR(100),
    GRUPOCONTA SMALLINT,
    RELCONTA INTEGER,
    TIPCONTA SMALLINT,
    BDORCADO INTEGER,
    BDREALIZADO NUMERIC(15,2),
    FORMULA VARCHAR(200))
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDOS_CTA_PART(PRCODEMP INTEGER,
PRCODPLAPADRAO INTEGER,
PRDTINICIAL DATE,
PRDTFINAL DATE,
PRCONTA INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRCODTERCEIRO INTEGER,
PRRETORNAAPENASCONTAS INTEGER,
PRCONCILIADOS INTEGER,
PREMPRESAS VARCHAR(2048),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDNOME VARCHAR(100),
BDCLASSIFICACAO VARCHAR(40),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_ANT_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALDO_ANT_CRE NUMERIC(15,2),
BDSALDO_ATUAL NUMERIC(15,2),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDCODPARTICIPANTE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_GET_CLASSIFICACAO_NIVEL (
    PRCLASSIFICACAO VARCHAR(100),
    PRNIVEL INTEGER)
RETURNS (
    BDCLASSIFICACAO VARCHAR(100))
AS
BEGIN
  SUSPEND;
END
^

create or alter procedure VSUC_SP_RETORNA_SALDOS_CTAPARTY (
    PRCODEMP integer,
    PRCODPLAPADRAO integer,
    PRDTINICIAL date,
    PRDTFINAL date,
    PRCONTA integer,
    PRINDICE integer,
    PRIGNORAZERAMENTO integer,
    PRCODTERCEIRO integer,
    PRCONCILIADOS varchar(20),
    PREMPRESAS varchar(2048),
    PRCONTABILIZACAO integer,
    PRAGRUPARPARTICIPANTEPORCNPJ integer = 0,
    PRCC DM_MAXVARCHAR = '',
    PRLANCSEMCC integer = 0,
    PRAGRUPARPARTICIPANTEPORCPF integer = 0,
    PRNIVELCC integer = 0,
    PRSOMENTEMOVIMENTO integer = 0,
    PRREFEMP integer = 0,
    PRTODOSPART varchar(2048) = '',
    PRTIPOLAN varchar(3200) = '',
    PREMPRESAGRPECO integer = 0,
    PRGRPECO integer = 0,
    PRELIMINACOESK300K315 integer = 0)
returns (
    BDNOME varchar(100),
    BDCLASSIFICACAO varchar(40),
    BDSALDO_DEB numeric(15,2),
    BDSALDO_ANT_DEB numeric(15,2),
    BDSALDO_CRE numeric(15,2),
    BDSALDO_ANT_CRE numeric(15,2),
    BDMOVIMENTO numeric(15,2),
    BDSALDO_ATUAL numeric(15,2),
    BDSALDO_ANTERIOR numeric(15,2),
    BDCODPARTICIPANTE integer,
    BDRAIZCNPJPARTICIPANTE varchar(10),
    BDRAIZCLASSIFICACAOCTA varchar(40),
    BDCENTROCUSTO integer,
    BDNOMTPCC varchar(40),
    BDTPCCLON varchar(20),
    BDVALOR_NAO_CONCILIADO numeric(15,2),
    BDCGCTER varchar(18),
    BDDATAULTLANCAMENTO date)
as
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_TOTAIS_LANC(PRCODEMP VARCHAR(2048),
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRSTATUSTRANSACAO INTEGER = 0,
PRLANCSEMTRANS INTEGER = 1,
PRDATAS VARCHAR(1024) = '')
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDQTDLINHA INTEGER,
BDVALLINHA NUMERIC(15,2),
BDQTDDEB INTEGER,
BDVALDEB NUMERIC(15,2),
BDQTDCRE INTEGER,
BDVALCRE NUMERIC(15,2),
BDQTDGERAL INTEGER,
BDVALGERAL NUMERIC(15,2),
BDDIF NUMERIC(15,2),
BDCODEMPFILIAL INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_TENC_EXERCICIO(PRCODEMP INTEGER,
PRCONTA VARCHAR(1024),
PRCTACONTRAPARTIDA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRDATALANC DATE,
PRLOTE VARCHAR(10),
PRCOMPLEMENTO VARCHAR(100),
PRCODTPHI INTEGER,
PRUSUARIO INTEGER,
PRCHAVEZERA INTEGER,
PRCODPLAPADRAO INTEGER,
PRCODHIST INTEGER,
PRREFEMP INTEGER,
PRLANCCONTRAPART INTEGER)
 RETURNS(PRCHAVEZERAMENTO INTEGER,
PRZEROUCONTAS INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_UPDATE_TLAN_CONC_BANC(PREMPRESA INTEGER,
PRDEBCRE INTEGER,
PRCONTA INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRCOMPL VARCHAR(200),
PRVALOR FLOAT,
PRCODPLAPADRAO INTEGER,
PRDCTO VARCHAR(15),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODPLAPADRAO INTEGER,
BDCHAVE INTEGER)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE VSUC_SP_UPDATE_TLAN_CONC_CLIFOR(PREMPRESA INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINICIAL VARCHAR(10),
PRDATAFINAL VARCHAR(10),
PRCLIFOR SMALLINT,
PRCODPLAPADRAO INTEGER)
 RETURNS(CONCILIACAOOK SMALLINT)
 AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORIDADE (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRDATAATUAL DATE,
    PRAGRUPADOR SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMECC DM_BDNOMEMP,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDIDADE01 INTEGER,
    BDIDADE02 INTEGER,
    BDIDADE03 INTEGER,
    BDIDADE04 INTEGER,
    BDIDADE05 INTEGER,
    BDIDADE06 INTEGER,
    BDIDADE07 INTEGER,
    BDIDADE08 INTEGER,
    BDIDADE09 INTEGER,
    BDIDADE10 INTEGER,
    BDIDADE11 INTEGER,
    BDTOTAL INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMECC DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WDATANASC DATE;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WNOMECCATU DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WID01 INTEGER;
DECLARE VARIABLE WID02 INTEGER;
DECLARE VARIABLE WID03 INTEGER;
DECLARE VARIABLE WID04 INTEGER;
DECLARE VARIABLE WID05 INTEGER;
DECLARE VARIABLE WID06 INTEGER;
DECLARE VARIABLE WID07 INTEGER;
DECLARE VARIABLE WID08 INTEGER;
DECLARE VARIABLE WID09 INTEGER;
DECLARE VARIABLE WID10 INTEGER;
DECLARE VARIABLE WID11 INTEGER;
DECLARE VARIABLE WID INTEGER;
DECLARE VARIABLE WDTRESC DATE;
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORTEMPO (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRDATAATUAL DATE,
    PRAGRUPADOR SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMECC DM_BDNOMEMP,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDTEMPO01 INTEGER,
    BDTEMPO02 INTEGER,
    BDTEMPO03 INTEGER,
    BDTEMPO04 INTEGER,
    BDTEMPO05 INTEGER,
    BDTEMPO06 INTEGER,
    BDTEMPO07 INTEGER,
    BDTEMPO08 INTEGER,
    BDTEMPO09 INTEGER,
    BDTEMPO10 INTEGER,
    BDTEMPO11 INTEGER,
    BDTOTAL INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMECC DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WDATAADM DATE;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WNOMECCATU DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WTP01 INTEGER;
DECLARE VARIABLE WTP02 INTEGER;
DECLARE VARIABLE WTP03 INTEGER;
DECLARE VARIABLE WTP04 INTEGER;
DECLARE VARIABLE WTP05 INTEGER;
DECLARE VARIABLE WTP06 INTEGER;
DECLARE VARIABLE WTP07 INTEGER;
DECLARE VARIABLE WTP08 INTEGER;
DECLARE VARIABLE WTP09 INTEGER;
DECLARE VARIABLE WTP10 INTEGER;
DECLARE VARIABLE WTP11 INTEGER;
DECLARE VARIABLE WTP INTEGER;
DECLARE VARIABLE WDTRESC DATE;
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORFUNCAO (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRDATAATUAL DATE,
    PRAGRUPADOR SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMECC DM_BDNOMEMP,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDTEMPO01 INTEGER,
    BDTEMPO02 INTEGER,
    BDTEMPO03 INTEGER,
    BDTEMPO04 INTEGER,
    BDTEMPO05 INTEGER,
    BDTEMPO06 INTEGER,
    BDTEMPO07 INTEGER,
    BDTEMPO08 INTEGER,
    BDTEMPO09 INTEGER,
    BDTEMPO10 INTEGER,
    BDTEMPO11 INTEGER,
    BDTOTAL INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WSQL2 VARCHAR(1000);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WNOMECC DM_BDNOMEMP;
DECLARE VARIABLE WNOMECCATU DM_BDNOMEMP;
DECLARE VARIABLE WDTCOL DATE;
DECLARE VARIABLE WDTCOLANTES DATE;
DECLARE VARIABLE WCODPLAFUC INTEGER;
DECLARE VARIABLE WCODTFUC INTEGER;
DECLARE VARIABLE WDTADM DATE;
DECLARE VARIABLE WDTRESC DATE;
DECLARE VARIABLE WTP INTEGER;
DECLARE VARIABLE WTP01 INTEGER;
DECLARE VARIABLE WTP02 INTEGER;
DECLARE VARIABLE WTP03 INTEGER;
DECLARE VARIABLE WTP04 INTEGER;
DECLARE VARIABLE WTP05 INTEGER;
DECLARE VARIABLE WTP06 INTEGER;
DECLARE VARIABLE WTP07 INTEGER;
DECLARE VARIABLE WTP08 INTEGER;
DECLARE VARIABLE WTP09 INTEGER;
DECLARE VARIABLE WTP10 INTEGER;
DECLARE VARIABLE WTP11 INTEGER;
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORINST (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRDATAATUAL DATE,
    PRGRAUINST SMALLINT = 0,
    PRAGRUPADOR SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMECC DM_BDNOMEMP,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDINST01 INTEGER,
    BDINST02 INTEGER,
    BDINST03 INTEGER,
    BDINST04 INTEGER,
    BDINST05 INTEGER,
    BDINST06 INTEGER,
    BDINST07 INTEGER,
    BDINST08 INTEGER,
    BDINST09 INTEGER,
    BDINST10 INTEGER,
    BDINST11 INTEGER,
    BDINST12 INTEGER,
    BDINST13 INTEGER,
    BDTOTAL INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMECC DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WNOMECCATU DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WGRAU INTEGER;
DECLARE VARIABLE WINST01 INTEGER;
DECLARE VARIABLE WINST02 INTEGER;
DECLARE VARIABLE WINST03 INTEGER;
DECLARE VARIABLE WINST04 INTEGER;
DECLARE VARIABLE WINST05 INTEGER;
DECLARE VARIABLE WINST06 INTEGER;
DECLARE VARIABLE WINST07 INTEGER;
DECLARE VARIABLE WINST08 INTEGER;
DECLARE VARIABLE WINST09 INTEGER;
DECLARE VARIABLE WINST10 INTEGER;
DECLARE VARIABLE WINST11 INTEGER;
DECLARE VARIABLE WINST12 INTEGER;
DECLARE VARIABLE WINST13 INTEGER;
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORRESC (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRAGRUPADOR SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMECC DM_BDNOMEMP,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDREFRESCISAO INTEGER,
    BDINIEMP INTEGER,
    BDINICOL INTEGER,
    BDTOTALSAIDAS INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMECC DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WNOMECCATU DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WREFRESC INTEGER;
DECLARE VARIABLE WREFRESCANT INTEGER;
DECLARE VARIABLE WINIC INTEGER;
DECLARE VARIABLE WINIEMP INTEGER;
DECLARE VARIABLE WINICOL INTEGER;
BEGIN SUSPEND; END
^

--alt:12049 - 14/10/2015 - Criada nova procedure para o Relatório de Análises. Pedro
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_BALANCO_PATRI_X (
    PRCODEMP VARCHAR(1024),
    PRDATINI DATE,
    PRDATFIN DATE,
    PRIGNZER INTEGER,
    PRCTALONINI VARCHAR(40),
    PRCTALONFIN VARCHAR(40),
    PRINDICE INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRNAOMOSTRACONTACOMP INTEGER,
    PRCTASEMMOV INTEGER,
    PRREFEMP INTEGER,
    PRCONSOLIDADA INTEGER,
    PRDETALHARCTAPARTICIPANTE INTEGER,
    PRCONCATENACODPARTICIPANTE INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRCONTATITULO INTEGER = NULL,
    PRSALDOCOMPARACAO INTEGER = 1)
RETURNS (
    BDCODEMP INTEGER,
    BDCODMATRIZ INTEGER,
    BDCODEMPFILIAL INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP VARCHAR(20),
    BDCODPLAPADRAO INTEGER,
    BDCODCTA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDTIPCTA INTEGER,
    BDSEQCTA VARCHAR(40),
    BDSALANT NUMERIC(15,2),
    BDSALMOV NUMERIC(15,2),
    BDSALATU NUMERIC(15,2),
    BDANAVER NUMERIC(15,2),
    BDANAHOR NUMERIC(15,2),
    BDFORMULA VARCHAR(1024),
    BDGRPCTA INTEGER,
    BDAPECTA VARCHAR(20),
    BDCONTATITULO INTEGER,
    BDSALDOCOMPARACAO NUMERIC(15,2))
AS
 BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_BASE_TDADOS_EMPRESAS
RETURNS (
    BDEMPRESA INTEGER,
    BDANO INTEGER,
    BDMES INTEGER,
    BDVALOR NUMERIC(15,2))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_TDADOS_EMPRESAS_PROXIMA
RETURNS (
    BDCODEMP INTEGER,
    BDANO INTEGER,
    BDMES INTEGER,
    BDVALOR NUMERIC(15,2))
AS
DECLARE VARIABLE WANOI INTEGER;
DECLARE VARIABLE WANOA INTEGER;
DECLARE VARIABLE WMESA INTEGER;
DECLARE VARIABLE WMESMAX INTEGER;
DECLARE VARIABLE WTEM INTEGER;
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_INSS_FN_PREV_RESC (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(30000),
    PRREF INTEGER,
    PRGPSSEFIP SMALLINT = 0,
    PRFILIAIS VARCHAR(15000) = NULL)
RETURNS (
    BDGPSSEFIP INTEGER,
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREFFN INTEGER,
    BDCODCENTROS INTEGER,
    BDCODTPCC INTEGER,
    BDINSSFNPR NUMERIC(18,6),
    BDINSSFEFOLFNPR NUMERIC(18,6),
    BDINSS13FNPR NUMERIC(18,6),
    BDBINSSFNPR NUMERIC(18,6),
    BDBINSSFEFOLFNPR NUMERIC(18,6),
    BDBINSS13FNPR NUMERIC(18,6),
    BDBRATAPOFNPR NUMERIC(18,6),
    BDBRATAPOFEFNPR NUMERIC(18,6),
    BDBRATAPO13FNPR NUMERIC(18,6),
    BDSALFAMFNPR NUMERIC(18,6),
    BDSALMATEMPFNPR NUMERIC(18,6),
    BDBINSS13INDFNPR NUMERIC(18,6),
    BDBINSSAPFNPR NUMERIC(18,6),
    BDBINSS13APFNPR NUMERIC(18,6),
    BDINSSAPFNPR NUMERIC(18,6),
    BDINSS13APFNPR NUMERIC(18,6),
    BDVALREEMBOLSO NUMERIC(18,6),
    BDVALINDEVIDO NUMERIC(18,6),
    BDVALINDEVIDOSF NUMERIC(18,6),
    BDBAVPREV NUMERIC(18,6),
    BDPERCRATCOL NUMERIC(18,6),
    BDPERCDESCFPASCOL NUMERIC(18,6))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_INSS_FT_PREV_RESC (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(30000),
    PRREF INTEGER,
    PRGPSSEFIP SMALLINT = 0,
    PRFILIAIS VARCHAR(15000) = NULL)
RETURNS (
    BDGPSSEFIP INTEGER,
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREFFN INTEGER,
    BDORDEM INTEGER,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDINSSFTPR NUMERIC(18,6),
    BDINSSFEFOLFTPR NUMERIC(18,6),
    BDINSS13FTPR NUMERIC(18,6),
    BDBINSSFTPR NUMERIC(18,6),
    BDBINSSFEFOLFTPR NUMERIC(18,6),
    BDBINSS13FTPR NUMERIC(18,6),
    BDBRATAPOFTPR NUMERIC(18,6),
    BDBRATAPOFEFTPR NUMERIC(18,6),
    BDBRATAPO13FTPR NUMERIC(18,6),
    BDSALFAMFTPR NUMERIC(18,6),
    BDSALMATEMPFTPR NUMERIC(18,6),
    BDBINSSAPFTPR NUMERIC(18,6),
    BDBINSS13INDFTPR NUMERIC(18,6),
    BDBINSS13APFTPR NUMERIC(18,6),
    BDINSSAPFTPR NUMERIC(18,6),
    BDINSS13APFTPR NUMERIC(18,6),
    BDVALREEMBOLSO NUMERIC(18,6),
    BDVALINDEVIDO NUMERIC(18,6),
    BDVALINDEVIDOSF NUMERIC(18,6),
    BDBAVPREV NUMERIC(18,6),
    BDPERCRATCOL NUMERIC(18,6),
    BDPERCDESCFPASCOL NUMERIC(18,6))
AS
BEGIN SUSPEND; END
^

create or alter procedure SP_PEGAEVT_VINCULADOS (
    PRCODIGO integer,
    PRSTATUS integer,
    PRCHAVE varchar(60),
    PREMPRESA integer)
returns (
    BDSTATUS integer,
    BDCHAVE varchar(60),
    BDCODIGO integer,
    BDCODEMP integer)
as
BEGIN SUSPEND; END
^

create or alter procedure SP_PEGA_EVENTO_ORIGINAL (
    PRCHAVE varchar(60))
returns (
    BDCODIGO integer,
    BDSTATUS integer)
as
begin SUSPEND; END
^

CREATE OR ALTER procedure SP_PEGAEVT_VINCULADO_SUCESSO (
    PREMPRESA integer,
    PRCODIGO integer)
returns (
    BDCODEVT integer)
as
declare variable BDEVENTOVINC integer;
declare variable BDSTATUS integer;
declare variable WSQL varchar(250);
declare variable WEVTVINC integer;
begin SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_BI_DRE (
    EMPRESA INTEGER,
    PLANO INTEGER,
    DATA_INICIAL DATE,
    DATA_FINAL DATE,
    TIPO_CONTABILIZACAO SMALLINT,
    IGNORA_ZERAMENTO SMALLINT,
    DETALHAR_FILIAIS SMALLINT)
RETURNS (
    BDCODEMP INTEGER,
    BDCODEMPFILIAL INTEGER,
    BDCODCONTA INTEGER,
    BDCLASSIFICACAO VARCHAR(40),
    BDTIPO_CONTA INTEGER,
    BDVALOR NUMERIC(15,6))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_BI_FAT (
    EMPRESA INTEGER,
    PLANO INTEGER,
    QUADRO INTEGER,
    DATA_INICIAL DATE,
    DATA_FINAL DATE,
    SOMAMATRIZFILIAL SMALLINT)
RETURNS (
    BDCODEMP INTEGER,
    BDREF INTEGER,
    BDORDEM INTEGER,
    BDDESCRICAO VARCHAR(152),
    BDVALOR NUMERIC(15,6))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE GETINTEGERLIST("AINTEGERLIST" VARCHAR(32000))
returns (
  ID integer
)
as
begin SUSPEND; end
^

CREATE OR ALTER PROCEDURE GETINTEGERLISTBLOB (AINTEGERLIST blob sub_type 0 segment size 80)
returns (
  ID integer
)
as
begin SUSPEND; end
^

CREATE OR ALTER PROCEDURE SP_BI_FAT_TODAS(
    PLANO INTEGER,
    QUADRO INTEGER,
    DATA_INICIAL DATE,
    DATA_FINAL DATE,
    SOMAMATRIZFILIAL SMALLINT)
RETURNS (
    BDCODEMP INTEGER,
    BDREF INTEGER,
    BDORDEM INTEGER,
    BDDESCRICAO VARCHAR(152),
    BDVALOR NUMERIC(15,6))
AS
BEGIN SUSPEND; END
^

CREATE OR ALTER PROCEDURE SP_BI_CONF_FOLHA_TODAS (
    CODIGO_RELATORIO INTEGER,
    DATA_INICIAL DATE,
    DATA_FINAL DATE,
    AGRUPAR_POR SMALLINT)
RETURNS (
    BDCODEMP INTEGER,
    BDREF INTEGER,
    BDCODCOL INTEGER,
    BDCODTER INTEGER,
    BDORDEM INTEGER,
    BDDESCRICAO VARCHAR(152),
    BDVALOR NUMERIC(15,6),
    BDCODTPCC INTEGER)
AS
BEGIN SUSPEND; END^

CREATE OR ALTER PROCEDURE SP_BI_CONF_FOLHA (
    EMPRESA INTEGER,
    CODIGO_RELATORIO INTEGER,
    DATA_INICIAL DATE,
    DATA_FINAL DATE,
    AGRUPAR_POR SMALLINT)
RETURNS (
    BDCODEMP INTEGER,
    BDREF INTEGER,
    BDCODCOL INTEGER,
    BDCODTER INTEGER,
    BDORDEM INTEGER,
    BDDESCRICAO VARCHAR(152),
    BDVALOR NUMERIC(15,6),
    BDCODTPCC INTEGER)
AS
BEGIN SUSPEND; END^

CREATE OR ALTER PROCEDURE SP_BI_RELATORIOS(
    NOME_RELATORIO VARCHAR(80),
    CODIGO_EMPRESA INTEGER,
    PARAMS_REL VARCHAR(5000),
    TIPO_SAIDA INTEGER
) RETURNS (
    RETORNO VARCHAR(32000)
)
AS
BEGIN SUSPEND; END^

/* Create Views... */
/* CREATE OR ALTER VIEW: VRH_BASE_TTERC (ViwData.CreateDependDef) */
SET TERM ; ^

CREATE OR ALTER VIEW VRH_BASE_TTERC(
    BDCODTER,
    BDREFTER,
    BDCODCID,
    BDCODCIDNASCTER,
    BDNOMTER,
    BDNOMESOCIALTER,
    BDGERARNMSOCIALTER,
    BDLOGRTER,
    BDENDTER,
    BDNUMTER,
    BDCOMPLTER,
    BDBAITER,
    BDCEPTER,
    BDDDDTER,
    BDFONETER,
    BDCELTER,
    BDEMAILTER,
    BDSEXOTER,
    BDDATANASCTER,
    BDDATACADTER,
    BDDDDCELTER,
    BDCPFTER,
    BDRACACOR,
    BDNOMMAETER,
    BDNOMPAITER,
    BDNUMRICCOL,
    BDORGAORICCOL,
    BDDATAEMIRICCOL,
    BDNUMRNECOL,
    BDORGAORNECOL,
    BDDATAEMIRNECOL,
    BDNUMOCCOL,
    BDORGAOOCCOL,
    BDDATAEMIOCCOL,
    BDDATAVALOCCOL,
    BDCASADOBR,
    BDFILHOSBR,
    BDLOGRESTRCOL,
    BDNUMESTRCOL,
    BDCOMPLESTRCOL,
    BDBAIESTRCOL,
    BDNOMCIDESTRCOL,
    BDCODPOSTESTRCOL,
    BDCODPAISNAS,
    BDCODPAISORIGEM,
    BDCODPAISRES,
    BDCHEGADABRASIL,
    BDNATURALIZADO,
    BDPORTARIANATU,
    BDDATANATURALIZACAO,
    BDDEFFISICOTER,
    BDDEFFISTER,
    BDDEFVISTER,
    BDDEFAUDTER,
    BDDEFMENTER,
    BDDEFINTTER,
    BDDEFREABTER,
    BDOBSDEFFISICOTER,
    BDEMAIL2,
    BDSUS,
    BDNIF,
    BDDISPNIF,
    BDDISPPAISNIF,
    BDCODREND,
    BDCODCIDRIC,
    BDCODCLAESTRANG,
    BDTEMPORESIDENCIA,
    BDCONDICAOINGRESSO,
    BDMATRICULATERC,
    BDUTILIZADESCSIMPLIFICADO,
    BDTRIBUTACAOEXTERIOR)
AS
SELECT
    TER.BDCODTER,
    REF.BDREFEMP,
    REF.BDCODCID,
    RH.BDCODCIDNASCTER,
    REF.BDNOMETER,
    REF.BDNOMESOCIALTER,
    REF.BDGERARNMSOCIALTER,
    REF.BDLOGRTER,
    REF.BDENDTER,
    REF.BDNUMTER,
    REF.BDCOMPTER,
    REF.BDBAITER,
    REF.BDCEPTER,
    CAST((SELECT BDRETORNO FROM PREENCHE_ESQUERDA(TRIM(COALESCE(REF.BDDDDTER,'0')),3,'0')) AS INTEGER),
    REF.BDFONETER,
    RH.BDCELTER,
    REF.BDEMAILTER,
    FIS_REF.BDSEXOTER,
    RH.BDDATANASCTER,
    REF.BDDATACADTER,
    RH.BDDDDCELTER,
    TER.BDCGCTER,
    FIS_REF.BDRACACORTER,
    PAR.BDNOMEMAETER,
    PAR.BDNOMEPAITER,
    DOC_REF.BDNUMRICCOL,
    DOC_REF.BDORGAORICCOL,
    DOC_REF.BDDATAEMIRICCOL,
    DOC_REF.BDNUMRNECOL,
    DOC_REF.BDORGAORNECOL,
    DOC_REF.BDDATAEMIRNECOL,
    DOC_REF.BDNUMOCCOL,
    DOC_REF.BDORGAOOCCOL,
    DOC_REF.BDDATAEMIOCCOL,
    DOC_REF.BDDATAVALOCCOL,
    REF.BDCASADOBR,
    REF.BDFILHOSBR,
    RH.BDLOGRESTRCOL,
    RH.BDNUMESTRCOL,
    RH.BDCOMPLESTRCOL,
    RH.BDBAIESTRCOL,
    RH.BDNOMCIDESTRCOL,
    RH.BDCODPOSTESTRCOL,
    RH.BDCODPAISNAS,
    REF.BDCODPAIS,
    REF.BDCODPAISRES,
    REF.BDCHEGADABRASIL,
    RH.BDNATURALIZADO,
    RH.BDPORTARIANATU,
    RH.BDDATANATURALIZACAO,
    FIS_REF.BDDEFFISICOTER,
    FIS_REF.BDDEFFISTER,
    FIS_REF.BDDEFVISTER,
    FIS_REF.BDDEFAUDTER,
    FIS_REF.BDDEFMENTER,
    FIS_REF.BDDEFINTTER,
    FIS_REF.BDDEFREABTER,
    FIS_REF.BDOBSDEFFISICOTER,
    REF.BDEMAIL2TER,
    DOC.BDSUS,
    RH.BDNIF,
    RH.BDDISPNIF,
    RH.BDDISPPAISNIF,
    RH.BDCODREND,
    DOC_REF.BDCODCIDRIC,
    REF.BDCODCLAESTRANG,
    REF.BDTEMPORESIDENCIA,
    REF.BDCONDICAOINGRESSO,
    RH.BDMATRICULATERC,
    REF.bdutilizadescsimplificado,
    RH.BDTRIBUTACAOEXTERIOR
FROM(SELECT
         X.BDCODTER,
         X.BDCGCTER,
         COALESCE(
                  (SELECT MAX(D1.BDREFEMP) FROM TTERCEIRO_REF D1 WHERE D1.BDCODTER = X.BDCODTER AND CAST(D1.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) FROM RDB$DATABASE)),
                  (SELECT MIN(D1.BDREFEMP) FROM TTERCEIRO_REF D1 WHERE D1.BDCODTER = X.BDCODTER)) AS BDREFEMP
     FROM TTERCEIRO X) AS TER
LEFT OUTER JOIN TTERCEIRO_REF         REF     ON (REF.BDCODTER      = TER.BDCODTER AND
                                                  REF.BDREFEMP      = TER.BDREFEMP     )
LEFT OUTER JOIN TTERCEIRO_RH          RH      ON (TER.BDCODTER      = RH.BDCODTER      )
LEFT OUTER JOIN VRH_BASE_TTERC_FIS    FIS     ON (FIS.BDCODTER      = TER.BDCODTER     )
LEFT OUTER JOIN VRH_BASE_TTERC_FISREF FIS_REF ON (FIS_REF.BDCODTER  = TER.BDCODTER AND
                                                  FIS_REF.BDREFTERC = TER.BDREFEMP     )
LEFT OUTER JOIN VRH_BASE_TTERC_PARENT PAR     ON (PAR.BDCODTER      = TER.BDCODTER     )
LEFT OUTER JOIN VRH_BASE_TTERC_DOC    DOC     ON (DOC.BDCODTER      = TER.BDCODTER     )
LEFT OUTER JOIN VRH_BASE_TTERC_DOCREF DOC_REF ON (DOC_REF.BDCODTER  = TER.BDCODTER AND
                                                  DOC_REF.BDREFTERC = TER.BDREFEMP     )
WHERE
((TER.BDCGCTER IS NULL OR (CHAR_LENGTH(TER.BDCGCTER) <= 14)) OR ((char_length(RH.BDCPFMEITER) = 14) and (REF.BDENQSIMPLESFEDTER = 3)))
ORDER BY
TER.BDCODTER
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TTERC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TTERC(
    BDCODTER,
    BDCODCID,
    BDCODCIDNASCTER,
    BDNOMTER,
    BDLOGRTER,
    BDENDTER,
    BDNUMTER,
    BDCOMPLTER,
    BDBAITER,
    BDCEPTER,
    BDDDDTER,
    BDFONETER,
    BDCELTER,
    BDEMAILTER,
    BDSEXOTER,
    BDDATANASCTER,
    BDDATACADTER,
    BDDDDCELTER)
AS
    SELECT
    t.bdcodter,
    r.bdcodcid,
    rh.bdcodcidnascter,
    r.bdnometer,
    r.bdlogrter,
    r.bdendter,
    r.bdnumter,
    r.bdcompter,
    r.bdbaiter,
    r.bdcepter,
    CAST((SELECT bdretorno FROM preenche_esquerda(TRIM(COALESCE(r.bddddter,'0')),3,'0')) AS INTEGER),
    r.bdfoneter,
    rh.bdcelter,
    r.bdemailter,
    FIS_REF.bdsexoter,
    rh.bddatanascter,
    r.bddatacadter,
    rh.bddddcelter
    FROM TTERCEIRO t
    LEFT OUTER JOIN (SELECT bdCODTER, MAX(bdrefemp) bdrefemp FROM TTERCEIRO_REF GROUP BY bdCODTER) a ON (a.bdcodter = t.bdcodter)
    LEFT OUTER JOIN tterceiro_ref r ON (r.bdcodter = t.bdcodter AND r.bdrefemp = a.bdrefemp)
    LEFT OUTER JOIN tterceiro_rh rh ON (t.bdcodter = rh.bdcodter)
    LEFT OUTER JOIN VRH_BASE_TTERC_FISREF FIS_REF ON (FIS_REF.BDCODTER = T.BDCODTER AND FIS_REF.BDREFTERC = A.BDREFEMP)
    WHERE ((t.bdcgcter IS NULL OR (CHAR_LENGTH(t.bdcgcter) <= 14) or (char_length(RH.bdcpfmeiter) = 14)))
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TTERC_REF_MAX_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TTERC_REF_MAX_MIN(
BDCODTER,
BDREFTER)
 AS 
SELECT
ter.bdcodter,

  COALESCE(

    (
      SELECT FIRST 1 x.bdrefterc FROM VRH_BASE_TTERC_REF x
      WHERE x.bdcodter = ter.bdcodter AND
      CAST(X.bdrefterc AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
      ORDER BY x.bdrefterc DESC
     )

    ,
     (SELECT FIRST 1 x.bdrefterc FROM VRH_BASE_TTERC_REF x
       WHERE x.bdcodter = ter.bdcodter
       ORDER BY x.bdrefterc
      )
    ) BDREFTER

FROM tterceiro ter
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TTERC_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TTERC_REF(
    BDCODCOL,
    BDREFCOL,
    BDFORMAPAGTOCOL,
    BDNRODEPIRCOL,
    BDBASEIRRFADCOL,
    BDVALORPREVPRIVNCOL,
    BDVALORPREVPRIV13COL,
    BDGRAUINSTRUCAO,
    BDESTADOCIVIL,
    BDUTILIZADESCSIMPLIFICADO,
    BDNOMESOCIALTER,
    BDGERARNMSOCIALTER)
AS
SELECT
    X.bdcodter,
    X.bdrefterc,
    0,
    X.bdnrodepirter,
    0.0,
    0.0,
    0.0,
    X.bdgrauinstter,
    X.bdestcivter,
    z.bdutilizadescsimplificado,
    z.BDNOMESOCIALTER,
    z.BDGERARNMSOCIALTER
FROM vrh_base_tterc_ref X
JOIN VW_VRH_BASE_TTERC_REF_MAX_MIN Y ON (x.bdcodter = y.bdcodter AND x.bdrefterc = y.bdrefter)
join TTERCEIRO_REF z On (x.bdcodter = z.bdcodter and x.bdrefterc = z.bdrefemp)
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TTERC_DOC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TTERC_DOC(
    BDCODTER,
    BDREFTERC,
    BDRGTER,
    BDORGEMIRGTER,
    BDDATAEMIRGTER,
    BDCODUFRG,
    BDCPFTER,
    BDCPFMEI,
    BDFOTORGTER,
    BDFOTOCPFTER,
    BDFOTOTER_PIS,
    BDFOTOTER_CTPS,
    BDFOTOTER_CNH,
    BDRESERVISTATER,
    BDNROCONSPROTER,
    BDSIGLACONSPROTER,
    BDCODCCMPROTER,
    BDPISTER,
    BDSTATUSQC,
    BDCNHTER,
    BDCATCNHTER,
    BDORGAOCNH,
    BDCODUFCNH,
    BDDATAEMICNH,
    BDVENCCNHTER,
    BDCTPSTER,
    BDSERIECTPSTER,
    BDDSERIECTPSTER,
    BDDATAEMICTPSTER,
    BDCODUFCTPS,
    BDNUMRICCOL,
    BDDATAEMIRICCOL,
    BDORGAORICCOL,
    BDCODCIDRIC,
    BDNUMOCCOL,
    BDORGAOOCCOL,
    BDDATAEMIOCCOL,
    BDDATAVALOCCOL,
    BDDATAEMIRNECOL,
    BDORGAORNECOL,
    BDNUMRNECOL)
as
select DOC.BDCODTER, DOCREF.BDREFTERC, DOCREF.BDRGTER, DOCREF.BDORGEMIRGTER, DOCREF.BDDATAEMIRGTER, DOCREF.BDCODUFRG,
       TER.BDCGCTER, RH.BDCPFMEITER, IMG.BDFOTOTER_RG, IMG.BDFOTOTER_CPF, IMG.BDFOTOTER_PIS, IMG.BDFOTOTER_CTPS,
       IMG.BDFOTOTER_CNH, DOC.BDRESERVISTATER, DOCREF.BDNROCONSPROTER, DOCREF.BDSIGLACONSPROTER, DOCREF.BDCODCCMPROTER,
       DOCREF.BDPISTER, DOC.BDSTATUSQC, DOCREF.BDCNHTER, DOCREF.BDCATCNHTER, DOCREF.BDORGAOCNH, DOCREF.BDCODUFCNH,
       DOCREF.BDDATAEMICNH, DOCREF.BDVENCCNHTER, DOCREF.BDCTPSTER, DOCREF.BDSERIECTPSTER, DOCREF.BDDSERIECTPSTER,
       DOCREF.BDDATAEMICTPSTER, DOCREF.BDCODUFCTPS, DOCREF.BDNUMRICCOL, DOCREF.BDDATAEMIRICCOL, DOCREF.BDORGAORICCOL,
       DOCREF.BDCODCIDRIC, DOCREF.BDNUMOCCOL, DOCREF.BDORGAOOCCOL, DOCREF.BDDATAEMIOCCOL, DOCREF.BDDATAVALOCCOL,
       DOCREF.BDDATAEMIRNECOL, DOCREF.BDORGAORNECOL, DOCREF.BDNUMRNECOL
from (select X.BDCODTER, coalesce((select max(D1.BDREFTERC)
                                   from VRH_BASE_TTERC_DOCREF D1
                                   where D1.BDCODTER = X.BDCODTER and
                                         cast(D1.BDREFTERC as varchar(6)) <= (select trim(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES'))
                                                                              from RDB$DATABASE)),
             (select min(D1.BDREFTERC)
              from VRH_BASE_TTERC_DOCREF D1
              where D1.BDCODTER = X.BDCODTER)) as BDREFTERC
      from VRH_BASE_TTERC_DOC X) as BASE
left join VRH_BASE_TTERC_DOC DOC on (DOC.BDCODTER = BASE.BDCODTER)
join TTERCEIRO TER on (BASE.BDCODTER = TER.BDCODTER)
left join TTERCEIRO_RH RH on (BASE.BDCODTER = RH.BDCODTER)
left join VRH_BASE_TTERC_IMG IMG on (IMG.BDCODTER = TER.BDCODTER)
left join VRH_BASE_TTERC_DOCREF DOCREF on (DOCREF.BDCODTER = BASE.BDCODTER and DOCREF.BDREFTERC = BASE.BDREFTERC); 

                                           
/* CREATE OR ALTER VIEW: VW_AUTONOMO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_AUTONOMO(
    BDCODCOL,
    BDCODMCAG,
    BDCODCID,
    BDCODCSEG,
    BDREFCSEG,
    BDCODCIDNASC,
    BDCODUF,
    BDNOMCOL,
    BDLOGRCOL,
    BDENDCOL,
    BDNUMCOL,
    BDCOMPLCOL,
    BDBAICOL,
    BDCEPCOL,
    BDDDDCOL,
    BDFONECOL,
    BDCELCOL,
    BDEMAILCOL,
    BDSEXOCOL,
    BDDATANASCCOL,
    BDDATACADCOL,
    BDGRAUINSTCOL,
    BDESTCIVCOL,
    BDDATAADMCOL,
    BDDATAADICCOL,
    BDCONTRCOL,
    BDRGCOL,
    BDORGEMIRGCOL,
    BDDATAEMIRGCOL,
    BDCPFCOL,
    BDRESERVISTACOL,
    BDPISCOL,
    BDDATAEMIPISCOL,
    BDCODUF_COL_DOC,
    BDTITELEICOL,
    BDZONAELEICOL,
    BDSECAOELEICOL,
    BDCTPSCOL,
    BDSERIECTPSCOL,
    BDDSERIECTPSCOL,
    BDDATAEMICTPSCOL,
    BDCNHCOL,
    BDVENCCNHCOL,
    BDCATCNHCOL,
    BDCODCID_HIST,
    BDCODPAIS,
    BDNATURALIZADOCOL,
    BDDATACHEBRASILCOL,
    BDCODCIDNASCCONJ,
    BDNOMPAICOL,
    BDNOMMAECOL,
    BDNOMCONJCOL,
    BDDATANASCCONJCOL,
    BDCORCOL,
    BDCABELOSCOL,
    BDOLHOSCOL,
    BDALTURACOL,
    BDPESOCOL,
    BDSINAISCOL,
    BDDEFFISICOCOL,
    BDTIPOSANGUETER,
    BDNROCONSPROCOL,
    BDSIGLACONSPROCOL,
    BDCODCCMPROCOL,
    BDTIPOADMCOL,
    BDNATUOCUPCOL,
    BDDATAINIAQUICOL,
    BDSALINICOL,
    BDDIASPRAZO1COL,
    BDDATAFIMPRAZO1COL,
    BDDIASPRAZO2COL,
    BDDATAFIMPRAZO2COL,
    BDDESCCONTSINCOL,
    BDVINCEMPCOL,
    BDALVARACOL,
    BDSINDICALIZADOCOL,
    BDREGIMEPARCIALCOL,
    BDFICHAREGCOL,
    BDLIVROREGCOL,
    BDNROFOLHAREGCOL)
AS
SELECT COLCON.bdcodter ,
       0,
       COLCON.BDCODCID,
       0,
       0,
       COLCON.BDCODCIDNASCTER,
       CAST('' AS VARCHAR(2)),
       COLCON.bdnomter,
       COLCON.bdlogrter,
       COLCON.bdendter ,
       COLCON.bdnumter,
       COLCON.bdcomplter,
       COLCON.bdbaiter,
       COLCON.bdcepter,
       COLCON.bddddter ,
       COLCON.bdfoneter,
       COLCON.bdcelter,
       COLCON.bdemailter,
       COLCON.bdsexoter,
       COLCON.bddatanascter,
       COLCON.bddatacadter,
       terc_ref.bdgrauinstrucao,
       terc_ref.bdestadocivil ,
       COLCON.bddatacadter,
       COLCON.bddatacadter,
       0,
       COLCON_DOC.bdrgter,
       COLCON_DOC.bdorgemirgter,
       COLCON_DOC.bddataemirgter,
       case 
       when (char_length(COLCON_DOC.bdcpfmei) = 14) then COLCON_DOC.bdcpfmei
       else COLCON_DOC.bdcpfter
       end BDCPFTER,
       COLCON_DOC.bdreservistater,
       COLCON_DOC.bdpister,
       COLCON.BDDATACADTER,
       CAST('' AS VARCHAR(2)),
       CAST('' AS VARCHAR(14)),
       0,
       0,
       0,
       0,
       CAST('' AS VARCHAR(1)),
       COLCON.BDDATACADTER,
       CAST('' AS VARCHAR(11)),
       COLCON.BDDATACADTER,
       NULL,
       NULL,
       NULL,
       NULL,
       COLCON.BDDATACADTER,
       NULL,
       NULL,
       NULL,
       NULL,
       COLCON.BDDATACADTER,
       0,
       0,
       0,
       0.0,
       0.0,
       0,
       0,
       FIS.BDTIPOSANGUE,
       COLCON_DOC.bdnroconsproter,
       COLCON_DOC.bdsiglaconsproter,
       COLCON_DOC.bdcodccmproter,
       NULL,
       NULL,
       COLCON.BDDATACADTER,
       NULL,
       NULL,
       COLCON.BDDATACADTER,
       NULL,
       COLCON.BDDATACADTER,
       NULL,
       NULL,
       CAST('FALSE' AS VARCHAR(5)),
       NULL,
       NULL,
       NULL,
       NULL,
       NULL 
FROM VW_VRH_BASE_TTERC COLCON
LEFT OUTER JOIN VW_VRH_BASE_TTERC_REF TERC_REF ON (COLCON.BDCODTER = TERC_REF.BDCODCOL)
LEFT OUTER JOIN VW_VRH_BASE_TTERC_DOC COLCON_DOC ON (COLCON.BDCODTER = COLCON_DOC.BDCODTER)
LEFT OUTER JOIN VRH_BASE_TTERC_FIS FIS ON (FIS.BDCODTER = COLCON.BDCODTER)
;

CREATE OR ALTER VIEW VW_VRH_BASE_TTERC_FIS(
    BDCODTER,
    BDREFTERC,
    BDCORCABELOTER,
    BDCOROLHOSTER,
    BDALTURATER,
    BDPESOTER,
    BDSINAISTER,
    BDTIPOSANGUE,
    BDSEXOTER,
    BDRACACORTER,
    BDDEFFISICOTER,
    BDOBSDEFFISICOTER,
    BDDEFFISTER,
    BDDEFVISTER,
    BDDEFAUDTER,
    BDDEFMENTER,
    BDDEFINTTER,
    BDDEFREABTER,
    BDCOTADEFTER)
AS
SELECT
    FIS.BDCODTER,
    FISREF.BDREFTERC,
    FIS.BDCORCABELOTER,
    FIS.BDCOROLHOSTER,
    FIS.BDALTURATER,
    FIS.BDPESOTER,
    FIS.BDSINAISTER,
    FIS.BDTIPOSANGUE,
    FISREF.BDSEXOTER,
    FISREF.BDRACACORTER,
    FISREF.BDDEFFISICOTER,
    FISREF.BDOBSDEFFISICOTER,
    FISREF.BDDEFFISTER,
    FISREF.BDDEFVISTER,
    FISREF.BDDEFAUDTER,
    FISREF.BDDEFMENTER,
    FISREF.BDDEFINTTER,
    FISREF.BDDEFREABTER,
    FISREF.BDCOTADEFTER
FROM(SELECT
        X.BDCODTER,
        COALESCE(
                 (SELECT MAX(D1.BDREFTERC) FROM VRH_BASE_TTERC_FISREF D1 WHERE D1.BDCODTER = X.BDCODTER AND CAST(D1.BDREFTERC AS VARCHAR(6)) <= (SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) FROM RDB$DATABASE)),
                 (SELECT MIN(D1.BDREFTERC) FROM VRH_BASE_TTERC_FISREF D1 WHERE D1.BDCODTER = X.BDCODTER)) AS BDREFTERC
     FROM VRH_BASE_TTERC_FIS X) AS BASE
LEFT JOIN VRH_BASE_TTERC_FIS    FIS    ON (FIS.BDCODTER     = BASE.BDCODTER    )
LEFT JOIN VRH_BASE_TTERC_FISREF FISREF ON (FISREF.BDCODTER  = BASE.BDCODTER AND
                                           FISREF.BDREFTERC = BASE.BDREFTERC   );


CREATE OR ALTER VIEW VW_VRH_BASE_TTERC_PARENT(
    BDCODTER,
    BDNOMEPAITER,
    BDNOMEMAETER,
    BDNOMECONJTER,
    BDDATANASCCONJTER,
    BDCODCIDNASCCONJ)
AS
SELECT
    PARENT.BDCODTER,
    PARENT.BDNOMEPAITER,
    PARENT.BDNOMEMAETER,
    PARENT.BDNOMECONJTER,
    PARENT.BDDATANASCCONJTER,
    PARENT.BDCODCIDNASCCONJ
FROM VRH_BASE_TTERC_PARENT PARENT;

CREATE OR ALTER VIEW VW_VRH_BASE_TTERC_VINC_MAX_MIN(
BDCODTER,
BDREFTER)
 AS 
SELECT
ter.bdcodter,

  COALESCE(

    (
      SELECT FIRST 1 x.bdrefterc FROM vrh_base_tterc_vinc x
      WHERE x.bdcodter = ter.bdcodter AND
      CAST(X.bdrefterc AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
      ORDER BY x.bdrefterc DESC
     )

    ,
     (SELECT FIRST 1 x.bdrefterc FROM vrh_base_tterc_vinc x
       WHERE x.bdcodter = ter.bdcodter
       ORDER BY x.bdrefterc
      )
    ) BDREFTER

FROM tterceiro ter
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TTERC_VINC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TTERC_VINC(
    BDCODCOL,
    BDREFCOL,
    BDCODCLA,
    BDCODCBO,
    BDCODCBOTSIN,
    BDCODSINTRAB,
    BDACORDOINSSTERC,
    BDPERCIRTERC,
    BDPIRTERC)
AS
SELECT
    X.bdcodter,
    X.bdrefTERC,
    X.bdcodcla,
    x.bdcodcbo,
    x.bdcodcbotsin,
    x.bdcodsintrab,
    x.bdacordoinssterc,
    x.bdpercirterc,
    x.bdpirterc
FROM vrh_base_tterc_vinc X
JOIN VW_VRH_BASE_TTERC_VINC_MAX_MIN y ON (x.bdcodter = y.bdcodter AND x.bdrefterc = y.bdrefter)
;

CREATE OR ALTER VIEW VW_VRHF_BASE_TTERC_BANCO(
    BDCODCOL,
    BDREFCOL,
    BDCODBAN,
    BDCODAG,
    BDCTADEPCOL,
    BDDIGCTADEPCOL,
    BDTIPOCTACOL,
    BDMODOPAGTOCOL,
    BDCARTAOSALCOL,
    BDMODOPAGTOCOLPIXTPCH,
    BDMODOPAGTOCOLPIXCH)
AS
SELECT
    X.bdcodter,
    X.bdrefterc,
    X.bdcodban,
    X.bdcodag,
    X.bdctadepter,
    X.bddigctadepter,
    X.bdtipoctater,
    X.bdmodopagtoter,
    X.bdcartaosalter,
    X.bdmodopagtoterpixtpch,
    X.bdmodopagtoterpixch
FROM vrhf_base_tterc_banco X
WHERE X.bdrefterc =
      (
       SELECT MAX(Y.bdrefterc)
       FROM vrhf_base_tterc_banco Y
       WHERE Y.bdcodter = X.bdcodter AND
             Y.bdrefterc <=
                (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER)
                 FROM rdb$database
                )
      )
;

create or alter view VW_VRHF_TTERC_FGTSGPS_REFATU (
BDCODTER,
BDREFTER)
as
select TER.BDCODTER,

       coalesce(

       (select first 1 X.BDREFTERC
        from VRHF_BASE_TTERC_FGTSGPS X
        where X.BDCODTER = TER.BDCODTER and
              cast(X.BDREFTERC as varchar(6)) <= (select trim(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES'))
                                                  from RDB$DATABASE)
        order by X.BDREFTERC desc)

       ,
       (select first 1 X.BDREFTERC
        from VRHF_BASE_TTERC_FGTSGPS X
        where X.BDCODTER = TER.BDCODTER
        order by X.BDREFTERC)) BDREFTER

from (select T.BDCODTER
      from TTERCEIRO T
      left outer join TTERCEIRO_RH RH on (T.BDCODTER = RH.BDCODTER)
      where ((T.BDCGCTER is null or (char_length(T.BDCGCTER) <= 14)) or (char_length(RH.BDCPFMEITER) = 14))) TER;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TTERC_FGTSGPS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TTERC_FGTSGPS(
    BDCODCOL,
    BDREFCOL,
    BDDATAOPCAOFGTSCOL,
    BDCTAFGTSCOL,
    BDCATEGORIACOL,
    BDPERCFGTSCOL,
    BDOCORRENCIACOL,
    BDPERCRATCOL,
    BDPERCDESCFPASCOL,
    BDCATEGORIAESOCIAL,
    BDVINCEMPTER,
    BDCODMULTVINC,
    BDREGPREV)
AS
SELECT
    X.BDCODTER,
    X.BDREFTERC,
    Z.BDDATACADTER,
    CAST(NULL AS DATE),
    X.BDCATEGORIATER,
    0.0,
    X.BDOCORRENCIATER,
    X.BDPERCRATTER,
    0.0,
    X.BDCATEGORIAESOCIAL,
    X.BDVINCEMPTER,
    X.BDCODMULTVINC,
    X.BDREGPREV
FROM VRHF_BASE_TTERC_FGTSGPS X
JOIN VW_VRHF_TTERC_FGTSGPS_REFATU A ON (X.BDCODTER = A.BDCODTER AND X.BDREFTERC = A.BDREFTER)
LEFT OUTER JOIN VW_VRH_BASE_TTERC Z ON (Z.BDCODTER = X.BDCODTER)
;

/* CREATE OR ALTER VIEW: VW_AUTONOMOS_REF_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_AUTONOMOS_REF_ATUAL(
    BDCODCOL,
    BDCONTRCOL,
    BDCODCLA,
    BDGRUPOCLA,
    BDCODMEN,
    BDCODSINTRAB,
    BDCODBAN,
    BDCODAG,
    BDCTADEPCOL,
    BDDIGCTADEPCOL,
    BDTIPOCTACOL,
    BDMODOPAGTOCOL,
    BDCARTAOSALCOL,
    BDFORMAPAGTOCOL,
    BDNRODEPIRCOL,
    BDBASEIRRFADCOL,
    BDVALORPREVPRIVNCOL,
    BDVALORPREVPRIV13COL,
    BDDATAOPCAOFGTSCOL,
    BDCTAFGTSCOL,
    BDCATEGORIACOL,
    BDPERCFGTSCOL,
    BDOCORRENCIACOL,
    BDPERCRATCOL,
    BDPERCDESCFPASCOL,
    BDTIPOCOL,
    BDHORASMENSAISCOL,
    BDHORASSEMANAISCOL,
    BDHORASDIARIASCOL,
    BDPERCINSALUBCOL,
    BDINCIDINSALUBCOL,
    BDPERCPERCULCOL,
    BDINCIDPERICULCOL,
    BDPERCNOTURNOCOL,
    BDINCIDNOTURNOCOL,
    BDNRODEPSALFAMCOL,
    BDIGNORAFALTASFERCOL,
    BDCALCADIANTACOL,
    BDNAOARREDONDARCOL,
    BDIMPETIQUETACOL,
    BDCALCDSRRVCOL,
    BDCALCDSRHECOL,
    BDCALCDSRSALCOL,
    BDCALCVALTRANSCOL,
    BDCALCVALREFCOL,
    BDOBSCOL,
    BDCODGPS,
    BDDESCINSSDOIRCOL,
    BDCODMULTVINC)
AS
SELECT COLCON.BDCODTER,
       0,
       COLCON_VINC.BDCODCLA,
       CLASSE.BDGRUPOCLA,
       0,
       0,
       COLCON_BANCO.BDCODBAN,
       COLCON_BANCO.BDCODAG,
       COLCON_BANCO.BDCTADEPCOL,
       COLCON_BANCO.BDDIGCTADEPCOL ,
       COLCON_BANCO.BDTIPOCTACOL,
       COLCON_BANCO.BDMODOPAGTOCOL,
       COLCON_BANCO.BDCARTAOSALCOL,
       0,
       COLCON_CALC.BDNRODEPIRCOL,
       COLCON_CALC.BDBASEIRRFADCOL ,
       COLCON_CALC.BDVALORPREVPRIVNCOL,
       COLCON_CALC.BDVALORPREVPRIV13COL, 
       COLCON_FGTSGPS.BDDATAOPCAOFGTSCOL,
       CAST('' AS VARCHAR(11)),
       COLCON_FGTSGPS.BDCATEGORIACOL ,
       COLCON_FGTSGPS.BDPERCFGTSCOL,
       COLCON_FGTSGPS.BDOCORRENCIACOL ,
       COLCON_FGTSGPS.BDPERCRATCOL,
       COLCON_FGTSGPS.BDPERCDESCFPASCOL,
       0,
       0.0,
       0.0,
       0.0,
       0.0,
       0,
       0.0,
       0,
       0.0,
       0,
       0,
       CAST('' AS VARCHAR(5)),
       CAST('' AS VARCHAR(5)),
       CAST('' AS VARCHAR(5)),
       CAST('' AS VARCHAR(5)),
       CAST('' AS VARCHAR(5)),
       CAST('' AS VARCHAR(5)),
       CAST('' AS VARCHAR(5)),
       CAST('' AS VARCHAR(5)),
       CAST('' AS VARCHAR(5)),
       CAST('' AS VARCHAR(5)),
       0,
       CAST('' AS VARCHAR(5)),
       COLCON_FGTSGPS.bdcodmultvinc

FROM vw_VRH_BASE_TTERC COLCON
LEFT OUTER JOIN VW_vrh_base_tterc_vinc COLCON_VINC
  ON (COLCON_VINC.BDCODCOL = COLCON.BDCODTER)
LEFT OUTER JOIN VW_VRHF_BASE_TTERC_BANCO COLCON_BANCO
  ON (COLCON_BANCO.BDCODCOL = COLCON.BDCODTER)
LEFT OUTER JOIN VW_vrh_base_tterc_ref COLCON_CALC
  ON (COLCON_CALC.BDCODCOL = COLCON.BDCODTER)
LEFT OUTER JOIN VW_vrhf_base_tterc_fgtsgps COLCON_FGTSGPS
  ON (COLCON_FGTSGPS.BDCODCOL = COLCON.BDCODTER)
LEFT OUTER JOIN VRH_BASE_TCLASSE CLASSE
  ON (COLCON_VINC.BDCODCLA = CLASSE.BDCODCLA)
;

/* CREATE OR ALTER VIEW: VW_CALCVESP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_CALCVESP(
BDCODCTP,
BDCODCIT,
BDCODVER,
BDCODCVE,
BDCODVERCVE,
BDFORMULABASECVE,
BDFORMCIT,
BDCLASSCIT,
BDCODTCA)
 AS 
SELECT X.BDCODCTP,
       X.BDCODCIT,
       X.BDCODVER,
       X.BDCODCVE,
       X.BDCODVERCVE,
       X.BDFORMULABASECVE,
       Y.BDFORMCIT,
       Y.BDCLASSCIT,
       Y.BDCODTCA
FROM VRH_BASE_TCALCVESP X,
     VRH_BASE_TCALCITENS Y
WHERE (Y.BDCODCTP = X.BDCODCTP AND Y.BDCODCIT = X.BDCODCIT)
;

/* CREATE OR ALTER VIEW: VWRH_UNION_FN_FT_MES (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_UNION_FN_FT_MES(
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDCODVER,
    BDCOMPESP,
    BDFORMREFAUX,
    BDFORMREF,
    BDFORMVAL,
    BDREFVFN_SUM,
    BDREFAUXVFN_SUM,
    BDREFVFN_MAX,
    BDREFAUXVFN_MAX,
    BDVALVFN,
    BDVALVIFN,
    BDIGNREFVFN,
    BDIGNREFAVFN,
    BDIGNVALVFN,
    BDORVERBA)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDCODVER,
  BDCOMPESP,
  BDFORMREFAUX,
  BDFORMREF,
  BDFORMVAL,
  BDREFVFN,
  BDREFAUXVFN,
  BDREFVFN,
  BDREFAUXVFN,
  BDVALVFN,
  BDVALVIFN,
  BDIGNREFVFN,
  BDIGNREFAVFN,
  BDIGNVALVFN,
  BDORVERBAFN
FROM
  VRHF_EMP_TVERBAFN

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFTOMADOR,
  BDCODVER,
  MAX(BDCOMPESP),
  MAX(BDFORMREFAUX),
  MAX(BDFORMREF),
  MAX(BDFORMVAL),
  SUM(BDREFVFT),
  SUM(BDREFAUXVFT),
  MAX(BDREFVFT),
  MAX(BDREFAUXVFT),
  SUM(BDVALVFT),
  SUM(BDVALVIFT),
  MAX(BDIGNREFVFT),
  MAX(BDIGNREFAVFT),
  MAX(BDIGNVALVFT),
  MAX(BDORVERBAFT)
FROM
  VRHF_EMP_TVERBATOMADOR
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFTOMADOR,
  BDCODVER
;

/* View: VWRH_UNION_FI_FTI_MES */
CREATE OR ALTER VIEW VWRH_UNION_FI_FTI_MES(
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDCODCONTTI,
    BDCODVER,
    BDCOMPESP,
    BDFORMREFAUX,
    BDFORMREF,
    BDFORMVAL,
    BDREFVFN_SUM,
    BDREFAUXVFN_SUM,
    BDREFVFN_MAX,
    BDREFAUXVFN_MAX,
    BDVALVFN,
    BDVALVIFN,
    BDIGNREFVFN,
    BDIGNREFAVFN,
    BDIGNVALVFN,
    BDORVERBA)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDCODCONTTI,
  BDCODVER,
  MAX(BDCOMPESP),
  MAX(BDFORMREFAUX),
  MAX(BDFORMREF),
  MAX(BDFORMVAL),
  SUM(BDREFVFN),
  SUM(BDREFAUXVFN),
  MAX(BDREFVFN),
  MAX(BDREFAUXVFN),
  SUM(BDVALVFN),
  SUM(BDVALIFN),
  MAX(BDIGNREFVFN),
  MAX(BDIGNREFAVFN),
  MAX(BDIGNVALVFN),
  MAX(BDORVERBAFN)
FROM
  VRHF_EMP_TVERBAINT
GROUP BY BDCODEMP, BDCODCOL, BDREFFN, BDCODCONTTI, BDCODVER
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFTOMADOR,
  BDCODCONTTI,
  BDCODVER,
  MAX(BDCOMPESP),
  MAX(BDFORMREFAUX),
  MAX(BDFORMREF),
  MAX(BDFORMVAL),
  SUM(BDREFVFT),
  SUM(BDREFAUXVFT),
  MAX(BDREFVFT),
  MAX(BDREFAUXVFT),
  SUM(BDVALVFT),
  SUM(BDVALIFT),
  MAX(BDIGNREFVFT),
  MAX(BDIGNREFAVFT),
  MAX(BDIGNVALVFT),
  MAX(BDORVERBAFT)
FROM
  VRHF_EMP_TVERBATOMINT
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFTOMADOR,
  BDCODCONTTI,
  BDCODVER
;

/* CREATE OR ALTER VIEW: VW_CLASS_00400 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_CLASS_00400(
BDCODEMP,
BDCODCOL,
BDREFFN,
BDCODVER,
BDVALVFN)
 AS 
SELECT fn.bdcodemp, fn.bdcodcol, fn.bdreffn, fn.bdcodver, fn.bdvalvfn
FROM VWRH_UNION_FN_FT_MES fn
JOIN vrh_base_tverbas verbas ON  (fn.bdcodver = verbas.bdcodver)
WHERE (BDCLAVER STARTING WITH '0.004.0.0') OR (BDCLAVER STARTING WITH '0.710.0.0')
;

/* CREATE OR ALTER VIEW: VW_CLASS_00401 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_CLASS_00401(
BDCODEMP,
BDCODCOL,
BDREFFN,
BDCODVER,
BDVALVFN)
 AS 
SELECT fn.bdcodemp, fn.bdcodcol, fn.bdreffn, fn.bdcodver, fn.bdvalvfn
FROM VWRH_UNION_FN_FT_MES fn
JOIN vrh_base_tverbas verbas ON  (fn.bdcodver = verbas.bdcodver)
WHERE (BDCLAVER STARTING WITH '0.004.0.1') OR (BDCLAVER STARTING WITH '0.710.0.1')
;

/* CREATE OR ALTER VIEW: VW_CLASS_00402 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_CLASS_00402(
BDCODEMP,
BDCODCOL,
BDREFFN,
BDCODVER,
BDVALVFN)
 AS 
SELECT fn.bdcodemp, fn.bdcodcol, fn.bdreffn, fn.bdcodver, fn.bdvalvfn
FROM VWRH_UNION_FN_FT_MES fn
JOIN vrh_base_tverbas verbas ON  (fn.bdcodver = verbas.bdcodver)
WHERE (BDCLAVER STARTING WITH '0.004.0.2') OR (BDCLAVER STARTING WITH '0.710.0.2')
;

/* CREATE OR ALTER VIEW: VW_CLASS_00403 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_CLASS_00403(
BDCODEMP,
BDCODCOL,
BDREFFN,
BDCODVER,
BDVALVFN)
 AS 
SELECT fn.bdcodemp, fn.bdcodcol, fn.bdreffn, fn.bdcodver, fn.bdvalvfn
FROM VWRH_UNION_FN_FT_MES fn
JOIN vrh_base_tverbas verbas ON  (fn.bdcodver = verbas.bdcodver)
WHERE (BDCLAVER STARTING WITH '0.004.0.3') OR (BDCLAVER STARTING WITH '0.710.0.3')
;

/* CREATE OR ALTER VIEW: VW_CLASS_00404 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_CLASS_00404(
BDCODEMP,
BDCODCOL,
BDREFFN,
BDCODVER,
BDVALVFN)
 AS 
SELECT fn.bdcodemp, fn.bdcodcol, fn.bdreffn, fn.bdcodver, fn.bdvalvfn
FROM VWRH_UNION_FN_FT_MES fn
JOIN vrh_base_tverbas verbas ON  (fn.bdcodver = verbas.bdcodver)
WHERE (BDCLAVER STARTING WITH '0.004.0.4') OR (BDCLAVER STARTING WITH '0.710.0.4')
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOLCON_VINC_ADM (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_VINC_ADM(
BDCODEMP,
BDCODCOL,
BDREFCOL,
BDCODCLA)
 AS 
SELECT BASE.bdcodemp, BASE.bdcodcol, BASE.bdrefcol, V.bdcodcla
FROM
(
  SELECT
      X.bdcodemp,
      X.bdcodcol,
      (SELECT MIN(d1.bdrefcol) FROM vrh_emp_tcolcon_vinc d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol) AS bdrefcol
  FROM vrh_emp_tcolcon x
) AS BASE, vrh_emp_tcolcon_vinc v
WHERE BASE.bdcodemp = v.bdcodemp AND BASE.bdcodcol = v.bdcodcol AND BASE.bdREFCOL = v.bdREFCOL
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOL_VINC_ADM (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOL_VINC_ADM(
BDCODEMP,
BDCODCOL,
BDREFCOL,
BDCODMEN,
BDCODSINTRAB)
 AS 
SELECT BASE.bdCODEMP, BASE.bdCODCOL, BASE.bdREFCOL, VIN.bdCODMEN, VIN.bdCODSINTRAB
FROM
(
  SELECT
    col.bdCODEMP,
    col.bdCODCOL,
      (SELECT MIN(d2.bdrefcol) FROM vrh_emp_tcol_vinc d2 WHERE d2.bdcodemp = col.bdcodemp AND d2.bdcodcol = col.bdcodcol) AS bdREFCOL
  FROM vrh_emp_tcolcon col
) AS BASE, vrh_emp_tcol_vinc VIN
WHERE BASE.bdCODEMP = VIN.bdCODEMP AND BASE.bdCODCOL = VIN.bdCODCOL AND BASE.bdREFCOL = VIN.bdREFCOL
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_BANCO_REF */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_BANCO_REF(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDCODBAN,
    BDCODAG,
    BDCTADEPCOL,
    BDDIGCTADEPCOL,
    BDTIPOCTACOL,
    BDMODOPAGTOCOL,
    BDCARTAOSALCOL)
AS
SELECT BASE.bdcodemp, BASE.bdcodcol, BASE.bdrefcol,
REF.bdcodban,
REF.bdcodag,
REF.bdctadepcol,
REF.bddigctadepcol,
REF.bdtipoctacol,
REF.bdmodopagtocol,
REF.bdcartaosalcol
FROM
(
  SELECT
      X.bdcodemp,
      X.bdcodcol,
      COALESCE
  (
      (SELECT MAX(d2.bdrefcol) FROM vrhf_emp_tcolcon_banco d2 WHERE d2.bdcodemp = x.bdcodemp AND d2.bdcodcol = x.bdcodcol AND CAST(d2.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefcol) FROM vrhf_emp_tcolcon_banco d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol)
  ) AS bdrefcol
  FROM vrh_emp_tcolcon x
) AS BASE, vrhf_emp_tcolcon_banco REF
WHERE BASE.bdcodemp = REF.bdcodemp AND BASE.bdcodcol = REF.bdcodcol AND BASE.bdREFCOL = REF.bdREFCOL
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_BANCO_ADM (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_BANCO_ADM(
BDCODEMP,
BDCODCOL,
BDREFCOL,
BDCODBAN,
BDCODAG,
BDCTADEPCOL,
BDDIGCTADEPCOL,
BDTIPOCTACOL,
BDMODOPAGTOCOL,
BDCARTAOSALCOL)
 AS 
SELECT BASE.bdcodemp, BASE.bdcodcol, BASE.bdrefcol,
REF.bdcodban,
REF.bdcodag,
REF.bdctadepcol,
REF.bddigctadepcol,
REF.bdtipoctacol,
REF.bdmodopagtocol,
REF.bdcartaosalcol
FROM
(
  SELECT
      X.bdcodemp,
      X.bdcodcol,
      (SELECT MIN(d1.bdrefcol) FROM vrhf_emp_tcolcon_banco d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol) AS bdrefcol
  FROM vrh_emp_tcolcon x
) AS BASE, vrhf_emp_tcolcon_banco REF
WHERE BASE.bdcodemp = REF.bdcodemp AND BASE.bdcodcol = REF.bdcodcol AND BASE.bdREFCOL = REF.bdREFCOL
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_CALC_ADM (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_CALC_ADM(
BDCODEMP,
BDCODCOL,
BDREFCOL,
BDFORMAPAGTOCOL,
BDNRODEPIRCOL,
BDBASEIRRFADCOL,
BDVALORPREVPRIVNCOL,
BDVALORPREVPRIV13COL)
 AS 
SELECT BASE.bdcodemp, BASE.bdcodcol, BASE.bdrefcol,
REF.bdformapagtocol,
REF.bdnrodepircol,
REF.bdbaseirrfadcol,
REF.bdvalorprevprivncol,
REF.bdvalorprevpriv13col
FROM
(
  SELECT
      X.bdcodemp,
      X.bdcodcol,
      (SELECT MIN(d1.bdrefcol) FROM vrhf_emp_tcolcon_calc d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol) AS bdrefcol
  FROM vrh_emp_tcolcon x
) AS BASE, vrhf_emp_tcolcon_calc REF
WHERE BASE.bdcodemp = REF.bdcodemp AND BASE.bdcodcol = REF.bdcodcol AND BASE.bdREFCOL = REF.bdREFCOL
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_FGTSGPS_ADM (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_FGTSGPS_ADM(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDDATAOPCAOFGTSCOL,
    BDCTAFGTSCOL,
    BDCATEGORIACOL,
    BDPERCFGTSCOL,
    BDOCORRENCIACOL,
    BDPERCRATCOL,
    BDPERCDESCFPASCOL,
    BDREGPREV,
    BDCODMULTVINC)
AS
SELECT BASE.bdcodemp, BASE.bdcodcol, BASE.bdrefcol,
REF.bddataopcaofgtscol,
REF.bdctafgtscol,
REF.bdcategoriacol,
REF.bdpercfgtscol,
REF.bdocorrenciacol,
REF.bdpercratcol,
REF.bdpercdescfpascol,
REF.BDREGPREV,
REF.BDCODMULTVINC
FROM
(
  SELECT
      X.bdcodemp,
      X.bdcodcol,
      (SELECT MIN(d1.bdrefcol) FROM vrhf_emp_tcolcon_fgtsgps d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol) AS bdrefcol
  FROM vrh_emp_tcolcon x
) AS BASE, vrhf_emp_tcolcon_fgtsgps REF
WHERE BASE.bdcodemp = REF.bdcodemp AND BASE.bdcodcol = REF.bdcodcol AND BASE.bdREFCOL = REF.bdREFCOL
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_MVINC_ADM (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_MVINC_ADM(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDBASEINSSNCOL,
    BDVALORINSSNCOL,
    BDBASEIRRFNCOL,
    BDVALORIRRFNCOL,
    BDBASEINSS13COL,
    BDVALORINSS13COL,
    BDBASEIRRF13COL,
    BDVALORIRRF13COL)
AS
SELECT BDCODEMP, BDCODCOL, BDREFCOL,
SUM(BDBASEINSSNCOL),
SUM(BDVALORINSSNCOL),
SUM(BDBASEIRRFNCOL),
SUM(BDVALORIRRFNCOL),
SUM(BDBASEINSS13COL),
SUM(BDVALORINSS13COL),
SUM(BDBASEIRRF13COL),
SUM(BDVALORIRRF13COL)
FROM (
   SELECT BASE.BDCODEMP, BASE.BDCODCOL, BASE.BDREFCOL,
   REF.BDBASEINSSNCOL,
   REF.BDVALORINSSNCOL,
   REF.BDBASEIRRFNCOL,
   REF.BDVALORIRRFNCOL,
   0 BDBASEINSS13COL,
   0 BDVALORINSS13COL,
   0 BDBASEIRRF13COL,
   0 BDVALORIRRF13COL
   FROM
   (
     SELECT
         X.BDCODEMP,
         X.BDCODCOL,
         (SELECT MIN(D1.BDREFCOL) FROM VRHF_EMP_TCOLCON_MVINC D1 WHERE D1.BDCODEMP = X.BDCODEMP AND D1.BDCODCOL = X.BDCODCOL) AS BDREFCOL
     FROM VRH_EMP_TCOLCON X
   ) AS BASE,
   VRHF_EMP_TCOLCON_MVINC REF
   WHERE BASE.BDCODEMP = REF.BDCODEMP AND BASE.BDCODCOL = REF.BDCODCOL AND BASE.BDREFCOL = REF.BDREFCOL AND COALESCE(BDTIPOCALC, 0) = 0
   UNION ALL
   SELECT BASE.BDCODEMP, BASE.BDCODCOL, BASE.BDREFCOL,
   0 BDBASEINSSNCOL,
   0 BDVALORINSSNCOL,
   0 BDBASEIRRFNCOL,
   0 BDVALORIRRFNCOL,
   REF.BDBASEINSSNCOL BDBASEINSS13COL,
   REF.BDVALORINSSNCOL BDVALORINSS13COL,
   REF.BDBASEIRRFNCOL BDBASEIRRF13COL,
   REF.BDVALORIRRFNCOL BDVALORIRRF13COL
   FROM
   (
     SELECT
         X.BDCODEMP,
         X.BDCODCOL,
         (SELECT MIN(D1.BDREFCOL) FROM VRHF_EMP_TCOLCON_MVINC D1 WHERE D1.BDCODEMP = X.BDCODEMP AND D1.BDCODCOL = X.BDCODCOL) AS BDREFCOL
     FROM VRH_EMP_TCOLCON X
   ) AS BASE,
   VRHF_EMP_TCOLCON_MVINC REF
   WHERE BASE.BDCODEMP = REF.BDCODEMP AND BASE.BDCODCOL = REF.BDCODCOL AND BASE.BDREFCOL = REF.BDREFCOL AND COALESCE(BDTIPOCALC, 0) = 1
)
GROUP BY BDCODEMP, BDCODCOL, BDREFCOL
;

--Sol. 18845 - Bruno L. R. - 08/06/2017 - Adicionado campo BDPERCGORJ, que guarda o percentual de Gorjeta
/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOL_CALC_ADM (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOL_CALC_ADM(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDTIPOCOL,
    BDHORASMENSAISCOL,
    BDHORASSEMANAISCOL,
    BDHORASDIARIASCOL,
    BDPERCINSALUBCOL,
    BDINCIDINSALUBCOL,
    BDPERCPERCULCOL,
    BDINCIDPERICULCOL,
    BDPERCNOTURNOCOL,
    BDINCIDNOTURNOCOL,
    BDNRODEPSALFAMCOL,
    BDIGNORAFALTASFERCOL,
    BDCALCADIANTACOL,
    BDNAOARREDONDARCOL,
    BDIMPETIQUETACOL,
    BDCALCDSRRVCOL,
    BDCALCDSRHECOL,
    BDCALCDSRSALCOL,
    BDCALCVALTRANSCOL,
    BDCALCVALREFCOL,
    BDPERCADISAL,
    BDREGIMEPARCIALCOL,
    BDPERCGORJ,
    BDCARTAOVA,
    BDCARTAOVR,
    BDCARTAOVT)
AS
SELECT BASE.bdCODEMP, BASE.bdcodcol, BASE.bdREFCOL,
CALC.bdtipocol,
CALC.bdhorasmensaiscol,
CALC.bdhorassemanaiscol,
CALC.bdhorasdiariascol,
CALC.bdpercinsalubcol,
CALC.bdincidinsalubcol,
CALC.bdpercperculcol,
CALC.bdincidpericulcol,
CALC.bdpercnoturnocol,
CALC.bdincidnoturnocol,
CALC.bdnrodepsalfamcol,
CALC.bdignorafaltasfercol,
CALC.bdcalcadiantacol,
CALC.bdnaoarredondarcol,
CALC.bdimpetiquetacol,
CALC.bdcalcdsrrvcol,
CALC.bdcalcdsrhecol,
CALC.bdcalcdsrsalcol,
CALC.bdcalcvaltranscol,
CALC.bdcalcvalrefcol,
CALC.bdPERCADISAL,
CALC.BDREGIMEPARCIALCOL,
CALC.BDPERCGORJ,
CALC.BDCARTAOVA,
CALC.BDCARTAOVR,
CALC.BDCARTAOVT
FROM
(
  SELECT
    x.bdcodemp,
    x.bdcodcol,
    (SELECT MIN(d1.bdrefcol) FROM vrhf_emp_tcol_calc d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol) AS bdrefcol
  FROM vrh_emp_tcolcon x
)
AS BASE, VRHF_EMP_TCOL_CALC calc
WHERE calc.bdcodemp = base.bdcodemp AND calc.bdcodcol = base.bdcodcol AND calc.bdrefcol = base.bdrefcol
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCON_VINC_ADM (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCON_VINC_ADM(
BDCODEMP,
BDCODCOL,
BDREFCOL,
BDCODGPS,
BDDESCINSSDOIRCOL)
 AS 
SELECT BASE.bdcodemp, BASE.bdcodcol, BASE.bdrefcol,
REF.bdcodgps,
REF.bddescinssdoircol
FROM
(
  SELECT
      X.bdcodemp,
      X.bdcodcol,
      (SELECT MIN(d1.bdrefcol) FROM vrhf_emp_tcon_vinc d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol) AS bdrefcol
  FROM vrh_emp_tcolcon x
) AS BASE, vrhf_emp_tcon_vinc REF
WHERE BASE.bdcodemp = REF.bdcodemp AND BASE.bdcodcol = REF.bdcodcol AND BASE.bdREFCOL = REF.bdREFCOL
;

CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_CAD_ADM(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDCONTRCOL,
    BDNOMCOL,
    BDNOMCOLUPPER,
    BDCODPAISRES,
    BDCEPCOL,
    BDLOGRCOL,
    BDENDCOL,
    BDNUMCOL,
    BDCOMPLCOL,
    BDBAICOL,
    BDCODCID,
    BDDDDCOL,
    BDFONECOL,
    BDDDDCELCOL,
    BDCELCOL,
    BDEMAILCOL,
    BDGRAUINSTCOL,
    BDESTCIVCOL,
    BDSEXOCOL,
    BDDATACHEBRASILCOL,
    BDCASADOBR,
    BDFILHOSBR,
    BDCODCLE,
    BDTEMPORESIDENCIA,
    BDCONDICAOINGRESSO)
AS
SELECT BASE.BDCODEMP, BASE.BDCODCOL, BASE.BDREFCOL,
CAD.BDCONTRCOL,
CAD.BDNOMCOL,
CAD.BDNOMCOLUPPER,
CAD.BDCODPAISRES,
CAD.BDCEPCOL,
CAD.BDLOGRCOL,
CAD.BDENDCOL,
CAD.BDNUMCOL,
CAD.BDCOMPLCOL,
CAD.BDBAICOL,
CAD.BDCODCID,
CAD.BDDDDCOL,
CAD.BDFONECOL,
CAD.BDDDDCELCOL,
CAD.BDCELCOL,
CAD.BDEMAILCOL,
CAD.BDGRAUINSTCOL,
CAD.BDESTCIVCOL,
CAD.BDSEXOCOL,
CAD.BDDATACHEBRASILCOL,
CAD.BDCASADOBR,
CAD.BDFILHOSBR,
CAD.BDCODCLE,
CAD.BDTEMPORESIDENCIA,
CAD.BDCONDICAOINGRESSO
FROM
(
  SELECT
      X.BDCODEMP,
      X.BDCODCOL,
      (SELECT MIN(D1.BDREFCOL) FROM VRH_EMP_TCOLCON_CAD D1 WHERE D1.BDCODEMP = X.BDCODEMP AND D1.BDCODCOL = X.BDCODCOL) AS BDREFCOL
  FROM VRH_EMP_TCOLCON X
) AS BASE, VRH_EMP_TCOLCON_CAD CAD
WHERE BASE.BDCODEMP = CAD.BDCODEMP AND BASE.BDCODCOL = CAD.BDCODCOL AND BASE.BDREFCOL = CAD.BDREFCOL
;

CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_DOCREF(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDCONTRCOL,
    BDPISCOL,
    BDDATAEMIPISCOL,
    BDRGCOL,
    BDORGEMIRGCOL,
    BDDATAEMIRGCOL,
    BDCODUFRG,
    BDNUMRICCOL,
    BDORGAORICCOL,
    BDDATAEMIRICCOL,
    BDCODCIDRIC,
    BDNUMRNECOL,
    BDORGAORNECOL,
    BDDATAEMIRNECOL,
    BDNUMOCCOL,
    BDORGAOOCCOL,
    BDDATAEMIOCCOL,
    BDDATAVALOCCOL,
    BDCTPSCOL,
    BDSERIECTPSCOL,
    BDDSERIECTPSCOL,
    BDDATAEMICTPSCOL,
    BDCODUF,
    BDCNHCOL,
    BDVENCCNHCOL,
    BDCATCNHCOL,
    BDORGAOCNH,
    BDDATAEMICNH,
    BDUFCNH)
AS
SELECT BASE.BDCODEMP, BASE.BDCODCOL, BASE.BDREFCOL,
DOCREF.BDCONTRCOL,
DOCREF.BDPISCOL,
DOCREF.BDDATAEMIPISCOL,
DOCREF.BDRGCOL,
DOCREF.BDORGEMIRGCOL,
DOCREF.BDDATAEMIRGCOL,
DOCREF.BDCODUFRG,
DOCREF.BDNUMRICCOL,
DOCREF.BDORGAORICCOL,
DOCREF.BDDATAEMIRICCOL,
DOCREF.BDCODCIDRIC,
DOCREF.BDNUMRNECOL,
DOCREF.BDORGAORNECOL,
DOCREF.BDDATAEMIRNECOL,
DOCREF.BDNUMOCCOL,
DOCREF.BDORGAOOCCOL,
DOCREF.BDDATAEMIOCCOL,
DOCREF.BDDATAVALOCCOL,
CASE WHEN COALESCE(DOCREF.BDCTPSCOL, '') = '' AND COALESCE(DOCREF.BDSERIECTPSCOL, '') = '' THEN SUBSTRING(REPLACE(REPLACE(BASE.BDCPFCOL, '.', ''), '-', '') FROM 1 FOR 7) ELSE DOCREF.BDCTPSCOL END BDCTPSCOL,
CASE WHEN COALESCE(DOCREF.BDCTPSCOL, '') = '' AND COALESCE(DOCREF.BDSERIECTPSCOL, '') = '' THEN SUBSTRING(REPLACE(REPLACE(BASE.BDCPFCOL, '.', ''), '-', '') FROM 8 FOR 4) ELSE DOCREF.BDSERIECTPSCOL END BDSERIECTPSCOL,
DOCREF.BDDSERIECTPSCOL,
CASE WHEN COALESCE(DOCREF.BDCTPSCOL, '') = '' AND COALESCE(DOCREF.BDSERIECTPSCOL, '') = '' THEN BASE.BDDATACADCOL ELSE DOCREF.BDDATAEMICTPSCOL END BDDATAEMICTPSCOL,
CASE WHEN COALESCE(DOCREF.BDCTPSCOL, '') = '' AND COALESCE(DOCREF.BDSERIECTPSCOL, '') = '' THEN CASE WHEN CIDEMP.BDCODUF BETWEEN 1 AND 27 THEN CIDEMP.BDCODUF WHEN CIDEMPM.BDCODUF BETWEEN 1 AND 27 THEN CIDEMPM.BDCODUF ELSE NULL END ELSE DOCREF.BDCODUF END BDCODUF,
DOCREF.BDCNHCOL,
DOCREF.BDVENCCNHCOL,
DOCREF.BDCATCNHCOL,
DOCREF.BDORGAOCNH,
DOCREF.BDDATAEMICNH,
DOCREF.BDUFCNH
FROM
(
SELECT
    X.BDCODEMP,
    X.BDCODCOL,
COALESCE
(
  (SELECT MAX(D1.BDREFCOL) FROM VRH_EMP_TCOLCON_DOCREF D1 WHERE D1.BDCODEMP = X.BDCODEMP AND D1.BDCODCOL = X.BDCODCOL AND CAST(D1.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) FROM RDB$DATABASE)),
  (SELECT MIN(D1.BDREFCOL) FROM VRH_EMP_TCOLCON_DOCREF D1 WHERE D1.BDCODEMP = X.BDCODEMP AND D1.BDCODCOL = X.BDCODCOL)
) AS BDREFCOL,
    X.BDCPFCOL,
    X.BDDATACADCOL
FROM VRH_EMP_TCOLCON X
)
AS BASE
JOIN VRH_EMP_TCOLCON_DOCREF DOCREF ON DOCREF.BDCODEMP = BASE.BDCODEMP AND DOCREF.BDCODCOL = BASE.BDCODCOL AND DOCREF.BDREFCOL = BASE.BDREFCOL
LEFT OUTER JOIN TEMPRESAS EMPCOL ON (EMPCOL.BDCODEMP = BASE.BDCODEMP)
LEFT OUTER JOIN TEMPRESAS_REF EMPR ON (EMPR.BDCODEMP = EMPCOL.BDCODEMP AND
                                       EMPR.BDREFEMP = (SELECT FIRST 1 BDREFEMP FROM TEMPRESAS_REF WHERE BDCODEMP = EMPR.BDCODEMP AND BDREFEMP <= (SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) FROM RDB$DATABASE) ORDER BY BDREFEMP DESC))
LEFT OUTER JOIN TCIDADE CIDEMP ON (CIDEMP.BDCODCID = EMPR.BDCODCID)
LEFT OUTER JOIN TEMPRESAS EMPM ON (EMPM.BDCODEMP = EMPCOL.BDCODMATRIZ)
LEFT OUTER JOIN TEMPRESAS_REF EMPRM ON (EMPRM.BDCODEMP = EMPM.BDCODEMP AND
                                        EMPRM.BDREFEMP = (SELECT FIRST 1 BDREFEMP FROM TEMPRESAS_REF WHERE BDCODEMP = EMPRM.BDCODEMP AND BDREFEMP <= (SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) FROM RDB$DATABASE) ORDER BY BDREFEMP DESC))
LEFT OUTER JOIN TCIDADE CIDEMPM ON (CIDEMPM.BDCODCID = EMPRM.BDCODCID)
;

--Sol. 18845 - Bruno L. R. - Adicionado o campo BDPERCGORJ, que guarda o percentual de gorjeta
/* CREATE OR ALTER VIEW: VW_COLABORADORES_REF_ADM (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_COLABORADORES_REF_ADM(
BDCODEMP,
BDCODCOL,
BDNOMCOL,
BDDATAADMCOL,
BDCONTRCOL,
BDCODCID,
BDCODUF,
BDGRAUINSTCOL,
BDESTCIVCOL,
BDSEXOCOL,
BDDATANASCCOL,
BDDATACADCOL,
BDDATAADICCOL,
BDCODCLA,
BDGRUPOCLA,
BDCODMEN,
BDCODSINTRAB,
BDCODBAN,
BDCODAG,
BDCTADEPCOL,
BDDIGCTADEPCOL,
BDTIPOCTACOL,
BDMODOPAGTOCOL,
BDCARTAOSALCOL,
BDFORMAPAGTOCOL,
BDNRODEPIRCOL,
BDBASEIRRFADCOL,
BDVALORPREVPRIVNCOL,
BDVALORPREVPRIV13COL,
BDDATAOPCAOFGTSCOL,
BDCTAFGTSCOL,
BDCATEGORIACOL,
BDPERCFGTSCOL,
BDOCORRENCIACOL,
BDPERCRATCOL,
BDPERCDESCFPASCOL,
BDBASEINSSNCOL,
BDVALORINSSNCOL,
BDBASEIRRFNCOL,
BDVALORIRRFNCOL,
BDBASEINSS13COL,
BDVALORINSS13COL,
BDBASEIRRF13COL,
BDVALORIRRF13COL,
BDTIPOCOL,
BDHORASMENSAISCOL,
BDHORASSEMANAISCOL,
BDHORASDIARIASCOL,
BDPERCINSALUBCOL,
BDINCIDINSALUBCOL,
BDPERCPERCULCOL,
BDINCIDPERICULCOL,
BDPERCNOTURNOCOL,
BDINCIDNOTURNOCOL,
BDNRODEPSALFAMCOL,
BDIGNORAFALTASFERCOL,
BDCALCADIANTACOL,
BDNAOARREDONDARCOL,
BDIMPETIQUETACOL,
BDCALCDSRRVCOL,
BDCALCDSRHECOL,
BDCALCDSRSALCOL,
BDCALCVALTRANSCOL,
BDCALCVALREFCOL,
BDPERCADISAL,
BDOBSCOL,
BDCODGPS,
BDDESCINSSDOIRCOL,
BDCPFCOL,
BDDESCCLA,
BDPERCGORJ)
 AS 
SELECT COLCON.BDCODEMP, COLCON.BDCODCOL, COLCAD.BDNOMCOL, COLCON.BDDATAADMCOL, COLCON.BDCONTRCOL, COLCAD.BDCODCID, DOCREF.BDCODUF,
       COLCAD.BDGRAUINSTCOL, COLCAD.BDESTCIVCOL, COLCAD.BDSEXOCOL, COLCON.BDDATANASCCOL, COLCON.BDDATACADCOL, COLCON.BDDATAADICCOL,
       COLCON_VINC.BDCODCLA, CLASSE.BDGRUPOCLA,
       COL_VINC.BDCODMEN, COL_VINC.BDCODSINTRAB,
       COLCON_BANCO.BDCODBAN, COLCON_BANCO.BDCODAG, COLCON_BANCO.BDCTADEPCOL, COLCON_BANCO.BDDIGCTADEPCOL ,
       COLCON_BANCO.BDTIPOCTACOL, COLCON_BANCO.BDMODOPAGTOCOL, COLCON_BANCO.BDCARTAOSALCOL,
       COLCON_CALC.BDFORMAPAGTOCOL, COLCON_CALC.BDNRODEPIRCOL, COLCON_CALC.BDBASEIRRFADCOL ,
       COLCON_CALC.BDVALORPREVPRIVNCOL, COLCON_CALC.BDVALORPREVPRIV13COL,
       COLCON_FGTSGPS.BDDATAOPCAOFGTSCOL, COLCON_FGTSGPS.BDCTAFGTSCOL, COLCON_FGTSGPS.BDCATEGORIACOL ,
       COLCON_FGTSGPS.BDPERCFGTSCOL, COLCON_FGTSGPS.BDOCORRENCIACOL ,
       COLCON_FGTSGPS.BDPERCRATCOL, COLCON_FGTSGPS.BDPERCDESCFPASCOL,
       COLCON_MVINC.BDBASEINSSNCOL, COLCON_MVINC.BDVALORINSSNCOL, COLCON_MVINC.BDBASEIRRFNCOL ,
       COLCON_MVINC.BDVALORIRRFNCOL, COLCON_MVINC.BDBASEINSS13COL, COLCON_MVINC.BDVALORINSS13COL ,
       COLCON_MVINC.BDBASEIRRF13COL, COLCON_MVINC.BDVALORIRRF13COL,
       COL_CALC.BDTIPOCOL, COL_CALC.BDHORASMENSAISCOL, COL_CALC.BDHORASSEMANAISCOL, COL_CALC.BDHORASDIARIASCOL,
       COL_CALC.BDPERCINSALUBCOL, COL_CALC.BDINCIDINSALUBCOL, COL_CALC.BDPERCPERCULCOL, COL_CALC.BDINCIDPERICULCOL,
       COL_CALC.BDPERCNOTURNOCOL, COL_CALC.BDINCIDNOTURNOCOL, COL_CALC.BDNRODEPSALFAMCOL, COL_CALC.BDIGNORAFALTASFERCOL,
       COL_CALC.BDCALCADIANTACOL, COL_CALC.BDNAOARREDONDARCOL, COL_CALC.BDIMPETIQUETACOL, COL_CALC.BDCALCDSRRVCOL,
       COL_CALC.BDCALCDSRHECOL, COL_CALC.BDCALCDSRSALCOL, COL_CALC.BDCALCVALTRANSCOL, COL_CALC.BDCALCVALREFCOL, COL_CALC.BDPERCADISAL,
       COL_HISTF.BDOBSCOL, CON_VINC.BDCODGPS, CON_VINC.BDDESCINSSDOIRCOL,
       COLCON_DOC.BDCPFCOL, CLASSE.BDDESCCLA, COL_CALC.BDPERCGORJ
FROM VRH_EMP_TCOLCON COLCON
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_VINC_ADM COLCON_VINC
  ON (COLCON_VINC.BDCODEMP = COLCON.BDCODEMP AND COLCON_VINC.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRH_EMP_TCOL_VINC_ADM COL_VINC
  ON (COL_VINC.BDCODEMP = COLCON.BDCODEMP AND COL_VINC.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRHF_EMP_TCOLCON_BANCO_ADM COLCON_BANCO
  ON (COLCON_BANCO.BDCODEMP = COLCON.BDCODEMP AND COLCON_BANCO.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRHF_EMP_TCOLCON_CALC_ADM COLCON_CALC
  ON (COLCON_CALC.BDCODEMP = COLCON.BDCODEMP AND COLCON_CALC.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRHF_EMP_TCOLCON_FGTSGPS_ADM COLCON_FGTSGPS
  ON (COLCON_FGTSGPS.BDCODEMP = COLCON.BDCODEMP AND COLCON_FGTSGPS.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRHF_EMP_TCOLCON_MVINC_ADM COLCON_MVINC
  ON (COLCON_MVINC.BDCODEMP = COLCON.BDCODEMP AND COLCON_MVINC.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRHF_EMP_TCOL_CALC_ADM COL_CALC
  ON (COL_CALC.BDCODEMP = COLCON.BDCODEMP AND COL_CALC.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VRHF_EMP_TCOL_HIST COL_HISTF
  ON (COL_HISTF.BDCODEMP = COLCON.BDCODEMP AND COL_HISTF.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRHF_EMP_TCON_VINC_ADM CON_VINC
  ON (CON_VINC.BDCODEMP = COLCON.BDCODEMP AND CON_VINC.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC COLCON_DOC
  ON (COLCON_DOC.BDCODEMP = COLCON.BDCODEMP AND COLCON_DOC.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VRH_BASE_TCLASSE CLASSE
  ON (COLCON_VINC.BDCODCLA = CLASSE.BDCODCLA)
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD_ADM COLCAD
  ON (COLCAD.BDCODEMP = COLCON.BDCODEMP AND COLCAD.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF DOCREF
  ON (DOCREF.BDCODEMP = COLCON.BDCODEMP AND DOCREF.BDCODCOL = COLCON.BDCODCOL)
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOLCON_VINC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_VINC(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDCODCLA,
    BDCODCENTRO,
    BDCODTPCC)
AS
SELECT BASE.bdcodemp, BASE.bdcodcol, BASE.bdrefcol, V.bdcodcla, v.bdcodcentro, v.bdcodtpcc
FROM
(
  SELECT
      X.bdcodemp,
      X.bdcodcol,
      COALESCE
  (
      (SELECT MAX(d2.bdrefcol) FROM vrh_emp_tcolcon_vinc d2 WHERE d2.bdcodemp = x.bdcodemp AND d2.bdcodcol = x.bdcodcol AND CAST(d2.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefcol) FROM vrh_emp_tcolcon_vinc d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol)
  ) AS bdrefcol
  FROM vrh_emp_tcolcon x
) AS BASE, vrh_emp_tcolcon_vinc v
WHERE BASE.bdcodemp = v.bdcodemp AND BASE.bdcodcol = v.bdcodcol AND BASE.bdREFCOL = v.bdREFCOL
/*
select
    X.bdcodemp,
    X.bdcodcol,
    X.bdrefcol,
    X.bdcodcla
from vrh_emp_tcolcon_vinc X
where
  exists (select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFCOL, Z.BDREFCOL
          from VW_VRH_EMP_TCOLCON_VINC_MIN Y
          left outer join VW_VRH_EMP_TCOLCON_VINC_MAX Z
            on (Z.BDCODEMP = Y.BDCODEMP and Z.BDCODCOL = Y.BDCODCOL and Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL)
          where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and ((Y.BDREFCOL = X.BDREFCOL and Z.BDREFCOL is null) or (Z.BDREFCOL = X.BDREFCOL))
         )
*/
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOL_VINC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOL_VINC(
BDCODEMP,
BDCODCOL,
BDREFCOL,
BDCODMEN,
BDCODSINTRAB,
BDCODSINTRABCLA)
 AS 
SELECT BASE.bdCODEMP, BASE.bdCODCOL, BASE.bdREFCOL, VIN.bdCODMEN, VIN.bdCODSINTRAB, VIN.bdCODSINTRABCLA
FROM
(
  SELECT
    col.bdCODEMP,
    col.bdCODCOL,
    COALESCE
    (
      (SELECT MAX(d1.bdrefcol) FROM vrh_emp_tcol_vinc d1 WHERE d1.bdcodemp = col.bdcodemp AND d1.bdcodcol = col.bdcodcol AND CAST(d1.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d2.bdrefcol) FROM vrh_emp_tcol_vinc d2 WHERE d2.bdcodemp = col.bdcodemp AND d2.bdcodcol = col.bdcodcol)
    ) AS bdREFCOL
  FROM vrh_emp_tcolcon col
) AS BASE, vrh_emp_tcol_vinc VIN
WHERE BASE.bdCODEMP = VIN.bdCODEMP AND BASE.bdCODCOL = VIN.bdCODCOL AND BASE.bdREFCOL = VIN.bdREFCOL
/*
select
    X.bdcodemp,
    X.bdcodcol,
    X.bdrefcol,
    X.bdcodmen,
    X.bdcodsintrab
from vrh_emp_tcol_vinc X
where
  exists (select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFCOL, Z.BDREFCOL
          from VW_VRH_EMP_TCOL_VINC_MIN Y
          left outer join VW_VRH_EMP_TCOL_VINC_MAX Z
            on (Z.BDCODEMP = Y.BDCODEMP and Z.BDCODCOL = Y.BDCODCOL and Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL)
          where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and ((Y.BDREFCOL = X.BDREFCOL and Z.BDREFCOL is null) or (Z.BDREFCOL = X.BDREFCOL))
         )
*/
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_BANCO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_BANCO(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDCODBAN,
    BDCODAG,
    BDCTADEPCOL,
    BDDIGCTADEPCOL,
    BDTIPOCTACOL,
    BDMODOPAGTOCOL,
    BDCARTAOSALCOL,
    BDMODOPAGTOCOLPIXTPCH,
    BDMODOPAGTOCOLPIXCH)
AS
SELECT BASE.bdcodemp, BASE.bdcodcol, BASE.bdrefcol,
REF.bdcodban,
REF.bdcodag,
REF.bdctadepcol,
REF.bddigctadepcol,
REF.bdtipoctacol,
REF.bdmodopagtocol,
REF.bdcartaosalcol,
REF.bdmodopagtocolpixtpch,
REF.bdmodopagtocolpixch
FROM
(
  SELECT
      X.bdcodemp,
      X.bdcodcol,
      COALESCE
  (
      (SELECT MAX(d2.bdrefcol) FROM vrhf_emp_tcolcon_banco d2 WHERE d2.bdcodemp = x.bdcodemp AND d2.bdcodcol = x.bdcodcol AND CAST(d2.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefcol) FROM vrhf_emp_tcolcon_banco d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol)
  ) AS bdrefcol
  FROM vrh_emp_tcolcon x
) AS BASE, vrhf_emp_tcolcon_banco REF
WHERE BASE.bdcodemp = REF.bdcodemp AND BASE.bdcodcol = REF.bdcodcol AND BASE.bdREFCOL = REF.bdREFCOL
/*
select
    X.bdcodemp,
    X.bdcodcol,
    X.bdrefcol,
    X.bdcodban,
    X.bdcodag,
    X.bdctadepcol,
    X.bddigctadepcol,
    X.bdtipoctacol,
    X.bdmodopagtocol,
    X.bdcartaosalcol
from vrhf_emp_tcolcon_banco X
where
  exists (select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFCOL, Z.BDREFCOL
          from VW_VRHF_EMP_TCOLCON_BANCO_MIN Y
          left outer join VW_VRHF_EMP_TCOLCON_BANCO_MAX Z
            on (Z.BDCODEMP = Y.BDCODEMP and Z.BDCODCOL = Y.BDCODCOL and Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL)
          where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and ((Y.BDREFCOL = X.BDREFCOL and Z.BDREFCOL is null) or (Z.BDREFCOL = X.BDREFCOL))
         )
*/
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_CALC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_CALC(
BDCODEMP,
BDCODCOL,
BDREFCOL,
BDFORMAPAGTOCOL,
BDNRODEPIRCOL,
BDBASEIRRFADCOL,
BDVALORPREVPRIVNCOL,
BDVALORPREVPRIV13COL,
BDCODREND)
 AS 
SELECT BASE.bdcodemp, BASE.bdcodcol, BASE.bdrefcol,
REF.bdformapagtocol,
REF.bdnrodepircol,
REF.bdbaseirrfadcol,
REF.bdvalorprevprivncol,
REF.bdvalorprevpriv13col,
REF.bdcodrend
FROM
(
  SELECT
      X.bdcodemp,
      X.bdcodcol,
      COALESCE
  (
      (SELECT MAX(d2.bdrefcol) FROM vrhf_emp_tcolcon_calc d2 WHERE d2.bdcodemp = x.bdcodemp AND d2.bdcodcol = x.bdcodcol AND CAST(d2.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefcol) FROM vrhf_emp_tcolcon_calc d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol)
  ) AS bdrefcol
  FROM vrh_emp_tcolcon x
) AS BASE, vrhf_emp_tcolcon_calc REF
WHERE BASE.bdcodemp = REF.bdcodemp AND BASE.bdcodcol = REF.bdcodcol AND BASE.bdREFCOL = REF.bdREFCOL
/*
select
    X.bdcodemp,
    X.bdcodcol,
    X.bdrefcol,
    X.bdformapagtocol,
    X.bdnrodepircol,
    X.bdbaseirrfadcol,
    X.bdvalorprevprivncol,
    X.bdvalorprevpriv13col
from vrhf_emp_tcolcon_calc X
where
  exists (select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFCOL, Z.BDREFCOL
          from VW_VRHF_EMP_TCOLCON_CALC_MIN Y
          left outer join VW_VRHF_EMP_TCOLCON_CALC_MAX Z
            on (Z.BDCODEMP = Y.BDCODEMP and Z.BDCODCOL = Y.BDCODCOL and Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL)
          where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and ((Y.BDREFCOL = X.BDREFCOL and Z.BDREFCOL is null) or (Z.BDREFCOL = X.BDREFCOL))
         )
*/
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_FGTSGPS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_FGTSGPS(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDCONTRCOL,
    BDDATAOPCAOFGTSCOL,
    BDCTAFGTSCOL,
    BDCATEGORIACOL,
    BDPERCFGTSCOL,
    BDOCORRENCIACOL,
    BDPERCRATCOL,
    BDPERCDESCFPASCOL,
    BDCATEGORIAESOCIAL,
    BDREGPREV,
    BDINTERMITENTE,
    BDCODMULTVINC,
    BDREGIMETRAB)
AS
SELECT BASE.bdcodemp, BASE.bdcodcol, BASE.bdrefcol, BASE.bdcontrcol,
REF.bddataopcaofgtscol,
REF.bdctafgtscol,
REF.bdcategoriacol,
REF.bdpercfgtscol,
REF.bdocorrenciacol,
REF.bdpercratcol,
REF.bdpercdescfpascol,
ref.BDCATEGORIAESOCIAL,
REF.BDREGPREV,
case when (COALESCE(REF.bdocorrenciacol, 0) = 4) and (COALESCE(ref.BDCATEGORIAESOCIAL, 0) = 111) then 'TRUE' else 'FALSE' end,
REF.BDCODMULTVINC,
REF.BDREGIMETRAB
FROM
(
  SELECT
      X.bdcodemp,
      X.bdcodcol,
      COALESCE
  (
      (SELECT MAX(d2.bdrefcol) FROM vrhf_emp_tcolcon_fgtsgps d2 WHERE d2.bdcodemp = x.bdcodemp AND d2.bdcodcol = x.bdcodcol AND CAST(d2.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefcol) FROM vrhf_emp_tcolcon_fgtsgps d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol)
  ) AS bdrefcol,
  x.bdcontrcol
  FROM vrh_emp_tcolcon x
) AS BASE, vrhf_emp_tcolcon_fgtsgps REF
WHERE BASE.bdcodemp = REF.bdcodemp AND BASE.bdcodcol = REF.bdcodcol AND BASE.bdREFCOL = REF.bdREFCOL
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_MVINC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_MVINC(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDCNPJRESP,
    BDREFFIM,
    BDBASEINSSNCOL,
    BDVALORINSSNCOL,
    BDBASEIRRFNCOL,
    BDVALORIRRFNCOL,
    BDBASEINSS13COL,
    BDVALORINSS13COL,
    BDBASEIRRF13COL,
    BDVALORIRRF13COL)
AS
SELECT BDCODEMP, BDCODCOL, BDREFCOL, BDCNPJRESP, BDREFFIM,
SUM(BDBASEINSSNCOL),
SUM(BDVALORINSSNCOL),
SUM(BDBASEIRRFNCOL),
SUM(BDVALORIRRFNCOL),
SUM(BDBASEINSS13COL),
SUM(BDVALORINSS13COL),
SUM(BDBASEIRRF13COL),
SUM(BDVALORIRRF13COL)
FROM
(
   SELECT BASE.BDCODEMP, BASE.BDCODCOL, BASE.BDREFCOL, REF.BDCNPJRESP, REF.BDREFFIM,
   REF.BDBASEINSSNCOL,
   REF.BDVALORINSSNCOL,
   REF.BDBASEIRRFNCOL,
   REF.BDVALORIRRFNCOL,
   0 BDBASEINSS13COL,
   0 BDVALORINSS13COL,
   0 BDBASEIRRF13COL,
   0 BDVALORIRRF13COL
   FROM
   (
     SELECT
         X.BDCODEMP,
         X.BDCODCOL,
        (SELECT MAX(D2.BDREFCOL)
         FROM VRHF_EMP_TCOLCON_MVINC D2
         WHERE D2.BDCODEMP = X.BDCODEMP AND D2.BDCODCOL = X.BDCODCOL AND CAST(D2.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database) AND
               ((COALESCE(D2.BDREFFIM, 0) = 0) OR (CAST(D2.BDREFFIM AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)))
        ) AS BDREFCOL
     FROM VRH_EMP_TCOLCON X
   ) AS BASE, VRHF_EMP_TCOLCON_MVINC REF
   WHERE BASE.BDCODEMP = REF.BDCODEMP AND BASE.BDCODCOL = REF.BDCODCOL AND BASE.BDREFCOL = REF.BDREFCOL AND COALESCE(BDTIPOCALC, 0) = 0
   UNION ALL
   SELECT BASE.BDCODEMP, BASE.BDCODCOL, BASE.BDREFCOL, REF.BDCNPJRESP, REF.BDREFFIM,
   0 BDBASEINSSNCOL,
   0 BDVALORINSSNCOL,
   0 BDBASEIRRFNCOL,
   0 BDVALORIRRFNCOL,
   REF.BDBASEINSSNCOL BDBASEINSS13COL,
   REF.BDVALORINSSNCOL BDVALORINSS13COL,
   REF.BDBASEIRRFNCOL BDBASEIRRF13COL,
   REF.BDVALORIRRFNCOL BDVALORIRRF13COL
   FROM
   (
     SELECT
         X.BDCODEMP,
         X.BDCODCOL,
        (SELECT MAX(D2.BDREFCOL)
         FROM VRHF_EMP_TCOLCON_MVINC D2
         WHERE D2.BDCODEMP = X.BDCODEMP AND D2.BDCODCOL = X.BDCODCOL AND CAST(D2.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database) AND
               ((COALESCE(D2.BDREFFIM, 0) = 0) OR (CAST(D2.BDREFFIM AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)))
        ) AS BDREFCOL
     FROM VRH_EMP_TCOLCON X
   ) AS BASE, VRHF_EMP_TCOLCON_MVINC REF
   WHERE BASE.BDCODEMP = REF.BDCODEMP AND BASE.BDCODCOL = REF.BDCODCOL AND BASE.BDREFCOL = REF.BDREFCOL AND COALESCE(BDTIPOCALC, 0) = 1
)
GROUP BY BDCODEMP, BDCODCOL, BDREFCOL, BDCNPJRESP, BDREFFIM
;

--Sol. 18845 - Bruno L. R. - 08/06/2017 - Adicionado campo que guarda o percentual de Gorjeta
/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOL_CALC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOL_CALC(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDTIPOCOL,
    BDHORASMENSAISCOL,
    BDHORASSEMANAISCOL,
    BDHORASDIARIASCOL,
    BDPERCINSALUBCOL,
    BDINCIDINSALUBCOL,
    BDPERCPERCULCOL,
    BDINCIDPERICULCOL,
    BDPERCNOTURNOCOL,
    BDINCIDNOTURNOCOL,
    BDNRODEPSALFAMCOL,
    BDIGNORAFALTASFERCOL,
    BDCALCADIANTACOL,
    BDNAOARREDONDARCOL,
    BDIMPETIQUETACOL,
    BDCALCDSRRVCOL,
    BDCALCDSRHECOL,
    BDCALCDSRSALCOL,
    BDCALCVALTRANSCOL,
    BDCALCVALREFCOL,
    BDPERCADISAL,
    BDREGIMEPARCIALCOL,
    BDPERCGORJ,
    BDCARTAOVA,
    BDCARTAOVR,
    BDCARTAOVT,
    BDCONTSINDICAL,
    BDAULISTA)
AS
SELECT BASE.bdCODEMP, BASE.bdcodcol, BASE.bdREFCOL,
CALC.bdtipocol,
CALC.bdhorasmensaiscol,
CALC.bdhorassemanaiscol,
CALC.bdhorasdiariascol,
CALC.bdpercinsalubcol,
CALC.bdincidinsalubcol,
CALC.bdpercperculcol,
CALC.bdincidpericulcol,
CALC.bdpercnoturnocol,
CALC.bdincidnoturnocol,
CALC.bdnrodepsalfamcol,
CALC.bdignorafaltasfercol,
CALC.bdcalcadiantacol,
CALC.bdnaoarredondarcol,
CALC.bdimpetiquetacol,
CALC.bdcalcdsrrvcol,
CALC.bdcalcdsrhecol,
CALC.bdcalcdsrsalcol,
CALC.bdcalcvaltranscol,
CALC.bdcalcvalrefcol,
CALC.bdPERCADISAL,
CALC.BDREGIMEPARCIALCOL,
CALC.BDPERCGORJ,
CALC.BDCARTAOVA,
CALC.BDCARTAOVR,
CALC.BDCARTAOVT,
CALC.BDCONTSINDICAL,
CALC.BDAULISTA
FROM
(
SELECT
    x.bdcodemp,
    x.bdcodcol,
COALESCE
(
  (SELECT MAX(d1.bdrefcol) FROM vrhf_emp_tcol_calc d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol AND CAST(d1.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
  (SELECT MIN(d1.bdrefcol) FROM vrhf_emp_tcol_calc d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol)
) AS bdrefcol
FROM vrh_emp_tcolcon x
)
AS BASE, VRHF_EMP_TCOL_CALC calc
WHERE calc.bdcodemp = base.bdcodemp AND calc.bdcodcol = base.bdcodcol AND calc.bdrefcol = base.bdrefcol
;

CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_CAD(
    BDCODEMP,
    BDCODCOL,
    BDDTPCOL,
    BDREFCOL,
    BDCONTRCOL,
    BDNOMCOL,
    BDNOMCOLUPPER,
    BDCODPAISRES,
    BDCEPCOL,
    BDLOGRCOL,
    BDENDCOL,
    BDNUMCOL,
    BDCOMPLCOL,
    BDBAICOL,
    BDCODCID,
    BDDDDCOL,
    BDFONECOL,
    BDDDDCELCOL,
    BDCELCOL,
    BDEMAILCOL,
    BDEMAIL2COL,
    BDGRAUINSTCOL,
    BDESTCIVCOL,
    BDSEXOCOL,
    BDDATACHEBRASILCOL,
    BDCASADOBR,
    BDFILHOSBR,
    BDCODCLE,
    BDTEMPORESIDENCIA,
    BDCONDICAOINGRESSO)
AS
SELECT
BASE.BDCODEMP,
BASE.bdcodCOL,
BASE.BDDTPCOL,
BASE.BDREFCOL,
CAD.BDCONTRCOL,

CASE
    WHEN (FIS.BDNMSOCIAL <> '' and PAR.bdusanomesocial = 'TRUE') THEN FIS.BDNMSOCIAL
    ELSE CAD.BDNOMCOL
END BDNOMCOL,
CASE
    WHEN (FIS.BDNMSOCIAL <> '' and PAR.bdusanomesocial = 'TRUE') THEN UPPER(FIS.BDNMSOCIAL)
    ELSE CAD.BDNOMCOLUPPER
END BDNOMCOLUPPER,
CAD.BDCODPAISRES,
CAD.BDCEPCOL,
CAD.BDLOGRCOL,
CAD.BDENDCOL,
CAD.BDNUMCOL,
CAD.BDCOMPLCOL,
CAD.BDBAICOL,
CAD.BDCODCID,
CAD.BDDDDCOL,
CAD.BDFONECOL,
CAD.BDDDDCELCOL,
CAD.BDCELCOL,
CAD.BDEMAILCOL,
BASE.BDEMAIL2COL,
CAD.BDGRAUINSTCOL,
CAD.BDESTCIVCOL,
CAD.BDSEXOCOL,
CAD.BDDATACHEBRASILCOL,
CAD.BDCASADOBR,
CAD.BDFILHOSBR,
CAD.BDCODCLE,
CAD.BDTEMPORESIDENCIA,
CAD.BDCONDICAOINGRESSO
FROM
(
  SELECT
    X.BDCODEMP,
    X.BDCODCOL,
    X.BDDTPCOL,
      X.BDEMAIL2COL,
      COALESCE
      (
  (SELECT MAX(d1.BDREFCOL) FROM VRH_EMP_TCOLCON_CAD d1 WHERE d1.BDCODEMP = x.BDCODEMP AND d1.BDCODCOL = x.BDCODCOL AND CAST(d1.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
  (SELECT MIN(d1.BDREFCOL) FROM VRH_EMP_TCOLCON_CAD d1 WHERE d1.BDCODEMP = x.BDCODEMP AND d1.BDCODCOL = x.BDCODCOL)
      ) AS BDREFCOL
  FROM VRH_EMP_TCOLCON X
)
AS BASE
JOIN VRH_EMP_TCOLCON_CAD CAD       ON (CAD.BDCODEMP = BASE.BDCODEMP AND
                                       CAD.BDCODCOL = BASE.BDCODCOL AND
                                       CAD.BDREFCOL = BASE.BDREFCOL    )

LEFT JOIN VRH_EMP_TCOLCON_FIS FIS ON (FIS.BDCODEMP = BASE.BDCODEMP AND
                                 FIS.BDCODCOL = BASE.BDCODCOL AND
                                 FIS.BDREFCOL = (SELECT MAX(BDREFCOL)
                                                   FROM VRH_EMP_TCOLCON_FIS
                                                  WHERE BDCODEMP = CAD.BDCODEMP
                                                    AND BDCODCOL = CAD.BDCODCOL
                                                    AND BDREFCOL <= BASE.BDREFCOL))

LEFT JOIN VRHF_BASE_TEMPPAR PAR ON (CAD.BDCODEMP = PAR.BDCODEMP AND
                               PAR.BDREFEMP = (SELECT MAX(BDREFEMP)
                                                 FROM VRHF_BASE_TEMPPAR
                                                WHERE BDCODEMP = PAR.BDCODEMP
                                                  AND BDREFEMP <= BASE.BDREFCOL))
;

CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_FIS(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDCONTRCOL,
    BDGERARNMSOCIAL,
    BDNMSOCIAL,
    BDCORCOL,
    BDDEFCOL,
    BDDEFFIS,
    BDDEFVIS,
    BDDEFAUD,
    BDDEFMEN,
    BDDEFINT,
    BDREAB,
    BDCOTADEF,
    BDOBSDEFFISCOL)
AS
SELECT BASE.BDCODEMP, BASE.BDCODCOL, BASE.BDREFCOL,
FIS.BDCONTRCOL,
FIS.BDGERARNMSOCIAL,
FIS.BDNMSOCIAL,
FIS.BDCORCOL,
FIS.BDDEFCOL,
FIS.BDDEFFIS,
FIS.BDDEFVIS,
FIS.BDDEFAUD,
FIS.BDDEFMEN,
FIS.BDDEFINT,
FIS.BDREAB,
FIS.BDCOTADEF,
FIS.BDOBSDEFFISCOL
FROM
(
SELECT
    X.BDCODEMP,
    X.BDCODCOL,
COALESCE
(
  (SELECT MAX(d1.BDREFCOL) FROM VRH_EMP_TCOLCON_FIS d1 WHERE d1.BDCODEMP = x.BDCODEMP AND d1.BDCODCOL = x.BDCODCOL AND CAST(d1.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
  (SELECT MIN(d1.BDREFCOL) FROM VRH_EMP_TCOLCON_FIS d1 WHERE d1.BDCODEMP = x.BDCODEMP AND d1.BDCODCOL = x.BDCODCOL)
) AS BDREFCOL
FROM VRH_EMP_TCOLCON X
)
AS BASE, VRH_EMP_TCOLCON_FIS FIS
WHERE FIS.BDCODEMP = BASE.BDCODEMP AND FIS.BDCODCOL = BASE.BDCODCOL AND FIS.BDREFCOL = BASE.BDREFCOL
;

CREATE OR ALTER VIEW VW_VRH_EMP_TCOL_ADMREF(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDVINCEMPCOL,
    BDSINDICALIZADOCOL,
    BDALVARACOL,
    BDCODPROCESSO)
AS
SELECT BASE.BDCODEMP, BASE.BDCODCOL, BASE.BDREFCOL,
ADMREF.BDVINCEMPCOL,
ADMREF.BDSINDICALIZADOCOL,
ADMREF.BDALVARACOL,
ADMREF.BDCODPROCESSO
FROM
(
SELECT
    X.BDCODEMP,
    X.BDCODCOL,
COALESCE
(
  (SELECT MAX(d1.BDREFCOL) FROM VRH_EMP_TCOL_ADMREF d1 WHERE d1.BDCODEMP = x.BDCODEMP AND d1.BDCODCOL = x.BDCODCOL AND CAST(d1.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
  (SELECT MIN(d1.BDREFCOL) FROM VRH_EMP_TCOL_ADMREF d1 WHERE d1.BDCODEMP = x.BDCODEMP AND d1.BDCODCOL = x.BDCODCOL)
) AS BDREFCOL
FROM VRH_EMP_TCOLCON X
)
AS BASE, VRH_EMP_TCOL_ADMREF ADMREF
WHERE ADMREF.BDCODEMP = BASE.BDCODEMP AND ADMREF.BDCODCOL = BASE.BDCODCOL AND ADMREF.BDREFCOL = BASE.BDREFCOL
;


/* View: VW_VRH_EMP_TCOL_ADM */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOL_ADM(
    BDCODEMP,
    BDCODCOL,
    BDTIPOADMCOL,
    BDNATUOCUPCOL,
    BDDATAINIAQUICOL,
    BDSALINICOL,
    BDDIASPRAZO1COL,
    BDDATAFIMPRAZO1COL,
    BDDIASPRAZO2COL,
    BDDATAFIMPRAZO2COL,
    BDDESCCONTSINCOL,
    BDALVARACOL,
    BDFICHAREGCOL,
    BDLIVROREGCOL,
    BDNROFOLHAREGCOL,
    BDCONTRCOL,
    BDDESCCONTASSCOL,
    BDREGTRAB,
    BDCODTIPOADMSOCIAL,
    BDCNPJEMPANT,
    BDFICHAREGANT,
    BDDATAADMANT,
    BDFIMCONTRATO,
    BDCATEGORIAESOCIALANT,
    BDREGJORTRAB,
    BDMOTCONTRAT,
    BDCOLSUBST,
    BDINDADMCOL,
    BDTRANSONUS,
    BDNAOTEMMATRICULA,
    BDINDCONTRACAO,
    BDDATATERMINOCONTFATO,
    BDCODTIPOPROV,
    BDNUMEROPROCESSORT,
    BDNOVADATAADMRT,
    BDMATRICULART)
AS
select
  ADM.BDCODEMP,
  ADM.BDCODCOL,
  ADM.BDTIPOADMCOL,
  ADM.BDNATUOCUPCOL,
  ADM.BDDATAINIAQUICOL,
  ADM.BDSALINICOL,
  ADM.BDDIASPRAZO1COL,
  case when coalesce(ADM.BDDIASPRAZO1COL, 0) > 0 then COL.BDDATAADMCOL + ADM.BDDIASPRAZO1COL - 1 else ADM.BDDATAFIMPRAZO1COL end,
  ADM.BDDIASPRAZO2COL,
  case when coalesce(ADM.BDDIASPRAZO2COL, 0) > 0 then COL.BDDATAADMCOL + coalesce(ADM.BDDIASPRAZO1COL, 0) + ADM.BDDIASPRAZO2COL - 1 else ADM.BDDATAFIMPRAZO2COL end,
  ADM.BDDESCCONTSINCOL,
  ADM.BDALVARACOL,
  ADM.BDFICHAREGCOL,
  ADM.BDLIVROREGCOL,
  ADM.BDNROFOLHAREGCOL,
  ADM.BDCONTRCOL,
  ADM.BDDESCCONTASSCOL,
  ADM.BDREGTRAB,
  ADM.BDCODTIPOADMSOCIAL,
  ADM.BDCNPJEMPANT,
  ADM.BDFICHAREGANT,
  ADM.BDDATAADMANT,
  ADM.BDFIMCONTRATO,
  ADM.BDCATEGORIAESOCIALANT,
  ADM.BDREGJORTRAB,
  ADM.BDMOTCONTRAT,
  ADM.BDCOLSUBST,
  ADM.BDINDADMCOL,
  ADM.BDTRANSONUS,
  ADM.BDNAOTEMMATRICULA,
  ADM.BDINDCONTRACAO,
  ADM.BDDATATERMINOCONTFATO,
  ADM.BDCODTIPOPROV,
  ADM.BDNUMEROPROCESSORT,
  ADM.BDNOVADATAADMRT,
  ADM.BDMATRICULART
from
  VRH_EMP_TCOL_ADM ADM
join
  VRH_EMP_TCOLCON COL on (COL.BDCODEMP = ADM.BDCODEMP and COL.BDCODCOL = ADM.BDCODCOL)
;


--Sol. 18845 - Bruno L. R. - Adicionado campo que retorna o percentual de gorjeta
/* CREATE OR ALTER VIEW: VW_COLABORADORES (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_COLABORADORES(
    BDCODEMP,
    BDCODCOL,
    BDCODMCAG,
    BDCODCID,
    BDCODCSEG,
    BDREFCSEG,
    BDCODCIDNASC,
    BDCODUF,
    BDNOMCOL,
    BDLOGRCOL,
    BDENDCOL,
    BDNUMCOL,
    BDCOMPLCOL,
    BDBAICOL,
    BDCEPCOL,
    BDDDDCOL,
    BDFONECOL,
    BDDDDCELCOL,
    BDCELCOL,
    BDEMAILCOL,
    BDSEXOCOL,
    BDDATANASCCOL,
    BDDATACADCOL,
    BDDATAADMCOL,
    BDDATAADICCOL,
    BDCONTRCOL,
    BDRGCOL,
    BDORGEMIRGCOL,
    BDDATAEMIRGCOL,
    BDCPFCOL,
    BDRESERVISTACOL,
    BDPISCOL,
    BDDATAEMIPISCOL,
    BDTIPOCERTCIVILCOL,
    BDDATACERTCIVILCOL,
    BDTERMOCERTCIVILCOL,
    BDCARTORIOCERTCIVILCOL,
    BDLIVROCERTCIVILCOL,
    BDFOLHACERTCIVILCOL,
    BDCODUFRG,
    BDCODCIDCERTCIVIL,
    BDNUMRICCOL,
    BDORGAORICCOL,
    BDDATAEMIRICCOL,
    BDCODCIDRIC,
    BDCODUF_COL_DOC,
    BDTITELEICOL,
    BDZONAELEICOL,
    BDSECAOELEICOL,
    BDCTPSCOL,
    BDSERIECTPSCOL,
    BDDSERIECTPSCOL,
    BDDATAEMICTPSCOL,
    BDCNHCOL,
    BDVENCCNHCOL,
    BDCATCNHCOL,
    BDCODPAIS,
    BDNATURALIZADOCOL,
    BDDATACHEBRASILCOL,
    BDCODCIDNASCCONJ,
    BDNOMPAICOL,
    BDNOMMAECOL,
    BDNOMCONJCOL,
    BDDATANASCCONJCOL,
    BDCORCOL,
    BDCABELOSCOL,
    BDOLHOSCOL,
    BDALTURACOL,
    BDPESOCOL,
    BDSINAISCOL,
    BDDEFCOL,
    BDDEFFIS,
    BDDEFVIS,
    BDDEFAUD,
    BDDEFMEN,
    BDDEFINT,
    BDREAB,
    BDTIPOSANGUECOL,
    BDNROCONSPROCOL,
    BDSIGLACONSPROCOL,
    BDCODCCMPROCOL,
    BDTIPOADMCOL,
    BDNATUOCUPCOL,
    BDDATAINIAQUICOL,
    BDSALINICOL,
    BDDIASPRAZO1COL,
    BDDATAFIMPRAZO1COL,
    BDDIASPRAZO2COL,
    BDDATAFIMPRAZO2COL,
    BDDESCCONTSINCOL,
    BDVINCEMPCOL,
    BDALVARACOL,
    BDSINDICALIZADOCOL,
    BDREGIMEPARCIALCOL,
    BDFICHAREGCOL,
    BDLIVROREGCOL,
    BDNROFOLHAREGCOL,
    BDGRAUINSTCOL,
    BDESTCIVCOL,
    BDCODPAISNAS,
    BDDTAPOSENT,
    BDPERCGORJ,
    BDNOVADATAADMRT)
AS
SELECT COLCON.BDCODEMP, COLCON.BDCODCOL , COLCON.BDCODMCAG, COLCAD.BDCODCID, COLCON.BDCODCSEG, COLCON.BDREFCSEG ,
       COLCON.BDCODCIDNASC, DOCREF.BDCODUF, COLCAD.BDNOMCOL, COLCAD.BDLOGRCOL, COLCAD.BDENDCOL , COLCAD.BDNUMCOL,
       COLCAD.BDCOMPLCOL, COLCAD.BDBAICOL, COLCAD.BDCEPCOL, COLCAD.BDDDDCOL , COLCAD.BDFONECOL, COLCAD.BDDDDCELCOL, COLCAD.BDCELCOL,
       COLCAD.BDEMAILCOL, COLCAD.BDSEXOCOL, COLCON.BDDATANASCCOL, COLCON.BDDATACADCOL,
       COLCON.BDDATAADMCOL, COLCON.BDDATAADICCOL, COLCON.BDCONTRCOL,
       DOCREF.BDRGCOL, DOCREF.BDORGEMIRGCOL, DOCREF.BDDATAEMIRGCOL,
       COLCON_DOC.BDCPFCOL, COLCON_DOC.BDRESERVISTACOL, DOCREF.BDPISCOL, DOCREF.BDDATAEMIPISCOL,
       COLCON_DOC.BDTIPOCERTCIVILCOL, COLCON_DOC.BDDATACERTCIVILCOL, COLCON_DOC.BDTERMOCERTCIVILCOL, COLCON_DOC.BDCARTORIOCERTCIVILCOL,
       COLCON_DOC.BDLIVROCERTCIVILCOL, COLCON_DOC.BDFOLHACERTCIVILCOL, DOCREF.BDCODUFRG, COLCON_DOC.BDCODCIDCERTCIVIL,
       DOCREF.BDNUMRICCOL, DOCREF.BDORGAORICCOL, DOCREF.BDDATAEMIRICCOL, DOCREF.BDCODCIDRIC,
       DOCREF.BDCODUF, COL_DOC.BDTITELEICOL ,
       COL_DOC.BDZONAELEICOL, COL_DOC.BDSECAOELEICOL, DOCREF.BDCTPSCOL, DOCREF.BDSERIECTPSCOL , DOCREF.BDDSERIECTPSCOL,
       DOCREF.BDDATAEMICTPSCOL, DOCREF.BDCNHCOL, DOCREF.BDVENCCNHCOL , DOCREF.BDCATCNHCOL,
       COL_HIST.BDCODPAIS, COL_HIST.BDNATURALIZADOCOL, COLCAD.BDDATACHEBRASILCOL,
       COL_PARENT.BDCODCIDNASCCONJ, COL_PARENT.BDNOMPAICOL, COL_PARENT.BDNOMMAECOL, COL_PARENT.BDNOMCONJCOL,
       COL_PARENT.BDDATANASCCONJCOL,
       CFIS.BDCORCOL, COL_FIS.BDCABELOSCOL, COL_FIS.BDOLHOSCOL, COL_FIS.BDALTURACOL, COL_FIS.BDPESOCOL ,
       COL_FIS.BDSINAISCOL, CFIS.BDDEFCOL, CFIS.BDDEFFIS, CFIS.BDDEFVIS, CFIS.BDDEFAUD, CFIS.BDDEFMEN, CFIS.BDDEFINT, CFIS.BDREAB, COL_FIS.BDTIPOSANGUECOL,
       CON_DOC.BDNROCONSPROCOL, CON_DOC.BDSIGLACONSPROCOL, CON_DOC.BDCODCCMPROCOL,
       COL_ADM.BDTIPOADMCOL, COL_ADM.BDNATUOCUPCOL, COL_ADM.BDDATAINIAQUICOL, COL_ADM.BDSALINICOL ,
       COL_ADM.BDDIASPRAZO1COL, COL_ADM.BDDATAFIMPRAZO1COL, COL_ADM.BDDIASPRAZO2COL, COL_ADM.BDDATAFIMPRAZO2COL,
       COL_ADM.BDDESCCONTSINCOL, ADMREF.BDVINCEMPCOL, ADMREF.BDALVARACOL, ADMREF.BDSINDICALIZADOCOL ,
       COL_CALC.BDREGIMEPARCIALCOL, COL_ADM.BDFICHAREGCOL, COL_ADM.BDLIVROREGCOL, COL_ADM.BDNROFOLHAREGCOL,
       COLCAD.BDGRAUINSTCOL,COLCAD.BDESTCIVCOL, COL_HIST.BDCODPAISNAS, COL_HIST.BDDTAPOSENT, COL_CALC.BDPERCGORJ, COL_ADM.BDNOVADATAADMRT
FROM VRH_EMP_TCOLCON COLCON
LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC COLCON_DOC
  ON (COLCON.BDCODEMP = COLCON_DOC.BDCODEMP AND COLCON.BDCODCOL = COLCON_DOC.BDCODCOL)
LEFT OUTER JOIN VRH_EMP_TCOL_DOC COL_DOC
  ON (COLCON.BDCODEMP = COL_DOC.BDCODEMP AND COLCON.BDCODCOL = COL_DOC.BDCODCOL)
LEFT OUTER JOIN VRH_EMP_TCOL_HIST COL_HIST
  ON (COLCON.BDCODEMP = COL_HIST.BDCODEMP AND COLCON.BDCODCOL = COL_HIST.BDCODCOL)
LEFT OUTER JOIN VRH_EMP_TCOL_PARENT COL_PARENT
  ON (COLCON.BDCODEMP = COL_PARENT.BDCODEMP AND COLCON.BDCODCOL = COL_PARENT.BDCODCOL)
LEFT OUTER JOIN VRH_EMP_TCOL_FIS COL_FIS
  ON (COLCON.BDCODEMP = COL_FIS.BDCODEMP AND COLCON.BDCODCOL = COL_FIS.BDCODCOL)
LEFT OUTER JOIN VRH_EMP_TCON_DOC CON_DOC
  ON (COLCON.BDCODEMP = CON_DOC.BDCODEMP AND COLCON.BDCODCOL = CON_DOC.BDCODCOL)
LEFT OUTER JOIN VW_VRH_EMP_TCOL_ADM COL_ADM
  ON (COLCON.BDCODEMP = COL_ADM.BDCODEMP AND COLCON.BDCODCOL = COL_ADM.BDCODCOL)
LEFT OUTER JOIN VW_VRHF_EMP_TCOL_CALC COL_CALC
  ON (COLCON.BDCODEMP = COL_CALC.BDCODEMP AND COLCON.BDCODCOL = COL_CALC.BDCODCOL)
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD
  ON (COLCAD.BDCODEMP = COLCON.BDCODEMP AND COLCAD.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_FIS CFIS
  ON (CFIS.BDCODEMP = COLCON.BDCODEMP AND CFIS.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF DOCREF
  ON (DOCREF.BDCODEMP = COLCON.BDCODEMP AND DOCREF.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRH_EMP_TCOL_ADMREF ADMREF
  ON (ADMREF.BDCODEMP = COLCON.BDCODEMP AND ADMREF.BDCODCOL = COLCON.BDCODCOL)
;

CREATE OR ALTER VIEW VW_VRH_EMP_TCOL_HIST_COMPLETA(
    BDCODEMP,
    BDCODCOL,
    BDCIDNASC,
    BDCODPAIS,
    BDNATURALIZADOCOL,
    BDDATACHEBRASILCOL,
    BDCONTRCOL,
    BDCASADOBR,
    BDFILHOSBR,
    BDPORTNAT,
    BDDATANATURALIZACAO,
    BDCODPOSTESTRCOL,
    BDCODPAISNAS,
    BDCODPAISRES,
    BDNOMCIDN,
    BDUFN,
    BDDESCPAISNAS,
    BDDESCPAISRES,
    BDDTAPOSENT)
AS
SELECT
    HIST.BDCODEMP,
    HIST.BDCODCOL,
    COL.BDCODCIDNASC,
    HIST.BDCODPAIS,
    HIST.BDNATURALIZADOCOL,
    COLCAD.BDDATACHEBRASILCOL,
    HIST.BDCONTRCOL,
    COLCAD.BDCASADOBR,
    COLCAD.BDFILHOSBR,
    HIST.BDPORTNAT,
    HIST.BDDATANATURALIZACAO,
    HIST.BDCODPOSTESTRCOL,
    HIST.BDCODPAISNAS,
    COLCAD.BDCODPAISRES,
    CID.BDNOMCID,
    UF.BDSIGLAUF,
    PN.BDDESCPAIS,
    PR.BDDESCPAIS,
    HIST.BDDTAPOSENT
FROM VRH_EMP_TCOL_HIST HIST
LEFT OUTER JOIN VRH_EMP_TCOLCON COL ON (COL.BDCODEMP = HIST.BDCODEMP AND COL.BDCODCOL = HIST.BDCODCOL)
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON (COLCAD.BDCODEMP = HIST.BDCODEMP AND COLCAD.BDCODCOL = HIST.BDCODCOL)
LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = COL.BDCODCIDNASC)
LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF)
LEFT OUTER JOIN TPAIS PR ON (PR.BDCODPAIS = COLCAD.BDCODPAISRES)
LEFT OUTER JOIN TPAIS PN ON (PN.BDCODPAIS = HIST.BDCODPAISNAS)
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCON_VINC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCON_VINC(
BDCODEMP,
BDCODCOL,
BDREFCOL,
BDCODGPS,
BDDESCINSSDOIRCOL)
 AS 
SELECT BASE.bdcodemp, BASE.bdcodcol, BASE.bdrefcol,
REF.bdcodgps,
REF.bddescinssdoircol
FROM
(
  SELECT
      X.bdcodemp,
      X.bdcodcol,
      COALESCE
  (
      (SELECT MAX(d2.bdrefcol) FROM vrhf_emp_tcon_vinc d2 WHERE d2.bdcodemp = x.bdcodemp AND d2.bdcodcol = x.bdcodcol AND CAST(d2.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefcol) FROM vrhf_emp_tcon_vinc d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol)
  ) AS bdrefcol
  FROM vrh_emp_tcolcon x
) AS BASE, vrhf_emp_tcon_vinc REF
WHERE BASE.bdcodemp = REF.bdcodemp AND BASE.bdcodcol = REF.bdcodcol AND BASE.bdREFCOL = REF.bdREFCOL
/*
select
    x.bdcodemp,
    x.bdcodcol,
    x.bdrefcol,
    x.bdcodgps,
    x.bddescinssdoircol
from vrhf_emp_tcon_vinc x
where
  exists (select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFCOL, Z.BDREFCOL
          from VW_VRHF_EMP_TCON_VINC_MIN Y
          left outer join VW_VRHF_EMP_TCON_VINC_MAX Z
            on (Z.BDCODEMP = Y.BDCODEMP and Z.BDCODCOL = Y.BDCODCOL and Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL)
          where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and ((Y.BDREFCOL = X.BDREFCOL and Z.BDREFCOL is null) or (Z.BDREFCOL = X.BDREFCOL))
         )
*/
;

/* CREATE OR ALTER VIEW: VW_TEMPRESAS_REF_MAX_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TEMPRESAS_REF_MAX_MIN(
    BDCODEMP,
    BDREFEMP)
AS
SELECT
emp.bdcodemp,

  COALESCE(

    (
      SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x
      WHERE x.bdcodemp = emp.bdcodemp AND
      X.BDREFEMP <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
      ORDER BY x.bdcodemp DESC, x.bdrefemp DESC
     )

    ,
     (SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x
       WHERE x.bdcodemp = emp.bdcodemp
       AND x.bdcodplapadrao IS NOT NULL
       AND x.bdcodhist IS NOT NULL
       ORDER BY x.bdcodemp, x.bdrefemp
      )
    ,

     (SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x
       WHERE x.bdcodemp = emp.bdcodemp
       ORDER BY x.bdcodemp, x.bdrefemp
      )
    ) BDREFEMP

FROM tempresas emp
;

CREATE OR ALTER VIEW VW_EMPRESAS_TSOC_REF_MAX_MIN(
    BDCODEMP,
    BDCODSOC,
    BDREFSOC)
AS
SELECT soc.bdcodemp, soc.bdcodsoc,
       COALESCE(
         (SELECT FIRST 1 x.bdrefsoc FROM empresas_tsoc_ref x
          WHERE x.bdcodemp = soc.bdcodemp
          AND x.bdcodsoc = soc.bdcodsoc
          AND X.bdrefsoc <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
          ORDER BY x.bdcodemp DESC, x.bdrefsoc DESC),

          (SELECT FIRST 1 x.bdrefsoc FROM empresas_tsoc_ref x
           WHERE x.bdcodemp = soc.bdcodemp
           AND x.bdcodsoc = soc.bdcodsoc
           ORDER BY x.bdcodemp, x.bdrefsoc)
         ) BDREFEMP
FROM empresas_tsoc soc
;

CREATE OR ALTER VIEW VW_EMPRESAS_TSOC_REF(
    BDCODEMP,
    BDCODSOC,
    BDCODCID,
    BDCODPAIS,
    BDQUALILEGALDIPJSOC,
    BDQUALIRESPLEGALSOC,
    BDQUALISPEDSOC,
    BDQUALIFICACAOSOC,
    BDCODPLAPADRAO,
    BDCODCTA,
    BDCGCCEISOC,
    BDNOMSOC,
    BDENDSOC,
    BDNUMSOC,
    BDCOMPLSOC,
    BDBAISOC,
    BDCEPSOC,
    BDPERSOC,
    BDLOGRSOC,
    BDEXTERIORSOC,
    BDDATAENTSOC,
    BDDATASAISOC,
    BDRESPONSAVELSOC,
    BDCPFRESPLEGALSOC,
    BDESTCIVILSOC,
    BDREGESTCIVILSOC,
    BDRGSOC,
    BDDATANASCSOC,
    BDORGEMISOC,
    BDCODUFRG,
    BDCODCBO,
    BDASSINATURA,
    BDRESPONSAVELUF,
    BDCODPAISORIG,
    BDNATURALIZADO,
    BDPORTNAT,
    BDDATANATURALIZACAO,
    BDDATACHEBRASIL,
    BDSEXO,
    BDDATAEMIRG,
    BDCODCIDNASC,
    BDGRAUINST,
    BDINSCNIT,
    BDSIGNATARIOSPED,
    BDREFSOC,
    BDDDDSOC,
    BDTELRESSOC,
    BDDDCELSOC,
    BDTELCELSOC,
    BDDDDFAXSOC,
    BDFAXSOC,
    BDEMAILSOC,
    BDFALECIDO,
    BDDATAOBITO,
    BDSITESPOLIO,
    BDCPFINVENTARIANTE,
    BDNOMEINVENTARIANTE,
    BDSOCREPRESENTANTE,
    BDCODCTAEMPREST,
    BDCODTEREMPREST,
    BDSUBJECTNAME,
    BDTIPOCERTIFICADO,
    BDSERIAL,
    BDDOCUMENTO,
    BDSENHA,
    BDPFX,
    BDFORMATRIBU,
    BDCODCONVENIO,
    BDINDNIF,
    BDNUMNIF,
    BDCODTER,
    BDDATAVALIDADECERT,
    BDRELFONTEPAGADORA)
AS
select SOC.BDCODEMP, SOC.BDCODSOC, SOC.BDCODCID, SOC.BDCODPAIS, SOC.BDQUALILEGALDIPJSOC, SOC.BDQUALIRESPLEGALSOC,
       SOC.BDQUALISPEDSOC, SOC.BDQUALIFICACAOSOC, SOC.BDCODPLAPADRAO, SOC.BDCODCTA, SOC.BDCGCCEISOC, SOCREF.BDNOMSOC,
       SOC.BDENDSOC, SOC.BDNUMSOC, SOC.BDCOMPLSOC, SOC.BDBAISOC, SOC.BDCEPSOC, SOC.BDPERSOC, SOC.BDLOGRSOC,
       SOC.BDEXTERIORSOC, SOC.BDDATAENTSOC, SOC.BDDATASAISOC, SOCREF.BDRESPONSAVELSOC, SOC.BDCPFRESPLEGALSOC,
       SOC.BDESTCIVILSOC, SOC.BDREGESTCIVILSOC, SOC.BDRGSOC, SOC.BDDATANASCSOC, SOC.BDORGEMISOC, SOC.BDCODUFRG,
       SOC.BDCODCBO, SOC.BDASSINATURA, SOC.BDRESPONSAVELUF, SOC.BDCODPAISORIG, SOC.BDNATURALIZADO, SOC.BDPORTNAT,
       SOC.BDDATANATURALIZACAO, SOC.BDDATACHEBRASIL, SOC.BDSEXO, SOC.BDDATAEMIRG, SOC.BDCODCIDNASC, SOC.BDGRAUINST,
       SOC.BDINSCNIT, SOC.BDSIGNATARIOSPED, SOCREF.BDREFSOC, SOCREF.BDDDDSOC, SOCREF.BDTELRESSOC, SOCREF.BDDDCELSOC,
       SOCREF.BDTELCELSOC, SOCREF.BDDDDFAXSOC, SOCREF.BDFAXSOC, SOCREF.BDEMAILSOC, SOC.BDFALECIDO, SOC.BDDATAOBITO,
       SOCREF.BDSITESPOLIO, SOCREF.BDCPFINVENTARIANTE, SOCREF.BDNOMEINVENTARIANTE, SOCREF.BDSOCREPRESENTANTE,
       SOC.BDCODCTAEMPREST, SOC.BDCODTEREMPREST, SOC.BDSUBJECTNAME, SOC.BDTIPOCERTIFICADO, SOC.BDSERIAL,
       SOC.BDDOCUMENTO, SOC.BDSENHA, SOC.BDPFX, SOC.BDFORMATRIBU, SOC.BDCODCONVENIO, BDINDNIF, SOC.BDNUMNIF, SOC.BDCODTER,
       SOC.bddatavalidadecert, SOC.BDRELFONTEPAGADORA
from EMPRESAS_TSOC SOC
left outer join VW_EMPRESAS_TSOC_REF_MAX_MIN REF on (REF.BDCODEMP = SOC.BDCODEMP and
      REF.BDCODSOC = SOC.BDCODSOC)
left outer join EMPRESAS_TSOC_REF SOCREF on (SOCREF.BDCODEMP = REF.BDCODEMP and
      SOCREF.BDCODSOC = REF.BDCODSOC and
      SOCREF.BDREFSOC = REF.BDREFSOC)
;


/* CREATE OR ALTER VIEW: VW_TEMPRESAS_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TEMPRESAS_REF(
    BDCODEMP,
    BDREFEMP,
    BDCNPJEMP,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDCODCENTROS,
    BDCODPLATRIB,
    BDCODCID,
    BDCODCONT,
    BDCODNATJUR,
    BDCODCNAE,
    BDNOMEMP,
    BDNOMREDUZEMP,
    BDAPEEMP,
    BDNOMFANEMP,
    BDENDEMP,
    BDNUMEMP,
    BDBAIEMP,
    BDCEPEMP,
    BDDDDEMP,
    BDFONEEMP,
    BDFAXEMP,
    BDEMAILEMP,
    BDCOMPLEMP,
    BDLOGREMP,
    BDIEEMP,
    BDIMEMP,
    BDSITEMP,
    BDINICIOSIT,
    BDDDDFAXEMP,
    BDDOCAUXILIAR,
    BDCODPLANOONLINE,
    BDSUFRAMA,
    BDCODCONTABLALUR,
    BDCODCONTEF,
    BDCODCONTRH,
    BDNAOPERMITERATEIOGRUPO,
    BDABRIRRATEIO,
    BDCODPLAPADRAOREF,
    BDOPCAOESOCIAL,
    BDDDDCELULAREMP,
    BDCELULAREMP,
    BDENTIDADEPAA,
    BDORGAOEMP,
    BDDESCCARTEMP,
    BDDATAREGEMP,
    BDNOMECARTORIO,
    BDLIVRO,
    BDFOLHA,
    BDCODZONA,
    BDCONTABILIZASCP,
    BDCODMATRIZ,
    BDCNAEPREP,
    BDCODMOEDAS,
    BDDATAINIATIVEMP,
    BDDATAFIMATIVEMP,
    BDDATACADEMP,
    BDCODCLI,
    BDCARACTRIBUTARIA,
    BDIAT_PISCOF_SEM_ICMS,
    BDEXIBEINFOCOLLAN,
    BDNAOCONTCENTROCUSTO,
    BDDATAOBITO,
    BDDATATRANSFINSLUCR,
    BDEXCLUIR_QDO,
    BDDOCAUXILIARCAEPF,
    BDLANCARNOTASCLIENTE,
    BDDATAINCORP,
    BDIMPCONTINUASERTOMADO,
    BDNAOMAJORARIRCSLL)
AS
SELECT
    emp.BDCODEMP,
    emp.BDREFEMP,
    temp.BDCNPJEMP,
    dad.BDCODPLAPADRAO,--case when (dad.BDCODPLAPADRAO is null) then tol.bdcodplapadrao else dad.BDCODPLAPADRAO end as BDCODPLAPADRAO,
    dad.BDCODHIST,--case when (dad.BDCODHIST is null) then tol.BDCODHIST else dad.BDCODHIST end as BDCODHIST,
    dad.BDCODCENTROS,--case when (dad.BDCODCENTROS is null) then tol.bdcodcentro else dad.BDCODCENTROS end as BDCODCENTROS,
    dad.BDCODPLATRIB,
    dad.BDCODCID,
    dad.BDCODCONT,
    dad.BDCODNATJUR,
    dad.BDCODCNAE,
    dad.BDNOMEMP,
    dad.BDNOMREDUZEMP,
    dad.BDAPEEMP,
    dad.bdnomfanemp,
    dad.BDENDEMP,
    dad.BDNUMEMP,
    dad.BDBAIEMP,
    dad.BDCEPEMP,
    dad.BDDDDEMP,
    dad.BDFONEEMP,
    dad.BDFAXEMP,
    dad.BDEMAILEMP,
    dad.BDCOMPLEMP,
    dad.BDLOGREMP,
    dad.BDIEEMP,
    dad.BDIMEMP,
    dad.BDSITEMP,
 dad.BDINICIOSIT,
    dad.BDDDDFAXEMP,
    dad.BDDOCAUXILIAR,    
    dad.BDCODPLANOONLINE,
    dad.BDSUFRAMA,
    dad.BDCODCONTABLALUR,
    dad.bdcodcontef,
    dad.bdcodcontrh,
    dad.BDNAOPERMITERATEIOGRUPO,
    dad.BDABRIRRATEIO,
    dad.BDCODPLAPADRAOREF,
    dad.BDOPCAOESOCIAL,
    dad.BDDDDCELULAREMP,
    dad.BDCELULAREMP,
    dad.BDENTIDADEPAA,
    dad.BDORGAOEMP,
    dad.bddesccartempref,
    dad.bddataregemp,
    dad.bdnomecartorio, 
    dad.bdlivro, 
    dad.bdfolha,
    dad.bdcodzona,
    dad.BDCONTABILIZASCP,
    temp.bdcodmatriz,
    dad.bdcnaeprep,
    dad.bdcodmoedas,
    temp.bddatainiativemp,
    temp.bddatafimativemp,
    temp.BDDATACADEMP,    
    temp.BDCODCLI,
    DAD.BDCARACTRIBUTARIA,
    DAD.BDIAT_PISCOF_SEM_ICMS,
    dad.bdexibeinfocollan,
 dad.bdnaocontcentrocusto,
    Temp.bddataobito,
    Temp.bddatatransfinslucr,
    TEMP.BDEXCLUIR_QDO,
    TEMP.BDDOCAUXILIARCAEPF,
    TEMP.BDLANCARNOTASCLIENTE,
    dad.BDDATAINCORP,
    TEMP.BDIMPCONTINUASERTOMADO,
    dad.BDNAOMAJORARIRCSLL
FROM VW_TEMPRESAS_REF_MAX_MIN emp
inner join tempresas temp on (temp.bdcodemp = emp.bdcodemp)
JOIN tempresas_ref dad ON (dad.bdcodemp = emp.bdCODEMP AND dad.bdrefemp = emp.bdrefemp)
where((temp.bdexcluiremp is null)or(upper(temp.bdexcluiremp)<>'TRUE'))
;


create or alter view VW_EMPRESAS_CLIENTES_SCP(
    BDCODEMP_SO,
    BDCODCLI_SO,
    BDCODEMP_SCP,
    BDCODCLI_SCP,
    BDREFEMP,
    BDDATAINICIAL,
    BDDATAFINAL,
    BDCNPJ_SO,
    BDCNPJ_SCP)
as
select scp.bdcodemp as bdcodemp_so, EMP_SO.bdcodcli as BDCODCLI_SO, scp.bdcodempscp as bdcodemp_scp, EMP_SCP.bdcodcli as BDCODCLI_SCP, scp.bdrefemp,scp.bddatainicial as bddatainicial,scp.bddatafinal as bddatafinal, EMP_SO.bdcnpjemp as BDCNPJ_SO, EMP_SCP.BDCNPJEMP as BDCNPJ_SCP
from TEMPRESAS_SCP SCP
inner join tempresas EMP_SO on (EMP_SO.bdcodemp = scp.bdcodemp)
inner join tempresas EMP_SCP on (EMP_SCP.bdcodemp = scp.bdcodempscp)
inner join (select bdcodemp, max(bdrefemp) bdrefemp from tempresas_scp x where cast(x.bdrefemp as varchar(6)) <= (select trim(rdb$get_context('USER_SESSION', 'W_ANOMES')) from rdb$database)group by x.bdcodemp) ref on(ref.bdcodemp = scp.bdcodemp)-- and ref.bdrefemp = scp.bdrefemp)
;


--#alt:16965. Alterei o cast do código da empresa para 9 digitos. Ana - 24/01/2018
/* CREATE OR ALTER VIEW: VW_CONSULTA_RDE (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_CONSULTA_RDE(
BDCODEMP,
BDCODRDE,
BDREFRDE,
BDDESCRICAORDE)
 AS 
SELECT
  X.BDCODEMP, --Comentário de ajuste
  X.BDCODRDE,
  X.BDREFRDE,
  'Emissão: '||SUBSTRING(CAST(X.BDDATAEMIRDE AS VARCHAR(10)) FROM 9 FOR 2)||'/'||SUBSTRING(CAST(X.BDDATAEMIRDE AS VARCHAR(10)) FROM 6 FOR 2)||'/'||SUBSTRING(CAST(X.BDDATAEMIRDE AS VARCHAR(10)) FROM 1 FOR 4)||
  '. '||CAST(X.BDCODEMP AS VARCHAR(9))||' - '||EMP.BDNOMEMP BDDESC
FROM
  VRH_EMP_TRDE X,
  VW_TEMPRESAS_REF EMP
WHERE
  X.BDCODEMP = EMP.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_CONSULTA_RDT (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_CONSULTA_RDT(
BDCODEMP,
BDCODCOL,
BDCODRDT,
BDDESCRICAORDT)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODRDT,
  'Emissão: '||SUBSTRING(CAST(X.BDDATAEMIRDT AS VARCHAR(10)) FROM 9 FOR 2)||'/'||SUBSTRING(CAST(X.BDDATAEMIRDT AS VARCHAR(10)) FROM 6 FOR 2)||'/'||SUBSTRING(CAST(X.BDDATAEMIRDT AS VARCHAR(10)) FROM 1 FOR 4)||
  '. '||CAST(X.BDCODEMP AS VARCHAR(9))||'. Col - '||COLCAD.BDNOMCOL BDDESC
FROM VRH_EMP_TRDT X
JOIN VRH_EMP_TCOLCON COL ON X.BDCODEMP = COL.BDCODEMP AND X.BDCODCOL = COL.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON COLCAD.BDCODEMP = X.BDCODEMP AND COLCAD.BDCODCOL = X.BDCODCOL
;
--#alt:16965. fim

/* CREATE OR ALTER VIEW: VW_DEMITIDOS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_DEMITIDOS(
BDCODEMP,
BDCODCOL,
BDDATARESCISAO,
BDCODPRES,
BDDATAAVPREVIO,
BDDATAHOM,
BDDATAPAGRESCISAO,
BDSALDOFGTS,
BDCALCFGTSMESANT,
BDMAIORREMUNERACAO,
BDCHAVEINDENTIFICACAO,
BDDATAPAGGRFC,
BDREPOSICAOVAGA,
BDDISSIDIO,
BDDATADISSIDIO,
BDDESCANSOINDENIZADO)
 AS 
SELECT
  RESC.BDCODEMP,
  RESC.BDCODCOL,
  RESC.BDDATARESCISAO,
  RESC.BDCODPRES,
  RESC.BDDATAAVPREVIO,
  RESC.BDDATAHOM,
  RESC.BDDATAPAGRESCISAO,
  RESC.BDSALDOFGTS,
  RESC.BDCALCFGTSMESANT,
  RESC.BDMAIORREMUNERACAO,
  RESC.BDCHAVEINDENTIFICACAO,
  RESC.BDDATAPAGGRFC,
  RESC.BDREPOSICAOVAGA,
  RESC.BDDISSIDIO,
  RESC.BDDATADISSIDIO,
  RESC.BDDESCANSOINDENIZADO
FROM
  VRH_EMP_TRESCISAO RESC
WHERE
  NOT EXISTS (SELECT TRANS.BDCODEMPORIG, TRANS.BDCODCOLORIG FROM VRH_EMP_TTRANSCOL TRANS WHERE TRANS.BDCODEMPORIG = RESC.BDCODEMP AND TRANS.BDCODCOLORIG = RESC.BDCODCOL)
;

/* CREATE OR ALTER VIEW: VW_VEF_BASE_TEMPPARGER_MAX_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_TEMPPARGER_MAX_MIN(
    BDCODEMP,
    BDREFEMP)
AS
SELECT
emp.bdcodemp,

  COALESCE(

    (
      SELECT FIRST 1 x.bdrefemp FROM VEF_BASE_TEMPPARGER x
      WHERE x.bdcodemp = emp.bdcodemp AND
      X.BDREFEMP <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
      ORDER BY x.bdcodemp DESC, x.bdrefemp DESC
     )

    ,
     (SELECT FIRST 1 x.bdrefemp FROM VEF_BASE_TEMPPARGER x
       WHERE x.bdcodemp = emp.bdcodemp
       ORDER BY x.bdcodemp, x.bdrefemp
      )
    ) BDREFEMP

FROM tempresas emp
where((bdexcluiremp is null)or(upper(bdexcluiremp)<>'TRUE'))
;

/* CREATE OR ALTER VIEW: VW_VEF_BASE_TEMPPARGER (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_TEMPPARGER(
    BDCODEMP,
    BDREFEMP,
    BDCODCONFIPI,
    BDCODCONFIRLP,
    BDLANBCICMSVALCONT,
    BDLANBCICMSISEOUT,
    BDLANCLISAISER,
    BDLANPROENT,
    BDLANPROSAI,
    BDMOVSER,
    BDPERCISS,
    BDREDPERCISS,
    BDMOVIRRF,
    BDALIQIRRF,
    BDISENTOIRRF,
    BDALIQINSS,
    BDRETINSS,
    BDVLRMININSS,
    BDEMPINATIVA,
    BDEMPDIFPAPEL,
    BDEMPBARREST,
    BDVERIFICARNOTASJALAN,
    BDCODCONFATIVO,
    BDCODCONFDACON,
    BDCODCONFBLOCOM,
    BDCODCONFBLOCOP,
    BDCODCONFCIAP,
    BDCODCONFDASN,
    BDRETPARPIS,
    BDRETPARCOFINS,
    BDRETPARCSLL,
    BDRETPARIRRF,
    BDRETPARISSQN,
    BDRETPARINSS,
    BDRETPARFUNRURAL,
    BDTIPOAPURACAO,
    BDTIPOAPURACAORET,
    BDTIPOAPURACAORETIR,
    BDIGNORAREDISS,
    BDCODCONFCPRBREINF,
    BDTIPOAPURACAORETIRTOM,
    BDCONTPISCOFCAIXA)
AS
SELECT
    emp.bdcodemp,
    emp.bdrefemp,
    X.BDCODCONFIPI,
    X.BDCODCONFIRLP,
    X.BDLANBCICMSVALCONT,
    X.BDLANBCICMSISEOUT ,
    X.BDLANCLISAISER,
    X.BDLANPROENT,
    X.BDLANPROSAI,
    X.BDMOVSER   ,
    X.BDPERCISS  ,
    X.BDREDPERCISS,
    X.BDMOVIRRF   ,
    X.BDALIQIRRF  ,
    X.BDISENTOIRRF,
    x.bdaliqinss  ,
    X.BDRETINSS   ,
    X.BDVLRMININSS ,
    X.BDEMPINATIVA ,
    X.BDEMPDIFPAPEL,
    X.BDEMPBARREST ,
    X.BDVERIFICARNOTASJALAN,
    X.BDCODCONFATIVO,
    X.bdcodconfdacon,
    x.BDCODCONFBLOCOM, 
    X.bdcodconfblocop,
    X.BDCODCONFCIAP,
    x.BDCODCONFDASN,
    x.BDRETPARPIS,
    x.BDRETPARCOFINS,
    x.BDRETPARCSLL,
    x.BDRETPARIRRF,
    x.BDRETPARISSQN,
    x.BDRETPARINSS,
    x.BDRETPARFUNRURAL,
    x.bdtipoapuracao,
    x.BDTIPOAPURACAORET,
    x.BDTIPOAPURACAORETIR,
    x.BDIGNORAREDISS,
    X.BDCODCONFCPRBREINF,
    X.BDTIPOAPURACAORETIRTOM,
    x.BDCONTPISCOFCAIXA
FROM VW_VEF_BASE_TEMPPARGER_MAX_MIN emp
JOIN vef_base_tempparger x ON (x.bdcodemp = emp.bdCODEMP AND x.bdrefemp = emp.bdrefemp)
;


/* CREATE OR ALTER VIEW: VW_VEF_BASE_TEMPPARFED (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_TEMPPARFED(
    BDCODEMP,
    BDREFEMP,
    BDCODACESSOSN,
    BDPERFILSPED,
    BDATIVIDADESPED,
    BDCODCONFICMSSPED,
    BDTIPODECLARANTEDMED,
    BDREGISTROANSDMED,
    BDNUMEROCNESDMED,
    BDDTOBRIGSPEDCONT,
    BDDTOBRIGSPEDICMS,
    BDINDATIV,
    BDINDNATPJ,
    BDCODPLANOCONFSN,
    BDGERAC490,
    BDANTECIPAIMPOSTO,
    BDOPTANTERET,
    BDCODCLASSESTAB,
    BDCONTABGUIAMUN)
AS
SELECT
    X.bdcodemp,
    X.bdrefemp,
    X.BDCODACESSOSN ,
    X.BDPERFILSPED ,
    X.BDATIVIDADESPED,
    X.bdcodconficmssped,
    X.bdtipodeclarantedmed,
    X.bdregistroansdmed,
    X.bdnumerocnesdmed,
    X.BDDTOBRIGSPEDCONT,
    X.BDDTOBRIGSPEDICMS,
    X.BDINDATIV,
    X.BDINDNATPJ,

    X.BDCODPLANOCONFSN,

    X.BDGERAC490,
    X.BDANTECIPAIMPOSTO,
    X.BDOPTANTERET,
    X.BDCODCLASSESTAB,
    X.bdcontabguiamun


    FROM VEF_BASE_TEMPPARFED X
WHERE X.BDREFEMP =
      (COALESCE(
       (SELECT MAX(Y.BDREFEMP)
       FROM VEF_BASE_TEMPPARFED Y
       WHERE Y.BDCODEMP = X.BDCODEMP AND
              Y.BDREFEMP <= (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER) FROM rdb$database)),
       (SELECT FIRST 1 Y.BDREFEMP
        FROM VEF_BASE_TEMPPARFED Y
        WHERE Y.BDCODEMP = X.BDCODEMP
        ORDER BY Y.BDREFEMP, Y.BDREFEMP)
      ))
;

/* CREATE OR ALTER VIEW: VW_VEF_BASE_TEMPPARESTSC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_TEMPPARESTSC(
    BDCODEMP,
    BDREFEMP,
    BDCODCONFDIMESC,
    BDCODAPUCON,
    BDCODESCCONT,
    BDCODREGAPU,
    BDCONTPRODEC,
    BDNRPARPRODEC,
    BDALIMPREP,
    BDCOOPAGRO,
    BDDETFILIAL,
    BDEMPPRINCDIMESC,
    BDDETRESULTFILIAL,
    BDCODPLACONFDRCST,
    BDCODPLASEFSC)
AS
SELECT
    X.bdcodemp,
    X.bdrefemp,
    X.BDCODCONFDIMESC  ,
    X.BDCODAPUCON      ,
    X.BDCODESCCONT     ,
    X.BDCODREGAPU      ,
    X.BDCONTPRODEC     ,
    X.BDNRPARPRODEC    ,
    X.BDALIMPREP       ,
    X.BDCOOPAGRO       ,
    X.BDDETFILIAL      ,
    X.BDEMPPRINCDIMESC ,
    X.BDDETRESULTFILIAL,
    X.BDCODPLACONFDRCST,
    X.BDCODPLASEFSC

    FROM VEF_BASE_TEMPPARESTSC X
WHERE X.BDREFEMP =
      (COALESCE(
       (SELECT first 1 Y.BDREFEMP
       FROM VEF_BASE_TEMPPARESTSC Y
       WHERE Y.BDCODEMP = X.BDCODEMP AND
              Y.BDREFEMP <= (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER) FROM rdb$database)
        ORDER BY Y.BDCODEMP DESC, Y.BDREFEMP DESC),
       (SELECT FIRST 1 Y.BDREFEMP
        FROM VEF_BASE_TEMPPARESTSC Y
        WHERE Y.BDCODEMP = X.BDCODEMP
        ORDER BY Y.BDCODEMP, Y.BDREFEMP)
        ))
;


CREATE OR ALTER VIEW VW_VEF_BASE_TEMPPARESTPE(
    BDCODEMP,
    BDREFEMP,
    BDCODCONFGIAFPE)
AS
SELECT
    X.bdcodemp,
    X.bdrefemp,
    X.BDCODCONFGIAFPE

    FROM VEF_BASE_TEMPPARESTPE X
WHERE X.BDREFEMP =
      (COALESCE(
       (SELECT first 1 Y.BDREFEMP
       FROM VEF_BASE_TEMPPARESTPE Y
       WHERE Y.BDCODEMP = X.BDCODEMP AND
              Y.BDREFEMP <= (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER) FROM rdb$database)
        order by Y.bdcodemp desc, Y.bdrefemp desc),
       (SELECT FIRST 1 Y.BDREFEMP
        FROM VEF_BASE_TEMPPARESTPE Y
        WHERE Y.BDCODEMP = X.BDCODEMP
        ORDER BY Y.BDCODEMP, Y.BDREFEMP)
       ))
;


/* CREATE OR ALTER VIEW: VW_VEF_BASE_TEMPPARFEDPORATV (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_TEMPPARFEDPORATV(
    BDCODEMP,
    BDREFEMP,
    BDLRISSSN,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO)
AS
SELECT
    X.bdcodemp,
    X.bdrefemp,
    x.BDLRISSSN,
    x.BDCOMERCIO,
    x.BDINDUSTRIA,
    x.BDSERVICO

    FROM VEF_BASE_TEMPPARFEDPORATV X
WHERE X.BDREFEMP =
      (COALESCE(
       (SELECT MAX(Y.BDREFEMP)
       FROM VEF_BASE_TEMPPARFEDPORATV Y
       WHERE Y.BDCODEMP = X.BDCODEMP AND
              Y.BDREFEMP <= (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER) FROM rdb$database)),
       (SELECT FIRST 1 Y.BDREFEMP
        FROM VEF_BASE_TEMPPARFEDPORATV Y
        WHERE Y.BDCODEMP = X.BDCODEMP
        ORDER BY Y.BDCODEMP, Y.BDREFEMP)
       ))
;

/* CREATE OR ALTER VIEW: VW_VEF_BASE_TEMPITEMSATV (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_TEMPITEMSATV(
    BDCODEMP,
    BDREFEMP,
    BDANEXOIII,
    BDANEXOIV,
    BDANEXOV,
    BDANEXOVI,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO,
    BDANEXOIII_2018,
    BDANEXOIV_2018,
    BDANEXOV_2018,
    BDRELFOLHAANEXOIII)
AS
SELECT
    X.bdcodemp,
    X.bdrefemp,
    X.BDANEXOIII,
    X.BDANEXOIV,
    X.BDANEXOV,
    X.BDANEXOVI,
    ATV.BDCOMERCIO,
    ATV.BDINDUSTRIA,
    ATV.BDSERVICO,
    X.BDANEXOIII_2018,
    X.BDANEXOIV_2018,
    X.BDANEXOV_2018,
    X.BDRELFOLHAANEXOIII

FROM VEF_BASE_TEMPITEMSATV X
JOIN VEF_BASE_TEMPCADATV ATV ON (ATV.BDCODEMP = X.BDCODEMP AND ATV.BDREFEMP = X.BDREFEMP)
WHERE X.BDREFEMP =
      (COALESCE(
       (SELECT MAX(Y.BDREFEMP)
       FROM VEF_BASE_TEMPITEMSATV Y
       WHERE Y.BDCODEMP = X.BDCODEMP AND
              Y.BDREFEMP <= (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER) FROM rdb$database)),
       (SELECT FIRST 1 Y.BDREFEMP
        FROM VEF_BASE_TEMPITEMSATV Y
        WHERE Y.BDCODEMP = X.BDCODEMP
        ORDER BY Y.BDCODEMP, Y.BDREFEMP)
       ))
;

/* View: VW_VEF_BASE_TEMPITEMSATV_PGTO */
CREATE OR ALTER VIEW VW_VEF_BASE_TEMPITEMSATV_PGTO(
    BDCODEMP,
    BDREFEMP,
    BDANEXOIII,
    BDANEXOIV,
    BDANEXOV,
    BDANEXOVI,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO,
    BDANEXOIII_2018,
    BDANEXOIV_2018,
    BDANEXOV_2018,
    BDRELFOLHAANEXOIII)
AS
SELECT
    X.bdcodemp,
    X.bdrefemp,
    X.BDANEXOIII,
    X.BDANEXOIV,
    X.BDANEXOV,
    X.BDANEXOVI,
    ATV.BDCOMERCIO,
    ATV.BDINDUSTRIA,
    ATV.BDSERVICO,
    X.BDANEXOIII_2018,
    X.BDANEXOIV_2018,
    X.BDANEXOV_2018,
    X.BDRELFOLHAANEXOIII

FROM VEF_BASE_TEMPITEMSATV X
JOIN VEF_BASE_TEMPCADATV ATV ON (ATV.BDCODEMP = X.BDCODEMP AND ATV.BDREFEMP = X.BDREFEMP)
WHERE X.BDREFEMP =
      (
       SELECT MAX(Y.BDREFEMP)
       FROM VEF_BASE_TEMPITEMSATV Y
       WHERE Y.BDCODEMP = X.BDCODEMP AND
             Y.BDREFEMP <=
                (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMESPGTO'))) AS INTEGER)
                 FROM rdb$database
                )
      )
;

/* CREATE OR ALTER VIEW: VW_VEF_BASE_TEMPPAREST (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_TEMPPAREST(
    BDCODEMP,
    BDREFEMP,
    BDPARICMSEMP,
    BDDIAVCTOICMS,
    BDANTFERIADOICMS,
    BDVCTOMESICMS,
    BDMULTAMAXICMS,
    BDDIAJUROSICMS,
    BDPELASELIC,
    BDJURICMSEMP,
    BDJUROMESDIA,
    BDDIAMULTAICMS,
    BDMULTAICMSEMP,
    BDMULTAMESDIA,
    BDEMITEGIA,
    BDSUBSTRIB,
    BDREDBCICMSENT,
    BDREDBCICMSSAI,
    BDICMSMONO,
    BDCODPORTEEMP,
    BDCODCONFGIAST,
    BDAPURAGIAST,
    BDEC8715)
AS
SELECT
    X.BDCODEMP,
    X.BDREFEMP,
    X.BDPARICMSEMP,
    X.BDDIAVCTOICMS,
    X.BDANTFERIADOICMS,
    X.BDVCTOMESICMS,
    X.BDMULTAMAXICMS,
    X.BDDIAJUROSICMS,
    X.BDPELASELIC,
    X.BDJURICMSEMP,
    X.BDJUROMESDIA,
    X.BDDIAMULTAICMS,
    X.BDMULTAICMSEMP,
    X.BDMULTAMESDIA,
    X.BDEMITEGIA,
    X.BDSUBSTRIB,
    X.BDREDBCICMSENT,
    X.BDREDBCICMSSAI,
    X.BDICMSMONO,
    X.BDCODPORTEEMP,
    X.BDCODCONFGIAST,
    X.BDAPURAGIAST,
    X.BDEC8715
    FROM VEF_BASE_TEMPPAREST X
WHERE X.BDREFEMP =
      (COALESCE(
       (SELECT MAX(Y.BDREFEMP)
       FROM VEF_BASE_TEMPPAREST Y
       WHERE Y.BDCODEMP = X.BDCODEMP AND
              Y.BDREFEMP <= (SELECT CAST((TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES'))) AS INTEGER) FROM RDB$DATABASE)),
       (SELECT FIRST 1 Y.BDREFEMP
        FROM VEF_BASE_TEMPPAREST Y
        WHERE Y.BDCODEMP = X.BDCODEMP
        ORDER BY Y.BDCODEMP, Y.BDREFEMP)
       ))
;

/* CREATE OR ALTER VIEW: VW_VEF_BASE_TEMPPARESTSP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_TEMPPARESTSP(
    BDCODEMP,
    BDREFEMP,
    BDCODCONFGIASP,
    BDCREDAC,
    BDCODPLACATSP,
    BDMANTERC197CATSP,
    BDCALCSTIMPSUB,
    BDCODPLACAT42SP,
    BDCONSOLIDAR1200,
    BDSTRET)
AS
SELECT
    X.bdcodemp,
    X.bdrefemp,
    X.BDCODCONF,
    X.BDCREDAC,
    X.BDCODPLACATSP,
    X.BDMANTERC197CATSP,
    X.BDCALCSTIMPSUB,
    X.BDCODPLACAT42SP,
    X.BDCONSOLIDAR1200,
    X.BDSTRET

    FROM VEF_BASE_TEMPPARESTSP X
WHERE X.BDREFEMP =
      (COALESCE(
       (SELECT MAX(Y.BDREFEMP)
       FROM VEF_BASE_TEMPPARESTSP Y
       WHERE Y.BDCODEMP = X.BDCODEMP AND
              Y.BDREFEMP <= (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER) FROM rdb$database)),
       (SELECT FIRST 1 Y.BDREFEMP
        FROM VEF_BASE_TEMPPARESTSP Y
        WHERE Y.BDCODEMP = X.BDCODEMP
        ORDER BY Y.BDCODEMP,Y.BDREFEMP)
       ))
;

CREATE OR ALTER VIEW VW_TEMPPARESTMG_MAX_MIN(
    BDCODEMP,
    BDREFEMP)
AS
SELECT
emp.bdcodemp,

  COALESCE(

    (
      SELECT FIRST 1 x.bdrefemp FROM VEF_BASE_TEMPPARESTMG x
      WHERE x.bdcodemp = emp.bdcodemp AND
      X.BDREFEMP <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
      ORDER BY x.bdcodemp DESC, x.bdrefemp DESC
     )

    ,
     (SELECT FIRST 1 x.bdrefemp FROM VEF_BASE_TEMPPARESTMG x
       WHERE x.bdcodemp = emp.bdcodemp
       ORDER BY x.bdcodemp, x.bdrefemp
      )
    ) BDREFEMP

FROM tempresas emp
where((bdexcluiremp is null)or(upper(bdexcluiremp)<>'TRUE'))
;

/* CREATE OR ALTER VIEW: VW_VEF_BASE_TEMPPARESTMG (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_TEMPPARESTMG(
    BDCODEMP,
    BDREFEMP,
    BDCODCONFGIAMG,
    BDCODCONFDAMEF,
    BDCREDPRESUMIDO,
    BDTERMOACEITE,
    BDREGESP)
AS
SELECT X.BDCODEMP, X.BDREFEMP, X.BDCODCONFGIAMG, X.BDCODCONFDAMEF, X.BDCREDPRESUMIDO, X.BDTERMOACEITE, X.BDREGESP
FROM VW_TEMPPARESTMG_MAX_MIN emp
join VEF_BASE_TEMPPARESTMG X on (X.BDCODEMP = emp.BDCODEMP AND X.BDREFEMP = EMP.BDREFEMP)
;

CREATE OR ALTER VIEW VW_VEF_BASE_TEMPPARESTTO(
    BDCODEMP,
    BDREFEMP,
    BDCODCONFGIATO,
    BDTIPOESTAB,
    BDTIPOESCRIT,
    BDPORTARE,
    BDNUMTARE,
    BDDTVCTTARE,
    BDUSUECF,
    BDGERSEGM,
    BDEMPLACT,
    BDGERREGCOMB,
    BDDIAVCTICMSTO)
AS
SELECT
    x.bdcodemp,
    x.bdrefemp ,
    x.bdcodconfgiato,
    x.bdtipoestab,
    x.bdtipoescrit,
    x.bdportare,
    x.bdnumtare,
    x.BDDTVCTTARE,
    x.bdusuecf,
    x.bdgersegm,
    x.bdemplact,
    x.bdgerregcomb,
    x.bddiavcticmsto

    FROM VEF_BASE_TEMPPARESTTO X
WHERE X.BDREFEMP =
      (
       SELECT MAX(Y.BDREFEMP)
       FROM VEF_BASE_TEMPPARESTTO Y
       WHERE Y.BDCODEMP = X.BDCODEMP AND
             Y.BDREFEMP <=
                (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER)
                 FROM rdb$database
                )
      )
;

/* CREATE OR ALTER VIEW: VW_VEF_BASE_TEMPPARINTEG (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_TEMPPARINTEG(
    BDCODEMP,
    BDREFEMP,
    BDSOMFREVLRCONTAB,
    BDSOMFREBASEICMS,
    BDCODPLATROCA,
    BDCODPLACFOP,
    BDLANCAPARCELAAUTO,
    BDCODIGOPLA,
    BDIMPORTARVALORESICMSSN,
    BDDIFALIQ,
    BDDIFALIQBASEEM,
    BDSOMAPISCOFVLRCONT,
    BDSOMAIIVLRCONT,
    BDMANTERPARCELAS,
    BDCODPLANOINCONS,
    BDSOMAIPIPROD,
    BDRATDESCPAF,
    BDRATACREPAF,
    BDSOMAICMSVLRCONT,
    BDCODPLAE115,
    BDMANTERCODPROD,
    BDSOMASTPROD,
    BDCALCANTICMS,
    BDCONSIPIBC,
    BDIMPICMSST,
    BDIMPORTARISS,
    BDIMPORTARCTESAI,
    BDNAOVALIDACONTRATO,
    BDCONSISTIRCODPROD,
    BDSOMAAFRMMVLRCONT,
    BDCODPLAAJUSTE,
    BDVENDACOOP,
    BDDIFALIQ_NAOGERA_C197,
	BDUSARTAGVNF)
AS
SELECT emp.bdcodemp,
       emp.bdrefemp,
       par.bdsomfrevlrcontab,
       par.bdsomfrebaseicms,
       par.bdcodplatroca,
       par.bdcodplacfop,
       par.bdlancaparcelaauto,
       par.bdcodigopla,
       par.bdimportarvaloresicmssn,
       par.bddifaliq,
       par.bddifaliqbaseem,
       
       par.BDSOMAPISCOFVLRCONT,
       par.BDSOMAIIVLRCONT,
       par.BDMANTERPARCELAS,
       par.bdcodplanoincons,
       par.BDSOMAIPIPROD,
       par.BDRATDESCPAF,
       par.BDRATACREPAF,
       par.BDSOMAICMSVLRCONT,
       par.BDCODPLAE115,
       par.BDMANTERCODPROD,
       par.BDSOMASTPROD,
       par.BDCALCANTICMS,
       par.BDCONSIPIBC,
       par.BDIMPICMSST,
       par.BDIMPORTARISS,
       par.BDIMPORTARCTESAI,
       par.BDNAOVALIDACONTRATO,
       par.BDCONSISTIRCODPROD,
       par.BDSOMAAFRMMVLRCONT,
       par.BDCODPLAAJUSTE,
       par.BDVENDACOOP,
       par.BDDIFALIQ_NAOGERA_C197,
	   par.BDUSARTAGVNF
FROM
(
    SELECT e.bdcodemp,
           COALESCE
           (
               (
                   SELECT FIRST 1 x.bdrefemp FROM vef_base_tempparinteg x
                   WHERE ( x.bdcodemp = e.bdcodemp ) AND
                         ( CAST(x.bdrefemp AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database))
                   ORDER BY x.bdrefemp DESC
               ),
               (
                   SELECT FIRST 1 x.bdrefemp FROM vef_base_tempparinteg x
                   WHERE ( x.bdcodemp = e.bdcodemp )
                   ORDER BY x.bdrefemp
               )

           ) BDREFEMP
    FROM tempresas e
    where((e.bdexcluiremp is null)or(upper(e.bdexcluiremp)<>'TRUE'))
) EMP
INNER JOIN vef_base_tempparinteg par ON ( par.bdcodemp = emp.bdcodemp ) AND ( par.bdrefemp = emp.bdrefemp )
;

/* CREATE OR ALTER VIEW: VW_VEF_BASE_TEMPPARESTES (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_TEMPPARESTES(
BDCODEMP,
BDREFEMP,
BDCODCONFGIAES,
BDCODCONFDOT)
 AS 
/* alt.: #7125 - view alterada para seguir a regra das referencias corretamente (caso não encontre referencia igual a procurada, pega a maior anterior ou a menor posterior)
select X.BDCODEMP, X.BDREFEMP, X.bdcodconfgiaes, X.bdcodconfdot from vef_base_tempparestes X
where X.BDREFEMP =(select max(Y.BDREFEMP) from vef_base_tempparestes Y
                   where Y.BDCODEMP = X.BDCODEMP and
                         Y.BDREFEMP <=(select cast((trim(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES'))) as integer) from RDB$DATABASE))*/

SELECT EMP.BDCODEMP, EMP.BDREFEMP, ES.BDCODCONFGIAES, ES.bdcodconfdot
FROM
(
    SELECT E.BDCODEMP,
           COALESCE
           (
               (
                   SELECT FIRST 1 x.bdrefemp FROM vef_base_tempparestes x
                   WHERE (x.bdcodemp = e.bdcodemp) AND
                         (CAST(x.bdrefemp AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database))
                   ORDER BY x.bdrefemp DESC
               ),
               (
                   SELECT FIRST 1 x.bdrefemp FROM vef_base_tempparestes x
                   WHERE (x.bdcodemp = e.bdcodemp)
                   ORDER BY x.bdrefemp
               )
           ) BDREFEMP
    FROM TEMPRESAS E
    where((e.bdexcluiremp is null)or(upper(e.bdexcluiremp)<>'TRUE'))
) EMP
INNER JOIN vef_base_tempparestes es USING (bdcodemp, bdrefemp)
;

/* CREATE OR ALTER VIEW: VW_VEF_BASE_TEMPPARESTRO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_TEMPPARESTRO(
BDCODEMP,
BDREFEMP,
BDCODCONFGIARO)
 AS 
/* alt.: #7125 - view alterada para seguir a regra das referencias corretamente (caso não encontre referencia igual a procurada, pega a maior anterior ou a menor posterior)
select X.BDCODEMP, X.BDREFEMP, X.bdcodconfgiaro from vef_base_tempparestro X
where X.BDREFEMP =(select max(Y.BDREFEMP) from vef_base_tempparestro Y
                   where Y.BDCODEMP = X.BDCODEMP and
                         Y.BDREFEMP <=(select cast((trim(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES'))) as integer) from RDB$DATABASE))*/

SELECT EMP.BDCODEMP, EMP.BDREFEMP, RO.BDCODCONFGIARO
FROM
(
    SELECT E.BDCODEMP,
           COALESCE
           (
               (
                   SELECT FIRST 1 x.bdrefemp FROM vef_base_tempparestro x
                   WHERE (x.bdcodemp = e.bdcodemp) AND
                         (CAST(x.bdrefemp AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database))
                   ORDER BY x.bdrefemp DESC
               ),
               (
                   SELECT FIRST 1 x.bdrefemp FROM vef_base_tempparestro x
                   WHERE (x.bdcodemp = e.bdcodemp)
                   ORDER BY x.bdrefemp
               )
           ) BDREFEMP
    FROM TEMPRESAS E
    where((e.bdexcluiremp is null)or(upper(e.bdexcluiremp)<>'TRUE'))
) EMP
INNER JOIN vef_base_tempparestro ro USING (bdcodemp, bdrefemp)
;

/* CREATE OR ALTER VIEW: VW_VEF_BASE_TEMPPARESTPR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_TEMPPARESTPR(
    BDCODEMP,
    BDREFEMP,
    BDCODCONFGIAPR,
    BDCODCONFDFC,
    BDCODPLANOCONFADRCST,
    BDCREDPRESUMIDOPR,
    BDOPINTERNA,
    BDOPINTER12,
    BDOPINTER7,
    BDOPSP)
AS
SELECT EMP.BDCODEMP, EMP.BDREFEMP, PR.BDCODCONFGIAPR, PR.bdcodconfdfc, pr.bdcodplanoconfadrcst, BDCREDPRESUMIDOPR, BDOPINTERNA, BDOPINTER12,
      BDOPINTER7, BDOPSP
FROM
(
    SELECT E.BDCODEMP,
           COALESCE
           (
               (
                   SELECT FIRST 1 x.bdrefemp FROM vef_base_tempparestpr x
                   WHERE (x.bdcodemp = e.bdcodemp) AND
                         (CAST(x.bdrefemp AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database))
                   ORDER BY x.bdrefemp DESC
               ),
               (
                   SELECT FIRST 1 x.bdrefemp FROM vef_base_tempparestpr x
                   WHERE (x.bdcodemp = e.bdcodemp)
                   ORDER BY x.bdrefemp
               )
           ) BDREFEMP
    FROM TEMPRESAS E
    where((e.bdexcluiremp is null)or(upper(e.bdexcluiremp)<>'TRUE'))
) EMP
INNER JOIN vef_base_tempparestpr pr USING (bdcodemp, bdrefemp)
;

/* CREATE OR ALTER VIEW: VW_VEF_BASE_TEMPPARESTRJ (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_TEMPPARESTRJ(
    BDCODEMP,
    BDREFEMP,
    BDCODCONFGIARJ)
AS
SELECT EMP.BDCODEMP, EMP.BDREFEMP, rj.BDCODCONFGIARJ
FROM
(
    SELECT E.BDCODEMP,
           COALESCE
           (
               (
                   SELECT FIRST 1 x.bdrefemp FROM VEF_BASE_TEMPPARESTRJ x
                   WHERE (x.bdcodemp = e.bdcodemp) AND
                         (CAST(x.bdrefemp AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database))
                   ORDER BY x.bdrefemp DESC
               ),
               (
                   SELECT FIRST 1 x.bdrefemp FROM VEF_BASE_TEMPPARESTRJ x
                   WHERE (x.bdcodemp = e.bdcodemp)
                   ORDER BY x.bdrefemp
               )
           ) BDREFEMP
    FROM TEMPRESAS E
    where((e.bdexcluiremp is null)or(upper(e.bdexcluiremp)<>'TRUE'))
) EMP
INNER JOIN VEF_BASE_TEMPPARESTRJ rj USING (bdcodemp, bdrefemp)
;

/* CREATE OR ALTER VIEW: VW_EMP_REF_TOTAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_EMP_REF_TOTAL(
    BDCODEMP,
    BDREFEMP,
    BDRETINSS,
    BDVLRMININSS,
    BDSUFRAMA,
    BDCODACESSOSN,
    BDPERFILSPED,
    BDATIVIDADESPED,
    BDSOMFREVLRCONTAB,
    BDSOMFREBASEICMS,
    BDCODPLATROCA,
    BDCODPLACFOP,
    BDCODCONFIPI,
    BDCODCONFIRLP,
    BDCODCONFDIMESC,
    BDCODPORTEEMP,
    BDCODAPUCON,
    BDCODESCCONT,
    BDCODREGAPU,
    BDCONTPRODEC,
    BDNRPARPRODEC,
    BDCODCONFATIVO,
    BDLANBCICMSVALCONT,
    BDLANBCICMSISEOUT,
    BDLANCLISAISER,
    BDLANPROENT,
    BDLANPROSAI,
    BDMOVSER,
    BDPERCISS,
    BDREDPERCISS,
    BDMOVIRRF,
    BDALIQIRRF,
    BDISENTOIRRF,
    BDEMPINATIVA,
    BDEMPDIFPAPEL,
    BDEMPBARREST,
    BDVERIFICARNOTASJALAN,
    BDLRISSSN,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO,
    BDANEXOIII,
    BDANEXOIV,
    BDANEXOV,
    BDSUBSTRIB,
    BDCODCONFDACON,
    BDCODCONFBLOCOM,
    BDCODCONFBLOCOP,
    BDCODCONFGIASP,
    BDNOMEMP,
    BDCODCONFICMSSPED,
    BDCODCONFCIAP,
    BDREDBCICMSENT,
    BDREDBCICMSSAI,
    BDICMSMONO,
    BDCODCONFDASN,
    BDRETPARPIS,
    BDRETPARCOFINS,
    BDRETPARCSLL,
    BDRETPARIRRF,
    BDRETPARISSQN,
    BDRETPARINSS,
    BDRETPARFUNRURAL,
    BDTIPOAPURACAO,
    BDCODCONFGIAMG,
    BDCODCONFDAMEF,
    BDCREDPRESUMIDO,
    BDTERMOACEITE,
    BDANTECIPAIMPOSTO,
    BDTIPODECLARANTEDMED,
    BDREGISTROANSDMED,
    BDNUMEROCNESDMED,
    BDDTOBRIGSPEDCONT,
    BDTIPOAPURACAORET,
    BDTIPOAPURACAORETIR,
    BDDTOBRIGSPEDICMS,
    BDLANCAPARCELAAUTO,
    BDCODIGOPLA,
    BDCODCONFGIAES,
    BDCODCONFGIARO,
    BDINDATIV,
    BDCODCONFGIAPR,
    BDANEXOVI,
    BDINDNATPJ,
    BDMANTERPARCELAS,
    BDCODPLANOINCONS,
    BDCODCONFGIARJ,
    BDCODCONFDFC,
    BDCODCONFCPRBREINF,
    BDANEXOIII_2018,
    BDANEXOIV_2018,
    BDANEXOV_2018,
    BDRELFOLHAANEXOIII,
    BDCODCONFDOT,
    BDCODPLANOCONFSN,
    BDALIQINSS,
    BDGERAC490,
    BDCODPLACATSP,
    BDOPTANTERET,
    BDMANTERC197CATSP,
    BDCODCLASSESTAB,
    BDCODPLASEFSC,
    BDCODCONFGIAST,
    BDAPURAGIAST,
    BDEC8715,
    BDCODCONFGIAFPE,
    BDCALCSTIMPSUB,
    BDSTRET,
    BDTIPOAPURACAORETIRTOM,
    BDCONTPISCOFCAIXA,
    BDCODCONFGIATO,
    BDCONTABGUIAMUN)
AS
SELECT X.BDCODEMP,
       X.BDREFEMP,
       parger.bdretinss,
       parger.bdvlrmininss,
       X.bdsuframa,
       parfed.bdcodacessosn,
       parfed.bdperfilsped,
       parfed.bdatividadesped,
       parinteg.bdsomfrevlrcontab,
       parinteg.bdsomfrebaseicms,
       parinteg.bdcodplatroca,
       parinteg.bdcodplacfop,
       parger.BDCODCONFIPI,
       parger.BDCODCONFIRLP,

       parsc.BDCODCONFDIMESC,
       PAREST.BDCODPORTEEMP,
       parsc.BDCODAPUCON,
       parsc.BDCODESCCONT ,
       parsc.BDCODREGAPU ,
       parsc.BDCONTPRODEC ,
       parsc.BDNRPARPRODEC ,

       parger.BDCODCONFATIVO,
       parger.BDLANBCICMSVALCONT,
       parger.BDLANBCICMSISEOUT,
       parger.BDLANCLISAISER,
       parger.BDLANPROENT,
       parger.BDLANPROSAI,
       parger.BDMOVSER,
       parger.BDPERCISS,
       parger.BDREDPERCISS,
       parger.BDMOVIRRF,
       parger.BDALIQIRRF,
       parger.BDISENTOIRRF,
       parger.BDEMPINATIVA,
       parger.BDEMPDIFPAPEL,
       parger.BDEMPBARREST,
       parger.BDVERIFICARNOTASJALAN,
       paratvsn.bdlrisssn,
       paratvsn.bdcomercio,
       paratvsn.bdindustria,
       paratvsn.bdservico,
       paritatvsn.bdanexoiii,
       paritatvsn.bdanexoiv,
       paritatvsn.bdanexov,
       PAREST.BDSUBSTRIB,
       PARGER.bdcodconfdacon,
       PARGER.BDCODCONFBLOCOM,
       PARGER.bdcodconfblocop,
       parsp.BDCODCONFGIASP,
       X.BDNOMEMP,
       PARFED.bdcodconficmssped,
       PARGER.BDCODCONFCIAP,
       PAREST.BDREDBCICMSENT,
       PAREST.BDREDBCICMSSAI,
       PAREST.BDICMSMONO,
       parger.BDCODCONFDASN,
       parger.BDRETPARPIS,
       parger.BDRETPARCOFINS,
       parger.BDRETPARCSLL,
       parger.BDRETPARIRRF,
       parger.BDRETPARISSQN,
       parger.BDRETPARINSS,
       parger.BDRETPARFUNRURAL,
       parger.bdtipoapuracao,
       parmg.BDCODCONFGIAMG,
       parmg.BDCODCONFDAMEF,
       parmg.bdcredpresumido,
       parmg.bdtermoaceite,
       parfed.bdantecipaimposto,
       parfed.BDTIPODECLARANTEDMED,
       parfed.BDREGISTROANSDMED,
       parfed.BDNUMEROCNESDMED,
       parfed.BDDTOBRIGSPEDCONT,
       parger.BDTIPOAPURACAORET,
       parger.BDTIPOAPURACAORETIR,
       parfed.BDDTOBRIGSPEDICMS,
       parinteg.BDLANCAPARCELAAUTO,
       parinteg.bdcodigopla,
       pares.BDCODCONFGIAES,
       parro.BDCODCONFGIARO,
       parfed.BDINDATIV,
       parpr.bdcodconfgiapr,
       paritatvsn.BDANEXOVI,
       PARFED.BDINDNATPJ,
       parinteg.bdmanterparcelas,
       parinteg.bdcodplanoincons,
       parrj.BDCODCONFGIARJ,
       parpr.bdcodconfdfc,
       PARGER.BDCODCONFCPRBREINF,
       paritatvsn.BDANEXOIII_2018,
       paritatvsn.BDANEXOIV_2018,
       paritatvsn.BDANEXOV_2018,
       paritatvsn.BDRELFOLHAANEXOIII,
       pares.bdcodconfdot,
       PARFED.BDCODPLANOCONFSN,
       parger.bdaliqinss,
       parfed.BDGERAC490,
       parsp.BDCODPLACATSP,
       PARFED.BDOPTANTERET,
       parsp.BDMANTERC197CATSP,
       PARFED.BDCODCLASSESTAB,
       parsc.bdCODPLASEFSC,
       PAREST.BDCODCONFGIAST,
       PAREST.BDAPURAGIAST,
       PAREST.BDEC8715,
       parPE.BDCODCONFGIAFPE,
       parsp.BDCALCSTIMPSUB,
       parsp.BDSTRET,
       parger.BDTIPOAPURACAORETIRTOM,
       parger.BDCONTPISCOFCAIXA,
       parto.BDCODCONFGIATO,
       PARFED.bdcontabguiamun

FROM VW_TEMPRESAS_REF_MAX_MIN emp

inner join tempresas temp on (temp.bdcodemp = emp.bdcodemp)
JOIN TEMPRESAS_REF X ON (x.bdcodemp = emp.bdCODEMP AND x.bdrefemp = emp.bdrefemp)
/* Alt.: #224878 - Nao deve mais olhar a referencia, a view agora ja busca referencia correta... */
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARGER parger ON (parger.bdcodemp = emp.bdcodemp /*AND parger.bdrefemp = emp.bdrefemp*/)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARFED parfed ON (parfed.bdcodemp = emp.bdcodemp /*AND parfed.bdrefemp = emp.bdrefemp*/)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTSC parsc ON (parsc.bdcodemp = emp.bdcodemp /*AND parsc.bdrefemp = emp.bdrefemp*/)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARFEDPORATV paratvsn ON (paratvsn.bdcodemp = emp.bdcodemp /*AND paratvsn.bdrefemp = emp.bdrefemp*/)
LEFT OUTER JOIN VW_VEF_BASE_TEMPITEMSATV paritatvsn ON (paritatvsn.bdcodemp = emp.bdcodemp /*AND paritatvsn.bdrefemp = emp.bdrefemp*/)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPAREST PAREST ON (PAREST.bdcodemp = emp.bdcodemp /*AND PAREST.bdrefemp = emp.bdrefemp*/)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTSP parsp ON (parsp.bdcodemp = emp.bdcodemp /*AND parsp.bdrefemp = emp.bdrefemp*/)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTMG parmg ON (parmg.bdcodemp = emp.bdcodemp /*AND parmg.bdrefemp = emp.bdrefemp*/)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARINTEG parinteg ON (parinteg.bdcodemp = emp.bdcodemp /*AND parinteg.bdrefemp = emp.bdrefemp*/)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTES pares ON (pares.bdcodemp = emp.bdcodemp ) --alt.: #7125 - Para páginas novas no cadastro de empresa, pode não existir a referencia procurada, portanto só é usado o código da empresa para ligar as views
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTRO parro ON (parro.bdcodemp = emp.bdcodemp ) --alt.: #7125 - Para páginas novas no cadastro de empresa, pode não existir a referencia procurada, portanto só é usado o código da empresa para ligar as views
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTPR parpr ON (parpr.bdcodemp = emp.bdcodemp ) --alt.: #7125 - Para páginas novas no cadastro de empresa, pode não existir a referencia procurada, portanto só é usado o código da empresa para ligar as views
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTRJ parrj ON (parrj.bdcodemp = emp.bdcodemp)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTPE parpe ON (PARPE.BDCODEMP = EMP.BDCODEMP)
LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTTO parto ON (parto.bdcodemp = emp.bdcodemp)
where((temp.bdexcluiremp is null)or(upper(temp.bdexcluiremp)<>'TRUE'))
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TEMPVINC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TEMPVINC(
BDCODEMP,
BDREFEMP,
BDCODPLAFUC)
 AS 
SELECT
    EMP.bdcodemp,
    EMP.bdrefemp,
    DAD.bdcodplafuc
FROM
(
  SELECT
      X.bdcodemp,
      COALESCE
  (
      (SELECT MAX(d2.bdrefemp) FROM vrh_base_tempvinc d2 WHERE d2.bdcodemp = x.bdcodemp AND CAST(d2.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefemp) FROM vrh_base_tempvinc d1 WHERE d1.bdcodemp = x.bdcodemp)
  ) AS bdrefemp
  FROM TEMPRESAS x
  where((x.bdexcluiremp is null)or(upper(x.bdexcluiremp)<>'TRUE'))

) AS EMP, vrh_base_tempvinc DAD
WHERE EMP.BDCODEMP = DAD.BDCODEMP AND EMP.BDREFEMP = DAD.BDREFEMP
;

/* CREATE OR ALTER VIEW: VW_EMPRESAS_USU (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_EMPRESAS_USU(
    BDCODEMP)
AS
/*
select emp.bdcodemp from tempresas emp
where
-- verifica se pertence ao grupo 1 ou 2
((select count(*) from tgrupousuario_usuario gu where gu.bdcodgrupo in (1,2) and bdcodusu = (select bdcodusu from sp_get_usuario)) > 0)

-- trazer todas as empresas se não tiver configuração por empresa
or
(
(select count(*) from tempresa_usuario eu where eu.bdcodusu = (select bdcodusu from sp_get_usuario)) = 0
and
(
 select count(*) from tempresa_grupousuario egu
 where egu.bdcodgrupo in (select gu.bdcodgrupo from tgrupousuario_usuario gu where bdcodusu = (select bdcodusu from sp_get_usuario))
 ) = 0
and
emp.bdcodemp in (
                 select distinct eg.bdcodemp from tempresas eg
                 join tgrupousuario gu on ((eg.bdcodesc = gu.bdcodesc) or (gu.bdcodesc is null))
                 where gu.bdcodgrupo in (select gu.bdcodgrupo from tgrupousuario_usuario gu where bdcodusu = (select bdcodusu from sp_get_usuario))
                 )
)
-- verifica empresas do grupo de usuario
or
(
(select count(*) from tempresa_usuario eu where eu.bdcodusu = (select bdcodusu from sp_get_usuario)) = 0
and
(
(select count(*) from tempresa_grupousuario eg
                 join tgrupousuario gu on (eg.bdcodgrupo = gu.bdcodgrupo and ((emp.bdcodesc = gu.bdcodesc) or (gu.bdcodesc is null)))
                 where eg.bdcodgrupo in (select gu.bdcodgrupo from tgrupousuario_usuario gu where bdcodusu = (select bdcodusu from sp_get_usuario))) = 0
or
emp.bdcodemp in (
                 select distinct eg.bdcodemp from tempresa_grupousuario eg
                 join tgrupousuario gu on (eg.bdcodgrupo = gu.bdcodgrupo and ((emp.bdcodesc = gu.bdcodesc) or (gu.bdcodesc is null)))
                 where eg.bdcodgrupo in (select gu.bdcodgrupo from tgrupousuario_usuario gu where bdcodusu = (select bdcodusu from sp_get_usuario)))
))
-- verifica empresas por usuario se existir empresas no grupo de usuario
or
(
emp.bdcodemp in (select eu.bdcodemp from tempresa_usuario eu  where eu.bdcodusu = (select bdcodusu from sp_get_usuario))
and
emp.bdcodemp in (select distinct eg.bdcodemp from tempresa_grupousuario eg
                 join tgrupousuario gu on (eg.bdcodgrupo = gu.bdcodgrupo and ((emp.bdcodesc = gu.bdcodesc) or (gu.bdcodesc is null)))
                 where eg.bdcodgrupo in (select gu.bdcodgrupo from tgrupousuario_usuario gu where bdcodusu = (select bdcodusu from sp_get_usuario)))
)
-- verifica empresas por usuario se não existir empresas no grupo de usuario
or
(
emp.bdcodemp in (select eu.bdcodemp from tempresa_usuario eu  where eu.bdcodusu = (select bdcodusu from sp_get_usuario))
and
(select count(*) from tempresa_grupousuario eg
                 join tgrupousuario gu on (eg.bdcodgrupo = gu.bdcodgrupo and ((emp.bdcodesc = gu.bdcodesc) or (gu.bdcodesc is null)))
                 where eg.bdcodgrupo in (select gu.bdcodgrupo from tgrupousuario_usuario gu where bdcodusu = (select bdcodusu from sp_get_usuario))) = 0

)*/

/* Empresas por grupo de usuario */
/*SELECT DISTINCT emp.bdcodemp--, emp.bdcodgrupo, grp.bdcodusu
FROM tempresa_grupousuario emp
INNER JOIN tgrupousuario_usuario grp ON (grp.bdcodgrupo = emp.bdcodgrupo AND grp.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
WHERE NOT EXISTS (SELECT FIRST 1 * FROM tempresa_usuario WHERE bdcodusu = grp.bdcodusu)
AND (SELECT bdcodusu FROM sp_get_usuario) NOT IN (1,2)
UNION
*/ /* Empresas por usuario */
/*SELECT DISTINCT emp.bdcodemp--, grp.bdcodgrupo, emp.bdcodusu
FROM tempresa_usuario emp
INNER JOIN tgrupousuario_usuario grp ON (grp.bdcodusu = emp.bdcodusu AND grp.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
WHERE (SELECT bdcodusu FROM sp_get_usuario) NOT IN (1,2)
UNION
*/ /* empresas por escritório */
/*SELECT DISTINCT temp.bdcodemp--, tusu.bdcodgrupo, tusu.bdcodusu
FROM tempresas temp
INNER JOIN tgrupousuario tgrp ON (tgrp.bdcodesc = temp.bdcodesc)
INNER JOIN tgrupousuario_usuario tusu ON (tusu.bdcodgrupo = tgrp.bdcodgrupo AND tusu.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
WHERE NOT EXISTS (SELECT FIRST 1 * FROM tempresa_usuario WHERE bdcodusu = tusu.bdcodusu)
AND NOT EXISTS (SELECT FIRST 1 * FROM tempresa_grupousuario WHERE bdcodgrupo = tgrp.bdcodgrupo)
AND (SELECT bdcodusu FROM sp_get_usuario) NOT IN (1,2)

UNION*/
/* quando não houver configurado empresa nas situações acima */
/*SELECT DISTINCT emp.bdcodemp--, null, (select bdcodusu from sp_get_usuario) as bdcodusu
FROM tempresas emp
WHERE ((NOT EXISTS (SELECT FIRST 1 * FROM tempresa_usuario WHERE bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))) AND 
       (NOT EXISTS (SELECT FIRST 1 * FROM tempresa_grupousuario emp
                    INNER JOIN tgrupousuario_usuario tgrp ON (tgrp.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
                    WHERE emp.bdcodgrupo = tgrp.bdcodgrupo)) and
       (not exists (select first 1 * from tgrupousuario emp
                    inner join tgrupousuario_usuario tgrp on (tgrp.bdcodusu = (select bdcodusu from sp_get_usuario))
                    where emp.bdcodgrupo = tgrp.bdcodgrupo)))
OR (SELECT bdcodusu FROM sp_get_usuario) IN (1,2)*/

/*
SELECT * FROM
(
--Seleção das empresas por usuário
SELECT DISTINCT emp.bdcodemp--, grp.bdcodgrupo, emp.bdcodusu
FROM tempresa_usuario emp
INNER JOIN tgrupousuario_usuario grp ON (grp.bdcodusu = emp.bdcodusu AND grp.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
-- caso usuário pertence ao grupo master não deve listar empresas nesse sql
WHERE NOT exists (SELECT FIRST 1 * FROM tgrupousuario_usuario WHERE BDCODUSU = EMP.bdcodusu AND BDCODGRUPO = 1)
union

-- listar todas as empresas caso usuário do grupo master
SELECT EMP.BDCODEMP FROM tempresas EMP
--left JOIN vfin_base_tcliente CLI on (EMP.bdcodemp = CLI.bdcodcli)
WHERE(exists (SELECT FIRST 1 * FROM tgrupousuario_usuario WHERE BDCODUSU = (SELECT bdcodusu FROM sp_get_usuario) AND BDCODGRUPO = 1))
--and CLI.bdcodtipocli <> 3 or cli.bdcodtipocli is null--leonardo Pereira - 08/10/2018 - #90984 - Não permitir selecionar cliente eventual
and((emp.bdexcluiremp is null)or(upper(emp.bdexcluiremp)<>'TRUE'))
UNION

--Seleção das empresas grupo de usuário
--onde NÃO tenha configuração no usuário
SELECT DISTINCT emp.bdcodemp--, emp.bdcodgrupo, grp.bdcodusu
FROM tempresa_grupousuario emp
INNER JOIN tgrupousuario_usuario grp ON (grp.bdcodgrupo = emp.bdcodgrupo AND grp.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
WHERE NOT EXISTS (SELECT FIRST 1 * FROM tempresa_usuario WHERE bdcodusu = grp.bdcodusu)
UNION

--Seleção das empresas por escritório
--onde NÃO tenha configuração no usuário e grupo de usuário
SELECT DISTINCT temp.bdcodemp--, tusu.bdcodgrupo, tusu.bdcodusu
FROM tempresas temp
INNER JOIN tgrupousuario tgrp ON (tgrp.bdcodesc = temp.bdcodesc)
INNER JOIN tgrupousuario_usuario tusu ON (tusu.bdcodgrupo = tgrp.bdcodgrupo AND tusu.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
WHERE NOT EXISTS (SELECT FIRST 1 * FROM tempresa_usuario WHERE bdcodusu = tusu.bdcodusu)
AND NOT EXISTS (SELECT FIRST 1 * FROM tempresa_grupousuario WHERE bdcodgrupo = tgrp.bdcodgrupo)
and((temp.bdexcluiremp is null)or(upper(temp.bdexcluiremp)<>'TRUE'))
UNION

--Seleção das empresas
--onde NÃO tenha configuração por usuário e grupo de usuário
--Caso de não haver configurada essas restrições na base e usuário não ser master
SELECT DISTINCT emp.bdcodemp--, null, (select bdcodusu from sp_get_usuario) as bdcodusu
FROM tempresas emp
--left join vfin_base_tcliente cli on (cli.bdcodcli = emp.bdcodemp) --leonardo Pereira - 08/10/2018 - #90984 - Não permitir selecionar cliente eventual
WHERE ((NOT EXISTS (SELECT FIRST 1 * FROM tempresa_usuario WHERE bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))) AND 
       (NOT EXISTS (SELECT FIRST 1 * FROM tempresa_grupousuario emp
                    INNER JOIN tgrupousuario_usuario tgrp ON (tgrp.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
                    WHERE emp.bdcodgrupo = tgrp.bdcodgrupo)) )
and((emp.bdexcluiremp is null)or(upper(emp.bdexcluiremp)<>'TRUE'))
--and cli.bdcodtipocli <> 3 or cli.bdcodtipocli is null
) EMPRESASPARAUSUARIOATIVO
--Filtro para trazer todas as empresas que sejam do grupo 1 (master)
--Conforme conversado com a Graci, o grupo 2 pode ser aberto, devendo 
--considerar apenas o grupo 1 como master
WHERE NOT EXISTS (SELECT FIRST 1 emp.bdcodgrupo FROM tempresa_grupousuario emp
                  INNER JOIN tgrupousuario_usuario grp ON (grp.bdcodgrupo = emp.bdcodgrupo AND grp.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
                  WHERE grp.bdcodgrupo = 1)
*/
select EMPU.BDCODEMP from SP_EMPRESAS_USU EMPU group by BDCODEMP
;

CREATE OR ALTER VIEW vw_empresas_grupo_usuario (bdcodemp, bdcodgrupo, bdcodusu)
AS
-- Empresas por grupo de usuario
SELECT emp.bdcodemp, emp.bdcodgrupo, grp.bdcodusu
FROM tempresa_grupousuario emp
INNER JOIN tgrupousuario_usuario grp ON (grp.bdcodgrupo = emp.bdcodgrupo AND grp.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
WHERE NOT EXISTS (SELECT FIRST 1 * FROM tempresa_usuario WHERE bdcodusu = grp.bdcodusu)
AND (SELECT bdcodusu FROM sp_get_usuario) NOT IN (1,2)
UNION ALL
-- Empresas por usuario
SELECT emp.bdcodemp, grp.bdcodgrupo, emp.bdcodusu
FROM tempresa_usuario emp
INNER JOIN tgrupousuario_usuario grp ON (grp.bdcodusu = emp.bdcodusu AND grp.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
WHERE (SELECT bdcodusu FROM sp_get_usuario) NOT IN (1,2)
UNION ALL
-- empresas por escritório
SELECT temp.bdcodemp, tusu.bdcodgrupo, tusu.bdcodusu
FROM tempresas temp
INNER JOIN tgrupousuario tgrp ON (tgrp.bdcodesc = temp.bdcodesc)
INNER JOIN tgrupousuario_usuario tusu ON (tusu.bdcodgrupo = tgrp.bdcodgrupo AND tusu.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
WHERE NOT EXISTS (SELECT FIRST 1 * FROM tempresa_usuario WHERE bdcodusu = tusu.bdcodusu)
AND NOT EXISTS (SELECT FIRST 1 * FROM tempresa_grupousuario WHERE bdcodgrupo = tgrp.bdcodgrupo)
AND (SELECT bdcodusu FROM sp_get_usuario) NOT IN (1,2)
and((temp.bdexcluiremp is null)or(upper(temp.bdexcluiremp)<>'TRUE'))

UNION ALL
-- quando não houver configurado empresa nas situações acima
SELECT emp.bdcodemp, NULL, (SELECT bdcodusu FROM sp_get_usuario) AS bdcodusu
FROM tempresas emp
WHERE (((NOT EXISTS (SELECT FIRST 1 * FROM tempresa_usuario WHERE bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))) AND
       (NOT EXISTS (SELECT FIRST 1 * FROM tempresa_grupousuario emp
                    INNER JOIN tgrupousuario_usuario tgrp ON (tgrp.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
                    WHERE emp.bdcodgrupo = tgrp.bdcodgrupo)) AND 
       (NOT EXISTS (SELECT FIRST 1 * FROM tgrupousuario emp
                    INNER JOIN tgrupousuario_usuario tgrp ON (tgrp.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
                    WHERE emp.bdcodgrupo = tgrp.bdcodgrupo)))
OR (SELECT bdcodusu FROM sp_get_usuario) IN (1,2))
and((emp.bdexcluiremp is null)or(upper(emp.bdexcluiremp)<>'TRUE'));


/* CREATE OR ALTER VIEW: VW_EMPRESAS_REF_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_EMPRESAS_REF_ATUAL(
    BDCODEMP,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDCODCENTROS,
    BDCODPLATRIB,
    BDCODCID,
    BDCODCONT,
    BDCODCONTEF,
    BDCODCONTRH,
    BDCODNATJUR,
    BDCODCNAE,
    BDNOMEMP,
    BDNOMREDUZEMP,
    BDAPEEMP,
    BDENDEMP,
    BDNUMEMP,
    BDBAIEMP,
    BDCEPEMP,
    BDDDDEMP,
    BDFONEEMP,
    BDFAXEMP,
    BDEMAILEMP,
    BDCOMPLEMP,
    BDLOGREMP,
    BDIEEMP,
    BDIMEMP,
    BDSITEMP,
    BDCODPLAFUC,
    BDDDDFAXEMP,
    BDCODPLANOONLINE,
    BDSUFRAMA,
    BDCNPJEMP,
    BDCODMATRIZ,
    BDEMPREF,
    BDCERTDIGITAL,
    BDDESCCARTEMP,
    bdorgaoemp,
    bddataregemp,
    bdnomecartorio,
    bdlivro,
    bdfolha,
    BDTIPOCAEPF,
    BDINTEGRANET)
AS
SELECT x.BDCODEMP,
       X.BDCODPLAPADRAO,
       X.BDCODHIST,
       X.BDCODCENTROS,
       X.BDCODPLATRIB,
       X.BDCODCID,
       X.BDCODCONT,
       X.BDCODCONTEF,
       X.BDCODCONTRH,
       X.BDCODNATJUR,
       X.BDCODCNAE,
       X.BDNOMEMP,
       X.BDNOMREDUZEMP,
       X.BDAPEEMP,
       X.BDENDEMP,
       X.BDNUMEMP,
       X.BDBAIEMP,
       X.BDCEPEMP,
--       X.BDLOGOEMP,
       X.BDDDDEMP,
       X.BDFONEEMP,
       X.BDFAXEMP,
       X.BDEMAILEMP,
       X.BDCOMPLEMP,
       X.BDLOGREMP,
       X.BDIEEMP,
       X.BDIMEMP,
       X.BDSITEMP,
       Y.BDCODPLAFUC,
       X.BDDDDFAXEMP,
       x.BDCODPLANOONLINE,
       X.bdsuframa,
       z.BDCNPJEMP,
       z.BDCODMATRIZ,
       X.bdrefemp,
       Z.BDCERTDIGITAL,
       x.bddesccartemp,
       x.bdorgaoemp, 
       x.bddataregemp, 
       x.bdnomecartorio, 
       x.bdlivro, 
       x.bdfolha,
       z.BDTIPOCAEPF,
       z.BDINTEGRANET
FROM
  VW_TEMPRESAS_REF X
LEFT OUTER JOIN VW_VRH_BASE_TEMPVINC Y ON (Y.BDCODEMP = X.BDCODEMP)
INNER JOIN tempresas z ON (z.bdcodemp = x.bdcodemp)
inner join vw_empresas_usu a on (a.bdcodemp = z.bdcodemp)
;

/* CREATE OR ALTER VIEW: VW_TEMPRESAS_REF_MAX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TEMPRESAS_REF_MAX(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
  X.BDCODEMP,
  MAX(X.BDREFEMP)
FROM
  tempresas_ref X
--join vw_empresas_usu usu on (x.bdcodemp = usu.bdcodemp) /*deixava o sistema todo muito lento*/
WHERE
  CAST(X.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
GROUP BY X.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_TEMPRESAS_REF_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TEMPRESAS_REF_ATUAL(
BDCODEMP,
BDREFEMP,
BDCODPLAPADRAO,
BDCODHIST,
BDCODCENTROS,
BDCODCID,
BDCODCONT,
BDCODCONTEF,
BDCODCONTRH,
BDCODNATJUR,
BDCODCNAE,
BDNOMEMP,
BDAPEEMP,
BDENDEMP,
BDNUMEMP,
BDBAIEMP,
BDCEPEMP,
BDDDDEMP,
BDFONEEMP,
BDFAXEMP,
BDEMAILEMP,
BDCOMPLEMP,
BDLOGREMP,
BDIEEMP,
BDIMEMP,
BDSITEMP,
BDDDDFAXEMP,
BDDOCAUXILIAR,
BDCODPLANOONLINE,
bdnomreduzemp,
BDCODPLATRIB,
BDCODCONTABLALUR,
BDCODZONA)
 AS 
SELECT
    X.bdcodemp,
    X.bdrefemp,
    X.bdcodplapadrao,
    X.bdcodhist,
    X.bdcodcentros,
    X.bdcodcid,
    X.bdcodcont,
    X.bdcodcontef,
    X.bdcodcontrh,
    X.bdcodnatjur,
    X.bdcodcnae,
    X.bdnomemp,
    X.bdapeemp,
    X.bdendemp,
    X.bdnumemp,
    X.bdbaiemp,
    X.bdcepemp,
    X.bddddemp,
    X.bdfoneemp,
    X.bdfaxemp,
    X.bdemailemp,
    X.bdcomplemp,
    X.bdlogremp,
    X.bdieemp,
    X.bdimemp,
    X.bdsitemp,
    X.bddddfaxemp,
--    X.bdlogoemp,
    X.BDDOCAUXILIAR,
    X.BDCODPLANOONLINE,
    X.bdnomreduzemp,
    X.BDCODPLATRIB,
    X.BDCODCONTABLALUR,
    x.BDCODZONA
FROM tempresas_ref X
WHERE
  EXISTS (SELECT Y.BDCODEMP, Y.BDREFEMP
          FROM vw_tempresas_ref_max Y
          WHERE Y.BDCODEMP = X.BDCODEMP AND (Y.BDREFEMP = X.BDREFEMP)
         )
;

/* CREATE OR ALTER VIEW: VW_EMPRESAS_REF_ATUAL_SEARCH (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_EMPRESAS_REF_ATUAL_SEARCH(
BDCODEMP,
BDIEEMP,
BDAPEEMP)
 AS 
SELECT DISTINCT x.BDCODEMP,
       X.BDIEEMP, X.bdapeemp
FROM vw_tempresas_ref_atual X
;

/* CREATE OR ALTER VIEW: VW_EMPRESAS_TBEM (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_EMPRESAS_TBEM(
BDCODEMP,
BDCODBEM,
BDCODPLAPADRAO,
BDCODTPLA,
BDCODCENTRO,
BDCODTPCC,
BDCODATVEXT,
BDCODPAIS,
BDCODORIGBEM,
BDCODTER,
BDNATBEM,
BDNOMBEM,
BDIDBEM,
BDIDPATRBEM,
BDDATORIAQUIBEM,
BDDEPMESAQUIBEM,
BDDEPDIARIA,
BDDEPMESBAIXABEM,
BDVALAQUIBEM,
BDUFIR31_12_2000,
BDDEPDIADATA,
BDVLRBEMEMUFIR,
BDNUMDIAS,
BDNRCHAPA,
BDCODIND,
BDFUNCIONALIDADE,
BDTIPOBEM,
BDVIDAUTIL,
BDQUANTIDADEBEM,
BDTIPODOCBEM,
BDNRDOCBEM,
BDSERIEBEM,
BDNRORDBEM,
BDNRLIVROBEM,
BDNRFOLHABEM,
BDCLASSBEM,
BDVALICMSBEM,
BDDIVIDIRBEM,
BDCODCCSPED,
BDVLRICMSST,
BDVLRICMSFRETE,
BDVLRICMSDIFALIQ,
bdNUMDOCARREC, 
BDDATAPRIPAR)
 AS 
SELECT
    X.BDCODEMP,
    X.BDCODBEM,
    X.BDCODPLAPADRAO,
    X.BDCODTPLA,
    X.BDCODCENTRO,
    X.BDCODTPCC,
    X.BDCODATVEXT,
    X.BDCODPAIS,
    X.BDCODORIGBEM,
    X.BDCODTER,
    X.BDNATBEM,
    X.BDNOMBEM,
    X.BDIDBEM ,
    X.BDIDPATRBEM,
    X.BDDATORIAQUIBEM,
    X.BDDEPMESAQUIBEM,
    X.BDDEPDIARIA,
    X.BDDEPMESBAIXABEM,
    X.BDVALAQUIBEM,
    X.BDUFIR31_12_2000,
    X.BDDEPDIADATA,
    X.BDVLRBEMEMUFIR,
    X.BDNUMDIAS,
    X.BDNRCHAPA,
    X.BDCODIND,
    X.BDFUNCIONALIDADE,
    X.BDTIPOBEM,
    X.BDVIDAUTIL,
    X.BDQUANTIDADEBEM,

    Y.BDTIPODOCBEM,
    Y.BDNRDOCBEM,
    Y.BDSERIEBEM,
    Y.BDNRORDBEM,
    Y.BDNRLIVROBEM,
    Y.BDNRFOLHABEM,
    Y.BDCLASSBEM,
    Y.BDVALICMSBEM,
    Y.BDDIVIDIRBEM,
    Y.BDCODCCSPED,
    Y.BDVLRICMSST,
    Y.BDVLRICMSFRETE,
    Y.BDVLRICMSDIFALIQ,
    y.bdNUMDOCARREC,
    y.BDDATAPRIPAR

FROM EMPRESAS_TBEM X
LEFT OUTER JOIN vef_emp_tbem Y ON (Y.BDCODEMP = X.BDCODEMP AND Y.bdcodbem = X.bdcodbem)
;

/* CREATE OR ALTER VIEW: VW_EMPRESAS_TSOCCOTAS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_EMPRESAS_TSOCCOTAS(
BDCODEMP,
BDCODSOC,
BDREFCOTA,
BDPRESCOTA,
BDCAPTOTCOTA,
BDCAPVOLCOTA,
BDRENISECOTA,
BDRENTRICOTA,
BDIRFONTCOTA,
BDDEMRENCOTA,
BDREMTRACOTA,
BDQTDCOTA,
BDVALCOTA,
BDPERCCOTA,
BDVALORDISTRIBLUCRO)
 AS 
SELECT
    BDCODEMP,
    BDCODSOC,
    BDREFCOTA,
    BDPRESCOTA,
    BDCAPTOTCOTA,
    BDCAPVOLCOTA,
    BDRENISECOTA,
    BDRENTRICOTA,
    BDIRFONTCOTA,
    BDDEMRENCOTA,
    BDREMTRACOTA,
    BDQTDCOTA,
    BDVALCOTA,
    BDPERCCOTA,
    BDVALORDISTRIBLUCRO

FROM empresas_tsoccotas tsoccotas
WHERE tsoccotas.bdrefcota =
      (
       SELECT MAX(cotas.bdrefcota)
       FROM empresas_tsoccotas cotas
       WHERE cotas.bdcodemp = tsoccotas.bdcodemp AND cotas.bdcodsoc = tsoccotas.bdcodsoc AND
             cotas.bdrefcota <=
                (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER)
                 FROM rdb$database
                )
      )
ORDER BY bdcodemp, bdcodsoc
;

/* CREATE OR ALTER VIEW: VW_FGTS_13S (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_FGTS_13S(
BDCODEMP,
BDCODCOL,
BDREF,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF13,
  0.0 BDBFGTSFN,
  0.0 BDFGTSFN,
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  3 BDTIPO
FROM VRHF_EMP_T13SAL
;

/* CREATE OR ALTER VIEW: VW_FGTS_A13 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_FGTS_A13(
BDCODEMP,
BDCODCOL,
BDREF,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFA13,
  0.0 BDBFGTSFN,
  0.0 BDFGTSFN,
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  2 BDTIPO
FROM VRHF_EMP_TA13SAL
;

/* CREATE OR ALTER VIEW: VW_FGTS_AVULSA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_FGTS_AVULSA(
BDCODEMP,
BDCODCOL,
BDREF,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  CAST((SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) BDREFFA,
  SUM(BDBFGTSFA + BDBFGTS13FA + COALESCE(bdbfgtsfefa,0)),
  SUM(BDFGTSFA + BDFGTS13FA + COALESCE(bdfgtsfefa,0)),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBFGTS13FAASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  5 BDTIPO
FROM VRHF_EMP_TFOLHAAVULSA
GROUP BY BDCODEMP, BDCODCOL, BDREFFA
;

/* CREATE OR ALTER VIEW: VW_FGTS_C13 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_FGTS_C13(
BDCODEMP,
BDCODCOL,
BDREF,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFC13,
  0.0 BDBFGTSFN,
  0.0 BDFGTSFN,
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  4 BDTIPO
FROM VRHF_EMP_TC13SAL
;

/* CREATE OR ALTER VIEW: VW_FGTS_FOL_COMPLEMENTAR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_FGTS_FOL_COMPLEMENTAR(
BDCODEMP,
BDCODCOL,
BDREF,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFCOMP,
  0.0 BDBFGTSXX,
  0.0 BDFGTSXX,
  BDBFGTSFC + BDBFGTS13FC + COALESCE(BDBFGTSFEFC,0),
  BDFGTSFC + BDFGTS13FC + COALESCE(BDFGTSFEFC,0),
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  6 BDTIPO
FROM VRHF_EMP_TFOLHACOMP
UNION
SELECT
  X.bdcodemp,
  X.bdcodcol,
  X.bdrefcomp,
  0.0 BDBFGTSXX,
  0.0 BDFGTSXX,
  SUM(X.bdbfgtsfc) + SUM(X.bdbfgts13fc) + SUM(COALESCE(BDBFGTSFEFC,0)),
  SUM(X.bdfgtsfC) + SUM(X.bdfgts13fC) + SUM(COALESCE(BDFGTSFEFC,0)),
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  6 BDTIPO
FROM vrhf_emp_tfoltomcomp x
GROUP BY x.BDCODEMP, x.BDCODCOL, x.bdrefCOMP
;

CREATE OR ALTER VIEW VW_FGTS_FOL_COMPLEMENTAR_INT(
    BDCODEMP,
    BDCODCOL,
    BDCODCONTTI,
    BDREF,
    BDBFGTSFN,
    BDFGTSFN,
    BDBFGTSFC,
    BDFGTSFC,
    BDBASEFGTS13,
    BDFGTS13,
    BDBASEFGTSA13,
    BDFGTSA13,
    BDBASEFGTSC13,
    BDFGTSC13,
    BDTIPO)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDCODCONTTI,
  BDREFCOMP,
  0.0 BDBFGTSXX,
  0.0 BDFGTSXX,
  BDBFGTSFC + BDBFGTS13FC + COALESCE(BDBFGTSFEFC,0),
  BDFGTSFC + BDFGTS13FC + COALESCE(BDFGTSFEFC,0),
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  6 BDTIPO
FROM VRHF_EMP_TFOLHACOMPINT
UNION
SELECT
  X.bdcodemp,
  X.bdcodcol,
  X.bdcodcontti,
  X.bdrefcomp,
  0.0 BDBFGTSXX,
  0.0 BDFGTSXX,
  SUM(X.bdbfgtsfc) + SUM(X.bdbfgts13fc) + SUM(COALESCE(BDBFGTSFEFC,0)),
  SUM(X.bdfgtsfC) + SUM(X.bdfgts13fC) + SUM(COALESCE(BDFGTSFEFC,0)),
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  6 BDTIPO
FROM VRHF_EMP_TFOLTOMCOMPINT X
GROUP BY x.BDCODEMP, x.BDCODCOL, x.BDCODCONTTI, x.bdrefCOMP
;

/* View: VW_FGTS_FOL_COMPLEMENTAR_CC */
CREATE OR ALTER VIEW VW_FGTS_FOL_COMPLEMENTAR_CC(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCODCENTRO,
    BDCODTPCC,
    BDBFGTSFN,
    BDFGTSFN,
    BDBFGTSFC,
    BDFGTSFC,
    BDBASEFGTS13,
    BDFGTS13,
    BDBASEFGTSA13,
    BDFGTSA13,
    BDBASEFGTSC13,
    BDFGTSC13,
    BDTIPO)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFCOMP,
  cast(null as integer),
  cast(null as integer),
  0.0 BDBFGTSXX,
  0.0 BDFGTSXX,
  BDBFGTSFC + BDBFGTS13FC + COALESCE(BDBFGTSFEFC,0),
  BDFGTSFC + BDFGTS13FC + COALESCE(BDFGTSFEFC,0),
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  6 BDTIPO
FROM VRHF_EMP_TFOLHACOMP
UNION
SELECT
  X.bdcodemp,
  X.bdcodcol,
  X.bdrefcomp,
  pfn.bdcodcentro,
  pfn.bdcodtpcc,
  0.0 BDBFGTSXX,
  0.0 BDFGTSXX,
  SUM(X.bdbfgtsfc) + SUM(X.bdbfgts13fc) + SUM(COALESCE(BDBFGTSFEFC,0)),
  SUM(X.bdfgtsfC) + SUM(X.bdfgts13fC) + SUM(COALESCE(BDFGTSFEFC,0)),
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  6 BDTIPO
FROM vrhf_emp_tfoltomcomp x
join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = x.bdcodemp and pfn.bdcodcol = x.bdcodcol and pfn.bdordem = x.bdordem)
GROUP BY x.BDCODEMP, x.BDCODCOL, x.bdrefCOMP, pfn.bdcodcentro, pfn.bdcodtpcc
UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFCOMP,
  cast(null as integer),
  cast(null as integer),
  0.0 BDBFGTSXX,
  0.0 BDFGTSXX,
  SUM(COALESCE(BDBFGTSFC, 0) + COALESCE(BDBFGTS13FC, 0) + COALESCE(BDBFGTSFEFC,0)),
  SUM(COALESCE(BDFGTSFC, 0) + COALESCE(BDFGTS13FC, 0) + COALESCE(BDFGTSFEFC,0)),
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  6 BDTIPO
FROM VRHF_EMP_TFOLHACOMPINT
GROUP BY BDCODEMP, BDCODCOL, BDREFCOMP
UNION
SELECT
  X.bdcodemp,
  X.bdcodcol,
  X.bdrefcomp,
  pfn.bdcodcentro,
  pfn.bdcodtpcc,
  0.0 BDBFGTSXX,
  0.0 BDFGTSXX,
  SUM(X.bdbfgtsfc) + SUM(X.bdbfgts13fc) + SUM(COALESCE(BDBFGTSFEFC,0)),
  SUM(X.bdfgtsfC) + SUM(X.bdfgts13fC) + SUM(COALESCE(BDFGTSFEFC,0)),
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  6 BDTIPO
FROM VRHF_EMP_TFOLTOMCOMPINT X
join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = x.bdcodemp and pfn.bdcodcol = x.bdcodcol and pfn.bdordem = x.bdordem)
GROUP BY x.BDCODEMP, x.BDCODCOL, x.bdrefCOMP, pfn.bdcodcentro, pfn.bdcodtpcc
;

/* CREATE OR ALTER VIEW: VW_FGTS_FOL_NORMAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_FGTS_FOL_NORMAL(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDBFGTSFN,
    BDFGTSFN,
    BDBFGTSFC,
    BDFGTSFC,
    BDBASEFGTS13,
    BDFGTS13,
    BDBASEFGTSA13,
    BDFGTSA13,
    BDBASEFGTSC13,
    BDFGTSC13,
    BDTIPO)
AS
SELECT
  Y.BDCODEMP,
  Y.BDCODCOL,
  Y.BDREFFN,
  Y.BDBFGTSFN + Y.BDBFGTS13FN + COALESCE(Y.bdbfgtsfefn,0),
  Y.BDFGTSFN + Y.BDFGTS13FN + COALESCE(Y.bdfgtsfefn,0),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  0 BDTIPO
FROM VRHF_EMP_TFOLHANORMAL Y
UNION
SELECT
  Y.BDCODEMP,
  Y.BDCODCOL,
  Y.BDREFFN,
  SUM(Y.BDBFGTSFN + COALESCE(Y.bdbfgtsfefn,0)),
  SUM(Y.BDFGTSFN + COALESCE(Y.bdfgtsfefn,0)),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  SUM(Y.BDBFGTS13FN) BDBASEFGTS13,
  SUM(Y.BDFGTS13FN) BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  0 BDTIPO
FROM VRHF_EMP_TFOLHAINT Y
GROUP BY Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN
UNION
SELECT
  X.bdcodemp,
  X.bdcodcol,
  X.bdreftomador,
  SUM(X.bdbfgtsft) + SUM(X.bdbfgts13ft) + SUM(COALESCE(X.bdbfgtsFEft,0)),
  SUM(X.bdfgtsft) + SUM(X.bdfgts13ft) + SUM(COALESCE(x.bdfgtsFEft,0)),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  0 BDTIPO
FROM vrhf_emp_tfolhatomador x
GROUP BY x.BDCODEMP, x.BDCODCOL, x.bdreftomador
UNION
SELECT
  X.bdcodemp,
  X.bdcodcol,
  X.bdreftomador,
  SUM(X.bdbfgtsft) + SUM(COALESCE(X.bdbfgtsFEft,0)),
  SUM(X.bdfgtsft) + SUM(COALESCE(x.bdfgtsFEft,0)),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  SUM(X.bdbfgts13ft) BDBASEFGTS13,
  SUM(X.bdfgts13ft) BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  0 BDTIPO
FROM vrhf_emp_tfolhatomint x
GROUP BY x.BDCODEMP, x.BDCODCOL, x.bdreftomador
;

/* Create view: VW_FGTS_FOL_NORMAL_CC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_FGTS_FOL_NORMAL_CC(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCODCENTRO,
    BDCODTPCC,
    BDBFGTSFN,
    BDFGTSFN,
    BDBFGTSFC,
    BDFGTSFC,
    BDBASEFGTS13,
    BDFGTS13,
    BDBASEFGTSA13,
    BDFGTSA13,
    BDBASEFGTSC13,
    BDFGTSC13,
    BDTIPO)
AS
SELECT
  Y.BDCODEMP,
  Y.BDCODCOL,
  Y.BDREFFN,
  cast(null as integer),
  cast(null as integer),
  Y.BDBFGTSFN + Y.BDBFGTS13FN + COALESCE(Y.bdbfgtsfefn,0),
  Y.BDFGTSFN + Y.BDFGTS13FN + COALESCE(Y.bdfgtsfefn,0),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  0 BDTIPO
FROM VRHF_EMP_TFOLHANORMAL Y
UNION
SELECT
  Y.BDCODEMP,
  Y.BDCODCOL,
  Y.BDREFFN,
  cast(null as integer),
  cast(null as integer),
  SUM(Y.BDBFGTSFN + COALESCE(Y.bdbfgtsfefn,0)),
  SUM(Y.BDFGTSFN + COALESCE(Y.bdfgtsfefn,0)),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  SUM(Y.BDBFGTS13FN) BDBASEFGTS13,
  SUM(Y.BDFGTS13FN) BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  0 BDTIPO
FROM VRHF_EMP_TFOLHAINT Y
group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN
UNION
SELECT
  X.bdcodemp,
  X.bdcodcol,
  X.bdreftomador,
  pfn.bdcodcentro,
  pfn.bdcodtpcc,
  SUM(X.bdbfgtsft) + SUM(X.bdbfgts13ft) + SUM(COALESCE(X.bdbfgtsFEft,0)),
  SUM(X.bdfgtsft) + SUM(X.bdfgts13ft) + SUM(COALESCE(x.bdfgtsFEft,0)),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  0 BDTIPO
FROM vrhf_emp_tfolhatomador x
join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = x.bdcodemp and pfn.bdcodcol = x.bdcodcol and pfn.bdordem = x.bdordem)
GROUP BY x.BDCODEMP, x.BDCODCOL, x.bdreftomador, pfn.bdcodcentro, pfn.bdcodtpcc
UNION
SELECT
  X.bdcodemp,
  X.bdcodcol,
  X.bdreftomador,
  pfn.bdcodcentro,
  pfn.bdcodtpcc,
  SUM(X.bdbfgtsft) + SUM(COALESCE(X.bdbfgtsFEft,0)),
  SUM(X.bdfgtsft) + SUM(COALESCE(x.bdfgtsFEft,0)),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  SUM(X.bdbfgts13ft) BDBASEFGTS13,
  SUM(X.bdfgts13ft) BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  0 BDTIPO
FROM vrhf_emp_tfolhatomint x
join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = x.bdcodemp and pfn.bdcodcol = x.bdcodcol and pfn.bdordem = x.bdordem)
GROUP BY x.BDCODEMP, x.BDCODCOL, x.bdreftomador, pfn.bdcodcentro, pfn.bdcodtpcc
;

/* View: VW_FGTS_A13_CC */
CREATE OR ALTER VIEW VW_FGTS_A13_CC(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCODCENTRO,
    BDCODTPCC,
    BDBFGTSFN,
    BDFGTSFN,
    BDBFGTSFC,
    BDFGTSFC,
    BDBASEFGTS13,
    BDFGTS13,
    BDBASEFGTSA13,
    BDFGTSA13,
    BDBASEFGTSC13,
    BDFGTSC13,
    BDTIPO)
AS
SELECT
  A13.BDCODEMP,
  A13.BDCODCOL,
  A13.BDREFA13,
  pfn.BDCODCENTRO,
  pfn.BDCODTPCC,
  0.0 BDBFGTSFN,
  0.0 BDFGTSFN,
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  A13.BDBASEFGTSA13,
  A13.BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  2 BDTIPO
FROM VRHF_EMP_TA13SAL A13
left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = a13.bdcodemp and pfn.bdcodcol = a13.bdcodcol and pfn.bdordem = a13.bdordem)
;

/* View: VW_FGTS_13S_CC */
CREATE OR ALTER VIEW VW_FGTS_13S_CC(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCODCENTRO,
    BDCODTPCC,
    BDBFGTSFN,
    BDFGTSFN,
    BDBFGTSFC,
    BDFGTSFC,
    BDBASEFGTS13,
    BDFGTS13,
    BDBASEFGTSA13,
    BDFGTSA13,
    BDBASEFGTSC13,
    BDFGTSC13,
    BDTIPO)
AS
SELECT
  S13.BDCODEMP,
  S13.BDCODCOL,
  S13.BDREF13,
  pfn.BDCODCENTRO,
  pfn.BDCODTPCC,
  0.0 BDBFGTSFN,
  0.0 BDFGTSFN,
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  S13.BDBASEFGTS13,
  S13.BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  3 BDTIPO
FROM VRHF_EMP_T13SAL S13
left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = s13.bdcodemp and pfn.bdcodcol = s13.bdcodcol and pfn.bdordem = s13.bdordem)
;

/* View: VW_FGTS_C13_CC */
CREATE OR ALTER VIEW VW_FGTS_C13_CC(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCODCENTRO,
    BDCODTPCC,
    BDBFGTSFN,
    BDFGTSFN,
    BDBFGTSFC,
    BDFGTSFC,
    BDBASEFGTS13,
    BDFGTS13,
    BDBASEFGTSA13,
    BDFGTSA13,
    BDBASEFGTSC13,
    BDFGTSC13,
    BDTIPO)
AS
SELECT
  C13.BDCODEMP,
  C13.BDCODCOL,
  C13.BDREFC13,
  pfn.BDCODCENTRO,
  pfn.BDCODTPCC,
  0.0 BDBFGTSFN,
  0.0 BDFGTSFN,
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  C13.BDBASEFGTSC13,
  C13.BDFGTSC13,
  4 BDTIPO
FROM VRHF_EMP_TC13SAL C13
left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = c13.bdcodemp and pfn.bdcodcol = c13.bdcodcol and pfn.bdordem = c13.bdordem)
;

/* View: VW_FGTS_AVULSA_CC */
CREATE OR ALTER VIEW VW_FGTS_AVULSA_CC(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCODCENTRO,
    BDCODTPCC,
    BDBFGTSFN,
    BDFGTSFN,
    BDBFGTSFC,
    BDFGTSFC,
    BDBASEFGTS13,
    BDFGTS13,
    BDBASEFGTSA13,
    BDFGTSA13,
    BDBASEFGTSC13,
    BDFGTSC13,
    BDTIPO)
AS
SELECT
  FA.BDCODEMP,
  FA.BDCODCOL,
  CAST((SUBSTRING(CAST(FA.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FA.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) BDREFFA,
  pfn.BDCODCENTRO,
  pfn.BDCODTPCC,
  SUM(FA.BDBFGTSFA + FA.BDBFGTS13FA + COALESCE(FA.bdbfgtsfefa,0)),
  SUM(FA.BDFGTSFA + FA.BDFGTS13FA + COALESCE(FA.bdfgtsfefa,0)),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBFGTS13FAASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13,
  5 BDTIPO
FROM VRHF_EMP_TFOLHAAVULSA FA
left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = fa.bdcodemp and pfn.bdcodcol = fa.bdcodcol and pfn.bdordem = fa.bdordem)
GROUP BY FA.BDCODEMP, FA.BDCODCOL, BDREFFA, pfn.BDCODCENTRO,pfn.BDCODTPCC
;

/* CREATE OR ALTER VIEW: VW_FGTS_FOLHA_TOMADOR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_FGTS_FOLHA_TOMADOR(
BDCODEMP,
BDCODCOL,
BDREF,
BDORDEM,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13)
 AS 
SELECT
  X.bdcodemp,
  X.bdcodcol,
  X.bdreftomador,
  X.bdordem,
  X.bdbfgtsft + X.bdbfgts13ft + COALESCE(X.bdbfgtsfeft,0),
  X.bdfgtsft + X.bdfgts13ft + COALESCE(X.bdfgtsfeft,0),
  0.0 BDBFGTSFC,
  0.0 BDFGTSFC,
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13
FROM vrhf_emp_tfolhatomador x
UNION
SELECT
  Y.bdcodemp,
  Y.bdcodcol,
  Y.bdrefcomp,
  Y.bdordem,
  0.0 BDBFGTSXX,
  0.0 BDFGTSXX,
  Y.bdbfgtsfc + Y.bdbfgts13fc + COALESCE(y.bdbfgtsfefC,0),
  Y.bdfgtsfC + Y.bdfgts13fC + COALESCE(Y.bdfgtsfefC,0),
  0.0 BDBASEFGTS13,
  0.0 BDFGTS13,
  0.0 BDBASEFGTSA13,
  0.0 BDFGTSA13,
  0.0 BDBASEFGTSC13,
  0.0 BDFGTSC13
FROM vrhf_emp_tfoltomcomp y
;

/* CREATE OR ALTER VIEW: VW_FGTS_FOLHA_TOMADOR_AGR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_FGTS_FOLHA_TOMADOR_AGR(
BDCODEMP,
BDCODCOL,
BDREF,
BDORDEM,
BDBFGTS,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13)
 AS 
SELECT
  X.bdcodemp,
  X.bdcodcol, 
  X.bdref,
  X.bdordem,
  SUM(X.BDBFGTSFN) BDBFGTS,
  SUM(X.BDFGTSFN) BDFGTSFN,
  SUM(X.BDBFGTSFC) BDBFGTSFC,
  SUM(X.BDFGTSFC) BDFGTSFC,
  SUM(X.BDBASEFGTS13) BDBASEFGTS13,
  SUM(X.BDFGTS13) BDFGTS13,
  SUM(X.BDBASEFGTSA13) BDBASEFGTSA13,
  SUM(X.BDFGTSA13) BDFGTSA13,
  SUM(X.BDBASEFGTSC13) BDBASEFGTSC13,
  SUM(X.BDFGTSC13) BDFGTSC13
FROM VW_FGTS_FOLHA_TOMADOR X
GROUP BY X.bdcodemp, x.bdcodcol, x.bdref,  x.bdordem
;

/* CREATE OR ALTER VIEW: VW_FGTS_TOMADOR_FN_FC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_FGTS_TOMADOR_FN_FC(
BDTIPO,
BDCODEMP,
BDCODCOL,
BDREFFN,
BDCODCENTRO,
BDCODTPCC,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFE,
BDFGTSFE,
BDBFGTS13,
BDFGTS13)
 AS 
SELECT 0,x.bdcodemp,x.bdcodcol,x.bdreffn,x.bdcodcentro,x.bdcodtpcc,x.bdbfgtsfn,x.bdfgtsfn,X.bdbfgtsfefn,X.bdfgtsfefn,X.bdbfgts13fn,X.bdfgts13fn
FROM VRHF_SP_TFOLHA_NORMAL(NULL, NULL, NULL, NULL, 0) x
UNION
SELECT 1,y.bdcodemp,y.bdcodcol,y.BDREFCOMP,y.bdcodcentro,y.bdcodtpcc,y.bdbfgtsfc,y.bdfgtsfc,y.bdbfgtsfefc,y.bdfgtsfefc,y.bdbfgts13fc,y.bdfgts13fc
FROM vrhf_sp_tfolhacomp(NULL, NULL, NULL, NULL, NULL, NULL, 0) y
;

/* CREATE OR ALTER VIEW: VW_FICHA_FGTS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_FICHA_FGTS(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDBFGTSFN,
    BDFGTSFN,
    BDBFGTSFC,
    BDFGTSFC,
    BDBASEFGTS13,
    BDFGTS13,
    BDBASEFGTSA13,
    BDFGTSA13,
    BDBASEFGTSC13,
    BDFGTSC13,
    BDTIPO)
AS
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREF_FFGTS,
  case when X.BDTIPO_FFGTS not in (3, 4, 5, 7) then X.BDBFGTS_FFGTS else 0.00 end,
  case when X.BDTIPO_FFGTS not in (3, 4, 5, 7) then X.BDFGTS_FFGTS else 0.00 end,
  case when X.BDTIPO_FFGTS = 7 then X.BDBFGTS_FFGTS else 0.00 end,
  case when X.BDTIPO_FFGTS = 7 then X.BDFGTS_FFGTS else 0.00 end,
  case when X.BDTIPO_FFGTS = 4 then X.BDBFGTS_FFGTS else 0.00 end,
  case when X.BDTIPO_FFGTS = 4 then X.BDFGTS_FFGTS else 0.00 end,
  case when X.BDTIPO_FFGTS = 3 then X.BDBFGTS_FFGTS else 0.00 end,
  case when X.BDTIPO_FFGTS = 3 then X.BDFGTS_FFGTS else 0.00 end,
  case when X.BDTIPO_FFGTS = 5 then X.BDBFGTS_FFGTS else 0.00 end,
  case when X.BDTIPO_FFGTS = 5 then X.BDFGTS_FFGTS else 0.00 end,
  9 BDTIPO
FROM VRHF_EMP_TFICHAFGTS X
WHERE (X.BDTIPO_FFGTS = 1 AND -- Folha normal
  NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhanormal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREF_FFGTS) AND
       NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfolhatomador Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFTOMADOR = X.BDREF_FFGTS) AND
       NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhaint Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREF_FFGTS) AND
       NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfolhatomint Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFTOMADOR = X.BDREF_FFGTS))
      OR (X.BDTIPO_FFGTS = 3 AND -- Adiantamento de 13ºsalario
          NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_ta13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFA13 = X.BDREF_FFGTS))
      OR (X.BDTIPO_FFGTS = 4 AND -- 13 salario
          NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_t13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREF13 = X.BDREF_FFGTS))
      OR (X.BDTIPO_FFGTS = 5 AND -- Complemento de 13ºsalario
          NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tc13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFC13 = X.BDREF_FFGTS))

      OR (X.BDTIPO_FFGTS = 7 AND -- Folha complementar
  NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhacomp Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFCOMP = X.BDREF_FFGTS) AND
          NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfoltomcomp Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFCOMP = X.BDREF_FFGTS) AND
          NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhacompint Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFCOMP = X.BDREF_FFGTS) AND
          NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfoltomcompint Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFCOMP = X.BDREF_FFGTS))
/*
0              1         2              3            4                5            6                    7                            8      9           10          11                12
ccFolhaNormal, ccFerias, ccAd13Salario, cc13Salario, ccComp13Salario, ccAdSalario, ccFolhaComplementar, ccFolhaComplementarAgrupada, ccPLR, ccRescisao, ccSituacao, ccFeriasProvisao, cc13Provisao
*/
;

/* View: VW_UNION_FGTS_CC */
CREATE OR ALTER VIEW VW_UNION_FGTS_CC(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCODCENTRO,
    BDCODTPCC,
    BDBFGTSFN,
    BDFGTSFN,
    BDBFGTSFC,
    BDFGTSFC,
    BDBASEFGTS13,
    BDFGTS13,
    BDBASEFGTSA13,
    BDFGTSA13,
    BDBASEFGTSC13,
    BDFGTSC13,
    BDTIPO)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDCODCENTRO,
  BDCODTPCC,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_FOL_NORMAL_CC
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDCODCENTRO,
  BDCODTPCC,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_FOL_COMPLEMENTAR_CC
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDCODCENTRO,
  BDCODTPCC,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_A13_CC
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDCODCENTRO,
  BDCODTPCC,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_13S_CC
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDCODCENTRO,
  BDCODTPCC,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_C13_CC
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDCODCENTRO,
  BDCODTPCC,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_AVULSA_CC
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  cast(null as integer),
  cast(null as integer),
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM vw_ficha_fgts
;

/* CREATE OR ALTER VIEW: VW_FICHA_INSS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_FICHA_INSS(
BDCODEMP,
BDCODCOL,
BDREF,
BDBINSSFN,
BDINSSFN,
BDBASEINSS13,
BDINSS13,
BDBASEINSSC13,
BDINSSC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF_FINSS,
  BDBINSSN_FINSS,
  BDINSSN_FINSS,
  BDBINSS13_FINSS,
  BDINSS13_FINSS,
  BDBINSSC13_FINSS,
  BDINSSC13_FINSS,
  9 BDTIPO
FROM VRHF_EMP_TFICHAINSS
;

/* CREATE OR ALTER VIEW: VW_FICHA_IR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_FICHA_IR(
BDCODEMP,
BDCODCOL,
BDREF,
BDTIPOCALC,
BDBRUTO,
BDDEP,
BDVALIR,
BDVALINSS,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFIR,
  BDTIPOCALCFIR,
  BDBASEIRFIR,
  BDVALDEPFIR,
  BDVALIRFIR,
  BDVALINSSFIR,
  9 BDTIPO
FROM VRHF_EMP_TFICHAIR
;

/* CREATE OR ALTER VIEW: VW_FICHA_RAIS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_FICHA_RAIS(
BDCODEMP,
BDCODCOL,
BDREF,
BDBRAISFN,
BDBRAIS13,
BDBRAISA13,
BDBRAISC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFRAIS,
  BDRENDFRAIS,
  BD13FRAIS,
  BDA13FRAIS,
  BDC13FRAIS,
  9 BDTIPO
FROM VRHF_EMP_TFICHARAIS
;

CREATE OR ALTER VIEW VW_FICHA_RAIS2(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDBRAISFN,
    BDBRAIS13,
    BDBRAISA13,
    BDBRAISC13,
    BDTIPO)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFRAIS,
  BDRENDFRAIS,
  BD13FRAIS,
  0,
  BDC13FRAIS,
  9 BDTIPO
FROM VRHF_EMP_TFICHARAIS
;

CREATE OR ALTER VIEW VW_FICHA_RAIS_AD13(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDBRAISFN,
    BDBRAIS13,
    BDBRAISA13,
    BDBRAISC13,
    BDTIPO)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFRAIS,
  0,
  0,
  BDA13FRAIS,
  0,
  9 BDTIPO
FROM VRHF_EMP_TFICHARAIS
WHERE BDA13FRAIS IS NOT NULL AND BDA13FRAIS <> 0
;

/* CREATE OR ALTER VIEW: VW_HIST_AUM_SAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_HIST_AUM_SAL(
BDCODEMP,
BDCODCOL,
BDDATAHAUM,
BDCODMAS,
BDSALBASEHAUM,
BDSALBASEANTHAUM,
BDNOMEMP,
BDNOMCOL,
BDCODHAUM,
BDDATAEFEITOHAUM,
BDCONVCOLETIVA,
BDCODACCONV)
 AS 
SELECT
  HAUM.BDCODEMP,
  HAUM.BDCODCOL,
  HAUM.BDDATAHAUM,
  HAUM.BDCODMAS,
  HAUM.BDSALBASEHAUM,
  HAUM.BDSALBASEANTHAUM,
  EMPREF.BDNOMEMP,
  COLCAD.BDNOMCOL,
  HAUM.BDCODHAUM,
  HAUM.BDDATAEFEITOHAUM,
  HAUM.BDCONVCOLETIVA,
  HAUM.BDCODACCONV
FROM VRH_EMP_THIST_AUM HAUM
JOIN VW_TEMPRESAS_REF EMPREF ON HAUM.BDCODEMP = EMPREF.BDCODEMP
JOIN VRH_EMP_TCOLCON COL ON HAUM.BDCODEMP = COL.BDCODEMP AND HAUM.BDCODCOL = COL.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON COLCAD.BDCODEMP = COL.BDCODEMP AND COLCAD.BDCODCOL = COL.BDCODCOL
where HAUM.BDCODHAUM = (select max(BDCODHAUM)
                        from VRH_EMP_THIST_AUM
                        where BDCODEMP = HAUM.BDCODEMP and
                              BDCODCOL = HAUM.BDCODCOL and
                              BDDATAHAUM = HAUM.BDDATAHAUM and
                              BDDATAEFEITOHAUM = HAUM.BDDATAEFEITOHAUM and
                              BDSALBASEHAUM = HAUM.BDSALBASEHAUM and
                              BDSALBASEANTHAUM = HAUM.BDSALBASEANTHAUM)
;

--Sol. 18901 - Bruno L. R. - 05/07/2017 - Incluído o campo BDCODHAUMHE
/* CREATE OR ALTER VIEW: VW_HIST_AUMHE_SAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_HIST_AUMHE_SAL(
    BDCODEMP,
    BDCODCOL,
    BDCODSHE,
    BDDATAHAUMHE,
    BDCODMAS,
    BDSALBASEHAUMHE,
    BDSALBASEANTHAUMHE,
    BDNOMEMP,
    BDNOMCOL,
    BDDESCSHE,
    BDCODEMPHAUM,
    BDCODHAUMHE,         --Sol. 18901 - Bruno L. R. - 05/07/2017
    BDDATAEFEITOHAUMHE)    
AS
SELECT
  HAUM.BDCODEMP,
  HAUM.BDCODCOL,
  HAUM.BDCODSHE,
  HAUM.BDDATAHAUMHE,
  HAUM.BDCODMAS,
  HAUM.BDSALBASEHAUMHE,
  HAUM.BDSALBASEANTHAUMHE,
  EMPREF.BDNOMEMP,
  COLCAD.BDNOMCOL,
  CODSAL.BDDESCSHE,
  HAUM.BDCODEMPHAUM,
  HAUM.BDCODHAUMHE,   --Sol. 18901 - Bruno L. R. - 05/07/2017
  HAUM.BDDATAEFEITOHAUMHE
FROM VRH_EMP_THIST_AUMHE HAUM
JOIN VW_TEMPRESAS_REF EMPREF ON HAUM.BDCODEMP = EMPREF.BDCODEMP
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON HAUM.BDCODEMP = COLCAD.BDCODEMP AND HAUM.BDCODCOL = COLCAD.BDCODCOL
JOIN VRH_BASE_TSALHORESP CODSAL ON HAUM.BDCODEMP = CODSAL.BDCODEMP AND HAUM.BDCODSHE = CODSAL.BDCODSHE
;

/* CREATE OR ALTER VIEW: VW_INSS_13S (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_INSS_13S(
BDCODEMP,
BDCODCOL,
BDREF,
BDBINSSFN,
BDINSSFN,
BDBASEINSS13,
BDINSS13,
BDBASEINSSA13,
BDINSSA13,
BDBASEINSSC13,
BDINSSC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF13,
  0.0 BDBINSSFN,
  0.0 BDINSSFN,
  BDBASEINSS13,
  BDVALORINSS13,
  0.0 BDBASEINSSA13,
  0.0 BDINSSA13,
  0.0 BDBASEINSSC13,
  0.0 BDINSSC13,
  3 BDTIPO
FROM VRHF_EMP_T13SAL
;

/* CREATE OR ALTER VIEW: VW_INSS_C13 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_INSS_C13(
BDCODEMP,
BDCODCOL,
BDREF,
BDBINSSFN,
BDINSSFN,
BDBASEINSS13,
BDINSS13,
BDBASEINSSC13,
BDINSSC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFC13,
  0.0 BDBINSSFN,
  0.0 BDINSSFN,
  0.0 BDBASEINSS13,
  0.0 BDINSS13,
  BDBASEINSSC13,
  BDVALORINSSC13,
  4 BDTIPO
FROM VRHF_EMP_TC13SAL
;

/* CREATE OR ALTER VIEW: VW_INSS_FOL_COMPLEMENTAR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_INSS_FOL_COMPLEMENTAR(
BDCODEMP,
BDCODCOL,
BDREF,
BDBINSSFN,
BDINSSFN,
BDBASEINSS13,
BDINSS13,
BDBASEINSSC13,
BDINSSC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDBINSSFC + BDBINSS13FC,
  BDINSSFC + BDINSS13FC,
  0.0 BDBASEINSS13,
  0.0 BDINSS13,
  0.0 BDBASEINSSC13,
  0.0 BDINSSC13,
  1 BDTIPO
FROM VRHF_EMP_TFOLHACOMP
UNION
SELECT
  x.bdcodemp,
  x.bdcodcol,
  x.bdreftomador,
  SUM(x.bdbinssfc) + SUM(x.bdbinss13fc),
  SUM(x.bdinssfc) + SUM(x.bdbinss13fc),
  0.0 BDBASEINSS13,
  0.0 BDINSS13,
  0.0 BDBASEINSSC13,
  0.0 BDINSSC13,
  1 BDTIPO
FROM vrhf_emp_tfoltomcomp x
GROUP BY x.bdcodemp, x.bdcodcol, x.bdreftomador
;

/* CREATE OR ALTER VIEW: VW_INSS_FOL_NORMAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_INSS_FOL_NORMAL(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDBINSSFN,
    BDINSSFN,
    BDBASEINSS13,
    BDINSS13,
    BDBASEINSSC13,
    BDINSSC13,
    BDTIPO)
AS
SELECT
  Y.BDCODEMP,
  Y.BDCODCOL,
  Y.BDREFFN,
  Y.BDBINSSFN + Y.BDBINSS13FN,
  Y.BDINSSFN + Y.BDINSS13FN,
  0.0 BDBASEINSS13,
  0.0 BDINSS13,
  0.0 BDBASEINSSC13,
  0.0 BDINSSC13,
  0 BDTIPO
FROM VRHF_EMP_TFOLHANORMAL Y
UNION
SELECT
  x.bdcodemp,
  x.bdcodcol,
  x.bdreftomador,
  SUM(x.bdbinssft) + SUM(x.bdbinss13ft),
  SUM(x.bdinssft) + SUM(x.bdbinss13ft),
  0.0 BDBASEINSS13,
  0.0 BDINSS13,
  0.0 BDBASEINSSC13,
  0.0 BDINSSC13,
  0 BDTIPO
FROM vrhf_emp_tfolhatomador x
GROUP BY x.bdcodemp, x.bdcodcol, x.bdreftomador
UNION
SELECT
  Y.BDCODEMP,
  Y.BDCODCOL,
  Y.BDREFFN,
  SUM(Y.BDBINSSFN),
  SUM(Y.BDINSSFN),
  SUM(Y.BDBINSS13FN),
  SUM(Y.BDINSS13FN),
  0.0 BDBASEINSSC13,
  0.0 BDINSSC13,
  0 BDTIPO
FROM VRHF_EMP_TFOLHAINT Y
GROUP BY  Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN
UNION
SELECT
  x.bdcodemp,
  x.bdcodcol,
  x.bdreftomador,
  SUM(x.bdbinssft),
  SUM(x.bdinssft),
  SUM(x.bdbinss13ft),
  SUM(x.bdbinss13ft),
  0.0 BDBASEINSSC13,
  0.0 BDINSSC13,
  0 BDTIPO
FROM vrhf_emp_tfolhatomint x
GROUP BY x.bdcodemp, x.bdcodcol, x.bdreftomador
;

/* CREATE OR ALTER VIEW: VW_INT_SPEDICMS_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_INT_SPEDICMS_REF(
    BDCODEMP,
    BDCODIGO,
    BDREFERENCIA,
    BDTIPOEXPCODPART,
    BDEXP1400,
    BDTIPOEXPCONTA,
    BDREGD695,
    BDEXP1900,
    BDEXPINCENTFISCAIS,
    BDEXPSER,
    BDEXPE310,
    BDNAOEXPC173,
    BDEXP_REG_D300,
    BDGERARE115,
    BDGERAR1921,
    BDGERAR0221,
    BDNFCOM_CONSOLIDADA,
    BDSEMANAL)
AS
SELECT
    c.bdcodemp,
    c.bdcodigo,
    c.bdreferencia,
    c.bdtipoexpcodpart,
    c.BDEXP1400,
    c.BDTIPOEXPCONTA,
    c.BDREGD695,
    c.BDEXP1900,
    c.BDEXPINCENTFISCAIS,
    c.BDEXPSER,
    c.BDEXPE310,
    c.BDNAOEXPC173,
    c.BDEXP_REG_D300,
    c.BDGERARE115,
    c.BDGERAR1921,
    c.BDGERAR0221,
    c.BDNFCOM_CONSOLIDADA,
    c.BDSEMANAL
FROM
(SELECT p.bdcodemp,
        p.bdcodigo,
        p.bdreferencia,
        p.bdtipoexpcodpart,
        p.BDEXP1400,
        p.BDTIPOEXPCONTA,
        p.BDREGD695,
        p.BDEXP1900,
        p.BDEXPINCENTFISCAIS,
        P.BDEXPSER,
        P.BDEXPE310,
        P.BDNAOEXPC173,
        P.BDEXP_REG_D300,
        P.BDGERARE115,
        P.BDGERAR1921,
        P.BDGERAR0221,
        P.BDNFCOM_CONSOLIDADA,
        P.BDSEMANAL
FROM vef_int_tspedicms p
WHERE p.bdreferencia = (SELECT FIRST 1 ref.bdreferencia
                        FROM vef_int_tspedicms ref
                        WHERE ref.bdcodemp = p.bdcodemp
                          AND ref.bdreferencia <= (COALESCE(
                                                      (SELECT MAX(r1.bdreferencia) FROM vef_int_tspedicms r1 WHERE r1.bdcodemp = p.bdcodemp AND r1.bdreferencia <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
                                                      (SELECT MIN(r2.bdreferencia) FROM vef_int_tspedicms r2 WHERE r2.bdcodemp = p.bdcodemp)
                                                  ))
                        ORDER BY ref.bdreferencia DESC)
GROUP BY p.bdcodemp, p.bdcodigo, p.bdreferencia,  p.bdtipoexpcodpart, p.BDEXP1400, p.BDTIPOEXPCONTA, p.BDREGD695, P.BDEXP1900, P.BDEXPINCENTFISCAIS, P.BDEXPSER, P.BDEXPE310, P.BDNAOEXPC173, P.BDEXP_REG_D300, P.BDGERARE115, P.BDGERAR1921, P.BDGERAR0221, P.BDNFCOM_CONSOLIDADA, P.BDSEMANAL
) c
;

/* CREATE OR ALTER VIEW: VW_INT_SPEDPISCOFINS_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_INT_SPEDPISCOFINS_REF(
    BDCODEMP,
    BDCODIGO,
    BDINCTRIB,
    BDMETODOAPRO,
    BDTPCONTAPU,
    BDSOMENTEBLOCOP,
    BDEXPNFCOMVALENT,
    BDEXPNFCOMVALSAI,
    BDCODCRIT,
    BDCODCRITEXP,
    BDREFERENCIA,
    BDNAOEXPORTARPF,
    BDDESONREDZPERFILB,
    BDRBNCUMTRIBMI,
    BDRBNCUMNTMI,
    BDRBNCUMEXP,
    BDRBCUM,
    BDRETPISCOFPERANT,
    BDCREDITOSPERANT,
    BDSEMDADOS,
    BDINFCOMP,
    BDCREDITODEV,
    BDF525RECEITAF500,
    BDF550TOTCST,
    BDCONTACONTABF120,
    BDEXPCONTACONTAB,
    BDNAOCRED5ANOS,
    BDEXPCPFCNPJA100,
    BDEXPORTAPORSCP,
    BDCONTROLCRED,
    BDCREDANTERIOR,
    BDABATERESSARCIM,
    BDORDENACRED,
    BDNAOUTILIZARCRE,
    BDNAOUTILIZARCRED_201_208)
AS
SELECT
    c.bdcodemp,
    i.bdcodigo,
    i.bdinctrib,
    i.bdmetodoapro,
    i.bdtpcontapu,
    i.bdsomenteblocop,
    i.bdexpnfcomvalent,
    i.bdexpnfcomvalsai,
    i.bdcodcrit,
    t.bdcodcritexp,
    c.bdreferencia,
    i.bdnaoexportarpf,
    i.bddesonredzperfilb,
    i.BDRBNCUMTRIBMI,
    i.BDRBNCUMNTMI,
    i.BDRBNCUMEXP,
    i.BDRBCUM,
    i.BDRETPISCOFPERANT,
    i.BDCREDITOSPERANT,
    i.BDSEMDADOS,
    i.BDINFCOMP,
    i.BDCREDITODEV,
    i.BDF525RECEITAF500,
    i.BDF550TOTCST,
    i.BDCONTACONTABF120   ,
    i.BDEXPCONTACONTAB    ,
    i.BDNAOCRED5ANOS,
    i.BDEXPCPFCNPJA100,
    i.BDEXPORTAPORSCP,
    i.BDCONTROLCRED,
    i.BDCREDANTERIOR,
    i.BDABATERESSARCIM,
    i.BDORDENACRED,
    i.BDNAOUTILIZARCRE,
    i.BDNAOUTILIZARCRED_201_208
FROM
(
SELECT p.bdcodemp,
       COALESCE
       (
           (SELECT MAX(r1.bdreferencia) FROM vef_int_tsped_pis_cofins r1 WHERE r1.bdcodemp = p.bdcodemp AND r1.bdreferencia <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
           (SELECT MIN(r2.bdreferencia) FROM vef_int_tsped_pis_cofins r2 WHERE r2.bdcodemp = p.bdcodemp)
       ) AS "BDREFERENCIA"
FROM vef_int_tsped_pis_cofins p
GROUP BY p.bdcodemp
) c
INNER JOIN vef_int_tsped_pis_cofins i ON i.bdcodemp = c.bdcodemp AND i.bdreferencia = c.bdreferencia
LEFT OUTER JOIN VEF_BASE_TTABCRITESCRIT t ON (t.bdcodcrit = i.bdcodcrit);


CREATE OR ALTER VIEW VW_INT_SPEDICMSREF19_REF(
    BDCODEMP,
    BDREG,
    BDCODSUBAPU,
    BDVIGINICIAL,
    BDVIGFINAL)
AS
SELECT C.BDCODEMP, 'PE01' BDREG, C.BDCODSUBAPU, C.BDVIGINICIAL, C.BDVIGFINAL
FROM (
select ICMS.BDCODEMP,ICMS.BDCODIGO, ICMS.BDEXPINCENTFISCAIS
from VW_INT_SPEDICMS_REF ICMS
WHERE ICMS.BDEXPINCENTFISCAIS = 'TRUE'
) SPED
JOIN VEF_INT_TSPEDICMSCONF1960 C ON (C.BDCODEMP = SPED.BDCODEMP AND C.BDCODIGO = SPED.BDCODIGO)
UNION ALL
SELECT C.BDCODEMP,'PE03' BDREG, C.BDCODSUBAPU, C.BDVIGINICIAL, C.BDVIGFINAL
FROM (
select ICMS.BDCODEMP,ICMS.BDCODIGO, ICMS.BDEXPINCENTFISCAIS
from VW_INT_SPEDICMS_REF ICMS
WHERE ICMS.BDEXPINCENTFISCAIS = 'TRUE'
) SPED
JOIN VEF_INT_TSPEDICMSCONF1970 C ON (C.BDCODEMP = SPED.BDCODEMP AND C.BDCODIGO = SPED.BDCODIGO)
UNION ALL
SELECT C.BDCODEMP, 'PE04' BDREG, C.BDCODSUBAPU, C.BDVIGINICIAL, C.BDVIGFINAL
FROM (
select ICMS.BDCODEMP,ICMS.BDCODIGO, ICMS.BDEXPINCENTFISCAIS
from VW_INT_SPEDICMS_REF ICMS
WHERE ICMS.BDEXPINCENTFISCAIS = 'TRUE'
) SPED
JOIN VEF_INT_TSPEDICMSCONF1980 C ON (C.BDCODEMP = SPED.BDCODEMP AND C.BDCODIGO = SPED.BDCODIGO);


/* CREATE OR ALTER VIEW: VW_IR_13_FOL_NORMAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_IR_13_FOL_NORMAL(
BDCODEMP,
BDCODCOL,
BDREF,
BDTIPOCALC,
BDBRUTO,
BDDEP,
BDVALIR,
BDVALINSS,
BDTIPO)
 AS 
SELECT
  Y.BDCODEMP,
  Y.BDCODCOL,
  Y.BDREFFN,
  1 BDTIPOCALC,
  Y.BDBIRRF13FN,
  Y.BDDEPFN,
  Y.BDIRRF13FN,
  Y.BDINSS13FN,
  0 BDTIPO
FROM VRHF_EMP_TFOLHANORMAL Y
UNION
SELECT
  x.bdcodemp,
  x.bdcodcol,
  x.bdreftomador,
  1 BDTIPOCALC,
  SUM(x.BDBIRRF13FT),
  SUM(x.bddepft),
  SUM(x.BDIRRF13FT),
  SUM(x.BDINSS13FT),
  0 BDTIPO
FROM vrhf_emp_tfolhatomador x
GROUP BY x.BDCODEMP, x.BDCODCOL, x.bdreftomador
;

/* CREATE OR ALTER VIEW: VW_IR_13S (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_IR_13S(
BDCODEMP,
BDCODCOL,
BDREF,
BDTIPOCALC,
BDBRUTO,
BDDEP,
BDVALIR,
BDVALINSS,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  EXTRACT(YEAR FROM BDDATAPGTO13)||SUBSTRING(BDDATAPGTO13 FROM 6 FOR 2) BDREF13,
  4 BDTIPOCALC,
  BDBASEIR13,
  BDDEP13,
  BDVALORIR13,
  BDVALORINSS13,
  3 BDTIPO
FROM VRHF_EMP_T13SAL
;

/* CREATE OR ALTER VIEW: VW_IR_AD_SALARIO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_IR_AD_SALARIO(
BDCODEMP,
BDCODCOL,
BDREF,
BDTIPOCALC,
BDBRUTO,
BDDEP,
BDVALIR,
BDVALINSS,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  EXTRACT(YEAR FROM BDDATAAD)||SUBSTRING(BDDATAAD FROM 6 FOR 2) BDREFFN,
  2 BDTIPOCALC,
  BDBASEIRAD,
  BDDEPIRAD,
  BDVALORIRAD,
  0.0,
  2 BDTIPO
FROM VRHF_EMP_TADSAL
;

/* CREATE OR ALTER VIEW: VW_IR_C13 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_IR_C13(
BDCODEMP,
BDCODCOL,
BDREF,
BDTIPOCALC,
BDBRUTO,
BDDEP,
BDVALIR,
BDVALINSS,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  EXTRACT(YEAR FROM BDDATAPGTOC13)||SUBSTRING(BDDATAPGTOC13 FROM 6 FOR 2) BDREFC13,
  5 BDTIPOCALC,
  BDBASEIRC13,
  BDDEPC13,
  BDVALORIRC13,
  BDVALORINSSC13,
  4 BDTIPO
FROM VRHF_EMP_TC13SAL
;

/* CREATE OR ALTER VIEW: VW_IR_FERIAS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_IR_FERIAS(
BDCODEMP,
BDCODCOL,
BDREF,
BDTIPOCALC,
BDBRUTO,
BDDEP,
BDVALIR,
BDVALINSS,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  EXTRACT(YEAR FROM BDDATAPAGFE)||SUBSTRING(BDDATAPAGFE FROM 6 FOR 2)  BDREFFE,
  6 BDTIPOCALC,
  BDBASEIRFE,
  BDDEPFE,
  BDVALORIRFE,
  BDVALORINSSFE,
  7 BDTIPO
FROM VRH_EMP_TFERIAS
;

/* CREATE OR ALTER VIEW: VW_IR_FOL_COMPLEMENTAR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_IR_FOL_COMPLEMENTAR(
BDCODEMP,
BDCODCOL,
BDREF,
BDTIPOCALC,
BDBRUTO,
BDDEP,
BDVALIR,
BDVALINSS,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  EXTRACT(YEAR FROM BDDATAPAGFC)||SUBSTRING(BDDATAPAGFC FROM 6 FOR 2) BDREFFN,
  1 BDTIPOCALC,
  BDBIRRFFC,
  BDDEPFC,
  BDIRRFFC,
  BDINSSFC,
  1 BDTIPO
FROM VRHF_EMP_TFOLHACOMP
UNION
SELECT
  x.bdcodemp,
  x.bdcodcol,
  EXTRACT(YEAR FROM BDDATAPAGFC)||SUBSTRING(BDDATAPAGFC FROM 6 FOR 2) BDREFFN,
  1 BDTIPOCALC,
  SUM(x.bdbirrffc),
  SUM(x.bddepfc),
  SUM(x.bdirrffc),
  SUM(x.bdinssfc),
  1 BDTIPO
FROM vrhf_emp_tfoltomcomp x
GROUP BY x.BDCODEMP, x.BDCODCOL, BDREFFN
;

/* CREATE OR ALTER VIEW: VW_IR_FOL_NORMAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_IR_FOL_NORMAL(
BDCODEMP,
BDCODCOL,
BDREF,
BDTIPOCALC,
BDBRUTO,
BDDEP,
BDVALIR,
BDVALINSS,
BDTIPO)
 AS 
SELECT
  Y.BDCODEMP,
  Y.BDCODCOL,
  EXTRACT(YEAR FROM BDDATAPGTOFN)||SUBSTRING(BDDATAPGTOFN FROM 6 FOR 2) BDREFFN,
  1 BDTIPOCALC,
  Y.BDBIRRFFN,
  Y.BDDEPFN,
  Y.BDIRRFFN,
  Y.BDINSSFN,
  0 BDTIPO
FROM VRHF_EMP_TFOLHANORMAL Y
UNION
SELECT
  x.bdcodemp,
  x.bdcodcol,
  EXTRACT(YEAR FROM BDDATAPGTOFT)||SUBSTRING(BDDATAPGTOFT FROM 6 FOR 2) BDREFFN,
  1 BDTIPOCALC,
  SUM(x.bdbirrfft),
  SUM(x.bddepft),
  SUM(x.bdirrfft),
  SUM(x.bdinssft),
  0 BDTIPO
FROM vrhf_emp_tfolhatomador x
GROUP BY x.BDCODEMP, x.BDCODCOL, BDREFFN
;

/* CREATE OR ALTER VIEW: VW_PRIVILEGIO_EMPRESA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_PRIVILEGIO_EMPRESA(
BDCODEMP,
BDCODGRUPO,
BDCODUSU,
BDITEMPRIV)
 AS 
SELECT temp.bdcodemp, temp.bdcodgrupo,
       tgrp.bdcodusu,
       tpriv.bditempriv
FROM tempresa_grupousuario temp
INNER JOIN tgrupousuario_usuario tgrp ON (tgrp.bdcodgrupo = temp.bdcodgrupo AND tgrp.bdcodusu = (SELECT x.bdcodusu FROM sp_get_usuario x))
INNER JOIN tprivilegio_grupousuario tpriv ON (tpriv.bdcodgrupo = tgrp.bdcodgrupo )
WHERE temp.bdcodemp = CASE WHEN ((SELECT COUNT(bdcodusu) FROM tempresa_usuario WHERE bdcodusu = (SELECT bdcodusu FROM sp_get_usuario)) = 0) THEN temp.bdcodemp
                           WHEN ((SELECT bdcodemp FROM tempresa_usuario WHERE bdcodusu = (SELECT bdcodusu FROM sp_get_usuario) AND bdcodemp = temp.bdcodemp) IS NOT NULL) THEN temp.bdcodemp END
;

/* CREATE OR ALTER VIEW: VW_PROTOCOLOENTRADA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_PROTOCOLOENTRADA(
BDCODEMP,
BDCODPTE,
BDCODIPTE,
BDDESCRICAO)
 AS 
SELECT prot.BDCODEMP, pdoc.BDCODPTE, pdoc.BDCODIPTE, doc.BDDESCRICAO
FROM VCT_EMPRESA_PROTODOCENTRADA pdoc
INNER JOIN VCT_EMPRESA_PROTOCOLOENTRADA prot ON ((prot.BDCODPTE = pdoc.BDCODPTE) AND (prot.BDCODEMP = pdoc.BDCODEMP))
INNER JOIN VCT_BASE_DOCUMENTO doc ON (pdoc.BDCODDOC = doc.BDCODDOC)
;

/* CREATE OR ALTER VIEW: VW_RAIS_13S (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_RAIS_13S(
BDCODEMP,
BDCODCOL,
BDREF,
BDBRAISFN,
BDBRAIS13,
BDBRAISA13,
BDBRAISC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF13,
  0.0 BDBRAISFN,
  BDBRAIS13,
  0.0 BDBRAISA13,
  0.0 BDBRAISC13,
  3 BDTIPO
FROM VRHF_EMP_T13SAL
;

/* CREATE OR ALTER VIEW: VW_RAIS_A13 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_RAIS_A13(
BDCODEMP,
BDCODCOL,
BDREF,
BDBRAISFN,
BDBRAIS13,
BDBRAISA13,
BDBRAISC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFA13,
  0.0 BDBRAISFN,
  0.0 BDBRAIS13,
  case when coalesce(BDCALCFERA13, 'FALSE') = 'FALSE' then BDBRAISA13 else 0.0 end BDCALCFERA13,
  0.0 BDBRAISC13,
  2 BDTIPO
FROM VRHF_EMP_TA13SAL
;

/* CREATE OR ALTER VIEW: VW_RAIS_C13 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_RAIS_C13(
BDCODEMP,
BDCODCOL,
BDREF,
BDBRAISFN,
BDBRAIS13,
BDBRAISA13,
BDBRAISC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFC13,
  0.0 BDBRAISFN,
  0.0 BDBRAIS13,
  0.0 BDBRAISA13,
  BDBRAISC13,
  4 BDTIPO
FROM VRHF_EMP_TC13SAL
;

/* CREATE OR ALTER VIEW: VW_RAIS_FOL_AVULSA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_RAIS_FOL_AVULSA(
BDCODEMP,
BDCODCOL,
BDREF,
BDBRAISFN,
BDBRAIS13,
BDBRAISA13,
BDBRAISC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  CAST((SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) BDREFFA,
  SUM(BDBRAISFA),
  0.0 BDBRAIS13,
  0.0 BDBRAISA13,
  0.0 BDBRAISC13,
  5 BDTIPO
FROM VRHF_EMP_TFOLHAAVULSA
GROUP BY BDCODEMP,BDCODCOL,BDREFFA
;

/* CREATE OR ALTER VIEW: VW_RAIS_FOL_COMPLEMENTAR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_RAIS_FOL_COMPLEMENTAR(
BDCODEMP,
BDCODCOL,
BDREF,
BDBRAISFN,
BDBRAIS13,
BDBRAISA13,
BDBRAISC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDBRAISFC,
  0.0 BDBRAIS13,
  0.0 BDBRAISA13,
  0.0 BDBRAISC13,
  1 BDTIPO
FROM VRHF_EMP_TFOLHACOMP
UNION
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.bdreftomador,
  SUM(X.bdbraisfc),
  0.0 BDBRAIS13,
  0.0 BDBRAISA13,
  0.0 BDBRAISC13,
  0 BDTIPO
FROM vrhf_emp_tfoltomcomp x
GROUP BY x.BDCODEMP, x.BDCODCOL, x.bdreftomador
;

/* CREATE OR ALTER VIEW: VW_RAIS_FOL_COMPLEMENTAR_DETR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_RAIS_FOL_COMPLEMENTAR_DETR(
BDCODEMP,
BDCODCOL,
BDREF,
BDDATAENT,
BDCODCENTO,
BDCODTPCC,
BDBRAISFN,
BDBRAIS13,
BDBRAISA13,
BDBRAISC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  CAST(NULL AS DATE) BDDATAENT,
  CAST(NULL AS INTEGER) BDCODCENTO,
  CAST(NULL AS INTEGER) BDCODTPCC,
  BDBRAISFC,
  0.0 BDBRAIS13,
  0.0 BDBRAISA13,
  0.0 BDBRAISC13,
  1 BDTIPO
FROM VRHF_EMP_TFOLHACOMP
UNION
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.bdreftomador,
  cc.bddataentrada BDDATAENT,
  cc.bdcodcentro BDCODCENTO,
  cc.bdcodtpcc BDCODTPCC,
  X.bdbraisfc,
  0.0 BDBRAIS13,
  0.0 BDBRAISA13,
  0.0 BDBRAISC13,
  0 BDTIPO
FROM vrhf_emp_tfoltomcomp x
JOIN VRHF_EMP_TPREPFN cc ON (x.bdcodemp = cc.bdcodemp AND  x.bdcodcol = cc.bdcodcol AND x.bdordem = cc.bdordem)
;

/* CREATE OR ALTER VIEW: VW_RAIS_FOL_NORMAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_RAIS_FOL_NORMAL(
BDCODEMP,
BDCODCOL,
BDREF,
BDBRAISFN,
BDBRAIS13,
BDBRAISA13,
BDBRAISC13,
BDTIPO)
 AS 
SELECT
  Y.BDCODEMP,
  Y.BDCODCOL,
  Y.BDREFFN,
  Y.BDBRAISFN,
  0.0 BDBRAIS13,
  0.0 BDBRAISA13,
  0.0 BDBRAISC13,
  0 BDTIPO
FROM VRHF_EMP_TFOLHANORMAL Y
UNION
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.bdreftomador,
  SUM(X.bdbraisft),
  0.0 BDBRAIS13,
  0.0 BDBRAISA13,
  0.0 BDBRAISC13,
  0 BDTIPO
FROM vrhf_emp_tfolhatomador x
GROUP BY x.BDCODEMP, x.BDCODCOL, x.bdreftomador
;

/* CREATE OR ALTER VIEW: VW_RAIS_FOL_NORMAL_DETR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_RAIS_FOL_NORMAL_DETR(
BDCODEMP,
BDCODCOL,
BDREF,
BDDATAENT,
BDCODCENTO,
BDCODTPCC,
BDBRAISFN,
BDBRAIS13,
BDBRAISA13,
BDBRAISC13,
BDTIPO)
 AS 
SELECT
  Y.BDCODEMP,
  Y.BDCODCOL,
  Y.BDREFFN,
  CAST(NULL AS DATE) BDDATAENT,
  CAST(NULL AS INTEGER) BDCODCENTO,
  CAST(NULL AS INTEGER) BDCODTPCC,
  Y.BDBRAISFN,
  0.0 BDBRAIS13,
  0.0 BDBRAISA13,
  0.0 BDBRAISC13,
  0 BDTIPO
FROM VRHF_EMP_TFOLHANORMAL Y
UNION
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.bdreftomador,
  cc.bddataentrada BDDATAENT,
  cc.bdcodcentro BDCODCENTO,
  cc.bdcodtpcc BDCODTPCC,
  X.bdbraisft,
  0.0 BDBRAIS13,
  0.0 BDBRAISA13,
  0.0 BDBRAISC13,
  0 BDTIPO
FROM vrhf_emp_tfolhatomador x
JOIN VRHF_EMP_TPREPFN cc ON (x.bdcodemp = cc.bdcodemp AND  x.bdcodcol = cc.bdcodcol AND x.bdordem = cc.bdordem)
;

CREATE OR ALTER VIEW VW_RAIS_FOL_NORMAL(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDBRAISFN,
    BDBRAIS13,
    BDBRAISA13,
    BDBRAISC13,
    BDTIPO)
AS
SELECT
  Y.BDCODEMP,
  Y.BDCODCOL,
  Y.BDREFFN,
  Y.BDBRAISFN,
  0.0 BDBRAIS13,
  0.0 BDBRAISA13,
  0.0 BDBRAISC13,
  0 BDTIPO
FROM VRHF_EMP_TFOLHANORMAL Y
UNION
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.bdreftomador,
  SUM(X.bdbraisft),
  0.0 BDBRAIS13,
  0.0 BDBRAISA13,
  0.0 BDBRAISC13,
  0 BDTIPO
FROM vrhf_emp_tfolhatomador x
GROUP BY x.BDCODEMP, x.BDCODCOL, x.bdreftomador
;

/* CREATE OR ALTER VIEW: VW_UNIONREC_IR_PIS_COFINS_CSLL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNIONREC_IR_PIS_COFINS_CSLL(
BDCODEMP,
BDCODREC,
BDREFLAN,
BDVLRCONTAB,
BDACREDEDUIRSER,
BDVLRIMPOSTO,
BDTIPIMPOSTO,
BDTIPLAN,
BDCODTER,
BDCHAVE,
BDCODRECOF)
 AS 
SELECT ser.bdcodemp,
       seritens.bdcodrec,
       ser.bdreflan,
       seritens.bdvlrcontab,
       seritens.bdacrededuirser,
       seritens.bdvlrirser vlrimposto,
       codrec.bdtipoimposto,
       ser.bdtiplan,
       ser.bdcodter,
       ser.bdchave,
       CODREC.BDCODRECOF
FROM ( SELECT bdcodemp,bdchave,bdcodter,bdtiplan,bdreflan FROM vef_emp_tmovser WHERE bdcodsitnf NOT IN (2,3,4,5) ) ser
LEFT OUTER JOIN vef_emp_tmovseritens seritens ON (seritens.bdcodemp = ser.bdcodemp AND seritens.bdchave = ser.bdchave)
LEFT OUTER JOIN tcodrec codrec ON (codrec.bdcodrec = seritens.bdcodrec)

UNION ALL

SELECT ser.bdcodemp,
       serret.bdcodrecpis,
       ser.bdreflan,
       seritens.bdvlrcontab,
       seritens.bdacrededuirser,
       serret.bdvlrpis,
       codrec.bdtipoimposto,
       ser.bdtiplan,
       ser.bdcodter,
       ser.bdchave,
       CODREC.BDCODRECOF

FROM ( SELECT bdcodemp,bdchave,bdcodter,bdtiplan,bdreflan FROM vef_emp_tmovser WHERE bdcodsitnf NOT IN (2,3,4,5) ) ser
LEFT OUTER JOIN vef_emp_tmovseritens seritens ON (seritens.bdcodemp = ser.bdcodemp AND seritens.bdchave = ser.bdchave)
LEFT OUTER JOIN vef_emp_tmovserret serret ON (serret.bdcodemp = seritens.bdcodemp AND serret.bdchave = seritens.bdchave)
LEFT OUTER JOIN tcodrec codrec ON (codrec.bdcodrec = serret.bdcodrecpis)

UNION ALL

SELECT ser.bdcodemp,
       serret.bdcodreccofins,
       ser.bdreflan,
       seritens.bdvlrcontab,
       seritens.bdacrededuirser,
       serret.bdvlrcofins,
       codrec.bdtipoimposto,
       ser.bdtiplan,
       ser.bdcodter,
       ser.bdchave,
       CODREC.BDCODRECOF
FROM ( SELECT bdcodemp,bdchave,bdcodter,bdtiplan,bdreflan FROM vef_emp_tmovser WHERE bdcodsitnf NOT IN (2,3,4,5) ) ser
LEFT OUTER JOIN vef_emp_tmovseritens seritens ON (seritens.bdcodemp = ser.bdcodemp AND seritens.bdchave = ser.bdchave)
LEFT OUTER JOIN vef_emp_tmovserret serret ON (serret.bdcodemp = seritens.bdcodemp AND serret.bdchave = seritens.bdchave)
LEFT OUTER JOIN tcodrec codrec ON (codrec.bdcodrec = serret.bdcodreccofins)

UNION ALL

SELECT ser.bdcodemp,
       serret.bdcodreccsocial,
       ser.bdreflan,
       seritens.bdvlrcontab,
       seritens.bdacrededuirser,
       serret.bdvlrcsocial,
       codrec.bdtipoimposto,
       ser.bdtiplan,
       ser.bdcodter,
       ser.bdchave,
       CODREC.bdcodrecof

FROM ( SELECT bdcodemp,bdchave,bdcodter,bdtiplan,bdreflan FROM vef_emp_tmovser WHERE bdcodsitnf NOT IN (2,3,4,5) ) ser
LEFT OUTER JOIN vef_emp_tmovseritens seritens ON (seritens.bdcodemp = ser.bdcodemp AND seritens.bdchave = ser.bdchave)
LEFT OUTER JOIN vef_emp_tmovserret serret ON (serret.bdcodemp = seritens.bdcodemp AND serret.bdchave = seritens.bdchave)
LEFT OUTER JOIN tcodrec codrec ON (codrec.bdcodrec = serret.bdcodreccsocial)
;

/* CREATE OR ALTER VIEW: VW_REC_IR_PIS_COFINS_CSLL_AUX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_REC_IR_PIS_COFINS_CSLL_AUX(
BDCODEMP,
BDCODREC,
BDREFLAN,
BDVLRCONTAB,
BDACREDEDUIRSER,
BDVLRIMPOSTO,
BDTIPIMPOSTO,
BDTIPLAN,
BDCODTER,
BDCHAVE,
BDCODRECOF)
 AS 
SELECT BDCODEMP,
       BDCODREC,
       BDREFLAN,
       BDVLRCONTAB,
       BDACREDEDUIRSER,
       SUM(BDVLRIMPOSTO),
       BDTIPIMPOSTO,
       BDTIPLAN,
       BDCODTER,
       BDCHAVE,
       BDCODRECOF
FROM VW_UNIONREC_IR_PIS_COFINS_CSLL
GROUP BY BDCODEMP,
       BDCODREC,
       BDREFLAN,
       BDVLRCONTAB,
       BDACREDEDUIRSER,
       BDTIPIMPOSTO,
       BDTIPLAN,
       BDCODTER,
       BDCHAVE,
       BDCODRECOF
;

/* CREATE OR ALTER VIEW: VW_RELACIONAMENTO_GERADOR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_RELACIONAMENTO_GERADOR(
BDPRINCIPAL,
BDCAMPOSDE,
BDDESCP,
BDDEPENDENTE,
BDCAMPOSPARA,
BDDESCD)
 AS 
SELECT * FROM (
SELECT r.bdprincipal bdprincipal,r.bdcamposde bdcamposde, p.bddescricao bddescp, r.bddependente bddependente,r.bdcampospara bdcampospara, d.bddescricao bddescd
FROM TGR_RELACIONAMENTO_TABELAS r
JOIN ttabelagerador p ON (r.bdprincipal = p.bdcodtabger)  JOIN ttabelagerador d ON (r.bddependente = d.bdcodtabger)
)
ORDER BY bdprincipal,bddependente
;

/* CREATE OR ALTER VIEW: VW_RESCISAO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_RESCISAO(
    BDCODEMP,
    BDCODCOL,
    BDCODPRES,
    BDNOVOCODPRES,
    BDDATARESCISAO,
    BDNOVADATARESCISAO,
    BDDATAAVPREVIO,
    BDDATAHOM,
    BDDATAPAGRESCISAO,
    BDSALDOFGTS,
    BDCALCFGTSMESANT,
    BDMAIORREMUNERACAO,
    BDCHAVEINDENTIFICACAO,
    BDDATAPAGGRFC,
    BDREPOSICAOVAGA,
    BDDISSIDIO,
    BDDATADISSIDIO,
    BDDESCANSOINDENIZADO,
    BDCODMFG,
    BDCODSAQUE,
    BDCODMRAIS,
    BDCODMCAG,
    BDDESCPRES,
    BDINIPRES,
    BDJCPRES,
    BDAVPREPRES,
    BDGRRFPRES,
    BDESTPRES,
    BDINDFER13,
    BDTERMCONTRPRES,
    BDMULTAPRES,
    BDDIASAVPREPRES,
    BDDIASPAGPRES,
    BDCODSEFMFG,
    BDDESCMFG,
    BDDESCSAQUE,
    BDDESCMRAIS,
    BDDESCMCAGED,
    BDDATANOTIF,
    BDDIASINDENIZADOS,
    BDDIASTRABALHADOS,
    BDPERCMULTAFGTS,
    BDPERCMULTAFGTSCS,
    BDPROJECAOAVISO)
AS
SELECT
  RESC.BDCODEMP, RESC.BDCODCOL, RESC.BDCODPRES, RESC.BDNOVOCODPRES,  RESC.BDDATARESCISAO, RESC.BDNOVADATARESCISAO, RESC.BDDATAAVPREVIO, RESC.BDDATAHOM, RESC.BDDATAPAGRESCISAO,
  RESC.BDSALDOFGTS, RESC.BDCALCFGTSMESANT, RESC.BDMAIORREMUNERACAO, RESC.BDCHAVEINDENTIFICACAO,
  RESC.BDDATAPAGGRFC, RESC.BDREPOSICAOVAGA, RESC.BDDISSIDIO, RESC.BDDATADISSIDIO, RESC.BDDESCANSOINDENIZADO,
  
  PRESC.BDCODMFG, PRESC.BDCODSAQUE, PRESC.BDCODMRAIS, PRESC.BDCODMCAG, PRESC.BDDESCPRES, PRESC.BDINIPRES,
  PRESC.BDJCPRES, PRESC.BDAVPREPRES, PRESC.BDGRRFPRES, PRESC.BDESTPRES, PRESC.BDINDFER13, PRESC.BDTERMCONTRPRES,
  PRESC.BDMULTAPRES, PRESC.BDDIASAVPREPRES, PRESC.BDDIASPAGPRES,
  MFGTS.BDCODSEFMFG, MFGTS.BDDESCMFG,
  SAQUE.BDDESCSAQUE,
  RAIS.BDDESCMRAIS,
  CAGED.BDDESCMCAGED,
  
  resc.bddatanotif,
  resc.bddiasindenizados, resc.bddiastrabalhados,
  PRESC.bdpercmultafgts, PRESC.bdpercmultafgtscs,
  resc.bdprojecaoaviso
FROM VRH_EMP_TRESCISAO RESC
LEFT OUTER JOIN VRH_BASE_TPREPRESC PRESC ON (COALESCE(RESC.bdnovocodpres, RESC.BDCODPRES) = PRESC.BDCODPRES)
LEFT OUTER JOIN VRH_BASE_TMOTFGTS MFGTS ON (PRESC.BDCODMFG = MFGTS.BDCODMFG)
LEFT OUTER JOIN VRH_BASE_TSAQUE  SAQUE ON (PRESC.BDCODSAQUE = SAQUE.BDCODSAQUE)
LEFT OUTER JOIN VRH_BASE_TMOTRAIS RAIS ON (PRESC.BDCODMRAIS = RAIS.BDCODMRAIS)
LEFT OUTER JOIN VRH_BASE_TMOTCAGED CAGED ON (PRESC.BDCODMCAG = CAGED.BDCODMCAG)
;


/* CREATE OR ALTER VIEW: VW_RESCISAO_PREVIA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_RESCISAO_PREVIA(
    BDCODEMP,
    BDCODCOL,
    BDCODPRES,
    BDDATARESCISAO,
    BDDATAAVPREVIO,
    BDDATAHOM,
    BDDATAPAGRESCISAO,
    BDSALDOFGTS,
    BDCALCFGTSMESANT,
    BDMAIORREMUNERACAO,
    BDCHAVEINDENTIFICACAO,
    BDDATAPAGGRFC,
    BDREPOSICAOVAGA,
    BDDISSIDIO,
    BDDATADISSIDIO,
    BDDESCANSOINDENIZADO,
    BDCODMFG,
    BDCODSAQUE,
    BDCODMRAIS,
    BDCODMCAG,
    BDDESCPRES,
    BDINIPRES,
    BDJCPRES,
    BDAVPREPRES,
    BDGRRFPRES,
    BDESTPRES,
    BDINDFER13,
    BDTERMCONTRPRES,
    BDMULTAPRES,
    BDDIASAVPREPRES,
    BDDIASPAGPRES,
    BDCODSEFMFG,
    BDDESCMFG,
    BDDESCSAQUE,
    BDDESCMRAIS,
    BDDESCMCAGED,
    BDPERCMULTAFGTS,
    BDPERCMULTAFGTSCS,
    BDPROJECAOAVISO)
AS
SELECT
  RESC.BDCODEMP, RESC.BDCODCOL, RESC.BDCODPRES, RESC.BDDATARESCISAOPREV, RESC.BDDATAAVPREVIOPREV, RESC.BDDATAHOMPREV, RESC.BDDATAPAGRESCISAOPREV,
  RESC.BDSALDOFGTSPREV, RESC.BDCALCFGTSMESANTPREV, RESC.BDMAIORREMUNERACAOPREV, RESC.BDCHAVEINDENTIFICACAOPREV,
  RESC.BDDATAPAGGRFCPREV, RESC.BDREPOSICAOVAGAPREV, RESC.BDDISSIDIOPREV, RESC.BDDATADISSIDIOPREV, RESC.BDDESCANSOINDENIZADOPREV,
  
  PRESC.BDCODMFG, PRESC.BDCODSAQUE, PRESC.BDCODMRAIS, PRESC.BDCODMCAG, PRESC.BDDESCPRES, PRESC.BDINIPRES,
  PRESC.BDJCPRES, PRESC.BDAVPREPRES, PRESC.BDGRRFPRES, PRESC.BDESTPRES, PRESC.BDINDFER13, PRESC.BDTERMCONTRPRES,
  PRESC.BDMULTAPRES, PRESC.BDDIASAVPREPRES, PRESC.BDDIASPAGPRES,
  MFGTS.BDCODSEFMFG, MFGTS.BDDESCMFG,
  SAQUE.BDDESCSAQUE,
  RAIS.BDDESCMRAIS,
  CAGED.BDDESCMCAGED,
  PRESC.bdpercmultafgts, PRESC.bdpercmultafgtscs,
  RESC.BDPROJECAOAVISOPREV
FROM VRH_EMP_TRESCISAO_PREVIA RESC
LEFT OUTER JOIN VRH_BASE_TPREPRESC PRESC ON (RESC.BDCODPRES = PRESC.BDCODPRES)
LEFT OUTER JOIN VRH_BASE_TMOTFGTS MFGTS ON (PRESC.BDCODMFG = MFGTS.BDCODMFG)
LEFT OUTER JOIN VRH_BASE_TSAQUE  SAQUE ON (PRESC.BDCODSAQUE = SAQUE.BDCODSAQUE)
LEFT OUTER JOIN VRH_BASE_TMOTRAIS RAIS ON (PRESC.BDCODMRAIS = RAIS.BDCODMRAIS)
LEFT OUTER JOIN VRH_BASE_TMOTCAGED CAGED ON (PRESC.BDCODMCAG = CAGED.BDCODMCAG)
;

/* CREATE OR ALTER VIEW: VWRH_TVERBAS_REF_MAX_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_TVERBAS_REF_MAX_MIN(
BDCODVER,
BDREFVER)
 AS 
SELECT
  VER.BDCODVER,

  COALESCE(
    (
      SELECT FIRST 1 X.BDREFVER FROM VRH_BASE_TVERBAS_REF X
      WHERE X.BDCODVER = VER.BDCODVER AND
      CAST(X.BDREFVER AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
      ORDER BY X.BDREFVER DESC
     )
    ,
     (SELECT FIRST 1 X.BDREFVER FROM VRH_BASE_TVERBAS_REF X
       WHERE X.BDCODVER = VER.BDCODVER
       ORDER BY X.BDREFVER
      )
    ) BDREFVER

FROM VRH_BASE_TVERBAS VER
;

/* CREATE OR ALTER VIEW: VW_VERBAS_REF_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBAS_REF_ATUAL(
    BDCODVER,
    BDREFVER,
    BDTIPOCODVER,
    BDORDEMTIPOCODVER,
    BDINSSVER,
    BDFGTSVER,
    BDIRVER,
    BDTIPOREFVER,
    BDBASESFVER,
    BDPISVER,
    BDBASEHEVER,
    BDBASEMAIORVER,
    BDRAISVER,
    BDBASEGPSVER,
    BDMENORESVER,
    BDPROPVER,
    BDBASEVTVER,
    BDREEMBGPSVER,
    BDHEVER,
    BDGRAVAFICHAHNVER,
    BDCCPRINCIPALVER,
    BDFORMREFVER,
    BDFORMVALVER,
    BDFORMINTVER,
    BDFORMREFAUXVER,
    BDBASEDSRHEVER,
    BDBASEDSRRVVER,
    BDDEDFORMREFVER,
    BDDEDFORMVALVER,
    BDDEDFORMREFAUXVER,
    BDRENDISENTOIRVER,
    BDSIMPLESNACIONAL,
    BDBASE13HN,
    BDBASEFERHN,
    BDBASEAVHN,
    BDPAGAESTOUROVER,
    BDGARANTIAMINVER,
    BDINDRESC,
    BDNAOCONVHORASVER,
    BDBASEDSRHNVER,
    BDBASEDSROUVER,
    BDCODINCIDINSS,
    BDCODINCIDFGTS,
    BDCODINCIDIRRF,
    BDINCIDPISVER,
    BDCODINCIDPIS,
    BDDESCCOMPULSORIOVER)
AS
SELECT X.BDCODVER,
       X.BDREFVER,
       X.BDTIPOCODVER,
       CASE WHEN X.BDTIPOCODVER = 1 THEN 2 WHEN X.BDTIPOCODVER = 2 THEN 1 ELSE COALESCE(X.BDTIPOCODVER, 0) END BDORDEMTIPOCODVER,
       X.BDINSSVER,
       X.BDFGTSVER,
       X.BDIRVER,
       X.BDTIPOREFVER,
       X.BDBASESFVER,
       X.BDPISVER,
       X.BDBASEHEVER,
       X.BDBASEMAIORVER,
       X.BDRAISVER,
       X.BDBASEGPSVER,
       X.BDMENORESVER,
       X.BDPROPVER,
       X.BDBASEVTVER,
       X.BDREEMBGPSVER,
       X.BDHEVER,
       X.BDGRAVAFICHAHNVER,
       X.BDCCPRINCIPALVER,
       X.BDFORMREFVER,
       X.BDFORMVALVER,
       X.BDFORMINTVER,
       X.BDFORMREFAUXVER,
       X.BDBASEDSRHEVER,
       X.BDBASEDSRRVVER,
       X.BDDEDFORMREFVER,
       X.BDDEDFORMVALVER,
       X.BDDEDFORMREFAUXVER,
       X.BDRENDISENTOIRVER,
       X.BDSIMPLESNACIONAL,
       X.BDBASE13HN,
       X.BDBASEFERHN,
       X.BDBASEAVHN,
       X.BDPAGAESTOUROVER,
       X.BDGARANTIAMINVER,
       X.BDINDRESC,
       X.BDNAOCONVHORASVER,
       X.BDBASEDSRHNVER,
       X.BDBASEDSROUVER,
       X.BDCODINCIDINSS,
       X.BDCODINCIDFGTS,
       X.BDCODINCIDIRRF,
       X.BDINCIDPISVER,
       X.BDCODINCIDPIS,
       X.BDDESCCOMPULSORIOVER
FROM VRH_BASE_TVERBAS_REF X
JOIN VWRH_TVERBAS_REF_MAX_MIN Y ON (X.BDCODVER = Y.BDCODVER AND X.BDREFVER = Y.BDREFVER)
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_GPS_IND (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_GPS_IND(
BDCODEMP,
BDCHAVE,
BDCODCENTRO,
BDCODTPCC,
BDCODCOL,
BDCODTER,
BDCHAVEDARF,
BDCHAVEDARFGPSIND,
BDVALEMP,
BDVALSEG)
 AS 
SELECT gps.BDCODEMP, gps.BDCHAVE, gps.BDCODCENTRO, gps.BDCODTPCC, gps.BDCODCOL, gps.BDCODTER, gps.BDCHAVEDARF, gps.BDCHAVEDARFGPSIND,
       COALESCE(gps.BDVALFUNEMPFN,0)+ COALESCE(gps.BDVALFUNEMPFC,0)+ COALESCE(gps.BDVALFUNEMPFERFN,0)+ COALESCE(gps.BDVALFUNEMPFERFC,0)+ COALESCE(gps.BDVALFUNEMP13FN,0)+
       COALESCE(gps.BDVALFUNEMP13FC,0)+ COALESCE(gps.BDVALFUNEMP13,0)+ COALESCE(gps.BDVALFUNEMPC13,0)+ COALESCE(gps.BDVALPROEMPFN,0)+ COALESCE(gps.BDVALPROEMPFC,0)+
       COALESCE(gps.BDVALPROEMPFERFN,0)+ COALESCE(gps.BDVALPROEMPFERFC,0)+ COALESCE(gps.BDVALPROEMP13FN,0)+ COALESCE(gps.BDVALPROEMP13FC,0)+ COALESCE(gps.BDVALPROEMP13,0)+
       COALESCE(gps.BDVALPROEMPC13,0)+ COALESCE(gps.BDVALAUTEMPFN,0)+ COALESCE(gps.BDVALAUTEMPFC,0)+ COALESCE(gps.BDVALAUTEMPFERFN,0)+ COALESCE(gps.BDVALAUTEMPFERFC,0)+
       COALESCE(gps.BDVALAUTEMP13FN,0)+ COALESCE(gps.BDVALAUTEMP13FC,0)+ COALESCE(gps.BDVALAUTEMP13,0)+ COALESCE(gps.BDVALAUTEMPC13,0)+ COALESCE(gps.BDVALFPASEMPFN,0)+
       COALESCE(gps.BDVALFPASEMPFC,0)+ COALESCE(gps.BDVALFPASEMPFERFN,0)+ COALESCE(gps.BDVALFPASEMPFERFC,0)+ COALESCE(gps.BDVALFPASEMP13FN,0)+ COALESCE(gps.BDVALFPASEMP13FC,0)+
       COALESCE(gps.BDVALFPASEMP13,0)+ COALESCE(gps.BDVALFPASEMPC13,0)+ COALESCE(gps.BDVALRATEMPFN,0)+ COALESCE(gps.BDVALRATEMPFC,0)+ COALESCE(gps.BDVALRATEMPFERFN,0)+
       COALESCE(gps.BDVALRATEMPFERFC,0)+ COALESCE(gps.BDVALRATEMP13FN,0)+ COALESCE(gps.BDVALRATEMP13FC,0)+ COALESCE(gps.BDVALRATEMP13,0)+ COALESCE(gps.BDVALRATEMPC13,0)+
       COALESCE(gps.BDVALRATAPOEMPFN,0)+ COALESCE(gps.BDVALRATAPOEMPFC,0)+ COALESCE(gps.BDVALRATAPOEMPFERFN,0)+ COALESCE(gps.BDVALRATAPOEMPFERFC,0)+ COALESCE(gps.BDVALRATAPOEMP13FN,0)+
       COALESCE(gps.BDVALRATAPOEMP13FC,0)+ COALESCE(gps.BDVALRATAPOEMP13,0)+ COALESCE(gps.BDVALRATAPOEMPC13,0) bdVALEMP,
       COALESCE(gps.bdvaltotseg,0) bdvalseg
       FROM VRHF_EMP_GPS_IND gps
;

/* CREATE OR ALTER VIEW: VW_SN_IMPOSTOS_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_SN_IMPOSTOS_REF(
BDCODEMP,
BDCODMATRIZ,
BDCODIMP,
BDREFERENCIA,
BDVALOR,
BDMULTA,
BDJUROS,
BDTOTAL,
BDVALEMPGPS,
BDVALSEGGPS)
 AS 
SELECT imp.bdcodemp,
       COALESCE(E.bdcodmatriz,IMP.bdcodemp) bdcodmatriz,
       imp.bdcodimp,
       imp.bdreferencia,
       SUM(CASE WHEN ((gps.bdvalemp <> 0) OR (gps.bdvalseg <> 0)) THEN
               0
            WHEN (imp.bdcodemp IS NOT NULL) THEN
               COALESCE(imp.bdvalor,0)
       END) bdvalor,
       0 bdmulta,
       0 bdjuros,
       SUM(CASE WHEN ((gps.bdvalemp <> 0) OR (gps.bdvalseg <> 0)) THEN
               COALESCE(imp.bdvalor,0)
            WHEN (imp.bdcodemp IS NOT NULL) THEN
               COALESCE(imp.bdvalor,0)
       END) bdtotal,

       SUM(COALESCE(gps.bdvalemp,0)) bdvalempgps,
       SUM(COALESCE(gps.bdvalseg,0)) bdvalseggps
FROM tdarfpadrao imp
JOIN tempresas e ON (imp.bdcodemp = e.bdcodemp)
LEFT OUTER JOIN (SELECT gpsx.bdcodemp,gpsx.bdchavedarf,SUM(gpsx.bdvalemp) bdvalemp,SUM(gpsx.bdvalseg) bdvalseg FROM VW_VRHF_EMP_GPS_IND gpsx
                 GROUP BY gpsx.bdcodemp,gpsx.bdchavedarf) gps
                 ON (imp.bdcodemp = gps.bdcodemp AND imp.bdchavedarf = gps.bdchavedarf)
GROUP BY imp.bdcodemp,E.bdcodmatriz,imp.bdcodimp,imp.bdreferencia
;

/* CREATE OR ALTER VIEW: VW_SN_ENCARGOS_SALARIOS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_SN_ENCARGOS_SALARIOS(
BDCODEMP,
BDREF,
BDTIPOCODVER,
BDSALARIO)
 AS 
SELECT bdcodemp,bdref,bdtipocodver,SUM(bdsalario) bdsalario FROM (


SELECT vfn.bdcodemp,vfn.bdreffn bdref,v.bdtipocodver, vfn.bdvalvfn bdsalario FROM vrhf_emp_tverbafn vfn
JOIN vw_verbas_ref_atual v ON (vfn.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vfT.bdcodemp,vfT.bdreftomador bdref,v.bdtipocodver,vfT.bdvalvfT bdsalario FROM vrhf_emp_tverbatomador vfT
JOIN vw_verbas_ref_atual v ON (vfT.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vfC.bdcodemp,vfC.bdreffn bdref,v.bdtipocodver,vfC.bdvalvfc bdsalario FROM vrhf_emp_tverbafc vfC
JOIN vw_verbas_ref_atual v ON (vfC.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vfCt.bdcodemp,vfCt.bdreftomador bdref,v.bdtipocodver,vfCt.bdvalvfc bdsalario FROM vrhf_emp_tverbafctomador vfCt
JOIN vw_verbas_ref_atual v ON (vfCt.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vaut.bdcodemp,serv.BDREFSERV bdref,v.bdtipocodver,vaut.bdvalor bdsalario FROM VRHF_BASE_ITEMS_CALCTERC vaut
JOIN vw_verbas_ref_atual v ON (vaut.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
JOIN vrh_base_tservterc serv ON (serv.bdcodter = vaut.bdcodter AND vaut.bdcodemp = serv.bdcodemp AND vaut.bdcodserv = serv.bdcodserv)
UNION ALL

SELECT vad.bdcodemp,ad.BDREFAD bdref,v.bdtipocodver,vad.bdvalvad bdsalario FROM vrhf_emp_tverbaad vad
JOIN vw_verbas_ref_atual v ON (vad.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
JOIN vrhf_emp_tadsal ad ON (vad.bdcodemp = ad.bdcodemp AND vad.bdcodcol = ad.bdcodcol AND vad.bddataad = ad.bddataad)
UNION ALL

SELECT va13.bdcodemp,va13.bdrefa13 bdref,v.bdtipocodver,va13.bdvalva13 bdsalario FROM vrhf_emp_tverbaa13 va13
JOIN vw_verbas_ref_atual v ON (va13.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT v13.bdcodemp,v13.bdref13 bdref,v.bdtipocodver,v13.bdvalv13 bdsalario FROM vrhf_emp_tverba13 v13
JOIN vw_verbas_ref_atual v ON (v13.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vc13.bdcodemp,vc13.bdrefc13 bdref,v.bdtipocodver,vc13.bdvalvc13 bdsalario FROM vrhf_emp_tverbac13 vc13
JOIN vw_verbas_ref_atual v ON (vc13.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vimp.bdcodemp,vimp.bdreferencia,0 bdtipocodver,CASE WHEN imp.bddocarrecadacao = 12 THEN vimp.bdvalempgps ELSE vimp.bdtotal END FROM VW_SN_IMPOSTOS_REF vimp
JOIN timposto imp ON (vimp.bdcodimp = imp.bdcodimp AND (imp.bdcodsis = 2) AND ((imp.bddocarrecadacao IN (19,20,12)) OR ((imp.bddocarrecadacao IN (1)) AND (imp.bdtiporetencao = 1))))

--Elizeu - 13-06-2013 - alt:4594 - não deve buscar a base da grrf e sim o imposto gerado da grrf
--union all

--select gr.bdcodemp, r.BDREFRESCISAO/* (select bdAAAAMM from  AAAAMM(R.BDDATAPAGGRFC))*/ BDREF, 0 bdtipocodver,(gr.BDFGTSMESGR + gr.BDFGTSMESANTGR + gr.BDINDENIZADOGR) BDSALARIO
--from  vrh_emp_tgrrf gr
--join vrh_emp_trescisao r on (gr.bdcodemp = r.bdcodemp and gr.bdcodcol = r.bdcodcol)

)

GROUP BY bdcodemp, bdref, bdtipocodver
;

/* CREATE OR ALTER VIEW: VW_SN_IMPOSTOS_PGTO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_SN_IMPOSTOS_PGTO(
BDCODEMP,
BDCODMATRIZ,
BDCODIMP,
BDREFERENCIA,
BDVALOR,
BDMULTA,
BDJUROS,
BDTOTAL,
BDVALEMPGPS,
BDVALSEGGPS)
 AS 
SELECT bdcodemp,
       BDCODMATRIZ,
       bdcodimp,
       bdreferencia,
       SUM(CASE WHEN ((bdvalempgps <> 0) OR (bdvalseggps <> 0)) THEN
               0
            WHEN (bdcodemp IS NOT NULL) THEN
               COALESCE(bdvalor,0)
       END) bdvalor,
       SUM(bdmulta) bdmulta,
       SUM(bdjuros) bdjuros,
       SUM(bdtotal) bdtotal,
       SUM(bdvalempgps) bdvalempgps,
       SUM(bdvalseggps) bdvalseggps FROM (
SELECT imp.bdcodemp,COALESCE(E.bdcodmatriz,IMP.bdcodemp) bdcodmatriz,imp.bdcodimp,(SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) bdreferencia,imp.bdvalor bdvalor,imp.bdmulta bdmulta,imp.bdjuros bdjuros,imp.bdtotal bdtotal,
       gps.bdvalemp bdvalempgps, gps.bdvalseg bdvalseggps
FROM tdarfpadrao imp
JOIN tempresas e ON (imp.bdcodemp = e.bdcodemp)
LEFT OUTER JOIN (SELECT gpsx.bdcodemp,gpsx.bdchavedarf,SUM(gpsx.bdvalemp) bdvalemp,SUM(gpsx.bdvalseg) bdvalseg FROM VW_VRHF_EMP_GPS_IND gpsx
                 GROUP BY gpsx.bdcodemp,gpsx.bdchavedarf) gps
                 ON (imp.bdcodemp = gps.bdcodemp AND imp.bdchavedarf = gps.bdchavedarf)
JOIN tdarfgerpgto pgto ON (imp.bdcodemp = pgto.bdcodemp AND imp.bdchavedarf = pgto.bdchavedarf)
)
GROUP BY bdcodemp,BDCODMATRIZ,bdcodimp,bdreferencia
;

/* CREATE OR ALTER VIEW: VW_SN_VERBAS_CALCULOS_RH_PGTO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_SN_VERBAS_CALCULOS_RH_PGTO(
BDCODEMP,
BDCODVER,
BDREF,
BDVALFN,
BDVALFC,
BDVALAD,
BDVALFE,
BDVALAD13,
BDVAL13,
BDVALC13)
 AS 
SELECT bdcodemp,bdcodver,bdreffn bdref,SUM(bdvalvfn) bdvalfn, SUM(bdvalfc) bdvalfc,
                                       SUM(bdvalad) bdvalad, SUM(bdvalfe) bdvalfe,
                                       SUM(bdvalad13) bdvalad13, SUM(bdval13) bdval13,
                                       SUM(bdvalc13) bdvalc13 FROM (

SELECT ter.bdcodemp,ter.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) AS INTEGER) bdreffn,ter.bdvalor bdvalvfn,0 bdvalfc,0 bdvalad,0 bdvalfe,0 bdvalad13,0 bdval13,0 bdvalc13
FROM vrhf_base_items_calcterc ter
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (ter.bdcodemp = baixa.bdcodemp AND ter.bdcodter = baixa.bdcodter AND ter.bdcodserv = baixa.bdcodserv AND baixa.bdtipocalc = 1)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT fn.bdcodemp,fn.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) AS INTEGER) bdreffn,
        fn.bdvalvfn,0 bdvalfc,0 bdvalad,0 bdvalfe,0 bdvalad13,0 bdval13,0 bdvalc13 FROM vrhf_emp_tverbafn fn
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (fn.bdcodemp = baixa.bdcodemp AND fn.bdcodcol = baixa.bdcodcol AND fn.bdreffn = baixa.bdreferencia AND baixa.bdtipocalc = 6)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT fnt.bdcodemp,fnt.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) AS INTEGER),fnt.bdvalvft,0,0,0,0,0,0 FROM vrhf_emp_tverbatomador fnt
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (fnt.bdcodemp = baixa.bdcodemp AND fnt.bdcodcol = baixa.bdcodcol AND fnt.bdreftomador = baixa.bdreferencia AND baixa.bdtipocalc = 7)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT fc.bdcodemp,fc.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) AS INTEGER),0,fc.bdvalvfc,0,0,0,0,0 FROM vrhf_emp_tverbafc fc
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (fc.bdcodemp = baixa.bdcodemp AND fc.bdcodcol = baixa.bdcodcol AND fc.bdreffn = baixa.bdreferencia AND fc.bdrefcomp = baixa.bdrefcomp  AND baixa.bdtipocalc = 8)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT fct.bdcodemp,fct.bdcodver,fct.bdrefcomp,0,fct.bdvalvfc,0,0,0,0,0 FROM vrhf_emp_tverbafctomador fct
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (fct.bdcodemp = baixa.bdcodemp AND fct.bdcodcol = baixa.bdcodcol AND fct.bdreftomador = baixa.bdreferencia AND fct.bdrefcomp = baixa.bdrefcomp  AND baixa.bdtipocalc = 9)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT ad.bdcodemp,ad.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) AS INTEGER),0,0,ad.bdvalvad,0,0,0,0 FROM vrhf_emp_tverbaad ad
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (ad.bdcodemp = baixa.bdcodemp AND ad.bdcodcol = baixa.bdcodcol AND ad.bddataad = baixa.bddata AND baixa.bdtipocalc = 4)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT fe.bdcodemp,fe.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) AS INTEGER),0,0,0,fe.bdvalvfe,0,0,0 FROM vrhf_emp_tverbafe fe
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (fe.bdcodemp = baixa.bdcodemp AND fe.bdcodcol = baixa.bdcodcol AND fe.bdiniperaquisfe = baixa.bdiniperaqui AND fe.bdcodfe = baixa.bdcodfer AND baixa.bdtipocalc = 10)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT adt.bdcodemp,adt.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) AS INTEGER),0,0,0,0,adt.bdvalva13,0,0 FROM vrhf_emp_tverbaa13 adt
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (adt.bdcodemp = baixa.bdcodemp AND adt.bdcodcol = baixa.bdcodcol AND adt.bdrefa13 = baixa.bdreferencia AND baixa.bdtipocalc = 3)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT dt.bdcodemp,dt.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto))  AS INTEGER),0,0,0,0,0,dt.bdvalv13,0 FROM vrhf_emp_tverba13 dt
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (dt.bdcodemp = baixa.bdcodemp AND dt.bdcodcol = baixa.bdcodcol AND dt.bdref13 = baixa.bdreferencia AND baixa.bdtipocalc = 2)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
UNION
SELECT cdt.bdcodemp,cdt.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(pgto.bddatapgto)) AS INTEGER),0,0,0,0,0,0,cdt.bdvalvc13 FROM vrhf_emp_tverbac13 cdt
JOIN vrhf_emp_tdadoscalc_baixa baixa ON (cdt.bdcodemp = baixa.bdcodemp AND cdt.bdcodcol = baixa.bdcodcol AND cdt.bdref13 = baixa.bdreferencia AND cdt.bdrefc13 = baixa.bdrefcomp AND baixa.bdtipocalc = 5)
JOIN  vrhf_emp_tpgto_calc pgto ON (baixa.bdcodemp = pgto.bdcodemp AND pgto.bdchavepgto = baixa.bdchave)
)
GROUP BY bdcodemp,bdcodver,bdreffn
;

-- 15128 Denicio 28/07/2016 - Novas views para o cálculo das provisões 
/* View: VW_UNION_FC_TOMADOR */
CREATE OR ALTER VIEW VW_UNION_FC_TOMADOR(
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDREFCOMP,
    BDDATABAIXAFN,
    BDBFGTSFN,
    BDFGTSFN,
    BDFGTSCSFN,
    BDBFGTS13FN,
    BDFGTS13FN,
    BDFGTS13CSFN,
    BDMAIORREMFN,
    BDBINSSFN,
    BDALIQINSSFN,
    BDINSSFN,
    BDBIRRFFN,
    BDALIQIRRFFN,
    BDIRRFFN,
    BDBINSS13FN,
    BDALIQINSS13FN,
    BDINSS13FN,
    BDBIRRF13FN,
    BDALIQIRRF13FN,
    BDIRRF13FN,
    BDBSALFAMFN,
    BDSALFAMFN,
    BDBRAISFN,
    BDSALBASEFN,
    BDDEPFN,
    BDBASEPISFN,
    BDBASEPISFEFN,
    BDBASEPIS13FN,
    BDBSALMATEMPFN,
    BDSALMATEMPFN,
    BDBRATAPOFN,
    BDBRATAPOFEFN,
    BDBRATAPO13FN,
    BDBINSSFEFOLFN,
    BDINSSFEFOLFN,
    BDALIQINSSFEFOLFN,
    BDCREDITFN,
    BDDEBITOFN,
    BDBFGTSFEFN,
    BDFGTSFEFN,
    BDREFFC,
    BDREFVINCFN,
    BDDATAPAGFC)
AS
SELECT
  FC.BDCODEMP,
  FC.BDCODCOL,
  FC.BDREFFN,
  FC.BDREFCOMP,
  FC.bddatabaixafc,
  FC.bdbfgtsfc,
  FC.bdfgtsfc,
  FC.bdfgtscsfc,
  FC.bdbfgts13fc,
  FC.bdfgts13fc,
  FC.bdfgts13csfc,
  FC.bdmaiorremfc,
  FC.bdbinssfc,
  FC.bdaliqinssfc,
  FC.bdinssfc,
  FC.bdbirrffc,
  FC.bdaliqirrffc,
  FC.bdirrffc,
  FC.bdbinss13fc,
  FC.bdaliqinss13fc,
  FC.bdinss13fc,
  FC.bdbirrf13fc,
  FC.bdaliqirrf13fc,
  FC.bdirrf13fc,
  FC.bdbsalfamfc,
  FC.bdsalfamfc,
  FC.bdbraisfc,
  FC.bdsalbasefc,
  FC.bddepfc,
  FC.bdbasepisfc,
  FC.bdbasepisfefc,
  FC.bdbasepis13fc,
  FC.bdbsalmatempfc,
  FC.bdsalmatempfc,
  FC.bdbratapofc,
  FC.bdbratapofefc,
  FC.bdbratapo13fc,
  FC.bdbinssfefolfc,
  FC.bdinssfefolfc,
  FC.bdaliqinssfefolfc,
  FC.bdcreditofc,
  FC.bddebitofc,
  FC.bdbfgtsfefc,
  FC.bdfgtsfefc,
  FC.bdreffc,
  FC.bdrefvincfn,
  FC.bddatapagfc
FROM VRHF_EMP_TFOLHACOMP FC

UNION

SELECT
  FCT.BDCODEMP,
  FCT.BDCODCOL,
  FCT.BDREFTOMADOR,
  FCT.BDREFCOMP,
  FCT.bddatabaixafc,
  FCT.bdbfgtsfc,
  FCT.bdfgtsfc,
  FCT.bdfgtscsfc,
  FCT.bdbfgts13fc,
  FCT.bdfgts13fc,
  FCT.bdfgts13csfc,
  FCT.bdmaiorremfc,
  FCT.bdbinssfc,
  FCT.bdaliqinssfc,
  FCT.bdinssfc,
  FCT.bdbirrffc,
  FCT.bdaliqirrffc,
  FCT.bdirrffc,
  FCT.bdbinss13fc,
  FCT.bdaliqinss13fc,
  FCT.bdinss13fc,
  FCT.bdbirrf13fc,
  FCT.bdaliqirrf13fc,
  FCT.bdirrf13fc,
  FCT.bdbsalfamfc,
  FCT.bdsalfamfc,
  FCT.bdbraisfc,
  FCT.bdsalbasefc,
  FCT.bddepfc,
  FCT.bdbasepisfc,
  FCT.bdbasepisfefc,
  FCT.bdbasepis13fc,
  FCT.bdbsalmatempfc,
  FCT.bdsalmatempfc,
  FCT.bdbratapofc,
  FCT.bdbratapofefc,
  FCT.bdbratapo13fc,
  FCT.bdbinssfefolfc,
  FCT.bdinssfefolfc,
  FCT.bdaliqinssfefolfc,
  FCT.bdcreditofc,
  FCT.bddebitofc,
  FCT.bdbfgtsfefc,
  FCT.bdfgtsfefc,
  FCT.bdreffc,
  FCT.bdrefvincfn,
  FCT.bddatapagfc
FROM VRHF_EMP_TFOLTOMCOMP FCT
;

/* View: VW_UNION_FC_TOMADOR_VERBAS */
CREATE OR ALTER VIEW VW_UNION_FC_TOMADOR_VERBAS(
    BDCODVER,
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDREFCOMP,
    BDREFVFN,
    BDREFAUXVFN,
    BDVALVFN,
    BDIGNREFVFN,
    BDIGNVALVFN,
    BDREFFC)
AS
SELECT
  FC.BDCODVER,
  FC.BDCODEMP,
  FC.BDCODCOL,
  FC.BDREFFN,
  FC.BDREFCOMP,
  FC.bdrefvfc,
  FC.bdrefauxvfc,
  FC.bdvalvfc,
  FC.bdignrefvfc,
  FC.bdignvalvfc,
  FC.bdreffc
FROM VRHF_EMP_TVERBAFC FC

UNION

SELECT
  FCT.BDCODVER,
  FCT.BDCODEMP,
  FCT.BDCODCOL,
  FCT.BDREFTOMADOR,
  FCT.BDREFCOMP,
  FCT.bdrefvfc,
  FCT.bdrefauxvfc,
  FCT.bdvalvfc,
  FCT.bdignrefvfc,
  FCT.bdignvalvfc,
  FCT.bdreffc
FROM vrhf_emp_tverbafctomador FCT
;

CREATE OR ALTER VIEW VW_UNION_FC_TOMADOR_VERBAS_DET(
    BDCODVER,
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDREFFC,
    BDREFVFN,
    BDREFAUXVFN,
    BDVALVFN,
    BDIGNREFVFN,
    BDIGNVALVFN,
    BDORDEMDETALHE)
AS
SELECT
  FC.BDCODVER,
  FC.BDCODEMP,
  FC.BDCODCOL,
  FC.BDREFFN,
  FC.BDREFFC,
  FC.bdrefvfcd,
  FC.bdrefauxvfcd,
  FC.bdvalvfcd,
  FC.bdignrefvfcd,
  FC.bdignvalvfcd,
  FC.bdordemdetalhe
FROM VRHF_EMP_TVERBAFC_DET FC

UNION

SELECT
  FCT.BDCODVER,
  FCT.BDCODEMP,
  FCT.BDCODCOL,
  FCT.BDREFTOMADOR,
  FCT.BDREFFC,
  FCT.bdrefvfctd,
  FCT.bdrefauxvfctd,
  FCT.bdvalvfctd,
  FCT.bdignrefvfctd,
  FCT.bdignvalvfctd,
  FCT.bdordemdetalhe
FROM VRHF_EMP_TVERBAFCT_DET FCT
;

CREATE OR ALTER VIEW VW_VEF_BASE_TEMPCADATV(
    BDCODEMP,
    BDREFEMP,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO)
AS
SELECT
    x.bdcodemp,
    x.bdrefemp,
    x.bdcomercio,
    x.bdindustria,
    x.bdservico
FROM vef_base_tempcadatv x
WHERE X.BDREFEMP =
      (
       SELECT MAX(Y.BDREFEMP)
       FROM VEF_BASE_TEMPCADATV Y
       WHERE Y.BDCODEMP = X.BDCODEMP AND
             Y.BDREFEMP <=
                (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER)
                 FROM rdb$database
                )
      )
;

CREATE OR ALTER VIEW VW_VEF_BASE_TNBS_DADOS_MAXMIN(
    BDCOD_NBS,
    BDREF_DADOS)
AS
select BDCOD_NBS, COALESCE((SELECT FIRST 1 r.BDREF_DADOS FROM VEF_BASE_TNBS_DADOS r
                 WHERE r.BDCOD_NBS = nbsd.BDCOD_NBS AND
                 CAST(r.BDREF_DADOS AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
                 ORDER BY r.BDREF_DADOS DESC),
                 (SELECT FIRST 1 r.BDREF_DADOS FROM VEF_BASE_TNBS_DADOS r
                  WHERE r.BDCOD_NBS = nbsd.BDCOD_NBS
                  ORDER BY r.BDREF_DADOS
                 )
                ) BDREF_DADOS
from VEF_BASE_TNBS_DADOS nbsd
group by BDCOD_NBS, BDREF_DADOS
;

CREATE OR ALTER VIEW VW_VEF_BASE_TNBS_DADOS(
    BDCOD_NBS,
    BDCHAVE_DADOS,
    BDREF_DADOS,
    BDCOD_CCLASSTRIB,
    BDCOD_CST,
    BDREDUCAOIBS_DADOS,
    BDALIQCBS_DADOS,
    BDREDUCAOCBS_DADOS,
    BDINDOP)
AS
select
    nbsd.BDCOD_NBS,
    nbsd.BDCHAVE_DADOS,
    nbsd.BDREF_DADOS,
    nbsd.BDCOD_CCLASSTRIB,
    nbsd.BDCOD_CST,
    nbsd.BDREDUCAOIBS_DADOS,
    nbsd.BDALIQCBS_DADOS,
    nbsd.BDREDUCAOCBS_DADOS,
    nbsd.BDINDOP
from VEF_BASE_TNBS_DADOS nbsd
join VW_VEF_BASE_TNBS_DADOS_MAXMIN mm on (mm.BDCOD_NBS = nbsd.BDCOD_NBS and mm.BDREF_DADOS = nbsd.BDREF_DADOS)
;

/* CREATE OR ALTER VIEW: VW_SN_VERBAS_CALCULOS_RH_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_SN_VERBAS_CALCULOS_RH_REF(
BDCODEMP,
BDCODVER,
BDREF,
BDVALFN,
BDVALFC,
BDVALAD,
BDVALFE,
BDVALAD13,
BDVAL13,
BDVALC13)
 AS 
SELECT bdcodemp,bdcodver,bdreffn bdref,SUM(bdvalvfn) bdvalfn, SUM(bdvalfc) bdvalfc,
                                       SUM(bdvalad) bdvalad, SUM(bdvalfe) bdvalfe,
                                       SUM(bdvalad13) bdvalad13, SUM(bdval13) bdval13,
                                       SUM(bdvalc13) bdvalc13 FROM (

SELECT ter.bdcodemp,ter.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(cter.bddataserv)) AS INTEGER) bdreffn,ter.bdvalor bdvalvfn,0 bdvalfc,0 bdvalad,0 bdvalfe,0 bdvalad13,0 bdval13,0 bdvalc13
FROM vrhf_base_items_calcterc ter, vrhf_base_calc_terc cter
WHERE cter.bdcodter = ter.bdcodter AND cter.bdcodemp = ter.bdcodter AND cter.bdcodserv = ter.bdcodserv
UNION
SELECT fn.bdcodemp,fn.bdcodver,fn.bdreffn,fn.bdvalvfn,0 bdvalfc,0 bdvalad,0 bdvalfe,0 bdvalad13,0 bdval13,0 bdvalc13 FROM vrhf_emp_tverbafn fn
UNION
SELECT fnt.bdcodemp,fnt.bdcodver,fnt.bdreftomador,fnt.bdvalvft,0,0,0,0,0,0 FROM vrhf_emp_tverbatomador fnt
UNION
SELECT fc.bdcodemp,fc.bdcodver,fc.bdrefcomp,0,fc.bdvalvfc,0,0,0,0,0 FROM vrhf_emp_tverbafc fc
UNION
SELECT fct.bdcodemp,fct.bdcodver,fct.bdrefcomp,0,fct.bdvalvfc,0,0,0,0,0 FROM vrhf_emp_tverbafctomador fct
UNION
SELECT ad.bdcodemp,ad.bdcodver,CAST((SELECT bdaaaamm FROM aaaamm(ad.bddataad)) AS INTEGER),0,0,ad.bdvalvad,0,0,0,0 FROM vrhf_emp_tverbaad ad
UNION
SELECT fe.bdcodemp,fe.bdcodver, CASE WHEN fer.bdinipergozofe IS NULL THEN fer.bdrefpagabofe
                                     WHEN fer.bdinipergozofe IS NOT NULL THEN CAST((SELECT bdaaaamm FROM aaaamm(fer.bdinipergozofe)) AS INTEGER)
                                END,0,0,0,fe.bdvalvfe,0,0,0 FROM vrhf_emp_tverbafe fe, vrh_emp_tferias fer
       WHERE fer.bdcodemp = fe.bdcodemp AND fer.bdcodcol = fe.bdcodcol AND fer.bdiniperaquisfe = fe.bdiniperaquisfe AND fer.bdcodfe = fe.bdcodfe
UNION
SELECT adt.bdcodemp,adt.bdcodver,adt.bdrefa13,0,0,0,0,adt.bdvalva13,0,0 FROM vrhf_emp_tverbaa13 adt
UNION
SELECT dt.bdcodemp,dt.bdcodver,dt.bdref13,0,0,0,0,0,dt.bdvalv13,0 FROM vrhf_emp_tverba13 dt
UNION
SELECT cdt.bdcodemp,cdt.bdcodver,cdt.bdrefc13,0,0,0,0,0,0,cdt.bdvalvc13 FROM vrhf_emp_tverbac13 cdt
)
GROUP BY bdcodemp,bdcodver,bdreffn
;

/* CREATE OR ALTER VIEW: VW_SWS_EMP_SCIREPORT (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_SWS_EMP_SCIREPORT(
    BDCODEMP,
    BDCODWEB,
    bddatainiativemp)
AS
SELECT emp.bdcodemp,COALESCE(emp.bdcodweb,emp.bdcodemp), emp.bddatainiativemp FROM tempresas emp
WHERE(COALESCE(UPPER(emp.bdscireport),'FALSE') = 'TRUE')
and((emp.bdexcluiremp is null)or(upper(emp.bdexcluiremp)<>'TRUE'))
;

/* CREATE OR ALTER VIEW: VW_VARIAVEIS_SESSAO_BANCO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VARIAVEIS_SESSAO_BANCO(
BDCODUSU)
 AS 
SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_USUARIO'))) AS INTEGER) bdcodusu FROM rdb$database
;

/* CREATE OR ALTER VIEW: VW_TATVMUNICIPAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TATVMUNICIPAL(
    BDCODATVM,
    BDCODCID,
    BDCODMUNATVM,
    BDDESCATVM,
    BDALIQATVM,
    BDCODSER,
    BDRELFOLHAANEXOIII)
AS
SELECT
    BASE.bdcodatvm,
    BASE.bdcodcid,
    VINC.bdcodmunatvm,
    VINC.bddescatvm,
    VINC.bdaliqatvm,
    VINC.bdcodser,
    VINC.bdrelfolhaanexoiii
FROM
(
  SELECT
      X.bdcodatvm,
      X.bdcodcid,
      COALESCE
  (
      (SELECT MAX(d2.bdrefatvm) FROM tatvmunicipal d2 WHERE d2.bdcodatvm = x.bdcodatvm AND CAST(d2.BDREFATVM AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefatvm) FROM tatvmunicipal d1 WHERE d1.bdcodatvm = x.bdcodatvm)
  ) AS bdrefatvm
  FROM TATVMUNICIPAL x

) AS BASE
JOIN TATVMUNICIPAL VINC ON (BASE.BDCODATVM = VINC.BDCODATVM AND BASE.BDCODCID = VINC.BDCODCID AND BASE.BDREFATVM = VINC.BDREFATVM)
;

/* CREATE OR ALTER VIEW: VW_TCADPRO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TCADPRO(
BDCODPROD,
    BDCODEMP,
    BDCODUNIMED,
    BDNCMPROD,
    BDDESCPROD,
    BDAPEPROD,
    BDDESCUNIMED,
    BDAPEUNIMED,
    BDCODGEN,
    BDGENERO,
    BDDESCGEN,
    BDCODTIPOSER,
    BDTIPOSER,
    BDDESCSER,
    BDCODSER,
    BDSERVICO,
    BDDESCCODSER,
    BDCODSAIDA,
    BDCODCOMBANP,
    BDCODCOMBANPEXP,
    BDDESCCOMBANP,

    BDGENEROVINC,
    BDDESCGENVINC,
    BDTIPOSERVINC,
    BDDESCSERVINC,
    BDSERVICOVINC,
    BDDESCCODSERVINC,
    BDCODCOMBANPEXPVINC,
    BDDESCCOMBANPVINC)
AS
SELECT
    PRO.BDCODPROD,
    pro.bdcodemp,
    PRO.BDCODUNIMED  ,
    PRO.BDNCMPROD    ,
    PRO.BDDESCPROD   ,
    PRO.BDAPEPROD    ,
    UM.bddescunimed ,
    UM.bdapeunimed,
    gen.bdcodgen,
    gen.bdgenero,
    gen.bddescgen,
    ser.bdcodtiposer,
    ser.bdtiposer,
    ser.bddescser,
    codser.bdcodser,
    codser.bdservico,
    codser.bddescser bddescCodSer,
    pro.BDCODSAIDA,
    anp.bdcodcombanp,
    anp.bdregexp,
    anp.bddescricao,

    genV.bdgenero,
    genV.bddescgen,
    serV.bdtiposer,
    serV.bddescser,
    codserV.bdservico,
    codserV.bddescser bddescCodSer,
    anpV.bdregexp,
    anpV.bddescricao

FROM tcadpro_vinc PRO
LEFT OUTER JOIN tcadpro cadpro ON (pro.bdcodprod = cadpro.bdcodprod)
LEFT OUTER JOIN tunidademedida UM ON (PRO.bdcodunimed = UM.bdcodunimed)
LEFT OUTER JOIN tgeneropro gen ON (cadpro.bdcodgen = gen.bdcodgen)
LEFT OUTER JOIN ttipo_servico ser ON (cadpro.bdcodtiposer = ser.bdcodtiposer)
LEFT OUTER JOIN tcodigo_servico codser ON (cadpro.bdcodser = codser.bdcodser)
LEFT OUTER JOIN VEF_BASE_TTABCOMBANP anp ON (cadpro.bdcodcombanp = anp.bdcodcombanp)

LEFT OUTER JOIN tgeneropro genV ON (pro.bdcodgen = genV.bdcodgen)
LEFT OUTER JOIN ttipo_servico serV ON (pro.bdcodtiposer = serV.bdcodtiposer)
LEFT OUTER JOIN tcodigo_servico codserV ON (pro.bdcodser = codserV.bdcodser)
LEFT OUTER JOIN VEF_BASE_TTABCOMBANP anpV ON (pro.bdcodcombanp = anpV.bdcodcombanp)
;

/* CREATE OR ALTER VIEW: VW_TCADPRO_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TCADPRO_ATUAL(
BDCODPROD,
BDCODEMP,
BDCODUNIMED,
BDNCMPROD,
BDDESCPROD,
BDAPEPROD,
BDDESCUNIMED,
BDAPEUNIMED,
BDCODGEN,
BDGENERO,
BDDESCGEN,
BDCODTIPOSER,
BDTIPOSER,
BDDESCSER,
BDCODSER,
BDSERVICO,
BDDESCCODSER,
BDCODCSTCOFENT,
BDCODCSTIPIENT,
BDCODCSTPISENT,
BDCODCSTCOFSAI,
BDCODCSTIPISAI,
BDCODCSTPISSAI,
BDCODCSTICMS,
BDALIQCOF,
BDALIQIPI,
BDALIQPIS,
BDALIQICMS,
BDALIQICMSST,
BDCODSAIDA)
 AS 
SELECT
    PRO.BDCODPROD,
    PRO.bdcodemp,

    PRO.BDCODUNIMED  ,
    PRO.BDNCMPROD    ,
    PRO.BDDESCPROD   ,
    PRO.BDAPEPROD    ,
    UM.bddescunimed ,
    UM.bdapeunimed,
    gen.bdcodgen,
    gen.bdgenero,
    gen.bddescgen,
    ser.bdcodtiposer,
    ser.bdtiposer,
    ser.bddescser,
    codser.bdcodser,
    codser.bdservico,
    codser.bddescser bddescCodSer,
    PRO.BDCODCSTCOFENT,
    PRO.BDCODCSTIPIENT,
    PRO.BDCODCSTPISENT,
    PRO.BDCODCSTCOFSAI,
    PRO.BDCODCSTIPISAI,
    PRO.BDCODCSTPISSAI,
    PRO.BDCODCSTICMS,
    PRO.BDALIQCOF,
    PRO.BDALIQIPI,
    PRO.BDALIQPIS,
    PRO.BDALIQICMS,
    PRO.BDALIQICMSST,
    PRO.BDCODSAIDA

FROM tcadpro_vinc pro
LEFT OUTER JOIN tcadpro cadpro ON (pro.bdcodprod = cadpro.bdcodprod)
LEFT OUTER JOIN tunidademedida UM ON (PRO.bdcodunimed = UM.bdcodunimed)
LEFT OUTER JOIN tgeneropro gen ON (cadPRO.bdcodgen = gen.bdcodgen)
LEFT OUTER JOIN ttipo_servico ser ON (cadPRO.bdcodtiposer = ser.bdcodtiposer)
LEFT OUTER JOIN tcodigo_servico codser ON (cadPRO.bdcodser = codser.bdcodser)
;

/* CREATE OR ALTER VIEW: VW_TCADPRO_EXISTENTES (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TCADPRO_EXISTENTES(
BDCODPROD,
BDCODUNIMED,
BDNCMPROD,
BDDESCPROD,
BDAPEPROD,
BDCODEMP,
BDCODSAIDA,
BDCODGEN,
BDCODSER,
BDCODTIPOSER,
BDCODCOMBANP,
BDAPELIDOUNICO,
BDDESCRICAOUNICA,
BDCODIGOEAN)
 AS 
SELECT
    proemp.BDCODPROD    ,
    proemp.BDCODUNIMED  ,
    proemp.BDNCMPROD    ,
    proemp.BDDESCPROD   ,
    proemp.BDAPEPROD    ,
    proemp.bdCODEMP     ,
    proemp.BDCODSAIDA   ,
    cadpro.BDCODGEN     ,
    cadpro.BDCODSER     ,
    cadpro.BDCODTIPOSER ,
    cadpro.BDCODCOMBANP ,
    cadpro.BDAPELIDOUNICO,
    cadpro.BDDESCRICAOUNICA,
    cadpro.BDCODIGOEAN
FROM tcadpro_vinc proemp
LEFT OUTER JOIN tcadpro CADPRO ON (proemp.bdcodprod = cadpro.bdcodprod)
;

/* CREATE OR ALTER VIEW: VW_TCADPRO_SIMPLES (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TCADPRO_SIMPLES(
BDCODPROD,
BDCODEMP,
BDGRUPO,
BDCODCSTIPIENT,
BDCODCSTCOFENT,
BDCODCSTPISENT,
BDCODCSTPISSAI,
BDCODCSTCOFSAI,
BDCODCSTIPISAI,
BDCODCSTICMS,
BDCODUNIMED,
BDCODTABINCID,
BDORDEMMARCA,
BDNCMPROD,
BDALIQICMS,
BDALIQICMSST,
BDALIQIPI,
BDALIQPIS,
BDALIQPISENT,
BDALIQCOF,
BDALIQCOFENT,
BDCAPVOL,
BDDESCPROD,
BDAPEPROD,
BDCODSAIDA,
BDINATIVO,
BDCODTIPO)
 AS 
SELECT
    PROEMP.BDCODPROD,
    PROEMP.BDCODEMP,
    PROEMP.BDGRUPO,
    PROEMP.BDCODCSTIPIENT,
    PROEMP.BDCODCSTCOFENT,
    PROEMP.BDCODCSTPISENT,
    PROEMP.BDCODCSTPISSAI,
    PROEMP.BDCODCSTCOFSAI,
    PROEMP.BDCODCSTIPISAI,
    PROEMP.BDCODCSTICMS,
    PROEMP.BDCODUNIMED,
    PROEMP.BDCODTABINCID,
    PROEMP.BDORDEMMARCA,
    PROEMP.BDNCMPROD,
    PROEMP.BDALIQICMS,
    PROEMP.BDALIQICMSST,
    PROEMP.BDALIQIPI,
    PROEMP.BDALIQPIS,
    PROEMP.BDALIQPISENT,
    PROEMP.BDALIQCOF,
    PROEMP.BDALIQCOFENT,
    PROEMP.BDCAPVOL   ,
    PROEMP.BDDESCPROD ,
    PROEMP.BDAPEPROD  ,
    PROEMP.BDCODSAIDA ,
    PROEMP.BDINATIVO  ,
    PROEMP.BDCODTIPO

FROM tcadpro_vinc PROEMP
LEFT OUTER JOIN tcadpro PRO ON (proemp.bdcodprod = pro.bdcodprod)
;

/* CREATE OR ALTER VIEW: VW_TCIDADE_GOOGLE (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TCIDADE_GOOGLE(
BDCODCID,
BDCODUF,
BDNOMCID,
BDANIVCID,
BDDDD,
BDCODEST,
BDCODIBGE,
BDCODFED,
BDCODPAIS,
BDCODGIARS,
BDSIGLAUF,
BDDESCUF)
 AS 
SELECT
  CID.BDCODCID,
  CID.BDCODUF,
  CID.BDNOMCID,
  CID.BDANIVCID,
  CID.BDDDD,
  CID.BDCODEST,
  CID.BDCODIBGE,
  CID.BDCODFED,
  CID.BDCODPAIS,
  CID.BDCODGIARS,
  UF.BDSIGLAUF,
  UF.BDDESCUF
FROM TCIDADE CID
JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF)
;

/* CREATE OR ALTER VIEW: VW_TCNAE_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TCNAE_REF(
BDCODCNAE,
BDSECAO,
BDTIPOCNAE,
BDCLASSIFICACAO,
BDDESCCNAE,
BDTAXACNAE,
BDREFCNAE)
 AS 
SELECT
    X.BDCODCNAE,
    X.bdsecao,
    X.bdtipocnae,
    X.bdclassificacao,
    X.BDDESCCNAE,
    Y.BDTAXACNAE,
    Y.bdrefcnae
FROM TCNAE X
LEFT OUTER JOIN TCNAE_REF Y ON
     (
      Y.BDCODCNAE = X.BDCODCNAE AND
      Y.BDREFCNAE IN
            (
             SELECT MAX(W.BDREFCNAE)
             FROM TCNAE_REF W
             WHERE Y.BDCODCNAE = X.BDCODCNAE AND Y.BDCODCNAE = W.BDCODCNAE AND
                   CAST(W.BDREFCNAE AS VARCHAR(6)) <=
                      (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
                       FROM rdb$database
                      )
             GROUP BY W.BDCODCNAE
            )
     )
;

CREATE OR ALTER VIEW VW_TCNAE_REF_PGTO(
    BDCODCNAE,
    BDSECAO,
    BDTIPOCNAE,
    BDCLASSIFICACAO,
    BDDESCCNAE,
    BDTAXACNAE,
    BDREFCNAE)
AS
SELECT
    X.BDCODCNAE,
    X.bdsecao,
    X.bdtipocnae,
    X.bdclassificacao,
    X.BDDESCCNAE,
    Y.BDTAXACNAE,
    Y.bdrefcnae
FROM TCNAE X
LEFT OUTER JOIN TCNAE_REF Y ON
     (
      Y.BDCODCNAE = X.BDCODCNAE AND
      Y.BDREFCNAE IN
            (
             SELECT MAX(W.BDREFCNAE)
             FROM TCNAE_REF W
             WHERE Y.BDCODCNAE = X.BDCODCNAE AND Y.BDCODCNAE = W.BDCODCNAE AND
                   CAST(W.BDREFCNAE AS VARCHAR(6)) <=
                      (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMESPGTO'))
                       FROM rdb$database
                      )
             GROUP BY W.BDCODCNAE
            )
     )
;


/* CREATE OR ALTER VIEW: VW_TCOLCON_CALCDIA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TCOLCON_CALCDIA(
BDCODEMP,
BDCODCOL,
BDDATACOL,
BDCODMAS,
BDSALBASECOL,
BDDATAEFEITO)
 AS 
SELECT BASE.bdCODEMP, BASE.bdCODCOL, max(BASE.bdDATACOL), max(DIA.bdCODMAS), max(DIA.bdSALBASECOL), max(DIA.bddataefeito)
FROM
(
  SELECT
    col.bdCODEMP, col.bdCODCOL,
    COALESCE
    (
      (SELECT MAX(d1.bddatacol) FROM vrh_emp_tcolcon_calcdia d1 WHERE d1.bdcodemp = col.bdcodemp AND d1.bdcodcol = col.bdcodcol AND d1.BDDATACOL <= (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES'))) AS DATE) FROM rdb$database)),
      (SELECT MIN(d2.bddatacol) FROM vrh_emp_tcolcon_calcdia d2 WHERE d2.bdcodemp = col.bdcodemp AND d2.bdcodcol = col.bdcodcol)
    ) AS bdDATACOL
  FROM vrh_emp_tcolcon col
) AS BASE, vrh_emp_tcolcon_calcdia DIA
WHERE DIA.bdCODEMP = BASE.bdCODEMP AND DIA.bdCODCOL = BASE.bdCODCOL AND DIA.bdDATACOL = BASE.bdDATACOL and DIA.bddataefeito = (
       select MAX(Y.BDDATAEFEITO)
       from vrh_emp_tcolcon_calcdia Y
       where Y.BDCODEMP = DIA.BDCODEMP and Y.BDCODCOL = DIA.BDCODCOL and
             Y.BDDATACOL <=
                (select CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES'))) as DATE)
                 from rdb$database
                )
      )
group by BASE.bdCODEMP, BASE.bdCODCOL
;

/* CREATE OR ALTER VIEW: VW_TCOLCON_DIA_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TCOLCON_DIA_ATUAL(
BDCODEMP,
BDCODCOL,
BDDATACOL)
 AS 
SELECT X.BDCODEMP, X.BDCODCOL, X.BDDATACOL
FROM VRH_EMP_TCOLCON_DIA X
WHERE X.BDDATACOL =
      (
       SELECT MAX(Y.BDDATACOL)
       FROM VRH_EMP_TCOLCON_DIA Y
       WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND
             Y.BDDATACOL <=
                (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES'))) AS DATE)
                 FROM rdb$database
                )
      )
;

/* CREATE OR ALTER VIEW: VW_TCOLCON_REF_ATUAL (ViwData.CreateDependDef) */
/* View: VW_TCOLCON_REF_ATUAL */
CREATE OR ALTER VIEW VW_TCOLCON_REF_ATUAL(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDUTILIZADESCSIMPLIFICADO)
AS
SELECT X.BDCODEMP, X.BDCODCOL, X.BDREFCOL, X.BDUTILIZADESCSIMPLIFICADO
FROM VRH_EMP_TCOLCON_REF X
WHERE X.BDREFCOL =
      (
       SELECT MAX(Y.BDREFCOL)
       FROM VRH_EMP_TCOLCON_REF Y
       WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND
             CAST(Y.BDREFCOL AS VARCHAR(6)) <=
                (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
                 FROM rdb$database
                )
      )
;

/* CREATE OR ALTER VIEW: VW_TCOLCON_VINCDIA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TCOLCON_VINCDIA(
    BDCODEMP,
    BDCODCOL,
    BDDATACOL,
    BDCODPLAFUC,
    BDCODTFUC,
    BDCODPQUA,
    BDCODQH,
    BDREGJORTRAB,
    BDTIPOESCALA)
AS
SELECT X.BDCODEMP, X.BDCODCOL, X.BDDATACOL,
       X.BDCODPLAFUC, X.BDCODTFUC, X.BDCODPQUA, X.BDCODQH, X.BDREGJORTRAB, X.bdtipoescala
FROM
(
  SELECT
    col.bdCODEMP,
    col.bdCODCOL,
    COALESCE
    (
      (SELECT MAX(d1.bddatacol) FROM vrh_emp_tcol_vincdia d1 WHERE d1.bdcodemp = col.bdcodemp AND d1.bdcodcol = col.bdcodcol AND d1.BDDATACOL <= (SELECT CAST(TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) AS DATE) FROM rdb$database)),
      (SELECT MIN(d2.bddatacol) FROM vrh_emp_tcol_vincdia d2 WHERE d2.bdcodemp = col.bdcodemp AND d2.bdcodcol = col.bdcodcol)
    ) AS bdDATACOL
  FROM vrh_emp_tcolcon col
) AS BASE, VRH_EMP_TCOL_VINCDIA X
WHERE BASE.BDCODEMP = X.BDCODEMP AND BASE.BDCODCOL = X.BDCODCOL AND BASE.BDDATACOL = X.BDDATACOL
;

/*
select X.BDCODEMP, X.BDCODCOL, X.BDDATACOL,
       X.BDCODPLAFUC, X.BDCODTFUC, X.BDCODPQUA, X.BDCODQH
from VRH_EMP_TCOL_VINCDIA X
where X.BDDATACOL =
      (
       select MAX(Y.BDDATACOL)
       from VRH_EMP_TCOL_VINCDIA Y
       where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and
             Y.BDDATACOL <=
                (select CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES'))) as DATE)
                 from rdb$database
                )
      )  */
;

/* CREATE OR ALTER VIEW: VW_TEMP_SPED_FCONT_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TEMP_SPED_FCONT_REF(
BDCODEMP,
BDCODENQFED)
 AS 
SELECT
    X.bdcodemp,
    X.bdexpfcont

FROM TEMP_SPED_FCONT_REF X
WHERE X.bdrefemp IN
            (
             SELECT MAX(Y.bdrefemp)
             FROM TEMP_SPED_FCONT_REF Y
             WHERE Y.bdcodemp = X.bdcodemp AND
                   CAST(Y.bdrefemp AS VARCHAR(6)) <=
                      (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
                       FROM rdb$database
                      )
             GROUP BY Y.bdcodemp
            )
;

/* CREATE OR ALTER VIEW: VW_TEMPRESAIMPOSTO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TEMPRESAIMPOSTO(
BDCODEMP,
BDREFEMP,
BDREFFIMIMP,
BDCODIMP,
BDDESCIMP,
BDDATACRIACAO,
BDDATAEXTINTO,
BDCOMPETENCIA,
BDDOCARRECADACAO,
BDPERAPURACAO,
BDDIAVENCTO,
BDANTECIPA,
BDMESVENCTO,
BDJUROSDIA,
BDVLRJUROS,
BDJUROSDIAMES,
BDMULTADIA,
BDVLRMULTA,
BDMULTADIAMES,
BDVLRMAXMULTA,
BDALIQIMPOSTO,
BDLIMITEISENCAO,
BDTIPORETENCAO,
BDCODREC,
BDCODIND,
BDRETBCCALCULOIMP,
BDDESCREC,
BDTIPOIMPOSTO,
BDGPSPRINCIPAL,
BDCODRECOF)
 AS 
SELECT
    ei.bdcodemp,
    ei.bdrefemp,
    ei.bdreffimimp,
    ei.bdcodimp,
    imp.bddescimp,
    imp.bddatacriacao,
    imp.bddataextinto,
    imp.bdcompetencia,
    imp.bddocarrecadacao,
    imp.bdperapuracao,
    imp.bddiavencto,
    imp.bdantecipa,
    imp.bdmesvencto,
    imp.bdjurosdia,
    imp.bdvlrjuros,
    imp.bdjurosdiames,
    imp.bdmultadia,
    imp.bdvlrmulta,
    imp.bdmultadiames,
    imp.bdvlrmaxmulta,
    imp.bdaliqimposto,
    imp.bdlimiteisencao,
    imp.bdtiporetencao,
--    imp.bdformulaimp,
    imp.bdcodrec,
    imp.bdcodind,
    imp.bdretbccalculoimp,
    rec.bddescrec,
    rec.bdtipoimposto,
    imp.BDGPSPRINCIPAL,
    REC.BDCODRECOF
FROM tempresaimposto ei,
     timposto imp
LEFT OUTER JOIN tcodrec rec ON (imp.bdcodrec = rec.bdcodrec)
WHERE ei.bdcodimp = imp.bdcodimp
;

/* CREATE OR ALTER VIEW: VW_TEMPRESAIMPOSTOREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TEMPRESAIMPOSTOREF(
BDCODEMP,
BDREFEMP,
BDREFFIMIMP,
BDCODIMP,
BDDESCIMP,
BDDATACRIACAO,
BDDATAEXTINTO,
BDCOMPETENCIA,
BDDOCARRECADACAO,
BDPERAPURACAO,
BDDIAVENCTO,
BDANTECIPA,
BDMESVENCTO,
BDJUROSDIA,
BDVLRJUROS,
BDJUROSDIAMES,
BDMULTADIA,
BDVLRMULTA,
BDMULTADIAMES,
BDVLRMAXMULTA,
BDALIQIMPOSTO,
BDLIMITEISENCAO,
BDTIPORETENCAO,
BDCODREC,
BDCODIND,
BDRETBCCALCULOIMP,
BDDESCREC,
BDTIPOIMPOSTO,
BDGPSPRINCIPAL,
BDCODSIS,
BDTIPOIMPDOC,
BDCODRECOF)
 AS 
SELECT
    x.bdcodemp,
    x.bdrefemp,
    x.bdreffimimp,
    x.bdcodimp,
    i.bddescimp,
    i.bddatacriacao,
    i.bddataextinto,
    i.bdcompetencia,
    i.bddocarrecadacao,
    i.bdperapuracao,
    i.bddiavencto,
    i.bdantecipa,
    i.bdmesvencto,
    i.bdjurosdia,
    i.bdvlrjuros,
    i.bdjurosdiames,
    i.bdmultadia,
    i.bdvlrmulta,
    i.bdmultadiames,
    i.bdvlrmaxmulta,
    i.bdaliqimposto,
    i.bdlimiteisencao,
    i.bdtiporetencao,
    i.bdcodrec,
    i.bdcodind,
    i.bdretbccalculoimp,
    x.bddescrec,
    x.bdtipoimposto,
    i.BDGPSPRINCIPAL,
    i.BDCODSIS,
    i.bdtipoimpdoc,
    X.BDCODRECOF
FROM vw_tempresaimposto x
LEFT OUTER JOIN timposto i ON (i.bdcodimp = x.bdcodimp)
WHERE  (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER) FROM rdb$database) >= x.BDREFEMP AND
       ((x.BDREFFIMIMP IS NULL) OR (x.BDREFFIMIMP = 0) OR (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER) FROM rdb$database) <= x.BDREFFIMIMP)
;

/* CREATE OR ALTER VIEW: VW_TEMPRESAS_REF_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TEMPRESAS_REF_MIN(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
  X.BDCODEMP,
  MIN(X.bdREFEMP)
FROM
  TEMPRESAS_REF X
GROUP BY X.BDCODEMP
;

/* View: VW_TEMPRESAS_REF_JOIN */
CREATE OR ALTER VIEW VW_TEMPRESAS_REF_JOIN(
    BDCODEMP,
    BDREFEMP,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDCODCENTROS,
    BDCODCID,
    BDCODCONT,
    BDCODCONTEF,
    BDCODCONTRH,
    BDCODNATJUR,
    BDCODCNAE,
    BDNOMEMP,
    BDNOMREDUZEMP,
    BDNOMFANEMP,
    BDAPEEMP,
    BDENDEMP,
    BDNUMEMP,
    BDBAIEMP,
    BDCEPEMP,
    BDDDDEMP,
    BDFONEEMP,
    BDFAXEMP,
    BDEMAILEMP,
    BDCOMPLEMP,
    BDLOGREMP,
    BDIEEMP,
    BDIMEMP,
    BDSITEMP,
    BDDDDFAXEMP,
    BDDOCAUXILIAR,
    BDCODPLANOONLINE,
    BDCODPLATRIB,
    BDOPCAOESOCIAL,
    BDOPCAOESOCIALDESC,
    BDDESCCARTEMP,
    BDORGAOEMP,
    BDDATAREGEMP,
    BDNOMECARTORIO,
    BDLIVRO,
    BDFOLHA,
    BDNAOCONTCENTROCUSTO)
AS
SELECT
    X.BDCODEMP,
    X.BDREFEMP,
    X.BDCODPLAPADRAO,
    X.BDCODHIST,
    X.BDCODCENTROS,
    X.BDCODCID,
    X.BDCODCONT,
    X.BDCODCONTEF,
    X.BDCODCONTRH,
    X.BDCODNATJUR,
    X.BDCODCNAE,
    X.BDNOMEMP,
    X.BDNOMREDUZEMP,
    X.BDNOMFANEMP,
    X.BDAPEEMP,
    X.BDENDEMP,
    X.BDNUMEMP,
    X.BDBAIEMP,
    X.BDCEPEMP,
    X.BDDDDEMP,
    X.BDFONEEMP,
    X.BDFAXEMP,
    X.BDEMAILEMP,
    X.BDCOMPLEMP,
    X.BDLOGREMP,
    X.BDIEEMP,
    X.BDIMEMP,
    X.BDSITEMP,
    X.BDDDDFAXEMP,
    X.BDDOCAUXILIAR,
    X.BDCODPLANOONLINE,
    X.BDCODPLATRIB,
    X.BDOPCAOESOCIAL,
    ESOCIALTIPODADOS.BDDESCRICAO,
    x.bddesccartempref, 
    x.bdorgaoemp,
    x.bddataregemp, 
    x.bdnomecartorio,
    x.bdlivro,
    x.bdfolha,
    x.bdnaocontcentrocusto

FROM TEMPRESAS_REF X
LEFT OUTER JOIN VW_TEMPRESAS_REF_MAX XMAX ON (X.BDCODEMP = XMAX.BDCODEMP)
JOIN VW_TEMPRESAS_REF_MIN XMIN ON (X.BDCODEMP = XMIN.BDCODEMP)
LEFT OUTER JOIN VRH_ESOCIAL_TTIPODADOS  ESOCIALTIPODADOS ON (ESOCIALTIPODADOS.BDOPCAOESOCIAL = X.BDOPCAOESOCIAL)
WHERE X.BDREFEMP = COALESCE(XMAX.BDREFEMP,XMIN.BDREFEMP)
;

/* CREATE OR ALTER VIEW: VW_TEMPRESAS_REF_MAX_MIN_USU (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TEMPRESAS_REF_MAX_MIN_USU(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
emp.bdcodemp,

  COALESCE(

    (
      SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x
      WHERE x.bdcodemp = emp.bdcodemp AND
      CAST(X.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
      ORDER BY x.bdrefemp DESC
     )

    ,
     (SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x
       WHERE x.bdcodemp = emp.bdcodemp
       ORDER BY x.bdrefemp
      )
    ) BDREFEMP

FROM tempresas emp
where((bdexcluiremp is null)or(upper(bdexcluiremp)<>'TRUE'))
;

/* CREATE OR ALTER VIEW: VW_TEMPRESAS_REF_SEM_USU (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TEMPRESAS_REF_SEM_USU(
    BDCODEMP,
    BDREFEMP,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDCODCENTROS,
    BDCODCID,
    BDCODCONT,
    BDCODCONTEF,
    BDCODCONTRH,
    BDCODNATJUR,
    BDCODCNAE,
    BDNOMEMP,
    BDAPEEMP,
    BDENDEMP,
    BDNUMEMP,
    BDBAIEMP,
    BDCEPEMP,
    BDDDDEMP,
    BDFONEEMP,
    BDFAXEMP,
    BDEMAILEMP,
    BDCOMPLEMP,
    BDLOGREMP,
    BDIEEMP,
    BDIMEMP,
    BDSITEMP,
    BDDDDFAXEMP,
    BDDOCAUXILIAR,
    BDCODPLANOONLINE,
    BDDDDCELULAREMP,
    BDCELULAREMP,
    BDDESCCARTEMP,
    BDORGAOEMP,
    BDDATAREGEMP,
    BDNOMECARTORIO,
    BDLIVRO,
    BDFOLHA,
    BDEXIBEINFOCOLLAN)
AS
SELECT
    emp.BDCODEMP,
    emp.BDREFEMP,
    dad.BDCODPLAPADRAO,
    dad.BDCODHIST,
    dad.BDCODCENTROS,
    dad.BDCODCID,
    dad.BDCODCONT,
    dad.BDCODCONTEF,
    dad.BDCODCONTRH,
    dad.BDCODNATJUR,
    dad.BDCODCNAE,
    dad.BDNOMEMP,
    dad.BDAPEEMP,
    dad.BDENDEMP,
    dad.BDNUMEMP,
    dad.BDBAIEMP,
    dad.BDCEPEMP,
    dad.BDDDDEMP,
    dad.BDFONEEMP,
    dad.BDFAXEMP,
    dad.BDEMAILEMP,
    dad.BDCOMPLEMP,
    dad.BDLOGREMP,
    dad.BDIEEMP,
    dad.BDIMEMP,
    dad.BDSITEMP,
    dad.BDDDDFAXEMP,
    dad.BDDOCAUXILIAR,
    dad.BDCODPLANOONLINE,
    dad.BDDDDCELULAREMP,
    dad.BDCELULAREMP,
    dad.bddesccartempref,
    dad.bdorgaoemp, 
    dad.bddataregemp, 
    dad.bdnomecartorio, 
    dad.bdlivro, 
    dad.bdfolha,
    dad.bdexibeinfocollan
FROM VW_TEMPRESAS_REF_MAX_MIN_usu emp
JOIN tempresas_ref dad ON (dad.bdcodemp = emp.bdCODEMP AND dad.bdrefemp = emp.bdrefemp)
;

/* CREATE OR ALTER VIEW: VW_TENQFED (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TENQFED(
    BDCODEMP,
    BDCODENQFED,
    BDFORMATRIBUTACAO)
AS
/* #Alt:12174 - Incluído o campo BDFORMATRIBUTACAO    */
/*SELECT
    emp.bdcodemp,

    (
      SELECT FIRST 1 Y.bdcodenqfed
      FROM TENQFED Y
      WHERE Y.bdcodemp = emp.bdcodemp
      AND Y.bdrefemp <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))   FROM rdb$database)
      ORDER BY y.bdcodemp DESC, y.bdrefemp DESC
    )
FROM tempresas emp    */
SELECT
  emp.bdcodemp, enqFed.bdcodenqfed, enqFed.bdformatributacao
FROM (SELECT emp.bdcodemp,
             (SELECT FIRST 1 Y.bdrefemp
              FROM TENQFED Y
              WHERE Y.bdcodemp = emp.bdcodemp
              AND Y.bdrefemp <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))   FROM rdb$database)
              ORDER BY y.bdcodemp DESC, y.bdrefemp DESC) AS BDREFEMP
      FROM tempresas emp) emp, tenqfed enqFed
WHERE
enqFed.bdcodemp = emp.bdcodemp AND
enqFed.bdrefemp = emp.bdrefemp
;

/* View: VW_TENQFED_PGTO */
CREATE OR ALTER VIEW VW_TENQFED_PGTO(
    BDCODEMP,
    BDCODENQFED,
    BDFORMATRIBUTACAO)
AS
SELECT
  emp.bdcodemp, enqFed.bdcodenqfed, enqFed.bdformatributacao
FROM (SELECT emp.bdcodemp,
             (SELECT FIRST 1 Y.bdrefemp
              FROM TENQFED Y
              WHERE Y.bdcodemp = emp.bdcodemp
              AND Y.bdrefemp <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMESPGTO'))   FROM rdb$database)
              ORDER BY y.bdcodemp DESC, y.bdrefemp DESC) AS BDREFEMP
      FROM tempresas emp) emp, tenqfed enqFed
WHERE
enqFed.bdcodemp = emp.bdcodemp AND
enqFed.bdrefemp = emp.bdrefemp
;

/* CREATE OR ALTER VIEW: VW_TFERIADOS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TFERIADOS(
BDDATAFER,
BDCODCID,
BDCODUF,
BDDESCFER,
BDREFFER)
 AS 
SELECT
  bddatafer,
  bdcodcid,
  bdcoduf,
  bddescfer,
  CAST((SUBSTRING(CAST(bddatafer AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(bddatafer AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER)
FROM tferiados
;

/* CREATE OR ALTER VIEW: VW_TINDVAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TINDVAL(
BDCODIND,
BDREFIND,
BDDATAIND,
BDVALIND)
 AS 
SELECT
  BDCODIND,
  --CAST((substring(BDREFIND FROM 1 FOR 6)) AS INTEGER),  --alt:6178 - 06/11/2015 - Trocado para overlay visando melhoria de desempenho. Pedro
  CAST((OVERLAY(BDREFIND PLACING '' FROM 7 FOR 2)) AS INTEGER),
  --alt:6178 - 06/11/2015 - Adicionado para retornar a referência em formato data com os devidos tratamentos. Pedro
  CAST(SUBSTRING(BDREFIND FROM 5 FOR 2) ||'/'|| REPLACE(CASE WHEN CHAR_LENGTH(BDREFIND) > 6 THEN OVERLAY(BDREFIND PLACING '' FROM 1 FOR 6) ELSE '01' END, '00', '01') ||'/'|| OVERLAY(BDREFIND PLACING '' FROM 5 FOR 4) AS DATE),
  COALESCE(BDVALIND, 0)

FROM
  TINDVAL
;

/* CREATE OR ALTER VIEW: VW_TMENURAPIDO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TMENURAPIDO(
BDCODSIS,
BDCAPTIONMENU,
BDFORMMENU,
BDCHAVEPESQUISAMENU,
BDCAMINHOMENU,
BDTIPOMENU,
BDNOMSIS)
 AS 
SELECT
    X.bdcodsis,
    X.bdcaptionmenu,
    X.bdformmenu,
    X.bdchavepesquisamenu,
    X.bdcaminhomenu,
    X.bdtipomenu,
    Y.bdnomsis
FROM tmenurapido X
LEFT OUTER JOIN tsistema Y ON (Y.bdcodsis = X.bdcodsis)
;

/* CREATE OR ALTER VIEW: VW_TOMADORES (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TOMADORES(
BDCODCENTRO,
BDCODTPCC,
BDCTALON,
BDTIPCTA,
BDNOMCTA,
BDAPECTA,
BDFILTROGER,
BDCLANOM,
BDTIPO,
BDCNPJTOM,
BDTIPOTOM,
BDTIPOFERTOM,
BDSOMSALFERTOM,
BDTIPO13TOM,
BDSOMSAL13TOM,
BDNOMETOM,
BDAPELIDO,
BDNOME,
BDCODTER)
 AS 
SELECT
  TPCC.BDCODCENTRO,
  TPCC.BDCODTPCC,
  TPCC.BDCTALON,
  TPCC.BDTIPCTA,
  TPCC.BDNOMCTA,
  TPCC.BDAPECTA,
  TPCC.BDFILTROGER,
  TPCC.BDCLANOM,
  TPCC.BDTIPO,
  TOM.BDCNPJTOM,
  TOM.BDTIPOTOM,
  TOM.BDTIPOFERTOM,
  TOM.BDSOMSALFERTOM,
  TOM.BDTIPO13TOM,
  TOM.BDSOMSAL13TOM,
  TOM.BDNOMETOM,
  PCC.BDAPELIDO,
  PCC.BDNOME,
  TOM.BDCODTER
FROM centros_tpcc TPCC
LEFT OUTER JOIN vrh_base_tcustom TOM
  ON (TOM.BDCODCENTRO = TPCC.BDCODCENTRO AND TOM.BDCODTPCC = TPCC.BDCODTPCC)
LEFT OUTER JOIN tcentros PCC
  ON (PCC.BDCODCENTRO = TPCC.BDCODCENTRO)
;

/* CREATE OR ALTER VIEW: VW_TOMADORES_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TOMADORES_REF(
    BDCODCENTRO,
    BDCODTPCC,
    BDCODCID,
    BDLOGRTOM,
    BDENDTOM,
    BDNUMCTOM,
    BDBAITOM,
    BDCEPTOM,
    BDDDDTOM,
    BDFONETOM,
    BDCOMPLTOM,
    BDCODREC,
    BDCODRECTRANSP,
    BDCODENQFED,
    BDCODCNAE,
    BDEMPTOM,
    BDAUTTOM,
    BDCOLTOM,
    BDTAXSERTOM,
    BDDADCADTOM,
    BDDADPERTOM,
    BDCODFPAS,
    BDPERTERC,
    BDCODRECTERC,
    BDCODRECOF,
    BDINATIVO)
AS
SELECT CCREF.BDCODCENTRO,
       CCREF.BDCODTPCC,
       CCEND.BDCODCID,
       CCEND.BDLOGRTOM,
       CCEND.BDENDTOM,
       CCEND.BDNUMCTOM,
       CCEND.BDBAITOM,
       CCEND.BDCEPTOM,
       CCEND.BDDDDTOM,
       CCEND.BDFONETOM,
       CCEND.BDCOMPLTOM,
       CCGPS.BDCODREC,
       CCGPS.BDCODRECTRANSP,
       CCGPS.BDCODENQFED,
       CCGPS.BDCODCNAE,
       CCGPS.BDEMPTOM,
       CCGPS.BDAUTTOM,
       CCGPS.BDCOLTOM,
       CCGPS.BDTAXSERTOM,
       CCGPS.BDDADCADTOM,
       CCGPS.BDDADPERTOM,
       FPASTERC.BDCODFPAS,
       FPASTERC.BDPERTERC,
       CCGPS.BDCODRECTERC,
       TREC.BDCODRECOF,
       CCREF.BDINATIVO
FROM vrh_base_tcustom_ref CCREF
LEFT OUTER JOIN vrh_base_tcustom_end CCEND
  ON (CCEND.bdCODCENTRO = CCREF.BDCODCENTRO AND CCEND.BDCODTPCC = CCREF.BDCODTPCC AND CCEND.BDREFCUSTO = CCREF.BDREFCUSTO)
LEFT OUTER JOIN vrh_base_tcustom_gps CCGPS
  ON (CCGPS.bdCODCENTRO = CCREF.BDCODCENTRO AND CCGPS.BDCODTPCC = CCREF.BDCODTPCC AND CCGPS.BDREFCUSTO = CCREF.BDREFCUSTO)
LEFT OUTER JOIN VRH_BASE_TFPAS_TERCEIROS FPASTERC
  ON (FPASTERC.BDCODFPASTERC = CCGPS.BDCODFPASTERC)
LEFT OUTER JOIN tcodrec TREC ON (TREC.BDCODREC = CCGPS.bdcodrec);

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TCUSTOM_END (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TCUSTOM_END(
BDCODCENTRO,
BDCODTPCC,
BDREFCUSTO,
BDCODCID,
BDLOGRTOM,
BDENDTOM,
BDNUMCTOM,
BDBAITOM,
BDCEPTOM,
BDDDDTOM,
BDFONETOM,
BDCOMPLTOM)
 AS 
SELECT
    X.bdcodcentro,
    X.bdcodtpcc,
    X.bdrefcusto,
    X.bdcodcid,
    X.bdlogrtom,
    X.bdendtom,
    X.bdnumctom,
    X.bdbaitom,
    X.bdceptom,
    X.bddddtom,
    X.bdfonetom,
    X.bdcompltom
FROM vrh_base_tcustom_end X
WHERE X.bdrefcusto IN
            (
             SELECT MAX(Y.bdrefcusto)
             FROM vrh_base_tcustom_end Y
             WHERE Y.bdcodcentro = X.bdcodcentro AND Y.bdcodtpcc = X.bdcodtpcc AND
                   CAST(Y.bdrefcusto AS VARCHAR(6)) <=
                      (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
                       FROM rdb$database
                      )
             GROUP BY Y.bdcodcentro, Y.bdcodtpcc
            )
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TCUSTOM_GPS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TCUSTOM_GPS(
    BDCODGPS,
    BDCODRECTRANSP,
    BDCODFPASTERC,
    BDCODMEN,
    BDCODENQFED,
    BDCODCNAE,
    BDCODCENTRO,
    BDCODTPCC,
    BDREFCUSTO,
    BDEMPTOM,
    BDAUTTOM,
    BDCOLTOM,
    BDTAXSERTOM,
    BDDADCADTOM,
    BDDADPERTOM,
    BDFAPTOM,
    BDSIMPLESGPSTOM,
    BDCODFPAS,
    BDCODTERC,
    BDPERTERC,
    BDCODRECTERC,
    BDCODRECOF,
    BDATVANEXOSSN,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO,
    BDANEXOIII,
    BDANEXOIV,
    BDANEXOV,
    BDANEXOVI,
    BDDESONOBRA,
    BDRAT,
    BDCODIGOTERC,
    BDSALEDU,
    BDINCRA,
    BDSENAI,
    BDSESI,
    BDSENAC,
    BDSESC,
    BDSEBRAE,
    BDDPC,
    BDFUNAERO,
    BDSENAR,
    BDSEST,
    BDSENAT,
    BDSESCOOP,
    BDATUTAB)
AS
SELECT
    TREC.BDCODRECOF,
    X.bdcodrectransp,
    X.bdcodfpasterc,
    X.bdcodmen,
    X.bdcodenqfed,
    X.bdcodcnae,
    X.bdcodcentro,
    X.bdcodtpcc,
    X.bdrefcusto,
    X.bdemptom,
    X.bdauttom,
    X.bdcoltom,
    X.bdtaxsertom,
    X.bddadcadtom,
    X.bddadpertom,
    X.bdfaptom,
    X.bdsimplesgpstom,
    w.bdcodfpas,
    TER.bdcodterc,
      coalesce(w.BDSALEDU, 0) + coalesce(w.BDINCRA, 0) +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSENAI, 0) * 0.5 else coalesce(w.BDSENAI, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSESI, 0) * 0.5 else coalesce(w.BDSESI, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSENAC, 0) * 0.5 else coalesce(w.BDSENAC, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSESC, 0) * 0.5 else coalesce(w.BDSESC, 0) end +
      coalesce(w.BDSEBRAE, 0) +
      coalesce(w.BDDPC, 0) +
      coalesce(w.BDFUNAERO, 0) +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSENAR, 0) * 0.5 else coalesce(w.BDSENAR, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSEST, 0) * 0.5 else coalesce(w.BDSEST, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSENAT, 0) * 0.5 else coalesce(w.BDSENAT, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSESCOOP, 0) * 0.5 else coalesce(w.BDSESCOOP, 0) end
      ,
    X.BDCODRECTERC,
    TREC.BDCODRECOF,
    x.BDATVANEXOSSN,
    x.BDCOMERCIO,
    x.BDINDUSTRIA,
    x.BDSERVICO,
    x.BDANEXOIII,
    x.BDANEXOIV,
    x.BDANEXOV,
    x.BDANEXOVI,
    x.BDDESONOBRA,
    x.BDRAT,
    w.bdcodterc,
    w.BDSALEDU,
    w.BDINCRA,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSENAI, 0) * 0.5 else w.BDSENAI end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSESI, 0) * 0.5 else w.BDSESI end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSENAC, 0) * 0.5 else w.BDSENAC end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSESC, 0) * 0.5 else w.BDSESC end,
    w.BDSEBRAE,
    w.BDDPC,
    w.BDFUNAERO,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSENAR, 0) * 0.5 else w.BDSENAR end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSEST, 0) * 0.5 else w.BDSEST end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSENAT, 0) * 0.5 else w.BDSENAT end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSESCOOP, 0) * 0.5 else w.BDSESCOOP end,
    w.BDATUTAB
FROM
(
  SELECT
      X.bdcodcentro,
      X.bdcodtpcc,
      COALESCE
  (
      (SELECT MAX(d2.bdrefcusto) FROM vrh_base_tcustom_gps d2 WHERE d2.bdcodcentro = x.bdcodcentro AND d2.bdcodtpcc = x.bdcodtpcc AND CAST(d2.BDREFCUSTO AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefcusto) FROM vrh_base_tcustom_gps d1 WHERE d1.bdcodcentro = x.bdcodcentro AND d1.bdcodtpcc = x.bdcodtpcc)
  ) AS bdrefcusto,
  (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) BDREFATU FROM rdb$database) BDREFATU
  FROM CENTROS_TPCC x
) AS BASE
JOIN vrh_base_tcustom_gps X ON (X.BDCODCENTRO = BASE.BDCODCENTRO AND X.BDCODTPCC = BASE.BDCODTPCC AND X.BDREFCUSTO = BASE.BDREFCUSTO)
LEFT OUTER JOIN VRH_BASE_TFPAS_TERCEIROS w ON (w.bdcodfpasterc = x.bdcodfpasterc)
LEFT OUTER JOIN TCODREC TREC ON (TREC.BDCODREC = X.BDCODREC)
LEFT OUTER JOIN VRH_BASE_TTERCEIROS TER ON (TER.BDCODIGO = w.BDCODTERC)
;

/* View: VW_VRH_BASE_TCUSTOM_GPS_PGTO */
CREATE OR ALTER VIEW VW_VRH_BASE_TCUSTOM_GPS_PGTO(
    BDCODGPS,
    BDCODRECTRANSP,
    BDCODFPASTERC,
    BDCODMEN,
    BDCODENQFED,
    BDCODCNAE,
    BDCODCENTRO,
    BDCODTPCC,
    BDREFCUSTO,
    BDEMPTOM,
    BDAUTTOM,
    BDCOLTOM,
    BDTAXSERTOM,
    BDDADCADTOM,
    BDDADPERTOM,
    BDFAPTOM,
    BDSIMPLESGPSTOM,
    BDCODFPAS,
    BDCODTERC,
    BDPERTERC,
    BDCODRECTERC,
    BDCODRECOF,
    BDATVANEXOSSN,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO,
    BDANEXOIII,
    BDANEXOIV,
    BDANEXOV,
    BDANEXOVI,
    BDDESONOBRA,
    BDRAT,
    BDCODIGOTERC,
    BDSALEDU,
    BDINCRA,
    BDSENAI,
    BDSESI,
    BDSENAC,
    BDSESC,
    BDSEBRAE,
    BDDPC,
    BDFUNAERO,
    BDSENAR,
    BDSEST,
    BDSENAT,
    BDSESCOOP,
    BDATUTAB)
AS
SELECT
    TREC.BDCODRECOF,
    X.bdcodrectransp,
    X.bdcodfpasterc,
    X.bdcodmen,
    X.bdcodenqfed,
    X.bdcodcnae,
    X.bdcodcentro,
    X.bdcodtpcc,
    X.bdrefcusto,
    X.bdemptom,
    X.bdauttom,
    X.bdcoltom,
    X.bdtaxsertom,
    X.bddadcadtom,
    X.bddadpertom,
    X.bdfaptom,
    X.bdsimplesgpstom,
    w.bdcodfpas,
    TER.bdcodterc,
      coalesce(w.BDSALEDU, 0) + coalesce(w.BDINCRA, 0) +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSENAI, 0) * 0.5 else coalesce(w.BDSENAI, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSESI, 0) * 0.5 else coalesce(w.BDSESI, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSENAC, 0) * 0.5 else coalesce(w.BDSENAC, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSESC, 0) * 0.5 else coalesce(w.BDSESC, 0) end +
      coalesce(w.BDSEBRAE, 0) +
      coalesce(w.BDDPC, 0) +
      coalesce(w.BDFUNAERO, 0) +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSENAR, 0) * 0.5 else coalesce(w.BDSENAR, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSEST, 0) * 0.5 else coalesce(w.BDSEST, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSENAT, 0) * 0.5 else coalesce(w.BDSENAT, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSESCOOP, 0) * 0.5 else coalesce(w.BDSESCOOP, 0) end
      ,
    X.BDCODRECTERC,
    TREC.BDCODRECOF,
    x.BDATVANEXOSSN,
    x.BDCOMERCIO,
    x.BDINDUSTRIA,
    x.BDSERVICO,
    x.BDANEXOIII,
    x.BDANEXOIV,
    x.BDANEXOV,
    x.BDANEXOVI,
    x.BDDESONOBRA,
    x.BDRAT,
    w.bdcodterc,
    w.BDSALEDU,
    w.BDINCRA,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSENAI, 0) * 0.5 else w.BDSENAI end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSESI, 0) * 0.5 else w.BDSESI end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSENAC, 0) * 0.5 else w.BDSENAC end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSESC, 0) * 0.5 else w.BDSESC end,
    w.BDSEBRAE,
    w.BDDPC,
    w.BDFUNAERO,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSENAR, 0) * 0.5 else w.BDSENAR end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSEST, 0) * 0.5 else w.BDSEST end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSENAT, 0) * 0.5 else w.BDSENAT end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 then coalesce(w.BDSESCOOP, 0) * 0.5 else w.BDSESCOOP end,
    w.BDATUTAB
FROM
(
  SELECT
      X.bdcodcentro,
      X.bdcodtpcc,
      COALESCE
  (
      (SELECT MAX(d2.bdrefcusto) FROM vrh_base_tcustom_gps d2 WHERE d2.bdcodcentro = x.bdcodcentro AND d2.bdcodtpcc = x.bdcodtpcc AND CAST(d2.BDREFCUSTO AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMESPGTO')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefcusto) FROM vrh_base_tcustom_gps d1 WHERE d1.bdcodcentro = x.bdcodcentro AND d1.bdcodtpcc = x.bdcodtpcc)
  ) AS bdrefcusto,
  (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMESPGTO')) BDREFATU FROM rdb$database) BDREFATU
  FROM CENTROS_TPCC x
) AS BASE
JOIN vrh_base_tcustom_gps X ON (X.BDCODCENTRO = BASE.BDCODCENTRO AND X.BDCODTPCC = BASE.BDCODTPCC AND X.BDREFCUSTO = BASE.BDREFCUSTO)
LEFT OUTER JOIN VRH_BASE_TFPAS_TERCEIROS w ON (w.bdcodfpasterc = x.bdcodfpasterc)
LEFT OUTER JOIN TCODREC TREC ON (TREC.BDCODREC = X.BDCODREC)
LEFT OUTER JOIN VRH_BASE_TTERCEIROS TER ON (TER.BDCODIGO = w.BDCODTERC)
;

/* CREATE OR ALTER VIEW: VW_TOMADORES_REF_ATU (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TOMADORES_REF_ATU(
    BDCODCENTRO,
    BDCODTPCC,
    BDTIPOTOM,
    BDCNPJTOM,
    BDNOMETOM,
    BDREFCUSTO,
    BDCODCID,
    BDLOGRTOM,
    BDENDTOM,
    BDNUMCTOM,
    BDBAITOM,
    BDCEPTOM,
    BDDDDTOM,
    BDFONETOM,
    BDCOMPLTOM,
    BDCODGPS,
    BDCODRECTRANSP,
    BDCODENQFED,
    BDCODCNAE,
    BDEMPTOM,
    BDAUTTOM,
    BDCOLTOM,
    BDTAXSERTOM,
    BDDADCADTOM,
    BDDADPERTOM,
    BDCODFPAS,
    BDCODTERC,
    BDCODRECTERC,
    BDCODRECOF,
    BDFAPTOM,
    BDCODFPASTERC,
    BDSIMPLESGPSTOM,
    BDPERTERC,
    BDATVANEXOSSN,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO,
    BDANEXOIII,
    BDANEXOIV,
    BDANEXOV,
    BDANEXOVI,
    BDDESONOBRA,
    BDCODIGOTERC,
    BDSALEDU,
    BDINCRA,
    BDSENAI,
    BDSESI,
    BDSENAC,
    BDSESC,
    BDSEBRAE,
    BDDPC,
    BDFUNAERO,
    BDSENAR,
    BDSEST,
    BDSENAT,
    BDSESCOOP,
    BDATUTAB)
AS
SELECT CCREF.BDCODCENTRO,
       CCREF.BDCODTPCC,
       CCREF.BDTIPOTOM,
       CCREF.BDCNPJTOM,
       CCREF.BDNOMETOM,
       CCEND.BDREFCUSTO,
       CCEND.BDCODCID,
       CCEND.BDLOGRTOM,
       CCEND.BDENDTOM,
       CCEND.BDNUMCTOM,
       CCEND.BDBAITOM,
       CCEND.BDCEPTOM,
       CCEND.BDDDDTOM,
       CCEND.BDFONETOM,
       CCEND.BDCOMPLTOM,
       CCGPS.BDCODGPS,
       CCGPS.BDCODRECTRANSP,
       CCGPS.BDCODENQFED,
       CCGPS.BDCODCNAE,
       CCGPS.BDEMPTOM,
       CCGPS.BDAUTTOM,
       CCGPS.BDCOLTOM,
       CCGPS.BDTAXSERTOM,
       CCGPS.BDDADCADTOM,
       CCGPS.BDDADPERTOM,
       CCGPS.BDCODFPAS,
       CCGPS.BDCODTERC,
       CCGPS.BDCODRECTERC,
       CCGPS.BDCODRECOF,
       CCGPS.BDFAPTOM,
       CCGPS.BDCODFPASTERC,
       CCGPS.BDSIMPLESGPSTOM,
       CCGPS.BDPERTERC,
       CCGPS.BDATVANEXOSSN,
       CCGPS.BDCOMERCIO,
       CCGPS.BDINDUSTRIA,
       CCGPS.BDSERVICO,
       CCGPS.BDANEXOIII,
       CCGPS.BDANEXOIV,
       CCGPS.BDANEXOV,
       CCGPS.BDANEXOVI,
       CCGPS.BDDESONOBRA,
       CCGPS.BDCODIGOTERC,
       CCGPS.BDSALEDU,
       CCGPS.BDINCRA,
       CCGPS.BDSENAI,
       CCGPS.BDSESI,
       CCGPS.BDSENAC,
       CCGPS.BDSESC,
       CCGPS.BDSEBRAE,
       CCGPS.BDDPC,
       CCGPS.BDFUNAERO,
       CCGPS.BDSENAR,
       CCGPS.BDSEST,
       CCGPS.BDSENAT,
       CCGPS.BDSESCOOP,
       CCGPS.BDATUTAB
FROM vrh_base_tcustom CCREF
LEFT OUTER JOIN vw_vrh_base_tcustom_end CCEND
  ON (CCEND.bdCODCENTRO = CCREF.BDCODCENTRO AND CCEND.BDCODTPCC = CCREF.BDCODTPCC)
LEFT OUTER JOIN vw_vrh_base_tcustom_gps CCGPS
  ON (CCGPS.bdCODCENTRO = CCREF.BDCODCENTRO AND CCGPS.BDCODTPCC = CCREF.BDCODTPCC)
;

/* CREATE OR ALTER VIEW: VW_TOT_VRHF_EMP_TPGTO_CALC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TOT_VRHF_EMP_TPGTO_CALC(
BDCODEMP,
BDCHAVEPGTO,
BDVLRPGTO,
BDDATAPGTO)
 AS 
SELECT BDCODEMP, BDCHAVEPGTO, SUM(BDVLRPGTO), MAX(BDDATAPGTO)
       FROM VRHF_EMP_TPGTO_CALC
GROUP BY BDCODEMP, BDCHAVEPGTO
;

/* CREATE OR ALTER VIEW: VW_UNION_BASES_FN_FC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_BASES_FN_FC(
BDCODEMP,
BDCODCOL,
BDREFFN,
BDBFGTSFN,
BDFGTSFN,
BDFGTSCSFN,
BDBFGTS13FN,
BDFGTS13FN,
BDFGTS13CSFN,
BDMAIORREMFN,
BDBINSSFN,
BDALIQINSSFN,
BDINSSFN,
BDBIRRFFN,
BDALIQIRRFFN,
BDIRRFFN,
BDBINSS13FN,
BDALIQINSS13FN,
BDINSS13FN,
BDBIRRF13FN,
BDALIQIRRF13FN,
BDIRRF13FN,
BDBSALFAMFN,
BDSALFAMFN,
BDBRAISFN,
BDSALBASEFN,
BDDEPFN,
BDBASEPISFN,
BDBSALMATEMPFN,
BDSALMATEMPFN,
BDBRATAPOFN,
BDBINSSFEFOLFN,
BDINSSFEFOLFN,
BDALIQINSSFEFOLFN,
BDCREDITOFN,
BDDEBITOFN,
BDBFGTSFEFN,
BDFGTSFEFN,
BDBRATAPOFEFN,
BDBRATAPO13FN,
BDBASEPISFEFN,
BDBASEPIS13FN,
BDLIQUIDO)
 AS 
SELECT
  FN.BDCODEMP,
  FN.BDCODCOL,
  FN.BDREFFN,
  FN.BDBFGTSFN,
  FN.BDFGTSFN,
  FN.BDFGTSCSFN,
  FN.BDBFGTS13FN,
  FN.BDFGTS13FN,
  FN.BDFGTS13CSFN,
  FN.BDMAIORREMFN,
  FN.BDBINSSFN,
  FN.BDALIQINSSFN,
  FN.BDINSSFN,
  FN.BDBIRRFFN,
  FN.BDALIQIRRFFN,
  FN.BDIRRFFN,
  FN.BDBINSS13FN,
  FN.BDALIQINSS13FN,
  FN.BDINSS13FN,
  FN.BDBIRRF13FN,
  FN.BDALIQIRRF13FN,
  FN.BDIRRF13FN,
  FN.BDBSALFAMFN,
  FN.BDSALFAMFN,
  FN.BDBRAISFN,
  FN.BDSALBASEFN,
  FN.BDDEPFN,
  FN.BDBASEPISFN,
  FN.BDBSALMATEMPFN,
  FN.BDSALMATEMPFN,
  FN.BDBRATAPOFN,
  FN.BDBINSSFEFOLFN,
  FN.BDINSSFEFOLFN,
  FN.BDALIQINSSFEFOLFN,
  FN.BDCREDITOFN,
  FN.BDDEBITOFN,
  FN.BDBFGTSFEFN,
  FN.BDFGTSFEFN,
  FN.BDBRATAPOFEFN,
  FN.BDBRATAPO13FN,
  FN.BDBASEPISFEFN,
  FN.BDBASEPIS13FN,
  FN.BDLIQUIDO
FROM VRHF_EMP_TFOLHANORMAL FN

UNION

SELECT
  FT.BDCODEMP,
  FT.BDCODCOL,
  FT.BDREFTOMADOR,
  FT.BDBFGTSFT,
  FT.BDFGTSFT,
  FT.BDFGTSCSFT,
  FT.BDBFGTS13FT,
  FT.BDFGTS13FT,
  FT.BDFGTS13CSFT,
  FT.BDMAIORREMFT,
  FT.BDBINSSFT,
  FT.BDALIQINSSFT,
  FT.BDINSSFT,
  FT.BDBIRRFFT,
  FT.BDALIQIRRFFT,
  FT.BDIRRFFT,
  FT.BDBINSS13FT,
  FT.BDALIQINSS13FT,
  FT.BDINSS13FT,
  FT.BDBIRRF13FT,
  FT.BDALIQIRRF13FT,
  FT.BDIRRF13FT,
  FT.BDBSALFAMFT,
  FT.BDSALFAMFT,
  FT.BDBRAISFT,
  FT.BDSALBASEFT,
  FT.BDDEPFT,
  FT.BDBASEPISFT,
  FT.BDBSALMATEMPFT,
  FT.BDSALMATEMPFT,
  FT.BDBRATAPOFT,
  FT.BDBINSSFEFOLFT,
  FT.BDINSSFEFOLFT,
  FT.BDALIQINSSFEFOLFT,
  FT.BDCREDITOFT,
  FT.BDDEBITOFT,
  FT.BDBFGTSFEFT,
  FT.BDFGTSFEFT,
  FT.BDBRATAPOFEFT,
  FT.BDBRATAPO13FT,
  FT.BDBASEPISFEFT,
  FT.BDBASEPIS13FT,
  FT.BDLIQUIDO
FROM VRHF_EMP_TFOLHATOMADOR FT

UNION

SELECT
  FC.BDCODEMP,
  FC.BDCODCOL,
  FC.BDREFCOMP,
  FC.BDBFGTSFC,
  FC.BDFGTSFC,
  FC.BDFGTSCSFC,
  FC.BDBFGTS13FC,
  FC.BDFGTS13FC,
  FC.BDFGTS13CSFC,
  FC.BDMAIORREMFC,
  FC.BDBINSSFC,
  FC.BDALIQINSSFC,
  FC.BDINSSFC,
  FC.BDBIRRFFC,
  FC.BDALIQIRRFFC,
  FC.BDIRRFFC,
  FC.BDBINSS13FC,
  FC.BDALIQINSS13FC,
  FC.BDINSS13FC,
  FC.BDBIRRF13FC,
  FC.BDALIQIRRF13FC,
  FC.BDIRRF13FC,
  FC.BDBSALFAMFC,
  FC.BDSALFAMFC,
  FC.BDBRAISFC,
  FC.BDSALBASEFC,
  FC.BDDEPFC,
  FC.BDBASEPISFC,
  FC.BDBSALMATEMPFC,
  FC.BDSALMATEMPFC,
  FC.BDBRATAPOFC,
  FC.BDBINSSFEFOLFC,
  FC.BDINSSFEFOLFC,
  FC.BDALIQINSSFEFOLFC,
  FC.BDCREDITOFC,
  FC.BDDEBITOFC,
  FC.BDBFGTSFEFC,
  FC.BDFGTSFEFC,
  FC.BDBRATAPOFEFC,
  FC.BDBRATAPO13FC,
  FC.BDBASEPISFEFC,
  FC.BDBASEPIS13FC,
  FC.BDLIQUIDO
FROM VRHF_EMP_TFOLHACOMP FC

UNION

SELECT
  FTC.BDCODEMP,
  FTC.BDCODCOL,
  FTC.BDREFCOMP,
  FTC.BDBFGTSFC,
  FTC.BDFGTSFC,
  FTC.BDFGTSCSFC,
  FTC.BDBFGTS13FC,
  FTC.BDFGTS13FC,
  FTC.BDFGTS13CSFC,
  FTC.BDMAIORREMFC,
  FTC.BDBINSSFC,
  FTC.BDALIQINSSFC,
  FTC.BDINSSFC,
  FTC.BDBIRRFFC,
  FTC.BDALIQIRRFFC,
  FTC.BDIRRFFC,
  FTC.BDBINSS13FC,
  FTC.BDALIQINSS13FC,
  FTC.BDINSS13FC,
  FTC.BDBIRRF13FC,
  FTC.BDALIQIRRF13FC,
  FTC.BDIRRF13FC,
  FTC.BDBSALFAMFC,
  FTC.BDSALFAMFC,
  FTC.BDBRAISFC,
  FTC.BDSALBASEFC,
  FTC.BDDEPFC,
  FTC.BDBASEPISFC,
  FTC.BDBSALMATEMPFC,
  FTC.BDSALMATEMPFC,
  FTC.BDBRATAPOFC,
  FTC.BDBINSSFEFOLFC,
  FTC.BDINSSFEFOLFC,
  FTC.BDALIQINSSFEFOLFC,
  FTC.BDCREDITOFC,
  FTC.BDDEBITOFC,
  FTC.BDBFGTSFEFC,
  FTC.BDFGTSFEFC,
  FTC.BDBRATAPOFEFC,
  FTC.BDBRATAPO13FC,
  FTC.BDBASEPISFEFC,
  FTC.BDBASEPIS13FC,
  FTC.BDLIQUIDO
FROM VRHF_EMP_TFOLTOMCOMP FTC
;

/* CREATE OR ALTER VIEW: VW_TOTAL_FN_FC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TOTAL_FN_FC(
BDCODEMP,
BDCODCOL,
BDREFFN,
BDBFGTSFN,
BDFGTSFN,
BDFGTSCSFN,
BDBFGTS13FN,
BDFGTS13FN,
BDFGTS13CSFN,
BDMAIORREMFN,
BDBINSSFN,
BDALIQINSSFN,
BDINSSFN,
BDBIRRFFN,
BDALIQIRRFFN,
BDIRRFFN,
BDBINSS13FN,
BDALIQINSS13FN,
BDINSS13FN,
BDBIRRF13FN,
BDALIQIRRF13FN,
BDIRRF13FN,
BDBSALFAMFN,
BDSALFAMFN,
BDBRAISFN,
BDSALBASEFN,
BDDEPFN,
BDBASEPISFN,
BDBSALMATEMPFN,
BDSALMATEMPFN,
BDBRATAPOFN,
BDBINSSFEFOLFN,
BDINSSFEFOLFN,
BDALIQINSSFEFOLFN,
BDCREDITOFN,
BDDEBITOFN,
BDBFGTSFEFN,
BDFGTSFEFN,
BDBRATAPOFEFN,
BDBRATAPO13FN,
BDBASEPISFEFN,
BDBASEPIS13FN,
BDLIQUIDO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  COALESCE(SUM(BDBFGTSFN), 0.0),
  COALESCE(SUM(BDFGTSFN), 0.0),
  COALESCE(SUM(BDFGTSCSFN), 0.0),
  COALESCE(SUM(BDBFGTS13FN), 0.0),
  COALESCE(SUM(BDFGTS13FN), 0.0),
  COALESCE(SUM(BDFGTS13CSFN), 0.0),
  COALESCE(SUM(BDMAIORREMFN), 0.0),
  COALESCE(SUM(BDBINSSFN), 0.0),
  COALESCE(MAX(BDALIQINSSFN), 0.0),
  COALESCE(SUM(BDINSSFN), 0.0),
  COALESCE(SUM(BDBIRRFFN), 0.0),
  COALESCE(MAX(BDALIQIRRFFN), 0.0),
  COALESCE(SUM(BDIRRFFN), 0.0),
  COALESCE(SUM(BDBINSS13FN), 0.0),
  COALESCE(MAX(BDALIQINSS13FN), 0.0),
  COALESCE(SUM(BDINSS13FN), 0.0),
  COALESCE(SUM(BDBIRRF13FN), 0.0),
  COALESCE(MAX(BDALIQIRRF13FN), 0.0),
  COALESCE(SUM(BDIRRF13FN), 0.0),
  COALESCE(SUM(BDBSALFAMFN), 0.0),
  COALESCE(SUM(BDSALFAMFN), 0.0),
  COALESCE(SUM(BDBRAISFN), 0.0),
  COALESCE(SUM(BDSALBASEFN), 0.0),
  COALESCE(MAX(BDDEPFN), 0.0),
  COALESCE(SUM(BDBASEPISFN), 0.0),
  COALESCE(SUM(BDBSALMATEMPFN), 0.0),
  COALESCE(SUM(BDSALMATEMPFN), 0.0),
  COALESCE(SUM(BDBRATAPOFN), 0.0),
  COALESCE(SUM(BDBINSSFEFOLFN), 0.0),
  COALESCE(SUM(BDINSSFEFOLFN), 0.0),
  COALESCE(MAX(BDALIQINSSFEFOLFN), 0.0),
  COALESCE(SUM(BDCREDITOFN), 0.0),
  COALESCE(SUM(BDDEBITOFN), 0.0),
  COALESCE(SUM(BDBFGTSFEFN), 0.0),
  COALESCE(SUM(BDFGTSFEFN), 0.0),
  COALESCE(SUM(BDBRATAPOFEFN), 0.0),
  COALESCE(SUM(BDBRATAPO13FN), 0.0),
  COALESCE(SUM(BDBASEPISFEFN), 0.0),
  COALESCE(SUM(BDBASEPIS13FN), 0.0),
  COALESCE(SUM(BDLIQUIDO), 0.0)
FROM VW_UNION_BASES_FN_FC
GROUP BY BDCODEMP,BDCODCOL,BDREFFN
;

/* CREATE OR ALTER VIEW: VW_TRANSF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TRANSF(
BDCODEMPORIG,
BDCODEMPDEST,
BDCODPTRAN,
BDCODCOLDEST,
BDCODCOLORIG,
BDDATATRF,
BDCODMCAGENT,
BDCODMFG,
BDCODMRAIS,
BDDESCPTRAN,
BDCODPRES,
BDCODMCAGSAI,
BDCODSEFMFG,
BDDESCMFG,
BDDESCMRAIS,
BDDESCMCAGED_TE,
BDDESCMCAGED_TS)
 AS 
SELECT
  TRANS.BDCODEMPORIG,
  TRANS.BDCODEMPDEST,
  TRANS.BDCODPTRAN,
  TRANS.BDCODCOLORIG,
  TRANS.BDCODCOLDEST,
  TRANS.BDDATATRF,
  RESC.BDCODMCAGENT,
  RESC.BDCODMFG,
  RESC.BDCODMRAIS,
  RESC.bddescpres,
  RESC.BDCODPRES,
  RESC.BDCODMCAG,
  MFGT.BDCODSEFMFG,
  MFGT.BDDESCMFG,
  MRAI.BDDESCMRAIS,
  MCAGE.BDDESCMCAGED,
  MCAGS.BDDESCMCAGED


FROM VRH_EMP_TTRANSCOL TRANS
LEFT OUTER JOIN VRH_BASE_TPREPRESC RESC ON (RESC.BDCODPRES = TRANS.BDCODPTRAN)
LEFT OUTER JOIN VRH_BASE_TMOTFGTS MFGT ON (MFGT.BDCODMFG = RESC.BDCODMFG)
LEFT OUTER JOIN VRH_BASE_TMOTRAIS MRAI ON (MRAI.BDCODMRAIS = RESC.BDCODMRAIS)
LEFT OUTER JOIN VRH_BASE_TMOTCAGED MCAGE ON (MCAGE.BDCODMCAG = RESC.BDCODMCAGENT)
LEFT OUTER JOIN VRH_BASE_TMOTCAGED MCAGS ON (MCAGS.BDCODMCAG = RESC.BDCODMCAG)
;

/* CREATE OR ALTER VIEW: VW_TRANSFERIDOS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TRANSFERIDOS(
BDCODEMP,
BDCODCOL,
BDDATARESCISAO,
BDCODPRES,
BDDATAAVPREVIO,
BDDATAHOM,
BDDATAPAGRESCISAO,
BDSALDOFGTS,
BDCALCFGTSMESANT,
BDMAIORREMUNERACAO,
BDCHAVEINDENTIFICACAO,
BDDATAPAGGRFC,
BDREPOSICAOVAGA,
BDDISSIDIO,
BDDATADISSIDIO,
BDDESCANSOINDENIZADO)
 AS 
SELECT
  RESC.BDCODEMP,
  RESC.BDCODCOL,
  RESC.BDDATARESCISAO,
  RESC.BDCODPRES,
  RESC.BDDATAAVPREVIO,
  RESC.BDDATAHOM,
  RESC.BDDATAPAGRESCISAO,
  RESC.BDSALDOFGTS,
  RESC.BDCALCFGTSMESANT,
  RESC.BDMAIORREMUNERACAO,
  RESC.BDCHAVEINDENTIFICACAO,
  RESC.BDDATAPAGGRFC,
  RESC.BDREPOSICAOVAGA,
  RESC.BDDISSIDIO,
  RESC.BDDATADISSIDIO,
  RESC.BDDESCANSOINDENIZADO
FROM
  VRH_EMP_TRESCISAO RESC
WHERE
  EXISTS (SELECT TRANS.BDCODEMPORIG, TRANS.BDCODCOLORIG FROM VRH_EMP_TTRANSCOL TRANS WHERE TRANS.BDCODEMPORIG = RESC.BDCODEMP AND TRANS.BDCODCOLORIG = RESC.BDCODCOL)
;

/* CREATE OR ALTER VIEW: VW_TTERCEIRO_REF_MAX_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TTERCEIRO_REF_MAX_MIN(
    BDCODTER,
    BDREFEMP)
AS
SELECT bdcodter,
    COALESCE
    (
      (SELECT first 1 rf2.bdrefemp FROM TTERCEIRO_REF rf2 WHERE rf2.bdcodter = X.bdCODTER and rf2.BDREFEMP <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database) order by rf2.bdcodter desc, rf2.bdrefemp desc),
      (SELECT first 1 rf2.bdrefemp FROM TTERCEIRO_REF rf2 WHERE rf2.bdcodter = X.bdCODTER order by rf2.bdcodter, rf2.bdrefemp )
    ) AS bdREFEMP
    FROM tterceiro X
    GROUP BY X.bdCODTER
;

/* View: VW_TTERCEIRO */
CREATE OR ALTER VIEW VW_TTERCEIRO(
    BDCODTER,
    BDCODPLAPADRAO,
    BDCODTPLA,
    BDCGCTER,
    BDREFEMP,
    BDAPELIDOTER,
    BDNOMETER,
    BDLOGRTER,
    BDENDTER,
    BDNUMTER,
    BDCOMPTER,
    BDCEPTER,
    BDBAITER,
    BDDDDTER,
    BDFONETER,
    BDFAXTER,
    BDEMAILTER,
    BDIETER,
    BDDATACADTER,
    BDIMTER,
    BDPRURALTER,
    BDENQSIMPLESFEDTER,
    BDINSCSUFRAMATER,
    BDCODGPS,
    BDCODCID,
    BDCODPAIS,
    BDDESCPAIS,
    BDDDDFAXTER,
    BDORGAOPUBLICO,
    BDINATIVO,
    BDCODTIPO,
    BDINDIMUNEISE,
    BDCPFPROD,
    BDRECOLHEGUIAMUN,
    BDCODAQUIRUR,
    BDPRODPF,
    BDCODPAISRES,
    BDCODTRIBRUR,
    BDCODSPED,
    BDDDDCELULARTER,
    BDCELULARTER,
    BDUTILIZADESCSIMPLIFICADO,
    BDINDNIF,
    BDNUMERONIF,
    BDCODIGOPOSTAL)
AS
select TER.BDCODTER, TER.BDCODPLAPADRAO, TER.BDCODTPLA, TER.BDCGCTER, T.BDREFEMP, X.BDAPELIDOTER, X.BDNOMETER,
       X.BDLOGRTER, X.BDENDTER, X.BDNUMTER, X.BDCOMPTER, X.BDCEPTER, X.BDBAITER, X.BDDDDTER, X.BDFONETER, X.BDFAXTER,
       X.BDEMAILTER, X.BDIETER, X.BDDATACADTER, X.BDIMTER, X.BDPRURALTER, X.BDENQSIMPLESFEDTER, X.BDINSCSUFRAMATER,
       X.BDCODGPS, X.BDCODCID, X.BDCODPAIS, TPAIS.BDDESCPAIS, X.BDDDDFAXTER, X.BDORGAOPUBLICO,
       coalesce(X.BDINATIVO, 'FALSE'), TER.BDCODTIPO, X.BDINDIMUNEISE, X.BDCPFPROD, X.BDRECOLHEGUIAMUN, X.BDCODAQUIRUR,
       X.BDPRODPF, X.BDCODPAISRES, X.BDCODTRIBRUR, TPAIS.BDCODSPED, X.BDDDDCELULARTER, X.BDCELULARTER,
       X.BDUTILIZADESCSIMPLIFICADO, X.BDINDNIF, X.BDNUMERONIF, X.BDCODIGOPOSTAL
from TTERCEIRO TER
left outer join VW_TTERCEIRO_REF_MAX_MIN T on TER.BDCODTER = T.BDCODTER
join TTERCEIRO_REF X on (X.BDCODTER = TER.BDCODTER and
      X.BDREFEMP = T.BDREFEMP)
left outer join TPAIS on (TPAIS.BDCODPAIS = X.BDCODPAIS)
;

/* CREATE OR ALTER VIEW: VW_TTERCEIRO_SIMPLES (ViwData.CreateDependDef) */
create or alter view VW_TTERCEIRO_SIMPLES (
    BDCODTER,
    BDCGCTER,
    BDREFEMP,
    BDCODCID,
    BDIETER,
    BDNOME,
    BDCODPAIS,
    BDINATIVO)
as
select TER.BDCODTER,
       TER.BDCGCTER,
    TERREF.BDREFEMP,
    TERREF.BDCODCID,
       TERREF.BDIETER,
       TERREF.BDNOMETER,
       TERREF.BDCODPAIS,
       TERREF.BDINATIVO
from TTERCEIRO TER
left outer join VW_TTERCEIRO_REF_MAX_MIN T on (TER.BDCODTER = T.BDCODTER)
join TTERCEIRO_REF TERREF on (TERREF.BDCODTER = TER.BDCODTER and TERREF.BDREFEMP = T.BDREFEMP)
;

/* CREATE OR ALTER VIEW: VW_TTERCEIRO_VSUC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TTERCEIRO_VSUC(
BDCODTER,
BDCODPLAPADRAO,
BDCODTPLA,
BDCGCTER,
BDREFEMP,
BDAPELIDOTER,
BDNOMETER,
BDLOGRTER,
BDENDTER,
BDNUMTER,
BDCOMPTER,
BDCEPTER,
BDBAITER,
BDDDDTER,
BDFONETER,
BDFAXTER,
BDEMAILTER,
BDIETER,
BDDATACADTER,
BDIMTER,
BDPRURALTER,
BDENQSIMPLESFEDTER,
BDINSCSUFRAMATER,
BDCODGPS,
BDCODCID,
BDCODPAIS,
BDDESCPAIS,
BDDDDFAXTER)
 AS 
SELECT
    TER.BDCODTER,
    TER.BDCODPLAPADRAO  ,
    TER.BDCODTPLA       ,
    TER.BDCGCTER  ,
    TERREF.BDREFEMP,
    TERREF.BDAPELIDOTER,
    TERREF.BDNOMETER ,
    TERREF.BDLOGRTER ,
    TERREF.BDENDTER  ,
    TERREF.BDNUMTER  ,
    TERREF.BDCOMPTER ,
    TERREF.BDCEPTER  ,
    TERREF.BDBAITER  ,
    TERREF.BDDDDTER  ,
    TERREF.BDFONETER ,
    TERREF.BDFAXTER  ,
    TERREF.BDEMAILTER ,
    TERREF.BDIETER     ,
    TERREF.BDDATACADTER,
    TERREF.BDIMTER     ,
    TERREF.BDPRURALTER ,
    TERREF.BDENQSIMPLESFEDTER,
    TERREF.BDINSCSUFRAMATER ,
    TERREF.BDCODGPS ,
    TERREF.BDCODCID ,
    TERREF.BDCODPAIS,
    TPAIS.bddescpais,
    TERREF.BDDDDFAXTER

FROM tterceiro_ref TERREF
LEFT OUTER JOIN tterceiro TER ON TER.bdcodter = TERREF.bdcodter
LEFT OUTER JOIN tpais ON (tpais.bdcodpais = TERREF.bdcodpais)
WHERE
((TERREF.BDCODTER = TER.BDCODTER) AND TERREF.bdrefemp =
      (
       SELECT MAX(REF.bdrefemp)
       FROM tterceiro_ref REF
       WHERE REF.bdcodter = TER.bdcodter AND
             REF.bdrefemp <=
                (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER)
                 FROM rdb$database
                )
      )
)

ORDER BY TERREF.bdcodter
;

/*Sol.: 153354 - André Cursino - 26/11/2021 - View para ser usada na busca soletrada terceiro*/
CREATE OR ALTER VIEW VW_TTERCEIRO_SOLETRADO(
    BDCODEMP,
    BDCODCOL,
    BDNOMCOL,
    BDDTPCOL)
AS
SELECT
    0 as BDCODEMP,
    TER.BDCODTER ,
    X.BDNOMETER  ,
    'Terceiro' as BDDTPCOL
FROM tterceiro TER
LEFT OUTER JOIN VW_TTERCEIRO_REF_MAX_MIN T ON TER.bdcodter = T.bdcodter
JOIN tterceiro_ref X ON (x.bdcodTER = TER.bdcodter AND x.bdrefemp = T.bdrefemp)
;

/* CREATE OR ALTER VIEW: VW_TVERBAS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TVERBAS(
BDCODVER,
BDREFVER,
BDTIPOCODVER,
BDINSSVER,
BDFGTSVER,
BDIRVER,
BDTIPOREFVER,
BDBASESFVER,
BDPISVER,
BDBASEHEVER,
BDBASEMAIORVER,
BDRAISVER,
BDBASEGPSVER,
BDMENORESVER,
BDPROPVER,
BDBASEVTVER,
BDREEMBGPSVER,
BDHEVER,
BDGRAVAFICHAHNVER,
BDCCPRINCIPALVER,
BDFORMREFVER,
BDFORMVALVER,
BDBASEDSRHEVER,
BDBASEDSRRVVER,
BDFORMREFAUXVER,
BDDEDFORMREFAUXVER,
BDDEDFORMREFVER,
BDDEDFORMVALVER,
BDRENDISENTOIRVER,
BDPAGAESTOUROVER,
BDGARANTIAMINVER,
BDAPEVER,
BDDESCVER,
BDDESCREDVER,
BDCLAVER,
BDREADONLY,
BDORDEMVER)
 AS 
SELECT
  VERR.BDCODVER,
  VERR.BDREFVER,
  VERR.BDTIPOCODVER,
  VERR.BDINSSVER,
  VERR.BDFGTSVER,
  VERR.BDIRVER,
  VERR.BDTIPOREFVER,
  VERR.BDBASESFVER,
  VERR.BDPISVER,
  VERR.BDBASEHEVER,
  VERR.BDBASEMAIORVER,
  VERR.BDRAISVER,
  VERR.BDBASEGPSVER,
  VERR.BDMENORESVER,
  VERR.BDPROPVER,
  VERR.BDBASEVTVER,
  VERR.BDREEMBGPSVER,
  VERR.BDHEVER,
  VERR.BDGRAVAFICHAHNVER,
  VERR.BDCCPRINCIPALVER,
  VERR.BDFORMREFVER,
  VERR.BDFORMVALVER,
  VERR.BDBASEDSRHEVER,
  VERR.BDBASEDSRRVVER,
  VERR.BDFORMREFAUXVER,
  VERR.BDDEDFORMREFAUXVER,
  VERR.BDDEDFORMREFVER,
  VERR.BDDEDFORMVALVER,
  VERR.BDRENDISENTOIRVER,
  VERR.BDPAGAESTOUROVER,
  VERR.BDGARANTIAMINVER,

  VER.BDAPEVER,
  VER.BDDESCVER,
  VER.BDDESCREDVER,
  VER.BDCLAVER,
  VER.BDREADONLY,
  VER.BDORDEMVER

FROM
  VRH_BASE_TVERBAS VER,
  VRH_BASE_TVERBAS_REF VERR
WHERE
  VERR.BDCODVER = VER.BDCODVER
  AND STRLEN(VER.BDCLAVER) > 9
;

/* CREATE OR ALTER VIEW: VW_TVERBAS_EDIT (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TVERBAS_EDIT(
BDCODVER,
BDAPEVER,
BDCLAVER,
BDDESCVER,
BDTIPOCODVER,
BDTIPOREFVER,
BDTIPOVER)
 AS 
SELECT
  X.BDCODVER,
  X.BDAPEVER,
  X.BDCLAVER,
  X.BDDESCVER,
  Y.BDTIPOCODVER,
  Y.BDTIPOREFVER,
  X.BDTIPOVER
FROM VRH_BASE_TVERBAS X
JOIN (
  SELECT
      BASE.bdcodver,
      REF.bdrefver,
      REF.bdtipocodver,
      REF.bdtiporefver
  FROM
  (
    SELECT
        X.bdcodver,
        COALESCE
    (
        (SELECT MAX(d2.bdrefver) FROM vrh_base_tverbas_ref d2 WHERE d2.bdcodver = x.bdcodver AND CAST(d2.BDREFVER AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
        (SELECT MIN(d1.bdrefver) FROM vrh_base_tverbas_ref d1 WHERE d1.bdcodver = x.bdcodver)
    ) AS bdrefver
    FROM VRH_BASE_TVERBAS x
  
  ) AS BASE, vrh_base_tverbas_ref REF
  WHERE BASE.BDCODVER = REF.BDCODVER AND BASE.BDREFVER = REF.BDREFVER
) Y ON (Y.BDCODVER = X.BDCODVER)
;

/* CREATE OR ALTER VIEW: VW_VERBAS_REF_ATUAL_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBAS_REF_ATUAL_MIN(
BDCODVER,
BDREFVER)
 AS 
SELECT
  X.bdcodver,
  MIN(X.bdrefver)
FROM
  vrh_base_tverbas_ref X
GROUP BY X.BDCODVER
;

/* CREATE OR ALTER VIEW: VW_VERBAS_REF_ATUAL_MAX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBAS_REF_ATUAL_MAX(
BDCODVER,
BDREFVER)
 AS 
SELECT
  X.bdcodver,
  MAX(X.bdrefver)
FROM
  vrh_base_tverbas_ref X
WHERE
  CAST(X.BDREFVER AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
GROUP BY X.BDCODVER
;

/* CREATE OR ALTER VIEW: VW_TVERBAS_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_TVERBAS_REF(
BDCODVER,
BDAPEVER,
BDDESCVER,
BDDESCREDVER,
BDCLAVER,
BDREADONLY,
BDORDEMVER,
BDREFVER,
BDTIPOCODVER,
BDORDEMTIPOCODVER,
BDINSSVER,
BDFGTSVER,
BDIRVER,
BDTIPOREFVER,
BDBASESFVER,
BDPISVER,
BDBASEHEVER,
BDBASEMAIORVER,
BDRAISVER,
BDBASEGPSVER,
BDMENORESVER,
BDPROPVER,
BDBASEVTVER,
BDREEMBGPSVER,
BDHEVER,
BDGRAVAFICHAHNVER,
BDCCPRINCIPALVER,
BDFORMREFVER,
BDFORMVALVER,
BDBASEDSRHEVER,
BDBASEDSRRVVER,
BDFORMREFAUXVER,
BDDEDFORMREFAUXVER,
BDDEDFORMREFVER,
BDDEDFORMVALVER,
BDRENDISENTOIRVER)
 AS 
SELECT
  VER.BDCODVER,
  VER.BDAPEVER,
  VER.BDDESCVER,
  VER.BDDESCREDVER,
  VER.BDCLAVER,
  VER.BDREADONLY,
  VER.BDORDEMVER,
  VER.BDREFVER,
  VER.BDTIPOCODVER,
  CASE WHEN VER.BDTIPOCODVER = 1 THEN 2 WHEN VER.BDTIPOCODVER = 2 THEN 1 ELSE COALESCE(VER.BDTIPOCODVER, 0) END BDORDEMTIPOCODVER,
  VER.BDINSSVER,
  VER.BDFGTSVER,
  VER.BDIRVER,
  VER.BDTIPOREFVER,
  VER.BDBASESFVER,
  VER.BDPISVER,
  VER.BDBASEHEVER,
  VER.BDBASEMAIORVER,
  VER.BDRAISVER,
  VER.BDBASEGPSVER,
  VER.BDMENORESVER,
  VER.BDPROPVER,
  VER.BDBASEVTVER,
  VER.BDREEMBGPSVER,
  VER.BDHEVER,
  VER.BDGRAVAFICHAHNVER,
  VER.BDCCPRINCIPALVER,
  VER.BDFORMREFVER,
  VER.BDFORMVALVER,
  VER.BDBASEDSRHEVER,
  VER.BDBASEDSRRVVER,
  VER.BDFORMREFAUXVER,
  VER.BDDEDFORMREFAUXVER,
  VER.BDDEDFORMREFVER,
  VER.BDDEDFORMVALVER,
  VER.BDRENDISENTOIRVER
FROM
  VW_TVERBAS VER
WHERE
  EXISTS (SELECT Y.BDCODVER, Y.BDREFVER, Z.BDREFVER
          FROM VW_VERBAS_REF_ATUAL_MIN Y
          LEFT OUTER JOIN VW_VERBAS_REF_ATUAL_MAX Z
            ON (Z.BDCODVER = Y.BDCODVER AND Y.BDCODVER = VER.BDCODVER)
          WHERE Y.BDCODVER = VER.BDCODVER AND ((Y.BDREFVER = VER.BDREFVER AND Z.BDREFVER IS NULL) OR (Z.BDREFVER = VER.BDREFVER))
         )
;

/* CREATE OR ALTER VIEW: VW_UNION_BASES_IR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_BASES_IR(
BDCODEMP,
BDCODCOL,
BDREF,
BDBASEFN,
BDIRFN,
BDBASEFC,
BDIRFC,
BDBASE13SAL,
BDIR13SAL,
BDBASE13SALC,
BDIR13SALC,
BDBASEFERIAS,
BDIRFERIAS,
BDBASEPLR,
BDIRPLR,
BASEALUGUEL,
BDIRALUGUEL,
BDBASEADSAL,
BDIRADSAL)
 AS 
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREF,
    COALESCE(BDBRUTO,0.0),
    COALESCE(BDVALIR,0.0),
    0.0 BDBASEFC,
    0.0 BDIRFC,
    0.0 BDBASE13SAL,
    0.0 BDIR13SAL,
    0.0 BDBASE13SALC,
    0.0 BDIR13SALC,
    0.0 BDBASEFERIAS,
    0.0 BDIRFERIAS,
    0.0 BDBASEPLR,
    0.0 BDIRPLR,
    0.0 BASEALUGUEL,
    0.0 BDIRALUGUEL,
    0.0,
    0.0
FROM VW_IR_FOL_NORMAL
UNION
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREF,
    0.0 BDBASEFN,
    0.0 BDIRFN,
    COALESCE(BDBRUTO,0.0),
    COALESCE(BDVALIR,0.0),
    0.0 BDBASE13SAL,
    0.0 BDIR13SAL,
    0.0 BDBASE13SALC,
    0.0 BDIR13SALC,
    0.0 BDBASEFERIAS,
    0.0 BDIRFERIAS,
    0.0 BDBASEPLR,
    0.0 BDIRPLR,
    0.0 BASEALUGUEL,
    0.0 BDIRALUGUEL,
    0.0,
    0.0
FROM VW_IR_FOL_COMPLEMENTAR
UNION
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREF,
    0.0 BDBASEFN,
    0.0 BDIRFN,
    0.0 BDBASEFC,
    0.0 BDIRFC,
    0.0 BDBASE13SAL,
    0.0 BDIR13SAL,
    0.0 BDBASE13SALC,
    0.0 BDIR13SALC,
    COALESCE(BDBRUTO,0.0),
    COALESCE(BDVALIR,0.0),
    0.0 BDBASEPLR,
    0.0 BDIRPLR,
    0.0 BASEALUGUEL,
    0.0 BDIRALUGUEL,
    0.0,
    0.0
FROM VW_IR_FERIAS
UNION
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREF,
    0.0 BDBASEFN,
    0.0 BDIRFN,
    0.0 BDBASEFC,
    0.0 BDIRFC,
    COALESCE(BDBRUTO,0.0),
    COALESCE(BDVALIR,0.0),
    0.0 BDBASE13SALC,
    0.0 BDIR13SALC,
    0.0 BDBASEFERIAS,
    0.0 BDIRFERIAS,
    0.0 BDBASEPLR,
    0.0 BDIRPLR,
    0.0 BASEALUGUEL,
    0.0 BDIRALUGUEL,
    0.0,
    0.0
FROM VW_IR_13s
UNION
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREF,
    0.0 BDBASEFN,
    0.0 BDIRFN,
    0.0 BDBASEFC,
    0.0 BDIRFC,
    0.0 BDBASE13SAL,
    0.0 BDIR13SAL,
    COALESCE(BDBRUTO,0.0),
    COALESCE(BDVALIR,0.0),
    0.0 BDBASEFERIAS,
    0.0 BDIRFERIAS,
    0.0 BDBASEPLR,
    0.0 BDIRPLR,
    0.0 BASEALUGUEL,
    0.0 BDIRALUGUEL,
    0.0,
    0.0
FROM VW_IR_c13
UNION
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREF,
    0.0 BDBASEFN,
    0.0 BDIRFN,
    0.0 BDBASEFC,
    0.0 BDIRFC,
    0.0 BDBASE13SAL,
    0.0 BDIR13SAL,
    0.0,
    0.0,
    0.0 BDBASEFERIAS,
    0.0 BDIRFERIAS,
    0.0 BDBASEPLR,
    0.0 BDIRPLR,
    0.0 BASEALUGUEL,
    0.0 BDIRALUGUEL,
    COALESCE(BDBRUTO,0.0),
    COALESCE(BDVALIR,0.0)
FROM VW_IR_AD_SALARIO
;

/* CREATE OR ALTER VIEW: VW_UNION_CONS_CONTAB_AD (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_CONS_CONTAB_AD(
BDCODEMP,
BDCODCOL,
BDDATAAD,
BDCHAVE,
BDCODEMPSUC)
 AS 
SELECT ad.bdCODEMP, ad.bdcodcol, ad.bddataad, ad.bdCHAVE, ad.BDCODEMPSUC
FROM tol_vrhf_emp_tcalc_ad ad
UNION
SELECT vad.bdCODEMP, vad.bdcodcol, vad.bddataad, vad.bdCHAVE, vad.BDCODEMPSUC
FROM tol_vrhf_emp_tverba_ad vad
;

/* CREATE OR ALTER VIEW: VW_UNION_CONS_CONTAB_AUT (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_CONS_CONTAB_AUT(
BDCODEMP,
BDCODTER,
BDCODSERV,
BDCHAVE)
 AS 
SELECT aut.bdCODEMP, aut.bdcodter, aut.bdcodserv, aut.bdCHAVE
FROM tol_vrhf_emp_tcalc_aut aut
UNION
SELECT vaut.bdCODEMP, vaut.bdcodter, vaut.bdcodserv, vaut.bdCHAVE
FROM tol_vrhf_emp_tverba_aut vaut
;

/* CREATE OR ALTER VIEW: VW_UNION_CONS_CONTABILIZACA_A13 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_CONS_CONTABILIZACA_A13(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCHAVE,
    BDCODEMPSUC)
AS
SELECT fn.bdCODEMP, fn.bdCODCOL, fn.bdREFA13, fn.bdCHAVE, fn.bdCODEMPSUC
FROM tol_vrhf_emp_tcalc_a13 fn
UNION
SELECT vfn.bdCODEMP, vfn.bdCODCOL, vfn.bdREFA13, vfn.bdCHAVE, vfn.bdCODEMPSUC
FROM tol_vrhf_emp_tverba_a13 vfn
UNION
SELECT fgts.bdCODEMP, fgts.bdCODCOL, fgts.bdREFA13, fgts.bdCHAVE, fgts.bdCODEMPSUC
FROM tol_vrhf_emp_tfgts_a13 fgts
;

/* CREATE OR ALTER VIEW: VW_UNION_CONS_CONTABILIZACA_C13 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_CONS_CONTABILIZACA_C13(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCHAVE,
    BDCODEMPSUC)
AS
SELECT fn.bdCODEMP, fn.bdCODCOL, fn.bdREFC13, fn.bdCHAVE, fn.bdCODEMPSUC
FROM tol_vrhf_emp_tcalc_C13 fn
UNION
SELECT vfn.bdCODEMP, vfn.bdCODCOL, vfn.bdREFC13, vfn.bdCHAVE, vfn.bdCODEMPSUC
FROM tol_vrhf_emp_tverba_C13 vfn
UNION
SELECT fgts.bdCODEMP, fgts.bdCODCOL, fgts.bdREFC13, fgts.bdCHAVE, fgts.bdCODEMPSUC
FROM tol_vrhf_emp_tfgts_C13 fgts
;

/* CREATE OR ALTER VIEW: VW_UNION_CONS_CONTABILIZACAO_13 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_CONS_CONTABILIZACAO_13(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCHAVE,
    BDCODEMPSUC)
AS
SELECT fn.bdCODEMP, fn.bdCODCOL, fn.bdREF13, fn.bdCHAVE, fn.bdCODEMPSUC
FROM tol_vrhf_emp_tcalc_13 fn
UNION
SELECT vfn.bdCODEMP, vfn.bdCODCOL, vfn.bdREF13, vfn.bdCHAVE, vfn.bdCODEMPSUC
FROM tol_vrhf_emp_tverba_13 vfn
UNION
SELECT fgts.bdCODEMP, fgts.bdCODCOL, fgts.bdREF13, fgts.bdCHAVE, fgts.bdCODEMPSUC
FROM tol_vrhf_emp_tfgts_13 fgts
;

/* CREATE OR ALTER VIEW: VW_UNION_CONS_CONTABILIZACAO_AD (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_CONS_CONTABILIZACAO_AD(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCHAVE,
    BDCODEMPSUC)
AS
SELECT fn.bdCODEMP, fn.bdCODCOL, fn.bdDATAAD, fn.bdCHAVE, fn.bdCODEMPSUC
FROM tol_vrhf_emp_tcalc_ad fn
UNION
SELECT vfn.bdCODEMP, vfn.bdCODCOL, vfn.BDDATAAD, vfn.bdCHAVE, vfn.bdCODEMPSUC
FROM tol_vrhf_emp_tverba_ad vfn
;

/* CREATE OR ALTER VIEW: VW_UNION_CONS_CONTABILIZACAO_AU (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_CONS_CONTABILIZACAO_AU(
    BDCODEMP,
    BDCHAVE,
    BDCODTER,
    BDCODSERV,
    BDCODEMPSUC)
AS
SELECT BDCODEMP,BDCHAVE,BDCODTER,BDCODSERV,BDCODEMPSUC
FROM
  TOL_VRHF_EMP_TCALC_AUT
UNION
SELECT BDCODEMP,BDCHAVE,BDCODTER,BDCODSERV,BDCODEMPSUC
FROM
  TOL_VRHF_EMP_TVERBA_AUT
;

/* CREATE OR ALTER VIEW: VW_UNION_CONS_CONTABILIZACAO_FA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_CONS_CONTABILIZACAO_FA(
    BDCODEMP,
    BDCODCOL,
    BDCODTCA,
    BDDATA,
    BDCHAVE,
    BDCODEMPSUC)
AS
SELECT fa.bdCODEMP, fa.bdCODCOL, fa.bdcodtca, fa.bddatafa, fa.bdCHAVE, fa.bdCODEMPSUC
FROM tol_vrhf_emp_tcalc_fa fa
UNION
SELECT vfa.bdCODEMP, vfa.bdCODCOL, vfa.bdcodtca, vfa.bddatafa, vfa.bdCHAVE, vfa.bdCODEMPSUC
FROM tol_vrhf_emp_tverba_fa vfa
UNION
SELECT fgts.bdCODEMP, fgts.bdCODCOL, fgts.bdcodtca, fgts.bddatafa, fgts.bdCHAVE, fgts.bdCODEMPSUC
FROM tol_vrhf_emp_tfgts_fa fgts
;

/* CREATE OR ALTER VIEW: VW_UNION_CONS_CONTABILIZACAO_FC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_CONS_CONTABILIZACAO_FC(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDREFFC,
    BDCHAVE,
    BDCODCONTTI,
    BDCODEMPSUC)
AS
SELECT fn.bdCODEMP, fn.bdCODCOL, fn.bdREFFN, fn.bdREFFC, fn.bdCHAVE, cast(null as INTEGER) BDCODCONTTI, fn.bdCODEMPSUC
FROM tol_vrhf_emp_tcalc_fn_fc fn
UNION
SELECT vfn.bdCODEMP, vfn.bdCODCOL, vfn.bdREFFN, vfn.bdREFFC, vfn.bdCHAVE, cast(null as INTEGER) BDCODCONTTI, vfn.bdCODEMPSUC
FROM tol_vrhf_emp_tverba_fn_fc vfn
UNION
SELECT fgts.bdCODEMP, fgts.bdCODCOL, fgts.bdREFFN, fgts.bdREFFC, fgts.bdCHAVE, cast(null as INTEGER) BDCODCONTTI, fgts.bdCODEMPSUC
FROM tol_vrhf_emp_tfgts_fc fgts
UNION
SELECT fn.bdCODEMP, fn.bdCODCOL, fn.bdREFTOMADOR, fn.bdREFFC, fn.bdCHAVE, cast(null as INTEGER) BDCODCONTTI, fn.bdCODEMPSUC
FROM tol_vrhf_emp_tcalc_ft_fc fn
UNION
SELECT vfn.bdCODEMP, vfn.bdCODCOL, vfn.bdREFTOMADOR, vfn.bdREFFC, vfn.bdCHAVE, cast(null as INTEGER) BDCODCONTTI, vfn.bdCODEMPSUC
FROM tol_vrhf_emp_tverba_ft_fc vfn
UNION
SELECT fgts.bdCODEMP, fgts.bdCODCOL, fgts.bdREFTOMADOR, fgts.bdREFFC, fgts.bdCHAVE, cast(null as INTEGER) BDCODCONTTI, fgts.bdCODEMPSUC
FROM tol_vrhf_emp_tfgts_ft_fc fgts
UNION
SELECT fn.bdCODEMP, fn.bdCODCOL, fn.bdREFFN, fn.bdREFFC, fn.bdCHAVE, fn.BDCODCONTTI, fn.bdCODEMPSUC
FROM tol_vrhf_emp_tcalc_fn_fc_int fn
UNION
SELECT vfn.bdCODEMP, vfn.bdCODCOL, vfn.bdREFFN, vfn.bdREFFC, vfn.bdCHAVE, vfn.BDCODCONTTI, vfn.bdCODEMPSUC
FROM tol_vrhf_emp_tverba_fcint vfn
UNION
SELECT fgts.bdCODEMP, fgts.bdCODCOL, fgts.bdREFFN, fgts.bdREFFC, fgts.bdCHAVE, fgts.BDCODCONTTI, fgts.bdCODEMPSUC
FROM tol_vrhf_emp_tfgts_fc_int fgts
UNION
SELECT fn.bdCODEMP, fn.bdCODCOL, fn.bdREFTOMADOR, fn.bdREFFC, fn.bdCHAVE, fn.BDCODCONTTI, fn.bdCODEMPSUC
FROM tol_vrhf_emp_tcalc_ft_fc_int fn
UNION
SELECT vfn.bdCODEMP, vfn.bdCODCOL, vfn.bdREFTOMADOR, vfn.bdREFFC, vfn.bdCHAVE, vfn.BDCODCONTTI, vfn.bdCODEMPSUC
FROM tol_vrhf_emp_tverba_ft_fc_int vfn
UNION
SELECT fgts.bdCODEMP, fgts.bdCODCOL, fgts.bdREFTOMADOR, fgts.bdREFFC, fgts.bdCHAVE, fgts.BDCODCONTTI, fgts.bdCODEMPSUC
FROM tol_vrhf_emp_tfgts_ft_fc_int fgts
;

/* CREATE OR ALTER VIEW: VW_UNION_CONS_CONTABILIZACAO_FE (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_CONS_CONTABILIZACAO_FE(
    BDCODEMP,
    BDCODCOL,
    BDINIPERAQUISFE,
    BDCODFE,
    BDCHAVE,
    BDCODEMPSUC)
AS
SELECT fn.bdCODEMP, fn.bdCODCOL, fn.BDINIPERAQUISFE, fn.BDCODFE, fn.bdCHAVE, fn.BDCODEMPSUC
FROM tol_vrhf_emp_tcalc_fer fn
UNION
SELECT vfn.bdCODEMP, vfn.bdCODCOL, vfn.BDINIPERAQUISFE, vfn.BDCODFE, vfn.bdCHAVE, vfn.BDCODEMPSUC
FROM tol_vrhf_emp_tverba_fer vfn
;

/* CREATE OR ALTER VIEW: VW_UNION_CONS_CONTABILIZACAO_FN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_CONS_CONTABILIZACAO_FN(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCHAVE,
    BDCODCONTTI,
    BDCODEMPSUC)
AS
SELECT fn.bdCODEMP, fn.bdCODCOL, fn.bdREFFN, fn.bdCHAVE, null BDCODCONTTI, BDCODEMPSUC
FROM tol_vrhf_emp_tcalc_fn fn
UNION
SELECT vfn.bdCODEMP, vfn.bdCODCOL, vfn.bdREFFN, vfn.bdCHAVE, null BDCODCONTTI, BDCODEMPSUC
FROM tol_vrhf_emp_tverba_fn vfn
UNION
SELECT fgts.bdCODEMP, fgts.bdCODCOL, fgts.bdREFFN, fgts.bdCHAVE, null BDCODCONTTI, BDCODEMPSUC
FROM tol_vrhf_emp_tfgts_fn fgts
UNION
SELECT fn.bdCODEMP, fn.bdCODCOL, fn.bdREFTOMADOR, fn.bdCHAVE, null BDCODCONTTI, BDCODEMPSUC
FROM tol_vrhf_emp_tcalc_ft fn
UNION
SELECT vfn.bdCODEMP, vfn.bdCODCOL, vfn.bdREFTOMADOR, vfn.bdCHAVE, null BDCODCONTTI, BDCODEMPSUC
FROM tol_vrhf_emp_tverba_ft vfn
UNION
SELECT fgts.bdCODEMP, fgts.bdCODCOL, fgts.bdREFTOMADOR, fgts.bdCHAVE, null BDCODCONTTI, BDCODEMPSUC
FROM tol_vrhf_emp_tfgts_ft fgts
UNION
SELECT fn.bdCODEMP, fn.bdCODCOL, fn.bdREFFN, fn.bdCHAVE, fn.BDCODCONTTI, BDCODEMPSUC
FROM tol_vrhf_emp_tcalc_int fn
UNION
SELECT vfn.bdCODEMP, vfn.bdCODCOL, vfn.bdREFFN, vfn.bdCHAVE, vfn.BDCODCONTTI, BDCODEMPSUC
FROM tol_vrhf_emp_tverba_int vfn
UNION
SELECT fgts.bdCODEMP, fgts.bdCODCOL, fgts.bdREFFN, fgts.bdCHAVE, fgts.BDCODCONTTI, BDCODEMPSUC
FROM tol_vrhf_emp_tfgts_int fgts
UNION
SELECT fn.bdCODEMP, fn.bdCODCOL, fn.bdREFTOMADOR, fn.bdCHAVE, fn.BDCODCONTTI, BDCODEMPSUC
FROM tol_vrhf_emp_tcalc_tomint fn
UNION
SELECT vfn.bdCODEMP, vfn.bdCODCOL, vfn.bdREFTOMADOR, vfn.bdCHAVE, vfn.BDCODCONTTI, BDCODEMPSUC
FROM tol_vrhf_emp_tverba_tomint vfn
UNION
SELECT fgts.bdCODEMP, fgts.bdCODCOL, fgts.bdREFTOMADOR, fgts.bdCHAVE, fgts.BDCODCONTTI, BDCODEMPSUC
FROM tol_vrhf_emp_tfgts_tomint fgts
;

/* CREATE OR ALTER VIEW: VW_UNION_DADOS_CC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_DADOS_CC(
BDCODEMP,
BDCODCOL,
BDNOMCOL,
BDORDEM,
BDCODCENTRO,
BDCODTPCC,
BDDATAENTRADA,
BDHORAENTRADA,
BDTIPO,
BDQTDTEMPO,
BDCTALON,
BDTIPCTA,
BDNOMCTA,
BDAPECTA,
BDFILTROGER,
BDCLANOM,
BDCODTIPO)
 AS 
SELECT
  pfn.bdcodemp,
  pfn.bdcodcol,
  colcad.bdnomcol,
  pfn.bdordem,
  pfn.bdcodcentro,
  pfn.bdcodtpcc,
  pfn.bddataentrada,
  pfn.bdhoraentrada,
  pfn.bdtipo,
  pfn.bdqtdtempo,
  CAST(NULL AS VARCHAR(20)),
  0,
  empr.bdnomemp,
  CAST(NULL AS VARCHAR(20)),
  CAST(NULL AS VARCHAR(20)),
  CAST(NULL AS VARCHAR(80)),
  pfn.bdcodtipo
FROM vrhf_EMP_tprepfn pfn
JOIN VW_TEMPRESAS_REF EMPR ON (pfn.BDCODEMP = EMPR.BDCODEMP)
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON (colcad.bdcodemp = pfn.bdcodemp AND colcad.bdcodcol = pfn.bdcodcol)
WHERE pfn.bdcodtpcc IS NULL

UNION

SELECT
  pfn.bdcodemp,
  pfn.bdcodcol,
  colcad.bdnomcol,
  pfn.bdordem,
  pfn.bdcodcentro,
  pfn.bdcodtpcc,
  pfn.bddataentrada,
  pfn.bdhoraentrada,
  pfn.bdtipo,
  pfn.bdqtdtempo,
  cc.bdctalon,
  cc.bdtipcta,
  cc.bdnomcta,
  cc.bdapecta,
  cc.bdfiltroger,
  cc.bdclanom,
  pfn.bdcodtipo
FROM vrhf_EMP_tprepfn pfn
JOIN centros_tpcc cc ON (cc.bdcodcentro = pfn.bdcodcentro AND cc.bdcodtpcc = pfn.bdcodtpcc)
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON (colcad.bdcodemp = pfn.bdcodemp AND colcad.bdcodcol = pfn.bdcodcol)
WHERE pfn.bdcodtpcc IS NOT NULL
;

/* CREATE OR ALTER VIEW: VW_UNION_FF_HE_RV_HN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_FF_HE_RV_HN(
BDCODEMP,
BDCODCOL,
BDCODVER,
BDREFF,
BDREFVAL,
BDVALVAL)
 AS 
SELECT
  HE.BDCODEMP,
  HE.BDCODCOL,
  HE.BDCODVER,
  HE.BDREFFHE,
  HE.BDVREFFHE,
  HE.BDVVALFHE
FROM vrhf_emp_tfichahe HE

UNION

SELECT
  RV.BDCODEMP,
  RV.BDCODCOL,
  RV.BDCODVER,
  RV.BDREFFRV,
  RV.BDVREFFRV,
  RV.BDVVALFRV
FROM vrhf_emp_tficharv RV

UNION

SELECT
  HN.BDCODEMP,
  HN.BDCODCOL,
  HN.BDCODVER,
  HN.BDREFFHN,
  HN.BDVREFFHN,
  HN.BDVVALFHN
FROM vrhf_emp_tfichahn HN
;

/* CREATE OR ALTER VIEW: VW_UNION_FGTS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_FGTS(
BDCODEMP,
BDCODCOL,
BDREF,
BDBFGTSFN,
BDFGTSFN,
BDBFGTSFC,
BDFGTSFC,
BDBASEFGTS13,
BDFGTS13,
BDBASEFGTSA13,
BDFGTSA13,
BDBASEFGTSC13,
BDFGTSC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_FOL_NORMAL
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_FOL_COMPLEMENTAR
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_FOL_COMPLEMENTAR_INT
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_A13
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_13S
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_C13
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM VW_FGTS_AVULSA
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBFGTSFN,
  BDFGTSFN,
  BDBFGTSFC,
  BDFGTSFC,
  BDBASEFGTS13,
  BDFGTS13,
  BDBASEFGTSA13,
  BDFGTSA13,
  BDBASEFGTSC13,
  BDFGTSC13,
  BDTIPO
FROM vw_ficha_fgts
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TVERBAS_FICHA_HE (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TVERBAS_FICHA_HE(
BDCODVER,
BDCLAVER)
 AS 
SELECT
  X.BDCODVER,
  X.BDCLAVER
FROM VRH_BASE_TVERBAS X
JOIN VRH_BASE_TCONF_FICHA_HE Y ON (X.BDCLAVER STARTING WITH Y.BDCLAVER)
;

/* View: VW_VRHF_EMP_TFICHAIMP */
CREATE OR ALTER VIEW VW_VRHF_EMP_TFICHAIMP(
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFFF,
    BDTIPOFF,
    BDCCFF,
    BDVREFFF,
    BDVREFAUXFF,
    BDVVALFF,
    BDDATAFF)
AS
SELECT
  FF.BDCODEMP,
  FF.BDCODCOL,
  FF.BDCODVER,
  FF.BDREFFHE,
  FF.BDTIPOCALC,
  FF.BDCCFHE,
  FF.BDVREFFHE,
  FF.BDREFAUXFHE,
  FF.BDVVALFHE,
  FF.BDDATAHE
FROM (
  SELECT
    X.BDCODEMP,
    X.BDCODCOL,
    X.BDCODVER,
    X.BDREFFHE,
    9999 BDTIPOCALC,
    0 BDCCFHE,
    X.BDVREFFHE,
    0.000000 BDREFAUXFHE,
    X.BDVVALFHE,
    CAST(NULL AS DATE) BDDATAHE
  FROM
  VRHF_EMP_TFICHAHE X
  UNION
  SELECT
    X.BDCODEMP,
    X.BDCODCOL,
    X.BDCODVER,
    X.BDREFFRV,
    9999 BDTIPOCALC,
    0 BDCCFRV,
    X.BDVREFFRV,
    0.000000 BDREFAUXFRV,
    X.BDVVALFRV,
    CAST(NULL AS DATE)
  FROM
  VRHF_EMP_TFICHARV X
  UNION
  SELECT
    X.BDCODEMP,
    X.BDCODCOL,
    X.BDCODVER,
    X.BDREFFHN,
    9999 BDTIPOCALC,
    0 BDCCFHN,
    X.BDVREFFHN,
    0.000000 BDREFAUXFHN,
    X.BDVVALFHN,
    CAST(NULL AS DATE)
  FROM
  VRHF_EMP_TFICHAHN X
  UNION
  SELECT
    X.BDCODEMP,
    X.BDCODCOL,
    X.BDCODVER,
    X.BDREFFOT,
    9999 BDTIPOCALC,
    0 BDCCFHE,
    X.BDVREFFOT,
    0.000000 BDREFAUXFOT,
    X.BDVVALFOT,
    CAST(NULL AS DATE)
  FROM
  VRHF_EMP_TFICHAOUTRAS X
) FF
WHERE
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHANORMAL Y WHERE Y.BDCODEMP = FF.BDCODEMP AND Y.BDCODCOL = FF.BDCODCOL AND Y.BDREFFN = FF.BDREFFHE)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHAINT Y WHERE Y.BDCODEMP = FF.BDCODEMP AND Y.BDCODCOL = FF.BDCODCOL AND Y.BDREFFN = FF.BDREFFHE)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMADOR Y WHERE Y.BDCODEMP = FF.BDCODEMP AND Y.BDCODCOL = FF.BDCODCOL AND Y.BDREFTOMADOR = FF.BDREFFHE)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMINT Y WHERE Y.BDCODEMP = FF.BDCODEMP AND Y.BDCODCOL = FF.BDCODCOL AND Y.BDREFTOMADOR = FF.BDREFFHE)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMP Y WHERE Y.BDCODEMP = FF.BDCODEMP AND Y.BDCODCOL = FF.BDCODCOL AND Y.BDREFFN = FF.BDREFFHE)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMP Y WHERE Y.BDCODEMP = FF.BDCODEMP AND Y.BDCODCOL = FF.BDCODCOL AND Y.BDREFTOMADOR = FF.BDREFFHE)
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TFICHAHE (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TFICHAHE(
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFFHE,
    BDTIPOFHE,
    BDCCFHE,
    BDVREFFHE,
    BDVREFAUXFHE,
    BDVVALFHE,
    BDDATAHE)
AS
SELECT
  HE.BDCODEMP,
  HE.BDCODCOL,
  HE.BDCODVER,
  HE.BDREFFN,
  HE.BDTIPOCALC,
  HE.BDCCFN,
  HE.BDREFVFN,
  HE.BDREFAUXVFN,
  HE.BDVALVFN,
  HE.BDDATAHE
FROM (
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFFN,
    0 BDTIPOCALC,
    0 BDCCFN,
    BDREFVFN,
    BDREFAUXVFN,
    BDVALVFN,
    CAST(NULL AS DATE) BDDATAHE
  FROM
    VRHF_EMP_TVERBAFN
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFFN,
    0 BDTIPOCALC,
    0 BDCCFN,
    SUM(BDREFVFN),
    SUM(BDREFAUXVFN),
    SUM(BDVALVFN),
    CAST(NULL AS DATE)
  FROM
    VRHF_EMP_TVERBAINT
  GROUP BY BDCODEMP,BDCODCOL,BDCODVER,BDREFFN
  UNION
  SELECT
    TRANS.BDCODEMPDEST,
    TRANS.BDCODCOLDEST,
  X.BDCODVER,
  X.BDREFFN,
  0 BDTIPOCALC,
  0 BDCCFN,
  X.BDREFVFN,
  X.BDREFAUXVFN,
  X.BDVALVFN,
  CAST(NULL AS DATE)
  FROM
    VRH_EMP_TTRANSCOL TRANS
  JOIN
    VRHF_EMP_TVERBAFN X ON (X.BDCODEMP = TRANS.BDCODEMPORIG AND X.BDCODCOL = TRANS.BDCODCOLORIG)
  WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
        AND TRANS.BDREFTRF = X.BDREFFN
  UNION
  SELECT
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  X.BDCODVER,
  X.BDREFFN,
  0 BDTIPOCALC,
  0 BDCCFN,
    SUM(X.BDREFVFN),
    SUM(X.BDREFAUXVFN),
    SUM(X.BDVALVFN),
  CAST(NULL AS DATE)
  FROM
    VRH_EMP_TTRANSCOL TRANS
  JOIN
    VRHF_EMP_TVERBAINT X ON (X.BDCODEMP = TRANS.BDCODEMPORIG AND X.BDCODCOL = TRANS.BDCODCOLORIG)
  WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
 AND TRANS.BDREFTRF = X.BDREFFN
  GROUP BY TRANS.BDCODEMPDEST,TRANS.BDCODCOLDEST,X.BDCODVER,X.BDREFFN
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFTOMADOR,
    100 BDTIPOCALC,
    BDORDEM,
    BDREFVFT,
    BDREFAUXVFT,
    BDVALVFT,
    CAST(NULL AS DATE)
  FROM
    VRHF_EMP_TVERBATOMADOR
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFTOMADOR,
    100 BDTIPOCALC,
    BDORDEM,
    SUM(BDREFVFT),
    SUM(BDREFAUXVFT),
    SUM(BDVALVFT),
    CAST(NULL AS DATE)
  FROM
    VRHF_EMP_TVERBATOMINT
  GROUP BY BDCODEMP,BDCODCOL,BDCODVER,BDREFTOMADOR,BDORDEM
  UNION
  SELECT
    TRANS.BDCODEMPDEST,
    TRANS.BDCODCOLDEST,
  X.BDCODVER,
  X.BDREFTOMADOR,
    0 BDTIPOCALC,
    0 BDCCFN,
  X.BDREFVFT,
  X.BDREFAUXVFT,
  X.BDVALVFT,
  CAST(NULL AS DATE)
  FROM
    VRH_EMP_TTRANSCOL TRANS
  JOIN
    VRHF_EMP_TVERBATOMADOR X ON (X.BDCODEMP = TRANS.BDCODEMPORIG AND X.BDCODCOL = TRANS.BDCODCOLORIG)
  WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
        AND TRANS.BDREFTRF = X.BDREFTOMADOR
  UNION
  SELECT
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  X.BDCODVER,
  X.BDREFTOMADOR,
  0 BDTIPOCALC,
  0 BDCCFN,
    SUM(X.BDREFVFT),
    SUM(X.BDREFAUXVFT),
    SUM(X.BDVALVFT),
  CAST(NULL AS DATE)
  FROM
    VRH_EMP_TTRANSCOL TRANS
  JOIN
    VRHF_EMP_TVERBATOMINT X ON (X.BDCODEMP = TRANS.BDCODEMPORIG AND X.BDCODCOL = TRANS.BDCODCOLORIG)
  WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
 AND TRANS.BDREFTRF = X.BDREFTOMADOR
  GROUP BY TRANS.BDCODEMPDEST, TRANS.BDCODCOLDEST, X.BDCODVER, X.BDREFTOMADOR
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFFN,
  1 BDTIPOCALC,
  0 BDCCFC,
    BDREFVFC,
    BDREFAUXVFC,
    BDVALVFC,
    CAST((SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 7 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 1 FOR 4)) AS DATE)
  FROM
    VRHF_EMP_TVERBAFC
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFTOMADOR,
  101 BDTIPOCALC,
    BDORDEM,
    BDREFVFC,
    BDREFAUXVFC,
    BDVALVFC,
    CAST((SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 7 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 1 FOR 4)) AS DATE)
  FROM
    VRHF_EMP_TVERBAFCTOMADOR
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFFN,
  1 BDTIPOCALC,
  0 BDCCFC,
    BDREFVFC,
    BDREFAUXVFC,
    BDVALVFC,
    CAST((SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 7 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 1 FOR 4)) AS DATE)
  FROM
    VRHF_EMP_TVERBAFCINT
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFTOMADOR,
  101 BDTIPOCALC,
    BDORDEM,
    BDREFVFC,
    BDREFAUXVFC,
    BDVALVFC,
    CAST((SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 7 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 1 FOR 4)) AS DATE)
  FROM
    VRHF_EMP_TVERBAFCTOMINT
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    CAST((SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER),
    0 BDTIPOCALC,
  0 BDCCFHE,
    BDREFVFA,
    BDREFAUXVFA,
    BDVALVFA,
    BDDATAFA
  FROM
    VRHF_EMP_TVERBAFA
  UNION
  SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFFHE,
  9999 BDTIPOCALC,
  0 BDCCFHE,
  X.BDVREFFHE,
  0.000000 BDREFAUXFHE,
  X.BDVVALFHE,
  CAST(NULL AS DATE)
  FROM
  VRHF_EMP_TFICHAHE X
  WHERE
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHANORMAL Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREFFHE)
  AND
    NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHAINT Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREFFHE)
    AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMADOR Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFTOMADOR = X.BDREFFHE)
  AND
    NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMINT Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFTOMADOR = X.BDREFFHE)
    AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMP Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREFFHE)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMP Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFTOMADOR = X.BDREFFHE)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMPINT Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREFFHE)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMPINT Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFTOMADOR = X.BDREFFHE)
) HE
left outer join VW_VRH_BASE_TVERBAS_FICHA_HE FHE on (FHE.BDCODVER = HE.BDCODVER)
where FHE.BDCODVER is not null
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TVERBAS_FICHA_RV (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TVERBAS_FICHA_RV(
BDCODVER,
BDCLAVER)
 AS 
SELECT
  X.BDCODVER,
  X.BDCLAVER
FROM VRH_BASE_TVERBAS X
JOIN VRH_BASE_TCONF_FICHA_RV Y ON (X.BDCLAVER STARTING WITH Y.BDCLAVER)
GROUP BY X.BDCODVER,  X.BDCLAVER
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TFICHARV (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TFICHARV(
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFFRV,
    BDTIPOFRV,
    BDCCFRV,
    BDVREFFRV,
    BDVREFAUXFRV,
    BDVVALFRV,
    BDDATARV)
AS
SELECT
  RV.BDCODEMP,
  RV.BDCODCOL,
  RV.BDCODVER,
  RV.BDREFFN,
  RV.BDTIPOCALC,
  RV.BDCCFN,
  RV.BDREFVFN,
  RV.BDREFAUXVFN,
  RV.BDVALVFN,
  RV.BDDATARV
FROM (
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFFN,
    0 BDTIPOCALC,
    0 BDCCFN,
    BDREFVFN,
    BDREFAUXVFN,
    BDVALVFN,
    CAST(NULL AS DATE) BDDATARV
  FROM
    VRHF_EMP_TVERBAFN
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFFN,
    0 BDTIPOCALC,
    0 BDCCFN,
    SUM(BDREFVFN),
    SUM(BDREFAUXVFN),
    SUM(BDVALVFN),
    CAST(NULL AS DATE)
  FROM
    VRHF_EMP_TVERBAINT
  GROUP BY BDCODEMP,BDCODCOL,BDCODVER,BDREFFN
  UNION
  SELECT
    TRANS.BDCODEMPDEST,
    TRANS.BDCODCOLDEST,
  X.BDCODVER,
  X.BDREFFN,
  0 BDTIPOCALC,
  0 BDCCFN,
  X.BDREFVFN,
  X.BDREFAUXVFN,
  X.BDVALVFN,
  CAST(NULL AS DATE)
  FROM
    VRH_EMP_TTRANSCOL TRANS
  JOIN VRHF_EMP_TVERBAFN X ON (X.BDCODEMP = TRANS.BDCODEMPORIG AND X.BDCODCOL = TRANS.BDCODCOLORIG)
  WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
        AND TRANS.BDREFTRF = X.BDREFFN
  UNION
  SELECT
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  X.BDCODVER,
  X.BDREFFN,
  0 BDTIPOCALC,
  0 BDCCFN,
    SUM(X.BDREFVFN),
    SUM(X.BDREFAUXVFN),
    SUM(X.BDVALVFN),
  CAST(NULL AS DATE)
  FROM
    VRH_EMP_TTRANSCOL TRANS
  JOIN VRHF_EMP_TVERBAINT X ON (X.BDCODEMP = TRANS.BDCODEMPORIG AND X.BDCODCOL = TRANS.BDCODCOLORIG)
  WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
 AND TRANS.BDREFTRF = X.BDREFFN
  GROUP BY TRANS.BDCODEMPDEST,TRANS.BDCODCOLDEST,X.BDCODVER,X.BDREFFN
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFTOMADOR,
    100 BDTIPOCALC,
    BDORDEM,
    BDREFVFT,
    BDREFAUXVFT,
    BDVALVFT,
    CAST(NULL AS DATE)
  FROM
    VRHF_EMP_TVERBATOMADOR
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFTOMADOR,
    100 BDTIPOCALC,
    BDORDEM,
    SUM(BDREFVFT),
    SUM(BDREFAUXVFT),
    SUM(BDVALVFT),
    CAST(NULL AS DATE)
  FROM
    VRHF_EMP_TVERBATOMINT
  GROUP BY BDCODEMP,BDCODCOL,BDCODVER,BDREFTOMADOR,BDORDEM
  UNION
  SELECT
    TRANS.BDCODEMPDEST,
    TRANS.BDCODCOLDEST,
  X.BDCODVER,
  X.BDREFTOMADOR,
    0 BDTIPOCALC,
    0 BDCCFN,
  X.BDREFVFT,
  X.BDREFAUXVFT,
  X.BDVALVFT,
  CAST(NULL AS DATE)
  FROM
    VRH_EMP_TTRANSCOL TRANS
  JOIN
    VRHF_EMP_TVERBATOMADOR X ON (X.BDCODEMP = TRANS.BDCODEMPORIG AND X.BDCODCOL = TRANS.BDCODCOLORIG)
  WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
        AND TRANS.BDREFTRF = X.BDREFTOMADOR
  UNION
  SELECT
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  X.BDCODVER,
  X.BDREFTOMADOR,
  0 BDTIPOCALC,
  0 BDCCFN,
    SUM(X.BDREFVFT),
    SUM(X.BDREFAUXVFT),
    SUM(X.BDVALVFT),
  CAST(NULL AS DATE)
  FROM
    VRH_EMP_TTRANSCOL TRANS
  JOIN
    VRHF_EMP_TVERBATOMINT X ON (X.BDCODEMP = TRANS.BDCODEMPORIG AND X.BDCODCOL = TRANS.BDCODCOLORIG)
  WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
 AND TRANS.BDREFTRF = X.BDREFTOMADOR
  GROUP BY TRANS.BDCODEMPDEST,TRANS.BDCODCOLDEST,X.BDCODVER,X.BDREFTOMADOR
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFFN,
  1 BDTIPOCALC,
  0 BDCCFC,
    BDREFVFC,
    BDREFAUXVFC,
    BDVALVFC,
    CAST((SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 7 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 1 FOR 4)) AS DATE)
  FROM
    VRHF_EMP_TVERBAFC
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFTOMADOR,
  101 BDTIPOCALC,
    BDORDEM,
    BDREFVFC,
    BDREFAUXVFC,
    BDVALVFC,
    CAST((SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 7 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 1 FOR 4)) AS DATE)
  FROM
    VRHF_EMP_TVERBAFCTOMADOR
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFFN,
  1 BDTIPOCALC,
  0 BDCCFC,
    BDREFVFC,
    BDREFAUXVFC,
    BDVALVFC,
    CAST((SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 7 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 1 FOR 4)) AS DATE)
  FROM
    VRHF_EMP_TVERBAFCINT
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFTOMADOR,
  101 BDTIPOCALC,
    BDORDEM,
    BDREFVFC,
    BDREFAUXVFC,
    BDVALVFC,
    CAST((SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 7 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 1 FOR 4)) AS DATE)
  FROM
    VRHF_EMP_TVERBAFCTOMINT
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    CAST((SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER),
  200 BDTIPOCALC,
  0 BDCCFRV,
    BDREFVFA,
    BDREFAUXVFA,
    BDVALVFA,
    BDDATAFA
  FROM
    VRHF_EMP_TVERBAFA
  UNION
  SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFFRV,
  9999 BDTIPOCALC,
  0 BDCCFRV,
  X.BDVREFFRV,
  0.000000 BDREFAUXFRV,
  X.BDVVALFRV,
  CAST(NULL AS DATE)
  FROM
  VRHF_EMP_TFICHARV X
  WHERE
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHANORMAL Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREFFRV)
  AND
    NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHAINT Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREFFRV)
    AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMADOR Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFTOMADOR = X.BDREFFRV)
  AND
    NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMINT Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFTOMADOR = X.BDREFFRV)
    AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMP Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREFFRV)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMP Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFTOMADOR = X.BDREFFRV)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMPINT Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREFFRV)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMPINT Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFTOMADOR = X.BDREFFRV)
) RV
left outer join VW_VRH_BASE_TVERBAS_FICHA_RV FRV on (FRV.BDCODVER = RV.BDCODVER)
where FRV.BDCODVER is not null
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TVERBAS_FICHA_HN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TVERBAS_FICHA_HN(
BDCODVER,
BDCLAVER)
 AS 
SELECT
  X.BDCODVER,
  X.BDCLAVER
FROM VRH_BASE_TVERBAS X
JOIN VRH_BASE_TCONF_FICHA_HN Y ON (X.BDCLAVER STARTING WITH Y.BDCLAVER)
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TFICHAHN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TFICHAHN(
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFFHN,
    BDTIPOFHN,
    BDCCFHN,
    BDVREFFHN,
    BDVREFAUXFHN,
    BDVVALFHN,
    BDDATAHN)
AS
SELECT
  HN.BDCODEMP,
  HN.BDCODCOL,
  HN.BDCODVER,
  HN.BDREFFN,
  HN.BDTIPOCALC,
  HN.BDCCFN,
  HN.BDREFVFN,
  HN.BDREFAUXVFN,
  HN.BDVALVFN,
  HN.BDDATAHN
FROM (
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFFN,
    0 BDTIPOCALC,
    0 BDCCFN,
    BDREFVFN,
    BDREFAUXVFN,
    BDVALVFN,
    CAST(NULL AS DATE) BDDATAHN
  FROM
    VRHF_EMP_TVERBAFN
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFFN,
    0 BDTIPOCALC,
    0 BDCCFN,
    SUM(BDREFVFN),
    SUM(BDREFAUXVFN),
    SUM(BDVALVFN),
    CAST(NULL AS DATE)
  FROM
    VRHF_EMP_TVERBAINT
  GROUP BY BDCODEMP,BDCODCOL,BDCODVER,BDREFFN
  UNION
  SELECT
    TRANS.BDCODEMPDEST,
    TRANS.BDCODCOLDEST,
  X.BDCODVER,
  X.BDREFFN,
  0 BDTIPOCALC,
  0 BDCCFN,
  X.BDREFVFN,
  X.BDREFAUXVFN,
  X.BDVALVFN,
  CAST(NULL AS DATE)
  FROM
    VRH_EMP_TTRANSCOL TRANS
  JOIN
    VRHF_EMP_TVERBAFN X ON (X.BDCODEMP = TRANS.BDCODEMPORIG AND X.BDCODCOL = TRANS.BDCODCOLORIG)
  WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
        AND TRANS.BDREFTRF = X.BDREFFN
  UNION
  SELECT
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  X.BDCODVER,
  X.BDREFFN,
  0 BDTIPOCALC,
  0 BDCCFN,
    SUM(X.BDREFVFN),
    SUM(X.BDREFAUXVFN),
    SUM(X.BDVALVFN),
  CAST(NULL AS DATE)
  FROM
    VRH_EMP_TTRANSCOL TRANS
  JOIN VRHF_EMP_TVERBAINT X ON (X.BDCODEMP = TRANS.BDCODEMPORIG AND X.BDCODCOL = TRANS.BDCODCOLORIG)
  WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
 AND TRANS.BDREFTRF = X.BDREFFN
  GROUP BY TRANS.BDCODEMPDEST,TRANS.BDCODCOLDEST,X.BDCODVER,X.BDREFFN
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFTOMADOR,
    100 BDTIPOCALC,
    BDORDEM,
    BDREFVFT,
    BDREFAUXVFT,
    BDVALVFT,
    CAST(NULL AS DATE)
  FROM
    VRHF_EMP_TVERBATOMADOR
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFTOMADOR,
    100 BDTIPOCALC,
    BDORDEM,
    SUM(BDREFVFT),
    SUM(BDREFAUXVFT),
    SUM(BDVALVFT),
    CAST(NULL AS DATE)
  FROM
    VRHF_EMP_TVERBATOMINT
  GROUP BY BDCODEMP,BDCODCOL,BDCODVER,BDREFTOMADOR,BDORDEM
  UNION
  SELECT
    TRANS.BDCODEMPDEST,
    TRANS.BDCODCOLDEST,
  X.BDCODVER,
  X.BDREFTOMADOR,
    0 BDTIPOCALC,
    0 BDCCFN,
  X.BDREFVFT,
  X.BDREFAUXVFT,
  X.BDVALVFT,
  CAST(NULL AS DATE)
  FROM
    VRH_EMP_TTRANSCOL TRANS
  JOIN
    VRHF_EMP_TVERBATOMADOR X ON (X.BDCODEMP = TRANS.BDCODEMPORIG AND X.BDCODCOL = TRANS.BDCODCOLORIG)
  WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
        AND TRANS.BDREFTRF = X.BDREFTOMADOR
  UNION
  SELECT
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  X.BDCODVER,
  X.BDREFTOMADOR,
  0 BDTIPOCALC,
  0 BDCCFN,
    SUM(X.BDREFVFT),
    SUM(X.BDREFAUXVFT),
    SUM(X.BDVALVFT),
  CAST(NULL AS DATE)
  FROM
    VRH_EMP_TTRANSCOL TRANS
  JOIN
    VRHF_EMP_TVERBATOMINT X ON (X.BDCODEMP = TRANS.BDCODEMPORIG AND X.BDCODCOL = TRANS.BDCODCOLORIG)
  WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
 AND TRANS.BDREFTRF = X.BDREFTOMADOR
  GROUP BY TRANS.BDCODEMPDEST,TRANS.BDCODCOLDEST,X.BDCODVER,X.BDREFTOMADOR
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFFN,
  1 BDTIPOCALC,
  0 BDCCFC,
    BDREFVFC,
    BDREFAUXVFC,
    BDVALVFC,
    CAST((SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 7 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 1 FOR 4)) AS DATE)
  FROM
    VRHF_EMP_TVERBAFC
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFTOMADOR,
  101 BDTIPOCALC,
    BDORDEM,
    BDREFVFC,
    BDREFAUXVFC,
    BDVALVFC,
    CAST((SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 7 FOR 2)||'/'||SUBSTRING(CAST(BDREFFC AS VARCHAR(8)) FROM 1 FOR 4)) AS DATE)
  FROM
    VRHF_EMP_TVERBAFCTOMADOR
  UNION
  SELECT
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    CAST((SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER),
  200 BDTIPOCALC,
  0 BDCCFHE,
    BDREFVFA,
    BDREFAUXVFA,
    BDVALVFA,
    BDDATAFA
  FROM
    VRHF_EMP_TVERBAFA
  UNION
  SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFFHN,
  9999 BDTIPOCALC,
  0 BDCCFHN,
  X.BDVREFFHN,
  0.000000 BDREFAUXFHN,
  X.BDVVALFHN,
  CAST(NULL AS DATE)
  FROM
  VRHF_EMP_TFICHAHN X
  WHERE
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHANORMAL Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREFFHN)
  AND
    NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHAINT Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREFFHN)
    AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMADOR Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFTOMADOR = X.BDREFFHN)
  AND
    NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMINT Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFTOMADOR = X.BDREFFHN)
    AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMP Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREFFHN)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMP Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFTOMADOR = X.BDREFFHN)
) HN
left outer join VW_VRH_BASE_TVERBAS_FICHA_HN FHN on (FHN.BDCODVER = HN.BDCODVER)
where FHN.BDCODVER is not null
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TVERBAS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TVERBAS(
BDCODVER,
BDAPEVER,
BDDESCVER,
BDDESCREDVER,
BDCLAVER,
BDREADONLY,
BDORDEMVER,
BDINATIVAVER,
BDSITVER,
BDSITMATVER,
BDSITDOEVER,
BDSITACITRABVER,
BDSITMILITARVER,
BDSITMATEMPVER,
BDSITACITRAB15VER,
BDSITDOETRABVER,
BDSITLICVENCVER,
BDSITDOE15VER,
BDSITSINDICALVER,
BDSITAPOINVVER,
BDSITOUTRASVER)
 AS 
SELECT
    bdcodver,
    bdapever,
    bddescver,
    bddescredver,
    bdclaver,
    bdreadonly,
    bdordemver,
    bdinativaver,
    bdsitver,
    bdsitmatver,
    bdsitdoever,
    bdsitacitrabver,
    bdsitmilitarver,
    bdsitmatempver,
    bdsitacitrab15ver,
    bdsitdoetrabver,
    bdsitlicvencver,
    bdsitdoe15ver,
    bdsitsindicalver,
    bdsitapoinvver,
    bdsitoutrasver
FROM vrh_base_tverbas
WHERE strlen(BDCLAVER) > 9
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TVERBAS_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TVERBAS_REF(
    BDCODVER,
    BDCLAVER,
    BDDESCVER,
    BDREFVER,
    BDTIPOCODVER,
    BDINSSVER,
    BDFGTSVER,
    BDIRVER,
    BDTIPOREFVER,
    BDBASESFVER,
    BDPISVER,
    BDBASEHEVER,
    BDBASEMAIORVER,
    BDRAISVER,
    BDBASEGPSVER,
    BDMENORESVER,
    BDPROPVER,
    BDBASEVTVER,
    BDREEMBGPSVER,
    BDHEVER,
    BDGRAVAFICHAHNVER,
    BDCCPRINCIPALVER,
    BDFORMREFVER,
    BDFORMVALVER,
    BDFORMINTVER,
    BDBASEDSRHEVER,
    BDBASEDSRRVVER,
    BDFORMREFAUXVER,
    BDDEDFORMREFAUXVER,
    BDDEDFORMREFVER,
    BDDEDFORMVALVER,
    BDRENDISENTOIRVER,
    BDBASE13HN,
    BDBASEFERHN,
    BDBASEAVHN,
    BDPAGAESTOUROVER,
    BDGARANTIAMINVER,
    BDINDRESC,
    BDSIMPLESNACIONAL,
    BDNAOCONVHORASVER,
    BDBASEDSRHNVER,
    BDBASEDSROUVER,
    BDREMINTERMVER,
    BDCODINCIDFGTS,
    BDCODINCIDINSS,
    BDCODINCIDIRRF,
    BDINCIDPISVER,
    BDCODINCIDPIS,
    BDDESCCOMPULSORIOVER)
AS
SELECT
    BASE.bdcodver,
    BASE.bdclaver,
    BASE.bddescver,
    REF.bdrefver,
    REF.bdtipocodver,
    REF.bdinssver,
    REF.bdfgtsver,
    REF.bdirver,
    REF.bdtiporefver,
    REF.bdbasesfver,
    REF.bdpisver,
    REF.bdbasehever,
    REF.bdbasemaiorver,
    REF.bdraisver,
    REF.bdbasegpsver,
    REF.bdmenoresver,
    REF.bdpropver,
    REF.bdbasevtver,
    REF.bdreembgpsver,
    REF.bdhever,
    REF.bdgravafichahnver,
    REF.bdccprincipalver,
    REF.bdformrefver,
    REF.bdformvalver,
    REF.bdformintver,
    REF.bdbasedsrhever,
    REF.bdbasedsrrvver,
    REF.bdformrefauxver,
    REF.bddedformrefauxver,
    REF.bddedformrefver,
    REF.bddedformvalver,
    REF.bdrendisentoirver,
    REF.BDBASE13HN,
    REF.BDBASEFERHN,
    REF.BDBASEAVHN,
    REF.BDPAGAESTOUROVER,
    REF.BDGARANTIAMINVER,
    REF.bdindresc,
    REF.bdsimplesnacional,
    REF.bdnaoconvhorasver,
    REF.bdbasedsrhnver,
    REF.bdbasedsrouver,
    REF.bdremintermver,
    REF.bdcodincidfgts,
    REF.bdcodincidinss,
    REF.bdcodincidirrf,
    REF.BDINCIDPISVER,
    REF.BDCODINCIDPIS,
    REF.BDDESCCOMPULSORIOVER
FROM
(
  SELECT
      X.bdcodver,
      X.bdclaver,
      X.bddescver,
      COALESCE
  (
      (SELECT MAX(d2.bdrefver) FROM vrh_base_tverbas_ref d2 WHERE d2.bdcodver = x.bdcodver AND CAST(d2.BDREFVER AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefver) FROM vrh_base_tverbas_ref d1 WHERE d1.bdcodver = x.bdcodver)
  ) AS bdrefver
  FROM VW_VRH_BASE_TVERBAS x

) AS BASE, vrh_base_tverbas_ref REF
WHERE BASE.BDCODVER = REF.BDCODVER AND BASE.BDREFVER = REF.BDREFVER
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TFICHAOUTRAS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TFICHAOUTRAS(
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFFOT,
    BDTIPOFOT,
    BDCCFOT,
    BDVREFFOT,
    BDVREFAUXFOT,
    BDVVALFOT,
    BDDATAFOT)
AS
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFFN,
  0 BDTIPOCALC,
  0 BDCCFN,
  X.BDREFVFN,
  X.BDREFAUXVFN,
  X.BDVALVFN,
  CAST(NULL AS DATE)
FROM
VRHF_EMP_TVERBAFN X
WHERE EXISTS (SELECT Y.BDCODVER FROM VW_VRH_BASE_TVERBAS_REF Y WHERE Y.BDCODVER = X.BDCODVER AND Y.BDGRAVAFICHAHNVER = 'TRUE')
UNION
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFFN,
  0 BDTIPOCALC,
  0 BDCCFN,
  X.BDREFVFN,
  X.BDREFAUXVFN,
  X.BDVALVFN,
  CAST(NULL AS DATE)
FROM
VRHF_EMP_TVERBAINT X
WHERE EXISTS (SELECT Y.BDCODVER FROM VW_VRH_BASE_TVERBAS_REF Y WHERE Y.BDCODVER = X.BDCODVER AND Y.BDGRAVAFICHAHNVER = 'TRUE')
UNION
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFTOMADOR,
  100 BDTIPOCALC,
  X.BDORDEM,
  X.BDREFVFT,
  X.BDREFAUXVFT,
  X.BDVALVFT,
  CAST(NULL AS DATE)
FROM
VRHF_EMP_TVERBATOMADOR X
WHERE EXISTS (SELECT Y.BDCODVER FROM VW_VRH_BASE_TVERBAS_REF Y WHERE Y.BDCODVER = X.BDCODVER AND Y.BDGRAVAFICHAHNVER = 'TRUE')
UNION
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFTOMADOR,
  100 BDTIPOCALC,
  X.BDORDEM,
  X.BDREFVFT,
  X.BDREFAUXVFT,
  X.BDVALVFT,
  CAST(NULL AS DATE)
FROM
VRHF_EMP_TVERBATOMINT X
WHERE EXISTS (SELECT Y.BDCODVER FROM VW_VRH_BASE_TVERBAS_REF Y WHERE Y.BDCODVER = X.BDCODVER AND Y.BDGRAVAFICHAHNVER = 'TRUE')
UNION
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFFN,
  1 BDTIPOCALC,
  0 BDCCFC,
  X.BDREFVFC,
  X.BDREFAUXVFC,
  X.BDVALVFC,
  CAST((SUBSTRING(CAST(X.BDREFFC AS VARCHAR(8)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(8)) FROM 7 FOR 2)||'/'||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(8)) FROM 1 FOR 4)) AS DATE)
FROM
VRHF_EMP_TVERBAFC X
WHERE EXISTS (SELECT Y.BDCODVER FROM VW_VRH_BASE_TVERBAS_REF Y WHERE Y.BDCODVER = X.BDCODVER AND Y.BDGRAVAFICHAHNVER = 'TRUE')
UNION
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFTOMADOR,
  101 BDTIPOCALC,
  X.BDORDEM,
  X.BDREFVFC,
  X.BDREFAUXVFC,
  X.BDVALVFC,
  CAST((SUBSTRING(CAST(X.BDREFFC AS VARCHAR(8)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(8)) FROM 7 FOR 2)||'/'||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(8)) FROM 1 FOR 4)) AS DATE)
FROM
VRHF_EMP_TVERBAFCTOMADOR X
WHERE EXISTS (SELECT Y.BDCODVER FROM VW_VRH_BASE_TVERBAS_REF Y WHERE Y.BDCODVER = X.BDCODVER AND Y.BDGRAVAFICHAHNVER = 'TRUE')
UNION
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  CAST((SUBSTRING(CAST(X.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(X.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER),
  200 BDTIPOCALC,
  0 BDCCFHE,
  X.BDREFVFA,
  X.BDREFAUXVFA,
  X.BDVALVFA,
  X.BDDATAFA
FROM
  VRHF_EMP_TVERBAFA X
WHERE EXISTS (SELECT Y.BDCODVER FROM VW_VRH_BASE_TVERBAS_REF Y WHERE Y.BDCODVER = X.BDCODVER AND Y.BDGRAVAFICHAHNVER = 'TRUE')

UNION
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFFOT,
  9999 BDTIPOCALC,
  0 BDCCFHE,
  X.BDVREFFOT,
  0.000000 BDREFAUXFOT,
  X.BDVVALFOT,
  CAST(NULL AS DATE)
FROM
VRHF_EMP_TFICHAOUTRAS X
WHERE
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHANORMAL Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREFFOT)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMADOR Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFTOMADOR = X.BDREFFOT)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMP Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREFFOT)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMP Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFTOMADOR = X.BDREFFOT)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHAINT Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREFFOT)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMINT Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFTOMADOR = X.BDREFFOT)
;

/* CREATE OR ALTER VIEW: VW_UNION_FICHASFINANCEIRAS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_FICHASFINANCEIRAS(
BDCODEMP,
BDCODCOL,
BDCODVER,
BDREF,
BDTIPO,
BDCC,
BDVREF,
BDVREFAUX,
BDVVAL)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDCODVER,
  BDREFFHE,
  BDTIPOFHE,
  BDCCFHE,
  BDVREFFHE,
  BDVREFAUXFHE,
  BDVVALFHE
FROM
  VW_VRHF_EMP_TFICHAHE

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDCODVER,
  BDREFFRV,
  BDTIPOFRV,
  BDCCFRV,
  BDVREFFRV,
  BDVREFAUXFRV,
  BDVVALFRV
FROM VW_VRHF_EMP_TFICHARV

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDCODVER,
  BDREFFHN,
  BDTIPOFHN,
  BDCCFHN,
  BDVREFFHN,
  BDVREFAUXFHN,
  BDVVALFHN
FROM VW_VRHF_EMP_TFICHAHN

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDCODVER,
  BDREFFOT,
  BDTIPOFOT,
  BDCCFOT,
  BDVREFFOT,
  BDVREFAUXFOT,
  BDVVALFOT
FROM
  VW_VRHF_EMP_TFICHAOUTRAS
;

/* CREATE OR ALTER VIEW: VW_UNION_FN_TOMADOR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_FN_TOMADOR(
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDDATABAIXAFN,
    BDDATAPGTOFN,
    BDBFGTSFN,
    BDFGTSFN,
    BDFGTSCSFN,
    BDBFGTS13FN,
    BDFGTS13FN,
    BDFGTS13CSFN,
    BDMAIORREMFN,
    BDBINSSFN,
    BDALIQINSSFN,
    BDINSSFN,
    BDBIRRFFN,
    BDALIQIRRFFN,
    BDIRRFFN,
    BDBINSS13FN,
    BDALIQINSS13FN,
    BDINSS13FN,
    BDBIRRF13FN,
    BDALIQIRRF13FN,
    BDIRRF13FN,
    BDBSALFAMFN,
    BDSALFAMFN,
    BDBRAISFN,
    BDSALBASEFN,
    BDDEPFN,
    BDBASEPISFN,
    BDBASEPISFEFN,
    BDBASEPIS13FN,
    BDBSALMATEMPFN,
    BDSALMATEMPFN,
    BDBRATAPOFN,
    BDBRATAPOFEFN,
    BDBRATAPO13FN,
    BDBINSSFEFOLFN,
    BDINSSFEFOLFN,
    BDALIQINSSFEFOLFN,
    BDCREDITFN,
    BDDEBITOFN,
    BDBFGTSFEFN,
    BDFGTSFEFN)
AS
SELECT
  FN.BDCODEMP,
  FN.BDCODCOL,
  FN.BDREFFN,
  FN.BDDATABAIXAFN,
  FN.BDDATAPGTOFN,
  FN.BDBFGTSFN,
  FN.BDFGTSFN,
  FN.BDFGTSCSFN,
  FN.BDBFGTS13FN,
  FN.BDFGTS13FN,
  FN.BDFGTS13CSFN,
  FN.BDMAIORREMFN,
  FN.BDBINSSFN,
  FN.BDALIQINSSFN,
  FN.BDINSSFN,
  FN.BDBIRRFFN,
  FN.BDALIQIRRFFN,
  FN.BDIRRFFN,
  FN.BDBINSS13FN,
  FN.BDALIQINSS13FN,
  FN.BDINSS13FN,
  FN.BDBIRRF13FN,
  FN.BDALIQIRRF13FN,
  FN.BDIRRF13FN,
  FN.BDBSALFAMFN,
  FN.BDSALFAMFN,
  FN.BDBRAISFN,
  FN.BDSALBASEFN,
  FN.BDDEPFN,
  FN.BDBASEPISFN,
  FN.BDBASEPISFEFN,
  FN.BDBASEPIS13FN,
  FN.BDBSALMATEMPFN,
  FN.BDSALMATEMPFN,
  FN.BDBRATAPOFN,
  FN.BDBRATAPOFEFN,
  FN.BDBRATAPO13FN,
  FN.BDBINSSFEFOLFN,
  FN.BDINSSFEFOLFN,
  FN.BDALIQINSSFEFOLFN,
  FN.BDCREDITOFN,
  FN.BDDEBITOFN,
  FN.bdbfgtsfefn,
  FN.bdfgtsfefn
FROM vrhf_emp_tfolhanormal FN

UNION

SELECT
  FNT.BDCODEMP,
  FNT.BDCODCOL,
  FNT.BDREFTOMADOR,
  FNT.BDDATABAIXAFT,
  FNT.BDDATAPGTOFT,
  FNT.BDBFGTSFT,
  FNT.BDFGTSFT,
  FNT.BDFGTSCSFT,
  FNT.BDBFGTS13FT,
  FNT.BDFGTS13FT,
  FNT.BDFGTS13CSFT,
  FNT.BDMAIORREMFT,
  FNT.BDBINSSFT,
  FNT.BDALIQINSSFT,
  FNT.BDINSSFT,
  FNT.BDBIRRFFT,
  FNT.BDALIQIRRFFT,
  FNT.BDIRRFFT,
  FNT.BDBINSS13FT,
  FNT.BDALIQINSS13FT,
  FNT.BDINSS13FT,
  FNT.BDBIRRF13FT,
  FNT.BDALIQIRRF13FT,
  FNT.BDIRRF13FT,
  FNT.BDBSALFAMFT,
  FNT.BDSALFAMFT,
  FNT.BDBRAISFT,
  FNT.BDSALBASEFT,
  FNT.BDDEPFT,
  FNT.BDBASEPISFT,
  FNT.BDBASEPISFEFT,
  FNT.BDBASEPIS13FT,
  FNT.BDBSALMATEMPFT,
  FNT.BDSALMATEMPFT,
  FNT.BDBRATAPOFT,
  FNT.BDBRATAPOFEFT,
  FNT.BDBRATAPO13FT,
  FNT.BDBINSSFEFOLFT,
  FNT.BDINSSFEFOLFT,
  FNT.BDALIQINSSFEFOLFT,
  FNT.BDCREDITOFT,
  FNT.BDDEBITOFT,
  FNT.bdbfgtsfeft,
  FNT.bdfgtsfeft
FROM VRHF_EMP_TFOLHATOMADOR FNT
;

/* CREATE OR ALTER VIEW: VW_UNION_FN_TOMADOR_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_FN_TOMADOR_REF(
BDCODEMP,
BDCODCOL,
BDREFFN,
BDDATABAIXAFN,
BDBFGTSFN,
BDFGTSFN,
BDFGTSCSFN,
BDBFGTS13FN,
BDFGTS13FN,
BDFGTS13CSFN,
BDMAIORREMFN,
BDBINSSFN,
BDALIQINSSFN,
BDINSSFN,
BDBIRRFFN,
BDALIQIRRFFN,
BDIRRFFN,
BDBINSS13FN,
BDALIQINSS13FN,
BDINSS13FN,
BDBIRRF13FN,
BDALIQIRRF13FN,
BDIRRF13FN,
BDBSALFAMFN,
BDSALFAMFN,
BDBRAISFN,
BDSALBASEFN,
BDDEPFN,
BDBASEPISFN,
BDBASEPISFEFN,
BDBASEPIS13FN,
BDBSALMATEMPFN,
BDSALMATEMPFN,
BDBRATAPOFN,
BDBRATAPOFEFN,
BDBRATAPO13FN,
BDBINSSFEFOLFN,
BDINSSFEFOLFN,
BDALIQINSSFEFOLFN,
BDCREDITOFN,
BDDEBITOFN,
BDBFGTSFEFN,
BDFGTSFEFN,
BDLIQUIDO,
BDPROVENTO,
BDDESCONTO)
 AS 
SELECT
  FN.BDCODEMP,
  FN.BDCODCOL,
  FN.BDREFFN,
  FN.BDDATABAIXAFN,
  FN.BDBFGTSFN,
  FN.BDFGTSFN,
  FN.BDFGTSCSFN,
  FN.BDBFGTS13FN,
  FN.BDFGTS13FN,
  FN.BDFGTS13CSFN,
  FN.BDMAIORREMFN,
  FN.BDBINSSFN,
  FN.BDALIQINSSFN,
  FN.BDINSSFN,
  FN.BDBIRRFFN,
  FN.BDALIQIRRFFN,
  FN.BDIRRFFN,
  FN.BDBINSS13FN,
  FN.BDALIQINSS13FN,
  FN.BDINSS13FN,
  FN.BDBIRRF13FN,
  FN.BDALIQIRRF13FN,
  FN.BDIRRF13FN,
  FN.BDBSALFAMFN,
  FN.BDSALFAMFN,
  FN.BDBRAISFN,
  FN.BDSALBASEFN,
  FN.BDDEPFN,
  FN.BDBASEPISFN,
  FN.BDBASEPISFEFN,
  FN.BDBASEPIS13FN,
  FN.BDBSALMATEMPFN,
  FN.BDSALMATEMPFN,
  FN.BDBRATAPOFN,
  FN.BDBRATAPOFEFN,
  FN.BDBRATAPO13FN,
  FN.BDBINSSFEFOLFN,
  FN.BDINSSFEFOLFN,
  FN.BDALIQINSSFEFOLFN,
  FN.BDCREDITOFN,
  FN.BDDEBITOFN,
  FN.BDBFGTSFEFN,
  FN.BDFGTSFEFN,
  fn.BDLIQUIDO,
  tot.bdprovento,
  tot.bddesconto
FROM vrhf_emp_tfolhanormal FN
LEFT OUTER JOIN (SELECT vf.bdcodemp,vf.bdcodcol,vf.bdreffn,SUM(CASE WHEN v.bdtipocodver = 0 THEN vf.bdvalvfn ELSE 0 END) bdprovento, SUM(CASE WHEN v.bdtipocodver = 1 THEN vf.bdvalvfn ELSE 0 END) bddesconto
FROM vrhf_emp_tverbafn vf
JOIN vw_tverbas_ref v ON (vf.bdcodver = v.bdcodver)
GROUP BY vf.bdcodemp,vf.bdcodcol,vf.bdreffn) tot ON (fn.bdcodemp = tot.bdcodemp AND fn.bdcodcol = tot.bdcodcol AND fn.bdreffn = tot.bdreffn)

UNION ALL

SELECT
  FNT.BDCODEMP,
  FNT.BDCODCOL,
  FNT.BDREFTOMADOR,
  MAX(FNT.BDDATABAIXAFT),
  SUM(FNT.BDBFGTSFT),
  SUM(FNT.BDFGTSFT),
  SUM(FNT.BDFGTSCSFT),
  SUM(FNT.BDBFGTS13FT),
  SUM(FNT.BDFGTS13FT),
  SUM(FNT.BDFGTS13CSFT),
  MAX(FNT.BDMAIORREMFT),
  SUM(FNT.BDBINSSFT),
  MAX(FNT.BDALIQINSSFT),
  SUM(FNT.BDINSSFT),
  SUM(FNT.BDBIRRFFT),
  MAX(FNT.BDALIQIRRFFT),
  SUM(FNT.BDIRRFFT),
  SUM(FNT.BDBINSS13FT),
  MAX(FNT.BDALIQINSS13FT),
  SUM(FNT.BDINSS13FT),
  SUM(FNT.BDBIRRF13FT),
  MAX(FNT.BDALIQIRRF13FT),
  SUM(FNT.BDIRRF13FT),
  SUM(FNT.BDBSALFAMFT),
  SUM(FNT.BDSALFAMFT),
  SUM(FNT.BDBRAISFT),
  MAX(FNT.BDSALBASEFT),
  SUM(FNT.BDDEPFT),
  SUM(FNT.BDBASEPISFT),
  SUM(FNT.BDBASEPISFEFT),
  SUM(FNT.BDBASEPIS13FT),
  SUM(FNT.BDBSALMATEMPFT),
  SUM(FNT.BDSALMATEMPFT),
  SUM(FNT.BDBRATAPOFT),
  SUM(FNT.BDBRATAPOFEFT),
  SUM(FNT.BDBRATAPO13FT),
  SUM(FNT.BDBINSSFEFOLFT),
  SUM(FNT.BDINSSFEFOLFT),
  MAX(FNT.BDALIQINSSFEFOLFT),
  SUM(FNT.BDCREDITOFT),
  SUM(FNT.BDDEBITOFT),
  SUM(FNT.BDBFGTSFEFT),
  SUM(FNT.BDFGTSFEFT),
  SUM(fnt.bdliquido),
  MAX(tot.bdprovento),
  MAX(tot.bddesconto)
FROM VRHF_EMP_TFOLHATOMADOR FNT
LEFT OUTER JOIN (
SELECT vf.bdcodemp,vf.bdcodcol,vf.bdreftomador,SUM(CASE WHEN v.bdtipocodver = 0 THEN vf.bdvalvft ELSE 0 END) bdprovento, SUM(CASE WHEN v.bdtipocodver = 1 THEN vf.bdvalvft ELSE 0 END) bddesconto
FROM vrhf_emp_tverbatomador vf
JOIN vw_tverbas_ref v ON (vf.bdcodver = v.bdcodver)
GROUP BY vf.bdcodemp,vf.bdcodcol,vf.bdreftomador) tot ON (fnt.bdreftomador = tot.bdreftomador AND fnt.bdcodemp = tot.bdcodemp AND fnt.bdcodcol = tot.bdcodcol)

GROUP BY FNT.BDCODEMP, FNT.BDCODCOL, FNT.BDREFTOMADOR
;

CREATE OR ALTER VIEW VW_UNION_FNINT_TOMINT_REF(
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDDATABAIXAFN,
    BDBFGTSFN,
    BDFGTSFN,
    BDFGTSCSFN,
    BDBFGTS13FN,
    BDFGTS13FN,
    BDFGTS13CSFN,
    BDMAIORREMFN,
    BDBINSSFN,
    BDALIQINSSFN,
    BDINSSFN,
    BDBIRRFFN,
    BDALIQIRRFFN,
    BDIRRFFN,
    BDBINSS13FN,
    BDALIQINSS13FN,
    BDINSS13FN,
    BDBIRRF13FN,
    BDALIQIRRF13FN,
    BDIRRF13FN,
    BDBSALFAMFN,
    BDSALFAMFN,
    BDBRAISFN,
    BDSALBASEFN,
    BDDEPFN,
    BDBASEPISFN,
    BDBASEPISFEFN,
    BDBASEPIS13FN,
    BDBSALMATEMPFN,
    BDSALMATEMPFN,
    BDBRATAPOFN,
    BDBRATAPOFEFN,
    BDBRATAPO13FN,
    BDBINSSFEFOLFN,
    BDINSSFEFOLFN,
    BDALIQINSSFEFOLFN,
    BDCREDITOFN,
    BDDEBITOFN,
    BDBFGTSFEFN,
    BDFGTSFEFN,
    BDLIQUIDO,
    BDPROVENTO,
    BDDESCONTO)
AS
SELECT
  FN.BDCODEMP,
  FN.BDCODCOL,
  FN.BDREFFN,
  MAX(FN.BDDATABAIXAFN),
  SUM(FN.BDBFGTSFN),
  SUM(FN.BDFGTSFN),
  SUM(FN.BDFGTSCSFN),
  SUM(FN.BDBFGTS13FN),
  SUM(FN.BDFGTS13FN),
  SUM(FN.BDFGTS13CSFN),
  MAX(FN.BDMAIORREMFN),
  SUM(FN.BDBINSSFN),
  MAX(FN.BDALIQINSSFN),
  SUM(FN.BDINSSFN),
  SUM(FN.BDBIRRFFN),
  MAX(FN.BDALIQIRRFFN),
  SUM(FN.BDIRRFFN),
  SUM(FN.BDBINSS13FN),
  MAX(FN.BDALIQINSS13FN),
  SUM(FN.BDINSS13FN),
  SUM(FN.BDBIRRF13FN),
  MAX(FN.BDALIQIRRF13FN),
  SUM(FN.BDIRRF13FN),
  SUM(FN.BDBSALFAMFN),
  SUM(FN.BDSALFAMFN),
  SUM(FN.BDBRAISFN),
  MAX(FN.BDSALBASEFN),
  SUM(FN.BDDEPFN),
  SUM(FN.BDBASEPISFN),
  SUM(FN.BDBASEPISFEFN),
  SUM(FN.BDBASEPIS13FN),
  SUM(FN.BDBSALMATEMPFN),
  SUM(FN.BDSALMATEMPFN),
  SUM(FN.BDBRATAPOFN),
  SUM(FN.BDBRATAPOFEFN),
  SUM(FN.BDBRATAPO13FN),
  SUM(FN.BDBINSSFEFOLFN),
  SUM(FN.BDINSSFEFOLFN),
  MAX(FN.BDALIQINSSFEFOLFN),
  SUM(FN.BDCREDITOFN),
  SUM(FN.BDDEBITOFN),
  SUM(FN.BDBFGTSFEFN),
  SUM(FN.BDFGTSFEFN),
  SUM(fn.BDLIQUIDO),
  MAX(tot.bdprovento),
  MAX(tot.bddesconto)
FROM vrhf_emp_tfolhaint FN
LEFT OUTER JOIN (SELECT vf.bdcodemp,vf.bdcodcol,vf.bdreffn,SUM(CASE WHEN v.bdtipocodver = 0 THEN vf.bdvalvfn ELSE 0 END) bdprovento,
                        SUM(CASE WHEN v.bdtipocodver = 1 THEN vf.bdvalvfn ELSE 0 END) bddesconto
                 FROM vrhf_emp_tverbaint vf
                 JOIN vw_tverbas_ref v ON (vf.bdcodver = v.bdcodver)
                 GROUP BY vf.bdcodemp,vf.bdcodcol,vf.bdreffn) tot ON (fn.bdcodemp = tot.bdcodemp AND fn.bdcodcol = tot.bdcodcol AND fn.bdreffn = tot.bdreffn)
GROUP BY FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFN

UNION ALL

SELECT
  FNT.BDCODEMP,
  FNT.BDCODCOL,
  FNT.BDREFTOMADOR,
  MAX(FNT.BDDATABAIXAFT),
  SUM(FNT.BDBFGTSFT),
  SUM(FNT.BDFGTSFT),
  SUM(FNT.BDFGTSCSFT),
  SUM(FNT.BDBFGTS13FT),
  SUM(FNT.BDFGTS13FT),
  SUM(FNT.BDFGTS13CSFT),
  MAX(FNT.BDMAIORREMFT),
  SUM(FNT.BDBINSSFT),
  MAX(FNT.BDALIQINSSFT),
  SUM(FNT.BDINSSFT),
  SUM(FNT.BDBIRRFFT),
  MAX(FNT.BDALIQIRRFFT),
  SUM(FNT.BDIRRFFT),
  SUM(FNT.BDBINSS13FT),
  MAX(FNT.BDALIQINSS13FT),
  SUM(FNT.BDINSS13FT),
  SUM(FNT.BDBIRRF13FT),
  MAX(FNT.BDALIQIRRF13FT),
  SUM(FNT.BDIRRF13FT),
  SUM(FNT.BDBSALFAMFT),
  SUM(FNT.BDSALFAMFT),
  SUM(FNT.BDBRAISFT),
  MAX(FNT.BDSALBASEFT),
  SUM(FNT.BDDEPFT),
  SUM(FNT.BDBASEPISFT),
  SUM(FNT.BDBASEPISFEFT),
  SUM(FNT.BDBASEPIS13FT),
  SUM(FNT.BDBSALMATEMPFT),
  SUM(FNT.BDSALMATEMPFT),
  SUM(FNT.BDBRATAPOFT),
  SUM(FNT.BDBRATAPOFEFT),
  SUM(FNT.BDBRATAPO13FT),
  SUM(FNT.BDBINSSFEFOLFT),
  SUM(FNT.BDINSSFEFOLFT),
  MAX(FNT.BDALIQINSSFEFOLFT),
  SUM(FNT.BDCREDITOFT),
  SUM(FNT.BDDEBITOFT),
  SUM(FNT.BDBFGTSFEFT),
  SUM(FNT.BDFGTSFEFT),
  SUM(fnt.bdliquido),
  MAX(tot.bdprovento),
  MAX(tot.bddesconto)
FROM VRHF_EMP_TFOLHATOMINT FNT
LEFT OUTER JOIN (SELECT vf.bdcodemp,vf.bdcodcol,vf.bdreftomador,SUM(CASE WHEN v.bdtipocodver = 0 THEN vf.bdvalvft ELSE 0 END) bdprovento,
                        SUM(CASE WHEN v.bdtipocodver = 1 THEN vf.bdvalvft ELSE 0 END) bddesconto
                 FROM vrhf_emp_tverbatomint vf
                 JOIN vw_tverbas_ref v ON (vf.bdcodver = v.bdcodver)
                 GROUP BY vf.bdcodemp,vf.bdcodcol,vf.bdreftomador) tot ON (fnt.bdreftomador = tot.bdreftomador AND fnt.bdcodemp = tot.bdcodemp AND fnt.bdcodcol = tot.bdcodcol)
GROUP BY FNT.BDCODEMP, FNT.BDCODCOL, FNT.BDREFTOMADOR
;

/* CREATE OR ALTER VIEW: VW_UNION_FN_TOMADOR_VERBAS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_FN_TOMADOR_VERBAS(
BDCODVER,
BDCODEMP,
BDCODCOL,
BDREFFN,
BDREFVFN,
BDREFAUXVFN,
BDVALVFN,
BDIGNREFVFN,
BDIGNVALVFN)
 AS 
SELECT
  FN.BDCODVER,
  FN.BDCODEMP,
  FN.BDCODCOL,
  FN.BDREFFN,
  FN.BDREFVFN,
  FN.BDREFAUXVFN,
  FN.BDVALVFN,
  FN.BDIGNREFVFN,
  FN.BDIGNVALVFN
FROM VRHF_EMP_TVERBAFN FN

UNION

SELECT
  FNT.BDCODVER,
  FNT.BDCODEMP,
  FNT.BDCODCOL,
  FNT.BDREFTOMADOR,
  FNT.BDREFVFT,
  FNT.BDREFAUXVFT,
  FNT.BDVALVFT,
  FNT.BDIGNREFVFT,
  FNT.BDIGNVALVFT
FROM VRHF_EMP_TVERBATOMADOR FNT
;

/* CREATE OR ALTER VIEW: VW_UNION_FN_TOMADOR_VERBAS_DET (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_FN_TOMADOR_VERBAS_DET(
BDCODVER,
BDCODEMP,
BDCODCOL,
BDREFFN,
BDREFVFN,
BDREFAUXVFN,
BDVALVFN,
BDIGNREFVFN,
BDIGNVALVFN,
BDORDEMDETALHE,
BDDETALHEFND)
 AS 
SELECT
  FN.BDCODVER,
  FN.BDCODEMP,
  FN.BDCODCOL,
  FN.BDREFFN,
  FN.bdrefvfnd,
  FN.bdrefauxvfnd,
  FN.bdvalvfnd,
  FN.bdignrefvfnd,
  FN.bdignvalvfnd,
  fn.bdordemdetalhe,
  FN.BDDETALHEFND
FROM VRHF_EMP_TVERBAFN_DET FN

UNION

SELECT
  FNT.BDCODVER,
  FNT.BDCODEMP,
  FNT.BDCODCOL,
  FNT.BDREFTOMADOR,
  FNT.bdreftomador,
  FNT.bdrefauxvftd,
  FNT.bdvalvftd,
  FNT.bdignrefvftd,
  FNT.bdignvalvftd,
  fnt.bdordemdetalhe,
  FNT.BDDETALHEFTD
FROM vrhf_emp_tverbaft_det FNT
;

/* CREATE OR ALTER VIEW: VW_UNION_INSS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_INSS(
BDCODEMP,
BDCODCOL,
BDREF,
BDBINSSFN,
BDINSSFN,
BDBASEINSS13,
BDINSS13,
BDBASEINSSC13,
BDINSSC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBINSSFN,
  BDINSSFN,
  BDBASEINSS13,
  BDINSS13,
  BDBASEINSSC13,
  BDINSSC13,
  BDTIPO
FROM VW_INSS_FOL_NORMAL
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBINSSFN,
  BDINSSFN,
  BDBASEINSS13,
  BDINSS13,
  BDBASEINSSC13,
  BDINSSC13,
  BDTIPO
FROM VW_INSS_FOL_COMPLEMENTAR
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBINSSFN,
  BDINSSFN,
  BDBASEINSS13,
  BDINSS13,
  BDBASEINSSC13,
  BDINSSC13,
  BDTIPO
FROM VW_INSS_13S
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBINSSFN,
  BDINSSFN,
  BDBASEINSS13,
  BDINSS13,
  BDBASEINSSC13,
  BDINSSC13,
  BDTIPO
FROM VW_INSS_C13
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBINSSFN,
  BDINSSFN,
  BDBASEINSS13,
  BDINSS13,
  BDBASEINSSC13,
  BDINSSC13,
  BDTIPO
FROM vw_ficha_INSS
;

/* CREATE OR ALTER VIEW: VW_UNION_IR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_IR(
BDCODEMP,
BDCODCOL,
BDREF,
BDTIPOCALC,
BDBRUTO,
BDDEP,
BDVALIR,
BDVALINSS,
BDTIPO)
 AS 
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDTIPOCALC,
    BDBRUTO,
    BDDEP,
    BDVALIR,
    BDVALINSS,
    BDTIPO
FROM VW_IR_FOL_NORMAL
UNION
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDTIPOCALC,
    BDBRUTO,
    BDDEP,
    BDVALIR,
    BDVALINSS,
    BDTIPO
FROM VW_IR_FOL_COMPLEMENTAR
UNION
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDTIPOCALC,
    BDBRUTO,
    BDDEP,
    BDVALIR,
    BDVALINSS,
    BDTIPO
FROM vw_ficha_IR
UNION
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDTIPOCALC,
    BDBRUTO,
    BDDEP,
    BDVALIR,
    BDVALINSS,
    BDTIPO
FROM vw_IR_13S
UNION
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDTIPOCALC,
    BDBRUTO,
    BDDEP,
    BDVALIR,
    BDVALINSS,
    BDTIPO
FROM vw_IR_C13


UNION
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDTIPOCALC,
    BDBRUTO,
    BDDEP,
    BDVALIR,
    BDVALINSS,
    BDTIPO
FROM vw_IR_FERIAS
;

/* CREATE OR ALTER VIEW: VW_UNION_MOVIMENTACOES (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_MOVIMENTACOES(
BDCODEMP,
BDCODCOL,
BDDATAMOV,
BDCODMFG,
BDCODSEFMFG,
BDDESCMFG,
BDTIPO)
 AS 
SELECT
  RESC.BDCODEMP,
  RESC.BDCODCOL,
  RESC.BDDATARESCISAO,
  PRES.BDCODMFG,
  MFG.BDCODSEFMFG,
  MFG.BDDESCMFG,
  'Rescisão'
FROM
  VRH_EMP_TRESCISAO RESC,
  VRH_BASE_TPREPRESC PRES,
  VRH_BASE_TMOTFGTS MFG
WHERE
  PRES.bdtipomov = 0 AND
  RESC.BDCODPRES = PRES.BDCODPRES
  AND PRES.BDCODMFG = MFG.BDCODMFG

UNION

SELECT
  SIT.BDCODEMP,
  SIT.BDCODCOL,
  SIT.BDDATAINISIT,
  PSIT.BDCODMFGENT,
  MFG.BDCODSEFMFG,
  MFG.BDDESCMFG,
  'Situação (afastamento) Entrada'
FROM
  VRH_EMP_TSITCOL SIT,
  VRH_BASE_TPREPSIT PSIT,
  VRH_BASE_TMOTFGTS MFG
WHERE
  SIT.BDCODSIT = PSIT.BDCODSIT
  AND PSIT.BDCODMFGENT = MFG.BDCODMFG

UNION

SELECT
  SIT.BDCODEMP,
  SIT.BDCODCOL,
  SIT.BDDATAFIMSIT,
  PSIT.BDCODMFGSAI,
  MFG.BDCODSEFMFG,
  MFG.BDDESCMFG,
  'Situação (afastamento) Retorno'
FROM
  VRH_EMP_TSITCOL SIT,
  VRH_BASE_TPREPSIT PSIT,
  VRH_BASE_TMOTFGTS MFG

WHERE
  SIT.BDDATAFIMSIT IS NOT NULL AND
  SIT.BDCODSIT = PSIT.BDCODSIT
  AND PSIT.BDCODMFGSAI = MFG.BDCODMFG

UNION

SELECT
  TRANS.BDCODEMPORIG,
  TRANS.BDCODCOLORIG,
  TRANS.BDDATATRF,
  PTRANS.BDCODMFG,
  MFG.BDCODSEFMFG,
  MFG.BDDESCMFG,
  'Transferência'
FROM
  VRH_EMP_TTRANSCOL TRANS,
  vrh_base_tprepresc PTRANS,
  VRH_BASE_TMOTFGTS MFG
WHERE
  PTRANS.bdtipomov = 1 AND
  TRANS.BDCODPTRAN = PTRANS.bdcodpres
  AND PTRANS.BDCODMFG = MFG.BDCODMFG
;

/* CREATE OR ALTER VIEW: VW_VERBAS_FF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBAS_FF(
BDCODEMP,
BDCODCOL,
BDCODVER,
BDREFF,
BDREF,
BDVAL)
 AS 
SELECT
  DISTINCT X.BDCODEMP,
           X.BDCODCOL,
           X.BDCODVER,
           X.BDREFF,
           X.BDREFVAL BDREF,
           X.BDREFVAL BDVAL
FROM VW_UNION_FF_HE_RV_HN X
WHERE NOT EXISTS(SELECT FN.BDREFFN FROM VRHF_EMP_TFOLHANORMAL FN WHERE FN.BDCODEMP = X.BDCODEMP AND FN.BDCODCOL = X.BDCODCOL AND FN.BDREFFN = X.BDREFF) AND
      NOT EXISTS(SELECT FC.BDREFCOMP FROM VRHF_EMP_TFOLHACOMP FC WHERE FC.BDCODEMP = X.BDCODEMP AND FC.BDCODCOL = X.BDCODCOL AND FC.BDREFCOMP = X.BDREFF) AND
      NOT EXISTS(SELECT PL.BDCOMPLANC FROM VRHF_EMP_TPLANLANC PL WHERE PL.BDCODEMP = X.BDCODEMP AND PL.BDCODCOL = X.BDCODCOL AND PL.BDCOMPLANC = X.BDREFF)
;

/* CREATE OR ALTER VIEW: VW_UNION_PL_VERBAS_FF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_PL_VERBAS_FF(
BDCODEMP,
BDCODCOL,
BDCODVER,
BDDATA,
BDREFV,
BDVALV,
BDREFCONG,
BDVALCONG,
BDORIGEM,
BDCOMP)
 AS 
SELECT
  PL.BDCODEMP,
  PL.BDCODCOL,
  PL.BDCODVER,
  PL.BDDATALANC,
  PL.BDREFLANC,
  PL.BDVALLANC,
  PL.BDREFCONGLANC,
  PL.BDVALCONGLANC,
  PL.BDORIGEMLANC,
  PL.BDCOMPLANC
FROM VRHF_EMP_TPLANLANC PL
WHERE
  EXISTS(SELECT FN.BDCODVER FROM VRHF_EMP_TVERBAFN FN WHERE PL.BDCODEMP = FN.BDCODEMP AND PL.BDCODCOL = FN.BDCODCOL AND PL.BDCOMPLANC = FN.BDREFFN AND PL.BDCODVER = FN.BDCODVER) OR
  EXISTS(SELECT FC.BDCODVER FROM VRHF_EMP_TVERBAFC FC WHERE PL.BDCODEMP = FC.BDCODEMP AND PL.BDCODCOL = FC.BDCODCOL AND PL.BDCOMPLANC = FC.BDREFCOMP AND PL.BDCODVER = FC.BDCODVER)

UNION

SELECT
  FF.BDCODEMP,
  FF.BDCODCOL,
  FF.BDCODVER,
  CAST(   (SUBSTRING((CAST(FF.BDREFF AS VARCHAR(6))) FROM 5 FOR 2)||'/'||'01/'||SUBSTRING((CAST(FF.BDREFF AS VARCHAR(6))) FROM 1 FOR 4))    AS DATE) BDDATA_1,
  FF.BDREF,
  FF.BDVAL,
  'FALSE',
  'FALSE',
  0,
  FF.BDREFF
FROM VW_VERBAS_FF FF

UNION

SELECT
  FN.BDCODEMP,
  FN.BDCODCOL,
  FN.BDCODVER,
  CAST(   (SUBSTRING((CAST(FN.BDREFFN AS VARCHAR(6))) FROM 5 FOR 2)||'/'||'01/'||SUBSTRING((CAST(FN.BDREFFN AS VARCHAR(6))) FROM 1 FOR 4))    AS DATE) BDDATA_2,
  FN.BDREFVFN,
  FN.BDVALVFN,
  'FALSE',
  'FALSE',
  1,
  FN.BDREFFN
FROM VRHF_EMP_TVERBAFN FN
WHERE
  NOT EXISTS(SELECT P.BDCODEMP, P.BDCODCOL FROM VRHF_EMP_TPLANLANC P WHERE P.BDCODEMP = FN.BDCODEMP AND P.BDCODCOL = FN.BDCODCOL AND P.BDCODVER = FN.BDCODVER AND P.BDCOMPLANC = FN.BDREFFN) AND
  NOT EXISTS(SELECT W.BDCODVER FROM VRH_BASE_TVERBAS W WHERE W.BDCODVER = FN.BDCODVER AND W.BDCLAVER LIKE '9%')
;

/* CREATE OR ALTER VIEW: VW_UNION_RAIS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_RAIS(
BDCODEMP,
BDCODCOL,
BDREF,
BDBRAISFN,
BDBRAIS13,
BDBRAISA13,
BDBRAISC13,
BDTIPO)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBRAISFN,
  BDBRAIS13,
  BDBRAISA13,
  BDBRAISC13,
  BDTIPO
FROM VW_RAIS_FOL_NORMAL
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBRAISFN,
  BDBRAIS13,
  BDBRAISA13,
  BDBRAISC13,
  BDTIPO
FROM VW_RAIS_FOL_COMPLEMENTAR
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBRAISFN,
  BDBRAIS13,
  BDBRAISA13,
  BDBRAISC13,
  BDTIPO
FROM VW_RAIS_A13
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBRAISFN,
  BDBRAIS13,
  BDBRAISA13,
  BDBRAISC13,
  BDTIPO
FROM VW_RAIS_13S
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBRAISFN,
  BDBRAIS13,
  BDBRAISA13,
  BDBRAISC13,
  BDTIPO
FROM VW_RAIS_C13
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBRAISFN,
  BDBRAIS13,
  BDBRAISA13,
  BDBRAISC13,
  BDTIPO
FROM VW_RAIS_FOL_AVULSA
UNION
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDBRAISFN,
  BDBRAIS13,
  BDBRAISA13,
  BDBRAISC13,
  BDTIPO
FROM vw_ficha_RAIS
;

/* CREATE OR ALTER VIEW: VW_UNION_RENDIMENTO_ISENTO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_RENDIMENTO_ISENTO(
BDCODEMP,
BDCODCOL,
BDREFRIS,
BDVALRIS,
BDCLAVER,
BDDESCVER,
BDDESCREDVER)
 AS 
SELECT
  FN.BDCODEMP,
  FN.BDCODCOL,
  FN.BDREFFN,
  FN.BDVALVFN,
  VER.BDCLAVER,
  VER.BDDESCVER,
  VER.BDDESCREDVER
FROM vrhf_emp_tverbafn FN
LEFT OUTER JOIN VRH_BASE_TVERBAS VER
  ON (VER.BDCODVER = FN.BDCODVER)
LEFT OUTER JOIN vw_verbas_ref_atual VERR     -- Nao se esqueca de setar as variaveis de Ano_Mes
  ON (VERR.BDCODVER = FN.BDCODVER)
WHERE VERR.BDRENDISENTOIRVER = 'TRUE'
UNION
SELECT
  FC.BDCODEMP,
  FC.BDCODCOL,
  FC.BDREFCOMP,
  FC.BDVALVFC,
  VER2.BDCLAVER,
  VER2.BDDESCVER,
  VER2.BDDESCREDVER
FROM vrhf_emp_tverbafc FC
LEFT OUTER JOIN VRH_BASE_TVERBAS VER2
  ON (VER2.BDCODVER = FC.BDCODVER)
LEFT OUTER JOIN vw_verbas_ref_atual VERR2
  ON (VERR2.BDCODVER = FC.BDCODVER)
WHERE VERR2.BDRENDISENTOIRVER = 'TRUE'
;

/* CREATE OR ALTER VIEW: VW_UNION_VEF_SER_RET (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_VEF_SER_RET(
    BDCODEMP,
    BDDATAEMISSAO,
    BDDT_EXE_SERV,
    BDVLRPIS,
    BDVLRCOFINS,
    BDVLRCSOCIAL,
    BDSUBEMPREI,
    BDMATERIAIS,
    BDCODRECPIS,
    BDCODRECCOFINS,
    BDCODRECCSOCIAL,
    BDVLRIRSER,
    BDCODRECIR,
    BDTIPLAN,
    BDVLRMATERIAIS,
    BDVLRSUBEMPREITEIRAS,
    BDCODRECINSS,
    BDISSRET,
    BDREFLAN,
    BDCHAVE,
    BDRETINSS,
    BDCONDPGTO)
AS
SELECT MOV.BDCODEMP,MOV.BDDATAEMISSAO, MOV.BDDT_EXE_SERV, RET.BDVLRPIS, RET.BDVLRCOFINS, RET.BDVLRCSOCIAL, RET.BDSUBEMPREI,
       RET.BDMATERIAIS, RET.BDCODRECPIS, RET.BDCODRECCOFINS, RET.BDCODRECCSOCIAL, mov.BDVLRIRSER,
       mov.BDCODRECIR, MOV.BDTIPLAN, 0 BDVLRMATERIAIS, 0 BDVLRSUBEMPREITEIRAS, 0 BDCODRECINSS, RET.BDISSRET,
       MOV.BDREFLAN, MOV.BDCHAVE, 0 BDRETINSS, MOV.BDCONDPGTO
FROM (
      SELECT MOV.BDCODEMP,MOV.BDCHAVE, MOV.BDDATAEMISSAO, MOV.BDDT_EXE_SERV, MOV.BDTIPLAN, MOV.BDREFLAN, MOV.BDCONDPGTO,ITENS.BDCODREC BDCODRECIR, SUM(ITENS.BDVLRIRSER) BDVLRIRSER
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDDATAEMISSAO, MOV.BDDT_EXE_SERV, MOV.BDTIPLAN, MOV.BDREFLAN, MOV.BDCHAVE, MOV.BDCONDPGTO
            FROM VEF_EMP_TMOVSER MOV
            WHERE MOV.BDCODSITNF NOT IN (2, 3, 4, 5)
            )mov
      JOIN VEF_EMP_TMOVSERITENS ITENS ON ITENS.BDCODEMP = MOV.BDCODEMP AND ITENS.BDCHAVE = MOV.BDCHAVE
      GROUP BY MOV.BDCODEMP,MOV.BDCHAVE, MOV.BDDATAEMISSAO, MOV.BDDT_EXE_SERV, MOV.BDTIPLAN, MOV.BDREFLAN, MOV.BDCONDPGTO,ITENS.BDCODREC
      ) MOV
LEFT OUTER JOIN VEF_EMP_TMOVSERRET RET ON RET.BDCODEMP = MOV.BDCODEMP AND RET.BDCHAVE = MOV.BDCHAVE

UNION ALL

SELECT mov.bdcodemp,mov.bddataemissao, MOV.BDDT_EXE_SERV,0 BDVLRPIS,0 BDVLRCOFINS, 0 BDVLRCSOCIAL,0 BDSUBEMPREI,
       0 BDMATERIAIS,0 BDCODRECPIS,0 BDCODRECCOFINS,0 BDCODRECCSOCIAL,0 BDVLRIRSER,0 bdcodrecir,MOV.bdtiplan,
       d.bdvlrmateriais,d.bdvlrsubempreiteiras,d.bdcodrecinss, 0 BDISSRET,mov.bdreflan,mov.bdchave, d.bdretinss, mov.bdcondpgto
FROM (
      SELECT MOV.BDCODEMP, MOV.BDDATAEMISSAO, MOV.BDDT_EXE_SERV, MOV.BDTIPLAN, MOV.BDREFLAN, MOV.BDCHAVE, MOV.BDCONDPGTO
      FROM VEF_EMP_TMOVSER MOV
      WHERE MOV.BDCODSITNF NOT IN (2, 3, 4, 5)
      ) mov
LEFT OUTER JOIN vef_emp_tmovserded d ON d.bdcodemp = mov.bdcodemp AND d.bdchave = mov.bdchave
;

/* CREATE OR ALTER VIEW: VW_VERBAS_SIM_COL_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBAS_SIM_COL_ATUAL(
BDCODEMP,
BDCODCOL,
BDCODVER,
BDDATAINI,
BDDATAFIM,
BDDIAINI,
BDMESINI,
BDANOINI,
BDDIAFIM,
BDMESFIM,
BDANOFIM,
BDFORMULAREF,
BDFORMULAVAL,
BDFORMULAREFAUX,
BDCLAVER)
 AS 
SELECT V.BDCODEMP,
         V.BDCODCOL,
         V.BDCODVER,
         CASE WHEN ((V.BDANOINIVSCOL = 0) OR (V.BDANOINIVSCOL IS NULL)) AND (V.BDMESINIVSCOL > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (V.BDANOINIVSCOL = 0) OR (V.BDANOINIVSCOL IS NULL) THEN
                '0000'
              WHEN (V.BDANOINIVSCOL > 0) THEN
                CAST(V.BDANOINIVSCOL AS VARCHAR(4))
         END||
         CASE WHEN (V.BDMESINIVSCOL = 0) OR (V.BDMESINIVSCOL IS NULL) THEN
                '00'
              WHEN (V.BDMESINIVSCOL < 10) THEN
                '0'||V.BDMESINIVSCOL
              ELSE
                CAST(V.BDMESINIVSCOL AS VARCHAR(2))
         END||
         CASE WHEN (V.BDDIAINIVSCOL = 0) OR (V.BDDIAINIVSCOL IS NULL) THEN
                '00'
              WHEN (V.BDDIAINIVSCOL < 10) THEN
                '0'||V.BDDIAINIVSCOL
              ELSE
                CAST(V.BDDIAINIVSCOL AS VARCHAR(2))
         END, -- Data inicial

         CASE WHEN ((V.BDANOFIMVSCOL = 0) OR (V.BDANOFIMVSCOL IS NULL)) AND (V.BDMESFIMVSCOL > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (V.BDANOFIMVSCOL = 0) OR (V.BDANOFIMVSCOL IS NULL) THEN
                '9999'
              WHEN (V.BDANOFIMVSCOL > 0) THEN
                CAST(V.BDANOFIMVSCOL AS VARCHAR(4))
         END||
         CASE WHEN (V.BDMESFIMVSCOL = 0) OR (V.BDMESFIMVSCOL IS NULL) THEN
                '99'
              WHEN (V.BDMESFIMVSCOL < 10) THEN
                '0'||V.BDMESFIMVSCOL
              ELSE
                CAST(V.BDMESFIMVSCOL AS VARCHAR(2))
         END||
         CASE WHEN (V.BDDIAFIMVSCOL = 0) OR (V.BDDIAFIMVSCOL IS NULL) THEN
                '99'
              WHEN (V.BDDIAFIMVSCOL < 10) THEN
                '0'||V.BDDIAFIMVSCOL
              ELSE
                CAST(V.BDDIAFIMVSCOL AS VARCHAR(2))
         END, -- Data final
         V.BDDIAINIVSCOL,
         V.BDMESINIVSCOL,
         V.BDANOINIVSCOL,
         V.BDDIAFIMVSCOL,
         V.BDMESFIMVSCOL,
         V.BDANOFIMVSCOL,
         V.BDFORMULAREFCOL,
         V.BDFORMULAVALCOL,
         V.BDFORMULAREFAUXCOL,
         B.BDCLAVER
FROM VRHF_EMP_TVSCOL V
JOIN VRH_BASE_TVERBAS B on (B.BDCODVER = V.BDCODVER)
;

/* CREATE OR ALTER VIEW: VW_VERBAS_NAO_COL_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBAS_NAO_COL_ATUAL(
BDCODEMP,
BDCODCOL,
BDCODVER,
BDDATAINI,
BDDATAFIM,
BDDIAINI,
BDMESINI,
BDANOINI,
BDDIAFIM,
BDMESFIM,
BDANOFIM,
BDDESCCOND,
BDFERIASVN,
BD13VN)
 AS 
SELECT BDCODEMP,
         BDCODCOL,
         BDCODVER,
         CASE WHEN ((BDANOINIVNCOL = 0) OR (BDANOINIVNCOL IS NULL)) AND (BDMESINIVNCOL > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOINIVNCOL = 0) OR (BDANOINIVNCOL IS NULL) THEN
                '0000'
              WHEN (BDANOINIVNCOL > 0) THEN
                CAST(BDANOINIVNCOL AS VARCHAR(4))
         END||
         CASE WHEN (BDMESINIVNCOL = 0) OR (BDMESINIVNCOL IS NULL) THEN
                '00'
              WHEN (BDMESINIVNCOL < 10) THEN
                '0'||BDMESINIVNCOL
              ELSE
                CAST(BDMESINIVNCOL AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAINIVNCOL = 0) OR (BDDIAINIVNCOL IS NULL) THEN
                '00'
              WHEN (BDDIAINIVNCOL < 10) THEN
                '0'||BDDIAINIVNCOL
              ELSE
                CAST(BDDIAINIVNCOL AS VARCHAR(2))
         END, -- Data inicial

         CASE WHEN ((BDANOFIMVNCOL = 0) OR (BDANOFIMVNCOL IS NULL)) AND (BDMESFIMVNCOL > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOFIMVNCOL = 0) OR (BDANOFIMVNCOL IS NULL) THEN
                '9999'
              WHEN (BDANOFIMVNCOL > 0) THEN
                CAST(BDANOFIMVNCOL AS VARCHAR(4))
         END||
         CASE WHEN (BDMESFIMVNCOL = 0) OR (BDMESFIMVNCOL IS NULL) THEN
                '99'
              WHEN (BDMESFIMVNCOL < 10) THEN
                '0'||BDMESFIMVNCOL
              ELSE
                CAST(BDMESFIMVNCOL AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAFIMVNCOL = 0) OR (BDDIAFIMVNCOL IS NULL) THEN
                '99'
              WHEN (BDDIAFIMVNCOL < 10) THEN
                '0'||BDDIAFIMVNCOL
              ELSE
                CAST(BDDIAFIMVNCOL AS VARCHAR(2))
         END, -- Data final
         BDDIAINIVNCOL,
         BDMESINIVNCOL,
         BDANOINIVNCOL,
         BDDIAFIMVNCOL,
         BDMESFIMVNCOL,
         BDANOFIMVNCOL,
         BDDESCCONDCOL,
         BDFERIASVNCOL,
         BD13VNCOL
FROM VRHF_EMP_TVNCOL
;

/* CREATE OR ALTER VIEW: VW_VERBAS_SIM_EMP_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBAS_SIM_EMP_ATUAL(
BDCODEMP,
BDCODVER,
BDDATAINI,
BDDATAFIM,
BDDIAINI,
BDMESINI,
BDANOINI,
BDDIAFIM,
BDMESFIM,
BDANOFIM,
BDFORMULAREF,
BDFORMULAREFAUX,
BDFORMULAVAL)
 AS 
SELECT BDCODEMP,
         BDCODVER,
         CASE WHEN ((BDANOINIVSEMP = 0) OR (BDANOINIVSEMP IS NULL)) AND (BDMESINIVSEMP > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOINIVSEMP = 0) OR (BDANOINIVSEMP IS NULL) THEN
                '0000'
              WHEN (BDANOINIVSEMP > 0) THEN
                CAST(BDANOINIVSEMP AS VARCHAR(4))
         END||
         CASE WHEN (BDMESINIVSEMP = 0) OR (BDMESINIVSEMP IS NULL) THEN
                '00'
              WHEN (BDMESINIVSEMP < 10) THEN
                '0'||BDMESINIVSEMP
              ELSE
                CAST(BDMESINIVSEMP AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAINIVSEMP = 0) OR (BDDIAINIVSEMP IS NULL) THEN
                '00'
              WHEN (BDDIAINIVSEMP < 10) THEN
                '0'||BDDIAINIVSEMP
              ELSE
                CAST(BDDIAINIVSEMP AS VARCHAR(2))
         END, -- Data inicial

         CASE WHEN ((BDANOFIMVSEMP = 0) OR (BDANOFIMVSEMP IS NULL)) AND (BDMESFIMVSEMP > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOFIMVSEMP = 0) OR (BDANOFIMVSEMP IS NULL) THEN
                '9999'
              WHEN (BDANOFIMVSEMP > 0) THEN
                CAST(BDANOFIMVSEMP AS VARCHAR(4))
         END||
         CASE WHEN (BDMESFIMVSEMP = 0) OR (BDMESFIMVSEMP IS NULL) THEN
                '99'
              WHEN (BDMESFIMVSEMP < 10) THEN
                '0'||BDMESFIMVSEMP
              ELSE
                CAST(BDMESFIMVSEMP AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAFIMVSEMP = 0) OR (BDDIAFIMVSEMP IS NULL) THEN
                '99'
              WHEN (BDDIAFIMVSEMP < 10) THEN
                '0'||BDDIAFIMVSEMP
              ELSE
                CAST(BDDIAFIMVSEMP AS VARCHAR(2))
         END, -- Data final
         BDDIAINIVSEMP,
         BDMESINIVSEMP,
         BDANOINIVSEMP,
         BDDIAFIMVSEMP,
         BDMESFIMVSEMP,
         BDANOFIMVSEMP,
         BDFORMULAREFEMP,
         BDFORMULAREFAUXEMP,
         BDFORMULAVALEMP
FROM VRHF_EMP_TVSEMP
;

/* CREATE OR ALTER VIEW: VW_VERBAS_NAO_EMP_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBAS_NAO_EMP_ATUAL(
BDCODEMP,
BDCODVER,
BDDATAINI,
BDDATAFIM,
BDDIAINI,
BDMESINI,
BDANOINI,
BDDIAFIM,
BDMESFIM,
BDANOFIM,
BDDESCCOND,
BDFERIASVN,
BD13VN)
 AS 
SELECT BDCODEMP,
         BDCODVER,
         CASE WHEN ((BDANOINIVNEMP = 0) OR (BDANOINIVNEMP IS NULL)) AND (BDMESINIVNEMP > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOINIVNEMP = 0) OR (BDANOINIVNEMP IS NULL) THEN
                '0000'
              WHEN (BDANOINIVNEMP > 0) THEN
                CAST(BDANOINIVNEMP AS VARCHAR(4))
         END||
         CASE WHEN (BDMESINIVNEMP = 0) OR (BDMESINIVNEMP IS NULL) THEN
                '00'
              WHEN (BDMESINIVNEMP < 10) THEN
                '0'||BDMESINIVNEMP
              ELSE
                CAST(BDMESINIVNEMP AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAINIVNEMP = 0) OR (BDDIAINIVNEMP IS NULL) THEN
                '00'
              WHEN (BDDIAINIVNEMP < 10) THEN
                '0'||BDDIAINIVNEMP
              ELSE
                CAST(BDDIAINIVNEMP AS VARCHAR(2))
         END, -- Data inicial

         CASE WHEN ((BDANOFIMVNEMP = 0) OR (BDANOFIMVNEMP IS NULL)) AND (BDMESFIMVNEMP > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOFIMVNEMP = 0) OR (BDANOFIMVNEMP IS NULL) THEN
                '9999'
              WHEN (BDANOFIMVNEMP > 0) THEN
                CAST(BDANOFIMVNEMP AS VARCHAR(4))
         END||
         CASE WHEN (BDMESFIMVNEMP = 0) OR (BDMESFIMVNEMP IS NULL) THEN
                '99'
              WHEN (BDMESFIMVNEMP < 10) THEN
                '0'||BDMESFIMVNEMP
              ELSE
                CAST(BDMESFIMVNEMP AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAFIMVNEMP = 0) OR (BDDIAFIMVNEMP IS NULL) THEN
                '99'
              WHEN (BDDIAFIMVNEMP < 10) THEN
                '0'||BDDIAFIMVNEMP
              ELSE
                CAST(BDDIAFIMVNEMP AS VARCHAR(2))
         END, -- Data final
         BDDIAINIVNEMP,
         BDMESINIVNEMP,
         BDANOINIVNEMP,
         BDDIAFIMVNEMP,
         BDMESFIMVNEMP,
         BDANOFIMVNEMP,
         BDDESCCONDEMP,
         BDFERIASVNEMP,
         BD13VNEMP

FROM VRHF_EMP_TVNEMP
;

/* CREATE OR ALTER VIEW: VW_VERBAS_SIM_SIND_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBAS_SIM_SIND_ATUAL(
BDCODSINTRAB,
BDCODVER,
BDDATAINI,
BDDATAFIM,
BDDIAINI,
BDMESINI,
BDANOINI,
BDDIAFIM,
BDMESFIM,
BDANOFIM,
BDFORMULAREF,
BDFORMULAREFAUX,
BDFORMULAVAL)
 AS 
SELECT BDCODSINTRAB,
       BDCODVER,
       CASE WHEN ((BDANOINIVSSIND = 0) OR (BDANOINIVSSIND IS NULL)) AND (BDMESINIVSSIND > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOINIVSSIND = 0) OR (BDANOINIVSSIND IS NULL) THEN
                '0000'
              WHEN (BDANOINIVSSIND > 0) THEN
                CAST(BDANOINIVSSIND AS VARCHAR(4))
         END||
         CASE WHEN (BDMESINIVSSIND = 0) OR (BDMESINIVSSIND IS NULL) THEN
                '00'
              WHEN (BDMESINIVSSIND < 10) THEN
                '0'||BDMESINIVSSIND
              ELSE
                CAST(BDMESINIVSSIND AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAINIVSSIND = 0) OR (BDDIAINIVSSIND IS NULL) THEN
                '00'
              WHEN (BDDIAINIVSSIND < 10) THEN
                '0'||BDDIAINIVSSIND
              ELSE
                CAST(BDDIAINIVSSIND AS VARCHAR(2))
         END, -- Data inicial

         CASE WHEN ((BDANOFIMVSSIND = 0) OR (BDANOFIMVSSIND IS NULL)) AND (BDMESFIMVSSIND > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOFIMVSSIND = 0) OR (BDANOFIMVSSIND IS NULL) THEN
                '9999'
              WHEN (BDANOFIMVSSIND > 0) THEN
                CAST(BDANOFIMVSSIND AS VARCHAR(4))
         END||
         CASE WHEN (BDMESFIMVSSIND = 0) OR (BDMESFIMVSSIND IS NULL) THEN
                '99'
              WHEN (BDMESFIMVSSIND < 10) THEN
                '0'||BDMESFIMVSSIND
              ELSE
                CAST(BDMESFIMVSSIND AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAFIMVSSIND = 0) OR (BDDIAFIMVSSIND IS NULL) THEN
                '99'
              WHEN (BDDIAFIMVSSIND < 10) THEN
                '0'||BDDIAFIMVSSIND
              ELSE
                CAST(BDDIAFIMVSSIND AS VARCHAR(2))
         END, -- Data final
         BDDIAINIVSSIND,
         BDMESINIVSSIND,
         BDANOINIVSSIND,
         BDDIAFIMVSSIND,
         BDMESFIMVSSIND,
         BDANOFIMVSSIND,
         BDFORMULAREFSIND,
         BDFORMULAREFAUXSIND,
         BDFORMULAVALSIND
FROM VRHF_BASE_TVSSIND
;

/* CREATE OR ALTER VIEW: VW_VERBAS_NAO_SIND_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBAS_NAO_SIND_ATUAL(
BDCODSINTRAB,
BDCODVER,
BDDATAINI,
BDDATAFIM,
BDDIAINI,
BDMESINI,
BDANOINI,
BDDIAFIM,
BDMESFIM,
BDANOFIM,
BDDESCCOND,
BDFERIASVN,
BD13VN)
 AS 
SELECT BDCODSINTRAB,
       BDCODVER,
       CASE WHEN ((BDANOINIVNSIND = 0) OR (BDANOINIVNSIND IS NULL)) AND (BDMESINIVNSIND > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOINIVNSIND = 0) OR (BDANOINIVNSIND IS NULL) THEN
                '0000'
              WHEN (BDANOINIVNSIND > 0) THEN
                CAST(BDANOINIVNSIND AS VARCHAR(4))
         END||
         CASE WHEN (BDMESINIVNSIND = 0) OR (BDMESINIVNSIND IS NULL) THEN
                '00'
              WHEN (BDMESINIVNSIND < 10) THEN
                '0'||BDMESINIVNSIND
              ELSE
                CAST(BDMESINIVNSIND AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAINIVNSIND = 0) OR (BDDIAINIVNSIND IS NULL) THEN
                '00'
              WHEN (BDDIAINIVNSIND < 10) THEN
                '0'||BDDIAINIVNSIND
              ELSE
                CAST(BDDIAINIVNSIND AS VARCHAR(2))
         END, -- Data inicial

         CASE WHEN ((BDANOFIMVNSIND = 0) OR (BDANOFIMVNSIND IS NULL)) AND (BDMESFIMVNSIND > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOFIMVNSIND = 0) OR (BDANOFIMVNSIND IS NULL) THEN
                '9999'
              WHEN (BDANOFIMVNSIND > 0) THEN
                CAST(BDANOFIMVNSIND AS VARCHAR(4))
         END||
         CASE WHEN (BDMESFIMVNSIND = 0) OR (BDMESFIMVNSIND IS NULL) THEN
                '99'
              WHEN (BDMESFIMVNSIND < 10) THEN
                '0'||BDMESFIMVNSIND
              ELSE
                CAST(BDMESFIMVNSIND AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAFIMVNSIND = 0) OR (BDDIAFIMVNSIND IS NULL) THEN
                '99'
              WHEN (BDDIAFIMVNSIND < 10) THEN
                '0'||BDDIAFIMVNSIND
              ELSE
                CAST(BDDIAFIMVNSIND AS VARCHAR(2))
         END, -- Data final
         BDDIAINIVNSIND,
         BDMESINIVNSIND,
         BDANOINIVNSIND,
         BDDIAFIMVNSIND,
         BDMESFIMVNSIND,
         BDANOFIMVNSIND,
         BDDESCCONDSIND,
         BDFERIASVNSIND,
         BD13VNSIND

FROM VRHF_BASE_TVNSIND
;

/* CREATE OR ALTER VIEW: VW_VERBAS_SIM_FUNCOES_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBAS_SIM_FUNCOES_ATUAL(
BDCODPLAFUC,
BDCODTFUC,
BDCODVER,
BDDATAINI,
BDDATAFIM,
BDDIAINI,
BDMESINI,
BDANOINI,
BDDIAFIM,
BDMESFIM,
BDANOFIM,
BDFORMULAREF,
BDFORMULAREFAUX,
BDFORMULAVAL)
 AS 
SELECT BDCODPLAFUC,
       BDCODTFUC,
       BDCODVER,
       CASE WHEN ((BDANOINIVSFUC = 0) OR (BDANOINIVSFUC IS NULL)) AND (BDMESINIVSFUC > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOINIVSFUC = 0) OR (BDANOINIVSFUC IS NULL) THEN
                '0000'
              WHEN (BDANOINIVSFUC > 0) THEN
                CAST(BDANOINIVSFUC AS VARCHAR(4))
         END||
         CASE WHEN (BDMESINIVSFUC = 0) OR (BDMESINIVSFUC IS NULL) THEN
                '00'
              WHEN (BDMESINIVSFUC < 10) THEN
                '0'||BDMESINIVSFUC
              ELSE
                CAST(BDMESINIVSFUC AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAINIVSFUC = 0) OR (BDDIAINIVSFUC IS NULL) THEN
                '00'
              WHEN (BDDIAINIVSFUC < 10) THEN
                '0'||BDDIAINIVSFUC
              ELSE
                CAST(BDDIAINIVSFUC AS VARCHAR(2))
         END, -- Data inicial

         CASE WHEN ((BDANOFIMVSFUC = 0) OR (BDANOFIMVSFUC IS NULL)) AND (BDMESFIMVSFUC > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOFIMVSFUC = 0) OR (BDANOFIMVSFUC IS NULL) THEN
                '9999'
              WHEN (BDANOFIMVSFUC > 0) THEN
                CAST(BDANOFIMVSFUC AS VARCHAR(4))
         END||
         CASE WHEN (BDMESFIMVSFUC = 0) OR (BDMESFIMVSFUC IS NULL) THEN
                '99'
              WHEN (BDMESFIMVSFUC < 10) THEN
                '0'||BDMESFIMVSFUC
              ELSE
                CAST(BDMESFIMVSFUC AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAFIMVSFUC = 0) OR (BDDIAFIMVSFUC IS NULL) THEN
                '99'
              WHEN (BDDIAFIMVSFUC < 10) THEN
                '0'||BDDIAFIMVSFUC
              ELSE
                CAST(BDDIAFIMVSFUC AS VARCHAR(2))
         END, -- Data final
         BDDIAINIVSFUC,
         BDMESINIVSFUC,
         BDANOINIVSFUC,
         BDDIAFIMVSFUC,
         BDMESFIMVSFUC,
         BDANOFIMVSFUC,
         BDFORMULAREFFUC,
         BDFORMULAREFAUXFUC,
         BDFORMULAVALFUC
FROM VRHF_FUNCOES_TVSFUC
;

/* CREATE OR ALTER VIEW: VW_VERBAS_NAO_FUNCOES_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBAS_NAO_FUNCOES_ATUAL(
BDCODPLAFUC,
BDCODTFUC,
BDCODVER,
BDDATAINI,
BDDATAFIM,
BDDIAINI,
BDMESINI,
BDANOINI,
BDDIAFIM,
BDMESFIM,
BDANOFIM,
BDDESCCOND,
BDFERIASVN,
BD13VN)
 AS 
SELECT BDCODPLAFUC,
       BDCODTFUC,
       BDCODVER,
       CASE WHEN ((BDANOINIVNFUC = 0) OR (BDANOINIVNFUC IS NULL)) AND (BDMESINIVNFUC > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOINIVNFUC = 0) OR (BDANOINIVNFUC IS NULL) THEN
                '0000'
              WHEN (BDANOINIVNFUC > 0) THEN
                CAST(BDANOINIVNFUC AS VARCHAR(4))
         END||
         CASE WHEN (BDMESINIVNFUC = 0) OR (BDMESINIVNFUC IS NULL) THEN
                '00'
              WHEN (BDMESINIVNFUC < 10) THEN
                '0'||BDMESINIVNFUC
              ELSE
                CAST(BDMESINIVNFUC AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAINIVNFUC = 0) OR (BDDIAINIVNFUC IS NULL) THEN
                '00'
              WHEN (BDDIAINIVNFUC < 10) THEN
                '0'||BDDIAINIVNFUC
              ELSE
                CAST(BDDIAINIVNFUC AS VARCHAR(2))
         END, -- Data inicial

         CASE WHEN ((BDANOFIMVNFUC = 0) OR (BDANOFIMVNFUC IS NULL)) AND (BDMESFIMVNFUC > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOFIMVNFUC = 0) OR (BDANOFIMVNFUC IS NULL) THEN
                '9999'
              WHEN (BDANOFIMVNFUC > 0) THEN
                CAST(BDANOFIMVNFUC AS VARCHAR(4))
         END||
         CASE WHEN (BDMESFIMVNFUC = 0) OR (BDMESFIMVNFUC IS NULL) THEN
                '99'
              WHEN (BDMESFIMVNFUC < 10) THEN
                '0'||BDMESFIMVNFUC
              ELSE
                CAST(BDMESFIMVNFUC AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAFIMVNFUC = 0) OR (BDDIAFIMVNFUC IS NULL) THEN
                '99'
              WHEN (BDDIAFIMVNFUC < 10) THEN
                '0'||BDDIAFIMVNFUC
              ELSE
                CAST(BDDIAFIMVNFUC AS VARCHAR(2))
         END, -- Data final
         BDDIAINIVNFUC,
         BDMESINIVNFUC,
         BDANOINIVNFUC,
         BDDIAFIMVNFUC,
         BDMESFIMVNFUC,
         BDANOFIMVNFUC,
         BDDESCCONDFUC,
         BDFERIASVNFUC,
         BD13VNFUC
FROM VRHF_FUNCOES_TVNFUC
;

/* CREATE OR ALTER VIEW: VW_UNION_VERBAS_SIM_NAO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_UNION_VERBAS_SIM_NAO(
BDCODEMP,
BDCODCOL,
BDCODSINTRAB,
BDCODPLAFUC,
BDCODFUNCAO,
BDCODVER,
BDDATAINI,
BDDATAFIM,
BDDIAINI,
BDMESINI,
BDANOINI,
BDDIAFIM,
BDMESFIM,
BDANOFIM,
BDFORMULAREF,
BDFORMULAREFAUX,
BDFORMULAVAL,
BDDESCCOND,
BDLOCAL,
BDSIMNAO)
 AS 
SELECT
    BDCODEMP,
    BDCODCOL,
    0 BDCODSINTRAB,
    NULL BDCODPLAFUC,
    NULL BDCODFUNCAO,
    BDCODVER,
    BDDATAINI,
    BDDATAFIM,
    BDDIAINI,
    BDMESINI,
    BDANOINI,
    BDDIAFIM,
    BDMESFIM,
    BDANOFIM,
    BDFORMULAREF,
    BDFORMULAREFAUX,
    BDFORMULAVAL,
    NULL BDDESCCOND,
    'FUNC' BDLOCAL,
    0 BDSIMNAO
FROM VW_VERBAS_SIM_COL_ATUAL
UNION
SELECT
    BDCODEMP,
    BDCODCOL,
    0 BDCODSINTRAB,
    NULL BDCODPLAFUC,
    NULL BDCODFUNCAO,
    BDCODVER,
    BDDATAINI,
    BDDATAFIM,
    BDDIAINI,
    BDMESINI,
    BDANOINI,
    BDDIAFIM,
    BDMESFIM,
    BDANOFIM,
    NULL BDFORMULAREF,
    NULL BDFORMULAREFAUX,
    NULL BDFORMULAVAL,
    BDDESCCOND,
    'FUNC' BDLOCAL,
    1 BDSIMNAO
FROM VW_VERBAS_NAO_COL_ATUAL
UNION
SELECT
    BDCODEMP,
    NULL BDCODCOL,
    0 BDCODSINTRAB,
    NULL BDCODPLAFUC,
    NULL BDCODFUNCAO,
    BDCODVER,
    BDDATAINI,
    BDDATAFIM,
    BDDIAINI,
    BDMESINI,
    BDANOINI,
    BDDIAFIM,
    BDMESFIM,
    BDANOFIM,
    BDFORMULAREF,
    BDFORMULAREFAUX,
    BDFORMULAVAL,
    NULL BDDESCCOND,
    'EMP' BDLOCAL,
    0 BDSIMNAO
FROM VW_VERBAS_SIM_EMP_ATUAL
UNION
SELECT
    BDCODEMP,
    NULL BDCODCOL,
    0 BDCODSINTRAB,
    NULL BDCODPLAFUC,
    NULL BDCODFUNCAO,
    BDCODVER,
    BDDATAINI,
    BDDATAFIM,
    BDDIAINI,
    BDMESINI,
    BDANOINI,
    BDDIAFIM,
    BDMESFIM,
    BDANOFIM,
    NULL BDFORMULAREF,
    NULL BDFORMULAREFAUX,
    NULL BDFORMULAVAL,
    BDDESCCOND,
    'EMP' BDLOCAL,
    1 BDSIMNAO
FROM VW_VERBAS_NAO_EMP_ATUAL
UNION
SELECT
    NULL BDCODEMP,
    NULL BDCODCOL,
    BDCODSINTRAB,
    NULL BDCODPLAFUC,
    NULL BDCODFUNCAO,
    BDCODVER,
    BDDATAINI,
    BDDATAFIM,
    BDDIAINI,
    BDMESINI,
    BDANOINI,
    BDDIAFIM,
    BDMESFIM,
    BDANOFIM,
    BDFORMULAREF,
    BDFORMULAREFAUX,
    BDFORMULAVAL,
    NULL BDDESCCOND,
    'SIND' BDLOCAL,
    0 BDSIMNAO
FROM VW_VERBAS_SIM_SIND_ATUAL
UNION
SELECT
    NULL BDCODEMP,
    NULL BDCODCOL,
    BDCODSINTRAB,
    NULL BDCODPLAFUC,
    NULL BDCODFUNCAO,
    BDCODVER,
    BDDATAINI,
    BDDATAFIM,
    BDDIAINI,
    BDMESINI,
    BDANOINI,
    BDDIAFIM,
    BDMESFIM,
    BDANOFIM,
    NULL BDFORMULAREF,
    NULL BDFORMULAREFAUX,
    NULL BDFORMULAVAL,
    BDDESCCOND,
    'SIND' BDLOCAL,
    1 BDSIMNAO
FROM VW_VERBAS_NAO_SIND_ATUAL
UNION
SELECT
    NULL BDCODEMP,
    NULL BDCODCOL,
    0 BDCODSINTRAB,
    BDCODPLAFUC,
    BDCODTFUC,
    BDCODVER,
    BDDATAINI,
    BDDATAFIM,
    BDDIAINI,
    BDMESINI,
    BDANOINI,
    BDDIAFIM,
    BDMESFIM,
    BDANOFIM,
    BDFORMULAREF,
    BDFORMULAREFAUX,
    BDFORMULAVAL,
    NULL BDDESCCOND,
    'FUNCAO' BDLOCAL,
    0 BDSIMNAO
FROM VW_VERBAS_SIM_FUNCOES_ATUAL
UNION
SELECT
    NULL BDCODEMP,
    NULL BDCODCOL,
    0 BDCODSINTRAB,
    BDCODPLAFUC,
    BDCODTFUC,
    BDCODVER,
    BDDATAINI,
    BDDATAFIM,
    BDDIAINI,
    BDMESINI,
    BDANOINI,
    BDDIAFIM,
    BDMESFIM,
    BDANOFIM,
    NULL BDFORMULAREF,
    NULL BDFORMULAREFAUX,
    NULL BDFORMULAVAL,
    BDDESCCOND,
    'FUNCAO' BDLOCAL,
    1 BDSIMNAO
FROM VW_VERBAS_NAO_FUNCOES_ATUAL
;

/* CREATE OR ALTER VIEW: VW_USUARIO_EMPRESA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_USUARIO_EMPRESA(
    BDCODEMP,
    BDCODUSU)
AS
SELECT DISTINCT bdcodemp, bdcodusu FROM (
SELECT bdcodemp, bdcodusu, NULL AS bdcodgrupo FROM tempresa_usuario
WHERE bdcodusu = (SELECT x.bdcodusu FROM SP_GET_USUARIO x)
UNION
SELECT temp.bdcodemp, tgrp.bdcodusu, tgrp.bdcodgrupo FROM TEMPRESA_GRUPOUSUARIO temp
INNER JOIN TGRUPOUSUARIO_USUARIO tgrp ON (tgrp.bdcodgrupo = temp.bdcodgrupo)
WHERE tgrp.bdcodusu = (SELECT x.bdcodusu FROM SP_GET_USUARIO x)
and not exists(select first 1 bdcodusu from tempresa_usuario WHERE bdcodusu = (SELECT x.bdcodusu FROM SP_GET_USUARIO x))
union
select emp.bdcodemp, usu.bdcodusu, usu.bdcodgrupo from tempresas emp
inner join tgrupousuario grp on (grp.bdcodesc = emp.bdcodesc)
inner join tgrupousuario_usuario usu on (usu.bdcodgrupo = grp.bdcodgrupo and usu.bdcodusu = (SELECT x.bdcodusu FROM SP_GET_USUARIO x))
where (not exists(select first 1 bdcodemp from tempresa_usuario WHERE bdcodusu = (SELECT x.bdcodusu FROM SP_GET_USUARIO x)))
and (not exists(select first 1 bdcodemp from tempresa_grupousuario grp
                inner join tgrupousuario_usuario usu on (usu.bdcodgrupo = grp.bdcodgrupo)
                WHERE usu.bdcodusu = (SELECT x.bdcodusu FROM SP_GET_USUARIO x)))
and((emp.bdexcluiremp is null)or(upper(emp.bdexcluiremp)<>'TRUE'))
union
select emp.bdcodemp, usu.bdcodusu, null from tempresas emp
left outer join tusuario usu on (usu.bdcodusu = (SELECT x.bdcodusu FROM SP_GET_USUARIO x))
where (not exists(select first 1 bdcodemp from tempresa_usuario WHERE bdcodusu = (SELECT x.bdcodusu FROM SP_GET_USUARIO x)))
and (not exists(select first 1 bdcodemp from tempresa_grupousuario grp
                inner join tgrupousuario_usuario usu on (usu.bdcodgrupo = grp.bdcodgrupo)
                WHERE usu.bdcodusu = (SELECT x.bdcodusu FROM SP_GET_USUARIO x)))
and (not exists(select emp.bdcodemp, usu.bdcodusu, usu.bdcodgrupo from tempresas emp
                inner join tgrupousuario grp on (grp.bdcodesc = emp.bdcodesc)
                inner join tgrupousuario_usuario usu on (usu.bdcodgrupo = grp.bdcodgrupo and usu.bdcodusu = (SELECT x.bdcodusu FROM SP_GET_USUARIO x))))
and((emp.bdexcluiremp is null)or(upper(emp.bdexcluiremp)<>'TRUE'))
union
select bdcodemp, (SELECT bdcodusu FROM SP_GET_USUARIO) as bdcodusu, null as bdcodgrupo from tempresas y
where (exists (select bdcodgrupo from tgrupousuario_usuario where bdcodgrupo = 1 and bdcodusu = (SELECT x.bdcodusu FROM SP_GET_USUARIO x)))
and((y.bdexcluiremp is null)or(upper(y.bdexcluiremp)<>'TRUE')));

/* CREATE OR ALTER VIEW: VW_VALOR_MES_DESPESAS_MEDICAS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VALOR_MES_DESPESAS_MEDICAS(
BDCODEMP,
BDCODCOL,
BDREFDME,
BDVALDME,
BDCLAVER)
 AS 
SELECT
  FN.BDCODEMP,
  FN.BDCODCOL,
  FN.BDREFFN,
  FN.BDVALVFN,
  VER.BDCLAVER
FROM vrhf_emp_tverbafn FN,
     VRH_BASE_TVERBAS VER
WHERE FN.BDCODVER = VER.BDCODVER AND
      VER.BDCLAVER LIKE '0.030.1.0%'
UNION
SELECT
  FC.BDCODEMP,
  FC.BDCODCOL,
  FC.BDREFCOMP,
  FC.BDVALVFC,
  VER2.BDCLAVER
FROM vrhf_emp_tverbafc FC,
     VRH_BASE_TVERBAS VER2
WHERE FC.BDCODVER = VER2.BDCODVER AND
      VER2.BDCLAVER LIKE '0.030.1.0%'
UNION
SELECT
  S13.BDCODEMP,
  S13.BDCODCOL,
  S13.BDREF13,
  S13.BDVALV13,
  VER3.BDCLAVER
FROM vrhf_emp_tverba13 S13,
     VRH_BASE_TVERBAS VER3
WHERE S13.BDCODVER = VER3.BDCODVER AND
      VER3.BDCLAVER LIKE '0.030.1.0%'
UNION
SELECT
  C13.BDCODEMP,
  C13.BDCODCOL,
  C13.BDREFC13,
  C13.BDVALVC13,
  VER4.BDCLAVER
FROM vrhf_emp_tverbac13 C13,
     VRH_BASE_TVERBAS VER4
WHERE C13.BDCODVER = VER4.BDCODVER AND
      VER4.BDCLAVER LIKE '0.030.1.0%'
;

/* CREATE OR ALTER VIEW: VW_VALOR_MES_DIARIAS_ACUSTOS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VALOR_MES_DIARIAS_ACUSTOS(
BDCODEMP,
BDCODCOL,
BDREFDIR,
BDVALDIR,
BDCLAVER)
 AS 
SELECT
  FN.BDCODEMP,
  FN.BDCODCOL,
  FN.BDREFFN,
  FN.BDVALVFN,
  VER.BDCLAVER
FROM vrhf_emp_tverbafn FN,
     VRH_BASE_TVERBAS VER
WHERE FN.BDCODVER = VER.BDCODVER AND
      VER.BDCLAVER LIKE '0.040.0%'
UNION
SELECT
  FC.BDCODEMP,
  FC.BDCODCOL,
  FC.BDREFCOMP,
  FC.BDVALVFC,
  VER2.BDCLAVER
FROM vrhf_emp_tverbafc FC,
     VRH_BASE_TVERBAS VER2
WHERE FC.BDCODVER = VER2.BDCODVER AND
      VER2.BDCLAVER LIKE '0.040.0%'
UNION
SELECT
  S13.BDCODEMP,
  S13.BDCODCOL,
  S13.BDREF13,
  S13.BDVALV13,
  VER3.BDCLAVER
FROM vrhf_emp_tverba13 S13,
     VRH_BASE_TVERBAS VER3
WHERE S13.BDCODVER = VER3.BDCODVER AND
      VER3.BDCLAVER LIKE '0.040.0%'
UNION
SELECT
  C13.BDCODEMP,
  C13.BDCODCOL,
  C13.BDREFC13,
  C13.BDVALVC13,
  VER4.BDCLAVER
FROM vrhf_emp_tverbac13 C13,
     VRH_BASE_TVERBAS VER4
WHERE C13.BDCODVER = VER4.BDCODVER AND
      VER4.BDCLAVER LIKE '0.040.0%'
;

/* CREATE OR ALTER VIEW: VW_VALOR_MES_INDENIZACAO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VALOR_MES_INDENIZACAO(
BDCODEMP,
BDCODCOL,
BDREFIND,
BDVALIND,
BDCLAVER)
 AS 
SELECT
  FN.BDCODEMP,
  FN.BDCODCOL,
  FN.BDREFFN,
  FN.BDVALVFN,
  VER.BDCLAVER
FROM vrhf_emp_tverbafn FN,
     VRH_BASE_TVERBAS VER
WHERE FN.BDCODVER = VER.BDCODVER AND
      VER.BDCLAVER LIKE '7.001.2.1%'
UNION
SELECT
  FC.BDCODEMP,
  FC.BDCODCOL,
  FC.BDREFCOMP,
  FC.BDVALVFC,
  VER2.BDCLAVER
FROM vrhf_emp_tverbafc FC,
     VRH_BASE_TVERBAS VER2
WHERE FC.BDCODVER = VER2.BDCODVER AND
      VER2.BDCLAVER LIKE '7.001.2.1%'
;

/* CREATE OR ALTER VIEW: VW_VALOR_MES_PENSAO_ALIMENTICIA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VALOR_MES_PENSAO_ALIMENTICIA(
BDCODEMP,
BDCODCOL,
BDREFPEN,
BDVALPEN,
BDCLAVER)
 AS 
SELECT
  FN.BDCODEMP,
  FN.BDCODCOL,
  FN.BDREFFN,
  FN.BDVALVFN,
  VER.BDCLAVER
FROM vrhf_emp_tverbafn FN,
     VRH_BASE_TVERBAS VER
WHERE FN.BDCODVER = VER.BDCODVER AND
      VER.BDCLAVER LIKE '0.030.0.1%'
UNION
SELECT
  FC.BDCODEMP,
  FC.BDCODCOL,
  FC.BDREFCOMP,
  FC.BDVALVFC,
  VER2.BDCLAVER
FROM vrhf_emp_tverbafc FC,
     VRH_BASE_TVERBAS VER2
WHERE FC.BDCODVER = VER2.BDCODVER AND
      VER2.BDCLAVER LIKE '0.030.0.1%'
UNION
SELECT
  S13.BDCODEMP,
  S13.BDCODCOL,
  S13.BDREF13,
  S13.BDVALV13,
  VER3.BDCLAVER
FROM vrhf_emp_tverba13 S13,
     VRH_BASE_TVERBAS VER3
WHERE S13.BDCODVER = VER3.BDCODVER AND
      VER3.BDCLAVER LIKE '0.030.0.1%'
UNION
SELECT
  C13.BDCODEMP,
  C13.BDCODCOL,
  C13.BDREFC13,
  C13.BDVALVC13,
  VER4.BDCLAVER
FROM vrhf_emp_tverbac13 C13,
     VRH_BASE_TVERBAS VER4
WHERE C13.BDCODVER = VER4.BDCODVER AND
      VER4.BDCLAVER LIKE '0.030.0.1%'
;

/* CREATE OR ALTER VIEW: VW_VALOR_MES_RENDIMENTO_ISENTO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VALOR_MES_RENDIMENTO_ISENTO(
BDCODEMP,
BDCODCOL,
BDCLAVER,
BDDESCVER,
BDDESCREDVER,
BDREFRIS,
BDVALRIS)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDCLAVER,
  BDDESCVER,
  BDDESCREDVER,
  MAX(BDREFRIS),
  SUM(COALESCE(BDVALRIS, 0.0))
FROM VW_UNION_RENDIMENTO_ISENTO
GROUP BY BDCODEMP, BDCODCOL, BDCLAVER, BDDESCVER, BDDESCREDVER
;

/* CREATE OR ALTER VIEW: VW_VEF_BASE_LIVROICMSUF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_LIVROICMSUF(
BDCODLIVICMS,
BDCODLIVICMSUF,
BDREFERENCIA,
BDNUMCAMPO,
BDCODTIPO,
BDCODUF,
BDTITQUADRO,
BDTITLATERAL,
BDCAMPO)
 AS 
SELECT uf.BDCODLIVICMS,
       uf.BDCODLIVICMSUF,
       uf.BDREFERENCIA,
       uf.BDNUMCAMPO,
       uf.BDCODTIPO,
       uf.BDCODUF,
       l.BDTITQUADRO,
       l.BDTITLATERAL,
       l.BDCAMPO
FROM VEF_BASE_LIVROICMSUF uf
JOIN VEF_BASE_LIVROICMS l ON (uf.bdcodlivicms = l.bdcodlivicms)
WHERE CAST(uf.BDREFERENCIA AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
;

/* CREATE OR ALTER VIEW: VW_VEF_BASE_TCONFATIVA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_TCONFATIVA(
BDCODCONFATIVO,
BDDESCCONF,
BDNUMCAMPO,
BDNUMITEM,
BDDESCFORM,
BDFORMULA,
BDINATIVO)
 AS 
SELECT
  tconfativa.BDCODCONFATIVO,
  tconfativa.BDDESCCONF,
  tconfativaform.BDNUMCAMPO,
  tconfativaform.BDNUMITEM,
  tconfativaform.BDDESCFORM,
  tconfativaform.BDFORMULA,
  tconfativaform.BDINATIVO
FROM vef_base_tconfativa tconfativa
LEFT OUTER JOIN vef_base_tconfativaform tconfativaform ON (tconfativaform.bdcodconfativo = tconfativa.bdcodconfativo)
;

/* CREATE OR ALTER VIEW: VW_VEF_BASE_TTABSIMPLESN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_TTABSIMPLESN(
BDCODCONFSIMPNAC,
BDCODATIVSIMPNAC,
BDREFSIMPNAC,
BDDE,
BDATE,
BDIRPJ,
BDCSLL,
BDCOFINS,
BDPIS_PASEP,
BDCPP,
BDICMS,
BDIPI,
BDISS,
BDALIQGERAL)
 AS 
SELECT sn.BDCODCONFSIMPNAC,sn.BDCODATIVSIMPNAC,sn.BDREFSIMPNAC,AC.BDDE,AC.BDATE,AC.BDIRPJ,AC.BDCSLL,
       AC.BDCOFINS,AC.BDPIS_PASEP,AC.BDCPP,AC.BDICMS, 0 BDIPI, 0 BDISS, 0 BDALIQGERAL
FROM VEF_BASE_TCONF_SN sn, VEF_BASE_TTAB_SN_COMERCIO AC
WHERE (sn.BDCODCONFSIMPNAC = AC.BDCODCONFSIMPNAC)
AND (sn.bdrefsimpnac =(SELECT MAX(Y.bdrefsimpnac) FROM VEF_BASE_TCONF_SN Y WHERE y.bdcodativsimpnac = 1 AND Y.bdrefsimpnac <=
            (SELECT FIRST 1 MAX(a.bdrefsimpnac)
             FROM VEF_BASE_TCONF_SN a
             WHERE (a.bdcodativsimpnac = SN.bdcodativsimpnac) AND  CAST(a.bdrefsimpnac AS VARCHAR(6)) <=
                      (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
                       FROM rdb$database)
             GROUP BY a.bdrefsimpnac
             ORDER BY a.bdrefsimpnac DESC )))

UNION
SELECT sn.BDCODCONFSIMPNAC,sn.BDCODATIVSIMPNAC,sn.BDREFSIMPNAC,AI.BDDE,AI.BDATE,AI.BDIRPJ,AI.BDCSLL,
       AI.BDCOFINS,AI.BDPIS_PASEP,AI.BDCPP,AI.BDICMS, AI.BDIPI, 0 BDISS, 0 BDALIQGERAL
FROM VEF_BASE_TCONF_SN sn, vef_base_ttab_sn_industria AI
WHERE (sn.BDCODCONFSIMPNAC = AI.BDCODCONFSIMPNAC)
AND (sn.bdrefsimpnac =(SELECT MAX(Y.bdrefsimpnac) FROM VEF_BASE_TCONF_SN Y WHERE y.bdcodativsimpnac = 2 AND Y.bdrefsimpnac <=
            (SELECT FIRST 1 MAX(a.bdrefsimpnac)
             FROM VEF_BASE_TCONF_SN a
             WHERE (a.bdcodativsimpnac = SN.bdcodativsimpnac) AND  CAST(a.bdrefsimpnac AS VARCHAR(6)) <=
                      (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
                       FROM rdb$database)
             GROUP BY a.bdrefsimpnac
             ORDER BY a.bdrefsimpnac DESC )))


UNION
SELECT sn.BDCODCONFSIMPNAC,sn.BDCODATIVSIMPNAC,sn.BDREFSIMPNAC,AIII.BDDE,AIII.BDATE,AIII.BDIRPJ,AIII.BDCSLL,
       AIII.BDCOFINS,AIII.BDPIS_PASEP,AIII.BDCPP,AIII.BDICMS, 0 BDIPI, AIII.BDISS, 0 BDALIQGERAL
FROM VEF_BASE_TCONF_SN sn, VEF_BASE_TTAB_SN_SERVICO_III AIII
WHERE (sn.BDCODCONFSIMPNAC = AIII.BDCODCONFSIMPNAC)
AND (sn.bdrefsimpnac =(SELECT MAX(Y.bdrefsimpnac) FROM VEF_BASE_TCONF_SN Y WHERE y.bdcodativsimpnac = 3 AND Y.bdrefsimpnac <=
            (SELECT FIRST 1 MAX(a.bdrefsimpnac)
             FROM VEF_BASE_TCONF_SN a
             WHERE (a.bdcodativsimpnac = SN.bdcodativsimpnac) AND  CAST(a.bdrefsimpnac AS VARCHAR(6)) <=
                      (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
                       FROM rdb$database)
             GROUP BY a.bdrefsimpnac
             ORDER BY a.bdrefsimpnac DESC )))


UNION
SELECT sn.BDCODCONFSIMPNAC,sn.BDCODATIVSIMPNAC,sn.BDREFSIMPNAC,AIV.BDDE,AIV.BDATE,AIV.BDIRPJ,AIV.BDCSLL,
       AIV.BDCOFINS,AIV.BDPIS_PASEP,0 BDCPP, 0 BDICMS, 0 BDIPI, aiv.bdiss, 0 BDALIQGERAL
FROM VEF_BASE_TCONF_SN sn, VEF_BASE_TTAB_SN_SERVICO_IV AIV
WHERE (sn.BDCODCONFSIMPNAC = AIV.BDCODCONFSIMPNAC)
AND (sn.bdrefsimpnac =(SELECT MAX(Y.bdrefsimpnac) FROM VEF_BASE_TCONF_SN Y WHERE y.bdcodativsimpnac = 4 AND Y.bdrefsimpnac <=
            (SELECT FIRST 1 MAX(a.bdrefsimpnac)
             FROM VEF_BASE_TCONF_SN a
             WHERE (a.bdcodativsimpnac = SN.bdcodativsimpnac) AND  CAST(a.bdrefsimpnac AS VARCHAR(6)) <=
                      (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
                       FROM rdb$database)
             GROUP BY a.bdrefsimpnac
             ORDER BY a.bdrefsimpnac DESC )))
UNION ALL
SELECT SN.BDCODCONFSIMPNAC,
       SN.BDCODATIVSIMPNAC,
       SN.BDREFSIMPNAC,
       AVI.BDDE,
       AVI.BDATE,
       0 BDIRPJ,
       0 BDCSLL,
       0 BDCOFINS,
       0 BDPIS_PASEP,
       0 BDCPP,
       0 BDICMS,
       0 BDIPI,
       AVI.BDISS,
       AVI.BDALIQGERAL
FROM VEF_BASE_TCONF_SN SN, VEF_BASE_TTAB_SN_SERVICO_VI AVI
WHERE (SN.BDCODCONFSIMPNAC = AVI.BDCODCONFSIMPNAC) AND
      (SN.BDREFSIMPNAC = (SELECT MAX(Y.BDREFSIMPNAC)
                          FROM VEF_BASE_TCONF_SN Y
                          WHERE Y.BDCODATIVSIMPNAC = 6 AND
                                Y.BDREFSIMPNAC <= (SELECT FIRST 1 MAX(A.BDREFSIMPNAC)
                                                   FROM VEF_BASE_TCONF_SN A
                                                   WHERE (A.BDCODATIVSIMPNAC = SN.BDCODATIVSIMPNAC) AND
                                                         CAST(A.BDREFSIMPNAC AS VARCHAR(6)) <= (SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES'))
                                                                                                FROM RDB$DATABASE)
                                                   GROUP BY A.BDREFSIMPNAC
                                                   ORDER BY A.BDREFSIMPNAC DESC)))                          
;

/* CREATE OR ALTER VIEW: VW_VEF_BASE_TvincuLOISS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_BASE_TVINCULOISS(
    BDCODCID,
    BDNOMCID,
    BDREFVINCISS,
    BDCODTIPOISS,
    BDDESTIPOISS,
    BDCODTIPOISSEXP,
    BDDESTIPOISSEXP,
    BDPERISS,
    BDVALORLIMISS,
    BDCODTIPORPS,
    BDDESTIPORPS,
    BDCODIBGE,
    BDDEDISS)
AS
SELECT
    VINC.BDCODCID,
    CID.BDNOMCID,
    VINC.BDREFVINCISS,
    VINC.BDCODTIPOISS,
    TIPOISS.BDDESTIPOISS,
    VINC.BDCODTIPOISSEXP,
    TIPOISSEXP.BDDESTIPOISS BDDESTIPOISSEXP,
    VINC.BDPERISS,
    VINC.BDVALORLIMISS,
    VINC.BDCODTIPORPS,
    TIPORPSEXP.bddestiporps,
    cid.bdCODIBGE,
    VINC.BDDEDISS
FROM vef_base_tvinculoiss VINC
LEFT OUTER JOIN tcidade cid ON (cid.bdcodcid = vinc.bdcodcid)
LEFT OUTER JOIN vef_base_ttipoiss tipoiss ON (tipoiss.bdcodtipoiss = vinc.bdcodtipoiss)
LEFT OUTER JOIN vef_base_ttipoiss tipoissexp ON (tipoissexp.bdcodtipoiss = vinc.bdcodtipoissexp)
LEFT OUTER JOIN vfin_base_ttiporpsexp tiporpsexp ON (tiporpsexp.bdcodtiporps = vinc.bdcodtiporps)

WHERE vinc.bdrefvinciss =
     (
      SELECT MAX(vincref.bdrefvinciss) FROM vef_base_tvinculoiss vincref
       WHERE vincref.bdcodcid = vinc.bdcodcid AND
             vincref.bdrefvinciss <=
                (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER)
                 FROM rdb$database)
     )
;


/* CREATE OR ALTER VIEW: VW_VEF_CONSULTA_LAN_ENTRADA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_CONSULTA_LAN_ENTRADA(
BDCODEMP,
BDCHAVE,
BDDATAENTRADAENT,
BDDATAEMISSAO,
BDCODTER,
BDNOMETER,
BDNUMDOCINI,
BDCONDPGTO,
BDMODELO,
BDMODELOSTR,
BDESPECIE,
BDSERIE,
BDSUBSERIE,
BDEMITENTE,
BDCODSITNF,
BDCHAVENFE,
BDDATACANC,
BDSIGLAUF,
BDREFLAN,
BDCODTIPO,
BDNOMETIPO,
BDCODUSU,
BDNOMEUSU,
BDDATALAN,
BDHORALAN,
BDVALORNOTA,
BDDESCONTO)
 AS 
SELECT  ENT.BDCODEMP,ENT.BDCHAVE, ENT.BDDATAENTRADAENT, ENT.BDDATAEMISSAO, ENT.BDCODTER,  TER.bdnome BDNOMETER, ENT.BDNUMDOCINI,ent.BDCONDPGTO,
        ENT.BDMODELO, modlan.bdmodelostr, ENT.BDESPECIE,  ENT.BDSERIE, ENT.BDSUBSERIE,  ENT.BDEMITENTE,  ENT.BDCODSITNF, ENT.BDCHAVENFE, ENT.BDDATACANC,u.bdsiglauf,ENT.BDREFLAN,
        ENT.BDCODTIPO, tplan.bddescricao BDNOMETIPO, ENT.BDCODUSU, usu.bdnomcomplusu BDNOMEUSU, ENT.BDDATALAN, ent.bdhoralan, SUM(COALESCE(BDVALORNOTA,0)), SUM(COALESCE(BDDESCONTONOTA,0))

FROM VEF_EMP_TMOVENT ENT
LEFT OUTER JOIN vw_tterceiro_simples TER ON (ENT.bdcodter = ter.bdcodter)
LEFT OUTER JOIN tcidade c ON (ter.bdcodcid = c.bdcodcid)
LEFT OUTER JOIN tuf u ON (c.bdcoduf = u.bdcoduf)
LEFT OUTER JOIN tusuario usu ON (ent.bdcodusu = usu.bdcodusu)
LEFT OUTER JOIN tipos_lancamentos_padrao tplan ON (ent.bdcodtipo = tplan.bdcodtipo)
LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN modlan ON (modlan.bdmodelo = ent.bdmodelo)
GROUP BY ENT.BDCODEMP, ENT.BDCHAVE, ENT.BDDATAENTRADAENT, ENT.BDDATAEMISSAO, ENT.BDCODTER,  BDNOMETER, ENT.BDNUMDOCINI,ent.BDCONDPGTO,
ENT.BDMODELO, MODLAN.bdmodelostr, ENT.BDESPECIE,  ENT.BDSERIE, ENT.BDSUBSERIE,  ENT.BDEMITENTE,  ENT.BDCODSITNF, ENT.BDCHAVENFE, ENT.BDDATACANC,u.bdsiglauf,ENT.BDREFLAN,
ENT.BDCODTIPO, BDNOMETIPO, ENT.BDCODUSU, BDNOMEUSU, ENT.BDDATALAN, ent.bdhoralan, ENT.BDVALORNOTA
ORDER BY ENT.BDCODEMP,ENT.BDCHAVE DESC
;

/* CREATE OR ALTER VIEW: VW_VEF_CONSULTA_LAN_SAIDA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_CONSULTA_LAN_SAIDA(
BDCODEMP,
BDCHAVE,
BDDATASAIDA,
BDDATAEMISSAO,
BDCODTER,
BDNOMETER,
BDNUMDOCINI,
BDNUMDOCFIM,
BDCONDPGTO,
BDMODELO,
BDMODELOSTR,
BDESPECIE,
BDSERIE,
BDSUBSERIE,
BDEMITENTE,
BDCODSITNF,
BDSIGLAUF,
BDCODTIPO,
BDNOMETIPO,
BDCODUSU,
BDNOMEUSU,
BDDATALAN,
BDVALORNOTA,
BDDESCONTO,
BDREFLAN,
BDCHAVENFE,
BDHORALAN,
BDDATACANC)
 AS 
SELECT  SAI.BDCODEMP,
        SAI.BDCHAVE,
        SAI.bddatasaida,
        SAI.BDDATAEMISSAO,
        SAI.BDCODTER,
        TER.bdnome BDNOMETER, 
        SAI.BDNUMDOCINI,
        SAI.BDNUMDOCFIM,
        SAI.BDCONDPGTO,
        SAI.BDMODELO,
        MODLAN.BDMODELOSTR,
        SAI.BDESPECIE,
        SAI.BDSERIE,
        SAI.BDSUBSERIE,
        SAI.bdemitente,
        SAI.BDCODSITNF,
        U.BDSIGLAUF,
        sai.BDCODTIPO, tplan.bddescricao BDNOMETIPO, sai.BDCODUSU, usu.bdnomcomplusu BDNOMEUSU, sai.BDDATALAN,
        SAI.BDVALORNOTA,
        SAI.bddescontonota,
        SAI.BDREFLAN,
        SAI.BDCHAVENFE,
        sai.bdhoralan,
        sai.bddatacanc
FROM VEF_EMP_TMOVSAI SAI
LEFT OUTER JOIN vw_tterceiro_simples TER ON (sai.bdcodter = ter.bdcodter)
LEFT OUTER JOIN tcidade c ON (ter.bdcodcid = c.bdcodcid)
LEFT OUTER JOIN tuf u ON (c.bdcoduf = u.bdcoduf)
LEFT OUTER JOIN tusuario usu ON (sai.bdcodusu = usu.bdcodusu)
LEFT OUTER JOIN tipos_lancamentos_padrao tplan ON (sai.bdcodtipo = tplan.bdcodtipo)
LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN modlan ON (modlan.bdmodelo = sai.bdmodelo)
GROUP BY SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDDATASAIDA, SAI.BDDATAEMISSAO, SAI.BDCODTER,  BDNOMETER,  SAI.BDNUMDOCINI,SAI.BDNUMDOCFIM,SAI.BDCONDPGTO,
SAI.BDMODELO, MODLAN.BDMODELOSTR, SAI.BDESPECIE,  SAI.BDSERIE, SAI.BDSUBSERIE,  SAI.bdemitente,  SAI.BDCODSITNF, U.BDSIGLAUF,
sai.BDCODTIPO, BDNOMETIPO, sai.BDCODUSU, BDNOMEUSU, sai.BDDATALAN, SAI.BDVALORNOTA, SAI.bddescontonota, SAI.BDREFLAN, SAI.BDCHAVENFE, sai.bdhoralan,sai.bddatacanc
ORDER BY SAI.BDCODEMP,SAI.BDCHAVE DESC
;

/* CREATE OR ALTER VIEW: VW_VEF_CONSULTA_LAN_SERVICO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_CONSULTA_LAN_SERVICO(
BDCODEMP,
BDCHAVE,
BDTIPLAN,
BDDATAEMISSAO,
BDCODTER,
BDNOME,
BDNUMDOCINI,
BDNUMDOCFIM,
BDCONDPGTO,
BDESPECIE,
BDSERIE,
BDSUBSERIE,
BDCODSITNF,
BDSIGLAUF,
BDCODTIPO,
BDNOMETIPO,
BDCODUSU,
BDNOMEUSU,
BDDATALAN,
BDCODCID,
BDVALORNOTA,
BDDESCONTO,
BDNOMCID,
BDREFLAN,
BDHORALAN)
 AS 
SELECT  SER.BDCODEMP, SER.BDCHAVE, SER.BDTIPLAN, SER.BDDATAEMISSAO,
        SER.BDCODTER, TER.bdnome,  SER.BDNUMDOCINI, SER.BDNUMDOCFIM,SER.BDCONDPGTO,
        SER.BDESPECIE,  SER.BDSERIE, SER.BDSUBSERIE,  SER.BDCODSITNF,u.bdsiglauf,
        ser.BDCODTIPO, tplan.bddescricao BDNOMETIPO, ser.BDCODUSU, usu.bdnomcomplusu BDNOMEUSU, ser.BDDATALAN, SER.bdcodcid,--SERITENS.bdcodrec, SERITENS.bdvlrirser,
        SER.BDVALORNOTA,SER.BDDESCONTONOTA, c.BDNOMCID, SER.BDREFLAN, ser.bdhoralan
FROM VEF_EMP_TMOVSER SER
LEFT OUTER JOIN vw_tterceiro_simples TER ON (ser.bdcodter = ter.bdcodter)
LEFT OUTER JOIN tcidade c ON (ser.bdcodcid = c.bdcodcid)
LEFT OUTER JOIN tuf u ON (c.bdcoduf = u.bdcoduf)
LEFT OUTER JOIN tusuario usu ON (ser.bdcodusu = usu.bdcodusu)
LEFT OUTER JOIN tipos_lancamentos_padrao tplan ON (ser.bdcodtipo = tplan.bdcodtipo)
GROUP BY SER.BDCODEMP, SER.BDCHAVE, SER.BDTIPLAN, SER.BDDATAEMISSAO,
         SER.BDCODTER, TER.bdnome,  SER.BDNUMDOCINI, SER.BDNUMDOCFIM,SER.BDCONDPGTO,
         SER.BDESPECIE,  SER.BDSERIE, SER.BDSUBSERIE,  SER.BDCODSITNF, u.bdsiglauf ,
         ser.BDCODTIPO, BDNOMETIPO, ser.BDCODUSU, BDNOMEUSU, ser.BDDATALAN, SER.bdcodcid ,-- SERITENS.BDCODREC,SERITENS.BDVLRIRSER,
         SER.BDVALORNOTA,SER.BDDESCONTONOTA, c.BDNOMCID,SER.BDREFLAN, bdhoralan
ORDER BY SER.BDCODEMP,SER.BDCHAVE DESC
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_SIMPLESNACIONAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_SIMPLESNACIONAL(
    BDTP,
    BDCODEMP,
    BDREFLAN,
    BDCODATIVSIMPNAC,
    BDCODBASESN,
    BDCODIMPOSTO,
    BDCODTIPOIMPOSTO,
    ENT,
    SAI,
    SER,
    CRED)
AS
SELECT BDTP, BDCODEMP, BDREFLAN, BDCODATIVSIMPNAC, BDCODBASESN, BDCODIMPOSTO, BDCODTIPOIMPOSTO, ENT, SAI, SER , CRED
FROM (

 SELECT ent.BDTP, ent.BDCODEMP, ent.BDREFLAN, ent.BDCODATIVSIMPNAC, ent.BDCODBASESN, ent.BDCODIMPOSTO,
             ent.BDCODTIPOIMPOSTO, SUM(ent.ENT) ENT, SUM(ent.SAI) sai, SUM(ent.SER) ser, SUM(ENT.CRED) CRED
      FROM (

              SELECT 0 BDTP, SN.BDCODEMP, MOV.BDREFLAN, SN.BDCODATIVSIMPNAC, SN.BDCODBASESN, SN.BDCODIMPOSTO,
                     SN.BDCODTIPOIMPOSTO, SUM(COALESCE(SN.BDVLRBASE, 0)) ENT, 0 SAI, 0 SER , 0 CRED
              FROM VEF_EMP_TMOVENTSN SN, VEF_EMP_TMOVENT MOV, VEF_EMP_TMOVENTITENS MOVI 
              LEFT OUTER JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = MOVI.BDCODNAT) 
              WHERE (SN.BDCODEMP = MOVI.BDCODEMP AND
                    SN.BDCHAVE = MOVI.BDCHAVE AND
                    SN.BDORDEM = MOVI.BDORDEM) AND
                    (SN.BDCODEMP = MOV.BDCODEMP AND
                    SN.BDCHAVE = MOV.BDCHAVE) AND
                    (MOV.bdcodsitnf NOT IN (2,3,4,5)) AND
                    (N.BDNAOLEVARSN <> 'TRUE') 
              GROUP BY BDTP, sn.BDCODEMP, MOV.BDREFLAN, sn.BDCODATIVSIMPNAC, sn.BDCODBASESN, sn.BDCODIMPOSTO,sn.BDCODTIPOIMPOSTO
        
              UNION ALL
        
              SELECT 0 BDTP, pla.BDCODEMP, pla.BDREFERENCIA BDREFLAN, pla.BDCODATIVSIMPNAC, pla.BDCODBASESN, pla.BDCODIMPOSTO,
                     pla.BDCODTIPOIMPOSTO,SUM(COALESCE(pla.bdvalorcred, 0)) ENT, 0 SAI, 0 SER,
                     SUM(COALESCE(pla.bdvalorcred, 0)) CRED
              FROM vef_emp_tplanilhasncred pla
              GROUP BY BDTP, pla.BDCODEMP, pla.BDREFERENCIA, pla.BDCODATIVSIMPNAC, pla.BDCODBASESN, pla.BDCODIMPOSTO,pla.BDCODTIPOIMPOSTO
            ) ent

    GROUP BY ent.BDTP, Ent.BDCODEMP, Ent.BDREFLAN, Ent.BDCODATIVSIMPNAC, Ent.BDCODBASESN, Ent.BDCODIMPOSTO,Ent.BDCODTIPOIMPOSTO


) E
WHERE ENT > 0 
UNION ALL
SELECT BDTP, BDCODEMP, BDREFLAN, BDCODATIVSIMPNAC, BDCODBASESN, BDCODIMPOSTO, BDCODTIPOIMPOSTO, ENT, SAI, SER , CRED
FROM (
      SELECT sai.BDTP, sai.BDCODEMP, sai.BDREFLAN, sai.BDCODATIVSIMPNAC, sai.BDCODBASESN, sai.BDCODIMPOSTO,
             sai.BDCODTIPOIMPOSTO, SUM(sai.ENT) ENT, SUM(sai.SAI) sai, SUM(sai.SER) ser, SUM(sai.CRED) CRED
      FROM (
            SELECT 1 BDTP, SN.BDCODEMP, MOV.BDREFLAN, SN.BDCODATIVSIMPNAC, SN.BDCODBASESN, SN.BDCODIMPOSTO,
                   SN.BDCODTIPOIMPOSTO, 0 ENT, SUM(COALESCE(SN.BDVLRBASE, 0)) SAI, 0 SER ,0 CRED
            FROM VEF_EMP_TMOVSAISN SN, VEF_EMP_TMOVSAI MOV, VEF_EMP_TMOVSAIITENS MOVI 
            LEFT OUTER JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = MOVI.BDCODNAT) 
            WHERE (SN.BDCODEMP = MOVI.BDCODEMP AND
                  SN.BDCHAVE = MOVI.BDCHAVE AND
                  SN.BDORDEM = MOVI.BDORDEM) AND
                  (SN.BDCODEMP = MOV.BDCODEMP AND
                  SN.BDCHAVE = MOV.BDCHAVE) AND
                  (MOV.bdcodsitnf NOT IN (2,3,4,5)) AND
                  (N.BDNAOLEVARSN <> 'TRUE') 
            GROUP BY BDTP, SN.BDCODEMP, MOV.BDREFLAN, SN.BDCODATIVSIMPNAC, SN.BDCODBASESN, SN.BDCODIMPOSTO, SN.BDCODTIPOIMPOSTO
      
            UNION ALL
            -- Subtrai os lançamentos de débito dos lançamentos de saída...
            SELECT 1 BDTP, pla.BDCODEMP, pla.BDREFERENCIA BDREFLAN, pla.BDCODATIVSIMPNAC, pla.BDCODBASESN, pla.BDCODIMPOSTO,
                   pla.BDCODTIPOIMPOSTO, 0 ENT, (SUM(COALESCE(pla.bdvalordeb, 0)) * -1) SAI, 0 SER, 0 CRED
            FROM VEF_EMP_TPLANILHASNDEB pla
            GROUP BY BDTP, pla.BDCODEMP, pla.BDREFERENCIA, pla.BDCODATIVSIMPNAC, pla.BDCODBASESN, pla.BDCODIMPOSTO,pla.BDCODTIPOIMPOSTO
            ) sai
      GROUP BY sai.BDTP, sai.BDCODEMP, sai.BDREFLAN, sai.BDCODATIVSIMPNAC, sai.BDCODBASESN, sai.BDCODIMPOSTO, sai.BDCODTIPOIMPOSTO
      ) S
WHERE SAI > 0 

UNION ALL
SELECT BDTP, BDCODEMP, BDREFLAN, BDCODATIVSIMPNAC, BDCODBASESN, BDCODIMPOSTO, BDCODTIPOIMPOSTO, ENT, SAI, SER , CRED
FROM (SELECT 1 BDTP, SN.BDCODEMP, MOV.BDREFLAN, SN.BDCODATIVSIMPNAC, SN.BDCODBASESN, SN.BDCODIMPOSTO, 
             SN.BDCODTIPOIMPOSTO, 0 ENT, 0 SAI, SUM(COALESCE(SN.BDVLRBASE, 0)) SER ,0 CRED
      FROM VEF_EMP_TMOVSERSN SN, VEF_EMP_TMOVSER MOV, VEF_EMP_TMOVSERITENS MOVI 
      LEFT OUTER JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = MOVI.BDCODNAT) 
      WHERE (SN.BDCODEMP = MOVI.BDCODEMP AND
            SN.BDCHAVE = MOVI.BDCHAVE AND
            SN.BDORDEM = MOVI.BDORDEM) AND
            (SN.BDCODEMP = MOV.BDCODEMP AND
            SN.BDCHAVE = MOV.BDCHAVE) AND
            (MOV.bdcodsitnf NOT IN (2,3,4,5)) AND
            (mov.bdtiplan = 0) AND
            ((SN.BDCODATVM IS NOT NULL AND
            SN.BDCODCID IS NOT NULL AND
            SN.BDCODCONFATVMSN IS NOT NULL) OR (SN.BDCODNAT IS NOT NULL AND
            SN.BDCODCONFSN IS NOT NULL AND
            UPPER(N.BDNAOLEVARSN) <> 'TRUE')) 
      GROUP BY BDTP, SN.BDCODEMP, MOV.BDREFLAN, SN.BDCODATIVSIMPNAC, SN.BDCODBASESN, SN.BDCODIMPOSTO, SN.BDCODTIPOIMPOSTO) R 
WHERE SER > 0 

UNION ALL
SELECT BDTP, BDCODEMP, BDREFLAN, BDCODATIVSIMPNAC, BDCODBASESN, BDCODIMPOSTO, BDCODTIPOIMPOSTO, ENT, SAI, SER ,CRED
FROM (SELECT 1 BDTP, SN.BDCODEMP, MOV.BDREFLAN, SN.BDCODATIVSIMPNAC, SN.BDCODBASESN, SN.BDCODIMPOSTO, 
             SN.BDCODTIPOIMPOSTO, 0 ENT, SUM(COALESCE(SN.BDVLRBASE, 0)) SAI, 0 SER ,0 CRED
      FROM VEF_EMP_TREDZSN SN, VEF_EMP_TREDZ MOV, VEF_EMP_TREDZVARCFOP MOVI 
      LEFT OUTER JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = MOVI.BDCODNAT) 
      WHERE (SN.BDCODEMP = MOVI.BDCODEMP AND
            SN.BDCHAVE = MOVI.BDCHAVE AND
            SN.BDORDEMVARCFOP = MOVI.BDORDEMVARCFOP) AND
            (SN.BDCODEMP = MOV.BDCODEMP AND
            SN.BDCHAVE = MOV.BDCHAVE) AND
            (N.BDNAOLEVARSN <> 'TRUE') 
      GROUP BY BDTP, SN.BDCODEMP, MOV.BDREFLAN, SN.BDCODATIVSIMPNAC, SN.BDCODBASESN, SN.BDCODIMPOSTO, SN.BDCODTIPOIMPOSTO) Z 
WHERE SAI > 0
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TDACONGERF1323 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TDACONGERF1323(
BDCODPERIODO,
BDCODEMP,
BDREFERENCIA,
BDCODQDACON,
BDNUMCAMPO,
BDVALOR,
BDTIPOCREDITO)
 AS 
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQDACON,
        BDNUMCAMPO,
        BDVALOR,
        BDTIPOCREDITO

FROM vef_emp_tdacongerf1323
ORDER BY bdcodemp, bdreferencia ,bdcodqdacon,bdtipocredito
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TDACONGERUNION (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TDACONGERUNION(
BDCODPERIODO,
BDCODEMP,
BDREFERENCIA,
BDCODQDACON,
BDNUMCAMPO,
BDCODREC,
BDVALOR,
BDVALOR2,
BDVALOR3,
BDCNPJ,
BDTIPOCREDITO)
 AS 
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQDACON,
        BDNUMCAMPO,
        NULL,
        BDVALOR,
        BDVALOR2,
        BDVALOR3,
        NULL,
        NULL
FROM VEF_EMP_TDACONGERREG
UNION
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQDACON,
        BDNUMCAMPO,
        BDCODREC,
        BDVALOR,
        NULL, 
        NULL,
        BDCNPJPART,
        NULL

FROM VEF_EMP_TDACONGERRECEITA
UNION
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQDACON,
        BDNUMCAMPO,
        NULL,
        BDVALOR,
        NULL, 
        NULL,
        NULL,
        BDTIPOCREDITO

FROM VW_vef_emp_tdacongerf1323
UNION
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQDACON,
        BDNUMCAMPO,
        NULL,
        BDVALOR,
        NULL, 
        NULL,
        NULL,
        bdcodtipocre AS BDTIPOCREDITO
FROM vef_emp_tdacongerregf1424
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TDIMEGERUNION (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TDIMEGERUNION(
BDCODPERIODO,
BDCODEMP,
BDREFERENCIA,
BDCODQDIME,
BDNUMCAMPO,
BDCODNAT,
BDVALOR,
BDCODCID,
BDCODCIDTOT,
BDCODUF,
BDDATAREC,
BDCLAVENDIMEGERQ12,
BDCODRECDIMEGERQ12,
BDORIGEMDIMEGERQ46,
BDIDENTIFICACAOREGESP,
BDQ12,
BDQ46,
BDCODEXP48,
BDALIMPREP)
 AS 
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQDIME,
        BDNUMCAMPO,
        BDPREFIXONAT,
        SUM(COALESCE(BDVALOR,0)),
        NULL, -- Q 47, Q48 BDCODCID
        NULL, -- Q 47, Q48 BDCODCIDTOT
        NULL, -- Q 49 BDCODUF
        NULL, -- Q12
        NULL, -- Q12
        NULL, -- Q12
        NULL, -- Q46
        NULL, -- Q46
        'FALSE', -- Q12
        'FALSE', -- Q46
        '', -- Q48
        '' -- Q48
FROM VEF_EMP_TDIMEGERNAT
GROUP BY BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQDIME, BDNUMCAMPO, BDPREFIXONAT
UNION
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQDIME,
        BDNUMCAMPO,
        NULL,
        BDVALOR,
        BDCODCID,
        BDCODCIDTOT,
        NULL, -- Q49
        NULL, -- Q12
        NULL, -- Q12
        NULL, -- Q12
        NULL, -- Q46
        NULL, -- Q46
        'FALSE', -- Q12
        'FALSE', -- Q46
        '', -- Q48
        '' -- Q48
FROM VEF_EMP_TDIMEGERQ47
UNION
SELECT  BDCODPERIODO,
        q48.BDCODEMP,
        BDREFERENCIA,
        BDCODQDIME,
        BDNUMCAMPO,
        NULL,
        BDVALOR,
        BDCODCID,
        BDCODCIDTOT,
        NULL, -- Q49
        NULL, -- Q12
        NULL, -- Q12
        NULL, -- Q12
        NULL, -- Q46
        NULL, -- Q46
        'FALSE', -- Q12
        'FALSE', -- Q46
        CASE WHEN bdcodcidtot = 99999 THEN 999 ELSE BDCODEXP END BDCODEXP,  -- Q48
        ALIM.BDALIMPREP -- Q48
FROM VEF_EMP_TDIMEGERQ48 q48
JOIN  VW_VEF_BASE_TEMPPARESTSC Alim ON (alim.bdcodemp = q48.bdcodemp)
LEFT OUTER JOIN VEF_BASE_TTABATIVQ48 exp48 ON (q48.bdcodativq48 = exp48.bdcodativq48)
WHERE q48.bdcodativq48 IS NOT NULL OR BDCODCIDTOT = 99999

UNION
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQDIME,
        BDNUMCAMPO,
        NULL,
        BDVALOR,
        NULL,
        NULL,
        bdcoduf, -- Q49
        NULL, -- Q12
        NULL, -- Q12
        NULL, -- Q12
        NULL, -- Q46
        NULL, -- Q46
        'FALSE', -- Q12
        'FALSE',  -- Q46
        '', -- Q48
        '' -- Q48
FROM VEF_EMP_TDIMEGERQ49
UNION
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQDIME,
        BDNUMCAMPO,
        NULL BDCODNAT,
        SUM(COALESCE(BDVALOR,0)) BDVALOR,
        NULL BDCODCID,
        NULL BDCODCIDTOT,
        bdcoduf, -- Q49
        NULL BDDATAREC, -- Q12
        NULL BDCLAVENDIMEGERQ12, -- Q12
        NULL BDCODRECDIMEGERQ12, -- Q12
        NULL BDORIGEMDIMEGERQ46, -- Q46
        NULL, -- Q46
        'FALSE' BDQ12, -- Q12
        'FALSE' BDQ46, -- Q46
        '', -- Q48
        '' -- Q48
FROM VEF_EMP_TDIMEGERQ50
GROUP BY BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQDIME, BDNUMCAMPO, BDCODNAT, BDCODCID, BDCODCIDTOT,bdcoduf, BDDATAREC, BDCLAVENDIMEGERQ12, BDCODRECDIMEGERQ12, 

BDORIGEMDIMEGERQ46,BDQ12, BDQ46
UNION
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQDIME,
        BDNUMCAMPO,
        NULL,
        BDVALOR,
        NULL,
        NULL,
        NULL, -- Q49
        NULL, -- Q12
        NULL, -- Q12
        NULL, -- Q12
        NULL, -- Q46
        NULL, -- Q46
        'FALSE', -- Q12
        'FALSE', -- Q46
        '', -- Q48
        '' -- Q48
FROM VEF_EMP_TDIMESCGERREG

UNION
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQDIME,
        BDNUMCAMPO,
        NULL,
        BDVALOR,
        NULL,
        NULL,
        NULL, -- Q49
        BDDATAREC, -- Q12
        BDCLAVENDIMEGERQ12, -- Q12
        BDCODRECDIMEGERQ12, -- Q12
        NULL, -- Q46
        NULL, -- Q46
        'TRUE', -- Q12
        'FALSE',  -- Q46
        '', -- Q48
        '' -- Q48
FROM VEF_EMP_TDIMEGERQ12
UNION

SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQDIME,
        BDNUMCAMPO,
        BDCODNAT,
        BDVALOR,
        BDCODCID,
        BDCODCIDTOT,
        BDCODUF,
        BDDATAREC, -- Q12
        BDCLAVENDIMEGERQ12, -- Q12
        BDCODRECDIMEGERQ12, -- Q12
        BDORIGEMDIMEGERQ46,
        BDIDENTIFICACAOREGESP,
        BDQ12, -- Q12
        BDQ46,  -- Q46
        '', -- Q48
        '' -- Q48
FROM VEF_SP_DIMEQ46
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TGIAESGERUNION (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TGIAESGERUNION(
BDCODPERIODO,
BDCODEMP,
BDREFERENCIA,
BDCODQUADRO,
BDNUMCAMPO,
BDPREFIXONAT,
BDVALOR,
BDTIPOAPU,
BDAUXCFOP,
BDORDEMTTNAT)
 AS 
SELECT  BDCODPERIODO,  BDCODEMP, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDPREFIXONAT, SUM(COALESCE(BDVALOR,0)) BDVALOR, BDTIPOAPU, BDAUXCFOP, NULL
FROM VEF_EMP_TGIAESGERNAT
GROUP BY BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDPREFIXONAT, BDTIPOAPU, BDAUXCFOP
UNION
SELECT   BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, NULL, BDVALOR, BDTIPOAPU, NULL, NULL
FROM VEF_EMP_TGIAESGERREG
UNION
SELECT bdcodperiodo, bdcodemp, bdreferencia, bdcodquadro, bdnumcampo , NULL, bdVAlor, NULL, NULL, BDORDEMTTNAT
FROM vef_emp_tgiaesttnat
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TGIAMGGERUNION (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TGIAMGGERUNION(
BDCODPERIODO,
BDCODEMP,
BDREFERENCIA,
BDCODQUADRO,
BDNUMCAMPO,
BDPREFIXONAT,
BDVALOR)
 AS 
SELECT  BDCODPERIODO,  BDCODEMP, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDPREFIXONAT, SUM(COALESCE(BDVALOR,0)) BDVALOR
FROM VEF_EMP_TGIAMGGERNAT
GROUP BY BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDPREFIXONAT
UNION
SELECT   BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, NULL, BDVALOR
FROM VEF_EMP_TGIAMGGERREG
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TGIAROGERUNION (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TGIAROGERUNION(
BDCODPERIODO,
BDCODEMP,
BDREFERENCIA,
BDCODQUADRO,
BDNUMCAMPO,
BDPREFIXONAT,
BDVALOR,
BDORDEMTTNAT)
 AS 
SELECT   BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDPREFIXONAT, SUM(COALESCE(BDVALOR,0)) BDVALOR, NULL
FROM VEF_EMP_TGIAROGERNAT
GROUP BY BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDPREFIXONAT
UNION
SELECT   BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, NULL, BDVALOR, NULL
FROM VEF_EMP_TGIAROGERREG
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TGIASPGERUNION (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TGIASPGERUNION(
BDCODPERIODO,
BDCODEMP,
BDREFERENCIA,
BDCODQUADRO,
BDNUMCAMPO,
BDPREFIXONAT,
BDVALOR)
 AS 
SELECT  BDCODPERIODO,  BDCODEMP, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDPREFIXONAT, SUM(COALESCE(BDVALOR,0)) BDVALOR
FROM VEF_EMP_TGIASPGERNAT
GROUP BY BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDPREFIXONAT
UNION
SELECT   BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, NULL, BDVALOR
FROM VEF_EMP_TGIASPGERREG
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TICMSSPEDGERUNION (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TICMSSPEDGERUNION(
    BDCODPERIODO,
    BDCODEMP,
    BDREFERENCIA,
    BDCODQICMSSPED,
    BDNUMCAMPO,
    BDVALOR,
    BDCODUF,
    BDCODSUBAPU,
    BDALIQICMS,
    BDMOTIVO,
    BDSEMANA)
AS
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQICMSSPED,
        BDNUMCAMPO,
        BDVALOR,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL
FROM VEF_EMP_TICMSSPEDGERREG
UNION
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQICMSSPED,
        BDNUMCAMPO,
        BDVALOR,
        BDCODUF,
        NULL,
        NULL,
        NULL,
        NULL
FROM VEF_EMP_TICMSSPEDSTUF
UNION ALL
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQICMSSPED,
        BDNUMCAMPO,
        BDVALOR,
        NULL, 
        BDCODSUBAPU,
        NULL,
        NULL,
        NULL
FROM VEF_EMP_TICMSSPED1920
UNION ALL
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQICMSSPED,
        BDNUMCAMPO,
        BDVALOR,
        NULL, 
        BDCODSUBAPU,
        NULL,
        NULL,
        NULL
FROM VEF_EMP_TICMSSPED1960
UNION ALL
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQICMSSPED,
        BDNUMCAMPO,
        BDVALOR,
        NULL, 
        BDCODSUBAPU,
        NULL,
        NULL,
        NULL
FROM VEF_EMP_TICMSSPED1970
UNION ALL
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQICMSSPED,
        BDNUMCAMPO,
        BDVALOR,
        NULL, 
        BDCODSUBAPU,
        BDALIQICMS,
        NULL,
        NULL
FROM VEF_EMP_TICMSSPED1975
UNION ALL
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQICMSSPED,
        BDNUMCAMPO,
        BDVALOR,
        NULL, 
        BDCODSUBAPU,
        NULL,
        NULL,
        NULL
FROM VEF_EMP_TICMSSPED1980
UNION ALL
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQICMSSPED,
        BDNUMCAMPO,
        BDVALOR,
        NULL, 
        NULL,
        NULL,
        NULL,
        NULL
FROM VEF_EMP_TICMSSPED1250
UNION ALL
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQICMSSPED,
        BDNUMCAMPO,
        BDVALOR,
        NULL, 
        NULL,
        NULL,
        BDCODMOTIVO,
        NULL
FROM VEF_EMP_TICMSSPED1255
UNION ALL
SELECT  BDCODPERIODO,
        BDCODEMP,
        BDREFERENCIA,
        BDCODQICMSSPED,
        BDNUMCAMPO,
        BDVALOR,
        NULL,
        NULL,
        NULL,
        NULL,
        BDSEMANA
FROM VEF_EMP_TICMSSPEDGERREG_SEMANAL;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TMOVENT (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TMOVENT(
BDCODEMP,
BDCHAVE,
BDCODTER,
BDNUMDOCINI,
BDDATAEMISSAO,
BDESPECIE,
BDSERIE,
BDSUBSERIE,
BDNUMDOCFIM,
BDMODELO,
BDEMITENTE,
BDDATAENTRADAENT,
BDCODSITNF,
BDORDEMINFCOM_D500,
BDCODCTA,
BDTIPOASSINANTE,
BDVLRSER,
BDVLRSERNTRIB,
BDVLRCOBTERC,
BDVLROUTDESP_D500,
BDVLRPIS_D500,
BDVLRCOFINS_D500,
BDCODTENSAO,
BDORDEMINFCOM_C500,
BDORDEMCONS,
BDVLRCONSFOR,
BDVLRCOBTER,
BDVLRDESPACE,
BDVLRPIS_C500,
BDVLRCOFINS_C500,
BDTIPOLIGACAO,
BDCHAVENFE,
BDINDFRETE,
BDVLRFRETE,
BDVLRSEGURO,
BDVLROUTDESP_C100,
BDVLRTOTPIS,
BDVLRTOTCOFINS,
BDVLRTOTPISST,
BDVLRTOTCOFINSST,
BDCODCTA_C300,
BDVLRTOTPIS_C300,
BDVLRTOTCOFINS_C300,
BDCODCONS,
BDCODINFCOM_C500,
BDCODINFCOM_D500,
BDCODCTA_D100,
BDORDEMINFCOM_D100,
BDCHAVECTE_D100,
BDTIPOCTE_D100,
BDCHAVECTEREF_D100,
BDINDFRETE_D100,
BDREFLAN,
BDCONDPGTO,
BDDESCONTONOTA)
 AS 
SELECT ENT.bdcodemp, ENT.bdchave, ENT.BDCODTER,ENT.BDNUMDOCINI,ENT.BDDATAEMISSAO,ENT.BDESPECIE,ENT.BDSERIE,ENT.BDSUBSERIE,
       ENT.BDNUMDOCFIM, ENT.BDMODELO, ENT.BDEMITENTE, ENT.BDDATAENTRADAENT,ENT.BDCODSITNF,

       ENTD500.BDORDEMINFCOM BDORDEMINFCOM_D500,ENTD500.BDCODCTA,ENTD500.BDTIPOASSINANTE,ENTD500.BDVLRSER,ENTD500.BDVLRSERNTRIB,
       ENTD500.BDVLRCOBTERC,ENTD500.BDVLROUTDESP BDVLROUTDESP_D500,ENTD500.BDVLRPIS BDVLRPIS_D500,ENTD500.BDVLRCOFINS BDVLRCOFINS_D500,

       ENTC500.BDCODTENSAO, ENTC500.BDORDEMINFCOM BDORDEMINFCOM_C500,ENTC500.BDORDEMCONS,ENTC500.BDVLRCONSFOR,ENTC500.BDVLRCOBTER,
       ENTC500.BDVLRDESPACE,ENTC500.BDVLRPIS BDVLRPIS_C500,ENTC500.BDVLRCOFINS BDVLRCOFINS_C500,ENTC500.BDTIPOLIGACAO, ENT.BDCHAVENFE,

       ENTC100.BDINDFRETE,ENTC100.BDVLRFRETE,ENTC100.BDVLRSEGURO,ENTC100.BDVLROUTDESP BDVLROUTDESP_C100,
       ENTC100.BDVLRTOTPIS,ENTC100.BDVLRTOTCOFINS,ENTC100.BDVLRTOTPISST,ENTC100.BDVLRTOTCOFINSST,

       C300C350.bdcodcta bdcodcta_C300, C300C350.bdvlrtotpis bdvlrtotpis_C300, C300C350.bdvlrtotcofins bdvlrtotcofins_C300,

       codcons.bdcodcons,

       infconc500.bdcodinfcom bdcodinfcom_c500,
       infcond500.bdcodinfcom bdcodinfcom_d500,
       --D100
       entD100.BDCODCTA BDCODCTA_D100 ,INFCOND100.bdcodinfcom BDORDEMINFCOM_D100 ,
       entD100.BDCHAVECTE BDCHAVECTE_D100 ,entD100.BDTIPOCTE BDTIPOCTE_D100 ,
       entD100.BDCHAVECTEREF BDCHAVECTEREF_D100 ,entD100.BDINDFRETE BDINDFRETE_D100
       ,
       ENT.bdreflan,ENT.bdcondpgto,ENT.BDDESCONTONOTA



FROM vef_emp_tmovent ENT
LEFT OUTER JOIN vef_emp_td100ent entD100 ON (ent.BDCODEMP = entD100.BDCODEMP AND ent.bdchave = entD100.bdchave)
LEFT OUTER JOIN vef_emp_td500ent ENTD500 ON (ENT.BDCODEMP = ENTD500.BDCODEMP AND ENT.bdchave = ENTD500.bdchave)
LEFT OUTER JOIN vef_emp_tC500ent ENTC500 ON (ENT.BDCODEMP = ENTC500.BDCODEMP AND ENT.bdchave = ENTC500.bdchave)
LEFT OUTER JOIN vef_emp_tc100ent ENTC100 ON (ENT.BDCODEMP = ENTC100.BDCODEMP AND ENT.bdchave = ENTC100.bdchave)
LEFT OUTER JOIN vef_emp_tc300350sai C300C350 ON (ENT.BDCODEMP = C300C350.BDCODEMP AND ENT.bdchave = C300C350.bdchave)

LEFT OUTER JOIN vef_base_ttabcodcons codcons ON (codcons.bdordemcons = entc500.bdordemcons)
LEFT OUTER JOIN vef_base_tcadinfcom infconc500 ON (infconc500.bdordeminfcom = entc500.bdordeminfcom)
LEFT OUTER JOIN vef_base_tcadinfcom infcond500 ON (infcond500.bdordeminfcom = entd500.bdordeminfcom)
LEFT OUTER JOIN vef_base_tcadinfcom infconD100 ON (infconD100.bdordeminfcom = ENTD100.bdordeminfcom)
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TMOVENT_E_ITENS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TMOVENT_E_ITENS(
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    BDDATAENTRADAENT,
    BDDATAEMISSAO,
    BDCODTER,
    BDNUMDOCINI,
    BDMODELO,
    BDESPECIE,
    BDSERIE,
    BDEMITENTE,
    BDCODSITNF,
    BDCONDPGTO,
    BDVLRPIS,
    BDVLRCOFINS,
    BDVLRCSOCIAL,
    BDVLRIR,
    BDVLRINSS,
    BDVLRISS,
    BDVLRCONTAB,
    BDBASEICMS,
    BDBASEIPI,
    BDBASEST,
    BDISENTASICMS,
    BDISENTASIPI,
    BDOUTRASICMS,
    BDOUTRASIPI,
    BDVLRICMS,
    BDVLRIPI,
    BDVLRST,
    BDIMPEXCLUIDAS,
    BDOUTROSIMP,
    BDDESCONTO,
    BDICMSRETENT,
    BDDIFALIQENT,
    BDCODRECPIS,
    BDCODRECCOFINS,
    BDCODRECCSOCIAL,
    BDCODREC,
    BDCODRECISS,
    BDCODRECINSS)
AS
SELECT  mov.bdcodemp,
        mov.BDCHAVE,
        mov.bdreflan,
        mov.BDDATAENTRADAENT,
        mov.BDDATAEMISSAO,
        mov.BDCODTER,
        mov.BDNUMDOCINI,
        mov.BDMODELO,
        mov.BDESPECIE,
        mov.BDSERIE,
        mov.BDEMITENTE,
        mov.BDCODSITNF,
        MOV.bdcondpgto,
        COALESCE(RET.bdvlrpis,0.0) BDVLRPIS,
        COALESCE(RET.bdvlrcofins,0.0) BDVLRCOFINS,
        COALESCE(RET.bdvlrcsocial,0.0) BDVLRCSOCIAL,
        COALESCE(RET.bdvlrir,0.0) BDVLRIR,
        COALESCE(ded.bdretinss,0.0) BDVLRINSS,
        COALESCE(RET.bdissret,0.0) BDVLRISS,
        SUM(COALESCE(itens.BDVLRCONTAB,0)) BDVLRCONTAB,
        SUM(COALESCE(itens.BDBASEICMS,0)) BDBASEICMS,
        SUM(COALESCE(itens.BDBASEIPI,0)) BDBASEIPI,
        SUM(COALESCE(itens.BDBASEST,0)) BDBASEST,
        SUM(COALESCE(itens.BDISENTASICMS,0)) BDISENTASICMS,
        SUM(COALESCE(itens.BDISENTASIPI,0)) BDISENTASIPI,
        SUM(COALESCE(itens.BDOUTRASICMS,0)) BDOUTRASICMS,
        SUM(COALESCE(itens.BDOUTRASIPI,0)) BDOUTRASIPI,
        SUM(COALESCE(itens.BDVLRICMS,0)) BDVLRICMS,
        SUM(COALESCE(itens.BDVLRIPI,0)) BDVLRIPI,
        SUM(COALESCE(itens.BDVLRST,0)) BDVLRST,
        SUM(COALESCE(itens.BDIMPEXCLUIDAS,0)) BDIMPEXCLUIDAS,
        SUM(COALESCE(itens.BDOUTROSIMP,0)) BDOUTROSIMP,
        mov.BDDESCONTONOTA AS BDDESCONTO,
        SUM(COALESCE(itens.BDICMSRETENT,0)) BDICMSRETENT,
        SUM(COALESCE(itens.BDDIFALIQENT,0)) BDDIFALIQENT,

        PIS.bdcodrecof AS bdcodrecpis,
        COFINS.bdcodrecof AS bdcodreccofins,
        CSOCIAL.bdcodrecof AS bdcodreccsocial,
        IRRF.bdcodrecof AS bdcodrec,
        ISS.bdcodrecof AS bdcodreciss,
        INSS.bdcodrecof AS bdcodrecinss

FROM vef_emp_tmovent mov
LEFT OUTER JOIN vef_emp_tmoventitens itens ON (itens.bdcodemp = mov.bdcodemp AND itens.bdchave = mov.bdchave)
LEFT OUTER JOIN VEF_EMP_TMOVENTRET ret ON (ret.bdcodemp = mov.bdcodemp AND ret.bdchave = mov.bdchave)
LEFT OUTER JOIN VEF_EMP_TMOVENTDED ded ON (ded.bdcodemp = mov.bdcodemp AND ded.bdchave = mov.bdchave)

LEFT OUTER JOIN tcodrec PIS ON (PIS.bdcodrec = ret.bdcodrecpis)
LEFT OUTER JOIN tcodrec COFINS ON (COFINS.bdcodrec = ret.bdcodreccofins)
LEFT OUTER JOIN tcodrec CSOCIAL ON (CSOCIAL.bdcodrec = ret.bdcodreccsocial)
LEFT OUTER JOIN tcodrec IRRF ON (IRRF.bdcodrec = ret.bdcodrecir)
LEFT OUTER JOIN tcodrec ISS ON (ISS.bdcodrec = ret.bdcodreciss)
LEFT OUTER JOIN tcodrec INSS ON (INSS.bdcodrec = ded.bdcodrecinss)

GROUP BY mov.bdcodemp, mov.BDCHAVE, mov.bdreflan,  mov.BDDATAENTRADAENT, mov.BDDATAEMISSAO, mov.BDCODTER, mov.BDNUMDOCINI, mov.BDMODELO, mov.BDESPECIE,
         mov.BDSERIE, mov.BDEMITENTE, mov.BDCODSITNF,MOV.bdcondpgto, RET.bdvlrpis , RET.bdvlrcofins , RET.bdvlrcsocial, RET.bdvlrir, ded.bdretinss, RET.bdissret, mov.BDDESCONTONOTA,
         PIS.bdcodrecof, COFINS.bdcodrecof, CSOCIAL.bdcodrecof, IRRF.bdcodrecof, ISS.bdcodrecof, INSS.bdcodrecof

ORDER BY mov.bdcodemp,mov.bdchave
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TMOVENT_EXP_SVA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TMOVENT_EXP_SVA(
BDCODEMP,
BDCHAVE,
BDREFLAN,
BDDATAENTSAI,
BDDATAEMISSAO,
BDCODTER,
BDNUMDOCINI,
BDMODELO,
BDMODELOSTR,
BDESPECIE,
BDSERIE,
BDEMITENTE,
BDCODSITNF,
BDCIFFOB,
BDORDEM,
BDCODNAT,
BDVLRCONTAB,
BDBASEICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRICMS,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSRETENTSAI,
BDDIFALIQENTSAI,
BDCONDPGTO,
BDTIPOMOV)
 AS 
SELECT
        -- vef_emp_tmovent mov
        mov.bdcodemp,
        mov.BDCHAVE,
        mov.bdreflan,
        mov.BDDATAENTRADAENT,
        mov.BDDATAEMISSAO,
        mov.BDCODTER,

        mov.BDNUMDOCINI,
        mov.BDMODELO,
        modlan.bdmodelostr,
        mov.BDESPECIE,
        mov.BDSERIE,
        mov.BDEMITENTE,
        mov.BDCODSITNF,
        mov.bdciffob,

        -- vef_emp_tmoventitens itens

        itens.BDORDEM,
        itens.bdcodnat,
        itens.BDVLRCONTAB,
        itens.BDBASEICMS,
        itens.BDBASEIPI,
        itens.BDBASEST,
        itens.BDISENTASICMS,
        itens.BDISENTASIPI,
        itens.BDOUTRASICMS,
        itens.BDOUTRASIPI,
        itens.BDVLRICMS,
        itens.BDVLRIPI,
        itens.BDVLRST,
        itens.BDIMPEXCLUIDAS,
        itens.BDOUTROSIMP,
        mov.BDDESCONTONOTA AS BDDESCONTO,
        itens.BDICMSRETENT,
        itens.BDDIFALIQENT,
        MOV.bdcondpgto,

        'ENT'

FROM vef_emp_tmoventitens itens
LEFT OUTER JOIN vef_emp_tmovent mov ON (mov.bdcodemp = itens.bdcodemp AND mov.bdchave = itens.bdchave)
LEFT OUTER JOIN vef_base_ttabmodelolan modlan ON (modlan.bdmodelo = mov.bdmodelo)
ORDER BY mov.bdcodemp, mov.bdchave, itens.bdordem
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TMOVENT_ITENS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TMOVENT_ITENS(
BDCODEMP,
BDCHAVE,
BDORDEM,
BDCODOBS,
BDCODNAT,
BDALIQICMS,
BDALIQST,
BDBASEICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRICMS,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDREDBCICMS,
BDVLRCONTAB,
BDDESCONTO,
BDTIPOLANENT,
BDICMSRETENT,
BDTIPORETENT,
BDDIFALIQENT,
BDVLRPISRET,
BDVLRCOFINSRET,
BDVLRCSOCIALRET,
BDIMPSUBSTITUIDORET,
BDIMPSUBSTITUTORET,
BDCSTICMS,
BDPREFIXONAT)
 AS 
SELECT ENTITENS.bdcodemp, ENTITENS.bdchave, ENTITENS.BDORDEM,ENTITENS.BDCODOBS,ENTITENS.BDCODNAT,ENTITENS.BDALIQICMS,
       ENTITENS.BDALIQST,ENTITENS.BDBASEICMS,ENTITENS.BDBASEIPI,ENTITENS.BDBASEST,ENTITENS.BDISENTASICMS,ENTITENS.BDISENTASIPI,
       ENTITENS.BDOUTRASICMS,ENTITENS.BDOUTRASIPI,ENTITENS.BDVLRICMS,ENTITENS.BDVLRIPI,ENTITENS.BDVLRST,ENTITENS.BDIMPEXCLUIDAS,
       ENTITENS.BDOUTROSIMP,ENTITENS.BDREDBCICMS,ENTITENS.BDVLRCONTAB,/*ENTITENS.BDCONDPGTO,*/ENTITENS.BDDESCONTO,ENTITENS.BDTIPOLANENT,
       ENTITENS.BDICMSRETENT,ENTITENS.BDTIPORETENT,ENTITENS.BDDIFALIQENT,

       ENTRET.BDVLRPIS BDVLRPISRET,ENTRET.bdvlrcofins BDVLRCOFINSRET,ENTRET.bdvlrcsocial BDVLRCSOCIALRET,
       ENTIMPRET.bdimpsubstituido BDIMPSUBSTITUIDORET,ENTIMPRET.bdimpsubstituto BDIMPSUBSTITUTORET,

       --cst
       cst.bdcsticms,
       entitens.bdprefixonat


FROM vef_emp_tmoventitens ENTITENS

LEFT OUTER JOIN vef_emp_tmoventret ENTRET
  ON (ENTITENS.BDCODEMP = ENTRET.BDCODEMP AND ENTITENS.bdchave = ENTRET.bdchave)

LEFT OUTER JOIN vef_base_ttabcsticms cst ON (ENTITENS.bdcodcsticms = cst.bdcodcsticms)

LEFT OUTER JOIN VEF_EMP_TMOVENTIMPRETSP ENTIMPRET
  ON (ENTITENS.BDCODEMP = ENTIMPRET.BDCODEMP AND ENTITENS.bdchave = ENTIMPRET.bdchave)
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TMOVENT_PRO_CST (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TMOVENT_PRO_CST(
BDCODEMP,
BDCODMATRIZ,
BDREFERENCIA,
BDCSTPIS,
BDCSTCOF,
BDCSTICMS,
BDCSTIPI,
BDTIPOLAN,
BDQTDITEM,
BDVLRITEM,
BDBCPIS,
BDBCCOFINS,
BDVLRPIS,
BDVLRCOFINS,
BDBCICMS,
BDBCIPI,
BDVLRICMS,
BDVLRIPI)
 AS 
SELECT  ENT.BDCODEMP,
        COALESCE(E.bdcodmatriz,ent.bdcodemp) bdcodmatriz,
        ENT.bdreflan,
        CSTPIS.bdcstpis,
        CSTCOF.bdcstcof,
        CSTICMS.bdcstICMS,
        CSTIPI.bdcodexpcstipi,
        'LAN' BDTIPOLAN,
        SUM(COALESCE(ENTPRO.BDQTDITEM,0)) BDQTDITEM,
        SUM(COALESCE(ENTPRO.BDVLRITEM,0)) BDVLRITEM,
        SUM(COALESCE(ENTPRO.BDBCPIS,0)) BDBCPIS,
        SUM(COALESCE(ENTPRO.BDBCCOFINS,0)) BDBCCOFINS,
        SUM(COALESCE(ENTPRO.BDVLRPIS,0)) BDVLRPIS,
        SUM(COALESCE(ENTPRO.BDVLRCOFINS,0)) BDVLRCOFINS,
        SUM(COALESCE(ENTPRO.bdbcicms,0)) bdbcicms,
        SUM(COALESCE(ENTPRO.bdbcipi,0)) bdbcipi,
        SUM(COALESCE(ENTPRO.bdvlricms,0)) bdvlricms,
        SUM(COALESCE(ENTPRO.bdvlripi,0)) bdvlripi


FROM vef_emp_tmovENT ENT
JOIN tempresas e ON (ent.bdcodemp = e.bdcodemp)
JOIN vef_emp_tmovENTitens ENTitens ON (ENT.bdcodemp = ENTitens.bdcodemp AND ENT.bdchave = ENTitens.bdchave)
JOIN vef_emp_tmovproENT ENTPRO ON (ENTitens.bdcodemp = ENTPRO.bdcodemp AND ENTitens.bdchave = ENTPRO.bdchave AND ENTitens.bdordem = ENTpro.bdordem)
LEFT OUTER JOIN VEF_BASE_TTABCSTPIS CSTPIS ON (ENTPRO.bdcodcstPIS = CSTPIS.bdcodcstPIS)
LEFT OUTER JOIN VEF_BASE_TTABCSTCOF CSTCOF ON (ENTPRO.bdcodcstCOF = CSTCOF.bdcodcstCOF)
LEFT OUTER JOIN VEF_BASE_TTABCSTICMS CSTICMS ON (ENTPRO.bdcodcsticms = CSTICMS.bdcodcsticms)
LEFT OUTER JOIN VEF_BASE_TTABCSTIPI CSTIPI ON (ENTPRO.bdcodcstipi = CSTIPI.bdcodcstipi)

GROUP BY ENT.BDCODEMP,e.bdcodmatriz, ENT.bdreflan, CSTPIS.bdcstpis, CSTCOF.bdcstcof, CSTICMS.bdcstICMS, CSTIPI.bdcodexpcstipi, BDTIPOLAN
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TMOVENT_PRO_EXPNFP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TMOVENT_PRO_EXPNFP(
BDCODEMP,
BDCHAVE,
BDORDEM,
BDORDEMPRO,
BDCODCTA,
BDCODPROD,
BDCODCSTCOF,
BDCODCSTICMS,
BDCODCSTPIS,
BDCODCSTIPI,
BDMOVFISICO,
BDQTDITEM,
BDVLRITEM,
BDVLRDESC,
BDVLRDESPACESSORIA,
BDREDBCICMS,
BDBCICMS,
BDBCPIS,
BDBCST,
BDBCIPI,
BDBCCOFINS,
BDBCISSQN,
BDALIQICMS,
BDALIQPIS,
BDALIQST,
BDALIQIPI,
BDALIQCOFINS,
BDALIQISSQN,
BDVLRICMS,
BDVLRPIS,
BDVLRST,
BDVLRIPI,
BDVLRCOFINS,
BDVLRISSQN,
BDCSTICMS,
BDCODEXPCSTIPI,
BDAPEUNIMEDFAT)
 AS 
SELECT ENTPRO.BDCODEMP,ENTPRO.BDCHAVE,ENTPRO.BDORDEM,ENTPRO.BDORDEMPRO,ENTPRO.BDCODCTA,ENTPRO.BDCODPROD,ENTPRO.BDCODCSTCOF,
       ENTPRO.BDCODCSTICMS,ENTPRO.BDCODCSTPIS,ENTPRO.BDCODCSTIPI,ENTPRO.BDMOVFISICO,ENTPRO.BDQTDITEM,ENTPRO.BDVLRITEM,
       ENTPRO.BDVLRDESC,ENTPRO.BDVLRDESPACESSORIA,ENTPRO.BDREDBCICMS,ENTPRO.BDBCICMS,ENTPRO.BDBCPIS,ENTPRO.BDBCST,
       ENTPRO.BDBCIPI,ENTPRO.BDBCCOFINS,ENTPRO.BDBCISSQN,ENTPRO.BDALIQICMS,ENTPRO.BDALIQPIS,ENTPRO.BDALIQST,ENTPRO.BDALIQIPI,
       ENTPRO.BDALIQCOFINS,ENTPRO.BDALIQISSQN,ENTPRO.BDVLRICMS,ENTPRO.BDVLRPIS,ENTPRO.BDVLRST,ENTPRO.BDVLRIPI,ENTPRO.BDVLRCOFINS,
       ENTPRO.BDVLRISSQN, CSTICMS.BDCSTICMS, CSTIPI.bdcodexpcstipi,
       --fator de conversão
       umfat.bdapeunimed BDAPEUNIMEDFAT


FROM vef_emp_tmovproENT ENTPRO

LEFT OUTER JOIN vef_base_ttabcsticms CSTICMS ON ( ENTPRO.BDCODCSTICMS = CSTICMS.bdcodcsticms)

LEFT OUTER JOIN VEF_BASE_TTABCSTIPI CSTIPI ON ( ENTPRO.bdcodcstipi = CSTIPI.bdcodcstipi)
LEFT OUTER JOIN tfatconv fatcon ON (ENTPRO.BDCODEMP = FATCON.BDCODEMP AND ENTPRO.bdcodprod = fatcon.bdcodprod AND ENTPRO.bdcodfatcon = fatcon.bdcodfatcon)
LEFT OUTER JOIN tunidademedida umfat ON (fatcon.bdcodunimed = umfat.bdcodunimed)
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TMOVSAI (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TMOVSAI(
BDCODEMP,
BDCHAVE,
BDCODTER,
BDNUMDOCINI,
BDDATAEMISSAO,
BDESPECIE,
BDSERIE,
BDSUBSERIE,
BDNUMDOCFIM,
BDMODELO,
BDMODELOSTR,
BDEMITENTE,
BDDATASAIDA,
BDCODSITNF,
BDORDEMINFCOM_D500,
BDCODCTA,
BDTIPOASSINANTE,
BDVLRSER,
BDVLRSERNTRIB,
BDVLRCOBTERC,
BDVLROUTDESP_D500,
BDVLRPIS_D500,
BDVLRCOFINS_D500,
BDCODTENSAO,
BDORDEMINFCOM_C500,
BDORDEMCONS,
BDVLRCONSFOR,
BDVLRCOBTER,
BDVLRDESPACE,
BDVLRPIS_C500,
BDVLRCOFINS_C500,
BDTIPOLIGACAO,
BDCHAVENFE,
BDINDFRETE,
BDVLRFRETE,
BDVLRSEGURO,
BDVLROUTDESP_C100,
BDVLRTOTPIS,
BDVLRTOTCOFINS,
BDVLRTOTPISST,
BDVLRTOTCOFINSST,
BDCODTER_VLTRAN,
BDCODUF,
BDQTDVOLTRAN,
BDPESOBRUTO,
BDPESOLIQUIDO,
BDPLACAID,
BDSIGLAUF,
BDCGCTER,
BDCODCTA_C300,
BDVLRTOTPIS_C300,
BDVLRTOTCOFINS_C300,
BDCODCONS,
BDCODINFCOM_C500,
BDCODINFCOM_D500,
BDCODCTA_D100,
BDORDEMINFCOM_D100,
BDCHAVECTE_D100,
BDTIPOCTE_D100,
BDCHAVECTEREF_D100,
BDINDFRETE_D100,
BDCONDPGTO,
BDVALORNOTA,
BDDESCONTONOTA)
 AS 
SELECT SAI.bdcodemp, SAI.bdchave, SAI.BDCODTER,SAI.BDNUMDOCINI,SAI.BDDATAEMISSAO,SAI.BDESPECIE,SAI.BDSERIE,SAI.BDSUBSERIE,
       SAI.BDNUMDOCFIM, SAI.BDMODELO, MODLAN.bdmodelostr, SAI.BDEMITENTE, SAI.bddatasaida,SAI.BDCODSITNF,

       SAID500.BDORDEMINFCOM BDORDEMINFCOM_D500,SAID500.BDCODCTA,SAID500.BDTIPOASSINANTE,SAID500.BDVLRSER,SAID500.BDVLRSERNTRIB,
       SAID500.BDVLRCOBTERC,SAID500.BDVLROUTDESP BDVLROUTDESP_D500,SAID500.BDVLRPIS BDVLRPIS_D500,SAID500.BDVLRCOFINS BDVLRCOFINS_D500,

       SAIC500.BDCODTENSAO, SAIC500.BDORDEMINFCOM BDORDEMINFCOM_C500,SAIC500.BDORDEMCONS,SAIC500.BDVLRCONSFOR,SAIC500.BDVLRCOBTER,
       SAIC500.BDVLRDESPACE,SAIC500.BDVLRPIS BDVLRPIS_C500,SAIC500.BDVLRCOFINS BDVLRCOFINS_C500,SAIC500.BDTIPOLIGACAO, SAI.BDCHAVENFE,

       INDFRETEC100.BDCODEXPFRETE BDINDFRETE,SAIC100.BDVLRFRETE,SAIC100.BDVLRSEGURO,SAIC100.BDVLROUTDESP BDVLROUTDESP_C100,
       SAIC100.BDVLRTOTPIS,SAIC100.BDVLRTOTCOFINS,SAIC100.BDVLRTOTPISST,SAIC100.BDVLRTOTCOFINSST,

       SAIVLTRAN.BDCODTER BDCODTER_VLTRAN ,SAIVLTRAN.BDCODUF,SAIVLTRAN.BDQTDVOLTRAN,SAIVLTRAN.BDPESOBRUTO,
       SAIVLTRAN.BDPESOLIQUIDO,SAIVLTRAN.BDPLACAID,

       uf.bdsiglauf,
       TER.BDCGCTER,

       C300C350.bdcodcta bdcodcta_C300, C300C350.bdvlrtotpis bdvlrtotpis_C300, C300C350.bdvlrtotcofins bdvlrtotcofins_C300,

       codcons.bdcodcons,

       infconc500.bdcodinfcom bdcodinfcom_c500,
       infcond500.bdcodinfcom bdcodinfcom_d500,
       --D100
       SAID100.BDCODCTA BDCODCTA_D100 ,infconD100.bdcodinfcom BDORDEMINFCOM_D100 ,
       SAID100.BDCHAVECTE BDCHAVECTE_D100 ,SAID100.BDTIPOCTE BDTIPOCTE_D100 ,
       SAID100.BDCHAVECTEREF BDCHAVECTEREF_D100 ,INDFRETED100.BDCODEXPFRETE BDINDFRETE_D100,
       SAI.BDCONDPGTO, SAI.bdvalornota, SAI.BDDESCONTONOTA

FROM vef_emp_tmovsai SAI
LEFT OUTER JOIN vef_emp_td100sai SAID100 ON (SAI.BDCODEMP = SAID100.BDCODEMP AND SAI.bdchave = SAID100.bdchave)
LEFT OUTER JOIN vef_emp_td500sai SAID500 ON (SAI.BDCODEMP = SAID500.BDCODEMP AND SAI.bdchave = SAID500.bdchave)
LEFT OUTER JOIN vef_emp_tC500sai SAIC500 ON (SAI.BDCODEMP = SAIC500.BDCODEMP AND SAI.bdchave = SAIC500.bdchave)
LEFT OUTER JOIN vef_emp_tc100sai SAIC100 ON (SAI.BDCODEMP = SAIC100.BDCODEMP AND SAI.bdchave = SAIC100.bdchave)
LEFT OUTER JOIN VEF_EMP_TMOVSAIVLTRAN SAIVLTRAN ON (SAI.BDCODEMP = SAIVLTRAN.BDCODEMP AND SAI.bdchave = SAIVLTRAN.bdchave)
LEFT OUTER JOIN vef_emp_tc300350sai C300C350 ON (SAI.BDCODEMP = C300C350.BDCODEMP AND SAI.bdchave = C300C350.bdchave)
LEFT OUTER JOIN tuf uf ON (saivltran.bdcoduf = uf.bdcoduf)
LEFT OUTER JOIN tterceiro ter ON (ter.bdcodter = SAI.bdcodter)
LEFT OUTER JOIN vef_base_ttabcodcons codcons ON (codcons.bdordemcons = saic500.bdordemcons)

LEFT OUTER JOIN vef_base_tcadinfcom infconc500 ON (infconc500.bdordeminfcom = SAIc500.bdordeminfcom)
LEFT OUTER JOIN vef_base_tcadinfcom infcond500 ON (infcond500.bdordeminfcom = SAId500.bdordeminfcom)
LEFT OUTER JOIN vef_base_tcadinfcom infconD100 ON (infconD100.bdordeminfcom = SAID100.bdordeminfcom)
LEFT OUTER JOIN VEF_BASE_TTABINFRETE INDFRETEC100 ON (INDFRETEC100.BDORDEMFRETE = SAIC100.BDINDFRETE)
LEFT OUTER JOIN VEF_BASE_TTABINFRETE INDFRETED100 ON (INDFRETED100.BDORDEMFRETE = SAID100.BDINDFRETE)
LEFT OUTER JOIN vef_base_ttabmodelolan modlan ON (modlan.bdmodelo = sai.bdmodelo)
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TMOVSAI_E_ITENS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TMOVSAI_E_ITENS(
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    BDDATASAIDA,
    BDDATAEMISSAO,
    BDCODTER,
    BDNUMDOCINI,
    BDMODELO,
    BDESPECIE,
    BDSERIE,
    BDEMITENTE,
    BDCODSITNF,
    BDCONDPGTO,
    BDVLRPIS,
    BDVLRCOFINS,
    BDVLRCSOCIAL,
    BDVLRIR,
    BDVLRINSS,
    BDVLRISS,
    BDVLRCONTAB,
    BDBASEICMS,
    BDBASEIPI,
    BDBASEST,
    BDISENTASICMS,
    BDISENTASIPI,
    BDOUTRASICMS,
    BDOUTRASIPI,
    BDVLRICMS,
    BDVLRIPI,
    BDVLRST,
    BDIMPEXCLUIDAS,
    BDOUTROSIMP,
    BDDESCONTO,
    BDICMSRETENT,
    BDCODRECPIS,
    BDCODRECCOFINS,
    BDCODRECCSOCIAL,
    BDCODREC,
    BDCODRECISS,
    BDCODRECINSS)
AS
SELECT  mov.bdcodemp,
        mov.BDCHAVE,
        mov.bdreflan,
        mov.BDDATASAIDA,
        mov.BDDATAEMISSAO,
        mov.BDCODTER,
        mov.BDNUMDOCINI,
        mov.BDMODELO,
        mov.BDESPECIE,
        mov.BDSERIE,
        mov.BDEMITENTE,
        mov.BDCODSITNF,
        mov.BDCONDPGTO,

        COALESCE(RET.bdvlrpis,0.0) BDVLRPIS,
        COALESCE(RET.bdvlrcofins,0.0) BDVLRCOFINS,
        COALESCE(RET.bdvlrcsocial,0.0) BDVLRCSOCIAL,
        COALESCE(RET.bdvlrir,0.0) BDVLRIR,
        COALESCE(DED.bdretinss,0.0) BDVLRINSS,
        COALESCE(RET.bdissret,0.0) BDVLRISS,

        SUM(COALESCE(itens.BDVLRCONTAB,0)) BDVLRCONTAB,
        SUM(COALESCE(itens.BDBASEICMS,0)) BDBASEICMS,
        SUM(COALESCE(itens.BDBASEIPI,0)) BDBASEIPI,
        SUM(COALESCE(itens.BDBASEST,0)) BDBASEST,
        SUM(COALESCE(itens.BDISENTASICMS,0)) BDISENTASICMS,
        SUM(COALESCE(itens.BDISENTASIPI,0)) BDISENTASIPI,
        SUM(COALESCE(itens.BDOUTRASICMS,0)) BDOUTRASICMS,
        SUM(COALESCE(itens.BDOUTRASIPI,0)) BDOUTRASIPI,
        SUM(COALESCE(itens.BDVLRICMS,0)) BDVLRICMS,
        SUM(COALESCE(itens.BDVLRIPI,0)) BDVLRIPI,
        SUM(COALESCE(itens.BDVLRST,0)) BDVLRST,
        SUM(COALESCE(itens.BDIMPEXCLUIDAS,0)) BDIMPEXCLUIDAS,
        SUM(COALESCE(itens.BDOUTROSIMP,0)) BDOUTROSIMP,
        mov.BDDESCONTONOTA AS BDDESCONTO,
        SUM(COALESCE(itens.bdicmsfretesai,0)) BDICMSRETSAI,

        PIS.bdcodrecof AS bdcodrecpis,
        COFINS.bdcodrecof AS bdcodreccofins,
        CSOCIAL.bdcodrecof AS bdcodreccsocial,
        IRRF.bdcodrecof AS bdcodrec,
        ISS.bdcodrecof AS bdcodreciss,
        INSS.bdcodrecof AS bdcodrecinss

FROM vef_emp_TMOVSAI mov
LEFT OUTER JOIN vef_emp_TMOVSAIitens itens ON (itens.bdcodemp = mov.bdcodemp AND itens.bdchave = mov.bdchave)
LEFT OUTER JOIN VEF_EMP_TMOVSAIRET ret ON (ret.bdcodemp = mov.bdcodemp AND ret.bdchave = mov.bdchave)
LEFT OUTER JOIN VEF_EMP_TMOVSAIDED ded ON (ded.bdcodemp = mov.bdcodemp AND ded.bdchave = mov.bdchave)

LEFT OUTER JOIN tcodrec PIS ON (PIS.bdcodrec = ret.bdcodrecpis)
LEFT OUTER JOIN tcodrec COFINS ON (COFINS.bdcodrec = ret.bdcodreccofins)
LEFT OUTER JOIN tcodrec CSOCIAL ON (CSOCIAL.bdcodrec = ret.bdcodreccsocial)
LEFT OUTER JOIN tcodrec IRRF ON (IRRF.bdcodrec = ret.bdcodrecir)
LEFT OUTER JOIN tcodrec ISS ON (ISS.bdcodrec = ret.bdcodreciss)
LEFT OUTER JOIN tcodrec INSS ON (INSS.bdcodrec = ded.bdcodrecinss)

GROUP BY mov.bdcodemp, mov.BDCHAVE,  mov.bdreflan,  mov.bddatasaida, mov.BDDATAEMISSAO, mov.BDCODTER, mov.BDNUMDOCINI, mov.BDMODELO, mov.BDESPECIE,
         mov.BDSERIE, mov.BDEMITENTE, mov.BDCODSITNF, mov.BDCONDPGTO, RET.bdvlrpis , RET.bdvlrcofins , RET.bdvlrcsocial, RET.bdvlrir, ded.bdretinss, RET.bdissret, mov.BDDESCONTONOTA,
         PIS.bdcodrecof, COFINS.bdcodrecof, CSOCIAL.bdcodrecof, IRRF.bdcodrecof, ISS.bdcodrecof, INSS.bdcodrecof

ORDER BY mov.bdcodemp,mov.bdchave
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TMOVSAI_EXP_SVA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TMOVSAI_EXP_SVA(
BDCODEMP,
BDCHAVE,
BDREFLAN,
BDDATAENTSAI,
BDDATAEMISSAO,
BDCODTER,
BDNUMDOCINI,
BDMODELO,
BDMODELOSTR,
BDESPECIE,
BDSERIE,
BDEMITENTE,
BDCODSITNF,
BDCIFFOB,
BDORDEM,
BDCODNAT,
BDVLRCONTAB,
BDBASEICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRICMS,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSRETENTSAI,
BDDIFALIQENTSAI,
BDCONDPGTO,
BDTIPOMOV)
 AS 
SELECT
        -- vef_emp_tmovent mov
        mov.bdcodemp,
        mov.BDCHAVE,
        mov.bdreflan,
        mov.bddatasaida,
        mov.BDDATAEMISSAO,
        mov.BDCODTER,
        mov.BDNUMDOCINI,
        mov.BDMODELO,
        modlan.bdmodelostr, 
        mov.BDESPECIE,
        mov.BDSERIE,
        mov.BDEMITENTE,
        mov.BDCODSITNF,
        mov.bdciffob,

        -- vef_emp_tmoventitens itens

        itens.BDORDEM,
        itens.bdcodnat,
        itens.BDVLRCONTAB,
        itens.BDBASEICMS,
        itens.BDBASEIPI,
        itens.BDBASEST,
        itens.BDISENTASICMS,
        itens.BDISENTASIPI,
        itens.BDOUTRASICMS,
        itens.BDOUTRASIPI,
        itens.BDVLRICMS,
        itens.BDVLRIPI,
        itens.BDVLRST,
        itens.BDIMPEXCLUIDAS,
        itens.BDOUTROSIMP,
        mov.BDDESCONTONOTA AS BDDESCONTO,
        itens.bdicmsfretesai,
        NULL,
        MOV.bdcondpgto,


        'SAI'

FROM vef_emp_tmovsai mov
LEFT OUTER JOIN vef_emp_tmovsaiitens itens ON (itens.bdcodemp = mov.bdcodemp AND itens.bdchave = mov.bdchave)
LEFT OUTER JOIN vef_base_ttabmodelolan modlan ON (modlan.bdmodelo = mov.bdmodelo)
ORDER BY mov.bdcodemp, mov.bdchave, itens.bdordem
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TMOVSAI_ITENS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TMOVSAI_ITENS(
BDCODEMP,
BDCHAVE,
BDORDEM,
BDCODOBS,
BDCODNAT,
BDALIQICMS,
BDALIQST,
BDBASEICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRICMS,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDREDBCICMS,
BDVLRCONTAB,
BDDESCONTO,
BDICMSFRETESAI,
BDACRECFINSAI,
BDREGEXPSAI,
BDVLRPISRET,
BDVLRCOFINSRET,
BDVLRCSOCIALRET,
BDIMPSUBSTITUIDORET,
BDIMPSUBSTITUTORET,
BDVLRIRRET,
    BDRETINSS,
BDISSRET,
BDCSTICMS,
BDPREFIXONAT)
 AS 
SELECT SAIITENS.bdcodemp, SAIITENS.bdchave, SAIITENS.BDORDEM,SAIITENS.BDCODOBS,SAIITENS.BDCODNAT,SAIITENS.BDALIQICMS,
       SAIITENS.BDALIQST,SAIITENS.BDBASEICMS,SAIITENS.BDBASEIPI,SAIITENS.BDBASEST,SAIITENS.BDISENTASICMS,SAIITENS.BDISENTASIPI,
       SAIITENS.BDOUTRASICMS,SAIITENS.BDOUTRASIPI,SAIITENS.BDVLRICMS,SAIITENS.BDVLRIPI,SAIITENS.BDVLRST,SAIITENS.BDIMPEXCLUIDAS,
       SAIITENS.BDOUTROSIMP,SAIITENS.BDREDBCICMS,SAIITENS.BDVLRCONTAB,SAIITENS.BDDESCONTO,
       SAIITENS.BDICMSFRETESAI, SAIITENS.BDACRECFINSAI, SAIITENS.BDREGEXPSAI,

       SAIRET.BDVLRPIS BDVLRPISRET,SAIRET.bdvlrcofins BDVLRCOFINSRET,SAIRET.bdvlrcsocial BDVLRCSOCIALRET,
       SAIIMPRET.bdimpsubstituido BDIMPSUBSTITUIDORET,SAIIMPRET.bdimpsubstituto BDIMPSUBSTITUTORET,
       SAIRET.BDVLRIR BDVLRIRRET, SAIDED.BDRETINSS , SAIRET.BDISSRET,

       cst.bdcsticms,
       saiitens.bdprefixonat


FROM vef_emp_tmovSAIITENS SAIITENS

LEFT OUTER JOIN vef_emp_tmovsairet SAIRET
  ON (SAIITENS.BDCODEMP = SAIRET.BDCODEMP AND SAIITENS.bdchave = SAIRET.bdchave)

LEFT OUTER JOIN vef_emp_tmovsaided SAIDED
  ON (SAIITENS.BDCODEMP = SAIDED.BDCODEMP AND SAIITENS.bdchave = SAIDED.bdchave)

LEFT OUTER JOIN vef_base_ttabcsticms cst ON (cst.bdcodcsticms = saiitens.bdcodcsticms)

LEFT OUTER JOIN VEF_EMP_TMOVSAIIMPRETSP SAIIMPRET
  ON (SAIITENS.BDCODEMP = SAIIMPRET.BDCODEMP AND SAIITENS.bdchave = SAIIMPRET.bdchave)
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TMOVSAI_PRO_CST (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TMOVSAI_PRO_CST(
BDCODEMP,
BDCODMATRIZ,
BDREFERENCIA,
BDCSTPIS,
BDCSTCOF,
BDCSTICMS,
BDCSTIPI,
BDTIPOLAN,
BDQTDITEM,
BDVLRITEM,
BDBCPIS,
BDBCCOFINS,
BDVLRPIS,
BDVLRCOFINS,
BDBCICMS,
BDBCIPI,
BDVLRICMS,
BDVLRIPI)
 AS 
SELECT  SAI.BDCODEMP,
        COALESCE(E.bdcodmatriz,sai.bdcodemp) bdcodmatriz,
        SAI.bdreflan,
        CSTPIS.bdcstpis,
        CSTCOF.bdcstcof,
        CSTICMS.bdcstICMS,
        CSTIPI.bdcodexpcstipi,
        'LAN' BDTIPOLAN,
        SUM(COALESCE(SAIPRO.BDQTDITEM,0)) BDQTDITEM,
        SUM(COALESCE(SAIPRO.BDVLRITEM,0)) BDVLRITEM,
        SUM(COALESCE(SAIPRO.BDBCPIS,0)) BDBCPIS,
        SUM(COALESCE(SAIPRO.BDBCCOFINS,0)) BDBCCOFINS,
        SUM(COALESCE(SAIPRO.BDVLRPIS,0)) BDVLRPIS,
        SUM(COALESCE(SAIPRO.BDVLRCOFINS,0)) BDVLRCOFINS,
        SUM(COALESCE(SAIPRO.bdbcicms,0)) bdbcicms,
        SUM(COALESCE(SAIPRO.bdbcipi,0)) bdbcipi,
        SUM(COALESCE(SAIPRO.bdvlricms,0)) bdvlricms,
        SUM(COALESCE(SAIPRO.bdvlripi,0)) bdvlripi

FROM vef_emp_tmovsai SAI
JOIN tempresas e ON (sai.bdcodemp = e.bdcodemp)
JOIN vef_emp_tmovsaiitens saiitens ON (sai.bdcodemp = saiitens.bdcodemp AND sai.bdchave = saiitens.bdchave)
JOIN vef_emp_tmovprosai SAIPRO ON (saiitens.bdcodemp = SAIPRO.bdcodemp AND saiitens.bdchave = SAIPRO.bdchave AND saiitens.bdordem = saipro.bdordem)
LEFT OUTER JOIN VEF_BASE_TTABCSTPIS CSTPIS ON (SAIPRO.bdcodcstPIS = CSTPIS.bdcodcstPIS)
LEFT OUTER JOIN VEF_BASE_TTABCSTCOF CSTCOF ON (SAIPRO.bdcodcstCOF = CSTCOF.bdcodcstCOF)
LEFT OUTER JOIN VEF_BASE_TTABCSTICMS CSTICMS ON (SAIPRO.bdcodcsticms = CSTICMS.bdcodcsticms)
LEFT OUTER JOIN VEF_BASE_TTABCSTIPI CSTIPI ON (SAIPRO.bdcodcstipi = CSTIPI.bdcodcstipi)

GROUP BY SAI.BDCODEMP,e.bdcodmatriz, SAI.bdreflan, CSTPIS.bdcstpis, CSTCOF.bdcstcof, CSTICMS.bdcstICMS, CSTIPI.bdcodexpcstipi, BDTIPOLAN


UNION

SELECT  REDZ.BDCODEMP,
        COALESCE(E.bdcodmatriz,redz.bdcodemp) bdcodmatriz,
        REDZ.bdreflan,
        CSTPIS.bdcstpis,
        CSTCOF.bdcstcof,
        CSTICMS.bdcstICMS,
        NULL bdcodexpcstipi,
        'ECF' BDTIPOLAN,
        SUM(ITEMDOCECF.bdqtditem) bdqtditem,
        SUM(ITEMDOCECF.bdvlrtotpro) bdvlrtotpro,
        SUM(ITEMDOCECF.BDVL_BC_PIS) BDVL_BC_PIS,
        SUM(ITEMDOCECF.bdvl_bc_cofins) bdvl_bc_cofins,
        SUM(ITEMDOCECF.BDVLRPIS) BDVLRPIS,
        SUM(ITEMDOCECF.BDVLRCOFINS) BDVLRCOFINS,
        SUM(0) bdbcicms,
        SUM(0) bdbcipi,
        SUM(0) bdvlricms,
        SUM(0) bdvlripi

FROM vef_emp_tredz REDZ
JOIN tempresas e ON (redz.bdcodemp = e.bdcodemp)
JOIN VEF_EMP_TDOCECF DOCECF ON (redz.bdcodemp = docecf.bdcodemp AND redz.bdchave = docecf.bdchave)
JOIN VEF_EMP_TITEMDOCECF ITEMDOCECF ON (REDZ.bdcodemp = ITEMDOCECF.bdcodemp AND REDZ.bdchave = ITEMDOCECF.bdchave AND docecf.bdordemdocecf = itemdocecf.bdordemdocecf)
LEFT OUTER JOIN VEF_BASE_TTABCSTPIS CSTPIS ON (itemDOCECF.bdcodcstPIS = CSTPIS.bdcodcstPIS)
LEFT OUTER JOIN VEF_BASE_TTABCSTCOF CSTCOF ON (itemDOCECF.bdcodcstCOF = CSTCOF.bdcodcstCOF)
LEFT OUTER JOIN VEF_BASE_TTABCSTICMS CSTICMS ON (itemDOCECF.bdcodcsticms = CSTICMS.bdcodcsticms)

GROUP BY REDZ.BDCODEMP,e.bdcodmatriz, REDZ.bdreflan, CSTPIS.bdcstpis, CSTCOF.bdcstcof, CSTICMS.bdcstICMS, bdcodexpcstipi, BDTIPOLAN

UNION

SELECT  REDZ.BDCODEMP,
        COALESCE(E.bdcodmatriz,redz.bdcodemp) bdcodmatriz,
        REDZ.bdreflan,
        CSTPIS.bdcstpis,
        CSTCOF.bdcstcof,
        NULL bdcstICMS,
        NULL bdcodexpcstipi,
        'C425' BDTIPOLAN,
        SUM(C425.bdqtdacu) bdqtdacu,
        SUM(C425.bdvlracu) bdvlracu,
        SUM(C425.BDVL_BC_PIS) BDVL_BC_PIS,
        SUM(C425.bdvl_bc_cofins) BDVL_BC_cof,
        SUM(C425.BDVLRPIS) BDVLRPIS,
        SUM(C425.BDVLRCOFINS) BDVLRCOFINS,
        SUM(0) bdbcicms,
        SUM(0) bdbcipi,
        SUM(0) bdvlricms,
        SUM(0) bdvlripi

FROM vef_emp_tredz REDZ
JOIN tempresas e ON (redz.bdcodemp = e.bdcodemp)
JOIN VEF_EMP_TREDZC425 C425 ON (redz.bdcodemp = C425.bdcodemp AND redz.bdchave = C425.bdchave)

LEFT OUTER JOIN VEF_BASE_TTABCSTPIS CSTPIS ON (C425.bdcodcstPIS = CSTPIS.bdcodcstPIS)
LEFT OUTER JOIN VEF_BASE_TTABCSTCOF CSTCOF ON (C425.bdcodcstCOF = CSTCOF.bdcodcstCOF)

GROUP BY REDZ.BDCODEMP,e.bdcodmatriz, REDZ.bdreflan, CSTPIS.bdcstpis, CSTCOF.bdcstcof, bdcstICMS, bdcodexpcstipi, BDTIPOLAN

UNION

SELECT  REDZ.BDCODEMP,
        COALESCE(E.bdcodmatriz,redz.bdcodemp) bdcodmatriz,
        REDZ.bdreflan,
        CSTPIS.bdcstpis,
        CSTCOF.bdcstcof,
        NULL bdcstICMS,
        NULL bdcodexpcstipi,
        'C425ALIQ' BDTIPOLAN,
        SUM(C425ALIQ.bdqtdacu) bdqtdacu,
        SUM(C425ALIQ.bdvlracu) bdvlracu,
        SUM(C425ALIQ.BDVL_BC_PIS) BDVL_BC_PIS,
        SUM(C425ALIQ.bdvl_bc_cofins) bdvl_bc_cofins,
        SUM(C425ALIQ.BDVLRPIS) BDVLRPIS,
        SUM(C425ALIQ.BDVLRCOFINS) BDVLRCOFINS,
        SUM(0) bdbcicms,
        SUM(0) bdbcipi,
        SUM(0) bdvlricms,
        SUM(0) bdvlripi

FROM vef_emp_tredz REDZ 
JOIN tempresas e ON (redz.bdcodemp = e.bdcodemp)
JOIN VEF_EMP_TREDZVARALIQ VARALIQ ON (redz.bdcodemp = varaliq.bdcodemp AND redz.bdchave = varaliq.bdchave)
JOIN VEF_EMP_TREDZC425ALIQ C425ALIQ ON (redz.bdcodemp = C425aliq.bdcodemp AND redz.bdchave = C425aliq.bdchave AND varaliq.bdordemicms = C425aliq.bdordemicms)

LEFT OUTER JOIN VEF_BASE_TTABCSTPIS CSTPIS ON (C425ALIQ.bdcodcstPIS = CSTPIS.bdcodcstPIS)
LEFT OUTER JOIN VEF_BASE_TTABCSTCOF CSTCOF ON (C425ALIQ.bdcodcstCOF = CSTCOF.bdcodcstCOF)

GROUP BY REDZ.BDCODEMP,e.bdcodmatriz, REDZ.bdreflan, CSTPIS.bdcstpis, CSTCOF.bdcstcof, bdcstICMS, bdcodexpcstipi, BDTIPOLAN
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TMOVSAI_PRO_EXPNFP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TMOVSAI_PRO_EXPNFP(
BDCODEMP,
BDCHAVE,
BDORDEM,
BDORDEMPRO,
BDCODCTA,
BDCODPROD,
BDCODCSTCOF,
BDCODCSTICMS,
BDCODCSTPIS,
BDCODCSTIPI,
BDMOVFISICO,
BDQTDITEM,
BDVLRITEM,
BDVLRDESC,
BDVLRDESPACESSORIA,
BDREDBCICMS,
BDBCICMS,
BDBCPIS,
BDBCST,
BDBCIPI,
BDBCCOFINS,
BDBCISSQN,
BDALIQICMS,
BDALIQPIS,
BDALIQST,
BDALIQIPI,
BDALIQCOFINS,
BDALIQISSQN,
BDVLRICMS,
BDVLRPIS,
BDVLRST,
BDVLRIPI,
BDVLRCOFINS,
BDVLRISSQN,
BDCODCLAENETEL,
BDINDREC,
BDCODCLAENETELGAS,
BDINDRECGAS,
BDCSTICMS,
BDCODEXPCSTIPI,
BDCODSELOIPI,
BDQTDSELOIPI,
BDCODCLASSEIPI,
BDVLRUNIDADE,
BDQTDUNIDADE,
BDAPEUNIMEDFAT)
 AS 
SELECT SAIPRO.BDCODEMP,SAIPRO.BDCHAVE,SAIPRO.BDORDEM,SAIPRO.BDORDEMPRO,SAIPRO.BDCODCTA,SAIPRO.BDCODPROD,SAIPRO.BDCODCSTCOF,
       SAIPRO.BDCODCSTICMS,SAIPRO.BDCODCSTPIS,SAIPRO.BDCODCSTIPI,SAIPRO.BDMOVFISICO,SAIPRO.BDQTDITEM,SAIPRO.BDVLRITEM,
       SAIPRO.BDVLRDESC,SAIPRO.BDVLRDESPACESSORIA,SAIPRO.BDREDBCICMS,SAIPRO.BDBCICMS,SAIPRO.BDBCPIS,SAIPRO.BDBCST,
       SAIPRO.BDBCIPI,SAIPRO.BDBCCOFINS,SAIPRO.BDBCISSQN,SAIPRO.BDALIQICMS,SAIPRO.BDALIQPIS,SAIPRO.BDALIQST,SAIPRO.BDALIQIPI,
       SAIPRO.BDALIQCOFINS,SAIPRO.BDALIQISSQN,SAIPRO.BDVLRICMS,SAIPRO.BDVLRPIS,SAIPRO.BDVLRST,SAIPRO.BDVLRIPI,SAIPRO.BDVLRCOFINS,
       SAIPRO.BDVLRISSQN,

       SAIENETELE.bdcodclaenetel ,  SAIENETELE.bdindrec, /* D510 */

       SAIENEGAS.bdcodclaenetel BDCODCLAENETELGAS,  SAIENEGAS.bdindrec BDINDRECGAS,  /* C510 */

       CSTICMS.bdcsticms, CSTIPI.BDCODEXPCSTIPI,

       c177.bdcodseloipi, c177.bdqtdseloipi,

       clipi.bdcodclasseipi,

       c178.bdvlrunidade, c178.bdqtdunidade,

       --fator de conversão
       umfat.bdapeunimed BDAPEUNIMEDFAT

FROM vef_emp_tmovprosai SAIPRO

LEFT OUTER JOIN vef_emp_tenetele SAIENETELE ON (SAIPRO.BDCODEMP = SAIENETELE.BDCODEMP AND SAIPRO.bdchave = SAIENETELE.bdchave AND saipro.bdordem = saienetele.bdordem)
LEFT OUTER JOIN vef_emp_tenegas SAIENEGAS ON (SAIPRO.BDCODEMP = SAIENEGAS.BDCODEMP AND SAIPRO.bdchave = SAIENEGAS.bdchave AND saipro.bdordem = saienetele.bdordem)
LEFT OUTER JOIN vef_base_ttabcsticms CSTICMS ON ( SAIPRO.BDCODCSTICMS = CSTICMS.bdcodcsticms)
LEFT OUTER JOIN VEF_BASE_TTABCSTIPI CSTIPI ON ( SAIPRO.bdcodcstipi = CSTIPI.bdcodcstipi)
LEFT OUTER JOIN vef_emp_tmovprosaic177 c177 ON (C177.BDCODEMP = SAIPRO.bdcodemp AND C177.BDCHAVE = SAIPRO.bdchave AND C177.bdordem = SAIPRO.bdordem AND  C177.bdordempro = SAIPRO.bdordempro)
LEFT OUTER JOIN vef_emp_tmovprosaic178 c178 ON (C178.BDCODEMP = SAIPRO.bdcodemp AND C178.BDCHAVE = SAIPRO.bdchave AND C178.bdordem = SAIPRO.bdordem AND  C178.bdordempro = SAIPRO.bdordempro)
LEFT OUTER JOIN vef_base_ttabclasseipi clipi ON (clipi.bdordemclaipi = c178.bdordemclaipi)
LEFT OUTER JOIN tfatconv fatcon ON (saipro.bdcodemp = fatcon.bdcodemp AND saipro.bdcodprod = fatcon.bdcodprod AND saipro.bdcodfatcon = fatcon.bdcodfatcon)
LEFT OUTER JOIN tunidademedida umfat ON (fatcon.bdcodunimed = umfat.bdcodunimed)
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TMOVSER_E_ITENS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TMOVSER_E_ITENS(
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    BDDATAEMISSAO,
    BDCODTER,
    BDNUMDOCINI,
    BDESPECIE,
    BDSERIE,
    BDTIPLAN,
    BDCODSITNF,
    BDCONDPGTO,
    BDVLRPIS,
    BDVLRCOFINS,
    BDVLRCSOCIAL,
    BDCODRECPIS,
    BDCODRECCOFINS,
    BDCODRECCSOCIAL,
    BDCODREC,
    BDVLRCONTAB,
    BDDESCONTO,
    BDBCISSSER,
    BDVLRISSSER,
    BDISENTASISSSER,
    BDOUTRASISSSER,
    BDBCIRSER,
    BDVLRIRSER,
    BDACREDEDUIRSER,
    BDVLRINSS,
    BDCODRECINSS)
AS
SELECT  mov.bdcodemp,
        mov.BDCHAVE,
        mov.bdreflan,
        mov.BDDATAEMISSAO,
        mov.BDCODTER,
        mov.BDNUMDOCINI,
        mov.BDESPECIE,
        mov.BDSERIE,
        mov.bdtiplan,
        mov.BDCODSITNF,
        mov.BDCONDPGTO,

        COALESCE(RET.bdvlrpis,0.0) BDVLRPIS,
        COALESCE(RET.bdvlrcofins,0.0) BDVLRCOFINS,
        COALESCE(RET.bdvlrcsocial,0.0) BDVLRCSOCIAL,

        PIS.bdcodrecof AS bdcodrecpis,
        COFINS.bdcodrecof AS bdcodreccofins,
        CSOCIAL.bdcodrecof AS bdcodreccsocial,
        itens.bdcodrec,

        SUM(COALESCE(itens.BDVLRCONTAB,0)) BDVLRCONTAB,
        mov.BDDESCONTONOTA AS BDDESCONTO,
        SUM(COALESCE(itens.bdbcissser,0)) bdbcissser,
        SUM(COALESCE(RET.bdissRET,0)) bdvlrissser,
        SUM(COALESCE(itens.bdisentasissser,0)) bdisentasissser,
        SUM(COALESCE(itens.bdoutrasissser,0)) bdoutrasissser,
        SUM(COALESCE(itens.bdbcirser,0)) bdbcirser,
        SUM(COALESCE(itens.bdvlrirser,0)) bdvlrirser,
        SUM(COALESCE(itens.bdacrededuirser,0)) bdacrededuirser,
        SUM(COALESCE(ded.bdretinss,0)) bdvlrinss,

        ded.BDCODRECINSS

FROM vef_emp_TMOVSER mov
LEFT OUTER JOIN vef_emp_TMOVSERitens itens ON (itens.bdcodemp = mov.bdcodemp AND itens.bdchave = mov.bdchave)
LEFT OUTER JOIN VEF_EMP_TMOVSERRET ret ON (ret.bdcodemp = mov.bdcodemp AND ret.bdchave = mov.bdchave)
LEFT OUTER JOIN VEF_EMP_TMOVSERDED ded ON (ded.bdcodemp = itens.bdcodemp AND ded.bdchave = itens.bdchave)

LEFT OUTER JOIN tcodrec PIS ON (PIS.bdcodrec = ret.bdcodrecpis)
LEFT OUTER JOIN tcodrec COFINS ON (COFINS.bdcodrec = ret.bdcodreccofins)
LEFT OUTER JOIN tcodrec CSOCIAL ON (CSOCIAL.bdcodrec = ret.bdcodreccsocial)


GROUP BY mov.bdcodemp, mov.BDCHAVE,  MOV.bdreflan, mov.BDDATAEMISSAO, mov.BDCODTER, mov.BDNUMDOCINI, mov.BDESPECIE,
         mov.BDSERIE, mov.bdtiplan, mov.BDCODSITNF, mov.BDCONDPGTO, RET.bdvlrpis , RET.bdvlrcofins , RET.bdvlrcsocial,
         PIS.bdcodrecof, COFINS.bdcodrecof, CSOCIAL.bdcodrecof, itens.bdcodrec,  ded.BDCODRECINSS, mov.BDDESCONTONOTA

ORDER BY mov.bdcodemp,mov.bdchave
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TMOVSER_EXP_SVA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TMOVSER_EXP_SVA(
BDCODEMP,
BDCHAVE,
BDREFLAN,
BDCODCIC,
BDDATAEMISSAO,
BDCODTER,
BDNUMDOCINI,
BDNUMDOCFIM,
BDTIPLAN,
BDESPECIE,
BDSERIE,
BDCODSITNF,
BDORDEM,
BDCODNAT,
BDVLRCONTAB,
BDDESCONTO,
BDALIQIRSER,
BDBCIRSER,
BDVLRIRSER,
BDVLRISSSER,
BDIDCFPS,
BDCODREC,
BDCODOBS,
BDIDCST,
BDCONDPGTO,
BDALIQREDBCISSSER,
BDBCISSSER,
BDALIQREDISSSER,
BDISENTASISSSER,
BDOUTRASISSSER,
BDACREDEDUIRSER,
BDACRECFINSER,
BDDIGOPERNAT,
BDPREFIXONAT,
BDCODATVM,
BDTIPOMOV)
 AS 
SELECT
        -- vef_emp_tmovser mov

        mov.bdcodemp,
        mov.bdchave,
        mov.bdreflan,
        mov.bdcodcid,
        mov.bddataemissao,
        mov.bdcodter,

        CAST(SUBSTRING(LPAD(mov.bdnumdocini,15,'0') FROM 7 FOR 9) AS INTEGER),
        CAST(SUBSTRING(LPAD(mov.bdnumdocfim,15,'0') FROM 7 FOR 9) AS INTEGER),
        mov.bdtiplan,
        mov.bdespecie,
        mov.bdserie,
        mov.bdcodsitnf,

        -- vef_emp_tmovseritens itens

        itens.bdordem,
        itens.bdcodnat,
        itens.bdvlrcontab,
        mov.BDDESCONTONOTA AS BDDESCONTO,
        itens.bdaliqirser,
        itens.bdbcirser,
        itens.bdvlrirser,
        itens.bdvlrissser,
        ISS.bdidcfps,
        itens.bdcodrec,
        itens.bdcodobs,
        ISS.bdidcst,
        MOV.bdcondpgto,
        itens.bdaliqredbcissser,
        itens.bdbcissser,
        itens.bdaliqredissser,
        itens.bdisentasissser,
        itens.bdoutrasissser,
        itens.bdacrededuirser,
        itens.bdacrecfinser,
        itens.bddigopernat,
        itens.bdprefixonat,
        itens.bdcodatvm,

        'SER'

FROM vef_emp_tmovseritens itens
JOIN vef_emp_tmovser mov ON (ITENS.bdcodemp = MOV.bdcodemp AND ITENS.bdchave = MOV.bdchave)
LEFT OUTER JOIN VEF_EMP_TMOVSERINDISS ISS ON (MOV.bdcodemp = ISS.bdcodemp AND MOV.bdchave = ISS.bdchave)
ORDER BY mov.bdcodemp, mov.bdchave, itens.bdordem
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TREDZ_E_VARCFOP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TREDZ_E_VARCFOP(
BDCODEMP,
BDCHAVE,
BDREFLAN,
BDORDEMMAQ,
BDDATAREDZ,
BDCONDPGTO,
BDNUMCUPINI,
BDNUMCUPFIN,
BDPOSCRO,
BDPOSCRZ,
BDNUMCOO,
BDVALGTFINAL,
BDVALVENBRU,
BDCODUSU,
BDCODTIPO,
BDDATALAN,
BDHORALAN,
BDNAOINCIDICMS,
BDISSQN,
BDALIQISSQN,
BDNAOINCIDISS,
BDVALOPNFISCAIS,
BDVALCANCOPNFISCAIS,
BDVALACREOPNFISCAIS,
BDVALDESCOPNFISCAIS,
BDVALIOF,
BDVALCANCICMS,
BDVALACREICMS,
BDVALDESCICMS,
BDVALCANCISSQN,
BDVALACREISSQN,
BDVALDESCISSQN,
BDVLRCONTAB,
BDBASEICMS,
BDVLRICMS,
BDISENTASICMS,
BDOUTRASICMS,
BDBASEST,
BDVLRST,
BDVLRPIS,
BDVLRCOFINS)
 AS 
SELECT  r.BDCODEMP,
        r.BDCHAVE,
        r.BDREFLAN,
        r.BDORDEMMAQ,
        r.BDDATAREDZ,
        v.bdcondpgto,
        r.BDNUMCUPINI,
        r.BDNUMCUPFIN,
        r.BDPOSCRO,
        r.BDPOSCRZ,
        r.BDNUMCOO,
        r.BDVALGTFINAL,
        r.BDVALVENBRU,
        r.BDCODUSU,
        r.BDCODTIPO,
        r.BDDATALAN,
        r.BDHORALAN,
        r.BDNAOINCIDICMS,
        r.BDISSQN,
        r.BDALIQISSQN,
        r.BDNAOINCIDISS,
        r.BDVALOPNFISCAIS,
        r.BDVALCANCOPNFISCAIS,
        r.BDVALACREOPNFISCAIS,
        r.BDVALDESCOPNFISCAIS,
        r.BDVALIOF,
        r.BDVALCANCICMS,
        r.BDVALACREICMS,
        r.BDVALDESCICMS,
        r.BDVALCANCISSQN,
        r.BDVALACREISSQN,
        r.BDVALDESCISSQN,
        SUM(COALESCE(v.BDVLRCONTAB, 0)) BDVLRCONTAB,
        SUM(COALESCE(v.BDBASEICMS, 0)) BDBASEICMS,
        SUM(COALESCE(v.BDVLRICMS, 0)) BDVLRICMS,
        SUM(COALESCE(v.BDISENTASICMS, 0)) BDISENTASICMS,
        SUM(COALESCE(v.BDOUTRASICMS, 0)) BDOUTRASICMS,
        SUM(COALESCE(v.BDBASEST, 0)) BDBASEST,
        SUM(COALESCE(v.BDVLRST, 0)) BDVLRST,
        SUM(COALESCE(v.bdvlrpis, 0)) BDVLRPIS,
  SUM(COALESCE(v.bdvlrcofins, 0)) BDVLRCOFINS
FROM vef_emp_tredz r
LEFT OUTER JOIN vef_emp_tredzvarcfop  v ON (v.bdcodemp = r.bdcodemp AND v.bdchave = r.bdchave)
GROUP BY r.BDCODEMP, r.BDCHAVE, r.BDREFLAN, r.BDORDEMMAQ, r.BDDATAREDZ, v.bdcondpgto, r.BDNUMCUPINI, r.BDNUMCUPFIN,
        r.BDPOSCRO, r.BDPOSCRZ, r.BDNUMCOO, r.BDVALGTFINAL, r.BDVALVENBRU, r.BDCODUSU, r.BDCODTIPO, r.BDDATALAN,
        r.BDHORALAN, r.BDNAOINCIDICMS, r.BDISSQN, r.BDALIQISSQN, r.BDISENTASISS,
        r.BDNAOINCIDISS, r.BDVALOPNFISCAIS, r.BDVALCANCOPNFISCAIS, r.BDVALACREOPNFISCAIS, r.BDVALDESCOPNFISCAIS,
        r.BDVALIOF, r.BDVALCANCICMS, r.BDVALACREICMS, r.BDVALDESCICMS, r.BDVALCANCISSQN, r.BDVALACREISSQN, r.BDVALDESCISSQN
ORDER BY r.bdcodemp, r.bdchave
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TREDZ_EXP_SVA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TREDZ_EXP_SVA(
BDCODEMP,
BDDATAREDZ,
BDCODPROD,
BDQTDITEM,
BDALIQICMS,
BDVLRTOTPRO)
 AS 
SELECT C470.BDCODEMP ,MRC.bddataredz, C470.BDCODPROD , C470.BDQTDITEM ,  C470.BDALIQICMS , C470.BDVLRTOTPRO

FROM VEF_EMP_TITEMDOCECF C470 ,VEF_EMP_TDOCECF C460, VEF_EMP_TREDZ MRC
WHERE (C470.bdcodemp = C460.bdcodemp AND C470.bdchave = C460.bdchave AND C470.bdordemdocecf = C460.bdordemdocecf)
AND (C460.bdcodemp = MRC.bdcodemp AND C460.bdchave = MRC.bdchave)
ORDER BY c460.bdcodemp, c460.bdchave
;

/* CREATE OR ALTER VIEW: VW_VEF_EMP_TREDZC425 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_EMP_TREDZC425(
BDCODEMP,
BDCHAVE,
BDORDEMICMS,
BDORDEMTOT,
BDORDEMC425,
BDCODPROD,
BDCODNATREC,
BDCODCSTCOF,
BDCODCSTPIS,
BDQTDACU,
BDVLRACU,
BDVLRPIS,
BDVL_BC_PIS,
BDALIQ_PIS,
BDQUANT_BC_PIS,
BDALIQ_PIS_QUANT,
BDVL_BC_COFINS,
BDALIQ_COFINS,
BDQUANT_BC_COFINS,
BDALIQ_COFINS_QUANT,
BDNUMTOT,
BDVLRCOFINS,
BDALIQICMS)
 AS 
SELECT

    a.BDCODEMP,a.BDCHAVE,a.BDORDEMICMS,a.BDORDEMTOT,a.BDORDEMC425,a.BDCODPROD,a.BDCODNATREC,a.BDCODCSTCOF,a.BDCODCSTPIS,a.BDQTDACU,a.BDVLRACU,
    a.BDVLRPIS,a.BDVL_BC_PIS,a.BDALIQ_PIS,a.BDQUANT_BC_PIS,a.BDALIQ_PIS_QUANT,a.BDVL_BC_COFINS,a.BDALIQ_COFINS,a.BDQUANT_BC_COFINS,a.BDALIQ_COFINS_QUANT,
    a.BDNUMTOT,a.BDVLRCOFINS,b.bdaliqicms
FROM VEF_EMP_TREDZC425ALIQ a
LEFT OUTER JOIN vef_emp_tredzvaraliq b ON (b.bdcodemp = a.bdcodemp AND b.bdchave = a.bdchave AND b.bdordemicms = a.bdordemicms)


UNION
  SELECT
    BDCODEMP,BDCHAVE,0 BDORDEMICMS,BDORDEMTOT,BDORDEMC425,BDCODPROD,BDCODNATREC,BDCODCSTCOF,BDCODCSTPIS,BDQTDACU,BDVLRACU,
    BDVLRPIS,BDVL_BC_PIS,BDALIQ_PIS,BDQUANT_BC_PIS,BDALIQ_PIS_QUANT,BDVL_BC_COFINS,BDALIQ_COFINS,BDQUANT_BC_COFINS,
    BDALIQ_COFINS_QUANT,BDNUMTOT,BDVLRCOFINS,0
FROM VEF_EMP_TREDZC425
;

/* CREATE OR ALTER VIEW: VW_VEF_RETENCOES_ENT_SAI_SER (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_RETENCOES_ENT_SAI_SER(
BDCODEMP,
BDREFLAN,
BDVLRPIS,
BDVLRCOFINS,
BDVLRCSOCIAL,
BDISSRET)
 AS 
SELECT SER.BDCODEMP,SER.bdreflan ,COALESCE(SER.BDVLRPIS,0),COALESCE(SER.BDVLRCOFINS,0),COALESCE(SER.BDVLRCSOCIAL,0),COALESCE(SER.BDISSRET,0)
FROM VW_UNION_VEF_SER_RET SER

UNION ALL

SELECT retent.BDCODEMP,ent.bdreflan ,COALESCE(retent.bdvlrpis,0),COALESCE(retent.bdvlrcofins,0),COALESCE(retent.bdvlrcsocial,0),0 BDISSRET
FROM vef_emp_tmoventret retent , vef_emp_tmovent ent
WHERE (retent.bdcodemp = ent.bdcodemp AND retent.bdchave = ent.bdchave )
AND ent.bdcodsitnf NOT IN (2,3,4,5)

UNION ALL

SELECT retsai.BDCODEMP,sai.bdreflan ,COALESCE(retsai.bdvlrpis,0),COALESCE(retsai.bdvlrcofins,0),COALESCE(retsai.bdvlrcsocial,0),0 BDISSRET
FROM vef_emp_tmovsairet retsai ,vef_emp_tmovsai sai
WHERE (retsai.bdcodemp = sai.bdcodemp AND retsai.bdchave = sai.bdchave)
AND sai.bdcodsitnf NOT IN (2,3,4,5)

UNION ALL

SELECT retdem.BDCODEMP,dem.bdreflan ,COALESCE(retdem.bdvlrpis,0),COALESCE(retdem.bdvlrcofins,0),COALESCE(retdem.bdvlrcsocial,0) ,0 BDISSRET
FROM vef_emp_tmovdemret retdem ,vef_emp_tmovdemaisdoc_f100 dem
WHERE (retdem.bdcodemp = dem.bdcodemp AND retdem.bdchave = dem.bdchave)
;

/* CREATE OR ALTER VIEW: VW_VEF_SER_RET (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_SER_RET(
BDCODEMP,
BDREFLAN,
BDBCISSSER,
BDVLRPIS,
BDVLRCOFINS,
BDVLRCSOCIAL,
BDISSRET,
BDSUBEMPREI,
BDMATERIAIS,
BDVLRINSS,
BDCODRECINSS,
BDCODRECPIS,
BDCODRECCOFINS,
BDCODRECCSOCIAL,
BDVLRIRSER,
BDCODRECIR,
BDTIPLAN,
BDCGCTER)
 AS 
SELECT ret.BDCODEMP,mov.bdreflan,itens.bdbcissser,ret.BDVLRPIS,ret.BDVLRCOFINS,ret.BDVLRCSOCIAL,ret.bdissret,ret.BDSUBEMPREI,
       ret.BDMATERIAIS,ret.BDVLRINSS,ret.BDCODRECINSS,ret.BDCODRECPIS,ret.BDCODRECCOFINS,ret.BDCODRECCSOCIAL,
       itens.BDVLRIRSER,itens.bdcodrec bdcodrecir,MOV.bdtiplan, ter.bdcgcter
FROM vef_emp_tmovserret ret ,vef_emp_tmovseritens itens , vef_emp_tmovser mov, tterceiro ter
 WHERE (ret.bdcodemp = itens.bdcodemp AND ret.bdchave = itens.bdchave)
 AND (itens.bdcodemp = mov.bdcodemp) AND (itens.bdchave = mov.bdchave)
 AND (ter.bdcodter = mov.bdcodter)
;

/* CREATE OR ALTER VIEW: VW_VEF_TABELAS_TREDICMSSN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TABELAS_TREDICMSSN(
BDCODRED,
BDCODUF,
BDREFERENCIA,
BDCODREDFAIXA,
BDFAIXADE,
BDFAIXAATE,
BDALIQRED)
AS
SELECT icms.bdCODRED, icms.bdCODUF, icms.bdREFERENCIA,
       fx.bdCODREDFAIXA, fx.bdFAIXADE, fx.bdFAIXAATE, fx.bdALIQRED
FROM VEF_TABELAS_TREDICMSSN icms
JOIN VEF_TABELAS_TREDICMSFAIXASSN fx ON (fx.bdCODRED = icms.bdCODRED)
WHERE (
       icms.bdREFERENCIA = (SELECT FIRST 1 x.bdREFERENCIA
                            FROM VEF_TABELAS_TREDICMSSN x
                            WHERE x.bdCODUF = icms.bdCODUF
                              AND x.bdREFERENCIA <= CASE icms.bdCODUF
                                                      WHEN 18 THEN -- No caso do Paraná caso seja após 2017, vaio jogar fixo para 2017, pois deve verificar as alíquotas anteriores a 2018 e após e pegar a menor alíquota
                                                        IIF(((SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) FROM RDB$DATABASE) > 201712),
                                                            201712,
                                                            (SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) FROM RDB$DATABASE))
                                                      ELSE (SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) FROM RDB$DATABASE)
                                                    END
                            ORDER BY x.bdCODUF DESC, x.bdREFERENCIA DESC)
       )
;

/* CREATE OR ALTER VIEW: VW_VEF_TABELAS_TREDISSSN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TABELAS_TREDISSSN(
BDCODRED,
BDCODCID,
BDREFERENCIA,
BDCODREDFAIXA,
BDFAIXADE,
BDFAIXAATE,
BDALIQRED)
 AS 
SELECT ISS.BDCODRED,ISS.BDCODCID,ISS.BDREFERENCIA,ISSFX.BDCODREDFAIXA,ISSFX.BDFAIXADE,ISSFX.BDFAIXAATE,ISSFX.BDALIQRED
FROM VEF_TABELAS_TREDISSSN ISS, VEF_TABELAS_TREDISSFAIXASN ISSFX
WHERE (ISS.BDCODRED = ISSFX.BDCODRED)
AND (ISS.BDREFERENCIA =(SELECT MAX(Y.BDREFERENCIA) FROM VEF_TABELAS_TREDISSSN Y WHERE Y.BDREFERENCIA <=
            (SELECT FIRST 1 MAX(a.BDREFERENCIA)
             FROM VEF_TABELAS_TREDISSSN a
             WHERE (a.BDCODRED = ISS.BDCODRED) AND  CAST(a.BDREFERENCIA AS VARCHAR(6)) <=
                      (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
                       FROM rdb$database)
             GROUP BY a.BDREFERENCIA
             ORDER BY a.BDREFERENCIA DESC )))
;

/* CREATE OR ALTER VIEW: VW_VEF_TMOVENTDIFALIQ (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TMOVENTDIFALIQ(
BDCODEMP,
BDCHAVE,
BDORDEM,
BDVLRDIFENTALIQ)
 AS 
SELECT dif.bdcodemp,
       dif.bdchave,
       dif.bdordem,
       SUM(COALESCE(dif.BDVLRDIFENTALIQ,0)) BDVLRDIFENTALIQ

FROM vef_emp_tmoventdifaliq dif
GROUP BY dif.bdcodemp, dif.bdchave, dif.bdordem
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_CID_ENT (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_CID_ENT(
BDCODEMP,
BDREFLAN,
BDCODCID,
BDNOMCID,
BDCODUF,
BDPRURALTER,
BDCODNAT,
BDPREFIXONAT,
BDVLRCONTAB)
 AS 
SELECT ENT.BDCODEMP,
       ENT.BDREFLAN,
       TER.BDCODCID,
       CID.BDNOMCID,
       CID.BDCODUF,
       TER.BDPRURALTER,
       ITENS.BDCODNAT,
       ITENS.BDPREFIXONAT,
       SUM(COALESCE(ITENS.BDVLRCONTAB, 0)) BDVLRCONTAB 
FROM VEF_EMP_TMOVENT ENT 
LEFT OUTER JOIN VEF_EMP_TMOVENTITENS ITENS ON ENT.BDCODEMP = ITENS.BDCODEMP AND ENT.BDCHAVE = ITENS.BDCHAVE 
LEFT OUTER JOIN VW_TTERCEIRO TER ON TER.BDCODTER = ENT.BDCODTER 
LEFT OUTER JOIN TCIDADE CID ON CID.BDCODCID = TER.BDCODCID 

GROUP BY ENT.BDCODEMP, ENT.BDREFLAN, TER.BDCODCID, CID.BDNOMCID, CID.BDCODUF, TER.BDPRURALTER, ITENS.BDCODNAT, ITENS.BDPREFIXONAT 
ORDER BY ENT.BDCODEMP, ENT.BDREFLAN, TER.BDCODCID, ITENS.BDCODNAT, ITENS.BDPREFIXONAT
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_CID_SAI (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_CID_SAI(
BDCODEMP,
BDREFLAN,
BDCODCID,
BDNOMCID,
BDCODUF,
BDCODNAT,
BDPREFIXONAT,
BDVLRCONTAB)
 AS 
SELECT SAI.BDCODEMP,
       SAI.BDREFLAN,
       SAI.BDCODCID,
       CID.BDNOMCID,
       CID.BDCODUF,
       ITENS.BDCODNAT,
       ITENS.BDPREFIXONAT,
       SUM(COALESCE(ITENS.BDVLRCONTAB, 0)) BDVLRCONTAB 
FROM VEF_EMP_TMOVSAI SAI 
LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS ITENS ON SAI.BDCODEMP = ITENS.BDCODEMP AND SAI.BDCHAVE = ITENS.BDCHAVE 
LEFT OUTER JOIN VW_TTERCEIRO TER ON TER.BDCODTER = SAI.BDCODTER 
LEFT OUTER JOIN TCIDADE CID ON CID.BDCODCID = SAI.BDCODCID 

GROUP BY SAI.BDCODEMP, SAI.BDREFLAN, SAI.BDCODCID, CID.BDNOMCID, CID.BDCODUF, ITENS.BDCODNAT, ITENS.BDPREFIXONAT 
ORDER BY SAI.BDCODEMP, SAI.BDREFLAN, SAI.BDCODCID, ITENS.BDCODNAT, ITENS.BDPREFIXONAT
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_ENT (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_ENT(
BDREFLAN,
BDCODEMP,
BDCODMATRIZ,
BDCODNAT,
BDPREFIXONAT,
BDCODOPDAPI,
BDVLRCONTAB,
BDBASEICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRICMS,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSRETENT,
BDDIFALIQENT,
BDIMPSUBSTITUTO,
BDIMPSUBSTITUIDO,
BDVLRPIS,
BDVLRCOFINS,
BDVALNTRIBST,
BDICMSRETST)
 AS 
SELECT  MOV.BDREFLAN,
        itens.bdcodemp,
        COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,
        itens.bdcodnat,
        itens.BDPREFIXONAT,
        nat.bdcodopdapi,
        SUM(COALESCE(itens.BDVLRCONTAB,0)) BDVLRCONTAB,
        SUM(COALESCE(itens.BDBASEICMS,0)) BDBASEICMS,
        SUM(COALESCE(itens.BDBASEIPI,0)) BDBASEIPI,
        SUM(COALESCE(itens.BDBASEST,0)) BDBASEST,
        SUM(COALESCE(itens.BDISENTASICMS,0)) BDISENTASICMS,
        SUM(COALESCE(itens.BDISENTASIPI,0)) BDISENTASIPI,
        SUM(COALESCE(itens.BDOUTRASICMS,0)) BDOUTRASICMS,
        SUM(COALESCE(itens.BDOUTRASIPI,0)) BDOUTRASIPI,
        SUM(COALESCE(itens.BDVLRICMS,0)) BDVLRICMS,
        SUM(COALESCE(itens.BDVLRIPI,0)) BDVLRIPI,
        SUM(COALESCE(itens.BDVLRST,0)) BDVLRST,
        SUM(COALESCE(itens.BDIMPEXCLUIDAS,0)) BDIMPEXCLUIDAS,
        SUM(COALESCE(itens.BDOUTROSIMP,0)) BDOUTROSIMP,
        SUM(COALESCE(itens.BDDESCONTO,0)) BDDESCONTO,
        SUM(COALESCE(itens.BDICMSRETENT,0)) BDICMSRETENT,
        SUM(COALESCE(dif.bdvlrdifentaliq,0)) BDDIFALIQENT,
        SUM(COALESCE(r.bdimpsubstituto,0)) bdimpsubstituto,
        SUM(COALESCE(r.bdimpsubstituido,0)) bdimpsubstituido,
        SUM(COALESCE(itens.BDVLRPIS,0)) BDVLRPIS,
        SUM(COALESCE(itens.BDVLRCOFINS,0)) BDVLRCOFINS,
        SUM(COALESCE(itens.BDVALNTRIBST,0)) BDVALNTRIBST,
        SUM(COALESCE(itens.bdicmsretent,0)) BDICMSRETST

FROM vef_emp_tmoventitens itens
JOIN TEMPRESAS E ON (ITENS.BDCODEMP = E.BDCODEMP)
JOIN vef_emp_tmovent MOV ON ((itens.bdcodemp = MOV.bdcodemp) AND (itens.bdchave = MOV.bdchave))
LEFT OUTER JOIN VEF_EMP_TMOVENTIMPRETSP r ON (MOV.bdcodemp = r.bdcodemp AND MOV.bdchave = r.bdchave AND itens.bdordem = r.bdordem)
JOIN VEF_BASE_TNATOP nat ON (itens.bdcodnat = nat.bdcodnat) 
LEFT OUTER JOIN VW_VEF_TMOVENTDIFALIQ dif ON (dif.bdcodemp = itens.bdcodemp AND dif.bdchave = itens.bdchave AND dif.bdordem = itens.bdordem)
WHERE (MOV.bdcodsitnf NOT IN (2,3,4,5)) AND (COALESCE(itens.bdvlrcontab,0) + COALESCE(itens.bdbaseicms,0) + COALESCE(itens.bdvlricms,0) + COALESCE(itens.bdisentasicms,0) + COALESCE(itens.bdoutrasicms,0) + COALESCE(itens.bdoutrosimp,0) + COALESCE(bdvlrst,0) + COALESCE(bdvlripi,0) > 0)
GROUP BY MOV.bdreflan, itens.bdcodemp,e.bdcodmatriz,itens.bdcodnat, itens.bdprefixonat,nat.bdcodopdapi
ORDER BY itens.bdcodemp,mov.bdreflan
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_ENT_DATE (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_ENT_DATE(
BDDATAENTRADAENT,
BDCODEMP,
BDCODMATRIZ,
BDCODNAT,
BDPREFIXONAT,
BDVLRCONTAB,
BDBASEICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRICMS,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSRETENT,
BDDIFALIQENT)
 AS 
SELECT  MOV.BDdataentradaent,
        itens.bdcodemp,
        COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,
        itens.bdcodnat,
        itens.BDPREFIXONAT,
        SUM(COALESCE(itens.BDVLRCONTAB,0)) BDVLRCONTAB,
        SUM(COALESCE(itens.BDBASEICMS,0)) BDBASEICMS,
        SUM(COALESCE(itens.BDBASEIPI,0)) BDBASEIPI,
        SUM(COALESCE(itens.BDBASEST,0)) BDBASEST,
        SUM(COALESCE(itens.BDISENTASICMS,0)) BDISENTASICMS,
        SUM(COALESCE(itens.BDISENTASIPI,0)) BDISENTASIPI,
        SUM(COALESCE(itens.BDOUTRASICMS,0)) BDOUTRASICMS,
        SUM(COALESCE(itens.BDOUTRASIPI,0)) BDOUTRASIPI,
        SUM(COALESCE(itens.BDVLRICMS,0)) BDVLRICMS,
        SUM(COALESCE(itens.BDVLRIPI,0)) BDVLRIPI,
        SUM(COALESCE(itens.BDVLRST,0)) BDVLRST,
        SUM(COALESCE(itens.BDIMPEXCLUIDAS,0)) BDIMPEXCLUIDAS,
        SUM(COALESCE(itens.BDOUTROSIMP,0)) BDOUTROSIMP,
        SUM(COALESCE(itens.BDDESCONTO,0)) BDDESCONTO,
        SUM(COALESCE(itens.BDICMSRETENT,0)) BDICMSRETENT,
        SUM(COALESCE(itens.BDDIFALIQENT,0)) BDDIFALIQENT

FROM vef_emp_tmoventitens itens, vef_emp_tmovent MOV, tempresas e
WHERE ((itens.bdcodemp = MOV.bdcodemp) AND (itens.bdchave = MOV.bdchave))
AND (itens.bdcodemp = e.bdcodemp)
AND (MOV.bdcodsitnf NOT IN (2,3,4,5))
GROUP BY MOV.BDdataentradaent, itens.bdcodemp,e.bdcodmatriz,itens.bdcodnat, itens.bdprefixonat
ORDER BY itens.bdcodemp,mov.BDdataentradaent
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_ENT_DATE_PROD (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_ENT_DATE_PROD(
BDDATAENTRADAENT,
BDCODEMP,
BDCODPROD,
BDCODSAIDA,
BDCODIGOEAN,
BDNCMPROD,
BDDESCPROD,
BDCODNAT,
BDPREFIXONAT,
BDVLRCONTAB,
BDBASEICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRICMS,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSRETENT,
BDDIFALIQENT,
BDVLRITEMPROD,
BDVLRDESPAACESSORIAPROD,
BDVLRICMSPROD,
BDVLRPISPROD,
BDVLRSTPROD,
BDVLRIPIPROD,
BDVLRCOFINSPROD,
BDVLRISSQNPROD)
 AS 
SELECT  ent.bddataentradaent,
        movpro.bdcodemp,
        movpro.bdcodprod,
        cadpro.BDCODSAIDA,
        cadprounico.bdcodigoean,
        cadpro.bdncmprod,
        cadpro.bddescprod,
        itens.bdcodnat,
        itens.BDPREFIXONAT,
        SUM(COALESCE(itens.BDVLRCONTAB,0)) BDVLRCONTAB,
        SUM(COALESCE(itens.BDBASEICMS,0)) BDBASEICMS,
        SUM(COALESCE(itens.BDBASEIPI,0)) BDBASEIPI,
        SUM(COALESCE(itens.BDBASEST,0)) BDBASEST,
        SUM(COALESCE(itens.BDISENTASICMS,0)) BDISENTASICMS,
        SUM(COALESCE(itens.BDISENTASIPI,0)) BDISENTASIPI,
        SUM(COALESCE(itens.BDOUTRASICMS,0)) BDOUTRASICMS,
        SUM(COALESCE(itens.BDOUTRASIPI,0)) BDOUTRASIPI,
        SUM(COALESCE(itens.BDVLRICMS,0)) BDVLRICMS,
        SUM(COALESCE(movpro.BDVLRIPI,0)) BDVLRIPI,
        SUM(COALESCE(itens.BDVLRST,0)) BDVLRST,
        SUM(COALESCE(itens.BDIMPEXCLUIDAS,0)) BDIMPEXCLUIDAS,
        SUM(COALESCE(itens.BDOUTROSIMP,0)) BDOUTROSIMP,
        SUM(COALESCE(itens.BDDESCONTO,0)) BDDESCONTO,
        SUM(COALESCE(itens.BDICMSRETENT,0)) BDICMSRETENT,
        SUM(COALESCE(itens.BDDIFALIQENT,0)) BDDIFALIQENT,
        SUM(COALESCE(movpro.bdvlritem,0)) BDVLRITEMPROD,
        SUM(COALESCE(movpro.bdvlrdespacessoria,0)) BDVLRDESPAACESSORIAPROD,
        SUM(COALESCE(movpro.bdvlricms,0)) BDVLRICMSPROD,
        SUM(COALESCE(movpro.bdvlrpis,0)) BDVLRPISPROD,
        SUM(COALESCE(movpro.bdvlrst,0)) BDVLRSTPROD,
        SUM(COALESCE(movpro.bdvlripi,0)) BDVLRIPIPROD,
        SUM(COALESCE(movpro.bdvlrcofins,0)) BDVLRCOFINSPROD,
        SUM(COALESCE(movpro.bdvlrissqn,0)) BDVLRISSQNPROD



FROM vef_emp_tmovproent movpro
LEFT OUTER JOIN vef_emp_tmoventitens itens ON (itens.bdcodemp = movpro.bdcodemp AND itens.bdchave = movpro.bdchave AND itens.bdordem = movpro.bdordem)
LEFT OUTER JOIN vef_emp_tmovent ent ON (ent.bdcodemp = movpro.bdcodemp AND ent.bdchave = movpro.bdchave)
LEFT OUTER JOIN tcadpro_vinc cadpro ON (cadpro.bdcodemp = movpro.bdcodemp AND cadpro.bdcodprod = movpro.bdcodprod)
LEFT OUTER JOIN tcadpro cadprounico ON (cadprounico.bdcodprod = cadpro.bdcodprod)
WHERE (ENT.bdcodsitnf NOT IN (2,3,4,5))
GROUP BY ent.bddataentradaent, movpro.bdcodemp,movpro.bdcodprod,cadpro.BDCODSAIDA,cadprounico.bdcodigoean,cadpro.bdncmprod,cadpro.bddescprod,itens.bdcodnat,itens.bdprefixonat
ORDER BY movpro.bdcodemp, ent.bddataentradaent, cadpro.bdncmprod
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_ENT_DATE_REGCX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_ENT_DATE_REGCX(
BDDATAENTRADAENT,
BDCODEMP,
BDCODMATRIZ,
BDCODNAT,
BDPREFIXONAT,
BDVLRCONTAB,
BDBASEICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRICMS,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSRETENT,
BDDIFALIQENT)
 AS 
SELECT  MOV.BDdataentradaent,
        itens.bdcodemp,
        COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,
        itens.bdcodnat,
        itens.BDPREFIXONAT,
        SUM(COALESCE(itens.BDVLRCONTAB,0)) BDVLRCONTAB,
        SUM(COALESCE(itens.BDBASEICMS,0)) BDBASEICMS,
        SUM(COALESCE(itens.BDBASEIPI,0)) BDBASEIPI,
        SUM(COALESCE(itens.BDBASEST,0)) BDBASEST,
        SUM(COALESCE(itens.BDISENTASICMS,0)) BDISENTASICMS,
        SUM(COALESCE(itens.BDISENTASIPI,0)) BDISENTASIPI,
        SUM(COALESCE(itens.BDOUTRASICMS,0)) BDOUTRASICMS,
        SUM(COALESCE(itens.BDOUTRASIPI,0)) BDOUTRASIPI,
        SUM(COALESCE(itens.BDVLRICMS,0)) BDVLRICMS,
        SUM(COALESCE(itens.BDVLRIPI,0)) BDVLRIPI,
        SUM(COALESCE(itens.BDVLRST,0)) BDVLRST,
        SUM(COALESCE(itens.BDIMPEXCLUIDAS,0)) BDIMPEXCLUIDAS,
        SUM(COALESCE(itens.BDOUTROSIMP,0)) BDOUTROSIMP,
        SUM(COALESCE(itens.BDDESCONTO,0)) BDDESCONTO,
        SUM(COALESCE(itens.BDICMSRETENT,0)) BDICMSRETENT,
        SUM(COALESCE(itens.BDDIFALIQENT,0)) BDDIFALIQENT

FROM vef_emp_tmoventitens itens, vef_emp_tmovent MOV, tempresas e
WHERE ((itens.bdcodemp = MOV.bdcodemp) AND (itens.bdchave = MOV.bdchave)) AND (MOV.bdcondpgto <> 1)
AND (itens.bdcodemp = e.bdcodemp)
GROUP BY MOV.BDdataentradaent, itens.bdcodemp,e.bdcodmatriz,itens.bdcodnat, itens.bdprefixonat
ORDER BY itens.bdcodemp,mov.BDdataentradaent
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_ENT_DATE_TERC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_ENT_DATE_TERC(
BDDATAENTRADAENT,
BDCODTER,
BDCODEMP,
BDCODNAT,
BDPREFIXONAT,
BDVLRCONTAB,
BDBASEICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRICMS,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSRETENT,
BDDIFALIQENT)
 AS 
SELECT  mov.bddataentradaent,
        mov.bdcodter, 
        itens.bdcodemp,
        itens.bdcodnat,
        itens.BDPREFIXONAT,
        SUM(COALESCE(itens.BDVLRCONTAB,0)) BDVLRCONTAB,
        SUM(COALESCE(itens.BDBASEICMS,0)) BDBASEICMS,
        SUM(COALESCE(itens.BDBASEIPI,0)) BDBASEIPI,
        SUM(COALESCE(itens.BDBASEST,0)) BDBASEST,
        SUM(COALESCE(itens.BDISENTASICMS,0)) BDISENTASICMS,
        SUM(COALESCE(itens.BDISENTASIPI,0)) BDISENTASIPI,
        SUM(COALESCE(itens.BDOUTRASICMS,0)) BDOUTRASICMS,
        SUM(COALESCE(itens.BDOUTRASIPI,0)) BDOUTRASIPI,
        SUM(COALESCE(itens.BDVLRICMS,0)) BDVLRICMS,
        SUM(COALESCE(itens.BDVLRIPI,0)) BDVLRIPI,
        SUM(COALESCE(itens.BDVLRST,0)) BDVLRST,
        SUM(COALESCE(itens.BDIMPEXCLUIDAS,0)) BDIMPEXCLUIDAS,
        SUM(COALESCE(itens.BDOUTROSIMP,0)) BDOUTROSIMP,
        SUM(COALESCE(itens.BDDESCONTO,0)) BDDESCONTO,
        SUM(COALESCE(itens.BDICMSRETENT,0)) BDICMSRETENT,
        SUM(COALESCE(itens.BDDIFALIQENT,0)) BDDIFALIQENT

FROM vef_emp_tmoventitens itens , vef_emp_tmovent MOV

WHERE ((itens.bdcodemp = MOV.bdcodemp) AND (itens.bdchave = MOV.bdchave))
    AND (MOV.bdcodsitnf NOT IN (2,3,4,5))

GROUP BY MOV.BDdataentradaent,
         MOV.bdcodter,
         itens.bdcodemp,
         itens.bdcodnat,
         itens.bdprefixonat
ORDER BY itens.bdcodemp,mov.BDdataentradaent, MOV.bdcodter
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_ENT_REGCAIXA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_ENT_REGCAIXA(
BDREFLAN,
BDCODEMP,
BDCODMATRIZ,
BDCODNAT,
BDPREFIXONAT,
BDCODOPDAPI,
BDVLRCONTAB,
BDBASEICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRICMS,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSRETENT,
BDDIFALIQENT,
BDIMPSUBSTITUTO,
BDIMPSUBSTITUIDO,
BDVLRPIS,
BDVLRCOFINS,
BDVALNTRIBST)
 AS 
SELECT  MOV.BDREFLAN,
        itens.bdcodemp,
        COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,
        itens.bdcodnat,
        itens.BDPREFIXONAT,
        nat.bdcodopdapi,
        SUM(COALESCE(itens.BDVLRCONTAB,0)) BDVLRCONTAB,
        SUM(COALESCE(itens.BDBASEICMS,0)) BDBASEICMS,
        SUM(COALESCE(itens.BDBASEIPI,0)) BDBASEIPI,
        SUM(COALESCE(itens.BDBASEST,0)) BDBASEST,
        SUM(COALESCE(itens.BDISENTASICMS,0)) BDISENTASICMS,
        SUM(COALESCE(itens.BDISENTASIPI,0)) BDISENTASIPI,
        SUM(COALESCE(itens.BDOUTRASICMS,0)) BDOUTRASICMS,
        SUM(COALESCE(itens.BDOUTRASIPI,0)) BDOUTRASIPI,
        SUM(COALESCE(itens.BDVLRICMS,0)) BDVLRICMS,
        SUM(COALESCE(itens.BDVLRIPI,0)) BDVLRIPI,
        SUM(COALESCE(itens.BDVLRST,0)) BDVLRST,
        SUM(COALESCE(itens.BDIMPEXCLUIDAS,0)) BDIMPEXCLUIDAS,
        SUM(COALESCE(itens.BDOUTROSIMP,0)) BDOUTROSIMP,
        SUM(COALESCE(itens.BDDESCONTO,0)) BDDESCONTO,
        SUM(COALESCE(itens.BDICMSRETENT,0)) BDICMSRETENT,
        SUM(COALESCE(itens.BDDIFALIQENT,0)) BDDIFALIQENT,
        SUM(COALESCE(r.bdimpsubstituto,0)) bdimpsubstituto,
        SUM(COALESCE(r.bdimpsubstituido,0)) bdimpsubstituido,
        SUM(COALESCE(itens.BDVLRPIS,0)) BDVLRPIS,
        SUM(COALESCE(itens.BDVLRCOFINS,0)) BDVLRCOFINS,
        SUM(COALESCE(itens.BDVALNTRIBST,0)) BDVALNTRIBST

FROM vef_emp_tmoventitens itens
JOIN TEMPRESAS E ON (ITENS.BDCODEMP = E.BDCODEMP)
JOIN vef_emp_tmovent MOV ON ((itens.bdcodemp = MOV.bdcodemp) AND (itens.bdchave = MOV.bdchave))
LEFT OUTER JOIN VEF_EMP_TMOVENTIMPRETSP r ON (MOV.bdcodemp = r.bdcodemp AND MOV.bdchave = r.bdchave AND itens.bdordem = r.bdordem)
JOIN VEF_BASE_TNATOP nat ON (itens.bdcodnat = nat.bdcodnat) 
WHERE (MOV.bdcodsitnf NOT IN (2,3,4,5)) AND (MOV.bdcondpgto <> 1)
GROUP BY MOV.bdreflan, itens.bdcodemp,e.bdcodmatriz,itens.bdcodnat, itens.bdprefixonat,nat.bdcodopdapi
ORDER BY itens.bdcodemp,mov.bdreflan
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_ENT_UF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_ENT_UF(
BDREFLAN,
BDCODEMP,
BDCODMATRIZ,
BDCODNAT,
BDPREFIXONAT,
BDCODUF,
BDCODOPDAPI,
BDVLRCONTAB,
BDBASEICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRICMS,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSRETENT,
BDDIFALIQENT,
BDIMPSUBSTITUTO,
BDIMPSUBSTITUIDO,
BDVLRPIS,
BDVLRCOFINS)
 AS 
SELECT  MOV.BDREFLAN,
        itens.bdcodemp,
        COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,
        itens.bdcodnat,
        itens.BDPREFIXONAT,
        cid.bdcoduf, 
        nat.BDCODOPDAPI,
        COALESCE(SUM(itens.BDVLRCONTAB),0) BDVLRCONTAB,
        COALESCE(SUM(itens.BDBASEICMS),0) BDBASEICMS,
        COALESCE(SUM(itens.BDBASEIPI),0) BDBASEIPI,
        COALESCE(SUM(itens.BDBASEST),0) BDBASEST,
        COALESCE(SUM(itens.BDISENTASICMS),0) BDISENTASICMS,
        COALESCE(SUM(itens.BDISENTASIPI),0) BDISENTASIPI,
        COALESCE(SUM(itens.BDOUTRASICMS),0) BDOUTRASICMS,
        COALESCE(SUM(itens.BDOUTRASIPI),0) BDOUTRASIPI,
        COALESCE(SUM(itens.BDVLRICMS),0) BDVLRICMS,
        COALESCE(SUM(itens.BDVLRIPI),0) BDVLRIPI,
        COALESCE(SUM(itens.BDVLRST),0) BDVLRST,
        COALESCE(SUM(itens.BDIMPEXCLUIDAS),0) BDIMPEXCLUIDAS,
        COALESCE(SUM(itens.BDOUTROSIMP),0) BDOUTROSIMP,
        COALESCE(SUM(itens.BDDESCONTO),0) BDDESCONTO,
        COALESCE(SUM(itens.BDICMSRETENT),0) BDICMSRETENT,
        COALESCE(SUM(itens.BDDIFALIQENT),0) BDDIFALIQENT,
        COALESCE(SUM(r.bdimpsubstituto),0) bdimpsubstituto,
        COALESCE(SUM(r.bdimpsubstituido),0) bdimpsubstituido,
        COALESCE(SUM(itens.BDVLRPIS),0) BDVLRPIS,
        COALESCE(SUM(itens.BDVLRCOFINS),0) BDVLRCOFINS

FROM vef_emp_tmoventitens itens
JOIN TEMPRESAS E ON (itens.bdcodemp = e.bdcodemp)
JOIN vef_emp_tmovent MOV ON ((itens.bdcodemp = MOV.bdcodemp) AND (itens.bdchave = MOV.bdchave))
LEFT OUTER JOIN VEF_EMP_TMOVENTIMPRETSP r ON (MOV.bdcodemp = r.bdcodemp AND MOV.bdchave = r.bdchave AND itens.bdordem = r.bdordem)
LEFT OUTER JOIN vw_tterceiro ter ON (mov.bdcodter = ter.bdcodter)
LEFT OUTER JOIN tcidade cid ON (ter.bdcodcid = cid.bdcodcid)
JOIN VEF_BASE_TNATOP nat ON (itens.bdcodnat = nat.bdcodnat) 
WHERE MOV.bdcodsitnf NOT IN (2,3,4,5)
GROUP BY MOV.bdreflan, itens.bdcodemp,e.bdcodmatriz,itens.bdcodnat, itens.bdprefixonat, cid.bdcoduf, nat.BDCODOPDAPI
ORDER BY itens.bdcodemp,mov.bdreflan,cid.bdcoduf
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_SAI (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_SAI(
BDREFLAN,
BDCODEMP,
BDCODMATRIZ,
BDCODNAT,
BDPREFIXONAT,
BDCODOPDAPI,
BDVLRCONTAB,
BDBASEICMS,
BDVLRICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSFRETESAI,
BDACRECFINSAI,
BDIMPSUBSTITUTO,
BDIMPSUBSTITUIDO,
BDVLRPIS,
BDVLRCOFINS,
BDSTTRANSPORTE)
 AS 
SELECT  BDREFLAN,bdcodemp,BDCODMATRIZ,bdcodnat,BDPREFIXONAT,BDCODOPDAPI,COALESCE(SUM(bdvlrcontab),0) bdvlrcontab,COALESCE(SUM(bdbaseicms),0) bdbaseicms,
        COALESCE(SUM(bdvlricms),0) bdvlricms,COALESCE(SUM(BDBASEIPI),0) BDBASEIPI,COALESCE(SUM(BDBASEST),0) BDBASEST,COALESCE(SUM(BDISENTASICMS),0) BDISENTASICMS,
        COALESCE(SUM(BDISENTASIPI),0) BDISENTASIPI,COALESCE(SUM(BDOUTRASICMS),0) BDOUTRASICMS,COALESCE(SUM(BDOUTRASIPI),0) BDOUTRASIPI,
        COALESCE(SUM(BDVLRIPI),0) BDVLRIPI,COALESCE(SUM(BDVLRST),0) BDVLRST,COALESCE(SUM(BDIMPEXCLUIDAS),0) BDIMPEXCLUIDAS,
        COALESCE(SUM(BDOUTROSIMP),0) BDOUTROSIMP,COALESCE(SUM(BDDESCONTO),0) BDDESCONTO,COALESCE(SUM(BDICMSFRETESAI),0) BDICMSFRETESAI,COALESCE(SUM(BDACRECFINSAI),0) BDACRECFINSAI,
        COALESCE(SUM(bdimpsubstituto),0) bdimpsubstituto,COALESCE(SUM(bdimpsubstituido),0) bdimpsubstituido,COALESCE(SUM(BDVLRPIS),0) BDVLRPIS,COALESCE(SUM(BDVLRCOFINS),0) BDVLRCOFINS,
        COALESCE(SUM(BDSTTRANSPORTE),0) BDSTTRANSPORTE
FROM (
    SELECT  SAI.BDREFLAN,itens.bdcodemp,COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,itens.bdcodnat,itens.BDPREFIXONAT,nat.bdcodopdapi,SUM(COALESCE(itens.bdvlrcontab,0)) bdvlrcontab,SUM(COALESCE(itens.bdbaseicms,0)) bdbaseicms,
            SUM(COALESCE(itens.bdvlricms,0)) bdvlricms,SUM(COALESCE(BDBASEIPI,0)) BDBASEIPI,SUM(COALESCE(BDBASEST,0)) BDBASEST,SUM(COALESCE(BDISENTASICMS,0)) BDISENTASICMS,SUM(COALESCE(BDISENTASIPI,0)) BDISENTASIPI,
            SUM(COALESCE(BDOUTRASICMS,0)) BDOUTRASICMS,SUM(COALESCE(BDOUTRASIPI,0)) BDOUTRASIPI,SUM(COALESCE(BDVLRIPI,0)) BDVLRIPI,SUM(COALESCE(BDVLRST,0)) BDVLRST,SUM(COALESCE(BDIMPEXCLUIDAS,0)) BDIMPEXCLUIDAS,
            SUM(COALESCE(BDOUTROSIMP,0)) BDOUTROSIMP,SUM(COALESCE(BDDESCONTO,0)) BDDESCONTO,SUM(COALESCE(BDICMSFRETESAI,0)) BDICMSFRETESAI,SUM(COALESCE(BDACRECFINSAI,0)) BDACRECFINSAI,
            SUM(COALESCE(r.bdimpsubstituto,0)) bdimpsubstituto,SUM(COALESCE(r.bdimpsubstituido,0)) bdimpsubstituido,SUM(COALESCE(itens.BDVLRPIS,0)) BDVLRPIS,
            SUM(COALESCE(itens.BDVLRCOFINS,0)) BDVLRCOFINS, SUM(COALESCE(itens.BDSTTRANSPORTE,0)) BDSTTRANSPORTE
    FROM vef_emp_tmovsaiitens itens
    JOIN TEMPRESAS E ON (itens.bdcodemp = e.bdcodemp)
    JOIN vef_emp_tmovsai sai ON ((itens.bdcodemp = sai.bdcodemp) AND (itens.bdchave = sai.bdchave))
    LEFT OUTER JOIN VEF_EMP_TMOVSAIIMPRETSP r ON (SAI.bdcodemp = r.bdcodemp AND SAI.bdchave = r.bdchave AND itens.bdordem = r.bdordem)
    JOIN VEF_BASE_TNATOP nat ON (itens.bdcodnat = nat.bdcodnat) 
    WHERE (SAI.bdcodsitnf NOT IN (2,3,4,5)) AND (COALESCE(bdvlrcontab,0) + COALESCE(bdbaseicms,0) + COALESCE(bdvlricms,0) + COALESCE(bdisentasicms,0) + COALESCE(bdoutrasicms,0) + COALESCE(bdicmsfretesai,0) + COALESCE(bdoutrosimp,0) + COALESCE(bdvlrst,0) + COALESCE(bdvlripi,0) > 0)
    GROUP BY SAI.bdreflan, itens.bdcodemp,e.bdcodmatriz,itens.bdcodnat, itens.bdprefixonat,nat.bdcodopdapi

    UNION ALL
    
    SELECT BDREFLAN, bdcodemp, bdcodmatriz, bdcodnat, BDPREFIXONAT, bdcodopdapi,
       SUM(COALESCE(bdvlrcontab,0)) bdvlrcontab, SUM(COALESCE(bdbaseicms,0)) bdbaseicms, SUM(COALESCE(bdvlricms,0)) bdvlricms, SUM(COALESCE(BDBASEIPI,0)) BDBASEIPI, SUM(COALESCE(BDBASEST,0)) BDBASEST,
       SUM(COALESCE(BDISENTASICMS,0)) BDISENTASICMS, SUM(COALESCE(BDISENTASIPI,0)) BDISENTASIPI, SUM(COALESCE(BDOUTRASICMS,0)) BDOUTRASICMS , SUM(COALESCE(BDOUTRASIPI,0)) BDOUTRASIPI, SUM(COALESCE(BDVLRIPI,0)) BDVLRIPI,
       SUM(COALESCE(BDVLRST,0)) bdVLRST , SUM(COALESCE(BDIMPEXCLUIDAS,0)) BDIMPEXCLUIDAS , SUM(COALESCE(BDOUTROSIMP,0)) BDOUTROSIMP, SUM(COALESCE(BDDESCONTO,0)) BDDESCONTO,
       SUM(COALESCE(BDICMSFRETESAI,0)) BDICMSFRETESAI, SUM(COALESCE(BDACRECFINSAI,0)) BDACRECFINSAI,
       SUM(COALESCE(bdimpsubstituto,0)) bdimpsubstituto, SUM(COALESCE(bdimpsubstituido,0)) bdimpsubstituido, SUM(COALESCE(BDVLRPIS,0)) BDVLRPIS, SUM(COALESCE(BDVLRCOFINS,0)) BDVLRCOFINS,
       SUM(COALESCE(BDSTTRANSPORTE,0)) BDSTTRANSPORTE FROM (
       SELECT  SAI.BDREFLAN, SAI.bdcodemp,COALESCE(E.bdcodmatriz,sai.bdcodemp) bdcodmatriz,c.bdcodnat,CAST(SUBSTRING(CAST(c.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4) AS INTEGER) BDPREFIXONAT,nat.bdcodopdapi,
                  C.bdvlrcontab, C.bdbaseicms, C.bdvlricms, 0 BDBASEIPI, 0 BDBASEST,
                  c.bdisentasicms,
                  
                  0 BDISENTASIPI,
                  CASE WHEN c.bdaliqicms = 0 AND c.bdcodnat = 5405000 THEN c.bdvlrcontab ELSE c.bdoutrasicms END BDOUTRASICMS,
                  0 BDOUTRASIPI, 0 BDVLRIPI,
                  BDVLRST, 0 BDIMPEXCLUIDAS, 0 BDOUTROSIMP, 0 BDDESCONTO, 0 BDICMSFRETESAI, 0 BDACRECFINSAI,
                  0 bdimpsubstituto, 0 bdimpsubstituido, 0 BDVLRPIS, 0 BDVLRCOFINS, 0 BDSTTRANSPORTE
       FROM VEF_EMP_TREDZ SAI
       INNER JOIN VEF_EMP_TREDZVARCFOP c ON (SAI.bdcodemp = c.bdcodemp) AND (SAI.bdchave = c.bdchave)
       INNER JOIN VEF_BASE_TCADMAQMRC m ON (SAI.bdcodemp = m.bdcodemp) AND (SAI.bdordemmaq = m.bdordemmaq)
       INNER JOIN tempresas e ON (sai.bdcodemp = e.bdcodemp)
       JOIN VEF_BASE_TNATOP nat ON (c.bdcodnat = nat.bdcodnat))
    GROUP BY bdreflan, bdcodemp, bdcodmatriz, bdcodnat, bdprefixonat, bdcodopdapi
) s
GROUP BY bdreflan, bdcodemp,bdcodmatriz,bdcodnat,bdprefixonat,bdcodopdapi
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_SAI_DATE (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_SAI_DATE(
BDDATAEMISSAO,
BDCODEMP,
BDCODMATRIZ,
BDCODNAT,
BDPREFIXONAT,
BDVLRCONTAB,
BDBASEICMS,
BDVLRICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSFRETESAI,
BDACRECFINSAI)
 AS 
SELECT  SAI.BDDATAEMISSAO,
        itens.bdcodemp,
        COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,
        itens.bdcodnat,
        itens.BDPREFIXONAT,
        SUM(COALESCE(itens.bdvlrcontab,0)) bdvlrcontab,
        SUM(COALESCE(itens.bdbaseicms,0)) bdbaseicms,
        SUM(COALESCE(itens.bdvlricms,0)) bdvlricms,
        SUM(COALESCE(BDBASEIPI,0)) BDBASEIPI,
        SUM(COALESCE(BDBASEST,0)) BDBASEST,
        SUM(COALESCE(BDISENTASICMS,0)) BDISENTASICMS,
        SUM(COALESCE(BDISENTASIPI,0)) BDISENTASIPI,
        SUM(COALESCE(BDOUTRASICMS,0)) BDOUTRASICMS,
        SUM(COALESCE(BDOUTRASIPI,0)) BDOUTRASIPI,
        SUM(COALESCE(BDVLRIPI,0)) BDVLRIPI,
        SUM(COALESCE(BDVLRST,0)) BDVLRST,
        SUM(COALESCE(BDIMPEXCLUIDAS,0)) BDIMPEXCLUIDAS,
        SUM(COALESCE(BDOUTROSIMP,0)) BDOUTROSIMP,
        SUM(COALESCE(BDDESCONTO,0)) BDDESCONTO,
        SUM(COALESCE(BDICMSFRETESAI,0)) BDICMSFRETESAI,
        SUM(COALESCE(BDACRECFINSAI,0)) BDACRECFINSAI

FROM vef_emp_tmovsaiitens itens , vef_emp_tmovsai sai, TEMPRESAS E
WHERE ((itens.bdcodemp = sai.bdcodemp) AND (itens.bdchave = sai.bdchave))
AND (itens.bdcodemp = e.bdcodemp)
AND (sai.bdcodsitnf NOT IN (2,3,4,5))
GROUP BY SAI.BDDATAEMISSAO, itens.bdcodemp,e.bdcodmatriz,itens.bdcodnat, itens.bdprefixonat
--order by itens.bdcodemp,sai.bddataemissao

UNION ALL

SELECT  SAI.bddataredz,
        SAI.bdcodemp,
        COALESCE(E.bdcodmatriz,sai.bdcodemp) bdcodmatriz,
        c.bdcodnat,
        CAST(SUBSTRING(CAST(c.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4) AS INTEGER) BDPREFIXONAT,
        SUM(C.bdvlrcontab) bdvlrcontab,
        SUM(C.bdbaseicms) bdbaseicms,
        SUM(C.bdvlricms) bdvlricms,
        SUM(0) BDBASEIPI,
        SUM(0) BDBASEST,
        SUM(C.BDISENTASICMS) BDISENTASICMS,
        SUM(0) BDISENTASIPI,
        SUM(C.BDOUTRASICMS) BDOUTRASICMS,
        SUM(0) BDOUTRASIPI,
        SUM(0) BDVLRIPI,
        SUM(0) BDVLRST,
        SUM(0) BDIMPEXCLUIDAS,
        SUM(0) BDOUTROSIMP,
        SUM(0) BDDESCONTO,
        SUM(0) BDICMSFRETESAI,
        SUM(0) BDACRECFINSAI

FROM VEF_EMP_TREDZ SAI, VEF_EMP_TREDZVARCFOP c, VEF_BASE_TCADMAQMRC m, tempresas e
WHERE SAI.bdcodemp = c.bdcodemp AND SAI.bdchave = c.bdchave AND SAI.bdcodemp = m.bdcodemp AND SAI.bdordemmaq = m.bdordemmaq
AND (sai.bdcodemp = e.bdcodemp)

GROUP BY SAI.bddataredz, SAI.bdcodemp,e.bdcodmatriz,c.bdcodnat, bdprefixonat
--order by SAI.bdcodemp,sai.bddataredz
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_SAI_DATE_PROD (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_SAI_DATE_PROD(
BDDATAEMISSAO,
BDCODEMP,
BDCODPROD,
BDCODSAIDA,
BDCODIGOEAN,
BDNCMPROD,
BDDESCPROD,
BDCODNAT,
BDPREFIXONAT,
BDVLRCONTAB,
BDBASEICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRICMS,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSFRETESAI,
BDACRECFINSAI,
BDVLRITEMPROD,
BDVLRDESPAACESSORIAPROD,
BDVLRICMSPROD,
BDVLRPISPROD,
BDVLRSTPROD,
BDVLRIPIPROD,
BDVLRCOFINSPROD,
BDVLRISSQNPROD)
 AS 
SELECT  sai.bddataemissao,
        movpro.bdcodemp,
        movpro.bdcodprod,
        cadpro.BDCODSAIDA,
        cadprounico.bdcodigoean,
        cadpro.bdncmprod,
        cadpro.bddescprod,
        itens.bdcodnat,
        itens.BDPREFIXONAT,
        SUM(COALESCE(itens.BDVLRCONTAB,0)) BDVLRCONTAB,
        SUM(COALESCE(itens.BDBASEICMS,0)) BDBASEICMS,
        SUM(COALESCE(itens.BDBASEIPI,0)) BDBASEIPI,
        SUM(COALESCE(itens.BDBASEST,0)) BDBASEST,
        SUM(COALESCE(itens.BDISENTASICMS,0)) BDISENTASICMS,
        SUM(COALESCE(itens.BDISENTASIPI,0)) BDISENTASIPI,
        SUM(COALESCE(itens.BDOUTRASICMS,0)) BDOUTRASICMS,
        SUM(COALESCE(itens.BDOUTRASIPI,0)) BDOUTRASIPI,
        SUM(COALESCE(itens.BDVLRICMS,0)) BDVLRICMS,
        SUM(COALESCE(movpro.BDVLRIPI,0)) BDVLRIPI,
        SUM(COALESCE(itens.BDVLRST,0)) BDVLRST,
        SUM(COALESCE(itens.BDIMPEXCLUIDAS,0)) BDIMPEXCLUIDAS,
        SUM(COALESCE(itens.BDOUTROSIMP,0)) BDOUTROSIMP,
        SUM(COALESCE(itens.BDDESCONTO,0)) BDDESCONTO,
        SUM(COALESCE(itens.BDICMSFRETESAI,0)) BDICMSFRETESAI,
        SUM(COALESCE(itens.BDACRECFINSAI,0)) BDACRECFINSAI,
        SUM(COALESCE(movpro.bdvlritem,0)) BDVLRITEMPROD,
        SUM(COALESCE(movpro.bdvlrdespacessoria,0)) BDVLRDESPAACESSORIAPROD,
        SUM(COALESCE(movpro.bdvlricms,0)) BDVLRICMSPROD,
        SUM(COALESCE(movpro.bdvlrpis,0)) BDVLRPISPROD,
        SUM(COALESCE(movpro.bdvlrst,0)) BDVLRSTPROD,
        SUM(COALESCE(movpro.bdvlripi,0)) BDVLRIPIPROD,
        SUM(COALESCE(movpro.bdvlrcofins,0)) BDVLRCOFINSPROD,
        SUM(COALESCE(movpro.bdvlrissqn,0)) BDVLRISSQNPROD



FROM vef_emp_tmovprosai movpro
LEFT OUTER JOIN vef_emp_tmovsaiitens itens ON (itens.bdcodemp = movpro.bdcodemp AND itens.bdchave = movpro.bdchave AND itens.bdordem = movpro.bdordem)
LEFT OUTER JOIN vef_emp_tmovsai sai ON (sai.bdcodemp = movpro.bdcodemp AND sai.bdchave = movpro.bdchave)
LEFT OUTER JOIN tcadpro_vinc cadpro ON (cadpro.bdcodemp = movpro.bdcodemp AND cadpro.bdcodprod = movpro.bdcodprod)
LEFT OUTER JOIN tcadpro cadprounico ON (cadprounico.bdcodprod = cadpro.bdcodprod)
WHERE (SAI.bdcodsitnf NOT IN (2,3,4,5))
GROUP BY sai.bddataemissao,movpro.bdcodemp,movpro.bdcodprod,cadpro.BDCODSAIDA,cadprounico.bdcodigoean,cadpro.bdncmprod,cadpro.bddescprod,itens.bdcodnat,itens.bdprefixonat
ORDER BY movpro.bdcodemp, sai.bddataemissao, cadpro.bdncmprod
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_SAI_DATE_REGCX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_SAI_DATE_REGCX(
BDDATAEMISSAO,
BDCODEMP,
BDCODMATRIZ,
BDCODNAT,
BDPREFIXONAT,
BDVLRCONTAB,
BDBASEICMS,
BDVLRICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSFRETESAI,
BDACRECFINSAI)
 AS 
SELECT  SAI.BDDATAEMISSAO,
        itens.bdcodemp,
        COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,
        itens.bdcodnat,
        itens.BDPREFIXONAT,
        SUM(COALESCE(itens.bdvlrcontab,0)) bdvlrcontab,
        SUM(COALESCE(itens.bdbaseicms,0)) bdbaseicms,
        SUM(COALESCE(itens.bdvlricms,0)) bdvlricms,
        SUM(COALESCE(BDBASEIPI,0)) BDBASEIPI,
        SUM(COALESCE(BDBASEST,0)) BDBASEST,
        SUM(COALESCE(BDISENTASICMS,0)) BDISENTASICMS,
        SUM(COALESCE(BDISENTASIPI,0)) BDISENTASIPI,
        SUM(COALESCE(BDOUTRASICMS,0)) BDOUTRASICMS,
        SUM(COALESCE(BDOUTRASIPI,0)) BDOUTRASIPI,
        SUM(COALESCE(BDVLRIPI,0)) BDVLRIPI,
        SUM(COALESCE(BDVLRST,0)) BDVLRST,
        SUM(COALESCE(BDIMPEXCLUIDAS,0)) BDIMPEXCLUIDAS,
        SUM(COALESCE(BDOUTROSIMP,0)) BDOUTROSIMP,
        SUM(COALESCE(BDDESCONTO,0)) BDDESCONTO,
        SUM(COALESCE(BDICMSFRETESAI,0)) BDICMSFRETESAI,
        SUM(COALESCE(BDACRECFINSAI,0)) BDACRECFINSAI

FROM vef_emp_tmovsaiitens itens , vef_emp_tmovsai sai, TEMPRESAS E
WHERE ((itens.bdcodemp = sai.bdcodemp) AND (itens.bdchave = sai.bdchave))
AND (itens.bdcodemp = e.bdcodemp) AND (sai.bdcondpgto <> 1)
    AND (SAI.bdcodsitnf NOT IN (2,3,4,5))
GROUP BY SAI.BDDATAEMISSAO, itens.bdcodemp,e.bdcodmatriz,itens.bdcodnat, itens.bdprefixonat

UNION ALL

SELECT  SAI.bddataredz,
        SAI.bdcodemp,
        COALESCE(E.bdcodmatriz,sai.bdcodemp) bdcodmatriz,
        c.bdcodnat,
        CAST(SUBSTRING(CAST(c.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4) AS INTEGER) BDPREFIXONAT,
        SUM(COALESCE(C.bdvlrcontab,0)) bdvlrcontab,
        SUM(COALESCE(C.bdbaseicms,0)) bdbaseicms,
        SUM(COALESCE(C.bdvlricms,0)) bdvlricms,
        SUM(0) BDBASEIPI,
        SUM(0) BDBASEST,
        SUM(COALESCE(C.BDISENTASICMS,0)) BDISENTASICMS,
        SUM(0) BDISENTASIPI,
        SUM(COALESCE(C.BDOUTRASICMS,0)) BDOUTRASICMS,
        SUM(0) BDOUTRASIPI,
        SUM(0) BDVLRIPI,
        SUM(0) BDVLRST,
        SUM(0) BDIMPEXCLUIDAS,
        SUM(0) BDOUTROSIMP,
        SUM(0) BDDESCONTO,
        SUM(0) BDICMSFRETESAI,
        SUM(0) BDACRECFINSAI

FROM VEF_EMP_TREDZ SAI, VEF_EMP_TREDZVARCFOP c, VEF_BASE_TCADMAQMRC m, tempresas e
WHERE SAI.bdcodemp = c.bdcodemp AND SAI.bdchave = c.bdchave AND SAI.bdcodemp = m.bdcodemp AND SAI.bdordemmaq = m.bdordemmaq
AND (sai.bdcodemp = e.bdcodemp) AND (C.bdcondpgto <> 1)

GROUP BY SAI.bddataredz, SAI.bdcodemp,e.bdcodmatriz,c.bdcodnat, bdprefixonat
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_SAI_DATE_TERC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_SAI_DATE_TERC(
BDDATAEMISSAO,
BDCODTER,
BDCODEMP,
BDCODNAT,
BDPREFIXONAT,
BDVLRCONTAB,
BDBASEICMS,
BDVLRICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSFRETESAI,
BDACRECFINSAI)
 AS 
SELECT  SAI.BDDATAEMISSAO,
        SAI.bdcodter,
        itens.bdcodemp,
        itens.bdcodnat,
        itens.BDPREFIXONAT,
        SUM(COALESCE(itens.bdvlrcontab,0)) bdvlrcontab,
        SUM(COALESCE(itens.bdbaseicms,0)) bdbaseicms,
        SUM(COALESCE(itens.bdvlricms,0)) bdvlricms,
        SUM(COALESCE(BDBASEIPI,0)) BDBASEIPI,
        SUM(COALESCE(BDBASEST,0)) BDBASEST,
        SUM(COALESCE(BDISENTASICMS,0)) BDISENTASICMS,
        SUM(COALESCE(BDISENTASIPI,0)) BDISENTASIPI,
        SUM(COALESCE(BDOUTRASICMS,0)) BDOUTRASICMS,
        SUM(COALESCE(BDOUTRASIPI,0)) BDOUTRASIPI,
        SUM(COALESCE(BDVLRIPI,0)) BDVLRIPI,
        SUM(COALESCE(BDVLRST,0)) BDVLRST,
        SUM(COALESCE(BDIMPEXCLUIDAS,0)) BDIMPEXCLUIDAS,
        SUM(COALESCE(BDOUTROSIMP,0)) BDOUTROSIMP,
        SUM(COALESCE(BDDESCONTO,0)) BDDESCONTO,
        SUM(COALESCE(BDICMSFRETESAI,0)) BDICMSFRETESAI,
        SUM(COALESCE(BDACRECFINSAI,0)) BDACRECFINSAI

FROM vef_emp_tmovsaiitens itens , vef_emp_tmovsai sai
WHERE ((itens.bdcodemp = sai.bdcodemp) AND (itens.bdchave = sai.bdchave))
    AND (SAI.bdcodsitnf NOT IN (2,3,4,5))
GROUP BY SAI.BDDATAEMISSAO, SAI.bdcodter, itens.bdcodemp, itens.bdcodnat, itens.bdprefixonat
ORDER BY itens.bdcodemp,sai.bddataemissao, sai.bdcodter
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_SAI_REGCAIXA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_SAI_REGCAIXA(
BDREFLAN,
BDCODEMP,
BDCODMATRIZ,
BDCODNAT,
BDPREFIXONAT,
BDCODOPDAPI,
BDVLRCONTAB,
BDBASEICMS,
BDVLRICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSFRETESAI,
BDACRECFINSAI,
BDIMPSUBSTITUTO,
BDIMPSUBSTITUIDO,
BDVLRPIS,
BDVLRCOFINS)
 AS 
SELECT  SAI.BDREFLAN,
        itens.bdcodemp,
        COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,
        itens.bdcodnat,
        itens.BDPREFIXONAT,
        nat.BDCODOPDAPI,
        COALESCE(SUM(itens.bdvlrcontab),0) bdvlrcontab,
        COALESCE(SUM(itens.bdbaseicms),0) bdbaseicms,
        COALESCE(SUM(itens.bdvlricms),0) bdvlricms,
        COALESCE(SUM(BDBASEIPI),0) BDBASEIPI,
        COALESCE(SUM(BDBASEST),0) BDBASEST,
        COALESCE(SUM(BDISENTASICMS),0) BDISENTASICMS,
        COALESCE(SUM(BDISENTASIPI),0) BDISENTASIPI,
        COALESCE(SUM(BDOUTRASICMS),0) BDOUTRASICMS,
        COALESCE(SUM(BDOUTRASIPI),0) BDOUTRASIPI,
        COALESCE(SUM(BDVLRIPI),0) BDVLRIPI,
        COALESCE(SUM(BDVLRST),0) BDVLRST,
        COALESCE(SUM(BDIMPEXCLUIDAS),0) BDIMPEXCLUIDAS,
        COALESCE(SUM(BDOUTROSIMP),0) BDOUTROSIMP,
        COALESCE(SUM(BDDESCONTO),0) BDDESCONTO,
        COALESCE(SUM(BDICMSFRETESAI),0) BDICMSFRETESAI,
        COALESCE(SUM(BDACRECFINSAI),0) BDACRECFINSAI,
        COALESCE(SUM(r.bdimpsubstituto),0) bdimpsubstituto,
        COALESCE(SUM(r.bdimpsubstituido),0) bdimpsubstituido,
        COALESCE(SUM(itens.BDVLRPIS),0) BDVLRPIS,
        COALESCE(SUM(itens.BDVLRCOFINS),0) BDVLRCOFINS

FROM vef_emp_tmovsaiitens itens
JOIN TEMPRESAS E ON (itens.bdcodemp = e.bdcodemp)
JOIN vef_emp_tmovsai sai ON ((itens.bdcodemp = sai.bdcodemp) AND (itens.bdchave = sai.bdchave))
LEFT OUTER JOIN VEF_EMP_TMOVSAIIMPRETSP r ON (SAI.bdcodemp = r.bdcodemp AND SAI.bdchave = r.bdchave AND itens.bdordem = r.bdordem)
JOIN VEF_BASE_TNATOP nat ON (itens.bdcodnat = nat.bdcodnat) 
WHERE (SAI.bdcodsitnf NOT IN (2,3,4,5)) AND (SAI.bdcondpgto <> 1)
GROUP BY SAI.bdreflan, itens.bdcodemp, e.bdcodmatriz,itens.bdcodnat, itens.bdprefixonat,nat.BDCODOPDAPI

UNION ALL

SELECT  SAI.BDREFLAN,
        SAI.bdcodemp,
        COALESCE(E.bdcodmatriz,SAI.bdcodemp) bdcodmatriz,
        c.bdcodnat,
        CAST(SUBSTRING(CAST(c.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4) AS INTEGER) BDPREFIXONAT,
        nat.BDCODOPDAPI,
        COALESCE(SUM(C.bdvlrcontab),0) bdvlrcontab,
        COALESCE(SUM(C.bdbaseicms),0) bdbaseicms,
        COALESCE(SUM(C.bdvlricms),0) bdvlricms,
        SUM(0) BDBASEIPI,
        SUM(0) BDBASEST,
        COALESCE(SUM(C.BDISENTASICMS),0) BDISENTASICMS,
        SUM(0) BDISENTASIPI,
        COALESCE(SUM(C.BDOUTRASICMS),0) BDOUTRASICMS,
        SUM(0) BDOUTRASIPI,
        SUM(0) BDVLRIPI,
        SUM(0) BDVLRST,
        SUM(0) BDIMPEXCLUIDAS,
        SUM(0) BDOUTROSIMP,
        SUM(0) BDDESCONTO,
        SUM(0) BDICMSFRETESAI,
        SUM(0) BDACRECFINSAI,
        SUM(0) bdimpsubstituto,
        SUM(0) bdimpsubstituido,
        SUM(0) BDVLRPIS,
        SUM(0) BDVLRCOFINS

FROM VEF_EMP_TREDZ SAI
INNER JOIN VEF_EMP_TREDZVARCFOP c ON (SAI.bdcodemp = c.bdcodemp) AND (SAI.bdchave = c.bdchave)
INNER JOIN VEF_BASE_TCADMAQMRC m ON (SAI.bdcodemp = m.bdcodemp) AND (SAI.bdordemmaq = m.bdordemmaq)
INNER JOIN tempresas e ON (sai.bdcodemp = e.bdcodemp)
JOIN VEF_BASE_TNATOP nat ON (c.bdcodnat = nat.bdcodnat)
WHERE  (c.bdcondpgto <> 1) 
GROUP BY SAI.bdreflan, SAI.bdcodemp,e.bdcodmatriz,C.bdcodnat, bdprefixonat, nat.BDCODOPDAPI
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_SAI_UF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_SAI_UF(
BDREFLAN,
BDCODEMP,
BDCODMATRIZ,
BDCODNAT,
BDPREFIXONAT,
BDCODUF,
BDCODOPDAPI,
BDVLRCONTAB,
BDBASEICMS,
BDVLRICMS,
BDBASEIPI,
BDBASEST,
BDISENTASICMS,
BDISENTASIPI,
BDOUTRASICMS,
BDOUTRASIPI,
BDVLRIPI,
BDVLRST,
BDIMPEXCLUIDAS,
BDOUTROSIMP,
BDDESCONTO,
BDICMSFRETESAI,
BDACRECFINSAI,
BDIMPSUBSTITUTO,
BDIMPSUBSTITUIDO,
BDVLRPIS,
BDVLRCOFINS)
 AS 
SELECT  BDREFLAN,bdcodemp,bdcodmatriz,bdcodnat,BDPREFIXONAT,bdcoduf,BDCODOPDAPI,
        COALESCE(SUM(bdvlrcontab),0) bdvlrcontab,
        COALESCE(SUM(bdbaseicms),0) bdbaseicms,
        COALESCE(SUM(bdvlricms),0) bdvlricms,
        COALESCE(SUM(BDBASEIPI),0) BDBASEIPI,
        COALESCE(SUM(BDBASEST),0) BDBASEST,
        COALESCE(SUM(BDISENTASICMS),0) BDISENTASICMS,
        COALESCE(SUM(BDISENTASIPI),0) BDISENTASIPI,
        COALESCE(SUM(BDOUTRASICMS),0) BDOUTRASICMS,
        COALESCE(SUM(BDOUTRASIPI),0) BDOUTRASIPI,
        COALESCE(SUM(BDVLRIPI),0) BDVLRIPI,
        COALESCE(SUM(BDVLRST),0) BDVLRST,
        COALESCE(SUM(BDIMPEXCLUIDAS),0) BDIMPEXCLUIDAS,
        COALESCE(SUM(BDOUTROSIMP),0) BDOUTROSIMP,
        COALESCE(SUM(BDDESCONTO),0) BDDESCONTO,
        COALESCE(SUM(BDICMSFRETESAI),0) BDICMSFRETESAI,
        COALESCE(SUM(BDACRECFINSAI),0) BDACRECFINSAI,
        COALESCE(SUM(bdimpsubstituto),0) bdimpsubstituto,
        COALESCE(SUM(bdimpsubstituido),0) bdimpsubstituido,
        COALESCE(SUM(BDVLRPIS),0) BDVLRPIS,
        COALESCE(SUM(BDVLRCOFINS),0) BDVLRCOFINS
FROM (
    SELECT  SAI.BDREFLAN,itens.bdcodemp,COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,itens.bdcodnat,itens.BDPREFIXONAT,cid.bdcoduf,nat.BDCODOPDAPI,SUM(itens.bdvlrcontab) bdvlrcontab,SUM(itens.bdbaseicms) bdbaseicms,
            SUM(itens.bdvlricms) bdvlricms,SUM(BDBASEIPI) BDBASEIPI,SUM(BDBASEST) BDBASEST,SUM(BDISENTASICMS) BDISENTASICMS,SUM(BDISENTASIPI) BDISENTASIPI,
            SUM(BDOUTRASICMS) BDOUTRASICMS,SUM(BDOUTRASIPI) BDOUTRASIPI,SUM(BDVLRIPI) BDVLRIPI,SUM(BDVLRST) BDVLRST,SUM(BDIMPEXCLUIDAS) BDIMPEXCLUIDAS,
            SUM(BDOUTROSIMP) BDOUTROSIMP,SUM(BDDESCONTO) BDDESCONTO,SUM(BDICMSFRETESAI) BDICMSFRETESAI,SUM(BDACRECFINSAI) BDACRECFINSAI,
            SUM(r.bdimpsubstituto) bdimpsubstituto,SUM(r.bdimpsubstituido) bdimpsubstituido,SUM(itens.BDVLRPIS) BDVLRPIS,SUM(itens.BDVLRCOFINS) BDVLRCOFINS
    FROM vef_emp_tmovsaiitens itens
    JOIN tempresas e ON (itens.bdcodemp = e.bdcodemp)
    JOIN vef_emp_tmovsai sai ON ((itens.bdcodemp = sai.bdcodemp) AND (itens.bdchave = sai.bdchave))
    LEFT OUTER JOIN VEF_EMP_TMOVSAIIMPRETSP r ON (SAI.bdcodemp = r.bdcodemp AND SAI.bdchave = r.bdchave AND itens.bdordem = r.bdordem)
    LEFT OUTER JOIN vw_tterceiro ter ON (sai.bdcodter = ter.bdcodter)
    LEFT OUTER JOIN tcidade cid ON (SAI.bdcodcid = cid.bdcodcid)
    JOIN VEF_BASE_TNATOP nat ON (itens.bdcodnat = nat.bdcodnat) 
    WHERE SAI.bdcodsitnf NOT IN (2,3,4,5)
    GROUP BY SAI.bdreflan, itens.bdcodemp,e.bdcodmatriz,itens.bdcodnat, itens.bdprefixonat, cid.bdcoduf,nat.BDCODOPDAPI

) s
GROUP BY bdreflan, bdcodemp,bdcodmatriz,bdcodnat,bdprefixonat,bdcoduf,BDCODOPDAPI
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_SER (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_SER(
BDREFLAN,
BDCODEMP,
BDCODMATRIZ,
BDCODNAT,
BDPREFIXONAT,
BDTIPLAN,
BDCODOPDAPI,
BDVLRCONTAB,
BDDESCONTO,
BDBCISSSER,
BDVLRISSSER,
BDISENTASISSSER,
BDOUTRASISSSER,
BDBCIRSER,
BDVLRIRSER,
BDACREDEDUIRSER,
BDACRECFINSER,
BDVLRPIS,
BDVLRCOFINS)
 AS 
SELECT  MOV.BDREFLAN,
        itens.bdcodemp,
        COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,
        itens.bdcodnat,
        itens.BDPREFIXONAT,
        MOV.bdtiplan,
        nat.BDCODOPDAPI,
        COALESCE(SUM(itens.BDVLRCONTAB),0) BDVLRCONTAB,
        COALESCE(SUM(itens.BDDESCONTO),0) BDDESCONTO,
        COALESCE(SUM(itens.BDBCISSSER),0) BDBCISSSER ,
        COALESCE(SUM(itens.BDVLRISSSER),0) BDVLRISSSER ,
        COALESCE(SUM(itens.BDISENTASISSSER),0) BDISENTASISSSER  ,
        COALESCE(SUM(itens.BDOUTRASISSSER),0) BDOUTRASISSSER   ,
        COALESCE(SUM(itens.BDBCIRSER),0) BDBCIRSER ,
        COALESCE(SUM(itens.BDVLRIRSER),0) BDVLRIRSER,
        COALESCE(SUM(itens.BDACREDEDUIRSER),0) BDACREDEDUIRSER ,
        COALESCE(SUM(itens.BDACRECFINSER),0) BDACRECFINSER,
        COALESCE(SUM(itens.BDVLRPIS),0) BDVLRPIS,
        COALESCE(SUM(itens.BDVLRCOFINS),0) BDVLRCOFINS

FROM vef_emp_tmovseritens itens 
INNER JOIN vef_emp_tmovser MOV ON ((itens.bdcodemp = MOV.bdcodemp) AND (itens.bdchave = MOV.bdchave))
INNER JOIN tempresas e on (itens.bdcodemp = e.bdcodemp)
JOIN VEF_BASE_TNATOP nat ON (itens.bdcodnat = nat.bdcodnat) 
WHERE (MOV.bdcodsitnf NOT IN (2,3,4,5))
GROUP BY MOV.bdreflan, itens.bdcodemp,e.bdcodmatriz,itens.bdcodnat, itens.bdprefixonat, MOV.bdtiplan,nat.BDCODOPDAPI
ORDER BY itens.bdcodemp,mov.bdreflan
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_SER_ATVM (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_SER_ATVM(
BDREFLAN,
BDCODEMP,
BDCODMATRIZ,
BDCODMUNATVM,
BDTIPLAN,
BDVLRCONTAB,
BDDESCONTO,
BDBCISSSER,
BDVLRISSSER,
BDISENTASISSSER,
BDOUTRASISSSER,
BDBCIRSER,
BDVLRIRSER,
BDACREDEDUIRSER,
BDACRECFINSER,
BDVLRPIS,
BDVLRCOFINS)
 AS 
SELECT  MOV.BDREFLAN,
        itens.bdcodemp,
        COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,
        atvm.BDCODMUNATVM,
        MOV.bdtiplan,
        COALESCE(SUM(itens.BDVLRCONTAB),0) BDVLRCONTAB,
        COALESCE(SUM(mov.BDDESCONTONOTA),0) AS BDDESCONTO,
        COALESCE(SUM(itens.BDBCISSSER),0) BDBCISSSER ,
        COALESCE(SUM(itens.BDVLRISSSER),0) BDVLRISSSER ,
        COALESCE(SUM(itens.BDISENTASISSSER),0) BDISENTASISSSER  ,
        COALESCE(SUM(itens.BDOUTRASISSSER),0) BDOUTRASISSSER   ,
        COALESCE(SUM(itens.BDBCIRSER),0) BDBCIRSER ,
        COALESCE(SUM(itens.BDVLRIRSER),0) BDVLRIRSER,
        COALESCE(SUM(itens.BDACREDEDUIRSER),0) BDACREDEDUIRSER ,
        COALESCE(SUM(itens.BDACRECFINSER),0) BDACRECFINSER,
        COALESCE(SUM(itens.BDVLRPIS),0) BDVLRPIS,
        COALESCE(SUM(itens.BDVLRCOFINS),0) BDVLRCOFINS
FROM vef_emp_tmovseritens itens 
INNER JOIN vef_emp_tmovser MOV ON ((itens.bdcodemp = MOV.bdcodemp) AND (itens.bdchave = MOV.bdchave))
INNER JOIN tempresas e ON (itens.bdcodemp = e.bdcodemp)
JOIN TATVMUNICIPAL atvm ON (itens.bdcodatvm = atvm.bdcodatvm)
WHERE (MOV.bdcodsitnf NOT IN (2,3,4,5))
GROUP BY MOV.bdreflan, itens.bdcodemp,e.bdcodmatriz, atvm.BDCODMUNATVM, MOV.bdtiplan
ORDER BY itens.bdcodemp,mov.bdreflan
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_SER_ATVM_REGCX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_SER_ATVM_REGCX(
BDREFLAN,
BDCODEMP,
BDCODMATRIZ,
BDCODMUNATVM,
BDTIPLAN,
BDVLRCONTAB,
BDDESCONTO,
BDBCISSSER,
BDVLRISSSER,
BDISENTASISSSER,
BDOUTRASISSSER,
BDBCIRSER,
BDVLRIRSER,
BDACREDEDUIRSER,
BDACRECFINSER,
BDVLRPIS,
BDVLRCOFINS)
 AS 
SELECT  MOV.BDREFLAN,
        itens.bdcodemp,
        COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,
        atvm.BDCODMUNATVM,
        MOV.bdtiplan,
        COALESCE(SUM(itens.BDVLRCONTAB),0) BDVLRCONTAB,
        COALESCE(SUM(mov.BDDESCONTONOTA),0) AS BDDESCONTO,
        COALESCE(SUM(itens.BDBCISSSER),0) BDBCISSSER ,
        COALESCE(SUM(itens.BDVLRISSSER),0) BDVLRISSSER ,
        COALESCE(SUM(itens.BDISENTASISSSER),0) BDISENTASISSSER  ,
        COALESCE(SUM(itens.BDOUTRASISSSER),0) BDOUTRASISSSER   ,
        COALESCE(SUM(itens.BDBCIRSER),0) BDBCIRSER ,
        COALESCE(SUM(itens.BDVLRIRSER),0) BDVLRIRSER,
        COALESCE(SUM(itens.BDACREDEDUIRSER),0) BDACREDEDUIRSER ,
        COALESCE(SUM(itens.BDACRECFINSER),0) BDACRECFINSER,
        COALESCE(SUM(itens.BDVLRPIS),0) BDVLRPIS,
        COALESCE(SUM(itens.BDVLRCOFINS),0) BDVLRCOFINS
FROM vef_emp_tmovseritens itens  
INNER JOIN vef_emp_tmovser MOV ON ((itens.bdcodemp = MOV.bdcodemp) AND (itens.bdchave = MOV.bdchave)) 
INNER JOIN tempresas e ON (itens.bdcodemp = e.bdcodemp)
JOIN TATVMUNICIPAL atvm ON (itens.bdcodatvm = atvm.bdcodatvm)
WHERE (MOV.bdcodsitnf NOT IN (2,3,4,5)) AND (MOV.bdcondpgto <> 1)
GROUP BY MOV.bdreflan, itens.bdcodemp,e.bdcodmatriz, atvm.BDCODMUNATVM, MOV.bdtiplan
ORDER BY itens.bdcodemp,mov.bdreflan
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_SER_DATE (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_SER_DATE(
BDDATAEMISSAO,
BDCODEMP,
BDCODMATRIZ,
BDCODNAT,
BDPREFIXONAT,
BDTIPLAN,
BDVLRCONTAB,
BDDESCONTO,
BDBCISSSER,
BDVLRISSSER,
BDISENTASISSSER,
BDOUTRASISSSER,
BDBCIRSER,
BDVLRIRSER,
BDACREDEDUIRSER,
BDACRECFINSER)
 AS 
SELECT  MOV.bddataemissao,
        itens.bdcodemp,
        COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,
        itens.bdcodnat,
        itens.BDPREFIXONAT,
        MOV.bdtiplan,
        SUM(COALESCE(itens.BDVLRCONTAB,0)) BDVLRCONTAB,
        SUM(COALESCE(itens.BDDESCONTO,0)) BDDESCONTO,
        SUM(COALESCE(itens.BDBCISSSER,0)) BDBCISSSER ,
        SUM(COALESCE(itens.BDVLRISSSER,0)) BDVLRISSSER ,
        SUM(COALESCE(itens.BDISENTASISSSER,0)) BDISENTASISSSER  ,
        SUM(COALESCE(itens.BDOUTRASISSSER,0)) BDOUTRASISSSER   ,
        SUM(COALESCE(itens.BDBCIRSER,0)) BDBCIRSER ,
        SUM(COALESCE(itens.BDVLRIRSER,0)) BDVLRIRSER,
        SUM(COALESCE(itens.BDACREDEDUIRSER,0)) BDACREDEDUIRSER ,
        SUM(COALESCE(itens.BDACRECFINSER,0)) BDACRECFINSER

FROM vef_emp_tmovseritens itens , vef_emp_tmovser MOV, TEMPRESAS E
WHERE ((itens.bdcodemp = MOV.bdcodemp) AND (itens.bdchave = MOV.bdchave))
AND (itens.bdcodemp = e.bdcodemp)
    AND (MOV.bdcodsitnf NOT IN (2,3,4,5))
GROUP BY MOV.bddataemissao, itens.bdcodemp,e.bdcodmatriz,itens.bdcodnat, itens.bdprefixonat, MOV.bdtiplan
ORDER BY itens.bdcodemp,mov.bddataemissao
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_SER_DATE_REGCX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_SER_DATE_REGCX(
BDDATAEMISSAO,
BDCODEMP,
BDCODMATRIZ,
BDCODNAT,
BDPREFIXONAT,
BDTIPLAN,
BDVLRCONTAB,
BDDESCONTO,
BDBCISSSER,
BDVLRISSSER,
BDISENTASISSSER,
BDOUTRASISSSER,
BDBCIRSER,
BDVLRIRSER,
BDACREDEDUIRSER,
BDACRECFINSER)
 AS 
SELECT  MOV.bddataemissao,
        itens.bdcodemp,
        COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,
        itens.bdcodnat,
        itens.BDPREFIXONAT,
        MOV.bdtiplan,
        SUM(COALESCE(itens.BDVLRCONTAB,0)) BDVLRCONTAB,
        SUM(COALESCE(itens.BDDESCONTO,0)) BDDESCONTO,
        SUM(COALESCE(itens.BDBCISSSER,0)) BDBCISSSER ,
        SUM(COALESCE(itens.BDVLRISSSER,0)) BDVLRISSSER ,
        SUM(COALESCE(itens.BDISENTASISSSER,0)) BDISENTASISSSER  ,
        SUM(COALESCE(itens.BDOUTRASISSSER,0)) BDOUTRASISSSER   ,
        SUM(COALESCE(itens.BDBCIRSER,0)) BDBCIRSER ,
        SUM(COALESCE(itens.BDVLRIRSER,0)) BDVLRIRSER,
        SUM(COALESCE(itens.BDACREDEDUIRSER,0)) BDACREDEDUIRSER ,
        SUM(COALESCE(itens.BDACRECFINSER,0)) BDACRECFINSER

FROM vef_emp_tmovseritens itens , vef_emp_tmovser MOV, TEMPRESAS E
WHERE ((itens.bdcodemp = MOV.bdcodemp) AND (itens.bdchave = MOV.bdchave))
AND (itens.bdcodemp = e.bdcodemp) AND (MOV.bdcondpgto <> 1)
    AND (MOV.bdcodsitnf NOT IN (2,3,4,5))
GROUP BY MOV.bddataemissao, itens.bdcodemp,e.bdcodmatriz,itens.bdcodnat, itens.bdprefixonat, MOV.bdtiplan
ORDER BY itens.bdcodemp,mov.bddataemissao
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_NAT_SER_REGCAIXA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_NAT_SER_REGCAIXA(
BDREFLAN,
BDCODEMP,
BDCODMATRIZ,
BDCODNAT,
BDPREFIXONAT,
BDTIPLAN,
BDCODOPDAPI,
BDVLRCONTAB,
BDDESCONTO,
BDBCISSSER,
BDVLRISSSER,
BDISENTASISSSER,
BDOUTRASISSSER,
BDBCIRSER,
BDVLRIRSER,
BDACREDEDUIRSER,
BDACRECFINSER,
BDVLRPIS,
BDVLRCOFINS)
 AS 
SELECT  MOV.BDREFLAN,
        itens.bdcodemp,
        COALESCE(E.bdcodmatriz,ITENS.bdcodemp) bdcodmatriz,
        itens.bdcodnat,
        itens.BDPREFIXONAT,
        MOV.bdtiplan,
        nat.BDCODOPDAPI,
        COALESCE(SUM(itens.BDVLRCONTAB),0) BDVLRCONTAB,
        COALESCE(SUM(itens.BDDESCONTO),0) BDDESCONTO,
        COALESCE(SUM(itens.BDBCISSSER),0) BDBCISSSER ,
        COALESCE(SUM(itens.BDVLRISSSER),0) BDVLRISSSER ,
        COALESCE(SUM(itens.BDISENTASISSSER),0) BDISENTASISSSER  ,
        COALESCE(SUM(itens.BDOUTRASISSSER),0) BDOUTRASISSSER   ,
        COALESCE(SUM(itens.BDBCIRSER),0) BDBCIRSER ,
        COALESCE(SUM(itens.BDVLRIRSER),0) BDVLRIRSER,
        COALESCE(SUM(itens.BDACREDEDUIRSER),0) BDACREDEDUIRSER ,
        COALESCE(SUM(itens.BDACRECFINSER),0) BDACRECFINSER,
        COALESCE(SUM(itens.BDVLRPIS),0) BDVLRPIS,
        COALESCE(SUM(itens.BDVLRCOFINS),0) BDVLRCOFINS

FROM vef_emp_tmovseritens itens 
INNER JOIN vef_emp_tmovser MOV ON ((itens.bdcodemp = MOV.bdcodemp) AND (itens.bdchave = MOV.bdchave))
INNER JOIN TEMPRESAS E ON (ITENS.BDCODEMP = E.BDCODEMP)
JOIN VEF_BASE_TNATOP nat ON (itens.bdcodnat = nat.bdcodnat) 
WHERE (MOV.bdcodsitnf NOT IN (2,3,4,5)) AND (MOV.bdcondpgto <> 1)
GROUP BY MOV.bdreflan, itens.bdcodemp,E.BDCODMATRIZ,itens.bdcodnat, itens.bdprefixonat, MOV.bdtiplan,nat.BDCODOPDAPI
ORDER BY itens.bdcodemp,mov.bdreflan
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_UF_ENT (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_UF_ENT(
BDCODEMP,
BDREFLAN,
BDCODUF,
BDSIGLAUF,
BDCODNAT,
BDPREFIXONAT,
BDTIPORETENT,
BDVLRCONTAB,
BDBASEICMS,
BDOUTRASICMS,
BDICMSRETENT)
 AS 
SELECT ENT.BDCODEMP,
       ENT.BDREFLAN,
       CID.BDCODUF,
       UF.BDSIGLAUF,
       ITENS.BDCODNAT,
       ITENS.BDPREFIXONAT,
       ITENS.BDTIPORETENT,
       SUM(COALESCE(ITENS.BDVLRCONTAB, 0)) BDVLRCONTAB,
       SUM(COALESCE(ITENS.BDBASEICMS, 0)) BDBASEICMS,
       SUM(COALESCE(ITENS.BDOUTRASICMS, 0)) + SUM(COALESCE(ITENS.BDISENTASICMS, 0)) BDOUTRASICMS,
       SUM(COALESCE(ITENS.BDICMSRETENT, 0)) BDICMSRETENT 
FROM VEF_EMP_TMOVENT ENT 
LEFT OUTER JOIN VEF_EMP_TMOVENTITENS ITENS ON ENT.BDCODEMP = ITENS.BDCODEMP AND ENT.BDCHAVE = ITENS.BDCHAVE 
LEFT OUTER JOIN VW_TTERCEIRO TER ON ENT.BDCODTER = TER.BDCODTER 
LEFT OUTER JOIN TCIDADE CID ON TER.BDCODCID = CID.BDCODCID 
LEFT OUTER JOIN TUF UF ON CID.BDCODUF = UF.BDCODUF 
WHERE ENT.bdcodsitnf NOT IN (2,3,4,5)

GROUP BY ENT.BDCODEMP, ENT.BDREFLAN, CID.BDCODUF, UF.BDSIGLAUF, ITENS.BDCODNAT, ITENS.BDPREFIXONAT, ITENS.BDTIPORETENT 
ORDER BY ENT.BDCODEMP, ENT.BDREFLAN, CID.BDCODUF, ITENS.BDCODNAT, ITENS.BDPREFIXONAT, ITENS.BDTIPORETENT
;

/* CREATE OR ALTER VIEW: VW_VEF_TOT_UF_SAI (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOT_UF_SAI(
BDCODEMP,
BDREFLAN,
BDCODUF,
BDSIGLAUF,
BDCODNAT,
BDPREFIXONAT,
BDIETER,
BDVLRCONTAB,
BDBASEICMS,
BDOUTRASICMS,
BDICMSRETSAI)
 AS 
SELECT SAI.BDCODEMP,
       SAI.BDREFLAN,
       CID.BDCODUF,
       UF.BDSIGLAUF,
       ITENS.BDCODNAT,
       ITENS.BDPREFIXONAT,
       TER.BDIETER,
       SUM(COALESCE(ITENS.BDVLRCONTAB, 0)) BDVLRCONTAB,
       SUM(COALESCE(ITENS.BDBASEICMS, 0)) BDBASEICMS,
       SUM(COALESCE(ITENS.BDOUTRASICMS, 0)) + SUM(COALESCE(ITENS.BDISENTASICMS, 0)) BDOUTRASICMS,
       SUM(COALESCE(ITENS.BDVLRST, 0)) BDVLRST 
FROM VEF_EMP_TMOVSAI SAI 
LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS ITENS ON SAI.BDCODEMP = ITENS.BDCODEMP AND SAI.BDCHAVE = ITENS.BDCHAVE 
LEFT OUTER JOIN VW_TTERCEIRO TER ON SAI.BDCODTER = TER.BDCODTER 
LEFT OUTER JOIN TCIDADE CID ON SAI.BDCODCID = CID.BDCODCID 
LEFT OUTER JOIN TUF UF ON CID.BDCODUF = UF.BDCODUF 
WHERE SAI.bdcodsitnf NOT IN (2,3,4,5)

GROUP BY SAI.BDCODEMP, SAI.BDREFLAN, CID.BDCODUF, UF.BDSIGLAUF, ITENS.BDCODNAT, ITENS.BDPREFIXONAT, TER.BDIETER 
ORDER BY SAI.BDCODEMP, SAI.BDREFLAN, CID.BDCODUF, ITENS.BDCODNAT, ITENS.BDPREFIXONAT
;

/* CREATE OR ALTER VIEW: VW_VEF_TOTEXP_UF_ENT_GIASP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOTEXP_UF_ENT_GIASP(
BDCODEMP,
BDREFERENCIA,
BDSIGLAUF,
BDCODNAT,
BDTIPORETENT,
BDDIGOPERNAT,
BDPREFIXONAT,
BDVLRCONTAB,
BDBASEICMS,
BDVLRICMS,
BDOUTRASICMS,
BDVLRST,
BDICMSRET,
BDOUTROSIMPOSTOS,
BDIMPSUBSTITUTO,
BDIMPSUBSTITUIDO)
 AS 
SELECT  itens.bdcodemp,
        ENT.bdreflan,
        uf.bdsiglauf,
        itens.bdcodnat,
        itens.bdtiporetent,
        itens.BDDIGOPERNAT,
        itens.bdprefixonat,
        SUM(COALESCE(itens.bdvlrcontab,0)) BDVLRCONTAB,
        SUM(COALESCE(itens.BDBASEICMS,0)) BDBASEICMS,
        SUM(COALESCE(itens.bdvlricms,0)) bdvlricms,
        SUM(COALESCE(itens.BDOUTRASICMS,0)) BDOUTRASICMS,
        SUM(COALESCE(itens.bdvlrst,0)) BDVLRST,
        SUM(COALESCE(itens.bdicmsretent,0)) bdicmsret,
        SUM(0) BDOUTROSIMPOSTOS,
        SUM(COALESCE(impret.bdimpsubstituto,0)) bdimpsusbstituto,
        SUM(COALESCE(impret.bdimpsubstituido,0)) bdimpsusbstituido

FROM vef_emp_tmoventitens itens

LEFT OUTER JOIN VEF_EMP_TMOVENTIMPRETSP impret ON (impret.bdcodemp = itens.bdcodemp AND impret.bdchave = itens.bdchave AND impret.bdordem = itens.bdordem)
LEFT OUTER JOIN vef_emp_tmovent ent ON (ent.bdcodemp = itens.bdcodemp AND ent.bdchave = itens.bdchave)
LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.bdcodter = ent.bdcodter)
LEFT OUTER JOIN tcidade cidade ON (cidade.bdcodcid = ter.bdcodcid)
LEFT OUTER JOIN TUF uf ON (uf.bdcoduf = cidade.bdcoduf)
LEFT OUTER JOIN VEF_BASE_TNATOP tnat ON (tnat.bdcodnat = itens.bdcodnat)

WHERE ent.bdcodsitnf NOT IN (2,3,4,5)
   -- Sol.19711 Gabriel Ariel (04/09/17) - Não estava gerando R14 em notas complementares pois apenas buscava registros com valor contábil maior que 0
  --AND itens.BDVLRCONTAB > 0

GROUP BY itens.bdcodemp, ent.bdreflan, cidade.bdcoduf, uf.bdsiglauf,itens.bdcodnat, itens.BDDIGOPERNAT, itens.bdprefixonat,itens.bdtiporetent
ORDER BY itens.bdcodemp, ent.bdreflan, cidade.bdcoduf, itens.bdcodnat,itens.BDDIGOPERNAT, itens.bdprefixonat
;

/* CREATE OR ALTER VIEW: VW_VEF_TOTEXP_UF_SAI_GIASP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOTEXP_UF_SAI_GIASP(
    BDCODEMP,
    BDREFERENCIA,
    BDSIGLAUF,
    BDCODNAT,
    BDTIPORETENT,
    BDDIGOPERNAT,
    BDPREFIXONAT,
    BDVLRCONTAB,
    BDBASEICMS,
    BDVLRICMS,
    BDOUTRASICMS,
    BDVLRST,
    BDICMSRET,
    BDOUTROSIMPOSTOS,
    BDVLRCONT1,
    BDBASEICMS1,
    BDVLRCONT2,
    BDBASEICMS2,
    BDIMPSUBSTITUTO,
    BDIMPSUBSTITUIDO)
AS
SELECT  itens.bdcodemp,
        SAI.bdreflan,
        uf.bdsiglauf,
        itens.bdcodnat,
        NULL bdtiporetent,
        itens.BDDIGOPERNAT,
        itens.bdprefixonat,
        SUM(COALESCE(itens.bdvlrcontab,0)) BDVLRCONTAB,
        SUM(COALESCE(itens.BDBASEICMS,0)) BDBASEICMS,
        SUM(COALESCE(itens.bdvlricms,0)) bdvlricms,
        SUM(COALESCE(itens.BDOUTRASICMS,0)) BDOUTRASICMS,
        SUM(COALESCE(itens.bdvlrst,0)) BDVLRST,
        SUM(0) bdicmsret,
        SUM(0) BDOUTROSIMPOSTOS,
        SUM(0) BDVLRCONT1,
        SUM(0) BDBASEICMS1,
        SUM(COALESCE(itens.bdvlrcontab,0)) BDVLRCONT2,
        SUM(COALESCE(itens.BDBASEICMS,0)) BDBASEICMS2,
        SUM(COALESCE(impret.bdIMPSUBSTITUTO,0)) BDIMPSUBSTITUTO,
        SUM(COALESCE(impret.bdIMPSUBSTITUIDO,0)) BDIMPSUBSTITUIDO


FROM vef_emp_tmovSAIitens itens

LEFT OUTER JOIN VEF_EMP_TMOVSAIIMPRETSP impret ON (impret.bdcodemp = itens.bdcodemp AND impret.bdchave = itens.bdchave AND impret.bdordem = itens.bdordem)
LEFT OUTER JOIN vef_emp_tmovSAI SAI ON (SAI.bdcodemp = itens.bdcodemp AND SAI.bdchave = itens.bdchave)
LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.bdcodter = SAI.bdcodter)
LEFT OUTER JOIN tcidade cidade ON (cidade.bdcodcid = ter.bdcodcid)
LEFT OUTER JOIN TUF uf ON (uf.bdcoduf = cidade.bdcoduf)
LEFT OUTER JOIN VEF_BASE_TNATOP tnat ON (tnat.bdcodnat = itens.bdcodnat)

WHERE ((ter.bdieter IS NULL) OR (ter.bdieter = '') OR (UPPER(ter.bdieter) = 'ISENTO'))

  AND sai.bdcodsitnf NOT IN (2,3,4,5)
  AND itens.BDVLRCONTAB > 0

GROUP BY itens.bdcodemp, SAI.bdreflan, cidade.bdcoduf, uf.bdsiglauf,itens.bdcodnat, itens.BDDIGOPERNAT, itens.bdprefixonat,bdtiporetENT

UNION

SELECT  itens.bdcodemp,
        SAI.bdreflan,
        uf.bdsiglauf,
        itens.bdcodnat,
        NULL bdtiporetent,
        itens.BDDIGOPERNAT,
        itens.bdprefixonat,
        SUM(itens.bdvlrcontab) BDVLRCONTAB,
        SUM(itens.BDBASEICMS) BDBASEICMS,
        SUM(itens.bdvlricms) bdvlricms,
        SUM(itens.BDOUTRASICMS) BDOUTRASICMS,
        SUM(itens.bdvlrst) BDVLRST,
        SUM(0) bdicmsret,
        SUM(0) BDOUTROSIMPOSTOS,
        SUM(itens.bdvlrcontab) BDVLRCONT1,
        SUM(itens.BDBASEICMS) BDBASEICMS1,
        SUM(0) BDVLRCONT2,
        SUM(0) BDBASEICMS2,
        SUM(impret.bdIMPSUBSTITUTO) BDIMPSUBSTITUTO,
        SUM(impret.bdIMPSUBSTITUIDO) BDIMPSUBSTITUIDO

FROM vef_emp_tmovSAIitens itens

LEFT OUTER JOIN VEF_EMP_TMOVSAIIMPRETSP impret ON (impret.bdcodemp = itens.bdcodemp AND impret.bdchave = itens.bdchave AND impret.bdordem = itens.bdordem)
LEFT OUTER JOIN vef_emp_tmovSAI SAI ON (SAI.bdcodemp = itens.bdcodemp AND SAI.bdchave = itens.bdchave)
LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.bdcodter = SAI.bdcodter)
LEFT OUTER JOIN tcidade cidade ON (cidade.bdcodcid = ter.bdcodcid)
LEFT OUTER JOIN TUF uf ON (uf.bdcoduf = cidade.bdcoduf)
LEFT OUTER JOIN VEF_BASE_TNATOP tnat ON (tnat.bdcodnat = itens.bdcodnat)

WHERE ((ter.bdieter IS NOT NULL) AND (ter.bdieter <> '') AND (UPPER(ter.bdieter) <> 'ISENTO'))

  AND sai.bdcodsitnf NOT IN (2,3,4,5)
  AND itens.BDVLRCONTAB > 0

GROUP BY itens.bdcodemp, SAI.bdreflan, cidade.bdcoduf, uf.bdsiglauf,itens.bdcodnat, itens.BDDIGOPERNAT, itens.bdprefixonat,bdtiporetENT
;

/* CREATE OR ALTER VIEW: VW_VEF_TOTEXP_UF_GIASP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VEF_TOTEXP_UF_GIASP(
BDCODEMP,
BDREFERENCIA,
BDSIGLAUF,
BDCODNAT,
BDTIPORETENT,
BDDIGOPERNAT,
BDPREFIXONAT,
BDVLRCONTAB,
BDBASEICMS,
BDVLRICMS,
BDOUTRASICMS,
BDVLRST,
BDICMSRET,
BDOUTROSIMPOSTOS,
BDVLRCONT1,
BDBASEICMS1,
BDVLRCONT2,
BDBASEICMS2,
BDIMPSUBSTITUTO,
BDIMPSUBSTITUIDO)
 AS 
SELECT sai.BDCODEMP,
       sai.BDREFERENCIA,
       sai.BDSIGLAUF,
       sai.BDCODNAT,
       sai.BDTIPORETENT,
       sai.BDDIGOPERNAT,
       sai.BDPREFIXONAT,
       SUM(COALESCE(sai.BDVLRCONTAB,0)) BDVLRCONTAB,
       SUM(COALESCE(sai.BDBASEICMS,0)) BDBASEICMS,
       SUM(COALESCE(sai.BDVLRICMS,0)) BDVLRICMS,
       SUM(COALESCE(sai.BDOUTRASICMS,0)) BDOUTRASICMS,
       SUM(COALESCE(sai.BDVLRST,0)) BDVLRST,
       SUM(COALESCE(sai.BDICMSRET,0)) BDICMSRET,
       SUM(COALESCE(sai.BDOUTROSIMPOSTOS,0)) BDOUTROSIMPOSTOS,
       SUM(COALESCE(sai.BDVLRCONT1,0)) BDVLRCONT1,
       SUM(COALESCE(sai.BDBASEICMS1,0)) BDBASEICMS1,
       SUM(COALESCE(sai.BDVLRCONT2,0)) BDVLRCONT2,
       SUM(COALESCE(sai.BDBASEICMS2,0)) BDBASEICMS2,
       SUM(COALESCE(sai.bdimpsubstituto,0)) bdimpsubstituto,
       SUM(COALESCE(sai.bdimpsubstituido,0)) bdimpsubstituido

FROM VW_VEF_TOTEXP_UF_SAI_GIASP sai

GROUP BY sai.BDCODEMP, sai.BDREFERENCIA, sai.BDSIGLAUF, sai.BDCODNAT, sai.BDDIGOPERNAT, sai.BDPREFIXONAT, sai.BDTIPORETENT
ORDER BY sai.BDCODEMP, sai.BDREFERENCIA, sai.BDCODNAT, sai.BDDIGOPERNAT, sai.BDPREFIXONAT
;

/* CREATE OR ALTER VIEW: VW_VERBAS_NAO_CUSTO_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBAS_NAO_CUSTO_ATUAL(
BDCODCENTRO,
BDCODTPCC,
BDCODVER,
BDDATAINI,
BDDATAFIM,
BDDIAINI,
BDMESINI,
BDANOINI,
BDDIAFIM,
BDMESFIM,
BDANOFIM,
BDDESCCOND,
BDFERIASVN,
BD13VN)
 AS 
SELECT BDCODCENTRO,
         BDCODTPCC,
         BDCODVER,
         CASE WHEN ((BDANOINIVNCUSTO = 0) OR (BDANOINIVNCUSTO IS NULL)) AND (BDMESINIVNCUSTO > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOINIVNCUSTO = 0) OR (BDANOINIVNCUSTO IS NULL) THEN
                '0000'
              WHEN (BDANOINIVNCUSTO > 0) THEN
                CAST(BDANOINIVNCUSTO AS VARCHAR(4))
         END||
         CASE WHEN (BDMESINIVNCUSTO = 0) OR (BDMESINIVNCUSTO IS NULL) THEN
                '00'
              WHEN (BDMESINIVNCUSTO < 10) THEN
                '0'||BDMESINIVNCUSTO
              ELSE
                CAST(BDMESINIVNCUSTO AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAINIVNCUSTO = 0) OR (BDDIAINIVNCUSTO IS NULL) THEN
                '00'
              WHEN (BDDIAINIVNCUSTO < 10) THEN
                '0'||BDDIAINIVNCUSTO
              ELSE
                CAST(BDDIAINIVNCUSTO AS VARCHAR(2))
         END, -- Data inicial

         CASE WHEN ((BDANOFIMVNCUSTO = 0) OR (BDANOFIMVNCUSTO IS NULL)) AND (BDMESFIMVNCUSTO > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOFIMVNCUSTO = 0) OR (BDANOFIMVNCUSTO IS NULL) THEN
                '9999'
              WHEN (BDANOFIMVNCUSTO > 0) THEN
                CAST(BDANOFIMVNCUSTO AS VARCHAR(4))
         END||
         CASE WHEN (BDMESFIMVNCUSTO = 0) OR (BDMESFIMVNCUSTO IS NULL) THEN
                '99'
              WHEN (BDMESFIMVNCUSTO < 10) THEN
                '0'||BDMESFIMVNCUSTO
              ELSE
                CAST(BDMESFIMVNCUSTO AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAFIMVNCUSTO = 0) OR (BDDIAFIMVNCUSTO IS NULL) THEN
                '99'
              WHEN (BDDIAFIMVNCUSTO < 10) THEN
                '0'||BDDIAFIMVNCUSTO
              ELSE
                CAST(BDDIAFIMVNCUSTO AS VARCHAR(2))
         END, -- Data final
         BDDIAINIVNCUSTO,
         BDMESINIVNCUSTO,
         BDANOINIVNCUSTO,
         BDDIAFIMVNCUSTO,
         BDMESFIMVNCUSTO,
         BDANOFIMVNCUSTO,
         BDDESCCONDCUSTO,
         BDFERIASVNCUSTO,
         BD13VNCUSTO
FROM VRHF_CUSTOS_TVNCUSTO
;

/* CREATE OR ALTER VIEW: VW_VERBAS_NAO_PRESC_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBAS_NAO_PRESC_ATUAL(
BDCODPRES,
BDCODVER,
BDDATAINI,
BDDATAFIM,
BDDIAINI,
BDMESINI,
BDANOINI,
BDDIAFIM,
BDMESFIM,
BDANOFIM,
BDDESCCOND,
BDFERIASVN,
BD13VN)
 AS 
SELECT BDCODPRES,
         BDCODVER,
         CASE WHEN ((BDANOINIVNPRES = 0) OR (BDANOINIVNPRES IS NULL)) AND (BDMESINIVNPRES > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOINIVNPRES = 0) OR (BDANOINIVNPRES IS NULL) THEN
                '0000'
              WHEN (BDANOINIVNPRES > 0) THEN
                CAST(BDANOINIVNPRES AS VARCHAR(4))
         END||
         CASE WHEN (BDMESINIVNPRES = 0) OR (BDMESINIVNPRES IS NULL) THEN
                '00'
              WHEN (BDMESINIVNPRES < 10) THEN
                '0'||BDMESINIVNPRES
              ELSE
                CAST(BDMESINIVNPRES AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAINIVNPRES = 0) OR (BDDIAINIVNPRES IS NULL) THEN
                '00'
              WHEN (BDDIAINIVNPRES < 10) THEN
                '0'||BDDIAINIVNPRES
              ELSE
                CAST(BDDIAINIVNPRES AS VARCHAR(2))
         END, -- Data inicial

         CASE WHEN ((BDANOFIMVNPRES = 0) OR (BDANOFIMVNPRES IS NULL)) AND (BDMESFIMVNPRES > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOFIMVNPRES = 0) OR (BDANOFIMVNPRES IS NULL) THEN
                '9999'
              WHEN (BDANOFIMVNPRES > 0) THEN
                CAST(BDANOFIMVNPRES AS VARCHAR(4))
         END||
         CASE WHEN (BDMESFIMVNPRES = 0) OR (BDMESFIMVNPRES IS NULL) THEN
                '99'
              WHEN (BDMESFIMVNPRES < 10) THEN
                '0'||BDMESFIMVNPRES
              ELSE
                CAST(BDMESFIMVNPRES AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAFIMVNPRES = 0) OR (BDDIAFIMVNPRES IS NULL) THEN
                '99'
              WHEN (BDDIAFIMVNPRES < 10) THEN
                '0'||BDDIAFIMVNPRES
              ELSE
                CAST(BDDIAFIMVNPRES AS VARCHAR(2))
         END, -- Data final
         BDDIAINIVNPRES,
         BDMESINIVNPRES,
         BDANOINIVNPRES,
         BDDIAFIMVNPRES,
         BDMESFIMVNPRES,
         BDANOFIMVNPRES,
         BDDESCCONDPRES,
         BDFERIASVNPRES,
         BD13VNPRES
FROM VRHF_BASE_TVNPRES
;

/* CREATE OR ALTER VIEW: VW_VERBAS_SIM_CUSTO_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBAS_SIM_CUSTO_ATUAL(
BDCODCENTRO,
BDCODTPCC,
BDCODVER,
BDDATAINI,
BDDATAFIM,
BDDIAINI,
BDMESINI,
BDANOINI,
BDDIAFIM,
BDMESFIM,
BDANOFIM,
BDFORMULAREF,
BDFORMULAVAL,
BDFORMULAREFAUX)
 AS 
SELECT BDCODCENTRO,
         BDCODTPCC,
         BDCODVER,
         CASE WHEN ((BDANOINIVSCUSTO = 0) OR (BDANOINIVSCUSTO IS NULL)) AND (BDMESINIVSCUSTO > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOINIVSCUSTO = 0) OR (BDANOINIVSCUSTO IS NULL) THEN
                '0000'
              WHEN (BDANOINIVSCUSTO > 0) THEN
                CAST(BDANOINIVSCUSTO AS VARCHAR(4))
         END||
         CASE WHEN (BDMESINIVSCUSTO = 0) OR (BDMESINIVSCUSTO IS NULL) THEN
                '00'
              WHEN (BDMESINIVSCUSTO < 10) THEN
                '0'||BDMESINIVSCUSTO
              ELSE
                CAST(BDMESINIVSCUSTO AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAINIVSCUSTO = 0) OR (BDDIAINIVSCUSTO IS NULL) THEN
                '00'
              WHEN (BDDIAINIVSCUSTO < 10) THEN
                '0'||BDDIAINIVSCUSTO
              ELSE
                CAST(BDDIAINIVSCUSTO AS VARCHAR(2))
         END, -- Data inicial

         CASE WHEN ((BDANOFIMVSCUSTO = 0) OR (BDANOFIMVSCUSTO IS NULL)) AND (BDMESFIMVSCUSTO > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOFIMVSCUSTO = 0) OR (BDANOFIMVSCUSTO IS NULL) THEN
                '9999'
              WHEN (BDANOFIMVSCUSTO > 0) THEN
                CAST(BDANOFIMVSCUSTO AS VARCHAR(4))
         END||
         CASE WHEN (BDMESFIMVSCUSTO = 0) OR (BDMESFIMVSCUSTO IS NULL) THEN
                '99'
              WHEN (BDMESFIMVSCUSTO < 10) THEN
                '0'||BDMESFIMVSCUSTO
              ELSE
                CAST(BDMESFIMVSCUSTO AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAFIMVSCUSTO = 0) OR (BDDIAFIMVSCUSTO IS NULL) THEN
                '99'
              WHEN (BDDIAFIMVSCUSTO < 10) THEN
                '0'||BDDIAFIMVSCUSTO
              ELSE
                CAST(BDDIAFIMVSCUSTO AS VARCHAR(2))
         END, -- Data final
         BDDIAINIVSCUSTO,
         BDMESINIVSCUSTO,
         BDANOINIVSCUSTO,
         BDDIAFIMVSCUSTO,
         BDMESFIMVSCUSTO,
         BDANOFIMVSCUSTO,
         BDFORMULAREFCUSTO,
         BDFORMULAVALCUSTO,
         BDFORMULAREFAUXCUSTO
FROM VRHF_CUSTOS_TVSCUSTO
;

/* CREATE OR ALTER VIEW: VW_VERBAS_SIM_PRESC_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBAS_SIM_PRESC_ATUAL(
BDCODPRES,
BDCODVER,
BDDATAINI,
BDDATAFIM,
BDDIAINI,
BDMESINI,
BDANOINI,
BDDIAFIM,
BDMESFIM,
BDANOFIM,
BDFORMULAREF,
BDFORMULAVAL,
BDFORMULAREFAUX)
 AS 
SELECT BDCODPRES,
         BDCODVER,
         CASE WHEN ((BDANOINIVSPRES = 0) OR (BDANOINIVSPRES IS NULL)) AND (BDMESINIVSPRES > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOINIVSPRES = 0) OR (BDANOINIVSPRES IS NULL) THEN
                '0000'
              WHEN (BDANOINIVSPRES > 0) THEN
                CAST(BDANOINIVSPRES AS VARCHAR(4))
         END||
         CASE WHEN (BDMESINIVSPRES = 0) OR (BDMESINIVSPRES IS NULL) THEN
                '00'
              WHEN (BDMESINIVSPRES < 10) THEN
                '0'||BDMESINIVSPRES
              ELSE
                CAST(BDMESINIVSPRES AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAINIVSPRES = 0) OR (BDDIAINIVSPRES IS NULL) THEN
                '00'
              WHEN (BDDIAINIVSPRES < 10) THEN
                '0'||BDDIAINIVSPRES
              ELSE
                CAST(BDDIAINIVSPRES AS VARCHAR(2))
         END, -- Data inicial

         CASE WHEN ((BDANOFIMVSPRES = 0) OR (BDANOFIMVSPRES IS NULL)) AND (BDMESFIMVSPRES > 0) THEN
                SUBSTRING((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database) FROM 1 FOR 4)
              WHEN (BDANOFIMVSPRES = 0) OR (BDANOFIMVSPRES IS NULL) THEN
                '9999'
              WHEN (BDANOFIMVSPRES > 0) THEN
                CAST(BDANOFIMVSPRES AS VARCHAR(4))
         END||
         CASE WHEN (BDMESFIMVSPRES = 0) OR (BDMESFIMVSPRES IS NULL) THEN
                '99'
              WHEN (BDMESFIMVSPRES < 10) THEN
                '0'||BDMESFIMVSPRES
              ELSE
                CAST(BDMESFIMVSPRES AS VARCHAR(2))
         END||
         CASE WHEN (BDDIAFIMVSPRES = 0) OR (BDDIAFIMVSPRES IS NULL) THEN
                '99'
              WHEN (BDDIAFIMVSPRES < 10) THEN
                '0'||BDDIAFIMVSPRES
              ELSE
                CAST(BDDIAFIMVSPRES AS VARCHAR(2))
         END, -- Data final
         BDDIAINIVSPRES,
         BDMESINIVSPRES,
         BDANOINIVSPRES,
         BDDIAFIMVSPRES,
         BDMESFIMVSPRES,
         BDANOFIMVSPRES,
         BDFORMULAREFPRES,
         BDFORMULAVALPRES,
         BDFORMULAREFAUXPRES
FROM VRHF_BASE_TVSPRES
;

/* CREATE OR ALTER VIEW: VW_VERBASFC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBASFC(
BDCODEMP,
BDCODCOL,
BDREF,
BDCODVER,
BDREFV,
BDREFAUXV,
BDVALV)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFCOMP,
  BDCODVER,
  BDREFVFC,
  BDREFAUXVFC,
  BDVALVFC
FROM VRHF_EMP_TVERBAFC
;

/* CREATE OR ALTER VIEW: VW_VERBASFN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBASFN(
BDCODEMP,
BDCODCOL,
BDREF,
BDCODVER,
BDREFV,
BDREFAUXV,
BDVALV)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDCODVER,
  BDREFVFN,
  BDREFAUXVFN,
  BDVALVFN
FROM VRHF_EMP_TVERBAFN
;

/* CREATE OR ALTER VIEW: VW_VERBASSERVICO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VERBASSERVICO(
BDCODEMP,
BDCODTER,
BDNOMTER,
BDCODSERV,
BDDATASERV,
BDCODTIPOSERV,
BDDESCTIPOSERV,
BDCODVER,
BDDESCVER,
BDREFERENCIA,
BDVALOR,
BDIGNFORREF,
BDIGNFORREFA,
BDIGNFORVAL)
 AS 
SELECT tlan.bdcodemp,
       tlan.bdcodter,
       tterc.bdnomter,
       tlan.bdcodserv,
       tserv.bddataserv,
       tserv.BDCODTIPOSERV,
       ttipo.BDDESCTIPOSERV,
       tlan.bdcodver,
       tver.bddescver,
       tlan.bdreferencia,
       tlan.bdvalor,
       tlan.BDIGNFORREFA,
       tlan.BDIGNFORREF,
       tlan.BDIGNFORVAL
FROM vrh_base_tpla_tserv tlan
JOIN vrh_base_tverbas tver ON (tver.bdcodver = tlan.bdcodver)
JOIN vrh_base_tservterc tserv ON (tserv.bdcodemp = tlan.bdcodemp AND tserv.bdcodter = tlan.bdcodter AND tserv.bdcodserv = tlan.bdcodserv)
LEFT OUTER JOIN ttiposervico ttipo ON (ttipo.bdcodtiposerv = tserv.bdcodtiposerv)
LEFT OUTER JOIN vw_VRH_BASE_TTERC tterc ON (tterc.bdcodter = tlan.bdcodter)
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_AUMENTOFAIXASCONV (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_AUMENTOFAIXASCONV(
BDCODCONVENIO,
BDCODOPERADORA,
BDCODPLACONVSAU,
BDORDEM,
BDREF)
 AS 
SELECT
  BDCODCONVENIO,
  BDCODOPERADORA,
  BDCODPLACONVSAU,
  BDORDEM,
  MAX(BDREF)
FROM VRH_BASE_FAIXAS_CONVENIOS X
WHERE
  CAST(BDREF AS VARCHAR(6)) < (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
GROUP BY
  BDCODCONVENIO,
  BDCODOPERADORA,
  BDCODPLACONVSAU,
  BDORDEM
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TEMPVINC_MAX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TEMPVINC_MAX(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
    X.bdcodemp,
    MAX(X.bdrefemp)
FROM VRH_BASE_TEMPVINC X
WHERE
  CAST(X.BDREFEMP AS VARCHAR(6)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TEMPVINC_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TEMPVINC_MIN(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
    X.bdcodemp,
    MIN(X.bdrefemp)
FROM VRH_BASE_TEMPVINC X
WHERE
  CAST(X.BDREFEMP AS VARCHAR(6)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TRESPEMP_FIRST (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TRESPEMP_FIRST(
BDCODEMP,
BDCODRESP,
BDCODPLAFUC,
BDCODTFUC,
BDNOMERESP,
BDCPFRESP,
BDNITRESP,
BDDDDRESP,
BDFONERESP,
BDRAMALRESP,
BDRGRESP,
BDPADRAORESP,
BDEMAILRESP)
 AS 
SELECT
    X.BDCODEMP,
    X.BDCODRESP,
    X.BDCODPLAFUC,
    X.BDCODTFUC,
    X.BDNOMERESP,
    X.BDCPFRESP,
    X.BDNITRESP,
    X.BDDDDRESP,
    X.BDFONERESP,
    X.BDRAMALRESP,
    X.BDRGRESP,
    X.BDPADRAORESP,
    X.BDEMAILRESP
FROM VRH_BASE_TRESPEMP X
WHERE EXISTS (SELECT Y.BDCODEMP, MIN(Y.BDCODRESP)
              FROM VRH_BASE_TRESPEMP Y
              WHERE Y.BDPADRAORESP <> 'TRUE'
              GROUP BY Y.BDCODEMP
              HAVING Y.BDCODEMP = X.BDCODEMP AND MIN(Y.BDCODRESP) = X.BDCODRESP
             )
ORDER BY X.BDCODEMP, X.BDCODRESP
;

--Sol. 14304 - Adicionado campo BDQTDDIASANTPAG - Bruno L. R.
/* CREATE OR ALTER VIEW: VW_VRH_BASE_TSINDTREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TSINDTREF(
BDCODSINTRAB,
BDDESCSINTRAB,
BDMEDSITSINTRAB,
BDMESESMEDSITSINTRAB,
BDREFST,
BDCODIND,
BDVERFERIST,
BDVERMULRESST,
BDCODPMS,
BDPERABFERST,
BDDATBASEST,
BDESTABST,
BDPERCNOTST,
BDMESCSST,
BDFERRESCST,
BDFERDOBST,
BDFERJCST,
BDTIPODESCCONTRST,
BDBASEADICST,
BDLIMITE13ST,
BDPISOSAL,
BDSALMINGAR,
BDMESTXASST,
BDTIPODESCTXASST,
BDMESRESCMEDIASST,
BDTIPOMESRESCMEDIASST,
BDINIHORANOTST,
BDFIMHORANOTST,
BDLIMINARAVPREVST,
BDQTDDIASANTPAG,
BDINATIVO)
 AS 
SELECT
  BASE.bdcodsintrab,
  BASE.BDDESCSINTRAB,
  BASE.BDMEDSITSINTRAB,
  BASE.BDMESESMEDSITSINTRAB,
  REF.bdrefst,
  REF.bdcodind,
  REF.bdverferist,
  REF.bdvermulresst,
  REF.bdcodpms,
  REF.bdperabferst,
  REF.bddatbasest,
  REF.bdestabst,
  REF.bdpercnotst,
  REF.bdmescsst,
  REF.bdferrescst,
  REF.bdferdobst,
  REF.bdferjcst,
  REF.bdtipodesccontrst,
  REF.bdbaseadicst,
  REF.bdlimite13st,
  REF.BDPISOSAL,
  REF.BDSALMINGAR,
  ref.bdmestxasst,
  ref.bdtipodesctxasst,
  ref.bdmesrescmediasst,
  ref.bdtipomesrescmediasst,
  ref.bdinihoranotst,
  ref.bdfimhoranotst,
  ref.bdliminaravprevst,
  ref.bdqtddiasantpag,
  ref.bdinativo

FROM
(
  SELECT
      X.bdcodsintrab,
      X.bddescsintrab,
      X.bdmedsitsintrab,
      X.bdmesesmedsitsintrab,
      COALESCE
  (
      (SELECT MAX(d2.bdrefst) FROM vrh_base_tsindtref d2 WHERE d2.bdcodsintrab = x.bdcodsintrab AND CAST(d2.BDREFST AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefst) FROM vrh_base_tsindtref d1 WHERE d1.bdcodsintrab = x.bdcodsintrab)
  ) AS bdrefst
  FROM VRH_BASE_TSINDTRAB x
) AS BASE, vrh_base_tsindtref REF
WHERE BASE.bdcodsintrab = REF.bdcodsintrab AND BASE.bdREFST = REF.bdREFST
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TSINDTREF_MAX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TSINDTREF_MAX(
BDCODSINTRAB,
BDREFST)
 AS 
SELECT
  X.bdcodsintrab,
  MAX(X.bdrefst)
FROM vrh_base_tsindtref X
WHERE
  CAST(X.BDREFST AS VARCHAR(6)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODSINTRAB
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TSINDTREF_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TSINDTREF_MIN(
BDCODSINTRAB,
BDREFST)
 AS 
SELECT
  X.bdcodsintrab,
  MIN(X.bdrefst)
FROM vrh_base_tsindtref X
GROUP BY X.BDCODSINTRAB
;

/* CREATE OR ALTER VIEW: VW_VRH_BASE_TSINDTREF_MINREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_BASE_TSINDTREF_MINREF(
BDCODSINTRAB,
BDREFST)
 AS 
SELECT
  BDCODSINTRAB,
  MIN(BDREFST)
FROM VRH_BASE_TSINDTREF
GROUP BY BDCODSINTRAB
;

CREATE OR ALTER VIEW VW_VRH_EMP_TDEP_REF(
    BDCODEMP,
    BDCODCOL,
    BDCODDPN,
    BDREFDPN,
    BDPARENESCODPN,
    BDNOMEDPN,
    BDDATANASCDPN,
    BDCPFDPN,
    BDINVALIDODPN,
    BDCODCID,
    BDCARTDPN,
    BDREGDPN,
    BDLIVDPN,
    BDFOLDPN,
    BDDATAENTREDPN,
    BDDATABAUXADPN,
    BDDPN,
    BDREFIRDPN,
    BDMATRICULADPN,
    BDCODTIPO,
    BDTIPODEPESOCIAL,
    BDUNIVERSITARIO,
    BDIDRHNET,
    BDSTATUS_ES,
    BDDATA_ES,
    BDCONVMEDDPN,
    BDSALFAMDPN,
    BDDEPIRDPN,
    BDDESCRDEPDPN)
AS
SELECT BASE.BDCODEMP, BASE.BDCODCOL, BASE.bdcoddpn, V.BDREFDPN, V.bdparenescodpn, V.bdnomedpn, v.bddatanascdpn, v.bdcpfdpn, v.bdinvalidodpn,
       BASE.bdcodcid, BASE.bdcartdpn, BASE.bdregdpn, BASE.bdlivdpn, BASE.bdfoldpn, BASE.bddataentredpn, BASE.bddatabauxadpn, BASE.bddpn,
       BASE.bdrefirdpn, BASE.bdmatriculadpn, BASE.bdcodtipo, BASE.bdtipodepesocial, BASE.bduniversitario, BASE.bdidrhnet, BASE.bdstatus_es, BASE.bddata_es,
       coalesce(v.bdconvmeddpn, 'FALSE'), coalesce(v.bdsalfamdpn, 'FALSE'), coalesce(v.bddepirdpn, 'FALSE'), v.BDDESCRDEPDPN
FROM (
  SELECT
      X.bdcodemp,
      X.BDCODCOL,
      X.bdcoddpn,
      COALESCE
  (
      (SELECT MAX(d2.BDREFDPN) FROM vrh_emp_tdep_ref d2 WHERE d2.bdcodemp = x.bdcodemp AND d2.bdcodcol = x.bdcodcol AND d2.bdcoddpn = x.bdcoddpn AND CAST(d2.BDREFDPN AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.BDREFDPN) FROM vrh_emp_tdep_ref d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol AND d1.bdcoddpn = x.bdcoddpn)
  ) AS BDREFDPN,
      X.bdcodcid, x.bdcartdpn, x.bdregdpn, x.bdlivdpn, x.bdfoldpn, x.bddataentredpn, x.bddatabauxadpn, x.bddpn, x.bdrefirdpn, x.bdmatriculadpn, x.bdcodtipo, x.bdtipodepesocial, x.bduniversitario, x.bdidrhnet, x.bdstatus_es, x.bddata_es
  FROM  vrh_emp_tdep x
) AS BASE
join vrh_emp_tdep_ref v on (BASE.bdcodemp = v.bdcodemp AND BASE.bdcodcol = v.bdcodcol AND BASE.bdcoddpn = v.bdcoddpn AND BASE.BDREFDPN = v.BDREFDPN)
;

CREATE OR ALTER VIEW VW_VRH_EMP_TDEP_REF_ESOCIAL(
    BDCODEMP,
    BDCODCOL,
    BDCODDPN,
    BDREFDPN,
    BDPARENESCODPN,
    BDNOMEDPN,
    BDDATANASCDPN,
    BDCPFDPN,
    BDINVALIDODPN,
    BDCONVMEDDPN,
    BDSALFAMDPN,
    BDDEPIRDPN,
    BDCODCID,
    BDCARTDPN,
    BDREGDPN,
    BDLIVDPN,
    BDFOLDPN,
    BDDATAENTREDPN,
    BDDATABAUXADPN,
    BDDPN,
    BDREFIRDPN,
    BDMATRICULADPN,
    BDCODTIPO,
    BDTIPODEPESOCIAL,
    BDUNIVERSITARIO,
    BDIDRHNET,
    BDSTATUS_ES,
    BDDATA_ES,
    BDDESCRDEPDPN)
AS
SELECT
    BASE.BDCODEMP, BASE.BDCODCOL, BASE.BDCODDPN, V.BDREFDPN, V.BDPARENESCODPN,
    V.BDNOMEDPN, V.BDDATANASCDPN, V.BDCPFDPN, V.BDINVALIDODPN, BDCONVMEDDPN,
    BDSALFAMDPN, BDDEPIRDPN, BASE.BDCODCID, BASE.BDCARTDPN, BASE.BDREGDPN,
    BASE.BDLIVDPN, BASE.BDFOLDPN, BASE.BDDATAENTREDPN, BASE.BDDATABAUXADPN, BASE.BDDPN,
    BASE.BDREFIRDPN, BASE.BDMATRICULADPN, BASE.BDCODTIPO, BASE.BDTIPODEPESOCIAL, BASE.BDUNIVERSITARIO,
    BASE.BDIDRHNET, BASE.BDSTATUS_ES, BASE.BDDATA_ES, V.BDDESCRDEPDPN
FROM (SELECT
          X.BDCODEMP,
          X.BDCODCOL,
          X.BDCODDPN,
          coalesce(
          (SELECT
               MAX(D2.BDREFDPN)
           FROM VRH_EMP_TDEP_REF D2
           WHERE
               D2.BDCODEMP = X.BDCODEMP AND
               D2.BDCODCOL = X.BDCODCOL AND
               D2.BDCODDPN = X.BDCODDPN AND
               CAST(D2.BDREFDPN AS VARCHAR(6)) <= (SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) FROM RDB$DATABASE)),
          (SELECT MIN(d1.BDREFDPN) FROM vrh_emp_tdep_ref d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol AND d1.bdcoddpn = x.bdcoddpn)
          ) AS BDREFDPN,
          X.BDCODCID,
          X.BDCARTDPN,
          X.BDREGDPN,
          X.BDLIVDPN,
          X.BDFOLDPN,
          X.BDDATAENTREDPN,
          X.BDDATABAUXADPN,
          X.BDDPN,
          X.BDREFIRDPN,
          X.BDMATRICULADPN,
          X.BDCODTIPO,
          X.BDTIPODEPESOCIAL,
          X.BDUNIVERSITARIO,
          X.BDIDRHNET,
          X.BDSTATUS_ES,
          X.BDDATA_ES
      FROM VRH_EMP_TDEP X) AS BASE
JOIN VRH_EMP_TDEP_REF V ON (BASE.BDCODEMP = V.BDCODEMP AND
                           BASE.BDCODCOL  = V.BDCODCOL AND
                           BASE.BDCODDPN  = V.BDCODDPN AND
                           BASE.BDREFDPN = V.BDREFDPN     )
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_CONSCOLCON (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_CONSCOLCON(
BDCODEMP,
BDCODCOL,
BDNOMCOL,
BDCODCLA,
BDDATAADMCOL,
BDREFCOL)
 AS 
SELECT COLCON.BDCODEMP, COLCON.BDCODCOL, COLCAD.BDNOMCOL, COLCONV.BDCODCLA, COLCON.BDDATAADMCOL, COLCONV.BDREFCOL
FROM VRH_EMP_TCOLCON COLCON
LEFT OUTER JOIN VRH_EMP_TCOLCON_VINC COLCONV ON (COLCON.bdcodemp = COLCONV.bdcodemp AND COLCON.bdcodcol = COLCONV.bdcodcol)
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON (COLCAD.BDCODEMP = COLCON.BDCODEMP AND COLCAD.BDCODCOL = COLCON.BDCODCOL)
ORDER BY COLCON.bdcodemp, COLCON.BDCODCOL, COLCONV.bdrefcol
;

/* CREATE OR ALTER VIEW: VW_VRHM_FAIXA_CONV_OP_SAU_MAX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHM_FAIXA_CONV_OP_SAU_MAX(
BDCODPLACONVSAU,
BDCODOPERADORA,
BDCODCONVENIO,
BDREF)
 AS 
SELECT faixa.bdcodplaconvsau,faixa.BDCODOPERADORA,faixa.bdcodconvenio,MAX(faixa.bdref) FROM VRH_BASE_FAIXAS_CONVENIOS faixa
WHERE CAST(faixa.BDREf AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
GROUP BY faixa.bdcodplaconvsau,faixa.BDCODOPERADORA,faixa.bdcodconvenio
;

/* CREATE OR ALTER VIEW: VW_VRHM_FAIXA_CONV_OP_SAU_ATU (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHM_FAIXA_CONV_OP_SAU_ATU(
BDCODPLACONVSAU,
BDCODOPERADORA,
BDCODCONVENIO,
BDREF,
BDIDADE,
BDVALOR,
BDTIPO)
 AS 
SELECT faixa.bdcodplaconvsau,faixa.bdcodoperadora,faixa.bdcodconvenio,faixa.bdref,COALESCE(faixa.bdidade,0),faixa.bdvalor,faixa.bdtipo
FROM VRH_BASE_FAIXAS_CONVENIOS faixa
WHERE EXISTS (SELECT * FROM VW_VRHM_FAIXA_CONV_OP_SAU_MAX xmax
WHERE faixa.bdcodoperadora = xmax.bdcodoperadora AND
      faixa.bdcodplaconvsau = xmax.bdcodplaconvsau AND
      faixa.bdcodconvenio = xmax.bdcodconvenio AND faixa.bdref = xmax.bdref)
;


/* CREATE OR ALTER VIEW: VW_VRH_EMP_TAVISOFERIAS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TAVISOFERIAS(
BDCODEMP,
BDCODCOL,
BDDATAAVISO,
BDINIGOZO,
BDQTDGOZO,
BDTIPOCALC,
BDREFABONO,
BDQTDABONO)
 AS 
SELECT   BDCODEMP     ,
    BDCODCOL     ,
    BDDATAAVISO  ,
    BDINIGOZO    ,
    BDQTDGOZO    ,
    CASE WHEN BDTIPOCALC = 0 THEN 'Normal' ELSE 'Coletivas' END,
    BDREFABONO   ,
    BDQTDABONO    FROM vrh_emp_tavisoferias
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOL_ASO_PERI_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOL_ASO_PERI_ATUAL(
BDCODEMP,
BDCODCOL,
BDCODASO,
BDDTASO,
BDCODMED,
BDTPASO,
BDRESULTASO)
 AS 
SELECT aso.bdcodemp, aso.bdcodcol, aso.bdcodaso, aso.bddtaso, aso.bdcodmed, aso.bdtpaso, aso.bdresultaso
FROM VRH_EMP_TCOL_ASO aso
JOIN (
SELECT aso.bdcodemp, aso.bdcodcol, MAX(aso.bdcodaso) bdcodaso FROM VRH_EMP_TCOL_ASO aso
JOIN (SELECT aso.bdcodemp, aso.bdcodcol, MAX(aso.bddtaso) bddtaso
       FROM VRH_EMP_TCOL_ASO aso
       WHERE aso.BDTPASO = 0 AND aso.bddtaso <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database)
       GROUP BY aso.bdcodemp, aso.bdcodcol) ax ON (aso.bdcodemp = ax.bdcodemp AND aso.bdcodcol = ax.bdcodcol AND aso.bddtaso = ax.bddtaso)
GROUP BY aso.bdcodemp, aso.bdcodcol
) ax ON (aso.bdcodemp = ax.bdcodemp AND aso.bdcodcol = ax.bdcodcol AND aso.bdcodaso = ax.bdcodaso)
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOL_SHE (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOL_SHE(
    BDCODEMP,
    BDCODCOL,
    BDCODEMPSHE,
    BDCODSHE,
    BDDATASHE,
    BDCODMAS,
    BDSALSHE)
AS
SELECT
    BASE.bdcodemp,
    BASE.bdcodcol,
    REF.bdcodempshe,
    REF.bdcodshe,
    REF.bddatashe,
    REF.bdcodmas,
    REF.bdsalshe
FROM
(
  SELECT
      X.bdcodemp,
      y.bdcodcol,
      X.bdcodshe, 
      COALESCE
  (
      (SELECT MAX(d2.bddatashe) FROM VRH_EMP_TCOL_SHE d2 WHERE d2.bdcodemp = x.bdcodemp AND d2.bdcodcol = y.bdcodcol AND d2.bdcodshe = x.bdcodshe AND d2.BDDATASHE <= (SELECT COALESCE(CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES'))) AS DATE), d2.BDDATASHE) FROM rdb$database)),
      (SELECT MIN(d1.bddatashe) FROM VRH_EMP_TCOL_SHE d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = y.bdcodcol AND d1.bdcodshe = x.bdcodshe)
  ) AS bddatashe
  FROM VRH_BASE_TSALHORESP x
  join VRH_EMP_TCOLCON y on (y.BDCODEMP = x.BDCODEMP)

) AS BASE, VRH_EMP_TCOL_SHE REF
WHERE BASE.BDCODEMP = REF.BDCODEMP AND BASE.BDCODCOL = REF.BDCODCOL AND BASE.BDCODSHE = REF.BDCODSHE AND BASE.BDDATASHE = REF.BDDATASHE
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOL_SHE_COMP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOL_SHE_COMP(
    BDCODEMP,
    BDCODCOL,
    BDCODEMPSHE,
    BDCODSHE,
    BDDATASHE,
    BDCODMAS,
    BDSALSHE)
AS
SELECT
    BASE.bdcodemp,
    BASE.bdcodcol,
    REF.bdcodempshe,
    REF.bdcodshe,
    REF.BDDATASHE,
    REF.bdcodmas,
    REF.bdsalshe
FROM
(
  SELECT
      X.bdcodemp,
      y.bdcodcol,
      X.bdcodshe,
      COALESCE
  (
      (SELECT MAX(d2.BDDATASHE) FROM VRH_EMP_TCOL_SHE d2 WHERE d2.bdcodemp = x.bdcodemp AND d2.bdcodcol = y.bdcodcol AND d2.bdcodshe = x.bdcodshe AND d2.BDDATAEFEITOHE <= (SELECT COALESCE(CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES'))) AS DATE), d2.BDDATAEFEITOHE) FROM rdb$database)),
      (SELECT MIN(d1.BDDATASHE) FROM VRH_EMP_TCOL_SHE d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = y.bdcodcol AND d1.bdcodshe = x.bdcodshe)
  ) AS BDDATASHE
  FROM VRH_BASE_TSALHORESP x
  join VRH_EMP_TCOLCON y on (y.BDCODEMP = x.BDCODEMP)

) AS BASE, VRH_EMP_TCOL_SHE REF
WHERE BASE.BDCODEMP = REF.BDCODEMP AND BASE.BDCODCOL = REF.BDCODCOL AND BASE.BDCODSHE = REF.BDCODSHE AND BASE.BDDATASHE = REF.BDDATASHE AND REF.bddataefeitohe <= (select MAX(Y.bddataefeitohe)
       from VRH_EMP_TCOL_SHE Y
       where Y.BDCODEMP = REF.BDCODEMP and Y.BDCODCOL = REF.BDCODCOL and
             Y.bddataefeitohe <=
                (select CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES'))) as DATE)
                 from rdb$database
                )
      )
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOL_VDIA_COMPLETA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOL_VDIA_COMPLETA(
BDCODEMP,
BDCODCOL,
BDDATACOL,
BDCODPLAFUC,
BDCODTFUCA,
BDCODQHA,
BDCONTRCOL,
BDCODPQUA,
BDDESCTFUCA,
BDDESCQHA,
BDCODCBOA,
BDDESCCBOA)
 AS 
SELECT
    vinc.bdcodemp,
    vinc.bdcodcol,
    vinc.bddatacol,
    vinc.bdcodplafuc,
    vinc.bdcodtfuc,
    vinc.bdcodqh,
    vinc.bdcontrcol,
    vinc.bdcodpqua,
    fuc.bddesctfuc,
    qua.bddescqh,
    CASE WHEN ((fuc.bdcodcbo IS NULL) OR (fuc.bdcodcbo = 0)) THEN ''
         WHEN strlen(fuc.bdcodcbo) = 3 THEN '000'||SUBSTRING(fuc.bdcodcbo FROM 1 FOR 1)||'-'||SUBSTRING(fuc.bdcodcbo FROM 2 FOR 2)
         WHEN strlen(fuc.bdcodcbo) = 4 THEN '00'||SUBSTRING(fuc.bdcodcbo FROM 1 FOR 2)||'-'||SUBSTRING(fuc.bdcodcbo FROM 3 FOR 2)
         WHEN strlen(fuc.bdcodcbo) = 5 THEN '0'||SUBSTRING(fuc.bdcodcbo FROM 1 FOR 3)||'-'||SUBSTRING(fuc.bdcodcbo FROM 4 FOR 2)
    ELSE SUBSTRING(fuc.bdcodcbo FROM 1 FOR 4)||'-'||SUBSTRING(fuc.bdcodcbo FROM 5 FOR 2)
    END bdcodcbo,
    cbo.bddesccbo
FROM vrh_emp_tcol_vincdia vinc
LEFT OUTER JOIN vrh_funcoes_tfuc fuc ON (fuc.bdcodplafuc = vinc.bdcodplafuc AND fuc.bdcodtfuc = vinc.bdcodtfuc)
LEFT OUTER JOIN vrh_base_tqh qua ON (qua.bdcodpqua = vinc.bdcodpqua AND qua.bdcodqh = vinc.bdcodqh)
LEFT OUTER JOIN vrh_base_tcbo cbo ON (cbo.bdcodcbo = fuc.bdcodcbo)
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOL_VINC_MAX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOL_VINC_MAX(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MAX(X.bdrefcol)
FROM VRH_EMP_TCOL_VINC X
WHERE
  CAST(X.BDREFCOL AS VARCHAR(6)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOL_VINC_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOL_VINC_MIN(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MIN(X.bdrefcol)
FROM VRH_EMP_TCOL_VINC X
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOL_VINCDIA (ViwData.CreateDependDef) */
/* View: VW_VRH_EMP_TCOL_VINCDIA */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOL_VINCDIA(
    BDCODEMP,
    BDCODCOL,
    BDDATACOL,
    BDCODPLAFUC,
    BDCODTFUC,
    BDCODPQUA,
    BDCODQH,
    BDREGJORTRAB,
    BDTIPOJORNADA,
    BDDESCTPJORNADA,
    BDINDHORARIONOT,
    BDACUMCARGO,
    BDTIPOESCALA,
    BDCODREVEZAMENTO,
    BDDATAINICIALESCALA,
    BDDTAINICIALFOLGA,
    BDREFCOL,
 BDDESCQH)
AS
SELECT
    BASE.bdcodemp,
    BASE.bdcodcol,
    BASE.bddatacol,
    VIN.bdcodplafuc,
    VIN.bdcodtfuc,
    VIN.bdcodpqua,
    VIN.bdcodqh,
    VIN.bdregjortrab,
    VIN.BDTIPOJORNADA,
    VIN.BDDESCTPJORNADA,
    VIN.BDINDHORARIONOT,
    VIN.BDACUMCARGO,
    VIN.bdtipoescala,
    VIN.bdcodrevezamento,
    Vin.bddatainicialescala,
    VIN.BDDTAINICIALFOLGA,
    vin.bdrefcol,
 q.BDDESCQH
FROM
(
  SELECT
    col.bdCODEMP,
    col.bdCODCOL,
    COALESCE
    (
      (SELECT MAX(d1.bddatacol) FROM VRH_EMP_TCOL_VINCDIA d1 WHERE d1.bdcodemp = col.bdcodemp AND d1.bdcodcol = col.bdcodcol AND CAST(d1.BDDATACOL AS VARCHAR(10)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database)),
      (SELECT MIN(d2.bddatacol) FROM VRH_EMP_TCOL_VINCDIA d2 WHERE d2.bdcodemp = col.bdcodemp AND d2.bdcodcol = col.bdcodcol)
    ) AS bdDATACOL
  FROM vrh_emp_tcolcon col
) AS BASE, VRH_EMP_TCOL_VINCDIA VIN
left outer join VRH_BASE_TQH q on q.bdcodpqua = VIN.bdcodpqua and  q.bdcodqh = VIN.bdcodqh
WHERE BASE.bdCODEMP = VIN.bdCODEMP AND BASE.bdCODCOL = VIN.bdCODCOL AND BASE.bdDATACOL = VIN.bdDATACOL;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOL_VINCDIA_MAX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOL_VINCDIA_MAX(
BDCODEMP,
BDCODCOL,
BDDATACOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MAX(X.bddatacol)
FROM VRH_EMP_TCOL_VINCDIA X
WHERE
  CAST(X.BDDATACOL AS VARCHAR(10)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOL_VINCDIA_MAX_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOL_VINCDIA_MAX_MIN(
BDCODEMP,
BDCODCOL,
BDDATACOL)
 AS 
SELECT
    W.bdcodemp,
    W.bdcodcol,
    (SELECT FIRST 1 X.bddatacol
      FROM VRH_EMP_TCOL_VINCDIA X
      WHERE W.bdcodemp = x.bdcodemp AND w.bdcodcol = x.bdcodcol AND
        CAST(X.BDDATACOL AS VARCHAR(10)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database )
      ORDER BY X.bddatacol DESC
     )
FROM vrh_emp_tcolcon W
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOL_VINCDIA_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOL_VINCDIA_MIN(
BDCODEMP,
BDCODCOL,
BDDATACOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MIN(X.bddatacol)
FROM VRH_EMP_TCOL_VINCDIA X
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOL_VINCDIA_NOVO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOL_VINCDIA_NOVO(
    BDCODEMP,
    BDCODCOL,
    BDDATACOL,
    BDCODPLAFUC,
    BDCODTFUC,
    BDCODPQUA,
    BDCODQH,
    BDREGJORTRAB,
    BDINDHORARIONOT,
    BDTIPOESCALA,
    BDDTAINICIALFOLGA)
AS
SELECT
    X.bdcodemp,
    X.bdcodcol,
    X.bddatacol,
    X.bdcodplafuc,
    X.bdcodtfuc,
    x.bdcodpqua,
    X.bdcodqh,
    X.bdregjortrab,
    X.bdindhorarionot,
    X.BDTIPOESCALA,
    X.BDDTAINICIALFOLGA
FROM vw_vrh_emp_tcol_vincdia_max_min W
JOIN vrh_emp_tcol_vincdia X ON (w.bdcodemp = x.bdcodemp AND w.bdcodcol = x.bdcodcol AND w.bddatacol = x.bddatacol)
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOLCON_CALCDIA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_CALCDIA(
    BDCODEMP,
    BDCODCOL,
    BDDATACOL,
    BDCODMAS,
    BDSALBASECOL,
    BDDATAEFEITO)
AS
SELECT
    BASE.bdcodemp,
    BASE.bdcodcol,
    max(VIN.bddatacol),
    max(VIN.bdcodmas),
    max(VIN.bdsalbasecol),
    max(VIN.bddataefeito)
FROM
(
  SELECT
    col.bdCODEMP,
    col.bdCODCOL,
    COALESCE
    (
      (SELECT MAX(d1.bddatacol) FROM vrh_emp_tcolcon_calcdia d1 WHERE d1.bdcodemp = col.bdcodemp AND d1.bdcodcol = col.bdcodcol AND CAST(d1.BDDATACOL AS VARCHAR(10)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database)),
      (SELECT MIN(d2.bddatacol) FROM vrh_emp_tcolcon_calcdia d2 WHERE d2.bdcodemp = col.bdcodemp AND d2.bdcodcol = col.bdcodcol)
    ) AS bdDATACOL
  FROM vrh_emp_tcolcon col
) AS BASE, vrh_emp_tcolcon_calcdia VIN
WHERE BASE.bdCODEMP = VIN.bdCODEMP AND BASE.bdCODCOL = VIN.bdCODCOL AND BASE.bdDATACOL = VIN.bdDATACOL
group by
    BASE.bdcodemp,
    BASE.bdcodcol
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOLCON_CALCDIA_MAX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_CALCDIA_MAX(
BDCODEMP,
BDCODCOL,
BDDATACOL,
BDDATAEFEITO)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MAX(X.bddatacol),
    MAX(X.bddataefeito)
FROM VRH_EMP_TCOLCON_CALCDIA X
WHERE
  CAST(X.BDDATACOL AS VARCHAR(10)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOLCON_CALCDIA_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_CALCDIA_MIN(
BDCODEMP,
BDCODCOL,
BDDATACOL,
BDDATAEFEITO)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MIN(X.bddatacol),
    MIN(X.bddataefeito)
FROM VRH_EMP_TCOLCON_CALCDIA X
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOLCON_CALCDIA_MMIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_CALCDIA_MMIN(
BDCODEMP,
BDCODCOL,
BDDATACOL,
BDDATAEFEITO)
 AS 
SELECT
    w.bdcodemp,
    w.bdcodcol,
    ( SELECT FIRST 1 X.bddatacol
      FROM VRH_EMP_TCOLCON_CALCDIA X
      WHERE w.bdcodemp = x.bdcodemp AND w.bdcodcol = x.bdcodcol AND
      CAST(X.BDDATACOL AS VARCHAR(10)) <=(SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database)
      ORDER BY x.bddatacol DESC),
    ( SELECT FIRST 1 X.bddataefeito
      FROM VRH_EMP_TCOLCON_CALCDIA X
      WHERE w.bdcodemp = x.bdcodemp AND w.bdcodcol = x.bdcodcol AND
      CAST(X.BDDATACOL AS VARCHAR(10)) <=(SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database)
      ORDER BY x.bddataefeito DESC)
FROM vrh_emp_tcolcon W
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOLCON_CALCDIA_NOVO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_CALCDIA_NOVO(
    BDCODEMP,
    BDCODCOL,
    BDDATACOL,
    BDCODMAS,
    BDSALBASECOL,
    BDDESCSALVAR,
    BDDATAEFEITO)
AS
SELECT
    X.BDCODEMP,
    X.BDCODCOL,
    X.BDDATACOL,
    X.BDCODMAS,
    X.BDSALBASECOL,
    X.BDDESCSALVAR,
    X.BDDATAEFEITO
FROM VW_VRH_EMP_TCOLCON_CALCDIA_MMIN W
JOIN VRH_EMP_TCOLCON_CALCDIA X ON (X.BDCODEMP = W.BDCODEMP AND X.BDCODCOL = W.BDCODCOL AND X.BDDATACOL = W.BDDATACOL)
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOLCON_CALCDIA_COMP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_CALCDIA_COMP(
    BDCODEMP,
    BDCODCOL,
    BDDATAEFEITO,
    BDCODMAS,
    BDSALBASECOL)
AS
select BASE.BDCODEMP, BASE.BDCODCOL, VIN.BDDATAEFEITO, VIN.BDCODMAS, VIN.BDSALBASECOL
from (select COL.BDCODEMP, COL.BDCODCOL, coalesce((select max(D1.BDDATAEFEITO)
                                                   from VRH_EMP_TCOLCON_CALCDIA D1
                                                   where D1.BDCODEMP = COL.BDCODEMP and
                                                         D1.BDCODCOL = COL.BDCODCOL and
                                                         cast(D1.BDDATAEFEITO as varchar(10)) <= (select trim(RDB$GET_CONTEXT('USER_SESSION', 'W_ULTDIAMES'))
                                                                                                  from RDB$DATABASE)),
             (select min(D2.BDDATAEFEITO)
              from VRH_EMP_TCOLCON_CALCDIA D2
              where D2.BDCODEMP = COL.BDCODEMP and
                    D2.BDCODCOL = COL.BDCODCOL)) as BDDATAEFEITO,

              coalesce(
                (select max(D1.BDDATACOL) from VRH_EMP_TCOLCON_CALCDIA D1 where D1.BDCODEMP = COL.BDCODEMP and D1.BDCODCOL = COL.BDCODCOL and cast(D1.BDDATAEFEITO as varchar(10)) <= (select trim(RDB$GET_CONTEXT('USER_SESSION', 'W_ULTDIAMES')) from RDB$DATABASE)),
                (select min(D2.BDDATACOL) from VRH_EMP_TCOLCON_CALCDIA D2 where D2.BDCODEMP = COL.BDCODEMP and D2.BDCODCOL = COL.BDCODCOL)
              ) as BDDATACOL
             from VRH_EMP_TCOLCON COL) as BASE, VRH_EMP_TCOLCON_CALCDIA VIN
where BASE.BDCODEMP = VIN.BDCODEMP and
      BASE.BDCODCOL = VIN.BDCODCOL and
      BASE.BDDATAEFEITO = VIN.BDDATAEFEITO and
      BASE.BDDATACOL = VIN.BDDATACOL
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOLCON_ESTAG_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_ESTAG_ATUAL(
BDCODEMP,
BDCODCOL,
BDCODEST,
BDCODINSTEST,
BDDATAEST,
BDNATEST,
BDNIVELEST,
BDAREATUEST,
BDAPOLICEEST,
BDVLRBOLSAEST,
BDDIASEST,
BDDATATERMEST,
BDCPFCOORDEST,
BDNOMCOORDEST,
BDCODAGENTEEST)
 AS 
SELECT est.bdcodemp, est.bdcodcol, est.bdcodest, est.bdcodinstest, est.bddataest, est.bdnatest, est.bdnivelest, est.bdareatuest, est.bdapoliceest,
       est.bdvlrbolsaest, est.bddiasest, est.bddatatermest, est.bdcpfcoordest, est.bdnomcoordest, est.bdcodagenteest
FROM vrh_emp_tcolcon_estagio est
JOIN (
SELECT est.bdcodemp, est.bdcodcol, MAX(est.bdcodest) bdcodest FROM vrh_emp_tcolcon_estagio est
JOIN (SELECT est.bdcodemp, est.bdcodcol, MAX(est.bddataest) bddataest
       FROM vrh_emp_tcolcon_estagio est
       WHERE est.bddataest <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) FROM rdb$database)
       GROUP BY est.bdcodemp, est.bdcodcol) ax ON (est.bdcodemp = ax.bdcodemp AND est.bdcodcol = ax.bdcodcol AND est.bddataest = ax.bddataest)
GROUP BY est.bdcodemp, est.bdcodcol
) ax ON (est.bdcodemp = ax.bdcodemp AND est.bdcodcol = ax.bdcodcol AND est.bdcodest = ax.bdcodest)
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOLCON_REF_MAX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_REF_MAX(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MAX(X.bdrefcol)
FROM vrh_emp_tcolcon_ref X
WHERE
  CAST(X.BDREFCOL AS VARCHAR(6)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOLCON_REF_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_REF_MIN(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MIN(X.bdrefcol)
FROM vrh_emp_tcolcon_ref X
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* View: VW_VRH_EMP_TCOLCON_REF */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_REF(
    BDCODEMP,
    BDCODCOL,
    BDCONTRCOL,
    BDINATIVO,
    BDREFCOL,
    BDUTILIZADESCSIMPLIFICADO)
AS
SELECT BASE.BDCODEMP, BASE.BDCODCOL, V.BDCONTRCOL, V.BDINATIVO, BASE.BDREFCOL, v.bdutilizadescsimplificado
FROM (
  SELECT
      X.bdcodemp,
      X.BDCODCOL,
      COALESCE
  (
      (SELECT MAX(d2.bdrefcol) FROM vrh_emp_tcolcon_ref d2 WHERE d2.bdcodemp = x.bdcodemp AND d2.bdcodcol = x.bdcodcol AND CAST(d2.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefcol) FROM vrh_emp_tcolcon_ref d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol)
  ) AS bdrefcol
  FROM vrh_emp_tcolcon x
) AS BASE, vrh_emp_tcolcon_ref v
WHERE BASE.bdcodemp = v.bdcodemp AND BASE.bdcodcol = v.bdcodcol AND BASE.bdREFCOL = v.bdREFCOL
;

--Sol. 18845 - Bruno L. R. - 08/06/2017 - Adicionado campo BDPERCGORJ // Adicionado campo BDDTAPOSENT Valmor 04/04/2022 
/* CREATE OR ALTER VIEW: VW_COLABORADORES_REF_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_COLABORADORES_REF_ATUAL(
    BDCODEMP,
    BDCODCOL,
    BDNOMCOL,
    BDNOMCOLUPPER,
    BDDATAADMCOL,
    BDCONTRCOL,
    BDCODCID,
    BDCODUF,
    BDGRAUINSTCOL,
    BDESTCIVCOL,
    BDSEXOCOL,
    BDDATANASCCOL,
    BDDATACADCOL,
    BDDATAADICCOL,
    BDCODCLA,
    BDGRUPOCLA,
    BDCODMEN,
    BDCODSINTRAB,
    BDCODBAN,
    BDCODAG,
    BDCTADEPCOL,
    BDDIGCTADEPCOL,
    BDTIPOCTACOL,
    BDMODOPAGTOCOL,
    BDCARTAOSALCOL,
    BDFORMAPAGTOCOL,
    BDNRODEPIRCOL,
    BDBASEIRRFADCOL,
    BDVALORPREVPRIVNCOL,
    BDVALORPREVPRIV13COL,
    BDDATAOPCAOFGTSCOL,
    BDCTAFGTSCOL,
    BDCATEGORIACOL,
    BDCATEGORIAESOCIAL,
    BDPERCFGTSCOL,
    BDOCORRENCIACOL,
    BDPERCRATCOL,
    BDPERCDESCFPASCOL,
    BDBASEINSSNCOL,
    BDVALORINSSNCOL,
    BDBASEIRRFNCOL,
    BDVALORIRRFNCOL,
    BDBASEINSS13COL,
    BDVALORINSS13COL,
    BDBASEIRRF13COL,
    BDVALORIRRF13COL,
    BDTIPOCOL,
    BDHORASMENSAISCOL,
    BDHORASSEMANAISCOL,
    BDHORASDIARIASCOL,
    BDPERCINSALUBCOL,
    BDINCIDINSALUBCOL,
    BDPERCPERCULCOL,
    BDINCIDPERICULCOL,
    BDPERCNOTURNOCOL,
    BDINCIDNOTURNOCOL,
    BDNRODEPSALFAMCOL,
    BDIGNORAFALTASFERCOL,
    BDCALCADIANTACOL,
    BDNAOARREDONDARCOL,
    BDIMPETIQUETACOL,
    BDCALCDSRRVCOL,
    BDCALCDSRHECOL,
    BDCALCDSRSALCOL,
    BDCALCVALTRANSCOL,
    BDCALCVALREFCOL,
    BDPERCADISAL,
    BDOBSCOL,
    BDCODGPS,
    BDDESCINSSDOIRCOL,
    BDCPFCOL,
    BDRGCOL,
    BDPISCOL,
    BDDESCCLA,
    BDINATIVO,
    BDREGIMEPARCIALCOL,
    BDPERCGORJ,
    BDCODMULTVINC,
    BDDTAPOSENT,
    BDPENSAONOVA,
    BDPERCIREXT,
    BDAULISTA,
    BDTRIBUTACAOEXTERIOR,
    BDDESCTRIBUTACAOIR)
AS
SELECT COLCON.BDCODEMP, COLCON.BDCODCOL, COLCAD.BDNOMCOL, COLCAD.BDNOMCOLUPPER, COLCON.BDDATAADMCOL, COLCON.BDCONTRCOL, COLCAD.BDCODCID, DOCREF.BDCODUF,
       COLCAD.BDGRAUINSTCOL, COLCAD.BDESTCIVCOL, COLCAD.BDSEXOCOL, COLCON.BDDATANASCCOL, COLCON.BDDATACADCOL, COLCON.BDDATAADICCOL,
       COLCON_VINC.BDCODCLA, CLASSE.BDGRUPOCLA,
       COL_VINC.BDCODMEN, COL_VINC.BDCODSINTRAB,
       COLCON_BANCO.BDCODBAN, COLCON_BANCO.BDCODAG, COLCON_BANCO.BDCTADEPCOL, COLCON_BANCO.BDDIGCTADEPCOL ,
       COLCON_BANCO.BDTIPOCTACOL, COLCON_BANCO.BDMODOPAGTOCOL, COLCON_BANCO.BDCARTAOSALCOL,
       COLCON_CALC.BDFORMAPAGTOCOL, COLCON_CALC.BDNRODEPIRCOL, COLCON_CALC.BDBASEIRRFADCOL ,
       COLCON_CALC.BDVALORPREVPRIVNCOL, COLCON_CALC.BDVALORPREVPRIV13COL,
       COLCON_FGTSGPS.BDDATAOPCAOFGTSCOL, COLCON_FGTSGPS.BDCTAFGTSCOL, COLCON_FGTSGPS.BDCATEGORIACOL , COLCON_FGTSGPS.BDCATEGORIAESOCIAL,
       COLCON_FGTSGPS.BDPERCFGTSCOL, COLCON_FGTSGPS.BDOCORRENCIACOL ,
       COLCON_FGTSGPS.BDPERCRATCOL, COLCON_FGTSGPS.BDPERCDESCFPASCOL,
       COLCON_MVINC.BDBASEINSSNCOL, COLCON_MVINC.BDVALORINSSNCOL, COLCON_MVINC.BDBASEIRRFNCOL ,
       COLCON_MVINC.BDVALORIRRFNCOL, COLCON_MVINC.BDBASEINSS13COL, COLCON_MVINC.BDVALORINSS13COL ,
       COLCON_MVINC.BDBASEIRRF13COL, COLCON_MVINC.BDVALORIRRF13COL,
       COL_CALC.BDTIPOCOL, COL_CALC.BDHORASMENSAISCOL, COL_CALC.BDHORASSEMANAISCOL, COL_CALC.BDHORASDIARIASCOL,
       COL_CALC.BDPERCINSALUBCOL, COL_CALC.BDINCIDINSALUBCOL, COL_CALC.BDPERCPERCULCOL, COL_CALC.BDINCIDPERICULCOL,
       COL_CALC.BDPERCNOTURNOCOL, COL_CALC.BDINCIDNOTURNOCOL, COL_CALC.BDNRODEPSALFAMCOL, COL_CALC.BDIGNORAFALTASFERCOL,
       COL_CALC.BDCALCADIANTACOL, COL_CALC.BDNAOARREDONDARCOL, COL_CALC.BDIMPETIQUETACOL, COL_CALC.BDCALCDSRRVCOL,
       COL_CALC.BDCALCDSRHECOL, COL_CALC.BDCALCDSRSALCOL, COL_CALC.BDCALCVALTRANSCOL, COL_CALC.BDCALCVALREFCOL, COL_CALC.BDPERCADISAL,
       COL_HISTF.BDOBSCOL, CON_VINC.BDCODGPS, CON_VINC.BDDESCINSSDOIRCOL,
       COLCON_DOC.BDCPFCOL, DOCREF.BDRGCOL, DOCREF.BDPISCOL, CLASSE.BDDESCCLA, COLREF.BDINATIVO, COL_CALC.BDREGIMEPARCIALCOL,
       COL_CALC.BDPERCGORJ, COLCON_FGTSGPS.BDCODMULTVINC,COL_HISTF2.bddtaposent,COLCON.BDPENSAONOVA, COL_HISTF2.BDPERCIREXT,
       COL_CALC.BDAULISTA,
       COL_HISTF2.BDTRIBUTACAOEXTERIOR, TIR.BDDESCFTB BDDESCTRIBUTACAOIR
FROM VRH_EMP_TCOLCON COLCON
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_VINC COLCON_VINC
  ON (COLCON_VINC.BDCODEMP = COLCON.BDCODEMP AND COLCON_VINC.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRH_EMP_TCOL_VINC COL_VINC
  ON (COL_VINC.BDCODEMP = COLCON.BDCODEMP AND COL_VINC.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRHF_EMP_TCOLCON_BANCO COLCON_BANCO
  ON (COLCON_BANCO.BDCODEMP = COLCON.BDCODEMP AND COLCON_BANCO.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRHF_EMP_TCOLCON_CALC COLCON_CALC
  ON (COLCON_CALC.BDCODEMP = COLCON.BDCODEMP AND COLCON_CALC.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRHF_EMP_TCOLCON_FGTSGPS COLCON_FGTSGPS
  ON (COLCON_FGTSGPS.BDCODEMP = COLCON.BDCODEMP AND COLCON_FGTSGPS.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN(select BDCODEMP, BDCODCOL, SUM(BDBASEINSSNCOL) BDBASEINSSNCOL, SUM(BDVALORINSSNCOL) BDVALORINSSNCOL,
   SUM(BDBASEIRRFNCOL) BDBASEIRRFNCOL, SUM(BDVALORIRRFNCOL) BDVALORIRRFNCOL, SUM(BDBASEINSS13COL) BDBASEINSS13COL,
   SUM(BDVALORINSS13COL) BDVALORINSS13COL, SUM(BDBASEIRRF13COL) BDBASEIRRF13COL, SUM(BDVALORIRRF13COL) BDVALORIRRF13COL
   from VW_VRHF_EMP_TCOLCON_MVINC
   group by BDCODEMP, BDCODCOL) COLCON_MVINC
  ON (COLCON_MVINC.BDCODEMP = COLCON.BDCODEMP AND COLCON_MVINC.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRHF_EMP_TCOL_CALC COL_CALC
  ON (COL_CALC.BDCODEMP = COLCON.BDCODEMP AND COL_CALC.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VRHF_EMP_TCOL_HIST COL_HISTF
  ON (COL_HISTF.BDCODEMP = COLCON.BDCODEMP AND COL_HISTF.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VRH_EMP_TCOL_HIST COL_HISTF2
  ON (COL_HISTF2.BDCODEMP = COLCON.BDCODEMP AND COL_HISTF2.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VRH_BASE_TFORMATRIBUTACAO TIR ON TIR.BDCODFTB = COL_HISTF2.BDTRIBUTACAOEXTERIOR
LEFT OUTER JOIN VW_VRHF_EMP_TCON_VINC CON_VINC
  ON (CON_VINC.BDCODEMP = COLCON.BDCODEMP AND CON_VINC.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC COLCON_DOC
  ON (COLCON_DOC.BDCODEMP = COLCON.BDCODEMP AND COLCON_DOC.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VRH_BASE_TCLASSE CLASSE
  ON (COLCON_VINC.BDCODCLA = CLASSE.BDCODCLA)
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_REF COLREF
  ON (COLREF.BDCODEMP = COLCON.BDCODEMP AND COLREF.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD
  ON (COLCAD.BDCODEMP = COLCON.BDCODEMP AND COLCAD.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF DOCREF
  ON (DOCREF.BDCODEMP = COLCON.BDCODEMP AND DOCREF.BDCODCOL = COLCON.BDCODCOL)
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_CAT (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_CAT(
BDCODEMP,
BDCODCOL,
BDCHAVE,
BDCODCID_CAT,
BDDATAACIDENTE,
BDDATAEMISSAO,
BDDATAULTIMODIA,
BDDATAOBITO,
BDEMITENTE,
BDNRCAT,
BDTIPOAFAST,
BDREGPOLICIAL,
BDAFASTAMENTO,
BDHORAACIDENTE,
BDTIPOCAT,
BDLOCALACIDENTE,
BDESPLOCALACIDENTE,
BDOBJETOCAUSADORACID,
BDDESCACIDENTE,
BDPARTESATINGIDAS,
BDAREAACIDENTE,
BDHOUVEOBITO,
BDREMUNMENSAL,
BDCODSITGER,
BDCNPJEMP,
BDNOMEMP,
BDBAIEMP,
BDCODCNAE,
BDNUMEMP,
BDENDEMP,
BDCODCID_EMP,
BDLOGREMP,
BDCEPEMP,
BDDDDEMP,
BDFONEEMP,
BDNOMCOL,
BDNOMMAECOL,
BDDATANASCCOL,
BDSEXOCOL,
BDCTPSCOL,
BDSERIECTPSCOL,
BDDSERIECTPSCOL,
BDDATAEMICTPSCOL,
BDCODUF_CTPS,
BDRGCOL,
BDDATAEMIRGCOL,
BDORGEMIRGCOL,
BDPISCOL,
BDLOGRCOL,
BDENDCOL,
BDCODCID_COL,
BDNUMCOL,
BDBAICOL,
BDCEPCOL,
BDDDDCOL,
BDFONECOL,
BDFILIACAOPREV,
BDAPOSENTADO,
BDESTCIVCOL,
BDSIGLAUFRG)
 AS 
SELECT
  CAT.BDCODEMP,
  CAT.BDCODCOL,
  CAT.BDCHAVE,
  CAT.BDCODCID,
  CAT.BDDATAACIDENTE,
  CAT.BDDATAEMISSAO,
  CAT.BDDATAULTIMODIA,
  CAT.BDDATAOBITO,
  CAT.BDEMITENTE,
  CAT.BDNRCAT,
  CAT.BDTIPOAFAST,
  CAT.BDREGPOLICIAL,
  CAT.BDAFASTAMENTO,
  CAT.BDHORAACIDENTE,
  CAT.BDTIPOCAT,
  CAT.BDLOCALACIDENTE,
  CAT.BDESPLOCALACIDENTE,
  CAT.BDOBJETOCAUSADORACID,
  CAT.BDDESCACIDENTE,
  CAT.BDPARTESATINGIDAS,
  CAT.BDAREAACIDENTE,
  CAT.BDHOUVEOBITO,
  CAT.BDREMUNMENSAL,
  CAT.BDCODSITGER,
  EMP.BDCNPJEMP,
  EMPR.BDNOMEMP,
  EMPR.BDBAIEMP,
  EMPR.BDCODCNAE,
  EMPR.BDNUMEMP,
  EMPR.BDENDEMP,
  EMPR.BDCODCID,
  EMPR.BDLOGREMP,
  EMPR.BDCEPEMP,
  EMPR.BDDDDEMP,
  EMPR.BDFONEEMP,

  COLCAD.BDNOMCOL,
  COL.BDNOMMAECOL,
  COL.BDDATANASCCOL,
  COLCAD.BDSEXOCOL,
  DOCREF.BDCTPSCOL,
  DOCREF.BDSERIECTPSCOL,
  DOCREF.BDDSERIECTPSCOL,
  DOCREF.BDDATAEMICTPSCOL,
  DOCREF.BDCODUF,
  DOCREF.BDRGCOL,
  DOCREF.BDDATAEMIRGCOL,
  DOCREF.BDORGEMIRGCOL,
  DOCREF.BDPISCOL,
  COLCAD.BDLOGRCOL,
  COLCAD.BDENDCOL,
  COLCAD.BDCODCID,
  COLCAD.BDNUMCOL,
  COLCAD.BDBAICOL,
  COLCAD.BDCEPCOL,
  COLCAD.BDDDDCOL,
  COLCAD.BDFONECOL,
  COLR.BDGRUPOCLA BDFILIACAOPREV,
  COLR.BDGRUPOCLA BDAPOSENTADO,
  COLCAD.BDESTCIVCOL,
  UFRG.BDSIGLAUF


FROM VRH_EMP_TCAT CAT
JOIN TEMPRESAS EMP ON (EMP.BDCODEMP = CAT.BDCODEMP)
JOIN VW_EMPRESAS_REF_ATUAL EMPR ON (EMPR.BDCODEMP = CAT.BDCODEMP)
JOIN VW_COLABORADORES COL ON (COL.BDCODEMP = CAT.BDCODEMP AND COL.BDCODCOL = CAT.BDCODCOL)
JOIN VW_COLABORADORES_REF_ATUAL COLR ON (COLR.BDCODEMP = CAT.BDCODEMP AND COLR.BDCODCOL = CAT.BDCODCOL)
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON (COLCAD.BDCODEMP = CAT.BDCODEMP AND COLCAD.BDCODCOL = CAT.BDCODCOL)
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF DOCREF ON (DOCREF.BDCODEMP = CAT.BDCODEMP AND DOCREF.BDCODCOL = CAT.BDCODCOL)
LEFT OUTER JOIN TUF UFRG ON (UFRG.BDCODUF = DOCREF.BDCODUFRG)
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOLCON_VINC_MAX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_VINC_MAX(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MAX(X.bdrefcol)
FROM VRH_EMP_TCOLCON_VINC X
WHERE
  CAST(X.BDREFCOL AS VARCHAR(6)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TCOLCON_VINC_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TCOLCON_VINC_MIN(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MIN(X.bdrefcol)
FROM VRH_EMP_TCOLCON_VINC X
--where
--  CAST(X.BDREFCOL as VARCHAR(6)) <=
--     (select TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
--      from rdb$database
--     )
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRH_EMP_TREEMBOLSO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_EMP_TREEMBOLSO(
BDCODEMP,
BDCODIMP,
BDORDEM,
BDVALOR,
BDREF,
BDTIPO)
 AS 
SELECT r.bdcodemp, r.bdcodimp, r.bdordem, r.bdvalor,
             COALESCE(r.bdreferencia,(SELECT MAX(bdref) FROM (SELECT comp.bdrefcgps bdref FROM vrh_emp_rcomp a
             JOIN vrhf_emp_tcompgps comp ON (a.bdchave= comp.bdchave AND a.bdcodemp = comp.bdcodemp)
             UNION ALL
             SELECT nf.bdrefnf FROM vrh_emp_rnf a
             JOIN vrhf_emp_tnotasfiscais nf ON (a.bdchave= nf.bdchave AND a.bdcodemp = nf.bdcodemp)
             UNION ALL
             SELECT d.bdreferencia FROM vrh_emp_hrcomp b
             JOIN vrhf_emp_thistcomp hb ON (b.bdchavedarfhistcomp= hb.bdchavedarfhistcomp AND b.bdcodemp = hb.bdcodempcompgps)
             JOIN tdarfpadrao d ON (hb.bdchavedarf = d.bdchavedarf AND hb.bdcodempcompgps = d.bdcodemp)
             UNION ALL
             SELECT d.bdreferencia FROM vrh_emp_hrded c
             JOIN vrhf_emp_thistoricogps hc ON (c.bdchavedarfhistgps= hc.bdchavedarfhistgps AND c.bdcodemp = hc.bdcodemp)
             JOIN tdarfpadrao d ON (hc.bdchavedarf = d.bdchavedarf AND hc.bdcodemp = d.bdcodemp)
             UNION ALL
             SELECT d.bdreferencia FROM vrh_emp_hrnf e
             JOIN vrhf_emp_thistnf he ON (e.BDCHAVEDARFHISTNF = he.bdchavedarfhistnf AND e.bdcodemp = he.bdcodemp)
             JOIN tdarfpadrao d ON (he.bdchavedarf = d.bdchavedarf AND he.bdcodemp = d.bdcodemp)
             ))) bdref, r.bdtipo
           FROM VRH_EMP_TREEMBOLSO r
;

/* CREATE OR ALTER VIEW: VW_VRH_FUNCOES_TFUC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_FUNCOES_TFUC(
    BDCODPLAFUC,
    BDCODTFUC,
    BDCODCBO,
    BDDESCTFUC,
    BDCODCBOTSIN,
    BDDESCCBO,
    BDDESCFUNCDET)
AS
SELECT
    X.bdcodplafuc,
    X.bdcodtfuc,
    X.bdcodcbo,
    X.bddesctfuc,
    X.bdcodcbotsin,
    CASE WHEN ((Y.bddesccbotsin IS NULL OR (Y.bddesccbotsin = '')) AND (Z.bddesccbo IS NULL OR (Z.bddesccbo = ''))) THEN X.bddesctfuc
         WHEN (Y.bddesccbotsin IS NULL OR (Y.bddesccbotsin = '')) THEN Z.bddesccbo
         ELSE Y.bddesccbotsin
    END BDDESCCBO,
    X.BDDESCFUNCDET
FROM vrh_funcoes_tfuc X
LEFT OUTER JOIN vrh_base_cbo_tsin Y ON (Y.bdcodcbo = X.bdcodcbo AND Y.bdcodcbotsin = X.bdcodcbotsin)
LEFT OUTER JOIN vrh_base_tcbo Z ON (Z.bdcodcbo = X.bdcodcbo)
;

/* CREATE OR ALTER VIEW: VW_VRH_TEMPRESAS_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRH_TEMPRESAS_REF(
    BDCODEMP,
    BDREFEMP,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDCODCENTROS,
    BDCODCID,
    BDCODCONT,
    BDCODCONTEF,
    BDCODCONTRH,
    BDCODNATJUR,
    BDCODCNAE,
    BDNOMEMP,
    BDNOMREDUZEMP,
    BDAPEEMP,
    BDENDEMP,
    BDNUMEMP,
    BDBAIEMP,
    BDCEPEMP,
    BDDDDEMP,
    BDFONEEMP,
    BDFAXEMP,
    BDEMAILEMP,
    BDCOMPLEMP,
    BDLOGREMP,
    BDIEEMP,
    BDIMEMP,
    BDSITEMP,
    BDDDDFAXEMP,
    BDDOCAUXILIAR,
    BDCODPLANOONLINE,
    BDSUFRAMA)
AS
SELECT
    emp.BDCODEMP,
    emp.BDREFEMP,
    dad.BDCODPLAPADRAO,
    dad.BDCODHIST,
    dad.BDCODCENTROS,
    dad.BDCODCID,
    dad.BDCODCONT,
    dad.BDCODCONTEF,
    dad.BDCODCONTRH,
    dad.BDCODNATJUR,
    dad.BDCODCNAE,
    dad.BDNOMEMP,
    dad.BDNOMREDUZEMP,
    dad.BDAPEEMP,
    dad.BDENDEMP,
    dad.BDNUMEMP,
    dad.BDBAIEMP,
    dad.BDCEPEMP,
    dad.BDDDDEMP,
    dad.BDFONEEMP,
    dad.BDFAXEMP,
    dad.BDEMAILEMP,
    dad.BDCOMPLEMP,
    dad.BDLOGREMP,
    dad.BDIEEMP,
    dad.BDIMEMP,
    dad.BDSITEMP,
    dad.BDDDDFAXEMP,    
    dad.BDDOCAUXILIAR,
    dad.BDCODPLANOONLINE,
    dad.BDSUFRAMA
FROM
(
  SELECT
      X.bdcodemp,
      COALESCE
  (
      (SELECT MAX(d2.bdrefemp) FROM tempresas_ref d2 WHERE d2.bdcodemp = x.bdcodemp AND CAST(d2.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefemp) FROM tempresas_ref d1 WHERE d1.bdcodemp = x.bdcodemp)
  ) AS bdrefemp
  FROM TEMPRESAS x
  where((x.bdexcluiremp is null)or(upper(x.bdexcluiremp)<>'TRUE'))

) AS EMP, tempresas_ref DAD
WHERE EMP.BDCODEMP = DAD.BDCODEMP AND EMP.BDREFEMP = DAD.BDREFEMP;

/* CREATE OR ALTER VIEW: VW_VRHF_13SAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_13SAL(
BDCODEMP,
BDCODCOL,
BDREF,
BDCODVER,
BDREFV,
BDREFAUXV,
BDVALV,
BDIGNREFAV,
BDIGNREFV,
BDIGNVALV,
BDMESESPROP13,
BDBASEIR13,
BDBASEFGTS13,
BDFGTS13,
BDFGTSCS13,
BDDATABAIXA13,
BDREFBAIXA13,
BDPERCIR13,
BDVALORIR13,
BDBASEINSS13,
BDPERCINSS13,
BDVALORINSS13,
BDBRAIS13,
BDDEP13,
BDSALBASE13,
BDARREPROV13,
BDARREDESC13,
BDVAL13,
BDBSALFAM13,
BDSALFAM13,
BDANO13,
BDBASEPIS13,
BDDATAPGTO13)
 AS 
SELECT
  VFOL13.BDCODEMP,
  VFOL13.BDCODCOL,
  VFOL13.BDREF13,
  VFOL13.BDCODVER,
  VFOL13.BDREFV13,
  VFOL13.BDREFAUXV13,
  VFOL13.BDVALV13,
  VFOL13.BDIGNREFAV13,
  VFOL13.BDIGNREFV13,
  VFOL13.BDIGNVALV13,
  DFOL13.BDMESESPROP13,
  DFOL13.BDBASEIR13,
  DFOL13.BDBASEFGTS13,
  DFOL13.BDFGTS13,
  DFOL13.BDFGTSCS13,
  DFOL13.BDDATABAIXA13,
  DFOL13.BDREFBAIXA13,
  DFOL13.BDPERCIR13,
  DFOL13.BDVALORIR13,
  DFOL13.BDBASEINSS13,
  DFOL13.BDPERCINSS13,
  DFOL13.BDVALORINSS13,
  DFOL13.BDBRAIS13,
  DFOL13.BDDEP13,
  DFOL13.BDSALBASE13,
  DFOL13.BDARREPROV13,
  DFOL13.BDARREDESC13,
  DFOL13.BDVAL13,
  DFOL13.BDBSALFAM13,
  DFOL13.BDSALFAM13,
  DFOL13.BDANO13,
  DFOL13.BDBASEPIS13,
  DFOL13.BDDATAPGTO13

FROM VRHF_EMP_TVERBA13 VFOL13
LEFT OUTER JOIN vrhf_emp_t13sal DFOL13
  ON (DFOL13.BDCODEMP = VFOL13.BDCODEMP AND DFOL13.BDCODCOL = VFOL13.BDCODCOL AND DFOL13.BDREF13 = VFOL13.BDREF13)
;

/* CREATE OR ALTER VIEW: VW_VRHF_A13SAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_A13SAL(
BDCODEMP,
BDCODCOL,
BDREFA13,
BDCODVER,
BDREFVA13,
BDREFAUXVA13,
BDVALVA13,
BDIGNREFVA13,
BDIGNVALVA13,
BDANOA13,
BDPERCA13,
BDVALA13,
BDTIPOPROPA13,
BDMESESPROPA13,
BDBASEIRA13,
BDFGTSA13,
BDFGTSCSA13,
BDBASEFGTSA13,
BDDATABAIXAA13,
BDREFBAIXAA13,
BDPERCIRA13,
BDVALORIRA13,
BDBSALFAMA13,
BDSALFAMA13,
BDBRAISA13,
BDDEPA13,
BDSALBASEA13,
BDARREPROVA13,
BDARREDESCA13,
BDDATAPGTOA13)
 AS 
SELECT
   VFOLA13.BDCODEMP,
   VFOLA13.BDCODCOL,
   VFOLA13.BDREFA13,
   VFOLA13.BDCODVER,
   VFOLA13.BDREFVA13,
   VFOLA13.BDREFAUXVA13,
   VFOLA13.BDVALVA13,
   VFOLA13.BDIGNREFVA13,
   VFOLA13.BDIGNVALVA13,
   DFOLA13.BDANOA13,
   DFOLA13.BDPERCA13,
   DFOLA13.BDVALA13,
   DFOLA13.BDTIPOPROPA13,
   DFOLA13.BDMESESPROPA13,
   DFOLA13.BDBASEIRA13,
   DFOLA13.BDFGTSA13,
   DFOLA13.BDFGTSCSA13,
   DFOLA13.BDBASEFGTSA13,
   DFOLA13.BDDATABAIXAA13,
   DFOLA13.BDREFBAIXAA13,
   DFOLA13.BDPERCIRA13,
   DFOLA13.BDVALORIRA13,
   DFOLA13.BDBSALFAMA13,
   DFOLA13.BDSALFAMA13,
   DFOLA13.BDBRAISA13,
   DFOLA13.BDDEPA13,
   DFOLA13.BDSALBASEA13,
   DFOLA13.BDARREPROVA13,
   DFOLA13.BDARREDESCA13,
   DFOLA13.BDDATAPGTOA13

FROM vrhf_emp_tverbaa13 VFOLA13
LEFT OUTER JOIN vrhf_emp_ta13sal DFOLA13
  ON (DFOLA13.BDCODEMP = VFOLA13.BDCODEMP AND DFOLA13.BDCODCOL = VFOLA13.BDCODCOL AND DFOLA13.bdrefa13 = VFOLA13.bdrefa13)
;

/* CREATE OR ALTER VIEW: VW_VRHF_ADIANTAMENTO_SAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_ADIANTAMENTO_SAL(
BDCODEMP,
BDCODCOL,
BDCODVER,
BDREFVAD,
BDREFAUXVAD,
BDVALVAD,
BDIGNREFAVAD,
BDIGNREFVAD,
BDIGNVALVAD,
BDDATAAD,
BDBASEAD,
BDTIPOAD,
BDVALPERCAD,
BDBASEIRAD,
BDDATABAIXAAD,
BDREFBAIXAAD,
BDVALORIRAD,
BDPERCIRAD,
BDCREDITO,
BDDEBITO,
BDREFAD)
 AS 
SELECT AD.BDCODEMP,
       AD.BDCODCOL,
       AD.BDCODVER,
       AD.BDREFVAD,
       AD.BDREFAUXVAD,
       AD.BDVALVAD,
       AD.BDIGNREFAVAD,
       AD.BDIGNREFVAD,
       AD.BDIGNVALVAD,
       ADS.BDDATAAD,
       ADS.BDBASEAD,
       ADS.BDTIPOAD,
       ADS.BDVALPERCAD,
       ADS.BDBASEIRAD,
       ADS.BDDATABAIXAAD,
       ADS.BDREFBAIXAAD,
       ADS.BDVALORIRAD,
       ADS.BDPERCIRAD,
       ADS.BDCREDITOAD,
       ADS.BDDEBITOAD,
       ADS.BDREFAD
FROM
  VRHF_EMP_TVERBAAD AD,
  VRHF_EMP_TADSAL ADS
WHERE
  ADS.BDCODEMP = AD.BDCODEMP AND ADS.BDCODCOL = AD.BDCODCOL AND ADS.BDDATAAD = AD.BDDATAAD
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TREF_REF_MAXMIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TREF_REF_MAXMIN(
BDCODCONVREF,
BDREF)
 AS 
SELECT bdcodconvref,
    COALESCE
    (
      (SELECT MAX(rf2.bdref) FROM VRHF_BASE_TCONVREFEICAO_REF rf2 WHERE rf2.bdref <=
         (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database) AND rf2.bdcodconvref = X.bdcodconvref),
      (SELECT MIN(rf2.bdref) FROM VRHF_BASE_TCONVREFEICAO_REF rf2 WHERE rf2.bdcodconvref = X.bdcodconvref)
    ) AS bdREF
    FROM VRHF_BASE_TCONVREFEICAO_REF X
    GROUP BY X.bdcodconvref
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TCONVREFEICAO_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TCONVREFEICAO_REF(
BDCODCONVREF,
BDDESC,
BDVALUNI)
 AS 
SELECT X.bdcodconvref, X.bddesc, val.bdvaluni
FROM VRHF_BASE_TCONVREFEICAO X
LEFT OUTER JOIN VW_VRHF_BASE_TREF_REF_MAXMIN ref ON (X.bdcodconvref = ref.bdcodconvref)
LEFT OUTER JOIN VRHF_BASE_TCONVREFEICAO_REF val ON (X.bdcodconvref = val.bdcodconvref AND ref.bdref = val.bdref)
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPCALC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPCALC(
    BDCODEMP,
    BDPAGEMP,
    BDFECHAMESEMP,
    BDFECHAVTEMP,
    BDARREMP,
    BDTIPOARREMP,
    BDTIPOFEREMP,
    BDSOMSALFEREMP,
    BDTIPOAD13EMP,
    BDSOMSALAD13EMP,
    BDPERCADSALEMP,
    BDREFHOREMP,
    BDLICREMFEREMP,
    BDESTOUROEMP,
    BDESTOURORESEMP,
    BDFALFEREMP,
    BDFALHORFEREMP,
    BDDEPIRRESCEMP,
    BDARREFALFER,
    BDMESDSREMP,
    BDANOSAVPREVIOIND,
    BDTIPCALCFERCOLINF,
    BDTIPCALCFERCOLSUP,
    BDLIMINARAVPREVEMP,
    BDARREDONDAFN,
    BDARREDONDAFC,
    BDARREDONDAFE,
    BDARREDONDAA13,
    BDARREDONDA13,
    BDARREDONDAC13,
    BDARREDONDAAD,
    BDARREDONDAAU,
    BDARREDONDAFA,
    BDARREDONDAFTINT,
    BDPAGEMPCONTR,
    BDDESCFALHORASDIAS,
    BDPERCLIMIDESCPAR,
    BDDSRMEDATUSAL,
    BDIDADESAUDEEMP,
    BDCODEMPPONTO,
    BDCONSIDERAFERICIDADETOM,
    BDRATEIOINTEGRALVER)
AS
SELECT
    BASE.bdcodemp,
    VIN.bdpagemp,
    VIN.bdfechamesemp,
    VIN.bdfechavtemp,
    VIN.bdarremp,
    VIN.bdtipoarremp,
    VIN.bdtipoferemp,
    VIN.bdsomsalferemp,
    VIN.bdtipoad13emp,
    VIN.bdsomsalad13emp,
    VIN.bdpercadsalemp,
    VIN.bdrefhoremp,
    VIN.bdlicremferemp,
    VIN.bdestouroemp,
    VIN.bdestouroresemp,
    VIN.bdfalferemp,
    VIN.bdfalhorferemp,
    VIN.bddepirrescemp,
    VIN.bdarrefalfer,
    VIN.bdmesdsremp,
    COALESCE(VIN.BDANOSAVPREVIOIND,0),
    COALESCE(VIN.bdtipcalcfercolinf,2),
    COALESCE(vin.bdtipcalcfercolsup,4),
    VIN.bdliminaravprevemp,
    VIN.bdarredondafn,
    VIN.bdarredondafc,
    VIN.bdarredondafe,
    VIN.bdarredondaa13,
    VIN.bdarredonda13,
    VIN.bdarredondac13,
    VIN.bdarredondaad,
    VIN.bdarredondaau,
    VIN.bdarredondafa,
    VIN.bdarredondaftint, 
    VIN.bdpagempcontr,
    VIN.bddescfalhorasdias,
    VIN.BDPERCLIMIDESCPAR,  
    VIN.BDDSRMEDATUSAL,
    VIN.BDIDADESAUDEEMP,
    VIN.BDCODEMPPONTO,
    VIN.bdconsiderafericidadetom,
    VIN.BDRATEIOINTEGRALVER
FROM
(
  SELECT
      X.bdcodemp,
      COALESCE
  (
      (SELECT MAX(d2.bdrefemp) FROM vrhf_base_tempcalc d2 WHERE d2.bdcodemp = x.bdcodemp AND CAST(d2.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefemp) FROM vrhf_base_tempcalc d1 WHERE d1.bdcodemp = x.bdcodemp)
  ) AS bdrefemp
  FROM TEMPRESAS x
  where((x.bdexcluiremp is null)or(upper(x.bdexcluiremp)<>'TRUE'))

) AS BASE, vrhf_base_tempcalc VIN
WHERE BASE.BDCODEMP = VIN.BDCODEMP AND BASE.BDREFEMP = VIN.BDREFEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPCALC_MAXREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPCALC_MAXREF(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
    X.bdcodemp,
    MAX(X.bdrefemp)
FROM vrhf_base_tempcalc X
WHERE CAST(X.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
GROUP BY X.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPCALC_MINREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPCALC_MINREF(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
    X.bdcodemp,
    MIN(X.bdrefemp)
FROM vrhf_base_tempcalc X
GROUP BY X.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPDIRF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPDIRF(
BDCODEMP,
BDREFEMP,
BDCODFTB,
BDCODBREND)
 AS 
SELECT X.BDCODEMP, X.BDREFEMP, X.BDCODFTB, X.BDCODBREND
FROM VRHF_BASE_TEMPDIRF X
WHERE X.BDREFEMP =
      (
       SELECT MAX(Y.BDREFEMP)
       FROM VRHF_BASE_TEMPDIRF Y
       WHERE Y.BDCODEMP = X.BDCODEMP AND
             CAST(Y.BDREFEMP AS VARCHAR(6)) <=
                (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
                 FROM rdb$database
                )
      )
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPESOCIAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPESOCIAL(
    BDCODEMP,
    BDREFEMP,
    BDCODCLATRI,
    BDESCOOPERATIVA,
    BDESCONSTRUTORA,
    BDESFGTSFIN,
    BDESDEBAUTFGTS,
    BDESAGERECFGTS,
    BDESSMSRESP,
    BDAPURAT,
    BDAPUFAP,
    BDACINTISENMULTA,
    BDSOCOSTCONTAPART,
    BDINDSITESPECIAL,
    BDINDCCONTRAAPRENDIZ,
    BDINDCCONTRAPCD,
    BDINDICATIVOREGELETR,
    BDINDICEMPMATRIZ,
    BDRELPORINTERM,
    BDCNPJEFR)
AS
SELECT
    BASE.BDCODEMP,
    ESOCIAL.BDREFEMP,
    ESOCIAL.BDCODCLATRI,
    ESOCIAL.BDESCOOPERATIVA,
    ESOCIAL.BDESCONSTRUTORA,
    ESOCIAL.BDESFGTSFIN,
    ESOCIAL.BDESDEBAUTFGTS,
    ESOCIAL.BDESAGERECFGTS,
    ESOCIAL.BDESSMSRESP,
    ESOCIAL.BDAPURAT,
    ESOCIAL.BDAPUFAP,
    ESOCIAL.BDACINTISENMULTA,
    ESOCIAL.BDSOCOSTCONTAPART,
    ESOCIAL.BDINDSITESPECIAL,
    ESOCIAL.BDINDCCONTRAAPRENDIZ,
    ESOCIAL.BDINDCCONTRAPCD,
    ESOCIAL.BDINDICATIVOREGELETR,
    ESOCIAL.BDINDICEMPMATRIZ,
    ESOCIAL.BDRELPORINTERM,
    ESOCIAL.BDCNPJEFR

FROM
(
  SELECT
      X.bdcodemp,
      COALESCE
  (
      (SELECT MAX(d2.bdrefemp) FROM vrhf_base_tempesocial d2 WHERE d2.bdcodemp = x.bdcodemp AND CAST(d2.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefemp) FROM vrhf_base_tempesocial d1 WHERE d1.bdcodemp = x.bdcodemp)
  ) AS bdrefemp
  FROM TEMPRESAS x
  where((x.bdexcluiremp is null)or(upper(x.bdexcluiremp)<>'TRUE'))

) AS BASE, vrhf_base_tempesocial ESOCIAL
WHERE BASE.BDCODEMP = ESOCIAL.BDCODEMP AND BASE.BDREFEMP = ESOCIAL.BDREFEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPGPS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPGPS(
    BDCODEMP,
    BDREFEMP,
    BDCODGPS,
    BDCNAERATEMP,
    BDEMPEMP,
    BDAUTEMP,
    BDFUNEMP,
    BDCODFPASTERC,
    BDSIMPLESGPS,
    BDFAP,
    BDCODFPAS,
    BDCODTERC,
    BDPERTERC,
    BDCCATVCONCOM,
    BDINDCOMP,
    BDDESONTOMAEMP,
    BDCODIGOTERC,
    BDCODTRIBRUR,
    BDATUTAB,
    BDSALEDU,
    BDINCRA,
    BDSENAI,
    BDSESI,
    BDSENAC,
    BDSESC,
    BDSEBRAE,
    BDDPC,
    BDFUNAERO,
    BDSENAR,
    BDSEST,
    BDSENAT,
    BDSESCOOP,
    BDTOMADORNO13EMP, /* 216919 - Nnao retirado or possuir dependencias */
    BDRATEIO13SAL)
AS
SELECT
    BASE.bdcodemp,
    BASE.BDREFEMP,
    VIN.bdcodrec,
    VIN.bdcnaeratemp,
    VIN.bdempemp,
    VIN.bdautemp,
    VIN.bdfunemp,
    VIN.bdcodfpasterc,
    VIN.bdsimplesgps,
    VIN.BDFAP,
    w.bdcodfpas,
    TER.BDCODTERC,
    coalesce(w.BDSALEDU, 0) + coalesce(w.BDINCRA, 0) +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAI, 0) * 0.5 else coalesce(w.BDSENAI, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESI, 0) * 0.5 else coalesce(w.BDSESI, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAC, 0) * 0.5 else coalesce(w.BDSENAC, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESC, 0) * 0.5 else coalesce(w.BDSESC, 0) end +
      coalesce(w.BDSEBRAE, 0) +
      coalesce(w.BDDPC, 0) +
      coalesce(w.BDFUNAERO, 0) +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAR, 0) * 0.5 else coalesce(w.BDSENAR, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSEST, 0) * 0.5 else coalesce(w.BDSEST, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAT, 0) * 0.5 else coalesce(w.BDSENAT, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESCOOP, 0) * 0.5 else coalesce(w.BDSESCOOP, 0) end
      ,
    VIN.BDCCATVCONCOM,
    VIN.BDINDCOMP,
    VIN.BDDESONTOMAEMP,
    w.BDCODTERC,
    VIN.BDCODTRIBRUR,
    upper(coalesce(w.BDATUTAB, 'FALSE')),
    w.BDSALEDU,
    w.BDINCRA,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAI, 0) * 0.5 else w.BDSENAI end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESI, 0) * 0.5 else w.BDSESI end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAC, 0) * 0.5 else w.BDSENAC end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESC, 0) * 0.5 else w.BDSESC end,
    w.BDSEBRAE,
    w.BDDPC,
    w.BDFUNAERO,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAR, 0) * 0.5 else w.BDSENAR end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSEST, 0) * 0.5 else w.BDSEST end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAT, 0) * 0.5 else w.BDSENAT end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESCOOP, 0) * 0.5 else w.BDSESCOOP end,
    upper(coalesce(VIN.BDTOMADORNO13EMP, 'FALSE')) ,
    VIN.BDRATEIO13SAL
FROM
(
  SELECT
      X.bdcodemp,
      COALESCE
  (
      (SELECT MAX(d2.bdrefemp) FROM vrhf_base_tempgps d2 WHERE d2.bdcodemp = x.bdcodemp AND CAST(d2.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefemp) FROM vrhf_base_tempgps d1 WHERE d1.bdcodemp = x.bdcodemp)
  ) AS bdrefemp,
  (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) BDREFATU FROM rdb$database) BDREFATU
  FROM TEMPRESAS x
  where((x.bdexcluiremp is null)or(upper(x.bdexcluiremp)<>'TRUE'))
) AS BASE
JOIN vrhf_base_tempgps VIN ON (VIN.BDCODEMP = BASE.BDCODEMP AND VIN.BDREFEMP = BASE.BDREFEMP)
LEFT OUTER JOIN VRH_BASE_TFPAS_TERCEIROS w ON (w.bdcodfpasterc = VIN.bdcodfpasterc)
LEFT OUTER JOIN VRH_BASE_TTERCEIROS TER ON (TER.BDCODIGO = w.BDCODTERC)
LEFT OUTER JOIN VRHF_BASE_TEMPMP932 MP932 ON (MP932.BDCODEMP = BASE.BDCODEMP)
;


/* View: VW_VRHF_BASE_TEMPGPS_PGTO */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPGPS_PGTO(
    BDCODEMP,
    BDREFEMP,
    BDCODGPS,
    BDCNAERATEMP,
    BDEMPEMP,
    BDAUTEMP,
    BDFUNEMP,
    BDCODFPASTERC,
    BDSIMPLESGPS,
    BDFAP,
    BDCODFPAS,
    BDCODTERC,
    BDPERTERC,
    BDCCATVCONCOM,
    BDINDCOMP,
    BDDESONTOMAEMP,
    BDCODIGOTERC,
    BDCODTRIBRUR,
    BDATUTAB,
    BDSALEDU,
    BDINCRA,
    BDSENAI,
    BDSESI,
    BDSENAC,
    BDSESC,
    BDSEBRAE,
    BDDPC,
    BDFUNAERO,
    BDSENAR,
    BDSEST,
    BDSENAT,
    BDSESCOOP,
    BDRATEIO13SAL)
AS
SELECT
    BASE.bdcodemp,
    BASE.BDREFEMP,
    VIN.bdcodrec,
    VIN.bdcnaeratemp,
    VIN.bdempemp,
    VIN.bdautemp,
    VIN.bdfunemp,
    VIN.bdcodfpasterc,
    VIN.bdsimplesgps,
    VIN.BDFAP,
    w.bdcodfpas,
    TER.BDCODTERC,
    coalesce(w.BDSALEDU, 0) + coalesce(w.BDINCRA, 0) +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAI, 0) * 0.5 else coalesce(w.BDSENAI, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESI, 0) * 0.5 else coalesce(w.BDSESI, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAC, 0) * 0.5 else coalesce(w.BDSENAC, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESC, 0) * 0.5 else coalesce(w.BDSESC, 0) end +
      coalesce(w.BDSEBRAE, 0) +
      coalesce(w.BDDPC, 0) +
      coalesce(w.BDFUNAERO, 0) +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAR, 0) * 0.5 else coalesce(w.BDSENAR, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSEST, 0) * 0.5 else coalesce(w.BDSEST, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAT, 0) * 0.5 else coalesce(w.BDSENAT, 0) end +
      case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESCOOP, 0) * 0.5 else coalesce(w.BDSESCOOP, 0) end,
    VIN.BDCCATVCONCOM,
    VIN.BDINDCOMP,
    VIN.BDDESONTOMAEMP,
    w.BDCODTERC,
    VIN.BDCODTRIBRUR,
    upper(coalesce(w.BDATUTAB, 'FALSE')),
    w.BDSALEDU,
    w.BDINCRA,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAI, 0) * 0.5 else w.BDSENAI end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESI, 0) * 0.5 else w.BDSESI end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAC, 0) * 0.5 else w.BDSENAC end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESC, 0) * 0.5 else w.BDSESC end,
    w.BDSEBRAE,
    w.BDDPC,
    w.BDFUNAERO,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAR, 0) * 0.5 else w.BDSENAR end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSEST, 0) * 0.5 else w.BDSEST end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAT, 0) * 0.5 else w.BDSENAT end,
    case when coalesce(CAST(BASE.BDREFATU AS INTEGER), 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESCOOP, 0) * 0.5 else w.BDSESCOOP end,
    VIN.BDRATEIO13SAL
FROM
(
  SELECT
      X.bdcodemp,
      COALESCE
  (
      (SELECT MAX(d2.bdrefemp) FROM vrhf_base_tempgps d2 WHERE d2.bdcodemp = x.bdcodemp AND CAST(d2.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMESPGTO')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefemp) FROM vrhf_base_tempgps d1 WHERE d1.bdcodemp = x.bdcodemp)
  ) AS bdrefemp,
  (SELECT COALESCE(CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMESPGTO'))) AS INTEGER), 0) FROM rdb$database) BDREFATU
  FROM TEMPRESAS x
  where((x.bdexcluiremp is null)or(upper(x.bdexcluiremp)<>'TRUE'))

) AS BASE
JOIN vrhf_base_tempgps VIN ON (VIN.BDCODEMP = BASE.BDCODEMP AND VIN.BDREFEMP = BASE.BDREFEMP)
LEFT OUTER JOIN VRH_BASE_TFPAS_TERCEIROS w ON (w.bdcodfpasterc = VIN.bdcodfpasterc)
LEFT OUTER JOIN VRH_BASE_TTERCEIROS TER ON (TER.BDCODIGO = w.BDCODTERC)
LEFT OUTER JOIN VRHF_BASE_TEMPMP932 MP932 on (MP932.BDCODEMP = BASE.BDCODEMP)
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPGPS_MINREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPGPS_MINREF(
    BDCODEMP,
    BDREFEMP,
    BDREFATU)
AS
SELECT
    X.bdcodemp,
    MIN(X.bdrefemp),
    (SELECT COALESCE(CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER), 0) FROM rdb$database)
FROM vrhf_base_tempgps X
GROUP BY X.BDCODEMP
;

CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPGPS_MAXREF(
    BDCODEMP,
    BDREFEMP,
    BDREFATU)
AS
SELECT
    X.bdcodemp,
    MAX(X.bdrefemp),
    (SELECT COALESCE(CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER), 0) FROM rdb$database)
FROM vrhf_base_tempgps X
WHERE CAST(X.BDREFEMP AS VARCHAR(6)) <=
          (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
          FROM rdb$database
         )
GROUP BY X.BDCODEMP
;

/* View: VW_VRHF_BASE_TEMPGPS_JOIN */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPGPS_JOIN(
    BDCODEMP,
    BDCODGPS,
    BDCNAERATEMP,
    BDEMPEMP,
    BDAUTEMP,
    BDFUNEMP,
    BDCODFPASTERC,
    BDSIMPLESGPS,
    BDFAP,
    BDCODFPAS,
    BDCODTERC,
    BDPERTERC,
    BDCCATVCONCOM,
    BDDESONTOMAEMP,
    BDCODTRIBRUR,
    BDATUTAB,
    BDSALEDU,
    BDINCRA,
    BDSENAI,
    BDSESI,
    BDSENAC,
    BDSESC,
    BDSEBRAE,
    BDDPC,
    BDFUNAERO,
    BDSENAR,
    BDSEST,
    BDSENAT,
    BDSESCOOP,
    BDRATEIO13SAL)
AS
SELECT
    X.bdcodemp,
    X.bdcodrec,
    X.bdcnaeratemp,
    X.bdempemp,
    X.bdautemp,
    X.bdfunemp,
    X.bdcodfpasterc,
    X.bdsimplesgps,
    x.BDFAP,
    w.bdcodfpas,
    w.bdcodterc,
      coalesce(w.BDSALEDU, 0) +
      coalesce(w.BDINCRA, 0) +
      case when coalesce(z.BDREFATU, y.bdrefatu, 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAI, 0) * 0.5 else coalesce(w.BDSENAI, 0) end +
      case when coalesce(z.BDREFATU, y.bdrefatu, 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESI, 0) * 0.5 else coalesce(w.BDSESI, 0) end +
      case when coalesce(z.BDREFATU, y.bdrefatu, 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAC, 0) * 0.5 else coalesce(w.BDSENAC, 0) end +
      case when coalesce(z.BDREFATU, y.bdrefatu, 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESC, 0) * 0.5 else coalesce(w.BDSESC, 0) end +
      coalesce(w.BDSEBRAE, 0) +
      coalesce(w.BDDPC, 0) +
      coalesce(w.BDFUNAERO, 0) +
      case when coalesce(z.BDREFATU, y.bdrefatu, 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAR, 0) * 0.5 else coalesce(w.BDSENAR, 0) end +
      case when coalesce(z.BDREFATU, y.bdrefatu, 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSEST, 0) * 0.5 else coalesce(w.BDSEST, 0) end +
      case when coalesce(z.BDREFATU, y.bdrefatu, 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAT, 0) * 0.5 else coalesce(w.BDSENAT, 0) end +
      case when coalesce(z.BDREFATU, y.bdrefatu, 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESCOOP, 0) * 0.5 else coalesce(w.BDSESCOOP, 0) end
    ,
    x.bdccatvconcom,
    x.BDDESONTOMAEMP,
    x.BDCODTRIBRUR,
    upper(coalesce(w.BDATUTAB, 'FALSE')),
    w.BDSALEDU,
    w.BDINCRA,
    case when coalesce(z.BDREFATU, y.bdrefatu, 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAI, 0) * 0.5 else w.BDSENAI end,
    case when coalesce(z.BDREFATU, y.bdrefatu, 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESI, 0) * 0.5 else w.BDSESI end,
    case when coalesce(z.BDREFATU, y.bdrefatu, 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAC, 0) * 0.5 else w.BDSENAC end,
    case when coalesce(z.BDREFATU, y.bdrefatu, 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESC, 0) * 0.5 else w.BDSESC end,
    w.BDSEBRAE,
    w.BDDPC,
    w.BDFUNAERO,
    case when coalesce(z.BDREFATU, y.bdrefatu, 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAR, 0) * 0.5 else w.BDSENAR end,
    case when coalesce(z.BDREFATU, y.bdrefatu, 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSEST, 0) * 0.5 else w.BDSEST end,
    case when coalesce(z.BDREFATU, y.bdrefatu, 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSENAT, 0) * 0.5 else w.BDSENAT end,
    case when coalesce(z.BDREFATU, y.bdrefatu, 0) between 202004 and 202006 and upper(coalesce(MP932.BDNAOAPLICAMP932, 'FALSE')) = 'FALSE' then coalesce(w.BDSESCOOP, 0) * 0.5 else w.BDSESCOOP end,
    x.BDRATEIO13SAL

FROM vrhf_base_tempgps X
LEFT OUTER JOIN VRH_BASE_TFPAS_TERCEIROS w ON (w.bdcodfpasterc = x.bdcodfpasterc)
LEFT OUTER JOIN vw_vrhf_base_tempgps_maxref Z ON (Z.BDCODEMP = x.BDCODEMP)
JOIN vw_vrhf_base_tempgps_minref Y ON (Z.BDCODEMP = y.BDCODEMP)
LEFT OUTER JOIN VRHF_BASE_TEMPMP932 MP932 ON (MP932.BDCODEMP = X.BDCODEMP)
WHERE x.bdrefemp = COALESCE(z.bdrefemp,y.bdrefemp)
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPGRCS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPGRCS(
BDCODEMP,
BDCODSINPAT,
BDCAPSOCEMP,
BDTIPOESTABE)
 AS 
SELECT
    BASE.bdcodemp,
    REF.bdcodsinpat,
    REF.bdcapsocemp,
    REF.bdtipoestabe
FROM
(
  SELECT
      X.bdcodemp,
      COALESCE
  (
      (SELECT MAX(d2.bdrefemp) FROM vrhf_base_tempgrcs d2 WHERE d2.bdcodemp = x.bdcodemp AND CAST(d2.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefemp) FROM vrhf_base_tempgrcs d1 WHERE d1.bdcodemp = x.bdcodemp)
  ) AS bdrefemp
  FROM TEMPRESAS x
  where((x.bdexcluiremp is null)or(upper(x.bdexcluiremp)<>'TRUE'))
) AS BASE, vrhf_base_tempgrcs REF
WHERE BASE.BDCODEMP = REF.BDCODEMP AND BASE.BDREFEMP = REF.BDREFEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPGRCS_MAXREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPGRCS_MAXREF(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
    X.bdcodemp,
    MAX(X.bdrefemp)
FROM vrhf_base_tempgrcs X
WHERE CAST(X.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
GROUP BY X.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPGRCS_MINREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPGRCS_MINREF(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
    X.bdcodemp,
    MIN(X.bdrefemp)
FROM vrhf_base_tempgrcs X
GROUP BY X.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPPAR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPPAR(
    BDCODEMP,
    BDETIQEMP,
    BDTAXSEREMP,
    BDREFCAGEDEMP,
    BDCALCFCNAFNEMP,
    BDCALCC13NAFNEMP,
    BDTIPOCONTAB,
    BDTIPOEMIGUIAS,
    BDNIVELAGRUPEMP,
    BDCALCC13FNNEGEMP,
    BDCALC13MP936,
    /*Solicitação 133597 - André Cursino - 25/10/2021*/
    BDUSANOMESOCIAL,
 BDDESCCOMPL13NEG)
AS
SELECT
    BASE.bdcodemp,
    REF.bdetiqemp,
    REF.bdtaxseremp,
    REF.bdrefcagedemp,
    REF.bdcalcfcnafnemp,
    REF.bdcalcc13nafnemp,
    REF.bdtipocontab,
    REF.bdtipoemiguias,
    REF.bdnivelagrupemp,
    REF.bdcalcc13fnnegemp,
    REF.bdcalc13mp936,
    /*Solicitação 133597 - André Cursino - 25/10/2021*/
    REF.bdusanomesocial,
 REF.BDDESCCOMPL13NEG
FROM
(
  SELECT
      X.bdcodemp,
      COALESCE
  (
      (SELECT MAX(d2.bdrefemp) FROM vrhf_base_temppar d2 WHERE d2.bdcodemp = x.bdcodemp AND CAST(d2.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefemp) FROM vrhf_base_temppar d1 WHERE d1.bdcodemp = x.bdcodemp)
  ) AS bdrefemp
  FROM TEMPRESAS x
  where((x.bdexcluiremp is null)or(upper(x.bdexcluiremp)<>'TRUE'))
) AS BASE, vrhf_base_temppar REF
WHERE BASE.BDCODEMP = REF.BDCODEMP AND BASE.BDREFEMP = REF.BDREFEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPPAR_MAXREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPPAR_MAXREF(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
    X.bdcodemp,
    MAX(X.bdrefemp)
FROM vrhf_base_temppar X
WHERE
  CAST(X.BDREFEMP AS VARCHAR(6)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPPAR_MINREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPPAR_MINREF(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
    X.bdcodemp,
    MIN(X.bdrefemp)
FROM vrhf_base_temppar X
GROUP BY X.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPPROP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPPROP(
BDCODEMP,
BDPROPADMEMP,
BDPROPRESEMP,
BDPROPFEREMP,
BDPROPSITEMP,
BDCALCMEDIASTEMP,
BDPROPTOMEMP,
BDDIASTRABADI)
 AS 
SELECT
    BASE.bdcodemp,
    REF.bdpropadmemp,
    REF.bdpropresemp,
    REF.bdpropferemp,
    REF.bdpropsitemp,
    REF.bdcalcmediastemp,
    REF.bdproptomemp,
    REF.bddiastrabadi
FROM
(
  SELECT
      X.bdcodemp,
      COALESCE
  (
      (SELECT MAX(d2.bdrefemp) FROM vrhf_base_tempprop d2 WHERE d2.bdcodemp = x.bdcodemp AND CAST(d2.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefemp) FROM vrhf_base_tempprop d1 WHERE d1.bdcodemp = x.bdcodemp)
  ) AS bdrefemp
  FROM TEMPRESAS x
  where((x.bdexcluiremp is null)or(upper(x.bdexcluiremp)<>'TRUE'))
) AS BASE, vrhf_base_tempprop REF
WHERE BASE.BDCODEMP = REF.BDCODEMP AND BASE.BDREFEMP = REF.BDREFEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPPROP_MAXREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPPROP_MAXREF(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
    X.bdcodemp,
    MAX(X.bdrefemp)
FROM vrhf_base_tempprop X
WHERE
  CAST(X.BDREFEMP AS VARCHAR(6)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPPROP_MINREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPPROP_MINREF(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
    X.bdcodemp,
    MIN(X.bdrefemp)
FROM vrhf_base_tempprop X
GROUP BY X.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPRAIS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPRAIS(
    BDCODEMP,
    BDNATESTEMP,
    BDDATABASEEMP,
    BDPATEMP,
    BDNROPROPEMP,
    BDSERPROPRIOPATEMP,
    BDPATREFCONVENIOEMP,
    BDPATCESTAALIMENTOEMP,
    BDPATADMCOZINHAEMP,
    BDPATREFTRANSPEMP,
    BDPATALICONVENIOEMP,
    BDSINDICALIZEMP,
    BDCODEMPPAT,
    BDCODTPPONT,
    BDTRABTEMP)
AS
SELECT
    BASE.bdcodemp,
    REF.bdnatestemp,
    REF.bddatabaseemp,
    REF.bdpatemp,
    REF.bdnropropemp,
    REF.bdserpropriopatemp,
    REF.bdpatrefconvenioemp,
    REF.bdpatcestaalimentoemp,
    REF.bdpatadmcozinhaemp,
    REF.bdpatreftranspemp,
    REF.bdpataliconvenioemp,
    REF.bdsindicalizemp,
    REF.bdcodemppat,
    REF.BDCODTPPONT,
    REF.BDTRABTEMP
FROM
(
  SELECT
      X.bdcodemp,
      COALESCE
  (
      (SELECT MAX(d2.bdrefemp) FROM vrhf_base_temprais d2 WHERE d2.bdcodemp = x.bdcodemp AND CAST(d2.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefemp) FROM vrhf_base_temprais d1 WHERE d1.bdcodemp = x.bdcodemp)
  ) AS bdrefemp
  FROM TEMPRESAS x
  where((x.bdexcluiremp is null)or(upper(x.bdexcluiremp)<>'TRUE'))
) AS BASE, vrhf_base_temprais REF
WHERE BASE.BDCODEMP = REF.BDCODEMP AND BASE.BDREFEMP = REF.BDREFEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPRAIS_MAXREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPRAIS_MAXREF(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
    X.bdcodemp,
    MAX(X.bdrefemp)
FROM vrhf_base_temprais X
WHERE
  CAST(X.BDREFEMP AS VARCHAR(6)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPRAIS_MINREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPRAIS_MINREF(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
    X.bdcodemp,
    MIN(X.bdrefemp)
FROM vrhf_base_temprais X
GROUP BY X.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPSEFIP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPSEFIP(
BDCODEMP,
BDCODBAN,
BDCODAG,
BDCODUF,
BDIDENTEMP,
BDCATSEFIPEMP,
BDISENFILEMP,
BDCETRTALIZAEMP,
BDCODSEFIPEMP)
 AS 
SELECT
    BASE.bdcodemp,
    REF.bdcodban,
    REF.bdcodag,
    REF.bdcoduf,
    REF.bdidentemp,
    REF.bdcatsefipemp,
    REF.bdisenfilemp,
    REF.bdcetrtalizaemp,
    REF.bdcodsefipemp
FROM
(
  SELECT
      X.bdcodemp,
      COALESCE
  (
      (SELECT MAX(d2.bdrefemp) FROM vrhf_base_tempsefip d2 WHERE d2.bdcodemp = x.bdcodemp AND CAST(d2.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefemp) FROM vrhf_base_tempsefip d1 WHERE d1.bdcodemp = x.bdcodemp)
  ) AS bdrefemp
  FROM TEMPRESAS x
  where((x.bdexcluiremp is null)or(upper(x.bdexcluiremp)<>'TRUE'))
) AS BASE, vrhf_base_tempsefip REF
WHERE BASE.BDCODEMP = REF.BDCODEMP AND BASE.BDREFEMP = REF.BDREFEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPSEFIP_MAXREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPSEFIP_MAXREF(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
    X.bdcodemp,
    MAX(X.bdrefemp)
FROM vrhf_base_tempsefip X
WHERE
  CAST(X.BDREFEMP AS VARCHAR(6)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPSEFIP_MINREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPSEFIP_MINREF(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
    X.bdcodemp,
    MIN(X.bdrefemp)
FROM vrhf_base_tempsefip X
GROUP BY X.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPVINC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPVINC(
BDCODEMP,
BDCODIR,
BDCODINSS,
BDCODMEN,
BDCODIND,
BDCODPQUA,
BDCODPLACONVSAU,
BDCODPLANOONLINE,
BDCODBAIXA,
BDCODMEN2,
BDCODINDGPS)
 AS 
SELECT
    BASE.bdcodemp,
    REF.bdcodir,
    REF.bdcodinss,
    REF.bdcodmen,
    REF.bdcodind,
    REF.bdcodpqua,
    REF.BDCODPLACONVSAU,
    ref.bdcodplanoonline,
    ref.bdcodbaixa,
    REF.BDCODMEN2,
    REF.BDCODINDGPS

FROM
(
  SELECT
      X.bdcodemp,
      COALESCE
  (
      (SELECT MAX(d2.bdrefemp) FROM vrhf_base_tempvinc d2 WHERE d2.bdcodemp = x.bdcodemp AND CAST(d2.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefemp) FROM vrhf_base_tempvinc d1 WHERE d1.bdcodemp = x.bdcodemp)
  ) AS bdrefemp
  FROM TEMPRESAS x
  where((x.bdexcluiremp is null)or(upper(x.bdexcluiremp)<>'TRUE'))
) AS BASE, vrhf_base_tempvinc REF
WHERE BASE.BDCODEMP = REF.BDCODEMP AND BASE.BDREFEMP = REF.BDREFEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPVINC_MAXREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPVINC_MAXREF(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
    X.bdcodemp,
    MAX(X.bdrefemp)
FROM vrhf_base_tempvinc X
WHERE
  CAST(X.BDREFEMP AS VARCHAR(6)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TEMPVINC_MINREF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TEMPVINC_MINREF(
BDCODEMP,
BDREFEMP)
 AS 
SELECT
    X.bdcodemp,
    MIN(X.bdrefemp)
FROM vrhf_base_tempvinc X
GROUP BY X.BDCODEMP
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TITI_REF_MAXMIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TITI_REF_MAXMIN(
BDCODITI,
BDREF)
 AS 
SELECT bdcoditi,
    COALESCE
    (
      (SELECT MAX(rf2.bdreferencia) FROM VRHF_BASE_TITINERARIO_REF rf2 WHERE rf2.bdreferencia <=
         (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database) AND rf2.bdcoditi = X.bdcoditi),
      (SELECT MIN(rf2.bdreferencia) FROM VRHF_BASE_TITINERARIO_REF rf2 WHERE rf2.bdcoditi = X.bdcoditi)
    ) AS bdREF
    FROM VRHF_BASE_TITINERARIO_REF X
    GROUP BY X.bdcoditi
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TITINERARIOS_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TITINERARIOS_REF(
BDCODITI,
BDDESCITI,
BDLINHAITI,
BDVEICULOITI,
BDEMPITI,
    BDVALITI,
    BDCODOPER,
    BDCODLINHA)
 AS 
SELECT it.bdcoditi, it.bddesciti, it.bdlinhaiti, it.bdveiculoiti, it.bdempiti, val.bdvaliti, it.bdcodoper, it.bdcodlinha
FROM VW_VRHF_BASE_TITI_REF_MAXMIN ref
JOIN VRHF_BASE_TITINERARIOS it ON (it.bdcoditi = ref.bdcoditi)
JOIN vrhf_base_titinerario_ref val ON (it.bdcoditi = val.bdcoditi AND ref.bdref = val.bdreferencia)
;

/* CREATE OR ALTER VIEW: VW_VRHF_BASE_TTERC_MVINC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_BASE_TTERC_MVINC(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDBASEINSSNCOL,
    BDVALORINSSNCOL,
    BDBASEIRRFNCOL,
    BDVALORIRRFNCOL,
    BDBASEINSS13COL,
    BDVALORINSS13COL,
    BDBASEIRRF13COL,
    BDVALORIRRF13COL)
AS
SELECT
    X.BDCODEMP,
    X.BDCODTER,
    X.BDREFTERC,
    SUM(X.BDBASEINSSNTER) BDBASEINSSNTER,
    SUM(X.BDVALORINSSNTER) BDVALORINSSNTER,
    SUM(X.BDBASEIRRFNTER) BDBASEIRRFNTER,
    SUM(X.BDVALORIRRFNTER) BDVALORIRRFNTER,
    0,
    0,
    0,
    0
FROM VRHF_BASE_TTERC_MVINC X
WHERE X.BDREFTERC =
      (
       SELECT MAX(Y.BDREFTERC)
       FROM VRHF_BASE_TTERC_MVINC Y
       WHERE Y.BDCODTER = X.BDCODTER AND
             Y.BDREFTERC <=
                (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER)
                 FROM rdb$database
                )
      )
GROUP BY X.BDCODEMP, X.BDCODTER, X.BDREFTERC
;

/* CREATE OR ALTER VIEW: VW_VRHF_C13SAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_C13SAL(
BDCODEMP,
BDCODCOL,
BDREF13,
BDREFC13,
BDCODVER,
BDREFAUXVC13,
BDVALVC13,
BDREFVC13,
BDIGNREFVC13,
BDIGNVALVC13,
BDBASEIRC13,
BDBASEINSSC13,
BDBASEFGTSC13,
BDFGTSC13,
BDFGTSCSC13,
BDDATABAIXAC13,
BDREFBAIXAC13,
BDPERCIRC13,
BDVALORIRC13,
BDPERCINSSC13,
BDVALORINSSC13,
BDBRAISC13,
BDDEPC13,
BDSALBASEC13,
BDBASEPISC13,
BDDATAPGTOC13)
 AS 
SELECT
    VFOLC13.BDCODEMP,
    VFOLC13.BDCODCOL,
    VFOLC13.BDREF13,
    VFOLC13.BDREFC13,
    VFOLC13.BDCODVER,
    VFOLC13.BDREFAUXVC13,
    VFOLC13.BDVALVC13,
    VFOLC13.BDREFVC13,
    VFOLC13.BDIGNREFVC13,
    VFOLC13.BDIGNVALVC13,
    DFOLC13.BDBASEIRC13,
    DFOLC13.BDBASEINSSC13,
    DFOLC13.BDBASEFGTSC13,
    DFOLC13.BDFGTSC13,
    DFOLC13.BDFGTSCSC13,
    DFOLC13.BDDATABAIXAC13,
    DFOLC13.BDREFBAIXAC13,
    DFOLC13.BDPERCIRC13,
    DFOLC13.BDVALORIRC13,
    DFOLC13.BDPERCINSSC13,
    DFOLC13.BDVALORINSSC13,
    DFOLC13.BDBRAISC13,
    DFOLC13.BDDEPC13,
    DFOLC13.BDSALBASEC13,
    DFOLC13.BDBASEPISC13,
    DFOLC13.BDDATAPGTOC13


FROM VRHF_EMP_TVERBAC13 VFOLC13
LEFT OUTER JOIN vrhf_emp_tc13sal DFOLC13
  ON (DFOLC13.BDCODEMP = VFOLC13.BDCODEMP AND DFOLC13.BDCODCOL = VFOLC13.BDCODCOL AND DFOLC13.bdref13 = VFOLC13.BDREF13 AND DFOLC13.bdrefc13 = VFOLC13.bdrefc13)
;

/* CREATE OR ALTER VIEW: VW_VRHF_CONS_CALC_FOLHA_VERBAS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_CONS_CALC_FOLHA_VERBAS(
BDCODEMP,
BDCODCOL,
BDCODVER,
BDREFFN,
BDREFV,
BDREFAUXV,
BDVALV,
BDIGNREFVFN,
BDIGNVALVFN,
BDORDEM,
BDCODCENTRO,
BDCODTPCC,
BDCALCTOMADOR)
 AS 
SELECT
  bdcodemp,
  bdcodcol,
  bdcodver,
  bdreffn,
  bdrefvfn,
  bdrefauxvfn,
  bdvalvfn,
  bdignrefvfn,
  bdignvalvfn,
  CAST(NULL AS INTEGER),
  CAST(NULL AS INTEGER),
  CAST(NULL AS INTEGER),
  'FALSE'
FROM
  vrhf_emp_tverbafn COLCON


UNION


SELECT
  COLCON.BDCODEMP,
  COLCON.BDCODCOL,
  COLCON.BDCODVER,
  COLCON.BDREFTOMADOR,
  SUM(COLCON.BDREFVFT),
  MAX(COLCON.BDREFAUXVFT),
  SUM(COLCON.BDVALVFT),
  MAX(COLCON.BDIGNREFVFT),
  MAX(COLCON.BDIGNVALVFT),
  CAST(NULL AS INTEGER),
  CAST(NULL AS INTEGER),
  CAST(NULL AS INTEGER),
  'TRUE'
FROM
  vrhf_emp_tverbatomador COLCON
GROUP BY
  COLCON.BDCODVER,
  colcon.bdcodemp,
  colcon.bdcodcol,
  colcon.BDREFTOMADOR
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_FERIAS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_FERIAS(
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFVFE,
    BDREFAUXVFE,
    BDVALVFE,
    BDIGNREFAVFE,
    BDIGNREFVFE,
    BDIGNVALVFE,
    BDORVERBAFE,
    BDALTINT,
    BDDATABAIXAFE,
    BDBASEFGTSFE,
    BDVALORFGTSFE,
    BDVALORFGTSCSFE,
    BDMAIORREMFE,
    BDBASEINSSFE,
    BDALIQINSSFE,
    BDVALORINSSFE,
    BDBASEIRFE,
    BDALIQIRFE,
    BDVALORIRFE,
    BDBSALFAMFE,
    BDSALFAMFE,
    BDSALBASEFE,
    BDDEPFE,
    BDDETALHE,
    BDREFFN,
    BDCODFE,
    BDINIPERAQUISFE,
    BDBASEIROUTFE,
    BDVALORIROUTFE,
    BDDEPIROUTFE,
    BDCREDITOFE,
    BDDEBITOFE,
    BDBFGTS13,
    BDFGTS13,
    BDCOMPESP,
    BDFORMREFAUX,
    BDFORMREF,
    BDFORMVAL,
    BDDATAPAGFE,
    BDBASEIRBRUTARED,
    BDVALORIRBRUTARED,
    BDVALORRED)
AS
SELECT
  FE.BDCODEMP,
  FE.BDCODCOL,
  FE.BDCODVER,
  FE.BDREFVFE,
  FE.BDREFAUXVFE,
  FE.BDVALVFE,
  FE.BDIGNREFAVFE,
  FE.BDIGNREFVFE,
  FE.BDIGNVALVFE,
  FE.BDORVERBAFE,
  FE.BDALTINT,
  FERN.BDDATABAIXAFE,
  FERN.BDBASEFGTSFE,
  FERN.BDVALORFGTSFE,
  FERN.BDVALORFGTSCSFE,
  FERN.BDMAIORREMFE,
  FERN.BDBASEINSSFE,
  FERN.BDALIQINSSFE,
  FERN.BDVALORINSSFE,
  FERN.BDBASEIRFE,
  FERN.BDALIQIRFE,
  FERN.BDVALORIRFE,
  FERN.BDBSALFAMFE,
  FERN.BDSALFAMFE,
  COALESCE(FERN.BDSALBASEFE, 0.0) BDSALBASEFE,
  FERN.BDDEPFE,
  'Competencia: '||FERN.BDCOMPETENCIAFE BDDETALHE,
  CAST((SUBSTRING(FERN.BDCOMPETENCIAFE FROM 4 FOR 4)||SUBSTRING(FERN.BDCOMPETENCIAFE FROM 1 FOR 2)) AS INTEGER) BDREFFN,
  FERN.BDCODFE,
  FERN.BDINIPERAQUISFE,
  FERN.BDBASEIROUTFE,
  FERN.BDVALORIROUTFE,
  FERN.BDDEPIROUTFE,
  FERN.BDCREDITOFE,
  FERN.BDDEBITOFE,
  FERN.BDBFGTS13,
  FERN.BDFGTS13,
  FE.BDCOMPESP,
  FE.BDFORMREFAUX,
  FE.BDFORMREF,
  FE.BDFORMVAL,
  FERN.BDDATAPAGFE,
  FERN.BDBASEIRBRUTARED,
  FERN.BDVALORIRBRUTARED,
  FERN.BDVALORRED
FROM VRHF_EMP_TVERBAFE FE,
     VRH_EMP_TFERIAS FERN
WHERE FERN.BDCODEMP = FE.BDCODEMP AND FERN.BDCODCOL = FE.BDCODCOL AND FERN.BDCODFE = FE.BDCODFE AND FERN.BDINIPERAQUISFE = FE.BDINIPERAQUISFE
;


/* CREATE OR ALTER VIEW: VW_VRHF_EMP_T13SAL_RAT_AGRU (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_T13SAL_RAT_AGRU(
BDCODEMP,
BDREF13,
BDCHAVE,
BDCODCOL,
BDORDEM,
BDMESESPROP13,
BDBASEIR13,
BDBASEFGTS13,
BDFGTS13,
BDFGTSCS13,
BDDATABAIXA13,
BDREFBAIXA13,
BDPERCIR13,
BDVALORIR13,
BDBASEINSS13,
BDPERCINSS13,
BDVALORINSS13,
BDBRAIS13,
BDSALBASE13,
BDDEP13,
BDARREPROV13,
BDARREDESC13,
BDVAL13,
BDBSALFAM13,
BDSALFAM13,
BDANO13,
BDBASEPIS13,
BDBSALMATEMP13,
BDSALMATEMP13,
BDBRATAPO13,
BDRATAPO13,
BDESTPROV13,
BDCREDITO13,
BDDEBITO13,
BDLIQUIDO,
BDDATAPGTO13,
BDBINSSMV13,
BDJAN,
BDFEV,
BDMAR,
BDABR,
BDMAI,
BDJUN,
BDJUL,
BDAGO,
BDSET,
BDOUT,
BDNOV,
BDDEZ,
BDDATAPROC13,
BDHORAPROC13,
BDCODCENTRO,
BDCODTPCC,
BDCODTOMADOR)
 AS 
SELECT X.bdcodemp, x.bdref13, NULL bdchave, x.bdcodcol, NULL bdordem, MAX(bdmesesprop13),
       SUM(bdbaseir13), SUM(bdbasefgts13),
       SUM(bdfgts13), SUM(bdfgtscs13), MAX(bddatabaixa13), MAX(bdrefbaixa13),
       MAX(bdpercir13), SUM(bdvalorir13),
       SUM(bdbaseinss13), MAX(x.bdpercinss13),
       SUM(bdvalorinss13), SUM(x.bdbrais13),
       MAX(x.bdsalbase13), MAX(x.bddep13),
       MAX(x.bdarreprov13), MAX(x.bdarredesc13),
       MAX(x.bdval13), MAX(x.bdbsalfam13),
       MAX(x.bdsalfam13), MAX(x.bdano13), SUM(bdbasepis13),
       SUM(bdbsalmatemp13), SUM(bdsalmatemp13), SUM(bdbratapo13),
       SUM(bdratapo13), MAX(x.bdestprov13), MAX(x.bdcredito13),
       MAX(x.bddebito13), SUM(bdliquido), MAX(x.bddatapgto13),
       MAX(x.bdbinssmv13), MAX(x.bdjan), MAX(x.bdfev),
       MAX(x.bdmar), MAX(x.bdabr), MAX(x.bdmai), MAX(x.bdjun),
       MAX(x.bdjul), MAX(x.bdago), MAX(x.bdset), MAX(x.bdout),
       MAX(x.bdnov), MAX(x.bddez), MAX(x.bddataproc13), MAX(x.bdhoraproc13),
       NULL bdcodcentro, NULL bdcodtpcc, NULL bdcodtomador
FROM VRHF_EMP_T13SAL_RAT X
GROUP BY x.bdcodemp,x.bdcodcol,x.bdref13
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_T13SAL_RAT_CC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_T13SAL_RAT_CC(
BDCODEMP,
BDREF13,
BDCHAVE,
BDCODCOL,
BDORDEM,
BDMESESPROP13,
BDBASEIR13,
BDBASEFGTS13,
BDFGTS13,
BDFGTSCS13,
BDDATABAIXA13,
BDREFBAIXA13,
BDPERCIR13,
BDVALORIR13,
BDBASEINSS13,
BDPERCINSS13,
BDVALORINSS13,
BDBRAIS13,
BDSALBASE13,
BDDEP13,
BDARREPROV13,
BDARREDESC13,
BDVAL13,
BDBSALFAM13,
BDSALFAM13,
BDANO13,
BDBASEPIS13,
BDBSALMATEMP13,
BDSALMATEMP13,
BDBRATAPO13,
BDRATAPO13,
BDESTPROV13,
BDCREDITO13,
BDDEBITO13,
BDLIQUIDO,
BDDATAPGTO13,
BDBINSSMV13,
BDJAN,
BDFEV,
BDMAR,
BDABR,
BDMAI,
BDJUN,
BDJUL,
BDAGO,
BDSET,
BDOUT,
BDNOV,
BDDEZ,
BDDATAPROC13,
BDHORAPROC13,
BDCODCENTRO,
BDCODTPCC,
BDCODTOMADOR)
 AS 
SELECT X.bdcodemp, x.bdref13, MAX(x.bdchave), x.bdcodcol, NULL bdordem, MAX(bdmesesprop13),
       SUM(bdbaseir13), SUM(bdbasefgts13),
       SUM(bdfgts13), SUM(bdfgtscs13), MAX(bddatabaixa13), MAX(bdrefbaixa13),
       MAX(bdpercir13), SUM(bdvalorir13),
       SUM(bdbaseinss13), MAX(x.bdpercinss13),
       SUM(bdvalorinss13), SUM(x.bdbrais13),
       MAX(x.bdsalbase13), MAX(x.bddep13),
       MAX(x.bdarreprov13), MAX(x.bdarredesc13),
       MAX(x.bdval13), MAX(x.bdbsalfam13),
       MAX(x.bdsalfam13), MAX(x.bdano13), SUM(bdbasepis13),
       SUM(bdbsalmatemp13), SUM(bdsalmatemp13), SUM(bdbratapo13),
       SUM(bdratapo13), MAX(x.bdestprov13), MAX(x.bdcredito13),
       MAX(x.bddebito13), SUM(bdliquido), MAX(x.bddatapgto13),
       MAX(x.bdbinssmv13), MAX(x.bdjan), MAX(x.bdfev),
       MAX(x.bdmar), MAX(x.bdabr), MAX(x.bdmai), MAX(x.bdjun),
       MAX(x.bdjul), MAX(x.bdago), MAX(x.bdset), MAX(x.bdout),
       MAX(x.bdnov), MAX(x.bddez), MAX(x.bddataproc13), MAX(x.bdhoraproc13),
       cc.bdcodcentro, cc.bdcodtpcc, tom.bdcodtpcc bdcodtomador
FROM VRHF_EMP_T13SAL_RAT X
LEFT OUTER JOIN vrhf_emp_tprepfn cc ON (x.bdcodemp = cc.bdcodemp AND x.bdcodcol = cc.bdcodcol AND x.bdordem = cc.bdordem)
LEFT OUTER JOIN vrhf_sp_tomador(cc.bdcodtpcc,cc.bdcodcentro) tom ON (cc.bdcodcentro = tom.bdcodcentro AND cc.bdcodtpcc = tom.bdcodcencus)
GROUP BY x.bdcodemp,x.bdcodcol,x.bdref13,cc.bdcodcentro, cc.bdcodtpcc, tom.bdcodtpcc
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_T13SAL_RAT_TOM (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_T13SAL_RAT_TOM(
BDCODEMP,
BDREF13,
BDCHAVE,
BDCODCOL,
BDORDEM,
BDMESESPROP13,
BDBASEIR13,
BDBASEFGTS13,
BDFGTS13,
BDFGTSCS13,
BDDATABAIXA13,
BDREFBAIXA13,
BDPERCIR13,
BDVALORIR13,
BDBASEINSS13,
BDPERCINSS13,
BDVALORINSS13,
BDBRAIS13,
BDSALBASE13,
BDDEP13,
BDARREPROV13,
BDARREDESC13,
BDVAL13,
BDBSALFAM13,
BDSALFAM13,
BDANO13,
BDBASEPIS13,
BDBSALMATEMP13,
BDSALMATEMP13,
BDBRATAPO13,
BDRATAPO13,
BDESTPROV13,
BDCREDITO13,
BDDEBITO13,
BDLIQUIDO,
BDDATAPGTO13,
BDBINSSMV13,
BDJAN,
BDFEV,
BDMAR,
BDABR,
BDMAI,
BDJUN,
BDJUL,
BDAGO,
BDSET,
BDOUT,
BDNOV,
BDDEZ,
BDDATAPROC13,
BDHORAPROC13,
BDCODCENTRO,
BDCODTPCC,
BDCODTOMADOR)
 AS 
SELECT X.bdcodemp, x.bdref13, MAX(x.bdchave), x.bdcodcol, NULL bdordem, MAX(bdmesesprop13),
       SUM(bdbaseir13), SUM(bdbasefgts13),
       SUM(bdfgts13), SUM(bdfgtscs13), MAX(bddatabaixa13), MAX(bdrefbaixa13),
       MAX(bdpercir13), SUM(bdvalorir13),
       SUM(bdbaseinss13), MAX(x.bdpercinss13),
       SUM(bdvalorinss13), SUM(x.bdbrais13),
       MAX(x.bdsalbase13), MAX(x.bddep13),
       MAX(x.bdarreprov13), MAX(x.bdarredesc13),
       MAX(x.bdval13), MAX(x.bdbsalfam13),
       MAX(x.bdsalfam13), MAX(x.bdano13), SUM(bdbasepis13),
       SUM(bdbsalmatemp13), SUM(bdsalmatemp13), SUM(bdbratapo13),
       SUM(bdratapo13), MAX(x.bdestprov13), MAX(x.bdcredito13),
       MAX(x.bddebito13), SUM(bdliquido), MAX(x.bddatapgto13),
       MAX(x.bdbinssmv13), MAX(x.bdjan), MAX(x.bdfev),
       MAX(x.bdmar), MAX(x.bdabr), MAX(x.bdmai), MAX(x.bdjun),
       MAX(x.bdjul), MAX(x.bdago), MAX(x.bdset), MAX(x.bdout),
       MAX(x.bdnov), MAX(x.bddez), MAX(x.bddataproc13), MAX(x.bdhoraproc13),
       cc.bdcodcentro, tom.bdcodtpcc, tom.bdcodtpcc bdcodtomador
FROM VRHF_EMP_T13SAL_RAT X
LEFT OUTER JOIN vrhf_emp_tprepfn cc ON (x.bdcodemp = cc.bdcodemp AND x.bdcodcol = cc.bdcodcol AND x.bdordem = cc.bdordem)
LEFT OUTER JOIN vrhf_sp_tomador(cc.bdcodtpcc,cc.bdcodcentro) tom ON (cc.bdcodcentro = tom.bdcodcentro AND cc.bdcodtpcc = tom.bdcodcencus)
GROUP BY x.bdcodemp,x.bdcodcol,x.bdref13,cc.bdcodcentro, tom.bdcodtpcc
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TADSAL_FIXO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TADSAL_FIXO(
BDCODEMP,
BDCODCOL,
BDREFADSAL,
BDVALORADSAL)
 AS 
SELECT
    bdcodemp,
    bdcodcol,
    bdrefadsal,
    bdvaloradsal
FROM vrhf_emp_tadsal_fixo
ORDER BY bdcodemp, bdcodcol, bdrefadsal DESC
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOL_CALC_MAX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOL_CALC_MAX(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MAX(X.bdrefcol)
FROM VRHF_EMP_TCOL_CALC X
WHERE
  CAST(X.BDREFCOL AS VARCHAR(6)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOL_CALC_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOL_CALC_MIN(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MIN(X.bdrefcol)
FROM VRHF_EMP_TCOL_CALC X
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_BANCO_MAX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_BANCO_MAX(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MAX(X.bdrefcol)
FROM vrhf_emp_tcolcon_banco X
WHERE
  CAST(X.BDREFCOL AS VARCHAR(6)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_BANCO_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_BANCO_MIN(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MIN(X.bdrefcol)
FROM vrhf_emp_tcolcon_banco X
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_CALC_MAX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_CALC_MAX(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MAX(X.bdrefcol)
FROM VRHF_EMP_TCOLCON_CALC X
WHERE
  CAST(X.BDREFCOL AS VARCHAR(6)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_CALC_MAXMIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_CALC_MAXMIN(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    W.bdcodemp,
    W.bdcodcol,
    ( SELECT FIRST 1 X.bdrefcol
       FROM VRHF_EMP_TCOLCON_CALC X
       WHERE w.bdcodemp = x.bdcodemp AND w.bdcodcol = x.bdcodcol AND
      CAST(X.BDREFCOL AS VARCHAR(6)) <=  (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))  FROM rdb$database)
      ORDER BY X.bdrefcol DESC)
FROM vrh_emp_tcolcon w
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_CALC_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_CALC_MIN(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MIN(X.bdrefcol)
FROM VRHF_EMP_TCOLCON_CALC X
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_CALC_NOVO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_CALC_NOVO(
BDCODEMP,
BDCODCOL,
BDREFCOL,
BDFORMAPAGTOCOL,
BDNRODEPIRCOL,
BDBASEIRRFADCOL,
BDVALORPREVPRIVNCOL,
BDVALORPREVPRIV13COL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    X.bdrefcol,
    X.bdformapagtocol,
    X.bdnrodepircol,
    X.bdbaseirrfadcol,
    X.bdvalorprevprivncol,
    X.bdvalorprevpriv13col
FROM VW_VRHF_EMP_TCOLCON_CALC_MAXMIN W
JOIN vrhf_emp_tcolcon_calc X ON (x.bdcodemp = w.bdcodemp AND x.bdcodcol = w.bdcodcol AND w.bdrefcol = x.bdrefcol)
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_FGTSGPS_MAX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_FGTSGPS_MAX(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MAX(X.bdrefcol)
FROM VRHF_EMP_TCOLCON_FGTSGPS X
WHERE
  CAST(X.BDREFCOL AS VARCHAR(6)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_FGTSGPS_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_FGTSGPS_MIN(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MIN(X.bdrefcol)
FROM VRHF_EMP_TCOLCON_FGTSGPS X
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_FGTS_JOIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_FGTS_JOIN(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDDATAOPCAOFGTSCOL,
    BDCTAFGTSCOL,
    BDCATEGORIACOL,
    BDPERCFGTSCOL,
    BDOCORRENCIACOL,
    BDPERCRATCOL,
    BDPERCDESCFPASCOL,
    BDCODMULTVINC)
AS
SELECT
    X.bdcodemp,
    X.bdcodcol,
    X.bdrefcol,
    x.bddataopcaofgtscol,
    x.bdctafgtscol,
    x.bdcategoriacol,
    x.bdpercfgtscol,
    x.bdocorrenciacol,
    x.bdpercratcol,
    x.bdpercdescfpascol,
    x.bdcodmultvinc
FROM vrhf_emp_tcolcon_fgtsgps x
LEFT OUTER JOIN VW_VRHF_EMP_TCOLCON_FGTSGPS_MAX Z ON (x.bdcodemp = z.bdcodemp AND x.bdcodcol = z.bdcodcol)
JOIN VW_VRHF_EMP_TCOLCON_FGTSGPS_MIN Y ON (x.bdcodemp = y.bdcodemp AND x.bdcodcol = y.bdcodcol)
WHERE x.bdrefcol = COALESCE(z.bdrefcol,y.bdrefcol)
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_FGTSGPS_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_FGTSGPS_REF(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    w.bdcodemp,
    w.bdcodcol,

    (SELECT FIRST 1 X.bdrefcol
     FROM VRHF_EMP_TCOLCON_FGTSGPS X
     WHERE x.bdcodemp = w.bdcodemp AND x.bdcodcol = w.bdcodcol AND
            CAST(X.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))  FROM rdb$database)
     ORDER BY x.bdrefcol DESC)

FROM vrh_emp_tcolcon w
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_FGTSGPS_ATU (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_FGTSGPS_ATU(
    BDCODEMP,
    BDCODCOL,
    BDREFCOL,
    BDDATAOPCAOFGTSCOL,
    BDCTAFGTSCOL,
    BDCATEGORIACOL,
    BDPERCFGTSCOL,
    BDOCORRENCIACOL,
    BDPERCRATCOL,
    BDPERCDESCFPASCOL,
    BDCATEGORIAESOCIAL,
    BDREGPREV,
    BDINTERMITENTE,
    BDCODMULTVINC)
AS
SELECT
    X.bdcodemp,
    X.bdcodcol,
    X.bdrefcol,
    x.bddataopcaofgtscol,
    x.bdctafgtscol,
    x.bdcategoriacol,
    x.bdpercfgtscol,
    x.bdocorrenciacol,
    x.bdpercratcol,
    x.bdpercdescfpascol,
    x.bdcategoriaesocial,
    x.bdregprev,
    case when (COALESCE(x.bdocorrenciacol, 0) = 4) and (COALESCE(x.BDCATEGORIAESOCIAL, 0) = 111) then 'TRUE' else 'FALSE' end,
    x.bdcodmultvinc
FROM vrhf_emp_tcolcon_fgtsgps x
JOIN VW_VRHF_EMP_TCOLCON_FGTSGPS_REF w ON (x.bdcodemp = w.bdcodemp AND x.bdcodcol = w.bdcodcol AND x.bdrefcol = w.bdrefcol)
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCOLCON_MVINC_MAX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCOLCON_MVINC_MAX(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MAX(X.bdrefcol)
FROM VRHF_EMP_TCOLCON_MVINC X
WHERE
  CAST(X.BDREFCOL AS VARCHAR(6)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCON_VINC_MAX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCON_VINC_MAX(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MAX(X.bdrefcol)
FROM VRHF_EMP_TCON_VINC X
WHERE
  CAST(X.BDREFCOL AS VARCHAR(6)) <=
     (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
      FROM rdb$database
     )
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCON_VINC_MIN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCON_VINC_MIN(
BDCODEMP,
BDCODCOL,
BDREFCOL)
 AS 
SELECT
    X.bdcodemp,
    X.bdcodcol,
    MIN(X.bdrefcol)
FROM VRHF_EMP_TCON_VINC X
GROUP BY X.BDCODEMP,X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TCONVREFCOL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TCONVREFCOL(
BDCODEMP,
BDCODCOL,
BDCODCONVREF,
BDDIASEMCONVREF,
BDREFCONVREF,
BDQTDCONVREF)
 AS 
SELECT
  BASE.BDCODEMP,
  BASE.BDCODCOL,
  REF.BDCODCONVREF,
  REF.BDDIASEMCONVREF,
  REF.BDREFCONVREF,
  REF.BDQTDCONVREF
FROM
(
  SELECT
      X.bdcodemp,
      X.bdcodcol,
      COALESCE
  (
      (SELECT MAX(d2.bdrefconvref) FROM vrhf_emp_tconvrefcol d2 WHERE d2.bdcodemp = x.bdcodemp AND d2.bdcodcol = x.bdcodcol AND CAST(d2.BDREFCONVREF AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefconvref) FROM vrhf_emp_tconvrefcol d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol)
  ) AS bdrefconvref
  FROM VRH_EMP_TCOLCON x

) AS BASE, vrhf_emp_tconvrefcol REF
WHERE BASE.BDCODEMP = REF.BDCODEMP AND BASE.BDCODCOL = REF.BDCODCOL AND BASE.BDREFCONVREF = REF.BDREFCONVREF
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TFICHAHE_DETR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TFICHAHE_DETR(
BDCODEMP,
BDCODCOL,
BDCODVER,
BDREFFHE,
BDDATAENT,
BDCODCENTO,
BDCODTPCC,
BDTIPOFHE,
BDCCFHE,
BDVREFFHE,
BDVREFAUXFHE,
BDVVALFHE,
BDDATAHE)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFFN,
  CAST(NULL AS DATE) BDDATAENT,
  CAST(NULL AS INTEGER) BDCODCENTO,
  CAST(NULL AS INTEGER) BDCODTPCC,
  0 BDTIPOCALC,
  0 BDCCFN,
  X.BDREFVFN,
  X.BDREFAUXVFN,
  X.BDVALVFN,
  CAST(NULL AS DATE)
FROM
VRHF_EMP_TVERBAFN X
WHERE EXISTS (SELECT Y.BDCODVER FROM VW_VRH_BASE_TVERBAS_FICHA_HE Y WHERE Y.BDCODVER = X.BDCODVER)
UNION ALL
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFTOMADOR,
  CASE WHEN CHAR_LENGTH(tom.bdcnpjtom) = 15 THEN cc.BDDATAENTRADA ELSE CAST(NULL AS DATE) END BDDATAENT,
  CASE WHEN CHAR_LENGTH(tom.bdcnpjtom) = 15 THEN cc.BDCODCENTRO ELSE CAST(NULL AS INTEGER) END BDCODCENTO,
  CASE WHEN CHAR_LENGTH(tom.bdcnpjtom) = 15 THEN cc.BDCODTPCC ELSE CAST(NULL AS INTEGER) END BDCODTPCC,
  100 BDTIPOCALC,
  X.BDORDEM,
  X.BDREFVFT,
  X.BDREFAUXVFT,
  X.BDVALVFT,
  CAST(NULL AS DATE)
FROM
VRHF_EMP_TVERBATOMADOR X
JOIN VRHF_EMP_TPREPFN cc ON (x.bdcodemp = cc.bdcodemp AND  x.bdcodcol = cc.bdcodcol AND x.bdordem = cc.bdordem)
LEFT OUTER JOIN VRH_BASE_TCUSTOM tom ON (tom.bdcodcentro = cc.bdcodcentro AND tom.bdcodtpcc = cc.bdcodtpcc)
WHERE EXISTS (SELECT Y.BDCODVER FROM VW_VRH_BASE_TVERBAS_FICHA_HE Y WHERE Y.BDCODVER = X.BDCODVER)
UNION  ALL
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFFN,
  CAST(NULL AS DATE) BDDATAENT,
  CAST(NULL AS INTEGER) BDCODCENTO,
  CAST(NULL AS INTEGER) BDCODTPCC,
  1 BDTIPOCALC,
  0 BDCCFC,
  X.BDREFVFC,
  X.BDREFAUXVFC,
  X.BDVALVFC,
  CAST((SUBSTRING(CAST(X.BDREFFC AS VARCHAR(8)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(8)) FROM 7 FOR 2)||'/'||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(8)) FROM 1 FOR 4)) AS DATE)
FROM
VRHF_EMP_TVERBAFC X
WHERE EXISTS (SELECT Y.BDCODVER FROM VW_VRH_BASE_TVERBAS_FICHA_HE Y WHERE Y.BDCODVER = X.BDCODVER)
UNION ALL
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFTOMADOR,
  CASE WHEN CHAR_LENGTH(tom.bdcnpjtom) = 15 THEN cc.BDDATAENTRADA ELSE CAST(NULL AS DATE) END BDDATAENT,
  CASE WHEN CHAR_LENGTH(tom.bdcnpjtom) = 15 THEN cc.BDCODCENTRO ELSE CAST(NULL AS INTEGER) END BDCODCENTO,
  CASE WHEN CHAR_LENGTH(tom.bdcnpjtom) = 15 THEN cc.BDCODTPCC ELSE CAST(NULL AS INTEGER) END BDCODTPCC,
  101 BDTIPOCALC,
  X.BDORDEM,
  X.BDREFVFC,
  X.BDREFAUXVFC,
  X.BDVALVFC,
  CAST((SUBSTRING(CAST(X.BDREFFC AS VARCHAR(8)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(8)) FROM 7 FOR 2)||'/'||SUBSTRING(CAST(X.BDREFFC AS VARCHAR(8)) FROM 1 FOR 4)) AS DATE)
FROM
VRHF_EMP_TVERBAFCTOMADOR X
JOIN VRHF_EMP_TPREPFN cc ON (x.bdcodemp = cc.bdcodemp AND  x.bdcodcol = cc.bdcodcol AND x.bdordem = cc.bdordem)
LEFT OUTER JOIN VRH_BASE_TCUSTOM tom ON (tom.bdcodcentro = cc.bdcodcentro AND tom.bdcodtpcc = cc.bdcodtpcc)
WHERE EXISTS (SELECT Y.BDCODVER FROM VW_VRH_BASE_TVERBAS_FICHA_HE Y WHERE Y.BDCODVER = X.BDCODVER)
UNION ALL
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFFHE,
  CAST(NULL AS DATE) BDDATAENT,
  CAST(NULL AS INTEGER) BDCODCENTO,
  CAST(NULL AS INTEGER) BDCODTPCC,
  9999 BDTIPOCALC,
  0 BDCCFHE,
  X.BDVREFFHE,
  0.000000 BDREFAUXFHE,
  X.BDVVALFHE,
  CAST(NULL AS DATE)
FROM
VRHF_EMP_TFICHAHE X
WHERE
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHANORMAL Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREFFHE)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMADOR Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFTOMADOR = X.BDREFFHE)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMP Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREFFHE)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMP Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFTOMADOR = X.BDREFFHE)
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TFICHAINSS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TFICHAINSS(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDANO,
    BDBINSSMES,
    BDVINSSMES,
    BDBINSS13,
    BDINSS13,
    BDBINSSC13,
    BDINSSC13)
AS
SELECT bdcodemp,bdcodcol,bdreffn,
       SUBSTRING(CAST(bdreffn AS VARCHAR(6)) FROM 1 FOR 4),
       bdbinssmes,
       bdvinssmes,
       bdbinss13,
       bdinss13,
       bdbinssc13,
       bdinssc13
FROM (
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdreffn,
       COALESCE(fn.bdbinssfn,0)+COALESCE(fn.bdbinssfefolfn,0) bdbinssmes,
       COALESCE(fn.bdinssfn,0)+COALESCE(fn.bdinssfefolfn,0) bdvinssmes,
       fn.bdbinss13fn bdbinss13,
       fn.bdinss13fn bdinss13,
       0 bdbinssc13,
       0 bdinssc13
    FROM vrhf_emp_tfolhanormal fn
    UNION
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdreffn,
           COALESCE(fn.bdbinssfn,0)+COALESCE(fn.bdbinssfefolfn,0) bdbinssmes,
           COALESCE(fn.bdinssfn,0)+COALESCE(fn.bdinssfefolfn,0) bdvinssmes,
           fn.bdbinss13fn bdbinss13,
           fn.bdinss13fn bdinss13,
           0 bdbinssc13,
           0 bdinssc13
    FROM vrhf_emp_tfolhaint fn
    UNION
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdreftomador,
       COALESCE(fn.bdbinssft,0)+COALESCE(fn.bdbinssfefolft,0) bdbinssmes,
       COALESCE(fn.bdinssft,0)+COALESCE(fn.bdinssfefolft,0) bdvinssmes,
       fn.bdbinss13ft bdbinss13,
       fn.bdinss13ft bdinss13,
       0 bdbinssc13,
       0 bdinssc13
    
    FROM vrhf_emp_tfolhatomador fn
    UNION
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdreftomador,
           COALESCE(fn.bdbinssft,0)+COALESCE(fn.bdbinssfefolft,0) bdbinssmes,
           COALESCE(fn.bdinssft,0)+COALESCE(fn.bdinssfefolft,0) bdvinssmes,
           fn.bdbinss13ft bdbinss13,
           fn.bdinss13ft bdinss13,
           0 bdbinssc13,
           0 bdinssc13
    
    FROM vrhf_emp_tfolhatomint fn
    UNION
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdreffn,
       COALESCE(fn.bdbinssfc,0)+COALESCE(fn.bdbinssfefolfc,0) bdbinssmes,
       COALESCE(fn.bdinssfc,0)+COALESCE(fn.bdinssfefolfc,0) bdvinssmes,
       fn.bdbinss13fc bdbinss13,
       fn.bdinss13fc bdinss13,
       0 bdbinssc13,
       0 bdinssc13
    
    FROM vrhf_emp_tfolhacomp fn
    UNION
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdreftomador,
       COALESCE(fn.bdbinssfc,0)+COALESCE(fn.bdbinssfefolfc,0) bdbinssmes,
       COALESCE(fn.bdinssfc,0)+COALESCE(fn.bdinssfefolfc,0) bdvinssmes,
       fn.bdbinss13fc bdbinss13,
       fn.bdinss13fc bdinss13,
       0 bdbinssc13,
       0 bdinssc13
    
    FROM vrhf_emp_tfoltomcomp fn
    UNION
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdref13,
       0 bdbinssmes,
       0 bdvinssmes,
       fn.bdbaseinss13 bdbinss13,
       fn.bdvalorinss13 bdinss13,
       0 bdbinssc13,
       0 bdinssc13
    
    FROM vrhf_emp_t13sal fn
    UNION
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdrefc13,
       0 bdbinssmes,
       0 bdvinssmes,
       0 bdbinss13,
       0 bdinss13,
       CASE WHEN COALESCE(fn.bdbaseinssc13,0) < 0 THEN 0 ELSE fn.bdbaseinssc13 END bdbinssc13,
       CASE WHEN COALESCE(fn.bdvalorinssc13,0) < 0 THEN 0 ELSE fn.bdvalorinssc13 END bdinssc13
    
    FROM vrhf_emp_tc13sal fn
    UNION
    SELECT fn.bdcodemp,fn.bdcodcol,
  CAST((SUBSTRING(CAST(fn.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(fn.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER),
       COALESCE(fn.bdbinssfa, 0) + COALESCE(fn.bdbinssfefolfa, 0),
       COALESCE(fn.bdinssfa, 0) + COALESCE(fn.bdinssfefolfa, 0),
       COALESCE(fn.bdbinss13fa, 0),
       COALESCE(fn.bdinss13fa, 0),
       0 bdbinssc13,
       0 bdinssc13
    
    FROM vrhf_emp_tfolhaavulsa fn
    UNION
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdref_finss,
       COALESCE(fn.bdbinssn_finss,0)+COALESCE(fn.bdbinssfer_finss,0) bdbinssmes,
       COALESCE(fn.bdinssn_finss,0)+COALESCE(fn.bdinssfer_finss,0) bdvinssmes,
       fn.bdbinss13_finss bdbinss13,
       fn.bdinss13_finss bdinss13,
       fn.bdbinssc13_finss bdbinssc13,
       fn.bdinssc13_finss bdinssc13
    FROM vrhf_emp_tfichainss fn
    WHERE
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHANORMAL Y WHERE Y.BDCODEMP = fn.BDCODEMP AND Y.BDCODCOL = fn.BDCODCOL AND Y.BDREFFN = fn.bdref_finss)
  AND
      NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHAINT Y WHERE Y.BDCODEMP = fn.BDCODEMP AND Y.BDCODCOL = fn.BDCODCOL AND Y.BDREFFN = fn.bdref_finss)
      AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMADOR Y WHERE Y.BDCODEMP = fn.BDCODEMP AND Y.BDCODCOL = fn.BDCODCOL AND Y.BDREFTOMADOR = fn.bdref_finss)
  AND
      NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMINT Y WHERE Y.BDCODEMP = fn.BDCODEMP AND Y.BDCODCOL = fn.BDCODCOL AND Y.BDREFTOMADOR = fn.bdref_finss)
      AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMP Y WHERE Y.BDCODEMP = fn.BDCODEMP AND Y.BDCODCOL = fn.BDCODCOL AND Y.BDREFFN = fn.bdref_finss)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMP Y WHERE Y.BDCODEMP = fn.BDCODEMP AND Y.BDCODCOL = fn.BDCODCOL AND Y.BDREFTOMADOR = fn.bdref_finss)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM vrhf_emp_t13sal Y WHERE Y.BDCODEMP = fn.BDCODEMP AND Y.BDCODCOL = fn.BDCODCOL AND Y.bdref13 = fn.bdref_finss)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM vrhf_emp_tc13sal Y WHERE Y.BDCODEMP = fn.BDCODEMP AND Y.BDCODCOL = fn.BDCODCOL AND Y.bdrefc13 = fn.bdref_finss)
)
;


CREATE OR ALTER VIEW VW_VRHF_EMP_TFICHAINSS_UNION_ALL(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDANO,
    BDBINSSMES,
    BDVINSSMES,
    BDBINSS13,
    BDINSS13,
    BDBINSSC13,
    BDINSSC13)
AS
SELECT bdcodemp,bdcodcol,bdreffn,
       SUBSTRING(CAST(bdreffn AS VARCHAR(6)) FROM 1 FOR 4),
       bdbinssmes,
       bdvinssmes,
       bdbinss13,
       bdinss13,
       bdbinssc13,
       bdinssc13
FROM (
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdreffn,
       COALESCE(fn.bdbinssfn,0)+COALESCE(fn.bdbinssfefolfn,0) bdbinssmes,
       COALESCE(fn.bdinssfn,0)+COALESCE(fn.bdinssfefolfn,0) bdvinssmes,
       fn.bdbinss13fn bdbinss13,
       fn.bdinss13fn bdinss13,
       0 bdbinssc13,
       0 bdinssc13
    FROM vrhf_emp_tfolhanormal fn
    UNION ALL
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdreffn,
           COALESCE(fn.bdbinssfn,0)+COALESCE(fn.bdbinssfefolfn,0) bdbinssmes,
           COALESCE(fn.bdinssfn,0)+COALESCE(fn.bdinssfefolfn,0) bdvinssmes,
           fn.bdbinss13fn bdbinss13,
           fn.bdinss13fn bdinss13,
           0 bdbinssc13,
           0 bdinssc13
    FROM vrhf_emp_tfolhaint fn
    UNION ALL
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdreftomador,
       COALESCE(fn.bdbinssft,0)+COALESCE(fn.bdbinssfefolft,0) bdbinssmes,
       COALESCE(fn.bdinssft,0)+COALESCE(fn.bdinssfefolft,0) bdvinssmes,
       fn.bdbinss13ft bdbinss13,
       fn.bdinss13ft bdinss13,
       0 bdbinssc13,
       0 bdinssc13
    
    FROM vrhf_emp_tfolhatomador fn
    UNION ALL
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdreftomador,
           COALESCE(fn.bdbinssft,0)+COALESCE(fn.bdbinssfefolft,0) bdbinssmes,
           COALESCE(fn.bdinssft,0)+COALESCE(fn.bdinssfefolft,0) bdvinssmes,
           fn.bdbinss13ft bdbinss13,
           fn.bdinss13ft bdinss13,
           0 bdbinssc13,
           0 bdinssc13
    
    FROM vrhf_emp_tfolhatomint fn
    UNION ALL
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdreffn,
       COALESCE(fn.bdbinssfc,0)+COALESCE(fn.bdbinssfefolfc,0) bdbinssmes,
       COALESCE(fn.bdinssfc,0)+COALESCE(fn.bdinssfefolfc,0) bdvinssmes,
       fn.bdbinss13fc bdbinss13,
       fn.bdinss13fc bdinss13,
       0 bdbinssc13,
       0 bdinssc13
    
    FROM vrhf_emp_tfolhacomp fn
    UNION ALL
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdreftomador,
       COALESCE(fn.bdbinssfc,0)+COALESCE(fn.bdbinssfefolfc,0) bdbinssmes,
       COALESCE(fn.bdinssfc,0)+COALESCE(fn.bdinssfefolfc,0) bdvinssmes,
       fn.bdbinss13fc bdbinss13,
       fn.bdinss13fc bdinss13,
       0 bdbinssc13,
       0 bdinssc13
    
    FROM vrhf_emp_tfoltomcomp fn
    UNION ALL
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdref13,
       0 bdbinssmes,
       0 bdvinssmes,
       fn.bdbaseinss13 bdbinss13,
       fn.bdvalorinss13 bdinss13,
       0 bdbinssc13,
       0 bdinssc13
    
    FROM vrhf_emp_t13sal fn
    UNION ALL
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdref13,
       0 bdbinssmes,
       0 bdvinssmes,
       0 bdbinss13,
       0 bdinss13,
       CASE WHEN COALESCE(fn.bdbaseinssc13,0) < 0 THEN 0 ELSE fn.bdbaseinssc13 END bdbinssc13,
       CASE WHEN COALESCE(fn.bdvalorinssc13,0) < 0 THEN 0 ELSE fn.bdvalorinssc13 END bdinssc13
    
    FROM vrhf_emp_tc13sal fn
    UNION ALL
    SELECT fn.bdcodemp,fn.bdcodcol,
  CAST((SUBSTRING(CAST(fn.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(fn.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER),
       COALESCE(fn.bdbinssfa, 0) + COALESCE(fn.bdbinssfefolfa, 0),
       COALESCE(fn.bdinssfa, 0) + COALESCE(fn.bdinssfefolfa, 0),
       COALESCE(fn.bdbinss13fa, 0),
       COALESCE(fn.bdinss13fa, 0),
       0 bdbinssc13,
       0 bdinssc13
    
    FROM vrhf_emp_tfolhaavulsa fn
    UNION ALL
    SELECT fn.bdcodemp,fn.bdcodcol,fn.bdref_finss,
       COALESCE(fn.bdbinssn_finss,0)+COALESCE(fn.bdbinssfer_finss,0) bdbinssmes,
       COALESCE(fn.bdinssn_finss,0)+COALESCE(fn.bdinssfer_finss,0) bdvinssmes,
       fn.bdbinss13_finss bdbinss13,
       fn.bdinss13_finss bdinss13,
       fn.bdbinssc13_finss bdbinssc13,
       fn.bdinssc13_finss bdinssc13
    FROM vrhf_emp_tfichainss fn
    WHERE
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHANORMAL Y WHERE Y.BDCODEMP = fn.BDCODEMP AND Y.BDCODCOL = fn.BDCODCOL AND Y.BDREFFN = fn.bdref_finss)
  AND
      NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHAINT Y WHERE Y.BDCODEMP = fn.BDCODEMP AND Y.BDCODCOL = fn.BDCODCOL AND Y.BDREFFN = fn.bdref_finss)
      AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMADOR Y WHERE Y.BDCODEMP = fn.BDCODEMP AND Y.BDCODCOL = fn.BDCODCOL AND Y.BDREFTOMADOR = fn.bdref_finss)
  AND
      NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMINT Y WHERE Y.BDCODEMP = fn.BDCODEMP AND Y.BDCODCOL = fn.BDCODCOL AND Y.BDREFTOMADOR = fn.bdref_finss)
      AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMP Y WHERE Y.BDCODEMP = fn.BDCODEMP AND Y.BDCODCOL = fn.BDCODCOL AND Y.BDREFFN = fn.bdref_finss)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMP Y WHERE Y.BDCODEMP = fn.BDCODEMP AND Y.BDCODCOL = fn.BDCODCOL AND Y.BDREFTOMADOR = fn.bdref_finss)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM vrhf_emp_t13sal Y WHERE Y.BDCODEMP = fn.BDCODEMP AND Y.BDCODCOL = fn.BDCODCOL AND Y.bdref13 = fn.bdref_finss)
  AND
  NOT EXISTS (SELECT Y.BDCODEMP FROM vrhf_emp_tc13sal Y WHERE Y.BDCODEMP = fn.BDCODEMP AND Y.BDCODCOL = fn.BDCODCOL AND Y.bdref13 = fn.bdref_finss)
)
;


/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TFICHARAIS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TFICHARAIS(
BDCODEMP,
BDCODCOL,
BDREF,
BDANO,
BDBRAISFN,
BDBRAIS13,
BDBRAISA13,
BDBRAISC13,
BDORIGEM)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  SUBSTRING(CAST(BDREF AS VARCHAR(6)) FROM 1 FOR 4),
  BDBRAISFN,
  BDBRAIS13,
  BDBRAISA13,
  BDBRAISC13,
  ORIGEM
FROM (
SELECT x.BDCODEMP, x.BDCODCOL, x.BDREF,
       CASE WHEN x.ORIGEM = 0 THEN x.BDBRAISFN ELSE x.x1 END BDBRAISFN,
       CASE WHEN x.ORIGEM = 0 THEN x.BDBRAIS13 ELSE x.x2 END BDBRAIS13,
       CASE WHEN x.ORIGEM = 0 THEN x.BDBRAISA13 ELSE x.x3 END BDBRAISA13,
       CASE WHEN x.ORIGEM = 0 THEN x.BDBRAISC13 ELSE x.x4 END BDBRAISC13,
       ORIGEM

FROM (

SELECT BDCODEMP, BDCODCOL, BDREF,

       SUM(BDBRAISFN) BDBRAISFN, SUM(BDBRAIS13) BDBRAIS13, SUM(BDBRAISA13) BDBRAISA13, SUM(BDBRAISC13) BDBRAISC13, SUM(x1) x1, SUM(x2) x2, SUM(x3) x3, SUM(x4) x4,

       MIN(BDORIGEM) ORIGEM

       FROM (
SELECT BDCODEMP, BDCODCOL, BDREF, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0 x1,0 x2,0 x3,0 x4, BDTIPO, 0 BDORIGEM FROM VW_RAIS_FOL_NORMAL
UNION ALL
SELECT BDCODEMP, BDCODCOL, BDREF, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0,0,0,0,BDTIPO, 0 BDORIGEM  FROM VW_RAIS_FOL_COMPLEMENTAR
UNION ALL
SELECT BDCODEMP, BDCODCOL, BDREF, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0,0,0,0,BDTIPO, 0 BDORIGEM  FROM VW_RAIS_A13
UNION ALL
SELECT BDCODEMP, BDCODCOL, BDREF, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0,0,0,0,BDTIPO, 0 BDORIGEM  FROM VW_RAIS_13S
UNION ALL
SELECT BDCODEMP, BDCODCOL, BDREF, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0,0,0,0,BDTIPO, 0 BDORIGEM  FROM VW_RAIS_C13
UNION ALL
SELECT FF.BDCODEMP, FF.BDCODCOL, FF.BDREF, 0,0,0,0,FF.BDBRAISFN, FF.BDBRAIS13, FF.BDBRAISA13, FF.BDBRAISC13, ff.BDTIPO, 1 BDORIGEM FROM vw_ficha_rais FF
)
GROUP BY BDCODEMP, BDCODCOL, BDREF

) x

--join vw_tempresas_ref_join EMP on (EMP.BDCODEMP = X.BDCODEMP)

--join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL)
)
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TFICHARAIS_DETR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TFICHARAIS_DETR(
BDCODEMP,
BDCODCOL,
BDREF,
BDDATAENT,
BDCODCENTO,
BDCODTPCC,
BDANO,
BDBRAISFN,
BDBRAIS13,
BDBRAISA13,
BDBRAISC13,
BDORIGEM)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREF,
  BDDATAENT,
  BDCODCENTO,
  BDCODTPCC,
  SUBSTRING(CAST(BDREF AS VARCHAR(6)) FROM 1 FOR 4),
  BDBRAISFN,
  BDBRAIS13,
  BDBRAISA13,
  BDBRAISC13,
  ORIGEM
FROM (
SELECT x.BDCODEMP, x.BDCODCOL, x.BDREF,
       BDDATAENT, BDCODCENTO, BDCODTPCC,
       CASE WHEN x.ORIGEM = 0 THEN x.BDBRAISFN ELSE x.x1 END BDBRAISFN,
       CASE WHEN x.ORIGEM = 0 THEN x.BDBRAIS13 ELSE x.x2 END BDBRAIS13,
       CASE WHEN x.ORIGEM = 0 THEN x.BDBRAISA13 ELSE x.x3 END BDBRAISA13,
       CASE WHEN x.ORIGEM = 0 THEN x.BDBRAISC13 ELSE x.x4 END BDBRAISC13,
       ORIGEM

FROM (

SELECT BDCODEMP, BDCODCOL, BDREF, BDDATAENT, BDCODCENTO, BDCODTPCC,

       BDBRAISFN BDBRAISFN, BDBRAIS13 BDBRAIS13, BDBRAISA13 BDBRAISA13, BDBRAISC13 BDBRAISC13, x1 x1, x2 x2, x3 x3, x4 x4,

       BDORIGEM ORIGEM

       FROM (
SELECT BDCODEMP, BDCODCOL, BDREF,  BDDATAENT, BDCODCENTO, BDCODTPCC,
 BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0 x1,0 x2,0 x3,0 x4, BDTIPO, 0 BDORIGEM FROM VW_RAIS_FOL_NORMAL_DETR
UNION ALL
SELECT BDCODEMP, BDCODCOL, BDREF, BDDATAENT, BDCODCENTO, BDCODTPCC,
 BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0,0,0,0,BDTIPO, 0 BDORIGEM  FROM VW_RAIS_FOL_COMPLEMENTAR_DETR
UNION ALL
SELECT BDCODEMP, BDCODCOL, BDREF, CAST(NULL AS DATE) BDDATAENT, CAST(NULL AS INTEGER) BDCODCENTO, CAST(NULL AS INTEGER) BDCODTPCC,
BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0,0,0,0,BDTIPO, 0 BDORIGEM  FROM VW_RAIS_A13
UNION ALL
SELECT BDCODEMP, BDCODCOL, BDREF, CAST(NULL AS DATE) BDDATAENT, CAST(NULL AS INTEGER) BDCODCENTO, CAST(NULL AS INTEGER) BDCODTPCC,
BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0,0,0,0,BDTIPO, 0 BDORIGEM  FROM VW_RAIS_13S
UNION ALL
SELECT BDCODEMP, BDCODCOL, BDREF,CAST(NULL AS DATE) BDDATAENT, CAST(NULL AS INTEGER) BDCODCENTO, CAST(NULL AS INTEGER) BDCODTPCC,
BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0,0,0,0,BDTIPO, 0 BDORIGEM  FROM VW_RAIS_C13
UNION ALL
SELECT BDCODEMP, BDCODCOL, BDREF,CAST(NULL AS DATE) BDDATAENT, CAST(NULL AS INTEGER) BDCODCENTO, CAST(NULL AS INTEGER) BDCODTPCC,
BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0,0,0,0,BDTIPO, 0 BDORIGEM  FROM VW_RAIS_FOL_AVULSA
UNION ALL
SELECT FF.BDCODEMP, FF.BDCODCOL, FF.BDREF, CAST(NULL AS DATE) BDDATAENT, CAST(NULL AS INTEGER) BDCODCENTO, CAST(NULL AS INTEGER) BDCODTPCC,
0,0,0,0,FF.BDBRAISFN, FF.BDBRAIS13, FF.BDBRAISA13, FF.BDBRAISC13, ff.BDTIPO, 1 BDORIGEM FROM vw_ficha_rais FF
)

) x

--join vw_tempresas_ref_join EMP on (EMP.BDCODEMP = X.BDCODEMP)

--join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL)
)
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TITICOL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TITICOL(
BDCODEMP,
BDCODCOL,
BDCODITI,
BDDIASEMITF,
BDREFITF,
BDHORARIOITF,
BDQTDITF)
 AS 
SELECT
  BASE.bdcodemp,
  BASE.bdcodcol,
  REF.bdcoditi,
  REF.bddiasemitf,
  REF.bdrefitf,
  REF.bdhorarioitf,
  REF.bdqtditf
FROM
(
  SELECT
      X.bdcodemp,
      X.bdcodcol,
      COALESCE
  (
      (SELECT MAX(d2.bdrefitf) FROM vrhf_emp_titicol d2 WHERE d2.bdcodemp = x.bdcodemp AND d2.bdcodcol = x.bdcodcol AND CAST(d2.BDREFITF AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefitf) FROM vrhf_emp_titicol d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol)
  ) AS bdrefitf
  FROM VRH_EMP_TCOLCON x

) AS BASE, vrhf_emp_titicol REF
WHERE BASE.BDCODEMP = REF.BDCODEMP AND BASE.BDCODCOL = REF.BDCODCOL AND BASE.BDREFITF = REF.BDREFITF
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TNOTASFISCAIS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TNOTASFISCAIS(
BDCODEMP,
BDCHAVE,
BDCODCENTRO,
BDCODTPCC,
BDREFNF,
BDNOTAFISCAL,
BDDATAEMINF,
BDVALNF,
BDVALDESCNF,
BDPERCRETENCAONF,
BDTIPOLAN)
 AS 
SELECT nf.BDCODEMP,
    nf.BDCHAVE,
    nf.BDCODCENTRO,
    nf.BDCODTPCC,
    nf.BDREFNF,
    nf.BDNOTAFISCAL,
    nf.BDDATAEMINF,
    nf.BDVALNF,
    nf.BDVALDESCNF - (SELECT COALESCE(SUM(r.bdvalor),0) bdvalor FROM vrh_emp_rnf r WHERE nf.bdcodemp = r.bdcodemp AND nf.bdchave = r.bdchave) BDVALDESCNF,
    nf.BDPERCRETENCAONF,
    nf.BDTIPOLAN

FROM vrhf_emp_tnotasfiscais nf
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TPREPFN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TPREPFN(
BDCODEMP,
BDCODCOL,
BDORDEM,
BDCODCENTRO,
BDCODTPCC,
BDDATAENTRADA,
BDHORAENTRADA,
BDTIPO,
BDQTDTEMPO,
BDREF)
 AS 
SELECT
    bdcodemp,
    bdcodcol,
    bdordem,
    bdcodcentro,
    bdcodtpcc,
    bddataentrada,
    bdhoraentrada,
    bdtipo,
    bdqtdtempo,
    CAST((SUBSTRING(CAST(BDDATAENTRADA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAENTRADA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER)
FROM vrhf_emp_tprepfn
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TPREPFN_MAX_NOVO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TPREPFN_MAX_NOVO(
BDCODEMP,
BDCODCOL,
BDORDEM)
 AS 
SELECT w.bdcodemp,
       w.bdcodcol,

       (SELECT FIRST 1 x.bdordem FROM VRHF_EMP_TPREPFN x
        WHERE x.bdcodemp = w.bdcodemp AND x.bdcodcol = w.bdcodcol AND
              x.bddataentrada <= (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES'))) AS DATE) FROM rdb$database)
        ORDER BY x.bddataentrada DESC,x.bdhoraentrada DESC
        )

FROM vrh_emp_tcolcon w
;


/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TPREPFN_ATU (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TPREPFN_ATU(
BDCODEMP,
BDCODCOL,
BDCODCENTRO,
BDCODTPCC,
BDCODCENCUS,
BDDATAENTRADA,
BDHORAENTRADA,
BDORDEM,
BDNOMCC,
BDNOMTOM,
BDCNPJTOM)
 AS 
SELECT x.bdcodemp,x.bdcodcol,w.bdcodcentro,toma.bdcodcencus,
       w.bdcodtpcc,w.bddataentrada,w.bdhoraentrada,w.bdordem,
       cc.bdnomcta BDNOMCC, toma.bdnomcta BDNOMTOM, toma.bdcnpjtom

FROM vw_vrhf_emp_tprepfn_max_novo x
LEFT OUTER JOIN vrhf_emp_tprepfn w ON (x.bdcodemp = w.bdcodemp AND x.bdcodcol = w.bdcodcol AND x.bdordem = w.bdordem)
LEFT OUTER JOIN centros_tpcc cc ON (cc.bdcodcentro = w.bdcodcentro AND cc.bdcodtpcc = w.bdcodtpcc)
LEFT OUTER JOIN VRHF_SP_TOMADOR(w.bdcodtpcc,w.bdcodcentro) toma ON (toma.bdcodcencus = w.bdcodtpcc AND toma.bdcodcentro = w.bdcodcentro)
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TPROVISAO13_CC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TPROVISAO13_CC(
    BDCODEMP,
    BDCODCOL,
    BDLINHAP13,
    BDREFP13,
    BDORDEMCCP13,
    BDPLANOCC,
    BDCODCENTRO,
    BDCODHIST,
    BDSALBASEP13,
    BDADICIONAISP13,
    BDMEDIASP13,
    BDOUTRASBASESP13,
    BDCODTPCC,
    BDVLR13SALP13,
    BDFGTSP13,
    BDINSSP13,
    BDTERCFPASP13,
    BDCNAERATP13,
    BDRATAPOP13,
    BDPISP13,
    BDBASEFGTSP13,
    BDBASEINSSP13,
    BDRESCISAOP13,
    BDBASEPISP13,
    BDPROPP13,
    BDTOTP13,
    BDPORTOMADORP13,
    BDOBSERVACAO,
    BDORDEM)
AS
SELECT  x.BDCODEMP,x.BDCODCOL, x.BDLINHAP13, x.BDREFP13, x.BDORDEMCCP13,
        x.BDPLANOCC, x.BDCODCENTRO, x.BDCODHIST,
        p13.BDSALBASEP13, p13.BDADICIONAISP13, p13.BDMEDIASP13, p13.BDOUTRASBASESP13,
        x.BDCODTPCC, x.BDVLR13SALP13, x.BDFGTSP13, x.BDINSSP13, x.BDTERCFPASP13, x.BDCNAERATP13, x.BDRATAPOP13, x.BDPISP13,
        p13.BDBASEFGTSP13, p13.BDBASEINSSP13, p13.BDRESCISAOP13, 
        p13.BDBASEPISP13, p13.BDPROPP13,
        COALESCE(X.BDVLR13SALP13,0)+COALESCE(X.bdfgtsp13,0)+COALESCE(X.bdinssp13,0)+COALESCE(X.BDTERCFPASP13,0)+COALESCE(X.BDCNAERATP13,0)+
        COALESCE(X.BDRATAPOP13,0)+COALESCE(X.bdpisp13,0) BDTOTP13, p13.BDPORTOMADORP13, p13.BDOBSERVACAO, X.BDORDEM
    
FROM (

SELECT det.bdcodemp, det.bdcodcol, det.bdlinhap13, det.bdrefp13, det.bdordemccp13,
       det.bdplanocc, cccol.bdcodcentro,cccol.bdcodtpcc,
       det.bdcodhist,
       SUM(det.bd13sal) BDVLR13SALP13,
       SUM(det.bdfgts) bdfgtsp13,
       SUM(det.bdinss) bdinssp13,
       SUM(det.bdfpas) BDTERCFPASP13,
       SUM(det.bdcnae) BDCNAERATP13,
       SUM(det.bdratapo) BDRATAPOP13,
       SUM(det.bdpis) bdpisp13,
       det.bdordem
FROM VRHF_EMP_TPROVISAO13_DET det
LEFT OUTER JOIN vrhf_emp_tprepfn cccol ON (det.bdcodemp = cccol.bdcodemp AND det.bdcodcol = cccol.bdcodcol AND det.bdcodhist = cccol.bdordem)
GROUP BY det.bdcodemp, det.bdcodcol, det.bdlinhap13, det.bdrefp13, det.bdordemccp13, det.bdplanocc, cccol.bdcodcentro,cccol.bdcodtpcc, det.bdcodhist, det.bdordem

) x
JOIN vrhf_emp_tprovisao13 p13 ON (x.bdcodemp = p13.bdcodemp AND
                                  x.bdcodcol = p13.bdcodcol AND
                                  x.bdlinhap13 = p13.bdlinhap13 AND
                                  x.bdrefp13 = p13.bdrefp13 AND
                                  x.bdordemccp13 = p13.bdordemccp13 AND
                                  x.bdplanocc = p13.bdplanocc)
;

/* CREATE OR ALTER VIEW: VW_VSUC_TSELECOESCONTA (ViwData.CreateDependDef) (Pedro)*/
CREATE OR ALTER VIEW VW_VSUC_TSELECOESCONTA(
    BDCODIGOSELCONTA,
    BDCODEMP,
    BDCODUSU,
    BDNOMUSU,
    BDCODSIS,
    BDNOMSIS,
    BDNOMESELCONTA)
AS
SELECT SEL.BDCODIGOSELCONTA, SEL.BDCODEMP, USU.BDCODUSU, USU.BDNOMUSU, SIS.BDCODSIS, SIS.BDNOMSIS, SEL.BDNOMESELCONTA
  FROM TSELECOESEMP_CONTA SEL 
  INNER JOIN TSISTEMA SIS ON (SEL.BDCODSIS = SIS.BDCODSIS) 
  LEFT OUTER JOIN TUSUARIO USU ON (SEL.BDCODUSU = USU.BDCODUSU) 
  WHERE (SEL.BDCODUSU IS NULL OR SEL.BDCODUSU = (SELECT rdb$get_context('USER_SESSION', 'W_USUARIO') FROM rdb$database))
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TPROVISAOFERIAS_CC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TPROVISAOFERIAS_CC(
    BDCODEMP,
    BDCODCOL,
    BDLINHAPFER,
    BDREFPFER,
    BDINIPERAQUISPFER,
    BDORDEMCCPFER,
    BDPLANOCC,
    BDCODCENTRO,
    BDSALBASEPFER,
    BDADICIONAISPFER,
    BDMEDIASPFER,
    BDOUTRASBASESPFER,
    BDCODTPCC,
    BDFERIASPFER,
    BDUMTERCOPFER,
    BDFGTSPFER,
    BDINSSPFER,
    BDTERCFPASPFER,
    BDCNAERATPFER,
    BDRATAPOPFER,
    BDPISPFER,
    BDBASEFGTSPFER,
    BDBASEINSSPFER,
    BDRESCISAOPFER,
    BDBASEPISPFER,
    BDPROPPFER,
    BDTOTPFER,
    BDPORTOMADORPFER,
    BDFALTASPFER,
    BDDATAVENCPFER,
    BDMVPFER,
    BDPRPFER,
    BDSDPFER,
    BDCENTROTPCC,
    BDOBSERVACAO)
AS
SELECT PFER.BDCODEMP, PFER.BDCODCOL, PFER.BDLINHAPFER, PFER.BDREFPFER, PFER.BDINIPERAQUISPFER, PFER.BDORDEMCCPFER, PFER.BDPLANOCC,
       pfer.BDCODCENTRO, FER.BDSALBASEPFER, FER.BDADICIONAISPFER, FER.BDMEDIASPFER,
       FER.BDOUTRASBASESPFER, pfer.BDCODTPCC,

       pfer.bdferias BDFERIASPFER,
       pfer.bdumterco BDUMTERCOPFER,
       PFER.bdfgts BDFGTSPFER,
       PFER.bdinss BDINSSPFER,
       PFER.bdfpas BDTERCFPASPFER,
       PFER.bdcnae BDCNAERATPFER,
       PFER.bdratapo BDRATAPOPFER,
       PFER.bdpis BDPISPFER,

       FER.BDBASEFGTSPFER, FER.BDBASEINSSPFER, FER.BDRESCISAOPFER, FER.BDBASEPISPFER,
       FER.BDPROPPFER, COALESCE(PFER.bdferias,0) + COALESCE(PFER.bdumterco,0) + COALESCE(PFER.bdfgts,0) + COALESCE(PFER.bdinss,0) + COALESCE(PFER.bdfpas,0) +
       COALESCE(PFER.bdcnae,0) + COALESCE(PFER.bdratapo,0) + COALESCE(PFER.bdpis,0) BDTOTPFER,
       FER.BDPORTOMADORPFER, FER.BDFALTASPFER,
       FER.BDDATAVENCPFER, 
       FER.BDMVPFER, FER.BDPRPFER, FER.BDSDPFER,

       CAST(COALESCE(pfer.BDCODCENTRO, 0) AS VARCHAR(5))||'.'||(SELECT BDRETORNO FROM PREENCHE_ESQUERDA(CAST(COALESCE(pfer.BDCODTPCC, 0) AS VARCHAR(10)), 10, '0')) BDCENTROTPCC,
                            CAST(NULL AS VARCHAR(3000))
       
FROM (

SELECT x.bdcodemp, x.bdcodcol, x.bdlinhapfer, x.bdiniperaquispfer, x.bdordemccpfer, x.bdplanocc, x.bdrefpfer, hist.bdcodcentro, hist.bdcodtpcc,
      SUM(x.bdferias) bdferias,
      SUM(x.bdumterco) bdumterco,
      SUM(x.bdfgts) bdfgts,
      SUM(x.bdinss) bdinss,
      SUM(x.bdfpas) bdfpas,
      SUM(x.bdcnae) bdcnae,
      SUM(x.bdratapo) bdratapo,
      SUM(x.bdpis) bdpis
FROM VRHF_EMP_TPROVISAOFERIAS_det x
LEFT OUTER JOIN vrhf_emp_tprepfn hist ON (x.bdcodemp = hist.bdcodemp AND x.bdcodcol = hist.bdcodcol AND x.bdcodhist = hist.bdordem)
GROUP BY x.bdcodemp, x.bdcodcol, x.bdlinhapfer, x.bdiniperaquispfer, x.bdordemccpfer, x.bdplanocc, x.bdrefpfer, hist.bdcodcentro, hist.bdcodtpcc

) PFER
JOIN VRHF_EMP_TPROVISAOFERIAS fer ON (pfer.bdcodemp = fer.bdcodemp AND
                                          pfer.bdcodcol = fer.bdcodcol AND
                                          pfer.bdlinhapfer = fer.bdlinhapfer AND
                                          pfer.bdiniperaquispfer = fer.bdiniperaquispfer AND
                                          pfer.bdordemccpfer = fer.bdordemccpfer AND
                                          pfer.bdplanocc =fer.bdplanocc AND
                                          pfer.bdrefpfer = fer.bdrefpfer)
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TVERBA_13_RAT_AGRU (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TVERBA_13_RAT_AGRU(
BDCODEMP,
BDREF13,
BDCHAVE,
BDCODCOL,
BDCODVER,
BDREFV13,
BDREFAUXV13,
BDVALV13,
BDIGNREFV13,
BDIGNVALV13,
BDORVERBA13,
BDIGNREFAV13,
BDCODCENTRO,
BDCODTPCC,
BDCODTOMADOR,
BDCOMPESP,
BDFORMREFAUX,
BDFORMREF,
BDFORMVAL)
 AS 
SELECT a.BDCODEMP,
    a.BDREF13,
    a.BDCHAVE,
    a.BDCODCOL,
    a.BDCODVER,

    CASE WHEN (v.BDTIPOREFVER = 4) THEN BDREFV13max ELSE BDREFV13sum END,

    CASE WHEN (SUBSTRING(UPPER(v.BDDEDFORMREFAUXVER) FROM 1 FOR 1) = 'T') THEN a.bdrefauxsum ELSE a.bdrefauxmax END,

    a.BDVALV13,
    a.BDIGNREFV13,
    a.BDIGNVALV13,
    a.BDORVERBA13,
    a.BDIGNREFAV13,
    a.BDCODCENTRO,
    a.BDCODTPCC,
    a.BDCODTOMADOR,
    a.BDCOMPESP,
    a.BDFORMREFAUX,
    a.BDFORMREF,
    a.BDFORMVAL
FROM (
SELECT X.BDCODEMP,
    X.BDREF13,
    NULL BDCHAVE,
    X.BDCODCOL,
    X.BDCODVER,

    SUM(X.BDREFV13) BDREFV13sum,
    MAX(X.BDREFV13) BDREFV13max,

    SUM(X.BDREFAUXV13) bdrefauxsum,
    MAX(BDREFAUXV13) bdrefauxmax,

    SUM(X.BDVALV13) BDVALV13,
    MAX(X.BDIGNREFV13) BDIGNREFV13,
    MAX(X.BDIGNVALV13) BDIGNVALV13,
    MAX(X.BDORVERBA13) BDORVERBA13,
    MAX(X.BDIGNREFAV13) BDIGNREFAV13,
    NULL BDCODCENTRO,
    NULL BDCODTPCC,
    NULL BDCODTOMADOR,
    X.BDCOMPESP,
    X.BDFORMREFAUX,
    X.BDFORMREF,
    X.BDFORMVAL

FROM VRHF_EMP_TVERBA_13_RAT X
GROUP BY x.bdcodemp, x.bdcodcol, x.bdref13, x.bdcodver,
         X.BDCOMPESP, X.BDFORMREFAUX, X.BDFORMREF, X.BDFORMVAL
) a
LEFT OUTER JOIN VW_VERBAS_REF_ATUAL v ON (a.bdcodver = v.bdcodver)
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TVERBA_13_RAT_CC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TVERBA_13_RAT_CC(
BDCODEMP,
BDREF13,
BDCHAVE,
BDCODCOL,
BDCODVER,
BDREFV13,
BDREFAUXV13,
BDVALV13,
BDIGNREFV13,
BDIGNVALV13,
BDORVERBA13,
BDIGNREFAV13,
BDCODCENTRO,
BDCODTPCC,
BDCODTOMADOR,
BDCOMPESP,
BDFORMREFAUX,
BDFORMREF,
BDFORMVAL)
 AS 
SELECT a.BDCODEMP,
    a.BDREF13,
    a.BDCHAVE,
    a.BDCODCOL,
    a.BDCODVER,

    CASE WHEN (v.BDTIPOREFVER = 4) THEN BDREFV13max ELSE BDREFV13sum END,

    CASE WHEN (SUBSTRING(UPPER(v.BDDEDFORMREFAUXVER) FROM 1 FOR 1) = 'T') THEN a.bdrefauxsum ELSE a.bdrefauxmax END,

    a.BDVALV13,
    a.BDIGNREFV13,
    a.BDIGNVALV13,
    a.BDORVERBA13,
    a.BDIGNREFAV13,
    a.BDCODCENTRO,
    a.BDCODTPCC,
    a.BDCODTOMADOR,
    a.BDCOMPESP,
    a.BDFORMREFAUX,
    a.BDFORMREF,
    a.BDFORMVAL
FROM (
SELECT X.BDCODEMP,
    X.BDREF13,
    MAX(x.BDCHAVE) BDCHAVE,
    X.BDCODCOL,
    X.BDCODVER,

    SUM(X.BDREFV13) BDREFV13sum,
    MAX(X.BDREFV13) BDREFV13max,

    SUM(X.BDREFAUXV13) bdrefauxsum,
    MAX(BDREFAUXV13) bdrefauxmax,

    SUM(X.BDVALV13) BDVALV13,
    MAX(X.BDIGNREFV13) BDIGNREFV13,
    MAX(X.BDIGNVALV13) BDIGNVALV13,
    MAX(X.BDORVERBA13) BDORVERBA13,
    MAX(X.BDIGNREFAV13) BDIGNREFAV13,
    cc.bdcodcentro, 
    cc.bdcodtpcc, 
    tom.bdcodtpcc bdcodtomador,
    X.BDCOMPESP,
    X.BDFORMREFAUX,
    X.BDFORMREF,
    X.BDFORMVAL

FROM VRHF_EMP_TVERBA_13_RAT X
LEFT OUTER JOIN VRHF_EMP_T13SAL_RAT y ON (x.bdcodemp = y.bdcodemp AND x.bdcodcol = y.bdcodcol AND x.bdchave = y.bdchave AND x.bdref13 = y.bdref13)
LEFT OUTER JOIN vrhf_emp_tprepfn cc ON (y.bdcodemp = cc.bdcodemp AND y.bdcodcol = cc.bdcodcol AND y.bdordem = cc.bdordem)
LEFT OUTER JOIN vrhf_sp_tomador(cc.bdcodtpcc,cc.bdcodcentro) tom ON (cc.bdcodcentro = tom.bdcodcentro AND cc.bdcodtpcc = tom.bdcodcencus)

GROUP BY x.bdcodemp, x.bdcodcol, x.bdref13, x.bdcodver, cc.bdcodcentro, tom.bdcodtpcc, cc.bdcodtpcc,
         X.BDCOMPESP, X.BDFORMREFAUX, X.BDFORMREF, X.BDFORMVAL
) a
LEFT OUTER JOIN VW_VERBAS_REF_ATUAL v ON (a.bdcodver = v.bdcodver)
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TVERBA_13_RAT_TOM (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TVERBA_13_RAT_TOM(
BDCODEMP,
BDREF13,
BDCHAVE,
BDCODCOL,
BDCODVER,
BDREFV13,
BDREFAUXV13,
BDVALV13,
BDIGNREFV13,
BDIGNVALV13,
BDORVERBA13,
BDIGNREFAV13,
BDCODCENTRO,
BDCODTPCC,
BDCODTOMADOR,
BDCOMPESP,
BDFORMREFAUX,
BDFORMREF,
BDFORMVAL)
 AS 
SELECT a.BDCODEMP,
    a.BDREF13,
    a.BDCHAVE,
    a.BDCODCOL,
    a.BDCODVER,

    CASE WHEN (v.BDTIPOREFVER = 4) THEN BDREFV13max ELSE BDREFV13sum END,

    CASE WHEN (SUBSTRING(UPPER(v.BDDEDFORMREFAUXVER) FROM 1 FOR 1) = 'T') THEN a.bdrefauxsum ELSE a.bdrefauxmax END,

    a.BDVALV13,
    a.BDIGNREFV13,
    a.BDIGNVALV13,
    a.BDORVERBA13,
    a.BDIGNREFAV13,
    a.BDCODCENTRO,
    a.BDCODTPCC,
    a.BDCODTOMADOR,
    a.BDCOMPESP,
    a.BDFORMREFAUX,
    a.BDFORMREF,
    a.BDFORMVAL
FROM (
SELECT X.BDCODEMP,
    X.BDREF13,
    MAX(x.BDCHAVE) BDCHAVE,
    X.BDCODCOL,
    X.BDCODVER,

    SUM(X.BDREFV13) BDREFV13sum,
    MAX(X.BDREFV13) BDREFV13max,

    SUM(X.BDREFAUXV13) bdrefauxsum,
    MAX(BDREFAUXV13) bdrefauxmax,

    SUM(X.BDVALV13) BDVALV13,
    MAX(X.BDIGNREFV13) BDIGNREFV13,
    MAX(X.BDIGNVALV13) BDIGNVALV13,
    MAX(X.BDORVERBA13) BDORVERBA13,
    MAX(X.BDIGNREFAV13) BDIGNREFAV13,
    cc.bdcodcentro,
    tom.bdcodtpcc,
    tom.bdcodtpcc bdcodtomador,
    X.BDCOMPESP,
    X.BDFORMREFAUX,
    X.BDFORMREF,
    X.BDFORMVAL

FROM VRHF_EMP_TVERBA_13_RAT X
LEFT OUTER JOIN VRHF_EMP_T13SAL_RAT y ON (x.bdcodemp = y.bdcodemp AND x.bdcodcol = y.bdcodcol AND x.bdchave = y.bdchave AND x.bdref13 = y.bdref13)
LEFT OUTER JOIN vrhf_emp_tprepfn cc ON (y.bdcodemp = cc.bdcodemp AND y.bdcodcol = cc.bdcodcol AND y.bdordem = cc.bdordem)
LEFT OUTER JOIN vrhf_sp_tomador(cc.bdcodtpcc,cc.bdcodcentro) tom ON (cc.bdcodcentro = tom.bdcodcentro AND cc.bdcodtpcc = tom.bdcodcencus)

GROUP BY x.bdcodemp, x.bdcodcol, x.bdref13, x.bdcodver, cc.bdcodcentro, tom.bdcodtpcc,
         X.BDCOMPESP, X.BDFORMREFAUX, X.BDFORMREF, X.BDFORMVAL
) a
LEFT OUTER JOIN VW_VERBAS_REF_ATUAL v ON (a.bdcodver = v.bdcodver)
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TVERBAAD (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TVERBAAD(
BDCODEMP,
BDCODCOL,
BDDATAAD,
BDCODVER,
BDREFVAD,
BDREFAUXVAD,
BDVALVAD,
BDIGNREFVAD,
BDIGNREFAVAD,
BDIGNVALVAD,
BDORVERBAAD,
BDBASEAD,
BDTIPOAD,
BDVALPERCAD,
BDBASEIRAD,
BDDATABAIXAAD,
BDREFBAIXAAD,
BDVALORIRAD,
BDPERCIRAD,
BDDEPIRAD,
BDCREDITOAD,
BDDEBITOAD,
BDLIQUIDO,
BDREFAD,
BDCOMPESP,
BDFORMREFAUX,
BDFORMREF,
BDFORMVAL)
 AS 
SELECT
  X.bdcodemp,
  X.bdcodcol,
  X.bddataad,
  X.bdcodver,
  X.bdrefvad,
  X.bdrefauxvad,
  X.bdvalvad,
  X.bdignrefvad,
  X.bdignrefavad,
  X.bdignvalvad,
  X.bdorverbaad,
  Y.BDBASEAD,
  Y.BDTIPOAD,
  Y.BDVALPERCAD,
  Y.BDBASEIRAD,
  Y.BDDATABAIXAAD,
  Y.BDREFBAIXAAD,
  Y.BDVALORIRAD,
  Y.BDPERCIRAD,
  Y.BDDEPIRAD,
  Y.BDCREDITOAD,
  Y.BDDEBITOAD,
  Y.BDLIQUIDO,
  Y.BDREFAD,
  X.BDCOMPESP,
  X.BDFORMREFAUX,
  X.BDFORMREF,
  X.BDFORMVAL

FROM
  vrhf_emp_tverbaad X,
  VRHF_EMP_TADSAL Y
WHERE
  X.BDCODEMP = Y.BDCODEMP AND X.BDCODCOL = Y.BDCODCOL AND X.BDDATAAD = Y.BDDATAAD
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMP_TVERBAFN_DET (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMP_TVERBAFN_DET(
BDCODEMP,
BDCODCOL,
BDNOMCOL,
BDDATAINI,
BDDATAFIM)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  COLCAD.BDNOMCOL,
  CAST((SUBSTRING(X.BDDETALHEFND FROM 21 FOR 2)||'/'||SUBSTRING(X.BDDETALHEFND FROM 18 FOR 2)||'/'||SUBSTRING(X.BDDETALHEFND FROM 24 FOR 4)) AS DATE),
  CAST((SUBSTRING(X.BDDETALHEFND FROM 36 FOR 2)||'/'||SUBSTRING(X.BDDETALHEFND FROM 33 FOR 2)||'/'||SUBSTRING(X.BDDETALHEFND FROM 39 FOR 4)) AS DATE)
FROM VRHF_EMP_TVERBAFN_DET X
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON (COLCAD.BDCODEMP = X.BDCODEMP AND COLCAD.BDCODCOL = X.BDCODCOL)
WHERE X.BDTIPODETFND = 3 and substring(X.BDDETALHEFND from 1 for 17) = 'Per. aquisitivo: '
UNION

SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  COLCAD.BDNOMCOL,
  CAST((SUBSTRING(X.BDDETALHEFTD FROM 21 FOR 2)||'/'||SUBSTRING(X.BDDETALHEFTD FROM 18 FOR 2)||'/'||SUBSTRING(X.BDDETALHEFTD FROM 24 FOR 4)) AS DATE),
  CAST((SUBSTRING(X.BDDETALHEFTD FROM 36 FOR 2)||'/'||SUBSTRING(X.BDDETALHEFTD FROM 33 FOR 2)||'/'||SUBSTRING(X.BDDETALHEFTD FROM 39 FOR 4)) AS DATE)
FROM VRHF_EMP_TVERBAFT_DET X
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON (COLCAD.BDCODEMP = X.BDCODEMP AND COLCAD.BDCODCOL = X.BDCODCOL)
WHERE X.BDTIPODETFTD = 3 and substring(X.BDDETALHEFTD from 1 for 17) = 'Per. aquisitivo: '
;

/* CREATE OR ALTER VIEW: VW_VRHF_EMPRESAS_REF_ATUAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_EMPRESAS_REF_ATUAL(
    BDCODEMP,
    BDPAGEMP,
    BDFECHAMESEMP,
    BDFECHAVTEMP,
    BDARREMP,
    BDTIPOARREMP,
    BDTIPOFEREMP,
    BDSOMSALFEREMP,
    BDTIPOAD13EMP,
    BDSOMSALAD13EMP,
    BDPERCADSALEMP,
    BDREFHOREMP,
    BDLICREMFEREMP,
    BDESTOUROEMP,
    BDESTOURORESEMP,
    BDFALFEREMP,
    BDFALHORFEREMP,
    BDDEPIRRESCEMP,
    BDMESDSREMP,
    BDDESCFALHORASDIAS,
    BDCODGPS,
    BDCNAERATEMP,
    BDEMPEMP,
    BDAUTEMP,
    BDFUNEMP,
    BDCODFPASTERC,
    BDFAP,
    BDCODFPAS,
    BDCODTERC,
    BDPERTERC,
    BDSIMPLESGPS,
    BDCODSINPAT,
    BDCAPSOCEMP,
    BDETIQEMP,
    BDTAXSEREMP,
    BDREFCAGEDEMP,
    BDCALCFCNAFNEMP,
    BDCALCC13NAFNEMP,
    BDTIPOCONTAB,
    BDTIPOEMIGUIAS,
    BDPROPADMEMP,
    BDPROPRESEMP,
    BDPROPFEREMP,
    BDPROPSITEMP,
    BDCALCMEDIASTEMP,
    BDNATESTEMP,
    BDDATABASEEMP,
    BDPATEMP,
    BDNROPROPEMP,
    BDSERPROPRIOPATEMP,
    BDPATREFCONVENIOEMP,
    BDPATCESTAALIMENTOEMP,
    BDPATADMCOZINHAEMP,
    BDPATREFTRANSPEMP,
    BDPATALICONVENIOEMP,
    BDSINDICALIZEMP,
    BDCODBAN,
    BDCODAG,
    BDIDENTEMP,
    BDCODUFSEFIP,
    BDCATSEFIPEMP,
    BDISENFILEMP,
    BDCETRTALIZAEMP,
    BDCODSEFIPEMP,
    BDCODIR,
    BDCODINSS,
    BDCODMEN,
    BDCODPQUA,
    BDPROPTOMEMP,
    BDDIASTRABADI,
    BDANOSAVPREVIOIND,
    BDCODPLACONVSAU,
    BDTIPCALCFERCOLINF,
    BDTIPCALCFERCOLSUP,
    BDLIMINARAVPREVEMP,
    BDARREDONDAFN,
    BDARREDONDAFC,
    BDARREDONDAFE,
    BDARREDONDAA13,
    BDARREDONDA13,
    BDARREDONDAC13,
    BDARREDONDAAD,
    BDARREDONDAAU,
    BDARREDONDAFA,
    BDARREDONDAFTINT,
    BDPAGEMPCONTR,
    BDPERCLIMIDESCPAR,
    BDCALCC13FNNEGEMP,
    BDDSRMEDATUSAL,
    BDIDADESAUDEEMP,
    BDCALC13MP936,
    BDDESCCOMPL13NEG,
    BDRATEIO13SAL,
    BDCONSIDERAFERICIDADETOM,
    BDRATEIOINTEGRALVER)
AS
SELECT EMP_REF.BDCODEMP,
       EMP_CALC.BDPAGEMP,
       EMP_CALC.BDFECHAMESEMP,
       EMP_CALC.BDFECHAVTEMP,
       EMP_CALC.BDARREMP,
       EMP_CALC.BDTIPOARREMP,
       EMP_CALC.BDTIPOFEREMP,
       EMP_CALC.BDSOMSALFEREMP,
       EMP_CALC.BDTIPOAD13EMP,
       EMP_CALC.BDSOMSALAD13EMP,
       EMP_CALC.BDPERCADSALEMP,
       EMP_CALC.BDREFHOREMP,
       EMP_CALC.BDLICREMFEREMP,
       EMP_CALC.BDESTOUROEMP,
       EMP_CALC.BDESTOURORESEMP,
       EMP_CALC.BDFALFEREMP,
       EMP_CALC.BDFALHORFEREMP,
       EMP_CALC.BDDEPIRRESCEMP,
       EMP_CALC.BDMESDSREMP,
       EMP_CALC.BDDESCFALHORASDIAS,
       EMP_GPS.BDCODGPS,
       EMP_GPS.BDCNAERATEMP,
       EMP_GPS.BDEMPEMP,
       EMP_GPS.BDAUTEMP,
       EMP_GPS.BDFUNEMP,
       EMP_GPS.BDCODFPASTERC,
       EMP_GPS.BDFAP,
       EMP_GPS.BDCODFPAS,
       EMP_GPS.BDCODTERC,
       EMP_GPS.BDPERTERC,
       EMP_GPS.BDSIMPLESGPS,
       EMP_GRCS.BDCODSINPAT,
       EMP_GRCS.BDCAPSOCEMP,
       EMP_PAR.BDETIQEMP,
       EMP_PAR.BDTAXSEREMP,
       EMP_PAR.BDREFCAGEDEMP,
       EMP_PAR.BDCALCFCNAFNEMP,
       EMP_PAR.BDCALCC13NAFNEMP,
       EMP_PAR.BDTIPOCONTAB,
       EMP_PAR.BDTIPOEMIGUIAS,
       EMP_PROP.BDPROPADMEMP,
       EMP_PROP.BDPROPRESEMP,
       EMP_PROP.BDPROPFEREMP,
       EMP_PROP.BDPROPSITEMP,
       EMP_PROP.BDCALCMEDIASTEMP,
       EMP_RAIS.BDNATESTEMP,
       EMP_RAIS.BDDATABASEEMP,
       EMP_RAIS.BDPATEMP,
       EMP_RAIS.BDNROPROPEMP,
       EMP_RAIS.BDSERPROPRIOPATEMP,
       EMP_RAIS.BDPATREFCONVENIOEMP,
       EMP_RAIS.BDPATCESTAALIMENTOEMP,
       EMP_RAIS.BDPATADMCOZINHAEMP,
       EMP_RAIS.BDPATREFTRANSPEMP,
       EMP_RAIS.BDPATALICONVENIOEMP,
       EMP_RAIS.BDSINDICALIZEMP,
       EMP_SEFIP.BDCODBAN,
       EMP_SEFIP.BDCODAG,
       EMP_SEFIP.BDIDENTEMP,
       EMP_SEFIP.bdcoduf,
       EMP_SEFIP.BDCATSEFIPEMP,
       EMP_SEFIP.BDISENFILEMP,
       EMP_SEFIP.BDCETRTALIZAEMP,
       EMP_SEFIP.BDCODSEFIPEMP,
       EMP_VINC.BDCODIR,
       EMP_VINC.BDCODINSS,
       EMP_VINC.BDCODMEN,
       EMP_VINC.BDCODPQUA,
       EMP_PROP.BDPROPTOMEMP,
       EMP_PROP.BDDIASTRABADI,
       EMP_CALC.bdanosavprevioind,
       EMP_VINC.BDCODPLACONVSAU,
       EMP_CALC.BDTIPCALCFERCOLINF,
       EMP_CALC.BDTIPCALCFERCOLSUP,
       EMP_CALC.BDLIMINARAVPREVEMP,
       EMP_CALC.BDARREDONDAFN,
       EMP_CALC.BDARREDONDAFC,
       EMP_CALC.BDARREDONDAFE,
       EMP_CALC.BDARREDONDAA13,
       EMP_CALC.BDARREDONDA13,
       EMP_CALC.BDARREDONDAC13,
       EMP_CALC.BDARREDONDAAD,
       EMP_CALC.BDARREDONDAAU,
       EMP_CALC.BDARREDONDAFA,
       EMP_CALC.BDARREDONDAFTINT, 
       EMP_CALC.BDPAGEMPCONTR,
       EMP_CALC.BDPERCLIMIDESCPAR,  
       EMP_PAR.BDCALCC13FNNEGEMP,
       EMP_CALC.BDDSRMEDATUSAL,
       EMP_CALC.BDIDADESAUDEEMP,
       EMP_PAR.BDCALC13MP936,
       EMP_PAR.BDDESCCOMPL13NEG,
       EMP_GPS.BDRATEIO13SAL,
       EMP_CALC.bdconsiderafericidadetom,
       EMP_CALC.BDRATEIOINTEGRALVER
FROM TEMPRESAS EMP_REF
LEFT OUTER JOIN VW_VRHF_BASE_TEMPCALC EMP_CALC ON (EMP_CALC.BDCODEMP = EMP_REF.BDCODEMP)
LEFT OUTER JOIN VW_VRHF_BASE_TEMPGPS EMP_GPS ON (EMP_GPS.BDCODEMP = EMP_REF.BDCODEMP)
LEFT OUTER JOIN VW_VRHF_BASE_TEMPGRCS EMP_GRCS ON (EMP_GRCS.BDCODEMP = EMP_REF.BDCODEMP)
LEFT OUTER JOIN VW_VRHF_BASE_TEMPPAR EMP_PAR ON (EMP_PAR.BDCODEMP = EMP_REF.BDCODEMP)
LEFT OUTER JOIN VW_VRHF_BASE_TEMPPROP EMP_PROP ON (EMP_PROP.BDCODEMP = EMP_REF.BDCODEMP)
LEFT OUTER JOIN VW_VRHF_BASE_TEMPRAIS EMP_RAIS ON (EMP_RAIS.BDCODEMP = EMP_REF.BDCODEMP)
LEFT OUTER JOIN VW_VRHF_BASE_TEMPSEFIP EMP_SEFIP ON (EMP_SEFIP.BDCODEMP = EMP_REF.BDCODEMP)
LEFT OUTER JOIN VW_VRHF_BASE_TEMPVINC EMP_VINC ON (EMP_VINC.BDCODEMP = EMP_REF.BDCODEMP)
where((EMP_REF.bdexcluiremp is null)or(upper(EMP_REF.bdexcluiremp)<>'TRUE'))
;

/* CREATE OR ALTER VIEW: VW_VRHF_FERIAS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_FERIAS(
    BDCODEMP,
    BDCODCOL,
    BDINIPERAQUISFE,
    BDCODFE,
    BDINIPERGOZOFE,
    BDFIMPERAQUISFE,
    BDFIMPERGOZOFE,
    BDDATAPAGFE,
    BDQTDGOZOFE,
    BDQTDABONOFE,
    BDSALDOINIFE,
    BDSALDOFIMFE,
    BDBASEIRFE,
    BDALIQIRFE,
    BDVALORIRFE,
    BDBASEINSSFE,
    BDALIQINSSFE,
    BDVALORINSSFE,
    BDDEPFE,
    BDSALBASEFE,
    BDSALBASEHEFE,
    BDDATABAIXAFE,
    BDCOLETIVASFE,
    BDREFPAGABOFE,
    BDBASEFGTSFE,
    BDVALORFGTSFE,
    BDVALORFGTSCSFE,
    BDMAIORREMFE,
    BDBSALFAMFE,
    BDSALFAMFE,
    BDCOMPETENCIAFE,
    BDFALTASFE,
    BDFERIADOSFE,
    BDSALDOFINALSINDFE,
    BDCODVER,
    BDREFVFE,
    BDREFAUXVFE,
    BDVALVFE,
    BDIGNREFVFE,
    BDIGNREFAVFE,
    BDIGNVALVFE,
    BDCREDITOFE,
    BDDEBITOFE,
    BDLIQUIDO,
    BDCALCA13FE,
    BDDATAAVISO,
    BDORDEM,
    BDINIGOZORECIBOFE,
    BDFIMGOZORECIBOFE,
    BDQTDGOZORECIBOFE,
    BDMIGRACAO)
AS
SELECT DFER.BDCODEMP,
       DFER.BDCODCOL,
       DFER.BDINIPERAQUISFE,
       DFER.BDCODFE,
       DFER.BDINIPERGOZOFE,
       DFER.BDFIMPERAQUISFE,
       DFER.BDFIMPERGOZOFE,
       DFER.BDDATAPAGFE,
       DFER.BDQTDGOZOFE,
       DFER.BDQTDABONOFE,
       DFER.BDSALDOINIFE,
       DFER.BDSALDOFIMFE,
       DFER.BDBASEIRFE,
       DFER.BDALIQIRFE,
       DFER.BDVALORIRFE,
       DFER.BDBASEINSSFE,
       DFER.BDALIQINSSFE,
       DFER.BDVALORINSSFE,
       DFER.BDDEPFE,
       DFER.BDSALBASEFE,
       DFER.BDSALBASEHEFE,
       DFER.BDDATABAIXAFE,
       DFER.BDCOLETIVASFE,
       DFER.BDREFPAGABOFE,
       DFER.BDBASEFGTSFE,
       DFER.BDVALORFGTSFE,
       DFER.BDVALORFGTSCSFE,
       DFER.BDMAIORREMFE,
       DFER.BDBSALFAMFE,
       DFER.BDSALFAMFE,
       DFER.BDCOMPETENCIAFE,
       DFER.BDFALTASFE,
       DFER.BDFERIADOSFE,
       DFER.BDSALDOFINALSINDFE,
       VFER.BDCODVER,
       VFER.BDREFVFE,
       VFER.BDREFAUXVFE,
       VFER.BDVALVFE,
       VFER.BDIGNREFAVFE,
       VFER.BDIGNREFVFE,
       VFER.BDIGNVALVFE,
       DFER.BDCREDITOFE,
       DFER.BDDEBITOFE,
       DFER.BDLIQUIDO,
       DFER.BDCALCA13FE,
       DFER.BDDATAAVISO,
       DFER.BDORDEM,
       DFER.BDINIGOZORECIBOFE,
       DFER.BDFIMGOZORECIBOFE,
       DFER.BDQTDGOZORECIBOFE,
       case when VFER.BDINIPERAQUISFE is null then 'TRUE' else 'FALSE' end
FROM VRH_EMP_TFERIAS DFER
LEFT OUTER JOIN VRHF_EMP_TVERBAFE VFER
  ON (VFER.BDCODEMP = DFER.BDCODEMP AND
      VFER.BDCODCOL = DFER.BDCODCOL AND
      VFER.BDINIPERAQUISFE = DFER.BDINIPERAQUISFE AND
      VFER.BDCODFE = DFER.BDCODFE)
;

/* CREATE OR ALTER VIEW: VW_VRHF_FGTS_INDIVIDUALIZACAO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_FGTS_INDIVIDUALIZACAO(
BDCODEMP,
BDCODCOL,
BDREF,
BDBFGTSFN,
BDFGTSFN,
BDBFGTS13FN,
BDFGTS13FN,
BDBFGTSA13,
BDFGTSA13,
BDBFGTSS13,
BDFGTSS13,
BDBFGTSFE,
BDVFGTSFE,
BDCODCENTRO,
BDCODTPCC)
 AS 
SELECT
  FN.BDCODEMP,
  FN.BDCODCOL,
  FN.BDREFFN,
  COALESCE(FN.BDBFGTSFN, 0.0),
  COALESCE(FN.BDFGTSFN, 0.0),
  COALESCE(FN.BDBFGTS13FN, 0.0),
  COALESCE(FN.BDFGTS13FN, 0.0),
  0.0,
  0.0,
  0.0,
  0.0,
  COALESCE(FN.BDBFGTSFEFN, 0.0),
  COALESCE(FN.BDFGTSFEFN, 0.0),
  -1,
  -1
FROM VRHF_EMP_TFOLHANORMAL FN

UNION ALL

SELECT
  FNT.BDCODEMP,
  FNT.BDCODCOL,
  FNT.BDREFTOMADOR,
  COALESCE(FNT.BDBFGTSFT,0),
  COALESCE(FNT.BDFGTSFT,0),
  FNT.BDBFGTS13FT,
  FNT.BDFGTS13FT,
  0.0,
  0.0,
  0.0,
  0.0,
  COALESCE(FNT.BDBFGTSFEFT,0),
  COALESCE(FNT.BDFGTSFEFT,0),
  COALESCE(PFT.BDCODCENTRO, 0),
  COALESCE(PFT.BDCODTPCC, 0)
FROM VRHF_EMP_TFOLHATOMADOR FNT
JOIN VRHF_EMP_TPREPFN PFT ON (PFT.BDCODEMP = FNT.BDCODEMP AND PFT.BDCODCOL = FNT.BDCODCOL AND PFT.BDORDEM = FNT.BDORDEM)

UNION ALL

SELECT
  A13.BDCODEMP,
  A13.BDCODCOL,
  A13.BDREFA13,
  0.0,
  0.0,
  0.0,
  0.0,
  COALESCE(A13.BDBASEFGTSA13, 0.0),
  COALESCE(A13.BDFGTSA13, 0.0),
  0.0,
  0.0,
  0.0,
  0.0,
  -1,
  -1
FROM VRHF_EMP_TA13SAL A13

UNION ALL

SELECT
  S13.BDCODEMP,
  S13.BDCODCOL,
  S13.BDREF13,
  0.0,
  0.0,
  0.0,
  0.0,
  0.0,
  0.0,
  COALESCE(S13.BDBASEFGTS13, 0.0),
  COALESCE(S13.BDFGTS13, 0.0),
  0.0,
  0.0,
  -1,
  -1
FROM VRHF_EMP_T13SAL S13
;

/* CREATE OR ALTER VIEW: VW_VRHF_FGTSSEFIP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_FGTSSEFIP(
    BDSOMA,
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCODTPCC,
    BDCODCENTRO,
    BDBASEFGTSFN,
    BDBASEFGTS13,
    BDFGTSFN,
    BDFGTS13,
    BDINSSFN,
    BDINSS13,
    BDBINSSFN,
    BDBINSS13,
    BDBINSS13R,
    BDSALFAMFN,
    BDBINSSC13,
    BDBINSSAPFN,
    BDBINSS13APFN,
    BDINSSAPFN,
    BDINSS13APFN,
    BDINSS13DT,
    BDINSSC13,
    BDINSSMV)
AS
SELECT bdsoma, bdcodemp,bdcodcol, bdref, bdcodtpcc, bdcodcentro,
       bdbasefgtsfn bdbasefgtsfn,
       bdbasefgts13 bdbasefgts13,
       bdfgtsfn bdfgtsfn,
       bdfgts13 bdfgts13,
       bdinssfn bdinssfn,
       bdinss13 bdinss13,
       bdbinssfn bdbinssfn,
       bdbinss13 bdbinss13,
       bdbinss13r bdbinss13r,
       bdsalfamfn bdsalfamfn,
       bdbinssc13 bdbinssc13,
       bdbinssapfn,
       bdbinss13apfn,
       bdinssapfn,
       bdinss13apfn,
       BDINSS13DT,
       BDINSSC13,
       BDINSSMV
        FROM (
SELECT 1 bdsoma, ad13.bdcodemp,ad13.bdcodcol,ad13.bdrefa13 bdref, NULL bdcodtpcc, NULL bdcodcentro,
       0 bdbasefgtsfn,
       CASE WHEN (ad13.bdbasefgtsa13 < 0) THEN 0 ELSE COALESCE(ad13.bdbasefgtsa13,0) END bdbasefgts13,
       0 bdfgtsfn,
       CASE WHEN (ad13.bdfgtsa13 < 0) THEN 0 ELSE COALESCE(ad13.bdfgtsa13,0) END bdfgts13,
       0 bdinssfn,
       0 bdinss13,
       0 bdbinssfn,
       0 bdbinss13,
       0 bdbinss13r,
       0 bdsalfamfn,
       0 bdbinssc13,
       0 bdbinssapfn,
       0 bdbinss13apfn,
       0 bdinssapfn,
       0 bdinss13apfn,
       0 BDINSS13DT,
       0 BDINSSC13,
       0 BDINSSMV
FROM vrhf_emp_ta13sal ad13
WHERE ad13.BDCALCFERA13 <> 'TRUE'
UNION ALL
SELECT 2 bdsoma, t13.bdcodemp,t13.bdcodcol,t13.bdref13, cc.bdcodtpcc bdcodtpcc, CASE WHEN cc.bdcodtpcc IS NULL THEN NULL ELSE cc.bdcodcentro END bdcodcentro,
       0 bdbasefgtsfn,
       CASE WHEN (t13.bdbasefgts13 < 0) THEN 0 ELSE COALESCE(t13.bdbasefgts13,0) END bdbasefgts13,
       0 bdfgtsfn,
       CASE WHEN (t13.bdfgts13 < 0) THEN 0 ELSE COALESCE(t13.bdfgts13,0) END bdfgts13,
       0 bdinssfn,
       0 bdinss13,
       0 bdbinssfn,
       0 bdbinss13,
       0 bdbinss13r,
       0 bdsalfamfn,
       0 bdbinssc13,
       0 bdbinssapfn,
       0 bdbinss13apfn,
       0 bdinssapfn,
       0 bdinss13apfn,
       0 BDINSS13DT,
       0 BDINSSC13,
       0 BDINSSMV
FROM vrhf_emp_t13sal_rat t13
LEFT OUTER JOIN vrhf_emp_tprepfn cc ON (t13.bdcodemp = cc.bdcodemp AND t13.bdcodcol = cc.bdcodcol AND t13.bdordem = cc.bdordem)
UNION ALL
SELECT 2 bdsoma, t13.bdcodemp,t13.bdcodcol,CASE WHEN CAST(t13.bdano13||'12' AS INTEGER) < COALESCE(res.bdrefrescisao,999999) THEN CAST(t13.bdano13||'12' AS INTEGER) ELSE res.bdrefrescisao END, cc.bdcodtpcc, CASE WHEN cc.bdcodtpcc IS NULL THEN NULL ELSE cc.bdcodcentro END bdcodcentro,
       0 bdbasefgtsfn,
       0 bdbasefgts13,
       0 bdfgtsfn,
       0 bdfgts13,
       0 bdinssfn,
       COALESCE(t13.bdvalorinss13,0),
       0 bdbinssfn,
       COALESCE(t13.bdbaseinss13,0),
       0 bdbinss13r,
       0 bdsalfamfn,
       0 bdbinssc13,
       0 bdbinssapfn,
       0 bdbinss13apfn,
       0 bdinssapfn,
       0 bdinss13apfn,
       COALESCE(t13.bdvalorinss13,0),
       0 BDINSSC13,
       0 BDINSSMV
FROM vrhf_emp_t13sal_rat t13
LEFT OUTER JOIN vrh_emp_trescisao res ON (t13.bdcodemp = res.bdcodemp AND t13.bdcodcol = res.bdcodcol)
LEFT OUTER JOIN vrhf_emp_tprepfn cc ON (t13.bdcodemp = cc.bdcodemp AND t13.bdcodcol = cc.bdcodcol AND t13.bdordem = cc.bdordem)
UNION ALL
SELECT 4 bdsoma, c13.bdcodemp,c13.bdcodcol,c13.bdrefc13, NULL bdcodtpcc, NULL bdcodcentro,
       0 bdbasefgtsfn,
       CASE WHEN (c13.bdbasefgtsc13 < 0) THEN 0 ELSE COALESCE(c13.bdbasefgtsc13,0) END bdbasefgts13,
       0 bdfgtsfn,
       CASE WHEN (c13.bdfgtsc13 < 0) THEN 0 ELSE COALESCE(c13.bdfgtsc13,0) END bdfgts13,
       0 bdinssfn,
       0 bdinss13,
       0 bdbinssfn,
       0 bdbinss13,
       COALESCE(c13.bdbaseinssc13,0),
       0 bdsalfamfn,
--       c13.bdbaseinssc13 bdbinssc13,
       case when (COALESCE(c13.bdvalorinssc13,0) = 0 and COALESCE(c13.bdbaseinssc13,0) = 0) then COALESCE(c13.bdbasefgtsc13,0) else COALESCE(c13.bdbaseinssc13,0) end,
       0 bdbinssapfn,
       0 bdbinss13apfn,
       0 bdinssapfn,
       0 bdinss13apfn,
       0 BDINSS13DT,
       COALESCE(c13.bdvalorinssc13,0) BDINSSC13,
       0 BDINSSMV
FROM vrhf_emp_tc13sal c13
UNION ALL
SELECT 10 bdsoma, tfol.bdcodemp, tfol.bdcodcol, tfol.bdreffn, NULL bdcodtpcc, NULL bdcodcentro,
   CASE WHEN (COALESCE(tfol.bdbfgtsfn, 0) + COALESCE(tfol.BDBFGTSFEFN, 0) < 0) THEN 0 ELSE COALESCE(tfol.bdbfgtsfn,0) END +CASE WHEN (tfol.BDBFGTSFEFN < 0) THEN 0 ELSE COALESCE(tfol.BDBFGTSFEFN,0) END,
   CASE WHEN (tfol.bdbfgts13fn < 0) THEN 0 ELSE COALESCE(tfol.bdbfgts13fn,0) END,
   CASE WHEN (COALESCE(tfol.bdfgtsfn, 0) + COALESCE(tfol.BDFGTSFEFN, 0) < 0) THEN 0 ELSE COALESCE(tfol.bdfgtsfn,0) END + CASE WHEN (tfol.BDFGTSFEFN < 0) THEN 0 ELSE COALESCE(tfol.BDFGTSFEFN,0) END,
   CASE WHEN (tfol.bdfgts13fn < 0) THEN 0 ELSE COALESCE(tfol.bdfgts13fn,0) END,
   COALESCE(tfol.bdinssfn,0) + COALESCE(tfol.bdinssfefolfn,0),
   COALESCE(tfol.bdinss13fn,0),
   case when coalesce(tfol.bdbaseinssnmvnovo, 0) = 0 then (COALESCE(tfol.bdbinssfn,0) + COALESCE(tfol.bdbinssfefolfn,0)) - COALESCE(tfol.bdbinssmvfn,0) else COALESCE(tfol.bdbinssfn,0) + COALESCE(tfol.bdbinssfefolfn,0) end,
   0 bdbinss13,
   case when coalesce(tfol.bdbaseinss13mvnovo, 0) = 0 then COALESCE(tfol.bdbinss13fn,0) - COALESCE(tfol.bdbinssmv13fn,0) else COALESCE(tfol.bdbinss13fn,0) end,
   COALESCE(tfol.bdsalfamfn,0) + COALESCE(tfol.bdcovid19fn,0) bdsalfamfn,
   0 bdbinssc13,
   CASE
     WHEN (tfol.bdbinssapfn IS NULL) OR (tfol.bdbinssapfn = 0) THEN 0
     ELSE COALESCE(tfol.bdbinssapfn,0) + COALESCE(tfol.bdbinssfefolfn,0)
   END,
   COALESCE(tfol.bdbinss13apfn,0),
   CASE
     WHEN (tfol.bdinssapfn IS NULL) OR (tfol.bdinssapfn = 0) THEN 0
     ELSE COALESCE(tfol.bdinssapfn,0) + COALESCE(tfol.bdinssfefolfn,0)
   END,
   COALESCE(tfol.bdinss13apfn,0),
   0 BDINSS13DT,
   0 BDINSSC13,
   BDBASEINSSNMVNOVO
FROM vrhf_emp_tfolhanormal tfol
UNION ALL
SELECT 10 bdsoma, tfol.bdcodemp, tfol.bdcodcol, tfol.bdreffn, NULL bdcodtpcc, NULL bdcodcentro,
   CASE WHEN (COALESCE(tfol.bdbfgtsfn, 0) + COALESCE(tfol.BDBFGTSFEFN, 0) < 0) THEN 0 ELSE COALESCE(tfol.bdbfgtsfn,0) END + MAXVALUE(0, COALESCE(tfol.BDBFGTSFEFN,0)),
   MAXVALUE(0, COALESCE(tfol.bdbfgts13fn,0)),
   CASE WHEN (COALESCE(tfol.bdfgtsfn, 0) + COALESCE(tfol.BDFGTSFEFN, 0) + COALESCE(tfol.bdfgts13fn,0) < 0) THEN 0 ELSE COALESCE(tfol.bdfgtsfn,0) + COALESCE(tfol.bdfgts13fn,0) END + CASE WHEN (tfol.BDFGTSFEFN < 0) THEN 0 ELSE COALESCE(tfol.BDFGTSFEFN,0) END,
   0,
   COALESCE(tfol.bdinssfn,0) + COALESCE(tfol.bdinssfefolfn,0) + COALESCE(tfol.bdinss13fn,0),
   0,
   case when coalesce(tfol.bdbaseinssnmvnovo, 0) = 0 then COALESCE(tfol.bdbinssfn,0) + COALESCE(tfol.bdbinssfefolfn,0) - COALESCE(tfol.bdbinssmvfn,0) else COALESCE(tfol.bdbinssfn,0) + COALESCE(tfol.bdbinssfefolfn,0) end,
   case when coalesce(tfol.bdbaseinssnmvnovo, 0) = 0 then COALESCE(tfol.bdbinss13fn,0) - COALESCE(tfol.bdbinssmv13fn,0) else COALESCE(tfol.bdbinss13fn,0) end,
   0,
   COALESCE(tfol.bdsalfamfn,0) + COALESCE(tfol.bdcovid19fn,0) bdsalfamfn,
   0 bdbinssc13,
   CASE
     WHEN (tfol.bdbinssapfn IS NULL) OR (tfol.bdbinssapfn = 0) THEN 0
     ELSE COALESCE(tfol.bdbinssapfn,0) + COALESCE(tfol.bdbinssfefolfn,0) + COALESCE(tfol.bdbinss13apfn,0)
   END,
   0,
   CASE
     WHEN (tfol.bdinssapfn IS NULL) OR (tfol.bdinssapfn = 0) THEN 0
     ELSE COALESCE(tfol.bdinssapfn,0) + COALESCE(tfol.bdinssfefolfn,0) + COALESCE(tfol.bdinss13apfn,0)
   END,
   0,
   0 BDINSS13DT,
   0 BDINSSC13,
   BDBASEINSSNMVNOVO
FROM vrhf_emp_tfolhaint tfol
UNION ALL
SELECT 100 bdsoma, tfolt.bdcodemp, tfolt.bdcodcol, tfolt.bdreftomador, pf.bdcodtpcc, CASE WHEN pf.bdcodtpcc IS NULL THEN NULL ELSE pf.bdcodcentro END,
   CASE WHEN (COALESCE(tfolt.bdbfgtsft, 0) + COALESCE(tfolt.bdbfgtsfeft, 0) < 0) THEN 0 ELSE COALESCE(tfolt.bdbfgtsft,0) END +CASE WHEN (tfolt.bdbfgtsfeft < 0) THEN 0 ELSE COALESCE(tfolt.bdbfgtsfeft,0) END,
   CASE WHEN (tfolt.bdbfgts13ft < 0) THEN 0 ELSE COALESCE(tfolt.bdbfgts13ft,0) END,
   CASE WHEN (COALESCE(tfolt.bdfgtsft, 0) + COALESCE(tfolt.bdfgtsfeft, 0) < 0) THEN 0 ELSE COALESCE(tfolt.bdfgtsft,0) END + CASE WHEN (tfolt.bdfgtsfeft < 0) THEN 0 ELSE COALESCE(tfolt.bdfgtsfeft,0) END,
   CASE WHEN (tfolt.bdfgts13ft < 0) THEN 0 ELSE COALESCE(tfolt.bdfgts13ft,0) END,
   (COALESCE(tfolt.bdinssft,0) + COALESCE(tfolt.bdinssfefolft,0)),
   COALESCE(tfolt.bdinss13ft,0),
   case when coalesce(tfolt.bdbaseinssnmvnovo, 0) = 0 then COALESCE(tfolt.bdbinssft,0) + COALESCE(tfolt.bdbinssfefolft,0) - COALESCE(tfolt.bdbinssmvft,0) else COALESCE(tfolt.bdbinssft,0) + COALESCE(tfolt.bdbinssfefolft,0) end,
   0 bdbinss13,
   case when coalesce(tfolt.bdbaseinss13mvnovo, 0) = 0 then COALESCE(tfolt.bdbinss13ft,0)  - COALESCE(tfolt.bdbinssmv13ft,0) else COALESCE(tfolt.bdbinss13ft,0) end,
   COALESCE(tfolt.bdsalfamft,0) + COALESCE(tfolt.bdcovid19ft, 0) bdsalfamft,
   0 bdbinssc13,
   CASE
     WHEN (tfolt.bdbinssapft IS NULL) OR (tfolt.bdbinssapft = 0) THEN 0
     ELSE COALESCE(tfolt.bdbinssapft,0) + COALESCE(tfolt.bdbinssfefolft,0)
   END,
   COALESCE(tfolt.bdbinss13apft,0),
   CASE
     WHEN (tfolt.bdinssapft IS NULL) OR (tfolt.bdinssapft = 0) THEN 0
     ELSE COALESCE(tfolt.bdinssapft,0) + COALESCE(tfolt.bdinssfefolft,0)
   END,
   COALESCE(tfolt.bdinss13apft,0),
   0 BDINSS13DT,
   0 BDINSSC13,
   BDBASEINSSNMVNOVO
FROM vrhf_emp_tfolhatomador tfolt, vrhf_emp_tprepfn pf
WHERE (tfolt.bdcodemp = pf.bdcodemp AND tfolt.bdcodcol = pf.bdcodcol AND tfolt.bdordem = pf.bdordem)
UNION ALL
SELECT 100 bdsoma, tfolt.bdcodemp, tfolt.bdcodcol, tfolt.bdreftomador, pf.bdcodtpcc, CASE WHEN pf.bdcodtpcc IS NULL THEN NULL ELSE pf.bdcodcentro END,
   CASE WHEN (COALESCE(tfolt.bdbfgtsft, 0) + COALESCE(tfolt.bdbfgtsfeft, 0) < 0) THEN 0 ELSE COALESCE(tfolt.bdbfgtsft,0) END + MAXVALUE(0, COALESCE(tfolt.bdbfgtsfeft,0)),
   MAXVALUE(0, COALESCE(tfolt.bdbfgts13ft,0)),
   CASE WHEN (COALESCE(tfolt.bdfgtsft, 0) + COALESCE(tfolt.bdfgtsfeft, 0) + COALESCE(tfolt.bdfgts13ft,0) < 0) THEN 0 ELSE COALESCE(tfolt.bdfgtsft,0) + COALESCE(tfolt.bdfgts13ft,0) END + CASE WHEN (tfolt.bdfgtsfeft < 0) THEN 0 ELSE COALESCE(tfolt.bdfgtsfeft,0) END,
   0,
   (COALESCE(tfolt.bdinssft,0) + COALESCE(tfolt.bdinssfefolft,0) + COALESCE(tfolt.bdinss13ft,0)),
   0,
   case when coalesce(tfolt.bdbaseinssnmvnovo, 0) = 0 then COALESCE(tfolt.bdbinssft,0) + COALESCE(tfolt.bdbinssfefolft,0) - COALESCE(tfolt.bdbinssmvft,0) + COALESCE(tfolt.bdbinss13ft,0)  - COALESCE(tfolt.bdbinssmv13ft,0) else COALESCE(tfolt.bdbinssft,0) + COALESCE(tfolt.bdbinssfefolft,0) + COALESCE(tfolt.bdbinss13ft,0) end,
   case when coalesce(tfolt.bdbaseinssnmvnovo, 0) = 0 then COALESCE(tfolt.bdbinss13ft,0) - COALESCE(tfolt.bdbinssmv13ft,0) else COALESCE(tfolt.bdbinss13ft,0) end,
   0,
   COALESCE(tfolt.bdsalfamft,0) + COALESCE(tfolt.bdcovid19ft,0) bdsalfamft,
   0 bdbinssc13,
   CASE
     WHEN (tfolt.bdbinssapft IS NULL) OR (tfolt.bdbinssapft = 0) THEN 0
     ELSE COALESCE(tfolt.bdbinssapft,0) + COALESCE(tfolt.bdbinssfefolft,0) + COALESCE(tfolt.bdbinss13apft,0)
   END,
   0,
   CASE
     WHEN (tfolt.bdinssapft IS NULL) OR (tfolt.bdinssapft = 0) THEN 0
     ELSE COALESCE(tfolt.bdinssapft,0) + COALESCE(tfolt.bdinssfefolft,0) + COALESCE(tfolt.bdinss13apft,0)
   END,
   0,
   0 BDINSS13DT,
   0 BDINSSC13,
   BDBASEINSSNMVNOVO
FROM vrhf_emp_tfolhatomint tfolt, vrhf_emp_tprepfn pf
WHERE (tfolt.bdcodemp = pf.bdcodemp AND tfolt.bdcodcol = pf.bdcodcol AND tfolt.bdordem = pf.bdordem)
)
;

/* CREATE OR ALTER VIEW: VW_VRHF_FGTSSEFIP_13 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_FGTSSEFIP_13(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCODTPCC,
    BDCODCENTRO,
    BDBASEFGTSFN,
    BDBASEFGTS13,
    BDFGTSFN,
    BDFGTS13,
    BDINSSFN,
    BDINSS13,
    BDBINSSFN,
    BDBINSS13,
    BDBINSS13R,
    BDSALFAMFN,
    BDBINSSC13,
    BDBINSSAPFN,
    BDBINSS13APFN,
    BDINSSAPFN,
    BDINSS13APFN,
    BDINSS13DT,
    BDINSSC13,
    BDINSSMV)
AS
SELECT t13.bdcodemp,t13.bdcodcol,CAST(t13.bdano13||'12' AS INTEGER), NULL bdcodtpcc, NULL bdcodcentro,
       0 bdbasefgtsfn,
       CASE WHEN (t13.bdbasefgts13 < 0) THEN 0 ELSE COALESCE(t13.bdbasefgts13,0) END bdbasefgts13,
       0 bdfgtsfn,
       CASE WHEN (t13.bdfgts13 < 0) THEN 0 ELSE COALESCE(t13.bdfgts13,0) END bdfgts13,
       0 bdinssfn,
       COALESCE(t13.bdvalorinss13,0),
       0 bdbinssfn,
       COALESCE(t13.bdbaseinss13,0),
       0 bdbinss13r,
       0 bdsalfamfn,
       0 bdbinssc13,
       0 bdbinssapfn,
       0 bdbinss13apfn,
       0 bdinssapfn,
       0 bdinss13apfn,
       0 BDINSS13DT,
       0 BDINSSC13,
       0 bdinssmv
FROM vrhf_emp_t13sal t13;

/* CREATE OR ALTER VIEW: VW_VRHF_FGTSSEFIP_13_CC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_FGTSSEFIP_13_CC(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCODTPCC,
    BDCODCENTRO,
    BDBASEFGTSFN,
    BDBASEFGTS13,
    BDFGTSFN,
    BDFGTS13,
    BDINSSFN,
    BDINSS13,
    BDBINSSFN,
    BDBINSS13,
    BDBINSS13R,
    BDSALFAMFN,
    BDBINSSC13,
    BDBINSSAPFN,
    BDBINSS13APFN,
    BDINSSAPFN,
    BDINSS13APFN,
    BDINSS13DT,
    BDINSSC13,
    BDINSSMV)
AS
SELECT t13.bdcodemp,t13.bdcodcol,CAST(t13.bdano13||'12' AS INTEGER), t13.bdcodtpcc, t13.bdcodcentro,
       0 bdbasefgtsfn,
       SUM(CASE WHEN (t13.bdbasefgts13 < 0) THEN 0 ELSE COALESCE(t13.bdbasefgts13,0) END) bdbasefgts13,
       0 bdfgtsfn,
       SUM(CASE WHEN (t13.bdfgts13 < 0) THEN 0 ELSE COALESCE(t13.bdfgts13,0) END) bdfgts13,
       0 bdinssfn,
       SUM(COALESCE(t13.bdvalorinss13,0)),
       0 bdbinssfn,
       SUM(COALESCE(t13.bdbaseinss13,0)),
       0 bdbinss13r,
       0 bdsalfamfn,
       0 bdbinssc13,
       0 bdbinssapfn,
       0 bdbinss13apfn,
       0 bdinssapfn,
       0 bdinss13apfn,
       0 BDINSS13DT,
       0 bdinssc13,
       0 bdinssmv
FROM vw_vrhf_emp_t13sal_rat_cc t13
GROUP BY t13.bdcodemp,t13.bdcodcol,t13.bdano13,t13.bdcodcentro,t13.bdcodtpcc
;

/* CREATE OR ALTER VIEW: VW_VRHF_FGTSSEFIP_AGRUPA_1 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_FGTSSEFIP_AGRUPA_1(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCODTPCC,
    BDCODCENTRO,
    BDBASEFGTSFN,
    BDBASEFGTS13,
    BDFGTSFN,
    BDFGTS13,
    BDINSSFN,
    BDINSS13,
    BDBINSSFN,
    BDBINSS13,
    BDBINSS13R,
    BDSALFAMFN,
    BDBINSSC13,
    BDBINSSAPFN,
    BDBINSS13APFN,
    BDINSSAPFN,
    BDINSS13APFN,
    BDINSS13DT,
    BDINSSC13,
    BDINSSMV)
AS
SELECT bdcodemp,bdcodcol, bdref, NULL bdcodtpcc, NULL bdcodcentro,
       SUM(bdbasefgtsfn) bdbasefgtsfn,
       SUM(bdbasefgts13) bdbasefgts13,
       SUM(bdfgtsfn) bdfgtsfn,
       SUM(bdfgts13) bdfgts13,
       SUM(bdinssfn) bdinssfn,
       SUM(bdinss13) bdinss13,
       SUM(bdbinssfn) bdbinssfn,
       SUM(bdbinss13) bdbinss13,
       SUM(bdbinss13r) bdbinss13r,
       SUM(bdsalfamfn) bdsalfamfn,
       SUM(bdbinssc13) bdbinssc13,
       SUM(bdbinssapfn) bdbinssapfn,
       SUM(bdbinss13apfn) bdbinss13apfn,
       SUM(bdinssapfn) bdinssapfn,
       SUM(bdinss13apfn) bdinss13apfn,
       SUM(bdinss13dt) bdinss13dt,
       SUM(bdinssc13) bdinssc13,
       SUM(bdinssmv) bdinssmv
      FROM VW_vrhf_fgtssefip
GROUP BY bdcodemp,bdcodcol, bdref
;

/* CREATE OR ALTER VIEW: VW_VRHF_FGTSSEFIP_AGRUPA_3 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_FGTSSEFIP_AGRUPA_3(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCODTPCC,
    BDCODCENTRO,
    BDBASEFGTSFN,
    BDBASEFGTS13,
    BDFGTSFN,
    BDFGTS13,
    BDINSSFN,
    BDINSS13,
    BDBINSSFN,
    BDBINSS13,
    BDBINSS13R,
    BDSALFAMFN,
    BDBINSSC13,
    BDBINSSAPFN,
    BDBINSS13APFN,
    BDINSSAPFN,
    BDINSS13APFN,
    bdinss13DT,
    BDINSSC13,
    BDINSSMV)
AS
SELECT tcalc.bdcodemp, tcalc.bdcodcol, tcalc.bdref, toma.bdcodtpcc, tcalc.bdcodcentro,
       SUM(tcalc.bdbasefgtsfn) bdbasefgtsfn,
       SUM(tcalc.bdbasefgts13) bdbasefgts13,
       SUM(tcalc.bdfgtsfn) bdfgtsfn,
       SUM(tcalc.bdfgts13) bdfgts13,
       SUM(tcalc.bdinssfn) bdinssfn,
       SUM(tcalc.bdinss13) bdinss13,
       SUM(tcalc.bdbinssfn) bdbinssfn,
       SUM(tcalc.bdbinss13) bdbinss13,
       SUM(tcalc.bdbinss13r) bdbinss13r,
       SUM(tcalc.bdsalfamfn) bdsalfamfn,
       SUM(tcalc.bdbinssc13) bdbinssc13,
       SUM(tcalc.bdbinssapfn) bdbinssapfn,
       SUM(tcalc.bdbinss13apfn) bdbinss13apfn,
       SUM(tcalc.bdinssapfn) bdinssapfn,
       SUM(tcalc.bdinss13apfn) bdbinss13apfn,
       SUM(tcalc.bdinss13DT) bdinss13DT,
       SUM(tcalc.bdinssc13) bdinssc13,
       SUM(bdinssmv) bdinssmv
FROM VW_vrhf_fgtssefip tcalc
LEFT OUTER JOIN vrhf_sp_tomador(tcalc.bdcodtpcc,tcalc.bdcodcentro) toma ON (toma.bdcodcencus = tcalc.bdcodtpcc AND toma.bdcodcentro = tcalc.bdcodcentro)
GROUP BY tcalc.bdcodemp, tcalc.bdcodcol, tcalc.bdref, tcalc.bdcodcentro, toma.bdcodtpcc
;

/* CREATE OR ALTER VIEW: VW_VRHF_FGTSSEFIP_AGRUPA_CC_MES (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_FGTSSEFIP_AGRUPA_CC_MES(
    BDCODEMP,
    BDCODCOL,
    BDREF,
    BDCODTPCC,
    BDCODCENTRO,
    BDBASEFGTSFN,
    BDBASEFGTS13,
    BDFGTSFN,
    BDFGTS13,
    BDINSSFN,
    BDINSS13,
    BDBINSSFN,
    BDBINSS13,
    BDBINSS13R,
    BDSALFAMFN,
    BDBINSSC13,
    BDBINSSAPFN,
    BDBINSS13APFN,
    BDINSSAPFN,
    BDINSS13APFN,
    BDINSS13DT,
    BDINSSC13,
    BDINSSMV)
AS
SELECT x.bdcodemp,x.bdcodcol, bdref, COALESCE(x.bdcodtpcc,a.bdcodtpcc) bdcodtpccx, COALESCE(x.bdcodcentro,CASE WHEN a.bdcodtpcc IS NULL THEN NULL ELSE a.bdcodcentro END) bdcodcentrox,
       SUM(bdbasefgtsfn) bdbasefgtsfn,
       SUM(bdbasefgts13) bdbasefgts13,
       SUM(bdfgtsfn) bdfgtsfn,
       SUM(bdfgts13) bdfgts13,
       SUM(bdinssfn) bdinssfn,
       SUM(bdinss13) bdinss13,
       SUM(bdbinssfn) bdbinssfn,
       SUM(bdbinss13) bdbinss13,
       SUM(bdbinss13r) bdbinss13r,
       SUM(bdsalfamfn) bdsalfamfn,
       SUM(bdbinssc13) bdbinssc13,
       SUM(bdbinssapfn) bdbinssapfn,
       SUM(bdbinss13apfn) bdbinss13apfn,
       SUM(bdinssapfn) bdinssapfn,
       SUM(bdinss13apfn) bdinss13apfn,
       SUM(BDINSS13DT) BDINSS13DT,
       SUM(BDINSSC13) BDINSSC13,
       SUM(BDINSSMV) BDINSSMV
FROM VW_vrhf_fgtssefip x

LEFT OUTER JOIN sp_vrh_cc_data(
 x.bdcodemp,x.bdcodcol,SUBSTRING(''||x.bdref FROM 5 FOR 2)||'/'||(SELECT ultdia
 FROM ULTIMO_DIA_MES(CAST(SUBSTRING(''||x.bdref FROM 5 FOR 2) AS SMALLINT),
 CAST(SUBSTRING(''||x.bdref FROM 1 FOR 4) AS INTEGER)))||'/'||SUBSTRING(''||x.bdref FROM 1 FOR 4)) a
 ON (x.bdcodemp = a.bdcodemp AND x.bdcodcol = a.bdcodcol AND x.bdcodtpcc IS NULL AND x.bdsoma NOT IN (2,10,100))

GROUP BY x.bdcodemp,x.bdcodcol, bdref, bdcodtpccx, bdcodcentrox
;

/* CREATE OR ALTER VIEW: VW_VRHF_FICHAHE (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_FICHAHE(
BDCODEMP,
BDCODCOL,
BDREF,
BDCODVER,
BDREFV,
BDREFAUXV,
BDVALV,
BDBFGTS,
BDFGTS,
BDFGTSCS,
BDBFGTS13,
BDFGTS13,
BDFGTS13CS,
BDMAIORREM,
BDBINSS,
BDALIQINSS,
BDINSS,
BDBIRRF,
BDALIQIRRF,
BDIRRF,
BDBINSS13,
BDALIQINSS13,
BDINSS13,
BDBIRRF13,
BDALIQIRRF13,
BDIRRF13,
BDBSALFAM,
BDSALFAM,
BDBRAIS,
BDSALBASE,
BDDEP,
BDIGNREFV,
BDIGNVALV,
BDTIPO)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREFFHE,
  X.BDCODVER,
  X.BDVREFFHE BDREFV,
  0.0 BDREFAUXV,
  X.BDVVALFHE BDVALV,
  0.0 BDBFGTS,
  0.0 BDFGTS,
  0.0 BDFGTSCS,
  0.0 BDBFGTS13,
  0.0 BDFGTS13,
  0.0 BDFGTS13CS,
  0.0 BDMAIORREM,
  0.0 BDBINSS,
  0.0 BDALIQINSS,
  0.0 BDINSS,
  0.0 BDBIRRF,
  0.0 BDALIQIRRF,
  0.0 BDIRRF,
  0.0 BDBINSS13,
  0.0 BDALIQINSS13,
  0.0 BDINSS13,
  0.0 BDBIRRF13,
  0.0 BDALIQIRRF13,
  0.0 BDIRRF13,
  0.0 BDBSALFAM,
  0.0 BDSALFAM,
  0.0 BDBRAIS,
  0.0 BDSALBASE,
  0.0 BDDEP,
  'FALSE' BDIGNREFV,
  'FALSE' BDIGNVALV,
  1 BDTIPO
FROM VRHF_EMP_TFICHAHE X
WHERE NOT EXISTS (
  SELECT BDCODEMP, BDCODCOL, BDREFFN, BDCODVER
  FROM VRHF_EMP_TVERBAFN Y
  WHERE Y.BDCODEMP = X.BDCODEMP AND
        Y.BDCODCOL = X.BDCODCOL AND
        Y.BDREFFN = X.BDREFFHE AND
        Y.BDCODVER = X.BDCODVER)

  AND

  (NOT EXISTS (
  SELECT BDCODEMP, BDCODCOL, BDREFFN, BDCODVER
  FROM vrhf_emp_tverbafc a
  WHERE a.BDCODEMP = X.BDCODEMP AND
        a.BDCODCOL = X.BDCODCOL AND
        a.BDREFFN = X.BDREFFHE AND
        a.BDCODVER = X.BDCODVER))

  AND

  (NOT EXISTS (
  SELECT BDCODEMP, BDCODCOL, bdreftomador, BDCODVER
  FROM vrhf_emp_tverbatomador b
  WHERE b.BDCODEMP = X.BDCODEMP AND
        b.BDCODCOL = X.BDCODCOL AND
        b.bdreftomador = X.BDREFFHE AND
        b.BDCODVER = X.BDCODVER))

  AND

  (NOT EXISTS (
  SELECT BDCODEMP, BDCODCOL, bdreftomador, BDCODVER
  FROM vrhf_emp_tverbafctomador c
  WHERE c.BDCODEMP = X.BDCODEMP AND
        c.BDCODCOL = X.BDCODCOL AND
        c.bdreftomador = X.BDREFFHE AND
        c.BDCODVER = X.BDCODVER))
;

/* CREATE OR ALTER VIEW: VW_VRHF_FICHAHN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_FICHAHN(
BDCODEMP,
BDCODCOL,
BDREF,
BDCODVER,
BDREFV,
BDREFAUXV,
BDVALV,
BDBFGTS,
BDFGTS,
BDFGTSCS,
BDBFGTS13,
BDFGTS13,
BDFGTS13CS,
BDMAIORREM,
BDBINSS,
BDALIQINSS,
BDINSS,
BDBIRRF,
BDALIQIRRF,
BDIRRF,
BDBINSS13,
BDALIQINSS13,
BDINSS13,
BDBIRRF13,
BDALIQIRRF13,
BDIRRF13,
BDBSALFAM,
BDSALFAM,
BDBRAIS,
BDSALBASE,
BDDEP,
BDIGNREFV,
BDIGNVALV,
BDTIPO)
 AS 
SELECT
  X.bdcodemp,
  X.bdcodcol,
  X.bdreffhn,
  X.bdcodver,
  X.BDVREFFHN BDREFV,
  0.0 BDREFAUXV,
  X.BDVVALFHN BDVALV,
  0.0 BDBFGTS,
  0.0 BDFGTS,
  0.0 BDFGTSCS,
  0.0 BDBFGTS13,
  0.0 BDFGTS13,
  0.0 BDFGTS13CS,
  0.0 BDMAIORREM,
  0.0 BDBINSS,
  0.0 BDALIQINSS,
  0.0 BDINSS,
  0.0 BDBIRRF,
  0.0 BDALIQIRRF,
  0.0 BDIRRF,
  0.0 BDBINSS13,
  0.0 BDALIQINSS13,
  0.0 BDINSS13,
  0.0 BDBIRRF13,
  0.0 BDALIQIRRF13,
  0.0 BDIRRF13,
  0.0 BDBSALFAM,
  0.0 BDSALFAM,
  0.0 BDBRAIS,
  0.0 BDSALBASE,
  0.0 BDDEP,
  'FALSE' BDIGNREFV,
  'FALSE' BDIGNVALV,
  1 BDTIPO
FROM VRHF_EMP_TFICHAHN X
WHERE NOT EXISTS (
  SELECT BDCODEMP, BDCODCOL, BDREFFN, BDCODVER
  FROM VRHF_EMP_TVERBAFN Y
  WHERE Y.BDCODEMP = X.bdcodemp AND
        Y.BDCODCOL = X.bdcodcol AND
        Y.BDREFFN = X.bdreffhn AND
        Y.BDCODVER = X.bdcodver)
;

/* CREATE OR ALTER VIEW: VW_VRHF_FICHARV (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_FICHARV(
BDCODEMP,
BDCODCOL,
BDREF,
BDCODVER,
BDREFV,
BDREFAUXV,
BDVALV,
BDBFGTS,
BDFGTS,
BDFGTSCS,
BDBFGTS13,
BDFGTS13,
BDFGTS13CS,
BDMAIORREM,
BDBINSS,
BDALIQINSS,
BDINSS,
BDBIRRF,
BDALIQIRRF,
BDIRRF,
BDBINSS13,
BDALIQINSS13,
BDINSS13,
BDBIRRF13,
BDALIQIRRF13,
BDIRRF13,
BDBSALFAM,
BDSALFAM,
BDBRAIS,
BDSALBASE,
BDDEP,
BDIGNREFV,
BDIGNVALV,
BDTIPO)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREFFRV,
  X.BDCODVER,
  X.BDVREFFRV BDREFV,
  0.0 BDREFAUXV,
  X.BDVVALFRV BDVALV,
  0.0 BDBFGTS,
  0.0 BDFGTS,
  0.0 BDFGTSCS,
  0.0 BDBFGTS13,
  0.0 BDFGTS13,
  0.0 BDFGTS13CS,
  0.0 BDMAIORREM,
  0.0 BDBINSS,
  0.0 BDALIQINSS,
  0.0 BDINSS,
  0.0 BDBIRRF,
  0.0 BDALIQIRRF,
  0.0 BDIRRF,
  0.0 BDBINSS13,
  0.0 BDALIQINSS13,
  0.0 BDINSS13,
  0.0 BDBIRRF13,
  0.0 BDALIQIRRF13,
  0.0 BDIRRF13,
  0.0 BDBSALFAM,
  0.0 BDSALFAM,
  0.0 BDBRAIS,
  0.0 BDSALBASE,
  0.0 BDDEP,
  'FALSE' BDIGNREFV,
  'FALSE' BDIGNVALV,
  1 BDTIPO
FROM VRHF_EMP_TFICHARV X
WHERE NOT EXISTS (
  SELECT BDCODEMP, BDCODCOL, BDREFFN, BDCODVER
  FROM VRHF_EMP_TVERBAFN Y
  WHERE Y.BDCODEMP = X.BDCODEMP AND
        Y.BDCODCOL = X.BDCODCOL AND
        Y.BDREFFN = X.BDREFFRV AND
        Y.BDCODVER = X.BDCODVER)
  AND

  (NOT EXISTS (
  SELECT BDCODEMP, BDCODCOL, BDREFFN, BDCODVER
  FROM vrhf_emp_tverbafc a
  WHERE a.BDCODEMP = X.BDCODEMP AND
        a.BDCODCOL = X.BDCODCOL AND
        a.BDREFFN = X.bdreffrv AND
        a.BDCODVER = X.BDCODVER))

  AND

  (NOT EXISTS (
  SELECT BDCODEMP, BDCODCOL, bdreftomador, BDCODVER
  FROM vrhf_emp_tverbatomador b
  WHERE b.BDCODEMP = X.BDCODEMP AND
        b.BDCODCOL = X.BDCODCOL AND
        b.bdreftomador = X.bdreffrv AND
        b.BDCODVER = X.BDCODVER))

  AND

  (NOT EXISTS (
  SELECT BDCODEMP, BDCODCOL, bdreftomador, BDCODVER
  FROM vrhf_emp_tverbafctomador c
  WHERE c.BDCODEMP = X.BDCODEMP AND
        c.BDCODCOL = X.BDCODCOL AND
        c.bdreftomador = X.bdreffrv AND
        c.BDCODVER = X.BDCODVER))
;

/* CREATE OR ALTER VIEW: VW_VRHF_FN_FC_13_C13_VERBAS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_FN_FC_13_C13_VERBAS(
BDCODEMP,
BDCODCOL,
BDREF,
BDCODVER,
BDREFV,
BDREFAUXV,
BDVALV,
BDIGNREFAV,
BDIGNREFV,
BDIGNVALV)
 AS 
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDCODVER,
    BDREFVFN,
    BDREFAUXVFN,
    BDVALVFN,
    BDIGNREFAVFN,
    BDIGNREFVFN,
    BDIGNVALVFN
FROM vrhf_emp_tverbafn
UNION ALL
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREFCOMP,
    BDCODVER,
    BDREFVFC,
    BDREFAUXVFC,
    BDVALVFC,
    BDIGNREFAVFC,
    BDIGNREFVFC,
    BDIGNVALVFC
FROM vrhf_emp_tverbafc
UNION ALL
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREF13,
    BDCODVER,
    BDREFV13,
    BDREFAUXV13,
    BDVALV13,
    BDIGNREFAV13,
    BDIGNREFV13,
    BDIGNVALV13
FROM vrhf_emp_tverba13
UNION ALL
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREFC13,
    BDCODVER,
    BDREFVC13,
    BDREFAUXVC13,
    BDVALVC13,
    BDIGNREFAVC13,
    BDIGNREFVC13,
    BDIGNVALVC13
FROM vrhf_emp_tverbac13
UNION ALL
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREFTOMADOR,
    BDCODVER,
    BDREFVFT,
    BDREFAUXVFT,
    BDVALVFT,
    BDIGNREFAVFT,
    BDIGNREFVFT,
    BDIGNVALVFT
FROM vrhf_emp_tverbatomador
UNION ALL
SELECT
    BDCODEMP,
    BDCODCOL,
    BDREFTOMADOR,
    BDCODVER,
    BDREFVFC,
    BDREFAUXVFC,
    BDVALVFC,
    BDIGNREFAVFC,
    BDIGNREFVFC,
    BDIGNVALVFC
FROM vrhf_emp_tverbafctomador
;

/* CREATE OR ALTER VIEW: VW_VRHF_FOLHAAD (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_FOLHAAD(
BDCODEMP,
BDCODCOL,
BDREFAD,
BDCODVER,
BDREFV,
BDREFAUXV,
BDVALV,
BDIGNREFV,
BDIGNVALV,
BDBASEAD,
BDTIPOAD,
BDVALPERCAD,
BDBASEIRAD,
BDDATABAIXAAD,
BDREFBAIXAAD,
BDVALORIRAD,
BDPERCIRAD,
BDCREDITO,
BDDEBITO)
 AS 
SELECT VFOLAD.BDCODEMP,
       VFOLAD.BDCODCOL,
       CAST((SUBSTRING(CAST(VFOLAD.BDDATAAD AS VARCHAR(10)) FROM 1 FOR 4) ||
             SUBSTRING(CAST(VFOLAD.BDDATAAD AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) BDREFAD,
       VFOLAD.BDCODVER,
       VFOLAD.BDREFVAD,
       VFOLAD.BDREFAUXVAD,
       VFOLAD.BDVALVAD,
       VFOLAD.BDIGNREFVAD,
       VFOLAD.BDIGNVALVAD,
       DFOLAD.BDBASEAD,
       DFOLAD.BDTIPOAD,
       DFOLAD.BDVALPERCAD,
       DFOLAD.BDBASEIRAD,
       DFOLAD.BDDATABAIXAAD,
       DFOLAD.BDREFBAIXAAD,
       DFOLAD.BDVALORIRAD,
       DFOLAD.BDPERCIRAD,
       DFOLAD.BDCREDITOAD,
       DFOLAD.BDDEBITOAD
FROM VRHF_EMP_TVERBAAD VFOLAD
LEFT OUTER JOIN vrhf_emp_tadsal DFOLAD
 ON (DFOLAD.BDCODEMP = VFOLAD.BDCODEMP AND DFOLAD.BDCODCOL = VFOLAD.BDCODCOL AND DFOLAD.bddataad = VFOLAD.bddataad)
;

/* CREATE OR ALTER VIEW: VW_VRHF_SS_COMP_13 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_SS_COMP_13(
BDCODVER,
BDCODEMP,
BDREF13,
BDVALOR)
 AS 
SELECT vdt.BDCODVER, vdt.BDCODEMP, vdt.bdref13, SUM(vdt.bdvalv13) bdvalor
FROM vrhf_emp_tverba13 vdt
GROUP BY vdt.BDCODVER,  vdt.BDCODEMP, vdt.bdref13
;

/* CREATE OR ALTER VIEW: VW_VRHF_SS_COMP_A13 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_SS_COMP_A13(
BDCODVER,
BDCODEMP,
BDREFA13,
BDVALOR)
 AS 
SELECT vA13.BDCODVER, vA13.BDCODEMP, vA13.bdrefa13, SUM(vA13.bdvalva13) bdvalor
FROM vrhf_emp_tverbaa13 vA13
GROUP BY vA13.BDCODVER,  vA13.BDCODEMP, vA13.bdrefa13
;

/* CREATE OR ALTER VIEW: VW_VRHF_SS_COMP_ADSAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_SS_COMP_ADSAL(
BDCODVER,
BDCODEMP,
BDREFAD,
BDVALOR)
 AS 
SELECT vfn.BDCODVER, vfn.BDCODEMP,
       EXTRACT(YEAR FROM vfn.bddataad)||SUBSTRING(vfn.bddataad FROM 6 FOR 2)
       bdrefad, SUM(vfn.bdvalvad) bdvalor
  FROM vrhf_emp_tverbaad vfn
  GROUP BY vfn.BDCODVER,  vfn.BDCODEMP, bdrefad
;

/* CREATE OR ALTER VIEW: VW_VRHF_SS_COMP_C13 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_SS_COMP_C13(
BDCODVER,
BDCODEMP,
BDREFC13,
BDVALOR)
 AS 
SELECT vdt.BDCODVER, vdt.BDCODEMP, vdt.bdrefC13, SUM(vdt.bdvalvC13) bdvalor
FROM vrhf_emp_tverbaC13 vdt
GROUP BY vdt.BDCODVER,  vdt.BDCODEMP, vdt.bdrefC13
;

/* CREATE OR ALTER VIEW: VW_VRHF_SS_COMP_FC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_SS_COMP_FC(
BDCODVER,
BDCODEMP,
BDREFCOMP,
BDVALOR)
 AS 
SELECT BDCODVER, BDCODEMP, bdrefcomp, SUM(bdvalor) FROM (
SELECT vfn.BDCODVER, vfn.BDCODEMP, vfn.bdrefcomp, SUM(vfn.bdvalvfc) bdvalor FROM vrhf_emp_tverbafc vfn
GROUP BY vfn.BDCODVER,  vfn.BDCODEMP, vfn.bdrefcomp
UNION
SELECT vft.BDCODVER, vft.BDCODEMP, vft.bdrefcomp, SUM(vft.bdvalvfc) FROM vrhf_emp_tverbafctomador vft
GROUP BY vft.BDCODVER,  vft.BDCODEMP, vft.bdrefcomp
)
GROUP BY BDCODVER, BDCODEMP, bdrefcomp
;

/* CREATE OR ALTER VIEW: VW_VRHF_SS_COMP_FER (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_SS_COMP_FER(
BDCODVER,
BDCODEMP,
BDREFFER,
BDVALOR)
 AS 
SELECT BDCODVER, BDCODEMP, bdreffer, SUM(bdvalor) bdvalor FROM (
SELECT vfe.BDCODVER, vfe.BDCODEMP, fe.bdrefpagabofe bdreffer, SUM(vfe.bdvalvfe) bdvalor
FROM vrhf_emp_tverbafe vfe, vrh_emp_tferias fe
WHERE fe.bdcodemp = vfe.bdcodemp AND fe.bdcodcol = vfe.bdcodcol AND fe.bdiniperaquisfe = vfe.bdiniperaquisfe AND fe.bdcodfe = vfe.bdcodfe
      AND fe.bdinipergozofe IS NULL
GROUP BY vfe.BDCODVER,  vfe.BDCODEMP, bdreffer
UNION
SELECT vfe.BDCODVER, vfe.BDCODEMP, EXTRACT(YEAR FROM fe.bdinipergozofe)||SUBSTRING(fe.bdinipergozofe FROM 6 FOR 2) bdreffer, SUM(vfe.bdvalvfe) bdvalor
FROM vrhf_emp_tverbafe vfe, vrh_emp_tferias fe
WHERE fe.bdcodemp = vfe.bdcodemp AND fe.bdcodcol = vfe.bdcodcol AND fe.bdiniperaquisfe = vfe.bdiniperaquisfe AND fe.bdcodfe = vfe.bdcodfe
      AND fe.bdinipergozofe IS NOT NULL
GROUP BY vfe.BDCODVER,  vfe.BDCODEMP, bdreffer
)
GROUP BY BDCODVER, BDCODEMP, bdreffer
;

/* CREATE OR ALTER VIEW: VW_VRHF_SS_COMP_FN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_SS_COMP_FN(
BDCODVER,
BDCODEMP,
BDREFFN,
BDVALOR)
 AS 
SELECT BDCODVER, BDCODEMP, bdreffn, SUM(bdvalor) FROM (
SELECT vfn.BDCODVER, vfn.BDCODEMP, vfn.bdreffn, SUM(vfn.BDVALVFN) bdvalor FROM vrhf_emp_tverbafn vfn
GROUP BY vfn.BDCODVER,  vfn.BDCODEMP, vfn.bdreffn
UNION
SELECT vft.BDCODVER, vft.BDCODEMP, vft.bdreftomador, SUM(vft.bdvalvft) FROM vrhf_emp_tverbatomador vft
GROUP BY vft.BDCODVER,  vft.BDCODEMP, vft.bdreftomador
)
GROUP BY BDCODVER, BDCODEMP, bdreffn
;

/* CREATE OR ALTER VIEW: VW_VRHF_SS_PGTO_13 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_SS_PGTO_13(
BDCODVER,
BDCODEMP,
BDREF13,
BDVALOR)
 AS 
SELECT vdt.BDCODVER, vdt.BDCODEMP, EXTRACT(YEAR FROM dt.bddatabaixa13)||SUBSTRING(dt.bddatabaixa13 FROM 6 FOR 2) bdref13, SUM(vdt.bdvalv13) bdvalor
FROM vrhf_emp_tverba13 vdt, vrhf_emp_t13sal dt
WHERE dt.bdcodemp = vdt.bdcodemp AND dt.bdcodcol = vdt.bdcodcol AND dt.bdref13 = vdt.bdref13
      AND dt.bddatabaixa13 IS NOT NULL
GROUP BY vdt.BDCODVER,  vdt.BDCODEMP, bdref13
;

/* CREATE OR ALTER VIEW: VW_VRHF_SS_PGTO_A13 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_SS_PGTO_A13(
BDCODVER,
BDCODEMP,
BDREFA13,
BDVALOR)
 AS 
SELECT vA13.BDCODVER, vA13.BDCODEMP, EXTRACT(YEAR FROM a13.bddatabaixaa13)||SUBSTRING(a13.bddatabaixaa13 FROM 6 FOR 2) bdrefa13, SUM(vA13.bdvalva13) bdvalor
FROM vrhf_emp_tverbaa13 vA13, vrhf_emp_ta13sal a13
WHERE a13.bdcodemp = va13.bdcodemp AND a13.bdcodcol = va13.bdcodcol AND a13.bdrefa13 = va13.bdrefa13
      AND a13.bddatabaixaa13 IS NOT NULL
GROUP BY vA13.BDCODVER,  vA13.BDCODEMP, bdrefa13
;

/* CREATE OR ALTER VIEW: VW_VRHF_SS_PGTO_ADSAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_SS_PGTO_ADSAL(
BDCODVER,
BDCODEMP,
BDREFAD,
BDVALOR)
 AS 
SELECT vfn.BDCODVER, vfn.BDCODEMP,
       EXTRACT(YEAR FROM fn.bddatabaixaad)||SUBSTRING(fn.bddatabaixaad FROM 6 FOR 2)
       bdrefad, SUM(vfn.bdvalvad) bdvalor
  FROM vrhf_emp_tverbaad vfn, vrhf_emp_tadsal fn
  WHERE (fn.bdcodemp = vfn.bdcodemp AND fn.bdcodcol = vfn.bdcodcol AND fn.bddataad = vfn.bddataad)
        AND fn.bddatabaixaad IS NOT NULL
  GROUP BY vfn.BDCODVER,  vfn.BDCODEMP, bdrefad
;

/* CREATE OR ALTER VIEW: VW_VRHF_SS_PGTO_C13 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_SS_PGTO_C13(
BDCODVER,
BDCODEMP,
BDREFC13,
BDVALOR)
 AS 
SELECT vdt.BDCODVER, vdt.BDCODEMP, EXTRACT(YEAR FROM dt.bddatabaixaC13)||SUBSTRING(dt.bddatabaixaC13 FROM 6 FOR 2) bdrefC13, SUM(vdt.bdvalvC13) bdvalor
FROM vrhf_emp_tverbaC13 vdt, vrhf_emp_tC13sal dt
WHERE dt.bdcodemp = vdt.bdcodemp AND dt.bdcodcol = vdt.bdcodcol AND dt.bdrefC13 = vdt.bdrefC13
      AND dt.bddatabaixaC13 IS NOT NULL
GROUP BY vdt.BDCODVER,  vdt.BDCODEMP, bdrefC13
;

/* CREATE OR ALTER VIEW: VW_VRHF_SS_PGTO_FC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_SS_PGTO_FC(
BDCODVER,
BDCODEMP,
BDREFCOMP,
BDVALOR)
 AS 
SELECT BDCODVER, BDCODEMP, bdrefcomp, SUM(bdvalor) FROM (
SELECT vfn.BDCODVER, vfn.BDCODEMP,
       EXTRACT(YEAR FROM fn.bddatabaixafc)||SUBSTRING(fn.bddatabaixafc FROM 6 FOR 2)
       bdrefcomp, SUM(vfn.bdvalvfc) bdvalor
  FROM vrhf_emp_tverbafc vfn, vrhf_emp_tfolhacomp fn
  WHERE (fn.bdcodemp = vfn.bdcodemp AND fn.bdcodcol = vfn.bdcodcol AND fn.bdreffn = vfn.bdreffn AND fn.bdreffc = vfn.bdreffc)
        AND fn.bddatabaixafc IS NOT NULL
  GROUP BY vfn.BDCODVER,  vfn.BDCODEMP, bdrefcomp
UNION
SELECT vft.BDCODVER, vft.BDCODEMP,
       EXTRACT(YEAR FROM ft.bddatabaixafc)||SUBSTRING(ft.bddatabaixafc FROM 6 FOR 2)
       bdrefcomp, SUM(vft.bdvalvfc)
  FROM vrhf_emp_tverbafctomador vft, vrhf_emp_tfoltomcomp ft
  WHERE (ft.bdcodemp = vft.bdcodemp AND ft.bdcodcol = vft.bdcodcol AND ft.bdreftomador = vft.bdreftomador AND ft.bdordem = vft.bdordem AND ft.bdreffc = vft.bdreffc)
        AND ft.bddatabaixafc IS NOT NULL
  GROUP BY vft.BDCODVER,  vft.BDCODEMP, bdrefcomp
)
GROUP BY BDCODVER, BDCODEMP, bdrefcomp
;

/* CREATE OR ALTER VIEW: VW_VRHF_SS_PGTO_FER (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_SS_PGTO_FER(
BDCODVER,
BDCODEMP,
BDREFFER,
BDVALOR)
 AS 
SELECT vfe.BDCODVER, vfe.BDCODEMP, EXTRACT(YEAR FROM fe.bddatabaixafe)||SUBSTRING(fe.bddatabaixafe FROM 6 FOR 2) bdreffer, SUM(vfe.bdvalvfe) bdvalor
FROM vrhf_emp_tverbafe vfe, vrh_emp_tferias fe
WHERE fe.bdcodemp = vfe.bdcodemp AND fe.bdcodcol = vfe.bdcodcol AND fe.bdiniperaquisfe = vfe.bdiniperaquisfe AND fe.bdcodfe = vfe.bdcodfe
      AND fe.bddatabaixafe IS NOT NULL
GROUP BY vfe.BDCODVER,  vfe.BDCODEMP, bdreffer
;

/* CREATE OR ALTER VIEW: VW_VRHF_SS_PGTO_FN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_SS_PGTO_FN(
BDCODVER,
BDCODEMP,
BDREFFN,
BDVALOR)
 AS 
SELECT BDCODVER, BDCODEMP, bdreffn, SUM(bdvalor) FROM (
SELECT vfn.BDCODVER, vfn.BDCODEMP,
       EXTRACT(YEAR FROM fn.bddatabaixafn)||SUBSTRING(fn.bddatabaixafn FROM 6 FOR 2)
       bdreffn, SUM(vfn.BDVALVFN) bdvalor
  FROM vrhf_emp_tverbafn vfn, vrhf_emp_tfolhanormal fn
  WHERE (fn.bdcodemp = vfn.bdcodemp AND fn.bdcodcol = vfn.bdcodcol AND fn.bdreffn = vfn.bdreffn)
        AND fn.bddatabaixafn IS NOT NULL
  GROUP BY vfn.BDCODVER,  vfn.BDCODEMP, bdreffn
UNION
SELECT vft.BDCODVER, vft.BDCODEMP,
       EXTRACT(YEAR FROM ft.bddatabaixaft)||SUBSTRING(ft.bddatabaixaft FROM 6 FOR 2)
       bdreffn, SUM(vft.bdvalvft)
  FROM vrhf_emp_tverbatomador vft, vrhf_emp_tfolhatomador ft
  WHERE (ft.bdcodemp = vft.bdcodemp AND ft.bdcodcol = vft.bdcodcol AND ft.bdreftomador = vft.bdreftomador AND ft.bdordem = vft.bdordem)
        AND ft.bddatabaixaft IS NOT NULL
  GROUP BY vft.BDCODVER,  vft.BDCODEMP, bdreffn
)
GROUP BY BDCODVER, BDCODEMP, bdreffn
;

/* CREATE OR ALTER VIEW: VW_VRHF_TABELAS_TCONTRSINDFAIX (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VRHF_TABELAS_TCONTRSINDFAIX(
BDCODCONTRSIND,
BDCLAINISIND,
BDREFCONTRSIND,
BDCLAFIMSIND,
BDALIQSIND,
BDPARCADICSIND)
 AS 
SELECT
  BDCODCONTRSIND  ,
  BDCLAINISIND    ,
  BDREFCONTRSIND  ,
  BDCLAFIMSIND    ,
  BDALIQSIND      ,
  BDPARCADICSIND
FROM VRHF_TABELAS_TCONTRSINDFAIX x
WHERE X.bdrefcontrsind =
      (
       SELECT MAX(Y.bdrefcontrsind)
       FROM VRHF_TABELAS_TCONTRSINDFAIX Y
       WHERE Y.bdcodcontrsind = X.bdcodcontrsind AND
             Y.bdrefcontrsind <=
                (SELECT COALESCE(CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER),y.bdrefcontrsind)
                 FROM rdb$database
                )
      )
;


/* CREATE OR ALTER VIEW: VW_VSUC_TLAN_CONTAS_USADAS_DEB (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VSUC_TLAN_CONTAS_USADAS_DEB(
BDCODEMP,
BDCODPLAPADRAO,
BDDEBITO,
BDDATA)
 AS 
SELECT BDCODEMP, BDCODPLAPADRAO, BDDEBITO, BDDATA FROM vsuc_empresas_tlan
WHERE (bddebito IS NOT NULL)
;

/* CREATE OR ALTER VIEW: VW_VSUC_TLAN_CONTAS_USADAS_CRE (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VSUC_TLAN_CONTAS_USADAS_CRE(
BDCODEMP,
BDCODPLAPADRAO,
BDDEBITO,
BDDATA)
 AS 
SELECT BDCODEMP, BDCODPLAPADRAO, BDCREDITO, BDDATA FROM vsuc_empresas_tlan
WHERE (BDCREDITO IS NOT NULL)
;

/* CREATE OR ALTER VIEW: VW_VSUC_TLAN_CONTAS_USADAS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_VSUC_TLAN_CONTAS_USADAS(
BDCODEMP,
BDCODPLAPADRAO,
BDCONTA,
BDDATA)
 AS 
SELECT BDCODEMP, BDCODPLAPADRAO, BDDEBITO, BDDATA FROM VW_VSUC_TLAN_CONTAS_USADAS_DEB
 UNION
SELECT BDCODEMP, BDCODPLAPADRAO, BDDEBITO, BDDATA FROM VW_VSUC_TLAN_CONTAS_USADAS_CRE
;

/* Create view: VWEF_EMPMENSAL_ABA_FEDE (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWEF_EMPMENSAL_ABA_FEDE(
    BDCODEMP,
    BDREFEMP,
    BDPERFILSPED,
    BDATIVIDADESPED,
    BDTIPODECLARANTEDMED,
    BDREGISTROANSDMED,
    BDNUMEROCNESDMED,
    BDLRISSSN,
    BDINDNATPJ,
    BDINDATIV,
    BDCODACESSOSN,
    BDCODPLANOCONFSN,
    BDDESCRICAOPLANOSN,
    BDGERAC490,
    BDENTREGAECDREINF,
    BDOPTANTERET,
    BDCODCLASSESTAB,
    BDCONTABGUIAMUN,
    BDCODCONFICMSSPED)
AS
SELECT
  EFFED.BDCODEMP,
  EFFED.BDREFEMP,
  CASE
    WHEN EFFED.BDPERFILSPED = 0 THEN 'A - Perfil A'
    WHEN EFFED.BDPERFILSPED = 1 THEN 'B - Perfil B'
    WHEN EFFED.BDPERFILSPED = 2 THEN 'C - Perfil C'
    WHEN EFFED.BDPERFILSPED IS NULL THEN 'A - Perfil A'
  END BDPERFILSPED,
  CASE
    WHEN EFFED.BDATIVIDADESPED = 1 THEN '1 - Outros'
    WHEN EFFED.BDATIVIDADESPED <> 1 THEN '0 - Industrial ou equiparado a industrial'
    WHEN EFFED.BDATIVIDADESPED IS NULL THEN '0 - Industrial ou equiparado a industrial'
  END BDATIVIDADESPED,
  CASE
    WHEN EFFED.BDTIPODECLARANTEDMED = 1 THEN '1 - Prestador de serviço de saúde'
    WHEN EFFED.BDTIPODECLARANTEDMED = 2 THEN '2 - Operadora de plano privado de assistência a saúde'
    WHEN EFFED.BDTIPODECLARANTEDMED = 3 THEN '3 - Prestador de serviço de saúde e operadora de plano privado de assistência a saúde'
    WHEN EFFED.BDTIPODECLARANTEDMED NOT IN (1,2,3) THEN '0 - Não se aplica'
    WHEN EFFED.BDTIPODECLARANTEDMED IS NULL THEN '0 - Não se aplica'
  END BDTIPODECLARANTEDMED,
  COALESCE(EFFED.BDREGISTROANSDMED, 0) BDREGISTROANSDMED,
  COALESCE(EFFED.BDNUMEROCNESDMED, 0) BDNUMEROCNESDMED,
  COALESCE(EFFEDATV.BDLRISSSN, 0.000000) BDLRISSSN,

  
  CASE
    WHEN EFFED.BDINDNATPJ = 0 THEN '00 - Sociedade empresária em geral'
    WHEN EFFED.BDINDNATPJ = 1 THEN '01 - Sociedade cooperativa'
    WHEN EFFED.BDINDNATPJ = 2 THEN '02 - Entidade sujeita ao PIS/Pasep exclusivamente com base na folha de salários'
    WHEN EFFED.BDINDNATPJ = 3 THEN '03 - Pessoa jurídica em geral participante de SCP como sócia ostensiva'
    WHEN EFFED.BDINDNATPJ = 4 THEN '04 - Sociedade cooperativa participante de SCP como sócia ostensiva'
    WHEN EFFED.BDINDNATPJ = 5 THEN '05 - Sociedade em Conta de Participação - SCP'
    ELSE '00 - Sociedade empresária em geral'
  END BDINDNATPJ,

  i.bdcodexportar||' - '||i.bddescricao bdindativ,
  EFFED.BDCODACESSOSN,effed.bdcodplanoconfsn , sn.bddescricaoplanosn ,
  EFFED.BDGERAC490,EFFED.BDENTREGAECDREINF,EFFED.BDOPTANTERET, EFFED.BDCODCLASSESTAB, EFFED.BDCONTABGUIAMUN, EFFED.BDCODCONFICMSSPED


FROM
  VEF_BASE_TEMPPARFED EFFED
LEFT OUTER JOIN VEF_BASE_TEMPPARFEDPORATV EFFEDATV ON (EFFED.BDCODEMP = EFFEDATV.BDCODEMP AND EFFED.BDREFEMP = EFFEDATV.BDREFEMP)
LEFT OUTER JOIN vef_base_ttabindativ i ON (effed.bdindativ = i.bdindativ)
left outer join vef_base_tplanoconfsn sn on (sn.bdcodplanoconfsn = effed.bdcodplanoconfsn)
;

/* CREATE OR ALTER VIEW: VWEF_EMPMENSAL_ABA_FEDE_REF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWEF_EMPMENSAL_ABA_FEDE_REF(
BDCODEMP,
BDREFEMP,
BDPERFILSPED,
BDATIVIDADESPED,
BDTIPODECLARANTEDMED,
BDREGISTROANSDMED,
BDNUMEROCNESDMED,
BDLRISSSN,
BDINDNATPJ,
BDINDATIV,
    BDCODACESSOSN,
    BDOPTANTERET,
    BDGERAC490,
    BDCODCONFICMSSPED)
AS
SELECT
    BDCODEMP,
    BDREFEMP,
    BDPERFILSPED,
    BDATIVIDADESPED,
    BDTIPODECLARANTEDMED,
    BDREGISTROANSDMED,
    BDNUMEROCNESDMED,
    BDLRISSSN,
    BDINDNATPJ,
    BDINDATIV,
    BDCODACESSOSN,
    BDOPTANTERET,
    BDGERAC490,
    BDCODCONFICMSSPED
FROM VWEF_EMPMENSAL_ABA_FEDE x
WHERE x.bdrefemp = COALESCE(

  (SELECT MAX(y.bdrefemp) bdrefempx FROM VWEF_EMPMENSAL_ABA_FEDE y
    WHERE y.bdrefemp <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database) AND y.bdcodemp = x.bdcodemp GROUP BY y.bdcodemp)
  ,
  (SELECT MIN(y.bdrefemp) bdrefempx FROM VWEF_EMPMENSAL_ABA_FEDE y WHERE y.bdcodemp = x.bdcodemp GROUP BY y.bdcodemp)

  )
;

/* CREATE OR ALTER VIEW: VWEF_EMPMENSAL_ABA_PARA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWEF_EMPMENSAL_ABA_PARA(
    BDCODEMP,
    BDREFEMP,
    BDLANBCICMSISEOUT,
    BDMOVSER,
    BDPERCISS,
    BDREDPERCISS,
    BDMOVIRRF,
    BDALIQIRRF,
    BDISENTOIRRF,
    BDRETINSS,
    BDVLRMININSS,
    BDLANBCICMSVALCONT,
    BDEMPDIFPAPEL,
    BDLANPROENT,
    BDLANPROSAI,
    BDTIPOAPURACAO,
    BDTIPOAPURACAORET,
    BDTIPOAPURACAORETIR,
    BDTIPOAPURACAORETIRTOM)
AS
SELECT
  EFCONF.BDCODEMP,
  EFCONF.BDREFEMP,
  CASE
    WHEN EFCONF.BDLANBCICMSISEOUT = 1 THEN 'Outras'
    WHEN EFCONF.BDLANBCICMSISEOUT <> 1 THEN 'Isentas'
    WHEN EFCONF.BDLANBCICMSISEOUT IS NULL THEN 'Isentas'
  END BDLANBCICMSISEOUT,
  COALESCE(EFCONF.BDMOVSER, 'FALSE') BDMOVSER,
  COALESCE(EFCONF.BDPERCISS, 0.000000) BDPERCISS,
  COALESCE(EFCONF.BDREDPERCISS, 0.000000) BDREDPERCISS,
  COALESCE(EFCONF.BDMOVIRRF, 'FALSE') BDMOVIRRF,
  COALESCE(EFCONF.BDALIQIRRF, 0.000000) BDALIQIRRF,
  COALESCE(EFCONF.BDISENTOIRRF, 0.000000) BDISENTOIRRF,
  COALESCE(EFCONF.BDRETINSS, 'FALSE') BDRETINSS,
  COALESCE(EFCONF.BDVLRMININSS, 0.000000) BDVLRMININSS,
  COALESCE(EFCONF.BDLANBCICMSVALCONT,'FALSE') BDLANBCICMSVALCONT,
  COALESCE(EFCONF.BDEMPDIFPAPEL, 'FALSE') BDEMPDIFPAPEL,
  COALESCE(EFCONF.BDLANPROENT, 'FALSE') BDLANPROENT,
  COALESCE(EFCONF.BDLANPROSAI, 'FALSE') BDLANPROSAI,
  COALESCE(EFCONF.BDTIPOAPURACAO, -1) BDTIPOAPURACAO,
  COALESCE(EFCONF.BDTIPOAPURACAORET, -1) BDTIPOAPURACAORET,  
  COALESCE(EFCONF.BDTIPOAPURACAORETIR, -1) BDTIPOAPURACAORETIR,
  COALESCE(EFCONF.BDTIPOAPURACAORETIRTOM, -1) BDTIPOAPURACAORETIRTOM
FROM
  VEF_BASE_TEMPPARGER EFCONF
;

/* CREATE OR ALTER VIEW: VWEF_EMPMENSAL_ABA_PGER (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWEF_EMPMENSAL_ABA_PGER(
    BDCODEMP,
    BDREFEMP,
    BDSUBSTRIB,
    BDCODPORTEEMP,
    BDREDBCICMSENT,
    BDREDBCICMSSAI,
    BDPARICMSEMP,
    BDDIAVCTOICMS,
    BDANTFERIADOICMS,
    BDVCTOMESICMS,
    BDDIAJUROSICMS,
    BDJURICMSEMP,
    BDJUROMESDIA,
    BDPELASELIC,
    BDDIAMULTAICMS,
    BDMULTAICMSEMP,
    BDMULTAMESDIA,
    BDMULTAMAXICMS,
    BDAPURAGIAST,
    BDDISTRIBUIDORCOMB,
    BDCODCONFGIAST,
    BDEC8715,
    BDICMSMONO)
AS
SELECT
  EFPAREST.BDCODEMP,
  EFPAREST.BDREFEMP,
  CASE
    WHEN EFPAREST.BDSUBSTRIB = 1 THEN 'Não'
    WHEN EFPAREST.BDSUBSTRIB = 2 THEN 'Substituído solidário'
    WHEN EFPAREST.BDSUBSTRIB NOT IN (1,2) THEN 'Sim'
    WHEN EFPAREST.BDSUBSTRIB IS NULL THEN 'Sim'
  END BDSUBSTRIB,
  COALESCE(EFPAREST.BDCODPORTEEMP||'-'||PORTEEMP.BDDESPORTEEMP, '') BDCODPORTEEMP,
  COALESCE(EFPAREST.BDREDBCICMSENT, 0.000000) BDREDBCICMSENT,
  COALESCE(EFPAREST.BDREDBCICMSSAI, 0.000000) BDREDBCICMSSAI,
  COALESCE(EFPAREST.BDPARICMSEMP, 'FALSE') BDPARICMSEMP,
  COALESCE(EFPAREST.BDDIAVCTOICMS, 0) BDDIAVCTOICMS,
  COALESCE(EFPAREST.BDANTFERIADOICMS, 'FALSE') BDANTFERIADOICMS,
  CASE
    WHEN EFPAREST.BDVCTOMESICMS = 1 THEN 'Seguinte'
    WHEN EFPAREST.BDVCTOMESICMS = 2 THEN 'Subsequente'
    WHEN EFPAREST.BDVCTOMESICMS = 3 THEN 'Dia útil'
    WHEN EFPAREST.BDVCTOMESICMS = 4 THEN '3º mês subsequente'
    WHEN EFPAREST.BDVCTOMESICMS IS NULL THEN 'Do movimento'
    WHEN EFPAREST.BDVCTOMESICMS NOT IN (1,2,3) THEN 'Do movimento'
  END BDVCTOMESICMS,
  COALESCE(EFPAREST.BDDIAJUROSICMS, 0) BDDIAJUROSICMS,
  COALESCE(EFPAREST.BDJURICMSEMP, 0.000000) BDJURICMSEMP,
  CASE
    WHEN EFPAREST.BDJUROMESDIA = 1 THEN 'Mês'
    WHEN EFPAREST.BDJUROMESDIA <> 1 THEN 'Dia'
    WHEN EFPAREST.BDJUROMESDIA IS NULL THEN 'Dia'
  END BDJUROMESDIA,
  CASE
    WHEN EFPAREST.BDPELASELIC = 1 THEN 'Selic'
    WHEN EFPAREST.BDPELASELIC = 2 THEN 'TJLP'
    WHEN EFPAREST.BDPELASELIC NOT IN (1,2) THEN 'Nenhum'
    WHEN EFPAREST.BDPELASELIC IS NULL THEN 'Nenhum'
  END BDPELASELIC,
  COALESCE(EFPAREST.BDDIAMULTAICMS, 0) BDDIAMULTAICMS,
  COALESCE(EFPAREST.BDMULTAICMSEMP, 0.000000) BDMULTAICMSEMP,
  CASE
    WHEN EFPAREST.BDMULTAMESDIA = 1 THEN 'Mês'
    WHEN EFPAREST.BDMULTAMESDIA <> 1 THEN 'Dia'
    WHEN EFPAREST.BDMULTAMESDIA IS NULL THEN 'Dia'
  END BDMULTAMESDIA,
  COALESCE(EFPAREST.BDMULTAMAXICMS, 0.000000) BDMULTAMAXICMS,
  EFPAREST. BDAPURAGIAST,
  EFPAREST. BDDISTRIBUIDORCOMB,
  EFPAREST.BDCODCONFGIAST,
  EFPAREST.BDEC8715,
  EFPAREST.BDICMSMONO

FROM
  VEF_BASE_TEMPPAREST EFPAREST
LEFT OUTER JOIN TPORTE_EMPRESA PORTEEMP ON (EFPAREST.BDCODPORTEEMP = PORTEEMP.BDCODPORTEEMP)
;
/* CREATE OR ALTER VIEW: VWEF_EMPMENSAL_ABA_UFSC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWEF_EMPMENSAL_ABA_UFSC(
    BDCODEMP,
    BDREFEMP,
    BDCONTPRODEC,
    BDNRPARPRODEC,
    BDCODCONFDIMESC,
    BDCODESCCONT,
    BDCODAPUCON,
    BDCODREGAPU,
    BDDESCCONF,
    BDALIMPREP,
    BDCOOPAGRO,
    BDDETFILIAL,
    BDDETRESULTFILIAL,
    BDCODPLACONFDRCST,
    BDCODPLASEFSC)
AS
SELECT
  EFPARESTSC.BDCODEMP,
  EFPARESTSC.BDREFEMP,
  COALESCE(EFPARESTSC.BDCONTPRODEC, 'FALSE') BDCONTPRODEC,
  EFPARESTSC.BDNRPARPRODEC,
  EFPARESTSC.BDCODCONFDIMESC,
  COALESCE(EFPARESTSC.BDCODESCCONT||'-'||EFPARESTSCEC.BDDESCESCCONT , '') BDCODESCCONT,
  COALESCE(EFPARESTSC.BDCODAPUCON||'-'||EFPARESTSCAC.BDDESCAPUCON, '') BDCODAPUCON,
  COALESCE(EFPARESTSC.BDCODREGAPU||'-'||EFPARESTSCRA.BDDESCREGAPU, '') BDCODREGAPU,
  DIMEESTSC.BDDESCCONF,
  COALESCE(EFPARESTSC.BDALIMPREP, 'FALSE') BDALIMPREP,
  COALESCE(EFPARESTSC.BDCOOPAGRO, 'FALSE') BDCOOPAGRO,
  COALESCE(EFPARESTSC.bddetfilial, 'FALSE') BDDETFILIAL,
  COALESCE(EFPARESTSC.bdDETRESULTFILIAL, 'FALSE') bdDETRESULTFILIAL ,
  EFPARESTSC.BDCODPLACONFDRCST,
  efparestsc.bdCODPLASEFSC
FROM
  VEF_BASE_TEMPPARESTSC EFPARESTSC
LEFT OUTER JOIN VEF_ESTADOS_TCONFDIMESC DIMEESTSC ON (EFPARESTSC.BDCODCONFDIMESC = DIMEESTSC.BDCODCONFDIMESC)
LEFT OUTER JOIN VEF_BASE_TEMPPARESTSCEC EFPARESTSCEC ON (EFPARESTSC.BDCODESCCONT = EFPARESTSCEC.BDCODESCCONT)
LEFT OUTER JOIN VEF_BASE_TEMPPARESTSCAC EFPARESTSCAC ON (EFPARESTSC.BDCODAPUCON = EFPARESTSCAC.BDCODAPUCON)
LEFT OUTER JOIN VEF_BASE_TEMPPARESTSCRA EFPARESTSCRA ON (EFPARESTSC.BDCODREGAPU = EFPARESTSCRA.BDCODREGAPU)
;

create or alter view VW_PLANOS_TFOR_IBGE_REF_MAX_MIN (
    BDCODIBGE,
    BDCODTFOR,
    BDREFCTA)
as
select TFOR.BDCODIBGE, TFOR.BDCODTFOR,

       coalesce((select first 1 X.BDREFCTA from PLANOS_TFOR_IBGE_PADRAO X
                 where X.BDCODIBGE = TFOR.BDCODIBGE and
                       X.BDCODTFOR = TFOR.BDCODTFOR and
                       cast(X.BDREFCTA as varchar(6)) <= (select trim(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) from RDB$DATABASE)
                 order by X.BDREFCTA desc),
       (select first 1 X.BDREFCTA from PLANOS_TFOR_IBGE_PADRAO X
        where X.BDCODIBGE = TFOR.BDCODIBGE and
              X.BDCODTFOR = TFOR.BDCODTFOR
        order by X.BDREFCTA)) BDREFCTA

from PLANOS_TFOR_IBGE_PADRAO TFOR
group by TFOR.BDCODIBGE, TFOR.BDCODTFOR; 


CREATE OR ALTER VIEW VW_CONTAS_IBGE(
    BDCODIBGE,
    BDANO,
    BDCODEMP,
    BDCOLUNAIBGE,
    BDCODTFOR,
    BDNOMFOR,
    BDFORMULA,
    BDEXPORTANEG,
    BDDTINIVALIDADE,
    BDDTFIMVALIDADE)
AS
select PADRAO.BDCODIBGE, FORM.BDANO, FORM.BDCODEMP, PADRAO.BDCOLUNAIBGE, PADRAO.BDCODTFOR,
       PADRAO.BDNOMFOR,
       case
         when (trim(FORM.BDDESCFOR) = '') then FORM.BDDESCFOR
         else case
                when (FORM.BDTIPOFOR = 1) then FORM.BDDESCFOR
                when (FORM.BDTIPOFOR = 2) then 'SALATU(' || FORM.BDDESCFOR || ')'
                when (FORM.BDTIPOFOR = 3) then 'SALANT(' || FORM.BDDESCFOR || ')'
                when (FORM.BDTIPOFOR = 4) then 'MOVPER(' || FORM.BDDESCFOR || ')'
                else ''
              end
       end BDFORMULA,
       FORM.BDEXPORTANEG, PADRAO.BDDTINIVALIDADE, PADRAO.BDDTFIMVALIDADE
from PLANOS_TFOR_IBGE_PADRAO PADRAO
join VW_PLANOS_TFOR_IBGE_REF_MAX_MIN M on (M.BDCODIBGE = PADRAO.BDCODIBGE and M.BDCODTFOR = PADRAO.BDCODTFOR and M.BDREFCTA = PADRAO.BDREFCTA)
left outer join PLANOS_TFOR_EMP_IBGE FORM on (PADRAO.BDCODIBGE = FORM.BDCODIBGE and PADRAO.BDCODTFOR = FORM.BDCODTFOR)
where FORM.BDTIPOFOR > 0 and
      FORM.BDDESCFOR <> ''
order by BDCODIBGE, BDANO, BDCODEMP, BDCOLUNAIBGE
;

CREATE OR ALTER VIEW VW_CONTAS_ECF (
    BDCODPLAFORPADRAOREF,
    BDCODTFORREF,
    BDCODPLAPADRAO,
    BDANO,
    BDTIPOFOR,
    BDDESCFOR)
as
select TFOR.BDCODPLAFORPADRAOREF, TFOR.BDCODTFORREF, TFOR.BDCODPLAPADRAO, TFOR.BDANO, TFOR.BDTIPOFOR,
       case
         when (trim(TFOR.BDDESCFOR) = '') then TFOR.BDDESCFOR
         else case
                when (TFOR.BDTIPOFOR = 1) then TFOR.BDDESCFOR
                when (TFOR.BDTIPOFOR = 2) then 'SALATU(' || TFOR.BDDESCFOR || ')'
                when (TFOR.BDTIPOFOR = 3) then 'SALANT(' || TFOR.BDDESCFOR || ')'
                when (TFOR.BDTIPOFOR = 4) then 'MOVPER(' || TFOR.BDDESCFOR || ')'
                else ''
              end
       end BDDESCFOR
from PLANOS_TFOR_ECF TFOR;

/* CREATE OR ALTER VIEW: VWGR_EF_DARESC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWGR_EF_DARESC(
BDCODEMP,
BDCNPJEMP,
BDIEEMP,
BDNOMEMP,
BDDDDEMP,
BDFONEEMP,
BDCODCID,
BDCODREC,
BDCODIMP,
BDCODPERIODO,
BDREFERENCIA,
BDPERIODO,
BDDATAVCTO,
BDVALOR,
BDMULTA,
BDJUROS,
BDVLRIMPORIGINAL,
BDVLRACUMULO,
BDVLRMULTAJUROS,
BDTOTAL,
BDREFPAG,
BDCLAVENDIMEGERQ12,
BDPARAMREL,
BDCODRECOF)
 AS 
SELECT temp.BDCODEMP,
       temp.BDCNPJEMP,
       trefemp.BDIEEMP,
       trefemp.BDNOMEMP,
       trefemp.BDDDDEMP,
       trefemp.BDFONEEMP,
       trefemp.BDCODCID,
       trec.bdCODREC,
       tdarf.bdCODIMP,
       tdarf.bdCODPERIODO,
       tdarf.bdREFERENCIA,
       tdarf.bdPERIODO,
       tdarf.bdDATAVCTO,
       tdarf.bdVALOR,
       tdarf.bdMULTA,
       tdarf.bdJUROS,
       tdarf.bdVLRIMPORIGINAL,
       tdarf.bdVLRACUMULO,
       tdarf.bdVLRMULTAJUROS,
       tdarf.bdTOTAL,
       tdarf.bdrefpag,
       tdimegerq12.bdclavendimegerq12,
       0,
       TREC.bdcodrecof
FROM TEMPRESAS temp
INNER JOIN vw_empresas_ref_atual trefemp ON (trefemp.bdCODEMP = temp.bdCODEMP)
INNER JOIN tdarfpadrao tdarf ON (tdarf.bdcodemp = temp.bdcodemp)
INNER JOIN timposto timp ON (timp.bdcodimp = tdarf.bdcodimp)
LEFT OUTER JOIN tcodrec trec ON (trec.bdcodrec = timp.bdcodrec)
LEFT OUTER JOIN VEF_EMP_TDIMEGERQ12 tdimegerq12 ON (tdimegerq12.bdcodemp = temp.bdcodemp AND tdimegerq12.bdcodperiodo = tdarf.bdcodperiodo
                                                    AND tdimegerq12.bdreferencia = tdarf.bdreferencia)

/*tipo imposto DARE no cadastro de codigo de receitas*/
WHERE (trec.bdtipoimposto = 8)
and((TEMP.bdexcluiremp is null)or(upper(TEMP.bdexcluiremp)<>'TRUE'))
;

/* CREATE OR ALTER VIEW: VWGR_EF_EXP_DCIP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWGR_EF_EXP_DCIP(
BDCODEMP,
BDCNPJEMP,
BDNOMEMP,
BDIEEMP,
BDCODTIPODISC,
BDCHAVEDCIP,
BDCODTIPCRED,
BDREFDCIP,
BDVLRCREDDCIP,
BDNUMDCIP,
BDPARAMREL)
 AS 
SELECT movocorr.BDCODEMP,
       TEMP.bdcnpjemp,
       TREF.bdnomemp,
       TREF.bdieemp,
       movocorr.BDCODTIPODISC,
       movocorr.BDCHAVEDCIP,
       movocorr.BDCODTIPCRED,
       movocorr.BDREFDCIP,
       movocorr.BDVLRCREDDCIP,
       movocorr.BDNUMDCIP,
       0




FROM VEF_EMP_TMOV_OCORR_DCIP movocorr
INNER JOIN tempresas temp ON (temp.bdcodemp = movocorr.bdcodemp)
INNER JOIN tempresas_ref tref ON (tref.bdcodemp = temp.bdcodemp)

WHERE tref.bdrefemp =
      (
       SELECT MAX(tref2.BDREFEMP)
       FROM tempresas_ref tref2
       WHERE tref2.BDCODEMP = tref.BDCODEMP AND
             tref2.BDREFEMP <=
                (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER)
                 FROM rdb$database
                )

      )


ORDER BY movocorr.BDCODEMP, movocorr.BDCODTIPODISC, movocorr.bdcodtipcred
;

/* CREATE OR ALTER VIEW: VWGR_EF_EXP_DCTF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWGR_EF_EXP_DCTF(
    BDCODEMP,
    BDCNPJEMP,
    BDCODCID,
    BDCODCONT,
    BDNOMEMP,
    BDAPEEMP,
    BDENDEMP,
    BDNUMEMP,
    BDBAIEMP,
    BDCEPEMP,
    BDDDDEMP,
    BDFONEEMP,
    BDFAXEMP,
    BDEMAILEMP,
    BDCOMPLEMP,
    BDLOGREMP,
    BDDDDFAXEMP,
    BDCODNATJUR,
    BDNOMCID,
    BDCODUF,
    BDSIGLAUFEMP,
    BDDESCUF,
    BDNOMSOC,
    BDCGCCEISOC,
    BDDDSOC,
    BDTELRESSOC,
    BDDDDFAXSOC,
    BDFAXSOC,
    BDEMAILSOC,
    BDNOMECONT,
    BDCPFCONT,
    BDCRCCONT,
    BDDDDCONT,
    BDFONECONT,
    BDDDDFAXCONT,
    BDFAXCONT,
    BDEMAILCONT,
    BDSIGLAUFCRC,
    BDCODREC,
    BDTIPOIMPOSTO,
    BDVARIACAO,
    BDPERAPURACAO,
    BDCODIMP,
    BDCODPERIODO,
    BDREFERENCIA,
    BDQUOTA,
    BDPERIODO,
    BDDATAVCTO,
    BDVALOR,
    BDMULTA,
    BDJUROS,
    BDVLRIMPORIGINAL,
    BDVLRACUMULO,
    BDVLRMULTAJUROS,
    BDTOTAL,
    BDSUMTOTAL,
    BDPARAMREL,
    BDCODRECOF)
AS
SELECT temp.BDCODEMP,
       temp.BDCNPJEMP,
       trefemp.BDCODCID,
       trefemp.BDCODCONT,
       trefemp.BDNOMEMP,
       trefemp.BDAPEEMP,
       trefemp.BDENDEMP,
       trefemp.BDNUMEMP,
       trefemp.BDBAIEMP,
       trefemp.BDCEPEMP,
       trefemp.BDDDDEMP,
       trefemp.BDFONEEMP,
       trefemp.BDFAXEMP,
       trefemp.BDEMAILEMP,
       trefemp.BDCOMPLEMP,
       trefemp.BDLOGREMP,
       trefemp.BDDDDFAXEMP,
       trefemp.BDCODNATJUR,
       tcid.BDNOMCID,
       tcid.BDCODUF,
       test.BDSIGLAUF,
       test.BDDESCUF,
       tsoc_ref.bdNOMSOC,
       tsoc.bdCGCCEISOC,
       tsoc_ref.bdDDDSOC AS bdDDSOC,
       tsoc_ref.bdTELRESSOC,
       tsoc_ref.bdDDDFAXSOC,
       tsoc_ref.bdFAXSOC,
       tsoc_ref.bdEMAILSOC,
       tcon.bdNOMECONT,
       tcon.bdCPFCONT,
       tcon.bdCRCCONT,
       tcon.bdDDDCONT,
       tcon.bdFONECONT,
       tcon.bdDDDFAXCONT,
       tcon.bdFAXCONT,
       tcon.bdEMAILCONT,
       tufcrccont.bdSIGLAUF,
       trec.bdCODREC,
       trec.bdTIPOIMPOSTO,
       tvarrec.bdVARIACAO,
       timp.bdPERAPURACAO,
       tdarf.bdCODIMP,
       tdarf.bdCODPERIODO,
       tdarf.bdREFERENCIA,
       tdarf.bdQUOTA,
       tdarf.bdPERIODO,
       tdarf.bdDATAVCTO,
       tdarf.bdVALOR,
       tdarf.bdMULTA,
       tdarf.bdJUROS,
       tdarf.bdVLRIMPORIGINAL,
       tdarf.bdVLRACUMULO,
       tdarf.bdVLRMULTAJUROS,
       tdarf.bdTOTAL,
       (SELECT SUM(tdarfsub.bdtotal) FROM tdarfpadrao tdarfsub
        LEFT OUTER JOIN timposto timpsub ON (timpsub.bdcodimp = tdarfsub.bdcodimp)
        LEFT OUTER JOIN tcodrec trecsub ON (trecsub.bdcodrec = timpsub.bdcodrecvar)
        WHERE tdarfsub.bdcodemp = tdarf.bdcodemp AND tdarfsub.bdreferencia = tdarf.bdreferencia AND tdarf.bdcodimp = tdarfsub.bdcodimp
        GROUP BY tdarfsub.bdcodemp, tdarfsub.bdreferencia, trecsub.bdcodrec
       ) bdsumtotal,
       0,
       TREC. BDCODRECOF

FROM TEMPRESAS temp
LEFT OUTER JOIN vw_empresas_ref_atual trefemp ON (trefemp.bdCODEMP = temp.bdCODEMP)
LEFT OUTER JOIN TCIDADE tcid ON (tcid.BDCODCID = trefemp.BDCODCID)
LEFT OUTER JOIN TCONTADOR_PADRAO tcon  ON (tcon.BDCODCONT = trefemp.BDCODCONT)
LEFT OUTER JOIN TCIDADE tcidcrccont ON (tcidcrccont.bdCODCID = tcon.bdCODCID)
LEFT OUTER JOIN TUF tufcrccont ON (tufcrccont.bdCODUF = tcidcrccont.bdCODUF)
LEFT OUTER JOIN TUF test  ON (test.BDCODUF = tcid.BDCODUF)
LEFT OUTER JOIN EMPRESAS_TSOC tsoc ON (tsoc.bdcodemp = temp.bdcodemp)
LEFT OUTER JOIN tdarfpadrao tdarf ON (tdarf.bdcodemp = temp.bdcodemp)
LEFT OUTER JOIN timposto timp ON (timp.bdcodimp = tdarf.bdcodimp)
LEFT OUTER JOIN tcodrec trec ON (trec.bdcodrec = timp.bdcodrecvar)
LEFT OUTER JOIN tvariacao_receita tvarrec ON (tvarrec.bdcodrec = trec.bdcodrec AND tvarrec.bdvariacao = timp.bdvariacao)
LEFT OUTER JOIN vw_empresas_tsoc_ref_max_min socref ON (socref.bdcodemp = tsoc.bdcodemp AND socref.bdcodsoc = tsoc.bdcodsoc)
LEFT OUTER JOIN empresas_tsoc_ref tsoc_ref ON (tsoc_ref.bdcodemp = socref.bdcodemp AND tsoc_ref.bdcodsoc = socref.bdcodsoc AND tsoc_ref.bdrefsoc = socref.bdrefsoc)

WHERE((UPPER(tsoc_ref.bdRESPONSAVELSOC)='TRUE')
AND(tdarf.bdreferencia=(SELECT MAX(tdarf2.bdreferencia)
       FROM tdarfpadrao tdarf2
                        WHERE tdarf2.BDCODEMP = tdarf.BDCODEMP
                        AND tdarf2.bdreferencia <= (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER)FROM rdb$database))))
and((temp.bdexcluiremp is null)or(upper(temp.bdexcluiremp)<>'TRUE'))
;


/* CREATE OR ALTER VIEW: VWGR_EF_EXP_DNF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWGR_EF_EXP_DNF(
BDCODEMP,
BDCNPJEMP,
BDNOMEMP,
BDREF,
BDCHAVE,
BDNOMEOBS,
BDORDEM,
BDCODOBS,
BDCODNAT,
BDBASEIPI,
BDCODTER,
BDCGCTER,
BDNUMDOCINI,
BDDATAEMISSAO,
BDESPECIE,
BDSERIE,
BDNUMDOCFIM,
BDMODELO,
BDEMITENTE,
BDDATASAIDA,
BDORDEMPRO,
BDCODPROD,
BDQTDITEM,
BDVLRITEM,
BDVALTOTAL,
BDALIQIPI,
BDAPEUNIMEDFAT,
BDPARAMREL)
 AS 
SELECT SAIITENS.bdcodemp,
       TREF.bdcnpjemp,
       TREF.bdnomemp,
       sai.bdreflan  BDREF,
       SAIITENS.bdchave,
       obs.bdnomeobs,
       SAIITENS.BDORDEM,
       SAIITENS.BDCODOBS,
       SAIITENS.BDCODNAT,
       SAIITENS.BDBASEIPI,

       SAI.BDCODTER,
       TER.BDCGCTER,
       SAI.BDNUMDOCINI,
       SAI.BDDATAEMISSAO,
       SAI.BDESPECIE,
       SAI.BDSERIE,
       SAI.BDNUMDOCFIM,
       SAI.BDMODELO,
       SAI.BDEMITENTE,
       SAI.BDDATASAIDA,

       movpro.bdordempro,
       movpro.bdcodprod,
       movpro.bdqtditem,
       movpro.bdvlritem,
       movpro.bdqtditem * movpro.bdvlritem bdvaltotal,
       movpro.bdaliqipi,
       movpro.BDAPEUNIMEDFAT,
       0

FROM vw_vef_emp_tmovsai_pro_expnfp movpro
LEFT OUTER JOIN  vef_emp_tmovSAIITENS SAIITENS ON (SAIITENS.BDCODEMP = movpro.BDCODEMP AND SAIITENS.bdchave = movpro.bdchave AND saiitens.bdordem = movpro.bdordem)
LEFT OUTER JOIN  vef_emp_tmovSAI SAI ON (SAI.BDCODEMP = saiitens.BDCODEMP AND SAI.bdchave = saiitens.bdchave)
INNER JOIN vw_empresas_ref_atual tref ON  (tref.bdcodemp = movpro.bdcodemp)
LEFT OUTER JOIN  tterceiro ter ON (ter.bdcodter = sai.bdcodter)-- and (ter.BDCODTIPTER = 2)
LEFT OUTER JOIN VEF_BASE_TOBSERVACAO obs ON (obs.bdcodobs = SAIITENS.bdcodobs)
;

/* CREATE OR ALTER VIEW: VWGR_VSUC_CENTROS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWGR_VSUC_CENTROS(
BDCODEMP,
BDNOMEMP,
BDCNPJEMP,
BDCODCENTRO,
BDAPELIDO,
BDNOME,
BDCODTPCC,
BDCTALON,
BDTIPCTA,
BDNOMCTA,
BDAPECTA)
 AS 
SELECT tref.bdcodemp, tref.bdnomemp, tref.bdcnpjemp,
       tcc.bdcodcentro, tcc.bdapelido, tcc.bdnome,
       tpcc.bdcodtpcc, tpcc.bdctalon, tpcc.bdtipcta, tpcc.bdnomcta, tpcc.bdapecta
FROM CENTROS_TPCC tpcc
inner join
     (SELECT tref.bdcodemp, tref.bdcodplapadrao, tref.bdcodhist, tref.bdcodcentros, tref.bdnomemp, temp.bdcnpjemp
      FROM tempresas_ref tref
      INNER JOIN VW_TEMPRESAS_REF_MAX_MIN tid ON (tid.bdcodemp = tref.bdcodemp AND tid.bdrefemp = tref.bdrefemp)
      INNER JOIN tempresas temp ON (temp.bdcodemp = tref.bdcodemp)
      where((temp.bdexcluiremp is null)or(upper(temp.bdexcluiremp)<>'TRUE'))) tref on tref.bdcodcentros = tpcc.bdcodcentro 
INNER JOIN tplano_padrao tpad ON (tpad.bdcodplapadrao = tref.bdcodplapadrao)
INNER JOIN tcentros tcc ON (tcc.bdcodcentro = tpcc.bdcodcentro)
;

/* CREATE OR ALTER VIEW: VWGR_VSUC_HISTORICOS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWGR_VSUC_HISTORICOS(
BDCODEMP,
BDNOMEMP,
BDCNPJEMP,
BDCODHIST,
BDAPELIDO,
BDNOME,
BDCODTPHI,
BDAPEHIS,
BDNOMHIS)
 AS 
SELECT tref.bdcodemp, tref.bdnomemp, tref.bdcnpjemp,
       thist.bdcodhist, thist.bdapelido, thist.bdnome,
       tphi.bdcodtphi, tphi.bdapelido, tphi.bdnome
FROM HIST_TPHI tphi
INNER JOIN thist ON (thist.bdcodhist = tphi.bdcodhist)
INNER JOIN (SELECT tref.bdcodemp, tref.bdcodplapadrao, tref.bdcodhist, tref.bdcodcentros, tref.bdnomemp, temp.bdcnpjemp
            FROM tempresas_ref tref
            INNER JOIN VW_TEMPRESAS_REF_MAX_MIN tid ON (tid.bdcodemp = tref.bdcodemp AND tid.bdrefemp = tref.bdrefemp)
            INNER JOIN tempresas temp ON (temp.bdcodemp = tref.bdcodemp)
            where((temp.bdexcluiremp is null)or(upper(temp.bdexcluiremp)<>'TRUE'))) tref ON (tref.bdcodhist = tphi.bdcodhist)
;

/* CREATE OR ALTER VIEW: VWGR_VSUC_LANCAMENTO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWGR_VSUC_LANCAMENTO(
EMP_BDCODEMP,
EMP_BDNOMEMP,
EMP_BDCNPJEMP,
EMP_BDENDEMP,
EMP_BDNUMEMP,
EMP_BDBAIEMP,
EMP_BDCEPEMP,
EMP_BDDDDEMP,
EMP_BDFONEEMP,
EMP_BDFAXEMP,
EMP_BDEMAILEMP,
EMP_BDCOMPLEMP,
EMP_BDLOGREMP,
EMP_BDIEEMP,
EMP_BDIMEMP,
EMP_BDSITEMP,
EMP_BDDDDFAXEMP,
EMP_BDDOCAUXILIAR,
HIS_BDCODTPHI,
HIS_BDAPELIDO,
HIS_BDNOME,
PARTDEB_BDCODTERCEIROD,
PARTDEB_BDCGCTER,
PARTDEB_BDAPELIDOTER,
PARTDEB_BDNOMETER,
PARTDEB_BDLOGRTER,
PARTDEB_BDENDTER,
PARTDEB_BDNUMTER,
PARTDEB_BDCOMPTER,
PARTDEB_BDCEPTER,
PARTDEB_BDBAITER,
PARTDEB_BDDDDTER,
PARTDEB_BDFONETER,
PARTDEB_BDFAXTER,
PARTDEB_BDEMAILTER,
PARTDEB_BDIETER,
PARTDEB_BDDATACADTER,
PARTDEB_BDIMTER,
PARTDEB_BDPRURALTER,
PARTDEB_BDENQSIMPLESFEDTER,
PARTDEB_BDINSCSUFRAMATER,
PARTDEB_BDDESCPAIS,
PARTDEB_BDDDDFAXTER,
PARTCRE_BDCODTERCEIROC,
PARTCRE_BDCGCTER,
PARTCRE_BDAPELIDOTER,
PARTCRE_BDNOMETER,
PARTCRE_BDLOGRTER,
PARTCRE_BDENDTER,
PARTCRE_BDNUMTER,
PARTCRE_BDCOMPTER,
PARTCRE_BDCEPTER,
PARTCRE_BDBAITER,
PARTCRE_BDDDDTER,
PARTCRE_BDFONETER,
PARTCRE_BDFAXTER,
PARTCRE_BDEMAILTER,
PARTCRE_BDIETER,
PARTCRE_BDDATACADTER,
PARTCRE_BDIMTER,
PARTCRE_BDPRURALTER,
PARTCRE_BDENQSIMPLESFEDTER,
PARTCRE_BDINSCSUFRAMATER,
PARTCRE_BDDESCPAIS,
PARTCRE_BDDDDFAXTER,
CTADEB_BDDEBITO,
CTADEB_BDCTALON,
CTADEB_BDNOMCTA,
CTADEB_BDAPECTA,
CTADEB_BDTIPCTA,
CTADEB_BDRELCTA,
CTADEB_BDCLANOM,
CTADEB_BDFORMULA,
CTADEB_BDCONDICAO,
CTADEB_BDGRUPOCTA,
CTADEB_BDCTACOMP,
CTACRE_BDCREDITO,
CTACRE_BDCTALON,
CTACRE_BDNOMCTA,
CTACRE_BDAPECTA,
CTACRE_BDTIPCTA,
CTACRE_BDRELCTA,
CTACRE_BDCLANOM,
CTACRE_BDFORMULA,
CTACRE_BDCONDICAO,
CTACRE_BDGRUPOCTA,
CTACRE_BDCTACOMP,
LAN_BDCHAVE,
LAN_BDLOTE,
LAN_BDDATA,
LAN_BDVALOR,
LAN_BDCOMPL)
 AS 
SELECT tlan.bdcodemp, tref.bdnomemp, temp.bdcnpjemp, tref.bdendemp, tref.bdnumemp, tref.bdbaiemp, tref.bdcepemp, tref.bddddemp, tref.bdfoneemp, tref.bdfaxemp, tref.bdemailemp, tref.bdcomplemp, tref.bdlogremp, tref.bdieemp, tref.bdimemp, tref.bdsitemp, tref.bddddfaxemp, tref.bddocauxiliar,
       tlan.bdcodtphi, this.bdapelido, this.bdnome,

       tlan.bdcodterceirod, ttercd.bdcgcter, ttercd.bdapelidoter, ttercd.bdnometer, ttercd.bdlogrter, ttercd.bdendter, ttercd.bdnumter, ttercd.bdcompter, ttercd.bdcepter, ttercd.bdbaiter, ttercd.bddddter, ttercd.bdfoneter, ttercd.bdfaxter, ttercd.bdemailter, ttercd.bdieter, ttercd.bddatacadter, ttercd.bdimter, ttercd.bdpruralter, ttercd.bdenqsimplesfedter, ttercd.bdinscsuframater, ttercd.bddescpais, ttercd.bddddfaxter,
       tlan.bdcodterceiroc, ttercc.bdcgcter, ttercc.bdapelidoter, ttercc.bdnometer, ttercc.bdlogrter, ttercc.bdendter, ttercc.bdnumter, ttercc.bdcompter, ttercc.bdcepter, ttercc.bdbaiter, ttercc.bddddter, ttercc.bdfoneter, ttercc.bdfaxter, ttercc.bdemailter, ttercc.bdieter, ttercc.bddatacadter, ttercc.bdimter, ttercc.bdpruralter, ttercc.bdenqsimplesfedter, ttercc.bdinscsuframater, ttercc.bddescpais, ttercc.bddddfaxter,
       tlan.bddebito, tctad.bdctalon, tctad.bdnomcta, tctad.bdapecta, tctad.bdtipcta, tctad.bdrelcta, tctad.bdclanom, tctad.bdformula, tctad.bdcondicao, tctad.bdgrupocta, tctad.bdctacomp,
       tlan.bdcredito, tctac.bdctalon, tctac.bdnomcta, tctac.bdapecta, tctac.bdtipcta, tctac.bdrelcta, tctac.bdclanom, tctac.bdformula, tctac.bdcondicao, tctac.bdgrupocta, tctac.bdctacomp,
       tlan.bdchave, tlan.bdlote, tlan.bddata, tlan.bdvalor, tlan.bdcompl
FROM vsuc_empresas_tlan tlan
JOIN vw_tempresas_ref tref ON (tref.bdcodemp = tlan.bdcodemp)
JOIN tempresas temp ON (temp.bdcodemp = tlan.bdcodemp)
LEFT OUTER JOIN hist_tphi this ON (this.bdcodhist = tlan.bdcodhist AND this.bdcodtphi = tlan.bdcodtphi)
LEFT OUTER JOIN SP_TERCEIRO(tlan.bdcodterceirod) ttercd ON (ttercd.bdCODTER = tlan.bdcodterceirod)
LEFT OUTER JOIN SP_TERCEIRO(tlan.bdcodterceiroc) ttercc ON (ttercc.bdCODTER = tlan.bdcodterceiroc)
LEFT OUTER JOIN planos_tpla tctad ON (tctad.bdcodplapadrao = tlan.bdcodplapadrao AND tctad.bdcodtpla = tlan.bddebito)
LEFT OUTER JOIN planos_tpla tctac ON (tctac.bdcodplapadrao = tlan.bdcodplapadrao AND tctac.bdcodtpla = tlan.bdcredito)
;

/* CREATE OR ALTER VIEW: VWGR_VSUC_PLANOCONTAS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWGR_VSUC_PLANOCONTAS(
BDCODEMP,
BDNOMEMP,
BDCNPJEMP,
BDCODPLAPADRAO,
BDAPELIDO,
BDNOME,
BDCODTPLA,
BDCTALON,
BDNOMCTA,
BDAPECTA,
BDTIPCTA,
BDFORMULA,
BDCONDICAO,
BDGRUPOCTA)
 AS 
SELECT
tref.bdcodemp,
tref.bdnomemp,
tref.bdcnpjemp,
tpla.BDCODPLAPADRAO,
tpad.bdapelido,
tpad.bdnome,
tpla.BDCODTPLA,
tpla.BDCTALON,
tpla.BDNOMCTA,
tpla.BDAPECTA,
tpla.BDTIPCTA,
tpla.BDFORMULA,
tpla.BDCONDICAO,
tpla.BDGRUPOCTA
FROM planos_tpla tpla,
     (SELECT tref.bdcodemp, tref.bdcodplapadrao, tref.bdcodhist, tref.bdcodcentros, tref.bdnomemp, temp.bdcnpjemp
      FROM tempresas_ref tref
      INNER JOIN VW_TEMPRESAS_REF_MAX_MIN tid ON (tid.bdcodemp = tref.bdcodemp AND tid.bdrefemp = tref.bdrefemp)
      INNER JOIN tempresas temp ON (temp.bdcodemp = tref.bdcodemp)
      where((temp.bdexcluiremp is null)or(upper(temp.bdexcluiremp)<>'TRUE'))) tref
INNER JOIN tplano_padrao tpad ON (tpad.bdcodplapadrao = tref.bdcodplapadrao)
WHERE tref.bdcodplapadrao = tpla.bdcodplapadrao
ORDER BY tref.bdcodemp, tpla.bdcodplapadrao, tpla.bdclanom
;

/* CREATE OR ALTER VIEW: VWRH_AGRUPADADOSADSAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_AGRUPADADOSADSAL(
BDCODEMP,
BDCODCOL,
BDCODVER,
BDREFV,
BDREFAUXV,
BDIGNREFV,
BDIGNVALV,
BDPROVENTO,
BDDESCONTO,
BDREF,
BDDATAAD,
BDFGTS,
BDSALBASE,
BDDEP,
BDINSS,
BDIRRF,
BDTIPOCODVER,
BDORDEMTIPOCODVER,
BDINSSVER,
BDFGTSVER,
BDIRVER,
BDTIPOREFVER,
BDBASESFVER,
BDPISVER,
BDBASEHEVER,
BDBASEMAIORVER,
BDRAISVER,
BDBASEGPSVER,
BDDESCVER,
BDCLAVER,
BDREFHOREMP)
 AS 
SELECT
  ASALV.BDCODEMP,
  ASALV.BDCODCOL,
  ASALV.BDCODVER,
  ASALV.BDREFVAD,
  ASALV.BDREFAUXVAD,
  ASALV.BDIGNREFVAD,
  ASALV.BDIGNVALVAD,
  CASE WHEN (VREF.BDTIPOCODVER IN (0, 2)) THEN ASALV.BDVALVAD
       ELSE 0 END BDPROVENTO,
  CASE WHEN (VREF.BDTIPOCODVER IN (0, 2)) THEN 0
       ELSE ASALV.BDVALVAD END BDDESCONTO,
  ASAL.BDREFAD,
  ASAL.BDDATAAD,
  0.0000 BDFGTS,
  ASAL.BDSALBASEAD,
  ASAL.BDDEPIRAD,
  0.0000 BDINSS,
  ASAL.BDVALORIRAD,
  VREF.BDTIPOCODVER,
  VREF.BDORDEMTIPOCODVER,
  VREF.BDINSSVER,
  VREF.BDFGTSVER,
  VREF.BDIRVER,
  VREF.BDTIPOREFVER,
  VREF.BDBASESFVER,
  VREF.BDPISVER,
  VREF.BDBASEHEVER,
  VREF.BDBASEMAIORVER,
  VREF.BDRAISVER,
  VREF.BDBASEGPSVER,
  VERBAS.BDDESCVER,
  VERBAS.BDCLAVER,
  EMPC.BDREFHOREMP
FROM
  VRHF_EMP_TVERBAAD ASALV,
  VRHF_EMP_TADSAL ASAL,
  vw_tverbas_ref VREF,
  VRH_BASE_TVERBAS VERBAS,
  VW_VRHF_BASE_TEMPCALC EMPC

WHERE
  ASALV.BDCODVER = VREF.BDCODVER
  AND ASALV.BDCODEMP = ASAL.BDCODEMP AND ASALV.BDCODCOL = ASAL.BDCODCOL AND ASALV.BDDATAAD = ASAL.BDDATAAD
  AND ASALV.BDCODVER = VERBAS.BDCODVER
  AND ASAL.BDCODEMP = EMPC.BDCODEMP
;

/* CREATE OR ALTER VIEW: VWRH_AGRUPADADOSFOLAVUL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_AGRUPADADOSFOLAVUL(
BDCODEMP,
BDCODCOL,
BDCODVER,
BDREFV,
BDREFAUXV,
BDIGNREFV,
BDIGNVALV,
BDPROVENTO,
BDDESCONTO,
BDREF,
BDDATAFA,
BDCODTCA,
BDFGTS,
BDSALBASE,
BDDEP,
BDINSS,
BDIRRF,
BDTIPOCODVER,
BDORDEMTIPOCODVER,
BDINSSVER,
BDFGTSVER,
BDIRVER,
BDTIPOREFVER,
BDBASESFVER,
BDPISVER,
BDBASEHEVER,
BDBASEMAIORVER,
BDRAISVER,
BDBASEGPSVER,
BDDESCVER,
BDCLAVER,
BDREFHOREMP,
BDDATAPGTOFA)
 AS 
SELECT
  FAV.BDCODEMP,
  FAV.BDCODCOL,
  FAV.BDCODVER,
  FAV.BDREFVFA,
  FAV.BDREFAUXVFA,
  FAV.BDIGNREFVFA,
  FAV.BDIGNVALVFA,
  CASE WHEN (VREF.BDTIPOCODVER IN (0, 2)) THEN FAV.BDVALVFA
       ELSE 0 END BDPROVENTO,
  CASE WHEN (VREF.BDTIPOCODVER IN (0, 2)) THEN 0
       ELSE FAV.BDVALVFA END BDDESCONTO,
  FA.BDREF,
  FA.BDDATAFA,
  FA.BDCODTCA,
  FA.BDFGTSFA,
  FA.BDSALBASEFA,
  FA.BDDEPFA,
  FA.BDINSSFA,
  FA.BDIRRFFA,
  VREF.BDTIPOCODVER,
  VREF.BDORDEMTIPOCODVER,
  VREF.BDINSSVER,
  VREF.BDFGTSVER,
  VREF.BDIRVER,
  VREF.BDTIPOREFVER,
  VREF.BDBASESFVER,
  VREF.BDPISVER,
  VREF.BDBASEHEVER,
  VREF.BDBASEMAIORVER,
  VREF.BDRAISVER,
  VREF.BDBASEGPSVER,
  VERBAS.BDDESCVER,
  VERBAS.BDCLAVER,
  EMPC.BDREFHOREMP,
  FA.BDDATAPGTOFA
FROM
  VRHF_EMP_TVERBAFA FAV,
  VRHF_EMP_TFOLHAAVULSA FA,
  vw_tverbas_ref VREF,
  VRH_BASE_TVERBAS VERBAS,
  VW_VRHF_BASE_TEMPCALC EMPC

WHERE
  FAV.BDCODVER = VREF.BDCODVER
  AND FAV.BDCODEMP = FA.BDCODEMP AND FAV.BDCODCOL = FA.BDCODCOL AND FAV.BDDATAFA = FA.BDDATAFA AND FAV.BDCODTCA = FA.BDCODTCA
  AND FAV.BDCODVER = VERBAS.BDCODVER
  AND FA.BDCODEMP = EMPC.BDCODEMP
;

--Sol. 18845 - Bruno L. R. - Adicionado campo BDPERCGORJ
/* CREATE OR ALTER VIEW: VWRH_COL_CALCULO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_COL_CALCULO(
BDCODEMP,
BDCODCOL,
BDCODSINTRAB,
BDCODPLAFUC,
BDCODTFUC,
BDCODPQUA,
BDCODQH,
BDTIPOCOL,
BDHORASMENSAISCOL,
BDHORASSEMANAISCOL,
BDHORASDIARIASCOL,
BDPERCINSALUBCOL,
BDINCIDINSALUBCOL,
BDPERCPERCULCOL,
BDINCIDPERICULCOL,
BDPERCNOTURNOCOL,
BDINCIDNOTURNOCOL,
BDNRODEPSALFAMCOL,
BDIGNORAFALTASFERCOL,
BDCALCADIANTACOL,
BDNAOARREDONDARCOL,
BDIMPETIQUETACOL,
BDCALCDSRRVCOL,
BDCALCDSRHECOL,
BDCALCDSRSALCOL,
BDCALCVALTRANSCOL,
BDCALCVALREFCOL,
BDTIPOADMCOL,
BDNATUOCUPCOL,
BDDATAINIAQUICOL,
BDSALINICOL,
BDDIASPRAZO1COL,
BDDATAFIMPRAZO1COL,
BDDIASPRAZO2COL,
BDDATAFIMPRAZO2COL,
BDDESCCONTSINCOL,
BDVINCEMPCOL,
BDALVARACOL,
BDSINDICALIZADOCOL,
BDREGIMEPARCIALCOL,
BDDESCCONTASSCOL,
BDPERCADISAL,
BDPERCGORJ)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODSINTRAB,
  Y.BDCODPLAFUC,
  Y.BDCODTFUC,
  Y.BDCODPQUA,
  Y.BDCODQH,
  Z.BDTIPOCOL,
  Z.BDHORASMENSAISCOL,
  Z.BDHORASSEMANAISCOL,
  Z.BDHORASDIARIASCOL,
  Z.BDPERCINSALUBCOL,
  Z.BDINCIDINSALUBCOL,
  Z.BDPERCPERCULCOL,
  Z.BDINCIDPERICULCOL,
  Z.BDPERCNOTURNOCOL,
  Z.BDINCIDNOTURNOCOL,
  Z.BDNRODEPSALFAMCOL,
  Z.BDIGNORAFALTASFERCOL,
  Z.BDCALCADIANTACOL,
  Z.BDNAOARREDONDARCOL,
  Z.BDIMPETIQUETACOL,
  Z.BDCALCDSRRVCOL,
  Z.BDCALCDSRHECOL,
  Z.BDCALCDSRSALCOL,
  Z.BDCALCVALTRANSCOL,
  Z.BDCALCVALREFCOL,
  W.BDTIPOADMCOL,
  W.BDNATUOCUPCOL,
  W.BDDATAINIAQUICOL,
  W.BDSALINICOL,
  W.BDDIASPRAZO1COL,
  W.BDDATAFIMPRAZO1COL,
  W.BDDIASPRAZO2COL,
  W.BDDATAFIMPRAZO2COL,
  W.BDDESCCONTSINCOL,
  ADMREF.BDVINCEMPCOL,
  ADMREF.BDALVARACOL,
  ADMREF.BDSINDICALIZADOCOL,
  Z.BDREGIMEPARCIALCOL,
  W.BDDESCCONTASSCOL,
  Z.BDPERCADISAL,
  Z.BDPERCGORJ
FROM
  VW_VRH_EMP_TCOL_VINC X
JOIN VW_VRHF_EMP_TCOL_CALC Z ON (X.BDCODEMP = Z.BDCODEMP AND X.BDCODCOL = Z.BDCODCOL)
JOIN VW_VRH_EMP_TCOL_ADM W ON (X.BDCODEMP = W.BDCODEMP AND X.BDCODCOL = w.BDCODCOL)
JOIN VW_VRH_EMP_TCOL_ADMREF ADMREF ON (X.BDCODEMP = ADMREF.BDCODEMP AND X.BDCODCOL = ADMREF.BDCODCOL)
LEFT OUTER JOIN VW_VRH_EMP_TCOL_VINCDIA Y ON (X.BDCODEMP = Y.BDCODEMP AND X.BDCODCOL = Y.BDCODCOL)
;

/* CREATE OR ALTER VIEW: VWRH_COLCON_CALCULO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_COLCON_CALCULO(
BDCODEMP,
BDCODCOL,
BDNOMCOL,
BDCODCLA,
BDDATACOL,
BDCODMAS,
BDSALBASECOL,
BDFORMAPAGTOCOL,
BDNRODEPIRCOL,
BDBASEIRRFADCOL,
BDVALORPREVPRIVNCOL,
BDVALORPREVPRIV13COL,
BDDATAOPCAOFGTSCOL,
BDCTAFGTSCOL,
BDCATEGORIACOL,
BDPERCFGTSCOL,
BDOCORRENCIACOL,
BDPERCRATCOL,
BDPERCDESCFPASCOL,
BDSEXOCOL,
BDDATANASCCOL,
BDDATACADCOL,
BDDATAADMCOL,
BDDATAADICCOL,
BDESTCIVCOL,
BDGRAUINSTCOL,
BDCONTRCOL,
BDGRUPOCLA)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  COLCAD.bdnomcol,
  X.BDCODCLA,
  Y.BDDATACOL,
  Y.BDCODMAS,
  Y.BDSALBASECOL,
  Z.BDFORMAPAGTOCOL,
  Z.BDNRODEPIRCOL,
  Z.BDBASEIRRFADCOL,
  Z.BDVALORPREVPRIVNCOL,
  Z.BDVALORPREVPRIV13COL,
  W.BDDATAOPCAOFGTSCOL,
  W.BDCTAFGTSCOL,
  W.BDCATEGORIACOL,
  W.BDPERCFGTSCOL,
  W.BDOCORRENCIACOL,
  W.BDPERCRATCOL,
  W.BDPERCDESCFPASCOL,
  COLCAD.BDSEXOCOL,
  T.BDDATANASCCOL,
  T.BDDATACADCOL,
  T.BDDATAADMCOL,
  T.BDDATAADICCOL,
  COLCAD.BDESTCIVCOL,
  COLCAD.BDGRAUINSTCOL,
  T.BDCONTRCOL,
  R.BDGRUPOCLA
FROM VW_vrh_emp_tcolcon_vinc X
JOIN VW_VRH_EMP_TCOLCON_CALCDIA Y ON X.BDCODEMP = Y.BDCODEMP AND X.BDCODCOL = Y.BDCODCOL
JOIN VW_VRHF_EMP_TCOLCON_CALC Z ON X.BDCODEMP = Z.BDCODEMP AND X.BDCODCOL = Z.BDCODCOL
JOIN VW_VRHF_EMP_TCOLCON_FGTSGPS W ON X.BDCODEMP = W.BDCODEMP AND X.BDCODCOL = W.BDCODCOL
JOIN VRH_EMP_TCOLCON T ON X.BDCODEMP = T.BDCODEMP AND X.BDCODCOL = T.BDCODCOL
JOIN VRH_BASE_TCLASSE R ON X.BDCODCLA = R.BDCODCLA
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON COLCAD.BDCODEMP = X.BDCODEMP AND COLCAD.BDCODCOL = X.BDCODCOL
ORDER BY
  X.BDCODEMP, X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VWRH_DADOS_RDE (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_DADOS_RDE(
BDCODEMP,
BDCODRDE,
BDREFRDE,
BDCNPJEMP,
BDNOMEMP,
BDCODCID,
BDIDENTEMP,
BDCODUF)
 AS 
SELECT
  RDE.BDCODEMP,
  RDE.BDCODRDE,
  RDE.BDREFRDE,
  EMP.BDCNPJEMP,
  EMPR.BDNOMEMP,
  EMPR.BDCODCID,
  EMPSEF.BDIDENTEMP,
  EMPSEF.BDCODUF
FROM
  VRH_EMP_TRDE RDE,
  TEMPRESAS EMP,
  VW_TEMPRESAS_REF EMPR,
  VW_VRHF_BASE_TEMPSEFIP EMPSEF
WHERE
  RDE.BDCODEMP = EMP.BDCODEMP
  AND RDE.BDCODEMP = EMPR.BDCODEMP
  AND RDE.BDCODEMP = EMPSEF.BDCODEMP
;

/* CREATE OR ALTER VIEW: VWRH_DADOS_RDE_RELATORIO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_DADOS_RDE_RELATORIO(
BDCODEMP,
BDCODRDE,
BDREFRDE,
BDCNPJEMP,
BDNOMEMP,
BDIDENTEMP,
BDRAZAOSOCIALRDES2,
BDDATARECOLRDES3,
BDMODALIDADERDES3,
BDDEPOSITORDES3,
BDENCATRASORDES3,
BDTOTGRFRDES3,
BDIMPRIMERDES3,
BDCODFPASS31D,
BDINSCMATRIZRDES31D,
BDSIMPLESRDES31D,
BDCODRECRDES31D,
BDMODALIDADERDES31D,
BDINSCTOMADORRDES31D,
BDNUMPROCESSORDES31D,
BDNUMVARARDES31D,
BDPERINIRDES31D,
BDPERFIMRDES31D,
BDSOMA8RDES31D,
BDSOMA2RDES31D,
BDIMPRIMERDES31D,
BDCODFPASS31P,
BDINSCMATRIZRDES31P,
BDSIMPLESRDES31P,
BDCODRECRDES31P,
BDMODALIDADERDES31P,
BDINSCTOMADORRDES31P,
BDNUMPROCESSORDES31P,
BDNUMVARARDES31P,
BDPERINIRDES31P,
BDPERFIMRDES31P,
BDSOMA8RDES31P,
BDSOMA2RDES31P,
BDIMPRIMERDES31P,
BDSOMA8RDES4,
BDSOMA2RDES4,
BDIMPRIMERDES4,
BDAUSENCIAFATORDES5,
BDTOMADORINDEVRDES5,
BDINSCTOMADORS5,
BDSOMA8RDES5,
BDIMPRIMERDES5,
BDSIGLAUF,
BDNOMCID,
BDSIGLAUFEMP)
 AS 
SELECT
  RDE.BDCODEMP,
  RDE.BDCODRDE,
  RDE.BDREFRDE,
  RDE.BDCNPJEMP,
  RDE.BDNOMEMP,
  RDE.BDIDENTEMP,
  RDE_S2.BDRAZAOSOCIALRDES2,
  RDE_S3.BDDATARECOLRDES3,
  RDE_S3.BDMODALIDADERDES3,
  RDE_S3.BDDEPOSITORDES3,
  RDE_S3.BDENCATRASORDES3,
  RDE_S3.BDTOTGRFRDES3,
  RDE_S3.BDIMPRIMERDES3,
  RDE_S3D.BDCODFPASS31D,
  RDE_S3D.BDINSCMATRIZRDES31D,
  RDE_S3D.BDSIMPLESRDES31D,
  RDE_S3D.BDCODRECRDES31D,
  RDE_S3D.BDMODALIDADERDES31D,
  RDE_S3D.BDINSCTOMADORRDES31D,
  RDE_S3D.BDNUMPROCESSORDES31D,
  RDE_S3D.BDNUMVARARDES31D,
  RDE_S3D.BDPERINIRDES31D,
  RDE_S3D.BDPERFIMRDES31D,
  RDE_S3D.BDSOMA8RDES31D,
  RDE_S3D.BDSOMA2RDES31D,
  RDE_S3D.BDIMPRIMERDES31D,
  RDE_S3P.BDCODFPASS31P,
  RDE_S3P.BDINSCMATRIZRDES31P,
  RDE_S3P.BDSIMPLESRDES31P,
  RDE_S3P.BDCODRECRDES31P,
  RDE_S3P.BDMODALIDADERDES31P,
  RDE_S3P.BDINSCTOMADORRDES31P,
  RDE_S3P.BDNUMPROCESSORDES31P,
  RDE_S3P.BDNUMVARARDES31P,
  RDE_S3P.BDPERINIRDES31P,
  RDE_S3P.BDPERFIMRDES31P,
  RDE_S3P.BDSOMA8RDES31P,
  RDE_S3P.BDSOMA2RDES31P,
  RDE_S3P.BDIMPRIMERDES31P,
  RDE_S4.BDSOMA8RDES4,
  RDE_S4.BDSOMA2RDES4,
  RDE_S4.BDIMPRIMERDES4,
  COALESCE(RDE_S5.BDAUSENCIAFATORDES5, 'FALSE'),
  COALESCE(RDE_S5.BDTOMADORINDEVRDES5, 'FALSE'),
  RDE_S5.BDINSCTOMADORS5,
  RDE_S5.BDSOMA8RDES5,
  RDE_S5.BDIMPRIMERDES5,
  UF.BDSIGLAUF,
  CID.BDNOMCID,
  UFE.BDSIGLAUF
FROM
  VWRH_DADOS_RDE RDE
  LEFT OUTER JOIN VRH_EMP_TRDE_SECAO_2 RDE_S2
    ON (RDE.BDCODEMP = RDE_S2.BDCODEMP AND RDE.BDCODRDE = RDE_S2.BDCODRDE AND RDE_S2.BDIMPRIMERDES2 = 'TRUE')
  LEFT OUTER JOIN VRH_EMP_TRDE_SECAO_3 RDE_S3
    ON (RDE.BDCODEMP = RDE_S3.BDCODEMP AND RDE.BDCODRDE = RDE_S3.BDCODRDE AND RDE_S3.BDIMPRIMERDES3 = 'TRUE')
  LEFT OUTER JOIN VRH_EMP_TRDE_SECAO_31_DE RDE_S3D
    ON (RDE.BDCODEMP = RDE_S3D.BDCODEMP AND RDE.BDCODRDE = RDE_S3D.BDCODRDE AND RDE_S3D.BDIMPRIMERDES31D = 'TRUE')
  LEFT OUTER JOIN VRH_EMP_TRDE_SECAO_31_PARA RDE_S3P
    ON (RDE.BDCODEMP = RDE_S3P.BDCODEMP AND RDE.BDCODRDE = RDE_S3P.BDCODRDE AND RDE_S3P.BDIMPRIMERDES31P = 'TRUE')
  LEFT OUTER JOIN VRH_EMP_TRDE_SECAO_4 RDE_S4
    ON (RDE.BDCODEMP = RDE_S4.BDCODEMP AND RDE.BDCODRDE = RDE_S4.BDCODRDE AND RDE_S4.BDIMPRIMERDES4 = 'TRUE')
  LEFT OUTER JOIN VRH_EMP_TRDE_SECAO_5 RDE_S5
    ON (RDE.BDCODEMP = RDE_S5.BDCODEMP AND RDE.BDCODRDE = RDE_S5.BDCODRDE AND RDE_S5.BDIMPRIMERDES5 = 'TRUE')
  LEFT OUTER JOIN TUF UF
    ON (RDE.BDCODUF = UF.BDCODUF)
  LEFT OUTER JOIN TCIDADE CID
    ON (RDE.BDCODCID = CID.BDCODCID)
  LEFT OUTER JOIN TUF UFE
    ON (CID.BDCODUF = UFE.BDCODUF)
;

/* CREATE OR ALTER VIEW: VWRH_DADOS_RDT (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_DADOS_RDT(
BDCODEMP,
BDCODCOL,
BDCODRDT,
BDREFRDT,
BDCNPJEMP,
BDNOMEMP,
BDCODCID,
BDIDENTEMP,
BDCODUF,
BDNOMCOL,
BDDATAADMCOL,
BDPISCOL,
BDCATEGORIACOL,
BDCTAFGTSCOL,
BDSIGLAUFEMP)
 AS 
SELECT
  RDT.BDCODEMP,
  RDT.BDCODCOL,
  RDT.BDCODRDT,
  RDT.BDCOMPRDT,
  EMP.BDCNPJEMP,
  EMPR.BDNOMEMP,
  EMPR.BDCODCID,
  EMPSEF.BDIDENTEMP,
  EMPSEF.BDCODUF,
  COLCAD.BDNOMCOL,
  COLCON.BDDATAADMCOL,
  DOCREF.BDPISCOL,
  COLCONFGTS.BDCATEGORIACOL,
  COLCONFGTS.BDCTAFGTSCOL,
  UFEMP.BDSIGLAUF
FROM
  VRH_EMP_TRDT RDT
JOIN TEMPRESAS EMP ON (RDT.BDCODEMP = EMP.BDCODEMP)
JOIN VW_TEMPRESAS_REF EMPR ON (RDT.BDCODEMP = EMPR.BDCODEMP)
JOIN VW_VRHF_BASE_TEMPSEFIP EMPSEF ON (RDT.BDCODEMP = EMPSEF.BDCODEMP)
JOIN VRH_EMP_TCOLCON COLCON ON (RDT.BDCODEMP = COLCON.BDCODEMP AND RDT.BDCODCOL = COLCON.BDCODCOL)
JOIN VRH_EMP_TCOLCON_DOC COLCONDOC ON (RDT.BDCODEMP = COLCONDOC.BDCODEMP AND RDT.BDCODCOL = COLCONDOC.BDCODCOL)
JOIN VW_VRH_EMP_TCOLCON_DOCREF DOCREF ON (RDT.BDCODEMP = DOCREF.BDCODEMP AND RDT.BDCODCOL = DOCREF.BDCODCOL)
JOIN VW_VRHF_EMP_TCOLCON_FGTSGPS COLCONFGTS ON (RDT.BDCODEMP = COLCONFGTS.BDCODEMP AND RDT.BDCODCOL = COLCONFGTS.BDCODCOL)
LEFT OUTER JOIN TCIDADE CIDEMP ON (CIDEMP.BDCODCID = EMPR.BDCODCID)
LEFT OUTER JOIN TUF UFEMP ON (UFEMP.BDCODUF = CIDEMP.BDCODUF)
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON (COLCAD.BDCODEMP = RDT.BDCODEMP AND COLCAD.BDCODCOL = RDT.BDCODCOL)
;

/* CREATE OR ALTER VIEW: VWRH_DADOS_RDT_RELATORIO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_DADOS_RDT_RELATORIO(
BDCODEMP,
BDCODCOL,
BDCODRDT,
BDREFRDT,
BDCNPJEMP,
BDNOMEMP,
BDIDENTEMP,
BDNOMCOL,
BDDATAADMCOL,
BDPISCOL,
BDCATEGORIACOL,
BDCTAFGTSCOL,
BDCODCATEGORIA,
BDNOMERDTS3,
BDPISRDTS3,
BDCTPSRDTS3,
BDSERIERDTS3,
BDDSERIERDTS3,
BDDATAADMRDTS3,
BDDATAOPCAORDTS3,
BDDATARETRORDTS3,
BDDATANASCRDTS3,
BDIMPRIMERDTS3,
BDDATARDTS4,
BDIMPRIMES4,
BDCODRDTS5,
BDNOMERDTS5D,
BDNOMERDTS5P,
BDPISRDTS5D,
BDPISRDTS5P,
BDDATAADMRDTS5D,
BDDATAADMRDTS5P,
BDREMRDTS5D,
BDREMRDTS5P,
BDCODCATRDTS5D,
BDCODCATRDTS5P,
BDIMPRIMIRRDTS5,
BDUNIFICA01RDTS6,
BDUNIFICA02RDTS6,
BDUNIFICA03RDTS6,
BDIMPRIMIRRDTS6,
BDATU01RDTS7,
BDATU02RDTS7,
BDATU03RDTS7,
BDIMPRIMIRRDTS7,
BDSIGLAUF_EMP,
BDSIGLAUF_CTPS,
BDNOMCID,
BDCODSEFMFG,
BDSIGLAUF_CONTA)
 AS 
SELECT
  RDT.BDCODEMP,
  RDT.BDCODCOL,
  RDT.BDCODRDT,
  RDT.BDREFRDT,
  RDT.BDCNPJEMP,
  RDT.BDNOMEMP,
  RDT.BDIDENTEMP,
  RDT.BDNOMCOL,
  RDT.BDDATAADMCOL,
  RDT.BDPISCOL,
  RDT.BDCATEGORIACOL,
  RDT.BDCTAFGTSCOL,
  RDTS3.BDCODCATEGORIA,
  RDTS3.BDNOMERDTS3,
  RDTS3.BDPISRDTS3,
  RDTS3.BDCTPSRDTS3,
  RDTS3.BDSERIERDTS3,
  RDTS3.BDDSERIERDTS3,
  RDTS3.BDDATAADMRDTS3,
  RDTS3.BDDATAOPCAORDTS3,
  RDTS3.BDDATARETRORDTS3,
  RDTS3.BDDATANASCRDTS3,
  COALESCE(RDTS3.BDIMPRIMERDTS3, 'FALSE'),
  RDTS4.BDDATARDTS4,
  COALESCE(RDTS4.BDIMPRIMES4, 'FALSE'),
  RDTS5.BDCODRDTS5,
  RDTS5.BDNOMERDTS5D,
  RDTS5.BDNOMERDTS5P,
  RDTS5.BDPISRDTS5D,
  RDTS5.BDPISRDTS5P,
  RDTS5.BDDATAADMRDTS5D,
  RDTS5.BDDATAADMRDTS5P,
  RDTS5.BDREMRDTS5D,
  RDTS5.BDREMRDTS5P,
  RDTS5.BDCODCATRDTS5D,
  RDTS5.BDCODCATRDTS5P,
  COALESCE(RDTS5.BDIMPRIMIRRDTS5, 'FALSE'),
  RDTS6.BDUNIFICA01RDTS6,
  RDTS6.BDUNIFICA02RDTS6,
  RDTS6.BDUNIFICA03RDTS6,
  COALESCE(RDTS6.BDIMPRIMIRRDTS6, 'FALSE'),
  RDTS7.BDATU01RDTS7,
  RDTS7.BDATU02RDTS7,
  RDTS7.BDATU03RDTS7,
  COALESCE(RDTS7.BDIMPRIMIRRDTS7, 'FALSE'),
  RDT.BDSIGLAUFEMP BDSIGLAUF_EMP,
  UFCTPS.BDSIGLAUF BDSIGLAUF_CTPS,
  CID.BDNOMCID,
  MFGTS.BDCODSEFMFG,
  UFEMP.BDSIGLAUF BDSIGLAUF_CONTA
FROM
  VWRH_DADOS_RDT RDT
LEFT OUTER JOIN
  VRH_EMP_TRDT_SECAO_3 RDTS3 ON (RDTS3.BDCODEMP = RDT.BDCODEMP AND RDTS3.BDCODCOL = RDT.BDCODCOL AND RDTS3.BDCODRDT = RDT.BDCODRDT AND RDTS3.BDIMPRIMERDTS3 = 'TRUE')
LEFT OUTER JOIN
  VRH_EMP_TRDT_SECAO_4 RDTS4 ON (RDTS4.BDCODEMP = RDT.BDCODEMP AND RDTS4.BDCODCOL = RDT.BDCODCOL AND RDTS4.BDCODRDT = RDT.BDCODRDT AND RDTS4.BDIMPRIMES4 = 'TRUE')
LEFT OUTER JOIN
  VRH_EMP_TRDT_SECAO_5 RDTS5 ON (RDTS5.BDCODEMP = RDT.BDCODEMP AND RDTS5.BDCODCOL = RDT.BDCODCOL AND RDTS5.BDCODRDT = RDT.BDCODRDT AND RDTS5.BDIMPRIMIRRDTS5 = 'TRUE')
LEFT OUTER JOIN
  VRH_EMP_TRDT_SECAO_6 RDTS6 ON (RDTS6.BDCODEMP = RDT.BDCODEMP AND RDTS6.BDCODCOL = RDT.BDCODCOL AND RDTS6.BDCODRDT = RDT.BDCODRDT AND RDTS6.BDIMPRIMIRRDTS6 = 'TRUE')
LEFT OUTER JOIN
  VRH_EMP_TRDT_SECAO_7 RDTS7 ON (RDTS7.BDCODEMP = RDT.BDCODEMP AND RDTS7.BDCODCOL = RDT.BDCODCOL AND RDTS7.BDCODRDT = RDT.BDCODRDT AND RDTS7.BDIMPRIMIRRDTS7 = 'TRUE')
LEFT OUTER JOIN
  TUF UFEMP ON (UFEMP.BDCODUF = RDT.BDCODUF)
LEFT OUTER JOIN
  TUF UFCTPS ON (UFCTPS.BDCODUF = RDTS3.BDCODUF)
LEFT OUTER JOIN
  TCIDADE CID ON (RDT.BDCODCID = CID.BDCODCID)
LEFT OUTER JOIN
  VRH_BASE_TMOTFGTS MFGTS ON (MFGTS.BDCODMFG = RDTS4.BDCODMFG)
;

/* CREATE OR ALTER VIEW: VWRH_UNION_FN_FT_MES_BASES (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_UNION_FN_FT_MES_BASES(
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDCODCENTRO,
    BDCODTPCC,
    BDDATABAIXA,
    BDBFGTS,
    BDFGTS,
    BDFGTSCS,
    BDBFGTS13,
    BDFGTS13,
    BDFGTS13CS,
    BDMAIORREM,
    BDBINSS,
    BDALIQINSS,
    BDINSS,
    BDBIRRF,
    BDALIQIRRF,
    BDIRRF,
    BDBINSS13,
    BDALIQINSS13,
    BDINSS13,
    BDBIRRF13,
    BDALIQIRRF13,
    BDIRRF13,
    BDBSALFAM,
    BDSALFAM,
    BDBRAIS,
    BDSALBASE,
    BDDEP,
    BDBINSSFEFOL,
    BDINSSFEFOL,
    BDALIQINSSFEFOL,
    BDCREDITO,
    BDDEBITO,
    BDBFGTSFEFOL,
    BDFGTSFEFOL,
    BDBIRRFFE,
    BDIRRFFE,
    BDLIQUIDO,
    BDDATAPGTO,
    BDCODEMPREENDIMENTO)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  CAST(NULL AS INTEGER),
  CAST(NULL AS INTEGER),
  BDDATABAIXAFN,
  BDBFGTSFN,
  BDFGTSFN,
  BDFGTSCSFN,
  BDBFGTS13FN,
  BDFGTS13FN,
  BDFGTS13CSFN,
  BDMAIORREMFN,
  BDBINSSFN,
  BDALIQINSSFN,
  BDINSSFN,
  BDBIRRFFN,
  BDALIQIRRFFN,
  BDIRRFFN,
  BDBINSS13FN,
  BDALIQINSS13FN,
  BDINSS13FN,
  BDBIRRF13FN,
  BDALIQIRRF13FN,
  BDIRRF13FN,
  BDBSALFAMFN,
  BDSALFAMFN,
  BDBRAISFN,
  BDSALBASEFN,
  BDDEPFN,
  BDBINSSFEFOLFN,
  BDINSSFEFOLFN,
  BDALIQINSSFEFOLFN,
  BDCREDITOFN,
  BDDEBITOFN,
  BDBFGTSFEFN,
  BDFGTSFEFN,
  BDBIRRFFEFN,
  BDIRRFFEFN,
  BDLIQUIDO,
  BDDATAPGTOFN,
  null
FROM
  VRHF_EMP_TFOLHANORMAL

UNION

SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREFTOMADOR,
  MAX(Y.BDCODCENTRO),
  MAX(Y.BDCODTPCC),
  MAX(X.BDDATABAIXAFT),
  SUM(X.BDBFGTSFT),
  SUM(X.BDFGTSFT),
  SUM(X.BDFGTSCSFT),
  SUM(X.BDBFGTS13FT),
  SUM(X.BDFGTS13FT),
  SUM(X.BDFGTS13CSFT),
  MAX(X.BDMAIORREMFT),
  SUM(X.BDBINSSFT),
  MAX(X.BDALIQINSSFT),
  SUM(X.BDINSSFT),
  SUM(X.BDBIRRFFT),
  MAX(X.BDALIQIRRFFT),
  SUM(X.BDIRRFFT),
  SUM(X.BDBINSS13FT),
  MAX(X.BDALIQINSS13FT),
  SUM(X.BDINSS13FT),
  SUM(X.BDBIRRF13FT),
  MAX(X.BDALIQIRRF13FT),
  SUM(X.BDIRRF13FT),
  SUM(X.BDBSALFAMFT),
  SUM(X.BDSALFAMFT),
  SUM(X.BDBRAISFT),
  MAX(X.BDSALBASEFT),
  SUM(X.BDDEPFT),
  SUM(X.BDBINSSFEFOLFT),
  SUM(X.BDINSSFEFOLFT),
  MAX(X.BDALIQINSSFEFOLFT),
  SUM(X.BDCREDITOFT),
  SUM(X.BDDEBITOFT),
  SUM(X.BDBFGTSFEFT),
  SUM(X.BDFGTSFEFT),
  SUM(X.BDBIRRFFEFT),
  SUM(X.BDIRRFFEFT),
  SUM(X.bdliquido),
  MAX(X.BDDATAPGTOFT),
  MAX(Z.BDCODEMPREENDIMENTO)
FROM
  VRHF_EMP_TFOLHATOMADOR X
JOIN
  VRHF_EMP_TPREPFN Y on (Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDORDEM = X.BDORDEM)
LEFT OUTER JOIN
  VEF_EMP_TCADEMPREENDIMENTO Z on (Z.BDCODEMP = X.BDCODEMP and Z.BDCODCENTRO = Y.BDCODCENTRO and Z.BDCODTPCC = Y.BDCODTPCC)
GROUP BY
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREFTOMADOR
;

/* CREATE OR ALTER VIEW: VWRH_DADOS_REL_GRRF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_DADOS_REL_GRRF(
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDBFGTS,
    BDFGTS,
    BDFGTSCS,
    BDBFGTS13,
    BDFGTS13,
    BDFGTS13CS,
    BDBFGTSFEFOL,
    BDFGTSFEFOL,
    BDNOMCOL,
    BDDATANASCCOL,
    BDDATAADMCOL,
    BDPISCOL,
    BDCPFCOL,
    BDCATEGORIACOL,
    BDSALDOFGTS,
    BDDATARESCISAO,
    BDCALCFGTSMESANT,
    BDDATAAVPREVIO,
    BDAVPREPRES,
    BDMULTAPRES,
    BDMULTA10PRES,
    BDCODSEFMFG,
    BDDESCMFG,
    BDDESCCATEGORIA,
    BDPROJECAOAVISO,
    BDDIASINDENIZADOS,
    BDDIASTRABALHADOS,
    BDDATANOTIF,
    BDPERCMULTAFGTS,
    BDPERCMULTAFGTSCS)
AS
SELECT
  FOL.BDCODEMP,
  FOL.BDCODCOL,
  FOL.BDREFFN,
  COALESCE(FOL.BDBFGTS, 0.00),
  COALESCE(FOL.BDFGTS, 0.00),
  COALESCE(FOL.BDFGTSCS, 0.00),
  COALESCE(FOL.BDBFGTS13, 0.00),
  COALESCE(FOL.BDFGTS13, 0.00),
  COALESCE(FOL.BDFGTS13CS, 0.00),
  COALESCE(FOL.BDBFGTSFEFOL, 0.00),
  COALESCE(FOL.BDFGTSFEFOL, 0.00),
  COLCAD.BDNOMCOL,
  COL.BDDATANASCCOL,
  COL.BDDATAADMCOL,
  DOCREF.BDPISCOL,
  COLDOC.BDCPFCOL,
  COLFGTS.BDCATEGORIACOL,
  RESC.BDSALDOFGTS,
  RESC.BDDATARESCISAO,
  RESC.BDCALCFGTSMESANT,
  RESC.BDDATAAVPREVIO,
  PRES.BDAVPREPRES,
  PRES.BDMULTAPRES,
  PRES.BDMULTA10PRES,
  MFG.BDCODSEFMFG,
  MFG.BDDESCMFG,
  CAT.BDDESCCATEGORIA,
  RESC.BDPROJECAOAVISO,
  RESC.BDDIASINDENIZADOS,
  RESC.BDDIASTRABALHADOS,
  RESC.BDDATANOTIF,
  PRES.BDPERCMULTAFGTS,
  PRES.BDPERCMULTAFGTSCS
FROM
  (select BDCODEMP,BDCODCOL,BDREFFN,BDBFGTS,BDFGTS,BDFGTSCS,BDBFGTS13,BDFGTS13,BDFGTS13CS,BDBFGTSFEFOL,BDFGTSFEFOL
   from VWRH_UNION_FN_FT_MES_BASES
   union all
   select BDCODEMP,BDCODCOL,BDREFFN,SUM(BDBFGTS),SUM(BDFGTS),SUM(BDFGTSCS),SUM(BDBFGTS13),SUM(BDFGTS13),SUM(BDFGTS13CS),SUM(BDBFGTSFEFOL),SUM(BDFGTSFEFOL)
   from VWRH_UNION_FI_FTI_MES_BASES
   group by BDCODEMP,BDCODCOL,BDREFFN
   ) FOL
JOIN VRH_EMP_TCOLCON COL ON FOL.BDCODEMP = COL.BDCODEMP AND FOL.BDCODCOL = COL.BDCODCOL
JOIN VRH_EMP_TRESCISAO RESC ON FOL.BDCODEMP = RESC.BDCODEMP AND FOL.BDCODCOL = RESC.BDCODCOL AND FOL.BDREFFN = RESC.BDREFRESCISAO
JOIN VRH_BASE_TPREPRESC PRES ON RESC.BDCODPRES = PRES.BDCODPRES
JOIN VRH_BASE_TMOTFGTS MFG ON PRES.BDCODMFG = MFG.BDCODMFG
LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC COLDOC ON FOL.BDCODEMP = COLDOC.BDCODEMP AND FOL.BDCODCOL = COLDOC.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF DOCREF ON FOL.BDCODEMP = DOCREF.BDCODEMP AND FOL.BDCODCOL = DOCREF.BDCODCOL
LEFT OUTER JOIN VW_VRHF_EMP_TCOLCON_FGTSGPS COLFGTS ON FOL.BDCODEMP = COLFGTS.BDCODEMP AND FOL.BDCODCOL = COLFGTS.BDCODCOL
LEFT OUTER JOIN VRH_BASE_TCATEGORIA CAT ON CAT.BDCODCATEGORIA = COLFGTS.BDCATEGORIACOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON COLCAD.BDCODEMP = FOL.BDCODEMP AND COLCAD.BDCODCOL = FOL.BDCODCOL
;


/* CREATE OR ALTER VIEW: VWRH_UNION_FI_FTI_MES_BASES (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_UNION_FI_FTI_MES_BASES(
    BDCODEMP,
    BDCODCOL,
    BDCODCONTTI,
    BDREFFN,
    BDCODCENTRO,
    BDCODTPCC,
    BDDATABAIXA,
    BDBFGTS,
    BDFGTS,
    BDFGTSCS,
    BDBFGTS13,
    BDFGTS13,
    BDFGTS13CS,
    BDMAIORREM,
    BDBINSS,
    BDALIQINSS,
    BDINSS,
    BDBIRRF,
    BDALIQIRRF,
    BDIRRF,
    BDBINSS13,
    BDALIQINSS13,
    BDINSS13,
    BDBIRRF13,
    BDALIQIRRF13,
    BDIRRF13,
    BDBSALFAM,
    BDSALFAM,
    BDBRAIS,
    BDSALBASE,
    BDDEP,
    BDBINSSFEFOL,
    BDINSSFEFOL,
    BDALIQINSSFEFOL,
    BDCREDITO,
    BDDEBITO,
    BDBFGTSFEFOL,
    BDFGTSFEFOL,
    BDBIRRFFE,
    BDIRRFFE,
    BDLIQUIDO,
    BDDATAPGTO)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDCODCONTTI,
  BDREFFN,
  CAST(NULL AS INTEGER),
  CAST(NULL AS INTEGER),
  MAX(BDDATABAIXAFN) BDDATABAIXAFN,
  SUM(BDBFGTSFN) BDBFGTSFN,
  SUM(BDFGTSFN) BDFGTSFN,
  SUM(BDFGTSCSFN) BDFGTSCSFN,
  SUM(BDBFGTS13FN) BDBFGTS13FN,
  SUM(BDFGTS13FN) BDFGTS13FN,
  SUM(BDFGTS13CSFN) BDFGTS13CSFN,
  SUM(BDMAIORREMFN) BDMAIORREMFN,
  SUM(BDBINSSFN) BDBINSSFN,
  MAX(BDALIQINSSFN) BDALIQINSSFN,
  SUM(BDINSSFN) BDINSSFN,
  SUM(BDBIRRFFN) BDBIRRFFN,
  MAX(BDALIQIRRFFN) BDALIQIRRFFN,
  SUM(BDIRRFFN) BDIRRFFN,
  SUM(BDBINSS13FN) BDBINSS13FN,
  MAX(BDALIQINSS13FN) BDALIQINSS13FN,
  SUM(BDINSS13FN) BDINSS13FN,
  SUM(BDBIRRF13FN) BDBIRRF13FN,
  MAX(BDALIQIRRF13FN) BDALIQIRRF13FN,
  SUM(BDIRRF13FN) BDIRRF13FN,
  SUM(BDBSALFAMFN) BDBSALFAMFN,
  SUM(BDSALFAMFN) BDSALFAMFN,
  SUM(BDBRAISFN) BDBRAISFN,
  MAX(BDSALBASEFN) BDSALBASEFN,
  MAX(BDDEPFN) BDDEPFN,
  SUM(BDBINSSFEFOLFN) BDBINSSFEFOLFN,
  SUM(BDINSSFEFOLFN) BDINSSFEFOLFN,
  MAX(BDALIQINSSFEFOLFN) BDALIQINSSFEFOLFN,
  SUM(BDCREDITOFN) BDCREDITOFN,
  SUM(BDDEBITOFN) BDDEBITOFN,
  SUM(BDBFGTSFEFN) BDBFGTSFEFN,
  SUM(BDFGTSFEFN) BDFGTSFEFN,
  SUM(BDBIRRFFEFN) BDBIRRFFEFN,
  SUM(BDIRRFFEFN) BDIRRFFEFN,
  SUM(BDLIQUIDO) BDLIQUIDO,
  MAX(BDDATAPGTOFN) BDDATAPGTOFN
FROM
  VRHF_EMP_TFOLHAINT
GROUP BY BDCODEMP,BDCODCOL,BDCODCONTTI,BDREFFN

UNION

SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODCONTTI,
  X.BDREFTOMADOR,
  MAX(Y.BDCODCENTRO),
  MAX(Y.BDCODTPCC),
  MAX(X.BDDATABAIXAFT),
  SUM(X.BDBFGTSFT),
  SUM(X.BDFGTSFT),
  SUM(X.BDFGTSCSFT),
  SUM(X.BDBFGTS13FT),
  SUM(X.BDFGTS13FT),
  SUM(X.BDFGTS13CSFT),
  MAX(X.BDMAIORREMFT),
  SUM(X.BDBINSSFT),
  MAX(X.BDALIQINSSFT),
  SUM(X.BDINSSFT),
  SUM(X.BDBIRRFFT),
  MAX(X.BDALIQIRRFFT),
  SUM(X.BDIRRFFT),
  SUM(X.BDBINSS13FT),
  MAX(X.BDALIQINSS13FT),
  SUM(X.BDINSS13FT),
  SUM(X.BDBIRRF13FT),
  MAX(X.BDALIQIRRF13FT),
  SUM(X.BDIRRF13FT),
  SUM(X.BDBSALFAMFT),
  SUM(X.BDSALFAMFT),
  SUM(X.BDBRAISFT),
  MAX(X.BDSALBASEFT),
  SUM(X.BDDEPFT),
  SUM(X.BDBINSSFEFOLFT),
  SUM(X.BDINSSFEFOLFT),
  MAX(X.BDALIQINSSFEFOLFT),
  SUM(X.BDCREDITOFT),
  SUM(X.BDDEBITOFT),
  SUM(X.BDBFGTSFEFT),
  SUM(X.BDFGTSFEFT),
  SUM(X.BDBIRRFFEFT),
  SUM(X.BDIRRFFEFT),
  SUM(X.bdliquido),
  MAX(X.BDDATAPGTOFT)
FROM
  VRHF_EMP_TFOLHATOMINT X,
  VRHF_EMP_TPREPFN Y
WHERE X.BDCODEMP = Y.BDCODEMP AND X.BDCODCOL = Y.BDCODCOL AND X.BDORDEM = Y.BDORDEM
GROUP BY
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODCONTTI,
  X.BDREFTOMADOR
;

/* View: VWRH_UNION_FC_FCT_MESFN_BASES */
CREATE OR ALTER VIEW VWRH_UNION_FC_FCT_MESFN_BASES(
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDREFFC,
    BDDATAGRRFFC,
    BDCODCENTRO,
    BDCODTPCC,
    BDDATABAIXA,
    BDBFGTS,
    BDFGTS,
    BDFGTSCS,
    BDBFGTS13,
    BDFGTS13,
    BDFGTS13CS,
    BDMAIORREM,
    BDBINSS,
    BDALIQINSS,
    BDINSS,
    BDBIRRF,
    BDALIQIRRF,
    BDIRRF,
    BDBINSS13,
    BDALIQINSS13,
    BDINSS13,
    BDBIRRF13,
    BDALIQIRRF13,
    BDIRRF13,
    BDBSALFAM,
    BDSALFAM,
    BDBRAIS,
    BDSALBASE,
    BDDEP,
    BDBINSSFEFOL,
    BDINSSFEFOL,
    BDALIQINSSFEFOL,
    BDCREDITO,
    BDDEBITO,
    BDBFGTSFEFOL,
    BDFGTSFEFOL,
    BDCODTIPOFC,
    BDBIRRFFE,
    BDIRRFFE,
    BDLIQUIDO,
    BDBIRRFFEFOL,
    BDIRRFFEFOL,
    BDCODACCONV,
    BDREFVINCFN,
    BDVERCALCRRA,
    BDTIPODEDUCAOFOLHA,
    BDVALORDESCONTOSIMPLIFICADO,
    BDBIRCOMOUTRASBASES,
    BDREFFNINI,
    BDREFFNFIM,
    BDBASEIRBRUTARED,
    BDBASEIR13BRUTARED,
    BDVALORIRBRUTARED,
    BDVALORIR13BRUTARED,
    BDVALORRED,
    BDVALOR13RED)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDREFFC,
  BDDATAGRRFFC,
  MAX(CAST(NULL AS INTEGER)),
  MAX(CAST(NULL AS INTEGER)),
  MAX(BDDATABAIXAFC),
  SUM(BDBFGTSFC),
  SUM(BDFGTSFC),
  SUM(BDFGTSCSFC),
  SUM(BDBFGTS13FC),
  SUM(BDFGTS13FC),
  SUM(BDFGTS13CSFC),
  MAX(BDMAIORREMFC),
  SUM(BDBINSSFC),
  MAX(BDALIQINSSFC),
  SUM(BDINSSFC),
  SUM(BDBIRRFFC),
  MAX(BDALIQIRRFFC),
  SUM(BDIRRFFC),
  SUM(BDBINSS13FC),
  MAX(BDALIQINSS13FC),
  SUM(BDINSS13FC),
  SUM(BDBIRRF13FC),
  MAX(BDALIQIRRF13FC),
  SUM(BDIRRF13FC),
  SUM(BDBSALFAMFC),
  SUM(BDSALFAMFC),
  SUM(BDBRAISFC),
  MAX(BDSALBASEFC),
  MAX(BDDEPFC),
  SUM(BDBINSSFEFOLFC),
  SUM(BDINSSFEFOLFC),
  MAX(BDALIQINSSFEFOLFC),
  SUM(BDCREDITOFC),
  SUM(BDDEBITOFC),
  SUM(BDBFGTSFEFC),
  SUM(BDFGTSFEFC),
  COALESCE(MAX(BDCODTIPOFC),1),
  SUM(BDBIRRFFEFC),
  SUM(BDIRRFFEFC),
  SUM(BDLIQUIDO),
  SUM(BDBIRRFFEFC),
  SUM(BDIRRFFEFC),
  MAX(BDCODACCONV),
  MAX(BDREFVINCFN),
  BDVERCALCRRA,
  MAX(bdtipodeducaofolha),
  MAX(BDVALORDESCONTOSIMPLIFICADO),
  SUM(BDBIRCOMOUTRASBASES),
  max(BDREFFNINI) BDREFFNINI,
  max(BDREFFNFIM) BDREFFNFIM,
  max(BDBASEIRBRUTARED),
  max(BDBASEIR13BRUTARED),
  max(BDVALORIRBRUTARED),
  max(BDVALORIR13BRUTARED),
  max(BDVALORRED),
  max(BDVALOR13RED)
FROM
  VRHF_EMP_TFOLHACOMP

GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDREFFC,
  BDDATAGRRFFC,
  BDVERCALCRRA

UNION ALL

SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREFTOMADOR,
  X.bdreffc, 
  X.bddatagrrffc,
  MAX(Y.BDCODCENTRO),
  MAX(Y.BDCODTPCC),
  MAX(X.BDDATABAIXAFC),
  SUM(X.BDBFGTSFC),
  SUM(X.BDFGTSFC),
  SUM(X.BDFGTSCSFC),
  SUM(X.BDBFGTS13FC),
  SUM(X.BDFGTS13FC),
  SUM(X.BDFGTS13CSFC),
  MAX(X.BDMAIORREMFC),
  SUM(X.BDBINSSFC),
  MAX(X.BDALIQINSSFC),
  SUM(X.BDINSSFC),
  SUM(X.BDBIRRFFC),
  MAX(X.BDALIQIRRFFC),
  SUM(X.BDIRRFFC),
  SUM(X.BDBINSS13FC),
  MAX(X.BDALIQINSS13FC),
  SUM(X.BDINSS13FC),
  SUM(X.BDBIRRF13FC),
  MAX(X.BDALIQIRRF13FC),
  SUM(X.BDIRRF13FC),
  SUM(X.BDBSALFAMFC),
  SUM(X.BDSALFAMFC),
  SUM(X.BDBRAISFC),
  MAX(X.BDSALBASEFC),
  MAX(X.BDDEPFC),
  SUM(X.BDBINSSFEFOLFC),
  SUM(X.BDINSSFEFOLFC),
  MAX(X.BDALIQINSSFEFOLFC),
  SUM(X.BDCREDITOFC),
  SUM(X.BDDEBITOFC),
  SUM(X.BDBFGTSFEFC),
  SUM(X.BDFGTSFEFC),
  COALESCE(MAX(X.BDCODTIPOFC),1),
  SUM(X.BDBIRRFFEFC),
  SUM(X.BDIRRFFEFC),
  SUM(X.BDLIQUIDO),
  SUM(X.BDBIRRFFEFC),
  SUM(X.BDIRRFFEFC),
  MAX(BDCODACCONV),
  MAX(BDREFVINCFN),
  BDVERCALCRRA,
  MAX(bdtipodeducaofolha),
  MAX(BDVALORDESCONTOSIMPLIFICADO),
  MAX(BDBIRCOMOUTRASBASES),
  max(X.BDREFFNINI) BDREFFNINI,
  max(X.BDREFFNFIM) BDREFFNFIM,
  max(X.BDBASEIRBRUTARED),
  max(X.BDBASEIR13BRUTARED),
  max(X.BDVALORIRBRUTARED),
  max(X.BDVALORIR13BRUTARED),
  max(X.BDVALORRED),
  max(X.BDVALOR13RED)
FROM
  VRHF_EMP_TFOLTOMCOMP X,
  VRHF_EMP_TPREPFN Y
WHERE
  X.BDCODEMP = Y.BDCODEMP AND X.BDCODCOL = Y.BDCODCOL AND X.BDORDEM = Y.BDORDEM
GROUP BY
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREFTOMADOR,
  X.BDREFFC,
  X.BDDATAGRRFFC,
  BDVERCALCRRA
;

/* View: VWRH_UNION_FCI_FCTI_MESFN_BASES */
CREATE OR ALTER VIEW VWRH_UNION_FCI_FCTI_MESFN_BASES(
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDREFFC,
    BDCODCONTTI,
    BDDATAGRRFFC,
    BDCODCENTRO,
    BDCODTPCC,
    BDDATABAIXA,
    BDBFGTS,
    BDFGTS,
    BDFGTSCS,
    BDBFGTS13,
    BDFGTS13,
    BDFGTS13CS,
    BDMAIORREM,
    BDBINSS,
    BDALIQINSS,
    BDINSS,
    BDBIRRF,
    BDALIQIRRF,
    BDIRRF,
    BDBINSS13,
    BDALIQINSS13,
    BDINSS13,
    BDBIRRF13,
    BDALIQIRRF13,
    BDIRRF13,
    BDBSALFAM,
    BDSALFAM,
    BDBRAIS,
    BDSALBASE,
    BDDEP,
    BDBINSSFEFOL,
    BDINSSFEFOL,
    BDALIQINSSFEFOL,
    BDCREDITO,
    BDDEBITO,
    BDBFGTSFEFOL,
    BDFGTSFEFOL,
    BDCODTIPOFC,
    BDBIRRFFE,
    BDIRRFFE,
    BDLIQUIDO,
    BDBIRRFFEFOL,
    BDIRRFFEFOL,
    BDCODACCONV,
    BDDATAPAGFC,
    BDBASEIRBRUTARED,
    BDBASEIR13BRUTARED,
    BDVALORIRBRUTARED,
    BDVALORIR13BRUTARED,
    BDVALORRED,
    BDVALOR13RED)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDREFFC,
  BDCODCONTTI,
  BDDATAGRRFFC,
  MAX(CAST(NULL AS INTEGER)),
  MAX(CAST(NULL AS INTEGER)),
  MAX(BDDATABAIXAFC),
  SUM(BDBFGTSFC),
  SUM(BDFGTSFC),
  SUM(BDFGTSCSFC),
  SUM(BDBFGTS13FC),
  SUM(BDFGTS13FC),
  SUM(BDFGTS13CSFC),
  MAX(BDMAIORREMFC),
  SUM(BDBINSSFC),
  MAX(BDALIQINSSFC),
  SUM(BDINSSFC),
  SUM(BDBIRRFFC),
  MAX(BDALIQIRRFFC),
  SUM(BDIRRFFC),
  SUM(BDBINSS13FC),
  MAX(BDALIQINSS13FC),
  SUM(BDINSS13FC),
  SUM(BDBIRRF13FC),
  MAX(BDALIQIRRF13FC),
  SUM(BDIRRF13FC),
  SUM(BDBSALFAMFC),
  SUM(BDSALFAMFC),
  SUM(BDBRAISFC),
  MAX(BDSALBASEFC),
  MAX(BDDEPFC),
  SUM(BDBINSSFEFOLFC),
  SUM(BDINSSFEFOLFC),
  MAX(BDALIQINSSFEFOLFC),
  SUM(BDCREDITOFC),
  SUM(BDDEBITOFC),
  SUM(BDBFGTSFEFC),
  SUM(BDFGTSFEFC),
  COALESCE(MAX(BDCODTIPOFC),1),
  SUM(BDBIRRFFEFC),
  SUM(BDIRRFFEFC),
  SUM(BDLIQUIDO),
  SUM(BDBIRRFFEFC),
  SUM(BDIRRFFEFC),
  MAX(BDCODACCONV),
  BDDATAPAGFC,
  MAX(BDBASEIRBRUTARED),
  MAX(BDBASEIR13BRUTARED),
  MAX(BDVALORIRBRUTARED),
  MAX(BDVALORIR13BRUTARED),
  MAX(BDVALORRED),
  MAX(BDVALOR13RED)
FROM
  VRHF_EMP_TFOLHACOMPINT

GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDREFFC,
  BDCODCONTTI,
  BDDATAGRRFFC,
  BDDATAPAGFC

UNION ALL

SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREFTOMADOR,
  X.bdreffc, 
  X.BDCODCONTTI,
  X.bddatagrrffc,
  MAX(Y.BDCODCENTRO),
  MAX(Y.BDCODTPCC),
  MAX(X.BDDATABAIXAFC),
  SUM(X.BDBFGTSFC),
  SUM(X.BDFGTSFC),
  SUM(X.BDFGTSCSFC),
  SUM(X.BDBFGTS13FC),
  SUM(X.BDFGTS13FC),
  SUM(X.BDFGTS13CSFC),
  MAX(X.BDMAIORREMFC),
  SUM(X.BDBINSSFC),
  MAX(X.BDALIQINSSFC),
  SUM(X.BDINSSFC),
  SUM(X.BDBIRRFFC),
  MAX(X.BDALIQIRRFFC),
  SUM(X.BDIRRFFC),
  SUM(X.BDBINSS13FC),
  MAX(X.BDALIQINSS13FC),
  SUM(X.BDINSS13FC),
  SUM(X.BDBIRRF13FC),
  MAX(X.BDALIQIRRF13FC),
  SUM(X.BDIRRF13FC),
  SUM(X.BDBSALFAMFC),
  SUM(X.BDSALFAMFC),
  SUM(X.BDBRAISFC),
  MAX(X.BDSALBASEFC),
  MAX(X.BDDEPFC),
  SUM(X.BDBINSSFEFOLFC),
  SUM(X.BDINSSFEFOLFC),
  MAX(X.BDALIQINSSFEFOLFC),
  SUM(X.BDCREDITOFC),
  SUM(X.BDDEBITOFC),
  SUM(X.BDBFGTSFEFC),
  SUM(X.BDFGTSFEFC),
  COALESCE(MAX(X.BDCODTIPOFC),1),
  SUM(X.BDBIRRFFEFC),
  SUM(X.BDIRRFFEFC),
  SUM(X.BDLIQUIDO),
  SUM(X.BDBIRRFFEFC),
  SUM(X.BDIRRFFEFC),
  MAX(X.BDCODACCONV),
  X.BDDATAPAGFC,
  MAX(X.BDBASEIRBRUTARED),
  MAX(X.BDBASEIR13BRUTARED),
  MAX(X.BDVALORIRBRUTARED),
  MAX(X.BDVALORIR13BRUTARED),
  MAX(X.BDVALORRED),
  MAX(X.BDVALOR13RED)
FROM VRHF_EMP_TFOLTOMCOMPINT X
JOIN VRHF_EMP_TPREPFN Y on (X.BDCODEMP = Y.BDCODEMP AND X.BDCODCOL = Y.BDCODCOL AND X.BDORDEM = Y.BDORDEM)
GROUP BY
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREFTOMADOR,
  X.BDREFFC,
  X.BDCODCONTTI,
  X.BDDATAGRRFFC,
  X.BDDATAPAGFC
;


/* CREATE OR ALTER VIEW: VWRH_DADOS_REL_GRRF_FC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_DADOS_REL_GRRF_FC(
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDBFGTS,
    BDFGTS,
    BDFGTSCS,
    BDBFGTS13,
    BDFGTS13,
    BDFGTS13CS,
    BDBFGTSFEFOL,
    BDFGTSFEFOL,
    BDNOMCOL,
    BDDATANASCCOL,
    BDDATAADMCOL,
    BDPISCOL,
    BDCPFCOL,
    BDCATEGORIACOL,
    BDSALDOFGTS,
    BDDATARESCISAO,
    BDCALCFGTSMESANT,
    BDDATAAVPREVIO,
    BDDIASINDENIZADOS,
    BDDIASTRABALHADOS,
    BDPROJECAOAVISO,
    BDDATANOTIF,
    BDAVPREPRES,
    BDMULTAPRES,
    BDMULTA10PRES,
    BDCODSEFMFG,
    BDDESCMFG,
    BDDESCCATEGORIA,
    BDREFFC,
    BDCODTIPOFC,
    BDDATAGRRFFC,
    BDPERCMULTAFGTS,
    BDPERCMULTAFGTSCS)
AS
SELECT
  FOL.BDCODEMP,
  FOL.BDCODCOL,
  FOL.BDREFFN,
  COALESCE(FOL.BDBFGTS, 0.00),
  COALESCE(FOL.BDFGTS, 0.00),
  COALESCE(FOL.BDFGTSCS, 0.00),
  COALESCE(FOL.BDBFGTS13, 0.00),
  COALESCE(FOL.BDFGTS13, 0.00),
  COALESCE(FOL.BDFGTS13CS, 0.00),
  COALESCE(FOL.BDBFGTSFEFOL, 0.00),
  COALESCE(FOL.BDFGTSFEFOL, 0.00),
  COLCAD.BDNOMCOL,
  COL.BDDATANASCCOL,
  COL.BDDATAADMCOL,
  DOCREF.BDPISCOL,
  COLDOC.BDCPFCOL,
  COLFGTS.BDCATEGORIACOL,
  RESC.BDSALDOFGTS,
  RESC.BDDATARESCISAO,
  RESC.BDCALCFGTSMESANT,
  RESC.BDDATAAVPREVIO,
  RESC.BDDIASINDENIZADOS,
  RESC.BDDIASTRABALHADOS,
  RESC.BDPROJECAOAVISO,
  RESC.BDDATANOTIF,
  PRES.BDAVPREPRES,
  PRES.BDMULTAPRES,
  PRES.BDMULTA10PRES,
  MFG.BDCODSEFMFG,
  MFG.BDDESCMFG,
  CAT.BDDESCCATEGORIA,
  FOL.BDREFFC,
  FOL.BDCODTIPOFC,
  FOL.BDDATAGRRFFC,
  PRES.BDPERCMULTAFGTS,
  PRES.BDPERCMULTAFGTSCS
FROM (
  select BDCODEMP,BDCODCOL,BDREFFN,BDBFGTS,BDFGTS,BDFGTSCS,BDBFGTS13,BDFGTS13,BDFGTS13CS,BDBFGTSFEFOL,BDFGTSFEFOL,BDREFFC,BDCODTIPOFC,BDDATAGRRFFC
  from VWRH_UNION_FC_FCT_MESFN_BASES
  union all
  select BDCODEMP,BDCODCOL,BDREFFN,BDBFGTS,BDFGTS,BDFGTSCS,BDBFGTS13,BDFGTS13,BDFGTS13CS,BDBFGTSFEFOL,BDFGTSFEFOL,BDREFFC,BDCODTIPOFC,BDDATAGRRFFC
  from VWRH_UNION_FCI_FCTI_MESFN_BASES) FOL
JOIN VRH_EMP_TCOLCON COL ON FOL.BDCODEMP = COL.BDCODEMP AND FOL.BDCODCOL = COL.BDCODCOL
JOIN VRH_EMP_TRESCISAO RESC ON FOL.BDCODEMP = RESC.BDCODEMP AND FOL.BDCODCOL = RESC.BDCODCOL AND ((FOL.BDREFFN = RESC.BDREFRESCISAO) OR (FOL.BDREFFN = RESC.BDREFPROJECAOAVISO))
JOIN VRH_BASE_TPREPRESC PRES ON RESC.BDCODPRES = PRES.BDCODPRES
JOIN VRH_BASE_TMOTFGTS MFG ON PRES.BDCODMFG = MFG.BDCODMFG
LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC COLDOC ON FOL.BDCODEMP = COLDOC.BDCODEMP AND FOL.BDCODCOL = COLDOC.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF DOCREF ON FOL.BDCODEMP = DOCREF.BDCODEMP AND FOL.BDCODCOL = DOCREF.BDCODCOL
LEFT OUTER JOIN VW_VRHF_EMP_TCOLCON_FGTSGPS COLFGTS ON FOL.BDCODEMP = COLFGTS.BDCODEMP AND FOL.BDCODCOL = COLFGTS.BDCODCOL
LEFT OUTER JOIN VRH_BASE_TCATEGORIA CAT ON CAT.BDCODCATEGORIA = COLFGTS.BDCATEGORIACOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON COLCAD.BDCODEMP = FOL.BDCODEMP AND COLCAD.BDCODCOL = FOL.BDCODCOL
;

/* View: VWRH_UNION_FNPR_FTPR_MES_BASES */
CREATE OR ALTER VIEW VWRH_UNION_FNPR_FTPR_MES_BASES(
    BDCODEMP,
    BDCODCOL,
    BDCODCENTRO,
    BDCODTPCC,
    BDDATABAIXA,
    BDBFGTS,
    BDFGTS,
    BDFGTSCS,
    BDBFGTS13,
    BDFGTS13,
    BDFGTS13CS,
    BDMAIORREM,
    BDBINSS,
    BDALIQINSS,
    BDINSS,
    BDBIRRF,
    BDALIQIRRF,
    BDIRRF,
    BDBINSS13,
    BDALIQINSS13,
    BDINSS13,
    BDBIRRF13,
    BDALIQIRRF13,
    BDIRRF13,
    BDBSALFAM,
    BDSALFAM,
    BDBRAIS,
    BDSALBASE,
    BDDEP,
    BDBINSSFEFOL,
    BDINSSFEFOL,
    BDALIQINSSFEFOL,
    BDCREDITO,
    BDDEBITO,
    BDBFGTSFEFOL,
    BDFGTSFEFOL,
    BDBIRRFFE,
    BDIRRFFE,
    BDREFFN,
    BDBINSSAPFNPR,
    BDINSSAPFNPR,
    BDBINSS13APFNPR,
    BDINSS13APFNPR,
    BDBASEFGTSMESESOCIAL,
    BDVALORFGTSMESESOCIAL,
    BDBASEFGTS13ESOCIAL,
    BDVALORFGTS13ESOCIAL,
    BDBASEFGTSINDESOCIAL,
    BDVALORFGTSINDESOCIAL,
    BDBASEIRBRUTARED,
    BDBASEIR13BRUTARED,
    BDVALORIRBRUTARED,
    BDVALORIR13BRUTARED,
    BDVALORRED,
    BDVALOR13RED)
AS
SELECT
  BPR.BDCODEMP,
  BPR.BDCODCOL,
  CAST(NULL AS INTEGER),
  CAST(NULL AS INTEGER),
  BPR.BDDATABAIXAFNPR,
  BPR.BDBFGTSFNPR,
  BPR.BDFGTSFNPR,
  BPR.BDFGTSCSFNPR,
  BPR.BDBFGTS13FNPR,
  BPR.BDFGTS13FNPR,
  BPR.BDFGTS13CSFNPR,
  BPR.BDMAIORREMFNPR,

  BPR.BDBINSSFNPR,
  BPR.BDALIQINSSFNPR,
  BPR.BDINSSFNPR,
  BPR.BDBIRRFFNPR,
  BPR.BDALIQIRRFFNPR,
  BPR.BDIRRFFNPR,

  BPR.BDBINSS13FNPR,
  BPR.BDALIQINSS13FNPR,
  BPR.BDINSS13FNPR,
  BPR.BDBIRRF13FNPR,
  BPR.BDALIQIRRF13FNPR,
  BPR.BDIRRF13FNPR,
  BPR.BDBSALFAMFNPR,
  BPR.BDSALFAMFNPR,
  BPR.BDBRAISFNPR,
  BPR.BDSALBASEFNPR,
  BPR.BDDEPFNPR,
  BPR.BDBINSSFEFOLFNPR,
  BPR.BDINSSFEFOLFNPR,
  BPR.BDALIQINSSFEFOLFNPR,
  CAST(0 AS NUMERIC(18,6)),
  CAST(0 AS NUMERIC(18,6)),
  BPR.BDBFGTSFEFN,
  BPR.BDFGTSFEFN,
  BPR.BDBIRRFFEFNPR,
  BPR.BDIRRFFEFNPR,
  REF.BDREF,
  BPR.BDBINSSAPFNPR,
  BPR.BDINSSAPFNPR,
  BPR.BDBINSS13APFNPR,
  BPR.BDINSS13APFNPR,
  BPR.BDBASEFGTSMESESOCIAL,
  BPR.BDVALORFGTSMESESOCIAL,
  BPR.BDBASEFGTS13ESOCIAL,
  BPR.BDVALORFGTS13ESOCIAL,
  BPR.BDBASEFGTSINDESOCIAL,
  BPR.BDVALORFGTSINDESOCIAL,
  BPR.BDBASEIRBRUTARED,
  BPR.BDBASEIR13BRUTARED,
  BPR.BDVALORIRBRUTARED,
  BPR.BDVALORIR13BRUTARED,
  BPR.BDVALORRED,
  BPR.BDVALOR13RED
FROM
  VRHF_EMP_TFOLHANORMAL_PREV_RESC BPR,
  (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER) BDREF FROM rdb$database) REF

UNION

SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  MAX(Y.BDCODCENTRO),
  MAX(Y.BDCODTPCC),
  MAX(X.BDDATABAIXAFTPR),
  SUM(X.BDBFGTSFTPR),
  SUM(X.BDFGTSFTPR),
  SUM(X.BDFGTSCSFTPR),
  SUM(X.BDBFGTS13FTPR),
  SUM(X.BDFGTS13FTPR),
  SUM(X.BDFGTS13CSFTPR),
  MAX(X.BDMAIORREMFTPR),

  SUM(X.BDBINSSFTPR),
  MAX(X.BDALIQINSSFTPR),
  SUM(X.BDINSSFTPR),
  SUM(X.BDBIRRFFTPR),
  MAX(X.BDALIQIRRFFTPR),
  SUM(X.BDIRRFFTPR),

  SUM(X.BDBINSS13FTPR),
  MAX(X.BDALIQINSS13FTPR),
  SUM(X.BDINSS13FTPR),
  SUM(X.BDBIRRF13FTPR),
  MAX(X.BDALIQIRRF13FTPR),
  SUM(X.BDIRRF13FTPR),
  SUM(X.BDBSALFAMFTPR),
  SUM(X.BDSALFAMFTPR),
  SUM(X.BDBRAISFTPR),
  MAX(X.BDSALBASEFTPR),
  SUM(X.BDDEPFTPR),    
  SUM(X.BDBINSSFEFOLFTPR),
  SUM(X.BDINSSFEFOLFTPR),
  MAX(X.BDALIQINSSFEFOLFTPR),
  SUM(X.BDCREDITOFTPR),
  SUM(X.BDDEBITOFTPR),
  SUM(X.BDBFGTSFEFTPR),
  SUM(X.BDFGTSFEFTPR),
  SUM(X.BDBIRRFFEFTPR),
  SUM(X.BDIRRFFEFTPR),
  REF.BDREF,
  SUM(X.BDBINSSAPFTPR),
  SUM(X.BDINSSAPFTPR),
  SUM(X.BDBINSS13APFTPR),
  SUM(X.BDINSS13APFTPR),
  SUM(X.BDBASEFGTSMESESOCIAL),
  SUM(X.BDVALORFGTSMESESOCIAL),
  SUM(X.BDBASEFGTS13ESOCIAL),
  SUM(X.BDVALORFGTS13ESOCIAL),
  SUM(X.BDBASEFGTSINDESOCIAL),
  SUM(X.BDVALORFGTSINDESOCIAL),
  MAX(X.BDBASEIRBRUTARED),
  MAX(X.BDBASEIR13BRUTARED),
  MAX(X.BDVALORIRBRUTARED),
  MAX(X.BDVALORIR13BRUTARED),
  MAX(X.BDVALORRED),
  MAX(X.BDVALOR13RED)
FROM
  VRHF_EMP_TFOLTOM_PREV_RESC X,
  VRHF_EMP_TPREPFN Y,
  (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER) BDREF FROM rdb$database) REF
WHERE X.BDCODEMP = Y.BDCODEMP AND X.BDCODCOL = Y.BDCODCOL AND X.BDORDEM = Y.BDORDEM
GROUP BY
  X.BDCODEMP,
  X.BDCODCOL,
  REF.BDREF
;


/* CREATE OR ALTER VIEW: VWRH_DADOS_REL_GRRF_PREVIA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_DADOS_REL_GRRF_PREVIA(
    BDCODEMP,
    BDCODCOL,
    BDBFGTS,
    BDFGTS,
    BDFGTSCS,
    BDBFGTS13,
    BDFGTS13,
    BDFGTS13CS,
    BDBFGTSFEFOL,
    BDFGTSFEFOL,
    BDNOMCOL,
    BDDATANASCCOL,
    BDDATAADMCOL,
    BDPISCOL,
    BDCPFCOL,
    BDCATEGORIACOL,
    BDREFFN,
    BDSALDOFGTS,
    BDDATARESCISAO,
    BDCALCFGTSMESANT,
    BDDATAAVPREVIO,
    BDAVPREPRES,
    BDCODSEFMFG,
    BDDESCMFG,
    BDDESCCATEGORIA,
    BDPROJECAOAVISO,
    BDDIASINDENIZADOS,
    BDDIASTRABALHADOS,
    BDDATANOTIF,
    BDPERCMULTAFGTS,
    BDPERCMULTAFGTSCS,
    BDBASEFGTSMESESOCIAL,
    BDVALORFGTSMESESOCIAL,
    BDBASEFGTS13ESOCIAL,
    BDVALORFGTS13ESOCIAL,
    BDBASEFGTSINDESOCIAL,
    BDVALORFGTSINDESOCIAL)
AS
SELECT
  FOL.BDCODEMP,
  FOL.BDCODCOL,
  COALESCE(FOL.BDBFGTS, 0.00),
  COALESCE(FOL.BDFGTS, 0.00),
  COALESCE(FOL.BDFGTSCS, 0.00),
  COALESCE(FOL.BDBFGTS13, 0.00),
  COALESCE(FOL.BDFGTS13, 0.00),
  COALESCE(FOL.BDFGTS13CS, 0.00),
  COALESCE(FOL.BDBFGTSFEFOL, 0.00),
  COALESCE(FOL.BDFGTSFEFOL, 0.00),
  COLCAD.BDNOMCOL,
  COL.BDDATANASCCOL,
  COL.BDDATAADMCOL,
  DOCREF.BDPISCOL,
  COLDOC.BDCPFCOL,
  COLFGTS.BDCATEGORIACOL,
  RESC.BDREFRESCISAOPREV,
  RESC.BDSALDOFGTSPREV,
  RESC.BDDATARESCISAOPREV,
  RESC.BDCALCFGTSMESANTPREV,
  RESC.BDDATAAVPREVIOPREV,
  PRES.BDAVPREPRES,
  MFG.BDCODSEFMFG,
  MFG.BDDESCMFG,
  CAT.BDDESCCATEGORIA,
  RESC.bdprojecaoavisoprev,
  RESC.bddiasindenizadosprev,
  RESC.bddiastrabalhadosprev,
  RESC.bddatanotifprev,
  PRES.bdpercmultafgts,
  PRES.bdpercmultafgtscs,
  FOL.BDBASEFGTSMESESOCIAL,
  FOL.BDVALORFGTSMESESOCIAL,
  FOL.BDBASEFGTS13ESOCIAL,
  FOL.BDVALORFGTS13ESOCIAL,
  FOL.BDBASEFGTSINDESOCIAL,
  FOL.BDVALORFGTSINDESOCIAL
FROM VWRH_UNION_FNPR_FTPR_MES_BASES FOL
JOIN VRH_EMP_TCOLCON COL ON FOL.BDCODEMP = COL.BDCODEMP AND FOL.BDCODCOL = COL.BDCODCOL
JOIN VRH_EMP_TRESCISAO_PREVIA RESC ON FOL.BDCODEMP = RESC.BDCODEMP AND FOL.BDCODCOL = RESC.BDCODCOL
JOIN VRH_BASE_TPREPRESC PRES ON RESC.BDCODPRES = PRES.BDCODPRES
JOIN VRH_BASE_TMOTFGTS MFG ON PRES.BDCODMFG = MFG.BDCODMFG
LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC COLDOC ON FOL.BDCODEMP = COLDOC.BDCODEMP AND FOL.BDCODCOL = COLDOC.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF DOCREF ON FOL.BDCODEMP = DOCREF.BDCODEMP AND FOL.BDCODCOL = DOCREF.BDCODCOL
LEFT OUTER JOIN VW_VRHF_EMP_TCOLCON_FGTSGPS COLFGTS ON FOL.BDCODEMP = COLFGTS.BDCODEMP AND FOL.BDCODCOL = COLFGTS.BDCODCOL
LEFT OUTER JOIN VRH_BASE_TCATEGORIA CAT ON CAT.BDCODCATEGORIA = COLFGTS.BDCATEGORIACOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON COLCAD.BDCODEMP = FOL.BDCODEMP AND COLCAD.BDCODCOL = FOL.BDCODCOL
;

/* CREATE OR ALTER VIEW: VWRH_EMP_TPARCELAMENTO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_EMP_TPARCELAMENTO(
BDCODEMP,
BDCODCOL,
BDCODPARC,
BDCODVER,
BDQTDMESESPAR,
BDPARCELAPI,
BDREFPI,
BDVALORPI)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODPARC,
  X.BDCODVER,
  X.BDQTDMESESPAR,
  Y.BDPARCELAPI,
  Y.BDREFPI,
  Y.BDVALORPI
FROM VRH_EMP_TPARCELAMENTOS X
JOIN VRH_EMP_TPARCELAMENTOS_ITENS Y ON (Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDCODPARC = X.BDCODPARC)
;

/* CREATE OR ALTER VIEW: VWRH_EMPMENSAL_ABA_GPS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_EMPMENSAL_ABA_GPS(
    BDCODEMP,
    BDREFEMP,
    BDCODFPASTERC,
    BDSIMPLESGPS,
    BDEMPEMP,
    BDAUTEMP,
    BDFUNEMP,
    BDFAP,
    BDCODFPAS,
    BDCODTERC,
    BDPERTERC,
    BDDESCFPAS,
    BDDESCTERC,
    BDCCATVCONCOM,
    BDINDCOMP,
    BDDESONTOMAEMP,
    BDCODCLATRI,
    BDDESCCLATRI,
    BDESCOOPERATIVA,
    BDESCONSTRUTORA,
    BDAPURAT,
    BDAPUFAP,
    BDACINTISENMULTA,
    BDCODTRIBRUR,
    BDDESCTRIBRUR,
    BDRATEIO13SAL,
    BDDESCRATEIO13SAL)
AS
SELECT
  RHGPS.BDCODEMP,
  RHGPS.BDREFEMP,
  RHGPS.BDCODFPASTERC,
  CASE
    WHEN RHGPS.BDSIMPLESGPS = 1 THEN 'Optante'
    WHEN RHGPS.BDSIMPLESGPS = 2 THEN 'Optante - fat. anual superior a R$ 1.200.000,00'
    WHEN RHGPS.BDSIMPLESGPS = 3 THEN 'Não Optante - prod.Rural PF (CEI e FPAS 604)'
    WHEN RHGPS.BDSIMPLESGPS = 4 THEN 'Não Optante - c/liminar p/não pagto.Contr.Soc.'
    WHEN RHGPS.BDSIMPLESGPS = 5 THEN 'Optante - C/liminar p/não pagto.Contr.Social'
    WHEN RHGPS.BDSIMPLESGPS IS NULL THEN 'Não Optante'
    WHEN RHGPS.BDSIMPLESGPS NOT IN (1,2,3,4,5) THEN 'Não Optante'
  END BDSIMPLESGPS,
  RHGPS.BDEMPEMP,
  RHGPS.BDAUTEMP,
  RHGPS.BDFUNEMP,
  RHGPS.BDFAP,
  RHFPASTERC.BDCODFPAS,
  RHFPASTERC.BDCODTERC,
  CASE
    WHEN RHGPS.BDSIMPLESGPS IN (1,2,5) THEN
      0
    ELSE
      RHFPASTERC.BDPERTERC
  END,
  CAST(FPAS.BDDESCFPAS AS VARCHAR(10000)) BDDESCFPAS,
  TTERC.BDDESCTERC,
  RHGPS.BDCCATVCONCOM,
  RHGPS.BDINDCOMP,
  RHGPS.BDDESONTOMAEMP,
  ESOC.BDCODCLATRI,
  CT.BDDESCCLATRI,
  CASE
    WHEN ESOC.BDESCOOPERATIVA = 0 THEN 'Não'
    WHEN ESOC.BDESCOOPERATIVA = 1 THEN 'De trabalho'
    WHEN ESOC.BDESCOOPERATIVA = 2 THEN 'De produção'
    WHEN ESOC.BDESCOOPERATIVA = 3 THEN 'Outras'
    ELSE                            'Não informado'
  END BDESCOOPERATIVA,
  ESOC.BDESCONSTRUTORA,
  CASE
    WHEN ESOC.BDAPURAT = 1 THEN 'CNAE preponderante de cada estabelecimento'
    ELSE 'CNAE preponderante da empresa'
  END BDAPURAT,
  CASE
    WHEN ESOC.BDAPUFAP = 1 THEN 'FAP atribuído à cada estabelecimento'
    ELSE 'FAP atribuído à empresa'
  END BDAPUFAP,
  CASE
    WHEN ESOC.BDACINTISENMULTA = 1 THEN 'Com acordo'
    ELSE 'Sem acordo'
  END BDACINTISENMULTA,
  RHGPS.BDCODTRIBRUR,
  TR.BDDESCTRIBRUR,
  RHGPS.BDRATEIO13SAL,
  CASE
    WHEN RHGPS.BDRATEIO13SAL = 0 THEN 'Rateio conforme alocações do mês'
    WHEN RHGPS.BDRATEIO13SAL = 1 THEN 'Utilizar os dados do último tomador alocado no mês'
    WHEN RHGPS.BDRATEIO13SAL = 2 THEN 'Utilizar os dados da empresa - Não ratear'
    ELSE                              'Não informado'
  END BDESCRATEIO13SAL

FROM
  VRHF_BASE_TEMPGPS RHGPS
LEFT OUTER JOIN VRH_BASE_TFPAS_TERCEIROS RHFPASTERC ON (RHGPS.BDCODFPASTERC = RHFPASTERC.BDCODFPASTERC)
LEFT OUTER JOIN VRH_BASE_TFPAS FPAS ON (RHFPASTERC.BDCODFPAS = FPAS.BDCODFPAS)
LEFT OUTER JOIN VRH_BASE_TTERCEIROS TTERC ON (RHFPASTERC.BDCODTERC = TTERC.BDCODIGO)
LEFT OUTER JOIN VRHF_BASE_TEMPESOCIAL ESOC ON (ESOC.BDCODEMP = RHGPS.BDCODEMP AND ESOC.BDREFEMP = RHGPS.BDREFEMP)
LEFT OUTER JOIN VRH_BASE_CLASSTRIBUTARIA CT ON (CT.BDCODCLATRI = ESOC.BDCODCLATRI)
LEFT OUTER JOIN TTRIBUTACAO_RURAL TR ON (TR.BDCODTRIBRUR = RHGPS.BDCODTRIBRUR)
;

/* CREATE OR ALTER VIEW: VWRH_EMPMENSAL_ABA_GRCS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_EMPMENSAL_ABA_GRCS(
BDCODEMP,
BDREFEMP,
BDCODSINPAT,
BDCAPSOCEMP,
BDTIPOESTABE,
BDDESCSINPAT)
 AS 
SELECT
  RHGRCS.BDCODEMP,
  RHGRCS.BDREFEMP,
  RHGRCS.BDCODSINPAT,
  RHGRCS.BDCAPSOCEMP,
  CASE
    WHEN RHGRCS.BDTIPOESTABE = 1 THEN 'Principal'
    WHEN RHGRCS.BDTIPOESTABE = 2 THEN 'Filial'
    WHEN RHGRCS.BDTIPOESTABE = 3 THEN 'Outros'
    WHEN RHGRCS.BDTIPOESTABE NOT IN (1,2,3) THEN 'Único'
    WHEN RHGRCS.BDTIPOESTABE IS NULL THEN 'Único'
  END BDTIPOESTABE,
  SINDPAT.BDDESCSINPAT
FROM
  VRHF_BASE_TEMPGRCS RHGRCS
LEFT OUTER JOIN VRHF_BASE_TSINDPATRONAL SINDPAT ON (RHGRCS.BDCODSINPAT = SINDPAT.BDCODSINPAT)
;

/* CREATE OR ALTER VIEW: VWRH_EMPMENSAL_ABA_PCALC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_EMPMENSAL_ABA_PCALC(
    BDCODEMP,
    BDREFEMP,
    BDFECHAMESEMP,
    BDFECHAVTEMP,
    BDPAGEMP,
    BDCODPAGEMP,
    BDARREMP,
    BDTIPOARREMP,
    BDPERCADSALEMP,
    BDMESDSREMP,
    BDREFHOREMP,
    BDCALCFCNAFNEMP,
    BDCALCC13NAFNEMP,
    BDPAGEMPCONTR,
    BDARREDONDAFN,
    BDARREDONDAFC,
    BDARREDONDAFE,
    BDARREDONDAFA,
    BDARREDONDAAD,
    BDARREDONDAA13,
    BDARREDONDA13,
    BDARREDONDAC13,
    BDARREDONDAAU,
    BDARREDONDAFTINT,
    BDDESCFALHORASDIAS,
    BDPERCLIMIDESCPAR,
    BDCALCC13FNNEGEMP,
    BDDSRMEDATUSAL,
    BDIDADESAUDEEMP,
    BDCALC13MP936,
    BDNAOALTPERAQUIMP936,
    BDDESCCOMPL13NEG,
    BDCONSIDERAFERICIDADETOM,
    BDRATEIOINTEGRALVER,
    BDCALCAD13UMAVEZFE)
AS
SELECT
  RHCALC.BDCODEMP,
  RHCALC.BDREFEMP,
  COALESCE(RHCALC.BDFECHAMESEMP, 0) BDFECHAMESEMP,
  COALESCE(RHCALC.BDFECHAVTEMP, 0) BDFECHAVTEMP,
  CASE
    WHEN RHCALC.BDPAGEMP = 1 THEN 'Mês da competência da folha'
    WHEN RHCALC.BDPAGEMP <> 1 THEN 'Mês posterior a competência da folha'
    WHEN RHCALC.BDPAGEMP IS NULL THEN 'Mês posterior a competência da folha'
  END BDPAGEMP,
  RHCALC.BDPAGEMP BDCODPAGEMP,
  CASE
    WHEN RHCALC.BDARREMP = 1 THEN 'Centavos'
    WHEN RHCALC.BDARREMP = 2 THEN 'De 5 em 5'
    WHEN RHCALC.BDARREMP = 3 THEN 'De 10 em 10'
    WHEN RHCALC.BDARREMP NOT IN (1,2,3) THEN 'Não arredondar'
    WHEN RHCALC.BDARREMP IS NULL THEN 'Não arredondar'
  END BDARREMP,
  CASE
    WHEN RHCALC.BDTIPOARREMP = 1 THEN 'Para cima - não desconta no mês seguinte'
    WHEN RHCALC.BDTIPOARREMP = 2 THEN 'Para baixo - acrescenta no mês seguinte'
    WHEN RHCALC.BDTIPOARREMP = 3 THEN 'Para baixo - não acrescenta no mês seguinte'
    WHEN RHCALC.BDTIPOARREMP NOT IN (1,2,3) THEN 'Para cima - desconta no mês seguinte'
    WHEN RHCALC.BDTIPOARREMP IS NULL THEN 'Para cima - desconta no mês seguinte'
  END BDTIPOARREMP,
  COALESCE(RHCALC.BDPERCADSALEMP, 0.0000) BDPERCADSALEMP,
  CASE
    WHEN RHCALC.BDMESDSREMP = 1 THEN 'Mês subsequente'
    WHEN RHCALC.BDMESDSREMP <> 1 THEN 'Mês atual'
    WHEN RHCALC.BDMESDSREMP IS NULL THEN 'Mês atual'
  END BDMESDSREMP,
  COALESCE(RHCALC.BDREFHOREMP, 'FALSE') BDREFHOREMP,
  COALESCE(RHPAR.BDCALCFCNAFNEMP, 'FALSE') BDCALCFCNAFNEMP,
  COALESCE(RHPAR.BDCALCC13NAFNEMP, 'FALSE') BDCALCC13NAFNEMP,
  CASE
    WHEN RHCALC.BDPAGEMPCONTR = 1 THEN 'Mês da competência da folha'
    WHEN RHCALC.BDPAGEMPCONTR <> 1 THEN 'Mês posterior a competência da folha'
    WHEN RHCALC.BDPAGEMPCONTR IS NULL THEN 'Mês posterior a competência da folha'
  END BDPAGEMPCONTR,
  RHCALC.BDARREDONDAFN,
  RHCALC.BDARREDONDAFC,
  RHCALC.BDARREDONDAFE,
  RHCALC.BDARREDONDAFA,
  RHCALC.BDARREDONDAAD,
  RHCALC.BDARREDONDAA13,
  RHCALC.BDARREDONDA13,
  RHCALC.BDARREDONDAC13,
  RHCALC.BDARREDONDAAU,
  RHCALC.BDARREDONDAFTINT,
  RHCALC.BDDESCFALHORASDIAS,
  RHCALC.BDPERCLIMIDESCPAR,    
  COALESCE(RHPAR.BDCALCC13FNNEGEMP, 'FALSE') BDCALCC13FNNEGEMP,
  COALESCE(RHCALC.BDDSRMEDATUSAL, 'FALSE') BDDSRMEDATUSAL,
  COALESCE(RHCALC.BDIDADESAUDEEMP, 'FALSE') BDIDADESAUDEEMP,
  COALESCE(RHPAR.BDCALC13MP936, 'FALSE') BDCALC13MP936,
  COALESCE(RHPAR.BDNAOALTPERAQUIMP936, 'FALSE') BDNAOALTPERAQUIMP936,
  COALESCE(RHPAR.BDDESCCOMPL13NEG, 'FALSE') BDDESCCOMPL13NEG,
  CASE
    WHEN RHCALC.BDCONSIDERAFERICIDADETOM = True THEN 'Sim'
    WHEN RHCALC.BDCONSIDERAFERICIDADETOM = False THEN 'Não'
    WHEN RHCALC.BDCONSIDERAFERICIDADETOM IS NULL THEN 'Não'
  END BDCONSIDERAFERICIDADETOM,
  RHCALC.BDRATEIOINTEGRALVER,
  COALESCE(RHPAR.BDCALCAD13UMAVEZFE, 'FALSE') BDCALCAD13UMAVEZFE
FROM
VRHF_BASE_TEMPCALC RHCALC
LEFT OUTER JOIN VRHF_BASE_TEMPPAR RHPAR ON (RHCALC.BDCODEMP = RHPAR.BDCODEMP AND RHCALC.BDREFEMP = RHPAR.BDREFEMP)
;

/* CREATE OR ALTER VIEW: VWRH_EMPMENSAL_ABA_PGER (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_EMPMENSAL_ABA_PGER(
    BDCODEMP,
    BDREFEMP,
    BDTIPOFEREMP,
    BDSOMSALFEREMP,
    BDTIPOAD13EMP,
    BDSOMSALAD13EMP,
    BDANOSAVPREVIOIND,
    BDLIMINARAVPREVEMP,
    BDTIPCALCFERCOLINF,
    BDTIPCALCFERCOLSUP,
    BDINDSITESPECIAL,
    BDSENHAARQEMP,
    BDSENHAARQEMPSEP,
    BDSENHAARQEMP_DESC
)
AS
SELECT
  RHCALC.BDCODEMP,
  RHCALC.BDREFEMP,
  CASE
    WHEN RHCALC.BDTIPOFEREMP = 1 THEN '1/12 (mensal)'
    WHEN RHCALC.BDTIPOFEREMP = 2 THEN '1/30 (diário)'
    WHEN RHCALC.BDTIPOFEREMP NOT IN (1,2) THEN 'Convencional (Anual)'
    WHEN RHCALC.BDTIPOFEREMP IS NULL THEN 'Convencional (Anual)'
  END BDTIPOFEREMP,
  COALESCE(RHCALC.BDSOMSALFEREMP, 'FALSE') BDSOMSALFEREMP,
  CASE
    WHEN RHCALC.BDTIPOAD13EMP = 1 THEN '1/12 (mensal)'
    WHEN RHCALC.BDTIPOAD13EMP = 2 THEN '1/30 (diário)'
    WHEN RHCALC.BDTIPOAD13EMP NOT IN (1,2) THEN 'Convencional (Anual)'
    WHEN RHCALC.BDTIPOAD13EMP IS NULL THEN 'Convencional (Anual)'
  END BDTIPOAD13EMP,
  COALESCE(RHCALC.BDSOMSALAD13EMP, 'FALSE') BDSOMSALAD13EMP,
  CASE
    WHEN BDANOSAVPREVIOIND = 1 THEN 'Após o primeiro ano de serviço'
    ELSE                            'Após o segundo ano de serviço'
  END BDANOSAVPREVIOIND,
  CASE
    WHEN BDLIMINARAVPREVEMP = 0 THEN 'Não possui'
    WHEN BDLIMINARAVPREVEMP = 1 THEN 'Segurados'
    WHEN BDLIMINARAVPREVEMP = 2 THEN 'Patronal'
    WHEN BDLIMINARAVPREVEMP = 3 THEN 'Segurados e patronal'
    WHEN BDLIMINARAVPREVEMP = 4 THEN 'Segurados e 13º salário'
    WHEN BDLIMINARAVPREVEMP = 5 THEN 'Patronal e 13° salário'
    WHEN BDLIMINARAVPREVEMP = 6 THEN 'Segurados, patronal e 13º salário'
    ELSE 'Não informado'
  END BDLIMINARAVPREVEMP,
  FCINF.BDDESCRICAO,
  FCSUP.BDDESCRICAO,
  CASE
    WHEN CHAR_LENGTH(EMP.BDCNPJEMP) = 18 THEN
      CASE
        WHEN ES.BDINDSITESPECIAL = 0 THEN 'Situação normal'
        WHEN ES.BDINDSITESPECIAL = 1 THEN 'Extinção'
        WHEN ES.BDINDSITESPECIAL = 2 THEN 'Fusão'
        WHEN ES.BDINDSITESPECIAL = 3 THEN 'Cisão'
        WHEN ES.BDINDSITESPECIAL = 4 THEN 'Incorporação'
        ELSE 'Não informado'
      END
    ELSE
      CASE
        WHEN ES.BDINDSITESPECIAL = 0 THEN 'Situação normal'
        WHEN ES.BDINDSITESPECIAL = 1 THEN 'Encerramento de espólio'
        WHEN ES.BDINDSITESPECIAL = 2 THEN 'Saída do país em caráter permanente'
        ELSE 'Não informado'
      END
  END BDINDSITESPECIAL ,
  RHPAR.BDSENHAARQEMP, RHPAR.BDSENHAARQEMPSEP,
  CASE
    WHEN RHPAR.BDSENHAARQEMP = 1 THEN 'CPF'
    WHEN RHPAR.BDSENHAARQEMP = 2 THEN 'Data de nascimento'
    ELSE 'Não utiliza'
  END AS BDSENHAARQEMP_DESC

FROM
VRHF_BASE_TEMPCALC RHCALC
JOIN TEMPRESAS EMP ON EMP.BDCODEMP = RHCALC.BDCODEMP
LEFT OUTER JOIN VRHF_BASE_TEMPPAR RHPAR ON (RHCALC.BDCODEMP = RHPAR.BDCODEMP AND RHCALC.BDREFEMP = RHPAR.BDREFEMP)
LEFT OUTER JOIN VRHF_BASE_TTIPOCALCFERCOLETIVA FCINF ON (FCINF.BDTIPCALCFERCOL = RHCALC.BDTIPCALCFERCOLINF)
LEFT OUTER JOIN VRHF_BASE_TTIPOCALCFERCOLETIVA FCSUP ON (FCSUP.BDTIPCALCFERCOL = RHCALC.BDTIPCALCFERCOLSUP)
LEFT OUTER JOIN VRHF_BASE_TEMPESOCIAL ES ON (ES.BDCODEMP = RHCALC.BDCODEMP AND ES.BDREFEMP = RHCALC.BDREFEMP)
;

/* CREATE OR ALTER VIEW: VWRH_EMPMENSAL_ABA_PGERA (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_EMPMENSAL_ABA_PGERA(
BDCODEMP,
BDREFEMP,
BDTIPOCONTAB,
BDTIPOEMIGUIAS)
 AS 
SELECT
  RHPAR.BDCODEMP,
  RHPAR.BDREFEMP,
  CASE
    WHEN RHPAR.BDTIPOCONTAB = 1 THEN 'Agrupada'
    WHEN RHPAR.BDTIPOCONTAB <> 1 THEN 'Centro de custos'
    WHEN RHPAR.BDTIPOCONTAB IS NULL THEN 'Centro de custos'
  END BDTIPOCONTAB,
  CASE
    WHEN RHPAR.BDTIPOEMIGUIAS = 1 THEN 'Agrupada'
    WHEN RHPAR.BDTIPOEMIGUIAS <> 1 THEN 'Centro de custos'
    WHEN RHPAR.BDTIPOEMIGUIAS IS NULL THEN 'Centro de custos'
  END BDTIPOEMIGUIAS
FROM
VRHF_BASE_TEMPPAR RHPAR
;

/* CREATE OR ALTER VIEW: VWRH_EMPMENSAL_ABA_PROP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_EMPMENSAL_ABA_PROP(
BDCODEMP,
BDREFEMP,
BDPROPADMEMP,
BDPROPRESEMP,
BDPROPFEREMP,
BDPROPSITEMP,
BDPROPTOMEMP)
 AS 
SELECT
  RHPROP.BDCODEMP,
  RHPROP.BDREFEMP,
  CASE
    WHEN RHPROP.BDPROPADMEMP = 1 THEN 'Divisão por 30 considerando até o último dia do mês'
    WHEN RHPROP.BDPROPADMEMP = 2 THEN 'Divisão por 30 dias considerando meses com no máximo 30 dias'
    WHEN RHPROP.BDPROPADMEMP NOT IN (1,2) THEN 'Divisão pelos dias do mês e multiplica pelos dias trabalhados'
    WHEN RHPROP.BDPROPADMEMP IS NULL THEN 'Divisão pelos dias do mês e multiplica pelos dias trabalhados'
  END BDPROPADMEMP,
  CASE
    WHEN RHPROP.BDPROPRESEMP = 1 THEN 'Divisão por 30'
    WHEN RHPROP.BDPROPRESEMP <> 1 THEN 'Divisão por dias do mês'
    WHEN RHPROP.BDPROPRESEMP IS NULL THEN 'Divisão por dias do mês'
  END BDPROPRESEMP,
  CASE
    WHEN RHPROP.BDPROPFEREMP = 1 THEN 'Divisão por 30'
    WHEN RHPROP.BDPROPFEREMP <> 1 THEN 'Divisão por dias do mês'
    WHEN RHPROP.BDPROPFEREMP IS NULL THEN 'Divisão por dias do mês'
  END BDPROPFEREMP,
  CASE
    WHEN RHPROP.BDPROPSITEMP = 1 THEN 'Divisão por 30'
    WHEN RHPROP.BDPROPSITEMP <> 1 THEN 'Divisão por dias do mês'
    WHEN RHPROP.BDPROPSITEMP IS NULL THEN 'Divisão por dias do mês'
  END BDPROPSITEMP,
  CASE
    WHEN RHPROP.bdproptomemp = 1 THEN 'Divisão por 30'
    WHEN RHPROP.bdproptomemp <> 1 THEN 'Divisão por dias do mês'
    WHEN RHPROP.bdproptomemp IS NULL THEN 'Divisão por dias do mês'
  END bdproptomemp

FROM
VRHF_BASE_TEMPPROP RHPROP
;

/* CREATE OR ALTER VIEW: VWRH_EMPMENSAL_ABA_RAIS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_EMPMENSAL_ABA_RAIS(
    BDCODEMP,
    BDREFEMP,
    BDNATESTEMP,
    BDDATABASEEMP,
    BDPATEMP,
    BDNROPROPEMP,
    BDSERPROPRIOPATEMP,
    BDPATREFCONVENIOEMP,
    BDPATCESTAALIMENTOEMP,
    BDPATADMCOZINHAEMP,
    BDPATREFTRANSPEMP,
    BDPATALICONVENIOEMP,
    BDSINDICALIZEMP,
    BDCODEMPPAT,
    BDSOCOSTCONTAPART,
    BDCODTPPONT,
    BDDESCTCP,
    BDENTSFL,
    BDTRABTEMP,
    BDREGMTE)
AS
SELECT
  RHRAIS.BDCODEMP,
  RHRAIS.BDREFEMP,
  CASE
    WHEN RHRAIS.BDNATESTEMP = 1 THEN '10 - Autônomo, profissional liberal e condomínio'
    WHEN RHRAIS.BDNATESTEMP = 2 THEN '20 - Empresa Privada, sociedade civil, associação de classe e sindicato'
    WHEN RHRAIS.BDNATESTEMP = 3 THEN '30 - Fundação mantida com recursos privados'
    WHEN RHRAIS.BDNATESTEMP = 4 THEN '35 - Fundação mantida com recursos públicos'
    WHEN RHRAIS.BDNATESTEMP = 5 THEN '40 - Sociedade de economia mista'
    WHEN RHRAIS.BDNATESTEMP = 6 THEN '50 - Empresa pública'
    WHEN RHRAIS.BDNATESTEMP = 7 THEN '60 - Órgão autônomo de direito público'
    WHEN RHRAIS.BDNATESTEMP = 8 THEN '70 - Autarquia'
    WHEN RHRAIS.BDNATESTEMP = 9 THEN '80 - Administração pública direita'
    WHEN RHRAIS.BDNATESTEMP = 10 THEN '90 - Cartório'
    WHEN RHRAIS.BDNATESTEMP NOT IN (1,2,3,4,5,6,7,8,9,10) THEN '00 - Nenhum'
    WHEN RHRAIS.BDNATESTEMP IS NULL THEN '00 - Nenhum'
  END BDNATESTEMP,
  RHRAIS.BDDATABASEEMP,
  COALESCE(RHRAIS.BDPATEMP, 'FALSE') BDPATEMP,
  RHRAIS.BDNROPROPEMP,
  RHRAIS.BDSERPROPRIOPATEMP,
  RHRAIS.BDPATREFCONVENIOEMP,
  RHRAIS.BDPATCESTAALIMENTOEMP,
  RHRAIS.BDPATADMCOZINHAEMP,
  RHRAIS.BDPATREFTRANSPEMP,
  RHRAIS.BDPATALICONVENIOEMP,
  COALESCE(RHRAIS.BDSINDICALIZEMP, 'FALSE') BDSINDICALIZEMP,
  RHRAIS.BDCODEMPPAT,
  ESOC.BDSOCOSTCONTAPART,
  RHRAIS.BDCODTPPONT,
  TCP.BDDESCRICAO BDDESCTCP,
  RHRAIS.BDENTSFL,
  RHRAIS.BDTRABTEMP,
  RHRAIS.BDREGMTE
FROM
  VRHF_BASE_TEMPRAIS RHRAIS
  LEFT OUTER JOIN VRHF_BASE_TEMPESOCIAL ESOC ON (ESOC.BDCODEMP = RHRAIS.BDCODEMP AND ESOC.BDREFEMP = RHRAIS.BDREFEMP)
  LEFT OUTER JOIN VRH_BASE_TCONTROLE_PONTO TCP ON (TCP.BDCODTPPONT = RHRAIS.BDCODTPPONT)
;

/* CREATE OR ALTER VIEW: VWRH_EMPMENSAL_ABA_SEFIP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_EMPMENSAL_ABA_SEFIP(
BDCODEMP,
BDREFEMP,
BDCODBAN,
BDCODAG,
BDCODUF,
BDIDENTEMP,
BDCATSEFIPEMP,
BDISENFILEMP,
BDCETRTALIZAEMP,
BDCODSEFIPEMP,
BDNOMBAN,
BDNOMAG,
BDSIGLAUF)
 AS 
SELECT
  RHSEFIP.BDCODEMP,
  RHSEFIP.BDREFEMP,
  RHSEFIP.BDCODBAN,
  RHSEFIP.BDCODAG,
  RHSEFIP.BDCODUF,
  RHSEFIP.BDIDENTEMP,
  CASE
    WHEN RHSEFIP.BDCATSEFIPEMP = 1 THEN 'Entidade filantrópica'
    WHEN RHSEFIP.BDCATSEFIPEMP = 2 THEN 'Clube de futebol'
    WHEN RHSEFIP.BDCATSEFIPEMP = 3 THEN 'Pessoa física urbana'
    WHEN RHSEFIP.BDCATSEFIPEMP = 4 THEN 'Pessoa física rural'
    WHEN RHSEFIP.BDCATSEFIPEMP = 5 THEN 'Pessoa jurídica rural'
    WHEN RHSEFIP.BDCATSEFIPEMP = 6 THEN 'Sind. agregador trab. avulso'
    WHEN RHSEFIP.BDCATSEFIPEMP NOT IN (1,2,3,4,5,6) THEN 'Outros'
    WHEN RHSEFIP.BDCATSEFIPEMP IS NULL THEN 'Outros'
  END BDCATSEFIPEMP,
  RHSEFIP.BDISENFILEMP,
  CASE
    WHEN RHSEFIP.BDCETRTALIZAEMP = 1 THEN 'Centralizadora'
    WHEN RHSEFIP.BDCETRTALIZAEMP = 2 THEN 'Centralizada'
    WHEN RHSEFIP.BDCETRTALIZAEMP NOT IN (1,2) THEN 'Não centraliza'
    WHEN RHSEFIP.BDCETRTALIZAEMP IS NULL THEN 'Não centraliza'
  END BDCETRTALIZAEMP,
  RHSEFIP.BDCODSEFIPEMP,
  BANCO.BDNOMBAN,
  BANAG.BDNOMAG,
  UF.BDSIGLAUF
FROM
  VRHF_BASE_TEMPSEFIP RHSEFIP
LEFT OUTER JOIN TBANCOS BANCO ON (RHSEFIP.BDCODBAN = BANCO.BDCODBAN)
LEFT OUTER JOIN TBANCOS_AG BANAG ON (RHSEFIP.BDCODBAN = BANAG.BDCODBAN AND RHSEFIP.BDCODAG = BANAG.BDCODAG)
LEFT OUTER JOIN TUF UF ON (RHSEFIP.BDCODUF = UF.BDCODUF)
;

/* CREATE OR ALTER VIEW: VWRH_MAIORREMUNERACAO_VERBAS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_MAIORREMUNERACAO_VERBAS(
BDCODEMP,
BDCODCOL,
BDREFFN,
BDVALVFN)
 AS 
SELECT vercalc.bdcodemp,vercalc.bdcodcol,vercalc.bdreffn,SUM(vercalc.bdvalvfn) bdvalvfn
FROM vwrh_union_fn_ft_mes vercalc, vrh_base_tverbas ver, vw_verbas_ref_atual vref
WHERE (ver.bdcodver = vercalc.bdcodver)
AND (ver.bdcodver = vref.bdcodver) AND (SUBSTRING(ver.bdclaver FROM 1 FOR 7) NOT IN ('0.001.0','0.001.2'))
AND UPPER(vref.bdbasemaiorver) = 'TRUE'
GROUP BY vercalc.bdcodemp,vercalc.bdcodcol,vercalc.bdreffn
;

/* CREATE OR ALTER VIEW: VWRH_MAIORREMUNERACAO_DEMITIDOS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_MAIORREMUNERACAO_DEMITIDOS(
BDCODEMP,
BDCODCOL,
BDREFFN,
BDMAIORREMUNERACAO)
 AS 
SELECT calc.bdcodemp,calc.bdcodcol,calc.bdreffn,(COALESCE(calc.bdsalbase,0) + COALESCE(verba.bdvalvfn,0)) bdmaiorremuneracao FROM vwrh_union_fn_ft_mes_bases calc
JOIN vrh_emp_trescisao resc ON (calc.bdcodemp = resc.bdcodemp AND calc.bdcodcol = resc.bdcodcol)
LEFT OUTER JOIN VWRH_MAIORREMUNERACAO_VERBAS verba ON
      (verba.bdcodemp = calc.bdcodemp AND verba.bdcodcol = calc.bdcodcol AND verba.bdreffn = calc.bdreffn)
;

/* CREATE OR ALTER VIEW: VWRH_PENSAO_DEP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_PENSAO_DEP(
    BDCODDPN,
    BDCODEMP,
    BDCODCOL,
    BDTIPO,
    BDREFFN,
    BDREFPAGPEND,
    BDREFPEND,
    BDREFAUXPEND,
    BDVALPEND,
    BDDATAPGTO,
    BDTIPOFOL)
AS
SELECT
  BDCODDPN,
  BDCODEMP,
  BDCODCOL,
  0,
  BDREFFN,
  BDREFPAGPEND,
  BDREFPEND,
  BDREFAUXPEND,
  BDVALPEND,
  CAST(null as DATE),
  0
FROM VRHF_EMP_TFNPENSAO_DEP
UNION  ALL

SELECT
  FCD.BDCODBENEF,
  FCD.BDCODEMP,
  FCD.BDCODCOL,
  10,
  FCD.BDREFFN,
  FCD.BDREFPAGPEND,
  FCD.BDREFPEND,
  FCD.BDREFAUXPEND,
  FCD.BDVALPEND,
  CAST((SUBSTRING(FCD.BDREFFC FROM 5 FOR 2)||'-'||SUBSTRING(FCD.BDREFFC FROM 7 FOR 2)||'-'||SUBSTRING(FCD.BDREFFC FROM 1 FOR 4)) AS DATE),
  1
FROM VRHF_EMP_TFCPENSAO_DEP FCD
LEFT OUTER JOIN VRHF_EMP_TFOLHACOMP FC ON (FC.BDCODEMP = FCD.BDCODEMP AND FC.BDCODCOL = FCD.BDCODCOL AND FC.BDREFFN = FCD.BDREFFN AND FC.BDREFFC = FCD.BDREFFC)
WHERE coalesce(FC.BDVERCALCRRA,0) = 0
UNION  ALL

SELECT
  BDCODDPN,
  BDCODEMP,
  BDCODCOL,
  0,
  BDREFTOMADOR,
  BDREFPAGPEND,
  BDREFPEND,
  BDREFAUXPEND,
  BDVALPEND,
  CAST(null as DATE),
  0
FROM VRHF_EMP_TFTPENSAO_DEP
UNION ALL

SELECT
  FCDT.BDCODBENEF,
  FCDT.BDCODEMP,
  FCDT.BDCODCOL,
  10,
  FCDT.BDREFTOMADOR,
  FCDT.BDREFPAGPEND,
  FCDT.BDREFPEND,
  FCDT.BDREFAUXPEND,
  FCDT.BDVALPEND,
  CAST((SUBSTRING(FCDT.BDREFFC FROM 5 FOR 2)||'-'||SUBSTRING(FCDT.BDREFFC FROM 7 FOR 2)||'-'||SUBSTRING(FCDT.BDREFFC FROM 1 FOR 4)) AS DATE),
  1
FROM VRHF_EMP_TFCTPENSAO_DEP FCDT
LEFT OUTER JOIN VRHF_EMP_TFOLTOMCOMP FCT ON (FCT.BDCODEMP = FCDT.BDCODEMP AND
                                             FCT.BDCODCOL = FCDT.BDCODCOL AND
                                             FCT.BDORDEM = FCDT.BDORDEM AND
                                             FCT.BDREFTOMADOR = FCDT.BDREFTOMADOR AND
                                             FCT.BDREFFC = FCDT.BDREFFC)
WHERE coalesce(FCT.BDVERCALCRRA,0) = 0
UNION ALL

SELECT
  BDCODDPN,
  BDCODEMP,
  BDCODCOL,
  1,
  BDREFA13,
  BDREFA13 BDREFPAGPEND,
  BDREFPEND,
  BDREFAUXPEND,
  BDVALPEND,
  CAST(null as DATE),
  2
FROM
  VRHF_EMP_TA13PENSAO_DEP
UNION ALL

SELECT
  BDCODDPN,
  BDCODEMP,
  BDCODCOL,
  1,
  BDREF13,
  BDREFPAGPEND,
  BDREFPEND,
  BDREFAUXPEND,
  BDVALPEND,
  CAST(null as DATE),
  3
FROM
  VRHF_EMP_T13PENSAO_DEP
UNION ALL

SELECT
  BDCODBENEF,
  BDCODEMP,
  BDCODCOL,
  1,
  BDREFC13,
  BDREFPAGPEND,
  BDREFPEND,
  BDREFAUXPEND,
  BDVALPEND,
  CAST(null as DATE),
  4
FROM
  VRHF_EMP_TC13PENSAO_DEP
UNION ALL

SELECT
  BDCODBENEF,
  BDCODEMP,
  BDCODCOL,
  2,
  BDREFPAGPEND,
  BDREFPAGPEND,
  BDREFPEND,
  BDREFAUXPEND,
  BDVALPEND,
  CAST(null as DATE),
  5
FROM
  VRHF_EMP_TFEPENSAO_DEP
UNION ALL

SELECT
  BDCODDPN,
  BDCODEMP,
  BDCODCOL,
  0,
  BDREFPAGPEND,
  BDREFPAGPEND,
  BDREFPEND,
  BDREFAUXPEND,
  BDVALPEND,
  CAST(null as DATE),
  6
FROM
  VRHF_EMP_TADSALPENSAO_DEP

UNION ALL

SELECT
  BDCODDPN,
  BDCODEMP,
  BDCODCOL,
  50,
  BDREFPAGPEND,
  BDREFPAGPEND,
  BDREFPEND,
  BDREFAUXPEND,
  BDVALPEND,
  BDDATAFA,
  7
FROM
  VRHF_EMP_TFAPENSAO_DEP

UNION ALL

SELECT
  X.BDCODBENEF,
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDTIPOPEND,
  X.BDCOMPPEND,
  X.BDREFPAGPEND,
  X.BDREFPEND,
  X.BDREFAUXPEND,
  X.BDVALPEND,
  CAST(null as DATE),
  0
FROM
  VRHF_EMP_TFIPENSAO_DEP X
WHERE (NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFNPENSAO_DEP Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDCODDPN = X.BDCODBENEF AND Y.BDREFFN = X.BDCOMPPEND AND X.BDTIPOPEND = 9000)) AND
      (NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFTPENSAO_DEP Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDCODDPN = X.BDCODBENEF AND Y.BDREFTOMADOR = X.BDCOMPPEND AND X.BDTIPOPEND = 9000)) AND
      (NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TA13PENSAO_DEP Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDCODDPN = X.BDCODBENEF AND Y.BDREFA13 = X.BDCOMPPEND AND X.BDTIPOPEND = 9099)) AND
      (NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TADSALPENSAO_DEP Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDCODDPN = X.BDCODBENEF AND Y.BDREFPEND = X.BDCOMPPEND AND X.BDTIPOPEND = 9000))

UNION ALL

SELECT
  BDCODBENEF,
  BDCODEMP,
  BDCODCOL,
  0,
  BDREFPAGPEND,
  BDREFPAGPEND,
  BDREFPEND,
  BDREFAUXPEND,
  BDVALPEND,
  CAST(null as DATE),
  0
FROM
  VRHF_EMP_TINTPENSAO_DEP

UNION ALL

SELECT
  BDCODBENEF,
  BDCODEMP,
  BDCODCOL,
  0,
  BDREFPAGPEND,
  BDREFPAGPEND,
  BDREFPEND,
  BDREFAUXPEND,
  BDVALPEND,
  CAST(null as DATE),
  0
FROM
  VRHF_EMP_TTOMINTPENSAO_DEP
;

/* CREATE OR ALTER VIEW: VWRH_PESQUISA_COLCON_PIS_CPF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_PESQUISA_COLCON_PIS_CPF(
    BDCODEMP,
    BDCODCOL,
    BDCPFCOL,
    BDPISCOL,
    BDNOMEMP,
    BDNOMCOL,
    BDDATAADMCOL,
    BDCONTRCOL,
    BDRESERVISTACOL,
    BDTIPOCERTCIVILCOL,
    BDDATACERTCIVILCOL,
    BDTERMOCERTCIVILCOL,
    BDCARTORIOCERTCIVILCOL,
    BDLIVROCERTCIVILCOL,
    BDFOLHACERTCIVILCOL,
    BDCODCIDCERTCIVIL,
    BDREGPROF,
    BDSUS,
    BDCODCIDNASC,
    BDDATANASCCOL)
AS
SELECT
  COL.BDCODEMP,
  COL.BDCODCOL,
  COL.BDCPFCOL,
  DOCREF.BDPISCOL,
  EMP.BDNOMEMP,
  COLCAD.BDNOMCOL,
  COL.BDDATAADMCOL,
  COL.BDCONTRCOL,
  COLDOC.BDRESERVISTACOL,
  COLDOC.BDTIPOCERTCIVILCOL,
  COLDOC.BDDATACERTCIVILCOL,
  COLDOC.BDTERMOCERTCIVILCOL,
  COLDOC.BDCARTORIOCERTCIVILCOL,
  COLDOC.BDLIVROCERTCIVILCOL,
  COLDOC.BDFOLHACERTCIVILCOL,
  COLDOC.BDCODCIDCERTCIVIL,
  COLDOC.BDREGPROF,
  COLDOC.BDSUS,
  COL.BDCODCIDNASC,
  COL.BDDATANASCCOL
FROM VRH_EMP_TCOLCON COL
LEFT OUTER JOIN VW_TEMPRESAS_REF EMP ON EMP.BDCODEMP = COL.BDCODEMP
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON COLCAD.BDCODEMP = COL.BDCODEMP AND COLCAD.BDCODCOL = COL.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF DOCREF ON DOCREF.BDCODEMP = COL.BDCODEMP AND DOCREF.BDCODCOL = COL.BDCODCOL
LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC COLDOC ON COLDOC.BDCODEMP = COL.BDCODEMP AND COLDOC.BDCODCOL = COL.BDCODCOL
;

/* CREATE OR ALTER VIEW: VWRH_RELATORIORECIBO13SAL01 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_RELATORIORECIBO13SAL01(
BDCODEMP,
BDCODCOL,
BDCODVER,
BDREFFN,
BDREFV13,
BDREFAUXV13,
BDVALV13,
BDSALBASE,
BDBINSS,
BDBFGTS,
BDFGTS,
BDBIRRF,
BDCNPJEMP,
BDDESCVER,
BDDESCREDVER,
BDORDEMVER,
BDNOMCOL,
BDDATAADMCOL,
BDPISCOL,
BDCPFCOL,
BDTIPOCODVER,
BDTIPOREFVER,
BDCODBAN,
BDCODAG,
BDCTADEPCOL,
BDDIGCTADEPCOL,
BDMODOPAGTOCOL,
BDDATAFN)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREF13,
  X.BDREFV13,
  X.BDREFAUXV13,
  X.BDVALV13,
  Y.BDSALBASE13,
  Y.BDBASEINSS13,
  Y.BDBASEFGTS13,
  Y.BDFGTS13,
  Y.BDBASEIR13,
  EMP.BDCNPJEMP,
  VERB.BDDESCVER,
  VERB.BDDESCREDVER,
  VERB.BDORDEMVER,
  COLCAD.BDNOMCOL,
  COL.BDDATAADMCOL,
  DOCREF.BDPISCOL,
  COLDOC.BDCPFCOL,
  VERR.BDTIPOCODVER,
  VERR.BDTIPOREFVER,
  COLBANCO.BDCODBAN,
  COLBANCO.BDCODAG,
  COLBANCO.BDCTADEPCOL,
  COLBANCO.BDDIGCTADEPCOL,
  COLBANCO.BDMODOPAGTOCOL,
  X.BDREF13

FROM VRHF_EMP_TVERBA13 X
JOIN VRHF_EMP_T13SAL Y ON X.BDCODEMP = Y.BDCODEMP AND X.BDCODCOL = Y.BDCODCOL AND X.BDREF13 = Y.BDREF13
JOIN TEMPRESAS EMP ON X.BDCODEMP = EMP.BDCODEMP
JOIN VRH_BASE_TVERBAS VERB ON X.BDCODVER = VERB.BDCODVER
JOIN VRH_EMP_TCOLCON COL ON X.BDCODEMP = COL.BDCODEMP AND X.BDCODCOL = COL.BDCODCOL
JOIN VRH_EMP_TCOLCON_DOC COLDOC ON X.BDCODEMP = COLDOC.BDCODEMP AND X.BDCODCOL = COLDOC.BDCODCOL
JOIN VW_TVERBAS_REF VERR ON X.BDCODVER = VERR.BDCODVER
JOIN VW_VRHF_EMP_TCOLCON_BANCO COLBANCO ON X.BDCODEMP = COLBANCO.BDCODEMP AND X.BDCODCOL = COLBANCO.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON COLCAD.BDCODEMP = X.BDCODEMP AND COLCAD.BDCODCOL = X.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF DOCREF ON DOCREF.BDCODEMP = X.BDCODEMP AND DOCREF.BDCODCOL = X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VWRH_RELATORIORECIBOAD1301 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_RELATORIORECIBOAD1301(
BDCODEMP,
BDCODCOL,
BDCODVER,
BDREFFN,
BDREFVA13,
BDREFAUXVA13,
BDVALVA13,
BDSALBASE,
BDBINSS,
BDBFGTS,
BDFGTS,
BDBIRRF,
BDCALCFERA13,
BDCNPJEMP,
BDDESCVER,
BDDESCREDVER,
BDORDEMVER,
BDNOMCOL,
BDDATAADMCOL,
BDPISCOL,
BDCPFCOL,
BDTIPOCODVER,
BDTIPOREFVER,
BDCODBAN,
BDCODAG,
BDCTADEPCOL,
BDDIGCTADEPCOL,
BDMODOPAGTOCOL,
BDDATAFN)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFA13,
  X.BDREFVA13,
  X.BDREFAUXVA13,
  X.BDVALVA13,
  Y.BDSALBASEA13,
  0.0000,
  Y.BDBASEFGTSA13,
  Y.BDFGTSA13,
  Y.BDBASEIRA13,
  Y.BDCALCFERA13,
  EMP.BDCNPJEMP,
  VERB.BDDESCVER,
  VERB.BDDESCREDVER,
  VERB.BDORDEMVER,
  COLCAD.BDNOMCOL,
  COL.BDDATAADMCOL,
  DOCREF.BDPISCOL,
  COLDOC.BDCPFCOL,
  VERR.BDTIPOCODVER,
  VERR.BDTIPOREFVER,
  COLBANCO.BDCODBAN,
  COLBANCO.BDCODAG,
  COLBANCO.BDCTADEPCOL,
  COLBANCO.BDDIGCTADEPCOL,
  COLBANCO.BDMODOPAGTOCOL,
  X.BDREFA13

FROM VRHF_EMP_TVERBAA13 X
JOIN VRHF_EMP_TA13SAL Y ON X.BDCODEMP = Y.BDCODEMP AND X.BDCODCOL = Y.BDCODCOL AND X.BDREFA13 = Y.BDREFA13
JOIN TEMPRESAS EMP ON X.BDCODEMP = EMP.BDCODEMP
JOIN VRH_BASE_TVERBAS VERB ON X.BDCODVER = VERB.BDCODVER
JOIN VRH_EMP_TCOLCON COL ON X.BDCODEMP = COL.BDCODEMP AND X.BDCODCOL = COL.BDCODCOL
JOIN VRH_EMP_TCOLCON_DOC COLDOC ON X.BDCODEMP = COLDOC.BDCODEMP AND X.BDCODCOL = COLDOC.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF DOCREF ON X.BDCODEMP = DOCREF.BDCODEMP AND X.BDCODCOL = DOCREF.BDCODCOL
JOIN VW_TVERBAS_REF VERR ON X.BDCODVER = VERR.BDCODVER
JOIN VW_VRHF_EMP_TCOLCON_BANCO COLBANCO ON X.BDCODEMP = COLBANCO.BDCODEMP AND X.BDCODCOL = COLBANCO.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON COLCAD.BDCODEMP = X.BDCODEMP AND COLCAD.BDCODCOL = X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VWRH_RELATORIORECIBOADSAL01 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_RELATORIORECIBOADSAL01(
BDCODEMP,
BDCODCOL,
BDCODVER,
BDREFFN,
BDDATA,
BDREFVAD,
BDREFAUXVAD,
BDVALVAD,
BDBINSS,
BDBFGTS,
BDFGTS,
BDBIRRF,
BDCNPJEMP,
BDDESCVER,
BDDESCREDVER,
BDORDEMVER,
BDNOMCOL,
BDDATAADMCOL,
BDPISCOL,
BDCPFCOL,
BDTIPOCODVER,
BDTIPOREFVER,
BDCODBAN,
BDCODAG,
BDCTADEPCOL,
BDDIGCTADEPCOL,
BDMODOPAGTOCOL,
BDSALBASE,
BDDATAFN)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  CAST((SUBSTRING(CAST(X.BDDATAAD AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(X.BDDATAAD AS VARCHAR(10)) FROM 6 FOR 2)||SUBSTRING(CAST(X.BDDATAAD AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER),
  X.BDDATAAD,
  X.BDREFVAD,
  X.BDREFAUXVAD,
  X.BDVALVAD,
  0.00,
  0.00,
  0.00,
  Y.BDBASEIRAD,
  EMP.BDCNPJEMP,
  VERB.BDDESCVER,
  VERB.BDDESCREDVER,
  VERB.BDORDEMVER,
  COLCAD.BDNOMCOL,
  COL.BDDATAADMCOL,
  DOCREF.BDPISCOL,
  COLDOC.BDCPFCOL,
  VERR.BDTIPOCODVER,
  VERR.BDTIPOREFVER,
  COLBANCO.BDCODBAN,
  COLBANCO.BDCODAG,
  COLBANCO.BDCTADEPCOL,
  COLBANCO.BDDIGCTADEPCOL,
  COLBANCO.BDMODOPAGTOCOL,
  COLDIA.BDSALBASECOL,
  X.BDDATAAD

FROM VRHF_EMP_TVERBAAD X
JOIN VRHF_EMP_TADSAL Y ON X.BDCODEMP = Y.BDCODEMP AND X.BDCODCOL = Y.BDCODCOL AND X.BDDATAAD = Y.BDDATAAD
JOIN TEMPRESAS EMP ON X.BDCODEMP = EMP.BDCODEMP
JOIN VRH_BASE_TVERBAS VERB ON X.BDCODVER = VERB.BDCODVER
JOIN VRH_EMP_TCOLCON COL ON X.BDCODEMP = COL.BDCODEMP AND X.BDCODCOL = COL.BDCODCOL
JOIN VRH_EMP_TCOLCON_DOC COLDOC ON X.BDCODEMP = COLDOC.BDCODEMP AND X.BDCODCOL = COLDOC.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF DOCREF ON X.BDCODEMP = DOCREF.BDCODEMP AND X.BDCODCOL = DOCREF.BDCODCOL
JOIN VW_TVERBAS_REF VERR ON X.BDCODVER = VERR.BDCODVER
JOIN VW_VRHF_EMP_TCOLCON_BANCO COLBANCO ON X.BDCODEMP = COLBANCO.BDCODEMP AND X.BDCODCOL = COLBANCO.BDCODCOL
JOIN VW_VRH_EMP_TCOLCON_CALCDIA COLDIA ON X.BDCODEMP = COLDIA.BDCODEMP AND X.BDCODCOL = COLDIA.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON COLCAD.BDCODEMP = X.BDCODEMP AND COLCAD.BDCODCOL = X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VWRH_RELATORIORECIBOC13SAL01 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_RELATORIORECIBOC13SAL01(
BDCODEMP,
BDCODCOL,
BDCODVER,
BDREFFN,
BDREFVC13,
BDREFAUXVC13,
BDVALVC13,
BDSALBASE,
BDBINSS,
BDBFGTS,
BDFGTS,
BDBIRRF,
BDCNPJEMP,
BDDESCVER,
BDDESCREDVER,
BDORDEMVER,
BDNOMCOL,
BDDATAADMCOL,
BDPISCOL,
BDCPFCOL,
BDTIPOCODVER,
BDTIPOREFVER,
BDCODBAN,
BDCODAG,
BDCTADEPCOL,
BDDIGCTADEPCOL,
BDMODOPAGTOCOL,
DBDATAFN)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFC13,
  X.BDREFVC13,
  X.BDREFAUXVC13,
  X.BDVALVC13,
  Y.BDSALBASEC13,
  Y.BDBASEINSSC13,
  Y.BDBASEFGTSC13,
  Y.BDFGTSC13,
  Y.BDBASEIRC13,
  EMP.BDCNPJEMP,
  VERB.BDDESCVER,
  VERB.BDDESCREDVER,
  VERB.BDORDEMVER,
  COLCAD.BDNOMCOL,
  COL.BDDATAADMCOL,
  DOCREF.BDPISCOL,
  COLDOC.BDCPFCOL,
  VERR.BDTIPOCODVER,
  VERR.BDTIPOREFVER,
  COLBANCO.BDCODBAN,
  COLBANCO.BDCODAG,
  COLBANCO.BDCTADEPCOL,
  COLBANCO.BDDIGCTADEPCOL,
  COLBANCO.BDMODOPAGTOCOL,
  X.BDREFC13

FROM VRHF_EMP_TVERBAC13 X
JOIN VRHF_EMP_TC13SAL Y ON X.BDCODEMP = Y.BDCODEMP AND X.BDCODCOL = Y.BDCODCOL AND X.BDREFC13 = Y.BDREFC13
JOIN TEMPRESAS EMP ON X.BDCODEMP = EMP.BDCODEMP
JOIN VRH_BASE_TVERBAS VERB ON X.BDCODVER = VERB.BDCODVER
JOIN VRH_EMP_TCOLCON COL ON X.BDCODEMP = COL.BDCODEMP AND X.BDCODCOL = COL.BDCODCOL
JOIN VRH_EMP_TCOLCON_DOC COLDOC ON X.BDCODEMP = COLDOC.BDCODEMP AND X.BDCODCOL = COLDOC.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF DOCREF ON X.BDCODEMP = DOCREF.BDCODEMP AND X.BDCODCOL = DOCREF.BDCODCOL
JOIN VW_TVERBAS_REF VERR ON X.BDCODVER = VERR.BDCODVER
JOIN VW_VRHF_EMP_TCOLCON_BANCO COLBANCO ON X.BDCODEMP = COLBANCO.BDCODEMP AND X.BDCODCOL = COLBANCO.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON COLCAD.BDCODEMP = X.BDCODEMP AND COLCAD.BDCODCOL = X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VWRH_UNION_FC_FCT_MES (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_UNION_FC_FCT_MES(
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDREFFC,
    BDREFCOMP,
    BDCODVER,
    BDREFVFN_SUM,
    BDREFAUXVFN_SUM,
    BDREFVFN_MAX,
    BDREFAUXVFN_MAX,
    BDVALVFN,
    BDVALIFN,
    BDIGNREFAVFN,
    BDIGNREFVFN,
    BDIGNVALVFN,
    BDORVERBAFC,
    BDCOMPESP,
    BDFORMREFAUX,
    BDFORMREF,
    BDFORMVAL,
    BDALTINT)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDREFFC,
  BDREFCOMP,
  BDCODVER,
  BDREFVFC,
  BDREFAUXVFC,
  BDREFVFC,
  BDREFAUXVFC,
  BDVALVFC,
  BDVALIFC,
  BDIGNREFAVFC,
  BDIGNREFVFC,
  BDIGNVALVFC,
  BDORVERBAFC,
  BDCOMPESP,
  BDFORMREFAUX,
  BDFORMREF,
  BDFORMVAL,
  BDALTINT
FROM
  VRHF_EMP_TVERBAFC

UNION ALL

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFTOMADOR,
  BDREFFC,
  BDREFCOMP,
  BDCODVER,
  SUM(BDREFVFC),
  SUM(BDREFAUXVFC),
  MAX(BDREFVFC),
  MAX(BDREFAUXVFC),
  SUM(BDVALVFC),
  SUM(BDVALIFC),
  MAX(BDIGNREFAVFC),
  MAX(BDIGNREFVFC),
  MAX(BDIGNVALVFC),
  MAX(BDORVERBAVFC),
  MAX(BDCOMPESP),
  MAX(BDFORMREFAUX),
  MAX(BDFORMREF),
  MAX(BDFORMVAL),
  MAX(BDALTINT)
FROM
  VRHF_EMP_TVERBAFCTOMADOR
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFTOMADOR,
  BDREFFC,
  BDREFCOMP,
  BDCODVER
;

CREATE OR ALTER VIEW VWRH_UNION_FCI_FCTI_MES(
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDREFFC,
    BDCODCONTTI,
    BDREFCOMP,
    BDCODVER,
    BDREFVFN_SUM,
    BDREFAUXVFN_SUM,
    BDREFVFN_MAX,
    BDREFAUXVFN_MAX,
    BDVALVFN,
    BDVALIFN,
    BDIGNREFAVFN,
    BDIGNREFVFN,
    BDIGNVALVFN,
    BDORVERBAFC,
    BDCOMPESP,
    BDFORMREFAUX,
    BDFORMREF,
    BDFORMVAL,
    BDALTINT)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDREFFC,
  BDCODCONTTI,
  BDREFCOMP,
  BDCODVER,
  BDREFVFC,
  BDREFAUXVFC,
  BDREFVFC,
  BDREFAUXVFC,
  BDVALVFC,
  BDVALVIFC,
  BDIGNREFAVFC,
  BDIGNREFVFC,
  BDIGNVALVFC,
  BDORVERBAFC,
  BDCOMPESP,
  BDFORMREFAUX,
  BDFORMREF,
  BDFORMVAL,
  BDALTINT
FROM
  VRHF_EMP_TVERBAFCINT

UNION ALL

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFTOMADOR,
  BDREFFC,
  BDCODCONTTI,
  BDREFCOMP,
  BDCODVER,
  SUM(BDREFVFC),
  SUM(BDREFAUXVFC),
  MAX(BDREFVFC),
  MAX(BDREFAUXVFC),
  SUM(BDVALVFC),
  SUM(BDVALVIFC),
  MAX(BDIGNREFAVFC),
  MAX(BDIGNREFVFC),
  MAX(BDIGNVALVFC),
  MAX(BDORVERBAVFC),
  MAX(BDCOMPESP),
  MAX(BDFORMREFAUX),
  MAX(BDFORMREF),
  MAX(BDFORMVAL),
  MAX(BDALTINT)
FROM
  VRHF_EMP_TVERBAFCTOMINT
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFTOMADOR,
  BDREFFC,
  BDCODCONTTI,
  BDREFCOMP,
  BDCODVER
;

/* CREATE OR ALTER VIEW: VWRH_UNION_FC_FCT_MES_BASES (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_UNION_FC_FCT_MES_BASES(
    BDCODEMP,
    BDCODCOL,
    BDREFFN,
    BDREFFC,
    BDREFCOMP,
    BDCODCENTRO,
    BDCODTPCC,
    BDDATABAIXA,
    BDBFGTS,
    BDFGTS,
    BDFGTSCS,
    BDBFGTS13,
    BDFGTS13,
    BDFGTS13CS,
    BDMAIORREM,
    BDBINSS,
    BDALIQINSS,
    BDINSS,
    BDBIRRF,
    BDALIQIRRF,
    BDIRRF,
    BDBINSS13,
    BDALIQINSS13,
    BDINSS13,
    BDBIRRF13,
    BDALIQIRRF13,
    BDIRRF13,
    BDBSALFAM,
    BDSALFAM,
    BDBRAIS,
    BDSALBASE,
    BDDEP,
    BDBINSSFEFOL,
    BDINSSFEFOL,
    BDALIQINSSFEFOL,
    BDCREDITO,
    BDDEBITO,
    BDBFGTSFEFOL,
    BDFGTSFEFOL,
    BDLIQUIDO,
    BDCODEMPREENDIMENTO,
    BDDATAPAGFC,
    BDREFVINCFN,
    BDCODACCONV)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDREFFC,
  BDREFCOMP,
  CAST(NULL AS INTEGER),
  CAST(NULL AS INTEGER),
  BDDATABAIXAFC,
  BDBFGTSFC,
  BDFGTSFC,
  BDFGTSCSFC,
  BDBFGTS13FC,
  BDFGTS13FC,
  BDFGTS13CSFC,
  BDMAIORREMFC,
  BDBINSSFC,
  BDALIQINSSFC,
  BDINSSFC,
  BDBIRRFFC,
  BDALIQIRRFFC,
  BDIRRFFC,
  BDBINSS13FC,
  BDALIQINSS13FC,
  BDINSS13FC,
  BDBIRRF13FC,
  BDALIQIRRF13FC,
  BDIRRF13FC,
  BDBSALFAMFC,
  BDSALFAMFC,
  BDBRAISFC,
  BDSALBASEFC,
  BDDEPFC,
  BDBINSSFEFOLFC,
  BDINSSFEFOLFC,
  BDALIQINSSFEFOLFC,
  BDCREDITOFC,
  BDDEBITOFC,
  BDBFGTSFEFC,
  BDFGTSFEFC,
  BDLIQUIDO,
  null,
  bddatapagfc,
  BDREFVINCFN,
  BDCODACCONV
FROM
  VRHF_EMP_TFOLHACOMP

UNION

SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREFTOMADOR,
  X.BDREFFC,
  X.BDREFCOMP,
  MAX(Y.BDCODCENTRO),
  MAX(Y.BDCODTPCC),
  MAX(X.BDDATABAIXAFC),
  SUM(X.BDBFGTSFC),
  SUM(X.BDFGTSFC),
  SUM(X.BDFGTSCSFC),
  SUM(X.BDBFGTS13FC),
  SUM(X.BDFGTS13FC),
  SUM(X.BDFGTS13CSFC),
  MAX(X.BDMAIORREMFC),
  SUM(X.BDBINSSFC),
  MAX(X.BDALIQINSSFC),
  SUM(X.BDINSSFC),
  SUM(X.BDBIRRFFC),
  MAX(X.BDALIQIRRFFC),
  SUM(X.BDIRRFFC),
  SUM(X.BDBINSS13FC),
  MAX(X.BDALIQINSS13FC),
  SUM(X.BDINSS13FC),
  SUM(X.BDBIRRF13FC),
  MAX(X.BDALIQIRRF13FC),
  SUM(X.BDIRRF13FC),
  SUM(X.BDBSALFAMFC),
  SUM(X.BDSALFAMFC),
  SUM(X.BDBRAISFC),
  MAX(X.BDSALBASEFC),
  MAX(X.BDDEPFC),
  SUM(X.BDBINSSFEFOLFC),
  SUM(X.BDINSSFEFOLFC),
  MAX(X.BDALIQINSSFEFOLFC),
  SUM(X.BDCREDITOFC),
  SUM(X.BDDEBITOFC),
  SUM(X.BDBFGTSFEFC),
  SUM(X.BDFGTSFEFC),
  SUM(X.BDLIQUIDO),
  MAX(Z.BDCODEMPREENDIMENTO),
  x.bddatapagfc,
  X.BDREFVINCFN,
  X.bdcodacconv
FROM
  VRHF_EMP_TFOLTOMCOMP X
JOIN
  VRHF_EMP_TPREPFN Y on (Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDORDEM = X.BDORDEM)
LEFT OUTER JOIN
  VEF_EMP_TCADEMPREENDIMENTO Z on (Z.BDCODEMP = X.BDCODEMP and Z.BDCODCENTRO = Y.BDCODCENTRO and Z.BDCODTPCC = Y.BDCODTPCC)
GROUP BY
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDREFTOMADOR,
  X.BDREFFC,
  X.BDREFCOMP,
  x.bddatapagfc,
  X.BDREFVINCFN,
  X.bdcodacconv
;

/* CREATE OR ALTER VIEW: VWRH_RELATORIORECIBOFOLCOM01 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_RELATORIORECIBOFOLCOM01(
BDCODEMP,
BDCODCOL,
BDCODVER,
BDREFFN,
BDREFFC,
BDREFVFN_SUM,
BDREFVFN_MAX,
BDREFAUXVFN_SUM,
BDREFAUXVFN_MAX,
BDVALVFN,
BDSALBASE,
BDBINSS,
BDBFGTS,
BDFGTS,
BDBIRRF,
BDCNPJEMP,
BDDESCVER,
BDDESCREDVER,
BDORDEMVER,
BDNOMCOL,
BDDATAADMCOL,
BDPISCOL,
BDCPFCOL,
BDTIPOCODVER,
BDTIPOREFVER,
BDCODBAN,
BDCODAG,
BDCTADEPCOL,
BDDIGCTADEPCOL,
BDMODOPAGTOCOL,
BDDATAFN)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFFN,
  X.BDREFFC,
  X.BDREFVFN_SUM,
  X.BDREFVFN_MAX,
  X.BDREFAUXVFN_SUM,
  X.BDREFAUXVFN_MAX,
  X.BDVALVFN,
  Y.BDSALBASE,
  Y.BDBINSS,
  Y.BDBFGTS,
  Y.BDFGTS,
  Y.BDBIRRF,
  EMP.BDCNPJEMP,
  VERB.BDDESCVER,
  VERB.BDDESCREDVER,
  VERB.BDORDEMVER,
  COLCAD.BDNOMCOL,
  COL.BDDATAADMCOL,
  DOCREF.BDPISCOL,
  COLDOC.BDCPFCOL,
  VERR.BDTIPOCODVER,
  VERR.BDTIPOREFVER,
  COLBANCO.BDCODBAN,
  COLBANCO.BDCODAG,
  COLBANCO.BDCTADEPCOL,
  COLBANCO.BDDIGCTADEPCOL,
  COLBANCO.BDMODOPAGTOCOL,
  X.BDREFFC

FROM VWRH_UNION_FC_FCT_MES X
JOIN VWRH_UNION_FC_FCT_MES_BASES Y ON X.BDCODEMP = Y.BDCODEMP AND X.BDCODCOL = Y.BDCODCOL AND X.BDREFFN = Y.BDREFFN AND X.BDREFFC = Y.BDREFFC
JOIN TEMPRESAS EMP ON X.BDCODEMP = EMP.BDCODEMP
JOIN VRH_BASE_TVERBAS VERB ON X.BDCODVER = VERB.BDCODVER
JOIN VRH_EMP_TCOLCON COL ON X.BDCODEMP = COL.BDCODEMP AND X.BDCODCOL = COL.BDCODCOL
JOIN VRH_EMP_TCOLCON_DOC COLDOC ON X.BDCODEMP = COLDOC.BDCODEMP AND X.BDCODCOL = COLDOC.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF DOCREF ON X.BDCODEMP = DOCREF.BDCODEMP AND X.BDCODCOL = DOCREF.BDCODCOL
JOIN VW_TVERBAS_REF VERR ON X.BDCODVER = VERR.BDCODVER
JOIN VW_VRHF_EMP_TCOLCON_BANCO COLBANCO ON X.BDCODEMP = COLBANCO.BDCODEMP AND X.BDCODCOL = COLBANCO.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON COLCAD.BDCODEMP = X.BDCODEMP AND COLCAD.BDCODCOL = X.BDCODCOL
;

/* CREATE OR ALTER VIEW: VWRH_RELATORIORECIBOFOLHA01 (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_RELATORIORECIBOFOLHA01(
BDCODEMP,
BDCODCOL,
BDCODVER,
BDREFFN,
BDREFVFN_SUM,
BDREFVFN_MAX,
BDREFAUXVFN_SUM,
BDREFAUXVFN_MAX,
BDVALVFN,
BDSALBASE,
BDBINSS,
BDBFGTS,
BDFGTS,
BDBIRRF,
BDCNPJEMP,
BDDESCVER,
BDDESCREDVER,
BDORDEMVER,
BDNOMCOL,
BDDATAADMCOL,
BDPISCOL,
BDCPFCOL,
BDTIPOCODVER,
BDTIPOREFVER,
BDCODBAN,
BDCODAG,
BDCTADEPCOL,
BDDIGCTADEPCOL,
BDMODOPAGTOCOL,
BDDATAFN,
BDRG)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCODCOL,
  X.BDCODVER,
  X.BDREFFN,
  X.BDREFVFN_SUM,
  X.BDREFVFN_MAX,
  X.BDREFAUXVFN_SUM,
  X.BDREFAUXVFN_MAX,
  X.BDVALVFN,
  Y.BDSALBASE,
  Y.BDBINSS,
  Y.BDBFGTS,
  Y.BDFGTS,
  Y.BDBIRRF,
  EMP.BDCNPJEMP,
  VERB.BDDESCVER,
  VERB.BDDESCREDVER,
  VERB.BDORDEMVER,
  COLCAD.BDNOMCOL,
  COL.BDDATAADMCOL,
  DOCREF.BDPISCOL,
  COLDOC.BDCPFCOL,
  VERR.BDTIPOCODVER,
  VERR.BDTIPOREFVER,
  COLBANCO.BDCODBAN,
  COLBANCO.BDCODAG,
  COLBANCO.BDCTADEPCOL,
  COLBANCO.BDDIGCTADEPCOL,
  COLBANCO.BDMODOPAGTOCOL,
  X.BDREFFN,
  DOCREF.BDRGCOL

FROM VWRH_UNION_FN_FT_MES X
JOIN VWRH_UNION_FN_FT_MES_BASES Y ON X.BDCODEMP = Y.BDCODEMP AND X.BDCODCOL = Y.BDCODCOL AND X.BDREFFN = Y.BDREFFN
JOIN TEMPRESAS EMP ON X.BDCODEMP = EMP.BDCODEMP
JOIN VRH_BASE_TVERBAS VERB ON X.BDCODVER = VERB.BDCODVER
JOIN VRH_EMP_TCOLCON COL ON X.BDCODEMP = COL.BDCODEMP AND X.BDCODCOL = COL.BDCODCOL
JOIN VRH_EMP_TCOLCON_DOC COLDOC ON X.BDCODEMP = COLDOC.BDCODEMP AND X.BDCODCOL = COLDOC.BDCODCOL
JOIN VW_TVERBAS_REF VERR ON X.BDCODVER = VERR.BDCODVER
JOIN VW_VRHF_EMP_TCOLCON_BANCO COLBANCO ON X.BDCODEMP = COLBANCO.BDCODEMP AND X.BDCODCOL = COLBANCO.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON COLCAD.BDCODEMP = X.BDCODEMP AND COLCAD.BDCODCOL = X.BDCODCOL
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF DOCREF ON X.BDCODEMP = DOCREF.BDCODEMP AND X.BDCODCOL = DOCREF.BDCODCOL
;

--Wesley Kowalski 12/11/2018 | Alterando case
/* CREATE OR ALTER VIEW: VWRH_TRESCISAO_ADM_COL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_TRESCISAO_ADM_COL(
    BDCODEMP,
    BDCODCOL,
    BDDATARESCISAO,
    BDNOVADATARESCISAO,
    BDCODPRES,
    BDNOVOCODPRES,
    BDDATAAVPREVIO,
    BDDATAHOM,
    BDDATAPAGRESCISAO,
    BDSALDOFGTS,
    BDCALCFGTSMESANT,
    BDMAIORREMUNERACAO,
    BDCHAVEINDENTIFICACAO,
    BDDATAPAGGRFC,
    BDREPOSICAOVAGA,
    BDDISSIDIO,
    BDDATADISSIDIO,
    BDDESCANSOINDENIZADO,
    BDREFRESCISAO,
    BDDISPAVPREVRESC,
    BDNOVOEMPRESC,
    BDPERTRCTRESC,
    BDPERFGTSRESC,
    BDTIPOADMCOL,
    BDNATUOCUPCOL,
    BDDATAINIAQUICOL,
    BDSALINICOL,
    BDDIASPRAZO1COL,
    BDDATAFIMPRAZO1COL,
    BDDIASPRAZO2COL,
    BDDATAFIMPRAZO2COL,
    BDDESCCONTSINCOL,
    BDVINCEMPCOL,
    BDALVARACOL,
    BDSINDICALIZADOCOL,
    BDREGIMEPARCIALCOL,
    BDFICHAREGCOL,
    BDLIVROREGCOL,
    BDNROFOLHAREGCOL,
    BDCONTRCOL,
    BDCODTIPOCONTRATO,
    BDDATANOTIF,
    BDDATAOPCAOFGTS,
    BDPERCGORJ)
AS
SELECT
    RESC.BDCODEMP,
    RESC.BDCODCOL,
    RESC.BDDATARESCISAO,
    RESC.bdnovadatarescisao,
    RESC.BDCODPRES,
    RESC.bdnovocodpres,
    RESC.BDDATAAVPREVIO,
    RESC.BDDATAHOM,
    RESC.BDDATAPAGRESCISAO,
    RESC.BDSALDOFGTS,
    RESC.BDCALCFGTSMESANT,
    RESC.BDMAIORREMUNERACAO,
    RESC.BDCHAVEINDENTIFICACAO,
    RESC.BDDATAPAGGRFC,
    RESC.BDREPOSICAOVAGA,
    RESC.BDDISSIDIO,
    RESC.BDDATADISSIDIO,
    RESC.BDDESCANSOINDENIZADO,
    RESC.BDREFRESCISAO,
    RESC.BDDISPAVPREVRESC,
    RESC.BDNOVOEMPRESC,
    RESC.BDPERTRCTRESC,
    RESC.BDPERFGTSRESC,
    adm.BDTIPOADMCOL,
    adm.BDNATUOCUPCOL,
    adm.BDDATAINIAQUICOL,
    adm.BDSALINICOL,
    adm.BDDIASPRAZO1COL,
    adm.BDDATAFIMPRAZO1COL,
    adm.BDDIASPRAZO2COL,
    adm.BDDATAFIMPRAZO2COL,
    adm.BDDESCCONTSINCOL,
    admref.BDVINCEMPCOL,
    admref.BDALVARACOL,
    admref.BDSINDICALIZADOCOL,
    CALC.BDREGIMEPARCIALCOL,
    adm.BDFICHAREGCOL,
    adm.BDLIVROREGCOL,
    adm.BDNROFOLHAREGCOL,
    adm.BDCONTRCOL,
    COALESCE(PAR.bdcodtipocontrato,1) BDCODTIPOCONTRATO,    
    RESC.BDDATANOTIF,
    fgts.bddataopcaofgtscol,
    CALC.BDPERCGORJ
FROM
  VRH_EMP_TRESCISAO RESC
LEFT OUTER JOIN VW_VRH_EMP_TCOL_ADM adm ON (adm.bdcodemp = RESC.bdcodemp AND adm.bdcodcol = RESC.bdcodcol)
LEFT OUTER JOIN VW_VRH_EMP_TCOL_ADMREF ADMREF ON (ADMREF.BDCODEMP = RESC.BDCODEMP AND ADMREF.BDCODCOL = RESC.BDCODCOL)
LEFT OUTER JOIN VW_VRHF_EMP_TCOLCON_FGTSGPS FGTS ON (FGTS.BDCODEMP = RESC.BDCODEMP AND FGTS.BDCODCOL = RESC.BDCODCOL)
LEFT OUTER JOIN VW_VRHF_EMP_TCOL_CALC CALC ON (CALC.BDCODEMP = RESC.BDCODEMP AND CALC.BDCODCOL = RESC.BDCODCOL)
LEFT OUTER JOIN vrh_emp_tcolcon_partida PAR ON (PAR.BDCODEMP = ADM.BDCODEMP AND PAR.BDCODCOL = ADM.BDCODCOL)
;

/* CREATE OR ALTER VIEW: VWRH_UNION_FC_FCT_CALC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_UNION_FC_FCT_CALC(
BDCODEMP,
BDCODCOL,
BDREFFN,
BDDTCOMP,
BDCODVER,
BDREFVFN_SUM,
BDREFAUXVFN_SUM,
BDREFVFN_MAX,
BDREFAUXVFN_MAX,
BDVALVFN,
BDIGNREFVFN,
BDIGNVALVFN)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDREFFC,
  BDCODVER,
  BDREFVFC,
  BDREFAUXVFC,
  BDREFVFC,
  BDREFAUXVFC,
  BDVALVFC,
  BDIGNREFVFC,
  BDIGNVALVFC
FROM
  VRHF_EMP_TVERBAFC

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFTOMADOR,
  BDREFFC,
  BDCODVER,
  SUM(BDREFVFC),
  SUM(BDREFAUXVFC),
  MAX(BDREFVFC),
  MAX(BDREFAUXVFC),
  SUM(BDVALVFC),
  MAX(BDIGNREFVFC),
  MAX(BDIGNVALVFC)
FROM
  VRHF_EMP_TVERBAFCTOMADOR
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFTOMADOR,
  BDREFFC,
  BDCODVER
;

/* CREATE OR ALTER VIEW: VWRH_UNION_FC_FCT_MESFN (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_UNION_FC_FCT_MESFN(
BDCODEMP,
BDCODCOL,
BDREFFN,
BDCODVER,
BDREFVFN_SUM,
BDREFAUXVFN_SUM,
BDREFVFN_MAX,
BDREFAUXVFN_MAX,
BDVALVFN,
BDIGNREFVFN,
BDIGNVALVFN)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDCODVER,
  SUM(BDREFVFC),
  SUM(BDREFAUXVFC),
  MAX(BDREFVFC),
  MAX(BDREFAUXVFC),
  SUM(BDVALVFC),
  MAX(BDIGNREFVFC),
  MAX(BDIGNVALVFC)
FROM
  VRHF_EMP_TVERBAFC
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDCODVER


UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFTOMADOR,
  BDCODVER,
  SUM(BDREFVFC),
  SUM(BDREFAUXVFC),
  MAX(BDREFVFC),
  MAX(BDREFAUXVFC),
  SUM(BDVALVFC),
  MAX(BDIGNREFVFC),
  MAX(BDIGNVALVFC)
FROM
  VRHF_EMP_TVERBAFCTOMADOR
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFTOMADOR,
  BDCODVER
;

/* CREATE OR ALTER VIEW: VWRH_UNION_FICHAHE_TREEVIEW (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_UNION_FICHAHE_TREEVIEW(
    BDCODEMP,
    BDCODCOL,
    BDREFFHE)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN
FROM
  VWRH_UNION_FN_FT_MES_BASES
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFN

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN
FROM
  VWRH_UNION_FI_FTI_MES_BASES
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFN

UNION

SELECT
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  HE.BDREFFN
FROM VRH_EMP_TTRANSCOL TRANS
LEFT OUTER JOIN VWRH_UNION_FN_FT_MES_BASES HE ON (HE.BDCODEMP = TRANS.BDCODEMPORIG AND HE.BDCODCOL = TRANS.BDCODCOLORIG)
WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
AND HE.BDREFFN = TRANS.BDREFTRF
GROUP BY
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  HE.BDREFFN

UNION

SELECT
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  HE.BDREFFN
FROM VRH_EMP_TTRANSCOL TRANS
LEFT OUTER JOIN VWRH_UNION_FI_FTI_MES_BASES HE ON (HE.BDCODEMP = TRANS.BDCODEMPORIG AND HE.BDCODCOL = TRANS.BDCODCOLORIG)
WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
AND HE.BDREFFN = TRANS.BDREFTRF
GROUP BY
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  HE.BDREFFN

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN
FROM
  VWRH_UNION_FC_FCT_MES_BASES
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFN

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  CAST((SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) BDREFFN
FROM
  VRHF_EMP_TFOLHAAVULSA
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFN

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFHE
FROM
   VRHF_EMP_TFICHAHE
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFHE
;

/* CREATE OR ALTER VIEW: VWRH_UNION_FICHAHN_TREEVIEW (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_UNION_FICHAHN_TREEVIEW(
    BDCODEMP,
    BDCODCOL,
    BDREFFHN)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN
FROM
  VWRH_UNION_FN_FT_MES_BASES
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFN

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN
FROM
  VWRH_UNION_FI_FTI_MES_BASES
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFN

UNION

SELECT
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  HN.BDREFFN
FROM VRH_EMP_TTRANSCOL TRANS
LEFT OUTER JOIN VWRH_UNION_FN_FT_MES_BASES HN ON (HN.BDCODEMP = TRANS.BDCODEMPORIG AND HN.BDCODCOL = TRANS.BDCODCOLORIG)
WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
AND HN.BDREFFN = TRANS.BDREFTRF
GROUP BY
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  HN.BDREFFN

UNION

SELECT
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  HN.BDREFFN
FROM VRH_EMP_TTRANSCOL TRANS
LEFT OUTER JOIN VWRH_UNION_FI_FTI_MES_BASES HN ON (HN.BDCODEMP = TRANS.BDCODEMPORIG AND HN.BDCODCOL = TRANS.BDCODCOLORIG)
WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
AND HN.BDREFFN = TRANS.BDREFTRF
GROUP BY
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  HN.BDREFFN

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFHN
FROM
   VRHF_EMP_TFICHAHN
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFHN
;

/* CREATE OR ALTER VIEW: VWRH_UNION_FICHAOT_TREEVIEW (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_UNION_FICHAOT_TREEVIEW(
    BDCODEMP,
    BDCODCOL,
    BDREFFOT)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN
FROM
  VWRH_UNION_FN_FT_MES_BASES
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFN

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN
FROM
  VWRH_UNION_FI_FTI_MES_BASES
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFN

UNION

SELECT
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  OT.BDREFFN
FROM VRH_EMP_TTRANSCOL TRANS
LEFT OUTER JOIN VWRH_UNION_FN_FT_MES_BASES OT ON (OT.BDCODEMP = TRANS.BDCODEMPORIG AND OT.BDCODCOL = TRANS.BDCODCOLORIG)
WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
AND OT.BDREFFN = TRANS.BDREFTRF
GROUP BY
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  OT.BDREFFN

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN
FROM
  VWRH_UNION_FC_FCT_MES_BASES
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFN

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  CAST((SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) BDREFFN
FROM
  VRHF_EMP_TFOLHAAVULSA
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFN

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFOT
FROM
   VRHF_EMP_TFICHAOUTRAS
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFOT
;

/* CREATE OR ALTER VIEW: VWRH_UNION_FICHARV_TREEVIEW (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_UNION_FICHARV_TREEVIEW(
    BDCODEMP,
    BDCODCOL,
    BDREFFRV)
AS
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN
FROM
  VWRH_UNION_FN_FT_MES_BASES
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFN

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN
FROM
  VWRH_UNION_FI_FTI_MES_BASES
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFN

UNION

SELECT
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  RV.BDREFFN
FROM VRH_EMP_TTRANSCOL TRANS
LEFT OUTER JOIN VWRH_UNION_FN_FT_MES_BASES RV ON (RV.BDCODEMP = TRANS.BDCODEMPORIG AND RV.BDCODCOL = TRANS.BDCODCOLORIG)
WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
AND RV.BDREFFN = TRANS.BDREFTRF
GROUP BY
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  RV.BDREFFN

UNION

SELECT
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  RV.BDREFFN
FROM VRH_EMP_TTRANSCOL TRANS
LEFT OUTER JOIN VWRH_UNION_FI_FTI_MES_BASES RV ON (RV.BDCODEMP = TRANS.BDCODEMPORIG AND RV.BDCODCOL = TRANS.BDCODCOLORIG)
WHERE SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(TRANS.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2) = TRANS.BDREFTRF
AND RV.BDREFFN = TRANS.BDREFTRF
GROUP BY
  TRANS.BDCODEMPDEST,
  TRANS.BDCODCOLDEST,
  RV.BDREFFN

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFRV
FROM
   VRHF_EMP_TFICHARV
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFFRV
;

/* CREATE OR ALTER VIEW: VWRH_UNION_FN_FT_LIQ_MES (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_UNION_FN_FT_LIQ_MES(
BDCODEMP,
BDCODCOL,
BDREFFN,
BDCODVER,
BDREFVFN_SUM,
BDREFAUXVFN_SUM,
BDREFVFN_MAX,
BDREFAUXVFN_MAX,
BDVALVFN,
BDIGNREFVFN,
BDIGNVALVFN,
BDORVERBA,
BDCOMPESP,
BDFORMREFAUX,
BDFORMREF,
BDFORMVAL)
 AS 
SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDCODVER,
  BDREFVFN,
  BDREFAUXVFN,
  BDREFVFN,
  BDREFAUXVFN,
  BDVALVFN,
  BDIGNREFVFN,
  BDIGNVALVFN,
  BDORVERBAFN,
  BDCOMPESP,
  BDFORMREFAUX,
  BDFORMREF,
  BDFORMVAL
FROM
  VRHF_EMP_TVERBAFN

UNION

SELECT
  BDCODEMP,
  BDCODCOL,
  BDREFTOMADOR,
  BDCODVER,
  SUM(BDREFVFT),
  SUM(BDREFAUXVFT),
  MAX(BDREFVFT),
  MAX(BDREFAUXVFT),
  SUM(BDVALVFT),
  MAX(BDIGNREFVFT),
  MAX(BDIGNVALVFT),
  MAX(BDORVERBAFT),
  BDCOMPESP,
  BDFORMREFAUX,
  BDFORMREF,
  BDFORMVAL
FROM
  VRHF_EMP_TVERBATOMADOR
GROUP BY
  BDCODEMP,
  BDCODCOL,
  BDREFTOMADOR,
  BDCODVER,
  BDCOMPESP,
  BDFORMREFAUX,
  BDFORMREF,
  BDFORMVAL
;

/* CREATE OR ALTER VIEW: VWRH_UNION_FNPR_FTPR_MES (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_UNION_FNPR_FTPR_MES(
    BDCODEMP,
    BDCODCOL,
    BDCODVER,
    BDREFVFN_SUM,
    BDREFAUXVFN_SUM,
    BDREFVFN_MAX,
    BDREFAUXVFN_MAX,
    BDVALVFN,
    BDIGNREFAVFN,
    BDIGNREFVFN,
    BDIGNVALVFN,
    BDREFFN,
    BDFORMREFAUX,
    BDFORMREF,
    BDFORMVAL,
    BDCOMPESP,
    BDALTINT)
AS
SELECT
  VPR.BDCODEMP,
  VPR.BDCODCOL,
  VPR.BDCODVER,
  VPR.BDREFVFNPR,
  VPR.BDREFAUXVFNPR,
  VPR.BDREFVFNPR,
  VPR.BDREFAUXVFNPR,
  VPR.BDVALVFNPR,
  VPR.BDIGNREFAVFNPR,
  VPR.BDIGNREFVFNPR,
  VPR.BDIGNVALVFNPR,
  REF.BDREF,
  VPR.BDFORMREFAUX,
  VPR.BDFORMREF,
  VPR.BDFORMVAL,
  VPR.BDCOMPESP,
  VPR.BDALTINT
FROM
  VRHF_EMP_TVERBAFN_PREV_RESC VPR,
  (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER) BDREF FROM rdb$database) REF


UNION


SELECT
  VPR.BDCODEMP,
  VPR.BDCODCOL,
  VPR.BDCODVER,
  SUM(VPR.BDREFVFTPR),
  SUM(VPR.BDREFAUXVFTPR),
  MAX(VPR.BDREFVFTPR),
  MAX(VPR.BDREFAUXVFTPR),
  SUM(VPR.BDVALVFTPR),
  MAX(VPR.BDIGNREFAVFTPR),
  MAX(VPR.BDIGNREFVFTPR),
  MAX(VPR.BDIGNVALVFTPR),
  REF.BDREF,
  VPR.BDFORMREFAUX,
  VPR.BDFORMREF,
  VPR.BDFORMVAL,
  VPR.BDCOMPESP,
  MAX(VPR.BDALTINT)
FROM
  VRHF_EMP_TVERBAFT_PREV_RESC VPR,
  (SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))) AS INTEGER) BDREF FROM rdb$database) REF
GROUP BY
  VPR.BDCODEMP,
  VPR.BDCODCOL,
  VPR.BDCODVER,
  REF.BDREF,
  VPR.BDFORMREFAUX,
  VPR.BDFORMREF,
  VPR.BDFORMVAL,
  VPR.BDCOMPESP
;

/* CREATE OR ALTER VIEW: VWRH_UNION_MES_BASES (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_UNION_MES_BASES(
BDTIPO,
BDCODEMP,
BDCODCOL,
BDREFFN,
BDCODCENTRO,
BDCODTPCC,
BDDATABAIXA,
BDBFGTS,
BDFGTS,
BDFGTSCS,
BDBFGTS13,
BDFGTS13,
BDFGTS13CS,
BDMAIORREM,
BDBINSS,
BDALIQINSS,
BDINSS,
BDBIRRF,
BDALIQIRRF,
BDIRRF,
BDBINSS13,
BDALIQINSS13,
BDINSS13,
BDBIRRF13,
BDALIQIRRF13,
BDIRRF13,
BDBSALFAM,
BDSALFAM,
BDBRAIS,
BDSALBASE,
BDDEP,
BDBINSSFEFOL,
BDINSSFEFOL,
BDALIQINSSFEFOL,
BDCREDITO,
BDDEBITO,
BDBFGTSFEFOL,
    BDFGTSFEFOL,
    BDCODEMPREENDIMENTO)
 AS 
SELECT
  0 BDTIPO,
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDCODCENTRO,
  BDCODTPCC,
  BDDATABAIXA,
  BDBFGTS,
  BDFGTS,
  BDFGTSCS,
  BDBFGTS13,
  BDFGTS13,
  BDFGTS13CS,
  BDMAIORREM,
  BDBINSS,
  BDALIQINSS,
  BDINSS,
  BDBIRRF,
  BDALIQIRRF,
  BDIRRF,
  BDBINSS13,
  BDALIQINSS13,
  BDINSS13,
  BDBIRRF13,
  BDALIQIRRF13,
  BDIRRF13,
  BDBSALFAM,
  BDSALFAM,
  BDBRAIS,
  BDSALBASE,
  BDDEP,
  BDBINSSFEFOL,
  BDINSSFEFOL,
  BDALIQINSSFEFOL,
  BDCREDITO,
  BDDEBITO,
  BDBFGTSFEFOL,
  BDFGTSFEFOL,
  BDCODEMPREENDIMENTO
FROM
  VWRH_UNION_FN_FT_MES_BASES

UNION

SELECT
  1 BDTIPO,
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDCODCENTRO,
  BDCODTPCC,
  BDDATABAIXA,
  BDBFGTS,
  BDFGTS,
  BDFGTSCS,
  BDBFGTS13,
  BDFGTS13,
  BDFGTS13CS,
  BDMAIORREM,
  BDBINSS,
  BDALIQINSS,
  BDINSS,
  BDBIRRF,
  BDALIQIRRF,
  BDIRRF,
  BDBINSS13,
  BDALIQINSS13,
  BDINSS13,
  BDBIRRF13,
  BDALIQIRRF13,
  BDIRRF13,
  BDBSALFAM,
  BDSALFAM,
  BDBRAIS,
  BDSALBASE,
  BDDEP,
  BDBINSSFEFOL,
  BDINSSFEFOL,
  BDALIQINSSFEFOL,
  BDCREDITO,
  BDDEBITO,
  BDBFGTSFEFOL,
  BDFGTSFEFOL,
  BDCODEMPREENDIMENTO
FROM
  VWRH_UNION_FC_FCT_MES_BASES
;

/* CREATE OR ALTER VIEW: VWRH_UNION_MES_VERBAS (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWRH_UNION_MES_VERBAS(
BDTIPO,
BDCODEMP,
BDCODCOL,
BDREFFN,
BDCODVER,
BDREFVFN_SUM,
BDREFAUXVFN_SUM,
BDREFVFN_MAX,
BDREFAUXVFN_MAX,
BDVALVFN,
BDIGNREFVFN,
BDIGNREFAVFN,
BDIGNVALVFN)
 AS 
SELECT
  0,
  BDCODEMP,
  BDCODCOL,
  BDREFFN,
  BDCODVER,
  BDREFVFN_SUM,
  BDREFAUXVFN_SUM,
  BDREFVFN_MAX,
  BDREFAUXVFN_MAX,
  BDVALVFN,
  BDIGNREFVFN,
  BDIGNREFAVFN,
  BDIGNVALVFN
FROM
  VWRH_UNION_FN_FT_MES

UNION

SELECT
  1,
  BDCODEMP,
  BDCODCOL,
  BDREFCOMP,
  BDCODVER,
  BDREFVFN_SUM,
  BDREFAUXVFN_SUM,
  BDREFVFN_MAX,
  BDREFAUXVFN_MAX,
  BDVALVFN,
  BDIGNREFVFN,
  BDIGNREFAVFN,
  BDIGNVALVFN
FROM
  VWRH_UNION_FC_FCT_MES
;

/* alt. 14203 - Incluído o campo de retorno BDVLROUTENTIDADE com a verificação COALESCE para não retornar nulo. - Bruno L. R. */
/* CREATE OR ALTER VIEW: VWSCI_DADOS_DARFIMP (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWSCI_DADOS_DARFIMP(
BDCODEMP,
BDCHAVEDARF,
BDCODIMP,
BDREFERENCIA,
BDCODCOL,
BDCODEMPCOL,
BDCODCENTRO,
BDCODTPCC,
BDVALOR,
BDMULTA,
BDJUROS,
BDTOTAL,
BDCODSINTRAB,
BDCODSINPAT,
BDDESCIMP,
BDCODREC,
BDCODRECOUTENT,
BDCODSIS,
BDNOMEMP,
BDCODRECOF,
BDVLROUTENTIDADE)
 AS 
SELECT
  X.BDCODEMP,
  X.BDCHAVEDARF,
  X.BDCODIMP,
  CAST((SUBSTRING(CAST(X.BDREFERENCIA AS VARCHAR(8)) FROM 1 FOR 6)) AS INTEGER),
  X.BDCODCOL,
  X.BDCODEMPCOL,
  X.BDCODCENTRO,
  X.BDCODTPCC,
  COALESCE(X.BDVALOR, 0.00),
  COALESCE(X.BDMULTA, 0.00),
  COALESCE(X.BDJUROS, 0.00),
  COALESCE(X.BDTOTAL, 0.00),
  X.BDCODSINTRAB,
  X.BDCODSINPAT,
  Y.BDDESCIMP,
  Y.BDCODREC,
  Y.BDCODRECOUTENT,
  Y.BDCODSIS,
  EMPR.BDNOMEMP,
  TREC.BDCODRECOF,
  COALESCE(X.BDVLROUTENTIDADE, 0.00)
FROM TDARFPADRAO X
JOIN TIMPOSTO Y ON (Y.BDCODIMP = X.BDCODIMP)
JOIN VW_TEMPRESAS_REF EMPR ON (EMPR.BDCODEMP = X.BDCODEMP)
LEFT OUTER JOIN tcodrec TREC ON (TREC.BDCODREC = Y.bdcodrec)
;

/* alt. 14203 - Somado o valor do campo BDVLROUTENTIDADE no campo de retorno BDTOTAL e no campo de retorno BDVALOR. - Bruno L. R. */
/*Wesley Kowalski - 02/04/2018 - Solciitação: 23205 -  Alterado ultimo JOIN(JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON (COLCAD.BDCODEMP = COLCON.BDCODEMP AND COLCAD.BDCODCOL = COLCON.BDCODCOL)) para LEFT OUTER JOIN*/
/* CREATE OR ALTER VIEW: VWSCI_DADOS_DARFIMP_RELATORIO (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWSCI_DADOS_DARFIMP_RELATORIO(
    BDCODEMP,
    BDNOMEMP,
    BDCODIMP,
    BDREFERENCIA,
    BDCODCOL,
    BDCODEMPCOL,
    BDCODCENTRO,
    BDCODTPCC,
    BDVALOR,
    BDMULTA,
    BDJUROS,
    BDTOTAL,
    BDCODSINTRAB,
    BDCODSINPAT,
    BDDESCIMP,
    BDCODREC,
    BDCODRECOUTENT,
    BDCODSIS,
    BDCODPGTO,
    BDDATAPGTO,
    BDVLRPGTO,
    BDNOMCOL,
    BDNOMCTA,
    BDDESCSINTRAB,
    BDCNPJSINTRAB,
    BDDESCSINPAT,
    BDCNPJSINPAT,
    BDDESCREC,
    BDDESCREC_OE,
    BDCODRECOF)
AS
SELECT
  DARFP.BDCODEMP,
  DARFP.BDNOMEMP,
  DARFP.BDCODIMP,
  DARFP.BDREFERENCIA,
  DARFP.BDCODCOL,
  DARFP.BDCODEMPCOL,
  DARFP.BDCODCENTRO,
  DARFP.BDCODTPCC,
  DARFP.BDVALOR + DARFP.BDVLROUTENTIDADE BDVALOR,
  DARFP.BDMULTA,
  DARFP.BDJUROS,
  DARFP.BDVALOR + DARFP.BDMULTA + DARFP.BDJUROS + DARFP.BDVLROUTENTIDADE BDTOTAL,
  DARFP.BDCODSINTRAB,
  DARFP.BDCODSINPAT,
  DARFP.BDDESCIMP,
  DARFP.BDCODREC,
  DARFP.BDCODRECOUTENT,
  DARFP.BDCODSIS,
  DARFG.BDCODPGTO,
  DARFG.BDDATAPGTO,
  DARFG.BDVLRPGTO,
  COLCAD.BDNOMCOL,
  TPCC.BDNOMCTA,
  SINDT.BDDESCSINTRAB,
  SINDT.BDCNPJSINTRAB,
  SINDP.BDDESCSINPAT,
  SINDP.BDCNPJSINPAT,
  TREC.BDDESCREC,
  TRECOE.BDDESCREC,
  TREC.bdcodrecof

FROM VWSCI_DADOS_DARFIMP DARFP
LEFT OUTER JOIN TDARFGERPGTO DARFG ON (DARFP.BDCODEMP = DARFG.BDCODEMP AND DARFP.BDCHAVEDARF = DARFG.BDCHAVEDARF)
LEFT OUTER JOIN VRH_EMP_TCOLCON COLCON ON (DARFP.BDCODEMPCOL = COLCON.BDCODEMP AND DARFP.BDCODCOL = COLCON.BDCODCOL)
LEFT OUTER JOIN CENTROS_TPCC TPCC ON (DARFP.BDCODCENTRO = TPCC.BDCODCENTRO AND DARFP.BDCODTPCC = TPCC.BDCODTPCC)
LEFT OUTER JOIN VRH_BASE_TSINDTRAB SINDT ON (DARFP.BDCODSINTRAB = SINDT.BDCODSINTRAB)
LEFT OUTER JOIN VRHF_BASE_TSINDPATRONAL SINDP ON (DARFP.BDCODSINPAT = SINDP.BDCODSINPAT)
LEFT OUTER JOIN TCODREC TREC ON (DARFP.BDCODREC = TREC.BDCODREC)
LEFT OUTER JOIN TCODREC TRECOE ON (DARFP.BDCODRECOUTENT = TRECOE.BDCODREC)
LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON (COLCAD.BDCODEMP = COLCON.BDCODEMP AND COLCAD.BDCODCOL = COLCON.BDCODCOL)
;

/* CREATE OR ALTER VIEW: VWSCI_EMPMENSAL_ABA_ADIC (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWSCI_EMPMENSAL_ABA_ADIC(
    BDCODEMP,
    BDREFEMP,
    BDCODCNAE,
    BDCODNATJUR,
    BDDESCCNAE,
    BDDESCNAT,
    BDORGAOEMP,
    BDDESCCARTEMPREF,
    BDDATAREGEMP,
    BDNOMECARTORIO,
    BDLIVRO,
    BDFOLHA,
    BDCARACTRIBUTARIA,
    BDIAT_PISCOF_SEM_ICMS)
AS
SELECT
  EMPR.BDCODEMP,
  EMPR.BDREFEMP,
  EMPR.BDCODCNAE,
  EMPR.BDCODNATJUR,
  CNAE.BDDESCCNAE,
  NATJUR.BDDESCNAT,
  EMPR.bdorgaoemp,
  EMPR.bddesccartempref,
  empr.bddataregemp,
  empr.bdnomecartorio, 
  empr.bdlivro, 
  empr.bdfolha,
  EMPR.BDCARACTRIBUTARIA,
  EMPR.BDIAT_PISCOF_SEM_ICMS
FROM
  TEMPRESAS_REF EMPR
LEFT OUTER JOIN TCNAE CNAE ON (EMPR.BDCODCNAE = CNAE.BDCODCNAE)
LEFT OUTER JOIN TNATJUR NATJUR ON (EMPR.BDCODNATJUR = NATJUR.BDCODNATJUR)
;

/* CREATE OR ALTER VIEW: VWSCI_EMPMENSAL_ABA_ESOCIAL (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWSCI_EMPMENSAL_ABA_ESOCIAL(
    BDCODEMP,
    BDREFEMP,
    BDCODCLATRI,
    BDDESCCLATRI,
    BDESCOOPERATIVA,
    BDESCONSTRUTORA,
    BDESFGTSFIN,
    BDESDEBAUTFGTS,
    BDESAGERECFGTS,
    BDESSMSRESP,
    BDAPURAT,
    BDAPUFAP,
    BDACINTISENMULTA,
    BDSOCOSTCONTAPART,
    BDINDSITESPECIAL,
    BDOPCAOESOCIAL,
    BDINDCCONTRAAPRENDIZ,
    BDINDCCONTRAPCD,
    BDINDICATIVOREGELETR,
    BDRELPORINTERM,
    BDENTIDADEPAA)
AS
select X.BDCODEMP, X.BDREFEMP, X.BDCODCLATRI, Y.BDDESCCLATRI,
       case
         when X.BDESCOOPERATIVA = 0 then 'Não '
         when X.BDESCOOPERATIVA = 1 then 'De trabalho'
         when X.BDESCOOPERATIVA = 2 then 'De produção'
         when X.BDESCOOPERATIVA = 3 then 'Outras'
         else 'Não informado'
       end BDESCOOPERATIVA,
       X.BDESCONSTRUTORA, X.BDESFGTSFIN, X.BDESDEBAUTFGTS, X.BDESAGERECFGTS, X.BDESSMSRESP,
       case
         when X.BDAPURAT = 1 then 'CNAE preponderante de cada estabelecimento'
         else 'CNAE preponderante da empresa'
       end BDAPURAT,
       case
         when X.BDAPUFAP = 1 then 'FAP atribuído à cada estabelecimento'
         else 'FAP atribuído à empresa'
       end BDAPUFAP,
       case
         when X.BDACINTISENMULTA = 1 then 'Com acordo'
         else 'Sem acordo'
       end BDACINTISENMULTA,
       X.BDSOCOSTCONTAPART,
       case
         when X.BDINDSITESPECIAL = 1 then 'Extinção'
         when X.BDINDSITESPECIAL = 2 then 'Fusão'
         when X.BDINDSITESPECIAL = 3 then 'Cisão'
         when X.BDINDSITESPECIAL = 4 then 'Incorporação'
         else 'Situação normal'
       end BDINDSITESPECIAL,
       COALESCE(T.BDDESCRICAO,'Nenhum')   ,
       case
         when X.BDINDCCONTRAAPRENDIZ = 0 then 'Não informado'
         when X.BDINDCCONTRAAPRENDIZ = 1 then 'Dispensado de acordo com a lei'
         when X.BDINDCCONTRAAPRENDIZ = 2 then 'Dispensado, mesmo que parcialmente, em virtude de processo judicial'
         when X.BDINDCCONTRAAPRENDIZ = 3 then 'Obrigado'
       end BDINDCCONTRAAPRENDIZ,
       case
         when coalesce(X.BDINDCCONTRAPCD, 0) = 0 then 'Não informado'
         when X.BDINDCCONTRAPCD = 1 then 'Dispensado de acordo com a lei'
         when X.BDINDCCONTRAPCD = 2 then 'Dispensado, mesmo que parcialmente, em virtude de processo judicial'
         when X.BDINDCCONTRAPCD = 3 then 'Com exigibilidade de suspensa, mesmo que parcialmente em virtude de Termo de Compromisso  firmado com o Ministério do Trabalho'
         when X.BDINDCCONTRAPCD = 4 then 'Obrigado'
       end BDINDCCONTRAPCD,
       case
         when coalesce(X.BDINDICATIVOREGELETR, 0) = 0 then 'Não informado'
         when X.BDINDICATIVOREGELETR = 1 then 'Não optou pelo registro eletrônico de empregados'
         when X.BDINDICATIVOREGELETR = 2 then 'Optou pelo registro eletrônico de empregados'
       end BDINDICATIVOREGELETR,
       case
         when coalesce(X.BDRELPORINTERM, 'FALSE') = 'FALSE' then 'NÃO'
         when X.BDRELPORINTERM = 'TRUE' then 'SIM'
       end BDRELPORINTERM,
       case
         when coalesce(R.BDENTIDADEPAA, 'FALSE') = 'FALSE' then 'NÃO'
         when R.BDENTIDADEPAA = 'TRUE' then 'SIM'
       end BDENTIDADEPAA
from VRHF_BASE_TEMPESOCIAL X
LEFT OUTER JOIN VRH_BASE_CLASSTRIBUTARIA Y ON (Y.BDCODCLATRI = X.BDCODCLATRI)
LEFT OUTER JOIN TEMPRESAS_REF R ON R.BDCODEMP = X.BDCODEMP AND R.BDREFEMP = X.BDREFEMP
LEFT OUTER JOIN VRH_ESOCIAL_TFASEAMENTO F ON F.BDCODEMP = X.BDCODEMP
LEFT OUTER JOIN VRH_ESOCIAL_TTIPODADOS T on T.BDOPCAOESOCIAL = F.BDOPCAOESOCIAL
;

CREATE OR ALTER VIEW VW_TFK_MANUAL(
    BDTABELA,
    BDTABLE,
    BDCODIGO1,
    BDCODIGO2,
    BDTABELAFK,
    BDCOUNT,
    BDTABLEFK)
AS
SELECT MAN.BDTABELA, TAB.BDTABLE, MAN.BDCODIGO1, MAN.BDCODIGO2, MAN.BDTABELAFK, MAN.BDCOUNT, TABFK.BDTABLE AS BDTABLE
FROM TFK_MANUAL MAN
LEFT OUTER JOIN TDESC_TABLE_BANCO TAB ON (TAB.BDCHAVE = MAN.BDTABELA)
LEFT OUTER JOIN TDESC_TABLE_BANCO TABFK ON (TABFK.BDCHAVE = MAN.BDTABELAFK)
;

CREATE OR ALTER VIEW VWGR_SCI_EMPRESAS(
    BDCODEMP,
    BDCODMATRIZ,
    BDCNPJEMP,
    BDDATAINIATIVEMP,
    BDORGAOEMP,
    BDDATAREGEMP,
    BDDATACONSTEMP,
    BDDESCCARTEMP,
    BDDATAFIMATIVEMP,
    BDREFEMP,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDCODCENTROS,
    BDCODPLATRIB,
    BDCODCID,
    BDCODCONT,
    BDCODNATJUR,
    BDCODCNAE,
    BDNOMEMP,
    BDAPEEMP,
    BDENDEMP,
    BDNUMEMP,
    BDBAIEMP,
    BDCEPEMP,
    BDDDDEMP,
    BDFONEEMP,
    BDFAXEMP,
    BDEMAILEMP,
    BDCOMPLEMP,
    BDLOGREMP,
    BDIEEMP,
    BDIMEMP,
    BDSITEMP,
    BDCODPLANOONLINE,
    BDLOGOEMP,
    BDNOMESC,
    BDINIATIVESC,
    BDFIMATIVESC,
    BDLOGOESC,
    BDLOGRESC,
    BDENDESC,
    BDNUMESC,
    BDBAIESC,
    BDCEPESC,
    BDCNPJESC,
    BDDDDESC,
    BDFONEESC,
    BDRAMALESC,
    BDEMAILESC,
    BDCONTTERCESC,
    BDCOMPLESC,
    BDFAXESC,
    BDCODCIDESC,
    BDCRCESC,
    BDAPEPLA,
    BDNOMPLA,
    BDNOMCID,
    BDANIVCID,
    BDSIGLAUF,
    BDDESCUF,
    BDNOMECONT,
    BDCPFCONT,
    BDCRCCONT,
    BDENDCONT,
    BDLOGRCONT,
    BDNUMEROCONT,
    BDCOMPLCONT,
    BDCEPCONT,
    BDBAIRROCONT,
    BDDDDCONT,
    BDFONECONT,
    BDFAXCONT,
    BDEMAILCONT,
    BDCMCCONT,
    BDESCOLARIDADECONT,
    BDTIPOCONTABILISTA,
    BDCODOCUPA,
    BDCODQUACONT,
    BDCODQUA,
    BDREGJUN,
    BDCODCIDSOC,
    BDNOMSOC,
    BDENDSOC,
    BDNUMSOC,
    BDCOMPLSOC,
    BDBAISOC,
    BDCEPSOC,
    BDCGCCEISOC,
    BDDDSOC,
    BDTELRESSOC,
    BDTELCELSOC,
    BDEMAILSOC,
    BDLOGRSOC,
    BDQUALIRESPLEGALSOC,
    BDEXTERIORSOC,
    BDDATAENTSOC,
    BDDATASAISOC,
    BDCODPAISSOC,
    BDQUALIFICACAOSOC,
    BDDESCQUALISOC,
    BDRESPONSAVELSOC,
    BDCPFRESPLEGALSOC,
    BDPARAMREL,
    BDEXPQUALISOC,
    BDQUALISOCDIPJ,
    BDDESCQUALISOCREP,
    BDDESCQUALISOCSPED,
    BDPERSONALIZACAO,
    BDQTDCOTASOC,
    BDVALCOTASOC,
    BDPERCCOTASOC,
    BDCODCONTEF,
    BDNOMECONTEF,
    BDCPFCONTEF,
    BDCRCCONTEF,
    BDENDCONTEF,
    BDLOGRCONTEF,
    BDNUMEROCONTEF,
    BDCOMPLCONTEF,
    BDCEPCONTEF,
    BDBAIRROCONTEF,
    BDDDDCONTEF,
    BDFONECONTEF,
    BDFAXCONTEF,
    BDEMAILCONTEF,
    BDCMCCONTEF,
    BDESCOLARIDADECONTEF,
    BDTIPOCONTABILISTAEF,
    BDCODOCUPAEF,
    BDCODCONTRH,
    BDNOMECONTRH,
    BDCPFCONTRH,
    BDCRCCONTRH,
    BDENDCONTRH,
    BDLOGRCONTRH,
    BDNUMEROCONTRH,
    BDCOMPLCONTRH,
    BDCEPCONTRH,
    BDBAIRROCONTRH,
    BDDDDCONTRH,
    BDFONECONTRH,
    BDFAXCONTRH,
    BDEMAILCONTRH,
    BDCMCCONTRH,
    BDESCOLARIDADECONTRH,
    BDTIPOCONTABILISTARH,
    BDCODOCUPARH,
    BDLIVRO,
    BDFOLHA,
    BDNOMECARTORIO,
    BDRGSOC,
    BDORGEMISOC,
    BDSIGLAUFRG,
    BDDESCUFRG,
    BDESTCIVILSOC,
    BDCODCBO,
    BDDESCCBO,
    BDCODACESSOSN,
    BDSECAOCNAE,
    BDTIPOCNAE,
    BDCLASSIFICACAOCNAE,
    BDDESCCNAE,
    BDDESCCNAEADICIONAIS,
    BDNOMCIDESC,
    BDSIGLAUFESC,
    BDCODESC,
    BDCODSOC,
    BDCODFPAS,
    BDASSINATURACONTEF,
    BDASSINATURASOC,
    BDREGIMETRIBUTACAO,
    BDTIPOAPURACAO,
    BDCODZONA,
    BDNOMEZONA,
    BDDESCNAT,
    BDCEIEMP,
    BDCODIBGE,
    BDFORMATRIBUTACAO,
    BDDESCATIVIDADE,
    BDDESCANEXOS,
    BDDESCANEXOS_2018,
    BDSOCREPRESENTANTE,
    BDCODCLATRI,
    BDDATANASCSOC
    )
AS
select EMP.BDCODEMP, EMP.BDCODMATRIZ, EMP.BDCNPJEMP, EMP.BDDATAINIATIVEMP, EMP.BDORGAOEMP, EMP.BDDATAREGEMP,
       EMP.BDDATACONSTEMP, EMP.BDDESCCARTEMP, EMP.BDDATAFIMATIVEMP, EMP.BDREFEMP, EMP.BDCODPLAPADRAO, EMP.BDCODHIST,
       EMP.BDCODCENTROS, EMP.BDCODPLATRIB, EMP.BDCODCID, EMP.BDCODCONT, EMP.BDCODNATJUR, EMP.BDCODCNAE, EMP.BDNOMEMP,
       EMP.BDAPEEMP, EMP.BDENDEMP, EMP.BDNUMEMP, EMP.BDBAIEMP, EMP.BDCEPEMP, EMP.BDDDDEMP, EMP.BDFONEEMP, EMP.BDFAXEMP,
       EMP.BDEMAILEMP, EMP.BDCOMPLEMP, EMP.BDLOGREMP, EMP.BDIEEMP, EMP.BDIMEMP, EMP.BDSITEMP, EMP.BDCODPLANOONLINE,
       EMP.BDLOGOEMP, EMP.BDNOMESC, EMP.BDINIATIVESC, EMP.BDFIMATIVESC, EMP.BDLOGOESC, EMP.BDLOGRESC, EMP.BDENDESC,
       EMP.BDNUMESC, EMP.BDBAIESC, EMP.BDCEPESC, EMP.BDCNPJESC, EMP.BDDDDESC, EMP.BDFONEESC, EMP.BDRAMALESC,
       EMP.BDEMAILESC, EMP.BDCONTTERCESC, EMP.BDCOMPLESC, EMP.BDFAXESC, EMP.BDCODCIDESC, EMP.BDCRCESC, EMP.BDAPEPLA,
       EMP.BDNOMPLA, EMP.BDNOMCID, EMP.BDANIVCID, EMP.BDSIGLAUF, EMP.BDDESCUF, EMP.BDNOMECONT, EMP.BDCPFCONT,
       EMP.BDCRCCONT, EMP.BDENDCONT, EMP.BDLOGRCONT, EMP.BDNUMEROCONT, EMP.BDCOMPLCONT, EMP.BDCEPCONT, EMP.BDBAIRROCONT,
       EMP.BDDDDCONT, EMP.BDFONECONT, EMP.BDFAXCONT, EMP.BDEMAILCONT, EMP.BDCMCCONT, EMP.BDESCOLARIDADECONT,
       EMP.BDTIPOCONTABILISTA, EMP.BDCODOCUPA, EMP.BDCODQUACONT, EMP.BDCODQUA, EMP.BDREGJUN, EMP.BDCODCIDSOC,
       EMP.BDNOMSOC, EMP.BDENDSOC, EMP.BDNUMSOC, EMP.BDCOMPLSOC, EMP.BDBAISOC, EMP.BDCEPSOC, EMP.BDCGCCEISOC,
       EMP.BDDDSOC, EMP.BDTELRESSOC, EMP.BDTELCELSOC, EMP.BDEMAILSOC, EMP.BDLOGRSOC, EMP.BDQUALIRESPLEGALSOC,
       EMP.BDEXTERIORSOC, EMP.BDDATAENTSOC, EMP.BDDATASAISOC, EMP.BDCODPAISSOC, EMP.BDQUALIFICACAOSOC,
       EMP.BDDESCQUALISOC, EMP.BDRESPONSAVELSOC, EMP.BDCPFRESPLEGALSOC, EMP.BDPARAMREL, EMP.BDEXPQUALISOC,
       EMP.BDQUALISOCDIPJ, EMP.BDDESCQUALISOCREP, EMP.BDDESCQUALISOCSPED, EMP.BDPERSONALIZACAO, EMP.BDQTDCOTASOC,
       EMP.BDVALCOTASOC, EMP.BDPERCCOTASOC, EMP.BDCODCONTEF, EMP.BDNOMECONTEF, EMP.BDCPFCONTEF, EMP.BDCRCCONTEF,
       EMP.BDENDCONTEF, EMP.BDLOGRCONTEF, EMP.BDNUMEROCONTEF, EMP.BDCOMPLCONTEF, EMP.BDCEPCONTEF, EMP.BDBAIRROCONTEF,
       EMP.BDDDDCONTEF, EMP.BDFONECONTEF, EMP.BDFAXCONTEF, EMP.BDEMAILCONTEF, EMP.BDCMCCONTEF, EMP.BDESCOLARIDADECONTEF,
       EMP.BDTIPOCONTABILISTAEF, EMP.BDCODOCUPAEF, EMP.BDCODCONTRH, EMP.BDNOMECONTRH, EMP.BDCPFCONTRH, EMP.BDCRCCONTRH,
       EMP.BDENDCONTRH, EMP.BDLOGRCONTRH, EMP.BDNUMEROCONTRH, EMP.BDCOMPLCONTRH, EMP.BDCEPCONTRH, EMP.BDBAIRROCONTRH,
       EMP.BDDDDCONTRH, EMP.BDFONECONTRH, EMP.BDFAXCONTRH, EMP.BDEMAILCONTRH, EMP.BDCMCCONTRH, EMP.BDESCOLARIDADECONTRH,
       EMP.BDTIPOCONTABILISTARH, EMP.BDCODOCUPARH, EMP.BDLIVRO, EMP.BDFOLHA, EMP.BDNOMECARTORIO, EMP.BDRGSOC,
       EMP.BDORGEMISOC, EMP.BDSIGLAUFRG, EMP.BDDESCUFRG, EMP.BDESTCIVILSOC, EMP.BDCODCBO, EMP.BDDESCCBO,
       EMP.BDCODACESSOSN, EMP.BDSECAOCNAE, EMP.BDTIPOCNAE, EMP.BDCLASSIFICACAOCNAE, EMP.BDDESCCNAE,
       EMP.BDDESCCNAEADICIONAIS, EMP.BDNOMCIDESC, EMP.BDSIGLAUFESC, EMP.BDCODESC, EMP.BDCODSOC, EMP.BDCODFPAS,
       EMP.BDASSINATURACONTEF, EMP.BDASSINATURASOC, EMP.bdregimetributacao, EMP.BDTIPOAPURACAO, EMP.BDCODZONA, EMP.BDNOMEZONA, EMP.BDDESCNAT, EMP.BDCEIEMP, EMP.BDCODIBGE
       ,EMP.BDFORMATRIBUTACAO, EMP.BDDESCATIVIDADE ,EMP.BDDESCANEXOS ,EMP.BDDESCANEXOS_2018, EMP.BDSOCREPRESENTANTE, EMP.BDCODCLATRI,EMP.BDDATANASCSOC
from SP_GR_SCI_EMPRESAS EMP
;

CREATE OR ALTER VIEW VWGR_SCI_EMPRESAS_SOCIOS(
    BDCODEMP,
    BDCODMATRIZ,
    BDCNPJEMP,
    BDDATAINIATIVEMP,
    BDORGAOEMP,
    BDDATAREGEMP,
    BDDATACONSTEMP,
    BDDESCCARTEMP,
    BDDATAFIMATIVEMP,
    BDREFEMP,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDCODCENTROS,
    BDCODPLATRIB,
    BDCODCID,
    BDCODCONT,
    BDCODNATJUR,
    BDCODCNAE,
    BDNOMEMP,
    BDAPEEMP,
    BDENDEMP,
    BDNUMEMP,
    BDBAIEMP,
    BDCEPEMP,
    BDDDDEMP,
    BDFONEEMP,
    BDFAXEMP,
    BDEMAILEMP,
    BDCOMPLEMP,
    BDLOGREMP,
    BDIEEMP,
    BDIMEMP,
    BDSITEMP,
    BDCODPLANOONLINE,
    BDLOGOEMP,
    BDNOMESC,
    BDINIATIVESC,
    BDFIMATIVESC,
    BDLOGOESC,
    BDLOGRESC,
    BDENDESC,
    BDNUMESC,
    BDBAIESC,
    BDCEPESC,
    BDCNPJESC,
    BDDDDESC,
    BDFONEESC,
    BDRAMALESC,
    BDEMAILESC,
    BDCONTTERCESC,
    BDCOMPLESC,
    BDFAXESC,
    BDCODCIDESC,
    BDCRCESC,
    BDAPEPLA,
    BDNOMPLA,
    BDNOMCID,
    BDANIVCID,
    BDSIGLAUF,
    BDDESCUF,
    BDNOMECONT,
    BDCPFCONT,
    BDCRCCONT,
    BDENDCONT,
    BDLOGRCONT,
    BDNUMEROCONT,
    BDCOMPLCONT,
    BDCEPCONT,
    BDBAIRROCONT,
    BDDDDCONT,
    BDFONECONT,
    BDFAXCONT,
    BDEMAILCONT,
    BDCMCCONT,
    BDESCOLARIDADECONT,
    BDTIPOCONTABILISTA,
    BDCODOCUPA,
    BDCODQUACONT,
    BDCODQUA,
    BDREGJUN,
    BDCODCIDSOC,
    BDNOMSOC,
    BDENDSOC,
    BDNUMSOC,
    BDCOMPLSOC,
    BDBAISOC,
    BDCEPSOC,
    BDCGCCEISOC,
    BDDDSOC,
    BDTELRESSOC,
    BDTELCELSOC,
    BDEMAILSOC,
    BDLOGRSOC,
    BDQUALIRESPLEGALSOC,
    BDEXTERIORSOC,
    BDDATAENTSOC,
    BDDATASAISOC,
    BDCODPAISSOC,
    BDQUALIFICACAOSOC,
    BDDESCQUALISOC,
    BDRESPONSAVELSOC,
    BDCPFRESPLEGALSOC,
    BDPARAMREL,
    BDEXPQUALISOC,
    BDQUALISOCDIPJ,
    BDDESCQUALISOCREP,
    BDDESCQUALISOCSPED,
    BDPERSONALIZACAO,
    BDQTDCOTASOC,
    BDVALCOTASOC,
    BDPERCCOTASOC,
    BDCODCONTEF,
    BDNOMECONTEF,
    BDCPFCONTEF,
    BDCRCCONTEF,
    BDENDCONTEF,
    BDLOGRCONTEF,
    BDNUMEROCONTEF,
    BDCOMPLCONTEF,
    BDCEPCONTEF,
    BDBAIRROCONTEF,
    BDDDDCONTEF,
    BDFONECONTEF,
    BDFAXCONTEF,
    BDEMAILCONTEF,
    BDCMCCONTEF,
    BDESCOLARIDADECONTEF,
    BDTIPOCONTABILISTAEF,
    BDCODOCUPAEF,
    BDCODCONTRH,
    BDNOMECONTRH,
    BDCPFCONTRH,
    BDCRCCONTRH,
    BDENDCONTRH,
    BDLOGRCONTRH,
    BDNUMEROCONTRH,
    BDCOMPLCONTRH,
    BDCEPCONTRH,
    BDBAIRROCONTRH,
    BDDDDCONTRH,
    BDFONECONTRH,
    BDFAXCONTRH,
    BDEMAILCONTRH,
    BDCMCCONTRH,
    BDESCOLARIDADECONTRH,
    BDTIPOCONTABILISTARH,
    BDCODOCUPARH,
    BDLIVRO,
    BDFOLHA,
    BDNOMECARTORIO,
    BDRGSOC,
    BDORGEMISOC,
    BDSIGLAUFRG,
    BDDESCUFRG,
    BDESTCIVILSOC,
    BDCODCBO,
    BDDESCCBO,
    BDCODACESSOSN,
    BDSECAOCNAE,
    BDTIPOCNAE,
    BDCLASSIFICACAOCNAE,
    BDDESCCNAE,
    BDDESCCNAEADICIONAIS,
    BDNOMCIDESC,
    BDSIGLAUFESC,
    BDCODESC,
    BDCODSOC,
    BDCODFPAS,
    BDASSINATURACONTEF,
    BDASSINATURASOC,
    BDREGIMETRIBUTACAO,
    BDTIPOAPURACAO,
    BDDESCNAT,
    BDDATANASCSOC)
AS
select EMP.BDCODEMP, EMP.BDCODMATRIZ, EMP.BDCNPJEMP, EMP.BDDATAINIATIVEMP, EMP.BDORGAOEMP, EMP.BDDATAREGEMP,
       EMP.BDDATACONSTEMP, EMP.BDDESCCARTEMP, EMP.BDDATAFIMATIVEMP, EMP.BDREFEMP, EMP.BDCODPLAPADRAO, EMP.BDCODHIST,
       EMP.BDCODCENTROS, EMP.BDCODPLATRIB, EMP.BDCODCID, EMP.BDCODCONT, EMP.BDCODNATJUR, EMP.BDCODCNAE, EMP.BDNOMEMP,
       EMP.BDAPEEMP, EMP.BDENDEMP, EMP.BDNUMEMP, EMP.BDBAIEMP, EMP.BDCEPEMP, EMP.BDDDDEMP, EMP.BDFONEEMP, EMP.BDFAXEMP,
       EMP.BDEMAILEMP, EMP.BDCOMPLEMP, EMP.BDLOGREMP, EMP.BDIEEMP, EMP.BDIMEMP, EMP.BDSITEMP, EMP.BDCODPLANOONLINE,
       EMP.BDLOGOEMP, EMP.BDNOMESC, EMP.BDINIATIVESC, EMP.BDFIMATIVESC, EMP.BDLOGOESC, EMP.BDLOGRESC, EMP.BDENDESC,
       EMP.BDNUMESC, EMP.BDBAIESC, EMP.BDCEPESC, EMP.BDCNPJESC, EMP.BDDDDESC, EMP.BDFONEESC, EMP.BDRAMALESC,
       EMP.BDEMAILESC, EMP.BDCONTTERCESC, EMP.BDCOMPLESC, EMP.BDFAXESC, EMP.BDCODCIDESC, EMP.BDCRCESC, EMP.BDAPEPLA,
       EMP.BDNOMPLA, EMP.BDNOMCID, EMP.BDANIVCID, EMP.BDSIGLAUF, EMP.BDDESCUF, EMP.BDNOMECONT, EMP.BDCPFCONT,
       EMP.BDCRCCONT, EMP.BDENDCONT, EMP.BDLOGRCONT, EMP.BDNUMEROCONT, EMP.BDCOMPLCONT, EMP.BDCEPCONT, EMP.BDBAIRROCONT,
       EMP.BDDDDCONT, EMP.BDFONECONT, EMP.BDFAXCONT, EMP.BDEMAILCONT, EMP.BDCMCCONT, EMP.BDESCOLARIDADECONT,
       EMP.BDTIPOCONTABILISTA, EMP.BDCODOCUPA, EMP.BDCODQUACONT, EMP.BDCODQUA, EMP.BDREGJUN, EMP.BDCODCIDSOC,
       EMP.BDNOMSOC, EMP.BDENDSOC, EMP.BDNUMSOC, EMP.BDCOMPLSOC, EMP.BDBAISOC, EMP.BDCEPSOC, EMP.BDCGCCEISOC,
       EMP.BDDDSOC, EMP.BDTELRESSOC, EMP.BDTELCELSOC, EMP.BDEMAILSOC, EMP.BDLOGRSOC, EMP.BDQUALIRESPLEGALSOC,
       EMP.BDEXTERIORSOC, EMP.BDDATAENTSOC, EMP.BDDATASAISOC, EMP.BDCODPAISSOC, EMP.BDQUALIFICACAOSOC,
       EMP.BDDESCQUALISOC, EMP.BDRESPONSAVELSOC, EMP.BDCPFRESPLEGALSOC, EMP.BDPARAMREL, EMP.BDEXPQUALISOC,
       EMP.BDQUALISOCDIPJ, EMP.BDDESCQUALISOCREP, EMP.BDDESCQUALISOCSPED, EMP.BDPERSONALIZACAO, EMP.BDQTDCOTASOC,
       EMP.BDVALCOTASOC, EMP.BDPERCCOTASOC, EMP.BDCODCONTEF, EMP.BDNOMECONTEF, EMP.BDCPFCONTEF, EMP.BDCRCCONTEF,
       EMP.BDENDCONTEF, EMP.BDLOGRCONTEF, EMP.BDNUMEROCONTEF, EMP.BDCOMPLCONTEF, EMP.BDCEPCONTEF, EMP.BDBAIRROCONTEF,
       EMP.BDDDDCONTEF, EMP.BDFONECONTEF, EMP.BDFAXCONTEF, EMP.BDEMAILCONTEF, EMP.BDCMCCONTEF, EMP.BDESCOLARIDADECONTEF,
       EMP.BDTIPOCONTABILISTAEF, EMP.BDCODOCUPAEF, EMP.BDCODCONTRH, EMP.BDNOMECONTRH, EMP.BDCPFCONTRH, EMP.BDCRCCONTRH,
       EMP.BDENDCONTRH, EMP.BDLOGRCONTRH, EMP.BDNUMEROCONTRH, EMP.BDCOMPLCONTRH, EMP.BDCEPCONTRH, EMP.BDBAIRROCONTRH,
       EMP.BDDDDCONTRH, EMP.BDFONECONTRH, EMP.BDFAXCONTRH, EMP.BDEMAILCONTRH, EMP.BDCMCCONTRH, EMP.BDESCOLARIDADECONTRH,
       EMP.BDTIPOCONTABILISTARH, EMP.BDCODOCUPARH, EMP.BDLIVRO, EMP.BDFOLHA, EMP.BDNOMECARTORIO, EMP.BDRGSOC,
       EMP.BDORGEMISOC, EMP.BDSIGLAUFRG, EMP.BDDESCUFRG, EMP.BDESTCIVILSOC, EMP.BDCODCBO, EMP.BDDESCCBO,
       EMP.BDCODACESSOSN, EMP.BDSECAOCNAE, EMP.BDTIPOCNAE, EMP.BDCLASSIFICACAOCNAE, EMP.BDDESCCNAE,
       EMP.BDDESCCNAEADICIONAIS, EMP.BDNOMCIDESC, EMP.BDSIGLAUFESC, EMP.BDCODESC, EMP.BDCODSOC, EMP.BDCODFPAS,
       EMP.BDASSINATURACONTEF, EMP.BDASSINATURASOC, EMP.bdregimetributacao, EMP.BDTIPOAPURACAO,BDDESCNAT,EMP.BDDATANASCSOC
from SP_GR_SCI_EMPRESAS(1) EMP
;

/* CREATE OR ALTER VIEW: VWSCI_EMPMENSAL_ABA_LALUR (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VWSCI_EMPMENSAL_ABA_LALUR(
BDCODEMP,
BDREFEMP,
BDCODPARTEA,
BDCODPARTEB,
BDCODTRIBUT,
BDCODEST,
BDNOMPARTEA,
BDNOMPARTEB,
BDNOMTRIBUT,
    BDNOMEST,
    BDCODCONTABLALUR,
    BDNOMCONTAB)
 AS 
SELECT
  LALUR.BDCODEMP,
  LALUR.BDREFEMP,
  LALUR.BDCODPARTEA,
  LALUR.BDCODPARTEB,
  LALUR.BDCODTRIBUT,
  LALUR.BDCODEST,
  LALURA.BDNOMPARTEA,
  LALURB.BDNOMPARTEB,
  LALURT.BDNOMTRIBUT,
  LALURE.BDNOMPARTEA,
  TREF.BDCODCONTABLALUR,
  LALURC.BDNOME
FROM
  VLAL_BASE_TEMP LALUR
LEFT OUTER JOIN VLAL_BASE_LALUR_PARTEA LALURA ON (LALUR.BDCODPARTEA = LALURA.BDCODPARTEA)
LEFT OUTER JOIN VLAL_BASE_LALUR_PARTEB LALURB ON (LALUR.BDCODPARTEB = LALURB.BDCODPARTEB)
LEFT OUTER JOIN VLAL_BASE_LALUR_TRIBUTACAO LALURT ON (LALUR.BDCODTRIBUT = LALURT.BDCODTRIBUT)
LEFT OUTER JOIN VLAL_BASE_LALUR_PARTEA LALURE ON (LALUR.BDCODEST = LALURE.BDCODPARTEA)
LEFT OUTER JOIN TEMPRESAS_REF TREF ON (LALUR.bdcodemp = TREF.bdcodemp AND LALUR.bdrefemp = TREF.bdrefemp)
LEFT OUTER JOIN VLAL_BASE_TCONF_CONTAB_LALUR LALURC ON (LALURC.bdcodcontablalur = TREF.bdcodcontablalur)
;

/* View: VWSCI_EMPMENSAL_ABA_PLA */
CREATE OR ALTER VIEW VWSCI_EMPMENSAL_ABA_PLA(
    BDCODEMP,
    BDREFEMP,
    BDCODPLANOONLINE,
    BDDESCRICAO,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDCODCENTRO,
    BDCODPLATRIB,
    BDNOMEPLAP,
    BDNOMEPLAH,
    BDNOMEPLAC,
    BDDESCPLATRIB,
    BDCODPLAPADRAOREF,
    BDCONTABILIZASCP,
    BDNAOCONTCENTROCUSTO,
    BDEXIBEINFOCOLLAN,
    BDCONTABILIZAFILIALSEP)
AS
SELECT
  EMPR.BDCODEMP,
  EMPR.BDREFEMP,
  PLAOL.BDCODPLANOONLINE,
  PLAOL.BDDESCRICAO,
  PLAOL.BDCODPLAPADRAO,
  PLAOL.BDCODHIST,
  PLAC.BDCODCENTRO,
  PLAT.BDCODPLATRIB,
  PLAP.BDNOME,
  PLAH.BDNOME,
  PLAC.BDNOME,
  PLAT.BDDESCPLATRIB,
  plaref.bdAPELIDO AS BDCODPLAPADRAOREF,
  EMPR.BDCONTABILIZASCP,
  EMPR.BDNAOCONTCENTROCUSTO,
  EMPR.BDEXIBEINFOCOLLAN,
  EMPR.BDCONTABILIZAFILIALSEP
FROM
  TEMPRESAS_REF EMPR
LEFT OUTER JOIN TPLANO_CONF_ONLINE PLAOL ON (EMPR.BDCODPLANOONLINE = PLAOL.BDCODPLANOONLINE)
LEFT OUTER JOIN TPLANO_PADRAO PLAP ON (PLAOL.BDCODPLAPADRAO = PLAP.BDCODPLAPADRAO)
LEFT OUTER JOIN THIST PLAH ON (PLAOL.BDCODHIST = PLAH.BDCODHIST)
LEFT OUTER JOIN TCENTROS PLAC ON (EMPR.BDCODCENTROS = PLAC.BDCODCENTRO)
LEFT OUTER JOIN vct_plano_tributario PLAT ON (PLAT.bdcodplatrib = EMPR.bdcodplatrib)
LEFT OUTER JOIN TPLANO_PADRAO_ECF plaref ON (plaref.bdCODPLAPADRAOREF = empr.bdCODPLAPADRAOREF)
; 

CREATE OR ALTER VIEW VW_TCONF_CTAS_REF_MAX_MIN(
    BDCODPLANOONLINE,
    BDCHAVE,
    BDREFCTA)
AS
SELECT
cta.BDCODPLANOONLINE,
cta.BDCHAVE,
(
  SELECT FIRST 1 x.BDREFCTA FROM TCONF_CONTAS_ONLINE_REF x
  WHERE x.BDCODPLANOONLINE = CTA.BDCODPLANOONLINE AND
  x.BDCHAVE = coalesce(CTA.BDCHAVEVINC, CTA.BDCHAVE) AND
  X.BDREFCTA <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
  ORDER BY x.BDCODPLANOONLINE DESC, X.BDCHAVE DESC, x.BDREFCTA DESC
) BDREFCTA

FROM TCONF_CONTAS_ONLINE CTA
;

CREATE OR ALTER VIEW VW_TCONF_CONTAS_REF(
    BDCODPLANOONLINE,
    BDCHAVE,
    BDREFCTA,
    BDCODTIPOCONTA,
    BDCODNAT,
    BDCODVER,
    BDCONTADEBPROV,
    BDCONTACREDPROV,
    BDCODPLAPADRAO,
    BDCONTADEBPGTO,
    BDCONTACREDPGTO,
    BDCODHISTPROV,
    BDCODHISTPGTO,
    BDCODTPHI,
    BDCODCENTRO,
    BDCODTPCC,
    BDCODOREC,
    BDCODIMP,
    BDCHAVEVINC,
    BDCODGRUPOCLA,
    BDFORMULA,
    BDCLASSIFICACAO,
    BDCODITEMONLINE,
    BDCODCONFIRLP,
    BDCODCONFIPI,
    BDCODCONFDIMESC,
    BDCODCONFSP,
    BDCODUF,
    BDCODCOMPHISTPGTO,
    BDCODCOMPHISTPROV,
    BDCODCONFDACON,
    BDCODTCA,
    BDNAOCONTAB,
    BDCODCONFGIAMG,
    BDCODTIPODOC,
    BDCODREC,
    BDCOPYTITULO,
    BDCODCONFGIAES,
    BDCODCONFGIARO,
    BDCODCONFGIAPR,
    BDTIPOOPERIMOB,
    BDATIVA,
    BDCODOBRSER,
    BDCHAVECTABAN,
    BDCODCLI,
    BDCODCONFCIAP,
    BDCODCONFGIARJ,
    BDCODCONFBLOCOM,
    BDCODCONFICMSSPED,
    BDCODDESP,
    BDCODCONFGIAST,
    BDCODCONFGIATO)
AS
SELECT ctas.bdcodplanoonline, ctas.bdchave, tref.bdrefcta, ctas.bdcodtipoconta, ctas.bdcodnat, ctas.bdcodver, tref.bdcontadebprov,
       tref.bdcontacredprov, tref.bdcodplapadrao, tref.bdcontadebpgto, tref.bdcontacredpgto, tref.bdcodhistprov,
       tref.bdcodhistpgto, tref.bdcodtphi, ctas.bdcodcentro, ctas.bdcodtpcc, ctas.bdcodorec, ctas.bdcodimp,
       ctas.bdchavevinc, ctas.bdcodgrupocla, ctas.bdformula, ctas.bdclassificacao, ctas.bdcoditemonline,
       ctas.bdcodconfirlp, ctas.bdcodconfipi, ctas.bdcodconfdimesc, ctas.bdcodconfsp, ctas.bdcoduf,
       tref.bdcodcomphistpgto, tref.bdcodcomphistprov, ctas.bdcodconfdacon, ctas.bdcodtca, ctas.bdnaocontab,
       ctas.bdcodconfgiamg, ctas.bdcodtipodoc, ctas.bdcodrec, ctas.bdcopytitulo, ctas.bdcodconfgiaes,
       ctas.bdcodconfgiaro, ctas.bdcodconfgiapr, ctas.bdtipooperimob, ctas.bdativa, ctas.bdcodobrser,
       ctas.bdchavectaban, ctas.bdcodcli, ctas.bdcodconfciap, ctas.bdcodconfgiarj, ctas.bdcodconfblocom,
       ctas.bdcodconficmssped, ctas.bdcoddesp, ctas.bdcodconfgiast, ctas.BDCODCONFGIATO
FROM tconf_contas_online ctas
LEFT OUTER JOIN vw_tconf_ctas_ref_max_min max_min ON (max_min.bdcodplanoonline = ctas.bdcodplanoonline AND max_min.bdchave = ctas.bdchave)
LEFT OUTER JOIN tconf_contas_online_ref tref ON (tref.bdcodplanoonline = ctas.bdcodplanoonline AND tref.bdchave = ctas.bdchave AND tref.bdrefcta = max_min.bdrefcta)
;

CREATE OR ALTER VIEW VW_TCONF_CONTAS_TODAS_REF(
    BDCODPLANOONLINE,
    BDCHAVE,
    BDREFCTA,
    BDCODPLAPADRAO,
    BDCODTPHI,
    BDCONTADEBPROV,
    BDCONTACREDPROV,
    BDCODHISTPROV,
    BDCODCOMPHISTPROV,
    BDCONTADEBPGTO,
    BDCONTACREDPGTO,
    BDCODHISTPGTO,
    BDCODCOMPHISTPGTO,
    BDCOPYTITULO,
    BDCHAVEVINC)
AS
SELECT ONL.BDCODPLANOONLINE, ONL.BDCHAVE, REF_PAI.BDREFCTA, REF.BDCODPLAPADRAO, REF.BDCODTPHI, REF.BDCONTADEBPROV,
       REF.BDCONTACREDPROV, REF.BDCODHISTPROV, REF.BDCODCOMPHISTPROV, REF.BDCONTADEBPGTO, REF.BDCONTACREDPGTO,
       REF.BDCODHISTPGTO, REF.BDCODCOMPHISTPGTO, REF.BDCOPYTITULO, ONL.BDCHAVEVINC
FROM TCONF_CONTAS_ONLINE ONL
LEFT OUTER JOIN TCONF_CONTAS_ONLINE_REF REF_PAI ON (ONL.BDCODPLANOONLINE = REF_PAI.BDCODPLANOONLINE AND REF_PAI.BDCHAVE = COALESCE(ONL.bdchavevinc, ONL.BDCHAVE))
LEFT OUTER JOIN TCONF_CONTAS_ONLINE_REF REF ON (ONL.BDCODPLANOONLINE = REF.BDCODPLANOONLINE AND ONL.BDCHAVE = REF.BDCHAVE AND REF_PAI.BDREFCTA = REF.BDREFCTA)
;

CREATE OR ALTER VIEW VW_TCONF_CTAS_REF_TEMP_MAX_MIN(
    BDCODPLANOONLINE,
    BDCHAVE,
    BDREFCTA)
AS
SELECT
cta.BDCODPLANOONLINE,
cta.BDCHAVE,
(
  SELECT FIRST 1 x.BDREFCTA FROM TMP_TCONF_CONTAS_ONLINE_REF x
  WHERE
  X.BDSESSAO = (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_TV_CONTAS')) FROM rdb$database) AND
  x.BDCODPLANOONLINE = CTA.BDCODPLANOONLINE AND
  x.BDCHAVE = coalesce(CTA.BDCHAVEVINC, CTA.BDCHAVE) AND
  X.BDREFCTA <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
  ORDER BY x.BDCODPLANOONLINE DESC, X.BDCHAVE DESC, x.BDREFCTA DESC
) BDREFCTA

FROM TCONF_CONTAS_ONLINE CTA
;

CREATE OR ALTER VIEW VW_TCONF_CONTAS_REF_TEMP(
    BDCODPLANOONLINE,
    BDCHAVE,
    BDREFCTA,
    BDCODTIPOCONTA,
    BDCODNAT,
    BDCODVER,
    BDCONTADEBPROV,
    BDCONTACREDPROV,
    BDCODPLAPADRAO,
    BDCONTADEBPGTO,
    BDCONTACREDPGTO,
    BDCODHISTPROV,
    BDCODHISTPGTO,
    BDCODTPHI,
    BDCODCENTRO,
    BDCODTPCC,
    BDCODOREC,
    BDCODIMP,
    BDCHAVEVINC,
    BDCODGRUPOCLA,
    BDFORMULA,
    BDCLASSIFICACAO,
    BDCODITEMONLINE,
    BDCODCONFIRLP,
    BDCODCONFIPI,
    BDCODCONFDIMESC,
    BDCODCONFSP,
    BDCODUF,
    BDCODCOMPHISTPGTO,
    BDCODCOMPHISTPROV,
    BDCODCONFDACON,
    BDCODTCA,
    BDNAOCONTAB,
    BDCODCONFGIAMG,
    BDCODTIPODOC,
    BDCODREC,
    BDCOPYTITULO,
    BDCODCONFGIAES,
    BDCODCONFGIARO,
    BDCODCONFGIAPR,
    BDTIPOOPERIMOB,
    BDATIVA,
    BDCODOBRSER,
    BDCHAVECTABAN,
    BDCODCLI,
    BDCODCONFCIAP,
    BDCODCONFGIARJ,
    BDCODCONFBLOCOM,
    BDCODCONFICMSSPED,
    BDCODDESP,
    BDCODCONFGIAST,
    BDCODCONFGIATO)
AS
SELECT ctas.bdcodplanoonline, ctas.bdchave, COALESCE(tref.bdrefcta, ctas.bdrefcta), ctas.bdcodtipoconta, ctas.bdcodnat, ctas.bdcodver,
       iif(tref.bdrefcta is not null, tref.bdcontadebprov, ctas.bdcontadebprov), iif(tref.bdrefcta is not null, tref.bdcontacredprov, ctas.bdcontacredprov),
       iif(tref.bdrefcta is not null, tref.bdcodplapadrao, ctas.bdcodplapadrao), iif(tref.bdrefcta is not null, tref.bdcontadebpgto, ctas.bdcontadebpgto),
       iif(tref.bdrefcta is not null, tref.bdcontacredpgto, ctas.bdcontacredpgto), iif(tref.bdrefcta is not null, tref.bdcodhistprov, ctas.bdcodhistprov),
       iif(tref.bdrefcta is not null, tref.bdcodhistpgto, ctas.bdcodhistpgto), iif(tref.bdrefcta is not null, tref.bdcodtphi, ctas.bdcodtphi), ctas.bdcodcentro,
       ctas.bdcodtpcc, ctas.bdcodorec, ctas.bdcodimp, ctas.bdchavevinc, ctas.bdcodgrupocla, ctas.bdformula,
       ctas.bdclassificacao, ctas.bdcoditemonline, ctas.bdcodconfirlp, ctas.bdcodconfipi, ctas.bdcodconfdimesc,
       ctas.bdcodconfsp, ctas.bdcoduf, iif(tref.bdrefcta is not null, tref.bdcodcomphistpgto, ctas.bdcodcomphistpgto),
       iif(tref.bdrefcta is not null, tref.bdcodcomphistprov, ctas.bdcodcomphistprov), ctas.bdcodconfdacon, ctas.bdcodtca, ctas.bdnaocontab,
       ctas.bdcodconfgiamg, ctas.bdcodtipodoc, ctas.bdcodrec, ctas.bdcopytitulo, ctas.bdcodconfgiaes,
       ctas.bdcodconfgiaro, ctas.bdcodconfgiapr, ctas.bdtipooperimob, ctas.bdativa, ctas.bdcodobrser,
       ctas.bdchavectaban, ctas.bdcodcli, ctas.bdcodconfciap, ctas.bdcodconfgiarj, ctas.bdcodconfblocom,
       ctas.bdcodconficmssped, ctas.bdcoddesp, ctas.bdcodconfgiast, ctas.BDCODCONFGIATO
FROM VW_TCONF_CONTAS_REF ctas
LEFT OUTER JOIN VW_TCONF_CTAS_REF_TEMP_MAX_MIN max_min ON (max_min.bdcodplanoonline = ctas.bdcodplanoonline AND max_min.bdchave = ctas.bdchave)
LEFT OUTER JOIN TMP_TCONF_CONTAS_ONLINE_REF tref ON (tref.BDSESSAO = (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_TV_CONTAS')) FROM rdb$database) and tref.bdcodplanoonline = ctas.bdcodplanoonline AND tref.bdchave = ctas.bdchave AND tref.bdrefcta = max_min.bdrefcta)
;

CREATE OR ALTER VIEW VW_TCONF_VARIAS_CONTAS_REF_TEMP(
    BDCODPLANOONLINE,
    BDCHAVE,
    BDREFCTA,
    BDCODTIPOCONTA,
    BDCODNAT,
    BDCODVER,
    BDCONTADEBPROV,
    BDCONTACREDPROV,
    BDCODPLAPADRAO,
    BDCONTADEBPGTO,
    BDCONTACREDPGTO,
    BDCODHISTPROV,
    BDCODHISTPGTO,
    BDCODTPHI,
    BDCODCENTRO,
    BDCODTPCC,
    BDCODOREC,
    BDCODIMP,
    BDCHAVEVINC,
    BDCODGRUPOCLA,
    BDFORMULA,
    BDCLASSIFICACAO,
    BDCODITEMONLINE,
    BDCODCONFIRLP,
    BDCODCONFIPI,
    BDCODCONFDIMESC,
    BDCODCONFSP,
    BDCODUF,
    BDCODCOMPHISTPGTO,
    BDCODCOMPHISTPROV,
    BDCODCONFDACON,
    BDCODTCA,
    BDNAOCONTAB,
    BDCODCONFGIAMG,
    BDCODTIPODOC,
    BDCODREC,
    BDCOPYTITULO,
    BDCODCONFGIAES,
    BDCODCONFGIARO,
    BDCODCONFGIAPR,
    BDTIPOOPERIMOB,
    BDATIVA,
    BDCODOBRSER,
    BDCHAVECTABAN,
    BDCODCLI,
    BDCODCONFCIAP,
    BDCODCONFGIARJ,
    BDCODCONFBLOCOM,
    BDCODCONFICMSSPED,
    BDCODDESP,
    BDCODCONFGIAST,
    BDCODCONFGIATO)
AS
SELECT ref_max_min.bdcodplanoonline, ref_max_min.bdchave, tref_pai.bdrefcta, ctas.bdcodtipoconta, ctas.bdcodnat, ctas.bdcodver,
       tref.bdcontadebprov, tref.bdcontacredprov,
       tref.bdcodplapadrao, tref.bdcontadebpgto,
       tref.bdcontacredpgto,  tref.bdcodhistprov,
       tref.bdcodhistpgto, tref.bdcodtphi, ctas.bdcodcentro,
       ctas.bdcodtpcc, ctas.bdcodorec, ctas.bdcodimp, ref_max_min.bdchavevinc, ctas.bdcodgrupocla, ctas.bdformula,
       ctas.bdclassificacao, ctas.bdcoditemonline, ctas.bdcodconfirlp, ctas.bdcodconfipi, ctas.bdcodconfdimesc,
       ctas.bdcodconfsp, ctas.bdcoduf, tref.bdcodcomphistpgto,
       tref.bdcodcomphistprov, ctas.bdcodconfdacon, ctas.bdcodtca, ctas.bdnaocontab,
       ctas.bdcodconfgiamg, ctas.bdcodtipodoc, ctas.bdcodrec, ctas.bdcopytitulo, ctas.bdcodconfgiaes,
       ctas.bdcodconfgiaro, ctas.bdcodconfgiapr, ctas.bdtipooperimob, ctas.bdativa, ctas.bdcodobrser,
       ctas.bdchavectaban, ctas.bdcodcli, ctas.bdcodconfciap, ctas.bdcodconfgiarj, ctas.bdcodconfblocom,
       ctas.bdcodconficmssped, ctas.bdcoddesp, ctas.bdcodconfgiast, ctas.BDCODCONFGIATO
FROM (SELECT ref.bdsessao, ref.bdcodplanoonline, ref.bdchave, ref.bdchavevinc, MAX(ref.bdrefcta) AS bdrefcta
      FROM tmp_tconf_contas_online_ref ref
      WHERE bdsessao = (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_TV_CONTAS'))
                        FROM rdb$database)
      GROUP BY ref.bdsessao, ref.bdcodplanoonline, ref.bdchave, ref.bdchavevinc) ref_max_min
LEFT OUTER JOIN tconf_contas_online ctas ON (ctas.bdcodplanoonline = ref_max_min.bdcodplanoonline AND ctas.bdchave = COALESCE(ref_max_min.bdchavevinc, ref_max_min.bdchave))
LEFT OUTER JOIN VW_TCONF_CTAS_REF_TEMP_MAX_MIN tref_pai on (tref_pai.bdcodplanoonline = ref_max_min.bdcodplanoonline AND tref_pai.bdchave = COALESCE(ref_max_min.bdchavevinc, ref_max_min.bdchave))
inner JOIN tmp_tconf_contas_online_ref tref ON (tref.bdsessao = ref_max_min.bdsessao AND tref.bdcodplanoonline = ctas.bdcodplanoonline AND tref.bdchave = ref_max_min.bdchave AND tref.bdrefcta = tref_pai.bdrefcta)
;

/* Alter Procedure... */
/* Restore proc. body: AAAAMM */
SET TERM ^ ;

CREATE OR ALTER PROCEDURE AAAAMM(PRDATA DATE)
 RETURNS(BDAAAAMM VARCHAR(6))
 AS
DECLARE VARIABLE WMES VARCHAR(2);
DECLARE VARIABLE WANO VARCHAR(4);
BEGIN
  IF (prdata IS NULL) THEN
     BEGIN
       bdaaaamm = '';
     END
  ELSE
     BEGIN
       SELECT str FROM strZero(EXTRACT(MONTH FROM :prdata), 2) INTO :wmes;
    
       SELECT str FROM strzero(EXTRACT(YEAR FROM :prdata), 4) INTO :wano;
    
       bdaaaamm = :wano||:wmes;
     END

  SUSPEND;
END
^

create or alter procedure SP_GET_DEPENDENCIAS (
    PRTABELA varchar(100),
    PRWHERE varchar(1000))
returns (
    BDTABELA varchar(100),
    BDDESCRICAO varchar(1000))
as
declare variable WWHERE varchar(1000);
declare variable WCAMPO varchar(33);
declare variable WTABELA varchar(33);
declare variable WFOREINGKEY varchar(33);
declare variable WPOSITION integer;
declare variable WCAMPOPK varchar(33);
declare variable WSQL varchar(1000);
declare variable WFIELDS varchar(1000);
declare variable WEXISTS integer;
declare variable WFIELDSPK varchar(1000);
begin
  -- Listar Foreing Key's da tabela desejada
  for SELECT rc.RDB$CONSTRAINT_NAME AS constraint_name
      from RDB$RELATION_CONSTRAINTS rc
      inner JOIN RDB$REF_CONSTRAINTS refc ON(refc.RDB$CONSTRAINT_NAME=rc.RDB$CONSTRAINT_NAME)
      inner JOIN RDB$RELATION_CONSTRAINTS rc2 ON(rc2.RDB$CONSTRAINT_NAME=refc.RDB$CONST_NAME_UQ)
      WHERE(rc.RDB$CONSTRAINT_TYPE='FOREIGN KEY')
      AND((refc.RDB$DELETE_RULE<>'CASCADE')and(refc.RDB$DELETE_RULE<>'SET NULL'))
      AND(rc2.RDB$RELATION_NAME=upper(:prtabela))
      ORDER BY rc.RDB$CONSTRAINT_NAME
  into :wforeingkey do
  begin
    wwhere = prwhere;
    wfields = '';
    wfieldspk = '';
    -- listar as tabelas e campos usados nas Foreing Key's
    for SELECT trim(i.RDB$RELATION_NAME) AS table_name,
               trim(s.RDB$FIELD_NAME) AS field_name,
               s.RDB$FIELD_POSITION
        FROM RDB$INDEX_SEGMENTS s
        inner JOIN RDB$INDICES i ON i.RDB$INDEX_NAME = s.RDB$INDEX_NAME
        inner JOIN RDB$RELATION_CONSTRAINTS rc ON rc.RDB$INDEX_NAME = s.RDB$INDEX_NAME
        inner JOIN RDB$REF_CONSTRAINTS refc ON rc.RDB$CONSTRAINT_NAME = refc.RDB$CONSTRAINT_NAME
        WHERE rc.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY'
        AND rc.RDB$CONSTRAINT_NAME = :wforeingkey
        ORDER BY rc.RDB$CONSTRAINT_NAME, s.RDB$FIELD_POSITION
    into :wtabela, :wcampo, :wposition do
    begin
      wfields = wfields||wcampo||',';
      if (wfieldspk = '') then
         wfieldspk = wfieldspk||''''||'  '||wcampo||'='||''''||'||'||'trim('||wcampo||')';
      else
         wfieldspk = wfieldspk||'||'||''''||'  '||wcampo||'='||''''||'||'||'trim('||wcampo||')';

      -- encontrar o nome do campo na tabela que faz Foreing Key com a tabela principal
      -- ex.: Tabela PLANOS_TPLA = BDCODPLAPADRA,BDCODTPLA
      --      FK     VSUC_EMPRESAS_TLAN = BDCODPLAPADRAO,BDDEBITO
      --                                  BDCODPLAPADRAO,BDCREDITO
      for SELECT trim(s.rdb$field_name)
          FROM RDB$INDEX_SEGMENTS s
          inner JOIN RDB$RELATION_CONSTRAINTS rc ON rc.RDB$INDEX_NAME = s.RDB$INDEX_NAME
          WHERE rc.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY'
          AND rc.RDB$RELATION_NAME = :prtabela
          and s.RDB$FIELD_POSITION = :wposition
      into :wcampopk do
      begin
        -- Substiui campo da tabela principal pelo campo da tabela FK
        wwhere = replace(upper(wwhere), upper(wcampopk), upper(wcampo));
      end
    end

    if (wfields <> '') then
    begin
      bdtabela = wtabela;
      wfields = substring(wfields from 1 for strlen(wfields)-1);
      wsql = 'select coalesce(count(*), 0) from (select first 1 '||wfields||' from '||wtabela||' '||wwhere||')';
      execute statement wsql into :WEXISTS;
      if (wexists > 0) then
      begin
--        select bddescricao from TDESC_TABLE_BANCO where trim(bdtable) = trim(:wtabela) into :BDDESCRICAO;
        suspend;
      end
    end
  end
end^

create or alter procedure SP_EMPRESAS_USU (
    PREMP integer = 0)
returns (
    BDCODEMP integer)
as
declare variable WTEMEMPRESAPORUSUARIO integer;
declare variable WCODGRUPO integer;
declare variable WGRUPOSEMFILTROEMPRESA integer;
begin
   wCodGrupo = null;
   --Verifica se é grupo master
   select first 1 g.bdcodgrupo from tgrupousuario_usuario g where g.bdcodgrupo = 1 and g.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario) into wCodGrupo;

   --Se não for master (wCodGrupo = null), verifica de acordo com as permissões do usuário
   if (wCodGrupo is null) then
   begin
      wTemEmpresaPorUsuario = 0;

      premp = coalesce(premp, 0);

      if (premp > 0) then
         begin
      --Seleção das empresas por usuário
      for SELECT emp.bdcodemp--, grp.bdcodgrupo, emp.bdcodusu
      FROM tempresa_usuario emp
      inner join tempresas e on emp.bdcodemp = e.bdcodemp
      INNER JOIN tgrupousuario_usuario grp ON (grp.bdcodusu = emp.bdcodusu AND grp.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
      -- caso usuário pertence ao grupo master não deve listar empresas nesse sql
           WHERE e.bdcodemp = :premp and
                 (NOT exists (SELECT FIRST 1 * FROM tgrupousuario_usuario WHERE BDCODUSU = (SELECT bdcodusu FROM sp_get_usuario) AND BDCODGRUPO = 1))
                 and ((e.bdexcluiremp is null)or(upper(e.bdexcluiremp)<>'TRUE'))
           into bdcodemp do
              begin
                 wTemEmpresaPorUsuario = 1;
                 suspend;
              end
     
           -- listar todas as empresas caso usuário do grupo master
           for SELECT EMP.BDCODEMP FROM tempresas EMP
               WHERE EMP.BDCODEMP = :premp and (exists (SELECT FIRST 1 * FROM tgrupousuario_usuario WHERE BDCODUSU = (SELECT bdcodusu FROM sp_get_usuario) AND BDCODGRUPO = 1))
                    and((emp.bdexcluiremp is null)or(upper(emp.bdexcluiremp)<>'TRUE'))
     
           into bdcodemp do suspend;
     
           --Seleção das empresas grupo de usuário
           --onde NÃO tenha configuração no usuário
           for SELECT emp.bdcodemp--, emp.bdcodgrupo, grp.bdcodusu
               FROM tempresa_grupousuario emp
               inner join tempresas e on e.bdcodemp = emp.bdcodemp
               INNER JOIN tgrupousuario_usuario grp ON (grp.bdcodgrupo = emp.bdcodgrupo AND grp.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
               WHERE e.bdcodemp = :premp and
                     (NOT EXISTS (SELECT FIRST 1 * FROM tempresa_usuario WHERE bdcodusu = grp.bdcodusu))
                     and((e.bdexcluiremp is null)or(upper(e.bdexcluiremp)<>'TRUE'))
               into bdcodemp do suspend;
     
           --Seleção das empresas por escritório
           --onde NÃO tenha configuração no usuário e grupo de usuário
           for SELECT temp.bdcodemp--, tusu.bdcodgrupo, tusu.bdcodusu
               FROM tempresas temp
               INNER JOIN tgrupousuario tgrp ON (tgrp.bdcodesc = temp.bdcodesc)
               INNER JOIN tgrupousuario_usuario tusu ON (tusu.bdcodgrupo = tgrp.bdcodgrupo AND tusu.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
               WHERE temp.bdcodemp = :premp and
                     (NOT EXISTS (SELECT FIRST 1 * FROM tempresa_usuario WHERE bdcodusu = tusu.bdcodusu)) AND
                     (NOT EXISTS (SELECT FIRST 1 * FROM tempresa_grupousuario WHERE bdcodgrupo = tgrp.bdcodgrupo))
                     and((temp.bdexcluiremp is null)or(upper(temp.bdexcluiremp)<>'TRUE'))
               into bdcodemp do suspend;
     
     
               --Seleção das empresas
               --onde NÃO tenha configuração por usuário e grupo de usuário
               --Caso de não haver configurada essas restrições na base e usuário não ser master
           for SELECT emp.bdcodemp--, null, (select bdcodusu from sp_get_usuario) as bdcodusu
               FROM tempresas emp
               --left join vfin_base_tcliente cli on (cli.bdcodcli = emp.bdcodemp) --leonardo Pereira - 08/10/2018 - #90984 - Não permitir selecionar cliente eventual
               WHERE  emp.bdcodemp = :premp and
                      ((NOT EXISTS (SELECT FIRST 1 * FROM tempresa_usuario WHERE bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))) AND
                      (NOT EXISTS (SELECT FIRST 1 * FROM tempresa_grupousuario emp
                                   INNER JOIN tgrupousuario_usuario tgrp ON (tgrp.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
                                   WHERE emp.bdcodgrupo = tgrp.bdcodgrupo)) )
                     and((emp.bdexcluiremp is null)or(upper(emp.bdexcluiremp)<>'TRUE'))
               into bdcodemp do suspend;
     
     
           --Caso não tenha empresa por usuário e tenha algum grupo sem nenhuma empresa marcada
           --e sem escritório informado deve trazer todas as empresas
           if(WTEMEMPRESAPORUSUARIO = 0) then
           begin
              wGRUPOSEMFILTROEMPRESA = null;
               
              select first 1 GRP.BDCODGRUPO
              from TGRUPOUSUARIO_USUARIO GRP
              inner join tgrupousuario g on g.bdcodgrupo = grp.bdcodgrupo and ((g.bdcodesc is null) or (g.bdcodesc = 0))
              where GRP.BDCODUSU = (select BDCODUSU
                                    from SP_GET_USUARIO) and
                    (not exists(select first 1 E.BDCODEMP
                               from TEMPRESA_GRUPOUSUARIO E
                               where E.BDCODGRUPO = GRP.BDCODGRUPO))
              into wGRUPOSEMFILTROEMPRESA;
     
              if (wGRUPOSEMFILTROEMPRESA is not null) then
              begin
                 for select emp.BDCODEMP
                 from TEMPRESAS emp
                 where emp.bdcodemp = :premp and
                       ((emp.bdexcluiremp is null)or(upper(emp.bdexcluiremp)<>'TRUE'))
                 into bdcodemp do suspend;
              end
           end
         end
      else
         begin
              --Seleção das empresas por usuário
           for SELECT emp.bdcodemp--, grp.bdcodgrupo, emp.bdcodusu
           FROM tempresa_usuario emp
           inner join tempresas e on emp.bdcodemp = e.bdcodemp
           INNER JOIN tgrupousuario_usuario grp ON (grp.bdcodusu = emp.bdcodusu AND grp.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
           -- caso usuário pertence ao grupo master não deve listar empresas nesse sql
      WHERE (NOT exists (SELECT FIRST 1 * FROM tgrupousuario_usuario WHERE BDCODUSU = (SELECT bdcodusu FROM sp_get_usuario) AND BDCODGRUPO = 1))
            and((e.bdexcluiremp is null)or(upper(e.bdexcluiremp)<>'TRUE'))
      into bdcodemp do
         begin
            wTemEmpresaPorUsuario = 1;
            suspend;
         end

      -- listar todas as empresas caso usuário do grupo master
      for SELECT EMP.BDCODEMP FROM tempresas EMP
          WHERE(exists (SELECT FIRST 1 * FROM tgrupousuario_usuario WHERE BDCODUSU = (SELECT bdcodusu FROM sp_get_usuario) AND BDCODGRUPO = 1))
               and((emp.bdexcluiremp is null)or(upper(emp.bdexcluiremp)<>'TRUE'))

      into bdcodemp do suspend;

      --Seleção das empresas grupo de usuário
      --onde NÃO tenha configuração no usuário
      for SELECT emp.bdcodemp--, emp.bdcodgrupo, grp.bdcodusu
          FROM tempresa_grupousuario emp
          inner join tempresas e on e.bdcodemp = emp.bdcodemp
          INNER JOIN tgrupousuario_usuario grp ON (grp.bdcodgrupo = emp.bdcodgrupo AND grp.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
          WHERE (NOT EXISTS (SELECT FIRST 1 * FROM tempresa_usuario WHERE bdcodusu = grp.bdcodusu))
                and((e.bdexcluiremp is null)or(upper(e.bdexcluiremp)<>'TRUE'))
          into bdcodemp do suspend;

      --Seleção das empresas por escritório
      --onde NÃO tenha configuração no usuário e grupo de usuário
      for SELECT temp.bdcodemp--, tusu.bdcodgrupo, tusu.bdcodusu
          FROM tempresas temp
          INNER JOIN tgrupousuario tgrp ON (tgrp.bdcodesc = temp.bdcodesc)
          INNER JOIN tgrupousuario_usuario tusu ON (tusu.bdcodgrupo = tgrp.bdcodgrupo AND tusu.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
          WHERE (NOT EXISTS (SELECT FIRST 1 * FROM tempresa_usuario WHERE bdcodusu = tusu.bdcodusu)) AND
                (NOT EXISTS (SELECT FIRST 1 * FROM tempresa_grupousuario WHERE bdcodgrupo = tgrp.bdcodgrupo))
                and((temp.bdexcluiremp is null)or(upper(temp.bdexcluiremp)<>'TRUE'))
          into bdcodemp do suspend;


          --Seleção das empresas
          --onde NÃO tenha configuração por usuário e grupo de usuário
          --Caso de não haver configurada essas restrições na base e usuário não ser master
      for SELECT emp.bdcodemp--, null, (select bdcodusu from sp_get_usuario) as bdcodusu
          FROM tempresas emp
          --left join vfin_base_tcliente cli on (cli.bdcodcli = emp.bdcodemp) --leonardo Pereira - 08/10/2018 - #90984 - Não permitir selecionar cliente eventual
          WHERE ((NOT EXISTS (SELECT FIRST 1 * FROM tempresa_usuario WHERE bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))) AND 
                 (NOT EXISTS (SELECT FIRST 1 * FROM tempresa_grupousuario emp
                              INNER JOIN tgrupousuario_usuario tgrp ON (tgrp.bdcodusu = (SELECT bdcodusu FROM sp_get_usuario))
                              WHERE emp.bdcodgrupo = tgrp.bdcodgrupo)) )
                and((emp.bdexcluiremp is null)or(upper(emp.bdexcluiremp)<>'TRUE'))
          into bdcodemp do suspend;


      --Caso não tenha empresa por usuário e tenha algum grupo sem nenhuma empresa marcada
      --e sem escritório informado deve trazer todas as empresas
      if(WTEMEMPRESAPORUSUARIO = 0) then
      begin
         wGRUPOSEMFILTROEMPRESA = null;
          
         select first 1 GRP.BDCODGRUPO
         from TGRUPOUSUARIO_USUARIO GRP
         inner join tgrupousuario g on g.bdcodgrupo = grp.bdcodgrupo and ((g.bdcodesc is null) or (g.bdcodesc = 0))
         where GRP.BDCODUSU = (select BDCODUSU
                               from SP_GET_USUARIO) and
               (not exists(select first 1 E.BDCODEMP
                          from TEMPRESA_GRUPOUSUARIO E
                          where E.BDCODGRUPO = GRP.BDCODGRUPO))
         into wGRUPOSEMFILTROEMPRESA;

         if (wGRUPOSEMFILTROEMPRESA is not null) then
         begin
            for select emp.BDCODEMP
            from TEMPRESAS emp
            where ((emp.bdexcluiremp is null)or(upper(emp.bdexcluiremp)<>'TRUE'))
            into bdcodemp do suspend;
         end
      end
   end
   end
   else
   begin
      if (premp > 0) then
         begin
      for select emp.BDCODEMP
          from TEMPRESAS emp
               where emp.bdcodemp = :premp and
                     ((emp.bdexcluiremp is null)or(upper(emp.bdexcluiremp)<>'TRUE'))
           into bdcodemp do
              suspend;
         end
      else
         begin
           for select emp.BDCODEMP
               from TEMPRESAS emp
          where ((emp.bdexcluiremp is null)or(upper(emp.bdexcluiremp)<>'TRUE'))
      into bdcodemp do
         suspend;
   end
   end
end^

create or alter procedure SP_GET_PRODUTO_IMP (
    PRCODEMP integer,
    PRSESSAO integer,
    PRSESSAOTER integer,
    PRCODPRODARQ varchar(60),
    PRCNPJTER varchar(18),
    PRIETER varchar(20),
    PRDESCPROD varchar(200),
    PRNOMETER varchar(100),
    PRVER_ENT_E_SAI varchar(5),
    PRCODTER integer,
    PRCODPRODVINC integer)
returns (
    BDCODPROD integer,
    BDDESCPROD varchar(200))
as
declare variable WREF integer;
declare variable WVINCULOPART integer;
declare variable WORD integer;
declare variable WTER integer;
BEGIN
  --SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION',  'W_REF_IMP_'||:prSESSAO)) FROM RDB$DATABASE INTO :wREF;
  SELECT BDVALORINT FROM TTHREAD WHERE BDPARAM = 'W_REF_IMP_'||:prSESSAO INTO :wREF; -- Alt.: #201191 - Removida variavel de contexto...
  
  IF (:wREF IS NULL) THEN
    SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES') FROM RDB$DATABASE INTO :wREF;

  -- Alt.: #138509 - Busca a configuração do vinculo do participante, ja pesquisada anteriormente...
  --SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION',  'W_CONF_VINCULOPART_'||:prSESSAO)) FROM RDB$DATABASE INTO :wVINCULOPART;
  SELECT BDVALORINT FROM TTHREAD WHERE BDPARAM = 'W_CONF_VINCULOPART_'||:prSESSAO INTO :wVINCULOPART; -- Alt.: #201191 - Removida variavel de contexto...

  IF (:wVINCULOPART IS NULL) THEN
    BEGIN
      EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:wREF, NULL, NULL);
 
      SELECT PARINTEG.BDCODPLANOINCONS
      FROM VW_TEMPRESAS_REF_MAX_MIN EMP
      INNER JOIN TEMPRESAS TEMP ON (TEMP.BDCODEMP = EMP.BDCODEMP AND TEMP.BDCODEMP = :prCODEMP)
      LEFT OUTER JOIN VW_VEF_BASE_TEMPPARINTEG PARINTEG ON (PARINTEG.BDCODEMP = EMP.BDCODEMP AND PARINTEG.BDREFEMP = EMP.BDREFEMP)
      INTO :wVINCULOPART;

      --RDB$SET_CONTEXT('USER_SESSION', 'W_CONF_PLANOINC_'||:prSESSAO, :wVINCULOPART); -- Alt.: #138509 - Guarda a configuração do plano de inconsistencias...
      UPDATE OR INSERT INTO TTHREAD (BDPARAM, BDVALORINT) VALUES ('W_CONF_PLANOINC_'||:prSESSAO, :wVINCULOPART); -- Alt.: #201191 - Removida variavel de contexto...

      SELECT sp.bdVINCULOPART
      FROM SP_GET_ACOES_INCONSISTENCIA(:PRCODEMP, :wREF) SP
      INTO :wVINCULOPART;

      --RDB$SET_CONTEXT('USER_SESSION', 'W_CONF_VINCULOPART_'||:prSESSAO, :wVINCULOPART); -- Alt.: #138509 - Caso nao encontre, guarda para consultar apenas uma vez...
      UPDATE OR INSERT INTO TTHREAD (BDPARAM, BDVALORINT) VALUES ('W_CONF_VINCULOPART_'||:prSESSAO, :wVINCULOPART); -- Alt.: #201191 - Removida variavel de contexto...
    END

  BDCODPROD = NULL;
  PRVER_ENT_E_SAI = UPPER(:PRVER_ENT_E_SAI);

  IF ((:PRCODPRODARQ IS NOT NULL) OR (:PRCODPRODARQ <> '')) THEN
    BEGIN
      /*1ª tentativa - busca por participante */
      IF ((:PRCNPJTER <> '') AND (:PRCNPJTER <> '#')) THEN
        BEGIN
          IF (TRIM(:PRDESCPROD) <> '') THEN
            BEGIN
              -- Alt.: #138509 - Faz uma busca para ver se tem o participante por CNPJ + IE...
              SELECT FIRST 1 t.bdCODTER
              FROM TMP_TTERCEIRO t
              WHERE T.BDSESSAO = COALESCE(:PRSESSAOTER, 0)
                AND T.BDCGCTER = :PRCNPJTER
                AND ((:wVINCULOPART <> 1) OR (t.bdIETER IS NULL) OR (t.bdIETER = '') OR (:prIETER IS NULL) OR (:prIETER = '') OR (t.bdIETER = :prIETER)) -- Alt.: #138509 - Parâmetro para verificar o participante por IE...
              INTO :WTER;

              IF (:WTER IS NULL) THEN
                wVINCULOPART = 0; -- Alt.: #138509 - Caso não tenha o participante, vai mandar buscar por CNPJ apenas e desconsiderar o parâmetro das ações de incosistências...

              SELECT FIRST 1 PRO.BDCODPROD, PRO.BDDESCPRODBUSCA, bdORD, bdCODTER
              FROM (
                    SELECT P.BDCODPROD, P.BDDESCPRODBUSCA, bdORD, bdCODTER
                    FROM (
                          SELECT FIRST 1 P.BDCODPROD, P.BDDESCPRODBUSCA, 0 AS bdORD, t.bdCODTER
                          FROM (
                                SELECT PP.BDEDITCHAVE BDCODPROD, PP.BDCODTER, PP.BDCODENTRADA, TRIM(PP.BDDESCPRODBUSCA) BDDESCPRODBUSCA, PP.BDCODEMP
                                FROM TMP_TCADPRO_PART pp
                                WHERE PP.BDEDITCHAVE > 0 -- Alt.: #161237 #161240 #161241 - Apenas deve vincular, caso o produto tenha chave...
                                AND pp.BDCODENTRADA = :PRCODPRODARQ
                                AND ((pp.BDCODEMP = :PRCODEMP) OR (pp.BDCODEMP IS NULL))
                                AND pp.bddescprodbusca = :PRDESCPROD
                               ) P
                          --JOIN TMP_TTERCEIRO T ON(T.BDSESSAO IN (0, :PRSESSAOTER) AND T.BDCGCTER = :PRCNPJTER)
                          JOIN TMP_TTERCEIRO T ON(T.BDSESSAO = COALESCE(:PRSESSAOTER, 0) AND T.BDCGCTER = :PRCNPJTER AND T.BDEDITCHAVE = P.BDCODTER AND
                                                  ((:wVINCULOPART <> 1) OR (t.bdIETER IS NULL) OR (t.bdIETER = '') OR (:prIETER IS NULL) OR (:prIETER = '') OR (t.bdIETER = :prIETER))) -- Alt.: #138509 - Parâmetro para verificar o participante por IE...
                          --JOIN TMP_TCADPRO PRO ON(((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL)) AND PRO.BDEDITCHAVE = P.BDCODPROD) Alt.: #234582 - Estava utilizando um indice errado, ajustado para buscar todos os produtos e depois filtrar a empresa...
                          LEFT OUTER JOIN TMP_TCADPRO PRO ON(PRO.BDEDITCHAVE = P.BDCODPROD)
                          WHERE ((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL))
                          --ORDER BY P.BDCODEMP DESC, P.BDCODPROD
                          ORDER BY PRO.BDCODEMP DESC, P.BDCODEMP DESC, P.BDCODPROD  -- Alt.: 210471 - Deve priorizar os produtos que estão na TMP_TCADPRO com produto informado...
                         ) P
                    UNION ALL
                    SELECT P.BDCODPROD, P.BDDESCPRODBUSCA, bdORD, bdCODTER
                    FROM (
                          SELECT FIRST 1 P.BDCODPROD, P.BDDESCPRODBUSCA, 1 AS bdORD, t.bdCODTER
                          FROM (
                                SELECT PP.BDEDITCHAVE BDCODPROD, PP.BDCODTER, PP.BDCODENTRADA, TRIM(PP.BDDESCPRODBUSCA) BDDESCPRODBUSCA, PP.BDCODEMP
                                FROM TMP_TCADPRO_PART pp
                                WHERE PP.BDEDITCHAVE > 0 -- Alt.: #161237 #161240 #161241 - Apenas deve vincular, caso o produto tenha chave...
                                AND pp.BDCODENTRADA = :PRCODPRODARQ
                                AND pp.bddescprodbusca = :PRDESCPROD
                               ) P
                          --JOIN TMP_TTERCEIRO T ON(T.BDSESSAO IN (0, :PRSESSAOTER) AND T.BDCGCTER = :PRCNPJTER)
                          JOIN TMP_TTERCEIRO T ON(T.BDSESSAO = COALESCE(:PRSESSAOTER, 0) AND T.BDCGCTER = :PRCNPJTER AND T.BDEDITCHAVE = P.BDCODTER AND
                                                  ((:wVINCULOPART <> 1) OR (t.bdIETER IS NULL) OR (t.bdIETER = '') OR (:prIETER IS NULL) OR (:prIETER = '') OR (t.bdIETER = :prIETER))) -- Alt.: #138509 - Parâmetro para verificar o participante por IE...
                          --JOIN TMP_TCADPRO PRO ON(((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL)) AND PRO.BDEDITCHAVE = P.BDCODPROD) Alt.: #234582 - Estava utilizando um indice errado, ajustado para buscar todos os produtos e depois filtrar a empresa...
                          LEFT OUTER JOIN TMP_TCADPRO PRO ON(PRO.BDEDITCHAVE = P.BDCODPROD)
                          WHERE ((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL))
                          ORDER BY P.BDCODPROD
                         ) P
                   ) PRO
              ORDER BY bdORD
              INTO :BDCODPROD, :BDDESCPROD, :wORD, :wTER;
            END
          ELSE
            BEGIN
              -- Alt.: #138509 - Faz uma busca para ver se tem o participante por CNPJ + IE...
              SELECT FIRST 1 t.bdCODTER
              FROM TMP_TTERCEIRO t
              WHERE T.BDSESSAO = COALESCE(:PRSESSAOTER, 0)
                AND T.BDCGCTER = :PRCNPJTER
                AND ((:wVINCULOPART <> 1) OR (t.bdIETER IS NULL) OR (t.bdIETER = '') OR (:prIETER IS NULL) OR (:prIETER = '') OR (t.bdIETER = :prIETER)) -- Alt.: #138509 - Parâmetro para verificar o participante por IE...
              INTO :WTER;

              IF (:WTER IS NULL) THEN
                wVINCULOPART = 0; -- Alt.: #138509 - Caso não tenha o participante, vai mandar buscar por CNPJ apenas e desconsiderar o parâmetro das ações de incosistências...

              /*Se não tem descrição pega o primeiro produto*/
              SELECT FIRST 1 PRO.BDCODPROD, PRO.BDDESCPRODBUSCA
              FROM (
                    SELECT P.BDCODPROD, P.BDDESCPRODBUSCA
                    FROM (
                          SELECT FIRST 1 PP.BDEDITCHAVE BDCODPROD, PP.BDDESCPRODBUSCA
                          FROM TMP_TCADPRO_PART pp
                          JOIN TMP_TTERCEIRO T ON(T.BDSESSAO = COALESCE(:PRSESSAOTER, 0) AND T.BDCGCTER = :PRCNPJTER AND T.BDEDITCHAVE = PP.BDCODTER AND
                                                  ((:wVINCULOPART <> 1) OR (t.bdIETER IS NULL) OR (t.bdIETER = '') OR (:prIETER IS NULL) OR (:prIETER = '') OR (t.bdIETER = :prIETER))) -- Alt.: #138509 - Parâmetro para verificar o participante por IE...
                          --JOIN TMP_TCADPRO PRO ON(((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL)) AND PRO.BDEDITCHAVE = PP.BDCODPROD) Alt.: #234582 - Estava utilizando um indice errado, ajustado para buscar todos os produtos e depois filtrar a empresa...
                          LEFT OUTER JOIN TMP_TCADPRO PRO ON(PRO.BDEDITCHAVE = PP.BDCODPROD)
                          WHERE ((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL))
                          AND pp.bdcodentrada = :PRCODPRODARQ
                          AND ((pp.BDCODEMP = :PRCODEMP) OR (pp.BDCODEMP IS NULL))
                          ORDER BY pp.BDCODEMP DESC, PP.BDEDITCHAVE
                         ) P
                    UNION ALL
                    SELECT P.BDCODPROD, P.BDDESCPRODBUSCA
                    FROM (
                          SELECT FIRST 1 PP.BDEDITCHAVE BDCODPROD, PP.BDDESCPRODBUSCA
                          FROM TMP_TCADPRO_PART pp
                          JOIN TMP_TTERCEIRO T ON(T.BDSESSAO = COALESCE(:PRSESSAOTER, 0) AND T.BDCGCTER = :PRCNPJTER AND T.BDEDITCHAVE = PP.BDCODTER AND
                                                  ((:wVINCULOPART <> 1) OR (t.bdIETER IS NULL) OR (t.bdIETER = '') OR (:prIETER IS NULL) OR (:prIETER = '') OR (t.bdIETER = :prIETER))) -- Alt.: #138509 - Parâmetro para verificar o participante por IE...
                          --JOIN TMP_TCADPRO PRO ON(((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL)) AND PRO.BDEDITCHAVE = PP.BDCODPROD) Alt.: #234582 - Estava utilizando um indice errado, ajustado para buscar todos os produtos e depois filtrar a empresa...
                          LEFT OUTER JOIN TMP_TCADPRO PRO ON(PRO.BDEDITCHAVE = PP.BDCODPROD)
                          WHERE ((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL))
                          AND pp.bdcodentrada = :PRCODPRODARQ
                          ORDER BY PP.BDEDITCHAVE
                         ) P
                   ) PRO
              INTO :BDCODPROD, :BDDESCPROD;
            END
        END
      ELSE
        BEGIN
          IF ((:PRNOMETER <> '') AND (:PRNOMETER <> '#') AND (COALESCE(:BDCODPROD, 0) = 0)) THEN
            BEGIN
              IF (TRIM(:PRDESCPROD) <> '') THEN
                BEGIN
                  SELECT FIRST 1 PRO.BDCODPROD, PRO.BDDESCPRODBUSCA
                  FROM (
                        SELECT P.BDCODPROD, P.BDDESCPRODBUSCA
                        FROM (
                  SELECT FIRST 1 P.BDCODPROD, P.BDDESCPRODBUSCA
                  FROM (
                        SELECT pp.BDEDITCHAVE BDCODPROD, pp.BDCODTER, TRIM(pp.BDDESCPRODBUSCA) BDDESCPRODBUSCA, pp.BDCODEMP
                        FROM TMP_TCADPRO_PART pp
                        WHERE pp.BDDESCPRODBUSCA = :PRDESCPROD
                        AND ((pp.BDCODEMP = :PRCODEMP) OR (pp.BDCODEMP IS NULL))
                       ) P
                  --JOIN TMP_TTERCEIRO T ON(T.BDSESSAO IN (0, :PRSESSAOTER) AND UPPER(T.BDNOMETER) = UPPER(:PRNOMETER))
                  JOIN TMP_TTERCEIRO T ON(T.BDSESSAO = COALESCE(:PRSESSAOTER, 0) AND T.BDNOMETER = :PRNOMETER AND T.BDEDITCHAVE = P.BDCODTER)
                  --JOIN TMP_TCADPRO PRO ON(((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL)) AND PRO.BDEDITCHAVE = P.BDCODPROD) Alt.: #234582 - Estava utilizando um indice errado, ajustado para buscar todos os produtos e depois filtrar a empresa...
                  LEFT OUTER JOIN TMP_TCADPRO PRO ON(PRO.BDEDITCHAVE = P.BDCODPROD)
                  WHERE ((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL))
                  ORDER BY P.BDCODEMP DESC, P.BDCODPROD
                             ) P
                        UNION ALL
                        SELECT FIRST 1 P.BDCODPROD, P.BDDESCPRODBUSCA
                        FROM (
                        SELECT P.BDCODPROD, P.BDDESCPRODBUSCA
                        FROM (
                              SELECT pp.BDEDITCHAVE BDCODPROD, pp.BDCODTER, TRIM(pp.BDDESCPRODBUSCA) BDDESCPRODBUSCA, pp.BDCODEMP
                              FROM TMP_TCADPRO_PART pp
                              WHERE pp.BDDESCPRODBUSCA = :PRDESCPROD
                             ) P
                        --JOIN TMP_TTERCEIRO T ON(T.BDSESSAO IN (0, :PRSESSAOTER) AND UPPER(T.BDNOMETER) = UPPER(:PRNOMETER))
                        JOIN TMP_TTERCEIRO T ON(T.BDSESSAO = COALESCE(:PRSESSAOTER, 0) AND T.BDNOMETER = :PRNOMETER AND T.BDEDITCHAVE = P.BDCODTER)
                        --JOIN TMP_TCADPRO PRO ON(((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL)) AND PRO.BDEDITCHAVE = P.BDCODPROD) Alt.: #234582 - Estava utilizando um indice errado, ajustado para buscar todos os produtos e depois filtrar a empresa...
                        LEFT OUTER JOIN TMP_TCADPRO PRO ON(PRO.BDEDITCHAVE = P.BDCODPROD)
                        WHERE ((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL))
                        ORDER BY P.BDCODPROD
                             ) P
                       ) PRO
                  INTO :BDCODPROD, :BDDESCPROD;
                END
              ELSE
                BEGIN
                  SELECT FIRST 1 PRO.BDCODPROD, PRO.BDDESCPRODBUSCA
                  FROM (
                        SELECT P.BDCODPROD, P.BDDESCPRODBUSCA
                        FROM (
                  SELECT FIRST 1 pp.BDEDITCHAVE BDCODPROD, pp.BDDESCPRODBUSCA
                  FROM TMP_TCADPRO_PART pp
                  JOIN TMP_TTERCEIRO T ON(T.BDSESSAO = COALESCE(:PRSESSAOTER, 0) AND T.BDNOMETER = :PRNOMETER AND T.BDEDITCHAVE = PP.BDCODTER)
                  --JOIN TMP_TCADPRO PRO ON(((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL)) AND PRO.BDEDITCHAVE = PP.BDCODPROD) Alt.: #234582 - Estava utilizando um indice errado, ajustado para buscar todos os produtos e depois filtrar a empresa...
                  LEFT OUTER JOIN TMP_TCADPRO PRO ON(PRO.BDEDITCHAVE = PP.BDCODPROD)
                  WHERE ((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL))
                  AND ((pp.BDCODEMP = :PRCODEMP) OR (pp.BDCODEMP IS NULL))
                  ORDER BY pp.BDCODEMP DESC, pp.BDEDITCHAVE
                             ) P
                        UNION ALL
                        SELECT FIRST 1 pp.BDCODPROD, pp.BDDESCPRODBUSCA
                        FROM (
                        SELECT pp.BDEDITCHAVE BDCODPROD, pp.BDDESCPRODBUSCA
                        FROM TMP_TCADPRO_PART pp
                        JOIN TMP_TTERCEIRO T ON(T.BDSESSAO = COALESCE(:PRSESSAOTER, 0) AND T.BDNOMETER = :PRNOMETER AND T.BDEDITCHAVE = PP.BDCODTER)
                        --JOIN TMP_TCADPRO PRO ON(((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL)) AND PRO.BDEDITCHAVE = PP.BDCODPROD) Alt.: #234582 - Estava utilizando um indice errado, ajustado para buscar todos os produtos e depois filtrar a empresa...
                        LEFT OUTER JOIN TMP_TCADPRO PRO ON(PRO.BDEDITCHAVE = PP.BDCODPROD)
                        WHERE ((PRO.BDCODEMP = :PRCODEMP) OR (PRO.BDCODEMP IS NULL))
                        ORDER BY pp.BDEDITCHAVE
                             ) pp
                       ) PRO
                  INTO :BDCODPROD, :BDDESCPROD;
                END
            END
        END
        /*Essa validação não vai mais ser feita nesse novo tipo de importação por que na memoria só tem o código sequencial do terceiro*/
          /*begin
            prDAOProdPart.SearchKey(['bdCODTER','bdCODENTRADA'],[prCodTer,prCodProdArq]);
            while not prDAOProdPart.Eof do
              begin
                if (prDAOProdPart.FN('bdCODTER').AsInteger <> prCodTer) or (AnsiUpperCase(prDAOProdPart.FN('BDCODENTRADA').AsString) <> AnsiUpperCase(prCodProdArq)) then
                  break;

                if prDescProdArqLay = '' then
                  begin
                    wOK := True;
                    break;
                  end;

                if (AnsiUpperCase(prDAOProdPart.FN('BDDESCPROD').AsString) = AnsiUpperCase(prDescProdArqLay)) or
                   (AnsiUpperCase(prDAOProdPart.FN('BDDESCPRODBUSCA').AsString) = AnsiUpperCase(prDescProdArqLay)) then
                  begin
                    wOK := True;
                    break;
                  end;

                prDAOProdPart.Next;
              end;
          end;*/

      --IF (:BDCODPROD > 0) THEN
      IF ((:BDCODPROD > 0) AND ((:BDDESCPROD IS NULL) OR (:BDDESCPROD = ''))) THEN
        BEGIN
          SELECT FIRST 1 CT.BDDESCPROD
          FROM TMP_TCADPRO_TEMP CT
          WHERE CT.BDSESSAO = :PRSESSAO
          AND CT.BDCODEMP = :PRCODEMP
          AND CT.BDEDITCHAVE = :BDCODPROD
          INTO :BDDESCPROD;
        END
      /*ELSE
        BEGIN
          if (Assigned(prDAOProdPart.InstanceFactory.FindField('bdCODPRODVINC'))) and (prDAOProdPart.FN('bdCODPRODVINC').AsInteger > 0) and
                      (prDAOProdVinc.SearchKeyPos(['bdCODEMP','bdCODPRODVINC'],[prCodEmp,prDAOProdPart.FN('bdCODPRODVINC').AsInteger])) then
            begin
              prFieldDesc := prDAOProdVinc.FN('BDDESCPROD').AsString;
              wAchou      := True;
            end;
        END*/

      IF (((:BDCODPROD IS NULL) OR (:BDCODPROD = 0)) AND (UPPER(:PRVER_ENT_E_SAI) = 'TRUE')) THEN
        BEGIN
          SELECT FIRST 1 P.BDEDITCHAVE BDCODPROD, P.BDDESCPROD
          FROM TMP_TCADPRO/*_TEMP*/ P
          WHERE P.BDCODSAIDA = :PRCODPRODARQ
          AND P.BDcodemp = :PRCODEMP
          ORDER BY p.BDEDITCHAVE
          INTO :BDCODPROD, :BDDESCPROD;
        END

      IF (((:BDCODPROD IS NULL) OR (:BDCODPROD = 0)) AND (COALESCE(:PRCODPRODVINC, 0) > 0)) THEN
        BEGIN
          SELECT CT.BDEDITCHAVE BDCODPROD, CT.BDDESCPROD
          FROM TMP_TCADPRO_TEMP CT
          WHERE CT.BDSESSAO = :PRSESSAO
          AND CT.BDCODEMP = :PRCODEMP
          AND CT.BDCODPRODVINC = :PRCODPRODVINC
          INTO :BDCODPROD, :BDDESCPROD;
        END

      IF ((:BDCODPROD IS NULL) OR (:BDCODPROD = 0)) THEN
          SELECT FIRST 1 P.bdCODPROD, P.BDDESCPRODBUSCA FROM TCADPRO_PART P WHERE P.bdcodter = :PRCODTER AND P.bdCODENTRADA = :PRCODPRODARQ ORDER BY P.bdCODPROD INTO :BDCODPROD, :BDDESCPROD;

      /*Sol: 14207 Patrick T. Sá 07/03/2017. Busca pela descrição do produto na empresa feita para uma situação que faz errado na versão do site.
        Para teste usar a nota de entrada que está em "computador do elizeu\Repositorio\iguacu teste\unica\1" */
      IF (((:BDCODPROD IS NULL) OR (:BDCODPROD = 0)) AND (:PRDESCPROD <> '')) THEN
        SELECT FIRST 1 P.BDEDITCHAVE, P.BDDESCPROD FROM TMP_TCADPRO P WHERE P.BDCODEMP = :PRCODEMP AND P.BDDESCPROD = :PRDESCPROD ORDER BY P.BDEDITCHAVE INTO :BDCODPROD, :BDDESCPROD;
    END

    SUSPEND;
END^

CREATE OR ALTER procedure SP_INS_UPT_TMP_TCADPRO (
    PRSESSAO integer,
    PRREF integer,
    PRCODSAIDA varchar(60),
    PRCODENTRADA varchar(60),
    PRCODPROD integer,
    PRCODEMP integer,
    PRCODTER integer,
    PRCNPJTER varchar(20),
    PRIETER varchar(20),
    PRDESCPROD varchar(200),
    PRORIGEMPROD integer,
    PROPERATION varchar(4),
    PRSEQ_PART integer,
    PRINS_PROUNICO DM_BOOLEAN)
as
declare variable WORIGEMPROD integer;
declare variable WCODTERLAYOUT integer;
declare variable WCNPJTERLAYOUT varchar(18);
declare variable WIETERLAYOUT varchar(20);
declare variable WCODEMP integer;
declare variable WCODSAIDA varchar(60) collate WIN_PTBR;
declare variable WAPEPROD varchar(30) collate WIN_PTBR;
declare variable WDESCPROD varchar(200) collate WIN_PTBR;
declare variable WAPELIDOUNICO varchar(30) collate WIN_PTBR;
declare variable WDESCRICAOUNICA varchar(200) collate WIN_PTBR;
declare variable WCODIGOEAN varchar(20) collate WIN_PTBR;
declare variable WCODTER integer;
declare variable WCODENTRADA varchar(60) collate WIN_PTBR;
declare variable WCODTIPO integer;
declare variable WCODGEN integer;
declare variable WCODSER integer;
declare variable WCODCOMBANP integer;
declare variable WCODUNIMED integer;
declare variable WAPEUNIMED varchar(5) collate WIN_PTBR;
declare variable WNCMPROD integer;
declare variable WCODTABINCID integer;
declare variable WGRUPO integer;
declare variable WORDEMMARCA integer;
declare variable WCODCSTIPISAI integer;
declare variable WCODCSTIPIENT integer;
declare variable WCODCSTICMS integer;
declare variable WCODCSTPISSAI integer;
declare variable WCODCSTPISENT integer;
declare variable WCODCSTCOFENT integer;
declare variable WCODCSTCOFSAI integer;
declare variable WVINCULOPART integer;
declare variable WALIQFCP DM_NUMERIC_7_4_ALIQ;
declare variable WPRODINCENTIVADO DM_BOOLEAN;
BEGIN
  /*Sol: 14207 Patrick T. Sá 10/10/2016. Está sp é usada na SP_ATUALIZAR_TMP_TCADPRO para inserir ou atualizar os produtos na importação.*/
  PROPERATION = UPPER(:PROPERATION);
  PRCODPROD   = COALESCE(:PRCODPROD, 0);
  PRCODSAIDA  = COALESCE(:PRCODSAIDA, '');
  PRCODENTRADA= COALESCE(:PRCODENTRADA, '');
  PRDESCPROD  = COALESCE(:PRDESCPROD, '');
  PRCNPJTER   = COALESCE(:PRCNPJTER, '');
  PRIETER     = COALESCE(:PRIETER, '');

  -- Alt.: #138509 - Busca a configuração do vinculo do participante, ja pesquisada anteriormente...
  --SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION',  'W_CONF_VINCULOPART_'||:prSESSAO)) FROM RDB$DATABASE INTO :wVINCULOPART;
  SELECT BDVALORINT FROM TTHREAD WHERE BDPARAM = 'W_CONF_VINCULOPART_'||:prSESSAO INTO :wVINCULOPART; -- Alt.: #201191 - Removida variavel de contexto...
 
  IF (:wVINCULOPART IS NULL) THEN
    BEGIN
      EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREF, NULL, NULL);
 
      SELECT PARINTEG.BDCODPLANOINCONS
      FROM VW_TEMPRESAS_REF_MAX_MIN EMP
      INNER JOIN TEMPRESAS TEMP ON (TEMP.BDCODEMP = EMP.BDCODEMP AND TEMP.BDCODEMP = :prCODEMP)
      LEFT OUTER JOIN VW_VEF_BASE_TEMPPARINTEG PARINTEG ON (PARINTEG.BDCODEMP = EMP.BDCODEMP AND PARINTEG.BDREFEMP = EMP.BDREFEMP)
      INTO :wVINCULOPART;

      --RDB$SET_CONTEXT('USER_SESSION', 'W_CONF_PLANOINC_'||:prSESSAO, :wVINCULOPART); -- Alt.: #138509 - Guarda a configuração do plano de inconsistencias...
      UPDATE OR INSERT INTO TTHREAD (BDPARAM, BDVALORINT) VALUES ('W_CONF_PLANOINC_'||:prSESSAO, :wVINCULOPART); -- Alt.: #201191 - Removida variavel de contexto...

      SELECT sp.bdVINCULOPART
      FROM SP_GET_ACOES_INCONSISTENCIA(:PRCODEMP, :prREF) SP
      INTO :wVINCULOPART;

      --RDB$SET_CONTEXT('USER_SESSION', 'W_CONF_VINCULOPART_'||:prSESSAO, :wVINCULOPART); -- Alt.: #138509 - Caso nao encontre, guarda para consultar apenas uma vez...
      UPDATE OR INSERT INTO TTHREAD (BDPARAM, BDVALORINT) VALUES ('W_CONF_VINCULOPART_'||:prSESSAO, :wVINCULOPART); -- Alt.: #201191 - Removida variavel de contexto...
    END

  IF (:PROPERATION = 'INS') THEN  /*Inserir novo*/
    BEGIN
      /* Alt.: #210594 - Quando tentou importar e por algum motivo deu erro, estava ficando um produto zerado nas tabelas temporarias,
         Com isso, o sistema se perde e nao consegue mais fazer os vinculos dos produtos, estava sempre tentando vincular com esse zerado e nao conseguia mais
         fazer os vinculos nos lancamentos, por isso se vier aqui, vai tentar excluir da tabela, antes de inserir o produto... */
      DELETE FROM TMP_TCADPRO t
      WHERE t.bdEDITCHAVE = 0 AND t.bdCODPROD = 0
        AND ((t.bdSESSAO > 0) and (t.bdSESSAO < :PRSESSAO)) -- Apenas produtos que tenha tentado importar
        AND t.bdCODSAIDA = :prCODSAIDA
        AND t.bdCODENTRADA = :prCODENTRADA
        AND EXISTS(SELECT *
                    FROM TMP_TCADPRO_A_VALIDAR a
                    WHERE a.bdCODSAIDA = t.bdCODSAIDA
                      AND a.bdCODENTRADA = t.bdCODENTRADA
                      AND a.bdAPELIDOUNICO = t.bdAPELIDOUNICO AND a.bdDESCRICAOUNICA = t.bdDESCRICAOUNICA /*AND a.bdCODIGOEAN = t.bdCODIGOEAN*/
                      AND a.bdCODTIPO = t.bdCODTIPO AND a.bdCODGEN = t.bdCODGEN /*AND a.bdCODSER = t.bdCODSER AND a.bdCODCOMBANP = t.bdCODCOMBANP*/
                      AND a.bdCODSAIDA = t.bdCODSAIDA AND a.bdCODENTRADA = t.bdCODENTRADA AND a.bdDESCPROD = t.bdDESCPROD AND a.bdCODTERLAYOUT = t.bdCODTERLAYOUT );
 
      IF (:PRORIGEMPROD = 1) THEN
        BEGIN
          /*Insere produto unico*/
          IF (:PRINS_PROUNICO = 'TRUE') THEN
            BEGIN
              INSERT INTO TMP_TCADPRO(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDAPELIDOUNICO, BDDESCRICAOUNICA,
                                      BDCODIGOEAN, BDCODTIPO, BDCODGEN, BDCODSER, BDCODCOMBANP,
                                      BDCODSAIDA, BDCODENTRADA, BDDESCPROD, BDCODTERLAYOUT)
              SELECT FIRST 1 :PRSESSAO, :PRCODPROD, :PRCODPROD, A.BDAPELIDOUNICO, A.BDDESCRICAOUNICA,
                              A.BDCODIGOEAN, A.BDCODTIPO, A.BDCODGEN, A.BDCODSER, A.BDCODCOMBANP,
                              A.BDCODSAIDA, A.BDCODENTRADA, A.BDDESCPROD, A.BDCODTERLAYOUT
              FROM TMP_TCADPRO_A_VALIDAR A
              WHERE A.BDCODSAIDA = :PRCODSAIDA
              AND A.BDCODENTRADA = :PRCODENTRADA;
            END

          /*Insere na empresa*/
          INSERT INTO TMP_TCADPRO(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDORIGEMPROD, BDCODTERLAYOUT, BDCNPJTERLAYOUT, bdIETERLAYOUT, BDCODEMP, BDCODSAIDA, BDAPEPROD,
                                  BDDESCPROD, BDAPELIDOUNICO, BDDESCRICAOUNICA, BDCODIGOEAN, BDCODTER, BDCODENTRADA, BDCODTIPO, BDCODGEN,
                                  BDCODSER, BDCODCOMBANP, BDCODUNIMED, BDAPEUNIMED, BDNCMPROD, BDCODTABINCID, BDGRUPO, BDORDEMMARCA,
                                  BDCODCSTIPISAI, BDCODCSTIPIENT, BDCODCSTICMS, BDCODCSTPISSAI, BDCODCSTPISENT, BDCODCSTCOFENT, BDCODCSTCOFSAI,BDALIQFCP, BDPRODINCENTIVADO)
          SELECT FIRST 1 :PRSESSAO, :PRCODPROD, :PRCODPROD, A.BDORIGEMPROD, A.BDCODTERLAYOUT, A.BDCNPJTERLAYOUT, a.bdIETERLAYOUT, A.BDCODEMP, A.BDCODSAIDA,
                         A.BDAPEPROD, A.BDDESCPROD, A.BDAPELIDOUNICO, A.BDDESCRICAOUNICA, A.BDCODIGOEAN, A.BDCODTER, A.BDCODENTRADA, A.BDCODTIPO,
                         A.BDCODGEN, A.BDCODSER, A.BDCODCOMBANP, A.BDCODUNIMED, A.BDAPEUNIMED, A.BDNCMPROD, A.BDCODTABINCID, A.BDGRUPO, A.BDORDEMMARCA,
                         A.BDCODCSTIPISAI, A.BDCODCSTIPIENT, A.BDCODCSTICMS, A.BDCODCSTPISSAI, A.BDCODCSTPISENT, A.BDCODCSTCOFENT, A.BDCODCSTCOFSAI, A.BDALIQFCP, A.BDPRODINCENTIVADO
          FROM TMP_TCADPRO_A_VALIDAR A
          WHERE A.BDCODSAIDA = :PRCODSAIDA
          AND A.BDCODENTRADA = :PRCODENTRADA;
        END
      ELSE
        BEGIN
          /*Insere produto unico*/
          IF (:PRINS_PROUNICO = 'TRUE') THEN
            BEGIN
              -- Alt.: #138509 - Primeiro busca por CNPJ + IE...
              SELECT FIRST 1 A.BDCODTERLAYOUT
              FROM TMP_TCADPRO_A_VALIDAR A
              WHERE A.BDCODSAIDA = :PRCODSAIDA
              AND A.BDCODENTRADA = :PRCODENTRADA
              AND A.BDDESCPROD = :PRDESCPROD
              AND A.BDCNPJTERLAYOUT = :PRCNPJTER
              AND ((a.bdIETERLAYOUT IS NOT NULL) OR (a.bdIETERLAYOUT <> '') OR (a.bdIETERLAYOUT = :prIETER))
              INTO :wCODTERLAYOUT;

              IF (:wCODTERLAYOUT IS NOT NULL) THEN
                BEGIN
                  INSERT INTO TMP_TCADPRO(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDAPELIDOUNICO, BDDESCRICAOUNICA,
                                          BDCODIGOEAN, BDCODTIPO, BDCODGEN, BDCODSER, BDCODCOMBANP,
                                          BDCODSAIDA, BDCODENTRADA, BDDESCPROD, BDCODTERLAYOUT)
                  SELECT FIRST 1 :PRSESSAO, :PRCODPROD, :PRCODPROD, A.BDAPELIDOUNICO, A.BDDESCRICAOUNICA,
                                  A.BDCODIGOEAN, A.BDCODTIPO, A.BDCODGEN, A.BDCODSER, A.BDCODCOMBANP,
                                  A.BDCODSAIDA, A.BDCODENTRADA, A.BDDESCPROD, A.BDCODTERLAYOUT
                  FROM TMP_TCADPRO_A_VALIDAR A
                  WHERE A.BDCODSAIDA = :PRCODSAIDA
                  AND A.BDCODENTRADA = :PRCODENTRADA
                  AND A.BDDESCPROD = :PRDESCPROD
                  AND A.BDCNPJTERLAYOUT = :PRCNPJTER
                  AND ((a.bdIETERLAYOUT IS NOT NULL) OR (a.bdIETERLAYOUT <> '') OR (a.bdIETERLAYOUT = :prIETER));
                END
              ELSE
                BEGIN -- Alt.: #138509 - Caso não encontre pelo CNPJ + IE, tenta pelo CNPJ apenas...
                  INSERT INTO TMP_TCADPRO(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDAPELIDOUNICO, BDDESCRICAOUNICA,
                                          BDCODIGOEAN, BDCODTIPO, BDCODGEN, BDCODSER, BDCODCOMBANP,
                                          BDCODSAIDA, BDCODENTRADA, BDDESCPROD, BDCODTERLAYOUT)
                  SELECT FIRST 1 :PRSESSAO, :PRCODPROD, :PRCODPROD, A.BDAPELIDOUNICO, A.BDDESCRICAOUNICA,
                                  A.BDCODIGOEAN, A.BDCODTIPO, A.BDCODGEN, A.BDCODSER, A.BDCODCOMBANP,
                                  A.BDCODSAIDA, A.BDCODENTRADA, A.BDDESCPROD, A.BDCODTERLAYOUT
                  FROM TMP_TCADPRO_A_VALIDAR A
                  WHERE A.BDCODSAIDA = :PRCODSAIDA
                  AND A.BDCODENTRADA = :PRCODENTRADA
                  AND A.BDDESCPROD = :PRDESCPROD
                  AND A.BDCNPJTERLAYOUT = :PRCNPJTER
                  ORDER BY a.bdCODTERLAYOUT;
                END
            END

          -- Alt.: #138509 - Faz uma busca para ver se tem o participante por CNPJ + IE...
          SELECT FIRST 1 A.BDCODTERLAYOUT
          FROM TMP_TCADPRO_A_VALIDAR A
          WHERE A.BDCODSAIDA = :PRCODSAIDA
          AND A.BDCODENTRADA = :PRCODENTRADA
          AND A.BDDESCPROD = :PRDESCPROD
          AND A.BDCNPJTERLAYOUT = :PRCNPJTER
          AND ((:wVINCULOPART <> 1) OR (a.bdIETERLAYOUT IS NULL) OR (a.bdIETERLAYOUT = '') OR (a.bdIETERLAYOUT = :prIETER)) -- Alt.: #138509 - Parâmetro para verificar o participante por IE...
          INTO :wCODTERLAYOUT;

          IF (:wCODTERLAYOUT IS NULL) THEN
            wVINCULOPART = 0; -- Alt.: #138509 - Caso não tenha o participante, vai mandar buscar por CNPJ apenas e desconsiderar o parâmetro das ações de incosistências...

          /*Insere na empresa*/
          INSERT INTO TMP_TCADPRO(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDORIGEMPROD, BDCODTERLAYOUT, BDCNPJTERLAYOUT, bdIETERLAYOUT, BDCODEMP, BDCODSAIDA, BDAPEPROD,
                                  BDDESCPROD, BDAPELIDOUNICO, BDDESCRICAOUNICA, BDCODIGOEAN, BDCODTER, BDCODENTRADA, BDCODTIPO, BDCODGEN,
                                  BDCODSER, BDCODCOMBANP, BDCODUNIMED, BDAPEUNIMED, BDNCMPROD, BDCODTABINCID, BDGRUPO, BDORDEMMARCA,
                                  BDCODCSTIPISAI, BDCODCSTIPIENT, BDCODCSTICMS, BDCODCSTPISSAI, BDCODCSTPISENT, BDCODCSTCOFENT, BDCODCSTCOFSAI, BDSEQ_PART, BDALIQFCP, BDPRODINCENTIVADO)
          SELECT FIRST 1 :PRSESSAO, :PRCODPROD, :PRCODPROD, A.BDORIGEMPROD, A.BDCODTERLAYOUT, A.BDCNPJTERLAYOUT, a.bdIETERLAYOUT, A.BDCODEMP, A.BDCODSAIDA,
                         A.BDAPEPROD, A.BDDESCPROD, A.BDAPELIDOUNICO, A.BDDESCRICAOUNICA, A.BDCODIGOEAN, A.BDCODTER, A.BDCODENTRADA, A.BDCODTIPO,
                         A.BDCODGEN, A.BDCODSER, A.BDCODCOMBANP, A.BDCODUNIMED, A.BDAPEUNIMED, A.BDNCMPROD, A.BDCODTABINCID, A.BDGRUPO, A.BDORDEMMARCA,
                         A.BDCODCSTIPISAI, A.BDCODCSTIPIENT, A.BDCODCSTICMS, A.BDCODCSTPISSAI, A.BDCODCSTPISENT, A.BDCODCSTCOFENT, A.BDCODCSTCOFSAI, :PRSEQ_PART, A.BDALIQFCP, BDPRODINCENTIVADO
          FROM TMP_TCADPRO_A_VALIDAR A
          WHERE A.BDCODSAIDA = :PRCODSAIDA
          AND A.BDCODENTRADA = :PRCODENTRADA
          AND A.BDDESCPROD = :PRDESCPROD
          AND A.BDCNPJTERLAYOUT = :PRCNPJTER
          AND ((:wVINCULOPART <> 1) OR (a.bdIETERLAYOUT IS NULL) OR (a.bdIETERLAYOUT = '') OR (a.bdIETERLAYOUT = :prIETER)) -- Alt.: #138509 - Parâmetro para verificar o participante por IE...
          ORDER BY a.bdCODTERLAYOUT;

          INSERT INTO TMP_TCADPRO_PART(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDCODTER, BDCODENTRADA, BDDESCPRODBUSCA, BDCODEMP, BDSEQ_PART)
          SELECT FIRST 1 :PRSESSAO, A.BDEDITCHAVE, :PRCODPROD, A.BDCODTERLAYOUT, A.BDCODENTRADA, A.BDDESCPROD, A.BDCODEMP, :PRSEQ_PART
          FROM TMP_TCADPRO_A_VALIDAR A
          WHERE A.BDCODSAIDA = :PRCODSAIDA
          AND A.BDCODENTRADA = :PRCODENTRADA
          AND A.BDCNPJTERLAYOUT = :PRCNPJTER
          AND ((:wVINCULOPART <> 1) OR (a.bdIETERLAYOUT IS NULL) OR (a.bdIETERLAYOUT = '') OR (a.bdIETERLAYOUT = :prIETER)) -- Alt.: #138509 - Parâmetro para verificar o participante por IE...
          AND TRIM(A.BDDESCPROD) = :PRDESCPROD    
          AND A.BDORIGEMPROD = 0
          AND NOT EXISTS (
                          SELECT PP.BDEDITCHAVE
                          FROM TMP_TCADPRO_PART PP
                          WHERE PP.BDCODTER = :PRCODTER
                          AND PP.BDCODENTRADA = :PRCODENTRADA
                          AND PP.BDDESCPRODBUSCA = :PRDESCPROD
                         )
          ORDER BY a.bdCODTERLAYOUT;
        END
    END
  ELSE
    BEGIN
      IF ((:PROPERATION = 'UPT') AND ((:PRCODPROD IS NOT NULL) OR (:PRCODPROD > 0))) THEN /*Atualizar existente*/
        BEGIN
          IF (:PRORIGEMPROD = 1) THEN
            BEGIN
              SELECT FIRST 1 COALESCE(A.BDORIGEMPROD, 0),
                             COALESCE(A.BDCODTERLAYOUT, 0),
                             COALESCE(A.BDCNPJTERLAYOUT, ''),
                             COALESCE(a.bdIETERLAYOUT, ''),
                             COALESCE(A.BDCODEMP, 0),
                             COALESCE(A.BDCODSAIDA, ''),
                             COALESCE(A.BDAPEPROD, ''),
                             COALESCE(A.BDDESCPROD, ''),
                             COALESCE(A.BDAPELIDOUNICO, ''),
                             COALESCE(A.BDDESCRICAOUNICA, ''),
                             COALESCE(A.BDCODIGOEAN, ''),
                             COALESCE(A.BDCODTER, 0),
                             COALESCE(A.BDCODENTRADA, ''),
                             A.BDCODTIPO,
                             A.BDCODGEN,
                             A.BDCODSER,
                             A.BDCODCOMBANP,
                             A.BDCODUNIMED,
                             COALESCE(A.BDAPEUNIMED, ''),
                             A.BDNCMPROD,
                             A.BDCODTABINCID,
                             A.BDGRUPO,
                             A.BDORDEMMARCA,
                             A.BDCODCSTIPISAI,
                             A.BDCODCSTIPIENT,
                             A.BDCODCSTICMS,
                             A.BDCODCSTPISSAI,
                             A.BDCODCSTPISENT,
                             A.BDCODCSTCOFENT,
                             A.BDCODCSTCOFSAI,
                             A.BDALIQFCP,
                             A.BDPRODINCENTIVADO
              FROM TMP_TCADPRO_A_VALIDAR A
              WHERE A.BDCODSAIDA = :PRCODSAIDA
              AND A.BDCODENTRADA = :PRCODENTRADA
              INTO :wORIGEMPROD,
                   :wCODTERLAYOUT,
                   :wCNPJTERLAYOUT,
                   :wIETERLAYOUT,
                   :wCODEMP,
                   :wCODSAIDA,
                   :wAPEPROD,
                   :wDESCPROD,
                   :wAPELIDOUNICO,
                   :wDESCRICAOUNICA,
                   :wCODIGOEAN,
                   :wCODTER,
                   :wCODENTRADA,
                   :wCODTIPO,
                   :wCODGEN,
                   :wCODSER,
                   :wCODCOMBANP,
                   :wCODUNIMED,
                   :wAPEUNIMED,
                   :wNCMPROD,
                   :wCODTABINCID,
                   :wGRUPO,
                   :wORDEMMARCA,
                   :wCODCSTIPISAI,
                   :wCODCSTIPIENT,
                   :wCODCSTICMS,
                   :wCODCSTPISSAI,
                   :wCODCSTPISENT,
                   :wCODCSTCOFENT,
                   :wCODCSTCOFSAI,
                   :WALIQFCP,
                   :WPRODINCENTIVADO;
            END
          ELSE
            BEGIN
              -- Alt.: #138509 - Faz uma busca para ver se tem o participante por CNPJ + IE...
              SELECT FIRST 1 COALESCE(A.BDCODTERLAYOUT, 0)
              FROM TMP_TCADPRO_A_VALIDAR A
              WHERE A.BDCODSAIDA = :PRCODSAIDA
              AND A.BDCODENTRADA = :PRCODENTRADA
              AND A.BDDESCPROD = :PRDESCPROD
              AND A.BDCNPJTERLAYOUT = :PRCNPJTER
              AND ((:wVINCULOPART <> 1) OR (a.bdIETERLAYOUT IS NULL) OR (a.bdIETERLAYOUT = '') OR (a.bdIETERLAYOUT = :prIETER)) -- Alt.: #138509 - Parâmetro para verificar o participante por IE...
              INTO :wCODTERLAYOUT;

              IF (:wCODTERLAYOUT IS NULL) THEN
                wVINCULOPART = 0; -- Alt.: #138509 - Caso não tenha o participante, vai mandar buscar por CNPJ apenas e desconsiderar o parâmetro das ações de incosistências...

              SELECT FIRST 1 COALESCE(A.BDORIGEMPROD, 0),
                             COALESCE(A.BDCODTERLAYOUT, 0),
                             COALESCE(A.BDCNPJTERLAYOUT, ''),
                             COALESCE(a.bdIETERLAYOUT, ''),
                             COALESCE(A.BDCODEMP, 0),
                             COALESCE(A.BDCODSAIDA, ''),
                             COALESCE(A.BDAPEPROD, ''),
                             COALESCE(A.BDDESCPROD, ''),
                             COALESCE(A.BDAPELIDOUNICO, ''),
                             COALESCE(A.BDDESCRICAOUNICA, ''),
                             COALESCE(A.BDCODIGOEAN, ''),
                             COALESCE(A.BDCODTER, 0),
                             COALESCE(A.BDCODENTRADA, ''),
                             A.BDCODTIPO,
                             A.BDCODGEN,
                             A.BDCODSER,
                             A.BDCODCOMBANP,
                             A.BDCODUNIMED,
                             COALESCE(A.BDAPEUNIMED, ''),
                             A.BDNCMPROD,
                             A.BDCODTABINCID,
                             A.BDGRUPO,
                             A.BDORDEMMARCA,
                             A.BDCODCSTIPISAI,
                             A.BDCODCSTIPIENT,
                             A.BDCODCSTICMS,
                             A.BDCODCSTPISSAI,
                             A.BDCODCSTPISENT,
                             A.BDCODCSTCOFENT,
                             A.BDCODCSTCOFSAI,
                             A.BDALIQFCP,
                             A.BDPRODINCENTIVADO
              FROM TMP_TCADPRO_A_VALIDAR A
              WHERE A.BDCODSAIDA = :PRCODSAIDA
              AND A.BDCODENTRADA = :PRCODENTRADA
              AND A.BDDESCPROD = :PRDESCPROD
              AND A.BDCNPJTERLAYOUT = :PRCNPJTER
              AND ((:wVINCULOPART <> 1) OR (a.bdIETERLAYOUT IS NULL) OR (a.bdIETERLAYOUT = '') OR (a.bdIETERLAYOUT = :prIETER)) -- Alt.: #138509 - Parâmetro para verificar o participante por IE...
              ORDER BY a.bdCODTERLAYOUT
              INTO :wORIGEMPROD,
                   :wCODTERLAYOUT,
                   :wCNPJTERLAYOUT,
                   :wIETERLAYOUT,
                   :wCODEMP,
                   :wCODSAIDA,
                   :wAPEPROD,
                   :wDESCPROD,
                   :wAPELIDOUNICO,
                   :wDESCRICAOUNICA,
                   :wCODIGOEAN,
                   :wCODTER,
                   :wCODENTRADA,
                   :wCODTIPO,
                   :wCODGEN,
                   :wCODSER,
                   :wCODCOMBANP,
                   :wCODUNIMED,
                   :wAPEUNIMED,
                   :wNCMPROD,
                   :wCODTABINCID,
                   :wGRUPO,
                   :wORDEMMARCA,
                   :wCODCSTIPISAI,
                   :wCODCSTIPIENT,
                   :wCODCSTICMS,
                   :wCODCSTPISSAI,
                   :wCODCSTPISENT,
                   :wCODCSTCOFENT,
                   :wCODCSTCOFSAI,
                   :WALIQFCP,
                   :WPRODINCENTIVADO;
            END

          UPDATE TMP_TCADPRO P SET P.BDORIGEMPROD = :wORIGEMPROD,
                                   P.BDCODTERLAYOUT = :wCodTerLayout,
                                   P.BDCNPJTERLAYOUT = :wCnpjTerLayout,
                                   p.bdIETERLAYOUT = :wIETERLAYOUT,
                                   P.BDCODEMP = :wCodEmp,
                                   P.BDCODSAIDA = :wCodSaida,
                                   P.BDAPEPROD = :wApeProd,
                                   P.BDDESCPROD = :wDescProd,
                                   P.BDAPELIDOUNICO = :wApelidoUnico,
                                   P.BDDESCRICAOUNICA = :wDescricaoUnica,
                                   P.BDCODIGOEAN = :wCodigoEan,
                                   P.BDCODTER = :wCodTer,
                                   P.BDCODENTRADA = :wCodEntrada,
                                   P.BDCODTIPO = :wCodTipo,
                                   P.BDCODGEN = :wCodGen,
                                   P.BDCODSER = :wCodSer,
                                   P.BDCODCOMBANP = :wCodCombAnp,
                                   P.BDCODUNIMED = :wCodUnimed,
                                   P.BDAPEUNIMED = :wApeUnimed,
                                   P.BDNCMPROD= :wNcmProd,
                                   P.BDCODTABINCID = :wCodTabIncid,
                                   P.BDGRUPO = :wGrupo,
                                   P.BDORDEMMARCA = :wOrdemMarca,
                                   P.BDCODCSTIPISAI = :wCodCstIpiSai,
                                   P.BDCODCSTIPIENT = :wCodCstIpiEnt,
                                   P.BDCODCSTICMS = :wCodCstIcms,
                                   P.BDCODCSTPISSAI = :wCodCstPisSai,
                                   P.BDCODCSTPISENT = :wCodCstPisEnt,
                                   P.BDCODCSTCOFENT = :wCodCstCofEnt,
                                   P.BDCODCSTCOFSAI = :wCodCstCofSai,
                                   P.BDSEQ_PART     = :PRSEQ_PART,
                                   P.BDALIQFCP      = :WALIQFCP,
                                   p.BDPRODINCENTIVADO = :WPRODINCENTIVADO
          WHERE P.BDCODPROD = :PRCODPROD;

          IF (:wOrigemProd = 0) THEN
            BEGIN
              UPDATE TMP_TCADPRO_PART C SET C.BDEDITCHAVE = :PRCODPROD, C.BDCODPROD = :PRCODPROD, C.BDDESCPRODBUSCA = :WDESCPROD, C.BDCODEMP = :WCODEMP, C.BDSEQ_PART = :PRSEQ_PART
              WHERE C.BDSESSAO = :PRSESSAO
              AND C.BDCODENTRADA = :WCODENTRADA
              AND C.BDCODTER = :PRCODTER;
            END
        END
      ELSE
        BEGIN
          IF (:PROPERATION = 'INUP') THEN
            BEGIN
              SELECT COALESCE(A.bdcodsaida, '') BDCODsaida,
                     A.bdapeprod bdapeprod,
                     A.bddescprod bddescproD,
                     A.bdapelidounico bdAPELIDOUNICO,
                     A.bddescricaounica BDDESCRICAOUNICA,
                     A.bdcodigoean BDCODIGOEAN,
                     A.BDCODTIPO,
                     A.BDCODGEN,
                     A.BDCODSER,
                     A.BDCODCOMBANP,
                     A.BDCODUNIMED,
                     A.BDNCMPROD,
                     A.bdcodtabincid,
                     A.bdgrupo,
                     A.bdordemmarca,
                     A.BDCODCSTIPISAI,
                     A.BDCODCSTIPIENT,
                     A.BDCODCSTICMS,
                     A.BDCODCSTPISSAI,
                     A.BDCODCSTPISENT,
                     A.BDCODCSTCOFENT,
                     A.BDCODCSTCOFSAI,
                     COALESCE(A.BDORIGEMPROD, 0) BDORIGEMPROD,
                     A.BDALIQFCP,
                     A.BDPRODINCENTIVADO
              FROM TMP_TCADPRO_A_VALIDAR A
              WHERE A.BDCODPROD = :PRCODPROD
              INTO :wCodSaida,
                   :wApeProd,
                   :wDescProd,
                   :wApelidoUnico,
                   :wDescricaoUnica,
                   :wCodigoEan,
                   :wCodTipo,
                   :wCodGen,
                   :wCodSer,
                   :wCodCombAnp,
                   :wCodUnimed,
                   :wNcmProd,
                   :wCodTabIncid,
                   :wGrupo,
                   :wOrdemMarca,
                   :wCodCstIpiSai,
                   :wCodCstIpiEnt,
                   :wCodCstIcms,
                   :wCodCstPisSai,
                   :wCodCstPisEnt,
                   :wCodCstCofEnt,
                   :wCodCstCofSai,
                   :wOrigemProd,
                   :WALIQFCP,
                   :WPRODINCENTIVADO;

              UPDATE OR INSERT INTO TMP_TCADPRO(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDCODEMP, BDCODSAIDA, BDAPEPROD, BDDESCPROD,
                                                BDAPELIDOUNICO, BDDESCRICAOUNICA, BDCODIGOEAN, BDCODTIPO, BDCODGEN, BDCODSER,
                                                BDCODCOMBANP, BDCODUNIMED, BDNCMPROD, BDCODTABINCID, BDGRUPO, BDORDEMMARCA,
                                                BDCODCSTIPISAI, BDCODCSTIPIENT, BDCODCSTICMS, BDCODCSTPISSAI, BDCODCSTPISENT,
                                                BDCODCSTCOFENT, BDCODCSTCOFSAI, BDSEQ_PART, BDALIQFCP, BDPRODINCENTIVADO)
              VALUES(0, :PRCODPROD, :PRCODPROD, IIF(:PRCODEMP = 0, NULL, :PRCODEMP), :wCodSaida, :WAPEPROD, :WDESCPROD, :WAPELIDOUNICO,
                    :WDESCRICAOUNICA, :WCODIGOEAN, :wCodTipo, :WCODGEN, :WCODSER, :wCodCombAnp, :wCodUnimed,
                    :wncmprod, :wCodtabincid, :wgrupo, :wOrdemMarca, :wCodCstIpiSai, :wCodCstIpiEnt, :wCodCstIcms,
                    :wCodCstPisSai, :wCodCstPisEnt, :wCodCstCofEnt, :wCodCstCofSai, :PRSEQ_PART,:WALIQFCP, :WPRODINCENTIVADO)
              MATCHING(BDCODEMP, BDCODPROD, BDEDITCHAVE);

              IF ((:wOrigemProd = 0) AND (TRIM(:wDescProd) <> '')) THEN
                BEGIN
                  UPDATE OR INSERT INTO TMP_TCADPRO_PART(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDCODTER, BDCODENTRADA, BDDESCPRODBUSCA, BDCODEMP, BDSEQ_PART)
                  VALUES(:PRSESSAO, :PRCODPROD, :PRCODPROD, :PRCODTER, :PRCODENTRADA, :wDescProd, :wCodEmp, :PRSEQ_PART) MATCHING(BDCODPROD, BDCODENTRADA, BDDESCPRODBUSCA, BDCODTER);
                END
            END
        END
    END
END
^

COMMENT ON PARAMETER SP_INS_UPT_TMP_TCADPRO.PROPERATION IS '''INS'' = INSERIR NOVO - ''UPT'' = ATUALIZAR DADOS -  ''INUP'' = ''LANÇAMENTO MANUAL'''^

/* Restore proc. body: VSUC_SP_COPIA_PREPARACAO_ECF */
CREATE OR ALTER procedure VSUC_SP_COPIA_PREPARACAO_ECF (
    PRCODPLAPADRAOREF_DE integer,
    PRCODPLAPADRAO_DE integer,
    PRCODPLAPADRAOREF_PARA integer,
    PRCODPLAPADRAO_PARA integer,
    PRANO_DE integer,
    PRANO_PARA integer,
    PROPCAOTROCA integer)
returns (
    BDCODPLAPADRAOREF integer,
    BDCODTPLAREF integer,
    BDCODPLAPADRAO integer,
    BDCODTPLA integer,
    BDANO integer,
    BDCODGRUPOCTA integer)
as
declare variable WSQL DM_MAXVARCHAR;
declare variable WANO_INI integer;
declare variable WANO_FIM integer;
declare variable WCODTPLAREF integer;
BEGIN
  --alt:11500 - Criada procedure para copiar a preparação da ECF. Pedro
  IF (:prOpcaoTroca = 1) THEN
    BEGIN
      wSQL = 'delete from PLANOS_TPLA_ECF where BDCODPLAPADRAO = '||prCodplapadrao_PARA||' and BDCODPLAPADRAOREF = '||prCodplapadraoRef_PARA||' and BDANO = '||prAno_PARA;
      EXECUTE STATEMENT wSQL;
    END

  --alt:14677 - 13/06/2016 - Alteração para copiar a conta corretamente baseada na classificação do plano de contas referencial também, pois com as alterações de layout, os códigos não são mais os mesmos entre os planos diferentes. Pedro
  --alt:12432 - 20/01/2016 - Incluído parâmetro prAno_PARA para poder copiar a preparação para outro ano base. Pedro
  wSQL = 'select '||:prCodPlaPadraoRef_PARA||' as BDCODPLAPADRAOREF, ECF_PARA.BDCODTPLAREF, '||:prCodPlaPadrao_PARA||' as BDCODPLAPADRAO,';
  wSQL = wSQL||'   PARA.BDCODTPLA, '||:prAno_PARA||', ECF.BDCODGRUPOCTA,';
  wSQL = wSQL||' coalesce(extract(year from ECF_PARA.BDDTINIVALIDADE),0) as ANO_INI, coalesce(extract(year from ECF_PARA.BDDTFIMVALIDADE),0) as ANO_FIM';
  wSQL = wSQL||'  from PLANOS_TPLA_ECF ECF';
  wSQL = wSQL||' left join PLANOS_TPLA_ECF_PADRAO ECF_DE on (ECF.BDCODPLAPADRAOREF = ECF_DE.BDCODPLAPADRAOREF AND ECF.BDCODTPLAREF = ECF_DE.BDCODTPLAREF)';
  wSQL = wSQL||' left join PLANOS_TPLA_ECF_PADRAO ECF_PARA on (ECF_PARA.BDCODPLAPADRAOREF = '||:prCodPlaPadraoRef_PARA||' and ECF_DE.BDCTALON = ECF_PARA.BDCTALON)';
  wSQL = wSQL||' inner join PLANOS_TPLA DE on (DE.BDCODPLAPADRAO = ECF.BDCODPLAPADRAO and DE.BDCODTPLA = ECF.BDCODTPLA)';
  wSQL = wSQL||'  left join PLANOS_TPLA PARA on (PARA.BDCODPLAPADRAO = '||:prCodPlaPadrao_PARA||' and PARA.BDCTALON = DE.BDCTALON)';
  wSQL = wSQL||' where ECF.BDCODPLAPADRAO = '||:prCodPlaPadrao_DE;
  wSQL = wSQL||'   and ECF.BDCODPLAPADRAOREF = '||:prCodPlaPadraoRef_DE;
  wSQL = wSQL||'   and ECF.BDANO = '||:prAno_DE;
  --wSQL = wSQL||'   and ECF_PARA.BDCODPLAPADRAOREF = '||:prCodPlaPadraoRef_PARA; alt:17229 - 30/03/2017 - Retirado daqui e colocado direto no join do "ECF_PARA", pois se filtrar aqui não trás as contas que não possuem conta referencial preparada. Pedro
  --wSQL = wSQL||'   and ((extract(year from ECF_PARA.BDDTINIVALIDADE) <= ECF.BDANO) or (ECF_PARA.BDDTINIVALIDADE is null))';
  --wSQL = wSQL||'   and ((extract(year from ECF_PARA.BDDTFIMVALIDADE) >= ECF.BDANO) or (ECF_PARA.BDDTFIMVALIDADE is null))';
  --wSQL = wSQL||'   and DE.BDCTALON = PARA.BDCTALON'; alt:17229 - 30/03/2017 - Retirado daqui e colocado direto no join do "PARA", pois se filtrar aqui não trás as contas que não possuem conta referencial preparada. Pedro
  --alt:17229 - 30/03/2017 - Alterada regra, conta título pode copiar a preparação tendo apenas o grupo referencial, mas contas analíticas precisam ter grupo e conta referencial preparadas. Pedro
  --alt:11743 - 21/05/2015 - Alterada regra para copiar bastando o grupo estar preparado, ignorando a conta ref. Pedro
  wSQL = wSQL||'   and (ECF.BDCODGRUPOCTA is not null) ';
  ---#139443 - Copiar apenas os grupos se não tiver conta praparada.
  --and ((ECF.BDCODTPLAREF is not null) or (DE.BDTIPCTA = 0))';

  IF (:prOpcaoTroca = 3) THEN
    BEGIN
      wSQL = wSQL||'       and not exists(select * ';
      wSQL = wSQL||'                      from PLANOS_TPLA_ECF ';
      wSQL = wSQL||'                      where BDCODPLAPADRAO = PARA.BDCODPLAPADRAO';
      wSQL = wSQL||'                        and BDCODTPLA = PARA.BDCODTPLA';
      wSQL = wSQL||'                        and BDCODPLAPADRAOREF = '||:prCodPlaPadraoRef_PARA;
      wSQL = wSQL||'                        and BDANO = '||:prAno_PARA;
      wSQL = wSQL||'                        and ((BDCODGRUPOCTA is not null) or (BDCODTPLAREF is not null)))'; --alt:11743 - 21/05/2015 - Colocado "or" aqui, porque estava substituindo a preparação de qualquer conta que não tivesse o grupo ou conta ref preparada. Pedro
    END

  FOR EXECUTE STATEMENT wSQL INTO :BDCODPLAPADRAOREF, :BDCODTPLAREF, :BDCODPLAPADRAO, :BDCODTPLA, :BDANO, :BDCODGRUPOCTA, :WANO_INI, :WANO_FIM  DO
  BEGIN
    --#alt:18406 - Adicionada verificação para quando não é encontrado nenhuma classificação semelhante entre os planos de cópia. Ana - 24/04/2017
    IF (BDCODTPLA IS NOT NULL) THEN
       begin
          ---#139443 - Copiar apenas os grupos se não tiver conta praparada.
          if (((BDANO >= WANO_INI) or (WANO_INI = 0) ) and ((bdano <= WANO_FIM) or (WANO_FIM = 0) )) then
             WCODTPLAREF = :BDCODTPLAREF;
          else
             WCODTPLAREF = null;
          UPDATE OR INSERT INTO PLANOS_TPLA_ECF (BDCODPLAPADRAOREF, BDCODTPLAREF, BDCODPLAPADRAO,
                                                 BDCODTPLA, BDANO, BDCODGRUPOCTA) VALUES
                                                (:BDCODPLAPADRAOREF, :WCODTPLAREF, :BDCODPLAPADRAO,
                                                 :BDCODTPLA, :BDANO, :BDCODGRUPOCTA)
                                                MATCHING (BDCODPLAPADRAOREF, BDCODPLAPADRAO, BDCODTPLA, BDANO);
       end
    --SUSPEND;
  END
END^

/* Restore proc. body: COMPARATEXTO */
ALTER PROCEDURE COMPARATEXTO(STR1 VARCHAR(1024),
STR2 VARCHAR(1024))
 RETURNS(RESULT VARCHAR(1024))
 AS
DECLARE VARIABLE WCOUNT INTEGER;
BEGIN
  wCount = 1;
  result = '';
  WHILE (wcount <= strlen(str1)) DO
    BEGIN
      IF (SUBSTRING(str1 FROM wcount FOR 1) = SUBSTRING(str2 FROM wcount FOR 1)) THEN
         result = result||SUBSTRING(str1 FROM wcount FOR 1);
      ELSE
         BREAK;
      wcount = wcount + 1;
    END
  SUSPEND;
END
^

/* Restore proc. body: CONTAR_CHAR */
CREATE OR ALTER PROCEDURE CONTAR_CHAR(PRSTR VARCHAR(200),
PRSTR_BUSCA VARCHAR(1))
 RETURNS(CONTAR_CHAR INTEGER)
 AS
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WLENGTH INTEGER;
BEGIN
  CONTAR_CHAR = 0;
  IF (prstr IS NULL OR prstr_busca IS NULL) THEN
    EXIT;

  wlength = CHARACTER_LENGTH(:prstr);
  wcount  = 1;
  WHILE (wcount <= wlength) DO
    BEGIN
      IF (prstr_busca = SUBSTRING(prstr FROM wcount FOR CHARACTER_LENGTH(prstr_busca))) THEN
        CONTAR_CHAR = CONTAR_CHAR + 1;

      wcount = wcount + 1;
    END

  SUSPEND;
END
^

/* Restore proc. body: DIA_SEGUINTE */
ALTER PROCEDURE DIA_SEGUINTE(PRDATA DATE)
 RETURNS(PRDIASEGUINTE DATE)
 AS
DECLARE VARIABLE WULTDIA SMALLINT;
DECLARE VARIABLE WDIA SMALLINT;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
BEGIN

  wdia = CAST(SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 9 FOR 2) AS SMALLINT);
  wmes = CAST(SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano = CAST(SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);

--  exception ex_date wdia||'-'||wmes||'-'||wano;

  SELECT UltDia FROM ultimo_dia_mes(:wmes,:wano) INTO :wultdia;

  IF (wultdia = wdia) THEN
     BEGIN
       wdia = 1;
       SELECT mes, ano FROM ref_seguinte(:wmes,:wano) INTO :wmes, :wAno;
     END
  ELSE
     BEGIN
       wdia = wdia + 1;
     END

  prdiaseguinte = :wmes||'/'||:wdia||'/'||:wano;

  SUSPEND;

END
^

/* Restore proc. body: DIFERENCA_MESES */
ALTER PROCEDURE DIFERENCA_MESES(PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDMESES INTEGER)
 AS
DECLARE VARIABLE WMESES INTEGER;
DECLARE VARIABLE WDATAINI VARCHAR(10);
DECLARE VARIABLE WDATAFIM VARCHAR(10);
DECLARE VARIABLE WMESINI SMALLINT;
DECLARE VARIABLE WANOINI INTEGER;
DECLARE VARIABLE WSQL VARCHAR(300);
DECLARE VARIABLE WAUX VARCHAR(10);
BEGIN

  /* criada giovanni */

  wdataini =   SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4) ||  SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2);
  wdatafim =   SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4) ||  SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2);

  wmesini = CAST(SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wanoini = CAST(SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);

  wmeses = 0;

  WHILE (wdataini <= wdatafim) DO
    BEGIN

      SELECT mes, ano FROM ref_seguinte(:wmesini,:wanoini) INTO :wmesini, :wanoini;

      wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(wmesini)||''''||',2,'||''''||'0'||''''||')';
      EXECUTE STATEMENT wsql INTO waux;
      wdataini = wanoini || waux ;

      wmeses = wmeses + 1;
    END

  bdmeses = wmeses;

  /* Procedure Text */
  SUSPEND;
END
^

/* Restore proc. body: EMPAUTSERV */
ALTER PROCEDURE EMPAUTSERV(PREMPRESA INTEGER,
PRAUTONOMO INTEGER,
PRSERVICO INTEGER)
 RETURNS(BDEMPAUTSERV VARCHAR(20))
 AS
DECLARE VARIABLE WRESULT VARCHAR(20);
DECLARE VARIABLE WEMP VARCHAR(6);
DECLARE VARIABLE WAUT VARCHAR(6);
DECLARE VARIABLE WSERV VARCHAR(6);
BEGIN
  SELECT str FROM strzero(:prempresa,6) INTO :wemp;
  SELECT str FROM strzero(:prautonomo,6) INTO :waut;
  SELECT str FROM strzero(:prservico,6) INTO :wserv;
  wresult = wemp||waut||wserv;

  bdempautserv = wresult;

  SUSPEND;
END
^

/* Restore proc. body: MAXSCI */
ALTER PROCEDURE MAXSCI(PRCAMPO VARCHAR(1024),
PRORDEM VARCHAR(1024),
PRCONDICAO VARCHAR(1024),
PRTABELA VARCHAR(1024))
 RETURNS(BDRESULT INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WORDEM_TRAN VARCHAR(150);
BEGIN
  /* procedimento criado para substituir a clausula "MAX" nos automatismos
  obs: nao esquecer de criar o indice descendente na tabela que for usar o MAXSCI*/

  SELECT bdresult FROM strtran(:prordem, ',', ' desc,') INTO wordem_tran;

  wsql = 'select first 1 coalesce('||prcampo||', 0) from '||prtabela;
  IF (prcondicao <> '') THEN
     wsql = wsql||' where '||prcondicao;
  IF (prordem <> '') THEN
     wsql = wsql||' order by '||wordem_tran||' desc';
     --wsql = wsql||' order by '||prordem||' desc';


  EXECUTE STATEMENT wsql INTO :bdresult;
  IF (bdresult IS NULL) THEN
     bdresult = 0;
--  bdresult = bdresult +1;
  SUSPEND;
END
^

/* Restore proc. body: PREENCHE_CLASSIFICACAOPRODUTO */
ALTER PROCEDURE PREENCHE_CLASSIFICACAOPRODUTO(PRSTRING VARCHAR(1000),
PRQTD INTEGER,
PRADICIONA VARCHAR(1000))
 RETURNS(BDRETORNO VARCHAR(1000))
 AS
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WAUX VARCHAR(100);
DECLARE VARIABLE WSEGSTR VARCHAR(100);
BEGIN
  bdRetorno = '';
  wAux = prString;
  wPos = 1;
  WHILE (wPos > 0) DO
    BEGIN
      SELECT pos.pos FROM pos('.', :wAux) INTO :wPos;
      IF (wPos > 0) THEN
         BEGIN
           wSegStr = SUBSTRING(wAux FROM 1 FOR wPos - 1);
           wAux = SUBSTRING(wAux FROM wPos + 1 FOR CHARACTER_LENGTH(prstring));
           IF (CHARACTER_LENGTH(wSegStr) < prQtd) THEN
              SELECT preenche_esquerda.bdretorno FROM preenche_esquerda(:wSegStr,:prQtd,:prAdiciona) INTO :wSegStr;
           wSegStr = wSegStr||'.';
         END
      ELSE
         BEGIN
           wSegStr = wAux;
           IF (CHARACTER_LENGTH(wSegStr) < prQtd) THEN
              SELECT preenche_esquerda.bdretorno FROM preenche_esquerda(:wSegStr,:prQtd,:prAdiciona) INTO :wSegStr;
         END
      bdRetorno = bdRetorno||wSegStr;
    END

  /*if (bdRetorno = '') then
     begin
       if (prString < prqtd) then
          select preenche_esquerda.bdretorno from preenche_esquerda(:prString,:prQtd,:prAdiciona) into :wSegStr;
       else
          bdretorno = prstring;
     end*/
  SUSPEND;
END
^

/* Restore proc. body: REF_SEGUINTE */
ALTER PROCEDURE REF_SEGUINTE(PRMES SMALLINT,
PRANO INTEGER)
 RETURNS(MES SMALLINT,
ANO INTEGER)
 AS
BEGIN

  IF (prmes = 12) THEN
     BEGIN
       mes = 1;
       ano = prano + 1;
     END
  ELSE
     BEGIN
       mes = prmes + 1;
       ano = prAno;
     END

  SUSPEND;

END
^

/* Restore proc. body: RETIRA_ACENTO */
ALTER PROCEDURE RETIRA_ACENTO(PRSTRING VARCHAR(1000))
 RETURNS(BDRETORNO VARCHAR(1000))
 AS
DECLARE VARIABLE WRETORNO VARCHAR(1000);
DECLARE VARIABLE WATU VARCHAR(1);
DECLARE VARIABLE WCONTA INTEGER;
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WTOT INTEGER;
BEGIN
  wtot = CHARACTER_LENGTH(prstring);
  wconta = 1;
  wretorno = '';


  WHILE (wconta <= wtot) DO
    BEGIN
      watu = SUBSTRING(prstring FROM wconta FOR 1);

      wsql = 'select bdsemacento from CHAR_ACENTUADO where bdacento = '||''''||watu||'''';
      EXECUTE STATEMENT wsql INTO watu;

      IF ((watu IS NULL) OR (watu = '')) THEN
         watu = SUBSTRING(prstring FROM wconta FOR 1);

      wretorno = wretorno||watu;
      wconta = wconta + 1;
    END

  bdretorno = wretorno;

  /* Procedure Text */
  SUSPEND;
END
^

/* Restore proc. body: RETIRA_CHAR_ESPECIAL */
ALTER PROCEDURE RETIRA_CHAR_ESPECIAL(PRSTRING VARCHAR(1000))
 RETURNS(BDRETORNO VARCHAR(1000))
 AS
DECLARE VARIABLE wretorno VARCHAR(1000);
DECLARE VARIABLE watu VARCHAR(1);
DECLARE VARIABLE wconta INTEGER;
DECLARE VARIABLE wtot INTEGER;
BEGIN
  wtot = CHARACTER_LENGTH(prstring);
  wconta = 1;
  wretorno = '';

  WHILE (wconta <= wtot) DO
    BEGIN
      watu = SUBSTRING(prstring FROM wconta FOR 1);

      IF ((watu = '`') OR (watu = '.') OR (watu = ',') OR
          (watu = ';') OR (watu = ':') OR (watu = '?') OR
          (watu = '%') OR (watu = '!') OR (watu = '/') OR
          (watu = '\') OR (watu = '&') OR (watu = '-') OR
          (watu = '_') OR (watu = '+') OR (watu = '*') OR
          (watu = '#') OR (watu = '@') OR (watu = '<') OR
          (watu = '>') OR (watu = '[') OR (watu = ']') OR
          (watu = '(') OR (watu = ')') OR (watu = '"') OR
          (watu = '''')) THEN
         BEGIN
           watu = '';
         END

      wretorno = wretorno||watu;
      wconta = wconta + 1;
    END

  bdretorno = wretorno;

  /* Procedure Text */
  SUSPEND;
END
^

/* Restore proc. body: RPOS */
ALTER PROCEDURE RPOS(SUBSTR VARCHAR(100),
STR VARCHAR(100))
 RETURNS(BDRPOS INTEGER)
 AS
DECLARE VARIABLE CONTA INTEGER;
BEGIN
  IF (SubStr IS NULL OR Str IS NULL)
  THEN BEGIN bdRPOS = NULL; EXIT; END

  conta = 1;
  bdRPOS = 0;

  WHILE (conta <= strlen(str)) DO
    BEGIN

      IF (SUBSTRING(str FROM conta FOR strlen(substr)) = substr) THEN
         BEGIN
           bdRPOS = conta;
         END

      conta = conta + 1;

    END

  SUSPEND;

END
^

/* Restore proc. body: SONUMEROS */
ALTER PROCEDURE SONUMEROS(PRTEXTO VARCHAR(100))
 RETURNS(BDRESULT SMALLINT)
 AS
DECLARE VARIABLE WCOUNT INTEGER;
BEGIN
  wcount = 1;
  bdresult = 1;
  WHILE (wcount <= char_length(prtexto)) DO
    BEGIN
      IF (NOT SUBSTRING(prtexto FROM wcount FOR 1) IN ('1','2','3','4','5','6','7','8','9','0')) THEN
         BEGIN
           bdresult = 0;
           BREAK;
         END
      wcount = wcount + 1;
    END
  SUSPEND;
END
^

/* Restore proc. body: SONUMEROS */
CREATE OR ALTER PROCEDURE SOLETRAS (
    prTEXTO VARCHAR(100))
RETURNS (
    bdRESULT SMALLINT)
AS
DECLARE VARIABLE wCOUNT INTEGER;
BEGIN
  wCOUNT = 1;
  bdRESULT = 1;
  WHILE (wCOUNT <= STRLEN(prTEXTO)) DO
    BEGIN
      IF (NOT UPPER(SUBSTRING(prTEXTO FROM wCOUNT FOR 1)) IN ('A','B','C','D','E','F','G','H','I','J','L','K','M','N','O','P','Q','R','S','T','U','V','W','Y','X','Z')) THEN
         BEGIN
           bdRESULT = 0;
           BREAK;
         END
      wCOUNT = wCOUNT + 1;
    END
  SUSPEND;
END
^

/* Restore proc. body: SP_AFASTADOS */
ALTER PROCEDURE SP_AFASTADOS(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODSIT INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE WWHERE VARCHAR(3000);
BEGIN
  wsql = 'select BDCODEMP, BDCODCOL, MAX(BDCODSIT) BDCODSIT from VRH_EMP_TSITCOL ';
  wwhere = '';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     wwhere = wwhere||:PRCODEMP;

  IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODCOL;
     END

  IF (PRDATAINI IS NOT NULL AND PRDATAFIM IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDDATAINISIT <= '''||:PRDATAFIM||''' and (BDDATAFIMSIT is null or (BDDATAFIMSIT >= '''||:PRDATAINI||''')) ';
     END

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wsql = wsql||' group by BDCODEMP, BDCODCOL';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODSIT
  DO
  SUSPEND;
END
^

/* Restore proc. body: SP_AFASTADOS_MES_INTEIRO */
create or alter procedure SP_AFASTADOS_MES_INTEIRO (
    PRDATAINI date,
    PRDATAFIM date,
    PRTBTEMP smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer)
as
declare variable WSQL varchar(2000);
declare variable WDATAINI date;
declare variable WDATAFIM date;
declare variable WSQL2 varchar(2000);
declare variable WDMIN date;
declare variable WDMAX date;
BEGIN
  prtbtemp = coalesce(prtbtemp, 0);

  wsql = 'select distinct COLCON.BDCODEMP, COLCON.BDCODCOL from VRH_EMP_TCOLCON COLCON ';

  if (prtbtemp > 0) then
     wsql = wsql||'join TMP_EMPRESAS_SELECT FILTRO on (FILTRO.BDCODEMP = COLCON.BDCODEMP) ';

  wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';

  -- Admissoes
  wsql = wsql||'where COLCON.BDDATAADMCOL <= '''||prdatafim||'''';

  -- Rescisoes e Transferencias
  wsql = wsql||' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataini||''')) ';

  -- Situacoes
  wsql = wsql||' and exists (select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TSITCOL Y where Y.BDCODEMP = COLCON.BDCODEMP and Y.BDCODCOL = COLCON.BDCODCOL and Y.BDDATAINISIT <= '''||prdataini||''' and (Y.BDDATAFIMSIT >= '''||prdatafim||''' or Y.BDDATAFIMSIT is null)) ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL
  do
    begin
      wsql2 = 'select ST.BDDATAINISIT, ST.BDDATAFIMSIT '||
              'from VRH_EMP_TSITCOL ST '||
              'join VRH_BASE_TPREPSIT PST on (PST.BDCODSIT = ST.BDCODSIT) '||
              'where ST.BDCODEMP = '||bdcodemp||' and ST.BDCODCOL = '||bdcodcol||' and PST.BDCODVER is not null and ST.BDDATAINISIT <= '''||prdatafim||''' and ((ST.BDDATAFIMSIT is null) or (ST.BDDATAFIMSIT >= '''||prdataini||''')) ';
      wdmin = null;
      wdmax = prdataini;

      for execute statement wsql2 into :wdataini, :wdatafim do
        begin
          if ((wdmin is null) or (wdataini < wdmin)) then
             wdmin = wdataini;

          if (wdatafim is null) then
             wdmax = prdatafim;
          else
          if (wdatafim > wdmax) then
             wdmax = wdatafim;
        end

      if (wdmin is not null and wdmax is not null) then
         begin
           if (wdmin <= prdataini and wdmax >= prdatafim) then
              SUSPEND;
         end
    end
END^

/* Restore proc. body: SP_ALTERA_TIPO_COLCON */
ALTER PROCEDURE SP_ALTERA_TIPO_COLCON(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRCONTRCOL INTEGER,
PRCODCLA INTEGER)
 AS
BEGIN
  UPDATE vrhf_emp_tcolcon_banco SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrhf_emp_tcolcon_calc SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrhf_emp_tcolcon_fgtsgps SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrhf_emp_tcol_ano SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrhf_emp_tcol_calc SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrhf_emp_tcol_hist SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrhf_emp_tcon_vinc SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrh_emp_tcolcon SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrh_emp_tcolcon_calcdia SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrh_emp_tcolcon_dia SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrh_emp_tcolcon_doc SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrh_emp_tcolcon_img SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrh_emp_tcolcon_partida SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrh_emp_tcolcon_ref SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrh_emp_tcolcon_vinc SET BDCONTRCOL = :prcontrcol, BDCODCLA = :prcodcla WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrh_emp_tcol_adm SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrh_emp_tcol_doc SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrh_emp_tcol_fis SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrh_emp_tcol_hist SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrh_emp_tcol_parent SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrh_emp_tcol_vinc SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrh_emp_tcol_vincdia SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
  UPDATE vrh_emp_tcon_doc SET BDCONTRCOL = :prcontrcol WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol;
--  suspend;
END
^

/* Restore proc. body: SP_ATI_SEM_AFAST_MES_INT */
create or alter procedure SP_ATI_SEM_AFAST_MES_INT (
    PRDATAINI date,
    PRDATAFIM date,
    PRTBTEMP smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer)
as
declare variable WSQL varchar(1000);
declare variable WSQL2 varchar(2000);
declare variable WCODSIT integer;
BEGIN
  prtbtemp = coalesce(prtbtemp, 0);

  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL from VRH_EMP_TCOLCON COLCON ';

  if (prtbtemp > 0) then
     wsql = wsql||'join TMP_EMPRESAS_SELECT FILTRO on (FILTRO.BDCODEMP = COLCON.BDCODEMP) ';

  wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';

  -- Admissões
  wsql = wsql||'where COLCON.BDDATAADMCOL <= '''||prdatafim||'''';

  -- Rescisões e Transferências
  wsql = wsql||' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataini||''')) ';

  -- Situações
  wsql = wsql||' and not exists (select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TSITCOL Y '||
         'join VRH_BASE_TPREPSIT Z on (Z.BDCODSIT = Y.BDCODSIT) '||
         'where Y.BDCODEMP = COLCON.BDCODEMP and Y.BDCODCOL = COLCON.BDCODCOL and Y.BDDATAINISIT <= '''||prdataini||''' and '||
     '(Y.BDDATAFIMSIT is null or Y.BDDATAFIMSIT >= '''||prdatafim||''') and Z.BDCODVER is not null)  ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL
  DO
    begin
      wsql2 = 'select first 1 SIT.BDCODSIT from VRH_EMP_TSITCOL SIT '||
              'left outer join VRH_BASE_TPREPSIT PSIT on (PSIT.BDCODSIT = SIT.BDCODSIT) '||
              'where SIT.BDCODEMP = '||bdcodemp||' and BDCODCOL = '||bdcodcol||' and SIT.BDDATAINISIT <= '''||prdataini||''' and '||
                    '((SIT.BDDATAFIMSIT is null) or (SIT.BDDATAFIMSIT >= '''||prdatafim||''')) and PSIT.BDCODVER is not null ';
      wcodsit = null;

      execute statement wsql2 into :wcodsit;

      if (wcodsit is null) then
        SUSPEND;
    end
END^


/* Restore proc. body: SP_ATI_SEM_DEM_COM_TRANSF */
create or alter procedure SP_ATI_SEM_DEM_COM_TRANSF (
    PRDATAINI date,
    PRDATAFIM date,
    PREMP varchar(32700) = null,
    PRTBTEMP smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer)
as
declare variable WSQL varchar(3000);
declare variable WTIPORESC integer;
declare variable WDATARESC date;
declare variable WSQL2 varchar(2000);
declare variable WCODCOL integer;
begin
  prtbtemp = coalesce(prtbtemp, 0);

  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COALESCE(PRES.BDTIPOMOV,0), RESC.BDDATARESCISAO from VRH_EMP_TCOLCON COLCON ';

  if (prtbtemp > 0) then
     wsql = wsql||'join TMP_EMPRESAS_SELECT FILTRO on (FILTRO.BDCODEMP = COLCON.BDCODEMP) ';

  wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql||'left outer join VRH_BASE_TPREPRESC PRES on (PRES.BDCODPRES = RESC.BDCODPRES) ';

  -- Admissões
  wsql = wsql||'where COLCON.BDDATAADMCOL <= '''||prdatafim||'''';

  -- Rescisões e Transferências
  wsql = wsql||' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataini||''')) ';

  if (coalesce(premp, '') <> '') then
     begin
       premp = Upper(premp);
       wsql = wsql||' and '||replace(premp, 'BDCODEMP', 'COLCON.BDCODEMP');
     end

  /*#Alt:18469. Precisa retornar os que não foram demitidos ou os que foram transferidos no período informado
     - Foi trocado a view VW_DEMITIDOS para utilizar direto a tabela porque na view já existe um controle com os colaboradores transferidos. Mas para o correto
       funcionamento desse SQL precisamos tratar os transferidos de outra forma.
     - Foi adicionado o comando "between" para o SQL utilizado na view VW_TRANSFERIDOS para retornar apenas os transferidos dentro do período informado.

  wsql = wsql||' and (not exists (select X.BDCODEMP, X.BDCODCOL from VW_DEMITIDOS X where X.BDCODEMP = COLCON.BDCODEMP and X.BDCODCOL = COLCON.BDCODCOL and X.BDDATARESCISAO <= '''||prdatafim||''') or '||
         '(exists (select W.BDCODEMP, W.BDCODCOL from VW_TRANSFERIDOS W where W.BDCODEMP = COLCON.BDCODEMP and W.BDCODCOL = COLCON.BDCODCOL and W.BDDATARESCISAO < '''||prdataini||''')))'; */

  for execute statement wsql
  into
    :BDCODEMP,
    :BDCODCOL,
    :wtiporesc,
    :wdataresc
  do
    begin
      if (wdataresc is null) then
         suspend;
      else
      if (wtiporesc = 0 and wdataresc > prdatafim) then
         suspend;
      else
      if (wtiporesc = 1 and wdataresc >= prdataini) then
         begin
           wsql2 = 'select first 1 BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPORIG = '||bdcodemp||' and BDCODCOLORIG = '||bdcodcol;
           wcodcol = null;
           execute statement wsql2 into :wcodcol;
           if (wcodcol is not null) then
              SUSPEND;
         end
    end
end^

/* Restore proc. body: SP_ATIVOS_SEM_DEMITIDOS_MES */
create or alter procedure SP_ATIVOS_SEM_DEMITIDOS_MES (
    PRDATAINI date,
    PRDATAFIM date,
    PRCODEMP varchar(32700) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer)
as
declare variable WSQL varchar(32700);
BEGIN
  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL from VRH_EMP_TCOLCON COLCON ';
  wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';

  -- Admissões
  wsql = wsql||'where COLCON.BDDATAADMCOL <= '''||prdatafim||'''';

  -- Rescisões e Transferências
  wsql = wsql||' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO > '''||prdatafim||'''))';

  if (coalesce(prcodemp, '') <> '') then
     begin
       prcodemp = upper(prcodemp);
       wsql = wsql||' and '||replace(prcodemp, 'BDCODEMP', 'COLCON.BDCODEMP');
     end

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL
  DO
  SUSPEND;
END^


/* Restore proc. body: SP_ATU_CAMPOS_GERADOR */
ALTER PROCEDURE SP_ATU_CAMPOS_GERADOR AS
DECLARE VARIABLE WCODTABELA INTEGER;
DECLARE VARIABLE WTABELA VARCHAR(256);
DECLARE VARIABLE WCAMPO VARCHAR(256);
DECLARE VARIABLE WDESCCAMPO VARCHAR(256);
BEGIN
  /* Procedure Text */
  EXECUTE PROCEDURE sp_seta_competencia(201110,NULL,NULL);

--  suspend;
  FOR SELECT t.bdcodtabger,t.bdtabela FROM ttabelagerador t INTO :wcodtabela,:wtabela DO
    BEGIN
      FOR SELECT rdb$field_name, CAST(rdb$description AS VARCHAR(256)) FROM RDB$RELATION_FIELDS
        WHERE UPPER(rdb$relation_name) = UPPER(:wtabela) INTO :wcampo, :wdesccampo DO
        BEGIN
           UPDATE OR INSERT INTO TCAMPOSGERADOR (BDCODTABGER, BDCODCAMPOGER, BDCAMPO, BDDESCRICAO, BDDESCRICAOAUX, bdfiltro)
                                         VALUES (:wcodtabela, NULL, :wcampo, :wdesccampo, :wdesccampo, 'TRUE')
                                       MATCHING (BDCODTABGER, BDCODCAMPOGER);

        END
    END

END
^

/* Restore proc. body: SP_ATU_CATEGORIA */
ALTER PROCEDURE SP_ATU_CATEGORIA AS
DECLARE VARIABLE wcontrol INTEGER;
DECLARE VARIABLE waux VARCHAR(3000);
DECLARE VARIABLE wemp INTEGER;
DECLARE VARIABLE wcol INTEGER;
DECLARE VARIABLE wanomes INTEGER;
DECLARE VARIABLE wcat INTEGER;
DECLARE VARIABLE wauxins VARCHAR(3000);
BEGIN
  /* Procedure Text */
--  suspend;
/*  waux = 'select x.bdcodemp,x.bdcodcol, x.bdrefcol, x.bdcategoriacol from VRHF_EMP_TCOLCON_FGTSGPS x';

  wauxins = 'delete from TCATEGORIATEMP';
  execute statement wauxins;

  for execute statement waux into
    :wemp,:wcol,:wanomes,:wcat
  do
    begin
      if (wcat is null) then
        wauxins = 'insert into TCATEGORIATEMP values('||wemp||','||wcol||','||wanomes||',null)';
      else
        wauxins = 'insert into TCATEGORIATEMP values('||wemp||','||wcol||','||wanomes||','||wcat||')';

      execute statement wauxins;
    end

  waux = 'update VRHF_EMP_TCOLCON_FGTSGPS x set x.bdcategoriacol = null';

  execute statement waux;*/

  waux = 'select x.bdcodemp,x.bdcodcol,x.bdanomes,x.bdcategoria,y.bdcontrcol from tcategoriatemp x'||
         ' left outer join vrh_emp_tcolcon y on (x.bdcodemp = y.bdcodemp and x.bdcodcol = y.bdcodcol)';

  FOR EXECUTE STATEMENT waux INTO
    :wemp,:wcol,:wanomes,:wcat, :wcontrol
  DO
    BEGIN
/*      if (wcontrol = 0) then
         begin
           if (wcat = 0) then
              wcat = 1; -- '1 - Empregado';
           else if (wcat = 1) then
              wcat = 2; -- '2 - Trabalhador avulso';
           else if (wcat = 2) then
              wcat = 3; -- '3 - Empregado afastado por prestar serviço militar';
           else if (wcat = 3) then
              wcat = 4; -- '4 - Empregado sob contrato de trabalho por prazo determinado';
           else if (wcat = 4) then
              wcat = 5; -- '5 - Diretor não empregado com FGTS (empresário)';
           else if (wcat = 5) then
              wcat = 6; -- '6 - Empregado doméstico';
           else if (wcat = 6) then
              wcat = 7; -- '7 - Trabalhador de 14 a 24 com contrato aprendizagem';
           else
              wcat = 1;
         end
      else
         begin
           if (wcat = 0) then
              wcat = 5; -- '05 - Diretor não empregado com FGTS (empresário)';
           else if (wcat = 1) then
              wcat = 11; -- '11 - Diretor não empregado sem FGTS';
           else if (wcat = 2) then
              wcat = 12; -- '12 - Agente público';
           else if (wcat = 3) then
              wcat = 13; -- '13 - Trab. autônomo equip. contrib. remuneração';
           else if (wcat = 4) then
              wcat = 14; -- '14 - Trab. autônomo equip. contrib. salário-base';
           else if (wcat = 5) then
              wcat = 15; -- '15 - Transp. autônomo contrib remuneração';
           else if (wcat = 6) then
              wcat = 16; -- '16 - Transp. autônomo contrib. salário-base';
           else if (wcat = 7) then
              wcat = 17; -- '17 - Contribuinte individual cooperado';
           else if (wcat = 8) then
              wcat = 18; -- '18 - Contribuinte individual transportador cooperado';
           else if (wcat = 9) then
              wcat = 19; -- '19 - Agente político';
           else if (wcat = 10) then
              wcat = 20; -- '20 - Servidor público temporário';
           else if (wcat = 11) then
              wcat = 21; -- '21 - Servidor público titular';
           else if (wcat = 12) then
              wcat = 22; -- '22 - Contrib. individual contratado por contrib indiv.';
           else if (wcat = 13) then
              wcat = 23; -- '23 - Contrib. individual transportador autônomo';
           else if (wcat = 14) then
              wcat = 24; -- '24 - Contrib. indiv. cooperado prestador de serviços';
           else if (wcat = 15) then
              wcat = 25; -- '25 - Contrib. indiv. transp. cooperado - beneficente';
           else
              wcat = 13;
         end*/

      wauxins = 'update VRHF_EMP_TCOLCON_FGTSGPS x set x.bdcategoriacol = '||wcat||
              ' where x.bdcodemp = '||wemp||' and x.bdcodcol = '||wcol||' and x.bdrefcol = '||wanomes;

      EXECUTE STATEMENT wauxins;
    END
END
^

/* Restore proc. body: SP_ATU_CODREC */
ALTER PROCEDURE SP_ATU_CODREC(PRCODREC DM_CODRECOF)
 AS
DECLARE VARIABLE WCODREC DM_CODRECOF;
BEGIN
  wcodrec = NULL;
  SELECT BDCODRECOF FROM TCODREC WHERE TRIM(BDCODRECOF) = :prcodrec INTO :wcodrec;
  IF (wcodrec IS NULL) THEN
     BEGIN
       INSERT INTO TCODREC (BDDESCREC,BDTIPOIMPOSTO,BDCODRECOF,BDCONFCONTABILIZA) VALUES ('Participação nos lucros ou resultados (PLR)', 2, :prcodrec, 'FALSE');
     END
END
^

/* Restore proc. body: SP_ATU_FGTS_CONT_13 */
CREATE OR ALTER PROCEDURE SP_ATU_FGTS_CONT_13 (
    PRVALOR NUMERIC(15,6),
    PRCODEMP INTEGER,
    PRCODCOL INTEGER,
    PRREFERENCIA INTEGER,
    PRVALORANT NUMERIC(15,6))
AS
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WSQLINVERT VARCHAR(1000);
BEGIN
  /* Procedure Text */
  wsqlinvert = '';
  IF (((prvalor < 0) AND (prvalorant > 0)) OR ((prvalor > 0) AND (prvalorant < 0)))  THEN
     wsqlinvert = ', lan.bddebito = lan.bdcredito, lan.bdcredito = lan.bddebito ';

  IF (prvalor < 0) THEN
     prvalor = prvalor * -1;

  IF (prvalor = 0) THEN
     wsql = 'delete from tol_vrhf_emp_tfgts_13 lan ';
  ELSE
     wsql = 'update vsuc_empresas_tlan lan set lan.bdvalor = '||prvalor||wsqlinvert;

  FOR EXECUTE STATEMENT 'select tol.bdchave from tol_vrhf_emp_tfgts_13 tol where tol.bdcodemp = '||prcodemp||
  ' and tol.bdcodcol = '||prcodcol||
  ' and tol.BDREF13 = '||prreferencia
  INTO :wchave DO
  BEGIN
    EXECUTE STATEMENT wsql||' where lan.bdcodemp='||prcodemp||' and bdchave='||wchave;
  END
--  suspend;
END^

/* Restore proc. body: SP_ATU_FGTS_CONT_A13 */
create or alter procedure SP_ATU_FGTS_CONT_A13 (
    PRVALOR numeric(15,6),
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFERENCIA integer,
    PRVALORANT numeric(15,6))
as
declare variable WSQL varchar(1000);
declare variable WSQLINVERT varchar(1000);
declare variable WCHAVE integer;
BEGIN
  wsqlinvert = '';
  IF (((prvalor < 0) AND (prvalorant > 0)) OR ((prvalor > 0) AND (prvalorant < 0)))  THEN
     wsqlinvert = ', lan.bddebito = lan.bdcredito, lan.bdcredito = lan.bddebito ';

  IF (prvalor < 0) THEN
     prvalor = prvalor * -1;

  IF (prvalor = 0) THEN
     wsql = 'delete from tol_vrhf_emp_tfgts_a13 lan ';
  ELSE
     wsql = 'update vsuc_empresas_tlan lan set lan.bdvalor = '||prvalor||wsqlinvert;


  FOR EXECUTE STATEMENT 'select tol.bdchave from tol_vrhf_emp_tfgts_a13 tol where tol.bdcodemp = '||prcodemp||
  ' and tol.bdcodcol = '||prcodcol||
  ' and tol.BDREFA13 = '||prreferencia
  INTO :wchave DO
  BEGIN
    EXECUTE STATEMENT wsql||' where lan.bdcodemp='||prcodemp||' and bdchave='||wchave;
  END
END^

/* Restore proc. body: SP_ATU_FGTS_CONT_C13 */
CREATE OR ALTER PROCEDURE SP_ATU_FGTS_CONT_C13 (
    PRVALOR NUMERIC(15,6),
    PRCODEMP INTEGER,
    PRCODCOL INTEGER,
    PRREF13 INTEGER,
    PRREFERENCIA INTEGER,
    PRVALORANT INTEGER)
AS
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WSQLINVERT VARCHAR(1000);
BEGIN
  /* Procedure Text */
  wsqlinvert = '';
  IF (((prvalor < 0) AND (prvalorant > 0)) OR ((prvalor > 0) AND (prvalorant < 0)))  THEN
     wsqlinvert = ', lan.bddebito = lan.bdcredito, lan.bdcredito = lan.bddebito ';

  IF (prvalor < 0) THEN
     prvalor = prvalor * -1;

  IF (prvalor = 0) THEN
     wsql = 'delete from tol_vrhf_emp_tfgts_13 lan ';
  ELSE
     wsql = 'update vsuc_empresas_tlan lan set lan.bdvalor = '||prvalor||wsqlinvert;

  FOR EXECUTE STATEMENT 'select tol.bdcodcol from tol_vrhf_emp_tfgts_13 tol where tol.bdcodemp = ' ||prcodemp||
  ' and tol.bdcodcol = '||prcodcol||
  ' and tol.BDREF13 = '||prref13||
  ' and tol.BDREFC13 = '||prreferencia INTO :wchave DO
  BEGIN
    EXECUTE STATEMENT wsql||' where lan.bdcodemp='||prcodemp||' and bdchave='||wchave;
  END
END^

/* Restore proc. body: SP_ATU_FGTS_CONT_FA */
ALTER PROCEDURE SP_ATU_FGTS_CONT_FA(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRCODTCA INTEGER,
PRDATA DATE,
PRVALOR NUMERIC(15,6),
PRFORMULA VARCHAR(100),
PRVALORANT NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WWHERE VARCHAR(1000);
DECLARE VARIABLE WSQLINVERT VARCHAR(1000);
BEGIN
  /* Procedure Text */
  wwhere = ' where lan.bdchave = tol.bdchave and tol.bdcodemp = lan.bdcodemp'||
              ' and tol.bdcodemp = '||prcodemp||
              ' and tol.bdcodcol = '||prcodcol||
              ' and tol.bdcodtca = '||prcodtca||
              ' and tol.bddatafa = '''||prdata||
              ''' and tol.BDFORMULA = '''||prformula||''' ';

  wsqlinvert = '';
  IF (((prvalor < 0) AND (prvalorant > 0)) OR ((prvalor > 0) AND (prvalorant < 0)))  THEN
     wsqlinvert = ', lan.bddebito = lan.bdcredito, lan.bdcredito = lan.bddebito ';

  IF (prvalor < 0) THEN
     prvalor = prvalor * -1;

  IF (prvalor = 0) THEN
     wsql = 'delete from tol_vrhf_emp_tfgts_fa lan ';
  ELSE
     wsql = 'update vsuc_empresas_tlan lan set lan.bdvalor = CAST('||prvalor||' AS NUMERIC(15,2))'||wsqlinvert;

  wsql = wsql||' where lan.bdcodemp = '||prcodemp||'  and exists (select tol.bdcodcol from tol_vrhf_emp_tfgts_fa tol';
  wsql = wsql||wwhere||')';

   EXECUTE STATEMENT wsql;
END
^

/* Restore proc. body: SP_ATU_FGTS_CONT_FC */
ALTER PROCEDURE SP_ATU_FGTS_CONT_FC(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER,
PRREFCOMP INTEGER,
PRORDEM INTEGER,
PRVALOR NUMERIC(15,6),
PRFORMULA VARCHAR(100),
PRVALORANT NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQLCC VARCHAR(1000);
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WWHERE VARCHAR(1000);
DECLARE VARIABLE WSQLINVERT VARCHAR(1000);
BEGIN
  /* Procedure Text */
  wwhere = ' where lan.bdchave = tol.bdchave and tol.bdcodemp = lan.bdcodemp'||
              ' and tol.bdcodemp = '||prcodemp||
              ' and tol.bdcodcol = '||prcodcol||
              ' and tol.BDREFFC = '||prrefcomp||
              ' and tol.BDFORMULA = '''||prformula||''' ';

  wsqlinvert = '';
  IF (((prvalor < 0) AND (prvalorant > 0)) OR ((prvalor > 0) AND (prvalorant < 0)))  THEN
     wsqlinvert = ', lan.bddebito = lan.bdcredito, lan.bdcredito = lan.bddebito ';

  IF (prvalor < 0) THEN
     prvalor = prvalor * -1;

  wsqlcc = NULL;
  IF (prordem IS NULL) THEN
     BEGIN
       IF (prvalor = 0) THEN
          wsql = 'delete from tol_vrhf_emp_tfgts_fc lan ';
       ELSE
          wsql = 'update vsuc_empresas_tlan lan set lan.bdvalor = '||prvalor||wsqlinvert;

       wsql = wsql||' where exists (select tol.bdcodcol from tol_vrhf_emp_tfgts_fc tol';
       wsql = wsql||wwhere||
                  ' and tol.BDREFFN = '||prreferencia||
                  ')';
     END
  ELSE
     BEGIN
       IF (prvalor = 0) THEN
          wsql = 'delete from tol_vrhf_emp_tfgts_ft_fc lan ';
       ELSE
          wsql = 'update vsuc_empresas_tlan lan set lan.bdvalor = '||prvalor||wsqlinvert;

       wsql = wsql||' where exists (select tol.bdcodcol from tol_vrhf_emp_tfgts_ft_fc tol';
    
       wsqlcc = 'update vsuc_empresas_tlcc lan set lan.bdvalor = '||prvalor||
              ' where exists (select tol.bdcodcol from tol_vrhf_emp_tfgts_ft_fc tol';

       wsql = wsql||wwhere;

       wsql = wsql||' and tol.bdordem = '||prordem||
                    ' and tol.BDREFTOMADOR = '||prreferencia;
       wsql = wsql||')';

       wsqlcc = wsqlcc||wwhere;
       wsqlcc = wsqlcc||' and tol.bdordem = '||prordem||
                        ' and tol.BDREFTOMADOR = '||prreferencia;
       wsqlcc = wsqlcc||')';
     END

   EXECUTE STATEMENT wsql;

   IF (wsqlcc IS NOT NULL) THEN
      BEGIN
        EXECUTE STATEMENT wsqlcc;
      END
END
^

/* Restore proc. body: SP_ATU_FGTS_CONT_FN */
ALTER PROCEDURE SP_ATU_FGTS_CONT_FN(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER,
PRORDEM INTEGER,
PRVALOR NUMERIC(15,6),
PRFORMULA VARCHAR(100),
PRVALORANT NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQLINVERT VARCHAR(1000);
DECLARE VARIABLE WSQLCC VARCHAR(1000);
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WWHERE VARCHAR(1000);
BEGIN
  /* Procedure Text */
  wwhere = ' where lan.bdchave = tol.bdchave and tol.bdcodemp = lan.bdcodemp'||
              ' and tol.bdcodemp = '||prcodemp||
              ' and tol.bdcodcol = '||prcodcol||
              ' and tol.BDFORMULA = '''||prformula||''' ';

  wsqlinvert = '';
  IF (((prvalor < 0) AND (prvalorant > 0)) OR ((prvalor > 0) AND (prvalorant < 0)))  THEN
     wsqlinvert = ', lan.bddebito = lan.bdcredito, lan.bdcredito = lan.bddebito ';

  IF (prvalor < 0) THEN
     prvalor = prvalor * -1;

  wsqlcc = NULL;
  IF (prordem IS NULL) THEN
     BEGIN
       IF (prvalor = 0) THEN
          wsql = 'delete from tol_vrhf_emp_tfgts_fn lan ';
       ELSE
          wsql = 'update vsuc_empresas_tlan lan set lan.bdvalor = CAST('||prvalor||' AS NUMERIC(15,2))'||wsqlinvert;

       wsql = wsql||' where lan.bdcodemp = '||prcodemp||'  and exists (select tol.bdcodcol from tol_vrhf_emp_tfgts_fn tol';
       wsql = wsql||wwhere||
                  ' and tol.BDREFFN = '||prreferencia||
                  ')';
     END
  ELSE
     BEGIN
       IF (prvalor = 0) THEN
          wsql = 'delete from tol_vrhf_emp_tfgts_ft lan';
       ELSE
          wsql = 'update vsuc_empresas_tlan lan set lan.bdvalor = CAST('||prvalor||' AS NUMERIC(15, 2))'||wsqlinvert;

       wsql = wsql||' where lan.bdcodemp = '||prcodemp||'  and exists (select tol.bdcodcol from tol_vrhf_emp_tfgts_ft tol';
    
       wsqlcc = 'update vsuc_empresas_tlcc lan set lan.bdvalor = CAST('||prvalor||' AS NUMERIC(15, 2))'||
              ' where lan.bdcodemp = '||prcodemp||'  and exists (select tol.bdcodcol from tol_vrhf_emp_tfgts_ft tol';

       wsql = wsql||wwhere;
       wsql = wsql||' and tol.bdordem = '||prordem||
                    ' and tol.BDREFTOMADOR = '||prreferencia;
       wsql = wsql||')';

       wsqlcc = wsqlcc||wwhere;
       wsqlcc = wsqlcc||' and tol.bdordem = '||prordem||
                        ' and tol.BDREFTOMADOR = '||prreferencia;
       wsqlcc = wsqlcc||')';
     END

   EXECUTE STATEMENT wsql;

   IF (wsqlcc IS NOT NULL) THEN
      BEGIN
        EXECUTE STATEMENT wsqlcc;
      END
END
^

CREATE OR ALTER PROCEDURE SP_REMOVER_VAR_COMPLEMENTO (
    PRCOMPLEMENTO VARCHAR(200),
    PRREPLACE VARCHAR(10))
RETURNS (
    BDRESULT VARCHAR(200))
AS
DECLARE VARIABLE WVAR VARCHAR(100);
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WPOSULTDEL INTEGER;
DECLARE VARIABLE WCOUNT INTEGER;
begin
  /* Procedure Text */
  wCOUNT= 0;
  WHILE ((POSITION('*', :PRCOMPLEMENTO) > 0) AND
         (wCOUNT < 30)) DO -- Alt.: #95379 - Ocorria que o cliente tinha um participante cadastrado com "**" no meio do nome, e ficava travado. Feito assim só para evitar futuros travamentos...
    BEGIN
      wCOUNT = wCOUNT+1;
      wPosUltDel = 1000;
      wPos = POSITION(' ', SUBSTRING(:PRCOMPLEMENTO FROM (POSITION('*', :PRCOMPLEMENTO)) FOR CHAR_LENGTH(:PRCOMPLEMENTO))); -- Não tem o -1 porque é um espaço, o Trim já remove ele.
      wPosUltDel = POSITION(',', SUBSTRING(:PRCOMPLEMENTO FROM (POSITION('*', :PRCOMPLEMENTO)) FOR CHAR_LENGTH(:PRCOMPLEMENTO)))-1; -- -1 para não pegar a , junto

      IF ((:wPosUltDel > 0) AND (wPosUltDel < :wPos)) THEN
        wPos = :wPosUltDel;

      wPosUltDel = 1000;
      wPosUltDel = POSITION('.', SUBSTRING(:PRCOMPLEMENTO FROM (POSITION('*', :PRCOMPLEMENTO)) FOR CHAR_LENGTH(:PRCOMPLEMENTO)))-1; -- -1 para não pegar o . junto

      IF ((:wPosUltDel > 0) AND (wPosUltDel < :wPos)) THEN
        wPos = :wPosUltDel;    

      wPosUltDel = 1000;
      wPosUltDel = POSITION('(', SUBSTRING(:PRCOMPLEMENTO FROM (POSITION('*', :PRCOMPLEMENTO)) FOR CHAR_LENGTH(:PRCOMPLEMENTO)))-1; -- -1 para não pegar o . junto

      IF ((:wPosUltDel > 0) AND (wPosUltDel < :wPos)) THEN
        wPos = :wPosUltDel;

      wPosUltDel = 1000;
      wPosUltDel = POSITION(')', SUBSTRING(:PRCOMPLEMENTO FROM (POSITION('*', :PRCOMPLEMENTO)) FOR CHAR_LENGTH(:PRCOMPLEMENTO)))-1; -- -1 para não pegar o . junto

      IF ((:wPosUltDel > 0) AND (wPosUltDel < :wPos)) THEN
        wPos = :wPosUltDel;   

      wPosUltDel = 1000;
      wPosUltDel = POSITION('/', SUBSTRING(:PRCOMPLEMENTO FROM (POSITION('*', :PRCOMPLEMENTO)) FOR CHAR_LENGTH(:PRCOMPLEMENTO)))-1; -- -1 para não pegar o . junto

      IF ((:wPosUltDel > 0) AND (wPosUltDel < :wPos)) THEN
        wPos = :wPosUltDel;

      wVar = TRIM(SUBSTRING(:PRCOMPLEMENTO FROM (POSITION('*', :PRCOMPLEMENTO)) FOR :wPos));
      wVar =  UPPER(REPLACE(REPLACE(:wVar, '(', ''), ')', ''));

      PRCOMPLEMENTO = REPLACE(:PRCOMPLEMENTO, :wVar, :PRREPLACE);
      wVar   = NULL;
    END
  bdresult = prcomplemento;
  suspend;
end
^

/* Restore proc. body: SP_ATU_LANCAMENTOS_CONTABIL */
CREATE OR ALTER PROCEDURE SP_ATU_LANCAMENTOS_CONTABIL (
    PRCODPLANO INTEGER,
    PRCHAVE INTEGER,
    PRTIPOLAN INTEGER,
    PRDEBITO INTEGER,
    PRCREDITO INTEGER,
    PRHISTORICO INTEGER,
    PROLDDEBITO INTEGER,
    PROLDCREDITO INTEGER,
    PROLDHISTORICO INTEGER,
    PRCODPLANOPADRAO INTEGER,
    PRCODPLANOHIST INTEGER,
    PRREFERENCIA INTEGER = 0,
    PRNOVACHAVE INTEGER = 0,
    PRCOMPL INTEGER = NULL,
    PROLDCOMPL INTEGER = NULL)
AS
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WVALUE VARCHAR(100);
DECLARE VARIABLE WOLDVALUE VARCHAR(100);
DECLARE VARIABLE WOK INTEGER;
DECLARE VARIABLE WTERCD VARCHAR(100);
DECLARE VARIABLE WTERCC VARCHAR(100);
DECLARE VARIABLE WPART INTEGER;
DECLARE VARIABLE WWHEREDATA VARCHAR(100);
DECLARE VARIABLE WPROX_REFERENCIA INTEGER;
DECLARE VARIABLE WULTIMO_DIA INTEGER;
DECLARE VARIABLE WCOMPL VARCHAR(200);
BEGIN
  /* Procedure Text */
--  suspend;
  wprox_referencia = null;
  select first 1 BDREFCTA FROM VW_TCONF_CONTAS_TODAS_REF REF
  WHERE REF.BDCODPLANOONLINE = :PRCODPLANO AND REF.BDCHAVE = :PRCHAVE  AND REF.BDREFCTA > :PRREFERENCIA
  ORDER BY REF.BDCODPLANOONLINE, REF.BDCHAVE, REF.BDREFCTA
  INTO :wprox_referencia;
  WWHEREDATA = '';
  if (PRREFERENCIA > 0) then
    WWHEREDATA = WWHEREDATA||' AND BDDATA >= '''||SUBSTRING(PRREFERENCIA FROM 5)||'/01/'||SUBSTRING(PRREFERENCIA FROM 1 for 4)||'''';

  if (WPROX_REFERENCIA > 0) then
    BEGIN
      WWHEREDATA = WWHEREDATA||' AND BDDATA < '''||SUBSTRING(WPROX_REFERENCIA FROM 5)||'/01/'||SUBSTRING(WPROX_REFERENCIA FROM 1 for 4)||'''';
    END

  IF ((prhistorico <> proldhistorico) OR ((prhistorico IS NULL) AND (proldhistorico IS NOT NULL)) OR ((prhistorico IS NOT NULL) AND (proldhistorico IS NULL))) THEN
     BEGIN
       -- mudou historico
       IF (prhistorico IS NULL) THEN
          WVALUE = ' = null';
       ELSE
          wvalue = ' = '||prhistorico;

       IF (proldhistorico IS NULL) THEN
          woldvalue = ' is null';
       ELSE
          woldvalue = ' = '||proldhistorico;

       wsql = ' update vsuc_empresas_tlan lan set lan.BDCODTPHI'||wvalue||
              ' where lan.BDCODTPHI'||woldvalue||' and'||
              '      exists (select * from tol_update_conta up '||
              '             where up.bdcodplanoonline = '||prcodplano||' and up.bdtipolan = '||prtipolan||' and (up.bdchave = '||prchave||' or up.bdchavetitulo = '||prchave||')'||
              '                   and up.bdcodemp = lan.bdcodemp and up.bdchavelan = lan.bdchave)'||WWHEREDATA;

       EXECUTE STATEMENT wsql;
     END

  IF ((PRCOMPL <> PROLDCOMPL) OR ((PRCOMPL IS NULL) AND (PROLDCOMPL IS NOT NULL)) OR ((PRCOMPL IS NOT NULL) AND (PROLDCOMPL IS NULL))) THEN
     BEGIN
       -- mudou historico
       select first 1 BDCOMPLEMENTO from TCOMPLEMENTO_HIST where BDCODCOMPHIST = :PRCOMPL into :wcompl;
       IF (PRCOMPL IS NULL) THEN
          WVALUE = ' = ''''';
       ELSE
          wvalue = ' = '''||wcompl||'''';

       select first 1 BDCOMPLEMENTO from TCOMPLEMENTO_HIST where BDCODCOMPHIST = :PROLDCOMPL into :wcompl;
       SELECT FIRST 1 BDRESULT FROM SP_REMOVER_VAR_COMPLEMENTO(:wcompl, '%') INTO :wcompl;
       IF (PROLDCOMPL IS NULL) THEN
          woldvalue = ' = lan.bdcompl';
       ELSE
          woldvalue = ' like '''||wcompl||'''';

       wsql = ' update vsuc_empresas_tlan lan set lan.bdcompl'||wvalue||
              ' where lan.bdcompl'||woldvalue||' and'||
              '      exists (select * from tol_update_conta up '||
              '             where up.bdcodplanoonline = '||prcodplano||' and up.bdtipolan = '||prtipolan||' and (up.bdchave = '||prchave||' or up.bdchavetitulo = '||prchave||')'||
              '                   and up.bdcodemp = lan.bdcodemp and up.bdchavelan = lan.bdchave)'||WWHEREDATA;

       EXECUTE STATEMENT wsql;
     END

  --Alterado para permitir excluir quando for folha, nesse caso nao deve alterar os lancamentos existentes
  IF (prcredito IS DISTINCT FROM proldcredito AND prcredito IS NOT NULL and proldcredito is not null) THEN
     BEGIN
       -- altera conta credito
       IF (prcredito IS NULL) THEN
          WVALUE = ' = null';
       ELSE
          wvalue = ' = '||prcredito;

       IF (proldcredito IS NULL) THEN
          woldvalue = ' is null';
       ELSE
          woldvalue = ' = '||proldcredito;

       WTERCD = '';
       WTERCC = '';

       SELECT COALESCE(a.bdparticipante,0) FROM planos_tpla a WHERE a.bdcodplapadrao = :prcodplanopadrao AND a.bdcodtpla = :prcredito INTO WPART;

       IF (wpart <> 1) THEN
          BEGIN
            WTERCD = ', lan.BDCODTERCEIROD = null';
            WTERCC = ', lan.BDCODTERCEIROC = null';
          END

       wsql = ' update vsuc_empresas_tlan lan set lan.bdcredito'||wvalue||WTERCC||
              ' where lan.bdcodplapadrao = '||prcodplanopadrao||' and lan.bdcredito'||woldvalue||' and'||
--              ' where lan.bdcredito'||woldvalue||' and'||

              '      exists (select * from tol_update_conta up '||
              '             where up.bdcodplanoonline = '||prcodplano||' and up.bdtipolan = '||prtipolan||' and (up.bdchave = '||prchave||' or up.bdchavetitulo = '||prchave||')'||
              '                   and up.bdcodemp = lan.bdcodemp and up.bdchavelan = lan.bdchave)'||WWHEREDATA;

       EXECUTE STATEMENT wsql;

       wsql = ' update vsuc_empresas_tlan lan set lan.bddebito'||wvalue||wtercd||
              ' where lan.bdcodplapadrao = '||prcodplanopadrao||' and lan.bddebito'||woldvalue||' and'||
--              ' where lan.bddebito'||woldvalue||' and'||

              '      exists (select * from tol_update_conta up '||
              '             where up.bdcodplanoonline = '||prcodplano||' and up.bdtipolan = '||prtipolan||' and (up.bdchave = '||prchave||' or up.bdchavetitulo = '||prchave||')'||
              '                   and up.bdcodemp = lan.bdcodemp and up.bdchavelan = lan.bdchave)'||WWHEREDATA;

       EXECUTE STATEMENT wsql;
     END

  --Alterado para permitir excluir quando for folha, nesse caso nao deve alterar os lancamentos existentes
  IF (prdebito IS DISTINCT FROM prolddebito AND prdebito IS NOT NULL and prolddebito is not null) THEN
     BEGIN
       -- altera conta credito
       IF (prdebito IS NULL) THEN
          WVALUE = ' = null';
       ELSE
          wvalue = ' = '||prdebito;

       IF (prolddebito IS NULL) THEN
          woldvalue = ' is null';
       ELSE
          woldvalue = ' = '||prolddebito;

       WTERCD = '';
       WTERCC = '';
       SELECT COALESCE(a.bdparticipante,0) FROM planos_tpla a WHERE a.bdcodplapadrao = :prcodplanopadrao AND a.bdcodtpla = :prdebito INTO WPART;

       IF (wpart <> 1) THEN
          BEGIN
            WTERCD = ', lan.BDCODTERCEIROD = null';
            WTERCC = ', lan.BDCODTERCEIROC = null';
          END

       wsql = ' update vsuc_empresas_tlan lan set lan.bdcredito'||wvalue||WTERCC||
              ' where lan.bdcodplapadrao = '||prcodplanopadrao||' and lan.bdcredito'||woldvalue||' and'||
--              ' where lan.bdcredito'||woldvalue||' and'||

              '      exists (select * from tol_update_conta up '||
              '             where up.bdcodplanoonline = '||prcodplano||' and up.bdtipolan = '||prtipolan||' and (up.bdchave = '||prchave||' or up.bdchavetitulo = '||prchave||')'||
              '                   and up.bdcodemp = lan.bdcodemp and up.bdchavelan = lan.bdchave)'||WWHEREDATA;

       EXECUTE STATEMENT wsql;

       wsql = ' update vsuc_empresas_tlan lan set lan.bddebito'||wvalue||wtercd||
              ' where lan.bdcodplapadrao = '||prcodplanopadrao||' and lan.bddebito'||woldvalue||' and'||
--              ' where lan.bddebito'||woldvalue||' and'||

              '      exists (select * from tol_update_conta up '||
              '             where up.bdcodplanoonline = '||prcodplano||' and up.bdtipolan = '||prtipolan||' and (up.bdchave = '||prchave||' or up.bdchavetitulo = '||prchave||')'||
              '                   and up.bdcodemp = lan.bdcodemp and up.bdchavelan = lan.bdchave)'||WWHEREDATA;

       EXECUTE STATEMENT wsql;
     END

  if (PRNOVACHAVE > 0) then
    begin
      wsql = ' update tol_update_conta up set bdchave = '||prnovachave||', BDCHAVETITULO = '||prnovachave||
             ' where bdchave = '||prchave||' and bdcodplanoonline = '||prcodplano||' and up.bdtipolan = '||prtipolan||
             ' and exists(select first 1 BDCODEMP from VSUC_EMPRESAS_TLAN lan WHERE lan.BDCODEMP = up.BDCODEMP and lan.BDCHAVE = up.BDCHAVELAN '||WWHEREDATA||')';
     EXECUTE STATEMENT wsql;

      wsql = ' update tol_update_conta up set bdchave = '||prnovachave||', BDCHAVETITULO = '||prnovachave||
             ' where bdchave = '||prchave||' and bdcodplanoonline = '||prcodplano||' and up.bdtipolan = '||prtipolan||
             ' and exists(select first 1 BDCODEMP from VSUC_EMPRESAS_TLAN lan WHERE lan.BDCODEMP = up.BDCODEMP and lan.BDCHAVE = up.BDCHAVELAN '||WWHEREDATA||')';
      EXECUTE STATEMENT wsql;

      wsql = 'UPDATE TDARFGERPGTO P SET P.bdchaveconfonline = '||prnovachave||
             ' WHERE P.bdchaveconfonline = '||prchave||' and P.bdcodplanoonline = '||prcodplano||REPLACE(WWHEREDATA, 'BDDATA', 'BDDATAPGTO');
      EXECUTE STATEMENT wsql;
      wsql = 'UPDATE VEF_EMP_TMOVENTPARPGTO P SET P.bdchaveconfonline = '||prnovachave||
             ' WHERE P.bdchaveconfonline = '||prchave||' and P.bdcodplanoonline = '||prcodplano||REPLACE(WWHEREDATA, 'BDDATA', 'BDDATAPGTOPAR');
      EXECUTE STATEMENT wsql;
      wsql = 'UPDATE VEF_EMP_TMOVF100PARPGTO P SET P.bdchaveconfonline = '||prnovachave||
             ' WHERE P.bdchaveconfonline = '||prchave||' and P.bdcodplanoonline = '||prcodplano||REPLACE(WWHEREDATA, 'BDDATA', 'BDDATAPGTOPAR');
      EXECUTE STATEMENT wsql;
      wsql = 'UPDATE VEF_EMP_TMOVOPIMOBI_F200_PGTO P SET P.BDCHAVEPLANOONLINE = '||prnovachave||
             ' WHERE P.BDCHAVEPLANOONLINE = '||prchave||' and P.bdcodplanoonline = '||prcodplano||REPLACE(WWHEREDATA, 'BDDATA', 'BDDATAPGTO');
      EXECUTE STATEMENT wsql;
      wsql = 'UPDATE VEF_EMP_TMOVSAIPARPGTO P SET P.bdchaveconfonline = '||prnovachave||
             ' WHERE P.bdchaveconfonline = '||prchave||' and P.bdcodplanoonline = '||prcodplano||REPLACE(WWHEREDATA, 'BDDATA', 'BDDATAPGTOPAR');
      EXECUTE STATEMENT wsql;
      wsql = 'UPDATE VEF_EMP_TMOVSERPARPGTO P SET P.bdchaveconfonline = '||prnovachave||
             ' WHERE P.bdchaveconfonline = '||prchave||' and P.bdcodplanoonline = '||prcodplano||REPLACE(WWHEREDATA, 'BDDATA', 'BDDATAPGTOPAR');
      EXECUTE STATEMENT wsql;
    end
END
^

/* Restore proc. body: SP_ATUALIZA_APELIDO_IE_EMP */
ALTER PROCEDURE SP_ATUALIZA_APELIDO_IE_EMP(PRCODEMP INTEGER,
PRREF INTEGER)
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WAPE VARCHAR(20);
DECLARE VARIABLE WIE VARCHAR(20);
DECLARE VARIABLE WSQL VARCHAR(20000);
BEGIN

/*  wSql = ' select ref.bdcodemp,ref.bdapeemp,ref.bdieemp '||
         ' from tempresas_ref ref '||
         ' join (select y.bdcodemp,max(y.bdrefemp) bdrefemp from tempresas_ref y group by y.bdcodemp) x '||
         '         on (ref.bdcodemp = x.bdcodemp and ref.bdrefemp = x.bdrefemp)';

   if (prcodemp is not null) then
      begin
        wsql = wsql||' where ref.bdcodemp = '||prcodemp;
        if (prref is not null) then
           wsql = wsql||' and ref.bdrefemp = '||prref;
      end

   for execute statement wSql into :wcodemp, :wape, :wie do
   begin
     update tempresas set BDAPELIDO = :wape, BDIE = :wie where bdcodemp = :wcodemp;
   end*/
END
^

/* Restore proc. body: SP_AUTONOMO_SEFIP */
CREATE OR ALTER procedure SP_AUTONOMO_SEFIP (
    PRREF integer = 0)
returns (
    BDCODCOL integer,
    BDOCORRENCIA varchar(1),
    BDPIS varchar(20),
    BDADM varchar(10),
    BDCATEGORIA varchar(10),
    BDNOME varchar(100),
    BDMATRICULA varchar(20),
    BDCTPS varchar(10),
    BDSERIECT DM_SERIECTPS,
    BDDATAOPCAO varchar(10),
    BDDATANASC varchar(10),
    BDCBO varchar(10),
    BDCPF varchar(14))
as
declare variable WCOL integer;
declare variable WEMP integer;
declare variable WSQL varchar(3600);
declare variable WWHERE varchar(3600);
declare variable WREF integer;
declare variable WSQL2 varchar(3600);
BEGIN
  /* Procedure Text */
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wemp;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_COLSEFIP') FROM rdb$database INTO wcol;
  IF (wcol IS NULL) THEN
     wcol = 0;

  IF (prref > 0) THEN
    BEGIN
      wref = prref;
    END
  ELSE
    BEGIN
      SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) FROM RDB$DATABASE INTO wref;
    END

--  wcol = 1;
/*
  wsql = 'select serv.bdcodter bdcodcol, cast(coalesce(fgts.bdocorrenciater,0) as varchar(1)), col_doc.bdpister, '||
         'cast(fgts.bdcategoriater as varchar(10)), col_cad.bdnomter, cast(serv.bdcodter as varchar(10)) bdmatricula,'||
         'col_doc.BDCTPSTER, col_doc.BDSERIECTPSTER||col_doc.BDDSERIECTPSTER BDSERIECT, '||
         '(select bdddmmaaaa from ddmmaaaa(col_cad.bddatacadter)) bdopcao,'||
         '(select bdddmmaaaa from ddmmaaaa(col_cad.bddatanascter)) bdnasc, cast(COL_DIAVINC.bdcodcbo as varchar(10)), '||
         'case '||
         'when (char_length(col_doc.BDCPFMEI) = 14) then col_doc.BDCPFMEI '||
         'else col_doc.BDCPFTER '||
         'end BDCPFTER '||
         ' from VRH_BASE_TSERVTERC serv '||
         ' left outer join VRHF_BASE_TTERC_FGTSGPS FGTS on (FGTS.BDCODTER = serv.BDCODTER and '||
                                                           'FGTS.BDREFTERC = (select first 1 BDREFTERC from VRHF_BASE_TTERC_FGTSGPS where BDCODTER = FGTS.BDCODTER and BDREFTERC <= '||wref||' order by BDCODTER, BDREFTERC desc)) '||
         ' left outer join vw_vrh_base_tterc_doc col_doc on (col_doc.bdcodter = serv.bdcodter) '||
         ' left outer join vrh_base_tterc col_cad on (col_cad.bdcodter = serv.bdcodter) '||
         ' left outer join VW_VRH_BASE_TTERC_VINC COL_DIAVINC on (COL_DIAVINC.bdcodcol = serv.bdcodter) ';


  wwhere = '';

  IF (prref > 0 AND prref IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||' where serv.bdrefserv = '||prref;
  IF (wcol > 0) THEN
          wwhere = wwhere||' and col.bdcodcol = '||wcol;
     END
  ELSE
     BEGIN
       IF (wcol > 0) THEN
     wwhere = wwhere||'  where col.bdcodcol = '||wcol;
     END

  if (wwhere <> '') then
    wwhere = wwhere||' and  char_length(case when (char_length(COL_DOC.BDCPFMEI) = 14) then COL_DOC.BDCPFMEI else COL_DOC.BDCPFTER end) = 14 ';
  else
    wwhere = wwhere||' where char_length(case when (char_length(COL_DOC.BDCPFMEI) = 14) then COL_DOC.BDCPFMEI else COL_DOC.BDCPFTER end) = 14 ';

  wsql = wsql||wwhere;
*/


  wsql = 'select serv.bdcodter bdcodcol, cast(coalesce(fgts.bdocorrenciater,0) as varchar(1)), '||
         'cast(fgts.bdcategoriater as varchar(10)), col_cad.bdnomter, cast(serv.bdcodter as varchar(10)) bdmatricula,'||
         '(select bdddmmaaaa from ddmmaaaa(col_cad.bddatacadter)) bdopcao,'||
         '(select bdddmmaaaa from ddmmaaaa(col_cad.bddatanascter)) bdnasc, cast(COL_DIAVINC.bdcodcbo as varchar(10)), '||
         'case '||
         'when (char_length(TRH.BDCPFMEITER) = 14) then TRH.BDCPFMEITER '||
         'else TER.BDCGCTER '||
         'end BDCPFTER '||
         ' from VRH_BASE_TSERVTERC serv '||
         ' left outer join VRHF_BASE_TTERC_FGTSGPS FGTS on (FGTS.BDCODTER = serv.BDCODTER and '||
                                                           'FGTS.BDREFTERC = (select first 1 BDREFTERC from VRHF_BASE_TTERC_FGTSGPS where BDCODTER = FGTS.BDCODTER and BDREFTERC <= '||wref||' order by BDCODTER, BDREFTERC desc)) '||
         ' left outer join vrh_base_tterc col_cad on (col_cad.bdcodter = serv.bdcodter) '||
         ' left outer join TTERCEIRO TER on (TER.BDCODTER = serv.BDCODTER)'||
         ' left outer join TTERCEIRO_RH TRH on (TRH.BDCODTER = SERV.BDCODTER)'||
         ' left outer join VW_VRH_BASE_TTERC_VINC COL_DIAVINC on (COL_DIAVINC.bdcodcol = serv.bdcodter) ';

  wwhere = '';

  IF (prref > 0 AND prref IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||' where serv.bdrefserv = '||prref;
  IF (wcol > 0) THEN
          wwhere = wwhere||' and col.bdcodcol = '||wcol;
     END
  ELSE
     BEGIN
       IF (wcol > 0) THEN
        wwhere = wwhere||'  where col.bdcodcol = '||wcol;
     END

  if (wwhere <> '') then
    wwhere = wwhere||' and  char_length(case when (char_length(TRH.BDCPFMEITER) = 14) then TRH.BDCPFMEITER else TER.BDCGCTER end) = 14 ';
  else
    wwhere = wwhere||' where char_length(case when (char_length(TRH.BDCPFMEITER) = 14) then TRH.BDCPFMEITER else TER.BDCGCTER end) = 14 ';

  wsql = wsql||wwhere;


  FOR EXECUTE STATEMENT wsql
    INTO
      bdcodcol,
      BDOCORRENCIA,
      --bdpis ,
      bdcategoria ,
      bdnome ,
      bdmatricula,
      --bdctps,
      --bdseriect,
      bddataopcao,
      bddatanasc,
      bdcbo,
      bdcpf
      DO
  BEGIN
     wSQL2 = 'select COL.BDPISTER, COL.BDCTPSTER, COL.BDSERIECTPSTER||COL.BDDSERIECTPSTER BDSERIECT '||
               'from '||
               '(select DOC.BDPISTER, DOC.BDCTPSTER, DOC.BDSERIECTPSTER, DOC.BDDSERIECTPSTER '||
               '  from TTERCEIRO TER '||
               '  left outer join VRH_BASE_TTERC_DOCREF DOC on (DOC.BDCODTER = TER.BDCODTER and DOC.BDREFTERC = (select max(R.BDREFTERC) from VRH_BASE_TTERC_DOCREF R where R.BDCODTER = TER.BDCODTER and R.BDREFTERC <= '||PRREF||'))'||
               '  where TER.BDCODTER = '||BDCODCOL||' )COL';

      execute statement wsql2 into :bdpis, :bdctps, :bdseriect;

      IF (BDOCORRENCIA IS NULL) THEN
         BDOCORRENCIA = '';
    
      IF (bdpis IS NULL) THEN
         bdpis  = '';
    
      IF (bdadm IS NULL) THEN
         bdadm = '';
    
      IF (bdcategoria IS NULL) THEN
         bdcategoria = '';
    
      IF (bdnome IS NULL) THEN
         bdnome = '';
    
      IF (bdmatricula IS NULL) THEN
         bdmatricula = '';
    
      IF (bdctps IS NULL) THEN
          bdctps = '';
    
      IF (bdseriect IS NULL) THEN
         bdseriect = '';
    
      IF (bddataopcao IS NULL) THEN
         bddataopcao = '';
    
      IF (bddatanasc IS NULL) THEN
         bddatanasc = '';
    
      IF (bdcbo IS NULL) THEN
         bdcbo = '';

      SUSPEND;
  END
END^

/* Restore proc. body: SP_BENEFICIARIOS_COLABORADOR */
create or alter procedure SP_BENEFICIARIOS_COLABORADOR (
    PRCODEMP varchar(32000),
    PRCODCOL varchar(32000),
    PRULTDIAMES date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDBENEFICIARIOS varchar(2000))
as
declare variable WDIA varchar(2);
declare variable WMES varchar(2);
declare variable WANO varchar(4);
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(32000);
declare variable WNOMEDPN varchar(68);
declare variable WDATANASCDPN date;
declare variable WCODDPN integer;
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WPARENT integer;
declare variable WREFERENCIA integer;
declare variable WSALFAM DM_BOOLEAN;
declare variable WDEPIR DM_BOOLEAN;
declare variable WDTAUX date;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
BEGIN
    
    wsql = 'select BDCODEMP, BDCODCOL, BDCODDPN, BDDATABAUXADPN from VRH_EMP_TDEP ';
--    wsql = 'select BDCODEMP, BDCODCOL, BDNOMEDPN, BDDATANASCDPN from VW_VRH_EMP_TDEP_REF';
    wwhere = '';

    IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        BEGIN
            wwhere = ' where '||prcodemp;
            IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
                wwhere = wwhere||' and '||prcodcol;
        END

--    IF (wwhere = '') THEN
--        wwhere = ' where ((BDDATABAUXADPN is null) or (BDDATABAUXADPN >= '''||:prultdiames||''')) and BDPARENESCODPN <> 3 and ((upper(coalesce(BDSALFAMDPN, ''FALSE'')) = ''TRUE'') or (upper(coalesce(BDDEPIRDPN, ''FALSE'')) = ''TRUE''))';
--    ELSE
--        wwhere = wwhere||' and ((BDDATABAUXADPN is null) or (BDDATABAUXADPN >= '''||:prultdiames||''')) and BDPARENESCODPN <> 3 and ((upper(coalesce(BDSALFAMDPN, ''FALSE'')) = ''TRUE'') or (upper(coalesce(BDDEPIRDPN, ''FALSE'')) = ''TRUE''))';
--
--    wqdebeneficiarios = 0;

    wsql = wsql||wwhere||' order by BDCODEMP, BDCODCOL, BDCODDPN ';

    wempatu = 0;
    wcolatu = 0;
    bdbeneficiarios = '';
    wreferencia = CAST((SUBSTRING(CAST(:prultdiames AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(:prultdiames AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

    FOR EXECUTE STATEMENT wsql INTO
--        :bdcodemp, :bdcodcol, :bdnomedpn, :bddatanascdpn
        :wcodemp, :wcodcol, :wcoddpn, :wdtaux
    DO
        BEGIN
          if (wempatu = 0) then
             wempatu = wcodemp;

          if (wcolatu = 0) then
             wcolatu = wcodcol;

          select first 1 BDNOMEDPN, BDPARENESCODPN, BDSALFAMDPN, BDDEPIRDPN, BDDATANASCDPN
          from VRH_EMP_TDEP_REF
          where BDCODEMP = :wcodemp and BDCODCOL = :wcodcol and BDCODDPN = :wcoddpn and BDREFDPN <= :wreferencia
          order by BDREFDPN DESC
          into :wnomedpn, :wparent, :wsalfam, :wdepir, wdatanascdpn;

          if (((wdtaux is null) or (wdtaux >= prultdiames)) and coalesce(wparent, 0) <> 3 and ((upper(coalesce(wsalfam, 'FALSE')) = 'TRUE') or (upper(coalesce(wdepir, 'FALSE')) = 'TRUE'))) then
             begin
               if ((wempatu <> wcodemp) or (wcolatu <> wcodcol)) then
                  begin
                    bdcodemp = wempatu;
                    bdcodcol = wcolatu;
                    suspend;
                    bdbeneficiarios = '';
                    wempatu = wcodemp;
                    wcolatu = wcodcol;
                  end
     
               wdia = SUBSTRING(CAST(wdatanascdpn AS VARCHAR(10)) FROM 9 FOR 2);
               wmes = SUBSTRING(CAST(wdatanascdpn AS VARCHAR(10)) FROM 6 FOR 2);
               wano = SUBSTRING(CAST(wdatanascdpn AS VARCHAR(10)) FROM 1 FOR 4);
     
               bdbeneficiarios = SUBSTRING(bdbeneficiarios || wnomedpn ||' '|| wdia||'/'||wmes||'/'||wano ||'; ' FROM 1 FOR 2000);
             end 
          else
             begin
               bdbeneficiarios = '';
               wempatu = wcodemp;
               wcolatu = wcodcol;
             end
        END

  IF (wempatu > 0 and wcolatu > 0) THEN
     begin
       bdcodemp = wempatu;
       bdcodcol = wcolatu;
       suspend;
     end
END^

/* Restore proc. body: SP_CALC_DEPRECIACAO */
ALTER PROCEDURE SP_CALC_DEPRECIACAO(PRCODEMP INTEGER,
PRCODBEM INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRTIPO INTEGER,
PRCONTABILIZACAO INTEGER)
 RETURNS(PRVALORCORRIGIDOANTERIOR NUMERIC(15,2),
PRCORRECAOPERIODO NUMERIC(15,2),
PRVALORCORRIGIDOATUAL NUMERIC(15,2),
PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2),
PRDEPRECIACAOPERIODO NUMERIC(15,2),
PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6),
PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2),
PRVALORRESIDUALCONTABIL NUMERIC(15,2),
PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
PRTOTALMESESDEPRECIACAO INTEGER,
PRMESESDEPRECIADOS INTEGER,
PRMESESDEPRECIAR INTEGER,
PRTAXADEPRECIACAOANUAL NUMERIC(6,6),
PRDATATAXADEPRECIACAO DATE,
PRVALORBAIXA NUMERIC(15,2),
PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,2),
PRVALORBAIXAREAL NUMERIC(15,2),
PRVALORMOEDA NUMERIC(15,6),
PRDATABAIXA DATE,
PRVALORAQUISICAOMOEDA NUMERIC(15,6),
PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
PRVALORAQUISICAOORIGINAL NUMERIC(15,2),
PRCTADEBITODEPRE INTEGER,
PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,2))
 AS
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WREFFIM INTEGER;
DECLARE VARIABLE WDATAAQUISICAO DATE;
DECLARE VARIABLE WDTINI DATE;
DECLARE VARIABLE WDTFIM DATE;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WULTDIAMES INTEGER;
DECLARE VARIABLE WCONTINUACALCULO VARCHAR(5);
DECLARE VARIABLE WCODBEMORIGINAL INTEGER;
DECLARE VARIABLE WDATAINICIOCALC DATE;
DECLARE VARIABLE WDATAFIMCALC DATE;
DECLARE VARIABLE WDATAORIGAQUISICAO DATE;
DECLARE VARIABLE WDEPDIA VARCHAR(5);
DECLARE VARIABLE WDEPMENSAL VARCHAR(5);
DECLARE VARIABLE WDEPMESBAIXA VARCHAR(5);
DECLARE VARIABLE WDATAULTIMOITEMDEP DATE;
DECLARE VARIABLE WVALDEPACUMUBEM NUMERIC(15,6);
DECLARE VARIABLE WMESESDEPACUMUBEM INTEGER;
DECLARE VARIABLE WNUMDIAS INTEGER;
DECLARE VARIABLE WCODMOEDA INTEGER;
DECLARE VARIABLE WDESCMOEDA VARCHAR(20);
DECLARE VARIABLE WVALORBAIXA NUMERIC(15,2);
DECLARE VARIABLE WVALORBAIXAAUX NUMERIC(15,2);
DECLARE VARIABLE WDATABAIXA DATE;
DECLARE VARIABLE WVALORAQUISICAO NUMERIC(15,6);
DECLARE VARIABLE WPOSSUIBAIXA VARCHAR(5);
DECLARE VARIABLE WREFMOEDAINI VARCHAR(10);
DECLARE VARIABLE WREFMOEDAFIM VARCHAR(10);
DECLARE VARIABLE WVALORMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPDIASADEPRECIAR INTEGER;
DECLARE VARIABLE WTOTALMESESDEPRECIACAO INTEGER;
DECLARE VARIABLE WMESESDEPRECIADOS INTEGER;
DECLARE VARIABLE WMESESDEPRECIAR INTEGER;
DECLARE VARIABLE WTOTALMESESDOPERIODO INTEGER;
DECLARE VARIABLE WDATAOFICIALINICIOLCALCULO DATE;
DECLARE VARIABLE WDATATOTALMESES DATE;
DECLARE VARIABLE WDATATOTALMESESDEPDIA DATE;
DECLARE VARIABLE WDATATOTALMESESULTIMODIA DATE;
DECLARE VARIABLE WDEPDIAFINAL VARCHAR(5);
DECLARE VARIABLE WDATAATUAL DATE;
DECLARE VARIABLE WDIFERENCAMESES INTEGER;
DECLARE VARIABLE WVALORAQUISICAOMOEDA NUMERIC(15,7);
DECLARE VARIABLE WVALORDEPRECIACAOMENSAL NUMERIC(15,7);
DECLARE VARIABLE WVALORDEPRECIACAODIARIA NUMERIC(15,6);
DECLARE VARIABLE WDATAINICIAL DATE;
DECLARE VARIABLE WDATAFINAL DATE;
DECLARE VARIABLE WDEPRECIACAOPERIODO NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOPERIODOMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUAL NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2);
DECLARE VARIABLE WVALORCORRIGIDOANTERIOR NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6);
DECLARE VARIABLE WCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2);
DECLARE VARIABLE WVALORRESIDUALCONTABIL NUMERIC(15,6);
DECLARE VARIABLE WVALORRESIDUALCONTABILMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOBAIXAMOEDA NUMERIC(15,2);
BEGIN
  /*Stored procedure para calcular a depreciação dos bens*/

  --#alt:6598.
  /*Esta stored procedure foi iniciada para calcular de uma forma mais rápida, mas conseguimos melhorar a rotina anterior.
  Caso a rotina SP_CONS_CALC_DEP volte a dar problema já tem essa meia encaminhada.
  OBS_1: Está rotina está no início, por isso precisa implementar várias situações e testar muito bem.
  OBS_2: Tem algumas stored procedure que podem ser trocadas por rotinas do próprio banco para melhorar o desempenho. 
  Ex: select BDNOVADATA from diminui_meses(:wdatatotalmesesultimodia,1) into wdatatotalmesesultimodia;   --->  wdatatotalmesesultimodia = addmonth(:wdatatotalmesesultimodia,-1);
      select bdMESES from DIFERENCA_MESES(:wdatainicial,:wdatafinal) into :wtotalmesesdoperiodo;         --->  wtotalmesesdoperiodo = datediff(month,:wdatainicial,:wdatafinal);                 
  */

  -- Inicializa parâmetros
  PRVALORCORRIGIDOANTERIOR        = 0;
  PRCORRECAOPERIODO               = 0;
  PRVALORCORRIGIDOATUAL           = 0;
  PRDEPRECIACAOACUMULADAANTERIOR  = 0;
  PRDEPRECIACAOPERIODO            = 0;
  PRDEPRECIACAOPERIODOMOEDA       = 0;
  PRDEPRECIACAOACUMULADAATUAL     = 0;
  PRDEPRECIACAOACUMULADAATUALMOED = 0;
  PRCORRECAOMONETARIADEPRECIACAO  = 0;
  PRVALORRESIDUALCONTABIL         = 0;
  PRVALORRESIDUALCONTABILMOEDA    = 0;
  PRTOTALMESESDEPRECIACAO         = 0;
  PRMESESDEPRECIADOS              = 0;
  PRMESESDEPRECIAR                = 0;
  PRTAXADEPRECIACAOANUAL          = 0;
  PRDATATAXADEPRECIACAO           = NULL;
  PRVALORBAIXA                    = 0;
  PRDEPRECIACAOBAIXAMOEDA         = 0;
  PRVALORBAIXAREAL                = 0;
  PRVALORMOEDA                    = 0;
  PRDATABAIXA                     = NULL;
  PRVALORAQUISICAOMOEDA           = 0;
  PRVALORCORRIGIDOANTERIORMOEDA   = 0;
  PRVALORAQUISICAOORIGINAL        = 0;
  PRCTADEBITODEPRE                = NULL;
  PRVALORDEPRECIACAODIARIAFIM     = 0;

  wcodbemoriginal            = 0;
  wdataorigaquisicao         = NULL;
  wdepdia                    = 'FALSE';
  wdepmensal                 = 'FALSE';
  wdepmesbaixa               = 'FALSE';
  wdatainiciocalc            = NULL;
  wdatafimcalc               = NULL;
  wdataultimoitemdep         = NULL;
  wvaldepacumubem            = 0;
  wnumdias                   = 0;
  wcodmoeda                  = 0;
  wdescmoeda                 = '';
  wvalormoeda                = 0;

  SELECT COALESCE(SUM(tbai.bdvalbai),0) AS TotalBaixa FROM empresas_tbai tbai
  WHERE (tbai.bdcodemp = :prcodemp)
  AND   (tbai.bdcodbem = :prcodbem)
  AND   (tbai.bddatbai <= :prdatafinal)
  INTO :wvalorbaixa;

  IF (wvalorbaixa > 0) THEN
    wpossuibaixa = 'TRUE';
  --Tipo 2 somente baixas
  IF ((prtipo = 2) AND (wvalorbaixa = 0)) THEN
    EXIT;

  SELECT tind.bddescind,tbem.bdcodind
  FROM (SELECT COALESCE(tbem.bdcodind,0) bdcodind FROM empresas_tbem tbem
        WHERE (tbem.bdcodemp = :prcodemp)
        AND   (tbem.bdcodbem = :prcodbem)) tbem
  LEFT OUTER JOIN TINDICES tind ON (tind.bdcodind = tbem.bdcodind)
  INTO :wdescmoeda,:wcodmoeda;

  SELECT tbem.bdDATORIAQUIBEM FROM empresas_tbem tbem
  WHERE (tbem.bdcodemp = :prcodemp) AND
        (tbem.bdcodbem = :prcodbem)
  INTO :wdataaquisicao;

  wmes = CAST(SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano = CAST(EXTRACT(YEAR FROM wdataaquisicao) AS INTEGER);
  SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO wultdiames;

  --wdtini           = wmes||'-01-'||wano;
  wdtini           = wdataaquisicao;
  wdtfim           = wmes||'-'||wultdiames||'-'||wano;
  wrefatu          = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
  wreffim          = CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER);
  wcontinuacalculo = 'TRUE';
  WHILE ((wrefatu <= wreffim) AND (wcontinuacalculo = 'TRUE')) DO
    BEGIN
      -- Inicializa variáveis
      wdatainicial               = wdtini;
      wdatafinal                 = wdtfim;
      wdepdiafinal               = 'FALSE';
      wmesesdepacumubem          = 0;
      wvalorbaixa                = 0;
      wvalorbaixaaux             = 0;
      wdatabaixa                 = NULL;
      wvaloraquisicao            = 0;
      wpossuibaixa               = 'FALSE';
      wrefmoedaini               = '';
      wrefmoedafim               = '';
      wdepdiasadepreciar         = 0;
      wtotalmesesdepreciacao     = 0;
      wmesesdepreciados          = 0;
      wmesesdepreciar            = 0;
      wtotalmesesdoperiodo       = 0;
      wdataoficialiniciolcalculo = NULL;
      wdatatotalmeses            = NULL;
      wdatatotalmesesdepdia      = NULL;
      wdatatotalmesesultimodia   = NULL;
      wdataatual                 = wdatafinal;
      wdiferencameses            = NULL;
      wvaloraquisicaomoeda       = 0;
      wvalordepreciacaomensal    = 0;
      wvalordepreciacaodiaria    = 0;
      wdepreciacaoperiodo        = 0;
      wdepreciacaoperiodomoeda   = 0;

      -- Quando o valor da depreciação acumulada passou do valor do bem não precisa continuar o processo até chegar na data informada
      IF ((wcontinuacalculo = 'TRUE') AND (prvaloraquisicaooriginal > 0) AND (prdepreciacaoacumuladaatual > COALESCE(prvaloraquisicaooriginal,0))) THEN
        wcontinuacalculo = 'FALSE';

      --Só faz o select da taxa da deprecição quando mudar o período
      IF ((prtaxadepreciacaoanual = 0) OR
          (wrefatu < CAST((SUBSTRING(wdatainiciocalc FROM 1 FOR 4)) || (SUBSTRING(wdatainiciocalc FROM 6 FOR 2)) AS INTEGER)) OR
          (wrefatu > CAST((SUBSTRING(wdatafimcalc FROM 1 FOR 4)) || (SUBSTRING(wdatafimcalc FROM 6 FOR 2)) AS INTEGER))) THEN
        SELECT tbem.bdcodorigbem, tbem.bdvalaquibem, tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem, tbem.bddepdiaria BDDEPDIARIA, tbem.bddepmesaquibem,
               tbem.bddepmesbaixabem, tdep.bddatinicalcbem, tdep.bddatfimcalcbem, tdep.bddatadep, tdep.bdvaldepacumubem,tdep.bdctadebitodepre, tbem.bdnumdias
        FROM empresas_tbem tbem
        LEFT OUTER JOIN empresas_tdepreciacao tdep ON ((tbem.bdcodemp = tdep.bdcodemp) AND (tbem.bdcodbem = tdep.bdcodbem) AND
                                                       (tdep.bdcontabilizacao = :prcontabilizacao) AND
                                                       (CAST((SUBSTRING(tdep.bddatinicalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatinicalcbem FROM 6 FOR 2)) AS INTEGER) <=
                                                        CAST((SUBSTRING(:wdtini FROM 1 FOR 4)) || (SUBSTRING(:wdtini FROM 6 FOR 2)) AS INTEGER)) AND
                                                       ((CAST((SUBSTRING(tdep.bddatfimcalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatfimcalcbem FROM 6 FOR 2)) AS INTEGER) >=
                                                         CAST((SUBSTRING(:wdtfim FROM 1 FOR 4)) || (SUBSTRING(:wdtfim FROM 6 FOR 2)) AS INTEGER)) OR (tdep.bddatfimcalcbem IS NULL)))
        WHERE (tbem.bdcodemp = :prcodemp) AND
              (tbem.bdcodbem = :prcodbem)
        INTO :wcodbemoriginal,    :prvaloraquisicaooriginal, :prtaxadepreciacaoanual, :wdataaquisicao,  :wdataorigaquisicao,
             :wdepdia,            :wdepmensal,               :wdepmesbaixa,           :wdatainiciocalc, :wdatafimcalc,
             :wdataultimoitemdep, :wvaldepacumubem,          :prctadebitodepre,       :wnumdias;

      IF ((wvaloraquisicao = 0) AND (prvaloraquisicaooriginal > 0)) THEN
        wvaloraquisicao = prvaloraquisicaooriginal;

      wvalorbaixa = 0;
      IF (wpossuibaixa = 'TRUE') THEN
        BEGIN
          FOR SELECT bddatbai,COALESCE(SUM(bdvalbai),0) AS TotalBaixa FROM empresas_tbai
              WHERE (bdcodemp = :prcodemp) AND (bdcodbem = :prcodbem)
              AND   (bddatbai BETWEEN :wdtini AND :wdtfim) GROUP BY bddatbai
              INTO :wdatabaixa,:wvalorbaixaaux DO
            BEGIN
              wvalorbaixa = wvalorbaixa + wvalorbaixaaux;
            END
        END

      IF (prvaloraquisicaooriginal IS NULL) THEN
        BEGIN
          EXCEPTION ex_date;
          SUSPEND;
          EXIT;
        END

      --if (prdatainicial > wdatafimcalc) then
      --  begin
      --    suspend;
      --    exit;
      --  end

      wvaloraquisicao = (wvaloraquisicao - wvalorbaixa);
    
      IF ((UPPER(wdepmesbaixa) = 'TRUE') AND (wvalorbaixa >= wvaloraquisicao)) THEN
        BEGIN
          wdatafinal = wdatabaixa; -- tinha prdatafinal
    
          IF (CAST((SUBSTRING(wdatabaixa FROM 1 FOR 4)) || (SUBSTRING(wdatabaixa FROM 6 FOR 2)) AS INTEGER) <=
              CAST((SUBSTRING(wdtfim FROM 1 FOR 4)) || (SUBSTRING(wdtfim FROM 6 FOR 2)) AS INTEGER)) THEN
            wdepmesbaixa = 'TRUE';
          ELSE
            wdepmesbaixa = 'FALSE';
        END
      ELSE
        wdepmesbaixa = 'FALSE';
    
      IF (UPPER(wdepmesbaixa) = 'TRUE') THEN
        wvaloraquisicao = (wvaloraquisicao + wvalorbaixa);

      IF ((((wvaloraquisicao IS NULL) OR (wvaloraquisicao <=0))) AND (UPPER(wdepmesbaixa) = 'FALSE')) THEN
        BEGIN
          SUSPEND;
          EXIT;
        END
    
      IF (prtipo = 2) THEN
        BEGIN
          prvaloraquisicaooriginal = wvalorbaixa;
          wvaloraquisicao          = wvalorbaixa;
        END

      -- CÁLCULO DE DEPRECIAÇÃO
      prvalorcorrigidoatual = wvaloraquisicao;

      --Conforme me explicado a moeda Ufir está congelada, por isso não preciso verifcar o valor dela todos os meses
      IF ((wvalormoeda IS NULL) OR (wvalormoeda = 0) OR (POSITION('UFIR',UPPER(wdescmoeda)) = 0))  THEN
        BEGIN
          --Seleciona o valor da moeda da data de aquisição ou se o bem já vier depreciado da data original de aquisição
          wrefmoedaini = SUBSTRING(CAST(:wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'0101';
          wrefmoedafim = SUBSTRING(CAST(:wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'1231';
          IF (wdataorigaquisicao IS NOT NULL) THEN
            BEGIN
              wrefmoedaini = SUBSTRING(CAST(:wdataorigaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'0101';
              wrefmoedafim = SUBSTRING(CAST(:wdataorigaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'1231';
            END
    
          SELECT MAX(tind.bdvalind) FROM tindval tind
                 WHERE (tind.bdcodind = :wcodmoeda) AND
                       (tind.bdrefind BETWEEN :wrefmoedaini AND :wrefmoedafim)
          INTO :wvalormoeda;
          --caso não encontre um valor nesse periodo, o sql a seguir retorna o mais próximo
          IF (wvalormoeda IS NULL) THEN
            BEGIN
              SELECT FIRST 1 tind.bdvalind FROM tindval tind
                     WHERE tind.bdcodind = :wcodmoeda AND
                     tind.bdrefind <= :wrefmoedaini
                     ORDER BY tind.bdrefind
              INTO :wvalormoeda;
            END
        END

      -- Depreciação diária (Início)
      IF (UPPER(wdepdia) = 'TRUE' ) THEN
        IF ((SUBSTRING(wdatainiciocalc FROM 9 FOR 2)) = '01') THEN
          wdepdia = 'FALSE';
    
      IF (UPPER(wdepdia) = 'TRUE') THEN
        BEGIN
          wdepdiasadepreciar = (SUBSTRING(wdatainiciocalc FROM 9 FOR 2));
    
          wmes = CAST(SUBSTRING(CAST(wdatainiciocalc AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
          wano = CAST(SUBSTRING(CAST(wdatainiciocalc AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
          SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO wultdiames;
    
          IF (wnumdias = 2) THEN
            wdepdiasadepreciar = wultdiames - wdepdiasadepreciar;
          ELSE
            wdepdiasadepreciar = 30 - wdepdiasadepreciar;
        END
      -- Depreciação diária (Fim)

      IF (prtaxadepreciacaoanual >= 0.1) THEN
        wtotalmesesdepreciacao = ((100 / prtaxadepreciacaoanual) * 12);
      ELSE
        BEGIN
          prvalorcorrigidoanteriormoeda = (wvaloraquisicao + wvalorbaixa) / wvalormoeda;
          prvalorresidualcontabil       = wvaloraquisicao;
          prvalorresidualcontabilmoeda  = (wvaloraquisicao / wvalormoeda);
          prdatataxadepreciacao         = wdataultimoitemdep;
          prvalorbaixa                  = wvalorbaixa;
          prvalorbaixareal              = wvalorbaixa;
          prvalormoeda                  = wvalormoeda;
          prdatabaixa                   = wdatabaixa;
          prvaloraquisicaomoeda         = (wvaloraquisicao / wvalormoeda);
    
          SUSPEND;
          EXIT;
        END

      IF (wdatainiciocalc IS NOT NULL) THEN
        wdataoficialiniciolcalculo = wdatainiciocalc;
      ELSE
        wdataoficialiniciolcalculo =  wdataaquisicao;

      IF (wvaloraquisicao = 0) THEN
        EXIT;
      -- Joga para uma variável o numero de meses que já foi depreciado em outro sistema
      IF (wvaldepacumubem > 0) THEN
        wmesesdepacumubem = ((wvaldepacumubem) / (wvaloraquisicao / wtotalmesesdepreciacao));

      wdatatotalmeses       = addmonth(wdataoficialiniciolcalculo, wtotalmesesdepreciacao-wmesesdepacumubem);
      wdatatotalmesesdepdia = addmonth(wdatatotalmeses, 1);
      -- Transforma no primeiro dia do mês
      wdatatotalmeses       = SUBSTRING(CAST(wdatatotalmeses AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                              SUBSTRING(CAST(wdatatotalmeses AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
      wdataaquisicao        = SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                              SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
    
      SELECT bdMESES FROM DIFERENCA_MESES(:wdatatotalmeses,:wdataatual) INTO :wdiferencameses ;
      ---------------wdiferencameses = datediff(month,:wdatatotalmeses,:wdataatual); --------------------
      IF (wdiferencameses-1 > 0) THEN
        BEGIN
         IF (wdepmensal = 'FALSE') THEN
           SELECT BDNOVADATA FROM add_meses(:wdatatotalmeses,1) INTO wdataatual;
         ELSE
           wdataatual = wdatatotalmeses;
        END

      IF ((wdepmensal = 'FALSE') AND
          (CAST(EXTRACT(YEAR FROM wdatainicial) || EXTRACT(MONTH FROM wdatainicial) AS INTEGER) = --
           CAST(EXTRACT(YEAR FROM wdataorigaquisicao) || EXTRACT(MONTH FROM wdataorigaquisicao) AS INTEGER))) THEN
        BEGIN
        SELECT BDNOVADATA FROM diminui_meses(:wdatafinal,1) INTO wdatafinal; -- tinha prdatafinal ---------------
        ---------------wdatafinal = addmonth(:wdatafinal,-1);
        END
    
      -- Se for relatorio de baixas, a data atual devera ser o do mes da baixa.
      IF ((prtipo = 2) OR ((wdatabaixa IS NOT NULL) AND (wvalorbaixa >= wvaloraquisicao))) THEN
        BEGIN
          wdataatual  = wdatabaixa;
          wdatafinal = wdatabaixa; -- tinha prdatafinal
        END
    
       IF ((wdatafimcalc IS NOT NULL) AND (wdatafimcalc < wdatafinal)) THEN -- tinha prdatafinal
         BEGIN
           wdataatual = wdatafimcalc;
           wdatafinal = wdatafimcalc; -- tinha prdatafinal
         END

      SELECT bdMESES FROM DIFERENCA_MESES(:wdataoficialiniciolcalculo,:wdataatual) INTO :wmesesdepreciados;
      ---------------wmesesdepreciados = datediff(month,:wdataoficialiniciolcalculo,:wdataatual); --------------------
      IF ((wdepmensal = 'FALSE') OR (wvaldepacumubem > 0)) THEN
        wmesesdepreciados = wmesesdepreciados - 1;
    
      -- Adiciona no total de meses depreciados o valor já depreciado de outro sistema
      IF ((wvaldepacumubem > 0) AND (wmesesdepreciados >= 0)) THEN
        wmesesdepreciados = wmesesdepreciados + ((wvaldepacumubem) / (wvaloraquisicao / wtotalmesesdepreciacao));
    
      IF (wmesesdepreciados > wtotalmesesdepreciacao) THEN
        wmesesdepreciados = wtotalmesesdepreciacao;

      -- Se os meses decreciados for menor que zero, significa que foi informado uma data inferior a data de aquisicao do bem
      IF (wmesesdepreciados > 0) THEN
        BEGIN
          -- Total de meses da diferença do periodo de depreciação
          wmes = CAST(SUBSTRING(CAST(wdatatotalmesesdepdia AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
          wano = CAST(SUBSTRING(CAST(wdatatotalmesesdepdia AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
          SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO wultdiames;
          wdatatotalmesesultimodia = wmes||'-'||wultdiames||'-'||wano;
          IF (wdatafinal > wdatatotalmesesultimodia) THEN -- tinha prdatafinal
            BEGIN
              IF (wdepdia = 'TRUE') THEN
                BEGIN
                  -- Caso seja o último mês para depreciar
                  IF (wmesesdepreciar = 0) THEN
                    wdepdiafinal = 'TRUE';
        
                  wdatatotalmesesultimodia = addmonth(wdatatotalmesesultimodia, 1);
                  wdatatotalmesesultimodia = SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                                             SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
                END
            END
        
          IF (wdatafinal > wdatatotalmeses) THEN -- tinha prdatafinal
            wdatafinal = wdatatotalmeses; -- tinha prdatafinal
        
          IF (wdatainicial < :wdataoficialiniciolcalculo) THEN --
            wdatainicial = wdataoficialiniciolcalculo; --
        
          SELECT bdMESES FROM DIFERENCA_MESES(:wdatainicial,:wdatafinal) INTO :wtotalmesesdoperiodo; -- tinha prdatafinal
          ---------------wtotalmesesdoperiodo = datediff(month,:wdatainicial,:wdatafinal); --------------------
          IF ((wvaldepacumubem > 0) AND (wdatainicial <= wdataorigaquisicao)) THEN --
            wtotalmesesdoperiodo = wtotalmesesdoperiodo-1;
          
          -- Meses à depreciar
          wmesesdepreciar      = (wtotalmesesdepreciacao - wmesesdepreciados);
          wvaloraquisicaomoeda = (wvaloraquisicao / wvalormoeda);
          -- Depreciação do período
          wvalordepreciacaomensal = (wvaloraquisicaomoeda / wtotalmesesdepreciacao);
    
          IF (wdepdiasadepreciar > 0) THEN
            BEGIN
              wvalordepreciacaodiaria     = (wvalordepreciacaomensal * wvalormoeda) / 30 * wdepdiasadepreciar;
              prvalordepreciacaodiariafim = (wvalordepreciacaomensal * wvalormoeda) - wvalordepreciacaodiaria;
            END
        
          IF (wdepdia = 'TRUE') THEN
            BEGIN
              -- Quer dizer que é o primeiro mês e esse mês não vai contar já que e parcial, o restante estara no último mês a depreciar
              wmesesdepreciar      = wmesesdepreciar + 1;
              wmesesdepreciados    = wmesesdepreciados - 1;
              wtotalmesesdoperiodo = wtotalmesesdoperiodo -1;
            END
    
          IF (wdatainicial <= :wdataaquisicao) THEN
            BEGIN
              wdepreciacaoperiodo      = ((wvalordepreciacaodiaria) + wvalordepreciacaomensal * wtotalmesesdoperiodo * wvalormoeda);
              wdepreciacaoperiodomoeda = ((wvalordepreciacaodiaria / wvalormoeda) + wvalordepreciacaomensal * wtotalmesesdoperiodo);
            END
          ELSE
          IF (wdepdia = 'TRUE') THEN
            BEGIN
              wdepreciacaoperiodo      = (wvalordepreciacaomensal * (wtotalmesesdoperiodo + 1) * wvalormoeda);
              wdepreciacaoperiodomoeda = (wvalordepreciacaomensal * wtotalmesesdoperiodo+1);
            END
          ELSE
            BEGIN
              wdepreciacaoperiodo      = (wvalordepreciacaomensal * (wtotalmesesdoperiodo) * wvalormoeda);
              wdepreciacaoperiodomoeda = (wvalordepreciacaomensal * wtotalmesesdoperiodo);
            END
    
          -----------------------------------------------------------------------------------
          IF ((wvalordepreciacaodiaria > 0) AND (wdatainicial <= :wdataaquisicao))  THEN
            BEGIN
              wdepreciacaoacumuladaatual = wvalordepreciacaomensal * wmesesdepreciados;
              wdepreciacaoacumuladaatual = wvalordepreciacaodiaria + wdepreciacaoacumuladaatual * wvalormoeda;
        
              wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
            END
          ELSE
            BEGIN
              wdepreciacaoacumuladaatual = wvalordepreciacaomensal * wmesesdepreciados;
              wdepreciacaoacumuladaatual = wvalordepreciacaodiaria + wdepreciacaoacumuladaatual * wvalormoeda;
        
              IF (wvalordepreciacaodiaria > 0) THEN
                wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
              ELSE
                wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual -  ((wvalordepreciacaomensal * (wtotalmesesdoperiodo) * wvalormoeda)));
            END
    
          IF (wdepreciacaoacumuladaanterior > 0) THEN
            wvalorcorrigidoanterior = wvaloraquisicao;
        
          IF (wdepreciacaoacumuladaanterior < 0) THEN
            wdepreciacaoacumuladaanterior = 0;
    
          wdepreciacaoacumuladaatualmoed = (wvalordepreciacaodiaria/wvalormoeda) + wvalordepreciacaomensal * wmesesdepreciados;
          wcorrecaomonetariadepreciacao  = 0;
          wvalorresidualcontabil         = (wvaloraquisicao - wdepreciacaoacumuladaatual);
          wvalorresidualcontabilmoeda    = wvalorresidualcontabil / wvalormoeda;
          wdepreciacaobaixamoeda         = (wvalorbaixa / wtotalmesesdepreciacao);
          wdepreciacaobaixamoeda         = (wdepreciacaobaixamoeda / wvalormoeda);
    
          IF (prtipo = 2) THEN
            BEGIN
              prvalorcorrigidoanterior      = wvalorcorrigidoanterior;
              prvalorcorrigidoanteriormoeda = (wvalorcorrigidoanterior) / wvalormoeda;
            END
          ELSE
            BEGIN
              prvalorcorrigidoanterior      = wvalorcorrigidoanterior + wvalorbaixa;
              prvalorcorrigidoanteriormoeda = (wvalorcorrigidoanterior + wvalorbaixa) / wvalormoeda;
            END
    
          IF ((wdepdia = 'TRUE')  AND (wdepdiafinal = 'TRUE')) THEN
            BEGIN
              IF (wdatainicial <= :wdataaquisicao) THEN
                BEGIN
                  wdepreciacaoperiodo      = ((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) + wvalordepreciacaomensal * wtotalmesesdoperiodo * wvalormoeda);
                  wdepreciacaoperiodomoeda = (((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) / wvalormoeda) + wvalordepreciacaomensal * wtotalmesesdoperiodo);
        
                  wdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual + prvalordepreciacaodiariafim;
                  wdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatual / wvalormoeda;
        
                  wvalorresidualcontabil      = (wvaloraquisicao - wdepreciacaoacumuladaatual);
                  wvalorresidualcontabilmoeda = 0;
        
                  wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
                END
              ELSE
                BEGIN
                  SELECT BDNOVADATA FROM diminui_meses(:wdatatotalmesesultimodia,1) INTO wdatatotalmesesultimodia;
                  ---------------wdatatotalmesesultimodia = addmonth(:wdatatotalmesesultimodia,-1);----------------------
        
                  wdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual + prvalordepreciacaodiariafim;
                  wdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatual / wvalormoeda;
        
                  wvalorresidualcontabil      = (wvaloraquisicao - wdepreciacaoacumuladaatual);
                  wvalorresidualcontabilmoeda = 0;
        
                  IF (wdatainicial <> :wdatatotalmesesultimodia) THEN
                    BEGIN
                      wdepreciacaoacumuladaanterior  = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
                      wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaanterior / wvalormoeda);
                    END
        
                  wdepreciacaoperiodo = wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior;
        
                  IF (wdepreciacaoperiodo <= 0) THEN
                    wdepreciacaoperiodomoeda = 0;
                  ELSE
                    wdepreciacaoperiodomoeda = ((wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior) / wvalormoeda);
                END
        
              wmesesdepreciados = wmesesdepreciados + 1;
              wmesesdepreciar   = 0;
            END
    
          prdepreciacaoacumuladaanterior  = wdepreciacaoacumuladaanterior;
          prdepreciacaoperiodo            = wdepreciacaoperiodo;
          prdepreciacaoperiodomoeda       = wdepreciacaoperiodomoeda;
          prdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual;
          prdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatualmoed;
          prcorrecaomonetariadepreciacao  = wcorrecaomonetariadepreciacao;
          prvalorresidualcontabil         = wvalorresidualcontabil;
          prvalorresidualcontabilmoeda    = wvalorresidualcontabilmoeda;
          prtotalmesesdepreciacao         = wtotalmesesdepreciacao;
          prmesesdepreciados              = wmesesdepreciados;
          prmesesdepreciar                = wmesesdepreciar;
          prdatataxadepreciacao           = wdataultimoitemdep;
          prvalorbaixa                    = wvalorbaixa;
          prdepreciacaobaixamoeda         = wdepreciacaobaixamoeda;
          prvalorbaixareal                = wvalorbaixa;
          prvalormoeda                    = wvalormoeda;
          prdatabaixa                     = wdatabaixa;
          prvaloraquisicaomoeda           = wvaloraquisicaomoeda;
        END

      wdtini  = addmonth(wdtini, 1);
      wmes    = CAST(SUBSTRING(CAST(wdtini AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
      wano    = CAST(EXTRACT(YEAR FROM wdtini) AS INTEGER);
      wdtini  = wmes||'-01-'||wano;
      wdtfim  = addmonth(wdtini, 1)-1;
      wrefatu = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
    END

  SUSPEND;
END
^

--Sol. 12021 - Alteração para trazer salário base como valor da remuneração quando não há base de INSS e nem base de INSS 13°, se for contribuinte em situação maternidade - Bruno L. R. - 09/12/2016
--Sol. 17123 - Erro causado pela solicitação 12021. 
--Sol. 146479 - Colocado o campo BDTIPOMOV
/* Restore proc. body: SP_CALC_EXP_SEFIP */
create or alter procedure SP_CALC_EXP_SEFIP (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRCODAUT varchar(20000),
    PRANOMES integer,
    PRANOMESPAG integer,
    PRAGRUPAR integer,
    PRVERIFICARBASE integer = 1)
returns (
    BDMODALIDADE varchar(1),
    BDTERC integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODTPCC integer,
    BDCODCENTRO integer,
    BDANOMESRESC integer,
    BDGRRFPRES integer,
    BDCALCFGTSMESANT varchar(5),
    BDBASEFGTSFOL numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDVALINSS numeric(18,6),
    BDVALINSS13 numeric(18,6),
    BDVALINSSC13 numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSSCALC13 numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDSALFAM numeric(18,6),
    BDVALFGTS numeric(18,6),
    BDVALFGTS13 numeric(18,6),
    BDPERCFGTSCOL numeric(18,6),
    BDBINSSC13 numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSS13DT numeric(18,6),
    BDCONTRCOL integer,
    BDMVCC DM_BOOLEAN,
    BDTEMMODALIDADE0 DM_BOOLEAN,
    BDMOVRESCSEFIP varchar(5),
    BDPISCOL varchar(14),
    BDPISTERC varchar(14),
    BDOCORRENCIACOL integer,
    BDCATEGORIA integer,
    BDDATAADMCOL date,
    BDDIASTRABMES integer,
    BDBASEINSSNMVNOVO numeric(18,6),
    BDTIPOMOV integer)
as
declare variable WTABELA varchar(20000);
declare variable WTIPOFOLHA integer;
declare variable WSQL varchar(30000);
declare variable WCODEMP varchar(20000);
declare variable WCODAUT varchar(20000);
declare variable WAAAAMM varchar(6);
declare variable WGRRFPRES integer;
declare variable WSQLCC varchar(1000);
declare variable WCC150 smallint;
declare variable WCC155 smallint;
declare variable WCC integer;
declare variable WCODSIT integer;
declare variable WTEMMODALIDADE0 smallint;
declare variable WEMPATU integer;
declare variable WSQLSALBASE varchar(500);
declare variable WDATARESC date;
declare variable WDATAINI date;
declare variable WVALAUX numeric(18,6);
declare variable WBASEINSSANTERIOR numeric(18,6);
declare variable WCODSERV integer;
declare variable WTERCMEI varchar(5) collate WIN1252;
BEGIN
--   prcodemp = 'colcon.bdcodemp = 3';
--   pranomes = 201005;
--   pragrupar = 3;
   BDMODALIDADE = ' ';
   SELECT rdb$get_context('USER_SESSION', 'W_TIPOFOLHA') FROM rdb$database INTO wtipofolha;

   IF (wtipofolha IS NULL) THEN
      wtipofolha = 0;

   IF (pranomespag IS NULL) THEN
      pranomespag = pranomes;

   IF (prcodemp IS NULL) THEN
      wcodemp = 'null';
   ELSE
      wcodemp = ''''||prcodemp||'''';

--   if (prcodcol is null) then
--      wcodcol = 'null';
--   else
--      wcodcol = ''''||prcodcol||'''';

   IF (prcodaut IS NULL) THEN
      wcodaut = 'null';
   ELSE
      wcodaut = ''''||prcodaut||'''';

   wsql = ' select * from (';
   IF (wtipofolha <> 1) THEN
      BEGIN
        wsql = wsql||'select 4 CONSTANT,colcon.bdcodemp, colcon.bdcodter,colcon.bdcodtpcc, colcon.bdcodcentro,'||
               '150001 BDCAMPO01,'||
               'null BDCAMPO02, null BDCAMPO03,'||
               '0 BDBASEFGTSFN,'||
               '0 BDBASEFGTS13,'||
               'coalesce(colcon.bdvalorinss,0) BDCAMPO06,'||
               '0 BDCAMPO07,'||
               '0 BDCAMPO23, '||
               'coalesce(colcon.bdbaseinss,0) BDCAMPO08,'||
               '0 BDCAMPO09,'||
               '0 BDCAMPO10,'||
               '0 BDCAMPO11,'||
               '0 BDCAMPO12,'||
               '0 BDCAMPO13,'||
               '0 BDCAMPO14,'||
               '0 BDCAMPO15,'||
               '0 BDCAMPO16,'||
               '0 BDCAMPO17,'||
               '0 BDCAMPO18,'||
               '0 BDCAMPO19,'||
               '0 BDCAMPO20,'||
               '0 BDCAMPO21,'||
               '0 BDCAMPO22,'||
               'cast(null as varchar(5)) BDCAMPO24, '||
               ''''' BDPISCOL, '||
               'tercdoc.BDPISTER, '||
               'colcon.bdocorrenciacol, '||
               'colcon.bdcategoriacol, '||
               'CAST(null as DATE) BDDATAADMCOL, '||
               'CAST(null as DATE) BDDATARESCISAO, '||
               'COLCON.BDBASEINSSNMVNOVO, '||
               'BDCODSERV, ' ||
               'case '||
               'when char_length(TERCDOC.BDCPFMEI) = 14 then '||'''TRUE'''||
               'else '||'''FALSE'''||
               'end TERCMEI, '||
               '0 CAMPO23 '||
               ' from VRHF_SP_TCALC_AUTONOMO('||wcodemp||','||wcodaut||','||pranomes||', null, '||pragrupar||') colcon '||
               ' left outer join VW_VRH_BASE_TTERC_DOC tercdoc on (tercdoc.bdcodter = colcon.bdcodter) ';
--               ' join vw_empresas_usu usu on (colcon.bdcodemp = usu.bdcodemp)';

         wsql = wsql||' union all ';
      END
    
      IF (wtipofolha = 2) THEN
         BEGIN
           wtabela = 'SP_VRHF_FGTSSEFIP_13(';
    
           if (coalesce(prcodemp, '') <> '') then
              begin
                wtabela = wtabela||''''||prcodemp||''',';
    
                if (coalesce(prcodcol, '') <> '') then
                   wtabela = wtabela||''''||prcodcol||''',';
                else
                   wtabela = wtabela||'null,';
              end
           else
              wtabela = wtabela||'null,null,';
    
           wtabela = wtabela||:pranomes||') ';

           IF (prAgrupar = 0) THEN
              begin
                wtabela = 'SP_VRHF_FGTSSEFIP_13_CC(';
         
                if (coalesce(prcodemp, '') <> '') then
                   begin
                     wtabela = wtabela||''''||prcodemp||''',';
         
                     if (coalesce(prcodcol, '') <> '') then
                        wtabela = wtabela||''''||prcodcol||''',';
                     else
                        wtabela = wtabela||'null,';
                   end
                else
                   wtabela = wtabela||'null,null,';
         
                wtabela = wtabela||:pranomes||') ';
              end


         END
      ELSE
      IF (pragrupar = 3) THEN
         begin
           wtabela = 'SP_VRHF_FGTSSEFIP_AGRUPA_3(';

           if (coalesce(prcodemp, '') <> '') then
              begin
                wtabela = wtabela||''''||prcodemp||''',';
    
                if (coalesce(prcodcol, '') <> '') then
                   wtabela = wtabela||''''||prcodcol||''',';
                else
                   wtabela = wtabela||'null,';
              end
           else
              wtabela = wtabela||'null,null,';
    
           wtabela = wtabela||:pranomes||') ';

         end
      ELSE
      IF (pragrupar = 1)  THEN
         begin
           wtabela = 'SP_VRHF_FGTSSEFIP_AGRUPA_1(';

           if (coalesce(prcodemp, '') <> '') then
              begin
                wtabela = wtabela||''''||prcodemp||''',';
    
                if (coalesce(prcodcol, '') <> '') then
                   wtabela = wtabela||''''||prcodcol||''',';
                else
                   wtabela = wtabela||'null,';
              end
           else
              wtabela = wtabela||'null,null,';
    
           wtabela = wtabela||:pranomes||') ';

         end
      ELSE
         begin
           wtabela = 'SP_VRHF_FGTSSEFIP_AGRUPA_CC_MES(';

           if (coalesce(prcodemp, '') <> '') then
              begin
                wtabela = wtabela||''''||prcodemp||''',';
    
                if (coalesce(prcodcol, '') <> '') then
                   wtabela = wtabela||''''||prcodcol||''',';
                else
                   wtabela = wtabela||'null,';
              end
           else
              wtabela = wtabela||'null,null,';
    
           wtabela = wtabela||:pranomes||') ';

         end

    wsql = wsql||' Select '||
                          'case '||
                          '  when COLCON.BDCODGRUPOCLA in (3, 11) then 3 '||
                          '  when COLCON.BDCODGRUPOCLA = 2 then 2 '||
                          '  else 1 '||
                          'end CONSTANT, '||
                          'COLCON.BDCODEMP, '||
                          'COLCON.BDCODCOL, '||
                          'COLCON.BDCODTPCC, '||
                          'COLCON.BDCODCENTRO, '||
                          '  (cast((select BDAAAAMM '||
                          '         from AAAAMM(coalesce(RES.BDDATARESCISAO, cast('||''''||'01/01/1500'||''''||' as date)))) as integer)) BDCAMPO01, '||
                          'PRES.BDGRRFPRES, '||
                          'RES.BDCALCFGTSMESANT, '||
                          'COLCON.BDBASEFGTSFN, '||
                          'COLCON.BDBASEFGTS13, '||
                          'COLCON.BDINSSFN, '||
                          'COLCON.BDINSS13, '||
                          'COLCON.BDINSSC13, '||
                          'COLCON.BDBINSSFN, '||
                          'COLCON.BDBINSS13, '||
                          'COLCON.BDBINSS13R, '||
                          'COLCON.BDSALFAMFN, '||
                          'COLCON.BDFGTSFN, '||
                          'COLCON.BDFGTS13, '||
                          'COLFGTS.BDPERCFGTSCOL, '||
                          'COLCON.BDBINSSC13, '||
                          'COLCON.BDBINSSAPFN, '||
                          'COLCON.BDBINSS13APFN, '||
                          'COLCON.BDINSSAPFN, '||
                          'COLCON.BDINSS13APFN, '||
                          'coalesce(PRES.BDGRRFPRES, 0) BDCAMPO20, '||
                          'COLCON.BDINSS13DT, '||
                          'COLCON.BDCONTRCOL, '||
                          'MOTSEFIP.BDCODSEFMFG, '||
                          'DOCREF.BDPISCOL, '||
                          ''''' BDPISTER, '||
                          'case '||
                          'when (coalesce(COLFGTS.BDCATEGORIAESOCIAL, 0) = 102) then 5 '||
                          'else COLFGTS.BDOCORRENCIACOL '||
                          'end BDOCORRENCIACOL, '||
                          'COLFGTS.BDCATEGORIACOL, '||
                          'COLCON.BDDATAADMCOL, '||
                          'RES.BDDATARESCISAO, '||
                          'COLCON.BDINSSMV, '||
                          '0 BDCODSERV, '||
                          '''FALSE'''||'TERCMEI, '||
                          'PRES.BDTIPOMOV '||
                 ' from ( '||
                          'Select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCONTRCOL, COLCON.BDDATAADMCOL, '||
                          'GRUPOCLA.BDCODGRUPOCLA, TCALC.BDCODTPCC, TCALC.BDCODCENTRO, TCALC.BDBASEFGTSFN, '||
                          'TCALC.BDBASEFGTS13, TCALC.BDINSSFN, TCALC.BDINSS13, TCALC.BDINSSC13, TCALC.BDBINSSFN, '||
                          'TCALC.BDBINSS13, TCALC.BDBINSS13R, TCALC.BDSALFAMFN, TCALC.BDFGTSFN, TCALC.BDFGTS13, '||
                          'TCALC.BDBINSSC13, TCALC.BDBINSSAPFN, TCALC.BDBINSS13APFN, TCALC.BDINSSAPFN, '||
                          'TCALC.BDINSS13APFN, TCALC.BDINSS13DT, TCALC.BDINSSMV '||
                          'from ( '||
                                  'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCONTRCOL, COLCON.BDDATAADMCOL '||
                                  'from VRH_EMP_TCOLCON COLCON ';
                                  IF (prcodemp IS NOT NULL) THEN
                                     wsql = wsql||' where '||prcodemp;
                                
                                  IF (prcodcol IS NOT NULL) THEN
                                     wsql = wsql||' and '||prcodcol;

    wsql = wsql||               ') COLCON '||
                          'join VW_VRH_EMP_TCOLCON_VINC CLA on (COLCON.BDCODEMP = CLA.BDCODEMP and COLCON.BDCODCOL = CLA.BDCODCOL) '||
                          'join VRH_BASE_TCLASSE CLASS on (CLASS.BDCODCLA = CLA.BDCODCLA) '||
                          'join TGRUPOCLASSECOL GRUPOCLA on (CLASS.BDGRUPOCLA = GRUPOCLA.BDCODGRUPOCLA and GRUPOCLA.BDCODGRUPOCLA <> 5) '||
                          'join '||wtabela||' TCALC on (TCALC.BDCODEMP = COLCON.BDCODEMP and TCALC.BDCODCOL = COLCON.BDCODCOL and TCALC.BDREF = '||pranomes||') '||
                       ') COLCON '||
                 'left outer join VRH_EMP_TRESCISAO RES on (COLCON.BDCODEMP = RES.BDCODEMP and COLCON.BDCODCOL = RES.BDCODCOL) '||
                 'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS COLFGTS on (COLCON.BDCODEMP = COLFGTS.BDCODEMP and COLCON.BDCODCOL = COLFGTS.BDCODCOL) '||
                 'left outer join VRH_BASE_TPREPRESC PRES on (PRES.BDCODPRES = RES.BDCODPRES) '||
                 'left outer join VRH_BASE_TMOTFGTS MOTSEFIP on (MOTSEFIP.BDCODMFG = PRES.BDCODMFG) '||
                 'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = COLCON.BDCODEMP and DOCREF.BDCODCOL = COLCON.BDCODCOL) '||
                 'where (not ((COLCON.BDCODGRUPOCLA = 12) and (COLCON.BDCONTRCOL = 1)))';  -- {130346}

    wsql = wsql||') order by BDCODEMP, CONSTANT, BDCAMPO02, BDCAMPO01, bdbasefgtsfn DESC, bdbasefgts13 DESC ';
    wtemmodalidade0 = 0;
    wempatu = 0;
    wcodserv = 0;
    FOR EXECUTE STATEMENT wsql INTO
         :BDTERC,
         :BDCODEMP,
         :BDCODCOL,
         :BDCODTPCC,
         :BDCODCENTRO,
         :BDANOMESRESC,
         :BDGRRFPRES,
         :BDCALCFGTSMESANT,
         :BDBASEFGTSFOL,
         :BDBASEFGTS13,
         :BDVALINSS,
         :BDVALINSS13,
         :BDVALINSSC13,
         :BDBASEINSS,
         :BDBASEINSSCALC13,
         :BDBASEINSS13,
         :bdsalfam,
         :bdvalfgts,
         :bdvalfgts13,
         :BDPERCFGTSCOL,
         :BDBINSSC13,
         :BDBINSSAPFN,
         :BDBINSS13APFN,
         :BDINSSAPFN,
         :BDINSS13APFN,
         :wgrrfpres,
         :bdinss13dt,
         :BDCONTRCOL,
         :BDMOVRESCSEFIP,
         :BDPISCOL,
         :BDPISTERC,
         :BDOCORRENCIACOL,
         :BDCATEGORIA,
         :BDDATAADMCOL,
         :wdataresc,
         :BDBASEINSSNMVNOVO,
         :wcodserv,
         :wtercmei,
         :BDTIPOMOV
  DO
  BEGIN
    IF (wempatu <> BDCODEMP) THEN
       BEGIN
         wempatu = BDCODEMP;
         wtemmodalidade0 = 0;
       END

    IF (BDBASEFGTSFOL IS NULL) THEN
       BDBASEFGTSFOL = 0;
    IF (BDBASEFGTS13 IS NULL) THEN
       BDBASEFGTS13 = 0;
    IF (BDVALINSS IS NULL) THEN
       BDVALINSS = 0;
    IF (BDVALINSS13 IS NULL) THEN
       BDVALINSS13 = 0;
    IF (BDBASEINSS IS NULL) THEN
       BDBASEINSS = 0;
    IF (BDBASEINSSCALC13 IS NULL) THEN
       BDBASEINSSCALC13 = 0;
    IF (BDBASEINSS13 IS NULL) THEN
       BDBASEINSS13 = 0;
    IF (bdvalfgts IS NULL) THEN
       bdvalfgts = 0;
    IF (bdvalfgts13 IS NULL) THEN
       bdvalfgts13 = 0;
    IF (bdpercfgtscol IS NULL) THEN
       bdpercfgtscol = 0;
    IF (bdbinssapfn IS NULL) THEN
       bdbinssapfn = 0;
    IF (bdbinss13apfn IS NULL) THEN
       bdbinss13apfn = 0;
    IF (bdinssapfn IS NULL) THEN
       bdinssapfn = 0;
    IF (bdinss13apfn IS NULL) THEN
       bdinss13apfn = 0;
    IF (bdinss13DT IS NULL) THEN
       bdinss13DT = 0;

    IF (SUBSTRING(pranomes FROM 5 FOR 2) = '12') THEN
       waaaamm = CAST((CAST((SUBSTRING(pranomes FROM 1 FOR 4)) AS INTEGER) + 1) AS VARCHAR(4))||'01';
    ELSE
       BEGIN
         IF (CAST((SUBSTRING(pranomes FROM 5 FOR 2)) AS INTEGER) < 9) THEN
            waaaamm = SUBSTRING(pranomes FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(pranomes FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(1));
         ELSE
            waaaamm = SUBSTRING(pranomes FROM 1 FOR 4)||CAST((CAST((SUBSTRING(pranomes FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(2));
       END

    IF ((bdterc = 1) AND ((pragrupar IS NULL) OR (pragrupar = 0) OR (pragrupar = 3))) THEN
      BEGIN
        wcc150 = 0;
        wcc155 = 0;
        wCC = 0;
        wsqlcc = 'select COALESCE(CC.BDTIPOTOM,0) from VRHF_EMP_TFOLHATOMADOR X '||
                 'join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = X.BDCODEMP and PFN.BDCODCOL = X.BDCODCOL and PFN.BDORDEM = X.BDORDEM) '||
                 'join VRH_BASE_TCUSTOM CC on (CC.BDCODCENTRO = PFN.BDCODCENTRO and CC.BDCODTPCC = PFN.BDCODTPCC) '||
                 'where X.BDCODEMP = '||bdcodemp||' and X.BDCODCOL = '||bdcodcol||' and X.BDREFTOMADOR = '||pranomes;
        FOR EXECUTE STATEMENT wsqlcc INTO :wcc DO
          BEGIN
            IF (wcc = 0) THEN
              wcc155 = wcc155 + 1;
            IF (wcc > 0) THEN
              wcc150 = 1;
          END

        IF ((wcc150 = 1 AND wcc155 >= 1) OR (wcc155 > 1)) THEN
          BDMVCC = 'TRUE';
        ELSE
          BDMVCC = 'FALSE';
      END
    ELSE
      BDMVCC = 'FALSE';

    IF (((BDBASEFGTSFOL <> 0) OR (BDBASEFGTS13 <> 0)) AND ((BDMOVRESCSEFIP IS NULL) OR (BDMOVRESCSEFIP <> 'I1' AND BDMOVRESCSEFIP <> 'I2' AND BDMOVRESCSEFIP <> 'I3' AND BDMOVRESCSEFIP <> 'I4' AND BDMOVRESCSEFIP <> 'I5' AND BDMOVRESCSEFIP <> 'L'))) THEN
       wtemmodalidade0 = 1;

    IF (wtemmodalidade0 = 0 AND CAST(waaaamm AS INTEGER) = BDANOMESRESC AND UPPER(BDCALCFGTSMESANT) = 'TRUE' AND wgrrfpres <> 0) THEN
       BEGIN
         IF (wtemmodalidade0 = 0) THEN
            BDMODALIDADE = 1;
         --BDBASEFGTSFOL = 0;
         --BDBASEFGTS13 = 0;
       END
    ELSE
       BDMODALIDADE = ' ';


    --Sol. 12021 - Bruno L. R. - 06/12/2016
    /*if (BDBASEFGTSFOL = 0 AND BDBASEFGTS13 = 0) then
       BEGIN
         wcodsit = null;
         wsqlcc = 'select first 1 BDCODSIT from VRH_EMP_TSITCOL where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and '||pranomes||' >= '||
                'SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) and '||pranomes||' <= '||
                'SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) '; 
         execute statement wsqlcc into :wcodsit;

         if (wcodsit is not null and wcodsit <> 0) then
            wtemmodalidade0 = 1;
       END */

    IF (wtemmodalidade0 = 1) THEN
       BDTEMMODALIDADE0 = 'TRUE';
    ELSE
       BDTEMMODALIDADE0 = 'FALSE';

    IF (BDBASEINSS = 0 AND BDBASEINSS13 = 0) THEN
       BEGIN
         wcodsit = NULL;
         /*wsqlcc = 'select first 1 BDCODSIT from VRH_EMP_TSITCOL where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and ((SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||'||
                  'SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) = '||pranomes||') or (((BDDATAFIMSIT is not null) and '||
                  '(SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2)= '||pranomes||')))) '; */

         --Sol. 12021 - Bruno L. R. - 09/12/2016
         wsqlcc = 'select first 1 X.BDCODSIT from VRH_EMP_TSITCOL X join VRH_EMP_TCOLCON Y on (Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL) '||
                -- Sol. 17123 Denicio 01/02/2017 
                'join VRH_BASE_TPREPSIT Z on (Z.BDCODSIT = X.BDCODSIT) '||
                'join VRH_BASE_TMOTFGTS W on (W.BDCODMFG = Z.BDCODMFGENT) '||
                'where X.BDCODEMP = '||BDCODEMP||' and X.BDCODCOL = '||BDCODCOL||' and '||pranomes||' >= '||
                'SUBSTRING(CAST(X.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(X.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) and '||pranomes||' <= '||
                'SUBSTRING(CAST(X.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(X.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) and Y.BDCONTRCOL = 1 '||
                -- Sol. 17123 Denicio 01/02/2017 
                'and UPPER(SUBSTRING(W.BDCODSEFMFG from 1 for 1)) = ''Q''';
         EXECUTE STATEMENT wsqlcc INTO :wcodsit;

         IF (wcodsit IS NOT NULL AND wcodsit <> 0 AND wcodsit <> 30) THEN
            BEGIN
              WSQLSALBASE = 'select BDSALBASEFN from VRHF_EMP_TFOLHANORMAL where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFFN = '||pranomes;
              EXECUTE STATEMENT WSQLSALBASE INTO :BDBASEINSS;

              --Sol. 17123 - Denicio 01/02/2017. 
              IF ((BDBASEINSS IS NULL) OR (BDBASEINSS = 0) ) THEN
                 BEGIN
                   WSQLSALBASE = 'select first 1 BDSALBASEFT from VRHF_EMP_TFOLHATOMADOR where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFTOMADOR = '||pranomes;
                   EXECUTE STATEMENT WSQLSALBASE INTO :BDBASEINSS;
                 END
            END
         --Sol. 12021 - Bruno L. R. - 09/12/2016
       END


    if ((BDTERC = 4) and (WTERCMEI = 'FALSE')) then
       begin
         wvalaux = null;
         select sum(MVINC.BDBASEINSSNTER)
         from VRHF_BASE_TTERC_MVINC MVINC
         join TEMPRESAS EMP on (EMP.BDCODEMP = MVINC.BDCODEMP)
         where MVINC.BDCODEMP = :BDCODEMP and MVINC.BDCODTER = :BDCODCOL and MVINC.BDREFTERC <= :pranomes and
               ((coalesce(MVINC.BDREFTERCFIM, 0) = 0) or (coalesce(MVINC.BDREFTERCFIM, 0) >= :pranomes)) and
               ((SUBSTRING(EMP.BDCNPJEMP FROM 1 FOR 10) <> SUBSTRING(MVINC.BDCNPJRESP FROM 1 FOR 10)))
         into :wvalaux;
         wvalaux = coalesce(wvalaux, 0);

         if (wvalaux <> 0) then
           begin
            BDBASEINSS = :BDBASEINSSNMVNOVO - wvalaux;
           end

            if (wcodserv <> 0) then
              begin
                SELECT SUM(BDBASEINSS) as BASEINSS
                FROM (SELECT TERC.BDBASEINSS BDBASEINSS
                      FROM VRHF_BASE_CALC_TERC TERC
                      WHERE TERC.BDCODEMP = :BDCODEMP AND  TERC.BDCODTER = :BDCODCOL AND TERC.BDCODSERV < :WCODSERV AND TERC.BDREFINSSSERV = :PRANOMES
                      GROUP BY TERC.BDBASEINSS)
                into :wbaseinssanterior;

                wbaseinssanterior     = coalesce(wbaseinssanterior , 0);

                if ((wbaseinssanterior <> 0) and (wvalaux <> 0)) then
                  begin
                    BDBASEINSS = BDBASEINSS - wbaseinssanterior;
                  end
              end
           if (BDBASEINSS < 0) then
              BDBASEINSS = 0;

       end
    else
    if (BDTERC = 2) then
       begin
         wvalaux = null;
         select sum(MVINC.BDBASEINSSNCOL)
         from VRHF_EMP_TCOLCON_MVINC MVINC
         join TEMPRESAS EMP on (EMP.BDCODEMP = MVINC.BDCODEMP)
         where MVINC.BDCODEMP = :BDCODEMP and MVINC.BDCODCOL = :BDCODCOL and MVINC.BDREFCOL <= :pranomes and
               ((coalesce(MVINC.BDREFFIM, 0) = 0) or (coalesce(MVINC.BDREFFIM, 0) >= :pranomes)) and (MVINC.BDTIPOCALC = 0) and
               ((SUBSTRING(EMP.BDCNPJEMP FROM 1 FOR 10) <> SUBSTRING(MVINC.BDCNPJRESP FROM 1 FOR 10)))
         into :wvalaux;
         wvalaux = coalesce(wvalaux, 0);

         if (wvalaux <> 0) then
           BDBASEINSS = :BDBASEINSSNMVNOVO - wvalaux;

         if (BDBASEINSS < 0) then
            BDBASEINSS = 0;
       end


    BDDIASTRABMES = 30;
    -- Admissão dentro do ano
    if (BDDATAADMCOL < CAST(('01-01-'||SUBSTRING(:pranomes FROM 1 FOR 4)) AS DATE)) then
       wdataini = CAST(('01-01-'||SUBSTRING(:pranomes FROM 1 FOR 4)) AS DATE);
    else
       wdataini = BDDATAADMCOL;

    if (wdataresc is not null and SUBSTRING(CAST(:wdataini AS VARCHAR(10)) FROM 1 FOR 4) = SUBSTRING(:pranomes FROM 1 FOR 4)) then
       BDDIASTRABMES = wdataresc - wdataini + 1;

    IF ((PRVERIFICARBASE <> 1) OR (BDBASEFGTSFOL <> 0) OR (BDBASEFGTS13 <> 0) OR (BDBASEINSS <> 0) OR (BDBASEINSSCALC13 <> 0) OR (BDBASEINSS13 <> 0)) THEN
       SUSPEND;
    else
    IF ((BDBASEFGTSFOL = 0) AND (BDBASEFGTS13 = 0) AND (BDBASEINSS = 0) AND (BDBASEINSSCALC13 = 0) AND (BDBASEINSS13 = 0) AND (TRIM(BDMOVRESCSEFIP) <> '')) THEN
       SUSPEND;
  END
END^


--Sol. 17685 - Bruno L. R. - 06/07/2017 - Adicionado o nome BDDATAGRRF como nome da coluna 30, pois fazia um sub-select e tentava trazer os dados para uma coluna sem nome 
/* Restore proc. body: SP_CALC_EXP_SEFIP_COMPLEMENTAR */
create or alter procedure SP_CALC_EXP_SEFIP_COMPLEMENTAR (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRCODAUT varchar(20000),
    PRANOMES integer,
    PRANOMESFIM integer,
    PRANOMESPAG integer,
    PRAGRUPAR integer,
    PRTIPOFC integer = 1,
    PRCODREC integer = 0)
returns (
    BDMODALIDADE varchar(20),
    BDTERC integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODTPCC integer,
    BDCODCENTRO integer,
    BDANOMESRESC integer,
    BDGRRFPRES integer,
    BDCALCFGTSMESANT varchar(5),
    BDBASEFGTSFOL numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDVALINSS numeric(18,6),
    BDVALINSS13 numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSSCALC13 numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDSALFAM numeric(18,6),
    BDVALFGTS numeric(18,6),
    BDVALFGTS13 numeric(18,6),
    BDPERCFGTSCOL numeric(18,6),
    BDVALINSSFC numeric(18,6),
    BDVALINSS13FC numeric(18,6),
    BDBINSSC13 numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSS13DT numeric(18,6),
    BDVALINSSC13 numeric(18,6),
    BDTEMMODALIDADE0 DM_BOOLEAN,
    BDMOVRESCSEFIP varchar(5),
    BDPISCOL varchar(14),
    BDPISTERC varchar(14),
    BDOCORRENCIACOL integer,
    BDCATEGORIA integer,
    BDDATAADMCOL date,
    BDDIASTRABMES integer,
    BDTIPOMOV integer,
    BDTIPOFOL integer,
    BDDTACCONV date,
    BDREFFN integer)
as
declare variable WMODALIDADE integer;
declare variable WSQL varchar(30000);
declare variable WPARFOLHANORMAL varchar(30000);
declare variable WPARCOMPANT varchar(30000);
declare variable WPARCOMPATU varchar(30000);
declare variable WTEMMODALIDADE0 smallint;
declare variable WREFFC integer;
declare variable WBFGTSIND numeric(15,6);
declare variable WDATAGRRF date;
declare variable WBFGTSSEFIP numeric(18,6);
declare variable WCATEGORIAESOCIAL integer;
declare variable WCATEGORIAESOCIALAUX integer;
declare variable WCOLANT integer;
declare variable WEMPANT integer;
declare variable WTPFOLANT integer;
BEGIN
  WEMPANT = 0;
  WCOLANT = 0;
  WTPFOLANT = -1;

--   prcodemp = 'colcon.bdcodemp = 3';
--   pranomes = 201003;
--   pragrupar = 3;
  BDINSS13DT = 0;

   IF (prcodemp IS NULL) THEN
      BEGIN
        wparfolhanormal = 'null,';
        wparcompant = 'null,';
        wparcompatu = 'null,';
      END
   ELSE
      BEGIN
        wparfolhanormal = ''''||prcodemp||''''||',';
        wparcompant = ''''||prcodemp||''''||',';
        wparcompatu = ''''||prcodemp||''''||',';
      END

   IF (prcodcol IS NULL) THEN
      BEGIN
        wparfolhanormal = wparfolhanormal||'null,';
        wparcompant = wparcompant||'null,';
        wparcompatu = wparcompatu||'null,';
      END
   ELSE
      BEGIN
        wparfolhanormal = wparfolhanormal||''''||prcodcol||''''||',';
        wparcompant = wparcompant||''''||prcodcol||''''||',';
        wparcompatu = wparcompatu||''''||prcodcol||''''||',';
      END

   /* Autônomos */
   IF (prcodaut IS NULL) THEN
     wparfolhanormal = wparfolhanormal||'null,';
   ELSE
     wparfolhanormal = wparfolhanormal||''''||prcodaut||''''||',';

   /*pranomes*/
   wparfolhanormal = wparfolhanormal||pranomes||',';

   /*pranomes pranomesfim*/
   wparcompant = wparcompant||pranomes||','||pranomesfim||',';
   wparcompatu = wparcompatu||pranomes||','||pranomesfim||',';

   /*pranomespag*/
   IF (pranomespag IS NULL) THEN
      pranomespag = pranomes;
   wparfolhanormal = wparfolhanormal||pranomespag||',';

   -- deve trazer todos os pagamentos ate o mes anterior
   IF (SUBSTRING(pranomespag FROM 5 FOR 2) = '01') THEN
     wparcompant = wparcompant||pranomes||','||(CAST(SUBSTRING(pranomespag FROM 1 FOR 4) AS INTEGER) - 1)||'12'||',';
   ELSE
     wparcompant = wparcompant||pranomes||','||(pranomespag-1)||',';

   wparcompatu = wparcompatu||pranomespag||',null,'; -- deve trazer apenas o pagamento do mes atual

   /* pragrupar */
   IF (pragrupar IS NULL) THEN
     BEGIN
       wparfolhanormal = wparfolhanormal||'0';
       wparcompant = wparcompant||'0';
       wparcompatu = wparcompatu||'0';
     END
   ELSE
     BEGIN
   wparfolhanormal = wparfolhanormal||pragrupar;
   wparcompant = wparcompant||pragrupar;
   wparcompatu = wparcompatu||pragrupar;
     END

   /* tipo folha complementar */
   wparcompant = wparcompant||','||prtipofc;
--   wparcompatu = wparcompatu||','||prtipofc;
   wparcompatu = wparcompatu||','||'0';
   wparcompatu = wparcompatu||',0,null,0,null,1';

   WCATEGORIAESOCIALAUX = 0;
   /* categoria eSocial auxiliar */
   if (prcodcol is not null) then
     begin
       EXECUTE STATEMENT 'select first 1 BDCATEGORIAESOCIAL from VW_VRHF_EMP_TCOLCON_FGTSGPS colcon ' ||
                     'where ' || prcodemp || ' and ' || prcodcol || ' and colcon.bdrefcol = ' || pranomes
       INTO :WCATEGORIAESOCIALAUX;
     end

   BDVALINSSFC = 0;
   bdvalinss13fc = 0;

   wsql = 'select * from (';
   IF (PRTIPOFC = 1) THEN
      BEGIN
         wsql = wsql||
                'select 9 BDMODALIDADE, base.bdterc, base.bdcodemp, base.bdcodcol, base.bdcodtpcc, base.bdcodcentro, max(base.bdanomesresc) bdanomesresc, max(base.bdgrrfpres) bdgrrfpres,'||
                     'max(base.bdcalcfgtsmesant) bdcalcfgtsmesant, sum(base.bdbasefgtsfol) bdbasefgtsfol, sum(base.bdbasefgts13) bdbasefgts13, sum(base.bdvalinss) bdvalinss, sum(base.bdvalinss13) bdvalinss13,'||
                     'sum(base.bdbaseinss) bdbaseinss, sum(base.bdbaseinsscalc13) bdbaseinsscalc13, sum(base.bdbaseinss13) bdbaseinss13, sum(base.bdsalfam) bdsalfam, sum(base.bdvalfgts) bdvalfgts, sum(base.bdvalfgts13) bdvalfgts13, '||
                     'max(COLFGTS.BDPERCFGTSCOL) BDPERCFGTSCOL , 0 bdvalinssfc, 0 bdvalinss13fc, sum(base.bdbinssapfn) bdbinssapfn, sum(base.bdbinss13apfn) bdbinss13apfn, sum(base.bdinssapfn) bdinssapfn, sum(base.bdinss13apfn) bdinss13apfn, '||
                     '0 BDVALINSSC13, base.bdreffc, base.BDMOVRESCSEFIP,colcon_cad.bdcpfcol bdpiscol, '''' BDPISTERC, max(COALESCE(COLFGTS.bdocorrenciacol,0)) bdocorrenciacol, '||
                     'max(COALESCE(COLFGTS.bdcategoriacol,0)) bdcategoriacol, max(COALESCE(COLFGTS.bdcategoriaesocial,0)) bdcategoriaesocial, max(base.BDDATAGRRF) BDDATAGRRF, max(colcon_cad.BDDATAADMCOL) BDDATAADMCOL, '||
                     'base.BDTIPOMOV, 0 BDTIPOFOL, ''01/01/1900'' BDDTACCONV, 0 BDREFFN '||        -- 168294 Leonardo 06/09/2022
                'from ('||
                     ' select x.bdterc, x.bdcodemp, x.bdcodcol, x.bdcodtpcc, x.bdcodcentro, x.bdanomesresc,'||
                            ' COALESCE(x.bdgrrfpres,0) bdgrrfpres, x.bdcalcfgtsmesant, x.bdbasefgtsfol, x.bdbasefgts13, x.bdvalinss,'||
                            ' x.bdvalinss13, x.bdbaseinss, x.bdbaseinsscalc13, x.bdbaseinss13, x.bdsalfam, x.bdvalfgts, x.bdvalfgts13, x.bdbinssapfn, x.bdbinss13apfn,'||
                            ' x.bdinssapfn, x.bdinss13apfn, '||pranomes||' BDREFFC, x.BDMOVRESCSEFIP, CAST(null as DATE) BDDATAGRRF, '||
                            ' X.BDTIPOMOV '||                    -- 168294 Leonardo 06/09/2022
                     ' from sp_calc_exp_sefip('||wparfolhanormal||',0) x'||
                     ' union all '||
                     ' select case when GCLA.BDCODGRUPOCLA in (3,11) then 3 when GCLA.BDCODGRUPOCLA = 2 then 2 else 1 end, y.bdcodemp, y.bdcodcol, y.bdcodtpcc, y.bdcodcentro, -1, -1, ''FALSE'', coalesce(y.BDBFGTSFC,0),'||
                            ' coalesce(y.BDBFGTS13FC,0), coalesce(y.BDINSSFC,0), coalesce(y.BDINSS13FC,0), coalesce(y.BDBINSSFC,0),'||
                            ' 0, coalesce(y.BDBINSS13FC,0), coalesce(y.BDSALFAMFC,0), coalesce(y.BDFGTSFC,0), coalesce(y.BDFGTS13FC,0), '||
                            ' coalesce(y.bdbinssapfc,0), coalesce(y.bdbinss13apfc,0), coalesce(y.bdinssapfc,0), coalesce(y.bdinss13apfc,0), Y.BDREFFC, cast(null as varchar(5)), y.BDDATAGRRF, '||
                            ' PRES.BDTIPOMOV '||                     -- 168294 Leonardo 06/09/2022
                     ' from vrhf_sp_tfolhacomp('||wparcompant||') y '||
                     ' left outer join VW_VRH_EMP_TCOLCON_VINC COLVINC on (COLVINC.BDCODEMP = y.bdcodemp and COLVINC.BDCODCOL = y.bdcodcol) '||
                     ' left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = COLVINC.BDCODCLA) '||
                     ' left outer join TGRUPOCLASSECOL GCLA on (GCLA.BDCODGRUPOCLA = CLA.BDGRUPOCLA) '||
                     ' left outer join VRH_EMP_TCOLCON colcon_cad on (colcon_cad.BDCODEMP = y.BDCODEMP and colcon_cad.BDCODCOL = y.BDCODCOL) '||  -- {130346}
                     ' left outer join VRH_EMP_TRESCISAO RES on (Y.BDCODEMP = RES.BDCODEMP and Y.BDCODCOL = RES.BDCODCOL and Y.BDREFFN = RES.BDREFRESCISAO) '||  -- 168294 Leonardo 06/09/2022
                     ' left outer join VRH_BASE_TPREPRESC PRES on (PRES.BDCODPRES = RES.BDCODPRES) '||                                                           -- 168294 Leonardo 06/09/2022
                     ' where (not ((GCLA.BDCODGRUPOCLA = 12) and (colcon_cad.BDCONTRCOL = 1))) '||
                ') base'||
                ' left outer join vw_vrhf_emp_tcolcon_fgtsgps COLFGTS on (BASE.BDCODEMP = COLFGTS.BDCODEMP and BASE.BDCODCOL = COLFGTS.BDCODCOL) '||
                ' left outer join vw_vrh_emp_tcolcon_docref DOCREF on (DOCREF.bdcodemp = base.bdcodemp and DOCREF.bdcodcol = base.bdcodcol) '||
                ' left outer join VRH_EMP_TCOLCON colcon_cad on (colcon_cad.BDCODEMP = base.BDCODEMP and colcon_cad.BDCODCOL = base.BDCODCOL) '||
                ' where not exists('||
                        'select z.BDCODEMP, z.BDCODCOL , z.bdcodtpcc '||
                        'from vrhf_sp_tfolhacomp('||wparcompatu||') z '||
                        'where z.BDCODEMP = base.BDCODEMP and z.BDCODCOL = base.BDCODCOL and coalesce(z.bdcodtpcc,0) = coalesce(base.bdcodtpcc,0)'||
                ')'||
                ' group by bdterc, bdcodemp, bdcodcol, bdcodtpcc, bdcodcentro, bdreffc, BDMOVRESCSEFIP, bdpiscol, BASE.BDTIPOMOV '||
                ' union all ';
      END

   wsql = wsql||
          ' select 0 BDMODALIDADE, case when GCLA.BDCODGRUPOCLA in (3,11) then 3 when GCLA.BDCODGRUPOCLA = 2 then 2 else 1 end bdTERC, y.bdcodemp, y.bdcodcol, y.bdcodtpcc, '||
               'y.bdcodcentro, res.bdrefrescisao bdanomesresc, COALESCE(pres.bdgrrfpres,0) bdgrrfpres, ''FALSE'' bdcalcfgtsmesant, coalesce(y.BDBFGTSFC,0) bdbasefgtsfol,'||
               ' coalesce(y.BDBFGTS13FC,0) bdbasefgts13, coalesce(y.BDINSSFC,0) ';

  IF (PRCODREC <> 650) THEN
     wsql = wsql||' + coalesce(fb.bdvalinss,0) + coalesce(Y.BDINSS13FC, 0) ';

   wsql = wsql||'bdvalinss, coalesce(y.BDINSS13FC,0) ';

  IF (PRCODREC <> 650) THEN
      wsql = wsql||' + coalesce(fb.bdvalinss13,0) ';

   wsql = wsql||'bdvalinss13, coalesce(y.BDBINSSFC,0) ';

  IF (PRCODREC <> 650) THEN
     wsql = wsql||' + coalesce(fb.bdbaseinss,0) ';

  IF (PRCODREC <> 650) THEN
     wsql = wsql||'bdbaseinss, coalesce(fb.BDBASEINSSCALC13, 0) ';
  ELSE
     wsql = wsql||'bdbaseinss, 0 ';

  wsql = wsql||'bdbaseinsscalc13, coalesce(y.BDBINSS13FC,0) ';

  IF ((PRCODREC <> 650) and (not wcategoriaesocialaux in (107, 108))) THEN
      wsql = wsql||' + coalesce(fb.bdbinss13,0) ';

  wsql = wsql||'bdbaseinss13, coalesce(y.BDSALFAMFC,0) bdsalfam, coalesce(y.BDFGTSFC,0) bdvalfgts, coalesce(y.BDFGTS13FC,0) bdvalfgts13, 0 BDPERCFGTSCOL, coalesce(y.BDINSSFC,0) bdvalinssfc, coalesce(y.BDINSS13FC,0) bdvalinss13fc';


  wsql = wsql||', coalesce(y.bdbinssapfc,0) ';
  IF (PRCODREC <> 650) THEN
     wsql = wsql||' + coalesce(fb.bdbinssapfn,0) ';

  wsql = wsql||'bdbinssapfn, coalesce(y.bdbinss13apfc,0) ';
  IF (PRCODREC <> 650) THEN
     wsql = wsql||' + coalesce(fb.bdbinss13apfn,0) ';

  wsql = wsql||'bdbinss13apfn, coalesce(y.bdinssapfc,0) ';
  IF (PRCODREC <> 650) THEN
     wsql = wsql||' + coalesce(fb.bdinssapfn,0) ';

  wsql = wsql||'bdinssapfn, coalesce(y.bdinss13apfc,0) ';
  IF (PRCODREC <> 650) THEN
     wsql = wsql||' + coalesce(fb.bdinss13apfn,0) ';

  wsql = wsql||'bdinss13apfn, 0 ';
  IF (PRCODREC <> 650) THEN
     wsql = wsql||' + coalesce(fb.BDVALINSSC13,0) ';

  wsql = wsql||'BDVALINSSC13, y.bdreffc, motsefip.BDCODSEFMFG, colcon_cad.bdcpfcol BDPISCOL, '''' BDPISTERC, COLFGTS.bdocorrenciacol, '||
               'COLFGTS.bdcategoriacol, COLFGTS.bdcategoriaesocial, COALESCE(y.BDDATAGRRF, y.BDDATAPAGFC) BDDATAGRRF, colcon_cad.BDDATAADMCOL, '||
               'pres.BDTIPOMOV, 1 BDTIPOFOL, y.bddtacconv, Y.BDREFFN';         -- 168294 Leonardo 06/09/2022

  wsql = wsql||' from vrhf_sp_tfolhacomp('||wparcompatu||') y '||
               ' left outer join vw_vrhf_emp_tcolcon_fgtsgps COLFGTS on (y.BDCODEMP = COLFGTS.BDCODEmP and y.BDCODCOL = COLFGTS.BDCODCOL) '||
               ' left outer join vw_vrh_emp_tcolcon_docref DOCREF on (DOCREF.bdcodemp = y.bdcodemp and DOCREF.bdcodcol = y.bdcodcol) '||
--               ' left outer join vrh_emp_trescisao res on (y.bdcodemp = res.bdcodemp and y.bdcodcol = res.bdcodcol and res.bdrefrescisao <= y.bdreffn) '||
--               ' left outer join vrh_emp_trescisao res on (y.bdcodemp = res.bdcodemp and y.bdcodcol = res.bdcodcol) '||
               ' left outer join vrh_emp_trescisao res on (y.bdcodemp = res.bdcodemp and y.bdcodcol = res.bdcodcol  AND Y.BDREFFN = RES.BDREFRESCISAO) '||  -- Sol.154499 Leonardo Schwab 25/04/2022
               ' left outer join vrh_base_tprepresc pres on (pres.bdcodpres = res.bdcodpres) '||
               ' left outer join VRH_BASE_TMOTFGTS motsefip on (motsefip.bdcodmfg = pres.bdcodmfg) '||
               ' left outer join VW_VRH_EMP_TCOLCON_VINC COLVINC on (COLVINC.BDCODEMP = y.bdcodemp and COLVINC.BDCODCOL = y.bdcodcol) '||
               ' left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = COLVINC.BDCODCLA) '||
               ' left outer join TGRUPOCLASSECOL GCLA on (GCLA.BDCODGRUPOCLA = CLA.BDGRUPOCLA) '||
               ' left outer join VRH_EMP_TCOLCON colcon_cad on (colcon_cad.BDCODEMP = y.BDCODEMP and colcon_cad.BDCODCOL = y.BDCODCOL) ';

--               ' left outer join (select bdcodemp,bdcodcol,bdcodtpcc, bdcodcentro, sum(bdbaseinssfn) bdbaseinss,sum(bdbaseinss13) bdbinss13, sum(bdvalinss) bdvalinss, sum(bdvalinss13) bdvalinss13 from ('||

  IF (PRCODREC <> 650) THEN
     BEGIN
       wsql = wsql||
                   ' left outer join (select bdcodemp,bdcodcol,bdcodtpcc, bdcodcentro, sum(bdbaseinssfn) bdbaseinss,sum(bdbaseinss13) bdbinss13, sum(bdvalinss) bdvalinss, sum(bdvalinss13) bdvalinss13, sum(bdbinssapfn) bdbinssapfn, sum(bdbinss13apfn) bdbinss13apfn, sum(bdinssapfn) bdinssapfn, sum(bdinss13apfn) bdinss13apfn, sum(bdbaseinsscalc13) bdbaseinsscalc13, sum(bdvalinssc13) bdvalinssc13 from ('||
                   '         select k.bdcodemp,k.bdcodcol,k.bdcodtpcc, k.bdcodcentro, coalesce(k.bdbaseinss,0) bdbaseinssfn,k.bdbaseinss13, coalesce(k.bdvalinss,0) bdvalinss, coalesce(K.BDVALINSS13, 0) BDVALINSS13, '||
                                   'coalesce(k.bdbinssapfn,0) bdbinssapfn, coalesce(k.bdbinss13apfn,0) bdbinss13apfn, coalesce(k.bdinssapfn,0) bdinssapfn, coalesce(k.bdinss13apfn,0) bdinss13apfn, coalesce(k.bdbaseinsscalc13, 0) bdbaseinsscalc13, coalesce(K.BDVALINSSC13, 0) BDVALINSSC13  '||
                   '         from sp_calc_exp_sefip('||wparfolhanormal||',0) k '||
                   '         union all '||
                   '         select s.bdcodemp,s.bdcodcol, s.bdcodtpcc, s.bdcodcentro, coalesce(s.bdbinssfc,0)+coalesce(s.bdbinssfefolfc,0) bdbaseinssfn,s.bdbinss13fc, coalesce(s.bdinssfc,0)+coalesce(s.bdinssfefolfc,0),coalesce(s.BDINSS13FC,0), '||
                                   'coalesce(s.bdbinssapfc,0), coalesce(s.bdbinss13apfc,0), coalesce(s.bdinssapfc,0), coalesce(s.bdinss13apfc,0), 0 bdbaseinsscalc13, 0 BDVALINSSC13 '||
                   '         from vrhf_sp_tfolhacomp('||wparcompant||') s '||
                   '         ) group by bdcodemp,bdcodcol, bdcodtpcc, bdcodcentro) fb '||
                   '              on (y.bdcodemp = fb.bdcodemp and fb.bdcodcol = y.bdcodcol and '||
                   '               (fb.bdcodtpcc = y.bdcodtpcc or (fb.bdcodtpcc is null and y.bdcodtpcc is null) ) and '||
                   '               (fb.bdcodcentro = y.bdcodcentro or (fb.bdcodcentro is null and y.bdcodcentro is null) )) ';
    END

    wsql = wsql||' where (not ((GCLA.BDCODGRUPOCLA = 12) and (colcon_cad.BDCONTRCOL = 1))) ';  -- {130346}
    IF (prtipofc > 1) THEN
       BEGIN
         wsql = wsql||' and y.BDCODTIPOFC = '||prtipofc;
       END

    wsql = wsql||') order by BDCODEMP, BDCODCOL, BDMODALIDADE, BDTERC, BDGRRFPRES, BDANOMESRESC ';


    SELECT rdb$get_context('USER_SESSION', 'W_TIPOFOLHA') FROM rdb$database INTO wparcompatu;

    SELECT rdb$set_context('USER_SESSION', 'W_TIPOFOLHA', '0') FROM rdb$database INTO wparcompant;
    wtemmodalidade0 = 0;
    FOR EXECUTE STATEMENT wsql INTO
         : wmodalidade,
         : BDTERC,
         : BDCODEMP,
         : BDCODCOL,
         : BDCODTPCC,
         : BDCODCENTRO,
         : BDANOMESRESC,
         : BDGRRFPRES,
         : BDCALCFGTSMESANT,
         : BDBASEFGTSFOL,
         : BDBASEFGTS13,
         : BDVALINSS,
         : BDVALINSS13,
         : BDBASEINSS,
         : BDBASEINSSCALC13,
         : BDBASEINSS13,
         : bdsalfam,
         : bdvalfgts,
         : bdvalfgts13,
         : BDPERCFGTSCOL,
         : bdvalinssfc,
         : bdvalinss13fc,
         : BDBINSSAPFN,
         : BDBINSS13APFN,
         : BDINSSAPFN,
         : BDINSS13APFN,
         : BDVALINSSC13,
         : wreffc,
         : BDMOVRESCSEFIP,
         : BDPISCOL,
         : BDPISTERC,
         : BDOCORRENCIACOL,
         : BDCATEGORIA,
         : wcategoriaesocial,
         : wdatagrrf,
         : BDDATAADMCOL,
         : BDTIPOMOV,                                      -- 168294 Leonardo 06/09/2022
         : BDTIPOFOL,
         : bddtacconv,
         : bdreffn
  DO
  BEGIN
    BDDIASTRABMES = 30;
    BDBINSSC13 = 0;
    WBFGTSSEFIP = 0;
    IF (wmodalidade = 9) THEN
       bdmodalidade = '9';
    ELSE
       bdmodalidade = ' ';

    if ((((wcolant <> BDCODCOL) or (wempant <> BDCODEMP)) and (BDTIPOFOL = 0)) or (((wcolant = BDCODCOL) and (wempant = BDCODEMP)) and (BDTIPOFOL = 0))) then
      begin
        if ((wcolant = BDCODCOL) and (wempant = bdcodemp) and (wtpfolant = 0)) then
          BDTIPOFOL = 1;
        else if (((wcolant <> BDCODCOL) or (wempant <> BDCODEMP)) and (BDTIPOFOL = 0)) then
          begin
          wtpfolant = BDTIPOFOL;
          BDTIPOFOL = 1;
          end
      end
    else if ((wempant = BDCODEMP) and (BDTIPOFOL = 1)) then
      wtpfolant = BDTIPOFOL;

    wcolant = bdcodcol;
    wempant = bdcodemp;

    IF (prtipofc = 3) THEN
       BEGIN
         wparcompant = 'select SUM(BDVALVFC) from ('||
                          'select FC.BDVALVFC from VRHF_EMP_TVERBAFC FC '||
                          'join VRHF_EMP_TFOLHACOMP FCN on (FCN.BDCODEMP = FC.BDCODEMP and FCN.BDCODCOL = FC.BDCODCOL and FCN.BDREFFN = FC.BDREFFN and FCN.BDREFFC = FC.BDREFFC) '||
                          'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FC.BDCODVER) '||
                          'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FC.BDCODVER) '||
                          'where FC.BDCODEMP = '||BDCODEMP||' and FC.BDCODCOL = '||BDCODCOL||' and FC.BDREFFN <= '||pranomes||' and FC.BDREFFC = '||wreffc||
                          ' and (VER.BDCLAVER like '''||'7.060%'''||') '||
                          'and VERF.BDFGTSVER > 0 '||
                          'union all '||
                          'select FC.BDVALVFC from VRHF_EMP_TVERBAFCTOMADOR FC '||
                          'join VRHF_EMP_TFOLTOMCOMP FCN on (FCN.BDCODEMP = FC.BDCODEMP and FCN.BDCODCOL = FC.BDCODCOL and FCN.BDREFTOMADOR = FC.BDREFTOMADOR and FCN.BDREFFC = FC.BDREFFC and FCN.BDORDEM = FC.BDORDEM) '||
                          'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FC.BDCODVER) '||
                          'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FC.BDCODVER) '||
                          'where FC.BDCODEMP = '||BDCODEMP||' and FC.BDCODCOL = '||BDCODCOL||' and FC.BDREFTOMADOR <= '||pranomes||' and FC.BDREFFC = '||wreffc||
                          ' and (VER.BDCLAVER like '''||'7.060%'''||') '||
                          'and VERF.BDFGTSVER > 0) ';

         EXECUTE STATEMENT wparcompant INTO :wbfgtsind;

         IF (wbfgtsind IS NULL) THEN
            wbfgtsind = 0;

         BDBASEFGTS13 = BDBASEFGTS13 - wbfgtsind;

         --Sol. 17956 - Bruno L. R. - 07/07/2017
         IF (wdatagrrf IS NOT NULL) THEN
            BEGIN
              wparcompant = 'select BDBFGTSMESSEFIP from VRHF_EMP_VAL_GRRF_FC('||BDCODEMP||', '||BDCODCOL||', '||pranomes||', '''||wdatagrrf||''', 3)';
            END
         ELSE
            wparcompant = 'select BDBFGTSMESSEFIP from VRHF_EMP_VAL_GRRF_FC('||BDCODEMP||', '||BDCODCOL||', '||pranomes||', null, 3)';
         --Sol. 17956 - Bruno L. R. - 07/07/2017

         EXECUTE STATEMENT wparcompant INTO :wbfgtssefip;

         IF ((wbfgtssefip IS NULL) OR (wbfgtssefip < 0)) THEN
            wbfgtssefip = 0;
       END

    if (wcategoriaesocial in (107, 108)) then
      begin
        EXECUTE STATEMENT 'select BDBINSS13FC from VRHF_EMP_TFOLHACOMP ' ||
                          'where bdcodemp = ' || BDCODEMP || ' and bdcodcol = ' || BDCODCOL || ' and bdreffn = ' || pranomes
        INTO :BDBASEINSS13;
      end

    IF (BDBASEFGTSFOL IS NULL) THEN
       BDBASEFGTSFOL = 0;
    IF (BDBASEFGTS13 IS NULL) THEN
       BDBASEFGTS13 = 0;
    IF (BDVALINSS IS NULL) THEN
       BDVALINSS = 0;
    IF (BDVALINSS13 IS NULL) THEN
       BDVALINSS13 = 0;
    IF (BDBASEINSS IS NULL) THEN
       BDBASEINSS = 0;
    IF (BDBASEINSSCALC13 IS NULL) THEN
       BDBASEINSSCALC13 = 0;
    IF (BDBASEINSS13 IS NULL) THEN
       BDBASEINSS13 = 0;
    IF (bdvalfgts IS NULL) THEN
       bdvalfgts = 0;
    IF (bdvalfgts13 IS NULL) THEN
       bdvalfgts13 = 0;
    IF (bdpercfgtscol IS NULL) THEN
       bdpercfgtscol = 0;
    IF (bdvalinssc13 IS NULL) THEN
       bdvalinssc13 = 0;

    IF (((BDBASEFGTSFOL <> 0) OR (BDBASEFGTS13 <> 0)) AND ((BDMOVRESCSEFIP IS NULL) OR (BDMOVRESCSEFIP <> 'I1' AND BDMOVRESCSEFIP <> 'I2' AND BDMOVRESCSEFIP <> 'I3' AND BDMOVRESCSEFIP <> 'I4' AND BDMOVRESCSEFIP <> 'I5' AND BDMOVRESCSEFIP <> 'L'))) THEN
         wtemmodalidade0 = 1;
    ELSE
       BEGIN
         IF (BDMODALIDADE = ' ' AND wtemmodalidade0 < 1) THEN
            BEGIN
              IF (wbfgtssefip > 0) THEN
                 wtemmodalidade0 = 1;
              ELSE
                 BDMODALIDADE = '1';
            END

         IF (wtemmodalidade0 < 1) THEN
            wtemmodalidade0 = 0;
       END

    IF (wtemmodalidade0 = 1) THEN
       BDTEMMODALIDADE0 = 'TRUE';
    ELSE
       BDTEMMODALIDADE0 = 'FALSE';

    IF ((BDBASEFGTSFOL <> 0) OR (BDBASEFGTS13 <> 0) OR (BDBASEINSS <> 0) OR (BDBASEINSSCALC13 <> 0) OR (BDBASEINSS13 <> 0)) THEN
       SUSPEND;
    ELSE
    IF ((BDBASEFGTSFOL = 0) AND (BDBASEFGTS13 = 0) AND (BDBASEINSS = 0) AND (BDBASEINSSCALC13 = 0) AND (BDBASEINSS13 = 0) AND (BDANOMESRESC > 150001) AND (TRIM(COALESCE(BDMOVRESCSEFIP, '')) <> '')) THEN
       SUSPEND;
  END

  SELECT rdb$set_context('USER_SESSION', 'W_TIPOFOLHA', :wparcompatu) FROM rdb$database INTO wparcompant;

END^

CREATE OR ALTER procedure SP_VRH_RELATORIOCUSTOCOL_PROV (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRSITCOL smallint,
    PRAGRUPAFILIAIS smallint = 0,
    PRCC varchar(5000) = null /* COLLATE WIN1252 - default */ ,
    PRCLA varchar(5000) = null /* COLLATE WIN1252 - default */ ,
    PRSIND varchar(5000) = null /* COLLATE WIN1252 - default */ ,
    PRFUC varchar(5000) = null /* COLLATE WIN1252 - default */ )
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDNOMCOL DM_BDNOMCOL,
    BDPROVFER DM_BOOLEAN,
    BDPROV13 DM_BOOLEAN)
as
declare variable WDTAUX varchar(10);
declare variable WSQL varchar(32700);
declare variable WWHEREFILTRO varchar(32000);
declare variable WSQLCOL varchar(1000);
declare variable WOK smallint;
declare variable WEMP integer;
declare variable WCAT integer;
declare variable WCATES integer;
declare variable WREFADM integer;
declare variable WREFRESC integer;
declare variable WULTDIA integer;
declare variable WIGNORACOL varchar(5);
BEGIN
  /* prsitcol
     0 = Somente ativos
     1 = Todos
     2 = Somente os demitidos
     3 = Somente admitidos no mês
     4 = Somente demitidos no mês
     5 = Ativos sem os demitidos no mês
     6 = Ativos sem demitidos com transferência
     7 = Ativos sem afastados o mês inteiro
     8 = Afastados o mês inteiro
   */

  if (coalesce(prsitcol, 0) = 0) then
     prsitcol = 0;

  if (coalesce(pragrupafiliais, 0) = 1) then
     begin
       wsqlcol = ' where coalesce(COL.BDCONTRCOL, 0) = 0 ';
     
       if (coalesce(premp, '') <> '') then
          begin
            wsqlcol = wsqlcol||' and (('||replace(upper(premp), 'COL.BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(upper(premp), 'COL.BDCODEMP', 'EMP.BDCODMATRIZ')||'))';
          end
     
       wsqlcol = 'select EMP.BDCODEMP, COL.BDCODCOL, SUBSTRING(CAST(COL.BDDATAADMCOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(COL.BDDATAADMCOL AS VARCHAR(10)) FROM 6 FOR 2), RESC.BDREFRESCISAO '||
                 'from TEMPRESAS EMP '||
                 'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = EMP.BDCODEMP) '||
                 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) '||
                 wsqlcol;
     end
  else
     begin
       wsqlcol = ' where coalesce(COL.BDCONTRCOL, 0) = 0 ';
     
       if (coalesce(premp, '') <> '') then
          begin
            wsqlcol = wsqlcol||' and '||premp;
     
            if (coalesce(prcol, '') <> '') then
               wsqlcol = wsqlcol||' and '||prcol;
          end
     
       wsqlcol = 'select COL.BDCODEMP, COL.BDCODCOL, SUBSTRING(CAST(COL.BDDATAADMCOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(COL.BDDATAADMCOL AS VARCHAR(10)) FROM 6 FOR 2), RESC.BDREFRESCISAO '||
                 'from VRH_EMP_TCOLCON COL '||
                 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) '||
                 wsqlcol;
     end

  while (prrefini <= prreffim) do
    begin
      BDREFFN = prrefini;

      for execute statement wsqlcol into :BDCODEMP, :BDCODCOL, :wrefadm, :wrefresc do
        begin
          wOk = 1;   --- 0 = NÃO; 1 = SIM

          wcat   = null;
          wcates = null;

          wignoracol = case
                         when ((prsitcol = 0) and ((wrefadm <= prrefini) and (wrefresc is null or wrefresc >= prrefini))) then 'FALSE' -- Somente ativos
                         when (prsitcol = 1) then 'FALSE' -- Todos
                         when ((prsitcol = 2) and (wrefresc <= prrefini)) then 'FALSE' -- Somente os demitidos
                         when ((prsitcol = 3) and (wrefadm = prrefini)) then 'FALSE' -- Somente admitidos no mês
                         when ((prsitcol = 4) and (wrefresc = prrefini)) then 'FALSE' -- Somente demitidos no mês
                         when ((prsitcol = 5) and ((wrefadm <= prrefini) and (wrefresc is null or wrefresc > prrefini))) then 'FALSE' -- Ativos sem os demitidos no mês
                         when ((prsitcol = 6) and ((wrefadm <= prrefini) and (wrefresc is null or wrefresc >= prrefini))) then 'FALSE' -- Ativos sem demitidos com transferência
                         when ((prsitcol = 7) and (wrefadm <= prrefini) and (wrefresc is null or wrefresc >= prrefini) and
                              (not exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TSITCOL Y
                                          join VRH_BASE_TPREPSIT Z on (Z.BDCODSIT = Y.BDCODSIT)
                                          where Y.BDCODEMP = :BDCODEMP and
                                                Y.BDCODCOL = :BDCODCOL and
                                              ((extract(year from Y.BDDATAINISIT) * 100 + extract(month from Y.BDDATAINISIT)) <= :prrefini) and
                                               (Y.BDDATAFIMSIT is null or ((extract(year from Y.BDDATAINISIT) * 100 + extract(month from Y.BDDATAINISIT)) >= :prrefini) and
                                                Z.BDCODVER is not null)))) then 'FALSE' -- Ativos sem afastados o mês inteiro
                         when ((prsitcol = 8) and (wrefadm <= prrefini) and (wrefresc is null or wrefresc >= prrefini) and
                              (exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TSITCOL Y
                                      where Y.BDCODEMP = :BDCODEMP and
                                            Y.BDCODCOL = :BDCODCOL and
                                           ((extract(year from Y.BDDATAINISIT) * 100 + extract(month from Y.BDDATAINISIT)) <= :prrefini) and
                                           (Y.BDDATAFIMSIT is null or ((extract(year from Y.BDDATAINISIT) * 100 + extract(month from Y.BDDATAINISIT)) >= :prrefini))))) then 'FALSE' -- Afastados o mês inteiro
                         else 'TRUE'
                       end;

          wsql = 'select first 1 BDCATEGORIACOL, BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFCOL <= '||prrefini||' order by BDREFCOL DESC ';
          execute statement wsql into :wcat, wcates;

          if (coalesce(wcat, 0) = 4 and coalesce(wcates, 0) = 111) then
             wOk = 0;

          if (wOK = 1 and prsitcol = 0) then   -- Somente ativos
             begin
               if ((wrefadm > prrefini) or (coalesce(wrefresc, 999999) < prrefini)) then
                  wOk = 0;
             end
           if (wignoracol = 'FALSE') then
              begin
                if ((coalesce(prcla,  '') <> '') or
                   (coalesce(prsind,  '') <> '') or
                   (coalesce(prfuc,  '') <> '') or
                   (coalesce(prcc,  '') <> '')) then
                  begin
                     /* Colaboradores */
                     wsql = 'select first 1 * from VRH_EMP_TCOLCON_VINC where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||bdcodcol||' and BDREFCOL <= '||prrefini||' order by BDREFCOL DESC';
                     wsql = 'select first 1 coalesce(bdcodcol,0) from ('||wsql||') ';
     
                     wwherefiltro = '';
                     if (coalesce(prcla,  '') <> '') then
                        begin
                          wwherefiltro = ' where '||prcla;
                  end
                
                     if (wwherefiltro <> '') then
                        begin
                          wok = 0;
                          execute statement wsql||wwherefiltro into :wok;
                          wok = coalesce(wok, 0);
                        end
     
                     wwherefiltro = '';
                     if (coalesce(prsind,  '') <> '') then
                  begin
                          wsql = 'select first 1 * from VRH_EMP_TCOL_VINC where BDCODEMP = '||bdcodemp||' and BDCODCOL = '||bdcodcol||' and BDREFCOL <= '||prrefini||' order by BDREFCOL DESC';
                          wsql = 'select first 1 coalesce(bdcodcol,0) from ('||wsql||') ';
                          wwherefiltro = ' where ';
                          wwherefiltro = wwherefiltro||prsind;
                  end
     
                     if ((wok > 0) and (wwherefiltro <> '')) then
                  begin
                          wok = 0;
                          execute statement wsql||wwherefiltro into :wok;
                          wok = coalesce(wok, 0);
                  end
             
                     select first 1 ULTDIA from ULTIMO_DIA_MES(CAST(SUBSTRING(:prrefini FROM 5 FOR 2) AS SMALLINT), CAST(SUBSTRING(:prrefini FROM 1 FOR 4) AS INTEGER)) into :wdtaux;
                     wdtaux = SUBSTRING(:prrefini FROM 5 FOR 2)||'-'||lpad(wdtaux,  2, '0')||'-'||SUBSTRING(:prrefini FROM 1 FOR 4);
     
                     wwherefiltro = '';
                     if (wok > 0) then
                  begin
                          wsql = 'select first 1 * from VRH_EMP_TCOL_VINCDIA where BDCODEMP = '||bdcodemp||' and BDCODCOL = '||bdcodcol||' and BDDATACOL <= '''||wdtaux||''' order by BDDATACOL DESC';
                          wsql = 'select first 1 coalesce(bdcodcol,0) from ('||wsql||') ';
                          if (coalesce(prfuc,  '') <> '') then
                             begin
                               if (wwherefiltro <> '') then
                                  wwherefiltro = wwherefiltro||' and ';
                               else
                                  wwherefiltro = ' where ';
                               wwherefiltro = wwherefiltro||prfuc;
                  end
             
                          if (wwherefiltro <> '') then
                             begin
                               wok = 0;
                               execute statement wsql||wwherefiltro into :wok;
                               wok = coalesce(wok, 0);
                             end
                        end
                   end
              end

          if (wignoracol = 'FALSE') then
             begin
                if (coalesce(wOk, 0) > 0) then
                   begin
                     wemp = null;
                     select first 1 BDCODEMP from VRHF_EMP_TPROVISAO13 where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFP13 = :prrefini into :wemp;
      
                     if (coalesce(wemp, 0) = 0) then
                        begin
                          wsql = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFCOL <= '||prrefini||' order by BDREFCOL DESC ';
                          execute statement wsql into :BDNOMCOL;
                          BDPROV13 = 'TRUE';
                        end
                     else
                       BDPROV13 = 'FALSE';
      
                     wemp = null;
                     select first 1 BDCODEMP from VRHF_EMP_TPROVISAOFERIAS where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFPFER = :prrefini into :wemp;
      
                     if (coalesce(wemp, 0) = 0) then
                        begin
                          wsql = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFCOL <= '||prrefini||' order by BDREFCOL DESC ';
                          execute statement wsql into :BDNOMCOL;
                          BDPROVFER = 'TRUE';
                        end
                     else
                       BDPROVFER = 'FALSE';
      
                     if ((BDPROV13 = 'TRUE') or (BDPROVFER = 'TRUE')) then
                        SUSPEND;
                   end
             end
        end

      if (SUBSTRING(prrefini FROM 5 FOR 2) = '12') then
         prrefini = CAST((CAST((CAST(SUBSTRING(prrefini FROM 1 FOR 4) AS INTEGER) + 1) AS VARCHAR(4))||'01') AS INTEGER);
      else
         prrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||lpad(CAST((CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) + 1) AS VARCHAR(2)), 2, '0')) AS INTEGER);
    end
END
^

create or alter procedure SP_VRH_RELATORIOCUSTOCOL_FN (
    PREMP varchar(10000),
    PRCOL varchar(20000),
    PRAUT varchar(10000),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPA smallint = 0,
    PRCC varchar(10000) = null,
    PRAGRUPAFILIAIS smallint = 0)
returns (
    BDCODEMP integer,
    BDREF integer,
    BDTIPOCOL integer,
    BDCODCOL integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCODFILIAL integer,
    BDCODVER integer,
    BDVALOR numeric(18,6),
    BDCLAVER varchar(20))
as
declare variable WSQL varchar(32700);
BEGIN
  /* pragrupa
    0 = sem centro de custos (não retorna o centro de custos)
    1 = por centro de custos (retorna o centro de custos)
   */

  wsql = '';

  premp = upper(premp);
  prcol = upper(prcol);

  IF (UPPER(COALESCE(prcol, '')) <> 'NENHUM') THEN
     BEGIN
       wsql = wsql||
              'select col.bdcodemp, col.BDCODFILIAL, col.BDREFFN, 0 BDTIPOCOL, col.bdcodcol, col.bdcodver, col.bdvalvfn, col.BDCODCENTRO, col.BDCODTPCC '||
              'from (';

       IF ((prcc IS NULL) OR (prcc = '')) THEN
          BEGIN
            if (coalesce(pragrupafiliais, 0) > 0) then
               begin
                 wsql = wsql||
                          'select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, EMP.bdcodemp BDCODFILIAL, FN.BDCODCOL, FN.BDREFFN, FN.BDCODVER, FN.BDVALVFN, cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBAFN FN join TEMPRESAS EMP on (EMP.BDCODEMP = FN.BDCODEMP) where FN.BDREFFN between '||prrefini||' and '||prreffim;
          
                          IF (premp IS NOT NULL AND premp <> '') THEN
                             wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||'))' ;

                          IF (prcol IS NOT NULL AND prcol <> '') THEN
                             wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FN.BDCODCOL');

                 wsql = wsql||' union all '||
                          'select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, EMP.bdcodemp BDCODFILIAL, FC.BDCODCOL, FC.BDREFCOMP, FC.BDCODVER, FC.BDVALVFC, cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBAFC FC join TEMPRESAS EMP on (EMP.BDCODEMP = FC.BDCODEMP) where FC.BDREFCOMP between '||prrefini||' and '||prreffim;
          
                          IF (premp IS NOT NULL AND premp <> '') THEN
                             wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||'))' ;

                          IF (prcol IS NOT NULL AND prcol <> '') THEN
                             wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FC.BDCODCOL');

                 wsql = wsql||' union all '||
                          'select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, EMP.bdcodemp BDCODFILIAL, FN.BDCODCOL, FN.BDREFFN, FN.BDCODVER, FN.BDVALVFN, cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBAINT FN join TEMPRESAS EMP on (EMP.BDCODEMP = FN.BDCODEMP) where FN.BDREFFN between '||prrefini||' and '||prreffim;
          
                          IF (premp IS NOT NULL AND premp <> '') THEN
                             wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||'))' ;

                          IF (prcol IS NOT NULL AND prcol <> '') THEN
                             wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FN.BDCODCOL');

               end
            else
               begin
                 wsql = wsql||
                          'select bdcodemp, bdcodemp BDCODFILIAL, BDCODCOL, BDREFFN, BDCODVER, BDVALVFN, cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBAFN where BDREFFN between '||prrefini||' and '||prreffim;
          
                          IF (premp IS NOT NULL AND premp <> '') THEN
                             BEGIN
                               wsql = wsql||' and '||premp;
     
                               IF (prcol IS NOT NULL AND prcol <> '') THEN
                                  wsql = wsql||' and '||prcol;
                             END
          
                 wsql = wsql||' union all '||
                          'select bdcodemp, bdcodemp BDCODFILIAL, BDCODCOL, BDREFCOMP, BDCODVER, BDVALVFC, cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBAFC where BDREFCOMP between '||prrefini||' and '||prreffim;
          
                          IF (premp IS NOT NULL AND premp <> '') THEN
                             BEGIN
                               wsql = wsql||' and '||premp;
                   
                               IF (prcol IS NOT NULL AND prcol <> '') THEN
                                  wsql = wsql||' and '||prcol;
                   
                             END

                 wsql = wsql||' union all '||
                          'select bdcodemp, bdcodemp BDCODFILIAL, BDCODCOL, BDREFFN, BDCODVER, BDVALVFN, cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBAINT where BDREFFN between '||prrefini||' and '||prreffim;
          
                          IF (premp IS NOT NULL AND premp <> '') THEN
                             BEGIN
                               wsql = wsql||' and '||premp;
                   
                               IF (prcol IS NOT NULL AND prcol <> '') THEN
                                  wsql = wsql||' and '||prcol;
                   
                             END
               end

            wsql = wsql||' union all ';
          END

       if (coalesce(pragrupafiliais, 0) > 0) then
          begin
            wsql = wsql||
                     'select FT.bdcodemp, FT.BDCODFILIAL, FT.BDCODCOL, FT.BDREFTOMADOR BDREFFN, FT.BDCODVER, FT.BDVALVFT BDVALVFN, ';
     
                     IF (pragrupa = 0) THEN
                        wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                     ELSE
                        wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

            wsql = wsql||
                     'from (select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, FT.BDCODEMP BDCODFILIAL, FT.BDCODCOL, FT.BDREFTOMADOR, FT.BDORDEM, FT.BDCODVER, FT.BDVALVFT from VRHF_EMP_TVERBATOMADOR FT '||
                            'join TEMPRESAS EMP on (EMP.BDCODEMP = FT.BDCODEMP) where FT.BDREFTOMADOR between '||prrefini||' and '||prreffim;
     
            IF (premp IS NOT NULL AND premp <> '') THEN
               wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||'))';

            IF (prcol IS NOT NULL AND prcol <> '') THEN
               wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FT.BDCODCOL');
          end
       else
          begin
            wsql = wsql||
                     'select FT.bdcodemp, FT.bdcodemp BDCODFILIAL, FT.BDCODCOL, FT.BDREFTOMADOR BDREFFN, FT.BDCODVER, FT.BDVALVFT BDVALVFN, ';
     
                     IF (pragrupa = 0) THEN
                        wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                     ELSE
                        wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

            wsql = wsql||
                     'from (select * from VRHF_EMP_TVERBATOMADOR where BDREFTOMADOR between '||prrefini||' and '||prreffim;
     
                            IF (premp IS NOT NULL AND premp <> '') THEN
                               BEGIN
                                 wsql = wsql||' and '||premp;
                     
                                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                                    wsql = wsql||' and '||prcol;
                     
                               END
          end

       wsql = wsql||
                ') FT left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = FT.BDCODEMP and prepft.BDCODCOL = FT.BDCODCOL and prepft.BDORDEM = FT.BDORDEM) ';

       IF (prcc IS NOT NULL AND prcc <> '') THEN
          wsql = wsql||' where '||prcc;


       if (coalesce(pragrupafiliais, 0) > 0) then
          begin
            wsql = wsql||
                     'union all select FT.bdcodemp, FT.BDCODFILIAL, FT.BDCODCOL, FT.BDREFTOMADOR BDREFFN, FT.BDCODVER, FT.BDVALVFT BDVALVFN, ';
     
                     IF (pragrupa = 0) THEN
                        wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                     ELSE
                        wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

            wsql = wsql||
                     'from (select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, FT.BDCODEMP BDCODFILIAL, FT.BDCODCOL, FT.BDREFTOMADOR, FT.BDORDEM, FT.BDCODVER, FT.BDVALVFT from VRHF_EMP_TVERBATOMINT FT '||
                            'join TEMPRESAS EMP on (EMP.BDCODEMP = FT.BDCODEMP) where FT.BDREFTOMADOR between '||prrefini||' and '||prreffim;
     
            IF (premp IS NOT NULL AND premp <> '') THEN
               wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||'))';

            IF (prcol IS NOT NULL AND prcol <> '') THEN
               wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FT.BDCODCOL');
          end
       else
          begin
            wsql = wsql||
                     'union all select FT.bdcodemp, FT.bdcodemp BDCODFILIAL, FT.BDCODCOL, FT.BDREFTOMADOR BDREFFN, FT.BDCODVER, FT.BDVALVFT BDVALVFN, ';
     
                     IF (pragrupa = 0) THEN
                        wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                     ELSE
                        wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

            wsql = wsql||
                     'from (select * from VRHF_EMP_TVERBATOMINT where BDREFTOMADOR between '||prrefini||' and '||prreffim;
     
                            IF (premp IS NOT NULL AND premp <> '') THEN
                               BEGIN
                                 wsql = wsql||' and '||premp;
                     
                                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                                    wsql = wsql||' and '||prcol;
                     
                               END
          end

       wsql = wsql||
                ') FT left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = FT.BDCODEMP and prepft.BDCODCOL = FT.BDCODCOL and prepft.BDORDEM = FT.BDORDEM) ';

       IF (prcc IS NOT NULL AND prcc <> '') THEN
          wsql = wsql||' where '||prcc;


       if (coalesce(pragrupafiliais, 0) > 0) then
          begin
            wsql = wsql||' union all '||
                     'select FT.bdcodemp, FT.BDCODFILIAL, FT.BDCODCOL, FT.BDREFCOMP, FT.BDCODVER, FT.BDVALVFC,';
     
                     IF (pragrupa = 0) THEN
                        wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                     ELSE
                        wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';
     
            wsql = wsql||
                     'from (select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, FC.BDCODEMP BDCODFILIAL, FC.BDCODCOL, FC.BDREFCOMP, FC.BDCODVER, FC.BDORDEM, FC.BDVALVFC from VRHF_EMP_TVERBAFCTOMADOR FC '||
                            'join TEMPRESAS EMP on (EMP.BDCODEMP = FC.BDCODEMP) '||
                            'where FC.BDREFCOMP between '||prrefini||' and '||prreffim;
     
            IF (premp IS NOT NULL AND premp <> '') THEN
               wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';

            IF (prcol IS NOT NULL AND prcol <> '') THEN
               wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FC.BDCODCOL');
          end
       else
          begin
            wsql = wsql||' union all '||
                     'select FT.bdcodemp, FT.bdcodemp BDCODFILIAL, FT.BDCODCOL, FT.BDREFCOMP, FT.BDCODVER, FT.BDVALVFC,';
     
                     IF (pragrupa = 0) THEN
                        wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                     ELSE
                        wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';
     
            wsql = wsql||
                     'from (select * from VRHF_EMP_TVERBAFCTOMADOR '||
                            'where BDREFCOMP between '||prrefini||' and '||prreffim;
     
                            IF (premp IS NOT NULL AND premp <> '') THEN
                               BEGIN
                                 wsql = wsql||' and '||premp;
                     
                                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                                    wsql = wsql||' and '||prcol;
                     
                               END
          end

       wsql = wsql||
                ') FT '||
                'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = FT.BDCODEMP and prepft.BDCODCOL = FT.BDCODCOL and prepft.BDORDEM = FT.BDORDEM) ';

       IF (prcc IS NOT NULL AND prcc <> '') THEN
          wsql = wsql||' where '||prcc;


      -- adiantamento de 13º salário
      wsql = wsql||
             ' union all ';


      if (coalesce(pragrupafiliais, 0) > 0) then
         begin
           wsql = wsql||
                  'select a13.BDCODEMP, a13.bdcodemp BDCODFILIAL, a13.BDCODCOL, a13.BDREFA13, a13.BDCODVER, a13.BDVALVA13,';

                  IF (pragrupa = 0) THEN
                     wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                  ELSE
                     wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

           wsql = wsql||
                  'from (select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, EMP.BDCODEMP BDCODFILIAL, a13.BDCODCOL, a13.BDREFA13, a13.BDCODVER, a13.BDCHAVE, a13.BDVALVA13 from VRHF_EMP_TVERBAA13_RAT a13 '||
                        'join TEMPRESAS EMP on (EMP.BDCODEMP = a13.BDCODEMP) '||
                        'where a13.BDREFA13 between '||prrefini||' and '||prreffim;
     
                        IF (premp IS NOT NULL AND premp <> '') THEN
                           wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';

                        IF (prcol IS NOT NULL AND prcol <> '') THEN
                           wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'A13.BDCODCOL');

           wsql = wsql||
                  ') a13 left outer join VRHF_EMP_TA13SAL_RAT aa13 on (aa13.BDCODEMP = a13.BDCODEMP and aa13.BDCODCOL = a13.bdcodcol and aa13.bdrefa13 = a13.bdrefa13 and aa13.bdchave = a13.bdchave) '||
                  'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = aa13.BDCODEMP and prepft.BDCODCOL = aa13.BDCODCOL and prepft.BDORDEM = aa13.BDORDEM) ';

           if (coalesce(prcc, '') <> '') then
              wsql = wsql||' where '||prcc;
         end
      else
         begin
           wsql = wsql||
                  'select a13.BDCODEMP, a13.bdcodemp BDCODFILIAL, a13.BDCODCOL, a13.BDREFA13, a13.BDCODVER, a13.BDVALVA13,';

                  IF (pragrupa = 0) THEN
                     wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                  ELSE
                     wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

           wsql = wsql||
                  'from (select * from VRHF_EMP_TVERBAA13_RAT '||
                        'where BDREFA13 between '||prrefini||' and '||prreffim;
     
                        IF (premp IS NOT NULL AND premp <> '') THEN
                           BEGIN
                             wsql = wsql||' and '||premp;
                 
                             IF (prcol IS NOT NULL AND prcol <> '') THEN
                                wsql = wsql||' and '||prcol;
                 
                           END

           wsql = wsql||
                  ') a13 left outer join VRHF_EMP_TA13SAL_RAT aa13 on (aa13.BDCODEMP = a13.BDCODEMP and aa13.BDCODCOL = a13.bdcodcol and aa13.bdrefa13 = a13.bdrefa13 and aa13.bdchave = a13.bdchave) '||
                  'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = aa13.BDCODEMP and prepft.BDCODCOL = aa13.BDCODCOL and prepft.BDORDEM = aa13.BDORDEM) ';

           if (coalesce(prcc, '') <> '') then
              wsql = wsql||' where '||prcc;
         end

      -- 13º salário
      wsql = wsql||
             ' union all ';

      IF (coalesce(pragrupafiliais, 0) > 0) THEN
         BEGIN
           wsql = wsql||
                  'select S13.BDCODEMP, S13.BDCODFILIAL, S13.BDCODCOL, S13.BDREF13, S13.BDCODVER, S13.BDVALV13,';

                  IF (pragrupa = 0) THEN
                     wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                  ELSE
                     wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

           wsql = wsql||
                  'from (select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, s13.BDCODEMP BDCODFILIAL, s13.BDCODCOL, s13.BDREF13, s13.BDCHAVE, s13.BDCODVER, s13.BDVALV13 from VRHF_EMP_TVERBA_13_RAT s13 '||
                         'join TEMPRESAS EMP on (EMP.BDCODEMP = s13.BDCODEMP) '||
                         'where s13.BDREF13 between '||prrefini||' and '||prreffim;
             
                         IF (premp IS NOT NULL AND premp <> '') THEN
                            wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';

                        IF (prcol IS NOT NULL AND prcol <> '') THEN
                           wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'S13.BDCODCOL');

           wsql = wsql||
                  ') S13 left outer join VRHF_EMP_T13SAL_RAT SS13 on (SS13.BDCODEMP = S13.BDCODEMP and SS13.BDCODCOL = S13.BDCODCOL and SS13.BDREF13 = S13.BDREF13 and SS13.bdchave = S13.BDCHAVE) '||
                  'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = ss13.BDCODEMP and prepft.BDCODCOL = ss13.BDCODCOL and prepft.BDORDEM = ss13.BDORDEM) ';

           if (coalesce(prcc, '') <> '') then
                  wsql = wsql||' where '||prcc;
         END
      ELSE
         BEGIN
           wsql = wsql||
                  'select S13.BDCODEMP, S13.bdcodemp BDCODFILIAL, S13.BDCODCOL, S13.BDREF13, S13.BDCODVER, S13.BDVALV13,';

                  IF (pragrupa = 0) THEN
                     wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                  ELSE
                     wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

           wsql = wsql||
                  'from (select * from VRHF_EMP_TVERBA_13_RAT '||
                         'where BDREF13 between '||prrefini||' and '||prreffim;
             
                         IF (premp IS NOT NULL AND premp <> '') THEN
                            BEGIN
                              wsql = wsql||' and '||premp;
                   
                              IF (prcol IS NOT NULL AND prcol <> '') THEN
                                 wsql = wsql||' and '||prcol;
                   
                            END
           wsql = wsql||
                  ') S13 left outer join VRHF_EMP_T13SAL_RAT SS13 on (SS13.BDCODEMP = S13.BDCODEMP and SS13.BDCODCOL = S13.BDCODCOL and SS13.BDREF13 = S13.BDREF13 and SS13.bdchave = S13.BDCHAVE) '||
                  'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = ss13.BDCODEMP and prepft.BDCODCOL = ss13.BDCODCOL and prepft.BDORDEM = ss13.BDORDEM) ';

           if (coalesce(prcc, '') <> '') then
                  wsql = wsql||' where '||prcc;
         END

      -- Complemento de 13º salário
      wsql = wsql||
             ' union all ';

      IF (coalesce(pragrupafiliais, 0) > 0) THEN
         BEGIN
           wsql = wsql||
                  'select C13.BDCODEMP, C13.BDCODFILIAL, C13.BDCODCOL, C13.BDREFC13, C13.BDCODVER, C13.BDVALVC13,';

                  IF (pragrupa = 0) THEN
                     wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                  ELSE
                     wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

           wsql = wsql||
                  'from (select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, EMP.BDCODEMP BDCODFILIAL, c13.BDCODCOL, c13.BDREFC13, c13.BDCODVER, c13.BDVALVC13 from VRHF_EMP_TVERBAC13 c13 '||
                        'join TEMPRESAS EMP on (EMP.BDCODEMP = c13.BDCODEMP) '||
                        'where c13.BDREFC13 between '||prrefini||' and '||prreffim;
           
                        IF (premp IS NOT NULL AND premp <> '') THEN
                           wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';

                        IF (prcol IS NOT NULL AND prcol <> '') THEN
                           wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'C13.BDCODCOL');

           wsql = wsql||
                  ') C13 join VRHF_EMP_T13SAL_RAT CC13 on (CC13.BDCODEMP = C13.BDCODEMP and CC13.BDCODCOL = C13.BDCODCOL and CC13.BDREF13 = C13.BDREFC13) '||
                  'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = CC13.BDCODEMP and prepft.BDCODCOL = CC13.BDCODCOL and prepft.BDORDEM = CC13.BDORDEM) ';

           if (coalesce(prcc, '') <> '') then
              wsql = wsql||' where '||prcc;
         END
      ELSE
         BEGIN
           wsql = wsql||
                  'select C13.BDCODEMP, C13.bdcodemp BDCODFILIAL, C13.BDCODCOL, C13.BDREFC13, C13.BDCODVER, C13.BDVALVC13,';

                  IF (pragrupa = 0) THEN
                     wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                  ELSE
                     wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

           wsql = wsql||
                  'from (select * from VRHF_EMP_TVERBAC13 '||
                        'where BDREFC13 between '||prrefini||' and '||prreffim;
           
                        IF (premp IS NOT NULL AND premp <> '') THEN
                           BEGIN
                             wsql = wsql||' and '||premp;
                 
                             IF (prcol IS NOT NULL AND prcol <> '') THEN
                                wsql = wsql||' and '||prcol;
                 
                           END
           wsql = wsql||
                  ') C13 join VRHF_EMP_T13SAL_RAT CC13 on (CC13.BDCODEMP = C13.BDCODEMP and CC13.BDCODCOL = C13.BDCODCOL and CC13.BDREF13 = C13.BDREFC13) '||
                  'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = CC13.BDCODEMP and prepft.BDCODCOL = CC13.BDCODCOL and prepft.BDORDEM = CC13.BDORDEM) ';

           if (coalesce(prcc, '') <> '') then
              wsql = wsql||' where '||prcc;
         END

      -- Folha avulsa

      if (coalesce(pragrupafiliais, 0) > 0) then
         begin
           wsql = wsql||
                  ' union all '||
                  'select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, EMP.BDCODEMP BDCODFILIAL, fa.BDCODCOL, SUBSTRING(CAST(fa.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(fa.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2) BDREF, fa.BDCODVER, fa.BDVALVFA,';

           if (coalesce(pragrupa, 0) = 0) then
              wsql = wsql||' cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODPTCC ';
           else
              wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

           wsql = wsql||
                  'from VRHF_EMP_TVERBAFA fa '||
                  'join TEMPRESAS EMP on (EMP.BDCODEMP = fa.BDCODEMP) '||
                  'join VRHF_EMP_TFOLHAAVULSA ffa on (ffa.BDCODEMP = fa.BDCODEMP and ffa.BDCODCOL = fa.BDCODCOL and ffa.BDCODTCA = fa.BDCODTCA and ffa.BDDATAFA = fa.BDDATAFA) '||
                  'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = ffa.BDCODEMP and prepft.BDCODCOL = ffa.BDCODCOL and prepft.BDORDEM = ffa.BDORDEM) '||
                  'where SUBSTRING(CAST(fa.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(fa.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2) between '||prrefini||' and '||prreffim;
     
                  IF (premp IS NOT NULL AND premp <> '') THEN
                     wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||'))';

                  IF (prcol IS NOT NULL AND prcol <> '') THEN
                     wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FA.BDCODCOL');

                  if (coalesce(prcc, '') <> '') then
                     wsql = wsql||' and '||prcc;
         end
       else
         begin
           wsql = wsql||
                  ' union all '||
                  'select fa.BDCODEMP, fa.bdcodemp BDCODFILIAL, fa.BDCODCOL, SUBSTRING(CAST(fa.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(fa.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2) BDREF, fa.BDCODVER, fa.BDVALVFA, ';

           if (coalesce(pragrupa, 0) = 0) then
              wsql = wsql||' cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODPTCC ';
           else
              wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

           wsql = wsql||
                  'from VRHF_EMP_TVERBAFA fa '||
                  'join VRHF_EMP_TFOLHAAVULSA ffa on (ffa.BDCODEMP = fa.BDCODEMP and ffa.BDCODCOL = fa.BDCODCOL and ffa.BDCODTCA = fa.BDCODTCA and ffa.BDDATAFA = fa.BDDATAFA) '||
                  'left outer join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = ffa.BDCODEMP and prepft.BDCODCOL = ffa.BDCODCOL and prepft.BDORDEM = ffa.BDORDEM) '||
                  'where SUBSTRING(CAST(fa.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(fa.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2) between '||prrefini||' and '||prreffim;
     
                  IF (premp IS NOT NULL AND premp <> '') THEN
                     BEGIN
                       wsql = wsql||' and '||replace(premp, 'BDCODEMP', 'fa.BDCODEMP');
           
                       IF (prcol IS NOT NULL AND prcol <> '') THEN
                          wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'fa.BDCODCOL');
                     END

                  if (coalesce(prcc, '') <> '') then
                     wsql = wsql||' and '||prcc;
         end

       wsql = wsql||
              ') col ';
     END

  IF (UPPER(COALESCE(prAut, '')) <> 'NENHUM') THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       if (coalesce(pragrupafiliais, 0) > 0) then
          begin
            wsql = wsql||
                   'select col.BDCODEMP, col.BDCODFILIAL, col.bdrefinssserv BDREFFN, 2 BDTIPOCOL, col.BDCODTER BDCODCOL, FN.BDCODVER, FN.BDVALOR BDVALVFN,';
     
                   IF (pragrupa = 0) THEN
                      wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                   ELSE
                      wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';
     
            wsql = wsql||
                   'from (select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, EMP.BDCODEMP BDCODFILIAL, aut.bdrefinssserv, aut.bdcodter, aut.BDCODSERV from VRHF_BASE_CALC_TERC aut '||
                      'join TEMPRESAS EMP on (EMP.BDCODEMP = aut.BDCODEMP) where aut.BDREFINSSSERV between '||prrefini||' and '||prreffim;
     
            IF (premp IS NOT NULL AND premp <> '') THEN
               begin
                 wsql = wsql||' and (('||replace(premp, 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(premp, 'BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';

                 IF (praut IS NOT NULL AND praut <> '') THEN
                    wsql = wsql||' and '||replace(praut, 'BDCODTER', 'aut.BDCODTER');

               end
          end
       else
          begin
            wsql = wsql||
                   'select col.BDCODEMP, col.bdcodemp BDCODFILIAL, col.bdrefinssserv BDREFFN, 2 BDTIPOCOL, col.BDCODTER BDCODCOL, FN.BDCODVER, FN.BDVALOR BDVALVFN,';
     
                   IF (pragrupa = 0) THEN
                      wsql = wsql||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                   ELSE
                      wsql = wsql||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';
     
            wsql = wsql||
                   'from (select * from VRHF_BASE_CALC_TERC where BDREFINSSSERV between '||prrefini||' and '||prreffim;
     
                      IF (premp IS NOT NULL AND premp <> '') THEN
                         BEGIN
                           wsql = wsql||' and '||premp;
               
                           IF (praut IS NOT NULL AND praut <> '') THEN
                              wsql = wsql||' and '||praut;
               
                         END
          end

       wsql = wsql||
              ') col '||
              'join VRHF_BASE_ITEMS_CALCTERC FN on (FN.BDCODTER = COL.BDCODTER and FN.BDCODEMP = COL.BDCODEMP and FN.BDCODSERV = COL.BDCODSERV) ';

       wsql = wsql||'join VRH_BASE_TSERVTERC prepft on (prepft.bdcodter = col.bdcodter and prepft.bdcodemp = col.bdcodemp and prepft.bdcodserv = col.bdcodserv) ';

       IF (prcc IS NOT NULL AND prcc <> '') THEN
          wsql = wsql||' where '||prcc;

     END

  IF (wsql <> '') THEN
     wsql = 'select FOLHA.BDCODEMP, FOLHA.BDREFFN, FOLHA.BDTIPOCOL, FOLHA.BDCODCOL, FOLHA.BDCODVER, FOLHA.BDVALVFN, COALESCE(FOLHA.BDCODCENTRO,0), COALESCE(FOLHA.BDCODTPCC, 0), VER.BDCLAVER, FOLHA.BDCODFILIAL '||
            'from ('||wsql||') FOLHA join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOLHA.BDCODVER) where VER.BDCLAVER not starting with ''0.191'' '||
            'order by FOLHA.BDCODEMP, FOLHA.BDCODFILIAL, FOLHA.BDCODTPCC, FOLHA.BDREFFN, FOLHA.BDCODCOL';

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP, :BDREF, :BDTIPOCOL, :BDCODCOL, :BDCODVER, :BDVALOR, :BDCODCENTRO, :BDCODTPCC, :BDCLAVER, :BDCODFILIAL
  DO
    SUSPEND;
END^

create or alter procedure SP_VRH_REL_CUSTOCOL_7186_CALC (
    PREMP varchar(10000),
    PRCOL varchar(20000),
    PRAUT varchar(10000),
    PRREFINI integer,
    PRCC varchar(5000) = '',
    PRPAGTO integer = 0)
returns (
    BDCODEMP integer,
    BDREFFN integer,
    BDTIPOCOL integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDVALVFN numeric(15,2),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCODFILIAL integer,
    BDFGTS numeric(15,2),
    BDBASEPIS numeric(15,2),
    BDTIPOCALC integer,
    BDREFFNAUX integer,
    BDREFPAG integer,
    BDORDEM integer)
as
declare variable WSQL varchar(32000);
declare variable W13 integer = 0;
declare variable WANO13 integer = 0;
declare variable WSQLCOMPNORMAL varchar(3000);
declare variable WWHERECOMPNORMAL varchar(3000);
declare variable WWHERECOMPADC varchar(3000);
declare variable WSQLCOMPADC varchar(3000);
declare variable WWHERE varchar(500);
declare variable WJOINCC varchar(1000);
begin
  bdcodcentro = null;

  /* Procedure Text */
  premp = upper(premp);
  prcol = upper(prcol);
  praut = upper(praut);
  wWhere = '';
  
  /*166040 - André Cursino - 31/10/2022 - inicio*/
  IF (SUBSTRING(CAST(prrefini AS VARCHAR(6)) FROM 5 FOR 2) = 12) THEN
    w13 = 1;

  wAno13 = cast(SUBSTRING(CAST(prrefini AS VARCHAR(6)) FROM 1 FOR 4) as integer);
  /*166040 - André Cursino - 31/10/2022 - fim*/

  if (coalesce(PRCOL,'') <> 'NENHUM') then
     begin
       if ((prcc is null) or (prcc = '')) then
          begin
               wSql = 'select 0 BDTIPOCOL, FN.BDCODVER, FN.BDCODEMP, FN.BDCODEMP, FN.BDCODCOL, ' ;
               /* 199696  25/04/2024 Isabella  alterado IR para apresentar por pagamento; antes apresentava por competencia da folha
                          por pagamento carega apenas verbas de IR; 
                          por competencia TODAS exceto as de IR                          
                          procedure SP_VRH_RELATORIOCUSTOCOL_7186 que chama esta carrega com os dois parametros:  prpagto = 0 UNION prpagto = 1  
   foi corrigida alteração de  apresentar apenas o ultimo centro de custo da competencia filtrada e nao mais valores por centro de custo*/

               if (prpagto = 0) then
                    wSql = wSQl || ' FN.BDREFFN,  FN.BDVALVFN ,  Coalesce(prepf.BDCODCENTRO, 0) bdcodcentro, Coalesce(prepf.bdcodtpcc, 0) bdcodtpcc, (COALESCE(BDFGTSFN,0) + COALESCE(BDFGTSFEFN,0) + COALESCE(BDFGTS13FN,0)) BDFGTS, (COALESCE(BDBASEPISFN,0) + COALESCE(BDBASEPISFEFN,0) + COALESCE(BDBASEPIS13FN, 0)) BDBASEPIS, ';
               else
                    wSql = wSQl || ' FOL.BDREFIRRFESOCIAL BDREFFN,   FN.BDVALVFN, Coalesce(prepf.BDCODCENTRO, 0) bdcodcentro, Coalesce(prepf.bdcodtpcc, 0) bdcodtpcc , 0 BDFGTS, 0 BDBASEPIS, ';

               wSql = wSql ||
                      ' 0 bdtipocalc,  FN.BDVALVFN BDREFAUX, FOL.BDREFIRRFESOCIAL BDREFPAG,0 BDORDEM ' ||               /*166040 - André Cursino - 22/11/2022*/
                      ' from VRHF_EMP_TVERBAFN FN '||
                      ' JOIN VRHF_EMP_TFOLHANORMAL FOL ON (FN.BDCODEMP = FOL.BDCODEMP AND FN.BDCODCOL = FOL.BDCODCOL AND FN.BDREFFN = FOL.BDREFFN) ' ||
                      ' left outer join VRHF_EMP_TPREPFN prepf on prepf.BDCODEMP = FOL.BDCODEMP and prepf.BDCODCOL = FOL.BDCODCOL and prepf.BDDATAENTRADA = ' ||
                      '                                             ( SELECT FIRST 1 X.BDDATAENTRADA FROM VRHF_EMP_TPREPFN X ' ||
                     '                                              WHERE X.BDCODEMP = FOL.BDCODEMP and X.BDCODCOL = FOL.BDCODCOL AND X.BDREFENTRADA <= '||prrefini||' ORDER BY X.BDDATAENTRADA DESC) ' ;
        
               if (prpagto = 0) then
                    wsql = wsql||' WHERE (FOL.BDREFFN = '||prrefini||') ' ;
               else
                    wsql = wsql||' WHERE (FOL.BDREFIRRFESOCIAL <> FOL.BDREFFN)  ' ||
                                    ' and (FOL.BDREFIRRFESOCIAL = '||prrefini||')  ' ||
                                    '   and ((select first 1 SUBSTRING(VERB.BDCLAVER FROM 1 FOR 7) from VRH_BASE_TVERBAS_REF REF join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = REF.BDCODVER) ' ||
                                    '         where REF.BDCODVER = FN.BDCODVER and REF.BDREFVER <= FOL.BDREFIRRFESOCIAL  order by REF.BDREFVER DESC ) = ''9.010.1'') ' ||
                                    '   and ((select first 1 SUBSTRING(VERB.BDCLAVER FROM 1 FOR 9) from VRH_BASE_TVERBAS_REF REF join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = REF.BDCODVER) ' ||
                                    '         where REF.BDCODVER = FN.BDCODVER and REF.BDREFVER <= FOL.BDREFIRRFESOCIAL  order by REF.BDREFVER DESC ) <> ''9.010.1.2'') ';
        
               if (premp is not null) then
                  wsql = wsql||' and '||replace(premp, 'BDCODEMP', 'FOL.BDCODEMP');
               if ((prcol is not null) and (prcol <> '')) then
                   wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FOL.BDCODCOL');
        
               for execute statement wSql into :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :bdcodcentro, :bdcodtpcc, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :BDREFFNAUX, :BDREFPAG, :bdordem do
                 begin
                   suspend;
                 end
          end

       wSql = 'select 0 BDTIPOCOL, FNT.BDCODVER, FNT.BDCODEMP, FNT.BDCODEMP, FNT.BDCODCOL,  ' ;
               if (prpagto = 0) then
                    wSql = wSQl || ' FNT.BDREFTOMADOR BDREFFN,  FNT.BDVALVFT  BDVALVFN, ' ||
                                   '  Coalesce(prepft.BDCODCENTRO, 0) bdcodcentro, Coalesce(prepft.bdcodtpcc, 0) bdcodtpcc, '||
                                   ' (COALESCE(BDFGTSFT,0) + COALESCE(BDFGTSFEFT,0) + COALESCE(BDFGTS13FT,0)) BDFGTS, (COALESCE(BDBASEPISFT,0) + COALESCE(BDBASEPISFEFT,0) + COALESCE(BDBASEPIS13FT, 0)) BDBASEPIS, ';
               else
                    wSql = wSQl || ' FOLFT.BDREFIRRFESOCIAL BDREFFN,    FNT.BDVALVFT  BDVALVFN,  ' ||
                                   '  Coalesce(prepft.BDCODCENTRO, 0) bdcodcentro, Coalesce(prepft.bdcodtpcc, 0) bdcodtpcc, '||
                                   '  0 BDFGTS, 0 BDBASEPIS, ';


               wSql = wSql ||
              ' 0 bdtipocalc, FNT.BDREFTOMADOR BDREFAUX,  FOLFT.BDREFIRRFESOCIAL BDREFPAG ,FOLFT.bdordem ' ||
              ' from VRHF_EMP_TVERBATOMADOR FNT '||
              '  JOIN VRHF_EMP_TFOLHATOMADOR FOLFT ON (FNT.BDCODEMP = FOLFT.BDCODEMP AND FNT.BDCODCOL = FOLFT.BDCODCOL AND FNT.BDREFTOMADOR = FOLFT.BDREFTOMADOR AND FNT.BDORDEM = FOLFT.BDORDEM) '||
              ' left outer join VRHF_EMP_TPREPFN prepft on prepft.BDCODEMP = FOLFT.BDCODEMP and prepft.BDCODCOL = FOLFT.BDCODCOL and prepft.BDDATAENTRADA = ' ||
              '                                             ( SELECT FIRST 1 X.BDDATAENTRADA FROM VRHF_EMP_TPREPFN X ' ||
              '                                              WHERE X.BDCODEMP = FOLFT.BDCODEMP and X.BDCODCOL = FOLFT.BDCODCOL AND X.BDREFENTRADA <= '||prrefini||' ORDER BY X.BDDATAENTRADA DESC) ' ;


               if (prpagto = 0) then
                    wsql = wsql||' WHERE (FOLFT.BDREFTOMADOR = '||prrefini||') ' ;
               else
                    wsql = wsql||' WHERE  (FOLFT.BDREFIRRFESOCIAL <> FOLFT.BDREFTOMADOR ) ' ||
                                    ' and (FOLFT.BDREFIRRFESOCIAL = '||prrefini||') ' ||
                                    '   and ((select first 1 SUBSTRING(VERB.BDCLAVER FROM 1 FOR 7) from VRH_BASE_TVERBAS_REF REF join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = REF.BDCODVER) ' ||
                                    '         where REF.BDCODVER = FNT.BDCODVER and REF.BDREFVER <= FOLFT.BDREFIRRFESOCIAL  order by REF.BDREFVER DESC ) = ''9.010.1'') ' ||
                                    '   and ((select first 1 SUBSTRING(VERB.BDCLAVER FROM 1 FOR 9) from VRH_BASE_TVERBAS_REF REF join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = REF.BDCODVER) ' ||
                                    '         where REF.BDCODVER = FNT.BDCODVER and REF.BDREFVER <= FOLFT.BDREFIRRFESOCIAL  order by REF.BDREFVER DESC ) <> ''9.010.1.2'') ';


       if (premp is not null) then
          wsql = wsql||' and '||replace(premp, 'BDCODEMP', 'FOLFT.BDCODEMP');

       if ((prcol is not null) and (prcol <> '')) then
          wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FOLFT.BDCODCOL');

       if ((prcc is not null) and (prcc <> '')) then
          wsql = wsql||' and '||replace(prcc, 'BDCODTPCC', 'prepft.BDCODTPCC');


       for execute statement wSql into :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDCODCENTRO, :bdcodtpcc, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :BDREFFNAUX, :BDREFPAG,:BDORDEM  do
         suspend;
     

     /*166040 - André Cursino - 31/10/2022 - inicio*/
       IF (w13 = 1) THEN
         BEGIN
           wSql = 'SELECT 0 BDTIPOCOL, V13.BDCODVER, V13.BDCODEMP, V13.BDCODEMP, V13.BDCODCOL,  ' ;
               if (prpagto = 0) then
                    wSql = wSQl || ' V13.BDREF13 BDREFFN, V13.BDVALV13 BDVALVFN, ' ||
                                   '  COALESCE(PREP13.BDCODCENTRO, 0) BDCOCENTRO, COALESCE(PREP13.BDCODTPCC, 0) BDCODTPCC, ' ||
                                   '  COALESCE(C13.BDFGTS13, 0) BDFGTS, COALESCE(C13.BDBASEPIS13, 0) BDBASEPIS,';
               else
                    wSql = wSQl || ' C13.BDREFIRRFESOCIAL BDREFFN,  V13.BDVALV13  BDVALVFN, ' ||
                                   '  COALESCE(PREP13.BDCODCENTRO, 0) BDCOCENTRO, COALESCE(PREP13.BDCODTPCC, 0) BDCODTPCC, ' ||
                                   '  0 BDFGTS, 0 BDBASEPIS, ';

               wSql = wSql ||
                  ' 1 bdtipocalc, V13.BDREF13 BDREFAUX, C13.BDREFIRRFESOCIAL BDREFPAG, 0 BDORDEM ' ||
                  'FROM VRHF_EMP_TVERBA13 V13 ' ||
                  'JOIN VRHF_EMP_T13SAL C13 ON (V13.BDCODEMP = C13.BDCODEMP AND ' ||
                  '      V13.BDCODCOL = C13.BDCODCOL AND ' ||
                  '      V13.BDREF13 = C13.BDREF13) ' ||
                  'LEFT JOIN VRHF_EMP_TPREPFN PREP13 ON C13.BDCODEMP = PREP13.BDCODEMP AND ' ||
                  '      C13.BDCODCOL = PREP13.BDCODCOL and PREP13.BDDATAENTRADA = ' ||
                  '                                             ( SELECT FIRST 1 X.BDDATAENTRADA FROM VRHF_EMP_TPREPFN X ' ||
                  '                                              WHERE X.BDCODEMP = C13.BDCODEMP and X.BDCODCOL = C13.BDCODCOL AND X.BDREFENTRADA <= '||prrefini||' ORDER BY X.BDDATAENTRADA DESC) ' ;

    
               if (prpagto = 0) then
                    wsql = wsql||' WHERE (V13.BDREF13 = '||prrefini||') ';
               else

                    wsql = wsql||' WHERE (C13.BDREFIRRFESOCIAL <> V13.BDREF13)' ||
                                    ' and (C13.BDREFIRRFESOCIAL = '||prrefini||')' ||
                                    '   and (select first 1 SUBSTRING(VERB.BDCLAVER FROM 1 FOR 7) from VRH_BASE_TVERBAS_REF REF join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = REF.BDCODVER) ' ||
                                    '         where REF.BDCODVER = V13.BDCODVER and REF.BDREFVER <= C13.BDREFIRRFESOCIAL  order by REF.BDREFVER DESC ) = ''9.010.1'' ';

           IF (premp IS NOT NULL) THEN
             wsql = wsql||' and '||REPLACE(premp, 'BDCODEMP', 'C13.BDCODEMP');
           IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
             wsql = wsql||' and '||REPLACE(prcol, 'BDCODCOL', 'C13.BDCODCOL');
           IF ((prcc IS NOT NULL) AND (prcc <> '')) THEN
             wsql = wsql||' and '||REPLACE(prcc, 'BDCODTPCC', 'PREP13.BDCODTPCC');

           FOR EXECUTE STATEMENT wSql INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDCODCENTRO, :bdcodtpcc, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :bdreffnAux, :BDREFPAG, :bdordem DO
             begin
               suspend;
             end
         
           /*172204 - André Cursino - 09/01/2023 - inicio*/
           wSql = 'select 0 BDTIPOCOL, VC13.BDCODVER, VC13.BDCODEMP, VC13.BDCODEMP, VC13.BDCODCOL,   ' ;
               if (prpagto = 0) then
                    wSql = wSQl || ' VC13.BDREFC13 BDREFFN,  VC13.BDVALVC13  BDVALVFN , ' ||
                                   '  coalesce(PREPC13.BDCODCENTRO, 0) BDCOCENTRO, coalesce(PREPC13.BDCODTPCC, 0) BDCODTPCC, ' ||
                                   '  coalesce(CC13.BDFGTSC13, 0) BDFGTS, coalesce(CC13.BDBASEPISC13, 0) BDBASEPIS, ';
               else
                    wSql = wSQl || ' CC13.BDREFIRRFESOCIAL BDREFFN, VC13.BDVALVC13  BDVALVFN,  ' ||
                                   '  coalesce(PREPC13.BDCODCENTRO, 0) BDCOCENTRO, coalesce(PREPC13.BDCODTPCC, 0) BDCODTPCC, ' ||
                                   '  0 BDFGTS, 0 BDBASEPIS, ';

               wSql = wSql ||
                  '       5 BDTIPOCALC, VC13.BDREFC13 BDREFAUX, CC13.BDREFIRRFESOCIAL BDREFPAG, CC13.BDORDEM  ' ||
                  'from VRHF_EMP_TVERBAC13 VC13 ' ||
                  'join VRHF_EMP_TC13SAL CC13 on (VC13.BDCODEMP = CC13.BDCODEMP and ' ||
                  '      VC13.BDCODCOL = CC13.BDCODCOL and ' ||
                  '      VC13.BDREF13 = CC13.BDREF13) ' ||
                  'left join VRHF_EMP_TPREPFN PREPC13 on CC13.BDCODEMP = PREPC13.BDCODEMP and ' ||
                  '      CC13.BDCODCOL = PREPC13.BDCODCOL and PREPC13.BDDATAENTRADA = ' ||
                  '                                             ( SELECT FIRST 1 X.BDDATAENTRADA FROM  VRHF_EMP_TPREPFN  X ' ||
                  '                                              WHERE X.BDCODEMP = CC13.BDCODEMP and X.BDCODCOL = CC13.BDCODCOL AND X.BDREFENTRADA <= '||prrefini||' ORDER BY X.BDDATAENTRADA DESC) ' ;



               if (prpagto = 0) then
                    wsql = wsql||' WHERE (VC13.BDREFC13 = '||prrefini||') ';
               else
                    wsql = wsql||' WHERE (CC13.BDREFIRRFESOCIAL <> VC13.BDREFC13) ' ||
                                    ' and (CC13.BDREFIRRFESOCIAL = '||prrefini||') ' ||
                                    '   and (select first 1 SUBSTRING(VERB.BDCLAVER FROM 1 FOR 7) from VRH_BASE_TVERBAS_REF REF join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = REF.BDCODVER) ' ||
                                    '         where REF.BDCODVER = VC13.BDCODVER and REF.BDREFVER <= CC13.BDREFIRRFESOCIAL  order by REF.BDREFVER DESC ) = ''9.010.1'' ';

           IF (premp IS NOT NULL) THEN
             wsql = wsql||' and '||REPLACE(premp, 'BDCODEMP', 'CC13.BDCODEMP');
           IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
             wsql = wsql||' and '||REPLACE(prcol, 'BDCODCOL', 'CC13.BDCODCOL');
           IF ((prcc IS NOT NULL) AND (prcc <> '')) THEN
             wsql = wsql||' and '||REPLACE(prcc, 'BDCODTPCC', 'PREPC13.BDCODTPCC');

           FOR EXECUTE STATEMENT wSql INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDCODCENTRO, :bdcodtpcc, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :bdreffnAux, :BDREFPAG, :BDORDEM DO
             begin
               suspend;
             end
           /*172204 - André Cursino - 09/01/2023 - fim*/
     end

       wSql = 'SELECT 0 BDTIPOCOL, VA13.BDCODVER, VA13.BDCODEMP, VA13.BDCODEMP, VA13.BDCODCOL,   ' ;
               if (prpagto = 0) then
                    wSql = wSQl || ' VA13.BDREFA13 BDREFFN,  VA13.BDVALVA13 BDVALVFN, ' ||
                                   '       COALESCE(PREPA13.BDCODCENTRO, 0) BDCOCENTRO, COALESCE(PREPA13.BDCODTPCC, 0) BDCODTPCC, ' ||
                                   '       COALESCE(CA13.BDFGTSA13, 0) BDFGTS, COALESCE(CA13.BDBASEPISA13, 0) BDBASEPIS, ';
               else
                    wSql = wSQl || ' CA13.BDREFIRRFESOCIAL BDREFFN, VA13.BDVALVA13 BDVALVFN,' ||
                                   '       COALESCE(PREPA13.BDCODCENTRO, 0) BDCOCENTRO, COALESCE(PREPA13.BDCODTPCC, 0) BDCODTPCC, ' ||
                                   '       0 BDFGTS, 0 BDBASEPIS, ';

               wSql = wSql || '  2 bdtipocalc, VA13.BDREFA13 BDREFAUX, CA13.BDREFIRRFESOCIAL BDREFPAG, CA13.bdordem ' ||
              'FROM VRHF_EMP_TVERBAA13 VA13 ' ||
              'JOIN VRHF_EMP_TA13SAL CA13 ON (VA13.BDCODEMP = CA13.BDCODEMP AND ' ||
              '      VA13.BDCODCOL = CA13.BDCODCOL AND ' ||
              '      VA13.BDREFA13 = CA13.BDREFA13) ' ||
              'LEFT JOIN VRHF_EMP_TPREPFN PREPA13 ON CA13.BDCODEMP = PREPA13.BDCODEMP AND ' ||
              '      CA13.BDCODCOL = PREPA13.BDCODCOL and PREPA13.BDDATAENTRADA = ' ||
                  '                                             ( SELECT FIRST 1 X.BDDATAENTRADA FROM VRHF_EMP_TPREPFN X ' ||
                  '                                              WHERE X.BDCODEMP = CA13.BDCODEMP and X.BDCODCOL = CA13.BDCODCOL AND X.BDREFENTRADA <= '||prrefini||' ORDER BY X.BDDATAENTRADA DESC) ' ;



               if (prpagto = 0) then
                    wsql = wsql||' WHERE (VA13.BDREFA13 = '||prrefini||')  ' ;
               else
                    wsql = wsql||' WHERE (CA13.BDREFIRRFESOCIAL  <> VA13.BDREFA13 ) ' ||
                                    ' and (CA13.BDREFIRRFESOCIAL = '||prrefini||')  ' ||
                                    '   and (select first 1 SUBSTRING(VERB.BDCLAVER FROM 1 FOR 7) from VRH_BASE_TVERBAS_REF REF join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = REF.BDCODVER) ' ||
                                    '         where REF.BDCODVER = VA13.BDCODVER and REF.BDREFVER <= CA13.BDREFIRRFESOCIAL  order by REF.BDREFVER DESC ) = ''9.010.1'' ';

       IF (premp IS NOT NULL) THEN
         wsql = wsql||' and '||REPLACE(premp, 'BDCODEMP', 'CA13.BDCODEMP');
       IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
         wsql = wsql||' and '||REPLACE(prcol, 'BDCODCOL', 'CA13.BDCODCOL');
       IF ((prcc IS NOT NULL) AND (prcc <> '')) THEN
         wsql = wsql||' and '||REPLACE(prcc, 'BDCODTPCC', 'PREPA13.BDCODTPCC');

       FOR EXECUTE STATEMENT wSql INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDCODCENTRO, :bdcodtpcc, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :bdreffnAux, :BDREFPAG, :bdordem DO
         SUSPEND;


       --complementar folha normal
       if (prpagto = 0) then
            begin
               wsql = 'select 0 BDTIPOCOL, VFC.BDCODVER, VFC.BDCODEMP, VFC.BDCODEMP, VFC.BDCODCOL, CFC.bdrefcomp, ' ||
                      '      VFC.BDVALVFC BDVALVFN, ' ||
                      '      (coalesce(CFC.BDFGTSFC, 0) + coalesce(CFC.BDFGTSFEFC, 0) + coalesce(CFC.BDFGTS13FC, 0)) BDFGTS, ' ||
                      '      (coalesce(CFC.BDBASEPISFC, 0) + coalesce(CFC.BDBASEPISFEFC, 0) + coalesce(CFC.BDBASEPIS13FC, 0)) BDBASEPIS, 0 BDCODCENTRO, 0 BDCODTPCC, ' ||
                      '      Case when BDCODACCONV IS NOT NULL then  3 else 4 end bdtipocalc, CFC.bdreffn bdreffnAux, CFC.bdrefcomp BDREFPAG, 0 BDORDEM ' ||
                      'from VRHF_EMP_TVERBAFC VFC ' ||
                      'join VRHF_EMP_TFOLHACOMP CFC on (VFC.BDCODEMP = CFC.BDCODEMP and ' ||
                      '     VFC.BDCODCOL = CFC.BDCODCOL and ' ||
                      '     VFC.BDREFFN = CFC.BDREFFN and ' ||
                      '     VFC.BDREFFC = CFC.BDREFFC and ';

               wWhereCompNormal = ' VFC.BDREFCOMP = ' || CAST(prrefini AS VARCHAR(6)) ||' and ' ||
                                  ' ((CFC.BDREFVINCFN IS NULL) OR (CFC.BDREFVINCFN = 0))) and CFC.BDCODACCONV is null ';
               wWhereCompADC = ' SUBSTRING(CAST(VFC.BDREFFC AS VARCHAR(8)) FROM 1 FOR 6) = ' || '''' || CAST(prrefini AS VARCHAR(6)) || '''' || ' AND ' ||
                               'CFC.BDCODTIPOFC = 3 AND ' ||
                               'CFC.BDCODACCONV IS NOT NULL AND ' ||
                               '((CFC.BDREFVINCFN IS NULL) OR (CFC.BDREFVINCFN = 0))) ';


               IF (premp IS NOT NULL) THEN
                  wWhere = REPLACE(premp, 'BDCODEMP', 'CFC.BDCODEMP');
               IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
                 BEGIN
                   IF (TRIM(wWhere) <> '') THEN
                     wWhere = wWhere||' and ';
                   wWhere = wWhere || REPLACE(prcol, 'BDCODCOL', 'CFC.BDCODCOL');
                 END

               IF (TRIM(wWhere) <> '') THEN
                 wWhere = 'Where ' || wWhere;

               wSqlCompNormal = wSql || wWhereCompNormal || wWhere;
               wSqlCompADC = wSql || wWhereCompADC || wWhere;

               FOR EXECUTE STATEMENT wSqlCompNormal INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDFGTS, :BDBASEPIS, :bdcodcentro, :bdcodtpcc, :BDTIPOCALC, :bdreffnAux, :BDREFPAG, :bdordem DO
                 SUSPEND;

               FOR EXECUTE STATEMENT wSqlCompADC INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDFGTS, :BDBASEPIS, :bdcodcentro, :bdcodtpcc, :BDTIPOCALC, :bdreffnAux, :BDREFPAG, :bdordem DO
                 SUSPEND;
     end

      --complementar tomador
    if (prpagto = 0) then
        begin
                wsql = 'select 0 BDTIPOCOL, VFCT.BDCODVER, VFCT.BDCODEMP, VFCT.BDCODEMP, VFCT.BDCODCOL, VFCT.bdrefcomp, ' ||
                          '      VFCT.BDVALVFC BDVALVFN, coalesce(PREPFCT.BDCODCENTRO, 0) BDCODCENTRO, coalesce(PREPFCT.BDCODTPCC, 0) BDCODTPCC, ' ||
                          '      (coalesce(CFCT.BDFGTSFC, 0) + coalesce(CFCT.BDFGTSFEFC, 0) + coalesce(CFCT.BDFGTS13FC, 0)) BDFGTS, ' ||
                          '      (coalesce(CFCT.BDBASEPISFC, 0) + coalesce(CFCT.BDBASEPISFEFC, 0) + coalesce(CFCT.BDBASEPIS13FC, 0)) BDBASEPIS, ' ||
                          '      Case when BDCODACCONV IS NOT NULL then  3 else 4 end bdtipocalc, VFCT.bdreftomador BDREFAUX, VFCT.bdrefcomp BDREFPAG,CFCT.bdordem  ' ||
                          'from VRHF_EMP_TVERBAFCTOMADOR VFCT ' ||
                          'join VRHF_EMP_TFOLTOMCOMP CFCT on (VFCT.BDCODEMP = CFCT.BDCODEMP and ' ||
                          '     VFCT.BDCODCOL = CFCT.BDCODCOL and ' ||
                          '     VFCT.BDORDEM = CFCT.BDORDEM and ' ||
                          '     VFCT.BDREFTOMADOR = CFCT.BDREFTOMADOR and ' ||
                          '     VFCT.BDREFFC = CFCT.BDREFFC and ';

                   wWhereCompNormal = REPLACE(wWhereCompNormal, 'VFC.', 'VFCT.');
                   wWhereCompNormal = REPLACE(wWhereCompNormal, 'CFC.', 'CFCT.');
                   wWhereCompNormal = REPLACE(wWhereCompNormal, 'BDREFFN', 'BDREFCOMP');

                   wWhereCompADC = REPLACE(wWhereCompADC, 'CFC.', 'CFCT.');
                   wWhereCompADC = REPLACE(wWhereCompADC, 'VFC.', 'VFCT.');
                   wWhereCompADC = REPLACE(wWhereCompADC, 'BDREFFN', 'BDREFCOMP');

                   wJoinCC = ' left join VRHF_EMP_TPREPFN PREPFCT on CFCT.BDCODEMP = PREPFCT.BDCODEMP and CFCT.BDCODCOL = PREPFCT.BDCODCOL and  PREPFCT.BDDATAENTRADA = ' ||
                              '                                             ( SELECT FIRST 1 X.BDDATAENTRADA FROM VRHF_EMP_TPREPFN X ' ||
                              '                                              WHERE X.BDCODEMP = CFCT.BDCODEMP and X.BDCODCOL = CFCT.BDCODCOL AND X.BDREFENTRADA <= '||prrefini||' ORDER BY X.BDDATAENTRADA DESC) ' ;


                   IF (premp IS NOT NULL) THEN
                      wWhere = REPLACE(premp, 'BDCODEMP', 'CFCT.BDCODEMP');
                   IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
                     BEGIN
                       IF (TRIM(wWhere) <> '') THEN
                         wWhere = wWhere||' and ';
                       wWhere = wWhere || REPLACE(prcol, 'BDCODCOL', 'CFCT.BDCODCOL');
                     END
                   IF ((prcc IS NOT NULL) AND (prcc <> '')) THEN
                     BEGIN
                       IF (TRIM(wWhere) <> '') THEN
                         wWhere = wWhere||' and ';
                       wWhere = wWhere || REPLACE(prcc, 'BDCODTPCC', 'PREPFCT.BDCODTPCC');
                     END

                   IF (TRIM(wWhere) <> '') THEN
                     wWhere = 'Where ' || wWhere;

                   wSqlCompNormal = wSql || wWhereCompNormal || wJoinCC || wWhere;
                   wSqlCompADC = wSql || wWhereCompADC || wJoinCC || wWhere;

                   FOR EXECUTE STATEMENT wSqlCompNormal INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDCODCENTRO, :bdcodtpcc, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :bdreffnAux, :BDREFPAG, :bdordem DO
                     SUSPEND;

                   FOR EXECUTE STATEMENT wSqlCompADC INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDCODCENTRO, :bdcodtpcc, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :bdreffnAux, :BDREFPAG, :bdordem DO
                     SUSPEND;


        end

     end

  if (coalesce(PRAUT,'') <> 'NENHUM') then
     begin
      wSql = '  select 2 BDTIPOCOL, VTER.BDCODVER, VTER.BDCODEMP, VTER.BDCODEMP, VTER.bdcodter,   ' ;
               if (prpagto = 0) then
                    wSql = wSQl || '  SERV.bdrefserv BDREFFN, case when (select first 1 SUBSTRING(VERB.BDCLAVER FROM 1 FOR 7) from VRH_BASE_TVERBAS_REF REF join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = REF.BDCODVER) ' ||
                                   '                                                where REF.BDCODVER = VTER.BDCODVER and REF.BDREFVER <= SERV.BDREFPAGSERV   order by REF.BDREFVER DESC ) <> ''9.010.1'' ' ||
                                   '                                   then 0 else VTER.bdvalor end BDVALVFN, '    ||
                                   '   Coalesce(serv.BDCODCENTRO, 0), Coalesce(serv.bdcodtpcc, 0), 0 BDFGTS, 0 BDBASEPIS, ';
               else
                    wSql = wSQl || ' SERV.BDREFPAGSERV BDREFFN, case when (select first 1 SUBSTRING(VERB.BDCLAVER FROM 1 FOR 7) from VRH_BASE_TVERBAS_REF REF join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = REF.BDCODVER) ' ||
                                   '                                                where REF.BDCODVER = VTER.BDCODVER and REF.BDREFVER <= SERV.BDREFPAGSERV   order by REF.BDREFVER DESC ) = ''9.010.1'' ' ||
                                   '                                   then VTER.bdvalor else 0 end BDVALVFN, 0 bdcodcentro , 0 bdcodtpcc, 0 BDFGTS, 0 BDBASEPIS, ';

               wSql = wSql ||
             '   4 bdtipocalc, SERV.bdrefserv BDREFAUX, SERV.BDREFPAGSERV BDREFPAG  ' ||                       /*166040 - André Cursino - 22/11/2022*/
             ' from VRHF_BASE_ITEMS_CALCTERC VTER '||
             '  JOIN VRHF_BASE_CALC_TERC TER ON (VTER.BDCODEMP = TER.BDCODEMP AND VTER.bdcodter = TER.bdcodter AND VTER.bdcodserv = TER.bdcodserv) '||
             '  join VRH_BASE_TSERVTERC SERV on (VTER.BDCODEMP = SERV.BDCODEMP AND VTER.bdcodter = SERV.bdcodter AND VTER.bdcodserv = SERV.bdcodserv) ';

               if (prpagto = 0) then
                    wsql = wsql||' WHERE ( SERV.bdrefserv = '||prrefini||') ';
               else
                    wsql = wsql||' WHERE (SERV.BDREFPAGSERV  <> SERV.bdrefserv ) ' ||
                                 ' and (SERV.BDREFPAGSERV = '||prrefini||') ';

       if (premp is not null) then
          wsql = wsql||' and '||replace(premp, 'BDCODEMP', 'VTER.BDCODEMP');

       if ((PRAUT is not null) and (PRAUT <> '') and (PRAUT <> 'NENHUM')) then
         wsql = wsql||' and '||replace(PRAUT, 'BDCODTER', 'VTER.BDCODTER');

       if ((prcc is not null) and (prcc <> '')) then
          wsql = wsql||' and '||replace(prcc, 'BDCODTPCC', 'SERV.BDCODTPCC');

       for execute statement wSql into :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :bdcodcol, :BDREFFN, :BDVALVFN, :BDCODCENTRO, :bdcodtpcc, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :bdreffnAux, :BDREFPAG do
         begin
           suspend;
         end
     end
end^




create or alter procedure SP_VRH_REL_CUSTOCOL_RCONF_CALC (
    PREMP varchar(10000),
    PRCOL varchar(20000),
    PRAUT varchar(10000),
    PRREFINI integer,
    PRAGRUPACC integer,
    PRCC varchar(5000) = '' /* COLLATE WIN1252 - default */ )
returns (
    BDCODEMP integer,
    BDREFFN integer,
    BDTIPOCOL integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDVALVFN numeric(15,2),
    BDCODFILIAL integer,
    BDFGTS numeric(15,2),
    BDBASEPIS numeric(15,2),
    BDTIPOCALC integer,
    BDREFFNAUX integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
declare variable WSQL varchar(32000);
declare variable W13 integer = 0;
declare variable WANO13 integer = 0;
declare variable WSQLCOMPNORMAL varchar(2000);
declare variable WWHERECOMPNORMAL varchar(2000);
declare variable WWHERECOMPADC varchar(2000);
declare variable WSQLCOMPADC varchar(2000);
declare variable WWHERE varchar(200);
declare variable WSQLJOIN varchar(200);
begin

  /* Procedure Text */
  premp = upper(premp);
  prcol = upper(prcol);
  praut = upper(praut);
  wWhere = '';
  wSqlJoin = '';

  /*166040 - André Cursino - 31/10/2022 - inicio*/
  IF (SUBSTRING(CAST(prrefini AS VARCHAR(6)) FROM 5 FOR 2) = 12) THEN
    w13 = 1;

  wAno13 = cast(SUBSTRING(CAST(prrefini AS VARCHAR(6)) FROM 1 FOR 4) as integer);
  /*166040 - André Cursino - 31/10/2022 - fim*/

  if (coalesce(PRCOL,'') <> 'NENHUM') then
     begin
       if ((prcc is null) or (prcc = '')) then
          begin
               wSql = 'select 0 BDTIPOCOL, FN.BDCODVER, FN.BDCODEMP, FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFN, FN.BDVALVFN, (COALESCE(BDFGTSFN,0) + COALESCE(BDFGTSFEFN,0) + COALESCE(BDFGTS13FN,0)) BDFGTS, (COALESCE(BDBASEPISFN,0) + COALESCE(BDBASEPISFEFN,0) + COALESCE(BDBASEPIS13FN, 0)) BDBASEPIS, '||
                      ' 0 bdtipocalc, fol.bdreffn,0 BDORDEM, 0 BDCODCENTRO, 0 BDCODTPCC ' ||               /*166040 - André Cursino - 22/11/2022*/
                      ' from VRHF_EMP_TVERBAFN FN '||
                      ' LEFT JOIN VRHF_EMP_TFOLHANORMAL FOL ON (FN.BDCODEMP = FOL.BDCODEMP AND FN.BDCODCOL = FOL.BDCODCOL AND FN.BDREFFN = FOL.BDREFFN) '||
                      ' WHERE FOL.BDREFFN = '||prrefini;
        
               if (premp is not null) then
                  wsql = wsql||' and '||replace(premp, 'BDCODEMP', 'FOL.BDCODEMP');
               if ((prcol is not null) and (prcol <> '')) then
                   wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FOL.BDCODCOL');
        
               for execute statement wSql into :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN,  :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :BDREFFNAUX, :bdordem,
                                               :BDCODCENTRO, :BDCODTPCC do
                 begin
                   BDREFFNAUX = 0;
                   suspend;
                 end
          end

       wSql = 'select 0 BDTIPOCOL, FNT.BDCODVER, FNT.BDCODEMP, FNT.BDCODEMP, FNT.BDCODCOL, FNT.BDREFTOMADOR BDREFFN, FNT.BDVALVFT BDVALVFN, (COALESCE(BDFGTSFT,0) + COALESCE(BDFGTSFEFT,0) + COALESCE(BDFGTS13FT,0)) BDFGTS, (COALESCE(BDBASEPISFT,0) + COALESCE(BDBASEPISFEFT,0) + COALESCE(BDBASEPIS13FT, 0)) BDBASEPIS, '||
              ' 0 bdtipocalc, FOLFT.bdreftomador,FOLFT.bdordem, ' ;

      if (pragrupacc = 0)  then
         wSql = wSql || '  0 BDCODCENTRO, 0 BDCODTPCC   ';
      else
         wSql = wSql || '  prepft.BDCODCENTRO, prepft.BDCODTPCC   ';


      wSql = wSql || ' from VRHF_EMP_TVERBATOMADOR FNT ' ||
                     ' LEFT JOIN VRHF_EMP_TFOLHATOMADOR FOLFT ON (FNT.BDCODEMP = FOLFT.BDCODEMP AND FNT.BDCODCOL = FOLFT.BDCODCOL AND FNT.BDREFTOMADOR = FOLFT.BDREFTOMADOR AND FNT.BDORDEM = FOLFT.BDORDEM) ';
              

      if ((pragrupacc = 1) or (prcc is not null) and (prcc <> ''))  then
             wSql = wSql || ' left outer join VRHF_EMP_TPREPFN prepft on prepft.BDCODEMP = FOLFT.BDCODEMP and prepft.BDCODCOL = FOLFT.BDCODCOL and prepft.BDORDEM = FOLFT.BDORDEM' ;

       wsql = wsql||' WHERE FOLFT.BDREFTOMADOR = '||prrefini;

       if (premp is not null) then
          wsql = wsql||' and '||replace(premp, 'BDCODEMP', 'FOLFT.BDCODEMP');

       if ((prcol is not null) and (prcol <> '')) then
          wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FOLFT.BDCODCOL');
       IF ((prcc IS NOT NULL) AND (prcc <> '')) THEN
         BEGIN
           IF (TRIM(wWhere) <> '') THEN
             wWhere = wWhere||' and ';
           wWhere = wWhere || REPLACE(prcc, 'BDCODTPCC', 'PREPFT.BDCODTPCC');
         END
       for execute statement wSql into :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN,  :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :BDREFFNaUX,:BDORDEM,
                                               :BDCODCENTRO, :BDCODTPCC do
         suspend;


       IF (w13 = 1) THEN
         BEGIN
           wSql = 'SELECT 0 BDTIPOCOL, V13.BDCODVER, V13.BDCODEMP, V13.BDCODEMP, V13.BDCODCOL, V13.BDREF13 BDREFFN, V13.BDVALV13 BDVALVFN, ' ||
                  '       COALESCE(C13.BDFGTS13, 0) BDFGTS, ' ||
                  '       COALESCE(C13.BDBASEPIS13, 0) BDBASEPIS, 1 bdtipocalc, 0 BDORDEM, ' ;

      if (pragrupacc = 0)  then
         wSql = wSql || '  0 BDCODCENTRO, 0 BDCODTPCC   ';
      else
         wSql = wSql || '  prep13.BDCODCENTRO, prep13.BDCODTPCC   ';


      wSql = wSql || 'FROM VRHF_EMP_TVERBA13 V13 ' ||
                  'JOIN VRHF_EMP_T13SAL C13 ON (V13.BDCODEMP = C13.BDCODEMP AND ' ||
                  '      V13.BDCODCOL = C13.BDCODCOL AND ' ||
                  '      V13.BDREF13 = C13.BDREF13) ';
      if ((pragrupacc = 1) or (prcc is not null) and (prcc <> ''))  then
             wSql = wSql || 'LEFT JOIN VRHF_EMP_TPREPFN PREP13 ON C13.BDCODEMP = PREP13.BDCODEMP AND ' ||
                  '      C13.BDCODCOL = PREP13.BDCODCOL and PREP13.BDDATAENTRADA = ' ||
                  '                                             ( SELECT FIRST 1 X.BDDATAENTRADA FROM VRHF_EMP_TPREPFN X ' ||
                  '                                              WHERE X.BDCODEMP = C13.BDCODEMP and X.BDCODCOL = C13.BDCODCOL AND X.BDREFENTRADA <= '||prrefini||' ORDER BY X.BDDATAENTRADA DESC) ' ;

           wsql = wsql||' WHERE V13.BDREF13 = '||prrefini;
    
           IF (premp IS NOT NULL) THEN
             wsql = wsql||' and '||REPLACE(premp, 'BDCODEMP', 'C13.BDCODEMP');
           IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
             wsql = wsql||' and '||REPLACE(prcol, 'BDCODCOL', 'C13.BDCODCOL');
           IF ((prcc IS NOT NULL) AND (prcc <> '')) THEN
             BEGIN
               IF (TRIM(wWhere) <> '') THEN
                 wWhere = wWhere||' and ';
               wWhere = wWhere || REPLACE(prcc, 'BDCODTPCC', 'PREP13.BDCODTPCC');
             END
           FOR EXECUTE STATEMENT wSql INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :bdordem,
                                               :BDCODCENTRO, :BDCODTPCC do
             begin
               BDREFFNAUX = 0;
               suspend;
     end
         
       wSql = 'select 0 BDTIPOCOL, VC13.BDCODVER, VC13.BDCODEMP, VC13.BDCODEMP, VC13.BDCODCOL, VC13.BDREFC13 BDREFFN, ' ||
              '       VC13.BDVALVC13 BDVALVFN, ' ||
              '       coalesce(CC13.BDFGTSC13, 0) BDFGTS, coalesce(CC13.BDBASEPISC13, 0) BDBASEPIS, 5 BDTIPOCALC,CC13.BDORDEM, ' ;

      if (pragrupacc = 0)  then
         wSql = wSql || '  0 BDCODCENTRO, 0 BDCODTPCC   ';
      else
         wSql = wSql || '  prepc13.BDCODCENTRO, prepc13.BDCODTPCC   ';


      wSql = wSql || 'from VRHF_EMP_TVERBAC13 VC13 ' ||
                  'join VRHF_EMP_TC13SAL CC13 on (VC13.BDCODEMP = CC13.BDCODEMP and ' ||
                  '      VC13.BDCODCOL = CC13.BDCODCOL and ' ||
                  '      VC13.BDREF13 = CC13.BDREF13) ' ;

       if ((pragrupacc = 1) or (prcc is not null) and (prcc <> ''))  then
             wSql = wSql || 'left join VRHF_EMP_TPREPFN PREPC13 on CC13.BDCODEMP = PREPC13.BDCODEMP and ' ||
                  '      CC13.BDCODCOL = PREPC13.BDCODCOL and PREPC13.BDORDEM = CC13.BDORDEM ' ;

           wSql = wSql || ' where VC13.BDREFC13 = ' || prrefini;

           IF (premp IS NOT NULL) THEN
             wsql = wsql||' and '||REPLACE(premp, 'BDCODEMP', 'CC13.BDCODEMP');
           IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
             wsql = wsql||' and '||REPLACE(prcol, 'BDCODCOL', 'CC13.BDCODCOL');
           IF ((prcc IS NOT NULL) AND (prcc <> '')) THEN
             BEGIN
               IF (TRIM(wWhere) <> '') THEN
                 wWhere = wWhere||' and ';
               wWhere = wWhere || REPLACE(prcc, 'BDCODTPCC', 'PREPC13.BDCODTPCC');
             END
           FOR EXECUTE STATEMENT wSql INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :BDORDEM,
                                               :BDCODCENTRO, :BDCODTPCC do
             begin
               BDREFFNAUX = 0;
               suspend;
             end
     end

       wSql = 'SELECT 0 BDTIPOCOL, VA13.BDCODVER, VA13.BDCODEMP, VA13.BDCODEMP, VA13.BDCODCOL, VA13.BDREFA13 BDREFFN, VA13.BDVALVA13 BDVALVFN, ' ||
              '       COALESCE(CA13.BDFGTSA13, 0) BDFGTS, COALESCE(CA13.BDBASEPISA13, 0) BDBASEPIS, 2 bdtipocalc, CA13.bdordem, ' ;

      if (pragrupacc = 0)  then
         wSql = wSql || '  0 BDCODCENTRO, 0 BDCODTPCC   ';
      else
         wSql = wSql || '  PREPA13.BDCODCENTRO, PREPA13.BDCODTPCC   ';


      wSql = wSql || 'FROM VRHF_EMP_TVERBAA13 VA13 ' ||
              'JOIN VRHF_EMP_TA13SAL CA13 ON (VA13.BDCODEMP = CA13.BDCODEMP AND ' ||
              '      VA13.BDCODCOL = CA13.BDCODCOL AND ' ||
              '      VA13.BDREFA13 = CA13.BDREFA13) ' ;

     if ((pragrupacc = 1) or (prcc is not null) and (prcc <> ''))  then
             wSql = wSql || 'LEFT JOIN VRHF_EMP_TPREPFN PREPA13 ON CA13.BDCODEMP = PREPA13.BDCODEMP AND ' ||
              '      CA13.BDCODCOL = PREPA13.BDCODCOL and PREPA13.BDORDEM = CA13.BDORDEM ' ;

       wsql = wsql||' WHERE VA13.BDREFA13 = '|| prrefini;

       IF (premp IS NOT NULL) THEN
         wsql = wsql||' and '||REPLACE(premp, 'BDCODEMP', 'CA13.BDCODEMP');
       IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
         wsql = wsql||' and '||REPLACE(prcol, 'BDCODCOL', 'CA13.BDCODCOL');
       IF ((prcc IS NOT NULL) AND (prcc <> '')) THEN
         BEGIN
           IF (TRIM(wWhere) <> '') THEN
             wWhere = wWhere||' and ';
           wWhere = wWhere || REPLACE(prcc, 'BDCODTPCC', 'PREPA13.BDCODTPCC');
         END
       FOR EXECUTE STATEMENT wSql INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :bdordem,
                                               :BDCODCENTRO, :BDCODTPCC do
         SUSPEND;


       -- folha intermitente
       wSql = 'SELECT 0 BDTIPOCOL, v.BDCODVER, v.BDCODEMP, v.BDCODEMP, v.BDCODCOL, v.BDREFFN, v.BDVALVFN, ' ||
              '       0 BDFGTS, 0 BDBASEPIS, 2 bdtipocalc, 0 bdordem,  0 BDCODCENTRO, 0 BDCODTPCC   '||
              'FROM VRHF_EMP_TVERBAINT v ' ||
              'JOIN VRHF_EMP_TFOLHAINT f ON (f.BDCODEMP = v.BDCODEMP AND ' ||
              '      v.BDCODCOL = f.BDCODCOL AND ' ||
              '      v.BDCODCONTTI = f.BDCODCONTTI AND ' ||
              '      v.BDREFFN = f.BDREFFN) ' ;

       wsql = wsql||' WHERE v.BDREFFN = '|| prrefini;

       IF (premp IS NOT NULL) THEN
         wsql = wsql||' and '||REPLACE(premp, 'BDCODEMP', 'v.BDCODEMP');
       IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
         wsql = wsql||' and '||REPLACE(prcol, 'BDCODCOL', 'v.BDCODCOL');

       FOR EXECUTE STATEMENT wSql INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :bdordem,
                                               :BDCODCENTRO, :BDCODTPCC do
         SUSPEND;


       -- folha intermitente  tomador
       wSql = 'SELECT 0 BDTIPOCOL, v.BDCODVER, v.BDCODEMP, v.BDCODEMP, v.BDCODCOL, v.BDREFTOMADOR BDREFFN, v.BDVALVFT, ' ||
              '       0 BDFGTS, 0 BDBASEPIS, 2 bdtipocalc, V.BDORDEM, ' ;

      if (pragrupacc = 0)  then
         wSql = wSql || '  0 BDCODCENTRO, 0 BDCODTPCC   ';
      else
         wSql = wSql || '  prepf.BDCODCENTRO, prepf.BDCODTPCC   ';


      wSql = wSql || 'FROM VRHF_EMP_TVERBATOMINT v ' ||
              'JOIN VRHF_EMP_TFOLHATOMINT f ON (f.BDCODEMP = v.BDCODEMP AND ' ||
              '      v.BDCODCOL = f.BDCODCOL AND ' ||
              '      v.BDCODCONTTI = f.BDCODCONTTI AND ' ||
              '      v.BDORDEM = f.BDORDEM AND ' ||
              '      v.BDREFTOMADOR = f.BDREFTOMADOR) ' ;

     if ((pragrupacc = 1) or (prcc is not null) and (prcc <> ''))  then
             wSql = wSql || ' left join VRHF_EMP_TPREPFN PREPF on f.BDCODEMP = PREPF.BDCODEMP and f.BDCODCOL = PREPF.BDCODCOL and  PREPF.BDORDEM = f.BDORDEM ' ;

       wsql = wsql||' WHERE v.BDREFTOMADOR = '|| prrefini;

       IF (premp IS NOT NULL) THEN
         wsql = wsql||' and '||REPLACE(premp, 'BDCODEMP', 'v.BDCODEMP');
       IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
         wsql = wsql||' and '||REPLACE(prcol, 'BDCODCOL', 'v.BDCODCOL');
       IF ((prcc IS NOT NULL) AND (prcc <> '')) THEN
         BEGIN
           IF (TRIM(wWhere) <> '') THEN
             wWhere = wWhere||' and ';
           wWhere = wWhere || REPLACE(prcc, 'BDCODTPCC', 'PREPF.BDCODTPCC');
         END

       FOR EXECUTE STATEMENT wSql INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :bdordem,
                                               :BDCODCENTRO, :BDCODTPCC do
         SUSPEND;


       --complementar intermitente
       wsql = 'select 0 BDTIPOCOL, VFC.BDCODVER, VFC.BDCODEMP, VFC.BDCODEMP, VFC.BDCODCOL, CFC.BDREFCOMP, ' ||
              '      VFC.BDVALVFC BDVALVFN, ' ||
              '      (coalesce(CFC.BDFGTSFC, 0) + coalesce(CFC.BDFGTSFEFC, 0) + coalesce(CFC.BDFGTS13FC, 0)) BDFGTS, ' ||
              '      (coalesce(CFC.BDBASEPISFC, 0) + coalesce(CFC.BDBASEPISFEFC, 0) + coalesce(CFC.BDBASEPIS13FC, 0)) BDBASEPIS,' ||
              '      Case when BDCODACCONV IS NOT NULL then  3 else 4 end bdtipocalc, VFC.BDREFCOMP bdreffnAux, 0 BDORDEM, ' ||
              '  0 BDCODCENTRO, 0 BDCODTPCC   ' ||
              'from VRHF_EMP_TVERBAFCINT VFC ' ||
              'join VRHF_EMP_TFOLHACOMPINT CFC on (VFC.BDCODEMP = CFC.BDCODEMP and ' ||
              '     VFC.BDCODCOL = CFC.BDCODCOL and ' ||
              '     VFC.BDREFFN = CFC.BDREFFN and ' ||
              '     VFC.BDREFFC = CFC.BDREFFC and ' ||
              '     VFC.BDREFCOMP = ' || CAST(prrefini AS VARCHAR(6)) || ')'  ;

       IF (premp IS NOT NULL) THEN
          wWhere = REPLACE(premp, 'BDCODEMP', 'CFC.BDCODEMP');

       IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
         BEGIN
           IF (TRIM(wWhere) <> '') THEN
             wWhere = wWhere||' and ';
           wWhere = wWhere || REPLACE(prcol, 'BDCODCOL', 'CFC.BDCODCOL');
         END

       IF (TRIM(wWhere) <> '') THEN
         wWhere = 'Where ' || wWhere;

       FOR EXECUTE STATEMENT wSql  || wWhere INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :bdreffnAux, :bdordem,
                                               :BDCODCENTRO, :BDCODTPCC do
         SUSPEND;



       --complementar intermitente  tomador
       wsql = 'select 0 BDTIPOCOL, VFC.BDCODVER, VFC.BDCODEMP, VFC.BDCODEMP, VFC.BDCODCOL, CFC.BDREFCOMP, ' ||
              '      VFC.BDVALVFC BDVALVFN, ' ||
              '      (coalesce(CFC.BDFGTSFC, 0) + coalesce(CFC.BDFGTSFEFC, 0) + coalesce(CFC.BDFGTS13FC, 0)) BDFGTS, ' ||
              '      (coalesce(CFC.BDBASEPISFC, 0) + coalesce(CFC.BDBASEPISFEFC, 0) + coalesce(CFC.BDBASEPIS13FC, 0)) BDBASEPIS, ' ||
              '      Case when BDCODACCONV IS NOT NULL then  3 else 4 end bdtipocalc, VFC.BDREFCOMP bdreffnAux, 0 BDORDEM, ' ;

      if (pragrupacc = 0)  then
         wSql = wSql || '  0 BDCODCENTRO, 0 BDCODTPCC   ' ;
      else
         wSql = wSql || '  prepf.BDCODCENTRO, prepf.BDCODTPCC   ';


      wSql = wSql || 'from VRHF_EMP_TVERBAFCTOMINT VFC ' ||
              'join VRHF_EMP_TFOLTOMCOMPINT CFC on (VFC.BDCODEMP = CFC.BDCODEMP and ' ||
              '     VFC.BDCODCOL = CFC.BDCODCOL and ' ||
              '     VFC.BDREFTOMADOR = CFC.BDREFTOMADOR and ' ||
              '     VFC.BDREFFC = CFC.BDREFFC and ' ||
              '     VFC.BDREFCOMP = ' || CAST(prrefini AS VARCHAR(6)) || ')'  ;


      if ((pragrupacc = 1) or (prcc is not null) and (prcc <> ''))  then
             wSql = wSql || ' left join VRHF_EMP_TPREPFN PREPF on CFC.BDCODEMP = PREPF.BDCODEMP and CFC.BDCODCOL = PREPF.BDCODCOL and  PREPF.BDORDEM = CFC.BDORDEM ' ;

       IF (premp IS NOT NULL) THEN
          wWhere = REPLACE(premp, 'BDCODEMP', 'CFC.BDCODEMP');

       IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
         BEGIN
           IF (TRIM(wWhere) <> '') THEN
             wWhere = wWhere||' and ';
           wWhere = wWhere || REPLACE(prcol, 'BDCODCOL', 'CFC.BDCODCOL');
         END
       IF ((prcc IS NOT NULL) AND (prcc <> '')) THEN
         BEGIN
           IF (TRIM(wWhere) <> '') THEN
             wWhere = wWhere||' and ';
           wWhere = wWhere || REPLACE(prcc, 'BDCODTPCC', 'PREPF.BDCODTPCC');
         END

       IF (TRIM(wWhere) <> '') THEN
         wWhere = 'Where ' || wWhere;

       FOR EXECUTE STATEMENT wSql  || wWhere INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :bdreffnAux, :bdordem,
                                               :BDCODCENTRO, :BDCODTPCC do
         SUSPEND;


       --complementar folha normal
       wsql = 'select 0 BDTIPOCOL, VFC.BDCODVER, VFC.BDCODEMP, VFC.BDCODEMP, VFC.BDCODCOL, CFC.BDREFCOMP, ' ||
              '      VFC.BDVALVFC BDVALVFN, ' ||
              '      (coalesce(CFC.BDFGTSFC, 0) + coalesce(CFC.BDFGTSFEFC, 0) + coalesce(CFC.BDFGTS13FC, 0)) BDFGTS, ' ||
              '      (coalesce(CFC.BDBASEPISFC, 0) + coalesce(CFC.BDBASEPISFEFC, 0) + coalesce(CFC.BDBASEPIS13FC, 0)) BDBASEPIS, ' ||
              '      Case when BDCODACCONV IS NOT NULL then  3 else 4 end bdtipocalc, VFC.BDREFCOMP bdreffnAux, 0 BDORDEM, ' ||
              '  0 BDCODCENTRO, 0 BDCODTPCC   ' ||
              'from VRHF_EMP_TVERBAFC VFC ' ||
              'join VRHF_EMP_TFOLHACOMP CFC on VFC.BDCODEMP = CFC.BDCODEMP and ' ||
              '     VFC.BDCODCOL = CFC.BDCODCOL and ' ||
              '     VFC.BDREFFN = CFC.BDREFFN and ' ||
              '     VFC.BDREFFC = CFC.BDREFFC and ';


       wWhereCompNormal = ' VFC.BDREFCOMP = ' || CAST(prrefini AS VARCHAR(6)) ||' and ' ||
                          ' ((CFC.BDREFVINCFN IS NULL) OR (CFC.BDREFVINCFN = 0)) and CFC.BDCODACCONV is null ';
       wWhereCompADC = ' SUBSTRING(CAST(VFC.BDREFFC AS VARCHAR(8)) FROM 1 FOR 6) = ' || '''' || CAST(prrefini AS VARCHAR(6)) || '''' || ' AND ' ||
                       'CFC.BDCODTIPOFC = 3 AND ' ||
                       'CFC.BDCODACCONV IS NOT NULL AND ' ||
                       '((CFC.BDREFVINCFN IS NULL) OR (CFC.BDREFVINCFN = 0)) ';


       IF (premp IS NOT NULL) THEN
          wWhere = REPLACE(premp, 'BDCODEMP', 'CFC.BDCODEMP');
       IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
         BEGIN
           IF (TRIM(wWhere) <> '') THEN
             wWhere = wWhere||' and ';
           wWhere = wWhere || REPLACE(prcol, 'BDCODCOL', 'CFC.BDCODCOL');
         END

       IF (TRIM(wWhere) <> '') THEN
         wWhere = 'Where ' || wWhere;

       wSqlCompNormal = wSql || wWhereCompNormal || wWhere;
       wSqlCompADC = wSql || wWhereCompADC || wWhere;

       FOR EXECUTE STATEMENT wSqlCompNormal INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :bdreffnAux, :bdordem,
                                               :BDCODCENTRO, :BDCODTPCC do
         SUSPEND;

       FOR EXECUTE STATEMENT wSqlCompADC INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :bdreffnAux, :bdordem,
                                               :BDCODCENTRO, :BDCODTPCC do
         SUSPEND;

      --complementar tomador
       wsql = 'select 0 BDTIPOCOL, VFCT.BDCODVER, VFCT.BDCODEMP, VFCT.BDCODEMP, VFCT.BDCODCOL, VFCT.BDREFCOMP, VFCT.BDVALVFC, ' ||
              '      (coalesce(CFCT.BDFGTSFC, 0) + coalesce(CFCT.BDFGTSFEFC, 0) + coalesce(CFCT.BDFGTS13FC, 0)) BDFGTS, ' ||
              '      (coalesce(CFCT.BDBASEPISFC, 0) + coalesce(CFCT.BDBASEPISFEFC, 0) + coalesce(CFCT.BDBASEPIS13FC, 0)) BDBASEPIS, ' ||
              '      Case when BDCODACCONV IS NOT NULL then  3 else 4 end bdtipocalc, VFCT.BDREFCOMP,CFCT.bdordem, ' ;

      if (pragrupacc = 0)  then
         wSql = wSql || '  0 BDCODCENTRO, 0 BDCODTPCC   ' ;
      else
         wSql = wSql || '  prepf.BDCODCENTRO, prepf.BDCODTPCC   ';


      wSql = wSql || ' from VRHF_EMP_TVERBAFCTOMADOR VFCT ' ||
              'join VRHF_EMP_TFOLTOMCOMP CFCT on VFCT.BDCODEMP = CFCT.BDCODEMP and ' ||
              '     VFCT.BDCODCOL = CFCT.BDCODCOL and ' ||
              '     VFCT.BDORDEM = CFCT.BDORDEM and ' ||
              '     VFCT.BDREFTOMADOR = CFCT.BDREFTOMADOR and ' ||
              '     VFCT.BDREFFC = CFCT.BDREFFC and ';

       wWhereCompNormal = REPLACE(wWhereCompNormal, 'VFC.', 'VFCT.');
       wWhereCompNormal = REPLACE(wWhereCompNormal, 'CFC.', 'CFCT.');
       wWhereCompNormal = REPLACE(wWhereCompNormal, 'BDREFFN', 'BDREFCOMP');

       wWhereCompADC = REPLACE(wWhereCompADC, 'CFC.', 'CFCT.');
       wWhereCompADC = REPLACE(wWhereCompADC, 'VFC.', 'VFCT.');
       wWhereCompADC = REPLACE(wWhereCompADC, 'BDREFFN', 'BDREFCOMP');

       IF (premp IS NOT NULL) THEN
          wWhere = REPLACE(premp, 'BDCODEMP', 'CFCT.BDCODEMP');
       IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
         BEGIN
           IF (TRIM(wWhere) <> '') THEN
             wWhere = wWhere||' and ';
           wWhere = wWhere || REPLACE(prcol, 'BDCODCOL', 'CFCT.BDCODCOL');
         END
       IF ((prcc IS NOT NULL) AND (prcc <> '')) THEN
         BEGIN
           IF (TRIM(wWhere) <> '') THEN
             wWhere = wWhere||' and ';
           wWhere = wWhere || REPLACE(prcc, 'BDCODTPCC', 'PREPF.BDCODTPCC');
         END

      if ((pragrupacc = 1) or (prcc is not null) and (prcc <> ''))  then
             wSqlJoin = wSqlJoin || ' left join VRHF_EMP_TPREPFN PREPF on CFCT.BDCODEMP = PREPF.BDCODEMP and CFCT.BDCODCOL = PREPF.BDCODCOL and  PREPF.BDORDEM = CFCT.BDORDEM ' ;

       IF (TRIM(wWhere) <> '') THEN
         wWhere = 'Where ' || wWhere;

       wSqlCompNormal = wSql || wWhereCompNormal || wSqlJoin || wWhere;
       wSqlCompADC = wSql || wWhereCompADC || wSqlJoin || wWhere;

       FOR EXECUTE STATEMENT wSqlCompNormal INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :bdreffnAux, :bdordem,
            :BDCODCENTRO, :BDCODTPCC do
         SUSPEND;

       FOR EXECUTE STATEMENT wSqlCompADC INTO :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :BDCODCOL, :BDREFFN, :BDVALVFN, :BDFGTS, :BDBASEPIS, :BDTIPOCALC, :bdreffnAux, :bdordem,
            :BDCODCENTRO, :BDCODTPCC do
         SUSPEND;

     end


  if (coalesce(PRAUT,'') <> 'NENHUM') then
     begin
      wSql = '  select 2 BDTIPOCOL, VTER.BDCODVER, VTER.BDCODEMP, VTER.BDCODEMP, VTER.bdcodter, SERV.bdrefserv BDREFFN, VTER.bdvalor BDVALVFN, 0 BDFGTS, 0 BDBASEPIS, '||
             '   4 bdtipocalc, SERV.bdcodcentro,  SERV.BDCODTPCC ' ||                       /*166040 - André Cursino - 22/11/2022*/
             ' from VRHF_BASE_ITEMS_CALCTERC VTER '||
             ' LEFT JOIN VRHF_BASE_CALC_TERC TER ON (VTER.BDCODEMP = TER.BDCODEMP AND VTER.bdcodter = TER.bdcodter AND VTER.bdcodserv = TER.bdcodserv) '||
             ' LEFT join VRH_BASE_TSERVTERC SERV on (VTER.BDCODEMP = SERV.BDCODEMP AND VTER.bdcodter = SERV.bdcodter AND VTER.bdcodserv = SERV.bdcodserv) ';

       wsql = wsql||' WHERE SERV.bdrefserv = '||prrefini;

       if (premp is not null) then
          wsql = wsql||' and '||replace(premp, 'BDCODEMP', 'VTER.BDCODEMP');

       if ((PRAUT is not null) and (PRAUT <> '') and (PRAUT <> 'NENHUM')) then
         wsql = wsql||' and '||replace(PRAUT, 'BDCODTER', 'VTER.BDCODTER');

       if ((prcc is not null) and (prcc <> '')) then
          wsql = wsql||' and '||replace(prcc, 'BDCODTPCC', 'SERV.BDCODTPCC');

       for execute statement wSql into :BDTIPOCOL, :BDCODVER, :BDCODEMP, :bdcodfilial, :bdcodcol, :BDREFFN, :BDVALVFN, :BDFGTS, :BDBASEPIS, :BDTIPOCALC,
                                               :BDCODCENTRO, :BDCODTPCC do
         begin
           BDREFFNAUX = 0;
           suspend;
         end
     end
end^

/* Restore proc. body: SP_VRH_RELATORIOCUSTOCOL */
create or alter procedure SP_VRH_RELATORIOCUSTOCOL (
    PREMP varchar(10000),
    PRCOL varchar(20000),
    PRAUT varchar(10000),
    PRCLA varchar(5000),
    PRSIND varchar(5000),
    PRFUC varchar(5000),
    PRREFINI integer,
    PRREFFIM integer,
    PRSITCOL smallint,
    PRAGRUPA smallint = 0,
    PRCC varchar(10000) = null,
    PRAGRUPAFILIAIS smallint = 0)
returns (
    BDCODEMP integer,
    BDREF integer,
    BDTIPOCOL integer,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDREMUNERACAO numeric(18,6),
    BDENCREMUNERACAO numeric(18,6),
    BDINSSPATRONAL numeric(18,6),
    BDTERC numeric(18,6),
    BDRAT numeric(18,6),
    BDFGTS numeric(18,6),
    BDRATAPO numeric(18,6),
    BDPROV13 numeric(18,6),
    BDENCPROV13 numeric(18,6),
    BDPROVFER numeric(18,6),
    BDENCPROVFER numeric(18,6),
    BDBENIFICIOS numeric(18,6),
    BDNOMTPCC DM_BDNOMEMP,
    BDTOTAL numeric(18,6),
    BDCODSIT integer,
    BDDESCSIT varchar(70),
    BDCODFILIAL integer,
    BDNOMEMP DM_BDNOMEMP)
as
declare variable WCLAVER varchar(20);
declare variable WSQL varchar(32700);
declare variable WWHEREFILTRO varchar(32000);
declare variable WVERBA integer;
declare variable WVALOR numeric(18,6);
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WTIPOCOL integer;
declare variable WTIPOCOLATU integer;
declare variable WREF integer;
declare variable WREFATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WBASEINSS integer;
declare variable WTIPOCODVER integer;
declare variable WCODTPCC integer;
declare variable WTPCCATU integer;
declare variable WCODCENTRO integer;
declare variable WCENTROATU integer;
declare variable WSQLAUX varchar(1000);
declare variable WCONTRCOL integer;
declare variable WPERCINSS numeric(18,6);
declare variable WCODFPASTERC integer;
declare variable WFAP numeric(18,6);
declare variable WPERCFGTS numeric(18,6);
declare variable WVT numeric(18,6);
declare variable WVR numeric(18,6);
declare variable WRETORNA smallint;
declare variable WRAUX integer;
declare variable WAAUX integer;
declare variable WTAUX integer;
declare variable WPERCAUT numeric(18,6);
declare variable WPERCEMP numeric(18,6);
declare variable WPERCCOL numeric(18,6);
declare variable WPERCFPAS numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WCODCNAE integer;
declare variable WNOMEMP DM_BDNOMEMP;
declare variable WPRIVEZ smallint;
declare variable WCODFILIAL integer;
declare variable WFILIALATU integer;
declare variable WOK integer;
declare variable WOKREGANT integer;
declare variable WDTAUX varchar(10);
declare variable WBASEGPS varchar(5);
declare variable WCODVERAUX integer;
declare variable WSIMPLESGPS integer;
declare variable WBASEFGTS numeric(18,6);
declare variable WFGTSVER integer;
declare variable WMP932 DM_BOOLEAN;
BEGIN
  /* prsitcol
     0 = Somente ativos
     1 = Todos
     2 = Somente os demitidos
     3 = Somente admitidos no mês
     4 = Somente demitidos no mês
     5 = Ativos sem os demitidos no mês
     6 = Ativos sem demitidos com transferência
     7 = Ativos sem afastados o mês inteiro
     8 = Afastados o mês inteiro
   */

  wsql = '';

  premp = upper(premp);
  prcol = upper(prcol);

  wsql = 'select FOLHA.BDCODEMP, FOLHA.BDREF, FOLHA.BDTIPOCOL, FOLHA.BDCODCOL, FOLHA.BDCODVER, FOLHA.BDVALOR, COALESCE(FOLHA.BDCODCENTRO,0), COALESCE(FOLHA.BDCODTPCC, 0), FOLHA.BDCODFILIAL '||
         'from SP_VRH_RELATORIOCUSTOCOL_FN(';

  if (premp is null) then
     wsql = wsql||'null,';
  else
     wsql = wsql||''''||premp||''',';

  if (prcol is null) then
     wsql = wsql||'null,';
  else
     wsql = wsql||''''||prcol||''',';

  if (coalesce(prfuc, '') <> '') then
     begin
       wsql = wsql||'null,';
     end
  else
     begin
       if (praut is null) then
          wsql = wsql||'null,';
       else
          wsql = wsql||''''||praut||''',';
     end

  wsql = wsql||prrefini||',';
  wsql = wsql||prreffim||',';
  wsql = wsql||pragrupa||',';

  if (prcc is null) then
     wsql = wsql||'null,';
  else
     wsql = wsql||''''||prcc||''',';

  wsql = wsql||pragrupafiliais;

  wsql = wsql||') FOLHA ';


  BDCODCENTRO = NULL;
  BDCODTPCC = NULL;

  wempatu = 0;
  wcolatu = 0;
  wtipocolatu = -1;
  wrefatu = 0;
  wtpccatu = -1;
  wcentroatu = -1;
  BDREMUNERACAO = 0;
  BDENCREMUNERACAO = 0;
  BDPROV13 = 0;
  BDENCPROV13 = 0;
  BDPROVFER = 0;
  BDENCPROVFER = 0;
  BDBENIFICIOS = 0;
  BDTOTAL = 0;
  wvt = 0;
  wvr = 0;
  wpercaut = 0;
  wpercemp = 0;
  wperccol = 0;
  wcodfpasterc = 0;
  wpercfpas = 0;
  wpercrat = 0;
  wprivez = 0;
  BDCODSIT = 0;
  BDDESCSIT = '';
  wfilialatu = 0;
  wsimplesgps = 0;
  wbasefgts = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wref, :wtipocol, :wcodcol, :wverba, :wvalor, :wcodcentro, :wcodtpcc, :wcodfilial DO
    BEGIN
      IF ((wempatu <> wcodemp) OR (wrefatu <> wref) OR (wcolatu <> wcodcol) OR (wtpccatu <> wcodtpcc) or (wfilialatu <> wcodfilial)) THEN
         begin
      wok = 1;

           if ((coalesce(prcla,  '') <> '') or
              (coalesce(prsind,  '') <> '') or
              (coalesce(prfuc,  '') <> '') or
              (coalesce(prcc,  '') <> '')) then
         begin
           if (coalesce(wtipocol, 0) = 2) then
                   begin
                     /* terceiro */
                     wsqlaux = 'select first 1 * from VRH_BASE_TTERC_VINC where BDCODTER = '||wcodcol||' and BDREFTERC <= '||wref||' order by BDREFTERC DESC';
                     wsqlaux = 'select first 1 coalesce(BDCODTER,0) from ('||wsqlaux||') ';
                   end
           else
                   begin
                     /* Colaboradores */
                     wsqlaux = 'select first 1 * from VRH_EMP_TCOLCON_VINC where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||' and BDREFCOL <= '||wref||' order by BDREFCOL DESC';
                     wsqlaux = 'select first 1 coalesce(bdcodcol,0) from ('||wsqlaux||') ';
         end
        
                wwherefiltro = '';
                if (coalesce(prcla,  '') <> '') then
         begin
                     wwherefiltro = ' where '||prcla;
                   end
           
                if (wwherefiltro <> '') then
                   begin
                     wok = 0;
                     execute statement wsqlaux||wwherefiltro into :wok;
              wok = coalesce(wok, 0);
         end

                wwherefiltro = '';
      if (coalesce(prsind,  '') <> '') then
         begin
                     if (coalesce(wtipocol, 0) <> 2) then
                        begin
                          wsqlaux = 'select first 1 * from VRH_EMP_TCOL_VINC where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||' and BDREFCOL <= '||wref||' order by BDREFCOL DESC';
                          wsqlaux = 'select first 1 coalesce(bdcodcol,0) from ('||wsqlaux||') ';
                        end
                     wwherefiltro = ' where ';
                     wwherefiltro = wwherefiltro||prsind;
                   end
        
                if ((wok > 0) and (wwherefiltro <> '')) then
                   begin
                     wok = 0;
                     execute statement wsqlaux||wwherefiltro into :wok;
              wok = coalesce(wok, 0);
         end
        
                select first 1 ULTDIA from ULTIMO_DIA_MES(CAST(SUBSTRING(:wref FROM 5 FOR 2) AS SMALLINT), CAST(SUBSTRING(:wref FROM 1 FOR 4) AS INTEGER)) into :wdtaux;
                wdtaux = SUBSTRING(:wref FROM 5 FOR 2)||'-'||lpad(wdtaux,  2, '0')||'-'||SUBSTRING(:wref FROM 1 FOR 4);

                wwherefiltro = '';
                if ((wok > 0) and (coalesce(wtipocol, 0) <> 2)) then
                   begin
                     wsqlaux = 'select first 1 * from VRH_EMP_TCOL_VINCDIA where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||' and BDDATACOL <= '''||wdtaux||''' order by BDDATACOL DESC';
                     wsqlaux = 'select first 1 coalesce(bdcodcol,0) from ('||wsqlaux||') ';
      if (coalesce(prfuc,  '') <> '') then
         begin
                          if (wwherefiltro <> '') then
                             wwherefiltro = wwherefiltro||' and ';
                          else
                             wwherefiltro = ' where ';
                          wwherefiltro = wwherefiltro||prfuc;
                        end
        
                     if (wwherefiltro <> '') then
                        begin
                          wok = 0;
                          execute statement wsqlaux||wwherefiltro into :wok;
              wok = coalesce(wok, 0);
         end
                   end
              end
         end

      if ((coalesce(wOK, 0) > 0) or (coalesce(wOKRegAnt, 0) > 0)) then
         begin
           wOKRegAnt = wOk;
           IF (wempatu = 0) THEN
              wempatu = wcodemp;
           IF (wrefatu = 0) THEN
              wrefatu = wref;
           IF (wtipocolatu = -1) THEN
              wtipocolatu = wtipocol;
           IF (wcolatu = 0) THEN
              wcolatu = wcodcol;
           IF (wtpccatu = -1) THEN
              wtpccatu = wcodtpcc;
           IF (wfilialatu = 0) THEN
              wfilialatu = wcodfilial;
          
           IF ((wempatu <> wcodemp) OR (wrefatu <> wref) OR (wcolatu <> wcodcol) OR (wtpccatu <> wcodtpcc) or (wfilialatu <> wcodfilial)) THEN
              BEGIN
                BDCODEMP    = wempatu;
                BDREF       = wrefatu;
                BDCODCOL    = wcolatu;
                BDCODCENTRO = wcentroatu;
                BDCODTPCC   = wtpccatu;
                BDCODFILIAL = wfilialatu;
                waaux       = 0;
                wraux       = 0;
                wtaux       = 0;
          
                IF (wtipocolatu = 2) THEN
                   BEGIN
                     SELECT FIRST 1 SUBSTRING(BDNOMETER FROM 1 FOR 70), SUBSTRING(UPPER(BDNOMETER) FROM 1 FOR 70) FROM VW_TTERCEIRO WHERE BDCODTER = :wcolatu INTO :BDNOMCOL, :BDNOMCOLUPPER;
                     wcontrcol = 2;
                   END
                ELSE
                   BEGIN
                     SELECT CAD.BDNOMCOL, UPPER(CAD.BDNOMCOL), C.BDCONTRCOL, SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 6 FOR 2) BDREFADMCOL, R.BDREFRESCISAO, PR.BDTIPOMOV
                     FROM VRH_EMP_TCOLCON C
                     LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD CAD ON (CAD.BDCODEMP = C.BDCODEMP AND CAD.BDCODCOL = C.BDCODCOL)
                     LEFT OUTER JOIN VRH_EMP_TRESCISAO R ON (R.BDCODEMP = C.BDCODEMP AND R.BDCODCOL = C.BDCODCOL)
                     LEFT OUTER JOIN VRH_BASE_TPREPRESC PR ON (PR.BDCODPRES = R.BDCODPRES)
                     WHERE C.BDCODEMP = :wfilialatu AND C.BDCODCOL = :wcolatu INTO :BDNOMCOL, :BDNOMCOLUPPER, :wcontrcol, :waaux, :wraux, :wtaux;
          
                     IF (wcontrcol = 1) THEN
                        BEGIN
                          wsqlaux = 'select first 1 X.BDGRUPOCLA from VRH_EMP_TCOLCON_VINC Y '||
                                    'join VRH_BASE_TCLASSE X on (X.BDCODCLA = Y.BDCODCLA) '||
                                    'where Y.BDCODEMP = '||wfilialatu||' and Y.BDCODCOL = '||wcolatu||' and Y.BDREFCOL <= '||wrefatu||' order by Y.BDREFCOL DESC ';
                          EXECUTE STATEMENT wsqlaux INTO: wcontrcol;
          
                          IF (wcontrcol = 3) THEN
                             wcontrcol = 2;
                          ELSE
                             wcontrcol = 1;
                        END
          
                   END
          
                wsqlaux = 'select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC';
                EXECUTE STATEMENT wsqlaux INTO: BDNOMEMP;
                BDTIPOCOL   = wcontrcol;
                wretorna = 0;
                IF (wcontrcol IN (0,1)) THEN
                   BEGIN
                     IF (prsitcol = 0) THEN   -- somente ativos
                        BEGIN
                          IF (COALESCE(waaux,0) > wrefatu) THEN
                             wretorna = 1;
          
                          IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) < wrefatu) THEN
                             wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 2) THEN   -- somente os demitidos
                        BEGIN
                          IF (COALESCE(waaux,0) > wrefatu) THEN
                             wretorna = 1;
          
                          IF ((COALESCE(wraux,0) = 0) OR (COALESCE(wraux,0) > wrefatu)) THEN
                             wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 3) THEN   -- admitidos no mês
                        BEGIN
                          IF (COALESCE(waaux,0) <> wrefatu) THEN
                             wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 4) THEN   -- somente os demitidos no mês
                        BEGIN
                          IF (COALESCE(waaux,0) > wrefatu) THEN
                             wretorna = 1;
          
                          IF (COALESCE(wraux,0) <> wrefatu) THEN
                             wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 5) THEN   -- ativos sem os demitidos no mês
                        BEGIN
                          IF (COALESCE(waaux,0) > wrefatu) THEN
                             wretorna = 1;
          
                          IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) <= wrefatu) THEN
                             wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 6) THEN   -- ativos sem os demitidos com transferência
                        BEGIN
                          IF (COALESCE(waaux,0) > wrefatu) THEN
                             wretorna = 1;
          
                          IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) <= wrefatu AND COALESCE(wtaux,0) = 0) THEN
                             wretorna = 1;
          
                          IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) < wrefatu AND COALESCE(wtaux,0) = 1) THEN
                             wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 7) THEN   -- ativos sem os afastados o mês inteiro
                        BEGIN
                          IF (COALESCE(waaux,0) > wrefatu) THEN
                             wretorna = 1;
          
                          IF (wretorna = 0) THEN
                             BEGIN
                               wsqlaux = 'select first 1 BDCODCOL from VRH_EMP_TSITCOL where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||
                                         ' and SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                                         ' and ((BDDATAFIMSIT is null) or (SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';
          
                               EXECUTE STATEMENT wsqlaux INTO :wretorna;
          
                               IF (COALESCE(wretorna,0) > 0) THEN
                                  wretorna = 1;
                               ELSE
                                  wretorna = 0;
                             END
                        END
                     ELSE
                     IF (prsitcol = 8) THEN   -- afastados o mês inteiro
                        BEGIN
                          IF (COALESCE(waaux,0) > wrefatu) THEN
                             wretorna = 1;
          
                          IF (wretorna = 0) THEN
                             BEGIN
                               wsqlaux = 'select first 1 BDCODCOL from VRH_EMP_TSITCOL where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||
                                         ' and SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                                         ' and ((BDDATAFIMSIT is null) or (SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';
          
                               EXECUTE STATEMENT wsqlaux INTO :wretorna;
          
                               IF (COALESCE(wretorna,0) = 0) THEN
                                  wretorna = 1;
                               ELSE
                                  wretorna = 0;
                             END
                        END
          
                   END
          
                IF (wretorna = 0) THEN
                   BEGIN
                     wpercinss = 0;
                     IF ((wempatu <> wcodemp) OR (wrefatu <> wref) OR (wprivez = 0) or (wfilialatu <> wcodfilial)) THEN
                        BEGIN
                          wsqlaux = 'select first 1 BDAUTEMP, BDEMPEMP, BDFUNEMP, BDCODFPASTERC, BDFAP, BDSIMPLESGPS from VRHF_BASE_TEMPGPS where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC ';
                          EXECUTE STATEMENT wsqlaux INTO :wpercaut, :wpercemp, :wperccol, :wcodfpasterc, :wfap, :wsimplesgps;
                          wmp932 = null;
                          select first 1 BDNAOAPLICAMP932 from VRHF_BASE_TEMPMP932 where BDCODEMP = :wfilialatu into :wmp932;
                          wmp932 = upper(coalesce(wmp932, 'FALSE'));
                          wsimplesgps = coalesce(wsimplesgps, 0);
                          IF (coalesce(wcodfpasterc, 0) > 0) THEN
                             begin
                               if (coalesce(wrefatu, 0) in (202004, 202005, 202006) and wmp932 = 'FALSE') then
                                  select coalesce(BDSALEDU, 0) + coalesce(BDINCRA, 0) + coalesce(BDSENAI, 0) * 0.5 + coalesce(BDSESI, 0) * 0.5 +
                                         coalesce(BDSENAC, 0) * 0.5 + coalesce(BDSESC, 0) * 0.5 + coalesce(BDSEBRAE, 0) + coalesce(BDDPC, 0) +
                                         coalesce(BDFUNAERO, 0) + coalesce(BDSENAR, 0) * 0.5 + coalesce(BDSEST, 0) * 0.5 + coalesce(BDSENAT, 0) * 0.5 +
                                         coalesce(BDSESCOOP, 0) * 0.5 from VRH_BASE_TFPAS_TERCEIROS WHERE BDCODFPASTERC = :wcodfpasterc INTO :wpercfpas;
                               else
                                  SELECT BDPERTERC FROM VRH_BASE_TFPAS_TERCEIROS WHERE BDCODFPASTERC = :wcodfpasterc INTO :wpercfpas;
                             end
          
                          wcodcnae = 0;
                          wsqlaux = 'select first 1 COALESCE(BDCNAEPREP, BDCODCNAE, 0) ';
          
                          IF (pragrupa = 1) THEN
                             wsqlaux = wsqlaux||', BDCODCENTROS ';
                          ELSE
                             wsqlaux = wsqlaux||', 0 BDCODCENTROS ';
          
                          wsqlaux = wsqlaux||', BDNOMEMP ';
          
          
                          wsqlaux = wsqlaux||' from TEMPRESAS_REF where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC ';
                          EXECUTE STATEMENT wsqlaux INTO :wcodcnae, :BDCODCENTRO, :wnomemp;
               
                          IF (pragrupa = 0) THEN
                             BDCODCENTRO = wcentroatu;
          
                          IF (wcodcnae IS NOT NULL AND wcodcnae > 0) THEN
                             BEGIN
                               wsqlaux = 'select first 1 BDTAXACNAE from TCNAE_REF where BDCODCNAE = '||wcodcnae||' and BDREFCNAE <= ' ||wrefatu||' order by BDREFCNAE desc ';
                               EXECUTE STATEMENT wsqlaux INTO :wpercrat;
                             END

                          IF ((wfap IS NULL) OR (wfap = 0)) THEN
                             wfap = 1;

                          wpercrat = CAST((wpercrat * wfap) AS NUMERIC(18, 4));
                        END
          
                     wprivez = 1;
          
                     IF (wcontrcol = 2) THEN
                        wpercinss = wpercaut;
                     ELSE
                     IF (wcontrcol = 1) THEN
                        wpercinss = wpercemp;
                     ELSE
                        wpercinss = wperccol;
          
                     -- Empresa OPTANTE do SIMPLES
                     if (wsimplesgps in (1, 2, 5)) then
                        begin
                          wpercinss = 0;
                          wpercfpas = 0;
                          wpercrat  = 0;
                        end
     
                     -- INSS Patronal
                     BDINSSPATRONAL = 0;
                     IF (BDREMUNERACAO <> 0 AND wpercinss IS NOT NULL AND wpercinss > 0) THEN
                        BEGIN
                          BDINSSPATRONAL = CAST(((BDREMUNERACAO * wpercinss / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta
                          BDENCREMUNERACAO = BDENCREMUNERACAO + BDINSSPATRONAL;
                        END
          
                     -- Terceiros
                     BDTERC = 0;
                     IF (BDREMUNERACAO <> 0 AND wpercfpas IS NOT NULL AND wpercfpas > 0 and wcontrcol = 0) THEN
                        BEGIN
                          BDTERC = CAST(((BDREMUNERACAO * wpercfpas / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta.
                          BDENCREMUNERACAO = BDENCREMUNERACAO + BDTERC;
                        END
          
                     -- RAT
                     BDRAT = 0;
                     IF (BDREMUNERACAO <> 0 AND wpercrat IS NOT NULL AND wpercrat > 0 and wcontrcol = 0) THEN
                        BEGIN
                          BDRAT = CAST(((BDREMUNERACAO * wpercrat / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta.
                          BDENCREMUNERACAO = BDENCREMUNERACAO + BDRAT;
                        END
          
                     BDFGTS = 0;
                     BDRATAPO = 0;
                     BDPROV13    = 0;
                     BDENCPROV13 = 0;
                     BDPROVFER    = 0;
                     BDENCPROVFER = 0;
          
                     IF (wcontrcol in (0, 1)) THEN
                        BEGIN
                          wpercinss = 0;
                          -- FGTS
                          wsqlaux = 'select first 1 BDPERCFGTSCOL, BDPERCRATCOL from VRHF_EMP_TCOLCON_FGTSGPS where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and BDREFCOL <= '||wrefatu||' order by BDREFCOL DESC ';
                          EXECUTE STATEMENT wsqlaux INTO :wpercfgts, :wpercinss;
          
                          IF (wbasefgts <> 0 AND wpercfgts IS NOT NULL AND wpercfgts > 0) THEN
                             BEGIN
                               BDFGTS = CAST(((wbasefgts * wpercfgts / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta.
                               BDENCREMUNERACAO = BDENCREMUNERACAO + BDFGTS;
                             END
               
                          -- RAT APO
                          IF (BDREMUNERACAO <> 0 AND wpercinss IS NOT NULL AND wpercinss > 0) THEN
                             BEGIN
                               BDRATAPO = CAST(((BDREMUNERACAO * wpercinss / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta.
                               BDENCREMUNERACAO = BDENCREMUNERACAO + BDRATAPO;
                             END
               
                          -- Provisão de 13º
                          BDPROV13    = 0;
                          BDENCPROV13 = 0;
                          wsqlaux = 'select SUM(BDVLR13SALP13) BDVALPROV13, SUM(BDFGTSP13 + BDINSSP13 + BDTERCFPASP13 + BDCNAERATP13 + BDRATAPOP13 + BDPISP13) BDENCPROV13 '||
                                    'from VRHF_EMP_TPROVISAO13 where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and BDREFP13 = '||wrefatu||' and BDLINHAP13 in (6,7,8,9,19) ';
          
                          EXECUTE STATEMENT wsqlaux INTO :BDPROV13, :BDENCPROV13;
                          IF (BDPROV13 IS NULL) THEN
                             BDPROV13 = 0;
                          IF (BDENCPROV13 IS NULL) THEN
                             BDENCPROV13 = 0;
          
                          -- Provisão de Férias
                          wsqlaux = 'select SUM(BDFERIASPFER + BDUMTERCOPFER) BDVALPROVFER, SUM(BDFGTSPFER + BDINSSPFER + BDTERCFPASPFER + BDCNAERATPFER + BDRATAPOPFER + BDPISPFER) BDENCPROVFER '||
                                    'from VRHF_EMP_TPROVISAOFERIAS where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and BDREFPFER = '||wrefatu||' and BDLINHAPFER in (4,5,6,7,14) ';
          
                          BDPROVFER    = 0;
                          BDENCPROVFER = 0;
                          EXECUTE STATEMENT wsqlaux INTO :BDPROVFER, :BDENCPROVFER;
                          IF (BDPROVFER IS NULL) THEN
                             BDPROVFER = 0;
                          IF (BDENCPROVFER IS NULL) THEN
                             BDENCPROVFER = 0;
          
                               -- Apuração do vale transporte
                               wvt = null;
                               wsqlaux = 'select first 1 BDVALOREMPRESA from SP_APURADOS_VALTRANS(''ValeTrans.BDCODEMP = '||wfilialatu||''', ''ValeTrans.BDCODCOL = '||wcolatu||''','||wrefatu||',1)';
                               execute statement wsqlaux into :wvt;
                               BDBENIFICIOS = BDBENIFICIOS + coalesce(wvt, 0);

     
                               -- Apuração do vale refeição
                               wvr = null;
                               wsqlaux = 'select first 1 BDVALOREMPRESA from SP_APURADOS_VALREF(''ValeRef.BDCODEMP = '||wfilialatu||''', ''ValeRef.BDCODCOL = '||wcolatu||''','||wrefatu||',1)';
                               execute statement wsqlaux into :wvr;
                               BDBENIFICIOS = BDBENIFICIOS + coalesce(wvr, 0);
                        END
          
                     IF (wtpccatu > 0 AND wcentroatu > 0) THEN
                        BEGIN
                          wsqlaux = 'select first 1 case when TRIM(COALESCE(CCRH.BDNOMETOM, '''')) <> '''' then CCRH.BDNOMETOM else CC.BDNOMCTA end BDNOMCC from CENTROS_TPCC CC '||
                                    'left outer join VRH_BASE_TCUSTOM CCRH on (CCRH.BDCODCENTRO = CC.BDCODCENTRO and CCRH.BDCODTPCC = CC.BDCODTPCC) '||
                                    'where CC.BDCODCENTRO = '||wcentroatu||' and CC.BDCODTPCC = '||wtpccatu;
                          EXECUTE STATEMENT wsqlaux INTO :BDNOMTPCC;
                        END
                     ELSE
                        BDNOMTPCC = wnomemp;
          
                     BDCODSIT = 0;
                     BDDESCSIT = '';
                     if (BDREMUNERACAO + BDENCREMUNERACAO + BDBENIFICIOS + BDPROV13 + BDENCPROV13 + BDPROVFER + BDENCPROVFER <= 0) then
                        begin
                          wsqlaux = 'select first 1 ST.BDCODSIT, PST.BDDESCSIT from VRH_EMP_TSITCOL ST '||
                                    'join VRH_BASE_TPREPSIT PST on (PST.BDCODSIT = ST.BDCODSIT) '||
                                    'where ST.BDCODEMP = '||wfilialatu||' and ST.BDCODCOL = '||wcolatu||
                                    ' and SUBSTRING(CAST(ST.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(ST.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                                    ' and ((ST.BDDATAFIMSIT is null) or (SUBSTRING(CAST(ST.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(ST.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';
                          execute statement wsqlaux into :BDCODSIT, :BDDESCSIT;
                        end
          
                     BDTOTAL = BDREMUNERACAO + BDENCREMUNERACAO + BDBENIFICIOS + BDPROV13 + BDENCPROV13 + BDPROVFER + BDENCPROVFER;
                     SUSPEND;
                   END
          
                wempatu          = wcodemp;
                wrefatu          = wref;
                wtipocolatu      = wtipocol;
                wcolatu          = wcodcol;
                wtpccatu         = wcodtpcc;
                wfilialatu       = wcodfilial;
                BDREMUNERACAO    = 0;
                BDENCREMUNERACAO = 0;
                BDPROV13         = 0;
                BDENCPROV13      = 0;
                BDPROVFER        = 0;
                BDENCPROVFER     = 0;
                BDBENIFICIOS     = 0;
                wbasefgts        = 0;
              END
          
           wcentroatu = wcodcentro;
          
           wsqlaux = 'select first 1 vrh_base_tverbas.BDCLAVER,r.BDINSSVER, r.BDTIPOCODVER, r.BDBASEGPSVER, r.BDFGTSVER from VRH_BASE_TVERBAS_REF r '||
                     'left join vrh_base_tverbas on vrh_base_tverbas.bdcodver=r.bdcodver ' --157964 Valmor 07/01/2022
                     ||'where r.BDCODVER = '||wverba||' and r.BDREFVER <= '||wrefatu||' order by r.BDREFVER DESC';
           EXECUTE STATEMENT wsqlaux INTO :wclaver,:wbaseinss, :wtipocodver, :wbasegps, wfgtsver;
          
           IF ((COALESCE(wbaseinss,0) > 0) or (COALESCE(wbasegps, 'FALSE') = 'TRUE')) THEN
              BEGIN
                IF ((COALESCE(wtipocodver, 0) = 0) and (wclaver<>'7.050.0.0.001')) THEN
                   BDREMUNERACAO = BDREMUNERACAO + wvalor;
                ELSE
                IF ((COALESCE(wtipocodver, 0) = 1)) THEN
                   BDREMUNERACAO = BDREMUNERACAO - wvalor;
              END

           if (coalesce(wfgtsver, 0) > 0) then
              begin
                IF (COALESCE(wtipocodver, 0) = 0) THEN
                   wbasefgts = wbasefgts + wvalor;
                ELSE
                IF (COALESCE(wtipocodver, 0) = 1) THEN
                   wbasefgts = wbasefgts - wvalor;
              end

           for select BDCODVER from VRH_BASE_TCONFIG_RELCUSTO where BDCODEMP = :wcodemp and BDCODVER = :wverba into :wcodveraux do
             BDBENIFICIOS = BDBENIFICIOS + coalesce(wvalor,0);
         end
    END


 IF ((coalesce(wok, 0) > 0) and (wempatu <> 0) AND (wrefatu <> 0) AND (wcolatu <> 0) AND (wtpccatu <> -1) and (wfilialatu <> 0)) THEN
    BEGIN
      BDCODEMP    = wempatu;
      BDREF       = wrefatu;
      BDCODCOL    = wcolatu;
      BDCODCENTRO = wcentroatu;
      BDCODTPCC   = wtpccatu;
      BDCODFILIAL = wfilialatu;
      waaux       = 0;
      wraux       = 0;
      wtaux       = 0;

      IF (wtipocolatu = 2) THEN
         BEGIN
           SELECT FIRST 1 SUBSTRING(BDNOMETER FROM 1 FOR 70), SUBSTRING(UPPER(BDNOMETER) FROM 1 FOR 70) FROM VW_TTERCEIRO WHERE BDCODTER = :wcolatu INTO :BDNOMCOL, :BDNOMCOLUPPER;
           wcontrcol = 2;
         END
      ELSE
         BEGIN
           SELECT CAD.BDNOMCOL, UPPER(CAD.BDNOMCOL), C.BDCONTRCOL, SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 6 FOR 2) BDREFADMCOL, R.BDREFRESCISAO, PR.BDTIPOMOV
           FROM VRH_EMP_TCOLCON C
           LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD CAD ON (CAD.BDCODEMP = C.BDCODEMP AND CAD.BDCODCOL = C.BDCODCOL)
           LEFT OUTER JOIN VRH_EMP_TRESCISAO R ON (R.BDCODEMP = C.BDCODEMP AND R.BDCODCOL = C.BDCODCOL)
           LEFT OUTER JOIN VRH_BASE_TPREPRESC PR ON (PR.BDCODPRES = R.BDCODPRES)
           WHERE C.BDCODEMP = :wfilialatu AND C.BDCODCOL = :wcolatu INTO :BDNOMCOL, :BDNOMCOLUPPER, :wcontrcol, :waaux, :wraux, :wtaux;

           IF (wcontrcol = 1) THEN
              BEGIN
                wsqlaux = 'select first 1 X.BDGRUPOCLA from VRH_EMP_TCOLCON_VINC Y '||
                          'join VRH_BASE_TCLASSE X on (X.BDCODCLA = Y.BDCODCLA) where Y.BDCODEMP = '||wfilialatu||' and Y.BDCODCOL = '||wcolatu||' and Y.BDREFCOL <= '||wrefatu||' order by Y.BDREFCOL DESC ';
                EXECUTE STATEMENT wsqlaux INTO: wcontrcol;

                IF (wcontrcol = 3) THEN
                   wcontrcol = 2;
                ELSE
                   wcontrcol = 1;
              END

         END

      wsqlaux = 'select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC';
      EXECUTE STATEMENT wsqlaux INTO: BDNOMEMP;
      BDTIPOCOL = wcontrcol;
      wretorna  = 0;
      IF (wcontrcol IN (0,1)) THEN
         BEGIN
           IF (prsitcol = 0) THEN   -- somente ativos
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) < wrefatu) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 2) THEN   -- somente os demitidos
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF ((COALESCE(wraux,0) = 0) OR (COALESCE(wraux,0) > wrefatu)) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 3) THEN   -- admitidos no mês
              BEGIN
                IF (COALESCE(waaux,0) <> wrefatu) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 4) THEN   -- somente os demitidos no mês
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) <> wrefatu) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 5) THEN   -- ativos sem os demitidos no mês
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) <= wrefatu) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 6) THEN   -- ativos sem os demitidos com transferência
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) <= wrefatu AND COALESCE(wtaux,0) = 0) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) < wrefatu AND COALESCE(wtaux,0) = 1) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 7) THEN   -- ativos sem os afastados o mês inteiro
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (wretorna = 0) THEN
                   BEGIN
                     wsqlaux = 'select first 1 BDCODCOL from VRH_EMP_TSITCOL where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||
                               ' and SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                               ' and ((BDDATAFIMSIT is null) or (SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';

                     EXECUTE STATEMENT wsqlaux INTO :wretorna;

                     IF (COALESCE(wretorna,0) > 0) THEN
                        wretorna = 1;
                     ELSE
                        wretorna = 0;
                   END
              END
           ELSE
           IF (prsitcol = 8) THEN   -- afastados o mês inteiro
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (wretorna = 0) THEN
                   BEGIN
                     wsqlaux = 'select first 1 BDCODCOL from VRH_EMP_TSITCOL where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||
                               ' and SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                               ' and ((BDDATAFIMSIT is null) or (SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';

                     EXECUTE STATEMENT wsqlaux INTO :wretorna;

                     IF (COALESCE(wretorna,0) = 0) THEN
                        wretorna = 1;
                     ELSE
                        wretorna = 0;
                   END
              END

         END

      IF (wretorna = 0) THEN
         BEGIN
           wpercinss = 0;
           IF ((wempatu <> wcodemp) OR (wrefatu <> wref) OR (wprivez = 0) or (wfilialatu <> wcodemp)) THEN
              BEGIN
                wsqlaux = 'select first 1 BDAUTEMP, BDEMPEMP, BDFUNEMP, BDCODFPASTERC, BDFAP, BDSIMPLESGPS from VRHF_BASE_TEMPGPS where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC ';
                EXECUTE STATEMENT wsqlaux INTO :wpercaut, :wpercemp, :wperccol, :wcodfpasterc, :wfap, :wsimplesgps;

                IF (coalesce(wcodfpasterc, 0) > 0) THEN
                   begin
                     wmp932 = null;
                     select first 1 BDNAOAPLICAMP932 from VRHF_BASE_TEMPMP932 where BDCODEMP = :wfilialatu into :wmp932;
                     wmp932 = upper(coalesce(wmp932, 'FALSE'));

                     if (coalesce(wrefatu, 0) in (202004, 202005, 202006) and wmp932 = 'FALSE') then
                        select coalesce(BDSALEDU, 0) + coalesce(BDINCRA, 0) + coalesce(BDSENAI, 0) * 0.5 + coalesce(BDSESI, 0) * 0.5 +
                               coalesce(BDSENAC, 0) * 0.5 + coalesce(BDSESC, 0) * 0.5 + coalesce(BDSEBRAE, 0) + coalesce(BDDPC, 0) +
                               coalesce(BDFUNAERO, 0) + coalesce(BDSENAR, 0) * 0.5 + coalesce(BDSEST, 0) * 0.5 + coalesce(BDSENAT, 0) * 0.5 +
                               coalesce(BDSESCOOP, 0) * 0.5 from VRH_BASE_TFPAS_TERCEIROS WHERE BDCODFPASTERC = :wcodfpasterc INTO :wpercfpas;
                     else
                        SELECT BDPERTERC FROM VRH_BASE_TFPAS_TERCEIROS WHERE BDCODFPASTERC = :wcodfpasterc INTO :wpercfpas;
                   end


                IF (wcodfpasterc IS NOT NULL AND wcodfpasterc > 0) THEN
                   SELECT BDPERTERC FROM VRH_BASE_TFPAS_TERCEIROS WHERE BDCODFPASTERC = :wcodfpasterc INTO :wpercfpas;

                wsimplesgps = coalesce(wsimplesgps, 0);

                wcodcnae = 0;
                wsqlaux = 'select first 1 COALESCE(BDCNAEPREP, BDCODCNAE, 0) ';

                IF (pragrupa = 1) THEN
                   wsqlaux = wsqlaux||', BDCODCENTROS ';
                ELSE
                   wsqlaux = wsqlaux||', 0 BDCODCENTROS ';

                wsqlaux = wsqlaux||', BDNOMEMP ';


                wsqlaux = wsqlaux||' from TEMPRESAS_REF where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC ';
                EXECUTE STATEMENT wsqlaux INTO :wcodcnae, :BDCODCENTRO, :wnomemp;
     
                IF (pragrupa = 0) THEN
                   BDCODCENTRO = wcentroatu;

                IF (wcodcnae IS NOT NULL AND wcodcnae > 0) THEN
                   BEGIN
                     wsqlaux = 'select first 1 BDTAXACNAE from TCNAE_REF where BDCODCNAE = '||wcodcnae||' and BDREFCNAE <= ' ||wrefatu||' order by BDREFCNAE desc ';
                     EXECUTE STATEMENT wsqlaux INTO :wpercrat;
                   END

                IF ((wfap IS NULL) OR (wfap = 0)) THEN
                   wfap = 1;

                wpercrat = CAST((wpercrat * wfap) AS NUMERIC(18, 4));
              END

           wprivez = 1;

           IF (wcontrcol = 2) THEN
              wpercinss = wpercaut;
           ELSE
           IF (wcontrcol = 1) THEN
              wpercinss = wpercemp;
           ELSE
              wpercinss = wperccol;

           -- Empresa OPTANTE do SIMPLES
           if (wsimplesgps in (1, 2, 5)) then
              begin
                wpercinss = 0;
                wpercfpas = 0;
                wpercrat  = 0;
              end

           -- INSS Patronal
           BDINSSPATRONAL = 0;
           IF (BDREMUNERACAO <> 0 AND wpercinss IS NOT NULL AND wpercinss > 0) THEN
              BEGIN
                BDINSSPATRONAL = CAST(((BDREMUNERACAO * wpercinss / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta
                BDENCREMUNERACAO = BDENCREMUNERACAO + BDINSSPATRONAL;
              END

           -- Terceiros
           BDTERC = 0;
           IF (BDREMUNERACAO <> 0 AND wpercfpas IS NOT NULL AND wpercfpas > 0 and wcontrcol = 0) THEN
              BEGIN
                BDTERC = CAST(((BDREMUNERACAO * wpercfpas / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta.
                BDENCREMUNERACAO = BDENCREMUNERACAO + BDTERC;
              END

           -- RAT
           BDRAT = 0;
           IF (BDREMUNERACAO <> 0 AND wpercrat IS NOT NULL AND wpercrat > 0 and wcontrcol = 0) THEN
              BEGIN
                BDRAT = CAST(((BDREMUNERACAO * wpercrat / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta.
                BDENCREMUNERACAO = BDENCREMUNERACAO + BDRAT;
              END

           BDFGTS = 0;
           BDRATAPO = 0;
           BDPROV13    = 0;
           BDENCPROV13 = 0;
           BDPROVFER    = 0;
           BDENCPROVFER = 0;

           IF (wcontrcol in (0,1)) THEN
              BEGIN
                wpercinss = 0;
                -- FGTS
                wsqlaux = 'select first 1 BDPERCFGTSCOL, BDPERCRATCOL from VRHF_EMP_TCOLCON_FGTSGPS where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and BDREFCOL <= '||wrefatu||' order by BDREFCOL DESC ';
                EXECUTE STATEMENT wsqlaux INTO :wpercfgts, :wpercinss;
      
                IF (wbasefgts <> 0 AND wpercfgts IS NOT NULL AND wpercfgts > 0) THEN
                   BEGIN
                     BDFGTS = CAST(((wbasefgts * wpercfgts / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta.
                     BDENCREMUNERACAO = BDENCREMUNERACAO + BDFGTS;
                   END

                -- RAT APO
                IF (BDREMUNERACAO <> 0 AND wpercinss IS NOT NULL AND wpercinss > 0) THEN
                   BEGIN
                     BDRATAPO = CAST(((BDREMUNERACAO * wpercinss / 100) - 0.005) AS NUMERIC(18, 2));   -- Corta.
                     BDENCREMUNERACAO = BDENCREMUNERACAO + BDRATAPO;
                   END
     
                -- Provisão de 13º
                wsqlaux = 'select SUM(BDVLR13SALP13) BDVALPROV13, SUM(BDFGTSP13 + BDINSSP13 + BDTERCFPASP13 + BDCNAERATP13 + BDRATAPOP13 + BDPISP13) BDENCPROV13 from VRHF_EMP_TPROVISAO13 where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and BDREFP13 = '||wrefatu||' and BDLINHAP13 in (6,7,8,9,19) ';

                EXECUTE STATEMENT wsqlaux INTO :BDPROV13, :BDENCPROV13;
                IF (BDPROV13 IS NULL) THEN
                   BDPROV13 = 0;
                IF (BDENCPROV13 IS NULL) THEN
                   BDENCPROV13 = 0;

                -- Provisão de Férias
                wsqlaux = 'select SUM(BDFERIASPFER + BDUMTERCOPFER) BDVALPROVFER, SUM(BDFGTSPFER + BDINSSPFER + BDTERCFPASPFER + BDCNAERATPFER + BDRATAPOPFER + BDPISPFER) BDENCPROVFER from VRHF_EMP_TPROVISAOFERIAS where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and BDREFPFER = '||wrefatu||' and BDLINHAPFER in (4,5,6,7,14) ';

                EXECUTE STATEMENT wsqlaux INTO :BDPROVFER, :BDENCPROVFER;
                IF (BDPROVFER IS NULL) THEN
                   BDPROVFER = 0;
                IF (BDENCPROVFER IS NULL) THEN
                   BDENCPROVFER = 0;

                -- Apuração do vale transporte
                wvt = null;
                wsqlaux = 'select first 1 BDVALOREMPRESA from SP_APURADOS_VALTRANS(''ValeTrans.BDCODEMP = '||wfilialatu||''', ''ValeTrans.BDCODCOL = '||wcolatu||''','||wrefatu||',1)';
                execute statement wsqlaux into :wvt;
                BDBENIFICIOS = BDBENIFICIOS + coalesce(wvt, 0);


                -- Apuração do vale refeição
                wvr = null;
                wsqlaux = 'select first 1 BDVALOREMPRESA from SP_APURADOS_VALREF(''ValeRef.BDCODEMP = '||wfilialatu||''', ''ValeRef.BDCODCOL = '||wcolatu||''','||wrefatu||',1)';
                execute statement wsqlaux into :wvr;
                BDBENIFICIOS = BDBENIFICIOS + coalesce(wvr, 0);
              END

           IF (wtpccatu > 0 AND wcentroatu > 0) THEN
              BEGIN
                wsqlaux = 'select first 1 case when TRIM(COALESCE(CCRH.BDNOMETOM, '''')) <> '''' then CCRH.BDNOMETOM else CC.BDNOMCTA end BDNOMCC from CENTROS_TPCC CC left outer join VRH_BASE_TCUSTOM CCRH on (CCRH.BDCODCENTRO = CC.BDCODCENTRO and CCRH.BDCODTPCC = CC.BDCODTPCC) where CC.BDCODCENTRO = '||wcentroatu||' and CC.BDCODTPCC = '||wtpccatu;
                EXECUTE STATEMENT wsqlaux INTO :BDNOMTPCC;
              END
           ELSE
              BDNOMTPCC = wnomemp;

           BDCODSIT = 0;
           BDDESCSIT = '';
           if (BDREMUNERACAO + BDENCREMUNERACAO + BDBENIFICIOS + BDPROV13 + BDENCPROV13 + BDPROVFER + BDENCPROVFER <= 0) then
              begin
                wsqlaux = 'select first 1 ST.BDCODSIT, PST.BDDESCSIT from VRH_EMP_TSITCOL ST '||
                          'join VRH_BASE_TPREPSIT PST on (PST.BDCODSIT = ST.BDCODSIT) '||
                          'where ST.BDCODEMP = '||wfilialatu||' and ST.BDCODCOL = '||wcolatu||
                          ' and SUBSTRING(CAST(ST.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(ST.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                          ' and ((ST.BDDATAFIMSIT is null) or (SUBSTRING(CAST(ST.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(ST.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';
                execute statement wsqlaux into :BDCODSIT, :BDDESCSIT;
              end

           BDTOTAL = BDREMUNERACAO + BDENCREMUNERACAO + BDBENIFICIOS + BDPROV13 + BDENCPROV13 + BDPROVFER + BDENCPROVFER;
           SUSPEND;
         END
    END
END^

/* Restore proc. body: SP_VRH_RELATORIOCUSTOCOL_7186 */
create or alter procedure SP_VRH_RELATORIOCUSTOCOL_7186 (
    PREMP varchar(10000),
    PRCOL varchar(20000),
    PRAUT varchar(10000),
    PRCLA varchar(5000),
    PRSIND varchar(5000),
    PRFUC varchar(5000),
    PRREFINI integer,
    PRSITCOL smallint,
    PRCC varchar(5000) = '',
    PRRELCONF integer = 0,
    PRAGRUPACC integer = 0)
returns (
    BDREG varchar(4),
    BDCODEMP integer,
    BDREF integer,
    BDTIPOFOLHAID integer,
    BDTIPOCOL integer,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDSALARIOBRUTO numeric(18,6),
    BDENCREMUNERACAO numeric(18,6),
    BDINSSPATRONAL numeric(18,6),
    BDTERC numeric(18,6),
    BDRAT numeric(18,6),
    BDFGTS numeric(18,6),
    BDRATAPO numeric(18,6),
    BDPROV13 numeric(18,6),
    BDENCPROV13 numeric(18,6),
    BDPROVFER numeric(18,6),
    BDENCPROVFER numeric(18,6),
    BDGRATIFICACOES numeric(18,6),
    BDNOMTPCC DM_BDNOMEMP,
    BDTOTAL numeric(18,6),
    BDCODSIT integer,
    BDDESCSIT varchar(70),
    BDCODFILIAL integer,
    BDNOMEMP DM_BDNOMEMP,
    BDVALORINSS numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDVALORHE numeric(18,6),
    BDOUTROSDESCONTOS numeric(18,6),
    BDSALLIQUIDO numeric(18,6),
    BDGPS numeric(18,6),
    BDPIS numeric(18,6),
    BDOBS varchar(255),
    BDDESCCARGO varchar(150),
    BDCPFCOL varchar(18),
    BDDATAADMCOL date,
    BDDATARESCISAO date,
    BDREFRESCISAO integer,
    BDVALRESCISAO numeric(18,6),
    BDVAL13SALARIO numeric(18,6),
    BDVALFERIAS numeric(18,6),
    BDVALABONOFERIAS numeric(18,6),
    BDQTDHORAS numeric(18,6),
    BDVALUMTERCOABONO numeric(18,6),
    BDFAP numeric(18,6),
    BDMULTAFGTS numeric(18,6),
    BDMULTAFGTSCS numeric(18,6),
    BDFGTSRES numeric(18,6),
    BDINSSPATRONALCOL numeric(18,6),
    BDINSSPATRONALEMP numeric(18,6))
as
declare variable WWHEREFILTRO varchar(30000);
declare variable WSQL varchar(32700);
declare variable WSQLSELECT varchar(32700);
declare variable WVERBA integer;
declare variable WVALOR numeric(18,6);
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WTIPOCOL integer;
declare variable WTIPOCOLATU integer;
declare variable WREF integer;
declare variable WREFATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WBASEINSS numeric(18,6);
declare variable WTIPOCODVER integer;
declare variable WCODTPCC integer;
declare variable WTPCCATU integer;
declare variable WCODCENTRO integer;
declare variable WCENTROATU integer;
declare variable WSQLAUX varchar(1000);
declare variable WCONTRCOL integer;
declare variable WPERCINSS numeric(18,6);
declare variable WCODFPASTERC integer;
declare variable WFAP numeric(18,6);
declare variable WRETORNA smallint;
declare variable WRAUX integer;
declare variable WAAUX integer;
declare variable WTAUX integer;
declare variable WPERCAUT numeric(18,6);
declare variable WPERCEMP numeric(18,6);
declare variable WPERCCOL numeric(18,6);
declare variable WPERCFPAS numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WPERCPIS numeric(18,6);
declare variable WCODCNAE integer;
declare variable WNOMEMP DM_BDNOMEMP;
declare variable WPRIVEZ smallint;
declare variable WCODFILIAL integer;
declare variable WFILIALATU integer;
declare variable WOK integer;
declare variable WOKREGANT integer;
declare variable WDTAUX varchar(10);
declare variable WSIMPLESGPS integer;
declare variable WMP932 DM_BOOLEAN;
declare variable WCLAVER varchar(20);
declare variable WCODVERAUX integer;
declare variable WINSSVER integer;
declare variable WBASEGPS varchar(5);
declare variable WVALOR13 numeric(18,6);
declare variable WSOMABASEINSSPATRONAL numeric(18,2);
declare variable WSOMAPATRONAL numeric(18,2);
declare variable WVALORAGRUPADO numeric(18,2);
declare variable WSOMATERCEIROS numeric(18,2);
declare variable WSOMABASEINSSTERCEIROS numeric(18,2);
declare variable WSOMABASEINSSRAT numeric(18,2);
declare variable WSOMARAT numeric(18,2);
declare variable WGRRFPRES smallint;
declare variable WBASEPIS numeric(18,6);
declare variable WSOMABASEPIS numeric(18,2);
declare variable WSOMAPIS numeric(18,2);
declare variable WBASEINSS13 numeric(18,6);
declare variable WFGTS numeric(18,2);
declare variable WFGTSATU numeric(18,2);
declare variable WBASEPISATU numeric(18,2);
declare variable WCLAVER13 integer;
declare variable WTIPOCALC integer;
declare variable WTIPOCALCATU integer;
declare variable WMESMOCOLOUTROCALC integer;
declare variable W13 integer;
declare variable WCONSIDERAAD13 integer;
declare variable WCLAVERRESC13 integer;
declare variable WREFFNAUX integer;
declare variable WREFPAG integer;
declare variable WREFFNAUXATU integer;
declare variable WVALORC13 numeric(18,2);
declare variable WFGTSRES numeric(18,2);
declare variable WSALDOFGTS numeric(18,2);
declare variable WPERCMULTAFGTS numeric(18,2);
declare variable WPERCMULTAFGTSCS numeric(18,2);
declare variable WCPFTER varchar(18);
declare variable WORDEMATU integer;
declare variable WORDEM integer;
BEGIN

  wsql = '';
  premp = upper(premp);
  if (Trim(PREMP) = '') then
    prEmp = null;
  prcol = upper(prcol);
  praut = upper(praut);

  if (PRRELCONF = 0) then
     wsqlselect = 'select  BDCODEMP, BDREFFN, BDTIPOCOL, BDCODCOL, BDCODVER, BDVALVFN, bdcodcentro, bdcodtpcc, BDCODFILIAL, BDFGTS, BDBASEPIS , BDTIPOCALC, BDREFFNAUX, BDREFPAG ,BDORDEM from SP_VRH_REL_CUSTOCOL_7186_CALC(';
   else
     wsqlselect = 'select  BDCODEMP, BDREFFN, BDTIPOCOL, BDCODCOL, BDCODVER, BDVALVFN, 0, 0, BDCODFILIAL, BDFGTS, BDBASEPIS , BDTIPOCALC, BDREFFNAUX, BDREFFN as BDREFPAG, BDORDEM from SP_VRH_REL_CUSTOCOL_RCONF_CALC(';

  if (premp is null) then
     wsqlselect = wsqlselect||'null,';
  else
     wsqlselect = wsqlselect||''''||premp||''',';

  if (prcol is null) then
     wsqlselect = wsqlselect||'null,';
  else
     wsqlselect = wsqlselect||''''||prcol||''',';

  if (praut is null) then
     wsqlselect = wsqlselect||'null,';
  else
     wsqlselect = wsqlselect||''''||praut||''',';

  wsqlselect = wsqlselect||prrefini||',';

  if (PRRELCONF = 1) then
     wsqlselect = wsqlselect||pragrupacc||',';

  if (prcc is null) then
     wsqlselect = wsqlselect||'null';
  else
     wsqlselect = wsqlselect||''''||prcc||'''';

  if (PRRELCONF = 0) then
     wsql = 'select  x.BDCODEMP, x.BDREFFN, x.BDTIPOCOL, x.BDCODCOL, x.BDCODVER, x.BDVALVFN, x.bdcodcentro , x.bdcodtpcc, x.BDCODFILIAL, x.BDFGTS, x.BDBASEPIS , x.BDTIPOCALC, x.BDREFFNAUX, x.BDREFPAG, x.BDORDEM from ( '||wsqlselect||', 0) '||
            ' UNION ALL ' || wsqlselect || ', 1)  ) X order by X.BDCODEMP, X.BDCODCOL, X.BDTIPOCOL,X.BDCODTPCC, X.BDTIPOCALC, X.BDORDEM, X.BDREFFN, X.BDREFFNAUX, X.BDCODVER ';
  else
    wsql =  wsqlselect||') order by BDCODEMP, BDCODCOL, BDTIPOCALC,BDORDEM, BDREFFN, BDREFFNAUX, BDCODVER ';

  BDCODCENTRO = NULL; BDCODTPCC = NULL; wempatu = 0; 
  wcolatu = 0; wtipocolatu = -1; wrefatu = 0;

  wtpccatu = -1; wcentroatu = -1;
  BDSALARIOBRUTO = 0; BDENCREMUNERACAO = 0; BDPROV13 = 0; BDENCPROV13 = 0;
  BDPROVFER = 0; BDENCPROVFER = 0; BDGRATIFICACOES = 0; 

  BDTOTAL = 0; BDVALORINSS = 0; BDVALORIRRF = 0; BDVALORHE = 0;
  BDOUTROSDESCONTOS = 0; BDSALLIQUIDO = 0; BDOBS = ''; BDDESCCARGO = '';
  BDQTDHORAS = 0; BDVALUMTERCOABONO = 0; BDDATARESCISAO = null; BDREFRESCISAO = 0;
  BDVALRESCISAO = null; BDVALFERIAS = 0; BDVALABONOFERIAS = 0; BDVAL13SALARIO = 0;
  BDPIS = 0; BDGPS = 0; wpercaut = 0; wpercemp = 0; wperccol = 0;
  wcodfpasterc = 0; wpercfpas = 0; wpercrat = 0; wpercpis = 0; wprivez = 0;
  BDCODSIT = 0; BDDESCSIT = ''; wfilialatu = 0; wsimplesgps = 0;
  wbaseinss = 0; wbaseinss13 = 0; wvalor13 = 0;
  wsomabaseinsspatronal = 0; wsomapatronal = 0; wsomaterceiros = 0;
  wsomabaseinssterceiros = 0; wsomabaseinssrat = 0; wsomarat = 0;
  wbasepis = 0; WSOMABASEPIS = 0; wsomapis = 0; wfgts = 0; wfgtsatu = -1; wbasepisatu = -1;
  wClaVer13 = 0;                                         
  wTipoCalc = 0; -- 0 norm; 1-13º; 2-Ad. 13º; 3-Compl; 4-Aut
  wTipoCalcAtu = 0;  wMesmoColOutroCalc = 0;
  w13 = iif(substring(cast(prrefini as varchar(6)) from 5 for 2) = '12', 1, 0);
  wConsideraAd13 = 0; wClaVerResc13 = 0;
  wRefFNAux = 0; wRefPag = 0; wRefFNAuxAtu = 0;
  wvalorc13 = 0; WFGTSRES = 0; WSALDOFGTS = 0; wPERCMULTAFGTS = 0; wPERCMULTAFGTSCS = 0;
  wordematu = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wref, :wtipocol, :wcodcol, :wverba, :wvalor, :wcodcentro, :wcodtpcc, :wcodfilial, :wfgts, :wbasepis, :wTipoCalc, :wRefFNAux, :wRefPag, :wordem DO
    BEGIN
      BDREG = '0500';
      if (wempatu <> wcodemp) then
        begin
            wsqlaux = 'SELECT IMP.BDALIQIMPOSTO FROM TEMPRESAS EMP ' ||
                        'JOIN TEMPRESAIMPOSTO EMPTRIB ON (EMP.BDCODEMP = EMPTRIB.BDCODEMP) ' ||
                        'JOIN TIMPOSTO IMP ON (EMPTRIB.BDCODIMP = IMP.BDCODIMP) ' ||
                       'WHERE EMP.BDCODEMP = ' || wcodemp || ' AND EMP.BDCODMATRIZ IS NULL AND ' ||
                       '      EMPTRIB.BDREFEMP <= ' || wref || ' AND ((coalesce(BDREFFIMIMP,0) = 0) or (BDREFFIMIMP >= ' || wref || ')) AND ' ||
                       '      (IMP.BDTIPORETENCAO = 1) AND IMP.BDDOCARRECADACAO = 1 AND ' ||
                       '      IMP.BDCODSIS = 2 AND IMP.BDTIPOIMPDOC = 2 ';
            EXECUTE STATEMENT wsqlaux INTO :wpercpis;
        end

       IF ((wempatu <> wcodemp)  OR  (wcolatu <> wcodcol)  or (wfilialatu <> wcodfilial)) THEN
         begin
           wok = 1;
           wMesmoColOutroCalc = 0;
           if ((coalesce(prcla,  '') <> '') or (coalesce(prsind,  '') <> '') or (coalesce(prfuc,  '') <> '') or (coalesce(prcc,  '') <> '')) then
              begin
           if (coalesce(wtipocol, 0) = 2) then
                   wsqlaux = 'select first 1 coalesce(BDCODTER,0) from (select first 1 * from VRH_BASE_TTERC_VINC where BDCODTER = '||wcodcol||' and BDREFTERC <= '||wref||' order by BDREFTERC DESC) ';
           else
                   wsqlaux = 'select first 1 coalesce(bdcodcol,0) from (select first 1 * from VRH_EMP_TCOLCON_VINC where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||' and BDREFCOL <= '||wref||' order by BDREFCOL DESC) ';

                wwherefiltro = '';
                if (coalesce(prcla,  '') <> '') then
                   wwherefiltro = ' where '||prcla;

                if (wwherefiltro <> '') then
         begin
                     wok = 0;
                     execute statement wsqlaux||wwherefiltro into :wok;
              wok = coalesce(wok, 0);
         end

      wwherefiltro = '';
      if (coalesce(prsind,  '') <> '') then
         begin
                     if (coalesce(wtipocol, 0) <> 2) then
                        wsqlaux = 'select first 1 coalesce(bdcodcol,0) from (select first 1 * from VRH_EMP_TCOL_VINC where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||' and BDREFCOL <= '||wref||' order by BDREFCOL DESC) ';
                     wwherefiltro = ' where '||prsind;
                   end
        
                if ((wok > 0) and (wwherefiltro <> '')) then
                   begin
                     wok = 0;
                     execute statement wsqlaux||wwherefiltro into :wok;
              wok = coalesce(wok, 0);
         end

           select first 1 ULTDIA from ULTIMO_DIA_MES(CAST(SUBSTRING(:wref FROM 5 FOR 2) AS SMALLINT), CAST(SUBSTRING(:wref FROM 1 FOR 4) AS INTEGER)) into :wdtaux;
           wdtaux = SUBSTRING(:wref FROM 5 FOR 2)||'-'||lpad(wdtaux,  2, '0')||'-'||SUBSTRING(:wref FROM 1 FOR 4);

                wwherefiltro = '';
                if ((wok > 0) and (coalesce(wtipocol, 0) <> 2)) then
                   begin
                     wsqlaux = 'select first 1 coalesce(bdcodcol,0) from (select first 1 * from VRH_EMP_TCOL_VINCDIA where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||' and BDDATACOL <= '''||wdtaux||''' order by BDDATACOL DESC) ';
                     if (coalesce(prfuc,  '') <> '') then
                        begin
                          if (wwherefiltro <> '') then
                             wwherefiltro = wwherefiltro||' and ';
                          else
                             wwherefiltro = ' where ';
                          wwherefiltro = wwherefiltro||prfuc;
                        end
        
                     if (wwherefiltro <> '') then
                        begin
                          wok = 0;
                          execute statement wsqlaux||wwherefiltro into :wok;
                          wok = coalesce(wok, 0);
                        end
                   end
              end
         end
      else if ((((wTipoCalcAtu <> wTipoCalc) or (wRefFNAux = wRefFNAuxAtu and  wtpccatu=wcodtpcc and wordem<>wordematu AND wTipoCalcAtu = wTipoCalc) or
                (wTipoCalc = 3) and (wRefFNAux <> wRefFNAuxAtu)))
              or  ((wRefFNAux <> wRefFNAuxAtu) and (wtipocalcatu = wtipocalc)))  then
        wMesmoColOutroCalc = 1;
      else
        wMesmoColOutroCalc = 0;

      if ((coalesce(wok, 0) > 0) or (coalesce(wOKREGANT,0) > 0)) then
         begin
           wOKREGANT = wOK;
           IF (wempatu = 0) THEN
              wempatu = wcodemp;
           IF (wrefatu = 0) THEN
              wrefatu = wref;
           IF (wtipocolatu = -1) THEN
              wtipocolatu = wtipocol;
           IF (wcolatu = 0) THEN
              wcolatu = wcodcol;
           IF (wtpccatu = -1) THEN
              wtpccatu = wcodtpcc;
           IF (wfilialatu = 0) THEN
              wfilialatu = wcodfilial;
           IF (wordematu = 0) THEN
              wordematu = wordem;
         
           if (wbasepisatu = -1) then
              wbasepisatu = wbasepis;
           else if (wMesmoColOutroCalc > 0) then
              wbasepisatu = wbasepisatu + wbasepis;
          
           if (wfgtsatu = -1) then
              wfgtsatu = wfgts;
           else if (wMesmoColOutroCalc > 0) then
             wfgtsatu = wfgtsatu + wfgts;

           wTipoCalcAtu = wTipoCalc;
           wRefFNAuxAtu = wRefFNAux;
           wordematu = wordem;

           IF ((wempatu <> wcodemp) OR (wRefFNAux <> wRefFNAuxAtu) OR (wcolatu <> wcodcol) or (wfilialatu <> wcodfilial)) THEN
              BEGIN
                BDCODEMP = wempatu;  BDREF = wrefatu;  BDTIPOCOL = wtipocolatu;  BDCODCOL = wcolatu;
                BDCODCENTRO = wcentroatu;  BDCODTPCC = wtpccatu;  BDCODFILIAL = wfilialatu;
                waaux = 0;  wraux = 0; wtaux = 0;
                IF (wtipocolatu = 2) THEN
                   BEGIN
                     bddataadmcol = null;
                     SELECT FIRST 1 SUBSTRING(BDNOMETER FROM 1 FOR 70), BDCGCTER FROM VW_TTERCEIRO WHERE BDCODTER = :wcolatu INTO :BDNOMCOL, :wCPFTER;

                     if (char_length(wCPFTER) > 14) then
                        begin
                          select BDCPFMEITER from TTERCEIRO_RH where bdcodter = :wcolatu into :bdcpfcol;
                          if (bdcpfcol is null) then
                             bdcpfcol = wcpfter;
                        end
                     else
                        bdcpfcol = wCPFTER;

                     wcontrcol = 5;
                   END
                ELSE
                   BEGIN
                     SELECT CAD.BDNOMCOL, C.BDCONTRCOL, SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 6 FOR 2) BDREFADMCOL, R.BDREFRESCISAO, PR.BDTIPOMOV, C.BDCPFCOL, C.BDDATAADMCOL                     FROM VRH_EMP_TCOLCON C
                     LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD CAD ON (CAD.BDCODEMP = C.BDCODEMP AND CAD.BDCODCOL = C.BDCODCOL)
                     LEFT OUTER JOIN VRH_EMP_TRESCISAO R ON (R.BDCODEMP = C.BDCODEMP AND R.BDCODCOL = C.BDCODCOL)
                     LEFT OUTER JOIN VRH_BASE_TPREPRESC PR ON (PR.BDCODPRES = R.BDCODPRES)
                     WHERE C.BDCODEMP = :wfilialatu AND C.BDCODCOL = :wcolatu INTO :BDNOMCOL, :wcontrcol, :waaux, :wraux, :wtaux, :bdcpfcol,  :bddataadmcol;
          
                     IF (wcontrcol = 1) THEN
                        BEGIN
                          wsqlaux = 'select first 1 X.BDGRUPOCLA from VRH_EMP_TCOLCON_VINC Y  join VRH_BASE_TCLASSE X on (X.BDCODCLA = Y.BDCODCLA) where Y.BDCODEMP = '||wfilialatu||' and Y.BDCODCOL = '||wcolatu||' and Y.BDREFCOL <= '||wrefatu||' order by Y.BDREFCOL DESC ';
                          EXECUTE STATEMENT wsqlaux INTO: wcontrcol;
                          IF (wcontrcol = 3) THEN
                             wcontrcol = 4;
                          ELSE
                             wcontrcol = 3;
                        END
                     ELSE
                        wcontrcol = 2;
                   END
          
                wsqlaux = 'select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC';
                EXECUTE STATEMENT wsqlaux INTO: BDNOMEMP;
                BDTIPOFOLHAID = wcontrcol;
                wretorna = 0;
                IF (wcontrcol IN (2,3)) THEN
                   BEGIN
                     IF (prsitcol = 0) THEN -- ativos
                        BEGIN
                          IF ((COALESCE(waaux,0) > wrefatu) OR (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) < wrefatu)) THEN
                             wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 2) THEN --  demit
                        BEGIN
                          IF ((COALESCE(waaux,0) > wrefatu) OR ((COALESCE(wraux,0) = 0) OR (COALESCE(wraux,0) > wrefatu))) THEN
                            wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 3) THEN -- adm mês
                        BEGIN
                          IF (COALESCE(waaux,0) <> wrefatu) THEN
                             wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 4) THEN -- demit mês
                        BEGIN
                          IF ((COALESCE(waaux,0) > wrefatu) OR (COALESCE(wraux,0) <> wrefatu)) THEN
                             wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 5) THEN -- ativos s/ demit mês
                        BEGIN
                          IF ((COALESCE(waaux,0) > wrefatu) OR (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) <= wrefatu)) THEN
                             wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 6) THEN -- ativos s/ demit transf
                        BEGIN
                          IF ((COALESCE(waaux,0) > wrefatu) OR (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) <= wrefatu AND COALESCE(wtaux,0) = 0) OR (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) < wrefatu AND COALESCE(wtaux,0) = 1)) THEN
                             wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 7) THEN -- ativos s/ afast mês inteiro
                        BEGIN
                          IF (COALESCE(waaux,0) > wrefatu) THEN
                             wretorna = 1;
          
                          IF (wretorna = 0) THEN
                             BEGIN
                               wsqlaux = 'select first 1 BDCODCOL from VRH_EMP_TSITCOL where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                                         ' and ((BDDATAFIMSIT is null) or (SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';
                               EXECUTE STATEMENT wsqlaux INTO :wretorna;
                               IF (COALESCE(wretorna,0) > 0) THEN
                                  wretorna = 1;
                               ELSE
                                  wretorna = 0;
                             END
                        END
                     ELSE
                     IF (prsitcol = 8) THEN -- afast mês inteiro
                        BEGIN
                          IF (COALESCE(waaux,0) > wrefatu) THEN
                             wretorna = 1;
          
                          IF (wretorna = 0) THEN
                             BEGIN
                               wsqlaux = 'select first 1 BDCODCOL from VRH_EMP_TSITCOL where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                                         ' and ((BDDATAFIMSIT is null) or (SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';
                               EXECUTE STATEMENT wsqlaux INTO :wretorna;
                               IF (COALESCE(wretorna,0) = 0) THEN
                                  wretorna = 1;
                               ELSE
                                  wretorna = 0;
                             END
                        END
                   END
          
                IF (wretorna = 0) THEN
                   BEGIN
                     wpercinss = 0;
                     IF ((wempatu <> wcodemp) OR (wrefatu <> wref) OR (wprivez = 0) or (wfilialatu <> wcodfilial)) THEN
                        BEGIN
                          wsqlaux = 'select first 1 BDAUTEMP, BDEMPEMP, BDFUNEMP, BDCODFPASTERC, BDFAP, BDSIMPLESGPS from VRHF_BASE_TEMPGPS where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC ';
                          EXECUTE STATEMENT wsqlaux INTO :wpercaut, :wpercemp, :wperccol, :wcodfpasterc, :wfap, :wsimplesgps;
                          wmp932 = null;
                          select first 1 BDNAOAPLICAMP932 from VRHF_BASE_TEMPMP932 where BDCODEMP = :wfilialatu into :wmp932;
                          wmp932 = upper(coalesce(wmp932, 'FALSE'));
                          wsimplesgps = coalesce(wsimplesgps, 0);
                          IF (coalesce(wcodfpasterc, 0) > 0) THEN
                             begin
                               if (coalesce(wrefatu, 0) in (202004, 202005, 202006) and wmp932 = 'FALSE') then
                                  select coalesce(BDSALEDU, 0) + coalesce(BDINCRA, 0) + coalesce(BDSENAI, 0) * 0.5 + coalesce(BDSESI, 0) * 0.5 + coalesce(BDSENAC, 0) * 0.5 + coalesce(BDSESC, 0) * 0.5 + 
                                         coalesce(BDSEBRAE, 0) + coalesce(BDDPC, 0) + coalesce(BDFUNAERO, 0) + coalesce(BDSENAR, 0) * 0.5 + coalesce(BDSEST, 0) * 0.5 + coalesce(BDSENAT, 0) * 0.5 +
                                         coalesce(BDSESCOOP, 0) * 0.5 from VRH_BASE_TFPAS_TERCEIROS WHERE BDCODFPASTERC = :wcodfpasterc INTO :wpercfpas;
                               else
                                  SELECT BDPERTERC FROM VRH_BASE_TFPAS_TERCEIROS WHERE BDCODFPASTERC = :wcodfpasterc INTO :wpercfpas;
                             end
          
                          wcodcnae = 0;
                          wsqlaux = 'select first 1 COALESCE(BDCNAEPREP, BDCODCNAE, 0), 0 BDCODCENTROS, BDNOMEMP from TEMPRESAS_REF where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC ';
                          EXECUTE STATEMENT wsqlaux INTO :wcodcnae, :BDCODCENTRO, :wnomemp;
               
                          BDCODCENTRO = wcentroatu;
          
                          IF (wcodcnae IS NOT NULL AND wcodcnae > 0) THEN
                             BEGIN
                               wsqlaux = 'select first 1 BDTAXACNAE from TCNAE_REF where BDCODCNAE = '||wcodcnae||' and BDREFCNAE <= ' ||wrefatu||' order by BDREFCNAE desc ';
                               EXECUTE STATEMENT wsqlaux INTO :wpercrat;
                             END

                          IF (wfap IS NULL) THEN
                             wfap = 0;
                          wpercrat = CAST((wpercrat * wfap) AS NUMERIC(18, 4));
                        END
          
                     wprivez = 1;
          
                     IF (wcontrcol = 5) THEN
                        wpercinss = wpercaut;
                     ELSE
                     IF (wcontrcol = 3) THEN
                        wpercinss = wpercemp;
                     ELSE
                        wpercinss = wperccol;
          
                     -- SIMPLES
                     if (wsimplesgps in (1, 2, 5)) then
                        begin
                          wpercinss = 0;
                          wpercfpas = 0;
                          wpercrat  = 0;
                        end

                     if (wbaseinss < 0) then
                       wbaseinss = 0;
     
                     wbaseinss = wbaseinss + wbaseinss13;
     
                     BDINSSPATRONAL = 0;
                     BDINSSPATRONALCOL = 0;
                     BDINSSPATRONALEMP = 0;
                     IF (wpercinss IS NOT NULL AND wpercinss > 0 and wbaseinss <> 0) THEN
                        BEGIN
                          BDINSSPATRONAL = CAST(((wbaseinss * wpercinss / 100) - 0.005) AS NUMERIC(18, 2));
                          BDINSSPATRONALCOL = BDINSSPATRONALCOL + BDINSSPATRONAL;
                          wsomabaseinsspatronal = wsomabaseinsspatronal + wbaseinss;
                          wsomapatronal = wsomapatronal + BDINSSPATRONAL;
                          wvaloragrupado = CAST(((wsomabaseinsspatronal * wpercinss / 100) - 0.005) AS NUMERIC(18, 2));
                          while (wvaloragrupado > wsomapatronal) do
                            begin
                              BDINSSPATRONAL = BDINSSPATRONAL + 0.01;
                              wsomapatronal = wsomapatronal + 0.01;
                            end
                          BDENCREMUNERACAO = BDENCREMUNERACAO + BDINSSPATRONAL;
                        END
          
                     BDTERC = 0;
                     IF ( wpercfpas IS NOT NULL AND wpercfpas > 0 and wcontrcol = 2 and wbaseinss <> 0) THEN
                        BEGIN
                          BDTERC = CAST(((wbaseinss * wpercfpas / 100) - 0.005) AS NUMERIC(18, 2));
                          wsomabaseinssterceiros = wsomabaseinssterceiros + wbaseinss;
                          wsomaterceiros = wsomaterceiros + BDTERC;
                          wvaloragrupado = CAST(((wsomabaseinssterceiros * wpercfpas / 100) - 0.005) AS NUMERIC(18, 2));
                          while (wvaloragrupado > wsomaterceiros) do
                            begin
                              BDTERC = BDTERC + 0.01;
                              wsomaterceiros = wsomaterceiros + 0.01;
                            end
                          BDENCREMUNERACAO = BDENCREMUNERACAO + BDTERC;
                        END
          
                     BDRAT = 0;
                     IF ((wpercrat IS NOT NULL) AND (wpercrat > 0) and (wcontrcol = 2) and (wbaseinss <> 0) ) THEN
                        BEGIN
                          BDRAT = CAST(((wbaseinss * wpercrat / 100) - 0.005) AS NUMERIC(18, 2));
                          wsomabaseinssrat = wsomabaseinssrat + wbaseinss;
                          wsomarat = wsomarat + BDRAT;
                          wvaloragrupado = CAST(((wsomabaseinssrat * wpercrat / 100) - 0.005) AS NUMERIC(18, 2));
                          while (wvaloragrupado > wsomarat) do
                            begin
                              BDRAT = BDRAT + 0.01;
                              wsomarat = wsomarat + 0.01;
                            end
                          BDENCREMUNERACAO = BDENCREMUNERACAO + BDRAT;
                        END

                     BDPIS = 0;
                     IF ((wbasepisatu <> 0) and (wpercpis > 0 )) THEN
                     BEGIN
                        bdpis = CAST(((wbasepisatu * wpercpis / 100) - 0.005) AS NUMERIC(18,2));
                        wsomabasepis = wsomabasepis + wbasepisatu;
                        wsomapis = wsomapis + bdpis;
                        wvaloragrupado = CAST(((wsomabasepis * wpercpis / 100) - 0.005) AS NUMERIC(18, 2));
                        while (wvaloragrupado > wsomapis) do
                          begin
                            bdpis = bdpis + 0.01;
                            wsomapis = wsomapis + 0.01;
                          end
                     END

                     BDRATAPO = 0; BDPROV13 = 0; BDENCPROV13 = 0; BDPROVFER = 0; BDENCPROVFER = 0; BDFGTS = 0;
          
                     IF ((coalesce(wtipocolatu,0) < 2) and (wcontrcol in (2, 3))) THEN
                        BEGIN
                          wpercinss = 0;
                               WGRRFPRES = -1;
                          SELECT MOTRESC.BDGRRFPRES FROM VRH_EMP_TRESCISAO RESC LEFT JOIN VRH_BASE_TPREPRESC MOTRESC ON (RESC.BDCODPRES = MOTRESC.BDCODPRES) WHERE RESC.BDCODEMP = :wfilialatu AND RESC.BDCODCOL = :wcolatu AND RESC.BDREFRESCISAO <= :wrefatu INTO :WGRRFPRES;
                               IF (WGRRFPRES <= 0) THEN
                                 BEGIN
                                   BDFGTS = wfgtsatu;
                               BDENCREMUNERACAO = BDENCREMUNERACAO + BDFGTS;
                             END
                               ELSE
                                 BDFGTS = 0;

                          IF (BDSALARIOBRUTO <> 0 AND wpercinss IS NOT NULL AND wpercinss > 0) THEN
                             BEGIN
                               BDRATAPO = CAST(((BDSALARIOBRUTO * wpercinss / 100) - 0.005) AS NUMERIC(18, 2));
                               BDENCREMUNERACAO = BDENCREMUNERACAO + BDRATAPO;
                             END
               
                          BDPROV13 = 0;
                          BDENCPROV13 = 0;
                          wsqlaux = 'select SUM(BDVLR13SALP13) BDVALPROV13, SUM(BDFGTSP13 + BDINSSP13 + BDTERCFPASP13 + BDCNAERATP13 + BDRATAPOP13 + BDPISP13) BDENCPROV13 from VRHF_EMP_TPROVISAO13 where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and BDREFP13 = '||wrefatu||' and BDLINHAP13 in (6,7,8,9,19) ';
          
                          EXECUTE STATEMENT wsqlaux INTO :BDPROV13, :BDENCPROV13;
                          IF (BDPROV13 IS NULL) THEN
                             BDPROV13 = 0;
                          IF (BDENCPROV13 IS NULL) THEN
                             BDENCPROV13 = 0;
          
                          wsqlaux = 'select SUM(BDFERIASPFER + BDUMTERCOPFER) BDVALPROVFER, SUM(BDFGTSPFER + BDINSSPFER + BDTERCFPASPFER + BDCNAERATPFER + BDRATAPOPFER + BDPISPFER) BDENCPROVFER from VRHF_EMP_TPROVISAOFERIAS where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and BDREFPFER = '||wrefatu||' and BDLINHAPFER in (4,5,6,7,14) ';
          
                          BDPROVFER = 0;
                          BDENCPROVFER = 0;
                          EXECUTE STATEMENT wsqlaux INTO :BDPROVFER, :BDENCPROVFER;
                          IF (BDPROVFER IS NULL) THEN
                             BDPROVFER = 0;
                          IF (BDENCPROVFER IS NULL) THEN
                             BDENCPROVFER = 0;
                        END
          
                     IF (wtpccatu > 0 AND wcentroatu > 0) THEN
                        BEGIN
                          wsqlaux = 'select first 1 case when TRIM(COALESCE(CCRH.BDNOMETOM, '''')) <> '''' then CCRH.BDNOMETOM else CC.BDNOMCTA end BDNOMCC from CENTROS_TPCC CC '||'left outer join VRH_BASE_TCUSTOM CCRH on (CCRH.BDCODCENTRO = CC.BDCODCENTRO and CCRH.BDCODTPCC = CC.BDCODTPCC) '|| 'where CC.BDCODCENTRO = '||wcentroatu||' and CC.BDCODTPCC = '||wtpccatu;
                          EXECUTE STATEMENT wsqlaux INTO :BDNOMTPCC;
                        END
                     ELSE
                        BDNOMTPCC = wnomemp;
          
                     BDCODSIT = 0;
                     BDDESCSIT = '';
                     IF (coalesce(wtipocolatu,0) <> 2) THEN
                        begin
                     if (BDSALARIOBRUTO + BDENCREMUNERACAO + BDGRATIFICACOES + BDPROV13 + BDENCPROV13 + BDPROVFER + BDENCPROVFER <= 0) then
                        begin
                              wsqlaux = 'select first 1 ST.BDCODSIT, PST.BDDESCSIT from VRH_EMP_TSITCOL ST join VRH_BASE_TPREPSIT PST on (PST.BDCODSIT = ST.BDCODSIT) where ST.BDCODEMP = '||wfilialatu||' and ST.BDCODCOL = '||wcolatu||
                                        ' and SUBSTRING(CAST(ST.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(ST.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||' and ((ST.BDDATAFIMSIT is null) or (SUBSTRING(CAST(ST.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(ST.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';
                          execute statement wsqlaux into :BDCODSIT, :BDDESCSIT;
                        end
                        end

                     BDQTDHORAS = null;
                     IF (coalesce(wtipocolatu,0) <> 2) THEN
                        SELECT FIRST 1 BDHORASMENSAISCOL FROM VRHF_EMP_TCOL_CALC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu AND BDREFCOL <= :wrefatu ORDER BY BDREFCOL DESC INTO :BDQTDHORAS;

                     BDTOTAL = BDSALARIOBRUTO + BDENCREMUNERACAO + BDGRATIFICACOES + BDPROV13 + BDENCPROV13 + BDPROVFER + BDENCPROVFER;

                     BDDESCCARGO = null;
                     IF (coalesce(wtipocolatu,0) <> 2) THEN
                        begin
                          select first 1 ULTDIA from ULTIMO_DIA_MES(CAST(SUBSTRING(:wref FROM 5 FOR 2) AS SMALLINT), CAST(SUBSTRING(:wref FROM 1 FOR 4) AS INTEGER)) into :wdtaux;
                          wdtaux = SUBSTRING(:wref FROM 5 FOR 2)||'-'||lpad(wdtaux,  2, '0')||'-'||SUBSTRING(:wref FROM 1 FOR 4);
                          BDDESCCARGO = null;
                          SELECT SUBSTRING(TFUC.BDDESCTFUC from 1 for 40) FROM (select first 1 BDCODPLAFUC, BDCODTFUC from VRH_EMP_TCOL_VINCDIA where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDDATACOL <= CAST(:wdtaux AS DATE) order by BDDATACOL DESC) VINC LEFT OUTER JOIN VRH_FUNCOES_TFUC TFUC on (TFUC.BDCODPLAFUC = VINC.BDCODPLAFUC and TFUC.BDCODTFUC = VINC.BDCODTFUC) into :BDDESCCARGO;
                        end
                     else
                        select first 1 cbo.bddesccbo from VRH_BASE_TTERC_VINC vinc left outer join VRH_BASE_TCBO cbo on (vinc.BDCODCBO = cbo.BDCODCBO) where BDCODTER = :wcolatu and BDREFTERC <= :wref order by BDREFTERC DESC into :BDDESCCARGO;

                     if (coalesce(bdvalrescisao, 0) > 0) then
                       bdsalliquido = 0;

                     if (w13 > 0) then
                       begin
                         select BDVALC13 from VRHF_EMP_TC13SAL where BDCODEMP = :bdcodemp and BDCODCOL = :bdcodcol and BDREFC13 = :prrefini INTO :wValorC13;
                         if (coalesce(wValorC13, 0) > 0) then
                           bdval13salario = wValorC13;
                       end

                     SUSPEND;
                   END
          
                if ((wempatu <> wcodemp) or (wrefatu <> wref)) then
                   begin
                     wsomabaseinsspatronal = 0; wsomapatronal = 0; wsomaterceiros = 0; wsomabaseinssterceiros = 0; wsomabaseinssrat = 0;
                     wsomarat = 0;
                     WSOMABASEPIS = 0;
                     WSOMAPIS = 0;
                   end

                wempatu = wcodemp;
                wrefatu = wref;
                wtipocolatu = wtipocol;
                wcolatu = wcodcol;
                wtpccatu = wcodtpcc;
                wfilialatu = wcodfilial;
                wordematu = wordem;
                BDSALARIOBRUTO = 0; BDENCREMUNERACAO = 0;
                BDPROV13 = 0; BDENCPROV13 = 0; BDPROVFER = 0; BDENCPROVFER = 0;
                BDGRATIFICACOES  = 0;
                wbaseinss = 0; wbaseinss13 = 0;
                BDVALORHE = 0;
                BDVALORIRRF = 0;  BDVALORINSS = 0;  BDSALLIQUIDO = 0;
                BDCODCENTRO = 0;  BDCODTPCC = 0;
                BDDATARESCISAO = null; BDREFRESCISAO = 0;  BDVALRESCISAO = null;
                BDVALFERIAS = 0; BDVALABONOFERIAS = 0;
                BDVAL13SALARIO = 0;
                BDGPS = 0;
                BDQTDHORAS = 0;
                BDFGTS = 0;
                wfgtsatu = wfgts;
                wbasepisatu = wbasepis;
                wValorC13 = 0;

                --IR Ferias rec
                wsqlaux =  'select SUM(BDVALVFE) VALIRFE from VRHF_EMP_TVERBAFE v '||
                      '  JOIN VRH_BASE_TVERBAS t ON (T.BDCODVER = V.BDCODVER) '||
                      '  JOIN VRH_EMP_TFERIAS f ON (f.BDCODEMP = v.BDCODEMP AND f.BDCODCOL = v.BDCODCOL AND f.BDINIPERAQUISFE = v.BDINIPERAQUISFE AND f.BDCODFE = v.BDCODFE) '||
                      ' WHERE (F.BDREFIRRFESOCIAL = '||prrefini||') AND (T.BDCLAVER LIKE ''9.010.1.2%'') ' ||
                      ' and v.BDCODEMP = ' || wempatu || ' and v.BDCODCOL = ' || wcolatu;

                   EXECUTE STATEMENT wsqlaux INTO :BDVALORIRRF;
              END
          
           wcentroatu = wcodcentro;
          
           wsqlaux = 'select first 1 REF.BDINSSVER, REF.BDTIPOCODVER, VERB.BDCLAVER,  REF.bdbasegpsver from VRH_BASE_TVERBAS_REF REF  join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = REF.BDCODVER) where REF.BDCODVER = '||wverba||' and REF.BDREFVER <= '||wrefatu||' order by REF.BDREFVER DESC';
           EXECUTE STATEMENT wsqlaux INTO :winssver, :wtipocodver, :wclaver, :wbasegps;
          
           if (wTipoCalc in (1,2,5)) then
             wClaVer13 = 1;
           else
             wClaVer13 = 0;

           if ((SUBSTRING(wclaver FROM 1 FOR 5) = '7.050') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.060') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') or (SUBSTRING(wclaver FROM 1 FOR 5) = '7.080') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.090')) then
             wClaVerResc13 = 1;
           else
             wClaVerResc13 = 0;

           if (((w13 > 0) and (wTipoCalc <> 2)) or (w13 = 0)) then
             wConsideraAd13 = 1;
           else
             wConsideraAd13 = 0;

           if (SUBSTRING(wclaver FROM 1 FOR 7) = '9.010.0') then
                bdvalorinss = bdvalorinss + wvalor;
           else
           if ((SUBSTRING(wclaver FROM 1 FOR 7) = '9.010.1') AND (prRefIni = wRefPag)
              AND (SUBSTRING(wclaver FROM 1 FOR 9) <> '9.010.1.2')) /* IR fer Recolhido pela ref pgto fer */ then
                begin
                    bdvalorirrf = bdvalorirrf + wvalor;
                    if ((prrefini <> WREFFNAUX) and (wtipocalc=0)) then /* normal com ref ir diferente ref folha normal, pagto mes posterior  */
                        bdsalliquido = bdsalliquido + wvalor;
                end
           else
           if (SUBSTRING(wclaver FROM 1 FOR 7) = '0.006.0') then
              begin
                if (wverba <> 243) then
                bdvalorhe = bdvalorhe + wvalor;
              end
           else
           if ((SUBSTRING(wclaver FROM 1 FOR 5) = '0.100') or (SUBSTRING(wclaver FROM 1 FOR 5) = '0.110') or (SUBSTRING(wclaver FROM 1 FOR 5) = '0.140') or (SUBSTRING(wclaver FROM 1 FOR 5) = '0.150') or 
               (SUBSTRING(wclaver FROM 1 FOR 5) = '0.180') or (SUBSTRING(wclaver FROM 1 FOR 5) = '7.020') or (SUBSTRING(wclaver FROM 1 FOR 5) = '7.030') or (SUBSTRING(wclaver FROM 1 FOR 5) = '7.032') or (SUBSTRING(wclaver FROM 1 FOR 5) = '7.010')) then
                bdvalferias = bdvalferias + wvalor;
           else
           if ((SUBSTRING(wclaver FROM 1 FOR 5) = '0.120') or (SUBSTRING(wclaver FROM 1 FOR 5) = '0.130') or (SUBSTRING(wclaver FROM 1 FOR 5) = '0.160') or (SUBSTRING(wclaver FROM 1 FOR 5) = '0.170') or 
               (SUBSTRING(wclaver FROM 1 FOR 5) = '7.012') or (SUBSTRING(wclaver FROM 1 FOR 5) = '7.021') or (SUBSTRING(wclaver FROM 1 FOR 5) = '7.031') or (SUBSTRING(wclaver FROM 1 FOR 5) = '7.033')) then
                bdvalabonoferias = bdvalabonoferias + wvalor;
            else
            if ((SUBSTRING(wclaver FROM 1 FOR 5) = '9.050') or (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005')) then
                bdgps = bdgps + wvalor;

            IF ((COALESCE(wtipocodver, 0) = 0) and (wClaVer13 = 0)) then
              BDSALARIOBRUTO = BDSALARIOBRUTO + wvalor;

           if (SUBSTRING(wclaver FROM 1 FOR 9) = '0.010.0.0') then
              bdoutrosdescontos = bdoutrosdescontos + wvalor;

            if ((wConsideraAd13 > 0) and (wClaVer13 = 0)) then
              begin
           IF ((COALESCE(wtipocodver, 0) = 0) and (wRef = prrefini)) THEN
              bdsalliquido = bdsalliquido + wvalor;
           ELSE
           IF ((COALESCE(wtipocodver, 0) = 1) and (wRef = prrefini)) THEN
              bdsalliquido = bdsalliquido - wvalor;
              end

           if (coalesce(wbasegps,'FALSE') = 'TRUE') then
              begin
                IF (COALESCE(wtipocodver, 0) = 0) THEN
                  BEGIN
                    IF (wClaVerResc13 = 1) THEN
                      wbaseinss13 = wbaseinss13 + wvalor;
                ELSE
                      wbaseinss = wbaseinss + wvalor;
                  END
                ELSE
                IF (COALESCE(wtipocodver, 0) = 1) THEN
                  BEGIN
                    IF (wClaVerResc13 = 1) THEN
                      wbaseinss13 = wbaseinss13 - wvalor;
                ELSE
                      wbaseinss = wbaseinss - wvalor;
                  END
              end

           for select BDCODVER from VRH_BASE_TCONFIG_RELCUSTO where BDCODEMP = :wcodemp and BDCODVER = :wverba into :wcodveraux do
             BDGRATIFICACOES = BDGRATIFICACOES + coalesce(wvalor,0);

           SELECT r.bddatarescisao, r.bdrefrescisao, m.BDPERCMULTAFGTS, m.BDPERCMULTAFGTSCS,  R.BDSALDOFGTS FROM VRH_EMP_TRESCISAO  r join VRH_BASE_TPREPRESC m ON m.BDCODPRES = r.BDCODPRES
           where BDCODEMP = :wcodemp and BDCODCOL = :wcodcol and bdrefrescisao <= :wref into :bddatarescisao,  :bdrefrescisao, :wPERCMULTAFGTS, : wPERCMULTAFGTSCS, wSaldoFgts;

           if (BDDATARESCISAO IS NOT NULL) then
              begin
                select sum(bdliquido), sum(BDFGTS + BDFGTS13) from(
                    select bdliquido, BDFGTSFT BDFGTS, BDFGTS13FT  BDFGTS13 from VRHF_EMP_TFOLHATOMADOR where bdcodemp = :wcodemp and bdcodcol = :wcodcol and bdreftomador = :bdrefrescisao and bdreftomador = :PRREFINI
                    union all
                    select bdliquido, BDFGTSFN BDFGTS, BDFGTS13FN BDFGTS13 from VRHF_EMP_TFOLHANORMAL where bdcodemp = :wcodemp and bdcodcol = :wcodcol and bdreffn = :bdrefrescisao and bdreffn = :PRREFINI
                    union all
                    select bdliquido, BDFGTSFT BDFGTS, BDFGTS13FT BDFGTS13 from VRHF_EMP_TFOLHATOMINT  where bdcodemp = :wcodemp and bdcodcol = :wcodcol and bdreftomador = :bdrefrescisao  and bdreftomador = :PRREFINI
                    union all
                    select bdliquido, BDFGTSFN BDFGTS, BDFGTS13FN BDFGTS13 from VRHF_EMP_TFOLHAINT where bdcodemp = :wcodemp and bdcodcol = :wcodcol and bdreffn = :bdrefrescisao and bdreffn = :PRREFINI
                    union all
                    select bdliquido, BDFGTSFC BDFGTS, BDFGTS13FC BDFGTS13 from VRHF_EMP_TFOLTOMCOMP where bdcodemp = :wcodemp and bdcodcol = :wcodcol and bdrefcomp = :prrefini
                    union all
                    select bdliquido, BDFGTSFC BDFGTS, BDFGTS13FC BDFGTS13 from VRHF_EMP_TFOLHACOMP where bdcodemp = :wcodemp and bdcodcol = :wcodcol and bdrefcomp = :prrefini
                    union all
                    select bdliquido, BDFGTSFC BDFGTS, BDFGTS13FC BDFGTS13 from VRHF_EMP_TFOLTOMCOMPINT where bdcodemp = :wcodemp and bdcodcol = :wcodcol and bdrefcomp = :prrefini
                    union all
                    select bdliquido, BDFGTSFC BDFGTS, BDFGTS13FC BDFGTS13 from VRHF_EMP_TFOLHACOMPINT where bdcodemp = :wcodemp and bdcodcol = :wcodcol and bdrefcomp = :prrefini
                ) into :bdvalrescisao, :wfgtsres;

                BDMULTAFGTS = CAST((CAST(wfgtsres AS NUMERIC(12,2))) * wPERCMULTAFGTS/100 AS NUMERIC(12,2)) + cast((wSaldoFgts) * wPERCMULTAFGTS/100 AS NUMERIC(12,2));
                BDMULTAFGTSCS = CAST((CAST(wfgtsres AS NUMERIC(12,2))) * wPERCMULTAFGTSCS/100 AS NUMERIC(12,2)) + cast((wSaldoFgts) * wPERCMULTAFGTSCS/100 AS NUMERIC(12,2));
                BDFGTSRES = wfgtsres;
              end
           else
              begin
                BDMULTAFGTS = 0;
                BDMULTAFGTSCS = 0;
                BDFGTSRES = 0;
              end

           IF ((wClaVerResc13 > 0) or (wClaVer13 > 0) and (COALESCE(wtipocodver, 0) = 0) and ((wConsideraAd13 > 0) and (BDDATARESCISAO IS NULL))) then
                bdval13salario = bdval13salario + wvalor;
              end
    END

 IF ((coalesce(wok, 0) > 0) and (wempatu <> 0) AND (wrefatu <> 0) AND (wcolatu <> 0) AND (wtpccatu <> -1) and (wfilialatu <> 0)) THEN
    BEGIN
      BDCODEMP = wempatu;
      BDREF = wrefatu;
      BDTIPOCOL = wtipocolatu;
      BDCODCOL = wcolatu;
      BDCODCENTRO = wcentroatu;
      BDCODTPCC = wtpccatu;
      BDCODFILIAL = wfilialatu;
      waaux = 0;
      wraux = 0;
      wtaux = 0;
      wprivez = 0;

      IF (wtipocolatu = 2) THEN
         BEGIN
           SELECT FIRST 1 SUBSTRING(BDNOMETER FROM 1 FOR 70), BDCGCTER FROM VW_TTERCEIRO WHERE BDCODTER = :wcolatu INTO :BDNOMCOL, :wCPFTER;

           if (char_length(wCPFTER) > 14) then
              begin
                select BDCPFMEITER from TTERCEIRO_RH where bdcodter = :wcolatu into :bdcpfcol;
                if (bdcpfcol is null) then
                   bdcpfcol = wcpfter;
              end
           else
              bdcpfcol = wCPFTER;

           wcontrcol = 5;
         END
      ELSE
         BEGIN
           SELECT CAD.BDNOMCOL, C.BDCONTRCOL, SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 6 FOR 2) BDREFADMCOL, R.BDREFRESCISAO, PR.BDTIPOMOV, C.BDCPFCOL, C.BDDATAADMCOL
           FROM VRH_EMP_TCOLCON C
           LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD CAD ON (CAD.BDCODEMP = C.BDCODEMP AND CAD.BDCODCOL = C.BDCODCOL)
           LEFT OUTER JOIN VRH_EMP_TRESCISAO R ON (R.BDCODEMP = C.BDCODEMP AND R.BDCODCOL = C.BDCODCOL)
           LEFT OUTER JOIN VRH_BASE_TPREPRESC PR ON (PR.BDCODPRES = R.BDCODPRES)
           WHERE C.BDCODEMP = :wfilialatu AND C.BDCODCOL = :wcolatu INTO :BDNOMCOL, :wcontrcol, :waaux, :wraux, :wtaux, :bdcpfcol, :bddataadmcol;

           IF (wcontrcol = 1) THEN
              BEGIN
                wsqlaux = 'select first 1 X.BDGRUPOCLA from VRH_EMP_TCOLCON_VINC Y join VRH_BASE_TCLASSE X on (X.BDCODCLA = Y.BDCODCLA) where Y.BDCODEMP = '||wfilialatu||' and Y.BDCODCOL = '||wcolatu||' and Y.BDREFCOL <= '||wrefatu||' order by Y.BDREFCOL DESC ';
                EXECUTE STATEMENT wsqlaux INTO: wcontrcol;

                IF (wcontrcol = 3) THEN
                   wcontrcol = 4;
                ELSE
                   wcontrcol = 3;
              END
           ELSE
              wcontrcol = 2;

         END

      wsqlaux = 'select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC';
      EXECUTE STATEMENT wsqlaux INTO: BDNOMEMP;
      BDTIPOFOLHAID = wcontrcol;
      wretorna  = 0;
      IF (wcontrcol IN (2,3)) THEN
         BEGIN
           IF (prsitcol = 0) THEN   -- ativos
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) < wrefatu) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 2) THEN -- dem
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF ((COALESCE(wraux,0) = 0) OR (COALESCE(wraux,0) > wrefatu)) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 3) THEN -- adm mês
              BEGIN
                IF (COALESCE(waaux,0) <> wrefatu) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 4) THEN -- dem mês
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) <> wrefatu) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 5) THEN -- ativos s/ dem mês
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) <= wrefatu) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 6) THEN -- ativos s/ dem c/ trans
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) <= wrefatu AND COALESCE(wtaux,0) = 0) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) < wrefatu AND COALESCE(wtaux,0) = 1) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 7) THEN   -- ativos s/ afast mês inteiro
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (wretorna = 0) THEN
                   BEGIN
                     wsqlaux = 'select first 1 BDCODCOL from VRH_EMP_TSITCOL where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu|| ' and SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu|| ' and ((BDDATAFIMSIT is null) or (SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';

                     EXECUTE STATEMENT wsqlaux INTO :wretorna;

                     IF (COALESCE(wretorna,0) > 0) THEN
                        wretorna = 1;
                     ELSE
                        wretorna = 0;
                   END
              END
           ELSE
           IF (prsitcol = 8) THEN -- afast mês inteiro
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (wretorna = 0) THEN
                   BEGIN
                     wsqlaux = 'select first 1 BDCODCOL from VRH_EMP_TSITCOL where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu|| ' and SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu|| ' and ((BDDATAFIMSIT is null) or (SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';

                     EXECUTE STATEMENT wsqlaux INTO :wretorna;

                     IF (COALESCE(wretorna,0) = 0) THEN
                        wretorna = 1;
                     ELSE
                        wretorna = 0;
                   END
              END
         END

      IF (wretorna = 0) THEN
         BEGIN
           wpercinss = 0;
           IF ((wempatu <> wcodemp) OR (wrefatu <> wref) OR (wprivez = 0) or (wfilialatu <> wcodemp)) THEN
              BEGIN
                wsqlaux = 'select first 1 BDAUTEMP, BDEMPEMP, BDFUNEMP, BDCODFPASTERC, BDFAP, BDSIMPLESGPS from VRHF_BASE_TEMPGPS where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC ';
                EXECUTE STATEMENT wsqlaux INTO :wpercaut, :wpercemp, :wperccol, :wcodfpasterc, :wfap, :wsimplesgps;

                IF (coalesce(wcodfpasterc, 0) > 0) THEN
                   begin
                     wmp932 = null;
                     select first 1 BDNAOAPLICAMP932 from VRHF_BASE_TEMPMP932 where BDCODEMP = :wfilialatu into :wmp932;
                     wmp932 = upper(coalesce(wmp932, 'FALSE'));

                     if (coalesce(wrefatu, 0) in (202004, 202005, 202006) and wmp932 = 'FALSE') then
                        select coalesce(BDSALEDU, 0) + coalesce(BDINCRA, 0) + coalesce(BDSENAI, 0) * 0.5 + coalesce(BDSESI, 0) * 0.5 +
                               coalesce(BDSENAC, 0) * 0.5 + coalesce(BDSESC, 0) * 0.5 + coalesce(BDSEBRAE, 0) + coalesce(BDDPC, 0) +
                               coalesce(BDFUNAERO, 0) + coalesce(BDSENAR, 0) * 0.5 + coalesce(BDSEST, 0) * 0.5 + coalesce(BDSENAT, 0) * 0.5 +
                               coalesce(BDSESCOOP, 0) * 0.5 from VRH_BASE_TFPAS_TERCEIROS WHERE BDCODFPASTERC = :wcodfpasterc INTO :wpercfpas;
                     else
                        SELECT BDPERTERC FROM VRH_BASE_TFPAS_TERCEIROS WHERE BDCODFPASTERC = :wcodfpasterc INTO :wpercfpas;
                   end


                IF (wcodfpasterc IS NOT NULL AND wcodfpasterc > 0) THEN
                   SELECT BDPERTERC FROM VRH_BASE_TFPAS_TERCEIROS WHERE BDCODFPASTERC = :wcodfpasterc INTO :wpercfpas;

                wsimplesgps = coalesce(wsimplesgps, 0);

                wcodcnae = 0;
                wsqlaux = 'select first 1 COALESCE(BDCNAEPREP, BDCODCNAE, 0), 0 BDCODCENTROS, BDNOMEMP from TEMPRESAS_REF where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC ';
                EXECUTE STATEMENT wsqlaux INTO :wcodcnae, :BDCODCENTRO, :wnomemp;
     
                BDCODCENTRO = wcentroatu;

                IF (wcodcnae IS NOT NULL AND wcodcnae > 0) THEN
                   BEGIN
                     wsqlaux = 'select first 1 BDTAXACNAE from TCNAE_REF where BDCODCNAE = '||wcodcnae||' and BDREFCNAE <= ' ||wrefatu||' order by BDREFCNAE desc ';
                     EXECUTE STATEMENT wsqlaux INTO :wpercrat;
                   END

                IF (wfap IS NULL)  THEN
                   wfap = 0;
                wpercrat = CAST((wpercrat * wfap) AS NUMERIC(18, 4));
              END

           wprivez = 1;

           IF (wcontrcol = 5) THEN
              wpercinss = wpercaut;
           ELSE
           IF (wcontrcol = 3) THEN
              wpercinss = wpercemp;
           ELSE
              wpercinss = wperccol;

           -- SIMPLES
           if (wsimplesgps in (1, 2, 5)) then
              begin
                wpercinss = 0;
                wpercfpas = 0;
                wpercrat  = 0;
              end

           if (wbaseinss < 0) then
               wbaseinss = 0;
    
           wbaseinss = wbaseinss + wbaseinss13;
          
           BDINSSPATRONAL = 0;
           BDINSSPATRONALCOL = 0;
           BDINSSPATRONALEMP = 0;

           IF (BDSALARIOBRUTO <> 0 AND wpercinss IS NOT NULL AND wpercinss > 0 and wbaseinss <> 0) THEN
              BEGIN
                BDINSSPATRONAL = CAST(((wbaseinss * wpercinss / 100) - 0.005) AS NUMERIC(18, 2));
                BDINSSPATRONALEMP = BDINSSPATRONALEMP + BDINSSPATRONAL;
                wsomabaseinsspatronal = wsomabaseinsspatronal + wbaseinss;
                wsomapatronal = wsomapatronal + BDINSSPATRONAL;
                wvaloragrupado = CAST(((wsomabaseinsspatronal * wpercinss / 100) - 0.005) AS NUMERIC(18, 2));
                while (wvaloragrupado > wsomapatronal) do
                  begin
                    BDINSSPATRONAL = BDINSSPATRONAL + 0.01;
                    wsomapatronal = wsomapatronal + 0.01;
                  end
                BDENCREMUNERACAO = BDENCREMUNERACAO + BDINSSPATRONAL;
              END

           -- Terc
           BDTERC = 0;
           IF (BDSALARIOBRUTO <> 0 AND wpercfpas IS NOT NULL AND wpercfpas > 0 and wcontrcol = 2 and wbaseinss <> 0) THEN
              BEGIN
                BDTERC = CAST(((wbaseinss * wpercfpas / 100) - 0.005) AS NUMERIC(18, 2));
                wsomabaseinssterceiros = wsomabaseinssterceiros + wbaseinss;
                wsomaterceiros = wsomaterceiros + BDTERC;
                wvaloragrupado = CAST(((wsomabaseinssterceiros * wpercfpas / 100) - 0.005) AS NUMERIC(18, 2));
                while (wvaloragrupado > wsomaterceiros) do
                  begin
                    BDTERC = BDTERC + 0.01;
                    wsomaterceiros = wsomaterceiros + 0.01;
                  end
                BDENCREMUNERACAO = BDENCREMUNERACAO + BDTERC;
              END

           -- RAT
           BDRAT = 0;
           IF ((BDSALARIOBRUTO <> 0) AND (wpercrat IS NOT NULL) AND (wpercrat > 0) and (wcontrcol = 2) and (wbaseinss <> 0)) THEN
              BEGIN
                BDRAT = CAST(((wbaseinss * wpercrat / 100) - 0.005) AS NUMERIC(18, 2));
                wsomabaseinssrat = wsomabaseinssrat + wbaseinss;
                wsomarat = wsomarat + BDRAT;
                wvaloragrupado = CAST(((wsomabaseinssrat * wpercrat / 100) - 0.005) AS NUMERIC(18, 2));
                while (wvaloragrupado > wsomarat) do
                  begin
                    BDRAT = BDRAT + 0.01;
                    wsomarat = wsomarat + 0.01;
                  end
                BDENCREMUNERACAO = BDENCREMUNERACAO + BDRAT;
              END

           BDPIS = 0;
           IF (((BDSALARIOBRUTO <> 0) or (wClaver13 = 1)) and (wbasepisatu <> 0) and (wpercpis > 0 )) THEN
              BEGIN
                 bdpis = CAST(((wbasepisatu * wpercpis / 100) - 0.005) AS NUMERIC(18,2));
                 wsomabasepis = ROUND(wsomabasepis + wbasepisatu);
                 wsomapis = wsomapis + bdpis;
                 wvaloragrupado = CAST(((wsomabasepis * wpercpis / 100) - 0.005) AS NUMERIC(18, 2));
                 while (wvaloragrupado > wsomapis) do
                   begin
                     bdpis = bdpis + 0.01;
                     wsomapis = wsomapis + 0.01;
                   end
              END

           BDRATAPO = 0;
           BDPROV13 = 0;
           BDENCPROV13 = 0;
           BDPROVFER = 0;
           BDENCPROVFER = 0;
           BDFGTS = 0;

           IF (wcontrcol in (2,3)) THEN
              BEGIN
                wpercinss = 0;
                    SELECT r.bdrefrescisao FROM VRH_EMP_TRESCISAO  r
                    where BDCODEMP = :wcodemp and BDCODCOL = :wcodcol and bdrefrescisao <= :wref into  :bdrefrescisao;

                -- FGTS
                     WGRRFPRES = -1;
                     SELECT MOTRESC.BDGRRFPRES
                     FROM VRH_EMP_TRESCISAO RESC LEFT JOIN VRH_BASE_TPREPRESC MOTRESC ON (RESC.BDCODPRES = MOTRESC.BDCODPRES)
                     WHERE RESC.BDCODEMP = :wfilialatu AND RESC.BDCODCOL = :wcolatu AND RESC.BDREFRESCISAO = :bdrefrescisao
                     INTO :WGRRFPRES;

                     IF (WGRRFPRES <= 0) THEN
                       BEGIN
                         BDFGTS = wfgtsatu;
                     BDENCREMUNERACAO = BDENCREMUNERACAO + BDFGTS;
                   END
                     ELSE
                       BDFGTS = 0;

                -- RAT APO
                IF (BDSALARIOBRUTO <> 0 AND wpercinss IS NOT NULL AND wpercinss > 0) THEN
                   BEGIN
                     BDRATAPO = CAST(((BDSALARIOBRUTO * wpercinss / 100) - 0.005) AS NUMERIC(18, 2));
                     BDENCREMUNERACAO = BDENCREMUNERACAO + BDRATAPO;
                   END
     
                -- Provisão 13º
                wsqlaux = 'select SUM(BDVLR13SALP13) BDVALPROV13, SUM(BDFGTSP13 + BDINSSP13 + BDTERCFPASP13 + BDCNAERATP13 + BDRATAPOP13 + BDPISP13) BDENCPROV13 from VRHF_EMP_TPROVISAO13 where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and BDREFP13 = '||wrefatu||' and BDLINHAP13 in (6,7,8,9,19) ';

                EXECUTE STATEMENT wsqlaux INTO :BDPROV13, :BDENCPROV13;
                IF (BDPROV13 IS NULL) THEN
                   BDPROV13 = 0;
                IF (BDENCPROV13 IS NULL) THEN
                   BDENCPROV13 = 0;

                -- Provisão Fér
                wsqlaux = 'select SUM(BDFERIASPFER + BDUMTERCOPFER) BDVALPROVFER, SUM(BDFGTSPFER + BDINSSPFER + BDTERCFPASPFER + BDCNAERATPFER + BDRATAPOPFER + BDPISPFER) BDENCPROVFER from VRHF_EMP_TPROVISAOFERIAS where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||' and BDREFPFER = '||wrefatu||' and BDLINHAPFER in (4,5,6,7,14) ';

                EXECUTE STATEMENT wsqlaux INTO :BDPROVFER, :BDENCPROVFER;
                IF (BDPROVFER IS NULL) THEN
                   BDPROVFER = 0;
                IF (BDENCPROVFER IS NULL) THEN
                   BDENCPROVFER = 0;
              END

           IF (wtpccatu > 0 AND wcentroatu > 0) THEN
              BEGIN
                wsqlaux = 'select first 1 case when TRIM(COALESCE(CCRH.BDNOMETOM, '''')) <> '''' then CCRH.BDNOMETOM else CC.BDNOMCTA end BDNOMCC from CENTROS_TPCC CC left outer join VRH_BASE_TCUSTOM CCRH on (CCRH.BDCODCENTRO = CC.BDCODCENTRO and CCRH.BDCODTPCC = CC.BDCODTPCC) where CC.BDCODCENTRO = '||wcentroatu||' and CC.BDCODTPCC = '||wtpccatu;
                EXECUTE STATEMENT wsqlaux INTO :BDNOMTPCC;
              END
           ELSE
              BDNOMTPCC = wnomemp;

           BDCODSIT = 0;
           BDDESCSIT = '';
           if (BDSALARIOBRUTO + BDENCREMUNERACAO + BDGRATIFICACOES + BDPROV13 + BDENCPROV13 + BDPROVFER + BDENCPROVFER <= 0) then
              begin
                wsqlaux = 'select first 1 ST.BDCODSIT, PST.BDDESCSIT from VRH_EMP_TSITCOL ST '|| 'join VRH_BASE_TPREPSIT PST on (PST.BDCODSIT = ST.BDCODSIT) where ST.BDCODEMP = '||wfilialatu||' and ST.BDCODCOL = '||wcolatu|| ' and SUBSTRING(CAST(ST.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(ST.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                          ' and ((ST.BDDATAFIMSIT is null) or (SUBSTRING(CAST(ST.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(ST.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';
                execute statement wsqlaux into :BDCODSIT, :BDDESCSIT;
              end

           BDQTDHORAS = null;
           IF (coalesce(wtipocolatu,0) <> 2) THEN
              SELECT FIRST 1 BDHORASMENSAISCOL FROM VRHF_EMP_TCOL_CALC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu AND BDREFCOL <= :wrefatu ORDER BY BDREFCOL DESC INTO :BDQTDHORAS;

           BDTOTAL = BDSALARIOBRUTO + BDENCREMUNERACAO + BDGRATIFICACOES + BDPROV13 + BDENCPROV13 + BDPROVFER + BDENCPROVFER;

           select first 1 ULTDIA from ULTIMO_DIA_MES(CAST(SUBSTRING(:wref FROM 5 FOR 2) AS SMALLINT), CAST(SUBSTRING(:wref FROM 1 FOR 4) AS INTEGER)) into :wdtaux;
           wdtaux = SUBSTRING(:wref FROM 5 FOR 2)||'-'||lpad(wdtaux,  2, '0')||'-'||SUBSTRING(:wref FROM 1 FOR 4);
           BDDESCCARGO = null;
           IF (coalesce(wtipocolatu,0) <> 2) THEN
              begin
               SELECT SUBSTRING(TFUC.BDDESCTFUC from 1 for 40) FROM (select first 1 BDCODPLAFUC, BDCODTFUC from VRH_EMP_TCOL_VINCDIA where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDDATACOL <= CAST(:wdtaux AS DATE) order by BDDATACOL DESC) VINC
            LEFT OUTER JOIN VRH_FUNCOES_TFUC TFUC on (TFUC.BDCODPLAFUC = VINC.BDCODPLAFUC and TFUC.BDCODTFUC = VINC.BDCODTFUC)
           into :BDDESCCARGO;
              end
           else
              select first 1 cbo.bddesccbo from VRH_BASE_TTERC_VINC vinc left outer join VRH_BASE_TCBO cbo on (vinc.BDCODCBO = cbo.BDCODCBO) where BDCODTER = :wcolatu and BDREFTERC <= :wref order by BDREFTERC DESC into :BDDESCCARGO;

           if (coalesce(bdvalrescisao, 0) > 0) then
             bdsalliquido = 0;

           if (w13 > 0) then
             begin
               select BDVALC13 from VRHF_EMP_TC13SAL where BDCODEMP = :bdcodemp and BDCODCOL = :bdcodcol and BDREFC13 = :prrefini INTO :wValorC13;
               if (coalesce(wValorC13, 0) > 0) then
                 bdval13salario = wValorC13;
             end

           SUSPEND;
         END
    END
END^


/* Restore proc. body: SP_VRH_RELATORIOPLANOSAUDE */
create or alter procedure SP_VRH_RELATORIOPLANOSAUDE (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRCODTIPOCONV integer = 0,
    PRFILIAIS smallint = 0,
    PREMPFILIAL varchar(15000) = null,
    PRSITPLANO smallint = 0)
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDREF integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDCODPLACONVSAU integer,
    BDCODCONVENIO integer,
    BDCODOPERADORA integer,
    BDREFINI integer,
    BDREFFIM integer,
    BDCODTIPOCONV integer,
    BDDESCTIPOCONV varchar(200),
    BDDESCOPERADORA varchar(80),
    BDPARENTESCO varchar(500),
    BDSITUACAO varchar(30))
as
declare variable WREFATUAL integer;
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(15000);
BEGIN
  /* prSitPlano: 0 = Todos; 1 = Ativos; 2 = Inativos */

  wSql = 'select COL.BDCODEMP,';

  IF (prFiliais = 1) THEN
     wSql = wSql||'EMP.BDCODMATRIZ ';
  ELSE
     wSql = wSql||'COL.BDCODEMP BDCODMATRIZ ';

  wSql = wSql||', COL.BDCODCOL, COL.BDCODDPN, COL.BDNOMCOL, COL.BDNOMCOLUPPER, COL.BDCODPLACONVSAU, COL.BDCODCONVENIO, COL.BDCODOPERADORA, COL.BDREFINI, COL.BDREFFIM, '||
         'OPSAU.BDCODTIPOCONV, TCONV.BDDESCTIPOCONV, SAUDE.BDDESCRICAO, COL.BDPARENTESCO ';

  wSql = wSql||
          'from ('||
            'select COL.BDCODEMP, COL.BDCODCOL, 0 BDCODDPN, COLCAD.BDNOMCOL, COLCAD.BDNOMCOLUPPER, CONV_COL.BDCODPLACONVSAU, CONV_COL.BDCODCONVENIO, CONV_COL.BDCODOPERADORA, '||
                    'CONV_COL.BDREFINI, CONV_COL.BDREFFIM, CAST(null as VARCHAR(500)) BDPARENTESCO '||
            'from VRH_EMP_TCOLCON COL '||
            'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COL.BDCODEMP and COLCAD.BDCODCOL = COL.BDCODCOL) '||
            'join VRH_EMP_VINC_COL_CONV CONV_COL on (CONV_COL.BDCODEMP = COL.BDCODEMP and CONV_COL.BDCODCOL = COL.BDCODCOL) '||
            'where CONV_COL.BDREFINI <= '||prreffim||' and ';

            IF (prsitplano = 2) THEN
               wsql = wsql||'COALESCE(CONV_COL.BDREFFIM, 0) > 0 and COALESCE(CONV_COL.BDREFFIM, 0) >= '||prrefini||' ';
            ELSE
               wsql = wsql||'((COALESCE(CONV_COL.BDREFFIM, 0) = 0) or (COALESCE(CONV_COL.BDREFFIM, 0) >= '||prrefini||')) ';

            IF (prEmp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 IF (prFiliais = 0) THEN
                    BEGIN
                      wSql = wSql||' and '||premp;

                      IF (prCol IS NOT NULL AND prcol <> '') THEN
                         wSql = wSql||' and '||prcol;
                    END
               END

  wSql = wSql||
            ' union all '||
            'select COL.BDCODEMP, COL.BDCODCOL, COL.BDCODDPN, COL.BDNOMEDPN BDNOMCOL, UPPER(COL.BDNOMEDPN) BDNOMCOLUPPER, CONV_DEP.BDCODPLACONVSAU, CONV_DEP.BDCODCONVENIO, CONV_DEP.BDCODOPERADORA, '||
                    'CONV_DEP.BDREFINI, CONV_DEP.BDREFFIM, GRAUPARENTE.BDDESCTIPODEP '||
            'from VW_VRH_EMP_TDEP_REF COL '||
            'join VRH_EMP_VINC_DEP_CONV CONV_DEP on (CONV_DEP.BDCODEMP = COL.BDCODEMP and CONV_DEP.BDCODCOL = COL.BDCODCOL and CONV_DEP.BDCODDPN = COL.BDCODDPN) '||
            'left outer join VRH_TTIPO_DEP_ESOCIAL GRAUPARENTE on (GRAUPARENTE.BDCODTIPODEP = COL.BDPARENESCODPN) '||
            'where CONV_DEP.BDREFINI <= '||prreffim||' and upper(coalesce(COL.BDCONVMEDDPN, ''FALSE'')) = ''TRUE'' and ';

            IF (prsitplano = 2) THEN
               wsql = wsql||'COALESCE(CONV_DEP.BDREFFIM, 0) > 0 and COALESCE(CONV_DEP.BDREFFIM, 0) >= '||prrefini||' ';
            ELSE
               wsql = wsql||'((COALESCE(CONV_DEP.BDREFFIM, 0) = 0) or (COALESCE(CONV_DEP.BDREFFIM, 0) >= '||prrefini||')) ';

            IF (prEmp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 IF (prFiliais = 0) THEN
                    BEGIN
                      wSql = wSql||' and '||premp;

                      IF (prCol IS NOT NULL AND prCol <> '') THEN
                         wSql = wSql||' and '||prcol;
                    END
               END

  wSql = wSql||
          ') COL '||
          'join VRH_BASE_CONVENIO_OPERADORAS OPSAU on (OPSAU.BDCODCONVENIO = COL.BDCODCONVENIO and OPSAU.BDCODOPERADORA = COL.BDCODOPERADORA and OPSAU.BDCODPLACONVSAU = COL.BDCODPLACONVSAU) '||
          'join VRHM_BASE_TTIPOCONVENIO TCONV on (TCONV.BDCODTIPOCONV = OPSAU.BDCODTIPOCONV) '||
          'join VRH_BASE_TCONVSAUDE SAUDE on (SAUDE.BDCODCONVENIO = COL.BDCODOPERADORA) ';

  wWhere = '';

  IF (prFiliais = 1) THEN
     BEGIN
       wSql = wSql||'join TEMPRESAS EMP on (EMP.BDCODEMP = COL.BDCODEMP) ';

       IF (prEmp IS NOT NULL AND premp <> '' AND prempfilial IS NOT NULL AND prempfilial <> '') THEN
          wWhere = wWhere||' (('||premp||') or ('||prempfilial||')) ';
     END

  IF (prCodTipoConv > 0) THEN
     BEGIN
       IF (wWhere <> '') THEN
          wWhere = wWhere||' and ';

       wWhere = wWhere||' OPSAU.BDCODTIPOCONV = '||prcodtipoconv||' ';
     END

  IF (wWhere <> '') THEN
     wSql = wSql||' where '||wWhere;

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP, :BDCODMATRIZ, :BDCODCOL, :BDCODDPN, :BDNOMCOL, :BDNOMCOLUPPER, :BDCODPLACONVSAU, :BDCODCONVENIO, :BDCODOPERADORA, :BDREFINI, :BDREFFIM,
    :BDCODTIPOCONV, :BDDESCTIPOCONV, :BDDESCOPERADORA, :BDPARENTESCO DO
    BEGIN
      wrefatual = prrefini;

      WHILE (wrefatual <= prreffim) DO
        BEGIN
          BDREF = wrefatual;

          IF (bdrefini <= wrefatual) THEN
             BEGIN
               IF (prsitplano = 1) THEN
                  BEGIN
                    IF ((COALESCE(bdreffim,0) = 0) OR (COALESCE(bdreffim,0) >= wrefatual)) THEN
                       BEGIN
                         BDSITUACAO = 'Ativo';
                         SUSPEND;
                       END
                  END
               ELSE
               IF (prsitplano = 2) THEN
                  BEGIN
                    IF (COALESCE(bdreffim,0) > 0 AND COALESCE(bdreffim,0) < wrefatual) THEN
                       BEGIN
                         BDSITUACAO = 'Inativo';
                         SUSPEND;
                       END
                  END
               ELSE
                  BEGIN
                    IF ((COALESCE(bdreffim,0) = 0) OR (COALESCE(bdreffim,0) >= wrefatual)) THEN
                       BDSITUACAO = 'Ativo';
                    ELSE
                       BDSITUACAO = 'Inativo';

                    SUSPEND;
                  END

             END


          IF (SUBSTRING(wrefatual FROM 5 FOR 2) = '12' ) THEN
             wrefatual = CAST((CAST((CAST(SUBSTRING(wrefatual FROM 1 FOR 4) AS INTEGER) + 1) AS VARCHAR(4))||'01') AS INTEGER);
          ELSE
             BEGIN
               IF (CAST(SUBSTRING(wrefatual FROM 5 FOR 2) AS INTEGER) < 9) THEN
                  wrefatual = CAST((SUBSTRING(wrefatual FROM 1 FOR 4)||'0'||CAST((CAST(SUBSTRING(wrefatual FROM 5 FOR 2) AS INTEGER) + 1) AS VARCHAR(1))) AS INTEGER);
               ELSE
                  wrefatual = CAST((SUBSTRING(wrefatual FROM 1 FOR 4)||CAST((CAST(SUBSTRING(wrefatual FROM 5 FOR 2) AS INTEGER) + 1) AS VARCHAR(2))) AS INTEGER);
             END
    
        END
    END
END^

/* Restore proc. body: SP_COLABORADOR_SEFIP */
CREATE OR ALTER PROCEDURE SP_COLABORADOR_SEFIP RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDOCORRENCIA VARCHAR(1),
BDPIS VARCHAR(20),
BDADM VARCHAR(10),
BDCATEGORIA VARCHAR(10),
BDNOME VARCHAR(70),
BDMATRICULA VARCHAR(20),
BDCTPS VARCHAR(10),
BDSERIECT DM_SERIECTPS,
BDDATAOPCAO VARCHAR(10),
BDDATANASC VARCHAR(10),
BDCBO VARCHAR(10),
BDCODUF INTEGER,
BDCTAFGTSCOL VARCHAR(20),
BDDSERIECT VARCHAR(1),
BDCPF VARCHAR(14))
 AS
DECLARE VARIABLE WCOL INTEGER;
DECLARE VARIABLE WEMP INTEGER;
DECLARE VARIABLE WSQL VARCHAR(3600);
BEGIN
  /* Procedure Text */
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wemp;
  IF (wemp IS NULL) THEN
     wemp = 0;

  SELECT rdb$get_context('USER_TRANSACTION', 'W_COLSEFIP') FROM rdb$database INTO wcol;
  IF (wcol IS NULL) THEN
    wCol = 0;

  wsql = 'select col_cad.bdcodemp,col_cad.bdcodcol,
                 cast(coalesce(COLCON_FGTSGPS.bdocorrenciacol,0) as varchar(1)) BDOCORRENCIA,
                 DOCREF.bdpiscol,
                 (select bdddmmaaaa from ddmmaaaa(col_cad.bddataadmcol)) bdadm,
                 cast(COLCON_FGTSGPS.bdcategoriacol as varchar(10)) bdcategoria,
                 colcad.bdnomcol,
                 cast(col_cad.bdcodcol as varchar(10)) bdmatricula,
                 SUBSTRING(cast(DOCREF.bdctpscol as DM_BDCTPS) from 1 for 10) bdctps,
                 SUBSTRING(cast(DOCREF.bdseriectpscol as DM_SERIECTPS) from 1 for 10) bdseriect,
                 (select bdddmmaaaa from ddmmaaaa(COLCON_FGTSGPS.bddataopcaofgtscol)) bdopcao,
                 (select bdddmmaaaa from ddmmaaaa(col_cad.bddatanasccol)) bdnasc,
                 cast(cbo.bdcodcbo as varchar(10)) bdcbo,
                 DOCREF.BDCODUF,
                 COLCON_FGTSGPS.bdctafgtscol,
                 DOCREF.bddseriectpscol bddseriect,
                 col_cad.BDCPFCOL
          from VRH_EMP_TCOLCON col_cad
          left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS_ATU COLCON_FGTSGPS on (COLCON_FGTSGPS.BDCODEMP = COL_cad.BDCODEMP and COLCON_FGTSGPS.BDCODCOL = COL_cad.BDCODCOL)
          left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = col_cad.BDCODEMP and DOCREF.BDCODCOL = col_cad.BDCODCOL)
          left outer join VRH_EMP_TCOL_DOC  coldoc on (coldoc.BDCODEMP = col_cad.BDCODEMP and coldoc.BDCODCOL = col_cad.BDCODCOL)
          left outer join VW_TCOLCON_VINCDIA COL_DIAVINC on (COL_DIAVINC.BDCODEMP = col_cad.BDCODEMP and COL_DIAVINC.BDCODCOL = col_cad.BDCODCOL)
          left outer join vrh_funcoes_tfuc tfuc on (tfuc.bdCODPLAFUC = COL_DIAVINC.bdcodplafuc and tfuc.bdcodtfuc = COL_DIAVINC.bdcodtfuc)
          left outer join vrh_base_tcbo CBO on (CBO.bdcodcbo = tfuc.bdcodcbo)
          left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COL_CAD.BDCODEMP and COLCAD.BDCODCOL = COL_CAD.BDCODCOL)';

  IF (wemp > 0) THEN
     BEGIN
       wsql = wsql||' where col.bdcodemp = '||wemp;

       IF (wcol > 0) THEN
          wsql = wsql||' and col.bdcodcol = '||wcol;
     END

  FOR EXECUTE STATEMENT wsql INTO
      bdcodemp,
      bdcodcol,
      BDOCORRENCIA,
      bdpis ,
      bdadm ,
      bdcategoria ,
      bdnome ,
      bdmatricula,
      bdctps,
      bdseriect,
      bddataopcao,
      bddatanasc,
      bdcbo,
      bdcoduf,
      bdctafgtscol,
      bddseriect,
      bdcpf DO
  BEGIN
      IF (BDOCORRENCIA IS NULL) THEN
         BDOCORRENCIA = '';
    
      IF (bdpis IS NULL) THEN
         bdpis  = '';
    
      IF (bdadm IS NULL) THEN
         bdadm = '';
    
      IF (bdcategoria IS NULL) THEN
         bdcategoria = '';
    
      IF (bdnome IS NULL) THEN
         bdnome = '';
    
      IF (bdmatricula IS NULL) THEN
         bdmatricula = '';
    
      IF (bdctps IS NULL) THEN
          bdctps = '';
    
      IF (bdseriect IS NULL) THEN
         bdseriect = '';
    
      IF (bddataopcao IS NULL) THEN
         bddataopcao = '';
    
      IF (bddatanasc IS NULL) THEN
         bddatanasc = '';
    
      IF (bdcbo IS NULL) THEN
         bdcbo = '';
    
      SUSPEND;
  END
END
^

/* Restore proc. body: SP_COMP_ACUMULADO_GPS */
create or alter procedure SP_COMP_ACUMULADO_GPS (
    PRCODEMP integer,
    PRAGRUPADO integer,
    PRCODTPCC integer,
    PRANOMES integer,
    PRANOMESPAG integer,
    PRTIPOFOLHA integer,
    PRCHAVEDARF integer = 0,
    PRCODFC integer = 0)
returns (
    BDCOMPENSACAO numeric(15,6),
    BDINICOMP integer,
    BDFIMCOMP integer,
    BDACUMULADO numeric(15,6),
    BDACUMULADOTERC numeric(15,6))
as
declare variable WVALACUTER numeric(15,6);
declare variable WVALACU numeric(15,6);
declare variable WTOTACUTER numeric(15,6);
declare variable WTOTACU numeric(15,6);
declare variable WQUOTA integer;
declare variable WCODPERIODO integer;
declare variable WREFUTIMAL integer;
declare variable WORDEM integer;
declare variable WAUXCODCENTO varchar(3000);
declare variable WSQL varchar(3000);
declare variable WSQLMOVICOL varchar(3000);
declare variable WCOMPENSACAO numeric(15,6);
declare variable WINICIOCOMPENSACAO integer;
declare variable WFIMCOMPENSACAO integer;
declare variable WBUSCACOMP integer;
declare variable WACUMULADO numeric(15,6);
declare variable WACUMULADOTERC numeric(15,6);
declare variable WCODIMP integer;
declare variable WAUX1 numeric(15,6);
declare variable WAUX2 integer;
declare variable WAUX3 integer;
declare variable WCHAVEDARF integer;
BEGIN
  /* Procedure Text */
   IF (pranomespag IS NULL) THEN
      pranomespag = pranomes;

   wsql = 'select colcon.bdcodimp from vw_tempresaimpostoref colcon where colcon.bddocarrecadacao = 12 and colcon.bdcodemp = '||prcodemp;
   wcompensacao = 0;
   winiciocompensacao = 999999;
   wfimcompensacao = 0;
   wbuscacomp = 0;
   wacumulado = 0;
   wacumuladoterc = 0;

   IF (wtotacu IS NULL) THEN
      wtotacu = 0;

   IF (wtotacuter IS NULL) THEN
      wtotacuter = 0;

   EXECUTE PROCEDURE sp_seta_competencia(pranomespag);
   FOR EXECUTE STATEMENT wsql INTO : wcodimp DO
     BEGIN
       waux1 = NULL;
       IF (prtipofolha IN (0,1,2)) THEN
          BEGIN
            IF (prcodtpcc IS NULL) THEN
               wsqlmovicol = 'null';
            ELSE
               wsqlmovicol = ''||prcodtpcc;
            wsqlmovicol = 'select sum(comp.BDVALOR),min(comp.BDMESINI),max(comp.BDMESFIM) from vrhf_sp_tcompensacaogps('||wcodimp||','||prcodemp||','||prtipofolha||','||pragrupado||','||wsqlmovicol||','||wbuscacomp||','||pranomespag||','||prchavedarf||') comp';
            EXECUTE STATEMENT wsqlmovicol INTO waux1,waux2,waux3;
          END

       wbuscacomp = 1;
       IF (waux1 IS NOT NULL) THEN
          BEGIN
            IF (waux1 IS NULL) THEN
               waux1 = 0;
            IF (waux2 IS NULL) THEN
               waux2 = 999999;
            IF (waux3 IS NULL) THEN
               waux3 = 0;

            wcompensacao = wcompensacao + waux1;

            IF (waux2 < winiciocompensacao) THEN
               winiciocompensacao = waux2;

            IF (waux3 > wfimcompensacao) THEN
               wfimcompensacao = waux3;
          END

       /*Inicio acumulado*/
       /*****************************************************************************/
       wauxcodcento = '';
       IF (pragrupado = 3) THEN
          BEGIN
            IF (prcodtpcc IS NULL) THEN
               wauxcodcento = 'and x.bdcodtpcc is null';
            ELSE
               wauxcodcento = 'and x.bdcodtpcc = '||prcodtpcc;
          END

       wsqlmovicol = 'select first 1 x.bdchavedarf,x.bdrefpag,x.bdreferencia,x.bdordem from tdarfpadrao x '||
                     'where x.bdreferencia = '||pranomes||
                     ' and x.bdcodemp = '||prcodemp||
                     ' and x.bdcodimp = '||wcodimp||
                     ' and x.bdrefpag = '||pranomespag||
                     wauxcodcento||
                     ' and x.BDTIPOIMPOSTO = '||prtipofolha;

       wordem = NULL;
       wchavedarf = null;
       EXECUTE STATEMENT wsqlmovicol INTO :wchavedarf, :wrefutimal, :waux2, :wordem;

       -- Não existe a guia da competência atual
       if (coalesce(wchavedarf, 0) = 0) then
          begin
            wchavedarf = 0;
            wrefutimal = pranomespag;
            waux2      = pranomes;
            wordem     = -1;
          end

       wsqlmovicol = 'select y.bdvalcampo6,y.bdvalcampo9 from VRHF_SP_HIST_ACUMU_GPS2('||''''||'x.bdcodemp = '||prcodemp||' and x.bdcodimp = '||wcodimp||' and ';

       -- Não deve levar complemento de 13º acumulado para SEFIP. Essa diferença já é calculada quando são levados os valores complemento de 13º que o layout pede.
       wsqlmovicol = wsqlmovicol||' x.bdtipoimposto <> 3 and ';

       if (prtipofolha = 1 and prcodfc = 1) then
          wsqlmovicol = wsqlmovicol||' coalesce(x.bdtipoimposto, 0) <> 1 and ';

            wsqlmovicol = wsqlmovicol||
                     'CAST(X.BDREFPAG AS VARCHAR(6))||''''.''''||CAST(X.BDREFERENCIA AS VARCHAR(6))||''''.''''||lpad(CAST(X.BDORDEM AS VARCHAR(10)), 10, ''''0'''') <= '''''||
                     wrefutimal||'.'||waux2||'.';

       if (coalesce(wordem, 0) < 0) then
          wsqlmovicol = wsqlmovicol||'9000000000''''''';
       else
          wsqlmovicol = wsqlmovicol||lpad(wordem, 10, '0')||'''''';

       if (coalesce(wchavedarf, 0) <> 0) then
          wsqlmovicol = wsqlmovicol||' and x.bdchavedarf <> '||wchavedarf||'''';

       wsqlmovicol = wsqlmovicol||') y';

            FOR EXECUTE STATEMENT wsqlmovicol INTO
              : wvalacu,
              : wvalacuter
            DO
              BEGIN
                IF (wvalacu IS NOT NULL) THEN
                   wtotacu = wtotacu + wvalacu;

                IF (wvalacuter IS NOT NULL) THEN
                   wtotacuter = wtotacuter + wvalacuter;
              END

       wacumulado = wtotacu;
       wacumuladoterc = wvalacuter;
       /*****************************************************************************/
       /*Fim acumulado*/
     END

   IF ((wcompensacao = 0) OR (wcompensacao IS NULL)) THEN
      BEGIN
        winiciocompensacao = 0;
        wfimcompensacao = 0;
      END

  bdacumulado = wacumulado;
  bdacumuladoterc = wacumuladoterc;
  bdcompensacao = wcompensacao;
  bdinicomp = winiciocompensacao;
  bdfimcomp = wfimcompensacao;
  SUSPEND;
END^

/* Restore proc. body: SP_COMPOSICAO_RECURSOS_HUMANOS */
CREATE OR ALTER procedure SP_COMPOSICAO_RECURSOS_HUMANOS (
    PREMPRESAS varchar(30000),
    PRANO integer)
returns (
    BDCODEMP integer,
    BDANOATUAL integer,
    BDANOANTERIOR integer,
    BDTOTCOLFIMANO integer,
    BDTOTADMANO integer,
    BDTOTDEMANO integer,
    BDTOTCOLMASC integer,
    BDTOTCOLFEM integer,
    BDTOTPRESSERVPJ integer,
    BDTOTPRESSERVPF integer,
    BDTOTCOLIDADE18A35 integer,
    BDTOTCOLIDADE36A60 integer,
    BDTOTCOLIDADESUP60 integer,
    BDTOTCOLFIMANO_ANOANT integer,
    BDTOTADMANO_ANOANT integer,
    BDTOTDEMANO_ANOANT integer,
    BDTOTCOLMASC_ANOANT integer,
    BDTOTCOLFEM_ANOANT integer,
    BDTOTPRESSERVPJ_ANOANT integer,
    BDTOTPRESSERVPF_ANOANT integer,
    BDTOTCOLIDADE18A35_ANOANT integer,
    BDTOTCOLIDADE36A60_ANOANT integer,
    BDTOTCOLIDADESUP60_ANOANT integer)
as
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(500);
declare variable WWHEREAUX varchar(100);
declare variable WNOMCAMPOAUX varchar(10);
declare variable WANOATUAL varchar(6);
declare variable WI integer;
BEGIN
  bdtotcolfimano = 0;
  bdtotadmano = 0;
  bdtotdemano = 0;
  bdtotcolmasc = 0;
  bdtotcolfem = 0;
  bdtotpresservpj = 0;
  bdtotpresservpf = 0;
  bdtotcolidade18a35 = 0;
  bdtotcolidade36a60 = 0;
  bdtotcolidadesup60 = 0;
  bdtotcolfimano_anoant = 0;
  bdtotadmano_anoant = 0;
  bdtotdemano_anoant = 0;
  bdtotcolmasc_anoant = 0;
  bdtotcolfem_anoant = 0;
  bdtotpresservpj_anoant = 0;
  bdtotpresservpf_anoant = 0;
  bdtotcolidade18a35_anoant = 0;
  bdtotcolidade36a60_anoant = 0;
  bdtotcolidadesup60_anoant = 0;

  wanoatual = CAST(prano AS VARCHAR(6));
  wanoatual = SUBSTRING(wanoatual FROM 1 FOR 4);
  prano = CAST(wanoatual AS INTEGER);
  bdanoatual = prano;
  bdanoanterior = bdanoatual - 1;

  prempresas = COALESCE(prempresas, '');

  IF (prempresas <> '') THEN
    prempresas = ' where '||prempresas;

  wsql = 'select tab.BDCODEMP, ';

  wnomcampoaux = ', ';
  wi = 1;
  WHILE (wi <= 2) DO
  BEGIN
    wwhere = ' left outer join VRH_EMP_TRESCISAO R on (R.BDCODEMP = C.BDCODEMP) and (R.BDCODCOL = C.BDCODCOL) where (C.BDCODEMP = tab.BDCODEMP) and (C.BDDATAADMCOL <= ''12/31/'||prano||
        ''') and ((R.BDDATARESCISAO is null or R.BDDATARESCISAO > ''12/31/'||prano||'''))';
    wwhereaux = '(select BDANOS from SP_CALC_IDADE(C.BDDATANASCCOL, ''12/31/'||prano||'''))';

    IF (wi = 2) THEN
      wnomcampoaux = '_ANOANT, ';

    wsql = wsql ||' (select count(*) BDTOTCOLFIMANO from VRH_EMP_TCOLCON C '||wwhere||') BDTOTCOLFIMANO'||wnomcampoaux;
    wsql = wsql ||' (select count(*) BDTOTADMANO from VRH_EMP_TCOLCON C where (C.BDCODEMP = tab.BDCODEMP) and (C.BDDATAADMCOL between ''01/01/'||prano||''' and ''12/31/'||prano||''')) BDTOTADMANO'||wnomcampoaux;
    wsql = wsql ||' (select count(*) BDTOTDEMANO from VRH_EMP_TRESCISAO R where (R.BDCODEMP = tab.BDCODEMP) and (R.BDDATARESCISAO between ''01/01/'||prano||''' and ''12/31/'||prano||''')) BDTOTDEMANO'||wnomcampoaux;
    wsql = wsql ||' (select count(*) BDTOTCOLMASC from VW_VRH_EMP_TCOLCON_CAD COL join VRH_EMP_TCOLCON C on C.BDCODEMP = COL.BDCODEMP and C.BDCODCOL = COL.BDCODCOL '||wwhere||' and (COL.BDSEXOCOL = 1)) BDTOTCOLMASC'||wnomcampoaux;
    wsql = wsql ||' (select count(*) BDTOTCOLFEM from VW_VRH_EMP_TCOLCON_CAD COL join VRH_EMP_TCOLCON C on C.BDCODEMP = COL.BDCODEMP and C.BDCODCOL = COL.BDCODCOL '||wwhere||' and (COL.BDSEXOCOL <> 1)) BDTOTCOLFEM'||wnomcampoaux;
    wsql = wsql ||' (select sum(TBTOTSERVPJ'||REPLACE(wnomcampoaux,', ','')||'.BDTOTPRESSERVPJ) from (select 1 BDTOTPRESSERVPJ from VEF_EMP_TMOVSER M where (M.BDCODEMP = tab.BDCODEMP) and (M.BDDATAEMISSAO <= ''12/31/'||prano||''') group by M.BDCODEMP, M.BDCODTER) TBTOTSERVPJ'||REPLACE(wnomcampoaux,', ','')||' ) BDTOTPRESSERVPJ'||wnomcampoaux;
    wsql = wsql ||' (select sum(TBTOTSERVPF'||REPLACE(wnomcampoaux,', ','')||'.BDTOTPRESSERVPF) from (select 1 BDTOTPRESSERVPF from VRHF_BASE_CALC_TERC T where (T.BDCODEMP = tab.BDCODEMP) and (T.BDDATASERV <= ''12/31/'||prano||''') group by T.BDCODEMP, T.BDCODTER) TBTOTSERVPF'||REPLACE(wnomcampoaux,', ','')||' ) BDTOTPRESSERVPF'||wnomcampoaux;
    wsql = wsql ||' (select count(*) BDTOTCOLIDADE18A35 from VRH_EMP_TCOLCON C '||wwhere||' and '||wwhereaux||' >= 18 and '||wwhereaux||' <= 35) BDTOTCOLIDADE18A35'||wnomcampoaux;
    wsql = wsql ||' (select count(*) BDTOTCOLIDADE36A60 from VRH_EMP_TCOLCON C '||wwhere||' and '||wwhereaux||' >= 36 and '||wwhereaux||' <= 60) BDTOTCOLIDADE36A60'||wnomcampoaux;
    
    IF (wi = 2) THEN
      wnomcampoaux = '_ANOANT ';
      
    wsql = wsql ||'(select count(*) BDTOTCOLIDADESUP60 from VRH_EMP_TCOLCON C '||wwhere||' and '||wwhereaux||' > 60) BDTOTCOLIDADESUP60'||wnomcampoaux;
    prano = bdanoanterior;
    wi = wi + wi;
  END

  wsql = wsql || ' from TEMPRESAS tab '||prempresas;

  FOR EXECUTE STATEMENT wsql
    INTO :BDCODEMP, :BDTOTCOLFIMANO, :BDTOTADMANO, :BDTOTDEMANO, :BDTOTCOLMASC, :BDTOTCOLFEM, :BDTOTPRESSERVPJ, :BDTOTPRESSERVPF, :BDTOTCOLIDADE18A35, :BDTOTCOLIDADE36A60, :BDTOTCOLIDADESUP60,
    :BDTOTCOLFIMANO_ANOANT, :BDTOTADMANO_ANOANT, :BDTOTDEMANO_ANOANT, :BDTOTCOLMASC_ANOANT, :BDTOTCOLFEM_ANOANT, :BDTOTPRESSERVPJ_ANOANT, : BDTOTPRESSERVPF_ANOANT, :BDTOTCOLIDADE18A35_ANOANT,
    :BDTOTCOLIDADE36A60_ANOANT, :BDTOTCOLIDADESUP60_ANOANT
  DO
  BEGIN
    SUSPEND;
  END
END
^

/* Restore proc. body: SP_CONS_CALC_DEP */
CREATE OR ALTER PROCEDURE SP_CONS_CALC_DEP (
    PRCODEMP INTEGER,
    PRCODBEM INTEGER,
    PRDATAINICIAL DATE,
    PRDATAFINAL DATE,
    PRTIPO INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRDETALHARTAXADEP INTEGER = 0,
    PRRELBAIPAR INTEGER = 0)
RETURNS (
    PRVALORCORRIGIDOANTERIOR NUMERIC(15,2),
    PRCORRECAOPERIODO NUMERIC(15,2),
    PRVALORCORRIGIDOATUAL NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2),
    PRDEPRECIACAOPERIODO NUMERIC(15,2),
    PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,2),
    PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2),
    PRVALORRESIDUALCONTABIL NUMERIC(15,2),
    PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,2),
    PRTOTALMESESDEPRECIACAO INTEGER,
    PRMESESDEPRECIADOS INTEGER,
    PRMESESDEPRECIAR INTEGER,
    PRTAXADEPRECIACAOANUAL NUMERIC(6,2),
    PRDATATAXADEPRECIACAO DATE,
    PRVALORBAIXA NUMERIC(15,2),
    PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,2),
    PRVALORBAIXAREAL NUMERIC(15,2),
    PRVALORMOEDA NUMERIC(15,2),
    PRDATABAIXA DATE,
    PRVALORAQUISICAOMOEDA NUMERIC(15,2),
    PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,2),
    PRVALORAQUISICAOORIGINAL NUMERIC(15,2),
    PRCTADEBITODEPRE INTEGER,
    PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,2),
    BDCODEMP INTEGER,
    BDCODBEM INTEGER,
    PRSOMARDEPRECIACAO INTEGER,
    PRCOMPENSACAOBAIXAPERANTERIOR NUMERIC(15,2),
    BDVALORRESIDUAL NUMERIC(15,2),
    PRTAXADEPRECIACAOANUAL_ANT NUMERIC(6,2),
    PRDATAINICALC DATE,
    BDVALORCAPITAL NUMERIC(15,2))
AS
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WREFFIM INTEGER;
DECLARE VARIABLE WDATAAQUISICAO DATE;
DECLARE VARIABLE WDTINI DATE;
DECLARE VARIABLE WDTFIM DATE;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WULTDIAMES INTEGER;
DECLARE VARIABLE WCORRECAOPERIODO NUMERIC(15,6);
DECLARE VARIABLE WVALORCORRIGIDOATUAL NUMERIC(15,6);
DECLARE VARIABLE WVALORCORRIGIDOANTERIOR NUMERIC(15,6);
DECLARE VARIABLE WVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6);
DECLARE VARIABLE WMESESDEPRECIADOS INTEGER;
DECLARE VARIABLE WMESESDEPRECIADOSAUX INTEGER;
DECLARE VARIABLE WVALORBAIXA NUMERIC(15,6);
DECLARE VARIABLE WVALORBAIXABEM NUMERIC(15,6);
DECLARE VARIABLE WPOSSUIBAIXA VARCHAR(5);
DECLARE VARIABLE WDEPRECIACAOPERIODO NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOPERIODOMOEDA NUMERIC(15,6);
DECLARE VARIABLE WCORRECAOMONETARIADEPRECIACAO NUMERIC(15,6);
DECLARE VARIABLE WVALORRESIDUALCONTABIL NUMERIC(15,6);
DECLARE VARIABLE WVALORRESIDUALCONTABILMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOBAIXAMOEDA NUMERIC(15,6);
DECLARE VARIABLE WVALORBAIXAREAL NUMERIC(15,6);
DECLARE VARIABLE WVALORAQUISICAOMOEDA NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,6);
DECLARE VARIABLE WTAXAAUX NUMERIC(6,6);
DECLARE VARIABLE WTAXAANT NUMERIC(6,6);
DECLARE VARIABLE WDEPRECIACAOPERIODOAUX NUMERIC(15,6);
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,6);
DECLARE VARIABLE WCODMOEDA INTEGER;
DECLARE VARIABLE WVALORMOEDA NUMERIC(15,6);
DECLARE VARIABLE WREFMOEDAINI VARCHAR(10);
DECLARE VARIABLE WREFMOEDAFIM VARCHAR(10);
DECLARE VARIABLE WCODBEMORIGINAL INTEGER;
DECLARE VARIABLE WDATAORIGAQUISICAO DATE;
DECLARE VARIABLE WDEPDIA VARCHAR(5);
DECLARE VARIABLE WDEPMENSAL VARCHAR(5);
DECLARE VARIABLE WDEPMESBAIXA VARCHAR(5);
DECLARE VARIABLE WDATAINICIOCALC DATE;
DECLARE VARIABLE WDATAFIMCALC DATE;
DECLARE VARIABLE WDATAULTIMOITEMDEP DATE;
DECLARE VARIABLE WVALDEPACUMUBEM NUMERIC(15,6);
DECLARE VARIABLE WNUMDIAS INTEGER;
DECLARE VARIABLE WDEPDIADATA INTEGER;
DECLARE VARIABLE WFIRST VARCHAR(5);
DECLARE VARIABLE WDTBAIXAAUX DATE;
DECLARE VARIABLE WMESESDEPRECIADOSOUTRATAXA INTEGER;
DECLARE VARIABLE WDEPRECIACAOACUMULADA NUMERIC(15,6);
DECLARE VARIABLE WDATAINIMES DATE;
DECLARE VARIABLE WDATAINICIALCALCULO DATE;
DECLARE VARIABLE WDIASDEPRECIADOS INTEGER;
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUAL NUMERIC(15,6);
DECLARE VARIABLE WTIPO INTEGER;
DECLARE VARIABLE WVALORRESIDUAL NUMERIC(15,6);
DECLARE VARIABLE WREFANTERIORRESIDUAL INTEGER;
DECLARE VARIABLE WREFPOSTERIORRESIDUAL INTEGER;
DECLARE VARIABLE WPRIMEIRADEPRE INTEGER;
DECLARE VARIABLE WDEPDIABAIXA VARCHAR(5);
DECLARE VARIABLE WVALORCAPITAL NUMERIC(15,2);
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WINICIOCALCAUX DATE;
DECLARE VARIABLE WDATATOTALMESES DATE;
DECLARE VARIABLE WTOTALMESESDEPRECIACAO INTEGER;
DECLARE VARIABLE WMESDEPRECIACAONOVATAXA INTEGER;
DECLARE VARIABLE WVALORSEMBAIXA NUMERIC(15,6);
BEGIN
  /*Stored procedure para somar os valores das depreciações. Principalmente
  quando houver várias depreciações cadastradas no bem. O cálculo da depreciação
  é feito na verdade na sp_cons_calc_dep_correcao*/
  prvalorcorrigidoanterior        = 0;
  prcorrecaoperiodo               = 0;
  prvalorcorrigidoatual           = 0;
  prdepreciacaoacumuladaanterior  = 0;
  prdepreciacaoperiodo            = 0;
  prdepreciacaoperiodomoeda       = 0;
  prdepreciacaoacumuladaatual     = 0;
  prdepreciacaoacumuladaatualmoed = 0;
  prcorrecaomonetariadepreciacao  = 0;
  prvalorresidualcontabil         = 0;
  prvalorresidualcontabilmoeda    = 0;
  prtotalmesesdepreciacao         = 0;
  prmesesdepreciados              = 0;
  prmesesdepreciar                = 0;
  prtaxadepreciacaoanual          = 0;
  prdatataxadepreciacao           = NULL;
  PRDATAINICALC                   = NULL;
  prvalorbaixa                    = 0;
  BDVALORCAPITAL                  = 0;
  prdepreciacaobaixamoeda         = 0;
  prvalorbaixareal                = 0;
  prvalormoeda                    = 0;
  prdatabaixa                     = NULL;
  prvaloraquisicaomoeda           = 0;
  prvalorcorrigidoanteriormoeda   = 0;
  prvaloraquisicaooriginal        = 0;
  prctadebitodepre                = 0;
  prvalordepreciacaodiariafim     = 0;
  prtaxadepreciacaoanual_ant      = 0;
  wprimeiradepre                  = 0;

  wdepreciacaoperiodo             = 0;
  wdepreciacaoperiodoaux          = 0;
  wtaxaaux                        = 0;
  wdepreciacaoperiodomoeda        = 0;
  wmesesdepreciadosaux            = 0;
  wdepreciacaoacumuladaanterior   = 0;
  wcodmoeda                       = 0;
  wvalormoeda                     = 0;
  wrefmoedaini                    = '';
  wrefmoedafim                    = '';
  wvalorbaixabem                  = 0;
  wpossuibaixa                    = 'FALSE';
  wcodbemoriginal                 = 0;
  wdataorigaquisicao              = NULL;
  wdepdia                         = 'FALSE';
  wdepmensal                      = 'FALSE';
  wdepmesbaixa                    = 'FALSE';
  wdatainiciocalc                 = NULL;
  wdatafimcalc                    = NULL;
  WREFANTERIORRESIDUAL            = NULL;
  WREFPOSTERIORRESIDUAL           = NULL;
  wdataultimoitemdep              = NULL;
  wvaldepacumubem                 = 0;
  wnumdias                        = 0;
  wdepdiadata                     = 0;
  wfirst                          = 'TRUE';
  wdtbaixaaux                     = NULL;
  wdepreciacaoacumulada           = 0;
  WDATAINIMES                     = NULL;
  WDATAINICIAlCALCULO             = NULL;
  WDEPRECIACAOACUMULADAATUAL      = 0;
  wtaxaant                        = NULL;
  winiciocalcaux                  = NULL;
  wdatatotalmeses                 = NULL;
  wtotalmesesdepreciacao          = NULL;
  wcount                          = 0;
  wmesdepreciacaonovataxa         = 0;
  WVALORSEMBAIXA                  = 0;

  BDCODEMP = PRCODEMP;
  BDCODBEM = PRCODBEM;

  PRDATAINICIAL = extract(MONTH FROM PRDATAINICIAL)||'/01/'||extract(year FROM PRDATAINICIAL);
  prdatafinal = extract(MONTH FROM PRDATAFINAL)||'/01/'||extract(year FROM PRDATAFINAL);
  prdatafinal = DATEADD(MONTH, 1, prdatafinal);
  prdatafinal = DATEADD(DAY, -1, prdatafinal);

  --#alt:85169. Os cálculos para a opção de relatório 2 devem ser os mesmo da depreciação, se não os valores ficam incorretos. Ana - 21/06/2018
  --#133490. Os calsulos para opção de relátorio 3 devem ser os mesmo da depreciação. Leonardo Pereira - 12/03/2020
  WTIPO = PRTIPO;
  if (WTIPO in (2,3,4))  then
    WTIPO = 0;

  SELECT tbem.bdDATORIAQUIBEM, COALESCE(tbem.bdcodind,0) FROM empresas_tbem tbem
  WHERE (tbem.bdcodemp = :prcodemp) AND
        (tbem.bdcodbem = :prcodbem)
  INTO :wdataaquisicao, :wcodmoeda;

  --SELECT tind.bddescind,tbem.bdcodind

  --#alt:21384 - Estava sempre pegando o maior valor da moeda do ano da aquisição do bem, quando na verdade deve pegar sempre o valor mais próximo ao mês da aquisição. Ana - 13/11/2017
  --#alt:89963 - Carlos Machado - 24/10/2018 - Estava buscando 6.000 registros, no fim, na RN, em 1 mes buscava 20.000.000
  SELECT FIRST 1 tind.bdvalind FROM tindval tind
         WHERE tind.bdcodind = :wcodmoeda AND
         tind.bddataind <= :wdataaquisicao
         ORDER BY tind.bdcodind DESC,tind.bddataind DESC
   INTO :wvalormoeda;

  --Converte a moeda para cruzeiros reias
  --#alt:142871 - 05/10/2020 - Machado - Alterado para apenas fazer quando o valor da moeda e maior que 1000
  IF (wdataaquisicao <= CAST('06/30/1994' AS DATE) and wvalormoeda >= 1000) THEN
    wvalormoeda = wvalormoeda / 1000;

  IF ((wvalormoeda IS NULL) or (CAST(wvalormoeda AS NUMERIC(15, 2)) = 0)) THEN
    wvalormoeda = 0.8287;

  /*wrefmoedaini = SUBSTRING(CAST(:wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'0101';
  wrefmoedafim = SUBSTRING(CAST(:wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4)||'1231';
  SELECT MAX(tind.bdvalind) FROM tindval tind
         WHERE (tind.bdcodind = :wcodmoeda) AND
               (tind.bdrefind BETWEEN :wrefmoedaini AND :wrefmoedafim)
  INTO :wvalormoeda;
  --caso não encontre um valor nesse periodo, o sql a seguir retorna o mais próximo
  IF (wvalormoeda IS NULL) THEN
    BEGIN
      SELECT FIRST 1 tind.bdvalind FROM tindval tind
             WHERE tind.bdcodind = :wcodmoeda AND
             tind.bdrefind <= :wrefmoedaini
             ORDER BY tind.bdrefind DESC    --#alt:17142 - Alterado para pegar da ultima referencia. Ana - 02/02/2017
      INTO :wvalormoeda;
    END*/
  --#alt:21384. fim

  wmes = CAST(SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano = CAST(EXTRACT(YEAR FROM wdataaquisicao) AS INTEGER);--cast(substring(cast(wdataaquisicao as varchar(10)) from 1 for 4) as integer);
  --select ultdia from ULTIMO_DIA_MES(:wmes,:wano) into wultdiames;
  -- Cálculo que retorna o último dia do mês
  wultdiames = EXTRACT(DAY FROM (wdataaquisicao - EXTRACT(DAY FROM wdataaquisicao) +
                       32 - EXTRACT(DAY FROM wdataaquisicao - EXTRACT(DAY FROM wdataaquisicao) + 32)));

  wdtini  = wmes||'-01-'||wano;
  wdtfim  = wmes||'-'||wultdiames||'-'||wano ;
  wrefatu = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
  wreffim = CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER);

  --#alt:18204 - Adicionei a verificação da data da aquisição com a data final para não executar quando não pertencer ao período de aquisição do bem. Ana - 28/04/2017
  WHILE ((wrefatu < wreffim) AND (prdatafinal >= wdataaquisicao)) DO
    BEGIN
      /* A antiga rotina da depreciação estava pegando sempre o valor da moeda do mês de aquisição, por isso
         fiz a busca do valor fora do while das referências, mas deixei como comentário caso seja feito
         para busca o valor da moeda conforme o mês em que esta calculando
      --Conforme me explicado a moeda Ufir está congelada, por isso não preciso verifcar o valor dela todos os meses
      if ((wvalormoeda is null) or (wvalormoeda = 0) or (position('UFIR',upper(wdescmoeda)) = 0))  then
        begin
          --Seleciona o valor da moeda da data de aquisição ou se o bem já vier depreciado da data original de aquisição
          wrefmoedaini = substring(cast(:wdataaquisicao as varchar(10)) from 1 for 4)||'0101';
          wrefmoedafim = substring(cast(:wdataaquisicao as varchar(10)) from 1 for 4)||'1231';

          select max(tind.bdvalind) from tindval tind
                 where (tind.bdcodind = :wcodmoeda) and
                       (tind.bdrefind between :wrefmoedaini and :wrefmoedafim)
          into :wvalormoeda;
          --caso não encontre um valor nesse periodo, o sql a seguir retorna o mais próximo
          if (wvalormoeda is null) then
            begin
              select first 1 tind.bdvalind from tindval tind
                     where tind.bdcodind = :wcodmoeda and
                     tind.bdrefind <= :wrefmoedaini
                     order by tind.bdrefind
              into :wvalormoeda;
            end
        end*/
      --Só faz o select da taxa da deprecição quando mudar o período ou o valor resídual mudar de período
      --Valor residual, quando trocado o valor residual deve refazer o SELECT - Carlos Machado - #89963
      IF ((COALESCE(prtaxadepreciacaoanual,0) = 0) OR
          (wrefatu < CAST((SUBSTRING(wdatainiciocalc FROM 1 FOR 4)) || (SUBSTRING(wdatainiciocalc FROM 6 FOR 2)) AS INTEGER)) OR
          (wrefatu > CAST((SUBSTRING(wdatafimcalc FROM 1 FOR 4)) || (SUBSTRING(wdatafimcalc FROM 6 FOR 2)) AS INTEGER)) OR
          (WREFATU < WREFANTERIORRESIDUAL) or (wrefatu >= WREFPOSTERIORRESIDUAL))  THEN
        --#alt:16415 - Alterada a verificação do case, pois quando não havia nehuma contabilização ele não levava o valor do bem. Ana - 05/12/2016
        --Faz o select com o First, pois um bem pode ter mais de uma depreciação cadastrada.
        --alt:14255 - 28/06/2016 - Adicionado case para verificar o tipo da contabilização e ver de onde irá buscar valor da aquisição. Pedro
        --SELECT FIRST 1 tbem.bdcodorigbem, tbem.bdvalaquibem, tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem,
        SELECT FIRST 1 tbem.bdcodorigbem, COALESCE(CASE WHEN ((tdep.BDCONTABILIZACAO = 0) OR (tdep.BDCONTABILIZACAO IS NULL) ) THEN tbem.BDVALAQUIBEM ELSE tdep.BDVALAQUISOC END, 0),
               tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem, tbem.bddepdiaria BDDEPDIARIA, tbem.bddepmesaquibem, tbem.bddepmesbaixabem,
               tdep.bddatinicalcbem, tdep.bddatfimcalcbem, tdep.bddatadep, COALESCE(tdep.bdvaldepacumubem,0),tdep.bdctadebitodepre, tbem.bdnumdias, tbem.bddepdiadata,
               coalesce(TRES.BDVALORRESIDUAL, 0), TRES.BDREFERENCIA, TRESPOS.BDREFERENCIA, tbem.BDDEPDIABAIXA
        FROM empresas_tbem tbem
        LEFT OUTER JOIN empresas_tdepreciacao tdep ON ((tbem.bdcodemp = tdep.bdcodemp) AND (tbem.bdcodbem = tdep.bdcodbem) AND
                                                       (tdep.bdcontabilizacao = :prcontabilizacao) AND
                                                       (CAST((SUBSTRING(tdep.bddatinicalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatinicalcbem FROM 6 FOR 2)) AS INTEGER) <=
                                                        CAST((SUBSTRING(:wdtini FROM 1 FOR 4)) || (SUBSTRING(:wdtini FROM 6 FOR 2)) AS INTEGER)) AND
                                                       ((CAST((SUBSTRING(tdep.bddatfimcalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatfimcalcbem FROM 6 FOR 2)) AS INTEGER) >=
                                                         CAST((SUBSTRING(:wdtfim FROM 1 FOR 4)) || (SUBSTRING(:wdtfim FROM 6 FOR 2)) AS INTEGER)) OR (tdep.bddatfimcalcbem IS NULL)))
        LEFT OUTER JOIN EMPRESAS_TVALORRESIDUAL TRES ON (TBEM.BDCODBEM = TRES.BDCODBEM
                                                        AND TBEM.BDCODEMP = TRES.BDCODEMP
                                                        AND TRES.BDCONTABILIZACAO = :PRCONTABILIZACAO
                                                        AND TRES.BDREFERENCIA = (SELECT FIRST 1 RESI.BDREFERENCIA
                                                                                      FROM EMPRESAS_TVALORRESIDUAL RESI
                                                                                      WHERE RESI.BDCODBEM = TRES.BDCODBEM
                                                                                        AND RESI.BDCODEMP = TRES.BDCODEMP
                                                                                        AND RESI.BDCONTABILIZACAO = :PRCONTABILIZACAO
                                                                                        AND RESI.BDREFERENCIA <= :wrefatu
                                                                                      ORDER BY RESI.BDREFERENCIA DESC))
        LEFT OUTER JOIN EMPRESAS_TVALORRESIDUAL TRESPOS ON (TBEM.BDCODBEM = TRESPOS.BDCODBEM
                                                          AND TBEM.BDCODEMP = TRESPOS.BDCODEMP
                                                          AND TRESPOS.BDCONTABILIZACAO = :PRCONTABILIZACAO
                                                          AND TRESPOS.BDREFERENCIA = (SELECT FIRST 1 RESI.BDREFERENCIA
                                                                                          FROM EMPRESAS_TVALORRESIDUAL RESI
                                                                                          WHERE RESI.BDCODBEM = TRESPOS.BDCODBEM
                                                                                            AND RESI.BDCODEMP = TRESPOS.BDCODEMP
                                                                                            AND RESI.BDCONTABILIZACAO = :PRCONTABILIZACAO
                                                                                            AND RESI.BDREFERENCIA > :wrefatu
                                                                                          ORDER BY RESI.BDREFERENCIA))

        WHERE (tbem.bdcodemp = :prcodemp) AND
              (tbem.bdcodbem = :prcodbem)
        ORDER BY tdep.bddatinicalcbem DESC
        INTO :wcodbemoriginal,    :prvaloraquisicaooriginal, :wtaxaaux,         :wdataaquisicao,  :wdataorigaquisicao,
             :wdepdia,            :wdepmensal,               :wdepmesbaixa,     :wdatainiciocalc, :wdatafimcalc,
             :wdataultimoitemdep, :wvaldepacumubem,          :prctadebitodepre, :wnumdias,        :wdepdiadata,
             :wvalorresidual, :wrefanteriorresidual, :wrefposteriorresidual, :wdepdiabaixa;



      if (wtaxaaux is null) then
        wtaxaaux = 0;
      --alt:13784 - 12/04/2016 - Se tiver trocado de taxa de depreciação, precisa levar os meses já depreciados com a taxa anterior para o cálculo da próxima. Pedro
      IF ((wprimeiradepre > 0) AND (wtaxaant <> wtaxaaux)) THEN
        BEGIN
          prtaxadepreciacaoanual_ant = wtaxaant;
          wmesesdepreciadosoutrataxa = prmesesdepreciados;
          --alt:13784 - 12/04/2016 - Se estiver marcado para detalhar por taxa de depreciação, precisa retornar aqui a taxa. Pedro
          IF (prdetalhartaxadep = 1 and wtaxaaux > 0) THEN
            BEGIN
              prmesesdepreciar = prtotalmesesdepreciacao - prmesesdepreciados;
              prsomardepreciacao = 0; --alt:13784 - 03/05/2016 - Só deve somar nos totais do relatório quando for a única taxa ou a última (caso esteja detalhando por taxa de depreciação). Pedro
              SUSPEND;
            END
        END

      if (wtaxaaux > 0) then
        wprimeiradepre = 1;

      if (winiciocalcaux <> wdatainiciocalc) then
        begin
          wdepmensal = 'TRUE';
          wcount = wcount + 2;
          prmesesdepreciados = 0;
        end
      winiciocalcaux = wdatainiciocalc;

      wdepreciacaoperiodoaux = COALESCE(wdepreciacaoperiodo,0);
      SELECT prcorrecaoperiodo, prvalorcorrigidoatual, prdepreciacaoperiodo, prmesesdepreciados, prvalorbaixa,
             prdepreciacaoperiodomoeda, prvalorresidualcontabil, prvalorresidualcontabilmoeda,
             prdepreciacaobaixamoeda, prvalorbaixareal, prvaloraquisicaomoeda,
             prdepreciacaoacumuladaanterior, prtaxadepreciacaoanual, prdepreciacaoacumuladaatualmoed,
             prtotalmesesdepreciacao, prvaloraquisicaooriginal, prdatabaixa, prdepreciacaoacumuladaatual, PRMESNOVATAXA
      FROM sp_cons_calc_dep_correcao(:prcodemp, :prcodbem, :wdtini, :wdtfim, :WTIPO /*:prtipo*/, :prcontabilizacao,:wvalormoeda,:wpossuibaixa,:wcodbemoriginal,
                                     :prvaloraquisicaooriginal,:wtaxaaux,:wdataaquisicao,:wdataorigaquisicao,:wdepdia,:wdepmensal,
                                     :wdepmesbaixa,:wdatainiciocalc,:wdatafimcalc,:wdataultimoitemdep,:wvaldepacumubem,:prctadebitodepre,:wnumdias,
                                     :wdepdiadata, :wvalorbaixabem, :wmesesdepreciadosoutrataxa, :wdepreciacaoacumulada, :WVALORRESIDUAL, :wdepdiabaixa,0,:wcount, :wmesdepreciacaonovataxa, :prRelBaiPar)
      INTO :wcorrecaoperiodo, :wvalorcorrigidoatual, :wdepreciacaoperiodo, :wmesesdepreciados, :wvalorbaixa,
           :wdepreciacaoperiodomoeda, :wvalorresidualcontabil, :wvalorresidualcontabilmoeda,
           :wdepreciacaobaixamoeda, :wvalorbaixareal, :wvaloraquisicaomoeda,
           :wdepreciacaoacumuladaanterior, :prtaxadepreciacaoanual, :wdepreciacaoacumuladaatualmoed,
           :prtotalmesesdepreciacao, :prvaloraquisicaooriginal, :prdatabaixa, :wdepreciacaoacumulada, :wmesdepreciacaonovataxa;

      if (wcount = 2) then
       begin
        wcount = 1;
       end

      IF (wcorrecaoperiodo > 0) THEN
        BEGIN
          wcorrecaoperiodo = ABS(wcorrecaoperiodo - prcorrecaoperiodo);
          IF (wcorrecaoperiodo > 0) THEN
            prcorrecaoperiodo = prcorrecaoperiodo + wcorrecaoperiodo;
        END

      IF (wvalorcorrigidoatual > 0) THEN
        BEGIN
          wvalorcorrigidoatual = ABS(wvalorcorrigidoatual - prvalorcorrigidoatual);
          --alt:9013 - Foi retirada a incrementação do valor corrigido atual daqui pois estava duplicando a correção baseada no valor da baixa. Pedro
          /*if (wvalorcorrigidoatual > 0) then
            prvalorcorrigidoatual = abs(prvalorcorrigidoatual - wvalorcorrigidoatual);*/
        END

      --Feito esse tratamento pois posso ter várias taxas cadastradas para o bem. Não posso utilizar o
      --prdepreciacaoacumuladaanterior pois a rotina calcula como se sempre fosse a taxa do mês em questão
      -- Início
      IF ((prdepreciacaoacumuladaanterior = 0) AND (prtaxadepreciacaoanual > 0) AND (wdepreciacaoacumuladaanterior > 0)) THEN
        BEGIN
          wdepreciacaoacumuladaanterior = ABS(wdepreciacaoacumuladaanterior - prdepreciacaoacumuladaanterior);
          IF (wdepreciacaoacumuladaanterior > 0) THEN
            prdepreciacaoacumuladaanterior = prdepreciacaoacumuladaanterior + wdepreciacaoacumuladaanterior;
        END
      ELSE
      IF (wdepreciacaoperiodoaux > 0) THEN
        prdepreciacaoacumuladaanterior = prdepreciacaoacumuladaanterior + wdepreciacaoperiodoaux;

      IF ((prdepreciacaoacumuladaatualmoed = 0) AND (prtaxadepreciacaoanual > 0) AND (wdepreciacaoacumuladaatualmoed > 0)) THEN
        BEGIN
          wdepreciacaoacumuladaatualmoed = ABS(wdepreciacaoacumuladaatualmoed - prdepreciacaoacumuladaatualmoed);
          IF (wdepreciacaoacumuladaatualmoed > 0) THEN
            prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatualmoed + wdepreciacaoacumuladaatualmoed;
        END
      ELSE
      IF (wdepreciacaoperiodomoeda > 0) THEN
        prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatualmoed + wdepreciacaoperiodomoeda;
      -- Fim

      IF (wvalorresidualcontabil > 0) THEN
        BEGIN
          wvalorresidualcontabil = ABS(wvalorresidualcontabil - prvalorresidualcontabil);
          IF ((prvalorresidualcontabil > 0) AND (wdepreciacaoperiodo > 0) AND (wvalorresidualcontabil <> wdepreciacaoperiodo)) THEN
            wvalorresidualcontabil = wdepreciacaoperiodo;

          IF (wvalorresidualcontabil > 0) THEN
            prvalorresidualcontabil = ABS(prvalorresidualcontabil - wvalorresidualcontabil);
        END

      IF (wvalorresidualcontabilmoeda > 0) THEN
        BEGIN
          wvalorresidualcontabilmoeda = ABS(wvalorresidualcontabilmoeda - prvalorresidualcontabilmoeda);
          IF ((prvalorresidualcontabilmoeda > 0) AND (wdepreciacaoperiodomoeda > 0) AND (wvalorresidualcontabilmoeda <> wdepreciacaoperiodomoeda)) THEN
            wvalorresidualcontabilmoeda = wdepreciacaoperiodomoeda;

          IF (wvalorresidualcontabilmoeda > 0) THEN
            prvalorresidualcontabilmoeda = ABS(prvalorresidualcontabilmoeda - wvalorresidualcontabilmoeda);
        END

      --alt:14761 - 16/06/2016 - Se tiver valor de depreciação acumulada (informado no cadastro da depreciação)
      --é feito um cálculo da quantidade de meses já depreciados e assim precisa retornar eles também. Pedro
      IF ((wdepreciacaoperiodo > 0) OR (wvaldepacumubem > 0)) THEN
        BEGIN
          IF ((wtaxaaux > 0) AND (wtaxaaux <> prtaxadepreciacaoanual)) THEN
            wmesesdepreciadosaux = wmesesdepreciadosaux + ABS(wmesesdepreciadosaux - prmesesdepreciados);

          IF ((wmesesdepreciados > 0) AND ((prmesesdepreciados = 0) OR (wmesesdepreciados > prmesesdepreciados))) THEN --alt:13784 - 12/04/2016 - Quando trocada a taxa de depreciação não estava levando os meses depreciados corretamente. Pedro
            prmesesdepreciados = wmesesdepreciados;
          --alt:9013 - Colocada essa validação para não continuar depreciando depois do total de meses da depreciação, isso acontecia quando tinha depreciação diária. Pedro
          ELSE IF (prmesesdepreciados <> prtotalmesesdepreciacao) THEN
            prmesesdepreciados = prmesesdepreciados + 1;
        END
      --#Alt:5105
      /*if (wvalorbaixa > 0) then
        begin
          wvalorbaixa = ABS(wvalorbaixa - prvalorbaixa);
          if (wvalorbaixa > 0) then
            prvalorbaixa = prvalorbaixa + wvalorbaixa;
        end*/

      wvalorsembaixa = wvalorsembaixa + wvalorbaixa;

      IF (wdepreciacaobaixamoeda > 0) THEN
        BEGIN
          wdepreciacaobaixamoeda = (wdepreciacaobaixamoeda - prdepreciacaobaixamoeda);
          IF (wdepreciacaobaixamoeda > 0) THEN
            prdepreciacaobaixamoeda = prdepreciacaobaixamoeda + wdepreciacaobaixamoeda;
        END

      IF (wvalorbaixareal > 0) THEN
        BEGIN
          wvalorbaixareal = ABS(wvalorbaixareal - prvalorbaixareal);
          IF (wvalorbaixareal > 0) THEN
            prvalorbaixareal = prvalorbaixareal + wvalorbaixareal;
        END

      IF (wvaloraquisicaomoeda > 0) THEN
        BEGIN
          wvaloraquisicaomoeda = ABS(wvaloraquisicaomoeda - prvaloraquisicaomoeda);
          IF (wvaloraquisicaomoeda > 0) THEN
            prvaloraquisicaomoeda = ABS(prvaloraquisicaomoeda - wvaloraquisicaomoeda);
        END

      IF (prdatabaixa IS NOT NULL) THEN
        wdtbaixaaux = prdatabaixa;

      wtaxaant = wtaxaaux;
      wcount = wcount;
      wtaxaaux = prtaxadepreciacaoanual;
      wdtini   = addmonth(wdtini, 1);
      wdtfim   = addmonth(wdtini, 1)-1;
      wrefatu  = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
    END

  --alt:15196 - 09/11/2016 - Alterado para carregar a depreciação acumulada da variável que está somando o valor para cada período. Pedro
  /*IF (wdepreciacaoperiodo > 0) THEN
    prdepreciacaoacumuladaanterior = prdepreciacaoacumuladaanterior + wdepreciacaoperiodo;*/

  prdepreciacaoacumuladaanterior = wdepreciacaoacumulada;

  wtaxaaux = COALESCE(wtaxaaux,0);
  /* Final depreciação anteriores */

  wdtini  = prdatainicial;
  wmes    = CAST(SUBSTRING(CAST(wdtini AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano    = CAST(EXTRACT(YEAR FROM wdtini) AS INTEGER);--cast(substring(cast(wdtini as varchar(10)) from 1 for 4) as integer);
  --select ultdia from ULTIMO_DIA_MES(:wmes,:wano) into wultdiames;
  -- Cálculo que retorna o último dia do mês
  wultdiames = EXTRACT(DAY FROM (wdtini - EXTRACT(DAY FROM wdtini) +
               32 - EXTRACT(DAY FROM wdtini - EXTRACT(DAY FROM wdtini) + 32)));
  wdtfim  = CAST(wmes||'-'||wultdiames||'-'||wano AS DATE);
  IF (wdtfim > prdatafinal) THEN
    wdtfim = prdatafinal;
  wrefatu = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
  wreffim = CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER);

  prdepreciacaoacumuladaatual = prdepreciacaoacumuladaanterior;

  --#alt:18204 - Adicionei a verificação da data da aquisição com a data final para não executar quando não pertencer ao período de aquisição do bem. Ana - 28/04/2017
  WHILE ((wrefatu <= wreffim) AND (prdatafinal >= wdataaquisicao)) DO
    BEGIN
      /* A antiga rotina da depreciação estava pegando sempre o valor da moeda do mês de aquisição, por isso
         fiz a busca do valor fora do while das referências, mas deixei como comentário caso seja feito
         para busca o valor da moeda conforme o mês em que esta calculando
      --Conforme me explicado a moeda Ufir está congelada, por isso não preciso verifcar o valor dela todos os meses
      if ((wvalormoeda is null) or (wvalormoeda = 0) or (position('UFIR',upper(wdescmoeda)) = 0))  then
        begin
          --Seleciona o valor da moeda da data de aquisição ou se o bem já vier depreciado da data original de aquisição
          wrefmoedaini = substring(cast(:wdataaquisicao as varchar(10)) from 1 for 4)||'0101';
          wrefmoedafim = substring(cast(:wdataaquisicao as varchar(10)) from 1 for 4)||'1231';

          select max(tind.bdvalind) from tindval tind
                 where (tind.bdcodind = :wcodmoeda) and
                       (tind.bdrefind between :wrefmoedaini and :wrefmoedafim)
          into :wvalormoeda;
          --caso não encontre um valor nesse periodo, o sql a seguir retorna o mais próximo
          if (wvalormoeda is null) then
            begin
              select first 1 tind.bdvalind from tindval tind
                     where tind.bdcodind = :wcodmoeda and
                     tind.bdrefind <= :wrefmoedaini
                     order by tind.bdrefind
              into :wvalormoeda;
            end
        end*/

      --Só faz o select da taxa da deprecição quando mudar o período ou o valor resídual mudar de período
      --Valor residual, quando trocado o valor residual deve refazer o SELECT - Carlos Machado - #89963
      IF ((COALESCE(prtaxadepreciacaoanual,0) = 0) OR
          (wrefatu < CAST((SUBSTRING(wdatainiciocalc FROM 1 FOR 4)) || (SUBSTRING(wdatainiciocalc FROM 6 FOR 2)) AS INTEGER)) OR
          (wrefatu > CAST((SUBSTRING(wdatafimcalc FROM 1 FOR 4)) || (SUBSTRING(wdatafimcalc FROM 6 FOR 2)) AS INTEGER)) OR
          (WREFATU < WREFANTERIORRESIDUAL) or (wrefatu >= WREFPOSTERIORRESIDUAL)) THEN
        --#alt:16415 - Alterada a verificação do case, pois quando não havia nehuma contabilização ele não levava o valor do bem. Ana - 05/12/2016
        --Faz o select com o First, pois um bem pode ter mais de uma depreciação cadastrada.
        --alt:14255 - 28/06/2016 - Adicionado case para verificar o tipo da contabilização e ver de onde irá buscar valor da aquisição. Pedro
        --SELECT FIRST 1 tbem.bdcodorigbem, tbem.bdvalaquibem, tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem,
        SELECT FIRST 1 tbem.bdcodorigbem, COALESCE(CASE WHEN ((tdep.BDCONTABILIZACAO = 0) OR (tdep.BDCONTABILIZACAO IS NULL) ) THEN tbem.BDVALAQUIBEM ELSE tdep.BDVALAQUISOC END, 0),
               tdep.bdtaxadep, tbem.bddatoriaquibem, tbem.bddatoriaquibem, tbem.bddepdiaria BDDEPDIARIA, tbem.bddepmesaquibem, tbem.bddepmesbaixabem,
               tdep.bddatinicalcbem, tdep.bddatfimcalcbem, tdep.bddatadep, COALESCE(tdep.bdvaldepacumubem,0),tdep.bdctadebitodepre, tbem.bdnumdias, tbem.bddepdiadata,
               coalesce(TRES.BDVALORRESIDUAL, 0), TRES.BDREFERENCIA, TRESPOS.BDREFERENCIA, tbem.BDDEPDIABAIXA
        FROM empresas_tbem tbem
        LEFT OUTER JOIN empresas_tdepreciacao tdep ON ((tbem.bdcodemp = tdep.bdcodemp) AND (tbem.bdcodbem = tdep.bdcodbem) AND
                                                       (tdep.bdcontabilizacao = :prcontabilizacao) AND
                                                       (CAST((SUBSTRING(tdep.bddatinicalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatinicalcbem FROM 6 FOR 2)) AS INTEGER) <=
                                                        CAST((SUBSTRING(:wdtini FROM 1 FOR 4)) || (SUBSTRING(:wdtini FROM 6 FOR 2)) AS INTEGER)) AND
                                                       ((CAST((SUBSTRING(tdep.bddatfimcalcbem FROM 1 FOR 4)) || (SUBSTRING(tdep.bddatfimcalcbem FROM 6 FOR 2)) AS INTEGER) >=
                                                         CAST((SUBSTRING(:wdtfim FROM 1 FOR 4)) || (SUBSTRING(:wdtfim FROM 6 FOR 2)) AS INTEGER)) OR (tdep.bddatfimcalcbem IS NULL)))
        LEFT OUTER JOIN EMPRESAS_TVALORRESIDUAL TRES ON (TBEM.BDCODBEM = TRES.BDCODBEM
                                                        AND TBEM.BDCODEMP = TRES.BDCODEMP
                                                        AND TRES.BDCONTABILIZACAO = :PRCONTABILIZACAO
                                                        AND TRES.BDREFERENCIA = (SELECT FIRST 1 RESI.BDREFERENCIA
                                                                                      FROM EMPRESAS_TVALORRESIDUAL RESI
                                                                                      WHERE RESI.BDCODBEM = TRES.BDCODBEM
                                                                                        AND RESI.BDCODEMP = TRES.BDCODEMP
                                                                                        AND RESI.BDCONTABILIZACAO = :PRCONTABILIZACAO
                                                                                        AND RESI.BDREFERENCIA <= :wrefatu
                                                                                      ORDER BY RESI.BDREFERENCIA DESC))
        LEFT OUTER JOIN EMPRESAS_TVALORRESIDUAL TRESPOS ON (TBEM.BDCODBEM = TRESPOS.BDCODBEM
                                                          AND TBEM.BDCODEMP = TRESPOS.BDCODEMP
                                                          AND TRESPOS.BDCONTABILIZACAO = :PRCONTABILIZACAO
                                                          AND TRESPOS.BDREFERENCIA = (SELECT FIRST 1 RESI.BDREFERENCIA
                                                                                          FROM EMPRESAS_TVALORRESIDUAL RESI
                                                                                          WHERE RESI.BDCODBEM = TRESPOS.BDCODBEM
                                                                                            AND RESI.BDCODEMP = TRESPOS.BDCODEMP
                                                                                            AND RESI.BDCONTABILIZACAO = :PRCONTABILIZACAO
                                                                                            AND RESI.BDREFERENCIA > :wrefatu
                                                                                          ORDER BY RESI.BDREFERENCIA))
        WHERE (tbem.bdcodemp = :prcodemp) AND
              (tbem.bdcodbem = :prcodbem)
        INTO :wcodbemoriginal,    :prvaloraquisicaooriginal, :wtaxaaux,         :wdataaquisicao,  :wdataorigaquisicao,
             :wdepdia,            :wdepmensal,               :wdepmesbaixa,     :wdatainiciocalc, :wdatafimcalc,
             :wdataultimoitemdep, :wvaldepacumubem,          :prctadebitodepre, :wnumdias,        :wdepdiadata,
             :wvalorresidual, :wrefanteriorresidual, :wrefposteriorresidual, :wdepdiabaixa;

      --alt:96245 - 11/02/2019 - Carlos Machado - Caso a taxa venha nula leva 0
      if (wtaxaaux is null) then
        wtaxaaux = 0;
      IF ((wprimeiradepre > 0) AND (wtaxaant <> wtaxaaux)) THEN
        BEGIN
          prtaxadepreciacaoanual_ant = wtaxaant;
          wmesesdepreciadosoutrataxa = prmesesdepreciados;
          --alt:13784 - 12/04/2016 - Se estiver marcado para detalhar por taxa de depreciação, precisa retornar aqui a taxa. Pedro
          IF (prdetalhartaxadep = 1 and wtaxaaux > 0) THEN
            BEGIN
              prmesesdepreciar = prtotalmesesdepreciacao - prmesesdepreciados;
              prsomardepreciacao = 0; --alt:13784 - 03/05/2016 - Só deve somar nos totais do relatório quando for a única taxa ou a última (caso esteja detalhando por taxa de depreciação). Pedro
              SUSPEND;
            END
        END
      PRDATAINICALC = WDATAINICIOCALC;

      if (wtaxaaux > 0) then
        wprimeiradepre = 1;
      --alt:15793 - 22/09/2016 - Se tiver informação de depreciação em outra taxa ou valor acumulado, não é o primeiro mês a depreciar,
      --então precisa mudar o valor desta variável, pois estava calculando incorretamente a depreciação acumulada atual nestes casos. Pedro
      wFirst = IIF((wvaldepacumubem = 0) AND (wmesesdepreciadosoutrataxa = 0) AND (wFirst = 'TRUE'), 'TRUE', 'FALSE');

      --#alt:16929 - Quando há um valor de depreciação acumulada cadastrado deve ser substituido pelo valor da depreciação acumulada anterior ao período. Ana - 01/02/2017
      wdatainimes = SUBSTRING(CAST(wdtini AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                    SUBSTRING(CAST(wdtini AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
      wdatainicialcalculo = SUBSTRING(CAST(wdatainiciocalc AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                            SUBSTRING(CAST(wdatainiciocalc AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';

      wdiasdepreciados = DATEDIFF(DAY,:wdatainicialcalculo,:wdatainimes);

      IF (((wdiasdepreciados < 28) or (wdiasdepreciados < 30 AND extract(MONTH from wdatainicialcalculo) <> 2)) AND (wdepreciacaoacumuladaanterior > 0) AND ((wdiasdepreciados > -1) OR (prdepreciacaoacumuladaanterior <> wdepreciacaoacumuladaanterior)) )THEN
        prdepreciacaoacumuladaanterior = wvaldepacumubem;
      --#alt:16929. fim

      if (winiciocalcaux <> wdatainiciocalc) then
        wdepmensal = 'TRUE';
      IF ((wdepmensal = 'TRUE') AND (winiciocalcaux <> wdatainiciocalc)) THEN
        wcount = wcount + 1;

      if (wtaxaant <> wtaxaaux) then
        begin
         wmesesdepreciados = 0;
         prmesesdepreciados = 0;
        end

      if ((wrefatu = CAST((SUBSTRING(wdatainiciocalc FROM 1 FOR 4)) || (SUBSTRING(wdatainiciocalc FROM 6 FOR 2)) AS INTEGER))
      and (wdepmensal = 'TRUE') and (wtaxaant > 0) and ((prdepreciacaoacumuladaanterior <> 0) or (wvaldepacumubem > 0))) then
        wcount = 2;

      winiciocalcaux = wdatainiciocalc;

      SELECT prdepreciacaoperiodo, prdepreciacaoperiodomoeda, prcorrecaomonetariadepreciacao,
             prvalorresidualcontabil, prvalorresidualcontabilmoeda, prtotalmesesdepreciacao,
             prmesesdepreciados, prmesesdepreciar, prtaxadepreciacaoanual, prdatataxadepreciacao, prvalorbaixa, bdvalorcapital,
             prdepreciacaobaixamoeda, prvalorbaixareal, prvalormoeda, prdatabaixa, prvaloraquisicaomoeda, prvalorcorrigidoanteriormoeda,
             prvaloraquisicaooriginal, prctadebitodepre, prvalordepreciacaodiariafim, prvalorcorrigidoanterior,
             prvalorcorrigidoatual, prdepreciacaoacumuladaanterior, prdepreciacaoacumuladaatualmoed, prdepreciacaoacumuladaatual, prcompensacaobaixaperanterior,PRMESNOVATAXA
      FROM sp_cons_calc_dep_correcao(:prcodemp, :prcodbem, :wdtini, :wdtfim, :prtipo, :prcontabilizacao,:wvalormoeda,:wpossuibaixa,:wcodbemoriginal,
                                     :prvaloraquisicaooriginal,:wtaxaaux,:wdataaquisicao,:wdataorigaquisicao,:wdepdia,:wdepmensal,
                                     :wdepmesbaixa,:wdatainiciocalc,:wdatafimcalc,:wdataultimoitemdep,:wvaldepacumubem,:prctadebitodepre,:wnumdias,
                                     :wdepdiadata, :wvalorbaixabem, :wmesesdepreciadosoutrataxa, :prdepreciacaoacumuladaatual, :wvalorresidual, :wdepdiabaixa, 0,:wcount,:wmesdepreciacaonovataxa, :prRelBaiPar)
      INTO   :wdepreciacaoperiodo, :wdepreciacaoperiodomoeda, :wcorrecaomonetariadepreciacao,
             :wvalorresidualcontabil, :wvalorresidualcontabilmoeda, :prtotalmesesdepreciacao,
             :wmesesdepreciados, :prmesesdepreciar, :prtaxadepreciacaoanual, :prdatataxadepreciacao, :wvalorbaixa, :wvalorcapital,
             :wdepreciacaobaixamoeda, :wvalorbaixareal, :prvalormoeda, :prdatabaixa, :wvaloraquisicaomoeda, :wvalorcorrigidoanteriormoeda,
             :prvaloraquisicaooriginal, :prctadebitodepre, :prvalordepreciacaodiariafim, :wvalorcorrigidoanterior,
             :wvalorcorrigidoatual, :wdepreciacaoacumuladaanterior, :wdepreciacaoacumuladaatualmoed, :wdepreciacaoacumuladaatual, :prcompensacaobaixaperanterior, :wmesdepreciacaonovataxa;

      --#alt:16929 - Alterada verificação para substituir o valor da depreciação acumuludada anterior.
      -- Quando há uma depreciação acumulada anterior cadastrada na taxa de depreciação, então esta deve ser substituida. Ana - 31/01/2017
      --#Alt:5105 -> Acrescentado a variável wfirst

      if (wcount = 2) then
        wcount = 1;

      IF ((prdepreciacaoacumuladaanterior = 0)  AND (wdepreciacaoacumuladaanterior > 0) AND (wvaldepacumubem <> 0) and (datediff(month, :prdatainicalc, :prdatainicial) >= 0) /*AND (wfirst = 'TRUE')*/) THEN
        BEGIN
          wdepreciacaoacumuladaanterior = ABS(wdepreciacaoacumuladaanterior - prdepreciacaoacumuladaanterior);
          IF (wdepreciacaoacumuladaanterior > 0) THEN
            prdepreciacaoacumuladaanterior = prdepreciacaoacumuladaanterior + wdepreciacaoacumuladaanterior;

          IF (wfirst = 'TRUE') THEN
          prdepreciacaoacumuladaatual = prdepreciacaoacumuladaanterior;
        END
      wfirst = 'FALSE';

      IF (((wtaxaaux = prtaxadepreciacaoanual) OR (wtaxaaux = 0)) AND (prdepreciacaoacumuladaatualmoed = 0)) THEN
        BEGIN
          --if (wdepmensal = 'FALSE') then
           --wdepreciacaoacumuladaatualmoed = ABS(wdepreciacaoacumuladaatualmoed - wdepreciacaoperiodomoeda);
          IF (wdepreciacaoacumuladaatualmoed > 0) THEN
            prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatualmoed + wdepreciacaoacumuladaatualmoed;
        END

      prdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatualmoed;

      IF ((wvalorcorrigidoanterior > 0) AND (prvalorcorrigidoanterior = 0)) THEN
        prvalorcorrigidoanterior = prvaloraquisicaooriginal - wvalorsembaixa;

      if ((wvalorcorrigidoatual > 0) and (prvalorcorrigidoatual = 0)) then
        prvalorcorrigidoatual = wvalorcorrigidoatual;

      IF ((wvalorcorrigidoanteriormoeda > 0) AND (prvalorcorrigidoanteriormoeda = 0)) THEN
        prvalorcorrigidoanteriormoeda = wvalorcorrigidoanteriormoeda;

      prdepreciacaoperiodo            = (prdepreciacaoperiodo + COALESCE(wdepreciacaoperiodo,0));
      prdepreciacaoperiodomoeda       = prdepreciacaoperiodomoeda + COALESCE(wdepreciacaoperiodomoeda,0);
      prcorrecaomonetariadepreciacao  = prcorrecaomonetariadepreciacao + COALESCE(wcorrecaomonetariadepreciacao,0);

      --alt:14761 - 20/06/2016 - Quando há baixa, pode não haver depreciação no período, então estava sendo calculado incorretamente. Pedro
      --alt:14624 - 14/06/2016 - Aparentemente estava somando novamente a depreciação do período porque vinha
      --errado do sp_cons_calc_dep_correcao, porém agora vem certo e estava somando valor de um mês a mais. Pedro
      --prdepreciacaoacumuladaatual     = prdepreciacaoacumuladaatual + COALESCE(wdepreciacaoperiodo,0);
      --prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatualmoed + COALESCE(wdepreciacaoperiodomoeda,0);
      --prdepreciacaoacumuladaatual     = prdepreciacaoacumuladaanterior + COALESCE(wdepreciacaoperiodo,0);
      --prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatual / COALESCE(wvalormoeda,0);

      --#alt:18200 - Comentado pois foram feitas alterações na sp_cons_calc_dep_correcao que não há mais necessidade de fazer esta verificação. Ana - 04/05/2017
      --alt:16006 - 03/11/2016 - Só deve carregar o saldo anterior no caso de ter baixa e não depreciar neste mês, caso contrario, se estiver calculando mais de um mês de uma vez, o saldo anterior vem incorreto. Pedro
      /*if ((wdepmesbaixa <> 'TRUE') and (wvalorbaixa > 0)) then
        prdepreciacaoacumuladaanterior  = wdepreciacaoacumuladaanterior;  */
      --alt:14624 - Fim

      --#alt:16852 - Quando não tiver uma taxa cadastrada então deve levar o valor correto do valo residual que é o valor original do bem - o total de baixas. Ana - 01/02/2017
      IF ((prtotalmesesdepreciacao = 0) or (PRRELBAIPAR = 1)) THEN
        prvalorresidualcontabil = wvalorresidualcontabil;
      ELSE
      IF (wvalorresidualcontabil > 0) THEN
        BEGIN
          wvalorresidualcontabil = ABS(wvalorresidualcontabil - prvalorresidualcontabil);
          --alt:16006 - 23/11/2016 - Corrigido para trazer o valor residual considerando quando houver baixa. Pedro
          --IF ((prvalorresidualcontabil > 0) AND (wdepreciacaoperiodo > 0) AND (wvalorresidualcontabil <> wdepreciacaoperiodo)) THEN
          --  wvalorresidualcontabil = wdepreciacaoperiodo;

          IF (wvalorresidualcontabil > 0) THEN
            prvalorresidualcontabil = ABS(prvalorresidualcontabil - wvalorresidualcontabil);
        END

      --#alt:16852 - Quando o valor da aquisição for o mesmo do valor residual o valor residual moeda ja vem correto da sp. Ana - 10/02/2017
      IF ((prvaloraquisicaooriginal = prvalorresidualcontabil) or (PRRELBAIPAR = 1)) THEN
        prvalorresidualcontabilmoeda = wvalorresidualcontabilmoeda;
      ELSE
      IF (wvalorresidualcontabilmoeda > 0) THEN
        BEGIN
          wvalorresidualcontabilmoeda = ABS(wvalorresidualcontabilmoeda - prvalorresidualcontabilmoeda);
          --alt:16006 - 23/11/2016 - Corrigido para trazer o valor residual considerando quando houver baixa. Pedro
          --IF ((prvalorresidualcontabilmoeda > 0) AND (wdepreciacaoperiodomoeda > 0) AND (wvalorresidualcontabilmoeda <> wdepreciacaoperiodomoeda)) THEN
          --  wvalorresidualcontabilmoeda = wdepreciacaoperiodomoeda;

          IF (wvalorresidualcontabilmoeda > 0) THEN
            prvalorresidualcontabilmoeda = ABS(prvalorresidualcontabilmoeda - wvalorresidualcontabilmoeda);
        END

      --alt:14761 - 20/06/2016 - Se tiver baixa no período também precisa retornar os meses depreciados. Pedro
      --alt:14761 - 16/06/2016 - Se tiver valor de depreciação acumulada (informado no cadastro da depreciação)
      --é feito um cálculo da quantidade de meses já depreciados e assim precisa retornar eles também. Pedro
      IF ((wdepreciacaoperiodo > 0) OR (wvaldepacumubem > 0) OR (wvalorbaixa > 0)) THEN
        BEGIN
          IF ((wtaxaaux > 0) AND (wtaxaaux <> prtaxadepreciacaoanual)) THEN
            wmesesdepreciadosaux = wmesesdepreciadosaux + ABS(wmesesdepreciadosaux - prmesesdepreciados);

          IF ((wmesesdepreciados > 0) AND ((prmesesdepreciados = 0) OR (wmesesdepreciados > prmesesdepreciados))) THEN --alt:13784 - 12/04/2016 - Quando trocada a taxa de depreciação não estava levando os meses depreciados corretamente. Pedro
            prmesesdepreciados = wmesesdepreciados;
          --alt:9013 - Comentado pois essa validação não faz sentido quando é depreciação diária. Pedro
          /*else
            if (not prmesesdepreciados = prtotalmesesdepreciacao) then
               prmesesdepreciados = prmesesdepreciados + 1; */
        END

      IF (wvalorbaixa > 0) THEN
        BEGIN
          --#alt:18200 - Comentado pois desta forma estava calculando o valor da baixa incorretamente. Ana - 04/05/2017
          --wvalorbaixa = ABS(wvalorbaixa - prvalorbaixa);
          IF (wvalorbaixa > 0) THEN
            prvalorbaixa = prvalorbaixa + wvalorbaixa;
        END

      bdvalorcapital = bdvalorcapital + wvalorcapital;

      IF (wdepreciacaobaixamoeda > 0) THEN
        BEGIN
          wdepreciacaobaixamoeda = (wdepreciacaobaixamoeda - prdepreciacaobaixamoeda);
          IF (wdepreciacaobaixamoeda > 0) THEN
            prdepreciacaobaixamoeda = prdepreciacaobaixamoeda + wdepreciacaobaixamoeda;
        END

      IF (wvaloraquisicaomoeda > 0) THEN
        BEGIN
          wvaloraquisicaomoeda = ABS(wvaloraquisicaomoeda - prvaloraquisicaomoeda);
          IF (wvaloraquisicaomoeda > 0) THEN
            prvaloraquisicaomoeda = ABS(prvaloraquisicaomoeda - wvaloraquisicaomoeda);
        END

      IF (wvalorcorrigidoatual > 0) THEN
        BEGIN
          --#alt:18200 - O valor ja vem correto da sp_cons_calc_dep_correcao com as novas alterações. Ana - 02/05/2017
          prvalorcorrigidoatual = wvalorcorrigidoatual;
          /*wvalorcorrigidoatual = ABS(wvalorcorrigidoatual - prvalorcorrigidoatual);
          IF (wvalorcorrigidoatual > 0) THEN
            prvalorcorrigidoatual = ABS(prvalorcorrigidoatual - wvalorcorrigidoatual);*/
          --#alt:18200. fim
        END

      --#alt:19501 - Foi feito o tratamento na sp de correção para quando o bem estiver totalmente baixado e não for o mês da baixa total, então todos os saldos devem ser zerados. Ana - 22/09/2017
      IF ((wdepreciacaoperiodo = 0) AND (wdepreciacaoacumuladaatual = 0) AND (prdepreciacaoacumuladaanterior <> 0) AND (prvalorbaixa = 0) AND (wvalorbaixareal = PRVALORAQUISICAOORIGINAL)) THEN
        BEGIN
          prdepreciacaoacumuladaanterior = 0;
          prdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual * wvalormoeda);
          --se não tiver baixa no período da consulta, então o bem ja foi totalmente baixado. Com isso o saldo anterior, valor residual e valor residual moeda devem ir zerados
          IF (wpossuibaixa = 'FALSE') THEN
            BEGIN
              prdepreciacaoacumuladaatual  = 0;
              prvalorresidualcontabil      = 0;
              prvalorresidualcontabilmoeda = 0;
            END
        END
      ELSE
        IF ((prdepreciacaoacumuladaatual = 0) OR (wdepreciacaoacumuladaatual <> 0)) THEN
        BEGIN
          --antes o valor de retorno da sp era setado direto na variável de retorno, mas não deve substituir sempre
          prdepreciacaoacumuladaatual = wdepreciacaoacumuladaatual;
        END
      --#alt:19501. fim

      IF (prdepreciacaoacumuladaatual > (prdepreciacaoperiodo + prdepreciacaoacumuladaanterior)) then
         prdepreciacaoperiodo = prdepreciacaoacumuladaatual - prdepreciacaoacumuladaanterior;

      IF (wvalorbaixareal > 0) THEN
        BEGIN
          wvalorbaixareal = ABS(wvalorbaixareal - prvalorbaixareal);
          IF (wvalorbaixareal > 0) THEN
            prvalorbaixareal = prvalorbaixareal + wvalorbaixareal;
        END

      IF (prdatabaixa IS NOT NULL) THEN
        BEGIN
          wdtbaixaaux = prdatabaixa;
          --#alt:19501 - Atribui à variável o valor true quando possuir alguma baixa no período. Colocando como true não interfere na sp da correção, pois la dentro é refeita esta verificação. Ana - 22/09/2017'
          wpossuibaixa = 'TRUE';
        END

      wtaxaant = wtaxaaux;
      wtaxaaux = COALESCE(prtaxadepreciacaoanual,0);
      wdtini   = addmonth(wdtini, 1);
      wdtfim   = addmonth(wdtini, 1)-1;
      IF (wdtfim > prdatafinal) THEN
        wdtfim = prdatafinal;
      wrefatu = CAST((SUBSTRING(wdtini FROM 1 FOR 4)) || (SUBSTRING(wdtini FROM 6 FOR 2)) AS INTEGER);
    END

  --#alt:18200 - Alterada forma de cálculo do valor corrigido atual (valor corrigido anterior + correção do período - valor de baixas do período). Ana - 02/05/2017
  prvalorcorrigidoatual = (prvalorcorrigidoanterior + prcorrecaoperiodo - prvalorbaixa);

  --#alt:19501 - Se o valor corrigido atual for zero, então o bem ja foi totalmente depreciado/baixado. Ana - 22/09/2017
  IF (prvalorcorrigidoatual = 0) THEN
    BEGIN
      prcorrecaomonetariadepreciacao = 0;
      prvalorresidualcontabil        = 0;
      prvalorresidualcontabilmoeda   = 0;
    END

  prtotalmesesdepreciacao = prtotalmesesdepreciacao + wmesesdepreciadosaux;
  --alt:11609 - 21/10/2015 - Corrigido, estava retornando o valor incorreto para o meses a depreciar. Há um outro cálculo
  --que é feito na variável wmesesdepreciados que não estava sendo propagado por pegar o valor do prmesesdepreciados. Pedro
  prmesesdepreciar        = prtotalmesesdepreciacao - prmesesdepreciados; --alt:13978 - 06/04/2016 - Voltado como era antes, corrigido o tratamento dos campos. Pedro
  --prmesesdepreciar        = prtotalmesesdepreciacao - wmesesdepreciados;

  --#alt:16929 - Estava trazendo a quantidade de meses depreciados maior que o total de meses de depreciação e os meses a depreciar negativo. Ana - 01/02/2017
  IF (prmesesdepreciados > prtotalmesesdepreciacao) THEN
    BEGIN
      prmesesdepreciados = prtotalmesesdepreciacao;
      prmesesdepreciar   = 0;
    END

  --#alt:16852 - Quando não tiver uma taxa cadastrada então deve levar o valor correto do valor residual. Quando o valor residual for 0 o residual moeda também deve ser. Ana - 08/02/2017
  IF (((prtotalmesesdepreciacao = prmesesdepreciados) AND (prtotalmesesdepreciacao > 0)) OR (prvalorresidualcontabil = 0)) THEN
    BEGIN
      prcorrecaomonetariadepreciacao = 0;
      prvalorresidualcontabil        = 0;
      prvalorresidualcontabilmoeda   = 0;
    END

  --#alt:17098 - Com um período maior do que a data da baixa estava retornando null, então se teve alguma baixa durante o período selecionado deve retornar essa data. Ana - 19/05/2017
  IF ((prdatabaixa IS NULL) AND (wdtbaixaaux IS NOT NULL))THEN
    prdatabaixa = wdtbaixaaux;

  --alt:9581 - Joga o valor para a variável de retorno, antes no último mês em alguns casos não retornava nada. Pedro
  --prmesesdepreciados = wmesesdepreciados; --alt:13978 - 06/04/2016 - Agora o retorno está correto acima, e se jogar o valor aqui, mata outro tratamento acima. Pedro
  if (PRVALORCORRIGIDOATUAL = 0) then
     BDVALORRESIDUAL =  0;
  else
    BEGIN
      BDVALORRESIDUAL = WVALORRESIDUAL;
      if (PRVALORCORRIGIDOATUAL - BDVALORRESIDUAL > 0) then
        PRVALORCORRIGIDOATUAL = PRVALORCORRIGIDOATUAL - BDVALORRESIDUAL;
      else
        PRVALORCORRIGIDOATUAL = 0;
    END
  --#Alt:5105
  IF (prvaloraquisicaooriginal = wvalorbaixabem) THEN
    BEGIN
      prvalorresidualcontabil      = 0;
      prvalorresidualcontabilmoeda = 0;

      IF ((wdepmesbaixa = 'TRUE') AND
          (wreffim > CAST((SUBSTRING(wdtbaixaaux FROM 1 FOR 4)) || (SUBSTRING(wdtbaixaaux FROM 6 FOR 2)) AS INTEGER))) THEN
        BEGIN
          prvalorcorrigidoanterior        = 0;
          prcorrecaoperiodo               = 0;
          prvalorcorrigidoatual           = 0;
          prvalorbaixa                    = 0;
          prdepreciacaoacumuladaanterior  = 0;
          prdepreciacaoperiodo            = 0;
          prdepreciacaoperiodomoeda       = 0;
          prdepreciacaoacumuladaatual     = 0;
          prdepreciacaoacumuladaatualmoed = 0;
          prcorrecaomonetariadepreciacao  = 0;
          prtotalmesesdepreciacao         = 0;
          prmesesdepreciados              = 0;
          prmesesdepreciar                = 0;
        END
    END

  prsomardepreciacao = 1; --alt:13784 - 03/05/2016 - Só deve somar nos totais do relatório quando for a única taxa ou a última (caso esteja detalhando por taxa de depreciação). Pedro
  SUSPEND;
END
^

/* Restore proc. body: SP_CONS_CALC_DEP_CORRECAO */
CREATE OR ALTER PROCEDURE SP_CONS_CALC_DEP_CORRECAO (
    PRCODEMP INTEGER,
    PRCODBEM INTEGER,
    PRDATAINICIAL DATE,
    PRDATAFINAL DATE,
    PRTIPO INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRVLRMOEDA NUMERIC(15,2),
    PRPOSSUIBAIXA VARCHAR(5),
    PRCODBEMORIGINAL INTEGER,
    PRVALORAQUISICAO NUMERIC(15,2),
    PRTAXADEPANUAL NUMERIC(6,2),
    PRDATAAQUISICAO DATE,
    PRDATAORIGAQUISICAO DATE,
    PRDEPDIA VARCHAR(5),
    PRDEPMENSAL VARCHAR(5),
    PRDEPMESBAIXA VARCHAR(5),
    PRDATAINICIOCALC DATE,
    PRDATAFIMCALC DATE,
    PRDATAULTIMOITEMDEP DATE,
    PRVALDEPACUMUBEM NUMERIC(15,2),
    PRCTADEBDEPRE INTEGER,
    PRNUMDIAS INTEGER,
    PRDEPDIADATA INTEGER,
    PRVALORBAIXABEM NUMERIC(15,2),
    PRMESESDEPRECIADOSOUTRATAXA INTEGER,
    PRVALORACUMULADOANTERIOR NUMERIC(15,2),
    PRVALORRESIDUAL NUMERIC(15,2) = 0,
    PRDEPDIABAIXA VARCHAR(5) = 'FALSE',
    PRTAXAANT NUMERIC(15,2) = 0,
    PRCONT INTEGER = 0,
    PRMESDEPRECIACAONOVATAXA INTEGER = 0,
    prRelBaiPar INTEGER = 0)
RETURNS (
    PRVALORCORRIGIDOANTERIOR NUMERIC(15,2),
    PRCORRECAOPERIODO NUMERIC(15,2),
    PRVALORCORRIGIDOATUAL NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2),
    PRDEPRECIACAOPERIODO NUMERIC(15,2),
    PRDEPRECIACAOPERIODOMOEDA NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
    PRDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,2),
    PRCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2),
    PRVALORRESIDUALCONTABIL NUMERIC(15,2),
    PRVALORRESIDUALCONTABILMOEDA NUMERIC(15,2),
    PRTOTALMESESDEPRECIACAO INTEGER,
    PRMESESDEPRECIADOS INTEGER,
    PRMESESDEPRECIAR INTEGER,
    PRTAXADEPRECIACAOANUAL NUMERIC(6,2),
    PRDATATAXADEPRECIACAO DATE,
    PRVALORBAIXA NUMERIC(15,2),
    PRDEPRECIACAOBAIXAMOEDA NUMERIC(15,2),
    PRVALORBAIXAREAL NUMERIC(15,2),
    PRVALORMOEDA NUMERIC(15,2),
    PRDATABAIXA DATE,
    PRVALORAQUISICAOMOEDA NUMERIC(15,2),
    PRVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,2),
    PRVALORAQUISICAOORIGINAL NUMERIC(15,2),
    PRCTADEBITODEPRE INTEGER,
    PRVALORDEPRECIACAODIARIAFIM NUMERIC(15,2),
    PRCOMPENSACAOBAIXAPERANTERIOR NUMERIC(15,2),
    BDVALORCAPITAL NUMERIC(15,2),
    PRMESNOVATAXA INTEGER)
AS
DECLARE VARIABLE WCODBEMORIGINAL INTEGER;
DECLARE VARIABLE WVALORCORRIGIDOANTERIOR DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOACUMULADAANTERIOR DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOPERIODO DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOPERIODOMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUAL DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUALMOED DOUBLE PRECISION;
DECLARE VARIABLE WVALORRESIDUALCONTABIL DOUBLE PRECISION;
DECLARE VARIABLE WVALORRESIDUALCONTABILMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WTOTALMESESDEPRECIACAO INTEGER;
DECLARE VARIABLE WMESESDEPRECIADOS INTEGER;
DECLARE VARIABLE WDIASDEPRECIADOS INTEGER;
DECLARE VARIABLE WMESESDEPRECIAR INTEGER;
DECLARE VARIABLE WVALORAQUISICAO DOUBLE PRECISION;
DECLARE VARIABLE WVALORAQUISICAOAUX DOUBLE PRECISION;
DECLARE VARIABLE WVALORAQUISICAOORIGINAL DOUBLE PRECISION;
DECLARE VARIABLE WDATAORIGAQUISICAO DATE;
DECLARE VARIABLE WDATAAQUISICAO DATE;
DECLARE VARIABLE WDATAINICIOCALC DATE;
DECLARE VARIABLE WDATAFIMCALC DATE;
DECLARE VARIABLE WDATAATUAL DATE;
DECLARE VARIABLE WDATATOTALMESES DATE;
DECLARE VARIABLE WDATAULTIMOITEMDEP DATE;
DECLARE VARIABLE WVALORBAIXA DOUBLE PRECISION;
DECLARE VARIABLE WVALORBAIXAAUX DOUBLE PRECISION;
DECLARE VARIABLE WVALORBAIXAPER DOUBLE PRECISION;
DECLARE VARIABLE WDEPRECIACAOBAIXAMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WDEPDIA VARCHAR(5);
DECLARE VARIABLE WDEPDIASADEPRECIAR INTEGER;
DECLARE VARIABLE WDEPMENSAL VARCHAR(5);
DECLARE VARIABLE WTOTALMESESDOPERIODO INTEGER;
DECLARE VARIABLE WVALORDEPRECIACAOMENSAL DOUBLE PRECISION;
DECLARE VARIABLE WVALORDEPRECIACAODIARIA DOUBLE PRECISION;
DECLARE VARIABLE WVALORDEPRECIACAODIARIABAIXA DOUBLE PRECISION;
DECLARE VARIABLE WVALORAQUISICAOMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WDIFERENCAMESES INTEGER;
DECLARE VARIABLE WDATABAIXA DATE;
DECLARE VARIABLE WVALDEPACUMUBEM DOUBLE PRECISION;
DECLARE VARIABLE WMESESDEPACUMUBEM INTEGER;
DECLARE VARIABLE WDATAOFICIALINICIOLCALCULO DATE;
DECLARE VARIABLE WDATAINICIALINICIOCALCULO DATE;
DECLARE VARIABLE WULTIMODIADOMES SMALLINT;
DECLARE VARIABLE WDIA SMALLINT;
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WNUMDIAS INTEGER;
DECLARE VARIABLE WDEPDIADATA INTEGER;
DECLARE VARIABLE WDATAINICIALOFICIAL DATE;
DECLARE VARIABLE WDEPDIAFINAL VARCHAR(5);
DECLARE VARIABLE WDATATOTALMESESULTIMODIA DATE;
DECLARE VARIABLE WDEPMESBAIXA VARCHAR(5);
DECLARE VARIABLE WDATATOTALMESESDEPDIA DATE;
DECLARE VARIABLE WVALORCORRIGIDOANTERIORMOEDA DOUBLE PRECISION;
DECLARE VARIABLE WVERIFICAMESINTEIRO INTEGER;
DECLARE VARIABLE WDIASDEPDIARIA DOUBLE PRECISION;
DECLARE VARIABLE WMESESDEPDIARIA DOUBLE PRECISION;
DECLARE VARIABLE WDATAINICIOCALCAUX DATE;
DECLARE VARIABLE WVALOR DOUBLE PRECISION;
DECLARE VARIABLE WVALORDEPDIA_BAIXA NUMERIC(15,2);
DECLARE VARIABLE WDATADEPDIA_BAIXA INTEGER;
DECLARE VARIABLE WVALORDEPDIA_BAIXA_AUX NUMERIC(15,2);
DECLARE VARIABLE WDATADEPDIA_BAIXA_AUX INTEGER;
DECLARE VARIABLE WDATADEPDIA_BAIXA_AUX2 INTEGER;
DECLARE VARIABLE WVALORCAPITAL NUMERIC(15,2);
DECLARE VARIABLE WMUDOUTAXA INTEGER;
DECLARE VARIABLE WTAXAANT NUMERIC(6,2);
DECLARE VARIABLE WAQUISICAOREDUZIUVALORACUMULADO INTEGER;
DECLARE VARIABLE WTEMTRANSBEMREF INTEGER;
DECLARE VARIABLE WDATATRANSFBEM DATE;
BEGIN
  PRVALORCORRIGIDOANTERIOR        = 0;
  PRCORRECAOPERIODO               = 0;
  PRVALORCORRIGIDOATUAL           = 0;
  PRDEPRECIACAOACUMULADAANTERIOR  = 0;
  PRDEPRECIACAOPERIODO            = 0;
  PRDEPRECIACAOPERIODOMOEDA       = 0;
  PRDEPRECIACAOACUMULADAATUAL     = 0;
  PRDEPRECIACAOACUMULADAATUALMOED = 0;
  PRCORRECAOMONETARIADEPRECIACAO  = 0;
  PRVALORRESIDUALCONTABIL         = 0;
  PRVALORRESIDUALCONTABILMOEDA    = 0;
  PRTOTALMESESDEPRECIACAO         = 0;
  PRMESESDEPRECIADOS              = 0;
  PRMESESDEPRECIAR                = 0;
  PRTAXADEPRECIACAOANUAL          = 0;
  PRDATATAXADEPRECIACAO           = NULL;
  PRVALORBAIXA                    = 0;
  BDVALORCAPITAL                  = 0;
  PRDEPRECIACAOBAIXAMOEDA         = 0;
  PRVALORBAIXAREAL                = 0;
  PRVALORMOEDA                    = 0;
  PRDATABAIXA                     = NULL;
  PRVALORAQUISICAOMOEDA           = 0;
  PRVALORCORRIGIDOANTERIORMOEDA   = 0;
  PRVALORAQUISICAOORIGINAL        = 0;
  PRCTADEBITODEPRE                = NULL;
  PRVALORDEPRECIACAODIARIAFIM     = 0;
  wdatainicialoficial            = prdatainicial;
  wdepdiafinal                   = 'FALSE';
  wnumdias                       = 0;
  wdepdiadata                    = 0;
  wultimodiadomes                = 0;
  wdepdiasadepreciar             = 0;
  wvalordepreciacaodiaria        = 0;
  wvalordepreciacaodiariabaixa   = 0;
  wvaloraquisicaomoeda           = 0;
  wvalorcorrigidoanterior        = 0;
  wdepreciacaoacumuladaanterior  = 0;
  wdepreciacaoperiodo            = 0;
  wdepreciacaoperiodomoeda       = 0;
  wdepreciacaoacumuladaatual     = 0;
  wdepreciacaoacumuladaatualmoed = 0;
  wvalorresidualcontabil         = 0;
  wvalorresidualcontabilmoeda    = 0;
  wtotalmesesdepreciacao         = 0;
  wmesesdepreciados              = 0;
  wdiasdepreciados               = 0;
  wmesesdepreciar                = 0;
  wvaloraquisicao                = 0;
  wvaloraquisicaoaux             = 0;
  wvaloraquisicaooriginal       = 0;
  wdataaquisicao                 = NULL;
  wdatainiciocalc                = NULL;
  wdatafimcalc                   = NULL;
  wdataatual                     = :prdatafinal;
  wdatatotalmeses                = NULL;
  wdatatotalmesesdepdia          = NULL;
  wdatatotalmesesultimodia       = NULL;
  wdataultimoitemdep             = NULL;
  wvalorbaixa                    = 0;
  wvalorbaixaaux                 = 0;
  wvalorbaixaper                 = 0;
  wvaldepacumubem                = 0;
  wmesesdepacumubem              = 0;
  wdataoficialiniciolcalculo     = NULL;
  wdatainicialiniciocalculo      = NULL;
  prvaloracumuladoanterior       = COALESCE(prvaloracumuladoanterior, 0);
  WMUDOUTAXA                     = 0;
  wAquisicaoReduziuValorAcumulado= 0;
  WTEMTRANSBEMREF                = 0;
  WDATATRANSFBEM                 = NULL;

  wvaloraquisicao        = prvaloraquisicao;
  wvaloraquisicaooriginal= wvaloraquisicao;
  prtaxadepreciacaoanual = prtaxadepanual;
  wdataaquisicao         = prdataaquisicao;
  wdataorigaquisicao     = prdataorigaquisicao;
  wdepdia                = prdepdia;
  wdepmensal             = prdepmensal;
  wdepmesbaixa           = prdepmesbaixa;
  wdatainiciocalc        = prdatainiciocalc;
  wdatafimcalc           = prdatafimcalc;
  wdataultimoitemdep     = prdataultimoitemdep;
  wvaldepacumubem        = prvaldepacumubem;
  prctadebitodepre       = prctadebdepre;
  wnumdias               = prnumdias;
  wdepdiadata            = prdepdiadata;
  wdepreciacaoacumuladaatual = prvaloracumuladoanterior;
  prdepdiabaixa          = COALESCE(UPPER(prdepdiabaixa), 'FALSE');
  wtaxaant               = prtaxaant;

  IF (wvaloraquisicao IS NULL) THEN
     BEGIN
       EXCEPTION ex_date;
       SUSPEND;
       EXIT;
     END

   IF ((wdatafimcalc <> null) and (prdatainicial > wdatafimcalc)) THEN
     EXIT;

   if (wdatainiciocalc = wdatafimcalc) then
    prcont = 0;

  --Processo para calcular os meses anteriores ao período informado, pois posso ter várias depreciações cadastradas
  SELECT COALESCE(SUM(tbai.bdvalbai),0) AS TotalBaixa FROM empresas_tbai tbai
  WHERE (tbai.bdcodemp = :prcodemp)
  AND   (tbai.bdcodbem = :prcodbem)
  AND   (tbai.bddatbai <= :prdatafinal)
  AND   (tbai.BDCONTABILIZACAO = :prContabilizacao)
  INTO :wvalorbaixa;
  IF (wvalorbaixa > 0) THEN
    prpossuibaixa = 'TRUE';

  SELECT first 1 bddata_transf from  EMPRESAS_TBEM_TRANSFERENCIA 
  WHERE (BDCODEMP_PARA = :prcodemp) and (BDCODBEM_PARA = :prcodbem)
  INTO :WDATATRANSFBEM;
  
  if ((WDATATRANSFBEM is not null) and (F_AAAAMM(WDATATRANSFBEM) between F_AAAAMM(prdatainicial) and F_AAAAMM(prdatafinal))) then
    WTEMTRANSBEMREF = 1;

  prvaloraquisicaooriginal = wvaloraquisicao;
  IF (prpossuibaixa = 'TRUE') THEN
    BEGIN
      FOR SELECT bddatbai,COALESCE(SUM(bdvalbai),0) AS TotalBaixa, SUM(BDVALVENBAI) - SUM(bdvalbai) AS ValorCapital FROM empresas_tbai
          WHERE (bdcodemp = :prcodemp) AND (bdcodbem = :prcodbem) AND (BDCONTABILIZACAO = :prContabilizacao)
          AND   (bddatbai BETWEEN :prdatainicial AND :prdatafinal) GROUP BY bddatbai
          INTO :wdatabaixa,:wvalorbaixaaux, :wvalorcapital DO
        BEGIN
          wvalorbaixaper = wvalorbaixaper + wvalorbaixaaux;
          bdvalorcapital = bdvalorcapital + wvalorcapital;
        END
    END
  wvaloraquisicao = (wvaloraquisicao - wvalorbaixa);
  --Valor residual, subtrai valor residual - Carlos Machado - #alt:89963 - 24/10/2018
  IF (WVALORAQUISICAO - PRVALORRESIDUAL > 0) THEN
    WVALORAQUISICAO = (WVALORAQUISICAO - PRVALORRESIDUAL);
  ELSE
    WVALORAQUISICAO = 0;

  IF ((UPPER(wdepmesbaixa) = 'TRUE') /*and (wvalorbaixa >= wvaloraquisicao)*/) THEN
    BEGIN
      IF ((CAST((SUBSTRING(wdatabaixa FROM 1 FOR 4)) || (SUBSTRING(wdatabaixa FROM 6 FOR 2)) AS INTEGER) <=
          CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER))) THEN
        wdepmesbaixa = 'TRUE';
      ELSE
        wdepmesbaixa = 'FALSE';
    END
  ELSE
    wdepmesbaixa = 'FALSE';

  prcorrecaoperiodo     = 0;

  --#alt:123529 - Carlos Machado - 21/08/2020 - Quando for 31 e num dias ser "30 dias" deve depreciar um dia
  IF (UPPER(wdepdia) = 'TRUE' AND wnumdias <> 2 and extract(day from wdatainiciocalc) = 31) THEN
    wdatainiciocalc = wdatainiciocalc - 1;

  IF ((UPPER(wdepmesbaixa) = 'TRUE')) THEN
    wvaloraquisicao = (wvaloraquisicao + wvalorbaixaper);

  IF (wdatainiciocalc IS NOT NULL) THEN
    wdataoficialiniciolcalculo = wdatainiciocalc;
  ELSE
    wdataoficialiniciolcalculo =  wdataaquisicao;

  -- Meses já depreciados
  wmesesdepreciados = DATEDIFF(MONTH,:wdataoficialiniciolcalculo,:wdataatual);
  IF (wmesesdepreciados < 0) THEN
    wmesesdepreciados = 0;

  --#alt:16929 - Adicionada verificação para atribuir o valor do campo cadastrado na deprecição acumulada, pois estava ignorando este campo e fazendo os calculos errados. Ana - 31/01/2017
  wdatainicialoficial = SUBSTRING(CAST(prdatainicial AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                        SUBSTRING(CAST(prdatainicial AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
  wdatainicialiniciocalculo = SUBSTRING(CAST(wdataoficialiniciolcalculo AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                              SUBSTRING(CAST(wdataoficialiniciolcalculo AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';

  wdiasdepreciados = DATEDIFF(DAY,:wdatainicialiniciocalculo,:wdatainicialoficial);
  IF ((wvaldepacumubem <> 0) AND (((wdiasdepreciados < 28) or (wdiasdepreciados < 30 AND extract(MONTH from wdataoficialiniciolcalculo) <> 2)) AND ((wvaldepacumubem <> prdepreciacaoacumuladaanterior) OR (wdiasdepreciados > -1)))) THEN
    wdepreciacaoacumuladaatual = wVALDEPACUMUBEM;
  wdatainicialoficial = prdatainicial;
  --#alt:16929. fim

  IF (CAST((SUBSTRING(wdataatual FROM 1 FOR 4)) || (SUBSTRING(wdataatual FROM 6 FOR 2)) AS INTEGER) /*>*/=
      CAST((SUBSTRING(wdataoficialiniciolcalculo FROM 1 FOR 4)) || (SUBSTRING(wdataoficialiniciolcalculo FROM 6 FOR 2)) AS INTEGER)) THEN
    wmesesdepreciados = wmesesdepreciados + 1;

  --IF (prmesesdepreciadosoutrataxa > 0) THEN
  --wmesesdepreciados = wmesesdepreciados + prmesesdepreciadosoutrataxa;

  prmesesdepreciados = wmesesdepreciados;

  IF ((((wvaloraquisicao IS NULL) OR (wvaloraquisicao <= 0))) AND (UPPER(wdepmesbaixa) = 'FALSE')) THEN
     BEGIN
       IF ( prtaxadepreciacaoanual <> 0) THEN
         BEGIN
           wtotalmesesdepreciacao = ((100 / prtaxadepreciacaoanual) * 12);
           wvalordepreciacaomensal = (prvaloraquisicao / wtotalmesesdepreciacao);
         END
       ELSE
         BEGIN
           wtotalmesesdepreciacao = wmesesdepreciados;
           wvalordepreciacaomensal= 0;
         END

       --#alt:19501 - Se o bem ja foi totalmente baixado então não deve possuir depreciação acumulada anterior e nem depreciação no período, quando consultado em um período após a baixa total. Ana - 21/09/2017
       IF ((wvalorbaixa >= wvaloraquisicaooriginal) AND (wvalorbaixa <> wvalorbaixaper) AND (wvalorbaixaper = 0)) THEN
         BEGIN
           prdepreciacaoacumuladaanterior = 0;
           wdepreciacaoacumuladaatual = wvaloraquisicao;
           wdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatual;
         END
       ELSE
         BEGIN
           IF ((wvalordepreciacaodiaria > 0) AND (wdatainicialoficial <= :wdataaquisicao))  THEN
             BEGIN
               wdepreciacaoacumuladaatual     = (wvalordepreciacaodiaria + wvalordepreciacaomensal + wdepreciacaoacumuladaatual);
               wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual * prvlrmoeda);
             END
           ELSE
             BEGIN
               wdepreciacaoacumuladaatual     = (wvalordepreciacaomensal + wdepreciacaoacumuladaatual);
               wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual * prvlrmoeda);
             END

           IF (wvalorbaixaper > 0) THEN
             BEGIN
               prdatabaixa  = wdatabaixa;
               prvalorbaixa = wvalorbaixaper;
               wdepreciacaoacumuladaatual     = (wdepreciacaoacumuladaatual - wvalordepreciacaomensal);
               wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual * prvlrmoeda);
               prdepreciacaoacumuladaanterior = wdepreciacaoacumuladaatual;

               wvalorcorrigidoanterior  = (wvaloraquisicao + wvalorbaixaper);
               prvalorcorrigidoanterior = wvalorcorrigidoanterior;

               wvalorcorrigidoanteriormoeda  = (wvaloraquisicao + wvalorbaixaper) / prvlrmoeda;
               prvalorcorrigidoanteriormoeda = wvalorcorrigidoanteriormoeda;
             END
           ELSE
             prdepreciacaoacumuladaanterior  = wdepreciacaoacumuladaatual - wvalordepreciacaomensal;
         END

       prtotalmesesdepreciacao         = wtotalmesesdepreciacao;
       prdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual;
       prdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatualmoed;
       prcompensacaobaixaperanterior = wdepreciacaoacumuladaatual;

       IF ((prdepreciacaoacumuladaanterior + wtotalmesesdepreciacao) > wvaloraquisicao) THEN
         BEGIN
           IF (prdepreciacaoacumuladaanterior < wvaloraquisicao) THEN
             BEGIN
               wtotalmesesdepreciacao = wvaloraquisicao - prdepreciacaoacumuladaanterior;
               prdepreciacaoacumuladaatual = prdepreciacaoacumuladaanterior + wtotalmesesdepreciacao;
             END
           ELSE
             BEGIN
               wtotalmesesdepreciacao = 0;
               --#alt:19501 - Não deve assumir o valor da aquisição, pois mesmo que o bem ja tenha sido totalmente baixado ainda há como depreciar o valor acumulado anterior. Ana - 21/09/2017
               --prdepreciacaoacumuladaatual = wvaloraquisicao;
             END
           prdepreciacaoperiodo = wtotalmesesdepreciacao;
         END
       IF ((WVALORBAIXAPER > 0) AND (WVALORBAIXA >= WVALORAQUISICAOORIGINAL)) THEN
         BEGIN
          PRCOMPENSACAOBAIXAPERANTERIOR = PRCOMPENSACAOBAIXAPERANTERIOR + PRVALORRESIDUAL;
          prdepreciacaoperiodo = prdepreciacaoperiodo + PRVALORRESIDUAL;
         END
       prdepreciacaoperiodomoeda = prdepreciacaoperiodo * prvlrmoeda;
       prdepreciacaoacumuladaatualmoed = prdepreciacaoacumuladaatual * prvlrmoeda;
       prvalorbaixareal = wvalorbaixa; --Valor total baixado deve levar aqui tambem. Machado - 11/02/2019
       SUSPEND;
       EXIT;
     END

  IF (prtipo = 2) THEN
    BEGIN
      --#alt:85169. Ana - 20/06/2018
      wvaloraquisicaoaux       = wvaloraquisicao;
      IF ((wvalorbaixaper > 0) AND (wvalorbaixa > 0)) THEN
        BEGIN
          wvaloraquisicao          = wvalorbaixa;
          --prvaloraquisicaooriginal = wvalorbaixa;
        END
      --#alt:85169. fim
    END

  -- Depreciação diária (Início)
  --#alt:19501 - Alterada verificação da variável "wNumDias". Ana - 24/10/2017
  --#alt:18200 - Não estava fazendo a depreciação diária quando havia uma baixa no mesmo mês da aquisição do bem. Ana - 03/05/2017
  IF ((UPPER(wdepdia) = 'TRUE') AND (wnumdias <= 2) AND (wdepdiadata < 2) AND
      (((EXTRACT(DAY FROM wdatainiciocalc) = 1) AND (wdatainiciocalc BETWEEN prdatainicial AND prdatafinal)) OR
       ((wdatabaixa BETWEEN prdatainicial AND prdatafinal) AND (DATEDIFF(MONTH,:wdataorigaquisicao,:wdatabaixa) <> 0) and (prdepdiabaixa <> 'TRUE')))) THEN
    wdepdia = 'FALSE';

  IF (UPPER(wdepdia) = 'TRUE') THEN
    BEGIN
      --#alt:18200 - Adicionei a verificação da diferença de meses da baixa para a aquisição do bem, pois não estava fazendo a depreciação diária corretamente
      --             quando havia uma baixa no mesmo mês da aquisição do bem. Ana - 03/05/2017
      IF ((wdatabaixa BETWEEN prdatainicial AND prdatafinal) AND (DATEDIFF(MONTH,:wdataorigaquisicao,:wdatabaixa) <> 0)) THEN
        BEGIN
          IF (wvaloraquisicao <= 0) THEN
            wdepdiasadepreciar = EXTRACT(DAY FROM wdatabaixa);
          ELSE
            wdepdiasadepreciar = EXTRACT(DAY FROM wdatabaixa) -1;
        END
      ELSE
        BEGIN
          -- Total de meses para a depreciação
          IF (prtaxadepreciacaoanual >= 0.1) THEN
            wtotalmesesdepreciacao = ((100 / prtaxadepreciacaoanual) * 12);

          --#alt:19501 - Não estava considerando os dias a depreciar quando tem depreciação acumulada informada. Ana - 24/10/2017
          IF ((WTEMTRANSBEMREF <> 1) and ((wvaldepacumubem <> 0) AND (wtotalmesesdepreciacao <> 0))) THEN
            BEGIN
              wmesesdepdiaria = (wvaldepacumubem /(wvaloraquisicaooriginal / wtotalmesesdepreciacao));
              wverificamesinteiro = (TRUNC(wmesesdepdiaria));
              wdiasdepdiaria = (wmesesdepdiaria - wverificamesinteiro);
              IF (wdiasdepdiaria > 0) THEN
                BEGIN
                  --#alt:21342 - Quando a quantidade de dias depreciados for igual a 0.01 significa que há um valor de deprecição diária mas não fecha em um dia completo.
                  --             para isso truncamos o valor em 0.04 que já equivale a um dia para conseguir fazer os calculos. Ana - 09/11/2017
                  IF (wdiasdepdiaria < 0.04) THEN
                    wdiasdepdiaria = 0.04;

                  wmes = (ABS((TRUNC((((wmesesdepdiaria)/12) - TRUNC((wmesesdepdiaria)/12)) * 12)-12)+1));
                  wano = (EXTRACT(YEAR FROM wdatainiciocalc));
                  wano = (wano - TRUNC(wverificamesinteiro/12));

                  --#alt:21342 - Tenho que considerar a quantidade de dia de cada mês e não deixar fixo 30 dias. Ana - 13/11/2017
                  SELECT ULTDIA FROM ULTIMO_DIA_MES(:wmes, :wano)
                  INTO :wUltimoDiaDoMes;
                  IF (wUltimoDiaDoMes > 0) THEN
                    wdepdiasadepreciar = (TRUNC(wdiasdepdiaria * wUltimoDiaDoMes));

                  --#alt:21342 - Adicionei a verificação dos dias para não ocorrer erro na conversão. Ana - 09/11/2017
                  IF ((wdepdiasadepreciar > 0) AND (wano > 0) AND (wmes > 0) )THEN
                    wdatainiciocalcaux = (CAST(wano AS VARCHAR(4)) ||'-'|| CAST(wmes AS VARCHAR(2)) ||'-'|| CAST(wdepdiasadepreciar AS VARCHAR(2)));
                END
            END
          ELSE
            BEGIN
              wdepdiasadepreciar = EXTRACT(DAY FROM wdatainiciocalc);
              wdatainiciocalcaux = wdatainiciocalc;
            END

          -- Cálculo que retorna o último dia do mês
          IF (wnumdias = 2) THEN
            wUltimoDiaDoMes = EXTRACT(DAY FROM (wdatainiciocalcaux - EXTRACT(DAY FROM wdatainiciocalcaux) +
                                                32 - EXTRACT(DAY FROM wdatainiciocalcaux - EXTRACT(DAY FROM wdatainiciocalcaux) + 32)));
          ELSE
            wUltimoDiaDoMes = 30;

          IF (wvaldepacumubem = 0) THEN
            wdepdiasadepreciar = (wultimodiadomes + 1) - wdepdiasadepreciar;
          ELSE
            BEGIN
              --#alt:18204 - Quando o mes tinha 31 dias estava desconciderando o ultimo dia para depreciar. Ana - 28/04/2017
                wdepdiasadepreciar = (wUltimoDiaDoMes) - wdepdiasadepreciar;
            END
          -- Caso a opção Dia seguinte a aquisição esteja selecionada preciso diminuir um dia no
          -- número de dias a depreciar, pois a wdepdiasadepreciar veio calculada conforme
          -- a data de aquisição
          IF (wdepdiadata = 2) THEN
            wdepdiasadepreciar = wdepdiasadepreciar - 1;
          IF (wdepdiasadepreciar < 0) THEN
            wdepdiasadepreciar = 0;
        END
    END

  -- Total de meses para a depreciação
  IF (prtaxadepreciacaoanual >= 0.1) THEN
    wtotalmesesdepreciacao = ((100 / prtaxadepreciacaoanual) * 12);
  ELSE
    BEGIN
      prvalorcorrigidoanterior      = (wvaloraquisicao  + (wvalorbaixaper) + PRVALORRESIDUAL);
      prvalorcorrigidoanteriormoeda = ((wvaloraquisicao + (wvalorbaixaper) + PRVALORRESIDUAL) / prvlrmoeda);

      IF ((prvalorcorrigidoanterior > prvaloraquisicaooriginal) OR (UPPER(wdepmesbaixa) = 'TRUE') ) THEN
        BEGIN
          prvalorcorrigidoanterior      = (wvaloraquisicao + PRVALORRESIDUAL);
          prvalorcorrigidoanteriormoeda = (wvaloraquisicao + PRVALORRESIDUAL) / prvlrmoeda;
        END

      IF (prvalorcorrigidoanterior > 0) THEN
        wvalorresidualcontabil         = (((prvalorcorrigidoanterior + prcorrecaoperiodo) - wvalorbaixaper - PRVALORRESIDUAL) - wdepreciacaoacumuladaatual);
      ELSE
        wvalorresidualcontabil         = (wvaloraquisicao - wdepreciacaoacumuladaatual);
      prvalorresidualcontabil      = wvalorresidualcontabil;
      wvalorresidualcontabilmoeda  = wvalorresidualcontabil / prvlrmoeda;
      prvalorresidualcontabilmoeda = wvalorresidualcontabilmoeda;

      prdatataxadepreciacao         = wdataultimoitemdep;
      prvalorbaixa                  = wvalorbaixaper;
      prvalorbaixareal              = wvalorbaixa;
      prvalormoeda                  = prvlrmoeda;
      prdatabaixa                   = wdatabaixa;

      wvaloraquisicaomoeda = (wvaloraquisicao / prvlrmoeda);
      prvaloraquisicaomoeda = wvaloraquisicaomoeda;

       IF (prtaxadepanual < 0.1) THEN
         prdepreciacaoacumuladaatual = prvaloracumuladoanterior;

      IF ((WVALORBAIXAPER > 0) AND (WVALORBAIXA >= WVALORAQUISICAOORIGINAL)) THEN
         BEGIN
          PRCOMPENSACAOBAIXAPERANTERIOR = PRCOMPENSACAOBAIXAPERANTERIOR + PRVALORRESIDUAL;
          PRDEPRECIACAOPERIODO = PRDEPRECIACAOPERIODO + PRVALORRESIDUAL;
         END

      prtotalmesesdepreciacao= wmesesdepreciados + 1;
      SUSPEND;
      EXIT;
    END

  IF (wdatainiciocalc IS NOT NULL) THEN
    wdataoficialiniciolcalculo = wdatainiciocalc;
  ELSE
    wdataoficialiniciolcalculo =  wdataaquisicao;

  IF (wvaloraquisicao = 0) THEN
     EXIT;

  -- Joga para variável o número de meses que já foi depreciado em outro sistema
  IF (prmesesdepreciadosoutrataxa > 0) THEN
    wmesesdepacumubem = prmesesdepreciadosoutrataxa;
  ELSE IF (wvaldepacumubem > 0) THEN
    wmesesdepacumubem = (wvaldepacumubem / ( wvaloraquisicaooriginal / wtotalmesesdepreciacao ));

  wdatatotalmeses       = addmonth(wdataoficialiniciolcalculo, wtotalmesesdepreciacao-wmesesdepacumubem);
  if ((EXTRACT(DAY FROM wdatainiciocalc) <> 1) or (wdepdiadata = 2)) then
    wdatatotalmesesdepdia = addmonth(wdatatotalmeses, 1);
  else
    wdatatotalmesesdepdia = wdatatotalmeses;
  wdatatotalmeses       = SUBSTRING(CAST(wdatatotalmeses AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                          SUBSTRING(CAST(wdatatotalmeses AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
  -- Transforma no primeiro dia do mês
  wdataaquisicao = SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                   SUBSTRING(CAST(wdataaquisicao AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';

  wdiferencameses = DATEDIFF(MONTH,:wdatatotalmeses,:wdataatual);
  IF (wdiferencameses < 0) THEN
    wdiferencameses = 0;
  -- A rotina "datediff" não conta se as duas data estão no mesmo mês, por isso verifico se a referência da data atual
  -- é a mesma da data de aquisição para somar 1
  IF (CAST((SUBSTRING(wdataatual FROM 1 FOR 4)) || (SUBSTRING(wdataatual FROM 6 FOR 2)) AS INTEGER) >=
      CAST((SUBSTRING(wdataaquisicao FROM 1 FOR 4)) || (SUBSTRING(wdataaquisicao FROM 6 FOR 2)) AS INTEGER)) THEN
    wdiferencameses = wdiferencameses + 1;

  IF (wdiferencameses-1 > 0) THEN
    BEGIN
     IF (wdepmensal = 'FALSE') THEN
       BEGIN
         wdataatual = addmonth(:wdatatotalmeses,1);
         wmes       = CAST(SUBSTRING(CAST(wdataatual AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
         wano       = CAST(SUBSTRING(CAST(wdataatual AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
         wdataatual = CAST(wmes||'-01-'||wano AS DATE);
       END
     ELSE
       wdataatual = wdatatotalmeses;
    END

  IF ((wdepmensal = 'FALSE') AND
      (CAST(EXTRACT(YEAR FROM :prdatainicial) || EXTRACT(MONTH FROM :prdatainicial) AS INTEGER) = CAST(EXTRACT(YEAR FROM wdataorigaquisicao) || EXTRACT(MONTH FROM wdataorigaquisicao) AS INTEGER))) THEN
    BEGIN
      prdatafinal = addmonth(:prdatafinal,-1);
      wmes       = CAST(SUBSTRING(CAST(prdatafinal AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
      wano       = CAST(SUBSTRING(CAST(prdatafinal AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
      prdatafinal = CAST(wmes||'-01-'||wano AS DATE);
    END

  IF ((prtipo = 2) AND (wdatabaixa IS NOT NULL)) THEN
    BEGIN
      wdataatual  = wdatabaixa;
      prdatafinal = wdatabaixa;
    END

   IF ((wdatafimcalc IS NOT NULL) AND (wdatafimcalc < prdatafinal)) THEN
     BEGIN
       wdataatual  = wdatafimcalc;
       prdatafinal = wdatafimcalc;
     END

  --#alt:19501 - Devo considerar a depreciação diária no mês da aquisição, que não são considerados como mês cheio e por isso estão informados nas casas após
  --             a vírgula. Esta depreciação diária era desconsiderada para os cálculos. Ana - 18/10/2017
  IF (wdepdia = 'TRUE') THEN
    BEGIN
      wverificamesinteiro = TRUNC(wvaldepacumubem /(wvaloraquisicaooriginal / wtotalmesesdepreciacao));
      wdiasdepdiaria = ((wvaldepacumubem /(wvaloraquisicaooriginal / wtotalmesesdepreciacao)) - wverificamesinteiro);
    END
  ELSE
    BEGIN
      wverificamesinteiro = TRUNC(wdepreciacaoacumuladaatual/(wvaloraquisicaooriginal / wtotalmesesdepreciacao));
      --#alt:92279. Estava calculando uma depreciação a mais em cima do valor da baixa por causa deste valor. Não lembramos o motivo de calcular a depreciação diária sem ela estar habilitada no bem. Ana - 21/11/2018
      --wdiasdepdiaria = ((wdepreciacaoacumuladaatual /(wvaloraquisicaooriginal / wtotalmesesdepreciacao)) - wverificamesinteiro);
      wdiasdepdiaria = 0;
    END

  --#alt:19501 - Não deve considerar um mês a mais na depreciação diária. E verifico o parâmetro, pois a variável sofre alteração. Ana - 23/10/2017
  IF (prdepdia = 'FALSE' or (EXTRACT(DAY FROM wdatainiciocalc) = 1 AND (wdepdiadata < 2))) THEN
    BEGIN
      IF ((wdepmensal = 'TRUE') AND (wvaldepacumubem <> 0) AND (wdiasdepdiaria > 0)) THEN
        wmesesdepreciados = wmesesdepreciados + 1;
      ELSE
      --#alt:19501. Apenas somando este mês altera bastante os cálculos da depreciação. Para somar este mês só em situações bem específicas. Ana - 18/10/2017
      -- A rotina "datediff" não conta se as duas data estão no mesmo mês, por isso verifico se a referência da data atual
      -- é a mesma da data de aquisição para somar 1
      --Cálculo depreciação #151814 #151816 - Adicionado quando a data atual era maior que a data de aquisição
      IF (((CAST((SUBSTRING(wdataatual FROM 1 FOR 4)) || (SUBSTRING(wdataatual FROM 6 FOR 2)) AS INTEGER) >
               CAST((SUBSTRING(wdataoficialiniciolcalculo FROM 1 FOR 4)) || (SUBSTRING(wdataoficialiniciolcalculo FROM 6 FOR 2)) AS INTEGER))) OR
         ((CAST((SUBSTRING(wdataatual FROM 1 FOR 4)) || (SUBSTRING(wdataatual FROM 6 FOR 2)) AS INTEGER) =
           CAST((SUBSTRING(wdataoficialiniciolcalculo FROM 1 FOR 4)) || (SUBSTRING(wdataoficialiniciolcalculo FROM 6 FOR 2)) AS INTEGER)) AND
              ((wvaldepacumubem <> 0) OR (wdepmensal = 'TRUE')))  or
               (CAST((SUBSTRING(wdataatual FROM 1 FOR 4)) || (SUBSTRING(wdataatual FROM 6 FOR 2)) AS INTEGER) >
                CAST((SUBSTRING(wdataaquisicao FROM 1 FOR 4)) || (SUBSTRING(wdataaquisicao FROM 6 FOR 2)) AS INTEGER))) THEN
        begin
        wmesesdepreciados = wmesesdepreciados + 1;
        end
    END

  IF ((wdepmensal = 'FALSE') AND
     ((EXTRACT(YEAR FROM :prdatainicial) > EXTRACT(YEAR FROM wdataorigaquisicao)) OR
      ((EXTRACT(YEAR FROM :prdatainicial) = EXTRACT(YEAR FROM wdataorigaquisicao)) AND (EXTRACT(MONTH FROM :prdatainicial) >= EXTRACT(MONTH FROM wdataorigaquisicao)))) AND
      --#alt:13024 - Machado - 07/02/2020 - Quando a depreciação vem de outro sistema por exemplo ele não deprecia no primeiro mes.
      ((EXTRACT(YEAR FROM :PRDATAAQUISICAO) = EXTRACT(YEAR FROM PRDATAINICIOCALC)) AND (EXTRACT(MONTH FROM :PRDATAAQUISICAO) >= EXTRACT(MONTH FROM PRDATAINICIOCALC)))) THEN
    wmesesdepreciados = wmesesdepreciados - 1;

  if ((CAST((SUBSTRING(prdatainiciocalc FROM 1 FOR 4)) || (SUBSTRING(prdatainiciocalc FROM 6 FOR 2)) AS INTEGER) =
   CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER))
   and (wdepmensal = 'FALSE')) then
   wmesesdepreciados = 0;

  if ((CAST((SUBSTRING(prdatainiciocalc FROM 1 FOR 4)) || (SUBSTRING(prdatainiciocalc FROM 6 FOR 2)) AS INTEGER) =
   CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER))
   and (wmesesdepreciados > 1)) then
     wmesesdepreciados = wmesesdepreciados - 1;

  -- Adiciona no total de meses depreciados o valor já depreciado de outro sistema
  IF ((wvaldepacumubem > 0) AND (wmesesdepreciados >=0)) THEN
     --#alt:18200 - Alterado para pegar o valor original da aquisição e não o valor ja corrigido. Ana - 03/05/2017
     --wmesesdepreciados = wmesesdepreciados + (wvaldepacumubem / (wvaloraquisicao / wtotalmesesdepreciacao));
     wmesesdepreciados = wmesesdepreciados + (wvaldepacumubem / (wvaloraquisicaooriginal / wtotalmesesdepreciacao));

  --#alt:19501 - Antes os cálculos da depreciação do período estavam incorretos quando o bem possuia baixa parcial, então o total de meses depreciados sempre foi suficiente. Porém, com
  --             estas alterações, a quantidade de meses depreciados pode ser com um mês a mais para fazer o cálculo de compensação de baixa do período anterior corretamente. Ana - 19/10/2017
  IF (((wmesesdepreciados > (wtotalmesesdepreciacao + 1)) AND (wdepmesbaixa = 'FALSE')) OR
      ((wmesesdepreciados > (wtotalmesesdepreciacao))     AND (wdepmesbaixa = 'TRUE')) ) THEN
     wmesesdepreciados = wtotalmesesdepreciacao;

  --#alt:19501 - Adicionada a atribuição aqui, pois preciso dela para controle da variável wdepdiafinal. Ana - 17/10/2017
  -- Meses à depreciar
  wmesesdepreciar      = (wtotalmesesdepreciacao - wmesesdepreciados);

  -- Total de meses da diferença do periodo de depreciação
  wmes = CAST(SUBSTRING(CAST(wdatatotalmesesdepdia AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
  wano = CAST(SUBSTRING(CAST(wdatatotalmesesdepdia AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
  -- Cálculo que retorna o último dia do mês
  wultimodiadomes = EXTRACT(DAY FROM (wdatatotalmesesdepdia - EXTRACT(DAY FROM wdatatotalmesesdepdia) +
                                      32 - EXTRACT(DAY FROM wdatatotalmesesdepdia - EXTRACT(DAY FROM wdatatotalmesesdepdia) + 32)));
  wdatatotalmesesultimodia = CAST(wmes||'-'||wultimodiadomes||'-'||wano AS DATE);
  IF ((:prdatafinal > wdatatotalmesesultimodia) AND (wdepdia = 'TRUE')) THEN
    BEGIN
      -- Caso seja o último mês para depreciar
      IF (wmesesdepreciar = 0) THEN
        wdepdiafinal = 'TRUE';

      if ((extract(day from WDATAINICIOCALC) <> 1)  or (wdepdiadata = 2)) then
        wdatatotalmesesultimodia = addmonth(wdatatotalmesesultimodia, 1);
      wdatatotalmesesultimodia = SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 1 FOR 4) || '-' ||
                                 SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 6 FOR 2) || '-' || '01';
    END
  ELSE
    BEGIN
      IF (wmesesdepreciar = 0) THEN
        wdepdiafinal = 'TRUE';
    END

  IF (:prdatafinal > wdatatotalmeses) THEN
     prdatafinal = wdatatotalmeses;

  IF (:prdatainicial < :wdataoficialiniciolcalculo) THEN
      prdatainicial = wdataoficialiniciolcalculo;

  wtotalmesesdoperiodo = DATEDIFF(MONTH,:prdatainicial,:prdatafinal);
  IF (wtotalmesesdoperiodo < 0) THEN
    wtotalmesesdoperiodo = 0;

  -- A rotina "datediff" não conta se as duas data estão no mesmo mês, por isso verifico se a referência da data atual
  -- é a mesma da data de aquisição para somar 1

  if (((wtaxaant <> prtaxadepreciacaoanual) and wtaxaant <> 0) or (prcont = 2)) then
    prmesdepreciacaonovataxa = wmesesdepreciar + 1;

  if ((PRCONT > 0) and (PRMESDEPRECIACAONOVATAXA > 0)) then
    begin
      SELECT BDNOVADATA FROM add_meses(:prdatainiciocalc,:prmesdepreciacaonovataxa) INTO wdatatotalmeses;
      prdatafinal = wdatatotalmeses;
    end

  if ((((WTAXAANT <> PRTAXADEPRECIACAOANUAL)
      and (wvaloraquisicao > wdepreciacaoacumuladaatual)
      )) and
      ((cast((substring(PRDATAINICIAL from 1 for 4)) ||(substring(PRDATAINICIAL from 6 for 2)) as integer) < cast((substring(PRDATAFINAL from 1 for 4)) ||(substring(PRDATAFINAL from 6 for 2)) as integer)))) then
    WTOTALMESESDOPERIODO = WTOTALMESESDOPERIODO + 1;

  IF (CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER) =
      CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER) AND ((wmesesdepreciar <> -1) or ((wmesesdepreciar = -1) and (prValorAcumuladoAnterior < PRVALORAQUISICAOORIGINAL)))) THEN
    wtotalmesesdoperiodo = wtotalmesesdoperiodo + 1;

  --#alt:18204 - Quando a data for igual a data origem de aquisição então não deve ser calculado. Ana - 28/04/2017
  IF ((wvaldepacumubem > 0) AND (prdatainicial </*=*/ wdataorigaquisicao)) THEN
    wtotalmesesdoperiodo = wtotalmesesdoperiodo -1;

  IF (((wtotalmesesdoperiodo > 0) AND
       ((CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER) >
         CAST((SUBSTRING(wdatatotalmeses FROM 1 FOR 4)) || (SUBSTRING(wdatatotalmeses FROM 6 FOR 2)) AS INTEGER)) OR
        ((wdepmensal = 'TRUE') AND
         (CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER) =
          CAST((SUBSTRING(wdatatotalmeses FROM 1 FOR 4)) || (SUBSTRING(wdatatotalmeses FROM 6 FOR 2)) AS INTEGER))))) OR
      (wtotalmesesdoperiodo < 0) AND (wtaxaant = prtaxadepreciacaoanual) ) THEN
    wtotalmesesdoperiodo = 0;

  if ((wtotalmesesdoperiodo > 0) and
  ((CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER) <>
  CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER))) and
  (wDEPMENSAL = 'TRUE') and prcont = 0) then
    wtotalmesesdoperiodo = 0;

  if ((wtotalmesesdoperiodo = 0) and
  ((CAST((SUBSTRING(prdatainicial FROM 1 FOR 4)) || (SUBSTRING(prdatainicial FROM 6 FOR 2)) AS INTEGER) =
  CAST((SUBSTRING(prdatafinal FROM 1 FOR 4)) || (SUBSTRING(prdatafinal FROM 6 FOR 2)) AS INTEGER))) and
  (wDEPMENSAL = 'TRUE') AND (wmesesdepreciados <= wtotalmesesdepreciacao)) then
    wtotalmesesdoperiodo = wtotalmesesdoperiodo + 1;

  wvaloraquisicaomoeda = wvaloraquisicao / prvlrmoeda;

  --#alt:85169. O valor da aquisição deve ser o original para calcular a depreciação correta e não influenciar nos outro valores. Ana- 20/06/2018
  --wvalordepreciacaomensal = (wvaloraquisicao / wtotalmesesdepreciacao);

  if ((WVALORAQUISICAO <> WVALDEPACUMUBEM) and
      (PRMESDEPRECIACAONOVATAXA <> 0) and
      (prvaloracumuladoanterior  > 0)) then
  begin
    if (((WVALORAQUISICAO <> WVALDEPACUMUBEM) and
        (PRMESDEPRECIACAONOVATAXA <> 0)) and
        (WVALDEPACUMUBEM < WVALORAQUISICAO)) then
      begin
        WVALORAQUISICAO = WVALORAQUISICAO - WVALDEPACUMUBEM;
        wAquisicaoReduziuValorAcumulado = 1;
      end
    else
      prmesdepreciacaonovataxa = wtotalmesesdepreciacao;
  IF (prtipo = 2) THEN
        wvalordepreciacaomensal = (wvaloraquisicaoaux / prmesdepreciacaonovataxa);
      ELSE
        wvalordepreciacaomensal = (wvaloraquisicao / prmesdepreciacaonovataxa);
    end
  ELSE
    BEGIN
      IF (prtipo = 2) THEN
    wvalordepreciacaomensal = (wvaloraquisicaoaux / wtotalmesesdepreciacao);
  ELSE
    wvalordepreciacaomensal = (wvaloraquisicao / wtotalmesesdepreciacao);
    END

  --#alt:19501 - Quando tenho depreciação acumulada anterior cadastrada devo considerar os meses pertinentes a essa depreciação, independente da depreciação diária. Ana - 17/10/2017
  IF ((wdepdia = 'TRUE' and ((extract(day from WDATAINICIOCALC) <> 1)  or (wdepdiadata = 2))) /*AND ((wvaldepacumubem = 0) AND (wvaldepacumubem = wdepreciacaoacumuladaatual))*/) THEN
    BEGIN
      -- Quer dizer que é o primeiro mês e esse mês não vai contar já que e parcial, o restante estara no último mês a depreciar
      wmesesdepreciar      = wmesesdepreciar + 1;
      wmesesdepreciados    = wmesesdepreciados - 1;
      wtotalmesesdoperiodo = wtotalmesesdoperiodo -1;
    END

  IF (wdepmensal = 'TRUE') THEN
    wdatatotalmeses = AddMonth(wdatatotalmeses, -1);

  --#alt:123529 - Carlos Machado - 21/08/2020 - Depreciação no dia da baixa
  if (prdepdiabaixa = 'TRUE' and wdatabaixa between prdatainicial and prdatafinal) then
    WDATADEPDIA_BAIXA_AUX = 1;
  else
    WDATADEPDIA_BAIXA_AUX = 0;

  IF (wdepdiasadepreciar > 0 or WDATADEPDIA_BAIXA_AUX = 1) THEN
    BEGIN
      IF (wnumdias = 2) THEN
        BEGIN
          -- Cálculo que retorna o último dia do mês
          if (WDATADEPDIA_BAIXA_AUX = 1) then
            SELECT ULTDIA FROM ULTIMO_DIA_MES(EXTRACT(MONTH FROM :prdatafinal), EXTRACT(YEAR FROM :prdatafinal)) INTO :wUltimoDiaDoMes;
          ELSE
          IF (wdatabaixa BETWEEN prdatainicial AND prdatafinal) THEN
            wUltimoDiaDoMes = EXTRACT(DAY FROM (wdatabaixa - EXTRACT(DAY FROM wdatabaixa) +
                                                32 - EXTRACT(DAY FROM wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32)));
          ELSE
            wUltimoDiaDoMes = EXTRACT(DAY FROM (wdatainiciocalc - EXTRACT(DAY FROM wdatainiciocalc) +
                                                32 - EXTRACT(DAY FROM wdatainiciocalc - EXTRACT(DAY FROM wdatainiciocalc) + 32)));

          --#alt:101130. Deve arredondar todos os cálculos para não ter diferença entre o contábil e o patrimônio. Ana - 05/06/2019
          wvalordepreciacaodiaria = CAST((prvaloraquisicaooriginal - PRVALORRESIDUAL) AS NUMERIC(15,2));
          wvalordepreciacaodiaria = CAST((wvalordepreciacaodiaria / wtotalmesesdepreciacao) AS NUMERIC(15,2));
          wvalordepreciacaodiaria = CAST((wvalordepreciacaodiaria / wultimodiadomes) AS NUMERIC(15,2));
          if (WDATADEPDIA_BAIXA_AUX = 1) then
            begin
              wtotalmesesdoperiodo = 0;
              wDia = wUltimoDiaDoMes - EXTRACT(DAY FROM wdatainiciocalc) + 1;
              if (wdepdiadata = 2) then
                wDia = wDia - 1;
              if (wDia < 0) then
                wDia = 0;
              prcompensacaobaixaperanterior = 0;
              if (wdatainiciocalc not between prdatainicial and prdatafinal) then
                prcompensacaobaixaperanterior = (wvalorbaixaper / wtotalmesesdepreciacao) * (wmesesdepreciados + (CAST(wDia AS FLOAT) / wUltimoDiaDoMes));
              wvalordepdia_baixa_aux = 0;
              wvalordepreciacaodiariabaixa = 0;

              wdatadepdia_baixa_aux = 1;
              IF (wdatainicialoficial < wdataoficialiniciolcalculo) THEN
                  wdatadepdia_baixa_aux = EXTRACT(DAY FROM wdataoficialiniciolcalculo);
              WDATADEPDIA_BAIXA_AUX2 = wdatadepdia_baixa_aux;

              FOR select bddatbai, COALESCE(SUM(bdvalbai), 0) AS totalbaixa from (
                SELECT extract(day from bddatbai)+1 AS bddatbai, bdvalbai
                FROM empresas_tbai
                WHERE (bdcodemp = :prcodemp) AND
                      (bdcodbem = :prcodbem) AND
                      (bdcontabilizacao = :prcontabilizacao) AND
                      bddatbai BETWEEN :prdatainicial AND :prdatafinal
                UNION ALL
                SELECT :wUltimoDiaDoMes+1, 0 FROM RDB$DATABASE)
              GROUP BY bddatbai ORDER BY bddatbai INTO :WDATADEPDIA_BAIXA, :WVALORDEPDIA_BAIXA DO
              BEGIN
                prcompensacaobaixaperanterior = prcompensacaobaixaperanterior + ((WVALORDEPDIA_BAIXA / wtotalmesesdepreciacao) * (CAST((WDATADEPDIA_BAIXA - WDATADEPDIA_BAIXA_AUX2) AS FLOAT) / wUltimoDiaDoMes));

                wvalordepdia_baixa_aux = wvalordepdia_baixa_aux + wvalordepdia_baixa;

                if (WDATADEPDIA_BAIXA > 1) then
                  wvalordepreciacaodiariabaixa = wvalordepreciacaodiariabaixa
                  + CAST(((WDATADEPDIA_BAIXA - wdatadepdia_baixa_aux)) * wvalordepreciacaodiaria AS NUMERIC(15,2));
                wvalordepreciacaodiaria = CAST((prvaloraquisicaooriginal - PRVALORRESIDUAL - wvalordepdia_baixa_aux) AS NUMERIC(15,2));
                wvalordepreciacaodiaria = CAST((wvalordepreciacaodiaria / wtotalmesesdepreciacao) AS NUMERIC(15,2));
                wvalordepreciacaodiaria = CAST((wvalordepreciacaodiaria / wUltimoDiaDoMes) AS NUMERIC(15,2));
                wdatadepdia_baixa_aux = WDATADEPDIA_BAIXA;
              END
              wvalordepreciacaodiaria = wvalordepreciacaodiariabaixa;
              wvalordepreciacaodiariabaixa = 0;
            end
           else
            begin
              wvalordepreciacaodiaria = CAST((wvalordepreciacaodiaria * wdepdiasadepreciar) AS NUMERIC(15,2));
              --wvalordepreciacaodiaria = ((prvaloraquisicaooriginal - PRVALORRESIDUAL) / wtotalmesesdepreciacao) / wultimodiadomes * wdepdiasadepreciar;
    
              wvalordepreciacaodiariabaixa = (wvalordepreciacaomensal / wultimodiadomes) * (wultimodiadomes - wdepdiasadepreciar);
              wDia = EXTRACT(DAY FROM (wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32 -
                                       EXTRACT(DAY FROM wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32))) - EXTRACT(DAY FROM wdatainiciocalc);
              prcompensacaobaixaperanterior = (wvalorbaixaper / wtotalmesesdepreciacao) * (wmesesdepreciados -1 + (CAST(wdepdiasadepreciar + wDia AS FLOAT) / wUltimoDiaDoMes));
            end
        END
      ELSE
        BEGIN
           wvalordepreciacaodiaria = CAST((prvaloraquisicaooriginal - PRVALORRESIDUAL) AS NUMERIC(15,2));
           wvalordepreciacaodiaria = CAST((wvalordepreciacaodiaria / wtotalmesesdepreciacao) AS NUMERIC(15,2));
           wvalordepreciacaodiaria = CAST((wvalordepreciacaodiaria / 30) AS NUMERIC(15,2));

           if (WDATADEPDIA_BAIXA_AUX = 1) then
            begin
              wtotalmesesdoperiodo = 0;
              wDia = 30 - EXTRACT(DAY FROM wdatainiciocalc) + 1;
              if (wdepdiadata = 2) then
                wDia = wDia - 1;
              if (wDia < 0) then
                wDia = 0;
              if (wdatainiciocalc not between prdatainicial and prdatafinal) then
                prcompensacaobaixaperanterior = (wvalorbaixaper / wtotalmesesdepreciacao) * (wmesesdepreciados + (CAST(wDia AS FLOAT) / 30));
              wvalordepdia_baixa_aux = 0;
              wvalordepreciacaodiariabaixa = 0;

              wdatadepdia_baixa_aux = 1;
              IF (wdatainicialoficial < wdataoficialiniciolcalculo) THEN
                  wdatadepdia_baixa_aux = EXTRACT(DAY FROM wdataoficialiniciolcalculo);
              WDATADEPDIA_BAIXA_AUX2 = wdatadepdia_baixa_aux;

              FOR select bddatbai, COALESCE(SUM(bdvalbai), 0) AS totalbaixa from (
                SELECT iif(extract(day from bddatbai)+1 > 30, 31, extract(day from bddatbai)+1) AS bddatbai, bdvalbai
                FROM empresas_tbai
                WHERE (bdcodemp = :prcodemp) AND
                      (bdcodbem = :prcodbem) AND
                      (bdcontabilizacao = :prcontabilizacao) AND
                      bddatbai BETWEEN :prdatainicial AND :prdatafinal
                UNION ALL
                SELECT 31, 0 FROM RDB$DATABASE)
              GROUP BY bddatbai ORDER BY bddatbai INTO :WDATADEPDIA_BAIXA, :WVALORDEPDIA_BAIXA DO
              BEGIN
                prcompensacaobaixaperanterior = prcompensacaobaixaperanterior + ((WVALORDEPDIA_BAIXA / wtotalmesesdepreciacao) * (CAST((WDATADEPDIA_BAIXA - WDATADEPDIA_BAIXA_AUX2) AS FLOAT) / 30));

                wvalordepdia_baixa_aux = wvalordepdia_baixa_aux + wvalordepdia_baixa;

                if (WDATADEPDIA_BAIXA > 1) then
                  wvalordepreciacaodiariabaixa = wvalordepreciacaodiariabaixa
                  + CAST(((WDATADEPDIA_BAIXA - wdatadepdia_baixa_aux)) * wvalordepreciacaodiaria AS NUMERIC(15,2));
                wvalordepreciacaodiaria = CAST((prvaloraquisicaooriginal - PRVALORRESIDUAL - wvalordepdia_baixa_aux) AS NUMERIC(15,2));
                wvalordepreciacaodiaria = CAST((wvalordepreciacaodiaria / wtotalmesesdepreciacao) AS NUMERIC(15,2));
                wvalordepreciacaodiaria = CAST((wvalordepreciacaodiaria / 30) AS NUMERIC(15,2));
                wdatadepdia_baixa_aux = WDATADEPDIA_BAIXA;
              END
              wvalordepreciacaodiaria = wvalordepreciacaodiariabaixa;
              wvalordepreciacaodiariabaixa = 0;
            end
           else
            begin
              wvalordepreciacaodiaria = CAST((wvalordepreciacaodiaria * wdepdiasadepreciar) AS NUMERIC(15,2));
              wvalordepreciacaodiariabaixa = (wvalordepreciacaomensal / 30) * (30 - wdepdiasadepreciar);

              wDia = EXTRACT(DAY FROM (wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32 -
                                       EXTRACT(DAY FROM wdatabaixa - EXTRACT(DAY FROM wdatabaixa) + 32))) - EXTRACT(DAY FROM wdatainiciocalc);
              prcompensacaobaixaperanterior = (wvalorbaixaper / wtotalmesesdepreciacao) * (wmesesdepreciados -1 + (CAST(wdepdiasadepreciar + wDia AS FLOAT) / 30));
            end
        END

      --#alt:101130. Passava o valor incorreto. Ana - 05/06/2019
      --prvalordepreciacaodiariafim = wvalordepreciacaodiariabaixa;
    END
  ELSE
    --#alt:19501 - Adicionei o valor pertinente a depreciação diária no mês da aquisição. Ana - 24/10/2017
    prcompensacaobaixaperanterior = (wvalorbaixaper / wtotalmesesdepreciacao) * ((wmesesdepreciados + wdiasdepdiaria) - IIF(wdepmesbaixa = 'TRUE', 0, 1));

  --#alt:18200 - Adicionei a verificação da diferença de meses da baixa para a aquisição do bem, pois não estava fazendo a depreciação diária corretamente
  --             quando havia uma baixa no mesmo mês da aquisição do bem. Ana - 03/05/2017
  IF ((wdatabaixa BETWEEN prdatainicial AND prdatafinal)  AND (DATEDIFF(MONTH,:wdataorigaquisicao,:wdatabaixa) <> 0))THEN
    BEGIN
      wdepreciacaoperiodo = (wvalordepreciacaodiaria + wvalordepreciacaodiariabaixa) + (wvalordepreciacaomensal * wtotalmesesdoperiodo);
      wdepreciacaoperiodomoeda = wdepreciacaoperiodo / prvlrmoeda;
    END
  --#alt:19501 - Quando for depreciação diária e tiver valor de depreciação acumulada anterior informada, deve ignorar qualquer cálculo feito anteriormente. Ana - 17/10/2017
  ELSE IF ((WTEMTRANSBEMREF = 1) or ((wdatainicialoficial <= :wdataaquisicao) AND
          (((wdepdia = 'TRUE') AND (wvaldepacumubem = 0) OR ((wdepdia = 'FALSE') AND (wvaldepacumubem <> 0))) AND
          (wvaldepacumubem = wdepreciacaoacumuladaatual)))) THEN
    BEGIN
      wdepreciacaoperiodo      = (wvalordepreciacaodiaria + wvalordepreciacaomensal * wtotalmesesdoperiodo);
      wdepreciacaoperiodomoeda = wdepreciacaoperiodo / prvlrmoeda;
    END
  ELSE
  IF ((wdepdia = 'TRUE' and (extract(day from WDATAINICIOCALC) <> 1)  or (wdepdiadata = 2))) THEN
    BEGIN
      wdepreciacaoperiodo      = wvalordepreciacaomensal * (wtotalmesesdoperiodo +1);
      wdepreciacaoperiodomoeda = wdepreciacaoperiodo / prvlrmoeda;
    END
  ELSE
    BEGIN
      wdepreciacaoperiodo      = wvalordepreciacaomensal * wtotalmesesdoperiodo;
      wdepreciacaoperiodomoeda = wdepreciacaoperiodo / prvlrmoeda;
    END

  --#alt:19501 - Quando é informado um valor de depreciação acumulada anterior, deve ignorar o qualquer calculo feito anteriormente(depreciação diaria) e permanecer com o valor informado. Ana - 17/10/2017
  IF ((prvaloracumuladoanterior = 0) AND (wvaldepacumubem <> 0) AND (wvaldepacumubem = wdepreciacaoacumuladaatual)) THEN
    BEGIN
      wdepreciacaoacumuladaatual    = (cast(wdepreciacaoperiodo as numeric(15, 2)) + wdepreciacaoacumuladaatual);
      wdepreciacaoacumuladaanterior = (wvaldepacumubem);
    END
  ELSE
   IF ((wvalordepreciacaodiaria > 0) AND (wdatainicialoficial <= :wdataaquisicao))  THEN
     BEGIN
       wdepreciacaoacumuladaatual    = (wvalordepreciacaodiaria + wdepreciacaoacumuladaatual * prvlrmoeda);
       wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - cast(wdepreciacaoperiodo as numeric(15, 2)));
     END
   ELSE
     BEGIN
       wdepreciacaoacumuladaatual = cast(wdepreciacaoperiodo as numeric(15, 2)) + wdepreciacaoacumuladaatual;

       IF (wvalordepreciacaodiaria > 0) THEN
         wdepreciacaoacumuladaanterior = (wdepreciacaoacumuladaatual - cast(wdepreciacaoperiodo as numeric(15, 2)));
       ELSE
         BEGIN
          --#alt:19501 - Na depreciação diária devo considerar um mês a mais no total de meses do período. Ana - 25/10/2017
          IF (wdepdia = 'TRUE') THEN
            wdepreciacaoacumuladaanterior = wvalordepreciacaomensal * (wtotalmesesdoperiodo +1);
          ELSE
           wdepreciacaoacumuladaanterior = wvalordepreciacaomensal * wtotalmesesdoperiodo;
          wdepreciacaoacumuladaanterior = wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior;
         END
     END

  --#alt:18200 - Não precisa fazer esta verificação, pois o valor corrigido anterior sempre deve ser em relação ao valor da aquisição. Ana - 02/05/2017
  --IF (wdepreciacaoacumuladaanterior > 0) THEN
  wvalorcorrigidoanterior = wvaloraquisicao;

  IF (wdepreciacaoacumuladaanterior < 0) THEN
    wdepreciacaoacumuladaanterior = 0;

  --#alt:101130. Para calcular o resto ao final da depreciação, deve ser o valor original - a depreciação anterior. Ana - 05/06/2019
  prvalordepreciacaodiariafim = wvaloraquisicao - wdepreciacaoacumuladaanterior;

  --#alt:18200 - Só vai considerar a compensação da baixa do período anterior se tiver depreciação acumulada anterior ou se o mês da baixa não for o mesmo da aquisição.
  --             Deve ser o valor da aquisição original pois o valor da aquisição é diminuido conforme os valores das baixas. Ana - 04/05/2017
  IF ((wvalorbaixaper > 0) AND (wvalorbaixa < wvaloraquisicaooriginal) AND ((wdepreciacaoacumuladaanterior <> 0) OR (DATEDIFF(MONTH,:wdataorigaquisicao,:wdatabaixa) <> 0))) THEN
    wdepreciacaoacumuladaatual = wdepreciacaoacumuladaatual - prcompensacaobaixaperanterior;
  ELSE IF (wvalorbaixa = wvaloraquisicao) THEN
    prcompensacaobaixaperanterior = wdepreciacaoacumuladaatual;

   IF ((WVALORBAIXAPER > 0) AND (WVALORBAIXA >= WVALORAQUISICAOORIGINAL)) THEN
     BEGIN
      PRCOMPENSACAOBAIXAPERANTERIOR = PRCOMPENSACAOBAIXAPERANTERIOR + PRVALORRESIDUAL;
   --- #125405 Não subtrair valor residual na contar valor da depreciação do periodo  
      wdepreciacaoperiodo = wdepreciacaoperiodo + PRVALORRESIDUAL;
     END

  wdepreciacaoacumuladaatualmoed = (wvalordepreciacaodiaria + (wvalordepreciacaomensal * wmesesdepreciados)) / prvlrmoeda;
  wdepreciacaobaixamoeda         = (wvalorbaixa / wtotalmesesdepreciacao);
  wdepreciacaobaixamoeda         = (wdepreciacaobaixamoeda / prvlrmoeda);

  IF (prtipo = 2) THEN
    BEGIN
      prvalorcorrigidoanterior      = wvalorcorrigidoanterior;
      prvalorcorrigidoanteriormoeda = (wvalorcorrigidoanterior / prvlrmoeda);
    END
  ELSE
    BEGIN
      --#alt:18200 - Não estava calculando certo. Atribuia o valor da aquisição menos todas as baixas e somava todas as baixas aqui novamente, mas só deve somar as baixas que ja foram efetuadas. Ana - 02/05/2017
      /*prvalorcorrigidoanterior      = (wvalorcorrigidoanterior + wvalorbaixa);
      prvalorcorrigidoanteriormoeda = ((wvalorcorrigidoanterior + wvalorbaixa) / prvlrmoeda);  */
      prvalorcorrigidoanterior      = (wvalorcorrigidoanterior + (wvalorbaixaper) + PRVALORRESIDUAL);
      prvalorcorrigidoanteriormoeda = ((wvalorcorrigidoanterior + (wvalorbaixaper) + PRVALORRESIDUAL) / prvlrmoeda);

      --#alt:19501 - Quando é depreciação no mes da baixa, não deve considerar os valores de baixa no período para cálculo do valor corrigido anterior(Estes valores ja estão inclusos). Ana - 16/10/2017
      --#alt:18200 - Apenas se o valor for maior deve substituir. Ana - 02/05/2017
      IF ((prvalorcorrigidoanterior >/*=*/ prvaloraquisicaooriginal) OR (UPPER(wdepmesbaixa) = 'TRUE') ) THEN
        BEGIN
          prvalorcorrigidoanterior      = (wvalorcorrigidoanterior + PRVALORRESIDUAL);
          prvalorcorrigidoanteriormoeda = (wvalorcorrigidoanterior + PRVALORRESIDUAL) / prvlrmoeda;
        END
    END

  --#alt:19501 - O calculo deve ser em cima do valor corrigido atual e não do valor da aquisição, quando possuir valor. Ana - 16/10/2017
  if (wAquisicaoReduziuValorAcumulado = 1) then
    wvalorresidualcontabil         = (((prvalorcorrigidoanterior + prcorrecaoperiodo + WVALDEPACUMUBEM) - wvalorbaixaper - PRVALORRESIDUAL) - wdepreciacaoacumuladaatual);
  else
  IF (prvalorcorrigidoanterior > 0) THEN
    wvalorresidualcontabil         = (((prvalorcorrigidoanterior + prcorrecaoperiodo) - wvalorbaixaper - PRVALORRESIDUAL) - wdepreciacaoacumuladaatual);
  ELSE
    wvalorresidualcontabil         = (wvaloraquisicao - wdepreciacaoacumuladaatual);
  wvalorresidualcontabilmoeda    = (wvalorresidualcontabil / prvlrmoeda);
  --#alt:19501. fim

  IF ((prRelBaiPar = 1) and (prtipo = 2) and (wvalorbaixaper > 0)) THEN
     BEGIN
       wdepreciacaoperiodo = (wvalorbaixa / wtotalmesesdepreciacao);
       wdepreciacaoacumuladaatual = (wdepreciacaoperiodo * wmesesdepreciados);  
       wdepreciacaoperiodomoeda = wdepreciacaoperiodo * prvlrmoeda;
       wdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatual * prvlrmoeda;
       wvalorresidualcontabil = wvalorcorrigidoanterior - wdepreciacaoacumuladaatual;
       wvalorresidualcontabilmoeda = wvalorresidualcontabil * prvlrmoeda;
     END

  --#alt:89963 - Carlos Machado - Caso seja atualizado o valor residual de 100% para 10% depois de 3 meses por exemplo ele deve olhar esses caras aqui, já que o calculo é feito por data
  --Mas o bem ficou parado durante meses por causa do valor residual
  IF (CAST((SUBSTRING(PRDATAINICIAL              FROM 1 FOR 4)) || (SUBSTRING(PRDATAINICIAL              FROM 6 FOR 2)) AS INTEGER) >
      CAST((SUBSTRING(WDATAOFICIALINICIOLCALCULO FROM 1 FOR 4)) || (SUBSTRING(WDATAOFICIALINICIOLCALCULO FROM 6 FOR 2)) AS INTEGER)
     AND (WVALORRESIDUALCONTABIL > 0) AND (WDEPRECIACAOPERIODO < WVALORDEPRECIACAOMENSAL) AND (PRVALORRESIDUAL > 0)) THEN
    BEGIN
      IF (WVALORDEPRECIACAOMENSAL > WVALORRESIDUALCONTABIL) THEN
          WDEPRECIACAOPERIODO        = WVALORRESIDUALCONTABIL        + WDEPRECIACAOPERIODO;
      ELSE
          WDEPRECIACAOPERIODO        = WVALORDEPRECIACAOMENSAL;
      WDEPRECIACAOACUMULADAATUAL     = WDEPRECIACAOACUMULADAANTERIOR + cast(wdepreciacaoperiodo as numeric(15, 2));
      WDEPRECIACAOPERIODOMOEDA       = WDEPRECIACAOPERIODO        * PRVLRMOEDA;

      WDEPRECIACAOACUMULADAATUALMOED = WDEPRECIACAOACUMULADAATUAL * PRVLRMOEDA;
    END
  ELSE
  IF ((wdepdia = 'TRUE') AND (wdepdiafinal = 'TRUE')) THEN
    BEGIN
      IF (wdatainicialoficial < :wdataaquisicao) THEN
        BEGIN
          wdepreciacaoperiodo            = ((wvalordepreciacaodiaria + prvalordepreciacaodiariafim) + wvalordepreciacaomensal * wtotalmesesdoperiodo);
          wdepreciacaoperiodomoeda       = wdepreciacaoperiodo / prvlrmoeda;
          wdepreciacaoacumuladaatual     = (wdepreciacaoacumuladaatual + prvalordepreciacaodiariafim);
          wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual / prvlrmoeda);
          wvalorresidualcontabil         = (wvaloraquisicao - wdepreciacaoacumuladaatual);
          wvalorresidualcontabilmoeda    = 0;
          wdepreciacaoacumuladaanterior  = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
        END
      ELSE
        --#alt:19501 - Se o bem ja foi totalmente depreciado, não deve mais executar esta parte. Estava retornando a depreciação errada. Ana - 25/10/2017
        --#alt:100980 - 06/05/2019 - Carlos Machado - Fazia a verificacao com apenas inteiros, matando numeros pequenos
       IF ((CAST(wvalorcorrigidoanterior AS NUMERIC(15,2)) <> CAST(wdepreciacaoacumuladaatual AS NUMERIC(15,2))) OR
           ((wmesesdepreciados + 1) < wtotalmesesdepreciacao)) THEN
        BEGIN
          wdatatotalmesesultimodia = addmonth(:wdatatotalmesesultimodia,-1);
          wmes                     = CAST(SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 6 FOR 2) AS SMALLINT);
          wano                     = CAST(SUBSTRING(CAST(wdatatotalmesesultimodia AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);
          wdatatotalmesesultimodia = wmes||'-01-'||wano;
    IF (wvaloraquisicao < wdepreciacaoacumuladaatual) THEN
             wdepreciacaoacumuladaatual = wdepreciacaoacumuladaatual - wdepreciacaoperiodo;

          IF (wdatatotalmesesultimodia <= prdatainicial) THEN
             wdepreciacaoacumuladaatual     = (wdepreciacaoacumuladaatual + prvalordepreciacaodiariafim);

          wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaatual * prvlrmoeda);

          wvalorresidualcontabil      = (wvaloraquisicao - wdepreciacaoacumuladaatual);
          --#alt:16852 - Comentado pois não há necessidade de zerar e estava fazendo com que o valor fosse errado. Ana - 10/02/2017
          --wvalorresidualcontabilmoeda = 0;

          IF (wdatainicialoficial <> :wdatatotalmesesultimodia) THEN
            BEGIN
              wdepreciacaoacumuladaanterior  = (wdepreciacaoacumuladaatual - wdepreciacaoperiodo);
              wdepreciacaoacumuladaatualmoed = (wdepreciacaoacumuladaanterior * prvlrmoeda);
            END

          wdepreciacaoperiodo = wdepreciacaoacumuladaatual - wdepreciacaoacumuladaanterior;

          IF (wdepreciacaoperiodo <= 0) THEN
            wdepreciacaoperiodomoeda = 0;
          ELSE
            wdepreciacaoperiodomoeda = wdepreciacaoperiodo * prvlrmoeda;
        END
    END

  --#alt:18200 - Alterada forma de cálculo do valor corrigido atual (valor corrigido anterior + correção do período - valor de baixas do período). Ana - 02/05/2017
  --prvalorcorrigidoatual = (prvalorcorrigidoanterior + prcorrecaoperiodo - wvalorbaixaper);

  --#alt:92279. Quando o valor é aproximado não deve substituir. Ana - 19/11/2018
  wValor = CAST((wdepreciacaoacumuladaanterior + wdepreciacaoperiodo) AS NUMERIC(18,2));
  IF (wValor > prvaloraquisicaooriginal) THEN
    BEGIN
      IF (wdepreciacaoacumuladaanterior <= wvaloraquisicao + PRVALORRESIDUAL) THEN
        BEGIN
          wdepreciacaoperiodo = wvaloraquisicao - wdepreciacaoacumuladaanterior;
          wdepreciacaoacumuladaatual = wdepreciacaoacumuladaanterior + cast(wdepreciacaoperiodo as numeric(15, 2));
        END
      wdepreciacaoperiodomoeda = wdepreciacaoperiodo * prvlrmoeda;
      wdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatual * prvlrmoeda;
    END
  IF ((wdepdia = 'TRUE') and ((extract(day from WDATAINICIOCALC) <> 1)  or (wdepdiadata = 2))) THEN
    BEGIN
      -- Quer dizer que é o primeiro mês e esse mês não vai contar já que e parcial, o restante estara no último mês a depreciar
      wmesesdepreciar      = wmesesdepreciar - 1;
      wmesesdepreciados    = wmesesdepreciados + 1;
      wtotalmesesdoperiodo = wtotalmesesdoperiodo +1;
    END

  prdepreciacaoacumuladaanterior  = wdepreciacaoacumuladaanterior;
  prdepreciacaoperiodo            = wdepreciacaoperiodo;
  prdepreciacaoperiodomoeda       = wdepreciacaoperiodomoeda;
  prdepreciacaoacumuladaatual     = wdepreciacaoacumuladaatual;
  prdepreciacaoacumuladaatualmoed = wdepreciacaoacumuladaatualmoed;
  prcorrecaomonetariadepreciacao  = 0;
  prvalorresidualcontabil         = wvalorresidualcontabil;
  prvalorresidualcontabilmoeda    = wvalorresidualcontabilmoeda;
  prtotalmesesdepreciacao         = wtotalmesesdepreciacao;
  prmesesdepreciados              = wmesesdepreciados;
  prmesesdepreciar                = wmesesdepreciar;
  prdatataxadepreciacao           = wdataultimoitemdep;
  --#Alt:5105
  --prvalorbaixa                    = wvalorbaixa;
  prvalorbaixa                    = wvalorbaixaper;
  prdepreciacaobaixamoeda         = wdepreciacaobaixamoeda;
  prvalorbaixareal                = wvalorbaixa;
  prvalormoeda                    = prvlrmoeda;
  prdatabaixa                     = wdatabaixa;
  prvaloraquisicaomoeda           = wvaloraquisicaomoeda;
  prmesnovataxa                   = prmesdepreciacaonovataxa;

  SUSPEND;
END
^

--Sol. 134778 - procedure para buscar as escalar de férias de empresas anterios de colaboradores transferidos
/* Restore proc. body: SP_CONS_FERIAS_ESCALA_TRANSF */
create or alter procedure SP_CONS_FERIAS_ESCALA_TRANSF (
    PRCODEMP varchar(100),
    PRCODCOL varchar(100),
    PRREF integer,
    PRPRIDIA date,
    PRULTDIA date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDINIPERGOZOFE date,
    BDFIMPERAQUISFE date,
    BDFIMPERGOZOFE date,
    BDDATAPAGFE date,
    BDQTDABONOFE numeric(18,6),
    BDQTDGOZOFE numeric(18,6),
    BDSALDOINIFE numeric(15,6),
    BDSALDOFIMFE numeric(15,6),
    BDBASEIRFE numeric(15,6),
    BDALIQIRFE numeric(15,6),
    BDVALORIRFE numeric(15,6),
    BDBASEINSSFE numeric(15,6),
    BDALIQINSSFE numeric(15,6),
    BDVALORINSSFE numeric(15,6),
    BDDEPFE numeric(15,6),
    BDSALBASEFE numeric(15,6),
    BDSALBASEHEFE numeric(15,6),
    BDDATABAIXAFE date,
    BDCOLETIVASFE varchar(5),
    BDREFPAGABOFE integer,
    BDFALTASFE numeric(15,6),
    BDNOMEMP varchar(100),
    BDNOMCOL varchar(70),
    BDSALDOFINALSINDFE numeric(18,6),
    BDFERIADOSFE integer,
    BDMIGRACAO DM_BOOLEAN,
    BDPAGO DM_BOOLEAN)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(15000);
declare variable WEMPRESA integer;
declare variable WCOLABORADOR integer;
declare variable WPERAQUISINI date;
declare variable WPERAQUISFIM date;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WINIPERAQUISFE date;
declare variable WFIMPERAQUISFE date;
declare variable WCODFE integer;
declare variable WINIPERGOZOFE date;
declare variable WFIMPERGOZOFE date;
declare variable WDATAPAGFE date;
declare variable WQTDGOZOFE numeric(18,6);
declare variable WQTDABONOFE numeric(18,6);
declare variable WSALDOINIFE numeric(18,6);
declare variable WSALDOFIMFE numeric(18,6);
declare variable WBASEIRFE numeric(15,6);
declare variable WALIQIRFE numeric(15,6);
declare variable WVALORIRFE numeric(15,6);
declare variable WBASEINSSFE numeric(15,6);
declare variable WVALORINSSFE numeric(15,6);
declare variable WALIQINSSFE numeric(15,6);
declare variable WDEPFE numeric(15,6);
declare variable WSALBASEFE numeric(15,6);
declare variable WSALBASEHEFE numeric(15,6);
declare variable WDATABAIXAFE date;
declare variable WCOLETIVASFE varchar(5);
declare variable WREFPAGABOFE integer;
declare variable WFALTASFE numeric(15,6);
declare variable WNOMEMP DM_BDNOMEMP;
declare variable WNOMCOL DM_BDNOMCOL;
declare variable WSALDOFINALSINDFE numeric(18,6);
declare variable WFERIADOSFE integer;
declare variable WDATAAUX date;
declare variable WSALFIMMIGRACAO numeric(15,6);
declare variable WREFPAG integer;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref,  NULL, NULL);

  wsql = 'select FER.BDCODEMP, FER.BDCODCOL, FER.BDINIPERAQUISFE, FER.BDCODFE, FER.BDINIPERGOZOFE, FER.BDFIMPERAQUISFE, '||
                'FER.BDFIMPERGOZOFE, FER.BDDATAPAGFE, FER.BDQTDGOZOFE, FER.BDQTDABONOFE, FER.BDSALDOINIFE, '||
                'FER.BDSALDOFIMFE, FER.BDBASEIRFE, FER.BDALIQIRFE, FER.BDVALORIRFE, FER.BDBASEINSSFE, FER.BDALIQINSSFE, '||
                'FER.BDVALORINSSFE, FER.BDDEPFE, FER.BDSALBASEFE, FER.BDSALBASEHEFE, FER.BDDATABAIXAFE, FER.BDCOLETIVASFE, '||
                'FER.BDREFPAGABOFE, FER.BDFALTASFE, EMP.BDNOMEMP, COLCAD.BDNOMCOL, FER.BDSALDOFINALSINDFE, FER.BDFERIADOSFE ';

  wsql = wsql || 'from VRH_EMP_TFERIAS FER '||
                 'left outer join VW_TEMPRESAS_REF EMP '||
                    'on (EMP.BDCODEMP = FER.BDCODEMP) '||
                 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD '||
                    'on (COLCAD.BDCODEMP = FER.BDCODEMP and COLCAD.BDCODCOL = FER.BDCODCOL) ';

  wwhere = 'coalesce(coalesce(fer.BDDATAPAGFE,fer.BDINIPERGOZOFE),'||
           'cast(case when ((fer.bdrefpagabofe is null) or (fer.bdrefpagabofe = 0)) '||
           'then null else substring(cast(fer.bdrefpagabofe as varchar(6)) from 5 for 2)||'||
           ''''||'/01/'||''''||
           '||substring(cast(fer.bdrefpagabofe as varchar(6)) from 1 for 4) end as date))';

  wwhere = ' where '||wwhere||' <= '''||prultdia||''' ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||' and '||prcodcol;

  wsql = wsql||wwhere;

  wsql = wsql||' order by FER.BDCODEMP, FER.BDCODCOL, FER.BDINIPERAQUISFE, FER.BDCODFE';

  wEmpresa = 0;
  wColaborador = 0;
  wsalfimmigracao = 0;
  FOR EXECUTE STATEMENT wsql
  INTO :WCODEMP, :WCODCOL, :WINIPERAQUISFE, :WCODFE, :WINIPERGOZOFE, :WFIMPERAQUISFE,
       :WFIMPERGOZOFE, :WDATAPAGFE, :WQTDGOZOFE, :WQTDABONOFE, :WSALDOINIFE,
       :WSALDOFIMFE, :WBASEIRFE, :WALIQIRFE, :WVALORIRFE, :WBASEINSSFE, :WALIQINSSFE,
       :WVALORINSSFE, :WDEPFE, :WSALBASEFE, :WSALBASEHEFE, :WDATABAIXAFE, :WCOLETIVASFE,
       :WREFPAGABOFE, :WFALTASFE, :WNOMEMP, :WNOMCOL, :WSALDOFINALSINDFE, :WFERIADOSFE DO
    BEGIN

      IF ((wEmpresa <> WCODEMP) OR (wColaborador <> WCODCOL) OR (wPerAquisIni <> WINIPERAQUISFE)) THEN
        BEGIN
          IF (wEmpresa <> 0) THEN
             begin
               wdataaux = null;
               select first 1 BDINIPERAQUISFE from VRHF_EMP_TVERBAFE where BDCODEMP = :wempresa and BDCODCOL = :wcolaborador and BDINIPERAQUISFE = :wPerAquisIni into :wdataaux;
           
               if (wdataaux is null) then
                  begin
                    BDMIGRACAO = 'TRUE';

                    if (coalesce(bdfaltasfe, 0) = 0) then
                       begin
                         select count(*)
                         from (select BDDATAFAL
                               from VRH_EMP_TFALTAS_ITENS
                               where BDCODEMP = :wempresa and
                                     BDCODCOL = :wcolaborador and
                                     BDDATAFAL between :wPerAquisIni and :wPerAquisFim and
                                     coalesce(BDTIPOFAL, 0) = 1 and
                                     coalesce(BDTIPODESCFAL, 0) = 0
                               union all
                               select FAL.BDDATAFAL
                               from VRH_EMP_TTRANSCOL TRANS
                               join VRH_EMP_TFALTAS_ITENS FAL on (FAL.BDCODEMP = TRANS.BDCODEMPORIG and FAL.BDCODCOL = TRANS.BDCODCOLORIG)
                               where TRANS.BDCODEMPDEST = :wempresa and
                                     TRANS.BDCODCOLDEST = :wcolaborador and
                                     FAL.BDDATAFAL between :wPerAquisIni and :wPerAquisFim and
                                     coalesce(FAL.BDTIPOFAL, 0) = 1 and
                                     coalesce(FAL.BDTIPODESCFAL, 0) = 0
                         )
                         into :BDFALTASFE;
                       end

--                    if (wsalfimmigracao is not null) then
--                       BDSALDOFIMFE = wsalfimmigracao;
                  end
               else
                  BDMIGRACAO = 'FALSE';


               BDPAGO = 'FALSE';
         
               if (bdfimpergozofe is not null) then
                  begin
                    wrefpag = CAST((SUBSTRING(CAST(bdfimpergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdfimpergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                    if (wrefpag <= prref) then
                       BDPAGO = 'TRUE';
                  end

               if (BDPAGO = 'FALSE') then
                  begin
                    if (bdinipergozofe is not null) then
                       begin
                         wrefpag = CAST((SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                         if (wrefpag <= prref) then
                            BDPAGO = 'TRUE';
                       end
                  end
         
               if (BDPAGO = 'FALSE') then
                  begin
                    if (coalesce(bdrefpagabofe, 0) > 0) then
                       begin
                         if (bdrefpagabofe <= prref) then
                            BDPAGO = 'TRUE';
                       end
                  end

               SUSPEND;
             end

          wEmpresa = WCODEMP;
          wColaborador = WCODCOL;
          wPerAquisIni = WINIPERAQUISFE;
          wPerAquisFim = WFIMPERAQUISFE;
          BDQTDGOZOFE = 0;
          BDQTDABONOFE = 0;
          BDSALDOINIFE = 0;
        END

      BDCODEMP = WCODEMP;
      BDCODCOL = WCODCOL;
      BDINIPERAQUISFE = WINIPERAQUISFE;
      BDCODFE = WCODFE;
      BDINIPERGOZOFE = WINIPERGOZOFE;
      BDFIMPERAQUISFE = WFIMPERAQUISFE;
      BDFIMPERGOZOFE = WFIMPERGOZOFE;
      BDDATAPAGFE = NULL;     --WDATAPAGFE;
      BDQTDGOZOFE = COALESCE(BDQTDGOZOFE, 0) + COALESCE(WQTDGOZOFE, 0);
      BDQTDABONOFE = COALESCE(BDQTDABONOFE, 0) + COALESCE(WQTDABONOFE, 0);

      IF (WCODFE = 1) THEN
         begin
           BDSALDOINIFE = WSALDOINIFE;

           if (coalesce(BDSALDOINIFE, 0) = 0) then
              BDSALDOINIFE = 30;

           wsalfimmigracao = BDSALDOINIFE;
         end

      wsalfimmigracao = wsalfimmigracao - coalesce(WQTDGOZOFE, 0) - coalesce(WQTDABONOFE, 0);
      BDSALDOFIMFE = WSALDOFIMFE;
      BDBASEIRFE = WBASEIRFE;
      BDALIQIRFE = WALIQIRFE;
      BDVALORIRFE = WVALORIRFE;
      BDBASEINSSFE = WBASEINSSFE;
      BDALIQINSSFE = WALIQINSSFE;
      BDVALORINSSFE = WVALORINSSFE;
      BDDEPFE = WDEPFE;
      BDSALBASEFE = WSALBASEFE;
      BDSALBASEHEFE = WSALBASEHEFE;
      BDDATABAIXAFE = WDATABAIXAFE;
      BDCOLETIVASFE = WCOLETIVASFE;
      BDREFPAGABOFE = WREFPAGABOFE;
      BDFALTASFE = WFALTASFE;
      BDNOMEMP = WNOMEMP;
      BDNOMCOL = WNOMCOL;
      BDSALDOFINALSINDFE = wsaldofinalsindfe;
      BDFERIADOSFE = wferiadosfe;
    END

  wdataaux = null;
  select first 1 BDINIPERAQUISFE from VRHF_EMP_TVERBAFE where BDCODEMP = :bdcodemp and BDCODCOL = :bdcodcol and BDINIPERAQUISFE = :bdiniperaquisfe into :wdataaux;

  if (wdataaux is null) then
     begin
       BDMIGRACAO = 'TRUE';

       if (coalesce(bdfaltasfe, 0) = 0) then
          begin
            select count(*)
            from (select BDDATAFAL
                  from VRH_EMP_TFALTAS_ITENS
                  where BDCODEMP = :wempresa and
                        BDCODCOL = :wcolaborador and
                        BDDATAFAL between :wperaquisini and :wperaquisfim and
                        coalesce(BDTIPOFAL, 0) = 1 and
                        coalesce(BDTIPODESCFAL, 0) = 0
                  union all
                  select FAL.BDDATAFAL
                  from VRH_EMP_TTRANSCOL TRANS
                  join VRH_EMP_TFALTAS_ITENS FAL on (FAL.BDCODEMP = TRANS.BDCODEMPORIG and FAL.BDCODCOL = TRANS.BDCODCOLORIG)
                  where TRANS.BDCODEMPDEST = :wempresa and
                        TRANS.BDCODCOLDEST = :wcolaborador and
                        FAL.BDDATAFAL between :wperaquisini and :wperaquisfim and
                        coalesce(FAL.BDTIPOFAL, 0) = 1 and
                        coalesce(FAL.BDTIPODESCFAL, 0) = 0
            )
            into :BDFALTASFE;
          end

--       if (wsalfimmigracao is not null) then
--          BDSALDOFIMFE = wsalfimmigracao;
     end
  else
     BDMIGRACAO = 'FALSE';

  BDPAGO = 'FALSE';

  if (bdfimpergozofe is not null) then
     begin
       wrefpag = CAST((SUBSTRING(CAST(bdfimpergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdfimpergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
       if (wrefpag <= prref) then
          BDPAGO = 'TRUE';
     end

  if (BDPAGO = 'FALSE') then
     begin
       if (bdinipergozofe is not null) then
          begin
            wrefpag = CAST((SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
            if (wrefpag <= prref) then
               BDPAGO = 'TRUE';
          end
     end

  if (BDPAGO = 'FALSE') then
     begin
       if (coalesce(bdrefpagabofe, 0) > 0) then
          begin
            if (bdrefpagabofe <= prref) then
               BDPAGO = 'TRUE';
          end
     end

  if (wempresa <> 0 and wcolaborador <> 0) then
     SUSPEND;
END^

/* Restore proc. body: SP_VRHF_LISTAPERAQUISFE */
create or alter procedure SP_VRHF_LISTAPERAQUISFE (
    PREMP varchar(15000),
    PRCOL varchar(32700))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDCODEMPORIG integer,
    BDCODCOLORIG integer)
as
declare variable WSQL varchar(32700);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WEMPORIG integer;
declare variable WCOLORIG integer;
declare variable WACHOUPER integer;
declare variable WEMPANT integer;
declare variable WCOLANT integer;
declare variable WPERAQUIS2 date;
declare variable WFE2 integer;
declare variable WPERAQUISANT date;
declare variable WCODFEANT integer;
declare variable WCODCONTROLE integer;
begin
  wsql = 'select FER.BDCODEMP, FER.BDCODCOL, FER.BDINIPERAQUISFE, FER.BDCODFE '||
         'from VRH_EMP_TFERIAS FER ';

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||' where '||premp;

       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;
     end

  wsql = wsql||' order by FER.BDCODEMP, FER.BDCODCOL ';

  wempatu = 0;
  wcolatu = 0;

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDINIPERAQUISFE, :BDCODFE do
    begin
      BDCODEMPORIG = null;
      BDCODCOLORIG = null;
       if (wempant<>bdcodemp) then    --Valmor H Junior 159109 27/01/2022
           wempatu = 0;
       if (wcolant<>bdcodcol) then
            wcolatu =0;

      if (wempatu = 0) then
         wempatu = BDCODEMP;

      if (wcolatu = 0) then
         wcolatu = BDCODCOL;


      if ((wempatu <> BDCODEMP) or (wcolatu <> BDCODCOL)) then
         begin
           wempant = BDCODEMP;
           wcolant = BDCODCOL;
           WPERAQUISANT = BDINIPERAQUISFE;
           WCODFEANT = BDCODFE;


           for select BDCODEMPORIG, BDCODCOLORIG
               from VRH_EMP_TTRANSCOL
               where BDCODEMPDEST = :wempatu and BDCODCOLDEST = :wcolatu and BDCODEMPORIG is not null and BDCODCOLORIG is not null and
                     ((BDCODEMPDEST <> BDCODEMPORIG) or (BDCODEMPDEST = BDCODEMPORIG and BDCODCOLDEST <> BDCODCOLORIG))
           into :wemporig, :wcolorig do
             begin
      wcodcontrole = null;
               select bdcodemp from TMP_CONTROLE_PERAQUISFE where BDSPINSERIU = 3 AND bdcodemp = :wemporig and bdcodcol = :wcolorig and bdsessao = current_connection into :wcodcontrole;
               if (wcodcontrole IS NULL) then
                  begin
                    insert into TMP_CONTROLE_PERAQUISFE (BDCODEMP,BDCODCOL,BDSESSAO,BDSPINSERIU) values (:wemporig,:wcolorig,current_connection,3);

               for select BDINIPERAQUISFE, BDCODFE from SP_VRHF_LISTAPERAQUISFE('FER.BDCODEMP = '||:wemporig, 'FER.BDCODCOL = '||:wcolorig)
               into :wperaquis2, :wfe2 do
               begin
                 wachouper    = null;
                 select first 1 BDCODEMP from VRH_EMP_TFERIAS where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDINIPERAQUISFE = :wperaquis2 and BDCODFE = :wfe2 into :wachouper;
                 if (coalesce(wachouper, 0) <= 0) then
                    begin
                 BDCODEMP     = wempatu;
                 BDCODCOL     = wcolatu;
                 BDCODEMPORIG = wemporig;
                 BDCODCOLORIG = wcolorig;
                      BDINIPERAQUISFE = wperaquis2;
                      BDCODFE         = wfe2;
                    suspend;
               end
             end
             end
             end

           
           wempatu = wempant;
           wcolatu = wcolant;
     
     /* #189377 Leonardo Schwab 08/11/2023 Início */
           BDCODEMP     = wempatu;
           BDCODCOL     = wcolatu;
           BDCODEMPORIG = null;
           BDCODCOLORIG = null;
           BDINIPERAQUISFE = WPERAQUISANT;
           BDCODFE         = WCODFEANT;

           wempant = null;
           wcolant = null;
           WPERAQUISANT = null;
           WCODFEANT = null;
     /* #189377 Leonardo Schwab 08/11/2023 Fim */
         end

      suspend;
    end

  if (wempatu <> 0 and wcolatu <> 0) then
     begin
       for select BDCODEMPORIG, BDCODCOLORIG
           from VRH_EMP_TTRANSCOL
           where BDCODEMPDEST = :wempatu and BDCODCOLDEST = :wcolatu and BDCODEMPORIG is not null and BDCODCOLORIG is not null and
                 ((BDCODEMPDEST <> BDCODEMPORIG) or (BDCODEMPDEST = BDCODEMPORIG and BDCODCOLDEST <> BDCODCOLORIG))
       into :wemporig, :wcolorig do
         begin
     wcodcontrole = null;
           select bdcodemp from TMP_CONTROLE_PERAQUISFE where BDSPINSERIU = 3 AND bdcodemp = :wemporig and bdcodcol = :wcolorig and bdsessao = current_connection into :wcodcontrole;
           if (wcodcontrole IS NULL) then
              begin
                insert into TMP_CONTROLE_PERAQUISFE (BDCODEMP,BDCODCOL,BDSESSAO,BDSPINSERIU) values (:wemporig,:wcolorig,current_connection,3);

           for select BDCODEMP, BDCODCOL, BDINIPERAQUISFE, BDCODFE from SP_VRHF_LISTAPERAQUISFE('FER.BDCODEMP = '||:wemporig, 'FER.BDCODCOL = '||:wcolorig)
           into :BDCODEMP, :BDCODCOL, :BDINIPERAQUISFE, :BDCODFE do
           begin
             BDCODEMP     = wempatu;
             BDCODCOL     = wcolatu;
             BDCODEMPORIG = wemporig;
             BDCODCOLORIG = wcolorig;

             wachouper    = null;
             select first 1 BDCODEMP from VRH_EMP_TFERIAS where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDINIPERAQUISFE = :BDINIPERAQUISFE and BDCODFE = :BDCODFE into :wachouper;
             if (coalesce(wachouper, 0) <= 0) then
                suspend;
           end
         end
     end
     end
--  delete from TMP_CONTROLE_PERAQUISFE WHERE BDSESSAO = current_connection;
end^

/* Restore proc. body: SP_CONS_FERIAS_PER_AQUIS_ESCALA */
create or alter procedure SP_CONS_FERIAS_PER_AQUIS_ESCALA (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREF integer,
    PRPRIDIA date,
    PRULTDIA date,
    PRAGENDAFERIAS integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDINIPERGOZOFE date,
    BDFIMPERAQUISFE date,
    BDFIMPERGOZOFE date,
    BDDATAPAGFE date,
    BDQTDABONOFE numeric(18,6),
    BDQTDGOZOFE numeric(18,6),
    BDSALDOINIFE numeric(15,6),
    BDSALDOFIMFE numeric(15,6),
    BDBASEIRFE numeric(15,6),
    BDALIQIRFE numeric(15,6),
    BDVALORIRFE numeric(15,6),
    BDBASEINSSFE numeric(15,6),
    BDALIQINSSFE numeric(15,6),
    BDVALORINSSFE numeric(15,6),
    BDDEPFE numeric(15,6),
    BDSALBASEFE numeric(15,6),
    BDSALBASEHEFE numeric(15,6),
    BDDATABAIXAFE date,
    BDCOLETIVASFE varchar(5),
    BDREFPAGABOFE integer,
    BDFALTASFE numeric(15,6),
    BDNOMEMP varchar(100),
    BDNOMCOL varchar(70),
    BDSALDOFINALSINDFE numeric(18,6),
    BDFERIADOSFE integer,
    BDMIGRACAO DM_BOOLEAN,
    BDPAGO DM_BOOLEAN)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(15000);
declare variable WEMPRESA integer;
declare variable WCOLABORADOR integer;
declare variable WPERAQUISINI date;
declare variable WPERAQUISFIM date;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WINIPERAQUISFE date;
declare variable WCODFE integer;
declare variable WINIPERGOZOFE date;
declare variable WFIMPERAQUISFE date;
declare variable WFIMPERGOZOFE date;
declare variable WDATAPAGFE date;
declare variable WQTDGOZOFE numeric(18,6);
declare variable WQTDABONOFE numeric(18,6);
declare variable WSALDOINIFE numeric(15,6);
declare variable WSALDOFIMFE numeric(15,6);
declare variable WBASEIRFE numeric(15,6);
declare variable WALIQIRFE numeric(15,6);
declare variable WVALORIRFE numeric(15,6);
declare variable WBASEINSSFE numeric(15,6);
declare variable WALIQINSSFE numeric(15,6);
declare variable WVALORINSSFE numeric(15,6);
declare variable WDEPFE numeric(15,6);
declare variable WSALBASEFE numeric(15,6);
declare variable WSALBASEHEFE numeric(15,6);
declare variable WDATABAIXAFE date;
declare variable WCOLETIVASFE varchar(5);
declare variable WREFPAGABOFE integer;
declare variable WFALTASFE numeric(15,6);
declare variable WNOMEMP DM_BDNOMEMP;
declare variable WNOMCOL DM_BDNOMCOL;
declare variable WSALDOFINALSINDFE numeric(18,6);
declare variable WFERIADOSFE integer;
declare variable WDATAAUX date;
declare variable WSALFIMMIGRACAO numeric(15,6);
declare variable WREFPAG integer;
declare variable WCODEMPTRANSF varchar(20);
declare variable WCODCOLTRANSF varchar(20);
declare variable WSQL2 varchar(500);
declare variable WACHOUPER integer;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref,  NULL, NULL);

  delete from TMP_CONTROLE_PERAQUISFE WHERE BDSESSAO = current_connection;
  
  wsql = 'select FER2.BDCODEMP, FER2.BDCODCOL, FER2.BDINIPERAQUISFE, FER2.BDCODFE, FER.BDINIPERGOZOFE, FER.BDFIMPERAQUISFE, '||
                'FER.BDFIMPERGOZOFE, FER.BDDATAPAGFE, FER.BDQTDGOZOFE, FER.BDQTDABONOFE, FER.BDSALDOINIFE, '||
                'FER.BDSALDOFIMFE, FER.BDBASEIRFE, FER.BDALIQIRFE, FER.BDVALORIRFE, FER.BDBASEINSSFE, FER.BDALIQINSSFE, '||
                'FER.BDVALORINSSFE, FER.BDDEPFE, FER.BDSALBASEFE, FER.BDSALBASEHEFE, FER.BDDATABAIXAFE, FER.BDCOLETIVASFE, '||
                'FER.BDREFPAGABOFE, FER.BDFALTASFE, EMP.BDNOMEMP, COLCAD.BDNOMCOL, FER.BDSALDOFINALSINDFE, FER.BDFERIADOSFE ';

  wsql = wsql||'from SP_VRHF_LISTAPERAQUISFE(';

  IF (coalesce(prcodemp, '') <> '') THEN
     wsql = wsql||''''||prcodemp||''', ';
  else
     wsql = wsql||'null, ';

  IF (coalesce(prcodcol, '') <> '') THEN
     wsql = wsql||''''||prcodcol||''') FER2 ';
  else
     wsql = wsql||'null) FER2 ';

  wsql = wsql || 'join VRH_EMP_TFERIAS FER on (FER.BDCODEMP = coalesce(FER2.BDCODEMPORIG, FER2.BDCODEMP) and FER.BDCODCOL = coalesce(FER2.BDCODCOLORIG, FER2.BDCODCOL) and '||
                      'FER.BDINIPERAQUISFE = FER2.BDINIPERAQUISFE and FER.BDCODFE = FER2.BDCODFE) '||
                 'left outer join VW_TEMPRESAS_REF EMP '||
                    'on (EMP.BDCODEMP = FER.BDCODEMP) '||
                 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD '||
                    'on (COLCAD.BDCODEMP = FER.BDCODEMP and COLCAD.BDCODCOL = FER.BDCODCOL) ';

  wwhere = '';

  if (PRAGENDAFERIAS = 0) then /*Sol. 156258 - André Cursino - tira o filtro para pegar todos os periodos aquisitivos*/
    begin
  wwhere = 'coalesce(coalesce(fer.BDDATAPAGFE,fer.BDINIPERGOZOFE),'||
           'cast(case when ((fer.bdrefpagabofe is null) or (fer.bdrefpagabofe = 0)) '||
           'then null else substring(cast(fer.bdrefpagabofe as varchar(6)) from 5 for 2)||'||
           ''''||'/01/'||''''||
           '||substring(cast(fer.bdrefpagabofe as varchar(6)) from 1 for 4) end as date))';
    
    
  wwhere = ' where '||wwhere||' <= '''||prultdia||''' ';
    end

  wsql = wsql||wwhere;

  wsql = wsql||' order by FER2.BDCODEMP, FER2.BDCODCOL, FER2.BDINIPERAQUISFE, FER2.BDCODFE';

  wEmpresa = 0;
  wColaborador = 0;
  wsalfimmigracao = 0;
  FOR EXECUTE STATEMENT wsql
  INTO :WCODEMP, :WCODCOL, :WINIPERAQUISFE, :WCODFE, :WINIPERGOZOFE, :WFIMPERAQUISFE,
       :WFIMPERGOZOFE, :WDATAPAGFE, :WQTDGOZOFE, :WQTDABONOFE, :WSALDOINIFE,
       :WSALDOFIMFE, :WBASEIRFE, :WALIQIRFE, :WVALORIRFE, :WBASEINSSFE, :WALIQINSSFE,
       :WVALORINSSFE, :WDEPFE, :WSALBASEFE, :WSALBASEHEFE, :WDATABAIXAFE, :WCOLETIVASFE,
       :WREFPAGABOFE, :WFALTASFE, :WNOMEMP, :WNOMCOL, :WSALDOFINALSINDFE, :WFERIADOSFE DO
    BEGIN

      /*IF ((wEmpresa <> WCODEMP) OR (wColaborador <> WCODCOL) OR (wPerAquisIni <> WINIPERAQUISFE)) THEN*/
      IF ((wEmpresa <> WCODEMP) OR (wColaborador <> WCODCOL) OR (wPerAquisIni <> WINIPERAQUISFE) or (PRAGENDAFERIAS > 0)) THEN    /*Sol. 156258 - André Cursino - para que possa ser listado todos os periodos de ferias*/
        BEGIN
          IF (wEmpresa <> 0) THEN
             begin
               wdataaux = null;
               select first 1 BDINIPERAQUISFE from VRHF_EMP_TVERBAFE where BDCODEMP = :wempresa and BDCODCOL = :wcolaborador and BDINIPERAQUISFE = :wPerAquisIni into :wdataaux;
           
               if (wdataaux is null) then
                  begin
                    BDMIGRACAO = 'TRUE';

                    if (coalesce(bdfaltasfe, 0) = 0) then
                       begin
                         select count(*)
                         from (select BDDATAFAL
                               from VRH_EMP_TFALTAS_ITENS
                               where BDCODEMP = :wempresa and
                                     BDCODCOL = :wcolaborador and
                                     BDDATAFAL between :wPerAquisIni and :wPerAquisFim and
                                     coalesce(BDTIPOFAL, 0) = 1 and
                                     coalesce(BDTIPODESCFAL, 0) = 0
                               union all
                               select FAL.BDDATAFAL
                               from VRH_EMP_TTRANSCOL TRANS
                               join VRH_EMP_TFALTAS_ITENS FAL on (FAL.BDCODEMP = TRANS.BDCODEMPORIG and FAL.BDCODCOL = TRANS.BDCODCOLORIG)
                               where TRANS.BDCODEMPDEST = :wempresa and
                                     TRANS.BDCODCOLDEST = :wcolaborador and
                                     FAL.BDDATAFAL between :wPerAquisIni and :wPerAquisFim and
                                     coalesce(FAL.BDTIPOFAL, 0) = 1 and
                                     coalesce(FAL.BDTIPODESCFAL, 0) = 0
                         )
                         into :BDFALTASFE;
                       end
                  end
               else
                  BDMIGRACAO = 'FALSE';


               BDPAGO = 'FALSE';
         
               if (bdfimpergozofe is not null) then
                  begin
                    wrefpag = CAST((SUBSTRING(CAST(bdfimpergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdfimpergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                    if (wrefpag <= prref) then
                       BDPAGO = 'TRUE';
                  end

               if (BDPAGO = 'FALSE') then
                  begin
                    if (bdinipergozofe is not null) then
                       begin
                         wrefpag = CAST((SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                         if (wrefpag <= prref) then
                            BDPAGO = 'TRUE';
                       end
                  end
         
               if (BDPAGO = 'FALSE') then
                  begin
                    if (coalesce(bdrefpagabofe, 0) > 0) then
                       begin
                         if (bdrefpagabofe <= prref) then
                            BDPAGO = 'TRUE';
                       end
                  end

               SUSPEND;
             end

          wEmpresa = WCODEMP;
          wColaborador = WCODCOL;
          wPerAquisIni = WINIPERAQUISFE;
          wPerAquisFim = WFIMPERAQUISFE;
          BDQTDGOZOFE = 0;
          BDQTDABONOFE = 0;
          BDSALDOINIFE = 0;
        END

      BDCODEMP = WCODEMP;
      BDCODCOL = WCODCOL;
      BDINIPERAQUISFE = WINIPERAQUISFE;
      BDCODFE = WCODFE;
      BDINIPERGOZOFE = WINIPERGOZOFE;
      BDFIMPERAQUISFE = WFIMPERAQUISFE;
      BDFIMPERGOZOFE = WFIMPERGOZOFE;
      BDDATAPAGFE = NULL;     --WDATAPAGFE;
      BDQTDGOZOFE = COALESCE(BDQTDGOZOFE, 0) + COALESCE(WQTDGOZOFE, 0);
      BDQTDABONOFE = COALESCE(BDQTDABONOFE, 0) + COALESCE(WQTDABONOFE, 0);

      IF (WCODFE = 1) THEN
         begin
           BDSALDOINIFE = WSALDOINIFE;

           if (coalesce(BDSALDOINIFE, 0) = 0) then
              BDSALDOINIFE = 30;

           wsalfimmigracao = BDSALDOINIFE;
         end

      wsalfimmigracao = wsalfimmigracao - coalesce(WQTDGOZOFE, 0) - coalesce(WQTDABONOFE, 0);
      BDSALDOFIMFE = WSALDOFIMFE;
      BDBASEIRFE = WBASEIRFE;
      BDALIQIRFE = WALIQIRFE;
      BDVALORIRFE = WVALORIRFE;
      BDBASEINSSFE = WBASEINSSFE;
      BDALIQINSSFE = WALIQINSSFE;
      BDVALORINSSFE = WVALORINSSFE;
      BDDEPFE = WDEPFE;
      BDSALBASEFE = WSALBASEFE;
      BDSALBASEHEFE = WSALBASEHEFE;
      BDDATABAIXAFE = WDATABAIXAFE;
      BDCOLETIVASFE = WCOLETIVASFE;
      BDREFPAGABOFE = WREFPAGABOFE;
      BDFALTASFE = WFALTASFE;
      BDNOMEMP = WNOMEMP;
      BDNOMCOL = WNOMCOL;
      BDSALDOFINALSINDFE = wsaldofinalsindfe;
      BDFERIADOSFE = wferiadosfe;
    END

  wdataaux = null;
  select first 1 BDINIPERAQUISFE from VRHF_EMP_TVERBAFE where BDCODEMP = :bdcodemp and BDCODCOL = :bdcodcol and BDINIPERAQUISFE = :bdiniperaquisfe into :wdataaux;

  if (wdataaux is null) then
     begin
       BDMIGRACAO = 'TRUE';

       if (coalesce(bdfaltasfe, 0) = 0) then
          begin
            select count(*)
            from (select BDDATAFAL
                  from VRH_EMP_TFALTAS_ITENS
                  where BDCODEMP = :wempresa and
                        BDCODCOL = :wcolaborador and
                        BDDATAFAL between :wperaquisini and :wperaquisfim and
                        coalesce(BDTIPOFAL, 0) = 1 and
                        coalesce(BDTIPODESCFAL, 0) = 0
                  union all
                  select FAL.BDDATAFAL
                  from VRH_EMP_TTRANSCOL TRANS
                  join VRH_EMP_TFALTAS_ITENS FAL on (FAL.BDCODEMP = TRANS.BDCODEMPORIG and FAL.BDCODCOL = TRANS.BDCODCOLORIG)
                  where TRANS.BDCODEMPDEST = :wempresa and
                        TRANS.BDCODCOLDEST = :wcolaborador and
                        FAL.BDDATAFAL between :wperaquisini and :wperaquisfim and
                        coalesce(FAL.BDTIPOFAL, 0) = 1 and
                        coalesce(FAL.BDTIPODESCFAL, 0) = 0
            )
            into :BDFALTASFE;
          end
     end
  else
     BDMIGRACAO = 'FALSE';

  BDPAGO = 'FALSE';

  if (bdfimpergozofe is not null) then
     begin
       wrefpag = CAST((SUBSTRING(CAST(bdfimpergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdfimpergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
       if (wrefpag <= prref) then
          BDPAGO = 'TRUE';
     end

  if (BDPAGO = 'FALSE') then
     begin
       if (bdinipergozofe is not null) then
          begin
            wrefpag = CAST((SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
            if (wrefpag <= prref) then
               BDPAGO = 'TRUE';
          end
     end

  if (BDPAGO = 'FALSE') then
     begin
       if (coalesce(bdrefpagabofe, 0) > 0) then
          begin
            if (bdrefpagabofe <= prref) then
               BDPAGO = 'TRUE';
          end
     end

  SUSPEND;
END^

/* Restore proc. body: SP_CONSULTA_COL_POR_REF */
ALTER PROCEDURE SP_CONSULTA_COL_POR_REF(PREMP INTEGER,
PRCOL INTEGER,
PRREFMICRO INTEGER)
 RETURNS(BDREFCOL INTEGER)
 AS
BEGIN
   IF (prrefmicro IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);


       SELECT MAX(Y.BDREFCOL)
       FROM VRH_EMP_TCOLCON_REF Y
       WHERE Y.BDCODEMP = :premp AND
             Y.BDCODCOL = :prcol AND
             CAST(Y.BDREFCOL AS VARCHAR(6)) <=
                (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
                 FROM rdb$database
                )
       GROUP BY Y.BDCODEMP, Y.bdcodcol

  INTO
    :BDREFCOL;


  IF ((BDREFCOL IS NULL) OR (BDREFCOL = 0)) THEN
    BEGIN
      SELECT FIRST 1 Y.BDREFCOL
      FROM VRH_EMP_TCOLCON_REF Y
      WHERE Y.BDCODEMP = :premp AND
            Y.BDCODCOL = :prcol
      ORDER BY y.bdrefcol
      INTO
        :BDREFCOL;
    END

  SUSPEND;
END
^

/* Restore proc. body: SP_CONSULTA_EMP_POR_REF */
ALTER PROCEDURE SP_CONSULTA_EMP_POR_REF(PREMP INTEGER,
PRREFMICRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER)
 AS
DECLARE VARIABLE wref INTEGER;
BEGIN
   IF (prrefmicro IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);

   SELECT Y.BDCODEMP, MAX(Y.BDREFEMP)
          FROM TEMPRESAS_REF Y
          WHERE Y.BDCODEMP = :PREMP AND
                CAST(Y.BDREFEMP AS VARCHAR(6)) <=
                   (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES'))
                    FROM rdb$database
                   )
          GROUP BY Y.BDCODEMP
  INTO
    :BDCODEMP,
    :BDREFEMP;


  IF ((BDREFEMP IS NULL) OR (BDREFEMP = 0)) THEN
    BEGIN
      SELECT FIRST 1 Y.BDCODEMP, Y.BDREFEMP
      FROM TEMPRESAS_REF Y
      WHERE Y.BDCODEMP = :PREMP
      ORDER BY y.bdrefemp
      INTO
        :BDCODEMP,
        :BDREFEMP;
    END

  SUSPEND;
END
^

/* Restore proc. body: SP_CONSULTA_PLANO_CONTAS */
CREATE OR ALTER PROCEDURE SP_CONSULTA_PLANO_CONTAS (
    PRCODPLADARAO INTEGER,
    PRTODASCONTAS INTEGER,
    PRCONSOLIDADA VARCHAR(8000),
    PRFILTRO VARCHAR(1024),
    PREMPRESA INTEGER = 0)
RETURNS (
    BDCODPLAPADRAO INTEGER,
    BDCODTPLA INTEGER,
    BDCTALON VARCHAR(40),
    BDTIPCTA SMALLINT,
    BDNOMCTA VARCHAR(100),
    BDAPECTA VARCHAR(20),
    BDGRUPOCTA INTEGER,
    BDRELCTA INTEGER,
    BDFILTROGER VARCHAR(20),
    BDFORMULA VARCHAR(200),
    BDCONDICAO VARCHAR(100),
    BDPARTICIPANTE INTEGER,
    BDPERTENCECONTA INTEGER,
    BDCLANOM VARCHAR(140),
    BDCODSUBCONTA INTEGER,
    BDGRUPOSUBCONTA VARCHAR(10),
    BDCODNATSUBCONTA INTEGER,
    BDCTAEMPREENDIMENTOSIMOB DM_BOOLEAN,
    BDCTAUNIDADEIMOB DM_BOOLEAN,
    BDCTACAIXAPR DM_BOOLEAN,
    BDCTABANCOPR DM_BOOLEAN,
    BDCTATRANSPR DM_BOOLEAN,
    BDCARNELEAO DM_BOOLEAN)
as
declare variable WTIPCTA integer;
declare variable WSQL varchar(9000);
declare variable WPRIM integer;
declare variable WTAM integer;
declare variable WSQLAUX varchar(1024);
declare variable WCTALON varchar(40);
declare variable WTOTALCHAR integer;
declare variable WTOTALCHAR_ANT integer;
declare variable WCONSOLIDADA varchar(40);
declare variable WUSAPREP integer;
BEGIN
  if (PREMPRESA > 0) then
    BEGIN
      select first 1 COALESCE(BDCODMATRIZ, BDCODEMP) AS BDCODEMP
      from TEMPRESAS
      WHERE BDCODEMP = :prempresa
      INTO :prempresa;

      SELECT FIRST 1 BDCODEMP
      FROM VSUC_CONTAS_EMPRESA
      WHERE BDCODEMP = :prempresa
      INTO :WUSAPREP;

    END

  wsql = 'select bdCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDNOMCTA, BDAPECTA, ';
  wsql = wsql||' BDGRUPOCTA, BDRELCTA, BDFILTROGER, BDFORMULA, BDCONDICAO, BDPARTICIPANTE, ';
  wsql = wsql||' BDPERTENCECONTA, BDCLANOM, BDCODSUBCONTA, BDGRUPOSUBCONTA, BDCODNATSUBCONTA, ';
  wsql = wsql||' BDCTAEMPREENDIMENTOSIMOB, BDCTAUNIDADEIMOB, BDCTACAIXAPR, BDCTABANCOPR, BDCTATRANSPR, BDCARNELEAO ';

  IF ((TRIM(PRCONSOLIDADA) = '') OR (prconsolidada IS NULL)) THEN
    wsql = wsql||', null as BDCONSOLIDADA ';
  ELSE
    wsql = wsql||', case when (BDCODTPLA in ('||prconsolidada||')) and (BDTIPCTA = 2) then BDCTALON end as BDCONSOLIDADA ';

  wsql = wsql||'from PLANOS_TPLA X ';
  wsql = wsql||'where bdcodplapadrao = '||prcodpladarao||' ';
  if (wusaprep is not null) then
     wsql = wsql|| ' AND EXISTS(select first 1 BDCODEMP'
                || ' from PLANOS_TPLA P'
                || ' INNER JOIN vsuc_contas_empresa C ON (P.bdcodplapadrao = C.bdcodplapadrao AND P.bdcodtpla = C.bdcodtpla)'
                || ' where P.bdcodplapadrao = X.bdcodplapadrao AND P.bdctalon STARTING WITH X.bdctalon AND C.bdcodemp ='||prempresa||') ';
  IF (prfiltro <> '') THEN
     wsql = wsql||prfiltro;
  wsql = wsql||' Order By bdCTALON ASC ';

  wprim = 0;

  FOR EXECUTE STATEMENT wsql
      INTO :bdcodplapadrao, :bdcodtpla, :bdctalon, :bdtipcta, :bdnomcta, :bdapecta, :bdgrupocta, :bdrelcta, 
           :bdfiltroger, :bdformula, :bdcondicao, :bdparticipante, :bdpertenceconta, :bdclanom, :bdcodsubconta, :bdgruposubconta,
           :bdcodnatsubconta, :bdctaempreendimentosimob, :bdctaunidadeimob, :BDCTACAIXAPR, :BDCTABANCOPR, :BDCTATRANSPR, :BDCARNELEAO,
           :WSQLAUX DO
      BEGIN
        IF (wsqlaux IS NOT NULL) THEN
          wconsolidada = wsqlaux;

        IF (bdtipcta IN (0,2)) THEN
           BEGIN
             wtipcta = bdtipcta;
             IF (bdtipcta = 2) THEN
                SELECT CONTAR_CHAR FROM contar_char(:bdctalon, '.') INTO :wTotalChar;
           END
        ELSE
          IF ((wtipcta = 2) AND (bdtipcta = 1)) THEN
             BEGIN
               SELECT CONTAR_CHAR FROM contar_char(:bdctalon, '.') INTO :WTOTALCHAR_ANT;

               IF (WTOTALCHAR_ANT <= wTotalChar) THEN
                  wtipcta = 0;
             END

        IF (prtodascontas = 1) THEN
           SUSPEND;
        ELSE
        BEGIN
        IF ((prfiltro <> '') /*and (prconsolidada <> '')*/) THEN
           BEGIN
             IF (TRIM(wconsolidada) <> '') THEN
                BEGIN
                  wtam = strlen(TRIM(wconsolidada));
                  IF ((bdtipcta = 0) OR ((bdtipcta = 1) AND (wtipcta = 0))) THEN
                     SUSPEND;
                  ELSE
                  IF (bdtipcta = 2) THEN
                     BEGIN
                       wsqlaux = 'select bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdnomcta, bdapecta, ';
                       wsqlaux = wsqlaux||'bdgrupocta, bdrelcta, bdfiltroger, bdformula, bdcondicao, BDPARTICIPANTE, ';
                       wsqlaux = wsqlaux||'BDPERTENCECONTA, BDCLANOM, BDCODSUBCONTA, BDGRUPOSUBCONTA, BDCODNATSUBCONTA, BDCTAEMPREENDIMENTOSIMOB, BDCTAUNIDADEIMOB ';
                       wsqlaux = wsqlaux||'from planos_tpla X ';
                       wsqlaux = wsqlaux||'where bdcodplapadrao = '||prcodpladarao;
                       wsqlaux = wsqlaux||' and substring(bdctalon from 1 for '||strlen(bdctalon)||') = '''||bdctalon||'''';
                         if (wusaprep is not null) then
                           wsqlaux = wsqlaux || ' AND EXISTS(select first 1 BDCODEMP'
                                             || ' from PLANOS_TPLA P'
                                             || ' INNER JOIN vsuc_contas_empresa C ON (P.bdcodplapadrao = C.bdcodplapadrao AND P.bdcodtpla = C.bdcodtpla)'
                                             || ' where P.bdcodplapadrao = X.bdcodplapadrao AND P.bdctalon STARTING WITH X.bdctalon AND C.bdcodemp ='||prempresa||') ';
                       wsqlaux = wsqlaux||' order by bdctalon';

                       FOR EXECUTE STATEMENT wsqlaux
                           INTO :bdcodplapadrao, :bdcodtpla, :bdctalon, :bdtipcta, :bdnomcta, :bdapecta,
                                :bdgrupocta, :bdrelcta, :bdfiltroger, :bdformula, :bdcondicao, :bdparticipante,
                                :bdpertenceconta, :bdclanom, :bdcodsubconta, :bdgruposubconta, :bdcodnatsubconta, :bdctaempreendimentosimob, :bdctaunidadeimob DO
                           BEGIN
                             IF (bdtipcta = 2) THEN
                                SUSPEND;
                             ELSE
                             IF ((SUBSTRING(bdctalon FROM 1 FOR wtam) = TRIM(wconsolidada)) AND (bdtipcta = 1)) THEN
                                SUSPEND;
                           END
                     END
                END
             ELSE
                IF ((bdtipcta IN (0,2)) OR
                   (bdtipcta = 1 AND wtipcta = 0) /*or
                   ((bdtipcta = 1) and (prfiltro <> ''))*/) THEN
                   SUSPEND;
           END
        ELSE
        IF ((bdtipcta = 2) AND (prfiltro <> '')) THEN
           BEGIN
             IF (wprim = 0) THEN
                BEGIN
                  wprim = 1;
                  IF (wconsolidada = '') THEN
                     BEGIN
                       wsqlaux = 'select bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdnomcta, bdapecta, ';
                       wsqlaux = wsqlaux||'bdgrupocta, bdrelcta, bdfiltroger, bdformula, bdcondicao, BDPARTICIPANTE, ';
                       wsqlaux = wsqlaux||'BDPERTENCECONTA, BDCLANOM, BDCODSUBCONTA, BDGRUPOSUBCONTA, BDCODNATSUBCONTA, BDCTAEMPREENDIMENTOSIMOB, BDCTAUNIDADEIMOB ';
                       wsqlaux = wsqlaux||'from planos_tpla ';
                       wsqlaux = wsqlaux||'where bdcodplapadrao = '||prcodpladarao;
                       wsqlaux = wsqlaux||' and substring(bdctalon from 1 for '||strlen(bdctalon)||') = '''||bdctalon||'''';
          
                       FOR EXECUTE STATEMENT wsqlaux
                           INTO :bdcodplapadrao, :bdcodtpla, :bdctalon, :bdtipcta, :bdnomcta, :bdapecta,
                                :bdgrupocta, :bdrelcta, :bdfiltroger, :bdformula, :bdcondicao, :bdparticipante,
                                :bdpertenceconta, :bdclanom, :bdcodsubconta, :bdgruposubconta, :bdcodnatsubconta, :bdctaempreendimentosimob, :bdctaunidadeimob DO
                           SUSPEND;
                     END
                  ELSE
                     SUSPEND;
                END
           END
        ELSE
           IF (TRIM(wconsolidada) <> '') THEN
              BEGIN
                wtam = strlen(TRIM(wconsolidada));
                IF (bdtipcta IN (0,2)) THEN
                   SUSPEND;
                ELSE
                   IF (((SUBSTRING(bdctalon FROM 1 FOR wtam) = TRIM(wconsolidada)) AND (wtipcta IN (1,2))) OR (wtipcta = 0)) THEN
                      SUSPEND;
              END
           ELSE
              IF ((bdtipcta IN (0,2)) OR
                 (bdtipcta = 1 AND wtipcta = 0) /*or
                 ((bdtipcta = 1) and (prfiltro <> ''))*/) THEN
                 SUSPEND;

        END /* todas as contas */

      END
END
^

/* Restore proc. body: SP_CONSULTA_TERCEIRO */
ALTER PROCEDURE SP_CONSULTA_TERCEIRO(PRCODTER INTEGER,
PRREF INTEGER,
PRWHERETER VARCHAR(20000))
 RETURNS(BDCODTER INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCGCTER VARCHAR(18),
BDREFEMP INTEGER,
BDAPELIDOTER VARCHAR(20),
BDNOMETER VARCHAR(100),
BDLOGRTER VARCHAR(15),
BDENDTER DM_BDENDERECO,
BDNUMTER DM_NUMEND,
BDCOMPTER DM_BDCOMPENDERECO,
BDCEPTER VARCHAR(9),
BDBAITER VARCHAR(60),
BDDDDTER VARCHAR(3),
BDFONETER DM_BDTELEFONE,
BDFAXTER DM_BDTELEFONE,
BDEMAILTER DM_BDEMAIL,
BDIETER VARCHAR(20),
BDDATACADTER DATE,
BDIMTER VARCHAR(16),
BDPRURALTER VARCHAR(5),
BDENQSIMPLESFEDTER INTEGER,
BDINSCSUFRAMATER VARCHAR(10),
BDCODGPS INTEGER,
BDCODCID INTEGER,
BDCODPAIS INTEGER,
BDDESCPAIS VARCHAR(60),
BDDDDFAXTER VARCHAR(3),
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2),
BDNOMCID VARCHAR(40),
BDORGAOPUBLICO VARCHAR(5),
BDCODTIPO INTEGER,
BDCODIBGE INTEGER,
BDCODAQUIRUR INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
    IF (prref IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prref,NULL,NULL);

    wSql = ' select ';
    wSql = wSql || 'TER.BDCODTER, ';
    wSql = wSql || 'TER.BDCODPLAPADRAO, ';
    wSql = wSql || 'TER.BDCODTPLA, ';
    wSql = wSql || 'TER.BDCGCTER, ';
    wSql = wSql || 'TER.BDREFEMP, ';
    wSql = wSql || 'TER.BDAPELIDOTER, ';
    wSql = wSql || 'TER.BDNOMETER, ';
    wSql = wSql || 'TER.BDLOGRTER, ';
    wSql = wSql || 'TER.BDENDTER, ';
    wSql = wSql || 'TER.BDNUMTER, ';
    wSql = wSql || 'TER.BDCOMPTER, ';
    wSql = wSql || 'TER.BDCEPTER, ';
    wSql = wSql || 'TER.BDBAITER, ';
    wSql = wSql || 'TER.BDDDDTER, ';
    wSql = wSql || 'TER.BDFONETER, ';
    wSql = wSql || 'TER.BDFAXTER, ';
    wSql = wSql || 'TER.BDEMAILTER, ';
    wSql = wSql || 'TER.BDIETER, ';
    wSql = wSql || 'TER.BDDATACADTER, ';
    wSql = wSql || 'TER.BDIMTER, ';
    wSql = wSql || 'TER.BDPRURALTER, ';
    wSql = wSql || 'TER.BDENQSIMPLESFEDTER, ';
    wSql = wSql || 'TER.BDINSCSUFRAMATER, ';
    wSql = wSql || 'TER.BDCODGPS, ';
    wSql = wSql || 'TER.BDCODCID, ';
    wSql = wSql || 'TER.BDCODPAIS, ';
    wSql = wSql || 'TER.BDDESCPAIS, ';
    wSql = wSql || 'TER.BDDDDFAXTER, ';
    wSql = wSql || 'CID.BDCODUF, ';
    wSql = wSql || 'UF.BDSIGLAUF, ';
    wsql = wsql || 'CID.BDNOMCID,';
    wsql = wsql || 'TER.BDORGAOPUBLICO,';
    wsql = wsql || 'TER.BDCODTIPO,';
    wsql = wsql || 'CID.BDCODIBGE,';
    WSQL = WSQL || 'TER.BDCODAQUIRUR';
 
    wSql = wsql || ' FROM vw_tterceiro TER ';

    wSql = wsql || ' left outer join tcidade CID';
    wSql = wsql || ' on (TER.BDCODCID = CID.bdCODCID)';
    wSql = wsql || ' left outer join tuf UF';
    wSql = wsql || ' on (CID.BDCODUF = UF.bdCODUF)';

  wwhere = '';
  IF (prcodter IS NOT NULL AND prcodter <> 0) THEN
    wwhere = wwhere || ' TER.bdcodTER = '||prcodter;

  IF (prwhereTER IS NOT NULL AND prwhereTER <> '')  THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere ||prwhereTER;
    END

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By TER.bdcodTER';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODTER,
    :BDCODPLAPADRAO,
    :BDCODTPLA,
    :BDCGCTER,
    :BDREFEMP,
    :BDAPELIDOTER,
    :BDNOMETER, 
    :BDLOGRTER, 
    :BDENDTER, 
    :BDNUMTER, 
    :BDCOMPTER,
    :BDCEPTER, 
    :BDBAITER, 
    :BDDDDTER, 
    :BDFONETER,
    :BDFAXTER,
    :BDEMAILTER,
    :BDIETER,
    :BDDATACADTER,
    :BDIMTER,
    :BDPRURALTER,
    :BDENQSIMPLESFEDTER,
    :BDINSCSUFRAMATER,
    :BDCODGPS,
    :BDCODCID,
    :BDCODPAIS,
    :bddescpais, 
    :BDDDDFAXTER,
    :BDCODUF,
    :BDSIGLAUF,
    :bdnomcid,
    :BDORGAOPUBLICO,
    :BDCODTIPO,
    :BDCODIBGE,
    :BDCODAQUIRUR
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

CREATE OR ALTER PROCEDURE SP_CONSULTA_TERCEIRO_MATRIZ (
    PRCODTER INTEGER,
    PRCGCTER TYPE OF COLUMN TTERCEIRO.BDCGCTER)
RETURNS (
    BDCODTER INTEGER,
    BDCGCTER TYPE OF COLUMN TTERCEIRO.BDCGCTER)
AS
BEGIN
  IF (prCGCTER IS NULL) THEN
    SELECT FIRST 1 SUBSTRING(BDCGCTER FROM 1 FOR 10) FROM TTERCEIRO WHERE BDCODTER = :prCODTER INTO :prCGCTER;
  ELSE
    prCGCTER = SUBSTRING(:prCGCTER FROM 1 FOR 10);
  SELECT FIRST 1 BDCODTER, BDCGCTER FROM TTERCEIRO WHERE SUBSTRING(BDCGCTER FROM 1 FOR 10) = ''||:prCGCTER||'' ORDER BY BDCGCTER INTO :BDCODTER, :BDCGCTER;
  SUSPEND;
END
^

/* Restore proc. body: SP_CONSULTACIDADE */
ALTER PROCEDURE SP_CONSULTACIDADE(PRCIDADE INTEGER)
 RETURNS(BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDANIVCID VARCHAR(4),
BDDDD INTEGER,
BDCODEST INTEGER,
BDCODIBGE INTEGER,
BDCODFED INTEGER,
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2),
BDDESCUF VARCHAR(40))
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN


    wSql = ' select ';
    wSql = wsql || 'TCID.BDCODCID, ';
    wSql = wsql || 'TCID.BDNOMCID, ';
    wSql = wsql || 'TCID.BDANIVCID, ';
    wSql = wsql || 'TCID.BDDDD, ';
    wSql = wsql || 'TCID.BDCODEST, ';
    wSql = wsql || 'TCID.BDCODIBGE, ';
    wSql = wsql || 'TCID.BDCODFED, ';
    wSql = wsql || 'TCID.BDCODUF, ';
    wSql = wsql || 'UF.BDSIGLAUF, ';
    wSql = wsql || 'UF.BDDESCUF ';

    wSql = wsql || ' FROM TCIDADE TCID';

    wSql = wsql || ' left outer join tuf UF';
    wSql = wsql || '  on (TCID.BDCODUF = UF.bdCODUF)';

  wwhere = '';
  IF (prcidade IS NOT NULL AND prcidade <> 0) THEN
    wwhere = wwhere || ' tcid.bdcodcid = '||prcidade;

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By tcid.bdcodcid';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODCID,
    :BDNOMCID,
    :BDANIVCID,
    :BDDDD,
    :BDCODEST,
    :BDCODIBGE,
    :BDCODFED,
    :BDCODUF,
    :BDSIGLAUF,
    :BDDESCUF
  DO
  SUSPEND;

END
^

/* Restore proc. body: SP_CONSULTAEMPRESAS */
CREATE OR ALTER procedure SP_CONSULTAEMPRESAS (
    PRREFMICRO integer,
    PRCODEMP varchar(10240),
    PRINATIVAS smallint,
    PREXCLUIREMP integer = 0)
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDCNPJEMP varchar(18),
    BDDATAINIATIVEMP date,
    BDORGAOEMP varchar(8),
    BDDATAREGEMP date,
    BDDATACONSTEMP date,
    BDOMIE DM_BOOLEAN,
    BDDESCCARTEMP varchar(40),
    BDDATAFIMATIVEMP date,
    BDCODPLAPADRAO integer,
    BDCODHIST integer,
    BDCODCENTROS integer,
    BDCODCID integer,
    BDCODCONT integer,
    BDCODNATJUR integer,
    BDCODCNAE integer,
    BDNOMEMP DM_BDNOMEMP,
    BDNOMFANEMP varchar(200),
    BDNOMREDUZEMP DM_BDNOMREDUZEMP,
    BDAPEEMP DM_BDAPEMP,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP varchar(9),
    BDDDDEMP integer,
    BDFONEEMP DM_BDTELEFONE,
    BDFAXEMP DM_BDTELEFONE,
    BDEMAILEMP DM_BDEMAIL,
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDLOGREMP varchar(15),
    BDIEEMP varchar(20),
    BDIMEMP varchar(20),
    BDSITEMP varchar(5),
    BDDDDFAXEMP integer,
    BDNOMCID varchar(40),
    BDCODUF integer,
    BDNOMECONT varchar(40),
    BDSIGLAUF varchar(2),
    BDANTECIPICMS integer,
    BDANTECIPICMSCT integer,
    BDDESCUF varchar(40),
    BDCODPLANOONLINE integer,
    BDCODENQFED integer,
    BDPERSONALIZACAO varchar(120),
    BDCODCONTEF integer,
    BDLIVRO varchar(15),
    BDFOLHA varchar(15),
    BDNOMECARTORIO varchar(100),
    BDDATACADEMP date,
    BDTIPOAPURACAORET integer,
    BDCODPLATRIB integer,
    BDTRANMANUAL varchar(5),
    BDTIPOAPURACAORETIR integer,
    BDCODESC integer,
    BDCODPLAPADRAOREF integer,
    BDCODIBGE integer,
    BDFORMATRIBUTACAO integer,
    BDSTATUS_ES integer,
    BDABRIRRATEIO DM_BOOLEAN,
    BDNAOPERMITERATEIOGRUPO DM_BOOLEAN,
    BDINTEGRANET DM_BOOLEAN,
    BDIGNORAREDISS DM_BOOLEAN,
    BDDATAINIESOCIAL date,
    BDOPCAOESOCIAL integer,
    BDDDDCELULAREMP integer,
    BDCELULAREMP DM_BDTELEFONE,
    BDCODCLI integer,
    BDDATAOBRIGREINF date,
    BDNRTCE varchar(20),
    BDSTATUSEMP integer,
    BDQTDBACKUPEMP integer,
    BDMATRIZNAOCADSIS varchar(5),
    BDSITUACAOESOCIAL integer,
    BDCODGIARS integer,
    BDINCORPORADORAS DM_BOOLEAN,
    BDISSLEGAL varchar(5),
    BDISSLEGALSCI varchar(5),
    BDSCIREPORT DM_BOOLEAN,
    BDTIPOCAEPF integer,
    BDEXCLUIREMP varchar(5),
    BDCODTIPOCLI integer,
    BDCODZONA integer,
    BDNOMEZONA varchar(40),
    BDCARNELEAO DM_BOOLEAN,
    BDCEIEMP DM_CNPJ_CPF,
    BDGRUPO integer,
    BDENVIOS2210 integer,
    BDENVIOS2220 integer,
    BDENVIOS2240 integer,
    BDDATAINICIALTR date,
    BDTIPOAPURACAORETIRTOM integer,
    BDIMENDES varchar(5),
    BDCARACTRIBUTARIA integer,
    BDFORMATRIBUTACAOVW integer,
    BDESTABFORABASE DM_BOOLEAN,
    BDDESCCNAE varchar(200),
    BDIAT_PISCOF_SEM_ICMS DM_BOOLEAN,
    BDEXIBEINFOCOLLAN varchar(5),
    BDSENHAIAT varchar(30),
    BDSENHAARQEMP integer,
    BDSENHAARQEMPSEP varchar(1),
    BDDOCAUXILIAR varchar(19),
    BDDATAINIPARALISADESIF date,
    BDDATAFIMPARALISADESIF date,
    BDTIPODEPENDENCIADESIF varchar(200),
    BDCONTABPROPRIADESIF boolean,
    BDCODDEPENDENCIADESIF varchar(20),
    BDCNPJDEPUNIFICADORADESIF integer,
    BDESOCIALRT varchar(5),
    BDCONTAAZUL DM_BOOLEAN,
    BDNAOMAJORARIRCSLL boolean,
    BDCODCLATRI integer,
    BDCONTABILIZASCP DM_BOOLEAN,
    BDCALCAD13UMAVEZFE boolean,
    BDREGIBSCBS Boolean)
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(20000);
declare variable WPOS integer;
declare variable WTUDO integer;
declare variable WSHOWEMP integer;
declare variable WUSER integer;
BEGIN
  --Jaques aqui: otimizando um pouco este SQL
  SELECT x.bdcodusu FROM SP_GET_USUARIO x INTO :wUser;

  IF ((wUser IS NULL) OR (wUser = 0)) THEN
     wTudo = 1;
  ELSE
     BEGIN
       -- Gilberto - 13/04/2021 - Retornar apenas empresas configuradas para o usuário
       select count(BDCODUSU) from tusuario
       where bdcodusu = :wUser
       and coalesce(bdshowempusu,0) = 0
       into :wtudo;
       wshowemp = 0;

       --temos que ver se o usuário tem alguma empresa configurada...
       -- se o wTudo for igual a 0 indica que quer que exiba apenas as empresas dele...
       -- mas as vezes o usuário marca e quando olha, tem apenas as empresas do grupo do usuário
       -- e ele não salva isso no usuário
       if (wtudo = 0) then
          begin
             select count(TEU.bdcodemp)
             from tempresa_usuario TEU
             where TEU.bdcodusu = :wuser
             into :wtudo;

             --então se o wTudo aqui vier com 0, então ele deve ir como 1, para considerar o restante
             -- se vier com algum valor, então zera ele, assim vai considerar como que tem empresa mesmo
             if (wTudo = 0) then
                begin
                   wTudo = 1;
                end
             else
                begin
                   wTudo = 0;
                end
          end

       -- Gilberto - 13/04/2021 - Retornar apenas empresas configuradas para o grupo do usuário
       if (wtudo > 0) then
       begin
         select count(TGRP.bdcodgrupo) from tgrupousuario TGRP
         INNER JOIN tgrupousuario_usuario tusu ON (tusu.bdcodgrupo = tgrp.bdcodgrupo AND tusu.bdcodusu = :wUser)
         where coalesce(TGRP.bdshowempgrp,0) = 0
         into :wtudo;
         wshowemp = 1;
       end

       -- Gilberto - 13/04/2021 - Retornar apenas empresas configuradas para o Escritório
       if (wtudo > 0) then
       begin
       SELECT COUNT(tgrp.bdcodgrupo) FROM tgrupousuario tgrp
       INNER JOIN tgrupousuario_usuario tusu ON (tusu.bdcodgrupo = tgrp.bdcodgrupo AND tusu.bdcodusu = :wUser)
       WHERE tgrp.bdcodesc IS NULL
       -- 0 - Mostrar empresas que não pertencem ao grupo
       -- 1 - Esconder empresas que não pertencem ao grupo
       OR ((tgrp.bdimpemp IS NULL) OR (tgrp.bdimpemp = 0))
       INTO :wtudo;
         wshowemp = 2;
       end
     END

  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);

  wSql = ' select ';
  IF (wtudo = 0) THEN
     wsql = wsql||' distinct ';
  wSql = wSql||'TEMP.BDCODEMP, TEMP.BDCODMATRIZ, TEMP.BDCNPJEMP, TEMP.BDDATAINIATIVEMP, ';
  wSql = wSql||'tref.BDORGAOEMP, tref.BDDATAREGEMP,  TEMP.BDDATACONSTEMP, TREF.BDDESCCARTEMPREF, ';
  wSql = wSql||'TEMP.BDDATAFIMATIVEMP, TEMP.BDFORMATRIBUTACAOEMP, TEMP.BDNRTCE, TEMP.BDOMIE, UPPER(TEMP.BDSCIREPORT), ';
  wSql = wSql||'tref.BDCODPLAPADRAO, tref.BDCODHIST, tref.BDCODCENTROS,  ';
  wSql = wSql||'tref.BDCODCID, tref.BDCODCONT,  ';
  wSql = wSql||'tref.BDCODNATJUR, tref.BDCODCNAE, tref.BDNOMEMP, tref.BDNOMREDUZEMP, tref.BDAPEEMP, tref.BDENDEMP,  ';
  wSql = wSql||'tref.BDNUMEMP, tref.BDBAIEMP, tref.BDCEPEMP, tref.BDDDDEMP, tref.BDFONEEMP,  ';
  wSql = wSql||'tref.BDFAXEMP, tref.BDEMAILEMP, tref.BDCOMPLEMP, tref.BDLOGREMP, tref.BDIEEMP, tref.BDIMEMP,  ';
  wSql = wSql||'tref.BDSITEMP, tref.BDDDDFAXEMP,  ';
  wSql = wSql||'TCID.BDNOMCID, TCID.BDCODUF,  ';
  wSql = wSql||'TCON.BDNOMECONT, test.BDSIGLAUF, test.bdANTECIPICMS, test.BDANTECIPICMSCT, test.BDDESCUF, ';
  wSql = wSql||'tref.bdcodplanoonline, enq.bdcodenqfed, ';
    
  wSql = wSql||'case when (tesc.bdprintesc = 1) then tesc.bdnomesc ';
  wSql = wSql||    ' when (tesc.bdprintesc = 2) then tesc.bdnomesc||'||''' - '''||'||(select first 1 BDPERSONALIZACAO from TPERSONALIZACAO) ';
  wSql = wSql||    ' else (select first 1 BDPERSONALIZACAO from TPERSONALIZACAO) end bdpersonalizacao, ';

  wsql = wsql||' tref.BDCODCONTEF, tref.BDLIVRO, tref.BDFOLHA, tref.BDNOMECARTORIO, TEMP.BDDATACADEMP, ger.BDTIPOAPURACAORET, tref.bdcodplatrib, ';
  wsql = wsql||' TEMP.BDTRANMANUAL, ger.BDTIPOAPURACAORETIR, TEMP.bdcodesc, tref.BDCODPLAPADRAOREF, TCID.BDCODIBGE, TEMP.BDSTATUS_ES, ';
  wSQL = wSQL||' tref.BDABRIRRATEIO, BDNAOPERMITERATEIOGRUPO, '; --alt:13677 - 15/03/2016 - Adicionados parâmetros. Pedro
  wSql = wSql||' TEMP.BDINTEGRANET, ger.BDIGNORAREDISS, ';
  wSql = wSql||' TEMP.BDDATAINIESOCIAL, FAS.BDOPCAOESOCIAL, FAS.BDGRUPO, COALESCE(SST.BDENVIOS2210, 0) BDENVIOS2210, COALESCE(SST.BDENVIOS2220, 0) BDENVIOS2220, COALESCE(SST.BDENVIOS2240, 0) BDENVIOS2240, SST.BDDATAINICIALTR, ';
  wSql = wSql||' TREF.BDDDDCELULAREMP, tref.BDCELULAREMP, temp.bdcodcli, temp.BDDATAOBRIGREINF, tref.BDNOMFANEMP, ';
  wSql = wSql||' TEMP.BDSTATUSEMP, TEMP.BDQTDBACKUPEMP, TEMP.BDMATRIZNAOCADSIS, TEMP.BDSITUACAOESOCIAL, TCID.BDCODGIARS, temp.BDINCORPORADORAS, temp.BDISSLEGAL, temp.BDISSLEGALSCI, ';
  wSql = wSql||' TEMP.BDTIPOCAEPF, ';
  wsql = wsql||' TEMP.bdexcluiremp, cli.bdcodtipocli, tref.BDCODZONA, Z.BDNOMEZONA, TEMP.BDCARNELEAO, TEMP.BDCEIEMP, ger.BDTIPOAPURACAORETIRTOM, TEMP.BDIMENDES, TREF.BDCARACTRIBUTARIA , Enq.BDFORMATRIBUTACAO  BDFORMATRIBUTACAOVW, TEMP.BDESTABFORABASE, ';
  wsql = wsql||' CNAE.BDDESCCNAE, TREF.BDIAT_PISCOF_SEM_ICMS, TREF.BDEXIBEINFOCOLLAN, TEMP.BDSENHAIAT,  ';
  wsql = wsql||' TEMPPAR.BDSENHAARQEMP, TEMPPAR.BDSENHAARQEMPSEP, TREF.BDDOCAUXILIAR,  ';
  wsql = wsql||' TREF.BDDATAINIPARALISADESIF, TREF.BDDATAFIMPARALISADESIF, TREF.BDTIPODEPENDENCIADESIF, TREF.BDCONTABPROPRIADESIF,';
  wsql = wsql||' TREF.BDCODDEPENDENCIADESIF, TREF.BDCNPJDEPUNIFICADORADESIF, FAS.BDESOCIALRT, TEMP.BDCONTAAZUL, TREF.BDNAOMAJORARIRCSLL,TEMPSOCIAL.BDCODCLATRI, TREF.BDCONTABILIZASCP, TEMPPAR.BDCALCAD13UMAVEZFE, ';
  wsql = wSQL||' Coalesce(TREF.BDREGIBSCBS, ''FALSE'') BDREGIBSCBS ';
  wSql = wSql||' from TEMPRESAS TEMP ';
  wSql = wSql||' inner join VW_TEMPRESAS_REF_MAX_MIN REF on (REF.BDCODEMP = TEMP.BDCODEMP) ';
  wSql = wSql||' inner JOIN tempresas_ref TREF ON (TREF.bdcodemp = temp.bdCODEMP AND TREF.bdrefemp = ref.bdrefemp) ';
  wSql = wSql||' left outer join VRHF_BASE_TEMPPAR TEMPPAR on (TREF.bdcodemp = TEMPPAR.bdcodemp) and (TREF.bdrefemp = TEMPPAR.bdrefemp) ' ;
  wSql = wSql||' left outer join VRHF_BASE_TEMPESOCIAL TEMPSOCIAL on (TREF.bdcodemp = TEMPSOCIAL.bdcodemp) and (TREF.bdrefemp = TEMPSOCIAL.bdrefemp) ' ;

  wSql = wSql||' left outer join VW_TENQFED Enq  on (Enq.bdcodemp = temp.bdcodemp) ';
  wSql = wSql||' left outer join TCIDADE TCID on (TCID.BDCODCID = Tref.BDCODCID) ';
  wSql = wSql||' left outer join TCONTADOR_PADRAO TCON  on (Tcon.BDCODCONT = tref.BDCODCONT)';
  wSql = wSql||' left outer join TUF test  on (test.BDCODUF = TCID.BDCODUF) ';

  wSql = wSql||' left outer join tescritorio tesc on (tesc.bdcodesc = temp.bdcodesc) ';
  wSql = wSql||' left outer join VW_VEF_BASE_TEMPPARGER ger on ger.bdcodemp = temp.bdcodemp ';
  wSql = wSql||' left outer join VRH_ESOCIAL_TFASEAMENTO FAS on FAS.bdcodemp = temp.bdcodemp ';
  wSql = wSql||' left outer join VRH_EMP_ESOCIAL_TCONFIGSST SST on SST.bdcodemp = temp.bdcodemp ';
  wSql = wSql||' left outer join VFIN_BASE_TCLIENTE cli on (cli.bdcodcli = temp.bdcodcli) ';
  wSql = wSql||' left outer join TZONA Z on (tref.BDCODCID = Z.BDCODCID and tref.BDCODZONA = Z.BDCODZONA) ';
  wSql = wSql||' LEFT OUTER JOIN TCNAE CNAE ON TREF.BDCODCNAE = CNAE.BDCODCNAE ';

  IF (wtudo = 0) THEN
     BEGIN
    -- Gilberto - 13/04/2021 - Retornar apenas empresas configuradas para o usuário
    if (wshowemp = 0) then
    begin
      wSql = wSql||'inner join tempresa_usuario TEU on (TEU.bdcodemp = temp.bdcodemp and TEU.bdcodusu = '||Trim(cast(:wUser as VARCHAR(8)))||')';
    end
    else
    -- Gilberto - 13/04/2021 - Retornar apenas empresas configuradas para o grupo do usuário
    if (wshowemp = 1) then
    begin
      wSql = wSql||'inner join tgrupousuario_usuario TGRP on (TGRP.bdcodusu  = '||Trim(cast(:wUser as VARCHAR(8)))||')';
      wSql = wSql||'inner join tempresa_grupousuario TEGU on (TEGU.bdcodemp = temp.bdcodemp and TEGU.bdcodgrupo = TGRP.bdcodgrupo)';
    end
    else
    -- Gilberto - 13/04/2021 - Retornar apenas empresas configuradas para o Escritório
    if (wshowemp = 2) then
    begin
       wSql = wSql||'inner join tgrupousuario tgrp on (tgrp.bdcodesc = temp.bdcodesc) ';
       wSql = wSql||'inner join tgrupousuario_usuario tusu on (tusu.bdcodusu  = '||Trim(cast(:wUser as VARCHAR(8)))||') and (tusu.bdcodgrupo = tgrp.bdcodgrupo) ';
    end
     END

  wwhere = '';

/*  if (prcodemp is not null and prcodemp <> 0) then
     wwhere = wwhere || ' TEMP.bdcodemp = '||prcodemp;*/
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '0') AND (prcodemp <> '')) THEN
     BEGIN
       SELECT pos FROM pos('=', :prcodemp) INTO :wpos;

       IF (wPos = 0) THEN
          SELECT pos FROM pos(' in (', :prcodemp) INTO :wpos;

       IF (wPos = 0) THEN
          SELECT pos FROM pos(' between ', :prcodemp) INTO :wpos;

       IF (wPos = 0) THEN
          SELECT pos FROM pos(' is ', LOWER(:prcodemp)) INTO :wpos;

       IF (wpos > 0) THEN
          wwhere = wwhere||' ('||prcodemp||') ';
       ELSE
          wwhere = wwhere||' TEMP.bdcodemp = '||prcodemp;
     END

  /* filra empresas inativas */
  IF (prinativas = 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
 
    wwhere = wwhere||' ((UPPER(tref.BDSITEMP) = '''||'FALSE'')or(tref.bdsitemp is null)) ';
     END
  else
  IF (prinativas = 1) THEN
  BEGIN
    IF (wwhere <> '') THEN
       wwhere = wwhere||' and ';
 
    wwhere = wwhere||' UPPER(tref.BDSITEMP) = '''||'TRUE''';
  END

  -- #149491 - Antony Rairon (14/04/2021) - Filtra clientes eventuais
  IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
  wwhere = wwhere||' (cli.BDCODTIPOCLI <> 3 or cli.BDCODTIPOCLI is null) ';

  -- Processo de exclusão em massa de empresas pelo servidor
  if (prexcluiremp <> 1) then
  begin
    if (wWhere <> '') then
       wWhere = wwhere||' and ';
    wwhere = wwhere||'((TEMP.BDEXCLUIREMP is null)or(upper(TEMP.BDEXCLUIREMP)<>'''||'TRUE'||'''))';
  end

  /*
  for select BDCODUSU from sp_get_usuario
  into
    :wcodusu
  do

   filtra as empresas por usuario
  if (wcodusu is not null and wcodusu <> 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||'((exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||') and '||
                          'exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||' and Y.BDCODEMP = TEMP.BDCODEMP)) '||
                         'or '||
                         '(not exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||'))'||
                         ') ';
     end   */

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By TEMP.BDCODEMP';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODMATRIZ,
    :BDCNPJEMP,
    :BDDATAINIATIVEMP,
    :BDORGAOEMP,
    :BDDATAREGEMP,
    :BDDATACONSTEMP,
    :BDDESCCARTEMP,
    :BDDATAFIMATIVEMP,
    :BDFORMATRIBUTACAO,
    :BDNRTCE,
    :BDOMIE,
    :BDSCIREPORT,
    :BDCODPLAPADRAO,
    :BDCODHIST,
    :BDCODCENTROS,
    :BDCODCID,
    :BDCODCONT,
    :BDCODNATJUR,
    :BDCODCNAE,
    :BDNOMEMP,
    :BDNOMREDUZEMP,
    :BDAPEEMP,
    :BDENDEMP,
    :BDNUMEMP,
    :BDBAIEMP,
    :BDCEPEMP,
    :BDDDDEMP,
    :BDFONEEMP,
    :BDFAXEMP,
    :BDEMAILEMP,
    :BDCOMPLEMP,
    :BDLOGREMP,
    :BDIEEMP,
    :BDIMEMP,
    :BDSITEMP,
    :BDDDDFAXEMP,
    :BDNOMCID,
    :BDCODUF,
    :BDNOMECONT,
    :BDSIGLAUF,
    :bdANTECIPICMS,
    :BDANTECIPICMSCT,
    :BDDESCUF,
    :bdcodplanoonline,
    :bdcodenqfed,
    :bdpersonalizacao,
    :bdcodcontef,
    :BDLIVRO,
    :BDFOLHA,
    :BDNOMECARTORIO,
    :BDDATACADEMP,
    :BDTIPOAPURACAORET,
    :BDCODPLATRIB,
    :BDTRANMANUAL,
    :BDTIPOAPURACAORETIR,
    :bdcodesc,
    :BDCODPLAPADRAOREF,
    :BDCODIBGE,
    :BDSTATUS_ES,
    :BDABRIRRATEIO,
    :BDNAOPERMITERATEIOGRUPO,
    :BDINTEGRANET,
    :BDIGNORAREDISS,
    :BDDATAINIESOCIAL,
    :BDOPCAOESOCIAL,
    :BDGRUPO,
    :BDENVIOS2210,
    :BDENVIOS2220,
    :BDENVIOS2240,
    :BDDATAINICIALTR,
    :BDDDDCELULAREMP,
    :BDCELULAREMP,
    :BDCODCLI,
    :BDDATAOBRIGREINF,
    :BDNOMFANEMP,
    :BDSTATUSEMP, 
    :BDQTDBACKUPEMP,
    :BDMATRIZNAOCADSIS,
    :BDSITUACAOESOCIAL,
    :BDCODGIARS,
    :BDINCORPORADORAS,
    :BDISSLEGAL,
    :BDISSLEGALSCI,
    :BDTIPOCAEPF,
    :bdexcluiremp,
    :BDCODTIPOCLI,
    :BDCODZONA,
    :BDNOMEZONA,
    :BDCARNELEAO,
    :BDCEIEMP,
    :BDTIPOAPURACAORETIRTOM,
    :BDIMENDES,
    :BDCARACTRIBUTARIA,
    :BDFORMATRIBUTACAOVW,
    :BDESTABFORABASE,
    :BDDESCCNAE,
    :BDIAT_PISCOF_SEM_ICMS,
    :BDEXIBEINFOCOLLAN,
    :BDSENHAIAT,
    :BDSENHAARQEMP,
    :BDSENHAARQEMPSEP,
    :BDDOCAUXILIAR,
    :BDDATAINIPARALISADESIF,
    :BDDATAFIMPARALISADESIF,
    :BDTIPODEPENDENCIADESIF,
    :BDCONTABPROPRIADESIF,
    :BDCODDEPENDENCIADESIF,
    :BDCNPJDEPUNIFICADORADESIF,
    :BDESOCIALRT,
    :BDCONTAAZUL,
    :BDNAOMAJORARIRCSLL,
    :BDCODCLATRI,
    :BDCONTABILIZASCP,
    :BDCALCAD13UMAVEZFE,
    :BDREGIBSCBS
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^


/* Restore proc. body: SP_CONSULTAEMPRESAS_SEARCH */
ALTER PROCEDURE SP_CONSULTAEMPRESAS_SEARCH(PRREFMICRO INTEGER,
PRCODEMP INTEGER,
PRINATIVAS SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDAPEEMP VARCHAR(20),
BDIEEMP VARCHAR(20))
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);


  wSql = ' select TEMP.BDCODEMP, TEMP.BDCNPJEMP, TREF.bdapeemp, '||
                 'tref.BDIEEMP '||
      ' from TEMPRESAS TEMP'||
      ' left outer join vw_tempresas_ref tref  on (tref.bdcodemp = temp.bdcodemp)';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wwhere = wwhere || ' TEMP.bdcodemp = '||prcodemp;

  /* filra empresas inativas */
  IF (prinativas IS NOT NULL AND prinativas <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = 'UPPER(tref.BDSITEMP) = '''||'FALSE''';
     END


  /*
  for select BDCODUSU from sp_get_usuario
  into
    :wcodusu
  do

   filtra as empresas por usuario
  if (wcodusu is not null and wcodusu <> 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||'((exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||') and '||
                          'exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||' and Y.BDCODEMP = TEMP.BDCODEMP)) '||
                         'or '||
                         '(not exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||'))'||
                         ') ';
     end   */

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By TEMP.BDCODEMP';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCNPJEMP,
    :BDAPEEMP,
    :BDIEEMP
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: SP_CONSULTAEMPRESAS_SIS */
CREATE OR ALTER procedure SP_CONSULTAEMPRESAS_SIS (
    PRREFMICRO integer,
    PRCODEMP integer,
    PRINATIVAS smallint)
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDCNPJEMP varchar(18),
    BDDATAINIATIVEMP date,
    BDORGAOEMP varchar(8),
    BDDATAREGEMP date,
    BDDATACONSTEMP date,
    BDDESCCARTEMP varchar(40),
    BDDATAFIMATIVEMP date,
    BDCODPLAPADRAO integer,
    BDCODHIST integer,
    BDCODCENTROS integer,
    BDCODCID integer,
    BDCODCONT integer,
    BDCODNATJUR integer,
    BDCODCNAE integer,
    BDNOMEMP DM_BDNOMEMP,
    BDNOMREDUZEMP DM_BDNOMREDUZEMP,
    BDAPEEMP DM_BDAPEMP,
    BDNOMFANEMP varchar(200),
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP varchar(9),
    BDDDDEMP integer,
    BDFONEEMP DM_BDTELEFONE,
    BDFAXEMP DM_BDTELEFONE,
    BDDDDCELULAREMP integer,
    BDCELULAREMP DM_BDTELEFONE,
    BDEMAILEMP DM_BDEMAIL,
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDLOGREMP varchar(15),
    BDIEEMP varchar(20),
    BDIMEMP varchar(20),
    BDSITEMP varchar(5),
    BDDDDFAXEMP integer,
    BDNOMCID varchar(40),
    BDCODUF integer,
    BDNOMECONT varchar(40),
    BDSIGLAUF varchar(2),
    BDANTECIPICMS integer,
    BDANTECIPICMSCT integer,
    BDDESCUF varchar(40),
    BDRETINSS varchar(5),
    BDVLRMININSS numeric(15,2),
    BDCODCONFATIVO integer,
    BDSUFRAMA varchar(9),
    BDCODACESSOSN varchar(12),
    BDPERFILSPED integer,
    BDATIVIDADESPED integer,
    BDCODCONFIPI integer,
    BDCODCONFIRLP integer,
    BDCODCONFDIMESC integer,
    BDCODPORTEEMP integer,
    BDCODAPUCON integer,
    BDCODESCCONT integer,
    BDCODREGAPU integer,
    BDCONTPRODEC varchar(5),
    BDNRPARPRODEC integer,
    BDLANBCICMSVALCONT varchar(5),
    BDLANBCICMSISEOUT integer,
    BDLANCLISAISER varchar(5),
    BDLANPROENT varchar(5),
    BDLANPROSAI varchar(5),
    BDMOVSER varchar(5),
    BDPERCISS numeric(15,6),
    BDREDPERCISS numeric(15,6),
    BDMOVIRRF varchar(5),
    BDALIQIRRF numeric(15,6),
    BDISENTOIRRF numeric(15,6),
    BDEMPINATIVA varchar(5),
    BDEMPDIFPAPEL varchar(5),
    BDEMPBARREST varchar(5),
    BDVERIFICARNOTASJALAN integer,
    BDCODPLANOONLINE integer,
    BDLRISSSN numeric(15,6),
    BDCOMERCIO varchar(5),
    BDINDUSTRIA varchar(5),
    BDSERVICO varchar(5),
    BDANEXOIII varchar(5),
    BDANEXOIV varchar(5),
    BDANEXOV varchar(5),
    BDCODENQFED integer,
    BDSUBSTRIB integer,
    BDCODCONFDACON integer,
    BDCODCONFICMSSPED integer,
    BDCODCONFCIAP integer,
    BDREDBCICMSENT numeric(15,6),
    BDREDBCICMSSAI numeric(15,6),
    BDICMSMONO DM_BOOLEAN,
    BDCODCONFDASN integer,
    BDRETPARPIS varchar(5),
    BDRETPARCOFINS varchar(5),
    BDRETPARCSLL varchar(5),
    BDRETPARIRRF varchar(5),
    BDRETPARISSQN varchar(5),
    BDRETPARINSS varchar(5),
    BDRETPARFUNRURAL varchar(5),
    BDTIPOAPURACAO integer,
    BDSOMFREBASEICMS varchar(5),
    BDSOMFREVLRCONTAB varchar(5),
    BDCODPLATROCA integer,
    BDCODPLACFOP integer,
    BDCODCONFBLOCOP integer,
    BDCREDPRESUMIDO varchar(5),
    BDTERMOACEITE varchar(5),
    BDANTECIPAIMPOSTO varchar(5),
    BDTIPODECLARANTEDMED integer,
    BDREGISTROANSDMED integer,
    BDNUMEROCNESDMED integer,
    BDDTOBRIGSPEDCONT date,
    BDTIPOAPURACAORET integer,
    BDTIPOAPURACAORETIR integer,
    BDDTOBRIGSPEDICMS date,
    BDCODCONTEF integer,
    BDLIVRO varchar(15),
    BDFOLHA varchar(15),
    BDNOMECARTORIO varchar(100),
    BDLANCAPARCELAAUTO varchar(5),
    BDCODIGOPLA integer,
    BDINDATIV integer,
    BDTRANMANUAL varchar(5),
    BDIMPORTARVALORESICMSSN DM_BOOLEAN,
    BDDIFALIQ varchar(5),
    BDDIFALIQBASEEM integer,
    BDANEXOVI DM_BOOLEAN,
    BDCODPLATRIB integer,
    BDCODPLAPADRAOREF integer,
    BDINDNATPJ integer,
    BDCODIBGE integer,
    BDFORMATRIBUTACAO integer,
    BDSOMAPISCOFVLRCONT DM_BOOLEAN,
    BDSOMAIIVLRCONT DM_BOOLEAN,
    BDMANTERPARCELAS DM_BOOLEAN,
    BDCODPLANOINCONS integer,
    BDABRIRRATEIO DM_BOOLEAN,
    BDNAOPERMITERATEIOGRUPO DM_BOOLEAN,
    BDINTEGRANET DM_BOOLEAN,
    BDSOMAIPIPROD DM_BOOLEAN,
    BDSOMAICMSVLRCONT DM_BOOLEAN,
    BDCODPLAE115 integer,
    BDDATACADEMP date,
    BDCODCLATRI integer,
    BDDATAOBRIGREINF date,
    BDSOMASTPROD DM_BOOLEAN,
    BDCALCANTICMS varchar(5),
    BDCONSIPIBC varchar(5),
    BDIMPICMSST varchar(5),
    BDANEXOIII_2018 varchar(5),
    BDANEXOIV_2018 varchar(5),
    BDANEXOV_2018 varchar(5),
    BDSTATUSEMP integer,
    BDQTDBACKUPEMP integer,
    BDIMPORTARISS varchar(5),
    BDIMPORTARCTESAI DM_BOOLEAN,
    BDNAOVALIDACONTRATO DM_BOOLEAN,
    BDINCORPORADORAS DM_BOOLEAN,
    BDALIQINSS DM_NUMERIC_7_4_ALIQ,
    BDCODPLANOCONFSN integer,
    BDGERAC490 varchar(5),
    BDTIPOCAEPF integer,
    BDCODPLACATSP integer,
    BDOPTANTERET DM_BOOLEAN,
    BDMANTERC197CATSP varchar(5),
    BDCODCLASSESTAB integer,
    BDCODPLASEFSC integer,
    BDAPURAGIAST DM_BOOLEAN,
    BDCARNELEAO DM_BOOLEAN,
    BDEXPINCENTFISCAIS DM_BOOLEAN,
    BDCODCONFGIAFPE integer,
    BDCALCSTIMPSUB DM_BOOLEAN,
    BDSTRET DM_NUMERIC_7_4_ALIQ,
    BDTIPOAPURACAORETIRTOM integer,
    BDSCIREPORT DM_BOOLEAN,
    BDCONTPISCOFCAIXA DM_BOOLEAN,
    BDDOCAUXILIAR varchar(19),
    BDSOMAAFRMMVLRCONT DM_BOOLEAN,
    BDCODPLAAJUSTE integer,
    BDVENDACOOP DM_BOOLEAN,
    BDNFCOM_CONSOLIDADA boolean,
    BDDIFALIQ_NAOGERA_C197 boolean,
    BDCONTABILIZASCP DM_BOOLEAN,
    BDUSARTAGVNF boolean,
    BDREGIBSCBS boolean,
    BDCONTABGUIAMUN boolean)
as
declare variable WSQL varchar(10240);
declare variable WWHERE varchar(20000);
declare variable WPAR varchar(100);
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);
    wSql = ' select ';
    wSql = wsql || 'Tref.BDCODEMP, ';
    wSql = wsql || 'tref.BDCODMATRIZ, ';
    wSql = wsql || 'tref.BDCNPJEMP, ';
    wSql = wsql || 'tref.BDDATAINIATIVEMP, ';
    wSql = wsql || 'tref.BDORGAOEMP, ';
    wSql = wsql || 'tref.BDDATAREGEMP, ';
    wSql = wsql || 'tref.BDDATACONSTEMP, ';  --alt:14844 - Adicionado campo BDDATACONSTEMP na consulta. Ana - 05/08/2016
    wSql = wsql || 'tref.BDDESCCARTEMP, ';
    wSql = wsql || 'tref.BDDATAFIMATIVEMP, ';
    wSql = wsql || 'tref.BDCODPLAPADRAO, ';
    wSql = wsql || 'tref.BDCODHIST, ';
    wSql = wsql || 'tref.BDCODCENTROS, ';
    wSql = wsql || 'tref.BDCODCID, ';
    wSql = wsql || 'tref.BDCODCONT, ';
    wSql = wsql || 'tref.BDCODNATJUR, ';
    wSql = wsql || 'tref.BDCODCNAE, ';
    wSql = wsql || 'tref.BDNOMEMP, ';
    wSql = wsql || 'tref.BDNOMREDUZEMP, ';
    wSql = wsql || 'tref.BDAPEEMP, ';
    wSql = wsql || 'tref.bdNOMFANEMP, ';
    wSql = wsql || 'tref.BDENDEMP, ';
    wSql = wsql || 'tref.BDNUMEMP, ';
    wSql = wsql || 'tref.BDBAIEMP, ';
    wSql = wsql || 'tref.BDCEPEMP, ';
    wSql = wsql || 'tref.BDDDDEMP, ';
    wSql = wsql || 'tref.BDFONEEMP, ';
    wSql = wsql || 'tref.BDFAXEMP, ';
    wSql = wsql || 'tref.BDDDDCELULAREMP, ';
    wSql = wsql || 'tref.BDCELULAREMP, ';
    wSql = wsql || 'tref.BDEMAILEMP, ';
    wSql = wsql || 'tref.BDCOMPLEMP, ';
    wSql = wsql || 'tref.BDLOGREMP, ';
    wSql = wsql || 'tref.BDIEEMP, ';
    wSql = wsql || 'tref.BDIMEMP, ';
    wSql = wsql || 'tref.BDSITEMP, ';
    wSql = wsql || 'tref.BDDDDFAXEMP, ';
    wSql = wsql || 'Tref.BDNOMCID, ';
    wSql = wsql || 'Tref.BDCODUF, ';
    wSql = wsql || 'Tref.BDNOMECONT, ';
    wSql = wsql || 'tref.BDSIGLAUF, ';
    wSql = wsql || 'tref.bdANTECIPICMS, ';
 wSql = wsql || 'tref.BDANTECIPICMSCT, '; 
    wSql = wsql || 'tref.BDDESCUF, ';
    wSql = wsql || 'tref.BDTRANMANUAL, ';
    wSQL = wsql || 'tref.BDDATACADEMP, ';
    wSQL = wsql || 'tref.BDTIPOCAEPF, ';

    wSql = wsql || 'trefsis.bdretinss, ';
    wSql = wsql || 'trefsis.bdvlrmininss, ';
    wSql = wsql || 'trefsis.bdSUFRAMA, ';
    wSql = wsql || 'trefsis.bdcodacessosn, ';
    wSql = wsql || 'trefsis.bdperfilsped, ';
    wSql = wsql || 'trefsis.bdatividadesped, ';
    wSql = wsql || 'trefsis.BDCODCONFIPI, ';
    wSql = wsql || 'trefsis.BDCODCONFIRLP, ';
    wSql = wsql || 'trefsis.BDCODCONFDIMESC, ';
    wSql = wsql || 'trefsis.BDCODPORTEEMP, ';
    wSql = wsql || 'trefsis.BDCODAPUCON, ';
    wSql = wsql || 'trefsis.BDCODESCCONT, ';
    wSql = wsql || 'trefsis.BDCODREGAPU, ';
    wSql = wsql || 'trefsis.BDCONTPRODEC, ';
    wSql = wsql || 'trefsis.BDNRPARPRODEC, ';
    --wSql = wsql || 'trefsis.BDDIAVCTOEMPSC, ';
    wSql = wsql || 'trefsis.BDCODCONFATIVO, ';
    --harry 17-02-2011
    wSql = wsql || 'trefsis.BDLANBCICMSVALCONT, ';
    wSql = wsql || 'trefsis.BDLANBCICMSISEOUT, ';
    wSql = wsql || 'trefsis.BDLANCLISAISER, ';
    wSql = wsql || 'trefsis.BDLANPROENT, ';
    wSql = wsql || 'trefsis.BDLANPROSAI, ';
    wSql = wsql || 'trefsis.BDMOVSER, ';
    wSql = wsql || 'trefsis.BDPERCISS, ';
    wSql = wsql || 'trefsis.BDREDPERCISS, ';
    wSql = wsql || 'trefsis.BDMOVIRRF, ';
    wSql = wsql || 'trefsis.BDALIQIRRF, ';
    wSql = wsql || 'trefsis.BDISENTOIRRF, ';
    wSql = wsql || 'trefsis.BDEMPINATIVA, ';
    wSql = wsql || 'trefsis.BDEMPDIFPAPEL, ';
    wSql = wsql || 'trefsis.BDEMPBARREST, ';
    wSql = wsql || 'trefsis.BDVERIFICARNOTASJALAN, ';

    wSql = wsql || 'tref.bdcodplanoonline, ';

    wSql = wsql || 'trefsis.bdlrisssn, ';
    wSql = wsql || 'trefsis.bdcomercio, ';
    wSql = wsql || 'trefsis.bdindustria, ';
    wSql = wsql || 'trefsis.bdservico, ';
    wSql = wsql || 'trefsis.bdanexoiii, ';
    wSql = wsql || 'trefsis.bdanexoiv, ';
    wSql = wsql || 'trefsis.bdanexov, ';
    wSql = wsql || 'enq.BDCODENQFED, ';
    wSql = wsql || 'case when (not (enq.BDFORMATRIBUTACAO is null)) then enq.BDFORMATRIBUTACAO else tref.BDFORMATRIBUTACAO end, ';
    wSql = wsql || 'TREFSIS.BDSUBSTRIB, ';
    wSql = wsql || 'TREFSIS.bdcodconfdacon, ';
    wSql = wsql || 'TREFSIS.bdcodconficmssped, ';
    wSql = wsql || 'TREFSIS.BDCODCONFCIAP, ';
    wSql = wsql || 'TREFSIS.BDREDBCICMSENT, ';
    wSql = wsql || 'TREFSIS.BDREDBCICMSSAI, ';
    wSql = wsql || 'TREFSIS.BDICMSMONO, ';
    wSql = wsql || 'TREFSIS.BDCODCONFDASN, ';

    wSql = wsql || 'TREFSIS.BDRETPARPIS, ';
    wSql = wsql || 'TREFSIS.BDRETPARCOFINS, ';
    wSql = wsql || 'TREFSIS.BDRETPARCSLL, ';
    wSql = wsql || 'TREFSIS.BDRETPARIRRF, ';
    wSql = wsql || 'TREFSIS.BDRETPARISSQN, ';
    wSql = wsql || 'TREFSIS.BDRETPARINSS, ';
    wSql = wsql || 'TREFSIS.BDRETPARFUNRURAL, ';
    wSql = wsql || 'TREFSIS.bdtipoapuracao, ';
    wSql = wsql || 'TREFSIS.BDSOMFREVLRCONTAB, ';
    wSql = wsql || 'TREFSIS.BDSOMFREBASEICMS, ';
    wSql = wsql || 'TREFSIS.BDCODPLATROCA, ';
    wSql = wsql || 'TREFSIS.bdcodplacfop, ';
    wSql = wsql || 'TREFSIS.bdcodconfblocop, ';
    wSql = wSql || 'TREFSIS.bdcredpresumido, ';
    wSql = wSql || 'TREFSIS.bdTERMOACEITE, '; --#Alt:84445 (04/06/2018) Patrício H. Lehn
    wSql = wSql || 'TREFSIS.bdantecipaimposto, ';
    wSql = wsql || 'TREFSIS.BDTIPODECLARANTEDMED, ';
    wSql = wsql || 'TREFSIS.BDREGISTROANSDMED, ';
    wSql = wsql || 'TREFSIS.BDNUMEROCNESDMED, ';
    wSql = wsql || 'TREFSIS.BDDTOBRIGSPEDCONT, ';
    wSql = wsql || 'TREFSIS.BDTIPOAPURACAORET, ';
    wSql = wsql || 'TREFSIS.BDTIPOAPURACAORETIR, ';
    wSql = wSql || 'TREFSIS.BDDTOBRIGSPEDICMS, ';
    wsql = wsql || 'TREF.BDCODCONTEF, ';
    wsql = wsql || 'TREF.BDLIVRO, ';
    wsql = wsql || 'TREF.BDFOLHA, ';
    wsql = wsql || 'TREF.BDNOMECARTORIO, ';
    wsql = wsql || 'TREFSIS.BDLANCAPARCELAAUTO, ';
    wsql = wsql || 'TREFSIS.BDCODIGOPLA, ';
    wSql = wsql || 'TREFSIS.BDINDATIV, ';
    wSql = wSql || 'parinteg.BDIMPORTARVALORESICMSSN, ';
    wSql = wSql || 'parinteg.BDDIFALIQ, ';
    wSql = wSql || 'parinteg.BDDIFALIQBASEEM, ';
    wSql = wSql || 'TREFSIS.BDANEXOVI, ';
    wsql = wsql || 'tref.bdcodplatrib, ';
    wSQL = wSQL || 'TREF.BDCODPLAPADRAOREF, '; --alt:11108 - Adicionado novo campo na tabela e na SP. Pedro
    wSql = wsql || 'TREFSIS.BDINDNATPJ, ';
    wSql = wsql || 'TREF.BDCODIBGE, '; --Sol: 11334 Patrick T. Sá 03/07/2015. Traz o código do IBGE para verificar o tipo de ISS da empresa
     /*
      Sol: 11439 Patrick T. Sá 03/07/2015. Retorna campos para verificar
      se é para somar ou não o imposto de importação(II). Parametros incluidos no cadastro de empresas.
    */
    wSql = wSql || 'parinteg.BDSOMAPISCOFVLRCONT, ';
    wSql = wSql || 'parinteg.BDSOMAIIVLRCONT, ';
    wsql = wsql || 'TREFSIS.BDMANTERPARCELAS, ';
    wsql = wsql || 'TREFSIS.BDCODPLANOINCONS, ';
    wSQL = wSQL || 'tref.BDABRIRRATEIO, '; --alt:13677 - 15/03/2016 - Adicionados parâmetros. Pedro
    wSQL = wSQL || 'tref.BDNAOPERMITERATEIOGRUPO, '; --alt:13677 - 15/03/2016 - Adicionados parâmetros. Pedro
    wSQL = wSQL || 'tref.BDINTEGRANET, '; --alt:14035 - Adicionado parâmetro para o IntegraNet. Everton
    wSQL = wSQL || 'parinteg.BDSOMAIPIPROD, ';
    wSql = wSql || 'parinteg.BDSOMAICMSVLRCONT, ';
    wSql = wSql || 'parinteg.BDCODPLAE115, ';
    wSql = wSql || 'tesocial.BDCODCLATRI, ';
    wSql = wSql || 'tref.BDDATAOBRIGREINF, ';
    wSQL = wSQL || 'parinteg.BDSOMASTPROD, ';
    wSql = wSql || 'parinteg.BDCALCANTICMS, ';
    wSql = wSql || 'parinteg.BDCONSIPIBC, ';
    WSQL = WSQL || 'parinteg.BDIMPICMSST, ';
    wSql = wsql || 'trefsis.bdanexoiii_2018, ';
    wSql = wsql || 'trefsis.bdanexoiv_2018, ';
    wSql = wsql || 'trefsis.bdanexov_2018, ';
    wSQL = wsql || 'tref.BDSTATUSEMP, ';   --#Alt:16965 - Carlos Mello (06/10/2017)
    wSQL = wsql || 'tref.BDQTDBACKUPEMP, '; --#Alt:16965 - Carlos Mello (06/10/2017)
    wSql = wSql || 'parinteg.BDIMPORTARISS, ';
    wSql = wSql || 'parinteg.BDIMPORTARCTESAI, ';
    wSql = wSql || 'parinteg.BDNAOVALIDACONTRATO, ';
    wSql = wsql || 'tref.BDINCORPORADORAS,trefsis.BDALIQINSS,TREFSIS.BDCODPLANOCONFSN, ';
    wSql = wsql || 'trefsis.BDGERAC490,  ';
    wSql = wsql || 'trefsis.BDCODPLACATSP,  ';
    wSql = wsql || 'trefsis.BDOPTANTERET, ';
    wSql = wsql || 'trefsis.BDMANTERC197CATSP,  ';
    wSql = wsql || 'trefsis.BDCODCLASSESTAB, ';
    wSql = wsql || 'trefsis.BDCODPLASEFSC, ';
    wSql = wSql || 'TREFSIS.BDAPURAGIAST, ';
    wSql = wSql || 'tref.BDCARNELEAO, ';
    wSql = wSql || 'ConfSPED.BDEXPINCENTFISCAIS, ';
    wSql = wSql || 'trefsis.BDCODCONFGIAFPE, ';
    wSql = wsql || 'trefsis.BDCALCSTIMPSUB, ';
    wSQL = wsql || 'BDSTRET, ';
    wSql = wsql || 'TREFSIS.BDTIPOAPURACAORETIRTOM, ';
    wSql = wSql || 'TREF.BDSCIREPORT, ';
    wSql = wSql || 'TREFSIS.BDCONTPISCOFCAIXA, ';
    wSql = wSql || 'TREF.BDDOCAUXILIAR, ';
    wSql = wSql || 'parinteg.BDSOMAAFRMMVLRCONT, ';


    wSql = wSql || 'parinteg.BDCODPLAAJUSTE, ';
    wSql = wSql || 'parinteg.BDVENDACOOP,  ' ;
    wSql = wSql || 'ConfSPED.BDNFCOM_CONSOLIDADA,  ' ;
    wSql = wSql || 'parinteg.BDDIFALIQ_NAOGERA_C197, ';
    wSql = wSql || 'tref.BDCONTABILIZASCP, ';
    wSql = wSql || 'parinteg.BDUSARTAGVNF, ';
    wsql = wSQL || 'TREF.BDREGIBSCBS, ';
    wsql = wSQL || 'TREFSIS.BDCONTABGUIAMUN ';

/*
       parger.BDLANBCICMSVALCONT,
       parger.BDLANBCICMSISEOUT,
       parger.BDLANCLISAISER,
       parger.BDLANPROENT,
       parger.BDLANPROSAI,
       parger.BDMOVSER,
       parger.BDPERCISS,
       parger.BDREDPERCISS,
       parger.BDMOVIRRF,
       parger.BDALIQIRRF,
       parger.BDISENTOIRRF,
       parger.BDEMPINATIVA,
       parger.BDEMPDIFPAPEL,
       parger.BDEMPBARREST,
       parger.BDVERIFICARNOTASJALAN
*/

  WPAR = 'from sp_consultaempresas('||prrefmicro;
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
    wpar = wpar||','||prcodemp||',';
  ELSE
    wpar = wpar||',null,';

  IF (prinativas IS NULL) THEN
     wpar = wpar||'null) tref';
  ELSE
    wpar = wpar||prinativas||') tref';

--  if (prinativas is null) then
--     wSql = wsql || ' from sp_consultaempresas('||prrefmicro||','||PRCODEMP||',null) tref';
--  else
--     wSql = wsql || ' from sp_consultaempresas('||prrefmicro||','||PRCODEMP||','||PRINATIVAS||') tref';

    wSql = wsql || wpar;

    wSql = wsql || ' left outer join vw_emp_ref_TOTAL TREFSIS on (TREFSIS.bdcodemp = tref.bdcodemp) ';
    wSql = wsql || ' left outer join VW_TENQFED Enq  on (Enq.bdcodemp = tref.bdcodemp) ';
    --wSql = wSql || ' left outer join VW_VEF_BASE_TEMPPARINTEG parinteg on ( parinteg.bdCodEmp = tref.bdCodEmp ) and ( parinteg.bdRefEmp = trefsis.bdRefEmp ) ';  Alt.: #224878 - Nao deve mais olhar a referencia, a view agora ja busca referencia correta...
    wSql = wSql || ' left outer join VW_VEF_BASE_TEMPPARINTEG parinteg on ( parinteg.bdCodEmp = tref.bdCodEmp ) ';
    wSql = wSql || ' left outer join VW_VRHF_BASE_TEMPESOCIAL tesocial on ( tesocial.bdcodemp = tref.bdcodemp) ';
    wSql = wSql || ' LEFT OUTER JOIN VW_INT_SPEDICMS_REF ConfSPED ON (ConfSPED.bdCODEMP = tref.bdCODEMP) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wwhere = wwhere || ' tref.bdcodemp = '||prcodemp;

  /* filra empresas inativas */
  IF (prinativas IS NOT NULL AND prinativas <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       wwhere = 'UPPER(tref.BDSITEMP) = '''||'FALSE''';
     END

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By tref.BDCODEMP';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODMATRIZ,
    :BDCNPJEMP,
    :BDDATAINIATIVEMP,
    :BDORGAOEMP,
    :BDDATAREGEMP,
    :BDDATACONSTEMP,
    :BDDESCCARTEMP,
    :BDDATAFIMATIVEMP,
    :BDCODPLAPADRAO,
    :BDCODHIST,
    :BDCODCENTROS,
    :BDCODCID,
    :BDCODCONT,
    :BDCODNATJUR,
    :BDCODCNAE,
    :BDNOMEMP,
    :BDNOMREDUZEMP,
    :BDAPEEMP,
    :bdNOMFANEMP,
    :BDENDEMP,
    :BDNUMEMP,
    :BDBAIEMP,
    :BDCEPEMP,
    :BDDDDEMP,
    :BDFONEEMP,
    :BDFAXEMP,
    :bddddcelularemp,
    :bdcelularemp,
    :BDEMAILEMP,
    :BDCOMPLEMP,
    :BDLOGREMP,
    :BDIEEMP,
    :BDIMEMP,
    :BDSITEMP,
    :BDDDDFAXEMP,
    :BDNOMCID,
    :BDCODUF,
    :BDNOMECONT,
    :BDSIGLAUF,
    :bdANTECIPICMS,
 :BDANTECIPICMSCT,
    :BDDESCUF,
    :BDTRANMANUAL,
    :BDDATACADEMP, 
    :BDTIPOCAEPF,

    :bdretinss,
    :bdvlrmininss,
    :BDSUFRAMA,
    :bdcodacessosn,
    :bdperfilsped,
    :bdatividadesped,

    :BDCODCONFIPI,
    :BDCODCONFIRLP,
    :BDCODCONFDIMESC,
    :BDCODPORTEEMP,
    :BDCODAPUCON,
    :BDCODESCCONT ,
    :BDCODREGAPU ,
    :BDCONTPRODEC ,
    :BDNRPARPRODEC ,
    --:BDDIAVCTOEMPSC,
    :BDCODCONFATIVO,

    --harry 17-02-2011
    :bdlanbcicmsvalcont,
    :bdlanbcicmsiseout,
    :bdlanclisaiser,
    :bdlanproent,
    :bdlanprosai,
    :bdmovser,
    :bdperciss,
    :bdredperciss,
    :bdmovirrf,
    :bdaliqirrf ,
    :bdisentoirrf,
    :bdempinativa ,
    :bdempdifpapel,
    :bdempbarrest,
    :bdverificarnotasjalan,
    :bdcodplanoonline,
    :bdlrisssn,
    :bdcomercio,
    :bdindustria,
    :bdservico,
    :bdanexoiii,
    :bdanexoiv,
    :bdanexov,
    :BDCODENQFED,
    :BDFORMATRIBUTACAO,
    :BDSUBSTRIB,
    :bdcodconfdacon,
    :bdcodconficmssped,
    :BDCODCONFCIAP,
    :BDREDBCICMSENT,
    :BDREDBCICMSSAI,
    :BDICMSMONO,
    :BDCODCONFDASN,

    :BDRETPARPIS,
    :BDRETPARCOFINS,
    :BDRETPARCSLL,
    :BDRETPARIRRF,
    :BDRETPARISSQN,
    :BDRETPARINSS,
    :BDRETPARFUNRURAL,
    :bdtipoapuracao,
    :bdsomfrevlrcontab,
    :bdsomfrebaseicms,
    :bdcodplatroca,
    :bdcodplacfop,
    :bdcodconfblocop,
    :bdcredpresumido,
    :bdtermoaceite,
    :bdantecipaimposto,
    :BDTIPODECLARANTEDMED,
    :BDREGISTROANSDMED,
    :BDNUMEROCNESDMED,
    :BDDTOBRIGSPEDCONT,
    :BDTIPOAPURACAORET,
    :BDTIPOAPURACAORETIR,
    :BDDTOBRIGSPEDICMS,
    :BDCODCONTEF,
    :BDLIVRO,
    :BDFOLHA,
    :BDNOMECARTORIO,
    :BDLANCAPARCELAAUTO,
    :BDCODIGOPLA,
    :BDINDATIV,
    :BDIMPORTARVALORESICMSSN,
    :BDDIFALIQ,
    :BDDIFALIQBASEEM,
    :BDANEXOVI,
    :BDCODPLATRIB,
    :BDCODPLAPADRAOREF,
    :BDINDNATPJ,
    :BDCODIBGE,
    :BDSOMAPISCOFVLRCONT,
    :BDSOMAIIVLRCONT,
    :BDMANTERPARCELAS,
    :bdcodplanoincons,
    :BDABRIRRATEIO,
    :BDNAOPERMITERATEIOGRUPO,
    :BDINTEGRANET,
    :BDSOMAIPIPROD,
    :BDSOMAICMSVLRCONT,
    :BDCODPLAE115,
    :BDCODCLATRI,
    :BDDATAOBRIGREINF,
    :BDSOMASTPROD,
    :BDCALCANTICMS,
    :BDCONSIPIBC,
    :BDIMPICMSST,
    :BDANEXOIII_2018,
    :BDANEXOIV_2018,
    :BDANEXOV_2018,
    :BDSTATUSEMP,
    :BDQTDBACKUPEMP,
    :BDIMPORTARISS,
    :BDIMPORTARCTESAI,
    :BDNAOVALIDACONTRATO,
    :BDINCORPORADORAS,
    :BDALIQINSS,
    :BDCODPLANOCONFSN,
    
    :BDGERAC490,
    :BDCODPLACATSP,
    :BDOPTANTERET,
    :BDMANTERC197CATSP,
    :BDCODCLASSESTAB,
    :BDCODPLASEFSC,
    :BDAPURAGIAST,
    :BDCARNELEAO,
    :BDEXPINCENTFISCAIS,
    :BDCODCONFGIAFPE,
    :BDCALCSTIMPSUB,
    :BDSTRET,
    :BDTIPOAPURACAORETIRTOM,
    :BDSCIREPORT,
    :BDCONTPISCOFCAIXA,
    :BDDOCAUXILIAR,
    :BDSOMAAFRMMVLRCONT,
    :BDCODPLAAJUSTE,
    :BDVENDACOOP,
    :BDNFCOM_CONSOLIDADA,
    :BDDIFALIQ_NAOGERA_C197,
    :BDCONTABILIZASCP,
    :BDUSARTAGVNF,
    :BDREGIBSCBS,
    :BDCONTABGUIAMUN
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

create or alter procedure SP_GERALOG_TEMP (
    PRORIGEM varchar(50),
    PRMENSAGEM varchar(50),
    PRSESSAO integer = 0)
as
BEGIN     
  if ((SELECT FIRST 1 TRIM(rdb$get_context('USER_SESSION', 'W_GERALOG_TEMP')) FROM rdb$database) = 'TRUE') then
    INSERT INTO TMP_VEF_BASE_TLOG_TEMP(BDORIGEM, BDMENSAGEM, BDSESSAO) VALUES(:prORIGEM,:prMENSAGEM, :prsessao);
END^

create or alter procedure SP_ATUALIZAR_TMP_TCADPRO (
    PRSESSAO integer not null,
    PRLANCAMENTOMANUAL DM_BOOLEAN not null,
    PRGERARINCONSISTENCIAS DM_BOOLEAN not null,
    PRREF integer,
    PRCODEMP integer,
    PRIDTERMINAL integer,
    PRALTERARSIT DM_BOOLEAN,
    PRALTERACST DM_BOOLEAN,
    PRISSEGREG DM_BOOLEAN,
    PRGERARLOG DM_BOOLEAN)
as
declare variable WSEGREGACAO varchar(5);
declare variable WCODORIGEMPROD integer;
declare variable WCNPJTERLAYOUT varchar(18);
declare variable WIETERLAYOUT varchar(20);
declare variable WCODTERENCONTRADO integer;
declare variable WCODENTRADA varchar(60);
declare variable WCODSAIDA varchar(60);
declare variable WDESCPRO varchar(200);
declare variable WCODPROENCONTRADO integer;
declare variable WEANPROUNICO varchar(20);
declare variable WDESCPROUNICO varchar(200);
declare variable WCODEMP integer;
declare variable WCODPROVINC integer;
declare variable WATUPROD DM_BOOLEAN;
declare variable WCADAUT DM_BOOLEAN;
declare variable WCODPLANOINCO integer;
declare variable WCODTIPO integer;
declare variable WCODATVMUN varchar(20);
declare variable WCODCIDEMP integer;
declare variable WCODSAIDAEXISTENTE varchar(60);
declare variable WCODPERSONALIZACAO integer;
declare variable WSEQ_PART integer;
declare variable WAPENASCODPRODSAI DM_BOOLEAN;
declare variable WVINCULOPART integer;
declare variable WCODTERLAYOUT integer;
declare variable WTER integer;
BEGIN                   
  /* A variavel não é utilizada aqui, use a "PRISSEGREG"...
  SELECT Coalesce(rdb$get_context('USER_SESSION', 'W_SEGREGACAO_FISCAL'),'FALSE') FROM rdb$database INTO WSEGREGACAO; */

  --RDB$SET_CONTEXT('USER_SESSION', 'W_REF_IMP_'||:prSESSAO, :prREF); -- Alt.: #138509 - Insere a refereência que vai ser usada depois na hora de buscar os produtos...
  UPDATE OR INSERT INTO TTHREAD (BDPARAM, BDVALORINT) VALUES ('W_REF_IMP_'||:prSESSAO, :prREF); -- Alt.: #201191 - Removida variavel de contexto...

  RDB$SET_CONTEXT('USER_SESSION', 'W_GERALOG_TEMP', :PRGERARLOG); /* criado o log para pegar lentidao no cliente */

  PRLANCAMENTOMANUAL     = UPPER(:PRLANCAMENTOMANUAL);
  PRGERARINCONSISTENCIAS = UPPER(:PRGERARINCONSISTENCIAS);
  PRALTERARSIT           = UPPER(:PRALTERARSIT);
  SELECT FIRST 1 P.BDCODIGO FROM TPERSONALIZACAO P INTO :wCodPersonalizacao;
  /*Se não houver produto na TMP_TCADPRO e/ou TMP_TCADPRO_PART, vai inserir os dados.*/
  --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a versão com a alteração abaixo corretamente.
  --EXECUTE PROCEDURE SP_CARREGAR_TMP_TCADPRO('FALSE');
--  UPDATE TMP_TCADPRO SET BDSEQ_PART = NULL WHERE BDSEQ_PART >= 0/*IS NOT NULL*/;
--  UPDATE TMP_TCADPRO_PART SET BDSEQ_PART = NULL WHERE BDSEQ_PART >= 0/*IS NOT NULL*/;
--  UPDATE TMP_TCADPRO SET BDSEQ_PART = NULL WHERE BDSEQ_PART IS NOT NULL; /*Camilla M. 24/05/2021 - Os updates eram desnecessários pois esse campo não é mais utilizado e acaba causando lentidão nas importações - GFISCO */
--  UPDATE TMP_TCADPRO_PART SET BDSEQ_PART = NULL WHERE BDSEQ_PART IS NOT NULL;
  IF (:PRLANCAMENTOMANUAL = 'TRUE') THEN
    BEGIN
      wCodProEncontrado = NULL;
      SELECT FIRST 1 V.BDEDITCHAVE, V.BDCODENTRADA, V.BDCNPJTERLAYOUT, v.bdIETERLAYOUT, V.BDDESCPROD, V.BDORIGEMPROD, V.BDCODTER FROM TMP_TCADPRO_A_VALIDAR V
      INTO :wCodProEncontrado, :wCodEntrada, :wCnpjTerLayout, :wIETERLAYOUT, :wDescPro, :wCodOrigemProd, :wCodTerEncontrado;
      IF ((:wCodProEncontrado IS NOT NULL) AND (:wCodProEncontrado > 0)) THEN
        begin
         EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TCADPRO','SP_INS_UPT_TMP_TCADPRO(1)',:PRSESSAO);
         EXECUTE PROCEDURE SP_INS_UPT_TMP_TCADPRO(:PRSESSAO, :prREF, '', :wCodEntrada, :wCodProEncontrado, COALESCE(:PRCODEMP, 0), :wCodTerEncontrado, :wCnpjTerLayout, :wIETERLAYOUT, :wDescPro, :wCodOrigemProd,  'INUP', 1, 'TRUE');
        end
      DELETE FROM TMP_TCADPRO_TEMP WHERE BDSESSAO = 0;
      EXIT;
    END        
  SELECT SP.BDCODPLANOINCONS, SP.BDATUPROD, SP.BDCADPROAUTO, sp.bdAPENASCODPRODSAI, sp.bdVINCULOPART
  FROM SP_GET_ACOES_INCONSISTENCIA(:PRCODEMP, :PRREF) SP
  INTO :wCodPlanoInco, :wAtuProd, :wCadAut, :wAPENASCODPRODSAI, :wVINCULOPART;

  IF (:wVINCULOPART IS NOT NULL) THEN
    --RDB$SET_CONTEXT('USER_SESSION', 'W_CONF_VINCULOPART_'||:prSESSAO, :wVINCULOPART); -- Alt.: #138509 - Caso nao encontre, guarda para consultar apenas uma vez...
    UPDATE OR INSERT INTO TTHREAD (BDPARAM, BDVALORINT) VALUES ('W_CONF_VINCULOPART_'||:prSESSAO, :wVINCULOPART); -- Alt.: #201191 - Removida variavel de contexto...

  SELECT FIRST 1 SP.BDCODCID FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :PRCODEMP, NULL) SP INTO :wCodCidEmp;

  IF (:PRGERARINCONSISTENCIAS = 'TRUE') THEN
    BEGIN
      EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TCADPRO','SP_GERAR_INCON_TCADPRO(2)',:PRSESSAO);
      EXECUTE PROCEDURE SP_GERAR_INCON_TCADPRO(:PRSESSAO, :PRCODEMP, :wCodPlanoInco, :PRREF, :PRIDTERMINAL);
      /*Apaga os registros inconsistentes da TMP
      DELETE FROM TMP_TCADPRO T
      WHERE T.BDSESSAO = :PRSESSAO
      AND EXISTS(
                 SELECT C.BDCODPROD
                 FROM VEF_INCON_TCADPRO C
                 WHERE C.BDSESSAO = T.BDSESSAO
                 AND C.BDCODPROD = T.BDEDITCHAVE
                );*/
    END      
  wSeq_Part = 0;
  FOR SELECT COALESCE(V.BDORIGEMPROD, 0),
             COALESCE(V.BDCNPJTERLAYOUT, ''),
             COALESCE(V.BDIETERLAYOUT, ''),
             COALESCE(V.BDCODENTRADA, ''),
             COALESCE(V.BDCODSAIDA, ''),
             COALESCE(TRIM(V.BDDESCPROD), ''),
             COALESCE(V.BDCODIGOEAN, ''),
             COALESCE(TRIM(V.BDDESCRICAOUNICA), ''),
             COALESCE(V.BDCODEMP, 0),
             COALESCE(V.BDCODTIPO, 0),
             COALESCE(V.BDCODMUNATVM, ''),
             COALESCE(V.bdCODTERLAYOUT, 0)
      FROM TMP_TCADPRO_A_VALIDAR V
      /*Se já tem BDEDITCHAVE não precisa procurar, o produto já foi vinculado(se existe) e se não existe já foi gerada uma nova chave*/
      WHERE ((V.BDEDITCHAVE IS NULL) OR (V.BDEDITCHAVE = 0))
      ORDER BY V.BDISPRODUNICO DESC
      INTO :WCODORIGEMPROD,
           :WCNPJTERLAYOUT,
           :wIETERLAYOUT,
           :WCODENTRADA,
           :WCODSAIDA,
           :WDESCPRO,
           :WEANPROUNICO,
           :WDESCPROUNICO,
           :WCODEMP,
           :wCodTipo,
           :wCodAtvMun,
           :wCODTERLAYOUT
  DO
  BEGIN
    wSeq_Part = :wSeq_Part + 1;
    wCodProVinc = NULL;
    wCodProEncontrado = NULL;          
    /* ********************************************************** VÍNCULO ********************************************************** */
    /* SERVIÇO */
    IF (:wCodTipo IN (118, 119, 120, 121, 122, 130)) THEN
      BEGIN
        SELECT FIRST 1 P.BDCODPROD
        FROM TMP_TCADPRO P
        WHERE P.BDCODSER = (
                            SELECT FIRST 1 T.BDCODSER
                            FROM TATVMUNICIPAL T
                            WHERE T.BDCODCID = :wCodCidEmp
                            AND T.BDCODMUNATVM = :wCodAtvMun
                            AND T.BDREFATVM = (SELECT MAX(A.BDREFATVM) FROM TATVMUNICIPAL A WHERE A.BDCODCID = T.BDCODCID AND A.BDCODMUNATVM = T.BDCODMUNATVM)
                           )
        INTO :wCodProEncontrado;
      END       
    /* ENTRADA */
    IF (:WCODORIGEMPROD = 0) THEN
      BEGIN
        IF ((:wCodProEncontrado IS NULL) OR (:wCodProEncontrado = 0)) THEN
          BEGIN
            wCodTerEncontrado = NULL;                          

            IF ((:WVINCULOPART = 1) AND -- ALT.: #222422 - VERIFICA O PARÂMETRO "CADASTRAR/VINCULAR PARTICIPANTES USANDO CPF/CNPJ + INSCRIÇÃO ESTADUAL", SE NÃO ESTIVER MARCADO, APENAS BUSCA PELO CNPJ...
                (:WIETERLAYOUT IS NOT NULL) AND (:WIETERLAYOUT <> '') AND (:WIETERLAYOUT <> '#')) THEN
              BEGIN
                    -- TENTA ENCONTRAR O PARTICIPANTE PRIMEIRO
                -- ALT.: #138509 - PRIMEIRO BUSCA POR CNPJ + IE...
                    SELECT FIRST 1 T.BDEDITCHAVE FROM TMP_TTERCEIRO T
                WHERE /*(T.BDCODTER = :WCODTERLAYOUT) OR*/ (T.BDCGCTER = :WCNPJTERLAYOUT)
                 AND (T.BDIETER = :WIETERLAYOUT) -- ALT.: #138509 - PARÂMETRO PARA VERIFICAR O PARTICIPANTE POR IE...
                ORDER BY T.BDCODTER, T.BDCGCTER, T.BDIETER -- ALT.: #206079 - DEVE ORDENAR POR CODIGO, POIS TINHA BASE COM PARTICIPANTE REPETIDO, COM O MESMO CNPJ E IE...
                    INTO :WCODTERENCONTRADO;
                  END
                                               
                IF (:WCODTERENCONTRADO IS NULL) THEN
              BEGIN -- ALT.: #138509 - CASO NÃO ENCONTRE PELO CNPJ + IE, TENTA PELO CNPJ APENAS...
                    SELECT FIRST 1 T.BDEDITCHAVE FROM TMP_TTERCEIRO T
                WHERE /*(T.BDCODTER = :WCODTERLAYOUT) OR*/ (T.BDCGCTER = :WCNPJTERLAYOUT)
                ORDER BY T.BDCODTER, T.BDCGCTER, T.BDIETER -- ALT.: #206079 - DEVE ORDENAR POR CODIGO, POIS TINHA BASE COM PARTICIPANTE REPETIDO, COM O MESMO CNPJ E IE...
                    INTO :WCODTERENCONTRADO;
                  END

            -- TENDO O CÓDIGO DO PARTICIPANTE, PODE TENTAR ENCONTRAR VÍNCULO NA TMP_TCADPRO_PART
            IF (:WCODTERENCONTRADO IS NOT NULL) THEN
              BEGIN        
                -- PODE TENTAR ENCONTRAR POR CÓDIGO DE TERCEIRO, CÓDIGO DE ENTRADA E DESCRIÇÃO DO PRODUTO
                IF ((:wDescPro <> '') AND (:wDescPro <> '#')) THEN
                  BEGIN
                    SELECT FIRST 1 P.BDCODPROD
                    FROM TMP_TCADPRO_PART P
                    WHERE P.BDCODTER        = :WCODTERENCONTRADO
                    AND   P.bdcodentrada    = :wCodEntrada
                    AND   P.bddescprodbusca = :wdescpro
                    ORDER BY BDCODENTRADA,BDDESCPRODBUSCA,BDCODTER,BDCODPROD
                    INTO :wCodProEncontrado;
                  END             
                -- E SE NÃO CONSEGUIR, PODE TENTAR POR CÓDIGO DE TERCEIRO, CÓDIGO DE ENTRADA E EAN DO PRODUTO DA TMP_TCADPRO
                IF (((:wCodProEncontrado IS NULL) OR (:wCodProEncontrado = 0)) AND (:wEanProUnico <> '') AND (:wEanProUnico <> '#')) THEN
                  BEGIN
                    SELECT FIRST 1 PP.BDCODPROD
                    FROM TMP_TCADPRO_PART PP
                    INNER JOIN TMP_TCADPRO P ON(P.BDCODPROD = PP.BDCODPROD)
                    WHERE PP.bdcodter = :wCodTerEncontrado
                    AND PP.bdcodentrada = :wCodEntrada
                    AND P.BDCODIGOEAN = :wEanProUnico
                    ORDER BY P.BDCODIGOEAN, P.BDCODPROD
                    INTO :wCodProEncontrado;
                  END    
                IF (Upper(:PRISSEGREG) = 'TRUE') then
                  BEGIN
                    IF (:wcodproencontrado IS NULL) then
                       BEGIN
                         SELECT FIRST 1 P.BDCODPROD
                         FROM TMP_TCADPRO P
                         WHERE P.BDCODPROD = :wCodSaida
                         AND ((P.BDCODEMP = :wCodEmp) OR (P.BDCODEMP IS NULL))
                         INTO :wCodProEncontrado;
              END
          END
              END
          END         
        -- SE NÃO ENCONTROU ATÉ AGORA, PODE TENTAR ENCONTRAR POR EAN E DESCRIÇÃO
        IF (((:wCodProEncontrado IS NULL) OR (:wCodProEncontrado = 0)) AND ((:wEanProUnico <> '') AND (:wEanProUnico <> '#')) AND ((:wDescProUnico <> '') AND (:wDescProUnico <> '#'))) THEN
          BEGIN
            SELECT FIRST 1 P.BDCODPROD
            FROM TMP_TCADPRO P
            WHERE P.bddescricaounica = :wdescprounico
            AND P.BDCODIGOEAN = :wEanProUnico
            AND P.BDCODEMP IS NULL
            INTO :wCodProEncontrado;
          END         
        -- AINDA PODE TENTAR ENCONTRAR POR CÓDIGO DE EMPRESA E DESCRIÇÃO
        IF (((:wCodProEncontrado IS NULL) OR (:wCodProEncontrado = 0)) AND ((:wDescPro <> '') AND (:wDescPro <> '#'))) THEN
          BEGIN
            SELECT FIRST 1 P.BDCODPROD
            FROM TMP_TCADPRO P
            WHERE P.BDDESCPROD = :wDescPro
            AND ((P.BDCODEMP = :wCodEmp) OR (P.BDCODEMP IS NULL))
            ORDER BY P.BDCODEMP DESC
            INTO :wCodProEncontrado;
          END              
        -- POR FIM, AINDA PODE TENTAR ENCONTRAR POR DESCRIÇÃO ÚNICA
        IF (((:wCodProEncontrado IS NULL) OR (:wCodProEncontrado = 0)) AND ((:wDescProUnico <> '') AND (:wDescProUnico <> '#'))) THEN
          BEGIN
            SELECT FIRST 1 P.BDCODPROD
            FROM TMP_TCADPRO P
            WHERE P.BDDESCRICAOUNICA = :wDescProUnico
            AND ((P.BDCODEMP IS NULL) OR (P.BDCODEMP = 0))
            INTO :wCodProEncontrado;
          END
      END
    ELSE
      /* SAÍDA */
      BEGIN                           
        -- PODE TENTAR ENCONTRAR DIRETO POR CÓDIGO SAÍDA e EMPRESA
        IF ((:wCodProEncontrado IS NULL) OR (:wCodProEncontrado = 0)) THEN
          BEGIN
            SELECT FIRST 1 P.BDCODPROD
            FROM TMP_TCADPRO P
            WHERE P.BDCODSAIDA = :wCodSaida
            AND P.BDCODEMP = :wCodEmp
            INTO :wCodProEncontrado;
          END
        -- CASO NAO ENCONTRE, PARA SEGREGACAO BUSCAMOS PELO BDCODPROD
        IF (Upper(:PRISSEGREG) = 'TRUE') THEN
          BEGIN
            IF ((:wCodProEncontrado IS NULL) OR (:wCodProEncontrado = 0)) then
                BEGIN
                    SELECT FIRST 1 P.BDCODPROD
                    FROM TMP_TCADPRO P
                    WHERE P.BDCODPROD  = :wCodSaida
                    AND P.BDCODEMP = :wCodEmp
                    INTO :wCodProEncontrado;
                END
          END
        IF ((wAPENASCODPRODSAI <> 'TRUE') OR -- Alt.: Opção no cadastro de inconsistencia "Verificar apenas codigo dos produtos nas saidas"...
            (Upper(:PRISSEGREG) = 'TRUE')) THEN -- Alt.: #209351 - Caso venha da segregação, deve desconsiderar o parâmetro das ações de inconsistencias e buscar de todas as formas...
          BEGIN                        
            -- SE NÃO CONSEGUIR, TENTA POR EAN E DESCRIÇÃO
            IF (((:wcodproencontrado IS NULL) OR (:wcodproencontrado = 0)) AND ((:wEanProUnico <> '') AND (:wEanProUnico <> '#')) AND ((:wDescProUnico <> '') AND (:wDescProUnico <> '#'))) THEN
              BEGIN
                SELECT FIRST 1 P.BDCODPROD
                FROM TMP_TCADPRO P
                WHERE P.BDCODIGOEAN = :wEanProUnico
                AND P.bddescricaounica = :wDescProUnico
                AND ((P.BDCODEMP = :wCodEmp) OR (P.BDCODEMP IS NULL))
                INTO :wCodProEncontrado;
              END                          
            -- E SE AINDA NÃO CONSEGUIR, PODE TENTAR POR DESCRIÇÃO E CÓDIGO
            IF (((:wcodproencontrado IS NULL) OR (:wcodproencontrado = 0)) AND ((:wDescPro <> '') AND (:wDescPro <> '#'))) THEN
              BEGIN
                SELECT FIRST 1 P.BDCODPROD
                FROM TMP_TCADPRO P
                WHERE P.BDDESCPROD = :wDescPro
                AND P.BDCODSAIDA = :wCodSaida
                AND ((P.BDCODEMP = :wCodEmp) OR (P.BDCODEMP IS NULL))
                INTO :wCodProEncontrado;
              END                 
            -- E POR FIM TENTA BUSCAR UNICAMENTE POR DESCRICAO NO CADASTRO UNICO
            IF (((:wCodProEncontrado IS NULL) OR (:wCodProEncontrado = 0)) AND ((:wDescProUnico <> '') AND (:wDescProUnico <> '#'))) THEN
              BEGIN
                /*
                  Exemplo: Cód. Saída  Descrição
                           2020270537  ARAME GALVANIZADO N. <- Só vai vincular nesse primeiro, os outros serão produtos novos.
                           2020270883  ARAME GALVANIZADO N.
                           2020270853  ARAME GALVANIZADO N.
                           1750010010  ARAME GALVANIZADO N.
                */
                SELECT FIRST 1 P.BDCODPROD
                FROM TMP_TCADPRO P
                JOIN TMP_TCADPRO_TEMP T ON(T.BDSESSAO = :PRSESSAO AND T.BDCODSAIDA = :wCodSaida AND UPPER(T.BDISPRODUNICO) = 'TRUE')
                LEFT OUTER JOIN TCADPRO_VINC V ON(V.BDCODEMP = :PRCODEMP AND V.BDCODPROD = P.BDEDITCHAVE)
                WHERE P.BDDESCRICAOUNICA = :wDescProUnico
                AND T.BDCODPROD IS NULL
                AND V.BDCODPROD IS NULL
                INTO :wCodProEncontrado;  
                IF ((:wCodProEncontrado IS NULL) OR (:wCodProEncontrado = 0)) THEN
                  BEGIN
                    SELECT FIRST 1 P.BDCODPROD
                    FROM TMP_TCADPRO P
                    /*Se já tiver vinculado algum produto pela descrição, os outros são diferentes, para não vincular tudo no mesmo*/
                    LEFT OUTER JOIN TMP_TCADPRO_TEMP T ON(T.BDSESSAO = :PRSESSAO AND T.BDEDITCHAVE = P.BDEDITCHAVE)
                    LEFT OUTER JOIN TCADPRO_VINC V ON(V.BDCODEMP = :PRCODEMP AND V.BDCODPROD = P.BDEDITCHAVE)
                    WHERE P.BDDESCRICAOUNICA = :wDescProUnico
                    AND T.BDSESSAO IS NULL
                    AND V.BDCODPROD IS NULL
                    INTO :wCodProEncontrado;
                  END            
               IF (Upper(:PRISSEGREG) = 'TRUE') then
                  BEGIN
                    IF (:wcodproencontrado IS NULL) then
                       BEGIN
                         SELECT FIRST 1 P.BDCODPROD
                         FROM TMP_TCADPRO P
                         WHERE P.BDCODPROD = :wCodSaida
                         AND ((P.BDCODEMP = :wCodEmp) OR (P.BDCODEMP IS NULL))
                         INTO :wCodProEncontrado;
              END
          END
      END
          END
      END            
    /* ***************************************************************************************************************************** */
    IF ((:wCodPersonalizacao = 9615) AND (:wCodOrigemProd = 0)) THEN /*SOMENTE PARA O 9615 - VANCREIACESSORIA 16836999*/
      BEGIN
        DELETE FROM TCADPRO_PART PP
        WHERE PP.BDCODPROD <> :wCodProEncontrado
        AND PP.BDCODTER = :wCodTerEncontrado
        AND PP.BDCODENTRADA = :wCodEntrada
        AND PP.BDDESCPRODBUSCA = :wDescPro;
        DELETE FROM TMP_TCADPRO_PART PP
        WHERE PP.BDCODPROD <> :wCodProEncontrado
        AND PP.BDCODTER = :wCodTerEncontrado
        AND PP.BDCODENTRADA = :wCodEntrada
        AND PP.BDDESCPRODBUSCA = :wDescPro;
      END
    wCodProVinc = NULL;
    /*Saída precisa olhar o codsaida, pois pode ter 2 produtos com a mesma descrição e códigos de saída
      diferentes cadastrados na empresa*/    
    IF (((:wCodProEncontrado IS NOT NULL) AND (:wCodProEncontrado > 0)) AND (:wCodOrigemProd = 1)) THEN /*Saída*/
      BEGIN
        SELECT FIRST 1 P.BDCODPROD
        FROM TMP_TCADPRO P
        WHERE P.BDCODPROD = :wCodProEncontrado
        AND P.BDCODEMP = :wCodEmp
        --AND P.BDCODSAIDA = :wCodSaida
        INTO :wCodProVinc;
        /* Esse select a cima verificou se esse produto já não está cadastrado na empresa.
           Se não estiver, verifica se tem algum produto vinculado a esse na empresa.
           Se houver, cria um cadastro unico novo */   
        IF ((:wCodProVinc = 0) OR (:wCodProVinc IS NULL)) THEN
          BEGIN
            SELECT FIRST 1 P.BDCODPROD
            FROM TMP_TCADPRO P
            WHERE P.BDCODPROD = :wCodProEncontrado
            AND P.BDCODEMP = :wCodEmp
            INTO :wCodProVinc;
            IF ((:wCodProVinc IS NOT NULL) AND (:wCodProVinc > 0)) THEN
              wCodProEncontrado = NULL;
          END
      END                 
    IF ((:wCodProEncontrado IS NOT NULL) AND (:wCodProEncontrado > 0)) THEN /*Encontrou produto*/
      BEGIN
        /*Verifica se já está cadastrado na empresa*/
        wCodSaidaExistente = '';
        IF (:wCodOrigemProd = 0) THEN /*Entrada não olha o codsaida*/
          BEGIN
            SELECT FIRST 1 P.BDCODPROD, COALESCE(P.BDCODSAIDA, '')
            FROM TCADPRO_VINC P
            WHERE P.BDCODPROD = :wCodProEncontrado
            AND P.BDCODEMP = :wCodEmp
            INTO :wCodProVinc, :wCodSaidaExistente;
          END     
        /*Se entrar no if é porque o produto só existe no cadastro unico, então deve inserir na TMP_TCADPRO como cadastro vinculado á empresa*/
        IF ((:wCodProVinc IS NULL) OR (:wCodProVinc = 0)) THEN
          BEGIN
            EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TCADPRO','SP_INS_UPT_TMP_TCADPRO(3)',:PRSESSAO);
            EXECUTE PROCEDURE SP_INS_UPT_TMP_TCADPRO(:PRSESSAO, :prREF, :wCodSaida, :wCodEntrada, :wCodProEncontrado, 0, :wCodTerEncontrado, :wCNPJTerLayout, :wIETERLAYOUT, :wDescPro, :wCodOrigemProd, 'INS', :wSeq_Part, 'FALSE');
          END
        ELSE /*o else é se o produto já existir na empresa, só verifica se vai atualizar. Se for atualizar, atualiza, senão não faz nada.*/
          BEGIN
            IF ((:wAtuProd = 'TRUE') AND (:PRGERARINCONSISTENCIAS = 'TRUE')) THEN
              BEGIN /*Já existe na empresa e o usuário optou por atualizar os dados*/
                EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TCADPRO','SP_INS_UPT_TMP_TCADPRO(4)',:PRSESSAO);
                EXECUTE PROCEDURE SP_INS_UPT_TMP_TCADPRO(:PRSESSAO, :prREF, :wCodSaida, :wCodEntrada, :wCodProEncontrado, 0, :wCodTerEncontrado, :wCNPJTerLayout, :wIETERLAYOUT, :wDescPro, :wCodOrigemProd, 'UPT', :wSeq_Part, 'FALSE');
              END
            ELSE
              BEGIN     
                IF (:wCodOrigemProd = 0) THEN /*Entrada*/
                  BEGIN
                    wCodProVinc = NULL;
                    SELECT FIRST 1 PART.BDEDITCHAVE
                    FROM TMP_TCADPRO_PART PART
                    WHERE PART.BDEDITCHAVE = :wCodProEncontrado
                    AND PART.BDCODENTRADA = :wCodEntrada
                    AND PART.BDDESCPRODBUSCA = :wDescPro
                    AND PART.BDCODTER = :wCodTerEncontrado
                    INTO :wCodProVinc;
                    IF (:wCodProVinc IS NULL) THEN
                      BEGIN
                        UPDATE OR INSERT INTO TMP_TCADPRO_PART(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDCODTER, BDCODENTRADA, BDDESCPRODBUSCA, BDCODEMP, BDSEQ_PART)
                        VALUES(:PRSESSAO, :wCodProEncontrado, :wCodProEncontrado, :wCodTerEncontrado, :wCodEntrada, :wDescPro, :wCodEmp, :wSeq_Part) MATCHING(BDCODPROD, BDCODENTRADA, BDCODTER, BDDESCPRODBUSCA);
                      END
                    ELSE
                      UPDATE TMP_TCADPRO_PART SET BDSEQ_PART = :wSeq_Part WHERE BDCODENTRADA = :wCodEntrada AND BDDESCPRODBUSCA = :wDescPro AND BDCODTER = :wCodTerEncontrado AND BDSEQ_PART <> :wSeq_Part;
                  END   
                  END
          END         
        IF (:wCodOrigemProd = 0) THEN /*Entrada*/
          BEGIN
            -- Alt.: #138509 - Primeiro busca por CNPJ + IE...
            SELECT FIRST 1 t.bdCODTERLAYOUT
            FROM TMP_TCADPRO_TEMP T
            WHERE T.BDSESSAO = :PRSESSAO
            AND T.BDCODENTRADA = :wCodEntrada
            AND T.BDDESCPROD = :wDescPro
            AND T.BDCNPJTERLAYOUT = :wCnpjTerLayout
            AND ((:wVINCULOPART <> 1) OR (t.bdIETERLAYOUT IS NULL) OR (t.bdIETERLAYOUT = '') OR (t.bdIETERLAYOUT = :wIETERLAYOUT)) -- Alt.: #138509 - Parâmetro para verificar o participante por IE...
            ORDER BY t.bdCODTER, t.bdCNPJTERLAYOUT, t.bdIETERLAYOUT -- Alt.: #206079 - Deve ordenar por codigo, pois tinha base com participante repetido, com o mesmo CNPJ e IE...
            INTO :WTER;
                                
            IF (:WTER IS NULL) THEN
              BEGIN -- Alt.: #138509 - Caso não encontre pelo CNPJ + IE, tenta pelo CNPJ apenas...
            UPDATE TMP_TCADPRO_TEMP T SET T.BDEDITCHAVE = :wCodProEncontrado, T.BDCODPROD = :wCodProEncontrado, T.BDSITUACAO = 1, T.BDPRODEXISTEBASE = 'TRUE', T.BDCODSAIDA = :wCodSaidaExistente
            WHERE T.BDSESSAO = :PRSESSAO
            AND T.BDCODENTRADA = :wCodEntrada
            AND T.BDDESCPROD = :wDescPro
            AND T.BDCNPJTERLAYOUT = :wCnpjTerLayout;
          END
        ELSE
              BEGIN        
                UPDATE TMP_TCADPRO_TEMP T SET T.BDEDITCHAVE = :wCodProEncontrado, T.BDCODPROD = :wCodProEncontrado, T.BDSITUACAO = 1, T.BDPRODEXISTEBASE = 'TRUE', T.BDCODSAIDA = :wCodSaidaExistente
                WHERE T.BDSESSAO = :PRSESSAO
                AND T.BDCODENTRADA = :wCodEntrada
                AND T.BDDESCPROD = :wDescPro
                AND T.BDCNPJTERLAYOUT = :wCnpjTerLayout
                AND ((:wVINCULOPART <> 1) OR (t.bdIETERLAYOUT IS NULL) OR (t.bdIETERLAYOUT = '') OR (t.bdIETERLAYOUT = :wIETERLAYOUT)) -- Alt.: #138509 - Parâmetro para verificar o participante por IE...
                ORDER BY t.bdCODTER, t.bdCNPJTERLAYOUT, t.bdIETERLAYOUT; -- Alt.: #206079 - Deve ordenar por codigo, pois tinha base com participante repetido, com o mesmo CNPJ e IE...
              END
          END
        ELSE
          BEGIN /*Saída*/       
            UPDATE TMP_TCADPRO_TEMP T SET T.BDEDITCHAVE = :wCodProEncontrado, T.BDCODPROD = :wCodProEncontrado, T.BDSITUACAO = 1, T.BDPRODEXISTEBASE = 'TRUE'
            WHERE T.BDSESSAO = :PRSESSAO
            AND T.BDCODSAIDA = :wCodSaida;
          END
       /*Vai atualizar a tabela temp com as informações do GIAF*/
         --EXECUTE PROCEDURE SP_INS_UPT_TMP_TCADPRO(:PRSESSAO, :wCodSaida, :wCodEntrada, :wCodProEncontrado, 0, :wCodTerEncontrado, :wCNPJTerLayout, :wDescPro, :wCodOrigemProd, 'INS', :wSeq_Part, 'FALSE');

      END
    ELSE
      BEGIN          
        /*Se não encontrou então é um produto novo e deve inserir na TMP_TCADPRO*/
        EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TCADPRO','SP_INS_UPT_TMP_TCADPRO(5)',:PRSESSAO);
        EXECUTE PROCEDURE SP_INS_UPT_TMP_TCADPRO(:PRSESSAO, :prREF, :wCodSaida, :wCodEntrada, 0, 0, :wCodTerEncontrado, :wCNPJTerLayout, :wIETERLAYOUT, :wDescPro, :wCodOrigemProd, 'INS', :wSeq_Part, 'TRUE');
        IF (:PRALTERARSIT = 'TRUE') THEN
          BEGIN
        /*Se for pra cadastrar os produtos novos automaticamente, então define a situação como 2 - Cadastro automático*/
        IF (:wCodOrigemProd = 0) THEN /*Entrada*/
          BEGIN
            -- Alt.: #138509 - Primeiro busca por CNPJ + IE...
            SELECT FIRST 1 t.bdCODTERLAYOUT
            FROM TMP_TCADPRO_TEMP T
            WHERE T.BDSESSAO = :PRSESSAO
            AND T.BDCODENTRADA = :wCodEntrada
            AND T.BDDESCPROD = :wDescPro
            AND T.BDCNPJTERLAYOUT = :wCnpjTerLayout
            AND ((:wVINCULOPART <> 1) OR (t.bdIETERLAYOUT IS NULL) OR (t.bdIETERLAYOUT = '') OR (t.bdIETERLAYOUT = :wIETERLAYOUT)) -- Alt.: #138509 - Parâmetro para verificar o participante por IE...
            ORDER BY t.bdCODTER, t.bdCNPJTERLAYOUT, t.bdIETERLAYOUT -- Alt.: #206079 - Deve ordenar por codigo, pois tinha base com participante repetido, com o mesmo CNPJ e IE...
            INTO :WTER;
                             
            IF (:WTER IS NULL) THEN
              BEGIN -- Alt.: #138509 - Caso não encontre pelo CNPJ + IE, tenta pelo CNPJ apenas...
            UPDATE TMP_TCADPRO_TEMP T SET T.BDSITUACAO = IIF(:wCadAut = 'TRUE', 2, 0), T.BDPRODEXISTEBASE = 'FALSE'
            WHERE T.BDSESSAO = :PRSESSAO
            AND T.BDCODENTRADA = :wCodEntrada
            AND T.BDDESCPROD = :wDescPro
                AND T.BDCNPJTERLAYOUT = :wCnpjTerLayout; -- Alt.: #138509 - Parâmetro para verificar o participante por IE...
          END
        ELSE
              BEGIN        
                UPDATE TMP_TCADPRO_TEMP T SET T.BDSITUACAO = IIF(:wCadAut = 'TRUE', 2, 0), T.BDPRODEXISTEBASE = 'FALSE'
                WHERE T.BDSESSAO = :PRSESSAO
                AND T.BDCODENTRADA = :wCodEntrada
                AND T.BDDESCPROD = :wDescPro
                AND T.BDCNPJTERLAYOUT = :wCnpjTerLayout
                AND ((:wVINCULOPART <> 1) OR (t.bdIETERLAYOUT IS NULL) OR (t.bdIETERLAYOUT = '') OR (t.bdIETERLAYOUT = :wIETERLAYOUT)) -- Alt.: #138509 - Parâmetro para verificar o participante por IE...
                ORDER BY t.bdCODTER, t.bdCNPJTERLAYOUT, t.bdIETERLAYOUT; -- Alt.: #206079 - Deve ordenar por codigo, pois tinha base com participante repetido, com o mesmo CNPJ e IE...
              END
          END
        ELSE
          BEGIN /*Saída*/                    
            UPDATE TMP_TCADPRO_TEMP T SET T.BDSITUACAO = IIF(:wCadAut = 'TRUE', 2, 0), T.BDPRODEXISTEBASE = 'FALSE'
            WHERE T.BDSESSAO = :PRSESSAO
            AND T.BDCODENTRADA = :wCodEntrada
            AND T.BDCODSAIDA = :wCodSaida;
          END
      END
  END
  END
  /*Sol: 14207 Patrick T. Sá 20/01/2017. Busca o código CEST pela classificação CEST caso tenha no arquivo.*/
  /*Formata a classificação caso no arquivo só venha como inteiro*/
  UPDATE TMP_TCADPRO_TEMP P
  SET P.BDCODCEST = (
                     SELECT FIRST 1 C.BDCODCEST
                     FROM TCEST C
                     WHERE C.BDCLASSCEST = (SUBSTRING(P.BDCLASSCEST FROM 1 FOR 2)||'.'||SUBSTRING(P.BDCLASSCEST FROM 3 FOR 3)||'.'||SUBSTRING(P.BDCLASSCEST FROM 6 FOR 2))
                    )
  WHERE P.BDSESSAO = :PRSESSAO
  AND P.BDCLASSCEST IS NOT NULL
  AND CHAR_LENGTH(P.BDCLASSCEST) <= 7;              
  /*Caso no arquivo venha a classificação então não formata, só pesquisa*/
  UPDATE TMP_TCADPRO_TEMP P
  SET P.BDCODCEST = (
                     SELECT FIRST 1 C.BDCODCEST
                     FROM TCEST C
                     WHERE C.BDCLASSCEST = P.BDCLASSCEST
                    )
  WHERE P.BDSESSAO = :PRSESSAO
  AND P.BDCLASSCEST IS NOT NULL
  AND CHAR_LENGTH(P.BDCLASSCEST) > 7;  
  /*Joga a ordem do produto por participante na TEMP, para quando for gravar o produto por participante tem a ordem*/
--  UPDATE TMP_TCADPRO_TEMP P
--  SET P.BDORDEM = (
--                   SELECT FIRST 1 PP.BDORDEM
--                   FROM TMP_TCADPRO_PART PP
--                   WHERE PP.BDCODENTRADA = P.BDCODENTRADA
--                   AND PP.BDDESCPRODBUSCA = P.BDDESCPROD
--                   AND PP.BDCODTER = P.BDCODTERLAYOUT
--                  )
--  WHERE P.BDSESSAO = :PRSESSAO
--  AND P.BDORIGEMPROD = 0
--  AND P.BDORDEM IS NULL;
  EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TCADPRO','SP_ATUALIZAR_CST_PROD(6)',:PRSESSAO);
  EXECUTE PROCEDURE SP_ATUALIZAR_CST_PROD(:PRSESSAO, :PRALTERACST);
  EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TCADPRO','SP_ATUALIZAR_TMP_INSUMO_TEMP(7)',:PRSESSAO);
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_INSUMO_TEMP(:PRSESSAO, :wAtuProd, :PRGERARINCONSISTENCIAS);
  EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TCADPRO','SP_ATUALIZAR_TMP_PROD_GIAF(8)',:PRSESSAO);
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_PROD_GIAF(:PRSESSAO);

--#99586 #122780 #122865 #122871 #122938 - Não deve mostrar as inconsistência de produtos que já estão no banco, quando não for atualizar os cadastros
  if (wAtuProd = 'FALSE') then
    BEGIN
      DELETE FROM VEF_INCON_TCADPRO P
      WHERE P.BDSESSAO = :PRSESSAO
        AND EXISTS(SELECT FIRST 1 PV.BDCODPROD
                   FROM TCADPRO_VINC PV
                   WHERE PV.BDCODPROD = p.BDCODPROD AND
                         PV.BDCODEMP  = p.BDCODEMP);
    END                
END
^

COMMENT ON PARAMETER SP_ATUALIZAR_TMP_TCADPRO.PRALTERARSIT IS 'Especifico para o serviço, onde sempre é relacionado'^
COMMENT ON PARAMETER SP_ATUALIZAR_TMP_TCADPRO.PRALTERACST IS 'Layout padrão SCI não deve alterar o código de CST'^

CREATE OR ALTER procedure SP_INSERT_OR_UPDATE_TCADPRO (
    PRCODEMP integer,
    PRSESSAO integer,
    PRREF integer)
as
declare variable FCODPROD integer;
declare variable FCODGEN integer;
declare variable FCODSER integer;
declare variable FCODTIPOSER integer;
declare variable FCODCOMBANP integer;
declare variable FAPELIDOUNICO varchar(30) collate WIN_PTBR;
declare variable FDESCRICAOUNICA varchar(200) collate WIN_PTBR;
declare variable FCODIGOEAN varchar(20) collate WIN_PTBR;
declare variable FCODTIPO integer;
declare variable FCODEMP integer;
declare variable FCODSAIDA varchar(60) collate WIN_PTBR;
declare variable FDESCPROD varchar(200) collate WIN_PTBR;
declare variable FAPEPROD varchar(30) collate WIN_PTBR;
declare variable FCODUNIMED integer;
declare variable FNCMPROD integer;
declare variable FGRUPO integer;
declare variable FCODCSTIPIENT integer;
declare variable FCODCSTCOFENT integer;
declare variable FCODCSTPISENT integer;
declare variable FCODCSTPISSAI integer;
declare variable FCODCSTCOFSAI integer;
declare variable FCODCSTIPISAI integer;
declare variable FCODCSTICMS integer;
declare variable FCODTABINCID integer;
declare variable FORDEMMARCA integer;
declare variable FALIQICMS numeric(7,4);
declare variable FALIQICMSST numeric(7,4);
declare variable FALIQIPI numeric(7,4);
declare variable FALIQPIS numeric(7,4);
declare variable FALIQPISENT numeric(7,4);
declare variable FALIQCOF numeric(7,4);
declare variable FALIQCOFENT numeric(7,4);
declare variable FCAPVOL integer;
declare variable FINATIVO varchar(5);
declare variable FCODPRODBASE integer;
declare variable FREFPROD integer;
declare variable FORDEM integer;
declare variable FQTDCONSUMO numeric(17,6);
declare variable FPERDA DM_NUMERIC_7_4_ALIQ;
declare variable FDATAINIVAL date;
declare variable FDATAFIMVAL date;
declare variable FCADPROAUTO varchar(5);
declare variable FATUPROD varchar(5);
declare variable FPRODEXISTENTE varchar(5);
declare variable FPRODVINCEXISTENTE varchar(5);
declare variable FSITUACAO integer;
declare variable FCODTER integer;
declare variable FCODENTRADA varchar(60);
declare variable FCODCEST integer;
declare variable FCODTIPI integer;
declare variable FORDEMEXIST integer;
declare variable FORIGEM integer;
declare variable FDESCORIGINAL varchar(200);
declare variable FFATORCONVER numeric(15,6);
declare variable FALIQFCP DM_NUMERIC_15_2;
declare variable FEAN varchar(20) collate WIN_PTBR;
declare variable FEXCECAONCM boolean;
declare variable FTIPOITEM boolean;
declare variable FCODNATBCREC integer;
declare variable FTIPOPROD integer;
declare variable FCODITEM integer;
declare variable FQTDPROD integer;
declare variable FNAOATUALIZACSTENTRADA boolean;
declare variable FNAOATUALIZACSTSAIDA boolean;
declare variable FCODCCLASSTRIBIBSCBS integer;
declare variable FALIQUOTAREDUCAO DM_NUMERIC_7_4_ALIQ;
declare variable FALIQUOTACBS DM_NUMERIC_7_4_ALIQ;
declare variable FCODCCLASSTRIBIS integer;
declare variable FALIQUOTAIS DM_NUMERIC_7_4_ALIQ;
declare variable FALIQUOTAESPECIFICAS DM_NUMERIC_7_4_ALIQ;
declare variable FCODUNTRIBUTAVEL integer;
declare variable FCODCSTIBSCBS integer;
declare variable FCODCSTIBIS integer;
declare variable FPRODINCENTIVADO DM_BOOLEAN;
BEGIN
  SELECT SP.BDCADPROAUTO, SP.BDATUPROD, SP.bdexcecaoncm, sp.bdtipoitem, sp.bdnaoatualizacstentrada, sp.bdnaoatualizacstsaida FROM SP_GET_ACOES_INCONSISTENCIA(:PRCODEMP, :PRREF) SP INTO :FCADPROAUTO, :FATUPROD, :FEXCECAONCM, :FTIPOITEM, :FNAOATUALIZACSTENTRADA, :FNAOATUALIZACSTSAIDA;

  FOR SELECT P.BDCODPROD, P.BDCODGEN, IIF(P.BDCODSER = 0, NULL, P.BDCODSER), iif(:FATUPROD = 'TRUE' AND :FTIPOITEM = 'TRUE',PV.BDCODTIPOSER, P.BDCODTIPOSER), P.BDCODCOMBANP, P.BDAPELIDOUNICO, P.BDDESCRICAOUNICA,
             P.BDCODIGOEAN, P.BDCODTIPO , P.BDCODEMP, P.BDCODSAIDA, P.BDDESCPROD, p.BDAPEPROD,
             IIF(COALESCE(p.BDALTCODUNIMED, 0) = 0, NULL, P.BDALTCODUNIMED), IIF(p.BDNCMPROD = 0, NULL, p.BDNCMPROD),
             p.BDGRUPO, p.BDCODCSTIPIENT,
             IIF(:FNAOATUALIZACSTENTRADA = 'TRUE', PV.BDCODCSTCOFENT, p.BDCODCSTCOFENT),
             IIF(:FNAOATUALIZACSTENTRADA = 'TRUE', PV.BDCODCSTPISENT ,p.BDCODCSTPISENT),
             IIF(:FNAOATUALIZACSTSAIDA = 'TRUE', PV.BDCODCSTPISSAI ,p.BDCODCSTPISSAI),
             IIF(:FNAOATUALIZACSTSAIDA = 'TRUE', PV.BDCODCSTCOFSAI ,p.BDCODCSTCOFSAI), p.BDCODCSTIPISAI,
             p.BDCODCSTICMS, IIF(p.BDCODTABINCID = 0,NULL, p.BDCODTABINCID) BDCODTABINCID, p.BDORDEMMARCA, p.BDALIQICMS, p.BDALIQICMSST, p.BDALIQIPI, p.BDALIQPIS,
             p.BDALIQPISENT, p.BDALIQCOF, p.BDALIQCOFENT, p.BDCAPVOL, p.BDINATIVO, P.BDEDITCHAVE, P.bdrefprodlay,
             IIF(PRO.BDCODPROD IS NULL, 'FALSE', 'TRUE') BDPRODEXISTENTE, P.BDSITUACAO, IIF(PV.BDCODPROD IS NULL, 'FALSE', 'TRUE') BDPRODVINCEXISTEBASE,
             P.BDCODTERLAYOUT, P.BDCODENTRADA, P.BDCODCEST, iif(:FATUPROD = 'TRUE' AND :FEXCECAONCM = 'TRUE', tipi.bdcodtipi, p.BDCODTIPI), P.BDORDEM, P.BDORIGEMPROD, P.BDDESCORIGINAL,
             P.BDALIQFCP, P.BDCODNATBCREC, p.bdTIPOPROD, P.BDCODCCLASSTRIBIBSCBS, P.BDALIQUOTAREDUCAO, P.BDALIQUOTACBS, P.BDCODCCLASSTRIBIS, P.BDALIQUOTAIS, P.BDALIQUOTAESPECIFICAS, P.BDCODUNTRIBUTAVEL,
             p.BDCODCSTIBSCBS, p.BDCODCSTIBIS, p.BDPRODINCENTIVADO
      FROM TMP_TCADPRO_TEMP P
      LEFT OUTER JOIN TCADPRO_VINC PV ON(PV.BDCODEMP = P.BDCODEMP AND PV.BDCODPROD = P.BDEDITCHAVE /*AND P.BDPRODEXISTEBASE <> 'TRUE'*/)
      LEFT OUTER JOIN TCADPRO PRO ON(PRO.BDCODPROD = P.BDEDITCHAVE)
      left join TCODEXTIPI tipi on (tipi.BDNCMPROD = p.BDNCMPROD and tipi.BDCODTIPI = pv.BDCODTIPI)
      WHERE P.bdsessao = :PRSESSAO 
      AND ((P.bdinconsistente IS NULL) OR (P.bdinconsistente = 0)) 
      AND P.BDEDITCHAVE IS NOT NULL
      AND NOT EXISTS (
                      SELECT I.BDCODINCONSISTENCIA FROM VEF_INCON_TCADPRO I
                      WHERE I.BDSESSAO = :PRSESSAO
                      AND I.BDCODPROD = P.BDCODPROD
                     )      
      INTO :FCODPROD, :FCODGEN, :FCODSER, :FCODTIPOSER, :FCODCOMBANP, :FAPELIDOUNICO, :FDESCRICAOUNICA,
           :FCODIGOEAN, :FCODTIPO, :FCODEMP, :FCODSAIDA, :FDESCPROD, :FAPEPROD,
           :FCODUNIMED, :FNCMPROD,  :FGRUPO,  :FCODCSTIPIENT , :FCODCSTCOFENT,  :FCODCSTPISENT, :FCODCSTPISSAI,
           :FCODCSTCOFSAI, :FCODCSTIPISAI,  :FCODCSTICMS, :FCODTABINCID, :FORDEMMARCA, :FALIQICMS, :FALIQICMSST,
           :FALIQIPI,:FALIQPIS,:FALIQPISENT,:FALIQCOF,:FALIQCOFENT, :FCAPVOL, :FINATIVO, :FCODPRODBASE,
           :FREFPROD, :FPRODEXISTENTE, :FSITUACAO, :FPRODVINCEXISTENTE, :FCODTER, :FCODENTRADA, :FCODCEST, :FCODTIPI, :FORDEM, :FORIGEM, :FDESCORIGINAL,
           :FALIQFCP, :FCODNATBCREC, :FTIPOPROD, :FCODCCLASSTRIBIBSCBS, :FALIQUOTAREDUCAO, :FALIQUOTACBS, :FCODCCLASSTRIBIS, :FALIQUOTAIS, :FALIQUOTAESPECIFICAS, :FCODUNTRIBUTAVEL,
           :FCODCSTIBSCBS, :FCODCSTIBIS, :FPRODINCENTIVADO
      DO
  BEGIN
    /*Verifica se é pra cadastrar os produtos novos automaticamente*/
    IF ((:FCADPROAUTO = 'TRUE') OR (COALESCE(:FSITUACAO, 0) IN (1, 2))) THEN
      BEGIN
        /*Verifica se é pra atualizar o cadastro de produto, se for, simplesmente da update or insert em todos os produtos*/
        IF (:FATUPROD = 'TRUE') THEN
          BEGIN
            UPDATE OR INSERT INTO TCADPRO (BDCODPROD, BDCODGEN, BDCODSER, BDCODTIPOSER, BDCODCOMBANP, BDAPELIDOUNICO,BDDESCRICAOUNICA, BDCODIGOEAN,BDCODTIPO, BDPRODINCENTIVADO, BDCODCEST)
            VALUES(:FCODPROD, :FCODGEN, :FCODSER, :FCODTIPOSER, :FCODCOMBANP,:FAPELIDOUNICO, :FDESCRICAOUNICA, :FCODIGOEAN, :FCODTIPO, :FPRODINCENTIVADO, :FCODCEST) MATCHING(BDCODPROD);

            IF ((FCODNATBCREC IS NULL) OR (FCODNATBCREC <= 0)) THEN
                BEGIN
            UPDATE OR INSERT INTO TCADPRO_VINC (BDCODPROD, BDCODEMP, BDCODSAIDA, BDDESCPROD, BDAPEPROD, BDCODUNIMED, BDNCMPROD,
                                                BDGRUPO, BDCODCSTIPIENT, BDCODCSTCOFENT, BDCODCSTPISENT, BDCODCSTPISSAI,
                                                BDCODCSTCOFSAI, BDCODCSTIPISAI, BDCODCSTICMS, BDCODTABINCID, BDORDEMMARCA,
                                                BDALIQICMS, BDALIQICMSST, BDALIQIPI, BDALIQPIS, BDALIQPISENT, BDALIQCOF,
                                                BDALIQCOFENT, BDCAPVOL, BDINATIVO, BDCODTIPO, BDCODTIPOSER, BDCODGEN, BDCODSER,
                                                BDCODCOMBANP, BDCODCEST, BDCODTIPI, BDALIQFCP,
                                                BDCODCCLASSTRIBIBSCBS, BDALIQUOTAREDUCAO, BDALIQUOTACBS, BDCODCCLASSTRIBIS, BDALIQUOTAIS, BDALIQUOTAESPECIFICAS, BDCODUNTRIBUTAVEL,
                                                BDCODCSTIBSCBS, BDCODCSTIBIS, BDPRODINCENTIVADO)
            VALUES(
                   :FCODPROD, :FCODEMP, :FCODSAIDA, :FDESCPROD, :FAPEPROD, :FCODUNIMED, :FNCMPROD, :FGRUPO, :FCODCSTIPIENT,
                   :FCODCSTCOFENT, :FCODCSTPISENT, :FCODCSTPISSAI, :FCODCSTCOFSAI, :FCODCSTIPISAI, :FCODCSTICMS, :FCODTABINCID,
                   :FORDEMMARCA, :FALIQICMS, :FALIQICMSST, :FALIQIPI, :FALIQPIS, :FALIQPISENT, :FALIQCOF, :FALIQCOFENT, :FCAPVOL,
                   :FINATIVO, :FCODTIPO, :FCODTIPOSER, :FCODGEN, :FCODSER, :FCODCOMBANP, :FCODCEST, :FCODTIPI, :FALIQFCP,
                   :FCODCCLASSTRIBIBSCBS, :FALIQUOTAREDUCAO, :FALIQUOTACBS, :FCODCCLASSTRIBIS, :FALIQUOTAIS, :FALIQUOTAESPECIFICAS, :FCODUNTRIBUTAVEL,
                   :FCODCSTIBSCBS, :FCODCSTIBIS, :FPRODINCENTIVADO
                  ) MATCHING(BDCODPROD, BDCODEMP);
                END
            ELSE
                BEGIN
                    UPDATE OR INSERT INTO TCADPRO_VINC (BDCODPROD, BDCODEMP, BDCODSAIDA, BDDESCPROD, BDAPEPROD, BDCODUNIMED, BDNCMPROD,
                                                        BDGRUPO, BDCODCSTIPIENT, BDCODCSTCOFENT, BDCODCSTPISENT, BDCODCSTPISSAI,
                                                        BDCODCSTCOFSAI, BDCODCSTIPISAI, BDCODCSTICMS, BDCODTABINCID, BDORDEMMARCA,
                                                        BDALIQICMS, BDALIQICMSST, BDALIQIPI, BDALIQPIS, BDALIQPISENT, BDALIQCOF,
                                                        BDALIQCOFENT, BDCAPVOL, BDINATIVO, BDCODTIPO, BDCODTIPOSER, BDCODGEN, BDCODSER,
                                                        BDCODCOMBANP, BDCODCEST, BDCODTIPI, BDALIQFCP, BDTIPOPROD, BDCODNATBCREC,
                                                        BDCODCCLASSTRIBIBSCBS, BDALIQUOTAREDUCAO, BDALIQUOTACBS, BDCODCCLASSTRIBIS,
                                                        BDALIQUOTAIS, BDALIQUOTAESPECIFICAS, BDCODUNTRIBUTAVEL, BDCODCSTIBSCBS, BDCODCSTIBIS, BDPRODINCENTIVADO)
                    VALUES(
                            :FCODPROD, :FCODEMP, :FCODSAIDA, :FDESCPROD, :FAPEPROD, :FCODUNIMED, :FNCMPROD, :FGRUPO, :FCODCSTIPIENT,
                            :FCODCSTCOFENT, :FCODCSTPISENT, :FCODCSTPISSAI, :FCODCSTCOFSAI, :FCODCSTIPISAI, :FCODCSTICMS, :FCODTABINCID,
                            :FORDEMMARCA, :FALIQICMS, :FALIQICMSST, :FALIQIPI, :FALIQPIS, :FALIQPISENT, :FALIQCOF, :FALIQCOFENT, :FCAPVOL,
                            :FINATIVO, :FCODTIPO, :FCODTIPOSER, :FCODGEN, :FCODSER, :FCODCOMBANP, :FCODCEST, :FCODTIPI, :FALIQFCP, :FTIPOPROD, :FCODNATBCREC,
                            :FCODCCLASSTRIBIBSCBS, :FALIQUOTAREDUCAO, :FALIQUOTACBS, :FCODCCLASSTRIBIS, :FALIQUOTAIS, :FALIQUOTAESPECIFICAS, :FCODUNTRIBUTAVEL,
                            :FCODCSTIBSCBS, :FCODCSTIBIS, :FPRODINCENTIVADO
                          ) MATCHING(BDCODPROD, BDCODEMP);
                END



            UPDATE OR INSERT INTO TCADPRO_REF (BDCODPROD,BDCODEMP,BDREFPROD,BDDESCPROD) VALUES (:FCODPROD, :FCODEMP, :FREFPROD, :FDESCPROD) MATCHING(BDCODPROD, BDREFPROD, BDCODEMP);

            IF (:FORIGEM = 0) THEN
              BEGIN
                FORDEMEXIST = NULL;
                SELECT COALESCE((
                                 SELECT FIRST 1 P.BDORDEM
                                 FROM TCADPRO_PART P
                                 WHERE P.BDCODPROD = :FCODPROD
                                 AND P.BDCODTER = :FCODTER
                                 AND CAST(P.BDCODENTRADA AS DM_DESC_WINPTBR) = CAST(:FCODENTRADA AS DM_DESC_WINPTBR)
                                 AND CAST(P.BDDESCPRODBUSCA AS DM_DESC_WINPTBR) = CAST(:FDESCORIGINAL AS DM_DESC_WINPTBR)
                                ),
                                (
                                 SELECT FIRST 1 P.BDORDEM
                                 FROM TCADPRO_PART P
                                 WHERE P.BDCODPROD = :FCODPROD
                                 AND P.BDCODTER = :FCODTER
                                 AND UPPER(CAST(P.BDCODENTRADA AS DM_DESC_WINPTBR)) = UPPER(CAST(:FCODENTRADA AS DM_DESC_WINPTBR))
                                 AND UPPER(CAST(P.BDDESCPRODBUSCA AS DM_DESC_WINPTBR)) = UPPER(CAST(:FDESCORIGINAL AS DM_DESC_WINPTBR)))
                                ) BDORDEM
                FROM RDB$DATABASE
                INTO :FORDEMEXIST;

                IF ((:FORDEMEXIST IS NULL) OR (:FORDEMEXIST = 0)) THEN
                  BEGIN
                    INSERT INTO TCADPRO_PART(BDCODPROD, BDCODTER, BDORDEM, BDCODENTRADA, BDDESCPRODBUSCA)
                    VALUES(:FCODPROD, :FCODTER, :FORDEM, :FCODENTRADA, :FDESCORIGINAL);
              END
          END
          END
        ELSE
          BEGIN 
            /*Se chegou aqui não é pra atualizar os produtos existentes, apenas inserir os novos.*/
            IF (:FPRODEXISTENTE <> 'TRUE') THEN
              BEGIN
                UPDATE OR INSERT INTO TCADPRO (BDCODPROD, BDCODGEN, BDCODSER, BDCODTIPOSER, BDCODCOMBANP, BDAPELIDOUNICO,BDDESCRICAOUNICA, BDCODIGOEAN,BDCODTIPO,BDPRODINCENTIVADO, BDCODCEST)
                VALUES(:FCODPROD, :FCODGEN, :FCODSER, :FCODTIPOSER, :FCODCOMBANP,:FAPELIDOUNICO, :FDESCRICAOUNICA, :FCODIGOEAN, :FCODTIPO,:FPRODINCENTIVADO ,:FCODCEST) MATCHING(BDCODPROD);
              END
            IF (:FPRODVINCEXISTENTE = 'FALSE') THEN
              BEGIN

                IF ((FCODNATBCREC IS NULL) OR (FCODNATBCREC <= 0)) THEN
                    BEGIN
                UPDATE OR INSERT INTO TCADPRO_VINC (BDCODPROD, BDCODEMP, BDCODSAIDA, BDDESCPROD, BDAPEPROD, BDCODUNIMED, BDNCMPROD,
                                                    BDGRUPO, BDCODCSTIPIENT, BDCODCSTCOFENT, BDCODCSTPISENT, BDCODCSTPISSAI,
                                                    BDCODCSTCOFSAI, BDCODCSTIPISAI, BDCODCSTICMS, BDCODTABINCID, BDORDEMMARCA,
                                                    BDALIQICMS, BDALIQICMSST, BDALIQIPI, BDALIQPIS, BDALIQPISENT, BDALIQCOF,
                                                    BDALIQCOFENT, BDCAPVOL, BDINATIVO, BDCODTIPO, BDCODTIPOSER, BDCODGEN, BDCODSER,
                                                    BDCODCOMBANP, BDCODCEST, BDCODTIPI, BDALIQFCP, BDTIPOPROD,
                                                    BDCODCCLASSTRIBIBSCBS, BDALIQUOTAREDUCAO, BDALIQUOTACBS, BDCODCCLASSTRIBIS,
                                                    BDALIQUOTAIS, BDALIQUOTAESPECIFICAS, BDCODUNTRIBUTAVEL, BDCODCSTIBSCBS, BDCODCSTIBIS, BDPRODINCENTIVADO)
                VALUES(
                       :FCODPROD, :FCODEMP, :FCODSAIDA, :FDESCPROD, :FAPEPROD, :FCODUNIMED, :FNCMPROD, :FGRUPO, :FCODCSTIPIENT,
                       :FCODCSTCOFENT, :FCODCSTPISENT, :FCODCSTPISSAI, :FCODCSTCOFSAI, :FCODCSTIPISAI, :FCODCSTICMS, :FCODTABINCID,
                       :FORDEMMARCA, :FALIQICMS, :FALIQICMSST, :FALIQIPI, :FALIQPIS, :FALIQPISENT, :FALIQCOF, :FALIQCOFENT, :FCAPVOL,
                       :FINATIVO, :FCODTIPO, :FCODTIPOSER, :FCODGEN, :FCODSER, :FCODCOMBANP, :FCODCEST, :FCODTIPI, :FALIQFCP, :FTIPOPROD,
                       :FCODCCLASSTRIBIBSCBS, :FALIQUOTAREDUCAO, :FALIQUOTACBS, :FCODCCLASSTRIBIS, :FALIQUOTAIS, :FALIQUOTAESPECIFICAS, :FCODUNTRIBUTAVEL,
                       :FCODCSTIBSCBS, :FCODCSTIBIS, :FPRODINCENTIVADO
                        ) MATCHING(BDCODPROD, BDCODEMP);                    
                    END
                ELSE
                    BEGIN
                        UPDATE OR INSERT INTO TCADPRO_VINC (BDCODPROD, BDCODEMP, BDCODSAIDA, BDDESCPROD, BDAPEPROD, BDCODUNIMED, BDNCMPROD,
                                                    BDGRUPO, BDCODCSTIPIENT, BDCODCSTCOFENT, BDCODCSTPISENT, BDCODCSTPISSAI,
                                                    BDCODCSTCOFSAI, BDCODCSTIPISAI, BDCODCSTICMS, BDCODTABINCID, BDORDEMMARCA,
                                                    BDALIQICMS, BDALIQICMSST, BDALIQIPI, BDALIQPIS, BDALIQPISENT, BDALIQCOF,
                                                    BDALIQCOFENT, BDCAPVOL, BDINATIVO, BDCODTIPO, BDCODTIPOSER, BDCODGEN, BDCODSER,
                                                    BDCODCOMBANP, BDCODCEST, BDCODTIPI, BDALIQFCP, BDTIPOPROD, BDCODNATBCREC,
                                                    BDCODCCLASSTRIBIBSCBS, BDALIQUOTAREDUCAO, BDALIQUOTACBS, BDCODCCLASSTRIBIS,
                                                    BDALIQUOTAIS, BDALIQUOTAESPECIFICAS, BDCODUNTRIBUTAVEL, BDCODCSTIBSCBS, BDCODCSTIBIS, BDPRODINCENTIVADO)
                        VALUES(
                            :FCODPROD, :FCODEMP, :FCODSAIDA, :FDESCPROD, :FAPEPROD, :FCODUNIMED, :FNCMPROD, :FGRUPO, :FCODCSTIPIENT,
                            :FCODCSTCOFENT, :FCODCSTPISENT, :FCODCSTPISSAI, :FCODCSTCOFSAI, :FCODCSTIPISAI, :FCODCSTICMS, :FCODTABINCID,
                            :FORDEMMARCA, :FALIQICMS, :FALIQICMSST, :FALIQIPI, :FALIQPIS, :FALIQPISENT, :FALIQCOF, :FALIQCOFENT, :FCAPVOL,
                            :FINATIVO, :FCODTIPO, :FCODTIPOSER, :FCODGEN, :FCODSER, :FCODCOMBANP, :FCODCEST, :FCODTIPI, :FALIQFCP, :FTIPOPROD, :FCODNATBCREC,
                            :FCODCCLASSTRIBIBSCBS, :FALIQUOTAREDUCAO, :FALIQUOTACBS, :FCODCCLASSTRIBIS, :FALIQUOTAIS, :FALIQUOTAESPECIFICAS, :FCODUNTRIBUTAVEL,
                            :FCODCSTIBSCBS, :FCODCSTIBIS, :FPRODINCENTIVADO
                        ) MATCHING(BDCODPROD, BDCODEMP);
                    END

                UPDATE OR INSERT INTO TCADPRO_REF (BDCODPROD,BDCODEMP,BDREFPROD,BDDESCPROD) VALUES (:FCODPROD, :FCODEMP, :FREFPROD, :FDESCPROD) MATCHING(BDCODPROD, BDREFPROD, BDCODEMP);

              END

            IF (:FORIGEM = 0) THEN
              BEGIN
                FORDEMEXIST = NULL;
                SELECT COALESCE((
                                 SELECT FIRST 1 P.BDORDEM
                                 FROM TCADPRO_PART P
                                 WHERE P.BDCODPROD = :FCODPROD
                                 AND P.BDCODTER = :FCODTER
                                 AND CAST(P.BDCODENTRADA AS DM_DESC_WINPTBR) = CAST(:FCODENTRADA AS DM_DESC_WINPTBR)
                                 AND CAST(P.BDDESCPRODBUSCA AS DM_DESC_WINPTBR) = CAST(:FDESCORIGINAL AS DM_DESC_WINPTBR)
                                ),
                                (
                                 SELECT FIRST 1 P.BDORDEM
                                 FROM TCADPRO_PART P
                                 WHERE P.BDCODPROD = :FCODPROD
                                 AND P.BDCODTER = :FCODTER
                                 AND UPPER(CAST(P.BDCODENTRADA AS DM_DESC_WINPTBR)) = UPPER(CAST(:FCODENTRADA AS DM_DESC_WINPTBR))
                                 AND UPPER(CAST(P.BDDESCPRODBUSCA AS DM_DESC_WINPTBR)) = UPPER(CAST(:FDESCORIGINAL AS DM_DESC_WINPTBR)))
                                ) BDORDEM
                FROM RDB$DATABASE
                INTO :FORDEMEXIST;

                IF ((:FORDEMEXIST IS NULL) OR (:FORDEMEXIST = 0)) THEN
                  BEGIN
                    INSERT INTO TCADPRO_PART(BDCODPROD, BDCODTER, BDORDEM, BDCODENTRADA, BDDESCPRODBUSCA)
                    VALUES(:FCODPROD, :FCODTER, :FORDEM, :FCODENTRADA, :FDESCORIGINAL);
              END
          END
      END
  END
  END

  FOR SELECT I.BDALTCODPROD, I.BDCODEMP, I.BDALTORDEM, I.BDREFERENCIA, I.BDCODPROINSUMO,
             I.BDQTDCONSUMO, I.BDPERDA, I.BDDATAINIVAL, I.BDDATAFIMVAL
      FROM TMP_TCADPRO_INSUMOS_TEMP I
      WHERE I.BDSESSAO = :PRSESSAO      
      AND NOT EXISTS (
                      SELECT INCO.BDCODINCONSISTENCIA FROM VEF_INCON_TCADPRO INCO
                      WHERE INCO.BDSESSAO = :PRSESSAO
                      AND INCO.BDCODPROD = I.BDCODPROD
                     )
      INTO :FCODPROD, :FCODEMP, :FORDEM, :FREFPROD, :FCODPRODBASE,
           :FQTDCONSUMO, :FPERDA, :FDATAINIVAL, :FDATAFIMVAL
  DO
    BEGIN
      UPDATE OR INSERT INTO TCADPRO_INSUMOS(BDCODPROD, BDCODEMP, BDORDEM, BDREFERENCIA, BDCODPROINSUMO, BDQTDCONSUMO, BDPERDA, BDDATAINIVAL, BDDATAFIMVAL)
      VALUES(:FCODPROD, :FCODEMP, :FORDEM, :FREFPROD, :FCODPRODBASE, :FQTDCONSUMO, :FPERDA, :FDATAINIVAL, :FDATAFIMVAL) MATCHING(BDCODPROD, BDCODEMP, BDORDEM);
    END

  FOR SELECT I.BDALTCODPROD, I.BDCODEMP, I.BDALTCODFATCON, I.BDCODUNIMED, I.BDFATORCONVER, I.BDCODIGOEAN
      FROM TMP_TFATCONV_TEMP I
      WHERE I.BDSESSAO = :PRSESSAO
      AND NOT EXISTS (
                      SELECT P.BDCODINCONSISTENCIA FROM VEF_INCON_TCADPRO P
                      WHERE P.BDSESSAO = :PRSESSAO
                      AND I.BDCODPROD = P.BDCODPROD
                     )
      INTO :FCODPROD, :FCODEMP, :FORDEM, :FCODUNIMED, :FFATORCONVER, :FEAN
  DO
    BEGIN
      UPDATE OR INSERT INTO TFATCONV(BDCODPROD, BDCODEMP, BDCODFATCON, BDCODUNIMED, BDFATORCONVER, BDCODIGOEAN)
      VALUES(:FCODPROD, :FCODEMP, :FORDEM, :FCODUNIMED, :FFATORCONVER, :FEAN) MATCHING(BDCODPROD, BDCODEMP, BDCODFATCON);
    END
 
  FOR SELECT C.BDCODPROD, C.BDCODEMP, C.BDORDEM, C.BDCODITEM, C.BDQTDPROD
      FROM TMP_TCADPRO_CORREITENS_TEMP C
      WHERE C.BDSESSAO = :PRSESSAO
        AND NOT EXISTS (
                        SELECT P.BDCODINCONSISTENCIA FROM VEF_INCON_TCADPRO P
                        WHERE P.BDSESSAO = :PRSESSAO
                          AND P.BDCODPROD = C.BDCODPROD
                        )
      INTO :FCODPROD, :FCODEMP, :FORDEM, :FCODITEM, :FQTDPROD
  DO
    BEGIN
      UPDATE OR INSERT INTO TCADPRO_CORRELACAOITENS(BDCODPROD, BDCODEMP, BDORDEM, BDCODITEM, BDQTDPROD)
      VALUES(:FCODPROD, :FCODEMP, :FORDEM, :FCODITEM, :FQTDPROD) MATCHING(BDCODPROD, BDCODEMP, BDORDEM);
    END

END
^

/* Restore proc. body: SP_CONTAS_SEARCHCOMPONENT */
create or alter procedure SP_CONTAS_SEARCHCOMPONENT (
    PRCODPLAPADRAO integer,
    PRTEXT varchar(100),
    PREMPRESA integer = 0)
returns (
    BDCODTPLA integer,
    BDAPECTA varchar(20),
    BDCTALON varchar(40),
    BDNOMCTA varchar(100),
    BDTIPCTA integer)
as
declare variable WSQL varchar(1024);
declare variable WCLAATUAL DM_CLASSCONTAS;
declare variable WUSAPREP integer;
BEGIN
  prText = REPLACE(prtext, '''', '''''');
  wclaatual = '';
  if (PREMPRESA > 0) then
    BEGIN
      select first 1 COALESCE(BDCODMATRIZ, BDCODEMP) AS BDCODEMP
      from TEMPRESAS
      WHERE BDCODEMP = :prempresa
      INTO :prempresa;

      SELECT FIRST 1 BDCODEMP
      FROM VSUC_CONTAS_EMPRESA
      WHERE BDCODEMP = :prempresa
      INTO :WUSAPREP;
    END

  wSQL = ' select BDCTALON, bdtipcta, bdcodtpla, BDAPECTA, BDNOMCTA';
  wSQL = wSQL || ' from PLANOS_TPLA X';
  wSQL = wSQL || ' where (upper(BDCODTPLA) like ''' || UPPER(:prText) || '%''';
  wSQL = wSQL || ' or upper(BDAPECTA) like ''' || UPPER(:prText) || '%''';
  wSQL = wSQL || ' or upper(BDCTALON) like ''' || UPPER(:prText) || '%''';
  wSQL = wSQL || ' or upper(BDNOMCTA) like ''%' || UPPER(:prText) || '%'') ';
  wSQL = wSQL || ' and bdcodplapadrao = ' || :prcodplapadrao;

  if (wusaprep IS NOT NULL) then
    WSQL = WSQL || ' AND EXISTS(select first 1 BDCODEMP'
                || ' from PLANOS_TPLA P'
                || ' INNER JOIN vsuc_contas_empresa C ON (P.bdcodplapadrao = C.bdcodplapadrao AND P.bdcodtpla = C.bdcodtpla)'
                || ' where P.bdcodplapadrao = X.bdcodplapadrao AND P.bdctalon STARTING WITH X.bdctalon AND C.bdcodemp ='||prempresa||')';

  wSQL = wSQL || ' order by BDCTALON ';
  FOR EXECUTE STATEMENT wSQL INTO :bdctalon, :bdtipcta, bdcodtpla, bdapecta, bdnomcta DO
      BEGIN
        --#alt:96271 - 14/02/2019 - Carlos Machado - Essa regra do detalhamento da consolidada deve ficar
        IF (bdtipcta = 2) THEN
           BEGIN
             wclaatual = bdctalon;
             wSQL = 'select BDCODTPLA, BDAPECTA, BDCTALON, BDNOMCTA, BDTIPCTA from planos_tpla X where bdctalon like ''' || :bdctalon || '%'' and bdcodplapadrao=' || :prcodplapadrao;
             if (wusaprep IS NOT NULL) then
                WSQL = WSQL || ' AND EXISTS(select first 1 BDCODEMP'
                            || ' from PLANOS_TPLA P'
                            || ' INNER JOIN vsuc_contas_empresa C ON (P.bdcodplapadrao = C.bdcodplapadrao AND P.bdcodtpla = C.bdcodtpla)'
                            || ' where P.bdcodplapadrao = X.bdcodplapadrao AND P.bdctalon STARTING WITH X.bdctalon AND C.bdcodemp ='||prempresa||')';
             wSQL = wSQL || ' order by bdctalon ';

             FOR EXECUTE STATEMENT wsql INTO :bdcodtpla, :bdapecta, :bdctalon, :bdnomcta, :bdtipcta DO
                 SUSPEND;
           END
        ELSE
        IF (wclaatual = '' OR POSITION(wclaatual, bdctalon) <> 1) THEN
          BEGIN
            wclaatual = '';
           SUSPEND;
      END
END
END
^


/* Restore proc. body: SP_COPIA_PROGRAMAS_PLANO */
ALTER PROCEDURE SP_COPIA_PROGRAMAS_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 RETURNS(WCODPLAPROG INTEGER)
 AS
BEGIN
  DELETE FROM TPROGRAMAS WHERE bdCODPLAPROG = :codigonovo;

  IF (:codigonovo IS NULL OR (:codigonovo = 0)) THEN
     SELECT COALESCE(MAX(BDCODPLAPROG), 1) FROM TPLANO_PROGRAMAS INTO :wcodplaprog;
  ELSE
     wcodplaprog = :codigonovo;

  INSERT INTO TPROGRAMAS (BDCODPLAPROG,BDCODPROG,BDDESCPROG,BDCAMINHOPROG,BDICONEPROG,BDABREPROG,BDFORMPROG,BDHINTPROG,BDTIPOPROG,BDCODSIS)
  SELECT :wcodplaprog,X.BDCODPROG,X.BDDESCPROG,X.BDCAMINHOPROG,X.BDICONEPROG,X.BDABREPROG,X.BDFORMPROG,X.BDHINTPROG,X.BDTIPOPROG,X.BDCODSIS FROM TPROGRAMAS X WHERE X.BDCODPLAPROG = :codigocopiar;

END
^

/* Restore proc. body: SP_CRIA_DADOSCALC_BAIXA */
ALTER PROCEDURE SP_CRIA_DADOSCALC_BAIXA AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WLIQUIDO NUMERIC(18,6);
DECLARE VARIABLE WREFCOMP INTEGER;
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WDATAAUX DATE;
BEGIN
  /* Procedure Text */
  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdcodemp IS NOT NULL;

  /* 1 - Terceiros */
  FOR SELECT bdcodemp,bdcodter,bdcodserv,bdliquido FROM vrhf_base_calc_terc
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp, wcodcol, wreferencia,NULL,1,NULL,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 2 - 13º salario */
  FOR SELECT bdcodemp,bdcodcol,bdref13,bdliquido FROM vrhf_emp_t13sal
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,2,wreferencia,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 3 -  ad 13º */
  FOR SELECT bdcodemp,bdcodcol,bdrefa13,bdliquido FROM vrhf_emp_ta13sal
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,3,wreferencia,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 4 -  ad sal */
  FOR SELECT bdcodemp,bdcodcol,BDDATAAD,bdliquido FROM vrhf_emp_tadsal
   INTO
     :wcodemp,
     :wcodcol,
     :wdata,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,4,NULL,wdata,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 5 -  c 13º */
  FOR SELECT bdcodemp,bdcodcol,bdrefc13,bdref13,bdliquido FROM vrhf_emp_tc13sal
   INTO
     :wcodemp,
     :wcodcol,
     :wrefcomp,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,5,wreferencia,NULL,wrefcomp,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 6 - folha normal*/
  FOR SELECT bdcodemp,bdcodcol,bdreffn,bdliquido FROM vrhf_emp_tfolhanormal
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,6,wreferencia,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 7 - folha normal tomador */
  FOR SELECT bdcodemp,bdcodcol,bdreftomador,bdliquido FROM vrhf_emp_tfolhatomador
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,7,wreferencia,NULL,NULL,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 8 -  fc */
  FOR SELECT bdcodemp,bdcodcol,bdreffn,bdrefcomp,bdliquido,bddatapagfc FROM vrhf_emp_tfolhacomp
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wrefcomp,
     :wliquido,
     :wdata
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,8,wreferencia,wdata,wrefcomp,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 9 -  fct */
  FOR SELECT x.bdcodemp,x.bdcodcol,x.bdreftomador,x.bdliquido,x.bdrefcomp,x.bddatapagfc FROM vrhf_emp_tfoltomcomp x
   INTO
     :wcodemp,
     :wcodcol,
     :wreferencia,
     :wliquido,
     :wrefcomp,
     :wdata
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,9,wreferencia,wdata,wrefcomp,NULL,NULL,wliquido,NULL,NULL);
  END

  /* 10 -  férias */
  FOR SELECT x.bdcodemp,x.bdcodcol,x.bdliquido,x.bdiniperaquisfe,x.bdcodfe,x.bdiniperaquisfe,x.bdrefpagabofe FROM VRH_EMP_TFERIAS x
   INTO
     :wcodemp,
     :wcodcol,
     :wliquido,
     :wdata,
     :wreferencia,
     :wdataaux,
     :wrefcomp
   DO
  BEGIN
    EXECUTE PROCEDURE vrhf_sp_dados_baixa_calculo(wcodemp,NULL, NULL,wcodcol,10,NULL,NULL,NULL,wdata,wreferencia,wliquido,wdataaux,wrefcomp);
  END
END
^

/* Restore proc. body: SP_CRIA_DETGPSSEFIP */
ALTER PROCEDURE SP_CRIA_DETGPSSEFIP(PRCODEMP VARCHAR(32000),
PRANOMESPAG INTEGER,
PRTIPOGPS INTEGER,
PRTIPOEMISSAO INTEGER)
 RETURNS(BDOK INTEGER)
 AS
DECLARE VARIABLE wanomes INTEGER;
DECLARE VARIABLE wwhereemp VARCHAR(32000);
DECLARE VARIABLE wsqlemp VARCHAR(32000);
DECLARE VARIABLE wcodimpant INTEGER;
DECLARE VARIABLE wcodimp INTEGER;
DECLARE VARIABLE wsql VARCHAR(32000);
DECLARE VARIABLE wcodemp INTEGER;
DECLARE VARIABLE wcodtpcc INTEGER;
DECLARE VARIABLE wcompensacao NUMERIC(15,6);
DECLARE VARIABLE winiciocompensacao INTEGER;
DECLARE VARIABLE wfimcompensacao INTEGER;
DECLARE VARIABLE wacumulado NUMERIC(15,6);
DECLARE VARIABLE wacumuladoterc NUMERIC(15,6);
DECLARE VARIABLE wnotasfiscais NUMERIC(15,6);
DECLARE VARIABLE wnotascoop NUMERIC(15,6);
DECLARE VARIABLE wruralfisica NUMERIC(15,6);
DECLARE VARIABLE wruraljuridica NUMERIC(15,6);
DECLARE VARIABLE wsqlinsert VARCHAR(3000);
BEGIN
  /* Procedure Text */
  DELETE FROM tdetgpssefip;

  SELECT rdb$get_context('USER_SESSION', 'W_ANOMES') FROM rdb$database INTO wanomes;

  wcodimp = 9053;
  prcodemp = 'colcon.bdcodemp = 3';
--  pranomes = 201005;
  pranomespag = 201005;
  prtipogps = 0;
  prtipoemissao = 0;

  wsqlemp = 'select colcon.bdcodimp,colcon.bdcodemp'||
            ' from vw_tempresaimpostoref colcon'||
            ' where colcon.bddocarrecadacao = 12';

  IF (prcodemp IS NOT NULL) THEN
     wsqlemp = wsqlemp||' and '||prcodemp;

  wsqlemp = wsqlemp||' order by colcon.bdcodimp,colcon.bdcodemp';

  wcodimpant = 0;
  wwhereemp = '';
  FOR EXECUTE STATEMENT wsqlemp INTO
    : wcodimp,
    : wcodemp
  DO
    BEGIN
      IF ((wcodimp = wcodimpant) OR (wcodimpant = 0)) THEN
         BEGIN
           wcodimpant = wcodimp;
           IF (wwhereemp <> '') THEN
              wwhereemp = wwhereemp||',';
           wwhereemp = wwhereemp||wcodemp;
         END
      ELSE
         BEGIN
          wwhereemp = ''''||'colcon.bdcodemp in ('||wwhereemp||')'||'''';
          wsql = 'select x.bdcodemp,x.bdcodtpcc,x.bdtotcompensacao,x.bdtotvaloracumulado,x.bdtotvaloracumuladoterc,x.bdnfcoop,x.bdvalnotas,x.bdinicomp,x.bdfimcomp from vrhf_sp_gps('||wcodimpant||','||wwhereemp||',null,'||wanomes||','||pranomespag||','||prtipoemissao||',0,'||prtipogps||',0) x';
        
          FOR EXECUTE STATEMENT wsql INTO
            : wCODEMP,
            : wCODTPCC,
            : wCOMPENSACAO,
            : wACUMULADO,
            : wACUMULADOTERC,
            : wNOTASCOOP,
            : wNOTASFISCAIS,
            : wINICIOCOMPENSACAO,
            : wFIMCOMPENSACAO
        --    : wRURALFISICA,
        --    : wRURALJURIDICA
          DO
            BEGIN
              wsqlinsert = 'insert into tdetgpssefip(bdcodemp,bdcodtpcc,bdcompensacao,bdacumulado,bdacumuladoterc,bdnotascoop,bdNOTASFISCAIS,BDINICIOCOMPENSACAO,BDFIMCOMPENSACAO) values(';
              IF (wcodemp IS NULL) THEN
                 wsqlinsert = wsqlinsert||'null,';
              ELSE
                 wsqlinsert = wsqlinsert||wcodemp||',';
        
              IF (wcodtpcc IS NULL) THEN
                 wsqlinsert = wsqlinsert||'null,';
              ELSE
                 wsqlinsert = wsqlinsert||wcodtpcc||',';
        
              IF (wcompensacao IS NULL) THEN
                 wsqlinsert = wsqlinsert||'null,';
              ELSE
                 wsqlinsert = wsqlinsert||wcompensacao||',';
        
              IF (wacumulado IS NULL) THEN
                 wsqlinsert = wsqlinsert||'null,';
              ELSE
                 wsqlinsert = wsqlinsert||wacumulado||',';
        
              IF (wACUMULADOTERC IS NULL) THEN
                 wsqlinsert = wsqlinsert||'null,';
              ELSE
                 wsqlinsert = wsqlinsert||wACUMULADOTERC||',';
        
              IF (wnotascoop IS NULL) THEN
                 wsqlinsert = wsqlinsert||'null,';
              ELSE
                 wsqlinsert = wsqlinsert||wnotascoop||',';

              IF (wnotasfiscais IS NULL) THEN
                 wsqlinsert = wsqlinsert||'null,';
              ELSE
                 wsqlinsert = wsqlinsert||wnotasfiscais||',';
        
              IF (winiciocompensacao IS NULL) THEN
                 wsqlinsert = wsqlinsert||'null,';
              ELSE
                 wsqlinsert = wsqlinsert||winiciocompensacao||',';

              IF (wfimcompensacao IS NULL) THEN
                 wsqlinsert = wsqlinsert||'null';
              ELSE
                 wsqlinsert = wsqlinsert||wfimcompensacao||'';

              wsqlinsert = wsqlinsert||')';
        
              EXECUTE STATEMENT wsqlinsert;
            END

           wwhereemp = ''||wcodemp;
           wcodimpant = wcodimp;
         END

    END

    wwhereemp = ''''||'colcon.bdcodemp in ('||wwhereemp||')'||'''';
    wsql = 'select x.bdcodemp,x.bdcodtpcc,x.bdtotcompensacao,x.bdtotvaloracumulado,x.bdtotvaloracumuladoterc,x.bdnfcoop,x.bdvalnotas,x.bdinicomp,x.bdfimcomp from vrhf_sp_gps('||wcodimpant||','||wwhereemp||',null,'||wanomes||','||pranomespag||','||prtipoemissao||',0,'||prtipogps||',0) x';

    FOR EXECUTE STATEMENT wsql INTO
    : wCODEMP,
    : wCODTPCC,
    : wCOMPENSACAO,
    : wACUMULADO,
    : wACUMULADOTERC,
    : wNOTASCOOP,
    : wNOTASFISCAIS,
    : wINICIOCOMPENSACAO,
    : wFIMCOMPENSACAO
    --    : wRURALFISICA,
    --    : wRURALJURIDICA
    DO
    BEGIN
      wsqlinsert = 'insert into tdetgpssefip(bdcodemp,bdcodtpcc,bdcompensacao,bdacumulado,bdacumuladoterc,bdnotascoop,bdNOTASFISCAIS,BDINICIOCOMPENSACAO,BDFIMCOMPENSACAO) values(';

      IF (wcodemp IS NULL) THEN
         wsqlinsert = wsqlinsert||'null,';
      ELSE
         wsqlinsert = wsqlinsert||wcodemp||',';
    
      IF (wcodtpcc IS NULL) THEN
         wsqlinsert = wsqlinsert||'null,';
      ELSE
         wsqlinsert = wsqlinsert||wcodtpcc||',';
    
      IF (wcompensacao IS NULL) THEN
         wsqlinsert = wsqlinsert||'null,';
      ELSE
         wsqlinsert = wsqlinsert||wcompensacao||',';
    
      IF (wacumulado IS NULL) THEN
         wsqlinsert = wsqlinsert||'null,';
      ELSE
         wsqlinsert = wsqlinsert||wacumulado||',';
    
      IF (wACUMULADOTERC IS NULL) THEN
         wsqlinsert = wsqlinsert||'null,';
      ELSE
         wsqlinsert = wsqlinsert||wACUMULADOTERC||',';
    
      IF (wnotascoop IS NULL) THEN
         wsqlinsert = wsqlinsert||'null,';
      ELSE
         wsqlinsert = wsqlinsert||wnotascoop||',';
    
      IF (wnotasfiscais IS NULL) THEN
         wsqlinsert = wsqlinsert||'null,';
      ELSE
         wsqlinsert = wsqlinsert||wnotasfiscais||',';

      IF (winiciocompensacao IS NULL) THEN
         wsqlinsert = wsqlinsert||'null,';
      ELSE
         wsqlinsert = wsqlinsert||winiciocompensacao||',';

      IF (wfimcompensacao IS NULL) THEN
         wsqlinsert = wsqlinsert||'null';
      ELSE
         wsqlinsert = wsqlinsert||wfimcompensacao||'';

      wsqlinsert = wsqlinsert||')';
    
      EXECUTE STATEMENT wsqlinsert;
    END
  bdok = 1;
  SUSPEND;
END
^

/* Restore proc. body: SP_DADOS_EMP_REF */
ALTER PROCEDURE SP_DADOS_EMP_REF(PRWHEREEMP VARCHAR(32000),
PRREFINICIAL INTEGER,
PRREFFINAL INTEGER)
 RETURNS(BDCODMATRIZ INTEGER,
BDCODEMP INTEGER,
BDREFATU INTEGER,
BDREFEMP INTEGER)
 AS
DECLARE VARIABLE wSql BLOB SUB_TYPE 1 SEGMENT SIZE 16384;
DECLARE VARIABLE wWhere VARCHAR(32000);
DECLARE VARIABLE wRefAtu INTEGER;
DECLARE VARIABLE wAno INTEGER;
DECLARE VARIABLE wMes INTEGER;
BEGIN
  wRefAtu = :prRefInicial;

  wSql   = '';
  wWhere = '';

  wSql = :wSql || :wWhere;

  IF ((:prWhereEmp IS NOT NULL) AND (:prWhereEmp <> '')) THEN
    wWhere = ' where ' || :prWhereEmp;

  WHILE (:wRefAtu <= :prRefFinal) DO
    BEGIN
      IF (wSql <> '') THEN
        wSql = wSql || ' union all ';
        
      wSql = wSql || 'select coalesce(emp.bdcodmatriz, emp.bdcodemp) BDCODMATRIZ,';
      wSql = wSql || '       emp.bdcodemp,';
      wSql = wSql || '       ' || wRefAtu || ' BDREFATU,';
      wSql = wSql || '       coalesce ';
      wSql = wSql || '       ( ';
      wSql = wSql || '           (';
      wSql = wSql || '               select first 1 x.bdrefemp from tempresas_ref x ';
      wSql = wSql || '               where (x.bdcodemp = emp.bdcodemp) and ';
      wSql = wSql || '                     (CAST(X.BDREFEMP as VARCHAR(6)) <= ' || wRefAtu || ')';
      wSql = wSql || '               order by x.bdrefemp desc ';
      wSql = wSql || '           ),';
      wSql = wSql || '           ( ';
      wSql = wSql || '               select first 1 x.bdrefemp from tempresas_ref x ';
      wSql = wSql || '               where (x.bdcodemp = emp.bdcodemp) and ';
      wSql = wSql || '                     (cast(X.BDREFEMP as varchar(6)) > ' || wRefAtu || ')';
      wSql = wSql || '               order by x.bdrefemp ';
      wSql = wSql || '           )';
      wSql = wSql || '       ) bdRefEmp ';
      wSql = wSql || 'from tempresas emp ' || wWhere;

      wRefAtu = :wRefAtu + 1;

      wMes = CAST(RIGHT(:wRefAtu, 2) AS INTEGER);

      IF (:wMes > 12) THEN
        BEGIN
          wAno = CAST(LEFT(:wRefAtu, 4) AS INTEGER);

          wAno = wAno + 1;

          wRefAtu = CAST(wAno || '01' AS INTEGER);
        END 
    END

  wSql = 'select * from (' || wSql || ') order by bdcodmatriz, bdcodemp, bdrefatu ';

  FOR EXECUTE STATEMENT wSql
  INTO
    :BDCODMATRIZ,
    :BDCODEMP,
    :BDREFATU,
    :BDREFEMP
  DO
  BEGIN
    SUSPEND;
  END
END
^

/* Restore proc. body: SP_EMPPRESA_IMP */
ALTER PROCEDURE SP_EMPPRESA_IMP(PRCODIMP INTEGER,
PRREF INTEGER,
PRCODEMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDEMPIMP INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(1000);
BEGIN
  /* Procedure Text */
  IF (prcodimp IS NULL) THEN
     prcodimp = 0;

  IF (prref IS NULL) THEN
     prref = 0;

--  execute procedure sp_seta_competencia(:prref,null,null);
--  suspend;
  WSQL = 'select emp.bdcodemp, '||
         '        case when ei.bdcodimp is null then '||
         '           emp.bdcodmatriz '||
         '        else '||
         '           emp.bdcodemp '||
         '        end bdempimp '||
         '        from tempresas emp '||
--         '        left outer join VW_TEMPRESAIMPOSTO ei on (ei.bdcodemp = emp.bdcodemp and ei.bdcodimp = '||prcodimp||')';
         'left outer join (select * from tempresaimposto where bdcodimp = '||prcodimp||' and BDREFEMP <= '||prref||
                           ' and ((coalesce(BDREFFIMIMP,0) = 0) or (BDREFFIMIMP >= '||prref||') )) ei on (ei.bdcodemp = emp.bdcodemp) ';

  IF ((prcodemp IS NOT NULL) AND (prcodemp > 0))  THEN
     wsql = wsql||' where emp.bdcodemp = '||prCodEmp||' or (emp.bdcodmatriz = '||prcodemp||') ';
  wsql = wsql||'        group by emp.bdcodemp, bdempimp ';

  FOR EXECUTE STATEMENT wsql INTO bdcodemp,bdempimp DO
    SUSPEND;
END
^

/* Restore proc. body: SP_EXCLUI_ONLINE */
ALTER PROCEDURE SP_EXCLUI_ONLINE(PREMPRESA INTEGER,
PRCHAVE INTEGER)
 AS
DECLARE VARIABLE wsql VARCHAR(300);
BEGIN
  /* Procedure Text */
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    wsql = 'delete from vsuc_empresas_tlan x where x.bdcodemp = '||prempresa||' and x.bdchave = '||prchave;
    EXECUTE STATEMENT wsql;
  end
--  suspend;
END
^

/* Restore proc. body: SP_EXCLUI_ONLINE_CC */
ALTER PROCEDURE SP_EXCLUI_ONLINE_CC(PREMPRESA INTEGER,
PRCHAVE INTEGER,
PRCODCENTRO INTEGER,
PRCODTPCC INTEGER,
PRDEBCRE INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(300);
BEGIN
  /* Procedure Text */
  wsql = 'delete from vsuc_empresas_tlCC x where x.bdcodemp = '||prempresa||' and x.bdchave = '||prchave;
  wsql =   wsql ||' and bdcodcentro = '||prCODCENTRO || 'and bdcodtpcc = '||prCODTPCC || ' and bdDEBCRE = '||PRDEBCRE;


  EXECUTE STATEMENT wsql;

--  suspend;
END
^

/* Restore proc. body: SP_EXCLUI_VERBA_DE_TUDO */
CREATE OR ALTER PROCEDURE SP_EXCLUI_VERBA_DE_TUDO (
    PRCODVER INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODVER INTEGER;
BEGIN
  wsql = 'select first 1 BDCODVER from ('||
         'select BDCODVER from VRHF_BASE_ITEMS_CALCTERC where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TFICHAHE where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TFICHAHN where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TFICHAOUTRAS where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TFICHARV where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_THIST_FOLHACOMP where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TPLANLANC where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TPLANLANC_ADSAL where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TPLANLANC_FA where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TRATEIO_VERBAS where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBA13 where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAA13 where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAAD where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAC13 where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAFA where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAFC where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAFCTOMADOR where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAFE where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAFN where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAFN_PREV_RESC where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAFT_PREV_RESC where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBAPREPFN where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVERBATOMADOR where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRH_EMP_TDEP_PENSAO where BDCODVER = '||prCODVER||
         'union all '||
         'select BDCODVER from VRH_EMP_TPARCELAMENTOS where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVSCOL where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVNCOL where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVSEMP where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVNEMP where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_EMP_TVSEMP_ESP where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_FUNCOES_TVNFUC where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_FUNCOES_TVSFUC where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_FUNCOES_TVSFUC_ESP where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from VRHF_BASE_TVERBASEMP where BDCODVER = '||prCODVER||' '||
         'union all '||
         'select BDCODVER from TCONF_CONTAS_ONLINE where BDCODVER = '||prCODVER||' '||
     'union all '||
     'select BDCODVER from VRHF_EMP_TVERBAINT where BDCODVER = '||prCODVER||' '||
     'union all '||
     'select BDCODVER from VRHF_EMP_TVERBATOMINT where BDCODVER = '||prCODVER||' '||
     ')';

  EXECUTE STATEMENT wsql INTO :wcodver;

  IF (wcodver <> 0) THEN
     UPDATE VRH_BASE_TVERBAS SET BDDESCVER = '*** NÃO UTILIZAR ***', BDDESCREDVER = '*** NÃO UTILIZAR ***' WHERE BDCODVER = :prcodver;
  ELSE
     BEGIN
       -- 17901 | Marcelo B. M. | 08/06/2017 | Trocada ordem das tabelas
       DELETE FROM VRHF_BASE_TRUBRICAS_DOM_VER_PD WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TVERBAS WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TVERBAS_PADRAO WHERE BDCODVERPD = :prcodver;
       DELETE FROM VRHF_BASE_ITEMS_CALCTERC WHERE BDCODVER = :prcodver;       
       DELETE FROM VRHF_BASE_TVNPRES WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_BASE_TVNSIND WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_BASE_TVNTER WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_BASE_TVSPRES WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_BASE_TVSPRES_ESP WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_BASE_TVSSIND WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_BASE_TVSSIND_ESP WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_BASE_TVSTER WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_CUSTOS_TVNCUSTO WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_CUSTOS_TVSCUSTO WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_CUSTOS_TVSCUSTO_ESP WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TFICHAHE WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TFICHAHN WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TFICHAOUTRAS WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TFICHARV WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_THIST_FOLHACOMP WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TPLANLANC WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TPLANLANC_ADSAL WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TPLANLANC_FA WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TRATEIO_VERBAS WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBA13 WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAA13 WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAA13_RAT WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAAD WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAC13 WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAFA WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAFC WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAFCTOMADOR WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAFE WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAFN WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAFN_PREV_RESC WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAFT_PREV_RESC WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBAPREPFN WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBARFE WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBATOMADOR WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVERBA_13_RAT WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVNCOL WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVNEMP WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVSCOL WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVSEMP WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_TVSEMP_ESP WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_EMP_VERBAS_GRCS WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_FUNCOES_TVNFUC WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_FUNCOES_TVSFUC WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_FUNCOES_TVSFUC_ESP WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_MTE_TVERBASCONF WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TCALCVESP WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TCALCVESP WHERE BDCODVERCVE = :prcodver;
       DELETE FROM VRH_BASE_TCONF_FICHA_HE WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TCONF_FICHA_HN WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TCONF_FICHA_RV WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TCONF_FICHA_OUT WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TITENSBLUESOFT WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TNATUREZA_VERBAS_GRUPO WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TPLACONFVERBAPONTOITEM WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TPLANO_LPL_ITEM WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TPLA_TSERV WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TPREPESTAB WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TPREPSIT WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TPREPSIT WHERE BDCODVER15DIAS = :prcodver;
       DELETE FROM VRH_BASE_TPREPSIT_DIA WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TPREPSIT_DIA WHERE BDCODVER15DIAS = :prcodver;
       DELETE FROM VRH_BASE_TRUBRICAESOCIAL_VER WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TRUBRICAES_VER_PD WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TRUBRICAS_DOM_VER WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TRUBRICAS_VERBA WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TRUBRICAS_VERBA_TP WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TSALHORESP WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TSINDTREF WHERE BDVERFERIST = :prcodver;
       DELETE FROM VRH_BASE_TSINDTREF WHERE BDVERMULRESST = :prcodver;
       DELETE FROM VRH_BASE_TVERBASEMP_PADRAO WHERE BDCODVER = :prcodver;
       DELETE FROM VRHF_BASE_TVERBASEMP WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TVERBASESP WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_BASE_TVERBASESP WHERE BDCODVERESP = :prcodver;
       DELETE FROM VRH_EMP_CONF_VCON_VERBAS WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_EMP_TDEP_PENSAO WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_EMP_TPARCELAMENTOS WHERE BDCODVER = :prcodver;
       DELETE FROM VRH_EMP_TPROCESSOS_VERBAS WHERE BDCODVERBA = :prcodver;
       DELETE FROM VRH_EMP_VERBA_RHNET WHERE BDCODVER = :prcodver;
       DELETE FROM TCONF_CONTAS_ONLINE WHERE BDCODVER = :prcodver;       
       DELETE FROM VRHF_EMP_TVERBAINT WHERE BDCODVER = :prcodver;       
       DELETE FROM VRHF_EMP_TVERBATOMINT WHERE BDCODVER = :prcodver;       
     END

END
^

/* Restore proc. body: SP_EXCLUSAO_CBO_NAOUSADO */
ALTER PROCEDURE SP_EXCLUSAO_CBO_NAOUSADO(BDCODCBO INTEGER)
 AS
DECLARE VARIABLE WCODCBO INTEGER;
DECLARE VARIABLE WCODCBOUSADO INTEGER;
DECLARE VARIABLE WCODCBOTSIN INTEGER;
DECLARE VARIABLE WSQL VARCHAR(20000);
BEGIN
  wSql = 'select terc.bdcodcbo, terc.bdcodcbotsin from vrh_base_tterc_vinc terc where terc.bdcodcbo = ' || :bdcodcbo ||
         ' union all select fuc.bdcodcbo, fuc.bdcodcbotsin from vrh_funcoes_tfuc fuc where fuc.bdcodcbo = ' || :bdcodcbo;

  wCodCBOUsado = 0;

  FOR EXECUTE STATEMENT wSql
  INTO
    wCodCBO,
    wCodCBOTSin
  DO
  BEGIN
    wCodCBOUsado = wCodCBOUsado + 1;
  END

  IF (wCodCBOUsado = 0) THEN
    DELETE FROM vrh_base_tcbo WHERE bdcodcbo = :bdcodcbo;
END
^

CREATE OR ALTER procedure SP_EXISTE_COLABORADOR_DOWNLOAD (PRCODCOL integer,PRCODEMP integer)
returns (BDCODIGO integer)
as
BEGIN
  prcodcol = coalesce(prcodcol, 0);
  bdcodigo = null;
  SELECT C.bdcodigo FROM TDEFFUNCIONARIODOWN C WHERE C.bdcodestab = :prcodemp AND C.bdcodigo = :prcodcol INTO :bdcodigo;

  IF ((bdcodigo IS NULL) OR (bdcodigo = 0)) THEN
     BEGIN
       bdcodigo = prcodcol;
       SUSPEND;
     END
  ELSE
     BEGIN
       prcodcol = prcodcol + 1;
       SELECT bdcodigo FROM SP_EXISTE_COLABORADOR_DOWNLOAD(:prcodcol,:prcodemp) INTO :bdcodigo;
       SUSPEND;
     END
END^

/* Restore proc. body: SP_EXISTE_COLABORADOR_NOVO */
create or alter procedure SP_EXISTE_COLABORADOR_NOVO (
    PRCODEMP integer,
    PRCODCOL integer)
returns (
    BDCODCOL integer)
as
BEGIN
  /* Procedure Text */
  prcodcol = coalesce(prcodcol, 0);
  bdcodcol = null;
  SELECT C.bdcodcol FROM vrh_emp_tcolcon C WHERE C.bdcodemp = :prcodemp AND C.bdcodcol = :prcodcol INTO :bdcodcol;

  IF ((bdcodcol IS NULL) OR (bdcodcol = 0)) THEN
     BEGIN
       bdcodcol = prcodcol;
       SUSPEND;
     END
  ELSE
     BEGIN
       prcodcol = prcodcol + 1;
       SELECT bdcodcol FROM sp_existe_colaborador_novo(:prcodemp,:prcodcol) INTO :bdcodcol;
       SUSPEND;
     END
END^

/* Restore proc. body: SP_EXP_ATIVA_CONTABIL */
CREATE OR ALTER PROCEDURE SP_EXP_ATIVA_CONTABIL (
    PRCODEMP INTEGER,
    PRDATAINICIAL DATE,
    PRDATAFINAL DATE,
    PRCTALONINI VARCHAR(40),
    PRCTALONFIM VARCHAR(40),
    PRCODPLANOPADRAO INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRCONTABILIZADATABAIXA INTEGER = 0,
    PRBAIXAINDIVIDUAL INTEGER = 0,
    PRORDER VARCHAR(10) = 'ASC')
RETURNS (
    BDREF VARCHAR(10),
    BDREFINTEIRO INTEGER,
    BDCODTPLABEM INTEGER,
    BDCTALONBEM VARCHAR(40),
    BDNOMTPLABEM VARCHAR(100),
    BDCODNOMTPLABEM VARCHAR(110),
    BDCODBEM INTEGER,
    BDNOMBEM VARCHAR(200),
    BDCODNOMBEM VARCHAR(210),
    BDCODTPCC INTEGER,
    BDNOMTPCC VARCHAR(40),
    BDDEPRECIACAOPERIODO NUMERIC(18,6),
    BDVALORBAIXAPERIODO NUMERIC(18,6),
    BDDEPRECIACAOACUMULADA NUMERIC(18,6),
    BDTAXA NUMERIC(9,6),
    BDDATATAXADEP DATE,
    BDVALORRESIDUAL NUMERIC(18,6),
    BDCODPLAPADRAO INTEGER,
    BDCODHIST INTEGER,
    BDCTADEBITODEPRE INTEGER,
    BDCTACREDITODEPRE INTEGER,
    BDHISTORICODEPRE INTEGER,
    BDCTADEBITOBAIXA INTEGER,
    BDCTACREDITOBAIXA INTEGER,
    BDHISTORICOBAIXA INTEGER,
    BDCTADEBITODEPBAI INTEGER,
    BDCTACREDITODEPBAI INTEGER,
    BDHISTORICODEPBAI INTEGER,
    BDDATABAIXA DATE,
    BDCOMPLEMENTOBAIXA VARCHAR(200),
    BDCODBAIXA INTEGER,
    BDRESIDUALDEB INTEGER,
    BDRESIDUALCRE INTEGER,
    BDRESIDUALHIS INTEGER,
    BDVALORRESIDUALBAIXA NUMERIC(15,2),
    BDCAPITALDEB INTEGER,
    BDCAPITALCRE INTEGER,
    BDCAPITALHIS INTEGER,
    BDVALORCAPITAL NUMERIC(15,2),
    BDPERDACAPITALDEB INTEGER,
    BDPERDACAPITALCRE INTEGER,
    BDPERDACAPITALHIS INTEGER,
    BDVALORBAIXATOTAL NUMERIC(15,2),
    BDVALORAQUISICAO NUMERIC(15,2),
    BDDEPCCIBE DM_BOOLEAN,
    BDBAIDEPCCIBE DM_BOOLEAN,
    BDBAIAQUICCIBE DM_BOOLEAN,
    BDRESIDUALCCIBE DM_BOOLEAN,
    BDCAPITALCCIBE DM_BOOLEAN,
    BDPERDACAPITALCCIBE DM_BOOLEAN)
AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WDATINI DATE;
DECLARE VARIABLE WDATFIN DATE;
DECLARE VARIABLE WDATABAIXA DATE;
DECLARE VARIABLE WCOMPENSACAOBAIXAPERANTERIOR NUMERIC(15,6);
DECLARE VARIABLE WDEPMESBAIXABEM VARCHAR(5);
DECLARE VARIABLE WVALORBAIXA NUMERIC(15,6);
DECLARE VARIABLE WTOTALMESESDEPRECIACAO INTEGER;
DECLARE VARIABLE WMESESDEPRECIADOS INTEGER;
DECLARE VARIABLE WDEPMESAQUIBEM VARCHAR(15);
DECLARE VARIABLE WDEPDIARIA VARCHAR(10);
DECLARE VARIABLE WDATORIAQUIBEM DATE;
DECLARE VARIABLE WNUMDIAS SMALLINT;
DECLARE VARIABLE WDATAFIMDEP DATE;
DECLARE VARIABLE WDEPANT SMALLINT;
DECLARE VARIABLE WBAIXATOTALDIA DOUBLE PRECISION;
DECLARE VARIABLE WBAIXAPARCIALDIA NUMERIC(15,6);
DECLARE VARIABLE WCOMPLEMENTOBAIXA VARCHAR(200);
DECLARE VARIABLE WBAIXAEXP INTEGER;
DECLARE VARIABLE WVALORAQUISICAOORIGINAL NUMERIC(15,6);
DECLARE VARIABLE WSOMA NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOANTERIOR NUMERIC(15,2);
BEGIN
  PRDATAINICIAL = extract(MONTH FROM PRDATAINICIAL)||'/01/'||extract(year FROM PRDATAINICIAL);
  prdatafinal = extract(MONTH FROM PRDATAFINAL)||'/01/'||extract(year FROM PRDATAFINAL);
  prdatafinal = DATEADD(MONTH, 1, prdatafinal);
  prdatafinal = DATEADD(DAY, -1, prdatafinal);
  
 --alt:8005 - Adicionado parâmetros tbem.BDDEPMESAQUIBEM, tbem.BDDEPDIARIA, tbem.BDDATORIAQUIBEM, tbem.BDNUMDIAS. Pedro
 --alt:9598 - Adicionados parâmetros tpcc.BDCODTPCC, tpcc.BDNOMCTA. Pedro
 wsql = 'select tbem.bdcodbem, tbem.BDNOMBEM, tpla.BDCODTPLA, tpla.bdctalon, tpla.bdnomcta, tpcc.BDCODTPCC, tpcc.BDNOMCTA, ';
 wsql = wsql||' tbem.BDDEPMESBAIXABEM, tbem.BDDEPMESAQUIBEM, tbem.BDDEPDIARIA, tbem.BDDATORIAQUIBEM, tbem.BDNUMDIAS ';
 wsql = wsql||' from empresas_tbem tbem ';
 wsql = wsql||' left outer join planos_tpla tpla on ((tpla.bdcodplapadrao = ' || :prcodplanopadrao || ')' || ' and (tpla.bdcodplapadrao = tbem.bdcodplapadrao and tpla.bdcodtpla = tbem.bdcodtpla)) ';
 --alt:9598 - Adicionado left outer join para trazer a descrição do centro de custos. Pedro
 wsql = wsql||' left outer join CENTROS_TPCC tpcc on (tpcc.BDCODCENTRO = tbem.BDCODCENTRO and tpcc.BDCODTPCC = tbem.BDCODTPCC) ';
 wsql = wsql||' where (tbem.bdcodemp = ' || :prcodemp || ') ';
 wsql = wsql||' and (tpla.bdctalon between '''|| prctalonini ||''' and '''|| prctalonfim ||''') ';
 wsql = wsql||' Order By tpla.bdctalon, tbem.bdcodbem '||PRORDER;

 --alt:14256 - 06/07/2016 - Alterados nomes dos campos para melhor distinção, pois agora retorna várias contas. Pedro
 FOR EXECUTE STATEMENT wsql INTO :bdcodbem , :bdnombem,  :bdcodtplabem, :bdctalonbem, :bdnomtplabem, :bdcodtpcc, :bdnomtpcc, :wdepmesbaixabem, :wdepmesaquibem, :wdepdiaria, :wdatoriaquibem, :wnumdias DO
   BEGIN
     bddepreciacaoperiodo = 0;
     bdvalorbaixaperiodo = 0;
     bdvalorcapital = 0;
     bddepreciacaoacumulada = 0;

     wdatini = prdatainicial;
     wdatfin = addmonth(wdatini, 1)-1;

      WHILE (wdatfin <= prdatafinal) DO
       BEGIN
         bddepreciacaoperiodo = 0;
         bdvalorbaixaperiodo = 0;
         bdvalorcapital = 0;
         bddepreciacaoacumulada = 0;
         bdcodnombem = bdcodbem || ' -  ' || bdnombem;
         bdcodnomtplabem = bdcodtplabem || ' -  ' || bdnomtplabem; --alt:14256 - 06/07/2016 - Alterados nomes dos campos para melhor distinção, pois agora retorna várias contas. Pedro
         bdrefinteiro = SUBSTRING(CAST(wdatfin AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(wdatfin AS VARCHAR(10)) FROM 6 FOR 2);
         bdref = SUBSTRING(CAST(wdatfin AS VARCHAR(10)) FROM 6 FOR 2)||'/'|| SUBSTRING(CAST(wdatfin AS VARCHAR(10)) FROM 1 FOR 4);

         --#alt:91871. Ana - 30/10/2018
         --#alt:93954. Machado - 15/01/2019 - Foi alterado para permitir baixas completamente individuais
         bddatabaixa = null;
         wdatabaixa = null;
         WCOMPLEMENTOBAIXA = '';
         if (PRCONTABILIZADATABAIXA = 1 or PRBAIXAINDIVIDUAL = 1) then
           BEGIN
             WDEPANT = 0;
             --#alt:91871. Alterei pra pegar todas as baixas do período e contabiliza-las individualmente. Ana - 30/10/2018
             for select bai.bddatbai, BAI.BDVALBAI, BAI.BDCOMPLBAI, bai.bdcodbai from EMPRESAS_TBAI bai
                 where (bai.BDCODEMP = :prcodemp AND bai.BDCODBEM = :bdcodbem AND bai.BDCONTABILIZACAO = :prContabilizacao AND bai.BDDATBAI <= :wdatfin AND bai.BDDATBAI >= :wdatini)
                 order by BDDATBAI
                 into :wdatabaixa, :WBAIXAPARCIALDIA, :WCOMPLEMENTOBAIXA, :WBAIXAEXP do
               begin
                 if (PRBAIXAINDIVIDUAL = 1) then
                  begin
                     select sum(bai.BDVALBAI) from EMPRESAS_TBAI bai
                     where (bai.BDCODEMP = :prcodemp AND bai.BDCODBEM = :bdcodbem AND bai.BDCONTABILIZACAO = :prContabilizacao AND bai.BDDATBAI = :wdatabaixa)
                     INTO :WBAIXATOTALDIA;
                   end

                 IF ((WDEPANT <> 0) and ((bddepreciacaoperiodo > 0) OR (bdvalorbaixaperiodo > 0))) THEN
                   BEGIN
                     bddepreciacaoperiodo = 0;
                     wSoma = cast((cast(wvalorbaixa as double precision) / cast(WVALORAQUISICAOORIGINAL as double precision)) * cast(bddepreciacaoperiodo+wdepreciacaoanterior as double precision) as numeric(15,2));
                     bdvalorcapital = wSoma + bdvalorcapital;
                     SUSPEND;
                   END
                 BDCOMPLEMENTOBAIXA = WCOMPLEMENTOBAIXA;
                 bdcodbaixa         = wbaixaexp;
                 SELECT prdepreciacaoperiodo, prcompensacaobaixaperanterior, prdatabaixa, prctadebitodepre, prtaxadepreciacaoanual,
                        prdatataxadepreciacao, prvalorresidualcontabil, prvalorbaixa, prtotalmesesdepreciacao, prmesesdepreciados,
                        bdvalorresidual, PRVALORAQUISICAOORIGINAL, bdvalorcapital, prvaloraquisicaooriginal,prdepreciacaoacumuladaanterior
                        FROM sp_cons_calc_dep(:prcodemp, :bdcodbem, :wdatabaixa, :wdatabaixa, 0, :prcontabilizacao)
                        INTO :bddepreciacaoperiodo, :wcompensacaobaixaperanterior, :wdatabaixa, :bdctadebitodepre, :bdtaxa,
                             :bddatataxadep, :bdvalorresidual, :wvalorbaixa, :wtotalmesesdepreciacao, :wmesesdepreciados,
                             BDVALORRESIDUALBAIXA, WVALORAQUISICAOORIGINAL, :bdvalorcapital, :BDVALORAQUISICAO, :wdepreciacaoanterior;
                     bdvalorbaixaperiodo = wvalorbaixa;
                     --alt:8005 - Retira um mês da contabilização porque quando é pra depreciar no mês da aquisição do bem vem um mês a mais do que deveria. Pedro
                     IF ((UPPER(wdepmesaquibem) = 'FALSE') AND (UPPER(wdepmesbaixabem) = 'TRUE')) THEN
                       wmesesdepreciados = wmesesdepreciados - 1;

                     SELECT FIRST 1 bem.BDCODEMP, bem.BDCODBEM, bem.BDNOMBEM, bem.BDCODTPLA AS BDCODTPLABEM, bem.BDCODPLAPADRAO, COALESCE(bai.BDCODHIST, ibe.BDCODHIST),
                      CASE WHEN dep.BDDATFIMCALCBEM IS NOT NULL THEN dep.BDDATFIMCALCBEM
                           WHEN dep.BDCODDEP IS NOT NULL THEN DATEADD(MONTH, ((100 / dep.BDTAXADEP) * 12), bem.BDDATORIAQUIBEM)
                           WHEN (bem.BDVIDAUTIL IS NOT NULL) AND (bem.BDVIDAUTIL > 0) THEN DATEADD(MONTH, bem.BDVIDAUTIL, bem.BDDATORIAQUIBEM) END AS BDDATAFINALCALCULO,
                      CASE WHEN dep.BDCTADEBITODEPRE IS NULL THEN ibe.BDDEPDEBIBE ELSE dep.BDCTADEBITODEPRE END AS BDCTADEBITODEPRE, ibe.BDDEPCREIBE, ibe.BDDEPHISTIBE,
                      COALESCE(bai.BDBAIDEPDEBBAI, ibe.BDBAIDEPDEBIBE), COALESCE(bai.BDBAIDEPCREBAI, ibe.BDBAIDEPCREIBE), COALESCE(bai.BDBAIDEPHISTBAI, ibe.BDBAIDEPHISTIBE),
                      COALESCE(bai.BDBAIAQUIDEBBAI, ibe.BDBAIAQUIDEBIBE), COALESCE(bai.BDBAIAQUICREBAI, ibe.BDBAIAQUICREIBE), COALESCE(bai.BDBAIAQUIHISTBAI, ibe.BDBAIAQUIHISTIBE),
                      coalesce(ibe.bdresidualdeb,0),coalesce(ibe.bdresidualcre,0),coalesce(ibe.bdresidualhis,0),
                      coalesce(ibe.bdcapitaldeb,0),coalesce(ibe.bdcapitalcre,0),coalesce(ibe.bdcapitalhis,0), bai.bdvalvenbai - bai.bdvalbai as bdvalorcapital,
                      coalesce(ibe.bdperdacapitaldeb,0),coalesce(ibe.bdperdacapitalcre,0),coalesce(ibe.bdperdacapitalhis,0), BDDEPCCIBE, BDBAIDEPCCIBE, BDBAIAQUICCIBE,
                      BDRESIDUALCCIBE, BDCAPITALCCIBE, BDPERDACAPITALCCIBE
                     FROM EMPRESAS_TBEM bem
                     LEFT JOIN EMPRESAS_TDEPRECIACAO dep ON (dep.BDCODEMP = bem.BDCODEMP AND dep.BDCODBEM = bem.BDCODBEM AND dep.BDCONTABILIZACAO = :prContabilizacao AND
                                                             ((dep.BDDATINICALCBEM IS NULL) OR (dep.BDDATINICALCBEM <= :wdatfin)) AND
                                                             ((dep.BDDATFIMCALCBEM IS NULL) OR (dep.BDDATFIMCALCBEM >= :wdatfin)))
                     LEFT JOIN EMPRESAS_TBAI bai ON (bai.BDCODEMP = bem.BDCODEMP AND bai.BDCODBEM = bem.BDCODBEM AND bai.bdcodbai = :WBAIXAEXP)
                     LEFT JOIN EMPRESAS_TIBE ibe ON (ibe.BDCODEMP = bem.BDCODEMP AND ibe.BDCODPLAPADRAO = bem.BDCODPLAPADRAO AND ibe.BDCODTPLA = bem.BDCODTPLA AND ibe.BDCONTABILIZACAO = :prContabilizacao)
                     WHERE bem.BDCODEMP = :prcodemp
                       AND bem.BDCODBEM = :bdcodbem
                     ORDER BY dep.BDDATFIMCALCBEM DESC, bai.BDDATBAI DESC
                     INTO :prcodemp, :bdcodbem, :bdnombem, :bdcodtplabem,
                          :bdcodplapadrao, :bdcodhist, :wdatafimdep,
                          :bdctadebitodepre, :bdctacreditodepre, :bdhistoricodepre,
                          :bdctadebitobaixa, :bdctacreditobaixa, :bdhistoricobaixa,
                          :bdctadebitodepbai, :bdctacreditodepbai, :bdhistoricodepbai,
                          :bdresidualdeb,:bdresidualcre, :bdresidualhis,
                          :bdcapitaldeb, :bdcapitalcre,  :bdcapitalhis, :bdvalorcapital,
                          :bdperdacapitaldeb, :bdperdacapitalcre, :bdperdacapitalhis,
                          :bddepccibe, :bdbaidepccibe, :bdbaiaquiccibe,
                          :bdresidualccibe, :bdcapitalccibe, :bdperdacapitalccibe;
                     --alt:14256 - Fim

                     IF  ((bdresidualdeb > 0) and (bdresidualcre > 0) and (bdresidualhis > 0)) THEN
                        begin
                          if ((wvalorbaixa > 0) and (wvalorbaixa >= wVALORAQUISICAOORIGINAL)) then
                             bddepreciacaoperiodo =  bddepreciacaoperiodo - coalesce(BDVALORRESIDUALBAIXA,0);
                        end
                    else
                        begin
                            BDVALORRESIDUALBAIXA = 0;
                        end

                     --alt:14256 - 11/07/2016 - Apenas se há baixa no período, posteriormente será tratado a baixa antes ou depois do término da depreciação. Pedro
                     IF (bdvalorbaixaperiodo > 0) THEN
                       BEGIN
                         --alt:8005 - Adiciona um mês porque quando é pra depreciar no mês da baixa do bem vem com um mês a menos do que deveria. Pedro
                         IF ((UPPER(wdepmesbaixabem) = 'TRUE') AND (UPPER(wdepmesaquibem) = 'FALSE')) THEN
                            wmesesdepreciados = wmesesdepreciados + 1;

                         --#alt:91871. Não soma o valor da depreciação. Ana - 05/11/2018
                         IF ((wdatafimdep IS NOT NULL) AND (wdatafimdep < wdatfin) AND (COALESCE(wdepmesbaixabem, 'FALSE') <> 'TRUE') AND (wvalorbaixa >= wVALORAQUISICAOORIGINAL)) THEN
                           BEGIN
                             SELECT PRDEPRECIACAOACUMULADAATUAL "prdepreciacaoacumuladaatual"
                             FROM sp_cons_calc_dep(:prcodemp, :bdcodbem , addmonth(:wdatini,-1) , addmonth(:wdatfin,-1) ,0,:prcontabilizacao)
                             INTO :wcompensacaobaixaperanterior;
                             bddepreciacaoacumulada = wcompensacaobaixaperanterior;
                             --Alt:159451 - Ruan Eliabe - Comentado essa linha pois ele ja faz essa validação abaixo.
                             --wSoma = cast((cast(wvalorbaixa as double precision) / cast(WVALORAQUISICAOORIGINAL as double precision)) * cast(bddepreciacaoperiodo+wdepreciacaoanterior as double precision) as numeric(15,2));
                             --bdvalorcapital = wSoma + bdvalorcapital;
                           END
                         ELSE
                           bddepreciacaoacumulada = wcompensacaobaixaperanterior;

                         IF  (wdatabaixa BETWEEN :wdatini AND :wdatfin)  THEN
                           begin
                             bdvalorbaixaperiodo = bdvalorbaixaperiodo;
                             if (PRBAIXAINDIVIDUAL = 1 and WBAIXAPARCIALDIA < WBAIXATOTALDIA) then
                              BEGIN
                               WBAIXATOTALDIA = WBAIXAPARCIALDIA / WBAIXATOTALDIA;
                               BDVALORBAIXAPERIODO = WBAIXAPARCIALDIA;
                               BDDEPRECIACAOACUMULADA = BDDEPRECIACAOACUMULADA * WBAIXATOTALDIA;
                              END
                             --#alt:91871. Ana - 30/10/2018
                             bddatabaixa = wdatabaixa;
                           end
                         ELSE
                            bdvalorbaixaperiodo = 0;
                       END

                     if (WDEPANT = 0) then
                       WDEPANT = 1;
                END

             --#alt:91871. Para quando ouver mais baixas no mesmo mês deve zerar todas as outras depreciações e levar apenas a depreciação atual do mês sem ser individual por baixa. Ana - 06/11/2018
             IF (WDEPANT > 0)  THEN
               BEGIN
                 SELECT prdepreciacaoperiodo, prvalorbaixareal
                 FROM sp_cons_calc_dep(:prcodemp, :bdcodbem, :wdatini, :wdatfin, 0, :prcontabilizacao)
                 INTO :bddepreciacaoperiodo, :bdvalorbaixatotal;
                 wSoma = cast((cast(wvalorbaixa as double precision) / cast(WVALORAQUISICAOORIGINAL as double precision)) * cast(bddepreciacaoperiodo+wdepreciacaoanterior as double precision) as numeric(15,2));
                 bdvalorcapital = wSoma + bdvalorcapital;
                 SUSPEND;
               END

           END

         if (wdatabaixa is null) then
           begin
             SELECT prdepreciacaoperiodo, prcompensacaobaixaperanterior, prdatabaixa, prctadebitodepre, prtaxadepreciacaoanual,
                    prdatataxadepreciacao, prvalorresidualcontabil, prvalorbaixa, prtotalmesesdepreciacao, prmesesdepreciados,
                    bdvalorresidual, PRVALORAQUISICAOORIGINAL, bdvalorcapital, prvalorbaixareal, prvaloraquisicaooriginal,prdepreciacaoacumuladaanterior
                    FROM sp_cons_calc_dep(:prcodemp, :bdcodbem, :wdatini, :wdatfin, 0, :prcontabilizacao)
                    INTO :bddepreciacaoperiodo, :wcompensacaobaixaperanterior, :wdatabaixa, :bdctadebitodepre, :bdtaxa,
                         :bddatataxadep, :bdvalorresidual, :wvalorbaixa, :wtotalmesesdepreciacao, :wmesesdepreciados,
                         BDVALORRESIDUALBAIXA,wVALORAQUISICAOORIGINAL, :bdvalorcapital, :bdvalorbaixatotal, :bdvaloraquisicao, :wdepreciacaoanterior;

             bdvalorbaixaperiodo = wvalorbaixa;
             --alt:8005 - Retira um mês da contabilização porque quando é pra depreciar no mês da aquisição do bem vem um mês a mais do que deveria. Pedro
             IF ((UPPER(wdepmesaquibem) = 'FALSE') AND (UPPER(wdepmesbaixabem) = 'TRUE')) THEN
               wmesesdepreciados = wmesesdepreciados - 1;

             SELECT COALESCE(SUM(bai.bdvalbai), 0) FROM EMPRESAS_TBAI bai
             WHERE bai.BDCODEMP = :prcodemp AND bai.bdcodbem = :bdcodbem AND bai.BDCONTABILIZACAO = :PRCONTABILIZACAO AND bai.BDDATBAI <= :wdatfin AND bai.BDDATBAI >= :wdatini
             INTO :wvalorbaixa;
             wbaixatotaldia = null;
             --alt:14256 - 06/07/2016 - SQL que retorna a data final da depreciação e todas as contas a serem lançadas com os tratamentos feitos para buscar na depreciação, baixa ou preparação. Pedro
             --#alt:96243 - o SQL Pega somente o ultimo, todavia, ele deveria pegar todos do pereiodo
             FOR SELECT bem.BDCODEMP, bem.BDCODBEM, bem.BDNOMBEM, bem.BDCODTPLA AS BDCODTPLABEM, bem.BDCODPLAPADRAO, COALESCE(bai.BDCODHIST, ibe.BDCODHIST),
              CASE WHEN dep.BDDATFIMCALCBEM IS NOT NULL THEN dep.BDDATFIMCALCBEM
                   WHEN dep.BDCODDEP IS NOT NULL THEN DATEADD(MONTH, ((100 / dep.BDTAXADEP) * 12), bem.BDDATORIAQUIBEM)
                   WHEN (bem.BDVIDAUTIL IS NOT NULL) AND (bem.BDVIDAUTIL > 0) THEN DATEADD(MONTH, bem.BDVIDAUTIL, bem.BDDATORIAQUIBEM) END AS BDDATAFINALCALCULO,
              CASE WHEN dep.BDCTADEBITODEPRE IS NULL THEN ibe.BDDEPDEBIBE ELSE dep.BDCTADEBITODEPRE END AS BDCTADEBITODEPRE, ibe.BDDEPCREIBE, ibe.BDDEPHISTIBE,
              COALESCE(bai.BDBAIDEPDEBBAI, ibe.BDBAIDEPDEBIBE), COALESCE(bai.BDBAIDEPCREBAI, ibe.BDBAIDEPCREIBE), COALESCE(bai.BDBAIDEPHISTBAI, ibe.BDBAIDEPHISTIBE),
              COALESCE(bai.BDBAIAQUIDEBBAI, ibe.BDBAIAQUIDEBIBE), COALESCE(bai.BDBAIAQUICREBAI, ibe.BDBAIAQUICREIBE), COALESCE(bai.BDBAIAQUIHISTBAI, ibe.BDBAIAQUIHISTIBE), COALESCE(bai.BDVALBAI, 0), bai.bdcodbai,
              coalesce(ibe.bdresidualdeb,0),coalesce(ibe.bdresidualcre,0),coalesce(ibe.bdresidualhis,0),
              coalesce(ibe.bdcapitaldeb,0),coalesce(ibe.bdcapitalcre,0),coalesce(ibe.bdcapitalhis,0), bai.bdvalvenbai - bai.bdvalbai as bdvalorcapital,
              coalesce(ibe.bdperdacapitaldeb,0),coalesce(ibe.bdperdacapitalcre,0),coalesce(ibe.bdperdacapitalhis,0), BDDEPCCIBE, BDBAIDEPCCIBE, BDBAIAQUICCIBE,
              BDRESIDUALCCIBE, BDCAPITALCCIBE, BDPERDACAPITALCCIBE
             FROM EMPRESAS_TBEM bem
             LEFT JOIN EMPRESAS_TDEPRECIACAO dep ON (dep.BDCODEMP = bem.BDCODEMP AND dep.BDCODBEM = bem.BDCODBEM AND dep.BDCONTABILIZACAO = :prContabilizacao AND
                                                     ((dep.BDDATINICALCBEM IS NULL) OR (dep.BDDATINICALCBEM <= :wdatfin)) AND
                                                     ((dep.BDDATFIMCALCBEM IS NULL) OR (dep.BDDATFIMCALCBEM >= :wdatfin)))
             LEFT JOIN EMPRESAS_TBAI bai ON (bai.BDCODEMP = bem.BDCODEMP AND bai.BDCODBEM = bem.BDCODBEM AND bai.BDCONTABILIZACAO = :prContabilizacao AND bai.BDDATBAI <= :wdatfin AND bai.BDDATBAI >= :wdatini)
             LEFT JOIN EMPRESAS_TIBE ibe ON (ibe.BDCODEMP = bem.BDCODEMP AND ibe.BDCODPLAPADRAO = bem.BDCODPLAPADRAO AND ibe.BDCODTPLA = bem.BDCODTPLA AND ibe.BDCONTABILIZACAO = :prContabilizacao)
             WHERE bem.BDCODEMP = :prcodemp
               AND bem.BDCODBEM = :bdcodbem
             ORDER BY dep.BDDATFIMCALCBEM DESC, bai.BDDATBAI DESC
             INTO :prcodemp, :bdcodbem, :bdnombem, :bdcodtplabem,
                  :bdcodplapadrao, :bdcodhist, :wdatafimdep,
                  :bdctadebitodepre, :bdctacreditodepre, :bdhistoricodepre,
                  :bdctadebitobaixa, :bdctacreditobaixa, :bdhistoricobaixa,
                  :bdctadebitodepbai, :bdctacreditodepbai, :bdhistoricodepbai, :wbaixaparcialdia, :wbaixaexp,
                  :bdresidualdeb,:bdresidualcre, :bdresidualhis,
                  :bdcapitaldeb, :bdcapitalcre,  :bdcapitalhis, :bdvalorcapital,
                  :bdperdacapitaldeb, :bdperdacapitalcre,  :bdperdacapitalhis,
                  :bddepccibe, :bdbaidepccibe, :bdbaiaquiccibe,
                  :bdresidualccibe, :bdcapitalccibe, :bdperdacapitalccibe DO
             BEGIN
               bdcodbaixa         = wbaixaexp;
               bddepreciacaoacumulada = 0;
               if (wbaixatotaldia is not null) then
                 bddepreciacaoperiodo = 0;
               wbaixatotaldia = wvalorbaixa;
             ----Leonardo Pereira - se houver contas de valor residual e histórico, e tiver baixa no mês
             IF  (((bdresidualdeb > 0) and (bdresidualcre > 0) and (bdresidualhis > 0)) and (wvalorbaixa > 0)) THEN
                 begin
                   if (wvalorbaixa >= wVALORAQUISICAOORIGINAL) then
                      bddepreciacaoperiodo =  bddepreciacaoperiodo - coalesce(BDVALORRESIDUALBAIXA,0);
                 end
             else
                begin
                  BDVALORRESIDUALBAIXA = 0;
                end

             IF (bdvalorbaixaperiodo > 0) THEN
               BEGIN
                 --alt:8005 - Adiciona um mês porque quando é pra depreciar no mês da baixa do bem vem com um mês a menos do que deveria. Pedro
                 IF ((UPPER(wdepmesbaixabem) = 'TRUE') AND (UPPER(wdepmesaquibem) = 'FALSE')) THEN
                    wmesesdepreciados = wmesesdepreciados + 1;

                 IF ((wdatafimdep IS NOT NULL) AND (wdatafimdep < wdatfin) AND (COALESCE(wdepmesbaixabem, 'FALSE') <> 'TRUE') AND (wvalorbaixa >= wVALORAQUISICAOORIGINAL)) THEN
                   BEGIN
                     SELECT PRDEPRECIACAOACUMULADAATUAL "prdepreciacaoacumuladaatual"
                     FROM sp_cons_calc_dep(:prcodemp, :bdcodbem , addmonth(:wdatini,-1) , addmonth(:wdatfin,-1) ,0,:prcontabilizacao)
                     INTO :wcompensacaobaixaperanterior;
                       bddepreciacaoacumulada = wcompensacaobaixaperanterior;
                       --wSoma = cast((cast(wvalorbaixa as double precision) / cast(WVALORAQUISICAOORIGINAL as double precision)) * cast(bddepreciacaoperiodo+wdepreciacaoanterior as double precision) as numeric(15,2));
                       --bdvalorcapital = wSoma + bdvalorcapital;
                   END
                 ELSE --alt:14624 - 27/05/2016 - Utiliza o valor retornado pela procedure para a depreciação acumulada, quando o bem ainda não foi totalmente depreciado. Pedro
                     bddepreciacaoacumulada = wcompensacaobaixaperanterior;
                 --alt:8005 - Fim

                 IF  (wdatabaixa BETWEEN :wdatini AND :wdatfin)  THEN
                   begin
                     bdvalorbaixaperiodo = bdvalorbaixaperiodo;
                     --#alt:91871. Ana - 30/10/2018
                     bddatabaixa = wdatabaixa;
                   end
                 ELSE
                    bdvalorbaixaperiodo = 0;
               END

                if (wbaixaparcialdia <> wbaixatotaldia) then
                  BEGIN
                    wbaixatotaldia = wbaixaparcialdia / wbaixatotaldia;
                    bdvalorbaixaperiodo = wbaixaparcialdia;
                    bddepreciacaoacumulada = bddepreciacaoacumulada * wbaixatotaldia;
                    bdvalorbaixaperiodo = wbaixaparcialdia;
                  END
             IF ((bddepreciacaoperiodo > 0) OR (bdvalorbaixaperiodo > 0)) THEN
                begin
                    wSoma = cast((cast(wvalorbaixa as double precision) / cast(WVALORAQUISICAOORIGINAL as double precision)) * cast(bddepreciacaoperiodo+wdepreciacaoanterior as double precision) as numeric(15,2));
                    bdvalorcapital = wSoma + bdvalorcapital;
                SUSPEND;
                end
             bdvalorresidualbaixa = 0;
             END
           end
         wdatini = addmonth(wdatini, 1);
         wdatfin = addmonth(wdatini, 1)-1;
       END
   END
END^

create or alter procedure SP_VATI_GERAR_INCON_TDEPAUTO (
    PRREFERENCIA integer,
    PRDATAINI date,
    PRDATAFIN date,
    PRDIAPROC integer = null)
as
declare variable WEMPRESA integer;
declare variable WCODPLAPADRAO integer;
declare variable WNOME varchar(100);
declare variable WAUX integer;
declare variable WSQL varchar(5000);
declare variable WREFERENCIA integer;
begin
  delete from TMP_VATI_INCON_TDEPAUTO;
  wsql = 'select distinct EMP.BDCODEMP, REF.BDNOMEMP, REF.BDCODPLAPADRAO, DEP.BDREFERENCIA ';
  wsql = wsql||'from VATI_DEPRECIACAO_AUTO AUT ';
  wsql = wsql||'inner join VATI_DEPRECIACAO_AUTO_EMPRESAS EMP on (EMP.BDCONFIG = AUT.BDCHAVE) ';
  wsql = wsql||'inner join VW_EMPRESAS_REF_ATUAL REF on (REF.BDCODEMP = EMP.BDCODEMP) ';
  wsql = wsql||'left outer join(select DEP.BDREFERENCIA, DEP.BDCODEMP ';
  wsql = wsql||'from VATI_EMPRESAS_IMP_ATIVACONTAB DEP ';
  wsql = wsql||'where DEP.BDREFERENCIA = '||:PRREFERENCIA||') DEP on (EMP.BDCODEMP = DEP.BDCODEMP) ';
  wsql = wsql||'where /*DEP.BDREFERENCIA is null and */ ';
  wsql = wsql||'AUT.BDREFERENCIA <= '||:PRREFERENCIA;
  if (prdiaproc is not null) then
      wsql = wsql||' and coalesce(AUT.BDDIAPROC,0) <= '||:prdiaproc;
  for execute statement wsql into :WEMPRESA, :WNOME, :WCODPLAPADRAO, :WREFERENCIA
  do
  begin
    ---Leonardo Pereira - 01/03/2020 - Retirado do where a referencia para poder atualizar a ultima depreciação
    if (WREFERENCIA is not null) then
       begin
         UPDATE VATI_DEPRECIACAO_AUTO_EMPRESAS SET BDULTDEPREC = :prreferencia where BDCODEMP = :WEMPRESA and coalesce(BDULTDEPREC,0) < :prreferencia;
       end
    else
      begin
        WAUX = null;
        select first 1 BEM.BDCODBEM
        from EMPRESAS_TBEM BEM
        where BEM.BDCODEMP = :WEMPRESA
        into :WAUX;
        if (WAUX is null) then
           begin
              insert into TMP_VATI_INCON_TDEPAUTO (BDCODEMP, BDNOMEMP, BDINCONSISTENCIA)
              values (:WEMPRESA, :WNOME, 'Bens não cadastrados para a empresa');
                UPDATE VATI_DEPRECIACAO_AUTO_EMPRESAS SET BDULTDEPREC = :prreferencia where BDCODEMP = :WEMPRESA and coalesce(BDULTDEPREC,0) < :prreferencia;
            continue;
           end

            WAUX = null;
            select first 1 BEM.BDCODBEM
            from EMPRESAS_TDEPRECIACAO BEM
            where BEM.BDCODEMP = :WEMPRESA
        into :WAUX;
        if (WAUX is null) then
          begin
            insert into TMP_VATI_INCON_TDEPAUTO (BDCODEMP, BDNOMEMP, BDINCONSISTENCIA)
            values (:WEMPRESA, :WNOME, 'Bens sem taxa de depreciação cadastrada para a empresa');
            UPDATE VATI_DEPRECIACAO_AUTO_EMPRESAS SET BDULTDEPREC = :prreferencia where BDCODEMP = :WEMPRESA and coalesce(BDULTDEPREC,0) < :prreferencia;
            continue;
           end
          
        WAUX = null;
        SELECT FIRST 1 coalesce(blq.bdcodemp, V.bdcodemp) FROM TBLOQLAN_EMPRESA BLQ
        LEFT JOIN VSUC_EMPRESAS_TENCEXE V ON
          BLQ.BDCODEMP = V.bdcodemp
        WHERE BLQ.BDCODEMP = :WEMPRESA
          AND ((BLQ.bddatainicial <= :PRDATAFIN AND BLQ.bddatafinal >= :prDataIni)
          or (v.bddatainizer <= :PRDATAFIN AND V.bddatafimzer >= :PRDATAINI))
                INTO :WAUX;
        if (WAUX is not null) then
          begin
            insert into TMP_VATI_INCON_TDEPAUTO (BDCODEMP, BDNOMEMP, BDINCONSISTENCIA)
            values (:WEMPRESA, :WNOME, 'Existe encerramento do exercício ou bloqueio de lançamentos para o período '|| substring(:prreferencia FROM 5 FOR 2)||'/'||substring(:prreferencia FROM 1 FOR 4)
             ||', o processo de depreciação automática não foi realizado.');
            continue;
          end

                    WAUX = null;
                    select first 1 BDCODTPLABEM from SP_EXP_ATIVA_CONTABIL(:WEMPRESA, :PRDATAINI, :PRDATAFIN, '0', '9999', :WCODPLAPADRAO, 0, 0, 0, 'DESC') INTO :WAUX;
        if (WAUX is not null) then
          begin
            insert into TMP_VATI_INCON_TDEPAUTO (BDCODEMP, BDNOMEMP, BDINCONSISTENCIA)
            values (:WEMPRESA, :WNOME, 'Depreciação não realizada. Houve algum problema com o servidor SCI');
            continue;
          end

        --Leonardo Pereira - 10/03/2020 - Quando tiver problema no servidor deve dar aviso, então não atulizar a referencia.
        UPDATE VATI_DEPRECIACAO_AUTO_EMPRESAS SET BDULTDEPREC = :prreferencia where BDCODEMP = :WEMPRESA and coalesce(BDULTDEPREC,0) < :prreferencia;
      end
   end
end^

/* Restore proc. body: SP_EXP_SEFIP */
ALTER PROCEDURE SP_EXP_SEFIP(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(10000),
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRDATARECFGTS DATE,
PRDATARECINSS DATE,
PRTIPOFOLHA INTEGER,
PRMODALIDADE VARCHAR(1),
PRINDRECFGST VARCHAR(1),
PRINDRECINSS VARCHAR(1))
 RETURNS(BDARQ INTEGER,
BDREG VARCHAR(360),
BDORDEM VARCHAR(70),
BDINC VARCHAR(32000),
BDCONTADOR INTEGER,
BDCODREC INTEGER,
BDMODALIDADE VARCHAR(1))
 AS
DECLARE VARIABLE windrecinss VARCHAR(1);
DECLARE VARIABLE windrecfgts VARCHAR(1);
DECLARE VARIABLE wmodalidade VARCHAR(1);
DECLARE VARIABLE wsqlcalc VARCHAR(32000);
DECLARE VARIABLE wparsqlcalc VARCHAR(32000);
DECLARE VARIABLE wsqlemp VARCHAR(32000);
DECLARE VARIABLE wempatu INTEGER;
DECLARE VARIABLE wcodrecatu INTEGER;
DECLARE VARIABLE wcodrecsqlatu INTEGER;
DECLARE VARIABLE wwhereemp VARCHAR(32000);
BEGIN
  /* Procedure Text */
  /* prtipoFolha
     0 = normal
     1 = folha complementar
     2 = 13 sal
  */
  wmodalidade = prmodalidade;

  windrecfgts = prindrecfgst;
  windrecinss = prindrecinss;

  IF (windrecfgts IS NULL) THEN
     windrecfgts = '1';

  IF (windrecinss IS NULL) THEN
     windrecinss  = '1';

  IF (prtipofolha IS NULL) THEN
     prtipofolha = 0;

  rdb$set_context('USER_TRANSACTION', 'W_TIPOFOLHA', :prtipofolha);

  rdb$set_context('USER_TRANSACTION', 'W_MODALIDADE', :wmodalidade);

  rdb$set_context('USER_TRANSACTION', 'W_INDRECFGTS', :windrecfgts);
  rdb$set_context('USER_TRANSACTION', 'W_INDRECINSS', :windrecinss);

  IF (prdatarecfgts IS NOT NULL) THEN
     rdb$set_context('USER_TRANSACTION', 'W_DATARECFGTS', :prdatarecfgts );

  IF (prdatarecinss IS NOT NULL) THEN
     rdb$set_context('USER_TRANSACTION', 'W_DATARECINSS', :prdatarecinss);

  EXECUTE PROCEDURE sp_seta_competencia(pranomes,NULL,NULL);

  IF (pranomespag IS NULL) THEN
     pranomespag = pranomes;

  rdb$set_context('USER_TRANSACTION', 'W_ANOMESPAG', :pranomespag);

  WPARSQLCALC = '';

  wsqlemp = 'select colcon.bdcodemp,case when colcon.bdcodsefipemp is null then 115 else colcon.bdcodsefipemp end from VW_VRHF_BASE_TEMPSEFIP colcon ';
  IF (prcodemp IS NOT NULL) THEN
     wsqlemp = wsqlemp||' where '||prcodemp;

  wsqlemp = wsqlemp||' order by colcon.bdcodsefipemp, colcon.bdcodemp';

  IF (pranomespag IS NULL) THEN
     pranomespag = pranomes;

  IF (prtipofolha IS NULL) THEN
     prtipofolha = 0;

  wcodrecsqlatu = -1;
  wwhereemp = '';
  FOR EXECUTE STATEMENT wsqlemp
  INTO
    : wempatu,
    : wcodrecatu
  DO
    BEGIN
      IF ((wcodrecatu IS NULL) OR (wcodrecatu = 0) ) THEN
         wcodrecatu = 115;

      IF ((wcodrecatu = wcodrecsqlatu) OR (wcodrecsqlatu = -1)) THEN
         BEGIN
           wcodrecsqlatu = wcodrecatu;
           IF (CHAR_LENGTH(wwhereemp)>0) THEN
              wwhereemp = wwhereemp||',';
           wwhereemp = wwhereemp||CAST(wempatu AS VARCHAR(10));
         END
      ELSE
         BEGIN
           WPARSQLCALC = ''''||'colcon.bdcodemp in ('||wwhereemp||')'||'''';
           wsqlcalc = 'select bdarq,bdreg,bdinc,bdordem,bdcontador,bdcodrec,bdmodalidade from sp_exp_sefip_codrec(';
           wparsqlcalc = wparsqlcalc||',';
           IF (prcodcol IS NULL) THEN
              wparsqlcalc = wparsqlcalc||'null';
           ELSE
              wparsqlcalc = wparsqlcalc||''''||prcodcol||'''';
           wparsqlcalc = wparsqlcalc||','||CAST(wcodrecsqlatu AS VARCHAR(10));

           wsqlcalc = wsqlcalc||wparsqlcalc||')';

           FOR EXECUTE STATEMENT wsqlcalc
           INTO
             : bdarq,
             : bdreg,
             : bdinc,
             : bdordem,
             : bdcontador,
             : bdcodrec,
             : bdmodalidade
           DO
             SUSPEND;

           /*proximo sql*/
           wcodrecsqlatu = wcodrecatu;
           wwhereemp = CAST(wempatu AS VARCHAR(10));
         END
    END

   WPARSQLCALC = ''''||'colcon.bdcodemp in ('||wwhereemp||')'||'''';

   wsqlcalc = 'select bdarq,bdreg,bdinc,bdordem,bdcontador,bdcodrec,bdmodalidade from sp_exp_sefip_codrec(';
   wparsqlcalc = wparsqlcalc||',';
   IF (prcodcol IS NULL) THEN
       wparsqlcalc = wparsqlcalc||'null';
   ELSE
       wparsqlcalc = wparsqlcalc||''''||prcodcol||'''';
   wparsqlcalc = wparsqlcalc||','||CAST(wcodrecsqlatu AS VARCHAR(10));

   wsqlcalc = wsqlcalc||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsqlcalc
   INTO
     : bdarq,
     : bdreg,
     : bdinc,
     : bdordem,
     : bdcontador,
     : bdcodrec,
     : bdmodalidade
   DO
     SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL,NULL,NULL);

  DELETE FROM VRHF_EXP_SEFIP;
END
^

/* Restore proc. body: SP_EXP_SEFIP_ARQ */
ALTER PROCEDURE SP_EXP_SEFIP_ARQ(PRCODREC INTEGER,
PRMODALIDADE VARCHAR(1))
 RETURNS(BDARQ INTEGER,
BDREG00 INTEGER,
BDREG10 INTEGER,
BDREG20 INTEGER)
 AS
DECLARE VARIABLE wcontador INTEGER;
DECLARE VARIABLE wcodtpcc INTEGER;
DECLARE VARIABLE wcodemp INTEGER;
DECLARE VARIABLE wsqlaux VARCHAR(1000);
DECLARE VARIABLE wultarq INTEGER;
DECLARE VARIABLE wencontro00 INTEGER;
DECLARE VARIABLE wencontro10 INTEGER;
DECLARE VARIABLE wencontro20 INTEGER;
BEGIN
  /* wencontroXX
    0 = nao
    1 = sim
  */
  wultarq = 0;
  wencontro00 = 0;
  wencontro10 = 0;
  wencontro20 = 0;
  /* Procedure Text */
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wcodemp;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_TOMADORSEFIP') FROM rdb$database INTO wcodtpcc;

  IF (prcodrec IS NULL) THEN
     prcodrec = 0;

  IF (prmodalidade IS NULL) THEN
     prmodalidade = ' ';

  IF (wcodemp IS NULL) THEN
     wcodemp = 0;

  IF (wcodtpcc IS NULL) THEN
     wcodtpcc = 0;

  wsqlaux = 'select emp.bdcodcont from vw_empresas_ref_atual emp where emp.bdcodemp ='||wcodemp;
  EXECUTE STATEMENT wsqlaux INTO wcontador;

  IF (wcontador IS NULL) THEN
     wcontador = 0;

  wultarq = NULL;
  wsqlaux = 'select bdarq from VRHF_EXP_SEFIP'||
            ' where BDCONTADOR = '||wcontador||
            ' and BDCODREC = '||prcodrec||
            ' and BDMODALIDADE = '||''''||prmodalidade||''''||
            ' and BDEMP = '||wcodemp||
            ' and BDCCC = '||wcodtpcc;
  EXECUTE STATEMENT wsqlaux INTO wultarq;
  IF ((wultarq IS NOT NULL) AND (wultarq > 0)) THEN
    BEGIN
      wencontro00 = 1;
      wencontro10 = 1;
      wencontro20 = 1;
    END

  IF ((wultarq IS NULL) OR (wultarq = 0)) THEN
     BEGIN
       wsqlaux = 'select bdarq from VRHF_EXP_SEFIP'||
                 ' where BDCONTADOR = '||wcontador||
                 ' and BDCODREC = '||prcodrec||
                 ' and BDMODALIDADE = '||''''||prmodalidade||''''||
                 ' and BDEMP = '||wcodemp;
    
       FOR EXECUTE STATEMENT wsqlaux INTO wultarq DO
         BEGIN
           IF ((wultarq IS NOT NULL) AND (wultarq > 0)) THEN
             BEGIN
               wencontro00 = 1;
               wencontro10 = 1;
             END
           BREAK;
         END
     END

  IF ((wultarq IS NULL) OR (wultarq = 0)) THEN
     BEGIN
       wsqlaux = 'select bdarq from VRHF_EXP_SEFIP'||
                 ' where BDCONTADOR = '||wcontador||
                 ' and BDCODREC = '||prcodrec||
                 ' and BDMODALIDADE = '||''''||prmodalidade||'''';

       FOR EXECUTE STATEMENT wsqlaux INTO wultarq DO
         BEGIN
           IF ((wultarq IS NOT NULL) AND (wultarq > 0)) THEN
             BEGIN
               wencontro00 = 1;
             END
           BREAK;
         END
     END

  IF (wultarq IS NULL) THEN
     BEGIN
       wsqlaux = 'select max(bdarq) from VRHF_EXP_SEFIP';
       EXECUTE STATEMENT wsqlaux INTO wultarq;
       IF (wultarq IS NULL) THEN
          wultarq = 1;
       ELSE
          wultarq = wultarq + 1;
     END

  IF ((wencontro00 = 0) OR (wencontro10 = 0) OR (wencontro20 = 0)) THEN
     BEGIN
       wsqlaux = 'insert into vrhf_exp_sefip values('||
                 wultarq||','|| -- arquivo
                 wcontador||','|| -- contador
                 prcodrec||','|| -- codrec
                 ''''||prmodalidade||''''||','|| -- modadlidade
                 wcodemp||','|| -- emp
                 wcodtpcc||')'; -- cc
       EXECUTE STATEMENT wsqlaux;
     END

  bdarq = wultarq;
  bdreg00 = wencontro00;
  bdreg10 = wencontro10;
  bdreg20 = wencontro20;
  SUSPEND;
END
^

/* Restore proc. body: SP_EXP_SEFIP_CODREC */
ALTER PROCEDURE SP_EXP_SEFIP_CODREC(PRWHEREEMP VARCHAR(32000),
PRCODCOL VARCHAR(32000),
PRCODREC INTEGER)
 RETURNS(BDARQ INTEGER,
BDMODALIDADE VARCHAR(1),
BDCONTADOR INTEGER,
BDCODREC INTEGER,
BDREG VARCHAR(360),
BDORDEM VARCHAR(70),
BDINC VARCHAR(32000),
BDQTDCHAR INTEGER)
 AS
DECLARE VARIABLE wmodaux VARCHAR(1);
DECLARE VARIABLE wanomespag INTEGER;
DECLARE VARIABLE wsalvaparsqlcalc VARCHAR(32000);
DECLARE VARIABLE wmatempc13 NUMERIC(15,6);
DECLARE VARIABLE wmatemp13 NUMERIC(15,6);
DECLARE VARIABLE wmatemp NUMERIC(15,6);
DECLARE VARIABLE wsalfam NUMERIC(15,6);
DECLARE VARIABLE wtipofolha INTEGER;
DECLARE VARIABLE wbaseinss13fol NUMERIC(15,6);
DECLARE VARIABLE wanomesaux INTEGER;
DECLARE VARIABLE wrecfgtsres INTEGER;
DECLARE VARIABLE wfgtsmesant VARCHAR(5);
DECLARE VARIABLE wcontador INTEGER;
DECLARE VARIABLE wcodempant INTEGER;
DECLARE VARIABLE wcodcolant INTEGER;
DECLARE VARIABLE wbaseinss13 NUMERIC(15,6);
DECLARE VARIABLE wbaseinssfol NUMERIC(15,6);
DECLARE VARIABLE wvalorinss13 NUMERIC(15,6);
DECLARE VARIABLE wvalorinssfol NUMERIC(15,6);
DECLARE VARIABLE wbasefgts13 NUMERIC(15,6);
DECLARE VARIABLE wbasefgtsfol NUMERIC(15,6);
DECLARE VARIABLE wdatamov VARCHAR(10);
DECLARE VARIABLE wmotivo VARCHAR(5);
DECLARE VARIABLE windfgts VARCHAR(1);
DECLARE VARIABLE wsqlmovicol VARCHAR(32000);
DECLARE VARIABLE wmodalidade VARCHAR(1);
DECLARE VARIABLE wsql VARCHAR(32000);
DECLARE VARIABLE wcodrec INTEGER;
DECLARE VARIABLE wanomes INTEGER;
DECLARE VARIABLE wsqlcalc VARCHAR(32000);
DECLARE VARIABLE wparsqlcalc VARCHAR(32000);
DECLARE VARIABLE wcodemp INTEGER;
DECLARE VARIABLE wcodcol INTEGER;
DECLARE VARIABLE wcodtpcc INTEGER;
DECLARE VARIABLE wcodcentro INTEGER;
DECLARE VARIABLE warq INTEGER;
DECLARE VARIABLE wreg00 INTEGER;
DECLARE VARIABLE wreg10 INTEGER;
DECLARE VARIABLE wreg20 INTEGER;
DECLARE VARIABLE wcompensacao NUMERIC(15,6);
DECLARE VARIABLE winiciocompensacao INTEGER;
DECLARE VARIABLE wfimcompensacao INTEGER;
DECLARE VARIABLE wacumulado NUMERIC(15,6);
DECLARE VARIABLE wacumuladoterc NUMERIC(15,6);
DECLARE VARIABLE wnotasfiscais NUMERIC(15,6);
DECLARE VARIABLE wnotascoop NUMERIC(15,6);
DECLARE VARIABLE wruralfisica NUMERIC(15,6);
DECLARE VARIABLE wruraljuridica NUMERIC(15,6);
DECLARE VARIABLE wautonomo INTEGER;
BEGIN
/*  delete from VRHF_EXP_SEFIP;

  rdb$set_context('USER_TRANSACTION', 'W_MODALIDADE', '1');-- from rdb$database into WMODALIDADE;
  rdb$set_context('USER_TRANSACTION', 'W_INDRECFGTS', '1');-- from rdb$database into windrecfgts;
  rdb$set_context('USER_TRANSACTION', 'W_INDRECINSS', '1');-- from rdb$database into windrecinss;

  execute procedure sp_seta_competencia(201005,null,null);
  */

  SELECT rdb$get_context('USER_SESSION', 'W_ANOMES') FROM rdb$database INTO wanomes;

  SELECT rdb$get_context('USER_TRANSACTION', 'W_TIPOFOLHA') FROM rdb$database INTO wtipofolha;

  IF (prcodrec IS NULL) THEN
     prcodrec = 115;

  wCodRec = prcodrec;

  IF (wtipofolha IS NULL) THEN
     wtipofolha = 0;

--  wanomes = 201005;
--  prwhereemp = 'colcon.bdcodemp in (3)';
--  execute procedure sp_seta_competencia(wanomes,null,null);
  rdb$set_context('USER_TRANSACTION', 'W_CODREC', :wCodRec);

  SELECT rdb$get_context('USER_TRANSACTION', 'W_ANOMESPAG') FROM rdb$database INTO wanomespag;

  IF (wanomespag IS NULL) THEN
     wanomespag = wanomes;

  wparsqlcalc = ''''||prwhereemp||'''';

  wparsqlcalc = wparsqlcalc||',';

  -- colaborador
  IF (prcodcol IS NULL) THEN
     wparsqlcalc = wparsqlcalc||'null';
  ELSE
     wparsqlcalc = wparsqlcalc||''''||prcodcol||'''';

  wparsqlcalc = wparsqlcalc||',';

  -- anomes
  wparsqlcalc = wparsqlcalc||CAST(wanomes AS VARCHAR(6))||',';

  -- anomesFim
    wparsqlcalc = wparsqlcalc||CAST(wanomes AS VARCHAR(6))||',';

  -- anomes pag
  IF (wanomespag IS NULL) THEN
     wparsqlcalc = wparsqlcalc||'null,';
  ELSE
     wparsqlcalc = wparsqlcalc||CAST(wanomespag AS VARCHAR(6))||',';

  IF (prcodrec = 115) THEN
     BEGIN
       wparsqlcalc = wparsqlcalc||'1';
     END
  ELSE
     BEGIN
       wparsqlcalc = wparsqlcalc||'3';
     END

  IF (wtipofolha = 1) THEN
     wsqlcalc = 'select * from sp_calc_exp_sefip_complementar('||wparsqlcalc||') colcon';
  ELSE
     wsqlcalc = 'select * from sp_calc_exp_sefip('||wparsqlcalc||') colcon';

  wsqlcalc = wsqlcalc||' order by colcon.bdcodemp, colcon.bdcodcol, colcon.bdcodtpcc';

  wcodcolant = NULL;
  wcodempant = NULL;

  FOR EXECUTE STATEMENT wsqlcalc
  INTO
    : wmodaux,
    : wautonomo,
    : wcodemp,
    : wcodcol,
    : wcodtpcc,
    : wcodcentro,
    : wanomesaux,
    : wrecfgtsres,
    : wfgtsmesant,
    : wbasefgtsfol,
    : wbasefgts13,
    : wvalorinssfol,
    : wvalorinss13,
    : wbaseinssfol,
    : wbaseinss13,
    : wbaseinss13fol
  DO
    BEGIN
      SELECT rdb$get_context('USER_TRANSACTION', 'W_MODALIDADE') FROM rdb$database INTO wmodalidade;

      IF ((wmodalidade = '') OR (wmodalidade IS NULL)) THEN
         wmodalidade = ' ';

      IF (wmodaux = '9') THEN
         wmodalidade = '9';

      IF (wbaseinss13fol < 0) THEN
         wbaseinss13fol = 0;

      IF (wbasefgtsfol < 0) THEN
         wbasefgtsfol = 0;

      IF (wbasefgts13 < 0) THEN
         wbasefgts13 = 0;

      IF (wvalorinssfol < 0) THEN
         wvalorinssfol = 0;

      IF (wvalorinss13 < 0) THEN
         wvalorinss13 = 0;

      IF (wbaseinssfol < 0) THEN
         wbaseinssfol = 0;

      IF (wbaseinss13 < 0) THEN
         wbaseinss13 = 0;

      IF ((wcodcolant IS NULL) OR (wcodcolant <> wcodcol) OR (wcodempant <> wcodemp)) THEN
         BEGIN
           wcodcolant = wcodcol;
         END
      ELSE
         BEGIN
           wbasefgts13 = 0;
           wbaseinss13 = 0;
         END

      IF ((wcodempant IS NULL) OR (wcodempant <> wcodemp)) THEN
         BEGIN
           wcodempant = wcodemp;
           wsql = 'select emp.bdcodcont from vw_empresas_ref_atual emp where emp.bdcodemp ='||wcodemp;
           EXECUTE STATEMENT wsql INTO wcontador;
    
           IF (wcontador IS NULL) THEN
              wcontador = 0;

           bdcontador = wcontador;
         END

      rdb$set_context('USER_TRANSACTION', 'W_EMPSEFIP', :wcodemp);
      rdb$set_context('USER_TRANSACTION', 'W_TOMADORSEFIP', :wcodtpcc);
      rdb$set_context('USER_TRANSACTION', 'W_COLSEFIP', :wcodcol);

      /* verifica a modalidade do funcionario
         ' ' = com recolhimento fgts
         '1' = demontra ou individualiza bases de fgts
         '9' = confirmacao de valores (apenas para folha complementar funcionario que nao tiverem folha complementar)
      */

      /*verificar em que arquivo deve ir o colaborador*/
      /* se nao tiver base de fgts deve ir para a modalidade 1*/

      IF (wmodalidade = ' ') THEN
         BEGIN
           IF (wbasefgtsfol + wbasefgts13 <= 0) THEN
              wmodalidade = '1';
           ELSE IF ((wrecfgtsres IS NOT NULL) AND (wrecfgtsres = 2))  THEN
              BEGIN
                IF ((wanomesaux IS NOT NULL) AND (wanomesaux = wanomes)) THEN
                   wmodalidade = '1';
                ELSE IF ((wfgtsmesant = 'TRUE') AND (SUBSTRING(CAST(wanomesaux AS VARCHAR(6)) FROM 5 FOR 2) <> '13')) THEN
                   BEGIN
                     IF (SUBSTRING(CAST(wanomesaux AS VARCHAR(6)) FROM 5 FOR 2) = '12') THEN
                        BEGIN
                          wanomesaux = CAST(CAST(CAST(SUBSTRING(CAST(wanomesaux AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER) + 1 AS VARCHAR(4))||'01' AS INTEGER);
                        END
                     ELSE
                        BEGIN
                          wanomesaux = wanomesaux + 1;
                        END
        
                     IF ((wanomesaux IS NOT NULL) AND (wanomesaux = wanomes)) THEN
                        wmodalidade = '1';
                   END
              END
         END


      wsql = 'select bdarq,bdreg00,bdreg10,bdreg20 from SP_EXP_SEFIP_ARQ('||prcodrec||','||''''||wmodalidade||''''||')';
      EXECUTE STATEMENT wsql INTO :warq, :wreg00, :wreg10, :wreg20;

      bdarq = warq;
      bdcodrec = prcodrec;
      bdmodalidade = wmodalidade;

      rdb$set_context('USER_TRANSACTION', 'W_MODALIDADEATU', wmodalidade);
      /*exporta o registro 00 se precisar*/
       IF ((wreg00 = 0) OR (wreg00 IS NULL) ) THEN
          BEGIN
            wsql = 'select r00.bdreg,r00.bdinc,r00.bdordem from sp_exp_sefip_reg_00 r00'; /*ok*/
            EXECUTE STATEMENT wsql INTO :bdreg, :bdinc, :bdordem;
            bdqtdchar = CHAR_LENGTH(bdreg);
            SUSPEND;
          END

       /*exporta o registro 10 se precisar*/
       IF ((wreg10 = 0) OR (wreg10 IS NULL) ) THEN
         BEGIN
           wsalvaparsqlcalc = wparsqlcalc;
           wparsqlcalc = ''''||' colcon.bdcodemp = '||wcodemp||'''';
           wparsqlcalc = wparsqlcalc||',';
           IF (prcodcol IS NULL) THEN
              wparsqlcalc = wparsqlcalc||'null';
           ELSE
              wparsqlcalc = wparsqlcalc||''''||prcodcol||'''';
           wparsqlcalc = wparsqlcalc||',';
           wparsqlcalc = wparsqlcalc||CAST(wanomes AS VARCHAR(6))||',';
           wparsqlcalc = wparsqlcalc||'null,';
           wparsqlcalc = wparsqlcalc||'1';

           wsql = 'select '||--colcon.bdcodemp, '||
                  'sum(coalesce(tfol.bdsalfamfn,0)),'||
                  'sum(coalesce(tfol.bdbsalmatempfn,0)),'||
                  'sum(coalesce(t13.BDSALMATEMP13,0)),'||
                  'sum(coalesce(c13.BDBSALMATEMPC13,0))'||
                  ' from vrh_emp_tcolcon colcon'||
                  ' left outer join vrhf_emp_t13sal t13 on (t13.bdcodemp = colcon.bdcodemp and t13.bdcodcol = colcon.bdcodcol and t13.bdref13 = '||wanomes||')'||
                  ' left outer join vrhf_emp_tc13sal c13 on (c13.bdcodemp = colcon.bdcodemp and c13.bdcodcol = colcon.bdcodcol and c13.bdrefc13 = '||wanomes||')'||
                  ' left outer join vrhf_sp_tfolha_normal('||wparsqlcalc||') tfol'||
                  ' on (colcon.bdcodemp = tfol.bdcodemp and colcon.bdcodcol = tfol.bdcodcol)'||
                  ' where ';

           wsql = wsql||' colcon.bdcodemp = '||wcodemp;
           wsql = wsql||' and ';

           IF (wcodtpcc IS NULL) THEN
              wsql = wsql||' tfol.bdcodtpcc is null';
           ELSE
              wsql = wsql||' tfol.bdcodtpcc = '||wcodtpcc;

           wsql = wsql||' and ';

           wsql = wsql||'(tfol.bdcodemp is not null or t13.bdcodemp is not null or c13.bdcodemp is not null)';
           wsql = wsql||' group by colcon.bdcodemp';
           wparsqlcalc = wsalvaparsqlcalc;
           EXECUTE STATEMENT wsql INTO /*: wempaux,*/ : wsalfam, : wmatemp, : wmatemp13, : wmatempc13;

           IF ((wsalfam IS NULL) OR (wsalfam < 0)) THEN
              wsalfam = 0;
    
           IF  ((wmatemp IS NULL) OR (wmatemp < 0)) THEN
              wmatemp = 0;
    
           IF (wmatemp13 < 0) THEN
              wmatemp13 = 0;
    
           IF (wmatempc13 < 0) THEN
              wmatempc13 = 0;

           wsql = 'select r10.bdreg,r10.bdinc,r10.bdordem from sp_exp_sefip_reg_10('||
                   wsalfam||','||
                   wmatemp||
                   ') r10';
           EXECUTE STATEMENT wsql INTO :bdreg, :bdinc, :bdordem;
           bdqtdchar = CHAR_LENGTH(bdreg);
           SUSPEND;

           /*exporta o registro 12 se precisar*/
           IF (prCodrec NOT IN (130, 135, 150, 155, 211, 317, 337, 608)) THEN
              BEGIN
                /* Notas cooperativas */
                wsqlmovicol = 'select BDVALLIQNF from VRHF_SP_TNFCOOP('||''''||'colcon.bdcodemp = '||wcodemp||''''||','||wanomes||',null,1,0)';
                EXECUTE STATEMENT wsqlmovicol INTO wnotascoop;

                wsqlmovicol = 'select bdcompensacao,bdinicomp,bdfimcomp,bdacumulado, bdacumuladoterc from SP_COMP_ACUMULADO_GPS('||wcodemp||',1,null,'||wanomes||','||wanomespag||','||wtipofolha||')';
                EXECUTE STATEMENT wsqlmovicol INTO wcompensacao,winiciocompensacao,wfimcompensacao,wacumulado, wacumuladoterc;

                wsqlmovicol = 'select * from vrhf_sp_gps_FunRural('||wcodemp||','||wanomes||',0,0)';

                EXECUTE STATEMENT wsqlmovicol INTO wruralfisica;

                wsqlmovicol = 'select * from vrhf_sp_gps_FunRural('||wcodemp||','||wanomes||',0,1)';

                EXECUTE STATEMENT wsqlmovicol INTO wruraljuridica;

                IF (wCOMPENSACAO IS NULL) THEN
                   wCOMPENSACAO = 0;

                IF (wINICIOCOMPENSACAO IS NULL) THEN
                   wINICIOCOMPENSACAO = 0;

                IF (wFIMCOMPENSACAO IS NULL) THEN
                   wFIMCOMPENSACAO = 0;

                IF (wACUMULADO IS NULL) THEN
                   wACUMULADO = 0;

                IF (wACUMULADOTERC IS NULL) THEN
                   wACUMULADOTERC = 0;

                IF (wNOTASCOOP IS NULL) THEN
                   wNOTASCOOP = 0;

                IF (wRURALFISICA IS NULL) THEN
                   wRURALFISICA = 0;

                IF (wRURALJURIDICA IS NULL) THEN
                   wRURALJURIDICA = 0;

                /* registro 12 nao tem notas fiscais */
                IF (wCOMPENSACAO + wACUMULADO + wACUMULADOTERC + wNOTASCOOP + wRURALFISICA + wRURALJURIDICA + wmatempc13 + wmatemp13 > 0) THEN
                   BEGIN
                     wsql = 'select r12.bdreg,r12.bdinc,r12.bdordem from sp_exp_sefip_reg_12('||(wmatempc13 + wmatemp13)||
                            ','||wruralfisica|| /*ok*/
                            ','||wruraljuridica|| /*ok*/
                            ','||wcompensacao|| /*ok*/
                            ','||winiciocompensacao|| /*ok*/
                            ','||wfimcompensacao|| /*ok*/
                            ','||wacumulado||  /*ok*/
                            ','||wacumuladoterc|| /*ok*/
                            ','||wnotascoop|| /*ok*/
                            ') r12';
                     EXECUTE STATEMENT wsql INTO :bdreg, :bdinc, :bdordem;
                     bdqtdchar = CHAR_LENGTH(bdreg);
                     SUSPEND;
                   END
              END
         END

      /*exporta o registro 20 se precisar*/
      IF ((prCodrec IN (130, 135, 150, 155, 211, 317, 337, 608)) AND ((wreg20 = 0) OR (wreg20 IS NULL))) THEN
         BEGIN
           wnotasfiscais = 0;
           IF (wtipofolha = 0) THEN
              BEGIN
                /*Notas fiscais*/
                IF (wcodtpcc IS NULL) THEN
                   wsqlmovicol = ' and toma.BDCODCENTRO is null';
                ELSE
                   wsqlmovicol = ' and toma.BDCODCENTRO = '||wcodtpcc;
    
                wsqlmovicol = 'select sum(nf.bdvaldescnf) from vrhf_emp_tnotasfiscais nf'||
                              ' left outer join vrhf_sp_tomador(nf.bdcodtpcc,nf.bdcodcentro) toma on (toma.bdcodcencus = nf.bdcodtpcc and toma.bdcodcentro = nf.bdcodcentro)'||
                              ' where nf.bdcodemp = '||wcodemp||
                              ' and nf.bdrefnf = '||wanomes||
                              wsqlmovicol||
                              ' group by nf.bdcodemp';
                EXECUTE STATEMENT wsqlmovicol INTO wnotasfiscais;
              END

           /*Compensacao e Acumulado*/

           IF (wcodtpcc IS NULL) THEN
              wsqlmovicol = 'select bdcompensacao,bdinicomp,bdfimcomp,bdacumulado, bdacumuladoterc from SP_COMP_ACUMULADO_GPS('||wcodemp||',3,null,'||wanomes||','||wanomespag||','||wtipofolha||')';
           ELSE
              wsqlmovicol = 'select bdcompensacao,bdinicomp,bdfimcomp,bdacumulado, bdacumuladoterc from SP_COMP_ACUMULADO_GPS('||wcodemp||',3,'||wcodtpcc||','||wanomes||','||wanomespag||','||wtipofolha||')';

           EXECUTE STATEMENT wsqlmovicol INTO wcompensacao,winiciocompensacao,wfimcompensacao,wacumulado, wacumuladoterc;

           IF (wCOMPENSACAO IS NULL) THEN
              wCOMPENSACAO = 0;
    
           IF (wINICIOCOMPENSACAO IS NULL) THEN
              wINICIOCOMPENSACAO = 0;
    
           IF (wFIMCOMPENSACAO IS NULL) THEN
              wFIMCOMPENSACAO = 0;
    
           IF (wACUMULADO IS NULL) THEN
              wACUMULADO = 0;
    
           IF (wACUMULADOTERC IS NULL) THEN
              wACUMULADOTERC = 0;

           IF (wNOTASFISCAIS IS NULL) THEN
              wNOTASFISCAIS = 0;

           IF (wsalfam IS NULL) THEN
              wsalfam = 0;

           wsql = 'select r20.bdreg,r20.bdinc,r20.bdordem from sp_exp_sefip_reg_20('||
                  wsalfam||
                  ','||wnotasfiscais||
                  ') r20';
           EXECUTE STATEMENT wsql INTO :bdreg, :bdinc, :bdordem;
           bdqtdchar = CHAR_LENGTH(bdreg);
           SUSPEND;

           IF (wCOMPENSACAO + wACUMULADO + wACUMULADOTERC > 0) THEN
              BEGIN
                wsql = 'select r21.bdreg,r21.bdinc,r21.bdordem from sp_exp_sefip_reg_21('||
                       wcompensacao||
                       ','||winiciocompensacao||
                       ','||wfimcompensacao||
                       ','||wacumulado||
                       ','||wacumuladoterc||
                       ') r21';
                EXECUTE STATEMENT wsql INTO :bdreg, :bdinc, :bdordem;
                bdqtdchar = CHAR_LENGTH(bdreg);
                SUSPEND;
              END
         END

      /*exporta o registro 30*/
      wsql = 'select r30.bdreg,r30.bdinc,r30.bdordem from sp_exp_sefip_reg_30('||
             wautonomo||','|| -- autonomo
             wbasefgtsfol||','|| -- rem. sem 13
             wbasefgts13||','|| -- rem. 13
             wvalorinssfol||','|| -- valor inss
             wbaseinssfol||','|| -- base inss
             wbaseinss13fol||','||
             wbaseinss13||
             ') r30';

      EXECUTE STATEMENT wsql INTO :bdreg, :bdinc, :bdordem;
      bdqtdchar = CHAR_LENGTH(bdreg);
      SUSPEND;

      /*exporta o registro 32 se precisar*/
      IF (wautonomo <> 0) THEN
         BEGIN
           wsqlmovicol = 'select bddatastr, bdmotivo, cast(bdindfgts as varchar(1)) from SP_EXP_SEFIP_MOVIMENTACAO_COL order by bddata';
           FOR EXECUTE STATEMENT wsqlmovicol INTO
             : wdatamov,
             : wmotivo,
             : windfgts
           DO
             BEGIN
               wsql = '';
               IF (wdatamov IS NULL) THEN
                  wdatamov = '';
               IF (wmotivo IS NULL) THEN
                  wmotivo = '';
               IF (windfgts IS NULL) THEN
                  windfgts = '';
    
               IF (CHAR_LENGTH(wdatamov)>0) THEN
                  BEGIN
                    wsql = 'select r32.bdreg,r32.bdinc,r32.bdordem from sp_exp_sefip_reg_32('||
                           ''''||wmotivo||''''||','||  -- motivo
                           ''''||wdatamov||''''||','|| -- data
                           ''''||windfgts||''''||      -- indfgts
                           ') r32';
                    EXECUTE STATEMENT wsql INTO :bdreg, :bdinc, :bdordem;
                    bdqtdchar = CHAR_LENGTH(bdreg);
                    SUSPEND;
                  END
             END
         END

      /*exporta o registro 90 se precisar o registro 00 deve criar o 90 tb*/
      IF ((wreg00 = 0) OR (wreg00 IS NULL)) THEN
         BEGIN
           wsql = 'select r90.bdreg,r90.bdordem from sp_exp_sefip_reg_90 r90';
           EXECUTE STATEMENT wsql INTO :bdreg, bdordem;
           bdinc = '';
           bdqtdchar = CHAR_LENGTH(bdreg);
           SUSPEND;
         END
    END
END
^

CREATE OR ALTER PROCEDURE SP_VRH_EMP_TSITCOL_ESOCIAL (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(32700)) 
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDDATAINISEFIP DATE,
    BDTIPOACID INTEGER,
    BDOBSERVACAO VARCHAR(255),
    BDCODDOE INTEGER,
    BDDIASSIT INTEGER,
    BDCODMOTESSIT INTEGER,
    BDCODMED INTEGER,
    BDCODSINTRAB INTEGER) 
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODSIT INTEGER;
BEGIN
  wsql = 'select BDCODEMP,BDCODCOL,BDDATAINISEFIP,BDTIPOACID,BDOBSERVACAO,BDCODDOE,BDDIASSIT,BDCODMED,BDCODSINTRAB,BDCODSIT from VRH_EMP_TSITCOL';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wsql = wsql||' where '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

     END

  FOR EXECUTE STATEMENT wsql INTO :BDCODEMP,:BDCODCOL,:BDDATAINISEFIP,:BDTIPOACID,:BDOBSERVACAO,:BDCODDOE,:BDDIASSIT,:BDCODMED,:BDCODSINTRAB,:wcodsit DO
    BEGIN
      SELECT Y.BDCODMOTESSIT FROM (
        SELECT BDCODSIT, MAX(BDDATASTD) BDDATASTD FROM VRH_BASE_TPREPSIT_DIA WHERE BDCODSIT = :wcodsit GROUP BY BDCODSIT) X
      JOIN VRH_BASE_TPREPSIT_DIA Y ON (Y.BDCODSIT = X.BDCODSIT AND Y.BDDATASTD = X.BDDATASTD) INTO :BDCODMOTESSIT;

      SUSPEND;
    END
END
^

/* Restore proc. body: SP_EXP_SEFIP_MOVIMENTACAO_COL */
create or alter procedure SP_EXP_SEFIP_MOVIMENTACAO_COL (
    PRREFINI integer = 0,
    PRREFFIM integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATA date,
    BDDATASTR varchar(10),
    BDMOTIVO varchar(5),
    BDINDFGTS integer,
    BDCODMFG integer,
    BDDATAFIM date,
    BDINSSINTSIT DM_BOOLEAN,
    BDDATAINICIOSIT date,
    BDMOTENTRADA varchar(5),
    BDBENEFDEFERIDO DM_BOOLEAN)
as
declare variable WDATAINCIOSIT date;
declare variable WMOTENTRADA varchar(5);
declare variable WOK integer;
declare variable WMES smallint;
declare variable WANO integer;
declare variable WSQL varchar(32000);
declare variable WSQLAUX varchar(1000);
declare variable WDATAINI varchar(10);
declare variable WDATAFIM varchar(10);
declare variable WANOMES integer;
declare variable WCODEMP integer;
declare variable WAUX integer;
declare variable WCODCOL integer;
declare variable WEMP integer;
declare variable WCOL integer;
declare variable WDATA date;
declare variable WDATASTR varchar(10);
declare variable WMOTIVO varchar(5);
declare variable WCODMFG integer;
declare variable WCODSIT integer;
declare variable WPROJECAO date;
declare variable WDATAFIMSIT date;
declare variable WCODSIT2 integer;
declare variable WINSSINTSIT varchar(5);
declare variable WWHEREEMPCOL varchar(100);
declare variable WAND varchar(7);
declare variable WATESTADO integer;
declare variable WDATA2 date;
BEGIN
  /* Procedure Text */
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wcodemp;
  IF (wcodemp IS NULL) THEN
     wcodemp = 0;

  SELECT rdb$get_context('USER_TRANSACTION', 'W_COLSEFIP') FROM rdb$database INTO wcodcol;
  IF (wcodcol IS NULL) THEN
     wcodcol = 0;

  wand = ' where ';
  wwhereempcol = '';
  IF (wcodemp > 0) THEN
     BEGIN
       wwhereempcol = wwhereempcol||wand||'(sit.bdcodemp = '||wcodemp||')';
       wand = ' and ';
     END

  IF (wcodcol > 0) THEN
     BEGIN
       wwhereempcol = wwhereempcol||wand||'(sit.bdcodcol = '||wcodcol||')';
       wand = ' and ';
     END

  IF (COALESCE(prrefini, 0) > 0 AND COALESCE(prreffim, 0) > 0) THEN
     BEGIN
       wanomes = prrefini;
       wdataini = SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 1 FOR 4);
       wanomes = prreffim;
     END
  ELSE
     BEGIN
       SELECT rdb$get_context('USER_SESSION', 'W_ANOMES') FROM rdb$database INTO wanomes;
       IF (wanomes IS NULL) THEN
          wanomes = 99999;
       wdataini = SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 1 FOR 4);
     END

  wmes = CAST(SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 5) AS SMALLINT);
  wano = CAST(SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO waux;

  wdatafim = SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 5)||'/'||waux||'/'||SUBSTRING(CAST(wanomes AS VARCHAR(6)) FROM 1 FOR 4);

  /* entrada em situacao */
  wsql = ' select sit.bdcodemp, sit.bdcodcol, case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end bddatainisefip,'||
                ' (select x.bdddmmaaaa from ddmmaaaa(case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end) x) Data,'||
                ' sit.bdcodsit, sit.bddatafimsit, sit.bdbenefdeferido, NULL bdatestado'||
         ' from vrh_emp_tsitcol sit'||
         ' join vrh_emp_tcolcon col on (col.bdcodemp = sit.bdcodemp) and (col.bdcodcol = sit.bdcodcol)'||
           wwhereempcol||
           wand||'(COALESCE(sit.bdbenefdeferido,''FALSE'') = ''FALSE'')'|| -- 146010 - Raphael Teodoro - 22/04/2021
           ' and (((sit.bddatainisefip - 1) between cast('''||wdataini||''' as date) and cast('''||wdatafim||''' as date)) or'||
                ' (sit.bddatafimsit'||    ' between cast('''||wdataini||''' as date) and cast('''||wdatafim||''' as date)))';

  -- 146010 - Raphael Teodoro - 22/04/2021 - Separa em "Atestado" e "Afastamento" quando "BDBENEFDEFERIDO = TRUE"
  -- Atestado
  wsql = wsql||' union all'||
         ' select sit.bdcodemp, sit.bdcodcol, case when (sit.bddatainiatestadoaux - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainiatestadoaux - 1) end bddatainisefip,'||
                ' (select x.bdddmmaaaa from ddmmaaaa(case when (sit.bddatainiatestadoaux - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainiatestadoaux - 1) end) x) Data,'||
                ' sit.bdcodsit, sit.bddatafimatestadoaux, sit.bdbenefdeferido, 1 bdatestado'||
         ' from vrh_emp_tsitcol sit '||
         ' join vrh_emp_tcolcon col on (col.bdcodemp = sit.bdcodemp) and (col.bdcodcol = sit.bdcodcol) '||
           wwhereempcol||
           wand||'(COALESCE(sit.bdbenefdeferido,''FALSE'') = ''TRUE'')'||
           ' and (sit.bddatainiatestadoaux is not NULL)'||
           ' and (((sit.bddatainiatestadoaux - 1) between cast('''||wdataini||''' as date) and cast('''||wdatafim||''' as date)) or '||
                 '(sit.bddatafimatestadoaux'||  ' between cast('''||wdataini||''' as date) and cast('''||wdatafim||''' as date)))';

  -- Afastamento
  wsql = wsql||' union all'||
         ' select sit.bdcodemp, sit.bdcodcol, case when (sit.bddatainiafastaux - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainiafastaux - 1) end bddatainisefip,'||
         '        (select x.bdddmmaaaa from ddmmaaaa(case when (sit.bddatainiafastaux - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainiafastaux - 1) end) x) Data,'||
         '        sit.bdcodsit, sit.bddatafimafastaux, sit.bdbenefdeferido, 0 bdatestado'||
         ' from vrh_emp_tsitcol sit '||
         ' join vrh_emp_tcolcon col on (col.bdcodemp = sit.bdcodemp) and (col.bdcodcol = sit.bdcodcol) '||
           wwhereempcol||
           wand||'(COALESCE(sit.bdbenefdeferido,''FALSE'') = ''TRUE'')'||
           ' and (sit.bddatainiafastaux is not NULL)'||
           ' and (((sit.bddatainiafastaux - 1) between cast('''||wdataini||''' as date) and cast('''||wdatafim||''' as date)) or '||
                 '(sit.bddatafimafastaux'||  ' between cast('''||wdataini||''' as date) and cast('''||wdatafim||''' as date)))';

  FOR EXECUTE STATEMENT wsql INTO :wemp, :wcol, :wdata, :wdatastr, :wcodsit, :wdatafimsit, :BDBENEFDEFERIDO, :watestado DO
    BEGIN
      wdata2 = wdata + 1;

      select STD.BDCODMFGENT, mot.BDCODSEFMFG, STD.BDINSSINTSIT
          from (
            select first 1 BDCODSIT, BDDATASTD, BDINSSINTSIT, BDCODMFGENT
            from vrh_base_tprepsit_dia
            where BDCODSIT = :wcodsit and BDDATASTD <= :wdata2
            order by BDCODSIT desc, BDDATASTD desc
          ) STD
          join vrh_base_tmotfgts mot on (mot.bdcodmfg = STD.BDCODMFGENT)
      INTO :wcodmfg,:wmotivo,:winssintsit;

       IF (watestado = 1) THEN
             BEGIN
               IF ((wcodmfg = 12) and (wmotivo = 'O1')) THEN
                  BEGIN
                    wcodmfg = 14;
                    wmotivo = 'O3';
                  END
               ELSE
               IF ((wcodmfg = 15) and (wmotivo = 'P1')) THEN
                  BEGIN
                    wcodmfg = 17;
                    wmotivo = 'P3';
                  END
               ELSE
               IF ((wcodmfg = 34) and (wmotivo = 'Z2')) THEN
                  BEGIN
                    wcodmfg = 38;
                    wmotivo = 'Z6';
                  END
             END

          -- Deve incluir a movimentacao Q1
          IF (UPPER(wmotivo) = 'Q2') THEN
             BEGIN
               BDINDFGTS = NULL;
               wsqlaux = 'select first 1 SIT.BDCODEMP, SIT.BDCODCOL,'||
                               ' case'||
                                 ' when (SIT.BDDATAINISEFIP - 1) < COL.BDDATAADMCOL then COL.BDDATAADMCOL'||
                                 ' else (SIT.BDDATAINISEFIP - 1)'||
                               ' end BDDATAINISEFIP,'||
                               ' (select X.BDDDMMAAAA'||
                                ' from DDMMAAAA(case'||
                                                ' when (SIT.BDDATAINISEFIP - 1) < COL.BDDATAADMCOL then COL.BDDATAADMCOL'||
                                                ' else (SIT.BDDATAINISEFIP - 1)'||
                                              ' end) X) DATA, SIT.BDCODSIT, SIT.BDDATAFIMSIT'||
                         ' from VRH_EMP_TSITCOL SIT'||
                         ' join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = SIT.BDCODEMP) and (COL.BDCODCOL = SIT.BDCODCOL)'||
                           wwhereempcol||
                           wand||'(SIT.BDDATAFIMSIT <= '''||wdata||''')'||
                           ' and (SUBSTRING(CAST(SIT.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 7) <= SUBSTRING(CAST('''||wdata||''' AS VARCHAR(10)) FROM 1 FOR 7))'||
                         ' order by SIT.BDDATAINISEFIP DESC';

               FOR EXECUTE STATEMENT wsqlaux INTO :bdcodemp, :bdcodcol, :bddata, :bddatastr, :wcodsit2, :bddatafim DO
                 BEGIN
                   IF (bddatafim < wdataini) THEN
                      BEGIN
                        for select STD2.BDCODMFGENT, MOT.BDCODSEFMFG, STD2.BDINSSINTSIT
                            from (select BDCODSIT, max(BDDATASTD) BDDATASTD
                                  from VRH_BASE_TPREPSIT_DIA
                                  where (BDCODSIT = :wcodsit2) and (BDDATASTD <= :bddata)
                                  group by BDCODSIT) STD
                                  join VRH_BASE_TPREPSIT_DIA STD2 on (STD2.BDCODSIT = STD.BDCODSIT and STD2.BDDATASTD = STD.BDDATASTD)
                                  join VRH_BASE_TMOTFGTS MOT on (MOT.BDCODMFG = STD2.BDCODMFGENT)
                                  where (MOT.BDCODSEFMFG = 'Q1')

                        INTO :bdcodmfg, :bdmotivo, :winssintsit DO
                          SUSPEND;
                      END
                 END
             END

          BDCODEMP   = wemp;
          BDCODCOL   = wcol;
          BDCODMFG   = wcodmfg;
          BDDATA     = wdata;
          BDDATASTR  = wdatastr;
          BDINDFGTS  = NULL;
          BDMOTIVO   = wmotivo;
          BDDATAFIM  = NULL;
          BDINSSINTSIT = winssintsit;
          BDMOTENTRADA    = wmotivo;
          BDDATAINICIOSIT = wdata + 1;

          SUSPEND;
    END

  /* o mes todo em situacao */
  wsql = 'select sit.bdcodemp, sit.bdcodcol, case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end bddatainisefip,'||
               ' (select x.bdddmmaaaa from ddmmaaaa(case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end) x) Data,'||
               ' sit.bdcodsit, sit.bddatafimsit, sit.bdbenefdeferido, NULL bdatestado'||
        ' from vrh_emp_tsitcol sit'||
        ' join vrh_emp_tcolcon col on (col.bdcodemp = sit.bdcodemp) and (col.bdcodcol = sit.bdcodcol)'||
          wwhereempcol||
          wand||'(COALESCE(sit.bdbenefdeferido,''FALSE'') = ''FALSE'')'|| -- 146010 - Raphael Teodoro - 22/04/2021
          ' and (sit.bddatainisefip - 1) < cast('''||wdataini||''' as date)'||
          ' and ((sit.bddatafimsit is null) or (sit.bddatafimsit > cast('''||wdatafim||''' as date)))';

  -- 146010 - Raphael Teodoro - 22/04/2021 - Separa em "Atestado" e "Afastamento" quando "BDBENEFDEFERIDO = TRUE"
  -- Atestado
  wsql = wsql||' union all'||
         ' select sit.bdcodemp, sit.bdcodcol, case when (sit.bddatainiatestadoaux - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainiatestadoaux - 1) end bddatainisefip,'||
                ' (select x.bdddmmaaaa from ddmmaaaa(case when (sit.bddatainiatestadoaux - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainiatestadoaux - 1) end) x) Data,'||
                ' sit.bdcodsit, sit.bddatafimatestadoaux, sit.bdbenefdeferido, 1 bdatestado'||
         ' from vrh_emp_tsitcol sit'||
         ' join vrh_emp_tcolcon col on (col.bdcodemp = sit.bdcodemp) and (col.bdcodcol = sit.bdcodcol)'||
           wwhereempcol||
           wand||'(COALESCE(sit.bdbenefdeferido,''FALSE'') = ''TRUE'')'||
           ' and (sit.bddatainiatestadoaux - 1) < cast('''||wdataini||''' as date)'||
           ' and ((sit.bddatafimatestadoaux is null) or (sit.bddatafimatestadoaux > cast('''||wdatafim||''' as date)))';

  -- Afastamento
  wsql = wsql||' union all'||
         ' select sit.bdcodemp, sit.bdcodcol, case when (sit.bddatainiafastaux - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainiafastaux - 1) end bddatainisefip,'||
         '        (select x.bdddmmaaaa from ddmmaaaa(case when (sit.bddatainiafastaux - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainiafastaux - 1) end) x) Data,'||
         '        sit.bdcodsit, sit.bddatafimafastaux, sit.bdbenefdeferido, 0 bdatestado'||
         ' from vrh_emp_tsitcol sit'||
         ' join vrh_emp_tcolcon col on (col.bdcodemp = sit.bdcodemp) and (col.bdcodcol = sit.bdcodcol)'||
           wwhereempcol||
           wand||'(COALESCE(sit.bdbenefdeferido,''FALSE'') = ''TRUE'')'||
           ' and (sit.bddatainiafastaux - 1) < cast('''||wdataini||''' as date)'||
           ' and ((sit.bddatafimafastaux is null) or (sit.bddatafimafastaux > cast('''||wdatafim||''' as date)))';

  FOR EXECUTE STATEMENT wsql INTO :wemp, :wcol, :wdata, :wdatastr, :wcodsit, :wdatafimsit, :BDBENEFDEFERIDO, :watestado DO
    BEGIN
      wdata2 = wdata + 1;

      select STD.BDCODMFGENT, mot.BDCODSEFMFG, STD.BDINSSINTSIT
          from (
            select first 1 BDCODSIT, BDDATASTD, BDINSSINTSIT, BDCODMFGENT
            from vrh_base_tprepsit_dia
            where BDCODSIT = :wcodsit and BDDATASTD <= :wdata2
            order by BDCODSIT desc, BDDATASTD desc
          ) STD
          join vrh_base_tmotfgts mot on (mot.bdcodmfg = STD.BDCODMFGENT)
      INTO :wcodmfg,:wmotivo,:winssintsit;
          IF (watestado = 1) THEN
             BEGIN
               IF ((wcodmfg = 12) and (wmotivo = 'O1')) THEN
                  BEGIN
                    wcodmfg = 14;
                    wmotivo = 'O3';
                  END
               ELSE
               IF ((wcodmfg = 15) and (wmotivo = 'P1')) THEN
                  BEGIN
                    wcodmfg = 17;
                    wmotivo = 'P3';
                  END
               ELSE
               IF ((wcodmfg = 34) and (wmotivo = 'Z2')) THEN
                  BEGIN
                    wcodmfg = 38;
                    wmotivo = 'Z6';
                  END
             END

          BDCODEMP   = wemp;
          BDCODCOL   = wcol;
          BDCODMFG   = wcodmfg;
          BDDATA     = wdata;
          BDDATASTR  = wdatastr;
          BDINDFGTS  = NULL;
          BDMOTIVO   = wmotivo;
          BDDATAFIM  = NULL;
          BDINSSINTSIT = winssintsit;
          BDMOTENTRADA = wmotivo;
          BDDATAINICIOSIT = wdata + 1;

          SUSPEND;
    END


  /* saida de situacao */
  wsql = 'select sit.bdcodemp,sit.bdcodcol,sit.bddatafimsit, (select x.bdddmmaaaa from ddmmaaaa(sit.bddatafimsit) x),'||
               ' sit.bdcodsit, sit.bddatafimsit, sit.bddatainisefip, sit.bdbenefdeferido, NULL bdatestado'||
        ' from vrh_emp_tsitcol sit'||
          wwhereempcol||
          wand||'(COALESCE(sit.bdbenefdeferido,''FALSE'') = ''FALSE'')'|| -- 146010 - Raphael Teodoro - 22/04/2021
          ' and (sit.bddatafimsit between cast('''||wdataini||''' as date) and cast('''||wdatafim||''' as date))';

  -- 146010 - Raphael Teodoro - 22/04/2021 - Separa em "Atestado" e "Afastamento" quando "BDBENEFDEFERIDO = TRUE"
  -- Atestado
  wsql = wsql||' union all'||
         ' select sit.bdcodemp, sit.bdcodcol, sit.bddatafimatestadoaux, (select x.bdddmmaaaa from ddmmaaaa(sit.bddatafimatestadoaux) x),'||
                ' sit.bdcodsit, sit.bddatafimatestadoaux, sit.bddatainiatestadoaux, sit.bdbenefdeferido, 1 bdatestado'||
         ' from vrh_emp_tsitcol sit'||
           wwhereempcol||
           wand||'(COALESCE(sit.bdbenefdeferido,''FALSE'') = ''TRUE'')'||
           ' and (sit.bddatafimatestadoaux between cast('''||wdataini||''' as date) and cast('''||wdatafim||''' as date))';

  -- Afastamento
  wsql = wsql||' union all'||
         ' select sit.bdcodemp,sit.bdcodcol,sit.bddatafimafastaux, (select x.bdddmmaaaa from ddmmaaaa(sit.bddatafimafastaux) x),'||
                ' sit.bdcodsit, sit.BDDATAfimafastaux, sit.bddatainiafastaux, sit.bdbenefdeferido, 0 bdatestado'||
         ' from vrh_emp_tsitcol sit'||
           wwhereempcol||
           wand||'(COALESCE(sit.bdbenefdeferido,''FALSE'') = ''TRUE'')'||
           ' and (sit.bddatafimafastaux between cast('''||wdataini||''' as date) and cast('''||wdatafim||''' as date))';

  FOR EXECUTE STATEMENT wsql INTO :wemp, :wcol, :wdata, :wdatastr, :wcodsit, :wdatafimsit, :wdatainciosit, :BDBENEFDEFERIDO, :watestado DO
    BEGIN
      wdata2 = wdata + 1;

      select STD.BDCODMFGENT, MOT.BDCODSEFMFG, STD.BDINSSINTSIT, MOT2.BDCODSEFMFG
      from (select first 1 BDCODSIT, BDDATASTD, BDINSSINTSIT, BDCODMFGENT, BDCODMFGSAI
            from VRH_BASE_TPREPSIT_DIA
            where BDCODSIT = :wcodsit and
                  BDDATASTD <= :wdata2
            order by BDCODSIT desc, BDDATASTD desc) STD
      join VRH_BASE_TMOTFGTS MOT on (MOT.BDCODMFG = STD.BDCODMFGSAI)
      join VRH_BASE_TMOTFGTS MOT2 on (MOT2.BDCODMFG = STD.BDCODMFGENT)
      INTO :wcodmfg,:wmotivo,:winssintsit, :wmotentrada;

          IF (watestado = 1) THEN
             BEGIN
               IF ((wcodmfg = 12) and (wmotentrada = 'O1')) THEN
                  BEGIN
                    wcodmfg = 14;
                    wmotentrada = 'O3';
                  END
               ELSE
               IF ((wcodmfg = 15) and (wmotentrada = 'P1')) THEN
                  BEGIN
                    wcodmfg = 17;
                    wmotentrada = 'P3';
                  END
               ELSE
               IF ((wcodmfg = 34) and (wmotentrada = 'Z2')) THEN
                  BEGIN
                    wcodmfg = 38;
                    wmotentrada = 'Z6';
                  END

               IF (wmotivo = 'O1') THEN
                  wmotivo = 'O3';
               ELSE
               IF (wmotivo = 'P1') THEN
                  wmotivo = 'P3';
               ELSE
               IF (wmotivo = 'Z2') THEN
                  wmotivo = 'Z6';
             END

          BDCODEMP   = wemp;
          BDCODCOL   = wcol;
          BDCODMFG   = wcodmfg;
          BDDATA     = wdata;
          BDDATASTR  = wdatastr;
          BDINDFGTS  = NULL;
          BDMOTIVO   = wmotivo;
          BDDATAFIM  = wdatafimsit;
          BDINSSINTSIT = winssintsit;
          BDMOTENTRADA = wmotentrada;
          BDDATAINICIOSIT = wdatainciosit;

          SUSPEND;
    END


  wsql = '';

  BDDATAFIM = NULL;
  BDBENEFDEFERIDO = NULL;

  /* rescisao */
  wsql = wsql||'SELECT res.bdcodemp,res.bdcodcol,res.bddatarescisao, (SELECT x.bdddmmaaaa FROM ddmmaaaa(res.bddatarescisao) x) Data,'||
         '       mot.bdcodsefmfg CodMovi, pres.bdgrrfpres, mot.BDCODMFG, res.bdprojecaoaviso '||
         ' FROM vrh_emp_trescisao res, vrh_base_tprepresc pres, VRH_BASE_TMOTFGTS mot'||
         ' where (pres.bdcodpres = res.bdcodpres)'||
         ' and (pres.bdcodmfg = mot.bdcodmfg)'||
         ' and ((res.bddatarescisao between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)) or '||
         ' (res.bdprojecaoaviso between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date))) ';

   IF (wcodemp > 0) THEN
      wsql = wsql||' and res.bdcodemp = '||wcodemp;

   IF (wcodcol > 0) THEN
      wsql = wsql||' and res.bdcodcol = '||wcodcol;


  wsql = wsql||' union all ';

  /* transferencia de entrada */
  wsql = wsql||'select tra.bdcodempdest,tra.bdcodcoldest,tra.bddatatrf, (select x.bdddmmaaaa from ddmmaaaa(tra.bddatatrf) x), '||''''||'N3'||''''||' CodMovi, null indfgts, mot.BDCODMFG, CAST(null as DATE) bdprojecaoaviso '||
               ' from vrh_emp_ttranscol tra, vrh_base_tprepRESc ptra, VRH_BASE_TMOTFGTS mot '||
               ' where  (ptra.bdcodpres = tra.bdcodptran)'||
               ' and (ptra.bdcodmfgent = mot.bdcodmfg)'||
         ' and tra.bddatatrf between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)';

  IF (wcodemp > 0) THEN
     wsql = wsql||' and tra.bdcodempdest = '||wcodemp;

  IF (wcodcol > 0) THEN
     wsql = wsql||' and tra.bdcodcoldest = '||wcodcol;

  FOR EXECUTE STATEMENT wsql INTO
      : bdcodemp,
      : bdcodcol,
      : bddata,
      : bddatastr,
      : bdmotivo,
      : bdindfgts,
      : bdcodmfg,
      : wprojecao
    DO
  BEGIN
    wok = 1;

    BDMOTENTRADA = wmotivo;
    BDDATAINICIOSIT = wdata + 1;

    IF (wprojecao IS NOT NULL) THEN
       BEGIN
         IF (wprojecao >= CAST(wdataini AS DATE) AND wprojecao <= CAST(wdatafim AS DATE) AND bddata < CAST(wdataini AS DATE)) THEN
            BEGIN
              bddata    = wprojecao;
              bddatastr = SUBSTRING(CAST(wprojecao AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
                          SUBSTRING(CAST(wprojecao AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
                          SUBSTRING(CAST(wprojecao AS VARCHAR(10)) FROM 1 FOR 4);
            END
       END


    IF ((bdmotivo = 'Q2') AND (bddata <= wdataini)) THEN
       BEGIN
         -- Se movimentacao Q2 for iniciada em mes diferente ou no primeira dia do mes atual precisa buscar a ultima situacao Q1 existente para o colaborador
         SUSPEND;

         for select first 1 sit.bdcodemp, sit.bdcodcol, case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end bddatainisefip,
                        (select x.bdddmmaaaa from ddmmaaaa(case when (sit.bddatainisefip - 1) < col.bddataadmcol then col.bddataadmcol else (sit.bddatainisefip - 1) end) x) Data,
                        mot.bdcodsefmfg codmovi, null indfgts, mot.bdcodmfg, sit.bddatafimsit, sit.bdcodsit
             from vrh_emp_tsitcol sit
             join vrh_base_tprepsit psit on (psit.bdcodsit = sit.bdcodsit)
             join vrh_base_tmotfgts mot on (mot.bdcodmfg = psit.bdcodmfgent)
             join vrh_emp_tcolcon col on (col.bdcodemp = sit.bdcodemp and col.bdcodcol = sit.bdcodcol)
             where upper(mot.bdcodsefmfg) = 'Q1' and (sit.bddatainisefip - 1) < :bddata
                   and sit.bdcodemp = :bdcodemp and sit.bdcodcol = :bdcodcol
             order by sit.bdcodemp desc, sit.bdcodcol desc, sit.bddatainisefip desc

         INTO : bdcodemp, : bdcodcol, : bddata, : bddatastr, : bdmotivo, : bdindfgts, : bdcodmfg, :bddatafim, :wcodsit
         do
           begin
             select first 1 BDINSSINTSIT from vrh_base_tprepsit_dia where BDCODSIT = :wcodsit and BDDATASTD <= :bddata order by BDCODSIT desc, BDDATASTD desc
             into :BDINSSINTSIT;
           end

         wok = 0;
       END

    IF (wok = 1) THEN
      SUSPEND;
  END
END^

/* Restore proc. body: SP_EXP_SEFIP_REG_00 */
ALTER PROCEDURE SP_EXP_SEFIP_REG_00 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
DECLARE VARIABLE wordem VARCHAR(60);
DECLARE VARIABLE wdatarecinss DATE;
DECLARE VARIABLE wdatarecfgts DATE;
DECLARE VARIABLE windrecinss VARCHAR(1);
DECLARE VARIABLE windrecfgts VARCHAR(1);
DECLARE VARIABLE wmodalidade VARCHAR(1);
DECLARE VARIABLE wcodrec INTEGER;
DECLARE VARIABLE wsql VARCHAR(32700);
DECLARE VARIABLE waux VARCHAR(1000);
DECLARE VARIABLE wretorno VARCHAR(1000);
DECLARE VARIABLE wcnpjesc VARCHAR(1000);
DECLARE VARIABLE wnomesc VARCHAR(1000);
DECLARE VARIABLE wnomecont VARCHAR(1000);
DECLARE VARIABLE wlogra VARCHAR(1000);
DECLARE VARIABLE wbaiesc VARCHAR(1000);
DECLARE VARIABLE wcepesc VARCHAR(1000);
DECLARE VARIABLE wnomcid VARCHAR(1000);
DECLARE VARIABLE wsiglauf VARCHAR(1000);
DECLARE VARIABLE wfoneesc VARCHAR(1000);
DECLARE VARIABLE wemailesc VARCHAR(1000);
DECLARE VARIABLE wemp INTEGER;
DECLARE VARIABLE wanomes INTEGER;
BEGIN
  SELECT rdb$get_context('USER_SESSION', 'W_ANOMES') FROM rdb$database INTO wanomes;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wemp;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_CODREC') FROM rdb$database INTO wcodrec;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_MODALIDADEATU') FROM rdb$database INTO WMODALIDADE;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_INDRECFGTS') FROM rdb$database INTO windrecfgts;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_INDRECINSS') FROM rdb$database INTO windrecinss;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_DATARECFGTS') FROM rdb$database INTO wDATArecfgts;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_DATARECINSS')FROM rdb$database INTO wDATArecinss;

  wordem = '0';

  IF (wcodrec IS NULL) THEN
     wcodrec = 0;

  IF (wemp IS NULL) THEN
     wemp = 0;

  wsql =  'select esc.bdcnpjesc, esc.bdnomesc, cp.bdnomecont, esc.bdlogresc||'||''''||' '||''''||'||esc.bdendesc bdlogra,'||
         'esc.bdbaiesc, esc.bdcepesc, cid.bdnomcid, uf.BDSIGLAUF, esc.bddddesc||'||''''||' '||''''||'||esc.bdfoneesc fone, esc.bdemailesc'||
         ' from vw_empresas_ref_atual emp left outer join tcontador_padrao cp on (cp.bdcodcont = emp.bdcodcont) left outer join tescritorio esc on (cp.bdcodesc = esc.bdcodesc) left outer join tcidade cid on (esc.bdcodcid = cid.bdcodcid) left outer join tuf uf on (cid.bdcoduf = uf.bdcoduf)'||
         ' where emp.bdcodemp = '||wemp;

  EXECUTE STATEMENT wsql INTO wcnpjesc, wnomesc, wnomecont, wlogra,wbaiesc, wcepesc, wnomcid, wSIGLAUF, wfoneesc, wemailesc;

    IF (wcnpjesc IS NULL) THEN
       wcnpjesc = '';
    IF (wnomesc IS NULL) THEN
       wnomesc = '';
    IF (wnomecont IS NULL) THEN
       wnomecont = '';
    IF (wlogra IS NULL) THEN
       wlogra = '';
    IF (wbaiesc IS NULL) THEN
       wbaiesc = '';
    IF (wcepesc IS NULL) THEN
       wcepesc = '';
    IF (wnomcid IS NULL) THEN
       wnomcid = '';
    IF (wSIGLAUF IS NULL) THEN
       wSIGLAUF = '';
    IF (wfoneesc IS NULL) THEN
       wfoneesc = '';
    IF (wemailesc IS NULL) THEN
       wemailesc = '';

  /* Procedure Text */
  --  001 a 002 002 N '00' tipo registro
  wRetorno = '00';

  --  003 a 053 051 A brancos
  SELECT bdretorno FROM preenche_direita('',51,' ') INTO waux;
  wRetorno = wRetorno||waux;

  --  054 a 054 001 N Tipo remessa Sefip = 1
  wRetorno = wRetorno||'1';

  waux = '';
  --  055 a 055 001 N Tipo inscrição responsavel 1 = cnpj / 2 = cei / 3 = cpf
  wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjesc||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  056 a 069 014 N Numero de inscrição
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wcnpjesc||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',14,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  070 a 099 030 A Nome responsavel (Razão social)
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wnomesc||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',30,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  100 a 119 020 A Nome pessoa contado
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wnomecont||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  120 a 169 050 A Logradouro, rua...
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wlogra||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',50,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  170 a 189 020 A bairro
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wbaiesc||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  190 a 197 008 N CEP
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wcepesc||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',8,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  198 a 217 020 A cidade
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wnomcid||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  218 a 219 002 A uf
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wSIGLAUF||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',2,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  220 a 231 012 N Telefone contato
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wfoneesc||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',12,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  232 a 291 060 A Endereco internet e-mail
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wemailesc||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  waux = wemailesc;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',60,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  292 a 297 006 N Compentecia AAAAMM
  IF (wanomes IS NULL) THEN
     wanomes = 0;
  wRetorno = wRetorno||CAST(wanomes AS VARCHAR(6));

  --  298 a 300 003 N Codigo recolhimento
  wRetorno = wRetorno||CAST(wcodrec AS VARCHAR(3));

  --  301 a 301 001 N Indicador recolhimento FGTS
  IF (windrecfgts IS NULL) THEN
     windrecfgts = '';

  wsql = 'select bdretorno from preenche_direita('||''''||windrecfgts||''''||',1,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  302 A 302 001 N modalidade do arquivo
  IF (wmodalidade IS NULL) THEN
     wmodalidade = '';

  wsql = 'select bdretorno from preenche_esquerda('||''''||wmodalidade||''''||',1,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  303 a 310 008 N Data recolhimento fgts
  IF (wdatarecfgts IS NULL) THEN
     SELECT bdretorno FROM preenche_direita('',8,' ') INTO waux;
  ELSE
     waux = SUBSTRING(CAST(wdatarecfgts AS VARCHAR(10)) FROM 9 FOR 2)||SUBSTRING(CAST(wdatarecfgts AS VARCHAR(10)) FROM 6 FOR 2)||SUBSTRING(CAST(wdatarecfgts AS VARCHAR(10)) FROM 1 FOR 4);
  wRetorno = wRetorno||waux;

  --  311 a 311 001 N Indicador recolhimento previdencia social
  IF (windrecinss IS NULL) THEN
     windrecinss = '';

  wsql = 'select bdretorno from preenche_direita('||''''||windrecinss||''''||',1,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  --  312 a 319 008 N Data recolhimento previdencia social
  IF (wdatarecinss IS NULL) THEN
     SELECT bdretorno FROM preenche_direita('',8,' ') INTO waux;
  ELSE
     waux = SUBSTRING(CAST(wdatarecinss AS VARCHAR(10)) FROM 9 FOR 2)||SUBSTRING(CAST(wdatarecinss AS VARCHAR(10)) FROM 6 FOR 2)||SUBSTRING(CAST(wdatarecinss AS VARCHAR(10)) FROM 1 FOR 4);
  wRetorno = wRetorno||waux;

  --  320 a 326 007 N Indicador de recolhimento em atraso da previdencia social
  SELECT bdretorno FROM preenche_direita('',7,' ') INTO waux;
  wRetorno = wRetorno||waux;

  --  327 a 327 001 N Tipo inscrição fornecedor folha
  wRetorno = wRetorno||'1';

  --  328 a 341 014 N Inscriçao fornecedor
  wRetorno = wRetorno||'82923160000177';

  --  342 a 359 018 A brancos
  SELECT bdretorno FROM preenche_direita('',18,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 360 a 360 001 A '*' fim do arquivo
  wRetorno = wRetorno||'*';

  bdReg = SUBSTRING(wretorno FROM 1 FOR 360);
  bdordem = wordem;
  SUSPEND;
END
^

/* Restore proc. body: SP_EXP_SEFIP_REG_10 */
ALTER PROCEDURE SP_EXP_SEFIP_REG_10(PRSALFAM NUMERIC(15,6),
PRMATERNIDADE NUMERIC(15,6))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
DECLARE VARIABLE WDDD INTEGER;
DECLARE VARIABLE WTIPOCALCULO INTEGER;
DECLARE VARIABLE WPERCISENCAO NUMERIC(15,6);
DECLARE VARIABLE WCODGPS INTEGER;
DECLARE VARIABLE WCODTERC INTEGER;
DECLARE VARIABLE WFPAS INTEGER;
DECLARE VARIABLE WCODREC INTEGER;
DECLARE VARIABLE WSIMPLES INTEGER;
DECLARE VARIABLE WORDEM VARCHAR(60);
DECLARE VARIABLE WPERCRAT VARCHAR(2);
DECLARE VARIABLE WCENTRALIZA INTEGER;
DECLARE VARIABLE WANOMES INTEGER;
DECLARE VARIABLE WCNAEEMP INTEGER;
DECLARE VARIABLE WEMP INTEGER;
DECLARE VARIABLE WSQL VARCHAR(31000);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WAUX VARCHAR(360);
DECLARE VARIABLE WRETORNO VARCHAR(360);
DECLARE VARIABLE WNOMEMP VARCHAR(360);
DECLARE VARIABLE WLOGRA VARCHAR(360);
DECLARE VARIABLE WBAIRRO VARCHAR(360);
DECLARE VARIABLE WCEP VARCHAR(10);
DECLARE VARIABLE WNOMCIDADE VARCHAR(360);
DECLARE VARIABLE WUF VARCHAR(2);
DECLARE VARIABLE WFONE VARCHAR(20);
BEGIN
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wemp;
  SELECT rdb$get_context('USER_SESSION', 'W_ANOMES') FROM rdb$database INTO wanomes;
  SELECT rdb$get_context('USER_TRANSACTION','W_CODREC') FROM rdb$database INTO wcodrec;
  SELECT rdb$get_context('USER_TRANSACTION','W_TIPOFOLHA') FROM rdb$database INTO wtipocalculo;

  wordem = '1';
--  // 001 a 002 002 N '10' tipo registro
  wretorno = '10';

  wsql =  'select emp.bdcnpjemp, remp.bdnomemp,'||
          'remp.bdlogremp||'||''''||' '||''''||'||remp.bdendemp||'||''''||' '||''''||'||remp.bdnumemp enderec,'||
          'remp.bdbaiemp, remp.bdcepemp, cid.bdnomcid, uf.bdsiglauf, remp.BDDDDEMP, remp.bdfoneemp fone, remp.bdcodcnae,'||
          'emps.bdcetrtalizaemp, substring(cast(cast(empg.bdcnaeratemp as integer) as varchar(10)) from 1 for 2),'||
          'tegps.bdsimplesgps, tegps.BDCODFPAS, tegps.bdcodterc, tegps.bdcodgps, emps.bdisenfilemp'||
          ' from vw_empresas_ref_atual remp'||
          ' left outer join tempresas emp on (emp.bdcodemp = remp.bdcodemp)'||
          ' left outer join VW_VRHF_BASE_TEMPSEFIP emps on (remp.bdcodemp = emps.bdcodemp)'||
          ' left outer join vw_vrhf_base_tempgps empg on (remp.bdcodemp = empg.bdcodemp)'||
          ' left outer join tcidade cid on (remp.bdcodcid = cid.bdcodcid)'||
          ' left outer join tuf uf on (cid.bdcoduf = uf.bdcoduf)'||
          ' left outer join VW_VRHF_BASE_TEMPGPS tegps on (tegps.bdcodemp = remp.bdcodemp)'||
          ' where emp.bdcodemp = '||wemp;

  EXECUTE STATEMENT wsql INTO
     wcnpjemp, wnomemp, wlogra,wbairro, wcep, wnomcidade, wuf, wddd, wfone, WCNAEEMP,
     WCENTRALIZA, wpercrat, wsimples, wfpas, wcodterc, wcodgps, wpercisencao;

  IF (wddd IS NULL) THEN
     wddd = 0;

  IF (wpercisencao IS NULL) THEN
     wpercisencao = 0;

  IF (wsimples IS NULL) THEN
     wsimples = 0;

  IF (wfpas IS NULL) THEN
     wfpas = 0;

  IF (wcodterc IS NULL) THEN
     wcodterc = 0;

  IF (wcodgps IS NULL) THEN
     wcodgps = 0;

  IF (wpercrat IS NULL) THEN
     wpercrat = '0';

  IF (wcentraliza IS NULL) THEN
     wcentraliza = 0;

  IF (wcnaeemp IS NULL) THEN
     wcnaeemp = 0;

  IF (wcnpjemp IS NULL) THEN
     wcnpjemp = '';

  IF (wnomemp IS NULL) THEN
     wnomemp = '';

  IF (wlogra IS NULL) THEN
     wlogra = '';

  IF (wbairro IS NULL) THEN
     wbairro = '';

  IF (wcep IS NULL) THEN
     wcep = '';

  IF (wnomcidade IS NULL) THEN
     wnomcidade = '';

  IF (wuf IS NULL) THEN
     wuf = '';

  IF (wfone IS NULL) THEN
     wfone = '';


--  003 a 003 001 N Tipo inscricao
  wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjemp||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

--  004 a 017 014 N Inscricao da empresa
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjemp)||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

--  018 a 053 036 N Zeros
  SELECT bdretorno FROM preenche_direita('',36,'0') INTO waux;
  wRetorno = wRetorno||waux;

--  054 a 093 040 A Nome empresa
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wnomemp||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',40,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  094 a 143 050 A endereço
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wlogra||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',50,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  144 a 163 020 A bairro
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wbairro||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  164 a 171 008 N Cep
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wcep||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',8,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  172 a 191 020 A Cidade
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wnomcidade||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  192 a 193 002 A Uf
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wuf||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',2,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  194 a 205 012 N Telefone
  -- ddd 4
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wddd||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',4,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  --- fone 8
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wfone||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',8,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  206 a 206 001 A Indicador alteracao de endereco
  SELECT bdretorno FROM preenche_direita('',1,'N') INTO waux;
  wRetorno = wRetorno||waux;

--  207 a 213 007 N CNAE
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||WCNAEEMP||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',7,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  214 a 214 001 A Indicacaor alteracao CNAE
  IF (wtipocalculo = 2) THEN /* ck13.Checked */
     wRetorno = wRetorno||'N';
  ELSE
  IF (wAnoMes >= '200812') THEN
     BEGIN
       IF (wcentraliza IN (0, 1)) THEN
          wRetorno = wRetorno|| 'P';
       ELSE
          wRetorno = wRetorno||'N';
     END
  ELSE
     wRetorno = wRetorno||'N';

--  215 a 216 002 N Aliquota rat
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',2,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  217 a 217 001 N codigo centralizacao
  waux = CAST(wcentraliza AS VARCHAR(10));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',1,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  218 a 218 001 N Simples
  IF ((wanomes < '199612') OR (wcodrec = 640)) THEN
     wRetorno = wRetorno||' ';
  ELSE
     BEGIN
       IF (wanomes < '200701') THEN
          BEGIN
            wRetorno = wRetorno||CAST(wSimples + 1 AS VARCHAR(1)) ;
          END
       ELSE
          BEGIN
            IF ((wSimples + 1) IN (1,4,5)) THEN
               wRetorno = wRetorno||'1';
            ELSE
               wRetorno = wRetorno||'2';
          END
     END

--  219 a 221 003 N FPAS
  waux = CAST(wfpas AS VARCHAR(10));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',3,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  222 a 225 004 N Codigo outras entidades (terceiros empresa)
  waux = CAST(wcodterc AS VARCHAR(10));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',4,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  226 a 229 004 N Codigo gps
  IF ((wcodrec NOT IN (327,135)) AND (wcodgps = 0)) THEN
     waux = '    ';
  ELSE
     waux = CAST(wcodgps AS VARCHAR(10));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',4,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  230 a 234 005 N Per. insensao filantropia
  waux = CAST(CAST((wpercisencao * 100) AS INTEGER) AS VARCHAR(5));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',5,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  235 a 249 015 N Salario- familia
  waux = TRIM(CAST(CAST((prsalfam * 100) AS INTEGER) AS VARCHAR(15)));
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  250 a 264 015 N Salario-maternidade
  waux = TRIM(CAST(CAST((prmaternidade * 100) AS INTEGER) AS VARCHAR(15)));
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

--  265 a 279 015 N Contri. Desc. Segurados preencher com zeros
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

--  280 a 280 001 N Indicador valor negativo preencher com zero
  wRetorno = wRetorno||'0';

--  281 a 294 015 N Valor devido previdencia preencher com zeros
  SELECT bdretorno FROM preenche_direita('',14,'0') INTO waux;
  wRetorno = wRetorno||waux;

--  295 a 297 003 N Banco
  SELECT bdretorno FROM preenche_esquerda('',3,'0') INTO waux;
  wRetorno = wRetorno||waux;

--  298 a 301 004 N Agencia
  SELECT bdretorno FROM preenche_esquerda('',4,'0') INTO waux;
  wRetorno = wRetorno||waux;

--  302 a 310 009 N Conta corrente
  SELECT bdretorno FROM preenche_esquerda('',9,'0') INTO waux;
  wRetorno = wRetorno||waux;

--  311 a 355 045 N Zeros (implementação furura da sefip)
  SELECT bdretorno FROM preenche_direita('',45,'0') INTO waux;
  wRetorno = wRetorno||waux;

--  356 a 359 004 A Brancos
  SELECT bdretorno FROM preenche_direita('',4,' ') INTO waux;
  wRetorno = wRetorno||waux;

--  360 a 360 001 A '*' final de linha
--  select bdretorno from preenche_direita('',18,' ') into waux;
  wRetorno = wRetorno||'*';

  /*ordem tomador*/
  wordem = wordem||'0'; -- tipo cnpj
  wordem = wordem||'00000000000000'; -- cnpj

  /*ordem trabalhador*/
  wordem = wordem||'00000000000'; --pis
  wordem = wordem||'00000000'; -- data adm
  wordem = wordem||'00'; -- categoria

  bdreg = SUBSTRING(wretorno FROM 1 FOR 360);
  bdordem = wordem||'10';
  SUSPEND;
END
^

/* Restore proc. body: SP_EXP_SEFIP_REG_12 */
ALTER PROCEDURE SP_EXP_SEFIP_REG_12(BDDEDMAT13 NUMERIC(15,6),
BDRURALFISICA NUMERIC(15,6),
BDRURALJURIDICA NUMERIC(15,6),
BDCOMPENSACAO NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDACUMULA NUMERIC(15,6),
BDACUMULATERC NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
DECLARE VARIABLE wordem VARCHAR(60);
DECLARE VARIABLE wcnpjemp VARCHAR(18);
DECLARE VARIABLE wsql VARCHAR(32000);
DECLARE VARIABLE wemp INTEGER;
DECLARE VARIABLE wretorno VARCHAR(360);
DECLARE VARIABLE waux VARCHAR(360);
BEGIN
  /* Procedure Text */
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wemp;

  wsql =  'select emp.bdcnpjemp from tempresas emp'||
          ' where emp.bdcodemp = '||wemp;

  wordem = '1';

  EXECUTE STATEMENT wsql INTO wcnpjemp;
  -- 001 a 002 002 N '12' tipo registro
  wretorno = '12';

  --  // 003 a 003 001 N Tipo inscricao
  wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjemp||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  --  // 004 a 017 014 N Inscricao da empresa
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjemp)||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  -- 018 a 053 036 N Zeros
  SELECT bdretorno FROM preenche_direita('',36,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 054 a 068 015 V Dedução 13º salario maternidade
  waux = CAST(CAST((bddedmat13 * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 069 a 083 015 V Receita evento desportivo
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 084 a 084 001 A Indicador origem receita
  wRetorno = wRetorno||' ';

  -- 085 a 099 015 V Comercializacao da producao Pessoa fisica
  waux = CAST(CAST((bdruralfisica * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 100 a 114 015 V Comercializacao da producao Pessoa Juridica
  waux = CAST(CAST((bdruraljuridica * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 115 a 125 011 N Outras informacoes processos (obrigatorio 650 e 660) demais deixar em branco
  SELECT bdretorno FROM preenche_direita('',11,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 126 a 129 004 N Outras informacoes Ano deixar em branco quando nao informado
  SELECT bdretorno FROM preenche_direita('',4,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 130 a 134 005 N Outras informacoes Vara deixar em branco quando nao informado
  SELECT bdretorno FROM preenche_direita('',5,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 135 a 140 006 N Outras informacoes Periodo inicio deixar em branco quando nao informado
  SELECT bdretorno FROM preenche_direita('',6,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 141 a 146 006 N Outras informacoes Periodo fim deixar em branco quando nao informado
  SELECT bdretorno FROM preenche_direita('',6,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 147 a 161 015 V Compensacao
  waux = CAST(CAST((bdcompensacao * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 162 a 167 006 D Periodo inicio compensacao AAAAMM
  waux = CAST(bdinicomp AS VARCHAR(6));
  waux = SUBSTRING(waux FROM 3)||SUBSTRING(waux FROM 1 FOR 2);
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',6,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 168 a 173 006 D Periodo final compensacao AAAAMM
  waux = CAST(bdfimcomp AS VARCHAR(6));
  waux = SUBSTRING(waux FROM 3)||SUBSTRING(waux FROM 1 FOR 2);
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',6,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 174 a 188 015 V Recolhimento competencias anteriores valor inss
  waux = CAST(CAST((bdacumula * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 189 a 203 015 V Recolhimento competencias anteriores outras entidades
  waux = CAST(CAST((bdacumulaterc * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 204 a 218 015 V Recolhimento competencias anteriores Comercializacao da producao
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 219 a 233 015 V Recolhimento competencias anteriores Comercializacao da producao outras entidades
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 234 a 248 015 V Recolhimento competencias receita de eventos desportivos
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 249 a 263 015 V Parcelamento FGTS Base Categorias 1,2,3,5,6 (preencher com zeros)
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 264 a 278 015 V Parcelamento FGTS Base Categorias 4 e 7 (preencher com zeros)
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 279 a 293 015 V Parcelamento FGTS Valor (preencher com zeros)
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 294 a 308 015 V Valor paga cooperativas
  waux = CAST(CAST((bdnfcoop * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 309 a 353 045 N Preencher com zeros
  SELECT bdretorno FROM preenche_direita('',45,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 354 a 359 006 A Brancos
  SELECT bdretorno FROM preenche_direita('',6,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 360 a 360 001 A '*' finalizar registro
  wretorno = wretorno||'*';

  /*ordem tomador*/
  wordem = wordem||'0'; -- tipo cnpj
  wordem = wordem||'00000000000000'; -- cnpj

  /*ordem trabalhador*/
  wordem = wordem||'00000000000'; --pis
  wordem = wordem||'00000000'; -- data adm
  wordem = wordem||'00'; -- categoria

  bdreg = SUBSTRING(wretorno FROM 1 FOR 360);
  bdordem = wordem||'12';
  SUSPEND;
END
^

/* Restore proc. body: SP_EXP_SEFIP_REG_20 */
ALTER PROCEDURE SP_EXP_SEFIP_REG_20(BDSALFAM INTEGER,
BDNOTASFISCAIS INTEGER)
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
DECLARE VARIABLE wcodgps INTEGER;
DECLARE VARIABLE wtomador INTEGER;
DECLARE VARIABLE wcodrec INTEGER;
DECLARE VARIABLE wordem VARCHAR(60);
DECLARE VARIABLE wcnpjemp VARCHAR(18);
DECLARE VARIABLE wsql VARCHAR(32000);
DECLARE VARIABLE wemp INTEGER;
DECLARE VARIABLE wretorno VARCHAR(360);
DECLARE VARIABLE waux VARCHAR(360);
DECLARE VARIABLE wcnpjtom VARCHAR(360);
DECLARE VARIABLE wnometom VARCHAR(360);
DECLARE VARIABLE wenderecotom VARCHAR(360);
DECLARE VARIABLE wbairrotom VARCHAR(360);
DECLARE VARIABLE wceptom VARCHAR(360);
DECLARE VARIABLE wcidadetom VARCHAR(360);
DECLARE VARIABLE wuftom VARCHAR(360);
DECLARE VARIABLE wcodgpstom VARCHAR(360);
BEGIN
  bdinc = '';
  /* Procedure Text */
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wemp;
  SELECT rdb$get_context('USER_TRANSACTION','W_CODREC') FROM rdb$database INTO wcodrec;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_TOMADORSEFIP') FROM rdb$database INTO wtomador;

  wsql =  'select emp.bdcnpjemp, tegps.bdcodgps from tempresas emp'||
          ' left outer join VW_VRHF_BASE_TEMPGPS tegps on (tegps.bdcodemp = emp.bdcodemp)'||
          ' where emp.bdcodemp = '||wemp;

  EXECUTE STATEMENT wsql INTO :wcnpjemp, :wcodgps;

  wordem = '1';

  -- 001 a 002 002 N '20' tipo registro
  wretorno = '20';

  SELECT bdcnpj,bdnome, bdendereco, bdbairro, bdcep, bdcidade, bduf, bdcodgps FROM sp_tomador_sefip
  INTO
    wcnpjtom,
    wnometom,
    wenderecotom,
    wbairrotom,
    wceptom,
    wcidadetom,
    wuftom,
    wcodgpstom;

  IF (wnometom = '') THEN
     BEGIN
       bdinc = bdinc||'Dados do Tomador '||wtomador||' não cadastrados. $A$B';
     END

  --  // 003 a 003 001 N Tipo inscricao
  wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjemp||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  --  // 004 a 017 014 N Inscricao da empresa
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjemp)||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  -- 018 a 018 001 N Tipo inscricao tomador
  wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjtom||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  -- 019 a 032 014 N Insricrao tomador
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjtom)||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  -- 033 a 053 021 N Zeros
  SELECT bdretorno FROM preenche_direita('',21,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 054 a 093 040 A Nome do tomador
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wnometom||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',40,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 094 a 143 050 A Endereco
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wenderecotom||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',50,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 144 a 163 020 A Bairro
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wbairrotom||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 164 a 171 008 N Cep
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wceptom||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',8,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 172 a 191 020 A Cidade
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wcidadetom||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 192 a 193 002 A Uf
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wuftom||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',2,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 194 a 197 004 N Codigo GPS (não informado deixar em branco)
  IF ((wcodrec NOT IN (130,155,135,317,337,608,908,909,910))
      OR  (wcodrec IN (911,211))) THEN
     SELECT bdretorno FROM preenche_esquerda('',4,' ') INTO waux;
  ELSE
     BEGIN
       IF ((wtomador IS NULL) OR (wtomador = 0)) THEN
          BEGIN
            IF (wcodgps IS NULL) THEN
               wcodgps = 0;

            waux = CAST(wcodgps AS VARCHAR(10));
            wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
            EXECUTE STATEMENT wsql INTO waux;
            wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',4,'||''''||'0'||''''||')';
            EXECUTE STATEMENT wsql INTO waux;
          END
       ELSE
          BEGIN
            waux = CAST(wcodgpstom AS VARCHAR(10));
            wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
            EXECUTE STATEMENT wsql INTO waux;
            wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',4,'||''''||'0'||''''||')';
            EXECUTE STATEMENT wsql INTO waux;
          END
     END
  wRetorno = wRetorno||waux;

  -- 198 a 212 015 V Salario familia
  waux = CAST(CAST((bdsalfam * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 213 a 227 015 V Contribuiçao descontada empregado comp. 13 (preencher com zeros)
  SELECT bdretorno FROM preenche_esquerda('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 228 a 228 001 N Indicador valor negativo preencher com zero
  wRetorno = wRetorno||'0';

  -- 229 a 242 014 V Valor devido a previdencia social preencher com zeros
  SELECT bdretorno FROM preenche_direita('',14,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 243 a 257 015 V Valor retenção (Notas fiscais)
  waux = CAST(CAST((bdnotasfiscais * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 258 a 272 015 V Valor faturas emitidas para o tomador
  SELECT bdretorno FROM preenche_esquerda('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 273 a 317 045 V preencher com zeros
  SELECT bdretorno FROM preenche_direita('',45,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 318 a 359 042 A Brancos
  SELECT bdretorno FROM preenche_direita('',42,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 360 a 360 001 A '*' finalizador de registro
  wretorno = wretorno||'*';

  /*ordem trabalhador*/
  wordem = wordem||'00000000000'; --pis
  wordem = wordem||'00000000'; -- data adm
  wordem = wordem||'00'; -- categoria

  bdreg = SUBSTRING(wretorno FROM 1 FOR 360);
  bdordem = wordem||'20';
  SUSPEND;
END
^

/* Restore proc. body: SP_EXP_SEFIP_REG_21 */
ALTER PROCEDURE SP_EXP_SEFIP_REG_21(BDCOMPENSACAO NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDACUMULA NUMERIC(15,6),
BDACUMULATERC NUMERIC(15,6))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
DECLARE VARIABLE wordem VARCHAR(60);
DECLARE VARIABLE wcnpjtom VARCHAR(20);
DECLARE VARIABLE wretorno VARCHAR(360);
DECLARE VARIABLE waux VARCHAR(360);
DECLARE VARIABLE wcnpjemp VARCHAR(20);
DECLARE VARIABLE wsql VARCHAR(32000);
DECLARE VARIABLE wemp INTEGER;
BEGIN
  /* Procedure Text */
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wemp;

  wsql =  'select emp.bdcnpjemp from tempresas emp'||
          ' where emp.bdcodemp = '||wemp;

  wordem = '1';

  EXECUTE STATEMENT wsql INTO wcnpjemp;
  -- Ini   fim Tam T Desc
  -- 001 a 002 002 N '21' tipo registro
  wRetorno = '21';

  --  // 003 a 003 001 N Tipo inscricao
  wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjemp||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  --  // 004 a 017 014 N Inscricao da empresa
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjemp)||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  SELECT bdcnpj FROM sp_tomador_sefip
  INTO
    wcnpjtom;

  -- 018 a 018 001 N Tipo inscricao tomador
  wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjtom||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  -- 019 a 032 014 N Insricrao tomador
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjtom)||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  -- 033 a 053 021 N Zeros
  SELECT bdretorno FROM preenche_direita('',21,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 054 a 068 015 V Compensaçao
  waux = CAST(CAST((bdcompensacao * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 069 a 074 006 D AAAAMM inicio compensacao
  waux = CAST(bdinicomp AS VARCHAR(6));
  waux = SUBSTRING(waux FROM 5)||SUBSTRING(waux FROM 1 FOR 4);
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',6,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 075 a 080 006 D AAAAMM fim compensacao
  waux = CAST(bdfimcomp AS VARCHAR(6));
  waux = SUBSTRING(waux FROM 5)||SUBSTRING(waux FROM 1 FOR 4);
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',6,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 081 a 095 015 V Recolhimento competencias anteriores Valor Inss
  waux = CAST(CAST((bdacumula * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 096 a 110 015 V Recolhimento competencias anteriores Valor outras entidades
  waux = CAST(CAST((bdacumulaterc * 100) AS INTEGER) AS VARCHAR(15));
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 111 a 125 015 V Parcelamento preencher com zeros
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 126 a 140 015 V Parcelamento preencher com zeros
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 141 a 155 015 V Parcelamento preencher com zeros
  SELECT bdretorno FROM preenche_direita('',15,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 156 a 359 204 A brancos
  SELECT bdretorno FROM preenche_direita('',204,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 360 a 360 001 A '*' finalizador de registros
  wRetorno = wRetorno||'*';

  /*ordem trabalhador*/
  wordem = wordem||'00000000000'; --pis
  wordem = wordem||'00000000'; -- data adm
  wordem = wordem||'00'; -- categoria

  bdreg = SUBSTRING(wretorno FROM 1 FOR 360);
  bdordem = wordem||'21';
  SUSPEND;
END
^

/* Restore proc. body: SP_EXP_SEFIP_REG_30 */
ALTER PROCEDURE SP_EXP_SEFIP_REG_30(PRAUTONOMO INTEGER,
PRREMSEM13 NUMERIC(15,6),
PRREM13 NUMERIC(15,6),
PRVALINSS NUMERIC(15,6),
PRBASEINSS NUMERIC(15,6),
PRBASEINSS13MES NUMERIC(15,6),
PRBASEINSS13 NUMERIC(15,6))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
DECLARE VARIABLE WOCORENCIA VARCHAR(1);
DECLARE VARIABLE WORDEM VARCHAR(60);
DECLARE VARIABLE WRETORNO VARCHAR(360);
DECLARE VARIABLE WAUX VARCHAR(360);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WCNPJTOM VARCHAR(20);
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WPIS VARCHAR(20);
DECLARE VARIABLE WADM VARCHAR(10);
DECLARE VARIABLE WCATEGORIA VARCHAR(10);
DECLARE VARIABLE WNOME VARCHAR(70);
DECLARE VARIABLE WMATRICULA VARCHAR(10);
DECLARE VARIABLE WCTPS VARCHAR(10);
DECLARE VARIABLE WSERIECT DM_SERIECTPS;
DECLARE VARIABLE WDATAOPCAO VARCHAR(10);
DECLARE VARIABLE WDATANASC VARCHAR(10);
DECLARE VARIABLE WCBO VARCHAR(10);
DECLARE VARIABLE WEMP INTEGER;
DECLARE VARIABLE WCPF VARCHAR(14);
BEGIN
  /* Procedure Text */
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wemp;

--  wemp = 3;
  wsql =  'select emp.bdcnpjemp from tempresas emp'||
          ' where emp.bdcodemp = '||wemp;

  wordem = '1';
  EXECUTE STATEMENT wsql INTO wcnpjemp;

  IF (wcnpjemp IS NULL) THEN
     wcnpjemp = '';

  -- Ini   fim Tam T Desc
  -- 001 a 002 002 N '30' tipo registro
  wRetorno = '30';

  --  // 003 a 003 001 N Tipo inscricao
  wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjemp||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  --  // 004 a 017 014 N Inscricao da empresa
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjemp)||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  SELECT bdcnpj FROM sp_tomador_sefip
  INTO
    wcnpjtom;

  IF (wcnpjtom IS NULL) THEN
     wcnpjtom = '';

  IF (wcnpjtom <> '') THEN
     BEGIN
       -- 018 a 018 001 N Tipo inscricao tomador
       wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjtom||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;
       wordem = wordem||waux;
    
       -- 019 a 032 014 N Insricrao tomador
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjtom)||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;
       wordem = wordem||waux;
     END
  ELSE
     BEGIN
       -- 018 a 018 001 N Tipo inscricao tomador
       waux = ' ';
       wRetorno = wRetorno||waux;
       waux = '0';
       wordem = wordem||waux;
    
       -- 019 a 032 014 N Insricrao tomador
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjtom)||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjtom)||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wordem = wordem||waux;
     END

  IF (prautonomo = 0) THEN
     BEGIN
       SELECT BDOCORRENCIA,bdpis,bdadm,bdcategoria,bdnome,bdmatricula,bdctps,bdseriect,bddataopcao,bddatanasc,bdcbo,bdcpf FROM sp_autonomo_sefip
       INTO
         wocorencia,wpis,wadm,wcategoria,wnome,wmatricula,wctps,wseriect,wdataopcao,wdatanasc,wcbo,wcpf;
     END
  ELSE
     BEGIN
       SELECT BDOCORRENCIA,bdpis,bdadm,bdcategoria,bdnome,bdmatricula,bdctps,bdseriect,bddataopcao,bddatanasc,bdcbo,bdcpf FROM sp_colaborador_sefip
       INTO
         wocorencia,wpis,wadm,wcategoria,wnome,wmatricula,wctps,wseriect,wdataopcao,wdatanasc,wcbo,wcpf;
     END

  -- 033 a 043 011 N Pis
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wpis)||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',11,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  -- 044 a 051 008 D Data admissao DDMMAAAA
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wadm||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  IF (wadm = '') THEN
     wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',8,'||''''||' '||''''||')';
  ELSE
     wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',8,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  waux = SUBSTRING(waux FROM 5)||SUBSTRING(waux FROM 3 FOR 2)||SUBSTRING(waux FROM 1 FOR 2);
  wordem = wordem||waux;

  -- 052 a 053 002 N Categoria
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wcategoria||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',2,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  -- 054 a 123 070 A Nome empregado
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wnome||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',70,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 124 a 134 011 N Matricula do empregasdo
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wmatricula||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',11,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  if ((wctps <> '') and (wseriect <> '')) then
    begin
      -- 135 a 141 007 N CTPS
      wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wctps||''''||')';
      EXECUTE STATEMENT wsql INTO waux;
      wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',7,'||''''||'0'||''''||')';
      EXECUTE STATEMENT wsql INTO waux;
      wRetorno = wRetorno||waux;
    
      -- 142 a 146 005 N Serie CTPS
      wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wseriect||''''||')';
      EXECUTE STATEMENT wsql INTO waux;
      wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',5,'||''''||'0'||''''||')';
      EXECUTE STATEMENT wsql INTO waux;
      wRetorno = wRetorno||waux;
    end
  else
    begin
      -- 135 a 141 007 N CTPS
      wsql = 'select substring(bdretorno from 1 for 7) bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wcpf||''''||')';
      EXECUTE STATEMENT wsql INTO waux;
      wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',7,'||''''||'0'||''''||')';
      EXECUTE STATEMENT wsql INTO waux;
      wRetorno = wRetorno||waux;
    
      -- 142 a 146 005 N Serie CTPS
      wsql = 'select substring(bdretorno from 8 for 4) bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wcpf||''''||')';
      EXECUTE STATEMENT wsql INTO waux;
      wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',5,'||''''||'0'||''''||')';
      EXECUTE STATEMENT wsql INTO waux;
      wRetorno = wRetorno||waux;
    end

  -- 147 a 154 008 D Data opcao DDMMAAAA
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wdataopcao||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',8,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 155 a 162 008 D Data nascimento DDMMAAAA
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wdatanasc||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',8,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 163 a 167 005 N CBO
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wcbo||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',5,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 168 a 182 015 V Remuneracao sem 13
  waux = TRIM(CAST(CAST((prremsem13 * 100) AS INTEGER) AS VARCHAR(15)));
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 183 a 197 015 V Remuneracao 13
  waux = TRIM(CAST(CAST((prrem13 * 100) AS INTEGER) AS VARCHAR(15)));
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 198 a 199 002 N Classe contribuicao
  SELECT bdretorno FROM preenche_esquerda('',2,'0') INTO waux;
  wRetorno = wRetorno||waux;

  -- 200 a 201 002 N Ocorrencia
  IF (wocorencia = '0') THEN
     wocorencia = '  ';
  wsql = 'select bdretorno from preenche_esquerda('||''''||wocorencia||''''||',2,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 202 a 216 015 V Valor descontado do segurado
  waux = TRIM(CAST(CAST((prvalinss * 100) AS INTEGER) AS VARCHAR(15)));
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 217 a 231 015 V Remuneracao base de calculo da previdencia social
  waux = TRIM(CAST(CAST((prbaseinss * 100) AS INTEGER) AS VARCHAR(15)));
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 232 a 246 015 V Base calculo 13ºprevidencia social ref. competencia movimento
  waux = TRIM(CAST(CAST((prbaseinss13mes * 100) AS INTEGER) AS VARCHAR(15)));
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 247 a 261 015 V Base calculo 13ºprevidencia social ref. competencia 13
  waux = TRIM(CAST(CAST((prbaseinss13 * 100) AS INTEGER) AS VARCHAR(15)));
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',15,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 262 a 359 098 A Brancos
  SELECT bdretorno FROM preenche_direita('',98,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 360 a 360 001 A '*'
  wRetorno = wRetorno||'*';
  bdreg = SUBSTRING(wretorno FROM 1 FOR 360);
  bdordem = wordem||'30';
  SUSPEND;
END
^

/* Restore proc. body: SP_EXP_SEFIP_REG_32 */
ALTER PROCEDURE SP_EXP_SEFIP_REG_32(PRCODMOV VARCHAR(5),
PRDATAMOV VARCHAR(10),
PRINDFGTS VARCHAR(1))
 RETURNS(BDREG VARCHAR(360),
BDINC VARCHAR(32000),
BDORDEM VARCHAR(60))
 AS
DECLARE VARIABLE windfgts VARCHAR(1);
DECLARE VARIABLE wordem VARCHAR(60);
DECLARE VARIABLE wretorno VARCHAR(360);
DECLARE VARIABLE wcnpjtom VARCHAR(20);
DECLARE VARIABLE waux VARCHAR(360);
DECLARE VARIABLE wcnpjemp VARCHAR(18);
DECLARE VARIABLE wsql VARCHAR(32000);
DECLARE VARIABLE wemp INTEGER;
DECLARE VARIABLE wpis VARCHAR(20);
DECLARE VARIABLE wadm VARCHAR(10);
DECLARE VARIABLE wcategoria VARCHAR(10);
DECLARE VARIABLE wnome VARCHAR(70);
BEGIN
  /* Procedure Text */
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wemp;

  wsql =  'select emp.bdcnpjemp from tempresas emp'||
          ' where emp.bdcodemp = '||wemp;

  EXECUTE STATEMENT wsql INTO wcnpjemp;

  wordem = '1';
  -- 001 a 002 002 N '32' tipo registro
  wRetorno = '32';

  --  // 003 a 003 001 N Tipo inscricao
  wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjemp||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  --  // 004 a 017 014 N Inscricao da empresa
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjemp)||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  SELECT bdcnpj FROM sp_tomador_sefip
  INTO
    wcnpjtom;

  IF (wcnpjtom <> '') THEN
     BEGIN
       -- 018 a 018 001 N Tipo inscricao tomador
       wsql = 'select bdtipoins from sp_tipo_ins_sefip('||''''||wcnpjtom||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;
       wordem = wordem||waux;
    
       -- 019 a 032 014 N Insricrao tomador
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjtom)||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;
       wordem = wordem||waux;
     END
  ELSE
     BEGIN
       -- 018 a 018 001 N Tipo inscricao tomador
       waux = ' ';
       wRetorno = wRetorno||waux;
       waux = '0';
       wordem = wordem||waux;
    
       -- 019 a 032 014 N Insricrao tomador
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjtom)||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wcnpjtom)||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',14,'||''''||'0'||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wordem = wordem||waux;
     END

  SELECT bdpis,bdadm,bdcategoria,bdnome FROM sp_colaborador_sefip
  INTO
    wpis,wadm,wcategoria,wnome;

  -- 033 a 043 011 N Pis
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||TRIM(wpis)||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||TRIM(waux)||''''||',11,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  -- 044 a 051 008 D Data admissao DDMMAAAA
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wadm||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',8,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  waux = SUBSTRING(waux FROM 5)||SUBSTRING(waux FROM 3 FOR 2)||SUBSTRING(waux FROM 1 FOR 2);
  wordem = wordem||waux;

  -- 052 a 053 002 N Categoria
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wcategoria||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',2,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  wordem = wordem||waux;

  -- 054 a 123 070 A Nome empregado
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wnome||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',70,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 124 a 125 002 A Codigo movimentacao
  wsql = 'select bdretorno from preenche_direita('||''''||prcodmov||''''||',2,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  /*ordem antes da data*/
  bdordem = wordem||'32';

  -- 126 a 133 008 D Data movimentacao DDMMAAAA
  wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||prdatamov||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wsql = 'select bdretorno from preenche_esquerda('||''''||waux||''''||',8,'||''''||'0'||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;
  waux = SUBSTRING(waux FROM 5)||SUBSTRING(waux FROM 3 FOR 2)||SUBSTRING(waux FROM 1 FOR 2);
  wordem = wordem||waux;

  -- 134 a 134 001 A indicador recolhimento FGTS
  windfgts = prindfgts;
  IF ((windfgts IS NULL) OR (windfgts < '0') OR (prcodmov NOT IN ('I1', 'I2', 'I3', 'I4', 'I5', 'L')) ) THEN -- deve ser informado apenas para os seguintes codigos de movimentacao I1, I2, I3, I4 ou L
     windfgts = '';

  wsql = 'select bdretorno from preenche_direita('||''''||windfgts||''''||',1,'||''''||' '||''''||')';
  EXECUTE STATEMENT wsql INTO waux;
  wRetorno = wRetorno||waux;

  -- 135 a 359 225 A Brancos
  SELECT bdretorno FROM preenche_direita('',225,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 360 a 360 001 A '*'
  wRetorno = wRetorno||'*';
  bdreg = SUBSTRING(wretorno FROM 1 FOR 360);
  SUSPEND;
END
^

/* Restore proc. body: SP_EXP_SEFIP_REG_90 */
ALTER PROCEDURE SP_EXP_SEFIP_REG_90 RETURNS(BDREG VARCHAR(360),
BDORDEM VARCHAR(300))
 AS
DECLARE VARIABLE wretorno VARCHAR(360);
DECLARE VARIABLE waux VARCHAR(360);
BEGIN
  /* Procedure Text */
  -- 001 a 002 002 N '90' tipo registro
  wRetorno = '90';

  -- 003 a 053 051 A marca final arquivo preencher com '9'
  SELECT bdretorno FROM preenche_direita('',51,'9') INTO waux;
  wRetorno = wRetorno||waux;

  -- 054 a 359 306 A Brancos
  SELECT bdretorno FROM preenche_direita('',306,' ') INTO waux;
  wRetorno = wRetorno||waux;

  -- 360 a 360 001 A '*' fim do arquivo
  wRetorno = wRetorno||'*';
  bdReg = SUBSTRING(wretorno FROM 1 FOR 360);
  bdordem = '2';
  SUSPEND;
END
^

/* Restore proc. body: SP_EXP_SEFIP_RESC_SEGUINTE_COL */
CREATE OR ALTER PROCEDURE SP_EXP_SEFIP_RESC_SEGUINTE_COL (
    PRANOMES INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDDATA DATE,
    BDDATASTR VARCHAR(10),
    BDMOTIVO VARCHAR(5),
    BDINDFGTS INTEGER,
    BDCODMFG INTEGER,
    BDDATAFIM DATE)
AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WANOMES INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
BEGIN
  /* Procedure Text */
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wcodemp;
  IF (wcodemp IS NULL) THEN
     wcodemp = 0;

  SELECT rdb$get_context('USER_TRANSACTION', 'W_COLSEFIP') FROM rdb$database INTO wcodcol;
  IF (wcodcol IS NULL) THEN
     wcodcol = 0;

  IF (pranomes IS NULL) THEN
     wanomes = 99999;
  ELSE
     wanomes = pranomes;

  /* rescisao */
  wsql = 'SELECT res.bdcodemp,res.bdcodcol,res.bddatarescisao, (SELECT x.bdddmmaaaa FROM ddmmaaaa(res.bddatarescisao) x) Data,'||
         '       mot.bdcodsefmfg CodMovi, pres.bdgrrfpres, mot.BDCODMFG '||
         ' FROM vrh_emp_trescisao res, vrh_base_tprepresc pres, VRH_BASE_TMOTFGTS mot'||
         ' where (pres.bdcodpres = res.bdcodpres)'||
         ' and (pres.bdcodmfg = mot.bdcodmfg)'||
         ' and res.bdrefrescisao = '||wanomes||
         ' and UPPER(res.bdcalcfgtsmesant) = '''||'TRUE'||''' and COALESCE(pres.bdgrrfpres,0) <> 0 ';

   IF (wcodemp > 0) THEN
      wsql = wsql||' and res.bdcodemp = '||wcodemp;

   IF (wcodcol > 0) THEN
      wsql = wsql||' and res.bdcodcol = '||wcodcol;


  BDDATAFIM = NULL;

  FOR EXECUTE STATEMENT wsql INTO
      : bdcodemp,
      : bdcodcol,
      : bddata,
      : bddatastr,
      : bdmotivo,
      : bdindfgts,
      : bdcodmfg
    DO
  BEGIN
    SUSPEND;
  END
END
^

/* Restore proc. body: SP_FERIADO_EMPRESA */
ALTER PROCEDURE SP_FERIADO_EMPRESA(PRCODEMP INTEGER,
PRDATA DATE,
PRREFERENCIA INTEGER = 0,
PRSINDICATO INTEGER = 0)
 RETURNS(BDFERIADO VARCHAR(5))
 AS
DECLARE VARIABLE WREF INTEGER;
DECLARE VARIABLE WCODCID INTEGER;
DECLARE VARIABLE WCODUF INTEGER;
DECLARE VARIABLE WCIDFER INTEGER;
DECLARE VARIABLE WUFFER INTEGER;
DECLARE VARIABLE WSINDFER INTEGER;
DECLARE VARIABLE WRETURN VARCHAR(5);
BEGIN
  IF ((prreferencia IS NULL) OR (prreferencia = 0)) THEN
     wref = CAST((SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
  ELSE
     wref = prreferencia;

  wcodcid = NULL;
  wcoduf  = NULL;
  EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
  SELECT EMP.BDCODCID, CID.BDCODUF FROM VW_TEMPRESAS_REF EMP LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID) WHERE EMP.BDCODEMP = :prcodemp INTO :wcodcid,:wcoduf;
  wreturn = 'FALSE';
  FOR SELECT BDCODSINTRAB,BDCODCID,BDCODUF FROM sp_tferiados(:wref, :wref) WHERE BDDATAFER = :prdata INTO :wsindfer,:wcidfer,wuffer DO
    BEGIN
      IF (wsindfer IS NULL AND wcidfer IS NULL AND wuffer IS NULL) THEN  -- Feriado nacional
         BEGIN
           wreturn = 'TRUE';
           LEAVE;
         END
      ELSE
      IF (wcidfer IS NOT NULL AND wcodcid IS NOT NULL AND wcidfer = wcodcid) THEN  -- Feriado municipal
         BEGIN
           wreturn = 'TRUE';
           LEAVE;
         END
      ELSE
      IF (wcidfer IS NULL AND wcoduf IS NOT NULL AND wuffer = wcoduf) THEN  -- Feriado estadual
         BEGIN
           wreturn = 'TRUE';
           LEAVE;
         END
      ELSE
      IF (wsindfer IS NOT NULL AND prsindicato IS NOT NULL AND wsindfer = prsindicato) THEN  -- Feriado sindical
         BEGIN
           wreturn = 'TRUE';
           LEAVE;
         END
    END

  bdferiado = wreturn;
  SUSPEND;
END
^

/* Restore proc. body: SP_FERIAS_PROVISAO */
create or alter procedure SP_FERIAS_PROVISAO (
    PRCODEMP varchar(25000),
    PRCODCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDREFFE integer,
    BDCODVER integer,
    BDREFVRFE numeric(15,6),
    BDVALVRFE numeric(15,6),
    BDREFAUXVRFE numeric(15,6),
    BDCLAVER varchar(20),
    BDTIPOCODVER integer,
    BDINSSVER integer,
    BDFGTSVER integer,
    BDIRVER integer,
    BDTIPOREFVER integer,
    BDBASESFVER integer)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(25000);
BEGIN
  /* Não se esqueça de setar a competência */

  wsql = 'select '||
            'VFER.BDCODEMP, '||
            'VFER.BDCODCOL, '||
            'VFER.BDINIPERAQUISFE, '||
            'VFER.BDCODFE, '||
            'VFERIAS.BDREFFE, '||
            'VFERIAS.BDCODVER, '||
            'VFERIAS.BDREFVRFE, '||
            'VFERIAS.BDVALVRFE, '||
            'VFERIAS.BDREFAUXVRFE, '||
            'VERBAS.BDCLAVER, '||
            'VERBAS.BDTIPOCODVER, '||
            'VERBAS.BDINSSVER, '||
            'VERBAS.BDFGTSVER, '||
            'VERBAS.BDIRVER, '||
            'VERBAS.BDTIPOREFVER, '||
            'VERBAS.BDBASESFVER ';

  wsql = wsql||'from VRH_EMP_TFERIAS VFER '||
               'left outer join VRHF_EMP_TVERBARFE VFERIAS on (VFERIAS.BDCODEMP = VFER.BDCODEMP and VFERIAS.BDCODCOL = VFER.BDCODCOL and '||
                  'VFERIAS.BDINIPERAQUISFE = VFER.BDINIPERAQUISFE and VFERIAS.BDCODFE = VFER.BDCODFE) '||
               'left outer join VW_TVERBAS_REF VERBAS on (VFERIAS.BDCODVER = VERBAS.BDCODVER) ';

  wwhere = 'where (VFERIAS.BDREFFE <= '||:prref||' or ((VFERIAS.BDREFFE is null) and (VFER.BDREFFIMFE <= '||:prref||'))) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||' and '||prcodcol;

  FOR EXECUTE STATEMENT wsql||wwhere
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDINIPERAQUISFE,
    :BDCODFE,
    :BDREFFE,
    :BDCODVER,
    :BDREFVRFE,
    :BDVALVRFE,
    :BDREFAUXVRFE,
    :BDCLAVER,
    :BDTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER
  DO
  SUSPEND;
END^

/* Restore proc. body: SP_FERIAS_PROVISAO_REF */
CREATE OR ALTER procedure SP_FERIAS_PROVISAO_REF (
    PRCODEMP varchar(25000),
    PRCODCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDREFFE integer,
    BDBASEINSSRFE numeric(15,6),
    BDBASEPISRFE numeric(15,6),
    BDBASEFGTSRFE numeric(15,6),
    BDVALORFGTSRFE numeric(15,6),
    BDBRATAPORFE numeric(15,6),
    BDDIASFERFE numeric(18,6),
    BDDIASABOFE numeric(18,6),
    BDREFFIMFE integer,
    BDINIPERGOZOFE date,
    BDFIMPERGOZOFE date)
as
declare variable WSQL varchar(32700);
declare variable WSQLAUX varchar(32700);
declare variable WWHERE varchar(25000);
declare variable WVALVERBA numeric(15,2);
declare variable WINCIDVERBA integer;
declare variable WTIPOVERBA integer;
BEGIN
  wsql = 'select '||
            'FER.BDCODEMP, '||
            'FER.BDCODCOL, '||
            'FER.BDINIPERAQUISFE, '||
            'FER.BDCODFE, '||
            'FERR.BDREFFE, '||
            'FERR.BDBASEINSSRFE, '||
            'FERR.BDBASEPISRFE, '||
            'FERR.BDBASEFGTSRFE, '||
            'FERR.BDVALORFGTSRFE, '||
            'FERR.BDBRATAPORFE, '||
            'case '||
              'when FERR.BDREFFE is null then COALESCE(FER.BDQTDGOZOFE, 0) '||
              'else FERR.BDDIASFERFE '||
            'end, '||
            'case '||
              'when FERR.BDREFFE is null then COALESCE(FER.BDQTDABONOFE, 0) '||
              'else FERR.BDDIASABOFE '||
            'end,FER.BDREFFIMFE,'||
            'FER.BDINIPERGOZOFE, '||
            'FER.BDFIMPERGOZOFE ';

  wsql = wsql||'from VRH_EMP_TFERIAS FER '||
         'left outer join VRH_EMP_TFERIASREF FERR on (FER.BDCODEMP = FERR.BDCODEMP and FER.BDCODCOL = FERR.BDCODCOL and FER.BDINIPERAQUISFE = FERR.BDINIPERAQUISFE and '||
             'FER.BDCODFE = FERR.BDCODFE) ';

  wwhere = 'where (FERR.BDREFFE <= '||:prref||' or ((FERR.BDREFFE is null) and ((FER.BDREFFIMFE <= '||:prref||') or (FER.BDREFINIFE <= '||:prref||')))) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||' and '||prcodcol;

  FOR EXECUTE STATEMENT wsql||wwhere
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDINIPERAQUISFE,
    :BDCODFE,
    :BDREFFE,
    :BDBASEINSSRFE,
    :BDBASEPISRFE,
    :BDBASEFGTSRFE,
    :BDVALORFGTSRFE,
    :BDBRATAPORFE,
    :BDDIASFERFE,
    :BDDIASABOFE,
    :BDREFFIMFE,
    :bdinipergozofe,
    :bdfimpergozofe
  DO
  BEGIN
    BDBASEINSSRFE = 0;

    wSQLAUX = 'select FERIAS.BDVALVRFE, VERBAS.BDINSSVER, VERBAS.BDTIPOCODVER '||
              'from VRHF_EMP_TVERBARFE FERIAS '||
              'join VW_TVERBAS_REF VERBAS on VERBAS.BDCODVER = FERIAS.BDCODVER '||
              'where FERIAS.BDCODEMP = '||BDCODEMP||
                    ' AND FERIAS.BDCODCOL = '||BDCODCOL||
                    ' AND FERIAS.BDINIPERAQUISFE = '''||BDINIPERAQUISFE||''''||
                    ' AND FERIAS.BDCODFE = '||BDCODFE||
                    ' AND FERIAS.BDREFFE = '||COALESCE(BDREFFE, 0);

    FOR EXECUTE STATEMENT wSQLAUX
    INTO WVALVERBA, WINCIDVERBA, WTIPOVERBA
    DO
    BEGIN
      IF (WINCIDVERBA = 2) THEN
        BEGIN
          if (WTIPOVERBA = 0) then
            BDBASEINSSRFE = BDBASEINSSRFE + WVALVERBA;
          ELSE if (WTIPOVERBA = 1) then
            BDBASEINSSRFE = BDBASEINSSRFE - WVALVERBA;
        END
    END

    SUSPEND;
  END
END^

/* Restore proc. body: SP_FICHA_REGISTROS_CARGOS */
CREATE OR ALTER procedure SP_FICHA_REGISTROS_CARGOS (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRULTDIA date,
    PRRETORNAVAZIO smallint = 0,
    PRFUCDET smallint = 0,
    PRHISTTRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATACOL date,
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDDESCTFUC varchar(100),
    BDCODCBO integer,
    BDNOMCOL varchar(70),
    BDCODMAS integer,
    BDDESCMAS varchar(50),
    BDCODEMPORIG integer,
    BDCODCOLORIG integer)
as
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WDATACOL date;
declare variable WCODPLAFUC integer;
declare variable WCODTFUC integer;
declare variable WDESCTFUC varchar(40);
declare variable WCODCBO integer;
declare variable WSQL varchar(30000);
declare variable WCONT integer;
declare variable WWHERE varchar(20000);
declare variable WCODMAS integer;
declare variable WDESCMAS varchar(50);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WDESCFUNCDET varchar(100);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
declare variable WSQLAUX varchar(2000);
declare variable WSQL2 varchar(2000);
declare variable WSQL3 varchar(2000);
BEGIN
  IF (PRRETORNAVAZIO = 1) THEN
     BEGIN
       WSQL = 'SELECT T.BDCODEMP, T.BDCODCOL FROM VW_VRH_EMP_TCOLCON_CAD T ';

       wwhere = '';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          BEGIN
            wwhere = prcodemp;
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';

            wwhere = wwhere||prcodcol;
          END

       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;

       WSQL = WSQL || wwhere || ' order by T.BDCODEMP, T.BDCODCOL';

       FOR EXECUTE STATEMENT wsql INTO :WCODEMP, :WCODCOL DO
         BEGIN
           if (PRHISTTRANSF = 1) then
              BEGIN
                WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = ' || WCODEMP || ' and BDCODCOLDEST = ' || WCODCOL;
                FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
                  BEGIN
                    IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
                      BEGIN
                    WSQL3 = 'SELECT * FROM SP_FICHA_REGISTROS_CARGOS(''T.BDCODEMP = '||wcodemporig||''', ''T.BDCODCOL = ' || wcodcolorig || ''',''' || prultdia || ''',' || prretornavazio || ',' || prfucdet || ',' || prhisttransf || ')';
                    FOR EXECUTE STATEMENT wsql3 INTO
                      :BDCODEMP,
                      :BDCODCOL,
                      :BDDATACOL,
                      :BDCODPLAFUC,
                      :BDCODTFUC,
                      :BDDESCTFUC,
                      :BDCODCBO,
                      :BDNOMCOL,
                      :BDCODMAS,
                      :BDDESCMAS,
                      :BDCODEMPORIG,
                      :BDCODCOLORIG DO
                          BEGIN
                        BDCODEMP = WCODEMP;
                        BDCODCOL = WCODCOL;
                        SUSPEND;
                  END
              END
                  END
              END

           WSQLAUX = 'SELECT T.BDCODEMP, T.BDCODCOL, T.BDDATACOL, T.BDCODPLAFUC, T.BDCODTFUC , COLFUNC.bddesctfuc , COLFUNC.bdcodcbo , X.BDCODMAS, Y.BDDESCMAS, COLFUNC.BDDESCFUNCDET ';
           WSQLAUX = WSQLAUX || 'FROM VRH_EMP_TCOL_VINCDIA T join VRH_EMP_TCOLCON_CALCDIA X on (X.BDCODEMP = T.BDCODEMP and X.BDCODCOL = T.BDCODCOL and X.BDDATACOL = T.BDDATACOL) '||
             'left outer join VRH_BASE_TMOTAUMSAL Y on (Y.BDCODMAS = X.BDCODMAS) '||
             'left outer join VRH_FUNCOES_TFUC colfunc on (T.BDCODPLAFUC = colfunc.BDCODPLAFUC and T.BDCODTFUC = colfunc.BDCODTFUC) ' ||
             'WHERE  (T.BDCODEMP = ' || WCODEMP || ') and ' ||
             '       (T.BDCODCOL = ' || WCODCOL || ')';

           WSQLAUX = WSQLAUX || ' order by T.BDCODEMP, T.BDCODCOL, T.BDDATACOL, T.BDCODTFUC';
     
           wempatu = 0;
           wcolatu = 0;

           WCONT = 0;
           FOR EXECUTE STATEMENT WSQLAUX INTO
             :WCODEMP,
             :WCODCOL,
             :WDATACOL,
             :WCODPLAFUC,
             :WCODTFUC,
             :Wdesctfuc,
             :Wcodcbo,
             :wcodmas,
             :wdescmas,
             :wdescfuncdet
           DO
           BEGIN
             IF (wcont = 0) THEN
                BEGIN
                 BDCODEMP = WCODEMP;
                 BDCODCOL = WCODCOL;
                 BDDATACOL = WDATACOL;
                 BDCODPLAFUC = WCODPLAFUC;
                 BDCODTFUC = WCODTFUC;

                 if (coalesce(prfucdet, 0) = 1) then
                    begin
                      if (TRIM(coalesce(wdescfuncdet, '')) <> '') then
                         BDDESCTFUC = SUBSTRING(wdescfuncdet from 1 for 100);
                      else
                         BDDESCTFUC = wdesctfuc;
                    end
                 else
                   BDdesctfuc = Wdesctfuc;

                 BDcodcbo = Wcodcbo;
                 BDCODMAS = wcodmas;

                 IF (wdescmas IS NULL) THEN
                    wdescmas = 'Admissão';

                 BDDESCMAS = wdescmas;

                 if ((wempatu <> wcodemp) or (wcolatu <> wcodcol)) then
                    begin
                      wwhere = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||
                               ' and BDREFCOL <= '||SUBSTRING(CAST(prultdia AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prultdia AS VARCHAR(10)) FROM 6 FOR 2)||
                               ' order by BDREFCOL DESC';
                      execute statement wwhere into :BDNOMCOL;

                      wempatu = wcodemp;
                      wcolatu = wcodcol;
                    end

                 BDCODEMPORIG = WCODEMP;
                 BDCODCOLORIG = WCODCOL;

                 SUSPEND;
                END
             ELSE
                BEGIN
                  IF ((BDCODEMP <> WCODEMP) OR (BDCODCOL <> WCODCOL) OR ((BDCODTFUC <> wCODTFUC) OR ((BDCODTFUC IS NULL) AND (wCODTFUC IS NOT NULL)) OR ((BDCODTFUC IS NOT NULL) AND (wCODTFUC IS NULL)))) THEN
                     BEGIN
                       IF (BDCODCOL <> WCODCOL AND wdescmas IS NULL) THEN
                          wdescmas = 'Admissão';

                       BDCODEMP = WCODEMP;
                       BDCODCOL = WCODCOL;
                       BDDATACOL = WDATACOL;
                       BDCODPLAFUC = WCODPLAFUC;
                       BDCODTFUC = WCODTFUC;

                       if (coalesce(prfucdet, 0) = 1) then
                          begin
                            if (TRIM(coalesce(wdescfuncdet, '')) <> '') then
                               BDDESCTFUC = SUBSTRING(wdescfuncdet from 1 for 100);
                            else
                               BDDESCTFUC = wdesctfuc;
                          end
                       else
                         BDdesctfuc = Wdesctfuc;

                       BDcodcbo = Wcodcbo;
                       BDCODMAS = wcodmas;
                       BDDESCMAS = wdescmas;

                       if ((wempatu <> wcodemp) or (wcolatu <> wcodcol)) then
                          begin
                            wwhere = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||
                                     ' and BDREFCOL <= '||SUBSTRING(CAST(prultdia AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prultdia AS VARCHAR(10)) FROM 6 FOR 2)||
                                     ' order by BDREFCOL DESC';
                            execute statement wwhere into :BDNOMCOL;
        
                            wempatu = wcodemp;
                            wcolatu = wcodcol;
                          end

                       BDCODEMPORIG = WCODEMP;
                       BDCODCOLORIG = WCODCOL;

                       SUSPEND;
                     END
                END
     
             WCONT = 1;
           END
         END
     END
   ELSE
     SUSPEND;
END^

/* Restore proc. body: SP_FICHA_REGISTROS_HORARIOS */
CREATE OR ALTER procedure SP_FICHA_REGISTROS_HORARIOS (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRULTDIA date,
    PRRETORNAVAZIO integer,
    PRHISTTRANSF integer = 0,
    PRSOMENTEALTERACAO integer = 0) /*158331 - André Cursino - 02/06/2022*/
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATACOL date,
    BDCODPQUA integer,
    BDCODQH integer,
    BDDESCQH DM_BDDESCQH,
    BDNOMCOL DM_BDNOMCOL,
    BDCODMAS integer,
    BDDESCMAS varchar(50),
    BDCODEMPORIG integer,
    BDCODCOLORIG integer)
as
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WDATACOL date;
declare variable WCODPQUA integer;
declare variable WCODQH integer;
declare variable WDESCQH DM_BDDESCQH;
declare variable WSQL varchar(20000);
declare variable WCONT integer;
declare variable WCODMAS integer;
declare variable WDESCMAS varchar(50);
declare variable WWHERE varchar(20000);
declare variable WTROCAPQUA integer;
declare variable WTROCAQH integer;
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WSQL2 varchar(2000);
declare variable WSQL3 varchar(2000);
declare variable WSQLAUX varchar(2000);
declare variable WCODEMPAUX integer;
declare variable WCODCOLAUX integer;
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
declare variable WDATAADMCOL date;    /*158331 - André Cursino - 02/06/2022*/
BEGIN
  IF (PRRETORNAVAZIO = 1) THEN
     BEGIN
       WSQL = 'SELECT T.BDCODEMP, T.BDCODCOL FROM VW_VRH_EMP_TCOLCON_CAD T ';

       wwhere = '';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          BEGIN
            wwhere = prcodemp;
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';

            wwhere = wwhere||prcodcol;
          END

       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;

       WSQL = WSQL || wwhere || ' order by T.BDCODEMP, T.BDCODCOL';

       FOR EXECUTE STATEMENT wsql INTO :WCODEMP, :WCODCOL DO
         BEGIN
           if (PRHISTTRANSF = 1) then
              BEGIN
                WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = ' || WCODEMP || ' and BDCODCOLDEST = ' || WCODCOL;
                FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
                  BEGIN
                    IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
                      BEGIN
                    WSQL3 = 'SELECT * FROM SP_FICHA_REGISTROS_HORARIOS(''T.BDCODEMP = '||wcodemporig||''', ''T.BDCODCOL = ' || wcodcolorig || ''',''' || prultdia || ''',' || prretornavazio || ',' || prhisttransf || ')';
                    FOR EXECUTE STATEMENT wsql3 INTO
                      :BDCODEMP,
                      :BDCODCOL,
                      :BDDATACOL,
                      :BDCODPQUA,
                      :BDCODQH,
                      :BDDESCQH,
                      :BDNOMCOL,
                      :BDCODMAS,
                      :BDDESCMAS,
                      :BDCODEMPORIG,
                      :BDCODCOLORIG DO
                          BEGIN
                        BDCODEMP = WCODEMP;
                        BDCODCOL = WCODCOL;
                        SUSPEND;
                  END
              END
                  END
              END

           WSQLAUX = 'SELECT T.BDCODEMP, T.BDCODCOL, T.BDDATACOL, T.BDCODPQUA, T.BDCODQH, QH.bddescqh, X.BDCODMAS, Y.BDDESCMAS ';
           WSQLAUX = WSQLAUX || 'FROM VRH_EMP_TCOL_VINCDIA T join VRH_EMP_TCOLCON_CALCDIA X on (X.BDCODEMP = T.BDCODEMP and X.BDCODCOL = T.BDCODCOL and X.BDDATACOL = T.BDDATACOL) '||
             'left outer join VRH_BASE_TMOTAUMSAL Y on (Y.BDCODMAS = X.BDCODMAS) '||
             'left outer join VRH_BASE_TQH QH on (T.BDCODPQUA = QH.BDCODPQUA and T.BDCODQH = QH.BDCODQH) ' ||
             'WHERE  (T.BDCODEMP = ' || WCODEMP || ') and ' ||
             '       (T.BDCODCOL = ' || WCODCOL || ')';

           WSQLAUX = WSQLAUX || ' order by T.BDCODEMP, T.BDCODCOL, T.BDDATACOL, T.BDCODPQUA, T.BDCODQH';

           wempatu = 0;
           wcolatu = 0;

           WCONT = 0;
           FOR EXECUTE STATEMENT WSQLAUX INTO
             :WCODEMPAUX,
             :WCODCOLAUX,
             :WDATACOL,
             :WCODPQUA,
             :WCODQH,
             :Wdescqh,
             :wcodmas,
             :wdescmas
           DO
           BEGIN
             IF (wcont = 0) THEN
                BEGIN
                 BDCODEMP = WCODEMPAUX;
                 BDCODCOL = WCODCOLAUX;
                 BDDATACOL = WDATACOL;
                 BDCODPQUA = WCODPQUA;
                 BDCODQH = WCODQH;
                 BDdescqh = Wdescqh;
                 BDCODMAS = wcodmas;
                 BDDESCMAS = wdescmas;

                 if ((wempatu <> wcodempaux) or (wcolatu <> wcodcolaux)) then
                    begin
                      wwhere = 'select first 1 CAD.BDNOMCOL, COL.BDDATAADMCOL ' ||
                                       'from VRH_EMP_TCOLCON_CAD CAD ' ||
                                       'JOIN VRH_EMP_TCOLCON COL ON (CAD.BDCODEMP = COL.BDCODEMP ' ||        /*158331 - André Cursino - 02/06/2022 - Adicionado join com VRH_EMP_TCOLCON para pegar data de admissão*/
                                                                    'AND CAD.BDCODCOL = COL.BDCODCOL) ' ||
                                      'where CAD.BDCODEMP = '||wcodemp||
                                       ' and CAD.BDCODCOL = '||wcodcol||
                                       ' and CAD.BDREFCOL <= '||SUBSTRING(CAST(prultdia AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prultdia AS VARCHAR(10)) FROM 6 FOR 2)||
                               ' order by BDREFCOL DESC';
                      execute statement wwhere into :BDNOMCOL, :wDataAdmCol;

                      wempatu = wcodempaux;
                      wcolatu = wcodcolaux;
                    end

                 BDCODEMPORIG = WCODEMP;
                 BDCODCOLORIG = WCODCOL;

                 if (((prsomentealteracao = 1) and (wDataAdmCol <> BDDATACOL))
                      or ((prsomentealteracao = 0) or (prsomentealteracao is null))) then  /*158331 - André Cursino - 02/06/2022 - verifica se está usando o parametro de somente alteração de horários*/
                 SUSPEND;
                END
             ELSE
                BEGIN
                  WTROCAPQUA = 0;
/*                  if (((wcodpqua is null) and (bdcodpqua is not null)) or
                     ((bdcodpqua is null) and (wcodpqua is not null)) or
                     (BDCODPQUA <> WCODPQUA)) then
                     WTROCAPQUA = 1;*/

                  wtrocaqh = 0;
                  IF (((wCODQH IS NULL) AND (BDCODQH IS NOT NULL)) OR
                     ((BDCODQH IS NULL) AND (wCODQH IS NOT NULL)) OR
                     (BDCODQH <> wCODQH)) THEN
                     wtrocaqh = 1;

                  IF ((BDCODEMP <> WCODEMP) OR (BDCODCOL <> WCODCOL) OR (WTROCAPQUA = 1) OR (wtrocaqh = 1)) THEN
                     BEGIN
                       BDCODEMP = WCODEMP;
                       BDCODCOL = WCODCOL;
                       BDDATACOL = WDATACOL;
                       BDCODPQUA = WCODPQUA;
                       BDCODQH = WCODQH;
                       BDdescqh = Wdescqh;
                       BDCODMAS = wcodmas;
                       BDDESCMAS = wdescmas;

                       if ((wempatu <> wcodemp) or (wcolatu <> wcolatu)) then
                          begin
                            wwhere = 'select first 1 CAD.BDNOMCOL, COL.BDDATAADMCOL ' ||
                                       'from VRH_EMP_TCOLCON_CAD CAD' ||
                                       'JOIN VRH_EMP_TCOLCON COL ON (CAD.BDCODEMP = COL.BDCODEMP ' ||          /*158331 - André Cursino - 02/06/2022 - Adicionado join com VRH_EMP_TCOLCON para pegar data de admissão*/
                                                                    'AND CAD.BDCODCOL = COL.BDCODCOL) ' ||
                                      'where CAD.BDCODEMP = '||wcodemp||
                                       ' and CAD.BDCODCOL = '||wcodcol||
                                       ' and CAD.BDREFCOL <= '||SUBSTRING(CAST(prultdia AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prultdia AS VARCHAR(10)) FROM 6 FOR 2)||
                                     ' order by BDREFCOL DESC';
                            execute statement wwhere into :BDNOMCOL, :wDataAdmCol;
        
                            wempatu = wcodemp;
                            wcolatu = wcolatu;
                          end

                       BDCODEMPORIG = WCODEMP;
                       BDCODCOLORIG = WCODCOL;

                       if (((prsomentealteracao = 1) and (wDataAdmCol <> BDDATACOL))
                           or ((prsomentealteracao = 0) or (prsomentealteracao is null)))   then   /*158331 - André Cursino - 02/06/2022 - verifica se está usando o parametro de somente alteração de horários*/
                       SUSPEND;
                     END
                END
     
             WCONT = 1;
          END
       END
     END
   ELSE
     SUSPEND;
END^


/* Restore proc. body: SP_FICHA_REGISTROS_SALARIOS */
create or alter procedure SP_FICHA_REGISTROS_SALARIOS (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRREF integer,
    PRRETORNAVAZIO integer,
    PRTRAZERSALINI integer = 0,
    PRHISTTRANSF integer = 0,
    PRDUPLICADO integer = 0,
    PRSALARIOFUNCAO integer = 0,  /*Solicitação 162323 - André Cursino - 09/06/2022*/
    prSomenteHistAum integer = 0) /*172795 - André Cursino - 11/01/2023*/
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDDATAADMCOL date,
    BDSALINICOL numeric(18,6),
    BDDATACOL date,
    BDSALBASECOL numeric(18,6),
    BDCODMAS integer,
    BDDESCMAS varchar(50),
    BDCODTFUC integer,
    BDCODSHE integer,
    BDDESCSHE varchar(50),
    BDSALBASEANT numeric(18,6),
    BDDATAEFEITO date,
    BDSALREDUZIDO DM_BOOLEAN,
    BDCODEMPORIG integer,
    BDCODCOLORIG integer)
as
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WDATAADMCOL date;
declare variable WSALINICOL numeric(18,6);
declare variable WDATACOL date;
declare variable WSALBASECOL numeric(18,6);
declare variable WCODMAS integer;
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(30000);
declare variable WCONT integer;
declare variable WDESCMAS varchar(50);
declare variable WCODTFUC integer;
declare variable WCODSHE integer;
declare variable WTIPOCOL integer;
declare variable WDESCSHE varchar(50);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WDATAEFEITO date;
declare variable WWHERE varchar(500);
declare variable WSQL3 varchar(2000);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
declare variable WCODTFUCANT integer;
declare variable WI integer;
BEGIN
  BDSALBASEANT = 0;

  IF (PRRETORNAVAZIO = 1) THEN
     BEGIN
       EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRREF);
       WSQL = ' select BDCODEMP, BDCODCOL, BDTIPOCOL from VW_VRHF_EMP_TCOL_CALC COL ';

       -- 14269 - Marcelo B. M. - 23/06/2016: Ajustado para aceitar mais de uma empresa e/ou colaborador
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
             WSQL = WSQL || ' where '||prcodemp;
             IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
                WSQL = WSQL || ' and '||PRCODCOL;
          END
       ELSE
          BEGIN
             IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
                WSQL = WSQL || ' where '||PRCODCOL;
          END

       FOR EXECUTE STATEMENT wsql INTO
         WCODEMP,
         WCODCOL,
         WTIPOCOL
       DO
       BEGIN
         if (PRHISTTRANSF = 1) then
            BEGIN
              WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = ' || WCODEMP || ' and BDCODCOLDEST = ' || WCODCOL;
              FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
                BEGIN
                  IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
                    BEGIN
                  WSQL3 = 'SELECT * FROM SP_FICHA_REGISTROS_SALARIOS(''COL.BDCODEMP = '||wcodemporig||''', ''COL.BDCODCOL = ' || wcodcolorig || ''',' || PRREF || ',' || PRRETORNAVAZIO || ',' || PRTRAZERSALINI || ',' || PRHISTTRANSF || ')';
                  FOR EXECUTE STATEMENT wsql3 INTO
                    :BDCODEMP,
                    :BDCODCOL,
                    :BDNOMCOL,
                    :BDDATAADMCOL,
                    :BDSALINICOL,
                    :BDDATACOL,
                    :BDSALBASECOL,
                    :BDCODMAS,
                    :BDDESCMAS,
                    :BDCODTFUC,
                    :BDCODSHE,
                    :BDDESCSHE,
                    :BDSALBASEANT,
                    :BDDATAEFEITO,
                    :BDSALREDUZIDO,
                    :BDCODEMPORIG,
                    :BDCODCOLORIG DO
                        BEGIN
                      BDCODEMP = WCODEMP;
                      BDCODCOL = WCODCOL;
                      SUSPEND;
                END
            END
                END
            END

         --Sol. 17643 - Bruno L. R. - 01/08/2017
         IF (WTIPOCOL = 4) THEN
            BEGIN
              if (prSomenteHistAum = 0) then
                begin
              WSQL2 = 'select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, SHE.BDSALSHE bdsalinicol, SHE.BDDATASHE BDDATACOL, SHE.BDSALSHE BDSALBASECOL, SHE.bdcodshe bdcodmas, '||
                      'MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, 0 bdcodshe,  CAST(null as varchar(50)) BDDESCSHE, SHE.BDDATAEFEITOHE, ''FALSE'' BDREDUZIDO  ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_SHE SHE on (SHE.bdcodemp = COL.bdcodemp and SHE.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = SHE.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VW_VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = SHE.bdcodemp and VINCDIA.bdcodcol = SHE.bdcodcol and VINCDIA.BDDATACOL = SHE.BDDATASHE) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;
                  WSQL2 = WSQL2 || ' union ';
                end

              WSQL2 = WSQL2 || ' select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, ADM.bdsalinicol, HIST.BDDATAHAUMHE BDDATACOL, '||
                      ' HIST.BDSALBASEHAUMHE,  HIST.bdcodshe bdcodmas, MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, HIST.BDCODSHE, BSHE.BDDESCSHE, HIST.BDDATAEFEITOHAUMHE, ''FALSE'' BDREDUZIDO ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_THIST_AUMHE HIST on (HIST.bdcodemp = COL.bdcodemp and HIST.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = hist.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VW_VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TSALHORESP BSHE on (BSHE.bdcodemp = HIST.bdcodemp and BSHE.bdcodshe = HIST.bdcodshe) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = col.bdcodemp and VINCDIA.bdcodcol = col.bdcodcol and VINCDIA.BDDATACOL = HIST.BDDATAHAUMHE) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;
              WSQL2 = WSQL2 || ' order by 1, 2, 6, 12 '; /*order by bdcodemp, bdcodcol, bdsalbasecol, bddataefeitohaumhe
                                                          Solicitação: 155817 - André Cursino - 22/11/2021 */

              /*
              WCAMPOSSHE = ' HIST.BDSALBASEANTHAUMHE bdsalinicol, HIST.BDDATAHAUMHE BDDATACOL, HIST.BDSALBASEHAUMHE BDSALBASECOL, HIST.bdcodmas, MAUMSAL.BDDESCMAS,'||
                           ' VINCDIA.BDCODTFUC, HIST.BDCODSHE, BSHE.BDDESCSHE ';
              WJOINSHE = ' left outer join VRH_EMP_THIST_AUMHE HIST on (HIST.bdcodemp = COL.bdcodemp and HIST.bdcodcol = COL.bdcodcol) '||
                         ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = HIST.bdcodmas) '||
                         ' left outer join VRH_BASE_TSALHORESP BSHE on (BSHE.bdcodemp = HIST.bdcodemp and BSHE.bdcodshe = HIST.bdcodshe) ';
              WCAMPODATA = 'HIST.BDDATAHAUMHE';      */
            END
          ELSE
            BEGIN
              wSQL2 = '';
                --158776 Valmor H Junior 01/02/2022
              wSQL2 = 'Select * from (';
              if (prSomenteHistAum = 0) then
                begin
              WSQL2 =  wSQL2 ||'select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, ADM.bdsalinicol, CALC.BDDATACOL, CALC.BDSALBASECOL, CALC.bdcodmas, '||
                      'MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, 0 bdcodshe, CAST(null as varchar(50)) BDDESCSHE, CALC.BDDATAEFEITO, ''FALSE'' BDREDUZIDO ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOLCON_CALCDIA CALC on (CALC.bdcodemp = COL.bdcodemp and CALC.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = CALC.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VW_VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = CALC.bdcodemp and VINCDIA.bdcodcol = CALC.bdcodcol and VINCDIA.BDDATACOL = CALC.BDDATACOL) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;
                  WSQL2 = WSQL2 || ' union ';
                end

              WSQL2 = WSQL2 || ' select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, ADM.bdsalinicol, HIST.BDDATAHAUM BDDATACOL, HIST.BDSALBASEHAUM bdsalbasecol, '||
                      ' HIST.bdcodmas, MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, 0 bdcodshe, CAST(null as varchar(50)) BDDESCSHE, HIST.BDDATAEFEITOHAUM, ''FALSE'' BDREDUZIDO ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_THIST_AUM HIST on (HIST.bdcodemp = COL.bdcodemp and HIST.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = hist.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VW_VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
            /*WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = COL.bdcodemp and VINCDIA.bdcodcol = COL.bdcodcol and VINCDIA.BDDATACOL = HIST.BDDATAHAUM) ';
     Sol.144936 LuizCovre 19/11/2021*/
     WSQL2 = WSQL2 || ' join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = COL.bdcodemp and VINCDIA.bdcodcol = COL.bdcodcol and VINCDIA.BDDATACOL = HIST.BDDATAHAUM) ';
     WSQL2 = WSQL2 || ' where COL.bdcodemp = ' || WCODEMP || ' and COL.bdcodcol = ' || WCODCOL;

                  WSQL2 = WSQL2 || ') a order by bdcodemp,bdcodcol,bdsalbasecol,bdcodmas desc';
            END
         --Sol. 17643 - Bruno L. R. - 01/08/2017

           wempatu = 0;
           wcolatu = 0;

           WCONT = 0;
           FOR EXECUTE STATEMENT WSQL2 INTO
             WCODEMP,
             WCODCOL,
             WDATAADMCOL,
             WSALINICOL,
             WDATACOL,
             WSALBASECOL,
             WCODMAS,
             WDESCMAS,
             WCODTFUC,
             WCODSHE,
             WDESCSHE,
             WDATAEFEITO,
             :BDSALREDUZIDO
           DO
           BEGIN
             IF (wcont = 0) THEN
                BEGIN
                   BDCODEMP = WCODEMP;
                   BDCODCOL = WCODCOL;
                   BDDATAADMCOL = WDATAADMCOL;
                   IF (WSALINICOL IS NULL) THEN
                      BDSALINICOL = 0;
                   ELSE
                      BDSALINICOL = WSALINICOL;
                   BDDATACOL = WDATACOL;
                   BDSALBASEANT = NULL;   --Sol. 17798 - Bruno L. R. - 05/04/2017
                   BDSALBASECOL = WSALBASECOL;
                   BDDATAEFEITO = WDATAEFEITO;

                   IF (((WDATACOL = WDATAADMCOL) OR (BDSALBASEANT IS NULL)) and (prSomenteHistAum = 0)) THEN   --Sol. 18509 - Bruno L. R. - 26/07/2017
                      BEGIN
                        BDCODMAS = 0;
                        BDDESCMAS = 'Admissão';

                        --IF ((BDSALINICOL <= BDSALBASECOL) OR (BDSALBASECOL IS NULL)) THEN
                          -- BDSALBASECOL = BDSALINICOL;

                       -- IF (BDSALBASECOL IS NOT NULL) THEN
                         --  BDSALINICOL = BDSALBASECOL;
                      END
                   ELSE
                     BEGIN
                       BDCODMAS = WCODMAS;
                       BDDESCMAS = WDESCMAS;
                     END

                   IF (BDDATACOL IS NULL) THEN
                      BDDATACOL = BDDATAADMCOL;

                   IF (BDDATAEFEITO IS NULL) THEN
                      BDDATAEFEITO = BDDATACOL;

                   IF (BDSALBASEANT = BDSALINICOL) THEN
                      BEGIN
                        BDCODMAS = 0;
                        BDDESCMAS = 'Admissão';
                        BDDATACOL = WDATAADMCOL;
                      END

                   BDCODSHE = WCODSHE;
                   BDDESCSHE = WDESCSHE;
                   --IF ((PRTRAZERSALINI = 1) AND ((BDSALBASECOL = BDSALINICOL) AND (WTIPOCOL = 4))) THEN
                   --IF ((PRTRAZERSALINI = 1) AND ((BDSALBASECOL <> BDSALINICOL) OR (BDSALBASECOL IS NULL))) THEN
                   IF ((PRTRAZERSALINI = 1) AND (BDSALINICOL <> 0)) THEN
                      begin
                        if ((wempatu <> wcodemp) or (wcolatu <> wcodcol)) then
                           begin
                             wwhere = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||
                                      ' and BDREFCOL <= '||prref||
                                      ' order by BDREFCOL DESC';
                             execute statement wwhere into :BDNOMCOL;
           
                             wempatu = wcodemp;
                             wcolatu = wcolatu;
                           end

                        bdcodemporig = bdcodemp;
                        bdcodcolorig = bdcodcol;

                        SUSPEND;
                      end
                END
             ELSE
                BEGIN
                --  IF ((BDCODEMP <> WCODEMP) OR (BDCODCOL <> WCODCOL) OR (BDSALBASECOL <> WSALBASECOL) OR (BDCODMAS <> WCODMAS)) THEN   --Sol. 18509 - Bruno L. R. - 03/07/2017
                 -- BEGIN
                        BDCODEMP = WCODEMP;
                        BDCODCOL = WCODCOL;
                        BDDATAADMCOL = WDATAADMCOL;
                        IF (WSALINICOL IS NULL) THEN
                           BDSALINICOL = 0;
                        ELSE
                           BDSALINICOL = WSALINICOL;
                        BDDATACOL = WDATACOL;
                        BDSALBASEANT = BDSALBASECOL;     --Sol. 17798 - Bruno L. R. - 04/04/2017
                        BDSALBASECOL = WSALBASECOL;
                        BDDATAEFEITO = WDATAEFEITO;
                        wi=0;

                         begin --158776 Valmor H Junior 01/02/2022
                          if (bdsalbaseant=bdsalbasecol) then
                              wi=1;
                         end

                       IF ((WDATACOL = WDATAADMCOL) OR (BDSALBASEANT IS NULL)) THEN    --Sol. 18509 - Bruno L. R. - 10/07/2017
                          BEGIN
                            BDCODMAS = 0;
                            BDDESCMAS = 'Admissão';

                         --   IF ((BDSALINICOL <= BDSALBASECOL) OR (BDSALBASECOL IS NULL)) THEN
                           --    BDSALBASECOL = BDSALINICOL;
                          END
                       ELSE
                         BEGIN
                           BDCODMAS = WCODMAS;
                           BDDESCMAS = WDESCMAS;
                         END
                        WCODTFUCANT = BDCODTFUC;
                        BDCODTFUC = WCODTFUC;
                        BDCODSHE = WCODSHE;
                        BDDESCSHE = WDESCSHE;

                        IF (BDDATACOL IS NULL) THEN
                           BDDATACOL = BDDATAADMCOL;

                        IF (BDDATAEFEITO IS NULL) THEN
                           BDDATAEFEITO = BDDATACOL;

                      --IF (BDSALBASEANT = BDSALINICOL) THEN
                        IF (BDDATACOL = WDATAADMCOL) THEN -- Sol.150948 acontece do Colab ter mudança de cargo sem alteração salárial.
                           BEGIN
                             BDCODMAS = 0;
                             BDDESCMAS = 'Admissão';
                       --      BDDATACOL = WDATAADMCOL;
                           END

                        /*Não estava retornando quando alterava apenas a função, tive que validar se é outra função - #144930 - Paulo Nunes - 21/12/2020*/
                       -- IF ((BDSALBASEANT <> BDSALBASECOL) OR (WCODTFUCANT IS NULL))  THEN
                      --     BEGIN
                         --    BDCODMAS = WCODMAS;
                         --    BDDESCMAS = WDESCMAS;
                        --   END

                       --IF ((PRTRAZERSALINI = 1) AND (((BDSALBASECOL <> BDSALINICOL) AND ((BDSALBASECOL <> BDSALBASEANT) OR (BDSALBASEANT IS NULL))) OR
                       --   ((WTIPOCOL = 4) AND (BDSALBASECOL <> BDSALBASEANT)))) THEN -
                       --IF ((PRTRAZERSALINI = 1) AND ((((BDSALBASECOL >= BDSALBASEANT) OR (BDSALBASEANT IS NULL))) OR -- Sol. 30767 - Paulo Nunes - 26/07/2019 - Retirado a verificação se o salario atual é diferente do inicial
                       --   ((WTIPOCOL = 4) AND (BDSALBASECOL <> BDSALBASEANT)))) THEN
                       --IF ((PRTRAZERSALINI = 1) AND (((BDSALBASECOL <> BDSALINICOL) AND (BDDATAADMCOL <> BDDATACOL) AND ((BDSALBASECOL > BDSALBASEANT) OR (BDSALBASEANT IS NULL))) OR -- Sol. 127578 - Jarde - 05/11/2019 - Estava duplicando a informação se o colaborador tivesse apenas o dado diário da admissão.
                       --   ((WTIPOCOL = 4) AND (BDSALBASECOL <> BDSALBASEANT)))) THEN
                       --IF ((PRTRAZERSALINI = 1) AND (((BDSALBASECOL <> BDSALINICOL) AND (BDDATAADMCOL <> BDDATACOL) AND ((BDSALBASECOL <> BDSALBASEANT) OR (BDSALBASEANT IS NULL) OR (WCODTFUCANT <> WCODTFUC))) OR -- Sol. 136718 - Peterson - 28/05/2020 - Nao estava demonstrando valores reduzidos no processo de alteração salarial.
                       --   ((WTIPOCOL = 4) AND (BDSALBASECOL <> BDSALBASEANT)))) THEN
                       IF ((PRTRAZERSALINI = 1) AND (((BDSALBASECOL >= BDSALINICOL) AND (BDDATAADMCOL <> BDDATACOL) AND ((BDSALBASECOL >= BDSALBASEANT) OR (BDSALBASEANT IS NULL) OR (WCODTFUCANT <> WCODTFUC))) OR -- Sol.: 152121 - André Cursino - 10/11/2021 - Alterado verificação de salários anteriores e atuais, pois quando há somente alteração de função não sai no relatório.
                          ((WTIPOCOL = 4) AND (BDSALBASECOL >= BDSALBASEANT)))) THEN
                          begin
                            if ((wempatu <> wcodemp) or (wcolatu <> wcodcol)) then
                               begin
                                 wwhere = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||
                                          ' and BDREFCOL <= '||prref||
                                          ' order by BDREFCOL DESC';
                                 execute statement wwhere into :BDNOMCOL;
               
                                 wempatu = wcodemp;
                                 wcolatu = wcolatu;
                               end

                            bdcodemporig = bdcodemp;
                            bdcodcolorig = bdcodcol;
       
                            /*if ((BDSALBASECOL <> BDSALBASEANT) and (BDDATAEFEITO = WDATAEFEITO)) then Adicionado verificação para não levar registros duplicados.
                                                                                   Solicitação: 155817 - André Cursino - 22/11/2021*/
                            if (((BDSALBASECOL <> BDSALBASEANT) and (BDDATAEFEITO = WDATAEFEITO)) or
                               ((WCODTFUCANT <> WCODTFUC) and (prSalarioFuncao = 1)))  then        /*Sol.: 162323 - André Cursino - Adicionado parametro para verificar se deseja levar alterações de cargo*/
                            SUSPEND;
                          end
      ELSE
     --SUSPEND; --Sol.150948 LuizCovre, quando tem mais de um registro. (Comentei esse SUSPEND. Sol.156194).
                   --  END
                     if (wi<>1) then
                   SUSPEND;
                END
    
             WCONT = 1;
           END
       END
     END
   ELSE
       if (wi<>1) then
     SUSPEND;
end^

/* Restore proc. body: SP_FUNCAO_CBO_ESOCIAL */
ALTER PROCEDURE SP_FUNCAO_CBO_ESOCIAL(PREMPRESA INTEGER,
PRCBO INTEGER)
 RETURNS(BDCODFUNCAO VARCHAR(30))
 AS
DECLARE VARIABLE WPLANO INTEGER;
DECLARE VARIABLE WDESCCBO VARCHAR(40);
BEGIN
  /* Procedure Text */
  bdcodfuncao = NULL;

  IF ((NOT prcbo IS NULL) AND (prcbo > 0)) THEN
     BEGIN
       SELECT FIRST 1 f.bdcodtfuc
       FROM vrh_funcoes_tfuc f
       JOIN vw_empresas_ref_atual emp ON (f.bdcodplafuc = emp.bdcodplafuc)
       WHERE emp.bdcodemp = :prempresa AND f.bdcodcbo = :prcbo INTO bdcodfuncao;
     
       IF ((bdcodfuncao IS NULL) OR (bdcodfuncao = 0)) THEN
          BEGIN
             wplano = NULL;
             SELECT FIRST 1 emp.bdcodplafuc FROM vw_empresas_ref_atual emp
             WHERE emp.bdcodemp = :prempresa INTO wplano;
     
             IF (wplano IS NOT NULL AND wplano > 0) THEN
                BEGIN
                  wdesccbo = NULL;
                  SELECT SUBSTRING(c.bddesccbo FROM 1 FOR 40) FROM vrh_base_tcbo c WHERE (c.bdcodcbo = :prcbo) INTO :wdesccbo;
     
                  IF (wdesccbo IS NOT NULL) THEN
                     BEGIN
                       INSERT INTO vrh_funcoes_tfuc ( BDCODPLAFUC, BDCODTFUC, BDCODCBO, BDDESCTFUC, BDCODCBOTSIN)
                                   VALUES ( :wplano, NULL, :prcbo, :wdesccbo, NULL);
     
                       SELECT fc.bdcodfuncao FROM SP_FUNCAO_CBO_ESOCIAL(:prempresa,:prcbo) fc INTO :bdcodfuncao;
                     END
                END
          END
     END

  SUSPEND;
END
^

/* Restore proc. body: SP_FUNCOES_PLANO_EMP */
create or alter procedure SP_FUNCOES_PLANO_EMP (
    PRCODEMP integer,
    PRCODPLAFUC integer,
    PRREFERENCIA integer,
    PRRHNET smallint = 0,
    PRCODTFUC integer = 0)
returns (
    BDCODEMP integer,
    BDCODEMPRHNET integer,
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDCODCBO integer,
    BDDESCCBO varchar(150),
    BDDESCTFUC varchar(40),
    BDCODCBOTSIN integer,
    BDDESCFUNCDET varchar(999),
    BDINATIVA varchar(5),
    BDATIVO varchar(3))
as
declare variable WCODPLAFUC integer;
declare variable WSQL varchar(1000);
declare variable WVALIDAPLANO integer;
declare variable WSQL2 varchar(10000);
BEGIN
  prcodemp    = coalesce(prcodemp, 0);
  prcodplafuc = coalesce(prcodplafuc, 0);

  prcodtfuc = coalesce(prcodtfuc, 0);

  wsql = '';

  if (prcodemp > 0) then
     wsql = wsql||' (BDCODEMP = '||prcodemp||') ';

  if (coalesce(prrhnet, 0) > 0) then
     begin
       if (wsql <> '') then
          wsql = wsql||' and ';

       wsql = wsql||'upper(BDRHNET) = ''TRUE'' ';
     end

  if (wsql <> '') then
     wsql = ' where '||wsql;


  BDATIVO = 'sim';

  for execute statement 'select BDCODEMP, coalesce(BDCODWEB, BDCODEMP) from TEMPRESAS '||wsql
  into :BDCODEMP, :BDCODEMPRHNET
  do
    begin
      if (prcodplafuc <= 0) then
         begin
           wcodplafuc = null;
           select first 1 BDCODPLAFUC from VRH_BASE_TEMPVINC where BDCODEMP = :BDCODEMP and BDREFEMP <= :prreferencia order by BDREFEMP DESC into :wcodplafuc;
           WVALIDAPLANO = wcodplafuc;
         end
      else
         begin
            wcodplafuc = prcodplafuc;
            select first 1 BDCODPLAFUC from VRH_BASE_TEMPVINC where BDCODEMP = :BDCODEMP and BDREFEMP <= :prreferencia order by BDREFEMP DESC into :wvalidaplano;
         end

      if ((coalesce(wcodplafuc, 0) > 0) and (wvalidaplano = wcodplafuc)) then
         begin
           wsql2 = 'select FUC.BDCODTFUC, FUC.bdcodplafuc, FUC.BDCODCBO, FUC.BDCODCBOTSIN, '||
                          'case when (CBO.BDDESCCBOTSIN <> '''') and (CBO.BDDESCCBOTSIN is not null) then CBO.BDDESCCBOTSIN else CBOO.BDDESCCBO end BDDESCCBO, '||
                          'FUC.BDDESCTFUC, FUC.BDDESCFUNCDET, FUC.BDINATIVA '||
                    'from VRH_FUNCOES_TFUC FUC '||
                    'left outer join VRH_BASE_TCBO CBOO on (CBOO.BDCODCBO = FUC.BDCODCBO) '||
                    'left outer join VRH_BASE_CBO_TSIN CBO on (CBO.BDCODCBO = FUC.BDCODCBO and CBO.BDCODCBOTSIN = FUC.BDCODCBOTSIN) '||
                    'where FUC.BDCODPLAFUC = '||:wcodplafuc ;

           if (prcodtfuc > 0) then
              wsql2 = wsql2||' and FUC.BDCODTFUC = '||prcodtfuc;

           for execute statement wsql2
           into
             :BDCODTFUC, :BDCODPLAFUC, :BDCODCBO, :BDCODCBOTSIN, :BDDESCCBO, :BDDESCTFUC, :BDDESCFUNCDET, :BDINATIVA
           do
             begin
               if (upper(coalesce(BDINATIVA, 'FALSE')) = 'TRUE') then
                  BDATIVO = 'nao';
               else
                  BDATIVO = 'sim';

             suspend;
         end
    end
    end
END^


/* Restore proc. body: SP_GERA_ADVERTENCIAS */
CREATE OR ALTER PROCEDURE SP_GERA_ADVERTENCIAS
AS
DECLARE VARIABLE WAUXINT INTEGER;
BEGIN
  /* Procedure Text */
--  suspend;
  FOR SELECT FIRST 1 p.bdcodplapadrao FROM tplano_conf_online p
      JOIN TCONF_CONTAS_ONLINE_REF c ON (p.bdcodplanoonline = c.bdcodplanoonline)
      WHERE p.bdcodplapadrao <> c.bdcodplapadrao INTO WAUXINT DO
    BEGIN
      EXECUTE PROCEDURE sp_insere_advertencia('Configuração online: Items da configuração online com plano de contas diferente do plano de contabilização!');
    END


  FOR SELECT FIRST 1 p.bdcodplapadrao FROM tplano_conf_online p
      JOIN TCONF_CONTAS_ONLINE_REF c ON (p.bdcodplanoonline = c.bdcodplanoonline)
      WHERE p.bdcodhist <> c.bdcodtphi INTO WAUXINT DO
    BEGIN
      EXECUTE PROCEDURE sp_insere_advertencia('Configuração online: Items da configuração online com plano de históricos diferente do plano de contabilização!');
    END

END
^

/* Restore proc. body: SP_IMPOSTO_EMPRESA */
ALTER PROCEDURE SP_IMPOSTO_EMPRESA(PRCODEMP INTEGER,
PRCODSIS INTEGER,
PRTIPORETENCAO INTEGER,
PRREF INTEGER,
PRQTD INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDREFFIMIMP INTEGER,
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(100),
BDDATACRIACAO DATE,
BDDATAEXTINTO DATE,
BDCOMPETENCIA INTEGER,
BDDOCARRECADACAO INTEGER,
BDPERAPURACAO INTEGER,
BDDIAVENCTO INTEGER,
BDANTECIPA VARCHAR(5),
BDMESVENCTO INTEGER,
BDJUROSDIA INTEGER,
BDVLRJUROS NUMERIC(15,6),
BDJUROSDIAMES INTEGER,
BDMULTADIA INTEGER,
BDVLRMULTA NUMERIC(15,6),
BDMULTADIAMES INTEGER,
BDVLRMAXMULTA NUMERIC(15,6),
BDALIQIMPOSTO NUMERIC(15,6),
BDLIMITEISENCAO NUMERIC(15,6),
BDTIPORETENCAO INTEGER,
BDCODREC INTEGER,
BDCODIND INTEGER,
BDRETBCCALCULOIMP VARCHAR(5),
BDDESCREC VARCHAR(150),
BDTIPOIMPOSTO INTEGER,
BDCODSIS INTEGER)
 AS
DECLARE VARIABLE WPRIDIA DATE;
DECLARE VARIABLE WULTDIA DATE;
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  wsql = 'select ';

  EXECUTE PROCEDURE sp_seta_competencia(:prref,NULL,NULL);

  IF (prqtd IS NOT NULL AND prqtd <> 0) THEN
     wsql = wsql||'first '||prqtd||' ';

  wsql = wsql|| 'BDCODEMP, '||
                'BDREFEMP, '||
                'BDREFFIMIMP, '||
                'BDCODIMP, '||
                'BDDESCIMP, '||
                'BDDATACRIACAO, '||
                'BDDATAEXTINTO, '||
                'BDCOMPETENCIA, '||
                'BDDOCARRECADACAO, '||
                'BDPERAPURACAO, '||
                'BDDIAVENCTO, '||
                'BDANTECIPA, '||
                'BDMESVENCTO, '||
                'BDJUROSDIA, '||
                'BDVLRJUROS, '||
                'BDJUROSDIAMES, '||
                'BDMULTADIA, '||
                'BDVLRMULTA, '||
                'BDMULTADIAMES, '||
                'BDVLRMAXMULTA, '||
                'COALESCE(BDALIQIMPOSTO, 0.0) BDALIQIMPOSTO, '||
                'BDLIMITEISENCAO, '||
                'BDTIPORETENCAO, '||
                'BDCODREC, '||
                'BDCODIND, '||
                'BDRETBCCALCULOIMP, '||
                'BDDESCREC, '||
                'BDTIPOIMPOSTO, '||
                'BDCODSIS ';
  wsql = wsql||'from VW_TEMPRESAIMPOSTOREF ';


  wwhere = '';

  IF (prref IS NOT NULL AND prref <> 0) THEN
     BEGIN
       wpridia = CAST((SUBSTRING(prref FROM 5 FOR 2)||'-01-'||SUBSTRING(prref FROM 1 FOR 4)) AS DATE);
       wultdia = wpridia - EXTRACT(DAY FROM wpridia) + 32 - EXTRACT(DAY FROM wpridia - EXTRACT(DAY FROM wpridia) + 32);

       wwhere = wwhere||'BDREFEMP <= '||prref||' ';

       wwhere = wwhere||' and (';

       wwhere = wwhere||'(BDDATACRIACAO is null) or (BDDATACRIACAO <= '''||wpridia||''') and ';
       wwhere = wwhere||'(BDDATAEXTINTO is null) or (BDDATAEXTINTO > '''||wultdia||''')';

       wwhere = wwhere||') ';
     END

  IF (prcodemp IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||' bdcodemp = '||prcodemp;
     END

  IF (prcodsis IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||' bdcodsis = '||prcodsis;
     END

  IF (prtiporetencao IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||' bdtiporetencao = '||prtiporetencao;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDREFEMP,
    :BDREFFIMIMP,
    :BDCODIMP,
    :BDDESCIMP,
    :BDDATACRIACAO,
    :BDDATAEXTINTO,
    :BDCOMPETENCIA,
    :BDDOCARRECADACAO,
    :BDPERAPURACAO,
    :BDDIAVENCTO,
    :BDANTECIPA,
    :BDMESVENCTO,
    :BDJUROSDIA,
    :BDVLRJUROS,
    :BDJUROSDIAMES,
    :BDMULTADIA,
    :BDVLRMULTA,
    :BDMULTADIAMES,
    :BDVLRMAXMULTA,
    :BDALIQIMPOSTO,
    :BDLIMITEISENCAO,
    :BDTIPORETENCAO,
    :BDCODREC,
    :BDCODIND,
    :BDRETBCCALCULOIMP,
    :BDDESCREC,
    :BDTIPOIMPOSTO,
    :BDCODSIS
  DO
  SUSPEND;
END
^

/* Restore proc. body: SP_INCLUI_VERBAS_NOVAS */
ALTER PROCEDURE SP_INCLUI_VERBAS_NOVAS AS
DECLARE VARIABLE WCODVER INTEGER;
DECLARE VARIABLE WSQL VARCHAR(1000);
BEGIN
  /* Procedure Text */

  wsql = 'select X.BDCODVERPD from VRH_BASE_TVERBAS_PADRAO X where not exists(select Y.BDCODVER from VRH_BASE_TVERBAS Y where Y.BDCODVER = X.BDCODVERPD) ';
  FOR EXECUTE STATEMENT wsql INTO :wcodver DO
    BEGIN
      EXECUTE PROCEDURE sp_restaura_verba_padrao(:wcodver);
    END

--  suspend;
END
^

/* Restore proc. body: SP_VRHF_PBM_NO_ANO */
CREATE OR ALTER PROCEDURE SP_VRHF_PBM_NO_ANO (
    PREMP VARCHAR(32700),
    PRANO INTEGER)
RETURNS (
    BDCODEMP INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WSQL2 VARCHAR(1000);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WREFINI INTEGER;
DECLARE VARIABLE WREFFIM INTEGER;
DECLARE VARIABLE WCODBLOCOP INTEGER;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES VARCHAR(2);
BEGIN
  wsql = 'select EMP.bdcodemp from TEMPRESAS EMP ';

  IF (premp IS NOT NULL AND premp <> '') THEN
    wsql = wsql||' where '||premp;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp DO
    BEGIN
      bdcodemp = wcodemp;
      wrefini = CAST((:prano||'01') AS INTEGER);
      wreffim = CAST((:prano||'12') AS INTEGER);

      WHILE (wreffim >= wrefini) DO
        BEGIN
          wsql2 = 'select first 1 BDCODCONFBLOCOP from VEF_BASE_TEMPPARGER where BDCODEMP = '||wcodemp||' and BDREFEMP <= '||wreffim||' order by BDREFEMP DESC ';
          wcodblocop = NULL;
          EXECUTE STATEMENT wsql2 INTO :wcodblocop;
          IF (wcodblocop IS NOT NULL AND wcodblocop <> 0) THEN
            BEGIN
              SUSPEND;
              BREAK;
            END

          IF (CAST((SUBSTRING(wreffim FROM 5 FOR 2)) AS INTEGER) = 1) THEN
            BEGIN
              wano = CAST((SUBSTRING(wreffim FROM 1 FOR 4)) AS INTEGER) - 1;
              wmes = '12';
              wreffim = CAST((CAST(wano AS VARCHAR(4))||wmes) AS INTEGER);
            END
          ELSE
            BEGIN
              wano = CAST((SUBSTRING(wreffim FROM 1 FOR 4)) AS INTEGER);
              wmes = SUBSTRING(wreffim FROM 5 FOR 2);
              wmes = CAST((CAST(wmes AS INTEGER) - 1) AS VARCHAR(2));
              WHILE (strlen(wmes) < 2) DO
                wmes = '0'||wmes;

              wreffim = CAST((CAST(wano AS VARCHAR(4))||wmes) AS INTEGER);
            END
        END
    END
END
^

/* Restore proc. body: SP_INCLUI_VERBASEMP */
create or alter procedure SP_INCLUI_VERBASEMP (
    PRVERBA integer,
    PRCLASSECOL integer = -1,
    PRTIPOCOL integer = -1,
    PRCOMFGTS DM_BOOLEAN = 'FALSE',
    PRINTERMITENTE DM_BOOLEAN = 'FALSE')
as
declare variable WCODEMP integer;
declare variable WSQL varchar(10000);
declare variable WEMP integer;
declare variable WCLASSVER varchar(9);
BEGIN
  /* Procedure Text */
  wclassver = null;
  SELECT SUBSTRING(BDCLAVER FROM 1 FOR 9) FROM VRH_BASE_TVERBAS WHERE BDCODVER = :prverba INTO :wclassver;

  IF (COALESCE(wclassver, '') <> '') THEN
  BEGIN
    FOR SELECT BDCODEMP FROM TEMPRESAS INTO :wcodemp DO
      BEGIN
        wsql = 'select first 1 BDCODEMP from VRHF_BASE_TVERBASEMP where BDCODEMP = '||:wcodemp||' and BDCLASSIFVEREMP = '''||:wclassver||''' and BDCLASSECOLVEREMP = '||:prclassecol||' and BDTIPOCOLVEREMP = '||:prtipocol||
               ' and UPPER(COALESCE(BDCOMFGTS, ''FALSE'')) = '''||:prcomfgts||''' and UPPER(COALESCE(BDINTERMITENTE, ''FALSE'')) = '''||:printermitente||'''';
        wemp = NULL;
        EXECUTE STATEMENT wsql INTO :wemp;

        IF (COALESCE(wemp, 0) = 0) THEN
           BEGIN
             wsql = 'insert into VRHF_BASE_TVERBASEMP (BDCODEMP,BDCODVER,BDCLASSECOLVEREMP,BDTIPOCOLVEREMP,BDCOMFGTS,BDCLASSIFVEREMP,BDCODTCA,BDINTERMITENTE) VALUES ' ||
                    '('||:wcodemp||','||:prverba||','||:prclassecol||','||:prtipocol||','''||:prcomfgts||''','''||:wclassver||''',null,'''||:printermitente||''')';    --Sol. 17178 - Bruno L. R. - 16/03/2017
  
             EXECUTE STATEMENT wsql;
           END
      END
  END

--  suspend;
END^

/* Restore proc. body: SP_INDICES_ACUMULADOS */
ALTER PROCEDURE SP_INDICES_ACUMULADOS(PRCODIND INTEGER)
 RETURNS(BDANO INTEGER,
BDJAN NUMERIC(15,6),
BDFEV NUMERIC(15,6),
BDMAR NUMERIC(15,6),
BDABR NUMERIC(15,6),
BDMAI NUMERIC(15,6),
BDJUN NUMERIC(15,6),
BDJUL NUMERIC(15,6),
BDAGO NUMERIC(15,6),
BDSET NUMERIC(15,6),
BDOUT NUMERIC(15,6),
BDNOV NUMERIC(15,6),
BDDEZ NUMERIC(15,6))
 AS
DECLARE VARIABLE WREF INTEGER;
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WVALATU NUMERIC(15,6);
DECLARE VARIABLE WVALACU NUMERIC(15,6);
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WANOATU INTEGER;
DECLARE VARIABLE WI INTEGER;
BEGIN
  wsql = 'select BDREFIND, SUM(BDVALIND) BDVALIND from VW_TINDVAL where BDCODIND = '||prcodind||' group by BDREFIND order by BDREFIND DESC ';
  BDJAN = 0;
  BDFEV = 0;
  BDMAR = 0;
  BDABR = 0;
  BDMAI = 0;
  BDJUN = 0;
  BDJUL = 0;
  BDAGO = 0;
  BDSET = 0;
  BDOUT = 0;
  BDNOV = 0;
  BDDEZ = 0;
  wanoatu = 0;
  wvalacu = 0;
  wi = 0;

  FOR EXECUTE STATEMENT wsql INTO :wref, :wvalatu DO
    BEGIN
      wano = CAST(SUBSTRING(wref FROM 1 FOR 4) AS INTEGER);

      IF (wanoatu = 0) THEN
         wanoatu = wano;

      IF (wanoatu <> wano) THEN
         BEGIN
           BDANO = wanoatu;
           SUSPEND;
           BDJAN = 0;
           BDFEV = 0;
           BDMAR = 0;
           BDABR = 0;
           BDMAI = 0;
           BDJUN = 0;
           BDJUL = 0;
           BDAGO = 0;
           BDSET = 0;
           BDOUT = 0;
           BDNOV = 0;
           BDDEZ = 0;
           wanoatu = wano;
         END

      IF (wI < 1) THEN
         BEGIN
           wvalacu = 1;
           wi = wi + 1;
         END

      IF (SUBSTRING(wref FROM 5 FOR 2) = '01') THEN
         BDJAN = BDJAN + wvalacu;
      ELSE
      IF (SUBSTRING(wref FROM 5 FOR 2) = '02') THEN
         BDFEV = BDFEV + wvalacu;
      ELSE
      IF (SUBSTRING(wref FROM 5 FOR 2) = '03') THEN
         BDMAR = BDMAR + wvalacu;
      ELSE
      IF (SUBSTRING(wref FROM 5 FOR 2) = '04') THEN
         BDABR = BDABR + wvalacu;
      ELSE
      IF (SUBSTRING(wref FROM 5 FOR 2) = '05') THEN
         BDMAI = BDMAI + wvalacu;
      ELSE
      IF (SUBSTRING(wref FROM 5 FOR 2) = '06') THEN
         BDJUN = BDJUN + wvalacu;
      ELSE
      IF (SUBSTRING(wref FROM 5 FOR 2) = '07') THEN
         BDJUL = BDJUL + wvalacu;
      ELSE
      IF (SUBSTRING(wref FROM 5 FOR 2) = '08') THEN
         BDAGO = BDAGO + wvalacu;
      ELSE
      IF (SUBSTRING(wref FROM 5 FOR 2) = '09') THEN
         BDSET = BDSET + wvalacu;
      ELSE
      IF (SUBSTRING(wref FROM 5 FOR 2) = '10') THEN
         BDOUT = BDOUT + wvalacu;
      ELSE
      IF (SUBSTRING(wref FROM 5 FOR 2) = '11') THEN
         BDNOV = BDNOV + wvalacu;
      ELSE
         BDDEZ = BDDEZ + wvalacu;

      wvalacu = wvalacu + wvalatu;
    END

  IF (wanoatu <> 0) THEN
     BEGIN
       IF (SUBSTRING(wref FROM 5 FOR 2) = '01') THEN
          wref = CAST((CAST((CAST(SUBSTRING(wref FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
       ELSE
          BEGIN
            IF (CAST(SUBSTRING(wref FROM 5 FOR 2) AS INTEGER) <= 10) THEN
               wref = CAST((SUBSTRING(wref FROM 1 FOR 4)||'0'||CAST((CAST(SUBSTRING(wref FROM 5 FOR 2) AS INTEGER) - 1) AS VARCHAR(1))) AS INTEGER);
            ELSE
               wref = CAST((SUBSTRING(wref FROM 1 FOR 4)||CAST((CAST(SUBSTRING(wref FROM 5 FOR 2) AS INTEGER) - 1) AS VARCHAR(2))) AS INTEGER);
          END

       IF (SUBSTRING(wref FROM 5 FOR 2) = '01') THEN
          BDJAN = BDJAN + wvalacu;
       ELSE
       IF (SUBSTRING(wref FROM 5 FOR 2) = '02') THEN
          BDFEV = BDFEV + wvalacu;
       ELSE
       IF (SUBSTRING(wref FROM 5 FOR 2) = '03') THEN
          BDMAR = BDMAR + wvalacu;
       ELSE
       IF (SUBSTRING(wref FROM 5 FOR 2) = '04') THEN
          BDABR = BDABR + wvalacu;
       ELSE
       IF (SUBSTRING(wref FROM 5 FOR 2) = '05') THEN
          BDMAI = BDMAI + wvalacu;
       ELSE
       IF (SUBSTRING(wref FROM 5 FOR 2) = '06') THEN
          BDJUN = BDJUN + wvalacu;
       ELSE
       IF (SUBSTRING(wref FROM 5 FOR 2) = '07') THEN
          BDJUL = BDJUL + wvalacu;
       ELSE
       IF (SUBSTRING(wref FROM 5 FOR 2) = '08') THEN
          BDAGO = BDAGO + wvalacu;
       ELSE
       IF (SUBSTRING(wref FROM 5 FOR 2) = '09') THEN
          BDSET = BDSET + wvalacu;
       ELSE
       IF (SUBSTRING(wref FROM 5 FOR 2) = '10') THEN
          BDOUT = BDOUT + wvalacu;
       ELSE
       IF (SUBSTRING(wref FROM 5 FOR 2) = '11') THEN
          BDNOV = BDNOV + wvalacu;
       ELSE
          BDDEZ = BDDEZ + wvalacu;

       BDANO = wanoatu;
       SUSPEND;
     END
END
^

/* Restore proc. body: SP_INSERE_ADVERTENCIA */
ALTER PROCEDURE SP_INSERE_ADVERTENCIA(PRDESCRICAO VARCHAR(1024),
PRTIPO INTEGER = 1)
 AS
BEGIN
  /* Procedure Text */
  INSERT INTO tadvertencia(BDDATA,BDHORA,BDCODTIPO,BDDESCRICAO,BDENVIADO) VALUES (CURRENT_DATE,CURRENT_TIME,1,:prdescricao,'FALSE');
--  suspend;
END
^

create or alter procedure SP_GETCODIGO_TELA (
    PRNOMETELA varchar(100),
    PRCAPTIONTELA varchar(150))
returns (
    BDCODTELASIS integer)
as
declare variable WCAPTION varchar(150);
begin
  bdcodtelasis = null;
  if (substring(upper(prnometela) from 1 for strlen('TFRRELGERADOR')) = 'TFRRELGERADOR') then
     SELECT FIRST 1 BDCODTELASIS,BDCAPTIONTELA FROM ttela_sistema WHERE upper(BDNOMETELA) = UPPER(:prnometela) and upper(BDCAPTIONTELA) = upper(:prcaptiontela) INTO :bdcodtelasis,:wcaption;
  else
     SELECT FIRST 1 BDCODTELASIS,BDCAPTIONTELA FROM ttela_sistema WHERE upper(BDNOMETELA) = UPPER(:prnometela) INTO :bdcodtelasis,:wcaption;

  IF (bdcodtelasis IS NULL) THEN
  BEGIN
    INSERT INTO ttela_sistema (BDNOMETELA, BDCAPTIONTELA) VALUES (UPPER(:prnometela), :prcaptiontela);
    select BDCODTELASIS from SP_GETCODIGO_TELA(:PRNOMETELA, :PRCAPTIONTELA) into :BDCODTELASIS;
  END
  ELSE
  IF (wcaption <> prcaptiontela and prcaptiontela <> '') THEN
  begin
    UPDATE ttela_sistema SET bdcaptiontela = :prcaptiontela WHERE bdcodtelasis = :bdcodtelasis and bdcaptiontela <> :prcaptiontela;
    -- Julio Cesar - 31/07/2024 - #207254 - Caso ocorra algum problema no update (como deadlock), não vai gerar o exception,
    -- e na próxima chamada da procedure corrige o caption da tela
    when any do
    begin
      --Apenas para fazer alguma coisa
      wcaption = :prcaptiontela;
    end
  end
  suspend;
end^

/* Restore proc. body: SP_INSERIR_LOG */
create or alter procedure SP_INSERIR_LOG (
    BDCODEMP integer,
    BDCODTER integer,
    BDCODUSU integer,
    BDCODIMP integer,
    BDCODSIS integer,
    BDCODCOL integer,
    BDDATASISTEMA date,
    BDHORAINICIAL time,
    BDACAO blob sub_type 1 segment size 80,
    BDACESSOID integer,
    BDTIPOACAO integer,
    PRNOME_MICRO varchar(80),
    PRIP_MICRO varchar(15),
    PRNOMETELA varchar(100),
    PRCAPTIONTELA varchar(150),
    BDCODRESP integer,
    PRTABELA varchar(50),
    BDTIPOIMPRESSAO smallint,
    BDERRO_PROCESSO varchar(5),
    BDDATACOMPETENCIA date,
    BDCODUSUINTRANET integer = null,
    BDNOMUSUINTRANET varchar(80) = null)
as
declare variable WCODIGO_TABELA integer;
declare variable WCODIGO_TELA integer;
declare variable WCODIGO_NOMEMICRO integer;
declare variable WCAPTION varchar(150);
declare variable WVERSAOFDB varchar(10);
declare variable WSQL DM_MAXVARCHAR;
declare variable WCODUSU integer;
declare variable WNOMUSUINTRA varchar(80);
declare variable WCODSIS integer;
declare variable WCODUSUINTRA integer;
declare variable WNOME_MICRO varchar(80);
declare variable WIP_MICRO varchar(15);
declare variable WDATACOMPETENCIA date;
BEGIN
  wversaofdb = NULL;
  wcodusu = bdcodusu;
  wcodusuintra = bdcodusuintranet;
  wnomusuintra = bdnomusuintranet;
  wcodsis = bdcodsis;
  wnome_micro = prnome_micro;
  wip_micro = prip_micro;
  wdatacompetencia = bddatacompetencia;
  SELECT FIRST 1 BDVERSAO FROM TVERSAOFDB INTO :wversaofdb;

  if (bddatasistema is null) then
     bddatasistema = CURRENT_DATE;
  if (bdhorainicial is null) then
     bdhorainicial = current_time;

  IF (:prTabela <> '') THEN
  BEGIN
    SELECT FIRST 1 BDCODTABLOG FROM ttabelas_log WHERE BDTABELA = UPPER(:prTabela) INTO wcodigo_tabela;

    IF (wcodigo_tabela IS NULL) THEN
    BEGIN
      INSERT INTO ttabelas_log (BDCODTABLOG, BDTABELA) VALUES (0, UPPER(:prTabela)) returning BDCODTABLOG INTO wcodigo_tabela;
    END
  END

  if ((:WNOME_MICRO is null) and (:WIP_MICRO is null)) then
  begin
     SELECT (TRIM(rdb$get_context('USER_SESSION', 'W_NOMEMICRO'))) FROM rdb$database into :WNOME_MICRO;
     SELECT (TRIM(rdb$get_context('USER_SESSION', 'W_IPMICRO'))) FROM rdb$database into :WIP_MICRO;
  end

  if (((wnome_micro = '') or (wnome_micro is null)) or ((wip_micro = '')or(wip_micro is null))) then
  begin
    select first 1 MON$REMOTE_ADDRESS from mon$attachments where MON$ATTACHMENT_ID = current_connection into :wnome_micro;
    SELECT FIRST 1 bdip_micro FROM TNOMEMICROLOG WHERE (BDNOME_MICRO = UPPER(:wnome_micro)) INTO wip_micro;
  end

  IF ((:wnome_micro <> '' AND :wip_micro <> '') or (:wnome_micro <> '')) THEN
  BEGIN
    SELECT FIRST 1 BDCODNOMMICRO FROM TNOMEMICROLOG WHERE ((BDNOME_MICRO = UPPER(:wnome_micro)) AND (BDIP_MICRO = UPPER(:wip_micro))) INTO WCODIGO_NOMEMICRO;

    IF (wcodigo_nomemicro IS NULL) THEN
    BEGIN
      --Fabiano 18/10/2021 estava dando erro de PK porque a chave dessa tabela é só o nome do computador
      SELECT FIRST 1 BDCODNOMMICRO FROM TNOMEMICROLOG WHERE (BDNOME_MICRO = UPPER(:wnome_micro)) INTO WCODIGO_NOMEMICRO;
      if (wcodigo_nomemicro is null) then
      begin
      WCODIGO_NOMEMICRO = GEN_ID(GEN_TNOMEMICROLOG, 1);
      INSERT INTO TNOMEMICROLOG (BDCODNOMMICRO, BDNOME_MICRO, BDIP_MICRO) VALUES (:WCODIGO_NOMEMICRO, UPPER(:wnome_micro), UPPER(:wip_micro));
      end
    END
  END

  IF (Trim(:prnometela) <> '') THEN
  BEGIN
    -- Gilberto - 01/12/2021 - Centralizando rotina
    select first 1 BDCODTELASIS from sp_getcodigo_tela(:prnometela, :prcaptiontela) into :wcodigo_tela;
    END

  if ((wcodusu is null) or (wcodusu = 0)) then
  begin
    execute statement 'select bdcodusu from vw_usuarios_secao' into :wcodusu;
  end

  if (((wcodusuintra is null) or (wcodusuintra = 0)) or (wnomusuintra = '')) then
  begin
    execute statement 'select bdcodusuintranet, bdnomusuintranet from vw_usuarios_secao' into :wcodusuintra, :wnomusuintra;
  end

  if ((wcodsis is null) or (wcodsis = 0)) then
  begin
    execute statement 'select bdcodsis from vw_get_modulo' into :wcodsis;
  end

  if (wdatacompetencia is null) then
  begin
    wdatacompetencia = current_date;
  end

  --#Alt:18972 - 13/06/2016 - Incluído o campo BDDATACOMPETENCIA.
  --alt:15642 - 13/09/2016 - Registros do tipo "exclusão de lançamentos contábeis" (13) também devem ser agrupados. Pedro
  --alt:15307 - 15/08/2016 - Alterado método de gravação do log. As funcionalidade anteriores foram implementadas diretamente em uma única rotina.
  --Quando for impressão de relatório (5) em vídeo (0), deve agrupar o registro com outros do mesmo usuário, empresa, data e sistema. Pedro
  wSQL = CASE WHEN ((BDTIPOACAO = 5) AND (BDTIPOIMPRESSAO = 0)) OR (BDTIPOACAO = 13) THEN 'update or' ELSE '' END;
  wSQL = wSQL||' insert into TLOG (BDCODEMP, BDCODTER, BDCODUSU, BDCODIMP, BDCODSIS, BDCODCOL, BDCODRESP,';
  wSQL = wSQL||' BDDATASISTEMA, BDDATA, BDHORAINICIAL, BDHORAFINAL, BDACAO, BDACESSOID, BDTIPOACAO,';
  wSQL = wSQL||' BDTIPOIMPRESSAO, BDERRO_PROCESSO, BDCODTELASIS, BDCODNOMMICRO, BDCODTABLOG, BDVERSAO, BDCODUSUINTRANET, BDNOMUSUINTRANET,';
  wSQL = wSQL||' BDDATACOMPETENCIA)';
  wSQL = wSQL||' values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ';
  wSQL = wSQL||CASE WHEN ((BDTIPOACAO = 5) AND (BDTIPOIMPRESSAO = 0)) OR (BDTIPOACAO = 13) THEN 'matching (BDCODEMP, BDCODUSU, BDCODSIS, BDDATASISTEMA, BDTIPOIMPRESSAO, BDCODTELASIS)' ELSE '' END||';';

  EXECUTE STATEMENT (wSQL) (:BDCODEMP, :BDCODTER, :wcodusu, :BDCODIMP, :wcodsis, :BDCODCOL, :BDCODRESP,
                            :BDDATASISTEMA, CURRENT_DATE, :BDHORAINICIAL, CURRENT_TIME, ''||:BDACAO||'', :BDACESSOID, :BDTIPOACAO,
                            :BDTIPOIMPRESSAO, :BDERRO_PROCESSO, :wCodigo_Tela, :wCodigo_NomeMicro, :wCodigo_Tabela, :wVersaoFDB,
                            :wcodusuintra, :wnomusuintra, :wDATACOMPETENCIA);
  --alt:15307 - Fim
  
END^

/* Restore proc. body: SP_INSERIR_LOG_ATUALIZACAO */
CREATE OR ALTER PROCEDURE SP_INSERIR_LOG_ATUALIZACAO (
    PRSISTEMA INTEGER,
    PRACAO BLOB SUB_TYPE 1 SEGMENT SIZE 80)
AS
BEGIN
  EXECUTE PROCEDURE sp_inserir_log(NULL, NULL, 1, NULL, :prSistema, NULL, CURRENT_DATE, CURRENT_TIME, :prAcao, 0, 4, 'SERVIDOR', 'SERVIDOR', 'UPDATESISTEMA', 'Processo de atualização do Único', NULL, NULL, NULL, 'FALSE', CURRENT_DATE);
END^

/* Restore proc. body: SP_INSERT_ATIVIDADE_BLUMENAU */
ALTER PROCEDURE SP_INSERT_ATIVIDADE_BLUMENAU AS
DECLARE VARIABLE CID INTEGER;
BEGIN

    SELECT bdcodcid FROM tcidade WHERE bdcodest = 80470 INTO cid;

--    bdcodcid = CID;

INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'1.01','Análise E Desenvolvimento De Sistemas.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'1.02','Programação.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'1.03','Processamento De Dados E Congêneres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'1.04','Elaboração De Programas De Computadores  Inclusive De Jogos Eletrônicos.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'1.05','Licenciamento Ou Cessão De Direito De Uso De Programas De Computação.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'1.06','Assessoria E Consultoria Em Informática.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'1.07','Suporte Técnico Em Informática  Inclusive Instalação  Configuração E Manutenção De Programas De Computação E Bancos De Dados.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'1.08','Planejamento  Confecção  Manutenção E Atualização De Páginas Eletrônicas.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'2.01','Serviços De Pesquisas E Desenvolvimento De Qualquer Natureza.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'3.01','(Vetado)',0);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'3.02','Cessão De Direito De Uso De Marcas E De Sinais De Propaganda.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'3.03','Exploração De Salões De Festas  Centro De Convenções  Escritórios Virtuais  Stands  Quadras Esportivas  Estádios  Ginásios  Auditórios  Casas De Espetáculos  Parques De Diversões  Canchas E Congêneres  Para Realização De Eventos Ou Negócios De Qualquer Natureza.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'3.04','Locação  Sublocação  Arrendamento  Direito De Passagem Ou Permissão De Uso  Compartilhado Ou Não  De Ferrovia  Rodovia  Postes  Cabos  Dutos E Condutos De Qualquer Natureza.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'3.05','Cessão De Andaimes  Palcos  Coberturas E Outras Estruturas De Uso Temporário.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.01','Medicina E Biomedicina.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.02','Análises Clínicas  Patologia  Eletricidade Médica  Radioterapia  Quimioterapia  Ultra-Sonografia  Ressonância Magnética  Radiologia  Tomografia E Congêneres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.03','Hospitais  Clínicas  Laboratórios  Sanatórios  Manicômios  Casas De Saúde  Prontos-Socorros  Ambulatórios E Congêneres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.04','Instrumentação Cirúrgica.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.05','Acupuntura.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.06','Enfermagem  Inclusive Serviços Auxiliares.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.07','Serviços Farmacêuticos.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.08','Terapia Ocupacional  Fisioterapia E Fonoaudiologia.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.09','Terapias De Qualquer Espécie Destinadas Ao Tratamento Físico  Orgânico E Mental.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.10','Nutrição.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.11','Obstetrícia.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.12','Odontologia.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.13','Ortóptica.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.14','Próteses Sob Encomenda.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.15','Psicanálise.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.16','Psicologia.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.17','Casas De Repouso E De Recuperação  Creches  Asilos E Congêneres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.18','Inseminação Artificial  Fertilização In Vitro E Congêneres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.19','Bancos De Sangue  Leite  Pele  Olhos  Óvulos  Sêmen E Congêneres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.20','Coleta De Sangue  Leite  Tecidos  Sêmen  Órgãos E Materiais Biológicos De Qualquer Espécie.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.21','Unidade De Atendimento  Assistência Ou Tratamento Móvel E Congêneres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.22','Planos De Medicina De Grupo Ou Individual E Convênios Para Prestação De Assistência Médica  Hospitalar  Odontológica E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'4.23','Outros Planos De Saúde Que Se Cumpram Através De Serviços De Terceiros Contratados  Credenciados  Cooperados Ou Apenas Pagos Pelo Operador Do Plano Mediante Indicação Do Beneficiário.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.01','Medicina Veterinária E Zootecnia.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.02','Hospitais  Clínicas  Ambulatórios  Prontos-Socorros E Congêneres  Na Área Veterinária.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.03','Laboratórios De Análise Na Área Veterinária.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.04','Inseminação Artificial  Fertilização In Vitro E Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.05','Bancos De Sangue E De Órgãos E Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.06','Coleta De Sangue  Leite  Tecidos  Sêmen  Órgãos E Materiais Biológicos De Qualquer Espécie.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.07','Unidade De Atendimento  Assistência Ou Tratamento Móvel E Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.08','Guarda  Tratamento  Amestramento  Embelezamento  Alojamento E Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'5.09','Planos De Atendimento E Assistência Médico-Veterinária.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'6.01','Barbearia  Cabeleireiros  Manicuros  Pedicuros E Congêneres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'6.02','Esteticistas  Tratamento De Pele  Depilação E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'6.03','Banhos  Duchas  Sauna  Massagens E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'6.04','Ginástica  Dança  Esportes  Natação  Artes Marciais E Demais Atividades Físicas.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'6.05','Centros De Emagrecimento  Spa E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.01','Engenharia  Agronomia  Agrimensura  Arquitetura  Geologia  Urbanismo  Paisagismo E Congêneres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.02','Execução  Por Administração  Empreitada Ou Subempreitada  De Obras De Construção Civil  Hidráulica Ou Elétrica E De Outras Obras Semelhantes  Inclusive Sondagem  Perfuração De Poços  Escavação  Drenagem E Irrigação  Terraplanagem  Pavimentação  Concretagem E A Instalação E Montagem De Produtos  Peças E Equipamento Exceto O Fornecimento De Mercadorias Produzidas Pelo Prestador De Serviços Fora Do Local Da Prestação Dos Serviços  Que Fica Sujeito Ao Icms).',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.03','Elaboração De Planos Diretores  Estudos De Viabilidade  Estudos Organizacionais E Outros  Relacionados Com Obras E Serviços De Engenharia  Elaboração De Anteprojetos  Projetos Básicos E Projetos Executivos Para Trabalhos De Engenharia.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.04','Demolição.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.05','Reparação  Conservação E Reforma De Edifícios  Estradas  Pontes  Portos E Congênere (Exceto O Fornecimento De Mercadorias Produzidas Pelo Prestador Dos Serviços  Fora Do Local Da Prestação Dos Serviços  Que Fica Sujeito Ao Icms).',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.06','Colocação E Instalação De Tapetes  Carpetes  Assoalhos  Cortinas  Revestimentos De Parede  Vidros  Divisórias  Placas De Gesso E Congêneres  Com Material Fornecido Pelo Tomador Do Serviço.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.07','Recuperação  Raspagem  Polimento E Lustração De Pisos E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.08','Calafetação.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.09','Varrição  Coleta  Remoção  Incineração  Tratamento  Reciclagem  Separação E Destinação Final De Lixo  Rejeitos E Outros Resíduos Quaisquer.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.10','Limpeza  Manutenção E Conservação De Vias E Logradouros Públicos  Imóveis  Chaminés  Piscinas  Parques  Jardins E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.11','Decoração E Jardinagem  Inclusive Corte E Poda De Árvores.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.12','Controle E Tratamento De Efluentes De Qualquer Natureza E De Agentes Físicos  Químicos E Biológicos.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.13','Dedetização  Desinfecção  Desinsetização  Imunização  Higienização  Desratização  Pulverização E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.14','(Vetado)',0);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.15','(Vetado)',0);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.16','Florestamento  Reflorestamento  Semeadura  Adubação E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.17','Escoramento  Contenção De Encostas E Serviços Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.18','Limpeza E Dragagem De Rios  Portos  Canais  Baías  Lagos  Lagoas  Represas  Açudes E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.19','Acompanhamento E Fiscalização Da Execução De Obras De Engenharia  Arquitetura E Urbanismo.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.20','Aerofotogrametria (Inclusive Interpretação)  Cartografia  Mapeamento  Levantamentos Topográficos  Batimétricos  Geográficos  Geodésicos  Geológicos  Geofísicos E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.21','Pesquisa  Perfuração  Cimentação  Mergulho  Perfilagem  Concretação  Testemunhagem  Pescaria  Estimulação E Outros Serviços Relacionados Com A Exploração E Explotação De Petróleo  Gás Natural E De Outros Recursos Minerais.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'7.22','Nucleação E Bombardeamento De Nuvens E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'8.01','Ensino Regular Pré-Escolar  Fundamental  Médio E Superior.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'8.02','Instrução  Treinamento  Orientação Pedagógica E Educacional  Avaliação De Conhecimentos De Qualquer Natureza.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'9.01','Hospedagem De Qualquer Natureza Em Hotéis  Apart-Service Condominiais  Flat  Apart-Hotéis  Hotéis Residência  Residence-Service  Suite Service  Hotelaria Marítima  Motéis  Pensões E Congêneres  Ocupação Por Temporada Com Fornecimento De Serviço (O Valor Da Alimentação E Gorjeta  Quando Incluído No Preço Da Diária  Fica Sujeito Ao Imposto Sobre Serviços).',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'9.02','Agenciamento  Organização  Promoção  Intermediação E Execução De Programas De Turismo  Passeios  Viagens  Excursões  Hospedagens E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'9.03','Guias De Turismo.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.01','Agenciamento  Corretagem Ou Intermediação De Câmbio  De Seguros  De Cartões De Crédito  De Planos De Saúde E De Planos De Previdência Privada.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.02','Agenciamento  Corretagem Ou Intermediação De Títulos Em Geral  Valores Mobiliários E Contratos Quaisquer.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.03','Agenciamento  Corretagem Ou Intermediação De Direitos De Propriedade Industrial  Artística Ou Literária.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.04','Agenciamento  Corretagem Ou Intermediação De Contratos De Arrendamento Mercantil (Leasing)  De Franquia (Franchising) E De Faturização (Factoring).',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.05','Agenciamento  Corretagem Ou Intermediação De Bens Móveis Ou Imóveis  Não Abrangidos Em Outros Itens Ou Subitens  Inclusive Aqueles Realizados No Âmbito De Bolsas De Mercadorias E Futuros  Por Quaisquer Meios.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.06','Agenciamento Marítimo.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.07','Agenciamento De Notícias.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.08','Agenciamento De Publicidade E Propaganda  Inclusive O Agenciamento De Veiculação Por Quaisquer Meios.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.09','Representação De Qualquer Natureza  Inclusive Comercial.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'10.10','Distribuição De Bens De Terceiros.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'11.01','Guarda E Estacionamento De Veículos Terrestres Automotores  De Aeronaves E De Embarcações.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'11.02','Vigilância  Segurança Ou Monitoramento De Bens E Pessoas.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'11.03','Escolta  Inclusive De Veículos E Cargas.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'11.04','Armazenamento  Depósito  Carga  Descarga  Arrumação E Guarda De Bens De Qualquer Espécie.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.01','Espetáculos Teatrais.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.02','Exibições Cinematográficas.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.03','Espetáculos Circenses.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.04','Programas De Auditório.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.05','Parques De Diversões  Centros De Lazer E Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.06','Boates  Taxi-Dancing E Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.07','Shows  Ballet  Danças  Desfiles  Bailes  Óperas  Concertos  Recitais  Festivais E Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.08','Feiras  Exposições  Congressos E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.09','Bilhares  Boliches E Diversões Eletrônicas Ou Não.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.10','Corridas E Competições De Animais.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.11','Competições Esportivas Ou De Destreza Física Ou Intelectual  Com Ou Sem A Participação Do Espectador.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.12','Execução De Música.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.13','Produção  Mediante Ou Sem Encomenda Prévia  De Eventos  Espetáculos  Entrevistas  Shows  Ballet  Danças  Desfiles  Bailes  Teatros  Óperas  Concertos  Recitais  Festivais E Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.14','Fornecimento De Música Para Ambientes Fechados Ou Não  Mediante Transmissão Por Qualquer Processo.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.15','Desfiles De Blocos Carnavalescos Ou Folclóricos  Trios Elétricos E Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.16','Exibição De Filmes  Entrevistas  Musicais  Espetáculos  Shows  Concertos  Desfiles  Óperas  Competições Esportivas  De Destreza Intelectual Ou Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'12.17','Recreação E Animação  Inclusive Em Festas E Eventos De Qualquer Natureza.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'13.01','(Vetado)',0);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'13.02','Fonografia Ou Gravação De Sons  Inclusive Trucagem  Dublagem  Mixagem E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'13.03','Fotografia E Cinematografia  Inclusive Revelação  Ampliação  Cópia  Reprodução  Trucagem E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'13.04','Reprografia  Microfilmagem E Digitalização.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'13.05','Composição Gráfica  Fotocomposição  Clicheria  Zincografia  Litografia  Fotolitografia.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.01','Lubrificação  Limpeza  Lustração  Revisão  Carga E Recarga  Conserto  Restauração  Blindagem  Manutenção E Conservação De Máquinas  Veículos  Aparelhos  Equipamentos  Motores  Elevadores Ou De Qualquer Objeto (Exceto Peças E Partes Empregadas  Que Ficam Sujeitas Ao Icms).',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.02','Assistência Técnica.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.03','Recondicionamento De MotoreS Exceto Peças E Partes Empregadas  Que Ficam Sujeitas Ao Icms).',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.04','Recauchutagem Ou Regeneração De Pneus.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.05','Restauração  Recondicionamento  Acondicionamento  Pintura  Beneficiamento  Lavagem  Secagem  Tingimento  Galvanoplastia  Anodização  Corte  Recorte  Polimento  Plastificação E Congêneres  De Objetos Quaisquer.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.06','Instalação E Montagem De Aparelhos  Máquinas E Equipamentos  Inclusive Montagem Industrial  Prestados Ao Usuário Final  Exclusivamente Com Material Por Ele Fornecido.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.07','Colocação De Molduras E Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.08','Encadernação  Gravação E Douração De Livros  Revistas E Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.09','Alfaiataria E Costura  Quando O Material For Fornecido Pelo Usuário Final  Exceto Aviamento.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.10','Tinturaria E Lavanderia.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.11','Tapeçaria E Reforma De Estofamentos Em Geral.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.12','Funilaria E Lanternagem.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'14.13','Carpintaria E Serralheria.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.01','Administração De Fundos Quaisquer  De Consórcio  De Cartão De Crédito Ou Débito E Congêneres  De Carteira De Clientes  De Cheques Pré-Datados E Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.02','Abertura De Contas Em Geral  Inclusive Conta-Corrente  Conta De Investimentos E Aplicação E Caderneta De Poupança  No País E No Exterior  Bem Como A Manutenção Das Referidas Contas Ativas E Inativas.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.03','Locação E Manutenção De Cofres Particulares  De Terminais Eletrônicos  De Terminais De Atendimento E De Bens E Equipamentos Em Geral.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.04','Fornecimento Ou Emissão De Atestados Em Geral  Inclusive Atestado De Idoneidade  Atestado De Capacidade Financeira E Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.05','Cadastro  Elaboração De Ficha Cadastral  Renovação Cadastral E Congêneres  Inclusão Ou Exclusão No Cadastro De Emitentes De Cheques Sem Fundos   Ccf Ou Em Quaisquer Outros Bancos Cadastrais.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.06','Emissão  Reemissão E Fornecimento De Avisos  Comprovantes E Documentos Em Geral  Abono De Firmas  Coleta E Entrega De Documentos  Bens E Valores  Comunicação Com Outra Agência Ou Com A Administração Central  Licenciamento Eletrônico De Veículos  Transferência De Veículos  Agenciamento Fiduciário Ou Depositário  Devolução De Bens Em Custódia.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.07','Acesso  Movimentação  Atendimento E Consulta A Contas Em Geral  Por Qualquer Meio Ou Processo  Inclusive Por Telefone  Fac-Símile  Internet E Telex  Acesso A Terminais De Atendimento  Inclusive Vinte E Quatro Horas  Acesso A Outro Banco E A Rede Compartilhada  Fornecimento De Saldo  Extrato E Demais Informações Relativas A Contas Em Geral  Por Qualquer Meio Ou Processo.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.08','Emissão  Reemissão  Alteração  Cessão  Substituição  Cancelamento E Registro De Contrato De Crédito  Estudo  Análise E Avaliação De Operações De Crédito  Emissão  Concessão  Alteração Ou Contratação De Aval  Fiança  Anuência E Congêneres  Serviços Relativos A Abertura De Crédito  Para Quaisquer Fins.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.09','Arrendamento Mercantil (Leasing) De Quaisquer Bens  Inclusive Cessão De Direitos E Obrigações  Substituição De Garantia  Alteração  Cancelamento E Registro De Contrato  E Demais Serviços Relacionados Ao Arrendamento Mercantil (Leasing).',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.10','Serviços Relacionados A Cobranças  Recebimentos Ou Pagamentos Em Geral  De Títulos Quaisquer  De Contas Ou Carnês  De Câmbio  De Tributos E Por Conta De Terceiros  Inclusive Os Efetuados Por Meio Eletrônico  Automático Ou Por Máquinas De Atendimento  Fornecimento De Posição De Cobrança  Recebimento Ou Pagamento  Emissão De Carnês  Fichas De Compensação  Impressos E Documentos Em Geral.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.11','Devolução De Títulos  Protesto De Títulos  Sustação De Protesto  Manutenção De Títulos  Reapresentação De Títulos  E Demais Serviços A Eles Relacionados.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.12','Custódia Em Geral  Inclusive De Títulos E Valores Mobiliários.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.13','Serviços Relacionados A Operações De Câmbio Em Geral  Edição  Alteração  Prorrogação  Cancelamento E Baixa De Contrato De Câmbio  Emissão De Registro De Exportação Ou De Crédito  Cobrança Ou Depósito No Exterior  Emissão  Fornecimento E Cancelamento De Cheques De Viagem  Fornecimento  Transferência  Cancelamento E Demais Serviços Relativos A Carta De Crédito De Importação  Exportação E Garantias Recebidas  Envio E Recebimento De Mensagens Em Geral Relacionadas A Operações De Câmbio.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.14','Fornecimento  Emissão  Reemissão  Renovação E Manutenção De Cartão Magnético  Cartão De Crédito  Cartão De Débito  Cartão Salário E Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.15','Compensação De Cheques E Títulos Quaisquer  Serviços Relacionados A Depósito  Inclusive Depósito Identificado  A Saque De Contas Quaisquer  Por Qualquer Meio Ou Processo  Inclusive Em Terminais Eletrônicos E De Atendimento.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.16','Emissão  Reemissão  Liquidação  Alteração  Cancelamento E Baixa De Ordens De Pagamento  Ordens De Crédito E Similares  Por Qualquer Meio Ou Processo  Serviços Relacionados À Transferência De Valores  Dados  Fundos  Pagamentos E Similares  Inclusive Entre Contas Em Geral.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.17','Emissão  Fornecimento  Devolução  Sustação  Cancelamento E Oposição De Cheques Quaisquer  Avulso Ou Por Talão.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'15.18','Serviços Relacionados A Crédito Imobiliário  Avaliação E Vistoria De Imóvel Ou Obra  Análise Técnica E Jurídica  Emissão  Reemissão  Alteração  Transferência E Renegociação De Contrato  Emissão E Reemissão Do Termo De Quitação E Demais Serviços Relacionados A Crédito Imobiliário.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'16.01','Serviços De Transporte De Natureza Municipal.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.01','Assessoria Ou Consultoria De Qualquer Natureza  Não Contida Em Outros Itens Desta Lista  Análise  Exame  Pesquisa  Coleta  Compilação E Fornecimento De Dados E Informações De Qualquer Natureza  Inclusive Cadastro E Similares.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.02','Datilografia  Digitação  Estenografia  Expediente  Secretaria Em Geral  Resposta Audível  Redação  Edição  Interpretação  Revisão  Tradução  Apoio E Infra-Estrutura Administrativa E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.03','Planejamento  Coordenação  Programação Ou Organização Técnica  Financeira Ou Administrativa.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.04','Recrutamento  Agenciamento  Seleção E Colocação De Mão-De-Obra.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.05','Fornecimento De Mão-De-Obra  Mesmo Em Caráter Temporário  Inclusive De Empregados Ou Trabalhadores  Avulsos Ou Temporários  Contratados Pelo Prestador De Serviço.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.06','Propaganda E Publicidade  Inclusive Promoção De Vendas  Planejamento De Campanhas Ou Sistemas De Publicidade  Elaboração De Desenhos  Textos E Demais Materiais Publicitários.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.07','(Vetado)',0);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.08','Franquia (Franchising).',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.09','Perícias  Laudos  Exames Técnicos E Análises Técnicas.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.10','Planejamento  Organização E Administração De Feiras  Exposições  Congressos E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.11','Organização De Festas E Recepções  Bufê (Exceto O Fornecimento De Alimentação E Bebidas  Que Fica Sujeito Ao Icms).',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.12','Administração Em Geral  Inclusive De Bens E Negócios De Terceiros.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.13','Leilão E Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.14','Advocacia.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.15','Arbitragem De Qualquer Espécie  Inclusive Jurídica.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.16','Auditoria.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.17','Análise De Organização E Métodos.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.18','Atuária E Cálculos Técnicos De Qualquer Natureza.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.19','Contabilidade  Inclusive Serviços Técnicos E Auxiliares.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.20','Consultoria E Assessoria Econômica Ou Financeira.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.21','Estatística.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.22','Cobrança Em Geral.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.23','Assessoria  Análise  Avaliação  Atendimento  Consulta  Cadastro  Seleção  Gerenciamento De Informações  Administração De Contas A Receber Ou A Pagar E Em Geral  Relacionados A Operações De Faturização (Factoring).',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'17.24','Apresentação De Palestras  Conferências  Seminários E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'18.01','Serviços De Regulação De Sinistros Vinculados A Contratos De Seguros  Inspeção E Avaliação De Riscos Para Cobertura De Contratos De Seguros  Prevenção E Gerência De Riscos Seguráveis E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'19.01','Serviços De Distribuição E Venda De Bilhetes E Demais Produtos De Loteria  Bingos  Cartões  Pules Ou Cupons De Apostas  Sorteios  Prêmios  Inclusive Os Decorrentes De Títulos De Capitalização E Congêneres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'20.01','Serviços Portuários  Ferroportuários  Utilização De Porto  Movimentação De Passageiros  Reboque De Embarcações  Rebocador Escoteiro  Atracação  Desatracação  Serviços De Praticagem  Capatazia  Armazenagem De Qualquer Natureza  Serviços Acessórios  Movimentação De Mercadorias  Serviços De Apoio Marítimo  De Movimentação Ao Largo  Serviços De Armadores  Estiva  Conferência  Logística E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'20.02','Serviços Aeroportuários  Utilização De Aeroporto  Movimentação De Passageiros  Armazenagem De Qualquer Natureza  Capatazia  Movimentação De Aeronaves  Serviços De Apoio Aeroportuários  Serviços Acessórios  Movimentação De Mercadorias  Logística E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'20.03','Serviços De Terminais Rodoviários  Ferroviários  Metroviários  Movimentação De Passageiros  Mercadorias  Inclusive     Suas Operações  Logística E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'21.01','Serviços De Registros Públicos  Cartorários E Notariais.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'22.01','Serviços De Exploração De Rodovia Mediante Cobrança De Preço Ou Pedágio Dos Usuários  Envolvendo Execução De Serviços De Conservação  Manutenção  Melhoramentos Para Adequação De Capacidade E Segurança De Trânsito  Operação  Monitoração  Assistência Aos Usuários E Outros Serviços Definidos Em Contratos  Atos De Concessão Ou De Permissão Ou Em Normas Oficiais.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'23.01','Serviços De Programação E Comunicação Visual  Desenho Industrial E Congêneres.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'24.01','Serviços De Chaveiros  Confecção De Carimbos  Placas  Sinalização Visual  Banners  Adesivos E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'25.01','Funerais  Inclusive Fornecimento De Caixão  Urna Ou Esquifes  Aluguel De Capela  Transporte Do Corpo Cadavérico  Fornecimento De Flores  Coroas E Outros Paramentos  Desembaraço De Certidão De Óbito  Fornecimento De Véu  Essa E Outros Adornos  Embalsamento  Embelezamento  Conservação Ou Restauração De Cadáveres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'25.02','Cremação De Corpos E Partes De Corpos Cadavéricos.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'25.03','Planos Ou Convênio Funerários.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'25.04','Manutenção E Conservação De Jazigos E Cemitérios.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'26.01','Serviços De Coleta  Remessa Ou Entrega De Correspondências  Documentos  Objetos  Bens Ou Valores  Inclusive Pelos Correios E Suas Agências Franqueadas  Courrier E Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'27.01','Serviços De Assistência Social.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'28.01','Serviços De Avaliação De Bens E Serviços De Qualquer Natureza.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'29.01','Serviços De Biblioteconomia.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'30.01','Serviços De Biologia  Biotecnologia E Química.',2);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'31.01','Serviços Técnicos Em Edificações  Eletrônica  Eletrotécnica  Mecânica  Telecomunicações E Congêneres.',5);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'32.01','Serviços De Desenhos Técnicos.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'33.01','Serviços De Desembaraço Aduaneiro  Comissários  Despachantes E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'34.01','Serviços De Investigações Particulares  Detetives E Congêneres.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'35.01','Serviços De Reportagem  Assessoria De Imprensa  Jornalismo E Relações Públicas.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'36.01','Serviços De Meteorologia.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'37.01','Serviços De Artistas  Atletas  Modelos E Manequins.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'38.01','Serviços De Museologia.',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'39.01','Serviços De Ourivesaria E Lapidação (Quando O Material For Fornecido Pelo Tomador Do Serviço).',3);
INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDALIQATVM) VALUES (0,:cid,201009,'40.01','Obras De Arte Sob Encomenda.',3);

END
^

/* Restore proc. body: SP_COPIA_ATIVIDADES_MUNICIPAIS */
CREATE OR ALTER PROCEDURE SP_COPIA_ATIVIDADES_MUNICIPAIS (
    CODCIDNOVA INTEGER,
    CODCIDCOPIAR INTEGER = 4445,
    REFERENCIA INTEGER = 201201)
AS
DECLARE VARIABLE WCODCID INTEGER;
DECLARE VARIABLE WSQL VARCHAR(2000);
DECLARE VARIABLE WCAMPOSINSERT VARCHAR(1000);
DECLARE VARIABLE WCAMPO VARCHAR(64);
BEGIN
  /* VERIFICA SE A CIDADE DESTINIO EXISTE */
  WSQL = 'SELECT BDCODCID FROM TCIDADE WHERE BDCODCID = '||:CODCIDNOVA;
  EXECUTE STATEMENT WSQL INTO :WCODCID;

  /* CASO A CIDADE PARA INSERIR AS ATIVIDADES NÃO EXISTA, NÃO EXECUTA O INSERT */
  IF ((WCODCID IS NULL) OR (WCODCID = 0)) THEN
    EXIT;

  /* LIMPA A TABELA DE ATIVIDADES DA CIDADE QUE VAI COPIAR 
  WSQL = 'DELETE FROM TATVMUNICIPAL WHERE BDCODCID = '||:CODCIDNOVA;
  EXECUTE STATEMENT WSQL; */

  /* OBTÉM OS CAMPOS DA TABELA DE ATIVIDADES */
  WSQL = 'SELECT R.RDB$FIELD_NAME AS BDCAMPO '||
         'FROM RDB$RELATION_FIELDS R '||
         'WHERE R.RDB$RELATION_NAME = ''TATVMUNICIPAL''';
  WCAMPOSINSERT = '';
  FOR EXECUTE STATEMENT WSQL
    INTO WCAMPO DO
      BEGIN
        IF (WCAMPO <> 'BDCODCID') THEN
          WCAMPOSINSERT = WCAMPOSINSERT||','||TRIM(WCAMPO);
      END
  /* CRIA INSERT DA TABELA DE ATIVIDADES DA CIDADE A COPIAR PARA A CIDADE NOVA */
  WSQL = 'INSERT INTO TATVMUNICIPAL (BDCODCID'||WCAMPOSINSERT||') '||
         ' SELECT '||CODCIDNOVA||WCAMPOSINSERT||' FROM TATVMUNICIPAL WHERE BDCODCID = (SELECT BDCODCID FROM TCIDADE WHERE BDCODCID = '||CODCIDCOPIAR||' and BDREFATVM = '||REFERENCIA||')';
  WSQL = WSQL || ' AND NOT EXISTS (SELECT X.BDCODATVM FROM tatvmunicipal X WHERE X.bdcodcid = '||CODCIDNOVA||' and BDREFATVM = '||REFERENCIA||')';

  EXECUTE STATEMENT wSQL;
END^


/* Restore proc. body: SP_INSERT_FERIADO */
ALTER PROCEDURE SP_INSERT_FERIADO(PRDATA DATE,
PRDESC VARCHAR(40),
PRCID INTEGER,
PRUF INTEGER)
 AS
BEGIN
  UPDATE OR INSERT INTO tferiados (bdDATAFER, bdDESCFER, BDCODCID, BDCODUF) VALUES (:prdata, :prdesc, :prcid, :pruf);
END
^

/* Restore proc. body: SP_INSERT_FOLHAAVULSA_ONLINE */
ALTER PROCEDURE SP_INSERT_FOLHAAVULSA_ONLINE(PRCODTCA INTEGER)
 AS
DECLARE VARIABLE WPLANO INTEGER;
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WCLASS VARCHAR(8);
DECLARE VARIABLE WCLASS2 VARCHAR(8);
DECLARE VARIABLE WGRUPOCOL INTEGER;
BEGIN
  /* Procedure Text */
  FOR SELECT bdcodplanoonline FROM tplano_conf_online
  INTO
    :wplano
  DO
    BEGIN
      -- insere a conta da classificação de título
      SELECT x.bdretorno FROM preenche_esquerda(:prcodtca, 8, '0') x INTO :wclass;
      wsql = 'insert into tconf_contas_online(bdcodplanoonline,bdcodtipoconta,bdcodtca,bdclassificacao,bdformula) values('||
                                              wplano||',408,'||prcodtca||','''||'02.001.000000010.T'||wclass||''','''||'LiqFolAvu('||prcodtca||',0)'''||') ';
      EXECUTE STATEMENT wsql;

      FOR SELECT bdcodgrupocla FROM tgrupoclassecol
      INTO
        :wgrupocol
      DO
        BEGIN
          SELECT x.bdretorno FROM preenche_esquerda(:wgrupocol, 8, '0') x INTO :wclass2;
          wsql = 'insert into tconf_contas_online(bdcodplanoonline,bdcodtipoconta,bdcodtca,bdcodgrupocla,bdclassificacao,bdformula) values('||
                                                  wplano||',408,'||prcodtca||','||:wgrupocol||','''||'02.001.000000010.T'||wclass||'.A'||wclass2||''','''||'LiqFolAvu('||prcodtca||','||wgrupocol||')'''||') ';
          EXECUTE STATEMENT wsql;
        END
    END
--  suspend;
END
^

/* Restore proc. body: SP_INSERT_NOVA_VERBA_ONLINE */
ALTER PROCEDURE SP_INSERT_NOVA_VERBA_ONLINE(PRCLASSIFICACAO VARCHAR(100),
PRVERBA INTEGER)
 AS
DECLARE VARIABLE WPLANO INTEGER;
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WCLAVERBA VARCHAR(100);
DECLARE VARIABLE WCLAVERBARESC VARCHAR(100);
DECLARE VARIABLE WFORMULA VARCHAR(100);
BEGIN
  /* Procedure Text */
  FOR SELECT bdcodplanoonline FROM tplano_conf_online
  INTO
    wplano
  DO
    BEGIN
      wsql = 'select x.bdclanovaverba,x.bdclanovaverbaresc from SPCLASSVERBAONLINE(null,'||''''||prclassificacao||''''||') x';

      EXECUTE STATEMENT wsql INTO wclaverba,wclaverbaresc;
      wformula = 'VALVERBA('||prverba||')';
      wformula = ''''||wformula||'''';
      wsql = 'insert into tconf_contas_online(bdcodplanoonline,bdcodtipoconta,bdcodver,bdclassificacao,bdformula) values('||
                                              wplano||',24,'||prverba||','||''''||wclaverba||''''||','||wformula||')';
      EXECUTE STATEMENT wsql;

      wformula = 'VALVERBARESC('||prverba||')';
      wformula = ''''||wformula||'''';
      wsql = 'insert into tconf_contas_online(bdcodplanoonline,bdcodtipoconta,bdcodver,bdclassificacao,bdformula) values('||
                                              wplano||',25,'||prverba||','||''''||wclaverbaresc||''''||','||wformula||')';
      EXECUTE STATEMENT wsql;
    END

--  suspend;
END
^

/* Restore proc. body: SP_INSERTS */
ALTER PROCEDURE SP_INSERTS(TABELA VARCHAR(50),
CAMPOS VARCHAR(1024),
VALORES VARCHAR(32750))
 AS
DECLARE VARIABLE wstart INTEGER;
DECLARE VARIABLE wcmd VARCHAR(32750);
DECLARE VARIABLE wpos INTEGER;
DECLARE VARIABLE wstr VARCHAR(32750);
BEGIN
  wStart = 1;
  WHILE (1=1) DO
  BEGIN
    wPOS = POSITION(' # ', valores, wStart);
    IF (wPOS = 0) THEN
      BREAK;

    wSTR = SUBSTRING(valores FROM wStart FOR wPOS - wStart);
    wStart = wPOS + 3;

    wCmd = 'insert into ' || tabela || campos || ' values ' || wSTR;
    EXECUTE STATEMENT wCmd;
  END
END
^

/* Restore proc. body: SP_LISTAR_PLANOS_ONLINE */
ALTER PROCEDURE SP_LISTAR_PLANOS_ONLINE(PRCODEMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDCODPLANOONLINE INTEGER)
 AS
DECLARE VARIABLE WCODPLANOONLINEANT INTEGER;
    BEGIN
      WCODPLANOONLINEANT = 0;
    
      FOR SELECT BDCODEMP, BDREFEMP, BDCODPLANOONLINE 
          FROM TEMPRESAS_REF 
          WHERE BDCODEMP = :PRCODEMP 
          ORDER BY BDCODEMP, BDREFEMP
      INTO
        :BDCODEMP,
        :BDREFEMP,
        :BDCODPLANOONLINE
      DO
      BEGIN
        IF (:BDCODPLANOONLINE <> :WCODPLANOONLINEANT) THEN
        BEGIN
          SUSPEND;
          WCODPLANOONLINEANT = :BDCODPLANOONLINE;
        END
      END
    END
^

/* Restore proc. body: SP_LISTAR_PLANOS_POR_REF */
ALTER PROCEDURE SP_LISTAR_PLANOS_POR_REF(PRWHEREEMP VARCHAR(32000),
PRREFINI INTEGER,
PRREFFIN INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDREFEMP INTEGER,
BDCODPLANOONLINE INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER)
 AS
DECLARE VARIABLE wsql VARCHAR(32000);
DECLARE VARIABLE wwhere VARCHAR(32000);
DECLARE VARIABLE wrefatu INTEGER;
DECLARE VARIABLE wAno INTEGER;
DECLARE VARIABLE wMes INTEGER;
BEGIN
  wrefatu = :prrefini;

  wwhere = '';
  
  IF ((:prwhereemp IS NOT NULL) AND (:prwhereemp <> '')) THEN
    wwhere = '  where ' || :prwhereemp;

  WHILE (:wrefatu <= :prreffin) DO
    BEGIN
      bdrefemp = :wrefatu;
      
      wsql =         ' select e.bdcodemp, ';
      wsql = wsql || '        e.bdcodmatriz, ';
      wsql = wsql || '        r.bdcodplanoonline, ';
      wsql = wsql || '        r.bdcodplapadrao, ';
      wsql = wsql || '        r.bdcodhist ';
      wsql = wsql || ' from ';
      wsql = wsql || ' ( ';
      wsql = wsql || '     select emp.bdcodemp, ';
      wsql = wsql || '            coalesce(emp.bdcodmatriz, emp.bdcodemp) BDCODMATRIZ, ';
      wsql = wsql || '            coalesce ';
      wsql = wsql || '            ( ';
      wsql = wsql || '                ( ';
      wsql = wsql || '                    select first 1 x.bdrefemp from tempresas_ref x ';
      wsql = wsql || '                    where (x.bdcodemp = emp.bdcodemp) and ';
      wsql = wsql || '                          (x.bdcodplanoonline is not null) and ';
      wsql = wsql || '                          (x.bdcodplapadrao is not null) and ';
      wsql = wsql || '                          (x.bdcodhist is not null) and ';
      wsql = wsql || '                          (CAST(X.BDREFEMP as VARCHAR(6)) <= ' || :WREFATU || ') ';
      wsql = wsql || '                    order by x.bdrefemp desc ';
      wsql = wsql || '                ), ';
      wsql = wsql || '                ( ';
      wsql = wsql || '                    select first 1 x.bdrefemp from tempresas_ref x ';
      wsql = wsql || '                    where (x.bdcodemp = emp.bdcodemp) and ';
      wsql = wsql || '                          (x.bdcodplanoonline is not null) and ';
      wsql = wsql || '                          (x.bdcodplapadrao is not null) and ';
      wsql = wsql || '                          (x.bdcodhist is not null) and ';      
      wsql = wsql || '                          (cast(X.BDREFEMP as varchar(6)) > ' || :WREFATU || ') ';
      wsql = wsql || '                    order by x.bdrefemp ';
      wsql = wsql || '                ), ';
      wsql = wsql || '                ( ';
      wsql = wsql || '                    select first 1 x.bdrefemp from tempresas_ref x ';
      wsql = wsql || '                    where (x.bdcodemp = emp.bdcodemp) ';
      wsql = wsql || '                    order by x.bdrefemp ';
      wsql = wsql || '                ) ';
      wsql = wsql || '            ) bdRefEmp ';
      wsql = wsql || '     from tempresas emp ' || wwhere;
      wsql = wsql || ' ) e ';
      wsql = wsql || ' inner join tempresas_ref r using (bdcodemp, bdrefemp) ';
      
      FOR EXECUTE STATEMENT wsql 
      INTO
        :bdcodemp,
        :bdcodmatriz,
        :bdcodplanoonline,
        :bdcodplapadrao,
        :bdcodhist
      DO
        BEGIN
          SUSPEND;
        END
      
      wrefatu = :wrefatu + 1;

      wMes = CAST(RIGHT(:wRefAtu, 2) AS INTEGER);

      IF (:wMes > 12) THEN
        BEGIN
          wAno = CAST(LEFT(:wRefAtu, 4) AS INTEGER);

          wAno = wAno + 1;

          wRefAtu = CAST(wAno || '01' AS INTEGER);
        END 
    END
END
^

/* Restore proc. body: SP_MANUTENCAO_TCALCVESP */
ALTER PROCEDURE SP_MANUTENCAO_TCALCVESP(PRTIPOCALC INTEGER,
PRCLASSITEM VARCHAR(20),
PRDESCITEM VARCHAR(40),
PRFORMULAITEM VARCHAR(350),
PRCODVERBASE INTEGER,
PRCODVERESP INTEGER,
PRFORMULADABASE VARCHAR(5))
 AS
DECLARE VARIABLE WCODCIT INTEGER;
DECLARE VARIABLE WCODCVE INTEGER;
BEGIN
  SELECT FIRST 1 bdcodcit FROM VRH_BASE_TCALCITENS WHERE bdcodctp = :prtipocalc AND bdclasscit = :prclassitem INTO :wcodcit;

  IF (wcodcit IS NOT NULL AND wcodcit <> 0) THEN
     BEGIN
       INSERT INTO VRH_BASE_TCALCITENS (BDCODCTP,BDCLASSCIT,BDDESCCIT,BDFORMCIT) VALUES (:prtipocalc, :prclassitem, :prdescitem, :prformulaitem);
       SELECT COALESCE(MAX(BDCODCIT), 1) FROM VRH_BASE_TCALCITENS WHERE BDCODCTP = :prtipocalc INTO :wcodcit;
     END

  IF (wcodcit IS NOT NULL AND wcodcit <> 0) THEN
     BEGIN
       SELECT FIRST 1 bdcodcve FROM VRH_BASE_TCALCVESP WHERE bdcodctp = :prtipocalc AND bdcodcit = :wcodcit AND bdcodvercve = :prcodveresp AND bdcodver = :prcodverbase INTO :wcodcve;
       IF (wcodcve IS NULL OR (wcodcve = 0)) THEN
          INSERT INTO VRH_BASE_TCALCVESP (BDCODCTP,BDCODCIT,BDCODVERCVE,BDCODVER,BDFORMULABASECVE) VALUES (:prtipocalc, :wcodcit, :prcodveresp, :prcodverbase, :prformuladabase);
     END
--  suspend;
END
^

/* Restore proc. body: SP_MASCARA_CODNAT */
ALTER PROCEDURE SP_MASCARA_CODNAT(PRCODNAT INTEGER)
 RETURNS(BDNATUREZA VARCHAR(9),
BDCODNAT INTEGER)
 AS
BEGIN
  BDNATUREZA = NULL;
  BDCODNAT = prcodnat;

  IF ((prcodnat IS NOT NULL) AND (prcodnat <> 0)) THEN
     BEGIN
       BDNATUREZA = SUBSTRING(prcodnat FROM 1 FOR 1);
       BDNATUREZA = BDNATUREZA||'.';
       BDNATUREZA = BDNATUREZA||SUBSTRING(prcodnat FROM 2 FOR 3);
       BDNATUREZA = BDNATUREZA||'-';
       BDNATUREZA = BDNATUREZA||SUBSTRING(prcodnat FROM 5 FOR 3);
     END

  SUSPEND;
END
^

/* Restore proc. body: SP_MODELOS_GERADOR_REL */
ALTER PROCEDURE SP_MODELOS_GERADOR_REL AS
DECLARE VARIABLE WCODIGO INTEGER;
DECLARE VARIABLE WDESC VARCHAR(1000);
DECLARE VARIABLE WRTF BLOB SUB_TYPE 0 SEGMENT SIZE 80;
DECLARE VARIABLE WFR3 BLOB SUB_TYPE 0 SEGMENT SIZE 80;
BEGIN
  /* Procedure Text */
--  suspend;
  DELETE FROM TMODELO_REL;

  FOR SELECT BDCODREP,BDDESCREP,BDRTFREP,BDFR3REP FROM trepositorio INTO
    : wcodigo, : wdesc, :wrtf, :wfr3 DO
  BEGIN
     INSERT INTO TMODELO_REL (BDCODREP, BDCHAVE, BDNOMEMOD, BDRTFREP, BDFR3REP)
                           VALUES (:wcodigo, NULL, :wdesc, :wrtf, : wfr3);

  END
END
^

/* Restore proc. body: SP_NOME_TERCEIRO */
ALTER PROCEDURE SP_NOME_TERCEIRO(PRREF INTEGER,
PRTER INTEGER)
 RETURNS(BDCODTER INTEGER,
BDNOME VARCHAR(200))
 AS
BEGIN
  /* Procedure Text */
  EXECUTE PROCEDURE sp_seta_competencia(prref,NULL,NULL);

  bdcodter = prter;

  SELECT ter.bdnome FROM vw_tterceiro_simples ter WHERE ter.bdcodter = :prter INTO bdnome;

  SUSPEND;
END
^

/* Restore proc. body: SP_PBM */
ALTER PROCEDURE SP_PBM(PREMP INTEGER,
PRREF INTEGER)
 RETURNS(BDEMP INTEGER,
BDREF INTEGER,
BDOK INTEGER)
 AS
BEGIN
  /* Procedure Text */
  /* BDOK */
  bdemp = premp;
  bdref = prref;

  EXECUTE PROCEDURE sp_seta_competencia(prref);
  bdok = 0;

  FOR SELECT COALESCE(BDCODCONFBLOCOP,0) FROM VW_VEF_BASE_TEMPPARGER WHERE bdcodemp = :premp INTO bdok DO
    BEGIN
    END

  IF (bdok <> 0) THEN
     bdok = 1;

  SUSPEND;
END
^

/* Restore proc. body: SP_PRAZO_EXPERIENCIA_SITUACAO */
create or alter procedure SP_PRAZO_EXPERIENCIA_SITUACAO (
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000),
    PRDIASPRAZO1COL integer,
    PRDIASPRAZO2COL integer,
    PRULTDIAMES date = null,
    PRCODSIT integer = 0,
    PRTABLETEMP integer = 0,
    PRRETORNO boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATAFIMPRAZO1COL date,
    BDDATAFIMPRAZO2COL date)
as
declare variable WSQL varchar(32000);
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WDIASSIT integer;
declare variable WDATAINISSIT date;
declare variable WDATAFIMSIT date;
declare variable WDATAPRAZO1 date;
declare variable WDATAPRAZO2 date;
declare variable WDATARESC date;
declare variable WCODSIT integer;
declare variable WCODSITATU integer;
declare variable WTOTDIASSIT integer;
declare variable WTOTDIASSIT2 integer;
declare variable WPRORROGCONTRATO DM_BOOLEAN;
declare variable WDATAPRAZO1ATU date;
declare variable WDATAPRAZO2ATU date;
declare variable WULTDIA integer;
declare variable WPOS integer;
BEGIN
  if (prultdiames is null) then
     begin
       select CURRENT_DATE from rdb$database into :prultdiames;
       select ULTDIA from ULTIMO_DIA_MES(CAST(EXTRACT(MONTH FROM :prultdiames) as SMALLINT), CAST(EXTRACT(YEAR FROM :prultdiames) as INTEGER)) into :wultdia;
       prultdiames = CAST((LPAD(EXTRACT(MONTH FROM :prultdiames), 2, '0')||'-'||LPAD(:wultdia, 2, '0')||'-'||LPAD(EXTRACT(YEAR FROM :prultdiames), 4, '0')) AS DATE);
     end

  wPos = 0;
  if (prcodemp <> null) then --Sol.155318 LuizCovre 06/10/2021
     execute statement 'select * from pos(''in (select bdcodemp from tmp_empresas_select)'', '''||prcodemp||''')' into wPos;

  if (prtabletemp = 1) then
     begin
       wSql = 'delete from TEMP_PRAZO_EXP_COL P';
       if (wPos > 0) then
          wSql = wsql||' join tmp_empresas_select f on (p.bdcodemp = f.bdcodemp and p.bdcodcol = f.bdcodcol)';
       else
       if (coalesce(prcodemp,'') <> '') then
          wSql = wsql||' where '||prCodEmp;
        execute statement wSql;
     end

  wsql = 'select '||
            'SIT.BDCODEMP, SIT.BDCODCOL, SIT.BDDIASSIT, SIT.BDDATAINISIT, SIT.BDDATAFIMSIT, ';

  if (prdiasprazo1col is not null ) then
     begin
       wsql = wsql||
              'case when '||prdiasprazo1col||' > 0 then COL.BDDATAADMCOL + '||prdiasprazo1col||' - 1 '||
                   'else CAST(null as date) end BDDATAFIMPRAZO1COL, ';
     end
  else
     wsql = wsql||
            'case when coalesce(COL_ADM.BDDIASPRAZO1COL, 0) > 0 then COL.BDDATAADMCOL + coalesce(COL_ADM.BDDIASPRAZO1COL - 1, 0) '||
                 'else CAST(null as date) end BDDATAFIMPRAZO1COL, ';

  if (prdiasprazo2col is not null ) then
     begin
       if (prdiasprazo1col is not null) then
          begin
            wsql = wsql||
                   'case when '||prdiasprazo2col||' > 0 then COL.BDDATAADMCOL + '||prdiasprazo1col||' + '||prdiasprazo2col||' - 1 '||
                        'else CAST(null as date) end BDDATAFIMPRAZO2COL, ';
          end
       else
          begin
            wsql = wsql||
                   'case when '||prdiasprazo2col||' > 0 then COL.BDDATAADMCOL + coalesce(COL_ADM.BDDIASPRAZO1COL, 0) + '||prdiasprazo2col||' - 1 '||
                        'else CAST(null as date) end BDDATAFIMPRAZO2COL, ';
          end
     end
  else
     begin
       if (prdiasprazo1col is not null) then
          wsql = wsql||
                 'case when coalesce(COL_ADM.BDDIASPRAZO2COL, 0) > 0 then COL.BDDATAADMCOL + '||prdiasprazo1col||' + COL_ADM.BDDIASPRAZO2COL - 1 '||
                      'else CAST(null as date) end BDDATAFIMPRAZO2COL, ';
       else
          wsql = wsql||
                 'case when coalesce(COL_ADM.BDDIASPRAZO1COL, 0) > 0 and coalesce(COL_ADM.BDDIASPRAZO2COL, 0) > 0 then COL.BDDATAADMCOL + coalesce(COL_ADM.BDDIASPRAZO1COL, 0) + coalesce(COL_ADM.BDDIASPRAZO2COL - 1, 0) '||
                      'else CAST(null as date) end BDDATAFIMPRAZO2COL, ';
     end

  wsql = wsql||
            'RESC.BDDATARESCISAO, '||
            'SIT.BDCODSIT '||
         'from VRH_EMP_TSITCOL SIT '||
         'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = SIT.BDCODEMP and COL.BDCODCOL = SIT.BDCODCOL) '||
         'join VW_VRH_EMP_TCOL_ADM COL_ADM on (COL_ADM.BDCODEMP = SIT.BDCODEMP and COL_ADM.BDCODCOL = SIT.BDCODCOL) '||
         'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = SIT.BDCODEMP and RESC.BDCODCOL = SIT.BDCODCOL) '||
         'where ';

  if (prdiasprazo1col is not null) then
     wsql = wsql||'(('||prdiasprazo1col||' > 0 and SIT.BDDATAINISIT <= (COL.BDDATAADMCOL + '||prdiasprazo1col||' - 1)) ';
  else
     wsql = wsql||'((coalesce(COL_ADM.BDDIASPRAZO1COL, 0) > 0 and SIT.BDDATAINISIT <= (COL.BDDATAADMCOL + COL_ADM.BDDIASPRAZO1COL - 1)) ';
  if (prdiasprazo2col is not null) then
     begin
       if (prdiasprazo1col is not null) then
          wsql = wsql||'or ('||prdiasprazo2col||' > 0 and SIT.BDDATAINISIT <= (COL.BDDATAADMCOL + '||prdiasprazo1col||' - 1 + '||prdiasprazo2col||' - 1) ';
       else
          wsql = wsql||'or ('||prdiasprazo2col||' > 0 and SIT.BDDATAINISIT <= (COL.BDDATAADMCOL + coalesce(COL_ADM.BDDIASPRAZO1COL - 1, 0) + '||prdiasprazo2col||' - 1) ';
     end
  else
  if (prdiasprazo1col is not null) then
     wsql = wsql||'or (coalesce(COL_ADM.BDDIASPRAZO2COL, 0) > 0 and SIT.BDDATAINISIT <= (COL.BDDATAADMCOL + '||prdiasprazo1col||' - 1 + COL_ADM.BDDIASPRAZO2COL - 1) ';
  else
     wsql = wsql||'or (coalesce(COL_ADM.BDDIASPRAZO1COL, 0) > 0 and coalesce(COL_ADM.BDDIASPRAZO2COL, 0) > 0';

     wsql = wsql||'))';

  if (wPos > 0) then
    begin
      wsql = wsql||' and SIT.BDCODEMP in (select bdcodemp from tmp_empresas_select) ';
    end
  else
  if (coalesce(prcodemp, '') <> '') then
     begin
       wsql = wsql||' and '||replace(upper(prcodemp), 'BDCODEMP', 'SIT.BDCODEMP');

       if (coalesce(prcodcol, '') <> '') then
          wsql = wsql||' and '||replace(upper(prcodcol), 'BDCODCOL', 'SIT.BDCODCOL');
     end

  if (coalesce(prcodsit, 0) <> 0) then
     wsql = wsql||' and SIT.BDCODSIT = '||prcodsit;

  wsql = wsql||' order by SIT.BDCODEMP, SIT.BDCODCOL ';

  wempatu      = 0;
  wcolatu      = 0;
  wcodsitatu   = 0;
  wtotdiassit  = 0;
  wtotdiassit2 = 0;

  for execute statement wsql into :wcodemp, :wcodcol, :wdiassit, :wdatainissit, :wdatafimsit, :wdataprazo1, :wdataprazo2, :wdataresc, :wcodsit
  do
    begin
      wprorrogcontrato = null;
      select first 1 BDPRORROGACONTRATO from VRH_BASE_TPREPSIT_DIA where BDCODSIT = :wcodsit and BDDATASTD <= :wdatainissit order by BDDATASTD DESC into :wprorrogcontrato;
      wprorrogcontrato = upper(coalesce(wprorrogcontrato, 'FALSE'));

      if (wprorrogcontrato = 'TRUE') then
         begin
          if ((wempatu <> wcodemp) or (wcolatu <> wcodcol)) then --Sol.162391 LuizCovre 24/06/2022
           begin
              wtotdiassit  = 0;
              wtotdiassit2 = 0;
           end

              wempatu    = wcodemp;
              wcolatu    = wcodcol;
              wcodsitatu = wcodsit; --Sol#227498 Davi Jedrzejczyk - 06/10/2025
     
           if (((wempatu <> wcodemp) or (wcolatu <> wcodcol)) and ((wtotdiassit > 0) or (wtotdiassit2 > 0)) ) then
              begin
                if ((wcodsit <> 1) and (wcodsit <> 11)) then
                  begin
                    wdataprazo1atu = wdataprazo1atu + wtotdiassit;
                    wdataprazo2atu = wdataprazo2atu + wtotdiassit + wtotdiassit2;
                   end

                BDCODEMP           = wempatu;
                BDCODCOL           = wcolatu;
                BDDATAFIMPRAZO1COL = wdataprazo1atu;
                BDDATAFIMPRAZO2COL = wdataprazo2atu;
                if (prtabletemp = 1) then
                   insert into TEMP_PRAZO_EXP_COL(BDCODEMP,BDCODCOL,BDDATAFIMPRAZO1COL, BDDATAFIMPRAZO2COL) values (:wempatu,:wcolatu,:wdataprazo1atu,:wdataprazo2atu);
                else
                suspend;

                wtotdiassit  = 0;
                wtotdiassit2 = 0;
                wempatu      = wcodemp;
                wcolatu      = wcodcol;
              end
     
           wdataprazo1atu = wdataprazo1;
           wdataprazo2atu = wdataprazo2;

           if (wdatafimsit is not null) then
              begin
                if (wdatainissit <= wdataprazo1 + wtotdiassit) then
                   wtotdiassit = wtotdiassit + wdiassit;
                else
                if (wdatainissit <= wdataprazo2 + wtotdiassit + wtotdiassit2) then
                   wtotdiassit2 = wtotdiassit2 + wdiassit;
              end
           else
              begin
                if (wdataresc is not null and wdataresc < prultdiames) then
                   begin
                     if (wdatainissit <= wdataprazo1 + wtotdiassit) then
                        wtotdiassit = wtotdiassit + (wdataresc - wdatainissit + 1);
                     else
                     if (wdatainissit <= wdataprazo2 + wtotdiassit + wtotdiassit2) then
                        wtotdiassit2 = wtotdiassit2 + (wdataresc - wdatainissit + 1);
                   end
                else
                   begin
                     if (wdatainissit <= wdataprazo1 + wtotdiassit) then
                        wtotdiassit = wtotdiassit + (prultdiames - wdatainissit + 1);
                     else
                     if (wdatainissit <= wdataprazo2 + wtotdiassit + wtotdiassit2) then
                        wtotdiassit2 = wtotdiassit2 + (prultdiames - wdatainissit + 1);
                   end
              end
             if (prtabletemp = 1 and (wtotdiassit > 0 or wtotdiassit2 > 0)) then
              begin
                wdataprazo1atu = wdataprazo1atu + wtotdiassit;
                wdataprazo2atu = wdataprazo2atu + wtotdiassit + wtotdiassit2;
                insert into TEMP_PRAZO_EXP_COL(BDCODEMP,BDCODCOL,BDDATAFIMPRAZO1COL, BDDATAFIMPRAZO2COL) values (:wempatu,:wcolatu,:wdataprazo1atu,:wdataprazo2atu);
              end
         end
    end

  if (wempatu <> 0 and wcolatu <> 0 and ((wtotdiassit > 0) or (wtotdiassit2 > 0)) ) then
     begin                                               --Sol:227498 -  Davi Jedrzejczyk
       if ((wcodsitatu <> 1) and (wcodsitatu <> 11) and (wdatainissit <= prultdiames)) then
         begin
           wdataprazo1atu = wdataprazo1atu + wtotdiassit;
           wdataprazo2atu = wdataprazo2atu + wtotdiassit + wtotdiassit2;
         end

       BDCODEMP           = wempatu;
       BDCODCOL           = wcolatu;
       BDDATAFIMPRAZO1COL = wdataprazo1atu;
       BDDATAFIMPRAZO2COL = wdataprazo2atu;
     end
  if (prRetorno) then
     suspend;
end^

/* Restore proc. body: SP_PROPORC_VALORES */
ALTER PROCEDURE SP_PROPORC_VALORES(PRBASETOTAL NUMERIC(15,6),
PRVALOR NUMERIC(15,6),
PRBASE01 NUMERIC(15,6),
PRBASE02 NUMERIC(15,6),
PRBASE03 NUMERIC(15,6),
PRBASE04 NUMERIC(15,6),
PRBASE05 NUMERIC(15,6),
PRBASE06 NUMERIC(15,6),
PRBASE07 NUMERIC(15,6),
PRBASE08 NUMERIC(15,6))
 RETURNS(BDVALOR01 NUMERIC(15,6),
BDVALOR02 NUMERIC(15,6),
BDVALOR03 NUMERIC(15,6),
BDVALOR04 NUMERIC(15,6),
BDVALOR05 NUMERIC(15,6),
BDVALOR06 NUMERIC(15,6),
BDVALOR07 NUMERIC(15,6),
BDVALOR08 NUMERIC(15,6))
 AS
DECLARE VARIABLE WAUX NUMERIC(15,6);
DECLARE VARIABLE WSOMA NUMERIC(15,6);
DECLARE VARIABLE WDIFERENCA NUMERIC(15,6);
DECLARE VARIABLE WMUDOU INTEGER;
BEGIN
  /* Procedure Text */
  bdvalor01 = 0;
  bdvalor02 = 0;
  bdvalor03 = 0;
  bdvalor04 = 0;
  bdvalor05 = 0;
  bdvalor06 = 0;
  bdvalor07 = 0;
  bdvalor08 = 0;

  IF (prbase01 IS NULL) THEN
     prbase01 = 0;

  IF (prbase02 IS NULL) THEN
     prbase02 = 0;

  IF (prbase03 IS NULL) THEN
     prbase03 = 0;

  IF (prbase04 IS NULL) THEN
     prbase04 = 0;

  IF (prbase05 IS NULL) THEN
     prbase05 = 0;

  IF (prbase06 IS NULL) THEN
     prbase06 = 0;

  IF (prbase07 IS NULL) THEN
     prbase07 = 0;

  IF (prbase08 IS NULL) THEN
     prbase08 = 0;

  IF (prbase01 > 0) THEN
     BEGIN
       waux = (prvalor / prbasetotal);
       waux = (prbase01 * waux);
       bdvalor01 = CAST(waux - 0.005 AS NUMERIC(15,2));
     END

  IF (prbase02 > 0) THEN
     BEGIN
       waux = (prvalor / prbasetotal);
       waux = (prbase02 * waux);
       bdvalor02 = CAST(waux - 0.005 AS NUMERIC(15,2));
     END

  IF (prbase03 > 0) THEN
     BEGIN
       waux = (prvalor / prbasetotal);
       waux = (prbase03 * waux);
       bdvalor03 = CAST(waux - 0.005 AS NUMERIC(15,2));
     END

  IF (prbase04 > 0) THEN
     BEGIN
       waux = (prvalor / prbasetotal);
       waux = (prbase04 * waux);
       bdvalor04 = CAST(waux - 0.005 AS NUMERIC(15,2));
     END

  IF (prbase05 > 0) THEN
     BEGIN
       waux = (prvalor / prbasetotal);
       waux = (prbase05 * waux);
       bdvalor05 = CAST(waux - 0.005 AS NUMERIC(15,2));
     END

  IF (prbase06 > 0) THEN
     BEGIN
       waux = (prvalor / prbasetotal);
       waux = (prbase06 * waux);
       bdvalor06 = CAST(waux - 0.005 AS NUMERIC(15,2));
     END

  IF (prbase07 > 0) THEN
     BEGIN
       waux = (prvalor / prbasetotal);
       waux = (prbase07 * waux);
       bdvalor07 = CAST(waux - 0.005 AS NUMERIC(15,2));
     END

  IF (prbase08 > 0) THEN
     BEGIN
       waux = (prvalor / prbasetotal);
       waux = (prbase08 * waux);
       bdvalor08 = CAST(waux - 0.005 AS NUMERIC(15,2));
     END

  wsoma = bdvalor01 + bdvalor02 + bdvalor03 + bdvalor04 + bdvalor05 + bdvalor06 + bdvalor07 + bdvalor08;

  IF (wsoma <> prvalor) THEN
     BEGIN
       wmudou = 0;
       IF (wsoma < prvalor) THEN
          wdiferenca = 1;
       ELSE
          wdiferenca = -1;

       WHILE ((wsoma <> prvalor) AND (wmudou = 0)) DO
          BEGIN
            wmudou = 1;

            IF ((prbase01 <> 0) AND (wsoma <> prvalor)) THEN
               BEGIN
                 wmudou = 0;
                 bdvalor01 = bdvalor01 + (0.01 * wdiferenca);
                 wsoma = wsoma + (0.01 * wdiferenca);
               END

            IF ((prbase02 <> 0) AND (wsoma <> prvalor)) THEN
               BEGIN
                 wmudou = 0;
                 bdvalor02 = bdvalor02 + (0.01 * wdiferenca);
                 wsoma = wsoma + (0.01 * wdiferenca);
               END

            IF ((prbase03 <> 0) AND (wsoma <> prvalor)) THEN
               BEGIN
                 wmudou = 0;
                 bdvalor03 = bdvalor03 + (0.01 * wdiferenca);
                 wsoma = wsoma + (0.01 * wdiferenca);
               END

            IF ((prbase04 <> 0) AND (wsoma <> prvalor)) THEN
               BEGIN
                 wmudou = 0;
                 bdvalor04 = bdvalor04 + (0.01 * wdiferenca);
                 wsoma = wsoma + (0.01 * wdiferenca);
               END

            IF ((prbase05 <> 0) AND (wsoma <> prvalor)) THEN
               BEGIN
                 wmudou = 0;
                 bdvalor05 = bdvalor05 + (0.01 * wdiferenca);
                 wsoma = wsoma + (0.01 * wdiferenca);
               END

            IF ((prbase06 <> 0) AND (wsoma <> prvalor)) THEN
               BEGIN
                 wmudou = 0;
                 bdvalor06 = bdvalor06 + (0.01 * wdiferenca);
                 wsoma = wsoma + (0.01 * wdiferenca);
               END

            IF ((prbase07 <> 0) AND (wsoma <> prvalor)) THEN
               BEGIN
                 wmudou = 0;
                 bdvalor07 = bdvalor07 + (0.01 * wdiferenca);
                 wsoma = wsoma + (0.01 * wdiferenca);
               END

            IF ((prbase08 <> 0) AND (wsoma <> prvalor)) THEN
               BEGIN
                 wmudou = 0;
                 bdvalor08 = bdvalor08 + (0.01 * wdiferenca);
                 wsoma = wsoma + (0.01 * wdiferenca);
               END
          END
     END

  SUSPEND;
END
^

/* Restore proc. body: SP_REF_TRIMESTRE */
ALTER PROCEDURE SP_REF_TRIMESTRE(PRREF INTEGER)
 RETURNS(BDTRIMESTRE INTEGER,
BDREF INTEGER)
 AS
BEGIN
  /* Procedure Text */
  bdtrimestre = 0;
  bdref = prref;

  IF ((prref IS NOT NULL) AND (prref <> 0)) THEN
     BEGIN
       bdtrimestre = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
       IF (bdtrimestre <= 3) THEN
          bdtrimestre = 1;
       ELSE IF (bdtrimestre <= 6) THEN
          bdtrimestre = 2;
       ELSE IF (bdtrimestre <= 9) THEN
          bdtrimestre = 3;
       ELSE IF (bdtrimestre <= 12) THEN
          bdtrimestre = 4;
     END

  SUSPEND;
END
^

/* Restore proc. body: SP_REL_CONSULTA_CONFIGURAVEL */
ALTER PROCEDURE SP_REL_CONSULTA_CONFIGURAVEL(PRCOLUNAS INTEGER,
PRMATRIZ INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREF INTEGER,
BDMESEXTENSO VARCHAR(20),
BDCOL01 NUMERIC(15,2),
BDCOL02 NUMERIC(15,2),
BDCOL03 NUMERIC(15,2),
BDCOL04 NUMERIC(15,2),
BDCOL05 NUMERIC(15,2),
BDCOL06 NUMERIC(15,2),
BDCOL07 NUMERIC(15,2),
BDCOL08 NUMERIC(15,2),
BDCODMATRIZ INTEGER,
BDQUEBRAQUADRO INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WCODQUADRO INTEGER;
DECLARE VARIABLE WINDICE INTEGER;
DECLARE VARIABLE WMES CHAR(2);
DECLARE VARIABLE WANO CHAR(4);
DECLARE VARIABLE WEMP INTEGER;
DECLARE VARIABLE WREF INTEGER;
BEGIN
  /*
    #6566:
    modificação para aceitar mais de 8 colunas no relatório
  */

  /* giovanni */

  /* Procedure Text */

--  wsql = 'select bdcodemp, bdref, bdcodqplaconsconf,  bdvalor from VEF_REL_CONS_ANUAL_CONF where bdordem < 9 order by bdcodemp, bdref , bdcodplaconsconf, bdcodqplaconsconf, bdordem ';


  /* prmatriz > 0 quer dizer que esta detalhando matriz e filial e o conteudo e o da matriz*/

  IF (prmatriz IS NULL) THEN
     prmatriz = 0;


  wsql = 'select bdcodemp, bdref, bdcodqplaconsconf,  bdvalor, bdcodmatriz from VEF_REL_CONS_ANUAL_CONF order by bdcodemp, bdref , bdcodplaconsconf, bdcodqplaconsconf, bdordem ';

  --#6566
  --if (prcolunas > 8) then
  --   prcolunas = 8;

  windice = 1;
  bdquebraquadro = 0;
  wemp = 0;
  wref = 0;

  bdcol01 = NULL;
  bdcol02 = NULL;
  bdcol03 = NULL;
  bdcol04 = NULL;
  bdcol05 = NULL;
  bdcol06 = NULL;
  bdcol07 = NULL;
  bdcol08 = NULL;


  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdref,
    wcodquadro,
    wvalor,
    bdcodmatriz
  DO
   BEGIN

    --#6566, se mudou de empresa precisa voltar o indice para 1, e a quebra de quadros para 0
    IF ((wemp <> bdcodemp) OR (wref <> bdref)) THEN
      BEGIN
        wemp = :bdcodemp;
        wref = :bdref;
        windice = 1;
        bdquebraquadro = 0;
      END

    IF (prmatriz > 0) THEN
       bdcodemp = prmatriz;

    wano = SUBSTRING(bdref FROM 1 FOR 4);
    wmes = SUBSTRING(bdref FROM 5 FOR 2);

    IF  (windice <= prcolunas)  THEN
      BEGIN

        IF (windice = 1 + (bdquebraquadro * 8)) THEN
           bdcol01 = wvalor;
        ELSE
        IF (windice = 2 + (bdquebraquadro * 8)) THEN
           bdcol02 = wvalor;
        ELSE
        IF (windice = 3 + (bdquebraquadro * 8)) THEN
           bdcol03 = wvalor;
        ELSE
        IF (windice = 4 + (bdquebraquadro * 8)) THEN
           bdcol04 = wvalor;
        ELSE
        IF (windice = 5 + (bdquebraquadro * 8)) THEN
           bdcol05 = wvalor;
        ELSE
        IF (windice = 6 + (bdquebraquadro * 8)) THEN
           bdcol06 = wvalor;
        ELSE
        IF (windice = 7 + (bdquebraquadro * 8)) THEN
           bdcol07 = wvalor;
        ELSE
        IF (windice = 8 + (bdquebraquadro * 8)) THEN
           bdcol08 = wvalor;
      END

    --#6566
--    if  (windice = prcolunas)  then
    IF  ((MOD(windice, 8) = 0) OR (windice = prcolunas)) THEN
      BEGIN
        IF (wmes = '01') THEN
           bdmesextenso =  'Janeiro / ' || wano;
        ELSE
        IF (wmes = '02') THEN
           bdmesextenso =  'Fevereiro / ' || wano;
        ELSE
        IF (wmes = '03') THEN
           bdmesextenso =  'Março / ' || wano;
        ELSE
        IF (wmes = '04') THEN
           bdmesextenso =  'Abril / ' || wano;
        ELSE
        IF (wmes = '05') THEN
           bdmesextenso =  'Maio / ' || wano;
        ELSE
        IF (wmes = '06') THEN
           bdmesextenso =  'Junho / ' || wano;
        ELSE
        IF (wmes = '07') THEN
           bdmesextenso =  'Julho / ' || wano;
        ELSE
        IF (wmes = '08') THEN
           bdmesextenso =  'Agosto / ' || wano;
        ELSE
        IF (wmes = '09') THEN
           bdmesextenso =  'Setembro / ' || wano;
        ELSE
        IF (wmes = '10') THEN
           bdmesextenso =  'Outubro / ' || wano;
        ELSE
        IF (wmes = '11') THEN
           bdmesextenso =  'Novembro / ' || wano;
        ELSE
        IF (wmes = '12') THEN
           bdmesextenso =  'Dezembro / ' || wano;

        SUSPEND;
--        windice = 1; #6566
        windice = windice + 1;
        bdquebraquadro = ((windice - 1) / 8);

        bdcol01 = NULL;
        bdcol02 = NULL;
        bdcol03 = NULL;
        bdcol04 = NULL;
        bdcol05 = NULL;
        bdcol06 = NULL;
        bdcol07 = NULL;
        bdcol08 = NULL;
      END
     ELSE
       windice = windice + 1;
   END
END
^

/* Restore proc. body: SP_REL_CONSULTA_CONFIGURAVEL2 */
create or alter procedure SP_REL_CONSULTA_CONFIGURAVEL2 (
    PRNAOIMPRIMEZERADO varchar(5) = '',
    PRDECLARACAO varchar(5) = '')
returns (
    BDCODMATRIZ integer,
    BDCODEMP integer,
    BDCODPLANO integer,
    BDCODQUADRO integer,
    BDREF integer,
    BDMESEXTENSO varchar(20),
    BDCOL01 numeric(15,2),
    BDCOL02 numeric(15,2),
    BDCOL03 numeric(15,2),
    BDCOL04 numeric(15,2),
    BDCOL05 numeric(15,2),
    BDCOL06 numeric(15,2),
    BDCOL07 numeric(15,2),
    BDCOL08 numeric(15,2),
    BDLINHA integer,
    BDTITULOS varchar(1280), 
    BDMEDIA01 numeric(15,2),
    BDMEDIA02 numeric(15,2),
    BDMEDIA03 numeric(15,2),
    BDMEDIA04 numeric(15,2),
    BDMEDIA05 numeric(15,2),
    BDMEDIA06 numeric(15,2),
    BDMEDIA07 numeric(15,2),
    BDMEDIA08 numeric(15,2))
as
declare variable WVALOR numeric(15,2);
declare variable WCOLUNAATUAL integer;
declare variable WMES char(2);
declare variable WANO char(4);
declare variable WINDICE integer;
declare variable WNUMCOLUNAS integer;
declare variable WNUMLINHAS integer;
declare variable WLINHAATUAL integer;
declare variable WDESCRICAO varchar(80);
declare variable WORDEM integer;
declare variable WCODEMP integer;
declare variable WVALORACUMULADO numeric(15,2);
BEGIN
  /*
    #6566:
    modificação para aceitar mais de 8 colunas no relatório
  */
  bdcol01 = NULL;
  bdcol02 = NULL;
  bdcol03 = NULL;
  bdcol04 = NULL;
  bdcol05 = NULL;
  bdcol06 = NULL;
  bdcol07 = NULL;
  bdcol08 = NULL;
  bdtitulos = '';
  WCODEMP = 0;
                   
  WVALORACUMULADO = 0;
  FOR SELECT c.bdcodmatriz,c.bdcodemp,c.bdcodplaconsconf,c.bdcodqplaconsconf,
             c.bdref,COUNT(c.bdordem) AS "BDNUMCOLUNAS"
      FROM vef_rel_cons_anual_conf c
      INNER JOIN tempresas e ON e.bdcodemp = c.bdcodemp
      GROUP BY bdcodmatriz, c.bdcodemp, c.bdcodplaconsconf, c.bdcodqplaconsconf, c.bdref
      ORDER BY bdcodmatriz, c.bdcodemp, c.bdcodplaconsconf, c.bdcodqplaconsconf, c.bdref
  INTO
    :bdcodmatriz,
    :bdcodemp,
    :bdcodplano,
    :bdcodquadro,
    :bdref, 
    :wnumcolunas
  DO
    BEGIN
      if (:WCODEMP <> :bdcodemp) then
        BEGIN
          WCODEMP = :bdcodemp;   
          WVALORACUMULADO = 0;
        END
      wano = SUBSTRING(:bdref FROM 1 FOR 4);
      wmes = SUBSTRING(:bdref FROM 5 FOR 2);
      SELECT FIRST 1 bdanomes FROM sp_retorna_mesano_extenso(:wmes, :wano,  '/') INTO :bdmesextenso;

      --Número de linhas para cada quadro (número de formulas no quadro / 8) arredondado para cima
      wNumLinhas = CEIL((CAST(:wnumcolunas AS NUMERIC(15,2))/CAST(8 AS NUMERIC(15,2))));
      wColunaAtual = 1;
      wIndice = 0;
      wLinhaAtual = 0;
                   
      --if ((:prdeclaracao = 'TRUE')) then
      --  BEGIN
      --    wnumcolunas = 2;
      --  END

      WHILE (:wLinhaAtual < wNumLinhas) DO
        BEGIN         
   -- Larissa - 24/08/2021 - Relatório de faturamento - média do período #146434
            wColunaAtual = 1;
            FOR SELECT FIRST 8 (SUM(f.bdvalor) / (COUNT(BDORDEM))) AS BDVALOR, LEFT(f.bddescricao, 80) AS "BDDESCRICAO", f.bdordem
              FROM vef_rel_cons_anual_conf f
              WHERE f.bdcodmatriz = :bdcodmatriz AND
                    f.bdcodemp          = :bdcodemp AND
                    f.bdcodplaconsconf  = :bdcodplano AND
                    f.bdcodqplaconsconf = :bdcodquadro AND
     f.bdvalor > IIF(:PRNAOIMPRIMEZERADO = 'TRUE', 0, -1)
              group BY F.bddescricao, f.bdordem
              ORDER BY f.bdordem
            INTO
              :wvalor,
              :wdescricao,
              :wordem
            DO
              BEGIN
        
                IF (:wColunaAtual = 1) THEN
                    BDMEDIA01 = :wvalor;
                  ELSE IF (:wColunaAtual = 2) THEN
                    BDMEDIA02 = :wvalor;
                  ELSE IF (:wColunaAtual = 3) THEN
                    BDMEDIA03 = :wvalor;
                  ELSE IF (:wColunaAtual = 4) THEN
                    BDMEDIA04 = :wvalor;
                  ELSE IF (:wColunaAtual = 5) THEN
                    BDMEDIA05 = :wvalor;
                  ELSE IF (:wColunaAtual = 6) THEN
                    BDMEDIA06 = :wvalor;
                  ELSE IF (:wColunaAtual = 7) THEN
                    BDMEDIA07 = :wvalor;
                  ELSE IF (:wColunaAtual = 8) THEN
                    BDMEDIA08 = :wvalor;      
                 wColunaAtual = wColunaAtual + 1;
            END

                                          --TCONFCONSFORM.BDDESCRICAO é um varchar(80), garante que vai ter no máximo 80 caracteres a descrição      
          wColunaAtual = 1;
          FOR SELECT FIRST 8 SKIP (:wLinhaAtual * 8) f.bdvalor, LEFT(f.bddescricao, 80) AS "BDDESCRICAO"
              FROM vef_rel_cons_anual_conf f
              WHERE f.bdcodmatriz       = :bdcodmatriz AND
                    f.bdcodemp          = :bdcodemp AND
                    f.bdcodplaconsconf  = :bdcodplano AND
                    f.bdcodqplaconsconf = :bdcodquadro AND
                    f.bdref             = :bdref
              ORDER BY f.bdordem
          INTO
            :wvalor,
            :wdescricao
          DO
            BEGIN
              wIndice = :wIndice + 1;
    
              IF (:wColunaAtual = 1) THEN
                bdcol01 = :wvalor;
              ELSE IF (:wColunaAtual = 2) THEN
                bdcol02 = :wvalor;
              ELSE IF (:wColunaAtual = 3) THEN
                bdcol03 = :wvalor;
              ELSE IF (:wColunaAtual = 4) THEN
                bdcol04 = :wvalor;
              ELSE IF (:wColunaAtual = 5) THEN
                bdcol05 = :wvalor;
              ELSE IF (:wColunaAtual = 6) THEN
                bdcol06 = :wvalor;
              ELSE IF (:wColunaAtual = 7) THEN
                bdcol07 = :wvalor;
              ELSE IF (:wColunaAtual = 8) THEN
                bdcol08 = :wvalor;

                                              
              if ((:prdeclaracao = 'TRUE') AND (:wColunaAtual = 1)) then
                BEGIN
                  bdcol02 = :wValorAcumulado + bdcol01;
                  WVALORACUMULADO = bdcol02;
                  wdescricao = 'Faturamento Mensal';
              bdtitulos = :bdtitulos || LPAD(:wdescricao, 80);
                  --BDMEDIA02  = wValorAcumulado + bdcol02;          
                  wdescricao = 'Faturamento Acumulado';   
                  bdtitulos = :bdtitulos || LPAD(:wdescricao, 80);
                END
              ELSE  
                bdtitulos = :bdtitulos || LPAD(:wdescricao, 80);

              IF ((MOD(:wColunaAtual, 8) = 0) OR (:wIndice = :wnumcolunas)) THEN
                BEGIN
                  bdlinha = :wlinhaatual;
                  bdtitulos = RPAD(:bdtitulos, 1280);
                                                    

--Incluído opção de não imprimir no relatório meses com faturamento zerado.
                  IF (PRNAOIMPRIMEZERADO = 'TRUE') THEN
                  BEGIN
                    IF (wvalor > 0) THEN
                  SUSPEND;
                  END
                  ELSE
                     SUSPEND;
    
                  wColunaAtual = 1;
                  bdcol01 = NULL;
                  bdcol02 = NULL;
                  bdcol03 = NULL;
                  bdcol04 = NULL;
                  bdcol05 = NULL;
                  bdcol06 = NULL;
                  bdcol07 = NULL;
                  bdcol08 = NULL;
      bdmedia01 = NULL;
                  bdmedia02 = NULL;
                  bdmedia03 = NULL;
                  bdmedia04 = NULL;
                  bdmedia05 = NULL;
                  bdmedia06 = NULL;
                  bdmedia07 = NULL;
                  bdmedia08 = NULL;
                  bdtitulos = '';
                END
              ELSE
                wColunaAtual = :wColunaAtual + 1;
            END
          wLinhaAtual = :wLinhaAtual + 1;
        END
    END
END
^
create or alter procedure SP_REL_CONSULTA_SIMULADOR_TRIB (
    PRTOTALTRIMESTRE DM_BOOLEAN = false /* COLLATE WIN1252 - default */ ,
    PRNAOIMPRIMEZERADO DM_BOOLEAN = false /* COLLATE WIN1252 - default */ )
returns (
    BDCODMATRIZ integer,
    BDCODEMP integer,
    BDCODPLANO integer,
    BDCODQUADRO integer,
    BDREF numeric(15,2),
    BDMESEXTENSO varchar(20),
    BDCOL01 numeric(15,2),
    BDCOL02 numeric(15,2),
    BDCOL03 numeric(15,2),
    BDCOL04 numeric(15,2),
    BDCOL05 numeric(15,2),
    BDCOL06 numeric(15,2),
    BDCOL07 numeric(15,2),
    BDCOL08 numeric(15,2),
    BDCOL09 numeric(15,2),
    BDCOL10 numeric(15,2),
    BDCOL11 numeric(15,2),
    BDCOL12 numeric(15,2),
    BDCOL13 numeric(15,2),
    BDCOL14 numeric(15,2),
    BDCOL15 numeric(15,2),
    BDCOL16 numeric(15,2),
    BDCOL17 numeric(15,2),
    BDCOL18 numeric(15,2),
    BDCOL19 numeric(15,2),
    BDCOL20 numeric(15,2),
    BDCOL21 numeric(15,2),
    BDCOL22 numeric(15,2),
    BDCOL23 numeric(15,2),
    BDCOL24 numeric(15,2),
    BDCOL25 numeric(15,2),
    BDCOL26 numeric(15,2),
    BDCOL27 numeric(15,2),
    BDCOL28 numeric(15,2),
    BDCOL29 numeric(15,2),
    BDCOL30 numeric(15,2),
    BDCOL31 numeric(15,2),
    BDCOL32 numeric(15,2),
    BDCOL33 numeric(15,2),
    BDCOL34 numeric(15,2),
    BDCOL35 numeric(15,2),
    BDCOL36 numeric(15,2),
    BDCOL37 numeric(15,2),
    BDCOL38 numeric(15,2),
    BDCOL39 numeric(15,2),
    BDCOL40 numeric(15,2),
    BDCOL41 numeric(15,2),
    BDCOL42 numeric(15,2),
    BDCOL43 numeric(15,2),
    BDCOL44 numeric(15,2),
    BDCOL45 numeric(15,2),
    BDCOL46 numeric(15,2),
    BDCOL47 numeric(15,2),
    BDCOL48 numeric(15,2),
    BDCOL49 numeric(15,2),
    BDCOL50 numeric(15,2),
    BDLINHA integer,
    BDTITULOS varchar(1500),
    BDTOTTRI DM_BOOLEAN,
    BDISTOT DM_BOOLEAN)
as
declare variable WVALOR numeric(15,2);
declare variable WCOLUNAATUAL integer;
declare variable WMES char(2);
declare variable WANO char(4);
declare variable WINDICE integer;
declare variable WNUMCOLUNAS integer;
declare variable WNUMLINHAS integer;
declare variable WLINHAATUAL integer;
declare variable WDESCRICAO varchar(80);
declare variable WORDEM integer;
declare variable WCODEMP integer;
declare variable WVALORACUMULADO numeric(15,2);
declare variable WVALTRIM01 numeric(15,2);
declare variable WVALTRIM02 numeric(15,2);
declare variable WVALTRIM03 numeric(15,2);
declare variable WVALTRIM04 numeric(15,2);
declare variable WVALTRIM05 numeric(15,2);
declare variable WVALTRIM06 numeric(15,2);
declare variable WVALTRIM07 numeric(15,2);
declare variable WVALTRIM08 numeric(15,2);
declare variable WVALTRIM09 numeric(15,2);
declare variable WVALTRIM10 numeric(15,2);
declare variable WVALTRIM11 numeric(15,2);
declare variable WVALTRIM12 numeric(15,2);
declare variable WVALTRIM13 numeric(15,2);
declare variable WVALTRIM14 numeric(15,2);
declare variable WVALTRIM15 numeric(15,2);
declare variable WVALTRIM16 numeric(15,2);
declare variable WVALTRIM17 numeric(15,2);
declare variable WVALTRIM18 numeric(15,2);
declare variable WVALTRIM19 numeric(15,2);
declare variable WVALTRIM20 numeric(15,2);
declare variable WVALTRIM21 numeric(15,2);
declare variable WVALTRIM22 numeric(15,2);
declare variable WVALTRIM23 numeric(15,2);
declare variable WVALTRIM24 numeric(15,2);
declare variable WVALTRIM25 numeric(15,2);
declare variable WVALTRIM26 numeric(15,2);
declare variable WVALTRIM27 numeric(15,2);
declare variable WVALTRIM28 numeric(15,2);
declare variable WVALTRIM29 numeric(15,2);
declare variable WVALTRIM30 numeric(15,2);
declare variable WVALTRIM31 numeric(15,2);
declare variable WVALTRIM32 numeric(15,2);
declare variable WVALTRIM33 numeric(15,2);
declare variable WVALTRIM34 numeric(15,2);
declare variable WVALTRIM35 numeric(15,2);
declare variable WVALTRIM36 numeric(15,2);
declare variable WVALTRIM37 numeric(15,2);
declare variable WVALTRIM38 numeric(15,2);
declare variable WVALTRIM39 numeric(15,2);
declare variable WVALTRIM40 numeric(15,2);
declare variable WVALTRIM41 numeric(15,2);
declare variable WVALTRIM42 numeric(15,2);
declare variable WVALTRIM43 numeric(15,2);
declare variable WVALTRIM44 numeric(15,2);
declare variable WVALTRIM45 numeric(15,2);
declare variable WVALTRIM46 numeric(15,2);
declare variable WVALTRIM47 numeric(15,2);
declare variable WVALTRIM48 numeric(15,2);
declare variable WVALTRIM49 numeric(15,2);
declare variable WVALTRIM50 numeric(15,2);
declare variable WCOUNTMESESTRI integer;
declare variable WTEMP integer;
declare variable WEMPANT integer;
declare variable WPLANOANT integer;
declare variable WQUADANT integer;
declare variable WPRIMEIRAVEZ DM_BOOLEAN;
declare variable WISSN DM_BOOLEAN;
begin
  BDCOL01 = null; BDCOL02 = null; BDCOL03 = null; BDCOL04 = null; BDCOL05 = null; BDCOL06 = null; BDCOL07 = null; BDCOL08 = null; BDCOL09 = null; BDCOL10 = null;
  BDCOL11 = null; BDCOL12 = null; BDCOL13 = null; BDCOL14 = null; BDCOL15 = null; BDCOL16 = null; BDCOL17 = null; BDCOL18 = null; BDCOL19 = null; BDCOL20 = null;
  BDCOL21 = null; BDCOL22 = null; BDCOL23 = null; BDCOL24 = null; BDCOL25 = null; BDCOL26 = null; BDCOL27 = null; BDCOL28 = null; BDCOL29 = null; BDCOL30 = null;
  BDCOL31 = null; BDCOL32 = null; BDCOL33 = null; BDCOL34 = null; BDCOL35 = null; BDCOL36 = null; BDCOL37 = null; BDCOL38 = null; BDCOL39 = null; BDCOL40 = null;
  BDCOL41 = null; BDCOL42 = null; BDCOL43 = null; BDCOL44 = null; BDCOL45 = null; BDCOL46 = null; BDCOL47 = null; BDCOL48 = null; BDCOL49 = null; BDCOL50 = null;


  BDTOTTRI = null;
  WEMPANT = 0;
  WPLANOANT = 0;
  WQUADANT = 0;
  BDISTOT = 'FALSE';

  WVALTRIM01 = null; WVALTRIM02 = null; WVALTRIM03 = null; WVALTRIM04 = null; WVALTRIM05 = null; WVALTRIM06 = null; WVALTRIM07 = null; WVALTRIM08 = null; WVALTRIM09 = null; WVALTRIM10 = null;
  WVALTRIM11 = null; WVALTRIM12 = null; WVALTRIM13 = null; WVALTRIM14 = null; WVALTRIM15 = null; WVALTRIM16 = null; WVALTRIM17 = null; WVALTRIM18 = null; WVALTRIM19 = null; WVALTRIM20 = null;
  WVALTRIM21 = null; WVALTRIM22 = null; WVALTRIM23 = null; WVALTRIM24 = null; WVALTRIM25 = null; WVALTRIM26 = null; WVALTRIM27 = null; WVALTRIM28 = null; WVALTRIM29 = null; WVALTRIM30 = null;
  WVALTRIM31 = null; WVALTRIM32 = null; WVALTRIM33 = null; WVALTRIM34 = null; WVALTRIM35 = null; WVALTRIM36 = null; WVALTRIM37 = null; WVALTRIM38 = null; WVALTRIM39 = null; WVALTRIM40 = null;
  WVALTRIM41 = null; WVALTRIM42 = null; WVALTRIM43 = null; WVALTRIM44 = null; WVALTRIM45 = null; WVALTRIM46 = null; WVALTRIM47 = null; WVALTRIM48 = null; WVALTRIM49 = null; WVALTRIM50 = null;


  BDTITULOS = '';
  WCODEMP = 0;
  WCOUNTMESESTRI = 0;
  WPRIMEIRAVEZ = 'TRUE';

  WVALORACUMULADO = 0;
  for select C.BDCODMATRIZ, C.BDCODEMP, C.BDCODPLACONSCONF, C.BDCODQPLACONSCONF, C.BDREF,
             count(C.BDORDEM) as "BDNUMCOLUNAS"
      from (select *
            from VEF_REL_SIMULATOR_TRIB
            where BDIGNORE = 'FALSE') C
      inner join TEMPRESAS E on (E.BDCODEMP = C.BDCODEMP)
      group by BDCODMATRIZ, C.BDCODEMP, C.BDCODPLACONSCONF, C.BDCODQPLACONSCONF, C.BDREF
      order by BDCODMATRIZ, C.BDCODEMP, C.BDCODPLACONSCONF, C.BDCODQPLACONSCONF, C.BDREF
      into :BDCODMATRIZ, :BDCODEMP, :BDCODPLANO, :BDCODQUADRO, :BDREF, :WNUMCOLUNAS
  do
  begin
    if (:WCODEMP <> :BDCODEMP) then
    begin
      WCODEMP = :BDCODEMP;
      WVALORACUMULADO = 0;
    end
    WANO = substring(:BDREF from 1 for 4);
    WMES = substring(:BDREF from 5 for 2);
    select first 1 BDANOMES
    from SP_RETORNA_MESANO_EXTENSO(:WMES, :WANO, '/')
    into :BDMESEXTENSO;

    WNUMLINHAS = ceil((cast(:WNUMCOLUNAS as numeric(15,2)) / cast(50 as numeric(15,2))));
    WCOLUNAATUAL = 1;
    WINDICE = 0;
    WLINHAATUAL = 0;

    WCOLUNAATUAL = 1;
    for select first 50 skip (:WLINHAATUAL * 50) F.BDVALOR, left(F.BDDESCRICAO, 80) as "BDDESCRICAO", Q.BDENQSIMPLES
        from VEF_REL_SIMULATOR_TRIB F
        left outer join TPLANOCONSCONF_Q Q on (Q.BDCODPLACONSCONF = :BDCODPLANO and
              Q.BDCODQPLACONSCONF = :BDCODQUADRO)
        where F.BDCODMATRIZ = :BDCODMATRIZ and
              F.BDCODEMP = :BDCODEMP and
              F.BDCODPLACONSCONF = :BDCODPLANO and
              F.BDCODQPLACONSCONF = :BDCODQUADRO and
              F.BDREF = :BDREF and
              F.BDIGNORE = 'FALSE'
        order by F.BDORDEM
        into :WVALOR, :WDESCRICAO, :WISSN
    do
    begin
      WINDICE = :WINDICE + 1;

        if (:WCOLUNAATUAL = 1) then
          BDCOL01 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 2) then
          BDCOL02 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 3) then
          BDCOL03 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 4) then
          BDCOL04 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 5) then
          BDCOL05 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 6) then
          BDCOL06 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 7) then
          BDCOL07 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 8) then
          BDCOL08 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 9) then
          BDCOL09 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 10) then
          BDCOL10 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 11) then
          BDCOL11 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 12) then
          BDCOL12 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 13) then
          BDCOL13 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 14) then
          BDCOL14 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 15) then
          BDCOL15 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 16) then
          BDCOL16 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 17) then
          BDCOL17 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 18) then
          BDCOL18 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 19) then
          BDCOL19 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 20) then
          BDCOL20 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 21) then
          BDCOL21 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 22) then
          BDCOL22 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 23) then
          BDCOL23 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 24) then
          BDCOL24 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 25) then
          BDCOL25 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 26) then
          BDCOL26 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 27) then
          BDCOL27 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 28) then
          BDCOL28 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 29) then
          BDCOL29 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 30) then
          BDCOL30 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 31) then
          BDCOL31 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 32) then
          BDCOL32 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 33) then
          BDCOL33 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 34) then
          BDCOL34 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 35) then
          BDCOL35 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 36) then
          BDCOL36 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 37) then
          BDCOL37 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 38) then
          BDCOL38 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 39) then
          BDCOL39 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 40) then
          BDCOL40 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 41) then
          BDCOL41 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 42) then
          BDCOL42 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 43) then
          BDCOL43 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 44) then
          BDCOL44 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 45) then
          BDCOL45 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 46) then
          BDCOL46 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 47) then
          BDCOL47 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 48) then
          BDCOL48 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 49) then
          BDCOL49 = :WVALOR;
        else
        if (:WCOLUNAATUAL = 50) then
          BDCOL50 = :WVALOR;

      if (:PRTOTALTRIMESTRE = 'TRUE') then
      begin
        if (:WCOLUNAATUAL = 1) then
        begin
          if (WVALTRIM01 is null) then
            WVALTRIM01 = 0;
          WVALTRIM01 = BDCOL01 + WVALTRIM01;
        end
        else
        if (:WCOLUNAATUAL = 2) then
        begin
          if (WVALTRIM02 is null) then
            WVALTRIM02 = 0;
          WVALTRIM02 = BDCOL02 + WVALTRIM02;
        end
        else
        if (:WCOLUNAATUAL = 3) then
        begin
          if ((WVALTRIM03 is null) and (:WISSN <> 'TRUE')) then
            WVALTRIM03 = 0;
          else
            WVALTRIM03 = null;
          WVALTRIM03 = BDCOL03 + WVALTRIM03;
        end
        else
        if (:WCOLUNAATUAL = 4) then
        begin
          if (WVALTRIM04 is null) then
            WVALTRIM04 = 0;
          WVALTRIM04 = BDCOL04 + WVALTRIM04;
        end
        else
        if (:WCOLUNAATUAL = 5) then
        begin
          if (WVALTRIM05 is null) then
            WVALTRIM05 = 0;
          WVALTRIM05 = BDCOL05 + WVALTRIM05;
        end
        else
        if (:WCOLUNAATUAL = 6) then
        begin
          if (WVALTRIM06 is null) then
            WVALTRIM06 = 0;
          WVALTRIM06 = BDCOL06 + WVALTRIM06;
        end
        else
        if (:WCOLUNAATUAL = 7) then
        begin
          if (WVALTRIM07 is null) then
            WVALTRIM07 = 0;
          WVALTRIM07 = BDCOL07 + WVALTRIM07;
        end
        else
        if (:WCOLUNAATUAL = 8) then
        begin
          if (WVALTRIM08 is null) then
            WVALTRIM08 = 0;
          WVALTRIM08 = BDCOL08 + WVALTRIM08;
        end
        else
        if (:WCOLUNAATUAL = 9) then
        begin
          if (WVALTRIM09 is null) then
            WVALTRIM09 = 0;
          WVALTRIM09 = BDCOL09 + WVALTRIM09;
        end
        else
        if (:WCOLUNAATUAL = 10) then
        begin
          if (WVALTRIM10 is null) then
            WVALTRIM10 = 0;
          WVALTRIM10 = BDCOL10 + WVALTRIM10;
        end
        else
        if (:WCOLUNAATUAL = 11) then
        begin
          if (WVALTRIM11 is null) then
            WVALTRIM11 = 0;
          WVALTRIM11 = BDCOL11 + WVALTRIM11;
        end
        else
        if (:WCOLUNAATUAL = 12) then
        begin
          if (WVALTRIM12 is null) then
            WVALTRIM12 = 0;
          WVALTRIM12 = BDCOL12 + WVALTRIM12;
        end
        else
        if (:WCOLUNAATUAL = 13) then
        begin
          if (WVALTRIM13 is null) then
            WVALTRIM13 = 0;
          WVALTRIM13 = BDCOL13 + WVALTRIM13;
        end
        else
        if (:WCOLUNAATUAL = 14) then
        begin
          if (WVALTRIM14 is null) then
            WVALTRIM14 = 0;
          WVALTRIM14 = BDCOL14 + WVALTRIM14;
        end
        else
        if (:WCOLUNAATUAL = 15) then
        begin
          if (WVALTRIM15 is null) then
            WVALTRIM15 = 0;
          WVALTRIM15 = BDCOL15 + WVALTRIM15;
        end
        else
        if (:WCOLUNAATUAL = 16) then
        begin
          if (WVALTRIM16 is null) then
            WVALTRIM16 = 0;
          WVALTRIM16 = BDCOL16 + WVALTRIM16;
        end
        else
        if (:WCOLUNAATUAL = 17) then
        begin
          if (WVALTRIM17 is null) then
            WVALTRIM17 = 0;
          WVALTRIM17 = BDCOL17 + WVALTRIM17;
        end
        else
        if (:WCOLUNAATUAL = 18) then
        begin
          if (WVALTRIM18 is null) then
            WVALTRIM18 = 0;
          WVALTRIM18 = BDCOL18 + WVALTRIM18;
        end
        else
        if (:WCOLUNAATUAL = 19) then
        begin
          if (WVALTRIM19 is null) then
            WVALTRIM19 = 0;
          WVALTRIM19 = BDCOL19 + WVALTRIM19;
        end
        else
        if (:WCOLUNAATUAL = 20) then
        begin
          if (WVALTRIM20 is null) then
            WVALTRIM20 = 0;
          WVALTRIM20 = BDCOL20 + WVALTRIM20;
        end
        else
        if (:WCOLUNAATUAL = 21) then
        begin
          if (WVALTRIM21 is null) then
            WVALTRIM21 = 0;
          WVALTRIM21 = BDCOL21 + WVALTRIM21;
        end
        else
        if (:WCOLUNAATUAL = 22) then
        begin
          if (WVALTRIM22 is null) then
            WVALTRIM22 = 0;
          WVALTRIM22 = BDCOL22 + WVALTRIM22;
        end
        else
        if (:WCOLUNAATUAL = 23) then
        begin
          if (WVALTRIM23 is null) then
            WVALTRIM23 = 0;
          WVALTRIM23 = BDCOL23 + WVALTRIM23;
        end
        else
        if (:WCOLUNAATUAL = 24) then
        begin
          if (WVALTRIM24 is null) then
            WVALTRIM24 = 0;
          WVALTRIM24 = BDCOL24 + WVALTRIM24;
        end
        else
        if (:WCOLUNAATUAL = 25) then
        begin
          if (WVALTRIM25 is null) then
            WVALTRIM25 = 0;
          WVALTRIM25 = BDCOL25 + WVALTRIM25;
        end
        else
        if (:WCOLUNAATUAL = 26) then
        begin
          if (WVALTRIM26 is null) then
            WVALTRIM26 = 0;
          WVALTRIM26 = BDCOL26 + WVALTRIM26;
        end
        else
        if (:WCOLUNAATUAL = 27) then
        begin
          if (WVALTRIM27 is null) then
            WVALTRIM27 = 0;
          WVALTRIM27 = BDCOL27 + WVALTRIM27;
        end
        else
        if (:WCOLUNAATUAL = 28) then
        begin
          if (WVALTRIM28 is null) then
            WVALTRIM28 = 0;
          WVALTRIM28 = BDCOL28 + WVALTRIM28;
        end
        else
        if (:WCOLUNAATUAL = 29) then
        begin
          if (WVALTRIM29 is null) then
            WVALTRIM29 = 0;
          WVALTRIM29 = BDCOL29 + WVALTRIM29;
        end
        else
        if (:WCOLUNAATUAL = 30) then
        begin
          if (WVALTRIM30 is null) then
            WVALTRIM30 = 0;
          WVALTRIM30 = BDCOL30 + WVALTRIM30;
        end
        else
        if (:WCOLUNAATUAL = 31) then
        begin
          if (WVALTRIM31 is null) then
            WVALTRIM31 = 0;
          WVALTRIM31 = BDCOL31 + WVALTRIM31;
        end
        else
        if (:WCOLUNAATUAL = 32) then
        begin
          if (WVALTRIM32 is null) then
            WVALTRIM32 = 0;
          WVALTRIM32 = BDCOL32 + WVALTRIM32;
        end
        else
        if (:WCOLUNAATUAL = 33) then
        begin
          if (WVALTRIM33 is null) then
            WVALTRIM33 = 0;
          WVALTRIM33 = BDCOL33 + WVALTRIM33;
        end
        else
        if (:WCOLUNAATUAL = 34) then
        begin
          if (WVALTRIM34 is null) then
            WVALTRIM34 = 0;
          WVALTRIM34 = BDCOL34 + WVALTRIM34;
        end
        else
        if (:WCOLUNAATUAL = 35) then
        begin
          if (WVALTRIM35 is null) then
            WVALTRIM35 = 0;
          WVALTRIM35 = BDCOL35 + WVALTRIM35;
        end
        else
        if (:WCOLUNAATUAL = 36) then
        begin
          if (WVALTRIM36 is null) then
            WVALTRIM36 = 0;
          WVALTRIM36 = BDCOL36 + WVALTRIM36;
        end
        else
        if (:WCOLUNAATUAL = 37) then
        begin
          if (WVALTRIM37 is null) then
            WVALTRIM37 = 0;
          WVALTRIM37 = BDCOL37 + WVALTRIM37;
        end
        else
        if (:WCOLUNAATUAL = 38) then
        begin
          if (WVALTRIM38 is null) then
            WVALTRIM38 = 0;
          WVALTRIM38 = BDCOL38 + WVALTRIM38;
        end
        else
        if (:WCOLUNAATUAL = 39) then
        begin
          if (WVALTRIM39 is null) then
            WVALTRIM39 = 0;
          WVALTRIM39 = BDCOL39 + WVALTRIM39;
        end
        else
        if (:WCOLUNAATUAL = 40) then
        begin
          if (WVALTRIM40 is null) then
            WVALTRIM40 = 0;
          WVALTRIM40 = BDCOL40 + WVALTRIM40;
        end
        else
        if (:WCOLUNAATUAL = 41) then
        begin
          if (WVALTRIM41 is null) then
            WVALTRIM41 = 0;
          WVALTRIM41 = BDCOL41 + WVALTRIM41;
        end
        else
        if (:WCOLUNAATUAL = 42) then
        begin
          if (WVALTRIM42 is null) then
            WVALTRIM42 = 0;
          WVALTRIM42 = BDCOL42 + WVALTRIM42;
        end
        else
        if (:WCOLUNAATUAL = 43) then
        begin
          if (WVALTRIM43 is null) then
            WVALTRIM43 = 0;
          WVALTRIM43 = BDCOL43 + WVALTRIM43;
        end
        else
        if (:WCOLUNAATUAL = 44) then
        begin
          if (WVALTRIM44 is null) then
            WVALTRIM44 = 0;
          WVALTRIM44 = BDCOL44 + WVALTRIM44;
        end
        else
        if (:WCOLUNAATUAL = 45) then
        begin
          if (WVALTRIM45 is null) then
            WVALTRIM45 = 0;
          WVALTRIM45 = BDCOL45 + WVALTRIM45;
        end
        else
        if (:WCOLUNAATUAL = 46) then
        begin
          if (WVALTRIM46 is null) then
            WVALTRIM46 = 0;
          WVALTRIM46 = BDCOL46 + WVALTRIM46;
        end
        else
        if (:WCOLUNAATUAL = 47) then
        begin
          if (WVALTRIM47 is null) then
            WVALTRIM47 = 0;
          WVALTRIM47 = BDCOL47 + WVALTRIM47;
        end
        else
        if (:WCOLUNAATUAL = 48) then
        begin
          if (WVALTRIM48 is null) then
            WVALTRIM48 = 0;
          WVALTRIM48 = BDCOL48 + WVALTRIM48;
        end
        else
        if (:WCOLUNAATUAL = 49) then
        begin
          if (WVALTRIM49 is null) then
            WVALTRIM49 = 0;
          WVALTRIM49 = BDCOL49 + WVALTRIM49;
        end
        else
        if (:WCOLUNAATUAL = 50) then
        begin
          if (WVALTRIM50 is null) then
            WVALTRIM50 = 0;
          WVALTRIM50 = BDCOL50 + WVALTRIM50;
        end
      end

      BDTITULOS = :BDTITULOS || :WDESCRICAO || '±';

      if ((mod(:WCOLUNAATUAL, 50) = 0) or (:WINDICE = :WNUMCOLUNAS)) then
      begin
        BDLINHA = :WLINHAATUAL;
        BDTITULOS = rpad(:BDTITULOS, 640);

        if (PRNAOIMPRIMEZERADO = 'TRUE') then
        begin
          if (WVALOR > 0) then
            suspend;
        end
        else
          suspend;

        if (((BDCODEMP <> WEMPANT) or (BDCODPLANO <> WPLANOANT) or (BDCODQUADRO <> WQUADANT)) and
            (WPRIMEIRAVEZ <> 'TRUE')) then


          WCOUNTMESESTRI = 0;

        WCOUNTMESESTRI = WCOUNTMESESTRI + 1;
        if ((:PRTOTALTRIMESTRE = 'TRUE') and
            (WCOUNTMESESTRI = 3)) then
        begin
          BDCOL01 = WVALTRIM01; BDCOL02 = WVALTRIM02; BDCOL03 = WVALTRIM03; BDCOL04 = WVALTRIM04; BDCOL05 = WVALTRIM05; BDCOL06 = WVALTRIM06; BDCOL07 = WVALTRIM07; BDCOL08 = WVALTRIM08; BDCOL09 = WVALTRIM09; BDCOL10 = WVALTRIM10;
          BDCOL11 = WVALTRIM11; BDCOL12 = WVALTRIM12; BDCOL13 = WVALTRIM13; BDCOL14 = WVALTRIM14; BDCOL15 = WVALTRIM15; BDCOL16 = WVALTRIM16; BDCOL17 = WVALTRIM17; BDCOL18 = WVALTRIM18; BDCOL19 = WVALTRIM19; BDCOL20 = WVALTRIM20;
          BDCOL21 = WVALTRIM21; BDCOL22 = WVALTRIM22; BDCOL23 = WVALTRIM23; BDCOL24 = WVALTRIM24; BDCOL25 = WVALTRIM25; BDCOL26 = WVALTRIM26; BDCOL27 = WVALTRIM27; BDCOL28 = WVALTRIM28; BDCOL29 = WVALTRIM29; BDCOL30 = WVALTRIM30;
          BDCOL31 = WVALTRIM31; BDCOL32 = WVALTRIM32; BDCOL33 = WVALTRIM33; BDCOL34 = WVALTRIM34; BDCOL35 = WVALTRIM35; BDCOL36 = WVALTRIM36; BDCOL37 = WVALTRIM37; BDCOL38 = WVALTRIM38; BDCOL39 = WVALTRIM39; BDCOL40 = WVALTRIM40;
          BDCOL41 = WVALTRIM41; BDCOL42 = WVALTRIM42; BDCOL43 = WVALTRIM43; BDCOL44 = WVALTRIM44; BDCOL45 = WVALTRIM45; BDCOL46 = WVALTRIM46; BDCOL47 = WVALTRIM47; BDCOL48 = WVALTRIM48; BDCOL49 = WVALTRIM49; BDCOL50 = WVALTRIM50;


          BDMESEXTENSO = 'Total Trimestre';
          WTEMP = BDREF;
          BDREF = WTEMP + 0.1;
          BDTOTTRI = 'TRUE';
          BDISTOT = 'TRUE';

          suspend;

          BDREF = WTEMP;

          WVALTRIM01 = null; WVALTRIM02 = null; WVALTRIM03 = null; WVALTRIM04 = null; WVALTRIM05 = null; WVALTRIM06 = null; WVALTRIM07 = null; WVALTRIM08 = null; WVALTRIM09 = null; WVALTRIM10 = null;
          WVALTRIM11 = null; WVALTRIM12 = null; WVALTRIM13 = null; WVALTRIM14 = null; WVALTRIM15 = null; WVALTRIM16 = null; WVALTRIM17 = null; WVALTRIM18 = null; WVALTRIM19 = null; WVALTRIM20 = null;
          WVALTRIM21 = null; WVALTRIM22 = null; WVALTRIM23 = null; WVALTRIM24 = null; WVALTRIM25 = null; WVALTRIM26 = null; WVALTRIM27 = null; WVALTRIM28 = null; WVALTRIM29 = null; WVALTRIM30 = null;
          WVALTRIM31 = null; WVALTRIM32 = null; WVALTRIM33 = null; WVALTRIM34 = null; WVALTRIM35 = null; WVALTRIM36 = null; WVALTRIM37 = null; WVALTRIM38 = null; WVALTRIM39 = null; WVALTRIM40 = null;
          WVALTRIM41 = null; WVALTRIM42 = null; WVALTRIM43 = null; WVALTRIM44 = null; WVALTRIM45 = null; WVALTRIM46 = null; WVALTRIM47 = null; WVALTRIM48 = null; WVALTRIM49 = null; WVALTRIM50 = null;


          WCOUNTMESESTRI = 0;
        end

        WCOLUNAATUAL = 1;
        BDCOL01 = null; BDCOL02 = null; BDCOL03 = null; BDCOL04 = null; BDCOL05 = null; BDCOL06 = null; BDCOL07 = null; BDCOL08 = null; BDCOL09 = null; BDCOL10 = null;
        BDCOL11 = null; BDCOL12 = null; BDCOL13 = null; BDCOL14 = null; BDCOL15 = null; BDCOL16 = null; BDCOL17 = null; BDCOL18 = null; BDCOL19 = null; BDCOL20 = null;
        BDCOL21 = null; BDCOL22 = null; BDCOL23 = null; BDCOL24 = null; BDCOL25 = null; BDCOL26 = null; BDCOL27 = null; BDCOL28 = null; BDCOL29 = null; BDCOL30 = null;
        BDCOL31 = null; BDCOL32 = null; BDCOL33 = null; BDCOL34 = null; BDCOL35 = null; BDCOL36 = null; BDCOL37 = null; BDCOL38 = null; BDCOL39 = null; BDCOL40 = null;
        BDCOL41 = null; BDCOL42 = null; BDCOL43 = null; BDCOL44 = null; BDCOL45 = null; BDCOL46 = null; BDCOL47 = null; BDCOL48 = null; BDCOL49 = null; BDCOL50 = null;
        BDTITULOS = '';
        BDTOTTRI = null;
        WPLANOANT = BDCODPLANO;
        WQUADANT = BDCODQUADRO;
        WEMPANT = BDCODEMP;
        BDTOTTRI = null;
        WPRIMEIRAVEZ = 'FALSE';
        BDISTOT = 'FALSE';
      end
      else
        WCOLUNAATUAL = :WCOLUNAATUAL + 1;
    end
    WLINHAATUAL = :WLINHAATUAL + 1;
  end
end^

/* Restore proc. body: SP_REL_CTRPAT_ANALILITIC_SINT */
ALTER PROCEDURE SP_REL_CTRPAT_ANALILITIC_SINT AS
BEGIN
  /* Procedure Text */
END
^

/* Restore proc. body: SP_REL_RESUMO_IMPOSTOS */
CREATE OR ALTER procedure SP_REL_RESUMO_IMPOSTOS (
    PRCODEMP varchar(10000),
    PRCODIMP varchar(10000),
    PRCODSIS varchar(10000),
    PRREFINI integer,
    PRREFFIN integer,
    PRREFATUAL integer,
    PRDTVCTOINI date,
    PRDTVCTOFIM date)
returns (
    BDCODEMP integer,
    BDCHAVEDARF integer,
    BDCODIMP integer,
    BDDESCIMP varchar(200),
    BDCODREC integer,
    BDCODSIS integer,
    BDCODPERIODO integer,
    BDDESCPERIODO varchar(40),
    BDORDEM integer,
    BDREFERENCIA integer,
    BDMESEXTENSO varchar(20),
    BDQUOTA integer,
    BDCODCOL integer,
    BDCODEMPCOL integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDPERIODO date,
    BDNUMREFDOC varchar(20),
    BDDATAVCTO date,
    BDVALOR numeric(15,6),
    BDMULTA numeric(15,6),
    BDJUROS numeric(15,6),
    BDTOTAL numeric(15,6),
    BDOBS blob sub_type 0 segment size 80,
    BDORDEMCOMPL integer,
    BDBASEIMP numeric(15,6),
    BDALIQIMP numeric(15,6),
    BDVLRIMPORIGINAL numeric(15,6),
    BDVLRACUMULO numeric(15,6),
    BDVLRMULTAJUROS numeric(15,6),
    BDVLROUTENTIDADE numeric(15,6),
    BDTIPOIMPOSTO integer,
    BDCOMPENSACAO numeric(15,6),
    BDVLRACUOUTENT numeric(15,6),
    BDREFPAG integer,
    BDDTPGTO date,
    BDDOCARRECADACAO integer)
as
declare variable WGROUPBY varchar(10000);
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(10000);
declare variable WORDERBY varchar(5000);
declare variable WMES char(10);
declare variable WANO char(10);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

  wSql = 'select DARF.BDCODEMP, ';
  wSql = wSql || 'DARF.BDCODIMP, ';
  wSql = wSql || 'IMP.BDDESCIMP, ';
  wSql = wSql || 'IMP.BDCODREC, ';
  wSql = wSql || 'IMP.BDCODSIS, ';
  wSql = wSql || 'DARF.BDCODPERIODO, ';
  wSql = wSql || 'periodo.bddescricao, ';
  wSql = wSql || 'DARF.BDREFERENCIA, ';
  wSql = wSql || 'DARF.BDQUOTA, ';
  wSql = wSql || 'DARF.BDDATAVCTO , ';

  wSql = wSql || 'DARF.BDBASEIMP , ';
  wSql = wSql || 'DARF.BDALIQIMP , ';
  wSql = wSql || 'DARF.BDVLRIMPORIGINAL , ';
  wSql = wSql || 'DARF.BDVALOR , ';
  wSql = wSql || 'DARF.BDMULTA , ';
  wSql = wSql || 'DARF.BDJUROS , ';
  wSql = wSql || 'DARF.BDTOTAL , ';
  wSql = wSql || 'DARF.BDOBS , ';
  wSql = wSql || 'DARF.BDORDEMCOMPL , ';
  wSql = wSql || 'DARF.BDVLRMULTAJUROS , ';
  wSql = wSql || 'DARF.BDVLROUTENTIDADE, ';
  wSql = wSql || 'DARF.BDORDEM, ';
  wSql = wSql || 'DARF.BDCHAVEDARF, ';
  wSql = wSql || 'IMP.BDDOCARRECADACAO ';
--  wsql = wsql || 'from tdarfpadrao DARF , timposto IMP , ttiposperiodo periodo, VW_EMPRESAS_REF_ATUAL emp ';

  wSql = wSql || 'from ( ';
  wSql = wSql || '      select darf.* ';
  wSql = wSql || '      from TDARFPADRAO darf ';


  wwhere = '';

  IF (prcodemp IS NOT NULL) THEN
     wwhere = wWhere||PRCODEMP||' ';

  IF ((prcodimp IS NOT NULL) OR (prcodimp > 0)) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wWhere = wwhere||prcodimp||' ';
     END

  IF ((prcodsis IS NOT NULL) OR (prcodsis > 0)) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wWhere = wwhere||prcodsis||' ';
     END

  IF ((prrefini IS NOT NULL) AND (prrefini > 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'cast(substring(darf.bdreferencia from 1 for 6) as integer) >= '||prrefini||' ';
     END

  IF ((prreffin IS NOT NULL) AND (prreffin > 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'cast(substring(darf.bdreferencia from 1 for 6) as integer) <= '||prreffin||' ';
     END

  IF (prdtvctoini IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'DARF.bddatavcto >= '||''''||prdtvctoini||'''';
     END

  IF (prdtvctofim IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'DARF.bddatavcto <= '||''''||prdtvctofim||'''';
     END

  IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

--      where DARF.BDCODEMP = 502 and
--      cast(substring(darf.bdreferencia from 1 for 6) as integer) >= 201906 and
--      cast(substring(darf.bdreferencia from 1 for 6) as integer) <= 201906
  wSql = wSql || '      ) DARF ';
  wSql = wSql || ' left outer join TIMPOSTO IMP on (imp.bdcodimp = darf.bdcodimp) ';
  wSql = wSql || ' left outer join TTIPOSPERIODO PERIODO on (PERIODO.BDCODPERIODO = darf.BDCODPERIODO) ';
--order by DARF.BDCODIMP, DARF.BDORDEM, DARF.BDREFERENCIA, DARF.BDCODPERIODO
--  wwhere = wwhere||' and (imp.bdcodimp = darf.bdcodimp) and (emp.bdcodemp = darf.bdcodemp) and (darf.bdcodperiodo = periodo.bdcodperiodo)';

  wgroupby = '';
  worderby = 'order by DARF.BDCODIMP, DARF.BDORDEM, DARF.bdreferencia, DARF.BDCODPERIODO';

  wsql = wsql||wwhere||wgroupby||worderby;

  FOR EXECUTE STATEMENT wsql
    INTO
      :bdcodemp,
      :BDCODIMP,
      :BDDESCIMP,
      :bdcodrec,
      :bdcodsis,
      :BDCODPERIODO,
      :bddescperiodo,
      :BDREFERENCIA,
      :BDQUOTA,
      :BDDATAVCTO ,
      :BDBASEIMP ,
      :BDALIQIMP ,
      :BDVLRIMPORIGINAL ,
      :BDVALOR ,
      :BDMULTA ,
      :BDJUROS ,
      :BDTOTAL ,
      :BDOBS ,
      :BDORDEMCOMPL ,
      :BDVLRMULTAJUROS ,
      :BDVLROUTENTIDADE,
      :BDORDEM,
      :BDCHAVEDARF,
      :BDDOCARRECADACAO  DO
      BEGIN


    wano = SUBSTRING(bdreferencia FROM 1 FOR 4);
    wmes = SUBSTRING(bdreferencia FROM 5 FOR 2);

    IF (wmes = '01') THEN
       bdmesextenso =  'Janeiro / ' || wano;
    IF (wmes = '02') THEN
       bdmesextenso =  'Fevereiro / ' || wano;
    IF (wmes = '03') THEN
       bdmesextenso =  'Março / ' || wano;
    IF (wmes = '04') THEN
       bdmesextenso =  'Abril / ' || wano;
    IF (wmes = '05') THEN
       bdmesextenso =  'Maio / ' || wano;
    IF (wmes = '06') THEN
       bdmesextenso =  'Junho / ' || wano;
    IF (wmes = '07') THEN
       bdmesextenso =  'Julho / ' || wano;
    IF (wmes = '08') THEN
       bdmesextenso =  'Agosto / ' || wano;
    IF (wmes = '09') THEN
       bdmesextenso =  'Setembro / ' || wano;
    IF (wmes = '10') THEN
       bdmesextenso =  'Outubro / ' || wano;
    IF (wmes = '11') THEN
       bdmesextenso =  'Novembro / ' || wano;
    IF (wmes = '12') THEN
       bdmesextenso =  'Dezembro / ' || wano;


        SELECT MAX(pgto.bddatapgto) FROM tdarfgerpgto pgto
               WHERE (PGTO.bdcodemp = :bdcodemp AND PGTO.BDCHAVEDARF = :BDCHAVEDARF) INTO :BDDTPGTO;

        SUSPEND;
      END
END
^

/* Restore proc. body: SP_RESTAURA_VERBA_SE_PADRAO */
create or alter procedure SP_RESTAURA_VERBA_SE_PADRAO (
    PRCODEVER integer,
    PRCRIARSEEXISTIR varchar(5) = false)
as
declare variable WVPADRAO integer;
declare variable WCODNOVO integer;
declare variable WCOUNT integer;
begin
  wvpadrao = null;
  select BDTIPOVER from VRH_BASE_TVERBAS where BDCODVER = :prcodever into :wvpadrao;

  if (COALESCE(wvpadrao, 0) = 1) then
     execute procedure sp_restaura_verba_padrao(:prcodever);
  else
    begin
      wvpadrao = null;
      select first 1 BDCODVER from VRH_BASE_TVERBAS where BDCODVER = :prcodever into :wvpadrao;

      if (coalesce(wvpadrao, 0) = 0) then   -- Verba não existe e pode ser inserida.
         execute procedure sp_restaura_verba_padrao(:prcodever);
      else if (upper(PRCRIARSEEXISTIR) = 'TRUE') then
         begin
           WCODNOVO = prcodever;
           WCOUNT = WCODNOVO;

           while (WCOUNT > 0) do
             begin
               WCOUNT = 0;
               WCODNOVO = WCODNOVO + 1;
               select first 1 BDCODVER from VRH_BASE_TVERBAS where BDCODVER = :WCODNOVO into :WCOUNT;
    end


           if (wcodnovo <> prcodever) then
              execute procedure sp_restaura_verba_padrao(:prcodever,:wcodnovo);
         end
    end
end^

create or alter procedure SP_RESTAURA_VERBA_PADRAO (
    PRCODVER integer,
    PRCODVERBANOVO integer = 0)
as
declare variable WSELECT varchar(3000);
declare variable WCODVER integer;
declare variable WAPVER varchar(20);
declare variable WDESCVER varchar(40);
declare variable WDESCREDVER varchar(20);
declare variable WCLAVER varchar(20);
declare variable WREFVER integer;
declare variable WTIPOCODVER integer;
declare variable WINSSVER integer;
declare variable WFGTSVER integer;
declare variable WIRVER integer;
declare variable WTIPOREFVER integer;
declare variable WBASESFVER integer;
declare variable WPISVER varchar(5);
declare variable WBASEHEVER varchar(5);
declare variable WBASEMAIORVER varchar(5);
declare variable WRAISVER varchar(5);
declare variable WBASEGPSVER varchar(5);
declare variable WMENORESVER varchar(5);
declare variable WPROPVER varchar(5);
declare variable WBASEVTVER varchar(5);
declare variable WREEMBGPSVER varchar(5);
declare variable WHEVER numeric(15,6);
declare variable WGRAVAFICHAHNVER varchar(5);
declare variable WCCPRINCIPALVER varchar(5);
declare variable WFORMREFVER varchar(5000);
declare variable WFORMVALVER varchar(5000);
declare variable WBASEDSRHEVER varchar(5);
declare variable WBASEDSRRVVER varchar(5);
declare variable WFORMREFAUXVER varchar(5000);
declare variable WDEDFORMREFAUXVER varchar(5);
declare variable WDEDFORMREFVER varchar(5);
declare variable WDEDFORMVALVER varchar(5);
declare variable WRENDISENTOIRVER varchar(5);
declare variable WFORMINTVER varchar(5000);
declare variable WSITVER integer;
declare variable WCODVERATU integer;
declare variable WSIMPLESVER varchar(5);
declare variable WPAGAESTVER varchar(5);
declare variable WBASE13HN varchar(5);
declare variable WBASEFERHN varchar(5);
declare variable WBASEAVHN varchar(5);
declare variable WGARANT varchar(5);
declare variable WSITMAT varchar(5);
declare variable WSITDOE varchar(5);
declare variable WSITACITRAB varchar(5);
declare variable WSITMILITAR varchar(5);
declare variable WSITMATEMP varchar(5);
declare variable WSITACITRAB15 varchar(5);
declare variable WSITDOETRAB varchar(5);
declare variable WSITLICVENC varchar(5);
declare variable WSITDOE15 varchar(5);
declare variable WSITSINDICAL varchar(5);
declare variable WSITAPOINV varchar(5);
declare variable WSITOUTRAS varchar(5);
declare variable WTIPOVERPD integer;
declare variable WINDRESCPD varchar(5);
declare variable WSALBASERAISPD varchar(5);
declare variable WNAOCONVHORASVERP DM_BOOLEAN;
declare variable WBASEDSRHNVER DM_BOOLEAN;
declare variable WBASEDSROUVER DM_BOOLEAN;
declare variable WREMINTERMVER DM_BOOLEAN;
declare variable WCODINCIDINSS integer;
declare variable WCODINCIDFGTS integer;
declare variable WCODINCIDIRRF integer;
declare variable WRUBRICAESOCIAL integer;
declare variable WCODINCIDPIS integer;
declare variable WDESCCOMPULSORIOVER DM_BOOLEAN;
BEGIN
  wselect = 'select '||
              'VER.BDCODVERPD, '||
              'VER.BDAPEVERPD, '||
              'VER.BDDESCVERPD, '||
              'VER.BDDESCREDVERPD, '||
              'VER.BDCLAVERPD, '||
              'VER.BDREFVERPD, '||
              'VER.BDTIPOCODVERPD, '||
              'VER.BDINSSVERPD, '||
              'VER.BDFGTSVERPD, '||
              'VER.BDIRVERPD, '||
              'VER.BDTIPOREFVERPD, '||
              'VER.BDBASESFVERPD, '||
              'VER.BDPISVERPD, '||
              'VER.BDBASEHEVERPD, '||
              'VER.BDBASEMAIORVERPD, '||
              'VER.BDRAISVERPD, '||
              'VER.BDBASEGPSVERPD, '||
              'VER.BDMENORESVERPD, '||
              'VER.BDPROPVERPD, '||
              'VER.BDBASEVTVERPD, '||
              'VER.BDREEMBGPSVERPD, '||
              'VER.BDHEVERPD, '||
              'VER.BDGRAVAFICHAHNVERPD, '||
              'VER.BDCCPRINCIPALVERPD, '||
              'VER.BDFORMREFVERPD, '||
              'VER.BDFORMVALVERPD, '||
              'VER.BDBASEDSRHEVERPD, '||
              'VER.BDBASEDSRRVVERPD, '||
              'VER.BDFORMREFAUXVERPD, '||
              'VER.BDDEDFORMREFAUXVERPD, '||
              'VER.BDDEDFORMREFVERPD, '||
              'VER.BDDEDFORMVALVERPD, '||
              'VER.BDRENDISENTOIRVERPD, '||
              'VER.BDFORMINTVERPD, '||
              'VER.BDSITVERPD, '||
              'VER.BDSIMPLESNACIONALPD, '||
              'VER.BDPAGAESTOUROVERPD, '||
              'VER.BDBASE13HNPD, '||
              'VER.BDBASEFERHNPD, '||
              'VER.BDBASEAVHNPD, '||
              'VER.BDGARANTIAMINVERPD, '||
              'VER.BDSITMATVERPD, '||
              'VER.BDSITDOEVERPD, '||
              'VER.BDSITACITRABVERPD, '||
              'VER.BDSITMILITARVERPD, '||
              'VER.BDSITMATEMPVERPD, '||
              'VER.BDSITACITRAB15VERPD, '||
              'VER.BDSITDOETRABVERPD, '||
              'VER.BDSITLICVENCVERPD, '||
              'VER.BDSITDOE15VERPD, '||
              'VER.BDSITSINDICALVERPD, '||
              'VER.BDSITAPOINVVERPD, '||
              'VER.BDSITOUTRASPD, '||
              'VER.BDTIPOVERPD, '||
              'VER.BDINDRESCPD, '||
              'VER.BDBASESALRAISPD, '||
              'VER.BDNAOCONVHORASVERPD, '||
              'VER.BDBASEDSRHNVERPD, '||
              'VER.BDBASEDSROUVERPD, '||
              'VER.BDREMINTERMVERPD, '||
              'VER.BDCODINCIDINSS, '||
              'VER.BDCODINCIDFGTS, '||
              'VER.BDCODINCIDIRRF, '||
              'coalesce(VER.BDCODRESPD, RUB.BDCHAVE, 0) BDRUBRICAESOCIAL,'||
              'VER.BDCODINCIDPIS, '||
              'VER.BDDESCCOMPULSORIOVERPD '||
            'from VRH_BASE_TVERBAS_PADRAO VER '||
            'left outer join VRH_BASE_TRUBRICAES_VER_PD RUB on RUB.BDCODVER = VER.BDCODVERPD '||
            'where VER.BDCODVERPD = '||:prcodver||' order by VER.BDCODVERPD, VER.BDREFVERPD ' ;

  wcodveratu = 0;
  
  FOR EXECUTE STATEMENT wselect INTO :wcodver, :wapver, :wdescver, :wdescredver, :wclaver, :wrefver, :wtipocodver, :winssver, :wfgtsver, :wirver, :wtiporefver, :wbasesfver, :wpisver,
     :wbasehever, :wbasemaiorver, :wraisver, :wbasegpsver, :wmenoresver, :wpropver, :wbasevtver, :wreembgpsver, :whever, :wgravafichahnver, :wccprincipalver, :wformrefver, :wformvalver,
     :wbasedsrhever, :wbasedsrrvver, :wformrefauxver, :wdedformrefauxver, :wdedformrefver, :wdedformvalver, :wrendisentoirver, :wformintver, :wsitver,
     :wsimplesver, :wpagaestver, :wbase13hn, :wbaseferhn, :wbaseavhn, :wgarant, :wsitmat, :wsitdoe, :wsitacitrab, :wsitmilitar, :wsitmatemp, :wsitacitrab15, :wsitdoetrab, :wsitlicvenc,
     :wsitdoe15, :wsitsindical, :wsitapoinv, :wsitoutras, :wtipoverpd, :windrescpd, :wsalbaseraispd, :wnaoconvhorasverp, :wbasedsrhnver, :wbasedsrouver, :wremintermver, :wcodincidinss,
     :wcodincidfgts, :wcodincidirrf, :wrubricaesocial, :wCODINCIDPIS, :WDESCCOMPULSORIOVER DO
  BEGIN
    if (PRCODVERBANOVO <> 0) then
        wcodver = PRCODVERBANOVO;

    IF (wcodveratu <> :wcodver) THEN
       BEGIN
         UPDATE OR INSERT INTO VRH_BASE_TVERBAS (BDCODVER,BDAPEVER,BDDESCVER,BDDESCREDVER,BDCLAVER,BDSITVER,
            BDSITMATVER,BDSITDOEVER,BDSITACITRABVER,BDSITMILITARVER,BDSITMATEMPVER,BDSITACITRAB15VER,BDSITDOETRABVER,BDSITLICVENCVER,BDSITDOE15VER,BDSITSINDICALVER,
            BDSITAPOINVVER,BDSITOUTRASVER,BDTIPOVER,BDBASESALRAIS) VALUES (:wcodver,:wapver,:wdescver,:wdescredver,:wclaver,:wsitver,
            :wsitmat, :wsitdoe, :wsitacitrab, :wsitmilitar, :wsitmatemp, :wsitacitrab15, :wsitdoetrab, :wsitlicvenc, :wsitdoe15, :wsitsindical,
            :wsitapoinv, :wsitoutras, :wtipoverpd, :wsalbaseraispd) MATCHING (BDCODVER);
         DELETE FROM VRH_BASE_TVERBAS_REF WHERE BDCODVER = :wcodver;

         if (prcodver <> prcodverbanovo) then
            update VRH_BASE_TVERBAS set BDCODVERBAPADRAO = :prcodver where bdcodver = :wcodver;

         wcodveratu = :wcodver;
       END

    UPDATE OR INSERT INTO VRH_BASE_TVERBAS_REF (BDCODVER,BDREFVER,BDTIPOCODVER,BDINSSVER,BDFGTSVER,BDIRVER,BDTIPOREFVER,BDBASESFVER,BDPISVER,BDBASEHEVER,BDBASEMAIORVER,BDRAISVER,BDBASEGPSVER,
      BDMENORESVER,BDPROPVER,BDBASEVTVER,BDREEMBGPSVER,BDHEVER,BDGRAVAFICHAHNVER,BDCCPRINCIPALVER,BDFORMREFVER,BDFORMVALVER,BDBASEDSRHEVER,BDBASEDSRRVVER,BDFORMREFAUXVER,
      BDDEDFORMREFAUXVER,BDDEDFORMREFVER,BDDEDFORMVALVER,BDRENDISENTOIRVER,BDFORMINTVER,BDSIMPLESNACIONAL,BDBASE13HN,BDBASEFERHN,BDBASEAVHN,BDPAGAESTOUROVER,BDGARANTIAMINVER,BDINDRESC,
      BDNAOCONVHORASVER,BDBASEDSRHNVER,BDBASEDSROUVER,BDREMINTERMVER,BDCODINCIDINSS,BDCODINCIDFGTS,BDCODINCIDIRRF,BDCODINCIDPIS, BDDESCCOMPULSORIOVER)
    VALUES (:wcodver,:wrefver,:wtipocodver,:winssver,:wfgtsver,:wirver,:wtiporefver,:wbasesfver,:wpisver,:wbasehever,:wbasemaiorver,:wraisver,:wbasegpsver,:wmenoresver,:wpropver,
      :wbasevtver,:wreembgpsver,:whever,:wgravafichahnver,:wccprincipalver,:wformrefver,:wformvalver,:wbasedsrhever,:wbasedsrrvver,:wformrefauxver,:wdedformrefauxver,:wdedformrefver,
      :wdedformvalver,:wrendisentoirver,:wformintver,:wsimplesver,:wbase13hn,:wbaseferhn,:wbaseavhn,:wpagaestver,:wgarant,:windrescpd, :wnaoconvhorasverp,:wbasedsrhnver,:wbasedsrouver,
      :wremintermver,:wcodincidinss,:wcodincidfgts,:wcodincidirrf,:wCODINCIDPIS, :WDESCCOMPULSORIOVER) MATCHING (bdcodver,bdrefver);

    IF (wrubricaesocial <> 0) THEN
      BEGIN
        DELETE FROM VRH_BASE_TRUBRICAESOCIAL_VER where (BDCODVER = :wcodver) and (BDCHAVE <> :wrubricaesocial);
        UPDATE OR INSERT INTO VRH_BASE_TRUBRICAESOCIAL_VER (BDCHAVE, BDCODVER) VALUES(:wrubricaesocial, :wcodver) MATCHING (BDCODVER);
  END

  END
END^

CREATE OR ALTER PROCEDURE SP_RESTAURA_VERBA_PADRAO_CLASS (
    PRCLAVER VARCHAR(20) = NULL) 
AS
DECLARE VARIABLE WCODVER INTEGER;
DECLARE VARIABLE WSQL VARCHAR(500);
BEGIN
  wsql = 'select bdcodverpd from vrh_base_tverbas_padrao ';

  IF (prclaver IS NOT NULL AND prclaver <> '') THEN
     wsql = wsql||' where bdclaverpd like '''||prclaver||'%''';

  FOR EXECUTE STATEMENT wsql INTO :wcodver DO
    BEGIN
      EXECUTE PROCEDURE sp_restaura_verba_padrao(:wcodver);
    END
END
^


/* Restore proc. body: SP_RETORNA_DIFERENCAS_VSUC_TLAN */
create or alter procedure SP_RETORNA_DIFERENCAS_VSUC_TLAN (
    PRCODEMP varchar(2048),
    PRDATAINICIAL date,
    PRDATAFINAL date,
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRTRANSACAO integer,
    PRSEMPRE integer = 0)
returns (
    PREMPRESA integer,
    PRDATA date,
    PRDEBITO numeric(15,6),
    PRCREDITO numeric(15,6),
    PRDIFERENCA numeric(15,6),
    PRTOTAL numeric(15,6))
as
declare variable WCREDITO integer;
declare variable WDEBITO integer;
declare variable WVALORCRE numeric(15,6);
declare variable WVALORDEB numeric(15,6);
declare variable WVALORAUX numeric(15,6);
declare variable WDATAAUX date;
declare variable WDATA date;
declare variable WSQL varchar(2000);
declare variable WFILIAL integer;
declare variable WTIPOLANCFILIAL integer;
declare variable WPERMITE integer;
declare variable WEMPPRINC integer;
declare variable WPOS integer;
declare variable WCAMPO integer;
declare variable WPOS_PERNAMATRIZ integer;
declare variable WPOS_MATRIZ integer;
declare variable WPOS_FILIAL integer;
declare variable WCODEMP integer;
BEGIN
  wdataaux  = '12/31/1990';

  wvalorcre = 0;
  wvalordeb = 0;
  prTotal   = 0;

  wsql = 'select bdcodemp,bdDEBITO,bdCREDITO,bdDATA,bdVALOR,bdfilial,bdtipolancfilial from vsuc_empresas_tlan ';
  wsql = wsql||'where ';
  wsql = wsql||'((BDDEBITO is null) or (BDCREDITO is null)) '; --#alt:6504 - Apenas lançamentos com uma perna - Bruno Borges
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  --#alt:4431. Transação
  IF (prtransacao > 0) THEN
    wsql = wsql||'and (bdtransacao = '||prtransacao||') ';
  wsql = wsql||'and (bddata between '''||:prdatainicial||''' and '''||:prdatafinal||''') ';
  --#alt:5837.wsql = wsql||'WHERE (bdCODEMP in ('||:prcodemp||')) ';
  wsql = wsql||'and (bdCODEMP in ('||:prcodemp||')) and (coalesce(bdfilial,0) = 0) order by bdDATA asc';

  --Retorna a empresa principal
  SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
  IF (wpos = 0) THEN
    wempprinc = prcodemp;
  ELSE
    wempprinc = SUBSTRING(prcodemp FROM 1 FOR (wpos - 1));

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wdebito,:wcredito,:wData,:wValorAux,:wfilial,:wtipolancfilial DO
     BEGIN
        prempresa = wcodemp;

        IF (wDataAux = '12/31/1990') THEN
           wdataaux = wData;

        IF (wDataAux <> wData) THEN -- gilberto - 10/01/2014
        --if ((wDataAux <> wData) or ((prempresa is not null) and (wcodemp <> prempresa))) then
           BEGIN
              IF (wvalorcre <> wvalordeb) THEN
                 BEGIN
                    prData = wDataAux;
                    prCredito = wvalorcre;
                    prDebito = wvalordeb;
                    prDiferenca = wvalorcre - wvalordeb;
                    prTotal = prTotal + (wvalorcre - wvalordeb);
                    SUSPEND;
                 END
              wdataaux = :wData;
              wvalorcre = 0;
              wvalordeb = 0;
              --prTotal = 0;-- gilberto - 10/01/2014
           END
        --prempresa = wcodemp;-- gilberto - 10/01/2014

        --alt:#6524 - implementado rotina "POS" aqui, por questão de desempenho, precisa apenas uma vez para as duas verificações
        -- IF (NOT ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0))) THEN
           -- BEGIN
             -- wpos_pernamatriz = POSITION(wempprinc, prcodemp);
             -- --Estou na matriz mas também quero os lançamentos da filial conforme o filtro(Lançamentos que foram feito na filial -> BDCODEMP = Filial)
             -- wpos_matriz = POSITION(wcodemp, prcodemp);
             -- --Estou na matriz mas também quero a perna que está na filial conforme o filtro
             -- wpos_filial = POSITION(wfilial, prcodemp);
          -- END
        --wpermite = 0;


        --alt:#6524 - implementado rotina "VSUC_SP_PERMITECALCSALDOLANCMF" diretamente aqui, por questão de desempenho
        --select bdpermite from vsuc_sp_permitecalcsaldolancmf(1,:wempprinc,:prempresa,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
        -- IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
           --wpermite = 1;
 ------------------------------------------------------------
        IF /*((wpermite = 1) AND*/ ((wdebito IS NOT NULL) OR (wdebito <> 0))  THEN
           wvalordeb = wvalordeb + wValorAux;

        --alt:#6524 - implementado rotina "VSUC_SP_PERMITECALCSALDOLANCMF" diretamente aqui, por questão de desempenho
        --select bdpermite from vsuc_sp_permitecalcsaldolancmf(2,:wempprinc,:prempresa,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
        -- IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
         -- wpermite = 1;
        -- ELSE
           -- BEGIN
             -- wcampo = 2;
             -- IF (((wempprinc = wcodemp) AND (wfilial = 0)) OR
                 -- --Estou na filial mas o lançamento foi feito na matriz para a filial(uma perna)
                 -- ((wempprinc = wfilial) AND (wcampo = wtipolancfilial)) OR
                 -- --Estou na matriz e tem uma perna do lançamento na filial, mas só quero os lançamentos da matriz(a perna da matriz) e que a matriz esteja no filtro
                 -- ((wempprinc = wcodemp) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
                 -- --Estou na matriz mas também quero os lançamentos da filial conforme o filtro(Lançamentos que foram feito na filial -> BDCODEMP = Filial)
                 -- ((prmatrizfilialconsolidado = 1) AND (wempprinc <> wcodemp) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
                 -- --Estou na matriz mas também quero a perna que está na filial conforme o filtro
                 -- ((prmatrizfilialconsolidado = 1) AND (wempprinc = wcodemp) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
               -- wpermite = 1;             
           -- END
        ------------------------------------------------------------------------
        IF /*((wpermite = 1) AND*/ ((wcredito IS NOT NULL) OR (wcredito <> 0))  THEN
           wvalorcre = wvalorcre + wValorAux;
     END

     if (prsempre <> 0 and prtransacao > 0) then
      BEGIN
        wsql = 'SELECT COALESCE(SUM(BDVALOR), 0) AS bdvalor FROM VSUC_EMPRESAS_TLAN WHERE';
        wsql = wsql||'((BDDEBITO is not null) AND (BDCREDITO is not null)) ';
        IF (prcontabilizacao <> 99) THEN
          wsql = wsql||'and (bdcontabilizacao in (0,'||prcontabilizacao||')) ';
        wsql = wsql||'and (bdtransacao = '||prtransacao||') ';
        wsql = wsql||'and (bddata between '''||:prdatainicial||''' and '''||:prdatafinal||''') ';
        wsql = wsql||'and (bdCODEMP in ('||:prcodemp||'))';
        EXECUTE STATEMENT wsql INTO :wvaloraux;
        wvalorcre = wvalorcre + wvaloraux;
        wvalordeb = wvalordeb + wvaloraux;
      END

     IF ((wvalorcre <> wvalordeb) or (prsempre <> 0))  THEN
        BEGIN
           prData = wdataaux;
           prCredito = wvalorcre;
           prDebito = wvalordeb;
           prDiferenca = wvalorcre - wvalordeb;
           prTotal = prTotal + (wvalorcre - wvalordeb);
           SUSPEND;
        END
END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_EMPRESA_FILIAIS (
    PRCODEMP INTEGER,
    PRREFEMP INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP VARCHAR(18),
    BDCODMATRIZ INTEGER)
AS
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMEMP VARCHAR(100);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
BEGIN
  /* retorna a empresa matriz ________________________________________________*/
  SELECT tempresas.bdcodemp, tempresas_ref.bdnomemp, tempresas.bdcnpjemp, tempresas.bdcodmatriz
  FROM tempresas
  LEFT OUTER JOIN tempresas_ref ON (tempresas_ref.bdcodemp = tempresas.bdcodemp)
  WHERE tempresas.bdcodemp = :prcodemp
  AND tempresas_ref.bdrefemp = (SELECT FIRST 1 temp.bdrefemp FROM tempresas_ref temp
                                WHERE temp.bdrefemp <= :prrefemp
                                AND temp.bdcodemp = :prcodemp
                                ORDER BY temp.bdcodemp DESC, temp.bdrefemp DESC)
  INTO :bdcodemp, :bdnomemp, :bdcnpjemp, :bdcodmatriz;
  SUSPEND;

  /* retorna as filiais da empresa ___________________________________________*/
  FOR SELECT tempresas.bdcodemp, tempresas_ref.bdnomemp, tempresas.bdcnpjemp, tempresas.bdcodmatriz
      FROM tempresas
      LEFT OUTER JOIN tempresas_ref ON (tempresas_ref.bdcodemp = tempresas.bdcodemp)
      WHERE tempresas.bdcodmatriz = :prcodemp
      AND tempresas.bdcodemp <> tempresas.bdcodmatriz
      AND tempresas_ref.bdrefemp = (SELECT FIRST 1 temp.bdrefemp FROM tempresas_ref temp
                                    WHERE temp.bdrefemp <= :prrefemp
                                    AND temp.bdcodemp = tempresas.bdcodemp
                                    ORDER BY temp.bdrefemp DESC)
      ORDER BY tempresas.bdcodemp
      INTO :wcodemp, :wnomemp, :wcnpjemp, :wcodmatriz DO
  BEGIN
    /* verifica se a filial possui filial ____________________________________*/
    SELECT COUNT(tempresas.bdcodemp) FROM tempresas
           WHERE tempresas.bdcodmatriz = :wcodemp
           AND tempresas.bdcodemp <> tempresas.bdcodmatriz INTO :wcount;

    IF (wcount > 0) THEN
       BEGIN
         /* retorna as filiais das filiais ___________________________________*/
         FOR SELECT spemp.bdcodemp, spemp.bdnomemp, spemp.bdcnpjemp, spemp.bdcodmatriz FROM sp_retorna_empresa_filiais(:wcodemp, :prrefemp) spemp
             INTO :bdcodemp, :bdnomemp, :bdcnpjemp, :bdcodmatriz DO
         SUSPEND;
       END
    ELSE
       BEGIN
         /* caso a filial não tenha filiais retorna o codigo da filial da
         empresa _____________________________________________________________*/
         bdcodemp = wcodemp;
         bdnomemp = wnomemp;
         bdcnpjemp = wcnpjemp;
         bdcodmatriz = wcodmatriz;
         SUSPEND;
       END
  END
END
^

/* Restore proc. body: SP_RETORNA_MESANO_EXTENSO */
ALTER PROCEDURE SP_RETORNA_MESANO_EXTENSO(PRMES VARCHAR(2),
PRANO VARCHAR(4),
PRSEPARADOR VARCHAR(1) = '/')
 RETURNS(BDANOMES VARCHAR(20))
 AS
DECLARE VARIABLE wmes INTEGER;
BEGIN
  wmes = CAST(prmes AS INTEGER);

  IF (wmes = 1) THEN
    bdanomes = 'Janeiro';
  ELSE IF (wmes = 2) THEN
    bdanomes = 'Fevereiro';
  ELSE IF (wmes = 3) THEN
    bdanomes = 'Março';
  ELSE IF (wmes = 4) THEN
    bdanomes = 'Abril';
  ELSE IF (wmes = 5) THEN
    bdanomes = 'Maio';
  ELSE IF (wmes = 6) THEN
    bdanomes = 'Junho';
  ELSE IF (wmes = 7) THEN
    bdanomes = 'Julho';
  ELSE IF (wmes = 8) THEN
    bdanomes = 'Agosto';
  ELSE IF (wmes = 9) THEN
    bdanomes = 'Setembro';
  ELSE IF (wmes = 10) THEN
    bdanomes = 'Outubro';
  ELSE IF (wmes = 11) THEN
    bdanomes = 'Novembro';
  ELSE IF (wmes = 12) THEN
    bdanomes = 'Dezembro';

  bdanomes = :bdanomes||prseparador||prano;

  SUSPEND;
END
^

CREATE OR ALTER PROCEDURE SP_SPLIT (
    PRSTRING VARCHAR(1000),
    PRSEPARADOR CHAR(1))
RETURNS (
    BDDADO VARCHAR(100),
    BDPOS INTEGER)
AS
DECLARE VARIABLE WTEMSEP DM_BOOLEAN;
BEGIN
  wTemSep = IIF(POSITION(:PRSEPARADOR, PRSTRING) > 0, 'TRUE', 'FALSE');
  BDPOS = 0;
  WHILE (:wTemSep = 'TRUE') DO
    BEGIN
      BDDADO = SUBSTRING(:PRSTRING FROM 1 FOR POSITION(:PRSEPARADOR, :PRSTRING)-1);
      PRSTRING = SUBSTRING(:PRSTRING FROM POSITION(:PRSEPARADOR, :PRSTRING)+1 FOR CHAR_LENGTH(:PRSTRING));

      SUSPEND;

      wTemSep = IIF(POSITION(:PRSEPARADOR, :PRSTRING) > 0, 'TRUE', 'FALSE'); 
      BDPOS = BDPOS + 1;
    END

END
^

/* Restore proc. body: SP_RETORNA_NUMEROS */
ALTER PROCEDURE SP_RETORNA_NUMEROS(PRSTR VARCHAR(1000),
PRTAMANHO INTEGER = 0)
 RETURNS(BDNUMERO VARCHAR(1000))
 AS
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCHAR VARCHAR(1);
DECLARE VARIABLE WPOSINICIALCORTE INTEGER;
BEGIN
  /*
    retorna somente os números encontrados na string,
    dando opção de fazer um corte(mantendo o final) na string resultado
    exemplo: '1234' com prtamanho = 2 fica: '34'
  */

  bdnumero = '';

  IF (:prstr IS NOT NULL) THEN
    BEGIN
      wpos = 1;

      WHILE (wpos <= CHAR_LENGTH(prstr)) DO
        BEGIN
          wchar = SUBSTRING(:prstr FROM :wpos FOR 1);

          IF (wchar IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')) THEN
             bdnumero = :bdnumero||:wchar;

          wpos = :wpos + 1;
        END

      /* faz um substring inverso (direta para esquerda) */
      IF ((prtamanho > 0) AND (CHAR_LENGTH(:bdnumero) > prtamanho))THEN
        BEGIN
          wposinicialcorte = CHAR_LENGTH(:bdnumero) - prtamanho + 1;
          bdnumero = SUBSTRING(:bdnumero FROM wposinicialcorte FOR prtamanho);
        END
    END

  IF (:bdnumero = '') THEN
     bdnumero = NULL;

  SUSPEND;
END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_ALFANUMERICO (
    PRSTR VARCHAR(1000),
    PRTAMANHO INTEGER = 0)
RETURNS (
    BDNUMERO VARCHAR(1000))
AS
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCHAR VARCHAR(1);
DECLARE VARIABLE WPOSINICIALCORTE INTEGER;
BEGIN
  /*
    retorna somente os números e letras encontrados na string,
    dando opção de fazer um corte(mantendo o final) na string resultado
    exemplo: '1234' com prtamanho = 2 fica: '34'
    mantido o nome do campo como BDNUMERO para ser compativel com o SP_RETORNA_NUMEROS
  */

  bdnumero = '';

  IF (:prstr IS NOT NULL) THEN
    BEGIN
      wpos = 1;

      WHILE (wpos <= CHAR_LENGTH(prstr)) DO
        BEGIN
          wchar = SUBSTRING(:prstr FROM :wpos FOR 1);

          IF ((wchar >= '0' and wchar <= '9') or (wchar >= 'A' and wchar <= 'Z') or (wchar >= 'a' and wchar <= 'z')) THEN
             bdnumero = :bdnumero||:wchar;

          wpos = :wpos + 1;
        END

      /* faz um substring inverso (direta para esquerda) */
      IF ((prtamanho > 0) AND (CHAR_LENGTH(:bdnumero) > prtamanho))THEN
        BEGIN
          wposinicialcorte = CHAR_LENGTH(:bdnumero) - prtamanho + 1;
          bdnumero = SUBSTRING(:bdnumero FROM wposinicialcorte FOR prtamanho);
        END
    END

  IF (:bdnumero = '') THEN
     bdnumero = NULL;

  SUSPEND;
END
^

/* Restore proc. body: SP_PRIMEIRO_NUMERO */
CREATE OR ALTER PROCEDURE SP_PRIMEIRO_NUMERO (
    PRTEXTO VARCHAR(255)
)
RETURNS (
    WNUMERODCTO VARCHAR(50)
)
AS
DECLARE VARIABLE WCONT INTEGER;
DECLARE VARIABLE WCHAR CHAR(1);
DECLARE VARIABLE WNUMERO VARCHAR(50);
DECLARE VARIABLE WACHOU INTEGER;
BEGIN
  WNUMERO = '';
  WACHOU = 0;
  WCONT = 1;

  WHILE (WCONT <= CHAR_LENGTH(PRTEXTO)) DO
  BEGIN
    WCHAR = SUBSTRING(PRTEXTO FROM WCONT FOR 1);

    IF (WCHAR BETWEEN '0' AND '9') THEN
    BEGIN
      WNUMERO = WNUMERO || WCHAR;
      WACHOU = 1;
    END
    ELSE
    BEGIN
      IF (WACHOU = 1) THEN
        LEAVE;
    END

    WCONT = WCONT + 1;
  END

  WNUMERODCTO = WNUMERO;

  SUSPEND;
END
^

/* Restore proc. body: SP_RETORNA_SALDO_EMP */
ALTER PROCEDURE SP_RETORNA_SALDO_EMP(PRCODEMP INTEGER,
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
PRCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRPARTICIPANTE INTEGER = 0)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER)
 AS
DECLARE VARIABLE wsql VARCHAR(5000);
DECLARE VARIABLE wtemcc SMALLINT = 0;
DECLARE VARIABLE wtamanho INTEGER;
DECLARE VARIABLE wclassificacao VARCHAR(50);
DECLARE VARIABLE wdatini VARCHAR(10);
DECLARE VARIABLE wdatfin VARCHAR(10);
DECLARE VARIABLE wgrupocta INTEGER;
DECLARE VARIABLE wdebito NUMERIC(15,2);
DECLARE VARIABLE wcredito NUMERIC(15,2);
DECLARE VARIABLE wlevel INTEGER;
DECLARE VARIABLE wcodplapadrao INTEGER;
DECLARE VARIABLE wcodemp INTEGER;
DECLARE VARIABLE wfilial INTEGER;
DECLARE VARIABLE wtipolancfilial INTEGER;
DECLARE VARIABLE wvlr NUMERIC(15,2);
DECLARE VARIABLE wpermite INTEGER;
BEGIN
  codemp = prcodemp;
  SALDO_ANT_DEB = 0;
  SALDO_ANT_CRE = 0;
  saldo_anterior = 0;
  SALDO_DEB = 0;
  SALDO_CRE = 0;
  saldo_atual = 0;

  -- BDCONCILIADOS:
  --   0: Todos
  --   1: Conciliados
  --   2: Não conciliados
  --   3: Pendentes
  --   4: Normal (todos, porém sem mostrar a coluna no relatório)

  -- pega a classificação da conta passada por parametro (prconta) _____________
  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta, planos_tpla.bdcodplapadrao
  FROM PLANOS_TPLA
  WHERE planos_tpla.bdcodtpla = :prconta
  AND planos_tpla.bdcodplapadrao = (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM tempresas_ref tref
                                    WHERE tref.bdcodemp = :prcodemp
                                    AND tref.bdrefemp <= :prrefemp
                                    ORDER BY tref.bdrefemp DESC)
  INTO :wclassificacao, :wgrupocta, :wcodplapadrao;

  wtamanho = strlen(wclassificacao);

  -- retorna o nivel da conta para calcular ou não as contas descendentes ______
  wsql = '';
  wsql = wsql||'select count(tpla.bdcodtpla) from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
  wsql = wsql||'and tpla.bdctalon like '''||wclassificacao||'%'' ';
  EXECUTE STATEMENT wsql INTO :wlevel;

  -- configura datas para serem usadas no sql __________________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- SALDO A DÉBITO ____________________________________________________________
  SALDO_DEB = 0;
  --#alt:5837.
  /*-- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
            join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
     wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lançamento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (prconciliados = 1) THEN
    wsql = wsql|| ' and (Upper(BDCONCD) = '||'''TRUE'''||')';
  ELSE
  IF (prconciliados = 2) THEN
    wsql = wsql|| ' and ((Upper(BDCONCD) = '||'''FALSE'''||') or (BDCONCD is null))';

  IF ((prparticipante IS NOT NULL) AND (prparticipante <> 0)) THEN-- gilberto - 28/05/2013 - incluido para calcular saldo levando em consideração apenas os participantes, quando for solicitado dessa forma
    wsql = wsql||' and (TLAN.BDCODTERCEIROD = '||prparticipante||')';

  wsql = wsql||' group by tlan.bdcodemp';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_DEB do
     if (SALDO_DEB is null) then
        SALDO_DEB = 0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
--      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:wcodemp, 0, 0, :prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
--      IF (wpermite = 1) THEN
        SALDO_DEB = SALDO_DEB + wvlr;
    END

--  exception ex_date;

  -- SALDO A CRÉDITO ___________________________________________________________
  SALDO_CRE = 0;
  --#alt:5837.
  /*-- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lançamento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (prconciliados = 1) THEN
    wsql = wsql|| ' and (Upper(BDCONCC) = '||'''TRUE'''||')';
  ELSE
  IF (prconciliados = 2) THEN
    wsql = wsql|| ' and ((Upper(BDCONCC) = '||'''FALSE'''||') or (BDCONCD is null))';

  IF ((prparticipante IS NOT NULL) AND (prparticipante <> 0)) THEN-- gilberto - 28/05/2013 - incluido para calcular saldo levando em consideração apenas os participantes, quando for solicitado dessa forma
    wsql = wsql||' and (TLAN.BDCODTERCEIROC = '||prparticipante||')';

  wsql = wsql||' group by tlan.bdcodemp';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_CRE do
     if (SALDO_CRE is null) then
        SALDO_CRE = 0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
--      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodemp,:wcodemp,0,0,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
--      IF (wpermite = 1) THEN
        SALDO_CRE = SALDO_CRE + wvlr;
    END

  -- SALDO ANTERIOR A DÉBITO _________________________________________________
  SALDO_ANT_DEB = 0;
  --#alt:5837.
  /*-- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';
/* #alt:6153 - gilberto - 09/08/2013 - retirado para sempre calcular zeramento no saldo anterior
  if (prignorazeramento = 1) then
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > lançamento de Zeramento
*/
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (prconciliados = 1) THEN
    wsql = wsql|| ' and (Upper(BDCONCD) = '||'''TRUE'''||')';
  ELSE
  IF (prconciliados = 2) THEN
    wsql = wsql|| ' and ((Upper(BDCONCD) = '||'''FALSE'''||') or (BDCONCD is null))';

  IF ((prparticipante IS NOT NULL) AND (prparticipante <> 0)) THEN-- gilberto - 28/05/2013 - incluido para calcular saldo levando em consideração apenas os participantes, quando for solicitado dessa forma
     wsql = wsql||' and (TLAN.BDCODTERCEIROD = '||prparticipante||')';

  wsql = wsql||' group by tlan.bdcodemp';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_ANT_DEB do
     if (SALDO_ANT_DEB is null) then
        SALDO_ANT_DEB = 0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
--      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:wcodemp,0,0,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
--      IF (wpermite = 1) THEN
        SALDO_ANT_DEB = SALDO_ANT_DEB + wvlr;
    END

  -- SALDO ANTERIOR A CRÉDITO __________________________________________________
  SALDO_ANT_CRE = 0;
  --#alt:5837.
  /*-- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';
/* #alt:6153 - gilberto - 09/08/2013 - retirado para sempre calcular zeramento no saldo anterior
  if (prignorazeramento = 1) then
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lançamento de Zeramento
*/
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (prconciliados = 1) THEN
    wsql = wsql|| ' and (Upper(BDCONCC) = '||'''TRUE'''||')';
  ELSE
  IF (prconciliados = 2) THEN
    wsql = wsql|| ' and ((BDCONCC is null) or (upper(bdconcc) = '|| '''FALSE'''||'))';

  IF ((prparticipante IS NOT NULL) AND (prparticipante <> 0)) THEN-- gilberto - 28/05/2013 - incluido para calcular saldo levando em consideração apenas os participantes, quando for solicitado dessa forma
    wsql = wsql||' and (TLAN.BDCODTERCEIROC = '||prparticipante||')';

  wsql = wsql||' group by tlan.bdcodemp';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_ANT_CRE do
     if (SALDO_ANT_CRE is null) then
        SALDO_ANT_CRE = 0; */
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
--      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodemp,:wcodemp,0,0,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
--      IF (wpermite = 1) THEN
        SALDO_ANT_CRE = SALDO_ANT_CRE + wvlr;
    END

  -- SALDO ANTERIOR ____________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5))  THEN -- ATIVO e DESPESAS
     SALDO_ANTERIOR = (SALDO_ANT_DEB-SALDO_ANT_CRE);
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        SALDO_ANTERIOR = (SALDO_ANT_CRE-SALDO_ANT_DEB);

  IF (saldo_anterior IS NULL) THEN
    saldo_anterior = 0;

  -- SALDO ATUAL _______________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5)) THEN -- ATIVO e DESPESAS
     saldo_atual = saldo_anterior + SALDO_DEB - SALDO_CRE;
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        saldo_atual = saldo_anterior - SALDO_DEB + SALDO_CRE;

  IF (saldo_atual IS NULL ) THEN
    saldo_atual = 0;

  SUSPEND;
END
^

create or alter procedure SP_RETORNA_SALDO_EMP_X (
    PRCODEMP integer,
    PRCONTA integer,
    PRDATAINI date,
    PRDATAFIM date,
    PRINDICE integer,
    PRIGNORAZERAMENTO smallint,
    PRCC varchar(8192),
    PRRELCTA integer,
    PRREFEMP integer,
    PRCONCILIADOS integer,
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRPARTICIPANTE integer = 0,
    PRPARTICIPANTEFINAL integer = 0,
    PREMPREENDIMENTO integer = 0,
    PRUNIDIMOB integer = 0,
    PRAPENASCONTABILIZACAOSEL integer = 0,
    PRCODEMPMATRIZ integer = 0,
    PRCONTABILIZACAOLALUR integer = 0,
    PRLISTAPART varchar(10000) = '' /* COLLATE WIN1252 - default */ ,
    PRFILTIPOLAN varchar(3200) = '' /* COLLATE WIN1252 - default */ ,
    PRCODPLAHISTLALUR integer = 0)
returns (
    SALDO_ANT_DEB numeric(18,2),
    SALDO_ANT_CRE numeric(18,2),
    SALDO_DEB numeric(18,2),
    SALDO_CRE numeric(18,2),
    MOVIMENTO numeric(18,2),
    SALDO_ATUAL numeric(18,2),
    SALDO_ANTERIOR numeric(18,2),
    CODEMP integer)
as
declare variable WSQL DM_MAXVARCHAR;
declare variable WTAMANHO integer;
declare variable WCLASSIFICACAO varchar(50);
declare variable WDATINI varchar(10);
declare variable WDATFIN varchar(10);
declare variable WGRUPOCTA integer;
declare variable WCODPLAPADRAO integer;
declare variable WCODEMP integer;
declare variable WFILIAL integer;
declare variable WTIPOLANCFILIAL integer;
declare variable WVLR numeric(15,2);
declare variable WSALANT numeric(15,2);
declare variable WSALATU numeric(15,2);
declare variable WPOS_PERNAMATRIZ integer;
declare variable WPOS_MATRIZ integer;
declare variable WPOS_FILIAL integer;
declare variable WNIVEL integer;
declare variable WPARTE varchar(2000);
declare variable WGROUPBY varchar(2000);
declare variable WAPENASCONTABILIZACAOSELEC varchar(10);
declare variable WTIPCTA integer;
BEGIN
  codemp = prcodemp;
  SALDO_ANT_DEB = 0;
  SALDO_ANT_CRE = 0;
  saldo_anterior = 0;
  SALDO_DEB = 0;
  SALDO_CRE = 0;
  saldo_atual = 0;

  IF (prapenascontabilizacaosel = 0) THEN
    WAPENASCONTABILIZACAOSELEC = '0,';
  ELSE
    WAPENASCONTABILIZACAOSELEC = '';

  -- BDCONCILIADOS:
  --   0: Todos
  --   1: Conciliados
  --   2: Não conciliados
  --   3: Pendentes
  --   4: Normal (todos, porém sem mostrar a coluna no relatório)

  --#alt:87155. SEMPRE DEVE PEGAR O PLANO DE CONTAS DA EMPRESA MATRIZ POIS ALGUMAS FILIAIS INICIAM AS ATIVIDADES EM REFERÊNCIAS DIFERENTES E ESTAVA DANDO ERRO. Ana - 20/07/2018
  IF (PRCODEMPMATRIZ > 0) THEN
    WCODEMP = PRCODEMPMATRIZ;
  ELSE
    WCODEMP = PRCODEMP;

  -- pega a classificação da conta passada por parametro (prconta) _____________
  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta, planos_tpla.bdcodplapadrao, planos_tpla.bdtipcta
  FROM PLANOS_TPLA
  WHERE planos_tpla.bdcodtpla = :prconta
  AND planos_tpla.bdcodplapadrao = (COALESCE(
                                            (SELECT FIRST 1 tref.bdcodplapadrao
                                             FROM tempresas_ref tref
                                             WHERE tref.bdcodemp = :WCODEMP
                                             AND tref.bdrefemp <= :prrefemp
                                             ORDER BY tref.bdcodemp DESC, tref.bdrefemp DESC),
                                             (SELECT FIRST 1 tref.bdcodplapadrao
                                             FROM tempresas_ref tref
                                             WHERE tref.bdcodemp = :WCODEMP
                                             AND tref.bdrefemp > :prrefemp
                                             ORDER BY tref.bdcodemp, tref.bdrefemp ))
                                    )
  INTO :wclassificacao, :wgrupocta, :wcodplapadrao, :wtipcta;

  wtamanho = strlen(wclassificacao);

  -- configura datas para serem usadas no sql __________________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- SALDO A DÉBITO ____________________________________________________________
  wsql = 'Select '||prcodemp||' as bdcodemp, ';
  /**************** ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS ****************/
  IF ((prcc IS NULL) OR (prcc = '') or (prcc = 'null')) THEN
    BEGIN
      IF (prIndice = 0) THEN
        wsql = wsql||'sum(case when (tlan.bddata < '''||prdataini||''') then tlan.bdvalor else 0 end) as bdsalant, ';
      ELSE
        BEGIN
          wsql = wsql||'sum(case when (tlan.bddata < '''||prdataini||''') then tlan.bdvalor';
          wsql = wsql||'      / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                 (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalant, ';
       END

      wsql = wsql||'sum(case when ((tlan.bddata >= '''||prdataini||''')';
      IF (prignorazeramento = 1) THEN
         wsql = wsql||' and (TLAN.BDTIPOLAN <> 10)';

      IF (prIndice = 0) THEN
        wsql = wsql||') then tlan.bdvalor else 0 end) as bdsalatu ';
      ELSE
        BEGIN
          wsql = wsql||') then tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                               (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalatu ';
        END

      --#alt:23030. Forma incorreta de consultar os dados, deixa o processo lento e não retorna o valor correto. Ana - 20/03/2018
      --wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN, planos_tpla TPLA ';

      --#Alt:100735. Melhoria de performance. Carlos Mello - 17/05/2019 - Início
      --wsql = wsql||'inner join (select * from PLANOS_TPLA where BDCTALON like '''||wclassificacao||'%'') TPLA on (TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO and TPLA.BDCODTPLA = TLAN.BDDEBITO) ';
      --wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 0) ';

      -- Caso seja contabilização do Lalur
      if (PRCONTABILIZACAOLALUR = 1) then
         begin
           wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';
           if (wtipcta = 0) then --Conta título
              wsql = wsql||'inner join VSUC_SELECT_CONTAS TPLA on (TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO and TPLA.BDCODTPLA = TLAN.BDDEBITO) ';
         end
      else
         begin
           --#148507 - Machado - 16/03/2021 - No FB3 ele não conseguia indexar na ordem que estava
           wsql = wsql||'FROM (select * from PLANOS_TPLA where bdcodplapadrao = '||wcodplapadrao||' AND BDCTALON like '''||wclassificacao||'%'') TPLA ';
           wsql = wsql||'inner join VSUC_EMPRESAS_TLAN TLAN on (TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO and TPLA.BDCODTPLA = TLAN.BDDEBITO) ';
           wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 0) ';
         end
      --#Alt:100735. Melhoria de performance. Carlos Mello - 17/05/2019 - Fim

      --#alt:23030. fim
    END
  /**************** ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS ****************/
  ELSE
    BEGIN
      IF (prIndice = 0) THEN
        wsql = wsql||'sum(case when (tlan.bddata < '''||prdataini||''') then tlcc.bdvalor else 0 end) as bdsalant, ';
      ELSE
        BEGIN
          wsql = wsql||'sum(case when (tlan.bddata < '''||prdataini||''') then tlcc.bdvalor';
          wsql = wsql||'      / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                 (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalant, ';
       END

      wsql = wsql||'sum(case when ((tlan.bddata >= '''||prdataini||''')';
      IF (prignorazeramento = 1) THEN
         wsql = wsql||' and (TLAN.BDTIPOLAN <> 10)';

      IF (prIndice = 0) THEN
        wsql = wsql||') then tlcc.bdvalor else 0 end) as bdsalatu ';
      ELSE
        BEGIN
          wsql = wsql||') then tlcc.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                               (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalatu ';
        END

      --#alt:23030. Forma incorreta de consultar os dados, deixa o processo lento e não retorna o valor correto. Ana - 20/03/2018
      --wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC, planos_tpla TPLA ';
      --#Alt:100735. Melhoria de performance. Carlos Mello - 17/05/2019 - Início
      --wsql = wsql||'inner join (select * from PLANOS_TPLA where BDCTALON like '''||wclassificacao||'%'') TPLA on (TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO and TPLA.BDCODTPLA = TLAN.BDDEBITO) ';
      --wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 0) ';

      -- Caso seja contabilização do Lalur
      if (PRCONTABILIZACAOLALUR = 1) then
         begin
           wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC ';
           wsql = wsql||'join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
           if (wtipcta = 0) then --Conta título
              wsql = wsql||'inner join VSUC_SELECT_CONTAS TPLA on (TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO and TPLA.BDCODTPLA = TLAN.BDDEBITO) ';
         end
      else
         begin
           --#148507 - Machado - 16/03/2021 - No FB3 ele não conseguia indexar na ordem que estava
           wsql = wsql||'FROM (select * from PLANOS_TPLA where bdcodplapadrao = '||wcodplapadrao||' AND BDCTALON like '''||wclassificacao||'%'') TPLA ';
           wsql = wsql||'inner join VSUC_EMPRESAS_TLAN TLAN on (TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO and TPLA.BDCODTPLA = TLAN.BDDEBITO) ';
           wsql = wsql||'left join VSUC_EMPRESAS_TLCC TLCC on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
           wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 0) ';
         end
      --#Alt:100735. Melhoria de performance. Carlos Mello - 17/05/2019 - Fim


      --#alt:23030. fim
    END

  --#alt:23030. Ana - 21/03/2018
  /*wsql = wsql||' where TPLA.BDCTALON like ''' || wclassificacao || '%''';
  wsql = wsql||' and tpla.bdcodplapadrao=' || wcodplapadrao;
  wsql = wsql||' and (tpla.bdtipcta = 1)';*/

  wsql = wsql||' where TLAN.BDDATA <= '''||wdatfin||''' ';
  wsql = wsql||' and tlan.bdcodplapadrao = '||wcodplapadrao;

  --#Alt:100735. Melhoria de performance. Carlos Mello - 17/05/2019
  if ((PRCONTABILIZACAOLALUR = 1) and (wtipcta = 1)) then --Conta analítica
     wsql = wsql||' and tlan.bddebito = '||prconta;

  --#alt:130625 - 17/12/2019 - Machado - Adicionado BDDEBCRE nos filtros
  IF (prcc CONTAINING ',') THEN
    BEGIN
      wSQL = wSQL||' and tlcc.BDCODTPCC in ('||prcc||')';
      wSQL = wSQL||' AND TLCC.BDDEBCRE  = 0';
    END
  ELSE IF (prcc = 'null') then
    wSQL = wSQL||' and not EXISTS(select first 1 aaa.bdcodtpcc from vsuc_empresas_tlcc aaa where aaa.BDCODEMP = tlan.bdcodemp and aaa.BDCHAVE = tlan.bdchave AND aaa.BDDEBCRE = 0)';
  ELSE IF ((prcc IS NOT NULL) AND (prcc <> '')) THEN
    BEGIN
    wSQL = wSQL||' and tlcc.BDCODTPCC = '||prcc;
      wSQL = wSQL||' AND TLCC.BDDEBCRE  = 0';
    END

  IF (prrelcta IS NOT NULL) THEN
    wsql = wsql||' and tpla.bdrelcta = '||prrelcta||' ';

  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||' and tlan.bdcontabilizacao in ('||WAPENASCONTABILIZACAOSELEC||prcontabilizacao||') ';

  if (PRFILTIPOLAN <> '') then --#212425
    wsql = wsql || ' and (tlan.bdtipolan in (' || PRFILTIPOLAN || ')) '; 

  --#alt:23030. Ana - 21/03/2018
  /*EXECUTE PROCEDURE CONTAR_CHAR(wclassificacao, '.') RETURNING_VALUES :wNivel;
  wsql = wsql||' and tpla.bdnivel >= ' || wNivel;

  wsql = wsql||' and TPLA.bdcodtpla = tlan.bddebito';*/
  if (coalesce(PRLISTAPART,'') <> '') then
     begin
       wsql = wsql||' and tlan.bdcodterceirod in ('||PRLISTAPART||') ';
     end
  else
     begin
  IF ((prparticipante > 0) AND (prparticipante IS NOT NULL)) THEN
     BEGIN
       --#Alt:24142. Corrigido tratamento do participante inicial e final
       IF ((prparticipantefinal = 0) OR (prparticipantefinal IS NULL)) THEN
          wsql = wsql||' and tlan.bdcodterceirod = '||prparticipante||' ';
       ELSE
          wsql = wsql||' and tlan.bdcodterceirod >= '||prparticipante||' ';
     END

  --#Alt:24142. Incluído o tratamento para o participante final. Só exista o parâmetro, mas não estava sendo utilizado.
  IF ((prparticipantefinal > 0) AND (prparticipantefinal IS NOT NULL)) THEN
     BEGIN
       IF ((prparticipante = 0) OR (prparticipante IS NULL)) THEN
          wsql = wsql||' and tlan.bdcodterceirod = '||prparticipantefinal||' ';
       ELSE
          wsql = wsql||' and tlan.bdcodterceirod <= '||prparticipantefinal||' ';
     END
     end

  IF ((prempreendimento > 0) AND (prempreendimento IS NOT NULL)) THEN
    wsql = wsql||' and TINCORP.BDCODEMPREENDIMENTO = '||prempreendimento||' ';

  IF ((prunidimob > 0) AND (prunidimob IS NOT NULL)) THEN
    wsql = wsql||' and TINCORP.BDCODIGOUNIIMOB = '||prunidimob||' ';
  --#alt:23030. fim
  if (prcodplahistlalur > 0) then
       wsql = wsql||' and (TLAN.bdcodtphi = '||coalesce(prcodplahistlalur,0)||') ';

  wsql = wsql||' and (tlan.bdcodemp = '||prcodemp||') ';

/* FIM RECONSTRUÇÃO */

  FOR EXECUTE STATEMENT wSQL INTO :wcodemp, :wsalant, :wsalatu DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      wpos_pernamatriz = POSITION(prcodemp, wcodemp);
      wpos_matriz = POSITION(wcodemp,  prcodemp);
      wpos_filial = POSITION(wfilial,  prcodemp);
      IF ((prcodemp = wcodemp) OR
          --Estou na filial mas o lançamento foi feito na matriz para a filial(uma perna)
          -- ((prcodemp = wfilial) AND (1 = wtipolancfilial)) OR
          --Estou na matriz e tem uma perna do lançamento na filial, mas só quero os lançamentos da matriz(a perna da matriz) e que a matriz esteja no filtro
          -- ((prcodemp = wcodemp) AND (wfilial <> 0) AND (1 <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
          --Estou na matriz mas também quero os lançamentos da filial conforme o filtro(Lançamentos que foram feito na filial -> BDCODEMP = Filial)
          ((prmatrizfilialconsolidado = 1) AND (prcodemp <> wcodemp) AND (wpos_matriz > 0))
          --Estou na matriz mas também quero a perna que está na filial conforme o filtro
          -- ((prmatrizfilialconsolidado = 1) AND (wcodemp = prcodemp) AND (wfilial <> 0) AND (1 = wtipolancfilial) AND (wpos_filial > 0))
      ) THEN
         BEGIN
           saldo_ant_deb = saldo_ant_deb +  coalesce(wsalant, 0);
           SALDO_DEB = SALDO_DEB + coalesce(wsalatu, 0);
         END
    END

  -- SALDO A CRÉDITO ___________________________________________________________
  wsql = 'Select '||prcodemp||' as bdcodemp, ';
  /**************** ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS ****************/
  IF ((prcc IS NULL) OR (prcc = '') or (PRCC = 'null')) THEN
    BEGIN
      IF (prIndice = 0) THEN
        wsql = wsql||'sum(case when (tlan.bddata < '''||prdataini||''') then tlan.bdvalor else 0 end) as bdsalant, ';
      ELSE
        BEGIN
          wsql = wsql||'sum(case when (tlan.bddata < '''||prdataini||''') then tlan.bdvalor';
          wsql = wsql||'      / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                 (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalant, ';
        END

      wsql = wsql||'sum(case when ((tlan.bddata >= '''||prdataini||''')';
      IF (prignorazeramento = 1) THEN
         wsql = wsql||' and (TLAN.BDTIPOLAN <> 10)';

      IF (prIndice = 0) THEN
        wsql = wsql||') then tlan.bdvalor else 0 end) as bdsalatu ';
      ELSE
        BEGIN
          wsql = wsql||') then tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                               (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalatu ';
        END

      --#alt:23030. Forma incorreta de consultar os dados, deixa o processo lento e não retorna o valor correto. Ana - 20/03/2018
      --wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN, planos_tpla TPLA ';
      --#Alt:100735. Melhoria de performance. Carlos Mello - 17/05/2019 - Início
      --wsql = wsql||'inner join (select * from PLANOS_TPLA where BDCTALON like '''||wclassificacao||'%'') TPLA on (TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO and TPLA.BDCODTPLA = TLAN.BDCREDITO) ';
      --wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 1) ';

      -- Caso seja contabilização do Lalur
      if (PRCONTABILIZACAOLALUR = 1) then
         begin
           wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';
           if (wtipcta = 0) then --Conta título
              wsql = wsql||'inner join VSUC_SELECT_CONTAS TPLA on (TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO and TPLA.BDCODTPLA = TLAN.BDCREDITO) ';
         end
      else
         begin
           wsql = wsql||'FROM (select * from PLANOS_TPLA where bdcodplapadrao = '||wcodplapadrao||' AND BDCTALON like '''||wclassificacao||'%'') TPLA ';
           wsql = wsql||'inner join VSUC_EMPRESAS_TLAN TLAN on (TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO and TPLA.BDCODTPLA = TLAN.BDCREDITO) ';
           wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 1) ';
         end
      --#Alt:100735. Melhoria de performance. Carlos Mello - 17/05/2019 - Fim


      --#alt:23030. fim
    END
  /**************** ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS ****************/
  ELSE
    BEGIN
      IF (prIndice = 0) THEN
        wsql = wsql||'sum(case when (tlan.bddata < '''||prdataini||''') then tlcc.bdvalor else 0 end) as bdsalant, ';
      ELSE
        BEGIN
         wsql = wsql||'sum(case when (tlan.bddata < '''||prdataini||''') then tlcc.bdvalor';
          wsql = wsql||'      / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                 (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalant, ';
        END

      wsql = wsql||'sum(case when ((tlan.bddata >= '''||prdataini||''')';
      IF (prignorazeramento = 1) THEN
         wsql = wsql||' and (TLAN.BDTIPOLAN <> 10)';

      IF (prIndice = 0) THEN
        wsql = wsql||') then tlcc.bdvalor else 0 end) as bdsalatu ';
      ELSE
        BEGIN
          wsql = wsql||') then tlcc.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                               (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalatu ';
        END

      --#alt:23030. Forma incorreta de consultar os dados, deixa o processo lento e não retorna o valor correto. Ana - 20/03/2018
      --wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC, planos_tpla TPLA ';
      --#Alt:100735. Melhoria de performance. Carlos Mello - 17/05/2019 - Início
      --wsql = wsql||'inner join (select * from PLANOS_TPLA where BDCTALON like '''||wclassificacao||'%'') TPLA on (TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO and TPLA.BDCODTPLA = TLAN.BDCREDITO) ';
      --wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 1) ';

      -- Caso seja contabilização do Lalur
      if (PRCONTABILIZACAOLALUR = 1) then
         begin
           wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC ';
           wsql = wsql||'join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
           if (wtipcta = 0) then --Conta título
              wsql = wsql||'inner join VSUC_SELECT_CONTAS TPLA on (TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO and TPLA.BDCODTPLA = TLAN.BDCREDITO) ';
         end
      else
         begin
           --#148507 - Machado - 16/03/2021 - No FB3 ele não conseguia indexar na ordem que estava
           wsql = wsql||'FROM (select * from PLANOS_TPLA where bdcodplapadrao = '||wcodplapadrao||' AND BDCTALON like '''||wclassificacao||'%'') TPLA ';
           wsql = wsql||'inner join VSUC_EMPRESAS_TLAN TLAN on (TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO and TPLA.BDCODTPLA = TLAN.BDCREDITO) ';
           wsql = wsql||'left join VSUC_EMPRESAS_TLCC TLCC on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
           wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 1) ';
         end
      --#Alt:100735. Melhoria de performance. Carlos Mello - 17/05/2019 - Fim

      --#alt:23030. fim
    END

  --#alt:23030. Ana - 20/03/2018
  /*wsql = wsql||' where TPLA.BDCTALON like ''' || wclassificacao || '%''';
  wsql = wsql||' and tpla.bdcodplapadrao=' || wcodplapadrao;
  wsql = wsql||' and (tpla.bdtipcta = 1)';*/

  wsql = wsql||' where TLAN.BDDATA <= '''||wdatfin||''' ';
  wsql = wsql||' and tlan.bdcodplapadrao = '||wcodplapadrao;

  --#Alt:100735. Melhoria de performance. Carlos Mello - 17/05/2019
  if ((PRCONTABILIZACAOLALUR = 1) and (wtipcta = 1)) then --Conta analítica
     wsql = wsql||' and tlan.bdcredito = '||prconta;

  --#alt:130625 - 17/12/2019 - Machado - Adicionado BDDEBCRE nos filtros
  IF (prcc CONTAINING ',') THEN
   BEGIN
      wSQL = wSQL||' and tlcc.BDCODTPCC in ('||prcc||')';
      wSQL = wSQL||' AND TLCC.BDDEBCRE  = 1';
    END
  ELSE if (prcc = 'null') then
    wSQL = wSQL||' and not EXISTS(select first 1 aaa.bdcodtpcc from vsuc_empresas_tlcc aaa where aaa.BDCODEMP = tlan.bdcodemp and aaa.BDCHAVE = tlan.bdchave AND aaa.BDDEBCRE = 1)';
  ELSE IF ((prcc IS NOT NULL) AND (prcc <> '')) THEN
    BEGIN
      wSQL = wSQL||' and tlcc.BDCODTPCC = '||prcc;
      wSQL = wSQL||' AND TLCC.BDDEBCRE  = 1';
    END

  IF (prrelcta IS NOT NULL) THEN
    wsql = wsql||' and tpla.bdrelcta = '||prrelcta||' ';

  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||' and tlan.bdcontabilizacao in ('||WAPENASCONTABILIZACAOSELEC||prcontabilizacao||') ';

  if (PRFILTIPOLAN <> '') then --#212425
    wsql = wsql || ' and (tlan.bdtipolan in (' || PRFILTIPOLAN || ')) '; 

  --#alt:23030. Ana - 20/03/2018
  /*EXECUTE PROCEDURE CONTAR_CHAR(wclassificacao, '.') RETURNING_VALUES :wNivel;
  wsql = wsql||' and tpla.bdnivel >= ' || wNivel;

  wsql = wsql||' and TPLA.bdcodtpla = tlan.bdcredito';*/
  if (coalesce(PRLISTAPART,'') <> '') then
     begin
       wsql = wsql||' and tlan.bdcodterceiroc in ('||PRLISTAPART||') ';
     end
  else
     begin
  IF ((prparticipante > 0) AND (prparticipante IS NOT NULL)) THEN
     BEGIN
       --#Alt:24142. Corrigido tratamento do participante inicial e final
       IF ((prparticipantefinal = 0) OR (prparticipantefinal IS NULL)) THEN
          wsql = wsql||' and tlan.bdcodterceiroc = '||prparticipante||' ';
       ELSE
          wsql = wsql||' and tlan.bdcodterceiroc >= '||prparticipante||' ';
     END

  --#Alt:24142. Incluído o tratamento para o participante final. Só exista o parâmetro, mas não estava sendo utilizado.
  IF ((prparticipantefinal > 0) AND (prparticipantefinal IS NOT NULL)) THEN
     BEGIN
       IF ((prparticipante = 0) OR (prparticipante IS NULL)) THEN
          wsql = wsql||' and tlan.bdcodterceiroc = '||prparticipantefinal||' ';
       ELSE
          wsql = wsql||' and tlan.bdcodterceiroc <= '||prparticipantefinal||' ';
     END
     end

  IF ((prempreendimento > 0) AND (prempreendimento IS NOT NULL)) THEN
    wsql = wsql||' and TINCORP.BDCODEMPREENDIMENTO = '||prempreendimento||' ';

  IF ((prunidimob > 0) AND (prunidimob IS NOT NULL)) THEN
    wsql = wsql||' and TINCORP.BDCODIGOUNIIMOB = '||prunidimob||' ';
  --#alt:23030. fim

  wsql = wsql||' and (tlan.bdcodemp = '||prcodemp||') ';

  FOR EXECUTE STATEMENT wSQL INTO :wcodemp, :wsalant, :wsalatu DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      wpos_pernamatriz = POSITION(prcodemp, wcodemp);
      wpos_matriz = POSITION(wcodemp,  prcodemp);
      wpos_filial = POSITION(wfilial,  prcodemp);
      IF ((prcodemp = wcodemp) OR
          --Estou na filial mas o lançamento foi feito na matriz para a filial(uma perna)
          -- ((prcodemp = wfilial) AND (2 = wtipolancfilial)) OR
          --Estou na matriz e tem uma perna do lançamento na filial, mas só quero os lançamentos da matriz(a perna da matriz) e que a matriz esteja no filtro
          -- ((prcodemp = wcodemp) AND (wfilial <> 0) AND (2 <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
          --Estou na matriz mas também quero os lançamentos da filial conforme o filtro(Lançamentos que foram feito na filial -> BDCODEMP = Filial)
          ((prmatrizfilialconsolidado = 1) AND (prcodemp <> wcodemp) AND (wpos_matriz > 0))
          --Estou na matriz mas também quero a perna que está na filial conforme o filtro
          -- ((prmatrizfilialconsolidado = 1) AND (wcodemp = prcodemp) AND (wfilial <> 0) AND (2 = wtipolancfilial) AND (wpos_filial > 0))
      ) THEN
         BEGIN
           saldo_ant_cre = saldo_ant_cre +  coalesce(wsalant, 0);
           SALDO_cre = SALDO_cre + coalesce(wsalatu, 0);
         END
    END

  -- SALDO ANTERIOR ____________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5))  THEN -- ATIVO e DESPESAS
     SALDO_ANTERIOR = (SALDO_ANT_DEB-SALDO_ANT_CRE);
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        SALDO_ANTERIOR = (SALDO_ANT_CRE-SALDO_ANT_DEB);

  IF (saldo_anterior IS NULL) THEN
    saldo_anterior = 0;

  -- SALDO ATUAL _______________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5)) THEN -- ATIVO e DESPESAS
     saldo_atual = saldo_anterior + SALDO_DEB - SALDO_CRE;
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        saldo_atual = saldo_anterior - SALDO_DEB + SALDO_CRE;

  IF (saldo_atual IS NULL ) THEN
    saldo_atual = 0;

  -- MOVIMENTO _________________________________________________________________
  movimento = saldo_atual - saldo_anterior; --alt:9515 - Adicionado campo do movimento. Pedro


  SUSPEND;
END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_CONTAS_EMPRESA (
    BDCODEMP INTEGER,
    BDCODPLANO INTEGER,
    BDCLASSIFICACAO VARCHAR(40))
RETURNS (
    BDCODPLAPADRAO INTEGER,
    BDCODTPLA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDTIPCTA INTEGER,
    BDCTAOBRIG DM_BOOLEAN,
    BDCTAEMP INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCTAEMP INTEGER;
BEGIN
  wsql = '';
  wsql = wsql || ' select TPLA.BDCODPLAPADRAO, TPLA.BDCODTPLA, TPLA.BDCTALON, TPLA.BDNOMCTA, TPLA.BDTIPCTA, CTEMP.BDCODTPLA as BDCTAEMP, ';
  wsql = wsql || '        CTRL.BDCTAOBRIGATORIA from PLANOS_TPLA TPLA ';
  wsql = wsql || ' left join VSUC_CONTAS_EMPRESA CTEMP on (CTEMP.BDCODPLAPADRAO = TPLA.BDCODPLAPADRAO and CTEMP.BDCODTPLA = TPLA.BDCODTPLA and CTEMP.BDCODEMP = '||BDCODEMP||') ';
  wsql = wsql || ' left join VSUC_EMPRESAS_TCONTROLECONTAS CTRL on (CTRL.BDCODPLAPADRAO = TPLA.BDCODPLAPADRAO and CTRL.BDCODTPLA = TPLA.BDCODTPLA and CTRL.BDCODEMP = '||BDCODEMP||') ';
  wsql = wsql || ' where (TPLA.BDCODPLAPADRAO = '|| BDCODPLANO ||') ';
  IF (bdclassificacao <> '') THEN
    wsql = wsql || ' and (substring(TPLA.BDCTALON from 1 for character_length('''||BDCLASSIFICACAO||''')) = '''||BDCLASSIFICACAO||''') order by TPLA.BDCTALON ';

  FOR EXECUTE STATEMENT wsql
  INTO :bdcodplapadrao, :bdcodtpla, :bdctalon, :bdnomcta, :bdtipcta, :wctaemp, :bdctaobrig DO
  BEGIN
    IF (bdtipcta = 1) THEN
      BEGIN
        IF (bdctaobrig = 1) THEN
          bdctaemp = 2;
        ELSE
        IF (wctaemp IS NOT NULL) THEN
          bdctaemp = 1;
        ELSE
          bdctaemp = 0;
      END
    ELSE
      bdctaemp = NULL;

    SUSPEND;
  END
END
^

CREATE OR ALTER PROCEDURE SP_CONTAS_LANCADAS (
    BDCODEMP INTEGER,
    BDCODPLANO INTEGER,
    BDREFERENCIA INTEGER,
    BDFILIAIS INTEGER = 0)
RETURNS (
    BDCONTA INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WSQLAUX VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
BEGIN
  -- Monta o sql que retorna as empresas
  wsqlaux = 'SELECT BDCODEMP FROM SP_RETORNA_EMPRESA_FILIAIS(' 
          || BDCODEMP || ', ' 
          || BDREFERENCIA || ')';

  FOR EXECUTE STATEMENT wsqlaux
      INTO :WCODEMP
  DO
  BEGIN
    -- Aqui unimos as contas de Débito e as de Crédito e retornamos sem duplicar
    wsql = 
          ' SELECT DISTINCT X.BDCONTA ' 
        || '   FROM ( '
        || '         SELECT TLAN.BDDEBITO AS BDCONTA '
        || '           FROM VSUC_EMPRESAS_TLAN TLAN '
        || '          WHERE TLAN.BDCODEMP = ' || WCODEMP 
        || '            AND TLAN.BDCODPLAPADRAO = ' || BDCODPLANO
        || '         UNION '    -- UNION elimina duplicados
        || '         SELECT TLAN.BDCREDITO AS BDCONTA '
        || '           FROM VSUC_EMPRESAS_TLAN TLAN '
        || '          WHERE TLAN.BDCODEMP = ' || WCODEMP
        || '            AND TLAN.BDCODPLAPADRAO = ' || BDCODPLANO
        || '       ) X ';

    FOR EXECUTE STATEMENT wsql
        INTO :BDCONTA
    DO
    BEGIN
      IF (BDCONTA IS NOT NULL) THEN
        SUSPEND;
    END
  END
END
^

CREATE OR ALTER PROCEDURE VSUC_RETORNA_CONTAS_ONLINE (
    BDCODPLAONLINE INTEGER,
    BDCODPLAPADRAO INTEGER)
RETURNS (
    BDCONTA INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCONTADEBPROV INTEGER;
DECLARE VARIABLE WCONTACREDPROV INTEGER;
DECLARE VARIABLE WCONTADEBPGTO INTEGER;
DECLARE VARIABLE WCONTACREDPGTO INTEGER;
BEGIN
  wsql = '';
  wsql = wsql || ' select distinct CONF.BDCONTADEBPROV, CONF.BDCONTACREDPROV, CONF.BDCONTADEBPGTO, CONF.BDCONTACREDPGTO from VW_TCONF_CONTAS_REF CONF ';
  wsql = wsql || ' where (CONF.BDCODPLANOONLINE = '|| BDCODPLAONLINE ||') and (CONF.BDCODPLAPADRAO = '|| BDCODPLAPADRAO ||')';

  FOR EXECUTE STATEMENT wsql
  INTO :WCONTADEBPROV, :WCONTACREDPROV, :WCONTADEBPGTO, :WCONTACREDPGTO DO
  BEGIN
    BDCONTA = WCONTADEBPROV;
    IF (BDCONTA IS NOT NULL) THEN
      SUSPEND;

    BDCONTA = WCONTACREDPROV;
    IF (BDCONTA IS NOT NULL) THEN
      SUSPEND;

    BDCONTA = WCONTADEBPGTO;
    IF (BDCONTA IS NOT NULL) THEN
      SUSPEND;

    BDCONTA = WCONTACREDPGTO;
    IF (BDCONTA IS NOT NULL) THEN
      SUSPEND;
  END
END
^

/* Restore proc. body: SP_RETORNA_SALDO_MATRIZFILIAL */
ALTER PROCEDURE SP_RETORNA_SALDO_MATRIZFILIAL(PRCODEMP INTEGER,
PRMATRIZFILIAIS VARCHAR(2048),
PRCONTA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO SMALLINT,
PRCC INTEGER,
PRRELCTA INTEGER,
PRREFEMP INTEGER,
BDCONCILIADOS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
MOVIMENTO NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
CODEMP INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WTEMCC SMALLINT = 0;
DECLARE VARIABLE WTAMANHO INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(50);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WGRUPOCTA INTEGER;
DECLARE VARIABLE WDEBITO NUMERIC(15,2);
DECLARE VARIABLE WCREDITO NUMERIC(15,2);
DECLARE VARIABLE WLEVEL INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WSQLEMP VARCHAR(10240);
DECLARE VARIABLE WCODEMPEFILIAL INTEGER;
DECLARE VARIABLE WSALDODEB NUMERIC(15,2);
DECLARE VARIABLE WSALDOCRE NUMERIC(15,2);
DECLARE VARIABLE WSALANTDEB NUMERIC(15,2);
DECLARE VARIABLE WSALANTCRE NUMERIC(15,2);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WVLR NUMERIC(15,2);
BEGIN
  codemp = prcodemp;

  IF (prmatrizfiliais IS NULL) THEN
     prmatrizfiliais = prcodemp;

  -- BDCONCILIADOS:
  --   0: Todos
  --   1: Conciliados
  --   2: Não conciliados
  --   3: Pendentes
  --   4: Normal (todos, porém sem mostrar a coluna no relatório)

  -- pega a classificação da conta passada por parametro (prconta) _____________
  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta, planos_tpla.bdcodplapadrao
  FROM PLANOS_TPLA
  WHERE planos_tpla.bdcodtpla = :prconta
  AND planos_tpla.bdcodplapadrao = (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM tempresas_ref tref
                                    WHERE tref.bdcodemp = :prcodemp
                                    AND tref.bdrefemp <= :prrefemp
                                    ORDER BY tref.bdrefemp DESC)
  INTO :wclassificacao, :wgrupocta, :wcodplapadrao;

  wtamanho = strlen(wclassificacao);

  -- retorna o nivel da conta para calcular ou não as contas descendentes ______
  wsql = '';
  wsql = wsql||'select count(tpla.bdcodtpla) from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
  wsql = wsql||'and tpla.bdctalon like '''||wclassificacao||'%'' ';
  EXECUTE STATEMENT wsql INTO :wlevel;

  -- configura datas para serem usadas no sql __________________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);



  -- retorna as empresas selecionadas
  wsqlemp = 'select temp.bdcodemp bdempresasefilial ';
  wsqlemp = wsqlemp||'from tempresas temp ';
  wsqlemp = wsqlemp||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsqlemp = wsqlemp||'where temp.bdcodemp in ('||PRMATRIZFILIAIS||') ';
  wsqlemp = wsqlemp||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';
  -- executa o sql das empresas

  -- SALDO A DÉBITO ____________________________________________________________
  SALDO_DEB = 0;
  wsaldodeb = 0;
  -- SALDO A CRÉDITO ___________________________________________________________
  SALDO_CRE = 0;
  wsaldocre = 0;
  -- SALDO ANTERIOR A DÉBITO _________________________________________________
  SALDO_ANT_DEB = 0;
  wsalantdeb = 0;
  -- SALDO ANTERIOR A CRÉDITO __________________________________________________
  SALDO_ANT_CRE = 0;
  wsalantcre = 0;

  movimento = 0;

  FOR EXECUTE STATEMENT wsqlemp
              INTO :wcodempefilial DO
  BEGIN


  -- SALDO A DÉBITO ____________________________________________________________
  -- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  --#alt:5837.
  /*if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
            join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp, ';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
     wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
     BEGIN
       wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
       IF (prrelcta IS NOT NULL) THEN
          wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
       ELSE
          wsql = wsql||') ';
     END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
     wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
     wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lançamento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' and (Upper(BDCONCD) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' and ((Upper(BDCONCD) = '||'''FALSE'''||') or (BDCONCD is null))';

  wsql = wsql||' group by tlan.bdcodemp ';
  --#alt:5837.
  /*for execute statement wSQL into :wsaldodeb do
  if (wsaldodeb is null) then
     wsaldodeb=0;*/
  wsaldodeb = 0;
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
   --   SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:wcodempefilial,:wcodemp,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
   --   IF (wpermite = 1) THEN
        wsaldodeb = wsaldodeb + wvlr;
    END
  saldo_deb = saldo_deb + wsaldodeb;

--  exception ex_date;

  -- SALDO A CRÉDITO ___________________________________________________________
  -- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  --#alt:5837.
  /*if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN '; */
  wsql = 'Select tlan.bdcodemp, ';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
     BEGIN
       wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
       IF (prrelcta IS NOT NULL) THEN
          wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
       ELSE
          wsql = wsql||') ';
     END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
     wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
     wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lançamento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' and (Upper(BDCONCC) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' and ((Upper(BDCONCC) = '||'''FALSE'''||') or (BDCONCD is null))';

  wsql = wsql||' group by tlan.bdcodemp ';
  --#alt:5837.
  /*for execute statement wSQL into :wsaldocre do
  if (wsaldocre is null) then
     wsaldocre=0;*/
  wsaldocre = 0;
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
 --     SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:wcodempefilial,:wcodemp,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
 --     IF (wpermite = 1) THEN
        wsaldocre = wsaldocre + wvlr;
    END
  saldo_cre = saldo_cre + wsaldocre;

  -- SALDO ANTERIOR A DÉBITO _________________________________________________
  -- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  --#alt:5837.
  /*if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp, ';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
     BEGIN
       wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
       IF (prrelcta IS NOT NULL) THEN
          wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
       ELSE
          wsql = wsql||') ';
     END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
     wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
     wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lançamento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' and (Upper(BDCONCD) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' and ((Upper(BDCONCD) = '||'''FALSE'''||') or (BDCONCD is null))';

  wsql = wsql||' group by tlan.bdcodemp';
  --#alt:5837.
  /*for execute statement wSQL into :wsalantdeb do
  if (wsalantdeb is null) then
     wsalantdeb=0;*/
  wsalantdeb = 0;
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
--      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:wcodempefilial,:wcodemp,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
--      IF (wpermite = 1) THEN
        wsalantdeb = wsalantdeb + wvlr;
    END
  saldo_ant_deb = saldo_ant_deb + wsalantdeb;

  -- SALDO ANTERIOR A CRÉDITO __________________________________________________
  -- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  --#alt:5837.
  /*if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';  */
  wsql = 'Select tlan.bdcodemp,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT É FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT É FEITO PARA QUANDO NÃO TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
     BEGIN
       wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
       IF (prrelcta IS NOT NULL) THEN
          wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
       ELSE
          wsql = wsql||') ';
     END
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'where (tlan.bdcodemp = '||wcodempefilial||') ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
     wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
     wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lançamento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' and (Upper(BDCONCC) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' and ((Upper(BDCONCC) = '||'''FALSE'''||') or (BDCONCD is null))';

  wsql = wsql||' group by tlan.bdcodemp';
  --#alt:5837.
  /*for execute statement wSQL into :wsalantcre do
  if (wsalantcre is null) then
     wsalantcre=0;*/
  wsalantcre = 0;
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
--      SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:wcodempefilial,:wcodemp,:prmatrizfilialconsolidado,:prmatrizfiliais) INTO :wpermite;
--      IF (wpermite = 1) THEN
        wsalantcre = wsalantcre + wvlr;
    END

  saldo_ant_cre = saldo_ant_cre + wsalantcre;

END /* matriz e filiais */

  -- SALDO ANTERIOR ____________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5))  THEN -- ATIVO e DESPESAS
     SALDO_ANTERIOR = (SALDO_ANT_DEB-SALDO_ANT_CRE);
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        SALDO_ANTERIOR = (SALDO_ANT_CRE-SALDO_ANT_DEB);

  IF (saldo_anterior IS NULL) THEN
    saldo_anterior = 0;

  -- SALDO ATUAL _______________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5)) THEN -- ATIVO e DESPESAS
     saldo_atual = saldo_anterior + SALDO_DEB - SALDO_CRE;
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        saldo_atual = saldo_anterior - SALDO_DEB + SALDO_CRE;

  IF (saldo_atual IS NULL ) THEN
    saldo_atual = 0;
  ELSE
    BEGIN
      movimento = saldo_atual - saldo_anterior;
    END

  SUSPEND;
END
^

/* Restore proc. body: SP_RETORNA_SALDO_MATRIZFILIAL_X */
create or alter procedure SP_RETORNA_SALDO_MATRIZFILIAL_X (
    PRCODEMP integer,
    PRMATRIZFILIAIS varchar(2048),
    PRCONTA integer,
    PRDATAINI date,
    PRDATAFIM date,
    PRIGNORAZERAMENTO smallint,
    PRCC integer,
    PRRELCTA integer,
    PRREFEMP integer,
    BDCONCILIADOS integer,
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRINTCONTABILLALUR integer = 0,
    PRCODTERCEIRO integer = 0,
    PRCONTABILIZACAOLALUR integer = 0,
    PRCODTPHISTLALUR integer = 0)
returns (
    SALDO_ANT_DEB numeric(15,2),
    SALDO_ANT_CRE numeric(15,2),
    SALDO_DEB numeric(15,2),
    SALDO_CRE numeric(15,2),
    MOVIMENTO numeric(15,2),
    SALDO_ATUAL numeric(15,2),
    SALDO_ANTERIOR numeric(15,2),
    CODEMP integer,
    CHAVELAN integer)
as
declare variable WSQL varchar(5000);
declare variable WTEMCC smallint = 0;
declare variable WTAMANHO integer;
declare variable WCLASSIFICACAO varchar(50);
declare variable WDATINI varchar(10);
declare variable WDATFIN varchar(10);
declare variable WGRUPOCTA integer;
declare variable WDEBITO numeric(15,2);
declare variable WCREDITO numeric(15,2);
declare variable WLEVEL integer;
declare variable WCODPLAPADRAO integer;
declare variable WSQLEMP varchar(10240);
declare variable WCODEMPEFILIAL integer;
declare variable WSALDODEB numeric(15,2);
declare variable WSALDOCRE numeric(15,2);
declare variable WSALANTDEB numeric(15,2);
declare variable WSALANTCRE numeric(15,2);
declare variable WCODEMP integer;
declare variable WFILIAL integer;
declare variable WTIPOLANCFILIAL integer;
declare variable WPERMITE integer;
declare variable WVLR_SALANT_DEB numeric(15,2);
declare variable WVLR_SALATU_DEB numeric(15,2);
declare variable WVLR_SALANT_CRE numeric(15,2);
declare variable WVLR_SALATU_CRE numeric(15,2);
declare variable WCHAVELAN integer;
declare variable WDEBCRE integer;
BEGIN
  codemp = prcodemp;
  IF (prmatrizfiliais IS NULL) THEN
     prmatrizfiliais = prcodemp;

  -- BDCONCILIADOS:
  --   0: Todos
  --   1: Conciliados
  --   2: Não conciliados
  --   3: Pendentes
  --   4: Normal (todos, porém sem mostrar a coluna no relatório)

  -- pega a classificação da conta passada por parametro (prconta) _____________
  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta, planos_tpla.bdcodplapadrao
  FROM PLANOS_TPLA
  WHERE planos_tpla.bdcodtpla = :prconta
  AND planos_tpla.bdcodplapadrao = (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM tempresas_ref tref
                                    WHERE tref.bdcodemp = :prcodemp
                                    AND tref.bdrefemp <= :prrefemp
                                    ORDER BY tref.bdcodemp DESC, tref.bdrefemp DESC)
  INTO :wclassificacao, :wgrupocta, :wcodplapadrao;

  wtamanho = strlen(wclassificacao);

  -- retorna o nivel da conta para calcular ou não as contas descendentes ______
  wsql = '';
  wsql = wsql||'select count(tpla.bdcodtpla) from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
  wsql = wsql||' and tpla.bdctalon starts with '''||wclassificacao||''' ';
  EXECUTE STATEMENT wsql INTO :wlevel;

  -- configura datas para serem usadas no sql __________________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- retorna as empresas selecionadas
  wsqlemp = 'select temp.bdcodemp bdempresasefilial ';
  wsqlemp = wsqlemp||'from tempresas temp ';
  --wsqlemp = wsqlemp||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) '; --alt:13181 - Não usa para nada este join. Pedro
  wsqlemp = wsqlemp||'where temp.bdcodemp in ('||PRMATRIZFILIAIS||') ';
  wsqlemp = wsqlemp||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';
  -- executa o sql das empresas

  -- SALDO A DÉBITO ____________________________________________________________
  SALDO_DEB = 0;
  wsaldodeb = 0;
  -- SALDO A CRÉDITO ___________________________________________________________
  SALDO_CRE = 0;
  wsaldocre = 0;
  -- SALDO ANTERIOR A DÉBITO _________________________________________________
  SALDO_ANT_DEB = 0;
  wsalantdeb = 0;
  -- SALDO ANTERIOR A CRÉDITO __________________________________________________
  SALDO_ANT_CRE = 0;
  wsalantcre = 0;
  movimento = 0;

  FOR EXECUTE STATEMENT wsqlemp
              INTO :wcodempefilial DO
  BEGIN

    --alt:11995 - 12/08/2015 - Somente irá agruprar tudo se não estiver fazendo isso na integração do Contábil pro Lalur (na parte de gravar as chaves dos lançamentos integrados). Pedro
    wSQL = '';
    IF ((PRINTCONTABILLALUR IS NULL) OR (PRINTCONTABILLALUR = 0))  THEN
      BEGIN
        wsql =        'select bddebcre, bdcodemp, null as BDCHAVE,';
        wsql = wsql|| '       sum(bdsalant_deb) as bdsalant_deb, sum(bdsalatu_deb) as bdsalatu_deb, ';
        wsql = wsql|| '       sum(bdsalant_cre) as bdsalant_cre, sum(bdsalatu_cre) as bdsalatu_cre  ';
    
        wsql = wsql|| ' from (';
      END
    --alt:11995 - Fim

    /*****Débito***************************************************************************************************************************************************************************/

    --alt:13181 - 04/03/2016 - Se não estiver gravando a integração, não precisa detalhar pela chave, o que agiliza muito o processo. Pedro
    IF (printcontabillalur = 1) THEN
      wsql = wsql|| 'Select 1 as BDDEBCRE, tlan.bdcodemp, TLAN.BDCHAVE, ';
    ELSE
      wsql = wsql|| 'Select 1 as BDDEBCRE, tlan.bdcodemp, ';
    --alt:13181 - Fim

    --if ((prcc <> 0) and (not (prcc is null))) then
    --   SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP))
    --else
      --coalesce(sum(tlan.bdvalor),0) AS SOMA
        wsql = wsql|| ' coalesce(sum(case when(tlan.bddata < '''||wdatini||''') then  tlan.bdvalor ';
        wsql = wsql|| '              else  0  end), 0) as bdsalant_deb, ';
    
        wsql = wsql|| ' coalesce(sum(case when(tlan.bddata >= '''||wdatini||''') then  tlan.bdvalor ';
        wsql = wsql|| '              else  0  end), 0) as bdsalatu_deb, ';
        wsql = wsql|| '0 as bdsalant_cre, 0 as bdsalatu_cre ';
    
        wsql = wsql|| ' FROM VSUC_EMPRESAS_TLAN TLAN ';
    
    IF (wlevel > 1) THEN
       BEGIN
         wsql = wsql|| ' inner join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null)) ';
         IF (prrelcta IS NOT NULL) THEN
            wsql = wsql|| ' and (tpla.bdrelcta = '||prrelcta||')) ';
         ELSE
            wsql = wsql|| ' ) ';
       END
  
    wsql = wsql|| ' where (tlan.bdcodplapadrao = '||wcodplapadrao||') ';

    --alt:11995 - 30/07/2015 - Quando for o processo de integração do contábil para o lalur não deve somar os lançamentos já integrados manualmente. Pedro
    IF (PRINTCONTABILLALUR = 1) THEN
       BEGIN
         wsql = wsql||' and (not exists (select BDCHAVE from VLAL_VINCULO_CONTABIL_LALUR TVINC ';
         wsql = wsql||' left join VLAL_EMPRESAS_TLLA TLA on (TVINC.BDCODEMPFILIAL = TLA.bdcodemp AND TVINC.BDCODLLA = TLA.bdcodlla)';
         wsql = wsql||' where BDCODEMPFILIAL = tlan.BDCODEMP and BDCHAVE = tlan.BDCHAVE AND TLA.BDLANANUAL = ''TRUE''))';
       END
  
    IF (prcontabilizacao <> 99) THEN
       wsql = wsql|| ' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';

    IF (wlevel = 1) THEN
       wsql = wsql|| ' and (tlan.bddebito = '||prconta||') ';
    ELSE
       wsql = wsql|| ' and (tpla.BDCTALON starting with '''||wclassificacao||''') ';

    --#Alt:19568. Incluído o filtro do participante
    IF ((prcodterceiro IS NOT NULL) AND (prcodterceiro <> 0)) THEN
       wsql = wsql|| ' and (tlan.bdcodterceirod = '||prcodterceiro||') ';
    
    --alt:7728 - Estava comentado o ignorar zeramento, habilitei novamente porque estava gerando uma diferença de saldos. Pedro
    IF (prignorazeramento = 1) THEN
       wsql = wsql|| ' AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';
    --alt:7728 - Fim
    
      --if ((prcc <> 0) and (not (prcc is null))) then
       --  AND (TLCC.bdcodtpcc = 'prcc')
    
    IF (bdconciliados = 1) THEN
       wsql = wsql|| ' and (Upper(BDCONCD) = '''||'TRUE'||''') ';
    ELSE
    IF (bdconciliados = 2) THEN
       wsql = wsql|| ' and ((Upper(BDCONCD) = '''||'FALSE'||''') or (BDCONCD is null)) ';
  
    wsql = wsql|| ' and (tlan.bddata <= '''||wdatfin||''') ';

    --alt:11995 - Se estiver carregando as chaves de lançamentos para a integração do Lalur, não pode carregar chaves de períodos anteriores. Pedro
    IF (PRINTCONTABILLALUR = 1)  THEN
      wsql = wsql|| ' and (tlan.bddata >= '''||wdatini||''') ';

    --alt:9604 - Alterada regra do código da empresa e código da filial, pois antes ele não verificava o TipoLancFilial
    --e pegava registros que estavam lançado na filial ou na matriz que não deveriam trazer aqui. Pedro
    --wsql = wsql|| ' and ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
    wsql = wsql|| ' and (tlan.bdcodemp = '||wcodempefilial||') ';

    if (PRCODTPHISTLALUR > 0) then
       wsql = wsql||' and (TLAN.bdcodtphi = '||PRCODTPHISTLALUR||') ';
  
    --alt:13181 - 04/03/2016 - Se não estiver gravando a integração, não precisa detalhar pela chave, o que agiliza muito o processo. Pedro
    IF (printcontabillalur = 1) THEN
      wsql = wsql|| ' group by bddebcre, tlan.bdcodemp, TLAN.BDCHAVE ';
    ELSE
      wsql = wsql|| ' group by bddebcre, tlan.bdcodemp ';
    --alt:13181 - Fim
    

    /******Crédito**************************************************************************************************************************************************************/
    wsql = wsql|| ' union all ';

    --alt:13181 - 04/03/2016 - Se não estiver gravando a integração, não precisa detalhar pela chave, o que agiliza muito o processo. Pedro
    IF (printcontabillalur = 1) THEN
      wsql = wsql|| ' Select 2 as BDDEBCRE, tlan.bdcodemp, TLAN.BDCHAVE, 0 as bdsalant_deb, 0 as bdsalatu_deb, ';
    ELSE
      wsql = wsql|| 'Select 2 as BDDEBCRE, tlan.bdcodemp, 0 as bdsalant_deb, 0 as bdsalatu_deb, ';
    --alt:13181 - Fim
    
      --if ((prcc <> 0) and (not (prcc is null))) then
      --   SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP))
      --else
        --coalesce(sum(tlan.bdvalor),0) AS SOMA
        wsql = wsql|| ' coalesce(sum(case when(tlan.bddata < '''||wdatini||''') then  tlan.bdvalor ';
        wsql = wsql|| '              else  0  end), 0) as bdsalant_cre, ';
    
        wsql = wsql|| ' coalesce(sum(case when(tlan.bddata >= '''||wdatini||''') then  tlan.bdvalor ';
        wsql = wsql|| '              else  0  end), 0) as bdsalatu_cre ';
    
        wsql = wsql|| ' FROM VSUC_EMPRESAS_TLAN TLAN ';
    
    IF (wlevel > 1) THEN
       BEGIN
         wsql = wsql|| ' inner join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null)) ';
         IF (prrelcta IS NOT NULL) THEN
            wsql = wsql|| ' and (tpla.bdrelcta = '||prrelcta||')) ';
         ELSE
            wsql = wsql|| ' ) ';
       END
    
    wsql = wsql|| ' where (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
    
    --alt:11995 - 30/07/2015 - Quando for o processo de integração do contábil para o lalur não deve somar os lançamentos já integrados manualmente. Pedro
    IF (printcontabillalur = 1) THEN
       BEGIN
         wsql = wsql||' and (not exists (select BDCHAVE from VLAL_VINCULO_CONTABIL_LALUR TVINC ';
         wsql = wsql||' left join VLAL_EMPRESAS_TLLA TLA on (TVINC.BDCODEMPFILIAL = TLA.bdcodemp AND TVINC.BDCODLLA = TLA.bdcodlla)';
         wsql = wsql||' where BDCODEMPFILIAL = tlan.BDCODEMP and BDCHAVE = tlan.BDCHAVE AND TLA.BDLANANUAL = ''TRUE''))';
       END

    IF (prcontabilizacao <> 99) THEN
       wsql = wsql|| ' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';

    IF (wlevel = 1) THEN
       wsql = wsql|| ' and (tlan.bdcredito = '||prconta||') ';
    ELSE
       wsql = wsql|| ' and (tpla.BDCTALON starting with '''||wclassificacao||''') ';

    --#Alt:19568. Incluído o filtro do participante
    IF ((prcodterceiro IS NOT NULL) AND (prcodterceiro <> 0)) THEN
       wsql = wsql|| ' and (tlan.bdcodterceiroc = '||prcodterceiro||') ';
    
    --alt:7728 - Estava comentado o ignorar zeramento, habilitei novamente porque estava gerando uma diferença de saldos. Pedro
    IF (prignorazeramento = 1) THEN
       wsql = wsql|| ' AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';
    --alt:7728 - Fim
    
      --if ((prcc <> 0) and (not (prcc is null))) then
       --  AND (TLCC.bdcodtpcc = 'prcc')
    
    IF (bdconciliados = 1) THEN
       wsql = wsql|| ' and (Upper(BDCONCD) = '''||'TRUE'||''') ';
    ELSE
    IF (bdconciliados = 2) THEN
       wsql = wsql|| ' and ((Upper(BDCONCD) = '''||'FALSE'||''') or (BDCONCD is null)) ';
  
    wsql = wsql|| ' and (tlan.bddata <= '''||wdatfin||''') ';

    --alt:11995 - Se estiver carregando as chaves de lançamentos para a integração do Lalur, não pode carregar chaves de períodos anteriores. Pedro
    IF (PRINTCONTABILLALUR = 1)  THEN
      wsql = wsql|| ' and (tlan.bddata >= '''||wdatini||''') ';

    --alt:9604 - Alterada regra do código da empresa e código da filial, pois antes ele não verificava o TipoLancFilial
    --e pegava registros que estavam lançado na filial ou na matriz que não deveriam trazer aqui. Pedro
    --wsql = wsql|| ' and ((tlan.bdcodemp = '||wcodempefilial||') or (bdfilial = '||wcodempefilial||')) ';
    wsql = wsql|| ' and (tlan.bdcodemp = '||wcodempefilial||' ) ';
  
    if (PRCODTPHISTLALUR > 0) then
       wsql = wsql||' and (TLAN.bdcodtphi = '||PRCODTPHISTLALUR||') ';

    --alt:13181 - 04/03/2016 - Se não estiver gravando a integração, não precisa detalhar pela chave, o que agiliza muito o processo. Pedro
    IF (printcontabillalur = 1) THEN
      wsql = wsql|| ' group by bddebcre, tlan.bdcodemp, TLAN.BDCHAVE ';
    ELSE
       wsql = wsql|| ' group by bddebcre, tlan.bdcodemp ';
    --alt:13181 - Fim

    --alt:11995 - 12/08/2015 - Somente irá agruprar tudo se não estiver fazendo isso na integração do Contábil pro Lalur (na parte de gravar as chaves dos lançamentos integrados). Pedro
    IF ((PRINTCONTABILLALUR IS NULL) OR (PRINTCONTABILLALUR = 0))  THEN
       wsql = wsql|| ' ) group by bddebcre, bdcodemp ';

    wvlr_salant_deb = 0;
    wvlr_salatu_deb = 0;
    wvlr_salant_cre = 0;
    wvlr_salatu_cre = 0;

    wsalantdeb = 0;
    wsaldodeb = 0;
    wsalantcre = 0;
    wsaldocre = 0;

    --Com o outro SQL estava deixando o processo muito lento e ocasionando grande lentidão nos clientes. Ana
    IF (printcontabillalur = 0) THEN
       wsql = ' select null, CODEMP, null, SALDO_ANT_DEB, SALDO_DEB, SALDO_ANT_CRE, SALDO_CRE'||
              ' from sp_retorna_saldo_emp_X('||:wcodempefilial||', '||:prconta||','''||:wdatini||''','''||:wdatfin||''', 0, '||:prignorazeramento||', null, null, '||
              :PRREFEMP||', 0,'||:prcontabilizacao||','||:prmatrizfilialconsolidado||','||PRCODTERCEIRO||',0,0,0,0,0,'||:prcontabilizacaolalur||','''','''','||coalesce(prcodtphistlalur,0)||')';
    
    FOR EXECUTE STATEMENT wSQL INTO :wdebcre, :wcodemp, :CHAVELAN, :wvlr_salant_deb, :wvlr_salatu_deb, :wvlr_salant_cre, :wvlr_salatu_cre DO
      BEGIN
        IF (wvlr_salant_deb IS NULL) THEN
           wvlr_salant_deb = 0;
    
        IF (wvlr_salatu_deb IS NULL) THEN
           wvlr_salatu_deb = 0;
    
        IF (wvlr_salant_cre IS NULL) THEN
           wvlr_salant_cre = 0;
    
        IF (wvlr_salatu_cre IS NULL) THEN
           wvlr_salatu_cre = 0;

        wsalantdeb = wsalantdeb + wvlr_salant_deb;
        wsaldodeb = wsaldodeb + wvlr_salatu_deb;
        wsalantcre = wsalantcre + wvlr_salant_cre;
        wsaldocre = wsaldocre + wvlr_salatu_cre;
    
        --alt:11995 - 12/08/2015 - Se estiver fazendo o processo de gravar as chaves integradas do Contábil pro Lalur deve retornar um lançamento para cada registro. Pedro
        IF ((CHAVELAN > 0) AND (printcontabillalur = 1)) THEN
           BEGIN
             CODEMP = :wcodempefilial;
             SUSPEND;
           END
      END

    saldo_deb = saldo_deb + wsaldodeb;
    saldo_ant_deb = saldo_ant_deb + wsalantdeb;
    saldo_cre = saldo_cre + wsaldocre;
    saldo_ant_cre = saldo_ant_cre + wsalantcre;

  END /* matriz e filiais */

  -- SALDO ANTERIOR ____________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5))  THEN -- ATIVO e DESPESAS
     SALDO_ANTERIOR = (SALDO_ANT_DEB - SALDO_ANT_CRE);
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        SALDO_ANTERIOR = (SALDO_ANT_CRE - SALDO_ANT_DEB);

  IF (saldo_anterior IS NULL) THEN
    saldo_anterior = 0;

  -- SALDO ATUAL _______________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4) OR (wgrupocta = 5)) THEN -- ATIVO e DESPESAS
     saldo_atual = saldo_anterior + SALDO_DEB - SALDO_CRE;
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3)) THEN -- PASSIVO e RECEITAS
        saldo_atual = saldo_anterior - SALDO_DEB + SALDO_CRE;

  IF (saldo_atual IS NULL ) THEN
    saldo_atual = 0;
  ELSE
    BEGIN
      movimento = saldo_atual - saldo_anterior;
    END

  --alt:11995 - 12/08/2015 - Só retorna aqui se não estiver fazendo o processo de integração, para não duplicar registros. Pedro
  IF ((printcontabillalur = 0) OR (printcontabillalur IS NULL))  THEN
    SUSPEND;
END
^

/* Restore proc. body: SP_RETORNA_SALDO_NATUREZA_CONTA */
ALTER PROCEDURE SP_RETORNA_SALDO_NATUREZA_CONTA(PRVALOR NUMERIC(15,2),
PRGRUPO INTEGER,
PRCREDITA INTEGER)
 RETURNS(BDRESULT INTEGER)
 AS
DECLARE VARIABLE wvalor NUMERIC(15,2);
BEGIN
  wvalor = prvalor;
  IF (wvalor IS NULL) THEN
     wvalor = 0;

  IF (wvalor = 0) THEN
     bdresult = 0;
  ELSE
  -- Ativo _____________________________________________________________________
  IF (prgrupo = 0) THEN
     BEGIN
       -- Credita
       IF (prcredita = 1) THEN
          bdresult = wvalor * -1;
       ELSE
       -- Debita
          bdresult = wvalor;
     END
  ELSE
  -- Passivo ___________________________________________________________________
  IF (prgrupo = 1) THEN
     BEGIN
       -- Credita
       IF (prcredita = 1) THEN
          bdresult = wvalor;
       ELSE
       -- Debita
          bdresult = wvalor * -1;
     END
  ELSE
  -- Receitas __________________________________________________________________
  IF (prgrupo = 3) THEN
     BEGIN
       -- Credita
       IF (prcredita = 1) THEN
          bdresult = wvalor;
       ELSE
       -- Debita
          bdresult = wvalor * -1;
     END
  ELSE
  -- Despesas __________________________________________________________________
  IF (prgrupo = 4) THEN
     BEGIN
       -- Credita
       IF (prcredita = 1) THEN
          bdresult = wvalor * -1;
       ELSE
       -- Debita
          bdresult = wvalor;
     END
  ELSE
  -- Demais grupos _____________________________________________________________
  bdresult = wvalor;
  SUSPEND;
END
^

/* Restore proc. body: SP_SELECAO_TOMADOR */
ALTER PROCEDURE SP_SELECAO_TOMADOR (
    PRPLANO integer,
    PREMPRESA integer,
    PRTIPO integer = -1)
returns (
    BDCODIGO integer,
    BDDESCRICAO DM_BDNOMEMP)
as
declare variable WAUX varchar(1000);
BEGIN
  /* Procedure Text */
  waux = 'select BDCODTPCC, '||
         ' case when BDNOMETOM is null then '||
         '   BDNOMCTA '||
         ' when BDNOMETOM is not null then '||
         '   BDNOMETOM '||
         ' end '||
         ' from VW_TOMADORES ';

  IF (prplano IS NOT NULL) THEN
     BEGIN
       waux = waux||'where BDCODCENTRO =  '||prplano;

       if (prtipo <> -1) then
          waux = waux||' and BDTIPO =  '||prtipo;
     END
  ELSE
  IF (prtipo <> -1) THEN
     BEGIN
       waux = waux||'where BDTIPO =  '||prtipo;
     END

  FOR EXECUTE STATEMENT waux INTO bdcodigo, bddescricao DO
    SUSPEND;

  bdcodigo = 0;
  bddescricao = '(Empresa)';
  IF (prempresa IS NOT NULL) THEN
     BEGIN
       waux = 'select x.bdnomemp from tempresas_ref X '||
              ' where X.BDREFEMP = '||
              ' ( '||
              ' select MAX(Y.BDREFEMP) '||
              ' from tempresas_ref Y '||
              ' where Y.BDCODEMP = X.BDCODEMP '||
              ' ) '||
              ' and X.bdcodemp = '||prempresa;

       EXECUTE STATEMENT waux INTO bddescricao;
       bddescricao = '(Empresa) '||bddescricao;
     END

  SUSPEND;
END
^

/* Restore proc. body: SP_SETA_RECONTABILIZA */
ALTER PROCEDURE SP_SETA_RECONTABILIZA(PRVALUE DM_BOOLEAN)
 AS
BEGIN
  IF (prvalue IS NULL) THEN
     prvalue = 'FALSE';

  /* Procedure Text */
  rdb$set_context('USER_SESSION', 'W_RECONTABILIZA', prvalue);
--  suspend;
END
^

-- #alt:16965 - Cria uma variável para controle da recontabilização. Ana - 12/02/2018
CREATE OR ALTER PROCEDURE SP_SETA_EMPRESA_DELETE(PRVALUE INTEGER)
 AS
BEGIN
  IF (prvalue IS NULL) THEN
     prvalue = 0;

  rdb$set_context('USER_SESSION', 'W_RECONTABILIZA_DELETE_EMPRESA', prvalue);
END
^

/* Restore proc. body: SP_SETA_USUARIO */
create or alter procedure SP_SETA_USUARIO (
    PRCODUSUARIO integer,
    PRATUALIZARLISTAEMP integer = 0)
as
  declare variable INVALIDO integer;
  declare variable WUSR varchar(32) collate WIN_PTBR;
  declare variable WCODUSUATUAL integer;
BEGIN
  select upper(current_user) from rdb$database INTO :WUSR;
  if (WUSR = 'INTEGRACOES') then
  begin
    select count(bdcodusu) invalido from tusuario where bdcodusu = :PRCODUSUARIO and ((upper(bdnomusu)='SCI') or (upper(bdnomusu)='PUSH') or (upper(bdnomusu)='UNICOIMPLANTACAO') or (upper(bdnomusu)='SCHIP')) into :invalido;
    if (invalido > 0) then
       EXCEPTION EX_USR_INV_INTEGR;
  end

  -- Gilberto - 21/01/2026
  select bdcodusu from sp_get_usuario into :wcodusuatual;

  IF (PRCODUSUARIO IS NOT NULL AND PRCODUSUARIO <> 0) THEN
     rdb$set_context('USER_SESSION', 'W_USUARIO', CAST(PRCODUSUARIO AS VARCHAR(6)));
  ELSE
     rdb$set_context('USER_SESSION', 'W_USUARIO', NULL);

  -- Gilberto - 21/01/2026 - Por questão de desempenho,
  --                         deve executar os processos abaixo apenas se houver troca de usuário
--  if ((Coalesce(wcodusuatual,0) <> Coalesce(prcodusuario,0)) or (PRATUALIZARLISTAEMP = 1)) then
  if (((coalesce(prcodusuario,0) <> 0) and (coalesce(prcodusuario,0) <> coalesce(wcodusuatual,0))) or (PRATUALIZARLISTAEMP = 1)) then
  begin
    execute statement 'delete from TMP_TEMPRESAS_USUARIO;';
    execute statement 'insert into TMP_TEMPRESAS_USUARIO select bdcodemp from VW_EMPRESAS_USU;';
    -- Gilberto - 13/01/2025 - #237931
    execute procedure vtpo_gethostid;
  end
END^

CREATE OR ALTER procedure SP_SETA_PROCESSO (
    PRNOMETELA varchar(100),
    PRCAPTIONTELA varchar(150))
as
begin
  rdb$set_context('USER_SESSION', 'W_NOMETELA', prnometela);
  rdb$set_context('USER_SESSION', 'W_CAPTIONTELA', prcaptiontela);
end
^

create or alter procedure SP_SETA_EXCLUIREMPRESAS (
    BDVALUE varchar(10))
as
begin
  rdb$set_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS', bdvalue);
end^

create or alter view VW_GET_EXCLUIREMPRESAS ( BDVALUE )
as
SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'))) AS varchar(10))
FROM rdb$database;^

create or alter procedure SP_SET_MICRO (
    PRNOME varchar(80) = null,
    PRIP varchar(15) = null)
as
declare variable WNOME_MICRO varchar(80);
declare variable WIP_MICRO varchar(15);
declare variable WCODIGO_NOMEMICRO integer;
begin
  wnome_micro = prnome;
  wip_micro = prip;
  wcodigo_nomemicro = null;
  if (((wnome_micro = '') or (wnome_micro is null)) or ((wip_micro = '')or(wip_micro is null))) then
  begin
    select first 1 MON$REMOTE_ADDRESS from mon$attachments where MON$ATTACHMENT_ID = current_connection into :wnome_micro;
    SELECT FIRST 1 bdip_micro FROM TNOMEMICROLOG WHERE (BDNOME_MICRO = UPPER(:wnome_micro)) INTO wip_micro;
  end

  IF ((:wnome_micro <> '' AND :wip_micro <> '') or (:wnome_micro <> '')) THEN
  BEGIN
    SELECT FIRST 1 BDCODNOMMICRO FROM TNOMEMICROLOG WHERE ((BDNOME_MICRO = UPPER(:wnome_micro)) AND (BDIP_MICRO = UPPER(:wip_micro))) INTO WCODIGO_NOMEMICRO;

    IF (wcodigo_nomemicro IS NULL) THEN
    BEGIN
      WCODIGO_NOMEMICRO = GEN_ID(GEN_TNOMEMICROLOG, 1);
      INSERT INTO TNOMEMICROLOG (BDCODNOMMICRO, BDNOME_MICRO, BDIP_MICRO) VALUES (:WCODIGO_NOMEMICRO, UPPER(:wnome_micro), UPPER(:wip_micro));
    END
  END

  rdb$set_context('USER_SESSION', 'W_NOMEMICRO', WNOME_MICRO);
  rdb$set_context('USER_SESSION', 'W_IPMICRO', WIP_MICRO);

  IF (WCODIGO_NOMEMICRO IS NOT NULL AND WCODIGO_NOMEMICRO <> 0) THEN
     rdb$set_context('USER_SESSION', 'W_CODIGOMICRO', WCODIGO_NOMEMICRO);
  ELSE
     rdb$set_context('USER_SESSION', 'W_CODIGOMICRO', NULL);
end^

create or alter procedure SP_SET_USUARIO_INTRANET (
    BDCODUSU integer,
    BDNOMUSU varchar(100))
as
begin
  IF (BDCODUSU IS NOT NULL AND BDCODUSU <> 0) THEN
  begin
    rdb$set_context('USER_SESSION', 'W_CODUSU_INTRANET', CAST(bdcodusu AS VARCHAR(6)));
    rdb$set_context('USER_SESSION', 'W_NOMUSU_INTRANET', CAST(bdnomusu AS VARCHAR(100)));
  end
  else
  begin
    rdb$set_context('USER_SESSION', 'W_CODUSU_INTRANET', NULL);
    rdb$set_context('USER_SESSION', 'W_NOMUSU_INTRANET', NULL);
  end
end^

create or alter procedure SP_SET_MODULO (
    PRCODSIS integer)
as
begin
  IF (prcodsis IS NOT NULL AND prcodsis <> 0) THEN
  begin
    rdb$set_context('USER_SESSION', 'W_CODSIS', prcodsis);
  end
  else
  begin
    rdb$set_context('USER_SESSION', 'W_CODSIS', NULL);
  end
end^

/* Restore proc. body: SP_SETA_VARIAVEIS_SESSAO_BANCO */
ALTER PROCEDURE SP_SETA_VARIAVEIS_SESSAO_BANCO(PRCODUSU INTEGER)
 AS
BEGIN

  IF ((PRcodusu IS NOT NULL) AND (prcodusu > 0)) THEN
    rdb$set_context('USER_SESSION', 'W_CODUSU', CAST(PRCODUSU AS VARCHAR(6)));

END
^

/* Restore proc. body: SP_SOMENTE_ADMITIDOS_MES */
ALTER PROCEDURE SP_SOMENTE_ADMITIDOS_MES(PRDATAINI DATE,
PRDATAFIM DATE,
PRCODEMP INTEGER = NULL)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(500);
BEGIN
  wsql = 'select X.BDCODEMP, X.BDCODCOL from VRH_EMP_TCOLCON X where ';

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wsql = wsql||'X.BDCODEMP = '||prcodemp||' and ';

  wsql = wsql||'X.BDDATAADMCOL between '''||prdataini||''' and '''||prdatafim||'''';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL
  DO
  SUSPEND;
END
^

/* Restore proc. body: SP_SOMENTE_ATIVOS */
create or alter procedure SP_SOMENTE_ATIVOS (
    PRDATAINI date,
    PRDATAFIM date,
    PRCODEMP integer = null,
    PRFILTROPAG boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer)
as
declare variable WSQL varchar(32700);
BEGIN
  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL from VRH_EMP_TCOLCON COLCON ';

  wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';

  -- Admissões
  wsql = wsql||'where ';
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wsql = wsql||'COLCON.BDCODEMP = '||prcodemp||' and ';

  wsql = wsql||'COLCON.BDDATAADMCOL <= '''||prdatafim||'''';

  if (prfiltropag) then
     wsql = wsql||' and ((RESC.BDDATARESCISAO is null) or (COALESCE(RESC.BDDATAPAGRESCISAO,RESC.BDDATARESCISAO) >= '''||prdataini||'''))';
  else
     wsql = wsql||' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataini||'''))';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL
  DO
  SUSPEND;
END^

/* Restore proc. body: SP_SOMENTE_ATIVOS_RAIS */
create or alter procedure SP_SOMENTE_ATIVOS_RAIS (
    PRDATAINI date,
    PRDATAFIM date,
    PRCODEMP integer = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer)
as
declare variable WSQL varchar(32700);
BEGIN
  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL from VRH_EMP_TCOLCON COLCON ';
  wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql||'left outer join VRH_BASE_TPREPRESC PRES on (PRES.BDCODPRES = RESC.BDCODPRES) ';

  wsql = wsql||'where ';
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wsql = wsql||'COLCON.BDCODEMP = '||prcodemp||' and ';

  -- Admissões
  wsql = wsql||'COLCON.BDDATAADMCOL <= '''||prdatafim||'''';

  -- Rescisões e Transferências
  wsql = wsql||' and ((RESC.BDDATARESCISAO is null) or '||
         '(case when COALESCE(PRES.BDAVPREPRES,0) in (0,1) and RESC.BDPROJECAOAVISO is not null then RESC.BDPROJECAOAVISO else RESC.BDDATARESCISAO end >= '''||prdataini||''')) ';


  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL
  DO
  SUSPEND;
END^


--Sol. 18259 - Estava totalizando colaboradores transferidos na competência posterior - Bruno L. R. - 18/04/2017
/* Restore proc. body: SP_SOMENTE_ATIVOS_CAGED */
create or alter procedure SP_SOMENTE_ATIVOS_CAGED (
    PRDATAINI date,
    PRDATAFIM date)
returns (
    BDCODEMP integer,
    BDCODCOL integer)
as
declare variable WSQL varchar(32700);
declare variable WDATAADM01 date;
BEGIN
  wdataadm01 = CAST((SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 8)||'01') AS DATE);

  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL from VRH_EMP_TCOLCON COLCON ';

  wsql = wsql||'left outer join vw_vrh_emp_tcolcon_vinc vinc on vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol ';
  wsql = wsql||'left outer join vrh_base_tclasse classe on classe.bdcodcla = vinc.bdcodcla ';
  wsql = wsql||'left outer join vrh_emp_trescisao RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql||'left outer join vrh_emp_ttranscol TRF on (TRF.BDCODEMPDEST = COLCON.BDCODEMP and TRF.BDCODCOLDEST = COLCON.BDCODCOL) ';
  wsql = wsql||'left outer join vrh_emp_tcolcon_partida P on (P.BDCODEMP = COLCON.BDCODEMP and P.BDCODCOL = COLCON.BDCODCOL) ';

  -- Somente colaboradores
  wsql = wsql||'where COLCON.BDCONTRCOL <> 1 and classe.bdgrupocla <> 5 and ';

  -- Admissões
  wsql = wsql||'COLCON.BDDATAADMCOL <= '''||prdatafim||'''';

  -- Rescisões
  wsql = wsql||' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >='''||prdataini||''')) ';

  -- Transferências
  wsql = wsql||' and ((TRF.BDDATATRF is null) or (TRF.BDDATATRF <= '''||prdatafim||''' '||
               'and SUBSTRING(CAST(TRF.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2)||SUBSTRING(CAST(TRF.BDDATATRF AS VARCHAR(10)) FROM 9 FOR 2) <> SUBSTRING(CAST('''||prdataini||''' AS VARCHAR(10)) FROM 6 FOR 2)||''01'')) ';

  wsql = wsql||' and COALESCE(P.BDDATATRFCOL, COLCON.BDDATAADMCOL) <> '''||:wdataadm01||'''';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL
  DO
  SUSPEND;
END^


/* Restore proc. body: SP_SOMENTE_DEMITIDOS */
create or alter procedure SP_SOMENTE_DEMITIDOS (
    PRDATAFIM date,
    PRCODEMP integer = null,
    PRFILTROPAG boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer)
as
declare variable WSQL varchar(32700);
BEGIN
  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL from VRH_EMP_TRESCISAO COLCON ';

  if (prfiltropag) then
     wsql = wsql||' where COALESCE(COLCON.BDDATAPAGRESCISAO, COLCON.BDDATARESCISAO) <= '''||prdatafim||'''';
  else
     wsql = wsql||' where COLCON.BDDATARESCISAO <= '''||prdatafim||'''';

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wsql = wsql||' and COLCON.BDCODEMP = '||prcodemp;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL
  DO
  SUSPEND;
END^


/* Restore proc. body: SP_SOMENTE_DEMITIDOS_MES */
create or alter procedure SP_SOMENTE_DEMITIDOS_MES (
    PRDATAINI date,
    PRDATAFIM date,
    PRCODEMP integer = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer)
as
declare variable WSQL varchar(32700);
BEGIN
  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL from VRH_EMP_TRESCISAO COLCON ';
  wsql = wsql||'where COLCON.BDDATARESCISAO between '''||prdataini||''' and '''||prdatafim||'''';

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wsql = wsql||' and COLCON.BDCODEMP = '||prcodemp;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL
  DO
  SUSPEND;
END^


/* Restore proc. body: SP_TEMPRESAIMPOSTO_REF */
ALTER PROCEDURE SP_TEMPRESAIMPOSTO_REF(PRCODEMP VARCHAR(20000),
PRREFERENCIA INTEGER,
PRQUANTIDADE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDREFFIMIMP INTEGER,
BDCODIMP INTEGER,
BDDESCIMP VARCHAR(100),
BDDATACRIACAO DATE,
BDDATAEXTINTO DATE,
BDCOMPETENCIA INTEGER,
BDDOCARRECADACAO INTEGER,
BDPERAPURACAO INTEGER,
BDDIAVENCTO INTEGER,
BDANTECIPA VARCHAR(5),
BDMESVENCTO INTEGER,
BDJUROSDIA INTEGER,
BDVLRJUROS NUMERIC(15,6),
BDJUROSDIAMES INTEGER,
BDMULTADIA INTEGER,
BDVLRMULTA NUMERIC(15,6),
BDMULTADIAMES INTEGER,
BDVLRMAXMULTA NUMERIC(15,6),
BDALIQIMPOSTO NUMERIC(15,6),
BDLIMITEISENCAO NUMERIC(15,6),
BDTIPORETENCAO INTEGER,
BDCODREC INTEGER,
BDCODIND INTEGER,
BDRETBCCALCULOIMP VARCHAR(5),
BDDESCREC VARCHAR(150),
BDTIPOIMPOSTO INTEGER)
 AS
DECLARE VARIABLE WPRIDIA DATE;
DECLARE VARIABLE WULTDIA DATE;
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  wsql = 'select ';

  EXECUTE PROCEDURE sp_seta_competencia(:prreferencia,NULL,NULL);

  IF (prquantidade IS NOT NULL AND prquantidade <> 0) THEN
     wsql = wsql||'first '||prquantidade||' ';

  wsql = wsql|| 'BDCODEMP, '||
                'BDREFEMP, '||
                'BDREFFIMIMP, '||
                'BDCODIMP, '||
                'BDDESCIMP, '||
                'BDDATACRIACAO, '||
                'BDDATAEXTINTO, '||
                'BDCOMPETENCIA, '||
                'BDDOCARRECADACAO, '||
                'BDPERAPURACAO, '||
                'BDDIAVENCTO, '||
                'BDANTECIPA, '||
                'BDMESVENCTO, '||
                'BDJUROSDIA, '||
                'BDVLRJUROS, '||
                'BDJUROSDIAMES, '||
                'BDMULTADIA, '||
                'BDVLRMULTA, '||
                'BDMULTADIAMES, '||
                'BDVLRMAXMULTA, '||
                'COALESCE(BDALIQIMPOSTO, 0.0) BDALIQIMPOSTO, '||
                'BDLIMITEISENCAO, '||
                'BDTIPORETENCAO, '||
                'BDCODREC, '||
                'BDCODIND, '||
                'BDRETBCCALCULOIMP, '||
                'BDDESCREC, '||
                'BDTIPOIMPOSTO ';
  wsql = wsql||'from VW_TEMPRESAIMPOSTOREF ';


  wwhere = '';

  IF (prreferencia IS NOT NULL AND prreferencia <> 0) THEN
     BEGIN
       wpridia = CAST((SUBSTRING(prreferencia FROM 5 FOR 2)||'-01-'||SUBSTRING(prreferencia FROM 1 FOR 4)) AS DATE);
       wultdia = wpridia - EXTRACT(DAY FROM wpridia) + 32 - EXTRACT(DAY FROM wpridia - EXTRACT(DAY FROM wpridia) + 32);

       wwhere = wwhere||'BDREFEMP <= '||prreferencia||' ';

       wwhere = wwhere||' and (';

       wwhere = wwhere||'(BDDATACRIACAO is null) or (BDDATACRIACAO <= '''||wpridia||''') and ';
       wwhere = wwhere||'(BDDATAEXTINTO is null) or (BDDATAEXTINTO > '''||wultdia||''')';

       wwhere = wwhere||') ';
     END

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodemp;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

--  wsql = wsql||' group by BDCODEMP, BDCODIMP, BDDESCIMP, BDDATACRIACAO, BDDATAEXTINTO, BDCOMPETENCIA, BDDOCARRECADACAO, BDPERAPURACAO, BDDIAVENCTO, '||
--                         'BDANTECIPA, BDMESVENCTO, BDJUROSDIA, BDVLRJUROS, BDJUROSDIAMES, BDMULTADIA, BDVLRMULTA, BDMULTADIAMES, BDVLRMAXMULTA, '||
--                         'BDALIQIMPOSTO, BDLIMITEISENCAO, BDTIPORETENCAO, BDCODREC, BDCODIND, BDRETBCCALCULOIMP, BDDESCREC, BDTIPOIMPOSTO ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDREFEMP,
    :BDREFFIMIMP,
    :BDCODIMP,
    :BDDESCIMP,
    :BDDATACRIACAO,
    :BDDATAEXTINTO,
    :BDCOMPETENCIA,
    :BDDOCARRECADACAO,
    :BDPERAPURACAO,
    :BDDIAVENCTO,
    :BDANTECIPA,
    :BDMESVENCTO,
    :BDJUROSDIA,
    :BDVLRJUROS,
    :BDJUROSDIAMES,
    :BDMULTADIA,
    :BDVLRMULTA,
    :BDMULTADIAMES,
    :BDVLRMAXMULTA,
    :BDALIQIMPOSTO,
    :BDLIMITEISENCAO,
    :BDTIPORETENCAO,
    :BDCODREC,
    :BDCODIND,
    :BDRETBCCALCULOIMP,
    :BDDESCREC,
    :BDTIPOIMPOSTO
  DO
  SUSPEND;
END
^

/* Restore proc. body: SP_TEMPRESAS_REF */
ALTER PROCEDURE SP_TEMPRESAS_REF(PRAAAAMM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODHIST INTEGER,
BDCODCENTROS INTEGER,
BDCODCID INTEGER,
BDCODCONT INTEGER,
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDCNAEPREP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDAPEEMP DM_BDAPEMP,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDBAIEMP DM_BDBAIRRO,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDFAXEMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDLOGREMP VARCHAR(15),
BDIEEMP VARCHAR(20),
BDIMEMP VARCHAR(20),
BDSITEMP VARCHAR(5),
BDDDDFAXEMP INTEGER,
BDDOCAUXILIAR VARCHAR(18),
BDSUFRAMA VARCHAR(9))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  wsql = 'select '||
           'X.bdcodemp, '||
           'X.bdrefemp, '||
           'X.bdcodplapadrao, '||
           'X.bdcodhist, '||
           'X.bdcodcentros, '||
           'X.bdcodcid, '||
           'X.bdcodcont, '||
           'X.bdcodnatjur, '||
           'X.bdcodcnae, '||
           'X.bdnomemp, '||
           'X.bdapeemp, '||
           'X.bdendemp, '||
           'X.bdnumemp, '||
           'X.bdbaiemp, '||
           'X.bdcepemp, '||
           'X.bddddemp, '||
           'X.bdfoneemp, '||
           'X.bdfaxemp, '||
           'X.bdemailemp, '||
           'X.bdcomplemp, '||
           'X.bdlogremp, '||
           'X.bdieemp, '||
           'X.bdimemp, '||
           'X.bdsitemp, '||
           'X.bddddfaxemp, '||
           'X.bddocauxiliar, '||
           'x.bdsuframa '||
        'from tempresas_ref X '||
        'where '||
          'exists (select Y.BDCODEMP, MAX(Y.BDREFEMP) '||
                  'from tempresas_ref Y '||
                  'where Y.BDREFEMP <= '||prAAAAMM||' '||
                  'group by Y.BDCODEMP '||
                  'having Y.BDCODEMP = X.BDCODEMP and MAX(Y.BDREFEMP) = X.BDREFEMP '||
                 ') ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDREFEMP,
    :BDCODPLAPADRAO,
    :BDCODHIST,
    :BDCODCENTROS,
    :BDCODCID,
    :BDCODCONT,
    :BDCODNATJUR,
    :BDCODCNAE,
    :BDNOMEMP,
    :BDAPEEMP,
    :BDENDEMP,
    :BDNUMEMP,
    :BDBAIEMP,
    :BDCEPEMP,
    :BDDDDEMP,
    :BDFONEEMP,
    :BDFAXEMP,
    :BDEMAILEMP,
    :BDCOMPLEMP,
    :BDLOGREMP,
    :BDIEEMP,
    :BDIMEMP,
    :BDSITEMP,
    :BDDDDFAXEMP,
    :BDDOCAUXILIAR,
    :BDSUFRAMA
  DO
  SUSPEND;
END
^

/* Restore proc. body: SP_TERCEIRO */
create or alter procedure SP_TERCEIRO (
    PRCODTER integer)
returns (
    BDCODTER integer,
    BDCODPLAPADRAO integer,
    BDCODTPLA integer,
    BDCGCTER varchar(18),
    BDREFEMP integer,
    BDAPELIDOTER varchar(20),
    BDNOMETER varchar(100),
    BDLOGRTER varchar(15),
    BDENDTER DM_BDENDERECO,
    BDNUMTER DM_NUMEND,
    BDCOMPTER DM_BDCOMPENDERECO,
    BDCEPTER varchar(9),
    BDBAITER DM_BDBAIRRO,
    BDDDDTER varchar(3),
    BDFONETER DM_BDTELEFONE,
    BDFAXTER DM_BDTELEFONE,
    BDEMAILTER DM_BDEMAIL,
    BDIETER varchar(20),
    BDDATACADTER date,
    BDIMTER varchar(16),
    BDPRURALTER varchar(5),
    BDENQSIMPLESFEDTER integer,
    BDINSCSUFRAMATER varchar(10),
    BDCODGPS integer,
    BDCODCID integer,
    BDCODPAIS integer,
    BDDESCPAIS varchar(60),
    BDDDDFAXTER varchar(3))
as
BEGIN
  IF (prcodter IS NOT NULL) THEN
     BEGIN
       SELECT FIRST 1 bdcodter, bdcodplapadrao, bdcodtpla, bdcgcter,
                      bdrefemp, bdapelidoter, bdnometer, bdlogrter, bdendter,
                      bdnumter, bdcompter, bdcepter, SUBSTRING(bdbaiter FROM 1 FOR 50), bddddter, bdfoneter,
                      bdfaxter, bdemailter, bdieter, bddatacadter, bdimter, bdpruralter,
                      bdenqsimplesfedter, bdinscsuframater, bdcodgps, bdcodcid,
                      bdcodpais, bddescpais, bddddfaxter
       FROM vw_tterceiro WHERE bdcodter = :prcodter
       INTO :BDCODTER, :BDCODPLAPADRAO, :BDCODTPLA, :BDCGCTER,
            :BDREFEMP, :BDAPELIDOTER, :BDNOMETER, :BDLOGRTER, :BDENDTER,
            :BDNUMTER, :BDCOMPTER, :BDCEPTER, :BDBAITER, :BDDDDTER, :BDFONETER,
            :BDFAXTER, :BDEMAILTER, :BDIETER, :BDDATACADTER, :BDIMTER, :BDPRURALTER,
            :BDENQSIMPLESFEDTER, :BDINSCSUFRAMATER, :BDCODGPS, :BDCODCID,
            :BDCODPAIS, :BDDESCPAIS, :BDDDDFAXTER;
       SUSPEND;
     END
END^

/* Restore proc. body: SP_TIPO_INS_SEFIP */
ALTER PROCEDURE SP_TIPO_INS_SEFIP(PRINSC VARCHAR(18))
 RETURNS(BDTIPOINS VARCHAR(1))
 AS
BEGIN
  /* Procedure Text */
  IF (CHARACTER_LENGTH(prinsc) = 14) THEN
     bdtipoins = '3';--CPF
  ELSE IF (CHARACTER_LENGTH(prinsc) = 15) THEN
     bdtipoins = '2';--CEI
  ELSE IF (CHARACTER_LENGTH(prinsc) > 15) THEN
     bdtipoins = '1'; --CNPJ
  ELSE
     bdtipoins = '0';
  SUSPEND;
END
^

/* Restore proc. body: SP_TOL_VSUC_EMPRESAS_TLAN */
ALTER PROCEDURE SP_TOL_VSUC_EMPRESAS_TLAN(PRCHAVE INTEGER,
PRCHAVETITULO INTEGER,
PRTIPOLAN INTEGER,
PRPLANOONLINE INTEGER,
PRVALOR VARCHAR(50))
 AS
DECLARE VARIABLE wcodemp INTEGER;
DECLARE VARIABLE wchave INTEGER;
DECLARE VARIABLE wsqlbase VARCHAR(3000);
DECLARE VARIABLE wsql VARCHAR(1000);
BEGIN
  /* Procedure Text */
  wsql = 'select up.bdcodemp, up.bdchavelan from tol_update_conta up';
  wsql = wsql||' where ';
  IF (prchave IS NULL) THEN
     wsql = wsql||' up.bdchave is null';
  ELSE
     wsql = wsql||' up.bdchave = '||prchave;

  IF (prchavetitulo IS NULL) THEN
     wsql = wsql||' and up.bdchavetitulo is null';
  ELSE
     wsql = wsql||' and up.bdchavetitulo = '||prchavetitulo;

  IF (prtipolan IS NULL) THEN
     wsql = wsql||' and up.bdtipolan is null';
  ELSE
     wsql = wsql||' and up.bdtipolan = '||prtipolan;

  IF (prplanoonline IS NULL) THEN
     wsql = wsql||' and up.bdcodplanoonline is null';
  ELSE
     wsql = wsql||' and up.bdcodplanoonline = '||prplanoonline;

  IF (prvalor IS NOT NULL) THEN
     BEGIN
       FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wchave DO
         BEGIN
           wsqlbase = 'update vsuc_empresas_tlan lan set '||prvalor||
                      ' where lan.bdcodemp = '||wcodemp||
                      ' and lan.bdchave = '||wchave;

           EXECUTE STATEMENT wsqlbase;
         END
     END
END
^

/* Restore proc. body: SP_TOMADOR_SEFIP */
ALTER PROCEDURE SP_TOMADOR_SEFIP RETURNS(BDCNPJ VARCHAR(20),
BDNOME DM_BDNOMEMP,
BDENDERECO DM_BDENDERECO,
BDBAIRRO DM_BDBAIRRO,
BDCEP VARCHAR(9),
BDCIDADE VARCHAR(40),
BDUF VARCHAR(2),
BDCODGPS VARCHAR(4))
 AS
DECLARE VARIABLE WCODREC INTEGER;
DECLARE VARIABLE WSQL VARCHAR(3000);
DECLARE VARIABLE WPLANOCC INTEGER;
DECLARE VARIABLE WEMP INTEGER;
DECLARE VARIABLE WTOMADOR INTEGER;
BEGIN
  /* Procedure Text */
  SELECT rdb$get_context('USER_TRANSACTION', 'W_EMPSEFIP') FROM rdb$database INTO wemp;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_TOMADORSEFIP') FROM rdb$database INTO wtomador;
  SELECT rdb$get_context('USER_TRANSACTION', 'W_CODREC') FROM rdb$database INTO wcodrec;

  wsql = 'select temp.bdcodcentros from vw_tempresas_ref temp where temp.bdcodemp = '||CAST(wemp AS VARCHAR(10));
  EXECUTE STATEMENT wsql INTO wplanocc;

  bdcnpj = '';
  bdnome = '';
  bdendereco = '';
  bdbairro = '';
  bdcep = '';
  bdcidade = '';
  bduf = '';
  bdcodgps = '';

  IF (((wtomador IS NOT NULL) AND (wtomador > 0)) AND ((wplanocc IS NOT NULL) AND (wplanocc > 0))) THEN
     BEGIN
       wsql = 'select tcus.bdcnpjtom, tcus.bdnometom, tom.bDLOGRTOM||'||''''||' '||''''||'||tom.bdendtom||'||''''||' '||''''||'||tom.bdnumctom,'||
              ' tom.bdbaitom, tom.bdceptom, cast(tom.bdcodgps as varchar(4)), cid.bdnomcid, est.bdsiglauf'||
              ' from VW_TOMADORES_REF_ATU tom'||
              ' inner join vrh_base_tcustom tcus on (tcus.bdcodcentro = tom.bdcodcentro and tcus.bdcodtpcc = tom.bdcodtpcc)'||
              ' left outer join tcidade cid on (cid.bdcodcid = tom.bdcodcid)'||
              ' left outer join tuf est on (cid.bdcoduf = est.bdcoduf)'||
              ' where '||
              '       (tcus.bdcodcentro = '||CAST(wplanocc AS VARCHAR(15))||' and tcus.bdcodtpcc = '||CAST(wtomador AS VARCHAR(15))||')';

       IF (wsql IS NULL) THEN
          wsql = '';

       EXECUTE STATEMENT wsql
           INTO
             : bdcnpj,
             : bdnome,
             : bdendereco,
             : bdbairro,                                
             : bdcep,
             : bdcodgps,
             : bdcidade,
             : bduf;
     END
  ELSE
     BEGIN

       wsql = 'select emp.bdcnpjemp, temp.bdnomemp, temp.bdlogremp||'||''''||' '||''''||'||temp.bdendemp||'||''''||' '||''''||'||temp.bdnumemp,'||
              ' temp.bdbaiemp, temp.bdcepemp, cast(tempaux.bdcodgps as varchar(4)), cid.bdnomcid, est.bdsiglauf'||
              ' from vw_empresas_ref_atual temp'||
              ' inner join VW_VRHF_EMPRESAS_REF_ATUAL tempaux on (temp.bdcodemp = tempaux.bdcodemp)'||
              ' inner join tempresas emp on (temp.bdcodemp = emp.bdcodemp)'||
              ' left outer join tcidade cid on (cid.bdcodcid = temp.bdcodcid)'||
              ' left outer join tuf     est on (cid.bdcoduf = est.bdcoduf)'||
              ' where temp.bdcodemp = '||CAST(wemp AS VARCHAR(10));

       IF (wsql IS NULL) THEN
          wsql = '';

       EXECUTE STATEMENT wsql
           INTO
             : bdcnpj,
             : bdnome,
             : bdendereco,
             : bdbairro,
             : bdcep,
             : bdcodgps,
             : bdcidade,
             : bduf;
     END

  IF (wCodrec NOT IN (130, 135, 150, 155, 211, 317, 337, 608)) THEN
     BEGIN
       bdcnpj = '';
       bdnome = '';
       bdendereco = '';
       bdbairro = '';
       bdcep = '';
       bdcodgps = '';
       bdcidade = '';
       bduf = '';
     END


  IF (bdcnpj IS NULL) THEN
     bdcnpj = '';

  IF (bdnome IS NULL) THEN
     bdnome = '';

  IF (bdendereco IS NULL) THEN
     bdendereco = '';

  IF (bdbairro IS NULL) THEN
     bdbairro = '';

  IF (bdcep IS NULL) THEN
     bdcep = '';

  IF (bdcidade IS NULL) THEN
     bdcidade = '';

  IF (bduf IS NULL) THEN
     bduf = '';

  IF (bdcodgps IS NULL) THEN
     bdcodgps = '';

  SUSPEND;
END
^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_C177_GIAF (
    PRSESSAO integer,
    PRSESSAOPROD integer,
    PRREFLAN integer)
as
declare variable PRCHAVE integer;
declare variable PRCODEMP integer;
declare variable PRCODITEMGIAF integer;
declare variable PRPRODINCENTIVADO DM_BOOLEAN;
declare variable PRINCENTIVOTRANSP DM_BOOLEAN;
declare variable PROPEDIFIMPORTACAO DM_BOOLEAN;
declare variable PRORDEM integer;
declare variable PRORDEMPROD integer;
declare variable PRDESCAD varchar(500);
begin
  /* Procedure Text */

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRREFLAN);

  FOR
   SELECT C.BDCODEMP,C.BDORDEM,C.BDORDEMPRO,C.BDCHAVE,PRO.BDPRODINCENTIVADO,PRO.BDCODITEMGIAF,
   PRO.BDINCENTIVOTRANSP,IIF((SUBSTRING(S.BDCSTICMS FROM 1 FOR 1) <> '0') AND (substring(A56.BDCODINFAD56 FROM 1 FOR 4) = 'PE03') AND  (SUBSTRING(S.BDCODNAT FROM 1 FOR 1) = '5'),PRO.BDOPEDIFIMPORTACAO, 'FALSE'),
   A56.BDDESCRICAO
   FROM TMP_VEF_EMP_TMOVPROSAIC177_TEMP C
   JOIN TMP_VEF_EMP_TMOVPROSAI_TEMP S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDCHAVE AND S.BDORDEM = C.BDORDEM AND S.BDORDEMPRO = C.BDORDEMPRO AND S.BDSESSAO = C.BDSESSAO)
   LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP SAI ON (SAI.BDCODEMP = S.BDCODEMP AND SAI.BDSESSAO = S.BDSESSAO AND SAI.BDCHAVE = S.BDCHAVE)
   LEFT OUTER JOIN TMP_TCADPRO_TEMP PRO ON (PRO.BDSESSAO = :PRSESSAOPROD AND PRO.BDCODEMP = S.BDCODEMP AND PRO.BDCODPROD = S.BDCODPROD AND PRO.BDCODPRODVINC = S.BDORDEMPRO)
   LEFT OUTER JOIN VEF_BASE_TTABINFAD56 A56 ON (A56.BDORDEM56 = PRO.BDCODITEMGIAF)
   JOIN VW_INT_SPEDICMSREF19_REF ICMS ON (ICMS.BDCODEMP = C.BDCODEMP AND ICMS.BDREG = substring(A56.BDCODINFAD56 FROM 1 FOR 4) AND ICMS.BDCODSUBAPU = substring(A56.BDCODINFAD56 FROM 5 FOR 2))
   WHERE C.BDSESSAO = :PRSESSAO
   AND COALESCE(C.BDCODTIPO,0) <> 152
   AND ICMS.BDVIGINICIAL <= SAI.BDREFLAN AND (ICMS.BDVIGFINAL >=  SAI.BDREFLAN OR (COALESCE(ICMS.BDVIGFINAL,0) = 0))
   INTO :PRCODEMP,:PRORDEM,:PRORDEMPROD,:PRCHAVE,:PRPRODINCENTIVADO,:PRCODITEMGIAF,:PRINCENTIVOTRANSP,:PROPEDIFIMPORTACAO,:PRDESCAD
  DO
   BEGIN
     UPDATE TMP_VEF_EMP_TMOVPROSAIC177_TEMP C SET
     C.BDOPEINCENTIVADA  = :PRPRODINCENTIVADO,
     C.BDCODINFAD        = :PRCODITEMGIAF,
     C.BDINCENTIVOTRANSP = :PRINCENTIVOTRANSP,
     C.BDSAIINCENTIVADAPORIMP = :PROPEDIFIMPORTACAO,
     C.BDVLRBASECREDPRESUMIDO = (IIF(COALESCE(:PROPEDIFIMPORTACAO,'FALSE') = 'FALSE',0,C.BDVLRBASECREDPRESUMIDO)),
     C.BDDESCCODINFAD =  :PRDESCAD
     WHERE C.BDCODEMP = :PRCODEMP
     AND C.BDSESSAO = :PRSESSAO
     AND C.BDCHAVE  = :PRCHAVE
     AND C.BDORDEM  = :PRORDEM
     AND C.BDORDEMPRO = :PRORDEMPROD;
   END
end^

/* Restore proc. body: SP_TREEVIEW_CONF_DEPARA_ONLINE */
ALTER PROCEDURE SP_TREEVIEW_CONF_DEPARA_ONLINE(PRPLANO_DE INTEGER,
PRPLANO_PARA INTEGER,
PRCODINT INTEGER,
PRPLANOCONTASANT INTEGER,
PRPLANOCONTASATU INTEGER,
PRPLANOHISTANT INTEGER,
PRPLANOHISTATU INTEGER,
PRCLASSIFICACAO VARCHAR(100),
PRLENGTH INTEGER,
PRREF INTEGER,
PRCHAVE INTEGER,
PRAPENASNIVEL INTEGER,
PRFILTERCLASSIFICACAO DM_MAXVARCHAR = '',
PRCONFAUT INTEGER = 0) 
RETURNS (
BDFORMULA VARCHAR(80),
BDFORMULAITEM VARCHAR(80),
BDCONFIGTIT DM_BOOLEAN,
BDCLASSIFICACAO VARCHAR(100),
BDDESCRICAO VARCHAR(500),
BDAPECTADV VARCHAR(20),
BDAPECTACV VARCHAR(20),
BDAPECTADO VARCHAR(20),
BDAPECTACO VARCHAR(20),
BDDESCONTADV VARCHAR(100),
BDDESCONTACV VARCHAR(100),
BDDESCONTADO VARCHAR(100),
BDDESCONTACO VARCHAR(100),
BDCODHISTPROV INTEGER,
BDCODHISTPGTO INTEGER,
BDCODTIPOCONTA INTEGER,
BDCODNAT INTEGER,
BDCODVER INTEGER,
BDDESCREDVER VARCHAR(20),
BDAPELIDOTER VARCHAR(20),
BDNOMENAT VARCHAR(335),
BDAPEHISTPROV VARCHAR(20),
BDAPEHISTPGTO VARCHAR(20),
BDCONTADEBPROV INTEGER,
BDCONTACREDPROV INTEGER,
BDCONTADEBPGTO INTEGER,
BDCONTACREDPGTO INTEGER,
BDCHAVE INTEGER,
BDCHAVEVINC INTEGER,
BDCODPLANOONLINE INTEGER,
BDDESCIMP VARCHAR(100),
BDDESCOREC VARCHAR(100),
BDCODOREC INTEGER,
BDCODIMP INTEGER,
BDCODTCA INTEGER,
BDCODGRUPOCLA INTEGER,
BDDESCGRUPOCLA VARCHAR(200),
BDTIPONAT INTEGER,
BDCLASSVER VARCHAR(20),
BDTIPOVER INTEGER,
BDCODITEMONLINE INTEGER,
BDAPECOMHISTPROV VARCHAR(20),
BDAPECOMHISTPGTO VARCHAR(20),
BDCODCOMPHISTPROV INTEGER,
BDCODCOMPHISTPGTO INTEGER,
BDCOMHISTPROV VARCHAR(1000),
BDCOMHISTPGTO VARCHAR(1000),
BDCONFIGPROV DM_BOOLEAN,
BDCONFIGDEBPROV DM_BOOLEAN,
BDCONFIGCREDPROV DM_BOOLEAN,
BDCONFIGPAG DM_BOOLEAN,
BDCONFIGDEBPAG DM_BOOLEAN,
BDCONFIGCREDPAG DM_BOOLEAN,
BDCONFIGHISTPROV DM_BOOLEAN,
BDCONFIGHISTPAG DM_BOOLEAN,
BDNAOCONTAB DM_BOOLEAN,
BDCODREC INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(42),
BDCODTPHIST INTEGER,
BDAPELIDOHIST VARCHAR(20),
BDCHAVE_PARA INTEGER,
BDCODMASTER INTEGER,
BDPODEEDITAR DM_BOOLEAN,
BDCLASSIFICACAOORI VARCHAR(100),
BDCODOBRSER INTEGER,
BDCHAVECTABAN INTEGER,
BDCODCLI INTEGER,
BDCODDESP INTEGER)
AS
DECLARE VARIABLE WSQL DM_MAXVARCHAR;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(100);
DECLARE VARIABLE WCODTPLAANT INTEGER;
DECLARE VARIABLE WCTALONANT VARCHAR(40);
DECLARE VARIABLE WNOMCTAANT VARCHAR(100);
DECLARE VARIABLE WTIPCTAANT INTEGER;
DECLARE VARIABLE WCODTPLAATU INTEGER;
DECLARE VARIABLE WCTALONATU VARCHAR(40);
DECLARE VARIABLE WNOMCTAATU VARCHAR(100);
DECLARE VARIABLE WCODTPHIANT INTEGER;
DECLARE VARIABLE WAPELIDOANT VARCHAR(20);
DECLARE VARIABLE WHISTANT VARCHAR(100);
DECLARE VARIABLE WCODTPHIATU INTEGER;
DECLARE VARIABLE WAPELIDOATU VARCHAR(20);
DECLARE VARIABLE WHISTATU VARCHAR(100);
DECLARE VARIABLE WCODPLANOONLINE_PARA INTEGER;
DECLARE VARIABLE WQTD INTEGER;
DECLARE VARIABLE WQTDAUX INTEGER;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WCHAVE_PARA INTEGER;
DECLARE VARIABLE WCODHISTPROV INTEGER;
DECLARE VARIABLE WCODHISTPGTO INTEGER;
DECLARE VARIABLE WCONTADEBPROV INTEGER;
DECLARE VARIABLE WCONTACREDPROV INTEGER;
DECLARE VARIABLE WCONTADEBPGTO INTEGER;
DECLARE VARIABLE WCONTACREDPGTO INTEGER;
DECLARE VARIABLE WCODCOMPHISTPROV INTEGER;
DECLARE VARIABLE WCODCOMPHISTPGTO INTEGER;
DECLARE VARIABLE WCOMHISTPROV VARCHAR(1000);
DECLARE VARIABLE WCOMHISTPGTO VARCHAR(1000);
DECLARE VARIABLE WDE INTEGER;
DECLARE VARIABLE WATE INTEGER;
BEGIN
  /*prconfaut - > 0 - False | 1 - True
  Quando for para configuração automática preciso trazer tudo de uma vez. E ele
  só traz os que não tenham nada configurado*/
  wde  = 1;
  wate = 1;
  IF (prconfaut = 1) THEN
    BEGIN
      wate = 4; -- 1 - Grupo principal | 2 - Plano de contas | 3 - Histórico | 4 - Online
      -- limpa tabela temporária da configuração automática
      DELETE FROM VINT_BASE_TINTCONFAUT WHERE bdcodplanoonline_de IS NOT NULL;
    END

  bdcodplanoonline = prplano_de;
  WHILE  (wde <= wate)  DO
    BEGIN
      IF (prconfaut = 1) THEN
        BEGIN
          IF (wde = 1) THEN
            prclassificacao = '';
          ELSE
          IF (wde = 2) THEN
            prclassificacao = '01';
          ELSE
          IF (wde = 3) THEN
            prclassificacao = '02';
          ELSE
            prclassificacao = '03';
        END

      IF (((prclassificacao IS NULL) OR (prclassificacao = '')) AND ((prapenasnivel = 0) OR (prapenasnivel IS NULL) OR (prconfaut = 1))) THEN
        BEGIN
          bdclassificacao    = '01';
          bdclassificacaoori = NULL;
          bddescricao        = 'Plano de contas';
          bdpodeeditar       = 'FALSE';
          SUSPEND;
          bdclassificacao    = '02';
          bdclassificacaoori = NULL;
          bddescricao        = 'Histórico';
          bdpodeeditar       = 'FALSE';
          SUSPEND;
          bdclassificacao    = '03';
          bdclassificacaoori = NULL;
          bddescricao        = 'Online';
          bdpodeeditar       = 'FALSE';
          SUSPEND;
        END
      ELSE
      IF (SUBSTRING(prclassificacao FROM 1 FOR 2) = '01') THEN --Plano de contas
        BEGIN
          wclassificacao = TRIM((SUBSTRING(prclassificacao FROM 4 FOR (CHAR_LENGTH(prclassificacao)))));
    
          wqtd = 0;
          IF (prapenasnivel = 0) THEN
            BEGIN
              wcount = 1;
              WHILE (wcount <= CHAR_LENGTH(prclassificacao)) DO
                BEGIN
                  IF (SUBSTRING(prclassificacao FROM wcount FOR 1) = '.') THEN
                    wqtd = wqtd + 1;
                  wcount = wcount + 1;
                END
            END
    
          wsql = 'Select tAnt.bdCODTPLA,tAnt.bdCTALON,tAnt.bdNOMCTA,tAnt.bdTIPCTA, ';
          wsql = wsql||'tInt.bdCODTPLAATU,tAtu.bdCTALON,tAtu.bdNOMCTA from planos_tpla tAnt ';
          wsql = wsql||'left join vint_base_tintcontas tInt on (tInt.bdcodint = '||:prcodint||' and tInt.bdcodplapadraoant = '||:prplanocontasant||' and tInt.bdcodtplaant = tAnt.bdcodtpla) ';
          wsql = wsql||'left join planos_tpla tAtu on (tAtu.bdcodplapadrao = tInt.bdcodplapadraoatu and tAtu.bdcodtpla = tInt.bdcodtplaatu) ';
          wsql = wsql||'where ';
    
          IF (prapenasnivel = 0) THEN
            wsql = wsql||'(tAnt.bdtipcta <> 1) and ';
    
          IF (wclassificacao <> '') THEN
            BEGIN
              wsql = wsql||'(substring(tAnt.bdctalon from 1 for '||CHAR_LENGTH(TRIM(wclassificacao))||') = '||''''||TRIM(wclassificacao)||''') and ';
              wsql = wsql||'(tant.bdctalon <> '||''''||TRIM(wclassificacao)||''') and ';
            END
    
    
          wsql = wsql||'(tAnt.bdcodplapadrao = '||:prplanocontasant||') order by tAnt.bdCTALON';
    
          FOR EXECUTE STATEMENT wsql
              INTO :wcodtplaant,:wctalonant,:wnomctaant,:wtipctaant,:wcodtplaatu,:wctalonatu,:wnomctaatu DO
            BEGIN
              wqtdaux = 0;
              IF (prapenasnivel = 0) THEN
                BEGIN
                  wcount = 1;
                  WHILE (wcount <= CHAR_LENGTH(wctalonant)) DO
                    BEGIN
                      IF (SUBSTRING(wctalonant FROM wcount FOR 1) = '.') THEN
                        wqtdaux = wqtdaux + 1;
                      wcount = wcount + 1;
                    END
                END
    
              IF (wqtd = wqtdaux) THEN
                BEGIN
                  bdclassificacao    = '01.'||wctalonant;
                  bdclassificacaoori = wctalonant;
                  bdcodmaster        = wcodtplaant;
                  bdcodcta           = wcodtplaant;
                  bdctalon           = wctalonant;
                  bddescricao        = wnomctaant;
                  bdpodeeditar       = 'FALSE';
                  IF ((COALESCE(prconfaut,0) = 0) OR ((COALESCE(prconfaut,0) = 1) AND (COALESCE(wcodtplaatu,0) = 0) AND (wtipctaant = 1))) THEN
                    SUSPEND;
        
                  IF (wtipctaant = 1) THEN -- Analíticas
                    BEGIN
                      bdclassificacao    = '01.'||wctalonant||'.Z';
                      bdclassificacaoori = wctalonant;
                      bdcodmaster        = wcodtplaant;
                      bdpodeeditar       = 'TRUE';
                      bdcodcta           = NULL;
                      bdctalon           = '';
                      bddescricao        = '';
                      IF (COALESCE(wcodtplaatu,0) > 0) THEN
                        BEGIN
                          bdcodcta        = wcodtplaatu;
                          bdctalon        = wctalonatu;
                          bddescricao     = wnomctaatu;
                        END

                      IF ((COALESCE(prconfaut,0) = 0) OR ((COALESCE(prconfaut,0) = 1) AND (COALESCE(wcodtplaatu,0) = 0))) THEN
                        SUSPEND;
                    END
                END
            END
        END
      ELSE
      IF ((SUBSTRING(prclassificacao FROM 1 FOR 2) = '02') AND (prapenasnivel = 1)) THEN --Histórico
        BEGIN
          wsql = 'Select tAnt.bdCODTPHI,tAnt.bdAPELIDO,tAnt.bdNOME,tInt.bdCODTPHIATU, ';
          wsql = wsql||'tAtu.bdAPELIDO,tAtu.bdNOME from hist_tphi tAnt ';
          wsql = wsql||'left join vint_base_tinthist tInt on (tInt.bdcodint = '||:prcodint||' and tInt.bdcodhistant = '||:prplanohistant||' and tInt.bdcodtphiant = tAnt.bdcodtphi) ';
          wsql = wsql||'left join hist_tphi tAtu on (tAtu.bdcodhist = tInt.bdcodhistatu and tAtu.bdcodtphi = tInt.bdcodtphiatu) ';
          wsql = wsql||'where ';
          wsql = wsql||'(tAnt.bdcodhist = '||:prplanohistant||') order by tAnt.bdcodtphi';
    
          FOR EXECUTE STATEMENT wsql
              INTO :wcodtphiant,:wapelidoant,:whistant,:wcodtphiatu,:wapelidoatu,:whistatu DO
            BEGIN
              bdclassificacao    = '02.'||LPAD(wcodtphiant||'.A', 15, '0');
              bdclassificacaoori = wcodtphiant;
              bdcodmaster        = wcodtphiant;
              bdcodtphist        = wcodtphiant;
              bdapelidohist      = wapelidoant;
              bddescricao        = whistant;
              bdpodeeditar       = 'FALSE';
              IF ((COALESCE(prconfaut,0) = 0) OR ((COALESCE(prconfaut,0) = 1) AND (COALESCE(wcodtphiatu,0) = 0))) THEN
                SUSPEND;

              bdclassificacao    = '02.'||LPAD(wcodtphiant||'.Z', 15, '0');
              bdclassificacaoori = wcodtphiant;
              bdcodmaster        = wcodtphiant;
              bdpodeeditar       = 'TRUE';
              bdcodtphist        = NULL;
              bdapelidohist      = '';
              bddescricao        = '';
              IF (COALESCE(wcodtphiatu,0) > 0) THEN
                BEGIN
                  bdcodtphist   = wcodtphiatu;
                  bdapelidohist = wapelidoatu;
                  bddescricao   = whistatu;
                END

              IF ((COALESCE(prconfaut,0) = 0) OR ((COALESCE(prconfaut,0) = 1) AND (COALESCE(wcodtphiatu,0) = 0))) THEN
                SUSPEND;
            END
        END
      ELSE
      IF (SUBSTRING(prclassificacao FROM 1 FOR 2) = '03') THEN --Online
        BEGIN
          wclassificacao = TRIM((SUBSTRING(prclassificacao FROM 4 FOR (CHAR_LENGTH(prclassificacao)))));
          wqtd           = 0;
    
          wsql = 'Select tAnt.bdFORMULA,tAnt.bdFORMULAITEM,tAnt.bdCONFIGTIT,tAnt.bdCLASSIFICACAO,tAnt.bdDESCRICAO,tAnt.bdAPECTADV,tAnt.bdAPECTACV,';
          wsql = wsql||'tAnt.bdAPECTADO,tAnt.bdAPECTACO,tAnt.bdDESCONTADV,tAnt.bdDESCONTACV,tAnt.bdDESCONTADO,tAnt.bdDESCONTACO,tAnt.bdCODHISTPROV,';
          wsql = wsql||'tAnt.bdCODHISTPGTO,tAnt.bdCODTIPOCONTA,tAnt.bdCODNAT,tAnt.bdCODVER,tAnt.bdDESCREDVER,tAnt.bdAPELIDOTER,tAnt.bdNOMENAT,';
          wsql = wsql||'tAnt.bdAPEHISTPROV,tAnt.bdAPEHISTPGTO,tAnt.bdCONTADEBPROV,tAnt.bdCONTACREDPROV,tAnt.bdCONTADEBPGTO,tAnt.bdCONTACREDPGTO,';
          wsql = wsql||'tAnt.bdCHAVE,tAnt.bdCHAVEVINC,tAnt.bdCODPLANOONLINE,tAnt.bdDESCIMP,tAnt.bdDESCOREC,tAnt.bdCODOREC,tAnt.bdCODIMP,';
          wsql = wsql||'tAnt.bdCODTCA,tAnt.bdCODGRUPOCLA,tAnt.bdDESCGRUPOCLA,tAnt.bdTIPONAT,tAnt.bdCLASSVER,tAnt.bdTIPOVER,tAnt.bdCODITEMONLINE,';
          wsql = wsql||'tAnt.bdAPECOMHISTPROV,tAnt.bdAPECOMHISTPGTO,tAnt.bdCODCOMPHISTPROV,tAnt.bdCODCOMPHISTPGTO,tAnt.bdCOMHISTPROV,tAnt.bdCOMHISTPGTO,';
          wsql = wsql||'tAnt.bdCONFIGPROV,tAnt.bdCONFIGDEBPROV,tAnt.bdCONFIGCREDPROV,tAnt.bdCONFIGPAG,tAnt.bdCONFIGDEBPAG,tAnt.bdCONFIGCREDPAG,';
          wsql = wsql||'tAnt.bdCONFIGHISTPROV,tAnt.bdCONFIGHISTPAG,tAnt.bdNAOCONTAB,tAnt.bdCODREC,tint.bdCODPLANOONLINE_PARA,tint.bdCHAVE_PARA,';
          wsql = wsql||'tConf.bdcodhistprov,tConf.bdcodhistpgto,tConf.bdcontadebprov,tConf.bdcontacredprov,tConf.bdcontadebpgto,tConf.bdcontacredpgto,';
          wsql = wsql||'tConf.bdcodcomphistprov,tConf.bdcodcomphistpgto,tChistP.bdcomplemento bdcomhistprov,tChistO.bdcomplemento bdcomhistpgto,';
          wsql = wsql||'tAnt.bdcodobrser,tAnt.bdchavectaban,tAnt.bdcodcli,tAnt.bdcoddesp ';
          wsql = wsql||'from SP_TREEVIEW_CONS_CONF_ONLINE('||:prplano_de||','''||:wclassificacao||''',';
    
          IF (prlength > 0) THEN
            wsql = wsql||:prlength;
          ELSE
            wsql = wsql||'null';
          wsql = wsql||',';
          wsql = wsql||:prref||',';
    
          IF (prchave IS NOT NULL) THEN
            wsql = wsql||:prchave;
          ELSE
            wsql = wsql||'null';
          wsql = wsql||',';
          wsql = wsql||:prapenasnivel;
    
          IF ((TRIM(prfilterclassificacao) <> '') AND (TRIM(prfilterclassificacao) IS NOT NULL)) THEN
            wsql = wsql||','''||:prfilterclassificacao||'''';
          wsql = wsql||') tAnt ';
          wsql = wsql||'left join vint_base_tintconfcontasonline tInt on (tInt.bdcodint = '||:prcodint||' and tInt.bdcodplanoonline_de = '||:prplano_de||' and tInt.bdchave_de = tAnt.bdchave) ';
          wsql = wsql||'left join VW_TCONF_CONTAS_REF tConf on (tConf.bdcodplanoonline = '||:prplano_para||' and tConf.bdchave = tint.bdCHAVE_PARA and tint.bdCHAVE_PARA > 0) ';
          wsql = wsql||'left outer join tcomplemento_hist tChistP on (tChistP.bdcodcomphist = tConf.BDCODCOMPHISTPROV ) ';
          wsql = wsql||'left outer join tcomplemento_hist tChistO on (tChistO.bdcodcomphist = tConf.BDCODCOMPHISTPGTO ) ';
          wsql = wsql||'order by tAnt.bdclassificacao,tAnt.bdchave ';
          FOR EXECUTE STATEMENT wsql
              INTO :bdformula,:bdformulaitem,:bdconfigtit,:wclassificacao,:bddescricao,:bdapectadv,:bdapectacv,
                   :bdapectado,:bdapectaco,:bddescontadv,:bddescontacv,:bddescontado,:bddescontaco,:bdcodhistprov,
                   :bdcodhistpgto,:bdcodtipoconta,:bdcodnat,:bdcodver,:bddescredver,:bdapelidoter,:bdnomenat,
                   :bdapehistprov,:bdapehistpgto,:bdcontadebprov,:bdcontacredprov,:bdcontadebpgto,:bdcontacredpgto,
                   :bdchave,:bdchavevinc,:bdcodplanoonline,:bddescimp,:bddescorec,:bdcodorec,:bdcodimp,
                   :bdcodtca,:bdcodgrupocla,:bddescgrupocla,:bdtiponat,:bdclassver,:bdtipover,:bdcoditemonline,
                   :bdapecomhistprov,:bdapecomhistpgto,:bdcodcomphistprov,:bdcodcomphistpgto,:bdcomhistprov,:bdcomhistpgto,
                   :bdconfigprov,:bdconfigdebprov,:bdconfigcredprov,:bdconfigpag,:bdconfigdebpag,:bdconfigcredpag,
                   :bdconfighistprov,:bdconfighistpag,:bdnaocontab,:bdcodrec,:wcodplanoonline_para,:wchave_para,
                   :wcodhistprov,:wcodhistpgto,:wcontadebprov,:wcontacredprov,:wcontadebpgto,:wcontacredpgto,
                   :wcodcomphistprov,:wcodcomphistpgto,:wcomhistprov,:wcomhistpgto,:bdcodobrser,:bdchavectaban,:bdcodcli,:bdcoddesp DO
            BEGIN
              bdclassificacao    = '03.'||wclassificacao;
              bdclassificacaoori = wclassificacao;
              bdcodmaster        = bdchave;
              bdpodeeditar       = 'FALSE';
              bdchave_para       = NULL;
    
              --Registro que sejam filhos, ou seja, que tenham um vínculo
              IF (bdchavevinc > 0) THEN
                BEGIN
                  wqtd            = wqtd + 1;
                  bdclassificacao = bdclassificacao||'.Z'||LPAD(wqtd, 15, '0');
                  wqtd            = wqtd + 1;
                END

              IF (COALESCE(prconfaut,0) = 0) THEN
                SUSPEND;
    
              IF ((UPPER(bdconfigtit) = 'TRUE') OR
                  ((UPPER(bdconfigtit) = 'FALSE') AND (bdcoditemonline > 0) AND
                   ((COALESCE(bdconfigprov,'FALSE') <> 'FALSE') OR (COALESCE(bdconfigpag,'FALSE') <> 'FALSE')))) THEN -- Podem ser configuradas
                BEGIN
                  IF ((COALESCE(prconfaut,0) = 1) AND (COALESCE(wchave_para,0) = 0)) THEN
                    SUSPEND;

                  bdcodhistprov     = NULL;
                  bdcodhistpgto     = NULL;
                  bdcontadebprov    = NULL;
                  bdcontacredprov   = NULL;
                  bdcontadebpgto    = NULL;
                  bdcontacredpgto   = NULL;
                  bdcodcomphistprov = NULL;
                  bdcodcomphistpgto = NULL;
                  bdcomhistprov     = NULL;
                  bdcomhistpgto     = NULL;
    
                  bdclassificacao    = '03.'||wclassificacao||'.Z';
                  bdclassificacaoori = wclassificacao;
                  bdcodmaster        = bdchave;
                  bdpodeeditar       = 'TRUE';
                  bdchave            = NULL;
                  bdchave_para       = NULL;
    
                  --Registro que sejam filhos, ou seja, que tenham um vínculo
                  IF (bdchavevinc > 0) THEN
                    bdclassificacao = bdclassificacao||LPAD(wqtd, 15, '0');
    
                  IF (COALESCE(wchave_para,0) > 0) THEN
                    BEGIN
                      bdchave           = wchave_para;
                      bdchave_para      = wchave_para;
                      bdcodhistprov     = wcodhistprov;
                      bdcodhistpgto     = wcodhistpgto;
                      bdcontadebprov    = wcontadebprov;
                      bdcontacredprov   = wcontacredprov;
                      bdcontadebpgto    = wcontadebpgto;
                      bdcontacredpgto   = wcontacredpgto;
                      bdcodcomphistprov = wcodcomphistprov;
                      bdcodcomphistpgto = wcodcomphistpgto;
                      bdcomhistprov     = wcomhistprov;
                      bdcomhistpgto     = wcomhistpgto;
                    END

                  IF ((COALESCE(prconfaut,0) = 0) OR ((COALESCE(prconfaut,0) = 1) AND (COALESCE(wchave_para,0) = 0))) THEN
                    SUSPEND;
                END
            END
        END

      wde = wde + 1;
    END
END
^

/* Restore proc. body: SP_TREEVIEW_CONS_ANUAL_CONF */
ALTER PROCEDURE SP_TREEVIEW_CONS_ANUAL_CONF(PRSISTEMA INTEGER,
PRCODEMP VARCHAR(10000),
PRREF INTEGER,
PRCODQUADRO INTEGER,
PRDETALHAQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDREF INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDORDEM INTEGER,
BDDESCRICAO VARCHAR(80),
BDVALOR NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDJAN NUMERIC(15,6),
BDFEV NUMERIC(15,6),
BDMAR NUMERIC(15,6),
BDABR NUMERIC(15,6),
BDMAI NUMERIC(15,6),
BDJUN NUMERIC(15,6),
BDJUL NUMERIC(15,6),
BDAGO NUMERIC(15,6),
BDSET NUMERIC(15,6),
BDOUT NUMERIC(15,6),
BDNOV NUMERIC(15,6),
BDDEZ NUMERIC(15,6),
BDANOSWS VARCHAR(4))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WQUADROANT INTEGER;
DECLARE VARIABLE WQUADROATU INTEGER;
DECLARE VARIABLE WDESQUADROANT VARCHAR(80);
DECLARE VARIABLE WORDEMANT INTEGER;
DECLARE VARIABLE WDESCORDEMANT VARCHAR(80);
DECLARE VARIABLE WANO CHAR(10);
DECLARE VARIABLE WANOSWS CHAR(2);
DECLARE VARIABLE WPRIMEIROQUADRO INTEGER;
DECLARE VARIABLE WTOTALQUADRO NUMERIC(15,6);
DECLARE VARIABLE WJANQUADRO NUMERIC(15,6);
DECLARE VARIABLE WFEVQUADRO NUMERIC(15,6);
DECLARE VARIABLE WMARQUADRO NUMERIC(15,6);
DECLARE VARIABLE WABRQUADRO NUMERIC(15,6);
DECLARE VARIABLE WMAIQUADRO NUMERIC(15,6);
DECLARE VARIABLE WJUNQUADRO NUMERIC(15,6);
DECLARE VARIABLE WJULQUADRO NUMERIC(15,6);
DECLARE VARIABLE WAGOQUADRO NUMERIC(15,6);
DECLARE VARIABLE WSETQUADRO NUMERIC(15,6);
DECLARE VARIABLE WOUTQUADRO NUMERIC(15,6);
DECLARE VARIABLE WNOVQUADRO NUMERIC(15,6);
DECLARE VARIABLE WDEZQUADRO NUMERIC(15,6);
BEGIN
  /* giovanni */

  /* Procedure Text */

  /* SP Padrao para montar a treeview DA Consulta anual configuravel */
  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wano    = SUBSTRING(prref FROM 1 FOR 4);
  wanosws = SUBSTRING(prref FROM 3 FOR 2);

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql || 'empresas.BDNOMEMP, ';
  wsql = wsql || 'T.BDREF, ';
  wsql = wsql || 'T.BDCODQPLACONSCONF, ';
  wsql = wsql || 'QUADRO.BDDESCRICAO, ';
  wsql = wsql || 'T.BDORDEM, ';
  wsql = wsql || 'T.BDDESCRICAO,';
  wsql = wsql || 'T.BDVALOR';

  -- Baseado na tabela TSistema
  IF (prsistema = 4) THEN -- Contábil
    wsql = wsql || ' from VSUC_REL_CONS_ANUAL_CONF T';
  ELSE
    wsql = wsql || ' from VEF_REL_CONS_ANUAL_CONF T';

  /* tirado a spconsultaempresas_sis muito lenta... */
  --  wsql = wsql||' left outer join SP_CONSULTAEMPRESAS_SIS('|| pranomesfinal || ', t.bdcodemp, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;

  wsql = wsql||' left outer join VW_EMPRESAS_REF_ATUAL empresas on (empresas.bdcodemp = t.bdcodemp) ';
  wsql = wsql||' left outer join TPLANOCONSCONF_Q QUADRO on (QUADRO.BDCODQPLACONSCONF = t.BDCODQPLACONSCONF AND QUADRO.BDCODPLACONSCONF = T.BDCODPLACONSCONF) ' ;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
    wwhere = ' where '||:PRCODEMP;

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      ELSE
        wwhere = wwhere||' where ';

      wwhere = wwhere||'T.BDCODQPLACONSCONF  = '||:prcodquadro;
    END

  IF (wwhere <> '') THEN
    wwhere = wwhere||' and ';
  ELSE
    wwhere = wwhere||' where ';

  -- Baseado na tabela TSistema
  IF (prsistema = 4) THEN -- Contábil
    wwhere = wwhere||' QUADRO.bdcodsis = 4 ';
  ELSE
    wwhere = wwhere||' QUADRO.bdcodsis = 3 '; -- Escrita

  -- wsql = wsql||wwhere || ' order by bdcodemp, bdref desc, BDCODQPLACONSCONF, bdordem' ;
  wsql = wsql||wwhere || ' order by bdcodemp, BDCODQPLACONSCONF, bdordem, bdref  ' ;

  wquadroant      = 0;
  wordemant       = 0;
  wdesquadroant   = '';
  wdescordemant   = '';
  wPrimeiroQuadro = 1;

  -- Baseado na tabela TSistema
  --#6408, comentado o if: precisa inicializar as variaveis pois é feito soma incremental (null + valor = null)
  --if (prsistema = 4) then -- Contábil
  --  begin
      BDJAN   = 0;
      BDFEV   = 0;
      BDMAR   = 0;
      BDABR   = 0;
      BDMAI   = 0;
      BDJUN   = 0;
      BDJUL   = 0;
      BDAGO   = 0;
      BDSET   = 0;
      BDOUT   = 0;
      BDNOV   = 0;
      BDDEZ   = 0;
      BDVALOR = 0;
      BDTOTAL = 0;

      WTOTALQUADRO = 0;
      WJANQUADRO   = 0;
      WFEVQUADRO   = 0;
      WMARQUADRO   = 0;
      WABRQUADRO   = 0;
      WMAIQUADRO   = 0;
      WJUNQUADRO   = 0;
      WJULQUADRO   = 0;
      WAGOQUADRO   = 0;
      WSETQUADRO   = 0;
      WOUTQUADRO   = 0;
      WNOVQUADRO   = 0;
      WDEZQUADRO   = 0;
    --end

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp,
    bdref,
    bdcodquadro,
    bddescquadro,
    bdordem,
    bddescricao,
    bdvalor
  DO
  BEGIN
    IF (((wordemant = bdordem) OR (wordemant = 0)) AND ((wquadroant = bdcodquadro) OR (wquadroant = 0))) THEN   /* totaliza o quadro e a ordem atual */ -- (((wquadroant = bdcodquadro) or (wquadroant = 0))
      BEGIN
        wquadroant    = bdcodquadro;
        wdesquadroant = bddescquadro;
        wordemant     = bdordem;
        wdescordemant = bddescricao;

        IF (bdtotal <> 0) THEN
          bdtotal = bdtotal + bdvalor;
        ELSE
          bdtotal = bdvalor;

        wtotalquadro = wtotalquadro + bdvalor;

        -- Baseado na tabela TSistema
        IF (prSistema <> 4) THEN -- Contábil
          BEGIN
            IF (bdref = CAST(TRIM(wano)||'01' AS INTEGER)) THEN
              bdjan = bdjan + bdvalor; --#6408: bdjan = bdvalor, modificado para soma incremental para todos os meses desse if
            ELSE
            IF (bdref = CAST(TRIM(wano)||'02' AS INTEGER)) THEN
              bdfev = bdfev + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'03' AS INTEGER)) THEN
              bdmar = bdmar + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'04' AS INTEGER)) THEN
              bdabr = bdabr + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'05' AS INTEGER)) THEN
              bdmai = bdmai + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'06' AS INTEGER)) THEN
              bdjun = bdjun + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'07' AS INTEGER)) THEN
              bdjul = bdjul + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'08' AS INTEGER)) THEN
              bdago = bdago + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'09' AS INTEGER)) THEN
              bdset = bdset + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'10' AS INTEGER)) THEN
              bdout = bdout + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'11' AS INTEGER)) THEN
              bdnov = bdnov + bdvalor;
            ELSE
            IF (bdref = CAST(TRIM(wano)||'12' AS INTEGER)) THEN
              bddez = bddez + bdvalor;
          END
        ELSE
          BEGIN
            IF (bdref = CAST(TRIM(wano)||'01' AS INTEGER)) THEN
              BEGIN
                bdjan      = bdjan + bdvalor;
                wjanquadro = wjanquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'02' AS INTEGER)) THEN
              BEGIN
                bdfev      = bdfev + bdvalor;
                wfevquadro = wfevquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'03' AS INTEGER)) THEN
              BEGIN
                bdmar      = bdmar + bdvalor;
                wmarquadro = wmarquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'04' AS INTEGER)) THEN
              BEGIN
                bdabr      = bdabr + bdvalor;
                wabrquadro = wabrquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'05' AS INTEGER)) THEN
              BEGIN
                bdmai      = bdmai + bdvalor;
                wmaiquadro = wmaiquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'06' AS INTEGER)) THEN
              BEGIN
                bdjun      = bdjun + bdvalor;
                wjunquadro = wjunquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'07' AS INTEGER)) THEN
              BEGIN
                bdjul      = bdjul + bdvalor;
                wjulquadro = wjulquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'08' AS INTEGER)) THEN
              BEGIN
                bdago      = bdago + bdvalor;
                wagoquadro = wagoquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'09' AS INTEGER)) THEN
              BEGIN
                bdset      = bdset + bdvalor;
                wsetquadro = wsetquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'10' AS INTEGER)) THEN
              BEGIN
                bdout      = bdout + bdvalor;
                woutquadro = woutquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'11' AS INTEGER)) THEN
              BEGIN
                bdnov      = bdnov + bdvalor;
                wnovquadro = wnovquadro + bdvalor;
              END
            ELSE
            IF (bdref = CAST(TRIM(wano)||'12' AS INTEGER)) THEN
              BEGIN
                bddez      = bddez + bdvalor;
                wdezquadro = wdezquadro + bdvalor;
              END
          END
      END
    ELSE
      BEGIN
        IF ((prSistema <> 4) AND (((prdetalhaquadro = 1) AND (wquadroant <> bdcodquadro)) OR (wprimeiroquadro = 1))) THEN  /* quebra por quadro */
--        if  ((wprimeiroquadro = 1) and (prdetalhaquadro = 1)) then  /* quebra por quadro */
          BEGIN
            wprimeiroquadro = 0;
            bdordem         = NULL;
            bddescricao     = bddescquadro;
            bdanosws        = wanosws;
            SUSPEND;
          END

        bdordem      = wordemant;
        wquadroatu   = bdcodquadro;
        bdcodquadro  = wquadroant;
        bddescquadro = wdesquadroant;
        bddescricao  = wdescordemant;
        bdanosws     = wanosws;
        SUSPEND;

        IF ((prSistema = 4) AND (prdetalhaquadro = 1) AND (wquadroant <> wquadroatu)) THEN  /* quebra por quadro */
          BEGIN
            wprimeiroquadro = 0;
            bdordem         = NULL;
            bddescricao     = bddescquadro;
            BDJAN           = WJANQUADRO;
            BDFEV           = WFEVQUADRO;
            BDMAR           = WMARQUADRO;
            BDABR           = WABRQUADRO;
            BDMAI           = WMAIQUADRO;
            BDJUN           = WJUNQUADRO;
            BDJUL           = WJULQUADRO;
            BDAGO           = WAGOQUADRO;
            BDSET           = WSETQUADRO;
            BDOUT           = WOUTQUADRO;
            BDNOV           = WNOVQUADRO;
            BDDEZ           = WDEZQUADRO;
            BDTOTAL         = WTOTALQUADRO;
            SUSPEND;
            WTOTALQUADRO    = 0;
            WJANQUADRO      = 0;
            WFEVQUADRO      = 0;
            WMARQUADRO      = 0;
            WABRQUADRO      = 0;
            WMAIQUADRO      = 0;
            WJUNQUADRO      = 0;
            WJULQUADRO      = 0;
            WAGOQUADRO      = 0;
            WSETQUADRO      = 0;
            WOUTQUADRO      = 0;
            WNOVQUADRO      = 0;
            WDEZQUADRO      = 0;
          END

        wquadroant = 0;
        wordemant  = 0;
        bdtotal    = 0;

        IF (bdtotal <> 0) THEN
          bdtotal = bdtotal + bdvalor;
        ELSE
          bdtotal = bdvalor;

        wtotalquadro = wtotalquadro + bdvalor;

        IF (bdref = CAST(TRIM(wano)||'01' AS INTEGER)) THEN
          BEGIN
            bdjan      = bdvalor;
            wjanquadro = wjanquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'02' AS INTEGER)) THEN
          BEGIN
            bdfev      = bdvalor;
            wfevquadro = wfevquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'03' AS INTEGER)) THEN
          BEGIN
            bdmar      = bdvalor;
            wmarquadro = wmarquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'04' AS INTEGER)) THEN
          BEGIN
            bdabr      = bdvalor;
            wabrquadro = wabrquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'05' AS INTEGER)) THEN
          BEGIN
            bdmai      = bdvalor;
            wmaiquadro = wmaiquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'06' AS INTEGER)) THEN
          BEGIN
            bdjun      = bdvalor;
            wjunquadro = wjunquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'07' AS INTEGER)) THEN
          BEGIN
            bdjul      = bdvalor;
            wjulquadro = wjulquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'08' AS INTEGER)) THEN
          BEGIN
            bdago      = bdvalor;
            wagoquadro = wagoquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'09' AS INTEGER)) THEN
          BEGIN
            bdset      = bdvalor;
            wsetquadro = wsetquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'10' AS INTEGER)) THEN
          BEGIN
            bdout      = bdvalor;
            woutquadro = woutquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'11' AS INTEGER)) THEN
          BEGIN
            bdnov      = bdvalor;
            wnovquadro = wnovquadro + bdvalor;
          END
        ELSE
        IF (bdref = CAST(TRIM(wano)||'12' AS INTEGER)) THEN
          BEGIN
            bddez      = bdvalor;
            wdezquadro = wdezquadro + bdvalor;
          END

        wdesquadroant = '';
        wdescordemant = '';
          BDFEV = 0;
          BDMAR = 0;
          BDABR = 0;
          BDMAI = 0;
          BDJUN = 0;
          BDJUL = 0;
          BDAGO = 0;
          BDSET = 0;
          BDOUT = 0;
          BDNOV = 0;
          BDDEZ = 0;
      END
  END

  IF ((prsistema <> 4) AND (wprimeiroquadro = 1)) THEN  /* quebra por quadro */
    BEGIN
      wprimeiroquadro = 0;
      bdordem         = NULL;
      bddescricao     = bddescquadro;
      bdanosws        = wanosws;
      SUSPEND;
    END

  bdordem      = wordemant;
  bdcodquadro  = wquadroant;
  bddescquadro = wdesquadroant;
  bddescricao  = wdescordemant;
  bdanosws     = wanosws;
  SUSPEND;

  IF ((prsistema = 4) /*and (wprimeiroquadro = 1)*/) THEN  /* quebra por quadro */
    BEGIN
      wprimeiroquadro = 0;
      bdordem         = NULL;
      bddescricao     = bddescquadro;
      BDJAN           = WJANQUADRO;
      BDFEV           = WFEVQUADRO;
      BDMAR           = WMARQUADRO;
      BDABR           = WABRQUADRO;
      BDMAI           = WMAIQUADRO;
      BDJUN           = WJUNQUADRO;
      BDJUL           = WJULQUADRO;
      BDAGO           = WAGOQUADRO;
      BDSET           = WSETQUADRO;
      BDOUT           = WOUTQUADRO;
      BDNOV           = WNOVQUADRO;
      BDDEZ           = WDEZQUADRO;
      BDTOTAL         = WTOTALQUADRO;
      SUSPEND;
    END
END
^

/* Restore proc. body: SP_TREEVIEW_CONS_CONF_ONLINE */
create or alter procedure SP_TREEVIEW_CONS_CONF_ONLINE (
    PRPLANO integer,
    PRCLASSIFICACAO varchar(100),
    PRLENGTH integer,
    PRREF integer,
    PRCHAVE integer,
    PRAPENASNIVEL integer,
    PRFILTERCLASSIFICACAO DM_MAXVARCHAR = '',
    PRFILTRERTREEVIEW varchar(200) = '',
    PRORDENACAO integer = 0,
    PRCODIGO_TREEVIEW integer = -1,
    PRFORCEDESCRICAO smallint = 0,
    PRCONTAPREP integer = 0)
returns (
    BDFORMULA varchar(80),
    BDFORMULAITEM varchar(80),
    BDCONFIGTIT varchar(5),
    BDCLASSIFICACAO varchar(100),
    BDDESCRICAO varchar(500),
    BDAPECTADV varchar(20),
    BDAPECTACV varchar(20),
    BDAPECTADO varchar(20),
    BDAPECTACO varchar(20),
    BDDESCONTADV varchar(100),
    BDDESCONTACV varchar(100),
    BDDESCONTADO varchar(100),
    BDDESCONTACO varchar(100),
    BDCODHISTPROV integer,
    BDCODHISTPGTO integer,
    BDCODTIPOCONTA integer,
    BDCODNAT integer,
    BDCODVER integer,
    BDDESCREDVER varchar(20),
    BDAPELIDOTER varchar(20),
    BDNOMENAT varchar(335),
    BDAPEHISTPROV varchar(20),
    BDAPEHISTPGTO varchar(20),
    BDCONTADEBPROV integer,
    BDCONTACREDPROV integer,
    BDCONTADEBPGTO integer,
    BDCONTACREDPGTO integer,
    BDCHAVE integer,
    BDCHAVEVINC integer,
    BDCODPLANOONLINE integer,
    BDDESCIMP varchar(100),
    BDDESCOREC varchar(100),
    BDCODOREC integer,
    BDCODIMP integer,
    BDCODTCA integer,
    BDCODGRUPOCLA integer,
    BDDESCGRUPOCLA varchar(200),
    BDTIPONAT integer,
    BDCLASSVER varchar(20),
    BDTIPOVER integer,
    BDCODITEMONLINE integer,
    BDAPECOMHISTPROV varchar(20),
    BDAPECOMHISTPGTO varchar(20),
    BDCODCOMPHISTPROV integer,
    BDCODCOMPHISTPGTO integer,
    BDCOMHISTPROV varchar(1000),
    BDCOMHISTPGTO varchar(1000),
    BDCONFIGPROV varchar(5),
    BDCONFIGDEBPROV varchar(5),
    BDCONFIGCREDPROV varchar(5),
    BDCONFIGPAG varchar(5),
    BDCONFIGDEBPAG varchar(5),
    BDCONFIGCREDPAG varchar(5),
    BDCONFIGHISTPROV varchar(5),
    BDCONFIGHISTPAG varchar(5),
    BDNAOCONTAB varchar(5),
    BDCODREC integer,
    BDCONTABILIZA DM_BOOLEAN,
    BDATIVA DM_BOOLEAN,
    BDCODOBRSER integer,
    BDTIPOSER integer,
    BDSERDESCONTO DM_BOOLEAN,
    BDCHAVECTABAN integer,
    BDCODCLI integer,
    BDCODPLAPADRAO integer,
    BDCODDESP integer,
    BDDESCDESP varchar(100),
    BDTIPODESP integer,
    BDDESPDESCONTO varchar(5),
    BDREFCTA integer)
as
declare variable WWHERE varchar(10);
declare variable WSQL varchar(15000);
declare variable WDESCITEM varchar(200);
declare variable WDESCVERBA varchar(200);
declare variable WSIGLAUF varchar(2);
declare variable WCODCONFDIMESC integer;
declare variable WCODCONFGIASP integer;
declare variable WCODCONFGIAMG integer;
declare variable WCODCONFIPI integer;
declare variable WCODCONFCIAP integer;
declare variable WCODCONFDACON integer;
declare variable WCODDEMDOC integer;
declare variable WCODCONFIRLP integer;
declare variable WDESCIPI varchar(80);
declare variable WDESCCIAP varchar(80);
declare variable WDESCDACON varchar(80);
declare variable WDESCIRLP varchar(80);
declare variable WBDCONFIGPROV varchar(5);
declare variable WBDCONFIGDEBPROV varchar(5);
declare variable WBDCONFIGCREDPROV varchar(5);
declare variable WBDCONFIGPAG varchar(5);
declare variable WBDCONFIGDEBPAG varchar(5);
declare variable WBDCONFIGCREDPAG varchar(5);
declare variable WBDCONFIGHISTPROV varchar(5);
declare variable WBDCONFIGHISTPAG varchar(5);
declare variable WDESCDEMDOC varchar(250);
declare variable WSIS integer;
declare variable WCODCONFGIAES integer;
declare variable WCODCONFGIARO integer;
declare variable WCODCONFGIAPR integer;
declare variable WCODCONFGIARJ integer;
declare variable WSTR varchar(200);
declare variable WOR varchar(4);
declare variable WPOS integer;
declare variable WTIPOOPERIMOB integer;
declare variable WDESCOPERIMOB varchar(80);
declare variable WDESCSERFIN varchar(100);
declare variable WDESCCHAVECTABAN varchar(200);
declare variable WNOMCLI DM_BDNOMEMP;
declare variable WCODCONFBLOCOM integer;
declare variable WDESCBLOCOM varchar(80);
declare variable WCODCONFBLOCOMAUX integer;
declare variable WDESCBLOCOMAUX varchar(150);
declare variable WCODCONFICMSSPED integer;
declare variable WDESCICMSSPED varchar(80);
declare variable WCODCONFGIAST integer;
declare variable WDESCGIAST varchar(80);
declare variable WCODCONFGIATO integer;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREF,NULL,NULL);
  if (prcodigo_treeview > 0) then
    rdb$set_context('USER_SESSION', 'W_TV_CONTAS', prcodigo_treeview);
--  suspend;
  wsql = 'select contas.BDCODPLANOONLINE, '||
                'contas.bdcodtipoconta, '||
                'contas.BDCHAVE,'||
                'contas.BDREFCTA,'||
                'contas.BDCHAVEVINC,'||
                'contas.bdclassificacao,'||
                'tipoconta.bddescricao, '||
                'tipoconta.bdconfigtit,'||
                'contas.BDFORMULA, '||
                'tipoconta.bdFORMULA, '||
                'PLADV.bdapecta bdapectaDV,'||
                'PLACV.bdapecta bdapectaCV,'||
                'PLADO.bdapecta bdapectaDO,'||
                'PLACO.bdapecta bdapectaCO, '||

                'PLADV.BDNOMCTA bdDESCCONTADV,'||
                'PLACV.BDNOMCTA bdDESCCONTACV,'||
                'PLADO.BDNOMCTA bdDESCCONTADO,'||
                'PLACO.BDNOMCTA bdDESCCONTACO, '||

                'contas.BDCODHISTPROV ,'||
                'contas.BDCODHISTPGTO, '||
                'contas.bdcodnat, '||
                'contas.bdcodver, '||
                'ver.BDDESCREDVER, '||
                'null bdapelidoter, '|| --ter.
                'nat.bdnomenat, '||
                'histp.bdapelido bdapehistprov, '||
                'histo.bdapelido bdapehistpgto, '||
                'contas.bdcontadebprov,'||
                'contas.bdcontacredprov,'||
                'contas.bdcontadebpgto,'||
                'contas.bdcontacredpgto,'||
                'contas.bdcodimp,'||
                'contas.bdcodtca,'||
                'IMP.BDDESCIMP,'||
                'contas.bdcodorec, '||
                'OREC.BDDESCOREC,'||
                'cla.BDCODGRUPOCLA, '||
                'cla.BDDESCRICAO,'||
                'nat.BDTIPONAT, '||
                'ver.BDCLAVER, '||
                'verref.BDTIPOCODVER,'||
                'contas.BDCODITEMONLINE,'||
                --'itemconf.BDDESCRICAO,'||
                'CASE WHEN ((imp.bdDOCARRECADACAO = 11) and (contas.bdFORMULA like ''IMPCOMP%'')) THEN ''Compensação da retenção do ISS Serviços emitidos'' '|| -- Alt.: #125251 #125145 #125143 #124345 #124579 #124580 #100791 #88834 #84278 #75998 #73975 #72067 #71946 #64819 #128954 #129004 - Ajustes para mudar a descrição do campo na consulta dos impostos do simples nacional...
                '  ELSE ITEMCONF.BDDESCRICAO '||
                'END BDDESCRICAO, '||
                'ver.BDDESCVER,'||
                'uf.bdsiglauf,'||
                'contas.bdcodconfdimesc,'||
                'contas.bdcodconfSP,'||
                'contas.bdcodconfGIAMG,'||
                'contas.bdcodconfGIAES,'||
                'contas.bdcodconfGIARO,'||
                'contas.bdcodconfipi,'||
                'contas.BDCODCONFCIAP,'||
                'contas.bdcodconfDACON,'||
                'contas.bdcodconfirlp,'||

                'IPI.BDDESCIPI,'||
                'CIAP.BDDESCCIAP,'||
                'DACON.BDDESCDACON,'||
                'IRLP.BDDESCIRLP,'||
                'CHISTP.BDAPELIDO BDAPECOMHISTPROV,'||
                'CHISTO.BDAPELIDO BDAPECOMHISTPGTO,'||
                'CONTAS.BDCODCOMPHISTPROV,'||
                'CONTAS.BDCODCOMPHISTPGTO,'||
                'CHISTP.BDCOMPLEMENTO BDCOMHISTPROV,'||
                'CHISTO.BDCOMPLEMENTO BDCOMHISTPGTO,'||

                'tipoconta.BDCONFIGPROV,'||
                'tipoconta.BDCONFIGDEBPROV  ,'||
                'tipoconta.BDCONFIGCREDPROV,'||
                'tipoconta.BDCONFIGPAG,'||
                'tipoconta.BDCONFIGDEBPAG,'||
                'tipoconta.BDCONFIGCREDPAG,'||

                'itemconf.BDCONFIGPROV,'||
                'itemconf.BDCONFIGDEBPROV  ,'||
                'itemconf.BDCONFIGCREDPROV,'||
                'itemconf.BDCONFIGPAG,'||
                'itemconf.BDCONFIGDEBPAG,'||
                'itemconf.BDCONFIGCREDPAG,'||

                'tipoconta.BDCONFIGHISTPROV,'||
                'tipoconta.BDCONFIGHISTPAG,'||
                'itemconf.BDCONFIGHISTPROV,'||
                'itemconf.BDCONFIGHISTPAG,'||
                'DEMDOC.BDCODTIPODOC ,'||
                'contas.BDNAOCONTAB,'||
                'DEMDOC.BDDESCRICAO BDDESCDEMDOC,imp.bdcodsis, '||
                'contas.BDCODREC, '||
                'contas.BDCODCONFGIAPR, '||
                'contas.BDCODCONFGIARJ, '||
                'COALESCE(nat.BDCONTABILIZA, IIF(demdoc.BDNAOCONTABILIZA = ''TRUE'',''FALSE'',NULL) ) as BDCONTABILIZA, '|| -- Alt.: 13623 - Caso o tipo do documento não contabilize, deve bloquear a alteração das contas, caso contrário retorno "null" para caso venha outra configuração, é só inserir no Coalesce...
                'F200.bdtipooperimob, '||
                'F200.bddescricao, '||
                'contas.BDATIVA, '|| --alt:13055 - 04/04/2016 - Adicionado campo. Pedro
                'contas.bdCODOBRSER, '||
                'ser.BDDESCRICAO, '||
                'ser.BDTIPO, '||
                'ser.BDDESCONTO, '|| --Adilson Hasckel - sol. 14282
                'ctaban.BDCHAVECTABAN, '||
                'ctaban.BDDESCCTABAN, '|| --Adilson Hasckel - sol. 14543
                'cli.BDCODCLI, '||
                'cli.BDNOMCLI, '||
                'desp.bdcoddesp, '||
                'desp.bddescdesp, '||
                'desp.bdtipodesp, '||
                '(desp.bddesconto) bddescdesconto, '||
                'contas.BDCODCONFBLOCOM, BlocoM.BDDESCCONF as BDDESCBLOCOM, '|| -- Alt.: 22861 - Configuração do Bloco M
                'CAST(CASE '|| -- Alt.: 23804 - Contas detalhes da contabilização do Bloco M
                '       WHEN (contas.BDFORMULA like ''BLOCOMCREDDESC%'') then SUBSTRING(contas.bdCLASSIFICACAO from CHAR_LENGTH(contas.bdCLASSIFICACAO)-7 for 8) '||
                '       WHEN (contas.BDFORMULA like ''BLOCOMDEBITO%'') then SUBSTRING(contas.bdCLASSIFICACAO from CHAR_LENGTH(contas.bdCLASSIFICACAO)-7 for 8) '||
                '     ELSE NULL '||
                '     END as INTEGER) as BDCODCONFBLOCOMAUX, '||
                'CASE '|| -- Alt.: 23804 - Contas detalhes da contabilização do Bloco M
                '  WHEN (contas.BDFORMULA LIKE ''BLOCOMCREDDESC%'') THEN t437.bdDESCRICAO '||
                '  WHEN (contas.BDFORMULA LIKE ''BLOCOMDEBITO%'') THEN t435.bdDESCRICAO '||
                'ELSE NULL END as BDDESCBLOCOMAUX, '||
                'contas.bdCODCONFICMSSPED, sped.bdDESCICMSSPED, contas.BDCODPLAPADRAO, '||
                'giast.bdCODCONFGIAST, giast.BDDESCRICAO,  '||
                'contas.BDCODCONFGIATO ';

--  if ((prplano is not null) and (prplano <> 0))  then
--      wsql = wsql || ' from (select * from TCONF_CONTAS_ONLINE where bdcodplanoonline = '||prPlano||') contas ';
--  else

  if (prcodigo_treeview > 0 and prchave > 0) then
    wsql = wsql || ' from VW_TCONF_VARIAS_CONTAS_REF_TEMP contas ';
  else
  if (prcodigo_treeview > 0) then
    wsql = wsql || ' from VW_TCONF_CONTAS_REF_TEMP contas ';
  else
      wsql = wsql || ' from VW_TCONF_CONTAS_REF contas ';

  wsql = wsql || ' left outer join ttipocontaonline tipoconta on (contas.bdcodtipoconta = tipoconta.bdcodtipoconta)';
  wsql = wsql || ' left outer join planos_tpla PLADV on (PLADV.bdcodplapadrao = contas.bdcodplapadrao AND PLADV.bdcodtpla = CONTAS.bdcontadebprov) ';
  wsql = wsql || ' left outer join planos_tpla PLACV on (PLACV.bdcodplapadrao = contas.bdcodplapadrao AND PLACV.bdcodtpla = CONTAS.bdcontacredprov) ';
  wsql = wsql || ' left outer join planos_tpla PLADO on (PLADO.bdcodplapadrao = contas.bdcodplapadrao AND PLADO.bdcodtpla = CONTAS.bdcontadebpgto) ';
  wsql = wsql || ' left outer join planos_tpla PLACO on (PLACO.bdcodplapadrao = contas.bdcodplapadrao AND PLACO.bdcodtpla = CONTAS.bdcontacredpgto) ';
  wsql = wsql || ' left outer join hist_tphi histP on (histP.bdcodhist = contas.bdcodtphi and histP.bdcodtphi = contas.bdcodhistprov) ';
  wsql = wsql || ' left outer join hist_tphi histO on (histO.bdcodhist = contas.bdcodtphi and histO.bdcodtphi = contas.bdcodhistpgto) ';

  wsql = wsql || ' left outer join TCOMPLEMENTO_HIST ChistP on (ChistP.bdcodcomphist = contas.BDCODCOMPHISTPROV ) ';
  wsql = wsql || ' left outer join TCOMPLEMENTO_HIST ChistO on (ChistO.bdcodcomphist = contas.BDCODCOMPHISTPGTO ) ';

--  wsql = wsql || ' left outer join TIMPOSTO IMP on (IMP.bdcodimp = contas.bdCODIMP and IMP.bdcodsis = 3) ';
  wsql = wsql || ' left outer join TIMPOSTO IMP on (IMP.bdcodimp = contas.bdCODIMP and IMP.bdcodsis in (3,7)) ';--gilberto - 11/05/2014 - ALT#:1044

  wsql = wsql || ' left outer join Tuf uf on (uf.bdcoduf = contas.bdCODuf) ';
  wsql = wsql || ' left outer join tgrupoclassecol cla on (contas.BDCODGRUPOCLA = cla.BDCODGRUPOCLA)';
--  wsql = wsql || ' left outer join vw_tterceiro ter on (contas.bdcodter = ter.bdcodter and contas.bdcodtipter = ter.bdcodtipter)';
  wsql = wsql || ' left outer join vrh_base_tverbas ver on (contas.bdcodver = ver.bdcodver)';
  wsql = wsql || ' left outer join VW_VERBAS_REF_ATUAL verref on (contas.bdcodver = verref.bdcodver)';
  wsql = wsql || ' left outer join vef_base_tnatop nat on (contas.bdcodnat = nat.bdcodnat)';
  wsql = wsql || ' left outer join vef_base_tcadorec OREC on (OREC.bdcodorec = contas.bdcodorec) ';
  wsql = wsql || ' left outer join TITEMCONFIGONLINE itemconf on (itemconf.bdcoditemonline = contas.bdcoditemonline) ';
/* APURACAO DE IMPOSTOS*/
  wsql = wsql || ' left outer join vef_base_tconfipi IPI on (contas.bdcodconfipi = IPI.bdcodconfipi)';
  wsql = wsql || ' left outer join VEF_BASE_TCONFCIAP CIAP on (CIAP.BDCODCONFCIAP = contas.BDCODCONFCIAP)';
  wsql = wsql || ' left outer join vef_base_tconfDACON DACON on (contas.bdcodconfDACON = DACON.bdcodconfDACON)';
  wsql = wsql || ' left outer join vef_base_tconfirlp IRLP on (contas.bdcodconfIRLP = IRLP.bdcodconfirlp)';

/* DEMAIS DOCUMENTOS*/
  --wsql = wsql || ' left outer join VEF_BASE_TAB_BC_CRED DEMDOC on (contas.BDNAT_BC_CRED = DEMDOC.BDNAT_BC_CRED)';
  --alterado para utilizar a tabela de tipo de documento
  wsql = wsql || ' left outer join vef_base_tcadtipodemdoc DEMDOC on (contas.BDCODTIPODOC = DEMDOC.bdcodtipodoc)';
  
  /*Operações imobiliárias*/
  wsql = wsql || ' left outer join vef_base_ttabtipoopf200 f200 on(contas.bdtipooperimob = f200.bdtipooperimob)';

  /*serviços do financeiro*/
  wsql = wsql || ' left outer join VCT_BASE_SERVICO ser on (contas.bdCODOBRSER = ser.bdCODOBRSER) ';

  /*despesas do financeiro*/
  wsql = wsql || ' left outer join VFIN_BASE_TDESPESA desp on (contas.bdCODDESP = desp.bdCODDESP) ';

  /*contas bancárias do financeiro*/
  wsql = wsql || ' left outer join VFIN_ESC_TCONTASBAN ctaban on (contas.bdCHAVECTABAN = ctaban.bdCHAVECTABAN) ';

  /*cliente do financeiro*/
  wSql = wSql || ' left outer join VW_VFIN_CLIENTES_REF cli on (contas.bdcodcli = cli.bdcodcli) ';
  /* Bloco M */
  wSql = wSql || ' left outer join VEF_BASE_TCONFBLOCOM BlocoM on (BlocoM.BDCODCONF = contas.BDCODCONFBLOCOM) '; -- Alt.: 22861
  -- Alt.: 23804 - Contas detalhes da contabilização do Bloco M
  --#100977 #127609 #128357 #128465 #129082 #131597 #128582 - Melhoria na performance. Machado - 27/02/2020
  wSql = wSql || ' left outer join VEF_BASE_TNATBCPISCOFINS t437 on (cast(t437.bdREGEXP as integer) = CAST(IIF((contas.BDFORMULA like ''BLOCOMCREDDESC%''), SUBSTRING(contas.bdCLASSIFICACAO from CHAR_LENGTH(contas.bdCLASSIFICACAO)-7 for 8), ''0'') as INTEGER)) ';
  wSql = wSql || ' left outer join VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (cast(t435.bdCODCSOCIALEXP as integer) = CAST(IIF((contas.BDFORMULA like ''BLOCOMDEBITO%''), SUBSTRING(contas.bdCLASSIFICACAO from CHAR_LENGTH(contas.bdCLASSIFICACAO)-7 for 8), ''0'') as INTEGER)) ';
  /* SPED */
  wSql = wSql || 'left outer join VEF_BASE_TCONFICMSSPED sped on (sped.bdCODCONFICMSSPED = contas.bdCODCONFICMSSPED) '; -- Alt.: #82718
  /* GIA ST*/
  wSql = wSql || 'left outer join VEF_BASE_TCONFGIAST giast on (giast.bdCODCONFGIAST = contas.bdCODCONFGIAST) ';

--  wsql = wsql || ' left outer join centros_tpcc tpcc on (tpcc.bdcodcentro = contas.bdcodcentro and tpcc.bdcodtpcc = contas.bdcodtpcc) ';

  wwhere = ' where ';
  IF (prPlano IS NOT NULL) THEN
     BEGIN
       wsql = wsql||wwhere||'contas.bdcodplanoonline = '||prPlano;
       wwhere = ' and ';
     END

  IF ((prclassificacao <> '') AND (prclassificacao IS NOT NULL)) THEN
     BEGIN
       wsql = wsql||wwhere||'char_length(contas.bdclassificacao) >= '||CHAR_LENGTH(prclassificacao);

       IF (prApenasNivel = 2) THEN
          wsql = wsql||' and contas.bdclassificacao = '||''''||prclassificacao||'''';
       ELSE
       --#100977 #127609 #128357 #128465 #129082 #131597 #128582 - Melhoria na performance. Machado - 27/02/2020
          wsql = wsql||' and contas.bdclassificacao starting with '||''''||prclassificacao||'''';

       --IF (prCLASSIFICACAO <>  '03.002.000000010') THEN -- Alt.: 23804 - Contas detalhes da contabilização do Bloco M, não vai trazer todas as analiticas.
       --  wsql = wsql||' and contas.BDFORMULA not like ''%.%'' ';

       IF (SUBSTRING(prCLASSIFICACAO FROM 1 FOR 16) = '03.002.000000002') THEN -- Alt.: #82718 - Na busca do ICMS, não deve buscar as contas do RS, pois vai ter uma classficação própria pois não entrega GIA...
          wsql = wsql||' AND contas.bdCLASSIFICACAO NOT LIKE ''03.002.000000002.T00000023%'' ';

       -- Matheus Fritzen -#178227 - Contabilização Fundo Social/Fumdes Quadro 16
       if (((SUBSTRING(prCLASSIFICACAO FROM 1 FOR 16) = '03.002.000000002') AND  (SUBSTRING(prCLASSIFICACAO FROM 1 FOR 26) <> '03.002.000000002.T00000024')) AND ((CHAR_LENGTH(PRCLASSIFICACAO) = 26) or (CHAR_LENGTH(PRCLASSIFICACAO) = 36))) then
          wsql = wsql||' AND (CONTAS.BDCODITEMONLINE not in (670, 671, 672, 673, 674, 675) OR CONTAS.BDCODITEMONLINE IS NULL) ';
       ELSE
       if ((prCLASSIFICACAO = '03.002.000000002') AND (CHAR_LENGTH(PRCLASSIFICACAO) = 16)) then
          wsql = wsql||' AND IIF((UF.BDSIGLAUF <> ''SC'') OR (UF.BDSIGLAUF IS NULL), (CONTAS.BDCODITEMONLINE NOT IN (670, 671, 672, 673, 674, 675) OR (CONTAS.BDCODITEMONLINE IS NULL)), TRUE = TRUE) ';

       wwhere = ' and ';
     END

  IF (prApenasNivel IS NULL) THEN
     prApenasNivel = 1;

  IF ((prlength > 0) AND (prlength IS NOT NULL)) THEN
     BEGIN
       IF (prApenasNivel = 0) THEN
          wsql = wsql||wwhere||' char_length(contas.bdclassificacao) = '||prlength;
       ELSE
          wsql = wsql||wwhere||' char_length(contas.bdclassificacao) >= '||prlength;
       wwhere = ' and ';
     END

  IF ((prchave <> 0) AND (prchave IS NOT NULL)) THEN
     BEGIN
       IF (prapenasnivel = 3) THEN
         wsql = wsql||wwhere||' ((contas.bdchavevinc = '||prchave||') or (contas.bdchave = '||prchave||'))';
       ELSE
         wsql = wsql||wwhere||' contas.bdchavevinc = '||prchave;
       wwhere = ' and ';
     END
  ELSE
    IF ((prchave <> 0) OR (prchave IS NULL))  THEN
      BEGIN
       wsql = wsql||wwhere||' contas.bdchavevinc is null ';
        wwhere = ' and ';
      END

  --Alt.:5789, Não levar mais as classificações de "outras receitas".
  wsql = wsql||wwhere||' (NOT UPPER(CONTAS.BDCLASSIFICACAO) STARTING WITH UPPER(''03.001.000000004'')) ';

  --Alt.:6461. Quando for configuração do plano de troca de/para busco apenas os itens necessários, ou seja,
  --os que foram passado por parâmetro
  IF ((prfilterclassificacao IS NOT NULL) AND (prfilterclassificacao <> ''))  THEN
    BEGIN
      wor  = '';
      wsql = wsql||' and (';
      WHILE (TRIM(prfilterclassificacao) <> '') DO
        BEGIN
          wpos = POSITION(',', prfilterclassificacao);
          IF (wpos > 0) THEN
            BEGIN
              wstr = SUBSTRING(prfilterclassificacao FROM 1 FOR wpos-1);
              prfilterclassificacao = SUBSTRING(prfilterclassificacao FROM wpos+1 FOR CHAR_LENGTH(prfilterclassificacao));
            END
          ELSE
            BEGIN
              wstr                  = prfilterclassificacao;
              prfilterclassificacao = '';
            END

          IF (POSITION('#', wstr) > 0) THEN
            BEGIN
              wstr = SUBSTRING(wstr FROM 2 FOR CHAR_LENGTH(wstr));
              wsql = wsql||wor||' (Upper(contas.bdclassificacao) = Upper('''||wstr||'''))';
            END
          ELSE
            wsql = wsql||wor||' (Upper(contas.bdclassificacao) starting with Upper('''||wstr||'''))';

          wor  = ' or ';
        END
      wsql = wsql||') ';
    END

  wSQL = wSQL||' AND ((IMP.BDCODIMP IS NULL) OR '; -- Alt.: #125251 #125145 #125143 #124345 #124579 #124580 #100791 #88834 #84278 #75998 #73975 #72067 #71946 #64819 #128954 #129004 - Ajustes para nao trazer as contas de compensacao nos impostos, apenas no simples nacional...
  wSQL = wSQL||     ' ((IMP.BDCODIMP IS NOT NULL) AND ((IMP.BDDOCARRECADACAO = 11) OR (contas.bdFORMULA IS NULL) OR ((CONTAS.BDFORMULA NOT LIKE ''IMPCOMP%'') AND (CONTAS.BDFORMULA NOT LIKE ''AJUCONT%'')) )) ) ';

  IF ((prfiltrertreeview <> '') AND (prfiltrertreeview IS NOT NULL)) THEN
     BEGIN
       wsql = wsql||' and ('''||prfiltrertreeview||''' starting with contas.bdclassificacao) ';
     END

  if ((prcontaprep > 0) AND (prfiltrertreeview IS NOT NULL)) then
    BEGIN
       wsql = wsql||' and ('||prcontaprep||' IN (bdcontadebprov,bdcontacredprov)) ';
     END

  --#100977 #127609 #128357 #128465 #129082 #131597 #128582 - Melhoria na performance. Machado - 27/02/2020
  if (PRORDENACAO = 1) then
    wsql = wsql||' ORDER BY CONTAS.BDCODPLANOONLINE, CONTAS.BDCLASSIFICACAO';

  FOR EXECUTE STATEMENT wsql INTO
    bdcodplanoonline,
    bdcodtipoconta,
    bdchave,
    bdrefcta,
    bdchavevinc,
    bdclassificacao,
    bddescricao,
    bdconfigtit,
    bdformula,
    BDFORMULAITEM,
    bdapectadv,
    bdapectacv,
    bdapectado,
    bdapectaco,

    BDDESCONTAdv,
    BDDESCONTAcv,
    BDDESCONTAdo,
    BDDESCONTAco,

    bdcodhistprov,
    bdcodhistpgto,
    bdcodnat,
    bdcodver,
    bddescredver,
    bdapelidoter,
    bdnomenat,
    bdapehistprov,
    bdapehistpgto,
    bdcontadebprov,
    bdcontacredprov,
    bdcontadebpgto,
    bdcontacredpgto,
    bdcodimp,
    bdcodtca,
    bddescimp,
    bdcodorec,
    bddescorec,
    bdcodgrupocla,
    bddescgrupocla,
    bdtiponat,
    bdclassver,
    bdtipover,
    bdcoditemonline,
    wdescitem,
    wdescverba,
    wsiglauf,
    wcodconfdimesc,
    wcodconfGIASP,
    wcodconfGIAMG,
    wcodconfGIAES,
    wcodconfGIARO,
    wcodconfipi,
    wCODCONFCIAP,
    wcodconfDACON,
    wcodconfirlp,
    WDESCIPI,
    WDESCCIAP,
    WDESCDACON,
    WDESCIRLP,
    BDAPECOMHISTPROV,
    BDAPECOMHISTPGTO,
    BDCODCOMPHISTPROV,
    BDCODCOMPHISTPGTO,
    BDCOMHISTPROV,
    BDCOMHISTPGTO,

    BDCONFIGPROV,
    BDCONFIGDEBPROV,
    BDCONFIGCREDPROV,
    BDCONFIGPAG,
    BDCONFIGDEBPAG,
    BDCONFIGCREDPAG,

    WBDCONFIGPROV,
    WBDCONFIGDEBPROV,
    WBDCONFIGCREDPROV,
    WBDCONFIGPAG,
    WBDCONFIGDEBPAG,
    WBDCONFIGCREDPAG,

    BDCONFIGHISTPROV,
    BDCONFIGHISTPAG,
    WBDCONFIGHISTPROV,
    WBDCONFIGHISTPAG,
    WCODDEMDOC,
    BDNAOCONTAB,
    WDESCDEMDOC,
    wsis,
    bdcodrec,
    wcodconfgiapr,
    wCODCONFGIARJ,
    BDCONTABILIZA,
    wtipooperimob,
    wdescoperimob,
    BDATIVA,
    bdcodobrser,
    wdescserfin,
    bdtiposer,
    bdserdesconto,
    bdchavectaban,
    wDescChaveCtaBan,
    bdcodcli, 
    wNomcli,
    bdcoddesp,
    bddescdesp,
    bdtipodesp,
    bddespdesconto,
    WCODCONFBLOCOM,
    WDESCBLOCOM,
    wCODCONFBLOCOMAUX,
    wDESCBLOCOMAUX,
    wCODCONFICMSSPED,
    wDESCICMSSPED,
    BDCODPLAPADRAO,
    WCODCONFGIAST,
    WDESCGIAST,
    WCODCONFGIATO
    DO
   BEGIN
     if (PRFORCEDESCRICAO = 1) then
        BEGIN
          bdcoditemonline = NULL;
          WDESCITEM = NULL;
        END

     IF ((bdcodnat IS NOT NULL) AND (bdcoditemonline IS NULL)) THEN
        BEGIN
          bddescricao = SUBSTRING(bdcodnat FROM 1 FOR 1)||'.'||SUBSTRING(bdcodnat FROM 2 FOR 3)||'-'||SUBSTRING(bdcodnat FROM 5 FOR 3)||' - '||bdnomenat;
        END

     IF ((WCODDEMDOC IS NOT NULL) AND (bdcoditemonline IS NULL)) THEN
        bddescricao = WCODDEMDOC ||'-'|| WDESCDEMDOC;

     IF ((wcodconfipi IS NOT NULL) AND (bdcoditemonline IS NULL)) THEN
        bddescricao = wcodconfipi ||'-'|| wdescipi;

     IF ((wCODCONFCIAP IS NOT NULL) AND (BDCODITEMONLINE IS NULL)) THEN
        bdDESCRICAO = wCODCONFCIAP ||'-'|| wDESCCIAP;

     IF ((wcodconfDACON IS NOT NULL) AND (bdcoditemonline IS NULL)) THEN
        bddescricao = wcodconfDACON ||'-'|| wdescDACON;

     IF ((wcodconfirlp IS NOT NULL) AND (bdcoditemonline IS NULL)) THEN
        bddescricao = wcodconfirlp ||'-'|| wdescirlp;

     IF ((wtipooperimob IS NOT NULL) AND (bdcoditemonline IS NULL)) THEN
        bddescricao = wtipooperimob ||'-'|| wdescoperimob;  

     IF ((wCodConfBlocoM IS NOT NULL) AND (bdCodItemOnline IS NULL)) THEN
        bdDESCRICAO = wCodConfBlocoM ||'-'|| WDESCBLOCOM;

     IF (wsiglauf IS NOT NULL) THEN
        bddescricao = wsiglauf;

     IF ((wcodconfdimesc IS NOT NULL) OR (wcodconfgiasp IS NOT NULL) OR (wcodconfgiamg IS NOT NULL) OR (wcodconfgiaes IS NOT NULL)
        OR (wcodconfgiaro IS NOT NULL) OR (wcodconfgiapr IS NOT NULL) OR (wCODCONFGIARJ IS NOT NULL) OR (wCODCONFGIATO IS NOT NULL) AND (bdcoditemonline IS NULL)) THEN
        BEGIN
          IF (wsiglauf = 'ES') THEN
             BEGIN
               SELECT conf.bddescconf FROM vef_estados_tconfgiaes conf WHERE conf.bdcodconf = :wcodconfgiaes INTO bddescricao;
               bddescricao = wcodconfgiaes ||'-'|| bddescricao;
             END
          ELSE
          IF (wsiglauf = 'SC') THEN
            BEGIN
              SELECT conf.bddescconf FROM VEF_ESTADOS_TCONFDIMESC conf WHERE conf.bdcodconfdimesc = :wcodconfdimesc INTO bddescricao;
              bddescricao = wcodconfdimesc ||'-'|| bddescricao;
            END
          ELSE
          IF (wsiglauf = 'SP') THEN
            BEGIN
              SELECT conf.bddescconf FROM vef_estados_tconfgiasp conf WHERE conf.bdcodconf = :wcodconfgiasp INTO bddescricao;
              bddescricao = wcodconfgiasp ||'-'|| bddescricao;
            END
          ELSE
          IF (wsiglauf = 'MG') THEN
            BEGIN
              SELECT conf.bddescconf FROM vef_estados_tconfgiamg conf WHERE conf.bdcodconf = :wcodconfgiamg INTO bddescricao;
              bddescricao = wcodconfgiamg ||'-'|| bddescricao;
            END
          ELSE
          IF (wsiglauf = 'RO') THEN
             BEGIN
               SELECT conf.bddescconf FROM vef_estados_tconfgiaro conf WHERE conf.bdcodconf = :wcodconfgiaro INTO bddescricao;
               bddescricao = wcodconfgiaro ||'-'|| bddescricao;
             END
          ELSE
          IF (wsiglauf = 'PR') THEN
             BEGIN
               SELECT confpr.bddescconf FROM vef_estados_tconfgiapr confpr WHERE confpr.bdcodconf = :wcodconfgiapr INTO bddescricao;
               bddescricao = wcodconfgiapr ||'-'|| bddescricao;
             END
          ELSE
          IF (wSiglaUF = 'RJ') THEN
             BEGIN
               SELECT confrj.BDDESCCONF FROM VEF_ESTADOS_TCONFGIARJ confrj WHERE confrj.BDCODCONF = :wCODCONFGIARJ INTO BDDESCRICAO;
               BDDESCRICAO = wCODCONFGIARJ ||'-'|| BDDESCRICAO;
             END
   ELSE
          IF (wSiglaUF = 'TO') THEN
             BEGIN
               SELECT confto.BDDESCCONF FROM VEF_ESTADOS_TCONFGIATO confto WHERE confto.BDCODCONF = :wCODCONFGIATO INTO BDDESCRICAO;
               BDDESCRICAO = wCODCONFGIATO ||'-'|| BDDESCRICAO;
             END
        END

     IF (bdapelidoter IS NOT NULL) THEN
        bddescricao = bdapelidoter;

     IF (bddescorec IS NOT NULL) THEN
        bddescricao = bddescorec;

     IF (bddescimp IS NOT NULL) THEN
        bddescricao = bdcodimp ||' - '|| bddescimp;

     IF (wdescitem IS NOT NULL) THEN
        bddescricao = wdescitem;

     IF (bddescgrupocla IS NOT NULL) THEN
        bddescricao = bddescgrupocla;
     ELSE
     IF (bdcodtca IS NOT NULL) THEN
        BEGIN
          SELECT X.BDDESCTCA FROM vrh_base_ttipocalcavul X WHERE x.bdcodtca = :bdcodtca INTO :bddescricao;
        END

     IF ((bdcodrec IS NOT NULL) AND (bdcoditemonline IS NULL)) THEN
        BEGIN
           SELECT X.bddescrec FROM tcodrec X WHERE x.bdcodrec = :bdcodrec INTO :bddescricao;

           bddescricao = bdcodrec||' - '||bddescricao;
        END

     IF (wdescverba IS NOT NULL) THEN
--        bddescricao = bdclassver||' - '||wdescverba;
        bddescricao = bdcodver||' - '||wdescverba;

     IF (wdescserfin IS NOT NULL) THEN
        bddescricao =  bdcodobrser||' - '||wdescserfin;

     IF (wdescchavectaban IS NOT NULL) THEN
        bddescricao = bdchavectaban||' - '||wdescchavectaban;

     IF (wnomcli IS NOT NULL) THEN
        bddescricao = bdcodcli||' - '||wnomcli;

     IF (bddescdesp IS NOT NULL) THEN
        bddescricao =  bdcoddesp||' - '||bddescdesp;

     IF ((wCODCONFBLOCOMAUX IS NOT NULL) AND (wDESCBLOCOMAUX IS NOT NULL)) THEN
        bdDESCRICAO = LPAD(wCODCONFBLOCOMAUX, 2, '0') ||'-'|| wDESCBLOCOMAUX;

     IF ((wCODCONFICMSSPED IS NOT NULL) AND (wDESCICMSSPED IS NOT NULL)) THEN
        bdDESCRICAO = wCODCONFICMSSPED||'-'||wDESCICMSSPED;

     IF ((WCODCONFGIAST IS NOT NULL) AND (bdcoditemonline IS NULL)) THEN
        bdDESCRICAO = WCODCONFGIAST||'-'||WDESCGIAST;

     IF (bdcoditemonline IS NOT NULL) THEN
        BEGIN
          BDCONFIGPROV = WBDCONFIGPROV;
          BDCONFIGDEBPROV  = WBDCONFIGDEBPROV;
          BDCONFIGCREDPROV = WBDCONFIGCREDPROV;
          BDCONFIGPAG = WBDCONFIGPAG;
          BDCONFIGDEBPAG = WBDCONFIGDEBPAG;
          BDCONFIGCREDPAG = WBDCONFIGCREDPAG;
          BDCONFIGHISTPROV = WBDCONFIGHISTPROV;
          BDCONFIGHISTPAG = WBDCONFIGHISTPAG;
        END

    IF (BDCODOBRSER > 0 AND BDSERDESCONTO = UPPER('TRUE')) THEN
        BEGIN
          BDCONFIGDEBPROV  = 'TRUE';
          BDCONFIGCREDPROV = 'TRUE';
          BDCONFIGDEBPAG   = 'TRUE';
        END

     --if ((bdcodimp is null) or (wsis = 3) and (bdcodimp is not null)) then
     IF ((bdcodimp IS NULL) OR (wsis IN (3,7)) AND (bdcodimp IS NOT NULL)) THEN --gilberto - 11/05/2014 - ALT#:1044
     SUSPEND;
   END
END
^

/* Restore proc. body: SP_TREEVIEW_PREP_CONTA */
create or alter procedure SP_TREEVIEW_PREP_CONTA (
    PRPLANOONLINE integer,
    PRREF integer,
    PRCONTA integer)
returns (
    BDCLASSIFICACAO varchar(100),
    BDCONTADEBPROV integer,
    BDCONTACREDPROV integer,
    BDDESCRICAO varchar(100),
    BDCODVER integer,
    BDCHAVE integer)
as
declare variable WSQL varchar(32000);
declare variable WCLASSIFICACAO varchar(100);
declare variable WCLASSIFICACAOANT varchar(100);
declare variable WCODIGOVERBA integer;
declare variable WCHAVE integer;
declare variable WCONTAPREPD integer;
declare variable WCONTAPREPC integer;
declare variable wdescricao varchar(100);
declare variable WWHERE varchar(32000);
begin
  execute procedure SP_SETA_COMPETENCIA(PRREF, null, null);

  WSQL = 'select BDCLASSIFICACAO, bdcontadebprov, bdcontacredprov, BDCODVER, BDCHAVE, BDDESCRICAO from SP_TREEVIEW_CONS_CONF_ONLINE';
  WSQL = WSQL || '(' || :PRPLANOONLINE || ', ''02'', null,' || :PRREF || ' , null, 1, '''','''', 1, 1, 0)';

  WWHERE = '';
  for execute statement WSQL into
    :wClassificacao,
    :wContaPrepD,
    :wContaPrepC,
    :WCODIGOVERBA,
    :WCHAVE,
    :wdescricao
  do
  begin

    if ((:WCONTAPREPD = PRCONTA) or (:WCONTAPREPC = PRCONTA)) then
    begin

      if (WWHERE = '') then
        WWHERE = ' WHERE BDCLASSIFICACAO starting with ''' || :WCLASSIFICACAO || '''';

      if (character_length(substring(WCLASSIFICACAO from 1 for character_length(WCLASSIFICACAOANT))) <> character_length(WCLASSIFICACAOANT)) then
        WWHERE = WWHERE || ' or BDCLASSIFICACAO starting with ''' || :WCLASSIFICACAO || '''';
      WCLASSIFICACAOANT = :WCLASSIFICACAO;
    end

  end

  WSQL = WSQL || WWHERE;

  for execute statement WSQL into
    BDCLASSIFICACAO,
    BDCONTADEBPROV,
    BDCONTACREDPROV,
    BDCODVER,
    BDCHAVE,
    bddescricao
  do
    begin
    suspend;
  end
end
^

/* Restore proc. body: SP_TREEVIEW_CONS_FORM_PAD_EF */
CREATE OR ALTER PROCEDURE SP_TREEVIEW_CONS_FORM_PAD_EF (
    PRPLANO INTEGER,
    PRCLASSQUADRO VARCHAR(10),
    PRGRUPO INTEGER,
    PRTPIMP VARCHAR(10))
RETURNS (
    BDCODPLANO INTEGER,
    BDDESCPLANO VARCHAR(150),
    BDNUMITEM INTEGER,
    BDDESCFORM VARCHAR(150),
    BDFORMULA VARCHAR(10000),
    BDCODQUADRO INTEGER,
    BDDESCQUADRO VARCHAR(150),
    BDCLASSIFICACAO VARCHAR(10),
    BDCODITEMONLINE INTEGER,
    BDDESCCODITEMONLINE VARCHAR(200))
AS
DECLARE VARIABLE WGROUPBY VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE WWHERE VARCHAR(10000);
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WCODQ INTEGER;
DECLARE VARIABLE WITEM INTEGER;
DECLARE VARIABLE WDESC VARCHAR(150);
DECLARE VARIABLE WCLAS VARCHAR(10);
DECLARE VARIABLE WFORM VARCHAR(10000);
DECLARE VARIABLE WAUX INTEGER;
DECLARE VARIABLE WDESCQT VARCHAR(150);
DECLARE VARIABLE WCLASQT VARCHAR(10);
DECLARE VARIABLE WCLASQTANT VARCHAR(10);
DECLARE VARIABLE WCODITEMONLINE INTEGER;
DECLARE VARIABLE WDESCCODITEMONLINE VARCHAR(200);
DECLARE VARIABLE WCAMPOQUADRO VARCHAR(20);
DECLARE VARIABLE WCAMPODESC VARCHAR(20);
DECLARE VARIABLE WCAMPODESCFORM VARCHAR(20);
DECLARE VARIABLE WCAMPOFORMULA VARCHAR(20);
BEGIN
  WCAMPOQUADRO = 'BDCODQ'||prtpimp;
  IF (UPPER(prTPIMP) IN ('GIAST')) THEN  
    WCAMPOQUADRO = 'BDCODQUADRO';

  WCAMPODESC = 'bddesc'||:prtpimp;
  IF (UPPER(prTPIMP) IN ('GIAST')) THEN  
    WCAMPODESC = 'BDDESCRICAO';

  WCAMPODESCFORM = 'BDDESCFORM'||prtpimp;
  IF (UPPER(prTPIMP) IN ('GIAST')) THEN  
    WCAMPODESCFORM = 'BDDESCFORM';

  WCAMPOFORMULA = 'BDFORMULA'||prtpimp;
  IF (UPPER(prTPIMP) IN ('GIAST')) THEN  
    WCAMPOFORMULA = 'BDFORMULA';

  IF (prgrupo = 1) THEN
     BEGIN
       wSql = 'select conf.bdcodconf'||:prtpimp||' BDCODPLANO, ';
       wSql = wSql || 'conf.'||:WCAMPODESC||' BDDESCPLANO ';
     END
  ELSE
  IF (prgrupo = 2) THEN
     BEGIN
       wSql = 'select qd.bdclassificacao, ';
       wSql = wSql || ' QD.BDDESCQ'||prtpimp||' BDDESCQUADRO ';
     END
  ELSE
  IF (prgrupo = 3) THEN
     BEGIN
       wSql = 'select conff.BDNUMITEM, conff.'||WCAMPODESCFORM||' BDDESCFORM, conff.'||WCAMPOFORMULA||' BDFORMULA, ';
       wSql = wSql || ' QD.BDDESCQ'||prtpimp||' BDDESCQUADRO ,CONFF.'||WCAMPOQUADRO||' BDCODQUADRO ,QD.BDCLASSIFICACAO, ';
       IF (not Upper(prTPIMP) in ('BLOCOP','DAMEF','DASN','DOT','DFC', 'DECLANRJ')) THEN  -- #94432 - Dava erro em algumas telas
         wSql = wSql || 'conff.bdCODITEMONLINE, itemOnline.bdDESCRICAO AS bdDESCCODITEMONLINE ';
       ELSE
         wSql = wSql || 'NULL AS bdCODITEMONLINE, NULL AS bdDESCCODITEMONLINE ';
     END

  wwhere = '';

  IF (prgrupo = 2) THEN
    BEGIN
      wsql = wsql || ' from VEF_BASE_TCONF'||prtpimp||'Q qd  ';

      IF ((prPlano IS NOT NULL) AND (prtpimp = 'DACON')) THEN
         wwhere = wWhere||' qd.bdcodconf'||:prtpimp||' = '||prPlano||' OR  qd.bdcodconf'||:prtpimp||' IS NULL';

      IF (wwhere <> '') THEN
          wwhere = 'where '||wwhere||' ';

    END
  ELSE
    BEGIN
      wsql = wsql || ' from VEF_BASE_TCONF'||prtpimp||'FORM conff ';
      wsql = wsql || ' left outer join  vef_BASE_tconf'||prtpimp||' conf on( conf.bdcodconf'||:prtpimp||' = conff.bdcodconf'||:prtpimp|| ')';
      wsql = wsql || ' left outer join VEF_BASE_TCONF'||prtpimp||'Q QD on(conff.'||WCAMPOQUADRO||' = qd.bdcodQ'||prtpimp||')';
      IF (not Upper(prTPIMP) in ('BLOCOP','DAMEF','DASN','DOT','DFC', 'DECLANRJ')) THEN  -- #94432 - Dava erro em algumas telas
        wSql = wSql || 'LEFT OUTER JOIN TITEMCONFIGONLINE itemOnline ON (itemOnline.bdCODITEMONLINE = conff.bdCODITEMONLINE) ';

      IF (prPlano IS NOT NULL) THEN
         wwhere = wWhere||' conff.bdcodconf'||:prtpimp||' = '||prPlano||' ';
    
      IF ((PRCLASSQUADRO IS NOT NULL) AND (PRCLASSQUADRO <> '')) THEN
         BEGIN
            IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
            waux = CHARACTER_LENGTH(TRIM(prclassquadro));
            wWhere = wwhere||' substring(QD.BDCLASSIFICACAO from 1 for '||waux||') = '''||PRCLASSQUADRO||''' ';
         END
    
    
      IF (wwhere <> '') THEN
          wwhere = 'where '||wwhere||' ';
    
    END
  IF (prgrupo = 1) THEN
     BEGIN
       wgroupby = ' group by conf.bdcodconf'||:prtpimp||', conf.'||WCAMPODESC;
       worderby = ' order by conf.bdcodconf'||:prtpimp||' ';
      END
  ELSE
  IF (prgrupo = 2) THEN
     BEGIN
       wgroupby = '';
       worderby = ' order by qd.bdclassificacao ';
      END
  ELSE
  IF (prgrupo = 3) THEN
     BEGIN
       wgroupby = '';
       worderby = ' order by  conff.'||WCAMPOQUADRO||', conff.BDNUMITEM ';
      END

  wsql = wsql||wwhere||wgroupby||worderby;

  IF (prgrupo = 1) THEN
     BEGIN
        FOR EXECUTE STATEMENT wsql
          INTO
            :BDCODPLANO,
            :BDDESCPLANO
          DO
          SUSPEND;
    END
  ELSE
  IF (prgrupo = 2) THEN
     BEGIN
        FOR EXECUTE STATEMENT wsql
          INTO
            :bdclassificacao,
            :BDDESCQUADRO
          DO
          BEGIN
            SELECT FIRST 1 tpos.pos FROM pos('.',:bdclassificacao) tpos INTO :waux;
            IF (waux = 0) THEN
              BEGIN
                SUSPEND;
              END
          END
    END
  ELSE
  IF (prgrupo = 3) THEN
     BEGIN
       wCodQ = 0;
       wclasqtANT = '';
        FOR EXECUTE STATEMENT wsql
          INTO
            :BDNUMITEM,
            :BDDESCFORM,
            :BDFORMULA,
            :BDDESCQUADRO,
            :BDCODQUADRO,
            :bdCLASSIFICACAO,
            :bdCODITEMONLINE,
            :bdDESCCODITEMONLINE
          DO
          BEGIN
            wItem = BDNUMITEM;
            wDesc = BDDESCFORM;
            wForm = BDFORMULA;
            wclas = bdclassificacao;
            wCODITEMONLINE     = bdCODITEMONLINE;
            wDESCCODITEMONLINE = bdDESCCODITEMONLINE;

            IF (wCodQ <> BDCODQUADRO) THEN
              BEGIN
                SELECT FIRST 1 tpos.pos FROM pos('.',:bdclassificacao) tpos INTO :waux;
                IF (waux > 0) THEN
                  BEGIN
                    WAUX = WAUX -1;
--                    wdescqt = '';
                    wsql = 'select qd.bddescQ'||prtpimp||',qd.bdclassificacao from VEF_BASE_TCONF'||prtpimp||'Q qd ';
                    wsql = wsql||'where (bdclassificacao = substring('||''''||:bdclassificacao||''''||' from 1 for '||waux||'))';
                    IF (PRTPIMP = 'DACON') THEN
                       wsql = wsql||' and (qd.bdcodconf'||:prtpimp||' = '||prPlano||' OR  qd.bdcodconf'||:prtpimp||' IS NULL) ';

                    EXECUTE STATEMENT wsql INTO :wdescqt,wclasqt;
                    IF (wclasqtANT <> wclasqt) THEN
                      BEGIN
                        wclasqtANT = wclasqt;
                        bddescform = wdescqt;
                        bdnumitem = NULL;
                        bdformula = NULL;
                        bdclassificacao = wclasqt;
                        bdCODITEMONLINE     = NULL;
                        bdDESCCODITEMONLINE = NULL;
                        SUSPEND;
                      END
                  END

                bdclassificacao = wclas;
                wcodq = BDCODQUADRO;
                bddescform = BDDESCQUADRO;
                bdnumitem = NULL;
                bdformula = NULL;
                bdCODITEMONLINE     = NULL;
                bdDESCCODITEMONLINE = NULL;
                SUSPEND;
              END

            BDNUMITEM  = wItem;
            BDDESCFORM = wDesc;
            BDFORMULA  = wForm;
            bdCODITEMONLINE     = wCODITEMONLINE;
            bdDESCCODITEMONLINE = wDESCCODITEMONLINE;
            SUSPEND;
          END
    END

END^

/* Restore proc. body: SP_TREEVIEW_CONS_GIA_FORMULA */
ALTER PROCEDURE SP_TREEVIEW_CONS_GIA_FORMULA (
    PRPLANO INTEGER,
    PRCLASSQUADRO VARCHAR(10),
    PRGRUPO INTEGER,
    PRUF VARCHAR(2))
RETURNS (
    BDCODPLANO INTEGER,
    BDDESCPLANO VARCHAR(100),
    BDNUMITEM VARCHAR(5), --integer
    BDDESCFORM VARCHAR(100),
    BDFORMULA VARCHAR(10000),
    BDCODQUADRO INTEGER,
    BDDESCQUADRO VARCHAR(100),
    BDCLASSIFICACAO VARCHAR(11),
    BDCODITEMONLINE INTEGER,
    BDDESCCODITEMONLINE VARCHAR(300))
AS
DECLARE VARIABLE WGROUPBY VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE WWHERE VARCHAR(10000);
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WCAMPOCODCONF VARCHAR(10);
DECLARE VARIABLE WCAMPOQUADRO VARCHAR(10);
DECLARE VARIABLE WCAMPOTABELA VARCHAR(10);
DECLARE VARIABLE WCAMPOTABELAFOR VARCHAR(10);
DECLARE VARIABLE WCAMPODESCFORM VARCHAR(10);
DECLARE VARIABLE WCODQ INTEGER;
DECLARE VARIABLE WITEM VARCHAR(5); --integer
DECLARE VARIABLE WDESC VARCHAR(100);
DECLARE VARIABLE WCLAS VARCHAR(11);
DECLARE VARIABLE WFORM VARCHAR(10000);
DECLARE VARIABLE WAUX INTEGER;
DECLARE VARIABLE WDESCQT VARCHAR(100);
DECLARE VARIABLE WCLASQT VARCHAR(10);
DECLARE VARIABLE WCLASQTANT VARCHAR(10);
DECLARE VARIABLE WCODITEMONLINE INTEGER;
DECLARE VARIABLE WDESCRICAOITEM VARCHAR(300);
BEGIN
  IF (prUf = 'SC') THEN
    BEGIN
      wcampocodconf = 'DIMESC';
      wcampoquadro  = 'QDIME';
      wcampotabela  = 'dimesc';
      wcampotabelafor = 'DIME';
      wcampodescform = 'DIME';
    END
  ELSE
    BEGIN
      wcampocodconf = '';
      wcampoquadro  = 'QUADRO';
      wcampotabela  = 'GIA'||pruf;
      wcampotabelafor = 'GIA'||pruf;
      wcampodescform = '';
    END

  IF (prgrupo = 1) THEN
     BEGIN
       wSql = 'select conf.bdcodconf'||:wcampocodconf||' BDCODPLANO, ';
       wSql = wSql || 'conf.bddescconf BDDESCPLANO ';
     END
  ELSE
  IF (prgrupo = 2) THEN
     BEGIN
       wSql = 'select qd.bdclassificacao, ';
       wSql = wSql || ' QD.BDDESC'||wcampoquadro||' BDDESCQUADRO ';
     END
  ELSE
  IF (prgrupo = 3) THEN
     BEGIN
       wSql = 'select conff.BDNUMITEM, conff.BDDESCFORM'||wcampodescform||' BDDESCFORM, conff.BDFORMULA'||wcampodescform||' BDFORMULA, ';
       wSql = wSql || ' QD.BDDESC'||wcampoquadro||' BDDESCQUADRO ,CONFF.BDCOD'||wcampoquadro||' BDCODQUADRO ,QD.BDCLASSIFICACAO, conff.BDCODITEMONLINE, i.bddescricao AS bdDESCCODITEMONLINE ';
     END

  wwhere = '';

  IF (prgrupo = 2) THEN
    BEGIN
--      wsql = wsql || ' qd.bddesc'||wcampoquadro||',qd.bdclassificacao from VEF_ESTADOS_TCONF'||wcampotabelafor||'Q qd where bdclassificacao = substring('||:bdclassificacao||' from 1 for '||waux||')';
      wsql = wsql || ' from VEF_ESTADOS_TCONF'||wcampotabelafor||'Q qd  ';
    END
  ELSE
    BEGIN
      wsql = wsql || ' from VEF_ESTADOS_TCONF'||wcampotabelafor||'FORM conff ';
      wsql = wsql || ' left outer join  vef_estados_tconf'||wcampotabela||' conf on( conf.bdcodconf'||:wcampocodconf||' = conff.bdcodconf'||:wcampocodconf|| ')';
      wsql = wsql || ' left outer join VEF_ESTADOS_TCONF'||wcampotabelafor||'Q QD on(conff.bdcod'||wcampoquadro||' = qd.bdcod'||wcampoquadro||')';

      wsql = wsql || ' left outer join titemconfigonline i on(i.bdcoditemonline = conff.bdcoditemonline)';



      IF (prPlano IS NOT NULL) THEN
         wwhere = wWhere||' conff.bdcodconf'||:wcampocodconf||' = '||prPlano||' ';
    
      IF ((PRCLASSQUADRO IS NOT NULL) AND (PRCLASSQUADRO <> '')) THEN
         BEGIN
            IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
            waux = CHARACTER_LENGTH(TRIM(prclassquadro));
            IF (prUf = 'MG') THEN
               BEGIN
                  waux = waux + 1;
                  wWhere = wwhere||' substring(QD.BDCLASSIFICACAO from 1 for '||waux||') = '''||PRCLASSQUADRO||'.'' ';--Caso quadro fosse VI, retornava VII e também VIII
                  waux = waux - 1;
               END
            ELSE
               wWhere = wwhere||' substring(QD.BDCLASSIFICACAO from 1 for '||waux||') = '||PRCLASSQUADRO||' ';
         END
    
    
      IF (wwhere <> '') THEN
          wwhere = 'where '||wwhere||' ';
    
    END
  IF (prgrupo = 1) THEN
     BEGIN
       wgroupby = ' group by conf.bdcodconf'||:wcampocodconf||', conf.bddescconf ';
       worderby = ' order by conf.bdcodconf'||:wcampocodconf||' ';
      END
  ELSE
  IF (prgrupo = 2) THEN
     BEGIN
       wgroupby = '';
       worderby = ' order by qd.bdclassificacao ';
--       wgroupby = ' group by CONFF.BDCOD'||wcampoquadro||' , QD.BDDESC'||wcampoquadro||'  ';
--       worderby = ' order by CONFF.BDCOD'||wcampoquadro||' ';
      END
  ELSE
  IF (prgrupo = 3) THEN
     BEGIN
       wgroupby = '';
--       worderby = ' order by  conff.BDCOD'||wcampoquadro||', conff.BDNUMITEM ';
       worderby = ' order by qd.bdclassificacao, conff.BDNUMITEM '; 
      END

  wsql = wsql||wwhere||wgroupby||worderby;

  IF (prgrupo = 1) THEN
     BEGIN
        FOR EXECUTE STATEMENT wsql
          INTO
            :BDCODPLANO,
            :BDDESCPLANO
          DO
          SUSPEND;
    END
  ELSE
  IF (prgrupo = 2) THEN
     BEGIN
        FOR EXECUTE STATEMENT wsql
          INTO
            :bdclassificacao,
            :BDDESCQUADRO
          DO
          BEGIN
            SELECT FIRST 1 tpos.pos FROM pos('.',:bdclassificacao) tpos INTO :waux;
            IF (waux = 0) THEN
              BEGIN
                SUSPEND;
              END
          END
    END
  ELSE
  IF (prgrupo = 3) THEN
     BEGIN
       wCodQ = 0;
       wclasqtANT = '';
        FOR EXECUTE STATEMENT wsql
          INTO
            :BDNUMITEM,
            :BDDESCFORM,
            :BDFORMULA,
            :BDDESCQUADRO,
            :BDCODQUADRO,
            :bdclassificacao,
            :BDCODITEMONLINE,
            :BDDESCCODITEMONLINE
          DO
          BEGIN
            wItem = BDNUMITEM;
            wDesc = BDDESCFORM;
            wForm = BDFORMULA;
            wclas = bdclassificacao;

            IF (wCodQ <> BDCODQUADRO) THEN
              BEGIN
                SELECT FIRST 1 tpos.pos FROM pos('.',:bdclassificacao) tpos INTO :waux;
                IF (waux > 0) THEN
                  BEGIN
                    WAUX = WAUX -1;
--                    wdescqt = '';
                    wsql = 'select qd.bddesc'||wcampoquadro||',qd.bdclassificacao from VEF_ESTADOS_TCONF'||wcampotabelafor||'Q qd where bdclassificacao = substring('||''''||:bdclassificacao||''''||' from 1 for '||waux||')';
                    EXECUTE STATEMENT wsql INTO :wdescqt,wclasqt;
                    IF (wclasqtANT <> wclasqt) THEN
                      BEGIN
                        wclasqtANT = wclasqt;
                        bddescform = wclasqt || ' - ' || wdescqt;
                        bdnumitem = NULL;
                        bdformula = NULL;
                        WCODITEMONLINE = BDCODITEMONLINE;
                        WDESCRICAOITEM = BDDESCCODITEMONLINE;

                        BDCODITEMONLINE = NULL;
                        BDDESCCODITEMONLINE = NULL;
                        bdclassificacao = wclasqt;
                        SUSPEND;
                        BDCODITEMONLINE = WCODITEMONLINE;
                        BDDESCCODITEMONLINE = WDESCRICAOITEM;
                      END
                  END

                bdclassificacao = wclas;
                wcodq = BDCODQUADRO;
                bddescform = bdclassificacao || ' - ' || BDDESCQUADRO;
                bdnumitem = NULL;
                bdformula = NULL;
                WCODITEMONLINE = BDCODITEMONLINE;
                WDESCRICAOITEM = BDDESCCODITEMONLINE;
                BDCODITEMONLINE = NULL;
                BDDESCCODITEMONLINE = NULL;
                SUSPEND;
                BDCODITEMONLINE = WCODITEMONLINE;
                BDDESCCODITEMONLINE = WDESCRICAOITEM;
              END

            BDNUMITEM  = wItem;
            BDDESCFORM = wDesc;
            BDFORMULA  = wForm;
--            bdclassificacao = wclas;

            SUSPEND;
          END
    END

END
^

/* Restore proc. body: SP_TREEVIEW_CONS_IMP_EMITIDOS */
CREATE OR ALTER PROCEDURE SP_TREEVIEW_CONS_IMP_EMITIDOS (
    PRONLINE VARCHAR(10000),
    PRCODEMP VARCHAR(10000),
    PRCODIMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER,
    PRREFATUAL INTEGER,
    PRGRUPO INTEGER,
    PRDTVCTOINI DATE,
    PRDTVCTOFIM DATE,
    PRPERIODO INTEGER,
    PRFILTRO INTEGER,
    PRSICALCIC varchar(5))
RETURNS (
    BDVLRPGTO DM_NUMERIC_15_2,
    BDCODMATRIZ INTEGER,
    BDTIPOLANC INTEGER,
    BDNRDOCPGTO VARCHAR(18),
    BDCODEMP INTEGER,
    BDCHAVEDARF INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP VARCHAR(18),
    BDCODIMP INTEGER,
    BDDESCIMP VARCHAR(200),
    BDCODPERIODO INTEGER,
    BDORDEM INTEGER,
    BDREFERENCIA INTEGER,
    BDQUOTA INTEGER,
    BDCODTPCC INTEGER,
    BDDATAVCTO DATE,
    BDVALOR NUMERIC(15,6),
    BDMULTA NUMERIC(15,6),
    BDJUROS NUMERIC(15,6),
    BDTOTAL NUMERIC(15,6),
    BDOBS BLOB SUB_TYPE 1 SEGMENT SIZE 80,
    BDORDEMCOMPL INTEGER,
    BDBASEIMP NUMERIC(15,6),
    BDALIQIMP NUMERIC(15,6),
    BDVLRIMPORIGINAL NUMERIC(15,6),
    BDVLRMULTAJUROS NUMERIC(15,6),
    BDVLROUTENTIDADE NUMERIC(15,6),
    BDDTPGTO DATE,
    BDLIMITEISENCAO NUMERIC(15,6),
    BDDOCARRECADACAO INTEGER,
    BDFORMREL VARCHAR(1000),
    BDCODREC INTEGER,
    BDVLRRETENCAO NUMERIC(15,2),
    BDDESCTIPOCALC VARCHAR(25),
    BDFLAG VARCHAR(5),
    BDVLRACUMULO NUMERIC(15,6),
    BDCNPJDARF VARCHAR(18),
    BDCODEMPSCP INTEGER,
    BDCOMPENSACAODCOMP DM_NUMERIC_15_2,
    BDESFERA INTEGER,
    BDSTATUSPARCELA INTEGER)
AS
DECLARE VARIABLE WGROUPBY VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(10000);
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WEXISTS VARCHAR(1000);
DECLARE VARIABLE WTIPOIMPDOC INTEGER;
DECLARE VARIABLE WCODDOCARREC INTEGER;
DECLARE VARIABLE WTIPOIMPOSTO INTEGER;
DECLARE VARIABLE WTIPOCALC INTEGER;
DECLARE VARIABLE WVLRPGTO NUMERIC(15,6);
DECLARE VARIABLE WTOTAL NUMERIC(15,6);
DECLARE VARIABLE WVALOR NUMERIC(15,6);
DECLARE VARIABLE WVLRMULTAJUROS NUMERIC(15,6);
DECLARE VARIABLE WIMPEMPZERO INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMEMP DM_BDNOMEMP;
DECLARE VARIABLE WPOS INTEGER;
begin
  execute procedure SP_SETA_COMPETENCIA(PRREFATUAL, null, null);

  /*agrupar por empresa*/
  if (PRGRUPO = 1) then
  begin
    WSQL = 'select DARF.BDCODEMP, ';
    WSQL = WSQL || 'emp.BDNOMEMP ';
  end
  else


  /*agrupar por REFERÊNCIA*/
  if (PRGRUPO = 2) then
  begin
    WSQL = 'select DARF.BDREFERENCIA ';
  end
  else


  /*agrupar por IMPOSTO*/
  if (PRGRUPO = 3) then
  begin
    WSQL = 'select DARF.BDCODIMP,IMP.BDDESCIMP ';
  end
  else
  begin
    WSQL = 'select DARF.BDCODEMP, ';
    WSQL = WSQL || 'EMP.BDNOMEMP, ';
    WSQL = WSQL || 'EMP.BDCNPJEMP, ';
    WSQL = WSQL || 'DARF.BDCODIMP, ';
    WSQL = WSQL || 'DARF.BDCODTPCC, ';
    WSQL = WSQL || 'IMP.BDDESCIMP, ';
    WSQL = WSQL || 'DARF.BDCODPERIODO, ';
    WSQL = WSQL || 'DARF.BDREFERENCIA, ';
    WSQL = WSQL || 'DARF.BDQUOTA, ';
    WSQL = WSQL || 'DARF.BDDATAVCTO , ';
    --        wSql = wSql || 'PGTO.bddatapgto , ';
    WSQL = WSQL || 'DARF.BDBASEIMP , ';
    WSQL = WSQL || 'DARF.BDALIQIMP , ';
    WSQL = WSQL || 'DARF.BDVLRIMPORIGINAL , ';
    WSQL = WSQL || 'DARF.BDVALOR , ';
    WSQL = WSQL || 'DARF.BDMULTA , ';
    WSQL = WSQL || 'DARF.BDJUROS , ';
    WSQL = WSQL || 'DARF.BDTOTAL , ';
    WSQL = WSQL || 'DARF.BDOBS , ';
    WSQL = WSQL || 'DARF.BDORDEMCOMPL , ';
    WSQL = WSQL || 'DARF.BDVLRMULTAJUROS , ';
    WSQL = WSQL || 'DARF.BDVLROUTENTIDADE, ';
    WSQL = WSQL || 'DARF.BDORDEM, ';
    WSQL = WSQL || 'DARF.BDCHAVEDARF, ';
    WSQL = WSQL || 'IMP.BDLIMITEISENCAO, ';
    WSQL = WSQL || 'IMP.BDDOCARRECADACAO, ';
    WSQL = WSQL || 'DocArr.BDFORMREL, ';
    WSQL = WSQL || 'DARF.BDCODREC, ';
    WSQL = WSQL || 'DARF.BDVLRRETENCAO, ';
    WSQL = WSQL || 'IMP.BDTIPOIMPDOC, ';
    WSQL = WSQL || 'DocArr.BDCODDOCARREC, ';
    WSQL = WSQL || 'DARF.BDTIPOIMPOSTO, ';
    WSQL = WSQL || 'DARF.BDTIPOCALC, ';
    WSQL = WSQL || 'DARF.BDVLRACUMULO, ';
    WSQL = WSQL || 'emp.BDCODMATRIZ, ';
    WSQL = WSQL || 'DARF.BDCNPJDARF,  ';
    WSQL = WSQL || 'DARF.BDCODEMPSCP, ';
    wSQL = wSQL || 'IMP.BDCOMPETENCIA AS BDESFERA,';
    wSQL = wSQL || 'DARF.BDSTATUSPARCELA ';

    --left outer join sp _consultaempresas(201010, DARF.bdcodemp, null) emp on (emp.bdcodemp = DARF.bdcodemp )
    --LEFT OUTER JOIN timposto IMP ON (IMP.BDCODIMP = DARF.bdcodimp)
    --left outer join tdarfgerpgto PGTO on (PGTO.bdcodemp = DARF.bdcodemp and PGTO.BDCODIMP = DARF.BDCODIMP AND PGTO.bdcodperiodo = DARF.bdcodperiodo AND PGTO.bdreferencia = DARF.bdreferencia AND PGTO.bdordem = DARF.bdordem AND PGTO.bdquota = DARF.bdquota)
    --LEFT OUTER join TTIPOSPERIODO PER on (PER.bdcodperiodo = DARF.bdcodperiodo)
    --where DARF.BDREFERENCIA >= 201001  and DARF.BDREFERENCIA <= 201012
    --AND DARF.bdcodperiodo = 7
    --AND DARF.bddatavcto BETWEEN '03/01/2010' AND '03/31/2010'
    --AND PGTO.bddatapgto BETWEEN '03/01/2010' AND '03/31/2010'
    --order by DARF.bdcodemp, DARF.BDCODIMP, DARF.bdreferencia

  end

  WWHERE = '';

  WSQL = WSQL || 'from (SELECT * ';
  WSQL = WSQL ||      ' FROM TDARFPADRAO darf ';

  if (PRCODEMP is not null) then
    WWHERE = WWHERE || PRCODEMP || ' ';

  if ((PRCODIMP is not null) or (PRCODIMP > 0)) then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';
    WWHERE = WWHERE || PRCODIMP || ' ';
  end

  if ((PRREFINI is not null) and (PRREFINI > 0)) then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';
       /*Elizeu - 01/08/2013 - sol 4886 - imposto semanal*/
    if (PRPERIODO <> 1) then
      WWHERE = WWHERE || 'DARF.BDREFERENCIA >= ' || PRREFINI || ' ';
    else
      WWHERE = WWHERE || ' cast(substring(cast(DARF.BDREFERENCIA as varchar(8)) from 1 for 6) as integer) >= ' || PRREFINI || ' ';
    end

  if ((PRREFFIN is not null) and (PRREFFIN > 0)) then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';
  
       /*Elizeu - 01/08/2013 - sol 4886 - imposto semanal*/
    if (PRPERIODO <> 1) then
      WWHERE = WWHERE || 'DARF.BDREFERENCIA <= ' || PRREFFIN || ' ';
    else
      WWHERE = WWHERE || ' cast(substring(cast(DARF.BDREFERENCIA as varchar(8)) from 1 for 6) as integer) <= ' || PRREFFIN || ' ';
    end
    
  if (UPPER(PRSICALCIC) = 'TRUE') then
    WWHERE = WWHERE || 'AND (DARF.BDCODREC NOT IN(''2985'', ''2991'', ''561'', ''588'', ''8301'') OR DARF.BDCODREC IS NULL) '; /*#213811 - Matheus Fritzen - Esses caras não podem ser mandados pro SICALC pelo Integra Contador */    

  if ((PRPERIODO is not null) and (PRPERIODO > 0)) then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';
  
    WWHERE = WWHERE || 'DARF.bdcodperiodo = ' || PRPERIODO || ' ';
  end

  if (PRDTVCTOINI is not null) then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';
  
    WWHERE = WWHERE || 'DARF.bddatavcto >= ' || '''' || PRDTVCTOINI || '''';
  end

  if (PRDTVCTOFIM is not null) then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';
  
    WWHERE = WWHERE || 'DARF.bddatavcto <= ' || '''' || PRDTVCTOFIM || '''';
  end

  if (WWHERE <> '') then
    WSQL = WSQL || 'where ' || WWHERE || ' ';

  WSQL = WSQL ||      ' ) DARF ';
  WSQL = WSQL || 'LEFT OUTER JOIN TIMPOSTO IMP ON (IMP.BDCODIMP = DARF.BDCODIMP) ';
  WSQL = WSQL || 'LEFT OUTER JOIN VW_EMPRESAS_REF_ATUAL EMP ON (EMP.BDCODEMP = DARF.BDCODEMP) ';
  WSQL = WSQL || 'LEFT OUTER JOIN TDOCARRECADACAO DOCARR ON (IMP.BDDOCARRECADACAO = DOCARR.BDCODDOCARREC) ';
  
  IF (UPPER(PRSICALCIC) = 'TRUE') THEN --#213811 - Só pode mandar DARFs para o integra contador, no recurso de transmissão do SICALC
    BEGIN
      WSQL = WSQL || 'WHERE DOCARR.BDCODDOCARREC = 1 ';
    END

  --  wsql = wsql||'left outer join SP_CONSULTAEMPRESAS('|| prrefatual || ', DARF.bdcodemp, null) emp on (emp.bdcodemp = DARF.bdcodemp ) ' ;
  --  wsql = wsql||'LEFT OUTER JOIN timposto IMP ON (IMP.BDCODIMP = DARF.bdcodimp) ' ;
  --  wsql = wsql||'left outer join tdarfgerpgto PGTO on (PGTO.bdcodemp = DARF.bdcodemp and PGTO.BDCODIMP = DARF.BDCODIMP AND PGTO.bdcodperiodo = DARF.bdcodperiodo AND PGTO.bdreferencia = DARF.bdreferencia AND PGTO.bdordem = DARF.bdordem AND PGTO.bdquota = DARF.bdquota) ' ;

  --  if (prgrupo is not null) then
  --     wsql = wSql||'left outer join tdarfgerpgto PGTO on (PGTO.bdcodemp = emp.bdcodemp and PGTO.BDCODIMP = DARF.BDCODIMP) ';

  WWHERE = '';

  if ((PRONLINE is not null)) then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';
    WWHERE = WWHERE || PRONLINE || ' ';
  end

  /*
  if (prdtpgtoini is not null) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||'PGTO.bddatapgto >= '||''''||prdtpgtoini||'''';
     end

  if (prdtpgtofim is not null) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||'PGTO.bddatapgto <= '||''''||prdtpgtofim||'''';
     end
*/
  WEXISTS = '';

  if ((PRFILTRO is not null) and
      (PRFILTRO <> 0) and
      (PRFILTRO <> 1234)) then
  begin
    WEXISTS = ' exists ( ' || ' select baixa.bdcodemp,baixa.bdchavedarf ' || ' from tdarfpadrao baixa ' || ' left outer join (select pgto.bdcodemp,pgto.bdchavedarf,max(pgto.bddatapgto) bddatapgto ,sum(pgto.bdvlrpgto) bdvlrpgto from tdarfgerpgto pgto ' || '                  group by pgto.bdcodemp,pgto.bdchavedarf ) pgto on (PGTO.bdcodemp = baixa.bdcodemp and PGTO.BDCHAVEDARF = baixa.bdchavedarf) ' || ' where (';

       /* prFiltro
         1 = sem baixa
         2 = baixa parcial
         3 = baixa integral
         4 = Acumulada
         12 = sem baixa/baixa parcial
         13 = sem baixa/baixa integral
         14 = sem baixa/acumula
         23 = baixa parcial/baixa integral
         24 = baixa parcial/acumulada
         34 = baixa integral/acumulada
         123 = sem baixa/baixa parcia/baixa total
         124 = sem baixa/baixa parcia/acumulada
         134 = sem baixa/baixa total/acumulada
         234 = baixa parcia/baixa total/acumulada
         1234 = todos (não faz o filtro)

         1,2,3,4,12,13,14,23,24,34,123,124,134,234,1234
       */
    if (PRFILTRO in (1, 12, 13, 14, 123, 124, 134)) then
    begin
      WEXISTS = WEXISTS || ' (pgto.bdvlrpgto is null) ';
    end

    if (PRFILTRO in (2, 12, 24, 123, 124, 234)) then
    begin
      if ((PRFILTRO > 2) and
          (PRFILTRO <> 24) and
          (PRFILTRO <> 234)) then
        WEXISTS = WEXISTS || ' or ';
      WEXISTS = WEXISTS || ' ((pgto.bdvlrpgto < coalesce(baixa.BDTOTAL,coalesce(baixa.BDVALOR,0)+coalesce(baixa.BDVLRMULTAJUROS,0))) and (pgto.bdvlrpgto is not null))';
    end

    if (PRFILTRO in (3, 13, 34, 123, 134, 234)) then
    begin
      if ((PRFILTRO > 3) and
          (PRFILTRO <> 34)) then
        WEXISTS = WEXISTS || ' or ';
      WEXISTS = WEXISTS || ' (pgto.bdvlrpgto >= coalesce(baixa.BDTOTAL,coalesce(baixa.BDVALOR,0)+coalesce(baixa.BDVLRMULTAJUROS,0)))';
    end

    if (PRFILTRO = 23) then
    begin
      WEXISTS = WEXISTS || ' (pgto.bdvlrpgto is not null) ';
    end

    if (PRFILTRO in (4, 14, 24, 34, 124, 134, 234)) then
    begin
      if (PRFILTRO > 4) then
        WEXISTS = WEXISTS || ' or ';
      WEXISTS = WEXISTS || ' (IMP.BDLIMITEISENCAO > coalesce(baixa.BDTOTAL,coalesce(baixa.BDVALOR,0)+coalesce(baixa.BDVLRMULTAJUROS,0)))';
      WEXISTS = WEXISTS ||  ' AND (BAIXA.BDTOTAL <= IMP.BDLIMITEISENCAO) AND (BAIXA.BDTOTAL > 0) '; --Larissa - 04/2021 - Baixa de Impostos - Filtro #147473 #147903 #147966 #148026 #148253 #148255 #148572
    end

    WEXISTS = WEXISTS || ' ) ';/* fim where sql filtro */

    if (PRFILTRO not in (4, 14, 24, 34, 124, 134, 234)) then
    begin
      WEXISTS = WEXISTS || ' and ';
      WEXISTS = WEXISTS || ' (IMP.BDLIMITEISENCAO < coalesce(baixa.BDTOTAL,coalesce(baixa.BDVALOR,0)+coalesce(baixa.BDVLRMULTAJUROS,0)))';
    end

    WEXISTS = WEXISTS || ' and  baixa.bdcodemp = darf.bdcodemp and baixa.bdchavedarf = darf.bdchavedarf) ';
  end

--Baixa de Impostos - Filtro #147473 #147903 #147966 #148026 #148253 #148255 #148572
  if (WWHERE <> '') then
    begin
      if (WEXISTS <> '') then
        WWHERE = 'where ' || WWHERE || ' ' || ' and ' || ' ( ' || WEXISTS || ' ) ';
      else
    WWHERE = 'where ' || WWHERE || ' ';
    end
  else
    begin
  if (WEXISTS <> '') then
        WWHERE = 'where ' || ' ( ' || WEXISTS || ' ) ';
    end

  if (PRGRUPO = 1) then
  begin
    WGROUPBY = 'group by DARF.bdcodemp, EMP.bdnomemp ';
    WORDERBY = 'order by DARF.bdcodemp ';
  end
  else
  if (PRGRUPO = 2) then
  begin
    WGROUPBY = 'group by DARF.BDREFERENCIA ';
    WORDERBY = 'order by DARF.BDREFERENCIA ';
  end
  else
  if (PRGRUPO = 3) then
  begin
    WGROUPBY = 'group by DARF.BDCODIMP,IMP.BDDESCIMP ';
    WORDERBY = 'order by DARF.BDCODIMP,IMP.BDDESCIMP ';
  end
  else
  begin
    WGROUPBY = '';
    WORDERBY = 'order by DARF.BDCODIMP, DARF.bdreferencia, DARF.BDORDEM, DARF.BDCODPERIODO';
  end

  WSQL = WSQL || WWHERE || WGROUPBY || WORDERBY;

  if (PRGRUPO = 1) then
  begin
    WIMPEMPZERO = 0;
    EXECUTE STATEMENT 'SELECT COUNT(AUX.BDCODEMP) FROM ('||WSQL||') AUX' INTO :WIMPEMPZERO;

    for execute statement WSQL
            into :BDCODEMP, :BDNOMEMP
    do
      begin
        -- Alt.: #137338 #135565 #135935 - Apenas quando tiver o filtrando mais de uma empresa...
--        SELECT p.POS FROM POS(',', UPPER(:prCODEMP)) p INTO :wPOS;
--        if (:wPOS = 0) then
--          SELECT p.POS FROM POS('OR', UPPER(:prCODEMP)) p INTO :wPOS;
--        if (:wPOS = 0) then
--          SELECT p.POS FROM POS('AND', UPPER(:prCODEMP)) p INTO :wPOS;

--        WIMPEMPZERO = ROW_COUNT;
--        WIMPEMPZERO = 0;

--        if ((:wPOS > 0) AND (WIMPEMPZERO = 0) AND (BDCODEMP IS NOT NULL)) then
        if (WIMPEMPZERO > 1) then
          begin -- Alt.: #137338 #135565 #135935 - Ajustes para sempre trazer no inicio da consulta um nó "TODAS EMPRESAS"...
            WCODEMP  = BDCODEMP;
            WNOMEMP  = BDNOMEMP;

            BDCODEMP = 0;
            BDNOMEMP = 'TODAS EMPRESAS';
            WIMPEMPZERO = 0;
      suspend;

            BDCODEMP  = WCODEMP;
            BDNOMEMP  = WNOMEMP;
  end
        suspend;
      end
  end
  else
  if (PRGRUPO = 2) then
  begin
    for execute statement WSQL
            into :BDREFERENCIA

    do
      suspend;
  end
  else
  if (PRGRUPO = 3) then
  begin
    for execute statement WSQL
            into :BDCODIMP, :BDDESCIMP
    do
      suspend;
  end
  else
  begin
    for execute statement WSQL
            into :BDCODEMP, :BDNOMEMP, :BDCNPJEMP, :BDCODIMP, :BDCODTPCC, :BDDESCIMP, :BDCODPERIODO, :BDREFERENCIA,
            :BDQUOTA, :BDDATAVCTO,
            --              :bddatapgto ,
            :BDBASEIMP, :BDALIQIMP, :BDVLRIMPORIGINAL, :BDVALOR, :BDMULTA, :BDJUROS, :BDTOTAL, :BDOBS, :BDORDEMCOMPL,
            :BDVLRMULTAJUROS, :BDVLROUTENTIDADE, :BDORDEM, :BDCHAVEDARF, :BDLIMITEISENCAO, :BDDOCARRECADACAO,
            :BDFORMREL, :BDCODREC, :BDVLRRETENCAO, :WTIPOIMPDOC, :WCODDOCARREC, :WTIPOIMPOSTO, :WTIPOCALC,
            :BDVLRACUMULO, :BDCODMATRIZ, :BDCNPJDARF, :BDCODEMPSCP, :BDESFERA, :BDSTATUSPARCELA
    do
    begin
      if (coalesce(WCODDOCARREC, 0) not in (1, 2) and
          BDTOTAL <= BDLIMITEISENCAO) then
        /* Darf's */
                BDVLRACUMULO = BDTOTAL;

      BDDESCTIPOCALC = null;
      select max(PGTO.BDDATAPGTO), sum(PGTO.BDVLRPGTO), max(PGTO.BDNRODOC)
      from TDARFGERPGTO PGTO
      where (PGTO.BDCODEMP = :BDCODEMP and
            PGTO.BDCHAVEDARF = :BDCHAVEDARF)
      into :BDDTPGTO, :BDVLRPGTO, :BDNRDOCPGTO;

      select first 1 BDCODTIPOLANC
      from TDARFGERPGTO PGTO
      where (PGTO.BDCODEMP = :BDCODEMP and
            PGTO.BDCHAVEDARF = :BDCHAVEDARF)
      order by PGTO.BDDATAPGTO desc
      into :BDTIPOLANC;

      --Matheus Amaral - DARF com DCOMP #140327 #144635 #144684 #146877 #147776 #Bernhoeft!
      SELECT SUM(COALESCE(PGTO.BDCOMPENSACAODCOMP, 0))
      FROM TDARFGERPGTO PGTO
      WHERE (PGTO.BDCODEMP      = :BDCODEMP AND
             PGTO.BDCHAVEDARF   = :BDCHAVEDARF AND
             PGTO.BDCOMPENSACAO = 'TRUE')
      INTO :BDCOMPENSACAODCOMP;

      IF (:BDCOMPENSACAODCOMP > 0) THEN
        BEGIN
            IF (POSITION('Imposto compensado via DCOMP', :BDOBS) = 0) THEN
            BEGIN
                --UPDATE TDARFPADRAO DARF SET DARF.BDOBS = :BDOBS || 'Imposto compensado via DCOMP'
                --WHERE DARF.BDCODEMP    = :BDCODEMP AND
                --      DARF.BDCHAVEDARF = :BDCHAVEDARF;
                BDOBS = BDOBS || 'Imposto compensado via DCOMP';
            END
        END
        ELSE
        IF (POSITION('Imposto compensado via DCOMP', :BDOBS) > 0) THEN
        BEGIN
            --UPDATE TDARFPADRAO DARF SET DARF.BDOBS = REPLACE(:BDOBS, 'Imposto compensado via DCOMP', '')
            --WHERE DARF.BDCODEMP    = :BDCODEMP AND
            --      DARF.BDCHAVEDARF = :BDCHAVEDARF;
        END

              /* Setar a flag se for uma baixa parcial - Início */
      WVLRPGTO = 0;
      WTOTAL = 0;
      WVALOR = 0;
      WVLRMULTAJUROS = 0;
      select coalesce(PGTO.BDVLRPGTO, 0), coalesce(BAIXA.BDTOTAL, 0), coalesce(BAIXA.BDVALOR, 0),
             coalesce(BAIXA.BDVLRMULTAJUROS, 0)
      /* Alt:22559 - Everton
         Alterado o trecho abaixo para ao invés de pegar direto da tabela TDARFPADRAO inteira,
         fazer um select apenas com os registros dela correspondentes ao for execute statement atual.
         Desta forma, evita leitura de registros não indexados, o que deixava o processo lento.
      */
      --FROM tdarfpadrao baixa
      from (select DARFP.BDCODEMP, DARFP.BDCHAVEDARF, DARFP.BDTOTAL, DARFP.BDVALOR, DARFP.BDVLRMULTAJUROS
            from TDARFPADRAO DARFP
            where DARFP.BDCODEMP = :BDCODEMP and
                  DARFP.BDCHAVEDARF = :BDCHAVEDARF) BAIXA
      left outer join(select PGTO.BDCODEMP, PGTO.BDCHAVEDARF, max(PGTO.BDDATAPGTO) BDDATAPGTO,
                             sum(PGTO.BDVLRPGTO) BDVLRPGTO
                      from TDARFGERPGTO PGTO
                      where (PGTO.BDVLRPGTO is not null) and
                            (PGTO.BDCODEMP = :BDCODEMP) and
                            (PGTO.BDCHAVEDARF = :BDCHAVEDARF)
                      group by PGTO.BDCODEMP, PGTO.BDCHAVEDARF) PGTO on (PGTO.BDCODEMP = BAIXA.BDCODEMP and PGTO.BDCHAVEDARF = BAIXA.BDCHAVEDARF)
      where (PGTO.BDVLRPGTO < coalesce(BAIXA.BDTOTAL, coalesce(BAIXA.BDVALOR, 0) + coalesce(BAIXA.BDVLRMULTAJUROS, 0)))

      into WVLRPGTO, WTOTAL, WVALOR, WVLRMULTAJUROS;

              BDFLAG = 'FALSE';
      if (WVLRPGTO > 0) then
      begin
        if ((WTOTAL > 0) and
            (WVLRPGTO < WTOTAL)) then
                    BDFLAG = 'TRUE';
        else
        if (WVLRPGTO < WVALOR + WVLRMULTAJUROS) then
                    BDFLAG = 'TRUE';
      end
              /* Setar a flag se for uma baixa parcial - Fim */

      --                                  tdaDARF, tdaGPS
      if (WCODDOCARREC = 12) then
      begin --         tcRHGPS_Calculo, tcRHGPS_Carne, tcRHGPS_Complementar
        if (WTIPOIMPOSTO = 0) then
                       BDDESCTIPOCALC = 'Folha normal';
        else
        if (WTIPOIMPOSTO = 1) then
                       BDDESCTIPOCALC = 'Folha complementar';
        else
        if (WTIPOIMPOSTO = 2) then
                       BDDESCTIPOCALC = '13º Salário';
        else
        if (WTIPOIMPOSTO = 3) then
                       BDDESCTIPOCALC = 'Complemento 13º salário';
        else
                       BDDESCTIPOCALC = 'Não informado';
      end
      else
      if (WCODDOCARREC = 1) then
      begin --    tcRHDarf_IRRF_Por_Calc, tcRHDarf_PIS_Por_Calc
        if (WTIPOCALC = 0) then
                       BDDESCTIPOCALC = 'Todos';
        else
        if (WTIPOCALC = 1) then
                       BDDESCTIPOCALC = 'Folha normal';
        else
        if (WTIPOCALC = 2) then
                       BDDESCTIPOCALC = 'Adiantamento salarial';
        else
        if (WTIPOCALC = 3) then
                       BDDESCTIPOCALC = 'Adiantamento 13º salário';
        else
        if (WTIPOCALC = 4) then
                       BDDESCTIPOCALC = '13 Salário';
        else
        if (WTIPOCALC = 5) then
                       BDDESCTIPOCALC = 'Complemento 13º salário';
        else
        if (WTIPOCALC = 6) then
                       BDDESCTIPOCALC = 'Férias';
        else
        if (WTIPOCALC = 7) then
                       BDDESCTIPOCALC = 'Folha avulsa';
        else
        if (WTIPOCALC = 8) then
                       BDDESCTIPOCALC = 'Folha complementar';
        else
        if (WTIPOCALC = 9) then
                       BDDESCTIPOCALC = 'Rescisão';
        else
        if (WTIPOCALC = 10) then
                       BDDESCTIPOCALC = 'Médias';
        else
                       BDDESCTIPOCALC = 'Não informado';
      end
      else


      --                                tdaGRCS_contribuição_sindical, tdaGRCS_mensalidade_sindical, tdaGRCS_contribuição_confederativa, tdaGRCS_taxa_assistencial, tdaGRCS_reversão_salárial
      if (WCODDOCARREC in (14, 15, 16, 17, 18)) then
      begin
        if (WTIPOIMPDOC in (0, 14, 15, 16, 17, 18)) then
        begin
          if (WTIPOCALC = 0) then
                           BDDESCTIPOCALC = 'Todos';
          else
          if (WTIPOCALC = 1) then
                           BDDESCTIPOCALC = 'Folha normal';
          else
          if (WTIPOCALC = 2) then
                           BDDESCTIPOCALC = 'Adiantamento salarial';
          else
          if (WTIPOCALC = 3) then
                           BDDESCTIPOCALC = 'Adiantamento 13º salário';
          else
          if (WTIPOCALC = 4) then
                           BDDESCTIPOCALC = '13 Salário';
          else
          if (WTIPOCALC = 5) then
                           BDDESCTIPOCALC = 'Complemento 13º salário';
          else
          if (WTIPOCALC = 6) then
                           BDDESCTIPOCALC = 'Férias';
          else
          if (WTIPOCALC = 7) then
                           BDDESCTIPOCALC = 'Folha avulsa';
          else
          if (WTIPOCALC = 8) then
                           BDDESCTIPOCALC = 'Folha complementar';
          else
          if (WTIPOCALC = 9) then
                           BDDESCTIPOCALC = 'Rescisão';
          else
          if (WTIPOCALC = 10) then
                           BDDESCTIPOCALC = 'Médias';
          else
                           BDDESCTIPOCALC = 'Não informado';
        end
      end
      else
      if (WCODDOCARREC = 19) then
      begin
        if (WTIPOCALC = 1) then
                       BDDESCTIPOCALC = 'Complementar';
        else
                       BDDESCTIPOCALC = 'Original';
      end

      suspend;
    end
  end
end^

/* Restore proc. body: SP_UNION_FN_FC */
ALTER PROCEDURE SP_UNION_FN_FC RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDCODVER INTEGER,
BDREFVFN NUMERIC(15,6),
BDREFAUXVFN NUMERIC(15,6),
BDVALVFN NUMERIC(15,6),
BDBFGTSFN NUMERIC(15,6),
BDFGTSFN NUMERIC(15,6),
BDFGTSCSFN NUMERIC(15,6),
BDBFGTS13FN NUMERIC(15,6),
BDFGTS13FN NUMERIC(15,6),
BDFGTS13CSFN NUMERIC(15,6),
BDMAIORREMFN NUMERIC(15,6),
BDBINSSFN NUMERIC(15,6),
BDALIQINSSFN NUMERIC(15,6),
BDINSSFN NUMERIC(15,6),
BDBIRRFFN NUMERIC(15,6),
BDALIQIRRFFN NUMERIC(15,6),
BDIRRFFN NUMERIC(15,6),
BDBINSS13FN NUMERIC(15,6),
BDALIQINSS13FN NUMERIC(15,6),
BDINSS13FN NUMERIC(15,6),
BDBIRRF13FN NUMERIC(15,6),
BDALIQIRRF13FN NUMERIC(15,6),
BDIRRF13FN NUMERIC(15,6),
BDBSALFAMFN NUMERIC(15,6),
BDSALFAMFN NUMERIC(15,6),
BDBRAISFN NUMERIC(15,6),
BDSALBASEFN NUMERIC(15,6),
BDDEPFN NUMERIC(15,6),
BDIGNREFVFN VARCHAR(5),
BDIGNREFAVFN VARCHAR(5),
BDIGNVALVFN VARCHAR(5),
BDTIPO INTEGER,
BDBFGTSFEFN NUMERIC(15,6),
BDFGTSFEFN NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(3000);
BEGIN
  /* Procedure Text */

  wsql = 'select '||
         '    BDCODEMP,'||
         '    BDCODCOL,'||
         '    BDREF,'||
         '    BDCODVER,'||
         '    BDREFV,'||
         '    BDREFAUXV,'||
         '    BDVALV,'||
         '    BDBFGTS,'||
         '    BDFGTS,'||
         '    BDFGTSCS,'||
         '    BDBFGTS13,'||
         '    BDFGTS13,'||
         '    BDFGTS13CS,'||
         '    BDMAIORREM,'||
         '    BDBINSS,'||
         '    BDALIQINSS,'||
         '    BDINSS,'||
         '    BDBIRRF,'||
         '    BDALIQIRRF,'||
         '    BDIRRF,'||
         '    BDBINSS13,'||
         '    BDALIQINSS13,'||
         '    BDINSS13,'||
         '    BDBIRRF13,'||
         '    BDALIQIRRF13,'||
         '    BDIRRF13,'||
         '    BDBSALFAM,'||
         '    BDSALFAM,'||
         '    BDBRAIS,'||
         '    BDSALBASE,'||
         '    BDDEP,'||
         '    BDIGNREFV,'||
         '    BDIGNREFAV,'||
         '    BDIGNVALV,'||
         '    BDTIPO ,'||
         '    BDBFGTSFEFN ,'||
         '    BDFGTSFEFN '||
         ' from SP_VRHF_FOLHANORMAL';

   FOR EXECUTE STATEMENT wSql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFFN,
    :BDCODVER,
    :BDREFVFN,
    :BDREFAUXVFN,
    :BDVALVFN,
    :BDBFGTSFN,
    :BDFGTSFN,
    :BDFGTSCSFN,
    :BDBFGTS13FN,
    :BDFGTS13FN,
    :BDFGTS13CSFN,
    :BDMAIORREMFN,
    :BDBINSSFN,
    :BDALIQINSSFN,
    :BDINSSFN,
    :BDBIRRFFN,
    :BDALIQIRRFFN,
    :BDIRRFFN,
    :BDBINSS13FN,
    :BDALIQINSS13FN,
    :BDINSS13FN,
    :BDBIRRF13FN,
    :BDALIQIRRF13FN,
    :BDIRRF13FN,
    :BDBSALFAMFN,
    :BDSALFAMFN,
    :BDBRAISFN,
    :BDSALBASEFN,
    :BDDEPFN,
    :BDIGNREFVFN,
    :BDIGNREFAVFN,
    :BDIGNVALVFN,
    :BDTIPO,
    :BDBFGTSFEFN,
    :BDFGTSFEFN
    DO
      SUSPEND;


  wsql = 'select '||
         '    BDCODEMP,'||
         '    BDCODCOL,'||
         '    BDREF,'||
         '    BDCODVER,'||
         '    BDREFV,'||
         '    BDREFAUXV,'||
         '    BDVALV,'||
         '    BDBFGTS,'||
         '    BDFGTS,'||
         '    BDFGTSCS,'||
         '    BDBFGTS13,'||
         '    BDFGTS13,'||
         '    BDFGTS13CS,'||
         '    BDMAIORREM,'||
         '    BDBINSS,'||
         '    BDALIQINSS,'||
         '    BDINSS,'||
         '    BDBIRRF,'||
         '    BDALIQIRRF,'||
         '    BDIRRF,'||
         '    BDBINSS13,'||
         '    BDALIQINSS13,'||
         '    BDINSS13,'||
         '    BDBIRRF13,'||
         '    BDALIQIRRF13,'||
         '    BDIRRF13,'||
         '    BDBSALFAM,'||
         '    BDSALFAM,'||
         '    BDBRAIS,'||
         '    BDSALBASE,'||
         '    BDDEP,'||
         '    BDIGNREFV,'||
         '    BDIGNREFAV,'||
         '    BDIGNVALV,'||
         '    BDTIPO ,'||
         '    bdbfgtsfefc,'||
         '    bdfgtsfefc'||
         ' from SP_VRHF_FOLHACOMPLEMENTAR';

   FOR EXECUTE STATEMENT wSql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFFN,
    :BDCODVER,
    :BDREFVFN,
    :BDREFAUXVFN,
    :BDVALVFN,
    :BDBFGTSFN,
    :BDFGTSFN,
    :BDFGTSCSFN,
    :BDBFGTS13FN,
    :BDFGTS13FN,
    :BDFGTS13CSFN,
    :BDMAIORREMFN,
    :BDBINSSFN,
    :BDALIQINSSFN,
    :BDINSSFN,
    :BDBIRRFFN,
    :BDALIQIRRFFN,
    :BDIRRFFN,
    :BDBINSS13FN,
    :BDALIQINSS13FN,
    :BDINSS13FN,
    :BDBIRRF13FN,
    :BDALIQIRRF13FN,
    :BDIRRF13FN,
    :BDBSALFAMFN,
    :BDSALFAMFN,
    :BDBRAISFN,
    :BDSALBASEFN,
    :BDDEPFN,
    :BDIGNREFVFN,
    :BDIGNREFAVFN,
    :BDIGNVALVFN,
    :BDTIPO,
    :bdbfgtsfefn,
    :bdfgtsfefn
    DO
      SUSPEND;
END
^

/* Restore proc. body: SP_UPDATE_VERBA_ONLINE */
create or alter procedure SP_UPDATE_VERBA_ONLINE (
    PRCLAANT varchar(1000),
    PRCLANOVA varchar(1000),
    PRCODVER integer)
as
declare variable WSQL varchar(1000);
declare variable WCLANOVA varchar(100);
declare variable WCLANOVARESC varchar(100);
declare variable WCODPLANOONLINE integer;
declare variable WCHAVE integer;
begin
  wsql = 'select x.bdclanovaverba,x.bdclanovaverbaresc from SPCLASSVERBAONLINE('||
         ''''||prclaant||''''||
         ','||''''||prclanova||''''||') x';
  execute statement wsql into wclanova,wclanovaresc;


  for select BDCODPLANOONLINE, BDCHAVE from TCONF_CONTAS_ONLINE where BDCODVER = :prcodver and BDCODTIPOCONTA = 24 into :wcodplanoonline, :wchave do
  begin
    update tconf_contas_online set bdclassificacao = :wclanova where BDCODPLANOONLINE = :wcodplanoonline and BDCHAVE = :wchave;
  end

  for select BDCODPLANOONLINE, BDCHAVE from TCONF_CONTAS_ONLINE where BDCODVER = :prcodver and BDCODTIPOCONTA = 25 into :wcodplanoonline, :wchave do
  begin
    update tconf_contas_online set bdclassificacao = :wclanovaresc where BDCODPLANOONLINE = :wcodplanoonline and BDCHAVE = :wchave;
  end
end
^

CREATE OR ALTER procedure SP_CONVERTE_COD_VERB_DASHBOARD (
    BDCODVER integer,
    BDCLAVER varchar(20),
    BDGRUPOCLA integer)
returns (
    BDVERBA integer)
as
begin
  /* Procedure Text */
  BDVERBA = 0;
  IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '0.001') THEN
      BEGIN
          IF (BDGRUPOCLA IN(9,10,12,2)) THEN
              BEGIN
                  /*Prolabore*/
                  BDVERBA = 102;
              END
          ELSE
              BEGIN
                  IF (BDGRUPOCLA = 3) THEN
                      BEGIN
                          /*Autônomo*/
                          BDVERBA = 103;
                      END
                  ELSE
                      BEGIN
                          IF (BDGRUPOCLA = 5) THEN
                              BEGIN
                                  /*Estágio*/
                                  BDVERBA = 104;
                              END
                          ELSE
                              BEGIN
                                 /*Assalariado*/
                                 BDVERBA = 101;
                              END
                      END
              END
          SUSPEND;
          EXIT;
      END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '0.800') THEN
          BEGIN
              BDVERBA = 101;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '0.002') THEN
          BEGIN
              BDVERBA = 105;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '0.003') THEN
          BEGIN
              BDVERBA = 106;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '0.004') THEN
          BEGIN
              BDVERBA = 107;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '0.005') THEN
          BEGIN
              BDVERBA = 108;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '0.006') THEN
          BEGIN
              BDVERBA = 108;
              SUSPEND;
              EXIT;
          END
             
      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '0.007') THEN
          BEGIN
              BDVERBA = 109;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '0.715') THEN
          BEGIN
              BDVERBA = 109;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '0.008') THEN
          BEGIN
              BDVERBA = 110;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '0.020') THEN
          BEGIN
              BDVERBA = 111;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '8.015') THEN
          BEGIN
              BDVERBA = 111;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '8.035') THEN
          BEGIN
              BDVERBA = 111;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 7) = '0.030.0') THEN
          BEGIN
              BDVERBA = 112;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '3.040') THEN
          BEGIN
              BDVERBA = 112;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '4.047') THEN
          BEGIN
              BDVERBA = 112;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '5.070') THEN
          BEGIN
              BDVERBA = 112;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '6.070') THEN
          BEGIN
              BDVERBA = 112;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '1.040') THEN
          BEGIN
              BDVERBA = 112;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 9) = '0.030.1.0') THEN
          BEGIN
              BDVERBA = 113;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 9) = '0.030.1.2') THEN
          BEGIN
              BDVERBA = 114;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '0.070') THEN
          BEGIN
              BDVERBA = 115;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '0.180') THEN
          BEGIN
              BDVERBA = 116;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '0.200') THEN
          BEGIN
              BDVERBA = 117;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '1.001') THEN
          BEGIN
              BDVERBA = 118;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 1) = '2') THEN
          BEGIN
              BDVERBA = 119;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 1) = '3') THEN
          BEGIN
              BDVERBA = 120;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 1) = '4') THEN
          BEGIN
              BDVERBA = 121;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 1) = '5') THEN
          BEGIN
              BDVERBA = 122;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 1) = '6') THEN
          BEGIN
              BDVERBA = 123;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '7.001') THEN
          BEGIN
              BDVERBA = 124;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 4) = '7.01') THEN
          BEGIN
              BDVERBA = 125;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 4) = '7.02') THEN
          BEGIN
              BDVERBA = 125;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 4) = '7.03') THEN
          BEGIN
              BDVERBA = 125;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 4) = '7.05') THEN
          BEGIN
              BDVERBA = 126;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 4) = '7.06') THEN
          BEGIN
              BDVERBA = 126;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 4) = '7.07') THEN
          BEGIN
              BDVERBA = 126;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 4) = '7.08') THEN
          BEGIN
              BDVERBA = 126;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '8.005') THEN
          BEGIN
              BDVERBA = 127;
              SUSPEND;
              EXIT;
          END

      IF (SUBSTRING(BDCLAVER FROM 1 FOR 5) = '9.002') THEN
          BEGIN
              BDVERBA = 128;
              SUSPEND;
              EXIT;
          END
    SUSPEND;
END^

/* Restore proc. body: SP_VAL_GPS_PROV_13 */
create or alter procedure SP_VAL_GPS_PROV_13 (
    PRREFERENCIA integer,
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000))
returns (
    BDREFERENCIA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODTER integer,
    BDTIPOIMPOSTO integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(15,6),
    BDTERCFN numeric(15,6),
    BDRATFN numeric(15,6),
    BDRATAPOFN numeric(15,6),
    BDINSS13 numeric(15,6),
    BDTERC13 numeric(15,6),
    BDRAT13 numeric(15,6),
    BDRATAPO13 numeric(15,6),
    BDINSS13IND numeric(15,6),
    BDTERC13IND numeric(15,6),
    BDRAT13IND numeric(15,6),
    BDRATAPO13IND numeric(15,6),
    BDINSSC13 numeric(15,6),
    BDTERCC13 numeric(15,6),
    BDRATC13 numeric(15,6),
    BDRATAPOC13 numeric(15,6),
    BDINSSPBM13 numeric(15,6))
as
declare variable WSQL varchar(10000);
BEGIN
  /* Procedure Text */
  wsql = 'select y.bdreferencia,x.bdcodemp,x.bdcodcol,x.bdcodter,y.bdtipoimposto,x.bdcodcentro,x.bdcodtpcc,'||
       /*FOLHA*/
         'coalesce(x.bdvalfunemp13fn,0) +'||
         'coalesce(x.bdvalfunemp13fc,0) +'||
         'coalesce(x.bdvalproemp13fc,0) +'||
         'coalesce(x.bdvalproemp13fn,0) +'||
         'coalesce(x.bdvalautemp13fn,0) +'||
         'coalesce(x.bdvalautemp13fc,0) INSSFN,'||
         'coalesce(x.bdvalfpasemp13fn,0) +'||
         'coalesce(x.bdvalfpasemp13fc,0) +'||

         'coalesce(x.bdvalSALEDUemp13fn,0) +'||
         'coalesce(x.bdvalSALEDUemp13fc,0) +'||
         'coalesce(x.bdvalINCRAemp13fn,0) +'||
         'coalesce(x.bdvalINCRAemp13fc,0) +'||
         'coalesce(x.bdvalSENAIemp13fn,0) +'||
         'coalesce(x.bdvalSENAIemp13fc,0) +'||
         'coalesce(x.bdvalSESIemp13fn,0) +'||
         'coalesce(x.bdvalSESIemp13fc,0) +'||
         'coalesce(x.bdvalSENACemp13fn,0) +'||
         'coalesce(x.bdvalSENACemp13fc,0) +'||
         'coalesce(x.bdvalSESCemp13fn,0) +'||
         'coalesce(x.bdvalSESCemp13fc,0) +'||
         'coalesce(x.bdvalSEBRAEemp13fn,0) +'||
         'coalesce(x.bdvalSEBRAEemp13fc,0) +'||
         'coalesce(x.bdvalDPCemp13fn,0) +'||
         'coalesce(x.bdvalDPCemp13fc,0) +'||
         'coalesce(x.bdvalFUNAEROemp13fn,0) +'||
         'coalesce(x.bdvalFUNAEROemp13fc,0) +'||
         'coalesce(x.bdvalSENARemp13fn,0) +'||
         'coalesce(x.bdvalSENARemp13fc,0) +'||
         'coalesce(x.bdvalSESTemp13fn,0) +'||
         'coalesce(x.bdvalSESTemp13fc,0) +'||
         'coalesce(x.bdvalSENATemp13fn,0) +'||
         'coalesce(x.bdvalSENATemp13fc,0) +'||
         'coalesce(x.bdvalSESCOOPemp13fn,0) +'||
         'coalesce(x.bdvalSESCOOPemp13fc,0) TERCFN,'||
         'coalesce(x.bdvalRATemp13fn,0) +'||
         'coalesce(x.bdvalRATemp13fc,0) RATFN,'||
         'coalesce(x.bdvalRATAPOemp13fn,0) +'||
         'coalesce(x.bdvalRATAPOemp13fc,0) RATAPOFN,'||
       /*13*/
         'coalesce(x.bdvalfunemp13,0) +'||
         'coalesce(x.bdvalproemp13,0) +'||
         'coalesce(x.bdvalautemp13,0) INSS13,'||
         'coalesce(x.bdvalfpasemp13,0) + '||
         'coalesce(x.bdvalSALEDUemp13,0) + '||
         'coalesce(x.bdvalINCRAemp13,0) + '||
         'coalesce(x.bdvalSENAIemp13,0) + '||
         'coalesce(x.bdvalSESIemp13,0) + '||
         'coalesce(x.bdvalSENACemp13,0) + '||
         'coalesce(x.bdvalSESCemp13,0) + '||
         'coalesce(x.bdvalSEBRAEemp13,0) + '||
         'coalesce(x.bdvalDPCemp13,0) + '||
         'coalesce(x.bdvalFUNAEROemp13,0) + '||
         'coalesce(x.bdvalSENARemp13,0) + '||
         'coalesce(x.bdvalSESTemp13,0) + '||
         'coalesce(x.bdvalSENATemp13,0) + '||
         'coalesce(x.bdvalSESCOOPemp13,0) TERC13,'||
         'coalesce(x.bdvalRATemp13,0) RAT13,'||
         'coalesce(x.bdvalRATAPOemp13,0) RATAPO13,'||
       /* Complemento 13*/
         'coalesce(x.bdvalfunempc13,0) +'||
         'coalesce(x.bdvalproempc13,0) +'||
         'coalesce(x.bdvalautempc13,0) INSSc13,'||
         'coalesce(x.bdvalfpasempc13,0) + '||
         'coalesce(x.bdvalSALEDUempc13,0) + '||
         'coalesce(x.bdvalINCRAempc13,0) + '||
         'coalesce(x.bdvalSENAIempc13,0) + '||
         'coalesce(x.bdvalSESIempc13,0) + '||
         'coalesce(x.bdvalSENACempc13,0) + '||
         'coalesce(x.bdvalSESCempc13,0) + '||
         'coalesce(x.bdvalSEBRAEempc13,0) + '||
         'coalesce(x.bdvalDPCempc13,0) + '||
         'coalesce(x.bdvalFUNAEROempc13,0) + '||
         'coalesce(x.bdvalSENARempc13,0) + '||
         'coalesce(x.bdvalSESTempc13,0) + '||
         'coalesce(x.bdvalSENATempc13,0) + '||
         'coalesce(x.bdvalSESCOOPempc13,0) TERCc13,'||
         'coalesce(x.bdvalRATempc13,0) RATc13,'||
         'coalesce(x.bdvalRATAPOempc13,0) RATAPOc13,'||
       /*13º Indenizado*/
         'coalesce(x.bdvalfunemp13indfn,0) +'||
         'coalesce(x.bdvalproemp13indfn,0) +'||
         'coalesce(x.bdvalautemp13indfn,0) +'||
         'coalesce(x.bdvalautemp13fc,0) INSS13INDFN,'||
         'coalesce(x.bdvalfpasemp13indfn,0) + '||
         'coalesce(x.BDVALSALEDUemp13INDFN,0) + '||
         'coalesce(x.BDVALINCRAemp13INDFN,0) + '||
         'coalesce(x.BDVALSENAIemp13INDFN,0) + '||
         'coalesce(x.BDVALSESIemp13INDFN,0) + '||
         'coalesce(x.BDVALSENACemp13INDFN,0) + '||
         'coalesce(x.BDVALSESCemp13INDFN,0) + '||
         'coalesce(x.BDVALSEBRAEemp13INDFN,0) + '||
         'coalesce(x.BDVALDPCemp13INDFN,0) + '||
         'coalesce(x.BDVALFUNAEROemp13INDFN,0) + '||
         'coalesce(x.BDVALSENARemp13INDFN,0) + '||
         'coalesce(x.BDVALSESTemp13INDFN,0) + '||
         'coalesce(x.BDVALSENATemp13INDFN,0) + '||
         'coalesce(x.BDVALSESCOOPemp13INDFN,0) TERC13INDFN,'||
         'coalesce(x.bdvalRATemp13indfn,0) RAT13INDFN,'||
         'coalesce(x.bdvalRATAPOemp13indfn,0) RATAPO13INDFN,'||
         /*PBM*/
         'coalesce(x.bdvalpbm13,0) INSSPBM13'||
         ' from vrhf_emp_gps_ind x'||
         ' left outer join tdarfpadrao y on (x.bdcodemp = y.bdcodemp and x.BDCHAVEDARF = y.BDCHAVEDARF)';


  IF (prreferencia IS NULL) THEN
     prreferencia = 0;

  wsql = wsql||' where y.bdreferencia <= '||prreferencia;

  IF (prcodemp IS NOT NULL) THEN
     BEGIN
       wsql = wsql||' and '||prcodemp;
     END

  IF (prcodcol IS NOT NULL) THEN
     BEGIN
       wsql = wsql||' and '||prcodcol;
     END

  wsql = wsql||' and x.bdcodter is null ';
  wsql = wsql||' order by x.bdcodemp,x.bdcodcol,x.bdcodtpcc,y.bdreferencia';

  FOR EXECUTE STATEMENT wsql INTO
   :bdreferencia,
   :bdcodemp ,
   :bdcodcol ,
   :bdcodter ,
   :bdtipoimposto ,
   :bdcodcentro ,
   :bdcodtpcc,
   :bdinssfn,
   :bdtercfn,
   :bdratfn,
   :bdratapofn,
   :bdinss13,
   :bdterc13,
   :bdrat13,
   :bdratapo13,
   :bdinssc13,
   :bdtercc13,
   :bdratc13,
   :bdratapoc13,
   :bdinss13IND,
   :bdterc13IND,
   :bdrat13IND,
   :bdratapo13IND,
   :bdinsspbm13
  DO
  BEGIN
    SUSPEND;
  END
END^

/* Restore proc. body: SP_VAL_GPS_PROV_FER */
create or alter procedure SP_VAL_GPS_PROV_FER (
    PRREFERENCIA integer,
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000))
returns (
    BDREFERENCIA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODTER integer,
    BDTIPOIMPOSTO integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(15,6),
    BDTERCFN numeric(15,6),
    BDRATFN numeric(15,6),
    BDRATAPOFN numeric(15,6),
    BDINSSPBMFN numeric(15,6),
    BDINSSREONERACAOFN numeric(15,6),
    BDVALPBMFERFN integer)
as
declare variable WSQL varchar(10000);
BEGIN
  /* Procedure Text */
  wsql = 'select y.bdreferencia,x.bdcodemp,x.bdcodcol,x.bdcodter,y.bdtipoimposto,x.bdcodcentro,x.bdcodtpcc,'||
       /*FOLHA*/
         'coalesce(x.bdvalfunempFERfn,0) +'||
         'coalesce(x.bdvalfunempFERfc,0) +'||
         'coalesce(x.bdvalproempFERfc,0) +'||
         'coalesce(x.bdvalproempFERfn,0) +'||
         'coalesce(x.bdvalautempFERfn,0) +'||
         'coalesce(x.bdvalautempFERfc,0) INSSFN,'||
         'coalesce(x.bdvalfpasempFERfn,0) +'||
         'coalesce(x.bdvalfpasempFERfc,0) +'||
         'coalesce(x.bdvalSALEDUempferfn,0) +'||
         'coalesce(x.bdvalSALEDUempferfc,0) +'||

         'coalesce(x.bdvalINCRAempferfn,0) +'||
         'coalesce(x.bdvalINCRAempferfc,0) +'||
         'coalesce(x.bdvalSENAIempferfn,0) +'||
         'coalesce(x.bdvalSENAIempferfc,0) +'||
         'coalesce(x.bdvalSESIempferfn,0) +'||
         'coalesce(x.bdvalSESIempferfc,0) +'||
         'coalesce(x.bdvalSENACempferfn,0) +'||
         'coalesce(x.bdvalSENACempferfc,0) +'||
         'coalesce(x.bdvalSESCempferfn,0) +'||
         'coalesce(x.bdvalSESCempferfc,0) +'||
         'coalesce(x.bdvalSEBRAEempferfn,0) +'||
         'coalesce(x.bdvalSEBRAEempferfc,0) +'||
         'coalesce(x.bdvalDPCempferfn,0) +'||
         'coalesce(x.bdvalDPCempferfc,0) +'||
         'coalesce(x.bdvalFUNAEROempferfn,0) +'||
         'coalesce(x.bdvalFUNAEROempferfc,0) +'||
         'coalesce(x.bdvalSENARempferfn,0) +'||
         'coalesce(x.bdvalSENARempferfc,0) +'||
         'coalesce(x.bdvalSESTempferfn,0) +'||
         'coalesce(x.bdvalSESTempferfc,0) +'||
         'coalesce(x.bdvalSENATempferfn,0) +'||
         'coalesce(x.bdvalSENATempferfc,0) +'||
         'coalesce(x.bdvalSESCOOPempferfn,0) +'||
         'coalesce(x.bdvalSESCOOPempferfc,0) TERCFN,'||
         'coalesce(x.bdvalRATempFERfn,0) +'||
         'coalesce(x.bdvalRATempFERfc,0) RATFN,'||
         'coalesce(x.bdvalRATAPOempFERfn,0) +'||
         'coalesce(x.bdvalRATAPOempFERfc,0) RATAPOFN, '||
         'coalesce(x.bdvalpbmferfn,0) + '||
         'coalesce(x.bdvalpbmferfc,0) INSSPBMFN, '||
         'coalesce(x.bdvalreoneracaoferfn,0) + '||
         'coalesce(x.bdvalreoneracaoferfc,0) INSSREONERACAOFN, '||
         ' X.BDVALPBMFERFN '||
         ' from vrhf_emp_gps_ind x'||
         ' left outer join tdarfpadrao y on (x.bdcodemp = y.bdcodemp and x.BDCHAVEDARF = y.BDCHAVEDARF)';


  IF (prreferencia IS NULL) THEN
     prreferencia = 0;

  wsql = wsql||' where y.bdreferencia <= '||prreferencia||' and COALESCE(y.BDTIPOIMPOSTO, 0) <> 2';

  IF (prcodemp IS NOT NULL) THEN
     BEGIN
       wsql = wsql||' and '||prcodemp;
     END

  IF (prcodcol IS NOT NULL) THEN
     BEGIN
       wsql = wsql||' and '||prcodcol;
     END

  wsql = wsql||' and x.bdcodter is null ';
  wsql = wsql||' order by x.bdcodemp,x.bdcodcol,x.bdcodtpcc,y.bdreferencia';

  FOR EXECUTE STATEMENT wsql INTO
   :bdreferencia,
   :bdcodemp ,
   :bdcodcol ,
   :bdcodter ,
   :bdtipoimposto ,
   :bdcodcentro ,
   :bdcodtpcc,
   :bdinssfn,
   :bdtercfn,
   :bdratfn,
   :bdratapofn,
   :bdinsspbmfn,
   :bdinssreoneracaofn,
   :BDVALPBMFERFN
  DO
  BEGIN
    SUSPEND;
  END
END^

/* Restore proc. body: SP_VAL_HE_RAIS_FF */
ALTER PROCEDURE SP_VAL_HE_RAIS_FF(PREMP INTEGER,
PRCOL INTEGER,
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDHE NUMERIC(15,6),
BDCODVER INTEGER)
 AS
DECLARE VARIABLE WBOOL VARCHAR(5);
DECLARE VARIABLE WHE NUMERIC(15,6);
DECLARE VARIABLE WINT INTEGER;
BEGIN
  /* Procedure Text */
--  suspend;

  FOR SELECT bdcodemp,bdcodcol, bdreffhe, bdvreffhe, bdcodver FROM VW_VRHF_EMP_TFICHAHE WHERE bdcodemp = :premp AND bdcodcol = :prcol AND
       CAST(SUBSTRING(CAST(bdreffhe AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER) = :prano
  INTO bdcodemp,bdcodcol,bdref, bdhe, bdcodver DO
    BEGIN
      EXECUTE PROCEDURE sp_seta_competencia(:bdref,NULL,NULL);

      SELECT bdrefhoremp FROM VW_VRHF_BASE_TEMPCALC WHERE bdcodemp = :premp INTO wbool;

      IF (wBool = 'TRUE') THEN
         BEGIN
           whe = bdhe;
           wint = CAST(whe - 0.5 AS INTEGER);

           whe = whe - wint;

           IF ((whe > 0) AND (bdhe > 0)) THEN
              BEGIN
                whe = (whe / 60 * 100) + wint;
                bdhe = whe;
              END
         END

      SUSPEND;
    END
END
^

/* Restore proc. body: SP_VAL_RAIS_FF */
create or alter procedure SP_VAL_RAIS_FF (
    PREMP integer = 0,
    PRCOL integer = 0,
    PRANO integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDAVPREV numeric(15,6),
    BDFERIND numeric(15,6),
    BDGRATIF numeric(15,6),
    BDMULTA numeric(15,6),
    BDSINDICAL numeric(15,6),
    BDASSISTENCIAL numeric(15,6),
    BDCONFEDERATIVA numeric(15,6),
    BDBASEFN numeric(15,6),
    BDBASEA13 numeric(15,6),
    BDBASE13 numeric(15,6),
    BDBASEC13 numeric(15,6),
    BDORIGEM integer,
    BDMENSALIDADE numeric(15,6))
as
declare variable WCONTRESC boolean;
declare variable WSQLAUX varchar(32000);
declare variable WSQL varchar(32000);
declare variable WREFRESC integer;
declare variable WREF integer;
declare variable WVALOR numeric(15,6);
declare variable WCLASS varchar(300);
declare variable WCLASS2 varchar(300);
declare variable WCLASS3 varchar(300);
declare variable WCLASS4 varchar(300);
declare variable WCLASS1 varchar(10);
declare variable WBASRAIS varchar(5);
declare variable WTIPOCOD integer;
declare variable WVALAUX numeric(15,6);
declare variable WJAN integer;
declare variable WFEV integer;
declare variable WMAR integer;
declare variable WABR integer;
declare variable WMAI integer;
declare variable WJUN integer;
declare variable WJUL integer;
declare variable WAGO integer;
declare variable WSET integer;
declare variable WOUT integer;
declare variable WNOV integer;
declare variable WDEZ integer;
declare variable WMES integer;
declare variable WEXISTE integer;
declare variable WRESCORIGINAL integer;
declare variable WLANCOUESTOURO varchar(5);
declare variable WVALORARREDONDAMENTO numeric(15,6);
declare variable WCALCFERA13 varchar(5);
declare variable WDTGOZO date;
declare variable WREFAUX integer;
declare variable WSQL2 varchar(32000);
declare variable WVALVERBA numeric(15,6);
BEGIN
  /* Procedure Text */
--  wsql = 'select fol.bdreffn, fol.bdvalv, ver.bdclaver from VW_VRHF_CONS_CALC_FOLHA_VERBAS fol '||
--         ' left outer join vrh_base_tverbas ver on (ver.bdcodver = fol.bdcodver) '||

  --130346 Jarde 08/05/2020 - Não deve trazer contribuinte com classe sócio cotista
  wSQL = 'select CLASS.BDGRUPOCLA, COLCON.BDCONTRCOL from VRH_BASE_TCLASSE CLASS '||
         'join VW_VRH_EMP_TCOLCON_VINC CLA on (CLA.BDCODEMP = '||premp||' and CLA.BDCODCOL = '||prcol||') '||
         'join VRH_EMP_TCOLCON COLCON on (CLA.BDCODEMP = COLCON.BDCODEMP and CLA.BDCODCOL = COLCON.BDCODCOL) '||
         'where (CLASS.BDCODCLA = CLA.BDCODCLA)';
  EXECUTE STATEMENT wsql INTO wclass, wclass2;
  if ((wclass = 12) AND (wclass2 = 1)) then
     exit;

  bdorigem = 0;
  IF (prano >= 2014) THEN
     BEGIN
       wsql = 'select RAIS.BDREFFN, RAIS.BDVALV, VER.BDCLAVER, VERREF.BDRAISVER, VERREF.BDTIPOCODVER, RAIS.BDREFRESCISAO, RAIS.BDREFRESCORIGINAL, RAIS.bdCONTRES '||
              'from (select FOL.BDREFFN, FOL.BDVALVFN BDVALV,  '||
                           '0 BDREFRESCISAO, 0 BDREFRESCORIGINAL, FOL.BDCODVER, FOL.bdCONTRES '||
                    'from (select 1 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREFFN, BDREFFN BDREFFILTRO, BDREFVFN, BDREFAUXVFN, '||
                                 'BDVALVFN, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                 'cast(null as integer) BDCODTPCC, FALSE bdCONTRES '||
                          'from VRHF_EMP_TVERBAFN COLCON '||
                          'union all '||
                          'select 1 BDTIPOFICHA, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODVER, COLCON.BDREFFN, COLCON.BDREFFN BDREFFILTRO, COLCON.BDREFVFN, COLCON.BDREFAUXVFN, '||
                                 'COLCON.BDVALVFN, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                 'cast(null as integer) BDCODTPCC, CINT.bdconvrescti bdCONTRES '||
                          'from VRHF_EMP_TVERBAINT COLCON '||
                          'join VRH_EMP_TINTERMITENTE CINT ON (COLCON.bdcodemp = CINT.bdcodemp and colcon.bdcodcol = cint.bdcodcol and colcon.BDCODCONTTI = cint.bdcodcontti) '||
                          'union all '||
                          'select 1 BDTIPOFICHA, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODVER, COLCON.BDREFTOMADOR, '||
                                 'COLCON.BDREFTOMADOR BDREFFILTRO, COLCON.BDREFVFT, COLCON.BDREFAUXVFT, COLCON.BDVALVFT, '||
                                 'CC.BDDATAENTRADA, CC.BDCODCENTRO, CC.BDCODTPCC, FALSE bdCONTRES '||
                          'from VRHF_EMP_TVERBATOMADOR COLCON '||
                          'join VRHF_EMP_TPREPFN CC on (COLCON.BDCODEMP = CC.BDCODEMP and COLCON.BDCODCOL = CC.BDCODCOL and COLCON.BDORDEM = CC.BDORDEM) '||
                          'union all '||
                          'select 1 BDTIPOFICHA, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODVER, COLCON.BDREFTOMADOR, '||
                                 'COLCON.BDREFTOMADOR BDREFFILTRO, COLCON.BDREFVFT, COLCON.BDREFAUXVFT, COLCON.BDVALVFT, '||
                                 'CC.BDDATAENTRADA, CC.BDCODCENTRO, CC.BDCODTPCC, CINT.bdconvrescti bdCONTRES '||
                          'from VRHF_EMP_TVERBATOMINT COLCON '||
                          'join VRH_EMP_TINTERMITENTE CINT ON (COLCON.bdcodemp = CINT.bdcodemp and colcon.bdcodcol = cint.bdcodcol and colcon.BDCODCONTTI = cint.bdcodcontti) '||
                          'join VRHF_EMP_TPREPFN CC on (COLCON.BDCODEMP = CC.BDCODEMP and COLCON.BDCODCOL = CC.BDCODCOL and COLCON.BDORDEM = CC.BDORDEM) '||
                          'union all '||
                          'select 2 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREFFN, BDREFFN, BDREFVFC, BDREFAUXVFC, BDVALVFC, '||
                                 'cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, cast(null as integer) BDCODTPCC, FALSE bdCONTRES '||
                          'from VRHF_EMP_TVERBAFC FC '||
                          'union all '||
                          'select 2 BDTIPOFICHA, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODVER, COLCON.BDREFTOMADOR, '||
                                 'COLCON.BDREFTOMADOR, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, COLCON.BDVALVFC, CC.BDDATAENTRADA, '||
                                 'CC.BDCODCENTRO, CC.BDCODTPCC, FALSE bdCONTRES '||
                          'from VRHF_EMP_TVERBAFCTOMADOR COLCON '||
                          'join VRHF_EMP_TPREPFN CC on (COLCON.BDCODEMP = CC.BDCODEMP and COLCON.BDCODCOL = CC.BDCODCOL and COLCON.BDORDEM = CC.BDORDEM) '||
                          -- 161944 Leonardo Schwab 06/04/2022 adicionadas as tabelas de complementar intermitente
                          'union all '||
                          'select 2 BDTIPOFICHA, FC.BDCODEMP, FC.BDCODCOL, FC.BDCODVER, FC.BDREFFN, FC.BDREFFN, FC.BDREFVFC, FC.BDREFAUXVFC, FC.BDVALVFC, '||
                                 'cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, cast(null as integer) BDCODTPCC, CINT.bdconvrescti bdCONTRES '||
                          'from VRHF_EMP_TVERBAFCINT FC '||
                          'join VRH_EMP_TINTERMITENTE CINT ON (FC.bdcodemp = CINT.bdcodemp and FC.bdcodcol = cint.bdcodcol and FC.BDCODCONTTI = cint.bdcodcontti) '||
                          'union all '||
                          'select 2 BDTIPOFICHA, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODVER, COLCON.BDREFTOMADOR, '||
                                 'COLCON.BDREFTOMADOR, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, COLCON.BDVALVFC, CC.BDDATAENTRADA, '||
                                 'CC.BDCODCENTRO, CC.BDCODTPCC, CINT.bdconvrescti bdCONTRES '||
                          'from VRHF_EMP_TVERBAFCTOMINT COLCON '||
                          'join VRH_EMP_TINTERMITENTE CINT ON (COLCON.bdcodemp = CINT.bdcodemp and colcon.bdcodcol = cint.bdcodcol and colcon.BDCODCONTTI = cint.bdcodcontti) '||
                          'join VRHF_EMP_TPREPFN CC on (COLCON.BDCODEMP = CC.BDCODEMP and COLCON.BDCODCOL = CC.BDCODCOL and COLCON.BDORDEM = CC.BDORDEM) '||
                          -- 161944 Leonardo Schwab 06/04/2022 fim
                          'union all '||
                          'select 3 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREFA13, BDREFA13 BDREFFILTRO, BDREFVA13, BDREFAUXVA13, '||
                                 'BDVALVA13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                 'cast(null as integer) BDCODTPCC, FALSE bdCONTRES '||
                          'from VRHF_EMP_TVERBAA13 FC '||
                          'union all '||
                          'select 4 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREF13, BDREF13 BDREFFILTRO, BDREFV13, BDREFAUXV13, '||
                                 'BDVALV13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                 'cast(null as integer) BDCODTPCC, FALSE bdCONTRES '||
                          'from VRHF_EMP_TVERBA13 FC '||
                          'union all '||
                          'select 4 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREFC13, BDREFC13 BDREFFILTRO, BDREFVC13, BDREFAUXVC13, '||
                                 'BDVALVC13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                 'cast(null as integer) BDCODTPCC, FALSE bdCONTRES '||
                          'from VRHF_EMP_TVERBAC13 FC) FOL '||
                    'where (FOL.BDCODEMP = '||premp||') and '||
                          '(substring(FOL.BDREFFILTRO from 1 for 4) = '''||prano||''') and '||
                          'FOL.BDCODCOL = '||prcol||' '||
                    'union all '||
                    'select FOL.BDREFFN, FOL.BDVALVFN BDVALV, '||
                           'case '||
                             'when PRES.BDINIPRES = 1 and RES.BDPROJECAOAVISO is not null then RES.BDREFPROJECAOAVISO '||
                             'else RES.BDREFRESCISAO '||
                           'end BDREFRESCISAO, '||
                           'RES.BDREFRESCISAO BDREFRESCORIGINAL, FOL.BDCODVER, FOL.bdCONTRES '||
                    'from VRH_EMP_TRESCISAO RES '||
                    'join(select 1 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREFFN, BDREFFN BDREFFILTRO, BDREFVFN, BDREFAUXVFN, '||
                                'BDVALVFN, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                'cast(null as integer) BDCODTPCC, FALSE bdCONTRES '||
                         'from VRHF_EMP_TVERBAFN COLCON '||
                         'union all '||
                         'select 1 BDTIPOFICHA, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODVER, COLCON.BDREFFN, COLCON.BDREFFN BDREFFILTRO, COLCON.BDREFVFN, COLCON.BDREFAUXVFN, '||
                                'BDVALVFN, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                'cast(null as integer) BDCODTPCC, CINT.bdconvrescti bdCONTRES '||
                         'from VRHF_EMP_TVERBAINT COLCON '||
                         'join VRH_EMP_TINTERMITENTE CINT ON (COLCON.bdcodemp = CINT.bdcodemp and colcon.bdcodcol = cint.bdcodcol and colcon.BDCODCONTTI = cint.bdcodcontti) '||
                         'union all '||
                         'select 1 BDTIPOFICHA, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODVER, COLCON.BDREFTOMADOR, '||
                                'COLCON.BDREFTOMADOR BDREFFILTRO, COLCON.BDREFVFT, COLCON.BDREFAUXVFT, COLCON.BDVALVFT, '||
                                'CC.BDDATAENTRADA, CC.BDCODCENTRO, CC.BDCODTPCC, FALSE bdCONTRES '||
                         'from VRHF_EMP_TVERBATOMADOR COLCON '||
                         'join VRHF_EMP_TPREPFN CC on (COLCON.BDCODEMP = CC.BDCODEMP and COLCON.BDCODCOL = CC.BDCODCOL and COLCON.BDORDEM = CC.BDORDEM) '||
                         'union all '||
                         'select 1 BDTIPOFICHA, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODVER, COLCON.BDREFTOMADOR, '||
                                'COLCON.BDREFTOMADOR BDREFFILTRO, COLCON.BDREFVFT, COLCON.BDREFAUXVFT, COLCON.BDVALVFT, '||
                                'CC.BDDATAENTRADA, CC.BDCODCENTRO, CC.BDCODTPCC, CINT.bdconvrescti bdCONTRES '||
                         'from VRHF_EMP_TVERBATOMINT COLCON '||
                         'join VRH_EMP_TINTERMITENTE CINT ON (COLCON.bdcodemp = CINT.bdcodemp and colcon.bdcodcol = cint.bdcodcol and colcon.BDCODCONTTI = cint.bdcodcontti) '||
                         'join VRHF_EMP_TPREPFN CC on (COLCON.BDCODEMP = CC.BDCODEMP and COLCON.BDCODCOL = CC.BDCODCOL and COLCON.BDORDEM = CC.BDORDEM) '||
                         'union all '||
                         'select 2 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREFFN, BDREFFN BDREFFILTRO, BDREFVFC, BDREFAUXVFC, '||
                                'BDVALVFC, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                'cast(null as integer) BDCODTPCC, FALSE bdCONTRES '||
                         'from VRHF_EMP_TVERBAFC FC '||
                         'union all '||
                         'select 2 BDTIPOFICHA, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODVER, COLCON.BDREFTOMADOR, '||
                                'COLCON.BDREFTOMADOR BDREFFILTRO, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, COLCON.BDVALVFC, CC.BDDATAENTRADA, '||
                                'CC.BDCODCENTRO, CC.BDCODTPCC, FALSE bdCONTRES '||
                         'from VRHF_EMP_TVERBAFCTOMADOR COLCON '||
                         'join VRHF_EMP_TPREPFN CC on (COLCON.BDCODEMP = CC.BDCODEMP and COLCON.BDCODCOL = CC.BDCODCOL and COLCON.BDORDEM = CC.BDORDEM) '||
                         -- 161944 Leonardo Schwab 06/04/2022 adicionadas as tabelas de complementar intermitente
                         'union all '||
                         'select 2 BDTIPOFICHA, FC.BDCODEMP, FC.BDCODCOL, FC.BDCODVER, FC.BDREFFN, FC.BDREFFN BDREFFILTRO, FC.BDREFVFC, FC.BDREFAUXVFC, '||
                                'BDVALVFC, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                'cast(null as integer) BDCODTPCC, CINT.bdconvrescti bdCONTRES '||
                         'from VRHF_EMP_TVERBAFCINT FC '||
                         'join VRH_EMP_TINTERMITENTE CINT ON (FC.bdcodemp = CINT.bdcodemp and FC.bdcodcol = cint.bdcodcol and FC.BDCODCONTTI = cint.bdcodcontti) '||
                         'union all '||
                         'select 2 BDTIPOFICHA, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODVER, COLCON.BDREFTOMADOR, '||
                                'COLCON.BDREFTOMADOR BDREFFILTRO, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, COLCON.BDVALVFC, CC.BDDATAENTRADA, '||
                                'CC.BDCODCENTRO, CC.BDCODTPCC, CINT.bdconvrescti bdCONTRES '||
                         'from VRHF_EMP_TVERBAFCTOMINT COLCON '||
                         'join VRH_EMP_TINTERMITENTE CINT ON (COLCON.bdcodemp = CINT.bdcodemp and colcon.bdcodcol = cint.bdcodcol and colcon.BDCODCONTTI = cint.bdcodcontti) '||
                         'join VRHF_EMP_TPREPFN CC on (COLCON.BDCODEMP = CC.BDCODEMP and COLCON.BDCODCOL = CC.BDCODCOL and COLCON.BDORDEM = CC.BDORDEM) '||
                         -- 161944 Leonardo Schwab 06/04/2022 fim
                         'union all '||
                         'select 3 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREFA13, BDREFA13 BDREFFILTRO, BDREFVA13, BDREFAUXVA13, '||
                                'BDVALVA13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                'cast(null as integer) BDCODTPCC, FALSE bdCONTRES '||
                         'from VRHF_EMP_TVERBAA13 FC '||
                         'union all '||
                         'select 4 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREF13, BDREF13 BDREFFILTRO, BDREFV13, BDREFAUXV13, '||
                                'BDVALV13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                'cast(null as integer) BDCODTPCC, FALSE bdCONTRES '||
                         'from VRHF_EMP_TVERBA13 FC '||
                         'union all '||
                         'select 4 BDTIPOFICHA, BDCODEMP, BDCODCOL, BDCODVER, BDREFC13, BDREFC13 BDREFFILTRO, BDREFVC13, BDREFAUXVC13, '||
                                'BDVALVC13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, '||
                                'cast(null as integer) BDCODTPCC, FALSE bdCONTRES '||
                         'from VRHF_EMP_TVERBAC13 FC) FOL on (FOL.BDCODEMP = RES.BDCODEMP and FOL.BDCODCOL = RES.BDCODCOL and FOL.BDREFFN = RES.BDREFRESCISAO) '||
                    'join VRH_BASE_TPREPRESC PRES on (PRES.BDCODPRES = RES.BDCODPRES) '||
                    'where (FOL.BDCODEMP = '||premp||') and '||
                          '((substring(RES.BDREFRESCISAO from 1 for 4) = '''||prano||''') or (substring(RES.BDREFPROJECAOAVISO from 1 for 4) = '''||prano||''')) and '||
                          '(substring(RES.BDREFRESCISAO from 1 for 4) > '''||'2013'||''') and '||
                          'FOL.BDCODCOL = '||prcol||') RAIS '||

              'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = RAIS.BDCODVER) '||
              'join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = RAIS.BDCODVER) '||
              ' where VERREF.BDTIPOCODVER <= 1 '||
              'order by RAIS.BDREFFN, RAIS.BDREFRESCISAO, RAIS.BDCODVER ';
     END
  ELSE
     BEGIN
       wsql = ' select fol.bdreffn,  fol.bdvalvfn BDVALV, ver.bdclaver,  '||
                 ' verref.bdraisver, verref.bdtipocodver, res.bdrefrescisao, 0 bdrefrescoriginal, FALSE bdCONTRES from '||
                 ' ( '||
     --            // Folha normal
                 ' select  BDCODEMP, BDCODCOL,  bdcodver,  bdreffn,  bdrefvfn,  bdrefauxvfn,  bdvalvfn, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, cast(null as integer) BDCODTPCC  from vrhf_emp_tverbafn COLCON '||
                 ' UNION all '||
     --            // Folha intermitente
                 ' select  BDCODEMP, BDCODCOL,  bdcodver,  bdreffn,  bdrefvfn,  bdrefauxvfn,  bdvalvfn, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, cast(null as integer) BDCODTPCC  from vrhf_emp_tverbaint COLCON '||
                 ' UNION all '||
     --              // Folha normal tomador
                 ' select COLCON.BDCODEMP, COLCON.BDCODCOL,  COLCON.BDCODVER,  COLCON.BDREFTOMADOR,  COLCON.BDREFVFT,  COLCON.BDREFAUXVFT,  COLCON.BDVALVFT, cc.bddataentrada, cc.bdcodcentro, cc.bdcodtpcc '||
                 ' from vrhf_emp_tverbatomador COLCON '||
                 ' join VRHF_EMP_TPREPFN cc on (COLCON.bdcodemp = cc.bdcodemp and  COLCON.bdcodcol = cc.bdcodcol and COLCON.bdordem = cc.bdordem) '||
                 'union all'||
     --              // Folha intermitente tomador
                 ' select COLCON.BDCODEMP, COLCON.BDCODCOL,  COLCON.BDCODVER,  COLCON.BDREFTOMADOR,  COLCON.BDREFVFT,  COLCON.BDREFAUXVFT,  COLCON.BDVALVFT, cc.bddataentrada, cc.bdcodcentro, cc.bdcodtpcc '||
                 ' from vrhf_emp_tverbatomint COLCON '||
                 ' join VRHF_EMP_TPREPFN cc on (COLCON.bdcodemp = cc.bdcodemp and  COLCON.bdcodcol = cc.bdcodcol and COLCON.bdordem = cc.bdordem) '||
                 ' union all '||
     --              // Folha Complementar
                 ' select  bdcodemp,  bdcodcol,  bdcodver,  bdreffn,  bdrefvfc,  bdrefauxvfc,  bdvalvfc, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, cast(null as integer) BDCODTPCC  from vrhf_emp_tverbafc fc '||
                 ' UNION all '||
     --              // Folha Complementar tomador
                 ' select COLCON.BDCODEMP, COLCON.BDCODCOL,  COLCON.BDCODVER,  COLCON.BDREFTOMADOR,  COLCON.BDREFVFc,  COLCON.BDREFAUXVFc,  COLCON.BDVALVFc, cc.bddataentrada, cc.bdcodcentro, cc.bdcodtpcc '||
                 ' from vrhf_emp_tverbafctomador COLCON '||
                 ' join VRHF_EMP_TPREPFN cc on (COLCON.bdcodemp = cc.bdcodemp and  COLCON.bdcodcol = cc.bdcodcol and COLCON.bdordem = cc.bdordem) '||
                 ' union all '||
     --              // Folha Complementar intermitente                -- 161944 Leonardo Schwab 06/04/2022 adicionadas as tabelas de complementar intermitente
                 ' select  bdcodemp,  bdcodcol,  bdcodver,  bdreffn,  bdrefvfc,  bdrefauxvfc,  bdvalvfc, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, cast(null as integer) BDCODTPCC  from vrhf_emp_tverbafcint fc '||
                 ' UNION all '||
     --              // Folha Complementar tomador intermitente        -- 161944 Leonardo Schwab 06/04/2022 adicionadas as tabelas de complementar intermitente 
                 ' select COLCON.BDCODEMP, COLCON.BDCODCOL,  COLCON.BDCODVER,  COLCON.BDREFTOMADOR,  COLCON.BDREFVFc,  COLCON.BDREFAUXVFc,  COLCON.BDVALVFc, cc.bddataentrada, cc.bdcodcentro, cc.bdcodtpcc '||
                 ' from vrhf_emp_tverbafctomint COLCON '||
                 ' join VRHF_EMP_TPREPFN cc on (COLCON.bdcodemp = cc.bdcodemp and  COLCON.bdcodcol = cc.bdcodcol and COLCON.bdordem = cc.bdordem) '||
     --              // Adiantamento 13º salário
                 ' union all '||
                 ' select  bdcodemp,  bdcodcol,  bdcodver,  bdrefa13,  bdrefva13,  bdrefauxva13,  bdvalva13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, cast(null as integer) BDCODTPCC '||
                 ' from vrhf_emp_tverbaa13 fc '||
     --              // 13º salário
                 ' union all '||
                 ' select  bdcodemp,  bdcodcol,  bdcodver,  bdref13,  bdrefv13,  bdrefauxv13,  bdvalv13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, cast(null as integer) BDCODTPCC '||
                 ' from vrhf_emp_tverba13 fc '||
     --              // Complemento 13º salário
                 ' union all '||
                 ' select  bdcodemp,  bdcodcol,  bdcodver,  bdrefc13,  bdrefvc13,  bdrefauxvc13,  bdvalvc13, cast(null as date) BDDATAENT, cast(null as integer) BDCODCENTO, cast(null as integer) BDCODTPCC '||
                 ' from vrhf_emp_tverbac13 fc '||
                 ' ) fol '||
                 ' join vrh_base_tverbas ver on (ver.bdcodver = fol.bdcodver) '||
                 ' join vw_vrh_base_tverbas_ref verref on (verref.bdcodver = fol.bdcodver) '||
                 ' left outer join vrh_emp_trescisao res on (fol.bdcodemp = res.bdcodemp and fol.bdcodcol = res.bdcodcol) '||
     
     
              ' where verref.bdtipocodver <= 1 and (fol.bdcodemp = '||premp||')  and (cast (substring(fol.bdreffn from 1 for 4) as integer) = '||prano||') AND FOL.bdcodcol = '||prcol||
              ' order by bdreffn, fol.bdcodver ';
     END

  bdcodcol = prcol;
  bdcodemp = premp;
  bdref = 0;

  wjan = 0;
  wfev = 0;
  wmar = 0;
  wabr = 0;
  wmai = 0;
  wjun = 0;
  wjul = 0;
  wago = 0;
  wset = 0;
  wout = 0;
  wnov = 0;
  wdez = 0;

  WEXISTE = 0;
  wLancouEstouro = 'FALSE';
  wValorArredondamento = 0;
  FOR EXECUTE STATEMENT wsql INTO wref,wvalor,wclass,wbasrais,wtipocod,wrefresc,:wrescoriginal,:WCONTRESC DO
    BEGIN
      WEXISTE = 1;

      IF (bdref <> wref) THEN
         BEGIN
           IF (bdref <> 0) THEN
              BEGIN
                IF (prano >= 2014) THEN
                   BEGIN
                     IF (SUBSTRING(wrefresc FROM 1 FOR 4) = CAST(prano AS VARCHAR(4)) AND wref = wrescoriginal) THEN
                        bdref = wrefresc;
                   END

                SUSPEND;
              END

           IF (prano >= 2014) THEN
              BEGIN
                IF (SUBSTRING(wrefresc FROM 1 FOR 4) = CAST(prano AS VARCHAR(4)) AND wref = wrescoriginal) THEN
                   wmes = CAST(SUBSTRING(CAST(wrefresc AS VARCHAR(6)) FROM 5 FOR 6) AS INTEGER);
                ELSE
                   wmes = CAST(SUBSTRING(CAST(wref AS VARCHAR(6)) FROM 5 FOR 6) AS INTEGER);
              END
           ELSE
              wmes = CAST(SUBSTRING(CAST(wref AS VARCHAR(6)) FROM 5 FOR 6) AS INTEGER);

           IF (wmes = 1) THEN
              wjan = 1;
           IF (wmes = 2) THEN
              wfev = 1;
           IF (wmes = 3) THEN
              wmar = 1;
           IF (wmes = 4) THEN
              wabr = 1;
           IF (wmes = 5) THEN
              wmai = 1;
           IF (wmes = 6) THEN
              wjun = 1;
           IF (wmes = 7) THEN
              wjul = 1;
           IF (wmes = 8) THEN
              wago = 1;
           IF (wmes = 9) THEN
              wset = 1;
           IF (wmes = 10) THEN
              wout = 1;
           IF (wmes = 11) THEN
              wnov = 1;
           IF (wmes = 12) THEN
              wdez = 1;

           bdref = wref;

           BDMULTA = 0;

           IF (prano >= 2014) THEN
              BEGIN
                IF ((wref = wrescoriginal) AND (SUBSTRING(wrefresc FROM 1 FOR 4) = CAST(prano AS VARCHAR(4)))) THEN
                   BEGIN
                     SELECT bdfgts40 FROM vrhf_emp_val_grrf(:premp,:prcol,:wrescoriginal,:wrescoriginal, 0) INTO bdmulta;
                   END
              END
           ELSE
              BEGIN
                IF (wref = wrefresc) THEN
                   BEGIN
                     SELECT bdfgts40 FROM vrhf_emp_val_grrf(:premp,:prcol,:wref,:wref, 0) INTO bdmulta;
                   END
              END

           /* Zera todos valores */
           BDAVPREV = 0;
           BDFERIND = 0;
           BDGRATIF = 0;
           BDSINDICAL = 0;
           BDASSISTENCIAL = 0;
           BDCONFEDERATIVA = 0;
           bdbase13 = 0;
           bdbasea13 = 0;
           bdbasec13 = 0;
           bdbasefn = 0;
           bdmensalidade = 0;
         END

      wclass1 = SUBSTRING(wclass FROM 1 FOR 1);
      wclass2 = SUBSTRING(wclass FROM 1 FOR 5);
      wclass3 = SUBSTRING(wclass FROM 1 FOR 7);
      wclass4 = SUBSTRING(wclass FROM 1 FOR 9);

      IF (wbasrais = 'TRUE') THEN
         BEGIN
           wvalaux = wvalor;
           IF (wtipocod = 1) THEN
              wvalaux = wvalaux * -1;


           IF (wclass1 = '4') THEN
              BEGIN
                IF (prano >= 2014) THEN
                   BEGIN
                     IF (wrefresc = 0) THEN
                        bdbasea13 = bdbasea13 + wvalaux;
                   END
                ELSE
                   bdbasea13 = bdbasea13 + wvalaux;
              END
--          //Adiantamento de 13º
         IF (WCLASS2 = '4.001') then
            begin
              if (BDBASEA13 > 0) then
                begin
                  select A13.BDCALCFERA13
                  from VRHF_EMP_TA13SAL A13
                  where A13.BDCODEMP = :PREMP and A13.BDCODCOL = :PRCOL and A13.BDREFA13 = :BDREF
                        into :WCALCFERA13;

                  select max(BDINIPERGOZOFE) from SP_VRHF_GETFERIAS(:PREMP, :PRCOL, :BDREF) where BDCALCA13FE = 'TRUE' into :WDTGOZO;
                  WREFAUX = extract (year from WDTGOZO) || RIGHT('0'||trim(EXTRACT(MONTH from WDTGOZO)), 2);

                  if ((:WCALCFERA13 = 'TRUE') and (WREFAUX is not null)) then
                    begin
                      WSQL2 = '  select FOL.BDVALVFN '||
                              '  from VRHF_EMP_TVERBAFN FOL '||
                              '  join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                              '  left outer join VRH_BASE_TVERBAS_REF REF on REF.BDCODVER = VER.BDCODVER and '||
                                                 ' REF.BDREFVER = (select max(BDREFVER) '||
                                                               '  from VRH_BASE_TVERBAS_REF '||
                                                               ' where BDCODVER = VER.BDCODVER and '||
                                                               ' BDREFVER <= '||:WREFAUX||') '||
                              ' where (FOL.BDCODEMP = '||:BDCODEMP||') and '||
                                    ' (FOL.BDCODCOL in ('||:BDCODCOL||')) and '||
                                    ' (FOL.BDREFFN = '||:WREFAUX||') and '||
                                    ' (VER.BDCLAVER like ''0.191%'') and '||
                                    ' (REF.BDFGTSVER = 3) '||
                              ' union all '||
                              ' select FOL.BDVALVFT '||
                              ' from VRHF_EMP_TVERBATOMADOR FOL '||
                              ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                              ' left outer join VRH_BASE_TVERBAS_REF REF on REF.BDCODVER = VER.BDCODVER and '||
                              '        REF.BDREFVER = (select max(BDREFVER) '||
                                                    ' from VRH_BASE_TVERBAS_REF '||
                                                    ' where BDCODVER = VER.BDCODVER and '||
                                                          ' BDREFVER <= '||:WREFAUX||') '||
                              ' where (FOL.BDCODEMP = '||:BDCODEMP||') and '||
                                     '(FOL.BDCODCOL in ('||:BDCODCOL||')) and '||
                                     '(FOL.BDREFVFT = '||:WREFAUX||') and '||
                                     '(VER.BDCLAVER like ''0.191%'') and '||
                                     '(REF.BDFGTSVER = 3) '||
                               ' union all '||
                               ' select FOL.BDVALVFN '||
                               ' from VRHF_EMP_TVERBAINT FOL '||
                               ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                               ' left outer join VRH_BASE_TVERBAS_REF REF on REF.BDCODVER = VER.BDCODVER and '||
                                     ' REF.BDREFVER = (select max(BDREFVER) '||
                                                     ' from VRH_BASE_TVERBAS_REF '||
                                                     ' where BDCODVER = VER.BDCODVER and '||
                                                           ' BDREFVER <= '||:WREFAUX||') '||
                               ' where (FOL.BDCODEMP = '||:BDCODEMP||') and '||
                                      '(FOL.BDCODCOL in ('||:BDCODCOL||')) and '||
                                      '(FOL.BDREFFN = '||:WREFAUX||') and '||
                                      '(VER.BDCLAVER like ''0.191%'') and '||
                                      '(REF.BDFGTSVER = 3) '||
                               ' union all '||
                               ' select FOL.BDVALVFT '||
                               ' from VRHF_EMP_TVERBATOMINT FOL '||
                               ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                               ' left outer join VRH_BASE_TVERBAS_REF REF on REF.BDCODVER = VER.BDCODVER and '||
                                     ' REF.BDREFVER = (select max(BDREFVER) '||
                                                     ' from VRH_BASE_TVERBAS_REF '||
                                                     ' where BDCODVER = VER.BDCODVER and '||
                                                           ' BDREFVER <= '||:WREFAUX||') '||
                               ' where (FOL.BDCODEMP = '||:BDCODEMP||') and '||
                                     ' (FOL.BDCODCOL in ('||:BDCODCOL||')) and '||
                                     ' (FOL.BDREFTOMADOR = '||:WREFAUX||') and '||
                                     ' (VER.BDCLAVER like ''0.191%'') and '||
                                     ' (REF.BDFGTSVER = 3)';
                      for execute statement WSQL2 into :WVALVERBA do
                        begin
                          if ((WVALVERBA > 0) and (WVALVERBA = BDBASEA13)) then
                            begin
                              BDBASEA13 = 0;
                            end
                        end
                    end

                end
            end

--           // Verba de 13º
           ELSE IF ((wclass1 = '5') OR (wclass2 = '7.060') OR (wclass4 = '0.800.6.2') or
                   (wclass2 = '7.050') OR (wclass2 = '7.061')) THEN
              BEGIN
                IF (prano >= 2014) THEN
                   BEGIN
                     IF (wrefresc = 0) THEN
                        begin
                          if ((wclass4 <> '0.800.6.2') or (wcontresc))  THEN
                        bdbase13 = bdbase13 + wvalaux;
                          else if ((wclass4 = '0.800.6.2')) then
                             bdbasefn = bdbasefn + wvalaux;
                        end
                   END
                ELSE
                   bdbase13 = bdbase13 + wvalaux;
              END
--           // Verba de Complemento 13º
           ELSE IF (wclass1 = '6') THEN
              BEGIN
                IF (prano >= 2014) THEN
                   BEGIN
                     IF (wrefresc = 0) THEN
                        bdbasec13 = bdbasec13 + wvalaux;
                   END
                ELSE
                   bdbasec13 = bdbasec13 + wvalaux;
              END
--           // Demais Verbas participa da folha normal
           ELSE
              BEGIN
                IF ((wclass3 <> '7.001.3') AND (wclass2 <> '7.010') AND (wclass2 <> '7.030') AND (wclass2 <> '7.032') AND (wclass2 <> '7.012') AND
                    (wclass2 <> '7.031') AND (wclass2 <> '7.033') AND (wclass2 <> '7.020') AND (wclass2 <> '7.021')) THEN
                   BEGIN
                     IF (prano >= 2014) THEN
                        BEGIN
--                          ((wclass4 = '0.800.6.0') OR (wclass4 = '0.800.6.1')))
                          if (wrefresc = 0) then
                             begin
                                  IF (((wclass4 <> '0.800.6.0') and (wclass4 <> '0.800.6.1')) or
                                    ((not (wcontresc)) and ((wclass4 = '0.800.6.0') or (wclass4 = '0.800.6.1')) ))  THEN
                             bdbasefn = bdbasefn + wvalaux;
                             end
                        END
                     ELSE
                        bdbasefn = bdbasefn + wvalaux;
                   END
              END
         END

--    // Verba estouro complemento 13º
      IF (wclass4 = '9.002.0.4') THEN
        BEGIN
          bdbasec13 = bdbasec13 + wvalor - wValorArredondamento;
          wLancouEstouro = 'TRUE';
        END
      ELSE
      IF (wclass4 = '9.001.1.8') THEN
        BEGIN
          IF (wLancouEstouro = 'TRUE') THEN
            BEGIN
              bdbasec13 = (bdbasec13 - wvalor);
            END
          ELSE
            wValorArredondamento = wvalor;
        END
      ELSE
      -- aviso prévio indenizado // 7.001.3
      IF (prano >= 2014) THEN
         BEGIN
           IF (SUBSTRING(wrefresc FROM 1 FOR 4) = CAST(prano AS VARCHAR(4)) AND wclass3 = '7.001.3') THEN
              bdavprev = bdavprev + wvalor;
         END
      ELSE
         BEGIN
           IF (wclass3 = '7.001.3') THEN
              bdavprev = bdavprev + wvalor;
         END


      -- férias indenizadas // 7.020 - 7.021

      IF (prano >= 2014) THEN
         BEGIN
           IF (SUBSTRING(wrefresc FROM 1 FOR 4) = CAST(prano AS VARCHAR(4))) THEN
              BEGIN
                IF ((((wclass2 = '7.010') OR (wclass2 = '7.012')) OR
                    ((wclass2 = '7.030') OR (wclass2 = '7.031')) OR
                    ((wclass2 = '7.032') OR (wclass2 = '7.033')) OR
                    (((wclass4 = '0.800.6.0') OR (wclass4 = '0.800.6.1')) and (wcontresc))) OR    -- 161944 Leonardo Schwab 08/04/2022 - Adicionadas as class. de INTERMITENTE_INDENIZADO_FERIAS(0.800.6.0) e INTERMITENTE_INDENIZADO_1_3_FERIAS(0.800.6.1)
                   (((wclass2 = '7.020') OR (wclass2 = '7.021')) AND (wbasrais = 'TRUE'))) THEN
                   bdferind = bdferind + wvalor;
              END
         END
      ELSE
         BEGIN
           IF (((wclass2 = '7.010') OR (wclass2 = '7.012')) OR
              ((wclass2 = '7.030') OR (wclass2 = '7.031')) OR
              ((wclass2 = '7.032') OR (wclass2 = '7.033')) OR
              ((wclass4 = '0.800.6.0') OR (wclass4 = '0.800.6.1'))) THEN        -- 161944 Leonardo Schwab 08/04/2022 - Adicionadas as class. de INTERMITENTE_INDENIZADO_FERIAS(0.800.6.0) e INTERMITENTE_INDENIZADO_1_3_FERIAS(0.800.6.1)
              bdferind = bdferind + wvalor;
         END

      -- gratificações // 0.003.0.0
      IF (prano >= 2014) THEN
         BEGIN
           IF (wref = wrefresc) THEN
              BEGIN
                IF (wclass4 = '0.003.0.0') THEN
                   bdgratif = bdgratif + wvalor;
              END
         END
      ELSE
         BEGIN
           IF (wref = wrefresc) THEN
              BEGIN
                IF (wclass4 = '0.003.0.0') THEN
                   bdgratif = bdgratif + wvalor;
              END
         END

      -- multa rescisória // 7.001.1.0 é a multa de FGTS
--      if (wclass4 = '7.001.1.0') then
--         bdmulta = bdmulta + wvalor;

      -- contribuição sindical // 0.004.0.1 - 0.004.0.0
      IF (prano >= 2014) THEN
         BEGIN
           IF ((wclass4 = '0.004.0.1') OR (wclass4 = '0.004.0.0') OR (wclass4 = '0.710.0.1') OR (wclass4 = '0.710.0.0') OR
               (wclass4 = '4.047.0.1') OR (wclass4 = '4.047.0.0') OR (wclass4 = '5.070.0.1') OR (wclass4 = '5.070.0.0') OR
               (wclass4 = '6.070.0.1') OR (wclass4 = '6.070.0.0')) THEN
              BEGIN
                IF ((wrefresc = 0) OR (wrefresc = wrescoriginal) OR (SUBSTRING(wrefresc FROM 1 FOR 4) <> CAST(prano AS VARCHAR(4)))) THEN
                   bdsindical = bdsindical + wvalor;
              END
         END
      ELSE
         BEGIN
           IF ((wclass4 = '0.004.0.1') OR (wclass4 = '0.004.0.0') OR (wclass4 = '0.710.0.1') OR (wclass4 = '0.710.0.0') OR
               (wclass4 = '4.047.0.1') OR (wclass4 = '4.047.0.0') OR (wclass4 = '5.070.0.1') OR (wclass4 = '5.070.0.0') OR
               (wclass4 = '6.070.0.1') OR (wclass4 = '6.070.0.0')) THEN
              bdsindical = bdsindical + wvalor;
         END

      IF (prano >= 2014) THEN
         BEGIN
           -- contribuição assistencial // 0.004.0.3
           IF ((wclass4 = '0.004.0.3') OR (wclass4 = '0.710.0.3') OR (wclass4 = '4.047.0.3') OR (wclass4 = '5.070.0.3') OR (wclass4 = '6.070.0.3')) THEN
              BEGIN
                IF ((wrefresc = 0) OR (wrefresc = wrescoriginal) OR (SUBSTRING(wrefresc FROM 1 FOR 4) <> CAST(prano AS VARCHAR(4)))) THEN
                   bdassistencial = bdassistencial + wvalor;
              END
     
           -- contribuição confederativa // 0.004.0.2
           IF ((wclass4 = '0.004.0.2') OR (wclass4 = '0.710.0.2') OR (wclass4 = '4.047.0.2') OR (wclass4 = '5.070.0.2') OR (wclass4 = '6.070.0.2')) THEN
              BEGIN
                IF ((wrefresc = 0) OR (wrefresc = wrescoriginal) OR (SUBSTRING(wrefresc FROM 1 FOR 4) <> CAST(prano AS VARCHAR(4)))) THEN
                   bdconfederativa = bdconfederativa + wvalor;
              END
     
           -- Mensalidade sindical
           IF ((wclass4 = '0.004.0.0') OR (wclass4 = '0.710.0.0') OR (wclass4 = '4.047.0.0') OR (wclass4 = '5.070.0.0') OR (wclass4 = '6.070.0.0')) THEN
              BEGIN
                IF ((wrefresc = 0) OR (wrefresc = wrescoriginal) OR (SUBSTRING(wrefresc FROM 1 FOR 4) <> CAST(prano AS VARCHAR(4)))) THEN
                   bdmensalidade = bdmensalidade + wvalor;
              END
         END
      ELSE
         BEGIN
           -- contribuição assistencial // 0.004.0.3
           IF ((wclass4 = '0.004.0.3') OR (wclass4 = '0.710.0.3') OR (wclass4 = '4.047.0.3') OR (wclass4 = '5.070.0.3') OR (wclass4 = '6.070.0.3')) THEN
              bdassistencial = bdassistencial + wvalor;
     
           -- contribuição confederativa // 0.004.0.2
           IF ((wclass4 = '0.004.0.2') OR (wclass4 = '0.710.0.2') OR (wclass4 = '4.047.0.2') OR (wclass4 = '5.070.0.2') OR (wclass4 = '6.070.0.2')) THEN
              bdconfederativa = bdconfederativa + wvalor;
     
           -- Mensalidade sindical
           IF ((wclass4 = '0.004.0.0') OR (wclass4 = '0.710.0.0') OR (wclass4 = '4.047.0.0') OR (wclass4 = '5.070.0.0') OR (wclass4 = '6.070.0.0')) THEN
              bdmensalidade = bdmensalidade + wvalor;
         END
    END

  IF (wexiste = 1) THEN
     SUSPEND;

  bdmensalidade = 0;
  -- busca valores da ficha financeira para meses que não tem informações
  wsqlaux = 'select a.bdreffrais,coalesce(a.bdrendfrais,0), coalesce(a.bda13frais,0), coalesce(a.bd13frais,0), coalesce(a.bdferiasrescisaofrais,0), '||
              ' coalesce(a.bdmultarescfrais,0), coalesce(a.bdcontrsindfrais,0), coalesce(a.bdcontassistfrais,0), '||
              ' coalesce(a.bdcontconffrais,0), coalesce(a.bdavisopreviofrais,0), coalesce(a.bdc13frais,0), '||
              ' coalesce(a.bdgratificacaofrais,0), coalesce(BDCONTAASS1FRAIS,0) from vrhf_emp_tficharais a '||
              ' where a.bdcodemp = '||:premp||' and a.bdcodcol = '||:prcol||
              ' and a.bdreffrais = '||:prano;
  bdorigem = 1;
  IF (wjan = 0) THEN
     BEGIN
       wsql = wsqlaux||'01';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wfev = 0) THEN
     BEGIN
       wsql = wsqlaux||'02';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wmar = 0) THEN
     BEGIN
       wsql = wsqlaux||'03';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wabr = 0) THEN
     BEGIN
       wsql = wsqlaux||'04';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wmai = 0) THEN
     BEGIN
       wsql = wsqlaux||'05';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wjun = 0) THEN
     BEGIN
       wsql = wsqlaux||'06';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wjul = 0) THEN
     BEGIN
       wsql = wsqlaux||'07';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wago = 0) THEN
     BEGIN
       wsql = wsqlaux||'08';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wset = 0) THEN
     BEGIN
       wsql = wsqlaux||'09';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wout = 0) THEN
     BEGIN
       wsql = wsqlaux||'10';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wnov = 0) THEN
     BEGIN
       wsql = wsqlaux||'11';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END

  IF (wdez = 0) THEN
     BEGIN
       wsql = wsqlaux||'12';

       FOR EXECUTE STATEMENT wsql INTO bdref,bdbasefn,bdbasea13,bdbase13, bdferind, bdmulta, bdsindical, bdassistencial, bdconfederativa, bdavprev,
            bdbasec13, bdgratif, bdmensalidade DO
       SUSPEND;
     END
END^

/* Restore proc. body: SP_VEF_BASE_TCONFDACOM1424 */
ALTER PROCEDURE SP_VEF_BASE_TCONFDACOM1424(PRCODCONF INTEGER)
 RETURNS(BDCODCONFDACON INTEGER,
BDCODQDACON INTEGER,
BDCODTIPOCRE INTEGER,
BDNUMCAMPODACON INTEGER,
BDNUMITEM INTEGER,
BDDESCFORMDACON VARCHAR(150),
BDFORMULADACON VARCHAR(15000),
BDFORMULADACON2 VARCHAR(15000),
BDFORMULADACON3 VARCHAR(15000),
BDCODTIPO INTEGER,
BDCAMPOINATIVO VARCHAR(5))
 AS
DECLARE VARIABLE WSQL VARCHAR(3000);
BEGIN

  wSql ='SELECT FORM.bdcodconfdacon,form.bdcodqdacon,0 BDCODTIPOCRE,form.bdnumcampodacon,form.bdnumitem,form.bddescformdacon,form.bdformuladacon, ';
  wSql =  wSql || ' form.bdformuladacon2,form.bdformuladacon3, QUADRO.bdcodtipo,form.BDCAMPOINATIVO ';
  wSql =  wSql || ' FROM VEF_BASE_TCONFDACONFORM FORM, VEF_BASE_TCONFDACONQ QUADRO';
  wSql =  wSql || ' where QUADRO.BDCODQDACON = FORM.BDCODQDACON';
  wSql =  wSql || ' AND FORM.BDCODCONFDACON = '||:prCODCONF;
--  wSql =  wSql || ' AND FORM.BDCAMPOINATIVO <> ''TRUE''';
  wSql =  wSql || ' AND QUADRO.bdcodtipo IN (21,40,22,41,64,65,66,67,68,69) ';
  wSql =  wSql || ' ORDER BY FORM.BDCODQDACON,FORM.BDNUMCAMPODACON';


  FOR EXECUTE STATEMENT wSql INTO
     :BDCODCONFDACON,
     :BDCODQDACON,
     :BDCODTIPOCRE,
     :BDNUMCAMPODACON,
     :BDNUMITEM,
     :BDDESCFORMDACON,
     :BDFORMULADACON,
     :bdformuladacon2,
     :bdformuladacon3,
     :bdcodtipo,
     :BDCAMPOINATIVO
    DO
      SUSPEND;

  wsql =' SELECT F.bdcodconfdacon,f.bdcodqdacon,F.BDCODTIPOCRE,f.bdnumcampodacon,f.bdnumitem,f.bddescformdacon,f.bdformuladacon,';
  wSql =  wSql || ' '''' bdformuladacon2, '''' bdformuladacon3, Q.bdcodtipo,f.BDCAMPOINATIVO ';
  wSql =  wSql || ' FROM vef_base_tconfdaconf1424 F, VEF_BASE_TCONFDACONQ Q ';
  wSql =  wSql || ' where Q.BDCODQDACON = F.BDCODQDACON ';
  wSql =  wSql || ' AND F.BDCODCONFDACON = '||:prCODCONF;
--  wSql =  wSql || ' AND F.BDCAMPOINATIVO <> ''TRUE'' ';
  wSql =  wSql || ' AND Q.bdcodtipo IN (36,55)';
  wSql =  wSql || ' ORDER BY F.BDCODQDACON,f.BDCODTIPOCRE, F.BDNUMCAMPODACON';


   FOR EXECUTE STATEMENT wSql INTO
     :BDCODCONFDACON,
     :BDCODQDACON,
     :BDCODTIPOCRE,
     :BDNUMCAMPODACON,
     :BDNUMITEM,
     :BDDESCFORMDACON,
     :BDFORMULADACON,
     :bdformuladacon2,
     :bdformuladacon3,
     :bdcodtipo,
     :BDCAMPOINATIVO
    DO
      SUSPEND;


END
^

/* Restore proc. body: SP_VEF_EMP_PODEEXCLUIRVINCPROD */
CREATE OR ALTER PROCEDURE SP_VEF_EMP_PODEEXCLUIRVINCPROD (
    PRCODEMP INTEGER,
    PRCODPROD INTEGER)
RETURNS (
    BDTABELA_VINCULADA VARCHAR(100))
AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WTABLE VARCHAR(2000);
DECLARE VARIABLE WSQL VARCHAR(20000);
DECLARE VARIABLE WSQLP VARCHAR(20000);
DECLARE VARIABLE WCAMPO VARCHAR(100);
DECLARE VARIABLE WCAMPOPRODUTO VARCHAR(64);
BEGIN

 WSQLP = 'select x.RDB$RELATION_NAME BDNAME, NULL BDTABELA_VINCULADA, I.RDB$FIELD_NAME BDCAMPO ';
 WSQLP = WSQLP||' from RDB$RELATION_CONSTRAINTS x ';
 WSQLP = WSQLP||' join RDB$REF_CONSTRAINTS y on (x.RDB$CONSTRAINT_NAME = y.RDB$CONSTRAINT_NAME) ';
 WSQLP = WSQLP||' join RDB$RELATION_CONSTRAINTS z on (Z.RDB$CONSTRAINT_NAME = y.RDB$CONST_NAME_UQ) ';
 WSQLP = WSQLP||' JOIN RDB$INDEX_SEGMENTS I ON(I.RDB$INDEX_NAME = X.RDB$INDEX_NAME) ';
 WSQLP = WSQLP||' WHERE x.RDB$CONSTRAINT_TYPE = '||'''FOREIGN KEY'''||' and y.RDB$DELETE_RULE <> '||'''CASCADE''';
 WSQLP = WSQLP||' and Z.RDB$RELATION_NAME = '||'''TCADPRO''';
 WSQLP = WSQLP||' AND x.RDB$RELATION_NAME <> '||'''TCADPRO_VINC''';--TABELA QUE ESTÁ CHAMANDO A ROTINA

 FOR EXECUTE STATEMENT WSQLP
  INTO
    :wtable,
    :BDTABELA_VINCULADA,
    :wCampoProduto
  DO
   BEGIN
      WCAMPO = NULL;

      SELECT FIRST 1 f.rdb$field_name BDCAMPO FROM rdb$relations r LEFT JOIN rdb$relation_fields f ON f.rdb$relation_name = r.rdb$relation_name
      WHERE ((r.rdb$relation_name IN (:wtable))) AND (UPPER(F.rdb$field_name) = 'BDCODEMP') ORDER BY r.rdb$relation_name, f.rdb$field_position INTO :WCAMPO;

      IF (WCAMPO IS NOT NULL) THEN
         BEGIN
           WCAMPO = NULL;

           SELECT FIRST 1 f.rdb$field_name BDCAMPO FROM rdb$relations r LEFT JOIN rdb$relation_fields f ON f.rdb$relation_name = r.rdb$relation_name
           WHERE ((r.rdb$relation_name IN (:wtable))) AND (UPPER(F.rdb$field_name) = :wCampoProduto) ORDER BY r.rdb$relation_name, f.rdb$field_position INTO :WCAMPO;
         END

      IF (WCAMPO IS NOT NULL) THEN
         BEGIN

          wsql = 'SELECT first 1 coalesce(bdcodemp,0) from '||wtable||' where bdcodemp = '||:prcodemp||' and '||:wCampoProduto||' = '||:PRCODPROD;
    
          WCODEMP = 0;
          FOR EXECUTE STATEMENT wsql
          INTO
            WCODEMP
          DO
          BEGIN
            IF (WCODEMP > 0) THEN
               BEGIN
                 BREAK;
               END
          END
    
          IF (WCODEMP > 0) THEN
            BEGIN
              BDTABELA_VINCULADA = wtable;
              WCODEMP = 0;
              SUSPEND;
            END
         END
   END
END^

/* Restore proc. body: SP_VEF_ENT_FORMULAS_DAPI */
ALTER PROCEDURE SP_VEF_ENT_FORMULAS_DAPI(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDCODNAT INTEGER,
BDCODOPDAPI INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDBASEICMS NUMERIC(15,2),
BDVLRICMS NUMERIC(15,2),
BDISENTASICMS NUMERIC(15,2),
BDVLRST NUMERIC(15,2),
BDIMPAPCREDDAPI NUMERIC(15,2),
BDISENTASDAPI NUMERIC(15,2),
BDNTRIBDAPI NUMERIC(15,2),
BDPARBCCREDDAPI NUMERIC(15,2),
BDDIFERIDASTDAPI NUMERIC(15,2),
BDSUSPENSASDAPI NUMERIC(15,2),
BDSTDAPI NUMERIC(15,2),
BDOUTRASDAPI NUMERIC(15,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WCODTIPODAPI INTEGER;
DECLARE VARIABLE WVALORDAPI NUMERIC(15,2);
DECLARE VARIABLE WBDOUTRASIPIST NUMERIC(15,2);
DECLARE VARIABLE WOUTRASIPIST NUMERIC(15,2);
DECLARE VARIABLE WOUTRASIPIST2 NUMERIC(15,2);
DECLARE VARIABLE WCODEMPAUX INTEGER;
DECLARE VARIABLE WCHAVEAUX INTEGER;
DECLARE VARIABLE WORDEMAUX INTEGER;
DECLARE VARIABLE WREFLANAUX INTEGER;
DECLARE VARIABLE WCODNATAUX INTEGER;
DECLARE VARIABLE WCODOPDAPIAUX INTEGER;
DECLARE VARIABLE WVLRCONTABAUX NUMERIC(15,2);
DECLARE VARIABLE WBASEICMSAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRICMSAUX NUMERIC(15,2);
DECLARE VARIABLE WISENTASICMSAUX NUMERIC(15,2);
DECLARE VARIABLE WISENTASDAPIAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRSTAUX NUMERIC(15,2);
DECLARE VARIABLE WOUTRASDAPIAUX NUMERIC(15,2);
DECLARE VARIABLE WIMPAPCREDDAPIAUX NUMERIC(15,2);
DECLARE VARIABLE WNTRIBDAPIAUX NUMERIC(15,2);
DECLARE VARIABLE WPARBCCREDDAPIAUX NUMERIC(15,2);
DECLARE VARIABLE WDIFERIDASTDAPIAUX NUMERIC(15,2);
DECLARE VARIABLE WSUSPENSASDAPIAUX NUMERIC(15,2);
DECLARE VARIABLE WSTDAPIAUX NUMERIC(15,2);
DECLARE VARIABLE WCODEMPAUX2 INTEGER;
DECLARE VARIABLE WREFLANAUX2 INTEGER;
DECLARE VARIABLE WCODNATAUX2 INTEGER;
DECLARE VARIABLE WCODOPDAPIAUX2 INTEGER;
DECLARE VARIABLE WVLRCONTABAUX2 NUMERIC(15,2);
DECLARE VARIABLE WBASEICMSAUX2 NUMERIC(15,2);
DECLARE VARIABLE WVLRICMSAUX2 NUMERIC(15,2);
DECLARE VARIABLE WISENTASICMSAUX2 NUMERIC(15,2);
DECLARE VARIABLE WISENTASDAPIAUX2 NUMERIC(15,2);
DECLARE VARIABLE WVLRSTAUX2 NUMERIC(15,2);
DECLARE VARIABLE WOUTRASDAPIAUX2 NUMERIC(15,2);
DECLARE VARIABLE WIMPAPCREDDAPIAUX2 NUMERIC(15,2);
DECLARE VARIABLE WNTRIBDAPIAUX2 NUMERIC(15,2);
DECLARE VARIABLE WPARBCCREDDAPIAUX2 NUMERIC(15,2);
DECLARE VARIABLE WDIFERIDASTDAPIAUX2 NUMERIC(15,2);
DECLARE VARIABLE WSUSPENSASDAPIAUX2 NUMERIC(15,2);
DECLARE VARIABLE WSTDAPIAUX2 NUMERIC(15,2);
DECLARE VARIABLE WIMPRIMIRFINAL INTEGER;
DECLARE VARIABLE WBDCHAVE INTEGER;
DECLARE VARIABLE WBDORDEM INTEGER;
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  IF ((:PRCODEMP IS NOT NULL) AND (:PRCODEMP <> '')) THEN
     BEGIN
        wwhere = ' where ('||:PRCODEMP;
        wwhere = wwhere||')';
     END

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'(';
       wwhere = wwhere||'AUX.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'AUX.BDREFLAN <= '||:pranomesfinal;
       wwhere = wwhere||')';
     END

/*  wsql = 'select MOV.bdcodemp, MOV.bdchave,itens.bdordem, MOV.bdreflan,nat.BDCODNAT,nat.bdcodopdapi, dapi.bdcodtipodapi, ';
  wsql = wsql || '       coalesce(SUM(itens.BDVLRCONTAB),0) BDVLRCONTAB, coalesce(sum(itens.BDBASEICMS),0) BDBASEICMS, ';
  wsql = wsql || '       coalesce(sum(itens.BDVLRICMS),0) BDVLRICMS, coalesce(sum(itens.BDISENTASICMS),0) BDISENTASICMS, coalesce(sum(itens.BDVLRST),0) BDVLRST,  ';
  wsql = wsql || '       coalesce(sum(dapi.BDVALOR),0) BDVALORDAPI, coalesce(sum(itens.BDVLRIPI + itens.BDVLRST),0) BDOUTRASIPIST, ';
  wsql = wsql || '       case when dapi.bdcodtipodapi in (1) then SUM(dapi.BDVALOR) else 0 end BDISENTASDAPI, ';
  wsql = wsql || '       case when dapi.bdcodtipodapi in (2) then SUM(dapi.BDVALOR) else 0 end BDNTRIBDAPI, ';
  wsql = wsql || '       case when dapi.bdcodtipodapi in (3) then SUM(dapi.BDVALOR) else 0 end BDPARBCCREDDAPI, ';
  wsql = wsql || '       case when dapi.bdcodtipodapi in (4) then SUM(dapi.BDVALOR) else 0 end BDDIFERIDASTDAPI, ';
  wsql = wsql || '       case when dapi.bdcodtipodapi in (5) then SUM(dapi.BDVALOR) else 0 end BDSUSPENSASDAPI, ';
  wsql = wsql || '       case when dapi.bdcodtipodapi in (6) then SUM(dapi.BDVALOR) else 0 end BDSTDAPI, ';
  wsql = wsql || '       case when dapi.bdcodtipodapi in (7) then SUM(dapi.BDVALOR) else 0 end BDIMPAPCREDDAPI, ';
  wsql = wsql || '       case when dapi.bdcodtipodapi in (8) then SUM(dapi.BDVALOR) else 0 end BDOUTRASDAPI ';
  wsql = wsql || 'from ( ';
  wsql = wsql || '        select * from vef_emp_tmovent aux ';
  wsql = wsql||wwhere;
  wsql = wsql || '     ) MOV ';
  wsql = wsql || 'join vef_emp_tmoventitens itens on ((itens.bdcodemp = MOV.bdcodemp) and (itens.bdchave = MOV.bdchave)) ';
  wsql = wsql || 'join VEF_BASE_TNATOP nat on (itens.bdcodnat = nat.bdcodnat) ';
  wsql = wsql || 'left outer join VEF_EMP_TMOVENTSTDAPI dapi on (dapi.bdcodemp = mov.bdcodemp and dapi.bdchave = mov.bdchave and dapi.bdordem = itens.bdordem) ';
  wsql = wsql || 'where (MOV.BDCODSITNF <> 2) and (nat.bdcodopdapi is not null and nat.bdcodopdapi <> 1) ';
  wsql = wsql || 'group by MOV.bdcodemp, MOV.bdchave,itens.bdordem, MOV.bdreflan,nat.BDCODNAT,nat.bdcodopdapi, dapi.bdcodtipodapi ';
  wsql = wsql || 'order by MOV.bdcodemp, MOV.bdchave,itens.bdordem, MOV.bdreflan,nat.BDCODNAT,nat.bdcodopdapi, dapi.bdcodtipodapi ';
          */
  --alt:# 7279
/*  wsql = '    select D.BDCODEMP, D.BDCHAVE, ITENS.BDORDEM, D.BDREFLAN, NAT.BDCODNAT, NAT.BDCODOPDAPI, D.BDCODTIPODAPI, ';
  wsql = wsql || '         sum(coalesce(ITENS.BDVLRCONTAB, 0)) BDVLRCONTAB, ';
  wsql = wsql || '         sum(coalesce(ITENS.BDBASEICMS, 0)) BDBASEICMS, ';
  wsql = wsql || '         sum(coalesce(ITENS.BDVLRICMS, 0)) BDVLRICMS, ';
  wsql = wsql || '         sum(coalesce(ITENS.BDISENTASICMS, 0)) BDISENTASICMS, ';
  wsql = wsql || '         sum(coalesce(ITENS.BDVLRST, 0)) BDVLRST, ';
  wsql = wsql || '         sum(coalesce(ITENS.BDVLRIPI, 0)) + ';
  wsql = wsql || '         sum(coalesce(ITENS.BDVLRST, 0)) BDOUTRASIPIST, ';
  wsql = wsql || '         sum(BDVALORDAPI) BDVALORDAPI, ';
  wsql = wsql || '         sum(D.BDISENTASDAPI) BDISENTASDAPI, ';
  wsql = wsql || '         sum(D.BDNTRIBDAPI) BDNTRIBDAPI, ';
  wsql = wsql || '         sum(D.BDPARBCCREDDAPI) BDPARBCCREDDAPI, ';
  wsql = wsql || '         sum(D.BDDIFERIDASTDAPI) BDDIFERIDASTDAPI, ';
  wsql = wsql || '         sum(D.BDSUSPENSASDAPI) BDSUSPENSASDAPI, ';
  wsql = wsql || '         sum(D.BDSTDAPI) BDSTDAPI, ';
  wsql = wsql || '         sum(D.BDIMPAPCREDDAPI) BDIMPAPCREDDAPI, ';
  wsql = wsql || '         sum(D.BDOUTRASDAPI) BDOUTRASDAPI ';
  wsql = wsql || '  from ( ';
  wsql = wsql || '        select MOV.BDCODEMP, MOV.BDCHAVE, mov.bdordem, MOV.BDREFLAN, DAPI.BDCODTIPODAPI, sum(coalesce(DAPI.BDVALOR, 0)) BDVALORDAPI, ';
  wsql = wsql || '               case  ';
  wsql = wsql || '                 when DAPI.BDCODTIPODAPI in (1) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                 else 0  ';
  wsql = wsql || '               end BDISENTASDAPI, ';
  wsql = wsql || '               case  ';
  wsql = wsql || '                 when DAPI.BDCODTIPODAPI in (2) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                 else 0  ';
  wsql = wsql || '               end BDNTRIBDAPI, ';
  wsql = wsql || '               case  ';
  wsql = wsql || '                 when DAPI.BDCODTIPODAPI in (3) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                 else 0  ';
  wsql = wsql || '               end BDPARBCCREDDAPI, ';
  wsql = wsql || '               case  ';
  wsql = wsql || '                 when DAPI.BDCODTIPODAPI in (4) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                 else 0 ';
  wsql = wsql || '               end BDDIFERIDASTDAPI, ';
  wsql = wsql || '               case  ';
  wsql = wsql || '                 when DAPI.BDCODTIPODAPI in (5) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                 else 0  ';
  wsql = wsql || '               end BDSUSPENSASDAPI, ';
  wsql = wsql || '               case  ';
  wsql = wsql || '                 when DAPI.BDCODTIPODAPI in (6) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                 else 0  ';
  wsql = wsql || '               end BDSTDAPI, ';
  wsql = wsql || '               case  ';
  wsql = wsql || '                 when DAPI.BDCODTIPODAPI in (7) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                 else 0  ';
  wsql = wsql || '               end BDIMPAPCREDDAPI, ';
  wsql = wsql || '               case ';
  wsql = wsql || '                 when DAPI.BDCODTIPODAPI in (8) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                 else 0  ';
  wsql = wsql || '               end BDOUTRASDAPI  ';
  wsql = wsql || '        from ( ';
  wsql = wsql || '         select mov.bdcodemp,mov.bdchave,mov.bdreflan, i.bdordem from ( ';
  wsql = wsql || '                         select aux.bdcodemp,aux.bdchave,aux.bdreflan ';
  wsql = wsql || '                              from VEF_EMP_TMOVENT AUX  ';
  wsql = wsql||wwhere;
  wsql = wsql || '                       ) MOV ';
  wsql = wsql || '        join vef_emp_tmoventitens i on (i.bdcodemp = mov.bdcodemp and i.bdchave = mov.bdchave)) mov ';
  wsql = wsql || '        join VEF_EMP_TMOVENTSTDAPI DAPI on (DAPI.BDCODEMP = MOV.BDCODEMP and DAPI.BDCHAVE = MOV.BDCHAVE and dapi.bdordem = mov.bdordem) ';
  wsql = wsql || '        group by MOV.BDCODEMP, MOV.BDCHAVE,mov.bdordem, MOV.BDREFLAN, DAPI.BDCODTIPODAPI, DAPI.BDCODTIPODAPI ';
  wsql = wsql || '        ) D ';
  wsql = wsql || '  join VEF_EMP_TMOVENTITENS ITENS on ((ITENS.BDCODEMP = D.BDCODEMP) and (ITENS.BDCHAVE = D.BDCHAVE) and itens.bdordem = d.bdordem) ';
  wsql = wsql || '  join VEF_BASE_TNATOP NAT on (ITENS.BDCODNAT = NAT.BDCODNAT) ';
  wsql = wsql || '  where (NAT.BDCODOPDAPI is not null and ';
  wsql = wsql || '        NAT.BDCODOPDAPI <> 1)  ';
  wsql = wsql || ' group by D.BDCODEMP, D.BDCHAVE, ITENS.BDORDEM, D.BDREFLAN, NAT.BDCODNAT, NAT.BDCODOPDAPI, D.BDCODTIPODAPI ';
  wsql = wsql || ' order by D.BDCODEMP, D.BDCHAVE, ITENS.BDORDEM, D.BDREFLAN, NAT.BDCODNAT, NAT.BDCODOPDAPI, D.BDCODTIPODAPI ';
   */

  wsql = '  select BDCODEMP, BDCHAVE, BDORDEM, BDREFLAN, BDCODNAT, BDCODOPDAPI, BDCODTIPODAPI,BDVLRCONTAB, ';
  wsql = wsql || '          BDBASEICMS,BDVLRICMS,BDISENTASICMS,BDVLRST,BDOUTRASIPIST,BDVALORDAPI,BDISENTASDAPI,BDNTRIBDAPI, ';
  wsql = wsql || '          BDPARBCCREDDAPI,BDDIFERIDASTDAPI,BDSUSPENSASDAPI,BDSTDAPI,BDIMPAPCREDDAPI,BDOUTRASDAPI ';
  wsql = wsql || '   from ( ';
  wsql = wsql || '   select D.BDCODEMP, D.BDCHAVE, ITENS.BDORDEM, D.BDREFLAN, NAT.BDCODNAT, NAT.BDCODOPDAPI, D.BDCODTIPODAPI, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRCONTAB, 0)) BDVLRCONTAB, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDBASEICMS, 0)) BDBASEICMS, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRICMS, 0)) BDVLRICMS, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDISENTASICMS, 0)) BDISENTASICMS, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRST, 0)) BDVLRST, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRIPI, 0)) + ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRST, 0)) BDOUTRASIPIST, ';
  wsql = wsql || '          sum(BDVALORDAPI) BDVALORDAPI, ';
  wsql = wsql || '          sum(D.BDISENTASDAPI) BDISENTASDAPI, ';
  wsql = wsql || '          sum(D.BDNTRIBDAPI) BDNTRIBDAPI, ';
  wsql = wsql || '          sum(D.BDPARBCCREDDAPI) BDPARBCCREDDAPI, ';
  wsql = wsql || '          sum(D.BDDIFERIDASTDAPI) BDDIFERIDASTDAPI, ';
  wsql = wsql || '          sum(D.BDSUSPENSASDAPI) BDSUSPENSASDAPI, ';
  wsql = wsql || '          sum(D.BDSTDAPI) BDSTDAPI, ';
  wsql = wsql || '          sum(D.BDIMPAPCREDDAPI) BDIMPAPCREDDAPI, ';
  wsql = wsql || '          sum(D.BDOUTRASDAPI) BDOUTRASDAPI ';
  wsql = wsql || '   from ( ';
  wsql = wsql || '         select MOV.BDCODEMP, MOV.BDCHAVE, mov.bdordem, MOV.BDREFLAN, DAPI.BDCODTIPODAPI, sum(coalesce(DAPI.BDVALOR, 0)) BDVALORDAPI, ';
  wsql = wsql || '                case  ';
  wsql = wsql || '                  when DAPI.BDCODTIPODAPI in (1) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                  else 0  ';
  wsql = wsql || '                end BDISENTASDAPI, ';
  wsql = wsql || '                case  ';
  wsql = wsql || '                  when DAPI.BDCODTIPODAPI in (2) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                  else 0  ';
  wsql = wsql || '                end BDNTRIBDAPI, ';
  wsql = wsql || '                case  ';
  wsql = wsql || '                  when DAPI.BDCODTIPODAPI in (3) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                  else 0  ';
  wsql = wsql || '                end BDPARBCCREDDAPI, ';
  wsql = wsql || '                case  ';
  wsql = wsql || '                  when DAPI.BDCODTIPODAPI in (4) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                  else 0  ';
  wsql = wsql || '                end BDDIFERIDASTDAPI, ';
  wsql = wsql || '                case  ';
  wsql = wsql || '                  when DAPI.BDCODTIPODAPI in (5) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                  else 0  ';
  wsql = wsql || '                end BDSUSPENSASDAPI, ';
  wsql = wsql || '                case  ';
  wsql = wsql || '                  when DAPI.BDCODTIPODAPI in (6) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                  else 0  ';
  wsql = wsql || '                end BDSTDAPI, ';
  wsql = wsql || '                case  ';
  wsql = wsql || '                  when DAPI.BDCODTIPODAPI in (7) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                  else 0  ';
  wsql = wsql || '                end BDIMPAPCREDDAPI, ';
  wsql = wsql || '                case  ';
  wsql = wsql || '                  when DAPI.BDCODTIPODAPI in (8) then sum(DAPI.BDVALOR)  ';
  wsql = wsql || '                  else 0  ';
  wsql = wsql || '                end BDOUTRASDAPI  ';
  wsql = wsql || '         from ( ';
  wsql = wsql || '          select mov.bdcodemp,mov.bdchave,mov.bdreflan, i.bdordem from ( ';
  wsql = wsql || '                          select aux.bdcodemp,aux.bdchave,aux.bdreflan ';
  wsql = wsql || '                               from VEF_EMP_TMOVENT AUX  ';
  wsql = wsql||wwhere;
  wsql = wsql || '                        ) MOV ';
  wsql = wsql || '         join vef_emp_tmoventitens i on (i.bdcodemp = mov.bdcodemp and i.bdchave = mov.bdchave)) mov ';
  wsql = wsql || '         join VEF_EMP_TMOVENTSTDAPI DAPI on (DAPI.BDCODEMP = MOV.BDCODEMP and DAPI.BDCHAVE = MOV.BDCHAVE and dapi.bdordem = mov.bdordem) ';
  wsql = wsql || '         group by MOV.BDCODEMP, MOV.BDCHAVE,mov.bdordem, MOV.BDREFLAN, DAPI.BDCODTIPODAPI, DAPI.BDCODTIPODAPI ';
  wsql = wsql || '         ) D ';
  wsql = wsql || '   join VEF_EMP_TMOVENTITENS ITENS on ((ITENS.BDCODEMP = D.BDCODEMP) and (ITENS.BDCHAVE = D.BDCHAVE) and itens.bdordem = d.bdordem) ';
  wsql = wsql || '   join VEF_BASE_TNATOP NAT on (ITENS.BDCODNAT = NAT.BDCODNAT) ';
  wsql = wsql || '   where (NAT.BDCODOPDAPI is not null and ';
  wsql = wsql || '         NAT.BDCODOPDAPI <> 1)  ';
  wsql = wsql || '   group by D.BDCODEMP, D.BDCHAVE, ITENS.BDORDEM, D.BDREFLAN, NAT.BDCODNAT, NAT.BDCODOPDAPI, D.BDCODTIPODAPI ';
  wsql = wsql || '   union all ';
  wsql = wsql || '   select D.BDCODEMP, D.BDCHAVE, ITENS.BDORDEM, D.BDREFLAN, NAT.BDCODNAT, NAT.BDCODOPDAPI, D.BDCODTIPODAPI, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRCONTAB, 0)) BDVLRCONTAB, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDBASEICMS, 0)) BDBASEICMS, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRICMS, 0)) BDVLRICMS, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDISENTASICMS, 0)) BDISENTASICMS, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRST, 0)) BDVLRST, ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRIPI, 0)) + ';
  wsql = wsql || '          sum(coalesce(ITENS.BDVLRST, 0)) BDOUTRASIPIST, ';
  wsql = wsql || '          sum(BDVALORDAPI) BDVALORDAPI, ';
  wsql = wsql || '          sum(D.BDISENTASDAPI) BDISENTASDAPI, ';
  wsql = wsql || '          sum(D.BDNTRIBDAPI) BDNTRIBDAPI, ';
  wsql = wsql || '          sum(D.BDPARBCCREDDAPI) BDPARBCCREDDAPI, ';
  wsql = wsql || '          sum(D.BDDIFERIDASTDAPI) BDDIFERIDASTDAPI, ';
  wsql = wsql || '          sum(D.BDSUSPENSASDAPI) BDSUSPENSASDAPI, ';
  wsql = wsql || '          sum(D.BDSTDAPI) BDSTDAPI, ';
  wsql = wsql || '          sum(D.BDIMPAPCREDDAPI) BDIMPAPCREDDAPI, ';
  wsql = wsql || '          sum(D.BDOUTRASDAPI) BDOUTRASDAPI ';
  wsql = wsql || '   from ( ';
  wsql = wsql || '         select MOV.BDCODEMP, MOV.BDCHAVE, mov.bdordem, MOV.BDREFLAN, 0 BDCODTIPODAPI, 0 BDVALORDAPI, ';
  wsql = wsql || '                0 BDISENTASDAPI,0 BDNTRIBDAPI,0 BDPARBCCREDDAPI,0 BDDIFERIDASTDAPI,0 BDSUSPENSASDAPI,0 BDSTDAPI,0 BDIMPAPCREDDAPI,0 BDOUTRASDAPI ';
  wsql = wsql || '         from ( ';
  wsql = wsql || '          select mov.bdcodemp,mov.bdchave,mov.bdreflan, i.bdordem from ( ';
  wsql = wsql || '                          select aux.bdcodemp,aux.bdchave,aux.bdreflan ';
  wsql = wsql || '                               from VEF_EMP_TMOVENT AUX  ';
  wsql = wsql||wwhere;
  wsql = wsql || '                        ) MOV ';
  wsql = wsql || '         join vef_emp_tmoventitens i on (i.bdcodemp = mov.bdcodemp and i.bdchave = mov.bdchave) ';
  wsql = wsql || '         where not exists (select dapi.bdcodemp from VEF_EMP_TMOVENTSTDAPI dapi ';
  wsql = wsql || '                           where dapi.bdcodemp = mov.bdcodemp and dapi.bdchave = mov.bdchave and dapi.bdordem = i.bdordem ';
  wsql = wsql || '                          ) ';
  wsql = wsql || '         ) mov ';
  wsql = wsql || '         group by MOV.BDCODEMP, MOV.BDCHAVE,mov.bdordem, MOV.BDREFLAN, BDCODTIPODAPI,  BDCODTIPODAPI ';
  wsql = wsql || '         ) D ';
  wsql = wsql || '   join VEF_EMP_TMOVENTITENS ITENS on ((ITENS.BDCODEMP = D.BDCODEMP) and (ITENS.BDCHAVE = D.BDCHAVE) and itens.bdordem = d.bdordem) ';
  wsql = wsql || '   join VEF_BASE_TNATOP NAT on (ITENS.BDCODNAT = NAT.BDCODNAT) ';
  wsql = wsql || '   where (NAT.BDCODOPDAPI is not null and ';
  wsql = wsql || '         NAT.BDCODOPDAPI <> 1)  ';
  wsql = wsql || '   group by D.BDCODEMP, D.BDCHAVE, ITENS.BDORDEM, D.BDREFLAN, NAT.BDCODNAT, NAT.BDCODOPDAPI, D.BDCODTIPODAPI ';
  wsql = wsql || '   ) ';
  wsql = wsql || '   order by BDCODEMP, BDCHAVE, BDORDEM, BDREFLAN, BDCODNAT, BDCODOPDAPI, BDCODTIPODAPI ';



  wVLRCONTABaux = 0;
  wBASEICMSaux = 0;
  wVLRICMSaux = 0;
  wisentasicmsaux = 0;
  wVLRSTaux = 0;
  WOUTRASIPIST = 0;

  WIMPAPCREDDAPIAUX = 0;
  WISENTASDAPIAUX = 0;
  WNTRIBDAPIAUX = 0;
  WPARBCCREDDAPIAUX = 0;
  WDIFERIDASTDAPIAUX = 0;
  WSUSPENSASDAPIAUX = 0;
  WSTDAPIAUX = 0;
  WOUTRASDAPIAUX = 0;

  WIMPRIMIRFINAL = 0;
  WCHAVEAUX = 0;
  WORDEMAUX = 0;
  WOUTRASIPIST = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    :WBDCHAVE,
    :WBDORDEM,
    BDREFLAN,
    BDCODNAT,
    BDCODOPDAPI,
    :WCODTIPODAPI,
    BDVLRCONTAB,
    BDBASEICMS,
    BDVLRICMS,
    BDISENTASICMS,
    BDVLRST,
    :WVALORDAPI,
    :WBDOUTRASIPIST,
    BDISENTASDAPI,
    BDNTRIBDAPI,
    BDPARBCCREDDAPI,
    BDDIFERIDASTDAPI,
    BDSUSPENSASDAPI,
    BDSTDAPI,
    BDIMPAPCREDDAPI,
    BDOUTRASDAPI
  DO
  BEGIN
    WIMPRIMIRFINAL = 1;
    IF ((wcodempaux IS NULL) OR ((wcodempaux = bdcodemp) AND (wREFLANaux = BDREFLAN) AND (wCODNATaux = BDCODNAT))) THEN
       BEGIN
          wcodempaux = bdcodemp;
          wREFLANaux = bdREFLAN;
          wCODNATaux = bdCODNAT;
          wcodopdapiaux = bdcodopdapi;

          IF ((WCHAVEAUX <> WBDCHAVE) OR (WORDEMAUX <> WBDORDEM)) THEN
            BEGIN
              wVLRCONTABaux = wVLRCONTABaux + bdVLRCONTAB;
              wBASEICMSaux = wBASEICMSaux + bdBASEICMS;
              wVLRICMSaux = wVLRICMSaux + bdVLRICMS;
              wisentasicmsaux = wisentasicmsaux + bdisentasicms;
              wVLRSTaux = wVLRSTaux + bdVLRST;
              WOUTRASIPIST = WOUTRASIPIST + WBDOUTRASIPIST;
            END

          WCHAVEAUX = WBDCHAVE;
          WORDEMAUX = WBDORDEM;

          WIMPAPCREDDAPIAUX = WIMPAPCREDDAPIAUX + BDIMPAPCREDDAPI;
          WISENTASDAPIAUX = WISENTASDAPIAUX + BDISENTASDAPI;
          WNTRIBDAPIAUX = WNTRIBDAPIAUX + BDNTRIBDAPI;
          WPARBCCREDDAPIAUX = WPARBCCREDDAPIAUX + BDPARBCCREDDAPI;
          WDIFERIDASTDAPIAUX = WDIFERIDASTDAPIAUX + BDDIFERIDASTDAPI;
          WSUSPENSASDAPIAUX = WSUSPENSASDAPIAUX + BDSUSPENSASDAPI;
          WSTDAPIAUX = WSTDAPIAUX + BDSTDAPI;
          WOUTRASDAPIAUX = WOUTRASDAPIAUX + BDOUTRASDAPI;
       END
    ELSE
       BEGIN
          wcodempaux2 = bdcodemp;
          wREFLANaux2 = bdREFLAN;
          wCODNATaux2 = bdCODNAT;
          wcodopdapiaux2 = bdcodopdapi;
          wVLRCONTABaux2 = bdVLRCONTAB;
          wBASEICMSaux2 = bdBASEICMS;
          wVLRICMSaux2 = bdVLRICMS;
          wisentasicmsaux2 = bdisentasicms;
          wVLRSTaux2 = bdVLRST;
          WOUTRASIPIST2 = WBDOUTRASIPIST;
          WIMPAPCREDDAPIAUX2 = BDIMPAPCREDDAPI;
          WISENTASDAPIAUX2 = BDISENTASDAPI;
          WNTRIBDAPIAUX2 = BDNTRIBDAPI;
          WPARBCCREDDAPIAUX2 = BDPARBCCREDDAPI;
          WDIFERIDASTDAPIAUX2 = BDDIFERIDASTDAPI;
          WSUSPENSASDAPIAUX2 = BDSUSPENSASDAPI;
          WSTDAPIAUX2 = BDSTDAPI;
          WOUTRASDAPIAUX2 = BDOUTRASDAPI;

          bdcodemp = wcodempaux;
          bdREFLAN = wREFLANaux;
          bdCODNAT = wCODNATaux;
          bdcodopdapi = wcodopdapiaux;
          bdVLRCONTAB = wVLRCONTABaux;
          bdBASEICMS = wBASEICMSaux;
          bdVLRICMS = wVLRICMSaux;
          bdisentasicms = wisentasicmsaux;
          bdVLRST = wVLRSTaux;
          WBDOUTRASIPIST = WOUTRASIPIST;
          BDIMPAPCREDDAPI = WIMPAPCREDDAPIAUX;
          BDISENTASDAPI = WISENTASDAPIAUX;
          BDNTRIBDAPI = WNTRIBDAPIAUX;
          BDPARBCCREDDAPI = WPARBCCREDDAPIAUX;
          BDDIFERIDASTDAPI = WDIFERIDASTDAPIAUX;
          BDSUSPENSASDAPI = WSUSPENSASDAPIAUX;
          BDSTDAPI = WSTDAPIAUX;
          BDOUTRASDAPI = WOUTRASDAPIAUX;

          SUSPEND;

          wcodempaux = wcodempaux2;
          wREFLANaux = wREFLANaux2;
          wCODNATaux = wCODNATaux2;
          wcodopdapiaux = wcodopdapiaux2;
          WCHAVEAUX = WBDCHAVE;
          WORDEMAUX = WBDORDEM;
          wVLRCONTABaux = wVLRCONTABaux2;
          wBASEICMSaux = wBASEICMSaux2;
          wVLRICMSaux = wVLRICMSaux2;
          wisentasicmsaux = wisentasicmsaux2;
          wVLRSTaux = wVLRSTaux2;
          WOUTRASIPIST = WOUTRASIPIST2;
          WIMPAPCREDDAPIAUX = WIMPAPCREDDAPIAUX2;
          WISENTASDAPIAUX = WISENTASDAPIAUX2;
          WNTRIBDAPIAUX = WNTRIBDAPIAUX2;
          WPARBCCREDDAPIAUX = WPARBCCREDDAPIAUX2;
          WDIFERIDASTDAPIAUX = WDIFERIDASTDAPIAUX2;
          WSUSPENSASDAPIAUX = WSUSPENSASDAPIAUX2;
          WSTDAPIAUX = WSTDAPIAUX2;
          WOUTRASDAPIAUX = WOUTRASDAPIAUX2;
       END
  END

  IF (WIMPRIMIRFINAL = 1) THEN
    BEGIN
      bdcodemp = wcodempaux;
      bdREFLAN = wREFLANaux;
      bdCODNAT = wCODNATaux;
      bdcodopdapi = wcodopdapiaux;
      bdVLRCONTAB = wVLRCONTABaux;
      bdBASEICMS = wBASEICMSaux;
      bdVLRICMS = wVLRICMSaux;
      bdisentasicms = wisentasicmsaux;
      bdVLRST = wVLRSTaux;
--      WBDOUTRASIPIST = WOUTRASIPIST;
      BDIMPAPCREDDAPI = WIMPAPCREDDAPIAUX;
      BDISENTASDAPI = WISENTASDAPIAUX;
      BDNTRIBDAPI = WNTRIBDAPIAUX;
      BDPARBCCREDDAPI = WPARBCCREDDAPIAUX;
      BDDIFERIDASTDAPI = WDIFERIDASTDAPIAUX;
      BDSUSPENSASDAPI = WSUSPENSASDAPIAUX;
      BDSTDAPI = WSTDAPIAUX;
      BDOUTRASDAPI = WOUTRASDAPIAUX;

      SUSPEND;
  END

END
^

/* Restore proc. body: SP_VEF_DAS_TOTALIZADOR_UF */
create or alter procedure SP_VEF_DAS_TOTALIZADOR_UF (
    PREMP varchar(3000),
    PRDATAINI varchar(10),
    PRDATAFIM varchar(10),
    PRREF integer,
    PRREGIMECAIXA varchar(5))
returns (
    BDCODEMP integer,
    BDSIGLAUF varchar(2),
    BDNOMCID varchar(40),
    BDCODBASESN integer,
    BDVLRBASE numeric(18,2),
    BDCODFED integer,
    BDCODTIPOIMPPIS integer,
    BDCODTIPOIMPCOFINS integer,
    BDCODTIPOIMPCSLL integer,
    BDCODTIPOIMPICMS integer,
    BDCODTIPOIMPINSSCPP integer,
    BDCODTIPOIMPIRPJ integer,
    BDCODTIPOIMPIPI integer,
    BDCODTIPOIMPISS integer)
as
declare variable WSOBRAS numeric(15,2);
declare variable WCONT integer;
declare variable WSQL varchar(32750);
declare variable WTOTAL numeric(18,2);
declare variable WSOMADASBASES numeric(18,2);
declare variable WANULACAO numeric(18,2);
declare variable WBASEATUAL integer;
declare variable WANULACAOSOBRA numeric(18,2);
declare variable WBASEANULA numeric(18,2);
declare variable WCOUNTTOTAL integer;
declare variable WSOMATOTAL numeric(18,2);
BEGIN
--coalesce(sn.bdcodtipoimppis,1) bdcodtipoimppis, coalesce(sn.bdcodtipoimpcofins,1) bdcodtipoimpcofins,
--coalesce(sn.bdcodtipoimpcsll,1) bdcodtipoimpcsll, iif(coalesce(sn.bdcodtipoimpicms,1) = 6,5,coalesce(sn.bdcodtipoimpicms,1)) bdcodtipoimpicms,
--coalesce(sn.bdcodtipoimpinsscpp,1) bdcodtipoimpinsscpp,coalesce(sn.bdcodtipoimpirpj,1) bdcodtipoimpirpj ,
--coalesce(sn.bdcodtipoimpipi,1) bdcodtipoimpipi, coalesce(sn.bdcodtipoimpiss,1) bdcodtipoimpiss,


-- BDCODTIPOIMPPIS, BDCODTIPOIMPCOFINS, BDCODTIPOIMPCSLL, BDCODTIPOIMPICMS,
-- BDCODTIPOIMPINSSCPP, BDCODTIPOIMPIRPJ, BDCODTIPOIMPIPI, BDCODTIPOIMPISS

  wSQL =         'SELECT tot.BDCODEMP, tot.BDSIGLAUF, tot.BDNOMCID, tot.BDCODFED, tot.BDCODBASESN, SUM(IIF(tot.BDVLRBASE >= tot.BDVLRANULACAO, (tot.BDVLRBASE - tot.BDVLRANULACAO), 0)) BDVLRBASE, SUM(tot.BDVLRANULACAO) BDVLRANULACAO, ';
 /* 180272 -- foi feito um Colesce nos codigos de impostos porque na TSimplesNacionalMGR.GravarLancamentosCalculo ele tambem faz esse coalesce e depois aplica um filtro no dao comparando todos os codigos de impostos aonde nao trazia os valores pois estava um codigo com Null e outro com 1 */
  wSQL = wSQL || ' COALESCE(tot.BDCODTIPOIMPPIS, 1)BDCODTIPOIMPPIS, COALESCE(tot.BDCODTIPOIMPCOFINS, 1)BDCODTIPOIMPCOFINS, COALESCE(tot.BDCODTIPOIMPCSLL, 1)BDCODTIPOIMPCSLL, COALESCE(tot.BDCODTIPOIMPICMS, 1)BDCODTIPOIMPICMS, COALESCE(tot.BDCODTIPOIMPINSSCPP, 1)BDCODTIPOIMPINSSCPP, ';
  wSQL = wSQL || ' COALESCE(tot.BDCODTIPOIMPIRPJ, 1)BDCODTIPOIMPIRPJ, COALESCE(tot.BDCODTIPOIMPIPI, 1)BDCODTIPOIMPIPI, COALESCE(tot.BDCODTIPOIMPISS, 1)BDCODTIPOIMPISS ';
  wSQL = wSQL || 'FROM ( ';
  wSQL = wSQL ||        'SELECT sai.BDCODEMP, sai.BDSIGLAUF, sai.BDNOMCID, sai.BDCODFED, sai.BDCODBASESN, SUM(sai.BDVLRBASE) BDVLRBASE, 0 BDVLRANULACAO, ';
  wSQL = wSQL ||               'sai.BDCODTIPOIMPPIS, sai.BDCODTIPOIMPCOFINS, sai.BDCODTIPOIMPCSLL, sai.BDCODTIPOIMPICMS, sai.BDCODTIPOIMPINSSCPP, ';
  wSQL = wSQL ||               'sai.BDCODTIPOIMPIRPJ, sai.BDCODTIPOIMPIPI, sai.BDCODTIPOIMPISS ';
  wSQL = wSQL ||        'FROM ( ';
  wSQL = wSQL ||               'SELECT sai.BDCODEMP, sai.BDCHAVE, sai.BDORDEM, sai.BDCODTER, sai.BDCODBASESN, sai.BDVLRBASE, cid.BDNOMCID, cid.BDCODFED, uf.BDSIGLAUF, ';
  wSQL = wSQL ||               '       sai.BDCODTIPOIMPPIS, sai.BDCODTIPOIMPCOFINS, sai.BDCODTIPOIMPCSLL, sai.BDCODTIPOIMPICMS, sai.BDCODTIPOIMPINSSCPP, ';
  wSQL = wSQL ||               '       sai.BDCODTIPOIMPIRPJ, sai.BDCODTIPOIMPIPI, sai.BDCODTIPOIMPISS ';
  wSQL = wSQL ||               'FROM ( ';
  IF (:PRREGIMECAIXA = 'TRUE') THEN
    BEGIN
      wSQL = wSQL ||                  'SELECT SAI.BDCODEMP, SAI.BDCHAVE, SAIITENS.BDORDEM, SAI.BDCODTER, SAI.BDCODCID, PAR.BDCODBASESN, ';
      wSQL = wSQL ||                  '       SUM(COALESCE(PAR.BDVALORPGTOPAR, 0) + COALESCE(PAR.BDVALORRETPIS, 0) + COALESCE(PAR.BDVALORRETCOFINS, 0) + ';
      wSQL = wSQL ||                  '           COALESCE(PAR.BDVALORRETCSLL, 0) + COALESCE(PAR.BDVALORRETIRRF, 0) + COALESCE(PAR.BDVALORRETISSQN, 0) + ';
      wSQL = wSQL ||                  '           COALESCE(PAR.BDVALORRETINSS, 0)) BDVLRBASE, ';
      wSQL = wSQL ||                  '       PAR.BDCODTIPOIMPPIS, PAR.BDCODTIPOIMPCOFINS, PAR.BDCODTIPOIMPCSLL, PAR.BDCODTIPOIMPICMS, PAR.BDCODTIPOIMPINSSCPP, ';
      wSQL = wSQL ||                  '       PAR.BDCODTIPOIMPIRPJ, PAR.BDCODTIPOIMPIPI, PAR.BDCODTIPOIMPISS ';
      wSQL = wSQL ||                  'FROM (SELECT BDCODEMP, BDCHAVE, BDCODBASESN, BDVALORPGTOPAR, BDVALORRETPIS, BDVALORRETCOFINS, ';
      wSQL = wSQL ||                  '             BDVALORRETCSLL, BDVALORRETIRRF, BDVALORRETISSQN, BDVALORRETINSS, ';
      wSQL = wSQL ||                  '             BDCODTIPOIMPPIS, BDCODTIPOIMPCOFINS, BDCODTIPOIMPCSLL, BDCODTIPOIMPICMS, BDCODTIPOIMPINSSCPP, ';
      wSQL = wSQL ||                  '             BDCODTIPOIMPIRPJ, BDCODTIPOIMPIPI, BDCODTIPOIMPISS ';
      wSQL = wSQL ||                  '      FROM VEF_EMP_TMOVSAIPARPGTO ';
      wSQL = wSQL ||                  '      WHERE '||PREMP;
      wSQL = wSQL ||                  '        AND BDDATAPGTOPAR BETWEEN '''||PRDATAINI||''' AND '''||PRDATAFIM||'''';
      wSQL = wSQL ||                  '      ) PAR ';
      wSQL = wSQL ||                  'JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = PAR.BDCODEMP AND SAI.BDCHAVE = PAR.BDCHAVE) ';
      wSQL = wSQL ||                  'JOIN VEF_EMP_TMOVSAIITENS SAIITENS ON (SAIITENS.BDCODEMP = SAI.BDCODEMP AND SAIITENS.BDCHAVE = SAI.BDCHAVE) ';
      wSQL = wSQL ||                  'JOIN VEF_BASE_TNATOP NAT ON (SAIITENS.BDCODNAT = NAT.BDCODNAT) ';
      wSQL = wSQL ||                  'WHERE PAR.BDCODBASESN IN (18, 19, 20, 21, 22, 23, 24) AND ';
      wSQL = wSQL ||                  '      NAT.BDNAOLEVARSN <> ''TRUE'' AND ';
      wSQL = wSQL ||                  '     (SAI.BDCODSITNF NOT IN (2, 3, 4, 5)) ';
      wSQL = wSQL ||                  'GROUP BY SAI.BDCODEMP, SAI.BDCHAVE, SAIITENS.BDORDEM, SAI.BDCODTER, SAI.BDCODCID, PAR.BDCODBASESN, ';
      wSQL = wSQL ||                  '       PAR.BDCODTIPOIMPPIS, PAR.BDCODTIPOIMPCOFINS, PAR.BDCODTIPOIMPCSLL, PAR.BDCODTIPOIMPICMS, PAR.BDCODTIPOIMPINSSCPP, ';
      wSQL = wSQL ||                  '       PAR.BDCODTIPOIMPIRPJ, PAR.BDCODTIPOIMPIPI, PAR.BDCODTIPOIMPISS ';
      wSQL = wSQL ||                  ' UNION ALL ';
    END


  wSQL = wSQL ||                  'SELECT sai.BDCODEMP, sai.BDCHAVE, saiitens.BDORDEM, sai.BDCODTER, sai.BDCODCID, sn.BDCODBASESN, SUM(sn.BDVLRBASE) BDVLRBASE, ';
  wSQL = wSQL ||                  '       sn.BDCODTIPOIMPPIS, sn.BDCODTIPOIMPCOFINS, sn.BDCODTIPOIMPCSLL, sn.BDCODTIPOIMPICMS, sn.BDCODTIPOIMPINSSCPP, ';
  wSQL = wSQL ||                  '       sn.BDCODTIPOIMPIRPJ, sn.BDCODTIPOIMPIPI, sn.BDCODTIPOIMPISS ';
  wSQL = wSQL ||                  'FROM ( ';
  wSQL = wSQL ||                         'SELECT BDCODEMP, BDCHAVE, BDCODTER, BDCODCID ';
  wSQL = wSQL ||                         'FROM VEF_EMP_TMOVSAI ';
  wSQL = wSQL ||                         'WHERE '||PREMP;
  wSQL = wSQL ||                           'AND (BDCODSITNF NOT IN (2,3,4,5) ) ';
  wSQL = wSQL ||                           'AND BDDATAEMISSAO BETWEEN '''||PRDATAINI||''' AND '''||PRDATAFIM||'''';     
  IF (:PRREGIMECAIXA = 'TRUE') THEN               
    wSQL = wSQL ||                         ' AND BDCONDPGTO <> 1 ';

  wSQL = wSQL ||                        ') SAI ';
  wSQL = wSQL ||                  'JOIN VEF_EMP_TMOVSAIITENS saiitens ON (saiitens.BDCODEMP = sai.BDCODEMP and saiitens.BDCHAVE = sai.BDCHAVE) ';
  wSQL = wSQL ||                  'JOIN VEF_BASE_TNATOP nat ON (saiitens.BDCODNAT = nat.BDCODNAT) ';
  wSQL = wSQL ||                  'JOIN VEF_EMP_TMOVSAISN sn ON (sn.BDCODEMP = sai.BDCODEMP AND sn.BDCHAVE = sai.BDCHAVE and sn.BDORDEM = saiitens.BDORDEM) ';
  wSQL = wSQL ||                  'WHERE sn.BDCODBASESN IN (18, 19, 20, 21, 22, 23, 24) ';
  wSQL = wSQL ||                    'AND nat.BDNAOLEVARSN <> ''TRUE'' ';
  wSQL = wSQL ||                  'GROUP BY sai.BDCODEMP, sai.BDCHAVE, saiitens.BDORDEM, sai.BDCODTER, sai.BDCODTER, SAI.BDCODCID, sn.BDCODBASESN, ';
  wSQL = wSQL ||                  '         sn.BDCODTIPOIMPPIS, sn.BDCODTIPOIMPCOFINS, sn.BDCODTIPOIMPCSLL, sn.BDCODTIPOIMPICMS, sn.BDCODTIPOIMPINSSCPP, ';
  wSQL = wSQL ||                  '         sn.BDCODTIPOIMPIRPJ, sn.BDCODTIPOIMPIPI, sn.BDCODTIPOIMPISS ';

  wSQL = wSQL ||                     ') sai ';
  wSQL = wSQL ||               'LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES ter ON (sai.BDCODTER = ter.BDCODTER) ';
  wSQL = wSQL ||               'LEFT OUTER JOIN TCIDADE cid on (sai.BDCODCID = cid.BDCODCID) ';
  wSQL = wSQL ||               'LEFT OUTER JOIN TUF uf ON (cid.BDCODUF = uf.BDCODUF) ';
  wSQL = wSQL ||              ') sai ';
  wSQL = wSQL ||        'GROUP BY sai.BDCODEMP, sai.BDSIGLAUF, sai.BDNOMCID, sai.BDCODFED, sai.BDCODBASESN, ';
  wSQL = wSQL ||        '       sai.BDCODTIPOIMPPIS, sai.BDCODTIPOIMPCOFINS, sai.BDCODTIPOIMPCSLL, sai.BDCODTIPOIMPICMS, sai.BDCODTIPOIMPINSSCPP, ';
  wSQL = wSQL ||        '       sai.BDCODTIPOIMPIRPJ, sai.BDCODTIPOIMPIPI, sai.BDCODTIPOIMPISS ';
  wSQL = wSQL ||        'UNION ALL ';
  wSQL = wSQL ||        'SELECT deb.BDCODEMP, deb.BDSIGLAUF, null as BDNOMCID, null as BDCODFED, deb.BDCODBASESN, 0 as BDVLRBASE, SUM(deb.BDVALORDEB) as BDVLRANULACAO, ';
  wSQL = wSQL ||        '       deb.BDCODTIPOIMPPIS, deb.BDCODTIPOIMPCOFINS, deb.BDCODTIPOIMPCSLL, deb.BDCODTIPOIMPICMS, deb.BDCODTIPOIMPINSSCPP, ';
  wSQL = wSQL ||        '       deb.BDCODTIPOIMPIRPJ, deb.BDCODTIPOIMPIPI, deb.BDCODTIPOIMPISS ';
  wSQL = wSQL ||        'FROM ( ';
  wSQL = wSQL ||               'SELECT deb.BDCODEMP, uf.BDSIGLAUF, deb.BDCODBASESN, deb.BDVALORDEB, ';
  wSQL = wSQL ||               '       deb.BDCODTIPOIMPPIS, deb.BDCODTIPOIMPCOFINS, deb.BDCODTIPOIMPCSLL, deb.BDCODTIPOIMPICMS, deb.BDCODTIPOIMPINSSCPP, ';
  wSQL = wSQL ||               '       deb.BDCODTIPOIMPIRPJ, deb.BDCODTIPOIMPIPI, deb.BDCODTIPOIMPISS ';
  wSQL = wSQL ||               'FROM VEF_EMP_TPLANILHASNDEB deb ';
  wSQL = wSQL ||               'LEFT OUTER JOIN TUF uf ON (uf.BDCODUF = deb.BDCODUF) ';
  wSQL = wSQL ||               'WHERE deb.'||PREMP;
  wSQL = wSQL ||                 'AND deb.BDREFERENCIA = '||PRREF;
  wSQL = wSQL ||              ') deb ';
  wSQL = wSQL ||        'GROUP BY deb.BDCODEMP, deb.BDSIGLAUF, deb.BDCODBASESN, ';
  wSQL = wSQL ||        '         deb.BDCODTIPOIMPPIS, deb.BDCODTIPOIMPCOFINS, deb.BDCODTIPOIMPCSLL, deb.BDCODTIPOIMPICMS, deb.BDCODTIPOIMPINSSCPP, ';
  wSQL = wSQL ||        '         deb.BDCODTIPOIMPIRPJ, deb.BDCODTIPOIMPIPI, deb.BDCODTIPOIMPISS ';
  wSQL = wSQL ||        'UNION ALL '; /* Descontar base de cfop de anulação das entradas */
  wSQL = wSQL ||        'select ENT.BDCODEMP, ENT.BDSIGLAUF, ENT.BDNOMCID, ent.BDCODFED, ENT.BDCODBASESN, 0 BDVLRBASE, sum(ENT.BDVLRBASE) BDVLRANULACAO, ';
  wSQL = wSQL ||        '       ENT.BDCODTIPOIMPPIS, ENT.BDCODTIPOIMPCOFINS, ENT.BDCODTIPOIMPCSLL, ENT.BDCODTIPOIMPICMS, ENT.BDCODTIPOIMPINSSCPP, ';
  wSQL = wSQL ||        '       ENT.BDCODTIPOIMPIRPJ, ENT.BDCODTIPOIMPIPI, ENT.BDCODTIPOIMPISS ';
  wSQL = wSQL ||        'from ( ';
  wSQL = wSQL ||               'select ENT.BDCODEMP, ENT.BDCHAVE, ENT.BDORDEM, ENT.BDCODTER, ENT.BDCODBASESN, ENT.BDVLRBASE, CID.BDNOMCID, cid.BDCODFED,  UF.BDSIGLAUF, ';
  wSQL = wSQL ||               '       ENT.BDCODTIPOIMPPIS, ENT.BDCODTIPOIMPCOFINS, ENT.BDCODTIPOIMPCSLL, ENT.BDCODTIPOIMPICMS, ENT.BDCODTIPOIMPINSSCPP, ';
  wSQL = wSQL ||               '       ENT.BDCODTIPOIMPIRPJ, ENT.BDCODTIPOIMPIPI, ENT.BDCODTIPOIMPISS ';
  wSQL = wSQL ||               'from ( ';
  IF (:PRREGIMECAIXA = 'TRUE') THEN
    BEGIN      
      wSQL = wSQL ||                  'SELECT ENT.BDCODEMP, ENT.BDCHAVE, ENTITENS.BDORDEM, ENT.BDCODTER, PAR.BDCODBASESN, ';
      wSQL = wSQL ||                  '       SUM(COALESCE(PAR.BDVALORPGTOPAR, 0) + COALESCE(PAR.BDVALORRETPIS, 0) + COALESCE(PAR.BDVALORRETCOFINS, 0) + ';
      wSQL = wSQL ||                  '           COALESCE(PAR.BDVALORRETCSLL, 0) + COALESCE(PAR.BDVALORRETIRRF, 0) + COALESCE(PAR.BDVALORRETISSQN, 0) + ';
      wSQL = wSQL ||                  '           COALESCE(PAR.BDVALORRETINSS, 0)) BDVLRBASE, ';
      wSQL = wSQL ||                  '       PAR.BDCODTIPOIMPPIS, PAR.BDCODTIPOIMPCOFINS, PAR.BDCODTIPOIMPCSLL, PAR.BDCODTIPOIMPICMS, PAR.BDCODTIPOIMPINSSCPP, ';
      wSQL = wSQL ||                  '       PAR.BDCODTIPOIMPIRPJ, PAR.BDCODTIPOIMPIPI, PAR.BDCODTIPOIMPISS ';
      wSQL = wSQL ||                  'FROM (SELECT BDCODEMP, BDCHAVE, BDCODBASESN, BDVALORPGTOPAR, BDVALORRETPIS, BDVALORRETCOFINS, ';
      wSQL = wSQL ||                  '             BDVALORRETCSLL, BDVALORRETIRRF, BDVALORRETISSQN, BDVALORRETINSS, ';
      wSQL = wSQL ||                  '             BDCODTIPOIMPPIS, BDCODTIPOIMPCOFINS, BDCODTIPOIMPCSLL, BDCODTIPOIMPICMS, BDCODTIPOIMPINSSCPP, ';
      wSQL = wSQL ||                  '             BDCODTIPOIMPIRPJ, BDCODTIPOIMPIPI, BDCODTIPOIMPISS ';
      wSQL = wSQL ||                  '      FROM VEF_EMP_TMOVENTPARPGTO ';
      wSQL = wSQL ||                  '      WHERE '||PREMP;
      wSQL = wSQL ||                  '        AND BDDATAPGTOPAR BETWEEN '''||PRDATAINI||''' AND '''||PRDATAFIM||'''';
      wSQL = wSQL ||                  '      ) PAR ';
      wSQL = wSQL ||                  'JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = PAR.BDCODEMP AND ENT.BDCHAVE = PAR.BDCHAVE) ';
      wSQL = wSQL ||                  'JOIN VEF_EMP_TMOVENTITENS ENTITENS ON (ENTITENS.BDCODEMP = ENT.BDCODEMP AND ENTITENS.BDCHAVE = ENT.BDCHAVE) ';
      wSQL = wSQL ||                  'JOIN VEF_BASE_TNATOP NAT ON (ENTITENS.BDCODNAT = NAT.BDCODNAT) ';
      wSQL = wSQL ||                  'WHERE PAR.BDCODBASESN IN (18, 19, 20, 21, 22, 23, 24) AND ';
      wSQL = wSQL ||                  '      NAT.BDNAOLEVARSN <> ''TRUE'' AND ';
      wSQL = wSQL ||                  '     (ENT.BDCODSITNF NOT IN (2,3,4,5)) ';
      wSQL = wSQL ||                  'GROUP BY ENT.BDCODEMP, ENT.BDCHAVE, ENTITENS.BDORDEM, ENT.BDCODTER, PAR.BDCODBASESN, ';
      wSQL = wSQL ||                  '       PAR.BDCODTIPOIMPPIS, PAR.BDCODTIPOIMPCOFINS, PAR.BDCODTIPOIMPCSLL, PAR.BDCODTIPOIMPICMS, PAR.BDCODTIPOIMPINSSCPP, ';
      wSQL = wSQL ||                  '       PAR.BDCODTIPOIMPIRPJ, PAR.BDCODTIPOIMPIPI, PAR.BDCODTIPOIMPISS ';
      wSQL = wSQL ||                  ' UNION ALL ';
    END


  wSQL = wSQL ||                      'select ENT.BDCODEMP, ENT.BDCHAVE, ENTITENS.BDORDEM, ENT.BDCODTER, SN.BDCODBASESN, sum(SN.BDVLRBASE) BDVLRBASE, ';
  wSQL = wSQL ||                      '       SN.BDCODTIPOIMPPIS, SN.BDCODTIPOIMPCOFINS, SN.BDCODTIPOIMPCSLL, SN.BDCODTIPOIMPICMS, SN.BDCODTIPOIMPINSSCPP, ';
  wSQL = wSQL ||                      '       SN.BDCODTIPOIMPIRPJ, SN.BDCODTIPOIMPIPI, SN.BDCODTIPOIMPISS ';
  wSQL = wSQL ||                      'from ( ';
  wSQL = wSQL ||                             'select BDCODEMP, BDCHAVE, BDCODTER ';
  wSQL = wSQL ||                             'from VEF_EMP_TMOVENT ';
  wSQL = wSQL ||                             'where '||PREMP;
  wSQL = wSQL ||                               'and (BDCODSITNF not in (2,3,4,5) ) ';
  wSQL = wSQL ||                               'and BDDATAENTRADAENT between '''||PRDATAINI||''' and '''||PRDATAFIM||'''';            
  IF (:PRREGIMECAIXA = 'TRUE') THEN               
    wSQL = wSQL ||                         ' AND BDCONDPGTO <> 1 ';
  wSQL = wSQL ||                            ') ENT ';
  wSQL = wSQL ||                      'join VEF_EMP_TMOVENTITENS ENTITENS on (ENTITENS.BDCODEMP = ENT.BDCODEMP and ENTITENS.BDCHAVE = ENT.BDCHAVE) ';
  wSQL = wSQL ||                      'join VEF_BASE_TNATOP NAT on (ENTITENS.BDCODNAT = NAT.BDCODNAT) ';
  wSQL = wSQL ||                      'join VEF_EMP_TMOVENTSN SN on (SN.BDCODEMP = ENT.BDCODEMP and SN.BDCHAVE = ENT.BDCHAVE and SN.BDORDEM = ENTITENS.BDORDEM) ';
  wSQL = wSQL ||                      'where SN.BDCODBASESN in (18, 19, 20, 21, 22, 23, 24) ';
  wSQL = wSQL ||                        'and NAT.BDNAOLEVARSN <> ''TRUE'' ';
  wSQL = wSQL ||                      'group by ENT.BDCODEMP, ENT.BDCHAVE, ENTITENS.BDORDEM, ENT.BDCODTER, SN.BDCODBASESN, ';
  wSQL = wSQL ||                      '         SN.BDCODTIPOIMPPIS, SN.BDCODTIPOIMPCOFINS, SN.BDCODTIPOIMPCSLL, SN.BDCODTIPOIMPICMS, SN.BDCODTIPOIMPINSSCPP, ';
  wSQL = wSQL ||                      '         SN.BDCODTIPOIMPIRPJ, SN.BDCODTIPOIMPIPI, SN.BDCODTIPOIMPISS ';

  wSQL = wSQL ||                     ') ENT ';
  wSQL = wSQL ||               'left outer join VW_TTERCEIRO_SIMPLES TER on (ENT.BDCODTER = TER.BDCODTER) ';
  wSQL = wSQL ||               'left outer join TCIDADE CID on (TER.BDCODCID = CID.BDCODCID) ';
  wSQL = wSQL ||               'left outer join TUF UF on (CID.BDCODUF = UF.BDCODUF) ';
  wSQL = wSQL ||              ') ENT ';
  wSQL = wSQL ||        'group by ENT.BDCODEMP, ENT.BDSIGLAUF, ENT.BDNOMCID, ent.BDCODFED, ENT.BDCODBASESN, ';
  wSQL = wSQL ||        '         ENT.BDCODTIPOIMPPIS, ENT.BDCODTIPOIMPCOFINS, ENT.BDCODTIPOIMPCSLL, ENT.BDCODTIPOIMPICMS, ENT.BDCODTIPOIMPINSSCPP, ';
  wSQL = wSQL ||        '         ENT.BDCODTIPOIMPIRPJ, ENT.BDCODTIPOIMPIPI, ENT.BDCODTIPOIMPISS ';
  
  --DEMAIS DOCUMENTOS
  WSQL = WSQL || ' UNION ALL';
  WSQL = WSQL || ' SELECT BDCODEMP, BDSIGLAUF, BDNOMCID, BDCODFED, BDCODBASESN, SUM(BDVLRBASE) BDVLRBASE, 0 BDVLRANULACAO, BDCODTIPOIMPPIS,';
  WSQL = WSQL || '        BDCODTIPOIMPCOFINS, BDCODTIPOIMPCSLL, BDCODTIPOIMPICMS, BDCODTIPOIMPINSSCPP, BDCODTIPOIMPIRPJ, BDCODTIPOIMPIPI,';
  WSQL = WSQL || '        BDCODTIPOIMPISS';
  WSQL = WSQL || ' FROM (SELECT VDOC.BDCODEMP, VDOC.BDCHAVE, 0 AS BDORDEM, DEM.BDCODTER, VDOC.BDCODCIDADE, VDOC.BDBASE BDCODBASESN,';
  WSQL = WSQL || '              SUM(VDOC.BDVALOR) BDVLRBASE, VDOC.BDCODTIPOIMPPIS, VDOC.BDCODTIPOIMPCOFINS, VDOC.BDCODTIPOIMPCSLL,';
  WSQL = WSQL || '              VDOC.BDCODTIPOIMPICMS, VDOC.BDCODTIPOIMPINSSCPP, VDOC.BDCODTIPOIMPIRPJ, VDOC.BDCODTIPOIMPIPI,';
  WSQL = WSQL || '              VDOC.BDCODTIPOIMPISS, VDOC.BDSIGLAUF, CID.BDNOMCID, CID.BDCODFED';
  WSQL = WSQL || '       FROM (SELECT *';
  WSQL = WSQL || '             FROM VEF_EMP_TMOVDEMAISDOC_F100 DEM';
  WSQL = WSQL || '             WHERE ' || :PREMP || ' AND';
  WSQL = WSQL || '                   DEM.BDDT_OPER BETWEEN ''' || :PRDATAINI || ''' AND ''' || :PRDATAFIM || ''') DEM';
  WSQL = WSQL || '       INNER JOIN VEF_EMP_TVDOC VDOC ON (VDOC.BDCODEMP = DEM.BDCODEMP AND';
  WSQL = WSQL || '             VDOC.BDCHAVE = DEM.BDCHAVE)';
  WSQL = WSQL || '       INNER JOIN TCIDADE CID ON (VDOC.BDCODCIDADE = CID.BDCODCID)';
  WSQL = WSQL || '       INNER JOIN VEF_EMP_TSIMPLESNACIONAL SN ON (VDOC.BDCODEMP = SN.BDCODEMP AND';
  WSQL = WSQL || '             VDOC.BDCODIMP = SN.BDCODIMP AND';
  WSQL = WSQL || '             VDOC.BDREFERENCIA = SN.BDREFERENCIA AND';
  WSQL = WSQL || '             VDOC.BDORDEM = SN.BDORDEM AND';
  WSQL = WSQL || '             VDOC.BDORDEMCOMPL = SN.BDORDEMCOMPL)';
  WSQL = WSQL || '       GROUP BY BDCODEMP, BDCHAVE, BDORDEM, BDCODTER, BDCODTER, BDCODCIDADE, BDCODBASESN, BDCODTIPOIMPPIS, BDCODTIPOIMPCOFINS, BDCODTIPOIMPCSLL, BDCODTIPOIMPICMS, BDCODTIPOIMPINSSCPP, BDCODTIPOIMPIRPJ, BDCODTIPOIMPIPI, BDCODTIPOIMPISS, BDSIGLAUF, BDNOMCID, BDCODFED)';
  WSQL = WSQL || ' GROUP BY BDCODEMP, BDSIGLAUF, BDNOMCID, BDCODFED, BDCODBASESN, BDCODTIPOIMPPIS, BDCODTIPOIMPCOFINS, BDCODTIPOIMPCSLL, BDCODTIPOIMPICMS, BDCODTIPOIMPINSSCPP, BDCODTIPOIMPIRPJ, BDCODTIPOIMPIPI, BDCODTIPOIMPISS ';

  wSQL = wSQL ||       ') tot ';
  wSQL = wSQL || 'GROUP BY tot.BDCODEMP, tot.BDSIGLAUF, tot.BDNOMCID, tot.BDCODFED, tot.BDCODBASESN, tot.BDCODTIPOIMPPIS, tot.BDCODTIPOIMPCOFINS, ';
  wSQL = wSQL || '         tot.BDCODTIPOIMPCSLL, tot.BDCODTIPOIMPICMS, tot.BDCODTIPOIMPINSSCPP, tot.BDCODTIPOIMPIRPJ, tot.BDCODTIPOIMPIPI, tot.BDCODTIPOIMPISS ';

  /* Caso tenha valor na variável de anulação, há um valor de anulação maior que as receitas nesta base em algum estado, por isso deve descontar proporcionalmente dos outros estados da mesma base */
  EXECUTE STATEMENT 'SELECT SUM(tot.BDVLRBASE - tot.BDVLRANULACAO) as BDVLRBASE, Count(tot.BDVLRBASE) '||
                    'FROM ( '||wSQL||' ) tot ' INTO :WBASEANULA, :WCOUNTTOTAL;

  --wsobras = wtotal;
  WSOMATOTAL = 0;

  EXECUTE STATEMENT 'SELECT Coalesce(SUM(BDANULACAO),0) FROM '||
                    '(SELECT (sum(tot.BDVLRANULACAO) - SUM(tot.BDVLRBASE)) BDANULACAO '||
                        'FROM ( '||wSQL||' ) tot '||
                    ' GROUP BY tot.BDCODEMP, tot.BDCODBASESN '||
                    ' HAVING sum(tot.BDVLRANULACAO) > SUM(tot.BDVLRBASE)) tot '
  INTO WANULACAOSOBRA; 
  WANULACAOSOBRA = 0;
   
  WBASEATUAL = 0;

  wSQL = 'SELECT tot.BDCODEMP, IIF(tot.BDSIGLAUF = ''EX'',emp.BDSIGLAUF,tot.BDSIGLAUF) BDSIGLAUF, tot.BDNOMCID, tot.BDCODFED, tot.BDCODBASESN, SUM(tot.BDVLRBASE) as BDVLRBASE '||
         ', S.BDCOUNT, S.BDVLRANULACAO, S.BDVLRBASE, tot.BDCODTIPOIMPPIS, tot.BDCODTIPOIMPCOFINS, tot.BDCODTIPOIMPCSLL, tot.BDCODTIPOIMPICMS, tot.BDCODTIPOIMPINSSCPP, tot.BDCODTIPOIMPIRPJ, tot.BDCODTIPOIMPIPI, tot.BDCODTIPOIMPISS '||
                        'FROM ( '||wSQL||' ) tot '||
         'LEFT OUTER JOIN (SELECT tot.BDCODEMP, tot.BDCODBASESN, COUNT(BDVLRBASE) BDCOUNT,'||
         '                        SUM(IIF(tot.BDVLRBASE >= tot.BDVLRANULACAO, 0, tot.BDVLRANULACAO - tot.BDVLRBASE)) as BDVLRANULACAO, '||
         '                        SUM(IIF(tot.BDVLRBASE >= tot.BDVLRANULACAO, (tot.BDVLRBASE - tot.BDVLRANULACAO), 0)) as BDVLRBASE, '||
         '                        tot.BDCODTIPOIMPPIS, tot.BDCODTIPOIMPCOFINS, tot.BDCODTIPOIMPCSLL, tot.BDCODTIPOIMPICMS, tot.BDCODTIPOIMPINSSCPP, '||
         '                        tot.BDCODTIPOIMPIRPJ, tot.BDCODTIPOIMPIPI, tot.BDCODTIPOIMPISS ' ||
         '                 FROM ('||wSQL||') tot '||
         '                 GROUP BY tot.BDCODEMP, tot.BDCODBASESN, '||
         '                          tot.BDCODTIPOIMPPIS, tot.BDCODTIPOIMPCOFINS, tot.BDCODTIPOIMPCSLL, tot.BDCODTIPOIMPICMS, tot.BDCODTIPOIMPINSSCPP, '||
         '                          tot.BDCODTIPOIMPIRPJ, tot.BDCODTIPOIMPIPI, tot.BDCODTIPOIMPISS ' ||
         '                 ) S ON (S.BDCODEMP = TOT.BDCODEMP AND S.BDCODBASESN = TOT.BDCODBASESN AND '||
         '                        S.BDCODTIPOIMPPIS = tot.BDCODTIPOIMPPIS AND S.BDCODTIPOIMPCOFINS = tot.BDCODTIPOIMPCOFINS AND S.BDCODTIPOIMPCSLL = tot.BDCODTIPOIMPCSLL AND '||
         '                        S.BDCODTIPOIMPICMS = tot.BDCODTIPOIMPICMS AND S.BDCODTIPOIMPINSSCPP = tot.BDCODTIPOIMPINSSCPP AND '||
         '                        S.BDCODTIPOIMPIRPJ = tot.BDCODTIPOIMPIRPJ AND S.BDCODTIPOIMPIPI = tot.BDCODTIPOIMPIPI AND S.BDCODTIPOIMPISS = tot.BDCODTIPOIMPISS) ' ||
         'LEFT OUTER JOIN SP_CONSULTAEMPRESAS('||PRREF||', tot.BDCODEMP, null) emp ON (tot.BDCODEMP = emp.BDCODEMP) '||
         'GROUP BY tot.BDCODEMP, IIF(tot.BDSIGLAUF = ''EX'',emp.BDSIGLAUF,tot.BDSIGLAUF), tot.BDNOMCID, tot.BDCODFED, tot.BDCODBASESN, S.BDCOUNT, S.BDVLRANULACAO, S.BDVLRBASE, '||
         'tot.BDCODTIPOIMPPIS, tot.BDCODTIPOIMPCOFINS, tot.BDCODTIPOIMPCSLL, tot.BDCODTIPOIMPICMS, tot.BDCODTIPOIMPINSSCPP, tot.BDCODTIPOIMPIRPJ, tot.BDCODTIPOIMPIPI, tot.BDCODTIPOIMPISS ' ||
         --'ORDER BY tot.BDCODEMP, tot.BDCODBASESN, SUM(tot.BDVLRBASE) '; Alt.: #211364 - Deve ordenar pelas tributacoes, caso contrario, não funciona o calculo ali direito, afinal se funciona-se, nao seria o simples nacional...
         'ORDER BY tot.BDCODEMP, tot.BDCODBASESN, TOT.BDCODTIPOIMPPIS, TOT.BDCODTIPOIMPCOFINS, TOT.BDCODTIPOIMPCSLL, TOT.BDCODTIPOIMPICMS, TOT.BDCODTIPOIMPINSSCPP, '||
                                'TOT.BDCODTIPOIMPIRPJ, TOT.BDCODTIPOIMPIPI, TOT.BDCODTIPOIMPISS, SUM(tot.BDVLRBASE) ';

  FOR EXECUTE STATEMENT wSQL INTO
--  FOR EXECUTE STATEMENT 'SELECT tot.BDCODEMP, tot.BDSIGLAUF, tot.BDNOMCID, tot.BDCODFED, tot.BDCODBASESN, SUM(IIF(tot.BDVLRBASE > tot.BDVLRANULACAO, (tot.BDVLRBASE - tot.BDVLRANULACAO), 0)) as BDVLRBASE '||
--                        ', S.BDCOUNT, S.BDVLRANULACAO, S.BDVLRBASE '||
--                        'FROM ( '||wSQL||' ) tot '||
--                        'LEFT OUTER JOIN (SELECT tot.BDCODEMP, tot.BDCODBASESN, COUNT(BDVLRBASE) BDCOUNT,'||
--                        '                        SUM(IIF(tot.BDVLRBASE > tot.BDVLRANULACAO, 0, tot.BDVLRANULACAO - tot.BDVLRBASE)) as BDVLRANULACAO, '||
--                        '                        SUM(IIF(tot.BDVLRBASE > tot.BDVLRANULACAO, (tot.BDVLRBASE - tot.BDVLRANULACAO), 0)) as BDVLRBASE '||
--                        '                 FROM ('||wSQL||') tot '||
--                        '                 GROUP BY tot.BDCODEMP, tot.BDCODBASESN) S ON (S.BDCODEMP = TOT.BDCODEMP AND S.BDCODBASESN = TOT.BDCODBASESN) '||
--                        'GROUP BY tot.BDCODEMP, tot.BDSIGLAUF, tot.BDNOMCID, tot.BDCODFED, tot.BDCODBASESN, S.BDCOUNT, S.BDVLRANULACAO, S.BDVLRBASE ' INTO
    BDCODEMP, BDSIGLAUF, BDNOMCID, BDCODFED, BDCODBASESN, BDVLRBASE, :wcont, :wANULACAO, :wTOTAL,
    BDCODTIPOIMPPIS, BDCODTIPOIMPCOFINS, BDCODTIPOIMPCSLL, BDCODTIPOIMPICMS,
    BDCODTIPOIMPINSSCPP, BDCODTIPOIMPIRPJ, BDCODTIPOIMPIPI, BDCODTIPOIMPISS DO
  BEGIN
    /* Caso tenha anulacao, desconta do valor da base deste estado a parte proporcional referente a este valor de anulação */
    IF ((wANULACAO > 0) AND (BDVLRBASE > 0)) THEN
      BEGIN
        --BDVLRBASE = BDVLRBASE - :wANULACAO;
        BDVLRBASE = BDVLRBASE - ((BDVLRBASE * wANULACAO) / wTOTAL);
      END

    IF (BDVLRBASE < 0) THEN
      BEGIN
        BDVLRBASE = 0;
      END

    IF (WBASEATUAL = 0) THEN
      BEGIN
        wsobras = :wTOTAL;        
        wsomadasbases = 0;
      END

    wsomadasbases = wsomadasbases + bdvlrbase;
    wsobras = wsobras - bdvlrbase;
    WBASEATUAL = WBASEATUAL + 1;
    WCOUNTTOTAL = WCOUNTTOTAL - 1;

    IF ((WCOUNTTOTAL = 0) AND (WSOMATOTAL <> WBASEANULA)) THEN
      BEGIN
        bdvlrbase = (WBASEANULA - WSOMATOTAL);
      END
    ELSE
    IF ((wcont = WBASEATUAL) AND ((wsobras <> wanulacao) )) THEN
      BEGIN                                       
          bdvlrbase = bdvlrbase + (wTotal - (wsomadasbases+wanulacao) );
      END

    WSOMATOTAL = WSOMATOTAL + BDVLRBASE;

    IF (wcont = WBASEATUAL) THEN
      BEGIN
        WBASEATUAL = 0;
      END

    SUSPEND;
  END
END^


/* Restore proc. body: SP_VEF_EXPREG30_GIASP */
CREATE OR ALTER procedure SP_VEF_EXPREG30_GIASP (
    PRCODEMP varchar(10000),
    PRREFERENCIAINICIAL integer,
    PRREFERENCIAFINAL integer)
returns (
    BDCODEMP integer,
    BDREFERENCIA integer,
    BDCODEST integer,
    BDCODDIPAM varchar(3),
    BDVALOR numeric(18,6),
    BDCODCID integer,
    BDDIPAMB varchar(5))
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WPREFIXONAT integer;
declare variable WCODESTSP integer;
declare variable WSIGLAUF varchar(2);
begin

  execute procedure sp_seta_competencia(PRREFERENCIAFINAL, null, null);

  select first 1 c.bdcodgiars from tuf u,tcidade c where u.bdcoduf = c.bdcoduf and (upper(c.bdnomcid) = 'SÃO PAULO')  and upper(u.bdsiglauf) = 'SP' into WCODESTSP;

  wwhere = '';
  if (:PRCODEMP is not null) then
    wwhere = :PRCODEMP;

  if (:PRREFERENCIAINICIAL is not null) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
--       else
--          wwhere = wwhere||' where ';

       wwhere = wwhere||'M.bdreflan >= '||:PRREFERENCIAINICIAL;

       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||'M.bdreflan <= '||:PRREFERENCIAFINAL;
     end

--  wsql = 'select ent.bdcodemp,ent.bdreflan referencia,null bdprefixonat, ';
--  wsql = wsql||'       upper(ent.bdsiglauf),ent.bdcodest,''1.1'' BDCODDIPAM, ';
--  wsql = wsql||'       (coalesce(ent.bdbaseicms, 0) + coalesce(ent.bdisentasicms, 0) + coalesce(ent.bdoutrasicms, 0)) bdVALOR ';
--  wsql = wsql||'from (select ent.bdcodemp,ent.bdreflan,uf.bdsiglauf,cid.bdcodgiars bdcodest, ';
--  wsql = wsql||'             coalesce(sum(itens.bdbaseicms), 0) bdbaseicms, ';
--  wsql = wsql||'             coalesce(sum(itens.bdisentasicms), 0) bdisentasicms, ';
--  wsql = wsql||'             coalesce(sum(itens.bdoutrasicms), 0) bdoutrasicms ';
--  wsql = wsql||'      from ( select m.* from vef_emp_tmovent m where '||wwhere||' and ( m.bdcodsitnf not in (2,3,4,5) )   ) ent ';
--  wsql = wsql||'      inner join vef_emp_tmoventitens itens on itens.bdcodemp = ent.bdcodemp and itens.bdchave = ent.bdchave and substring(itens.bdprefixonat from 1 for 1) = ''1'' ';
--  wsql = wsql||'      inner join vw_tterceiro ter on ter.bdcodter = ent.bdcodter and upper(ter.bdpruralter) = ''TRUE'' ';
--  wsql = wsql||'      left outer join tcidade cid on cid.bdcodcid = ter.bdcodcid ';
--  wsql = wsql||'      left outer join tuf uf on uf.bdcoduf = cid.bdcoduf and uf.bdsiglauf <> ''EX'' ';
--  wsql = wsql||'      where upper(uf.BDSIGLAUF) = ''SP'' ';
--  wsql = wsql||'        and ( (itens.bdbaseicms > 0) or (itens.bdisentasicms > 0) or (itens.bdoutrasicms > 0) ) ';
--  wsql = wsql||'      group by bdcodemp, bdreflan, bdsiglauf, bdcodest) ent ';

    wsql = 'SELECT ENT.BDCODEMP, ENT.BDREFLAN REFERENCIA, NULL BDPREFIXONAT, UPPER(ENT.BDSIGLAUF), ENT.BDCODEST, ''1.1'' BDCODDIPAM, ';
    wsql = wsql||       '(COALESCE(ENT.BDBASEICMS, 0) + COALESCE(ENT.BDISENTASICMS, 0) + COALESCE(ENT.BDOUTRASICMS, 0)) BDVALOR ';
    wsql = wsql||'FROM (SELECT ENT.BDCODEMP, ENT.BDREFLAN, UF.BDSIGLAUF, CID.BDCODGIARS BDCODEST, ';
    wsql = wsql||             'COALESCE(SUM(ITENS.BDBASEICMS), 0) BDBASEICMS, COALESCE(SUM(ITENS.BDISENTASICMS), 0) BDISENTASICMS, ';
    wsql = wsql||             'COALESCE(SUM(ITENS.BDOUTRASICMS), 0) BDOUTRASICMS ';
    wsql = wsql||      'FROM (SELECT M.* ';
    wsql = wsql||            'FROM VEF_EMP_TMOVENT M ';
    wsql = wsql||            'WHERE '||wwhere||' and ';
    wsql = wsql||                  '(M.BDCODSITNF NOT IN (2, 3, 4, 5))) ENT ';
    wsql = wsql||      'INNER JOIN VEF_EMP_TMOVENTITENS ITENS ON ITENS.BDCODEMP = ENT.BDCODEMP AND ';
    wsql = wsql||            'ITENS.BDCHAVE = ENT.BDCHAVE AND ';
    wsql = wsql||            'SUBSTRING(ITENS.BDPREFIXONAT FROM 1 FOR 1) = ''1'' ';
    wsql = wsql||      'JOIN TTERCEIRO_REF TER ON (TER.BDCODTER = ENT.BDCODTER AND  ';
    wsql = wsql||            'TER.BDREFEMP = COALESCE((SELECT FIRST 1 BDREFEMP ';
    wsql = wsql||                                     'FROM TTERCEIRO_REF RF3 ';
    wsql = wsql||                                     'WHERE RF3.BDCODTER = TER.BDCODTER AND ';
    wsql = wsql||                                           'RF3.BDREFEMP <= '||:PRREFERENCIAFINAL||' ';
    wsql = wsql||                                    ' ORDER BY RF3.BDREFEMP DESC), (SELECT FIRST 1 BDREFEMP ';
    wsql = wsql||                                                                   'FROM TTERCEIRO_REF RF3 ';
    wsql = wsql||                                                                   'WHERE RF3.BDCODTER = TER.BDCODTER ';
    wsql = wsql||                                                                   'ORDER BY RF3.BDCODTER, RF3.BDREFEMP)) AND ';
    wsql = wsql||            'UPPER(TER.BDPRURALTER) = ''TRUE'') ';
    wsql = wsql||      'LEFT OUTER JOIN TCIDADE CID ON CID.BDCODCID = TER.BDCODCID ';
    wsql = wsql||      'LEFT OUTER JOIN TUF UF ON UF.BDCODUF = CID.BDCODUF AND ';
    wsql = wsql||            'UF.BDSIGLAUF <> ''EX'' ';
    wsql = wsql||      'WHERE UPPER(UF.BDSIGLAUF) = ''SP'' AND ';
    wsql = wsql||            '((ITENS.BDBASEICMS > 0) OR (ITENS.BDISENTASICMS > 0) OR (ITENS.BDOUTRASICMS > 0)) ';
    wsql = wsql||      'GROUP BY BDCODEMP, BDREFLAN, BDSIGLAUF, BDCODEST) ENT ';

  for execute statement wsql
  into
    BDCODEMP,
    BDREFERENCIA,
    WPREFIXONAT,
    WSIGLAUF,
    BDCODEST,
    BDCODDIPAM,
    BDVALOR
  do
  begin
    suspend;
  end

--  wsql = 'SELECT m.bdcodemp, m.bdreflan referencia, i.bdprefixonat, upper(u.bdsiglauf),c.BDCODGIARS, ';
--  wsql = wsql||' SUM(coalesce(i.bdbaseicms, 0) + coalesce(i.bdisentasicms, 0) + coalesce(i.bdoutrasicms, 0)) bdVALOR, ';
--  wsql = wsql||' DIP.BDCODDIPAMSP ';
--  wsql = wsql||' FROM vef_emp_tmovSAI m ';
--  wsql = wsql||' JOIN vef_emp_tmovSAIitens i ON (m.BDCODEMP = i.BDCODEMP and m.BDCHAVE = i.BDCHAVE)';
--  wsql = wsql||' JOIN vw_tterceiro t ON (m.BDCODTER = t.BDCODTER)';
--  wsql = wsql||' JOIN tcidade c ON (m.BDCODCID = c.BDCODCID)';
--  wsql = wsql||' JOIN tuf u ON (c.BDCODUF = u.BDCODUF)';
--  wsql = wsql||' JOIN VEF_BASE_TNATOP nat ON (i.BDCODNAT = nat.BDCODNAT)';
--  wsql = wsql||' JOIN VEF_BASE_TDIPAMSP DIP ON (nat.BDDIPAMSP = dip.BDDIPAMSP)';
--  wsql = wsql||' WHERE';
--  wsql = wsql||'   (m.bdcodsitnf not in (2,3,4,5)) ';
--  wsql = wsql||'   and ( (i.bdbaseicms > 0) or (i.bdisentasicms > 0) or (i.bdoutrasicms > 0) ) ';
--  wsql = wsql||'   and (u.bdsiglauf <> '''||'EX'||''')';
--  wsql = wsql||'   and (upper(u.bdsiglauf) = ''SP'')';
--  wsql = wsql||'   and ((coalesce(i.bdbaseicms, 0) + coalesce(i.bdisentasicms, 0) + coalesce(i.bdoutrasicms, 0)) > 0) AND (';
--  wsql = wsql||wwhere;
--  wsql = wsql||') group by m.bdcodemp, referencia, i.bdprefixonat, u.bdsiglauf,c.BDCODGIARS, DIP.BDCODDIPAMSP';


  wsql = 'SELECT m.bdcodemp, m.bdreflan referencia, i.bdprefixonat, upper(u.bdsiglauf), iif(DIP.BDCODDIPAMSP = ''3.1'', 0, C.BDCODGIARS) as BDCODGIARS, ';
  wsql = wsql||' sum((coalesce(I.BDBASEICMS, 0) + coalesce(I.BDISENTASICMS, 0) + coalesce(I.BDOUTRASICMS, 0)) * iif(SP.BDDIPAMB = ''TRUE'' and DIP.BDCODDIPAMSP = ''2.2'' and ((TER.BDENQSIMPLESFEDTER = 2) or (position(''-'', TER.BDCGCTER) = 12)), 0.32, 1)) as BDVALOR, ';
  wsql = wsql||' DIP.BDCODDIPAMSP, C.BDCODCID, SP.BDDIPAMB ';
  wsql = wsql||' from ( select m.* from vef_emp_tmovsai m where '||wwhere||' and ( m.bdcodsitnf not in (2,3,4,5)) ) m ';
  wsql = wsql||' JOIN vef_emp_tmovSAIitens i ON (m.BDCODEMP = i.BDCODEMP and m.BDCHAVE = i.BDCHAVE)';
  wsql = wsql||' join TTERCEIRO_REF TER on (M.BDCODTER = TER.BDCODTER and ';
  wsql = wsql||'       TER.BDREFEMP = coalesce((select first 1 BDREFEMP ';
  wsql = wsql||'                                from TTERCEIRO_REF RF3 ';
  wsql = wsql||'                                where RF3.BDCODTER = TER.BDCODTER and ';
  wsql = wsql||'                                      RF3.BDREFEMP <= ' || :PRREFERENCIAFINAL;
  wsql = wsql||'                                order by RF3.BDREFEMP desc), (select first 1 BDREFEMP ';
  wsql = wsql||'                                                              from TTERCEIRO_REF RF3 ';
  wsql = wsql||'                                                              where RF3.BDCODTER = TER.BDCODTER ';
  wsql = wsql||'                                                              order by RF3.BDCODTER, RF3.BDREFEMP))) ';
  wsql = wsql||' join VEF_BASE_TEMPPARESTSP SP on (M.BDCODEMP = SP.BDCODEMP and ';
  wsql = wsql||'      SP.BDREFEMP = coalesce((select first 1 X.BDREFEMP ';
  wsql = wsql||'                              from VEF_BASE_TEMPPARESTSP X ';
  wsql = wsql||'                              where X.BDCODEMP = SP.BDCODEMP and ';
  wsql = wsql||'                                    X.BDREFEMP <= ' || :PRREFERENCIAFINAL;
  wsql = wsql||'                              order by X.BDREFEMP desc), (select first 1 X.BDREFEMP ';
  wsql = wsql||'                                                          from VEF_BASE_TEMPPARESTSP X ';
  wsql = wsql||'                                                          where X.BDCODEMP = SP.BDCODEMP ';
  wsql = wsql||'                                                          order by X.BDCODEMP, X.BDREFEMP))) ';
  wsql = wsql||' JOIN tcidade c ON (m.BDCODCID = c.BDCODCID)';
  wsql = wsql||' JOIN tuf u ON (c.BDCODUF = u.BDCODUF)';
  wsql = wsql||' JOIN VEF_BASE_TNATOP nat ON (i.BDCODNAT = nat.BDCODNAT)';
  wsql = wsql||' JOIN VEF_BASE_TDIPAMSP DIP ON (nat.BDDIPAMSP = dip.BDDIPAMSP)';
  wsql = wsql||' WHERE ( (i.bdbaseicms > 0) or (i.bdisentasicms > 0) or (i.bdoutrasicms > 0) ) ';
  wsql = wsql||'   and (u.bdsiglauf <> ''EX'')';
  wsql = wsql||'   and (upper(u.bdsiglauf) = ''SP'')';
  wsql = wsql||'   and ((coalesce(i.bdbaseicms, 0) + coalesce(i.bdisentasicms, 0) + coalesce(i.bdoutrasicms, 0)) > 0) ';
  wsql = wsql||'   and ((coalesce(SP.BDDIPAMB, ''FALSE'') = ''FALSE'') or (SP.BDDIPAMB = ''TRUE'' and DIP.BDCODDIPAMSP = ''2.2'' and ((TER.BDENQSIMPLESFEDTER = 2) or (position(''-'', TER.BDCGCTER) = 12)))) ';
  wsql = wsql||' group by M.BDCODEMP, REFERENCIA, I.BDPREFIXONAT, U.BDSIGLAUF, C.BDCODGIARS, DIP.BDCODDIPAMSP, C.BDCODCID, SP.BDDIPAMB ';


  for execute statement wsql
  into
    BDCODEMP,
    BDREFERENCIA,
    WPREFIXONAT,
    WSIGLAUF,
    BDCODEST,
    BDVALOR,
    BDCODDIPAM,
    BDCODCID,
    BDDIPAMB
  do
  begin
    suspend;
  end

end
^

/* Restore proc. body: SP_VEF_FILTRO_NOTAS_NAO_LANCADA */
ALTER PROCEDURE SP_VEF_FILTRO_NOTAS_NAO_LANCADA(PRCODEMP INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRNUMDOCINI INTEGER,
PRNUMDOCFIN INTEGER,
PRESPECIE VARCHAR(5),
PRSERIE VARCHAR(6),
PRSERVICO_SAIDA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNUMDOC INTEGER,
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6))
 AS
DECLARE VARIABLE WSQL VARCHAR(1024);
DECLARE VARIABLE WWHERE VARCHAR(512);
DECLARE VARIABLE WORDER VARCHAR(256);
--declare variable WDATAEMISSAO date;
DECLARE VARIABLE WNUMDOCINI INTEGER;
DECLARE VARIABLE WNUMDOCFIN INTEGER;
--declare variable WESPECIE varchar(5);
--declare variable WSERIE varchar(6);
--declare variable WNUMDOC integer;
--declare variable WNUMDOCANT integer;
BEGIN
  wsql = 'select BDESPECIE, BDSERIE, BDNUMDOCINI, case when (BDNUMDOCFIM is null) then BDNUMDOCINI when (BDNUMDOCFIM is not null) then BDNUMDOCFIM end BDNUMDOCFIM ';
  IF (prservico_saida = 0) THEN
     wsql = wsql||'from vef_emp_tmovser ';
  ELSE
     wsql = wsql||'from vef_emp_tmovsai ';

  wwhere = '';
  IF (prcodemp IS NOT NULL) THEN
     wwhere = wwhere||' and (bdcodemp = '||prcodemp||') ';

  IF (prdatini IS NOT NULL) THEN
     wwhere = wwhere||' and (BDDATAEMISSAO >= '''||prdatini||''') ';
  IF (prdatfin IS NOT NULL) THEN
     wwhere = wwhere||' and (BDDATAEMISSAO <= '''||prdatfin||''') ';

  IF (prnumdocini IS NOT NULL) THEN
     wwhere = wwhere||' and (BDNUMDOCINI >= '||prnumdocini||' and BDNUMDOCFIM >= '||prnumdocini||') ';
  IF (prnumdocfin IS NOT NULL) THEN
     wwhere = wwhere||' and (BDNUMDOCINI <= '||prnumdocfin||' and BDNUMDOCFIM <= '||prnumdocfin||') ';

  IF (prespecie IS NOT NULL) THEN
     wwhere = wwhere||' and (BDESPECIE = '''||prespecie||''') ';

  IF (prserie IS NOT NULL) THEN
     wwhere = wwhere||' and (BDSERIE = '''||prserie||''') ';

  IF (wwhere <> '') THEN
     wwhere = ' where '||SUBSTRING(wwhere FROM 5 FOR strlen(wwhere)-4);

  worder = ' group by BDESPECIE, BDSERIE, BDNUMDOCINI, BDNUMDOCFIM';
  worder = worder||' order by BDESPECIE, BDSERIE, BDNUMDOCINI, BDNUMDOCFIM';

  bdcodemp = prcodemp;
--  wnumdocant = 1;
  FOR EXECUTE STATEMENT wsql||wwhere||worder
      INTO :bdespecie, :bdserie, :wnumdocini, :wnumdocfin DO
      BEGIN
/*
        select max(BDNUMDOCFIM)
        from (select BDESPECIE, BDSERIE,
                     BDNUMDOCINI, case when (BDNUMDOCFIM is null) then BDNUMDOCINI when (BDNUMDOCFIM is not null) then BDNUMDOCFIM end BDNUMDOCFIM
              from vef_emp_tmovser
              where bddataemissao < :prdatini
              group by BDESPECIE, BDSERIE, BDNUMDOCINI, BDNUMDOCFIM
              order by BDESPECIE, BDSERIE, BDNUMDOCINI, BDNUMDOCFIM)




        wnumdoc = wnumdocini;
        while (wnumdoc < wnumdocfin) do
          begin
            bdnumdoc = wnumdoc;
            suspend;
            wnumdoc = wnumdoc + 1;
          end
*/
      END
END
^

/* Restore proc. body: SP_VEF_LIVROENTRADA */
create or alter procedure SP_VEF_LIVROENTRADA (
    PRCODEMP varchar(10000),
    PRDATAINI date,
    PRDATAFIM date,
    PRIMPSUFIXONAT integer)
returns (
    BDCODEMP integer,
    BDREFLAN integer,
    BDDATAENTRADAENT date,
    BDCHAVE integer,
    BDORDEM integer,
    BDCODTER integer,
    BDCODCID integer,
    BDNOMETER varchar(100),
    BDCGCTER varchar(18),
    BDIETER varchar(20),
    BDESPECIE varchar(5),
    BDSERIE varchar(12),
    BDNUMDOCINI integer,
    BDDATAEMISSAO date,
    BDSIGLAUF varchar(2),
    BDCODSITNF integer,
    BDVLRCONTAB numeric(18,6),
    BDPREFIXONAT integer,
    BDBASEICMS numeric(18,6),
    BDBASEICMSVARALIQ numeric(18,6),
    BDALIQICMS numeric(18,6),
    BDVLRICMS numeric(18,6),
    BDISENTASICMS numeric(18,6),
    BDOUTRASICMS numeric(18,6),
    BDBASEIPI numeric(18,6),
    BDDIFALIQENT numeric(18,6),
    BDVLRIPI numeric(18,6),
    BDISENTASIPI numeric(18,6),
    BDOUTRASIPI numeric(18,6),
    BDBASEST numeric(18,6),
    BDVLRST numeric(18,6),
    BDNOMEOBS varchar(100),
    BDLINHABRANCO varchar(1),
    BDLANCVARALIQ integer,
    BDVALNTRIBST numeric(18,6),
    BDICMSRETENT numeric(18,6),
    BDBCSTNAORET numeric(18,6),
    BDVLRSTNAORET numeric(18,6),
    BDBCSTNAORETRE numeric(18,6),
    BDVLRSTNAORETRE numeric(18,6))
as
declare variable WSQL varchar(32700);
declare variable FDIVOUTRASICMS numeric(18,6);
declare variable FDIVBASEICMS numeric(18,6);
declare variable FDIVALIQICMS numeric(18,6);
declare variable FDIVVLRICMS numeric(18,6);
declare variable FDIVISENTASICMS numeric(18,6);
declare variable BDCODEMP_BKP integer;
declare variable BDCHAVE_BKP integer;
declare variable FORDEMALIQ numeric(18,6);
declare variable BDORDEM_BKP integer;
declare variable FSTREGESP varchar(5);
declare variable FBCSTNAORET numeric(18,6);
declare variable FVLRSTNAORET numeric(18,6);
BEGIN

 WSQL = 'select m.BDCODEMP, m.bdreflan, m.BDDATAENTRADAENT, m.BDCHAVE, I.BDORDEM, m.bdcodter, t.bdcodcid,t.BDNOMETER,t.BDCGCTER,t.bdieter, m.BDESPECIE, m.BDSERIE||Coalesce(M.BDSUBSERIE,'''') BDSERIE, m.BDNUMDOCINI, m.BDDATAEMISSAO, u.BDSIGLAUF,';
  IF (PRIMPSUFIXONAT = 0) THEN/*alt.:9059 = 0 false / 1 true*/
     WSQL = WSQL||' m.BDCODSITNF, i.BDVLRCONTAB, i.BDPREFIXONAT, i.BDBASEICMS, ';
  ELSE
     WSQL = WSQL||' m.BDCODSITNF, i.BDVLRCONTAB, i.BDCODNAT BDPREFIXONAT, i.BDBASEICMS, ';

  --WSQL = WSQL||' a.BDBASEICMS BDBASEICMSVARALIQ, ';--alt.:3860
  WSQL = WSQL||' case when a.bdordemicms is not null then coalesce(';

  WSQL = WSQL||' case ';
  WSQL = WSQL||' when A.bdbaseredicms > 0 then A.bdbaseredicms ';
  WSQL = WSQL||' else A.BDBASEICMS ';
  WSQL = WSQL||' end ';

  WSQL = WSQL||' ,0) else A.BDBASEICMS end BDBASEICMSVARALIQ, ';

  WSQL = WSQL||' i.BDALIQICMS, (COALESCE(i.BDVLRICMS, 0) + (IIF(UEMP.BDFCPOP = ''TRUE'', coalesce(I.BDVLRFCP, 0), 0))) BDVLRICMS, i.bdisentasicms, i.bdoutrasicms, i.BDBASEIPI,i.BDDIFALIQENT, i.BDVLRIPI, i.bdisentasipi, i.bdoutrasipi, i.bdbasest,i.bdvlrst, Coalesce(i.bdobservacao, o.bdnomeobs) bdnomeobs,';

  --WSQL = WSQL||' sum(a.bdoutrasicms) bddivoutrasicms, ';--alt.:3860
  WSQL = WSQL||' sum(case when a.bdordemicms is not null then coalesce(A.bdoutrasicms,0) else A.bdoutrasicms end) bddivoutrasicms, ';
  --WSQL = WSQL||' sum(a.bdbaseredicms) bdDIVbaseicms, ';--alt.:3860
  WSQL = WSQL||' sum(case when a.bdordemicms is not null then coalesce(';
  --WSQL = WSQL||' A.bdbaseredicms';  -- alt.:3860 - na importa????o esse campo vem zerado. Por isso ele calculado aqui
  WSQL = WSQL||' case when a.bdredbcicms = 0 then A.BDBASEICMS when a.bdredbcicms = 100 then 0 else A.BDBASEICMS * ((100 - a.bdredbcicms)/100) end ';
  WSQL = WSQL||' ,0) else A.bdbaseredicms end) bdDIVbaseicms, ';

  --WSQL = WSQL||' a.bdaliqicms bdDIValiqicms, ';--alt.:3860
  WSQL = WSQL||' case when a.bdordemicms is not null then coalesce(A.bdaliqicms,0) else A.bdaliqicms end bdDIValiqicms, ';
  --WSQL = WSQL||' sum(a.bdvlricms) bdDIVvlricms, ';--alt.:3860
  
  --WSQL = WSQL||' sum(case when a.bdordemicms is not null then (coalesce(A.BDVLRICMS, 0) + iif(UEMP.BDFCPOP = ''TRUE'', coalesce(I.BDVLRFCP * (cast(((A.BDVLRICMS * 100) /  coalesce(I.BDVLRICMS,1)) as numeric(15,10)) / 100), 0), 0)) else A.bdvlricms end) bdDIVvlricms, '; -- Larissa - 02/2021 - FCP OP - Livro Entrada\Sa??da\ICMS #144225 #144385
  WSQL = WSQL||'sum(case when a.bdordemicms is not null then (coalesce(A.BDVLRICMS, 0) + iif((UEMP.BDFCPOP = ''TRUE'') and (I.BDVLRFCP > 0), iif(I.BDVLRICMS > 0, coalesce(I.BDVLRFCP * (cast(((A.BDVLRICMS * 100) /  I.BDVLRICMS) as numeric(15,10)) / 100), 0),  I.BDVLRFCP * (cast (((A.BDVLRICMS * 100) / (select sum(BDVLRICMS) from VEF_EMP_TMOVENTVARALIQ where bdcodemp = a.bdcodemp and bdchave = a.bdchave)) as numeric(15,10) )/ 100)  ), 0)) else A.bdvlricms end) bdDIVvlricms,';
  
  --WSQL = WSQL||' sum(a.bdisentasicms) bdDIVisentasicms,';--alt.:3860
  WSQL = WSQL||' sum(case when a.bdordemicms is not null then coalesce(A.bdisentasicms,0) else A.bdisentasicms end) bdDIVisentasicms, ';

  wSQL = WSQL||' case when (a.bdaliqicms = 0) then 999.0 end bdordemaliq, a.bdchave bdLancVarAliq, i.BDVALNTRIBST, i.BDICMSRETENT ';
  WSQL = WSQL||' from (select m.BDCODEMP, m.BDREFLAN, m.BDDATAENTRADAENT, m.BDCHAVE, m.BDCODTER, m.BDESPECIE, m.BDSERIE, m.BDSUBSERIE, m.BDNUMDOCINI, m.BDDATAEMISSAO, m.BDCODSITNF ';
  WSQL = WSQL||'       from VEF_EMP_TMOVENT m ';

  IF (:prcodemp IS NULL) THEN
     WSQL = WSQL||'       where (BDDATAENTRADAENT between '''||:PRDATAINI||''' and '''||:PRDATAFIM||''') ';
  ELSE
     WSQL = WSQL||'       where ('||:PRCODEMP||') and (BDDATAENTRADAENT between '''||:PRDATAINI||''' and '''||:PRDATAFIM||''')  ';

  WSQL = WSQL||'       ) m ';
  WSQL = WSQL||' inner join VEF_EMP_TMOVENTITENS i on (m.bdcodemp = i.bdcodemp and m.bdchave = i.bdchave)';
  WSQL = WSQL||' left outer join VEF_EMP_TMOVENTVARALIQ a on (m.bdcodemp = a.bdcodemp and m.bdchave = a.bdchave and I.BDORDEM = a.BDORDEM)';
  WSQL = WSQL||' left outer join vw_tterceiro t on (m.bdcodter = t.bdcodter)';
  WSQL = WSQL||' left outer join TCIDADE c on (t.bdcodcid = c.bdcodcid)';
  WSQL = WSQL||' left outer join TUF u on (c.bdcoduf = u.bdcoduf)';
  WSQL = WSQL||' left outer join VEF_BASE_TOBSERVACAO o on (o.bdcodobs = i.bdcodobs)';

-- Larissa - 02/2021 - FCP OP - Livro Entrada\Sa??da\ICMS #144225 #144385
  WSQL = WSQL||' left outer join VW_TEMPRESAS_REF EMP on (M.BDCODEMP = EMP.BDCODEMP)';
  WSQL = WSQL||' left outer join TCIDADE CEMP on (EMP.BDCODCID = CEMP.BDCODCID)';
  WSQL = WSQL||' left outer join TUF UEMP on (CEMP.BDCODUF = UEMP.BDCODUF)';

  WSQL = wSQL||' group by m.BDCODEMP, m.bdreflan, m.BDDATAENTRADAENT, m.BDCHAVE, I.BDORDEM, m.bdcodter, t.bdcodcid,t.BDNOMETER,t.BDCGCTER,t.bdieter, ';
  WSQL = wSQL||' m.BDESPECIE, BDSERIE, m.BDNUMDOCINI, m.BDDATAEMISSAO, u.BDSIGLAUF,';
  IF (PRIMPSUFIXONAT = 0) THEN/*alt.:9059 = 0 false / 1 true*/
     WSQL = WSQL||' m.BDCODSITNF, i.BDVLRCONTAB, i.BDPREFIXONAT, i.BDBASEICMS, BDBASEICMSVARALIQ, i.BDALIQICMS, ';
  ELSE
     WSQL = WSQL||' m.BDCODSITNF, i.BDVLRCONTAB, i.BDCODNAT, i.BDBASEICMS, BDBASEICMSVARALIQ, i.BDALIQICMS, ';

  WSQL = WSQL||' BDVLRICMS, i.bdisentasicms, i.bdoutrasicms, i.BDBASEIPI,i.BDDIFALIQENT, i.BDVLRIPI, i.bdisentasipi, ';
  WSQL = WSQL||' i.bdoutrasipi, i.bdbasest,i.bdvlrst, bdnomeobs, bdDIValiqicms, bdLancVarAliq, i.BDVALNTRIBST, i.BDICMSRETENT,bdordemaliq ';

  WSQL = WSQL||' order by m.BDCODEMP, m.bdreflan, m.BDDATAENTRADAENT, m.bdchave, I.BDORDEM, bdaliqicms, bdordemaliq';


  BDCODEMP_BKP = 0;
  BDCHAVE_BKP = 0;
  BDORDEM_BKP = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDREFLAN,
    BDDATAENTRADAENT,
    BDCHAVE,
    BDORDEM,
    BDCODTER,
    BDCODCID,
    BDNOMETER,
    BDCGCTER,
    BDIETER,
    BDESPECIE,
    BDSERIE,
    BDNUMDOCINI,
    BDDATAEMISSAO,
    BDSIGLAUF,
    BDCODSITNF,
    BDVLRCONTAB,
    BDPREFIXONAT,
    BDBASEICMS,
    BDBASEICMSVARALIQ,
    BDALIQICMS,
    BDVLRICMS,
    BDISENTASICMS,
    BDOUTRASICMS,
    BDBASEIPI,
    BDDIFALIQENT,
    BDVLRIPI,
    BDISENTASIPI,
    BDOUTRASIPI,
    BDBASEST,
    BDVLRST,
    BDNOMEOBS,
    FDIVOUTRASICMS,
    FDIVBASEICMS,
    FDIVALIQICMS,
    FDIVVLRICMS,
    FDIVISENTASICMS,
    FORDEMALIQ,
    bdLancVarAliq,
    BDVALNTRIBST,
    BDICMSRETENT
  DO
  BEGIN
    IF ((BDCODEMP = BDCODEMP_BKP) AND (bdchave = BDCHAVE_BKP) AND (BDORDEM_BKP = BDORDEM)) THEN
       BEGIN
          BDLINHABRANCO = 'S';
          BDVLRCONTAB = 0;
          BDBASEIPI = 0;
          BDVLRIPI = 0;
          BDISENTASIPI = 0;
          BDOUTRASIPI = 0;
          BDBASEST = 0;
          BDVLRST = 0;
          BDDIFALIQENT = 0;
          BDVALNTRIBST = 0;
          BDICMSRETENT = 0;
       END
    ELSE
       BDLINHABRANCO = 'N';

    IF (BDLINHABRANCO = 'S') THEN
       BEGIN
         BDBCSTNAORET = 0;
         BDVLRSTNAORET = 0;
         BDBCSTNAORETRE = 0;
         BDVLRSTNAORETRE = 0;
       END
    ELSE
       BEGIN
         BDBCSTNAORET = 0;
         BDVLRSTNAORET = 0;
         BDBCSTNAORETRE = 0;
         BDVLRSTNAORETRE = 0;

         WSQL = 'select mva.bdregesp, sum(mva.BDBCRETENCAO) BDBCRETENCAO, sum(mva.BDVLRIMPREC) BDVLRIMPREC from vef_emp_tmoventmva mva';
         WSQL = WSQL||' where mva.bdcodemp = '||BDCODEMP||' and mva.bdchave = '||BDCHAVE||' and mva.bdordem = '||BDORDEM;
         WSQL = WSQL||' group by mva.bdregesp';

         FOR EXECUTE STATEMENT wsql
         INTO
           FSTREGESP,
           FBCSTNAORET,
           FVLRSTNAORET
         DO
         BEGIN
           IF (FSTREGESP = 'TRUE') THEN
              BEGIN
                BDBCSTNAORETRE = FBCSTNAORET;
                BDVLRSTNAORETRE = FVLRSTNAORET;
              END
           ELSE
              BEGIN
                BDBCSTNAORET = FBCSTNAORET;
                BDVLRSTNAORET = FVLRSTNAORET;
              END
         END
       END

    IF (FDIVOUTRASICMS IS NOT NULL) THEN
       BDOUTRASICMS = FDIVOUTRASICMS;

    IF ((FDIVBASEICMS IS NOT NULL) AND (FDIVBASEICMS > 0)) THEN
       BDBASEICMS = FDIVBASEICMS;

    IF ((BDBASEICMSVARALIQ IS NOT NULL) AND (BDBASEICMSVARALIQ > 0)) THEN
       BDBASEICMS = BDBASEICMSVARALIQ;  

    IF (FDIVALIQICMS IS NOT NULL) THEN
       BDALIQICMS = FDIVALIQICMS;

    IF (FDIVVLRICMS IS NOT NULL) THEN
       BDVLRICMS = FDIVVLRICMS;

    IF (FDIVISENTASICMS IS NOT NULL) THEN
       BDISENTASICMS = FDIVISENTASICMS;

    BDCODEMP_BKP = BDCODEMP;
    BDCHAVE_BKP = BDCHAVE;
    BDORDEM_BKP = BDORDEM;

    SUSPEND;
  END
END^


/* Restore proc. body: SP_VEF_LIVROSAIDA */
create or alter procedure SP_VEF_LIVROSAIDA (
    PRCODEMP varchar(10000),
    PRDATAINI date,
    PRDATAFIM date,
    PRIMPSUFIXONAT integer,
    PRDEDUZIPIICMSOUTRAS varchar(5))
returns (
    BDCODEMP integer,
    BDREFLAN integer,
    BDDATAEMISSAO date,
    BDCHAVE integer,
    BDORDEM integer,
    BDCODTER integer,
    BDCODCID integer,
    BDNOMETER varchar(100),
    BDCGCTER varchar(18),
    BDIETER varchar(20),
    BDESPECIE varchar(5),
    BDSERIE varchar(6),
    BDNUMDOCINI integer,
    BDNUMDOCFIM integer,
    BDCODSITNF integer,
    BDSIGLAUF varchar(2),
    BDVLRCONTAB numeric(18,6),
    BDPREFIXONAT integer,
    BDBASEICMS numeric(18,6),
    BDALIQICMS numeric(18,6),
    BDVLRICMS numeric(18,6),
    BDISENTASICMS numeric(18,6),
    BDOUTRASICMS numeric(18,6),
    BDBASEIPI numeric(18,6),
    BDVLRIPI numeric(18,6),
    BDISENTASIPI numeric(18,6),
    BDOUTRASIPI numeric(18,6),
    BDBASEST numeric(18,6),
    BDVLRST numeric(18,6),
    BDNOMEOBS varchar(100),
    BDLINHABRANCO varchar(1),
    BDIMPSOMENTECFOP varchar(1),
    BDVLRCONTABTOT numeric(18,6),
    BDLANCVARALIQ integer,
    BDSAIREDZ varchar(1),
    BDOBSERVACAO varchar(100),
    BDVALGTFINAL numeric(15,2))
as
declare variable WSQL varchar(32700);
declare variable WSQLTOT varchar(32700);
declare variable FDIVOUTRASICMS numeric(18,6);
declare variable FDIVBASEICMS numeric(18,6);
declare variable FDIVALIQICMS numeric(18,6);
declare variable FDIVVLRICMS numeric(18,6);
declare variable FDIVISENTASICMS numeric(18,6);
declare variable BDCODEMP_BKP integer;
declare variable BDCHAVE_BKP integer;
declare variable BDORDEM_BKP integer;
declare variable BDPREFIXONAT_BKP integer;
declare variable WVLRCONT numeric(18,6);
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WNAT integer;
declare variable WSTTRANSPORTE numeric(15,6);
BEGIN
   WSQL = 'select m.BDCODEMP, m.BDREFLAN, m.bddataemissao, m.BDCHAVE, I.BDORDEM, m.bdcodter, m.bdcodcid,t.BDNOMETER,t.BDCGCTER,t.bdieter, m.BDESPECIE, m.BDSERIE||Coalesce(M.BDSUBSERIE,'''') BDSERIE, m.BDNUMDOCINI, m.bdnumdocfim, ';
  IF (PRIMPSUFIXONAT = 0) THEN/*alt.:9059 = 0 false / 1 true*/
     WSQL = WSQL||' m.BDCODSITNF, u.BDSIGLAUF, i.BDVLRCONTAB, i.BDPREFIXONAT, i.BDBASEICMS, i.BDALIQICMS, (COALESCE(i.BDVLRICMS, 0) + (IIF(UEMP.BDFCPOP = ''TRUE'', coalesce(I.BDVLRFCP, 0), 0))) BDVLRICMS, i.bdisentasicms, IIF('||:prdeduzipiicmsoutras||' = ''TRUE'', IIF(I.BDOUTRASICMS - I.BDVLRIPI > 0, I.BDOUTRASICMS - I.BDVLRIPI, 0), I.BDOUTRASICMS) BDOUTRASICMS, i.BDBASEIPI, i.BDVLRIPI, i.bdisentasipi, i.bdoutrasipi, ';
  ELSE
     WSQL = WSQL||' m.BDCODSITNF, u.BDSIGLAUF, i.BDVLRCONTAB, i.BDCODNAT BDPREFIXONAT, i.BDBASEICMS, i.BDALIQICMS, (coalesce(I.BDVLRICMS, 0) + (IIF(UEMP.BDFCPOP = ''TRUE'', coalesce(I.BDVLRFCP, 0), 0))) BDVLRICMS, i.bdisentasicms, IIF('||:prdeduzipiicmsoutras||' = ''TRUE'', IIF(I.BDOUTRASICMS - I.BDVLRIPI > 0, I.BDOUTRASICMS - I.BDVLRIPI, 0), I.BDOUTRASICMS) BDOUTRASICMS, i.BDBASEIPI, i.BDVLRIPI, i.bdisentasipi, i.bdoutrasipi, ';

  WSQL = WSQL||' i.bdbasest, i.bdvlrst, CASE WHEN ((Coalesce(i.bdobservacao, o.bdnomeobs) is null) and (i.bdsttransporte > 0)) THEN '||'''ICMS ST transporte R$'''||'||CAST(CAST(i.bdsttransporte as numeric(15,2)) as VARCHAR(25)) ELSE Coalesce(i.bdobservacao, o.bdnomeobs) END bdnomeobs,';

  --WSQL = WSQL||' a.bdaliqicms bdDIValiqicms, ';--alt.:3860
  WSQL = WSQL||' case when a.bdordemicms is not null then coalesce(A.bdaliqicms,0) else A.bdaliqicms end bdDIValiqicms, ';
  --WSQL = WSQL||' sum(a.bdoutrasicms) bddivoutrasicms, ';--alt.:3860
  WSQL = WSQL||' sum(case when a.bdordemicms is not null then coalesce(A.bdoutrasicms,0) else A.bdoutrasicms end) bddivoutrasicms, ';
  --WSQL = WSQL||' sum(a.bdbaseredicms) bdDIVbaseicms, ';--alt.:3860
  WSQL = WSQL||' sum(case when a.bdordemicms is not null then coalesce(';
  --WSQL = WSQL||' A.bdbaseredicms ';-- alt.:3860 - na importa????o esse campo vem zerado. Por isso ele calculado aqui
  WSQL = WSQL||' case when a.bdredbcicms = 0 then ';
  WSQL = WSQL||' case ';
  WSQL = WSQL||' when A.bdbaseredicms > 0 then A.bdbaseredicms ';
  WSQL = WSQL||' else A.BDBASEICMS ';
  WSQL = WSQL||' end ';
  WSQL = WSQL||' when a.bdredbcicms = 100 then 0 else A.BDBASEICMS * ((100 - coalesce(a.bdredbcicms,0))/100) end '; --Leandro - adicionado o coalesce
  WSQL = WSQL||' ,0) else A.bdbaseredicms end) bdDIVbaseicms, ';
  --WSQL = WSQL||' sum(a.bdvlricms) bdDIVvlricms, ';--alt.:3860

--  WSQL = WSQL||' sum(case when A.BDORDEMICMS is not null then (coalesce(A.BDVLRICMS, 0) + iif(UEMP.BDFCPOP = ''TRUE'', coalesce(I.BDVLRFCP * (cast(((A.BDVLRICMS * 100) / I.BDVLRICMS) as numeric(15,10)) / 100), 0), 0)) else A.BDVLRICMS end) bdDIVvlricms, '; -- Larissa - 02/2021 - #144225 #144385
-- Leandro Correcao de erro de conversao quando i.vlricms = 0 Comentado anterior acima
  WSQL = WSQL||'sum(case when a.bdordemicms is not null then (coalesce(A.BDVLRICMS, 0) + iif((UEMP.BDFCPOP = ''TRUE'') and (I.BDVLRFCP > 0), iif(I.BDVLRICMS > 0, coalesce(I.BDVLRFCP * (cast(((A.BDVLRICMS * 100) /  I.BDVLRICMS) as numeric(15,10)) / 100), 0),  I.BDVLRFCP * (cast (((A.BDVLRICMS * 100) / (select sum(BDVLRICMS) from VEF_EMP_TMOVSAIVARALIQ where bdcodemp = a.bdcodemp and bdchave = a.bdchave)) as numeric(15,10) )/ 100)  ), 0)) else A.bdvlricms end) bdDIVvlricms,';

  --WSQL = WSQL||' sum(a.bdisentasicms) bdDIVisentasicms, ';--alt.:3860
  WSQL = WSQL||' sum(case when a.bdordemicms is not null then coalesce(A.bdisentasicms,0) else A.bdisentasicms end) bdDIVisentasicms, ';

  WSQL = WSQL||' a.bdchave bdLancVarAliq, i.bdsttransporte, '||'''S'''||' bdSAIREDZ ';

  WSQL = WSQL||' from ( select M.BDCODEMP, M.BDREFLAN, M.BDDATAEMISSAO, M.BDCHAVE, M.BDCODTER, M.BDCODCID, ';
  WSQL = WSQL||'               M.BDESPECIE, M.BDSERIE, M.BDSUBSERIE, M.BDNUMDOCINI, M.BDNUMDOCFIM, M.BDCODSITNF ';
  WSQL = WSQL||'        from VEF_EMP_TMOVSAI M ';

  IF (:prcodemp IS NULL) THEN
     WSQL = WSQL||'        where (m.bddataemissao >= '''||:PRDATAINI||''' and m.bddataemissao <= '''||:PRDATAFIM||''')';
  ELSE
     WSQL = WSQL||'        where ('||:PRCODEMP||') and (m.bddataemissao >= '''||:PRDATAINI||''' and m.bddataemissao <= '''||:PRDATAFIM||''')';

  WSQL = WSQL||'       ) m ';
  WSQL = WSQL||' left outer join vw_tterceiro t on (m.bdcodter = t.bdcodter)';
  WSQL = WSQL||' inner join VEF_EMP_TMOVSAIITENS i on (m.bdcodemp = i.bdcodemp and m.bdchave = i.bdchave)';
  WSQL = WSQL||' left outer join VEF_EMP_TMOVSAIVARALIQ a on (m.bdcodemp = a.bdcodemp and m.bdchave = a.bdchave and I.BDORDEM = a.BDORDEM)';
  WSQL = WSQL||' left outer join TCIDADE c on (m.bdcodcid = c.bdcodcid)';
  WSQL = WSQL||' left outer join TUF u on (c.bdcoduf = u.bdcoduf)';
  WSQL = WSQL||' left outer join VEF_BASE_TOBSERVACAO o on (o.bdcodobs = i.bdcodobs)';

  -- Larissa - 02/2021 - FCP OP - Livro Entrada\Sa??da\ICMS #144225 #144385
  WSQL = WSQL||' left outer join VW_TEMPRESAS_REF EMP on (M.BDCODEMP = EMP.BDCODEMP)';
  WSQL = WSQL||' left outer join TCIDADE CEMP on (EMP.BDCODCID = CEMP.BDCODCID)';
  WSQL = WSQL||' left outer join TUF UEMP on (CEMP.BDCODUF = UEMP.BDCODUF)';

  WSQL = WSQL||' group by m.BDCODEMP, m.BDREFLAN, m.bddataemissao, m.BDCHAVE, I.BDORDEM, m.bdcodter, m.bdcodcid,t.BDNOMETER,t.BDCGCTER,t.bdieter, m.BDESPECIE, BDSERIE, m.BDNUMDOCINI, m.bdnumdocfim, ';

  IF (PRIMPSUFIXONAT = 0) THEN/*alt.:9059 = 0 false / 1 true*/
     WSQL = WSQL||' m.BDCODSITNF, u.BDSIGLAUF, i.BDVLRCONTAB, i.BDPREFIXONAT, i.BDBASEICMS, i.BDALIQICMS, BDVLRICMS, i.bdisentasicms, i.bdoutrasicms, i.BDBASEIPI, i.BDVLRIPI, i.bdisentasipi, i.bdoutrasipi, ';
  ELSE
     WSQL = WSQL||' m.BDCODSITNF, u.BDSIGLAUF, i.BDVLRCONTAB, i.BDCODNAT, i.BDBASEICMS, i.BDALIQICMS, BDVLRICMS, i.bdisentasicms, i.bdoutrasicms, i.BDBASEIPI, i.BDVLRIPI, i.bdisentasipi, i.bdoutrasipi, ';

  WSQL = WSQL||' i.bdbasest, i.bdvlrst, bdnomeobs, bdDIValiqicms, bdLancVarAliq, i.bdsttransporte, bdSAIREDZ ';

  WSQL = WSQL||' order by m.BDCODEMP, m.bdreflan, m.bddataemissao, m.bdchave, I.BDORDEM';
  BDCODEMP_BKP = 0;
  BDCHAVE_BKP = 0;
  BDORDEM_BKP = 0;

  FOR EXECUTE STATEMENT wsql
  INTO 
    BDCODEMP,
    BDREFLAN, 
    BDDATAEMISSAO, 
    BDCHAVE, 
    BDORDEM, 
    BDCODTER, 
    BDCODCID, 
    BDNOMETER, 
    BDCGCTER, 
    BDIETER, 
    BDESPECIE, 
    BDSERIE, 
    BDNUMDOCINI, 
    BDNUMDOCFIM, 
    BDCODSITNF, 
    BDSIGLAUF, 
    BDVLRCONTAB, 
    BDPREFIXONAT, 
    BDBASEICMS, 
    BDALIQICMS, 
    BDVLRICMS, 
    BDISENTASICMS, 
    BDOUTRASICMS, 
    BDBASEIPI, 
    BDVLRIPI, 
    BDISENTASIPI, 
    BDOUTRASIPI, 
    BDBASEST, 
    BDVLRST, 
    BDNOMEOBS, 
    FDIVALIQICMS,
    FDIVOUTRASICMS,
    FDIVBASEICMS,
    FDIVVLRICMS,
    FDIVISENTASICMS,
    BDLANCVARALIQ, 
    WSTTRANSPORTE,
    BDSAIREDZ

  DO
  BEGIN
    IF ((BDCODEMP = BDCODEMP_BKP) AND (bdchave = BDCHAVE_BKP) AND (BDORDEM_BKP = BDORDEM)) THEN
       BEGIN
          BDLINHABRANCO = 'S';
          BDVLRCONTAB = 0;
          BDBASEIPI = 0;
          BDVLRIPI = 0;
          BDISENTASIPI = 0;
          BDOUTRASIPI = 0;
          BDBASEST = 0;
          BDVLRST = 0;
       END
    ELSE
       BDLINHABRANCO = 'N';

    BDVLRCONTABTOT = BDVLRCONTAB;
    BDIMPSOMENTECFOP = 'N';

    IF (FDIVOUTRASICMS IS NOT NULL) THEN
       BDOUTRASICMS = FDIVOUTRASICMS;

    IF (FDIVBASEICMS IS NOT NULL) THEN
       BDBASEICMS = FDIVBASEICMS;

    IF (FDIVALIQICMS IS NOT NULL) THEN
       BDALIQICMS = FDIVALIQICMS;

    IF (FDIVVLRICMS IS NOT NULL) THEN
       BDVLRICMS = FDIVVLRICMS;

    IF (FDIVISENTASICMS IS NOT NULL) THEN
       BDISENTASICMS = FDIVISENTASICMS;

    BDCODEMP_BKP = BDCODEMP;
    BDCHAVE_BKP = BDCHAVE;
    BDORDEM_BKP = BDORDEM;

    SUSPEND;

  END

  WSQL = 'select M.BDCODEMP, M.BDREFLAN, M.BDDATAREDZ BDDATAEMISSAO, M.BDCHAVE, C.BDORDEMVARCFOP BDORDEM, C.BDCODTER, null BDCODCID, ';
  WSQL = WSQL||' t.BDNOMETER, t.BDCGCTER, t.BDIETER, R.BDESPECIE, R.BDSERIE, ';

  IF (PRIMPSUFIXONAT = 0) THEN/*alt.:9059 = 0 false / 1 true*/
     WSQL = WSQL||' m.BDNUMCUPINI BDNUMDOCINI,m.BDNUMCUPFIN bdnumdocfim,null BDCODSITNF, '''' BDSIGLAUF, m.bdvalvenbru,CAST(SUBSTRING(cast(c.bdcodnat as varchar(7)) FROM 1 FOR 4) AS INTEGER) BDPREFIXONAT,';
  ELSE
     WSQL = WSQL||' m.BDNUMCUPINI BDNUMDOCINI,m.BDNUMCUPFIN bdnumdocfim,null BDCODSITNF, '''' BDSIGLAUF, m.bdvalvenbru,CAST(SUBSTRING(cast(c.bdcodnat as varchar(7)) FROM 1 FOR 7) AS INTEGER) BDPREFIXONAT,';

  WSQL = WSQL||' C.BDBASEICMS, C.BDALIQICMS, C.BDVLRICMS, C.BDISENTASICMS, C.BDOUTRASICMS, null BDBASEIPI, null BDVLRIPI, null BDISENTASIPI, ';
  WSQL = WSQL||' null BDOUTRASIPI, null BDBASEST, null BDVLRST, null BDNOMEOBS, null FDIVOUTRASICMS, 0 FDIVBASEICMS, ';
  WSQL = WSQL||' null FDIVALIQICMS, null FDIVVLRICMS, null FDIVISENTASIC, '||'''Z'''||' BDSAIREDZ, IIF(TRIM(C.BDOBSERVACAO) <> '''', C.BDOBSERVACAO, '||'''Contador de Redução Z: '''||'||M.BDPOSCRZ||'||''' GT Final: '') BDOBSERVACAO, M.BDVALGTFINAL ';

  WSQL = WSQL||'from ( select M.BDCODEMP, M.BDREFLAN, M.BDDATAREDZ, M.BDCHAVE, M.BDNUMCUPINI, M.BDNUMCUPFIN, M.BDVALVENBRU, M.BDPOSCRZ, M.BDVALGTFINAL, M.BDORDEMMAQ  ';
  WSQL = WSQL||'       from VEF_EMP_TREDZ M  ';
  IF (:prcodemp IS NULL) THEN
     WSQL = WSQL||'       where (m.BDDATAREDZ >= '''||:PRDATAINI||''' and m.BDDATAREDZ <= '''||:PRDATAFIM||''')';
  ELSE
     WSQL = WSQL||'       where ('||:PRCODEMP||') and (m.BDDATAREDZ >= '''||:PRDATAINI||''' and m.BDDATAREDZ <= '''||:PRDATAFIM||''')';
  WSQL = WSQL||'      ) M  ';

  WSQL = WSQL||' join VEF_EMP_TREDZVARCFOP C on (M.BDCODEMP = C.BDCODEMP and M.BDCHAVE = C.BDCHAVE) ';
  WSQL = WSQL||' join VEF_BASE_TCADMAQMRC R on (M.BDCODEMP = R.BDCODEMP and M.BDORDEMMAQ = R.BDORDEMMAQ) ';
  WSQL = WSQL||' left outer join vw_tterceiro t on (c.bdcodter = t.bdcodter) ';

  WSQL = WSQL||' where (m.bdcodemp = c.bdcodemp and m.bdchave = c.bdchave and m.bdcodemp = r.bdcodemp and m.bdordemmaq = r.bdordemmaq)';

  wSQL = WSQL||' order by m.BDCODEMP, m.BDCHAVE, BDPREFIXONAT, BDORDEM';

  BDCODEMP_BKP = 0;
  BDCHAVE_BKP = 0;
  BDPREFIXONAT_BKP = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDREFLAN,
    BDDATAEMISSAO,
    BDCHAVE,
    BDORDEM,
    BDCODTER,
    BDCODCID,
    BDNOMETER,
    BDCGCTER,
    BDIETER,
    BDESPECIE,
    BDSERIE,
    BDNUMDOCINI,
    bdnumdocfim,
    BDCODSITNF,
    BDSIGLAUF,
    BDVLRCONTAB,
    BDPREFIXONAT,
    BDBASEICMS,
    BDALIQICMS,
    BDVLRICMS,
    BDISENTASICMS,
    BDOUTRASICMS,
    BDBASEIPI,
    BDVLRIPI,
    BDISENTASIPI,
    BDOUTRASIPI,
    BDBASEST,
    BDVLRST,
    BDNOMEOBS,
    FDIVALIQICMS,
    FDIVOUTRASICMS,
    FDIVBASEICMS,    
    FDIVVLRICMS,
    FDIVISENTASICMS,
    BDSAIREDZ,
    BDOBSERVACAO,
    BDVALGTFINAL
  DO
  BEGIN
    IF ((BDCODEMP = BDCODEMP_BKP) AND (bdchave = BDCHAVE_BKP) AND (BDPREFIXONAT = BDPREFIXONAT_BKP)) THEN
       BDLINHABRANCO = 'S';
    ELSE
       BDLINHABRANCO = 'N';

    /* Quando muda somente CFOP da nota é preciso imprimí-la para separar */
    IF ((BDCODEMP = BDCODEMP_BKP) AND (bdchave = BDCHAVE_BKP)) THEN
       BEGIN
          IF (BDPREFIXONAT <> BDPREFIXONAT_BKP) THEN
             BEGIN
                BDIMPSOMENTECFOP = 'S';
             END
          ELSE
             BDIMPSOMENTECFOP = 'N';
       END
    ELSE
       BDIMPSOMENTECFOP = 'N';

    BDVLRCONTABTOT = BDVLRCONTAB;

    /* SQL que busca o valor por CFOP dos registros de várias alíquotas da redução Z */
    IF (PRIMPSUFIXONAT = 0) THEN/*alt.:9059 = 0 false / 1 true*/
       WSQLTOT = 'select m.BDCODEMP, m.BDCHAVE, CAST(SUBSTRING(cast(c.bdcodnat as varchar(7)) FROM 1 FOR 4) AS INTEGER) BDPREFIXONAT, SUM(c.bdvlrcontab)';
    ELSE
       WSQLTOT = 'select m.BDCODEMP, m.BDCHAVE, CAST(SUBSTRING(cast(c.bdcodnat as varchar(7)) FROM 1 FOR 7) AS INTEGER) BDPREFIXONAT, SUM(c.bdvlrcontab)';

    WSQLTOT = WSQLTOT||' from ( select M.BDCODEMP, M.BDCHAVE ';
    WSQLTOT = WSQLTOT||'        from VEF_EMP_TREDZ M ';
    WSQLTOT = WSQLTOT||'        where (m.BDDATAREDZ = '''||:BDDATAEMISSAO||''') ';
    WSQLTOT = WSQLTOT||'          and (m.BDCODEMP = '||BDCODEMP||') and (m.BDCHAVE = '||BDCHAVE||') ';
    WSQLTOT = WSQLTOT||'       ) m ';

    WSQLTOT = WSQLTOT||' join VEF_EMP_TREDZVARCFOP C on (c.BDCODEMP = m.BDCODEMP and c.BDCHAVE = m.BDCHAVE) ';

    IF (PRIMPSUFIXONAT = 0) THEN/*alt.:9059 = 0 false / 1 true*/
       WSQLTOT = WSQLTOT||' where (CAST(SUBSTRING(cast(c.bdcodnat as varchar(7)) FROM 1 FOR 4) AS INTEGER) = '||BDPREFIXONAT||')';
    ELSE
       WSQLTOT = WSQLTOT||' where (CAST(SUBSTRING(cast(c.bdcodnat as varchar(7)) FROM 1 FOR 7) AS INTEGER) = '||BDPREFIXONAT||')';
    
    WSQLTOT = WSQLTOT||' group by m.BDCODEMP, m.BDCHAVE, BDPREFIXONAT';
    WSQLTOT = WSQLTOT||' order by m.BDCODEMP, m.BDCHAVE, BDPREFIXONAT';

    EXECUTE STATEMENT WSQLTOT INTO :WCODEMP,wchave, :WNAT,:WVLRCONT;

    --select bdvlrcont FROM SP_VEF_VALORREDZLIVRO(:BDCODEMP,:BDPREFIXONAT,:bdchave,:BDDATAEMISSAO) into :WVLRCONT;
    BDVLRCONTAB = WVLRCONT;

    SUSPEND;

    BDCODEMP_BKP = BDCODEMP;
    BDCHAVE_BKP = BDCHAVE;
    BDPREFIXONAT_BKP = BDPREFIXONAT;
  END
END
^

/* Restore proc. body: SP_VEF_REL_APURACAO_GIAMG */
CREATE OR ALTER procedure SP_VEF_REL_APURACAO_GIAMG (
    PRCODEMP varchar(10000),
    PRANOMESINICIAL integer,
    PRANOMESFINAL integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDREFERENCIA integer,
    BDNUMCAMPO integer,
    BDCODQUADRO integer,
    BDCLASSIFICACAO varchar(11),
    BDDESCQUADRO varchar(80),
    BDDESCFORM varchar(150),
    BDVALOR numeric(15,2),
    BDCODTIPO integer,
    BDNUMITEM varchar(5),
    BDAREACONS varchar(10),
    BDESCCENTRAL varchar(5),
    BDTITULO varchar(60),
    BDREGISTRO varchar(60),
    BDSUBTITULO varchar(80),
    BDNUMITEMORD VARCHAR(7))
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable PRQUADROANT integer;
declare variable PRULTIMOCLASSIFITIT varchar(11);
declare variable WCLASSIFITITULO varchar(11);
declare variable WCLASSIFIPRINC varchar(11);
declare variable WAUX integer;
declare variable WAUX2 integer;
declare variable WTIT integer;
declare variable WULTIMOCLASSIFITIT varchar(11);
declare variable WTITULO varchar(60);
declare variable WREGISTRO varchar(60);
declare variable WDESCFORM varchar(150);
declare variable WSUBTITULO varchar(80);
declare variable WCODTIPO integer;
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql || 'empresas2.BDNOMEMP, ';
  wsql = wsql || 'T.BDREFERENCIA, ';
  wsql = wsql || 'T.BDNUMCAMPO, ';
  wsql = wsql || 'T.BDCODQUADRO,';
  wsql = wsql || 'TCONF.bdclassificacao, ';
  wsql = wsql || 'TCONF.bddescquadro,';
  wsql = wsql || 'TCONFGIAMGFORM.bddescform,';
  wsql = wsql || 'T.BDVALOR BDVALOR, ';
  wsql = wsql || 'TCONF.bdcodtipo, ';
  wsql = wsql || 'TCONFGIAMGFORM.BDNUMITEM, ';
--  wsql = wsql || 'cast(TCONFGIAMGFORM.BDNUMITEM as numeric(5,2)) BDNUMITEM, ';

  wsql = wsql || 'parmg.BDAREACONS, ';
  wsql = wsql || 'parmg.BDESCCENTRAL, ';
  wsql = wsql || 'null BDTITULO, ';
  wsql = wsql || 'null BDREGISTRO, ';
  wsql = wsql || 'null BDSUBTITULO, ';
  wsql = wsql || 'lPad(cast(TCONFGIAMGFORM.BDNUMITEM as numeric(5,2)),6,''0'') BDNUMITEMORD ';

  wsql = wsql || ' from VEF_EMP_TGIAMGGERREG T';

  wsql = wsql||' left outer join VW_EMPRESAS_REF_ATUAL empresas2 on (empresas2.bdcodemp = t.bdcodemp) ';
  wsql = wsql||' left outer join VEF_BASE_TEMPPARESTMG parmg on (parmg.bdcodemp = empresas2.bdcodemp and parmg.bdrefemp = empresas2.BDEMPREF) ';
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFGIAMGQ TCONF on (TCONF.bdcodquadro = t.bdcodquadro) ' ;
  wsql = wsql||' LEFT OUTER JOIN (SELECT t.BDDESCFORM, t.BDCODCONF, t.BDCODQUADRO, t.BDNUMCAMPO, ';
  wsql = wsql||'                         IIF((t.BDNUMITEM is null) or (t.BDNUMITEM = ''''), ''0'', t.BDNUMITEM) BDNUMITEM '; -- Alt.: #130006 - Estava com problema ao carregar as treeview da apuracao, pois tentava converter um campo vazio em integer...
  wsql = wsql||'                  FROM VEF_ESTADOS_TCONFGIAMGFORM t) TCONFGIAMGFORM on (TCONFGIAMGFORM.bdcodconf = parmg.BDCODCONFGIAMG and TCONFGIAMGFORM.bdcodquadro = T.BDCODQUADRO and TCONFGIAMGFORM.bdnumcampo = T.BDNUMCAMPO) ' ;
  wwhere = '';

  IF ((:PRCODEMP IS NOT NULL) AND (:PRCODEMP <> '')) THEN
     wwhere = ' where '||:PRCODEMP;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, BDCODQUADRO, cast(TCONFGIAMGFORM.BDNUMITEM as numeric(5,2))' ;

  prquadroant = 0;
  PRULTIMOCLASSIFITIT = '';
  WCLASSIFIPRINC = '';
  WTIT = 1;

  WTITULO = '';
  WREGISTRO = '';
  WSUBTITULO = '';
  WCODTIPO = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDNOMEMP ,
    BDREFERENCIA ,
    BDNUMCAMPO ,
    BDCODQUADRO,
    BDCLASSIFICACAO ,
    BDDESCQUADRO ,
    BDDESCFORM ,
    BDVALOR ,
    BDCODTIPO,
    BDNUMITEM,
    BDAREACONS,
    BDESCCENTRAL,
    BDTITULO,
    BDREGISTRO,
    BDSUBTITULO,
    BDNUMITEMORD
  DO
  BEGIN
    IF ((prquadroant <> bdcodquadro)) THEN   -- mostra o nome do quadro atual na consulta
      BEGIN
        SELECT FIRST 1 tpos.BDRPOS FROM rpos('.',  :bdclassificacao) tpos INTO :waux;

        IF ((WCLASSIFIPRINC = '') AND (waux > 1)) THEN
           BEGIN
              WCLASSIFIPRINC = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);
              WTIT = 1;
           END
        ELSE
           BEGIN
             IF (WCLASSIFIPRINC = SUBSTRING(bdclassificacao FROM 1 FOR waux-1)) THEN
                BEGIN
                   WTIT = 0;
                END
             ELSE
                BEGIN
                   WTIT = 1;
                END
    
             IF (waux > 1) THEN
                WCLASSIFIPRINC = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);
           END

        IF (waux > 1) THEN -- classificacao titulo
          BEGIN

            SELECT FIRST 1 tpos.pos FROM pos('.', :bdclassificacao) tpos INTO :waux2;

            wclassifititulo = SUBSTRING(bdclassificacao FROM 1 FOR waux2-1);

            SELECT FIRST 1 tpos.pos FROM pos('.', :prultimoclassifitit) tpos INTO :waux2;

            IF (waux2 > 0) THEN
               wultimoclassifitit = SUBSTRING(prultimoclassifitit FROM 1 FOR waux2-1);
            ELSE
               wultimoclassifitit = prultimoclassifitit;

            IF ((wultimoclassifitit <> wclassifititulo) AND (WTIT = 1)) THEN
              BEGIN

                SELECT x.bddescquadro FROM VEF_ESTADOS_TCONFGIAMGQ x WHERE x.bdclassificacao = :wclassifititulo INTO
                    :WDESCFORM;

                WTITULO = WDESCFORM;
              END

            wclassifititulo = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);

            IF ((prultimoclassifitit <> wclassifititulo) AND (WTIT = 1)) THEN
              BEGIN

                SELECT x.bddescquadro FROM VEF_ESTADOS_TCONFGIAMGQ x WHERE x.bdclassificacao = :wclassifititulo INTO
                    :WDESCFORM;

                WREGISTRO = WDESCFORM;
              END

            IF (WCODTIPO <> BDCODTIPO) THEN
               SELECT x.bddescquadro FROM VEF_ESTADOS_TCONFGIAMGQ x WHERE x.BDCODTIPO = :BDCODTIPO INTO
                      :WSUBTITULO;

            WCODTIPO = BDCODTIPO;
          END
      END

    BDREGISTRO = WREGISTRO;
    BDTITULO = WTITULO;
    BDSUBTITULO = WSUBTITULO;

    bddescform = '['||BDNUMITEM||'] - '||bddescform;
    SUSPEND;
  END
  
END
^

/* Restore proc. body: SP_VEF_REL_RETENCOES */

CREATE OR ALTER procedure SP_VEF_REL_RETENCOES (
    PRCODEMP varchar(10000),
    PRDATAINICIAL date,
    PRDATAFINAL date,
    PRTIPOMOV integer,
    PRCODTER integer,
    PRDETALHADO integer,
    PRTIPOLANSERV integer,
    PRTIPOAPURACAORETIR varchar(50),
    PRSOMAMATRIZFILIAL integer,
    PRVERORGAOPUBLICO varchar(5),
    PRCAMPODATA varchar(200))
returns (
    BDCODEMP integer,
    BDREF integer,
    BDMESEXTENSO varchar(20),
    BDCODTER integer,
    BDNOMETER varchar(100),
    BDCGCTER varchar(18),
    BDENDTER varchar(60),
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDVLRCONTAB numeric(15,2),
    BDVLRPIS numeric(15,2),
    BDVLRCOFINS numeric(15,2),
    BDVLRCSOCIAL numeric(15,2),
    BDVLRIR numeric(15,2),
    BDVLRINSS numeric(15,2),
    BDVLRISS numeric(15,2),
    BDVLRIRSER numeric(15,2),
    BDCONDPGTO integer)
as
declare variable WSQL varchar(32700);
declare variable WMES char(2);
declare variable WANO char(4);
declare variable WREFINCIAL integer;
declare variable WREFFINAL integer;
declare variable WDATA_FINAL date;
declare variable WCODTERATUAL integer;
declare variable WDATAAUX date;
declare variable WCHAVE integer;
BEGIN
  --sol:15749 - select externo responsavel por modificar os códigos das filiais em código da matriz, para que o relatorio agrupe tudo na mesma empresa
  IF (prSomaMatrizFilial = 1) then --1 true 0 false
    wsql = 'Select Coalesce(Emp.bdCodMatriz, Mov.BDCODEMP) BDCODEMP, ';
  ELSE
    wsql = 'Select MOV.BDCODEMP, ';
  wsql = wsql || 'Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDNOMETER,Mov.BDCGCTER,Mov.BDENDTER,Mov.BDCODCID,Mov.BDNOMCID,Mov.BDCONDPGTO,Mov.BDVLRCONTAB,';
  wsql = wSql || 'Mov.BDVLRPIS,Mov.BDVLRCOFINS,Mov.BDVLRCSOCIAL,Mov.BDVLRIR,Mov.BDVLRINSS,';
  IF ((prtipomov = 2) OR (prtipomov = 3))  THEN
     wsql = wSql || 'Mov.BDVLRISSSER';
  ELSE
     wsql = wSql || 'Mov.BDVLRISS';
  wsql = wSql || ',Mov.BDVLRIRSER from (';
  IF (prtipomov = 0) THEN -- entradas
    BEGIN
      wsql = wSql || 'Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Ter.BDNOMETER,Ter.BDCGCTER,Ter.BDENDTER,Ter.BDCODCID,Cid.BDNOMCID,Mov.BDCONDPGTO,Mov.BDVLRCONTAB BDVLRCONTAB,';
        wsql = wSql || 'SUM(Mov.BDVLRPIS) BDVLRPIS,SUM(Mov.BDVLRCOFINS) BDVLRCOFINS,SUM(Mov.BDVLRCSOCIAL) BDVLRCSOCIAL,';
        wsql = wSql || 'SUM(Mov.BDVLRIR) BDVLRIR,SUM(Mov.BDVLRINSS) BDVLRINSS,SUM(Mov.BDVLRISS) BDVLRISS,SUM(Mov.BDVLRIRSER) BDVLRIRSER from (';
      --sol:17084 - Competencia e regime de caixa PIS/Cofins/CSLL
      wsql = wSql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB,SUM(Mov.BDVLRPIS) BDVLRPIS,';
      wsql = wSql || '      SUM(Mov.BDVLRCOFINS) BDVLRCOFINS,SUM(Mov.BDVLRCSOCIAL) BDVLRCSOCIAL,0 as BDVLRIR,0 as BDVLRINSS,';
      wsql = wsql || '      0 as BDVLRISS,0 as BDVLRIRSER ';
      wsql = wSql || '      from VW_VEF_EMP_TMOVENT_E_ITENS Mov ';

      if (prsomamatrizfilial = 1) then
        begin
          wsql = wsql || '  join TEMPRESAS EMP on (EMP.BDCODEMP = MOV.BDCODEMP) ';
          wsql = wsql || '  join VW_VEF_BASE_TEMPPARGER PARGER on (COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) = PARGER.BDCODEMP) ';
        end
      else
        wsql = wsql || '    join VW_VEF_BASE_TEMPPARGER PARGER on (MOV.BDCODEMP = PARGER.BDCODEMP) ';

      wsql = wSql || '      where (MOV.'||:prCODEMP||') and (Mov.bdcodsitnf not in (2,3,4,5)) ';
      IF (prcodter > 0) THEN
         wsql = wSql || '   and Mov.BDCODTER =  (' || :prcodter || ')';
      wsql = wsql || '      and (Mov.BDDATAENTRADAENT BETWEEN '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || '      and (Mov.BDVLRCONTAB > 0) and ((BDVLRPIS > 0) or (BDVLRCOFINS > 0) or (BDVLRCSOCIAL > 0))';
      --Larissa - 20/09/2021 - Relatório de retenções para multi-seleção Empresa #93468 #99743 #147812 #152234 #154166 
      --IF (prtipoapuracaoret = 1) THEN
      wsql = wsql || '      and (MOV.BDCONDPGTO <> IIF(PARGER.BDTIPOAPURACAORET = 0, -1, 1)) ';
      wsql = wsql || '      Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO ';

      --Larissa - 20/09/2021 - Relatório de retenções para multi-seleção Empresa #93468 #99743 #147812 #152234 #154166 
      --IF (prtipoapuracaoret = 1) THEN
        --BEGIN
          wsql = wsql || '  union all ';
          wsql = wsql || '  Select Ret.BDCODEMP,Mov.BDCHAVE,cast(substring(Pgto.BDDATAPGTOPAR from 1 for 4) || substring(Pgto.BDDATAPGTOPAR from 6 for 2) as integer) as BDREFLAN,';
          wsql = wsql || '  Mov.BDCODTER,Mov.BDCONDPGTO,Mov.BDVALORNOTA BDVLRCONTAB, SUM(Pgto.BDVALORRETPIS) BDVLRPIS, SUM(Pgto.BDVALORRETCOFINS) BDVLRCOFINS,';
          wsql = wsql || '  SUM(Pgto.BDVALORRETCSLL) BDVLRCSOCIAL,0 as BDVLRIR,0 as BDVLRINSS,';
          wsql = wsql || '  0 as BDVLRISS, 0 as BDVLRIRSER ';
          wsql = wsql || '  from VEF_EMP_TMOVENTRET Ret ';
          wsql = wsql || '  join VEF_EMP_TMOVENT Mov on (RET.BDCODEMP = MOV.bdcodemp and RET.BDCHAVE = MOV.BDCHAVE) ';
          wsql = wsql || '  join VEF_EMP_TMOVENTPARPGTO Pgto on (RET.BDCODEMP = PGTO.BDCODEMP and RET.BDCHAVE = PGTO.BDCHAVE) ';

          if (prsomamatrizfilial = 1) then
            begin
              wsql = wsql || ' join TEMPRESAS EMP on (EMP.BDCODEMP = RET.BDCODEMP) ';
              wsql = wsql || ' join VW_VEF_BASE_TEMPPARGER PARGER on (COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) = PARGER.BDCODEMP) ';
            end
           else
             wsql = wsql || ' join VW_VEF_BASE_TEMPPARGER PARGER on (RET.BDCODEMP = PARGER.BDCODEMP) ';

          wsql = wsql || '  where ';
          wsql = wsql || '  PARGER.BDTIPOAPURACAORET = 1 and ';
          wsql = wsql || '  (RET.'||:prCODEMP||') and (Mov.bdcodsitnf not in (2,3,4,5)) and ';
          IF (prcodter > 0) THEN
            wsql = wSql || '(Mov.BDCODTER =  (' || :prcodter || ')) and ';
          wsql = wsql || '  (Pgto.BDDATAPGTOPAR between  '''||prdatainicial||''' and '''||prdatafinal||''') and ';
          wsql = wsql || '  (pgto.BDCODTIPOBAIXA <> 2) and '; --sol:16518 - Não levar no faturamento caso o tipo seja "Desconto"
          wsql = wsql || '  (BDVALORPGTOPAR > 0) and ((BDVLRPIS > 0) or (BDVLRCOFINS > 0) or (BDVLRCSOCIAL > 0)) ';
          wsql = wsql || '  Group By BDCODEMP,BDCHAVE,BDREFLAN,BDCODTER,BDCONDPGTO,BDVLRCONTAB';
        --END

      --sol:17084 - Competencia e regime de caixa IR
      wsql = wsql || '      union all ';
      wsql = wSql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB,0 as BDVLRPIS,';
      wsql = wSql || '      0 as BDVLRCOFINS,0 as BDVLRCSOCIAL,SUM(Mov.BDVLRIR) BDVLRIR,0 as BDVLRINSS,';
      wsql = wsql || '      0 as BDVLRISS,0 as BDVLRIRSER ';
      wsql = wSql || '      from VW_VEF_EMP_TMOVENT_E_ITENS Mov ';

      if (prsomamatrizfilial = 1) then
        begin
          wsql = wsql || '      join TEMPRESAS EMP on (EMP.BDCODEMP = MOV.BDCODEMP) ';
          wsql = wsql || '      join VW_VEF_BASE_TEMPPARGER PARGER on (COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) = PARGER.BDCODEMP) ';
        end
      else
        wsql = wsql || '      join VW_VEF_BASE_TEMPPARGER PARGER on (MOV.BDCODEMP = PARGER.BDCODEMP) ';
      wsql = wSql || '      where (MOV.'||:prCODEMP||') and (Mov.bdcodsitnf not in (2,3,4,5)) ';
      IF (prcodter > 0) THEN
         wsql = wSql || '   and Mov.BDCODTER =  (' || :prcodter || ')';
      wsql = wsql || '      and (Mov.BDDATAENTRADAENT BETWEEN '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || '      and (Mov.BDVLRCONTAB > 0) and (BDVLRIR > 0)';
      --IF (prtipoapuracaoretir = 1) THEN --Larissa - 20/09/2021 - Relatório de retenções para multi-seleção Empresa #93468 #99743 #147812 #152234 #154166 
      wsql = wsql || '      and (MOV.BDCONDPGTO <> IIF(PARGER.' || :PRTIPOAPURACAORETIR || ' = 0, -1, 1)) ';
      wsql = wsql || '      Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO ';

      --Larissa - 20/09/2021 - Relatório de retenções para multi-seleção Empresa #93468 #99743 #147812 #152234 #154166 
      --IF (prtipoapuracaoretir = 1) THEN
        --BEGIN
          wsql = wsql || '  union all ';
          wsql = wsql || '  Select Ret.BDCODEMP,Mov.BDCHAVE,cast(substring(Pgto.BDDATAPGTOPAR from 1 for 4) || substring(Pgto.BDDATAPGTOPAR from 6 for 2) as integer) as BDREFLAN,';
          wsql = wsql || '  Mov.BDCODTER,Mov.BDCONDPGTO,Mov.BDVALORNOTA BDVLRCONTAB, 0 as BDVLRPIS, 0 as BDVLRCOFINS,';
          wsql = wsql || '  0 as BDVLRCSOCIAL,SUM(Pgto.BDVALORRETIRRF) as BDVLRIR,0 as BDVLRINSS,';
          wsql = wsql || '  0 as BDVLRISS, 0 as BDVLRIRSER ';
          wsql = wsql || '  from VEF_EMP_TMOVENTRET Ret ';
          wsql = wsql || '  join VEF_EMP_TMOVENT Mov on (ret.bdcodemp = mov.bdcodemp and ret.bdchave = mov.bdchave) ';
          wsql = wsql || '  join VEF_EMP_TMOVENTPARPGTO Pgto on (ret.bdcodemp = pgto.bdcodemp and pgto.bdchave = RET.bdchave) ';

          if (prsomamatrizfilial = 1) then
            BEGIN
                wsql = wsql || ' join TEMPRESAS EMP on (EMP.BDCODEMP = RET.BDCODEMP) ';
                wsql = wsql || ' join VW_VEF_BASE_TEMPPARGER PARGER on (COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) = PARGER.BDCODEMP) ';
            END
          else
            wsql = wsql || '  join VW_VEF_BASE_TEMPPARGER PARGER on (RET.BDCODEMP = PARGER.BDCODEMP) ';

          wsql = wsql || '  where ';
          wsql = wsql || '  (RET.'||:prCODEMP||') and (Mov.bdcodsitnf not in (2,3,4,5)) and ';
          IF (prcodter > 0) THEN
            wsql = wSql || '(Mov.BDCODTER =  (' || :prcodter || ')) and ';
          wsql = wsql || '  (Pgto.BDDATAPGTOPAR between  '''||prdatainicial||''' and '''||prdatafinal||''') and ';
          wsql = wsql || '  (pgto.BDCODTIPOBAIXA <> 2) and '; --sol:16518 - Não levar no faturamento caso o tipo seja "Desconto"
          wsql = wsql || '  (BDVALORPGTOPAR > 0) and (BDVLRIR > 0) and ';
          wsql = wsql || '  PARGER.' || PRTIPOAPURACAORETIR ||' = 1 ';
          wsql = wsql || '  Group By BDCODEMP,BDCHAVE,BDREFLAN,BDCODTER,BDCONDPGTO,BDVLRCONTAB';
        --END

      --sol:17084 - ISS e INSS
      wsql = wsql || '      union all ';
      wsql = wSql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB,0 as BDVLRPIS,';
      wsql = wSql || '      0 as BDVLRCOFINS,0 as BDVLRCSOCIAL,0 as BDVLRIR,SUM(Mov.BDVLRINSS) BDVLRINSS,';
      wsql = wsql || '      SUM(Mov.BDVLRISS) BDVLRISS,0 as BDVLRIRSER ';
      wsql = wSql || '      from VW_VEF_EMP_TMOVENT_E_ITENS Mov ';
      wsql = wSql || '      where (MOV.'||:prCODEMP||') and (Mov.bdcodsitnf not in (2,3,4,5)) ';
      IF (prcodter > 0) THEN
         wsql = wSql || '   and Mov.BDCODTER =  (' || :prcodter || ')';
      wsql = wsql || '      and (Mov.BDDATAENTRADAENT BETWEEN '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || '      and (Mov.BDVLRCONTAB > 0) and ((BDVLRINSS > 0) or (BDVLRISS > 0))';
      wsql = wsql || '      Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO ';

      wsql = wsql || ') Mov ';
      wsql = wSql || 'LEFT OUTER JOIN VW_TTERCEIRO Ter ON (Ter.BDCODTER = Mov.BDCODTER) ';
      wsql = wSql || 'LEFT OUTER JOIN TCIDADE Cid ON (CID.BDCODCID = Ter.BDCODCID) ';
      --IF (prtipoapuracaoret = 1) THEN -- Tipo de apuração das retenções = Regime de caixa
      --  wsql = wsql || 'LEFT OUTER JOIN VEF_EMP_TMOVENTPARPGTO Pgto on (Mov.BDCODEMP = Pgto.BDCODEMP and Mov.BDCHAVE = Pgto.BDCHAVE and Pgto.BDDATAPGTOPAR between '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || 'Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Ter.BDNOMETER,Ter.BDCGCTER,Ter.BDENDTER,Ter.BDCODCID,Cid.BDNOMCID,Mov.BDCONDPGTO,Mov.BDVLRCONTAB ';
      wsql = wSql || 'Order by Mov.BDCODEMP,Mov.BDCODTER,Mov.BDREFLAN';
    END
  ELSE
  IF (prtipomov = 1) THEN -- saidas
    BEGIN
      wsql = wSql || 'Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Ter.BDNOMETER,Ter.BDCGCTER,Ter.BDENDTER,Ter.BDCODCID,Cid.BDNOMCID,Mov.BDCONDPGTO,Mov.BDVLRCONTAB BDVLRCONTAB,';
        wsql = wSql || 'SUM(Mov.BDVLRPIS) BDVLRPIS,SUM(Mov.BDVLRCOFINS) BDVLRCOFINS,SUM(Mov.BDVLRCSOCIAL) BDVLRCSOCIAL,SUM(Mov.BDVLRIR) BDVLRIR,';
        wsql = wSql || 'SUM(Mov.BDVLRINSS) BDVLRINSS,SUM(Mov.BDVLRISS) BDVLRISS,SUM(Mov.BDVLRIRSER) BDVLRIRSER from (';
      --sol:17084 - Competencia e regime de caixa PIS/Cofins/CSLL
      wsql = wsql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB,SUM(Mov.BDVLRPIS) BDVLRPIS,';
      wsql = wSql || '      SUM(Mov.BDVLRCOFINS) BDVLRCOFINS,SUM(Mov.BDVLRCSOCIAL) BDVLRCSOCIAL,0 AS BDVLRIR,0 AS BDVLRINSS,';
      wsql = wsql || '      0 AS BDVLRISS,0 as BDVLRIRSER ';
      wsql = wSql || '      from VW_VEF_EMP_TMOVSAI_E_ITENS Mov ';
      if (prsomamatrizfilial = 1) then
        BEGIN
          wsql = wsql || '  join TEMPRESAS EMP on (EMP.BDCODEMP = MOV.BDCODEMP) ';
          wsql = wsql || '  join VW_VEF_BASE_TEMPPARGER PARGER on (COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) = PARGER.BDCODEMP) ';
        END
      ELSE
        wsql = wsql || '      join VW_VEF_BASE_TEMPPARGER PARGER on (MOV.BDCODEMP = PARGER.BDCODEMP) ';
      wsql = wSql || '      where (MOV.'||:prCODEMP||') and (Mov.bdcodsitnf not in (2,3,4,5)) ';
      IF (prcodter > 0) THEN
         wsql = wSql || '   and Mov.BDCODTER =  (' || :prcodter || ') ';
      wsql = wsql || '      and (Mov.BDDATASAIDA BETWEEN '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || '      and (Mov.BDVLRCONTAB > 0) and ((BDVLRPIS > 0) or (BDVLRCOFINS > 0) or (BDVLRCSOCIAL > 0)) ';
      --Larissa - 20/09/2021 - Relatório de retenções para multi-seleção Empresa #93468 #99743 #147812 #152234 #154166 
        wsql = wsql || '   and (MOV.BDCONDPGTO <> IIF(PARGER.BDTIPOAPURACAORET = 0, -1, 1)) ';
      wsql = wsql || '     Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO';
      --Larissa - 20/09/2021 - Relatório de retenções para multi-seleção Empresa #93468 #99743 #147812 #152234 #154166 
          wsql = wsql || '  union all ';
          wsql = wsql || '  Select Ret.BDCODEMP,Mov.BDCHAVE,cast(substring(Pgto.BDDATAPGTOPAR from 1 for 4) || substring(Pgto.BDDATAPGTOPAR from 6 for 2) as integer) as BDREFLAN,';
          wsql = wsql || '  Mov.BDCODTER,Mov.BDCONDPGTO,Mov.BDVALORNOTA BDVLRCONTAB, SUM(Pgto.BDVALORRETPIS) BDVLRPIS, SUM(Pgto.BDVALORRETCOFINS) BDVLRCOFINS,';
          wsql = wsql || '  SUM(Pgto.BDVALORRETCSLL) BDVLRCSOCIAL, 0 as BDVLRIR,0 AS BDVLRINSS,';
          wsql = wsql || '  0 AS BDVLRISS, 0 as BDVLRIRSER ';
          wsql = wsql || '  from VEF_EMP_TMOVSAIRET Ret ';
          wsql = wsql || '  join VEF_EMP_TMOVSAI Mov on (ret.bdcodemp = mov.bdcodemp and ret.bdchave = mov.bdchave) ';
          wsql = wsql || '  join VEF_EMP_TMOVSAIPARPGTO Pgto on (ret.bdcodemp = pgto.bdcodemp and ret.bdchave = pgto.bdchave) ';

          if (prsomamatrizfilial = 1) then
            BEGIN
              wsql = wsql || '  join TEMPRESAS EMP on (EMP.BDCODEMP = MOV.BDCODEMP) ';
              wsql = wsql || '  join VW_VEF_BASE_TEMPPARGER PARGER on (COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) = PARGER.BDCODEMP) ';
            END
          ELSE
            wsql = wsql || '  join VW_VEF_BASE_TEMPPARGER PARGER on (MOV.BDCODEMP = PARGER.BDCODEMP) ';

          wsql = wsql || '  where ';
          wsql = wsql || '  (RET.'||:prCODEMP||') and (Mov.bdcodsitnf not in (2,3,4,5)) and ';
          IF (prcodter > 0) THEN
            wsql = wSql || '(Mov.BDCODTER =  (' || :prcodter || ')) and ';
          wsql = wsql || '  (Pgto.BDDATAPGTOPAR between  '''||prdatainicial||''' and '''||prdatafinal||''') and ';
          wsql = wsql || '  (pgto.BDCODTIPOBAIXA <> 2) and '; --sol:16518 - Não levar no faturamento caso o tipo seja "Desconto"
          wsql = wsql || '  (BDVALORPGTOPAR > 0) and ((BDVLRPIS > 0) or (BDVLRCOFINS > 0) or (BDVLRCSOCIAL > 0)) and ';
          wsql = wsql || '  PARGER.BDTIPOAPURACAORET = 1 ';
          wsql = wsql || '  Group By BDCODEMP,BDCHAVE,BDREFLAN,BDCODTER,BDCONDPGTO,BDVLRCONTAB';
        --END

      --sol:17084 - Competencia e regime de caixa IR
      wsql = wsql || '      union all ';
      wsql = wsql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB, 0 AS BDVLRPIS,';
      wsql = wSql || '      0 AS BDVLRCOFINS, 0 AS BDVLRCSOCIAL,SUM(Mov.BDVLRIR) BDVLRIR, 0 AS BDVLRINSS,';
      wsql = wsql || '      0 AS BDVLRISS,0 as BDVLRIRSER ';
      wsql = wSql || '      from VW_VEF_EMP_TMOVSAI_E_ITENS Mov ';

      if (prsomamatrizfilial = 1) then
        begin
          wsql = wsql || '  join TEMPRESAS emp on (EMP.BDCODEMP = MOV.BDCODEMP) ';
          wsql = wsql || '  join VW_VEF_BASE_TEMPPARGER PARGER on (COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) = PARGER.BDCODEMP) ';
        end
      else
        wsql = wsql || '      join VW_VEF_BASE_TEMPPARGER PARGER on (MOV.BDCODEMP = PARGER.BDCODEMP) ';

      if (UPPER(PRVERORGAOPUBLICO) = 'TRUE') then
      begin
        WSQL = WSQL || '            left outer join(select BDCODTER, RF2.BDORGAOPUBLICO, RF2.BDCGCTER, RF2.BDNOMETER, RF2.BDREFEMP ';
        WSQL = WSQL || '                            from TTERCEIRO_REF RF2 ';
        WSQL = WSQL || '                            where RF2.BDREFEMP = coalesce((select first 1 BDREFEMP ';
        WSQL = WSQL || '                                                           from TTERCEIRO_REF RF3 ';
        WSQL = WSQL || '                                                           where RF3.BDCODTER = RF2.BDCODTER and ';
        WSQL = WSQL || '                                                                 RF3.BDREFEMP <= Substring('''|| :PRDATAFINAL ||''' from 1 for 4) ||  Substring('''|| :PRDATAFINAL ||''' from 6 for 2) ';
        WSQL = WSQL || '                                                           order by RF3.BDREFEMP desc), (select first 1 BDREFEMP ';
        WSQL = WSQL || '                                                                                         from TTERCEIRO_REF RF3 ';
        WSQL = WSQL || '                                                                                         where RF3.BDCODTER = RF2.BDCODTER ';
        WSQL = WSQL || '                                                                                         order by RF3.BDCODTER, RF3.BDREFEMP))) as TER on TER.BDCODTER = ';
        IF (prcodter > 0) THEN
         wsql = wSql || ' (' || :prcodter || ')';
        ELSE
         WSQL = WSQL || ' Mov.BDCODTER ';
      end

      wsql = wSql || '      where (MOV.'||:prCODEMP||') and (Mov.bdcodsitnf not in (2,3,4,5)) ';
      IF (prcodter > 0) THEN
         wsql = wSql || '   and Mov.BDCODTER =  (' || :prcodter || ') ';
      wsql = wsql || '      and (Mov.BDDATASAIDA BETWEEN '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || '      and (Mov.BDVLRCONTAB > 0) and (BDVLRIR > 0) ';
      --Larissa - 20/09/2021 - Relatório de retenções para multi-seleção Empresa #93468 #99743 #147812 #152234 #154166 
      --IF (prtipoapuracaoretir = 1) THEN
      wsql = wsql || '     and (MOV.BDCONDPGTO <> ';

      if (UPPER(PRVERORGAOPUBLICO) = 'TRUE') then
        wsql = wsql || 'IIF(iif(ter.bdorgaopublico = true, 1, PARGER.' || :PRTIPOAPURACAORETIR || ') = 0, -1, 1)) ';
      else
        wsql = wsql || 'IIF(PARGER.' || :PRTIPOAPURACAORETIR || ' = 0, -1, 1)) ';

      wsql = wsql || '     Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO';

      --Larissa - 20/09/2021 - Relatório de retenções para multi-seleção Empresa #93468 #99743 #147812 #152234 #154166 
      --IF (prtipoapuracaoretir = 1) THEN
        --BEGIN
          wsql = wsql || '  union all ';
          wsql = wsql || '  Select Ret.BDCODEMP,Mov.BDCHAVE,cast(substring(Pgto.BDDATAPGTOPAR from 1 for 4) || substring(Pgto.BDDATAPGTOPAR from 6 for 2) as integer) as BDREFLAN,';
          wsql = wsql || '  Mov.BDCODTER,Mov.BDCONDPGTO,Mov.BDVALORNOTA BDVLRCONTAB, 0 AS BDVLRPIS, 0 AS BDVLRCOFINS,';
          wsql = wsql || '  0 AS BDVLRCSOCIAL,SUM(Pgto.BDVALORRETIRRF) as BDVLRIR,0 AS BDVLRINSS,';
          wsql = wsql || '  0 AS BDVLRISS, 0 as BDVLRIRSER ';
          wsql = wsql || '  from VEF_EMP_TMOVSAIRET Ret ';
          wsql = wsql || '  join VEF_EMP_TMOVSAI Mov on (ret.bdcodemp = mov.bdcodemp and ret.bdchave = mov.bdchave) ';
          wsql = wsql || '  join VEF_EMP_TMOVSAIPARPGTO Pgto on (ret.bdcodemp = pgto.bdcodemp and ret.bdchave = pgto.bdchave) ';

          if (prsomamatrizfilial = 1) then
            begin
              wsql = wsql || ' join TEMPRESAS emp on (EMP.BDCODEMP = MOV.BDCODEMP) ';
              wsql = wsql || '  join VW_VEF_BASE_TEMPPARGER PARGER on (COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) = PARGER.BDCODEMP) ';
            end
          else
            wsql = wsql || '  join VW_VEF_BASE_TEMPPARGER PARGER on (MOV.BDCODEMP = PARGER.BDCODEMP) ';

      if (UPPER(PRVERORGAOPUBLICO) = 'TRUE') then
      begin
        WSQL = WSQL || '            left outer join(select BDCODTER, RF2.BDORGAOPUBLICO, RF2.BDCGCTER, RF2.BDNOMETER, RF2.BDREFEMP ';
        WSQL = WSQL || '                            from TTERCEIRO_REF RF2 ';
        WSQL = WSQL || '                            where RF2.BDREFEMP = coalesce((select first 1 BDREFEMP ';
        WSQL = WSQL || '                                                           from TTERCEIRO_REF RF3 ';
        WSQL = WSQL || '                                                           where RF3.BDCODTER = RF2.BDCODTER and ';
        WSQL = WSQL || '                                                                 RF3.BDREFEMP <= Substring('''|| :PRDATAFINAL ||''' from 1 for 4) ||  Substring('''|| :PRDATAFINAL ||''' from 6 for 2) ';
        WSQL = WSQL || '                                                           order by RF3.BDREFEMP desc), (select first 1 BDREFEMP ';
        WSQL = WSQL || '                                                                                         from TTERCEIRO_REF RF3 ';
        WSQL = WSQL || '                                                                                         where RF3.BDCODTER = RF2.BDCODTER ';
        WSQL = WSQL || '                                                                                         order by RF3.BDCODTER, RF3.BDREFEMP))) as TER on TER.BDCODTER = ';
        IF (prcodter > 0) THEN
         wsql = wSql || ' (' || :prcodter || ')';
        ELSE
         WSQL = WSQL || ' Mov.BDCODTER ';
      end

          wsql = wsql || '  where ';
          wsql = wsql || '  (Ret.BDCODEMP = Mov.BDCODEMP) and ';
          wsql = wsql || '  (Ret.BDCHAVE = Mov.BDCHAVE) and ';
          wsql = wsql || '  (Ret.BDCODEMP = Pgto.BDCODEMP and Ret.BDCHAVE = Pgto.BDCHAVE) and ';
          wsql = wsql || '  (RET.'||:prCODEMP||') and (Mov.bdcodsitnf not in (2,3,4,5)) and ';
          IF (prcodter > 0) THEN
            wsql = wSql || '(Mov.BDCODTER =  (' || :prcodter || ')) and ';
          wsql = wsql || '  (Pgto.BDDATAPGTOPAR between  '''||prdatainicial||''' and '''||prdatafinal||''') and ';
          wsql = wsql || '  (pgto.BDCODTIPOBAIXA <> 2) and '; --sol:16518 - Não levar no faturamento caso o tipo seja "Desconto"
          wsql = wsql || '  (BDVALORPGTOPAR > 0) and (BDVLRIR > 0) and ';

          if (UPPER(PRVERORGAOPUBLICO) = 'TRUE') then
            wsql = wsql || 'iif(ter.bdorgaopublico = true, 1, PARGER.' || :PRTIPOAPURACAORETIR || ') = 1 ';
          else
          wsql = wsql || '  PARGER.' || :PRTIPOAPURACAORETIR || ' = 1 ';

          wsql = wsql || '  Group By BDCODEMP,BDCHAVE,BDREFLAN,BDCODTER,BDCONDPGTO,BDVLRCONTAB';
        --END

      --sol:17084 - ISS e INSS
      wsql = wsql || '      union all ';
      wsql = wsql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB,0 AS  BDVLRPIS,';
      wsql = wSql || '      0 AS BDVLRCOFINS,0 AS BDVLRCSOCIAL,0 AS BDVLRIR,SUM(Mov.BDVLRINSS) BDVLRINSS,';
      wsql = wsql || '      SUM(Mov.BDVLRISS) BDVLRISS,0 as BDVLRIRSER ';
      wsql = wSql || '      from VW_VEF_EMP_TMOVSAI_E_ITENS Mov ';
      wsql = wSql || '      where (MOV.'||:prCODEMP||') and (Mov.bdcodsitnf not in (2,3,4,5)) ';
      IF (prcodter > 0) THEN
         wsql = wSql || '   and Mov.BDCODTER =  (' || :prcodter || ') ';
      wsql = wsql || '      and (Mov.BDDATASAIDA BETWEEN '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || '      and (Mov.BDVLRCONTAB > 0) and ((BDVLRINSS > 0) or (BDVLRISS > 0)) ';
      wsql = wsql || '     Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO';

      wsql = wsql || ') Mov ';
      wsql = wSql || 'LEFT OUTER JOIN VW_TTERCEIRO Ter ON (Ter.BDCODTER = Mov.BDCODTER) ';
      wsql = wSql || 'LEFT OUTER JOIN TCIDADE Cid ON (Cid.BDCODCID = Ter.BDCODCID) ';
      --IF (prtipoapuracaoret = 1) THEN -- Tipo de apuração das retenções = Regime de caixa
      --  wsql = wsql || 'LEFT OUTER JOIN VEF_EMP_TMOVSAIPARPGTO Pgto on (Mov.BDCODEMP = Pgto.BDCODEMP and Mov.BDCHAVE = Pgto.BDCHAVE and Pgto.BDDATAPGTOPAR between '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || 'Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Ter.BDNOMETER,Ter.BDCGCTER,Ter.BDENDTER,Ter.BDCODCID,Cid.BDNOMCID,Mov.BDCONDPGTO,Mov.BDVLRCONTAB ';
      wsql = wSql || 'Order by Mov.BDCODEMP,Mov.BDCODTER,Mov.BDREFLAN';
    END
  ELSE
  IF (prtipomov = 2) THEN -- servicos
    BEGIN
      wsql = wSql || 'Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Ter.BDNOMETER,Ter.BDCGCTER,Ter.BDENDTER,Ter.BDCODCID,Cid.BDNOMCID,Mov.BDCONDPGTO,Mov.BDVLRCONTAB BDVLRCONTAB,';
        wsql = wSql || 'SUM(Mov.BDVLRPIS) BDVLRPIS,SUM(Mov.BDVLRCOFINS) BDVLRCOFINS,SUM(Mov.BDVLRCSOCIAL) BDVLRCSOCIAL,SUM(Mov.BDVLRIR) BDVLRIR,';
        wsql = wSql || 'SUM(Mov.BDVLRINSS) BDVLRINSS,SUM(Mov.BDVLRISSSER) BDVLRISSSER,SUM(Mov.BDVLRIRSER) BDVLRIRSER from (';

      --sol:17084 - Competencia e regime de caixa PIS/Cofins/CSLL
      wsql = wSql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB,SUM(Mov.BDVLRPIS) BDVLRPIS,';
      wsql = wSql || '      SUM(Mov.BDVLRCOFINS) BDVLRCOFINS,SUM(Mov.BDVLRCSOCIAL) BDVLRCSOCIAL, 0 AS BDVLRIR,0 AS BDVLRINSS,0 AS BDVLRISSSER,';
      wsql = wsql || '      0 AS BDVLRIRSER ';
      /*sol:10642 - substituido o VW_VEF_EMP_TMOVSER_E_ITENS pela tabela de serviço (com join para as deduções/retenções) pois essa view tras os valores de ded/ret matriciado se o lanc tiver mais de uma cfop
      wsql = wSql || '      from VW_VEF_EMP_TMOVSER_E_ITENS Mov ';*/
      wsql = wSql || '     from (select MOV.*, coalesce(RET.BDISSRET, 0) BDVLRISSSER, coalesce(DED.BDRETINSS, 0) BDVLRINSS, COALESCE(RET.bdvlrpis,0.0) BDVLRPIS, ';
      wsql = wSql || '                 COALESCE(RET.bdvlrcofins,0.0) BDVLRCOFINS, COALESCE(RET.bdvlrcsocial,0.0) BDVLRCSOCIAL ';
      wsql = wSql || '          from (select MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, MOV.BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, ';
      wsql = wSql || '                       MOV.BDNUMDOCINI, MOV.BDCONDPGTO, Mov.BDREFLAN, sum(ITEM.BDVLRCONTAB) BDVLRCONTAB, sum(COALESCE(ITEM.bdvlrirser,0)) bdvlrirser ';
      wsql = wSql || '                from (select MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, '||PRCAMPODATA||' BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, ';
      wsql = wSql || '                             MOV.BDNUMDOCINI, MOV.BDCONDPGTO,Mov.BDREFLAN ';
      wsql = wSql || '                      from VEF_EMP_TMOVSER MOV ';

      if (prsomamatrizfilial = 1) then
       begin
         wsql = wsql || '                   join TEMPRESAS EMP on (emp.bdcodemp = mov.bdcodemp) ';
         wsql = wsql || '                   join VW_VEF_BASE_TEMPPARGER PARGER on (COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) = PARGER.BDCODEMP) ';
       end
      else
        wsql = wsql || '                      join VW_VEF_BASE_TEMPPARGER PARGER on (MOV.BDCODEMP = PARGER.BDCODEMP) ';

      wsql = wSql || '                      where (MOV.'||:prCODEMP||') and ';
      wsql = wSql || '                            (MOV.BDCODSITNF not in (2, 3, 4, 5)) and ';
      IF (prcodter > 0) THEN
         wsql = wSql || '                          Mov.BDCODTER = (' || :prcodter || ') and ';
      wsql = wSql || '                            ('||PRCAMPODATA||' between '''||prdatainicial||''' and '''||prdatafinal||''') ';
      IF (prtipolanserv = 0) THEN /* Servico emitido */
         wsql = wSql || '                         and (Mov.BDTIPLAN = 0) ';
      ELSE
         wsql = wSql || '                         and (Mov.BDTIPLAN = 1) ';
      --Larissa - 20/09/2021 - Relatório de retenções para multi-seleção Empresa #93468 #99743 #147812 #152234 #154166 
      --IF (prtipoapuracaoret = 1) THEN
      wsql = wsql || '                            and (MOV.BDCONDPGTO <> IIF(PARGER.BDTIPOAPURACAORET = 0, -1, 1)) ';
      wsql = wSql || '                      ) MOV ';
      wsql = wSql || '                left outer join VEF_EMP_TMOVSERITENS ITEM on (ITEM.BDCODEMP = MOV.BDCODEMP and ITEM.BDCHAVE = MOV.BDCHAVE) ';
      wsql = wSql || '                group by MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, MOV.BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, MOV.BDNUMDOCINI, MOV.BDCONDPGTO, MOV.bdreflan) MOV ';
      wsql = wSql || '          left outer join VEF_EMP_TMOVSERRET RET on (RET.BDCODEMP = MOV.BDCODEMP and RET.BDCHAVE = MOV.BDCHAVE) ';
      wsql = wSql || '          left outer join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = MOV.BDCODEMP and DED.BDCHAVE = MOV.BDCHAVE)) MOV ';
      wsql = wSql || '      where (Mov.BDVLRCONTAB > 0) and ((Mov.BDVLRPIS > 0) or (Mov.BDVLRCOFINS > 0) or (Mov.BDVLRCSOCIAL > 0)) ';
      wsql = wsql || '      Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO';
      --Larissa - 20/09/2021 - Relatório de retenções para multi-seleção Empresa #93468 #99743 #147812 #152234 #154166 
          wsql = wsql || '  union all ';
          wsql = wsql || '  Select Ret.BDCODEMP,Mov.BDCHAVE,cast(substring(Pgto.BDDATAPGTOPAR from 1 for 4) || substring(Pgto.BDDATAPGTOPAR from 6 for 2) as integer) as BDREFLAN,';
          wsql = wsql || '  Mov.BDCODTER,Mov.BDCONDPGTO,Mov.BDVALORNOTA BDVLRCONTAB, SUM(Pgto.BDVALORRETPIS) BDVLRPIS, SUM(Pgto.BDVALORRETCOFINS) BDVLRCOFINS,';
          wsql = wsql || '  SUM(Pgto.BDVALORRETCSLL) BDVLRCSOCIAL,0 as BDVLRIR,0 as BDVLRINSS,';
          wsql = wsql || '  0 as BDVLRISS,0 as BDVLRIRSER ';
          wsql = wsql || '  from VEF_EMP_TMOVSERRET Ret ';
          wsql = wsql || '  join VEF_EMP_TMOVSER Mov on (ret.bdcodemp = mov.bdcodemp and ret.bdchave = mov.bdchave) ';
          wsql = wsql || '  join VEF_EMP_TMOVSERPARPGTO Pgto on (ret.bdcodemp = pgto.bdcodemp and ret.bdchave = pgto.bdchave) ';
          if (prsomamatrizfilial = 1) then
            begin
               wsql = wsql || ' join tempresas emp on (emp.bdcodemp = mov.bdcodemp) ';
               wsql = wsql || ' join VW_VEF_BASE_TEMPPARGER PARGER on (coalesce(emp.bdcodmatriz, emp.bdcodemp) = PARGER.BDCODEMP) ';
            end
          else
            wsql = wsql || '  join VW_VEF_BASE_TEMPPARGER PARGER on (MOV.BDCODEMP = PARGER.BDCODEMP) ';
          wsql = wsql || '  where ';
          wsql = wsql || '  (Ret.BDCODEMP = Mov.BDCODEMP) and ';
          wsql = wsql || '  (Ret.BDCHAVE = Mov.BDCHAVE) and ';
          wsql = wsql || '  (Ret.BDCODEMP = Pgto.BDCODEMP and Ret.BDCHAVE = Pgto.BDCHAVE) and ';
          wsql = wsql || '  (RET.'||:prCODEMP||') and (Mov.bdcodsitnf not in (2,3,4,5)) and ';
          IF (prcodter > 0) THEN
            wsql = wSql || '(Mov.BDCODTER =  (' || :prcodter || ')) and ';
          wsql = wsql || '  (Pgto.BDDATAPGTOPAR between  '''||prdatainicial||''' and '''||prdatafinal||''') and ';
          wsql = wsql || '  (pgto.BDCODTIPOBAIXA <> 2) and '; --sol:16518 - Não levar no faturamento caso o tipo seja "Desconto"
          wsql = wsql || '  (BDVALORPGTOPAR > 0) and ((BDVLRPIS > 0) or (BDVLRCOFINS > 0) or (BDVLRCSOCIAL > 0)) and ';
          wsql = wsql || '  PARGER.BDTIPOAPURACAORET = 1 ';
          IF (prtipolanserv = 0) THEN /* Servico emitido */
            wsql = wSql || 'and (Mov.BDTIPLAN = 0) ';
          ELSE
            wsql = wSql || 'and (Mov.BDTIPLAN = 1) ';
          wsql = wsql || '  Group By BDCODEMP,BDCHAVE,BDREFLAN,BDCODTER,BDCONDPGTO,BDVLRCONTAB';
        --END
      --sol:17084 - Competencia e regime de caixa IR
      wsql = wsql || '      union all ';
      wsql = wSql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB,0 AS BDVLRPIS,';
      wsql = wSql || '      0 AS BDVLRCOFINS,0 AS BDVLRCSOCIAL, 0 AS BDVLRIR,0 AS BDVLRINSS,0 AS BDVLRISSSER,';
      wsql = wsql || '      SUM(Mov.BDVLRIRSER) BDVLRIRSER ';
      wsql = wSql || '     from (select MOV.*, coalesce(RET.BDISSRET, 0) BDVLRISSSER, coalesce(DED.BDRETINSS, 0) BDVLRINSS, COALESCE(RET.bdvlrpis,0.0) BDVLRPIS, ';
      wsql = wSql || '                 COALESCE(RET.bdvlrcofins,0.0) BDVLRCOFINS, COALESCE(RET.bdvlrcsocial,0.0) BDVLRCSOCIAL ';
      wsql = wSql || '          from (select MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, MOV.BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, ';
      wsql = wSql || '                       MOV.BDNUMDOCINI, MOV.BDCONDPGTO, Mov.BDREFLAN, sum(ITEM.BDVLRCONTAB) BDVLRCONTAB, sum(COALESCE(ITEM.bdvlrirser,0)) bdvlrirser ';
      wsql = wSql || '                from (select MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, '||PRCAMPODATA||' BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, ';
      wsql = wSql || '                             MOV.BDNUMDOCINI, MOV.BDCONDPGTO,Mov.BDREFLAN ';
      wsql = wSql || '                      from VEF_EMP_TMOVSER MOV ';
      if (prsomamatrizfilial = 1) then
        begin
            wsql = wsql || '                join tempresas emp on (emp.bdcodemp = mov.bdcodemp) ';
            wsql = wsql || '                join VW_VEF_BASE_TEMPPARGER PARGER on (coalesce(emp.bdcodmatriz, emp.bdcodemp) = PARGER.BDCODEMP) ';
        end
      else
        wsql = wsql || '                      join VW_VEF_BASE_TEMPPARGER PARGER on (MOV.BDCODEMP = PARGER.BDCODEMP) ';
      if ((UPPER(PRVERORGAOPUBLICO) = 'TRUE') and (prtipolanserv = 0)) then
      begin
        WSQL = WSQL || '            left outer join(select BDCODTER, RF2.BDORGAOPUBLICO, RF2.BDCGCTER, RF2.BDNOMETER, RF2.BDREFEMP ';
        WSQL = WSQL || '                            from TTERCEIRO_REF RF2 ';
        WSQL = WSQL || '                            where RF2.BDREFEMP = coalesce((select first 1 BDREFEMP ';
        WSQL = WSQL || '                                                           from TTERCEIRO_REF RF3 ';
        WSQL = WSQL || '                                                           where RF3.BDCODTER = RF2.BDCODTER and ';
        WSQL = WSQL || '                                                                 RF3.BDREFEMP <= Substring('''|| :PRDATAFINAL ||''' from 1 for 4) ||  Substring('''|| :PRDATAFINAL ||''' from 6 for 2) ';
        WSQL = WSQL || '                                                           order by RF3.BDREFEMP desc), (select first 1 BDREFEMP ';
        WSQL = WSQL || '                                                                                         from TTERCEIRO_REF RF3 ';
        WSQL = WSQL || '                                                                                         where RF3.BDCODTER = RF2.BDCODTER ';
        WSQL = WSQL || '                                                                                         order by RF3.BDCODTER, RF3.BDREFEMP))) as TER on TER.BDCODTER = ';
        IF (prcodter > 0) THEN
         wsql = wSql || ' (' || :prcodter || ')';
        ELSE
         WSQL = WSQL || ' Mov.BDCODTER ';
      end
      wsql = wSql || '                      where (MOV.'||:prCODEMP||') and ';
      wsql = wSql || '                            (MOV.BDCODSITNF not in (2, 3, 4, 5)) and ';
      IF (prcodter > 0) THEN
         wsql = wSql || '                          Mov.BDCODTER = (' || :prcodter || ') and ';
      wsql = wSql || '                            ('||PRCAMPODATA||' between '''||prdatainicial||''' and '''||prdatafinal||''') ';
      IF (prtipolanserv = 0) THEN /* Servico emitido */
         wsql = wSql || '                         and (Mov.BDTIPLAN = 0) ';
      ELSE
         wsql = wSql || '                         and (Mov.BDTIPLAN = 1) ';
      --Larissa - 20/09/2021 - Relatório de retenções para multi-seleção Empresa #93468 #99743 #147812 #152234 #154166 
      wsql = wsql || '                            and (MOV.BDCONDPGTO <> ';
      if ((UPPER(PRVERORGAOPUBLICO) = 'TRUE') and (prtipolanserv = 0)) then
        wsql = wsql || 'IIF(iif(ter.bdorgaopublico = true, 1, PARGER.' || :PRTIPOAPURACAORETIR || ') = 0, -1, 1)) ';
      else
        wsql = wsql || 'IIF(PARGER.' || :PRTIPOAPURACAORETIR || ' = 0, -1, 1)) ';
      wsql = wSql || '                      ) MOV ';
      wsql = wSql || '                left outer join VEF_EMP_TMOVSERITENS ITEM on (ITEM.BDCODEMP = MOV.BDCODEMP and ITEM.BDCHAVE = MOV.BDCHAVE) ';
      wsql = wSql || '                group by MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, MOV.BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, MOV.BDNUMDOCINI, MOV.BDCONDPGTO, MOV.bdreflan) MOV ';
      wsql = wSql || '          left outer join VEF_EMP_TMOVSERRET RET on (RET.BDCODEMP = MOV.BDCODEMP and RET.BDCHAVE = MOV.BDCHAVE) ';
      wsql = wSql || '          left outer join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = MOV.BDCODEMP and DED.BDCHAVE = MOV.BDCHAVE)) MOV ';
      wsql = wSql || '      where (Mov.BDVLRCONTAB > 0) and (Mov.BDVLRIRSER > 0) ';
      wsql = wsql || '      Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO';
      --Larissa - 20/09/2021 - Relatório de retenções para multi-seleção Empresa #93468 #99743 #147812 #152234 #154166 
          wsql = wsql || '  union all ';
          wsql = wsql || '  Select Ret.BDCODEMP,Mov.BDCHAVE,cast(substring(Pgto.BDDATAPGTOPAR from 1 for 4) || substring(Pgto.BDDATAPGTOPAR from 6 for 2) as integer) as BDREFLAN,';
          wsql = wsql || '  Mov.BDCODTER,Mov.BDCONDPGTO,Mov.BDVALORNOTA BDVLRCONTAB, 0 AS BDVLRPIS, 0 AS BDVLRCOFINS,';
          wsql = wsql || '  0 AS BDVLRCSOCIAL,0 as BDVLRIR,0 AS BDVLRINSS,';
          wsql = wsql || '  0 AS BDVLRISS,SUM(Pgto.BDVALORRETIRRF) as BDVLRIRSER ';
          wsql = wsql || '  from VEF_EMP_TMOVSERRET Ret ';
          wsql = wsql || '  join VEF_EMP_TMOVSER Mov on (ret.bdcodemp = mov.bdcodemp and ret.bdchave = mov.bdchave) ';
          wsql = wsql || '  join VEF_EMP_TMOVSERPARPGTO Pgto on (ret.bdcodemp = pgto.bdcodemp and ret.bdchave = pgto.bdchave) ';
          if (prsomamatrizfilial = 1) then
            begin
                wsql = wsql || ' join tempresas emp on (emp.bdcodemp = mov.bdcodemp) ';
                wsql = wsql || ' join VW_VEF_BASE_TEMPPARGER PARGER on (coalesce(emp.bdcodmatriz, emp.bdcodemp) = PARGER.BDCODEMP) ';
            end
          else
            wsql = wsql || '  join VW_VEF_BASE_TEMPPARGER PARGER on (MOV.BDCODEMP = PARGER.BDCODEMP) ';
      if ((UPPER(PRVERORGAOPUBLICO) = 'TRUE') and (prtipolanserv = 0)) then
      begin
        WSQL = WSQL || '            left outer join(select BDCODTER, RF2.BDORGAOPUBLICO, RF2.BDCGCTER, RF2.BDNOMETER, RF2.BDREFEMP ';
        WSQL = WSQL || '                            from TTERCEIRO_REF RF2 ';
        WSQL = WSQL || '                            where RF2.BDREFEMP = coalesce((select first 1 BDREFEMP ';
        WSQL = WSQL || '                                                           from TTERCEIRO_REF RF3 ';
        WSQL = WSQL || '                                                           where RF3.BDCODTER = RF2.BDCODTER and ';
        WSQL = WSQL || '                                                                 RF3.BDREFEMP <= Substring('''|| :PRDATAFINAL ||''' from 1 for 4) ||  Substring('''|| :PRDATAFINAL ||''' from 6 for 2) ';
        WSQL = WSQL || '                                                           order by RF3.BDREFEMP desc), (select first 1 BDREFEMP ';
        WSQL = WSQL || '                                                                                         from TTERCEIRO_REF RF3 ';
        WSQL = WSQL || '                                                                                         where RF3.BDCODTER = RF2.BDCODTER ';
        WSQL = WSQL || '                                                                                         order by RF3.BDCODTER, RF3.BDREFEMP))) as TER on TER.BDCODTER = ';
        IF (prcodter > 0) THEN
         wsql = wSql || ' (' || :prcodter || ')';
        ELSE
         WSQL = WSQL || ' Mov.BDCODTER ';
      end
          wsql = wsql || '  where ';
          wsql = wsql || '  (Ret.BDCODEMP = Mov.BDCODEMP) and ';
          wsql = wsql || '  (Ret.BDCHAVE = Mov.BDCHAVE) and ';
          wsql = wsql || '  (Ret.BDCODEMP = Pgto.BDCODEMP and Ret.BDCHAVE = Pgto.BDCHAVE) and ';
          wsql = wsql || '  (RET.'||:prCODEMP||') and (Mov.bdcodsitnf not in (2,3,4,5)) and ';
          IF (prcodter > 0) THEN
            wsql = wSql || '(Mov.BDCODTER =  (' || :prcodter || ')) and ';
          wsql = wsql || '  (Pgto.BDDATAPGTOPAR between  '''||prdatainicial||''' and '''||prdatafinal||''') and ';
          wsql = wsql || '  (pgto.BDCODTIPOBAIXA <> 2) and '; --sol:16518 - Não levar no faturamento caso o tipo seja "Desconto"
          wsql = wsql || '  (BDVALORPGTOPAR > 0) and (BDVALORRETIRRF > 0) ';
          IF (prtipolanserv = 0) THEN /* Servico emitido */
            wsql = wSql || 'and (Mov.BDTIPLAN = 0) ';
          ELSE
            wsql = wSql || 'and (Mov.BDTIPLAN = 1) ';

          if ((UPPER(PRVERORGAOPUBLICO) = 'TRUE') and (prtipolanserv = 0)) then
            wsql = wsql || 'and iif(ter.bdorgaopublico = true, 1, PARGER.' || :PRTIPOAPURACAORETIR || ') = 1 ';
          else
          wsql = wsql || '  and PARGER.' || :PRTIPOAPURACAORETIR || ' = 1 ';

          wsql = wsql || '  Group By BDCODEMP,BDCHAVE,BDREFLAN,BDCODTER,BDCONDPGTO,BDVLRCONTAB';
        --END
      --sol:17084 - ISS e INSS
      wsql = wsql || '      union all ';
      wsql = wSql || '      Select Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) BDVLRCONTAB,0 AS BDVLRPIS,';
      wsql = wSql || '      0 AS BDVLRCOFINS,0 AS BDVLRCSOCIAL, 0 AS BDVLRIR,SUM(Mov.BDVLRINSS) BDVLRINSS,SUM(Mov.BDVLRISSSER) BDVLRISSSER,';
      wsql = wsql || '      0 AS BDVLRIRSER ';
      wsql = wSql || '     from (select MOV.*, coalesce(RET.BDISSRET, 0) BDVLRISSSER, coalesce(DED.BDRETINSS, 0) BDVLRINSS, COALESCE(RET.bdvlrpis,0.0) BDVLRPIS, ';
      wsql = wSql || '                 COALESCE(RET.bdvlrcofins,0.0) BDVLRCOFINS, COALESCE(RET.bdvlrcsocial,0.0) BDVLRCSOCIAL ';
      wsql = wSql || '          from (select MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, MOV.BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, ';
      wsql = wSql || '                       MOV.BDNUMDOCINI, MOV.BDCONDPGTO, Mov.BDREFLAN, sum(ITEM.BDVLRCONTAB) BDVLRCONTAB, sum(COALESCE(ITEM.bdvlrirser,0)) bdvlrirser ';
      wsql = wSql || '                from (select MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, '||PRCAMPODATA||' BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, ';
      wsql = wSql || '                             MOV.BDNUMDOCINI, MOV.BDCONDPGTO,Mov.BDREFLAN ';
      wsql = wSql || '                      from VEF_EMP_TMOVSER MOV ';
      wsql = wSql || '                      where (mov.'||:prCODEMP||') and ';
      wsql = wSql || '                            (MOV.BDCODSITNF not in (2, 3, 4, 5)) and ';
      IF (prcodter > 0) THEN
         wsql = wSql || '                          Mov.BDCODTER = (' || :prcodter || ') and ';
      wsql = wSql || '                            ('||PRCAMPODATA||' between '''||prdatainicial||''' and '''||prdatafinal||''') ';
      IF (prtipolanserv = 0) THEN /* Servico emitido */
         wsql = wSql || '                         and (Mov.BDTIPLAN = 0) ';
      ELSE
         wsql = wSql || '                         and (Mov.BDTIPLAN = 1) ';
      wsql = wSql || '                      ) MOV ';
      wsql = wSql || '                left outer join VEF_EMP_TMOVSERITENS ITEM on (ITEM.BDCODEMP = MOV.BDCODEMP and ITEM.BDCHAVE = MOV.BDCHAVE) ';
      wsql = wSql || '                group by MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCHAVE, MOV.BDDATAEMISSAO, MOV.BDESPECIE, MOV.BDSERIE, MOV.BDNUMDOCINI, MOV.BDCONDPGTO, MOV.bdreflan) MOV ';
      wsql = wSql || '          left outer join VEF_EMP_TMOVSERRET RET on (RET.BDCODEMP = MOV.BDCODEMP and RET.BDCHAVE = MOV.BDCHAVE) ';
      wsql = wSql || '          left outer join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = MOV.BDCODEMP and DED.BDCHAVE = MOV.BDCHAVE)) MOV ';
      wsql = wSql || '      where (Mov.BDVLRCONTAB > 0) and ((Mov.BDVLRISSSER > 0) or (Mov.BDVLRINSS > 0)) ';
      wsql = wsql || '      Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Mov.BDCONDPGTO';
      wsql = wsql || ') Mov ';
      wsql = wSql || 'LEFT OUTER JOIN VW_TTERCEIRO Ter ON (Ter.BDCODTER = Mov.BDCODTER) ';
      wsql = wSql || 'LEFT OUTER JOIN TCIDADE Cid ON (Cid.BDCODCID = Ter.BDCODCID) ';
      --IF (prtipoapuracaoret = 1) THEN -- Tipo de apuração das retenções = Regime de caixa
      --  wsql = wsql || 'LEFT OUTER JOIN VEF_EMP_TMOVSERPARPGTO Pgto on (Mov.BDCODEMP = Pgto.BDCODEMP and Mov.BDCHAVE = Pgto.BDCHAVE and Pgto.BDDATAPGTOPAR between '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql || 'Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Ter.BDNOMETER,Ter.BDCGCTER,Ter.BDENDTER,Ter.BDCODCID,Cid.BDNOMCID,Mov.BDCONDPGTO,Mov.BDVLRCONTAB ';
      wsql = wSql || 'Order by Mov.BDCODEMP,Mov.BDCODTER,Mov.BDREFLAN';
    END
  ELSE
  IF (prtipomov = 3) THEN -- demais documentos
    BEGIN
      wsql = wSql || 'Select  Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Ter.BDNOMETER,Ter.BDCGCTER,Ter.BDENDTER,Ter.BDCODCID,Cid.BDNOMCID,Mov.BDCONDPGTO,SUM(Mov.BDVLRCONTAB) as BDVLRCONTAB,SUM(Mov.BDVLRPIS) as BDVLRPIS,';
      wsql = wSql || 'SUM(Mov.BDVLRCOFINS) as BDVLRCOFINS,SUM(Mov.BDVLRCSOCIAL) as BDVLRCSOCIAL,SUM(Mov.BDVLRIR) as BDVLRIR,SUM(Mov.BDVLRINSS) as BDVLRINSS,SUM(Mov.BDVLRISSSER) as BDVLRISSSER,SUM(Mov.BDVLRIRSER) as BDVLRIRSER ';
      wsql = wSql || 'from ( Select Mov.BDCODEMP, Mov.BDCHAVE, Mov.BDREFLAN, Mov.BDCODTER, Mov.BDCONDPGTO, ';
      wsql = wsql || '              iif((PARGER.BDTIPOAPURACAORET = 1) and (MOV.BDCONDPGTO = 1), iif((select first 1 count(bdchave) from VEF_EMP_TMOVF100PARPGTO where BDCHAVE = MOV.BDCHAVE) > 0, 0, sum(MOV.BDVL_OPER)), sum(MOV.BDVL_OPER)) as BDVLRCONTAB, ';
      wsql = wsql || '              IIF(PARGER.BDTIPOAPURACAORET = 0, sum(RET.BDVLRPIS), IIF(MOV.BDCONDPGTO <> 1, sum(RET.BDVLRPIS), 0)) as BDVLRPIS, ';
      wsql = wsql || '              IIF(PARGER.BDTIPOAPURACAORET = 0, sum(RET.BDVLRCOFINS), IIF(MOV.BDCONDPGTO <> 1, sum(RET.BDVLRCOFINS), 0))  as BDVLRCOFINS, ';
      wsql = wsql || '              IIF(PARGER.BDTIPOAPURACAORET = 0, sum(RET.BDVLRCSOCIAL), IIF(MOV.BDCONDPGTO <> 1, sum(RET.BDVLRCSOCIAL), 0)) as BDVLRCSOCIAL, ';
      --wsql = wsql || '              IIF(' || prtipoapuracaoretir || ' = 1, SUM(Ret.BDVLRIR), 0) as BDVLRIR, ';
      if ((UPPER(PRVERORGAOPUBLICO) = 'TRUE')  and (prTipoLanServ = 1)) then
        wsql = wsql || '              IIF(iif(ter.bdorgaopublico = true, 1, PARGER.' || :PRTIPOAPURACAORETIR || ') ';
      else
       wsql = wsql || '              IIF(PARGER.' || :PRTIPOAPURACAORETIR;
      wsql = wsql || '  = 0, SUM(Ret.BDVLRIR), IIF(MOV.BDCONDPGTO <> 1, SUM(Ret.BDVLRIR), 0)) as BDVLRIR, ';
      wsql = wsql || '              0 BDVLRINSS, sum(RET.BDISSRET) as BDVLRISSSER, 0 BDVLRIRSER ';
      wsql = wSql || '       from VEF_EMP_TMOVDEMAISDOC_F100 Mov ';
      wsql = wsql || '       Left outer join VEF_EMP_TMOVDEMRET Ret on (Ret.BDCODEMP = Mov.BDCODEMP and Ret.BDCHAVE = Mov.BDCHAVE) ';
      wsql = wsql || '       Left outer join VEF_BASE_TAB_TIPO_OPERACAO tipo on (tipo.BDIND_OPER = Mov.BDIND_OPER) ';
      --Larissa - 20/09/2021 - Relatório de retenções para multi-seleção Empresa #93468 #99743 #147812 #152234 #154166
      if (prsomamatrizfilial = 1) then
        begin
            wsql = wsql || ' left outer join tempresas emp on (emp.bdcodemp = mov.bdcodemp) ';
            wsql = wsql || ' left outer join VW_VEF_BASE_TEMPPARGER PARGER on (coalesce(emp.bdcodmatriz, emp.bdcodemp) = PARGER.BDCODEMP) ';
        end
      else
        wsql = wsql || '     left outer join VW_VEF_BASE_TEMPPARGER PARGER on (MOV.BDCODEMP = PARGER.BDCODEMP) ';
      if ((UPPER(PRVERORGAOPUBLICO) = 'TRUE') and (prTipoLanServ = 1)) then
      begin
        WSQL = WSQL || '            left outer join(select BDCODTER, RF2.BDORGAOPUBLICO, RF2.BDCGCTER, RF2.BDNOMETER, RF2.BDREFEMP ';
        WSQL = WSQL || '                            from TTERCEIRO_REF RF2 ';
        WSQL = WSQL || '                            where RF2.BDREFEMP = coalesce((select first 1 BDREFEMP ';
        WSQL = WSQL || '                                                           from TTERCEIRO_REF RF3 ';
        WSQL = WSQL || '                                                           where RF3.BDCODTER = RF2.BDCODTER and ';
        WSQL = WSQL || '                                                                 RF3.BDREFEMP <= Substring('''|| :PRDATAFINAL ||''' from 1 for 4) ||  Substring('''|| :PRDATAFINAL ||''' from 6 for 2) ';
        WSQL = WSQL || '                                                           order by RF3.BDREFEMP desc), (select first 1 BDREFEMP ';
        WSQL = WSQL || '                                                                                         from TTERCEIRO_REF RF3 ';
        WSQL = WSQL || '                                                                                         where RF3.BDCODTER = RF2.BDCODTER ';
        WSQL = WSQL || '                                                                                         order by RF3.BDCODTER, RF3.BDREFEMP))) as TER on TER.BDCODTER = ';
        IF (prcodter > 0) THEN
         wsql = wSql || ' (' || :prcodter || ')';
        ELSE
         WSQL = WSQL || ' Mov.BDCODTER ';
      end
      wsql = wSql || '       where (MOV.'||:prCODEMP||') ';
      IF (prcodter > 0) THEN
        wsql = wSql|| ' and Mov.BDCODTER =  (' || :prcodter || ') ';
      wsql = wsql ||  '     and (Mov.BDDT_OPER BETWEEN '''||prdatainicial||''' and '''||prdatafinal||''') ';
      wsql = wSql ||  '     and ((Mov.BDVL_OPER > 0) and ((Ret.BDVLRPIS > 0) or (Ret.BDVLRCOFINS > 0) or (Ret.BDVLRCSOCIAL > 0) or (RET.BDISSRET > 0) or (RET.BDVLRIR > 0))) ';
      IF (prTipoLanServ = 1) THEN -- Receita
        wsql = wsql || ' and tipo.BDINDICADOR > 0 ';
      ELSE -- Aquisição
        wsql = wsql || ' and tipo.BDINDICADOR = 0 ';
      --Larissa - 20/09/2021 - Relatório de retenções para multi-seleção Empresa #93468 #99743 #147812 #152234 #154166 
      wsql = wsql || '      Group by Mov.BDCODEMP, Mov.BDCHAVE, Mov.BDREFLAN, Mov.BDCODTER, Mov.BDCONDPGTO, Ret.BDVLRIR, BDTIPOAPURACAORET, '  || :PRTIPOAPURACAORETIR;
      if ((UPPER(PRVERORGAOPUBLICO) = 'TRUE') and (prTipoLanServ = 1)) then
            wsql = wsql || ' , ter.bdorgaopublico ';
      --Larissa - 20/09/2021 - Relatório de retenções para multi-seleção Empresa #93468 #99743 #147812 #152234 #154166 
          wsql = wsql || ' union all ';
          wsql = wsql || ' Select Pgto.BDCODEMP,Pgto.BDCHAVE,cast(substring(Pgto.BDDATAPGTOPAR from 1 for 4) || substring(Pgto.BDDATAPGTOPAR from 6 for 2) as integer) as BDREFLAN,Mov.BDCODTER, MOV.BDCONDPGTO, ';
          wsql = wsql || '  Mov.BDVL_OPER as BDVLRCONTAB, ';
              wsql = wsql || '   IIF(PARGER.BDTIPOAPURACAORET = 1, SUM(Pgto.BDVALORRETPIS), 0) as BDVLRPIS, ';
              wsql = wsql || '   IIF(PARGER.BDTIPOAPURACAORET = 1, SUM(Pgto.BDVALORRETCOFINS), 0) as BDVLRCOFINS, ';
              wsql = wsql || '   IIF(PARGER.BDTIPOAPURACAORET = 1, SUM(Pgto.BDVALORRETCSLL), 0) as BDVLRCSOCIAL, ';
              if ((UPPER(PRVERORGAOPUBLICO) = 'TRUE') and (prTipoLanServ = 1)) then
                wsql = wsql || '              IIF(iif(ter.bdorgaopublico = true, 1, PARGER.' || :PRTIPOAPURACAORETIR || ') ';
              else
               wsql = wsql || '              IIF(PARGER.' || :PRTIPOAPURACAORETIR;

              wsql = wsql || '    = 1, SUM(Pgto.BDVALORRETIRRF), 0) as BDVLRIR, ';
              wsql = wsql || '   0 BDVLRINSS, ';
              wsql = wsql || '   0 BDVLRISSSER, ';
            if ((UPPER(PRVERORGAOPUBLICO) = 'TRUE') and (prTipoLanServ = 1)) then
              wsql = wsql || '              IIF(iif(ter.bdorgaopublico = true, 1, PARGER.' || :PRTIPOAPURACAORETIR || ') ';
            else
             wsql = wsql || '              IIF(PARGER.' || :PRTIPOAPURACAORETIR;
            wsql = wsql || '   = 1, SUM(Pgto.BDVALORRETIRRF), 0) as BDVLRIRSER ';
          wsql = wsql || ' from VEF_EMP_TMOVF100PARPGTO Pgto ';
          wsql = wsql || ' left outer join VEF_EMP_TMOVDEMAISDOC_F100 Mov on (Mov.BDCODEMP = Pgto.BDCODEMP and Mov.BDCHAVE = Pgto.BDCHAVE) ';
          wsql = wsql || ' left outer join VEF_BASE_TAB_TIPO_OPERACAO tipo on (tipo.BDIND_OPER = Mov.BDIND_OPER) ';
          if (prsomamatrizfilial = 1) then
            begin
                wsql = wsql || ' left outer join TEMPRESAS emp on (emp.bdcodemp = pgto.bdcodemp) ';
                wsql = wsql || ' left outer join VW_VEF_BASE_TEMPPARGER PARGER on (coalesce(emp.bdcodmatriz, emp.bdcodemp) = PARGER.BDCODEMP) ';
            end
          else
            wsql = wsql || ' left outer join VW_VEF_BASE_TEMPPARGER PARGER on (PGTO.BDCODEMP = PARGER.BDCODEMP) ';
          if ((UPPER(PRVERORGAOPUBLICO) = 'TRUE') and (prTipoLanServ = 1)) then
          begin
            WSQL = WSQL || '            left outer join(select BDCODTER, RF2.BDORGAOPUBLICO, RF2.BDCGCTER, RF2.BDNOMETER, RF2.BDREFEMP ';
            WSQL = WSQL || '                            from TTERCEIRO_REF RF2 ';
            WSQL = WSQL || '                            where RF2.BDREFEMP = coalesce((select first 1 BDREFEMP ';
            WSQL = WSQL || '                                                           from TTERCEIRO_REF RF3 ';
            WSQL = WSQL || '                                                           where RF3.BDCODTER = RF2.BDCODTER and ';
            WSQL = WSQL || '                                                                 RF3.BDREFEMP <= Substring('''|| :PRDATAFINAL ||''' from 1 for 4) ||  Substring('''|| :PRDATAFINAL ||''' from 6 for 2) ';
            WSQL = WSQL || '                                                           order by RF3.BDREFEMP desc), (select first 1 BDREFEMP ';
            WSQL = WSQL || '                                                                                         from TTERCEIRO_REF RF3 ';
            WSQL = WSQL || '                                                                                         where RF3.BDCODTER = RF2.BDCODTER ';
            WSQL = WSQL || '                                                                                         order by RF3.BDCODTER, RF3.BDREFEMP))) as TER on TER.BDCODTER = ';
            IF (prcodter > 0) THEN
             wsql = wSql || ' (' || :prcodter || ')';
            ELSE
             WSQL = WSQL || ' Mov.BDCODTER ';
          end
          wsql = wsql || ' Where (Pgto.BDDATAPGTOPAR Between '''||prdatainicial||''' and '''||prdatafinal||''') and ';
          wsql = wsql || '       (PGTO.'||:prCODEMP||') and ';
          wsql = wsql || '       (pgto.BDCODTIPOBAIXA <> 2) and '; --sol:16518 - Não levar no faturamento caso o tipo seja "Desconto"
          if ((UPPER(PRVERORGAOPUBLICO) = 'TRUE') and (prTipoLanServ = 1)) then
            wsql = wsql || '              ((iif(ter.bdorgaopublico = true, 1, PARGER.' || :PRTIPOAPURACAORETIR || ') ';
          else
           wsql = wsql || '              ((PARGER.' || :PRTIPOAPURACAORETIR;
          wsql = wsql || '    = 1) or (PARGER.BDTIPOAPURACAORET = 1)) and ';
          wsql = wsql || '       ((Pgto.BDVALORRETPIS > 0) or (Pgto.BDVALORRETCOFINS > 0) or (Pgto.BDVALORRETCSLL > 0) or (Pgto.BDVALORRETIRRF > 0) or (Pgto.BDVALORRETINSS > 0) or (Pgto.BDVALORRETINSS > 0) or (Pgto.BDVALORRETIRRF > 0)) ';
          IF (prTipoLanServ = 1) THEN
            wsql = wsql || '       and tipo.BDINDICADOR > 0 ';
          ELSE
            wsql = wsql || '       and tipo.BDINDICADOR = 0 ';
          wsql = wsql || ' group by BDCODEMP, BDCHAVE, BDREFLAN, BDCODTER, MOV.BDCONDPGTO, Mov.BDVL_OPER, BDTIPOAPURACAORET, ' || :PRTIPOAPURACAORETIR;
          if ((UPPER(PRVERORGAOPUBLICO) = 'TRUE') and (prTipoLanServ = 1)) then
            wsql = wsql || ' , ter.bdorgaopublico ';
        --END
      wsql = wsql || ') Mov ';
      wsql = wSql || 'LEFT OUTER JOIN VW_TTERCEIRO Ter ON (Ter.BDCODTER = Mov.BDCODTER) ';
      wsql = wSql || 'LEFT OUTER JOIN TCIDADE Cid ON (Cid.BDCODCID = Ter.BDCODCID) ';
      wsql = wSql || 'Group by Mov.BDCODEMP,Mov.BDCHAVE,Mov.BDREFLAN,Mov.BDCODTER,Ter.BDNOMETER,Ter.BDCGCTER,Ter.BDENDTER,Ter.BDCODCID,Cid.BDNOMCID,Mov.BDCONDPGTO ';
      wsql = wSql || 'Order by Mov.BDCODEMP,Mov.BDCODTER,Mov.BDREFLAN';
    END
  wsql = wSql || ') Mov ';
  wsql = wSql || 'join TEMPRESAS Emp on (Emp.BDCODEMP = Mov.BDCODEMP)';
  wrefincial = SUBSTRING(CAST(prdatainicial AS VARCHAR(40)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatainicial AS VARCHAR(40)) FROM 6 FOR 2);
  wreffinal = SUBSTRING(CAST(prdatafinal AS VARCHAR(40)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatafinal AS VARCHAR(40)) FROM 6 FOR 2);
  wdata_final = prdatafinal;
  wcodteratual = 0;
  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,   :wchave,    bdref,    bdcodter,    bdnometer,    bdcgcter,    bdendter,    bdcodcid,    bdnomcid,    bdcondpgto,    bdvlrcontab,    bdvlrpis,    bdvlrcofins,
    bdvlrcsocial, bdvlrir, bdvlrinss, bdvlriss, bdvlrirser
  DO
   BEGIN
    wano = SUBSTRING(bdref FROM 1 FOR 4);
    wmes = SUBSTRING(bdref FROM 5 FOR 2);
    IF (prdetalhado = 0) THEN
      BEGIN
         IF (wmes = '01') THEN
            bdmesextenso =  'Janeiro / ' || wano;
         IF (wmes = '02') THEN
            bdmesextenso =  'Fevereiro / ' || wano;
         IF (wmes = '03') THEN
            bdmesextenso =  'Março / ' || wano;
         IF (wmes = '04') THEN
            bdmesextenso =  'Abril / ' || wano;
         IF (wmes = '05') THEN
            bdmesextenso =  'Maio / ' || wano;
         IF (wmes = '06') THEN
            bdmesextenso =  'Junho / ' || wano;
         IF (wmes = '07') THEN
            bdmesextenso =  'Julho / ' || wano;
         IF (wmes = '08') THEN
            bdmesextenso =  'Agosto / ' || wano;
         IF (wmes = '09') THEN
            bdmesextenso =  'Setembro / ' || wano;
         IF (wmes = '10') THEN
            bdmesextenso =  'Outubro / ' || wano;
         IF (wmes = '11') THEN
            bdmesextenso =  'Novembro / ' || wano;
         IF (wmes = '12') THEN
            bdmesextenso =  'Dezembro / ' || wano;
         SUSPEND;
         IF (wcodteratual <> bdcodter) THEN
           BEGIN
             wrefincial = SUBSTRING(CAST(prdatainicial AS VARCHAR(40)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatainicial AS VARCHAR(40)) FROM 6 FOR 2);
           END
         /* verifica se precisa adicionar referencias anteriores da atual ex so tem o mes 3 precisa gerar janeiro e fevereiro vazios... */
         WHILE (wrefincial <= wreffinal) DO
          BEGIN
            wcodteratual = bdcodter;
            bdref = wrefincial;
            wano = SUBSTRING(bdref FROM 1 FOR 4);
            wmes = SUBSTRING(bdref FROM 5 FOR 2);
            bdvlrcontab = 0; bdvlrpis    = 0; bdvlrcofins = 0; bdvlrcsocial = 0; bdvlrir = 0; bdvlrinss = 0; bdvlriss = 0; bdvlrirser = 0;
            IF (wmes = '01') THEN
               bdmesextenso =  'Janeiro / ' || wano;
            IF (wmes = '02') THEN
               bdmesextenso =  'Fevereiro / ' || wano;
            IF (wmes = '03') THEN
               bdmesextenso =  'Março / ' || wano;
            IF (wmes = '04') THEN
               bdmesextenso =  'Abril / ' || wano;
            IF (wmes = '05') THEN
               bdmesextenso =  'Maio / ' || wano;
            IF (wmes = '06') THEN
               bdmesextenso =  'Junho / ' || wano;
            IF (wmes = '07') THEN
               bdmesextenso =  'Julho / ' || wano;
            IF (wmes = '08') THEN
               bdmesextenso =  'Agosto / ' || wano;
            IF (wmes = '09') THEN
               bdmesextenso =  'Setembro / ' || wano;
            IF (wmes = '10') THEN
               bdmesextenso =  'Outubro / ' || wano;
            IF (wmes = '11') THEN
               bdmesextenso =  'Novembro / ' || wano;
            IF (wmes = '12') THEN
               bdmesextenso =  'Dezembro / ' || wano;
            SUSPEND;
            wdataaux = CAST(SUBSTRING(CAST(wrefincial AS VARCHAR(6)) FROM 5 FOR 2)||'-'||'01'||'-'||SUBSTRING(CAST(wrefincial AS VARCHAR(6)) FROM 1 FOR 4) AS DATE);
            wdataaux = addmonth(wdataaux, 1);
            wrefincial = SUBSTRING(CAST(wdataaux AS VARCHAR(40)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataaux AS VARCHAR(40)) FROM 6 FOR 2);
          END
      END
    ELSE
      BEGIN
        IF (wmes = '01') THEN
           bdmesextenso =  'Janeiro / ' || wano;
        IF (wmes = '02') THEN
           bdmesextenso =  'Fevereiro / ' || wano;
        IF (wmes = '03') THEN
           bdmesextenso =  'Março / ' || wano;
        IF (wmes = '04') THEN
           bdmesextenso =  'Abril / ' || wano;
        IF (wmes = '05') THEN
           bdmesextenso =  'Maio / ' || wano;
        IF (wmes = '06') THEN
           bdmesextenso =  'Junho / ' || wano;
        IF (wmes = '07') THEN
           bdmesextenso =  'Julho / ' || wano;
        IF (wmes = '08') THEN
           bdmesextenso =  'Agosto / ' || wano;
        IF (wmes = '09') THEN
           bdmesextenso =  'Setembro / ' || wano;
        IF (wmes = '10') THEN
           bdmesextenso =  'Outubro / ' || wano;
        IF (wmes = '11') THEN
           bdmesextenso =  'Novembro / ' || wano;
        IF (wmes = '12') THEN
           bdmesextenso =  'Dezembro / ' || wano;
        SUSPEND;
      END
   END
END
^

/* Restore proc. body: SP_VEF_RETORNA_SALDO_DIME */
create or alter procedure SP_VEF_RETORNA_SALDO_DIME (
    PRCODEMP varchar(10000),
    PRDATAINI date,
    PRDATAFIM date,
    PRREFEMP integer,
    PRANO integer,
    PRCONTABILIZACAO integer)
returns (
    BDCODMATRIZ integer,
    BDCODEMP integer,
    BDQUADRO varchar(5),
    BDCODEXP integer,
    BDSALDO numeric(15,2),
    BDDETFILIAL varchar(5),
    BDDETRESULTFILIAL varchar(5),
    BDMATRIZNAOCADSIS varchar(5),
    BDCODUF_MATRIZ integer)
as
declare variable WSQL varchar(5000);
declare variable WSQL2 varchar(5000);
declare variable WCODTPLA integer;
declare variable WCODITEM_81_91 integer;
declare variable WCODITEM_82_92 integer;
declare variable WCODITEM_83_93 integer;
declare variable WCODITEM_84_94 integer;
declare variable WCODITEM_85 integer;
declare variable WPLANOCONTAS integer;
declare variable WREFATUAL integer;
declare variable WPRIMEIRAFILIAL integer;
declare variable WCODEMP integer;
declare variable BDCODUF_EMP integer;
declare variable WCODEMPAUX integer;
BEGIN
  SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) FROM RDB$DATABASE INTO :wRefAtual;
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prRefEmp);
                                                             
  wsql2 = '';
  wsql2 = wsql2||'select First 1 ref_matriz.BDCODEMP BDCODMATRIZ, cid_matriz.BDCODUF ';
  wsql2 = wsql2||'from tempresas emp ';
  wsql2 = wsql2||'left outer join VW_TEMPRESAS_REF ref on (ref.bdcodemp = emp.bdcodemp) ';
  wsql2 = wsql2||'left outer join VW_TEMPRESAS_REF ref_matriz on (ref_matriz.bdcodemp = emp.bdcodmatriz) ';
  wsql2 = wsql2||'left outer join TCIDADE cid_matriz on (cid_matriz.bdcodcid = ref_matriz.bdcodcid) ';
  IF (:prcodemp <> '') THEN
      wsql2 = wsql2||'where '||:PRCODEMP; -- 11418 - Maicon S. Filtrar todas
   execute STATEMENT wsql2 into :bdcodmatriz, :BDCODUF_MATRIZ;

  if (Coalesce(BDCODUF_MATRIZ, 24) <> 24) then
    BEGIN       
      wsql2 = '';
      wsql2 = wsql2||'select emp.bdcodemp, ref_matriz.BDCODEMP BDCODMATRIZ, ref.bdcodplapadrao, parser.bddetfilial, parser.bdDETRESULTFILIAL, emp.BDMATRIZNAOCADSIS, cid_matriz.BDCODUF BDCODUF_MATRIZ, CID_EMP.BDCODUF BDCODUF_EMP ';
      wsql2 = wsql2||'from tempresas emp ';
      wsql2 = wsql2||'left outer join VW_TEMPRESAS_REF ref on (ref.bdcodemp = emp.bdcodemp) ';
      wsql2 = wsql2||'left outer join VW_VEF_BASE_TEMPPARESTSC parser on (parser.bdcodemp = emp.bdcodemp) ';
      wsql2 = wsql2||'left outer join VW_TEMPRESAS_REF ref_matriz on (ref_matriz.bdcodemp = '||:bdcodmatriz||') ';
      wsql2 = wsql2||'left outer join TCIDADE cid_matriz on (cid_matriz.bdcodcid = ref_matriz.bdcodcid) ';
      wsql2 = wsql2||'LEFT OUTER JOIN TCIDADE CID_EMP ON (CID_EMP.BDCODCID = REF.BDCODCID) ';
      IF (:prcodemp <> '') THEN
          wsql2 = wsql2||'where emp.bdcodemp = '||:bdcodmatriz||' or emp.bdcodmatriz = '||:bdcodmatriz; -- 11418 - Maicon S. Filtrar todas
    END
  ELSE
    BEGIN
      bdcodmatriz = 0;
      BDCODUF_MATRIZ = 0;
      wsql2 = '';
      wsql2 = wsql2||'select emp.bdcodemp, emp.bdcodmatriz, ref.bdcodplapadrao, parser.bddetfilial, parser.bdDETRESULTFILIAL, emp.BDMATRIZNAOCADSIS, 24 BDCODUF_MATRIZ, CID_EMP.BDCODUF BDCODUF_EMP ';
      wsql2 = wsql2||'from tempresas emp ';
      wsql2 = wsql2||'left outer join VW_TEMPRESAS_REF ref on (ref.bdcodemp = emp.bdcodemp) ';
      wsql2 = wsql2||'left outer join VW_VEF_BASE_TEMPPARESTSC parser on (parser.bdcodemp = emp.bdcodemp) ';
      wsql2 = wsql2||'LEFT OUTER JOIN TCIDADE CID_EMP ON (CID_EMP.BDCODCID = REF.BDCODCID) ';
      IF (:prcodemp <> '') THEN
          wsql2 = wsql2||'where '||:PRCODEMP; -- 11418 - Maicon S. Filtrar todas
   END

  FOR EXECUTE STATEMENT wSQL2 INTO :bdcodemp, :bdcodmatriz, :WPLANOCONTAS, :bddetfilial, :bdDETRESULTFILIAL, :BDMATRIZNAOCADSIS, :BDCODUF_MATRIZ, :BDCODUF_EMP DO
    BEGIN
      WCODEMP = :bdcodemp;
      if ((BDCODUF_MATRIZ <> 24) AND (COALESCE(:bdDETRESULTFILIAL,'FALSE') <> 'TRUE')) then -- Matriz não é de SC
        BEGIN        
          /*wsql2 = '';
          wsql2 = wsql2||'select MIN(emp.bdcodemp) ';
          wsql2 = wsql2||'from tempresas emp ';
          wsql2 = wsql2||'left outer join VW_TEMPRESAS_REF ref on (ref.bdcodemp = emp.bdcodemp) ';
          wsql2 = wsql2||'left outer join TCIDADE cid on (cid.bdcodcid = ref.bdcodcid) ';
          wsql2 = wsql2||'where EMP.BDCODMATRIZ = '||:bdcodmatriz||' ';
          wsql2 = wsql2||'  AND cid.BDCODUF = 24 '; */

          wsql2 = '';
          wsql2 = wsql2||'SELECT FIRST 1 x.bdCODEMP FROM (';
          wsql2 = wsql2||'SELECT MIN(p.bdCODEMP) BDCODEMP, 0 AS bdORDENACAO ';
          wsql2 = wsql2||'FROM TEMPRESAS EMP ';
          wsql2 = wsql2||'LEFT OUTER JOIN VW_TEMPRESAS_REF ref ON (ref.bdCODEMP = emp.bdCODEMP) ';
          wsql2 = wsql2||'LEFT OUTER JOIN TCIDADE cid ON (cid.bdCODCID = ref.bdCODCID) ';
          wsql2 = wsql2||'JOIN VW_VEF_BASE_TEMPPARESTSC p ON(p.bdCODEMP = emp.bdCODEMP) ';
          wsql2 = wsql2||'WHERE p.bdEMPPRINCDIMESC = ''TRUE'' '; -- Alt.: 206370 - Criado parametro para permitr selecionar uma filial como principal e nao apenas pegar a de menor codigo...
          wsql2 = wsql2||'  AND emp.bdCODMATRIZ = '||:bdCODMATRIZ||' ';
          wsql2 = wsql2||'  AND cid.bdCODUF = 24 ';
          wsql2 = wsql2||'GROUP BY emp.bdCODMATRIZ ';
          wsql2 = wsql2||'UNION ALL ';
          wsql2 = wsql2||'select MIN(emp.bdcodemp), 1 AS bdORDENACAO ';
          wsql2 = wsql2||'from tempresas emp ';
          wsql2 = wsql2||'left outer join VW_TEMPRESAS_REF ref on (ref.bdcodemp = emp.bdcodemp) ';
          wsql2 = wsql2||'left outer join TCIDADE cid on (cid.bdcodcid = ref.bdcodcid) ';
          wsql2 = wsql2||'where EMP.BDCODMATRIZ = '||:bdcodmatriz||' ';
          wsql2 = wsql2||'  AND cid.BDCODUF = 24 ';
          wsql2 = wsql2||') x ';
          wsql2 = wsql2||'ORDER BY bdORDENACAO ';

          execute STATEMENT wsql2 into :bdcodmatriz;
          --WCODEMP = :bdcodmatriz;
        END
      ELSE
      IF ((bdcodmatriz = 0) OR (bdcodmatriz IS NULL)) THEN
         bdcodmatriz = bdcodemp;

      --81_91
      wsql = '';
      wsql = wsql||'select tpla.BDCODTPLA, tpla.BDCODITEM_81_91, Q.bdcodexp from PLANOS_TPLA_DIME tpla ';
      wsql = wsql||'left outer join TQUADRO_ITENS_DIME Q on (Q.bdcoditem_dime = tpla.BDCODITEM_81_91) ';
      wsql = wsql||'where tpla.BDCODPLA_DIME = 1 and tpla.BDCODPLAPADRAO = '||:WPLANOCONTAS||' and (tpla.BDCODITEM_81_91 is not null) order by tpla.BDCODITEM_81_91'; --and tpla.BDANO = '||:prano||'
    
      FOR EXECUTE STATEMENT wSQL INTO :wCODTPLA,:wCODITEM_81_91,:bdCODEXP DO
        BEGIN
          bdquadro = '81_91';
    
          --sol:3520 - a rotina da exportação da dime no contabil esta diferente do balancete e da consulta de saldo... por isso foi mudado
          --select SALDO_ATUAL from VSUC_SP_RETORNA_SALDO(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 1, 0, null, :PRREFEMP, '', 1, 0)
          --alt:#10458 - Quadros 81 e 82 devem igonar o zeramento (quinto parametro da sp)
--          select SALDO_ATUAL from SP_RETORNA_SALDO_EMP_X(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 1, 0, null, :PRREFEMP, 0, 1, 0)
          SELECT SALDO_ATUAL FROM SP_RETORNA_SALDO_EMP_X(:WCODEMP, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 0, 0, NULL, NULL, :PRREFEMP, 0, :PRCONTABILIZACAO, 0)
          INTO :bdSALDO;
    
          IF (bdSALDO <> 0) THEN
             SUSPEND;
        END

      --82_92
      wsql = '';
      wsql = wsql||'select tpla.BDCODTPLA, tpla.BDCODITEM_82_92, Q.bdcodexp from PLANOS_TPLA_DIME tpla ';
      wsql = wsql||'left outer join TQUADRO_ITENS_DIME Q on (Q.bdcoditem_dime = tpla.BDCODITEM_82_92) ';
      wsql = wsql||'where tpla.BDCODPLA_DIME = 1 and tpla.BDCODPLAPADRAO = '||:WPLANOCONTAS||' and (tpla.BDCODITEM_82_92 is not null) order by tpla.BDCODITEM_82_92'; --and tpla.BDANO = '||:prano||'
    
      FOR EXECUTE STATEMENT wSQL INTO :wCODTPLA,:wCODITEM_82_92,:bdCODEXP DO
        BEGIN
          bdquadro = '82_92';
    
          --sol:3520 - a rotina da exportação da dime no contabil esta diferente do balancete e da consulta de saldo... por isso foi mudado
          --select SALDO_ATUAL from VSUC_SP_RETORNA_SALDO(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 1, 0, null, :PRREFEMP, '', 1, 0)
          --alt:#10458 - Quadros 81 e 82 devem igonar o zeramento (quinto parametro da sp)
--          select SALDO_ATUAL from SP_RETORNA_SALDO_EMP_X(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 1, 0, null, :PRREFEMP, 0, 1, 0)
          SELECT SALDO_ATUAL FROM SP_RETORNA_SALDO_EMP_X(:WCODEMP, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 0, 0, NULL, NULL, :PRREFEMP, 0, :PRCONTABILIZACAO, 0)
          INTO :bdSALDO;
    
          IF (bdSALDO <> 0) THEN
             SUSPEND;
        END

      --83_93
      wsql = '';
      wsql = wsql||'select tpla.BDCODTPLA, tpla.BDCODITEM_83_93, Q.bdcodexp from PLANOS_TPLA_DIME tpla ';
      wsql = wsql||'left outer join TQUADRO_ITENS_DIME Q on (Q.bdcoditem_dime = tpla.BDCODITEM_83_93) ';
      wsql = wsql||'where tpla.BDCODPLA_DIME = 1 and tpla.BDCODPLAPADRAO = '||:WPLANOCONTAS||' and (tpla.BDCODITEM_83_93 is not null) order by tpla.BDCODITEM_83_93'; --and tpla.BDANO = '||:prano||'
    
      FOR EXECUTE STATEMENT wSQL INTO :wCODTPLA,:wCODITEM_83_93,:bdCODEXP DO
        BEGIN
          bdquadro = '83_93';
    
          IF (bdCODEXP = 353) THEN
             BEGIN
                  --sol:3520 - a rotina da exportação da dime no contabil esta diferente do balancete e da consulta de saldo... por isso foi mudado
                  --select SALDO_DEB from VSUC_SP_RETORNA_SALDO(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 1, 0, null, :PRREFEMP, '', 1, 0)
                  SELECT SALDO_ATUAL FROM SP_RETORNA_SALDO_EMP_X(:WCODEMP, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 0, 1, NULL, NULL, :PRREFEMP, 0, :PRCONTABILIZACAO, 0)
                  INTO :bdSALDO;
             END
          ELSE
             BEGIN
                  --sol:3520 - a rotina da exportação da dime no contabil esta diferente do balancete e da consulta de saldo... por isso foi mudado
                  --select SALDO_ATUAL from VSUC_SP_RETORNA_SALDO(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 1, 0, null, :PRREFEMP, '', 1, 0)
                  SELECT SALDO_ATUAL FROM SP_RETORNA_SALDO_EMP_X(:WCODEMP, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 0, 1, NULL, NULL, :PRREFEMP, 0, :PRCONTABILIZACAO, 0)
                  INTO :bdSALDO;
             END
    
          IF (bdSALDO <> 0) THEN
             SUSPEND;
        END

      --84_94
      wsql = '';
      wsql = wsql||'select tpla.BDCODTPLA, tpla.BDCODITEM_84_94, Q.bdcodexp from PLANOS_TPLA_DIME tpla ';
      wsql = wsql||'left outer join TQUADRO_ITENS_DIME Q on (Q.bdcoditem_dime = tpla.BDCODITEM_84_94) ';
      wsql = wsql||'where tpla.BDCODPLA_DIME = 1 and tpla.BDCODPLAPADRAO = '||:WPLANOCONTAS||' and (tpla.BDCODITEM_84_94 is not null) ';
      wsql = wsql||'  AND 24 = '||:BDCODUF_EMP; -- Alt.: 227307 - Deve considerar apenas as empresas de SC...
      wsql = wsql||' order by tpla.BDCODITEM_84_94'; --and tpla.BDANO = '||:prano||'

      :WCODEMPAUX = :bdCODEMP; -- Alt.: 227307 - Quandro 84/94 eh um gato de schrodinger, pode ou nao ser detalhado por filial, por isso, caso troque, guarda aqui a empresa para voltar para a empresa correta depois de apurar o quadro...
      FOR EXECUTE STATEMENT wSQL INTO :wCODTPLA,:wCODITEM_84_94,:bdCODEXP DO
        BEGIN
          bdquadro = '84_94';
          if (UPPER(:bdDETFILIAL) <> 'TRUE') then -- Alt.: 227307 - Se o parametro "Detalhamento das despesas por filial - Dime anual" estiver marcado, deve levar todos os valores na filial, caso contrario, soma tudo na matriz...
            :bdCODEMP = :bdCODMATRIZ;

          --sol:3520 - a rotina da exportação da dime no contabil esta diferente do balancete e da consulta de saldo... por isso foi mudado
          --select SALDO_ATUAL from VSUC_SP_RETORNA_SALDO(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 1, 0, null, :PRREFEMP, '', 1, 0)
          SELECT SALDO_ATUAL FROM SP_RETORNA_SALDO_EMP_X(:WCODEMP, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 0, 1, NULL, NULL, :PRREFEMP, 0, :PRCONTABILIZACAO, 0)
          INTO :bdSALDO;
    
          IF (bdSALDO <> 0) THEN
             SUSPEND;
        END
      :bdCODEMP = :WCODEMPAUX;

      --85 | Matheus Fritzen - 27/04/2023 - #176259
      wsql = '';
      wsql = wsql||'select tpla.BDCODTPLA, tpla.BDCODITEM_85, Q.bdcodexp from PLANOS_TPLA_DIME tpla ';
      wsql = wsql||'left outer join TQUADRO_ITENS_DIME Q on (Q.bdcoditem_dime = tpla.BDCODITEM_85) ';
      wsql = wsql||'where tpla.BDCODPLA_DIME = 1 and tpla.BDCODPLAPADRAO = '||:WPLANOCONTAS||' and (tpla.BDCODITEM_85 is not null) order by tpla.BDCODITEM_85'; --and tpla.BDANO = '||:prano||'
    
      FOR EXECUTE STATEMENT wSQL INTO :wCODTPLA,:wCODITEM_85,:bdCODEXP DO
        BEGIN
          bdquadro = '85';
    
          --sol:3520 - a rotina da exportação da dime no contabil esta diferente do balancete e da consulta de saldo... por isso foi mudado
          --select SALDO_ATUAL from VSUC_SP_RETORNA_SALDO(:bdcodemp, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 1, 0, null, :PRREFEMP, '', 1, 0)
          SELECT SALDO_ATUAL FROM SP_RETORNA_SALDO_EMP_X(:WCODEMP, :wCODTPLA, :PRDATAINI, :PRDATAFIM, 0, 1, NULL, NULL, :PRREFEMP, 0, :PRCONTABILIZACAO, 0)
          INTO :bdSALDO;
    
          IF (bdSALDO <> 0) THEN
             SUSPEND;
        END
    END

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:wRefAtual);

  --suspend;
END
^

/* Restore proc. body: SP_VEF_TREEVIEW_CONS_ANUAL_CON2 */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_ANUAL_CON2(PRCODEMP VARCHAR(10000),
PRREF INTEGER,
PRCODQUADRO INTEGER,
PRDETALHAQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDREF INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDORDEM INTEGER,
BDDESCRICAO VARCHAR(80),
BDVALOR NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDJAN NUMERIC(15,6),
BDFEV NUMERIC(15,6),
BDMAR NUMERIC(15,6),
BDABR NUMERIC(15,6),
BDMAI NUMERIC(15,6),
BDJUN NUMERIC(15,6),
BDJUL NUMERIC(15,6),
BDAGO NUMERIC(15,6),
BDSET NUMERIC(15,6),
BDOUT NUMERIC(15,6),
BDNOV NUMERIC(15,6),
BDDEZ NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WQUADROANT INTEGER;
DECLARE VARIABLE WDESQUADROANT VARCHAR(80);
DECLARE VARIABLE WORDEMANT INTEGER;
DECLARE VARIABLE WDESCORDEMANT VARCHAR(80);
DECLARE VARIABLE WANO CHAR(10);
DECLARE VARIABLE WPRIMEIROQUADRO INTEGER;
BEGIN
  /* giovanni */

  /* Procedure Text */

  /* SP Padrao para montar a treeview DA Consulta anual configuravel */

  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wano = SUBSTRING(prref FROM 1 FOR 4);

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql || 'empresas.BDNOMEMP, ';
  wsql = wsql || 'T.BDREF, ';
  wsql = wsql || 'T.BDCODQPLACONSCONF, ';
  wsql = wsql || 'QUADRO.BDDESCRICAO, ';
  wsql = wsql || 'T.BDORDEM, ';
  wsql = wsql || 'T.BDDESCRICAO,';
  wsql = wsql || 'T.BDVALOR';

  wsql = wsql || ' from VEF_REL_CONS_ANUAL_CONF T';


  /* tirado a spconsultaempresas_sis muito lenta... */
  --  wsql = wsql||' left outer join SP_CONSULTAEMPRESAS_SIS('|| pranomesfinal || ', t.bdcodemp, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;

  wsql = wsql||' left outer join VW_EMPRESAS_REF_ATUAL empresas on (empresas.bdcodemp = t.bdcodemp) ';
  wsql = wsql||' left outer join TPLANOCONSCONF_Q QUADRO on (QUADRO.BDCODQPLACONSCONF = t.BDCODQPLACONSCONF AND QUADRO.BDCODPLACONSCONF = T.BDCODPLACONSCONF) ' ;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODQPLACONSCONF  = '||:prcodquadro;
    END

  -- wsql = wsql||wwhere || ' order by bdcodemp, bdref desc, BDCODQPLACONSCONF, bdordem' ;
  wsql = wsql||wwhere || ' order by bdcodemp, BDCODQPLACONSCONF, bdordem, bdref  ' ;

  wquadroant = 0;
  wordemant = 0;
  wdesquadroant = '';
  wdescordemant = '';

  wPrimeiroQuadro = 1;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp,
    bdref,
    bdcodquadro,
    bddescquadro,
    bdordem,
    bddescricao,
    bdvalor

  DO
  BEGIN

     IF (((wordemant = bdordem) OR (wordemant = 0)) AND ((wquadroant = bdcodquadro) OR (wquadroant = 0))) THEN   /* totaliza o quadro e a ordem atual */ -- (((wquadroant = bdcodquadro) or (wquadroant = 0))
        BEGIN
          wquadroant = bdcodquadro;
          wdesquadroant = bddescquadro;
          wordemant = bdordem;
          wdescordemant = bddescricao;

          IF (bdtotal <> 0) THEN
             bdtotal = bdtotal + bdvalor;
          ELSE
             bdtotal = bdvalor;

          IF (bdref = CAST(TRIM(wano)||'01' AS INTEGER)) THEN
             bdjan = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'02' AS INTEGER)) THEN
             bdfev = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'03' AS INTEGER)) THEN
             bdmar = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'04' AS INTEGER)) THEN
             bdabr = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'05' AS INTEGER)) THEN
             bdmai = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'06' AS INTEGER)) THEN
             bdjun = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'07' AS INTEGER)) THEN
             bdjul = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'08' AS INTEGER)) THEN
             bdago = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'09' AS INTEGER)) THEN
             bdset = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'10' AS INTEGER)) THEN
             bdout = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'11' AS INTEGER)) THEN
             bdnov = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'12' AS INTEGER)) THEN
             bddez = bdvalor;

        END

     ELSE
       BEGIN

          IF (((prdetalhaquadro = 1) AND (wquadroant <> bdcodquadro)) OR (wprimeiroquadro = 1)) THEN  /* quebra por quadro */
--         if  ((wprimeiroquadro = 1) and (prdetalhaquadro = 1)) then  /* quebra por quadro */
           BEGIN
             wprimeiroquadro = 0;
             bdordem = NULL;
             bddescricao = bddescquadro;
             SUSPEND;
           END


         bdordem = wordemant;
         bdcodquadro = wquadroant;
         bddescquadro = wdesquadroant;
         bddescricao = wdescordemant;
         SUSPEND;
         wquadroant = 0;
         wordemant = 0;
         bdtotal = 0;

          IF (bdtotal <> 0) THEN
             bdtotal = bdtotal + bdvalor;
          ELSE
             bdtotal = bdvalor;

          IF (bdref = CAST(TRIM(wano)||'01' AS INTEGER)) THEN
             bdjan = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'02' AS INTEGER)) THEN
             bdfev = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'03' AS INTEGER)) THEN
             bdmar = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'04' AS INTEGER)) THEN
             bdabr = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'05' AS INTEGER)) THEN
             bdmai = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'06' AS INTEGER)) THEN
             bdjun = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'07' AS INTEGER)) THEN
             bdjul = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'08' AS INTEGER)) THEN
             bdago = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'09' AS INTEGER)) THEN
             bdset = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'10' AS INTEGER)) THEN
             bdout = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'11' AS INTEGER)) THEN
             bdnov = bdvalor;
          ELSE
          IF (bdref = CAST(TRIM(wano)||'12' AS INTEGER)) THEN
             bddez = bdvalor;


         wdesquadroant = '';
         wdescordemant = '';
       END

  END

  IF (wprimeiroquadro = 1) THEN  /* quebra por quadro */
     BEGIN
       wprimeiroquadro = 0;
       bdordem = NULL;
       bddescricao = bddescquadro;
       SUSPEND;
     END


  bdordem = wordemant;
  bdcodquadro = wquadroant;
  bddescquadro = wdesquadroant;
  bddescricao = wdescordemant;
  SUSPEND;


END
^

/* Restore proc. body: SP_VEF_TREEVIEW_CONS_BLOCOP */
CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_BLOCOP (
    PRCODEMP VARCHAR(10000),
    PRANOMESINICIAL INTEGER,
    PRANOMESFINAL INTEGER,
    PRCODPERIODO VARCHAR(1000),
    PRCLASSIFICACAO VARCHAR(10),
    PRGERAL INTEGER,
    PREMPFIL INTEGER,
    PRCODIGOAJUSTE VARCHAR(8),
    PRREINF DM_BOOLEAN)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP VARCHAR(100),
    BDCODCONF INTEGER,
    BDREFERENCIA INTEGER,
    BDCODPERIODO INTEGER,
    BDNUMCAMPO INTEGER,
    BDCODQUADRO INTEGER,
    BDDESCQUADRO VARCHAR(80),
    BDDESCFORM DM_BDNOMEMP,
    BDVALOR NUMERIC(15,2),
    BDANOMESINICIAL INTEGER,
    BDANOMESFINAL INTEGER,
    BDCLASSIFICACAO VARCHAR(10),
    BDCODEMPFILIAL INTEGER,
    BDORDENATVPREV INTEGER,
    BDCODIGOATVPREV VARCHAR(8),
    BDDESCPREV VARCHAR(550),
    BDNOMEMPFIL VARCHAR(100),
    BDCODTIPO INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE PRREFANT INTEGER;
DECLARE VARIABLE PRQUADROANT INTEGER;
DECLARE VARIABLE PRNUMCAMPO INTEGER;
DECLARE VARIABLE PRDESCFORM VARCHAR(60);
DECLARE VARIABLE PRVALOR NUMERIC(15,2);
DECLARE VARIABLE WEMPANT INTEGER;
DECLARE VARIABLE WATVANT INTEGER;
DECLARE VARIABLE PRSALVAQUADROANT INTEGER;
DECLARE VARIABLE PRCLASSIFIANT VARCHAR(10);
DECLARE VARIABLE PRDESCQUADROANT VARCHAR(80);
DECLARE VARIABLE WAUX INTEGER;
DECLARE VARIABLE WCLASSIFITITULO VARCHAR(10);
DECLARE VARIABLE PRULTIMOCLASSIFITIT VARCHAR(10);
DECLARE VARIABLE WISREINF CHAR(1);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);
  PRREINF = UPPER(:PRREINF);

  wIsReinf = SUBSTRING(:PRREINF FROM 1 FOR 1);

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql || 'empresas.BDNOMEMP, ';
  wsql = wsql || ' IIF('''||:wIsReinf|| ''' = ''T'', EMPRESAS.BDCODCONFCPRBREINF, EMPRESAS.BDCODCONFBLOCOP) BDCODCONFBLOCOP, ';
  wsql = wsql || 'T.BDREFERENCIA, ';
  wsql = wsql || 'T.BDCODPERIODO, ';
  wsql = wsql || 'T.BDNUMCAMPO, ';
  wsql = wsql || 'T.BDCODQBLOCOP, ';
  wsql = wsql || 'TCONF.bddescqBLOCOP,';
  wsql = wsql || 'TCONFBLOCOPFORM.bddescformBLOCOP,';
  wsql = wsql || 'T.BDVALOR, ';
  wsql = wsql || 'TCONF.BDCLASSIFICACAO, ';
  wsql = wsql || 'NULL BDCODEMPFILIAL, ';
  wsql = wsql || 'NULL BDORDENATVPREV, ';
  wsql = wsql || 'NULL BDCODIGOATVPREV, ';
  wsql = wsql || 'NULL BDDESCPREV, ';
  wsql = wsql || 'NULL BDNOMEMPFIL, ';
  wsql = wsql || 'TCONF.BDCODTIPO ';

  wsql = wsql || 'from VEF_EMP_TBLOCOPGERREG T';

  wsql = wsql||' JOIN VEF_EMP_TBLOCOPGER GER ON(GER.BDCODEMP = T.BDCODEMP AND GER.BDCODPERIODO = T.BDCODPERIODO AND GER.BDREFERENCIA = T.BDREFERENCIA AND GER.BDREINF = '||''''||:wIsReinf||''''||' AND GER.BDCODCONFBLOCOP = T.BDCODCONFBLOCOP)';
  wsql = wsql||' left outer join vw_emp_ref_total empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;
  wsql = wsql||' left outer join VEF_BASE_TCONFBLOCOPQ TCONF on (TCONF.bdcodqBLOCOP = t.bdcodqBLOCOP ) ' ;
  wsql = wsql||' left outer join VEF_BASE_TCONFBLOCOPFORM TCONFBLOCOPFORM on (TCONFBLOCOPFORM.bdcodconfBLOCOP = IIF('''||:wIsReinf|| ''' = ''T'', EMPRESAS.BDCODCONFCPRBREINF, EMPRESAS.BDCODCONFBLOCOP) and TCONFBLOCOPFORM.bdcodqBLOCOP = T.BDCODQBLOCOP  and TCONFBLOCOPFORM.bdnumcampoBLOCOP = T.BDNUMCAMPO) ' ;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;

  IF (wWhere <> '') THEN
    wWhere = wWhere || ' AND ';
  ELSE
    wWhere = wWhere || ' WHERE ';

  --wWhere = wWhere || 'T.BDCODCONFBLOCOP = '||:wCodConfBlocoP;
  wWhere = wWhere || 'T.BDCODCONFBLOCOP = '||'IIF('''||:wIsReinf|| ''' = ''T'', EMPRESAS.BDCODCONFCPRBREINF, EMPRESAS.BDCODCONFBLOCOP) ';

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

/*  if (:prcodquadro is not null) then
    begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       else
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODQBLOCOP = '||:prcodquadro;
    end*/

  IF (PRCLASSIFICACAO IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'TCONF.bdclassificacao LIKE '''||:PRCLASSIFICACAO||'%''';
    END

  IF (:prcodperiodo IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||'('||:prcodperiodo||')';
    END


  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, BDCODQBLOCOP, bdCODPERIODO, bdnumcampo' ;

  prrefant        = 0;
  prquadroant     = 0;
  PRULTIMOCLASSIFITIT = '';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp,
    bdcodconf,
    BDREFERENCIA,
    BDCODPERIODO,
    BDNUMCAMPO,
    bdcodquadro,
    bddescquadro,
    bddescform,
    BDVALOR,
    BDCLASSIFICACAO,
    BDCODEMPFILIAL,
    BDORDENATVPREV,
    BDCODIGOATVPREV,
    BDDESCPREV,
    BDNOMEMPFIL,
    BDCODTIPO
  DO
  BEGIN
    bdanomesfinal   = pranomesfinal;
    bdanomesinicial = pranomesinicial;
    prnumcampo = bdnumcampo;
    prdescform = bddescform;
    prvalor = bdvalor;

    --Referência
    IF ((prGeral = 1) AND (prrefant <> bdreferencia) AND (pranomesinicial <> pranomesfinal)) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  CAST(bdreferencia AS VARCHAR(6));
        bddescform =  SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
        BDVALOR = NULL;
        SUSPEND;
      END

    --Quadro
    IF ((prGeral = 1) AND (prquadroant <> bdcodquadro)) THEN
      BEGIN
        prsalvaquadroant = bdcodquadro;
        prclassifiant = bdclassificacao;
        prdescquadroant = bddescquadro;

        SELECT FIRST 1 tpos.pos FROM pos('.', :bdclassificacao) tpos INTO :waux;

        IF (waux > 1) THEN -- classificacao titulo
          BEGIN

            wclassifititulo = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);

            IF  (prultimoclassifitit <> wclassifititulo) THEN
              BEGIN

                SELECT x.bdcodqblocop, x.bddescqblocop FROM vef_base_tconfblocopq x WHERE x.bdclassificacao = :wclassifititulo INTO
                    :bdcodquadro,
                    :bddescform;


                prultimoclassifitit = wclassifititulo;
                bdnumcampo = NULL;
                BDVALOR = NULL;
                prquadroant = bdcodquadro;
                bdclassificacao = wclassifititulo;
                bddescquadro = bddescform;

                SUSPEND;
                bdclassificacao = prclassifiant;
                bddescquadro = prdescquadroant;
                bdcodquadro = prsalvaquadroant;
              END

          END

        bdnumcampo = NULL;
        BDDESCFORM = bdclassificacao || ' - ' || BDDESCQUADRO;
        BDVALOR = NULL;
        prquadroant = bdcodquadro;

        SUSPEND;



        --bdnumcampo = null;
        --BDDESCFORM =  BDDESCQUADRO;
        --BDVALOR = null;
        --suspend;
      END

    bdnumcampo = prnumcampo;
    bddescform = prdescform;
    bdvalor = prvalor;

    prrefant = bdreferencia;
    prquadroant = bdcodquadro;

    SUSPEND;
  END

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql || 'empresas.BDNOMEMP, ';
  wsql = wsql || ' IIF('''||:wIsReinf|| ''' = ''T'', EMPRESAS.BDCODCONFCPRBREINF, EMPRESAS.BDCODCONFBLOCOP) BDCODCONFBLOCOP, ';
  wsql = wsql || 'T.BDREFERENCIA, ';
  wsql = wsql || 'T.BDCODPERIODO, ';
  wsql = wsql || 'T.BDNUMCAMPO, ';
  wsql = wsql || 'T.BDCODQBLOCOP, ';
  wsql = wsql || 'TCONF.bddescqBLOCOP,';
  wsql = wsql || 'TCONFBLOCOPFORM.bddescformBLOCOP,';
  wsql = wsql || 'T.BDVALOR, ';
  wsql = wsql || 'TCONF.BDCLASSIFICACAO, ';
  wsql = wsql || 'T.BDCODEMPFILIAL, ';
  wsql = wsql || 'T.BDORDENATVPREV, ';
  wsql = wsql || 'prev.bdcodigoatvprev, ';
  wsql = wsql || 'prev.bddescprev, ';
--  wsql = wsql || ' (select n2.bdnomemp from vw_emp_ref_total n2 where n2.bdcodemp = T.BDCODEMPFILIAL) as BDNOMEMPFIL, ';
  wsql = wsql || 'fil.bdNOMEMP as bdNOMEMPFIL, ';
  wsql = wsql || 'TCONF.BDCODTIPO ';

  wsql = wsql || 'from vef_emp_tblocopger_filial T';

  wsql = wsql||' JOIN VEF_EMP_TBLOCOPGER GER ON(GER.BDCODEMP = T.BDCODEMP AND GER.BDCODPERIODO = T.BDCODPERIODO AND GER.BDREFERENCIA = T.BDREFERENCIA AND GER.BDREINF = '||''''||:wIsReinf||''''||' AND GER.BDCODCONFBLOCOP = T.BDCODCONFBLOCOP)';
  wsql = wsql||' left outer join vw_emp_ref_total empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;
  wsql = wsql||' left outer join VEF_BASE_TCONFBLOCOPQ TCONF on (TCONF.bdcodqBLOCOP = t.bdcodqBLOCOP ) ' ;
  wsql = wsql||' left outer join VEF_BASE_TCONFBLOCOPFORM TCONFBLOCOPFORM on (TCONFBLOCOPFORM.bdcodconfBLOCOP = IIF('''||:wIsReinf|| ''' = ''T'', EMPRESAS.BDCODCONFCPRBREINF, EMPRESAS.BDCODCONFBLOCOP) and TCONFBLOCOPFORM.bdcodqBLOCOP = T.BDCODQBLOCOP  and TCONFBLOCOPFORM.bdnumcampoBLOCOP = T.BDNUMCAMPO) ' ;
  wsql = wsql||' join VEF_BASE_TTABATVCONPREV prev on (t.bdordenatvprev = prev.bdordenatvprev) ';
  wsql = wsql||' JOIN VW_TEMPRESAS_REF fil ON (fil.bdCODEMP = t.bdCODEMPFILIAL) ';
  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;

  IF (wWhere <> '') THEN
    wWhere = wWhere || ' AND ';
  ELSE
    wWhere = wWhere || ' WHERE ';

  --wWhere = wWhere || 'T.BDCODCONFBLOCOP = '||:wCodConfBlocoP;
  wWhere = wWhere || 'T.BDCODCONFBLOCOP = '||'IIF('''||:wIsReinf|| ''' = ''T'', EMPRESAS.BDCODCONFCPRBREINF, EMPRESAS.BDCODCONFBLOCOP) ';


  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

/*  if (:prcodquadro is not null) then
    begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       else
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODQBLOCOP = '||:prcodquadro;

    end*/

  IF (PRCLASSIFICACAO IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'TCONF.bdclassificacao LIKE '''||:PRCLASSIFICACAO||'%''';
    END

  IF (:prcodperiodo IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||'('||:prcodperiodo||')';
    END

  IF (:PREMPFIL IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||'(T.BDCODEMPFILIAL = '||:PREMPFIL||')';
    END

  IF (:prcodigoajuste IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||'(prev.BDCODIGOATVPREV = '||''''||:prcodigoajuste||''''||')';
    END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';
  ELSE
     wwhere = wwhere||' where ';

  wwhere = wwhere||' ((T.BDCODQBLOCOP = 4 and T.BDVALOR > 0) or (T.BDCODQBLOCOP <> 4)) ';

  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, BDCODEMPFILIAL,BDCODQBLOCOP, bdCODPERIODO, BDORDENATVPREV, bdnumcampo' ;

  prrefant        = 0;
  prquadroant     = 0;
  WEMPANT         = 0;
  WATVANT         = 0;

  PRULTIMOCLASSIFITIT = '';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp,
    bdcodconf,
    BDREFERENCIA,
    BDCODPERIODO,
    BDNUMCAMPO,
    bdcodquadro,
    bddescquadro,
    bddescform,
    BDVALOR,
    BDCLASSIFICACAO,
    BDCODEMPFILIAL,
    BDORDENATVPREV,
    BDCODIGOATVPREV,
    BDDESCPREV,
    BDNOMEMPFIL,
    BDCODTIPO
  DO
  BEGIN
    bdanomesfinal   = pranomesfinal;
    bdanomesinicial = pranomesinicial;
    prnumcampo = bdnumcampo;
    prdescform = bddescform;
    prvalor = bdvalor;

    --Referência
    IF ((prGeral = 1) AND (prrefant <> bdreferencia) AND (pranomesinicial <> pranomesfinal)) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  CAST(bdreferencia AS VARCHAR(6));
        bddescform =  SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
        BDVALOR = NULL;
        SUSPEND;
      END

    --Empresa FILIAL
    IF ((prGeral = 1) AND (WEMPANT <> bdcodempfilial)) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  bdcodempfilial||' - '||BDNOMEMPFIL;
        BDVALOR = NULL;
        SUSPEND;
      END

    --Quadro
    IF ((prGeral = 1) AND (prquadroant <> bdcodquadro)) THEN
      BEGIN
        prsalvaquadroant = bdcodquadro;
        prclassifiant = bdclassificacao;
        prdescquadroant = bddescquadro;

        SELECT FIRST 1 tpos.pos FROM pos('.', :bdclassificacao) tpos INTO :waux;

        IF (waux > 1) THEN -- classificacao titulo
          BEGIN

            wclassifititulo = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);

            IF  (prultimoclassifitit <> wclassifititulo) THEN
              BEGIN

                --select x.bddescqblocop from vef_base_tconfblocopq x where x.bdclassificacao = :wclassifititulo into :bddescform;
                SELECT x.bdcodqblocop, x.bddescqblocop FROM vef_base_tconfblocopq x WHERE x.bdclassificacao = :wclassifititulo INTO
                    :bdcodquadro,
                    :bddescform;


                prultimoclassifitit = wclassifititulo;
                bdnumcampo = NULL;
                BDVALOR = NULL;
                prquadroant = bdcodquadro;
                bdclassificacao = wclassifititulo;
                bddescquadro = bddescform;

                SUSPEND;
                bdclassificacao = prclassifiant;
                bddescquadro = prdescquadroant;
                bdcodquadro = prsalvaquadroant;
              END

          END

        bdnumcampo = NULL;
        --BDDESCFORM = bdclassificacao || ' - ' || BDDESCQUADRO;
        BDDESCFORM = BDDESCQUADRO;
        BDVALOR = NULL;
        prquadroant = bdcodquadro;

        SUSPEND;
        --bdnumcampo = null;
        --BDDESCFORM =  BDDESCQUADRO;
        --BDVALOR = null;
        --suspend;

      END

    IF (BDCODTIPO = 73) THEN
       BEGIN
            bdnumcampo = prnumcampo;
            bddescform = prdescform;
            bdvalor = prvalor;
        
            prrefant = bdreferencia;
            prquadroant = bdcodquadro;
            --WEMPANT = bdcodempfilial;
            --WATVANT = bdordenatvprev;

            SUSPEND;
       END
    ELSE
       BEGIN
            --Atividade
            IF ((prGeral = 1) AND (WATVANT <> bdordenatvprev) OR (WEMPANT <> bdcodempfilial)) THEN
              BEGIN
                bdnumcampo = NULL;
                BDDESCFORM =  SUBSTRING(BDCODIGOATVPREV||' - '||BDDESCPREV FROM 1 FOR 80);
                BDVALOR = NULL;
                SUSPEND;
              END
        
            bdnumcampo = prnumcampo;
            bddescform = prdescform;
            bdvalor = prvalor;
        
            prrefant = bdreferencia;
            prquadroant = bdcodquadro;
            WEMPANT = bdcodempfilial;
            WATVANT = bdordenatvprev;
        
            SUSPEND;
       END
  END

END
^

/* Restore proc. body: SP_VEF_TREEVIEW_CONS_CALCATIVO */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_CALCATIVO(PRCODEMP VARCHAR(10000),
PRCODBEM VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PRGRUPO VARCHAR(30))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODBEM INTEGER,
BDNOMBEM VARCHAR(200),
BDREFERENCIA INTEGER,
BDFATOR NUMERIC(15,6),
BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE WGROUPBY VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(10000);
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE PRCODBEMANT INTEGER;
DECLARE VARIABLE PRNOMEBEMANT VARCHAR(100);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

  /*agrupar por empresa*/
  IF (prgrupo = 1) THEN
     BEGIN
       wSql = 'select tativo.BDCODEMP, ';
       wSql = wSql || 'emp.BDNOMEMP ';
     END
  ELSE
  /*agrupar por bem*/
  IF (prGrupo = 2) THEN
     BEGIN
       wSql = 'select tativo.BDCODBEM, ';
       wSql = wSql || 'tbem.BDNOMBEM ';
     END
  ELSE
     BEGIN
       wSql = 'select tativo.BDCODEMP, ';
       wSql = wSql || 'emp.BDNOMEMP, ';
       wSql = wSql || 'tativo.BDCODBEM, ';
       wSql = wSql || 'tbem.BDNOMBEM, ';
       wSql = wSql || 'tativo.BDREFERENCIA, ';
       wSql = wSql || 'tativo.BDFATOR, ';
       wSql = wSql || 'tativo.BDVALOR ';
     END

  wsql = wsql || 'from vef_emp_tfichaativo tativo ';

  wsql = wsql||'left outer join SP_CONSULTAEMPRESAS_SIS('|| prrefatual || ', tativo.bdcodemp, null) emp on (emp.bdcodemp = tativo.bdcodemp ) ' ;

  IF (prgrupo IS NOT NULL) THEN
     wsql = wSql||'left outer join EMPRESAS_TBEM TBEM on (tbem.bdcodemp = emp.bdcodemp and tbem.bdcodbem = tativo.bdCODBEM) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL) THEN
     wwhere = wWhere||PRCODEMP||' ';

  IF ((prcodbem IS NOT NULL) OR (prcodbem > 0)) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wWhere = wwhere||PRCODBEM||' ';
     END

  IF ((prrefini IS NOT NULL) AND (prrefini > 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDREFERENCIA >= '||prrefini||' ';
     END

  IF ((prreffin IS NOT NULL) AND (prreffin > 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDREFERENCIA <= '||prreffin||' ';
     END

  IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

  IF (prgrupo = 1) THEN
     BEGIN
       wgroupby = 'group by bdcodemp, bdnomemp ';
       worderby = 'order by bdcodemp ';
      END
  ELSE
  IF (prGrupo = 2) THEN
     BEGIN
       wgroupby = 'group by bdcodbem, bdnombem ';
       worderby = 'order by bdcodbem ';
     END
  ELSE
     BEGIN
       wgroupby = '';
       worderby = 'order by bdcodemp, bdcodbem, bdreferencia ';
     END

  wsql = wsql||wwhere||wgroupby||worderby;

  IF (prgrupo = 1) THEN
     BEGIN
        FOR EXECUTE STATEMENT wsql
          INTO
            :BDCODEMP,
            :BDNOMEMP
          DO
          SUSPEND;
    END
 ELSE
 IF (prgrupo = 2) THEN
   BEGIN
     FOR EXECUTE STATEMENT wsql
          INTO
            :BDCODBEM,
            :BDNOMBEM
          DO
          SUSPEND;
   END
 ELSE
    BEGIN
       prcodbemant = 0;
       FOR EXECUTE STATEMENT wsql
          INTO
            :BDCODEMP,
            :BDNOMEMP,
            :BDCODBEM,
            :BDNOMBEM,
            :BDREFERENCIA,
            :BDFATOR,
            :BDVALOR
          DO


       /* Giovanni inicio para nao repetir o nome do bem em todos os meses
       if (prCodBemAnt = bdcodbem) then
         begin
           prCodBemAnt = bdcodbem;
           prnomebemant = bdnombem;

           bdcodbem = null;
           bdnombem = null;
           suspend;
           bdcodbem = prCodBemAnt;
           bdnombem = prnomebemant;
        end
       else
         begin
           suspend;
           prcodbemant = bdcodbem;
         end

         */

       SUSPEND;
    END
END
^

/* Restore proc. body: SP_VEF_TREEVIEW_CONS_DACON */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_DACON(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO VARCHAR(1000),
PRCODQUADRO INTEGER,
PRGERAL INTEGER,
PRTIPO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(160),
BDDESCFORM VARCHAR(160),
BDVALOR NUMERIC(18,6),
BDVALOR2 NUMERIC(18,6),
BDVALOR3 NUMERIC(18,6),
BDNUMITEM INTEGER,
BDCLASSIFICACAO VARCHAR(10),
BDCODREC INTEGER,
BDTIPOCREDITO INTEGER,
BDTIPOCONFDACON INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE PRREFANT INTEGER;
DECLARE VARIABLE PRQUADROANT INTEGER;
DECLARE VARIABLE PRNUMCAMPO INTEGER;
DECLARE VARIABLE PRDESCFORM VARCHAR(150);
DECLARE VARIABLE WVALOR NUMERIC(18,6);
DECLARE VARIABLE WVALOR2 NUMERIC(18,6);
DECLARE VARIABLE WVALOR3 NUMERIC(18,6);
DECLARE VARIABLE PRCODPERIODOANT INTEGER;
DECLARE VARIABLE WNUMITEM INTEGER;
DECLARE VARIABLE WCODREC INTEGER;
DECLARE VARIABLE WBDTIPOCREDITO INTEGER;
DECLARE VARIABLE WBDDESCREC VARCHAR(150);
DECLARE VARIABLE WBDDESCTIPOCRED VARCHAR(100);
DECLARE VARIABLE WDESCQUADRO VARCHAR(150);
DECLARE VARIABLE WDESCQUADROBKP VARCHAR(150);
DECLARE VARIABLE WDESC1424 VARCHAR(150);
DECLARE VARIABLE WITEM1424 INTEGER;
DECLARE VARIABLE WCODTIPOQUADRO1424 INTEGER;
DECLARE VARIABLE WBDCNPJPART VARCHAR(18);
DECLARE VARIABLE WSALVACNPJPART VARCHAR(18);
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql = 'select distinct T.BDCODEMP, ';
  wsql = wsql || 'emp.BDNOMEMP, ';
--  wsql = wsql || 'empresas.BDCODCONFDACON, ';
  wsql = wsql || 'empresas.bdcodconfdacon, ';
  wsql = wsql || 'T.BDREFERENCIA, ';
  wsql = wsql || 'T.BDCODPERIODO, ';
  wsql = wsql || 'T.BDNUMCAMPO, ';
  wsql = wsql || 'T.BDCODQDACON, ';
  wsql = wsql || 'TCONF.bddescqDACON,';
  wsql = wsql || 'TCONFDACONFORM.bddescformDACON,';
  wsql = wsql || 'T.BDVALOR, ';
  wsql = wsql || 'T.BDVALOR2, ';
  wsql = wsql || 'T.BDVALOR3, ';
  wsql = wsql || 'TCONFDACONFORM.BDNUMITEM, ';
  wsql = wsql || 'TCONF.BDCLASSIFICACAO, ';
  wsql = wsql || 'T.BDCODREC, ';
  wsql = wsql || 'rec.BDDESCREC, ';
  wsql = wsql || 't.BDTIPOCREDITO, ';
  wsql = wsql || 'TIPOCRED.BDDESCTIPOCRED, ';

  wsql = wsql || 'TCONFDACONFORM1424.bddescformdacon, ';
  wsql = wsql || 'TCONFDACONFORM1424.BDNUMITEM, ';
  wsql = wsql || 'TCONF.BDCODTIPO, ';
  wsql = wsql || 'TCONFDACON.BDTIPOCONFDACON, ';
  wsql = wsql || 'T.BDCNPJ ';


--  wsql = wsql || 'BDQBH ';
  wsql = wsql || 'from VW_VEF_EMP_TDACONGERUNION T';


  wsql = wsql||' left outer join VW_VEF_BASE_TEMPPARGER empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;
  wsql = wsql||' left outer join vw_tempresas_ref emp on (emp.bdcodemp = t.bdcodemp ) ' ;
--  wsql = wsql||' left outer join SP_CONSULTAEMPRESAS_SIS('|| pranomesfinal || ', t.bdcodemp, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;
  wsql = wsql||' left outer join tcodrec rec on (t.bdcodrec = rec.bdcodrec) ';

  wsql = wsql||' left outer join VEF_BASE_TCONFDACONQ TCONF on (TCONF.bdcodqDACON = t.bdcodqDACON ) ' ;
--  wsql = wsql||' left outer join VEF_BASE_TCONFDACONFORM TCONFDACONFORM on (TCONFDACONFORM.bdcodconfDACON = empresas.bdcodconfDACON  and TCONFDACONFORM.bdcodqDACON = T.BDCODQDACON  and TCONFDACONFORM.bdnumcampoDACON = T.BDNUMCAMPO) ' ;
  wsql = wsql||' left outer join VEF_BASE_TCONFDACONFORM TCONFDACONFORM on (TCONFDACONFORM.bdcodconfDACON = empresas.bdcodconfdacon  and TCONFDACONFORM.bdcodqDACON = T.BDCODQDACON  and TCONFDACONFORM.bdnumcampoDACON = T.BDNUMCAMPO) ' ;

  wsql = wsql||' left outer join vef_base_tconfdaconf1424 TCONFDACONFORM1424 on (TCONFDACONFORM1424.bdcodconfDACON = empresas.bdcodconfdacon  and TCONFDACONFORM1424.bdcodqDACON = T.BDCODQDACON  and TCONFDACONFORM1424.bdnumcampoDACON = T.BDNUMCAMPO) ' ;

  wsql = wsql||' left outer join VEF_BASE_TTABTIPOSCREDTODOS TIPOCRED on (TIPOCRED.bdtipocredito = T.bdtipocredito ) ' ;

  wsql = wsql||' left outer join VEF_BASE_TCONFDACON TCONFDACON on (empresas.bdcodconfdacon = TCONFDACON.bdcodconfdacon ) ' ;


  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;


  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODQDACON = '||:prcodquadro;

    END

  IF (:prcodperiodo IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||'('||:prcodperiodo||')';
    END

  IF (:PRTIPO IS NOT NULL) THEN
    BEGIN
       IF (PRTIPO = 2) THEN--PIS
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
            ELSE
               wwhere = wwhere||' where ';
    
            --wwhere = wWhere||'(T.BDCODQDACON in (60,61,62,68,69,70))';
            wwhere = wWhere||'(TCONF.BDCODTIPO in (64,65,66))';
          END
       ELSE
       IF (PRTIPO = 3) THEN--COFINS
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
            ELSE
               wwhere = wwhere||' where ';
    
            --wwhere = wWhere||'(T.BDCODQDACON in (64,65,66,72,73,74))';
            wwhere = wWhere||'(TCONF.BDCODTIPO in (67,68,69))';
          END
       ELSE
       IF (PRTIPO = 4) THEN --Dacon
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
            ELSE
               wwhere = wwhere||' where ';
    
            --wwhere = wWhere||'(T.BDCODQDACON not in (60,61,62,68,69,70,64,65,66,72,73,74))';
            wwhere = wWhere||'(TCONF.BDCODTIPO not in (64,65,66,67,68,69))';
          END
    END

  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc , BDCLASSIFICACAO/*BDCODQDACON*/ ,bdcodrec,BDCNPJ,BDTIPOCREDITO,bdnumcampo, bdCODPERIODO';

  prrefant        = 0;
  prquadroant     = 0;
  prcodperiodoant = 0;
  wcodrec         = 0;
  wBDTIPOCREDITO  = 0;
  WDESCQUADRO     = '';
  WSALVACNPJPART  = '';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp,
    bdcodconf,
    BDREFERENCIA,
    BDCODPERIODO,
    BDNUMCAMPO,
    bdcodquadro,
    bddescquadro,
    bddescform,
    BDVALOR,
    BDVALOR2,
    BDVALOR3,
    BDNUMITEM,
    BDCLASSIFICACAO,
    BDCODREC,
    wBDDESCREC,
    BDTIPOCREDITO,
    wbddesctipocred,
    WDESC1424 ,
    WITEM1424,
    Wcodtipoquadro1424,
    BDTIPOCONFDACON,
    WBDCNPJPART

  DO
  BEGIN
    prnumcampo = bdnumcampo;
    prdescform = bddescform;
    wvalor = bdvalor;
    wvalor2 = bdvalor2;
    wvalor3 = bdvalor3;
    wNumItem = bdnumitem;
--    wcodrec  = bdcodrec;

    --Referência
    IF ((prGeral = 1) AND (prrefant <> bdreferencia) AND (pranomesinicial <> pranomesfinal)) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  CAST(bdreferencia AS VARCHAR(6));
        bddescform =  SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
        BDVALOR = NULL;
        BDVALOR2 = NULL;
        BDVALOR3 = NULL;
        BDNUMITEM = NULL;
        --prrefant = bdreferencia;
        SUSPEND;
      END

    --Quadro
    IF (/*(prGeral = 1) and */(prquadroant <> bdcodquadro)) THEN
      BEGIN
        IF ((((Wcodtipoquadro1424 = 64) AND (:PRCODQUADRO IS NULL)) OR ((Wcodtipoquadro1424 IN (64,65,66)) AND (:PRCODQUADRO IS NOT NULL))) OR
            (((Wcodtipoquadro1424 = 67) AND (:PRCODQUADRO IS NULL)) OR ((Wcodtipoquadro1424 IN (67,68,69)) AND (:PRCODQUADRO IS NOT NULL))) OR (PRTIPO = 1)) THEN
           BEGIN
            WDESCQUADROBKP = BDDESCQUADRO;
            IF (Wcodtipoquadro1424 IN (64,65,66)) THEN
               BDDESCQUADRO = 'Apuração do PIS';
            ELSE
               IF (Wcodtipoquadro1424 IN (67,68,69)) THEN
                  BDDESCQUADRO = 'Apuração do Cofins';
               ELSE
                  BDDESCQUADRO = 'Dacon';

            bdnumcampo = NULL;
            BDDESCFORM =  BDDESCQUADRO;
            BDNUMITEM = NULL;
            BDVALOR = NULL;
            BDVALOR2 = NULL;
            BDVALOR3 = NULL;
            wBDTIPOCREDITO = 0;
            --prquadroant = bdcodquadro;
            IF ((WDESCQUADRO <> BDDESCQUADRO) OR ((:PRTIPO IS NULL) OR (PRTIPO <> 1))) THEN
               SUSPEND;

            WDESCQUADRO = BDDESCQUADRO;
            BDDESCQUADRO = WDESCQUADROBKP;
           END
        ELSE
           IF (WDESCQUADRO = '') THEN
             BEGIN
                WDESCQUADROBKP = BDDESCQUADRO;
                BDDESCQUADRO = 'Dacon';
                bdnumcampo = NULL;
                BDDESCFORM =  BDDESCQUADRO;
                BDNUMITEM = NULL;
                BDVALOR = NULL;
                BDVALOR2 = NULL;
                BDVALOR3 = NULL;
                wBDTIPOCREDITO = 0;
                --prquadroant = bdcodquadro;
                SUSPEND;
    
                WDESCQUADRO = BDDESCQUADRO;
                BDDESCQUADRO = WDESCQUADROBKP;
              END

        bdnumcampo = NULL;
        BDDESCFORM =  BDDESCQUADRO;
        BDNUMITEM = NULL;
        BDVALOR = NULL;
        BDVALOR2 = NULL;
        BDVALOR3 = NULL;
        wBDTIPOCREDITO = 0;
        --prquadroant = bdcodquadro;
        IF ((:PRTIPO IS NULL) OR (PRTIPO <> 1)) THEN
           SUSPEND;
      END

    IF ((:PRTIPO IS NULL) OR (PRTIPO <> 1)) THEN
       BEGIN
        --Período
        IF (((prcodperiodoant <> bdcodperiodo) OR ((prquadroant <> bdcodquadro) AND (prcodperiodoant = bdcodperiodo))) AND (bdCodperiodo IN (2,3,4,5,6))) THEN
          BEGIN
            bdnumcampo = NULL;
            IF (bdcodperiodo = 2) THEN
               BDDESCFORM =  '1º decêndio';
            ELSE
            IF (bdcodperiodo = 3) THEN
               BDDESCFORM =  '2º decêndio';
            ELSE
            IF (bdcodperiodo = 4) THEN
               BDDESCFORM =  '3º decêndio';
            ELSE
            IF (bdcodperiodo = 5) THEN
               BDDESCFORM =  '1ª quinzena';
            ELSE
            IF (bdcodperiodo = 6) THEN
               BDDESCFORM =  '2ª quinzena';
    
            BDVALOR = NULL;
            BDVALOR2 = NULL;
            BDVALOR3 = NULL;
            BDNUMITEM = NULL;
            --prcodperiodoant = bdcodperiodo;
            SUSPEND;
          END
    
        IF ((BDCODREC IS NOT NULL) AND  (wcodrec <> BDCODREC)) THEN
          BEGIN
            bdnumcampo = NULL;
            BDVALOR = NULL;
            BDVALOR2 = NULL;
            BDVALOR3 = NULL;
            BDNUMITEM = NULL;
            wcodrec = BDCODREC;
            bddescform = bdcodrec || ' - '||wBDDESCREC;
    --        bdcodrec  =  ;
            SUSPEND;
          END
    

        IF ((WBDCNPJPART IS NOT NULL) AND  (WSALVACNPJPART <> WBDCNPJPART)) THEN
          BEGIN
            bdnumcampo = NULL;
            BDVALOR = NULL;
            BDVALOR2 = NULL;
            BDVALOR3 = NULL;
            BDNUMITEM = NULL;
            WSALVACNPJPART = WBDCNPJPART;
            bddescform = WBDCNPJPART;
            SUSPEND;
          END

    
        IF ((BDTIPOCREDITO IS NOT NULL) AND (wBDTIPOCREDITO <> BDTIPOCREDITO)) THEN
          BEGIN
            bdnumcampo = NULL;
            BDVALOR = NULL;
            BDVALOR2 = NULL;
            BDVALOR3 = NULL;
            BDNUMITEM = NULL;
            wBDTIPOCREDITO = BDTIPOCREDITO;
            bddescform = BDTIPOCREDITO || ' - '||wbddesctipocred;
            SUSPEND;
          END
    
    
        bdnumcampo = prnumcampo;
        IF (Wcodtipoquadro1424 IN (36,55)) THEN
          BEGIN
            bddescform = WDESC1424;
            bdnumitem = WITEM1424;
          END
        ELSE
          BEGIN
            bddescform = prdescform;
            bdnumitem = wNumItem;
          END

        bdvalor = wvalor;
        bdvalor2 = wvalor2;
        bdvalor3 = wvalor3;

        prrefant = bdreferencia;
        prquadroant = bdcodquadro;
        prcodperiodoant = bdcodperiodo;
    
        SUSPEND;
      END

   END
END
^

/* Restore proc. body: SP_VEF_TREEVIEW_CONS_DIME */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_DIME (
    PRCODEMP VARCHAR(10000),
    PRANOMESINICIAL INTEGER,
    PRANOMESFINAL INTEGER,
    PRCODPERIODO INTEGER,
    PRCODQUADRO INTEGER,
    PRCODQUADROPRINC INTEGER,
    PRGERAL INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCONF INTEGER,
    BDREFERENCIA INTEGER,
    BDCODPERIODO INTEGER,
    BDNUMCAMPO INTEGER,
    BDCODQUADRO INTEGER,
    BDCODQUADROPRINC INTEGER,
    BDCLASSIFICACAO VARCHAR(5),
    BDDESCQUADRO VARCHAR(80),
    BDDESCFORM VARCHAR(150),
    BDVALOR NUMERIC(15,6),
    BDCODTIPO INTEGER,
    BDCODNAT INTEGER,
    BDDATAREC DATE,
    BDCLAVENDIMEGERQ12 INTEGER,
    BDCODRECDIMEGERQ12 INTEGER,
    BDORIGEMDIMEGERQ46 INTEGER,
    BDNUMITEM INTEGER,
    BDANOMESINICIAL INTEGER,
    BDANOMESFINAL INTEGER,
    BDNUMACORDOQ12 varchar(15),
    BDCODBENEFTTD integer,
    BDVLRBCICMS numeric(15,2),
    BDVLRICMSEXON numeric(15,2),
    BDORDEMFUMDES varchar(250),
    BDVLRFUMDES numeric(15,2),
    BDVLRFUMDESDEV numeric(15,2),
    BDORDEMFUNSOC varchar(250),
    BDVLRFUNSOC numeric(15,2),
    BDVLRFUNSOCDEV numeric(15,2))
AS
declare variable PRVLRFUNSOCDEVANT numeric(15,2);
declare variable PRVLRFUNSOCANT numeric(15,2);
declare variable PRORDEMFUNSOCANT varchar(250);
declare variable PRVLRFUMDESDEVANT numeric(15,2);
declare variable PRVLRFUMDESANT numeric(15,2);
declare variable PRORDEMFUMDESANT varchar(250);
declare variable PRVLRICMSEXONANT numeric(15,2);
declare variable PRVLRBCICMSANT numeric(15,2);
declare variable PRCODBENEFTTDANT integer;
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE PRREFANT INTEGER;
DECLARE VARIABLE PRQUADROANT INTEGER;
DECLARE VARIABLE PRSALVAQUADROANT INTEGER;
DECLARE VARIABLE PRNATANT INTEGER;
DECLARE VARIABLE PRCLASSIFIANT VARCHAR(10);
DECLARE VARIABLE PRDESCQUADROANT VARCHAR(80);
DECLARE VARIABLE PRDATARECANTQ12 DATE;
DECLARE VARIABLE PRORIGEMDIMEGERQ46ANT INTEGER;
DECLARE VARIABLE PRCLAVENDIMEGERQ12ANT INTEGER;
DECLARE VARIABLE PRCODRECDIMEGERQ12ANT INTEGER;
DECLARE VARIABLE PRORIGEMDIMENUMACORDOQ12ANT VARCHAR(15);
DECLARE VARIABLE PRULTIMOCLASSIFITIT VARCHAR(10);
DECLARE VARIABLE PRNUMCAMPO INTEGER;
DECLARE VARIABLE PRNUMITEM INTEGER;
DECLARE VARIABLE PRDESCFORM VARCHAR(60);
DECLARE VARIABLE PRVALOR NUMERIC(15,6);
DECLARE VARIABLE WCODCID INTEGER;
DECLARE VARIABLE WCODCIDTOT INTEGER;
DECLARE VARIABLE WNOMCID VARCHAR(40);
DECLARE VARIABLE WCODNAT INTEGER;
DECLARE VARIABLE WCODUF INTEGER;
DECLARE VARIABLE WSIGLAUF VARCHAR(2);
DECLARE VARIABLE PRUFANT INTEGER;
DECLARE VARIABLE WPODETOTUFTIP6 INTEGER;
DECLARE VARIABLE WPODETOTUFTIP7 INTEGER;
declare variable WQ12 varchar(5);
declare variable WQ46 varchar(5);
DECLARE VARIABLE BDDESCFORMQ12 VARCHAR(150);
DECLARE VARIABLE BDDESCFORMQ46 VARCHAR(150);
DECLARE VARIABLE WCLASSIFITITULO VARCHAR(10);
DECLARE VARIABLE WAUX INTEGER;
BEGIN
  /* giovanni */

  /* SP Padrao para montar a treeview DA DIME */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql || 'empresas.BDNOMEMP, ';
  wsql = wsql || 'parsc.BDCODCONFDIMESC,';

  wsql = wsql || 'T.BDREFERENCIA, ';
  wsql = wsql || 'T.BDCODPERIODO, ';
  wsql = wsql || 'T.BDNUMCAMPO, ';
  wsql = wsql || 'T.BDCODQDIME,';
  wsql = wsql || 'TCONF.BDCODQDIMEPRINC,';
  wsql = wsql || 'TCONF.bdclassificacao, ';
  wsql = wsql || 'TCONF.bddescqDIME,';
  wsql = wsql || 'TCONFDIMEFORM.bddescformDIME,';
  wsql = wsql || 'TCONFDIMEFORMQ12.bddescformDIMEq12,';
  wsql = wsql || 'TCONFDIMEFORMQ46.bddescformDIMEq46,';
  wsql = wsql || 'T.BDVALOR BDVALOR, ';
  wsql = wsql || 'TCONF.bdcodtipo, ';
  wsql = wsql || 'T.bdcodcid, ';
  wsql = wsql || 'T.bdcodcidtot, ';
  wsql = wsql || 'TCID.BDNOMCID, ';
  wsql = wsql || 'T.BDCODNAT, ';
  wsql = wsql || 'T.BDDATAREC, '; -- Q12
  wsql = wsql || 'T.BDCLAVENDIMEGERQ12, ';
  wsql = wsql || 'T.BDCODRECDIMEGERQ12, ';
  wsql = wsql || 'T.BDORIGEMDIMEGERQ46, ';
  wsql = wsql || 'T.BDCODUF, ';
  wsql = wsql || 'UF.BDSIGLAUF, ';
  wsql = wsql || 'T.BDQ12, ';
  wsql = wsql || 'T.BDQ46, ';
  wsql = wsql || 'TCONFDIMEFORM.bdnumitem, ';
  wsql = wsql || 't.bdNUMACORDOQ12, ';
  wsql = wsql || 'T.bdcodbenefttd, ';--Q15
  wsql = wsql || 'T.bdvlrbcicms, ';
  wsql = wsql || 'T.bdvlricmsexon, ';
  wsql = wsql || 'T.bdordemfumdes, ';
  wsql = wsql || 'T.bdvlrfumdes, ';
  wsql = wsql || 'T.bdvlrfumdesdev, ';
  wsql = wsql || 'T.bdordemfunsoc, ';
  wsql = wsql || 'T.bdvlrfunsoc, ';
  wsql = wsql || 'T.bdvlrfunsocdev  ';

  /* Remvida a View "VW_VEF_EMP_TDIMEGERUNION" */
--  wsql = wsql || ' from VW_VEF_EMP_TDIMEGERUNION T';
  wsql = wsql || ' from ( ';
  --------------------------------------------------------------------------------
  --                                                                            --
  --------------------------------------------------------------------------------
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               BDPREFIXONAT as BDCODNAT, ';
  wsql = wsql||'               SUM(COALESCE(BDVALOR,0)) as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, /* Q 47, Q48 BDCODCID */ ';
  wsql = wsql||'               NULL as BDCODCIDTOT, /* Q 47, Q48 BDCODCIDTOT */ ';
  wsql = wsql||'               NULL as BDCODUF, /* Q 49 BDCODUF */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'               CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as bdcodbenefttd, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrbcicms, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlricmsexon, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdesdev, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsocdev /* Q15 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERNAT t ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRANOMESINICIAL;
    END
  IF (:PRANOMESFINAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') OR
           (:PRANOMESINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRANOMESFINAL;
    END
  wsql = wsql||'        GROUP BY BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQDIME, BDNUMCAMPO, BDPREFIXONAT ';
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               BDCODCID as BDCODCID, ';
  wsql = wsql||'               BDCODCIDTOT as BDCODCIDTOT, ';
  wsql = wsql||'               NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'               CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as bdcodbenefttd, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrbcicms, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlricmsexon, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdesdev, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsocdev /* Q15 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ47 t ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRANOMESINICIAL;
    END
  IF (:PRANOMESFINAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') OR
           (:PRANOMESINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRANOMESFINAL;
    END
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               t.BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL  as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               BDCODCID as BDCODCID, ';
  wsql = wsql||'               BDCODCIDTOT as BDCODCIDTOT, ';
  wsql = wsql||'               NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               CASE WHEN bdcodcidtot = 99999 THEN 999 ELSE BDCODEXP END as BDCODEXP48,  /* Q48 */ ';
  wsql = wsql||'               ALIM.BDALIMPREP as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'               CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as bdcodbenefttd, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrbcicms, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlricmsexon, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdesdev, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsocdev /* Q15 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ48 t ';
  wsql = wsql||'        JOIN VW_VEF_BASE_TEMPPARESTSC Alim ON (alim.bdcodemp = t.bdcodemp) ';
  wsql = wsql||'        LEFT OUTER JOIN VEF_BASE_TTABATIVQ48 exp48 ON (t.bdcodativq48 = exp48.bdcodativq48) ';
  wsql = wsql||'        WHERE (t.bdcodativq48 IS NOT NULL or alim.bdALIMPREP = ''TRUE'' OR BDCODCIDTOT = 99999) '; -- Alt.: #120134 - Quando a estiver marcada com "Fornecedor de alimentos preparados" deve levar no quadro 48
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        AND ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
  IF (:PRANOMESFINAL IS NOT NULL) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, ';
  wsql = wsql||'               NULL as BDCODCIDTOT, ';
  wsql = wsql||'               bdcoduf as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46,  /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'               CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as bdcodbenefttd, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrbcicms, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlricmsexon, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdesdev, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsocdev /* Q15 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ49 t ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRANOMESINICIAL;
    END
  IF (:PRANOMESFINAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') OR
           (:PRANOMESINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRANOMESFINAL;
    END
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               SUM(COALESCE(BDVALOR,0)) as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, ';
  wsql = wsql||'               NULL as BDCODCIDTOT, ';
  wsql = wsql||'               bdcoduf as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'               CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as bdcodbenefttd, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrbcicms, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlricmsexon, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdesdev, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsocdev /* Q15 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ50 t ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRANOMESINICIAL;
    END
  IF (:PRANOMESFINAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') OR
           (:PRANOMESINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRANOMESFINAL;
    END
  wsql = wsql||'        GROUP BY BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQDIME, BDNUMCAMPO, BDCODNAT, BDCODCID, BDCODCIDTOT,bdcoduf, BDDATAREC, BDCLAVENDIMEGERQ12, BDCODRECDIMEGERQ12, BDORIGEMDIMEGERQ46,BDQ12, BDQ46, BDCODBENEFTTD, bdvlrbcicms, BDVLRICMSEXON, BDORDEMFUMDES, BDVLRFUMDES, BDVLRFUMDESDEV, BDORDEMFUNSOC, BDVLRFUNSOC, BDVLRFUNSOCDEV';
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               NULL as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, ';
  wsql = wsql||'               NULL as BDCODCIDTOT, ';
  wsql = wsql||'               NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'               CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'               T.bdcodbenefttd, /* Q15 */';
  wsql = wsql||'               T.bdvlrbcicms, /* Q15 */';
  wsql = wsql||'               T.bdvlricmsexon, /* Q15 */';
  wsql = wsql||'               fds.bdcodfumdes || '' - '' || FDS.BDDESCRICAO AS BDORDEMFUMDES, /* Q15 */';
  wsql = wsql||'               T.bdvlrfumdes, /* Q15 */';
  wsql = wsql||'               T.bdvlrfumdesdev, /* Q15 */';
  wsql = wsql||'               fsc.bdcodfunsoc || '' - '' || FSC.BDDESCRICAO AS BDORDEMFUNSOC, /* Q15 */';
  wsql = wsql||'               T.bdvlrfunsoc, /* Q15 */';
  wsql = wsql||'               T.bdvlrfunsocdev /* Q15 */';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERVLRQ15  t ';
  wsql = wsql||'        LEFT OUTER JOIN VEF_BASE_TTABFUMDES FDS ON (FDS.BDORDEMFUMDES = T.BDORDEMFUMDES) ';
  wsql = wsql||'        LEFT OUTER JOIN VEF_BASE_TTABFUNDOSOCIAL FSC ON (FSC.BDORDEMFUNSOC = T.BDORDEMFUNSOC) ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRANOMESINICIAL;
    END
  IF (:PRANOMESFINAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') OR
           (:PRANOMESINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRANOMESFINAL;
    END
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, ';
  wsql = wsql||'               NULL as BDCODCIDTOT, ';
  wsql = wsql||'               NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'               CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as bdcodbenefttd, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrbcicms, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlricmsexon, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdesdev, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsocdev /* Q15 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMESCGERREG t ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRANOMESINICIAL;
    END
  IF (:PRANOMESFINAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') OR
           (:PRANOMESINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRANOMESFINAL;
    END
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, ';
  wsql = wsql||'               NULL as BDCODCIDTOT, ';
  wsql = wsql||'               NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               BDDATAREC as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               BDCLAVENDIMEGERQ12 as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               r.BDCODRECOF as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''TRUE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46,  /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'               t.BDNUMACORDO AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as bdcodbenefttd, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrbcicms, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlricmsexon, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdesdev, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsocdev /* Q15 */ ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ12 t ';
  wsql = wsql||'        left outer join TCODREC r on (r.BDCODREC = t.BDCODRECDIMEGERQ12) ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRANOMESINICIAL;
    END
  IF (:PRANOMESFINAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') OR
           (:PRANOMESINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRANOMESFINAL;
    END
  wsql = wsql||'      UNION ';
  wsql = wsql||'      select /*null*/7 BDCODPERIODO, ';
  wsql = wsql||'             BDCODEMP, ';
  wsql = wsql||'             BDREFERENCIA, ';
  wsql = wsql||'             /*39*/48 BDCODQDIME, /* Q10*/ ';
  wsql = wsql||'             (BDITEMDEBESP+100) BDNUMCAMPO, /* Q10*/ ';
  wsql = wsql||'             null as BDCODNAT, ';
  wsql = wsql||'             BDVALOR as BDVALOR, ';
  wsql = wsql||'             null as BDCODCID, ';
  wsql = wsql||'             null as BDCODCIDTOT, ';
  wsql = wsql||'             null as BDCODUF, /* Q49 */ ';
  wsql = wsql||'             BDDATAVENCTO as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'             BDCLAVENC as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'             r.BDCODRECOF as BDCODRECDIMEGERQ12, /* Q12 */ '; -- #169589 - Adam - 21/10/2022 - Estava trazendo o campo "t.BDCODREC"  mas precisava do campo "r.BDCODRECOF" que é o código de receita.
  wsql = wsql||'             null as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'             null as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'             ''TRUE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'             ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'             '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'             '''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'             CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as bdcodbenefttd, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrbcicms, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlricmsexon, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdesdev, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsocdev /* Q15 */ ';
  wsql = wsql||'      from VEF_EMP_TDIMEGERDEBESP t ';
  wsql = wsql||'      left outer join TCODREC r on (r.BDCODREC = t.BDCODREC) '; -- #169589 - Adam - 21/10/2022.
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRANOMESINICIAL;
    END
  IF (:PRANOMESFINAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') OR
           (:PRANOMESINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRANOMESFINAL;
    END
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               BDCODNAT as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               BDCODCID as BDCODCID, ';
  wsql = wsql||'               BDCODCIDTOT as BDCODCIDTOT, ';
  wsql = wsql||'               BDCODUF as BDCODUF, ';
  wsql = wsql||'               BDDATAREC as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               BDCLAVENDIMEGERQ12 as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               BDCODRECDIMEGERQ12 as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               BDORIGEMDIMEGERQ46 as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               BDIDENTIFICACAOREGESP as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               BDQ12 as BDQ12, /* Q12 */ ';
  wsql = wsql||'               BDQ46 as BDQ46,  /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'               CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12 /* Q12 */, ';
  wsql = wsql||'               NULL as bdcodbenefttd, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrbcicms, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlricmsexon, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdes, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfumdesdev, /* Q15 */ ';
  wsql = wsql||'               NULL as bdordemfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsoc, /* Q15 */ ';
  wsql = wsql||'               NULL as bdvlrfunsocdev /* Q15 */ ';
  wsql = wsql||'        FROM VEF_SP_DIMEQ46 t ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    wsql = wsql||'        WHERE ' ||:PRCODEMP;
  IF (:PRANOMESINICIAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') ) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRANOMESINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRANOMESINICIAL;
    END
  IF (:PRANOMESFINAL IS NOT NULL) THEN
    BEGIN
      IF ( (prcodemp IS NOT NULL) AND (prcodemp <> '') OR
           (:PRANOMESINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRANOMESFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRANOMESFINAL;
    END
  --------------------------------------------------------------------------------
  --                                                                            --
  --------------------------------------------------------------------------------
  wsql = wsql || '        ) T';
  /* tirado a spconsultaempresas_sis muito lenta... */
  --  wsql = wsql||' left outer join SP_CONSULTAEMPRESAS_SIS('|| pranomesfinal || ', t.bdcodemp, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;

  wsql = wsql||' LEFT OUTER JOIN (SELECT v.bdCODEMP, v.bdREFEMP, e.bdNOMEMP ';
  wsql = wsql||'                  FROM VW_TEMPRESAS_REF_MAX_MIN v ';
  wsql = wsql||'                  LEFT OUTER JOIN TEMPRESAS_REF e ON (v.bdCODEMP = e.bdCODEMP AND v.bdREFEMP = e.bdREFEMP) ';
  wsql = wsql||'                   ) empresas ON (empresas.bdCODEMP = t.bdCODEMP) ';
  --wsql = wsql||' LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTSC parsc ON (parsc.bdCODEMP = empresas.bdCODEMP AND parsc.bdREFEMP = empresas.bdREFEMP) '; Alt.: #224878 - Nao deve mais olhar a referencia, a view agora ja busca referencia correta...
  wsql = wsql||' LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTSC parsc ON (parsc.bdCODEMP = empresas.bdCODEMP) ';
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFDIMEQ tconf ON (TCONF.BDCODQDIME = T.BDCODQDIME) ';
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFDIMEFORM TCONFDIMEFORM on (TCONFDIMEFORM.bdcodconfdimesc = parsc.bdcodconfdimesc and ';
  wsql = wsql||'                                                             TCONFDIMEFORM.bdcodqdime = T.BDCODQDIME and TCONFDIMEFORM.bdnumcampodime = T.BDNUMCAMPO) ' ;
  --wsql = wsql||' left outer join vef_estados_tconfdimefq12 TCONFDIMEFORMQ12 on (TCONFDIMEFORMQ12.bdcodconfdimesc = empresas.bdcodconfdimesc and ';
  wsql = wsql||'left outer join ( ';
  wsql = wsql||'                 select BDCODCONFDIMESC, BDCODQDIME, BDNUMCAMPODIMEQ12, BDDESCFORMDIMEQ12 from VEF_ESTADOS_TCONFDIMEFQ12 ';
  wsql = wsql||'                 union all ';
  wsql = wsql||'                 select f.BDCODCONFDIMESC, 48 as BDCODQDIME, (esp.BDITEMDEBESP+100) as BDNUMCAMPODIMEQ12, esp.BDDESCRICAO ';
  wsql = wsql||'                 from VEF_ESTADOS_TCONFDIMEFORM f ';
  wsql = wsql||'                 join VEF_BASE_TTABITEMDEBESP esp on ( esp.bdcodexportar = f.bdnumitem ) ';
  wsql = wsql||'                 where /*f.BDCODCONFDIMESC = EMPRESAS.BDCODCONFDIMESC and*/ f.BDCODQDIME = 39 ';
  wsql = wsql||'                 ) TCONFDIMEFORMQ12 on (TCONFDIMEFORMQ12.BDCODCONFDIMESC = parsc.BDCODCONFDIMESC and TCONFDIMEFORMQ12.BDCODQDIME = T.BDCODQDIME and TCONFDIMEFORMQ12.BDNUMCAMPODIMEQ12 = T.BDNUMCAMPO) ';

  wsql = wsql||' left outer join vef_estados_tconfdimefq46 TCONFDIMEFORMQ46 on (TCONFDIMEFORMQ46.bdcodconfdimesc = parsc.bdcodconfdimesc and ';
  wsql = wsql||'                                                                TCONFDIMEFORMQ46.bdcodqdime = T.BDCODQDIME and TCONFDIMEFORMQ46.bdnumcampodimeq46 = T.BDNUMCAMPO) ' ;

  wsql = wsql||' left outer join TCIDADE TCID on (tcid.bdcodcid = t.bdcodcid) ';
  wsql = wsql||' left outer join TUF UF on (UF.bdcoduf = T.BDCODUF) ';
  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODQDIME  = '||:prcodquadro;

    END

  IF (:prcodquadroprinc IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'TCONF.BDCODQDIMEPRINC  = '||:prcodquadroprinc;
    END

  IF (:prcodperiodo IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODPERIODO' || ' = '||:prcodperiodo;

    END

--  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, BDCODQDIME, bdcodnat, bdcoduf desc, bdnumitem' ;
  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, bdclassificacao, bdcodnat, bdcoduf desc, bdnumitem' ;

  prrefant   = 0;
  prquadroant = 0;
  prnatant = 0;
  prufant = 0;
  wpodetotuftip6 = 0;
  wpodetotuftip7 = 0;
  PRULTIMOCLASSIFITIT = '';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp,
    bdcodconf,
    BDREFERENCIA,
    BDCODPERIODO,
    BDNUMCAMPO,
    bdcodquadro,
    bdcodquadroprinc,
    bdclassificacao,
    BDDESCQUADRO,
    bddescform,
    bddescformq12, 
    bddescformq46,
    BDVALOR,
    bdcodtipo,
    wcodcid,
    wcodcidtot,
    wnomcid,
    bdcodnat,
    BDDATAREC,
    bdclavendimegerq12,
    bdcodrecdimegerq12,
    bdorigemdimegerq46,
    wcoduf,
    wsiglauf,
    wq12,
    wq46,
    bdnumitem,
    bdNUMACORDOQ12,
    bdcodbenefttd,
    bdvlrbcicms,
    bdvlricmsexon,
    bdordemfumdes,
    bdvlrfumdes,
    bdvlrfumdesdev,
    bdordemfunsoc,
    bdvlrfunsoc,
    bdvlrfunsocdev
  DO
  BEGIN
    bdanomesfinal   = pranomesfinal;
    bdanomesinicial = pranomesinicial;
    wcodnat = bdcodnat;

    IF (bdcodtipo =74 OR bdcodtipo =76) THEN  /* QUADRO 47 E 48 POR CIDADE */
      BEGIN
        IF (wcodcid IS NULL) THEN
          BEGIN
            IF (wcodcidtot = 99999) THEN
               bddescform = '99999 - TOTALIZADOR';
            ELSE
              bddescform = wcodcidtot ||  ' - Outros Estados';
          END
        ELSE
           bddescform = wcodcid || ' - ' || wnomcid;
      END

    IF (wq12 = 'TRUE') THEN   /* verifica o tipo do quadro para ver de onde vai pegar a descrivao da formula. Conf geral, do quadro 12 ou quadro 46 */
      BEGIN
        bddescform = bddescformq12;
      END
    ELSE
      IF (wq46 = 'TRUE') THEN
        BEGIN
          bddescform = bddescformq46;

          IF (BDNUMCAMPO = 990) THEN
             bddescform = 'TOTAL';
        END

    prnumcampo = bdnumcampo;
    prnumitem  = bdnumitem;
    prdescform = bddescform;
    prvalor = bdvalor;

    IF ((prGeral = 1) AND (prrefant <> bdreferencia) AND (pranomesinicial <> pranomesfinal) ) THEN /* mostra a referencia caso esteja consultando varias */
      BEGIN
        bdnumcampo = NULL;
        bdnumitem = NULL;
        BDDESCFORM =  CAST(bdreferencia AS VARCHAR(6));
        bddescform =  SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
        BDVALOR = NULL;
        prrefant = bdreferencia;
        SUSPEND;
      END

    IF ((prGeral = 1) AND (prquadroant <> bdcodquadro)) THEN   /* mostra o nome do quadro atual na consulta */
      BEGIN
        prsalvaquadroant = bdcodquadro;
        prclassifiant = bdclassificacao;
        prdescquadroant = bddescquadro;
        prdatarecantq12 = bddatarec;
        prclavendimegerq12ant = bdclavendimegerq12;
        prcodrecdimegerq12ant = bdcodrecdimegerq12;
        prorigemdimegerq46ant = bdorigemdimegerq46;
        prorigemdimenumacordoq12ant = bdNUMACORDOQ12;
        prcodbenefttdant = bdcodbenefttd;
        prvlrbcicmsant = bdvlrbcicms; /*Q15 */
        prvlricmsexonant = bdvlricmsexon;
        prordemfumdesant = bdordemfumdes;
        prvlrfumdesant = bdvlrfumdes;
        prvlrfumdesdevant = bdvlrfumdesdev;
        prordemfunsocant = bdordemfunsoc;
        prvlrfunsocant = bdvlrfunsoc;
        prvlrfunsocdevant = bdvlrfunsocdev;

        SELECT FIRST 1 tpos.pos FROM pos('.', :bdclassificacao) tpos INTO :waux;

        IF (waux > 1) THEN /* classificacao titulo */
          BEGIN

            wclassifititulo = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);

            IF  (prultimoclassifitit <> wclassifititulo) THEN
              BEGIN

                SELECT x.bdcodqdime, x.bddescqdime FROM VEF_ESTADOS_TCONFDIMEQ x WHERE x.bdclassificacao = :wclassifititulo INTO
                    :bdcodquadro,
                    :bddescform;


                prultimoclassifitit = wclassifititulo;
                bdnumcampo = NULL;
                bdnumitem = NULL;
                BDVALOR = NULL;
                prquadroant = bdcodquadro;
                prufant = 0;
                bdclassificacao = wclassifititulo;
                bddescquadro = bddescform;
                bddatarec = NULL;
                bdclavendimegerq12 = NULL;
                bdcodrecdimegerq12 = NULL;
                bdorigemdimegerq46 = NULL;
                bdNUMACORDOQ12     = NULL;
                bdcodbenefttd = NULL;
                bdvlrbcicms = NULL;
                bdvlricmsexon = NULL;
                bdordemfumdes = NULL;
                bdvlrfumdes = NULL;
                bdvlrfumdesdev = NULL;
                bdordemfunsoc = NULL;
                bdvlrfunsoc = NULL;
                bdvlrfunsocdev = NULL;
                SUSPEND;
                bdclassificacao = prclassifiant;
                bddescquadro = prdescquadroant;
                bdcodquadro = prsalvaquadroant;
              END

          END

        bdnumcampo = NULL;
        bdnumitem = NULL;
        BDDESCFORM = bdclassificacao || ' - ' || BDDESCQUADRO;
        -- BDDESCFORM =  BDDESCQUADRO;
        BDVALOR = NULL;
        bdorigemdimegerq46 = NULL;
        bdclavendimegerq12 = NULL;
        bdcodrecdimegerq12 = NULL;
        bdNUMACORDOQ12     = NULL;
        bdcodbenefttd = NULL;
        bdvlrbcicms = NULL;
        bdvlricmsexon = NULL;
        bdordemfumdes = NULL;
        bdvlrfumdes = NULL;
        bdvlrfumdesdev = NULL;
        bdordemfunsoc = NULL;
        bdvlrfunsoc = NULL;
        bdvlrfunsocdev = NULL;
        bddatarec = NULL;
        prquadroant = bdcodquadro;
        prufant = 0;

        SUSPEND;

        bdorigemdimegerq46 = prorigemdimegerq46ant;
        bdclavendimegerq12 = prclavendimegerq12ant;
        bdcodrecdimegerq12 = prcodrecdimegerq12ant;
        bddatarec = prdatarecantq12;
        bdNUMACORDOQ12 = prorigemdimenumacordoq12ant;
        bdcodbenefttd = prcodbenefttdant;
        bdvlrbcicms = prvlrbcicmsant;
        bdvlricmsexon = prvlricmsexonant;
        bdordemfumdes = prordemfumdesant;
        bdvlrfumdes = prvlrfumdesant;
        bdvlrfumdesdev = prvlrfumdesdevant;
        bdordemfunsoc = prordemfunsocant;
        bdvlrfunsoc = prvlrfunsocant;
        bdvlrfunsocdev = prvlrfunsocdevant;
      END

    IF ((bdcodtipo =2) AND (prnatant <> wcodnat) OR ((bdcodtipo =3) AND (prnatant <> wcodnat)) ) THEN /* mostra a natureza atual na consuta... */
       BEGIN
         bdnumcampo = NULL;
         bdnumitem = NULL;
         bddescform =  SUBSTRING(CAST(wcodnat AS VARCHAR(10)) FROM 1 FOR 1) || '.' || SUBSTRING(CAST(wcodnat AS VARCHAR(10)) FROM 2 FOR 10) ;
         BDVALOR = NULL;
         prnatant = wcodnat;
         SUSPEND;
       END

    --if ((((bdcodtipo =6) and (prufant <> wcoduf))  or ((bdcodtipo =6) and (wcoduf is null)))  and (wpodetotuftip6 = 0)) then /* mostra a sigla do estado atual na consuta... */
    IF ((((bdcodtipo =78) AND (prufant <> wcoduf))  OR ((bdcodtipo =78) AND (wcoduf IS NULL)))  AND (wpodetotuftip6 = 0)) THEN /* mostra a sigla do estado atual na consuta... */
       BEGIN
         bdnumcampo = NULL;
         bdnumitem = NULL;
         IF (wcoduf IS NULL) THEN
           BEGIN
             bddescform =  'TT';
             wpodetotuftip6 = 1;
           END
         ELSE
            bddescform =  wsiglauf;
         BDVALOR = NULL;
         prufant = wcoduf;
         SUSPEND;
       END

    --if ((((bdcodtipo =7) and (prufant <> wcoduf))  or ((bdcodtipo =7) and (wcoduf is null)))  and (wpodetotuftip7 = 0)) then /* mostra a sigla do estado atual na consuta... */
    IF ((((bdcodtipo =80) AND (prufant <> wcoduf))  OR ((bdcodtipo =80) AND (wcoduf IS NULL)))  AND (wpodetotuftip7 = 0)) THEN /* mostra a sigla do estado atual na consuta... */
       BEGIN
         bdnumcampo = NULL;
         bdnumitem = NULL;
         IF (wcoduf IS NULL) THEN
           BEGIN
             bddescform =  'TT';
             wpodetotuftip7 = 1;
           END
         ELSE
            bddescform =  wsiglauf;
         BDVALOR = NULL;
         prufant = wcoduf;
         SUSPEND;
       END

    bdnumcampo = prnumcampo;
    bdnumitem = prnumitem;
    bddescform = prdescform;
    bdvalor = prvalor;

    SUSPEND;

  END

END
^

/* Restore proc. body: SP_VEF_TREEVIEW_CONS_GIAES */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIAES(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODPERIODO INTEGER,
PRCLASSIFICACAO VARCHAR(11),
PRGERAL INTEGER,
PRCODQUADRO INTEGER,
PRTIPOAPU INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDCLASSIFICACAO VARCHAR(11),
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(150),
BDVALOR NUMERIC(15,2),
BDCODTIPO INTEGER,
BDTIPO INTEGER,
BDNUMITEM INTEGER,
BDTIPOAPU INTEGER,
BDCODNAT INTEGER,
BDAUXCFOP INTEGER,
BDORDEMTTNAT INTEGER,
BDCLASSNATGRUP VARCHAR(20),
BDDESCTTNAT VARCHAR(20),
BDTITULOGRUPO VARCHAR(20))
 AS
DECLARE VARIABLE wsql VARCHAR(32700);
DECLARE VARIABLE wwhere VARCHAR(32700);
DECLARE VARIABLE prquadroant INTEGER;
DECLARE VARIABLE prsalvaquadroant INTEGER;
DECLARE VARIABLE wtit INTEGER;
DECLARE VARIABLE prultimoclassifitit VARCHAR(11);
DECLARE VARIABLE wclassifiprinc VARCHAR(11);
DECLARE VARIABLE wclassifititulo VARCHAR(20);
DECLARE VARIABLE prnumcampo INTEGER;
DECLARE VARIABLE prdescform VARCHAR(150);
DECLARE VARIABLE prclassifiant VARCHAR(11);
DECLARE VARIABLE prnatant INTEGER;
DECLARE VARIABLE waux INTEGER;
DECLARE VARIABLE waux2 INTEGER;
DECLARE VARIABLE prvalor NUMERIC(15,2);
DECLARE VARIABLE prrefant INTEGER;
DECLARE VARIABLE wultimoclassifitit VARCHAR(11);
DECLARE VARIABLE prdescquadroant VARCHAR(80);
DECLARE VARIABLE wtipo INTEGER;
DECLARE VARIABLE wprefixonat INTEGER;
DECLARE VARIABLE wauxcfop INTEGER;
DECLARE VARIABLE wordemttnatcompras INTEGER;
DECLARE VARIABLE wordemttnatvendas INTEGER;
DECLARE VARIABLE wnataux INTEGER;
DECLARE VARIABLE wtitulogrupo VARCHAR(20);
DECLARE VARIABLE wclasstitulo VARCHAR(20);
BEGIN


  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql = 'SELECT T.BDCODEMP, ';
  wsql = wsql || ' empAtual.BDNOMEMP, ';
  wsql = wsql || ' pares.BDCODCONFGIAES, ';
  wsql = wsql || ' T.BDREFERENCIA, ';
  wsql = wsql || ' T.BDCODPERIODO, ';
  wsql = wsql || ' T.BDNUMCAMPO, ';
  wsql = wsql || ' T.BDCODQUADRO, ';
  wsql = wsql || ' GIAESQ.BDCLASSIFICACAO, ';
  wsql = wsql || ' GIAESQ.BDDESCQUADRO, ';
  wsql = wsql || ' GIAESF.BDDESCFORM, ';
  wsql = wsql || ' T.BDVALOR BDVALOR, ';
  wsql = wsql || ' GIAESQ.BDCODTIPO, ';
  wsql = wsql || ' GIAESQ.BDTIPO, ';
  wsql = wsql || ' GIAESF.BDNUMITEM, ';
  wsql = wsql || ' T.BDTIPOAPU, ';
  wsql = wsql || ' T.BDPREFIXONAT BDCodNat, ';
  wsql = wsql || ' T.BDAUXCFOP, ';
  wsql = wsql || ' T.bdordemttnat, ';
  wsql = wsql || ' totaises.bdClassnatgrup, ';
  wsql = wsql || ' totaises.bddescttnat, ';
  wsql = wsql || ' null bdtitulogrupo ';

  wsql = wsql || ' FROM vw_vef_emp_tgiaesgerunion T';
  wsql = wsql || ' left outer join VW_EMPRESAS_REF_ATUAL empAtual on (empAtual.bdcodemp = t.bdcodemp) ';
  wsql = wsql || ' left outer join vef_base_tempparestes pares on (pares.bdCodEmp = empAtual.bdCodEmp and pares.bdrefemp = empAtual.bdempref) ';
  wsql = wsql || ' left outer join VEF_ESTADOS_TCONFGIAESQ GIAESQ on (GIAESQ.bdcodquadro = t.bdcodquadro)';
  wsql = wsql || ' left outer join vef_base_ttabtotaisnates TOTAISES on(TOTAISES.bdOrdemttnat = t.bdordemttnat)';
  wsql = wsql || ' left outer join VEF_ESTADOS_TCONFGIAESFORM GIAESF on (GIAESF.bdCodConf = pares.BDCODCONFGIAES and GIAESF.bdCODQUADRO = t.bdCODQUADRO and GIAESF.bdNumcampo = t.bdNumcampo)';

  wwhere = '';

   IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;

   IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';
       ELSE
          wwhere = wwhere || ' WHERE ';

       wwhere = wwhere || ' t.bdreferencia >= ' || :praNomesInicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || ' t.bdreferencia <= ' || :praNomesFinal;
     END

   IF (:prtipoapu IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';
        ELSE
          wwhere = wwhere || ' WHERE ';

        wwhere = wwhere || ' T.BDTIPOAPU = ' || :prtipoapu;
      END
   IF (prClassificacao IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere || ' and ';
        ELSE
           wwhere = wwhere || ' WHERE ';

        wwhere = wwhere || ' GIAESQ.bdclassificacao LIKE ''' ||:PRCLASSIFICACAO||'%''';
      END
   IF (:prcodperiodo IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere || ' and ';
        ELSE
           wwhere = wwhere || ' WHERE ';

        wwhere = wwhere || ' t.bdCODPERIODO ' || ' = ' || :prcodperiodo;
       END
   IF (:prcodquadro IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere || ' and ';
        ELSE
           wwhere = wwhere || ' WHERE ';

      wwhere = wwhere || ' GIAESQ.BDCODQUADRO' || ' = ' ||:prcodquadro;
      END


   wsql = wsql || wwhere || ' order by bdcodemp, bdreferencia desc, BDCODQUADRO,bdcodnat,totaises.bdClassnatgrup,t.bdnumcampo';

   prRefant = 0;
   prquadroant = 0;
   prnatant = 0;
   wTit = 0;
   PRULTIMOCLASSIFITIT = '';
   WCLASSIFIPRINC = '';
   wTIT = 1;
   wordemttnatcompras = NULL;
   wordemttnatvendas = NULL;
   wtitulogrupo = NULL;
   wclasstitulo = '';

   FOR EXECUTE STATEMENT wsql
   INTO
     BDCODEMP,
     BDNOMEMP,
     BDCODCONF,
     BDREFERENCIA,
     BDCODPERIODO,
     BDNUMCAMPO,
     BDCODQUADRO,
     bdclassificacao,
     bddescquadro,
     BDDESCFORM,
     BDVALOR,
     BDCODTIPO,
     BDTIPO,
     BDNUMITEM,
     BDTIPOAPU,
     BDCODNAT,
     BDAUXCFOP,
     bdordemttnat,
     bdclassnatgrup,
     bddescttnat,
     bdtitulogrupo

   DO
   BEGIN
   wnataux = 0;
   wprefixonat = bdcodnat;
   prNumCampo = BDNumcampo;
   prDescForm = BDDESCFORM;
   prValor = bdValor;
   wauxcfop = NULL;

   IF ((wtitulogrupo IS NULL) OR (wtitulogrupo <> bdtitulogrupo) OR (wclasstitulo <> SUBSTRING(bdclassificacao FROM 1 FOR 2)))  THEN
      BEGIN
         wclasstitulo = SUBSTRING(bdclassificacao FROM 1 FOR 2);
         SELECT FIRST 1 bddescquadro FROM VEF_ESTADOS_TCONFGIAESQ tit WHERE tit.bdtipo = 0 AND tit.bdclassificacao = SUBSTRING(:bdclassificacao FROM 1 FOR 2) INTO :wtitulogrupo;
      END

   bdtitulogrupo = wtitulogrupo;

   IF ((prgeral = 1) AND (prRefAnt <> bdReferencia) AND (praNomesInicial <> praNomesFinal)) THEN
      BEGIN
        bdNumCampo = NULL;
        BDDESCFORM = CAST(bdreferencia AS VARCHAR(6));
        bddescform = SUBSTRING(bddescform FROM 5 FOR 2) || '/' ||SUBSTRING(bddescform FROM 1 FOR 4);
        bdvalor = NULL;
        prRefant = bdreferencia;
        SUSPEND;
      END
    IF ((prgeral = 1) AND (bdcodquadro <> prquadroant)) THEN
       BEGIN
         prsalvaquadroant = bdcodquadro;
         prclassifiant = bdclassificacao;
         prdescquadroant = bddescquadro;

         IF (wPrefixoNat IS NULL) THEN
            BEGIN
              SELECT FIRST 1 tPos.BDRPOS FROM rpos('.', :bdclassificacao) tpos INTO :wAUX;

              IF ((wclassifiprinc = '') AND (wAux > 1)) THEN
                 BEGIN
                   wClassifiprinc = SUBSTRING(bdClassificacao FROM 1 FOR waux-1);
                   wtit = 1;
                 END
              ELSE
                 BEGIN
                   IF (wClassifiprinc = SUBSTRING(bdClassificacao FROM 1 FOR waux-1)) THEN
                      BEGIN
                        wtit = 0;
                      END
                   ELSE
                      BEGIN
                        wtit = 1;
                      END
                   IF (waux > 1) THEN
                      BEGIN
                        wClassifiprinc = SUBSTRING(bdClassificacao FROM 1 FOR waux-1);
                      END
                 END
            END
         ELSE
            BEGIN
              SELECT FIRST 1 tpos.pos FROM pos('.' , :Bdclassificacao) tpos INTO :waux;
              wtit = 1;
              wclassifititulo = '';
            END

         IF (waux > 1) THEN
            BEGIN

              IF (wprefixonat IS NULL) THEN
                 BEGIN
                   SELECT FIRST 1 tpos.pos FROM pos('.' , :bdClassificacao) tpos INTO :waux2;

                   wclassifiprinc = SUBSTRING(bdclassificacao FROM 1 FOR waux2-1);

                   SELECT FIRST 1 tpos.pos FROM pos('.' , :prUltimoClassifiTit) tpos INTO :waux2;

                   IF (waux2 > 0) THEN
                      BEGIN
                        wUltimoClassifiTit = SUBSTRING(prUltimoClassifiTit FROM 1 FOR waux2-1);
                      END
                   ELSE
                      BEGIN
                        wultimoclassifitit = prultimoclassifitit;
                      END
                  IF ((wUltimoclassifitit <> wclassifititulo) AND (wTit = 1)) THEN
                      BEGIN
                        SELECT Q.bdcodquadro, Q.bdDescQuadro FROM VEF_ESTADOS_TCONFGIAESQ Q WHERE Q.bdclassificacao = :wclassifititulo
                        INTO :bdcodquadro, :bddescform;

                        prultimoclassifitit = wClassifiTitulo;
                        bdNUmcampo = NULL;
                        bdValor = NULL;
                        prquadroant = bdCodQuadro;
                        bdclassificacao = wClassifiTitulo;
                        bddescquadro = bddescform;
                        wTipo = BDTipo;
                        bdTipo = 0;
                        bdcodnat = NULL;

                        SUSPEND;
                        bdclassificacao = prClassifiAnt;
                        bdcodquadro = prSalvaQuadroAnt;
                        bdDescQuadro = prDescQuadroAnt;
                        bdTipo = wTipo;
                        bdcodnat = NULL;
                      END
                 END

            wClassifiTitulo = SUBSTRING(bdClassificacao FROM 1 FOR waux-1);

            IF ((prUltimoClassifiTit <> wClassifiTitulo) AND (wTit = 1)) THEN
               BEGIN
                 SELECT Q.bdcodquadro, Q.bdDescQuadro FROM VEF_ESTADOS_TCONFGIAESQ Q WHERE Q.bdclassificacao = :wclassifititulo
                 INTO :bdcodquadro, :bddescform;
                 
                 prultimoclassifitit = wClassifiTitulo;
                 bdNUmcampo = NULL;
                 bdValor = NULL;
                 prquadroant = bdCodQuadro;
                 bdclassificacao = wClassifiTitulo;
                 bddescquadro = bddescform;
                 wTipo = BDTipo;
                 bdTipo = 0;

                 SUSPEND;
                 bdclassificacao = prClassifiAnt;
                 bdcodquadro = prSalvaQuadroAnt;
                 bdDescQuadro = prDescQuadroAnt;
                 bdTipo = wTipo;
               END
            END

         bdNUmcampo = NULL;
         BDDESCFORM = bdclassificacao || ' - ' || bddescquadro;
         bdvalor = NULL;
         prquadroant = bdcodquadro;

         SUSPEND;
       END

     IF (((bdcodtipo = 202) OR (bdcodtipo = 203) OR (bdcodtipo = 204)) AND ((wordemttnatcompras <> bdordemttnat) OR (wordemttnatcompras IS NULL) )) THEN     -- Naturezas de Entrada
        BEGIN
          wauxcfop = 1;
          bdnumcampo = NULL;
          bddescform = bddescttnat || ' ' || bdclassnatgrup ;
          bdclassificacao = bdclassnatgrup;
          bdvalor = NULL;
          bdauxcfop = wauxcfop;
          SUSPEND;
        END

     wordemttnatcompras = bdordemttnat;

     IF (((bdcodtipo = 205) OR (bdcodtipo = 206) OR (bdcodtipo = 207)) AND ((wordemttnatvendas <> bdordemttnat) OR (wordemttnatvendas IS NULL))) THEN   -- Naturezas de saida
        BEGIN
          wauxcfop = 1;
          bdnumcampo = NULL;
          bddescform = bddescttnat || ' ' || bdclassnatgrup ;
          bdclassificacao = bdclassnatgrup;
          bdvalor = NULL;
          bdauxcfop = wauxcfop;
          SUSPEND;
        END

     IF ((bdcodtipo = 202) OR (bdcodtipo = 203) OR (bdcodtipo = 204)) THEN
        wordemttnatvendas = NULL;
     ELSE
        wordemttnatvendas = bdordemttnat;


     IF ((bdcodtipo = 210) AND (prNatAnt <> wprefixonat) OR ((bdCodTipo = 211) AND (prNatAnt <> wprefixonat))) THEN
        BEGIN
          wauxcfop = 1;
          bdNumCampo = NULL;
          bddescForm = SUBSTRING(CAST(wprefixonat AS VARCHAR(10)) FROM 1 FOR 1) || '.' || SUBSTRING(CAST(wprefixonat AS VARCHAR(10)) FROM 2 FOR 3);
          bdValor = NULL;
          prnatAnt = wprefixonat;
          bdauxcfop = wauxcfop;
          SUSPEND;
        END

     IF (wnataux <> 0) THEN
        BEGIN
          SUSPEND;
        END


    bdnumcampo = prnumcampo;
    bddescform = /*'['||cast(BDNUMITEM as varchar(3))||'] - '||*/prdescform;
    bdvalor = prvalor;
    bdauxcfop = NULL;
    prtipoapu = bdtipoapu;
    SUSPEND;

  END

END
^

/* Restore proc. body: SP_VEF_TREEVIEW_CONS_GIAMG */
CREATE OR ALTER procedure SP_VEF_TREEVIEW_CONS_GIAMG (
    PRCODEMP varchar(10000),
    PRANOMESINICIAL integer,
    PRANOMESFINAL integer,
    PRCODPERIODO integer,
    PRCLASSIFICACAO varchar(11),
    PRGERAL integer,
    PRCODQUADRO integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCONF integer,
    BDREFERENCIA integer,
    BDCODPERIODO integer,
    BDNUMCAMPO integer,
    BDCODQUADRO integer,
    BDCLASSIFICACAO varchar(11),
    BDDESCQUADRO varchar(80),
    BDDESCFORM varchar(150),
    BDVALOR numeric(15,2),
    BDCODTIPO integer,
    BDCODNAT integer,
    BDTIPO integer,
    BDNUMITEMORDEM varchar(5),
    BDNUMITEM varchar(5))
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable PRREFANT integer;
declare variable PRQUADROANT integer;
declare variable PRSALVAQUADROANT integer;
declare variable PRNATANT integer;
declare variable PRCLASSIFIANT varchar(11);
declare variable PRDESCQUADROANT varchar(80);
declare variable PRULTIMOCLASSIFITIT varchar(11);
declare variable PRNUMCAMPO integer;
declare variable PRDESCFORM varchar(60);
declare variable PRVALOR numeric(15,6);
declare variable WPREFIXONAT integer;
declare variable WCLASSIFITITULO varchar(11);
declare variable WCLASSIFIPRINC varchar(11);
declare variable WAUX integer;
declare variable WAUX2 integer;
declare variable WTIT integer;
declare variable WTIPO integer;
declare variable WULTIMOCLASSIFITIT varchar(11);
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql || 'empresas2.BDNOMEMP, ';
  wsql = wsql || 'parmg.BDCODCONFGIAMG,';
  wsql = wsql || 'T.BDREFERENCIA, ';
  wsql = wsql || 'T.BDCODPERIODO, ';
  wsql = wsql || 'T.BDNUMCAMPO, ';
  wsql = wsql || 'T.BDCODQUADRO,';
  wsql = wsql || 'TCONF.bdclassificacao, ';
  wsql = wsql || 'TCONF.bddescquadro,';
  wsql = wsql || 'TCONFGIAMGFORM.bddescform,';
  wsql = wsql || 'T.BDVALOR BDVALOR, ';
  wsql = wsql || 'TCONF.bdcodtipo, ';
  wsql = wsql || 'T.BDPREFIXONAT BDCODNAT, ';
  wsql = wsql || 'TCONF.bdtipo, ';
  wsql = wsql || 'Lpad(TCONFGIAMGFORM.BDNUMITEM, 3, ''0'')||SUBSTRING(TCONFGIAMGFORM.BDNUMITEM FROM 4 FOR 2 ) BDNUMITEMORDEM, ';
  wsql = wsql || 'TCONFGIAMGFORM.BDNUMITEM';

  wsql = wsql || ' from VW_VEF_EMP_TGIAMGGERUNION T';

--  wsql = wsql||' left outer join VW_EMP_REF_TOTAL empresas on (empresas.bdcodemp = t.bdcodemp ) ';
--  wsql = wsql||' left outer join VW_EMPRESAS_REF_ATUAL empresas2 on (empresas2.bdcodemp = t.bdcodemp) ';
  wsql = wsql||' left outer join (select v.bdcodemp,v.bdrefemp BDEMPREF,e.bdnomemp ';
  wsql = wsql||'                  from VW_TEMPRESAS_REF_MAX_MIN v ';
  wsql = wsql||'                  left outer join tempresas_ref e on (v.bdcodemp = e.bdcodemp and v.bdrefemp = e.bdrefemp) ';
  wsql = wsql||'                   ) EMPRESAS2 on (EMPRESAS2.BDCODEMP = T.BDCODEMP) ';
  wsql = wsql||' left outer join VEF_BASE_TEMPPARESTMG parmg on (parmg.bdcodemp = empresas2.bdcodemp and parmg.bdrefemp = empresas2.BDEMPREF) ';
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFGIAMGQ TCONF on (TCONF.bdcodquadro = t.bdcodquadro) ' ;
  wsql = wsql||' LEFT OUTER JOIN (SELECT t.BDDESCFORM, t.BDCODCONF, t.BDCODQUADRO, t.BDNUMCAMPO, ';
  wsql = wsql||'                         IIF((t.BDNUMITEM is null) or (t.BDNUMITEM = ''''), ''0'', t.BDNUMITEM) BDNUMITEM '; -- Alt.: #130006 - Estava com problema ao carregar as treeview da apuracao, pois tentava converter um campo vazio em integer...
  wsql = wsql||'                  FROM VEF_ESTADOS_TCONFGIAMGFORM t) TCONFGIAMGFORM on (TCONFGIAMGFORM.bdcodconf = parmg.BDCODCONFGIAMG and TCONFGIAMGFORM.bdcodquadro = T.BDCODQUADRO and TCONFGIAMGFORM.bdnumcampo = T.BDNUMCAMPO) ' ;
  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

  IF (PRCLASSIFICACAO IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       --wwhere = wwhere||'T.BDCODQUADRO  = '||:prcodquadro;
       --wwhere = wwhere||'TCONF.bdclassificacao LIKE ''0'||:prcodquadro||'%''';
       wwhere = wwhere||'TCONF.bdclassificacao LIKE '''||:PRCLASSIFICACAO||'%''';
    END

  IF (:prcodperiodo IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODPERIODO' || ' = '||:prcodperiodo;

    END

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'TCONF.BDCODQPRINC' || ' = '||:prcodquadro;

    END

  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, BDCODQUADRO, BDCODNAT, cast(TCONFGIAMGFORM.BDNUMITEM as numeric(10,2))' ;

  prrefant   = 0;
  prquadroant = 0;
  prnatant = 0;
  PRULTIMOCLASSIFITIT = '';
  WCLASSIFIPRINC = '';
  WTIT = 1;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDNOMEMP ,
    BDCODCONF ,
    BDREFERENCIA ,
    BDCODPERIODO ,
    BDNUMCAMPO ,
    BDCODQUADRO,
    BDCLASSIFICACAO ,
    BDDESCQUADRO ,
    BDDESCFORM ,
    BDVALOR ,
    BDCODTIPO,
    BDCODNAT,
    BDTIPO,
    BDNUMITEMORDEM,
    BDNUMITEM
  DO
  BEGIN

    wPREFIXONAT = BDCODNAT;

    prnumcampo = bdnumcampo;
    prdescform = bddescform;
    prvalor = bdvalor;

    IF ((prGeral = 1) AND (prrefant <> bdreferencia) AND (pranomesinicial <> pranomesfinal) ) THEN -- mostra a referencia caso esteja consultando varias
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  CAST(bdreferencia AS VARCHAR(6));
        bddescform =  SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
        BDVALOR = NULL;
        prrefant = bdreferencia;
        SUSPEND;
      END

    IF ((prGeral = 1) AND (prquadroant <> bdcodquadro)) THEN   -- mostra o nome do quadro atual na consulta
      BEGIN
        prsalvaquadroant = bdcodquadro;
        prclassifiant = bdclassificacao;
        prdescquadroant = bddescquadro;

        IF (wPREFIXONAT IS NULL) THEN
           BEGIN
             SELECT FIRST 1 tpos.BDRPOS FROM rpos('.',  :bdclassificacao) tpos INTO :waux;

             IF ((WCLASSIFIPRINC = '') AND (waux > 1)) THEN
                BEGIN
                   WCLASSIFIPRINC = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);
                   WTIT = 1;
                END
             ELSE
                BEGIN
                  IF (WCLASSIFIPRINC = SUBSTRING(bdclassificacao FROM 1 FOR waux-1)) THEN
                     BEGIN
                        WTIT = 0;
                     END
                  ELSE
                     BEGIN
                        WTIT = 1;
                     END
    
                  IF (waux > 1) THEN
                     WCLASSIFIPRINC = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);
                END
           END
        ELSE
           BEGIN
             SELECT FIRST 1 tpos.pos FROM pos('.', :bdclassificacao) tpos INTO :waux;
             WTIT = 1;
             WCLASSIFIPRINC = '';
           END

        IF (waux > 1) THEN -- classificacao titulo
          BEGIN

            IF (wPREFIXONAT IS NULL) THEN
               BEGIN
                SELECT FIRST 1 tpos.pos FROM pos('.', :bdclassificacao) tpos INTO :waux2;
    
                wclassifititulo = SUBSTRING(bdclassificacao FROM 1 FOR waux2-1);
    
                SELECT FIRST 1 tpos.pos FROM pos('.', :prultimoclassifitit) tpos INTO :waux2;

                IF (waux2 > 0) THEN
                   wultimoclassifitit = SUBSTRING(prultimoclassifitit FROM 1 FOR waux2-1);
                ELSE
                   wultimoclassifitit = prultimoclassifitit;
    
                IF ((wultimoclassifitit <> wclassifititulo) AND (WTIT = 1)) THEN
                  BEGIN
    
                    SELECT x.bdcodquadro, x.bddescquadro FROM VEF_ESTADOS_TCONFGIAMGQ x WHERE x.bdclassificacao = :wclassifititulo INTO
                        :bdcodquadro,
                        :bddescform;
    
                    prultimoclassifitit = wclassifititulo;
                    bdnumcampo = NULL;
                    BDVALOR = NULL;
                    prquadroant = bdcodquadro;
                    bdclassificacao = wclassifititulo;
                    bddescquadro = bddescform;
                    WTIPO = BDTIPO;
                    BDTIPO = 0;
    
                    SUSPEND;
                    bdclassificacao = prclassifiant;
                    bddescquadro = prdescquadroant;
                    bdcodquadro = prsalvaquadroant;
                    BDTIPO = WTIPO;
                  END
               END

            wclassifititulo = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);

            IF ((prultimoclassifitit <> wclassifititulo) AND (WTIT = 1)) THEN
              BEGIN

                SELECT x.bdcodquadro, x.bddescquadro FROM VEF_ESTADOS_TCONFGIAMGQ x WHERE x.bdclassificacao = :wclassifititulo INTO
                    :bdcodquadro,
                    :bddescform;

                prultimoclassifitit = wclassifititulo;
                bdnumcampo = NULL;
                BDVALOR = NULL;
                prquadroant = bdcodquadro;
                bdclassificacao = wclassifititulo;
                bddescquadro = bddescform;
                WTIPO = BDTIPO;
                BDTIPO = 0;

                SUSPEND;
                bdclassificacao = prclassifiant;
                bddescquadro = prdescquadroant;
                bdcodquadro = prsalvaquadroant;
                BDTIPO = WTIPO;
              END

          END

        bdnumcampo = NULL;
        BDDESCFORM = bdclassificacao || ' - ' || BDDESCQUADRO;
        -- BDDESCFORM =  BDDESCQUADRO;
        BDVALOR = NULL;
        prquadroant = bdcodquadro;

        SUSPEND;

      END

    IF ((bdcodtipo =116) AND (prnatant <> wPREFIXONAT) OR ((bdcodtipo =149) AND (prnatant <> wPREFIXONAT)) ) THEN -- mostra a natureza atual na consuta...
       BEGIN
         bdnumcampo = NULL;
         bddescform =  SUBSTRING(CAST(wPREFIXONAT AS VARCHAR(10)) FROM 1 FOR 1) || '.' || SUBSTRING(CAST(wPREFIXONAT AS VARCHAR(10)) FROM 2 FOR 3);
         BDVALOR = NULL;
         prnatant = wPREFIXONAT;
         SUSPEND;
       END

    bdnumcampo = prnumcampo;
    bddescform = '['||BDNUMITEM||'] - '||prdescform;
    bdvalor = prvalor;

    SUSPEND;


  END

END
^

/* Restore proc. body: SP_VEF_TREEVIEW_CONS_GIAPR */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIAPR (
    PRCODEMP VARCHAR(10000),
    PRANOMESINICIAL INTEGER,
    PRANOMESFINAL INTEGER,
    PRCODPERIODO INTEGER,
    PRCLASSIFICACAO VARCHAR(11),
    PRGERAL INTEGER,
    PRCODQUADRO INTEGER,
    PRCODNAT INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCONF INTEGER,
    BDREFERENCIA INTEGER,
    BDCODPERIODO INTEGER,
    BDNUMCAMPO INTEGER,
    BDCODQUADRO INTEGER,
    BDCLASSIFICACAO VARCHAR(10),
    BDDESCQUADRO VARCHAR(80),
    BDDESCFORM VARCHAR(150),
    BDVALOR NUMERIC(15,2),
    BDCODTIPO INTEGER,
    BDCODNAT INTEGER,
    BDTIPO INTEGER,
    BDNUMITEM INTEGER)
AS
DECLARE VARIABLE WWHEREQUADRO VARCHAR(1000);
DECLARE VARIABLE WREFBETWEEN VARCHAR(100);
DECLARE VARIABLE WCONDICAONATUREZA VARCHAR(100);
DECLARE VARIABLE WINNERSELECT VARCHAR(1000);
DECLARE VARIABLE WSQL BLOB SUB_TYPE 1 SEGMENT SIZE 16384;
DECLARE VARIABLE WREFANT INTEGER;
DECLARE VARIABLE WCODQUADROANT INTEGER;
DECLARE VARIABLE WPOSPONTO INTEGER;
DECLARE VARIABLE WCLASSIFICACAOTITULO VARCHAR(10);
DECLARE VARIABLE WCLASSIFICACAOTITULOANT VARCHAR(10);
DECLARE VARIABLE WCLASSIFICACAOTITULO2 VARCHAR(10);
DECLARE VARIABLE WCLASSIFICACAOTITULO2ANT VARCHAR(10);
DECLARE VARIABLE WCLASSIFICACAOANALITICA VARCHAR(10);
DECLARE VARIABLE WCLASSIFICACAOANALITICAANT VARCHAR(10);
DECLARE VARIABLE WQTDPONTOS INTEGER;
DECLARE VARIABLE WCODQUADROSALVO INTEGER;
DECLARE VARIABLE WCODTIPOSALVO INTEGER;
DECLARE VARIABLE WDESCQUADROSALVO VARCHAR(80);
DECLARE VARIABLE WCLASSIFICACAOSALVO VARCHAR(10);
DECLARE VARIABLE WTIPOSALVO INTEGER;
DECLARE VARIABLE WNUMCAMPOSALVO INTEGER;
DECLARE VARIABLE WDESCFORMSALVO VARCHAR(150);
DECLARE VARIABLE WVALORSALVO NUMERIC(15,2);
DECLARE VARIABLE WNUMITEMSALVO INTEGER;
DECLARE VARIABLE WIMPRIMIRNOMEQUADROANALITICO INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  /* inicializa com uma string vazia */
  wSql              = '';
  wInnerSelect      = '';
  wRefBetween       = '';
  wWhereQuadro      = '';
  wCondicaoNatureza = '';

  /* adiciona condição da empresa */
  IF ((:PRCODEMP IS NOT NULL) AND (:PRCODEMP <> '')) THEN
    BEGIN
      wInnerSelect = :wInnerSelect || :PRCODEMP;
    END

  /* adiciona a condição do código do periodo */
  IF (:PRCODPERIODO > 0) THEN
    BEGIN
      IF (:wInnerSelect <> '') THEN
        BEGIN
          wInnerSelect = :wInnerSelect || ' and ';
        END 

      wInnerSelect = :wInnerSelect || 'bdCodPeriodo = ' || :PRCODPERIODO;
    END 

  /* adiciona a condição da referencia */
  IF ((:PRANOMESINICIAL > 0) OR (:PRANOMESFINAL > 0)) THEN
    BEGIN
      wRefBetween = 'bdreferencia between ';

      IF (:PRANOMESINICIAL > 0) THEN
        BEGIN
          wRefBetween = :wRefBetween || :PRANOMESINICIAL;
        END 
      ELSE
        BEGIN
          wRefBetween = :wRefBetween || :PRANOMESFINAL;
        END

      wRefBetween = :wRefBetween || ' and ';

      IF (:PRANOMESFINAL > 0) THEN
        BEGIN
          wRefBetween = :wRefBetween || :PRANOMESFINAL;
        END
      ELSE
        BEGIN
          wRefBetween = :wRefBetween || :PRANOMESINICIAL;
        END

      IF (:wInnerSelect <> '') THEN
        BEGIN
          wInnerSelect = :wInnerSelect || ' and ';
        END 

      wInnerSelect = :wInnerSelect || :wRefBetween;
    END 

  IF (:wInnerSelect <> '') THEN
    BEGIN
      wInnerSelect = ' where ' || :wInnerSelect;
    END 

  wInnerSelect = ' select bdcodemp, bdcodperiodo, bdreferencia from vef_emp_tgiaprger ' || :wInnerSelect;

  /* condição classificação do quadro (usado no join) */
  IF ((:PRCLASSIFICACAO IS NOT NULL) AND (:PRCLASSIFICACAO <> '')) THEN
    BEGIN
      wWhereQuadro = ' and Q.bdclassificacao like '''|| :PRCLASSIFICACAO ||'%''';
    END 

  IF ((:PRCODQUADRO IS NOT NULL) AND (:PRCODQUADRO > 0))  THEN
    BEGIN
      IF (:wWhereQuadro <> '') THEN
        BEGIN
          wWhereQuadro = :wWhereQuadro || ' and ';
        END 

      wWhereQuadro = :wWhereQuadro || ' Q.bdcodquadro = ' || :PRCODQUADRO;
    END 

  /* condição da natureza de operação */
  IF ((:PRCODNAT IS NOT NULL) AND (:PRCODNAT > 0)) THEN
    BEGIN
      wCondicaoNatureza = ' and nat.bdprefixonat = ' || :PRCODNAT;
    END 

  wSql = wSql || ' select T.bdcodemp, ';
  wSql = wSql || '        E.bdnomemp, ';
  wSql = wSql || '        P.bdcodconfgiapr, ';
  wSql = wSql || '        T.bdreferencia, ';
  wSql = wSql || '        T.bdcodperiodo, ';
  wSql = wSql || '        T.bdnumcampo, ';
  wSql = wSql || '        T.bdcodquadro, ';
  wSql = wSql || '        Q.bdclassificacao, ';
  wSql = wSql || '        Q.bddescquadro, ';
  wSql = wSql || '        F.bddescform, ';
  wSql = wSql || '        T.bdvalor , ';
  wSql = wSql || '        Q.bdcodtipo, ';
  wSql = wSql || '        T.bdprefixonat BDCODNAT, ';
  wSql = wSql || '        Q.bdtipo, ';
  wSql = wSql || '        F.bdnumitem ';
  wSql = wSql || ' from ';
  wSql = wSql || ' ( ';
  wSql = wSql || '     select ger.bdcodemp   , ger.bdcodperiodo, ger.bdreferencia,  ';
  wSql = wSql || '            nat.bdcodquadro, nat.bdnumcampo  , min(nat.bdprefixonat) BDPREFIXONAT, ';
  wSql = wSql || '            sum(coalesce(nat.bdvalor,  0)) "BDVALOR" ';
  wSql = wSql || '     from (' || :wInnerSelect || ') ger ';
  wSql = wSql || '     left outer join vef_emp_tgiaprgernat nat on nat.bdcodemp = ger.bdcodemp and nat.bdcodperiodo = ger.bdcodperiodo and nat.bdreferencia = ger.bdreferencia ' || :wCondicaoNatureza;
  wSql = wSql || '     group by ger.bdcodemp, ger.bdcodperiodo, ger.bdreferencia, nat.bdcodquadro, nat.bdnumcampo';
  wSql = wSql || '     union ';
  wSql = wSql || '     select ger.bdcodemp   , ger.bdcodperiodo, ger.bdreferencia, ';
  wSql = wSql || '            reg.bdcodquadro, reg.bdnumcampo  , null            , ';
  wSql = wSql || '            reg.bdvalor ';
  wSql = wSql || '     from (' || :wInnerSelect || ') ger ';
  wSql = wSql || '     left outer join vef_emp_tgiaprgerreg reg on reg.bdcodemp = ger.bdcodemp and reg.bdcodperiodo = ger.bdcodperiodo and reg.bdreferencia = ger.bdreferencia ';
  wSql = wSql || ' ) T ';
  wSql = wSql || ' inner join VEF_ESTADOS_TCONFGIAPRQ Q on (Q.bdcodquadro = t.bdcodquadro) ' || :wWhereQuadro;
  --wSql = wSql || ' left outer join VW_TEMPRESAS_REF_ATUAL E on (E.bdcodemp = T.bdcodemp) ';
  wsql = wsql || ' left outer join (select v.bdcodemp,v.bdrefemp BDEMPREF,e.bdnomemp ';
  wsql = wsql || '                  from VW_TEMPRESAS_REF_MAX_MIN v ';
  wsql = wsql || '                  left outer join tempresas_ref e on (v.bdcodemp = e.bdcodemp and v.bdrefemp = e.bdrefemp) ';
  wsql = wsql || '                   ) E on (E.bdcodemp = T.bdcodemp) ';
  wSql = wSql || ' left outer join VW_VEF_BASE_TEMPPARESTPR P on (P.bdcodemp = E.bdcodemp) ';
  wSql = wSql || ' left outer join VEF_ESTADOS_TCONFGIAPRFORM F on (F.bdcodconf = P.bdcodconfgiapr) and (F.bdcodquadro = T.BDCODQUADRO) and (F.bdnumcampo = T.bdnumcampo) ';

  /* inicializa variaveis de controle */
  wRefAnt                    = 0;
  wCodQuadroAnt              = 0;
  wClassificacaoTitulo       = '';
  wClassificacaoTituloAnt    = '';
  wClassificacaoTitulo2      = '';
  wClassificacaoTitulo2Ant   = '';
  wClassificacaoAnalitica    = '';
  wClassificacaoAnaliticaAnt = '';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCONF,
    :BDREFERENCIA,
    :BDCODPERIODO,
    :BDNUMCAMPO,
    :BDCODQUADRO,
    :BDCLASSIFICACAO,
    :BDDESCQUADRO,
    :BDDESCFORM,
    :BDVALOR,
    :BDCODTIPO,
    :BDCODNAT,
    :BDTIPO,
    :BDNUMITEM
  DO
    BEGIN
      /* variável de controle para verificar se precisa ou não imprimir o nome do quadro analitico */
      wImprimirNomeQuadroAnalitico = 0;

      /* salva valores dos registro em variaveis para restaurar depois */
      wCodQuadroSalvo     = :BDCODQUADRO;
      wCodTipoSalvo       = :BDCODTIPO;
      wDescQuadroSalvo    = :BDDESCQUADRO;
      wClassificacaoSalvo = :BDCLASSIFICACAO;
      wTipoSalvo          = :BDTIPO;
      wNumCampoSalvo      = :BDNUMCAMPO;
      wDescFormSalvo      = :BDDESCFORM;
      wValorSalvo         = :BDVALOR;
      wNumItemSalvo       = :BDNUMITEM;

--      wPrefixoNat = :bdcodnat;

      /* mostra a referencia na consulta */
      IF ((:PRGERAL = 1) AND (:PRANOMESINICIAL <> :PRANOMESFINAL) AND (:BDREFERENCIA <> :wRefAnt)) THEN
        BEGIN
          BDCODQUADRO = 0; /* para ordenação das referencias */
          BDVALOR     = NULL;
          BDNUMCAMPO  = NULL;
          BDNUMITEM   = NULL;
          BDDESCFORM  = CAST(:BDREFERENCIA AS VARCHAR(6));
          BDDESCFORM  = SUBSTRING(:BDDESCFORM FROM 5 FOR 2) || '/' || SUBSTRING(:BDDESCFORM FROM 1 FOR 4);

          SUSPEND;

          wRefAnt = :BDREFERENCIA;
          wImprimirNomeQuadroAnalitico = 1;
        END 

      /* mostra o nome do quadro na consulta */
      IF ((:PRGERAL = 1) AND (:BDCODQUADRO <> :wCodQuadroAnt))  THEN
        BEGIN
          SELECT p.pos FROM pos('.', :wClassificacaoSalvo) p INTO :wPosPonto;

          wClassificacaoTitulo = LEFT(:wClassificacaoSalvo, (:wPosPonto - 1));

          /* se mudou o título, mostra qual o título atual na consulta */
          IF (:wClassificacaoTitulo <> :wClassificacaoTituloAnt) THEN
            BEGIN
              SELECT q.bdcodquadro, q.bdcodtipo, q.bddescquadro, q.bdclassificacao, q.bdtipo
              FROM vef_estados_tconfgiaprq q WHERE (q.bdclassificacao = :wClassificacaoTitulo) AND (q.bdtipo = 0)
              INTO :BDCODQUADRO, :BDCODTIPO, :BDDESCQUADRO, :BDCLASSIFICACAO, :BDTIPO;

              BDVALOR    = NULL;
              BDNUMCAMPO = NULL;
              BDNUMITEM  = NULL;
              BDDESCFORM = :wClassificacaoTitulo || ' - ' || :BDDESCQUADRO;

              SUSPEND;

              wClassificacaoTituloAnt = :wClassificacaoTitulo;
              wImprimirNomeQuadroAnalitico = 1;
            END 

          /* verifica agora, se o registro atual possui mais de um título */
          SELECT cc.contar_char FROM contar_char(:wClassificacaoSalvo, '.') cc INTO :wQtdPontos;

          /* Exemplo: 08.01.01 */
          IF (:wQtdPontos > 1) THEN
            BEGIN
              SELECT (p.pos + :wPosPonto) FROM pos('.', SUBSTRING(:wClassificacaoSalvo FROM (:wPosPonto + 1) FOR (CHAR_LENGTH(:wClassificacaoSalvo)-:wPosPonto))) p INTO :wPosPonto;

              wClassificacaoTitulo2 = LEFT(:wClassificacaoSalvo, (:wPosPonto - 1));

              /* se mudou o título de segundo nível, mostra ele na consulta */
              IF (:wClassificacaoTitulo2 <> :wClassificacaoTitulo2Ant) THEN
                BEGIN
                  SELECT q.bdcodquadro, q.bdcodtipo, q.bddescquadro, q.bdclassificacao, q.bdtipo
                  FROM vef_estados_tconfgiaprq q WHERE (q.bdclassificacao = :wClassificacaoTitulo2) AND (q.bdtipo = 0)
                  INTO :BDCODQUADRO, :BDCODTIPO, :BDDESCQUADRO, :BDCLASSIFICACAO, :BDTIPO;

                  BDVALOR = NULL;
                  BDNUMCAMPO = NULL;
                  BDNUMITEM  = NULL;
                  BDDESCFORM = :wClassificacaoTitulo2 || ' - ' || :BDDESCQUADRO;

                  SUSPEND;

                  wClassificacaoTitulo2Ant = :wClassificacaoTitulo2;
                  wImprimirNomeQuadroAnalitico = 1;
                END
            END 

          /* quadro analitico */
          SELECT rp.bdrpos FROM rpos('.', :wClassificacaoSalvo) rp INTO :wPosPonto;

          wClassificacaoAnalitica = RIGHT(:wClassificacaoSalvo, (wPosPonto-1));

          IF ((:wImprimirNomeQuadroAnalitico > 0) OR (:wClassificacaoAnalitica <> :wClassificacaoAnaliticaAnt)) THEN
            BEGIN
              SELECT q.bdcodquadro, q.bdcodtipo, q.bddescquadro, q.bdclassificacao, q.bdtipo
              FROM vef_estados_tconfgiaprq q WHERE (q.bdclassificacao = :wClassificacaoSalvo) AND (q.bdtipo = 1)
              INTO :BDCODQUADRO, :BDCODTIPO, :BDDESCQUADRO, :BDCLASSIFICACAO, :BDTIPO;

              BDVALOR    = NULL;
              BDNUMCAMPO = NULL;
              BDNUMITEM  = NULL;
              BDDESCFORM = :BDCLASSIFICACAO || ' - ' || :BDDESCQUADRO;

              SUSPEND;

              wClassificacaoAnaliticaAnt = :wClassificacaoAnalitica;
            END 

          BDCODQUADRO   = :wCodQuadroSalvo;
          wCodQuadroAnt = :BDCODQUADRO;
        END 

      /* restaura os valores salvos anteriormente */
      BDCODQUADRO     = :wCodQuadroSalvo;
      BDCODTIPO       = :wCodTipoSalvo;
      BDDESCQUADRO    = :wDescQuadroSalvo;
      BDCLASSIFICACAO = :wClassificacaoSalvo;
      BDTIPO          = :wTipoSalvo;
      BDNUMCAMPO      = :wNumCampoSalvo;
      BDDESCFORM      = :wDescFormSalvo;
      BDVALOR         = :wValorSalvo;
      BDNUMITEM       = :wNumItemSalvo;

      SUSPEND;
    END
END
^

/* Restore proc. body: SP_VEF_TREEVIEW_CONS_GIARJ */
CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIARJ (
    PRCODEMP VARCHAR(10000),
    PRANOMESINICIAL INTEGER,
    PRANOMESFINAL INTEGER,
    PRCODPERIODO INTEGER,
    PRCLASSIFICACAO VARCHAR(11),
    PRGERAL INTEGER,
    PRCODQUADRO INTEGER,
    PRCODNAT INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCONF INTEGER,
    BDREFERENCIA INTEGER,
    BDCODPERIODO INTEGER,
    BDNUMCAMPO INTEGER,
    BDCODQUADRO INTEGER,
    BDCLASSIFICACAO VARCHAR(10),
    BDDESCQUADRO VARCHAR(80),
    BDDESCFORM VARCHAR(150),
    BDVALOR NUMERIC(15,2),
    BDCODTIPO INTEGER,
    BDCODNAT INTEGER,
    BDTIPO INTEGER,
    BDNUMITEM INTEGER)
AS
DECLARE VARIABLE WWHEREQUADRO VARCHAR(1000);
DECLARE VARIABLE WREFBETWEEN VARCHAR(100);
DECLARE VARIABLE WCONDICAONATUREZA VARCHAR(100);
DECLARE VARIABLE WINNERSELECT VARCHAR(1000);
DECLARE VARIABLE WSQL BLOB SUB_TYPE 1 SEGMENT SIZE 16384;
DECLARE VARIABLE WREFANT INTEGER;
DECLARE VARIABLE WCODQUADROANT INTEGER;
DECLARE VARIABLE WPOSPONTO INTEGER;
DECLARE VARIABLE WCLASSIFICACAOTITULO VARCHAR(10);
DECLARE VARIABLE WCLASSIFICACAOTITULOANT VARCHAR(10);
DECLARE VARIABLE WCLASSIFICACAOTITULO2 VARCHAR(10);
DECLARE VARIABLE WCLASSIFICACAOTITULO2ANT VARCHAR(10);
DECLARE VARIABLE WCLASSIFICACAOANALITICA VARCHAR(10);
DECLARE VARIABLE WCLASSIFICACAOANALITICAANT VARCHAR(10);
DECLARE VARIABLE WQTDPONTOS INTEGER;
DECLARE VARIABLE WCODQUADROSALVO INTEGER;
DECLARE VARIABLE WCODTIPOSALVO INTEGER;
DECLARE VARIABLE WDESCQUADROSALVO VARCHAR(80);
DECLARE VARIABLE WCLASSIFICACAOSALVO VARCHAR(10);
DECLARE VARIABLE WTIPOSALVO INTEGER;
DECLARE VARIABLE WNUMCAMPOSALVO INTEGER;
DECLARE VARIABLE WDESCFORMSALVO VARCHAR(150);
DECLARE VARIABLE WVALORSALVO NUMERIC(15,2);
DECLARE VARIABLE WNUMITEMSALVO INTEGER;
DECLARE VARIABLE WIMPRIMIRNOMEQUADROANALITICO INTEGER;
DECLARE VARIABLE WCODUF INTEGER;
DECLARE VARIABLE WCODUFANTERIOR INTEGER;
DECLARE VARIABLE WSIGLAUF VARCHAR(2);
DECLARE VARIABLE WPREFIXONATANTERIOR INTEGER;
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRANOMESFINAL, NULL, NULL);

  /* INICIALIZA COM UMA STRING VAZIA */
  WSQL              = '';
  WINNERSELECT      = '';
  WREFBETWEEN       = '';
  WWHEREQUADRO      = '';
  WCONDICAONATUREZA = '';

  /* ADICIONA CONDIÇÃO DA EMPRESA */
  IF ((:PRCODEMP IS NOT NULL) AND (:PRCODEMP <> '')) THEN
    BEGIN
      WINNERSELECT = :WINNERSELECT || :PRCODEMP;
    END

  /* ADICIONA A CONDIÇÃO DO CÓDIGO DO PERIODO */
  IF (:PRCODPERIODO > 0) THEN
    BEGIN
      IF (:WINNERSELECT <> '') THEN
        BEGIN
          WINNERSELECT = :WINNERSELECT || ' AND ';
        END 

      WINNERSELECT = :WINNERSELECT || 'BDCODPERIODO = ' || :PRCODPERIODO;
    END 

  /* ADICIONA A CONDIÇÃO DA REFERENCIA */
  IF ((:PRANOMESINICIAL > 0) OR (:PRANOMESFINAL > 0)) THEN
    BEGIN
      WREFBETWEEN = 'BDREFERENCIA BETWEEN ';

      IF (:PRANOMESINICIAL > 0) THEN
        BEGIN
          WREFBETWEEN = :WREFBETWEEN || :PRANOMESINICIAL;
        END 
      ELSE
        BEGIN
          WREFBETWEEN = :WREFBETWEEN || :PRANOMESFINAL;
        END

      WREFBETWEEN = :WREFBETWEEN || ' AND ';

      IF (:PRANOMESFINAL > 0) THEN
        BEGIN
          WREFBETWEEN = :WREFBETWEEN || :PRANOMESFINAL;
        END
      ELSE
        BEGIN
          WREFBETWEEN = :WREFBETWEEN || :PRANOMESINICIAL;
        END

      IF (:WINNERSELECT <> '') THEN
        BEGIN
          WINNERSELECT = :WINNERSELECT || ' AND ';
        END 

      WINNERSELECT = :WINNERSELECT || :WREFBETWEEN;
    END 

  IF (:WINNERSELECT <> '') THEN
    BEGIN
      WINNERSELECT = ' WHERE ' || :WINNERSELECT;
    END 

  WINNERSELECT = ' SELECT BDCODEMP, BDCODPERIODO, BDREFERENCIA FROM VEF_EMP_TGIARJGER ' || :WINNERSELECT;

  /* CONDIÇÃO CLASSIFICAÇÃO DO QUADRO (USADO NO JOIN) */
  IF ((:PRCLASSIFICACAO IS NOT NULL) AND (:PRCLASSIFICACAO <> '')) THEN
    BEGIN
      WWHEREQUADRO = ' AND Q.BDCLASSIFICACAO LIKE '''|| :PRCLASSIFICACAO ||'%''';
    END 

  IF ((:PRCODQUADRO IS NOT NULL) AND (:PRCODQUADRO > 0))  THEN
    BEGIN
      IF (:WWHEREQUADRO <> '') THEN
        BEGIN
          WWHEREQUADRO = :WWHEREQUADRO || ' AND ';
        END 

      WWHEREQUADRO = :WWHEREQUADRO || ' Q.BDCODQUADRO = ' || :PRCODQUADRO;
    END 

  /* CONDIÇÃO DA NATUREZA DE OPERAÇÃO */
  IF ((:PRCODNAT IS NOT NULL) AND (:PRCODNAT > 0)) THEN
    BEGIN
      WCONDICAONATUREZA = ' AND NAT.BDPREFIXONAT = ' || :PRCODNAT;
    END 

  WSQL = WSQL || ' SELECT T.BDCODEMP, ';
  WSQL = WSQL || '        E.BDNOMEMP, ';
  WSQL = WSQL || '        P.BDCODCONFGIARJ, ';
  WSQL = WSQL || '        T.BDREFERENCIA, ';
  WSQL = WSQL || '        T.BDCODPERIODO, ';
  WSQL = WSQL || '        T.BDNUMCAMPO, ';
  WSQL = WSQL || '        T.BDCODQUADRO, ';
  WSQL = WSQL || '        Q.BDCLASSIFICACAO, ';
  WSQL = WSQL || '        Q.BDDESCQUADRO, ';
  WSQL = WSQL || '        F.BDDESCFORM, ';
  WSQL = WSQL || '        T.BDVALOR , ';
  WSQL = WSQL || '        Q.BDCODTIPO, ';
  WSQL = WSQL || '        T.BDPREFIXONAT BDCODNAT, ';
  WSQL = WSQL || '        Q.BDTIPO, ';
  WSQL = WSQL || '        F.BDNUMITEM, ';
  WSQL = WSQL || '        T.BDCODUF, ';
  WSQL = WSQL || '        uf.BDSIGLAUF ';
  WSQL = WSQL || ' FROM ( ';
  WSQL = WSQL || '        SELECT GER.BDCODEMP   , GER.BDCODPERIODO, GER.BDREFERENCIA,  ';
  WSQL = WSQL || '               NAT.BDCODQUADRO, NAT.BDNUMCAMPO  , NAT.BDPREFIXONAT, ';
  WSQL = WSQL || '               SUM(COALESCE(NAT.BDVALOR,  0)) "BDVALOR", null as BDCODUF ';
  WSQL = WSQL || '        FROM (' || :WINNERSELECT || ') GER ';
  WSQL = WSQL || '        LEFT OUTER JOIN VEF_EMP_TGIARJGERNAT NAT ON NAT.BDCODEMP = GER.BDCODEMP AND NAT.BDCODPERIODO = GER.BDCODPERIODO AND NAT.BDREFERENCIA = GER.BDREFERENCIA ' || :WCONDICAONATUREZA;
  WSQL = WSQL || '        GROUP BY GER.BDCODEMP, GER.BDCODPERIODO, GER.BDREFERENCIA, NAT.BDCODQUADRO, NAT.BDNUMCAMPO, BDPREFIXONAT ';
  WSQL = WSQL || '        UNION ALL ';
  WSQL = WSQL || '        SELECT GER.BDCODEMP   , GER.BDCODPERIODO, GER.BDREFERENCIA, ';
  WSQL = WSQL || '               REG.BDCODQUADRO, REG.BDNUMCAMPO  , NULL            , ';
  WSQL = WSQL || '               REG.BDVALOR, null as BDCODUF ';
  WSQL = WSQL || '        FROM (' || :WINNERSELECT || ') GER ';
  WSQL = WSQL || '        LEFT OUTER JOIN VEF_EMP_TGIARJGERREG REG ON REG.BDCODEMP = GER.BDCODEMP AND REG.BDCODPERIODO = GER.BDCODPERIODO AND REG.BDREFERENCIA = GER.BDREFERENCIA ';

  WSQL = WSQL || '       union all ';
  -- // Entradas Interestaduais //
  WSQL = WSQL || '       select GER.BDCODEMP, GER.BDCODPERIODO, GER.BDREFERENCIA, q21.BDCODQUADRO, q21.BDNUMCAMPO, ';
  WSQL = WSQL || '              null as BDPREFIXONAT, sum(coalesce(q21.BDVALOR, 0)) "BDVALOR", COALESCE(Q21.BDCODUF, 9999) as BDCODUF ';
  WSQL = WSQL || '       from (' || :WINNERSELECT || ') GER ';
  WSQL = WSQL || '       left outer join VEF_EMP_TGIARJGERQ21 q21 on (q21.BDCODEMP = GER.BDCODEMP and q21.BDCODPERIODO = GER.BDCODPERIODO and q21.BDREFERENCIA = GER.BDREFERENCIA) ';
  WSQL = WSQL || '       group by GER.BDCODEMP, GER.BDCODPERIODO, GER.BDREFERENCIA, q21.BDCODQUADRO, q21.BDNUMCAMPO, q21.BDCODUF ';
  WSQL = WSQL || '       union all ';
  -- // Saídas Interestaduais //
  WSQL = WSQL || '       select GER.BDCODEMP, GER.BDCODPERIODO, GER.BDREFERENCIA, q22.BDCODQUADRO, q22.BDNUMCAMPO, ';
  WSQL = WSQL || '              null as BDPREFIXONAT, sum(coalesce(q22.BDVALOR, 0)) "BDVALOR", COALESCE(Q22.BDCODUF, 9999) as BDCODUF ';
  WSQL = WSQL || '       from (' || :WINNERSELECT || ') GER ';
  WSQL = WSQL || '       left outer join VEF_EMP_TGIARJGERQ22 q22 on (q22.BDCODEMP = GER.BDCODEMP and q22.BDCODPERIODO = GER.BDCODPERIODO and q22.BDREFERENCIA = GER.BDREFERENCIA) ';
  WSQL = WSQL || '       group by GER.BDCODEMP, GER.BDCODPERIODO, GER.BDREFERENCIA, q22.BDCODQUADRO, q22.BDNUMCAMPO, q22.BDCODUF ';

  WSQL = WSQL || '       ) T ';
  WSQL = WSQL || ' INNER JOIN VEF_ESTADOS_TCONFGIARJQ Q ON (Q.BDCODQUADRO = T.BDCODQUADRO) ' || :WWHEREQUADRO;
  --WSQL = WSQL || ' LEFT OUTER JOIN VW_TEMPRESAS_REF_ATUAL E ON (E.BDCODEMP = T.BDCODEMP) ';
  WSQL = WSQL || ' LEFT OUTER JOIN (select v.bdcodemp,v.bdrefemp BDEMPREF,e.bdnomemp ';
  WSQL = WSQL || '                  from VW_TEMPRESAS_REF_MAX_MIN v ';
  WSQL = WSQL || '                  left outer join tempresas_ref e on (v.bdcodemp = e.bdcodemp and v.bdrefemp = e.bdrefemp) ';
  WSQL = WSQL || '                   ) E ON (E.BDCODEMP = T.BDCODEMP) ';
  WSQL = WSQL || ' LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTRJ P ON (P.BDCODEMP = E.BDCODEMP) ';
  WSQL = WSQL || ' LEFT OUTER JOIN VEF_ESTADOS_TCONFGIARJFORM F ON (F.BDCODCONF = P.BDCODCONFGIARJ) AND (F.BDCODQUADRO = T.BDCODQUADRO) AND (F.BDNUMCAMPO = T.BDNUMCAMPO) ';
  WSQL = WSQL || ' left outer join TUF uf on (uf.BDCODUF = T.BDCODUF) ';
  WSQL = WSQL || ' order by BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCODQUADRO, BDPREFIXONAT,/*XXX*/ BDCODUF, BDNUMCAMPO, BDDESCFORM ';

  /* INICIALIZA VARIAVEIS DE CONTROLE */
  WREFANT                    = 0;
  WCODQUADROANT              = 0;
  WCLASSIFICACAOTITULO       = '';
  WCLASSIFICACAOTITULOANT    = '';
  WCLASSIFICACAOTITULO2      = '';
  WCLASSIFICACAOTITULO2ANT   = '';
  WCLASSIFICACAOANALITICA    = '';
  WCLASSIFICACAOANALITICAANT = '';

  FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCONF,
    :BDREFERENCIA,
    :BDCODPERIODO,
    :BDNUMCAMPO,
    :BDCODQUADRO,
    :BDCLASSIFICACAO,
    :BDDESCQUADRO,
    :BDDESCFORM,
    :BDVALOR,
    :BDCODTIPO,
    :BDCODNAT,
    :BDTIPO,
    :BDNUMITEM,
    :wCODUF,
    :wSIGLAUF
  DO
    BEGIN
      /* VARIÁVEL DE CONTROLE PARA VERIFICAR SE PRECISA OU NÃO IMPRIMIR O NOME DO QUADRO ANALITICO */
      WIMPRIMIRNOMEQUADROANALITICO = 0;

      /* SALVA VALORES DOS REGISTRO EM VARIAVEIS PARA RESTAURAR DEPOIS */
      WCODQUADROSALVO     = :BDCODQUADRO;
      WCODTIPOSALVO       = :BDCODTIPO;
      WDESCQUADROSALVO    = :BDDESCQUADRO;
      WCLASSIFICACAOSALVO = :BDCLASSIFICACAO;
      WTIPOSALVO          = :BDTIPO;
      WNUMCAMPOSALVO      = :BDNUMCAMPO;
      WDESCFORMSALVO      = :BDDESCFORM;
      WVALORSALVO         = :BDVALOR;
      WNUMITEMSALVO       = :BDNUMITEM;

      /* MOSTRA A REFERENCIA NA CONSULTA */
      IF ((:PRGERAL = 1) AND (:PRANOMESINICIAL <> :PRANOMESFINAL) AND (:BDREFERENCIA <> :WREFANT)) THEN
        BEGIN
          BDCODQUADRO = 0; /* PARA ORDENAÇÃO DAS REFERENCIAS */
          BDVALOR     = NULL;
          BDNUMCAMPO  = NULL;
          BDNUMITEM   = NULL;
          BDDESCFORM  = CAST(:BDREFERENCIA AS VARCHAR(6));
          BDDESCFORM  = SUBSTRING(:BDDESCFORM FROM 5 FOR 2) || '/' || SUBSTRING(:BDDESCFORM FROM 1 FOR 4);

          SUSPEND;

          WREFANT = :BDREFERENCIA;
          WIMPRIMIRNOMEQUADROANALITICO = 1;
        END 

      /* MOSTRA O NOME DO QUADRO NA CONSULTA */
      IF ((:PRGERAL = 1) AND (:BDCODQUADRO <> :WCODQUADROANT))  THEN
        BEGIN
          SELECT P.POS FROM POS('.', :WCLASSIFICACAOSALVO) P INTO :WPOSPONTO;

          WCLASSIFICACAOTITULO = LEFT(:WCLASSIFICACAOSALVO, (:WPOSPONTO - 1));

          /* SE MUDOU O TÍTULO, MOSTRA QUAL O TÍTULO ATUAL NA CONSULTA */
          IF (:WCLASSIFICACAOTITULO <> :WCLASSIFICACAOTITULOANT) THEN
            BEGIN
              SELECT Q.BDCODQUADRO, Q.BDCODTIPO, Q.BDDESCQUADRO, Q.BDCLASSIFICACAO, Q.BDTIPO
              FROM VEF_ESTADOS_TCONFGIARJQ Q WHERE (Q.BDCLASSIFICACAO = :WCLASSIFICACAOTITULO) AND (Q.BDTIPO = 0)
              INTO :BDCODQUADRO, :BDCODTIPO, :BDDESCQUADRO, :BDCLASSIFICACAO, :BDTIPO;

              BDVALOR    = NULL;
              BDNUMCAMPO = NULL;
              BDNUMITEM  = NULL;
              BDDESCFORM = :WCLASSIFICACAOTITULO || ' - ' || :BDDESCQUADRO;

              SUSPEND;

              WCLASSIFICACAOTITULOANT = :WCLASSIFICACAOTITULO;
              WIMPRIMIRNOMEQUADROANALITICO = 1;
            END 

          /* VERIFICA AGORA, SE O REGISTRO ATUAL POSSUI MAIS DE UM TÍTULO */
          SELECT CC.CONTAR_CHAR FROM CONTAR_CHAR(:WCLASSIFICACAOSALVO, '.') CC INTO :WQTDPONTOS;

          /* EXEMPLO: 08.01.01 */
          IF (:WQTDPONTOS > 1) THEN
            BEGIN
              SELECT (P.POS + :WPOSPONTO) FROM POS('.', SUBSTRING(:WCLASSIFICACAOSALVO FROM (:WPOSPONTO + 1) FOR (CHAR_LENGTH(:WCLASSIFICACAOSALVO)-:WPOSPONTO))) P INTO :WPOSPONTO;

              WCLASSIFICACAOTITULO2 = LEFT(:WCLASSIFICACAOSALVO, (:WPOSPONTO - 1));

              /* SE MUDOU O TÍTULO DE SEGUNDO NÍVEL, MOSTRA ELE NA CONSULTA */
              IF (:WCLASSIFICACAOTITULO2 <> :WCLASSIFICACAOTITULO2ANT) THEN
                BEGIN
                  SELECT Q.BDCODQUADRO, Q.BDCODTIPO, Q.BDDESCQUADRO, Q.BDCLASSIFICACAO, Q.BDTIPO
                  FROM VEF_ESTADOS_TCONFGIARJQ Q WHERE (Q.BDCLASSIFICACAO = :WCLASSIFICACAOTITULO2) AND (Q.BDTIPO = 0)
                  INTO :BDCODQUADRO, :BDCODTIPO, :BDDESCQUADRO, :BDCLASSIFICACAO, :BDTIPO;

                  BDVALOR = NULL;
                  BDNUMCAMPO = NULL;
                  BDNUMITEM  = NULL;
                  BDDESCFORM = :WCLASSIFICACAOTITULO2 || ' - ' || :BDDESCQUADRO;

                  SUSPEND;

                  WCLASSIFICACAOTITULO2ANT = :WCLASSIFICACAOTITULO2;
                  WIMPRIMIRNOMEQUADROANALITICO = 1;
                END
            END 

          /* QUADRO ANALITICO */
          SELECT RP.BDRPOS FROM RPOS('.', :WCLASSIFICACAOSALVO) RP INTO :WPOSPONTO;

          WCLASSIFICACAOANALITICA = RIGHT(:WCLASSIFICACAOSALVO, (WPOSPONTO-1));

          IF ((:WIMPRIMIRNOMEQUADROANALITICO > 0) OR (:WCLASSIFICACAOANALITICA <> :WCLASSIFICACAOANALITICAANT)) THEN
            BEGIN
              SELECT Q.BDCODQUADRO, Q.BDCODTIPO, Q.BDDESCQUADRO, Q.BDCLASSIFICACAO, Q.BDTIPO
              FROM VEF_ESTADOS_TCONFGIARJQ Q WHERE (Q.BDCLASSIFICACAO = :WCLASSIFICACAOSALVO) AND (Q.BDTIPO = 1)
              INTO :BDCODQUADRO, :BDCODTIPO, :BDDESCQUADRO, :BDCLASSIFICACAO, :BDTIPO;

              BDVALOR    = NULL;
              BDNUMCAMPO = NULL;
              BDNUMITEM  = NULL;
              BDDESCFORM = :BDCLASSIFICACAO || ' - ' || :BDDESCQUADRO;

              SUSPEND;

              WCLASSIFICACAOANALITICAANT = :WCLASSIFICACAOANALITICA;
            END 

          BDCODQUADRO   = :WCODQUADROSALVO;
          WCODQUADROANT = :BDCODQUADRO;
        END 

      /* JOGA OS PREFIXOS DA NATUREZAS */
      IF (WPREFIXONATANTERIOR IS NULL) THEN
        WPREFIXONATANTERIOR = 0; /* Para jogar na primeira linha dos totalizadores */
      IF ((PRGERAL = 1) AND 
          (((BDCODTIPO = 2) AND (WPREFIXONATANTERIOR <> BDCODNAT)) OR  /* Valores entradas */
           ((BDCODTIPO = 3) AND (WPREFIXONATANTERIOR <> BDCODNAT)))) THEN /* Valores saídas */
         BEGIN
           BDNUMCAMPO = NULL;
           BDNUMITEM  = NULL;
           BDDESCFORM = SUBSTRING(BDCODNAT FROM 1 FOR 1)||'.'||SUBSTRING(BDCODNAT FROM 2 FOR 3);
           BDVALOR    = NULL;
           BDTIPO     = 0;
           WPREFIXONATANTERIOR = BDCODNAT;
           SUSPEND;
         END

      /* JOGA OS ESTADOS NOS QUADROS ESTADUAIS */
      IF (WCODUFANTERIOR IS NULL) THEN
        WCODUFANTERIOR = 0; /* Para jogar na primeira linha dos totalizadores */
      IF ((PRGERAL = 1) AND 
          (((BDCODTIPO = 332) AND (((WCODUF = 9999) AND (WCODUFANTERIOR <> 9999)) OR ((WCODUF <> 9999) AND (WCODUF <> WCODUFANTERIOR)))) OR  /* Entradas Interestaduais */
           ((BDCODTIPO = 333) AND (((WCODUF = 9999) AND (WCODUFANTERIOR <> 9999)) OR ((WCODUF <> 9999) AND (WCODUF <> WCODUFANTERIOR)))))) THEN /* Saídas Interestaduais */
         BEGIN
           BDNUMCAMPO = NULL;
           BDNUMITEM  = NULL;
           IF (WCODUF = 9999) THEN
             BDDESCFORM = 'Total';
           ELSE
             BDDESCFORM = wSIGLAUF;
           BDVALOR        = NULL;
           WCODUFANTERIOR = WCODUF;
           BDTIPO         = 0;
           SUSPEND;
         END

      /* RESTAURA OS VALORES SALVOS ANTERIORMENTE */
      BDCODQUADRO     = :WCODQUADROSALVO;
      BDCODTIPO       = :WCODTIPOSALVO;
      BDDESCQUADRO    = :WDESCQUADROSALVO;
      BDCLASSIFICACAO = :WCLASSIFICACAOSALVO;
      BDTIPO          = :WTIPOSALVO;
      BDNUMCAMPO      = :WNUMCAMPOSALVO;
      BDDESCFORM      = :WDESCFORMSALVO;
      BDVALOR         = :WVALORSALVO;
      BDNUMITEM       = :WNUMITEMSALVO;

      SUSPEND;
    END
END
^

create or alter procedure SP_VEF_TREEVIEW_CONS_GIATO (
    PRCODEMP varchar(10000),
    PRANOMESINICIAL integer,
    PRANOMESFINAL integer,
    PRCODPERIODO integer,
    PRCLASSIFICACAO varchar(11),
    PRGERAL integer,
    PRCODQUADRO integer,
    PRCODNAT integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCONF integer,
    BDREFERENCIA integer,
    BDCODPERIODO integer,
    BDNUMCAMPO integer,
    BDCODQUADRO integer,
    BDCLASSIFICACAO varchar(10),
    BDDESCQUADRO varchar(80),
    BDDESCFORM varchar(150),
    BDVALOR numeric(15,2),
    BDCODTIPO integer,
    BDCODNAT integer,
    BDTIPO integer,
    BDNUMITEM integer)
as
declare variable WWHEREQUADRO varchar(1000);
declare variable WREFBETWEEN varchar(100);
declare variable WCONDICAONATUREZA varchar(100);
declare variable WINNERSELECT varchar(1000);
declare variable WSQL blob sub_type 1 segment size 16384;
declare variable WREFANT integer;
declare variable WCODQUADROANT integer;
declare variable WPOSPONTO integer;
declare variable WCLASSIFICACAOTITULO varchar(10);
declare variable WCLASSIFICACAOTITULOANT varchar(10);
declare variable WCLASSIFICACAOTITULO2 varchar(10);
declare variable WCLASSIFICACAOTITULO2ANT varchar(10);
declare variable WCLASSIFICACAOANALITICA varchar(10);
declare variable WCLASSIFICACAOANALITICAANT varchar(10);
declare variable WQTDPONTOS integer;
declare variable WCODQUADROSALVO integer;
declare variable WCODTIPOSALVO integer;
declare variable WDESCQUADROSALVO varchar(80);
declare variable WCLASSIFICACAOSALVO varchar(10);
declare variable WTIPOSALVO integer;
declare variable WNUMCAMPOSALVO integer;
declare variable WDESCFORMSALVO varchar(150);
declare variable WVALORSALVO numeric(15,2);
declare variable WNUMITEMSALVO integer;
declare variable WIMPRIMIRNOMEQUADROANALITICO integer;
declare variable WCODUF integer;
declare variable WCODUFANTERIOR integer;
declare variable WSIGLAUF varchar(200);
declare variable WPREFIXONATANTERIOR integer;
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRANOMESFINAL, NULL, NULL);

  /* INICIALIZA COM UMA STRING VAZIA */
  WSQL = '';
  WINNERSELECT = '';
  WREFBETWEEN = '';
  WWHEREQUADRO = '';
  WCONDICAONATUREZA = '';

  /* ADICIONA CONDIÇÃO DA EMPRESA */
  IF ((:PRCODEMP IS NOT NULL) AND
      (:PRCODEMP <> '')) THEN
  BEGIN
    WINNERSELECT = :WINNERSELECT || :PRCODEMP;
  END

  /* ADICIONA A CONDIÇÃO DO CÓDIGO DO PERIODO */
  IF (:PRCODPERIODO > 0) THEN
  BEGIN
    IF (:WINNERSELECT <> '') THEN
    BEGIN
      WINNERSELECT = :WINNERSELECT || ' AND ';
    END

    WINNERSELECT = :WINNERSELECT || 'BDCODPERIODO = ' || :PRCODPERIODO;
  END

  /* ADICIONA A CONDIÇÃO DA REFERENCIA */
  IF ((:PRANOMESINICIAL > 0) OR (:PRANOMESFINAL > 0)) THEN
  BEGIN
    WREFBETWEEN = 'BDREFERENCIA BETWEEN ';

    IF (:PRANOMESINICIAL > 0) THEN
    BEGIN
      WREFBETWEEN = :WREFBETWEEN || :PRANOMESINICIAL;
    END
    ELSE
    BEGIN
      WREFBETWEEN = :WREFBETWEEN || :PRANOMESFINAL;
    END

    WREFBETWEEN = :WREFBETWEEN || ' AND ';

    IF (:PRANOMESFINAL > 0) THEN
    BEGIN
      WREFBETWEEN = :WREFBETWEEN || :PRANOMESFINAL;
    END
    ELSE
    BEGIN
      WREFBETWEEN = :WREFBETWEEN || :PRANOMESINICIAL;
    END

    IF (:WINNERSELECT <> '') THEN
    BEGIN
      WINNERSELECT = :WINNERSELECT || ' AND ';
    END

    WINNERSELECT = :WINNERSELECT || :WREFBETWEEN;
  END

  IF (:WINNERSELECT <> '') THEN
  BEGIN
    WINNERSELECT = ' WHERE ' || :WINNERSELECT;
  END

  WINNERSELECT = ' SELECT BDCODEMP, BDCODPERIODO, BDREFERENCIA FROM VEF_EMP_TGIATOGER ' || :WINNERSELECT;

  /* CONDIÇÃO CLASSIFICAÇÃO DO QUADRO (USADO NO JOIN) */
  IF ((:PRCLASSIFICACAO IS NOT NULL) AND
      (:PRCLASSIFICACAO <> '')) THEN
  BEGIN
    WWHEREQUADRO = ' AND Q.BDCLASSIFICACAO LIKE ''' || :PRCLASSIFICACAO || '%''';
  END

  IF ((:PRCODQUADRO IS NOT NULL) AND
      (:PRCODQUADRO > 0)) THEN
  BEGIN
    IF (:WWHEREQUADRO <> '') THEN
    BEGIN
      WWHEREQUADRO = :WWHEREQUADRO || ' AND ';
    END

    WWHEREQUADRO = :WWHEREQUADRO || ' Q.BDCODQUADRO = ' || :PRCODQUADRO;
  END

  /* CONDIÇÃO DA NATUREZA DE OPERAÇÃO */
  IF ((:PRCODNAT IS NOT NULL) AND
      (:PRCODNAT > 0)) THEN
  BEGIN
    WCONDICAONATUREZA = ' AND NAT.BDPREFIXONAT = ' || :PRCODNAT;
  END

  WSQL = WSQL || ' SELECT T.BDCODEMP, ';
  WSQL = WSQL || '        E.BDNOMEMP, ';
  WSQL = WSQL || '        P.BDCODCONFGIATO, ';
  WSQL = WSQL || '        T.BDREFERENCIA, ';
  WSQL = WSQL || '        T.BDCODPERIODO, ';
  WSQL = WSQL || '        T.BDNUMCAMPO, ';
  WSQL = WSQL || '        T.BDCODQUADRO, ';
  WSQL = WSQL || '        Q.BDCLASSIFICACAO, ';
  WSQL = WSQL || '        Q.BDDESCQUADRO, ';
  WSQL = WSQL || '        F.BDDESCFORM, ';
  WSQL = WSQL || '        T.BDVALOR , ';
  WSQL = WSQL || '        Q.BDCODTIPO, ';
  WSQL = WSQL || '        T.BDPREFIXONAT BDCODNAT, ';
  WSQL = WSQL || '        Q.BDTIPO, ';
  WSQL = WSQL || '        F.BDNUMITEM, ';
  WSQL = WSQL || '        T.BDCODUF, ';
  WSQL = WSQL || '        CID.BDNOMCID ';
  WSQL = WSQL || ' FROM ( ';
  WSQL = WSQL || '        SELECT GER.BDCODEMP   , GER.BDCODPERIODO, GER.BDREFERENCIA,  ';
  WSQL = WSQL || '               NAT.BDCODQUADRO, NAT.BDNUMCAMPO  , NAT.BDPREFIXONAT, ';
  WSQL = WSQL || '               SUM(COALESCE(NAT.BDVALOR,  0)) "BDVALOR", NULL AS BDCODUF ';
  WSQL = WSQL || '        FROM (' || :WINNERSELECT || ') GER ';
  WSQL = WSQL || '        LEFT OUTER JOIN VEF_EMP_TGIATOGERNAT NAT ON NAT.BDCODEMP = GER.BDCODEMP AND NAT.BDCODPERIODO = GER.BDCODPERIODO AND NAT.BDREFERENCIA = GER.BDREFERENCIA ' || :WCONDICAONATUREZA;
  WSQL = WSQL || '        GROUP BY GER.BDCODEMP, GER.BDCODPERIODO, GER.BDREFERENCIA, NAT.BDCODQUADRO, NAT.BDNUMCAMPO, BDPREFIXONAT ';
  WSQL = WSQL || '        UNION ALL ';
  WSQL = WSQL || '        SELECT GER.BDCODEMP   , GER.BDCODPERIODO, GER.BDREFERENCIA, ';
  WSQL = WSQL || '               REG.BDCODQUADRO, REG.BDNUMCAMPO  , NULL            , ';
  WSQL = WSQL || '               REG.BDVALOR, NULL AS BDCODUF ';
  WSQL = WSQL || '        FROM (' || :WINNERSELECT || ') GER ';
  WSQL = WSQL || '        LEFT OUTER JOIN VEF_EMP_TGIATOGERREG REG ON REG.BDCODEMP = GER.BDCODEMP AND REG.BDCODPERIODO = GER.BDCODPERIODO AND REG.BDREFERENCIA = GER.BDREFERENCIA ';


    WSQL = WSQL || '       union all ';
  -- // 07.01 //
  WSQL = WSQL || '       select GER.BDCODEMP, GER.BDCODPERIODO, GER.BDREFERENCIA, q0701.BDCODQUADRO, q0701.BDNUMCAMPO, ';
  WSQL = WSQL || '              null as BDPREFIXONAT, sum(coalesce(q0701.BDVALOR, 0)) "BDVALOR", COALESCE(q0701.BDCODCID, 9999) as BDCODCID ';
  WSQL = WSQL || '       from (' || :WINNERSELECT || ') GER ';
  WSQL = WSQL || '       left outer join VEF_EMP_TGIATOGERQ_07_01 q0701 on (q0701.BDCODEMP = GER.BDCODEMP and q0701.BDCODPERIODO = GER.BDCODPERIODO and q0701.BDREFERENCIA = GER.BDREFERENCIA) ';
  WSQL = WSQL || '       group by GER.BDCODEMP, GER.BDCODPERIODO, GER.BDREFERENCIA, q0701.BDCODQUADRO, q0701.BDNUMCAMPO, q0701.BDCODCID ';
  WSQL = WSQL || '       union all ';
  -- // 07.02 //
  WSQL = WSQL || '       select GER.BDCODEMP, GER.BDCODPERIODO, GER.BDREFERENCIA, q0702.BDCODQUADRO, q0702.BDNUMCAMPO, ';
  WSQL = WSQL || '              null as BDPREFIXONAT, sum(coalesce(q0702.BDVALOR, 0)) "BDVALOR", COALESCE(q0702.BDCODCID, 9999) as BDCODCID ';
  WSQL = WSQL || '       from (' || :WINNERSELECT || ') GER ';
  WSQL = WSQL || '       left outer join VEF_EMP_TGIATOGERQ_07_02 q0702 on (q0702.BDCODEMP = GER.BDCODEMP and q0702.BDCODPERIODO = GER.BDCODPERIODO and q0702.BDREFERENCIA = GER.BDREFERENCIA) ';
  WSQL = WSQL || '       group by GER.BDCODEMP, GER.BDCODPERIODO, GER.BDREFERENCIA, q0702.BDCODQUADRO, q0702.BDNUMCAMPO, q0702.BDCODCID ';

  WSQL = WSQL || '       ) T ';
  WSQL = WSQL || ' INNER JOIN VEF_ESTADOS_TCONFGIATOQ Q ON (Q.BDCODQUADRO = T.BDCODQUADRO) ' || :WWHEREQUADRO;
  --WSQL = WSQL || ' LEFT OUTER JOIN VW_TEMPRESAS_REF_ATUAL E ON (E.BDCODEMP = T.BDCODEMP) ';
  WSQL = WSQL || ' LEFT OUTER JOIN (SELECT V.BDCODEMP,V.BDREFEMP BDEMPREF,E.BDNOMEMP ';
  WSQL = WSQL || '                  FROM VW_TEMPRESAS_REF_MAX_MIN V ';
  WSQL = WSQL || '                  LEFT OUTER JOIN TEMPRESAS_REF E ON (V.BDCODEMP = E.BDCODEMP AND V.BDREFEMP = E.BDREFEMP) ';
  WSQL = WSQL || '                   ) E ON (E.BDCODEMP = T.BDCODEMP) ';
  WSQL = WSQL || ' LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTTO P ON (P.BDCODEMP = E.BDCODEMP) ';
  WSQL = WSQL || ' LEFT OUTER JOIN VEF_ESTADOS_TCONFGIATOFORM F ON (F.BDCODCONF = P.BDCODCONFGIATO) AND (F.BDCODQUADRO = T.BDCODQUADRO) AND (F.BDNUMCAMPO = T.BDNUMCAMPO) ';
  WSQL = WSQL || ' LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = T.BDCODUF) ';

  WSQL = WSQL || ' LEFT OUTER JOIN TCIDADE CID ON (CID.bdcodcid = T.BDCODUF) ';

  WSQL = WSQL || ' ORDER BY BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCODQUADRO, BDPREFIXONAT,/*XXX*/ BDCODUF, BDNUMCAMPO, BDDESCFORM ';

  /* INICIALIZA VARIAVEIS DE CONTROLE */
  WREFANT = 0;
  WCODQUADROANT = 0;
  WCLASSIFICACAOTITULO = '';
  WCLASSIFICACAOTITULOANT = '';
  WCLASSIFICACAOTITULO2 = '';
  WCLASSIFICACAOTITULO2ANT = '';
  WCLASSIFICACAOANALITICA = '';
  WCLASSIFICACAOANALITICAANT = '';

  FOR EXECUTE STATEMENT WSQL
          INTO :BDCODEMP, :BDNOMEMP, :BDCODCONF, :BDREFERENCIA, :BDCODPERIODO, :BDNUMCAMPO, :BDCODQUADRO,
          :BDCLASSIFICACAO, :BDDESCQUADRO, :BDDESCFORM, :BDVALOR, :BDCODTIPO, :BDCODNAT, :BDTIPO, :BDNUMITEM, :WCODUF, :WSIGLAUF
  DO
  BEGIN
    /* VARIÁVEL DE CONTROLE PARA VERIFICAR SE PRECISA OU NÃO IMPRIMIR O NOME DO QUADRO ANALITICO */
    WIMPRIMIRNOMEQUADROANALITICO = 0;

    /* SALVA VALORES DOS REGISTRO EM VARIAVEIS PARA RESTAURAR DEPOIS */
    WCODQUADROSALVO = :BDCODQUADRO;
    WCODTIPOSALVO = :BDCODTIPO;
    WDESCQUADROSALVO = :BDDESCQUADRO;
    WCLASSIFICACAOSALVO = :BDCLASSIFICACAO;
    WTIPOSALVO = :BDTIPO;
    WNUMCAMPOSALVO = :BDNUMCAMPO;
    WDESCFORMSALVO = :BDDESCFORM;
    WVALORSALVO = :BDVALOR;
    WNUMITEMSALVO = :BDNUMITEM;

    /* MOSTRA A REFERENCIA NA CONSULTA */
    IF ((:PRGERAL = 1) AND
        (:PRANOMESINICIAL <> :PRANOMESFINAL) AND
        (:BDREFERENCIA <> :WREFANT)) THEN
    BEGIN
      BDCODQUADRO = 0;/* PARA ORDENAÇÃO DAS REFERENCIAS */
      BDVALOR = NULL;
      BDNUMCAMPO = NULL;
      BDNUMITEM = NULL;
      BDDESCFORM = CAST(:BDREFERENCIA AS VARCHAR(6));
      BDDESCFORM = SUBSTRING(:BDDESCFORM FROM 5 FOR 2) || '/' || SUBSTRING(:BDDESCFORM FROM 1 FOR 4);

      SUSPEND;

      WREFANT = :BDREFERENCIA;
      WIMPRIMIRNOMEQUADROANALITICO = 1;
    END

    /* MOSTRA O NOME DO QUADRO NA CONSULTA */
    IF ((:PRGERAL = 1) AND
        (:BDCODQUADRO <> :WCODQUADROANT)) THEN
    BEGIN
      SELECT P.POS
      FROM POS('.', :WCLASSIFICACAOSALVO) P
      INTO :WPOSPONTO;

      WCLASSIFICACAOTITULO = LEFT(:WCLASSIFICACAOSALVO, (:WPOSPONTO - 1));

      /* SE MUDOU O TÍTULO, MOSTRA QUAL O TÍTULO ATUAL NA CONSULTA */
      IF (:WCLASSIFICACAOTITULO <> :WCLASSIFICACAOTITULOANT) THEN
      BEGIN
        SELECT Q.BDCODQUADRO, Q.BDCODTIPO, Q.BDDESCQUADRO, Q.BDCLASSIFICACAO, Q.BDTIPO
        FROM VEF_ESTADOS_TCONFGIATOQ Q
        WHERE (Q.BDCLASSIFICACAO = :WCLASSIFICACAOTITULO) AND
              (Q.BDTIPO = 0)
        INTO :BDCODQUADRO, :BDCODTIPO, :BDDESCQUADRO, :BDCLASSIFICACAO, :BDTIPO;

        BDVALOR = NULL;
        BDNUMCAMPO = NULL;
        BDNUMITEM = NULL;
        BDDESCFORM = :WCLASSIFICACAOTITULO || ' - ' || :BDDESCQUADRO;

        SUSPEND;

        WCLASSIFICACAOTITULOANT = :WCLASSIFICACAOTITULO;
        WIMPRIMIRNOMEQUADROANALITICO = 1;
      END

      /* VERIFICA AGORA, SE O REGISTRO ATUAL POSSUI MAIS DE UM TÍTULO */
      SELECT CC.CONTAR_CHAR
      FROM CONTAR_CHAR(:WCLASSIFICACAOSALVO, '.') CC
      INTO :WQTDPONTOS;

      /* EXEMPLO: 08.01.01 */
      IF (:WQTDPONTOS > 1) THEN
      BEGIN
        SELECT (P.POS + :WPOSPONTO)
        FROM POS('.', SUBSTRING(:WCLASSIFICACAOSALVO FROM (:WPOSPONTO + 1) FOR (CHAR_LENGTH(:WCLASSIFICACAOSALVO) - :WPOSPONTO))) P
        INTO :WPOSPONTO;

        WCLASSIFICACAOTITULO2 = LEFT(:WCLASSIFICACAOSALVO, (:WPOSPONTO - 1));

        /* SE MUDOU O TÍTULO DE SEGUNDO NÍVEL, MOSTRA ELE NA CONSULTA */
        IF (:WCLASSIFICACAOTITULO2 <> :WCLASSIFICACAOTITULO2ANT) THEN
        BEGIN
          SELECT Q.BDCODQUADRO, Q.BDCODTIPO, Q.BDDESCQUADRO, Q.BDCLASSIFICACAO, Q.BDTIPO
          FROM VEF_ESTADOS_TCONFGIATOQ Q
          WHERE (Q.BDCLASSIFICACAO = :WCLASSIFICACAOTITULO2) AND
                (Q.BDTIPO = 0)
          INTO :BDCODQUADRO, :BDCODTIPO, :BDDESCQUADRO, :BDCLASSIFICACAO, :BDTIPO;

          BDVALOR = NULL;
          BDNUMCAMPO = NULL;
          BDNUMITEM = NULL;
          BDDESCFORM = :WCLASSIFICACAOTITULO2 || ' - ' || :BDDESCQUADRO;

          SUSPEND;

          WCLASSIFICACAOTITULO2ANT = :WCLASSIFICACAOTITULO2;
          WIMPRIMIRNOMEQUADROANALITICO = 1;
        END
      END

      /* QUADRO ANALITICO */
      SELECT RP.BDRPOS
      FROM RPOS('.', :WCLASSIFICACAOSALVO) RP
      INTO :WPOSPONTO;

      WCLASSIFICACAOANALITICA = RIGHT(:WCLASSIFICACAOSALVO, (WPOSPONTO - 1));

      IF ((:WIMPRIMIRNOMEQUADROANALITICO > 0) OR (:WCLASSIFICACAOANALITICA <> :WCLASSIFICACAOANALITICAANT)) THEN
      BEGIN
        SELECT Q.BDCODQUADRO, Q.BDCODTIPO, Q.BDDESCQUADRO, Q.BDCLASSIFICACAO, Q.BDTIPO
        FROM VEF_ESTADOS_TCONFGIATOQ Q
        WHERE (Q.BDCLASSIFICACAO = :WCLASSIFICACAOSALVO) AND
              (Q.BDTIPO = 1)
        INTO :BDCODQUADRO, :BDCODTIPO, :BDDESCQUADRO, :BDCLASSIFICACAO, :BDTIPO;

        BDVALOR = NULL;
        BDNUMCAMPO = NULL;
        BDNUMITEM = NULL;
        BDDESCFORM = :BDCLASSIFICACAO || ' - ' || :BDDESCQUADRO;

        SUSPEND;

        WCLASSIFICACAOANALITICAANT = :WCLASSIFICACAOANALITICA;
      END

      BDCODQUADRO = :WCODQUADROSALVO;
      WCODQUADROANT = :BDCODQUADRO;
    END

    /* JOGA OS PREFIXOS DA NATUREZAS */
    IF (WPREFIXONATANTERIOR IS NULL) THEN
      WPREFIXONATANTERIOR = 0;/* PARA JOGAR NA PRIMEIRA LINHA DOS TOTALIZADORES */
    IF ((PRGERAL = 1) AND
        (((BDCODTIPO = 2) AND
        (WPREFIXONATANTERIOR <> BDCODNAT)) OR /* VALORES ENTRADAS */
        ((BDCODTIPO = 3) AND
        (WPREFIXONATANTERIOR <> BDCODNAT)))) THEN
    /* VALORES SAÍDAS */
    BEGIN
      BDNUMCAMPO = NULL;
      BDNUMITEM = NULL;
      BDDESCFORM = SUBSTRING(BDCODNAT FROM 1 FOR 1) || '.' || SUBSTRING(BDCODNAT FROM 2 FOR 3);
      BDVALOR = NULL;
      BDTIPO = 0;
      WPREFIXONATANTERIOR = BDCODNAT;
      SUSPEND;
    END




    /* RESTAURA OS VALORES SALVOS ANTERIORMENTE */
    BDCODQUADRO = :WCODQUADROSALVO;
    BDCODTIPO = :WCODTIPOSALVO;
    BDDESCQUADRO = :WDESCQUADROSALVO;
    BDCLASSIFICACAO = :WCLASSIFICACAOSALVO;
    BDTIPO = :WTIPOSALVO;
    BDNUMCAMPO = :WNUMCAMPOSALVO;
    BDDESCFORM = :WDESCFORMSALVO;
    BDVALOR = :WVALORSALVO;
    BDNUMITEM = :WNUMITEMSALVO;

    IF (PRCLASSIFICACAO like '%07%')    then
      BEGIN
       BDDESCFORM = wSIGLAUF || ' - TO';
      END
    SUSPEND;
  END
END
^

/* Restore proc. body: SP_VEF_TREEVIEW_CONS_GIARO */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIARO (
    PRCODEMP VARCHAR(10000),
    PRANOMESINICIAL INTEGER,
    PRANOMESFINAL INTEGER,
    PRCODPERIODO INTEGER,
    PRCLASSIFICACAO VARCHAR(11),
    PRGERAL INTEGER,
    PRCODQUADRO INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCONF INTEGER,
    BDREFERENCIA INTEGER,
    BDCODPERIODO INTEGER,
    BDNUMCAMPO INTEGER,
    BDCODQUADRO INTEGER,
    BDCLASSIFICACAO VARCHAR(11),
    BDDESCQUADRO VARCHAR(80),
    BDDESCFORM VARCHAR(150),
    BDVALOR NUMERIC(15,2),
    BDCODTIPO INTEGER,
    BDTIPO INTEGER,
    BDNUMITEM INTEGER,
    BDCODNAT INTEGER,
    BDORDEMTTNAT INTEGER,
    BDTITULOGRUPO VARCHAR(80))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE PRQUADROANT INTEGER;
DECLARE VARIABLE PRSALVAQUADROANT INTEGER;
DECLARE VARIABLE WTIT INTEGER;
DECLARE VARIABLE WCLASSIFIPRINC VARCHAR(20);
DECLARE VARIABLE WCLASSIFITITULO VARCHAR(20);
DECLARE VARIABLE PRNUMCAMPO INTEGER;
DECLARE VARIABLE PRDESCFORM VARCHAR(150);
DECLARE VARIABLE PRCLASSIFIANT VARCHAR(11);
DECLARE VARIABLE PRNATANT INTEGER;
DECLARE VARIABLE WAUX INTEGER;
DECLARE VARIABLE WAUX2 INTEGER;
DECLARE VARIABLE PRVALOR NUMERIC(15,2);
DECLARE VARIABLE PRREFANT INTEGER;
DECLARE VARIABLE PRDESCQUADROANT VARCHAR(80);
DECLARE VARIABLE WTIPO INTEGER;
DECLARE VARIABLE WPREFIXONAT INTEGER;
DECLARE VARIABLE WORDEMTTNATCOMPRAS INTEGER;
DECLARE VARIABLE WORDEMTTNATVENDAS INTEGER;
DECLARE VARIABLE WNATAUX INTEGER;
DECLARE VARIABLE WTITULOGRUPO VARCHAR(80);
DECLARE VARIABLE WCLASSTITULO VARCHAR(20);
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(20);
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql = 'SELECT T.BDCODEMP, ';
  wsql = wsql || ' empAtual.BDNOMEMP, ';
  wsql = wsql || ' parro.BDCODCONFGIARO, ';
  wsql = wsql || ' T.BDREFERENCIA, ';
  wsql = wsql || ' T.BDCODPERIODO, ';
  wsql = wsql || ' T.BDNUMCAMPO, ';
  wsql = wsql || ' T.BDCODQUADRO, ';
  wsql = wsql || ' GIAROQ.BDCLASSIFICACAO, ';
  wsql = wsql || ' GIAROQ.BDDESCQUADRO, ';
  wsql = wsql || ' GIAROF.BDDESCFORM, ';
  wsql = wsql || ' T.BDVALOR BDVALOR, ';
  wsql = wsql || ' GIAROQ.BDCODTIPO, ';
  wsql = wsql || ' GIAROQ.BDTIPO, ';
  wsql = wsql || ' GIAROF.BDNUMITEM, ';
  wsql = wsql || ' T.BDPREFIXONAT BDCodNat, ';
  wsql = wsql || ' T.bdordemttnat, ';
  wsql = wsql || ' null bdtitulogrupo ';
  wsql = wsql || ' FROM vw_vef_emp_tGIAROgerunion T';
  --wsql = wsql || ' left outer join VW_EMPRESAS_REF_ATUAL empAtual on (empAtual.bdcodemp = t.bdcodemp) ';
  WSQL = WSQL || ' LEFT OUTER JOIN (select v.bdcodemp,v.bdrefemp BDEMPREF,e.bdnomemp ';
  WSQL = WSQL || '                  from VW_TEMPRESAS_REF_MAX_MIN v ';
  WSQL = WSQL || '                  left outer join tempresas_ref e on (v.bdcodemp = e.bdcodemp and v.bdrefemp = e.bdrefemp) ';
  WSQL = WSQL || '                   ) empAtual on (empAtual.bdcodemp = t.bdcodemp) ';
  wsql = wsql || ' left outer join vef_base_tempparestro parro on (parro.bdCodEmp = empAtual.bdCodEmp and parro.bdrefemp = empAtual.bdempref) ';
  wsql = wsql || ' left outer join VEF_ESTADOS_TCONFGIAROQ GIAROQ on (GIAROQ.bdcodquadro = t.bdcodquadro)';
  wsql = wsql || ' left outer join VEF_ESTADOS_TCONFGIAROFORM GIAROF on (GIAROF.bdCodConf = parro.BDCODCONFGIARO and GIAROF.bdCODQUADRO = t.bdCODQUADRO and GIAROF.bdNumcampo = t.bdNumcampo)';

  wwhere = '';

   IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;

   IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';
       ELSE
          wwhere = wwhere || ' WHERE ';

       wwhere = wwhere || ' t.bdreferencia >= ' || :praNomesInicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || ' t.bdreferencia <= ' || :praNomesFinal;
     END

   IF (prClassificacao IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere || ' and ';
        ELSE
           wwhere = wwhere || ' WHERE ';

        wwhere = wwhere || ' GIAROQ.bdclassificacao LIKE ''' ||:PRCLASSIFICACAO||'%''';
      END
   IF (:prcodperiodo IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere || ' and ';
        ELSE
           wwhere = wwhere || ' WHERE ';

        wwhere = wwhere || ' t.bdCODPERIODO ' || ' = ' || :prcodperiodo;
       END
   IF (:prcodquadro IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere || ' and ';
        ELSE
           wwhere = wwhere || ' WHERE ';

      wwhere = wwhere || ' GIAROQ.BDCODQUADRO' || ' = ' ||:prcodquadro;
      END

   wsql = wsql || wwhere || ' order by bdcodemp, bdreferencia desc, bdclassificacao, BDCODQUADRO,bdcodnat,t.bdnumcampo';

   prRefant = 0;
   prquadroant = 0;
   prnatant = 0;
   wTit = 0;
   WCLASSIFIPRINC = '';
   wTIT = 1;
   wtitulogrupo = NULL;
   wclasstitulo = '';
   wClassificacao = '';

   FOR EXECUTE STATEMENT wsql
   INTO
     BDCODEMP,
     BDNOMEMP,
     BDCODCONF,
     BDREFERENCIA,
     BDCODPERIODO,
     BDNUMCAMPO,
     BDCODQUADRO,
     bdclassificacao,
     bddescquadro,
     BDDESCFORM,
     BDVALOR,
     BDCODTIPO,
     BDTIPO,
     BDNUMITEM,
     BDCODNAT,
     bdordemttnat,
     bdtitulogrupo

   DO
   BEGIN
   wnataux = 0;
   wprefixonat = bdcodnat;
   prNumCampo = BDNumcampo;
   prDescForm = BDDESCFORM;
   prValor = bdValor;

   IF ((wtitulogrupo IS NULL) OR (wtitulogrupo <> bdtitulogrupo) OR (wclasstitulo <> SUBSTRING(bdclassificacao FROM 1 FOR 2)))  THEN
      BEGIN
         wclasstitulo = SUBSTRING(bdclassificacao FROM 1 FOR 2);
         SELECT FIRST 1 bddescquadro FROM VEF_ESTADOS_TCONFGIAROQ tit WHERE tit.bdtipo = 0 AND tit.bdclassificacao = SUBSTRING(:bdclassificacao FROM 1 FOR 2) INTO :wtitulogrupo;
      END

   bdtitulogrupo = wtitulogrupo;

   IF ((prgeral = 1) AND (prRefAnt <> bdReferencia) AND (praNomesInicial <> praNomesFinal)) THEN
      BEGIN
        bdNumCampo = NULL;
        BDDESCFORM = CAST(bdreferencia AS VARCHAR(6));
        bddescform = SUBSTRING(bddescform FROM 5 FOR 2) || '/' ||SUBSTRING(bddescform FROM 1 FOR 4);
        bdvalor = NULL;
        prRefant = bdreferencia;
        SUSPEND;
      END
    IF ((prgeral = 1) AND (bdcodquadro <> prquadroant)) THEN
       BEGIN
         prsalvaquadroant = bdcodquadro;
         prclassifiant = bdclassificacao;
         prdescquadroant = bddescquadro;

         IF (wPrefixoNat IS NULL) THEN
            BEGIN
              SELECT FIRST 1 tPos.BDRPOS FROM rpos('.', :bdclassificacao) tpos INTO :wAUX;

              IF ((wclassifiprinc = '') AND (wAux > 1)) THEN
                 BEGIN
                   wClassifiprinc = SUBSTRING(bdClassificacao FROM 1 FOR waux-1);
                   wtit = 1;
                 END
              ELSE
                 BEGIN
                   IF (wClassifiprinc = SUBSTRING(bdClassificacao FROM 1 FOR waux-1)) THEN
                      BEGIN
                        wtit = 0;
                      END
                   ELSE
                      BEGIN
                        wtit = 1;
                      END
                   IF (waux > 1) THEN
                      BEGIN
                        wClassifiprinc = SUBSTRING(bdClassificacao FROM 1 FOR waux-1);
                      END
                 END
            END
         ELSE
            BEGIN
              SELECT FIRST 1 tpos.pos FROM pos('.' , :Bdclassificacao) tpos INTO :waux;
              wtit = 1;
              wclassifititulo = '';
            END

         IF (waux > 1) THEN
            BEGIN

              IF (wprefixonat IS NULL) THEN
                 BEGIN
                   SELECT FIRST 1 tpos.pos FROM pos('.' , :bdClassificacao) tpos INTO :waux2;
                   wClassifiPrinc = SUBSTRING(bdclassificacao FROM 1 FOR waux2-1);
                 END

          wClassifiTitulo = SUBSTRING(bdClassificacao FROM 1 FOR waux-1);

          IF ((wClassifiPrinc <> wClassifiTitulo) AND (wTit = 1) AND (wClassificacao <> wClassifiPrinc)) THEN
             BEGIN
               SELECT Q.bdcodquadro, Q.bdDescQuadro FROM VEF_ESTADOS_TCONFGIAROQ Q WHERE Q.bdclassificacao = :wClassifiPrinc
               INTO :bdcodquadro, :bddescform;
 
               bdNUmcampo = NULL;
               bdValor = NULL;
               prquadroant = bdCodQuadro;
               bdclassificacao = wClassifiPrinc;
               bddescquadro = bddescform;
               wTipo = BDTipo;
               bdTipo = 0;
               bdcodnat = NULL;
 
               SUSPEND;
               bdclassificacao = prClassifiAnt;
               bdcodquadro = prSalvaQuadroAnt;
               bdDescQuadro = prDescQuadroAnt;
               bdTipo = wTipo;
               bdcodnat = NULL;
               wClassificacao = wClassifiPrinc;
             END
          IF ((wClassifiTitulo <> '') AND (wtit = 1)) THEN
               BEGIN
                 SELECT Q.bdcodquadro, Q.bdDescQuadro FROM VEF_ESTADOS_TCONFGIAROQ Q WHERE Q.bdclassificacao = :wclassifititulo
                 INTO :bdcodquadro, :bddescform;
                 
                 bdNUmcampo = NULL;
                 bdValor = NULL;
                 prquadroant = bdCodQuadro;
                 bdclassificacao = wClassifiTitulo;
                 bddescquadro = bddescform;
                 wTipo = BDTipo;
                 bdTipo = 0;

                 SUSPEND;
                 bdclassificacao = prClassifiAnt;
                 bdcodquadro = prSalvaQuadroAnt;
                 bdDescQuadro = prDescQuadroAnt;
                 bdTipo = wTipo;
               END
            END

         bdNUmcampo = NULL;
         BDDESCFORM = bdclassificacao || ' - ' || bddescquadro;
         bdvalor = NULL;
         prquadroant = bdcodquadro;

         SUSPEND;
       END

     IF ((bdcodtipo = 264) AND (prNatAnt <> wprefixonat) OR ((bdCodTipo = 268) AND (prNatAnt <> wprefixonat))) THEN
        BEGIN
          bdNumCampo = NULL;
          bddescForm = SUBSTRING(CAST(wprefixonat AS VARCHAR(10)) FROM 1 FOR 1) || '.' || SUBSTRING(CAST(wprefixonat AS VARCHAR(10)) FROM 2 FOR 3);
          bdValor = NULL;
          prnatAnt = wprefixonat;
          SUSPEND;
        END

     IF (wnataux <> 0) THEN
        BEGIN
          SUSPEND;
        END

    bdnumcampo = prnumcampo;
    bddescform = prdescform;
    bdvalor = prvalor;
    SUSPEND;
  END
END
^

/* Restore proc. body: SP_VEF_TREEVIEW_CONS_GIASP */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIASP (
    PRCODEMP VARCHAR(10000),
    PRANOMESINICIAL INTEGER,
    PRANOMESFINAL INTEGER,
    PRCODPERIODO INTEGER,
    PRCLASSIFICACAO VARCHAR(10),
    PRGERAL INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCONF INTEGER,
    BDREFERENCIA INTEGER,
    BDCODPERIODO INTEGER,
    BDNUMCAMPO INTEGER,
    BDCODQUADRO INTEGER,
    BDCLASSIFICACAO VARCHAR(5),
    BDDESCQUADRO VARCHAR(80),
    BDDESCFORM VARCHAR(150),
    BDVALOR NUMERIC(15,6),
    BDCODTIPO INTEGER,
    BDCODNAT INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE PRREFANT INTEGER;
DECLARE VARIABLE PRQUADROANT INTEGER;
DECLARE VARIABLE PRSALVAQUADROANT INTEGER;
DECLARE VARIABLE PRNATANT INTEGER;
DECLARE VARIABLE PRCLASSIFIANT VARCHAR(10);
DECLARE VARIABLE PRDESCQUADROANT VARCHAR(80);
DECLARE VARIABLE PRULTIMOCLASSIFITIT VARCHAR(10);
DECLARE VARIABLE PRNUMCAMPO INTEGER;
DECLARE VARIABLE PRDESCFORM VARCHAR(60);
DECLARE VARIABLE PRVALOR NUMERIC(15,6);
DECLARE VARIABLE WCODCID INTEGER;
DECLARE VARIABLE WCODCIDTOT INTEGER;
DECLARE VARIABLE WNOMCID VARCHAR(40);
DECLARE VARIABLE WPREFIXONAT INTEGER;
DECLARE VARIABLE WCODUF INTEGER;
DECLARE VARIABLE WSIGLAUF VARCHAR(2);
DECLARE VARIABLE PRUFANT INTEGER;
DECLARE VARIABLE WCLASSIFITITULO VARCHAR(10);
DECLARE VARIABLE WAUX INTEGER;
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql || 'empresas.BDNOMEMP, ';
  wsql = wsql || 'parsp.BDCODCONFGIASP,';
  wsql = wsql || 'T.BDREFERENCIA, ';
  wsql = wsql || 'T.BDCODPERIODO, ';
  wsql = wsql || 'T.BDNUMCAMPO, ';
  wsql = wsql || 'T.BDCODQUADRO,';
  wsql = wsql || 'TCONF.bdclassificacao, ';
  wsql = wsql || 'TCONF.bddescquadro,';
  wsql = wsql || 'TCONFGIASPFORM.bddescform,';
  wsql = wsql || 'T.BDVALOR BDVALOR, ';
  wsql = wsql || 'TCONF.bdcodtipo, ';
  wsql = wsql || 'T.BDPREFIXONAT BDCODNAT ';

  wsql = wsql || ' from VW_VEF_EMP_TGIASPGERUNION T';

  --wsql = wsql||' left outer join VW_EMP_REF_TOTAL empresas on (empresas.bdcodemp = t.bdcodemp ) ';
  --wsql = wsql||' left outer join VW_EMPRESAS_REF_ATUAL empresas2 on (empresas2.bdcodemp = t.bdcodemp) ';
  wsql = wsql||' LEFT OUTER JOIN (SELECT v.bdCODEMP, v.bdREFEMP, e.bdNOMEMP ';
  wsql = wsql||'                  FROM VW_TEMPRESAS_REF_MAX_MIN v ';
  wsql = wsql||'                  LEFT OUTER JOIN TEMPRESAS_REF e ON (v.bdCODEMP = e.bdCODEMP AND v.bdREFEMP = e.bdREFEMP) ';
  wsql = wsql||'                   ) empresas ON (empresas.bdCODEMP = t.bdCODEMP) ';
  --wsql = wsql||' LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTSP parsp ON (parsp.bdCODEMP = empresas.bdCODEMP AND parsp.bdREFEMP = empresas.bdREFEMP) '; Alt.: #224878 - Nao deve mais olhar a referencia, a view agora ja busca referencia correta...
  wsql = wsql||' LEFT OUTER JOIN VW_VEF_BASE_TEMPPARESTSP parsp ON (parsp.bdCODEMP = empresas.bdCODEMP) ';

  wsql = wsql||' left outer join VEF_ESTADOS_TCONFGIASPQ TCONF on (TCONF.bdcodquadro = t.bdcodquadro) ' ;
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFGIASPFORM TCONFGIASPFORM on (TCONFGIASPFORM.bdcodconf = parsp.BDCODCONFGIASP and ';
  wsql = wsql||' TCONFGIASPFORM.bdcodquadro = T.BDCODQUADRO and TCONFGIASPFORM.bdnumcampo = T.BDNUMCAMPO) ' ;
  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

  IF (PRCLASSIFICACAO IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       --wwhere = wwhere||'T.BDCODQUADRO  = '||:prcodquadro;
       --wwhere = wwhere||'TCONF.bdclassificacao LIKE ''0'||:prcodquadro||'%''';
       wwhere = wwhere||'TCONF.bdclassificacao LIKE '''||:PRCLASSIFICACAO||'%''';
    END

  IF (:prcodperiodo IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODPERIODO' || ' = '||:prcodperiodo;

    END

  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, BDCODQUADRO, BDCODNAT, bdnumcampo' ;

  prrefant   = 0;
  prquadroant = 0;
  prnatant = 0;
  prufant = 0;
  PRULTIMOCLASSIFITIT = '';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDNOMEMP ,
    BDCODCONF ,
    BDREFERENCIA ,
    BDCODPERIODO ,
    BDNUMCAMPO ,
    BDCODQUADRO,
    BDCLASSIFICACAO ,
    BDDESCQUADRO ,
    BDDESCFORM ,
    BDVALOR ,
    BDCODTIPO,
    BDCODNAT
  DO
  BEGIN

    wPREFIXONAT = BDCODNAT;

    prnumcampo = bdnumcampo;
    prdescform = bddescform;
    prvalor = bdvalor;

    IF ((prGeral = 1) AND (prrefant <> bdreferencia) AND (pranomesinicial <> pranomesfinal) ) THEN -- mostra a referencia caso esteja consultando varias
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  CAST(bdreferencia AS VARCHAR(6));
        bddescform =  SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
        BDVALOR = NULL;
        prrefant = bdreferencia;
        SUSPEND;
      END

    IF ((prGeral = 1) AND (prquadroant <> bdcodquadro)) THEN   -- mostra o nome do quadro atual na consulta
      BEGIN
        prsalvaquadroant = bdcodquadro;
        prclassifiant = bdclassificacao;
        prdescquadroant = bddescquadro;

        SELECT FIRST 1 tpos.pos FROM pos('.', :bdclassificacao) tpos INTO :waux;

        IF (waux > 1) THEN -- classificacao titulo
          BEGIN

            wclassifititulo = SUBSTRING(bdclassificacao FROM 1 FOR waux-1);

            IF  (prultimoclassifitit <> wclassifititulo) THEN
              BEGIN

                SELECT x.bdcodquadro, x.bddescquadro FROM VEF_ESTADOS_TCONFGIASPQ x WHERE x.bdclassificacao = :wclassifititulo INTO
                    :bdcodquadro,
                    :bddescform;


                prultimoclassifitit = wclassifititulo;
                bdnumcampo = NULL;
                BDVALOR = NULL;
                prquadroant = bdcodquadro;
                prufant = 0;
                bdclassificacao = wclassifititulo;
                bddescquadro = bddescform;

                SUSPEND;
                bdclassificacao = prclassifiant;
                bddescquadro = prdescquadroant;
                bdcodquadro = prsalvaquadroant;
              END

          END

        bdnumcampo = NULL;
        BDDESCFORM = bdclassificacao || ' - ' || BDDESCQUADRO;
        -- BDDESCFORM =  BDDESCQUADRO;
        BDVALOR = NULL;
        prquadroant = bdcodquadro;
        prufant = 0;

        SUSPEND;

      END

    IF ((bdcodtipo =2) AND (prnatant <> wPREFIXONAT) OR ((bdcodtipo =3) AND (prnatant <> wPREFIXONAT)) ) THEN -- mostra a natureza atual na consuta...
       BEGIN
         bdnumcampo = NULL;
         bddescform =  SUBSTRING(CAST(wPREFIXONAT AS VARCHAR(10)) FROM 1 FOR 1) || '.' || SUBSTRING(CAST(wPREFIXONAT AS VARCHAR(10)) FROM 2 FOR 3);
         BDVALOR = NULL;
         prnatant = wPREFIXONAT;
         SUSPEND;
       END

    bdnumcampo = prnumcampo;
    bddescform = prdescform;
    bdvalor = prvalor;

    SUSPEND;


  END

END
^

/* Restore proc. body: SP_VEF_TREEVIEW_CONS_ICMSSPED */
create or alter procedure SP_VEF_TREEVIEW_CONS_ICMSSPED (
    PRCODEMP varchar(10000),
    PRANOMESINICIAL integer,
    PRANOMESFINAL integer,
    PRCODPERIODO varchar(1000),
    PRCODQUADRO integer,
    PRGERAL integer,
    PRUF integer,
    PRCODSUBAPU integer = 0,
    PRALIQICMS numeric(7,4) = 0,
    PRSEMANA integer = 0)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCONF integer,
    BDREFERENCIA integer,
    BDCODPERIODO integer,
    BDNUMCAMPO integer,
    BDCODQUADRO integer,
    BDDESCQUADRO varchar(150),
    BDDESCFORM varchar(150),
    BDVALOR numeric(18,6),
    BDNUMITEM integer,
    BDCLASSIFICACAO varchar(10),
    BDCODUF integer,
    BDSIGLAUF varchar(2),
    BDCODTIPOVALAGRE integer,
    BDDESCRICAO varchar(150),
    BDCODTIPO integer,
    BDCODSUBAPU integer,
    BDDESCSUBAPU varchar(100),
    BDALIQICMS numeric(7,4),
    BDMOTIVO varchar(10),
    BDSEMANA integer)
as
declare variable WMESREF integer;
declare variable WEXPACUMULADODEZ varchar(5);
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WVALAGRE varchar(32700);
declare variable WREFANT integer;
declare variable PRQUADROANT integer;
declare variable WUFANT integer;
declare variable WCODAUBAPUANT integer;
declare variable WTIPOVA integer;
declare variable PRNUMCAMPO integer;
declare variable PRDESCFORM varchar(150);
declare variable WVALOR numeric(18,6);
declare variable WALIQICMS numeric(7,4);
declare variable WMOTIVO varchar(10);
declare variable WSEMANA integer;
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql =         ' SELECT FIRST 1 ';
  wsql = wsql || '     BDEXPACUMULADODEZ ';
  wsql = wsql || ' FROM ';
  wsql = wsql || '   (SELECT FIRST 1 ';
  wsql = wsql || '        T.BDCODEMP, T.BDREFERENCIA, T.BDCODIGO ';
  wsql = wsql || '    FROM ';
  wsql = wsql || '      VEF_INT_TSPEDICMS T ';
  wsql = wsql || '    WHERE ' || :PRCODEMP;
  wsql = wsql || '    ORDER BY T.BDREFERENCIA DESC) INTSPED ';
  wsql = wsql || ' LEFT JOIN VEF_INT_TSPEDICMSCONF1400 S1400 ON(S1400.BDCODEMP = INTSPED.BDCODEMP AND S1400.BDCODIGO = INTSPED.BDCODIGO AND S1400.BDCODTIPOVALAGRE = 3) ';

  EXECUTE STATEMENT WSQL
  INTO :WEXPACUMULADODEZ;

  WMESREF = SUBSTRING(:pranomesfinal FROM 5 FOR 2);

  WSQL = '';

  --sol:10913 - juntar os valores agregados
  wsql = 'select BDCODEMP, BDNOMEMP, BDCODCONFICMSSPED, BDREFERENCIA, BDCODPERIODO, BDNUMCAMPO, ';
  wsql = wsql || ' BDCODQICMSSPED, BDDESCQICMSSPED, BDDESCFORMICMSSPED, BDVALOR, ';
  wsql = wsql || ' BDNUMITEM, BDCLASSIFICACAO, BDCODUF, BDSIGLAUF, bdcodtipovalagre, bddescricao, BDCODTIPO,bdcodsubapu,bddescsubapu, BDALIQICMS, BDMOTIVO, BDSEMANA from ( ';

  wsql = wsql || 'select T.BDCODEMP, ';
  wsql = wsql || 'emp.BDNOMEMP, ';
  wsql = wsql || 'empresas.bdcodconfICMSSPED, ';
  wsql = wsql || 'T.BDREFERENCIA, ';
  wsql = wsql || 'T.BDCODPERIODO, ';
  wsql = wsql || 'T.BDNUMCAMPO, ';
  wsql = wsql || 'T.BDCODQICMSSPED, ';
  wsql = wsql || 'TCONF.bddescqICMSSPED,';
  wsql = wsql || 'IIF(T.BDCODQICMSSPED IN (12,13),TCONF1250.BDDESCCAMPO,TCONFICMSSPEDFORM.BDDESCFORMICMSSPED) BDDESCFORMICMSSPED,';
  wsql = wsql || 'COALESCE(T.BDVALOR,0) BDVALOR, ';
  wsql = wsql || 'TCONFICMSSPEDFORM.BDNUMITEM, ';
  wsql = wsql || 'TCONF.BDCLASSIFICACAO, ';
  wsql = wsql || 'T.BDCODUF, ';
  wsql = wsql || 'UF.BDSIGLAUF, ';
  wsql = wsql || 'null bdcodtipovalagre, ';
  wsql = wsql || 'null bddescricao, ';
  wsql = wsql || 'TCONF.BDCODTIPO, ';
  wsql = wsql || 'T.BDCODSUBAPU, ';
  wsql = wsql || 'IIF(T.BDCODQICMSSPED in (8,9,10,11), PESA.BDDESCRICAO, SA.BDDESCSUBAPU) BDDESCSUBAPU, ';
  wsql = wsql || 'T.BDALIQICMS, INF1250.BDCODAJUR BDMOTIVO, ';
  wsql = wsql || 'T.BDSEMANA ';

  wsql = wsql || 'from VW_VEF_EMP_TICMSSPEDGERUNION T';


  wsql = wsql||' left outer join VW_VEF_BASE_TEMPPARFED empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;
  wsql = wsql||' left outer join vw_tempresas_ref emp on (emp.bdcodemp = t.bdcodemp ) ' ;
  wsql = wsql||' left outer join TUF UF on (UF.bdcodUF = t.bdcodUF ) ' ;

  wsql = wsql||' LEFT OUTER JOIN VEF_BASE_TTIPOSUBAPURACAO SA ON (SA.BDCODSUBAPU = T.BDCODSUBAPU) ';
  wsql = wsql||' LEFT OUTER JOIN VEF_BASE_TTAB_4_7_1 PESA ON (PESA.BDCODSUBAPURACAO = T.BDCODSUBAPU) ';

  wsql = wsql||' left outer join VEF_BASE_TCONFICMSSPEDQ TCONF on (TCONF.bdcodqICMSSPED = t.bdcodqICMSSPED ) ' ;

  wsql = wsql||' left outer join VEF_BASE_TCONFICMSSPED_1250 TCONF1250 on (TCONF1250.BDNUMCAMPO = T.BDNUMCAMPO) ' ;

  wsql = wsql||' left outer join VEF_BASE_TCONFICMSSPEDFORM TCONFICMSSPEDFORM on (TCONFICMSSPEDFORM.bdcodconfICMSSPED = empresas.bdcodconfICMSSPED  and TCONFICMSSPEDFORM.bdcodqICMSSPED = T.BDCODQICMSSPED  and TCONFICMSSPEDFORM.bdnumcampoICMSSPED = T.BDNUMCAMPO) ' ;
  wsql = wsql||' left outer join VEF_BASE_TTABINFAD57 INF1250 ON (INF1250.BDORDEM57 = T.BDMOTIVO)';


  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;


  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODQICMSSPED = '||:prcodquadro;

    END

  IF (:prcodperiodo IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||'('||:prcodperiodo||')';
    END

  IF( (:pruf IS NOT NULL) AND (:pruf <> 0)) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||' T.BDCODUF = '||:prUF;
    END
  ELSE
    BEGIN
      IF (:prgeral = 2) THEN--por estado
        BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||' T.BDCODUF is not null ';
        END
    END

  --1920 - Elizeu - 02-05-19 - Sped Fiscal - 1900 - Apuração 1920 #94663 #95664 #94887 #97315 #94831 #94830 #98311
  IF( (:prcodsubapu IS NOT NULL) AND (:prcodsubapu <> 0)) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||' T.bdcodsubapu = '||:prcodsubapu;
    END

  --1975
  IF( (:PRALIQICMS IS NOT NULL) AND (:PRALIQICMS <> 0)) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||' T.BDALIQICMS = '||:PRALIQICMS;
    END


  IF( (:PRSEMANA IS NOT NULL) AND (:PRSEMANA <> 0)) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wWhere||' T.BDSEMANA = '||:PRSEMANA;
    END

  /* ConfiguraÃ§Ã£o 89 e 90 - E310 Ã© por estado */
  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';
  ELSE
     wwhere = wwhere||' where ';
  wwhere = wWhere||' (((TCONF.BDCODTIPO <> 89) or ((TCONF.BDCODTIPO = 89) and (T.BDCODUF is not null))) and '||
                   '  ((TCONF.BDCODTIPO <> 90) or ((TCONF.BDCODTIPO = 90) and (T.BDCODUF is not null))))  ';


  IF (((:pruf IS NOT NULL) AND (:pruf <> 0)) OR (:prgeral = 2)) THEN
     BEGIN
       --sol:10913 - se tiver UF então nesse momento não deve levar os valores agregados
       WVALAGRE = '';
     END
  ELSE
     BEGIN
  --sol:10913 - juntar os valores agregados
  WVALAGRE = ' union all ';

  IF ((WEXPACUMULADODEZ = 'TRUE') AND (WMESREF = 12)) THEN
     WVALAGRE = WVALAGRE || ' select t.BDCODEMP, emp.BDNOMEMP, empresas.bdcodconfICMSSPED, NULL bdreflan, 999 BDCODPERIODO, t.bdcodcid BDNUMCAMPO, ';
  ELSE
  WVALAGRE = WVALAGRE || ' select t.BDCODEMP, emp.BDNOMEMP, empresas.bdcodconfICMSSPED, t.bdreflan, 999 BDCODPERIODO, t.bdcodcid BDNUMCAMPO, ';

  WVALAGRE = WVALAGRE || ' q.bdcodqicmssped, q.bddescqICMSSPED, cid.bdnomcid bddescformICMSSPED, COALESCE(SUM(t.bdvalor),0) bdvalor, 1 BDNUMITEM, q.bdclassificacao, ';
  WVALAGRE = WVALAGRE || ' null BDCODUF, null BDSIGLAUF, (iif(UF.BDSIGLAUF = ''SC'',NULL,VA.BDCODTIPOVALAGRE)) BDCODTIPOVALAGRE, (iif(UF.BDSIGLAUF = ''SC'',NULL,VA.BDDESCRICAO)) BDDESCRICAO, ';
  WVALAGRE = WVALAGRE || ' q.BDCODTIPO,NULL BDCODSUBAPU,NULL BDDESCSUBAPU, null BDALIQICMS, NULL BDMOTIVO, NULL BDSEMANA from VEF_EMP_TMOVVALAGRE1400 t ';
  WVALAGRE = WVALAGRE || ' left outer join VW_VEF_BASE_TEMPPARFED empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;
  WVALAGRE = WVALAGRE || ' left outer join vw_tempresas_ref emp on (emp.bdcodemp = t.bdcodemp ) ';
  WVALAGRE = WVALAGRE || ' left outer join vef_base_tconficmsspedq q on (q.bdcodqicmssped = 4) ';
  WVALAGRE = WVALAGRE || ' left outer join tcidade cid on (cid.bdcodcid = t.bdcodcid) ';
  WVALAGRE = WVALAGRE || ' left outer join TUF UF on (CID.BDCODUF = UF.BDCODUF) ';
  WVALAGRE = WVALAGRE || ' left outer join VEF_BASE_TTABTIPOVALAGRE va on (va.bdcodtipovalagre = t.bdcodtipovalagre) ';
  --WVALAGRE = WVALAGRE || ' where u.bdcodemp = '+wEmpTreeView+' and u.BDREFLAN >= '+wRefTreeView+' and u.BDREFLAN <= '+wRefTreeView;

  IF (:PRCODEMP IS NOT NULL) THEN
     WVALAGRE = WVALAGRE || ' where ' || :PRCODEMP;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (WVALAGRE <> '') THEN
          WVALAGRE = WVALAGRE || ' and ';
       ELSE
          WVALAGRE = WVALAGRE || ' where ';

       IF ((WEXPACUMULADODEZ = 'TRUE') AND (WMESREF = 12)) THEN
         WVALAGRE = WVALAGRE || 't.BDREFLAN >= ' || SUBSTRING(:pranomesinicial FROM 1 FOR 4) || '01';
       ELSE
       WVALAGRE = WVALAGRE || 't.BDREFLAN >= ' || :pranomesinicial;

       IF (WVALAGRE <> '') THEN
          WVALAGRE = WVALAGRE || ' and ';

       IF ((WEXPACUMULADODEZ = 'TRUE') AND (WMESREF = 12)) THEN
         WVALAGRE = WVALAGRE || 't.BDREFLAN <= ' || SUBSTRING(:pranomesfinal FROM 1 FOR 4) || '12';
       ELSE
       WVALAGRE = WVALAGRE || 't.BDREFLAN <= ' || :pranomesfinal;
     END

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
       IF (WVALAGRE <> '') THEN
          WVALAGRE = WVALAGRE||' and ';
       ELSE
          WVALAGRE = WVALAGRE||' where ';

       WVALAGRE = WVALAGRE||'q.BDCODQICMSSPED = '||:prcodquadro;
    END
    IF ((WEXPACUMULADODEZ = 'TRUE') AND (WMESREF = 12)) THEN
         WVALAGRE = WVALAGRE || 'group by T.BDCODEMP, EMP.BDNOMEMP, EMPRESAS.BDCODCONFICMSSPED, BDREFLAN, BDCODPERIODO, BDNUMCAMPO, Q.BDCODQICMSSPED, ';
    ELSE
         WVALAGRE = WVALAGRE || 'group by T.BDCODEMP, EMP.BDNOMEMP, EMPRESAS.BDCODCONFICMSSPED, T.BDREFLAN, BDCODPERIODO, BDNUMCAMPO, Q.BDCODQICMSSPED, ';

    WVALAGRE = WVALAGRE || 'Q.BDDESCQICMSSPED, BDDESCFORMICMSSPED, BDNUMITEM, Q.BDCLASSIFICACAO, BDCODUF, BDSIGLAUF, bdcodtipovalagre, bddescricao, q.BDCODTIPO, bdcodsubapu,BDDESCSUBAPU,BDALIQICMS, bdmotivo, BDSEMANA ';

    END

  WVALAGRE = WVALAGRE || ')';

--  if (:prgeral = 2) then--por estado
--    begin
--      wsql = wsql || ' group by'
      if (PRCODQUADRO = 13) then
         wsql = wsql || wwhere || WVALAGRE || ' order by bdcodemp, bdreferencia desc, bdCODPERIODO,BDCODQICMSSPED, BDSEMANA, bdcoduf, bdcodtipovalagre,bdcodsubapu,BDALIQICMS, bdmotivo, bdnumcampo ';
      else
         wsql = wsql || wwhere || WVALAGRE || ' order by bdcodemp, bdreferencia desc, bdCODPERIODO,BDCODQICMSSPED, BDSEMANA, bdcoduf, bdcodtipovalagre,bdcodsubapu,BDALIQICMS, bdnumcampo, bdmotivo';
--    end
--  else
---    wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia ,bdCODPERIODO, BDCODQICMSSPED, bdnumcampo' ;


  wREFANT         = 0;
  prquadroant     = 0;
  wufANT          = 0;
  wcodaubapuant   = 0;
  wTIPOVA         = 0;
  WALIQICMS       = 0;
  WMOTIVO         = '0';
  wSEMANA         = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp,
    bdcodconf,
    BDREFERENCIA,
    BDCODPERIODO,
    BDNUMCAMPO,
    bdcodquadro,
    bddescquadro,
    bddescform,
    BDVALOR,
    BDNUMITEM,
    BDCLASSIFICACAO,
    bdcoduf,
    BDSIGLAUF,
    bdcodtipovalagre,
    bddescricao,
    BDCODTIPO,
    BDCODSUBAPU,
    BDDESCSUBAPU,
    BDALIQICMS,
    BDMOTIVO,
    BDSEMANA
  DO
  BEGIN
    prnumcampo = bdnumcampo;
    prdescform = bddescform;
    wvalor = bdvalor;

    --Referência
    IF ((prGeral = 1) AND (wREFANT <> bdreferencia) AND (pranomesinicial <> pranomesfinal)) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  CAST(bdreferencia AS VARCHAR(6));
        bddescform =  SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
        BDVALOR = NULL;
        --wREFANT = bdreferencia;
        SUSPEND;
      END

    --Quadro
    IF (/*(prGeral = 1) AND *Precisa levar a descrição do quadro nas apurações por UF também* */
        (prquadroant <> bdcodquadro)) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  BDDESCQUADRO;
        BDVALOR = NULL;
        --prquadroant = bdcodquadro;
        SUSPEND;
        --estado                   --acho que pode deixar aparecendo o estado
        IF ((bdcoduf IS NOT NULL)/* and (pruf = 0)*/)THEN
          BEGIN
            BDDESCFORM =  bdsiglauf;
            SUSPEND;
          END
        --1920 - Elizeu - 02-05-19 - Sped Fiscal - 1900 - Apuração 1920 #94663 #95664 #94887 #97315 #94831 #94830 #98311
--        IF ((BDALIQICMS IS NOT NULL)) THEN
--          BEGIN
--            BDDESCFORM =  BDALIQICMS;
--            SUSPEND;
--          END
        IF ((bdcodsubapu IS NOT NULL) AND (BDCODTIPO not in (149)))THEN
          BEGIN
            BDDESCFORM =  bddescsubapu;
            SUSPEND;
          END

        --tipo valor agregado
        IF ((bdcodtipovalagre IS NOT NULL))THEN
          BEGIN
            BDDESCFORM =  bdcodtipovalagre || ' - ' || bddescricao;
            SUSPEND;
          END
      END

    --estado
    IF (((prGeral = 2) OR (BDCODTIPO = 89) OR (BDCODTIPO = 90)) AND (wufant <> bdcoduf) AND (prquadroant = bdcodquadro)) THEN /* AQUI */
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  bdsiglauf;
        BDVALOR = NULL;
        SUSPEND;
      END
    --1920 - Elizeu - 02-05-19 - Sped Fiscal - 1900 - Apuração 1920 #94663 #95664 #94887 #97315 #94831 #94830 #98311
    IF (((prGeral = 2) OR (BDCODTIPO in (144,147,148,150))) AND (BDCODTIPO not in (149)) and (wcodaubapuant <> bdcodsubapu) AND (prquadroant = bdcodquadro)) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  bddescsubapu;
        BDVALOR = NULL;
        SUSPEND;
      END

    --aliq
    IF (((prGeral = 2) OR (BDCODTIPO in (149))) AND ((waliqicms <> bdaliqicms) or ((wcodaubapuant <> bdcodsubapu) and (waliqicms = bdaliqicms)) )) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  BDALIQICMS;
        BDVALOR = NULL;
        SUSPEND;
      END

    --Camilla M. Código Motivo - Apuração 1250 - ST - RS
    IF ((BDCODTIPO = 152) AND (WMOTIVO <> BDMOTIVO) /*AND (prquadroant = bdcodquadro)*/) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  BDMOTIVO;
        BDVALOR = NULL;
        WMOTIVO   = BDMOTIVO;
        SUSPEND;
      END

    --tipo valor agregado
    IF ((prGeral = 1) AND (wtipova <> bdcodtipovalagre) AND (prquadroant = bdcodquadro)) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM = bdcodtipovalagre || ' - ' || bddescricao;
        BDVALOR = NULL;
        SUSPEND;
      END

    IF ( (BDCODQUADRO = 2) AND (BDSEMANA IS NOT NULL) AND (WSEMANA <> BDSEMANA)) THEN
      BEGIN
        bdnumcampo = NULL;
        BDDESCFORM =  'Semana ' || CAST(BDSEMANA AS VARCHAR(1));
        BDVALOR = NULL;
        SUSPEND;
      END

/*
    --Período
    if (((prcodperiodoant <> bdcodperiodo) or ((prquadroant <> bdcodquadro) and (prcodperiodoant = bdcodperiodo))) and (bdCodperiodo in (2,3,4,5,6))) then
      begin
        bdnumcampo = null;
        if (bdcodperiodo = 2) then
           BDDESCFORM =  '1º decêndio';
        else
        if (bdcodperiodo = 3) then
           BDDESCFORM =  '2º decêndio';
        else
        if (bdcodperiodo = 4) then
           BDDESCFORM =  '3º decêndio';
        else
        if (bdcodperiodo = 5) then
           BDDESCFORM =  '1ª quinzena';
        else
        if (bdcodperiodo = 6) then
           BDDESCFORM =  '2ª quinzena';

        BDVALOR = null;
        --prcodperiodoant = bdcodperiodo;
        suspend;
      end            */

    bdnumcampo = prnumcampo;
    bddescform = prdescform;
    bdvalor = wvalor;

    wREFANT = bdreferencia;
    prquadroant = bdcodquadro;

    wufANT  = bdcoduf;
    wcodaubapuant  = bdcodsubapu;
    wTIPOVA = bdcodtipovalagre;
    waliqicms = bdaliqicms;
    wSEMANA = BDSEMANA;


    SUSPEND;

  END

END^

/* Restore proc. body: SP_VEF_TREEVIEW_CONS_IMPOSTOS */
create or alter procedure SP_VEF_TREEVIEW_CONS_IMPOSTOS (
    PRCODEMP varchar(10000),
    PRANOMESINICIAL integer,
    PRANOMESFINAL integer,
    PRCODPERIODO varchar(1000),
    PRCODQUADRO integer,
    PRGERAL integer,
    PRSIGLAIMPOSTO varchar(10))
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCONF integer,
    BDREFERENCIA integer,
    BDCODPERIODO integer,
    BDNUMCAMPO integer,
    BDCODQUADRO integer,
    BDDESCQUADRO varchar(80),
    BDDESCFORM varchar(60),
    BDVALOR numeric(15,8),
    BDANOMESINICIAL integer,
    BDANOMESFINAL integer,
    BDCLASSIFICACAO varchar(10))
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WREFANT integer;
declare variable WQUADROANT integer;
declare variable WNUMCAMPO integer;
declare variable WDESCFORM varchar(60);
declare variable WVALOR numeric(15,8);
declare variable WCODPERIODOANT integer;
declare variable WCAMPOQUADRO varchar(20);
declare variable WCAMPODESCQ varchar(20);
declare variable WCAMPOCONF varchar(20);
declare variable WCAMPONUMCAMPO varchar(20);
declare variable WCAMPODESCF varchar(20);
declare variable WCODEMPSO integer;
declare variable WCODCONFIRLP integer;
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA (prAnoMesInicial, NULL, NULL);

  /* SP Padrao para montar a treeview dos impostos que sao iguais... ex IRLP, COFINS, PIS */
  wCampoQuadro   = 'BDCODQ'||prSiglaImposto||' ';
  wCampoDescQ    = 'BDDESCQ'||prSiglaImposto||' ';
  wCampoConf     = 'BDCODCONF'||prSiglaImposto||' ';
  wCampoNumCampo = 'BDNUMCAMPO'||prSiglaImposto||' ';
  wCampoDescF    = 'BDDESCFORM'||prSiglaImposto||'';

  IF (prSiglaImposto = 'BLOCOM') THEN -- Alt.: 14060 - Campos das tabelas do Bloco M
    BEGIN
      wCampoQuadro   = 'BDCODQUADRO ';
      wCampoDescQ    = 'BDDESCQUADRO ';
      wCampoConf     = 'BDCODCONF ';
      wCampoNumCampo = 'BDNUMCAMPO ';
      wCampoDescF    = 'BDDESCFORM ';
    END

  IF (prSiglaImposto = 'GIAST') THEN -- Campos das tabelas da GIAST
    BEGIN
      wCampoQuadro   = 'BDCODQUADRO ';
      wCampoDescQ    = 'BDDESCQGIAST ';
      wCampoConf     = 'BDCODCONFGIAST ';
      wCampoNumCampo = 'BDNUMCAMPO ';
      wCampoDescF    = 'BDDESCFORM ';
    END

  if (:prSiglaImposto = 'IRLP') then
    begin
      :wCODEMPSO = null;
      :wCODCONFIRLP = null;

      wSQL =         'select first 1 T.BDCODEMPSO, PAR.BDCODCONFIRLP ';
      wSQL = wSQL || 'from (select BDCODEMP as BDCODEMPSO, BDCODEMPSCP as BDCODEMP, BDREFEMP, BDDATAINICIAL, BDDATAFINAL ';
      wSQL = wSQL ||       'from TEMPRESAS_SCP) T ';
      wSQL = wSQL || 'inner join(select F.BDCODEMP, F.BDREFEMP ';
      wSQL = wSQL ||            'from VEF_BASE_TEMPPARFED F ';
      wSQL = wSQL ||            'where F.BDINDNATPJ = 3 and ';
      wSQL = wSQL ||                  'F.BDREFEMP = (select first 1 G.BDREFEMP ';
      wSQL = wSQL ||                                'from VEF_BASE_TEMPPARFED G ';
      wSQL = wSQL ||                                'where G.BDCODEMP = F.BDCODEMP and ';
      wSQL = wSQL ||                                      'G.BDREFEMP <= ' || :PRANOMESFINAL;
      wSQL = wSQL ||                               ' order by G.BDREFEMP desc)) FED on (T.BDCODEMPSO = FED.BDCODEMP) ';
      wSQL = wSQL || 'inner join VEF_BASE_TEMPPARGER PAR on (FED.BDCODEMP = PAR.BDCODEMP and FED.BDREFEMP = PAR.BDREFEMP) ';
      wSQL = wSQL || 'where PAR.BDCODCONFIRLP is not null and ';
      wSQL = wSQL ||       :PRCODEMP || ' and ';
      wSQL = wSQL ||       '(((select BDAAAAMM from AAAAMM(T.BDDATAINICIAL)) <= ' || :PRANOMESINICIAL || ') and ';
      wSQL = wSQL ||       '(BDDATAFINAL is null or (select BDAAAAMM from AAAAMM(T.BDDATAFINAL)) >= ' || :PRANOMESFINAL || ')) and ';
      wSQL = wSQL ||       '(T.BDREFEMP = (select first 1 Y.BDREFEMP ';
      wSQL = wSQL ||                      'from TEMPRESAS_SCP Y ';
      wSQL = wSQL ||                      'where Y.BDCODEMP = T.BDCODEMPSO and ';
      wSQL = wSQL ||                            'Y.BDCODEMPSCP = T.BDCODEMP and ';
      wSQL = wSQL ||                            'Y.BDREFEMP <= ' || :PRANOMESFINAL;
      wSQL = wSQL ||                     ' order by Y.BDREFEMP)) ';

      execute statement wSQL
      into wCODEMPSO, :wCODCONFIRLP;
    end

  wSQL =         'select t.BDCODEMP, emp.BDNOMEMP, emp.BDCODCONF'||prSiglaImposto||', t.BDREFERENCIA, t.BDCODPERIODO, tconf'||prSiglaImposto||'form.BDNUMITEM as BDNUMCAMPO, ';--alt:# 7636 não estava ordenando o campo certo
  wSQL = wSQL ||        't.'||wCampoQuadro||', tconf.'||wCampoDescq||', tconf'||prSiglaImposto||'form.'||wCampoDescF||', t.BDVALOR BDQBH, tconf.BDCLASSIFICACAO ';
  wSQL = wSQL || 'from VEF_EMP_T'||prSiglaImposto||'GERREG t ';

  if (:PRSIGLAIMPOSTO = 'IRLP') then
    BEGIN
      --WSQL = wSQL || ' left outer join TEMPRESAS_SCP SCP ON (SCP.BDCODEMPSCP = T.BDCODEMP AND (SCP.BDDATAFINAL IS NULL OR (SELECT bdAAAAMM FROM AAAAMM(SCP.BDDATAFINAL)) >= '||:prAnoMesFinal||')) ';
      /* #201598 - Estava trazendo qualquer empresa vinculada com a SCP (SO e empresas participantes), tem que trazer apenas a que é SO. Movido SQL para ser feito por fora.
      WSQL = wSQL || ' left outer join TEMPRESAS_SCP SCP on (SCP.BDCODEMPSCP = T.BDCODEMP and ';
      WSQL = wSQL ||                                       ' (SCP.BDDATAFINAL = (SELECT FIRST 1 x.bdDATAFINAL FROM TEMPRESAS_SCP x  '; -- Alt.: #165174 - Ajustado para não carregar mais de uma empresa/referência, pois isso matriciava os resultados...
      WSQL = wSQL ||                                                           ' WHERE x.bdCODEMPSCP = t.bdCODEMP  ';
      WSQL = wSQL ||                                                             ' AND (x.bdDATAFINAL IS NULL OR (SELECT BDAAAAMM FROM AAAAMM(X.BDDATAFINAL)) >= '||:prAnoMesFinal||')';
      WSQL = wSQL ||                                                             'ORDER BY x.bdREFEMP DESC))) ';*/
      
      --wSQL = wSQL || ' left outer join VW_EMP_REF_TOTAL EMP on (EMP.BDCODEMP = COALESCE(SCP.BDCODEMP,T.BDCODEMP)) ';
      if (:wCODEMPSO is null) then
        begin
          WSQL = wSQL || ' left outer join(select T.BDCODEMP, EMP_REF.BDNOMEMP, T.BDCODCONFIRLP ';
          WSQL = wSQL ||                  'from VEF_BASE_TEMPPARGER T ';
          WSQL = wSQL ||                  'inner join TEMPRESAS_REF EMP_REF on (T.BDCODEMP = EMP_REF.BDCODEMP and T.BDREFEMP = EMP_REF.BDREFEMP) ';
          WSQL = wSQL ||                  'where ' || :PRCODEMP || ' and ';
          WSQL = wSQL ||                        'T.BDREFEMP = (select first 1 X.BDREFEMP ';
          WSQL = wSQL ||                                      'from VEF_BASE_TEMPPARGER X ';
          WSQL = wSQL ||                                      'where X.BDCODEMP = T.BDCODEMP and ';
          WSQL = wSQL ||                                            'X.BDREFEMP <= ' || :PRANOMESFINAL;
          WSQL = wSQL ||                                      'order by X.BDREFEMP desc)) EMP on (EMP.BDCODEMP = T.BDCODEMP) ';
        end
      else
        begin
          WSQL = wSQL || ' left outer join(select first 1 EMP_REF.BDCODEMP, EMP_REF.BDNOMEMP, ' || :wCODCONFIRLP || ' as BDCODCONFIRLP ';
          WSQL = wSQL ||                  'from TEMPRESAS_REF EMP_REF ';
          WSQL = wSQL ||                  'where EMP_REF.BDCODEMP = ' || :wCODEMPSO || ' and ';
          WSQL = wSQL ||                        'EMP_REF.BDREFEMP <= ' || :PRANOMESFINAL;
          WSQL = wSQL ||                 ' order by EMP_REF.BDREFEMP desc) EMP on (EMP.BDCODEMP = ' || :wCODEMPSO || ') ';
        end
    END
  ELSE
    wSQL = wSQL || ' left outer join VW_EMP_REF_TOTAL emp on (emp.BDCODEMP = t.BDCODEMP) ' ;

  IF (prSiglaImposto = 'GIAST') THEN
    wSQL = wSQL || ' left outer join VEF_BASE_TCONF'||prSiglaImposto||'Q tconf on (tconf.BDCODQGIAST'||' = t.'||wCampoQuadro||') ' ;
  ELSE
    wSQL = wSQL || ' left outer join VEF_BASE_TCONF'||prSiglaImposto||'Q tconf on (tconf.'||wCampoQuadro||' = t.'||wCampoQuadro||') ' ;

  wSQL = wSQL || ' left outer join VEF_BASE_TCONF'||prSiglaImposto||'FORM tconf'||prSiglaImposto||'form on (tconf'||prSiglaImposto||'form.'||wCampoConf||' = emp.BDCODCONF'||prSiglaImposto||' and ' ;
  wSQL = wSQL || '                 tconf'||prSiglaImposto||'form.'||wCampoQuadro||' = t.'||wCampoQuadro||' and tconf'||prSiglaImposto||'form.'||wCampoNumCampo||' = t.BDNUMCAMPO) ' ;

  wWhere = '';

  IF (:prCodEmp IS NOT NULL) THEN
    wWhere = ' where '||:prCodEmp;

  IF (:prAnoMesInicial IS NOT NULL) THEN
    BEGIN
      IF (wWhere <> '') THEN
        wWhere = wWhere||' and ';
      ELSE
        wWhere = wWhere||' where ';

      wWhere = wWhere||'t.BDREFERENCIA >= '||:prAnoMesInicial;

      IF (wWhere <> '') THEN
        wWhere = wWhere||' and ';

      wWhere = wWhere||'t.BDREFERENCIA <= '||:prAnoMesFinal;
    END

  IF (:prCodQuadro IS NOT NULL) THEN
    BEGIN
      IF (wWhere <> '') THEN
        wWhere = wWhere||' and ';
      ELSE
        wWhere = wWhere||' where ';

      wWhere = wWhere||'t.'||wCampoQuadro||' = '||:prCodQuadro;
    END

  IF (:prCodPeriodo IS NOT NULL) THEN
    BEGIN
      IF (wWhere <> '') THEN
        wWhere = wWhere||' and ';
      ELSE
        wWhere = wWhere||' where ';

      wWhere = wWhere||'('||:prCodPeriodo||')';
    END

  wSQL = wSQL || wWhere || ' order by BDCODEMP, BDREFERENCIA desc, ' ||wCampoQuadro||', BDCODPERIODO, BDNUMITEM ';

  wRefAnt        = 0;
  wQuadroant     = 0;
  wCodPeriodoAnt = 0;

  FOR EXECUTE STATEMENT wSQL
  INTO
    BDCODEMP,
    BDNOMEMP,
    BDCODCONF,
    BDREFERENCIA,
    BDCODPERIODO,
    BDNUMCAMPO,
    BDCODQUADRO,
    BDDESCQUADRO,
    BDDESCFORM,
    BDVALOR,
    BDCLASSIFICACAO
  DO
  BEGIN
    BDANOMESFINAL   = prAnoMesFinal;
    BDANOMESINICIAL = prAnoMesInicial;
    wNumCampo       = BDNUMCAMPO;
    wDescForm       = BDDESCFORM;
    wValor          = BDVALOR;

    --Referência
    IF ((prGeral = 1) AND (wRefAnt <> BDREFERENCIA) AND (prAnoMesInicial <> prAnoMesFinal)) THEN
      BEGIN
        BDNUMCAMPO = NULL;
        BDDESCFORM =  CAST(BDREFERENCIA AS VARCHAR(6));
        BDDESCFORM =  SUBSTRING(BDDESCFORM FROM 5 FOR 2)||'/'||SUBSTRING(BDDESCFORM FROM 1 FOR 4);
        BDVALOR = NULL;
        --wRefAnt  = BDREFERENCIA;
        SUSPEND;
      END

    --Quadro
    IF ((prGeral = 1) AND (wQuadroAnt <> BDCODQUADRO)) THEN
      BEGIN
        BDNUMCAMPO = NULL;
        BDDESCFORM =  BDDESCQUADRO;
        BDVALOR = NULL;
        --wQuadroAnt = BDCODQUADRO;
        SUSPEND;
      END

    --Período
    IF (((wCodPeriodoAnt <> BDCODPERIODO) OR ((wQuadroAnt <> BDCODQUADRO) AND (wCodPeriodoAnt = BDCODPERIODO))) AND (BDCODPERIODO IN (2,3,4,5,6))) THEN
      BEGIN
        BDNUMCAMPO = NULL;
        IF (BDCODPERIODO = 2) THEN
           BDDESCFORM =  '1º decêndio';
        ELSE
        IF (BDCODPERIODO = 3) THEN
           BDDESCFORM =  '2º decêndio';
        ELSE
        IF (BDCODPERIODO = 4) THEN
           BDDESCFORM =  '3º decêndio';
        ELSE
        IF (BDCODPERIODO = 5) THEN
           BDDESCFORM =  '1ª quinzena';
        ELSE
        IF (BDCODPERIODO = 6) THEN
           BDDESCFORM =  '2ª quinzena';
        ELSE
        BDVALOR = NULL;
        --wCodPeriodoAnt = bdcodperiodo;
        SUSPEND;
      END

    BDNUMCAMPO = wNumCampo;
    BDDESCFORM = wDescForm;
    BDVALOR    = wValor;

    wRefAnt    = BDREFERENCIA;
    wQuadroAnt = BDCODQUADRO;
    wCodPeriodoAnt = BDCODPERIODO;

    SUSPEND;
  END
END
^

/* Restore proc. body: SP_VEF_TREEVIEW_CONS_IPI */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_IPI(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODQUADRO INTEGER,
PRGERAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(60),
BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE PRREFANT INTEGER;
DECLARE VARIABLE PRNUMCAMPO INTEGER;
DECLARE VARIABLE PRDESCFORM VARCHAR(60);
DECLARE VARIABLE PRVALOR NUMERIC(15,6);
BEGIN
    EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);
  
    wSql = 'select TIPIGERREG.BDCODEMP, ';
    wSql = wSql ||'temp.BDNOMEMP, ';
    wSql = wSql ||'temp.BDCODCONFIPI, ';
    wSql = wSql ||'TIPIGERREG.BDREFERENCIA, ';
    wSql = wSql ||'TIPIGERREG.BDCODPERIODO, ';
    wSql = wSql ||'TIPIGERREG.BDNUMCAMPO, ';
    wSql = wSql ||'TIPIGERREG.BDCODQIPI, ';
    wSql = wSql ||'TCONFIPIQ.bddescqipi, ';
    wSql = wSql ||'TCONFIPIFORM.bddescformipi, ';
    wSql = wSql ||'TIPIGERREG.BDVALOR ';
    wSql = wSql ||'from VEF_EMP_TIPIGERREG TIPIGERREG ';

    wSql = wsql||'left outer join SP_CONSULTAEMPRESAS_SIS('|| pranomesfinal || ', TIPIGERREG.bdcodemp, null) temp on (temp.bdcodemp = TIPIGERREG.bdcodemp ) ' ;
    wSql = wsql||'left outer join VEF_BASE_TCONFIPIQ TCONFIPIQ on (TCONFIPIQ.bdcodqipi = TIPIGERREG.bdcodqipi ) ' ;
    wSql = wsql||'left outer join VEF_BASE_TCONFIPIFORM TCONFIPIFORM on (TCONFIPIFORM.bdcodconfipi = temp.bdcodconfipi and TCONFIPIFORM.bdcodqipi = TIPIGERREG.BDCODQIPI  and TCONFIPIFORM.bdnumcampoipi = TIPIGERREG.BDNUMCAMPO) ' ;

    wwhere = '';
  
    IF (:PRCODEMP IS NOT NULL) THEN
       wwhere = ' where '||:PRCODEMP;

    IF (:pranomesinicial IS NOT NULL) THEN
       BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
         ELSE
            wwhere = wwhere||' where ';
  
         wwhere = wwhere||'TIPIGERREG.BDREFERENCIA >= '||:pranomesinicial;
  
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
  
         wwhere = wwhere||'TIPIGERREG.BDREFERENCIA <= '||:pranomesfinal;
       END

    IF (:prcodquadro IS NOT NULL) THEN
      BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
         ELSE
            wwhere = wwhere||' where ';
  
         wwhere = wwhere||'TIPIGERREG.BDCODQIPI = '||:prcodquadro;
      END


    wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, bdnumcampo' ;
  
    prrefant = 0;
  
    FOR EXECUTE STATEMENT wsql
    INTO
      bdcodemp,
      bdnomemp,
      bdcodconf,
      bdreferencia,
      bdcodperiodo,
      bdnumcampo,
      bdcodquadro,
      bddescquadro,
      bddescform,
      bdvalor
    DO
    BEGIN
      prnumcampo = bdnumcampo;
      prdescform = bddescform;
      prvalor = bdvalor;
  
      IF ((prGeral = 1) AND (prrefant <> bdreferencia)) THEN
        BEGIN
          bdnumcampo = 0;
          bddescform = CAST(bdreferencia AS VARCHAR(6));
          bddescform = SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
          bdvalor  = 0;
          prrefant = bdreferencia;
          SUSPEND;
        END
  
      bdnumcampo = prnumcampo;
      bddescform = prdescform;
      bdvalor = prvalor;
  
      SUSPEND;
    END
  END
^

/* Restore proc. body: SP_VEF_TREEVIEW_CONS_IRLP */
ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_IRLP(PRCODEMP VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRCODQUADRO INTEGER,
PRGERAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCONF INTEGER,
BDREFERENCIA INTEGER,
BDCODPERIODO INTEGER,
BDNUMCAMPO INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDDESCFORM VARCHAR(60),
BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE PRREFANT INTEGER;
DECLARE VARIABLE PRNUMCAMPO INTEGER;
DECLARE VARIABLE PRDESCFORM VARCHAR(60);
DECLARE VARIABLE PRVALOR NUMERIC(15,6);
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  wsql = 'select T.BDCODEMP, '||
                 'empresas.BDNOMEMP, '||
                 'empresas.BDCODCONFIRLP,'||
                'T.BDREFERENCIA, '||
                'T.BDCODPERIODO, '||
                'T.BDNUMCAMPO, '||
                'T.BDCODQIRLP, '||
                'TCONFIRLPQ.bddescqirlp,'||
                'TCONFIRLPFORM.bddescformirlp,'||
                'T.BDVALOR '||
                'BDQBH '||
                'from VEF_EMP_TIRLPGERREG T';


  wsql = wsql||' left outer join SP_CONSULTAEMPRESAS_SIS('|| pranomesfinal || ', t.bdcodemp, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;
  wsql = wsql||' left outer join VEF_BASE_TCONFIRLPQ TCONFIRLPQ on (TCONFIRLPQ.bdcodqirlp = t.bdcodqirlp ) ' ;
  wsql = wsql||' left outer join VEF_BASE_TCONFIRLPFORM TCONFIRLPFORM on (TCONFIRLPFORM.bdcodconfirlp = empresas.bdcodconfirlp  and TCONFIRLPFORM.bdcodqirlp = T.BDCODQIRLP  and TCONFIRLPFORM.bdnumcampoirlp = T.BDNUMCAMPO) ' ;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = ' where '||:PRCODEMP;


  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDCODQIRLP = '||:prcodquadro;

    END


  wsql = wsql||wwhere || ' order by bdcodemp, bdreferencia desc, bdnumcampo' ;

  prrefant = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp,
    bdcodconf,
    BDREFERENCIA,
    BDCODPERIODO,
    BDNUMCAMPO,
    bdcodquadro,
    bddescquadro,
    bddescform,
    BDVALOR
  DO
  BEGIN

    prnumcampo = bdnumcampo;
    prdescform = bddescform;
    prvalor = bdvalor;


    IF ((prGeral = 1) AND (prrefant <> bdreferencia)) THEN
      BEGIN
        bdnumcampo = 0;
        BDDESCFORM =  CAST(bdreferencia AS VARCHAR(6));
        bddescform =  SUBSTRING(bddescform FROM 5 FOR 2)||'/'||SUBSTRING(bddescform FROM 1 FOR 4);
        BDVALOR = 0;
        prrefant = bdreferencia;
        SUSPEND;
      END

    bdnumcampo = prnumcampo;
    bddescform = prdescform;
    bdvalor = prvalor;

    SUSPEND;




  END




END
^

/* Restore proc. body: SP_VEF_TREEVIEW_CONSUF_GIASP */
CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONSUF_GIASP (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRNATENTSAI INTEGER,
    PRPREFIXONAT INTEGER,
    PRSIGLAUF VARCHAR(2))
RETURNS (
    BDCODEMP INTEGER,
    BDREFERENCIA INTEGER,
    BDNUMCAMPO INTEGER,
    BDSIGLAUF VARCHAR(2),
    BDPREFIXONAT INTEGER,
    BDDESCRICAO VARCHAR(100),
    BDVALOR NUMERIC(18,6))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WVLRCONTAB NUMERIC(18,6);
DECLARE VARIABLE WBASEICMS NUMERIC(18,6);
DECLARE VARIABLE WVLRICMS NUMERIC(18,6);
DECLARE VARIABLE WOUTRASICMS NUMERIC(18,6);
DECLARE VARIABLE WVLRST NUMERIC(18,6);
DECLARE VARIABLE WOUTROSIMPOSTOS NUMERIC(18,6);
DECLARE VARIABLE WNUMCAMPO INTEGER;
DECLARE VARIABLE WVLRCONTAB2 NUMERIC(18,6);
DECLARE VARIABLE WBASEICMS2 NUMERIC(18,6);
DECLARE VARIABLE WSUFIXO VARCHAR(3);
BEGIN

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA (PRREFERENCIA);


  if (prnatentsai = 2) then/* Elizeu - 09-10-18 - Separada o sql de entrada com o da saída - NOVA GIA CR 14 Entradas #88630*/
    begin
      wSQL =         'select BDCODEMP, BDREFERENCIA, BDSIGLAUF, BDNUMCAMPO, BDPREFIXONAT, BDDESCRICAO, sum(0) as BDVALOR, ';
      wSQL = wSQL ||       '       sum(iif(BDISENTO = ''FALSE'', BDVLRCONTAB, 0)) as BDVLRCONTAB, ';
      wSQL = wSQL ||       '       sum(iif(BDISENTO = ''FALSE'', BDBASEICMS, 0)) as BDBASEICMS, sum(BDVLRICMS) as BDVLRICMS, ';
      wSQL = wSQL ||       '       sum(BDOUTRASICMS) as BDOUTRASICMS, sum(BDVLRST) as BDVLRST, sum(BDOUTROSIMPOSTOS) as BDOUTROSIMPOSTOS, ';
      wSQL = wSQL ||       '       sum(iif(BDISENTO = ''TRUE'', BDVLRCONTAB, 0)) as BDVLRCONTAB2, ';
      wSQL = wSQL ||       '       sum(iif(BDISENTO = ''TRUE'', BDBASEICMS, 0)) as BDBASEICMS2 ';
      wSQL = wSQL ||       'from ( ';
      wSQL = wSQL ||       '     select I.BDCODEMP, MOV.BDREFLAN as BDREFERENCIA, null as BDNUMCAMPO, null as BDDESCRICAO, null as BDVALOR, ';
      wSQL = wSQL ||       '             I.BDPREFIXONAT, sum(coalesce(I.BDVLRCONTAB, 0)) as BDVLRCONTAB, ';
      wSQL = wSQL ||       '             sum(coalesce(I.BDBASEICMS, 0)) as BDBASEICMS, SUM(COALESCE(IIF(UFEMP.BDFCPOP = ''TRUE'', COALESCE(I.BDVLRICMS,0) + COALESCE(I.BDVLRFCP,0), COALESCE(I.BDVLRICMS,0)), 0)) AS BDVLRICMS, ';
      wSQL = wSQL ||       '             sum(coalesce(I.BDOUTRASICMS, 0)) as BDOUTRASICMS, sum(coalesce(I.BDVLRST, 0) + COALESCE(I.BDFCPRETIDO, 0)) as BDVLRST, ';
      wSQL = wSQL ||       '             sum(coalesce(0, 0)) as BDOUTROSIMPOSTOS, ';
      --wSQL = wSQL ||       '             IIF(uf.bdsiglauf <> ''SP'',uf.bdsiglauf,IIF(UfGRF.bdsiglauf IS NOT NULL and UfGRF.bdsiglauf <> ''SP'',UfGRF.bdsiglauf,ufD100.bdsiglauf)) bdsiglauf, ';
      wSQL = wSQL ||       '             iif(uf.bdSIGLAUF <> ''SP'', uf.bdSIGLAUF, ';
      wSQL = wSQL ||       '                 iif(ufgrf.bdSIGLAUF IS NOT NULL and ufgrf.bdSIGLAUF <> ''SP'', ufgrf.bdSIGLAUF, ';
      wSQL = wSQL ||       '                     iif(ufd100.bdSIGLAUF IS NOT NULL and ufd100.bdSIGLAUF <> ''SP'', ufd100.bdSIGLAUF, ufd100orig.bdSIGLAUF))) BDSIGLAUF, ';
      wSQL = wSQL ||       '             iif(TER.BDIETER = ''ISENTO'', ''TRUE'', ''FALSE'') as BDISENTO ';
      wSQL = wSQL ||       '      from ( ';
      wSQL = wSQL ||       '            select M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, M.BDCODTER, M.BDCODSITNF,G.bdcodterent,D.BDCIDDEST BDCIDDESTD100, d.bdCIDORIGEM bdCIDORIGD100 ';
      wSQL = wSQL ||       '            from VEF_EMP_TMOVENT M ';
      wSQL = wSQL ||       '            LEFT OUTER JOIN VEF_EMP_TMOVENTGRF g on (m.bdcodemp = g.bdcodemp and m.bdchave = g.bdchave) ';
      wSQL = wSQL ||       '            left outer join VEF_EMP_TD100ENT d on (m.bdcodemp = d.bdcodemp and m.bdchave = d.bdchave) ';
      wSQL = wSQL ||       '            WHERE m.bdCODEMP = '||:PRCODEMP;
      wSQL = wSQL ||       '            AND m.bdREFLAN = '||:PRREFERENCIA;
      wSQL = wSQL ||       '            and M.BDCODSITNF not in (2, 3, 4, 5) ';
      wSQL = wSQL ||       '            )MOV ';
      wSQL = wSQL ||       '      left outer join VEF_EMP_TMOVENTITENS I on (MOV.BDCODEMP = I.BDCODEMP and MOV.BDCHAVE = I.BDCHAVE) ';
      wSQL = wSQL ||       '      LEFT OUTER JOIN VW_TEMPRESAS_REF EMPREF ON (EMPREF.BDCODEMP = MOV.BDCODEMP AND EMPREF.BDREFEMP <= MOV.BDREFLAN) ';
      wSQL = wSQL ||       '      LEFT OUTER JOIN TCIDADE CIDEMP ON (CIDEMP.BDCODCID = EMPREF.BDCODCID) ';
      wSQL = wSQL ||       '      LEFT OUTER JOIN TUF UFEMP ON(UFEMP.BDCODUF = CIDEMP.BDCODUF) ';
      wSQL = wSQL ||       '      left outer join VW_TTERCEIRO TER on (TER.BDCODTER = MOV.BDCODTER) ';
      wSQL = wSQL ||       '      left outer join TCIDADE CID on (CID.BDCODCID = TER.BDCODCID) ';
      wSQL = wSQL ||       '      left outer join TUF UF on (UF.BDCODUF = CID.BDCODUF) ';
      wSQL = wSQL ||       '      LEFT OUTER JOIN VW_TTERCEIRO terGRF ON (MOV.bdcodterent = terGRF.bdcodter) ';
      wSQL = wSQL ||       '      LEFT OUTER JOIN TCIDADE CIDGRF ON (CIDGRF.bdcodcid = terGRF.bdcodcid) ';
      wSQL = wSQL ||       '      LEFT OUTER JOIN TUF ufGRF ON (ufGRF.bdcoduf = CIDGRF.bdcoduf) ';
      wSQL = wSQL ||       '      LEFT OUTER JOIN TCIDADE CIDD100 ON (CIDD100.bdcodcid = MOV.BDCIDDESTD100) ';
      wSQL = wSQL ||       '      LEFT OUTER JOIN TUF ufD100 ON (ufD100.bdcoduf = CIDD100.bdcoduf) ';
      wSQL = wSQL ||       '      LEFT OUTER JOIN TCIDADE cidd100orig ON (cidd100orig.bdCODCID = mov.bdCIDORIGD100) '; -- Alt.: #123606 - Incluido a verificação da cidade de origem para o R14...
      wSQL = wSQL ||       '      LEFT OUTER JOIN TUF ufD100orig ON (ufD100orig.bdCODUF = cidd100orig.bdCODUF) ';
      wSQL = wSQL ||       '      where ((uf.bdSIGLAUF <> ''SP'') or ';
      wSQL = wSQL ||       '             ((ufgrf.bdSIGLAUF IS NOT NULL) and (ufgrf.bdSIGLAUF <> ''SP'')) or ';
      wSQL = wSQL ||       '             ((ufD100.bdSIGLAUF IS NOT NULL) and (ufD100.bdSIGLAUF <> ''SP'')) or ';
      wSQL = wSQL ||       '             ((ufD100orig.bdSIGLAUF IS NOT NULL) and (ufD100orig.bdSIGLAUF <> ''SP''))) ';
      wSQL = wSQL ||       '      AND i.bdPREFIXONAT = '||:PRPREFIXONAT;
      wSQL = wSQL ||       '      GROUP by I.BDCODEMP, MOV.BDREFLAN, CID.BDCODUF, BDSIGLAUF, I.BDCODNAT, I.BDDIGOPERNAT, I.BDPREFIXONAT, BDISENTO ';
      wSQL = wSQL ||       '      order by I.BDCODEMP, MOV.BDREFLAN, CID.BDCODUF, I.BDCODNAT, I.BDDIGOPERNAT, I.BDPREFIXONAT ';
      wSQL = wSQL ||       '      ) AUX ';
      wSQL = wSQL ||       '   WHERE bdSIGLAUF = '''||:PRSIGLAUF||'''';
      wSQL = wSQL ||       '  AND bdPREFIXONAT = '||:PRPREFIXONAT;
      wSQL = wSQL ||       'GROUP by BDCODEMP, BDREFERENCIA, BDSIGLAUF, BDNUMCAMPO, BDPREFIXONAT, BDDESCRICAO ';
    end
  else
    begin
      wSQL =         'SELECT bdCODEMP, bdREFERENCIA, bdSIGLAUF, bdNUMCAMPO, bdPREFIXONAT, bdDESCRICAO, SUM(0) as bdVALOR, ';
      wSQL = wSQL ||       ' SUM(IIF(bdISENTO = '''||'FALSE'||''', bdVLRCONTAB, 0)) as bdVLRCONTAB, ';
      wSQL = wSQL ||       ' SUM(IIF(bdISENTO = '''||'FALSE'||''', bdBASEICMS, 0)) as bdBASEICMS, ';
      wSQL = wSQL ||       ' SUM(bdVLRICMS) as bdVLRICMS, SUM(bdOUTRASICMS) as bdOUTRASICMS, SUM(bdVLRST) as bdVLRST, SUM(bdOUTROSIMPOSTOS) as bdOUTROSIMPOSTOS, ';
      wSQL = wSQL ||       ' SUM(IIF(bdISENTO = '''||'TRUE'||''', bdVLRCONTAB, 0)) as bdVLRCONTAB2, ';
      wSQL = wSQL ||       ' SUM(IIF(bdISENTO = '''||'TRUE'||''', bdBASEICMS, 0)) as bdBASEICMS2 ';
      wSQL = wSQL || 'FROM ( ';
    
      IF (PRNATENTSAI = 2) THEN
         wSufixo = 'ENT';
      ELSE
         wSufixo = 'SAI';
    
      wSQL = wSQL ||        'SELECT i.bdCODEMP, mov.bdREFLAN as bdREFERENCIA, NULL as bdNUMCAMPO, NULL as bdDESCRICAO, NULL as bdVALOR, i.bdPREFIXONAT, ';
      wSQL = wSQL ||               'SUM(COALESCE(i.bdVLRCONTAB, 0)) as bdVLRCONTAB, SUM(COALESCE(i.bdBASEICMS, 0)) as bdBASEICMS, ';
      wSQL = wSQL ||               'SUM(COALESCE(IIF(UFEMP.BDFCPOP = ''TRUE'', COALESCE(I.BDVLRICMS,0) + COALESCE(I.BDVLRFCP,0), COALESCE(I.BDVLRICMS,0)), 0)) AS BDVLRICMS, SUM(COALESCE(i.bdOUTRASICMS, 0)) as bdOUTRASICMS, ';
      wSQL = wSQL ||               'SUM(COALESCE(i.bdVLRST, 0) + COALESCE(I.BDFCPRETIDO, 0)) as bdVLRST, SUM(COALESCE(0, 0)) as bdOUTROSIMPOSTOS, ';
      IF (wSufixo = 'ENT') THEN
        BEGIN
          wSQL = wSQL ||              'uf.bdSIGLAUF, ';
          wSQL = wSQL ||              'IIF(ter.bdIETER = ''ISENTO'', ''TRUE'', ''FALSE'') as bdISENTO ';
        END
      ELSE
      IF (wSufixo = 'SAI') THEN
        BEGIN
          wSQL = wSQL ||              'IIF(uf.bdSIGLAUF <> ''SP'', uf.bdSIGLAUF, COALESCE(ufD160.bdSIGLAUF, uf.bdSIGLAUF)) AS bdSIGLAUF, ';
          wSQL = wSQL ||              'IIF(uf.bdSIGLAUF <> ''SP'', IIF(ter.bdIETER = ''ISENTO'', ''TRUE'', ''FALSE''), ';
          wSQL = wSQL ||              '    IIF(cidd160.bdCODUF > 0, IIF(terd160.bdIETER = ''ISENTO'', ''TRUE'', ''FALSE''), IIF(ter.bdIETER = ''ISENTO'', ''TRUE'', ''FALSE''))) AS bdISENTO ';
        END
      wSQL = wSQL ||        'FROM ( ';
      wSQL = wSQL ||               'SELECT m.bdCODEMP, m.bdCHAVE, m.bdREFLAN, m.bdCODTER, m.bdCODSITNF ';
      IF (wSufixo = 'SAI') THEN
        BEGIN
          wSQL = wSQL ||                      ', m.bdCODCID, ';
          wSQL = wSQL ||                      'IIF(ciddest.bdCODUF <> 26, d160.bdCODTERDESTINATARIO, d160.bdCODTERREMETENTE) AS bdCODTERD160, ';
          wSQL = wSQL ||                      'IIF(ciddest.bdCODUF <> 26, Coalesce(D160.BDCODCIDDESTINATARIO,D100.BDCIDDEST), Coalesce(D160.BDCODCIDREMETENTE,D100.BDCIDORIGEM)) AS bdCODCIDD160 ';
        END
      wSQL = wSQL ||               'FROM VEF_EMP_TMOV'||:wSufixo||' m ';
      IF (wSufixo = 'SAI') THEN
        BEGIN
          wSQL = wSQL ||               'LEFT OUTER JOIN VEF_EMP_TD100SAI D100 ON (M.BDCODEMP = D100.BDCODEMP and M.BDCHAVE = D100.BDCHAVE) ';
          wSQL = wSQL ||               'LEFT OUTER JOIN VEF_EMP_TD160CARGATRANS d160 ON (m.bdCODEMP = d160.bdCODEMP AND m.bdCHAVE = d160.bdCHAVE) ';
          wSQL = wSQL ||               'LEFT OUTER JOIN TCIDADE ciddest ON (ciddest.bdCODCID = Coalesce(D160.BDCODCIDDESTINATARIO,D100.BDCIDDEST)) ';
        END
      wSQL = wSQL ||               'WHERE m.bdCODEMP = '||:PRCODEMP;
      wSQL = wSQL ||                 'AND m.bdREFLAN = '||:PRREFERENCIA;
      wSQL = wSQL ||               ') mov ';
      wSQL = wSQL ||        'LEFT OUTER JOIN VEF_EMP_TMOV'||:wSufixo||'ITENS i ON (mov.bdCODEMP = i.bdCODEMP AND mov.bdCHAVE = i.bdCHAVE) ';
      wSQL = wSQL ||        'LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.bdCODTER = mov.bdCODTER) ';
      if (wSufixo = 'ENT') then
        wSQL = wSQL ||      'LEFT OUTER JOIN TCIDADE cid ON (cid.bdCODCID = ter.bdCODCID) ';
      else
      if (wSufixo = 'SAI') then
        wSQL = wSQL ||      'LEFT OUTER JOIN TCIDADE cid ON (cid.bdCODCID = mov.bdCODCID) ';
    
      wSQL = wSQL ||        'LEFT OUTER JOIN TUF uf ON (uf.bdCODUF = cid.bdCODUF) ';
      if (wSufixo = 'SAI') then
        begin
          wSQL = wSQL ||    'LEFT OUTER JOIN VW_TTERCEIRO terD160 ON (terD160.bdCODTER = mov.bdCODTERD160) ';
          wSQL = wSQL ||    'LEFT OUTER JOIN TCIDADE cidD160 ON (cidD160.BDCODCID = mov.bdCODCIDD160) ';
          wSQL = wSQL ||    'LEFT OUTER JOIN TUF ufD160 ON (ufD160.BDCODUF = cidD160.bdCODUF) ';
          wSQL = wSQL ||    'LEFT OUTER JOIN VW_TEMPRESAS_REF EMPREF ON (EMPREF.BDCODEMP = MOV.BDCODEMP AND EMPREF.BDREFEMP <= MOV.BDREFLAN) ';
          wSQL = wSQL ||    'LEFT OUTER JOIN TCIDADE CIDEMP ON (CIDEMP.BDCODCID = EMPREF.BDCODCID)  ';
          wSQL = wSQL ||    'LEFT OUTER JOIN TUF UFEMP ON(UFEMP.BDCODUF = CIDEMP.BDCODUF)  ';
        end
      wSQL = wSQL ||        'WHERE (mov.bdCODSITNF NOT IN (2,3,4,5)) ';
      IF (wSufixo = 'ENT') THEN
        wSQL = wSQL ||        'AND uf.bdSIGLAUF <> ''SP'' ';
      ELSE
      IF (wSufixo = 'SAI') THEN
         wSQL = wSQL ||       'AND ((uf.bdSIGLAUF <> ''SP'') OR (ufD160.bdSIGLAUF <> ''SP'')) ';         
      wSQL = wSQL ||          'AND i.bdPREFIXONAT = '||:PRPREFIXONAT;
      wSQL = wSQL ||        'GROUP BY i.bdCODEMP, mov.bdREFLAN, cid.bdCODUF, bdSIGLAUF, i.bdCODNAT, i.bdDIGOPERNAT, i.bdPREFIXONAT, bdISENTO ';
      wSQL = wSQL ||        'ORDER BY i.bdCODEMP, mov.bdREFLAN, cid.bdCODUF, i.bdCODNAT, i.bdDIGOPERNAT, i.bdPREFIXONAT ';
    
      wSQL = wSQL || ') aux ';
      wSQL = wSQL || 'WHERE bdSIGLAUF = '''||:PRSIGLAUF||'''';
      wSQL = wSQL || '  AND bdPREFIXONAT = '||:PRPREFIXONAT;
      wSQL = wSQL || 'group by BDCODEMP, BDREFERENCIA, BDSIGLAUF, BDNUMCAMPO, BDPREFIXONAT, BDDESCRICAO ';
    
    end
  WNUMCAMPO = 0;

  FOR EXECUTE STATEMENT wSQL
  INTO
    BDCODEMP ,
    BDREFERENCIA,
    BDSIGLAUF,
    BDNUMCAMPO,
    BDPREFIXONAT,
    BDDESCRICAO,
    BDVALOR,
    wVLRCONTAB,
    wBASEICMS,
    wVLRICMS,
    wOUTRASICMS,
    wVLRST,
    wOUTROSIMPOSTOS,
    wVLRCONTAB2,
    wBASEICMS2
  DO
  BEGIN
    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;
    BDVALOR = wVLRCONTAB;
    BDDESCRICAO = 'Valor contábil de contribuinte';
    SUSPEND;

    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;

    BDVALOR = wBASEICMS;
    BDDESCRICAO = 'Base de cálculo de contribuinte';
    SUSPEND;

    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;

    BDVALOR = wVLRCONTAB2;
    BDDESCRICAO = 'Valor contábil de não contribuinte';
    SUSPEND;

    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;

    BDVALOR = wBASEICMS2;
    BDDESCRICAO = 'Base de cálculo de não contribuinte';
    SUSPEND;

    --

    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;

    BDVALOR = wVLRICMS;
    BDDESCRICAO = 'Imposto creditado ou debitado';
    SUSPEND;

    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;

    BDVALOR = wOUTRASICMS;
    BDDESCRICAO = 'Outros valores';
    SUSPEND;

    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;

    BDVALOR = wVLRST;
    BDDESCRICAO = 'ICMS cobrado por substituição tributária';
    SUSPEND;

    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;

    IF (PRNATENTSAI = 2) THEN
      BEGIN
        BDVALOR = wVLRST;
        --BDVALOR = wICMSRET;
        BDDESCRICAO = 'Petróleo energia / outros';
        SUSPEND;
      END

    WNUMCAMPO = WNUMCAMPO + 1;
    bdnumcampo = WNUMCAMPO;

    BDVALOR = wOUTROSIMPOSTOS;
    BDDESCRICAO = 'Outros produtos';
    SUSPEND;

  END

END^

/* Restore proc. body: SP_VERIFICATODASVERBASEMPPADRAO */
ALTER PROCEDURE SP_VERIFICATODASVERBASEMPPADRAO AS
DECLARE VARIABLE WCODEMP INTEGER;
BEGIN
  FOR SELECT BDCODEMP FROM TEMPRESAS INTO :wcodemp DO
    BEGIN
      EXECUTE PROCEDURE sp_vrh_verificaverbasemp_padrao(:wcodemp);
    END
END
^

/* Restore proc. body: SP_VRH_APAGACALCULOS */
ALTER PROCEDURE SP_VRH_APAGACALCULOS(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRCODAUT INTEGER,
PRREF INTEGER,
PRREFPAG INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
BEGIN
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     BEGIN
       /*
          FOLHA COMPLEMENTAR
        */

       wsql = 'delete from VRHF_EMP_TFOLHACOMP where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREFFN = '||prref;

       IF (prrefpag IS NOT NULL AND prrefpag <> 0) THEN
          wsql = wsql||' and BDREFCOMP = '||prrefpag;

       EXECUTE STATEMENT wsql;


       /*
          FOLHA COMPLEMENTAR POR TOMADOR
        */

       wsql = 'delete from VRHF_EMP_TFOLTOMCOMP where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREFTOMADOR = '||prref;

       IF (prrefpag IS NOT NULL AND prrefpag <> 0) THEN
          wsql = wsql||' and BDREFCOMP = '||prrefpag;

       EXECUTE STATEMENT wsql;


       /*
          FOLHA NORMAL
        */

       wsql = 'delete from VRHF_EMP_TFOLHANORMAL where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREFFN = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          FOLHA NORMAL POR TOMADOR
        */

       wsql = 'delete from VRHF_EMP_TFOLHATOMADOR where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREFTOMADOR = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          ADIANTAMENTO SALARIAL
        */

       wsql = 'delete from VRHF_EMP_TADSAL where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREFAD = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          FÉRIAS
        */

       wsql = 'delete from VRH_EMP_TFERIAS where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and ((BDREFINIFE = '||prref||') or (BDREFFIMFE = '||prref||'))';

       EXECUTE STATEMENT wsql;


       /*
          COMPLEMENTO DE 13º SALÁRIO
        */

       wsql = 'delete from VRHF_EMP_TC13SAL where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREFC13 = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          13º SALÁRIO
        */

       wsql = 'delete from VRHF_EMP_T13SAL where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREF13 = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          ADIANTAMENTO DE 13º SALÁRIO
        */

       wsql = 'delete from VRHF_EMP_TA13SAL where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREFA13 = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          FOLHA DE AUTÔNOMOS
        */

       wsql = 'delete from VRHF_BASE_CALC_TERC where BDCODEMP = '||prcodemp;

       IF (prcodaut IS NOT NULL AND prcodaut <> 0) THEN
          wsql = wsql||' and BDCODTER = '||prcodaut;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREFINSSSERV = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          FOLHA AVULSA
        */

       wsql = 'delete from VRHF_EMP_TFOLHAAVULSA where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDREF = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          CÁLCULO DA PRÉVIA DE RESCISÃO
        */

       wsql = 'delete from VRHF_EMP_TFOLHANORMAL_PREV_RESC where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       EXECUTE STATEMENT wsql;

       /*
          LANÇAMENTO DA PRÉVIA DE RESCISÃO
        */

       wsql = 'delete from VRH_EMP_TRESCISAO_PREVIA where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       EXECUTE STATEMENT wsql;


       /*
          PLANILHA DA LANÇAMENTOS
        */

       wsql = 'delete from VRHF_EMP_TPLANLANC where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDCOMPLANC = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          PLANILHA DA LANÇAMENTOS ADIANTAMENTO SALARIAL
        */

       wsql = 'delete from VRHF_EMP_TPLANLANC_ADSAL where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDCOMPLANC = '||prref;

       EXECUTE STATEMENT wsql;


       /*
          PLANILHA DA LANÇAMENTOS FOLHA AVULSA
        */

       wsql = 'delete from VRHF_EMP_TPLANLANC_FA where BDCODEMP = '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
          wsql = wsql||' and BDCODCOL = '||prcodcol;

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and BDCOMPFA = '||prref;

       EXECUTE STATEMENT wsql;

     END
END
^

/* Restore proc. body: SP_VRH_BASE_MTE_TCONFRESC */
CREATE OR ALTER procedure SP_VRH_BASE_MTE_TCONFRESC
returns (
    BDCHAVECONF integer,
    BDDESCRICAO DM_BDDESCCONFMTE,
    BDCLASSIFICACAO DM_BDCLASSCONFMTE,
    BDIMPZERADO varchar(5),
    BDINCSUBGRUPO varchar(5),
    BDFIXA varchar(5),
    BDCODCOMPHIST integer,
    BDCLASSCONF varchar(15),
    BDPADRAO varchar(5))
as
declare variable WCLASS varchar(15);
declare variable WCLASS2 varchar(15);
declare variable WPOS integer;
BEGIN
  FOR SELECT BDCHAVECONF,BDDESCRICAO,BDCLASSIFICACAO,BDIMPZERADO,BDINCSUBGRUPO,BDFIXA,BDCODCOMPHIST,BDPADRAO FROM VRH_BASE_MTE_TCONFRESC INTO
    :BDCHAVECONF,:BDDESCRICAO,:BDCLASSIFICACAO,:BDIMPZERADO,:BDINCSUBGRUPO,:BDFIXA,:BDCODCOMPHIST,:BDPADRAO
  DO
    BEGIN
      wclass = :BDCLASSIFICACAO;
      SELECT pos FROM POS('.', :wclass) INTO :wpos;

      IF (wpos > 0) THEN
         BEGIN
           wclass2 = TRIM(SUBSTRING(wclass FROM wpos + 1 FOR strlen(wclass)));
           wclass = SUBSTRING(wclass FROM 1 FOR wpos - 1);

           WHILE (strlen(wclass2) < 4) DO
             wclass2 = '0'||wclass2;

           WHILE (strlen(wclass) < 4) DO
             wclass = '0'||wclass;

           wclass = wclass||'.'||wclass2;
         END
       ELSE
         BEGIN
           wclass = TRIM(wclass);

           WHILE (strlen(wclass) < 4) DO
             wclass = '0'||wclass;

           wclass = wclass||'.0000';
         END

       BDCLASSCONF = wclass;
      SUSPEND;
    END
END
^

/* Restore proc. body: SP_VRH_BASE_TRESPEMP_PRINCIPAL */
ALTER PROCEDURE SP_VRH_BASE_TRESPEMP_PRINCIPAL(PRCODEMP VARCHAR(25000),
PRCODRESP VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCODRESP INTEGER,
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDNOMERESP VARCHAR(40),
BDCPFRESP VARCHAR(14),
BDNITRESP VARCHAR(14),
BDDDDRESP INTEGER,
BDFONERESP DM_BDTELEFONE,
BDRAMALRESP INTEGER,
BDRGRESP VARCHAR(13),
BDPADRAORESP VARCHAR(5),
BDEMAILRESP DM_BDEMAIL)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  wsql = 'select X.BDCODEMP, '||
                'X.BDCODRESP, '||
                'X.BDCODPLAFUC, '||
                'X.BDCODTFUC, '||
                'X.BDNOMERESP, '||
                'X.BDCPFRESP, '||
                'X.BDNITRESP, '||
                'X.BDDDDRESP, '||
                'X.BDFONERESP, '||
                'X.BDRAMALRESP, '||
                'X.BDRGRESP, '||
                'X.BDPADRAORESP, '||
                'X.BDEMAILRESP '||
         'from VRH_BASE_TRESPEMP X '||
         'where ((X.BDPADRAORESP = '''||'TRUE'||''') or '||
               '(exists (select Y.BDCODEMP '||
                        'from VW_VRH_BASE_TRESPEMP_FIRST Y '||
                        'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODRESP = X.BDCODRESP) and '||
                 'not exists (select W.BDCODEMP '||
                             'from VRH_BASE_TRESPEMP W '||
                             'where W.BDCODEMP = X.BDCODEMP and W.BDPADRAORESP = '''||'TRUE'||'''))) ';
            
  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||prcodemp;

  IF (prcodresp IS NOT NULL AND prcodresp <> '') THEN
     wsql = wsql||' and '||prcodresp;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODRESP,
    :BDCODPLAFUC,
    :BDCODTFUC,
    :BDNOMERESP,
    :BDCPFRESP,
    :BDNITRESP,
    :BDDDDRESP,
    :BDFONERESP,
    :BDRAMALRESP,
    :BDRGRESP,
    :BDPADRAORESP,
    :BDEMAILRESP
  DO
  SUSPEND;
END
^

/* Restore proc. body: SP_VRH_CC_DATA */
CREATE OR ALTER PROCEDURE SP_VRH_CC_DATA (
    PRCODEMP INTEGER,
    PRCODCOL INTEGER,
    PRDATA DATE)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDDATAENTRADA DATE,
    BDORDEM INTEGER,
    BDHORAENTRADA TIME)
AS
BEGIN
  /* Procedure Text */
  bdcodemp = prcodemp;
  bdcodcol = prcodcol;

  SELECT
   cc.bdcodtpcc,
   cc.bdcodcentro,
   cc.bddataentrada,
   cc.bdordem,
   cc.bdhoraentrada
  FROM (
  SELECT cc.bdcodemp ,cc.bdcodcol, MAX(cc.bddataentrada+cc.bdhoraentrada) bddataentrada FROM vrhf_emp_tprepfn cc
  WHERE cc.bddataentrada <= :prdata AND cc.bdcodemp = :prcodemp AND cc.bdcodcol = :prcodcol
  GROUP BY cc.bdcodemp ,cc.bdcodcol
  ORDER BY cc.bdcodemp ,cc.bdcodcol, bddataentrada DESC
  ) ccmax
  JOIN vrhf_emp_tprepfn cc ON (ccmax.bdcodemp = cc.bdcodemp AND ccmax.bdcodcol = cc.bdcodcol AND ccmax.bddataentrada = cc.bddataentrada+cc.bdhoraentrada)
  INTO :bdcodtpcc,:bdcodcentro,:bddataentrada,:bdordem,:bdhoraentrada;

  SUSPEND;
END
^

/* Restore proc. body: SP_VRH_DEC_REND_7_2 */
create or alter procedure SP_VRH_DEC_REND_7_2 (
    PRCODEMP varchar(32000),
    PRCODCOL varchar(32000),
    PRANO integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDREF integer,
    BDNOME varchar(70),
    BDCPF varchar(14),
    BDCNPJ varchar(18),
    BDRAZAOSOCIAL varchar(80),
    BDVALOR numeric(18,6))
as
declare variable WDATA varchar(10);
declare variable WSQL varchar(32700);
declare variable WSQL2 varchar(8000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WCODDPN integer;
declare variable WNOMDPN varchar(70);
declare variable WCPFDPN varchar(14);
declare variable WREF integer;
declare variable WREFATU integer;
declare variable WREFIRFIR integer;
declare variable WPLANO integer;
declare variable WVALOR1 numeric(18,6);
declare variable WVALOR2 numeric(18,6);
declare variable WCNPJ varchar(18);
declare variable WRS varchar(80);
declare variable WVALPLANOFFIR numeric(18,6);
declare variable WUTILIZOUVALOR varchar(5);
declare variable WEXISTEVINCULO varchar(5);
declare variable WDESPMEDLANCVALM numeric(18,6);
declare variable WDESPMEDLANCVALC numeric(18,6);
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WTIPOFOL integer;
declare variable WUSARTMP_COL_SELECT smallint;
BEGIN

  WUSARTMP_EMP_SELECT = 0;
  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  WUSARTMP_COL_SELECT = 0;
  IF (UPPER(prCodcol) = 'TEMP_FILTRO_COLCON_REL') THEN
     WUSARTMP_COL_SELECT = 1;

  wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDREFPAG, '||
                '(select first 1 BDCODPLACONVSAU from VRHF_BASE_TEMPVINC where BDCODEMP = FOL.BDCODEMP and BDREFEMP <= FOL.BDREFFN order by BDCODEMP desc, BDREFEMP desc) BDCODPLACONVSAU, '||
                'sum(FOL.BDVALVFN) BDDESPMED, FOL.BDTIPOFOL from ('||
           'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, SUBSTRING(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) FROM 6 FOR 2) BDREFPAG, FOL.BDVALVFN, 0 BDTIPOFOL '||
           'from VRHF_EMP_TVERBAFN FOL '||
           ' join VRHF_EMP_TFOLHANORMAL FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREFFN = FOL.BDREFFN) '||
           ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) ';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
    wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

  IF (WUSARTMP_COL_SELECT = 1) THEN
      wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

  wSQL = wSQL|| 'where SUBSTRING(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) FROM 6 FOR 2) between '||prano||'01 and '||prano||'12 and '||
                 '((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodemp;

  IF ((prcodcol IS NOT NULL AND prcodcol <> '') and (WUSARTMP_COL_SELECT = 0))  THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||' union all ';
  wsql = wsql||
           'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, SUBSTRING(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) FROM 6 FOR 2) BDREFPAG, FOL.BDVALVFN, 0 BDTIPOFOL '||
           'from VRHF_EMP_TVERBAINT FOL '||
           ' join VRHF_EMP_TFOLHAINT FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREFFN = FOL.BDREFFN and FN.BDCODCONTTI = FOL.BDCODCONTTI) '||
           ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) ';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
    wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

  IF (WUSARTMP_COL_SELECT = 1) THEN
      wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

  wSQL = wSQL|| 'where SUBSTRING(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) FROM 6 FOR 2) between '||prano||'01 and '||prano||'12 and '||
                 '((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodemp;

  IF ((prcodcol IS NOT NULL AND prcodcol <> '')  AND (WUSARTMP_COL_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||' union all ';
  wsql = wsql||
           'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, SUBSTRING(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) FROM 6 FOR 2) BDREFPAG, FOL.BDVALVFT, 0 BDTIPOFOL '||
           'from VRHF_EMP_TVERBATOMADOR FOL '||
           ' join VRHF_EMP_TFOLHATOMADOR FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREFTOMADOR = FOL.BDREFTOMADOR and FN.BDORDEM = FOL.BDORDEM) '||
           ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) ';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
    wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

  IF (WUSARTMP_COL_SELECT = 1) THEN
      wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';


  wSQL = wSQL|| 'where SUBSTRING(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) FROM 6 FOR 2) between '||prano||'01 and '||prano||'12 and '||
                 '((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodemp;

  IF ((prcodcol IS NOT NULL AND prcodcol <> '')  AND (WUSARTMP_COL_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||' union all ';
  wsql = wsql||
           'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, SUBSTRING(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) FROM 6 FOR 2) BDREFPAG, FOL.BDVALVFT, 0 BDTIPOFOL '||
           'from VRHF_EMP_TVERBATOMINT FOL '||
           ' join VRHF_EMP_TFOLHATOMINT FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREFTOMADOR = FOL.BDREFTOMADOR and FN.BDORDEM = FOL.BDORDEM and FN.BDCODCONTTI = FOL.BDCODCONTTI) '||
           ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) ';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
    wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

  IF (WUSARTMP_COL_SELECT = 1) THEN
      wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

  wSQL = wSQL|| 'where SUBSTRING(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) FROM 6 FOR 2) between '||prano||'01 and '||prano||'12 and '||
                 '((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodemp;

  IF ((prcodcol IS NOT NULL AND prcodcol <> '')  AND (WUSARTMP_COL_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||' union all ';
  wsql = wsql||
           'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FN.BDREFCOMP BDREFPAG, FOL.BDVALVFC, 1 BDTIPOFOL '||
           'from VRHF_EMP_TVERBAFC FOL '||
           ' join VRHF_EMP_TFOLHACOMP FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREFFN = FOL.BDREFFN and FN.BDREFFC = FOL.BDREFFC) '||
           ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) ';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
    wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

  IF (WUSARTMP_COL_SELECT = 1) THEN
      wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

  wSQL = wSQL|| 'where FOL.BDREFCOMP between '||prano||'01 and '||prano||'12 and ((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodemp;

  IF ((prcodcol IS NOT NULL AND prcodcol <> '')  AND (WUSARTMP_COL_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||' union all ';
  wsql = wsql||
           'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FN.BDREFCOMP BDREFPAG, FOL.BDVALVFC, 1 BDTIPOFOL '||
           'from VRHF_EMP_TVERBAFCTOMADOR FOL '||
           ' join VRHF_EMP_TFOLTOMCOMP FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREFTOMADOR = FOL.BDREFTOMADOR and FN.BDREFFC = FOL.BDREFFC and FN.BDORDEM = FOL.BDORDEM) '||
           ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) ';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
    wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

  IF (WUSARTMP_COL_SELECT = 1) THEN
      wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

  wSQL = wSQL|| 'where FOL.BDREFCOMP between '||prano||'01 and '||prano||'12 and ((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodemp;

  IF ((prcodcol IS NOT NULL AND prcodcol <> '')  AND (WUSARTMP_COL_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||' union all ';
  wsql = wsql||
           'select FOL.BDCODEMP, FOL.BDCODCOL, FN.BDREFAD, FN.BDREFAD BDREFPAG, FOL.BDVALVAD, 0 BDTIPOFOL '||
           'from VRHF_EMP_TVERBAAD FOL '||
           ' join VRHF_EMP_TADSAL FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDDATAAD = FOL.BDDATAAD) '||
           ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) ';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
    wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

  IF (WUSARTMP_COL_SELECT = 1) THEN
      wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

  wSQL = wSQL|| 'where FN.BDREFAD between '||prano||'01 and '||prano||'12 and ((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodemp;

  IF ((prcodcol IS NOT NULL AND prcodcol <> '')  AND (WUSARTMP_COL_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||' union all ';
  wsql = wsql||
           'select FOL.BDCODEMP, FOL.BDCODCOL, SUBSTRING(CAST(FN.BDDATAPAGFE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPAGFE AS VARCHAR(10)) FROM 6 FOR 2) BDREFFE, SUBSTRING(CAST(FN.BDDATAPAGFE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPAGFE AS VARCHAR(10)) FROM 6 FOR 2) BDREFPAG, FOL.BDVALVFE, 0 BDTIPOFOL '||
           'from VRHF_EMP_TVERBAFE FOL '||
           ' join VRH_EMP_TFERIAS FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDINIPERAQUISFE = FOL.BDINIPERAQUISFE and FN.BDCODFE = FOL.BDCODFE) '||
           ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) ';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
    wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

  IF (WUSARTMP_COL_SELECT = 1) THEN
      wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

  wSQL = wSQL|| 'where SUBSTRING(CAST(FN.BDDATAPAGFE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPAGFE AS VARCHAR(10)) FROM 6 FOR 2) between '||prano||'01 and '||prano||'12 and '||
                '((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodemp;

  IF ((prcodcol IS NOT NULL AND prcodcol <> '')  AND (WUSARTMP_COL_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||' union all ';
  wsql = wsql||
           'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13, SUBSTRING(CAST(FN.BDDATAPGTO13 AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTO13 AS VARCHAR(10)) FROM 6 FOR 2) BDREFPAG, FOL.BDVALV13, 0 BDTIPOFOL '||
           'from VRHF_EMP_TVERBA13 FOL '||
           ' join VRHF_EMP_T13SAL FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREF13 = FOL.BDREF13) '||
           ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) ';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
    wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

  IF (WUSARTMP_COL_SELECT = 1) THEN
      wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

  wSQL = wSQL|| 'where SUBSTRING(CAST(FN.BDDATAPGTO13 AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTO13 AS VARCHAR(10)) FROM 6 FOR 2) between '||prano||'01 and '||prano||'12 and '||
                '((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodemp;

  IF ((prcodcol IS NOT NULL AND prcodcol <> '')  AND (WUSARTMP_COL_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||' union all ';
  wsql = wsql||
           'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFC13, SUBSTRING(CAST(FN.BDDATAPGTOC13 AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTOC13 AS VARCHAR(10)) FROM 6 FOR 2) BDREFPAG, FOL.BDVALVC13, 0 BDTIPOFOL '||
           'from VRHF_EMP_TVERBAC13 FOL '||
           ' join VRHF_EMP_TC13SAL FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREF13 = FOL.BDREF13 and FN.BDREFC13 = FOL.BDREFC13) '||
           ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) ';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
    wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

  IF (WUSARTMP_COL_SELECT = 1) THEN
      wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

  wSQL = wSQL|| 'where SUBSTRING(CAST(FN.BDDATAPGTOC13 AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FN.BDDATAPGTOC13 AS VARCHAR(10)) FROM 6 FOR 2) between '||prano||'01 and '||prano||'12 and ((VER.BDCLAVER starting with ''0.030.1.0'') or (VER.BDCLAVER starting with ''0.420.0.2'')) ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodemp;

  IF ((prcodcol IS NOT NULL AND prcodcol <> '')  AND (WUSARTMP_COL_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql||
         ') FOL '||
         'group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDREFPAG, BDCODPLACONVSAU, BDTIPOFOL '||
         'order by FOL.BDREFFN, FOL.BDCODEMP, FOL.BDCODCOL ';

  -- Se for apartir de 2025 vai iginorar o sql inicial, pois deve verificar todos os calculos
  if (prano >= 2025) then
     begin
       --
       wsql = 'select FOL.bdcodemp,FOL.bdcodcol, FOL.bdreftomador BDREFFN, FOL.bdrefirrfesocial, 0 BDDESPMED, 0 BDTIPOFOL '||
              ' from vrhf_emp_tfolhatomador FOL ';
       IF (WUSARTMP_EMP_SELECT = 1) THEN
         wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';
       IF (WUSARTMP_COL_SELECT = 1) THEN
           wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';
       wsql = wsql||' where fol.bdrefirrfesocial between '||prano||'01 and '||prano||'12 ';

       wsql = wsql|| ' and exists (select 1 from VRH_EMP_VINC_COL_CONV C where C.BDCODEMP = FOL.BDCODEMP and C.BDCODCOL = FOL.BDCODCOL union all '||
      ' select 1 from VRH_EMP_VINC_DEP_CONV D where D.BDCODEMP = FOL.BDCODEMP and D.BDCODCOL = FOL.BDCODCOL) ';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;
       IF ((prcodcol IS NOT NULL AND prcodcol <> '')  AND (WUSARTMP_COL_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||' union all ';
       
       wsql = wsql||' select FOL.bdcodemp,FOL.bdcodcol, FOL.bdreffn, FOL.bdrefirrfesocial, 0 BDDESPMED, 0 BDTIPOFOL '||
                    ' from VRHF_EMP_Tfolhanormal FOL ';
       IF (WUSARTMP_EMP_SELECT = 1) THEN
         wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';
       IF (WUSARTMP_COL_SELECT = 1) THEN
           wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';
       wsql = wsql||' where fol.bdrefirrfesocial between '||prano||'01 and '||prano||'12';

       wsql = wsql|| ' and exists (select 1 from VRH_EMP_VINC_COL_CONV C where C.BDCODEMP = FOL.BDCODEMP and C.BDCODCOL = FOL.BDCODCOL union all '||
      ' select 1 from VRH_EMP_VINC_DEP_CONV D where D.BDCODEMP = FOL.BDCODEMP and D.BDCODCOL = FOL.BDCODCOL) ';


       IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;
       IF ((prcodcol IS NOT NULL AND prcodcol <> '')  AND (WUSARTMP_COL_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodcol;
       
       wsql = wsql||'union all ';
       
       wsql = wsql||'select FOL.bdcodemp,FOL.bdcodcol, FOL.bdreffir BDREFFN, FOL.BDREFIRFIR, 0 BDDESPMED, 0 BDTIPOFOL '||
                    ' from VRHF_EMP_TFICHAIRRF FOL ';
       IF (WUSARTMP_EMP_SELECT = 1) THEN
         wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';
       IF (WUSARTMP_COL_SELECT = 1) THEN
           wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';
       wsql = wsql||' where fol.BDREFIRFIR between '||prano||'01 and '||prano||'12';

       wsql = wsql|| ' and exists (select 1 from VRH_EMP_VINC_COL_CONV C where C.BDCODEMP = FOL.BDCODEMP and C.BDCODCOL = FOL.BDCODCOL union all '||
      ' select 1 from VRH_EMP_VINC_DEP_CONV D where D.BDCODEMP = FOL.BDCODEMP and D.BDCODCOL = FOL.BDCODCOL) ';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;
       IF ((prcodcol IS NOT NULL AND prcodcol <> '')  AND (WUSARTMP_COL_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||'union all ';
       
       wsql = wsql||'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR BDREFFN, FOL.BDREFIRRFESOCIAL, 0 BDDESPMED, 0 BDTIPOFOL '||
                    ' from VRHF_EMP_TFOLHATOMINT FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
         wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';
       IF (WUSARTMP_COL_SELECT = 1) THEN
           wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';
       wsql = wsql||' where FOL.BDREFIRRFESOCIAL between '||prano||'01 and '||prano||'12';

       wsql = wsql|| ' and exists (select 1 from VRH_EMP_VINC_COL_CONV C where C.BDCODEMP = FOL.BDCODEMP and C.BDCODCOL = FOL.BDCODCOL union all '||
      ' select 1 from VRH_EMP_VINC_DEP_CONV D where D.BDCODEMP = FOL.BDCODEMP and D.BDCODCOL = FOL.BDCODCOL) ';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;
       IF ((prcodcol IS NOT NULL AND prcodcol <> '')  AND (WUSARTMP_COL_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodcol;

       wsql = 'select BDCODEMP, BDCODCOL, BDREFFN, BDREFIRRFESOCIAL,'||
              '(select first 1 BDCODPLACONVSAU from VRHF_BASE_TEMPVINC where BDCODEMP = FOL.BDCODEMP and BDREFEMP <= FOL.BDREFFN order by BDCODEMP desc, BDREFEMP desc) BDCODPLACONVSAU, '||
              ' sum(BDDESPMED), sum(BDTIPOFOL) from ('||wsql||
              ') FOL group by BDCODEMP, BDCODCOL, BDREFFN, BDREFIRRFESOCIAL';
     end

  wrefatu = 0;
  EXECUTE PROCEDURE sp_seta_competencia(CAST((:prano||'12') AS INTEGER), NULL, NULL);
  FOR EXECUTE STATEMENT wsql
  INTO
    :wcodemp,
    :wcodcol,
    :wref,
    :wrefirfir,
    :wplano,
    :wvalplanoffir,
    :wtipofol
  DO
    BEGIN
      IF (wPlano IS NOT NULL) THEN
         BEGIN
           wutilizouvalor = 'FALSE';
           WEXISTEVINCULO = 'FALSE';

           wsql2 = 'select X.BDCODDPN,X.BDNOME,X.BDCPF,sum(X.BDVALORMENSALIDADE) BDVALORMENSALIDADE ,sum(X.BDVALORCOPAR) BDVALORCOPAR,X.BDCNPJ,X.BDRAZAOSOCIAL '||
                   'from SP_VRH_CONVSAU_DIRF('||wcodemp||','||wcodcol||','||wref||','||wplano||','||prano||') X '||
                   'where (BDVALORMENSALIDADE) > 0 or (BDVALORCOPAR > 0) '||
                   'group by X.BDCODDPN, X.BDNOME, X.BDCPF, X.BDCNPJ, X.BDRAZAOSOCIAL ';

           IF (wrefatu <> wref) THEN
              BEGIN
                wData = SUBSTRING(''||:wref FROM 5 FOR 2)||'/01/'||SUBSTRING(''||:wref FROM 1 FOR 4);
                EXECUTE PROCEDURE sp_seta_competencia(:wref, :wData, NULL);
                wrefatu = wref;
              END
     
           FOR EXECUTE STATEMENT wsql2 INTO :wcoddpn,:wnomdpn,:wcpfdpn,:wvalor1,:wvalor2,:wcnpj,:wrs DO
             BEGIN
               bdcodemp      = wcodemp;
               bdcodcol      = wcodcol;
               bdcoddpn      = COALESCE(:wcoddpn, 0);
               bdref         = wrefirfir;
               bdnome        = wnomdpn;
               bdcpf         = COALESCE(wcpfdpn, '   .   .   -  ');
               bdcnpj        = wcnpj;
               bdrazaosocial = wrs;

               if ((wtipofol = 0) or (wrefirfir >= 202501))  then
                 bdvalor       = COALESCE(:wvalor1, 0) + COALESCE(:wvalor2, 0);
               /* IF ABAIXO ATÉ 2024*/
               else if (wtipofol = 1) then
                 begin
                   bdvalor        = COALESCE(wvalplanoffir, 0);
                   wutilizouvalor = 'TRUE';
                 end

               wexistevinculo = 'TRUE';

               /* Quando bdvalor for zero, significa que não tem valores de faixa etária dos planos de saúde lançados. 
                  Se tiver valor na ficha de IR, deve levar no primeiro plano de saúde vinculado ao funcinário. */

               /* IF ABAIXO ATÉ 2024*/
               IF ((bdvalor = 0 AND wvalplanoffir > 0 AND wutilizouvalor = 'FALSE') and (wrefirfir < 202501)) THEN
                 BEGIN
                   bdvalor = COALESCE(wvalplanoffir, 0);
                   wutilizouvalor = 'TRUE';
                 END

               SUSPEND;
             END

          /* IF ABAIXO ATÉ 2024*/
           IF ((WEXISTEVINCULO = 'FALSE') and (wrefirfir < 202501)) THEN
              BEGIN
                wsql2 = 'select first 1 X.BDCODDPN,X.BDNOME,X.BDCPF,X.BDCNPJ,X.BDRAZAOSOCIAL '||
                        ' from SP_VRH_CONVSAU_DIRF('||wcodemp||','||wcodcol||','||wref||',0,'||prano||') X ';

                FOR EXECUTE STATEMENT wsql2 INTO :wcoddpn,:wnomdpn,:wcpfdpn,:wcnpj,:wrs DO
                  BEGIN
                    bdcodemp      = wcodemp;
                    bdcodcol      = wcodcol;
                    bdcoddpn      = COALESCE(:wcoddpn, 0);
                    bdref         = wrefirfir;
                    bdnome        = wnomdpn;
                    bdcpf         = COALESCE(wcpfdpn, '   .   .   -  ');
                    bdcnpj        = wcnpj;
                    bdrazaosocial = wrs;
     
                    /* Quando bdvalor for zero, significa que não tem valores de faixa etária dos planos de saúde lançados. 
                       Se tiver valor na ficha de IR, deve levar no primeiro plano de saúde vinculado ao funcinário. */
                    bdvalor = COALESCE(wvalplanoffir, 0);
                    wutilizouvalor = 'TRUE';

                    SUSPEND;
                  END
              END
         END
    END

/*  wsql = 'select distinct INF.BDCODEMP,INF.BDCODCOL,INF.BDREF,INF.BDREFPAG,INF.BDDESPMED,EMPRH.BDCODPLACONVSAU '||
         'from SP_VRHF_DADOS_IR_DIRF(';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||''''||prcodemp||''',';
  ELSE
     wsql = wsql||'null,';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||''''||prcodcol||''',';
  ELSE
     wsql = wsql||'null,';

  wsql = wsql||prano||'01,'||prano||'12) INF ';
  wsql = wsql||'join VW_VRHF_BASE_TEMPVINC EMPRH on (EMPRH.BDCODEMP = INF.BDCODEMP) ';

  wsql = wsql||'where (INF.BDDESPMED > 0 and INF.BDTIPO >= 9000) ';

  wsql = wsql||'order by INF.BDREF,INF.BDCODEMP,INF.BDCODCOL ';
  */

  if (prano < 2025) then
     begin
       wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFIR, FOL.BDREFIRFIR, FOL.BDDESPMEDFIR, EMPRH.BDCODPLACONVSAU '||
              'from VRHF_EMP_TFICHAIRRF FOL '||
              'left outer join VW_VRHF_BASE_TEMPVINC EMPRH on (EMPRH.BDCODEMP = FOL.BDCODEMP) ';
     
       IF (WUSARTMP_EMP_SELECT = 1) THEN
         wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';
     
       IF (WUSARTMP_COL_SELECT = 1) THEN
           wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';
     
       wSQL = wSQL|| 'where FOL.BDREFIRFIR between '||prano||'01 and '||prano||'12 and FOL.BDDESPMEDFIR > 0 ';
     
       IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF ((prcodcol IS NOT NULL AND prcodcol <> '')  AND (WUSARTMP_COL_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||
              'order by FOL.BDREFFIR, FOL.BDCODEMP, FOL.BDCODCOL ';
     
       wrefatu = 0;
       EXECUTE PROCEDURE sp_seta_competencia(CAST((:prano||'12') AS INTEGER), NULL, NULL);
       FOR EXECUTE STATEMENT wsql
       INTO
         :wcodemp,
         :wcodcol,
         :wref,
         :wrefirfir,
         :wvalplanoffir,
         :wplano
       DO
         BEGIN
           IF (wPlano IS NOT NULL) THEN
              BEGIN
                wutilizouvalor = 'FALSE';
                WEXISTEVINCULO = 'FALSE';
     
                wsql2 = 'select X.BDCODDPN, X.BDNOME, X.BDCPF, X.BDVALORMENSALIDADE, X.BDVALORCOPAR, Y.BDCNPJ, Y.BDRAZAOSOCIAL '||
                        'from SP_VRHM_EMP_VAL_TOD_OP_ATU('||wcodemp||','||wcodcol||','||wref||','||wplano||') X '||
                        'join VRH_BASE_TCONVSAUDE Y on (Y.BDCODCONVENIO = X.bdcodoperadora) '||
                        'where (X.BDVALORMENSALIDADE > 0 or X.BDVALORCOPAR > 0) '||
                        'and not exists (select FN.BDCODEMP, FN.BDCODCOL from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = X.BDCODEMP and FN.BDCODCOL = X.BDCODCOL and FN.BDREFFN = '||wref||') '||
                        'and not exists (select FT.BDCODEMP, FT.BDCODCOL from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = X.BDCODEMP and FT.BDCODCOL = X.BDCODCOL and FT.BDREFTOMADOR = '||wref||') '||
                        'and not exists (select FN.BDCODEMP, FN.BDCODCOL from VRHF_EMP_TFOLHAINT FN where FN.BDCODEMP = X.BDCODEMP and FN.BDCODCOL = X.BDCODCOL and FN.BDREFFN = '||wref||') '||
                        'and not exists (select FT.BDCODEMP, FT.BDCODCOL from VRHF_EMP_TFOLHATOMINT FT where FT.BDCODEMP = X.BDCODEMP and FT.BDCODCOL = X.BDCODCOL and FT.BDREFTOMADOR = '||wref||') '
                        ;
     
                IF (wrefatu <> wref) THEN
                   BEGIN
                     wData = SUBSTRING(''||:wref FROM 5 FOR 2)||'/01/'||SUBSTRING(''||:wref FROM 1 FOR 4);
                     EXECUTE PROCEDURE sp_seta_competencia(:wref, :wData, NULL);
                     wrefatu = wref;
                   END
     
                wdespmedlancvalm = 0;
                wdespmedlancvalc = 0;
                SELECT SUM(COALESCE(BDVALORMENSALIDADE, 0)) BDVALORMENSALIDADE, SUM(COALESCE(BDVALORCOPAR, 0)) BDVALORCOPAR
                FROM SP_VRHM_EMP_VAL_TOD_OP_ATU(:wcodemp, :wcodcol, :wref)
                GROUP BY BDCODEMP, BDCODCOL INTO wdespmedlancvalm, wdespmedlancvalc;
     
     --           IF (wdespmedlancvalm + wdespmedlancvalc = wvalplanoffir) THEN
                IF (wvalplanoffir > 0) THEN
                  BEGIN
                    FOR EXECUTE STATEMENT wsql2 INTO :wcoddpn,:wnomdpn,:wcpfdpn,:wvalor1,:wvalor2,:wcnpj,:wrs DO
                      BEGIN
                        bdcodemp      = wcodemp;
                        bdcodcol      = wcodcol;
                        bdcoddpn      = COALESCE(:wcoddpn, 0);
                        bdref         = wrefirfir;
                        bdnome        = wnomdpn;
                        bdcpf         = COALESCE(wcpfdpn, '   .   .   -  ');
                        bdcnpj        = wcnpj;
                        bdrazaosocial = wrs;
                        bdvalor     = COALESCE(:wvalor1, 0) + COALESCE(:wvalor2, 0);
         
                        --wexistevinculo = 'TRUE';
         
                        /* Quando bdvalor for zero, significa que não tem valores de faixa etária dos planos de saúde lançados. 
                           Se tiver valor na ficha de IR, deve levar no primeiro plano de saúde vinculado ao funcinário. */
                        /*IF (bdvalor = 0 AND wutilizouvalor = 'FALSE') THEN
                          BEGIN
                            bdvalor = COALESCE(wvalplanoffir, 0);
                            wutilizouvalor = 'TRUE';
                          END*/
         
                        SUSPEND;
                      END
                  END
                ELSE
                  BEGIN
                    wsql2 = 'select first 1 X.BDCODDPN,X.BDNOME,X.BDCPF,conv.BDCNPJ,conv.BDRAZAOSOCIAL '||
                            ' from ( '||
                            ' select cast(null as integer) BDCODDPN, colcad.bdnomcol BDNOME, doc.bdcpfcol bdcpf, vc.bdcodoperadora BDCODCONVENIO, vc.bdcodemp,vc.bdcodcol,vc.bdrefini '||
                            ' from VRH_EMP_VINC_COL_CONV vc '||
                            ' join vrh_emp_tcolcon col on (vc.bdcodemp = col.bdcodemp and vc.bdcodcol = col.bdcodcol) '||
                            ' join vrh_emp_tcolcon_doc doc on (vc.bdcodemp = doc.bdcodemp and vc.bdcodcol = doc.bdcodcol) '||
                            ' left outer join vw_vrh_emp_tcolcon_cad colcad on (colcad.bdcodemp = vc.bdcodemp and colcad.bdcodcol = vc.bdcodcol) '||
                            ' where vc.bdcodemp = '||wcodemp||' and vc.bdcodcol = '||wcodcol||' and '||
                            '       vc.bdrefini <= '||:wref||' and (vc.bdreffim >= '||:wref||' or vc.bdreffim is null or vc.bdreffim = 0)'||
                            ' union all '||
                            ' select dep.bdcoddpn, dep.bdnomedpn, dep.bdcpfdpn, dc.bdcodoperadora BDCODCONVENIO, dc.bdcodemp,dc.bdcodcol,dc.bdrefini from VRH_EMP_VINC_DEP_CONV dc '||
                            ' join vw_vrh_emp_tdep_ref dep on (dc.bdcodemp = dep.bdcodemp and dc.bdcodcol = dep.bdcodcol and dc.bdcoddpn = dep.bdcoddpn) '||
                            ' where dc.bdcodemp = '||wcodemp||' and dc.bdcodcol = '||wcodcol||' and '||
                            '       dc.bdrefini <= '||:wref||' and (dc.bdreffim >= '||:wref||' or dc.bdreffim is null or dc.bdreffim = 0) '||
                            ' ) X '||
                            ' join VRH_BASE_TCONVSAUDE conv on (conv.BDCODCONVENIO = x.BDCODCONVENIO) '||
                            'where '||
                            ' not exists (select FN.BDCODEMP, FN.BDCODCOL from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = X.BDCODEMP and FN.BDCODCOL = X.BDCODCOL and FN.BDREFFN = '||wref||') '||
                            'and not exists (select FT.BDCODEMP, FT.BDCODCOL from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = X.BDCODEMP and FT.BDCODCOL = X.BDCODCOL and FT.BDREFTOMADOR = '||wref||') '||
                            ' order by X.BDCODEMP, X.BDCODCOL, X.BDCODDPN, X.BDCODCONVENIO ';
     
                    FOR EXECUTE STATEMENT wsql2 INTO :wcoddpn,:wnomdpn,:wcpfdpn,:wcnpj,:wrs DO
                      BEGIN
                        bdcodemp      = wcodemp;
                        bdcodcol      = wcodcol;
                        bdcoddpn      = COALESCE(:wcoddpn, 0);
                        bdref         = wrefirfir;
                        bdnome        = wnomdpn;
                        bdcpf         = COALESCE(wcpfdpn, '   .   .   -  ');
                        bdcnpj        = wcnpj;
                        bdrazaosocial = wrs;
          
                        /* Quando bdvalor for zero, significa que não tem valores de faixa etária dos planos de saúde lançados.
                           Se tiver valor na ficha de IR, deve levar no primeiro plano de saúde vinculado ao funcinário. */
                        bdvalor = COALESCE(wvalplanoffir, 0);
                        wutilizouvalor = 'TRUE';
     
                        SUSPEND;
                      END
                  END
              END
         END
     end

  EXECUTE PROCEDURE sp_seta_competencia(CAST((:prano||'12') AS INTEGER), NULL, NULL);
END^


/* Restore proc. body: SP_VRH_DECLARACAO_RENDIMENTOS_7_PLANOSAUDE */
create or alter procedure SP_VRH_DECLARACAO_RENDIMENTOS_7_PLANOSAUDE (
    PRCODEMP varchar(32000),
    PRCODCOL varchar(32000),
    PRANO integer,
    PREXPORTACAO integer = 0,
    PRPENSAORRA boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDTIPOCALCFIR integer,
    BDINFORMACAO varchar(250),
    BDVALOR numeric(18,6),
    BDCPFCOL varchar(14),
    BDCPFBENEF varchar(14),
    BDTIPOIMP integer,
    BDVALOR2 numeric(18,6),
    BDTITCOL varchar(100),
    BDTITCOL2 varchar(100))
as
declare variable WSQL varchar(10000);
declare variable WCODDPN integer;
declare variable WNOMDPN varchar(70);
declare variable WCPFDPN varchar(14);
declare variable WVALDPN numeric(18,6);
declare variable WVALREND numeric(18,6);
declare variable WDESCREND varchar(200);
declare variable WCNPJ varchar(18);
declare variable WRS varchar(80);
declare variable WNRBENEF varchar(20);
declare variable WVALDPN2 numeric(18,6);
declare variable WREFPAG integer;
declare variable WRENDISENTOS numeric(18,6);
declare variable WRENDTRIB numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WOK integer;
declare variable WTOTRENDISENTOS numeric(18,6);
declare variable WTIPOFIR integer;
declare variable WDESCRENDATU varchar(300);
declare variable WPREVPRIV numeric(18,6);
declare variable WPRIVATU numeric(18,6);
declare variable WDTNASC date;
declare variable WDTNASCS varchar(10);
declare variable WSQL2 varchar(5000);
declare variable WTOTABONO numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WCNPJEMP varchar(18);
declare variable WNOMEMP varchar(100);
declare variable WIR numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WCOUNT integer;
declare variable WDESCANT varchar(300);
declare variable WDESCANT2 varchar(300);
declare variable WSQLAUXSOCIO varchar(32000);
declare variable WCODEMPSOCIO integer;
declare variable WCODCOLSOCIO integer;
declare variable WCODDEPSOCIO integer;
declare variable WCODCONVENIOSOCIO integer;
declare variable WVALORPLANO numeric(18,2);
declare variable WMESMACONSULTA varchar(100);
declare variable WWHERENOTCODEMP varchar(3200) = '';
declare variable WWHERENOTSOCIOS varchar(3200) = '';
declare variable WWHERENOTCONVENIO varchar(3200) = '';
declare variable WCNPJAUX varchar(18);
declare variable WRSAUX varchar(70);
declare variable WCPFAUX varchar(14);
declare variable WNOMEAUX varchar(70);
declare variable WVALORAUX numeric(18,2);
declare variable WCODDEPAUX integer;
declare variable WPREMPAUX varchar(32000);
declare variable WPRCOLAUX varchar(32000);
declare variable WCODCOLAUX integer;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WNMRPROC varchar(300);
declare variable WJAIMPRIMIUINFDEP boolean;
declare variable WVALOR numeric(15,2);
declare variable WREFERENCIASPROC varchar(300);
declare variable WMESMACONSULTA2 varchar(500);
declare variable WCODOPERADORA integer;
declare variable WINFREEMBOLSOTIT varchar(300);
declare variable WINFREEMBOLSODEP varchar(300);
declare variable WVALREEMBOLSO numeric(15,2);
declare variable WVALREEMBOLSORRA numeric(15,2);
declare variable WMESMOGRUPOPLANOSAUDE varchar(100);
declare variable WCPFANT varchar(20);
declare variable WSEPERAREEMBOLSO integer;
declare variable WORIGEM integer;
declare variable WOPERADORA integer;
declare variable WPRESTADOR varchar(100);
declare variable WNOMEOPARADORA varchar(100);
declare variable WQUEBRATITULO varchar(300);
declare variable WQUEBRACOLABORADOR varchar(300);
declare variable WQUEBRAOPERADORA varchar(300);
declare variable WIMPTITDEP integer;
begin
  /* Procedure Text */
--  suspend;
  BDTIPOIMP = 0; /*0 = Normal; 1 = Negrito Titulos; 2 = Sem Campo valor*/

  WUSARTMP_EMP_SELECT = 0;
  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  WUSARTMP_COL_SELECT = 0;
  IF (UPPER(prCodcol) = 'TEMP_FILTRO_COLCON_REL') THEN
     WUSARTMP_COL_SELECT = 1;

  IF (PREXPORTACAO = 0) THEN -- Quando for exportação não precisa levar a descrição do plano de saúde Almir 16/02/2015
     BEGIN
       wsql = 'select X.BDCODEMP, X.BDCODCOL, X.BDCODDPN, X.BDNOME, X.BDCPF, X.BDCNPJ, X.BDRAZAOSOCIAL, SUM(X.BDVALOR) BDVALOR from SP_VRH_DEC_REND_7_2(';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||''''||prcodemp||''',';
       ELSE
          wsql = wsql||'null,';
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||''''||prcodcol||''',';
       ELSE
          wsql = wsql||'null,';
     
       wsql = wsql||prano||') X group by X.BDCODEMP,X.BDCODCOL,X.BDCODDPN,X.BDNOME,X.BDCPF,X.BDCNPJ,X.BDRAZAOSOCIAL ';
     
       wsql = wsql||' order by X.BDCODEMP,X.BDCNPJ,X.BDCODCOL,X.BDCODDPN,X.BDCPF,X.BDNOME,X.BDRAZAOSOCIAL ';

       wmesmaconsulta = '';
       WMESMACONSULTA2 = '';
       bdvalor         = 0;
       WJAIMPRIMIUINFDEP = False;
       bdtipocalcfir= 35;
       FOR EXECUTE STATEMENT wsql
       INTO
         :bdcodemp, :bdcodcol, :bdcoddpn, :wnomdpn, :wcpfdpn, :wcnpj, :wrs, :wvaldpn
       DO
         BEGIN

           if (wmesmaconsulta <>  (bdcodemp||'|'||bdcodcol||'|'||bdcoddpn||'|'||wcnpj)) then
             begin
               wcodempsocio = NULL;
               wcodcolsocio = NULL;
               wcodconveniosocio = NULL;
               wvalorplano = NULL;
               /* Alt.: #199903 - O campo "SOC.BDCODDEP" estava sobrando ali na consulta...
               WSQLAUXSOCIO = 'select SOC.BDCODEMP, SOC.BDCODSOC, SOC.BDCODDEP, SOC.BDCODCONVENIO, SOC.BDVALORPLANO, SOC.BDCODCOL from SP_DECLARARENDPLANSAU_SOCIO('||''''||'SOC.BDCODEMP = '||bdcodemp||'''';*/
               WSQLAUXSOCIO = 'select SOC.BDCODEMP, SOC.BDCODSOC, SOC.BDCODCONVENIO, SUM(SOC.BDVALORPLANO) BDVALORPLANO, SOC.BDCODCOL from SP_DECLARARENDPLANSAU_SOCIO('||''''||'SOC.BDCODEMP = '||bdcodemp||'''';
               WSQLAUXSOCIO = WSQLAUXSOCIO ||', null, '||PRANO||', '||''''||'FALSE'||''''||', '||''''''||', '||''''''||', '||''''''||', '||bdcoddpn||', '||''''||wcnpj||''''||', '||''''||wcpfdpn||''''||') SOC ';
               WSQLAUXSOCIO = WSQLAUXSOCIO ||' group by SOC.BDCODEMP, SOC.BDCODSOC, SOC.BDCODCONVENIO, SOC.BDCODCOL ';


               execute statement wsqlauxsocio into :wcodempsocio, :wcodcolsocio, :wcodconveniosocio, :wvalorplano, :wcodcolaux;
               wmesmaconsulta = (bdcodemp||'|'||bdcodcol||'|'||bdcoddpn||'|'||wcnpj);

               if ((wwherenotcodemp = '') and (wcodempsocio is not null)) then
                 wwherenotcodemp = wcodempsocio;
               else
               if ((wwherenotcodemp <> '') and (wcodempsocio is not null)) then
                 wwherenotcodemp = wwherenotcodemp || ', ' || wcodempsocio;

               if ((WWHERENOTSOCIOS = '') and (wcodcolsocio is not null)) then
                 WWHERENOTSOCIOS = wcodcolsocio;
               else
               if ((WWHERENOTSOCIOS <> '') and (wcodcolsocio is not null)) then
                 WWHERENOTSOCIOS = WWHERENOTSOCIOS || ', ' || wcodcolsocio;

               if ((WWHERENOTCONVENIO = '') and (wcodconveniosocio is not null)) then
                 WWHERENOTCONVENIO = wcodconveniosocio;
               else
               if ((WWHERENOTCONVENIO <> '') and (wcodconveniosocio is not null)) then
                 WWHERENOTCONVENIO = WWHERENOTCONVENIO || ', ' || wcodconveniosocio;

             end


            if ((WMESMACONSULTA2 <> bdcodemp||'|'||bdcodcol||'|'||wcnpj)) then
               begin
                 WJAIMPRIMIUINFDEP = False;
                 if (coalesce(WMESMOGRUPOPLANOSAUDE,'') <> bdcodemp||'|'||bdcodcol) then
                    begin
                      bdinformacao ='Pagamentos a planos de saúde:';
                      bdtipocalcfir = bdtipocalcfir + 1;
                      BDTIPOIMP = 1;
                      WMESMOGRUPOPLANOSAUDE = bdcodemp||'|'||bdcodcol;
                      SUSPEND;
                    end
                 WMESMACONSULTA2 = bdcodemp||'|'||bdcodcol||'|'||wcnpj;
                 BDTIPOIMP = 0;
                 bdinformacao ='Operadora: ' ||TRIM(:wcnpj) || ' - ' ||TRIM(:wrs);
                 bdtipocalcfir = bdtipocalcfir + 1;
--                 bdvalor = wrs;
                 SUSPEND;
                 bdvalor = 0;
               end

           if (wcodcolaux <> bdcodcol) then
             wvalorplano = 0;
           wvalor      = :wvaldpn + coalesce(:wvalorplano, 0);
           IF (bdcoddpn = 0) THEN
              begin
                bdinformacao =  rpad('Titular :',65,' ');--||wvalor;
                bdvalor = wvalor;
              end
--             bdinformacao = 'Saúde: CNPJ: '||TRIM(:wcnpj)||', '||TRIM(:wrs)||', CPF: '||:wcpfdpn||', Beneficiário: '||TRIM(:wnomdpn);
           ELSE
             begin
--                if( not(WJAIMPRIMIUINFDEP)) then
--                   begin
--                     bdinformacao  = 'Valor pago no ano referente aos Dependentes :                   ';
--                     bdtipocalcfir = bdtipocalcfir + 1;
--                     SUSPEND;
----                     bdinformacao  = rpad('CPF',20,' ') ||rpad('Nome',45,' ');--||'Valor';
----                     bdtipocalcfir = bdtipocalcfir + 1;
----                     SUSPEND;
--                     WJAIMPRIMIUINFDEP = True;
--                   end
                     bdinformacao = 'Dependente: '||rpad(:wcpfdpn,16,' ')||rpad(:wnomdpn,45,' ');--||wvalor;
             end
           bdtipocalcfir = bdtipocalcfir + 1;
           bdvalor = wvalor;
           SUSPEND;
           bdvalor = 0;
         END


         WSQLAUXSOCIO = 'select SOC.BDCODEMP, SOC.BDCODSOC, SOC.BDCODDEP, SOC.BDCNPJ, SOC.BDRAZAOSOCIAL, SOC.BDCPF, SOC.BDCODDEP, SOC.BDNOME, SOC.BDVALORPLANO, SOC.BDCODCOL from SP_DECLARARENDPLANSAU_SOCIO(';

         if ((prcodemp is not null) and (prcodemp <> '')) then
           wprempaux = ''''||iif(position('FOL.BDCODEMP', upper(prcodemp)) > 0, replace(prcodemp, 'FOL.BDCODEMP', 'SOC.BDCODEMP'), replace(prcodemp, 'BDCODEMP', 'SOC.BDCODEMP'))||'''';
         else
           wprempaux = ' null ';

         wprcolaux = ' null ';
         
         WSQLAUXSOCIO = WSQLAUXSOCIO||wprempaux||', '||wprcolaux||', '||prano||', '||''''||'FALSE'||''''||', '||''''||WWHERENOTCODEMP||''''||', '||''''||WWHERENOTSOCIOS||''''||', '||''''||WWHERENOTCONVENIO||''''||') SOC ';

         FOR EXECUTE STATEMENT wsqlauxsocio
         INTO
           :BDCODEMP, :WCODCOLAUX, :BDCODDPN, :WCNPJAUX, :WRSAUX, :WCPFAUX, :WCODDEPAUX, :WNOMEAUX, :WVALORAUX, :BDCODCOL
         DO
           BEGIN
  
             IF(:BDCODCOL IS NOT NULL) then
               begin
                 IF (WCODDEPAUX = 0) THEN
                    bdinformacao = 'Saúde: CNPJ: '||TRIM(:WCNPJAUX)||', '||TRIM(:WRSAUX)||', CPF: '||:WCPFAUX||', Beneficiário: '||TRIM(:WNOMEAUX);
                 ELSE
                    bdinformacao = 'Saúde: CNPJ: '||TRIM(:WCNPJAUX)||', '||TRIM(:WRSAUX)||', CPF: '||:WCPFAUX||', Dependente: '||TRIM(:WNOMEAUX);
                 bdtipocalcfir= 14;
                 bdvalor      = coalesce(:WVALORAUX, 0);
               end
             SUSPEND;
     END

   /* Lancamentos manuais de reembolso */
     
     wsql = 'select REEM.BDORIGEM, REEM.BDCODEMP, max(REEM.BDCODCOL) BDCODCOL, sum(REEM.BDREEMBOLSO) BDREEMBOLSO,'||
            ' sum(REEM.BDREEMBOLSORRA) BDREEMBOLSORRA, REEM.BDOPERADORA, REEM.BDPRESTADOR, CC.BDCPFCOL, CADDEP.BDCPFDPN, '||
            ' CADDEP.BDNOMEDPN, conv.bdcnpj,conv.bdrazaosocial '||
            ' from (select COL.BDORIGEM, COL.BDCODEMP, COL.BDCODCOL, 0 BDCODDEP, COL.BDREEMBOLSO, COL.BDREEMBOLSORRA, COL.BDOPERADORA, COL.BDPRESTADOR '||
            '       from VRH_EMP_TREEMBOLSO_PLANOSAUDE COL ';
           /*filtros*/
     if (wusartmp_col_select=1) then
        wSql = wSql || ' join TEMP_FILTRO_COLCON_REL FILTRO on FILTRO.BDCODEMP = COL.BDCODEMP and FILTRO.BDCODCOL = COL.BDCODCOL ';

     wsql = wsql||'  union all '||
            '       select DEP.BDORIGEM, DEP.BDCODEMP, DEP.BDCODCOL, DEP.BDCODDEP, DEP.BDREEMBOLSO, DEP.BDREEMBOLSORRA, DEP.BDOPERADORA, DEP.BDPRESTADOR '||
            '       from VRH_EMP_REEMBOLSO_PLA_SAUDE_DEP DEP ';
           /*filtros*/
     if (wusartmp_col_select=1) then
        wSql = wSql || ' join TEMP_FILTRO_COLCON_REL FILTRO on FILTRO.BDCODEMP = DEP.BDCODEMP and FILTRO.BDCODCOL = DEP.BDCODCOL ';

     wsql = wsql||'  ) REEM '||
            '      join VRH_EMP_TCOLCON CC on REEM.BDCODEMP = CC.BDCODEMP and REEM.BDCODCOL = CC.BDCODCOL '||
            '      left outer join VRH_BASE_TCONVSAUDE conv on REEM.bdoperadora = conv.bdcodconvenio '||
            '      left outer join VRH_EMP_TDEP_REF CADDEP on (CADDEP.BDCODEMP = REEM.BDCODEMP and '||
            '            CADDEP.BDCODCOL = REEM.BDCODCOL and CADDEP.bdcoddpn = REEM.BDCODDEP AND '||
            '            CADDEP.BDREFDPN = (select first 1 X.BDREFDPN '||
            '                               from VRH_EMP_TDEP_REF X '||
            '                               where X.BDCODEMP = REEM.BDCODEMP and '||
            '                                     X.BDCODCOL = REEM.BDCODCOL and '||
            '                                     X.BDCODDPN = REEM.BDCODDEP '||
            '                               order by X.BDREFDPN desc)) '||
            ' group by REEM.BDORIGEM, REEM.BDCODEMP, CC.BDCPFCOL, REEM.BDOPERADORA, REEM.BDPRESTADOR, CADDEP.BDCPFDPN, CADDEP.BDNOMEDPN, conv.bdcnpj,conv.bdrazaosocial '||
            ' order by REEM.BDCODEMP, CC.BDCPFCOL, REEM.BDORIGEM, REEM.BDOPERADORA, REEM.BDPRESTADOR, CADDEP.BDCPFDPN, CADDEP.BDNOMEDPN  ';



     wQuebraTitulo = '';
     wQuebraColaborador = '';
     wImpTitDep = 0;
     for execute statement wsql into :wOrigem, :BDCODEMP, :BDCODCOL, wvalreembolso, :wvalreembolsorra,
           :wOperadora, :wPrestador, :bdcpfcol, :wcpfdpn, :wnomdpn, :wcnpj, :wNomeOparadora do
         begin
           bdtipoimp = 0;
           bdvalor = 0;
           bdvalor2 = 0;
           bdtitcol = '';
           bdtitcol2 = '';
           -- Imprime titulo reembolso quando troca de colaborador ou de origem
           if ((wQuebraColaborador <> bdcodemp||'.'||bdcpfcol) or  (wQuebraTitulo <> bdcodemp||'.'||bdcpfcol||'.'||worigem)) then
              begin
                wImpTitDep = 0;
                wQuebraOperadora = '';
                if (worigem = 1) then
                   bdinformacao ='Reembolsos referente a planos de saúde:';
                else
                   bdinformacao = rpad('Reembolso efetuado pelo empregador como benefício do próprio empregador:',80,' ');

                bdvalor = 0;
                bdtipoimp = 1;
                bdtipocalcfir = bdtipocalcfir + 1;
                suspend;
              end

           wQuebraColaborador = bdcodemp||'.'||bdcpfcol;
           wQuebraTitulo = bdcodemp||'.'||bdcpfcol||'.'||worigem;

           if ((worigem = 1) and (wQuebraOperadora <> ''||coalesce(:woperadora,0))) then
              begin
                bdinformacao ='Operadora: ' ||TRIM(:wcnpj) || ' - ' ||TRIM(:wnomeoparadora);
                bdtitcol = 'Ano calendário';
                bdtitcol2 = 'Anos anteriores';
                bdtipocalcfir = bdtipocalcfir + 1;
                bdtipoimp = 3;
                wQuebraOperadora = ''||coalesce(:woperadora,0);
                SUSPEND;
              end

           /* Prestador de servico */
           if ((worigem = 2) and (wQuebraOperadora <> ''||coalesce(:wprestador,''))) then
              begin
                bdinformacao = trim('CNPJ prestador de serviço: ' || :wprestador);
                bdtipoimp = 3;
                bdtitcol = 'Ano calendário';
                bdtitcol2 = 'Anos anteriores';
                bdtipocalcfir = bdtipocalcfir + 1;
                wQuebraOperadora = ''||coalesce(:wprestador,'');
                SUSPEND;
              end

           -- Se for o titular não tem nome de dependente
           if ((:WVALREEMBOLSO<>0) or (:wvalreembolsorra<>0)) then
              begin
                if (wnomdpn is null) then
                   begin
                     if (worigem = 1) then
                        begin
                          bdinformacao = rpad('Reembolso do plano de saúde referente ao titular:',60,' ');--||rpad('Valor ano calendário',30,' ')||'Valor anos anteriores';
                          bdtipoimp = 4;
                          bdvalor = WVALREEMBOLSO;
                          bdvalor2 = wvalreembolsorra;
                          bdinformacao = 'Titular:';
                          bdtipocalcfir = bdtipocalcfir + 1;
                          SUSPEND;
                        end
                     else
                        begin
                          bdvalor = WVALREEMBOLSO;
                          bdvalor2 = wvalreembolsorra;
                          bdinformacao = 'Titular:'; --trim('CNPJ prestador de serviço: ' || :wprestador);
                          bdtipoimp = 4;
                          bdtipocalcfir = bdtipocalcfir + 1;
                          SUSPEND;

                        end
                   end
                else
                   begin
                     if (worigem = 1) then
                        begin
                          bdtipoimp = 4;
                          bdvalor = WVALREEMBOLSO;
                          bdvalor2 = wvalreembolsorra;
                          bdinformacao = 'Dependente: '||rpad(:wcpfdpn,16,' ')||rpad(:wnomdpn,45,' ');
                          bdtipocalcfir = bdtipocalcfir + 1;
                          SUSPEND;
                          bdtipoimp = 0;
                        end
                     else
                        begin
                          bdtipoimp = 4;
                          bdvalor = WVALREEMBOLSO;
                          bdvalor2 = wvalreembolsorra;
                          bdinformacao = 'Dependente: '||rpad(:wcpfdpn,16,' ')||rpad(:wnomdpn,45,' ');
                          bdtipocalcfir = bdtipocalcfir + 1;
                          SUSPEND;
                        end
                   end
              end

         end

  /*------------------------------------------------*/

     END

end^

/* Restore proc. body: SP_VRH_DECLARACAO_RENDIMENTOS_7 */
create or alter procedure SP_VRH_DECLARACAO_RENDIMENTOS_7 (
    PRCODEMP varchar(32000),
    PRCODCOL varchar(32000),
    PRANO integer,
    PREXPORTACAO integer = 0,
    PRPENSAORRA boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDTIPOCALCFIR integer,
    BDINFORMACAO varchar(250),
    BDVALOR numeric(18,6),
    BDCPFCOL varchar(14),
    BDCPFBENEF varchar(14),
    BDTIPOIMP integer,
    BDVALOR2 numeric(18,6),
    BDTITCOL varchar(100),
    BDTITCOL2 varchar(100))
as
declare variable WSQL varchar(10000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WCODDPN integer;
declare variable WNOMDPN varchar(70);
declare variable WCPFDPN varchar(14);
declare variable WVALDPN numeric(18,6);
declare variable WVALREND numeric(18,6);
declare variable WDESCREND varchar(999);
declare variable WCNPJ varchar(18);
declare variable WRS varchar(80);
declare variable WNRBENEF varchar(20);
declare variable WVALDPN2 numeric(18,6);
declare variable WREFPAG integer;
declare variable WRENDISENTOS numeric(18,6);
declare variable WRENDTRIB numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WOK integer;
declare variable WTOTRENDISENTOS numeric(18,6);
declare variable WTIPOFIR integer;
declare variable WDESCRENDATU varchar(300);
declare variable WPREVPRIV numeric(18,6);
declare variable WPRIVATU numeric(18,6);
declare variable WDTNASC date;
declare variable WDTNASCS varchar(10);
declare variable WSQL2 varchar(5000);
declare variable WTOTABONO numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WCNPJEMP varchar(18);
declare variable WNOMEMP varchar(100);
declare variable WIR numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WCOUNT integer;
declare variable WDESCANT varchar(999);
declare variable WDESCANT2 varchar(999);
declare variable WSQLAUXSOCIO varchar(32000);
declare variable WCODEMPSOCIO integer;
declare variable WCODCOLSOCIO integer;
declare variable WCODDEPSOCIO integer;
declare variable WCODCONVENIOSOCIO integer;
declare variable WVALORPLANO numeric(18,2);
declare variable WMESMACONSULTA varchar(100);
declare variable WWHERENOTCODEMP varchar(3200) = '';
declare variable WWHERENOTSOCIOS varchar(3200) = '';
declare variable WWHERENOTCONVENIO varchar(3200) = '';
declare variable WCNPJAUX varchar(18);
declare variable WRSAUX varchar(80);
declare variable WCPFAUX varchar(14);
declare variable WNOMEAUX varchar(70);
declare variable WVALORAUX numeric(18,2);
declare variable WCODDEPAUX integer;
declare variable WPREMPAUX varchar(32000);
declare variable WPRCOLAUX varchar(32000);
declare variable WCODCOLAUX integer;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WNMRPROC varchar(300);
declare variable WJAIMPRIMIUINFDEP boolean;
declare variable WVALOR numeric(15,2);
declare variable WREFERENCIASPROC varchar(300);
declare variable WMESMACONSULTA2 varchar(500);
declare variable WCODOPERADORA integer;
declare variable WINFREEMBOLSOTIT varchar(300);
declare variable WINFREEMBOLSODEP varchar(300);
declare variable WVALREEMBOLSO numeric(15,2);
declare variable WVALREEMBOLSORRA numeric(15,2);
declare variable WMESMOGRUPOPLANOSAUDE varchar(100);
declare variable WCPFANT varchar(20);
declare variable WCODMATRIZ integer;
declare variable WAUXILIOMORADIA numeric(18,6);
declare variable WTAMDESC integer;
BEGIN
  BDTIPOIMP = 0; /*0 = Normal; 1 = Negrito Titulos; 2 = Sem Campo valor*/
  wtamdesc = 250;
  /* PENSAO ALIMENTICIA */

  WUSARTMP_EMP_SELECT = 0;
  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  WUSARTMP_COL_SELECT = 0;
  IF (UPPER(prCodcol) = 'TEMP_FILTRO_COLCON_REL') THEN
     WUSARTMP_COL_SELECT = 1;


  IF (PREXPORTACAO = 0) THEN -- Quando for exporta????o n??o precisa levar a descri????o do plano de sa??de Almir 16/02/2015
    BEGIN
      /* Rendimentos ISENTOS, RENDIMENTOS E PLR */
      wsql = 'SELECT * FROM (select FOL.BDCODEMP, '||
                    'FOL.BDCODCOL, '||
                    'FOL.BDREFPAG, '||
                    'case when COALESCE(FOL.BDTIPO, 0) in (0, 1, 2, 100, 110) then 0 else COALESCE(FOL.BDTIPO, 0) end BDTIPO, '||
                    'SUM(FOL.BDRENDISENTOS) BDRENDISENTOS, '||
                    'SUM(FOL.BDRENDTRIBUTAVEL) + case when sum(FOL.BDINSS) < 0 then sum(FOL.BDINSS) * -1 else 0 end BDRENDTRIBUTAVEL, '||
                    'case when sum(FOL.BDINSS) < 0 then 0 else sum(FOL.BDINSS) end BDINSS, '||
                    'MAX(FOL.BDDRENDISENTOS) bddesc, '||
                    'SUM(FOL.BDPREVPRIV) BDPREVPRIV, '||
                    'SUM(case when FOL.BDVALABO > 0 then FOL.BDVALABO else 0 end) BDVALABO, SUM(FOL.BDAUXILIOMORADIA) BDAUXILIOMORADIA '||
             'from SP_VRHF_DADOS_IR_DIRF(';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||''''||prcodemp||''',';
      ELSE
         wsql = wsql||'null,';
    
      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
         wsql = wsql||''''||prcodcol||''',';
      ELSE
         wsql = wsql||'null,';
    
      wsql = wsql ||prano||'01,'||prano||'12, 0, '''', 0,0) FOL '||
             'where (COALESCE(FOL.BDRENDISENTOS, 0.00) <> 0) or (COALESCE(FOL.BDRENDTRIBUTAVEL, 0.00) <> 0) or (COALESCE(FOL.BDINSS, 0.00) <> 0) or (COALESCE(FOL.BDVALABO, 0.00) <> 0)  or (COALESCE(FOL.BDPREVPRIV, 0.00) <> 0) or (COALESCE(FOL.BDAUXILIOMORADIA, 0) <> 0) '||
             'group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFPAG, BDTIPO '||
             'UNION ALL '||
             'select '||
             'rt.bdcodemp,rt.bdcodcol,rt.bdrefpgto BDREFPAG, 0 bdtipo, rt.BDRENDNAPTRIBUT BDRENDISENTOS,0 BDRENDTRIBUTAVEL, 0 BDINSS, rt.BDDESCRENDNAOTRIBUT BDDESC, 0 BDPREVPRIV, 0 BDVALABO, 0 BDAUXILIOMORADIA '||
             'FROM SP_VRHF_DADOS_IR_RT(';
   
                    if (prcodemp IS NULL or prcodemp = '') then
                       wsql = wsql||'null';
                    else
                       wsql = wsql||''''||replace(upper(prcodemp),'FOL.','')||'''';
   
                    wsql = wsql||',';
   
                    if (prcodcol IS NULL or prcodcol = '') then
                       wsql = wsql||'null';
                    else
                       wsql = wsql||''''||replace(upper(prcodcol),'FOL.','')||'''';
   
                    wsql = wsql||','||prano||'01,'||prano||'12,FALSE,TRUE,2) RT '||
             'where (coalesce(rt.BDRENDNAPTRIBUT, 0.00) <> 0) and (rt.bdcodcol is not null) '||
             ') A order by A.BDCODEMP, A.BDCODCOL,A.bddesc,A.BDREFPAG';

      wempatu         = 0;
      wcolatu         = 0;
      wrefatu         = 0;
      wrendisentos    = 0;
      wrendtrib       = 0;
      winss           = 0;
      wtotrendisentos = 0;
      wvalrend        = 0;
      wdescrendatu    = '';
      wprivatu        = 0;
      wtotabono       = 0;
      wok             = 0;
      wdescant        ='';

      FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wrefpag, :wtipofir, :wrendisentos, :wrendtrib, :winss, :wdescrend, :wprevpriv, :wvalabo, :WAUXILIOMORADIA  DO
        BEGIN
          IF (wempatu = 0) THEN
             wempatu = wcodemp;
          IF (wcolatu = 0) THEN
             wcolatu = wcodcol;
          IF (wrefatu = 0) THEN
             wrefatu = wrefpag;
          wdescant=wdescrend;
          if (wdescrend=wdescant2) then
            begin
             wdescrend='';
            end
            wdescant2=wdescant;

          IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol)) THEN
             BEGIN
               IF (wtotrendisentos <> 0) THEN
                  BEGIN
                    bdcodemp     = wempatu;
                    bdcodcol     = wcolatu;
                    bdinformacao = SUBSTRING('Rendimentos isentos: '||:wdescrendatu FROM 1 FOR wtamdesc);
                    bdtipocalcfir= 7;
                    bdvalor      = :wtotrendisentos;
                    bdcoddpn     = 0;
                    SUSPEND;
                  END

               IF (wprivatu <> 0) THEN
                  BEGIN
                    bdcodemp     = wempatu;
                    bdcodcol     = wcolatu;
                    bdcoddpn     = 0;
                    bdinformacao = 'Valor pago a título de Previdência Complementar'; -- 17110 - Marcelo B. M. - 28/09/2017 - 'Privada' para 'Complementar'
                    bdtipocalcfir= 5;
                    bdvalor      = :wprivatu;
                    SUSPEND;

                    wsql2 = 'select first 1 Y.BDCNPJ, Y.BDDESCPREV from VRH_EMP_TLANCPREVCOMP X join VRH_BASE_TCADPREVCOMP Y on (Y.BDCODCADPREV = X.BDCODCADPREV) '||
                            'where X.BDCODEMP = '||bdcodemp||' and X.BDCODCOL = '||bdcodcol||' and X.BDREFINI <= '||wrefatu||' and ((COALESCE(X.BDREFFIN, 0) = 0) or (X.BDREFFIN >= '||wrefatu||')) '||
                               ' and COALESCE(X.BDVALMENSAL, 0) + COALESCE(X.BDVAL13SAL, 0) > 0 '||
                               ' and Y.BDNATPREV <> 2 '||     /* 184717 Leonardo Schwab 16/11/2023 */
                               ' order by X.BDREFINI desc';

                    EXECUTE STATEMENT wsql2 INTO :wcnpjemp, :wnomemp;

                    IF (COALESCE(wnomemp,'') = '') THEN
                       wnomemp = 'Previdência complementar';

                    bdtipocalcfir= 6;
                    bdinformacao = 'CNPJ: '||COALESCE(wcnpjemp,'')||', Entidade: '||COALESCE(wnomemp,'');

                    bdvalor = 0;
                    wcnpjemp = '';
                    wnomemp = '';

                    SUSPEND;
                  END
               -- 17110 - Marcelo B. M. - Alt:16/10/2017 - Fim

               IF (wtotabono <> 0) THEN
                  BEGIN
                    bdcodemp     = wempatu;
                    bdcodcol     = wcolatu;
                    bdcoddpn     = 0;
                    bdinformacao = 'Abono pecuniário';
                    bdtipocalcfir= 30;
                    bdvalor      = wtotabono;
                    SUSPEND;
                  END

               wempatu         = wcodemp;
               wcolatu         = wcodcol;
               wrefatu         = wrefpag;
               wtotrendisentos = 0;
               wvalrend        = 0;
               wdescrendatu    = '';
               wprivatu        = 0;
               wtotabono       = 0;
             END

          IF ((TRIM(COALESCE(wdescrend, '')) <> '') OR (COALESCE(wrendisentos, 0.00) <> 0) or (COALESCE(WAUXILIOMORADIA, 0.00) <> 0)) THEN
             BEGIN
               IF (wdescrend <> '') THEN
                  begin
                    if (wdescrendatu<>'') then
                       wdescrendatu = SUBSTRING(wdescrendatu||','||wdescrend FROM 1 FOR wtamdesc);
                    else
                       wdescrendatu = SUBSTRING(wdescrendatu||wdescrend FROM 1 FOR wtamdesc);
                  end

               wtotrendisentos = wtotrendisentos + COALESCE(wrendisentos, 0.00);

               if (COALESCE(WAUXILIOMORADIA, 0.00) <> 0) then
                  BEGIN
                    wtotrendisentos = wtotrendisentos + COALESCE(WAUXILIOMORADIA, 0.00);

                    if ((TRIM(COALESCE(wdescrendatu, '')) = '')) then
                       wdescrendatu = 'AUXÍLIO MORADIA';
                    else
                      if ((POSITION('AUXÍLIO MORADIA', wdescrendatu) = 0)) then
                         wdescrendatu = substring(wdescrendatu || ', AUXÍLIO MORADIA' from 1 for wtamdesc);
                  END
             END

          IF (wvalabo <> 0) THEN
             wtotabono = wtotabono + wvalabo;

          IF (COALESCE(wtipofir,0) NOT IN (9, 10, 11, 101, 111, 9002, 9012, 9099, 9100) AND wrendtrib >= 0) THEN
             BEGIN
               wvalrend = wvalrend + wrendtrib;
             END

           if (coalesce(wtipofir, 0) <> 10) then /*160514 LuizCovre 05/07/2022*/
              wprivatu = wprivatu + wprevpriv;
        end
    
     IF (wempatu <> 0 AND wcolatu <> 0) THEN
        BEGIN
          IF (wtotrendisentos <> 0) THEN
             BEGIN
               bdcodemp     = wempatu;
               bdcodcol     = wcolatu;
               bdinformacao = SUBSTRING('Rendimentos isentos: '||:wdescrendatu FROM 1 FOR wtamdesc);
               bdtipocalcfir= 7;
               bdvalor      = :wtotrendisentos;
               bdcoddpn     = 0;
               SUSPEND;
             END

          IF (wprivatu <> 0) THEN
             BEGIN
               bdcodemp     = wempatu;
               bdcodcol     = wcolatu;
               bdcoddpn     = 0;
               bdinformacao = 'Valor pago a título de Previdência Complementar';
               bdtipocalcfir= 5;
               bdvalor      = :wprivatu;
               SUSPEND;

               wsql2 = 'select first 1 Y.BDCNPJ, Y.BDDESCPREV from VRH_EMP_TLANCPREVCOMP X join VRH_BASE_TCADPREVCOMP Y on (Y.BDCODCADPREV = X.BDCODCADPREV) '||
                       'where X.BDCODEMP = '||bdcodemp||' and X.BDCODCOL = '||bdcodcol||' and X.BDREFINI <= '||wrefatu||' and ((COALESCE(X.BDREFFIN, 0) = 0) or (X.BDREFFIN >= '||wrefatu||')) '||
                             ' and COALESCE(X.BDVALMENSAL, 0) + COALESCE(X.BDVAL13SAL, 0) > 0 '||
                             ' and Y.BDNATPREV <> 2 '||      /* 184717 Leonardo Schwab 16/11/2023 */
                             ' order by X.BDREFINI desc';

               EXECUTE STATEMENT wsql2 INTO :wcnpjemp, :wnomemp;

               IF (COALESCE(wnomemp,'') = '') THEN
                  wnomemp = 'Previdência privada';

               bdtipocalcfir= 6;
               bdinformacao = 'CNPJ: '||COALESCE(wcnpjemp,'')||', Entidade cadastrada: '||COALESCE(wnomemp,'');

               bdvalor = 0;
               wcnpjemp = '';
               wnomemp = '';

               SUSPEND;
             END
          -- 17110 - Marcelo B. M. - Alt:16/10/2017 - Fim

          IF (wtotabono <> 0) THEN
             BEGIN
               bdcodemp     = wempatu;
               bdcodcol     = wcolatu;
               bdcoddpn     = 0;
               bdinformacao = 'Abono pecuniário';
               bdtipocalcfir= 30;
               bdvalor      = wtotabono;
               SUSPEND;
        END
        END

      wsql = 'select X.BDCODEMP, X.BDCODCOL, SUM(COALESCE(X.BDRENDTRIBUTAVEL,0)) - SUM(COALESCE(X.BDINSS,0)) - SUM(COALESCE(X.BDDESPMED,0)) - SUM(COALESCE(X.BDPENJUD,0)) - '||
             'SUM(COALESCE(X.BDPENALIM,0)) - SUM(COALESCE(X.BDIR,0)) BDLIQUIDO from SP_VRHF_DADOS_IR_FA(';
    
      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||''''||prcodemp||''',';
      ELSE
         wsql = wsql||'null,';
    
      IF (prcodcol IS NOT NULL AND prcodcol <> '')  THEN
         wsql = wsql||''''||prcodcol||''',';
      ELSE
         wsql = wsql||'null,';
    
      wsql = wsql||prano||'01,'||prano||'12,0,null,1,0) X join VRH_BASE_TTIPOCALCAVUL FA on (FA.BDCODTCA = X.BDCODTCA and FA.BDCODCTP = 7) group by X.BDCODEMP,X.BDCODCOL ';
    
      FOR EXECUTE STATEMENT wsql
      INTO
        :bdcodemp,:bdcodcol,:wvaldpn2
      DO
        BEGIN
          IF (wvaldpn2 > 0) THEN
             BEGIN
               IF (wvaldpn <= 0) THEN
               BEGIN
                 bdcoddpn     = 0;
                 bdinformacao = 'Os rendimentos seguintes estão informados na linha 01, quadro 3 e/ou linha 03, quadro 05:';
                 bdtipocalcfir= 3;
                 bdvalor      = 0;
                 SUSPEND;
               END
    
               bdcoddpn     = 0;
               bdinformacao = 'O total informado na Linha 3 do Quadro 5 já inclui o valor total pago a título de PLR correspondente a:  ';
               bdtipocalcfir= 4;
               bdvalor      = :wvaldpn2;
               SUSPEND;
            END
        END

    wsql = 'SELECT A.*,Coalesce(emp.bdcodmatriz,emp.bdcodemp)bdcodmatriz FROM (select FOL.BDCODDPN,FOL.BDCODEMP,FOL.BDCODCOL,DEP.BDNOMBENEF BDNOMEDPN,DEP.BDCPFBENEF BDCPFDPN,DEP.BDDATANASCBENEF,SUM(COALESCE(FOL.BDVALPEND, 0)) BDVALDPN,col.bdcpfcol '||
       'from VWRH_PENSAO_DEP FOL join VRH_EMP_TCOLCON_BENEF DEP on (DEP.BDCODEMP = FOL.BDCODEMP and DEP.BDCODCOL = FOL.BDCODCOL and DEP.BDCODBENEF = FOL.BDCODDPN) '||
       ' left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and    COL.BDCODCOL = FOL.BDCODCOL) ';
  
    IF (WUSARTMP_EMP_SELECT = 1) THEN
      wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = DEP.BDCODEMP) ';

    IF (WUSARTMP_COL_SELECT = 1) THEN
       wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

    wsql = wsql||'where FOL.BDTIPO <> 1 and FOL.BDREFPAGPEND >= '||prano||'01 and FOL.BDREFPAGPEND <= '||prano||'12 ';
    
    IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
       wsql = wsql||' and '||prcodemp;
      
    IF ((prcodcol IS NOT NULL AND prcodcol <> '') AND (WUSARTMP_COL_SELECT = 0)) THEN
       wsql = wsql||' and '||prcodcol;
      
    wsql = wsql||' group by FOL.BDCODDPN,FOL.BDCODEMP,COL.bdcpfcol,FOL.BDCODCOL,DEP.BDNOMBENEF,DEP.BDCPFBENEF,DEP.BDDATANASCBENEF having SUM(COALESCE(FOL.BDVALPEND, 0)) <> 0 ';

    wsql = wsql||' UNION ALL '||
                 'SELECT 0 BDCODDPN, IR.BDCODEMP, IR.BDCODCOL, PA.BDNOMEBENEFPENSAO BDNOMEDPN, PA.BDCPFBENEFPENSAO BDCPFDPN, PA.BDDATANASCIMENTO BDDATANASCBENEF, SUM(COALESCE(PA.BDVALORPENSAOMENSAL,0)) BDVALDPN,IR.BDCPF  '||
                 'FROM SP_VRHF_DADOS_IR_RT(';

                 if (prcodemp IS NULL or prcodemp = '') then
                    wsql = wsql||'null';
                 else
                    wsql = wsql||''''||replace(upper(prcodemp),'FOL.','')||'''';

                 wsql = wsql||',';

                 if (prcodcol IS NULL or prcodcol = '') then
                    wsql = wsql||'null';
                 else
                    wsql = wsql||''''||replace(upper(prcodcol),'FOL.','')||'''';

                 wsql = wsql||','||prano||'01,'||prano||'12,FALSE,TRUE,2) IR '||
                 'JOIN TRT_CODIGORECEITA_IRRF CR ON (CR.BDCODRECEITAESOC = IR.BDCODRECEITAESOC) '||
                 'JOIN VRH_EMP_PENSAO_TENCARGOS_RT PA ON (PA.BDCODEMP = IR.BDCODEMP AND PA.BDCHAVE = IR.BDCHAVE AND PA.BDREFPGTO = IR.BDREFPGTO AND PA.BDCPF = IR.BDCPF AND PA.BDCODCR = CR.BDCODRECEITA) '||
                 'GROUP BY BDCODDPN, IR.BDCODEMP, IR.BDCODCOL, BDNOMEDPN, BDCPFDPN,  BDDATANASCBENEF,IR.BDCPF ';

      wsql = wsql||') A '||
                   ' join tempresas emp on  A.bdcodemp=emp.bdcodemp'||
                   ' ORDER BY emp.BDCODMATRIZ, A.bdcpfcol, A.BDCODCOL, A.BDNOMEDPN ';
  
    wempatu = 0;
    wcolatu = 0;
    wcount  = 0;
    wcpfant = '';
  
    FOR EXECUTE STATEMENT wsql INTO :wcoddpn, :wcodemp, :wcodcol, :wnomdpn, :wcpfdpn, :wdtnasc, :wvaldpn,:bdcpfcol,:wcodmatriz DO
      BEGIN
        wcodcol = coalesce(wcodcol,0);
        if ((wcount < 1) or (wempatu <> wcodmatriz)  or (wcpfant <> bdcpfcol) ) then
           BEGIN
             bdcodemp     = :wcodemp;
             bdcodcol     = :wcodcol;
             bdcoddpn     = 0;
             bdtipocalcfir= 9;
             bdinformacao = 'Beneficiários de pensão alimentícia';
             bdvalor      = 0;
             BDTIPOIMP    = 1;
             SUSPEND;
       
             BDTIPOIMP  = 0;
             bdcodemp     = :wcodemp;
             bdcodcol     = :wcodcol;
             bdcoddpn     = 0;
             bdtipocalcfir= 10;
             bdinformacao = 'CPF               Nascimento    Nome';
             bdvalor      = 0;
             SUSPEND;

             wempatu = :wcodmatriz;
             wcolatu = :wcodcol;
             wcpfant = :bdcpfcol;
             wcount  = 0;
            END
  
        SELECT SUM(COALESCE(fir.bdpenalimfir, 0)) bdpenalimfir FROM VRHF_EMP_TFICHAIRRF fir WHERE fir.bdcodemp = :wcodemp AND fir.bdcodcol = :wcodcol AND
              fir.bdrefirfir >= :prano||'01' AND fir.bdrefirfir <= :prano||'12' AND fir.bdtipocalcfir >= 9000 AND NOT EXISTS (
                 SELECT fpir.bdcodemp FROM VRHF_EMP_TFIPENSAO_DEP fpir WHERE fpir.bdcodemp = fir.bdcodemp AND fpir.bdcodcol = fir.bdcodcol AND fpir.bdrefpagpend = fir.bdrefirfir) INTO :wvaldpn2;
      
        bdcodemp     = :wcodemp;
        bdcodcol     = :wcodcol;
        bdcoddpn     = :wcoddpn;
        bdtipocalcfir= 11;
  
        IF (wdtnasc IS NULL) THEN
           wdtnascs = '  /  /    ';
        ELSE
           wdtnascs = SUBSTRING(CAST(wdtnasc AS VARCHAR(10)) FROM 9 FOR 2)||'/'||SUBSTRING(CAST(wdtnasc AS VARCHAR(10)) FROM 6 FOR 2)||'/'||SUBSTRING(CAST(wdtnasc AS VARCHAR(10)) FROM 1 FOR 4);
  
        IF ((wcpfdpn IS NULL) OR (TRIM(wcpfdpn) = '.   .   -') OR (TRIM(wcpfdpn) = '')) THEN
           wcpfdpn = '              ';
  
        bdinformacao = wcpfdpn||'    '||wdtnascs||'    '||COALESCE(:wnomdpn, '');
        bdvalor      = COALESCE(wvaldpn, 0) + COALESCE(wvaldpn2, 0);
        SUSPEND;
  
        wcount = wcount + 1;
      END

    wsql = 'select * from (select FOL.BDCODDPN,FOL.BDCODEMP,FOL.BDCODCOL,DEP.BDNOMBENEF BDNOMEDPN,DEP.BDCPFBENEF BDCPFDPN,DEP.BDDATANASCBENEF,SUM(COALESCE(FOL.BDVALPEND, 0)) BDVALDPN, COL.BDCPFCOL '||
       'from VWRH_PENSAO_DEP FOL join VRH_EMP_TCOLCON_BENEF DEP on (DEP.BDCODEMP = FOL.BDCODEMP and DEP.BDCODCOL = FOL.BDCODCOL and DEP.BDCODBENEF = FOL.BDCODDPN) '||
       ' join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = DEP.BDCODEMP AND COL.BDCODCOL = DEP.BDCODCOL) ';
  
    IF (WUSARTMP_EMP_SELECT = 1) THEN
      wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = DEP.BDCODEMP) ';

    IF (WUSARTMP_COL_SELECT = 1) THEN
       wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = DEP.BDCODEMP and TEMP.BDCODCOL = DEP.BDCODCOL) ';

    wsql = wsql||'where FOL.BDTIPO = 1 and FOL.BDREFPAGPEND >= '||prano||'01 and FOL.BDREFPAGPEND <= '||prano||'12 ';
      
    IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) then
       wsql = wsql||' and '||prcodemp;
      
    IF ((prcodcol IS NOT NULL AND prcodcol <> '') AND (WUSARTMP_COL_SELECT = 0)) THEN
       wsql = wsql||' and '||prcodcol;
      
    wsql = wsql||' group by FOL.BDCODDPN,FOL.BDCODEMP,COL.BDCPFCOL,FOL.BDCODCOL,DEP.BDNOMBENEF,DEP.BDCPFBENEF,DEP.BDDATANASCBENEF having SUM(COALESCE(FOL.BDVALPEND, 0)) <> 0 ';

    wsql = wsql||' UNION ALL '||
                 'SELECT 0 BDCODDPN, IR.BDCODEMP, IR.BDCODCOL, PA.BDNOMEBENEFPENSAO BDNOMEDPN, PA.BDCPFBENEFPENSAO BDCPFDPN, PA.BDDATANASCIMENTO BDDATANASCBENEF, SUM(COALESCE(PA.BDVALORPENSAO13,0)) BDVALDPN, IR.BDCPF '||
                 'FROM SP_VRHF_DADOS_IR_RT(';

                 if (prcodemp IS NULL or prcodemp = '') then
                    wsql = wsql||'null';
                 else
                    wsql = wsql||''''||replace(upper(prcodemp),'FOL.','')||'''';

                 wsql = wsql||',';

                 if (prcodcol IS NULL or prcodcol = '') then
                    wsql = wsql||'null';
                 else
                    wsql = wsql||''''||replace(upper(prcodcol),'FOL.','')||'''';

                 wsql = wsql||','||prano||'01,'||prano||'12,FALSE,TRUE,2) IR '||
                 'JOIN TRT_CODIGORECEITA_IRRF CR ON (CR.BDCODRECEITAESOC = IR.BDCODRECEITAESOC) '||
                 'JOIN VRH_EMP_PENSAO_TENCARGOS_RT PA ON (PA.BDCODEMP = IR.BDCODEMP AND PA.BDCHAVE = IR.BDCHAVE AND PA.BDREFPGTO = IR.BDREFPGTO AND PA.BDCPF = IR.BDCPF AND PA.BDCODCR = CR.BDCODRECEITA) '||
                 'GROUP BY BDCODDPN, IR.BDCODEMP, IR.BDCPF, IR.BDCODCOL, BDNOMEDPN, BDCPFDPN, BDDATANASCBENEF ';


    wsql = wsql||') A order by A.BDCODEMP,A.BDCODCOL,A.BDDATANASCBENEF,A.BDCPFDPN,A.BDCODDPN ';

    FOR EXECUTE STATEMENT wsql INTO :wcoddpn, :wcodemp, :wcodcol, :wnomdpn, :wcpfdpn, :wdtnasc, :wvaldpn, :bdcpfcol DO
      BEGIN
        bdcodemp     = :wcodemp;
        bdcodcol     = :wcodcol;
        bdcoddpn     = 0;
        bdtipocalcfir= 12;
        bdinformacao = '                                (*) 13º salário';
        bdvalor      = COALESCE(wvaldpn, 0);
        SUSPEND;
      END
    END
  ELSE
    BEGIN
      /* RENDIMENTOS ISENTOS / BOLSA DE ESTUDOS*/
      wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFPAG, case when COALESCE(FOL.BDTIPO, 0) in (0, 1, 2, 100, 110) then 0 else COALESCE(FOL.BDTIPO, 0) end BDTIPO, '||
                    'SUM(FOL.BDRENDISENTOS), MAX(FOL.BDDRENDISENTOS) from SP_VRHF_DADOS_IR_DIRF(';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||''''||prcodemp||''',';
      ELSE
         wsql = wsql||'null,';
    
      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
         wsql = wsql||''''||prcodcol||''',';
      ELSE
         wsql = wsql||'null,';
    
      wsql = wsql ||prano||'01,'||prano||'12, 0, '''', 0, 1) FOL where (COALESCE(FOL.BDRENDISENTOS, 0.00) <> 0) group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFPAG, BDTIPO '||
             'order by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFPAG';

      wempatu         = 0;
      wcolatu         = 0;
      wrefatu         = 0;
      wrendisentos    = 0;
      wtotrendisentos = 0;
      wdescrendatu    = '';

      FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wrefpag, :wtipofir, :wrendisentos, :wdescrend DO
        BEGIN
          if (wdescrend = 'BOLSA DE ESTUDOS') then
             BEGIN
               IF (wempatu = 0) THEN
                  wempatu = wcodemp;
               IF (wcolatu = 0) THEN
                  wcolatu = wcodcol;
               IF (wrefatu = 0) THEN
                  wrefatu = wrefpag;

               IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol)) THEN
                  BEGIN
                    IF (wtotrendisentos <> 0) THEN
                       BEGIN
                         bdcodemp     = wempatu;
                         bdcodcol     = wcolatu;
                         bdinformacao = SUBSTRING('Rendimentos isentos: '||:wdescrendatu FROM 1 FOR wtamdesc);
                         bdtipocalcfir= 7;
                         bdvalor      = :wtotrendisentos;
                         bdcoddpn     = 0;
                         SUSPEND;
                       END

                    wempatu         = wcodemp;
                    wcolatu         = wcodcol;
                    wrefatu         = wrefpag;
                    wtotrendisentos = 0;
                    wvalrend        = 0;
                    wdescrendatu    = '';
                    wprivatu        = 0;
                    wtotabono       = 0;
                  END

               IF ((TRIM(COALESCE(wdescrend, '')) <> '') OR (COALESCE(wrendisentos, 0.00) <> 0)) THEN
                  BEGIN
                    IF (wdescrendatu <> '') THEN
                       wdescrendatu = SUBSTRING(wdescrendatu||', ' FROM 1 FOR wtamdesc);

                    wdescrendatu = SUBSTRING(wdescrendatu||wdescrend FROM 1 FOR wtamdesc);
                    wtotrendisentos = wtotrendisentos + COALESCE(wrendisentos, 0.00);
                  END
             END
        END

     IF (wempatu <> 0 AND wcolatu <> 0) THEN
        BEGIN
          IF (wtotrendisentos <> 0) THEN
             BEGIN
               bdcodemp     = wempatu;
               bdcodcol     = wcolatu;
               bdinformacao = SUBSTRING('Rendimentos isentos: '||:wdescrendatu FROM 1 FOR wtamdesc);
               bdtipocalcfir= 7;
               bdvalor      = :wtotrendisentos;
               bdcoddpn     = 0;
               SUSPEND;
             END
        END

      /*   *************************************  DESPESAS JUDICIAIS  *************************************  175030 Leonardo Schwab 17/02/2023 */
      wsql = 'SELECT FOL.BDCODEMP, FOL.BDCODCOL, CASE WHEN COALESCE(FOL.BDTIPO, 0) IN (9, 10, 11, 101, 111, 9002, 9012, 9099, 9100, 9110) THEN 1 ELSE 0 END BDTIPO, '||  -- Essa verificação do BDTIPO é para separar as folhas de décimo.
                     'SUM(FOL.BDPENJUD) from SP_VRHF_DADOS_IR_DIRF(';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||''''||prcodemp||''',';
      ELSE
         wsql = wsql||'null,';
    
      IF (prcodcol IS NOT NULL AND prcodcol <> '')  THEN
         wsql = wsql||''''||prcodcol||''',';
      ELSE
         wsql = wsql||'null,';
    
      wsql = wsql ||prano||'01,'||prano||'12, 0, '''', 0, 1) FOL where (COALESCE(FOL.BDPENJUD, 0.00) <> 0) group by FOL.BDCODEMP, FOL.BDCODCOL, BDTIPO '||
             'order by FOL.BDCODEMP, FOL.BDCODCOL, BDTIPO';

      wempatu         = 0;
      wcolatu         = 0;
      wrefatu         = 0;
      wrendisentos    = 0;
      wtotrendisentos = 0;
      wdescrendatu    = '';

      FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wtipofir, :wrendisentos DO
        BEGIN
            bdcodemp     = :wcodemp;
            bdcodcol     = :wcodcol;
            bdcoddpn     = 0;
            bdtipocalcfir= 0;
            if (wtipofir = 0) then
               bdinformacao = 'Despesas judiciais';
            else
               bdinformacao = 'Despesas judiciais 13º';

            bdvalor      = COALESCE(wrendisentos, 0);
            SUSPEND;
    END
      /*   *************************************  DESPESAS JUDICIAIS  *************************************   */
    END

  /* PLANOS DE SAÚDE */
  for select a.bdcodemp, a.bdcodcol, a.bdcoddpn, a.bdtipocalcfir, a.bdinformacao, a.bdvalor, a.bdcpfcol, a.bdcpfbenef, a.bdtipoimp, a.bdvalor2, a.bdtitcol, a.bdtitcol2
      from SP_VRH_DECLARACAO_RENDIMENTOS_7_PLANOSAUDE(:prcodemp,:prcodcol,:prano,:prexportacao,:prpensaorra) a
    into :bdcodemp, :bdcodcol, :bdcoddpn, :bdtipocalcfir, :bdinformacao, :bdvalor, :bdcpfcol, :bdcpfbenef, :bdtipoimp, :bdvalor2, :bdtitcol, :bdtitcol2 do
      begin
        suspend;
      end
  BDVALOR2 = 0;
  BDTITCOL = '';
  BDTITCOL2 = '';

  /* Lançamentos anuais para DIRF. */

  wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL, FOL.BDPREVPRIVFANO, SUBSTRING(FOL.BDQUADRO3L3 FROM 1 FOR 250),'''' BDCPFCOL from VRH_EMP_TCOLCON_ANO FOL ';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
    wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

    IF (WUSARTMP_COL_SELECT = 1) THEN
       wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

  wsql = wsql||' where FOL.BDANOFUNC = '||prano||' and FOL.BDPREVPRIVFANO <> 0 ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodemp;

  IF ((prcodcol IS NOT NULL AND prcodcol <> '') AND (WUSARTMP_COL_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql|| ' union all ';
  wsql = wsql|| 'select FOL.BDCODEMP,0 BDCODCOL, FOL.BDPREVPRIVFANO, SUBSTRING(FOL.BDQUADRO3L3 FROM 1 FOR 250),BDCPFCOL from VRH_EMP_TCOLCON_ANO_cpf FOL ';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
    wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

    IF (WUSARTMP_COL_SELECT = 1) THEN
       wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCPF = FOL.BDCPFCOL AND TEMP.BDCODCOL = 0 AND TEMP.BDCODTER = 0) ';

  wsql = wsql||' where FOL.BDANOFUNC = '||prano||' and FOL.BDPREVPRIVFANO <> 0 ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodemp;


  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdvalor, :bdinformacao, :bdcpfcol DO
    BEGIN
      bdcoddpn = 0;
      bdtipocalcfir = 15;
      SUSPEND;
    END

  wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL, FOL.BDOUT13FANO, SUBSTRING(FOL.BDQUADRO5L3 FROM 1 FOR 250),'''' BDCPFCOL from VRH_EMP_TCOLCON_ANO FOL ';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
    wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

  IF (WUSARTMP_COL_SELECT = 1) THEN
     wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

  wsql = wsql||' where FOL.BDANOFUNC = '||prano||' and FOL.BDOUT13FANO <> 0 ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodemp;

  IF ((prcodcol IS NOT NULL AND prcodcol <> '') AND (WUSARTMP_COL_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodcol;

  wsql = wsql|| ' union all ';
  wsql = wsql|| 'select FOL.BDCODEMP,0 BDCODCOL, FOL.BDOUT13FANO, SUBSTRING(FOL.BDQUADRO5L3 FROM 1 FOR 250),BDCPFCOL from VRH_EMP_TCOLCON_ANO_CPF FOL ';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
    wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

  IF (WUSARTMP_COL_SELECT = 1) THEN
     wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCPF = FOL.BDCPFCOL AND TEMP.BDCODCOL = 0 AND TEMP.BDCODTER = 0) ';

  wsql = wsql||' where FOL.BDANOFUNC = '||prano||' and FOL.BDOUT13FANO <> 0 ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodemp;


  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdvalor, :bdinformacao, :bdcpfcol DO
    BEGIN
      bdcoddpn = 0;
      bdtipocalcfir = 16;
      SUSPEND;
    END

  /* Lançamentos anuais para pensão da DIRF. */

  IF (PREXPORTACAO = 0) THEN 
     begin
       wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDCODBENEF, SUM(FOL.BDVALDIRF), BEN.BDNOMBENEF, BEN.BDCPFBENEF, '''' BDCPFCOL '||
              'from VRH_EMP_TVALBENEF_DIRF FOL join VRH_EMP_TCOLCON_BENEF BEN on (BEN.BDCODEMP = FOL.BDCODEMP and BEN.BDCODCOL = FOL.BDCODCOL and BEN.BDCODBENEF = FOL.BDCODBENEF) ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
         wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';
      IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

       wsql = wsql || 'where FOL.BDANODIRF >= '||prano||'01 and FOL.BDANODIRF <= '||prano||'12';
     
       IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF ((prcodcol IS NOT NULL AND prcodcol <> '') AND (WUSARTMP_COL_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodcol;

     
       wsql = wsql||' group by FOL.BDCODEMP, FOL.BDCODCOL,BDCPFCOL , FOL.BDCODBENEF, BEN.BDNOMBENEF, BEN.BDCPFBENEF';

       wsql = wsql|| ' union all ';
       wsql = wsql|| 'select FOL.BDCODEMP, 0 BDCODCOL, 0 BDCODBENEF, SUM(FOL.BDVALDIRF), FOL.BDNOMBENEF, FOL.BDCPFBENEF,FOL.BDCPFCOL '||
              'from VRH_EMP_TVALBENEF_DIRF_CPF FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
         wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';
      IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCPF = FOL.BDCPFCOL and TEMP.BDCODCOL = 0 AND TEMP.BDCODTER  = 0)';

       wsql = wsql||' where FOL.BDANODIRF = '||prano||'  ';
     
       IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;

       wsql = wsql||' group by FOL.BDCODEMP, BDCODCOL, BDCPFCOL , BDCODBENEF, FOL.BDNOMBENEF, FOL.BDCPFBENEF';


       FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wcoddpn, :wvaldpn, :wnomdpn, :wcpfdpn, :bdcpfcol DO
         BEGIN
           bdcodemp = wcodemp;
           bdcodcol = wcodcol;
           bdcoddpn = wcoddpn;
           bdtipocalcfir = 17;
           bdinformacao = 'Pensão alimentícia: '||COALESCE(:wnomdpn, '')||', CPF: '||COALESCE(:wcpfdpn, '   .   .   -  ');
           bdvalor      = wvaldpn;
           bdcpfbenef   = wcpfdpn;
           SUSPEND;
         END
     end
    bdcpfbenef= '';
    bdcpfcol  = '';
  /* Afastamentos com benefícios */

  wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, COALESCE(S.BDNBENEFICIOSIT, '' '') from VRH_EMP_TCOLCON FOL join VRH_EMP_TSITCOL S on (S.BDCODEMP = FOL.BDCODEMP and S.BDCODCOL = FOL.BDCODCOL) ';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
    wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

  IF (WUSARTMP_COL_SELECT = 1) THEN
    wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

  wsql = wsql || 'where ((S.BDDATAINISEFIP between '||'''01/01/'||prano||''' and '||'''12/31/'||prano||''') or (s.BDDATAFIMSIT between '||'''01/01/'||prano||''' and '||'''12/31/'||prano||''')) and '||
                 ' (coalesce(S.BDNBENEFICIOSIT, ''0'') <> ''0'') and (trim(S.BDNBENEFICIOSIT) <> '''')';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodemp;

  IF ((prcodcol IS NOT NULL AND prcodcol <> '') AND (WUSARTMP_COL_SELECT = 0)) THEN
     wsql = wsql||' and '||prcodcol;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wnrbenef DO
    BEGIN
      bdcodemp = :wcodemp;
      bdcodcol = :wcodcol;
      bdinformacao = 'Número do benefício: '||:wnrbenef;
      bdvalor = 0;
      bdtipocalcfir = 18;
      SUSPEND;
    END

  /* 13º Intermitentes */

  if (coalesce(prexportacao, 0) = 0) then
     begin
       wsql = 'select BDCODEMP,BDCODCOL,SUM(BDRENDTRIBUTAVEL),SUM(BDINSS),SUM(BDIR),MAX(BDDEP),SUM(COALESCE(BDPENJUD,0) + COALESCE(BDPENALIM, 0)), SUM(BDPREVPRIV) '||
              'from (select BDCODEMP,BDCODCOL,BDREFPAG,SUM(BDRENDTRIBUTAVEL) BDRENDTRIBUTAVEL,SUM(BDINSS) BDINSS,SUM(BDIR) BDIR,MAX(BDDEP) BDDEP,SUM(BDPENJUD) BDPENJUD,'||
                           'SUM(BDPENALIM) BDPENALIM, SUM(BDPREVPRIV) BDPREVPRIV from SP_VRHF_DADOS_IR_INT13(';
       if (coalesce(prcodemp, '') <> '') then
          wsql = wsql||''''||prcodemp||''', ';
       else
          wsql = wsql||'null,';
     
       if (coalesce(prcodcol, '') <> '') then
          wsql = wsql||''''||prcodcol||''', ';
       else
          wsql = wsql||'null,';
     
       wsql = wsql||prano||'01, '||prano||'12, 0, '''', 0) ';
       wsql = wsql||'group by BDCODEMP,BDCODCOL,BDREFPAG) ';

       wsql = wsql||'group by BDCODEMP,BDCODCOL';

       for execute statement wsql into :wcodemp, :wcodcol, :wrendtrib, :winss, :wir, :wdep, :wprivatu, :wprevpriv do
         begin
           bdcodemp = :wcodemp;
           bdcodcol = :wcodcol;
           bdinformacao = 'Colaborador com trabalho intermitente:';
           bdvalor = 0;
           bdtipocalcfir = 19;
           bdtipoimp = 1;
           suspend;

           bdcodemp = :wcodemp;
           bdcodcol = :wcodcol;
           bdinformacao = SUBSTRING((' - Demonstrativo de 13º salário: '||REPLACE(CAST(CAST(:wrendtrib AS NUMERIC(18,2)) AS VARCHAR(20)), '.', ',')||' (RT) - '||
                          REPLACE(CAST(CAST(:winss AS NUMERIC(18,2)) AS VARCHAR(20)), '.', ',')||' (INSS) - '||REPLACE(CAST(CAST(:wir AS NUMERIC(18,2)) AS VARCHAR(20)), '.', ',')||' (IR) - '||
                          REPLACE(CAST(CAST(:wdep AS NUMERIC(18,2)) AS VARCHAR(20)), '.', ',')||' (Dep) - '||REPLACE(CAST(CAST(:wprivatu AS NUMERIC(18,2)) AS VARCHAR(20)), '.', ',')||' (Pensões) - '||
                          REPLACE(CAST(CAST(:wprevpriv AS NUMERIC(18,2)) AS VARCHAR(20)), '.', ',')||' (PrevComp)') FROM 1 FOR 250);
           bdvalor = wrendtrib - winss - wir - wdep - wprivatu - wprevpriv;
           if (coalesce(bdvalor, 0) < 0) then
              bdvalor = 0;
           bdtipocalcfir = 20;
           bdtipoimp = 0;
           SUSPEND;

           bdcodemp = :wcodemp;
           bdcodcol = :wcodcol;
           bdinformacao = '* RT = Rendimento Tributável; Dep = Dependentes; PrevComp = Previdência complementar';
           bdvalor = 0;
           bdtipocalcfir = 21;
           bdtipoimp = 2;
           suspend;
           bdtipoimp = 0;
         end
     end

                      /*Empréstimo sócio*/
   WSQL = 'select FOL.BDCODEMP, FOL.BDCODCOL, COTA.BDVALOREMPRESTIMO  '||
          'from EMPRESAS_TSOC SOC '||
          'join EMPRESAS_TSOCCOTAS COTA on COTA.BDCODEMP = SOC.BDCODEMP and  '||
          'COTA.BDCODSOC = SOC.BDCODSOC and '||
          ' COTA.BDREFCOTA like '''||:PRANO||'%'''||
          ' join VRH_EMP_TCOLCON FOL on FOL.BDCODEMP = SOC.BDCODEMP and '||
          ' FOL.BDCPFCOL = SOC.BDCGCCEISOC ';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
    wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

  IF (WUSARTMP_COL_SELECT = 1) THEN
     wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

  WSQL = WSQL || ' where FOL.BDCONTRCOL = 1 and'||
                 ' COTA.BDVALOREMPRESTIMO <> 0';

   IF ((prcodemp IS NOT NULL AND prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
      wsql = wsql||' and '||prcodemp;

   IF ((prcodcol IS NOT NULL AND prcodcol <> '') AND (WUSARTMP_COL_SELECT = 0)) THEN
       wsql = wsql||' and '||prcodcol;

   for execute statement wsql into :wcodemp, :wcodcol, :bdvalor do
     begin
       bdcodemp = :wcodemp;
       bdcodcol = :wcodcol;
       bdinformacao = 'Empréstimos a sócios';
       BDTIPOCALCFIR = 22;
       suspend;
     end

--  if (prpensaorra) then
--     begin
       WSQL = 'SELECT A.* FROM (select folha.bdcpfcol, FOLHA.BDCODEMP, FOLHA.BDCODCOL, FOLHA.BDCODBENEF,BNF.BDCPFBENEF,BNF.BDDATANASCBENEF,BNF.BDNOMBENEF,sum(FOLHA.BDVALPEND) BDVALOR '||
       'from (select COL.bdcpfcol, FCD.BDCODEMP, FCD.BDCODCOL, FCD.BDCODBENEF, FCD.BDVALPEND, FCD.BDREFPAGPEND as BDREF from VRHF_EMP_TFCPENSAO_DEP FCD '||
       'left outer join VRHF_EMP_TFOLHACOMP FC on (FC.BDCODEMP = FCD.BDCODEMP and FC.BDCODCOL = FCD.BDCODCOL and FC.BDREFFN = FCD.BDREFFN and FC.BDREFFC = FCD.BDREFFC)  '||
       'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FCD.BDCODEMP and COL.BDCODCOL = FCD.BDCODCOL) '||
       'where FC.BDVERCALCRRA = 1 '||
       'union all '||
       'select COL.bdcpfcol, FCDT.BDCODEMP, FCDT.BDCODCOL, FCDT.BDCODBENEF, FCDT.BDVALPEND, FCDT.BDREFPAGPEND as BDREF '||
       'from VRHF_EMP_TFCTPENSAO_DEP FCDT '||
       'left outer join VRHF_EMP_TFOLTOMCOMP FCT on (FCT.BDCODEMP = FCDT.BDCODEMP and FCT.BDCODCOL = FCDT.BDCODCOL and FCT.BDORDEM = FCDT.BDORDEM and FCT.BDREFTOMADOR = FCDT.BDREFTOMADOR and FCT.BDREFFC = FCDT.BDREFFC) '||
       'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FCDT.BDCODEMP and COL.BDCODCOL = FCDT.BDCODCOL) '||
       ' where FCT.BDVERCALCRRA = 1) FOLHA '||
       'left outer join VRH_EMP_TCOLCON_BENEF BNF on (BNF.BDCODEMP = FOLHA.BDCODEMP and BNF.BDCODCOL = FOLHA.BDCODCOL and BNF.BDCODBENEF = FOLHA.BDCODBENEF) ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
         wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = BNF.BDCODEMP) ';

       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = BNF.BDCODEMP and TEMP.BDCODCOL = BNF.BDCODCOL) ';

       wSQL = wSQL||'where FOLHA.BDREF >= '||prano||'01 and FOLHA.BDREF <= '||prano||'12 and (coalesce(BNF.BDFIMBENEF, 0) = 0) ';

      if ((prcodemp <> '') and (WUSARTMP_EMP_SELECT = 0)) THEN
         wsql = wsql ||' and '|| replace(upper(prcodemp),'FOL.','BNF.');

      if ((prcodcol <> '') AND (WUSARTMP_COL_SELECT = 0)) then
         wsql = wsql ||' and '|| replace(upper(prcodcol),'FOL.','BNF.');

      wsql = wsql || 'group by folha.BDCODEMP, folha.bdcpfcol, FOLHA.BDCODCOL, FOLHA.BDCODBENEF, BNF.BDCPFBENEF, BNF.BDDATANASCBENEF, BNF.BDNOMBENEF ';

      wsql = wsql ||' UNION ALL '||
                    'select IR.BDCPF, IR.BDCODEMP, IR.BDCODCOL, 0 BDCODBENEF, PA.BDCPFBENEFPENSAO BDCPFBENEF,PA.BDDATANASCIMENTO BDDATANASCBENEF, PA.BDNOMEBENEFPENSAO BDNOMBENEF,sum(coalesce(PA.BDVALORPENSAOMENSAL, 0)) BDVALOR  '||
                    'FROM SP_VRHF_DADOS_IR_RT(';
   
                    if (prcodemp IS NULL or prcodemp = '') then
                       wsql = wsql||'null';
                    else
                       wsql = wsql||''''||replace(upper(prcodemp),'FOL.','')||'''';
   
                    wsql = wsql||',';
   
                    if (prcodcol IS NULL or prcodcol = '') then
                       wsql = wsql||'null';
                    else
                       wsql = wsql||''''||replace(upper(prcodcol),'FOL.','')||'''';
   
                    wsql = wsql||','||prano||'01,'||prano||'12,FALSE,TRUE,1) IR '||
                    'JOIN TRT_CODIGORECEITA_IRRF CR ON (CR.BDCODRECEITAESOC = IR.BDCODRECEITAESOC) '||
                    'JOIN VRH_EMP_PENSAO_TENCARGOS_RT PA ON (PA.BDCODEMP = IR.BDCODEMP AND PA.BDCHAVE = IR.BDCHAVE AND PA.BDREFPGTO = IR.BDREFPGTO AND PA.BDCPF = IR.BDCPF AND PA.BDCODCR = CR.BDCODRECEITA) '||
                    'GROUP BY BDCODEMP, BDCODCOL, BDCPF, BDCODBENEF, BDCPFBENEF, BDDATANASCBENEF,  BDNOMBENEF ';

      wsql = wsql||') A ORDER BY A.BDCODEMP, A.bdcpfcol, A.BDCODCOL, A.BDNOMBENEF ';

      wcount = 0;
      wempatu = 0;
      wcolatu = 0;

       for execute statement wsql into :bdcpfcol, :WCODEMP, :WCODCOL, :wcoddpn, :wcpfdpn, :wdtnasc, :wnomdpn, :wvaldpn do
         begin
           wcodcol = coalesce(wcodcol,0);

           if ((wcount < 1) OR (wempatu <> wcodemp) OR (wcolatu <> wcodcol)) then
              begin
                BDCODEMP = :WCODEMP;
                BDCODCOL = :WCODCOL;
                bdcoddpn = 0;
                BDINFORMACAO = 'Beneficiários de pensão alimentícia RRA';
                BDTIPOCALCFIR = 23;
                bdtipoimp = 1;
                bdvalor = 0;
                SUSPEND;
                bdtipoimp = 0;
         
                BDCODEMP = :WCODEMP;
                BDCODCOL = :WCODCOL;
                bdcoddpn = 0;
                BDINFORMACAO = 'CPF               Nascimento    Nome';
                BDTIPOCALCFIR = 24;
                bdvalor = 0;
                SUSPEND;

                wempatu = :wcodemp;
                wcolatu = :wcodcol;
                wcount = 0;
              end

           BDCODEMP = :WCODEMP;
           BDCODCOL = :WCODCOL;
           bdcoddpn = :wcoddpn;

           if (:WDTNASC is null) then
             WDTNASCS = '  /  /    ';
           else
             WDTNASCS = substring(cast(:WDTNASC as varchar(10)) from 9 for 2) || '/' || substring(cast(:WDTNASC as varchar(10)) from 6 for 2) || '/' || substring(cast(:WDTNASC as varchar(10)) from 1 for 4);

           if ((:WCPFDPN is null) or (trim(:WCPFDPN) = '.   .   -') or (trim(:WCPFDPN) = '')) then
             WCPFDPN = '              ';


           BDINFORMACAO = wcpfdpn||'    '||WDTNASCS|| '    ' ||coalesce(:WNOMDPN, '');
           BDTIPOCALCFIR = 25;
           bdvalor = wvaldpn;
           SUSPEND;
           wcount = wcount + 1;
         end

       wsql = 'SELECT * FROM (select Y.BDCODEMP,Y.BDCODCOL,max(Y.BDDRENDISENTOS) BDINFORMACAO,sum(Y.BDRENDISENTOS) BDVALOR, sum(Y.BDAUXILIOMORADIA) BDAUXILIOMORADIA '||
              'from SP_VRHF_DADOS_IR_FC_RRA(';
              if (prcodemp IS NULL or prcodemp = '') then
                       wsql = wsql||'null';
                    else
                       wsql = wsql||''''||prcodemp||'''';
   
                    wsql = wsql||',';
   
                    if (prcodcol IS NULL or prcodcol = '') then
                       wsql = wsql||'null';
                    else
                       wsql = wsql||''''||prcodcol||'''';
   
                    wsql = wsql||','||prano||'01,'||prano||'12) Y ';
       wsql = wsql||'where (COALESCE(Y.BDRENDISENTOS,0) > 0) or (COALESCE(Y.BDAUXILIOMORADIA, 0) > 0) '||
              'group by Y.BDCODEMP, Y.BDCODCOL '||
              'UNION ALL '||
              'select RT.BDCODEMP,RT.BDCODCOL,max(RT.BDDESCRENDNAOTRIBUT) BDINFORMACAO,sum(RT.BDRENDNAPTRIBUT) BDVALOR, 0 BDAUXILIOMORADIA '||
              'FROM SP_VRHF_DADOS_IR_RT(';
   
                    if (prcodemp IS NULL or prcodemp = '') then
                       wsql = wsql||'null';
                    else
                       wsql = wsql||''''||replace(upper(prcodemp),'FOL.','')||'''';
   
                    wsql = wsql||',';
   
                    if (prcodcol IS NULL or prcodcol = '') then
                       wsql = wsql||'null';
                    else
                       wsql = wsql||''''||replace(upper(prcodcol),'FOL.','')||'''';
   
                    wsql = wsql||','||prano||'01,'||prano||'12,FALSE,TRUE,1) RT '||
              'where COALESCE(RT.BDRENDNAPTRIBUT,0) > 0 '||
              'GROUP BY RT.BDCODEMP,RT.BDCODCOL '||
              ') A ORDER BY A.BDCODEMP,A.BDCODCOL';

       wempatu = 0;
       wcolatu = 0;
       for execute statement wsql INTO :wcodemp, :wcodcol, :wdescrend, :wrendisentos, :wauxiliomoradia DO
         begin

           if ((wcodemp <> wempatu) or (wcodcol <> wcolatu)) then
              begin
                bdcodemp      = wcodemp;
                bdcodcol      = wcodcol;                
                bdtipocalcfir = 8;
                bdvalor       = :wrendisentos;

                if (COALESCE(WAUXILIOMORADIA, 0.00) <> 0) then
                   begin
                     bdvalor = bdvalor + wauxiliomoradia;

                     if ((TRIM(COALESCE(wdescrend, '')) = '')) then
                        wdescrend = 'AUXÍLIO MORADIA';
                     else
                        if ((POSITION('AUXÍLIO MORADIA', wdescrend) = 0)) then
                           wdescrend  = wdescrend || ', AUXÍLIO MORADIA';

                   end

                bdinformacao  = SUBSTRING('Rendimentos isentos : '||:wdescrend FROM 1 FOR 250);

                bdcoddpn      = 0;
                SUSPEND;
                wempatu = wcodemp;
                wcolatu = wcodcol;
             end
         end


      wsql =  'select  RT.BDCODEMP, RT.BDCODCOL,RT.BDCPF,BDNUMPROCESSO,list(substring(bdrefpgto from 5 for 2) || ''/'' || substring(bdrefpgto from 1 for 4)|| '' '','''')'||
              'FROM SP_VRHF_DADOS_IR_RT(';
   
                    if (prcodemp IS NULL or prcodemp = '') then
                       wsql = wsql||'null';
                    else
                       wsql = wsql||''''||replace(upper(prcodemp),'FOL.','')||'''';
   
                    wsql = wsql||',';
   
                    if (prcodcol IS NULL or prcodcol = '') then
                       wsql = wsql||'null';
                    else
                       wsql = wsql||''''||replace(upper(prcodcol),'FOL.','')||'''';
   
                    wsql = wsql||','||prano||'01,'||prano||'12,FALSE,TRUE,1) RT '||
              'where (coalesce(BDIRRFMENSAL, 0.00) > 0) '||
              'group by  RT.BDCODEMP, RT.BDCODCOL,RT.BDCPF,BDNUMPROCESSO ';

       wempatu = 0;
       wcolatu = 0;
       for execute statement wsql INTO :wcodemp, :wcodcol,:bdcpfcol, :WNMRPROC,:WREFERENCIASPROC DO
         begin
              begin
                bdcodemp      = wcodemp;
                bdcodcol      = wcodcol;
                bdinformacao  = 'Número do processo: ' ||:WNMRPROC;
                bdcoddpn      = 0;
                bdvalor       = 0;
                bdtipocalcfir = 26;
                SUSPEND;
                bdinformacao  = 'Meses RRA: ' ||:WREFERENCIASPROC;
                bdtipocalcfir = 27;
                SUSPEND;
             end
         end

end^

/* Restore proc. body: SP_DECLARARENDPLANSAU_SOCIO */
create or alter procedure SP_DECLARARENDPLANSAU_SOCIO (
    PRCODEMP varchar(32000),
    PRCODCOL varchar(32000),
    PRANOBASE integer,
    PRSOMENTESOCIOS varchar(5) = '',
    PRWHERENOTCODEMP varchar(32000) = '',
    PRWHERENOTSOCIOS varchar(32000) = '',
    PRWHERENOTCONVENIO varchar(32000) = '',
    PRCODDEP integer = null,
    PRCNPJCONVENIO varchar(18) = '',
    PRCPFSOCIO varchar(14) = '')
returns (
    BDCODEMP integer,
    BDCODSOC integer,
    BDCNPJ varchar(18),
    BDRAZAOSOCIAL varchar(80),
    BDCODDEP integer,
    BDNOME varchar(70),
    BDCPF varchar(14),
    BDVALORPLANO DM_NUMERIC_15_2,
    BDCODCONVENIO integer,
    BDCODCOL integer)
as
declare variable WSQL varchar(32700);
declare variable WREFINI integer;
declare variable WREFFIM integer;
declare variable WCNPJSOC varchar(18);
declare variable WBDREFINI integer;
declare variable WBDREFFIN integer;
declare variable WVALPLANO DM_NUMERIC_15_2;
declare variable WCODOPERADORA integer;
declare variable WCODOPERADORAATU integer;
declare variable WCODEMP integer;
declare variable WCODEMPATU integer;
declare variable WCODSOC integer;
declare variable WCODSOCATU integer;
declare variable WCODDEP integer;
declare variable WCODDEPATU integer;
declare variable WORDEMDEP integer;
declare variable WORDEMDEPATU integer;
begin
  prcodemp = trim(upper(coalesce(prcodemp, '')));
  prcodcol = trim(upper(coalesce(prcodcol, '')));
  prcnpjconvenio = trim(coalesce(prcnpjconvenio, ''));
  prcpfsocio = trim(coalesce(prcpfsocio, ''));

  wrefini = cast((cast(pranobase as varchar(4))||'01') as integer);
  wreffim = cast((cast(pranobase as varchar(4))||'12') as integer);

  wsql = 'select SOC.BDCODEMP, SOC.BDCODSOC, SOC.BDCGCCEISOC, COL.BDCODCOL '||
         'from EMPRESAS_TSOC SOC '||
         'join EMPRESAS_TSOCCOTAS CT on (CT.BDCODEMP = SOC.BDCODEMP and CT.BDCODSOC = SOC.BDCODSOC) ';

  if (prcodemp = 'TMP_EMPRESAS_SELECT') then
      wsql = wsql||'join TMP_EMPRESAS_SELECT FILTRO on (FILTRO.BDCODEMP = SOC.BDCODEMP) ';

  wsql = wsql||
         'left outer join (select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDCPFCOL ' ||
                          'from VRH_EMP_TCOLCON FOL ' ||
                          'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) ' ||
                          'where FOL.BDCONTRCOL = 1 and ' ||
                                '((RESC.BDDATARESCISAO is null) or (RESC.BDREFRESCISAO >= ' || wrefini || ')) and '||
                                '(FOL.BDREFADMCOL <= '||wreffim||')) COL '||
         ' on (COL.BDCODEMP = SOC.BDCODEMP and COL.BDCPFCOL = SOC.BDCGCCEISOC) ';

  wsql = wsql||
         'where (CT.BDREFCOTA between '||wrefini||' and '||wreffim||') ';

  if (prcodemp <> 'TMP_EMPRESAS_SELECT' and prcodemp <> '') then
     wsql = wsql||' and ('||prcodemp||') ';
  if (prcodcol <> '') then
     wsql = wsql||' and ('||prcodcol||') ';

   /*Caso seja sócio contribuinte deve verificar a informação se está ativo no ano da consulta*/
   if (PRSOMENTESOCIOS = 'TRUE') then
     wsql = wsql ||' and (COL.BDCPFCOL is null) ';
   else
   if (PRSOMENTESOCIOS = 'FALSE') then
     wsql = wsql ||' and (COL.BDCPFCOL is not null) ';

  if ((PRWHERENOTCODEMP <> '') and (PRWHERENOTSOCIOS <> '') and (PRWHERENOTCONVENIO <> '')) then
    wsql = wsql||' and ((not(SOC.BDCODEMP in ('||PRWHERENOTCODEMP||'))) and (not(SOC.BDCODSOC IN ('||PRWHERENOTSOCIOS||'))) and (not(SOC.BDCODCONVENIO IN ('||PRWHERENOTCONVENIO||'))))';

  if (PRCPFSOCIO <> '') then
     wsql = wsql||' and (COL.BDCPFCOL = '''||PRCPFSOCIO||''') ' ;

  wsql = wsql||
         'group by SOC.BDCODEMP, SOC.BDCODSOC, SOC.BDCGCCEISOC, COL.BDCODCOL ';

  BDCNPJ = null;
  BDRAZAOSOCIAL = null;
  BDNOME = null;
  BDCPF = null;

  wcodoperadoraatu = -1;
  wcodempatu = -1;
  wcodsocatu = -1;
  wcoddepatu = -1;
  wordemdepatu = -1;

  for execute statement wsql
  into :BDCODEMP, :BDCODSOC, :wcnpjsoc, :BDCODCOL
  do
    begin
      BDVALORPLANO = 0;
      wbdrefini = 0;
      for select SAU.BDREFINI, SAU.BDREFFIN, DEP.BDCODOPERADORA, SAU.BDCODEMP, SAU.BDCODSOC, coalesce(DEP.BDCODDEP, 0), coalesce(DEP.BDORDEMDEP, 0), DEP.BDVALORPLANO
          from VEF_EMP_TLAN_PLASAUDE SAU
          join VEF_EMP_TLAN_PLASAUDE_DEP DEP on (DEP.BDCODEMP = SAU.BDCODEMP and DEP.BDCHAVE = SAU.BDCHAVE)
          where SAU.BDCODEMP = :BDCODEMP and SAU.BDCODSOC = :BDCODSOC and
                SAU.BDREFINI <= :wreffim and ((coalesce(SAU.BDREFFIN, 0) <= 0) or (coalesce(SAU.BDREFFIN, 0) >= :wrefini))
          order by DEP.BDCODEMP, DEP.BDCODOPERADORA, DEP.BDCODDEP, DEP.BDORDEMDEP
      into :wbdrefini, :wbdreffin, :wcodoperadora, :wcodemp, wcodsoc, :wcoddep, :wordemdep, :wvalplano
      do
        begin
          if (prcoddep is not null and prcoddep <> wordemdep) then
             continue;

          if (wcodoperadoraatu = -1) then
              wcodoperadoraatu = wcodoperadora;
          if (wcodempatu = -1) then
              wcodempatu = wcodemp;
          if (wcodsocatu = -1) then
              wcodsocatu = wcodsoc;
          if (wcoddepatu = -1) then
              wcoddepatu = wcoddep;
          if (wordemdepatu = -1) then
              wordemdepatu = wordemdep;


          if ((wcodoperadoraatu <> wcodoperadora) or (wcoddepatu <> wcoddep) or (wordemdepatu <> wordemdep)) then
             begin
               BDCODCONVENIO = wcodoperadoraatu;
               BDCODEMP = wcodempatu;
               BDCODSOC = wcodsocatu;
               BDCODDEP = wordemdepatu;

               BDCNPJ = null;
               BDRAZAOSOCIAL = null;
               select first 1 OP.BDCNPJ, OP.BDRAZAOSOCIAL
               from VRH_BASE_TCONVSAUDE OP
               where OP.BDCODCONVENIO = :BDCODCONVENIO into :BDCNPJ, :BDRAZAOSOCIAL;

               BDNOME = null;
               BDCPF = null;

               if (prcnpjconvenio <> '') then
                  begin
                    if (prcnpjconvenio <> BDCNPJ) then
                       begin
                         wcodoperadoraatu = wcodoperadora;
                         wcoddepatu = wcoddep;
                         wordemdepatu = wordemdep;
                         BDVALORPLANO = 0;
                         continue;
                       end
                  end

               if (BDCODDEP <= 0) then
                  begin
                    select first 1 REF.BDNOMSOC
                    from EMPRESAS_TSOC_REF REF
                    where REF.BDCODEMP = :BDCODEMP and REF.BDCODSOC = :BDCODSOC
                    order by REF.BDCODEMP desc, REF.BDCODSOC desc, REF.bdrefsoc desc
                    into :BDNOME;
                    BDCPF = :wcnpjsoc;
                  end
               else
                  begin
                    select first 1 DEP.BDNOMDEP, DEP.BDCPFDEP
                    from VEF_EMP_TDEP_PLASAUDE_DEP DEP
                    where DEP.BDCODEMP = :BDCODEMP and DEP.BDCODDEP = :wcoddepatu and DEP.BDORDEM = :wordemdepatu
                    into :BDNOME, :BDCPF;
                  end

               if (prcpfsocio <> '') then
                  begin
                    if (prcpfsocio <> BDCPF) then
                       begin
                         wcodoperadoraatu = wcodoperadora;
                         wcoddepatu = wcoddep;
                         wordemdepatu = wordemdep;
                         BDVALORPLANO = 0;
                         continue;
                       end
                  end

               if (BDVALORPLANO > 0) then
                  suspend;

               wcodempatu = wcodemp;
               wcodsocatu = wcodsoc;
               wcodoperadoraatu = wcodoperadora;
               wcoddepatu = wcoddep;
               wordemdepatu = wordemdep;
               BDVALORPLANO = 0;
             end


          wbdreffin = coalesce(wbdreffin, 0);

          if (wbdrefini < wrefini) then
             wbdrefini = wrefini;

          if ((wbdreffin <= 0) or (wbdreffin > wreffim)) then
             wbdreffin = wreffim;

          while (wbdrefini <= wbdreffin) do
            begin
              wvalplano = coalesce(wvalplano, 0);
              BDVALORPLANO = BDVALORPLANO + wvalplano;


              -- Incrementa a competência inicial
              if (substring(wbdrefini from 5 for 2) = '12') then
                 wbdrefini = cast((cast((cast(substring(wbdrefini from 1 for 4) as integer) + 1) as varchar(4)) || '01') as integer);
              else
                 wbdrefini = cast((substring(wbdrefini from 1 for 4) || lpad(trim(cast((cast(substring(wbdrefini from 5 for 2) as integer) + 1) as varchar(2))), 2, '0')) as integer);
            end
        end

        if (wbdrefini = 0) then   -- socio nao possui nenhum registro no lancamento de plano de saude 
           continue;

        BDCODCONVENIO = wcodoperadoraatu;
        BDCODEMP = wcodempatu;
        BDCODSOC = wcodsocatu;
        BDCODDEP = wordemdepatu;

        BDCNPJ = null;
        BDRAZAOSOCIAL = null;
        select first 1 OP.BDCNPJ, OP.BDRAZAOSOCIAL
        from VRH_BASE_TCONVSAUDE OP
        where OP.BDCODCONVENIO = :BDCODCONVENIO into :BDCNPJ, :BDRAZAOSOCIAL;

        BDNOME = null;
        BDCPF = null;

        if (BDCODDEP <= 0) then
           begin
             select first 1 REF.BDNOMSOC
             from EMPRESAS_TSOC_REF REF
             where REF.BDCODEMP = :BDCODEMP and REF.BDCODSOC = :BDCODSOC
             order by REF.BDCODEMP desc, REF.BDCODSOC desc, REF.bdrefsoc desc
             into :BDNOME;
             BDCPF = :wcnpjsoc;
           end
        else
           begin
             select first 1 DEP.BDNOMDEP, DEP.BDCPFDEP
             from VEF_EMP_TDEP_PLASAUDE_DEP DEP
             where DEP.BDCODEMP = :BDCODEMP and DEP.BDCODDEP = :wcoddepatu and DEP.BDORDEM = :wordemdepatu
             into :BDNOME, :BDCPF;
           end

        if (BDVALORPLANO > 0) then
           suspend;
        BDVALORPLANO = 0;

    end


  BDCODCONVENIO = wcodoperadora;
  BDCODEMP = wcodemp;
  BDCODSOC = wcodsoc;
  BDCODDEP = wordemdep;

  wcodempatu = wcodemp;
  wcodsocatu = wcodsoc;
  wordemdepatu = wordemdep;

  if (wcodoperadoraatu > 0) then
     begin
       BDCODCONVENIO = wcodoperadoraatu;
       BDCODDEP = wordemdepatu;
 
       BDCNPJ = null;
       BDRAZAOSOCIAL = null;
       select first 1 OP.BDCNPJ, OP.BDRAZAOSOCIAL
       from VRH_BASE_TCONVSAUDE OP
       where OP.BDCODCONVENIO = :BDCODCONVENIO into :BDCNPJ, :BDRAZAOSOCIAL;
 
       if (prcnpjconvenio <> '') then
          begin
            if (prcnpjconvenio <> BDCNPJ) then
               exit;
          end

       BDNOME = null;
       BDCPF = null;
 
       if (BDCODDEP <= 0) then
          begin
            select first 1 REF.BDNOMSOC
            from EMPRESAS_TSOC_REF REF
            where REF.BDCODEMP = :BDCODEMP and REF.BDCODSOC = :BDCODSOC
            order by REF.BDCODEMP desc, REF.BDCODSOC desc, REF.bdrefsoc desc
            into :BDNOME;
            BDCPF = :wcnpjsoc;
          end
       else
          begin
            select first 1 DEP.BDNOMDEP, DEP.BDCPFDEP
            from VEF_EMP_TDEP_PLASAUDE_DEP DEP
            where DEP.BDCODEMP = :BDCODEMP and DEP.BDCODDEP = :wcoddepatu and DEP.BDORDEM = :wordemdepatu
            into :BDNOME, :BDCPF;
          end
 
       if (prcpfsocio <> '') then
       begin
         if (prcpfsocio <> BDCPF) then
            exit;
       end

      if (BDVALORPLANO > 0) then
         suspend;
   end
END^

/* Restore proc. body: SP_VRH_EMP_MULTVINC_PGTO */
ALTER PROCEDURE SP_VRH_EMP_MULTVINC_PGTO(PREMPRESA VARCHAR(32000),
PRCOL VARCHAR(32000),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFCOL INTEGER,
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6))
 AS
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WREF VARCHAR(6);
DECLARE VARIABLE WSQL VARCHAR(32000);
BEGIN
  /* Procedure Text */
--  suspend;
  EXECUTE PROCEDURE sp_seta_competencia(prref,NULL,NULL);

  wano = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wMes = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);

  IF (wmes = 1) THEN
     BEGIN
       wano = wano - 1;
       wmes = 12;
     END
  ELSE
     BEGIN
       wmes = wmes - 1;
     END

  wref = ''||wano;

  IF (wmes < 10) THEN
     wref = wref||'0'||wmes;
  ELSE
     wref = wref||wmes;

  prref = CAST(wref AS INTEGER);

  -- carrega dados do mês atual para empresas com pagamento no mês
  wsql = 'select v.bdcodemp, v.bdcodcol, v.bdrefcol, v.bdbaseinssncol, v.bdvalorinssncol, v.bdbaseirrfncol, '||
                 ' v.bdvalorirrfncol, v.bdbaseinss13col, v.bdvalorinss13col, v.bdbaseirrf13col, '||
                 ' v.bdvalorirrf13col from VW_VRHF_EMP_TCOLCON_MVINC v '||
         ' left outer join vw_vrhf_base_tempcalc emp on (emp.bdcodemp = v.bdcodemp) '||
         ' join VW_VRH_EMP_TCOLCON_VINC colv on (colv.bdcodemp = v.bdcodemp and colv.bdcodcol = v.bdcodcol)'||
         ' join vrh_base_tclasse cla on (cla.bdcodcla = colv.bdcodcla)'||
         ' where ((cla.bdgrupocla <> 2 and coalesce(emp.BDPAGEMP,0) = 1) or (cla.bdgrupocla = 2 and coalesce(emp.BDPAGEMPCONTR,0) = 1))';

  IF ((prempresa IS NOT NULL) AND (prempresa <> '')) THEN
     BEGIN
       wsql = wsql||' and '||prempresa;

       IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
          wsql = wsql||' and '||prcol;
     END

  FOR EXECUTE STATEMENT wsql INTO
    bdcodemp,
    bdcodcol,
    bdrefcol,
    bdbaseinssncol,
    bdvalorinssncol,
    bdbaseirrfncol,
    bdvalorirrfncol,
    bdbaseinss13col,
    bdvalorinss13col,
    bdbaseirrf13col,
    bdvalorirrf13col
  DO
   BEGIN
     SUSPEND;
   END

  -- Carrega dados do mês anterior para empresas com pagamento no mês seguinte
  EXECUTE PROCEDURE sp_seta_competencia(prref,NULL,NULL);
  wsql = 'select v.bdcodemp, v.bdcodcol, v.bdrefcol, v.bdbaseinssncol, v.bdvalorinssncol, v.bdbaseirrfncol, '||
                 ' v.bdvalorirrfncol, v.bdbaseinss13col, v.bdvalorinss13col, v.bdbaseirrf13col, '||
                 ' v.bdvalorirrf13col from VW_VRHF_EMP_TCOLCON_MVINC v '||
         ' left outer join vw_vrhf_base_tempcalc emp on (emp.bdcodemp = v.bdcodemp) '||
         ' join VW_VRH_EMP_TCOLCON_VINC colv on (colv.bdcodemp = v.bdcodemp and colv.bdcodcol = v.bdcodcol)'||
         ' join vrh_base_tclasse cla on (cla.bdcodcla = colv.bdcodcla)'||
         ' where ((cla.bdgrupocla <> 2 and coalesce(emp.BDPAGEMP,0) = 0) or (cla.bdgrupocla = 2 and coalesce(emp.BDPAGEMPCONTR,0) = 0))';

  IF ((prempresa IS NOT NULL) AND (prempresa <> '')) THEN
     BEGIN
       wsql = wsql||' and '||prempresa;

       IF ((prcol IS NOT NULL) AND (prcol <> '')) THEN
          wsql = wsql||' and '||prcol;
     END

  FOR EXECUTE STATEMENT wsql INTO
    bdcodemp,
    bdcodcol,
    bdrefcol,
    bdbaseinssncol,
    bdvalorinssncol,
    bdbaseirrfncol,
    bdvalorirrfncol,
    bdbaseinss13col,
    bdvalorinss13col,
    bdbaseirrf13col,
    bdvalorirrf13col
  DO
   BEGIN
     SUSPEND;
   END
END
^

/* Restore proc. body: SP_VRH_EMP_TCOLCON_VINC */
ALTER PROCEDURE SP_VRH_EMP_TCOLCON_VINC(PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDGRUPOCLA INTEGER)
 AS
BEGIN
/*  execute procedure sp_seta_competencia(PRREFERENCIA, null, null);

  for select VINC.BDCODEMP, VINC.BDCODCOL, VINC.BDCODCLA, CLA.BDDESCCLA, CLA.BDGRUPOCLA
      from vw_colaboradores_ref_atual VINC,
           vrh_base_tclasse CLA
      where VINC.bdcodcla = CLA.bdcodcla
      order by VINC.BDCODEMP, VINC.BDCODCOL

      into :BDCODEMP, :BDCODCOL, :BDCODCLA, :BDDESCCLA, :BDGRUPOCLA do

  suspend;

  execute procedure sp_seta_competencia(null, null, null); */
END
^

/* Restore proc. body: SP_VRH_FECHAMENTO */
alter procedure SP_VRH_FECHAMENTO (
    PREMPRESAS varchar(32000),
    PRREF integer = 0,
    PRTIPOPER integer = 1,
    prdataini varchar(10) = '',    /*André Cursino - 168821 - 14/12/2022*/
    prdatafim varchar(10) = '')    /*André Cursino - 168821 - 14/12/2022*/
returns (
    BDCODEMP integer,
    BDFECHAMENTO integer,
    BDDATA date)
as
declare variable WSQL varchar(32000);
declare variable WDATAINI date;
declare variable WDATFIM date;
declare variable WDIAINI integer;
declare variable WMESINI smallint;
declare variable WANOINI integer;
declare variable WDIAFIM integer;
declare variable WMESFIM smallint;
declare variable WANOFIM integer;
BEGIN
  /* Procedure Text */
  IF ((prref IS NULL) OR (prref = 0))  THEN
     SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database INTO prref;

  EXECUTE PROCEDURE sp_seta_competencia(prref,NULL,NULL);

  wSql = 'select bdcodemp,BDFECHAMESEMP from VW_VRHF_BASE_TEMPCALC';

  IF ((prempresas IS NOT NULL) AND (prempresas <> ''))  THEN
     wSql = wSql||' where '||prempresas;

  /*André Cursino - 168821 - 14/12/2022 - inicio*/
  if (prdataini = '12/30/1899') then
    prDataIni = '';

  if (prdatafim = '12/30/1899') then
    prDataFim = '';
  /*André Cursino - 168821 - 14/12/2022 - fim*/  

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdfechamento DO
    BEGIN
      /*André Cursino - 168821 - 14/12/2022 - inicio*/
      if (prdataini <> '') then
        begin
          wDiaIni = CAST(SUBSTRING(prdataini from 4 for 2) AS INTEGER);
          wMesIni = CAST(SUBSTRING(prdataini from 1 for 2) AS INTEGER);
          wAnoIni = CAST(SUBSTRING(prdataini from 7) AS INTEGER);
          if (prDataFim <> '') then
            begin
              wDiaFim = CAST(SUBSTRING(prDataFim from 4 for 2) AS INTEGER);
              wMesFim = CAST(SUBSTRING(prDataFim from 1 for 2) AS INTEGER);
              wAnoFim = CAST(SUBSTRING(prDataFim from 7) AS INTEGER);
            end
        end
      /*André Cursino - 168821 - 14/12/2022 - fim*/ 
      else IF ((bdfechamento >= 28) OR (bdfechamento IS NULL) OR (bdfechamento <= 1) OR (PRTIPOPER = 0)) THEN
         BEGIN
           wdiaini = 1;
           wmesini = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
           wmesfim = wmesini;
           wanoini = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
           wanofim =  wanoini;
           SELECT ULTDIA FROM ultimo_dia_mes(:wmesfim,:wanofim) INTO wdiafim;
         END
      ELSE
         BEGIN
           wdiaini = bdfechamento + 1;
           wdiafim = bdfechamento;
           wmesfim = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
           wanofim = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);

           IF (wmesfim = 1) THEN
              BEGIN
                wmesini = 12;
                wanoini = wanofim - 1;
              END
           ELSE
              BEGIN
                 wmesini = wmesfim - 1;
                 wanoini = wanofim;
              END
         END

      wdataini = CAST(''||wmesini||'-'||wdiaini||'-'||wanoini AS DATE);
      if (wdiafim is not null) then                                        /*André Cursino - 168821 - 14/12/2022*/
        wdatfim = CAST(''||wmesfim||'-'||wdiafim||'-'||wanofim AS DATE);
      else                                                                 /*André Cursino - 168821 - 14/12/2022*/
        wDatFim = DateAdd(month, 1, wdataini);                             /*André Cursino - 168821 - 14/12/2022*/

      WHILE (wdataini <= wdatfim) DO
        BEGIN
          bddata = wdataini;
          wdataini = wdataini + 1;

          SUSPEND;
        END
    END
END
^

/* Restore proc. body: SP_RETORNA_TIPOS_CONTR_SIND */
CREATE OR ALTER PROCEDURE SP_RETORNA_TIPOS_CONTR_SIND (
    PRCODEMP INTEGER,
    PRCODCOL INTEGER,
    PRREF INTEGER,
    PRRETMEN INTEGER,
    PRRETSIND INTEGER,
    PRRETCONF INTEGER,
    PRRETTAXAS INTEGER,
    PRRETREV INTEGER) 
RETURNS (
    BDMENSALIDADE NUMERIC(15,6),
    BDCONTSIND NUMERIC(15,6),
    BDCONTCONF NUMERIC(15,6),
    BDTAXAS NUMERIC(15,6),
    BDREVERSAO NUMERIC(15,6)) 
AS
DECLARE VARIABLE WSQL VARCHAR(1500);
DECLARE VARIABLE WLEFTCONTRIBUICOES VARCHAR(1000);
DECLARE VARIABLE WCAMPOSCONTRIBUICOES VARCHAR(500);
DECLARE VARIABLE WWHERECONTRIBUICOES VARCHAR(600);
DECLARE VARIABLE WOR VARCHAR(5);
BEGIN
  wleftcontribuicoes   = '';
  wcamposcontribuicoes = '';
  wwherecontribuicoes  = '';
  wor = '';

  IF (prretmen = 1) THEN
    BEGIN
      wor = ' or ';
      wcamposcontribuicoes = ' coalesce(MEN.BDVALVFN, 0.0) mensalidade, ';
      wleftcontribuicoes = ' left outer join VW_CLASS_00400 MEN on (MEN.BDCODEMP = COL.BDCODEMP and MEN.BDCODCOL = COL.BDCODCOL and MEN.BDREFFN = '||:prref||')';
      wwherecontribuicoes = ' (MEN.BDVALVFN <> 0.0)';
    END
  ELSE
    wcamposcontribuicoes = ' 0.0 mensalidade, ';

  IF (prretsind = 1) THEN
    BEGIN
      wcamposcontribuicoes = wcamposcontribuicoes || ' coalesce(SIND.BDVALVFN, 0.0) contsind, ';
      wleftcontribuicoes = wleftcontribuicoes ||' left outer join VW_CLASS_00401 SIND on (SIND.BDCODEMP = COL.BDCODEMP and SIND.BDCODCOL = COL.BDCODCOL and SIND.BDREFFN = '||:prref||')';
      wwherecontribuicoes = wwherecontribuicoes || wor || ' (SIND.BDVALVFN <> 0.0) ';
      wor = ' or ';
    END
  ELSE
    wcamposcontribuicoes = wcamposcontribuicoes || ' 0.0 contsind, ';

  IF (prretconf = 1) THEN
    BEGIN
      wcamposcontribuicoes = wcamposcontribuicoes || ' coalesce(CONF.BDVALVFN, 0.0) contconf, ';
      wleftcontribuicoes = wleftcontribuicoes ||' left outer join VW_CLASS_00402 CONF on (CONF.BDCODEMP = COL.BDCODEMP and CONF.BDCODCOL = COL.BDCODCOL and CONF.BDREFFN = '||:prref||')';
      wwherecontribuicoes = wwherecontribuicoes || wor || ' (CONF.BDVALVFN <> 0.0) ';
      wor = ' or ';
    END
  ELSE
    wcamposcontribuicoes = wcamposcontribuicoes || ' 0.0 contconf, ';

  IF (prrettaxas = 1) THEN
    BEGIN
      wcamposcontribuicoes = wcamposcontribuicoes || ' coalesce(TAXAS.BDVALVFN, 0.0) taxas, ';
      wleftcontribuicoes = wleftcontribuicoes ||' left outer join VW_CLASS_00403 TAXAS on (TAXAS.BDCODEMP = COL.BDCODEMP and TAXAS.BDCODCOL = COL.BDCODCOL and TAXAS.BDREFFN = '||:prref||')';
      wwherecontribuicoes = wwherecontribuicoes || wor || ' (TAXAS.BDVALVFN <> 0.0) ';
      wor = ' or ';
    END
  ELSE
    wcamposcontribuicoes = wcamposcontribuicoes || ' 0.0 taxas, ';

  IF (prretrev = 1) THEN
    BEGIN
      wcamposcontribuicoes = wcamposcontribuicoes || ' coalesce(REV.BDVALVFN, 0.0) reversao ';
      wleftcontribuicoes = wleftcontribuicoes ||' left outer join VW_CLASS_00404 REV on (REV.BDCODEMP = COL.BDCODEMP and REV.BDCODCOL = COL.BDCODCOL and REV.BDREFFN = '||:prref||')';
      wwherecontribuicoes = wwherecontribuicoes || wor || ' (REV.BDVALVFN <> 0.0) ';
      wor = ' or ';
    END
  ELSE
    wcamposcontribuicoes = wcamposcontribuicoes || ' 0.0 reversao ';

  IF (wwherecontribuicoes = '') THEN
    BEGIN
      SUSPEND;
      EXIT;
    END

  wsql = 'select ' ||wcamposcontribuicoes|| ' from VRH_EMP_TCOLCON COL ' || wleftcontribuicoes || ' where (COL.BDCODEMP = '||:prcodemp||')';

  IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
    wsql = wsql || ' and (COL.BDCODCOL = '||:prcodcol||')';

  wsql = wsql ||' and ('||wwherecontribuicoes||')';

  FOR EXECUTE STATEMENT wsql INTO :bdmensalidade, :bdcontsind, :bdcontconf, :bdtaxas, :bdreversao DO
    SUSPEND;
END^

--Sol. 17643 - Inserida a palavra 'where' na String da variável wwherecontrib2 - Bruno L. R. - 24/07/2017
/* Restore proc. body: SP_VRH_RETORNA_CONTR_SIND */
CREATE OR ALTER procedure SP_VRH_RETORNA_CONTR_SIND (
    PREMPRESA varchar(15000),
    PRCOLABORADOR varchar(30000),
    PRREF integer,
    PRMENSIND integer,
    PRCONTSIND integer,
    PRCONTCONF integer,
    PRTAXAASSIS integer,
    PRREVSAL integer,
    PRHISTTRANSF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDREF integer,
    MENSALIDADE numeric(15,6),
    CONTSIND numeric(15,6),
    CONTCONF numeric(15,6),
    TAXAS numeric(15,6),
    REVERSAO numeric(15,6),
    BDCODSINTRAB integer,
    BDDESCSINTRAB varchar(60),
    BDCODEMPORIG integer,
    BDCODCOLORIG integer)
as
declare variable WSQL varchar(5000);
declare variable WWHERE varchar(32700);
declare variable WEMP varchar(15000);
declare variable WCOL varchar(30000);
declare variable WWHERECONTRIB2 varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
declare variable WSQLAUX varchar(32700);
declare variable WSQL2 varchar(2000);
declare variable WSQL3 varchar(2000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
BEGIN
  IF (prempresa IS NOT NULL AND prempresa <> '') THEN
     BEGIN
       wwhere = prempresa;
     END

  IF (prcolaborador IS NOT NULL AND prcolaborador <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || prcolaborador;
     END

       IF (wwhere <> '') THEN
          wwhere = ' where ' || wwhere;

  WSQL = 'SELECT COLCON.BDCODEMP, COLCON.BDCODCOL FROM VW_VRH_EMP_TCOLCON_CAD COLCON ' ||
         wwhere || ' order by COLCON.BDCODEMP, COLCON.BDCODCOL';

  FOR EXECUTE STATEMENT wsql INTO :WCODEMP, :WCODCOL DO
    BEGIN
      wwherecontrib2 = '';
      wwhere = '';

      wemp = '''COLCON.BDCODEMP = '||WCODEMP||'''';
      wcol = '''COLCON.BDCODCOL = '||WCODCOL||'''';

      if (PRHISTTRANSF = 1) then
         BEGIN
           WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = ' || WCODEMP || ' and BDCODCOLDEST = ' || WCODCOL;
           FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
             BEGIN
               IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
                 BEGIN
               WSQL3 = 'SELECT * FROM SP_VRH_RETORNA_CONTR_SIND(''COLCON.BDCODEMP = '||wcodemporig||''', ''COLCON.BDCODCOL = ' || wcodcolorig || ''',' || PRREF || ',' || PRMENSIND || ',' || PRCONTSIND || ',' || PRCONTCONF ||  ',' || PRTAXAASSIS || ',' || PRREVSAL || ',' || PRHISTTRANSF || ')';
               FOR EXECUTE STATEMENT wsql3 INTO
                 :BDCODEMP,
                 :BDCODCOL,
                 :BDNOMCOL,
                 :BDREF,
                 :MENSALIDADE,
                 :CONTSIND,
                 :CONTCONF,
                 :TAXAS,
                 :REVERSAO,
                 :BDCODSINTRAB,
                 :BDDESCSINTRAB,
                 :BDCODEMPORIG,
                 :BDCODCOLORIG DO
                     BEGIN
                   BDCODEMP = WCODEMP;
                   BDCODCOL = WCODCOL;
                   SUSPEND;
             END
         END
             END
         END

      IF (prcontsind = 1) THEN
         wwherecontrib2 = ' COLCON.BDCONTRSINDFRAIS <> 0.0 ';

      IF (prcontconf = 1) THEN
        BEGIN
          IF (wwherecontrib2 <> '') THEN
            wwherecontrib2 = wwherecontrib2 || ' or COLCON.BDCONTCONFFRAIS <> 0.0';
          ELSE
            wwherecontrib2 = 'COLCON.BDCONTCONFFRAIS <> 0.0';
        END
    
      IF (PRTAXAASSIS = 1) THEN
        BEGIN
          IF (wwherecontrib2 <> '') THEN
            wwherecontrib2 = wwherecontrib2 || ' or COLCON.BDCONTASSISTFRAIS <> 0.0';
          ELSE
            wwherecontrib2 = 'COLCON.BDCONTASSISTFRAIS <> 0.0';
        END
    
      IF (PRMENSIND = 1) THEN
        BEGIN
          IF (wwherecontrib2 <> '') THEN
            wwherecontrib2 = wwherecontrib2 || ' or COLCON.BDCONTAASS1FRAIS <> 0.0';
          ELSE
            wwherecontrib2 = 'COLCON.BDCONTAASS1FRAIS <> 0.0';
        END

      IF (TRIM(wwherecontrib2) <> '') THEN
        wwherecontrib2 =  ' ('||wwherecontrib2||')';

      wsqlaux = 'select distinct COLCON.BDCODEMP, '||
                'COLCON.BDCODCOL, '||
                'COLCON.BDREFFN,'||
                ' SPS.BDMENSALIDADE MENSALIDADE, ' ||
                ' SPS.BDCONTSIND CONTSIND ,'||
                ' SPS.BDCONTCONF CONTCONF , ' ||
                ' SPS.BDTAXAS TAXAS , '||
                ' SPS.BDREVERSAO REVERSAO, ' ||
                ' VINC_COL.BDCODSINTRAB, '||
                ' TSIND.BDDESCSINTRAB '||
                ' from VRHF_SP_TFOLHA_NORMAL('||wemp||', '||wcol||', null, null, 1) COLCON '||
                ' inner join SP_RETORNA_TIPOS_CONTR_SIND(COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFFN, '||prmensind||','||:prcontsind||','||:prcontconf||','||:prtaxaassis||','||:prrevsal||') SPS on 1=1 '||

--       ' from VRHF_EMP_TFOLHANORMAL X ' ||
                'left outer join SP_VRHF_TCOL_VINC_REF(COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFFN) VINC_COL '||
                '  on (VINC_COL.BDCODEMP = COLCON.BDCODEMP and VINC_COL.BDCODCOL = COLCON.BDCODCOL and VINC_COL.BDREFCOL <= COLCON.BDREFFN) '||
                'left outer join vrh_base_tsindtrab TSIND on (TSIND.BDCODSINTRAB = VINC_COL.BDCODSINTRAB) ';

      wwhere = 'where (COLCON.BDCODEMP = ' || WCODEMP || ') and ' ||
               '      (COLCON.BDCODCOL = ' || WCODCOL || ')';

      IF (prref IS NOT NULL AND prref <> 0) THEN
        wwhere = wwhere||' and COLCON.BDREFFN <= '||prref||' ';
      ELSE
        wwhere = ' where COLCON.BDREFFN <= '||prref||' ';

      wsqlaux = wsqlaux || wwhere;

      IF ((prcontsind + prcontconf) = 0) THEN
        BEGIN
          IF (wwherecontrib2 <> '') THEN
            wwherecontrib2 = ' where ' || wwherecontrib2 || ' and COLCON.BDCODEMP = 0 ' ;       --Sol. 16164 - Bruno L. R. - 22/11/2016
          ELSE
            wwherecontrib2 = ' where COLCON.BDCODEMP = 0';
        END
      ELSE
        IF (COALESCE(WCODEMP, 0) <> 0) THEN
          BEGIN
            IF (wwherecontrib2 <> '') THEN
              wwherecontrib2 = ' where COLCON.BDCODEMP = ' || WCODEMP || ' and ' || wwherecontrib2 || ' ';

            IF (COALESCE(WCODCOL, 0) <> 0) THEN
              wwherecontrib2 = wwherecontrib2 || 'and COLCON.BDCODCOL = ' || WCODCOL || ' ';

            IF (prref IS NOT NULL AND prref <> 0) THEN
              BEGIN
                IF (wwherecontrib2 <> '') THEN
                  wwherecontrib2 = wwherecontrib2 || ' and COLCON.BDREFFRAIS <= ' || prref || ' ';
                ELSE
                  wwherecontrib2 = wwherecontrib2 || ' where COLCON.BDREFFRAIS <= ' || prref || ' ';
              END
          END
      ELSE  --Sol. 17643 - Bruno L. R. - 24/07/2017
        IF (COALESCE(WCODEMP, 0) <> 0) THEN
           BEGIN
             wwherecontrib2 = ' where ' || wwherecontrib2 || ' ';
           END

      wsqlaux = wsqlaux || ' union all ' ||
                            'select ' ||
                            'distinct COLCON.BDCODEMP, ' ||
                            'COLCON.BDCODCOL, ' ||
                            'COLCON.BDREFFRAIS BDREFFN, ' ||
                            'coalesce(COLCON.BDCONTAASS1FRAIS, 0.0) MENSALIDADE, ' ||
                            'coalesce(COLCON.BDCONTRSINDFRAIS, 0.0) CONTSIND, ' ||
                            'coalesce(COLCON.BDCONTCONFFRAIS, 0.0) CONTCONF, ' ||
                            'coalesce(COLCON.BDCONTASSISTFRAIS, 0.0) TAXAS, ' ||
                            '0 REVERSAO, ' ||
                            'VINC_COL.BDCODSINTRAB, ' ||
                            'TSIND.BDDESCSINTRAB ' ||
                        'from ' ||
                            'VRHF_EMP_TFICHARAIS COLCON ' ||
                        'left outer join ' ||
                            'SP_VRHF_TCOL_VINC_REF(COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFFRAIS) VINC_COL on (' ||
                                        'VINC_COL.BDCODEMP = COLCON.BDCODEMP and ' ||
                                        'VINC_COL.BDCODCOL = COLCON.BDCODCOL and ' ||
                                        'VINC_COL.BDREFCOL <= COLCON.BDREFFRAIS) ' ||
                        'left outer join ' ||
                            'VRH_BASE_TSINDTRAB TSIND on (TSIND.BDCODSINTRAB = VINC_COL.BDCODSINTRAB) ' ||
                        wwherecontrib2;


      wsqlaux = 'select BDCODEMP, BDCODCOL, BDREFFN, MENSALIDADE, CONTSIND, CONTCONF, TAXAS, REVERSAO, BDCODSINTRAB, BDDESCSINTRAB from ('||
             wsqlaux ||
             ') order by 1, 2, 3';

      FOR EXECUTE STATEMENT wsqlaux
        INTO
          :BDCODEMP,
          :BDCODCOL,
          :bdref,
          :mensalidade,
          :contsind,
          :contconf,
          :taxas,
          :reversao,
          :BDCODSINTRAB,
          :BDDESCSINTRAB
        DO
          begin
            BDCODEMPORIG = BDCODEMP;
            BDCODCOLORIG = BDCODCOL;

            wwhere = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||bdcodemp||' and BDCODCOL = '||bdcodcol||' and BDREFCOL <= '||prref||' order by BDREFCOL DESC ';
            execute statement wwhere into :BDNOMCOL;
            SUSPEND;
          end
    END
END^

/* Restore proc. body: SP_VRH_TREEVIEW_CONS_ADSALARIO */
/*alt:13612 - 29/03/2016 - Alterado para que: Se o parâmetro de entrada PRMESESANTERIORES for igual a 0 (zero), retornar todos os cálculos de adiantamentos salariais da COMPETÊNCIA (AAAAMM), parâmetro de entrada PRDATA
Se for igual a 1 (um) retornar todos os cálculos de adiantamentos salariais do ANO, parâmetro de entrada PRDATA;
Senão, retornar todos os cálculos de adiantamentos salariais da base - Bruno L.R.*/

ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_ADSALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATA VARCHAR(6),
PRMESESANTERIORES SMALLINT,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDATAAD DATE,
BDREF INTEGER)
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  wsql = 'select ASAL.BDCODEMP, EMP.BDNOMEMP, '||
                'ASAL.BDCODCOL, COLCAD.BDNOMCOL, '||
                'ASAL.BDDATAAD, '||
                'ASAL.BDREFAD BDREF '||

         'from VRHF_EMP_TADSAL ASAL '||
         'JOIN vw_tempresas_ref_join EMP ON ASAL.BDCODEMP = EMP.BDCODEMP '||
         'LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON ASAL.BDCODEMP = COLCAD.BDCODEMP and ASAL.BDCODCOL = COLCAD.BDCODCOL ';

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       IF (wwhere = '') THEN
         wwhere = 'where ';
       ELSE
         wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODEMP;
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere = '') THEN
         wwhere = 'where ';
       ELSE
         wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODCOL;
     END

  IF (:prdata IS NOT NULL) THEN
     BEGIN
       /*IF ((:PRMESESANTERIORES IS NULL) OR (:PRMESESANTERIORES <= 0)) THEN
          wwhere = wwhere ||' and ASAL.BDREFAD = ' ||prdata||' ';
       ELSE
          wwhere = wwhere ||' and ASAL.BDREFAD <= ' ||prdata||' ';*/

       IF (:PRMESESANTERIORES = 0) THEN
         BEGIN
           IF (wwhere = '') THEN
             wwhere = 'where ';
           ELSE
             wwhere = wwhere||' and ';

           wwhere = wwhere ||'ASAL.BDREFAD = ' ||prdata||' ';
         END
       ELSE
         BEGIN
           IF (:PRMESESANTERIORES = 1) THEN
             BEGIN
               IF (wwhere = '') THEN
                 wwhere = 'where ';
               ELSE
                 wwhere = wwhere||' and ';

               wwhere = wwhere ||'substring(ASAL.BDREFAD from 1 for 4) = ' ||SUBSTRING(prdata FROM 1 FOR 4)||' ';
             END
         END
     END

  wsql = wsql||wwhere;

  EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, NULL);

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDDATAAD,
    :BDREF
  DO
  SUSPEND;
END
^

/* Restore proc. body: SP_VRH_TREEVIEW_CONS_CALCAUT */
/* alt:13612 - 15/04/2016 - Alterado para que se o parâmetro PRMESESANTERIORES for igual a 0 retornar todos os cálculos de 13º salário da COMPETÊNCIA (AAAAMM), PRREFERENCIA
Se o parâmetro PRMESESANTERIORES for igual a 1 retornar todos os cálculos de 13º salário do ANO, PRREFERENCIA
Senão retornar todos os cálculos de 13º salário da base - Bruno L. R. */
ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_CALCAUT(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRMESESANTERIORES SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFFN INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, NULL);

  wsql = 'select FOL.BDCODEMP, EMP.BDNOMEMP, '||
                'FOL.BDCODTER, COL.BDNOMETER BDNOMTER, '||
                'FOL.BDREFINSSSERV '||
         'from VRHF_BASE_CALC_TERC FOL '||
         'join TEMPRESAS_REF EMP on EMP.BDCODEMP = FOL.BDCODEMP and EMP.BDREFEMP = (select first 1 BDREFEMP from TEMPRESAS_REF where BDCODEMP = EMP.BDCODEMP and BDREFEMP <= '||:PRREFERENCIA||' order by BDREFEMP desc) '||
         'join TTERCEIRO_REF COL on COL.BDCODTER = FOL.BDCODTER and COL.BDREFEMP = (select first 1 BDREFEMP from TTERCEIRO_REF where BDCODTER = COL.BDCODTER and BDREFEMP <= '||:PRREFERENCIA||' order by BDREFEMP desc) ';

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
    BEGIN
      IF (wwhere = '') THEN
        wwhere = 'where '||:PRCODEMP;
      ELSE
        wwhere = wwhere||' and '||:PRCODEMP;
    END

  IF (:PRCODCOL IS NOT NULL) THEN
    BEGIN
      IF (wwhere = '') THEN
        wwhere = 'where '||:PRCODCOL;
      ELSE
        wwhere = wwhere||' and '||:PRCODCOL;
    END

  IF (:PRREFERENCIA IS NOT NULL AND :PRREFERENCIA <> 0)  THEN
     BEGIN
       /*IF ((:PRMESESANTERIORES IS NULL) OR (:PRMESESANTERIORES <= 0)) THEN
          wwhere = wwhere||' and FOL.BDREFINSSSERV = '||:PRREFERENCIA;
       ELSE
          wwhere = wwhere||'and FOL.BDREFINSSSERV <= '||:PRREFERENCIA;*/

       IF (:PRMESESANTERIORES = 0) THEN
         BEGIN
           IF (wwhere = '') THEN
             wwhere = 'where FOL.BDREFINSSSERV = '||:PRREFERENCIA;
           ELSE
             wwhere = wwhere||' and FOL.BDREFINSSSERV = '||:PRREFERENCIA;
         END
       ELSE
       IF (:PRMESESANTERIORES = 1) THEN
         BEGIN
           IF (wwhere = '') THEN
             wwhere = 'where substring(FOL.BDREFINSSSERV from 1 for 4) = '||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4);
           ELSE
             wwhere = wwhere||' and substring(FOL.BDREFINSSSERV from 1 for 4) = '||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4);
         END
     END

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDREFFN
  DO
  SUSPEND;
END
^

/* Restore proc. body: SP_VRH_TREEVIEW_CONS_CALCULO */
ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_CALCULO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRMESESANTERIORES SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFFN INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, NULL);

  wsql = 'select FOL.BDCODEMP, EMP.BDNOMEMP, '||
                'FOL.BDCODCOL, COLCAD.BDNOMCOL, '||
                'FOL.BDREFFN '||
         'from VW_UNION_FN_TOMADOR_REF FOL, '||
         'VW_TEMPRESAS_REF EMP, '||
         'VW_VRH_EMP_TCOLCON_CAD COLCAD ';


  wwhere = 'where EMP.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL ';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODEMP;

  IF (:PRCODCOL IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODCOL;

  IF (:PRREFERENCIA IS NOT NULL AND :PRREFERENCIA <> 0)  THEN
     BEGIN
       /*IF ((:PRMESESANTERIORES IS NULL) OR (:PRMESESANTERIORES <= 0)) THEN
          wwhere = wwhere||' and FOL.BDREFFN = '||:PRREFERENCIA;
       ELSE
          wwhere = wwhere||' and FOL.BDREFFN <= '||:PRREFERENCIA;*/

       IF (:PRMESESANTERIORES = 0) THEN
          wwhere = wwhere ||' and FOL.BDREFFN = ' ||:PRREFERENCIA||' ';
       ELSE
          IF (:PRMESESANTERIORES = 1) THEN
             wwhere = wwhere ||' and substring(FOL.BDREFFN from 1 for 4) = ' ||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4)||' ';
     END

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDREFFN
  DO
  SUSPEND;
END
^

/* Restore proc. body: SP_VRH_TREEVIEW_CONS_CALCINT */
create or alter procedure SP_VRH_TREEVIEW_CONS_CALCINT (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRPORCONTRATO smallint,
    PRREFERENCIA integer,
    PRMESESANTERIORES smallint)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDREFFN integer,
    BDCODCONTTI integer)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WPORCONTRATO varchar(100);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, NULL);

  wporcontrato = ', CAST(null as INTEGER) BDCODCONTTI ';

  if (COALESCE(prporcontrato, 0) = 1) then
     wporcontrato = ',FOL.BDCODCONTTI ';

  wsql = 'select distinct FOL.BDCODEMP, EMP.BDNOMEMP, '||
                'FOL.BDCODCOL, COLCAD.BDNOMCOL, '||
                'FOL.BDREFFN '||wporcontrato||
         'from ('||
                'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN '||wporcontrato||
                'from VRHF_EMP_TFOLHAINT FOL ';

  wwhere = '';
  if (COALESCE(prcodemp,'') <> '') then
     begin
       wwhere = wwhere||prcodemp;

       if (COALESCE(prcodcol, '') <> '') then
          wwhere = wwhere||' and '||prcodcol;
     end

  if (COALESCE(prreferencia, 0) <> 0) then
     begin
       IF (:PRMESESANTERIORES = 0) THEN
          begin
            if (wwhere <> '') then
               wwhere = wwhere||' and ';
            wwhere = wwhere ||'FOL.BDREFFN = ' ||:PRREFERENCIA||' ';
          end
       ELSE
       IF (:PRMESESANTERIORES = 1) THEN
          begin
            if (wwhere <> '') then
               wwhere = wwhere||' and ';
             wwhere = wwhere ||'substring(FOL.BDREFFN from 1 for 4) = ' ||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4)||' ';
          end
     end

  if (wwhere <> '') then
     wsql = wsql||' where '||wwhere;

                wsql = wsql||
                'union all select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR '||wporcontrato||
                'from VRHF_EMP_TFOLHATOMINT FOL ';

  wwhere = '';
  if (COALESCE(prcodemp,'') <> '') then
     begin
       wwhere = wwhere||prcodemp;

       if (COALESCE(prcodcol, '') <> '') then
          wwhere = wwhere||' and '||prcodcol;
     end

  if (COALESCE(prreferencia, 0) <> 0) then
     begin
       IF (:PRMESESANTERIORES = 0) THEN
          begin
            if (wwhere <> '') then
               wwhere = wwhere||' and ';
            wwhere = wwhere ||'FOL.BDREFTOMADOR = ' ||:PRREFERENCIA||' ';
          end
       ELSE
       IF (:PRMESESANTERIORES = 1) THEN
          begin
            if (wwhere <> '') then
               wwhere = wwhere||' and ';
            wwhere = wwhere ||'substring(FOL.BDREFTOMADOR from 1 for 4) = ' ||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4)||' ';
          end
     end

  if (wwhere <> '') then
     wsql = wsql||' where '||wwhere;

  wsql = wsql||
         ') FOL '||
         'left outer join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = FOL.BDCODEMP) '||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';


  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDREFFN,
    :BDCODCONTTI
  DO
  SUSPEND;
END^

/* Restore proc. body: VRHF_SP_CONS_CALC_FOLHAINT */
create or alter procedure VRHF_SP_CONS_CALC_FOLHAINT (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRANOMES integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCODCONTTI integer,
    BDCODVER integer,
    BDDESCVER varchar(70),
    BDDESCREDVER varchar(35),
    BDREFV numeric(15,6),
    BDREFAUXV numeric(15,6),
    BDPROVENTO numeric(15,6),
    BDDESCONTO numeric(15,6),
    BDTIPOCODVER integer,
    BDORDEMTIPOCODVER integer,
    BDINSSVER integer,
    BDFGTSVER integer,
    BDIRVER integer,
    BDTIPOREFVER integer,
    BDBASESFVER integer,
    BDPISVER varchar(5),
    BDBASEHEVER varchar(5),
    BDBASEMAIORVER varchar(5),
    BDRAISVER varchar(5),
    BDBASEGPSVER varchar(5),
    BDIGNREFV varchar(5),
    BDIGNVALV varchar(5),
    BDCLAVER varchar(20),
    BDORDEMVER integer,
    BDREF integer,
    BDREFHOREMP varchar(5),
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDBFGTSFE numeric(15,6),
    BDFGTSFE numeric(15,6))
as
declare variable WWHERE varchar(32700);
declare variable WSQL varchar(32700);
declare variable WSUM numeric(15,6);
declare variable WMAX numeric(15,6);
BEGIN
  /*
    Retorna os dados da tabela de verbas folha normal, junto com os dados do colaborador
    e empresa.
    Retorna tambem os parametros de cada verba lancada.
    Retorna os Valores e bases de INSS, FGTS, IRRF, Dependentes, Maior remuneracao,
    Salario familia, etc.
    Salario base
  */

  EXECUTE PROCEDURE sp_seta_competencia(pranomes,  NULL, NULL);

  wsql = 'select GRUPOVERBAS.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'GRUPOVERBAS.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'GRUPOVERBAS.BDCODCONTTI, '||
                'GRUPOVERBAS.BDCODVER, '||
                'VERB.BDDESCVER, '||
                'VERB.BDDESCREDVER, '||
                'GRUPOVERBAS.BDREFVFN, '||
                'GRUPOVERBAS.BDREFAUXVFN, '||
                'case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.BDVALVFN '||
                     'when (VERREF.BDTIPOCODVER = 2) then GRUPOVERBAS.BDVALVFN '||
                     'else 0.00 end BDPROVENTO, '||
                'case when (VERREF.BDTIPOCODVER = 1) then GRUPOVERBAS.BDVALVFN '||
                     'when (VERREF.BDTIPOCODVER = 3) then GRUPOVERBAS.BDVALVFN '||
                     'else 0.00 end BDDESCONTO, '||
                'VERREF.BDTIPOCODVER, '||
                'case when VERREF.BDTIPOCODVER = 1 then 2 when VERREF.BDTIPOCODVER = 2 then 1 else coalesce(VERREF.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, '||
                'VERREF.BDINSSVER, '||
                'VERREF.BDFGTSVER, '||
                'VERREF.BDIRVER, '||
                'VERREF.BDTIPOREFVER, '||
                'VERREF.BDBASESFVER, '||
                'VERREF.BDPISVER, '||
                'VERREF.BDBASEHEVER, '||
                'VERREF.BDBASEMAIORVER, '||
                'VERREF.BDRAISVER, '||
                'VERREF.BDBASEGPSVER, '||
                'GRUPOVERBAS.BDIGNREFVFN, '||
                'GRUPOVERBAS.BDIGNVALVFN, '||
                'VERB.BDCLAVER, '||
                'VERB.BDORDEMVER, '||
                'GRUPOVERBAS.BDREFFN, '||
                'EMPCALC.BDREFHOREMP, '||
                'Y.BDBFGTSFN, '||
                'Y.BDFGTSFN, '||
                'Y.BDFGTSCSFN, '||
                'Y.BDBFGTS13FN, '||
                'Y.BDFGTS13FN, '||
                'Y.BDFGTS13CSFN, '||
                'Y.BDMAIORREMFN, '||
                'Y.BDBINSSFN, '||
                'Y.BDALIQINSSFN, '||
                'Y.BDINSSFN, '||
                'Y.BDBIRRFFN, '||
                'Y.BDALIQIRRFFN, '||
                'Y.BDIRRFFN, '||
                'Y.BDBINSS13FN, '||
                'Y.BDALIQINSS13FN, '||
                'Y.BDINSS13FN, '||
                'Y.BDBIRRF13FN, '||
                'Y.BDALIQIRRF13FN, '||
                'Y.BDIRRF13FN, '||
                'Y.BDBSALFAMFN, '||
                'Y.BDSALFAMFN, '||
                'Y.BDBRAISFN, '||
                'Y.BDSALBASEFN, '||
                'Y.BDDEPFN, '||
                'Y.BDBFGTSFEFN, '||
                'Y.BDFGTSFEFN, '||
                'Y.BDCREDITOFN, '||
                'Y.BDDEBITOFN '||
         'from VRHF_EMP_TVERBAINT GRUPOVERBAS, '||
         'VW_TEMPRESAS_REF EMP, '||
         'VW_VRH_EMP_TCOLCON_CAD COL, '||
         'VRH_BASE_TVERBAS VERB, '||
         'VW_VERBAS_REF_ATUAL VERREF, '||
         'VW_VRHF_BASE_TEMPCALC EMPCALC, '||
         'VRHF_EMP_TFOLHAINT Y ';

  wwhere = 'where EMP.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODCOL = GRUPOVERBAS.BDCODCOL and '||
           'VERB.BDCODVER = GRUPOVERBAS.BDCODVER and VERREF.BDCODVER = GRUPOVERBAS.BDCODVER and EMPCALC.BDCODEMP = GRUPOVERBAS.BDCODEMP and '||
           'Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODCOL = GRUPOVERBAS.BDCODCOL and Y.BDREFFN = GRUPOVERBAS.BDREFFN and Y.BDCODCONTTI = GRUPOVERBAS.BDCODCONTTI ';

  IF (pranomes IS NOT NULL) THEN
     wwhere = wwhere||' and GRUPOVERBAS.BDREFFN = '||:PRANOMES||' ';

  wsql = wsql || wwhere;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = ' and ';
       wwhere = wwhere || ' GRUPOVERBAS.' || :PRCODEMP || ' ';
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere = '') THEN
          wwhere = ' and ';

       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || 'GRUPOVERBAS.'||:PRCODCOL || ' ';
     END

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCODCONTTI,
    :BDCODVER,
    :BDDESCVER,
    :BDDESCREDVER,
    :BDREFV,
    :BDREFAUXV,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDTIPOCODVER,
    :BDORDEMTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDCLAVER,
    :BDORDEMVER,
    :BDREF,
    :BDREFHOREMP,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :bdbfgtsfe,
    :BDFGTSFE,
    :bdcredito,
    :bddebito
  DO
  SUSPEND;

  wwhere = '';

  -- folha por tomador
/*00*/  wsql = 'select GRUPOVERBAS.BDCODEMP,'||
/*01*/                'EMP.BDNOMEMP,'||
/*02*/                'GRUPOVERBAS.BDCODCOL,'||
/*03*/                'COL.BDNOMCOL,'||
/*04*/                'GRUPOVERBAS.BDCODCONTTI,'||
/*04*/                'GRUPOVERBAS.BDCODVER,'||
/*05*/                'VERB.BDDESCVER,'||
/*06*/                'VERB.BDDESCREDVER,'||
/*07*/                'sum(GRUPOVERBAS.bdrefvft),'|| -- aki
/*08*/                'max(GRUPOVERBAS.bdrefvft),'|| -- aki
/*09*/                'sum(GRUPOVERBAS.bdrefauxvft),'||
/*10*/                'sum(case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.bdvalvft'||
                      '     when (VERREF.BDTIPOCODVER <> 0) then 0 end) BDPROVENTO,'||
/*11*/                'sum(case when (VERREF.BDTIPOCODVER > 0) then GRUPOVERBAS.bdvalvft'||
                      '     when (VERREF.BDTIPOCODVER <= 0) then 0 end) BDDESCONTO,'||
/*12*/                'max(VERREF.BDTIPOCODVER),'||
/*13*/                'max(VERREF.BDINSSVER),'||
/*14*/                'max(VERREF.BDFGTSVER),'||
/*15*/                'max(VERREF.BDIRVER),'||
/*16*/                'max(VERREF.BDTIPOREFVER),'||
/*17*/                'max(VERREF.BDBASESFVER),'||
/*18*/                'VERREF.BDPISVER,'||
/*19*/                'VERREF.BDBASEHEVER,'||
/*20*/                'VERREF.BDBASEMAIORVER,'||
/*21*/                'VERREF.BDRAISVER,'||
/*22*/                'VERREF.BDBASEGPSVER,'||
/*23*/                'GRUPOVERBAS.bdignrefvft,'||
/*24*/                'GRUPOVERBAS.bdignvalvft,'||
/*25*/                'VERB.BDCLAVER,'||
/*26*/                'max(VERB.BDORDEMVER),'||
/*27*/                'GRUPOVERBAS.bdreftomador,'||
/*28*/                'EMPCALC.BDREFHOREMP,'||
/*29*/                'sum(Y.bdbfgtsft),'||
/*30*/                'sum(Y.bdfgtsft),'||
/*31*/                'sum(Y.bdfgtscsft),'||
/*32*/                'sum(Y.bdbfgts13ft),'||
/*33*/                'sum(Y.bdfgts13ft),'||
/*34*/                'sum(Y.bdfgts13csft),'||
/*35*/                'sum(Y.bdmaiorremft),'||
/*36*/                'sum(Y.bdbinssft),'||
/*37*/                'sum(Y.bdaliqinssft),'||
/*38*/                'sum(Y.bdinssft),'||
/*39*/                'sum(Y.bdbirrfft),'||
/*40*/                'sum(Y.bdaliqirrfft),'||
/*41*/                'sum(Y.bdirrfft),'||
/*42*/                'sum(Y.bdbinss13ft),'||
/*43*/                'sum(Y.bdaliqinss13ft),'||
/*44*/                'sum(Y.bdinss13ft),'||
/*45*/                'sum(Y.bdbirrf13ft),'||
/*46*/                'sum(Y.bdaliqirrf13ft),'||
/*47*/                'sum(Y.bdirrf13ft),'||
/*48*/                'sum(Y.bdbsalfamft),'||
/*49*/                'sum(Y.bdsalfamft),'||
/*50*/                'sum(Y.bdbraisft),'||
/*51*/                'sum(Y.bdsalbaseft),'||
/*52*/                'sum(Y.bddepft), '||
/*53*/                'sum(Y.BDBFGTSFEFT), '||
/*54*/                'sum(Y.BDFGTSFEFT), '||
/*55*/                'sum(Y.BDCREDITOFT), '||
/*56*/                'sum(Y.BDDEBITOFT) '||
         ' from vrhf_emp_tverbatomint GRUPOVERBAS,'||
         ' VW_TEMPRESAS_REF EMP,'||
         ' VW_VRH_EMP_TCOLCON_CAD COL,'||
         ' VRH_BASE_TVERBAS VERB,'||
         ' VW_VERBAS_REF_ATUAL VERREF,'||
         ' VW_VRHF_BASE_TEMPCALC EMPCALC,'||
         ' vrhf_emp_tfolhatomint Y'||
' where EMP.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODCOL = GRUPOVERBAS.BDCODCOL and'||
' VERB.BDCODVER = GRUPOVERBAS.BDCODVER and VERREF.BDCODVER = GRUPOVERBAS.BDCODVER and EMPCALC.BDCODEMP = GRUPOVERBAS.BDCODEMP and'||
' Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODCOL = GRUPOVERBAS.BDCODCOL and Y.bdreftomador = GRUPOVERBAS.bdreftomador and Y.bdordem = GRUPOVERBAS.bdordem and Y.BDCODCONTTI = GRUPOVERBAS.BDCODCONTTI ';

  IF (pranomes IS NOT NULL) THEN
     wwhere = wwhere||' and GRUPOVERBAS.bdreftomador = '||:PRANOMES||' ';

  wsql = wsql || wwhere;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = ' and ';
       wwhere = wwhere || ' GRUPOVERBAS.' || :PRCODEMP || ' ';
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere = '') THEN
          wwhere = ' and ';

       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || 'GRUPOVERBAS.'||:PRCODCOL || ' ';
     END

  wsql = wsql||wwhere;

  wsql = wsql||' group by GRUPOVERBAS.BDCODEMP,'||
                'EMP.BDNOMEMP,'||
                'GRUPOVERBAS.BDCODCOL,'||
                'COL.BDNOMCOL,'||
                'GRUPOVERBAS.BDCODCONTTI,'||
                'GRUPOVERBAS.BDCODVER,'||
                'GRUPOVERBAS.bdreftomador,'||
                'VERB.BDDESCVER,'||
                'VERB.BDDESCREDVER,'||
                'GRUPOVERBAS.bdignrefvft,'||
                'GRUPOVERBAS.bdignvalvft,'||
                'VERREF.BDPISVER,'||
                'VERREF.BDBASEHEVER,'||
                'VERREF.BDBASEMAIORVER,'||
                'VERREF.BDRAISVER,'||
                'VERREF.BDBASEGPSVER,'||
                'VERB.BDCLAVER,'||
                'EMPCALC.BDREFHOREMP';

  FOR EXECUTE STATEMENT wsql
  INTO
/*00*/    :BDCODEMP,
/*01*/    :BDNOMEMP,
/*02*/    :BDCODCOL,
/*03*/    :BDNOMCOL,
          :BDCODCONTTI,
/*04*/    :BDCODVER,
/*05*/    :BDDESCVER,
/*06*/    :BDDESCREDVER,
/*07*/    :wsum,
/*08*/    :wmax,
/*09*/    :BDREFAUXV,
/*10*/    :BDPROVENTO,
/*11*/    :BDDESCONTO,
/*12*/    :BDTIPOCODVER,
/*13*/    :BDINSSVER,
/*14*/    :BDFGTSVER,
/*15*/    :BDIRVER,
/*16*/    :BDTIPOREFVER,
/*17*/    :BDBASESFVER,
/*18*/    :BDPISVER,
/*19*/    :BDBASEHEVER,
/*20*/    :BDBASEMAIORVER,
/*21*/    :BDRAISVER,
/*22*/    :BDBASEGPSVER,
/*23*/    :BDIGNREFV,
/*24*/    :BDIGNVALV,
/*25*/    :BDCLAVER,
/*26*/    :BDORDEMVER,
/*27*/    :BDREF,
/*28*/    :BDREFHOREMP,
/*29*/    :BDBFGTS,
/*30*/    :BDFGTS,
/*31*/    :BDFGTSCS,
/*32*/    :BDBFGTS13,
/*33*/    :BDFGTS13,
/*34*/    :BDFGTS13CS,
/*35*/    :BDMAIORREM,
/*36*/    :BDBINSS,
/*37*/    :BDALIQINSS,
/*38*/    :BDINSS,
/*39*/    :BDBIRRF,
/*40*/    :BDALIQIRRF,
/*41*/    :BDIRRF,
/*42*/    :BDBINSS13,
/*43*/    :BDALIQINSS13,
/*44*/    :BDINSS13,
/*45*/    :BDBIRRF13,
/*46*/    :BDALIQIRRF13,
/*47*/    :BDIRRF13,
/*48*/    :BDBSALFAM,
/*49*/    :BDSALFAM,
/*50*/    :BDBRAIS,
/*51*/    :BDSALBASE,
/*52*/    :BDDEP,
/*53*/    :bdbfgtsfe,
/*54*/    :BDFGTSFE,
/*55*/    :bdcredito,
/*56*/    :bddebito
  DO
    BEGIN
      IF (BDTIPOREFVER = 4) THEN
         BDREFV = wmax;
      ELSE
         BDREFV = wsum;
      SUSPEND;
    END

END^


--#alt:16965. Alterei o cast do código da empresa para 9 digitos. Ana - 24/01/2018
/* Restore proc. body: SP_VRH_TREEVIEW_CONS_CALCULOFC */
ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_CALCULOFC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRMESESANTERIORES SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFCOMP INTEGER,
BDDATAPAGFC DATE)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
BEGIN
  wsql = 'select FOLCOMP.BDCODEMP, EMP.BDNOMEMP, '||
                'FOLCOMP.BDCODCOL, COL.BDNOMCOL, '||
                'FOLCOMP.BDREFCOMP, FOLCOMP.BDDATAPAGFC '||
         'from VRHF_EMP_TFOLHACOMP FOLCOMP '||
         'left outer join TEMPRESAS_REF EMP '||
           'on (CAST(EMP.BDCODEMP AS VARCHAR(9)) || CAST(EMP.BDREFEMP as VARCHAR(6)) in '||
                    '(select CAST(X.BDCODEMP AS VARCHAR(9)) || CAST(Max(X.BDREFEMP) as VARCHAR(6)) '||
                     'from TEMPRESAS_REF X '||
                     'where X.BDCODEMP = FOLCOMP.BDCODEMP and X.BDCODEMP = EMP.BDCODEMP '||
                     'group by X.BDCODEMP '||
                    ') '||
              ') '||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD '||
            'on (COLCAD.BDCODEMP = FOLCOMP.BDCODEMP and COLCAD.BDCODCOL = FOLCOMP.BDCODCOL) ';

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = 'where '||:PRCODEMP;

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODCOL;
     END

  IF (:PRREFERENCIA IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'FOLCOMP.BDREFCOMP <= '||:PRREFERENCIA;
     END


  IF (:PRREFERENCIA IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       IF ((:PRMESESANTERIORES IS NULL) OR (:PRMESESANTERIORES <= 0)) THEN
          wwhere = wwhere||'FOLCOMP.BDREFCOMP = '||:PRREFERENCIA;
       ELSE
          wwhere = wwhere||'FOLCOMP.BDREFCOMP <= '||:PRREFERENCIA;
     END


  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDREFCOMP,
    :BDDATAPAGFC
  DO
  SUSPEND;
END
^

/* Restore proc. body: SP_VRH_TREEVIEW_CONS_CALCULOPR */
/* alt:13612 - 28/03/2016 - Alterado para que: Se o parâmetro de entrada PRMESESANTERIORES for igual a 0 (zero), retornar todos os cálculos de prévias de rescisão (normal/tomador) da COMPETÊNCIA (AAAAMM), parâmetro de entrada PRANOMES; 
Se for igual a 1 (um) retornar todos os cálculos de prévias de rescisão (normal/tomador) do ANO, parâmetro de entrada PRANOMES;
Senão, retornar todos os cálculos de prévias de rescisão (normal/tomador) da base. - Bruno L. R. */
CREATE OR ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_CALCULOPR (
    PRMESESANTERIORES SMALLINT,
    PRANOMES INTEGER,
    PRCODEMP VARCHAR(10000),
    PRCODCOL VARCHAR(32700))
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCOL INTEGER,
    BDNOMCOL DM_BDNOMCOL,
    BDREFFNPR INTEGER,
    BDDATARESCISAOPREV DATE)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
BEGIN
  wsql = 'select FOL.BDCODEMP, EMP.BDNOMEMP, '||
                'FOL.BDCODCOL, COLCAD.BDNOMCOL, '||
                'cast(substring(cast(RESC.BDDATARESCISAOPREV as varchar(10)) from 1 for 4) || substring(cast(RESC.BDDATARESCISAOPREV as varchar(10)) from 6 for 2) as integer) as BDREFFNPR, '||
                'RESC.BDDATARESCISAOPREV '||
         'from VWRH_UNION_FNPR_FTPR_MES_BASES FOL '||
         'left outer join VW_TEMPRESAS_REF EMP '||
           'on (EMP.BDCODEMP = FOL.BDCODEMP) '||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD '||
            'on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) '||
         'join VRH_EMP_TRESCISAO_PREVIA RESC '||
            'on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL)';

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = 'where '||:PRCODEMP;

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODCOL;
     END

  IF (:PRANOMES IS NOT NULL AND :PRANOMES <> 0) THEN
     BEGIN
       IF (:PRMESESANTERIORES = 0) THEN
          wwhere = wwhere ||' and cast(substring(cast(RESC.BDDATARESCISAOPREV as varchar(10)) from 1 for 4) ||
                   substring(cast(RESC.BDDATARESCISAOPREV as varchar(10)) from 6 for 2) as integer) = ' ||:PRANOMES||' ';
       ELSE
          IF (:PRMESESANTERIORES = 1) THEN
             wwhere = wwhere ||' and substring(cast(substring(cast(RESC.BDDATARESCISAOPREV as varchar(10)) from 1 for 4) ||
                   substring(cast(RESC.BDDATARESCISAOPREV as varchar(10)) from 6 for 2) as integer) from 1 for 4) = ' ||
                   SUBSTRING(:PRANOMES FROM 1 FOR 4)||' ';
     END

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDREFFNPR,
    :BDDATARESCISAOPREV
  DO
  SUSPEND;
END
^

--#alt:16965. Alterei o cast do código da empresa para 9 digitos. Ana - 24/01/2018
/* Restore proc. body: SP_VRH_TREEVIEW_CONS_COMP13SAL */
/* alt:13612 - 29/03/2016 - Alterado para que: Se o parâmetro de entrada PRMESESANTERIORES for igual a 0 (zero), retornar todos os cálculos de complementos de 13º salário da COMPETÊNCIA (AAAAMM), parâmetro de entrada PRREFERENCIA
Se for igual a 1 (um) retornar todos os cálculos de complementos de 13º salário do ANO, parâmetro de entrada PRREFERENCIA
Senão, retornar todos os cálculos de complementos de 13º salário da base - Bruno L. R.*/
/* alt:13612 - 18/04/2016 - Alterado SQL para que na hora de fazer o CAST do campo BDCODEMP faça "AS VARCHAR(6)", 
pois quando era passado um código de empresa com mais de 5 caracteres ocorria um erro de conversão de dados - Bruno L. R. */
ALTER PROCEDURE SP_VRH_TREEVIEW_CONS_COMP13SAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRMESESANTERIORES SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFC13 INTEGER)
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  wsql = 'select COMP13.BDCODEMP, EMP.BDNOMEMP, '||
                'COMP13.BDCODCOL, COLCAD.BDNOMCOL, '||
                'COMP13.BDREFC13 '||
         'from VRHF_EMP_TC13SAL COMP13 '||

         'left outer join TEMPRESAS_REF EMP '||
           'on (CAST(EMP.BDCODEMP AS VARCHAR(9)) || CAST(EMP.BDREFEMP as VARCHAR(6)) in '||
                    '(select CAST(X.BDCODEMP AS VARCHAR(9)) || CAST(Max(X.BDREFEMP) as VARCHAR(6)) '||
                     'from TEMPRESAS_REF X '||
                     'where X.BDCODEMP = COMP13.BDCODEMP and X.BDCODEMP = EMP.BDCODEMP '||
                     'group by X.BDCODEMP '||
                    ') '||
              ') '||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD '||
            'on (COLCAD.BDCODEMP = COMP13.BDCODEMP and COLCAD.BDCODCOL = COMP13.BDCODCOL) ';

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = 'where '||:PRCODEMP;

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODCOL;
     END

  IF (:PRREFERENCIA IS NOT NULL) THEN
     BEGIN
       /*IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       IF ((:PRMESESANTERIORES IS NULL) OR (:PRMESESANTERIORES <= 0)) THEN
          wwhere = wwhere||'COMP13.BDREFC13 = '||:PRREFERENCIA;
       ELSE
          wwhere = wwhere||'COMP13.BDREFC13 <= '||:PRREFERENCIA; */

       IF (:PRMESESANTERIORES = 0) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
            ELSE
               wwhere = 'where ';
            wwhere = wwhere||'COMP13.BDREFC13 = '||:PRREFERENCIA;
          END
       ELSE
          IF (:PRMESESANTERIORES = 1) THEN
             BEGIN
               IF (wwhere <> '') THEN
                  wwhere = wwhere||' and ';
               ELSE
                  wwhere = 'where ';
               wwhere = wwhere||'substring(COMP13.BDREFC13 from 1 for 4) = '||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4)||' ';
             END
     END


  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :bdnomemp,
    :bdcodcol,
    :bdnomcol,
    :bdrefc13
  DO
  SUSPEND;
END
^

/* Restore proc. body: SP_VRH_TREEVIEW_CONS_FOLAVUL */
CREATE OR ALTER procedure SP_VRH_TREEVIEW_CONS_FOLAVUL (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRDATA varchar(6),
    PRMESESANTERIORES smallint,
    PRREFERENCIA integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDDATAFA date,
    BDREF integer)
as
declare variable WWHERE varchar(32700);
declare variable WSQL varchar(32700);
BEGIN
  wsql = 'select FA.BDCODEMP, EMP.BDNOMEMP, '||
                'FA.BDCODCOL, COLCAD.BDNOMCOL, '||
                'FA.BDDATAFA, '||
                'FA.BDREF '||
         'from VRHF_EMP_TFOLHAAVULSA FA '||
         'INNER JOIN TEMPRESAS_REF EMP ON (EMP.BDCODEMP = FA.BDCODEMP and ' ||
         '                                 EMP.BDREFEMP = coalesce((select max(D2.BDREFEMP) '||
         '                                                          from VRHF_BASE_TEMPCALC D2 '||
         '                                                          where D2.BDCODEMP = FA.BDCODEMP and ' ||
         '                                                          cast(D2.BDREFEMP as varchar(6)) <= (select trim(rdb$get_context(''USER_SESSION'', ''W_ANOMES''))'||
         '                                                                                              from RDB$DATABASE)), ' ||
         '                                                         (select min(D1.BDREFEMP) from VRHF_BASE_TEMPCALC D1 where D1.BDCODEMP = FA.BDCODEMP))) '||
         'inner join VRH_EMP_TCOLCON_CAD COLCAD on (FA.BDCODEMP = COLCAD.BDCODEMP and '||
         '                                          FA.BDCODCOL = COLCAD.BDCODCOL and '||
         '                                          COLCAD.BDREFCOL = coalesce((select max(D2.BDREFCOL) '||
         '                                                                      from VRH_EMP_TCOLCON_CAD D2 '||
         '                                                                      where D2.BDCODEMP = COLCAD.BDCODEMP and '||
         '                                                                            D2.BDCODCOL = COLCAD.BDCODCOL and '||
         '                                                                            cast(D2.BDREFCOL as varchar(6)) <= (select trim(rdb$get_context(''USER_SESSION'', ''W_ANOMES'')) '||
         '                                                                                                                from RDB$DATABASE)),  '||
         '                                                                      (select min(D1.BDREFCOL) '||
         '                                                                       from VRH_EMP_TCOLCON_CAD D1 '||
         '                                                                       where D1.BDCODEMP = COLCAD.BDCODEMP and '||
         '                                                                             D1.BDCODCOL = COLCAD.BDCODCOL))) ';

  wwhere = '';
  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = 'where '||:PRCODEMP;

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       else
          wwhere = 'where ';

      wwhere = wwhere||:prcodcol;
     END

  IF (:prdata IS NOT NULL) THEN
     BEGIN
       /*IF ((:PRMESESANTERIORES IS NULL) OR (:PRMESESANTERIORES <= 0)) THEN
          wwhere = wwhere ||' and FA.BDREF = ' ||prdata||' ';
       ELSE
          wwhere = wwhere ||' and FA.BDREF <= ' ||prdata||' '; */


      IF (:PRMESESANTERIORES = 0) THEN
         begin
            if (wwhere <> '') then
               wwhere = wwhere||' and ';
            else
               wwhere = 'where ';

           wwhere = wwhere ||' FA.BDREF = ' ||prdata||' ';
         end
      ELSE
         begin
           IF (:PRMESESANTERIORES = 1) THEN
              begin
               if (wwhere <> '') then
                   wwhere = wwhere||' and ';
               else
                   wwhere = 'where ';

               wwhere = wwhere ||' substring(FA.BDREF from 1 for 4) = ' ||SUBSTRING(prdata FROM 1 FOR 4)||' ';
              end
         end
     END

  wsql = wsql||wwhere;

  EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, NULL);

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDDATAFA,
    :BDREF
  DO
  SUSPEND;
END^

/* Restore proc. body: SP_VRH_TVERBAS_REF */
ALTER PROCEDURE SP_VRH_TVERBAS_REF(PRANOMES INTEGER)
 RETURNS(BDCODVER INTEGER,
BDREFVER INTEGER,
BDTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDMENORESVER VARCHAR(5),
BDPROPVER VARCHAR(5),
BDBASEVTVER VARCHAR(5),
BDREEMBGPSVER VARCHAR(5),
BDHEVER NUMERIC(15,6),
BDGRAVAFICHAHNVER VARCHAR(5),
BDCCPRINCIPALVER VARCHAR(5),
BDFORMREFVER VARCHAR(5000),
BDFORMREFAUXVER VARCHAR(5000),
BDFORMVALVER VARCHAR(5000),
BDFORMINTVER VARCHAR(5000),
BDBASEDSRHEVER VARCHAR(5),
BDBASEDSRRVVER VARCHAR(5),
BDDEDFORMREFVER VARCHAR(5),
BDDEDFORMREFAUXVER VARCHAR(5),
BDDEDFORMVALVER VARCHAR(5),
BDRENDISENTOIRVER VARCHAR(5))
 AS
DECLARE VARIABLE WSQL VARCHAR(10000);
BEGIN
  wsql = 'select X.BDCODVER, '||
                'X.BDREFVER, '||
                'X.BDTIPOCODVER, '||
                'X.BDINSSVER, '||
                'X.BDFGTSVER, '||
                'X.BDIRVER, '||
                'X.BDTIPOREFVER, '||
                'X.BDBASESFVER, '||
                'X.BDPISVER, '||
                'X.BDBASEHEVER, '||
                'X.BDBASEMAIORVER, '||
                'X.BDRAISVER, '||
                'X.BDBASEGPSVER, '||
                'X.BDMENORESVER, '||
                'X.BDPROPVER, '||
                'X.BDBASEVTVER, '||
                'X.BDREEMBGPSVER, '||
                'X.BDHEVER, '||
                'X.BDGRAVAFICHAHNVER, '||
                'X.BDCCPRINCIPALVER, '||
                'X.BDFORMREFVER, '||
                'X.BDFORMVALVER, '||
                'X.BDFORMINTVER, '||
                'X.BDFORMREFAUXVER, '||
                'X.BDBASEDSRHEVER, '||
                'X.BDBASEDSRRVVER, '||
                'X.BDDEDFORMREFVER, '||
                'X.BDDEDFORMREFAUXVER, '||
                'X.BDDEDFORMVALVER, '||
                'X.BDRENDISENTOIRVER ';

  wsql = wsql||'from VRH_BASE_TVERBAS_REF X '||
               'where exists (select Y.BDCODVER, MAX(Y.BDREFVER) '||
                             'from VRH_BASE_TVERBAS_REF Y '||
                             'where Y.BDREFVER <= '||pranomes||
                             ' group by Y.BDCODVER'||
                             ' having Y.BDCODVER = X.BDCODVER and MAX(Y.BDREFVER) = X.BDREFVER'||
                             ') ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODVER,
    :BDREFVER,
    :BDTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDMENORESVER,
    :BDPROPVER,
    :BDBASEVTVER,
    :BDREEMBGPSVER,
    :BDHEVER,
    :BDGRAVAFICHAHNVER,
    :BDCCPRINCIPALVER,
    :BDFORMREFVER,
    :BDFORMVALVER,
    :BDFORMINTVER,
    :BDFORMREFAUXVER,
    :BDBASEDSRHEVER,
    :BDBASEDSRRVVER,
    :BDDEDFORMREFVER,
    :BDDEDFORMREFAUXVER,
    :BDDEDFORMVALVER,
    :BDRENDISENTOIRVER
  DO

  SUSPEND;
END
^

/* Restore proc. body: SP_VRH_VAL_RAIS_FF */
ALTER PROCEDURE SP_VRH_VAL_RAIS_FF(PREMP VARCHAR(32000),
PRCOL VARCHAR(32000),
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDAVPREV NUMERIC(15,6),
BDFERIND NUMERIC(15,6),
BDGRATIF NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDSINDICAL NUMERIC(15,6),
BDASSISTENCIAL NUMERIC(15,6),
BDCONFEDERATIVA NUMERIC(15,6),
BDBASEFN NUMERIC(15,6),
BDBASEA13 NUMERIC(15,6),
BDBASE13 NUMERIC(15,6),
BDBASEC13 NUMERIC(15,6),
BDORIGEM INTEGER,
BDMENSALIDADE NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQLCOL VARCHAR(32000);
DECLARE VARIABLE WSQLFF VARCHAR(32000);
DECLARE VARIABLE WCOL INTEGER;
DECLARE VARIABLE WEMP INTEGER;
BEGIN
  /* Procedure Text */
--  suspend;
--  wsqlcol = 'select bdcodemp,bdcodcol from sp_somente_ativos('||''''||'01/01/'||prano||''''||','||''''||'12/31/'||prano||''''||')';
  wsqlcol = 'select col.bdcodemp,col.bdcodcol from vrh_emp_tcolcon col '||
            ' join sp_somente_ativos('||''''||'01/01/'||prano||''''||','||''''||'12/31/'||prano||''''||') filtro on (filtro.bdcodemp = col.bdcodemp and filtro.bdcodcol = col.bdcodcol)';

  IF ((premp <> '') AND (premp IS NOT NULL)) THEN
     BEGIN
       wsqlcol = wsqlcol||' where '||premp;

       IF ((prcol <> '') AND (prcol IS NOT NULL)) THEN
          wsqlcol = wsqlcol||' and '||prcol;
     END

  FOR EXECUTE STATEMENT wsqlcol INTO wemp,wcol DO
    BEGIN
      FOR SELECT BDCODEMP, BDCODCOL, BDREF, BDAVPREV, BDFERIND, BDGRATIF, BDMULTA,
                 BDSINDICAL, BDASSISTENCIAL, BDCONFEDERATIVA, BDBASEFN, BDBASEA13,
                 BDBASE13, BDBASEC13, BDORIGEM, bdmensalidade FROM sp_val_rais_ff(:wemp,:wcol,:prano)
          INTO BDCODEMP, BDCODCOL, BDREF, BDAVPREV, BDFERIND, BDGRATIF, BDMULTA,
                 BDSINDICAL, BDASSISTENCIAL, BDCONFEDERATIVA, BDBASEFN, BDBASEA13,
                 BDBASE13, BDBASEC13, BDORIGEM, bdmensalidade DO
          SUSPEND;
    END

END
^

/* Restore proc. body: SP_VRH_VAL_RAIS_FF_REF */
ALTER PROCEDURE SP_VRH_VAL_RAIS_FF_REF(PREMP VARCHAR(32000),
PRCOL VARCHAR(32000),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDAVPREV NUMERIC(15,6),
BDFERIND NUMERIC(15,6),
BDGRATIF NUMERIC(15,6),
BDMULTA NUMERIC(15,6),
BDSINDICAL NUMERIC(15,6),
BDASSISTENCIAL NUMERIC(15,6),
BDCONFEDERATIVA NUMERIC(15,6),
BDBASEFN NUMERIC(15,6),
BDBASEA13 NUMERIC(15,6),
BDBASE13 NUMERIC(15,6),
BDBASEC13 NUMERIC(15,6),
BDORIGEM INTEGER,
BDMENSALIDADE NUMERIC(15,6))
 AS
DECLARE VARIABLE WANOINI INTEGER;
DECLARE VARIABLE WANOFIM INTEGER;
BEGIN
  /* Procedure Text */
  wAnoIni = CAST(SUBSTRING(CAST(prrefini AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wAnoFim = CAST(SUBSTRING(CAST(prreffim AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);

  IF ((premp IS NOT NULL) AND (premp <> '')) THEN
     BEGIN
       premp = UPPER(premp);
       IF (POSITION('TAB.BDCODEMP',premp) > 0) THEN
          BEGIN
            SELECT bdresult FROM strtran(:premp,'TAB.BDCODEMP','COL.BDCODEMP') INTO premp;
          END
     END

  WHILE (wAnoIni <= wAnoFim) DO
    BEGIN
      FOR SELECT BDCODEMP, BDCODCOL, BDREF, BDAVPREV, BDFERIND, BDGRATIF, BDMULTA,
                 BDSINDICAL, BDASSISTENCIAL, BDCONFEDERATIVA, BDBASEFN, BDBASEA13,
                 BDBASE13, BDBASEC13, BDORIGEM, bdmensalidade FROM SP_VRH_VAL_RAIS_FF(:premp,:prcol,:wanoini)
          INTO BDCODEMP, BDCODCOL, BDREF, BDAVPREV, BDFERIND, BDGRATIF, BDMULTA,
                 BDSINDICAL, BDASSISTENCIAL, BDCONFEDERATIVA, BDBASEFN, BDBASEA13,
                 BDBASE13, BDBASEC13, BDORIGEM, bdmensalidade DO

          IF ((bdref >= prrefini) AND (bdref <= prreffim)) THEN
             SUSPEND;

      wAnoIni = wanoini+ 1;
    END

END
^

/* Restore proc. body: SP_VRH_VERIFICAVERBASEMP_PADRAO */
create or alter procedure SP_VRH_VERIFICAVERBASEMP_PADRAO (
    PRCODEMP integer)
as
declare variable WCODVER integer;
declare variable WCLASSECOL integer;
declare variable WTIPOCOL integer;
declare variable WCLASSVER varchar(9);
declare variable WFGTS varchar(5);
declare variable WCODTCA integer;
declare variable WCODEMP integer;
declare variable WCODTCA2 integer;
declare variable WCLASSVER2 varchar(9);
declare variable WFGTS2 varchar(5);
declare variable WINTERMITENTE varchar(5);
declare variable WAULISTA varchar(5);
BEGIN
  FOR SELECT BDCODVER, COALESCE(BDCLASSECOLVEREMPPD,-1), COALESCE(BDTIPOCOLVEREMPPD, -1), BDCLASSIFVEREMPPD, BDCOMFGTSPD, BDCODTCA, COALESCE(BDCLASSIFVEREMPPD, ''), COALESCE(BDCOMFGTSPD,''), COALESCE(BDCODTCA,0), COALESCE(BDINTERMITENTEPD, 'FALSE'), COALESCE(BDAULISTAPD, 'FALSE')
    FROM VRH_BASE_TVERBASEMP_PADRAO
    INTO :wcodver, :wclassecol, :wtipocol, :wclassver, :wfgts, :wcodtca, :wclassver2, :wfgts2, :wcodtca2, :wintermitente, :waulista DO
    BEGIN
      wcodemp = NULL;

      SELECT BDCODEMP FROM VRHF_BASE_TVERBASEMP WHERE BDCODEMP = :prcodemp AND BDCODVER = :wcodver AND BDCLASSECOLVEREMP = :wclassecol AND BDTIPOCOLVEREMP = :wtipocol
        AND COALESCE(BDCOMFGTS,'') = :wfgts2 AND COALESCE(BDCLASSIFVEREMP,'') = :wclassver2 AND COALESCE(BDCODTCA,0) = :wcodtca2 AND COALESCE(BDINTERMITENTE, 'FALSE') = :wintermitente INTO :wcodemp;

      IF (wcodemp IS NULL) THEN
         BEGIN
           INSERT INTO VRHF_BASE_TVERBASEMP (BDCODEMP,BDCODVER,BDCLASSECOLVEREMP,BDTIPOCOLVEREMP,BDCOMFGTS,BDCLASSIFVEREMP,BDCODTCA,BDINTERMITENTE,BDAULISTA)
           VALUES (:prcodemp,:wcodver,:wclassecol,:wtipocol,:wfgts,:wclassver,:wcodtca,:wintermitente,:waulista);
         END
    END
--  suspend;
END^

--Sol. 11965 - Inserido retorno dos campos de valor, dos campos de base: BDBRATAPO13, BDBSALFAM13 e BDBSALMAT13 - Bruno L. R. - 01/02/2017
/* Restore proc. body: SP_VRHF_13SALARIO_ANO */
create or alter procedure SP_VRHF_13SALARIO_ANO (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRANO integer,
    PRREFFINAL integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF13 integer,
    BDVAL13 numeric(15,6),
    BDMESESPROP13 integer,
    BDBASEIR13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTSCS13 numeric(15,6),
    BDBASEFGTS13 numeric(15,6),
    BDDATABAIXA13 date,
    BDREFBAIXA13 integer,
    BDPERCIR13 numeric(15,6),
    BDVALORIR13 numeric(15,6),
    BDBRAIS13 numeric(15,6),
    BDDEP13 numeric(15,6),
    BDSALBASE13 numeric(15,6),
    BDARREPROV13 numeric(15,6),
    BDARREDESC13 numeric(15,6),
    BDBASEINSS13 numeric(15,6),
    BDPERCINSS13 numeric(15,6),
    BDVALORINSS13 numeric(15,6),
    BDANO13 integer,
    BDESTPROV13 numeric(15,6),
    BDBASEPIS13 numeric(15,6),
    BDBRATAPO13 numeric(15,6),
    BDBSALFAM13 numeric(18,6),
    BDBSALMAT13 numeric(15,6),
    BDPREVPRIV13 numeric(18,6),
    BDRATAPO13 numeric(15,6),
    BDSALFAM13 numeric(18,6),
    BDSALMATEMP13 numeric(15,6))
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WSQLAUX varchar(1000);
declare variable WCLAVER varchar(20);
declare variable WVALV13 numeric(18,6);
declare variable WINSSVER integer;
declare variable WBASEGPSVER DM_BOOLEAN;
BEGIN
  wsql = 'select BDCODEMP, '||
                'BDCODCOL, '||
                'BDREF13, '||
                'BDVAL13, '||
                'BDMESESPROP13, '||
                'BDBASEIR13, '||
                'BDFGTS13, '||
                'BDFGTSCS13, '||
                'BDBASEFGTS13, '||
                'BDDATABAIXA13, '||
                'BDREFBAIXA13, '||
                'BDPERCIR13, '||
                'BDVALORIR13, '||
                'BDBRAIS13, '||
                'BDDEP13, '||
                'BDSALBASE13, '||
                'BDARREPROV13, '||
                'BDARREDESC13, '||
--                'BDBASEINSS13, '||
                'BDPERCINSS13, '||
                'BDVALORINSS13, '||
                'BDANO13, '||
                'BDESTPROV13, '||
                'BDBASEPIS13, '||
                'BDBRATAPO13, '||
                'BDBSALFAM13, '||
                'BDBSALMATEMP13, '||
                'BDRATAPO13, '||    --Sol. 11965 - Bruno L. R.    
                'BDSALFAM13, '||    --Sol. 11965 - Bruno L. R.
                'BDSALMATEMP13 '||    --Sol. 11965 - Bruno L. R.
         'from VRHF_EMP_T13SAL ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (prano IS NOT NULL AND prano <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDANO13 = '||prano;
     END

  IF (prreffinal IS NOT NULL AND prreffinal <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDREF13 <= '||prreffinal;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :BDCODCOL,
    :BDREF13,
    :BDVAL13,
    :BDMESESPROP13,
    :BDBASEIR13,
    :BDFGTS13,
    :BDFGTSCS13,
    :BDBASEFGTS13,
    :BDDATABAIXA13,
    :BDREFBAIXA13,
    :BDPERCIR13,
    :BDVALORIR13,
    :BDBRAIS13,
    :BDDEP13,
    :BDSALBASE13,
    :BDARREPROV13,
    :BDARREDESC13,
--    :BDBASEINSS13,
    :BDPERCINSS13,
    :BDVALORINSS13,
    :BDANO13,
    :BDESTPROV13,
    :BDBASEPIS13,
    :BDBRATAPO13,
    :BDBSALFAM13,
    :bdbsalmat13,
    :BDRATAPO13,    --Sol. 11965 - Bruno L. R.
    :BDSALFAM13,    --Sol. 11965 - Bruno L. R.
    :BDSALMATEMP13  --Sol. 11965 - Bruno L. R.
  DO
    BEGIN
      BDPREVPRIV13 = 0;
      wsqlaux = 'select first 1 COALESCE(BDVALORPREVPRIV13COL,0) from VRHF_EMP_TCOLCON_CALC where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||
                ' and BDREFCOL <= '||BDREF13||' order by BDCODEMP,BDCODCOL,BDREFCOL DESC';
      EXECUTE STATEMENT wsqlaux INTO :BDPREVPRIV13;

      wvalv13      = 0;
      wclaver      = null;
      winssver     = 0;
      wbasegpsver  = 'FALSE';
      BDBASEINSS13 = 0;

      for select case when VERREF.BDTIPOCODVER = 1 then FN.BDVALV13 * -1 when coalesce(VERREF.BDTIPOCODVER, 0) = 0 then FN.BDVALV13 else 0 end BDVALV13,
                 VER.BDCLAVER, coalesce(VERREF.BDINSSVER, 0) BDINSSVER, coalesce(upper(VERREF.BDBASEGPSVER), 'FALSE') BDBASEGPSVER
          from VRHF_EMP_TVERBA13 FN
          join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER)
          join VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER and
                                               VERREF.BDREFVER = (select first 1 BDREFVER
                                                                  from VRH_BASE_TVERBAS_REF
                                                                  where BDCODVER = VERREF.BDCODVER and
                                                                        BDREFVER <= :BDREF13
                                                                  order by BDCODVER desc, BDREFVER desc
                                                                  ))
          where FN.BDCODEMP = :BDCODEMP and FN.BDCODCOL = :BDCODCOL and FN.BDREF13 = :BDREF13
      into
          :wvalv13, :wclaver, :winssver, :wbasegpsver
      do
          begin
            if ((winssver = 3) or (:wbasegpsver = 'TRUE' and SUBSTRING(:wclaver from 1 for 5) <> '5.010')) then
               BDBASEINSS13 = BDBASEINSS13 + wvalv13;
          end

      SUSPEND;
    END

END^

/* Restore proc. body: SP_VRHF_C13SALARIO_ANO */
CREATE OR ALTER PROCEDURE SP_VRHF_C13SALARIO_ANO (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(32700),
    PRANO INTEGER,
    PRREFFINAL INTEGER = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF13 INTEGER,
    BDVAL13 NUMERIC(15,6),
    BDMESESPROP13 INTEGER,
    BDBASEIR13 NUMERIC(15,6),
    BDFGTS13 NUMERIC(15,6),
    BDFGTSCS13 NUMERIC(15,6),
    BDBASEFGTS13 NUMERIC(15,6),
    BDDATABAIXA13 DATE,
    BDREFBAIXA13 INTEGER,
    BDPERCIR13 NUMERIC(15,6),
    BDVALORIR13 NUMERIC(15,6),
    BDBRAIS13 NUMERIC(15,6),
    BDDEP13 NUMERIC(15,6),
    BDSALBASE13 NUMERIC(15,6),
    BDARREPROV13 NUMERIC(15,6),
    BDARREDESC13 NUMERIC(15,6),
    BDBASEINSS13 NUMERIC(15,6),
    BDPERCINSS13 NUMERIC(15,6),
    BDVALORINSS13 NUMERIC(15,6),
    BDANO13 INTEGER,
    BDESTPROV13 NUMERIC(15,6),
    BDBASEPIS13 NUMERIC(15,6),
    BDBRATAPO13 NUMERIC(15,6),
    BDBSALFAM13 NUMERIC(18,6),
    BDBSALMAT13 NUMERIC(18,6),
    BDSALMATEMP13 NUMERIC(18,6),
    BDPREVPRIV13 NUMERIC(18,6),
    BDRATAPO13 NUMERIC(18,6),
    BDSALFAM13 NUMERIC(18,6))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQLAUX VARCHAR(1000);
BEGIN
  wsql = 'select C13.BDCODEMP, '||
                'C13.BDCODCOL, '||
                'C13.BDREFC13, '||
                'C13.BDVALC13 - S13.BDVAL13, '||
                'C13.BDMESESPROPC13, '||
                'C13.BDBASEIRC13 - S13.BDBASEIR13, '||
                'C13.BDFGTSC13, '||
                'C13.BDFGTSCSC13, '||
                'C13.BDBASEFGTSC13, '||
                'C13.BDDATABAIXAC13, '||
                'C13.BDREFBAIXAC13, '||
                'C13.BDPERCIRC13, '||
                'C13.BDVALORIRC13, '||
                'C13.BDBRAISC13, '||
                'C13.BDDEPC13, '||
                'C13.BDSALBASEC13, '||
                'C13.BDARREPROVC13, '||
                'C13.BDARREDESCC13, '||
                'C13.BDBASEINSSC13, '||
                'C13.BDPERCINSSC13, '||
                'C13.BDVALORINSSC13, '||
                'C13.BDANO13, '||
                'C13.BDESTPROVC13, '||
                'C13.BDBASEPISC13, '||
                'C13.BDBRATAPOC13, '||
                'C13.BDBSALFAMC13, '||
                'C13.BDBSALMATEMPC13, '||
                'C13.BDSALMATEMPC13, '||
                'C13.BDRATAPOC13, '||
                'C13.BDSALFAMC13 '||
         'from ( ';
  wsql = wsql||'select BDCODEMP, '||
                'BDCODCOL, '||
                'BDREF13, '||
                'BDREFC13, '||
                'BDVALC13, '||
                '0 BDMESESPROPC13, '||
                'BDBASEIRC13, '||
                'BDFGTSC13, '||
                'BDFGTSCSC13, '||
                'BDBASEFGTSC13, '||
                'BDDATABAIXAC13, '||
                'BDREFBAIXAC13, '||
                'BDPERCIRC13, '||
                'BDVALORIRC13, '||
                'BDBRAISC13, '||
                'BDDEPC13, '||
                'BDSALBASEC13, '||
                'BDARREPROVC13, '||
                'BDARREDESCC13, '||
                'BDBASEINSSC13, '||
                'BDPERCINSSC13, '||
                'BDVALORINSSC13, '||
                'substring(cast(BDREF13 as varchar(6)) from 1 for 4) BDANO13, '||
                'BDESTPROVC13, '||
                'BDBASEPISC13, '||
                'BDBRATAPOC13, '||
                'BDBSALFAMC13, '||
                'BDBSALMATEMPC13, '||
                'BDSALMATEMPC13, '||
                'BDRATAPOC13, '||
                'BDSALFAMC13 '||
         'from VRHF_EMP_TC13SAL ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (prano IS NOT NULL AND prano <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'substring(cast(BDREFC13 as varchar(6)) from 1 for 4) = '||prano;
     END

  IF (prreffinal IS NOT NULL AND prreffinal <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDREFC13 <= '||prreffinal;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;
  wsql = wsql||') C13 '||
         'join VRHF_EMP_T13SAL S13 on (S13.BDCODEMP = C13.BDCODEMP and S13.BDCODCOL = C13.BDCODCOL and S13.BDREF13 = C13.BDREF13) ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :BDCODCOL,
    :BDREF13,
    :BDVAL13,
    :BDMESESPROP13,
    :BDBASEIR13,
    :BDFGTS13,
    :BDFGTSCS13,
    :BDBASEFGTS13,
    :BDDATABAIXA13,
    :BDREFBAIXA13,
    :BDPERCIR13,
    :BDVALORIR13,
    :BDBRAIS13,
    :BDDEP13,
    :BDSALBASE13,
    :BDARREPROV13,
    :BDARREDESC13,
    :BDBASEINSS13,
    :BDPERCINSS13,
    :BDVALORINSS13,
    :BDANO13,
    :BDESTPROV13,
    :BDBASEPIS13,
    :BDBRATAPO13,
    :BDBSALFAM13,
    :BDBSALMAT13,
    :BDSALMATEMP13,
    :BDRATAPO13,
    :BDSALFAM13
  DO
    BEGIN
      BDPREVPRIV13 = 0;
      wsqlaux = 'select first 1 COALESCE(BDVALORPREVPRIV13COL,0) from VRHF_EMP_TCOLCON_CALC where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||
                ' and BDREFCOL <= '||BDREF13||' order by BDCODEMP,BDCODCOL,BDREFCOL DESC';
      EXECUTE STATEMENT wsqlaux INTO :BDPREVPRIV13;

      SUSPEND;
    END
END
^

/* Restore proc. body: SP_VRHF_13SALARIO_ANO_RESC */
--Sol. 17607 - Bruno L. R. - 29/06/2017 - Alterada a procedure para retornar o 13º salário pago no ano, da empresa de origem, se o colaborador teve transferência
create or alter procedure SP_VRHF_13SALARIO_ANO_RESC (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRMES integer,
    PRANO integer,
    PRPREVIA smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF13 integer,
    BDVAL13 numeric(15,6),
    BDMESESPROP13 integer,
    BDBASEIR13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTSCS13 numeric(15,6),
    BDBASEFGTS13 numeric(15,6),
    BDDATABAIXA13 date,
    BDREFBAIXA13 integer,
    BDPERCIR13 numeric(15,6),
    BDVALORIR13 numeric(15,6),
    BDBRAIS13 numeric(15,6),
    BDDEP13 numeric(15,6),
    BDSALBASE13 numeric(15,6),
    BDARREPROV13 numeric(15,6),
    BDARREDESC13 numeric(15,6),
    BDBASEINSS13 numeric(15,6),
    BDPERCINSS13 numeric(15,6),
    BDVALORINSS13 numeric(15,6),
    BDANO13 integer,
    BDESTPROV13 numeric(15,6),
    BDSALMATEMP13 numeric(15,6))
as
declare variable WANOANT integer;
declare variable WSQL varchar(32700);
declare variable WSQLTRANS varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WCLAVER varchar(20);
declare variable WINSSVER integer;
declare variable WBASEGPSVER DM_BOOLEAN;
declare variable WVALV13 numeric(18,6);
BEGIN
  --Sol. 17607 - Bruno L. R. - 12/07/2017 - Início
  wsqltrans = 'select X.BDCODEMP, '||
                'X.BDCODCOL, '||
                'Z.BDREF13, '||
                'Z.BDVAL13, '||
                'Z.BDMESESPROP13, '||
                'Z.BDBASEIR13, '||
                'Z.BDFGTS13, '||
                'Z.BDFGTSCS13, '||
                'Z.BDBASEFGTS13, '||
                'Z.BDDATABAIXA13, '||
                'Z.BDREFBAIXA13, '||
                'Z.BDPERCIR13, '||
                'Z.BDVALORIR13, '||
                'Z.BDBRAIS13, '||
                'Z.BDDEP13, '||
                'Z.BDSALBASE13, '||
                'Z.BDARREPROV13, '||
                'Z.BDARREDESC13, '||
--                'Z.BDBASEINSS13, '||
                'Z.BDPERCINSS13, '||
                'Z.BDVALORINSS13, '||
                'Z.BDANO13, '||
                'Z.BDESTPROV13, '||
                'Z.BDSALMATEMP13 '||
         'from VRHF_EMP_T13SAL Z '||
         'join (select trans.bdcodemporig, trans.bdcodcolorig, trans.bdcodempdest bdcodemp, trans.bdcodcoldest bdcodcol '||
         'from vrh_emp_ttranscol trans ) x on (z.bdcodemp = x.BDCODEMPORIG and z.bdcodcol = x.BDCODCOLORIG) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wwhere = wwhere||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wwhere = wwhere||' and '||prcodcol;
     END

  IF (prano IS NOT NULL AND prano <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'Z.BDANO13 = '||prano;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsqltrans = wsqltrans||wwhere;

  --Sol. 17607 - Bruno L. R. - 12/07/2017 - Fim

  wwhere = '';

  wsql = 'select X.BDCODEMP, '||
                'X.BDCODCOL, '||
                'X.BDREF13, '||
                'X.BDVAL13, '||
                'X.BDMESESPROP13, '||
                'X.BDBASEIR13, '||
                'X.BDFGTS13, '||
                'X.BDFGTSCS13, '||
                'X.BDBASEFGTS13, '||
                'X.BDDATABAIXA13, '||
                'X.BDREFBAIXA13, '||
                'X.BDPERCIR13, '||
                'X.BDVALORIR13, '||
                'X.BDBRAIS13, '||
                'X.BDDEP13, '||
                'X.BDSALBASE13, '||
                'X.BDARREPROV13, '||
                'X.BDARREDESC13, '||
--                'X.BDBASEINSS13, '||
                'X.BDPERCINSS13, '||
                'X.BDVALORINSS13, '||
                'X.BDANO13, '||
                'X.BDESTPROV13, '||
                'X.BDSALMATEMP13 '||
         'from VRHF_EMP_T13SAL X ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (prano IS NOT NULL AND prano <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       IF (prmes IS NOT NULL AND prmes <> 0) THEN
          BEGIN
            IF (prmes = 1) THEN
               BEGIN
                 wanoant = prano - 1;
                 IF (prprevia = 1) THEN
                    wwhere = wwhere||--'(X.BDANO13 = '||wanoant||' or '||  179400   Valmor  18/05/2022 Após conversado com Almir e Hekeili não faz sentido essa condição
                                      '((X.BDANO13 = '||prano||
                                      ' and exists('||
                                                   'select Y.BDCODEMP, Y.BDCODCOL '||
                                                   'from VRH_EMP_TRESCISAO_PREVIA Y '||
                                                   'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and EXTRACT(MONTH from Y.BDDATARESCISAOPREV) = '||prmes||
                                                      ' and EXTRACT(YEAR from Y.BDDATARESCISAOPREV) = '||prano||')) '||
                                     ') ';
                 ELSE
                    wwhere = wwhere||--'(X.BDANO13 = '||wanoant||' or '||  179400   Valmor  18/05/2022 Após conversado com Almir e Hekeili não faz sentido essa condição
                                      '((X.BDANO13 = '||prano||
                                      ' and exists('||
                                                   'select Y.BDCODEMP, Y.BDCODCOL '||
                                                   'from VRH_EMP_TRESCISAO Y '||
                                                   'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and ((EXTRACT(MONTH from Y.BDDATARESCISAO) = '||prmes||
                                                   ' and EXTRACT(YEAR from Y.BDDATARESCISAO) = '||prano||') or (EXTRACT(MONTH from Y.BDPROJECAOAVISO) = '||prmes||
                                                   ' and EXTRACT(YEAR from Y.BDPROJECAOAVISO) = '||prano||'))))) ';
               END
            ELSE
               BEGIN
                 IF (prprevia = 1) THEN
                    wwhere = wwhere||'(X.BDANO13 = '||prano||
                             ' and exists('||
                                          'select Y.BDCODEMP, Y.BDCODCOL '||
                                          'from VRH_EMP_TRESCISAO_PREVIA Y '||
                                          'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and EXTRACT(MONTH from Y.BDDATARESCISAOPREV) = '||prmes||
                                          ' and EXTRACT(YEAR from Y.BDDATARESCISAOPREV) = '||prano||')) ';
                 ELSE
                    wwhere = wwhere||'(X.BDANO13 = '||prano||
                             ' and exists('||
                                          'select Y.BDCODEMP, Y.BDCODCOL '||
                                          'from VRH_EMP_TRESCISAO Y '||
                                          'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and ((EXTRACT(MONTH from Y.BDDATARESCISAO) = '||prmes||
                                          ' and EXTRACT(YEAR from Y.BDDATARESCISAO) = '||prano||') or (EXTRACT(MONTH from Y.BDPROJECAOAVISO) = '||prmes||
                                          ' and EXTRACT(YEAR from Y.BDPROJECAOAVISO) = '||prano||')))) ';
               END
          END
       ELSE
          BEGIN
            IF (prprevia = 1) THEN
               wwhere = wwhere||'(X.BDANO13 = '||prano||' and exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO_PREVIA Y where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and EXTRACT(YEAR from Y.BDDATARESCISAOPREV) = '||prano||')) ';
            ELSE
               wwhere = wwhere||'(X.BDANO13 = '||prano||' and exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and EXTRACT(YEAR from Y.BDDATARESCISAO) = '||prano||')) ';
          END
     END
  ELSE
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       IF (prprevia = 1) THEN
          wwhere = wwhere||'(exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO_PREVIA Y where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL)) ';
       ELSE
          wwhere = wwhere||'(exists(select Y.BDCODEMP, Y.BDCODCOL from VRH_EMP_TRESCISAO Y where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL)) ';
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  --Sol. 17607 - Bruno L. R. - 12/07/2017 - Início
  wsql = wsql||wwhere;
  wsql = wsql||' union all ';
  wsql = wsql||WSQLTRANS;
  --Sol. 17607 - Bruno L. R. - 12/07/2017 - Fim

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :BDCODCOL,
    :BDREF13,
    :BDVAL13,
    :BDMESESPROP13,
    :BDBASEIR13,
    :BDFGTS13,
    :BDFGTSCS13,
    :BDBASEFGTS13,
    :BDDATABAIXA13,
    :BDREFBAIXA13,
    :BDPERCIR13,
    :BDVALORIR13,
    :BDBRAIS13,
    :BDDEP13,
    :BDSALBASE13,
    :BDARREPROV13,
    :BDARREDESC13,
--    :BDBASEINSS13,
    :BDPERCINSS13,
    :BDVALORINSS13,
    :BDANO13,
    :BDESTPROV13,
    :BDSALMATEMP13
  DO
    begin
      wvalv13      = 0;
      wclaver      = null;
      winssver     = 0;
      wbasegpsver  = 'FALSE';
      BDBASEINSS13 = 0;

      for select case when VERREF.BDTIPOCODVER = 1 then FN.BDVALV13 * -1 when coalesce(VERREF.BDTIPOCODVER, 0) = 0 then FN.BDVALV13 else 0 end BDVALV13,
                 VER.BDCLAVER, coalesce(VERREF.BDINSSVER, 0) BDINSSVER, coalesce(upper(VERREF.BDBASEGPSVER), 'FALSE') BDBASEGPSVER
          from VRHF_EMP_TVERBA13 FN
          join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER)
          join VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER and
                                               VERREF.BDREFVER = (select first 1 BDREFVER
                                                                  from VRH_BASE_TVERBAS_REF
                                                                  where BDCODVER = VERREF.BDCODVER and
                                                                        BDREFVER <= :BDREF13
                                                                  order by BDCODVER desc, BDREFVER desc
                                                                  ))
          where FN.BDCODEMP = :BDCODEMP and FN.BDCODCOL = :BDCODCOL and FN.BDREF13 = :BDREF13
      into
          :wvalv13, :wclaver, :winssver, :wbasegpsver
      do
          begin
            if ((winssver = 3) or (:wbasegpsver = 'TRUE' and SUBSTRING(:wclaver from 1 for 5) <> '5.010')) then
               BDBASEINSS13 = BDBASEINSS13 + wvalv13;
          end

  SUSPEND;
    end
END^

CREATE OR ALTER PROCEDURE SP_VRHF_13SALARIO_ANO_SIT (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(32700),
    PRANO INTEGER) 
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF13 INTEGER,
    BDANO13 INTEGER,
    BDBSALMAT13 NUMERIC(18,6),
    BDBACITRAB13 NUMERIC(18,6),
    BDBAUXDOE13 NUMERIC(18,6)) 
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WREF13 INTEGER;
DECLARE VARIABLE WVALVER NUMERIC(18,6);
DECLARE VARIABLE WCLAVER VARCHAR(20);
DECLARE VARIABLE WTIPOCODVER INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCOLATU INTEGER;
DECLARE VARIABLE WBSALMAT NUMERIC(18,6);
DECLARE VARIABLE WBACITRA NUMERIC(18,6);
DECLARE VARIABLE WBAUXDOE NUMERIC(18,6);
BEGIN
  wsql = 'select S13.BDCODEMP, '||
                'S13.BDCODCOL, '||
                'S13.BDREF13, '||
                'S13.BDVALV13, '||
                'VER.BDCLAVER, '||
                'VER.BDTIPOCODVER '||
         'from VRHF_EMP_TVERBA13 S13 '||
         'join VW_TVERBAS_REF VER on (VER.BDCODVER = S13.BDCODVER) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (prano IS NOT NULL AND prano <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'SUBSTRING(S13.BDREF13 FROM 1 FOR 4) = '||prano;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  wempatu = 0;
  wcolatu = 0;
  wbsalmat = 0;
  wbacitra = 0;
  wbauxdoe = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    :wcodemp,
    :wcodcol,
    :wref13,
    :wvalver,
    :wclaver,
    :wtipocodver
  DO
    BEGIN
      IF (wempatu = 0) THEN
         wempatu = wcodemp;

      IF (wcolatu = 0) THEN
         wcolatu = wcodcol;

      IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol))  THEN
         BEGIN
           BDCODEMP = wempatu;
           BDCODCOL = wcolatu;
           BDREF13 = wref13;
           BDANO13 = CAST((SUBSTRING(:wref13 FROM 1 FOR 4)) AS INTEGER);
           BDBSALMAT13 = wbsalmat;
           BDBACITRAB13 = wbacitra;
           BDBAUXDOE13 = wbauxdoe;

           SUSPEND;

           wempatu = wcodemp;
           wcolatu = wcodcol;
           wbsalmat = 0;
           wbacitra = 0;
           wbauxdoe = 0;
         END

      -- Salário maternidade no 13º
      IF (SUBSTRING(:wclaver FROM 1 FOR 5) = '5.010') THEN
         BEGIN
           IF (wtipocodver = 0) THEN
              wbsalmat = wbsalmat + wvalver;
           ELSE
           IF (wtipocodver = 1) THEN
              wbsalmat = wbsalmat - wvalver;
         END

      -- Acidente de trabalho no 13º
      IF (SUBSTRING(:wclaver FROM 1 FOR 5) = '5.012') THEN
         BEGIN
           IF (wtipocodver = 0) THEN
              wbacitra = wbacitra + wvalver;
           ELSE
           IF (wtipocodver = 1) THEN
              wbacitra = wbacitra - wvalver;
         END

      -- Auxílio doença
      IF (SUBSTRING(:wclaver FROM 1 FOR 5) = '5.014') THEN
         BEGIN
           IF (wtipocodver = 0) THEN
              wbauxdoe = wbauxdoe + wvalver;
           ELSE
           IF (wtipocodver = 1) THEN
              wbauxdoe = wbauxdoe - wvalver;
         END
    END

  IF ((wempatu <> 0) AND (wcolatu <> 0))  THEN
     BEGIN
       BDCODEMP = wempatu;
       BDCODCOL = wcolatu;
       BDREF13 = wref13;
       BDANO13 = CAST((SUBSTRING(:wref13 FROM 1 FOR 4)) AS INTEGER);
       BDBSALMAT13 = wbsalmat;
       BDBACITRAB13 = wbacitra;
       BDBAUXDOE13 = wbauxdoe;

       SUSPEND;

     END
END
^

CREATE OR ALTER PROCEDURE SP_VRHF_A13SALARIO_ANO_SIT (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(32700),
    PRANO INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREFA13 INTEGER,
    BDBSALMATA13 NUMERIC(18,6),
    BDBACITRABA13 NUMERIC(18,6),
    BDBAUXDOEA13 NUMERIC(18,6))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WREFA13 INTEGER;
DECLARE VARIABLE WVALVER NUMERIC(18,6);
DECLARE VARIABLE WCLAVER VARCHAR(20);
DECLARE VARIABLE WTIPOCODVER INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCOLATU INTEGER;
DECLARE VARIABLE WBSALMAT NUMERIC(18,6);
DECLARE VARIABLE WBACITRA NUMERIC(18,6);
DECLARE VARIABLE WBAUXDOE NUMERIC(18,6);
BEGIN
  wsql = 'select S13.BDCODEMP, '||
                'S13.BDCODCOL, '||
                'S13.BDREFA13, '||
                'S13.BDVALVA13, '||
                'VER.BDCLAVER, '||
                'VER.BDTIPOCODVER '||
         'from VRHF_EMP_TVERBAA13 S13 '||
         'join VW_TVERBAS_REF VER on (VER.BDCODVER = S13.BDCODVER) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (prano IS NOT NULL AND prano <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'SUBSTRING(S13.BDREFA13 FROM 1 FOR 4) = '||prano;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  wempatu = 0;
  wcolatu = 0;
  wbsalmat = 0;
  wbacitra = 0;
  wbauxdoe = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    :wcodemp,
    :wcodcol,
    :wrefa13,
    :wvalver,
    :wclaver,
    :wtipocodver
  DO
    BEGIN
      IF (wempatu = 0) THEN
         wempatu = wcodemp;

      IF (wcolatu = 0) THEN
         wcolatu = wcodcol;

      IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol))  THEN
         BEGIN
           BDCODEMP = wempatu;
           BDCODCOL = wcolatu;
           BDREFA13 = wrefa13;
           BDBSALMATA13 = wbsalmat;
           BDBACITRABA13 = wbacitra;
           BDBAUXDOEA13 = wbauxdoe;

           SUSPEND;

           wempatu = wcodemp;
           wcolatu = wcodcol;
           wbsalmat = 0;
           wbacitra = 0;
           wbauxdoe = 0;
         END

      -- Salário maternidade no 13º
      IF (SUBSTRING(:wclaver FROM 1 FOR 5) = '4.010') THEN
         BEGIN
           IF (wtipocodver = 0) THEN
              wbsalmat = wbsalmat + wvalver;
           ELSE
           IF (wtipocodver = 1) THEN
              wbsalmat = wbsalmat - wvalver;
         END

      -- Acidente de trabalho no 13º
      IF (SUBSTRING(:wclaver FROM 1 FOR 5) = '4.012') THEN
         BEGIN
           IF (wtipocodver = 0) THEN
              wbacitra = wbacitra + wvalver;
           ELSE
           IF (wtipocodver = 1) THEN
              wbacitra = wbacitra - wvalver;
         END

      -- Auxílio doença
      IF (SUBSTRING(:wclaver FROM 1 FOR 5) = '4.014') THEN
         BEGIN
           IF (wtipocodver = 0) THEN
              wbauxdoe = wbauxdoe + wvalver;
           ELSE
           IF (wtipocodver = 1) THEN
              wbauxdoe = wbauxdoe - wvalver;
         END
    END

  IF ((wempatu <> 0) AND (wcolatu <> 0))  THEN
     BEGIN
       BDCODEMP = wempatu;
       BDCODCOL = wcolatu;
       BDREFA13 = wrefa13;
       BDBSALMATA13 = wbsalmat;
       BDBACITRABA13 = wbacitra;
       BDBAUXDOEA13 = wbauxdoe;

       SUSPEND;

     END
END
^


/* Restore proc. body: SP_VRHF_13SALARIO_MAIORIGUALREF */
ALTER PROCEDURE SP_VRHF_13SALARIO_MAIORIGUALREF(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF13 INTEGER,
BDVAL13 NUMERIC(15,6),
BDMESESPROP13 INTEGER,
BDBASEIR13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTSCS13 NUMERIC(15,6),
BDBASEFGTS13 NUMERIC(15,6),
BDDATABAIXA13 DATE,
BDREFBAIXA13 INTEGER,
BDPERCIR13 NUMERIC(15,6),
BDVALORIR13 NUMERIC(15,6),
BDBRAIS13 NUMERIC(15,6),
BDDEP13 NUMERIC(15,6),
BDSALBASE13 NUMERIC(15,6),
BDARREPROV13 NUMERIC(15,6),
BDARREDESC13 NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDPERCINSS13 NUMERIC(15,6),
BDVALORINSS13 NUMERIC(15,6),
BDANO13 INTEGER)
 AS
DECLARE VARIABLE wsql VARCHAR(32700);
DECLARE VARIABLE wwhere VARCHAR(32700);
DECLARE VARIABLE wano INTEGER;
BEGIN
  wsql = 'select BDCODEMP, '||
                'BDCODCOL, '||
                'BDREF13, '||
                'BDVAL13, '||
                'BDMESESPROP13, '||
                'BDBASEIR13, '||
                'BDFGTS13, '||
                'BDFGTSCS13, '||
                'BDBASEFGTS13, '||
                'BDDATABAIXA13, '||
                'BDREFBAIXA13, '||
                'BDPERCIR13, '||
                'BDVALORIR13, '||
                'BDBRAIS13, '||
                'BDDEP13, '||
                'BDSALBASE13, '||
                'BDARREPROV13, '||
                'BDARREDESC13, '||
                'BDBASEINSS13, '||
                'BDPERCINSS13, '||
                'BDVALORINSS13, '||
                'BDANO13 '||
         'from VRHF_EMP_T13SAL ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (prreferencia IS NOT NULL AND prreferencia <> 0) THEN
     BEGIN
       wano = CAST((SUBSTRING(prreferencia FROM 1 FOR 4)) AS INTEGER);


       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDREF13 >= '||prreferencia||' and BDANO13 = '||wano;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF13,
    :BDVAL13,
    :BDMESESPROP13,
    :BDBASEIR13,
    :BDFGTS13,
    :BDFGTSCS13,
    :BDBASEFGTS13,
    :BDDATABAIXA13,
    :BDREFBAIXA13,
    :BDPERCIR13,
    :BDVALORIR13,
    :BDBRAIS13,
    :BDDEP13,
    :BDSALBASE13,
    :BDARREPROV13,
    :BDARREDESC13,
    :BDBASEINSS13,
    :BDPERCINSS13,
    :BDVALORINSS13,
    :BDANO13
  DO

  SUSPEND;
END
^

/* Restore proc. body: SP_VRHF_AD13SAL_ANO */
CREATE OR ALTER PROCEDURE SP_VRHF_AD13SAL_ANO (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(32700),
    PRANO INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREFA13 INTEGER,
    BDPERCA13 NUMERIC(15,6),
    BDVALA13 NUMERIC(15,6),
    BDTIPOPROPA13 INTEGER,
    BDMESESPROPA13 INTEGER,
    BDBASEIRA13 NUMERIC(15,6),
    BDFGTSA13 NUMERIC(15,6),
    BDFGTSCSA13 NUMERIC(15,6),
    BDBASEFGTSA13 NUMERIC(15,6),
    BDDATABAIXAA13 DATE,
    BDREFBAIXAA13 INTEGER,
    BDPERCIRA13 NUMERIC(15,6),
    BDVALORIRA13 NUMERIC(15,6),
    BDBSALFAMA13 NUMERIC(15,6),
    BDSALFAMA13 NUMERIC(15,6),
    BDBRAISA13 NUMERIC(15,6),
    BDDEPA13 NUMERIC(15,6),
    BDSALBASEA13 NUMERIC(15,6),
    BDARREPROVA13 NUMERIC(15,6),
    BDARREDESCA13 NUMERIC(15,6),
    BDANOA13 INTEGER,
    BDESTPROVA13 NUMERIC(15,6),
    BDCALCFERA13 VARCHAR(5),
    BDCODEMPORIG INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
BEGIN
  wsql = 'select BDCODEMP, '||
                'BDCODCOL, '||
                'BDREFA13, '||
                'BDPERCA13, '||
                'BDVALA13, '||
                'BDTIPOPROPA13, '||
                'BDMESESPROPA13, '||
                'BDBASEIRA13, '||
                'BDFGTSA13, '||
                'BDFGTSCSA13, '||
                'BDBASEFGTSA13, '||
                'BDDATABAIXAA13, '||
                'BDREFBAIXAA13, '||
                'BDPERCIRA13, '||
                'BDVALORIRA13, '||
                'BDBSALFAMA13, '||
                'BDSALFAMA13, '||
                'BDBRAISA13, '||
                'BDDEPA13, '||
                'BDSALBASEA13, '||
                'BDARREPROVA13, '||
                'BDARREDESCA13, '||
                'BDANOA13, '||
                'BDESTPROVA13, '||
                'BDCALCFERA13 '||
         'from VRHF_EMP_TA13SAL ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (prano IS NOT NULL AND prano <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDANOA13 = '||prano;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFA13,
    :BDPERCA13,
    :BDVALA13,
    :BDTIPOPROPA13,
    :BDMESESPROPA13,
    :BDBASEIRA13,
    :BDFGTSA13,
    :BDFGTSCSA13,
    :BDBASEFGTSA13,
    :BDDATABAIXAA13,
    :BDREFBAIXAA13,
    :BDPERCIRA13,
    :BDVALORIRA13,
    :BDBSALFAMA13,
    :BDSALFAMA13,
    :BDBRAISA13,
    :BDDEPA13,
    :BDSALBASEA13,
    :BDARREPROVA13,
    :BDARREDESCA13,
    :BDANOA13,
    :BDESTPROVA13,
    :BDCALCFERA13
  DO
    BEGIN
      BDCODEMPORIG = NULL;
      SUSPEND;
    END

/* Transferidos */
  wsql = 'select TRANS.BDCODEMP, '||
                'TRANS.BDCODCOL, '||
                'A13.BDREFA13, '||
                'A13.BDPERCA13, '||
                'A13.BDVALA13, '||
                'A13.BDTIPOPROPA13, '||
                'A13.BDMESESPROPA13, '||
                'A13.BDBASEIRA13, '||
                'A13.BDFGTSA13, '||
                'A13.BDFGTSCSA13, '||
                'A13.BDBASEFGTSA13, '||
                'A13.BDDATABAIXAA13, '||
                'A13.BDREFBAIXAA13, '||
                'A13.BDPERCIRA13, '||
                'A13.BDVALORIRA13, '||
                'A13.BDBSALFAMA13, '||
                'A13.BDSALFAMA13, '||
                'A13.BDBRAISA13, '||
                'A13.BDDEPA13, '||
                'A13.BDSALBASEA13, '||
                'A13.BDARREPROVA13, '||
                'A13.BDARREDESCA13, '||
                'A13.BDANOA13, '||
                'A13.BDESTPROVA13, '||
                'A13.BDCALCFERA13, '||
                'TRANS.BDCODEMPORIG '||
         'from (select BDCODEMPORIG, BDCODCOLORIG, BDCODEMP, BDCODCOL from VW_VRH_EMP_TTRANSCOL_DESTINO ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;


  wsql = wsql||wwhere||') TRANS ';
  wsql = wsql||' join VRHF_EMP_TA13SAL A13 on (A13.BDCODEMP = TRANS.BDCODEMPORIG and A13.BDCODCOL = TRANS.BDCODCOLORIG) ';
  wwhere = '';

  IF (prano IS NOT NULL AND prano <> 0) THEN
     wwhere = ' where A13.BDANOA13 = '||prano;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFA13,
    :BDPERCA13,
    :BDVALA13,
    :BDTIPOPROPA13,
    :BDMESESPROPA13,
    :BDBASEIRA13,
    :BDFGTSA13,
    :BDFGTSCSA13,
    :BDBASEFGTSA13,
    :BDDATABAIXAA13,
    :BDREFBAIXAA13,
    :BDPERCIRA13,
    :BDVALORIRA13,
    :BDBSALFAMA13,
    :BDSALFAMA13,
    :BDBRAISA13,
    :BDDEPA13,
    :BDSALBASEA13,
    :BDARREPROVA13,
    :BDARREDESCA13,
    :BDANOA13,
    :BDESTPROVA13,
    :BDCALCFERA13,
    :BDCODEMPORIG
  DO
    BEGIN
      SUSPEND;
    END
END
^

/* Restore proc. body: SP_VRHF_AD13SAL_ANO_RESC */
CREATE OR ALTER PROCEDURE SP_VRHF_AD13SAL_ANO_RESC (
    PRCODEMP VARCHAR(15000),
    PRCODCOL VARCHAR(32700),
    PRMES INTEGER,
    PRANO INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREFA13 INTEGER,
    BDPERCA13 NUMERIC(15,6),
    BDVALA13 NUMERIC(15,6),
    BDTIPOPROPA13 INTEGER,
    BDMESESPROPA13 INTEGER,
    BDBASEIRA13 NUMERIC(15,6),
    BDFGTSA13 NUMERIC(15,6),
    BDFGTSCSA13 NUMERIC(15,6),
    BDBASEFGTSA13 NUMERIC(15,6),
    BDDATABAIXAA13 DATE,
    BDREFBAIXAA13 INTEGER,
    BDPERCIRA13 NUMERIC(15,6),
    BDVALORIRA13 NUMERIC(15,6),
    BDBSALFAMA13 NUMERIC(15,6),
    BDSALFAMA13 NUMERIC(15,6),
    BDBRAISA13 NUMERIC(15,6),
    BDDEPA13 NUMERIC(15,6),
    BDSALBASEA13 NUMERIC(15,6),
    BDARREPROVA13 NUMERIC(15,6),
    BDARREDESCA13 NUMERIC(15,6),
    BDANOA13 INTEGER,
    BDESTPROVA13 NUMERIC(15,6))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQLTRANS VARCHAR(32700);
DECLARE VARIABLE WWHERETRANS VARCHAR(32700);
BEGIN
  wsql = 'select X.BDCODEMP, '||'X.BDCODCOL, '||'X.BDREFA13, '||'X.BDPERCA13, '||'X.BDVALA13, '||'X.BDTIPOPROPA13, '||
                'X.BDMESESPROPA13, '||'X.BDBASEIRA13, '||'X.BDFGTSA13, '||'X.BDFGTSCSA13, '||'X.BDBASEFGTSA13, '||
                'X.BDDATABAIXAA13, '||'X.BDREFBAIXAA13, '||'X.BDPERCIRA13, '||'X.BDVALORIRA13, '||'X.BDBSALFAMA13, '||
                'X.BDSALFAMA13, '||'X.BDBRAISA13, '||'X.BDDEPA13, '||'X.BDSALBASEA13, '||'X.BDARREPROVA13, '||'X.BDARREDESCA13, '||
                'X.BDANOA13, '||'X.BDESTPROVA13 '||'from VRHF_EMP_TA13SAL X ';

  WSQLTRANS = ' select x.BDCODEMP BDCODEMP, X.BDCODCOL BDCODCOL, a13.BDREFA13, a13.BDPERCA13, a13.BDVALA13, a13.BDTIPOPROPA13, '||
                      ' a13.BDMESESPROPA13, a13.BDBASEIRA13, a13.BDFGTSA13, a13.BDFGTSCSA13, a13.BDBASEFGTSA13, a13.BDDATABAIXAA13, '||
                      'a13.BDREFBAIXAA13, a13.BDPERCIRA13, a13.BDVALORIRA13, '||
                      ' a13.BDBSALFAMA13, a13.BDSALFAMA13, a13.BDBRAISA13, a13.BDDEPA13, a13.BDSALBASEA13, a13.BDARREPROVA13, '||
                      ' a13.BDARREDESCA13, a13.BDANOA13, a13.BDESTPROVA13 '||
                      ' from VRHF_EMP_TA13SAL a13 '||
                      ' join (select trans.bdcodemporig, trans.bdcodcolorig, trans.bdcodempdest bdcodemp, trans.bdcodcoldest bdcodcol '||
                      '  from vrh_emp_ttranscol trans ) x on (a13.bdcodemp = x.BDCODEMPORIG and a13.bdcodcol = x.BDCODCOLORIG) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  wwheretrans = wwhere;
  IF (prano IS NOT NULL AND prano <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          BEGIN
            wwhere = wwhere||' and ';
            wwheretrans = wwheretrans||' and ';
          END

       wwhere = wwhere||'X.BDANOA13 = '||prano;
       wwheretrans = wwheretrans||'a13.BDANOA13 = '||prano;
     END

  IF (prmes IS NOT NULL AND prmes <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          BEGIN
            wwhere = wwhere||' and ';
            wwheretrans = wwheretrans||' and ';
          END

       wwhere = wwhere||'exists ('||
                                 'select Y.BDCODEMP '||
                                 'from VRH_EMP_TRESCISAO Y '||
                                 'where X.BDCODEMP = Y.BDCODEMP and X.BDCODCOL = Y.BDCODCOL and ((extract(YEAR FROM Y.BDDATARESCISAO) = '||prano||
                                 ' and extract(MONTH FROM Y.BDDATARESCISAO) = '||prmes||') or (extract(YEAR FROM Y.BDPROJECAOAVISO) = '||prano||
                                 ' and extract(MONTH FROM Y.BDPROJECAOAVISO) = '||prmes||')))';
       wwheretrans = wwheretrans||'exists ('||
                                           'select Y.BDCODEMP '||
                                           'from VRH_EMP_TRESCISAO Y '||
                                           'where X.BDCODEMP = Y.BDCODEMP and X.BDCODCOL = Y.BDCODCOL and ((extract(YEAR FROM Y.BDDATARESCISAO) = '||prano||
                                           ' and extract(MONTH FROM Y.BDDATARESCISAO) = '||prmes||') or (extract(YEAR FROM Y.BDPROJECAOAVISO) = '||prano||
                                           ' and extract(MONTH FROM Y.BDPROJECAOAVISO) = '||prmes||')))';
     END

  IF (wwhere <> '') THEN
     BEGIN
       wwhere = ' where '||wwhere;
       wwheretrans = ' where '||wwheretrans;
     END

  wsql = wsql||wwhere;
  wsql = wsql||' union all ';
  wsql = wsql||WSQLTRANS||' '||wwheretrans;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFA13,
    :BDPERCA13,
    :BDVALA13,
    :BDTIPOPROPA13,
    :BDMESESPROPA13,
    :BDBASEIRA13,
    :BDFGTSA13,
    :BDFGTSCSA13,
    :BDBASEFGTSA13,
    :BDDATABAIXAA13,
    :BDREFBAIXAA13,
    :BDPERCIRA13,
    :BDVALORIRA13,
    :BDBSALFAMA13,
    :BDSALFAMA13,
    :BDBRAISA13,
    :BDDEPA13,
    :BDSALBASEA13,
    :BDARREPROVA13,
    :BDARREDESCA13,
    :BDANOA13,
    :BDESTPROVA13
  DO
  SUSPEND;
END
^

/* Restore proc. body: SP_VRHF_AD13SAL_MAIORREF */
ALTER PROCEDURE SP_VRHF_AD13SAL_MAIORREF(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFA13 INTEGER,
BDPERCA13 NUMERIC(15,6),
BDVALA13 NUMERIC(15,6),
BDTIPOPROPA13 INTEGER,
BDMESESPROPA13 INTEGER,
BDBASEIRA13 NUMERIC(15,6),
BDFGTSA13 NUMERIC(15,6),
BDFGTSCSA13 NUMERIC(15,6),
BDBASEFGTSA13 NUMERIC(15,6),
BDDATABAIXAA13 DATE,
BDREFBAIXAA13 INTEGER,
BDPERCIRA13 NUMERIC(15,6),
BDVALORIRA13 NUMERIC(15,6),
BDBSALFAMA13 NUMERIC(15,6),
BDSALFAMA13 NUMERIC(15,6),
BDBRAISA13 NUMERIC(15,6),
BDDEPA13 NUMERIC(15,6),
BDSALBASEA13 NUMERIC(15,6),
BDARREPROVA13 NUMERIC(15,6),
BDARREDESCA13 NUMERIC(15,6),
BDANOA13 INTEGER,
BDESTPROVA13 NUMERIC(15,6))
 AS
DECLARE VARIABLE wsql VARCHAR(32700);
DECLARE VARIABLE wwhere VARCHAR(32700);
DECLARE VARIABLE wano INTEGER;
BEGIN
  wsql = 'select BDCODEMP, '||
                'BDCODCOL, '||
                'BDREFA13, '||
                'BDPERCA13, '||
                'BDVALA13, '||
                'BDTIPOPROPA13, '||
                'BDMESESPROPA13, '||
                'BDBASEIRA13, '||
                'BDFGTSA13, '||
                'BDFGTSCSA13, '||
                'BDBASEFGTSA13, '||
                'BDDATABAIXAA13, '||
                'BDREFBAIXAA13, '||
                'BDPERCIRA13, '||
                'BDVALORIRA13, '||
                'BDBSALFAMA13, '||
                'BDSALFAMA13, '||
                'BDBRAISA13, '||
                'BDDEPA13, '||
                'BDSALBASEA13, '||
                'BDARREPROVA13, '||
                'BDARREDESCA13, '||
                'BDANOA13, '||
                'BDESTPROVA13 '||
         'from VRHF_EMP_TA13SAL ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (prreferencia IS NOT NULL AND prreferencia <> 0) THEN
     BEGIN
       wano = CAST((SUBSTRING(prreferencia FROM 1 FOR 4)) AS INTEGER);


       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDREFA13 > '||prreferencia||' and BDANOA13 = '||wano;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFA13,
    :BDPERCA13,
    :BDVALA13,
    :BDTIPOPROPA13,
    :BDMESESPROPA13,
    :BDBASEIRA13,
    :BDFGTSA13,
    :BDFGTSCSA13,
    :BDBASEFGTSA13,
    :BDDATABAIXAA13,
    :BDREFBAIXAA13,
    :BDPERCIRA13,
    :BDVALORIRA13,
    :BDBSALFAMA13,
    :BDSALFAMA13,
    :BDBRAISA13,
    :BDDEPA13,
    :BDSALBASEA13,
    :BDARREPROVA13,
    :BDARREDESCA13,
    :BDANOA13,
    :BDESTPROVA13
  DO

  SUSPEND;
END
^

/* Restore proc. body: SP_VRHF_BASE_CALC_TERC */
create or alter procedure SP_VRHF_BASE_CALC_TERC (
    PRREF integer,
    PRGPSSEFIP integer = 0,
    PRCODEMP varchar(32000) = null,
    PRCODAUT varchar(32000) = null)
returns (
    BDCODEMP integer,
    BDREFSERV integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDVALORINSS numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASERATAPO numeric(18,6),
    BDVALOUTENTIDADES numeric(18,6),
    BDCODTER integer,
    BDGPSSEFIP integer,
    BDCATEGORIAESOCIAL integer)
as
declare variable WSQL varchar(5000);
declare variable WSOMAAP numeric(18,6);
declare variable WEMPATU integer;
declare variable WCODSERV integer;
declare variable WCLATRIB integer;
declare variable WCOOP integer;
declare variable WCATESOCIAL integer;
BEGIN
  wsql = 'select serv.bdcodemp bdcodemp, pf.bdrefserv, pf.bdcodcentro, pf.bdcodtpcc, coalesce(serv.bdvalorinss,0) bdinssfn,'||
           'coalesce(serv.bdbaseratapo,0) bdbratapofn, serv.bdvaloutentidades valOutentidade, serv.bdcodter bdcodter, 0 bdgpssefip, serv.bdcodserv ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wsql = wsql||'from (select * from vrhf_base_calc_terc where BDREFINSSSERV = '||prref;

       wsql = wsql||' and '||prcodemp;

       IF (prcodaut IS NOT NULL AND prcodaut <> '') THEN
          wsql = wsql||' and '||prcodaut;

       wsql = wsql||') serv ';
     END
  ELSE
     wsql = wsql||'from vrhf_base_calc_terc serv ';

  wsql = wsql||'join vrh_base_tservterc pf on (serv.bdcodemp = pf.bdcodemp and serv.bdcodter = pf.bdcodter and serv.bdcodserv = pf.bdcodserv) '||
         'where pf.bdrefserv = '||prref||' order by serv.bdcodemp, serv.bdcodter ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :BDREFSERV,
    :BDCODCENTRO,
    :BDCODTPCC,
    :BDVALORINSS,
    :BDBASERATAPO,
    :BDVALOUTENTIDADES,
    :BDCODTER,
    :BDGPSSEFIP,
    :wcodserv
  DO
    begin
      wclatrib = null;
      wcoop    = null;
      select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :BDCODEMP and BDREFEMP <= :prref order by BDREFEMP DESC into :wclatrib, :wcoop;
      wcatesocial = null;
      select first 1 BDCATEGORIAESOCIAL from VRHF_BASE_TTERC_FGTSGPS where BDCODTER = :BDCODTER and BDREFTERC <= :prref order by BDREFTERC DESC into :wcatesocial;
      bdcategoriaesocial = wcatesocial;


      if (not (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and coalesce(wcatesocial, 0) in (731, 734))) then
         begin
           select sum(FN.BDVALOR) from VRHF_BASE_ITEMS_CALCTERC FN
           join VW_TVERBAS_REF V on (V.BDCODVER = FN.BDCODVER)
           where FN.BDCODEMP = :BDCODEMP and FN.BDCODTER = :BDCODTER and FN.BDCODSERV = :wcodserv and ((coalesce(V.BDINSSVER, 0) <> 0) or (coalesce(V.BDBASEGPSVER, 'FALSE') = 'TRUE'))
           into :BDBASEINSS;
           BDBASEINSS = coalesce(BDBASEINSS, 0);
         end
      else
         BDBASEINSS = 0;

      SUSPEND;
    end

   IF (prgpssefip = 1) THEN
     BEGIN
       wsomaap = 0;
       wempatu = 0;

       wsql = 'select serv.bdcodemp bdcodemp, pf.bdrefserv, pf.bdcodcentro, pf.bdcodtpcc, coalesce(serv.bdvalorinss,0) bdinssfn,'||
                'coalesce(serv.bdbaseratapo,0) bdbratapofn, serv.bdvaloutentidades valOutentidade, serv.bdcodter bdcodter, 1 bdgpssefip, serv.bdcodserv ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          BEGIN
            wsql = wsql||'from (select * from vrhf_base_calc_terc where BDREFINSSSERV = '||prref;
     
            wsql = wsql||' and '||prcodemp;
     
            IF (prcodaut IS NOT NULL AND prcodaut <> '') THEN
               wsql = wsql||' and '||prcodaut;
     
            wsql = wsql||') serv ';
          END
       ELSE
          wsql = wsql||'from vrhf_base_calc_terc serv ';

       wsql = wsql||'join vrh_base_tservterc pf on (serv.bdcodemp = pf.bdcodemp and serv.bdcodter = pf.bdcodter and serv.bdcodserv = pf.bdcodserv) '||
              'where pf.bdrefserv = '||prref||' order by serv.bdcodemp, serv.bdcodter ';

       FOR EXECUTE STATEMENT wsql
       INTO
         :bdcodemp,
         :BDREFSERV,
         :BDCODCENTRO,
         :BDCODTPCC,
         :BDVALORINSS,
         :BDBASERATAPO,
         :BDVALOUTENTIDADES,
         :BDCODTER,
         :BDGPSSEFIP,
         :wcodserv
       DO
         BEGIN
           wclatrib = null;
           wcoop    = null;
           select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :BDCODEMP and BDREFEMP <= :prref order by BDREFEMP DESC into :wclatrib, :wcoop;
           wcatesocial = null;
           select first 1 BDCATEGORIAESOCIAL from VRHF_BASE_TTERC_FGTSGPS where BDCODTER = :BDCODTER and BDREFTERC <= :prref order by BDREFTERC DESC into :wcatesocial;
           bdcategoriaesocial = wcatesocial;
           
          
           if (not (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and coalesce(wcatesocial, 0) in (731, 734))) then
              begin
                select sum(FN.BDVALOR) from VRHF_BASE_ITEMS_CALCTERC FN
                join VW_TVERBAS_REF V on (V.BDCODVER = FN.BDCODVER)
                where FN.BDCODEMP = :BDCODEMP and FN.BDCODTER = :BDCODTER and FN.BDCODSERV = :wcodserv and ((coalesce(V.BDINSSVER, 0) <> 0) or (coalesce(V.BDBASEGPSVER, 'FALSE') = 'TRUE'))
                into :BDBASEINSS;
                BDBASEINSS = coalesce(BDBASEINSS, 0);
              end
           else
              BDBASEINSS = 0;

           IF (wempatu <> bdcodemp) THEN
              BEGIN
                wsomaap = 0;
                SELECT SUM(BDSOMA) FROM (
                  SELECT X.bdvalvfn BDSOMA FROM vrhf_emp_tverbafn X
                  JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
                  WHERE X.bdcodemp = :bdcodemp AND X.bdreffn = :prref
                  UNION ALL
                  SELECT X.bdvalvft BDSOMA FROM vrhf_emp_tverbatomador X
                  JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
                  WHERE X.bdcodemp = :bdcodemp AND X.bdreftomador = :prref
                )
                INTO :wsomaap;
              END

           IF (prRef >= 200903 and PRREF < 201606 AND wsomaap <> 0) THEN --IN RFB Nº 1730: a partir da competência junho de 2016, o valor do aviso prévio indenizado não deve ser computado para fins de preenchimento da GPS
              SUSPEND;
         END
     END
END^

/* Restore proc. body: SP_VRHF_BASE_TVERBASEMP_CONS */
create or alter procedure SP_VRHF_BASE_TVERBASEMP_CONS (
    PRCODEMP integer,
    PRANOMES integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODIGOVEREMP integer,
    BDCODVER integer,
    BDDESCVER varchar(40),
    BDTIPOCOLVEREMP integer,
    BDCLASSECOLVEREMP integer,
    BDCOMFGTS varchar(5),
    BDCODTCA integer,
    BDDESCTCA varchar(50),
    BDINTERMITENTE DM_BOOLEAN,
    BDADICNOTVAR DM_BOOLEAN,
    BDAULISTA boolean)
as
declare variable WSQL varchar(32700);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(pranomes, NULL, NULL);

  wsql = 'select X.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'X.BDCODIGOVEREMP, '||
                'X.BDCODVER, '||
                'VERBA.BDDESCVER, '||
                'X.BDTIPOCOLVEREMP, '||
                'X.BDCLASSECOLVEREMP, '||
                'X.BDCOMFGTS, '||
                'X.BDCODTCA, '||
                'TCA.BDDESCTCA, '||
                'X.BDINTERMITENTE, '||
                'X.BDADICNOTVAR, '||
                'X.BDAULISTA '||
  'from VRHF_BASE_TVERBASEMP X '||
  'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
     'on (EMP.BDCODEMP = X.BDCODEMP) '||
  'left outer join VRH_BASE_TVERBAS VERBA '||
     'on (VERBA.BDCODVER = X.BDCODVER) '||
  'left outer join VRH_BASE_TTIPOCALCAVUL TCA '||
     'on (TCA.BDCODTCA = X.BDCODTCA) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wsql = wsql||'where X.BDCODEMP = '||:prcodemp;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODIGOVEREMP,
    :BDCODVER,
    :BDDESCVER,
    :BDTIPOCOLVEREMP,
    :BDCLASSECOLVEREMP,
    :BDCOMFGTS,
    :BDCODTCA,
    :BDDESCTCA,
    :BDINTERMITENTE,
    :BDADICNOTVAR,
    :BDAULISTA
  DO
  SUSPEND;
END^

/* Restore proc. body: SP_VRHF_CONS_BASES_AD */
ALTER PROCEDURE SP_VRHF_CONS_BASES_AD(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREF INTEGER,
PRDATAPGTO DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFIR INTEGER,
BDREFIRFIR INTEGER,
BDTIPOCALCFIR INTEGER,
BDBASEIRFIR NUMERIC(18,6),
BDVALINSSFIR NUMERIC(18,6),
BDVALIRFIR NUMERIC(18,6),
BDDESCBASEIRFIR NUMERIC(18,6),
BDDATAFIR DATE,
BDDATAPROC DATE,
BDHORAPROC TIME)
 AS
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE WDATAPROC DATE;
DECLARE VARIABLE WHORAPROC TIME;
BEGIN
  wsql = 'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL - BDPENJUD - BDPENALIM,BDINSS,'||
         'BDIR,0,BDDATAPGTO,BDDATAPROC,BDHORAPROC '||
         'from SP_VRHF_DADOS_IR_AD('''||'FOL.BDCODEMP = '||prcodemp||''','''||'FOL.BDCODCOL = '||prcodcol||''','||prref||','||prref||') '||
         'where BDDATAPGTO <= '''||prdatapgto||''' and BDREFPAG = '||SUBSTRING(CAST(prdatapgto AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatapgto AS VARCHAR(10)) FROM 6 FOR 2);


  wdataproc = NULL;
  whoraproc = NULL;

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFFIR,
    :BDREFIRFIR,
    :BDTIPOCALCFIR,
    :BDBASEIRFIR,
    :BDVALINSSFIR,
    :BDVALIRFIR,
    :BDDESCBASEIRFIR, 
    :BDDATAFIR,
    :BDDATAPROC,
    :BDHORAPROC
  DO
    BEGIN
      IF (BDDATAFIR = prdatapgto AND BDREFFIR = prref) THEN
         BEGIN
           wdataproc = BDDATAPROC;
           whoraproc = BDHORAPROC;
         END
      ELSE
         SUSPEND;
    END

  IF ((wdataproc IS NULL) OR (whoraproc IS NULL)) THEN
     BEGIN
       SELECT CURRENT_DATE,  CURRENT_TIME FROM rdb$database INTO :wdataproc,:whoraproc;
     END

  wsql = 'select '||
           'BDCODEMP,BDCODCOL,BDREF BDREFFIR,BDREFPAG BDREFIRFIR,BDTIPO BDTIPOCALCFIR,BDRENDTRIBUTAVEL - BDPENJUD - BDPENALIM BDBASEIRFIR,BDINSS BDVALINSSFIR,BDIR BDVALIRFIR,0 BDDESCBASEIRFIR, '||
           'BDDATAPGTO BDDATAFIR,BDDATAPROC,BDHORAPROC '||
         'from SP_VRHF_DADOS_IR_FN('''||'FOL.BDCODEMP = '||prcodemp||''','''||'FOL.BDCODCOL = '||prcodcol||''','||prref||','||prref||') '||
         'where (BDDATAPGTO < '''||prdatapgto||''') or ((BDDATAPGTO = '''||prdatapgto||''') and (BDDATAPROC < '''||wdataproc||''')) or '||
           '((BDDATAPGTO = '''||prdatapgto||''') and (BDDATAPROC = '''||wdataproc||''') and (BDHORAPROC < '''||whoraproc||'''))  and BDREFPAG = '||SUBSTRING(CAST(prdatapgto AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatapgto AS VARCHAR(10)) FROM 6 FOR 2)||
         ' union all '||
         'select '||
           'BDCODEMP,BDCODCOL,BDREF BDREFFIR,BDREFPAG BDREFIRFIR,BDTIPO BDTIPOCALCFIR,BDRENDTRIBUTAVEL - BDPENJUD - BDPENALIM BDBASEIRFIR,BDINSS BDVALINSSFIR,BDIR BDVALIRFIR,0 BDDESCBASEIRFIR, '||
           'BDDATAPGTO BDDATAFIR,BDDATAPROC,BDHORAPROC '||
         'from SP_VRHF_DADOS_IR_FC('''||'FOL.BDCODEMP = '||prcodemp||''','''||'FOL.BDCODCOL = '||prcodcol||''','||prref||','||prref||') '||
         'where (BDDATAPGTO < '''||prdatapgto||''') or ((BDDATAPGTO = '''||prdatapgto||''') and (BDDATAPROC < '''||wdataproc||''')) or '||
           '((BDDATAPGTO = '''||prdatapgto||''') and (BDDATAPROC = '''||wdataproc||''') and (BDHORAPROC < '''||whoraproc||''')) and BDREFPAG = '||SUBSTRING(CAST(prdatapgto AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatapgto AS VARCHAR(10)) FROM 6 FOR 2);

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFFIR,
    :BDREFIRFIR,
    :BDTIPOCALCFIR,
    :BDBASEIRFIR,
    :BDVALINSSFIR,
    :BDVALIRFIR,
    :BDDESCBASEIRFIR, 
    :BDDATAFIR,
    :BDDATAPROC,
    :BDHORAPROC
  DO
    BEGIN
      SUSPEND;
    END
END
^

/* Restore proc. body: SP_VRHF_CONS_BASES_FN */
ALTER PROCEDURE SP_VRHF_CONS_BASES_FN(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREF INTEGER,
PRDATAPGTO DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFIR INTEGER,
BDREFIRFIR INTEGER,
BDTIPOCALCFIR INTEGER,
BDBASEIRFIR NUMERIC(18,6),
BDVALINSSFIR NUMERIC(18,6),
BDVALIRFIR NUMERIC(18,6),
BDDESCBASEIRFIR NUMERIC(18,6),
BDDATAFIR DATE,
BDDATAPROC DATE,
BDHORAPROC TIME)
 AS
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE WDATAPROC DATE;
DECLARE VARIABLE WHORAPROC TIME;
BEGIN
  --comentario so para testar
  wsql = 'select '||
           'BDCODEMP,BDCODCOL,BDREF BDREFFIR,BDREFPAG BDREFIRFIR,BDTIPO BDTIPOCALCFIR,BDRENDTRIBUTAVEL - BDPENJUD - BDPENALIM BDBASEIRFIR,BDINSS BDVALINSSFIR,BDIR BDVALIRFIR,0 BDDESCBASEIRFIR, '||
           'BDDATAPGTO BDDATAFIR,BDDATAPROC,BDHORAPROC '||
         'from SP_VRHF_DADOS_IR_FN('''||'FOL.BDCODEMP = '||prcodemp||''','''||'FOL.BDCODCOL = '||prcodcol||''','||prref||','||prref||') '||
         'where BDDATAPGTO <= '''||prdatapgto||''' and BDREFPAG = '||SUBSTRING(CAST(prdatapgto AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatapgto AS VARCHAR(10)) FROM 6 FOR 2);

  wdataproc = NULL;
  whoraproc = NULL;

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFFIR,
    :BDREFIRFIR,
    :BDTIPOCALCFIR,
    :BDBASEIRFIR,
    :BDVALINSSFIR,
    :BDVALIRFIR,
    :BDDESCBASEIRFIR, 
    :BDDATAFIR,
    :BDDATAPROC,
    :BDHORAPROC
  DO
    BEGIN
      IF (BDDATAFIR = prdatapgto AND BDREFFIR = prref)  THEN
         BEGIN
           wdataproc = BDDATAPROC;
           whoraproc = BDHORAPROC;
         END
      ELSE
         SUSPEND;
    END

  IF ((wdataproc IS NULL) OR (whoraproc IS NULL)) THEN
     BEGIN
       SELECT CURRENT_DATE,  CURRENT_TIME FROM rdb$database INTO :wdataproc,:whoraproc;
     END

  wsql = 'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL - BDPENJUD - BDPENALIM,BDINSS,'||
         'BDIR,0,BDDATAPGTO,BDDATAPROC,BDHORAPROC '||
         'from SP_VRHF_DADOS_IR_AD('''||'FOL.BDCODEMP = '||prcodemp||''','''||'FOL.BDCODCOL = '||prcodcol||''','||prref||','||prref||') '||
         'where (BDDATAPGTO < '''||prdatapgto||''') or ((BDDATAPGTO = '''||prdatapgto||''') and (BDDATAPROC < '''||wdataproc||''')) or '||
           '((BDDATAPGTO = '''||prdatapgto||''') and (BDDATAPROC = '''||wdataproc||''') and (BDHORAPROC < '''||whoraproc||''')) and BDREFPAG = '||SUBSTRING(CAST(prdatapgto AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatapgto AS VARCHAR(10)) FROM 6 FOR 2)||
         ' union all '||
         'select '||
           'BDCODEMP,BDCODCOL,BDREF BDREFFIR,BDREFPAG BDREFIRFIR,BDTIPO BDTIPOCALCFIR,BDRENDTRIBUTAVEL - BDPENJUD - BDPENALIM BDBASEIRFIR,BDINSS BDVALINSSFIR,BDIR BDVALIRFIR,0 BDDESCBASEIRFIR, '||
           'BDDATAPGTO BDDATAFIR,BDDATAPROC,BDHORAPROC '||
         'from SP_VRHF_DADOS_IR_FC('''||'FOL.BDCODEMP = '||prcodemp||''','''||'FOL.BDCODCOL = '||prcodcol||''','||prref||','||prref||') '||
         'where (BDDATAPGTO < '''||prdatapgto||''') or ((BDDATAPGTO = '''||prdatapgto||''') and (BDDATAPROC < '''||wdataproc||''')) or '||
           '((BDDATAPGTO = '''||prdatapgto||''') and (BDDATAPROC = '''||wdataproc||''') and (BDHORAPROC < '''||whoraproc||''')) and BDREFPAG = '||SUBSTRING(CAST(prdatapgto AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatapgto AS VARCHAR(10)) FROM 6 FOR 2);

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFFIR,
    :BDREFIRFIR,
    :BDTIPOCALCFIR,
    :BDBASEIRFIR,
    :BDVALINSSFIR,
    :BDVALIRFIR,
    :BDDESCBASEIRFIR, 
    :BDDATAFIR,
    :BDDATAPROC,
    :BDHORAPROC
  DO
    BEGIN
      IF (prref <> BDREFFIR) THEN
         SUSPEND;
    END
END
^

/* Restore proc. body: SP_VRHF_DADOS_INSS_13 */
CREATE OR ALTER procedure SP_VRHF_DADOS_INSS_13 (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRANOTODO smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF13 integer,
    BDVALORINSS13 numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDSALFAM13 numeric(18,6),
    BDSALMATEMP13 numeric(18,6),
    BDBINSSMV13 numeric(18,6),
    BDCHAVE integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCODTOMADOR integer,
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBRATAPO13 numeric(18,6),
    BDBASEPIS numeric(18,6))
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(30000);
declare variable WCHAVE integer;
declare variable WCHAVEATU integer;
declare variable WCODCENTROATU integer;
declare variable WCODTPCCATU integer;
declare variable WCODTOMADORATU integer;
declare variable WCODCENTRO integer;
declare variable WCODTPCC integer;
declare variable WCODTOMADOR integer;
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WCLAVER varchar(20);
declare variable WTIPOCODVER integer;
declare variable WINSSVER integer;
declare variable WBASEGPSVER varchar(5);
declare variable WREEMBGPSVER varchar(5);
declare variable WVALOR numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WBASEINSS13 numeric(18,6);
declare variable WSALFAM numeric(18,6);
declare variable WSALMATEMP numeric(18,6);
declare variable WBASEMV13 numeric(18,6);
declare variable WREEMB numeric(18,6);
declare variable WVINDEVIDO numeric(18,6);
declare variable WVINDEVIDOSF numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WINCIDEPIS DM_BOOLEAN;
declare variable WBASEPIS numeric(18,6);
declare variable WDIFINCIDVER DM_BOOLEAN;
declare variable WSQLDIFINSSGPS varchar(300);
declare variable WCODVER integer;
declare variable WDESCVER varchar(60);
declare variable WGRUPOCLA integer;
begin
  -- Obtem valor de variável de contexto e limpa os valores da tabela temporária da sessão atual
  WSQLDIFINSSGPS = 'SELECT RDB$GET_CONTEXT(''USER_SESSION'', ''W_DIFINCIDVER'') FROM RDB$DATABASE';
  execute statement WSQLDIFINSSGPS into :WDIFINCIDVER;

  WSQL = 'select FN.BDCHAVE,FN.BDCODCENTRO,coalesce(FN.BDCODTPCC,0),FN.BDCODEMP, FN.BDCODCOL, FN.BDVALV13, FN.BDCODVER, VER.BDDESCVER, FOLN.BDBINSSMV13, VER.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, VERREF.BDPISVER ';
  WSQL = WSQL || 'from (select * from VW_VRHF_EMP_TVERBA_13_rat_CC ';
  WWHERE = '';

  if (PRCODEMP is not null and
      PRCODEMP <> '') then
  begin
    WWHERE = WWHERE || PRCODEMP;
  end

  if (PRCODCOL is not null and
      PRCODCOL <> '') then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';

    WWHERE = WWHERE || PRCODCOL;
  end

  if (PRREF is not null and
      PRREF <> 0) then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';

    if (PRANOTODO = 1) then
      WWHERE = WWHERE || 'BDREF13 >= ' || substring(:PRREF from 1 for 4) || '01 and BDREF13 <= ' || PRREF || ' ';
    else
      WWHERE = WWHERE || 'BDREF13 = ' || PRREF || ' ';
  end

  if (WWHERE <> '') then
    WWHERE = ' where ' || WWHERE;

  WSQL = WSQL || WWHERE;

  WSQL = WSQL || ') FN ';
  WSQL = WSQL || 'join VW_VRHF_EMP_T13SAL_rat_CC FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREF13 = FN.BDREF13 and FOLN.BDCHAVE = FN.BDCHAVE) ';
  WSQL = WSQL || 'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) ';
  WSQL = WSQL || 'join VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER and VERREF.BDREFVER = (SELECT FIRST 1 BDREFVER FROM VRH_BASE_TVERBAS_REF WHERE BDCODVER = VERREF.BDCODVER AND BDREFVER <= ' || PRREF || ' ORDER BY BDCODVER DESC, BDREFVER DESC)) ';
--  WSQL = WSQL || 'left outer join VRHF_SP_TOMADOR(FOLN.BDCODTPCC, FOLN.BDCODCENTRO) toma on (FOLN.BDCODCENTRO = toma.BDCODCENTRO and FOLN.BDCODTPCC = toma.BDCODCENCUS) ';
--  WSQL = WSQL || ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(FOLN.bdcodtpcc,FOLN.bdcodcentro,'||prref||',1) toma on (toma.bdcodcencus = FOLN.bdcodtpcc and toma.bdcodcentro = FOLN.bdcodcentro) ';
  WSQL = WSQL || 'order by FN.BDCODEMP,FN.BDCODCOL,FN.BDCHAVE ';

  WCHAVEATU = 0;
  WEMPATU = 0;
  WCOLATU = 0;
  WSALFAM = 0;
  WINSS13 = 0;
  WBASEINSS13 = 0;
  WSALMATEMP = 0;
  WBASEMV13 = 0;
  WCODCENTROATU = -1;
  WCODTPCCATU = -1;
  WVINDEVIDO = 0;
  WVINDEVIDOSF = 0;
  wbasepis = 0;
  WCODVER = 0;
  WDESCVER = '';

  execute procedure SP_SETA_COMPETENCIA(PRREF);

  for execute statement WSQL
          into :WCHAVE, :WCODCENTRO, :WCODTPCC, :WCODEMP, :WCODCOL, :WVALOR, :wcodver, :wdescver, :WBASEMV13, :WCLAVER,
          :WTIPOCODVER, :WINSSVER, :WBASEGPSVER, :WREEMBGPSVER, :wincidepis
  do
  begin
    if (WEMPATU = 0) then
       begin
      WEMPATU = WCODEMP;
       end

    if (WCOLATU = 0) then
      WCOLATU = WCODCOL;

    if (WCHAVEATU = 0) then
      WCHAVEATU = WCHAVE;

    if (WCODCENTROATU = -1) then
      WCODCENTROATU = WCODCENTRO;

    if (WCODTPCCATU = -1) then
      WCODTPCCATU = WCODTPCC;

    /*
      Retorna bases de INSS
    */

    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL) or (WCHAVEATU <> WCHAVE)) then
    begin


      select first 1 BDCODTPCC from VRHF_SP_TOMADOR(:WCODTPCCATU, :WCODCENTROATU) into :BDCODTOMADOR;

      BDCODTOMADOR = coalesce(BDCODTOMADOR, 0);

      BDCODEMP = WEMPATU;
      BDCODCOL = WCOLATU;
      BDREF13 = PRREF;
      BDVALORINSS13 = WINSS13;
      BDBASEINSS13 = WBASEINSS13;
      BDSALFAM13 = WSALFAM;
      BDSALMATEMP13 = WSALMATEMP;
      BDBINSSMV13 = WBASEMV13;
      BDCHAVE = WCHAVEATU;
      BDCODCENTRO = WCODCENTROATU;
      BDCODTPCC = WCODTPCCATU;

      BDVALINDEVIDO = WVINDEVIDO;
      BDVALINDEVIDOSF = WVINDEVIDOSF;
      bdbasepis       = wbasepis;

      WPERCRAT = 0;
      select first 1 BDPERCRATCOL
      from VRHF_EMP_TCOLCON_FGTSGPS
      where BDCODEMP = :WEMPATU and
            BDCODCOL = :WCOLATU and
            BDREFCOL <= :prref
      order by BDREFCOL desc
      into :WPERCRAT;

      if (WPERCRAT <> 0 and
          WPERCRAT is not null) then
        BDBRATAPO13 = BDBASEINSS13;
      else
        BDBRATAPO13 = 0;

      suspend;

      WINSS13 = 0;
      WBASEINSS13 = 0;
      WSALFAM = 0;
      WSALMATEMP = 0;
      WBASEMV13 = 0;
      WEMPATU = WCODEMP;
      WCOLATU = WCODCOL;
      WCHAVEATU = WCHAVE;
      WCODCENTROATU = WCODCENTRO;
      WCODTPCCATU = WCODTPCC;
      WVINDEVIDO = 0;
      WVINDEVIDOSF = 0;
      wbasepis = 0;
    end

    -- verificar classe no colaborador:
    wgrupocla = 0;
    SELECT CLA.BDGRUPOCLA
    FROM VW_VRH_EMP_TCOLCON_VINC VINC
    LEFT OUTER JOIN VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
    WHERE (VINC.BDCODEMP = :wempatu)
      AND (VINC.BDCODCOL = :wcolatu)
      AND (VINC.BDREFCOL <= :prref)
    ORDER BY BDCODEMP DESC, BDCODCOL DESC, BDREFCOL DESC
    INTO :wgrupocla;

        -- Valor base PIS
    if (coalesce(UPPER(wincidepis), 'FALSE') = 'TRUE') then
       begin
          IF (wtipocodver = 0) THEN  -- Provento
             wbasepis = wbasepis + wvalor;
          ELSE
          IF (wtipocodver = 1) THEN  -- Desconto
             wbasepis = wbasepis - wvalor;
       end

    -- Verifica diferença de incidência de PIS e Base GPS
    if (coalesce(UPPER(WDIFINCIDVER), 'FALSE') = 'TRUE') then
       begin
         if ((wbasegpsver <> wincidepis) and (WGRUPOCLA not in (2, 3))) then
            begin
              WSQLDIFINSSGPS = 'update or insert into VRHF_TINFO_TEMP_DIFINCIDVER (BDSESSAO, BDCODEMP, BDCODVER, BDDESCVER) '||
                               'values ('||current_connection||', '||wcodemp||', '||wcodver||', '''||wdescver||''') matching (BDSESSAO, BDCODEMP, BDCODVER)';
              execute statement WSQLDIFINSSGPS;
            end
       end

    -- INSS 13o. rescisão descontado na folha normal
    if (substring(WCLAVER from 1 for 9) = '9.010.0.3') then
      WINSS13 = WINSS13 + WVALOR;

    -- Base de INSS 13o. salário descontado na rescisão
    if ((WINSSVER = 3)) then
    begin
      if ((WTIPOCODVER = 0) and
          (upper(WBASEGPSVER) = 'TRUE')) then -- Provento
        WBASEINSS13 = WBASEINSS13 + WVALOR;
      else
      if ((WTIPOCODVER = 1) and
          (upper(WBASEGPSVER) = 'TRUE')) then -- Desconto
        WBASEINSS13 = WBASEINSS13 - WVALOR;
    end
    else
    if (cast(substring(WCLAVER from 1 for 1) as integer) in (5, 6) and
        upper(WBASEGPSVER) = 'TRUE') then
    begin
      if ((WTIPOCODVER = 0) and
          (upper(WBASEGPSVER) = 'TRUE')) then -- Provento
        WBASEINSS13 = WBASEINSS13 + WVALOR;
      else
      if ((WTIPOCODVER = 1) and
          (upper(WBASEGPSVER) = 'TRUE')) then -- Desconto
        WBASEINSS13 = WBASEINSS13 - WVALOR;
    end

    -- Valor de salário família
    if (substring(WCLAVER from 1 for 5) = '9.050') then
      WSALFAM = WSALFAM + WVALOR;

    -- Valor indevido GPS
    if (substring(WCLAVER from 1 for 9) = '9.060.1.2') then
      WVINDEVIDO = WVINDEVIDO + WVALOR;

    -- Base de salário maternidade
    if ((upper(WREEMBGPSVER) = 'TRUE') and
        ((substring(WCLAVER from 1 for 5) = '4.010') or (substring(WCLAVER from 1 for 5) = '5.010') or (substring(WCLAVER from 1 for 5) = '5.510')  or (substring(WCLAVER from 1 for 5) = '6.010') or (substring(WCLAVER from 1 for 5) = '7.070') or (substring(WCLAVER from 1 for 5) = '7.071') or (substring(WCLAVER from 1 for 5) = '8.005'))) then
    begin
      if (WTIPOCODVER = 0) then -- provento
        WSALMATEMP = WSALMATEMP + WVALOR;
      else
      if (WTIPOCODVER = 1) then -- desconto
        WSALMATEMP = WSALMATEMP - WVALOR;
    end
    else
    if (upper(WREEMBGPSVER) = 'TRUE') then
    begin
      if (WTIPOCODVER = 0) then -- provento
        WREEMB = WREEMB + WVALOR;
      else
      if (WTIPOCODVER = 1) then -- desconto
        WREEMB = WREEMB - WVALOR;
    end

  end

  if ((WEMPATU <> 0) and
      (WCOLATU <> 0)) then
  begin
    BDCODEMP = WEMPATU;
    BDCODCOL = WCOLATU;
    BDREF13 = PRREF;
    BDVALORINSS13 = WINSS13;
    BDBASEINSS13 = WBASEINSS13;
    BDSALFAM13 = WSALFAM;
    BDSALMATEMP13 = WSALMATEMP;
    BDBINSSMV13 = WBASEMV13;
    BDCHAVE = WCHAVEATU;
    BDCODCENTRO = WCODCENTROATU;
    BDCODTPCC = WCODTPCCATU;
    bdbasepis = wbasepis;


    select first 1 BDCODTPCC from VRHF_SP_TOMADOR(:WCODTPCCATU, :WCODCENTROATU) into :BDCODTOMADOR;

    BDCODTOMADOR = coalesce(BDCODTOMADOR, 0);

    BDVALINDEVIDO = WVINDEVIDO;
    BDVALINDEVIDOSF = WVINDEVIDOSF;

    WPERCRAT = 0;
    select first 1 BDPERCRATCOL
    from VRHF_EMP_TCOLCON_FGTSGPS
    where BDCODEMP = :WEMPATU and
          BDCODCOL = :WCOLATU and
          BDREFCOL <= :prref
    order by BDREFCOL desc
    into :WPERCRAT;

    if (WPERCRAT <> 0 and
        WPERCRAT is not null) then
      BDBRATAPO13 = BDBASEINSS13;
    else
      BDBRATAPO13 = 0;
    suspend;
  end
END^

/* Restore proc. body: SP_VRHF_DADOS_INSS_C13 */
CREATE OR ALTER procedure SP_VRHF_DADOS_INSS_C13 (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRANOTODO smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF13 integer,
    BDVALORINSS13 numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDSALFAM13 numeric(18,6),
    BDSALMATEMP13 numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBRATAPO13 numeric(18,6),
    BDSEMBASEGPS numeric(18,6),
    BDBASEPIS numeric(18,6))
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(30000);
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WCLAVER varchar(20);
declare variable WTIPOCODVER integer;
declare variable WBASEGPSVER varchar(5);
declare variable WREEMBGPSVER varchar(5);
declare variable WVALOR numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WBASEINSS13 numeric(18,6);
declare variable WSALFAM numeric(18,6);
declare variable WSALMATEMP numeric(18,6);
declare variable WREEMB numeric(18,6);
declare variable WVINDEVIDO numeric(18,6);
declare variable WVINDEVIDOSF numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WSALMAT13 numeric(18,6);
declare variable WINSSVER integer;
declare variable WINCIDEPIS DM_BOOLEAN;
declare variable WBASEPIS numeric(18,6);
declare variable WDIFINCIDVER DM_BOOLEAN;
declare variable WSQLDIFINSSGPS varchar(300);
declare variable WCODVER integer;
declare variable WDESCVER varchar(60);
declare variable WGRUPOCLA integer;
BEGIN
  -- Obtem valor de variável de contexto e limpa os valores da tabela temporária da sessão atual
  WSQLDIFINSSGPS = 'SELECT RDB$GET_CONTEXT(''USER_SESSION'', ''W_DIFINCIDVER'') FROM RDB$DATABASE';
  execute statement WSQLDIFINSSGPS into :WDIFINCIDVER;

  wsql = 'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVC13, FN.BDCODVER, VER.BDDESCVER, VER.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, VERREF.BDPISVER ';
  wsql = wsql||'from (select * from VRHF_EMP_TVERBAC13 ';
  wwhere  = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wwhere = wwhere||prcodemp;
     END

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (prref IS NOT NULL AND prref <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       IF (pranotodo = 1) THEN
          wwhere = wwhere||'BDREF13 >= '||SUBSTRING(:prref FROM 1 FOR 4)||'01 and BDREF13 <= '||prref||' ';
       ELSE
          wwhere = wwhere||'BDREF13 = '||prref||' ';
     END


  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  WSQL = WSQL||wwhere;

  WSQL = WSQL || ') FN ';
  WSQL = WSQL || 'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) ';
  WSQL = WSQL || 'join VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER and VERREF.BDREFVER = (SELECT FIRST 1 BDREFVER FROM VRH_BASE_TVERBAS_REF WHERE BDCODVER = VERREF.BDCODVER AND BDREFVER <= ' || PRREF || ' ORDER BY BDCODVER DESC, BDREFVER DESC)) ';
  WSQL = WSQL || 'order by FN.BDCODEMP,FN.BDCODCOL';

  wempatu     = 0;
  wcolatu     = 0;
  wsalfam     = 0;
  winss13     = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wvindevido = 0;
  wvindevidosf = 0;
  wbasepis     = 0;
  WCODVER = 0;
  WDESCVER = '';



  EXECUTE PROCEDURE sp_seta_competencia(prref);
  BDSEMBASEGPS = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wvalor, :wcodver, :wdescver, :wclaver, :wtipocodver, :winssver, :wbasegpsver, :wreembgpsver, :wincidepis DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    -- verificar classe no colaborador
    wgrupocla = 0;
    SELECT CLA.BDGRUPOCLA
    FROM VW_VRH_EMP_TCOLCON_VINC VINC
    LEFT OUTER JOIN VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
    WHERE (VINC.BDCODEMP = :wempatu)
      AND (VINC.BDCODCOL = :wcolatu)
      AND (VINC.BDREFCOL <= :prref)
    ORDER BY BDCODEMP DESC, BDCODCOL DESC, BDREFCOL DESC
    INTO :wgrupocla;

    /*
      Retorna bases de INSS
    */


    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol)) THEN
       BEGIN
         BDCODEMP       = wempatu;
         BDCODCOL       = wcolatu;
         BDREF13        = prref;
         BDVALORINSS13  = winss13;
         BDSALFAM13     = wsalfam;
         BDVALINDEVIDO = wvindevido;
         BDVALINDEVIDOSF = wvindevidosf;
         BDBASEINSS13    = wbaseinss13;
         bdbasepis       = wbasepis;

         -- Sol. 146074 Jarde 06/08/2021
         if (BDBASEINSS13 < 0) then
            BDBASEINSS13 = 0;

         wsalmat13 = 0;
         SELECT SUM(BDSALMATEMP13) FROM VRHF_EMP_T13SAL WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu AND bdref13 = :prref
         INTO :wsalmat13;

         IF (wsalmat13 <> 0 AND wsalmat13 IS NOT NULL) THEN
           BEGIN
             BDSALMATEMP13   = wsalmatemp - wsalmat13;
           END
         ELSE
           BEGIN
             BDSALMATEMP13   = wsalmatemp;
           END

         wpercrat = 0;
         SELECT BDPERCRATCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BDBRATAPO13   = BDBASEINSS13;
         ELSE
            BDBRATAPO13   = 0;

         SUSPEND;

         winss13     = 0;
         wbaseinss13 = 0;
         wsalfam     = 0;
         wsalmatemp  = 0;
         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wvindevido = 0;
         wvindevidosf = 0;
         wbasepis     = 0;
       END

    -- Verifica diferença de incidência de PIS e Base GPS
    if (coalesce(UPPER(WDIFINCIDVER), 'FALSE') = 'TRUE') then
       begin
         if ((wbasegpsver <> wincidepis) and (WGRUPOCLA not in (2, 3))) then
            begin
              WSQLDIFINSSGPS = 'update or insert into VRHF_TINFO_TEMP_DIFINCIDVER (BDSESSAO, BDCODEMP, BDCODVER, BDDESCVER) '||
                               'values ('||current_connection||', '||wcodemp||', '||wcodver||', '''||wdescver||''') matching (BDSESSAO, BDCODEMP, BDCODVER)';
              execute statement WSQLDIFINSSGPS;
            end
       end

            -- Valor base PIS
    if (coalesce(UPPER(wincidepis), 'FALSE') = 'TRUE') then
       begin
          IF (wtipocodver = 0) THEN  -- Provento
             wbasepis = wbasepis + wvalor;
          ELSE
          IF (wtipocodver = 1) THEN  -- Desconto
             wbasepis = wbasepis - wvalor;
       end

    -- INSS 13o. rescisão descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.4') THEN
       winss13 = winss13 + wvalor;

    -- Base de INSS 13o. salário descontado na rescisão
    if (UPPER(wbasegpsver) = 'TRUE') then
       begin
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       end

    -- Valor de salário família
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '9.050') THEN
       wsalfam = wsalfam + wvalor;

    -- Valor indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.1.2') THEN
       wvindevido = wvindevido + wvalor;

    -- Base de salário maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005'))) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END
  END

  IF ((wempatu <> 0) AND (wcolatu <> 0)) THEN
     BEGIN
       BDCODEMP       = wempatu;
       BDCODCOL       = wcolatu;
       BDREF13        = prref;
       BDVALORINSS13  = winss13;
       BDSALFAM13     = wsalfam;
       BDVALINDEVIDO = wvindevido;
       BDVALINDEVIDOSF = wvindevidosf;
       BDBASEINSS13    = wbaseinss13;
       bdbasepis       = wbasepis;

       -- Sol. 146074 Jarde 06/08/2021
       if (BDBASEINSS13 < 0) then
          BDBASEINSS13 = 0;

       wsalmat13 = 0;
       SELECT SUM(BDSALMATEMP13) FROM VRHF_EMP_T13SAL WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu AND bdref13 = :prref
       INTO :wsalmat13;

       IF (wsalmat13 <> 0 AND wsalmat13 IS NOT NULL) THEN
         BEGIN
           BDSALMATEMP13   = wsalmatemp - wsalmat13;
         END
       ELSE
         BEGIN
           BDSALMATEMP13   = wsalmatemp;
         END

       wpercrat = 0;
       SELECT BDPERCRATCOL FROM VW_VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wpercrat;

       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BDBRATAPO13   = BDBASEINSS13;
       ELSE
          BDBRATAPO13   = 0;
       SUSPEND;
     END
END^

/* Restore proc. body: SP_VRHF_DADOS_INSS_FC */
create or alter procedure SP_VRHF_DADOS_INSS_FC (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRREFPAG integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS smallint = 0,
    PRREFFIM integer = 0,
    PRCOMPLEESOCIAL integer = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFCOMP integer,
    BDCODCENTROS integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDCODTIPOFC integer,
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEPIS numeric(18,6),
    BDBASEPIS13 numeric(18,6))
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(30000);
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WCLAVER varchar(20);
declare variable WTIPOCODVER integer;
declare variable WINSSVER integer;
declare variable WBASEGPSVER varchar(5);
declare variable WREEMBGPSVER varchar(5);
declare variable WVALOR numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WINSSFE numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WBASEINSS numeric(18,6);
declare variable WBASEINSSFE numeric(18,6);
declare variable WBASEINSS13 numeric(18,6);
declare variable WSALFAM numeric(18,6);
declare variable WSALMATEMP numeric(18,6);
declare variable WBASEMV numeric(18,6);
declare variable WBASEMV13 numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WCODTIPOFC integer;
declare variable WCODFCATU integer;
declare variable WBINSSAP numeric(18,6);
declare variable WBINSS13AP numeric(18,6);
declare variable WINSSAP numeric(18,6);
declare variable WINSS13AP numeric(18,6);
declare variable WAINSSAP numeric(18,6);
declare variable WAINSS13AP numeric(18,6);
declare variable WABASEMV numeric(18,6);
declare variable WABASEMV13 numeric(18,6);
declare variable WEMPAP integer;
declare variable WSOMAAP numeric(18,6);
declare variable WCODSIND integer;
declare variable WLIMSIND integer;
declare variable WLIMEMP integer;
declare variable WREEMB numeric(18,6);
declare variable WVINDEVIDO numeric(18,6);
declare variable WVINDEVIDOSF numeric(18,6);
declare variable WBAVPREV numeric(18,6);
declare variable WTEMVALOR smallint;
declare variable WREFFCA integer;
declare variable WREFFC integer;
declare variable WGRUPOCLA integer;
declare variable WVERDEAMARELO DM_BOOLEAN;
declare variable WCATEGORIAESOC integer;
declare variable WSALMIN numeric(15,2);
declare variable WCONTRCOL integer;
declare variable WINCIDEPIS DM_BOOLEAN;
declare variable WBASEPIS numeric(18,6);
declare variable WBASEPIS13 numeric(18,6);
declare variable WREFFN integer;
declare variable WREFFNATU integer;
declare variable WDIFINCIDVER DM_BOOLEAN;
declare variable WSQLDIFINSSGPS varchar(300);
declare variable WCODVER integer;
declare variable WDESCVER varchar(60);
BEGIN
  -- Obtem valor de variável de contexto e limpa os valores da tabela temporária da sessão atual
  WSQLDIFINSSGPS = 'SELECT RDB$GET_CONTEXT(''USER_SESSION'', ''W_DIFINCIDVER'') FROM RDB$DATABASE';
  execute statement WSQLDIFINSSGPS into :WDIFINCIDVER;

  wsql = 'select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFFN, FC.BDREFFC, FC.BDVALVFC, FC.BDCODVER, VERREF.BDDESCVER, FC.BDBINSSMVFC, FC.BDBINSSMV13FC, FC.BDINSSAPFC, FC.BDINSS13APFC, VER.BDCLAVER, VERREF.BDTIPOCODVER, '||
         'VERREF.BDINSSVER, VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, FC.BDCODTIPOFC, ' ||
         'case when COALESCE(FGTSGPS.BDCATEGORIACOL, 0) = 7 and COALESCE(FGTSGPS.BDCATEGORIAESOCIAL, 0) in (107,108) then ''TRUE'' else ''FALSE'' end BDVERDEAMARELO, VERREF.BDPISVER from (';
/*  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFC, FN.BDVALVFC, FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, FOLN.BDINSS13APFC, FOLN.BDCODTIPOFC, cast(null as INTEGER) BDCODCONTTI, FN.BDCODVER ';*/
  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFN, FN.BDREFFC, FN.BDVALVFC, FN.BDBINSSMVFC, FN.BDBINSSMV13FC, FN.BDINSSAPFC, FN.BDINSS13APFC, FN.BDCODTIPOFC, cast(null as INTEGER) BDCODCONTTI, FN.BDCODVER ';

  if (coalesce(prfiliais, 0) = 1 and coalesce(prcodemp, '') <> '') then
     begin
       wsql = wsql||
              'from (select BDCODEMP from TEMPRESAS where (('||prcodemp||') or ('||REPLACE(UPPER(prcodemp), 'BDCODEMP', 'BDCODMATRIZ')||'))) EMP '||
              'join (select VERN.BDCODEMP,VERN.BDCODCOL,VERN.BDREFFN,VERN.BDREFFC,VERN.BDCODVER,VERN.BDVALVFC, '||
              '      FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, FOLN.BDINSS13APFC, FOLN.BDCODTIPOFC '||
              '      from VRHF_EMP_TVERBAFC VERN '||
              '      join VRHF_EMP_TFOLHACOMP FOLN on (FOLN.BDCODEMP = VERN.BDCODEMP and FOLN.BDCODCOL = VERN.BDCODCOL and FOLN.BDREFFN = VERN.BDREFFN and FOLN.BDREFFC = VERN.BDREFFC) '||     /* 158041 Leonardo Schwab 05/06/2023 */
              '      left outer join VRH_EMP_TACCONV ACCONV ON (FOLN.BDCODEMP = ACCONV.BDCODEMP AND FOLN.BDCODACCONV = ACCONV.BDCODACCONV)';                          /* 158041 Leonardo Schwab 05/06/2023 */

       wwhere = '';

       IF ((coalesce(prref, 0) <> 0) and (coalesce(prreffim, 0) <> 0)) THEN
          wwhere = wwhere||'VERN.BDREFFN >= '||prref||' AND VERN.BDREFFN <= '||prreffim||' ';
       ELSE 
       IF (coalesce(prref, 0) <> 0) THEN
          wwhere = wwhere||'VERN.BDREFFN = '||prref||' ';

       IF (coalesce(prrefpag, 0) <> 0) THEN
          begin
            if (wwhere <> '') then
               wwhere = wwhere||' and ';
            /*wwhere = wwhere||'VERN.BDREFFC >= '||prrefpag||'01 and VERN.BDREFFC <= '||prrefpag||'31 ';*/

            if (PRCOMPLEESOCIAL = 1) THEN
                wwhere = wwhere||'((FOLN.BDCODTIPOFC <> 3 AND VERN.BDREFFN = '||prrefpag||') OR '||
                                 ' (FOLN.BDCODACCONV IS NOT NULL AND FOLN.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefpag||'))';
            ELSE
                wwhere = wwhere||'((FOLN.BDCODTIPOFC <> 3 AND VERN.BDREFFC >= '||prrefpag||'01 and VERN.BDREFFC <= '||prrefpag||'31) OR '||
                                 ' (FOLN.BDCODACCONV IS NOT NULL AND FOLN.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefpag||'))';
          end

       if (wwhere <> '') then
          wsql = wsql||' where '||wwhere;

       wsql = wsql||') FN on (FN.BDCODEMP = EMP.BDCODEMP) ';
     end
  else
     begin
       wsql = wsql||'from (select VERN.BDCODEMP,VERN.BDCODCOL,VERN.BDREFFN,VERN.BDREFFC,VERN.BDCODVER,VERN.BDVALVFC, '||
                    '      FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, FOLN.BDINSS13APFC, FOLN.BDCODTIPOFC '||
                    '      from VRHF_EMP_TVERBAFC VERN '||
                    '      join VRHF_EMP_TFOLHACOMP FOLN on (FOLN.BDCODEMP = VERN.BDCODEMP and FOLN.BDCODCOL = VERN.BDCODCOL and FOLN.BDREFFN = VERN.BDREFFN and FOLN.BDREFFC = VERN.BDREFFC) '||   /* 158041 Leonardo Schwab 05/06/2023 */
                    '      left outer join VRH_EMP_TACCONV ACCONV ON (FOLN.BDCODEMP = ACCONV.BDCODEMP AND FOLN.BDCODACCONV = ACCONV.BDCODACCONV)';                          /* 158041 Leonardo Schwab 05/06/2023 */
       wwhere  = '';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          BEGIN
            wwhere = wwhere||'VERN.'||prcodemp;
          END
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'VERN.'||prcodcol;
     END
     
     IF ((coalesce(prref, 0) <> 0) and (coalesce(prreffim, 0) <> 0)) THEN
        BEGIN
          IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'VERN.BDREFFN >= '||prref||' AND VERN.BDREFFN <= '||prreffim||' ';
        END
     ELSE
       IF (prref IS NOT NULL AND prref <> 0) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'VERN.BDREFFN = '||prref||' ';
          END
     
       IF (prrefpag IS NOT NULL AND prrefpag <> 0) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
/*            wwhere = wwhere||'VERN.BDREFFC >= '||prrefpag||'01 and VERN.BDREFFC <= '||prrefpag||'31 ';*/
            if (PRCOMPLEESOCIAL = 1) then
                wwhere = wwhere||'((FOLN.BDCODTIPOFC <> 3 AND VERN.BDREFFN = '||prrefpag||') OR '||
                                 ' (FOLN.BDCODACCONV IS NOT NULL AND FOLN.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefpag||'))';
            ELSE
                wwhere = wwhere||'((FOLN.BDCODTIPOFC <> 3 AND VERN.BDREFFC >= '||prrefpag||'01 and VERN.BDREFFC <= '||prrefpag||'31) OR '||
                                 ' (FOLN.BDCODACCONV IS NOT NULL AND FOLN.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefpag||'))';
          END
     
       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;
     
       wsql = wsql||wwhere;
     
       wsql = wsql||') FN ';
     end

/*  wsql = wsql||'join VRHF_EMP_TFOLHACOMP FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFFN = FN.BDREFFN and FOLN.BDREFFC = FN.BDREFFC) ';*/  /* 158041 Leonardo Schwab 05/06/2023 MOVIDO */

  wsql = wsql||' union all ';

/*  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFC, FN.BDVALVFC, FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, FOLN.BDINSS13APFC, FOLN.BDCODTIPOFC, FN.BDCODCONTTI, FN.BDCODVER ';*/
  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFN, FN.BDREFFC, FN.BDVALVFC, FN.BDBINSSMVFC, FN.BDBINSSMV13FC, FN.BDINSSAPFC, FN.BDINSS13APFC, FN.BDCODTIPOFC, FN.BDCODCONTTI, FN.BDCODVER ';

  if (coalesce(prfiliais, 0) = 1 and coalesce(prcodemp, '') <> '') then
     begin
       wsql = wsql||
              'from (select BDCODEMP from TEMPRESAS where (('||prcodemp||') or ('||REPLACE(UPPER(prcodemp), 'BDCODEMP', 'BDCODMATRIZ')||'))) EMP '||
              'join (select VERN.BDCODEMP,VERN.BDCODCOL,VERN.BDCODCONTTI,VERN.BDREFFN,VERN.BDREFFC,VERN.BDCODVER,VERN.BDVALVFC, '||
              '      FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, FOLN.BDINSS13APFC, FOLN.BDCODTIPOFC '||
              '      from VRHF_EMP_TVERBAFCINT VERN'||
              '      join VRHF_EMP_TFOLHACOMPINT FOLN on (FOLN.BDCODEMP = VERN.BDCODEMP and FOLN.BDCODCOL = VERN.BDCODCOL and FOLN.BDREFFN = VERN.BDREFFN and FOLN.BDREFFC = VERN.BDREFFC and FOLN.BDCODCONTTI = VERN.BDCODCONTTI) '||    /* 158041 Leonardo Schwab 05/06/2023 MOVIDO */
              '      left outer join VRH_EMP_TACCONV ACCONV ON (FOLN.BDCODEMP = ACCONV.BDCODEMP AND FOLN.BDCODACCONV = ACCONV.BDCODACCONV)';                          /* 158041 Leonardo Schwab 05/06/2023 */

       wwhere = '';

       IF ((coalesce(prref, 0) <> 0) and (coalesce(prreffim, 0) <> 0)) THEN
          wwhere = wwhere||'VERN.BDREFFN >= '||prref||' AND VERN.BDREFFN <= '||prreffim||' ';
       ELSE
       IF (coalesce(prref, 0) <> 0) THEN
          wwhere = wwhere||'VERN.BDREFFN = '||prref||' ';

       IF (coalesce(prrefpag, 0) <> 0) THEN
          begin
            if (wwhere <> '') then
               wwhere = wwhere||' and ';
            /*wwhere = wwhere||'VERN.BDREFFC >= '||prrefpag||'01 and VERN.BDREFFC <= '||prrefpag||'31 ';*/

            if (PRCOMPLEESOCIAL = 1) then
                wwhere = wwhere||'((FOLN.BDCODTIPOFC <> 3 AND VERN.BDREFFN = '||prrefpag||') OR '||
                                 ' (FOLN.BDCODACCONV IS NOT NULL AND FOLN.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefpag||'))';
            ELSE
                wwhere = wwhere||'((FOLN.BDCODTIPOFC <> 3 AND VERN.BDREFFC >= '||prrefpag||'01 and VERN.BDREFFC <= '||prrefpag||'31) OR '||
                                 ' (FOLN.BDCODACCONV IS NOT NULL AND FOLN.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefpag||'))';
          end

       if (wwhere <> '') then
          wsql = wsql||' where '||wwhere;

       wsql = wsql||') FN on (FN.BDCODEMP = EMP.BDCODEMP) ';
     end
  else
     begin
       wsql = wsql||'from (select VERN.BDCODEMP,VERN.BDCODCOL,VERN.BDREFFN,VERN.BDREFFC,VERN.BDCODVER,VERN.BDVALVFC,VERN.BDCODCONTTI, '||
                    '      FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, FOLN.BDINSS13APFC, FOLN.BDCODTIPOFC '||
                    '      from VRHF_EMP_TVERBAFCINT VERN '||
                    '      join VRHF_EMP_TFOLHACOMPINT FOLN on (FOLN.BDCODEMP = VERN.BDCODEMP and FOLN.BDCODCOL = VERN.BDCODCOL and FOLN.BDREFFN = VERN.BDREFFN and FOLN.BDREFFC = VERN.BDREFFC and FOLN.BDCODCONTTI = VERN.BDCODCONTTI) '||   /* 158041 Leonardo Schwab 05/06/2023 MOVIDO */
                    '      left outer join VRH_EMP_TACCONV ACCONV ON (FOLN.BDCODEMP = ACCONV.BDCODEMP AND FOLN.BDCODACCONV = ACCONV.BDCODACCONV)';                          /* 158041 Leonardo Schwab 05/06/2023 */
       wwhere  = '';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          BEGIN
            wwhere = wwhere||'VERN.'||prcodemp;
          END
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'VERN.'||prcodcol;
          END
     
       IF ((coalesce(prref, 0) <> 0) and (coalesce(prreffim, 0) <> 0)) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'VERN.BDREFFN >= '||prref||' AND VERN.BDREFFN <= '||prreffim||' ';
          END
       ELSE
       IF (prref IS NOT NULL AND prref <> 0) THEN
     BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'VERN.BDREFFN = '||prref||' ';
     END
     
       IF (prrefpag IS NOT NULL AND prrefpag <> 0) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            /*wwhere = wwhere||'BDREFFC >= '||prrefpag||'01 and BDREFFC <= '||prrefpag||'31 ';*/
            if (PRCOMPLEESOCIAL = 1) then
                wwhere = wwhere||'((FOLN.BDCODTIPOFC <> 3 AND VERN.BDREFFN = '||prrefpag||') OR '||
                                 ' (FOLN.BDCODACCONV IS NOT NULL AND FOLN.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefpag||'))';
            ELSE
                wwhere = wwhere||'((FOLN.BDCODTIPOFC <> 3 AND VERN.BDREFFC >= '||prrefpag||'01 and VERN.BDREFFC <= '||prrefpag||'31) OR '||
                                 ' (FOLN.BDCODACCONV IS NOT NULL AND FOLN.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefpag||'))';
          END
     
       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;
     
       wsql = wsql||wwhere;
     
       wsql = wsql||') FN ';
     end

/*  wsql = wsql||'join VRHF_EMP_TFOLHACOMPINT FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFFN = FN.BDREFFN and FOLN.BDREFFC = FN.BDREFFC and FOLN.BDCODCONTTI = FN.BDCODCONTTI) ';*/  /* 158041 Leonardo Schwab 05/06/2023 MOVIDO */

  wsql = wsql||') FC ';
  wsql = wsql||'left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FC.BDCODVER) ';
  wsql = wsql||'left outer join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FC.BDCODVER) ';
  wsql = wsql||'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS FGTSGPS on (FGTSGPS.BDCODEMP = FC.BDCODEMP and FGTSGPS.BDCODCOL = FC.BDCODCOL) ';
  wsql = wsql||'where VER.BDCODVER is not null and VERREF.BDCODVER is not null ';
  wsql = wsql||'order by FC.BDCODEMP,FC.BDCODCOL,FC.BDREFFC,FC.BDREFFN,FC.BDCODCONTTI ';

  wempatu     = 0;
  wcolatu     = 0;
  wsalfam     = 0;
  winss       = 0;
  winssfe     = 0;
  winss13     = 0;
  wbaseinss   = 0;
  wbaseinssfe = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wbasemv     = 0;
  wbasemv13   = 0;
  wbinssap    = 0;
  wbinss13ap  = 0;
  wainssap    = 0;
  wainss13ap  = 0;
  wabasemv    = 0;
  wabasemv13  = 0;
  wempap      = 0;
  wsomaap     = 0;
  wreemb      = 0;
  wvindevido  = 0;
  wvindevidosf = 0;
  wbavprev     = 0;
  wtemvalor   = 0;
  wreffca = 0;
  wreffca = 0;
  wbasepis = 0;
  wbasepis13 = 0;
  wreffnatu = 0;
  wcodver = 0;
  wdescver = '';

  if (prref > 0) then
     EXECUTE PROCEDURE sp_seta_competencia(prref);
  else
  if (prrefpag > 0) then
     EXECUTE PROCEDURE sp_seta_competencia(prrefpag);

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wreffn, :wreffc, :wvalor, :wcodver, :wdescver, :wbasemv, :wbasemv13, :winssap, :winss13ap, :wclaver, :wtipocodver, :winssver, :wbasegpsver,
                                  :wreembgpsver, :wcodtipofc, :wverdeamarelo, :wincidepis DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wreffca = 0) THEN
       wreffca = wreffc;

    IF (wreffnatu = 0) THEN
       wreffnatu = wreffn;
    /*
      Retorna bases de INSS
    */
    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wreffca <> wreffc) OR (wreffnatu <> wreffn)) THEN
       BEGIN
         wcodsind = NULL;
         wlimemp = NULL;
         wlimsind = NULL;
         SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
         IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
            BEGIN
              SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
            END

         IF (wlimsind IS NULL) THEN
            wlimsind = 0;             -- não possui liminar

         IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
            SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;

         IF (wlimemp IS NULL) THEN
            wlimemp = 0;    -- não possui liminar

         BDGPSSEFIP     = 0;
         BDCODEMP       = wempatu;
         BDCODCOL       = wcolatu;
         BDREFFN        = wreffnatu;
         BDREFCOMP      = CAST((SUBSTRING(prrefpag FROM 1 FOR 6)) AS INTEGER);
         BDCODTIPOFC    = wcodfcatu;
         BDCODCENTROS   = NULL;
         BDCODTPCC      = NULL;
         BDINSSFN       = winss;
         BDINSSFEFOLFN  = winssfe;
         BDINSS13FN     = winss13;
         BDBINSSFEFOLFN = wbaseinssfe;
         bdbasepis      = wbasepis;
         bdbasepis13    = wbasepis13;
    
         if (bdbasepis < 0) then
           bdbasepis = 0;
         if (bdbasepis13 < 0) then
           bdbasepis13 = 0;



         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSSFN = wbinssap;
         ELSE
            BDBINSSFN = wbaseinss;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13FN = wbaseinss13 - wbinss13ap;
         ELSE
            BDBINSS13FN = wbaseinss13;

         if (BDBINSS13FN < 0) then
            BDBINSS13FN = 0;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13INDFN = 0;
         ELSE
            BDBINSS13INDFN = wbinss13ap;

         IF (bdbinssfn < 0) THEN
            bdbinssfn = 0;

         wpercrat = 0;
         wcontrcol = null;
         wcategoriaesoc = null;
         SELECT first 1 BDPERCRATCOL, BDCATEGORIAESOCIAL, BDCONTRCOL
         FROM VRHF_EMP_TCOLCON_FGTSGPS
         WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :BDREFCOMP
         order by BDREFCOL DESC
         INTO :wpercrat, :wcategoriaesoc, :wcontrcol;
         wpercrat = coalesce(wpercrat, 0);
         wcategoriaesoc = coalesce(wcategoriaesoc, 0);
         wcontrcol = coalesce(wcontrcol, 0);

         -- 136305 - Raphael Teodoro - 21/08/2020
         wgrupocla = 0;
         SELECT CLA.BDGRUPOCLA
         FROM VW_VRH_EMP_TCOLCON_VINC VINC
         LEFT OUTER JOIN VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
         WHERE (VINC.BDCODEMP = :wempatu)
           AND (VINC.BDCODCOL = :wcolatu)
           AND (VINC.BDREFCOL <= :wreffnatu)
         ORDER BY BDCODEMP DESC, BDCODCOL DESC, BDREFCOL DESC
         INTO :wgrupocla;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BEGIN
              BDBRATAPOFN   = BDBINSSFN;
              BDBRATAPOFEFN = BDBINSSFEFOLFN;
              BDBRATAPO13FN = BDBINSS13FN;
            END
         ELSE
            BEGIN
              BDBRATAPOFN   = 0;
              BDBRATAPOFEFN = 0;
              BDBRATAPO13FN = 0;
            END

         BDSALFAMFN     = wsalfam;
         BDSALMATEMPFN  = wsalmatemp;
         BDBINSSMVFN    = wabasemv;
         BDBINSSMV13FN  = wabasemv13;
         BDBINSSAPFN    = wbinssap;
         BDBINSS13APFN  = wbinss13ap;
         BDINSSAPFN     = wainssap;
         BDINSS13APFN   = wainss13ap;
         BDVALREEMBOLSO = wreemb;
         BDVALINDEVIDO  = wvindevido;
         BDVALINDEVIDOSF = wvindevidosf;
         BDBAVPREV       = 0;

         if ((wcontrcol = 0) and
             (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
            BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
         else
            BDBASERAT = 0;

         BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
         BDBASEINSS13 = BDBINSS13FN;

         if (wcategoriaesoc IN (107, 108)) then
            begin
              BDBINSSFN = BDBINSSFN + BDBINSS13FN;
              BDBINSS13FN = 0;

              select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :wreffnatu order by bdrefsm DESC INTO :WSALMIN;
              if (BDBINSSFN > WSALMIN * 1.5) then
                 begin
                   BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                 end
              else
                 begin
                   BDBINSSFN = 0;
                 end
            end

         SUSPEND;

         IF (prrefpag >= 200903 AND prGPSSEFIP = 1 AND wsomaap <> 0) THEN
            BEGIN
              BDGPSSEFIP     = 1;
              BDCODEMP       = wempatu;
              BDCODCOL       = wcolatu;
              BDREFFN        = wreffnatu;
              BDREFCOMP      = CAST((SUBSTRING(prrefpag FROM 1 FOR 6)) AS INTEGER);
              BDCODTIPOFC    = wcodfcatu;
              BDCODCENTROS   = NULL;
              BDCODTPCC      = NULL;
              BDBAVPREV      = wbavprev;

              IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
                 BEGIN
                   IF (wbinssap < 0) THEN
                     wbinssap = 0;
                   BDINSSFN  = wainssap;
                   BDBINSSFN = wbinssap;
                 END
              ELSE
                 BEGIN
                   BDINSSFN  = winss;
                   BDBINSSFN = wbaseinss;
                 END

              BDINSSFEFOLFN  = winssfe;
              BDINSS13FN     = winss13;
              BDBINSSFEFOLFN = wbaseinssfe;
              BDBINSS13FN    = wbaseinss13;
              BDBINSS13INDFN = wbinss13ap;

              IF (bdbinssfn < 0) THEN
                 bdbinssfn = 0;

              IF (BDBINSS13FN < 0) THEN
                 BDBINSS13FN = 0;

              IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
                 BEGIN
                   BDBRATAPOFN   = BDBINSSFN;
                   BDBRATAPOFEFN = BDBINSSFEFOLFN;
                   BDBRATAPO13FN = BDBINSS13FN;
                 END
              ELSE
                 BEGIN
                   BDBRATAPOFN   = 0;
                   BDBRATAPOFEFN = 0;
                   BDBRATAPO13FN = 0;
                 END
     
              BDSALFAMFN     = wsalfam;
              BDSALMATEMPFN  = wsalmatemp;
              BDBINSSMVFN    = wabasemv;
              BDBINSSMV13FN  = wabasemv13;
              BDBINSSAPFN    = wbinssap;
              BDBINSS13APFN  = wbinss13ap;
              BDINSSAPFN     = wainssap;
              BDINSS13APFN   = wainss13ap;
              BDVALREEMBOLSO = wreemb;
              BDVALINDEVIDO  = wvindevido;
              BDVALINDEVIDOSF = wvindevidosf;

              if ((wcontrcol = 0) and
                  (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
                 BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
              else
                 BDBASERAT = 0;

              BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
              BDBASEINSS13 = BDBINSS13FN;

              if (wcategoriaesoc IN (107, 108)) then
                 begin
                   BDBINSSFN = BDBINSSFN + BDBINSS13FN;
                   BDBINSS13FN = 0;

                   select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :wreffnatu order by bdrefsm DESC INTO :WSALMIN;
                   if (BDBINSSFN > WSALMIN * 1.5) then
                      begin
                        BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                      end
                   else
                      begin
                        BDBINSSFN = 0;
                      end
                 end

              SUSPEND;
            END

         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wreffca     = wreffc;
         wreffnatu   = wreffn;
         wsalfam     = 0;
         winss       = 0;
         winssfe     = 0;
         winss13     = 0;
         wbaseinss   = 0;
         wbaseinssfe = 0;
         wbaseinss13 = 0;
         wsalmatemp  = 0;
         wabasemv    = 0;
         wabasemv13  = 0;
         wbinssap    = 0;
         wbinss13ap  = 0;
         wainss13ap  = 0;
         wainssap    = 0;
         wreemb      = 0;
         wvindevido  = 0;
         wvindevidosf = 0;
         wbavprev     = 0;
         wtemvalor = 0;
         wbasepis = 0;
         wbasepis13 = 0;
       END

    wcodfcatu  = wcodtipofc;
    wainss13ap = winss13ap;
    wainssap   = winssap;
    wabasemv   = wbasemv;
    wabasemv13 = wbasemv13;

    IF (prrefpag >= 200903 AND prgpssefip = 1 AND wempap <> wcodemp) THEN
       BEGIN
         wsomaap = 0;
         SELECT SUM(BDSOMA) FROM (
           SELECT X.bdvalvfc BDSOMA
           FROM vrhf_emp_tverbafc X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :wreffn AND X.bdrefcomp = :prrefpag and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvfc BDSOMA
           FROM vrhf_emp_tverbafctomador X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :wreffn AND X.bdrefcomp = :prrefpag and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvfn BDSOMA
           FROM vrhf_emp_tverbafn X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :wreffn and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvft BDSOMA
           FROM vrhf_emp_tverbatomador X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :wreffn and Y.BDCODVER is not null
         )
         INTO :wsomaap;
         wempap = wcodemp;
       END

    -- INSS folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.0') THEN
       winss = winss + wvalor;

    -- INSS férias demonstradas na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.2') THEN
       winssfe = winssfe + wvalor;

    -- INSS 13o. complemento de 13º na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.6') THEN
       winss13 = winss13 + wvalor;

    -- INSS 13o. rescisão descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;

    IF (wverdeamarelo = 'TRUE') THEN
      BEGIN
      -- INSS 13o. descontado na folha normal
        IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.3') THEN
           winss13 = winss13 + wvalor;
      END
    -- Base de INSS folha normal
    IF ((winssver = 1)) THEN
       BEGIN
         IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
            BEGIN
              IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
       END
    ELSE
    IF ((winssver = 0)) THEN  --não incide
       BEGIN
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
         ELSE
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss13 = wbaseinss13 + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss13 = wbaseinss13 - wvalor;
            END
       END

    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 2) THEN
       BEGIN

         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END
    ELSE
    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 1 AND SUBSTRING(wclaver FROM 1 FOR 5) >= '0.100' AND SUBSTRING(wclaver FROM 1 FOR 5) < '0.200') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END

    -- Base de INSS 13o. salário descontado na rescisão
    IF ((winssver = 3)) THEN
       BEGIN
         IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
         IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       END

    -- Verifica diferença de incidência de PIS e Base GPS
    if (coalesce(UPPER(WDIFINCIDVER), 'FALSE') = 'TRUE') then
       begin
         if ((wbasegpsver <> wincidepis) and (WGRUPOCLA not in (2, 3))) then
            begin
              WSQLDIFINSSGPS = 'update or insert into VRHF_TINFO_TEMP_DIFINCIDVER (BDSESSAO, BDCODEMP, BDCODVER, BDDESCVER) '||
                               'values ('||current_connection||', '||wcodemp||', '||wcodver||', '''||wdescver||''') matching (BDSESSAO, BDCODEMP, BDCODVER)';
              execute statement WSQLDIFINSSGPS;
            end
       end

    -- Valor base PIS
    if (coalesce(UPPER(wincidepis), 'FALSE') = 'TRUE') then
      BEGIN
         IF (winssver = 3) THEN
           BEGIN
             IF (wtipocodver = 0) THEN  -- Provento
                wbasepis13 = wbasepis13 + wvalor;
             ELSE
               IF (wtipocodver = 1) THEN  -- Desconto
                  wbasepis13 = wbasepis13 - wvalor;
           END
         ELSE
           BEGIN
             IF (wtipocodver = 0) THEN  -- Provento
                wbasepis = wbasepis + wvalor;
             ELSE
               IF (wtipocodver = 1) THEN  -- Desconto
                  wbasepis = wbasepis - wvalor;
           END
      END


    -- Valor de salário família
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '9.050') THEN
       wsalfam = wsalfam + wvalor;

    -- Valor indevido na GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.2') THEN
       wvindevido = wvindevido + wvalor;

    -- Valor SF indevido na GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.0') THEN
       wvindevidosf = wvindevidosf + wvalor;

    -- Base de salário maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005') OR
         (SUBSTRING(wclaver FROM 1 FOR 7) = '7.061.2') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '0.610') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.070')OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.710') )) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END

    -- Base de INSS sem o aviso prévio indenizado
    IF (SUBSTRING(wclaver FROM 1 FOR 7) <> '7.001.3') THEN
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
              ELSE
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinss13ap = wbinss13ap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinss13ap = wbinss13ap - wvalor;

                   wtemvalor = 1;
                 END
            END
       END
    ELSE
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 7, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
       END

    -- INSS sobre o aviso prévio indenizado do 13º salário
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '7.060') THEN
       BEGIN
         IF (winssver = 3) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbinss13ap = wbinss13ap + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbinss13ap = wbinss13ap - wvalor;
            END
       END
  END


  IF ((wempatu <> 0) AND (wcolatu <> 0) AND (wreffca <> 0) AND (wreffnatu <> 0)) THEN
     BEGIN
       wcodsind = NULL;
       wlimemp = NULL;
       wlimsind = NULL;
       SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
       IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
          BEGIN
            SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
          END

       IF (wlimsind IS NULL) THEN
          wlimsind = 0;             -- não possui liminar

       IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
          SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;

       IF (wlimemp IS NULL) THEN
          wlimemp = 0;    -- não possui liminar

       BDGPSSEFIP = 0;
       BDCODEMP       = wempatu;
       BDCODCOL       = wcolatu;
       BDREFFN        = wreffnatu;
       BDREFCOMP      = CAST((SUBSTRING(prrefpag FROM 1 FOR 6)) AS INTEGER);
       BDCODTIPOFC    = wcodfcatu;
       BDCODCENTROS   = NULL;
       BDCODTPCC      = NULL;
       BDINSSFN       = winss;
       BDINSSFEFOLFN  = winssfe;
       BDINSS13FN     = winss13;
       BDBINSSFEFOLFN = wbaseinssfe;
       BDBINSSAPFN    = wbinssap;
       BDBINSS13APFN  = wbinss13ap;
       BDBAVPREV      = 0;
       bdbasepis      = wbasepis;
       bdbasepis13    = wbasepis13;
    
       if (bdbasepis < 0) then
         bdbasepis = 0;
       if (bdbasepis13 < 0) then
         bdbasepis13 = 0;

       IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
          BDBINSSFN = wbinssap;
       ELSE
          BDBINSSFN = wbaseinss;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13FN = wbaseinss13 - wbinss13ap;
       ELSE
          BDBINSS13FN = wbaseinss13;

       IF (BDBINSS13FN < 0) THEN
           BDBINSS13FN = 0;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13INDFN = 0;
       ELSE
          BDBINSS13INDFN = wbinss13ap;

       IF (bdbinssfn < 0) THEN
          bdbinssfn = 0;

       wpercrat = 0;
       wcategoriaesoc = null;
       wcontrcol = null;
       SELECT first 1 BDPERCRATCOL, BDCATEGORIAESOCIAL, BDCONTRCOL
       FROM VRHF_EMP_TCOLCON_FGTSGPS
       WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :BDREFCOMP
       order by BDREFCOL DESC
       INTO :wpercrat, :wcategoriaesoc, :wcontrcol;
       wpercrat = coalesce(wpercrat, 0);
       wcategoriaesoc = coalesce(wcategoriaesoc, 0);
       wcontrcol = coalesce(wcontrcol, 0);

       -- 136305 - Raphael Teodoro - 21/08/2020
       wgrupocla = 0;
       SELECT CLA.BDGRUPOCLA
       FROM VW_VRH_EMP_TCOLCON_VINC VINC
       LEFT OUTER JOIN VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
       WHERE (VINC.BDCODEMP = :wempatu)
         AND (VINC.BDCODCOL = :wcolatu)
         AND (VINC.BDREFCOL <= :wreffnatu)
       ORDER BY BDCODEMP DESC, BDCODCOL DESC, BDREFCOL DESC
       INTO :wgrupocla;

       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BEGIN
            BDBRATAPOFN   = wbaseinss;
            BDBRATAPOFEFN = wbaseinssfe;
            BDBRATAPO13FN = wbaseinss13;
          END
       ELSE
          BEGIN
            BDBRATAPOFN   = 0;
            BDBRATAPOFEFN = 0;
            BDBRATAPO13FN = 0;
          END

       BDSALFAMFN     = wsalfam;
       BDSALMATEMPFN  = wsalmatemp;

       BDBINSSMVFN    = wabasemv;
       BDBINSSMV13FN  = wabasemv13;
       BDINSSAPFN     = wainssap;
       BDINSS13APFN   = wainss13ap;
       BDVALREEMBOLSO = wreemb;
       BDVALINDEVIDO  = wvindevido;
       BDVALINDEVIDOSF = wvindevidosf;

       if ((wcontrcol = 0) and
           (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
          BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
       else
          BDBASERAT = 0;

       BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
       BDBASEINSS13 = BDBINSS13FN;

       if (wcategoriaesoc IN (107, 108)) then
          begin
            BDBINSSFN = BDBINSSFN + BDBINSS13FN;
            BDBINSS13FN = 0;

            select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :wreffnatu order by bdrefsm DESC INTO :WSALMIN;
            if (BDBINSSFN > WSALMIN * 1.5) then
               begin
                 BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
               end
            else
               begin
                 BDBINSSFN = 0;
               end
          end

       SUSPEND;

    IF (prrefpag >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
          BEGIN
            BDGPSSEFIP     = 1;
            BDCODEMP       = wempatu;
            BDCODCOL       = wcolatu;
            BDREFFN        = wreffnatu;
            BDREFCOMP      = CAST((SUBSTRING(prrefpag FROM 1 FOR 6)) AS INTEGER);
            BDCODTIPOFC    = wcodfcatu;
            BDCODCENTROS   = NULL;
            BDCODTPCC      = NULL;
            BDBAVPREV      = wbavprev;

            IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
               BEGIN
                 IF (wbinssap < 0) THEN
                   wbinssap = 0;
                 BDINSSFN  = wainssap;
                 BDBINSSFN = wbinssap;
               END
             ELSE
               BEGIN
                 BDINSSFN  = winss;
                 BDBINSSFN = wbaseinss;
               END

            BDINSSFEFOLFN  = winssfe;
            BDINSS13FN     = winss13;
            BDBINSSFEFOLFN = wbaseinssfe;
            BDBINSS13FN    = wbaseinss13;
            BDBINSSAPFN    = wbinssap;
            BDBINSS13APFN  = wbinss13ap;

            IF (bdbinssfn < 0) THEN
               bdbinssfn = 0;
     
            IF (BDBINSS13FN < 0) THEN
               BDBINSS13FN = 0;

            IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
               BEGIN
                 BDBRATAPOFN   = BDBINSSFN;
                 BDBRATAPOFEFN = BDBINSSFEFOLFN;
                 BDBRATAPO13FN = BDBINSS13FN;
               END
            ELSE
               BEGIN
                 BDBRATAPOFN   = 0;
                 BDBRATAPOFEFN = 0;
                 BDBRATAPO13FN = 0;
               END
     
            BDSALFAMFN     = wsalfam;
            BDSALMATEMPFN  = wsalmatemp;
     
            BDBINSSMVFN    = wabasemv;
            BDBINSSMV13FN  = wabasemv13;
            BDINSSAPFN     = wainssap;
            BDINSS13APFN   = wainss13ap;
            BDVALREEMBOLSO = wreemb;
            BDVALINDEVIDO  = wvindevido;
            BDVALINDEVIDOSF = wvindevidosf;
            BDBINSS13INDFN = wbinss13ap;

            if ((wcontrcol = 0) and
                (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
               BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
            else
               BDBASERAT = 0;

            BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
            BDBASEINSS13 = BDBINSS13FN;

            if (wcategoriaesoc IN (107, 108)) then
               begin
                 BDBINSSFN = BDBINSSFN + BDBINSS13FN;
                 BDBINSS13FN = 0;

                 select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :wreffnatu order by bdrefsm DESC INTO :WSALMIN;
                 if (BDBINSSFN > WSALMIN * 1.5) then
                    begin
                      BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                    end
                 else
                    begin
                      BDBINSSFN = 0;
                    end
               end

            SUSPEND;
          END
     END
END^

/* Restore proc. body: SP_VRHF_DADOS_INSS_FC_ESOCIAL */
create or alter procedure SP_VRHF_DADOS_INSS_FC_ESOCIAL (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREFNEW integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS smallint = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFCOMP integer,
    BDCODCENTROS integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDCODTIPOFC integer,
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEPIS numeric(18,6))
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(30000);
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WCLAVER varchar(20);
declare variable WTIPOCODVER integer;
declare variable WINSSVER integer;
declare variable WBASEGPSVER varchar(5);
declare variable WREEMBGPSVER varchar(5);
declare variable WVALOR numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WINSSFE numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WBASEINSS numeric(18,6);
declare variable WBASEINSSFE numeric(18,6);
declare variable WBASEINSS13 numeric(18,6);
declare variable WSALFAM numeric(18,6);
declare variable WSALMATEMP numeric(18,6);
declare variable WBASEMV numeric(18,6);
declare variable WBASEMV13 numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WCODTIPOFC integer;
declare variable WCODFCATU integer;
declare variable WBINSSAP numeric(18,6);
declare variable WBINSS13AP numeric(18,6);
declare variable WINSSAP numeric(18,6);
declare variable WINSS13AP numeric(18,6);
declare variable WAINSSAP numeric(18,6);
declare variable WAINSS13AP numeric(18,6);
declare variable WABASEMV numeric(18,6);
declare variable WABASEMV13 numeric(18,6);
declare variable WEMPAP integer;
declare variable WSOMAAP numeric(18,6);
declare variable WCODSIND integer;
declare variable WLIMSIND integer;
declare variable WLIMEMP integer;
declare variable WREEMB numeric(18,6);
declare variable WVINDEVIDO numeric(18,6);
declare variable WVINDEVIDOSF numeric(18,6);
declare variable WBAVPREV numeric(18,6);
declare variable WTEMVALOR smallint;
declare variable WREFFCA integer;
declare variable WREFFC integer;
declare variable WSALMIN numeric(15,2);
declare variable WCATEGORIAESOC integer;
declare variable WCONTRCOL integer;
declare variable WGRUPOCLA integer;
declare variable WINCIDEPIS DM_BOOLEAN;
declare variable WBASEPIS numeric(18,6);
BEGIN
  wsql = 'select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFFC, FC.BDVALVFC, FC.BDBINSSMVFC, FC.BDBINSSMV13FC, FC.BDINSSAPFC, FC.BDINSS13APFC, '||
                'VER.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, FC.BDCODTIPOFC, VERREF.BDPISVER from (';

  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFC, FN.BDVALVFC, FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, FOLN.BDINSS13APFC, FOLN.BDCODTIPOFC, cast(null as INTEGER) BDCODCONTTI, FN.BDCODVER ';

  if (coalesce(prfiliais, 0) = 1 and coalesce(prcodemp, '') <> '') then
     begin
       wsql = wsql|| 'from (select BDCODEMP from TEMPRESAS where (('||prcodemp||') or ('||REPLACE(UPPER(prcodemp), 'BDCODEMP', 'BDCODMATRIZ')||'))) EMP '||
              /*'join VRHF_EMP_TFOLHACOMP FOLN on (FOLN.BDCODEMP = EMP.BDCODEMP) '*/
              'join VRHF_EMP_TFOLHACOMP FOLN on (FOLN.BDCODEMP = EMP.BDCODEMP) ';
       /*
       wwhere = '';

       IF (PRREFNEW IS NOT NULL AND PRREFNEW <> 0) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'((BDREFFN = '||PRREFNEW||') or ('||'BDREFFC >= '||PRREFNEW||'01 and BDREFFC <= '||PRREFNEW||'31)) ';
          END

       if (wwhere <> '') then
          wsql = wsql||' where '||wwhere;

       wsql = wsql||') FN on (FN.BDCODEMP = EMP.BDCODEMP) ';
       */
     end
  else
     begin
       wsql = wsql|| 'from VRHF_EMP_TFOLHACOMP FOLN ';

     /*
       wsql = wsql||'from (select BDCODEMP,BDCODCOL,BDREFFN,BDREFFC,BDCODVER,BDVALVFC from VRHF_EMP_TVERBAFC ';
       wwhere  = '';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          BEGIN
            wwhere = wwhere||prcodemp;
          END
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||prcodcol;
          END
     
       IF (PRREFNEW IS NOT NULL AND PRREFNEW <> 0) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'((BDREFFN = '||PRREFNEW||') or ('||'BDREFFC >= '||PRREFNEW||'01 and BDREFFC <= '||PRREFNEW||'31)) ';
          END
     
       if (wwhere <> '') then
          wsql = wsql||' where '||wwhere;
       wsql = wsql||') FN ';
*/
     end

  wsql = wsql||'join VRHF_EMP_TVERBAFC FN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFFN = FN.BDREFFN and FOLN.BDREFFC = FN.BDREFFC) ';
  wsql = wsql||'left join VRH_EMP_TACCONV AC on (FOLN.BDCODEMP = AC.BDCODEMP and FOLN.BDCODACCONV = AC.BDCODACCONV) ';

/*  wsql = wsql||' where ((FOLN.BDREFFN = '||PRREFNEW||' and FOLN.BDCODACCONV is null) or ('||'FOLN.BDREFFC >= '||PRREFNEW||'01 and FOLN.BDREFFC <= '||PRREFNEW||'31 and FOLN.BDCODACCONV is not null)) ';*/
  wsql = wsql||' where ((FOLN.BDCODTIPOFC = 3 and AC.BDCODACCONV is not null) and '||
                      '(((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = '||PRREFNEW||')) or (FOLN.BDCODTIPOFC <> 3 and FOLN.BDREFFN = '||PRREFNEW||'))';

  wsql = wsql||' union all ';
  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFC, FN.BDVALVFC, FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, FOLN.BDINSS13APFC, FOLN.BDCODTIPOFC, FN.BDCODCONTTI, FN.BDCODVER ';

  if (coalesce(prfiliais, 0) = 1 and coalesce(prcodemp, '') <> '') then
     begin
       wsql = wsql||
              'from (select BDCODEMP from TEMPRESAS where (('||prcodemp||') or ('||REPLACE(UPPER(prcodemp), 'BDCODEMP', 'BDCODMATRIZ')||'))) EMP '||
              'join VRHF_EMP_TFOLHACOMPINT FOLN on (FOLN.BDCODEMP = EMP.BDCODEMP) ';
              /*'join (select BDCODEMP,BDCODCOL,BDREFFN,BDREFFC,BDCODVER,BDVALVFC,BDCODCONTTI from VRHF_EMP_TVERBAFCINT '

       wwhere = '';

       IF (PRREFNEW IS NOT NULL AND PRREFNEW <> 0) THEN
     BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'((BDREFFN = '||PRREFNEW||') or ('||'BDREFFC >= '||PRREFNEW||'01 and BDREFFC <= '||PRREFNEW||'31)) ';
     END

       if (wwhere <> '') then
          wsql = wsql||' where '||wwhere;

       wsql = wsql||') FN on (FN.BDCODEMP = EMP.BDCODEMP) ';  */
     end
  else
     begin
       wsql = wsql|| 'from VRHF_EMP_TFOLHACOMPINT FOLN ';
       /*wsql = wsql||'from (select BDCODEMP,BDCODCOL,BDREFFN,BDREFFC,BDCODVER,BDVALVFC,BDCODCONTTI from VRHF_EMP_TVERBAFCINT ';
       wwhere  = '';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
            wwhere = wwhere||prcodemp;
     END
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||prcodcol;
          END
     
       IF (PRREFNEW IS NOT NULL AND PRREFNEW <> 0) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'((BDREFFN = '||PRREFNEW||') or ('||'BDREFFC >= '||PRREFNEW||'01 and BDREFFC <= '||PRREFNEW||'31)) ';
          END
     
       if (wwhere <> '') then
          wsql = wsql||' where '||wwhere;
       wsql = wsql||') FN ';   */
     end

  wsql = wsql||'join VRHF_EMP_TVERBAFCINT FN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFFN = FN.BDREFFN and FOLN.BDREFFC = FN.BDREFFC and FOLN.BDCODCONTTI = FN.BDCODCONTTI) ';
  wsql = wsql||'left join VRH_EMP_TACCONV AC on (FOLN.BDCODEMP = AC.BDCODEMP and FOLN.BDCODACCONV = AC.BDCODACCONV) ';
  /*wsql = wsql||' where ((FOLN.BDREFFN = '||PRREFNEW||' and FOLN.BDCODACCONV is null) or ('||'FOLN.BDREFFC >= '||PRREFNEW||'01 and FOLN.BDREFFC <= '||PRREFNEW||'31 and FOLN.BDCODACCONV is not null)) ';*/
  wsql = wsql||' where ((FOLN.BDCODTIPOFC = 3 and AC.BDCODACCONV is not null) and '||
               '(((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = '||PRREFNEW||')) or (FOLN.BDCODTIPOFC <> 3 and FOLN.BDREFFN = '||PRREFNEW||'))';

  wsql = wsql||') FC ';
  wsql = wsql||'left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FC.BDCODVER) ';
  wsql = wsql||'left outer join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FC.BDCODVER) ';
  wsql = wsql||'where VER.BDCODVER is not null and VERREF.BDCODVER is not null ';
  wsql = wsql||'order by FC.BDCODEMP,FC.BDCODCOL,FC.BDREFFC,FC.BDCODCONTTI ';

  wempatu     = 0;
  wcolatu     = 0;
  wsalfam     = 0;
  winss       = 0;
  winssfe     = 0;
  winss13     = 0;
  wbaseinss   = 0;
  wbaseinssfe = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wbasemv     = 0;
  wbasemv13   = 0;
  wbinssap    = 0;
  wbinss13ap  = 0;
  wainssap    = 0;
  wainss13ap  = 0;
  wabasemv    = 0;
  wabasemv13  = 0;
  wempap      = 0;
  wsomaap     = 0;
  wreemb      = 0;
  wvindevido  = 0;
  wvindevidosf = 0;
  wbavprev     = 0;
  wtemvalor   = 0;
  wreffca = 0;
  wreffca = 0;
  wbasepis = 0;

  EXECUTE PROCEDURE sp_seta_competencia(PRREFNEW);

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wreffc, :wvalor, :wbasemv, :wbasemv13, :winssap, :winss13ap, :wclaver, :wtipocodver, :winssver, :wbasegpsver, :wreembgpsver, :wcodtipofc, :wincidepis DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wreffca = 0) THEN
       wreffca = wreffc;

    /*
      Retorna bases de INSS
    */
    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wreffca <> wreffc)) THEN
       BEGIN
         wcodsind = NULL;
         wlimemp = NULL;
         wlimsind = NULL;
         SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
         IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
            BEGIN
              SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
            END

         IF (wlimsind IS NULL) THEN
            wlimsind = 0;             -- não possui liminar

         IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
            SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;

         IF (wlimemp IS NULL) THEN
            wlimemp = 0;    -- não possui liminar

         BDGPSSEFIP     = 0;
         BDCODEMP       = wempatu;
         BDCODCOL       = wcolatu;
         BDREFFN        = PRREFNEW;
         BDREFCOMP      = CAST((SUBSTRING(PRREFNEW FROM 1 FOR 6)) AS INTEGER);
         BDCODTIPOFC    = wcodfcatu;
         BDCODCENTROS   = NULL;
         BDCODTPCC      = NULL;
         BDINSSFN       = winss;
         BDINSSFEFOLFN  = winssfe;
         BDINSS13FN     = winss13;
         BDBINSSFEFOLFN = wbaseinssfe;
         bdbasepis      = wbasepis;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSSFN = wbinssap;
         ELSE
            BDBINSSFN = wbaseinss;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13FN = wbaseinss13 - wbinss13ap;
         ELSE
            BDBINSS13FN = wbaseinss13;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13INDFN = 0;
         ELSE
            BDBINSS13INDFN = wbinss13ap;

         IF (bdbinssfn < 0) THEN
            bdbinssfn = 0;

         wpercrat = 0;
         wcategoriaesoc = null;
         wcontrcol = null;
         SELECT first 1 BDPERCRATCOL, BDCATEGORIAESOCIAL, BDCONTRCOL
         FROM VRHF_EMP_TCOLCON_FGTSGPS
         WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prrefnew
         order by BDREFCOL DESC
         INTO :wpercrat, :wcategoriaesoc, :wcontrcol;
         wpercrat = coalesce(wpercrat, 0);
         wcategoriaesoc = coalesce(wcategoriaesoc, 0);
         wcontrcol = coalesce(wcontrcol, 0);

         -- 136305 - Raphael Teodoro - 21/08/2020
         wgrupocla = 0;
         SELECT CLA.BDGRUPOCLA
         FROM VW_VRH_EMP_TCOLCON_VINC VINC
         LEFT OUTER JOIN VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
         WHERE (VINC.BDCODEMP = :wempatu)
           AND (VINC.BDCODCOL = :wcolatu)
           AND (VINC.BDREFCOL <= :prrefnew)
         ORDER BY BDCODEMP DESC, BDCODCOL DESC, BDREFCOL DESC
         INTO :wgrupocla;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BEGIN
              BDBRATAPOFN   = BDBINSSFN;
              BDBRATAPOFEFN = BDBINSSFEFOLFN;
              BDBRATAPO13FN = BDBINSS13FN;
            END
         ELSE
            BEGIN
              BDBRATAPOFN   = 0;
              BDBRATAPOFEFN = 0;
              BDBRATAPO13FN = 0;
            END

         BDSALFAMFN     = wsalfam;
         BDSALMATEMPFN  = wsalmatemp;
         BDBINSSMVFN    = wabasemv;
         BDBINSSMV13FN  = wabasemv13;
         BDBINSSAPFN    = wbinssap;
         BDBINSS13APFN  = wbinss13ap;
         BDINSSAPFN     = wainssap;
         BDINSS13APFN   = wainss13ap;
         BDVALREEMBOLSO = wreemb;
         BDVALINDEVIDO  = wvindevido;
         BDVALINDEVIDOSF = wvindevidosf;
         BDBAVPREV       = 0;

         if ((wcontrcol = 0) and
             (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
            BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
         else
            BDBASERAT = 0;

         BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
         BDBASEINSS13 = BDBINSS13FN;

         if (wcategoriaesoc in (107, 108)) then
            begin
              BDBINSSFN = BDBINSSFN + BDBINSS13FN;
              BDBINSS13FN = 0;

              select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREFNEW order by bdrefsm DESC INTO :WSALMIN;
              if (BDBINSSFN > WSALMIN * 1.5) then
                 begin
                   BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                 end
              else
                 begin
                   BDBINSSFN = 0;
                 end
            end

         SUSPEND;

         IF (PRREFNEW >= 200903 AND prGPSSEFIP = 1 AND wsomaap <> 0) THEN
            BEGIN
              BDGPSSEFIP     = 1;
              BDCODEMP       = wempatu;
              BDCODCOL       = wcolatu;
              BDREFFN        = PRREFNEW;
              BDREFCOMP      = CAST((SUBSTRING(PRREFNEW FROM 1 FOR 6)) AS INTEGER);
              BDCODTIPOFC    = wcodfcatu;
              BDCODCENTROS   = NULL;
              BDCODTPCC      = NULL;
              BDBAVPREV      = wbavprev;

              IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
                 BEGIN
                   IF (wbinssap < 0) THEN
                     wbinssap = 0;
                   BDINSSFN  = wainssap;
                   BDBINSSFN = wbinssap;
                 END
              ELSE
                 BEGIN
                   BDINSSFN  = winss;
                   BDBINSSFN = wbaseinss;
                 END

              BDINSSFEFOLFN  = winssfe;
              BDINSS13FN     = winss13;
              BDBINSSFEFOLFN = wbaseinssfe;
              BDBINSS13FN    = wbaseinss13;
              BDBINSS13INDFN = wbinss13ap;

              IF (bdbinssfn < 0) THEN
                 bdbinssfn = 0;
     
              IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
                 BEGIN
                   BDBRATAPOFN   = BDBINSSFN;
                   BDBRATAPOFEFN = BDBINSSFEFOLFN;
                   BDBRATAPO13FN = BDBINSS13FN;
                 END
              ELSE
                 BEGIN
                   BDBRATAPOFN   = 0;
                   BDBRATAPOFEFN = 0;
                   BDBRATAPO13FN = 0;
                 END
     
              BDSALFAMFN     = wsalfam;
              BDSALMATEMPFN  = wsalmatemp;
              BDBINSSMVFN    = wabasemv;
              BDBINSSMV13FN  = wabasemv13;
              BDBINSSAPFN    = wbinssap;
              BDBINSS13APFN  = wbinss13ap;
              BDINSSAPFN     = wainssap;
              BDINSS13APFN   = wainss13ap;
              BDVALREEMBOLSO = wreemb;
              BDVALINDEVIDO  = wvindevido;
              BDVALINDEVIDOSF = wvindevidosf;

              if ((wcontrcol = 0) and
                  (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
                 BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
              else
                 BDBASERAT = 0;

              BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
              BDBASEINSS13 = BDBINSS13FN;

              if (wcategoriaesoc in (107, 108)) then
                 begin
                   BDBINSSFN = BDBINSSFN + BDBINSS13FN;
                   BDBINSS13FN = 0;

                   select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREFNEW order by bdrefsm DESC INTO :WSALMIN;
                   if (BDBINSSFN > WSALMIN * 1.5) then
                      begin
                        BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                      end
                   else
                      begin
                        BDBINSSFN = 0;
                      end
                 end

              SUSPEND;
            END

         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wreffca     = wreffc;
         wsalfam     = 0;
         winss       = 0;
         winssfe     = 0;
         winss13     = 0;
         wbaseinss   = 0;
         wbaseinssfe = 0;
         wbaseinss13 = 0;
         wsalmatemp  = 0;
         wabasemv    = 0;
         wabasemv13  = 0;
         wbinssap    = 0;
         wbinss13ap  = 0;
         wainss13ap  = 0;
         wainssap    = 0;
         wreemb      = 0;
         wvindevido  = 0;
         wvindevidosf = 0;
         wbavprev     = 0;
         wtemvalor = 0;
         wbasepis  = 0;
       END

    wcodfcatu  = wcodtipofc;
    wainss13ap = winss13ap;
    wainssap   = winssap;
    wabasemv   = wbasemv;
    wabasemv13 = wbasemv13;

    IF (PRREFNEW >= 200903 AND prgpssefip = 1 AND wempap <> wcodemp) THEN
       BEGIN
         wsomaap = 0;
         SELECT SUM(BDSOMA) FROM (
           SELECT X.bdvalvfc BDSOMA
           FROM vrhf_emp_tverbafc X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :PRREFNEW AND X.bdrefcomp = :PRREFNEW and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvfc BDSOMA
           FROM vrhf_emp_tverbafctomador X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :PRREFNEW AND X.bdrefcomp = :PRREFNEW and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvfn BDSOMA
           FROM vrhf_emp_tverbafn X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :PRREFNEW and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvft BDSOMA
           FROM vrhf_emp_tverbatomador X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :PRREFNEW and Y.BDCODVER is not null
         )
         INTO :wsomaap;
         wempap = wcodemp;
       END

    -- INSS folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.0') THEN
       winss = winss + wvalor;

    -- INSS férias demonstradas na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.2') THEN
       winssfe = winssfe + wvalor;

    -- INSS 13o. complemento de 13º na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.6') THEN
       winss13 = winss13 + wvalor;

    -- INSS 13o. rescisão descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;

    -- Base de INSS folha normal
    IF ((winssver = 1)) THEN
       BEGIN
         IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
            BEGIN
              IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
       END
    ELSE
    IF ((winssver = 0)) THEN  --não incide
       BEGIN
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
         ELSE
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                 wbaseinss13 = wbaseinss13 + wvalor;
              ELSE
              IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                 wbaseinss13 = wbaseinss13 - wvalor;
            END
       END

    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 2) THEN
       BEGIN

         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END
    ELSE
    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 1 AND SUBSTRING(wclaver FROM 1 FOR 5) >= '0.100' AND SUBSTRING(wclaver FROM 1 FOR 5) < '0.200') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END

    -- Base de INSS 13o. salário descontado na rescisão
    IF ((winssver = 3)) THEN
       BEGIN
         IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE'))  THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
         IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE'))  THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       END

    -- Valor base PIS
    if (coalesce(UPPER(wincidepis), 'FALSE') = 'TRUE') then
       begin
          IF (wtipocodver = 0) THEN  -- Provento
             wbasepis = wbasepis + wvalor;
          ELSE
          IF (wtipocodver = 1) THEN  -- Desconto
             wbasepis = wbasepis - wvalor;
       end

    -- Valor de salário família
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '9.050') THEN
       wsalfam = wsalfam + wvalor;

    -- Valor indevido na GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.2') THEN
       wvindevido = wvindevido + wvalor;

    -- Valor SF indevido na GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.0') THEN
       wvindevidosf = wvindevidosf + wvalor;

    -- Base de salário maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005') OR
         (SUBSTRING(wclaver FROM 1 FOR 7) = '7.061.2') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '0.610') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.070')OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.710'))) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END

    -- Base de INSS sem o aviso prévio indenizado
    IF (SUBSTRING(wclaver FROM 1 FOR 7) <> '7.001.3') THEN
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
              ELSE
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinss13ap = wbinss13ap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinss13ap = wbinss13ap - wvalor;

                   wtemvalor = 1;
                 END
            END
       END
    ELSE
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 7, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
       END

    -- INSS sobre o aviso prévio indenizado do 13º salário
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '7.060') THEN
       BEGIN
         IF (winssver = 3) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbinss13ap = wbinss13ap + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbinss13ap = wbinss13ap - wvalor;
            END
       END
  END


  IF ((wempatu <> 0) AND (wcolatu <> 0) AND (wreffca <> 0)) THEN
     BEGIN
       wcodsind = NULL;
       wlimemp = NULL;
       wlimsind = NULL;
       SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
       IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
          BEGIN
            SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
          END

       IF (wlimsind IS NULL) THEN
          wlimsind = 0;             -- não possui liminar

       IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
          SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;

       IF (wlimemp IS NULL) THEN
          wlimemp = 0;    -- não possui liminar

       BDGPSSEFIP = 0;
       BDCODEMP       = wempatu;
       BDCODCOL       = wcolatu;
       BDREFFN        = PRREFNEW;
       BDREFCOMP      = CAST((SUBSTRING(PRREFNEW FROM 1 FOR 6)) AS INTEGER);
       BDCODTIPOFC    = wcodfcatu;
       BDCODCENTROS   = NULL;
       BDCODTPCC      = NULL;
       BDINSSFN       = winss;
       BDINSSFEFOLFN  = winssfe;
       BDINSS13FN     = winss13;
       BDBINSSFEFOLFN = wbaseinssfe;
       BDBINSSAPFN    = wbinssap;
       BDBINSS13APFN  = wbinss13ap;
       BDBAVPREV      = 0;

       IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
          BDBINSSFN = wbinssap;
       ELSE
          BDBINSSFN = wbaseinss;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13FN = wbaseinss13 - wbinss13ap;
       ELSE
          BDBINSS13FN = wbaseinss13;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13INDFN = 0;
       ELSE
          BDBINSS13INDFN = wbinss13ap;

       IF (bdbinssfn < 0) THEN
          bdbinssfn = 0;

       wpercrat = 0;
       wcategoriaesoc = null;
       wcontrcol = null;
       SELECT first 1 BDPERCRATCOL, BDCATEGORIAESOCIAL, BDCONTRCOL
       FROM VRHF_EMP_TCOLCON_FGTSGPS
       WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prrefnew
       order by BDREFCOL DESC
       INTO :wpercrat, :wcategoriaesoc, :wcontrcol;

       -- 136305 - Raphael Teodoro - 21/08/2020
       wgrupocla = 0;
       SELECT CLA.BDGRUPOCLA
       FROM VW_VRH_EMP_TCOLCON_VINC VINC
       LEFT OUTER JOIN VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
       WHERE (VINC.BDCODEMP = :wempatu)
         AND (VINC.BDCODCOL = :wcolatu)
         AND (VINC.BDREFCOL <= :prrefnew)
       ORDER BY BDCODEMP DESC, BDCODCOL DESC, BDREFCOL DESC
       INTO :wgrupocla;

       wpercrat = coalesce(wpercrat, 0);
       wcategoriaesoc = coalesce(wcategoriaesoc, 0);
       wcontrcol = coalesce(wcontrcol, 0);
 
       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BEGIN
            BDBRATAPOFN   = wbaseinss;
            BDBRATAPOFEFN = wbaseinssfe;
            BDBRATAPO13FN = wbaseinss13;
          END
       ELSE
          BEGIN
            BDBRATAPOFN   = 0;
            BDBRATAPOFEFN = 0;
            BDBRATAPO13FN = 0;
          END

       BDSALFAMFN     = wsalfam;
       BDSALMATEMPFN  = wsalmatemp;

       BDBINSSMVFN    = wabasemv;
       BDBINSSMV13FN  = wabasemv13;
       BDINSSAPFN     = wainssap;
       BDINSS13APFN   = wainss13ap;
       BDVALREEMBOLSO = wreemb;
       BDVALINDEVIDO  = wvindevido;
       BDVALINDEVIDOSF = wvindevidosf;

       if ((wcontrcol = 0) and
           (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
          BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
       else
          BDBASERAT = 0;

       BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
       BDBASEINSS13 = BDBINSS13FN;
       bdbasepis      = wbasepis;


       if (wcategoriaesoc in (107, 108)) then
          begin
            BDBINSSFN = BDBINSSFN + BDBINSS13FN;
            BDBINSS13FN = 0;

            select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREFNEW order by bdrefsm DESC INTO :WSALMIN;
            if (BDBINSSFN > WSALMIN * 1.5) then
               begin
                 BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
               end
            else
               begin
                 BDBINSSFN = 0;
               end
          end

       SUSPEND;

    IF (PRREFNEW >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
          BEGIN
            BDGPSSEFIP     = 1;
            BDCODEMP       = wempatu;
            BDCODCOL       = wcolatu;
            BDREFFN        = PRREFNEW;
            BDREFCOMP      = CAST((SUBSTRING(PRREFNEW FROM 1 FOR 6)) AS INTEGER);
            BDCODTIPOFC    = wcodfcatu;
            BDCODCENTROS   = NULL;
            BDCODTPCC      = NULL;
            BDBAVPREV      = wbavprev;
            bdbasepis      = wbasepis;

            IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
               BEGIN
                 IF (wbinssap < 0) THEN
                   wbinssap = 0;
                 BDINSSFN  = wainssap;
                 BDBINSSFN = wbinssap;
               END
             ELSE
               BEGIN
                 BDINSSFN  = winss;
                 BDBINSSFN = wbaseinss;
               END

            BDINSSFEFOLFN  = winssfe;
            BDINSS13FN     = winss13;
            BDBINSSFEFOLFN = wbaseinssfe;
            BDBINSS13FN    = wbaseinss13;
            BDBINSSAPFN    = wbinssap;
            BDBINSS13APFN  = wbinss13ap;

            IF (bdbinssfn < 0) THEN
               bdbinssfn = 0;
     
            IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
               BEGIN
                 BDBRATAPOFN   = BDBINSSFN;
                 BDBRATAPOFEFN = BDBINSSFEFOLFN;
                 BDBRATAPO13FN = BDBINSS13FN;
               END
            ELSE
               BEGIN
                 BDBRATAPOFN   = 0;
                 BDBRATAPOFEFN = 0;
                 BDBRATAPO13FN = 0;
               END
     
            BDSALFAMFN     = wsalfam;
            BDSALMATEMPFN  = wsalmatemp;
     
            BDBINSSMVFN    = wabasemv;
            BDBINSSMV13FN  = wabasemv13;
            BDINSSAPFN     = wainssap;
            BDINSS13APFN   = wainss13ap;
            BDVALREEMBOLSO = wreemb;
            BDVALINDEVIDO  = wvindevido;
            BDVALINDEVIDOSF = wvindevidosf;
            BDBINSS13INDFN = wbinss13ap;

            if ((wcontrcol = 0) and
                (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
               BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
            else
               BDBASERAT = 0;

            BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
            BDBASEINSS13 = BDBINSS13FN;

            if (wcategoriaesoc in (107, 108)) then
               begin
                 BDBINSSFN = BDBINSSFN + BDBINSS13FN;
                 BDBINSS13FN = 0;

                 select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREFNEW order by bdrefsm DESC INTO :WSALMIN;
                 if (BDBINSSFN > WSALMIN * 1.5) then
                    begin
                      BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                    end
                 else
                    begin
                      BDBINSSFN = 0;
                    end
               end

            SUSPEND;
          END
     END
END^

/* Restore proc. body: SP_ESOCIAL_DADOS_INSS_FN */
create or alter procedure SP_ESOCIAL_DADOS_INSS_FN (
    PRCODEMP varchar(15000),
    PRREF integer,
    PRCONTRATO integer = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDCODCENTROS integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDPERCRATCOL numeric(18,6),
    BDPERCDESCFPASCOL numeric(18,6),
    BDCNPJEMP DM_CNPJ_CPF)
as
declare variable WSQL varchar(30000);
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WCLAVER varchar(20);
declare variable WTIPOCODVER integer;
declare variable WINSSVER integer;
declare variable WBASEGPSVER varchar(5);
declare variable WREEMBGPSVER varchar(5);
declare variable WVALOR numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WINSSFE numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WBASEINSS numeric(18,6);
declare variable WBASEINSSFE numeric(18,6);
declare variable WBASEINSS13 numeric(18,6);
declare variable WSALFAM numeric(18,6);
declare variable WSALMATEMP numeric(18,6);
declare variable WBASEMV numeric(18,6);
declare variable WBASEMV13 numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WBINSSAP numeric(18,6);
declare variable WBINSS13AP numeric(18,6);
declare variable WINSSAP numeric(18,6);
declare variable WINSS13AP numeric(18,6);
declare variable WAINSSAP numeric(18,6);
declare variable WAINSS13AP numeric(18,6);
declare variable WABASEMV numeric(18,6);
declare variable WABASEMV13 numeric(18,6);
declare variable WCODSIND integer;
declare variable WLIMSIND integer;
declare variable WLIMEMP integer;
declare variable WCONTRCOL integer;
declare variable WREEMB numeric(18,6);
declare variable WVINDEVIDO numeric(18,6);
declare variable WVINDEVIDOSF numeric(18,6);
declare variable WBAVPREV numeric(18,6);
declare variable WPERCDESCFPAS numeric(18,6);
declare variable WSINDATU integer;
declare variable WBASEINSSCONTR numeric(18,6);
declare variable WBASEINSSCONTRATU numeric(18,6);
declare variable WINTERMITENTE DM_BOOLEAN;
declare variable WCNPJEMP DM_CNPJ_CPF;
declare variable WCNPJANT DM_CNPJ_CPF;
declare variable WCLATRIB integer;
declare variable WCOOP integer;
declare variable WCATESOC integer;
BEGIN
  wsql = 'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFN, FN.BDBINSSMVFN, FN.BDBINSSMV13FN, FN.BDINSSAPFN, FN.BDINSS13APFN, VERREF.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, '||
                'VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, FN.BDBASEINSSNMVNOVO, '||
                'case when COALESCE(FGTSGPS.BDCATEGORIACOL,0) = 4 and COALESCE(FGTSGPS.BDCATEGORIAESOCIAL,0) = 111 then ''TRUE'' else ''FALSE'' end BDINTERM, FN.BDCNPJEMP '||
         'from (';
     
  if (coalesce(prcontrato, 0) = 0) then
     begin
       wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFN, FN.BDCODVER, FOLN.BDBINSSMVFN, FOLN.BDBINSSMV13FN, FOLN.BDINSSAPFN, FOLN.BDINSS13APFN, '||
                         'case when coalesce(FOLN.BDBASEINSSNMVNOVO, 0) <> 0 then FOLN.BDBASEINSSNMVNOVO else FOLN.BDBINSSFN end BDBASEINSSNMVNOVO, FILIAIS.BDCNPJEMP from (';
          
       if (coalesce(prcodemp, '') <> '') then
          wsql = wsql||'select BDCODEMP, BDCNPJEMP from (';
       wsql = wsql||'select BDCODEMP, BDCNPJEMP from TEMPRESAS ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          begin
            wsql = wsql||'where (('||prcodemp||') or ('||replace(upper(prcodemp), 'BDCODEMP', 'BDCODMATRIZ')||')) ';
            wsql = wsql||'union all select FIL.BDCODEMP, EMP.BDCNPJEMP from TEMPRESAS EMP ';
            wsql = wsql||'join TEMPRESAS FIL on (SUBSTRING(FIL.BDCNPJEMP FROM 1 FOR 10) = SUBSTRING(EMP.BDCNPJEMP FROM 1 FOR 10)) ';
            wsql = wsql||'where FIL.BDCODMATRIZ is null';
            wsql = wsql||' and '||replace(upper(prcodemp), 'BDCODEMP', 'EMP.BDCODEMP');
          end

       if (coalesce(prcodemp, '') <> '') then
          wsql = wsql||') group by BDCODEMP, BDCNPJEMP';
       wsql = wsql||') FILIAIS ';
       wsql = wsql||'join VRHF_EMP_TVERBAFN FN on (FN.BDCODEMP = FILIAIS.BDCODEMP) ';
       wsql = wsql||'join VRHF_EMP_TFOLHANORMAL FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFFN = FN.BDREFFN) ';
       wsql = wsql||'join VRH_ESOCIAL_TFASEAMENTO FASEMP on (FASEMP.BDCODEMP = FN.BDCODEMP) ';
       wsql = wsql||'where ((coalesce(FASEMP.BDOPCAOESOCIAL, 0) = 1 and coalesce(FASEMP.BDREFINIDCTFWEB, 0) > 0 and FN.BDREFFN >= coalesce(FASEMP.BDREFINIDCTFWEB, 0)) or (coalesce(FASEMP.BDOPCAOESOCIAL, 0) = 2)) ';

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and FN.BDREFFN = '||prref;

       wsql = wsql||' union all ';
     end

  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFN, FN.BDCODVER, FOLN.BDBINSSMVFN, FOLN.BDBINSSMV13FN, FOLN.BDINSSAPFN, FOLN.BDINSS13APFN, '||
                   'case when coalesce(FOLN.BDBASEINSSNMVNOVO, 0) <> 0 then FOLN.BDBASEINSSNMVNOVO else FOLN.BDBINSSFN end BDBASEINSSNMVNOVO, FILIAIS.BDCNPJEMP from (';

  if (coalesce(prcodemp, '') <> '') then
     wsql = wsql||'select BDCODEMP, BDCNPJEMP from (';
  wsql = wsql||'select BDCODEMP, BDCNPJEMP from TEMPRESAS ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     begin
       wsql = wsql||'where (('||prcodemp||') or ('||replace(upper(prcodemp), 'BDCODEMP', 'BDCODMATRIZ')||')) ';
       wsql = wsql||'union all select FIL.BDCODEMP, EMP.BDCNPJEMP from TEMPRESAS EMP ';
       wsql = wsql||'join TEMPRESAS FIL on (SUBSTRING(FIL.BDCNPJEMP FROM 1 FOR 10) = SUBSTRING(EMP.BDCNPJEMP FROM 1 FOR 10)) ';
       wsql = wsql||'where FIL.BDCODMATRIZ is null';
       wsql = wsql||' and '||replace(upper(prcodemp), 'BDCODEMP', 'EMP.BDCODEMP');
     end

  if (coalesce(prcodemp, '') <> '') then
     wsql = wsql||') group by BDCODEMP, BDCNPJEMP';
  wsql = wsql||') FILIAIS ';
  wsql = wsql||'join VRHF_EMP_TVERBAINT FN on (FN.BDCODEMP = FILIAIS.BDCODEMP) ';

  wsql = wsql||'join VRHF_EMP_TFOLHAINT FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFFN = FN.BDREFFN and FOLN.BDCODCONTTI = FN.BDCODCONTTI) ';

  wsql = wsql||'join VRH_ESOCIAL_TFASEAMENTO FASEMP on (FASEMP.BDCODEMP = FN.BDCODEMP) ';
  wsql = wsql||'where ((coalesce(FASEMP.BDOPCAOESOCIAL, 0) = 1 and coalesce(FASEMP.BDREFINIDCTFWEB, 0) > 0 and FN.BDREFFN >= coalesce(FASEMP.BDREFINIDCTFWEB, 0)) or (coalesce(FASEMP.BDOPCAOESOCIAL, 0) = 2)) ';

  IF (prref IS NOT NULL AND prref <> 0) THEN
     wsql = wsql||' and FN.BDREFFN = '||prref;

  if (coalesce(prcontrato, 0) > 0) then
     wsql = wsql||' and FN.BDCODCONTTI = '||prcontrato||' ';


  wsql = wsql||') FN ';

     wsql = wsql||'left outer join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';
  wsql = wsql||'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS FGTSGPS on (FGTSGPS.BDCODEMP = FN.BDCODEMP and FGTSGPS.BDCODCOL = FN.BDCODCOL) ';
  wsql = wsql||'where VERREF.BDCODVER is not null ';

  wsql = wsql||'order by FN.BDCODEMP,FN.BDCODCOL ';

  wempatu     = 0;
  wcolatu     = 0;
  wsalfam     = 0;
  winss       = 0;
  winssfe     = 0;
  winss13     = 0;
  wbaseinss   = 0;
  wbaseinssfe = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wbasemv     = 0;
  wbasemv13   = 0;
  wbinssap    = 0;
  wbinss13ap  = 0;
  wainssap    = 0;
  wainss13ap  = 0;
  wabasemv    = 0;
  wabasemv13  = 0;
  wreemb      = 0;
  wvindevido  = 0;
  wvindevidosf = 0;
  wbavprev     = 0;
  wsindatu = 0;
  wcodsind = -1;
  wcnpjant = null;
  wclatrib = null;
  wcoop    = null;
  wcatesoc = null;

  EXECUTE PROCEDURE sp_seta_competencia(prref);

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wvalor, :wbasemv, :wbasemv13, :winssap, :winss13ap, :wclaver, :wtipocodver, :winssver, :wbasegpsver,
                                  :wreembgpsver, :wbaseinsscontr, :wintermitente, :wcnpjemp DO
  BEGIN
    IF (wempatu = 0) THEN
      BEGIN
        wempatu = wcodemp;
        wlimemp = NULL;
        SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
        IF (wlimemp IS NULL) THEN
           wlimemp = 0;    -- não possui liminar

        wclatrib = null;
        wcoop    = null;
        select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
        into :wclatrib, :wcoop;

        wclatrib = coalesce(wclatrib, 0);
        wcoop    = coalesce(wcoop, 0);
      END

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    if (wcnpjant is null) then
       wcnpjant = coalesce(wcnpjemp, '');

    /*
      Retorna bases de INSS
    */


    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol)) THEN
       BEGIN
         --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a versão com a alteração abaixo corretamente.
         wcodsind = NULL;
         SELECT first 1 BDCODSINTRAB FROM VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC
         INTO :wcodsind;

         IF (wsindatu <> wcodsind) THEN
           BEGIN
             wlimsind = NULL;
             wsindatu = wcodsind;
             IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
                SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wsindatu INTO :wlimsind;
             IF (wlimsind IS NULL) THEN
                wlimsind = 0;             -- não possui liminar
           END

         IF (wempatu <> wcodemp) THEN
           BEGIN
             wlimemp = NULL;
             SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
             IF (wlimemp IS NULL) THEN
                wlimemp = 0;    -- não possui liminar

             wclatrib = null;
             wcoop    = null;
             select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
             into :wclatrib, :wcoop;
     
             wclatrib = coalesce(wclatrib, 0);
             wcoop    = coalesce(wcoop, 0);
           END

         BDGPSSEFIP     = 3;
         BDCODEMP       = wempatu;
         BDCODCOL       = wcolatu;
         BDREFFN        = prref;
         BDCODCENTROS   = NULL;
         BDCODTPCC      = NULL;
         BDINSSFN       = winss;
         BDINSSFEFOLFN  = winssfe;
         BDINSS13FN     = winss13;
         BDBAVPREV      = 0;
         BDCNPJEMP      = wcnpjant;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSSFN = wbinssap;
         ELSE
            BDBINSSFN = wbaseinss;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13FN = wbaseinss13 - wbinss13ap;
         ELSE
            BDBINSS13FN = wbaseinss13;

         BDBINSSFEFOLFN = wbaseinssfe;
         BDBINSSAPFN    = wbinssap;
         BDBINSS13APFN  = wbinss13ap;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13INDFN = 0;
         ELSE
            BDBINSS13INDFN = wbinss13ap;

         IF (BDBINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
            BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;

         IF (BDBINSSFN < 0 AND BDBINSSFEFOLFN > 0) THEN
            BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;

         -- 138080 - Raphael Teodoro - 26/08/2020
         IF (BDBINSSFEFOLFN < 0) THEN
            BDBINSSFEFOLFN = 0;

         wpercrat = 0;
         wpercdescfpas = 0;
         wcontrcol = NULL;
         wcatesoc = null;
         SELECT first 1 BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL, BDCATEGORIAESOCIAL
         FROM VRHF_EMP_TCOLCON_FGTSGPS
         WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prref
         order by BDREFCOL DESC
         INTO :wpercrat, :wpercdescfpas, :wcontrcol, :wcatesoc;
         IF (wcontrcol IS NULL) THEN
            wcontrcol = 0;

         IF (wcontrcol = 1) THEN
            bdbinssfn = wbaseinsscontratu - wabasemv;

         IF (bdbinssfn < 0) THEN
            bdbinssfn = 0;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BEGIN
              BDBRATAPOFN   = BDBINSSFN;     --+ BDBINSSFEFOLFN;
              BDBRATAPOFEFN = BDBINSSFEFOLFN;
              BDBRATAPO13FN = BDBINSS13FN;
            END
         ELSE
            BEGIN
              BDBRATAPOFN   = 0;
              BDBRATAPOFEFN = 0;
              BDBRATAPO13FN = 0;
            END

         BDSALFAMFN        = wsalfam;
         BDSALMATEMPFN     = wsalmatemp;
         BDBINSSMVFN       = wabasemv;
         BDBINSSMV13FN     = wabasemv13;
         BDINSSAPFN        = wainssap;
         BDINSS13APFN      = wainss13ap;
         BDVALREEMBOLSO    = wreemb;
         BDVALINDEVIDO     = wvindevido;
         BDVALINDEVIDOSF   = wvindevidosf;
         BDPERCRATCOL      = wpercrat;
         BDPERCDESCFPASCOL = wpercdescfpas;

         if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and coalesce(wcatesoc, 0) in (731, 734)) then
            begin
              BDBINSS13APFN  = 0;
              BDBINSS13FN    = 0;
              BDBINSS13INDFN = 0;
              BDBINSSAPFN    = 0;
              BDBINSSFEFOLFN = 0;
              BDBINSSFN      = 0;
              BDBINSSMV13FN  = 0;
              BDBINSSMVFN    = 0;
            end

         SUSPEND;

         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wsalfam     = 0;
         winss       = 0;
         winssfe     = 0;
         winss13     = 0;
         wbaseinss   = 0;
         wbaseinssfe = 0;
         wbaseinss13 = 0;
         wsalmatemp  = 0;
         wbinssap    = 0;
         wbinss13ap  = 0;
         wainssap    = 0;
         wainss13ap  = 0;
         wabasemv    = 0;
         wabasemv13  = 0;
         wreemb      = 0;
         wvindevido  = 0;
         wvindevidosf = 0;
         wbavprev     = 0;
         wcnpjant     = coalesce(wcnpjemp, '');
       END

    wainssap   = winssap;
    wainss13ap = winss13ap;
    wabasemv   = wbasemv;
    wabasemv13 = wbasemv13;
    wbaseinsscontratu = wbaseinsscontr;

    -- INSS folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.0') THEN
       winss = winss + wvalor;

    -- INSS férias demonstradas na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.2') THEN
       winssfe = winssfe + wvalor;

    -- INSS 13o. rescisão descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;

    if (wintermitente = 'TRUE') then
       begin
         -- INSS 13o. descontado na folha normal
         IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.6') THEN
            winss13 = winss13 + wvalor;
       end

    -- Base de INSS folha normal
    IF ((winssver = 1)) THEN
       BEGIN
         IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
       END
    ELSE
    IF ((winssver = 0)) THEN  --não incide
       BEGIN
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
         ELSE
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss13 = wbaseinss13 + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss13 = wbaseinss13 - wvalor;
            END
       END

    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 2) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END
    ELSE
    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 1 AND SUBSTRING(wclaver FROM 1 FOR 5) >= '0.100' AND SUBSTRING(wclaver FROM 1 FOR 5) < '0.200') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END

    -- Base de INSS 13o. salário descontado na rescisão
    IF ((winssver = 3)) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       END

    -- Valor de salário família
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '9.050' AND wtipocodver = 0) THEN
       wsalfam = wsalfam + wvalor;

    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.2') THEN  --  Valores indevidos da GPS
       wvindevido = wvindevido + wvalor;

    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.0') THEN  --  Valores SF indevidos da GPS
       wvindevidosf = wvindevidosf + wvalor;

    -- Base de salário maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005') OR
         (SUBSTRING(wclaver FROM 1 FOR 7) = '7.061.2')OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.710'))) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END

    -- Base INSS sem o aviso prévio indenizado
    IF (SUBSTRING(wclaver FROM 1 FOR 7) <> '7.001.3') THEN
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;
                 END
              ELSE
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinss13ap = wbinss13ap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinss13ap = wbinss13ap - wvalor;
                 END
            END
       END
    ELSE
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 7, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
       END

    -- INSS sobre o aviso prévio indenizado do 13º salário
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '7.060') THEN
       BEGIN
         IF (winssver = 3) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbinss13ap = wbinss13ap + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbinss13ap = wbinss13ap - wvalor;
            END
       END

  END

  IF ((wempatu <> 0) AND (wcolatu <> 0)) THEN
     BEGIN
       wcodsind = NULL;
       wlimemp = NULL;
       wlimsind = NULL;
       SELECT first 1 BDCODSINTRAB FROM VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC
       INTO :wcodsind;
       IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
          BEGIN
            SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
          END
 
       IF (wlimsind IS NULL) THEN
          wlimsind = 0;             -- não possui liminar
 
       IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
          SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
 
       IF (wlimemp IS NULL) THEN
          wlimemp = 0;    -- não possui liminar

       wclatrib = null;
       wcoop    = null;
       select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
       into :wclatrib, :wcoop;
       wclatrib = coalesce(wclatrib, 0);
       wcoop    = coalesce(wcoop, 0);

       BDGPSSEFIP     = 3;
       BDCODEMP       = wempatu;
       BDCODCOL       = wcolatu;
       BDREFFN        = prref;
       BDCODCENTROS   = NULL;
       BDCODTPCC      = NULL;
       BDINSSFN       = winss;
       BDINSSFEFOLFN  = winssfe;
       BDINSS13FN     = winss13;
       BDBINSSFEFOLFN = wbaseinssfe;
       BDBINSSAPFN    = wbinssap;
       BDBINSS13APFN  = wbinss13ap;
       BDINSSAPFN     = wainssap;
       BDINSS13APFN   = wainss13ap;
       BDBAVPREV      = 0;
       BDCNPJEMP      = wcnpjant;

       IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
          BDBINSSFN = wbinssap;
       ELSE
          BDBINSSFN = wbaseinss;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13FN = wbaseinss13 - wbinss13ap;
       ELSE
          BDBINSS13FN = wbaseinss13;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13INDFN = 0;
       ELSE
          BDBINSS13INDFN = wbinss13ap;

       IF (BDBINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
          BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;
       IF (BDBINSSFN < 0 AND BDBINSSFEFOLFN > 0) THEN
          BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;

       -- 138080 - Raphael Teodoro - 26/08/2020
       IF (BDBINSSFEFOLFN < 0) THEN
          BDBINSSFEFOLFN = 0;

       wpercrat = 0;
       wpercdescfpas = 0;
       wcontrcol = NULL;
       SELECT first 1 BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL, BDCATEGORIAESOCIAL
       FROM VRHF_EMP_TCOLCON_FGTSGPS
       WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prref
       order by BDREFCOL DESC
       INTO :wpercrat, :wpercdescfpas, :wcontrcol, :wcatesoc;
       IF (wcontrcol IS NULL) THEN
          wcontrcol = 0;
 
       IF (wcontrcol = 1) THEN
          bdbinssfn = wbaseinsscontratu - wabasemv;

       IF (bdbinssfn < 0) THEN
          bdbinssfn = 0;

       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BEGIN
            BDBRATAPOFN   = wbaseinss;   -- + wbaseinssfe;
            BDBRATAPOFEFN = wbaseinssfe;
            BDBRATAPO13FN = wbaseinss13;
          END
       ELSE
          BEGIN
            BDBRATAPOFN   = 0;
            BDBRATAPOFEFN = 0;
            BDBRATAPO13FN = 0;
          END

       BDSALFAMFN        = wsalfam;
       BDSALMATEMPFN     = wsalmatemp;
       BDBINSSMVFN       = wabasemv;
       BDBINSSMV13FN     = wabasemv13;
       BDVALREEMBOLSO    = wreemb;
       BDVALINDEVIDO     = wvindevido;
       BDPERCRATCOL      = wpercrat;
       BDPERCDESCFPASCOL = wpercdescfpas;

       if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and coalesce(wcatesoc, 0) in (731, 734)) then
          begin
            BDBINSS13APFN  = 0;
            BDBINSS13FN    = 0;
            BDBINSS13INDFN = 0;
            BDBINSSAPFN    = 0;
            BDBINSSFEFOLFN = 0;
            BDBINSSFN      = 0;
            BDBINSSMV13FN  = 0;
            BDBINSSMVFN    = 0;
          end
       SUSPEND;
     END
END^

/* Restore proc. body: SP_VRHF_DADOS_INSS_FN */
create or alter procedure SP_VRHF_DADOS_INSS_FN (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS varchar(15000) = null /* COLLATE WIN1252 - default */ ,
    PRCONTRATO integer = 0,
    PRSEPARARFOLHAS DM_BOOLEAN = 'FALSE' /* COLLATE WIN1252 - default */ )
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDCODCENTROS integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDPERCRATCOL numeric(18,6),
    BDPERCDESCFPASCOL numeric(18,6),
    BDCNPJEMP DM_CNPJ_CPF,
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDCOVID19FN numeric(18,6),
    BDBASEPIS numeric(15,2),
    BDBASEPIS13 numeric(15,2),
    BDCATEGORIAESOCIAL integer)
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(30000);
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WCLAVER varchar(20);
declare variable WTIPOCODVER integer;
declare variable WINSSVER integer;
declare variable WBASEGPSVER varchar(5);
declare variable WREEMBGPSVER varchar(5);
declare variable WVALOR numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WINSSFE numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WBASEINSS numeric(18,6);
declare variable WBASEINSSFE numeric(18,6);
declare variable WBASEINSS13 numeric(18,6);
declare variable WSALFAM numeric(18,6);
declare variable WSALMATEMP numeric(18,6);
declare variable WBASEMV numeric(18,6);
declare variable WBASEMV13 numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WBINSSAP numeric(18,6);
declare variable WBINSS13AP numeric(18,6);
declare variable WINSSAP numeric(18,6);
declare variable WINSS13AP numeric(18,6);
declare variable WAINSSAP numeric(18,6);
declare variable WAINSS13AP numeric(18,6);
declare variable WABASEMV numeric(18,6);
declare variable WABASEMV13 numeric(18,6);
declare variable WEMPAP integer;
declare variable WSOMAAP numeric(18,6);
declare variable WTABINSS integer;
declare variable WSQLINSS varchar(1500);
declare variable WALIQINSS numeric(18,6);
declare variable WFAIXAINSS numeric(18,6);
declare variable WCODSIND integer;
declare variable WLIMSIND integer;
declare variable WLIMEMP integer;
declare variable WCONTRCOL integer;
declare variable WREEMB numeric(18,6);
declare variable WREFRESC integer;
declare variable WBMULTVINC numeric(18,6);
declare variable WVMULTVINC numeric(18,6);
declare variable WVINDEVIDO numeric(18,6);
declare variable WVINDEVIDOSF numeric(18,6);
declare variable WBAVPREV numeric(18,6);
declare variable WTEMVALOR smallint;
declare variable WPERCDESCFPAS numeric(18,6);
declare variable WSINDATU integer;
declare variable WBASEINSSCONTR numeric(18,6);
declare variable WBASEINSSCONTRATU numeric(18,6);
declare variable WGRUPOCLA integer;
declare variable WINTERMITENTE DM_BOOLEAN;
declare variable WCLATRIB integer;
declare variable WCOOP integer;
declare variable WCATESOC integer;
declare variable WVERDEAMARELO varchar(5);
declare variable WSALMIN numeric(15,2);
declare variable WCOVID19 numeric(18,6);
declare variable WINCIDEPIS DM_BOOLEAN;
declare variable WBASEPIS numeric(18,6);
declare variable WBASEPIS13 numeric(18,6);
declare variable WBINSSRATINT numeric(18,6);
declare variable WBINSSANT numeric(18,6);
declare variable WCATEGORIAESOCIAL integer;
declare variable WDIFINCIDVER DM_BOOLEAN;
declare variable WSQLDIFINSSGPS varchar(300);
declare variable WCODVER integer;
declare variable WDESCVER varchar(60);
BEGIN
  -- Obtem valor de variável de contexto e limpa os valores da tabela temporária da sessão atual
  WSQLDIFINSSGPS = 'SELECT RDB$GET_CONTEXT(''USER_SESSION'', ''W_DIFINCIDVER'') FROM RDB$DATABASE';
  execute statement WSQLDIFINSSGPS into :WDIFINCIDVER;

  BDCNPJEMP = null;
  wsql = 'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFN, FN.BDCODVER, VERREF.BDDESCVER, FN.BDBINSSMVFN, FN.BDBINSSMV13FN, FN.BDINSSAPFN, FN.BDINSS13APFN, VERREF.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, '||
                'VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, FN.BDBASEINSSNMVNOVO, '||
                ' BDINTERM, '||
                'case when COALESCE(FGTSGPS.BDCATEGORIACOL, 0) = 7 and COALESCE(FGTSGPS.BDCATEGORIAESOCIAL, 0) in (107,108) then ''TRUE'' else ''FALSE'' end BDVERDEAMARELO, VERREF.BDPISVER, FGTSGPS.BDCATEGORIAESOCIAL from (';

  if (coalesce(prcontrato, 0) = 0) then
     begin
  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFN, FN.BDCODVER, FOLN.BDBINSSMVFN, FOLN.BDBINSSMV13FN, FOLN.BDINSSAPFN, FOLN.BDINSS13APFN,''FALSE''BDINTERM, '||
                    'case when coalesce(FOLN.BDBASEINSSNMVNOVO, 0) <> 0 then FOLN.BDBASEINSSNMVNOVO else FOLN.BDBINSSFN end BDBASEINSSNMVNOVO from (';
     
  IF (prfiliais IS NOT NULL AND prfiliais <> '') THEN
     BEGIN
       wsql = wsql||'select BDCODEMP from TEMPRESAS where ((';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||prcodemp||') or (';
     
       wsql = wsql||prfiliais||'))) FILIAIS ';
       wsql = wsql||'join VRHF_EMP_TVERBAFN FN on (FN.BDCODEMP = FILIAIS.BDCODEMP';
     
      IF (prref IS NOT NULL AND prref <> 0) THEN
         wsql = wsql||' and FN.BDREFFN = '||prref;
     
      wsql = wsql||') ';
     END
  ELSE
    BEGIN
      wsql = wsql||'select * from VRHF_EMP_TVERBAFN ';
     
      wwhere  = '';
     
      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         BEGIN
           wwhere = wwhere||prcodemp;
    
           IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
              BEGIN
                IF (wwhere <> '') THEN
                   wwhere = wwhere||' and ';
         
                wwhere = wwhere||prcodcol;
              END
         END
    
      IF (prref IS NOT NULL AND prref <> 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'BDREFFN = '||prref||' ';
         END
    
    
      IF (wwhere <> '') THEN
         wwhere = ' where '||wwhere;
    
      wsql = wsql||wwhere;
    
      wsql = wsql||') FN ';
    END
     
  wsql = wsql||'join VRHF_EMP_TFOLHANORMAL FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFFN = FN.BDREFFN) ';
       wsql = wsql||' union all ';
     end

  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFN, FN.BDCODVER, FOLN.BDBINSSMVFN, FOLN.BDBINSSMV13FN, FOLN.BDINSSAPFN, FOLN.BDINSS13APFN,''TRUE'' BDINTERM, '||
                   'case when coalesce(FOLN.BDBASEINSSNMVNOVO, 0) <> 0 then FOLN.BDBASEINSSNMVNOVO else FOLN.BDBINSSFN end BDBASEINSSNMVNOVO from (';

  IF (prfiliais IS NOT NULL AND prfiliais <> '') THEN
     BEGIN
       wsql = wsql||'select BDCODEMP from TEMPRESAS where ((';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||prcodemp||') or (';

       wsql = wsql||prfiliais||'))) FILIAIS ';
       wsql = wsql||'join VRHF_EMP_TVERBAINT FN on (FN.BDCODEMP = FILIAIS.BDCODEMP';

      IF (prref IS NOT NULL AND prref <> 0) THEN
         wsql = wsql||' and FN.BDREFFN = '||prref;

      wsql = wsql||') ';

      if (coalesce(prcontrato, 0) > 0) then
         begin
           if (wwhere <> '') then
              wwhere = wwhere||' and ';
           wwhere = wwhere||'FN.BDCODCONTTI = '||prcontrato||' ';
         end
     END
  ELSE
    BEGIN
      wsql = wsql||'select * from VRHF_EMP_TVERBAINT ';

      wwhere  = '';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         BEGIN
           wwhere = wwhere||prcodemp;
    
           IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
              BEGIN
                IF (wwhere <> '') THEN
                   wwhere = wwhere||' and ';
         
                wwhere = wwhere||prcodcol;
              END
         END
    
      IF (prref IS NOT NULL AND prref <> 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'BDREFFN = '||prref||' ';
         END
    
      IF (coalesce(prcontrato,0) > 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';

           wwhere = wwhere||'BDCODCONTTI = '||prcontrato||' ';
         END
    
      IF (wwhere <> '') THEN
         wwhere = ' where '||wwhere;
    
      wsql = wsql||wwhere;
    
      wsql = wsql||') FN ';
    END

  wsql = wsql||'join VRHF_EMP_TFOLHAINT FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFFN = FN.BDREFFN and FOLN.BDCODCONTTI = FN.BDCODCONTTI) ';

  wsql = wsql||') FN ';

     wsql = wsql||'left outer join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';
  wsql = wsql||'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS FGTSGPS on (FGTSGPS.BDCODEMP = FN.BDCODEMP and FGTSGPS.BDCODCOL = FN.BDCODCOL) ';
  wsql = wsql||'where VERREF.BDCODVER is not null ';

  wsql = wsql||'order by FN.BDCODEMP,FN.BDCODCOL ';

  wempatu     = 0;
  wcolatu     = 0;
  wsalfam     = 0;
  winss       = 0;
  winssfe     = 0;
  winss13     = 0;
  wbaseinss   = 0;
  wbaseinssfe = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wbasemv     = 0;
  wbasemv13   = 0;
  wbinssap    = 0;
  wbinss13ap  = 0;
  wainssap    = 0;
  wainss13ap  = 0;
  wabasemv    = 0;
  wabasemv13  = 0;
  wempap      = 0;
  wsomaap     = 0;
  wreemb      = 0;
  wvindevido  = 0;
  wvindevidosf = 0;
  wbavprev     = 0;
  wtemvalor = 0;
  wsindatu = 0;
  wcodsind = -1;
  wclatrib = null;
  wcoop    = null;
  wcatesoc = null;
  wcovid19 = 0;
  wbasepis = 0;
  wbasepis13   = 0;
  WBINSSRATINT = 0;
  wcodver = 0;
  wdescver = '';

  EXECUTE PROCEDURE sp_seta_competencia(prref);

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wvalor, :wcodver, :wdescver, :wbasemv, :wbasemv13, :winssap, :winss13ap, :wclaver, :wtipocodver, :winssver, :wbasegpsver,
                                  :wreembgpsver, :wbaseinsscontr, :wintermitente, :wverdeamarelo, :wincidepis, :wcategoriaesocial DO
  BEGIN
    IF (wempatu = 0) THEN
      BEGIN
        wempatu = wcodemp;
        wlimemp = NULL;
        SELECT first 1 BDLIMINARAVPREVEMP FROM VRHF_BASE_TEMPCALC WHERE BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
        INTO :wlimemp;
        IF (wlimemp IS NULL) THEN
           wlimemp = 0;    -- não possui liminar

        wclatrib = null;
        wcoop    = null;
        select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
        into :wclatrib, :wcoop;

        wclatrib = coalesce(wclatrib, 0);
        wcoop    = coalesce(wcoop, 0);

      END

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    /*
      Retorna bases de INSS
    */


    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol)) THEN
       BEGIN
         --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a versão com a alteração abaixo corretamente.
         wcodsind = NULL;
         SELECT first 1 BDCODSINTRAB FROM VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC
         INTO :wcodsind;

         IF (wsindatu <> wcodsind) THEN
           BEGIN
             wlimsind = NULL;
             wsindatu = wcodsind;
             IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
                SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wsindatu INTO :wlimsind;
             IF (wlimsind IS NULL) THEN
                wlimsind = 0;             -- não possui liminar
           END

         IF (wempatu <> wcodemp) THEN
           BEGIN
             wlimemp = NULL;
             SELECT first 1 BDLIMINARAVPREVEMP FROM VRHF_BASE_TEMPCALC WHERE BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
             INTO :wlimemp;
             IF (wlimemp IS NULL) THEN
                wlimemp = 0;    -- não possui liminar

             wclatrib = null;
             wcoop    = null;
             select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
             into :wclatrib, :wcoop;
             wclatrib = coalesce(wclatrib, 0);
             wcoop    = coalesce(wcoop, 0);

           END

         BDGPSSEFIP     = 0;
         BDCODEMP       = wempatu;
         BDCODCOL       = wcolatu;
         BDREFFN        = prref;
         BDCODCENTROS   = NULL;
         BDCODTPCC      = NULL;
         BDINSSFN       = winss;
         BDINSSFEFOLFN  = winssfe;
         BDINSS13FN     = winss13;
         BDBAVPREV      = 0;
         BDBASEPIS      = wbasepis;
         BDBASEPIS13    = wbasepis13;

         if (bdbasepis < 0) then
           bdbasepis = 0;
         if (bdbasepis13 < 0) then
           bdbasepis13 = 0;

         bdcategoriaesocial = wcategoriaesocial;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSSFN = wbinssap;
         ELSE
            BDBINSSFN = wbaseinss;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13FN = wbaseinss13 - wbinss13ap;
         ELSE
            BDBINSS13FN = wbaseinss13;

         BDBINSSFEFOLFN = wbaseinssfe;
         BDBINSSAPFN    = wbinssap;
         BDBINSS13APFN  = wbinss13ap;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13INDFN = 0;
         ELSE
            BDBINSS13INDFN = wbinss13ap;


           if (BDBINSS13FN < 0) then
              begin
                BDBINSS13FN = 0;
                if (NOT ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6)))) THEN
                  bdbinss13fn = coalesce(wbinss13ap, 0);
              end

         --IF (BDINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
         --   BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;

         if (BDBINSSFEFOLFN > 0 and BDBINSSFN < 0) then
            BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;

         -- 138080 - Raphael Teodoro - 26/08/2020
         IF (BDBINSSFEFOLFN < 0) THEN
            BDBINSSFEFOLFN = 0;

         wpercrat      = 0;
         wpercdescfpas = 0;
         wcontrcol     = NULL;
         wcatesoc      = null;
         SELECT first 1 BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL, BDCATEGORIAESOCIAL
         FROM VRHF_EMP_TCOLCON_FGTSGPS
         WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prref
         order by BDREFCOL DESC
         INTO :wpercrat, :wpercdescfpas, :wcontrcol, :wcatesoc;
         wcatesoc = coalesce(wcatesoc, 0);
         bdcategoriaesocial = wcatesoc;
         wcontrcol = coalesce(wcontrcol, 0);

         -- 136305 - Raphael Teodoro - 21/08/2020
         wgrupocla = 0;
         SELECT CLA.BDGRUPOCLA
         FROM VW_VRH_EMP_TCOLCON_VINC VINC
         LEFT OUTER JOIN VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
         WHERE (VINC.BDCODEMP = :wempatu)
           AND (VINC.BDCODCOL = :wcolatu)
           AND (VINC.BDREFCOL <= :prref)
         ORDER BY BDCODEMP DESC, BDCODCOL DESC, BDREFCOL DESC
         INTO :wgrupocla;

         IF (wcontrcol = 1) THEN
            bdbinssfn = wbaseinsscontratu - wabasemv;

         IF (bdbinssfn < 0) THEN
            bdbinssfn = 0;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BEGIN
              BDBRATAPOFN   = BDBINSSFN;     --+ BDBINSSFEFOLFN;
              BDBRATAPOFEFN = BDBINSSFEFOLFN;
              BDBRATAPO13FN = BDBINSS13FN;
            END
         ELSE
            BEGIN
              BDBRATAPOFN   = 0;
              BDBRATAPOFEFN = 0;
              BDBRATAPO13FN = 0;
            END

         if (wsalmatemp < 0) then
           wsalmatemp = 0;

         BDCOVID19FN       = wcovid19;
         BDSALFAMFN        = wsalfam;
         BDSALMATEMPFN     = wsalmatemp;
         BDBINSSMVFN       = wabasemv;
         BDBINSSMV13FN     = wabasemv13;
         BDINSSAPFN        = wainssap;
         BDINSS13APFN      = wainss13ap;
         BDVALREEMBOLSO    = wreemb;
         BDVALINDEVIDO     = wvindevido;
         BDVALINDEVIDOSF   = wvindevidosf;
         BDPERCRATCOL      = wpercrat;
         BDPERCDESCFPASCOL = wpercdescfpas;

         if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and wcatesoc in (731, 734)) then
            begin
              BDBINSS13APFN  = 0;
              BDBINSS13FN    = 0;
              BDBINSS13INDFN = 0;
              BDBINSSAPFN    = 0;
              BDBINSSFEFOLFN = 0;
              BDBINSSFN      = 0;
              BDBINSSMV13FN  = 0;
              BDBINSSMVFN    = 0;
            end

         if ((wcontrcol = 0) and
             (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
            begin
              if (WBINSSRATINT > 0) then
                begin
                  WBINSSANT = BDBINSSFN;

                  BDBINSSFN = BDBINSSFN - WBINSSRATINT;

                  if (BDBINSSFN < 0) then
                    BDBINSSFN = 0;
                end

              BDBASERAT = BDBINSSFN + BDBINSSFEFOLFN + WBINSSRATINT;

              if (BDBINSS13FN > 0) then
                 BDBASERAT = BDBASERAT + BDBINSS13FN;
              if (WBINSSRATINT > 0) then
                BDBINSSFN = WBINSSANT;
            end
         else
            BDBASERAT = 0;

         BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
         BDBASEINSS13 = BDBINSS13FN;

         if (wcatesoc IN (107, 108)) then
            begin
              BDBINSSFN = BDBINSSFN + BDBINSS13FN;
              BDBINSS13FN = 0;

              select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREF order by bdrefsm DESC INTO :WSALMIN;
              if (BDBINSSFN > WSALMIN * 1.5) then
                 begin
                   BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                 end
              else
                 begin
                   BDBINSSFN = 0;
                 end
            end

         /*SUSPEND;*/

         IF (prref >= 200903 and PRREF < 201606 AND prgpssefip = 1 AND wsomaap <> 0) THEN
            BEGIN
              BDGPSSEFIP     = 1;
              BDCODEMP       = wempatu;
              BDCODCOL       = wcolatu;
              BDREFFN        = prref;
              BDCODCENTROS   = NULL;
              BDCODTPCC      = NULL;
              BDBAVPREV      = wbavprev;

              wrefresc = NULL;
              SELECT BDREFRESCISAO FROM VRH_EMP_TRESCISAO WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu AND BDREFRESCISAO = :prref INTO :wrefresc;

              IF (wcontrcol = 0 AND wrefresc = prref) THEN
                 BEGIN
                   IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
                      BEGIN
                        BDINSSFN  = wainssap;
                        BDBINSSFN = wbinssap;
                      END
                   ELSE
                      BEGIN
                        IF ((wbinssap <> 0) OR (wtemvalor = 1)) THEN
                           BEGIN
                             IF (wbinssap < 0) THEN
                               wbinssap = 0;

                             BDBINSSFN = wbinssap;
                             wbinssap = wbinssap + wbaseinssfe;
                             wbmultvinc = 0;
                             wvmultvinc = 0;
                             wsqlinss = 'SELECT SUM(BDBASEINSSNCOL), SUM(BDVALORINSSNCOL) FROM SP_VRHF_EMP_TCOLCON_MVINC(''BDCODEMP = '||wempatu||''', ''BDCODCOL = '||wcolatu||''', '||prref||', 0, 0)';
                             execute statement wsqlinss INTO :wbmultvinc, :wvmultvinc;
                             BDBINSSFN = BDBINSSFN + wbmultvinc;

                             SELECT COALESCE(BDCODINSS, 0) FROM VW_VRHF_BASE_TEMPVINC WHERE BDCODEMP = :wempatu INTO :wtabinss;
                             IF (wtabinss = 0) THEN
                                wtabinss = 1;
     
                             waliqinss = 0;
                             wsqlinss = 'select first 1 COALESCE(X.BDALIQINSS, 0) '||
                                        'from VRHF_TABELAS_TINSSFAIXAS X '||
                                        'join ('||
                                          'select BDCODINSS, MAX(BDREFINSS) BDREFINSS from VRHF_TABELAS_TINSSFAIXAS '||
                                          'where BDREFINSS <= '||prref||' and BDCODINSS = '||wtabinss||' '||
                                          'group by BDCODINSS '||
                                        ') Y on (Y.BDCODINSS = X.BDCODINSS and Y.BDREFINSS = X.BDREFINSS) '||
                                        'where X.BDFAIXAINSS >= '||wbinssap||' order by X.BDFAIXAINSS ';
     
                             EXECUTE STATEMENT wsqlinss INTO :waliqinss;
     
                             IF ((waliqinss = 0) OR (waliqinss IS NULL)) THEN
                                BEGIN
                                  wsqlinss = 'select MAX(X.BDFAIXAINSS), MAX(X.BDALIQINSS) '||
                                             'from VRHF_TABELAS_TINSSFAIXAS X '||
                                             'join ('||
                                               'select BDCODINSS, MAX(BDREFINSS) BDREFINSS from VRHF_TABELAS_TINSSFAIXAS '||
                                               'where BDREFINSS <= '||prref||' and BDCODINSS = '||wtabinss||' '||
                                               'group by BDCODINSS '||
                                             ') Y on (Y.BDCODINSS = X.BDCODINSS and Y.BDREFINSS = X.BDREFINSS) '||
                                             'group by X.BDCODINSS, X.BDREFINSS ';
     
                                  wfaixainss = 0;
                                  waliqinss  = 0;
                                  EXECUTE STATEMENT wsqlinss INTO :wfaixainss, :waliqinss;
     
                                  IF (wfaixainss IS NULL) THEN
                                     wfaixainss = 0;
     
                                  IF (waliqinss IS NULL) THEN
                                     waliqinss = 0;
     
                                  BDINSSFN = wfaixainss * waliqinss / 100;
                                END
                             ELSE
                                BDINSSFN = wbinssap * waliqinss / 100;
     
                             BDBINSSFN = BDBINSSFN - wbmultvinc;
                             BDINSSFN = CAST(BDINSSFN - 0.005 AS NUMERIC(15,2)); /* cortar */
                             BDINSSFN = BDINSSFN - winssfe - wvmultvinc;
                           END
                        ELSE
                           BEGIN
                             BDINSSFN = winss;
                             BDBINSSFN = wbaseinss;
                           END
                      END
                 END
              ELSE
                 BEGIN
                   BDINSSFN = winss;
                   BDBINSSFN = wbaseinss;
                 END

              BDINSSFEFOLFN     = winssfe;
              BDINSS13FN        = wainss13ap;
              BDBINSSFEFOLFN    = wbaseinssfe;
              BDBINSSAPFN       = wbinssap;
              BDBINSS13FN       = wbaseinss13;
              BDBINSS13APFN     = wbinss13ap;
              BDBINSS13INDFN    = wbinss13ap;
              BDPERCRATCOL      = wpercrat;
              BDPERCDESCFPASCOL = wpercdescfpas;

              IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
                 BEGIN
                   BDBRATAPOFN   = BDBINSSFN;   -- + BDBINSSFEFOLFN;
                   BDBRATAPOFEFN = BDBINSSFEFOLFN;
                   BDBRATAPO13FN = BDBINSS13FN;
                 END
              ELSE
                 BEGIN
                   BDBRATAPOFN   = 0;
                   BDBRATAPOFEFN = 0;
                   BDBRATAPO13FN = 0;
                 END

              if (wsalmatemp < 0) then
                wsalmatemp = 0;
     
              BDCOVID19FN    = wcovid19;
              BDSALFAMFN     = wsalfam;
              BDSALMATEMPFN  = wsalmatemp;
              BDBINSSMVFN    = wabasemv;
              BDBINSSMV13FN  = wabasemv13;
              BDINSSAPFN     = wainssap;
              BDINSS13APFN   = wainss13ap;
              BDVALREEMBOLSO = wreemb;
              BDVALINDEVIDO  = wvindevido;
              BDVALINDEVIDOSF  = wvindevidosf;

              --IF (BDINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
              --   BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;

              if (BDBINSSFEFOLFN > 0 and BDBINSSFN < 0) then
                 BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;

              -- 138080 - Raphael Teodoro - 26/08/2020
              IF (BDBINSSFEFOLFN < 0) THEN
                 BDBINSSFEFOLFN = 0;

              if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and wcatesoc in (731, 734)) then
                 begin
                   BDBINSS13APFN  = 0;
                   BDBINSS13FN    = 0;
                   BDBINSS13INDFN = 0;
                   BDBINSSAPFN    = 0;
                   BDBINSSFEFOLFN = 0;
                   BDBINSSFN      = 0;
                   BDBINSSMV13FN  = 0;
                   BDBINSSMVFN    = 0;
                 end

              if ((wcontrcol = 0) and
                  (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
                 begin
                   BDBASERAT = BDBINSSFN + BDBINSSFEFOLFN;
                   if (BDBINSS13FN > 0) then
                      BDBASERAT = BDBASERAT + BDBINSS13FN;
                 end
              else
                 BDBASERAT = 0;

              BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
              BDBASEINSS13 = BDBINSS13FN;

              if (wcatesoc in (107, 108)) then
            begin
                   BDBINSSFN = BDBINSSFN + BDBINSS13FN;
                   BDBINSS13FN = 0;

                   select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREF order by bdrefsm DESC INTO :WSALMIN;
                   if (BDBINSSFN > WSALMIN * 1.5) then
                      begin
                        BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                      end
                   else
                      begin
                        BDBINSSFN = 0;
                      end
                 end

              SUSPEND;
            END
          else
            suspend;

         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wsalfam     = 0;
         winss       = 0;
         winssfe     = 0;
         winss13     = 0;
         wbaseinss   = 0;
         wbaseinssfe = 0;
         wbaseinss13 = 0;
         wsalmatemp  = 0;
         wbinssap    = 0;
         wbinss13ap  = 0;
         wainssap    = 0;
         wainss13ap  = 0;
         wabasemv    = 0;
         wabasemv13  = 0;
         wreemb      = 0;
         wvindevido  = 0;
         wvindevidosf = 0;
         wbavprev     = 0;
         wtemvalor   = 0;
         wcovid19    = 0;
         wbasepis    = 0;
         wbasepis13  = 0;
         WBINSSRATINT = 0;
       END

    wainssap   = winssap;
    wainss13ap = winss13ap;
    wabasemv   = wbasemv;
    wabasemv13 = wbasemv13;
    wbaseinsscontratu = wbaseinsscontr;

    IF (prref >= 200903 and PRREF < 201606 AND prgpssefip = 1 AND wempap <> wcodemp) THEN
       BEGIN
         wsomaap = 0;

         SELECT SUM(BDSOMA) FROM (
           SELECT X.bdvalvfn BDSOMA FROM vrhf_emp_tverbafn X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :prref and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvft BDSOMA FROM vrhf_emp_tverbatomador X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :prref and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvfn BDSOMA FROM vrhf_emp_tverbaint X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :prref and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvft BDSOMA FROM vrhf_emp_tverbatomint X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :prref and Y.BDCODVER is not null
         )
         INTO :wsomaap;
         wempap = wcodemp;
       END

    wgrupocla = 0;
    SELECT CLA.BDGRUPOCLA
    FROM VW_VRH_EMP_TCOLCON_VINC VINC
    LEFT OUTER JOIN VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
    WHERE (VINC.BDCODEMP = :wempatu)
      AND (VINC.BDCODCOL = :wcolatu)
      AND (VINC.BDREFCOL <= :prref)
    ORDER BY BDCODEMP DESC, BDCODCOL DESC, BDREFCOL DESC
    INTO :wgrupocla;

    -- INSS folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.0') THEN
       winss = winss + wvalor;

    -- INSS férias demonstradas na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.2') THEN
       winssfe = winssfe + wvalor;

    -- INSS 13o. rescisão descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;

    if (WINTERMITENTE = 'TRUE') then
       begin
         -- INSS 13o. descontado na folha normal
         IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.6') THEN
            winss13 = winss13 + wvalor;
       end

    IF (wverdeamarelo = 'TRUE') THEN
       begin
         -- INSS 13o. descontado na folha normal
         IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.3') THEN
            winss13 = winss13 + wvalor;
       end

    -- Base de INSS folha normal
    IF ((winssver = 1)) THEN
       BEGIN
         IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200') OR (SUBSTRING(wclaver FROM 1 FOR 7) = '0.180.1')) THEN
            BEGIN
              IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
       END
    ELSE
    IF ((winssver = 0)) THEN  --não incide
       BEGIN
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
         ELSE
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss13 = wbaseinss13 + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss13 = wbaseinss13 - wvalor;
            END
       END

    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 2) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END
    ELSE
    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 1 AND SUBSTRING(wclaver FROM 1 FOR 5) >= '0.100' AND SUBSTRING(wclaver FROM 1 FOR 5) < '0.200' AND (SUBSTRING(wclaver FROM 1 FOR 7) <> '0.180.1')) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END

    -- Base de INSS 13o. salário descontado na rescisão
    IF ((winssver = 3)) THEN
       BEGIN
         IF (PRSEPARARFOLHAS = 'TRUE') THEN
           BEGIN
             IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                wbaseinss13 = wbaseinss13 + wvalor;
             ELSE
             IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                wbaseinss13 = wbaseinss13 - wvalor;
           END
         ELSE
           BEGIN
             IF ((wtipocodver = 0) AND (SUBSTRING(wclaver FROM 1 FOR 9) = '0.800.6.2')) THEN  -- Provento
               begin
                wbaseinss13 = wbaseinss13 + wvalor;
--                WBINSSRATINT = WBINSSRATINT + wvalor;
               end
             ELSE
             IF ((wtipocodver = 1) AND (SUBSTRING(wclaver FROM 1 FOR 9) = '0.800.6.2')) THEN  -- Desconto
               begin
                wbaseinss13 = wbaseinss13 - wvalor;
--                WBINSSRATINT = WBINSSRATINT - wvalor;
               end
             ELSE
             IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                wbaseinss13 = wbaseinss13 + wvalor;
             ELSE
             IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                wbaseinss13 = wbaseinss13 - wvalor;
           END
       END

    -- Verifica diferença de incidência de PIS e Base GPS
    if (coalesce(UPPER(WDIFINCIDVER), 'FALSE') = 'TRUE') then
       begin
         if ((wbasegpsver <> wincidepis) and (WGRUPOCLA not in (2, 3))) then
            begin
              WSQLDIFINSSGPS = 'update or insert into VRHF_TINFO_TEMP_DIFINCIDVER (BDSESSAO, BDCODEMP, BDCODVER, BDDESCVER) '||
                               'values ('||current_connection||', '||wcodemp||', '||wcodver||', '''||wdescver||''') matching (BDSESSAO, BDCODEMP, BDCODVER)';
              execute statement WSQLDIFINSSGPS;
            end
       end


    -- Valor base PIS
    if (coalesce(UPPER(wincidepis), 'FALSE') = 'TRUE') then
      BEGIN
         IF (winssver = 3) THEN
           BEGIN
             IF (wtipocodver = 0) THEN  -- Provento
                wbasepis13 = wbasepis13 + wvalor;
             ELSE
               IF (wtipocodver = 1) THEN  -- Desconto
                  wbasepis13 = wbasepis13 - wvalor;
           END
         ELSE
           BEGIN
             IF (wtipocodver = 0) THEN  -- Provento
                wbasepis = wbasepis + wvalor;
             ELSE
               IF (wtipocodver = 1) THEN  -- Desconto
                  wbasepis = wbasepis - wvalor;
           END
      END

    -- Valor de salário família
    IF (SUBSTRING(wclaver FROM 1 FOR 7) = '9.050.0' AND wtipocodver = 0) THEN
       wsalfam = wsalfam + wvalor;

    -- Valor do COVID-19
    IF (SUBSTRING(wclaver FROM 1 FOR 7) = '9.050.1') THEN
       wcovid19 = wcovid19 + wvalor;

    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.2') THEN  --  Valores indevidos da GPS
       wvindevido = wvindevido + wvalor;

    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.0') THEN  --  Valores SF indevidos da GPS
       wvindevidosf = wvindevidosf + wvalor;

    -- Base de salário maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005') OR
         (SUBSTRING(wclaver FROM 1 FOR 7) = '7.061.2') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.070')OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.710'))) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END

    -- Base INSS sem o aviso prévio indenizado
    IF (SUBSTRING(wclaver FROM 1 FOR 7) <> '7.001.3') THEN
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200') OR (SUBSTRING(wclaver FROM 1 FOR 7) = '0.180.1')) THEN
                 BEGIN
                   IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
              ELSE
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinss13ap = wbinss13ap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinss13ap = wbinss13ap - wvalor;

                   wtemvalor = 1;
                 END
            END
       END
    ELSE
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200') OR (SUBSTRING(wclaver FROM 1 FOR 7) = '0.180.1')) THEN
                 BEGIN
                   IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 7, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
       END

    -- INSS sobre o aviso prévio indenizado do 13º salário
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '7.060') THEN
       BEGIN
         IF (winssver = 3) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbinss13ap = wbinss13ap + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbinss13ap = wbinss13ap - wvalor;
            END
       END

  END


  IF ((wempatu <> 0) AND (wcolatu <> 0)) THEN
     BEGIN
       wcodsind = NULL;
       wlimemp = NULL;
       wlimsind = NULL;
       SELECT first 1 BDCODSINTRAB FROM VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC
       INTO :wcodsind;
       IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
          BEGIN
            SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
          END
 
       IF (wlimsind IS NULL) THEN
          wlimsind = 0;             -- não possui liminar
 
       IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
          SELECT first 1 BDLIMINARAVPREVEMP FROM VRHF_BASE_TEMPCALC WHERE BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
          INTO :wlimemp;
 
       IF (wlimemp IS NULL) THEN
          wlimemp = 0;    -- não possui liminar

       wclatrib = null;
       wcoop    = null;
       select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
       into :wclatrib, :wcoop;
       wclatrib = coalesce(wclatrib, 0);
       wcoop    = coalesce(wcoop, 0);

       BDGPSSEFIP     = 0;
       BDCODEMP       = wempatu;
       BDCODCOL       = wcolatu;
       BDREFFN        = prref;
       BDCODCENTROS   = NULL;
       BDCODTPCC      = NULL;
       BDINSSFN       = winss;
       BDINSSFEFOLFN  = winssfe;
       BDINSS13FN     = winss13;
       BDBINSSFEFOLFN = wbaseinssfe;
       BDBINSSAPFN    = wbinssap;
       BDBINSS13APFN  = wbinss13ap;
       BDINSSAPFN     = wainssap;
       BDINSS13APFN   = wainss13ap;
       BDBAVPREV      = 0;

       IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
          BDBINSSFN = wbinssap;
       ELSE
          BDBINSSFN = wbaseinss;


       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13FN = wbaseinss13 - wbinss13ap;
       ELSE
          BDBINSS13FN = wbaseinss13;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13INDFN = 0;
       ELSE
          BDBINSS13INDFN = wbinss13ap;

       if (BDBINSS13FN < 0) then
          begin
            BDBINSS13FN = 0;
            if (NOT ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6)))) THEN
              bdbinss13fn = coalesce(wbinss13ap, 0);
          end

       --IF (BDINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
       --   BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;

       if (BDBINSSFEFOLFN > 0 and BDBINSSFN < 0) then
          BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;

       -- 138080 - Raphael Teodoro - 26/08/2020
       IF (BDBINSSFEFOLFN < 0) THEN
          BDBINSSFEFOLFN = 0;

       wpercrat = 0;
       wpercdescfpas = 0;
       wcontrcol = NULL;
       SELECT first 1 BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL, BDCATEGORIAESOCIAL
       FROM VRHF_EMP_TCOLCON_FGTSGPS
       WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prref
       order by BDREFCOL DESC
       INTO :wpercrat, :wpercdescfpas, :wcontrcol, :wcatesoc;
       wcatesoc = coalesce(wcatesoc, 0);
       wcontrcol = coalesce(wcontrcol, 0);
       bdcategoriaesocial = coalesce(wcatesoc,0);

--       -- 136305 - Raphael Teodoro - 21/08/2020
--       wgrupocla = 0;
--       SELECT CLA.BDGRUPOCLA
--       FROM VW_VRH_EMP_TCOLCON_VINC VINC
--       LEFT OUTER JOIN VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
--       WHERE (VINC.BDCODEMP = :wempatu)
--         AND (VINC.BDCODCOL = :wcolatu)
--         AND (VINC.BDREFCOL <= :prref)
--       ORDER BY BDCODEMP DESC, BDCODCOL DESC, BDREFCOL DESC
--       INTO :wgrupocla;

       IF (wcontrcol = 1) THEN
          bdbinssfn = wbaseinsscontratu - wabasemv;

       IF (bdbinssfn < 0) THEN
          bdbinssfn = 0;

       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BEGIN
            BDBRATAPOFN   = wbaseinss;   -- + wbaseinssfe;
            BDBRATAPOFEFN = wbaseinssfe;
            BDBRATAPO13FN = wbaseinss13;
          END
       ELSE
          BEGIN
            BDBRATAPOFN   = 0;
            BDBRATAPOFEFN = 0;
            BDBRATAPO13FN = 0;
          END

       if (wsalmatemp < 0) then
         wsalmatemp = 0;

       BDCOVID19FN       = wcovid19;
       BDSALFAMFN        = wsalfam;
       BDSALMATEMPFN     = wsalmatemp;
       BDBINSSMVFN       = wabasemv;
       BDBINSSMV13FN     = wabasemv13;
       BDVALREEMBOLSO    = wreemb;
       BDVALINDEVIDO     = wvindevido;
       BDPERCRATCOL      = wpercrat;
       BDPERCDESCFPASCOL = wpercdescfpas;

       if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and wcatesoc in (731, 734)) then
          begin
            BDBINSS13APFN  = 0;
            BDBINSS13FN    = 0;
            BDBINSS13INDFN = 0;
            BDBINSSAPFN    = 0;
            BDBINSSFEFOLFN = 0;
            BDBINSSFN      = 0;
            BDBINSSMV13FN  = 0;
            BDBINSSMVFN    = 0;
          end

       if ((wcontrcol = 0) and
           (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
          begin
            BDBASERAT = BDBINSSFN + BDBINSSFEFOLFN;
            if (BDBINSS13FN > 0) then
               BDBASERAT = BDBASERAT + BDBINSS13FN;
          end
       else
          BDBASERAT = 0;

       BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
       BDBASEINSS13 = BDBINSS13FN;

       if (wcatesoc in (107, 108)) then
          begin
            BDBINSSFN = BDBINSSFN + BDBINSS13FN;
            BDBINSS13FN = 0;

            select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREF order by bdrefsm DESC INTO :WSALMIN;
            if (BDBINSSFN > WSALMIN * 1.5) then
               begin
                 BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
               end
            else
               begin
                 BDBINSSFN = 0;
               end
          end

       /*SUSPEND;*/
       bdbasepis = wbasepis;
       bdbasepis13 = wbasepis13;

       if (bdbasepis < 0) then
         bdbasepis = 0;
       if (bdbasepis13 < 0) then
         bdbasepis13 = 0;
         
       IF (prRef >= 200903 and PRREF < 201606 AND prgpssefip = 1 AND wsomaap <> 0) THEN
          BEGIN
            BDGPSSEFIP     = 1;
            BDCODEMP       = wempatu;
            BDCODCOL       = wcolatu;
            BDREFFN        = prref;
            BDCODCENTROS   = NULL;
            BDCODTPCC      = NULL;
            BDBAVPREV      = wbavprev;

            wrefresc = NULL;
            SELECT BDREFRESCISAO FROM VRH_EMP_TRESCISAO WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu AND BDREFRESCISAO = :prref INTO :wrefresc;
            IF (wcontrcol = 0 AND wrefresc = prref) THEN
               BEGIN
                 IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
                    BEGIN
                      BDINSSFN  = wainssap;
                      BDBINSSFN = wbinssap;
                    END
                 ELSE
                    BEGIN
                      IF ((wbinssap <> 0) OR (wtemvalor = 1)) THEN
                         BEGIN
                           IF (wbinssap < 0) THEN
                             wbinssap = 0;

                           BDBINSSFN = wbinssap;
                           wbinssap = wbinssap + wbaseinssfe;
     
                           wbmultvinc = 0;
                           wvmultvinc = 0;
                           wsqlinss = 'SELECT SUM(BDBASEINSSNCOL), SUM(BDVALORINSSNCOL) FROM SP_VRHF_EMP_TCOLCON_MVINC(''BDCODEMP = '||wempatu||''', ''BDCODCOL = '||wcolatu||''', '||prref||', 0, 0)';
                           execute statement wsqlinss INTO :wbmultvinc, :wvmultvinc;
                           BDBINSSFN = BDBINSSFN + wbmultvinc;

                           SELECT COALESCE(BDCODINSS, 0) FROM VW_VRHF_BASE_TEMPVINC WHERE BDCODEMP = :wempatu INTO :wtabinss;
                           IF (wtabinss = 0) THEN
                              wtabinss = 1;
     
                           waliqinss = 0;
                           wsqlinss = 'select first 1 COALESCE(X.BDALIQINSS, 0) '||
                                      'from VRHF_TABELAS_TINSSFAIXAS X '||
                                      'join ('||
                                        'select BDCODINSS, MAX(BDREFINSS) BDREFINSS from VRHF_TABELAS_TINSSFAIXAS '||
                                        'where BDREFINSS <= '||prref||' and BDCODINSS = '||wtabinss||' '||
                                        'group by BDCODINSS '||
                                      ') Y on (Y.BDCODINSS = X.BDCODINSS and Y.BDREFINSS = X.BDREFINSS) '||
                                      'where X.BDFAIXAINSS >= '||wbinssap||' order by X.BDFAIXAINSS ';
     
                           EXECUTE STATEMENT wsqlinss INTO :waliqinss;
     
                           IF ((waliqinss = 0) OR (waliqinss IS NULL)) THEN
                              BEGIN
                                wsqlinss = 'select MAX(X.BDFAIXAINSS), MAX(X.BDALIQINSS) '||
                                           'from VRHF_TABELAS_TINSSFAIXAS X '||
                                           'join ('||
                                             'select BDCODINSS, MAX(BDREFINSS) BDREFINSS from VRHF_TABELAS_TINSSFAIXAS '||
                                             'where BDREFINSS <= '||prref||' and BDCODINSS = '||wtabinss||' '||
                                             'group by BDCODINSS '||
                                           ') Y on (Y.BDCODINSS = X.BDCODINSS and Y.BDREFINSS = X.BDREFINSS) '||
                                           'group by X.BDCODINSS, X.BDREFINSS ';
     
                                wfaixainss = 0;
                                waliqinss  = 0;
                                EXECUTE STATEMENT wsqlinss INTO :wfaixainss, :waliqinss;
     
                                IF (wfaixainss IS NULL) THEN
                                   wfaixainss = 0;
     
                                IF (waliqinss IS NULL) THEN
                                   waliqinss = 0;
     
                                BDINSSFN = wfaixainss * waliqinss / 100;
                              END
                           ELSE
                              BDINSSFN = wbinssap * waliqinss / 100;
     
                           BDBINSSFN = BDBINSSFN - wbmultvinc;
                           BDINSSFN = CAST(BDINSSFN - 0.005 AS NUMERIC(15,2)); /* cortar */
                           BDINSSFN = BDINSSFN - winssfe - wvmultvinc;
     
                         END
                      ELSE
                         BEGIN
                           BDINSSFN = winss;
                           BDBINSSFN = wbaseinss;
                         END
                    END
               END
            ELSE
               BEGIN
                 BDINSSFN = winss;
                 BDBINSSFN = wbaseinss;
               END

            BDINSSFEFOLFN     = winssfe;
            BDINSS13FN        = wainss13ap;
            BDBINSSFEFOLFN    = wbaseinssfe;
            BDBINSS13FN       = wbaseinss13;
            BDBINSSAPFN       = wbinssap;
            BDBINSS13APFN     = wbinss13ap;
            BDBINSS13INDFN    = wbinss13ap;
            BDINSSAPFN        = wainssap;
            BDINSS13APFN      = wainss13ap;
            BDPERCRATCOL      = wpercrat;
            BDPERCDESCFPASCOL = wpercdescfpas;
     
            IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
               BEGIN
                 BDBRATAPOFN   = BDBINSSFN;    -- + BDBINSSFEFOLFN;
                 BDBRATAPOFEFN = BDBINSSFEFOLFN;
                 BDBRATAPO13FN = BDBINSS13FN;
               END
            ELSE
               BEGIN
                 BDBRATAPOFN   = 0;
                 BDBRATAPOFEFN = 0;
                 BDBRATAPO13FN = 0;
               END
     
            BDCOVID19FN    = wcovid19;
            BDSALFAMFN     = wsalfam;
            BDSALMATEMPFN  = wsalmatemp;
     
            BDBINSSMVFN    = wabasemv;
            BDBINSSMV13FN  = wabasemv13;
            BDVALREEMBOLSO = wreemb;
            BDVALINDEVIDO  = wvindevido;

            --IF (BDINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
            --   BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;

            if (BDBINSSFEFOLFN > 0 and BDBINSSFN < 0) then
               BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;

            -- 138080 - Raphael Teodoro - 26/08/2020
            IF (BDBINSSFEFOLFN < 0) THEN
               BDBINSSFEFOLFN = 0;

            if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and wcatesoc in (731, 734)) then
               begin
                 BDBINSS13APFN  = 0;
                 BDBINSS13FN    = 0;
                 BDBINSS13INDFN = 0;
                 BDBINSSAPFN    = 0;
                 BDBINSSFEFOLFN = 0;
                 BDBINSSFN      = 0;
                 BDBINSSMV13FN  = 0;
                 BDBINSSMVFN    = 0;
               end

            if ((wcontrcol = 0) and
                (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
               begin
                 BDBASERAT = BDBINSSFN + BDBINSSFEFOLFN;
                 if (BDBINSS13FN > 0) then
                    BDBASERAT = BDBASERAT + BDBINSS13FN;
               end
            else
               BDBASERAT = 0;

            BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
            BDBASEINSS13 = BDBINSS13FN;

            if (wcatesoc in (107, 108)) then
               begin
                 BDBINSSFN = BDBINSSFN + BDBINSS13FN;
                 BDBINSS13FN = 0;

                 select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREF order by bdrefsm DESC INTO :WSALMIN;
                 if (BDBINSSFN > WSALMIN * 1.5) then
                    begin
                      BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                    end
                 else
                    begin
                      BDBINSSFN = 0;
                    end
               end

         SUSPEND;
          END
        ELSE
          SUSPEND;
     END

END^

/* Restore proc. body: SP_ESOCIAL_DADOS_INSS_FT */
create or alter procedure SP_ESOCIAL_DADOS_INSS_FT (
    PRCODEMP varchar(15000),
    PRREF integer,
    PRCONTRATO integer = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDPERCRATCOL numeric(18,6),
    BDPERCDESCFPASCOL numeric(18,6),
    BDCNPJEMP DM_CNPJ_CPF)
as
declare variable WCCNULL integer;
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(32000);
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WCENTROS integer;
declare variable WCENTROSATU integer;
declare variable WCC integer;
declare variable WCCATU integer;
declare variable WCLAVER varchar(20);
declare variable WTIPOCODVER integer;
declare variable WINSSVER integer;
declare variable WBASEGPSVER varchar(5);
declare variable WREEMBGPSVER varchar(5);
declare variable WVALOR numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WINSSFE numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WBASEINSS numeric(18,6);
declare variable WBASEINSSFE numeric(18,6);
declare variable WBASEINSS13 numeric(18,6);
declare variable WSALFAM numeric(18,6);
declare variable WSALMATEMP numeric(18,6);
declare variable WBASEMV numeric(18,6);
declare variable WBASEMV13 numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WBINSSAP numeric(18,6);
declare variable WBINSS13AP numeric(18,6);
declare variable WINSSAP numeric(18,6);
declare variable WINSS13AP numeric(18,6);
declare variable WAINSSAP numeric(18,6);
declare variable WAINSS13AP numeric(18,6);
declare variable WABASEMV numeric(18,6);
declare variable WABASEMV13 numeric(18,6);
declare variable WCODSIND integer;
declare variable WLIMSIND integer;
declare variable WLIMEMP integer;
declare variable WREEMB numeric(18,6);
declare variable WVINDEVIDO numeric(18,6);
declare variable WVINDEVIDOSF numeric(18,6);
declare variable WBAVPREV numeric(18,6);
declare variable WPERCDEDFPAS numeric(18,6);
declare variable WSINDATU integer;
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WCONTRCOL integer;
declare variable WBASEINSSCONTRATU numeric(18,6);
declare variable WINTERMITENTE DM_BOOLEAN;
declare variable WCNPJANT DM_CNPJ_CPF;
declare variable WCNPJEMP DM_CNPJ_CPF;
declare variable WCLATRIB integer;
declare variable WCOOP integer;
declare variable WCATESOC integer;
BEGIN
  wsql = 'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFT, FN.BDBINSSMVFT, FN.BDBINSSMV13FT, FN.BDINSSAPFT, FN.BDINSS13APFT, VERREF.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, '||
                'VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, PREP.BDORDEM, PREP.BDCODCENTRO, PREP.BDCODTPCC,'||
                'case when COALESCE(FGTSGPS.BDCATEGORIACOL, 0) = 4 and COALESCE(FGTSGPS.BDCATEGORIAESOCIAL, 0) = 111 then ''TRUE'' else ''FALSE'' end BDINTERM, FN.BDCNPJEMP '||
         'from (';

  if (coalesce(prcontrato, 0) = 0) then
     begin
       wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFT, FN.BDCODVER, FN.BDORDEM, FOLN.BDBINSSMVFT, FOLN.BDBINSSMV13FT, FOLN.BDINSSAPFT, FOLN.BDINSS13APFT, FILIAIS.BDCNPJEMP '||
                    'from (';
          
       if (coalesce(prcodemp, '') <> '') then
          wsql = wsql||'select BDCODEMP, BDCNPJEMP from (';
       wsql = wsql||'select BDCODEMP, BDCNPJEMP from TEMPRESAS ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          begin
            wsql = wsql||'where (('||prcodemp||') or ('||replace(upper(prcodemp), 'BDCODEMP', 'BDCODMATRIZ')||'))';
            wsql = wsql||'union all select FIL.BDCODEMP, EMP.BDCNPJEMP from TEMPRESAS EMP ';
            wsql = wsql||'join TEMPRESAS FIL on (SUBSTRING(FIL.BDCNPJEMP FROM 1 FOR 10) = SUBSTRING(EMP.BDCNPJEMP FROM 1 FOR 10)) ';
            wsql = wsql||'where FIL.BDCODMATRIZ is null';
            wsql = wsql||' and '||replace(upper(prcodemp), 'BDCODEMP', 'EMP.BDCODEMP');
          end
     
       if (coalesce(prcodemp, '') <> '') then
          wsql = wsql||') group by BDCODEMP, BDCNPJEMP';
       wsql = wsql||') FILIAIS ';
       wsql = wsql||'join VRHF_EMP_TVERBATOMADOR FN on (FN.BDCODEMP = FILIAIS.BDCODEMP)';
       wsql = wsql||'left outer join VRHF_EMP_TFOLHATOMADOR FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFTOMADOR = FN.BDREFTOMADOR and FOLN.BDORDEM = FN.BDORDEM) ';
       wsql = wsql||'left outer join VRH_ESOCIAL_TFASEAMENTO FASEMP on (FASEMP.BDCODEMP = FN.BDCODEMP) ';
       wsql = wsql||'where FOLN.BDCODEMP is not null and FASEMP.BDCODEMP is not null and '||
                          '((coalesce(FASEMP.BDOPCAOESOCIAL, 0) = 1 and coalesce(FASEMP.BDREFINIDCTFWEB, 0) > 0 and FN.BDREFTOMADOR >= coalesce(FASEMP.BDREFINIDCTFWEB, 0)) or (coalesce(FASEMP.BDOPCAOESOCIAL, 0) = 2)) ';

       IF (prref IS NOT NULL AND prref <> 0) THEN
          wsql = wsql||' and FN.BDREFTOMADOR = '||prref;

       wsql = wsql||' union all ';
    end

  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFT, FN.BDCODVER, FN.BDORDEM, FOLN.BDBINSSMVFT, FOLN.BDBINSSMV13FT, FOLN.BDINSSAPFT, FOLN.BDINSS13APFT, FILIAIS.BDCNPJEMP '||
               'from (';

  if (coalesce(prcodemp, '') <> '') then
     wsql = wsql||'select BDCODEMP, BDCNPJEMP from (';
  wsql = wsql||'select BDCODEMP, BDCNPJEMP from TEMPRESAS ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     begin
       wsql = wsql||' where (('||prcodemp||') or ('||replace(upper(prcodemp), 'BDCODEMP', 'BDCODMATRIZ')||'))';
       wsql = wsql||'union all select FIL.BDCODEMP, EMP.BDCNPJEMP from TEMPRESAS EMP ';
       wsql = wsql||'join TEMPRESAS FIL on (SUBSTRING(FIL.BDCNPJEMP FROM 1 FOR 10) = SUBSTRING(EMP.BDCNPJEMP FROM 1 FOR 10)) ';
       wsql = wsql||'where FIL.BDCODMATRIZ is null';
       wsql = wsql||' and '||replace(upper(prcodemp), 'BDCODEMP', 'EMP.BDCODEMP');
     end

  if (coalesce(prcodemp, '') <> '') then
     wsql = wsql||') group by BDCODEMP, BDCNPJEMP';
  wsql = wsql||') FILIAIS ';
  wsql = wsql||'join VRHF_EMP_TVERBATOMINT FN on (FN.BDCODEMP = FILIAIS.BDCODEMP) ';
  wsql = wsql||'left outer join VRHF_EMP_TFOLHATOMINT FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFTOMADOR = FN.BDREFTOMADOR and FOLN.BDORDEM = FN.BDORDEM and FOLN.BDCODCONTTI = FN.BDCODCONTTI) ';
  wsql = wsql||'left outer join VRH_ESOCIAL_TFASEAMENTO FASEMP on (FASEMP.BDCODEMP = FN.BDCODEMP) ';
  wsql = wsql||'where FOLN.BDCODEMP is not null and FASEMP.BDCODEMP is not null and '||
                     '((coalesce(FASEMP.BDOPCAOESOCIAL, 0) = 1 and coalesce(FASEMP.BDREFINIDCTFWEB, 0) > 0 and FN.BDREFTOMADOR >= coalesce(FASEMP.BDREFINIDCTFWEB, 0)) or (coalesce(FASEMP.BDOPCAOESOCIAL, 0) = 2)) ';

 IF (prref IS NOT NULL AND prref <> 0) THEN
    wsql = wsql||' and FN.BDREFTOMADOR = '||prref;

 if (coalesce(prcontrato, 0) > 0) then
    wsql = wsql||' and FN.BDCODCONTTI = '||prcontrato||' ';

  wsql = wsql||') FN ';

  wsql = wsql||'join VRHF_EMP_TPREPFN prep on (FN.bdcodemp = prep.bdcodemp and FN.bdcodcol = prep.bdcodcol and FN.bdordem = prep.bdordem) ';

  wsql = wsql||'left outer join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';
  wsql = wsql||'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS FGTSGPS on (FGTSGPS.BDCODEMP = FN.BDCODEMP and FGTSGPS.BDCODCOL = FN.BDCODCOL) ';
  wsql = wsql||'where VERREF.BDCODVER is not null ';
  wsql = wsql||'order by FN.BDCODEMP,FN.BDCODCOL,PREP.BDCODCENTRO,PREP.BDCODTPCC ';

  wempatu     = 0;
  wcolatu     = 0;
  wordematu   = 0;
  wcentrosatu = 0;
  wccatu      = 0;
  wsalfam     = 0;
  winss       = 0;
  winssfe     = 0;
  winss13     = 0;
  wbaseinss   = 0;
  wbaseinssfe = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wbinssap    = 0;
  wbinss13ap  = 0;
  wainssap    = 0;
  wainss13ap  = 0;
  wabasemv    = 0;
  wabasemv13  = 0;
  wreemb      = 0;
  wvindevido  = 0;
  wvindevidosf = 0;
  wbavprev     = 0;
  wsindatu = 0;
  wcodsind = -1;
  wcnpjant = null;
  wclatrib = null;
  wcoop    = null;
  wcatesoc = null;

  EXECUTE PROCEDURE sp_seta_competencia(prref);

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wvalor, :wbasemv, :wbasemv13, :winssap, :winss13ap, :wclaver, :wtipocodver, :winssver, :wbasegpsver, :wreembgpsver,
                                  :wordem, :wcentros, :wcc, :wintermitente, :wcnpjemp DO
  BEGIN
    IF (wempatu = 0) THEN
      BEGIN
        wempatu = wcodemp;
        wlimemp = NULL;
        SELECT first 1 BDLIMINARAVPREVEMP FROM VRHF_BASE_TEMPCALC WHERE BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
        INTO :wlimemp;
        IF (wlimemp IS NULL) THEN
           wlimemp = 0;    -- não possui liminar

        select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
        into :wclatrib, :wcoop;
        wclatrib = coalesce(wclatrib, 0);
        wcoop    = coalesce(wcoop, 0);
      END

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wcentrosatu = 0) THEN
       wcentrosatu = wcentros;

    IF (wccatu = 0) THEN
       wccatu = wcc;

    IF (wordematu = 0) THEN
       wordematu = wordem;

    if (wcnpjant is null) then
       wcnpjant = coalesce(wcnpjemp, '');

    wCCNull = 0;
    IF ((wccatu IS NULL) AND (wcc IS NOT NULL)) THEN
       wccnull = 1;
    IF ((wccatu IS NOT NULL) AND (wcc IS NULL)) THEN
       wccnull = 1;

    /*
      Retorna bases de INSS
    */
    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wcentrosatu <> wcentros) OR (wccatu <> wcc) OR (wCCNull = 1)) THEN
       BEGIN
         --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a versão com a alteração abaixo corretamente.
         wcodsind = NULL;
         wwhere = 'select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFCOL <= '||prref||' order by BDREFCOL DESC';

         EXECUTE STATEMENT wwhere INTO :wcodsind;

         IF (wsindatu <> wcodsind) THEN
           BEGIN
             wlimsind = NULL;
             wsindatu = wcodsind;
             IF (wsindatu IS NOT NULL AND wsindatu <> 0) THEN
               SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wsindatu INTO :wlimsind;
             IF (wlimsind IS NULL) THEN
                wlimsind = 0;             -- não possui liminar
           END

         IF (wempatu <> wcodemp) THEN
           BEGIN
             wlimemp = NULL;
             SELECT first 1 BDLIMINARAVPREVEMP FROM VRHF_BASE_TEMPCALC WHERE BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
             INTO :wlimemp;
             IF (wlimemp IS NULL) THEN
                wlimemp = 0;    -- não possui liminar

             wclatrib = null;
             wcoop    = null;
             select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
             into :wclatrib, :wcoop;
             wclatrib = coalesce(wclatrib, 0);
             wcoop    = coalesce(wcoop, 0);
           END

         BDGPSSEFIP     = 3;
         BDCODEMP       = wempatu;
         BDCODCOL       = wcolatu;
         BDREFFN        = prref;
         BDORDEM        = wordematu;
         BDCODCENTRO    = wcentrosatu;
         BDCODTPCC      = wccatu;
         BDINSSFN       = winss;
         BDINSSFEFOLFN  = winssfe;
         BDINSS13FN     = winss13;
         BDBINSSFEFOLFN = wbaseinssfe;
         BDBINSSAPFN    = wbinssap;
         BDBINSS13INDFN = wbinss13ap;
         BDBINSS13APFN  = wbinss13ap;
         BDINSSAPFN     = wainssap;
         BDINSS13APFN   = wainss13ap;
         BDBAVPREV      = 0;
         BDCNPJEMP      = wcnpjant;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSS13INDFN = 0;
         ELSE
            BDBINSS13INDFN = wbinss13ap;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSSFN = wbinssap;
         ELSE
            BDBINSSFN = wbaseinss;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13FN = wbaseinss13 - wbinss13ap;
         ELSE
            BDBINSS13FN = wbaseinss13;


         IF (BDBINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
            BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;

         IF (BDBINSSFN < 0 AND BDBINSSFEFOLFN > 0) THEN
            BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;

         -- 138080 - Raphael Teodoro - 26/08/2020
         IF (BDBINSSFEFOLFN < 0) THEN
            BDBINSSFEFOLFN = 0;

         wpercrat = 0;
         wpercdedfpas = 0;
         wcatesoc = null;
         SELECT first 1 BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL, BDCATEGORIAESOCIAL
         FROM VRHF_EMP_TCOLCON_FGTSGPS
         WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prref
         order by BDREFCOL DESC
         INTO :wpercrat, :wpercdedfpas, :wcontrcol, :wcatesoc;

         IF (wcontrcol = 1) THEN
            begin
              wwhere = 'select SUM(FT.BDBINSSFT) from (select BDCODEMP,BDCODCOL,BDREFTOMADOR,BDORDEM,case when coalesce(BDBASEINSSNMVNOVO, 0) <> 0 then BDBASEINSSNMVNOVO else BDBINSSFT end BDBINSSFT from VRHF_EMP_TFOLHATOMADOR '||
                                                      'where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFTOMADOR = '||prref||
                                                      ' union all '||
                                                      'select BDCODEMP,BDCODCOL,BDREFTOMADOR,BDORDEM,BDBINSSFT from VRHF_EMP_TFOLHATOMINT '||
                                                      'where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFTOMADOR = '||prref||
                       ') FT '||
                       'left outer join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FT.BDCODEMP and PFN.BDCODCOL = FT.BDCODCOL and PFN.BDORDEM = FT.BDORDEM) '||
                       'where FT.BDCODEMP = '||wempatu||' and FT.BDCODCOL = '||wcolatu||' and FT.BDREFTOMADOR = '||prref||' and COALESCE(PFN.BDCODCENTRO, 0) = '||COALESCE(:wcentrosatu, 0)||
                       case when COALESCE(:wccatu, 0) = 0 then ' and PFN.BDCODTPCC is null ' else ' and PFN.BDCODTPCC = '||COALESCE(:wccatu, 0) end;
              execute statement wwhere into :wbaseinsscontratu;
              wbaseinsscontratu = COALESCE(:wbaseinsscontratu, 0);
              BDBINSSFN = wbaseinsscontratu - wabasemv;
            end

         IF (BDBINSSFN < 0) THEN
            BDBINSSFN = 0;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BEGIN
              BDBRATAPOFN   = BDBINSSFN;   -- + BDBINSSFEFOLFN;
              BDBRATAPOFEFN = BDBINSSFEFOLFN;
              BDBRATAPO13FN = BDBINSS13FN;
            END
         ELSE
            BEGIN
              BDBRATAPOFN   = 0;
              BDBRATAPOFEFN = 0;
              BDBRATAPO13FN = 0;
            END

         BDSALFAMFN        = wsalfam;
         BDSALMATEMPFN     = wsalmatemp;
         BDBINSSMVFN       = wabasemv;
         BDBINSSMV13FN     = wabasemv13;
         BDVALREEMBOLSO    = wreemb;
         BDVALINDEVIDO     = wvindevido;
         BDVALINDEVIDOSF   = wvindevidosf;
         BDPERCRATCOL      = wpercrat;
         BDPERCDESCFPASCOL = wpercdedfpas;

         if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and coalesce(wcatesoc, 0) in (731, 734)) then
            begin
              BDBINSS13APFN  = 0;
              BDBINSS13FN    = 0;
              BDBINSS13INDFN = 0;
              BDBINSSAPFN    = 0;
              BDBINSSFEFOLFN = 0;
              BDBINSSFN      = 0;
              BDBINSSMV13FN  = 0;
              BDBINSSMVFN    = 0;
            end

         SUSPEND;

         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wordematu   = wordem;
         wcentrosatu = wcentros;
         wccatu      = wcc;
         wsalfam     = 0;
         winss       = 0;
         winssfe     = 0;
         winss13     = 0;
         wbaseinss   = 0;
         wbaseinssfe = 0;
         wbaseinss13 = 0;
         wsalmatemp  = 0;
         wbinssap    = 0;
         wbinss13ap  = 0;
         wainssap    = 0;
         wainss13ap  = 0;
         wabasemv    = 0;
         wabasemv13  = 0;
         wreemb      = 0;
         wvindevido  = 0;
         wvindevidosf = 0;
         wbavprev     = 0;
         wcnpjant     = coalesce(wcnpjemp, '');
       END

    wainssap   = winssap;
    wainss13ap = winss13ap;
    wabasemv   = wbasemv;
    wabasemv13 = wbasemv13;

    -- INSS folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.0') THEN
       winss = winss + wvalor;

    -- INSS férias demonstradas na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.2') THEN
       winssfe = winssfe + wvalor;

    -- INSS 13o. rescisão descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;

    if (wintermitente = 'TRUE') then
       begin
         -- INSS 13o. descontado na folha normal
         IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.6') THEN
            winss13 = winss13 + wvalor;
       end

    -- Base de INSS folha normal
    IF ((winssver = 1)) THEN
       BEGIN
         IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
       END
    ELSE
    IF ((winssver = 0)) THEN  --não incide
       BEGIN
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
         ELSE
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss13 = wbaseinss13 + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss13 = wbaseinss13 - wvalor;
            END
       END

    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 2) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END
    ELSE
    IF (winssver = 1 AND SUBSTRING(wclaver FROM 1 FOR 5) >= '0.100' AND SUBSTRING(wclaver FROM 1 FOR 5) < '0.200') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END

    -- Base de INSS 13o. salário descontado na rescisão
    IF ((winssver = 3)) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       END

    -- Valor de salário família
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '9.050') THEN
       wsalfam = wsalfam + wvalor;

    -- Valor indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.2') THEN
       wvindevido = wvindevido + wvalor;

    -- Valor SF indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.0') THEN
       wvindevidosf = wvindevidosf + wvalor;

    -- Base de salário maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005') OR
         (SUBSTRING(wclaver FROM 1 FOR 7) = '7.061.2') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.710'))) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END

    -- Base de INSS folha normal sem o aviso prévio indenizado
    IF (SUBSTRING(wclaver FROM 1 FOR 7) <> '7.001.3') THEN
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;
                 END
              ELSE
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinss13ap = wbinss13ap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinss13ap = wbinss13ap - wvalor;
                 END
            END
       END
    ELSE
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 7, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
       END

    -- INSS sobre o aviso prévio indenizado do 13º salário
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '7.060') THEN
       BEGIN
         IF (winssver = 3) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbinss13ap = wbinss13ap + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbinss13ap = wbinss13ap - wvalor;
            END
       END

  END

  IF ((wempatu <> 0) AND (wcolatu <> 0) AND ((wccatu <> 0) OR (wccatu IS NULL))) THEN
     BEGIN
       wcodsind = NULL;
       wlimemp = NULL;
       wlimsind = NULL;
       SELECT first 1 BDCODSINTRAB FROM VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC
       INTO :wcodsind;
       IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
          BEGIN
            SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
          END

       IF (wlimsind IS NULL) THEN
          wlimsind = 0;             -- não possui liminar

       IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
          SELECT first 1 BDLIMINARAVPREVEMP FROM VRHF_BASE_TEMPCALC WHERE BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
          INTO :wlimemp;

       IF (wlimemp IS NULL) THEN
          wlimemp = 0;    -- não possui liminar

       wclatrib = null;
       wcoop    = null;
       select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
       into :wclatrib, :wcoop;
       wclatrib = coalesce(wclatrib, 0);
       wcoop    = coalesce(wcoop, 0);

       BDGPSSEFIP     = 3;
       BDCODEMP       = wempatu;
       BDCODCOL       = wcolatu;
       BDREFFN        = prref;
       BDORDEM        = wordematu;
       BDCODCENTRO    = wcentrosatu;
       BDCODTPCC      = wccatu;
       BDINSSFN       = winss;
       BDINSSFEFOLFN  = winssfe;
       BDINSS13FN     = winss13;
       BDBINSSFEFOLFN = wbaseinssfe;
       BDBINSSAPFN    = wbinssap;
       BDBINSS13APFN  = wbinss13ap;
       BDINSSAPFN     = wainssap;
       BDINSS13APFN   = wainss13ap;
       BDBAVPREV      = 0;
       BDCNPJEMP      = coalesce(wcnpjemp, '');

       IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
          BDBINSSFN = wbinssap;
       ELSE
          BDBINSSFN = wbaseinss;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13INDFN = 0;
       ELSE
          BDBINSS13INDFN = wbinss13ap;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13FN = wbaseinss13 - wbinss13ap;
       ELSE
          BDBINSS13FN = wbaseinss13;

       IF (BDBINSSFN+BDBINSSFEFOLFN < 0) THEN
          BEGIN
            BDBINSSFEFOLFN = 0;
            BDBINSSFN = 0;
          END


       /*Wesley Kowalski | 05/12/2018 | Descomentei a verificação abaixo */   
       IF (BDBINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
          BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;

       IF (BDBINSSFN < 0 AND BDBINSSFEFOLFN > 0) THEN
          BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;

       -- 138080 - Raphael Teodoro - 26/08/2020
       IF (BDBINSSFEFOLFN < 0) THEN
          BDBINSSFEFOLFN = 0;

       wpercrat = 0;
       wpercdedfpas = 0;
       wcatesoc = null;
       SELECT first 1 BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL, BDCATEGORIAESOCIAL
       FROM VRHF_EMP_TCOLCON_FGTSGPS
       WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prref
       order by BDREFCOL DESC
       INTO :wpercrat, :wpercdedfpas, :wcontrcol, :wcatesoc;

       IF (wcontrcol = 1) THEN
          begin
            wwhere = 'select SUM(FT.BDBINSSFT) from (select BDCODEMP,BDCODCOL,BDREFTOMADOR,BDORDEM,case when coalesce(BDBASEINSSNMVNOVO, 0) <> 0 then BDBASEINSSNMVNOVO else BDBINSSFT end BDBINSSFT from VRHF_EMP_TFOLHATOMADOR '||
                                                    'where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFTOMADOR = '||prref||
                                                    ' union all '||
                                                    'select BDCODEMP,BDCODCOL,BDREFTOMADOR,BDORDEM,BDBINSSFT from VRHF_EMP_TFOLHATOMINT '||
                                                    'where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFTOMADOR = '||prref||
                     ') FT '||
                     'left outer join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FT.BDCODEMP and PFN.BDCODCOL = FT.BDCODCOL and PFN.BDORDEM = FT.BDORDEM) '||
                     'where FT.BDCODEMP = '||wempatu||' and FT.BDCODCOL = '||wcolatu||' and FT.BDREFTOMADOR = '||prref||' and COALESCE(PFN.BDCODCENTRO, 0) = '||COALESCE(:wcentrosatu, 0)||
                     case when COALESCE(:wccatu, 0) = 0 then ' and PFN.BDCODTPCC is null ' else ' and PFN.BDCODTPCC = '||COALESCE(:wccatu, 0) end;
            execute statement wwhere into :wbaseinsscontratu;
            wbaseinsscontratu = COALESCE(:wbaseinsscontratu, 0);
            BDBINSSFN = wbaseinsscontratu - wabasemv;
          end

       IF (BDBINSSFN < 0) THEN
          BDBINSSFN = 0;

       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BEGIN
            BDBRATAPOFN   = wbaseinss;    -- + wbaseinssfe;
            BDBRATAPOFEFN = wbaseinssfe;
            BDBRATAPO13FN = wbaseinss13;
          END
       ELSE
          BEGIN
            BDBRATAPOFN   = 0;
            BDBRATAPOFEFN = 0;
            BDBRATAPO13FN = 0;
          END

       BDSALFAMFN        = wsalfam;
       BDSALMATEMPFN     = wsalmatemp;
       BDBINSSMVFN       = wabasemv;
       BDBINSSMV13FN     = wabasemv13;
       BDVALREEMBOLSO    = wreemb;
       BDVALINDEVIDO     = wvindevido;
       BDVALINDEVIDOSF   = wvindevidosf;
       BDPERCRATCOL      = wpercrat;
       BDPERCDESCFPASCOL = wpercdedfpas;

       if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and coalesce(wcatesoc, 0) in (731, 734)) then
       begin
         BDBINSS13APFN  = 0;
         BDBINSS13FN    = 0;
         BDBINSS13INDFN = 0;
         BDBINSSAPFN    = 0;
         BDBINSSFEFOLFN = 0;
         BDBINSSFN      = 0;
         BDBINSSMV13FN  = 0;
         BDBINSSMVFN    = 0;
       end
       SUSPEND;
     END
END^

/* Restore proc. body: SP_VRHF_DADOS_INSS_FT */
create or alter procedure SP_VRHF_DADOS_INSS_FT (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS varchar(15000) = null /* COLLATE WIN1252 - default */ ,
    PRCONTRATO integer = 0,
    PRORDEM integer = 0,
    PRSEPARARFOLHAS DM_BOOLEAN = 'FALSE' /* COLLATE WIN1252 - default */ )
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDPERCRATCOL numeric(18,6),
    BDPERCDESCFPASCOL numeric(18,6),
    BDCNPJEMP DM_CNPJ_CPF,
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDCOVID19FN numeric(18,6),
    BDBASEPIS numeric(15,2),
    BDBASEPIS13 numeric(15,2),
    BDCATEGORIAESOCIAL integer)
as
declare variable WCCNULL integer;
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(32000);
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WCENTROS integer;
declare variable WCENTROSATU integer;
declare variable WCC integer;
declare variable WCCATU integer;
declare variable WCLAVER varchar(20);
declare variable WTIPOCODVER integer;
declare variable WINSSVER integer;
declare variable WBASEGPSVER varchar(5);
declare variable WREEMBGPSVER varchar(5);
declare variable WVALOR numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WINSSFE numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WBASEINSS numeric(18,6);
declare variable WBASEINSSFE numeric(18,6);
declare variable WBASEINSS13 numeric(18,6);
declare variable WSALFAM numeric(18,6);
declare variable WSALMATEMP numeric(18,6);
declare variable WBASEMV numeric(18,6);
declare variable WBASEMV13 numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WBINSSAP numeric(18,6);
declare variable WBINSS13AP numeric(18,6);
declare variable WINSSAP numeric(18,6);
declare variable WINSS13AP numeric(18,6);
declare variable WAINSSAP numeric(18,6);
declare variable WAINSS13AP numeric(18,6);
declare variable WABASEMV numeric(18,6);
declare variable WABASEMV13 numeric(18,6);
declare variable WEMPAP integer;
declare variable WSOMAAP numeric(18,6);
declare variable WCODSIND integer;
declare variable WLIMSIND integer;
declare variable WLIMEMP integer;
declare variable WREEMB numeric(18,6);
declare variable WVINDEVIDO numeric(18,6);
declare variable WVINDEVIDOSF numeric(18,6);
declare variable WBAVPREV numeric(18,6);
declare variable WTEMVALOR smallint;
declare variable WPERCDEDFPAS numeric(18,6);
declare variable WSINDATU integer;
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WCONTRCOL integer;
declare variable WBASEINSSCONTRATU numeric(18,6);
declare variable WGRUPOCLA integer;
declare variable WINTERMITENTE DM_BOOLEAN;
declare variable WCLATRIB integer;
declare variable WCOOP integer;
declare variable WCATESOC integer;
declare variable WVERDEAMARELO DM_BOOLEAN;
declare variable WSALMIN numeric(15,2);
declare variable WCOVID19FN numeric(18,6);
declare variable WINCIDEPIS DM_BOOLEAN;
declare variable WBASEPIS numeric(18,6);
declare variable WBASEPIS13 numeric(18,6);
declare variable WBINSSRATINT numeric(18,6);
declare variable WBINSSANT numeric(18,6);
declare variable WCATEGORIAESOCIAL integer;
declare variable WBDBASEINSS13 numeric(18,6);
declare variable WDIFINCIDVER DM_BOOLEAN;
declare variable WSQLDIFINSSGPS varchar(300);
declare variable WCODVER integer;
declare variable WDESCVER varchar(60);
BEGIN
  -- Obtem valor de variável de contexto e limpa os valores da tabela temporária da sessão atual
  WSQLDIFINSSGPS = 'SELECT RDB$GET_CONTEXT(''USER_SESSION'', ''W_DIFINCIDVER'') FROM RDB$DATABASE';
  execute statement WSQLDIFINSSGPS into :WDIFINCIDVER;

  BDCNPJEMP = null;
  wsql = 'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFT, FN.BDCODVER, VERREF.BDDESCVER, FN.BDBINSSMVFT, FN.BDBINSSMV13FT, FN.BDINSSAPFT, FN.BDINSS13APFT, VERREF.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, '||
                'VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, PREP.BDORDEM, PREP.BDCODCENTRO, PREP.BDCODTPCC,'||
                ' BDINTERM, '||
                'case when COALESCE(FGTSGPS.BDCATEGORIACOL, 0) = 7 and COALESCE(FGTSGPS.BDCATEGORIAESOCIAL, 0) in (107,108) then ''TRUE'' else ''FALSE'' end BDVERDEAMARELO, VERREF.BDPISVER, FGTSGPS.BDCATEGORIAESOCIAL from (';

  if (coalesce(prcontrato, 0) = 0) then
     begin
  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFT, FN.BDCODVER, FN.BDORDEM, FOLN.BDBINSSMVFT, FOLN.BDBINSSMV13FT, FOLN.BDINSSAPFT, FOLN.BDINSS13APFT,''FALSE'' BDINTERM from (';
     
  IF (prfiliais IS NOT NULL AND prfiliais <> '') THEN
     BEGIN
       wsql = wsql||'select BDCODEMP from TEMPRESAS where ((';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||prcodemp||') or (';
     
       wsql = wsql||prfiliais||'))) FILIAIS ';
       wsql = wsql||'join VRHF_EMP_TVERBATOMADOR FN on (FN.BDCODEMP = FILIAIS.BDCODEMP';
     
      IF (prref IS NOT NULL AND prref <> 0) THEN
         wsql = wsql||' and FN.BDREFTOMADOR = '||prref;
     
      wsql = wsql||') ';
     END
  ELSE
    BEGIN
      wsql = wsql||'select * from VRHF_EMP_TVERBATOMADOR ';
      wwhere  = '';
    
      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wwhere = wwhere||prcodemp;
    
      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||prcodcol;
         END
    
      IF (prref IS NOT NULL AND prref <> 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'BDREFTOMADOR = '||prref||' ';
         END
    
    
      IF (wwhere <> '') THEN
         wwhere = ' where '||wwhere;
    
      wsql = wsql||wwhere;
    
      wsql = wsql||') FN ';
    END
     
  wsql = wsql||'join VRHF_EMP_TFOLHATOMADOR FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFTOMADOR = FN.BDREFTOMADOR and FOLN.BDORDEM = FN.BDORDEM) ';
       wsql = wsql||' union all ';
    end

  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFT, FN.BDCODVER, FN.BDORDEM, FOLN.BDBINSSMVFT, FOLN.BDBINSSMV13FT, FOLN.BDINSSAPFT, FOLN.BDINSS13APFT,''TRUE'' BDINTERM from (';

  IF (prfiliais IS NOT NULL AND prfiliais <> '') THEN
     BEGIN
       wsql = wsql||'select BDCODEMP from TEMPRESAS where ((';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||prcodemp||') or (';

       wsql = wsql||prfiliais||'))) FILIAIS ';
       wsql = wsql||'join VRHF_EMP_TVERBATOMINT FN on (FN.BDCODEMP = FILIAIS.BDCODEMP';

      IF (prref IS NOT NULL AND prref <> 0) THEN
         wsql = wsql||' and FN.BDREFTOMADOR = '||prref;

      wsql = wsql||') ';

      if (coalesce(prcontrato, 0) > 0) then
         wsql = wsql||' where FN.BDCODCONTTI = '||prcontrato||' ';

      if (coalesce(prordem, 0) > 0) then
         wsql = wsql||' where FN.BDORDEM = '||prordem||' ';

     END
  ELSE
    BEGIN
      wsql = wsql||'select * from VRHF_EMP_TVERBATOMINT ';
      wwhere  = '';
    
      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wwhere = wwhere||prcodemp;
    
      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||prcodcol;
         END
    
      IF (prref IS NOT NULL AND prref <> 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'BDREFTOMADOR = '||prref||' ';
         END
    
      IF (coalesce(prcontrato, 0) > 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'BDCODCONTTI = '||prcontrato||' ';
         END

      IF (coalesce(prordem, 0) > 0) THEN
         BEGIN
      IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'BDORDEM = '||prordem||' ';
         END

      IF (wwhere <> '') THEN
         wwhere = ' where '||wwhere;
    
      wsql = wsql||wwhere;
    
      wsql = wsql||') FN ';
    END

  wsql = wsql||'join VRHF_EMP_TFOLHATOMINT FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFTOMADOR = FN.BDREFTOMADOR and FOLN.BDORDEM = FN.BDORDEM and FOLN.BDCODCONTTI = FN.BDCODCONTTI) ';


  wsql = wsql||') FN ';

  wsql = wsql||'join VRHF_EMP_TPREPFN prep on (FN.bdcodemp = prep.bdcodemp and FN.bdcodcol = prep.bdcodcol and FN.bdordem = prep.bdordem) ';

     wsql = wsql||'left outer join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';
  wsql = wsql||'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS FGTSGPS on (FGTSGPS.BDCODEMP = FN.BDCODEMP and FGTSGPS.BDCODCOL = FN.BDCODCOL) ';
  wsql = wsql||'where VERREF.BDCODVER is not null ';
  wsql = wsql||'order by FN.BDCODEMP,FN.BDCODCOL,PREP.BDCODCENTRO,PREP.BDCODTPCC ';

  wempatu     = 0;
  wcolatu     = 0;
  wordematu   = 0;
  wcentrosatu = 0;
  wccatu      = 0;
  wsalfam     = 0;
  winss       = 0;
  winssfe     = 0;
  winss13     = 0;
  wbaseinss   = 0;
  wbaseinssfe = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wbinssap    = 0;
  wbinss13ap  = 0;
  wainssap    = 0;
  wainss13ap  = 0;
  wabasemv    = 0;
  wabasemv13  = 0;
  wempap      = 0;
  wsomaap     = 0;
  wreemb      = 0;
  wvindevido  = 0;
  wvindevidosf = 0;
  wbavprev     = 0;
  wtemvalor = 0;
  wsindatu = 0;
  wcodsind = -1;
  wclatrib = null;
  wcoop    = null;
  wcatesoc = null;
  wcovid19fn = 0;
  wbasepis   = 0;
  wbasepis13   = 0;
  wbinssratint = 0;
  WBDBASEINSS13 = 0;
  wcodver = 0;
  wdescver = '';

  EXECUTE PROCEDURE sp_seta_competencia(prref);

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wvalor, :wcodver, :wdescver, :wbasemv, :wbasemv13, :winssap, :winss13ap, :wclaver, :wtipocodver, :winssver, :wbasegpsver, :wreembgpsver,
                                  :wordem, :wcentros, :wcc, :wintermitente, :wverdeamarelo, :wincidepis, :wcategoriaesocial DO
  BEGIN
    IF (wempatu = 0) THEN
      BEGIN
        wempatu = wcodemp;
        wlimemp = NULL;
        SELECT first 1 BDLIMINARAVPREVEMP FROM VRHF_BASE_TEMPCALC WHERE BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
        INTO :wlimemp;
        IF (wlimemp IS NULL) THEN
           wlimemp = 0;    -- não possui liminar

        select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
        into :wclatrib, :wcoop;
        wclatrib = coalesce(wclatrib, 0);
        wcoop    = coalesce(wcoop, 0);

      END

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wcentrosatu = 0) THEN
       wcentrosatu = wcentros;

    IF (wccatu = 0) THEN
       wccatu = wcc;

    IF (wordematu = 0) THEN
       wordematu = wordem;

    wCCNull = 0;
    IF ((wccatu IS NULL) AND (wcc IS NOT NULL)) THEN
       wccnull = 1;
    IF ((wccatu IS NOT NULL) AND (wcc IS NULL)) THEN
       wccnull = 1;

    /*
      Retorna bases de INSS
    */
    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wcentrosatu <> wcentros) OR (wccatu <> wcc) OR (wCCNull = 1)) THEN
       BEGIN
         --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a versão com a alteração abaixo corretamente.
         wcodsind = NULL;
         wwhere = 'select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFCOL <= '||prref||' order by BDREFCOL DESC';

         EXECUTE STATEMENT wwhere INTO :wcodsind;

         IF (wsindatu <> wcodsind) THEN
           BEGIN
             wlimsind = NULL;
             wsindatu = wcodsind;
             IF (wsindatu IS NOT NULL AND wsindatu <> 0) THEN
               SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wsindatu INTO :wlimsind;
             IF (wlimsind IS NULL) THEN
                wlimsind = 0;             -- não possui liminar
           END

         IF (wempatu <> wcodemp) THEN
           BEGIN
             wlimemp = NULL;
             SELECT first 1 BDLIMINARAVPREVEMP FROM VRHF_BASE_TEMPCALC WHERE BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
             INTO :wlimemp;
             IF (wlimemp IS NULL) THEN
                wlimemp = 0;    -- não possui liminar

             wclatrib = null;
             wcoop    = null;
             select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
             into :wclatrib, :wcoop;
             wclatrib = coalesce(wclatrib, 0);
             wcoop    = coalesce(wcoop, 0);

           END

         BDGPSSEFIP     = 0;
         BDCODEMP       = wempatu;
         BDCODCOL       = wcolatu;
         BDREFFN        = prref;
         BDORDEM        = wordematu;
         BDCODCENTRO    = wcentrosatu;
         BDCODTPCC      = wccatu;
         BDINSSFN       = winss;
         BDINSSFEFOLFN  = winssfe;
         BDINSS13FN     = winss13;
         BDBINSSFEFOLFN = wbaseinssfe;
         BDBINSSAPFN    = wbinssap;
         BDBINSS13INDFN = wbinss13ap;
         BDBINSS13APFN  = wbinss13ap;
         BDINSSAPFN     = wainssap;
         BDINSS13APFN   = wainss13ap;
         BDBAVPREV      = 0;
         BDBASEPIS      = wbasepis;
         BDBASEPIS13    = wbasepis13;

         if (bdbasepis < 0) then
           bdbasepis = 0;
         if (bdbasepis13 < 0) then
           bdbasepis13 = 0;

         bdcategoriaesocial = wcategoriaesocial;


         if ((BDCODCENTRO is null and BDCODTPCC is not null) or (BDCODTPCC is null)) then
            begin
              select first 1 BDCODCENTROS from TEMPRESAS_REF where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC into :BDCODCENTRO;
            end

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSS13INDFN = 0;
         ELSE
            BDBINSS13INDFN = wbinss13ap;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSSFN = wbinssap;
         ELSE
            BDBINSSFN = wbaseinss;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13FN = wbaseinss13 - wbinss13ap;
         ELSE
            BDBINSS13FN = wbaseinss13;

         if (BDBINSS13FN < 0) then
          begin
          BDBINSS13FN = 0;
            if (NOT ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6)))) THEN
              bdbinss13fn = coalesce(wbinss13ap, 0);
          end

         --IF (BDINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
         --   BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;

         if (bdbinssfefolfn > 0 and bdbinssfn < 0) then
            BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;

         -- 138080 - Raphael Teodoro - 26/08/2020
         IF (BDBINSSFEFOLFN < 0) THEN
            BDBINSSFEFOLFN = 0;

         wpercrat = 0;
         wpercdedfpas = 0;
         wcatesoc = null;
         SELECT first 1 BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL, BDCATEGORIAESOCIAL
         FROM VRHF_EMP_TCOLCON_FGTSGPS
         WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prref
         order by BDREFCOL DESC
         INTO :wpercrat, :wpercdedfpas, :wcontrcol, :wcatesoc;
         wcatesoc = coalesce(wcatesoc, 0);
         wcontrcol = coalesce(wcontrcol, 0);
         BDCATEGORIAESOCIAL = coalesce(wcatesoc,0);

         -- 136305 - Raphael Teodoro - 21/08/2020
         wgrupocla = 0;
         SELECT CLA.BDGRUPOCLA
         FROM VW_VRH_EMP_TCOLCON_VINC VINC
         LEFT OUTER JOIN VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
         WHERE (VINC.BDCODEMP = :wempatu)
           AND (VINC.BDCODCOL = :wcolatu)
           AND (VINC.BDREFCOL <= :prref)
         ORDER BY BDCODEMP DESC, BDCODCOL DESC, BDREFCOL DESC
         INTO :wgrupocla;

/*         IF (wcontrcol = 1) THEN
            begin
              wwhere = 'select SUM(FT.BDBINSSFT) from (select BDCODEMP,BDCODCOL,BDREFTOMADOR,BDORDEM,case when coalesce(BDBASEINSSNMVNOVO, 0) <> 0 then BDBASEINSSNMVNOVO else BDBINSSFT end BDBINSSFT from VRHF_EMP_TFOLHATOMADOR '||
                                                      'where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFTOMADOR = '||prref||
                                                      ' union all '||
                                                      'select BDCODEMP,BDCODCOL,BDREFTOMADOR,BDORDEM,BDBINSSFT from VRHF_EMP_TFOLHATOMINT '||
                                                      'where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFTOMADOR = '||prref||
                       ') FT '||
                       'left outer join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FT.BDCODEMP and PFN.BDCODCOL = FT.BDCODCOL and PFN.BDORDEM = FT.BDORDEM) '||
                       'where FT.BDCODEMP = '||wempatu||' and FT.BDCODCOL = '||wcolatu||' and FT.BDREFTOMADOR = '||prref||' and COALESCE(PFN.BDCODCENTRO, 0) = '||COALESCE(:wcentrosatu, 0)||
                       case when COALESCE(:wccatu, 0) = 0 then ' and PFN.BDCODTPCC is null ' else ' and PFN.BDCODTPCC = '||COALESCE(:wccatu, 0) end;
              execute statement wwhere into :wbaseinsscontratu;
              wbaseinsscontratu = COALESCE(:wbaseinsscontratu, 0);
              BDBINSSFN = wbaseinsscontratu - wabasemv;
            end
*/
         IF (BDBINSSFN < 0) THEN
            BDBINSSFN = 0;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BEGIN
              BDBRATAPOFN   = BDBINSSFN;   -- + BDBINSSFEFOLFN;
              BDBRATAPOFEFN = BDBINSSFEFOLFN;
              BDBRATAPO13FN = BDBINSS13FN;
            END
         ELSE
            BEGIN
              BDBRATAPOFN   = 0;
              BDBRATAPOFEFN = 0;
              BDBRATAPO13FN = 0;
            END

         if (wsalmatemp < 0) then
           wsalmatemp = 0;

         BDCOVID19FN       = wcovid19fn;
         BDSALFAMFN        = wsalfam;
         BDSALMATEMPFN     = wsalmatemp;
         BDBINSSMVFN       = wabasemv;
         BDBINSSMV13FN     = wabasemv13;
         BDVALREEMBOLSO    = wreemb;
         BDVALINDEVIDO     = wvindevido;
         BDVALINDEVIDOSF   = wvindevidosf;
         BDPERCRATCOL      = wpercrat;
         BDPERCDESCFPASCOL = wpercdedfpas;

         if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and wcatesoc in (731, 734)) then
            begin
              BDBINSS13APFN  = 0;
              BDBINSS13FN    = 0;
              BDBINSS13INDFN = 0;
              BDBINSSAPFN    = 0;
              BDBINSSFEFOLFN = 0;
              BDBINSSFN      = 0;
              BDBINSSMV13FN  = 0;
              BDBINSSMVFN    = 0;
            end

         if ((wcontrcol = 0) and
             (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
            begin
              if (WBINSSRATINT > 0) then
                begin
                  -- Solicitação #204159 | Título: Totalizador S-5011 e Resumo | Controle para que a base INSS de décimo terceiro seja somada a base INSS normal de intermitentes.
                  WBINSSANT = BDBINSSFN + WBDBASEINSS13;

                  BDBINSSFN = (BDBINSSFN + WBDBASEINSS13) - WBINSSRATINT;

                  if (BDBINSSFN < 0) then
                    BDBINSSFN = 0;
                end

              BDBASERAT   = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN + WBINSSRATINT;

              if (WBINSSRATINT > 0) then
                BDBINSSFN = WBINSSANT;
            end
         else
            BDBASERAT = 0;

         BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
         BDBASEINSS13 = BDBINSS13FN;

         if (wcatesoc in (107, 108)) then
            begin
              BDBINSSFN = BDBINSSFN + BDBINSS13FN;
              BDBINSS13FN = 0;

              select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREF order by bdrefsm DESC INTO :WSALMIN;
              if (BDBINSSFN > WSALMIN * 1.5) then
                 begin
                   BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                 end
              else
                 begin
                   BDBINSSFN = 0;
                 end
            end

         /*SUSPEND;*/

         IF (prref >= 200903 and PRREF < 201606 AND prgpssefip = 1 AND wsomaap <> 0) THEN
            BEGIN
              BDGPSSEFIP     = 1;
              BDCODEMP       = wempatu;
              BDCODCOL       = wcolatu;
              BDREFFN        = prref;
              BDORDEM        = wordematu;
              BDCODCENTRO    = wcentrosatu;
              BDCODTPCC      = wccatu;
              BDINSSFN       = wainssap;
              BDINSSFEFOLFN  = winssfe;
              BDINSS13FN     = wainss13ap;
              BDBAVPREV      = wbavprev;

              --if (wainssap <> 0) then
              IF ((wbavprev <> 0) OR (wtemvalor = 1)) THEN
                 BEGIN
                   IF (wbaseinssfe + wbinssap < 0) THEN
                      BEGIN
                   IF (wbinssap < 0) THEN
                     wbinssap = 0;
                      END

                   BDINSSFN  = wainssap;
                   BDBINSSFN = wbinssap;
                 END
              ELSE
                 BEGIN
                   BDINSSFN  = winss;
                   BDBINSSFN = wbaseinss;
                 END

              BDBINSSFEFOLFN    = wbaseinssfe;
              BDBINSS13FN       = wbaseinss13;
              BDBINSS13APFN     = wbinss13ap;
              BDINSSAPFN        = wainssap;
              BDINSS13APFN      = wainss13ap;
              BDPERCRATCOL      = wpercrat;
              BDPERCDESCFPASCOL = wpercdedfpas;


              IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
                 BEGIN
                   BDBRATAPOFN   = BDBINSSAPFN;   -- + BDBINSSFEFOLFN;
                   BDBRATAPOFEFN = BDBINSSFEFOLFN;
                   BDBRATAPO13FN = BDBINSS13FN;
                 END
              ELSE
                 BEGIN
                   BDBRATAPOFN   = 0;
                   BDBRATAPOFEFN = 0;
                   BDBRATAPO13FN = 0;
                 END

              if (wsalmatemp < 0) then
                wsalmatemp = 0;
     
              BDCOVID19FN    = wcovid19fn;
              BDSALFAMFN     = wsalfam;
              BDSALMATEMPFN  = wsalmatemp;
     
              BDBINSSMVFN    = wabasemv;
              BDBINSSMV13FN  = wabasemv13;
              BDVALREEMBOLSO = wreemb;
              BDVALINDEVIDO  = wvindevido;
              BDVALINDEVIDOSF = wvindevidosf;

              --IF (BDINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
              --   BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;

              if (bdbinssfefolfn > 0 and bdbinssfn < 0) then
                 BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;

              -- 138080 - Raphael Teodoro - 26/08/2020
              IF (BDBINSSFEFOLFN < 0) THEN
                 BDBINSSFEFOLFN = 0;

              if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and wcatesoc in (731, 734)) then
                 begin
                   BDBINSS13APFN  = 0;
                   BDBINSS13FN    = 0;
                   BDBINSS13INDFN = 0;
                   BDBINSSAPFN    = 0;
                   BDBINSSFEFOLFN = 0;
                   BDBINSSFN      = 0;
                   BDBINSSMV13FN  = 0;
                   BDBINSSMVFN    = 0;
                 end

              if ((wcontrcol = 0) and
                  (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
                 BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
              else
                 BDBASERAT = 0;

              BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
              BDBASEINSS13 = BDBINSS13FN;

              if (wcatesoc in (107, 108)) then
            begin
                   BDBINSSFN = BDBINSSFN + BDBINSS13FN;
                   BDBINSS13FN = 0;

                   select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREF order by bdrefsm DESC INTO :WSALMIN;
                   if (BDBINSSFN > WSALMIN * 1.5) then
                      begin
                        BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                      end
                   else
                      begin
                        BDBINSSFN = 0;
                      end
                 end

              SUSPEND;
            END
          else
            SUSPEND;

         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wordematu   = wordem;
         wcentrosatu = wcentros;
         wccatu      = wcc;
         wsalfam     = 0;
         winss       = 0;
         winssfe     = 0;
         winss13     = 0;
         wbaseinss   = 0;
         wbaseinssfe = 0;
         wbaseinss13 = 0;
         wsalmatemp  = 0;
         wbinssap    = 0;
         wbinss13ap  = 0;
         wainssap    = 0;
         wainss13ap  = 0;
         wabasemv    = 0;
         wabasemv13  = 0;
         wreemb      = 0;
         wvindevido  = 0;
         wvindevidosf = 0;
         wbavprev    = 0;
         wtemvalor   = 0;
         wcovid19fn  = 0;
         wbasepis    = 0;
         wbasepis13  = 0;
         WBINSSRATINT = 0;
         WBDBASEINSS13 = 0;
       END

    wainssap   = winssap;
    wainss13ap = winss13ap;
    wabasemv   = wbasemv;
    wabasemv13 = wbasemv13;

    IF (prref >= 200903 and PRREF < 201606 AND prgpssefip = 1 AND wempap <> wcodemp) THEN
       BEGIN
         wsomaap = 0;
         SELECT SUM(BDSOMA) FROM (
           SELECT X.bdvalvfn BDSOMA FROM vrhf_emp_tverbafn X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :prref and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvft BDSOMA FROM vrhf_emp_tverbatomador X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :prref and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvfn BDSOMA FROM vrhf_emp_tverbaint X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :prref and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvft BDSOMA FROM vrhf_emp_tverbatomint X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :prref and Y.BDCODVER is not null
         )
         INTO :wsomaap;
         wempap = wcodemp;
       END
 
 wgrupocla = 0;
    SELECT CLA.BDGRUPOCLA
    FROM VW_VRH_EMP_TCOLCON_VINC VINC
    LEFT OUTER JOIN VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
    WHERE (VINC.BDCODEMP = :wempatu)
      AND (VINC.BDCODCOL = :wcolatu)
      AND (VINC.BDREFCOL <= :prref)
    ORDER BY BDCODEMP DESC, BDCODCOL DESC, BDREFCOL DESC
    INTO :wgrupocla;

    -- INSS folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.0') THEN
       winss = winss + wvalor;

    -- INSS férias demonstradas na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.2') THEN
       winssfe = winssfe + wvalor;

    -- INSS 13o. rescisão descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;

    if (wintermitente = 'TRUE') then
       begin
         -- INSS 13o. descontado na folha normal
         IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.6') THEN
            winss13 = winss13 + wvalor;
       end

    IF (wverdeamarelo = 'TRUE') THEN
       begin
         -- INSS 13o. descontado na folha normal
         IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.3') THEN
            winss13 = winss13 + wvalor;
       end

    -- Base de INSS folha normal
    IF ((winssver = 1)) THEN
       BEGIN
         IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200') OR (SUBSTRING(wclaver FROM 1 FOR 7) = '0.180.1')) THEN
            BEGIN
              IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
       END
    ELSE
    IF ((winssver = 0)) THEN  --não incide
       BEGIN
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
         ELSE
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss13 = wbaseinss13 + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss13 = wbaseinss13 - wvalor;
            END
       END

    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 2) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END
    ELSE
    IF (winssver = 1 AND SUBSTRING(wclaver FROM 1 FOR 5) >= '0.100' AND SUBSTRING(wclaver FROM 1 FOR 5) < '0.200' AND (SUBSTRING(wclaver FROM 1 FOR 7) <> '0.180.1')) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END

    -- Base de INSS 13o. salário descontado na rescisão
    IF ((winssver = 3)) THEN
       BEGIN
         IF (PRSEPARARFOLHAS = 'TRUE') THEN
           BEGIN
             IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                wbaseinss13 = wbaseinss13 + wvalor;
             ELSE
             IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                wbaseinss13 = wbaseinss13 - wvalor;
           END
         ELSE
           BEGIN
         IF ((wtipocodver = 0) AND (SUBSTRING(wclaver FROM 1 FOR 9) = '0.800.6.2')) THEN  -- Provento
            begin
--              wbaseinss = wbaseinss + wvalor;
              wbaseinss13 = wbaseinss13 + wvalor;

--              WBINSSRATINT = WBINSSRATINT + wvalor;
--              WBDBASEINSS13 = WBDBASEINSS13 + wvalor;
            end
         ELSE
         IF ((wtipocodver = 1) AND (SUBSTRING(wclaver FROM 1 FOR 9) = '0.800.6.2')) THEN  -- Desconto
             begin
--               wbaseinss = wbaseinss - wvalor;
               wbaseinss13 = wbaseinss13 - wvalor;

--               WBINSSRATINT = WBINSSRATINT - wvalor;
--               WBDBASEINSS13 = WBDBASEINSS13 - wvalor;
             end
         ELSE
             IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
             IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       END
       END

    -- Verifica diferença de incidência de PIS e Base GPS
    if (coalesce(UPPER(WDIFINCIDVER), 'FALSE') = 'TRUE') then
       begin
         if ((wbasegpsver <> wincidepis) and (WGRUPOCLA not in (2, 3))) then
            begin
              WSQLDIFINSSGPS = 'update or insert into VRHF_TINFO_TEMP_DIFINCIDVER (BDSESSAO, BDCODEMP, BDCODVER, BDDESCVER) '||
                               'values ('||current_connection||', '||wcodemp||', '||wcodver||', '''||wdescver||''') matching (BDSESSAO, BDCODEMP, BDCODVER)';
              execute statement WSQLDIFINSSGPS;
            end
       end

    -- Valor base PIS
    if (coalesce(UPPER(wincidepis), 'FALSE') = 'TRUE') then
      BEGIN
         IF (winssver = 3) THEN
           BEGIN
             IF (wtipocodver = 0) THEN  -- Provento
                wbasepis13 = wbasepis13 + wvalor;
             ELSE
               IF (wtipocodver = 1) THEN  -- Desconto
                  wbasepis13 = wbasepis13 - wvalor;
           END
         ELSE
           BEGIN
             IF (wtipocodver = 0) THEN  -- Provento
                wbasepis = wbasepis + wvalor;
             ELSE
               IF (wtipocodver = 1) THEN  -- Desconto
                  wbasepis = wbasepis - wvalor;
           END
      END

    -- Valor de salário família
    IF (SUBSTRING(wclaver FROM 1 FOR 7) = '9.050.0') THEN
       wsalfam = wsalfam + wvalor;

    -- Valor do COVID-19
    IF (SUBSTRING(wclaver FROM 1 FOR 7) = '9.050.1') THEN
       wcovid19fn = wcovid19fn + wvalor;

    -- Valor indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.2') THEN
       wvindevido = wvindevido + wvalor;

    -- Valor SF indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.0') THEN
       wvindevidosf = wvindevidosf + wvalor;

    -- Base de salário maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005') OR
         (SUBSTRING(wclaver FROM 1 FOR 7) = '7.061.2') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.710'))) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END

    -- Base de INSS folha normal sem o aviso prévio indenizado
    IF (SUBSTRING(wclaver FROM 1 FOR 7) <> '7.001.3') THEN
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200') OR (SUBSTRING(wclaver FROM 1 FOR 7) = '0.180.1')) THEN
                 BEGIN
                   IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
              ELSE
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinss13ap = wbinss13ap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinss13ap = wbinss13ap - wvalor;

                   wtemvalor = 1;
                 END
            END
       END
    ELSE
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200') OR (SUBSTRING(wclaver FROM 1 FOR 7) = '0.180.1')) THEN
                 BEGIN
                   IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 7, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
       END

    -- INSS sobre o aviso prévio indenizado do 13º salário
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '7.060') THEN
       BEGIN
         IF (winssver = 3) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbinss13ap = wbinss13ap + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbinss13ap = wbinss13ap - wvalor;
            END
       END

  END


  IF ((wempatu <> 0) AND (wcolatu <> 0) AND ((wccatu <> 0) OR (wccatu IS NULL))) THEN
     BEGIN
       wcodsind = NULL;
       wlimemp = NULL;
       wlimsind = NULL;
       SELECT first 1 BDCODSINTRAB FROM VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC
       INTO :wcodsind;
       IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
          BEGIN
            SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
          END

       IF (wlimsind IS NULL) THEN
          wlimsind = 0;             -- não possui liminar

       IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
          SELECT first 1 BDLIMINARAVPREVEMP FROM VRHF_BASE_TEMPCALC WHERE BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
          INTO :wlimemp;

       IF (wlimemp IS NULL) THEN
          wlimemp = 0;    -- não possui liminar

       wclatrib = null;
       wcoop    = null;
       select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
       into :wclatrib, :wcoop;
       wclatrib = coalesce(wclatrib, 0);
       wcoop    = coalesce(wcoop, 0);

       BDGPSSEFIP     = 0;
       BDCODEMP       = wempatu;
       BDCODCOL       = wcolatu;
       BDREFFN        = prref;
       BDORDEM        = wordematu;
       BDCODCENTRO    = wcentrosatu;
       BDCODTPCC      = wccatu;
       BDINSSFN       = winss;
       BDINSSFEFOLFN  = winssfe;
       BDINSS13FN     = winss13;
       BDBINSSFEFOLFN = wbaseinssfe;
       BDBINSSAPFN    = wbinssap;
       BDBINSS13APFN  = wbinss13ap;
       BDINSSAPFN     = wainssap;
       BDINSS13APFN   = wainss13ap;
       BDBAVPREV      = 0;

       if ((BDCODCENTRO is null and BDCODTPCC is not null) or (BDCODTPCC is null)) then
          begin
            select first 1 BDCODCENTROS from TEMPRESAS_REF where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC into :BDCODCENTRO;
          end

       IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
          BDBINSSFN = wbinssap;
       ELSE
          BDBINSSFN = wbaseinss;


       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13INDFN = 0;
       ELSE
          BDBINSS13INDFN = wbinss13ap;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13FN = wbaseinss13 - wbinss13ap;
       ELSE
          BDBINSS13FN = wbaseinss13;

       if (BDBINSS13FN < 0) then
          begin
          BDBINSS13FN = 0;
            if (NOT ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6)))) THEN
              bdbinss13fn = coalesce(wbinss13ap, 0);
          end

       IF (BDBINSSFN+BDBINSSFEFOLFN < 0) THEN
          BEGIN
            BDBINSSFEFOLFN = 0;
            BDBINSSFN = 0;
          END


       /*Wesley Kowalski | 05/12/2018 | Descomentei a verificação abaixo */   
       --IF (BDINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
       --   BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;

       if (bdbinssfefolfn > 0 and bdbinssfn < 0) then
          BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;

       -- 138080 - Raphael Teodoro - 26/08/2020
       IF (BDBINSSFEFOLFN < 0) THEN
          BDBINSSFEFOLFN = 0;

       wpercrat = 0;
       wpercdedfpas = 0;
       SELECT first 1 BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL, BDCATEGORIAESOCIAL
       FROM VRHF_EMP_TCOLCON_FGTSGPS
       WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prref
       order by BDREFCOL DESC
       INTO :wpercrat, :wpercdedfpas, :wcontrcol, :wcatesoc;
       wcatesoc = coalesce(wcatesoc, 0);
       wcontrcol = coalesce(wcontrcol, 0);
       BDCATEGORIAESOCIAL = coalesce(wcatesoc,0);

       -- 136305 - Raphael Teodoro - 21/08/2020
       wgrupocla = 0;
       SELECT CLA.BDGRUPOCLA
       FROM VW_VRH_EMP_TCOLCON_VINC VINC
       LEFT OUTER JOIN VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
       WHERE (VINC.BDCODEMP = :wempatu)
         AND (VINC.BDCODCOL = :wcolatu)
         AND (VINC.BDREFCOL <= :prref)
       ORDER BY BDCODEMP DESC, BDCODCOL DESC, BDREFCOL DESC
       INTO :wgrupocla;

/*       IF (wcontrcol = 1) THEN
          begin
            wwhere = 'select SUM(FT.BDBINSSFT) from (select BDCODEMP,BDCODCOL,BDREFTOMADOR,BDORDEM,case when coalesce(BDBASEINSSNMVNOVO, 0) <> 0 then BDBASEINSSNMVNOVO else BDBINSSFT end BDBINSSFT from VRHF_EMP_TFOLHATOMADOR '||
                                                    'where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFTOMADOR = '||prref||
                                                    ' union all '||
                                                    'select BDCODEMP,BDCODCOL,BDREFTOMADOR,BDORDEM,BDBINSSFT from VRHF_EMP_TFOLHATOMINT '||
                                                    'where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFTOMADOR = '||prref||
                     ') FT '||
                     'left outer join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FT.BDCODEMP and PFN.BDCODCOL = FT.BDCODCOL and PFN.BDORDEM = FT.BDORDEM) '||
                     'where FT.BDCODEMP = '||wempatu||' and FT.BDCODCOL = '||wcolatu||' and FT.BDREFTOMADOR = '||prref||' and COALESCE(PFN.BDCODCENTRO, 0) = '||COALESCE(:wcentrosatu, 0)||
                     case when COALESCE(:wccatu, 0) = 0 then ' and PFN.BDCODTPCC is null ' else ' and PFN.BDCODTPCC = '||COALESCE(:wccatu, 0) end;
            execute statement wwhere into :wbaseinsscontratu;
            wbaseinsscontratu = COALESCE(:wbaseinsscontratu, 0);
            BDBINSSFN = wbaseinsscontratu - wabasemv;
          end
*/
       IF (BDBINSSFN < 0) THEN
          BDBINSSFN = 0;

       if (WBDBASEINSS13 < 0) then
          WBDBASEINSS13 = 0;

       BDBINSSFN = BDBINSSFN + WBDBASEINSS13;

       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BEGIN
            BDBRATAPOFN   = wbaseinss;    -- + wbaseinssfe;
            BDBRATAPOFEFN = wbaseinssfe;
            BDBRATAPO13FN = wbaseinss13;
          END
       ELSE
          BEGIN
            BDBRATAPOFN   = 0;
            BDBRATAPOFEFN = 0;
            BDBRATAPO13FN = 0;
          END

       if (wsalmatemp < 0) then
         wsalmatemp = 0;

       BDCOVID19FN       = wcovid19fn;
       BDSALFAMFN        = wsalfam;
       BDSALMATEMPFN     = wsalmatemp;
       BDBINSSMVFN       = wabasemv;
       BDBINSSMV13FN     = wabasemv13;
       BDVALREEMBOLSO    = wreemb;
       BDVALINDEVIDO     = wvindevido;
       BDVALINDEVIDOSF   = wvindevidosf;
       BDPERCRATCOL      = wpercrat;
       BDPERCDESCFPASCOL = wpercdedfpas;

       if (coalesce(wclatrib, 0)  = 99 and coalesce(wcoop, 0) = 1 and wcatesoc in (731, 734)) then
          begin
            BDBINSS13APFN  = 0;
            BDBINSS13FN    = 0;
            BDBINSS13INDFN = 0;
            BDBINSSAPFN    = 0;
            BDBINSSFEFOLFN = 0;
            BDBINSSFN      = 0;
            BDBINSSMV13FN  = 0;
            BDBINSSMVFN    = 0;
          end

       if ((wcontrcol = 0) and
           (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
          BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
       else
          BDBASERAT = 0;

       BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
       BDBASEINSS13 = BDBINSS13FN;

       if (wcatesoc in (107, 108)) then
          begin
            BDBINSSFN = BDBINSSFN + BDBINSS13FN;
            BDBINSS13FN = 0;

            select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREF order by bdrefsm DESC INTO :WSALMIN;
            if (BDBINSSFN > WSALMIN * 1.5) then
               begin
                 BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
               end
            else
               begin
                 BDBINSSFN = 0;
               end
          end

       /*SUSPEND;*/
    bdbasepis = wbasepis;
    bdbasepis13 = wbasepis13;

    if (bdbasepis < 0) then
      bdbasepis = 0;
    if (bdbasepis13 < 0) then
      bdbasepis13 = 0;

    IF (prref >= 200903 and PRREF < 201606 AND prgpssefip = 1 AND wsomaap <> 0) THEN
          BEGIN
            BDGPSSEFIP     = 1;
            BDCODEMP       = wempatu;
            BDCODCOL       = wcolatu;
            BDREFFN        = prref;
            BDORDEM        = wordematu;
            BDCODCENTRO    = wcentrosatu;
            BDCODTPCC      = wccatu;
            BDBAVPREV      = wbavprev;

            IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
               BEGIN
                 IF (wbaseinssfe + wbinssap < 0) THEN
                    BEGIN
                 IF (wbinssap < 0) THEN
                   wbinssap = 0;
                    END

                 BDINSSFN  = wainssap;
                 BDBINSSFN = wbinssap;
               END
            ELSE
               BEGIN
                 BDINSSFN  = winss;
                 BDBINSSFN = wbaseinss;
               END

            BDINSSFEFOLFN     = winssfe;
            BDINSS13FN        = wainss13ap;
            BDBINSSFEFOLFN    = wbaseinssfe;
            BDBINSS13FN       = wbaseinss13;
            BDBINSSAPFN       = wbinssap;
            BDBINSS13INDFN    = wbinss13ap;
            BDBINSS13APFN     = wbinss13ap;
            BDINSSAPFN        = wainssap;
            BDINSS13APFN      = wainss13ap;
            BDPERCRATCOL      = wpercrat;
            BDPERCDESCFPASCOL = wpercdedfpas;
     
            IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
               BEGIN
                 BDBRATAPOFN   = BDBINSSFN;    -- + BDBINSSFEFOLFN;
                 BDBRATAPOFEFN = BDBINSSFEFOLFN;
                 BDBRATAPO13FN = BDBINSS13FN;
               END
            ELSE
               BEGIN
                 BDBRATAPOFN   = 0;
                 BDBRATAPOFEFN = 0;
                 BDBRATAPO13FN = 0;
               END

            if (wsalmatemp < 0) then
              wsalmatemp = 0;
     
            BDCOVID19FN    = wcovid19fn;
            BDSALFAMFN     = wsalfam;
            BDSALMATEMPFN  = wsalmatemp;
     
            BDBINSSMVFN    = wabasemv;
            BDBINSSMV13FN  = wabasemv13;
            BDVALREEMBOLSO = wreemb;
            BDVALINDEVIDO  = wvindevido;
            BDVALINDEVIDOSF = wvindevidosf;

            --IF (BDBINSSFEFOLFN > 0 AND BDINSSFN < 0) THEN
            --   BDINSSFEFOLFN = bdinssfefolfn + bdinssfn;

            if (bdbinssfefolfn > 0 and bdbinssfn < 0) then
               BDBINSSFEFOLFN = BDBINSSFEFOLFN + BDBINSSFN;

            -- 138080 - Raphael Teodoro - 26/08/2020
            IF (BDBINSSFEFOLFN < 0) THEN
               BDBINSSFEFOLFN = 0;

            if (coalesce(wclatrib, 0)  = 99 and coalesce(wcoop, 0) = 1 and wcatesoc in (731, 734)) then
               begin
                 BDBINSS13APFN  = 0;
                 BDBINSS13FN    = 0;
                 BDBINSS13INDFN = 0;
                 BDBINSSAPFN    = 0;
                 BDBINSSFEFOLFN = 0;
                 BDBINSSFN      = 0;
                 BDBINSSMV13FN  = 0;
                 BDBINSSMVFN    = 0;
               end

            if ((wcontrcol = 0) and
                (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
               BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
            else
               BDBASERAT = 0;

            BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
            BDBASEINSS13 = BDBINSS13FN;

            if (wcatesoc in (107, 108)) then
          begin
                 BDBINSSFN = BDBINSSFN + BDBINSS13FN;
                 BDBINSS13FN = 0;

                 select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREF order by bdrefsm DESC INTO :WSALMIN;
                 if (BDBINSSFN > WSALMIN * 1.5) then
     begin
                      BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                    end
       else
                    begin
                      BDBINSSFN = 0;
                    end
               end

         SUSPEND;
         END
       ELSE
         SUSPEND;
     END
END^

/* Restore proc. body: SP_VRHF_DADOS_INSS_FTC */
create or alter procedure SP_VRHF_DADOS_INSS_FTC (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32000),
    PRREF integer,
    PRREFPAG integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS smallint = 0,
    PRREFFIM integer = 0,
    PRCOMPLEESOCIAL integer = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFCOMP integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDCODTIPOFC integer,
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEPIS numeric(18,6),
    BDBASEPIS13 numeric(18,6))
as
declare variable WCCNULL integer;
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(32000);
declare variable WVERDEAMARELO DM_BOOLEAN;
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WCENTROS integer;
declare variable WCENTROSATU integer;
declare variable WCC integer;
declare variable WCCATU integer;
declare variable WCLAVER varchar(20);
declare variable WTIPOCODVER integer;
declare variable WINSSVER integer;
declare variable WBASEGPSVER varchar(5);
declare variable WREEMBGPSVER varchar(5);
declare variable WVALOR numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WINSSFE numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WBASEINSS numeric(18,6);
declare variable WBASEINSSFE numeric(18,6);
declare variable WBASEINSS13 numeric(18,6);
declare variable WSALFAM numeric(18,6);
declare variable WSALMATEMP numeric(18,6);
declare variable WBASEMV numeric(18,6);
declare variable WBASEMV13 numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WCODTIPOFC integer;
declare variable WCODFCATU integer;
declare variable WBINSSAP numeric(18,6);
declare variable WBINSS13AP numeric(18,6);
declare variable WINSSAP numeric(18,6);
declare variable WINSS13AP numeric(18,6);
declare variable WAINSSAP numeric(18,6);
declare variable WAINSS13AP numeric(18,6);
declare variable WABASEMV numeric(18,6);
declare variable WABASEMV13 numeric(18,6);
declare variable WEMPAP integer;
declare variable WSOMAAP numeric(18,6);
declare variable WCODSIND integer;
declare variable WLIMSIND integer;
declare variable WLIMEMP integer;
declare variable WREEMB numeric(18,6);
declare variable WVINDEVIDO numeric(18,6);
declare variable WVINDEVIDOSF numeric(18,6);
declare variable WBAVPREV numeric(18,6);
declare variable WTEMVALOR smallint;
declare variable WREFFCA integer;
declare variable WREFFC integer;
declare variable WSALMIN numeric(15,2);
declare variable WCATEGORIAESOC integer;
declare variable WCONTRCOL integer;
declare variable WGRUPOCLA integer;
declare variable WINCIDEPIS DM_BOOLEAN;
declare variable WBASEPIS numeric(18,6);
declare variable WBASEPIS13 numeric(18,6);
declare variable WREFFN integer;
declare variable WREFFNATU integer;
declare variable WDIFINCIDVER DM_BOOLEAN;
declare variable WSQLDIFINSSGPS varchar(300);
declare variable WCODVER integer;
declare variable WDESCVER varchar(60);
BEGIN
  -- Obtem valor de variável de contexto e limpa os valores da tabela temporária da sessão atual
  WSQLDIFINSSGPS = 'SELECT RDB$GET_CONTEXT(''USER_SESSION'', ''W_DIFINCIDVER'') FROM RDB$DATABASE';
  execute statement WSQLDIFINSSGPS into :WDIFINCIDVER;

  wsql = 'select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFTOMADOR, FC.BDREFFC, FC.BDVALVFC, FC.BDCODVER, VERREF.BDDESCVER, FC.BDBINSSMVFC, FC.BDBINSSMV13FC, FC.BDINSSAPFC, FC.BDINSS13APFC, '||
                'VER.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, PREP.BDCODCENTRO, '||
                'PREP.BDCODTPCC, FC.BDCODTIPOFC, ' ||
                'case when COALESCE(FGTSGPS.BDCATEGORIACOL, 0) = 7 and COALESCE(FGTSGPS.BDCATEGORIAESOCIAL, 0) in (107,108)' ||
                ' then ''TRUE'' else ''FALSE'' end BDVERDEAMARELO, VERREF.BDPISVER from (';

/*  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFC, FN.BDVALVFC, FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, '||
                      'FOLN.BDINSS13APFC, FOLN.BDCODTIPOFC, cast(null as INTEGER) BDCODCONTTI, FN.BDCODVER, FN.BDORDEM '; */
  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFTOMADOR, FN.BDREFFC, FN.BDVALVFC, FN.BDBINSSMVFC, FN.BDBINSSMV13FC, FN.BDINSSAPFC, '||
                      'FN.BDINSS13APFC, FN.BDCODTIPOFC, cast(null as INTEGER) BDCODCONTTI, FN.BDCODVER, FN.BDORDEM ';

  if (coalesce(prfiliais, 0) = 1 and coalesce(prcodemp, '') <> '') then
     begin
       wsql = wsql||
              'from (select BDCODEMP from TEMPRESAS where (('||prcodemp||') or ('||REPLACE(UPPER(prcodemp), 'BDCODEMP', 'BDCODMATRIZ')||'))) EMP '||
              'join (select VERN.BDCODEMP,VERN.BDCODCOL,VERN.BDREFTOMADOR,VERN.BDREFFC,VERN.BDORDEM,VERN.BDCODVER,VERN.BDVALVFC, '||
              '      FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, FOLN.BDINSS13APFC, FOLN.BDCODTIPOFC'||
              '      from VRHF_EMP_TVERBAFCTOMADOR VERN '||
              '      join VRHF_EMP_TFOLTOMCOMP FOLN on (FOLN.BDCODEMP = VERN.BDCODEMP and FOLN.BDCODCOL = VERN.BDCODCOL and FOLN.BDREFTOMADOR = VERN.BDREFTOMADOR and FOLN.BDREFFC = VERN.BDREFFC and FOLN.BDORDEM = VERN.BDORDEM) '||
              '      left outer join VRH_EMP_TACCONV ACCONV ON (FOLN.BDCODEMP = ACCONV.BDCODEMP AND FOLN.BDCODACCONV = ACCONV.BDCODACCONV)';                          /* 158041 Leonardo Schwab 05/06/2023 */

       wwhere = '';

       IF ((coalesce(prref, 0) <> 0) and (coalesce(prreffim, 0) <> 0)) THEN
          wwhere = wwhere||'VERN.BDREFTOMADOR >= '||prref||' AND VERN.BDREFTOMADOR <= '||prreffim||' ';
       ELSE
       IF (coalesce(prref, 0) <> 0) THEN
          wwhere = wwhere||'VERN.BDREFTOMADOR = '||prref||' ';

       IF (coalesce(prrefpag, 0) <> 0) THEN
          begin
            if (wwhere <> '') then
               wwhere = wwhere||' and ';
            /*wwhere = wwhere||'VERN.BDREFFC >= '||prrefpag||'01 and VERN.BDREFFC <= '||prrefpag||'31 ';*/

            if (PRCOMPLEESOCIAL = 1) then
                wwhere = wwhere||'((FOLN.BDCODTIPOFC <> 3 AND VERN.BDREFTOMADOR = '||prrefpag||') OR '||
                                 ' (FOLN.BDCODACCONV IS NOT NULL AND FOLN.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefpag||'))';
            ELSE
                wwhere = wwhere||'((FOLN.BDCODTIPOFC <> 3 AND VERN.BDREFFC >= '||prrefpag||'01 and VERN.BDREFFC <= '||prrefpag||'31) OR '||
                                 ' (FOLN.BDCODACCONV IS NOT NULL AND FOLN.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefpag||'))';
          end

       if (wwhere <> '') then
          wsql = wsql||' where '||wwhere;

       wsql = wsql||') FN on (FN.BDCODEMP = EMP.BDCODEMP) ';
     end
  else
     begin
       wsql = wsql||'from (select VERN.BDCODEMP,VERN.BDCODCOL,VERN.BDREFTOMADOR,VERN.BDREFFC,VERN.BDORDEM,VERN.BDCODVER,VERN.BDVALVFC, '||
                    '      FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, FOLN.BDINSS13APFC, FOLN.BDCODTIPOFC'||
                    '      from VRHF_EMP_TVERBAFCTOMADOR VERN '||
                    '      join VRHF_EMP_TFOLTOMCOMP FOLN on (FOLN.BDCODEMP = VERN.BDCODEMP and FOLN.BDCODCOL = VERN.BDCODCOL and FOLN.BDREFTOMADOR = VERN.BDREFTOMADOR and FOLN.BDREFFC = VERN.BDREFFC and FOLN.BDORDEM = VERN.BDORDEM) '||
                    '      left outer join VRH_EMP_TACCONV ACCONV ON (FOLN.BDCODEMP = ACCONV.BDCODEMP AND FOLN.BDCODACCONV = ACCONV.BDCODACCONV)';                          /* 158041 Leonardo Schwab 05/06/2023 */
       wwhere  = '';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wwhere = wwhere||'VERN.'||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'VERN.'||prcodcol;
     END
     
       IF ((coalesce(prref, 0) <> 0) and (coalesce(prreffim, 0) <> 0)) THEN
          BEGIN
            IF (wwhere <> '') THEN
                 wwhere = wwhere||' and ';
     
              wwhere = wwhere||'VERN.BDREFTOMADOR >= '||prref||' AND VERN.BDREFTOMADOR <= '||prreffim||' ';
          END
       ELSE
       IF (prref IS NOT NULL AND prref <> 0) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'VERN.BDREFTOMADOR = '||prref||' ';
          END
     
       IF (prrefpag IS NOT NULL AND prrefpag <> 0) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            /*wwhere = wwhere||'BDREFFC >= '||prrefpag||'01 and BDREFFC <= '||prrefpag||'31 ';*/
            if (PRCOMPLEESOCIAL = 1) then
                wwhere = wwhere||'((FOLN.BDCODTIPOFC <> 3 AND VERN.BDREFTOMADOR = '||prrefpag||') OR '||
                                 ' (FOLN.BDCODACCONV IS NOT NULL AND FOLN.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefpag||'))';
            ELSE
                wwhere = wwhere||'((FOLN.BDCODTIPOFC <> 3 AND VERN.BDREFFC >= '||prrefpag||'01 and VERN.BDREFFC <= '||prrefpag||'31) OR '||
                                 ' (FOLN.BDCODACCONV IS NOT NULL AND FOLN.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefpag||'))';
          END
     
       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;
     
       wsql = wsql||wwhere;
     
       wsql = wsql||') FN ';
     end

/*  wsql = wsql||'join VRHF_EMP_TFOLTOMCOMP FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFTOMADOR = FN.BDREFTOMADOR and FOLN.BDREFFC = FN.BDREFFC and FOLN.BDORDEM = FN.BDORDEM) '; */

  wsql = wsql||' union all ';
  /*wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFC, FN.BDVALVFC, FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, '||
                      'FOLN.BDINSS13APFC, FOLN.BDCODTIPOFC, FN.BDCODCONTTI, FN.BDCODVER, FN.BDORDEM ';*/
  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFTOMADOR, FN.BDREFFC, FN.BDVALVFC, FN.BDBINSSMVFC, FN.BDBINSSMV13FC, FN.BDINSSAPFC, '||
                      'FN.BDINSS13APFC, FN.BDCODTIPOFC, FN.BDCODCONTTI, FN.BDCODVER, FN.BDORDEM ';

  if (coalesce(prfiliais, 0) = 1 and coalesce(prcodemp, '') <> '') then
     begin
       wsql = wsql||
              'from (select BDCODEMP from TEMPRESAS where (('||prcodemp||') or ('||REPLACE(UPPER(prcodemp), 'BDCODEMP', 'BDCODMATRIZ')||'))) EMP '||
              'join (select VERN.BDCODEMP,VERN.BDCODCOL,VERN.BDREFTOMADOR,VERN.BDREFFC,VERN.BDORDEM,VERN.BDCODVER,VERN.BDVALVFC,VERN.BDCODCONTTI, '||
              '      FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, FOLN.BDINSS13APFC, FOLN.BDCODTIPOFC '||
              '      from VRHF_EMP_TVERBAFCTOMINT VERN '||
              '      join VRHF_EMP_TFOLTOMCOMPINT FOLN on (FOLN.BDCODEMP = VERN.BDCODEMP and FOLN.BDCODCOL = VERN.BDCODCOL and FOLN.BDREFTOMADOR = VERN.BDREFTOMADOR and FOLN.BDREFFC = VERN.BDREFFC and FOLN.BDORDEM = VERN.BDORDEM and FOLN.BDCODCONTTI = VERN.BDCODCONTTI) '||
              '      left outer join VRH_EMP_TACCONV ACCONV ON (FOLN.BDCODEMP = ACCONV.BDCODEMP AND FOLN.BDCODACCONV = ACCONV.BDCODACCONV)';                          /* 158041 Leonardo Schwab 05/06/2023 */

       wwhere = '';

       IF ((coalesce(prref, 0) <> 0) and (coalesce(prreffim, 0) <> 0)) THEN
          wwhere = wwhere||'VERN.BDREFTOMADOR >= '||prref||' AND VERN.BDREFTOMADOR <= '||prreffim||' ';
       ELSE
       IF (coalesce(prref, 0) <> 0) THEN
          wwhere = wwhere||'VERN.BDREFTOMADOR = '||prref||' ';

       IF (coalesce(prrefpag, 0) <> 0) THEN
          begin
            if (wwhere <> '') then
               wwhere = wwhere||' and ';
            /*wwhere = wwhere||'VERN.BDREFFC >= '||prrefpag||'01 and VERN.BDREFFC <= '||prrefpag||'31 ';*/
            if (PRCOMPLEESOCIAL = 1) then
                wwhere = wwhere||'((FOLN.BDCODTIPOFC <> 3 AND VERN.BDREFTOMADOR = '||prrefpag||') OR '||
                                 ' (FOLN.BDCODACCONV IS NOT NULL AND FOLN.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefpag||'))';
            ELSE
                wwhere = wwhere||'((FOLN.BDCODTIPOFC <> 3 AND VERN.BDREFFC >= '||prrefpag||'01 and VERN.BDREFFC <= '||prrefpag||'31) OR '||
                                 ' (FOLN.BDCODACCONV IS NOT NULL AND FOLN.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefpag||'))';
          end

       if (wwhere <> '') then
          wsql = wsql||' where '||wwhere;

       wsql = wsql||') FN on (FN.BDCODEMP = EMP.BDCODEMP) ';
     end
  else
     begin
       wsql = wsql||'from (select VERN.BDCODEMP,VERN.BDCODCOL,VERN.BDREFTOMADOR,VERN.BDREFFC,VERN.BDORDEM,VERN.BDCODVER,VERN.BDVALVFC,VERN.BDCODCONTTI, '||
                    '      FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, FOLN.BDINSS13APFC, FOLN.BDCODTIPOFC '||
                    '      from VRHF_EMP_TVERBAFCTOMINT VERN '||
                    '      join VRHF_EMP_TFOLTOMCOMPINT FOLN on (FOLN.BDCODEMP = VERN.BDCODEMP and FOLN.BDCODCOL = VERN.BDCODCOL and FOLN.BDREFTOMADOR = VERN.BDREFTOMADOR and FOLN.BDREFFC = VERN.BDREFFC and FOLN.BDORDEM = VERN.BDORDEM and FOLN.BDCODCONTTI = VERN.BDCODCONTTI) '||
                    '      left outer join VRH_EMP_TACCONV ACCONV ON (FOLN.BDCODEMP = ACCONV.BDCODEMP AND FOLN.BDCODACCONV = ACCONV.BDCODACCONV)';                          /* 158041 Leonardo Schwab 05/06/2023 */
       wwhere  = '';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wwhere = wwhere||'VERN.'||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'VERN.'||prcodcol;
          END
     
       IF ((coalesce(prref, 0) <> 0) and (coalesce(prreffim, 0) <> 0)) THEN
          BEGIN
            IF (wwhere <> '') THEN
                 wwhere = wwhere||' and ';
     
              wwhere = wwhere||'VERN.BDREFTOMADOR >= '||prref||' AND VERN.BDREFTOMADOR <= '||prreffim||' ';
          END
       ELSE
       IF (prref IS NOT NULL AND prref <> 0) THEN
     BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'VERN.BDREFTOMADOR = '||prref||' ';
     END
     
       IF (prrefpag IS NOT NULL AND prrefpag <> 0) THEN
     BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            /*wwhere = wwhere||'VERN.BDREFFC >= '||prrefpag||'01 and VERN.BDREFFC <= '||prrefpag||'31 ';*/
            if (PRCOMPLEESOCIAL = 1) then
                wwhere = wwhere||'((FOLN.BDCODTIPOFC <> 3 AND VERN.BDREFTOMADOR = '||prrefpag||') OR '||
                                 ' (FOLN.BDCODACCONV IS NOT NULL AND FOLN.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefpag||'))';
            ELSE
                wwhere = wwhere||'((FOLN.BDCODTIPOFC <> 3 AND VERN.BDREFFC >= '||prrefpag||'01 and VERN.BDREFFC <= '||prrefpag||'31) OR '||
                                 ' (FOLN.BDCODACCONV IS NOT NULL AND FOLN.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefpag||'))';
     END
     
       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;
     
       wsql = wsql||wwhere;
     
       wsql = wsql||') FN ';
     end

/*  wsql = wsql||'join VRHF_EMP_TFOLTOMCOMPINT FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFTOMADOR = FN.BDREFTOMADOR and FOLN.BDREFFC = FN.BDREFFC and FOLN.BDORDEM = FN.BDORDEM and FOLN.BDCODCONTTI = FN.BDCODCONTTI) ';*/

  wsql = wsql||') FC ';
  wsql = wsql||'left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FC.BDCODVER) ';
  wsql = wsql||'left outer join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FC.BDCODVER) ';
  wsql = wsql||'left outer join VRHF_EMP_TPREPFN prep on (prep.bdcodemp = FC.bdcodemp and prep.bdcodcol = FC.bdcodcol and prep.bdordem = FC.bdordem) ';
  wsql = wsql||'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS FGTSGPS on (FGTSGPS.BDCODEMP = FC.BDCODEMP and FGTSGPS.BDCODCOL = FC.BDCODCOL) ';
  wsql = wsql||'where VER.BDCODVER is not null and VERREF.BDCODVER is not null and prep.BDCODEMP is not null ';
  wsql = wsql||'order by FC.BDCODEMP,FC.BDCODCOL,FC.BDREFFC,PREP.BDCODCENTRO,PREP.BDCODTPCC ';

  wempatu     = 0;
  wcolatu     = 0;
  wcentrosatu = 0;
  wccatu      = 0;
  wsalfam     = 0;
  winss       = 0;
  winssfe     = 0;
  winss13     = 0;
  wbaseinss   = 0;
  wbaseinssfe = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wbasemv     = 0;
  wbasemv13   = 0;
  wbinssap    = 0;
  wbinss13ap  = 0;
  wabasemv    = 0;
  wabasemv13  = 0;
  wainssap    = 0;
  wainss13ap  = 0;
  wempap      = 0;
  wsomaap     = 0;
  wreemb      = 0;
  wvindevido  = 0;
  wvindevidosf = 0;
  wbavprev     = 0;
  wtemvalor   = 0;
  wreffca = 0;
  wreffca = 0;
  wbasepis = 0;
  wbasepis13 = 0;
  wreffnatu = 0;
  wcodver = 0;
  wdescver = '';

  if (prref > 0) then
     EXECUTE PROCEDURE sp_seta_competencia(prref);
  else
  if (prrefpag > 0) then
     EXECUTE PROCEDURE sp_seta_competencia(prrefpag);

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wreffn, :wreffc, :wvalor, :wcodver, :wdescver, :wbasemv, :wbasemv13, :winssap, :winss13ap, :wclaver,
                                  :wtipocodver, :winssver, :wbasegpsver, :wreembgpsver, :wcentros, :wcc, :wcodtipofc, :wverdeamarelo, :wincidepis DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wreffca = 0) THEN
       wreffca = wreffc;

    IF (wcentrosatu = 0) THEN
       wcentrosatu = wcentros;

    IF (wccatu = 0) THEN
       wccatu = wcc;

    wCCNull = 0;
    IF ((wccatu IS NULL) AND (wcc IS NOT NULL)) THEN
       wccnull = 1;
    IF ((wccatu IS NOT NULL) AND (wcc IS NULL)) THEN
       wccnull = 1;

    if (wreffnatu = 0) then
       wreffnatu = wreffn;

    /*
      Retorna bases de INSS
    */
    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wcentrosatu <> wcentros) OR (wccatu <> wcc) OR (wCCNull = 1) OR (wreffca <> wreffc) OR (wreffnatu <> wreffn) ) THEN
       BEGIN
         wcodsind = NULL;
         wlimemp = NULL;
         wlimsind = NULL;
         SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
         IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
            BEGIN
              SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
            END

         IF (wlimsind IS NULL) THEN
            wlimsind = 0;             -- não possui liminar

         IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
            SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;

         IF (wlimemp IS NULL) THEN
            wlimemp = 0;    -- não possui liminar

         BDGPSSEFIP     = 0;
         BDCODEMP       = wempatu;
         BDCODCOL       = wcolatu;
         BDREFFN        = wreffnatu;
         BDREFCOMP      = prrefpag;
         BDCODCENTRO    = wcentrosatu;
         BDCODTPCC      = wccatu;
         BDINSSFN       = winss;
         BDINSSFEFOLFN  = winssfe;
         BDINSS13FN     = winss13;
         BDBINSSFEFOLFN = wbaseinssfe;
         BDCODTIPOFC    = wcodfcatu;
         BDBINSSAPFN    = wbinssap;
         BDBINSS13APFN  = wbinss13ap;
         BDINSSAPFN     = wainssap;
         BDINSS13APFN   = wainss13ap;
         BDBAVPREV      = 0;
         bdbasepis      = wbasepis;
         bdbasepis13    = wbasepis13;
    
         if (bdbasepis < 0) then
           bdbasepis = 0;
         if (bdbasepis13 < 0) then
           bdbasepis13 = 0;


         if ((BDCODCENTRO is null and BDCODTPCC is not null) or (BDCODTPCC is null)) then
            begin
              select first 1 BDCODCENTROS from TEMPRESAS_REF where BDCODEMP = :wempatu and BDREFEMP <= :wreffnatu order by BDREFEMP DESC into :BDCODCENTRO;
            end

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSSFN = wbinssap;
         ELSE
            BDBINSSFN = wbaseinss;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13FN = wbaseinss13 - wbinss13ap;
         ELSE
            BDBINSS13FN = wbaseinss13;

         if (BDBINSS13FN < 0) then
            BDBINSS13FN = 0;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13INDFN = 0;
         ELSE
            BDBINSS13INDFN = wbinss13ap;

         wpercrat = 0;
         wcategoriaesoc = null;
         wcontrcol = null;
         SELECT first 1 BDPERCRATCOL, BDCATEGORIAESOCIAL, BDCONTRCOL
         FROM VRHF_EMP_TCOLCON_FGTSGPS
         WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :BDREFCOMP
         order by BDREFCOL DESC
         INTO :wpercrat, :wcategoriaesoc, :wcontrcol;
         wpercrat = coalesce(wpercrat, 0);
         wcategoriaesoc = coalesce(wcategoriaesoc, 0);
         wcontrcol = coalesce(wcontrcol, 0);

         -- 136305 - Raphael Teodoro - 21/08/2020
         wgrupocla = 0;
         SELECT CLA.BDGRUPOCLA
         FROM VW_VRH_EMP_TCOLCON_VINC VINC
         LEFT OUTER JOIN VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
         WHERE (VINC.BDCODEMP = :wempatu)
           AND (VINC.BDCODCOL = :wcolatu)
           AND (VINC.BDREFCOL <= :wreffnatu)
         ORDER BY BDCODEMP DESC, BDCODCOL DESC, BDREFCOL DESC
         INTO :wgrupocla;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BEGIN
              BDBRATAPOFN   = BDBINSSFN;
              BDBRATAPOFEFN = BDBINSSFEFOLFN;
              BDBRATAPO13FN = BDBINSS13FN;
            END
         ELSE
            BEGIN
              BDBRATAPOFN   = 0;
              BDBRATAPOFEFN = 0;
              BDBRATAPO13FN = 0;
            END

         BDSALFAMFN     = wsalfam;
         BDSALMATEMPFN  = wsalmatemp;

         BDBINSSMVFN    = wabasemv;
         BDBINSSMV13FN  = wabasemv13;
         BDVALREEMBOLSO = wreemb;
         BDVALINDEVIDO  = wvindevido;
         BDVALINDEVIDOSF  = wvindevidosf;

         if ((wcontrcol = 0) and
             (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
            BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
         else
            BDBASERAT = 0;

         BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
         BDBASEINSS13 = BDBINSS13FN;

         if (wcategoriaesoc in (107, 108)) then
            begin
              BDBINSSFN = BDBINSSFN + BDBINSS13FN;
              BDBINSS13FN = 0;

              select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :wreffnatu order by bdrefsm DESC INTO :WSALMIN;
              if (BDBINSSFN > WSALMIN * 1.5) then
                 begin
                   BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                 end
              else
                 begin
                   BDBINSSFN = 0;
                 end
            end

         SUSPEND;

         IF (prrefpag >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
            BEGIN
              BDGPSSEFIP     = 1;
              BDCODEMP       = wempatu;
              BDCODCOL       = wcolatu;
              BDREFFN        = wreffnatu;
              BDREFCOMP      = prrefpag;
              BDCODCENTRO    = wcentrosatu;
              BDCODTPCC      = wccatu;
              BDBAVPREV      = wbavprev;

              IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
                 BEGIN
                   IF (wbinssap < 0) THEN
                     wbinssap = 0;
                   BDINSSFN  = wainssap;
                   BDBINSSFN = wbinssap;
                 END
              ELSE
                 BEGIN
                   BDINSSFN  = winss;
                   BDBINSSFN = wbaseinss;
                 END

              BDINSSFEFOLFN  = winssfe;
              BDINSS13FN     = winss13;
              BDBINSSFEFOLFN = wbaseinssfe;
              BDBINSS13FN    = wbaseinss13;
              BDCODTIPOFC    = wcodfcatu;
              BDBINSSAPFN    = wbinssap;
              BDBINSS13APFN  = wbinss13ap;
              BDINSSAPFN     = wainssap;
              BDINSS13APFN   = wainss13ap;
              BDBINSS13INDFN = wbinss13ap;
     
              IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
                 BEGIN
                   BDBRATAPOFN   = BDBINSSFN;
                   BDBRATAPOFEFN = BDBINSSFEFOLFN;
                   BDBRATAPO13FN = BDBINSS13FN;
                 END
              ELSE
                 BEGIN
                   BDBRATAPOFN   = 0;
                   BDBRATAPOFEFN = 0;
                   BDBRATAPO13FN = 0;
                 END
     
              BDSALFAMFN     = wsalfam;
              BDSALMATEMPFN  = wsalmatemp;
     
              BDBINSSMVFN    = wabasemv;
              BDBINSSMV13FN  = wabasemv13;
              BDVALREEMBOLSO = wreemb;
              BDVALINDEVIDO  = wvindevido;
              BDVALINDEVIDOSF = wvindevidosf;

              if ((wcontrcol = 0) and
                  (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
                 BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
              else
                 BDBASERAT = 0;

              BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
              BDBASEINSS13 = BDBINSS13FN;

              if (wcategoriaesoc in (107, 108)) then
                 begin
                   BDBINSSFN = BDBINSSFN + BDBINSS13FN;
                   BDBINSS13FN = 0;

                   select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :wreffnatu order by bdrefsm DESC INTO :WSALMIN;
                   if (BDBINSSFN > WSALMIN * 1.5) then
                      begin
                        BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                      end
                   else
                      begin
                        BDBINSSFN = 0;
                      end
                 end

              SUSPEND;
            END

         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wcentrosatu = wcentros;
         wccatu      = wcc;
         wsalfam     = 0;
         winss       = 0;
         winssfe     = 0;
         winss13     = 0;
         wbaseinss   = 0;
         wbaseinssfe = 0;
         wbaseinss13 = 0;
         wsalmatemp  = 0;
         wabasemv    = 0;
         wabasemv13  = 0;
         wbinssap    = 0;
         wbinss13ap  = 0;
         wainss13ap  = 0;
         wainssap    = 0;
         wreemb      = 0;
         wvindevido  = 0;
         wvindevidosf = 0;
         wbavprev     = 0;
         wtemvalor   = 0;
         wreffca     = wreffc;
         wreffca     = wreffc;
         wbasepis    = 0;
         wbasepis13  = 0;
         wreffnatu   = wreffn;
       END

    wcodfcatu  = wcodtipofc;
    wainssap   = winssap;
    wainss13ap = winss13ap;
    wabasemv   = wbasemv;
    wabasemv13 = wbasemv13;

    IF (prrefpag >= 200903 AND prgpssefip = 1 AND wempap <> wcodemp) THEN
       BEGIN
         wsomaap = 0;
         SELECT SUM(BDSOMA) FROM (
           SELECT X.bdvalvfc BDSOMA
           FROM vrhf_emp_tverbafc X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :wreffn AND X.bdrefcomp = :prrefpag and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvfc BDSOMA
           FROM vrhf_emp_tverbafctomador X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :wreffn AND X.bdrefcomp = :prrefpag and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvfn BDSOMA
           FROM vrhf_emp_tverbafn X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :wreffn and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvft BDSOMA
           FROM vrhf_emp_tverbatomador X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :wreffn and Y.BDCODVER is not null
         )
         INTO :wsomaap;
         wempap = wcodemp;
       END

    -- INSS folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.0') THEN
       winss = winss + wvalor;

    -- INSS férias demonstradas na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.2') THEN
       winssfe = winssfe + wvalor;

    -- INSS 13o. complemento de 13º na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.6') THEN
       winss13 = winss13 + wvalor;

    -- INSS 13o. rescisão descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;

    -- Verifica se é VeA pois somente ele pode descontar o 13º na folha normal.
    IF (wverdeamarelo = 'TRUE') THEN
      BEGIN
      -- INSS 13o. descontado na folha normal
        IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.3') THEN
           winss13 = winss13 + wvalor;
      END

    -- Base de INSS folha normal
    IF ((winssver = 1)) THEN
       BEGIN
         IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
            BEGIN
              IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
       END
    ELSE
    IF ((winssver = 0)) THEN  --não incide
       BEGIN
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss13 = wbaseinss13 + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss13 = wbaseinss13 - wvalor;
            END
       END

    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 2) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END
    ELSE
    IF (winssver = 1 AND SUBSTRING(wclaver FROM 1 FOR 5) >= '0.100' AND SUBSTRING(wclaver FROM 1 FOR 5) < '0.200') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END

    -- Base de INSS 13o. salário descontado na rescisão
    IF ((winssver = 3)) THEN
       BEGIN
         IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
         IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       END

    -- Verifica diferença de incidência de PIS e Base GPS
    if (coalesce(UPPER(WDIFINCIDVER), 'FALSE') = 'TRUE') then
       begin
         if ((wbasegpsver <> wincidepis) and (WGRUPOCLA not in (2, 3))) then
            begin
              WSQLDIFINSSGPS = 'update or insert into VRHF_TINFO_TEMP_DIFINCIDVER (BDSESSAO, BDCODEMP, BDCODVER, BDDESCVER) '||
                               'values ('||current_connection||', '||wcodemp||', '||wcodver||', '''||wdescver||''') matching (BDSESSAO, BDCODEMP, BDCODVER)';
              execute statement WSQLDIFINSSGPS;
            end
       end

    -- Valor base PIS
    if (coalesce(UPPER(wincidepis), 'FALSE') = 'TRUE') then
      BEGIN
         IF (winssver = 3) THEN
           BEGIN
             IF (wtipocodver = 0) THEN  -- Provento
                wbasepis13 = wbasepis13 + wvalor;
             ELSE
               IF (wtipocodver = 1) THEN  -- Desconto
                  wbasepis13 = wbasepis13 - wvalor;
           END
         ELSE
           BEGIN
             IF (wtipocodver = 0) THEN  -- Provento
                wbasepis = wbasepis + wvalor;
             ELSE
               IF (wtipocodver = 1) THEN  -- Desconto
                  wbasepis = wbasepis - wvalor;
           END
      END

    -- Valor de salário família
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '9.050') THEN
       wsalfam = wsalfam + wvalor;

    -- Valor indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.2') THEN
       wvindevido = wvindevido + wvalor;

    -- Valor SF indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.0') THEN
       wvindevidosf = wvindevidosf + wvalor;

    -- Base de salário maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005') OR
         (SUBSTRING(wclaver FROM 1 FOR 7) = '7.061.2') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '0.610') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.710') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.070'))) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END

    -- Base INSS sem o aviso prévio indenizado
    IF (SUBSTRING(wclaver FROM 1 FOR 7) <> '7.001.3') THEN
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
              ELSE
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinss13ap = wbinss13ap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinss13ap = wbinss13ap - wvalor;

                   wtemvalor = 1;
                 END
            END
       END
    ELSE
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 7, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
       END

    -- INSS sobre o aviso prévio indenizado do 13º salário
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '7.060') THEN
       BEGIN
         IF (winssver = 3) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbinss13ap = wbinss13ap + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbinss13ap = wbinss13ap - wvalor;
            END
       END
  END


  IF ((wempatu <> 0) AND (wcolatu <> 0) AND ((wccatu <> 0) OR (wccatu IS NULL)) AND (wreffca <> 0) AND (wreffnatu <> 0)) THEN
     BEGIN
       wcodsind = NULL;
       wlimemp = NULL;
       wlimsind = NULL;
       SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
       IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
          BEGIN
            SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
          END

       IF (wlimsind IS NULL) THEN
          wlimsind = 0;             -- não possui liminar

       IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
          SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;

       IF (wlimemp IS NULL) THEN
          wlimemp = 0;    -- não possui liminar

       BDGPSSEFIP     = 0;
       BDCODEMP       = wempatu;
       BDCODCOL       = wcolatu;
       BDREFFN        = wreffnatu;
       BDREFCOMP      = prrefpag;
       BDCODCENTRO    = wcentrosatu;
       BDCODTPCC      = wccatu;
       BDINSSFN       = winss;
       BDINSSFEFOLFN  = winssfe;
       BDINSS13FN     = winss13;
       BDBINSSFEFOLFN = wbaseinssfe;
       BDCODTIPOFC    = wcodfcatu;
       BDBINSSAPFN    = wbinssap;
       BDBINSS13APFN  = wbinss13ap;
       BDINSSAPFN     = wainssap;
       BDINSS13APFN   = wainss13ap;
       BDBAVPREV      = 0;
       bdbasepis      = wbasepis;
       bdbasepis13    = wbasepis13;
    
       if (bdbasepis < 0) then
         bdbasepis = 0;
       if (bdbasepis13 < 0) then
         bdbasepis13 = 0;

       if ((BDCODCENTRO is null and BDCODTPCC is not null) or (BDCODTPCC is null)) then
          begin
            select first 1 BDCODCENTROS from TEMPRESAS_REF where BDCODEMP = :wempatu and BDREFEMP <= :wreffnatu order by BDREFEMP DESC into :BDCODCENTRO;
          end

       IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
          BDBINSSFN = wbinssap;
       ELSE
          BDBINSSFN = wbaseinss;
 
       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13FN = wbaseinss13 - wbinss13ap;
       ELSE
          BDBINSS13FN = wbaseinss13;

       if (BDBINSS13FN < 0) then
            BDBINSS13FN = 0;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13INDFN = 0;
       ELSE
          BDBINSS13INDFN = wbinss13ap;

       wpercrat = 0;
       select first 1 BDPERCRATCOL, BDCATEGORIAESOCIAL, BDCONTRCOL from VRHF_EMP_TCOLCON_FGTSGPS
       where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :BDREFCOMP
       order by BDREFCOL DESC into :wpercrat, :wcategoriaesoc, :wcontrcol;
       wpercrat = coalesce(wpercrat, 0);
       wcategoriaesoc = coalesce(wcategoriaesoc, 0);
       wcontrcol = coalesce(wcontrcol, 0);

       -- 136305 - Raphael Teodoro - 21/08/2020
       wgrupocla = 0;
       SELECT CLA.BDGRUPOCLA
       FROM VW_VRH_EMP_TCOLCON_VINC VINC
       LEFT OUTER JOIN VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
       WHERE (VINC.BDCODEMP = :wempatu)
         AND (VINC.BDCODCOL = :wcolatu)
         AND (VINC.BDREFCOL <= :wreffnatu)
       ORDER BY BDCODEMP DESC, BDCODCOL DESC, BDREFCOL DESC
       INTO :wgrupocla;

       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BEGIN
            BDBRATAPOFN   = wbaseinss;
            BDBRATAPOFEFN = wbaseinssfe;
            BDBRATAPO13FN = wbaseinss13;
          END
       ELSE
          BEGIN
            BDBRATAPOFN   = 0;
            BDBRATAPOFEFN = 0;
            BDBRATAPO13FN = 0;
          END

       BDSALFAMFN     = wsalfam;
       BDSALMATEMPFN  = wsalmatemp;

       BDBINSSMVFN    = wabasemv;
       BDBINSSMV13FN  = wabasemv13;
       BDVALREEMBOLSO = wreemb;
       BDVALINDEVIDO  = wvindevido;
       BDVALINDEVIDOSF = wvindevidosf;

       if ((wcontrcol = 0) and
           (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
          BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
       else
          BDBASERAT = 0;

       BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
       BDBASEINSS13 = BDBINSS13FN;

       if (wcategoriaesoc in (107, 108)) then
          begin
            BDBINSSFN = BDBINSSFN + BDBINSS13FN;
            BDBINSS13FN = 0;

            select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :wreffnatu order by bdrefsm DESC INTO :WSALMIN;
            if (BDBINSSFN > WSALMIN * 1.5) then
               begin
                 BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
               end
            else
               begin
                 BDBINSSFN = 0;
               end
          end

       SUSPEND;

       IF (prrefpag >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
          BEGIN
            BDGPSSEFIP     = 1;
            BDCODEMP       = wempatu;
            BDCODCOL       = wcolatu;
            BDREFFN        = wreffnatu;
            BDREFCOMP      = prrefpag;
            BDCODCENTRO    = wcentrosatu;
            BDCODTPCC      = wccatu;
            BDBAVPREV      = wbavprev;

            IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
               BEGIN
                 IF (wbinssap < 0) THEN
                   wbinssap = 0;
                 BDINSSFN  = wainssap;
                 BDBINSSFN = wbinssap;
               END
            ELSE
               BEGIN
                 BDINSSFN  = winss;
                 BDBINSSFN = wbaseinss;
               END

            BDINSSFEFOLFN  = winssfe;
            BDINSS13FN     = winss13;
            BDBINSSFEFOLFN = wbaseinssfe;
            BDBINSS13FN    = wbaseinss13;
            BDCODTIPOFC    = wcodfcatu;
            BDBINSSAPFN    = wbinssap;
            BDBINSS13APFN  = wbinss13ap;
            BDINSSAPFN     = wainssap;
            BDINSS13APFN   = wainss13ap;
            BDBINSS13INDFN = wbinss13ap;
     
            if (BDBINSS13FN < 0) then
               BDBINSS13FN = 0;

            IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
               BEGIN
                 BDBRATAPOFN   = BDBINSSFN;
                 BDBRATAPOFEFN = BDBINSSFEFOLFN;
                 BDBRATAPO13FN = BDBINSS13FN;
               END
            ELSE
               BEGIN
                 BDBRATAPOFN   = 0;
                 BDBRATAPOFEFN = 0;
                 BDBRATAPO13FN = 0;
               END
     
            BDSALFAMFN     = wsalfam;
            BDSALMATEMPFN  = wsalmatemp;
     
            BDBINSSMVFN    = wabasemv;
            BDBINSSMV13FN  = wabasemv13;
            BDVALREEMBOLSO = wreemb;
            BDVALINDEVIDO  = wvindevido;
            BDVALINDEVIDOSF = wvindevidosf;

            if ((wcontrcol = 0) and
                (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
               BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
            else
               BDBASERAT = 0;

            BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
            BDBASEINSS13 = BDBINSS13FN;

            if (wcategoriaesoc in (107, 108)) then
               begin
                 BDBINSSFN = BDBINSSFN + BDBINSS13FN;
                 BDBINSS13FN = 0;

                 select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :wreffnatu order by bdrefsm DESC INTO :WSALMIN;
                 if (BDBINSSFN > WSALMIN * 1.5) then
                    begin
                      BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                    end
                 else
                    begin
                      BDBINSSFN = 0;
                    end
               end

            SUSPEND;
          END
     END
END^


/* Restore proc. body: SP_VRHF_DADOS_INSS_FTC_ESOCIAL */
create or alter procedure SP_VRHF_DADOS_INSS_FTC_ESOCIAL (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32000),
    PRREFNEW integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS smallint = 0)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFCOMP integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFN numeric(18,6),
    BDINSSFEFOLFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSSFEFOLFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDBRATAPOFN numeric(18,6),
    BDBRATAPOFEFN numeric(18,6),
    BDBRATAPO13FN numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDSALMATEMPFN numeric(18,6),
    BDBINSSMVFN numeric(18,6),
    BDBINSSMV13FN numeric(18,6),
    BDCODTIPOFC integer,
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDBINSS13INDFN numeric(18,6),
    BDBASERAT numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEPIS numeric(18,6))
as
declare variable WCCNULL integer;
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(32000);
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WCENTROS integer;
declare variable WCENTROSATU integer;
declare variable WCC integer;
declare variable WCCATU integer;
declare variable WCLAVER varchar(20);
declare variable WTIPOCODVER integer;
declare variable WINSSVER integer;
declare variable WBASEGPSVER varchar(5);
declare variable WREEMBGPSVER varchar(5);
declare variable WVALOR numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WINSSFE numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WBASEINSS numeric(18,6);
declare variable WBASEINSSFE numeric(18,6);
declare variable WBASEINSS13 numeric(18,6);
declare variable WSALFAM numeric(18,6);
declare variable WSALMATEMP numeric(18,6);
declare variable WBASEMV numeric(18,6);
declare variable WBASEMV13 numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WCODTIPOFC integer;
declare variable WCODFCATU integer;
declare variable WBINSSAP numeric(18,6);
declare variable WBINSS13AP numeric(18,6);
declare variable WINSSAP numeric(18,6);
declare variable WINSS13AP numeric(18,6);
declare variable WAINSSAP numeric(18,6);
declare variable WAINSS13AP numeric(18,6);
declare variable WABASEMV numeric(18,6);
declare variable WABASEMV13 numeric(18,6);
declare variable WEMPAP integer;
declare variable WSOMAAP numeric(18,6);
declare variable WCODSIND integer;
declare variable WLIMSIND integer;
declare variable WLIMEMP integer;
declare variable WREEMB numeric(18,6);
declare variable WVINDEVIDO numeric(18,6);
declare variable WVINDEVIDOSF numeric(18,6);
declare variable WBAVPREV numeric(18,6);
declare variable WTEMVALOR smallint;
declare variable WREFFCA integer;
declare variable WREFFC integer;
declare variable WSALMIN numeric(15,2);
declare variable WCATEGORIAESOC integer;
declare variable WCONTRCOL integer;
declare variable WGRUPOCLA integer;
declare variable WINCIDEPIS DM_BOOLEAN;
declare variable WBASEPIS numeric(18,6);
BEGIN
  wsql = 'select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFFC, FC.BDVALVFC, FC.BDBINSSMVFC, FC.BDBINSSMV13FC, FC.BDINSSAPFC, FC.BDINSS13APFC, '||
                'VER.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, '||
                'PREP.BDCODCENTRO, PREP.BDCODTPCC, FC.BDCODTIPOFC, VERREF.BDPISVER from (';

  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFC, FN.BDVALVFC, FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, '||
                      'FOLN.BDINSS13APFC, FOLN.BDCODTIPOFC, cast(null as INTEGER) BDCODCONTTI, FN.BDCODVER, FN.BDORDEM ';

  if (coalesce(prfiliais, 0) = 1 and coalesce(prcodemp, '') <> '') then
     begin
       wsql = wsql||
              'from (select BDCODEMP from TEMPRESAS where (('||prcodemp||') or ('||REPLACE(UPPER(prcodemp), 'BDCODEMP', 'BDCODMATRIZ')||'))) EMP '||
              'join VRHF_EMP_TFOLTOMCOMP FOLN on (FOLN.BDCODEMP = EMP.BDCODEMP) ';
              /*'join (select BDCODEMP,BDCODCOL,BDREFTOMADOR,BDREFFC,BDORDEM,BDCODVER,BDVALVFC from VRHF_EMP_TVERBAFCTOMADOR ';

       wwhere = '';

       IF (PRREFNEW IS NOT NULL AND PRREFNEW <> 0) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'((BDREFTOMADOR = '||PRREFNEW||') or ('||'BDREFFC >= '||PRREFNEW||'01 and BDREFFC <= '||PRREFNEW||'31)) ';
          END

       if (wwhere <> '') then
          wsql = wsql||' where '||wwhere;

       wsql = wsql||') FN on (FN.BDCODEMP = EMP.BDCODEMP) ';*/
     end
  else
     begin
        wsql = wsql||'from VRHF_EMP_TFOLTOMCOMP FOLN ';
       /*wsql = wsql||'from (select BDCODEMP,BDCODCOL,BDREFTOMADOR,BDREFFC,BDORDEM,BDCODVER,BDVALVFC from VRHF_EMP_TVERBAFCTOMADOR ';
       wwhere  = '';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wwhere = wwhere||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||prcodcol;
          END
     
       IF (PRREFNEW IS NOT NULL AND PRREFNEW <> 0) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'((BDREFTOMADOR = '||PRREFNEW||') or ('||'BDREFFC >= '||PRREFNEW||'01 and BDREFFC <= '||PRREFNEW||'31)) ';
          END
     
       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;
     
       wsql = wsql||wwhere;
     
       wsql = wsql||') FN ';*/
     end

  wsql = wsql||'join VRHF_EMP_TVERBAFCTOMADOR FN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFTOMADOR = FN.BDREFTOMADOR and FOLN.BDREFFC = FN.BDREFFC and FOLN.BDORDEM = FN.BDORDEM) ';
  wsql = wsql||'left join VRH_EMP_TACCONV AC on (FOLN.BDCODEMP = AC.BDCODEMP and FOLN.BDCODACCONV = AC.BDCODACCONV) ';
  /*wsql = wsql||' where ((FOLN.BDREFTOMADOR = '||PRREFNEW||' and FOLN.BDCODACCONV is null) or ('||'FOLN.BDREFFC >= '||PRREFNEW||'01 and FOLN.BDREFFC <= '||PRREFNEW||'31 and FOLN.BDCODACCONV is not null)) ';*/
  wsql = wsql||' where ((FOLN.BDCODTIPOFC = 3 and AC.BDCODACCONV is not null) and '||
                      '(((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = '||PRREFNEW||')) or (FOLN.BDCODTIPOFC <> 3 and FOLN.BDREFTOMADOR = '||PRREFNEW||'))';


  wsql = wsql||' union all ';
  wsql = wsql||'select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFC, FN.BDVALVFC, FOLN.BDBINSSMVFC, FOLN.BDBINSSMV13FC, FOLN.BDINSSAPFC, '||
                      'FOLN.BDINSS13APFC, FOLN.BDCODTIPOFC, FN.BDCODCONTTI, FN.BDCODVER, FN.BDORDEM ';

  if (coalesce(prfiliais, 0) = 1 and coalesce(prcodemp, '') <> '') then
     begin
       wsql = wsql||
              'from (select BDCODEMP from TEMPRESAS where (('||prcodemp||') or ('||REPLACE(UPPER(prcodemp), 'BDCODEMP', 'BDCODMATRIZ')||'))) EMP '||
              'join VRHF_EMP_TFOLTOMCOMPINT FOLN on (FOLN.BDCODEMP = EMP.BDCODEMP) ';
              /*'join (select BDCODEMP,BDCODCOL,BDREFTOMADOR,BDREFFC,BDORDEM,BDCODVER,BDVALVFC,BDCODCONTTI from VRHF_EMP_TVERBAFCTOMINT ';

       wwhere = '';

       IF (PRREFNEW IS NOT NULL AND PRREFNEW <> 0) THEN
     BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'((BDREFTOMADOR = '||PRREFNEW||') or ('||'BDREFFC >= '||PRREFNEW||'01 and BDREFFC <= '||PRREFNEW||'31)) ';
     END

       if (wwhere <> '') then
          wsql = wsql||' where '||wwhere;

       wsql = wsql||') FN on (FN.BDCODEMP = EMP.BDCODEMP) ';*/
     end
  else
     begin
       wsql = wsql||'from VRHF_EMP_TFOLTOMCOMPINT FOLN ';
       /*wsql = wsql||'from (select BDCODEMP,BDCODCOL,BDREFTOMADOR,BDREFFC,BDORDEM,BDCODVER,BDVALVFC,BDCODCONTTI from VRHF_EMP_TVERBAFCTOMINT ';
       wwhere  = '';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wwhere = wwhere||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||prcodcol;
     END
     
       IF (PRREFNEW IS NOT NULL AND PRREFNEW <> 0) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';
     
            wwhere = wwhere||'((BDREFTOMADOR = '||PRREFNEW||') or ('||'BDREFFC >= '||PRREFNEW||'01 and BDREFFC <= '||PRREFNEW||'31)) ';
          END
     
       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;
     
       wsql = wsql||wwhere;
     
       wsql = wsql||') FN ';*/
     end

  wsql = wsql||'join VRHF_EMP_TVERBAFCTOMINT FN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODCOL = FN.BDCODCOL and FOLN.BDREFTOMADOR = FN.BDREFTOMADOR and FOLN.BDREFFC = FN.BDREFFC and FOLN.BDORDEM = FN.BDORDEM and FOLN.BDCODCONTTI = FN.BDCODCONTTI) ';
  wsql = wsql||'left join VRH_EMP_TACCONV AC on (FOLN.BDCODEMP = AC.BDCODEMP and FOLN.BDCODACCONV = AC.BDCODACCONV) ';
  /*wsql = wsql||' where ((FOLN.BDREFTOMADOR = '||PRREFNEW||' and FOLN.BDCODACCONV is null) or ('||'FOLN.BDREFFC >= '||PRREFNEW||'01 and FOLN.BDREFFC <= '||PRREFNEW||'31 and FOLN.BDCODACCONV is not null)) ';*/
  wsql = wsql||' where ((FOLN.BDCODTIPOFC = 3 and AC.BDCODACCONV is not null) and '||
                      '(((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = '||PRREFNEW||')) or (FOLN.BDCODTIPOFC <> 3 and FOLN.BDREFTOMADOR = '||PRREFNEW||'))';

  wsql = wsql||') FC ';
  wsql = wsql||'left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FC.BDCODVER) ';
  wsql = wsql||'left outer join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FC.BDCODVER) ';
  wsql = wsql||'left outer join VRHF_EMP_TPREPFN prep on (prep.bdcodemp = FC.bdcodemp and prep.bdcodcol = FC.bdcodcol and prep.bdordem = FC.bdordem) ';
  wsql = wsql||'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS FGTSGPS on (FGTSGPS.BDCODEMP = FC.BDCODEMP and FGTSGPS.BDCODCOL = FC.BDCODCOL) ';
  wsql = wsql||'where VER.BDCODVER is not null and VERREF.BDCODVER is not null and prep.BDCODEMP is not null ';
  wsql = wsql||'order by FC.BDCODEMP,FC.BDCODCOL,FC.BDREFFC,PREP.BDCODCENTRO,PREP.BDCODTPCC ';

  wempatu     = 0;
  wcolatu     = 0;
  wcentrosatu = 0;
  wccatu      = 0;
  wsalfam     = 0;
  winss       = 0;
  winssfe     = 0;
  winss13     = 0;
  wbaseinss   = 0;
  wbaseinssfe = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wbasemv     = 0;
  wbasemv13   = 0;
  wbinssap    = 0;
  wbinss13ap  = 0;
  wabasemv    = 0;
  wabasemv13  = 0;
  wainssap    = 0;
  wainss13ap  = 0;
  wempap      = 0;
  wsomaap     = 0;
  wreemb      = 0;
  wvindevido  = 0;
  wvindevidosf = 0;
  wbavprev     = 0;
  wtemvalor   = 0;
  wreffca     = 0;
  wreffca     = 0;
  wbasepis    = 0;

  EXECUTE PROCEDURE sp_seta_competencia(PRREFNEW);

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wreffc, :wvalor, :wbasemv, :wbasemv13, :winssap, :winss13ap, :wclaver, :wtipocodver, :winssver, :wbasegpsver, :wreembgpsver, :wcentros, :wcc, :wcodtipofc, :wincidepis DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wreffca = 0) THEN
       wreffca = wreffc;

    IF (wcentrosatu = 0) THEN
       wcentrosatu = wcentros;

    IF (wccatu = 0) THEN
       wccatu = wcc;

    wCCNull = 0;
    IF ((wccatu IS NULL) AND (wcc IS NOT NULL)) THEN
       wccnull = 1;
    IF ((wccatu IS NOT NULL) AND (wcc IS NULL)) THEN
       wccnull = 1;

    /*
      Retorna bases de INSS
    */
    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wcentrosatu <> wcentros) OR (wccatu <> wcc) OR (wCCNull = 1) OR (wreffca <> wreffc)) THEN
       BEGIN
         wcodsind = NULL;
         wlimemp = NULL;
         wlimsind = NULL;
         SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
         IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
            BEGIN
              SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
            END

         IF (wlimsind IS NULL) THEN
            wlimsind = 0;             -- não possui liminar

         IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
            SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;

         IF (wlimemp IS NULL) THEN
            wlimemp = 0;    -- não possui liminar

         BDGPSSEFIP     = 0;
         BDCODEMP       = wempatu;
         BDCODCOL       = wcolatu;
         BDREFFN        = PRREFNEW;
         BDREFCOMP      = PRREFNEW;
         BDCODCENTRO    = wcentrosatu;
         BDCODTPCC      = wccatu;
         BDINSSFN       = winss;
         BDINSSFEFOLFN  = winssfe;
         BDINSS13FN     = winss13;
         BDBINSSFEFOLFN = wbaseinssfe;
         BDCODTIPOFC    = wcodfcatu;
         BDBINSSAPFN    = wbinssap;
         BDBINSS13APFN  = wbinss13ap;
         BDINSSAPFN     = wainssap;
         BDINSS13APFN   = wainss13ap;
         BDBAVPREV      = 0;
         bdbasepis      = wbasepis;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSSFN = wbinssap;
         ELSE
            BDBINSSFN = wbaseinss;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13FN = wbaseinss13 - wbinss13ap;
         ELSE
            BDBINSS13FN = wbaseinss13;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13INDFN = 0;
         ELSE
            BDBINSS13INDFN = wbinss13ap;

         wpercrat = 0;
         wcategoriaesoc = null;
         wcontrcol = null;
         select first 1 BDPERCRATCOL, BDCATEGORIAESOCIAL, BDCONTRCOL from VRHF_EMP_TCOLCON_FGTSGPS
         where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :PRREFNEW
         order by BDREFCOL DESC
         into :wpercrat, :wcategoriaesoc, :wcontrcol;
         wpercrat = coalesce(wpercrat, 0);
         wcategoriaesoc = coalesce(wcategoriaesoc, 0);
         wcontrcol = coalesce(wcontrcol, 0);

         -- 136305 - Raphael Teodoro - 21/08/2020
         wgrupocla = 0;
         SELECT CLA.BDGRUPOCLA
         FROM VW_VRH_EMP_TCOLCON_VINC VINC
         LEFT OUTER JOIN VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
         WHERE (VINC.BDCODEMP = :wempatu)
           AND (VINC.BDCODCOL = :wcolatu)
           AND (VINC.BDREFCOL <= :prrefnew)
         ORDER BY BDCODEMP DESC, BDCODCOL DESC, BDREFCOL DESC
         INTO :wgrupocla;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BEGIN
              BDBRATAPOFN   = BDBINSSFN;
              BDBRATAPOFEFN = BDBINSSFEFOLFN;
              BDBRATAPO13FN = BDBINSS13FN;
            END
         ELSE
            BEGIN
              BDBRATAPOFN   = 0;
              BDBRATAPOFEFN = 0;
              BDBRATAPO13FN = 0;
            END

         BDSALFAMFN     = wsalfam;
         BDSALMATEMPFN  = wsalmatemp;

         BDBINSSMVFN    = wabasemv;
         BDBINSSMV13FN  = wabasemv13;
         BDVALREEMBOLSO = wreemb;
         BDVALINDEVIDO  = wvindevido;
         BDVALINDEVIDOSF  = wvindevidosf;

         if ((wcontrcol = 0) and
             (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
            BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
         else
            BDBASERAT = 0;

         BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
         BDBASEINSS13 = BDBINSS13FN;

         if (wcategoriaesoc in (107, 108)) then
            begin
              BDBINSSFN = BDBINSSFN + BDBINSS13FN;
              BDBINSS13FN = 0;

              select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREFNEW order by bdrefsm DESC INTO :WSALMIN;
              if (BDBINSSFN > WSALMIN * 1.5) then
                 begin
                   BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                 end
              else
                 begin
                   BDBINSSFN = 0;
                 end
            end

         SUSPEND;

         IF (PRREFNEW >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
            BEGIN
              BDGPSSEFIP     = 1;
              BDCODEMP       = wempatu;
              BDCODCOL       = wcolatu;
              BDREFFN        = PRREFNEW;
              BDREFCOMP      = PRREFNEW;
              BDCODCENTRO    = wcentrosatu;
              BDCODTPCC      = wccatu;
              BDBAVPREV      = wbavprev;

              IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
                 BEGIN
                   IF (wbinssap < 0) THEN
                     wbinssap = 0;
                   BDINSSFN  = wainssap;
                   BDBINSSFN = wbinssap;
                 END
              ELSE
                 BEGIN
                   BDINSSFN  = winss;
                   BDBINSSFN = wbaseinss;
                 END

              BDINSSFEFOLFN  = winssfe;
              BDINSS13FN     = winss13;
              BDBINSSFEFOLFN = wbaseinssfe;
              BDBINSS13FN    = wbaseinss13;
              BDCODTIPOFC    = wcodfcatu;
              BDBINSSAPFN    = wbinssap;
              BDBINSS13APFN  = wbinss13ap;
              BDINSSAPFN     = wainssap;
              BDINSS13APFN   = wainss13ap;
              BDBINSS13INDFN = wbinss13ap;
     
              IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
                 BEGIN
                   BDBRATAPOFN   = BDBINSSFN;
                   BDBRATAPOFEFN = BDBINSSFEFOLFN;
                   BDBRATAPO13FN = BDBINSS13FN;
                 END
              ELSE
                 BEGIN
                   BDBRATAPOFN   = 0;
                   BDBRATAPOFEFN = 0;
                   BDBRATAPO13FN = 0;
                 END
     
              BDSALFAMFN     = wsalfam;
              BDSALMATEMPFN  = wsalmatemp;
     
              BDBINSSMVFN    = wabasemv;
              BDBINSSMV13FN  = wabasemv13;
              BDVALREEMBOLSO = wreemb;
              BDVALINDEVIDO  = wvindevido;
              BDVALINDEVIDOSF = wvindevidosf;

              if ((wcontrcol = 0) and
                  (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
                 BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
              else
                 BDBASERAT = 0;

              BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
              BDBASEINSS13 = BDBINSS13FN;

              if (wcategoriaesoc in (107, 108)) then
                 begin
                   BDBINSSFN = BDBINSSFN + BDBINSS13FN;
                   BDBINSS13FN = 0;

                   select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREFNEW order by bdrefsm DESC INTO :WSALMIN;
                   if (BDBINSSFN > WSALMIN * 1.5) then
                      begin
                        BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                      end
                   else
                      begin
                        BDBINSSFN = 0;
                      end
                 end

              SUSPEND;
            END

         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wcentrosatu = wcentros;
         wccatu      = wcc;
         wsalfam     = 0;
         winss       = 0;
         winssfe     = 0;
         winss13     = 0;
         wbaseinss   = 0;
         wbaseinssfe = 0;
         wbaseinss13 = 0;
         wsalmatemp  = 0;
         wabasemv    = 0;
         wabasemv13  = 0;
         wbinssap    = 0;
         wbinss13ap  = 0;
         wainss13ap  = 0;
         wainssap    = 0;
         wreemb      = 0;
         wvindevido  = 0;
         wvindevidosf = 0;
         wbavprev     = 0;
         wtemvalor   = 0;
         wreffca     = wreffc;
         wreffca     = wreffc;
         wbasepis    = 0;
       END

    wcodfcatu  = wcodtipofc;
    wainssap   = winssap;
    wainss13ap = winss13ap;
    wabasemv   = wbasemv;
    wabasemv13 = wbasemv13;

    IF (PRREFNEW >= 200903 AND prgpssefip = 1 AND wempap <> wcodemp) THEN
       BEGIN
         wsomaap = 0;
         SELECT SUM(BDSOMA) FROM (
           SELECT X.bdvalvfc BDSOMA
           FROM vrhf_emp_tverbafc X
           LEFT OUTER JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :PRREFNEW AND X.bdrefcomp = :PRREFNEW and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvfc BDSOMA
           FROM vrhf_emp_tverbafctomador X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :PRREFNEW AND X.bdrefcomp = :PRREFNEW and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvfn BDSOMA
           FROM vrhf_emp_tverbafn X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreffn = :PRREFNEW and Y.BDCODVER is not null
           UNION ALL
           SELECT X.bdvalvft BDSOMA
           FROM vrhf_emp_tverbatomador X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp AND X.bdreftomador = :PRREFNEW and Y.BDCODVER is not null
         )
         INTO :wsomaap;
         wempap = wcodemp;
       END

    -- INSS folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.0') THEN
       winss = winss + wvalor;

    -- INSS férias demonstradas na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.2') THEN
       winssfe = winssfe + wvalor;

    -- INSS 13o. complemento de 13º na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.6') THEN
       winss13 = winss13 + wvalor;

    -- INSS 13o. rescisão descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;

    -- Base de INSS folha normal
    IF ((winssver = 1)) THEN
       BEGIN
         IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
            BEGIN
              IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
       END
    ELSE
    IF ((winssver = 0)) THEN  --não incide
       BEGIN
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                 wbaseinss13 = wbaseinss13 + wvalor;
              ELSE
              IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE'))  THEN  -- Desconto
                 wbaseinss13 = wbaseinss13 - wvalor;
            END
       END

    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 2) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END
    ELSE
    IF (winssver = 1 AND SUBSTRING(wclaver FROM 1 FOR 5) >= '0.100' AND SUBSTRING(wclaver FROM 1 FOR 5) < '0.200') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END

    -- Base de INSS 13o. salário descontado na rescisão
    IF ((winssver = 3)) THEN
       BEGIN
         IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
         IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       END

        -- Valor base PIS
    if (coalesce(UPPER(wincidepis), 'FALSE') = 'TRUE') then
       begin
          IF (wtipocodver = 0) THEN  -- Provento
             wbasepis = wbasepis + wvalor;
          ELSE
          IF (wtipocodver = 1) THEN  -- Desconto
             wbasepis = wbasepis - wvalor;
       end

    -- Valor de salário família
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '9.050') THEN
       wsalfam = wsalfam + wvalor;

    -- Valor indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.2') THEN
       wvindevido = wvindevido + wvalor;

    -- Valor SF indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.0') THEN
       wvindevidosf = wvindevidosf + wvalor;

    -- Base de salário maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005') OR
         (SUBSTRING(wclaver FROM 1 FOR 7) = '7.061.2') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '0.610') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.710'))) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END

    -- Base INSS sem o aviso prévio indenizado
    IF (SUBSTRING(wclaver FROM 1 FOR 7) <> '7.001.3') THEN
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
              ELSE
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinss13ap = wbinss13ap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinss13ap = wbinss13ap - wvalor;

                   wtemvalor = 1;
                 END
            END
       END
    ELSE
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 7, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
       END

    -- INSS sobre o aviso prévio indenizado do 13º salário
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '7.060') THEN
       BEGIN
         IF (winssver = 3) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbinss13ap = wbinss13ap + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbinss13ap = wbinss13ap - wvalor;
            END
       END
  END


  IF ((wempatu <> 0) AND (wcolatu <> 0) AND ((wccatu <> 0) OR (wccatu IS NULL)) AND (wreffca <> 0)) THEN
     BEGIN
       wcodsind = NULL;
       wlimemp = NULL;
       wlimsind = NULL;
       SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
       IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
          BEGIN
            SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
          END

       IF (wlimsind IS NULL) THEN
          wlimsind = 0;             -- não possui liminar

       IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
          SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;

       IF (wlimemp IS NULL) THEN
          wlimemp = 0;    -- não possui liminar

       BDGPSSEFIP     = 0;
       BDCODEMP       = wempatu;
       BDCODCOL       = wcolatu;
       BDREFFN        = PRREFNEW;
       BDREFCOMP      = PRREFNEW;
       BDCODCENTRO    = wcentrosatu;
       BDCODTPCC      = wccatu;
       BDINSSFN       = winss;
       BDINSSFEFOLFN  = winssfe;
       BDINSS13FN     = winss13;
       BDBINSSFEFOLFN = wbaseinssfe;
       BDCODTIPOFC    = wcodfcatu;
       BDBINSSAPFN    = wbinssap;
       BDBINSS13APFN  = wbinss13ap;
       BDINSSAPFN     = wainssap;
       BDINSS13APFN   = wainss13ap;
       BDBAVPREV      = 0;
       bdbasepis      = wbasepis;

       IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
          BDBINSSFN = wbinssap;
       ELSE
          BDBINSSFN = wbaseinss;
 
       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13FN = wbaseinss13 - wbinss13ap;
       ELSE
          BDBINSS13FN = wbaseinss13;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13INDFN = 0;
       ELSE
          BDBINSS13INDFN = wbinss13ap;

       wpercrat = 0;
       wcategoriaesoc = null;
       wcontrcol = null;
       select first 1 BDPERCRATCOL, BDCATEGORIAESOCIAL, BDCONTRCOL from VRHF_EMP_TCOLCON_FGTSGPS
       where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :PRREFNEW
       order by BDREFCOL DESC
       into :wpercrat, :wcategoriaesoc, :wcontrcol;
       wpercrat = coalesce(wpercrat, 0);
       wcategoriaesoc = coalesce(wcategoriaesoc, 0);
       wcontrcol = coalesce(wcontrcol, 0);

       -- 136305 - Raphael Teodoro - 21/08/2020
       wgrupocla = 0;
       SELECT CLA.BDGRUPOCLA
       FROM VW_VRH_EMP_TCOLCON_VINC VINC
       LEFT OUTER JOIN VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
       WHERE (VINC.BDCODEMP = :wempatu)
         AND (VINC.BDCODCOL = :wcolatu)
         AND (VINC.BDREFCOL <= :prrefnew)
       ORDER BY BDCODEMP DESC, BDCODCOL DESC, BDREFCOL DESC
       INTO :wgrupocla;

       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BEGIN
            BDBRATAPOFN   = wbaseinss;
            BDBRATAPOFEFN = wbaseinssfe;
            BDBRATAPO13FN = wbaseinss13;
          END
       ELSE
          BEGIN
            BDBRATAPOFN   = 0;
            BDBRATAPOFEFN = 0;
            BDBRATAPO13FN = 0;
          END

       BDSALFAMFN     = wsalfam;
       BDSALMATEMPFN  = wsalmatemp;

       BDBINSSMVFN    = wabasemv;
       BDBINSSMV13FN  = wabasemv13;
       BDVALREEMBOLSO = wreemb;
       BDVALINDEVIDO  = wvindevido;
       BDVALINDEVIDOSF = wvindevidosf;

       if ((wcontrcol = 0) and
           (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
          BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
       else
          BDBASERAT = 0;

       BDBASEINSS = BDBINSSFN + BDBINSSFEFOLFN;
       BDBASEINSS13 = BDBINSS13FN;

       if (wcategoriaesoc in (107, 108)) then
          begin
            BDBINSSFN = BDBINSSFN + BDBINSS13FN;
            BDBINSS13FN = 0;

            select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREFNEW order by bdrefsm DESC INTO :WSALMIN;
            if (BDBINSSFN > WSALMIN * 1.5) then
               begin
                 BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
               end
            else
               begin
                 BDBINSSFN = 0;
               end
          end

       SUSPEND;

       IF (PRREFNEW >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
          BEGIN
            BDGPSSEFIP     = 1;
            BDCODEMP       = wempatu;
            BDCODCOL       = wcolatu;
            BDREFFN        = PRREFNEW;
            BDREFCOMP      = PRREFNEW;
            BDCODCENTRO    = wcentrosatu;
            BDCODTPCC      = wccatu;
            BDBAVPREV      = wbavprev;

            IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
               BEGIN
                 IF (wbinssap < 0) THEN
                   wbinssap = 0;
                 BDINSSFN  = wainssap;
                 BDBINSSFN = wbinssap;
               END
            ELSE
               BEGIN
                 BDINSSFN  = winss;
                 BDBINSSFN = wbaseinss;
               END

            BDINSSFEFOLFN  = winssfe;
            BDINSS13FN     = winss13;
            BDBINSSFEFOLFN = wbaseinssfe;
            BDBINSS13FN    = wbaseinss13;
            BDCODTIPOFC    = wcodfcatu;
            BDBINSSAPFN    = wbinssap;
            BDBINSS13APFN  = wbinss13ap;
            BDINSSAPFN     = wainssap;
            BDINSS13APFN   = wainss13ap;
            BDBINSS13INDFN = wbinss13ap;
     
            IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
               BEGIN
                 BDBRATAPOFN   = BDBINSSFN;
                 BDBRATAPOFEFN = BDBINSSFEFOLFN;
                 BDBRATAPO13FN = BDBINSS13FN;
               END
            ELSE
               BEGIN
                 BDBRATAPOFN   = 0;
                 BDBRATAPOFEFN = 0;
                 BDBRATAPO13FN = 0;
               END
     
            BDSALFAMFN     = wsalfam;
            BDSALMATEMPFN  = wsalmatemp;
     
            BDBINSSMVFN    = wabasemv;
            BDBINSSMV13FN  = wabasemv13;
            BDVALREEMBOLSO = wreemb;
            BDVALINDEVIDO  = wvindevido;
            BDVALINDEVIDOSF = wvindevidosf;

            if ((wcontrcol = 0) and
                (wgrupocla <> 2)) then -- 136305 - Raphael Teodoro - 21/08/2020
               BDBASERAT = BDBINSSFN + BDBINSS13FN + BDBINSSFEFOLFN;
            else
               BDBASERAT = 0;

            BDBASEINSS   = BDBINSSFN + BDBINSSFEFOLFN;
            BDBASEINSS13 = BDBINSS13FN;
            bdbasepis    = wbasepis;

            if (wcategoriaesoc in (107, 108)) then
               begin
                 BDBINSSFN = BDBINSSFN + BDBINSS13FN;
                 BDBINSS13FN = 0;

                 select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREFNEW order by bdrefsm DESC INTO :WSALMIN;
                 if (BDBINSSFN > WSALMIN * 1.5) then
                    begin
                      BDBINSSFN = BDBINSSFN - WSALMIN * 1.5;
                    end
                 else
                    begin
                      BDBINSSFN = 0;
                    end
               end

            SUSPEND;
          END
     END
END^

/* Restore proc. body: SP_VRHF_DADOS_IR_AD13 */
create or alter procedure SP_VRHF_DADOS_IR_AD13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ )
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WSQL varchar(5000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WDATAPGTO date;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WPREPRI numeric(18,6);
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WCODVER integer;
declare variable WGRAVARUBRICA integer;
BEGIN
  /*  PENSÕES DO ADIANTAMENTO DE 13º SALÁRIO  */
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;

  if (upper(PRCODEMP) = 'TMP_EMPRESAS_SELECT') then
    WUSARTMP_EMP_SELECT = 1;

  if (upper(PRCODCOL) = 'TEMP_FILTRO_COLCON_REL') then
    WUSARTMP_COL_SELECT = 1;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  if (PRPUXARFILIAIS = 0) then
  begin
    WSQL = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFA13, FOL.BDVALVA13, VER.BDCLAVER,VER.BDCODVER ';
    WSQL = WSQL || 'from VRHF_EMP_TVERBAA13 FOL ';

    if (WUSARTMP_EMP_SELECT = 1) then
      WSQL = WSQL || 'INNER JOIN tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
      WSQL = WSQL || 'JOIN TEMP_FILTRO_COLCON_REL TEM ON (TEM.BDCODEMP = FOL.BDCODEMP AND TEM.BDCODCOL = FOL.BDCODCOL) ';

    WSQL = WSQL || 'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) ' || 'where (VER.BDCLAVER starting with ''4.001.8'' or VER.BDCLAVER starting with ''4.009.0'') and FOL.BDREFA13 >= ' || PRREFINI || ' and FOL.BDREFA13 <= ' || PRREFFIM;
    --160514 LuizCovre 05/07/2022
    if (PRCODEMP is not null and
        PRCODEMP <> '' and
        WUSARTMP_EMP_SELECT = 0) then
      WSQL = WSQL || ' and ' || PRCODEMP;
    if (PRCODCOL is not null and
        PRCODCOL <> '' and
        WUSARTMP_COL_SELECT = 0) then
      WSQL = WSQL || ' and ' || PRCODCOL;
    WSQL = WSQL || ' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFA13 ';
  end
  else
  begin
    WSQL = 'select FO.BDCODEMP, FO.BDCODCOL, FO.BDREFA13, FO.BDVALVA13, VER.BDCLAVER,VER.BDCODVER ';
    WSQL = WSQL || 'from VRHF_EMP_TVERBAA13 FO join TEMPRESAS EMAT on (EMAT.BDCODEMP = FO.BDCODEMP) ';

    if (WUSARTMP_EMP_SELECT = 1) then
      WSQL = WSQL || 'inner join TMP_EMPRESAS_SELECT TEMP on (TEMP.BDCODEMP = FO.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
      WSQL = WSQL || 'inner join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FO.BDCODEMP and TEM.BDCODCOL = FO.BDCODCOL) ';

    WSQL = WSQL || 'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FO.BDCODVER) ' ||
           'where (VER.BDCLAVER starting with ''4.001.8'' or VER.BDCLAVER starting with ''4.009.0'') and FO.BDREFA13 >= ' || PRREFINI || ' and FO.BDREFA13 <= ' || PRREFFIM;
    --160514 LuizCovre 05/07/2022
    if (WUSARTMP_EMP_SELECT = 0) then
    begin
      if (PRCODEMP is not null and
          PRCODEMP <> '') then
        WSQL = WSQL || ' and ((' || replace(upper(PRCODEMP), 'FOL.', 'FO.') || ')';
      if (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '') then
        WSQL = WSQL || ' or (' || replace(upper(PRCODMATRIZ), 'FOL.', 'EMAT.') || ')';
      if (PRCODEMP is not null and
          PRCODEMP <> '') then
        WSQL = WSQL || ') ';
    end

    if (PRCODCOL is not null and
        PRCODCOL <> '' and
        WUSARTMP_COL_SELECT = 0) then
      WSQL = WSQL || ' and ' || replace(upper(PRCODCOL), 'FOL.', 'FO.') || ' ';

    WSQL = WSQL || ' order by FO.BDCODEMP,FO.BDCODCOL,FO.BDREFA13 ';
  end

  WEMPATU = 0;
  WCOLATU = 0;
  WREFATU = 0;
  WPENALIM = 0;
  WPENJUD = 0;
  WPREPRI = 0; --160514 LuizCovre 05/07/2022
  BDRENDTRIBUTAVEL = 0;
  BDINSS = 0;
  BDIR = 0;
  BDDEP = 0;
  BDPREVPRIV = 0;
  BDINDRESC = 0;
  BDVALABO = 0;
  BDRENDISENTOS = 0;
  BDDRENDISENTOS = '';
  BDINFADIC = '';
  BDLUCROPJ = 0;
  BDDESPMED = 0;
  BDAJCUSTOS = 0;
  BDDATAPROC = null;
  BDHORAPROC = null;
  BDORDEM = null;
  BDAUXILIOMORADIA = 0;
  BDDIARIA = 0;
  BDBOLSAMEDICO = 0;
  BDJUROSMORA = 0;
  BDINCIDESOCIAL = 0;

  for execute statement WSQL
          into :WCODEMP, :WCODCOL, :WREF, :WVALOR, :WCLASSIF,:WCODVER
  do
  begin
    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end
	   
    BDCODTIPO = 272; -- Cálculos gerados no Único Folha
    if (WEMPATU = 0) then
      WEMPATU = WCODEMP;
    if (WCOLATU = 0) then
      WCOLATU = WCODCOL;
    if (WREFATU = 0) then
      WREFATU = WREF;

    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL) or (WREFATU <> WREF)) then
    begin
      if (cast(substring(WREFATU from 5 for 2) as integer) in (1, 3, 5, 7, 8, 10, 12)) then
        WDATAPGTO = cast((substring(WREFATU from 5 for 2) || '-31-' || substring(WREFATU from 1 for 4)) as date);
      else
      if (cast(substring(WREFATU from 5 for 2) as integer) in (4, 6, 9, 11)) then
        WDATAPGTO = cast((substring(WREFATU from 5 for 2) || '-30-' || substring(WREFATU from 1 for 4)) as date);
      else
        WDATAPGTO = cast((substring(WREFATU from 5 for 2) || '-28-' || substring(WREFATU from 1 for 4)) as date);

      BDCODEMP = WEMPATU;
      BDCODCOL = WCOLATU;
      BDREF = WREFATU;
      BDREFPAG = WREFATU;
      BDREFIRRFESOCIAL = BDREFPAG;
      BDTIPO = 9; -- Adiantamento de 13º
      BDPENJUD = WPENJUD;
      BDPENALIM = WPENALIM;
      BDDATAPGTO = WDATAPGTO;
      suspend;
      WEMPATU = WCODEMP;
      WCOLATU = WCODCOL;
      WREFATU = WREF;
      WPENJUD = 0;
      WPENALIM = 0;
    end

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
	   end

    if (substring(WCLASSIF from 1 for 9) = '4.001.8.0') then
      WPENJUD = WPENJUD + WVALOR;
    if (substring(WCLASSIF from 1 for 9) = '4.001.8.1') then
      WPENALIM = WPENALIM + WVALOR;
    if (substring(WCLASSIF from 1 for 9) = '4.009.0.0') then -- Previdência complementar 160514 LuizCovre 05/07/2022
      WPREPRI = WPREPRI + WVALOR;
  end

  if (WEMPATU <> 0 and
      WCOLATU <> 0 and
      WREFATU <> 0) then
  begin
    if (cast(substring(WREFATU from 5 for 2) as integer) in (1, 3, 5, 7, 8, 10, 12)) then
      WDATAPGTO = cast((substring(WREFATU from 5 for 2) || '-31-' || substring(WREFATU from 1 for 4)) as date);
    else
    if (cast(substring(WREFATU from 5 for 2) as integer) in (4, 6, 9, 11)) then
      WDATAPGTO = cast((substring(WREFATU from 5 for 2) || '-30-' || substring(WREFATU from 1 for 4)) as date);
    else
      WDATAPGTO = cast((substring(WREFATU from 5 for 2) || '-28-' || substring(WREFATU from 1 for 4)) as date);

    BDCODEMP = WEMPATU;
    BDCODCOL = WCOLATU;
    BDREF = WREFATU;
    BDREFPAG = WREFATU;
    BDREFIRRFESOCIAL = BDREFPAG;
    BDTIPO = 9; -- Adiantamento de 13º
    BDPENJUD = WPENJUD;
    BDPENALIM = WPENALIM;
    BDDATAPGTO = WDATAPGTO;
    BDPREVPRIV = WPREPRI; --160514 LuizCovre 05/07/2022
    suspend;
  end
end^

/* Restore proc. body: SP_VRHF_DADOS_IR_13FN */
create or alter procedure SP_VRHF_DADOS_IR_13FN (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0,
    PRPORCC smallint = 1)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,6),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR13 numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WINSS13 numeric(18,6);
declare variable WIR13 numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WREFINI integer;
declare variable WDATARESC date;
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WDATAPGTO date;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WTIPOMOV integer;
declare variable WPREVPRIVCAD numeric(18,6);
declare variable WEXISTE13MES integer;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WTIPODEDUCAO integer;
declare variable WVALORDESCSIMPL numeric(18,2);
declare variable WVALORDIFDESCSIMPL numeric(18,2);
declare variable WSQLAUXSIMPLI varchar(3000);
declare variable WTIPODEDUCAOATU integer;
declare variable WVALORDESCSIMPLATU numeric(18,2);
declare variable WVALORDIFDESCSIMPLATU numeric(18,2);
declare variable WREFPGTOAUX integer;
declare variable WWHERERESCREINT varchar(32700);
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
declare variable WTEMVERBA13 boolean;
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WGRAVARUBRICA integer;
begin
  BDBOLSAESTUDOS = 0;
  BDINDRESC = 0;
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  if (upper(PRCODEMP) = 'TMP_EMPRESAS_SELECT') then
    WUSARTMP_EMP_SELECT = 1;
  if (upper(PRCODCOL) = 'TEMP_FILTRO_COLCON_REL') then
    WUSARTMP_COL_SELECT = 1;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  /* 13º RESCISAO DA FOLHA NORMAL */
  if (cast(substring(PRREFINI from 5 for 2) as integer) = 1) then
    WREFINI = cast((cast((cast(substring(PRREFINI from 1 for 4) as integer) - 1) as varchar(4)) || '12') as integer);
  else
  if (cast(substring(PRREFINI from 5 for 2) as integer) <= 10) then
    WREFINI = cast((substring(PRREFINI from 1 for 4) || '0' || cast((cast((substring(PRREFINI from 5 for 2)) as integer) - 1) as varchar(1))) as integer);
  else
    WREFINI = cast((substring(PRREFINI from 1 for 4) || cast((cast((substring(PRREFINI from 5 for 2)) as integer) - 1) as varchar(2))) as integer);

  WWHERERESCREINT = ' inner JOIN TEMPRESAS REMP on (REMP.BDCODEMP = FOL.BDCODEMP) ';
  if (WUSARTMP_EMP_SELECT = 1) then
     begin
       WWHERERESCREINT = WWHERERESCREINT||' inner JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';
       if (WUSARTMP_COL_SELECT = 1) then
          WWHERERESCREINT = WWHERERESCREINT||' inner join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';
     end
  else
  begin
    if (WUSARTMP_COL_SELECT = 1) then
       WWHERERESCREINT = WWHERERESCREINT||' inner join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

    if (wusartmp_col_select = 0 and wusartmp_emp_select = 0) then
       begin
         if (prpuxarfiliais = 0) then
            begin
              if (PRCODEMP is not null and PRCODEMP <> '') then
                 WWHERERESCREINT = WWHERERESCREINT||' where (' || PRCODEMP || ') ';

              if (PRCODCOL is not null and PRCODCOL <> '') then
                 WWHERERESCREINT = WWHERERESCREINT||' and (' || PRCODCOL || ') ';
            end
         else
            begin
              if (PRCODEMP is not null and PRCODEMP <> '') then
                 WWHERERESCREINT = WWHERERESCREINT||' where ((' || REPLACE(UPPER(PRCODEMP), 'FOL.', 'REMP.') || ')';
              if (PRCODMATRIZ is not null and PRCODMATRIZ <> '') then
                 WWHERERESCREINT = WWHERERESCREINT || ' or (' || REPLACE(UPPER(PRCODMATRIZ), 'FOL.', 'REMP.') || ')) ';

              if (PRCODCOL is not null and PRCODCOL <> '') then
                WWHERERESCREINT = WWHERERESCREINT || ' and (' || PRCODCOL|| ') ';
            end
       end
  end

  if (PRPUXARFILIAIS = 0) then
  begin
    if (PRIRRFESOCIAL = true) then
      WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODVER,FOL.BDVALVFN,FOLN.BDDEPFN,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGRESCISAO,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN,COALESCE(PRESC.BDTIPOMOV,0),FOLN.BDDATAPGTOFN, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
    else
      WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODVER,FOL.BDVALVFN,FOLN.BDDEPFN,RESC.BDDATAPAGRESCISAO,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN,COALESCE(PRESC.BDTIPOMOV,0),FOLN.BDDATAPGTOFN, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';

    wsql = wsql||'from ('||
                   'select R.BDCODEMP, R.BDCODCOL, max(R.BDDATAPAGRESCISAO) as BDDATAPAGRESCISAO, max(R.BDREFRESCISAO) as BDREFRESCISAO, max(R.BDCODPRES) as BDCODPRES, max(R.BDREFPAGRESCISAO) as BDREFPAGRESCISAO from ( ' ||
                      'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDDATAPAGRESCISAO, FOL.BDREFRESCISAO, FOL.BDCODPRES, FOL.BDREFPAGRESCISAO '||
                      'from vrh_emp_trescisao FOL '||WWHERERESCREINT||' '||
                      'union all '||
                      'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDDATAPAGRESCISAO, FOL.BDREFRESCISAO, FOL.BDCODPRES, FOL.BDREFPAGRESCISAO '||
                      'from VRH_EMP_TRESCISAO_REINTEGRACAO FOL '||WWHERERESCREINT||' '||
                   ') R group by R.BDCODEMP, R.BDCODCOL) RESC  ';

    wsql = wsql||'join VRHF_EMP_TFOLHANORMAL FOLN on (FOLN.BDCODEMP = RESC.BDCODEMP and FOLN.BDCODCOL = RESC.BDCODCOL and FOLN.BDREFFN = RESC.BDREFRESCISAO) ';
    WSQL = WSQL || 'join VRHF_EMP_TVERBAFN FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDREFFN = FOLN.BDREFFN) ';
    WSQL = WSQL || 'join vrh_base_tprepresc PRESC on (PRESC.bdcodpres = RESC.BDCODPRES) ';
    WSQL = WSQL || 'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOLN.BDREFFN ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';


    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where (COALESCE(COL.BDCONTRCOL,0) <> 1) and FOLN.BDREFIRRFESOCIAL between ' || WREFINI || ' and ' || PRREFFIM || ' ';
    else
    begin
      WSQL = WSQL || 'where (COALESCE(COL.BDCONTRCOL,0) <> 1) and ((FOLN.BDREFFN between ' || WREFINI || ' and ' || PRREFFIM || ') or (FOLN.BDREFFN <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO between ' || WREFINI || ' and ' || PRREFFIM || ')) ';
    end

    WSQL = WSQL || 'and (COALESCE(PRESC.BDTIPOMOV, 0) = 0)';

    WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN ';
  end
  else
  begin
    if (PRIRRFESOCIAL = true) then
      WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDCODVER,FO.BDVALVFN,FOLN.BDDEPFN,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGRESCISAO,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN,COALESCE(PRESC.BDTIPOMOV,0),FOLN.BDDATAPGTOFN, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
    else
      WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDCODVER,FO.BDVALVFN,FOLN.BDDEPFN,RESC.BDDATAPAGRESCISAO,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN,COALESCE(PRESC.BDTIPOMOV,0),FOLN.BDDATAPGTOFN, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';

    wsql = wsql||'from ('||
                   'select R.BDCODEMP, R.BDCODCOL, max(R.BDDATAPAGRESCISAO) as BDDATAPAGRESCISAO, max(R.BDREFRESCISAO) as BDREFRESCISAO, max(R.BDCODPRES) as BDCODPRES, max(R.BDREFPAGRESCISAO) as BDREFPAGRESCISAO from ( ' ||
                      'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDDATAPAGRESCISAO, FOL.BDREFRESCISAO, FOL.BDCODPRES, FOL.BDREFPAGRESCISAO '||
                      'from vrh_emp_trescisao FOL '||WWHERERESCREINT||' '||
                      'union all '||
                      'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDDATAPAGRESCISAO, FOL.BDREFRESCISAO, FOL.BDCODPRES, FOL.BDREFPAGRESCISAO '||
                      'from VRH_EMP_TRESCISAO_REINTEGRACAO FOL '||WWHERERESCREINT||' '||
                   ') R group by R.BDCODEMP, R.BDCODCOL) RESC  ';


    wsql = wsql||'join VRHF_EMP_TFOLHANORMAL FOLN on (FOLN.BDCODEMP = RESC.BDCODEMP and FOLN.BDCODCOL = RESC.BDCODCOL and FOLN.BDREFFN = RESC.BDREFRESCISAO) ';
    WSQL = WSQL || 'join VRHF_EMP_TVERBAFN FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDREFFN = FOLN.BDREFFN) ';
    WSQL = WSQL || 'join vrh_base_tprepresc PRESC on (PRESC.bdcodpres = RESC.BDCODPRES) ';
    WSQL = WSQL || 'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FO.BDCODEMP and COL.BDCODCOL = FO.BDCODCOL) ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOLN.BDREFFN ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where (COALESCE(COL.BDCONTRCOL,0) <> 1) and FOLN.BDREFIRRFESOCIAL between ' || WREFINI || ' and ' || PRREFFIM || ' ';
    else
    begin
      WSQL = WSQL || 'where (COALESCE(COL.BDCONTRCOL,0) <> 1) and ((FOLN.BDREFFN between ' || WREFINI || ' and ' || PRREFFIM || ') or (FOLN.BDREFFN <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO between ' || WREFINI || ' and ' || PRREFFIM || ')) ';
    end

    WSQL = WSQL || 'and (COALESCE(PRESC.BDTIPOMOV, 0) = 0)';

    WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN ';
  end

  WEMPATU = 0;
  WCOLATU = 0;
  WREFATU = 0;
  WBASEIR13 = 0;
  WINSS13 = 0;
  WIR13 = 0;
  WDEPATU = 0;
  WDATAATU = null;
  WPREPRI = 0;
  WDATAPROCA = null;
  WHORAPROCA = null;
  WTIPODEDUCAO = 0;
  WVALORDESCSIMPL = 0;
  WVALORDIFDESCSIMPL = 0;
  WTIPODEDUCAOATU = 0;
  WVALORDESCSIMPLATU = 0;
  WVALORDIFDESCSIMPLATU = 0;
  WBOLSAMEDICO = 0;
  WINCIDESOCIAL = 0;
  WCODINCIDIRRF = 0;
  WREFIRRFESOCIALATU = -1;
  WTEMVERBA13 = false;
  for execute statement WSQL
          into :WREFIRRFESOCIAL, :WCODEMP, :WCODCOL, :WREF, :WCODVER, :WVALOR, :WDEP, :WDATARESC,
          :WDATAPROC, :WHORAPROC, :WTIPOMOV, :WDATAPGTO, :WTIPODEDUCAO, :WVALORDESCSIMPL, :WVALORDIFDESCSIMPL,
          :WCODCLA, :WTRIBUTACAOEXTERIOR
  do
  begin
    BDCODTIPO = 272; -- Cálculos gerados pelo Único Folha

    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end

    if (WEMPATU = 0) then
      WEMPATU = WCODEMP;
    if (WCOLATU = 0) then
      WCOLATU = WCODCOL;
    if (WREFATU = 0) then
      WREFATU = WREF;
    if (WREFIRRFESOCIALATU = -1) then
      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;
    if (WVALORDESCSIMPLATU = 0) then
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
    if (WVALORDIFDESCSIMPLATU = 0) then
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
    if (WTIPODEDUCAOATU = 0) then
      WTIPODEDUCAOATU = WTIPODEDUCAO;

    if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WREF <> WREFATU)) then
    begin
      WREFPAGTO = cast((substring(cast(WDATAATU as varchar(10)) from 1 for 4) || substring(cast(WDATAATU as varchar(10)) from 6 for 2)) as integer);

      if (WREFPAGTO >= PRREFINI and
          WREFPAGTO <= PRREFFIM) then
      begin
        WPREVPRIVCAD = 0;
        select sum(COALESCE(LANPREV.BDVAL13SAL,0)) from VRH_EMP_TLANCPREVCOMP LANPREV join VRH_BASE_TCADPREVCOMP CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV and CADPREV.BDNATPREV <> 2)  -- 184717 Leonardo Schwab 16/11/2023
        where LANPREV.BDCODEMP = :WEMPATU and LANPREV.BDCODCOL = :WCOLATU and LANPREV.BDREFINI <= :WREFATU and ((COALESCE(LANPREV.BDREFFIN, 0) = 0) or (COALESCE(LANPREV.BDREFFIN, 0) >= :WREFATU)) and COALESCE(LANPREV.BDVAL13SAL,0) > 0
        into :WPREVPRIVCAD;
        WPREVPRIVCAD = coalesce(WPREVPRIVCAD, 0);

        if ((WBASEIR13 <> 0) or (WINSS13 <> 0) or (WIR13 <> 0) or (WPREVPRIVCAD <> 0) or (WTEMVERBA13)) then
        begin
          WEXISTE13MES = null;
          select first 1 dt.bdcodemp from vrhf_emp_t13sal dt where dt.bdcodemp = :WEMPATU and dt.bdcodcol = :WCOLATU and dt.bdref13 = :WREFPAGTO
          into :WEXISTE13MES;
          if (WEXISTE13MES is not null) then
            WDEPATU = 0;

          BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
          BDCODEMP = WEMPATU;
          BDCODCOL = WCOLATU;
          BDREF = WREFATU;
          BDREFPAG = WREFPAGTO;
          BDRENDTRIBUTAVEL = WBASEIR13;
          BDINSS = WINSS13;
          BDIR = WIR13;

          if ((WBASEIR13 <= 0 and
              WINSS13 <= 0) or (PRVEIODOTOTALIZADOR = 0)) then
            WDEPATU = 0;

          BDDEP = WDEPATU;
          BDLUCROPJ = 0;
          BDDESPMED = 0;
          BDAJCUSTOS = 0;
          BDPENJUD = 0;
          BDPENALIM = 0;

          if (WPREPRI <> 0) then
            BDPREVPRIV = WPREPRI;
          else
            BDPREVPRIV = WPREVPRIVCAD;

          BDVALABO = 0;
          BDRENDISENTOS = 0;
          BDDRENDISENTOS = '';
          BDDATAPGTO = WDATAATU;
          BDTIPO = 101;
          BDINFADIC = '';
          BDDATAPROC = WDATAPROCA;
          BDHORAPROC = WHORAPROCA;
          BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPL;
          BDAUXILIOMORADIA = 0;
          BDDIARIA = 0;
          BDBOLSAMEDICO = WBOLSAMEDICO;
          BDJUROSMORA = 0;
          BDINCIDESOCIAL = WINCIDESOCIAL;
          if (PRATUALIZAINFODESCSIMPLE = true) then
          begin
            WREFPGTOAUX = cast((substring(WREFPAGTO from 1 for 4) || '13') as integer);
            WSQLAUXSIMPLI = 'update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPGTOAUX || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';
            execute statement WSQLAUXSIMPLI;
          end
          suspend;
        end
      end

      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;
      WEMPATU = WCODEMP;
      WCOLATU = WCODCOL;
      WREFATU = WREF;
      WBASEIR13 = 0;
      WINSS13 = 0;
      WIR13 = 0;
      WDEPATU = 0;
      WDATAATU = null;
      WPREPRI = 0;
      WTIPODEDUCAOATU = WTIPODEDUCAO;
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
      WBOLSAMEDICO = 0;
      WINCIDESOCIAL = 0;
      WTEMVERBA13 = false;
    end

    WCODINCIDIRRF = 0;
    select first 1 V.BDCLAVER, VR.BDTIPOCODVER, VR.BDIRVER, VR.BDCODINCIDIRRF
    from VRH_BASE_TVERBAS_REF VR
    join VRH_BASE_TVERBAS V on (V.BDCODVER = VR.BDCODVER)
    where VR.BDCODVER = :WCODVER and
          VR.BDREFVER <= :WREFATU
    order by VR.BDCODVER desc, VR.BDREFVER desc
    into :WCLASSIF, :WTIPOCODVER, :WIRVER, :WCODINCIDIRRF;

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end
   

    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
      begin
        WIRVER = 0;
      end
    else
    --    if (wtipocodver <= 1) then
    begin
      if (WIRVER = 3) then
      begin
        if (WTIPOCODVER = 0) then
          WBASEIR13 = WBASEIR13 + WVALOR;
        else
        if (WTIPOCODVER = 1) then
        begin
          if (substring(WCLASSIF from 1 for 7) <> '9.010.0' and
              substring(WCLASSIF from 1 for 5) <> '0.030') then
            WBASEIR13 = WBASEIR13 - WVALOR;
        end

        WTEMVERBA13 = true;
      end


      if (substring(WCLASSIF from 1 for 9) = '9.010.1.7') then
         WIR13 = WIR13 + WVALOR;

    end

      if (substring(WCLASSIF from 1 for 9) = '9.010.0.7') then
        WINSS13 = WINSS13 + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.601.8.2') then
        WPREPRI = WPREPRI + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '7.720.0.0') then
        WBOLSAMEDICO = WBOLSAMEDICO + WVALOR;

      if (coalesce(WCODINCIDIRRF, 0) in (11, 12, 13, 14, 41, 42, 43, 51, 52, 53, 54)) then
        WINCIDESOCIAL = 1;

    WDEPATU = WDEP;
    if (WTIPOMOV < 1) then
      WDATAATU = WDATARESC;
    else
      WDATAATU = WDATAPGTO;

    WDATAPROCA = WDATAPROC;
    WHORAPROCA = WHORAPROC;

  end

  if (WEMPATU <> 0 and
      WCOLATU <> 0 and
      WREFATU <> 0) then
  begin
    WREFPAGTO = cast((substring(cast(WDATAATU as varchar(10)) from 1 for 4) || substring(cast(WDATAATU as varchar(10)) from 6 for 2)) as integer);
    if (WREFPAGTO >= PRREFINI and
        WREFPAGTO <= PRREFFIM) then
    begin
      WPREVPRIVCAD = 0;
      select sum(COALESCE(LANPREV.BDVAL13SAL,0)) from VRH_EMP_TLANCPREVCOMP LANPREV join VRH_BASE_TCADPREVCOMP CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV and CADPREV.BDNATPREV <> 2)  -- 184717 Leonardo Schwab 16/11/2023
      where LANPREV.BDCODEMP = :WEMPATU and LANPREV.BDCODCOL = :WCOLATU and LANPREV.BDREFINI <= :WREFATU and ((COALESCE(LANPREV.BDREFFIN, 0) = 0) or (COALESCE(LANPREV.BDREFFIN, 0) >= :WREFATU)) and COALESCE(LANPREV.BDVAL13SAL,0) > 0
      into :WPREVPRIVCAD;
      WPREVPRIVCAD = coalesce(WPREVPRIVCAD, 0);
      if ((WBASEIR13 <> 0) or (WINSS13 <> 0) or (WIR13 <> 0) or (WPREVPRIVCAD <> 0) or (WTEMVERBA13)) then
      begin
        WEXISTE13MES = null;
        select first 1 dt.bdcodemp from vrhf_emp_t13sal dt where dt.bdcodemp = :WEMPATU and dt.bdcodcol = :WCOLATU and dt.bdref13 = :WREFPAGTO
        into :WEXISTE13MES;
        if (WEXISTE13MES is not null) then
          WDEPATU = 0;

        BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
        BDCODEMP = WEMPATU;
        BDCODCOL = WCOLATU;
        BDREF = WREFATU;
        BDREFPAG = WREFPAGTO;
        BDRENDTRIBUTAVEL = WBASEIR13;
        BDINSS = WINSS13;
        BDIR = WIR13;
        BDDEP = WDEPATU;
        BDLUCROPJ = 0;
        BDDESPMED = 0;
        BDAJCUSTOS = 0;
        BDPENJUD = 0;
        BDPENALIM = 0;

        if (WPREPRI <> 0) then
          BDPREVPRIV = WPREPRI;
        else
          BDPREVPRIV = WPREVPRIVCAD;

        BDVALABO = 0;
        BDRENDISENTOS = 0;
        BDDRENDISENTOS = '';
        BDDATAPGTO = WDATAATU;
        BDTIPO = 101;
        BDINFADIC = '';
        BDDATAPROC = WDATAPROCA;
        BDHORAPROC = WHORAPROCA;
        BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
        BDAUXILIOMORADIA = 0;
        BDDIARIA = 0;
        BDBOLSAMEDICO = WBOLSAMEDICO;
        BDJUROSMORA = 0;
        BDINCIDESOCIAL = WINCIDESOCIAL;
        if (PRATUALIZAINFODESCSIMPLE = true) then
        begin
          WREFPGTOAUX = cast((substring(WREFPAGTO from 1 for 4) || '13') as integer);
          WSQLAUXSIMPLI = 'update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPGTOAUX || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';
          execute statement WSQLAUXSIMPLI;
        end
        suspend;
      end
    end
  end

  /*  13º RESCISAO FOLHA TOMADOR  */
  if (PRPUXARFILIAIS = 0) then
  begin
    if (PRIRRFESOCIAL = true) then
       WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDCODVER,FOL.BDVALVFT,FOLN.BDDEPFT,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGRESCISAO,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT,COALESCE(PRESC.BDTIPOMOV,0),FOLN.BDDATAPGTOFT, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
    else
       WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDCODVER,FOL.BDVALVFT,FOLN.BDDEPFT,RESC.BDDATAPAGRESCISAO,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT,COALESCE(PRESC.BDTIPOMOV,0),FOLN.BDDATAPGTOFT, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

    wsql = wsql||'from ('||
                    'select R.BDCODEMP, R.BDCODCOL, max(R.BDDATAPAGRESCISAO) as BDDATAPAGRESCISAO, max(R.BDREFRESCISAO) as BDREFRESCISAO, max(R.BDCODPRES) as BDCODPRES, max(R.BDREFPAGRESCISAO) as BDREFPAGRESCISAO from ( ' ||
                      'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDDATAPAGRESCISAO, FOL.BDREFRESCISAO, FOL.BDCODPRES, FOL.BDREFPAGRESCISAO '||
                      'from vrh_emp_trescisao FOL '||WWHERERESCREINT||' '||
                      'union all '||
                      'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDDATAPAGRESCISAO, FOL.BDREFRESCISAO, FOL.BDCODPRES, FOL.BDREFPAGRESCISAO '||
                      'from VRH_EMP_TRESCISAO_REINTEGRACAO FOL '||WWHERERESCREINT||' '||
                    ') R group by R.BDCODEMP, R.BDCODCOL) RESC ';

    wsql = wsql||'join VRHF_EMP_TFOLHATOMADOR FOLN on (FOLN.BDCODEMP = RESC.BDCODEMP and FOLN.BDCODCOL = RESC.BDCODCOL and FOLN.BDREFTOMADOR = RESC.BDREFRESCISAO) ';
    WSQL = WSQL || 'join VRHF_EMP_TVERBATOMADOR FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDREFTOMADOR = FOLN.BDREFTOMADOR and FOL.BDORDEM = FOLN.BDORDEM) ';
    WSQL = WSQL || 'join vrh_base_tprepresc PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES) ';
    WSQL = WSQL || 'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';

    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOLN.BDREFTOMADOR ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where (COALESCE(COL.BDCONTRCOL,0) <> 1) and FOLN.BDREFIRRFESOCIAL between ' || WREFINI || ' and ' || PRREFFIM || ' ';
    else
    begin
      WSQL = WSQL || 'where (COALESCE(COL.BDCONTRCOL,0) <> 1) and ((FOLN.BDREFTOMADOR between ' || WREFINI || ' and ' || PRREFFIM || ') or ';
      WSQL = WSQL || '      (FOLN.BDREFTOMADOR <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= ' || WREFINI || ' and RESC.BDREFPAGRESCISAO <= ' || PRREFFIM || ')) ';
    end

    WSQL = WSQL || 'and (COALESCE(PRESC.BDTIPOMOV, 0) = 0)';

    WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM ';
  end
  else
  begin
    if (PRIRRFESOCIAL = true) then
      WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDCODVER,FO.BDVALVFT,FOLN.BDDEPFT,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGRESCISAO,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT,COALESCE(PRESC.BDTIPOMOV,0),FOLN.BDDATAPGTOFT, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
    else
      WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDCODVER,FO.BDVALVFT,FOLN.BDDEPFT,RESC.BDDATAPAGRESCISAO,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT,COALESCE(PRESC.BDTIPOMOV,0),FOLN.BDDATAPGTOFT, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';

    wsql = wsql||'from ('||
                    'select R.BDCODEMP, R.BDCODCOL, max(R.BDDATAPAGRESCISAO) as BDDATAPAGRESCISAO, max(R.BDREFRESCISAO) as BDREFRESCISAO, max(R.BDCODPRES) as BDCODPRES, max(R.BDREFPAGRESCISAO) as BDREFPAGRESCISAO from ( ' ||
                      'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDDATAPAGRESCISAO, FOL.BDREFRESCISAO, FOL.BDCODPRES, FOL.BDREFPAGRESCISAO '||
                      'from vrh_emp_trescisao FOL '||WWHERERESCREINT||' '||
                      'union all '||
                      'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDDATAPAGRESCISAO, FOL.BDREFRESCISAO, FOL.BDCODPRES, FOL.BDREFPAGRESCISAO '||
                      'from VRH_EMP_TRESCISAO_REINTEGRACAO FOL '||WWHERERESCREINT||' '||
                    ') R group by R.BDCODEMP, R.BDCODCOL) RESC ';

    wsql = wsql||'join VRHF_EMP_TFOLHATOMADOR FOLN on (FOLN.BDCODEMP = RESC.BDCODEMP and FOLN.BDCODCOL = RESC.BDCODCOL and FOLN.BDREFTOMADOR = RESC.BDREFRESCISAO) ';
    WSQL = WSQL || 'join VRHF_EMP_TVERBATOMADOR FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDREFTOMADOR = FOLN.BDREFTOMADOR and FO.BDORDEM = FOLN.BDORDEM) ';
    WSQL = WSQL || 'join vrh_base_tprepresc PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES) ';
    WSQL = WSQL || 'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FO.BDCODEMP and COL.BDCODCOL = FO.BDCODCOL) ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOLN.BDREFTOMADOR ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where (COALESCE(COL.BDCONTRCOL,0) <> 1) and FOLN.BDREFIRRFESOCIAL between ' || WREFINI || ' and ' || PRREFFIM || ' ';
    else
    begin
      WSQL = WSQL || 'where (COALESCE(COL.BDCONTRCOL,0) <> 1) and ((FOLN.BDREFTOMADOR >= ' || WREFINI || ' and FOLN.BDREFTOMADOR <= ' || PRREFFIM || ') or ';
      WSQL = WSQL || '      (FOLN.BDREFTOMADOR <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= ' || WREFINI || ' and RESC.BDREFPAGRESCISAO <= ' || PRREFFIM || ')) ';
    end

    WSQL = WSQL || 'and (COALESCE(PRESC.BDTIPOMOV, 0) = 0)';

    WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM ';
  end

  WEMPATU = 0;
  WCOLATU = 0;
  WREFATU = 0;
  WORDEMATU = 0;
  WBASEIR13 = 0;
  WINSS13 = 0;
  WIR13 = 0;
  WDEPATU = 0;
  WDATAATU = null;
  WPREPRI = 0;
  WDATAPROCA = null;
  WHORAPROCA = null;
  WTIPODEDUCAO = 0;
  WVALORDESCSIMPL = 0;
  WVALORDIFDESCSIMPL = 0;
  WTIPODEDUCAOATU = 0;
  WVALORDESCSIMPLATU = 0;
  WVALORDIFDESCSIMPLATU = 0;
  WBOLSAMEDICO = 0;
  WINCIDESOCIAL = 0;
  WCODINCIDIRRF = 0;
  WREFIRRFESOCIALATU = -1;
  WTEMVERBA13 = false;
  for execute statement WSQL
          into :WREFIRRFESOCIAL, :WCODEMP, :WCODCOL, :WREF, :WORDEM, :WCODVER, :WVALOR, :WDEP,
          :WDATARESC, :WDATAPROC, :WHORAPROC, :WTIPOMOV, :WDATAPGTO, :WTIPODEDUCAO, :WVALORDESCSIMPL,
          :WVALORDIFDESCSIMPL, :WCODCLA, :WTRIBUTACAOEXTERIOR
  do
  begin
    BDCODTIPO = 272;   -- Cálculos gerados no Único Folha
    if (WEMPATU = 0) then
      WEMPATU = WCODEMP;
    if (WCOLATU = 0) then
      WCOLATU = WCODCOL;
    if (WREFATU = 0) then
      WREFATU = WREF;
    if (WREFIRRFESOCIALATU = -1) then
      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;

    if (PRPORCC = 0) then
      WORDEMATU = coalesce(WORDEM, 0);
    else
    if (WORDEMATU = 0) then
      WORDEMATU = WORDEM;

    if (WVALORDESCSIMPLATU = 0) then
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
    if (WVALORDIFDESCSIMPLATU = 0) then
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
    if (WTIPODEDUCAOATU = 0) then
      WTIPODEDUCAOATU = WTIPODEDUCAO;

    if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WREF <> WREFATU) or (WORDEM <> WORDEMATU)) then
    begin
      WREFPAGTO = cast((substring(cast(WDATAATU as varchar(10)) from 1 for 4) || substring(cast(WDATAATU as varchar(10)) from 6 for 2)) as integer);
      if (WREFPAGTO >= PRREFINI and
          WREFPAGTO <= PRREFFIM) then
      begin
        WPREVPRIVCAD = 0;
        select sum(COALESCE(LANPREV.BDVAL13SAL,0)) from VRH_EMP_TLANCPREVCOMP LANPREV join VRH_BASE_TCADPREVCOMP CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV and CADPREV.BDNATPREV <> 2) -- 184717 Leonardo Schwab 16/11/2023
        where LANPREV.BDCODEMP = :WEMPATU and LANPREV.BDCODCOL = :WCOLATU and LANPREV.BDREFINI <= :WREFATU and ((COALESCE(LANPREV.BDREFFIN, 0) = 0) or (COALESCE(LANPREV.BDREFFIN, 0) >= :WREFATU)) and COALESCE(LANPREV.BDVAL13SAL,0) > 0
        into :WPREVPRIVCAD;
        WPREVPRIVCAD = coalesce(WPREVPRIVCAD, 0);

        if ((WBASEIR13 <> 0) or (WINSS13 <> 0) or (WIR13 <> 0) or (WPREVPRIVCAD <> 0) or (WTEMVERBA13)) then
        begin
          WEXISTE13MES = null;
          select first 1 dt.bdcodemp from vrhf_emp_t13sal dt where dt.bdcodemp = :WEMPATU and dt.bdcodcol = :WCOLATU and dt.bdref13 = :WREFPAGTO
          into :WEXISTE13MES;
          if (WEXISTE13MES is not null) then
            WDEPATU = 0;

          BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
          BDCODEMP = WEMPATU;
          BDCODCOL = WCOLATU;
          BDREF = WREFATU;
          BDREFPAG = WREFPAGTO;
          BDORDEM = WORDEMATU;
          BDRENDTRIBUTAVEL = WBASEIR13;
          BDINSS = WINSS13;
          BDIR = WIR13;
          BDDEP = WDEPATU;
          BDLUCROPJ = 0;
          BDDESPMED = 0;
          BDAJCUSTOS = 0;
          BDPENJUD = 0;
          BDPENALIM = 0;

          if (WPREPRI <> 0) then
            BDPREVPRIV = WPREPRI;
          else
            BDPREVPRIV = WPREVPRIVCAD;

          BDVALABO = 0;
          BDRENDISENTOS = 0;
          BDDRENDISENTOS = '';
          BDDATAPGTO = WDATAATU;
          BDTIPO = 101;
          BDINFADIC = '';
          BDDATAPROC = WDATAPROCA;
          BDHORAPROC = WHORAPROCA;
          BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPL;
          BDAUXILIOMORADIA = 0;
          BDDIARIA = 0;
          BDBOLSAMEDICO = WBOLSAMEDICO;
          BDJUROSMORA = 0;
          BDINCIDESOCIAL = WINCIDESOCIAL;
          if (PRATUALIZAINFODESCSIMPLE = true) then
          begin
            WREFPGTOAUX = cast((substring(WREFPAGTO from 1 for 4) || '13') as integer);
            WSQLAUXSIMPLI = 'update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPGTOAUX || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';
            execute statement WSQLAUXSIMPLI;
          end
          suspend;
        end
      end
      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;
      WEMPATU = WCODEMP;
      WCOLATU = WCODCOL;
      WREFATU = WREF;
      WORDEMATU = WORDEM;
      WBASEIR13 = 0;
      WINSS13 = 0;
      WIR13 = 0;
      WDEPATU = 0;
      WDATAATU = null;
      WPREPRI = 0;
      WTIPODEDUCAOATU = WTIPODEDUCAO;
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
      WBOLSAMEDICO = 0;
      WINCIDESOCIAL = 0;
      WTEMVERBA13 = false;
    end
    select first 1 V.BDCLAVER, VR.BDTIPOCODVER, VR.BDIRVER, VR.BDCODINCIDIRRF
    from VRH_BASE_TVERBAS_REF VR
    join VRH_BASE_TVERBAS V on (V.BDCODVER = VR.BDCODVER)
    where VR.BDCODVER = :WCODVER and
          VR.BDREFVER <= :WREFATU
    order by VR.BDCODVER desc, VR.BDREFVER desc
    into :WCLASSIF, :WTIPOCODVER, :WIRVER, :WCODINCIDIRRF;

    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
      begin
        WIRVER = 0;
      end
    else
    --    if (wtipocodver <= 1) then
    begin
      if (WIRVER = 3) then
      begin
        if (WTIPOCODVER = 0) then
          WBASEIR13 = WBASEIR13 + WVALOR;
        else
        if (WTIPOCODVER = 1) then
        begin
          if (substring(WCLASSIF from 1 for 7) <> '9.010.0' and
              substring(WCLASSIF from 1 for 5) <> '0.030') then
            WBASEIR13 = WBASEIR13 - WVALOR;
        end

        WTEMVERBA13 = true;
      end

      if (substring(WCLASSIF from 1 for 9) = '9.010.1.7') then
        WIR13 = WIR13 + WVALOR;
   end

      if (substring(WCLASSIF from 1 for 9) = '9.010.0.7') then
        WINSS13 = WINSS13 + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '7.720.0.0') then
        WBOLSAMEDICO = WBOLSAMEDICO + WVALOR;

      if (coalesce(WCODINCIDIRRF, 0) in (11, 12, 13, 14, 41, 42, 43, 51, 52, 53, 54)) then
        WINCIDESOCIAL = 1;


    WDEPATU = WDEP;
    if (WTIPOMOV < 1) then
      WDATAATU = WDATARESC;
    else
      WDATAATU = WDATAPGTO;

    WDATAPROCA = WDATAPROC;
    WHORAPROCA = WHORAPROC;
  end
  if (WEMPATU <> 0 and
      WCOLATU <> 0 and
      WREFATU <> 0 and
      WORDEMATU <> 0) then
  begin
    WREFPAGTO = cast((substring(cast(WDATAATU as varchar(10)) from 1 for 4) || substring(cast(WDATAATU as varchar(10)) from 6 for 2)) as integer);
    if (WREFPAGTO >= PRREFINI and
        WREFPAGTO <= PRREFFIM) then
    begin
      WPREVPRIVCAD = 0;
      select sum(COALESCE(LANPREV.BDVAL13SAL,0)) from VRH_EMP_TLANCPREVCOMP LANPREV join VRH_BASE_TCADPREVCOMP CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV and CADPREV.BDNATPREV <> 2)   -- 184717 Leonardo Schwab 16/11/2023
      where LANPREV.BDCODEMP = :WEMPATU and LANPREV.BDCODCOL = :WCOLATU and LANPREV.BDREFINI <= :WREFATU and ((COALESCE(LANPREV.BDREFFIN, 0) = 0) or (COALESCE(LANPREV.BDREFFIN, 0) >= :WREFATU)) and COALESCE(LANPREV.BDVAL13SAL,0) > 0
      into :WPREVPRIVCAD;
      WPREVPRIVCAD = coalesce(WPREVPRIVCAD, 0);
      if ((WBASEIR13 <> 0) or (WINSS13 <> 0) or (WIR13 <> 0) or (WPREVPRIVCAD <> 0) or (WTEMVERBA13)) then
      begin
        WEXISTE13MES = null;
        select first 1 dt.bdcodemp from vrhf_emp_t13sal dt where dt.bdcodemp = :WEMPATU and dt.bdcodcol = :WCOLATU and dt.bdref13 = :WREFPAGTO
        into :WEXISTE13MES;
        if (WEXISTE13MES is not null) then
          WDEPATU = 0;

        BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
        BDCODEMP = WEMPATU;
        BDCODCOL = WCOLATU;
        BDREF = WREFATU;
        BDORDEM = WORDEMATU;
        BDREFPAG = WREFPAGTO;
        BDRENDTRIBUTAVEL = WBASEIR13;
        BDINSS = WINSS13;
        BDIR = WIR13;
        BDDEP = WDEPATU;
        BDLUCROPJ = 0;
        BDDESPMED = 0;
        BDAJCUSTOS = 0;
        BDPENJUD = 0;
        BDPENALIM = 0;

        if (WPREPRI <> 0) then
          BDPREVPRIV = WPREPRI;
        else
          BDPREVPRIV = WPREVPRIVCAD;

        BDVALABO = 0;
        BDRENDISENTOS = 0;
        BDDRENDISENTOS = '';
        BDDATAPGTO = WDATAATU;
        BDTIPO = 101;
        BDINFADIC = '';
        BDDATAPROC = WDATAPROCA;
        BDDATAPROC = WDATAPROCA;
        BDHORAPROC = WHORAPROCA;
        BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPL;
        BDAUXILIOMORADIA = 0;
        BDDIARIA = 0;
        BDBOLSAMEDICO = WBOLSAMEDICO;
        BDJUROSMORA = 0;
        BDINCIDESOCIAL = WINCIDESOCIAL;
        if (PRATUALIZAINFODESCSIMPLE = true) then
        begin
          WREFPGTOAUX = cast((substring(WREFPAGTO from 1 for 4) || '13') as integer);
          WSQLAUXSIMPLI = 'update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPGTOAUX || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';
          execute statement WSQLAUXSIMPLI;
        end
        suspend;
      end
    end
  end
end^

/* Restore proc. body: SP_VRHF_DADOS_IR_13FC */
create or alter procedure SP_VRHF_DADOS_IR_13FC (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRIRRFESOCIAL boolean = false,
    PRVERCALCRRA integer = -1,
    PRPORCC smallint = 1)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFFC integer,
    BDCODACCONV integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR13 numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WINSS13 numeric(18,6);
declare variable WIR13 numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WREFAUX integer;
declare variable WREFAUXATU integer;
declare variable WDATAPGTO date;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WDEP numeric(18,6);
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WCODACCONV integer;
declare variable WCODACCONVATU integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
declare variable WDEPATU numeric(18,6);
declare variable WWHERERESCREINT varchar(32700);
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WGRAVARUBRICA integer;
BEGIN
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  IF (UPPER(prcodcol) = 'TEMP_FILTRO_COLCON_REL') THEN
     WUSARTMP_COL_SELECT = 1;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  WWHERERESCREINT = 'inner join TEMPRESAS REMP on (REMP.BDCODEMP = FOL.BDCODEMP) ';
  if (WUSARTMP_EMP_SELECT = 1) then
     begin
       WWHERERESCREINT = WWHERERESCREINT||' inner JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';
       if (WUSARTMP_COL_SELECT = 1) then
          WWHERERESCREINT = WWHERERESCREINT||' inner join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';
     end
  else
  begin
    if (WUSARTMP_COL_SELECT = 1) then
       WWHERERESCREINT = WWHERERESCREINT||' inner join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

    if (wusartmp_col_select = 0 and wusartmp_emp_select = 0) then
       begin
         if (prpuxarfiliais = 0) then
            begin
              if (PRCODEMP is not null and PRCODEMP <> '') then
                 WWHERERESCREINT = WWHERERESCREINT||' where (' || PRCODEMP || ') ';

              if (PRCODCOL is not null and PRCODCOL <> '') then
                 WWHERERESCREINT = WWHERERESCREINT||' and (' || PRCODCOL || ') ';
            end
         else
            begin
              if (PRCODEMP is not null and PRCODEMP <> '') then
                 WWHERERESCREINT = WWHERERESCREINT||' where ((' || REPLACE(UPPER(PRCODEMP), 'FOL.', 'REMP.') || ')';
              if (PRCODMATRIZ is not null and PRCODMATRIZ <> '') then
                 WWHERERESCREINT = WWHERERESCREINT || ' or (' || REPLACE(UPPER(PRCODMATRIZ), 'FOL.', 'REMP.') || ')) ';

              if (PRCODCOL is not null and PRCODCOL <> '') then
                WWHERERESCREINT = WWHERERESCREINT || ' and (' || PRCODCOL|| ') ';
            end
       end
  end

  /*  13º RESCISAO FOLHA COMPLEMENTAR NORMAL  */

  BDINDRESC = 0;
  BDORDEM = null;

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDREFFC,FOL.BDCODVER,FOL.BDVALVFC,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGFC, FOLN.BDDEPFC, VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC,FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
       ELSE
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDREFFC,FOL.BDCODVER,FOL.BDVALVFC,FOLN.BDDATAPAGFC, FOLN.BDDEPFC, VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC,FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

       wsql = wsql||'from ('||
                      'select R.BDCODEMP, R.BDCODCOL, max(R.BDDATAPAGRESCISAO) as BDDATAPAGRESCISAO, max(R.BDREFRESCISAO) as BDREFRESCISAO, max(R.BDCODPRES) as BDCODPRES, max(R.BDREFPAGRESCISAO) as BDREFPAGRESCISAO, max(R.BDREFPROJECAOAVISO) as BDREFPROJECAOAVISO from ( ' ||
                         'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDDATAPAGRESCISAO, FOL.BDREFRESCISAO, FOL.BDCODPRES, FOL.BDREFPAGRESCISAO, FOL.BDREFPROJECAOAVISO '||
                         'from vrh_emp_trescisao FOL '||WWHERERESCREINT||' '||
                         'union all '||
                         'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDDATAPAGRESCISAO, FOL.BDREFRESCISAO, FOL.BDCODPRES, FOL.BDREFPAGRESCISAO, FOL.BDREFPROJECAOAVISO '||
                         'from VRH_EMP_TRESCISAO_REINTEGRACAO FOL '||WWHERERESCREINT||' '||
                      ') R group by R.BDCODEMP, R.BDCODCOL) RESC  ';

       wsql = wsql||'join vrhf_emp_tfolhacomp FOLN on (FOLN.BDCODEMP = RESC.BDCODEMP and FOLN.BDCODCOL = RESC.BDCODCOL and ((FOLN.BDREFFN = RESC.BDREFRESCISAO) or (FOLN.BDREFFN = RESC.BDREFPROJECAOAVISO))) ';
       wsql = wsql||'join vrhf_emp_tverbafc FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDREFFN = FOLN.BDREFFN and FOL.BDREFFC = FOLN.BDREFFC) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrh_base_tprepresc PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES) ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  ';
       if (PRIRRFESOCIAL = TRUE) THEN
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
       ELSE
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFFC ORDER BY X.BDREFCOL DESC) ';
      
       WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

       IF (PRIRRFESOCIAL = TRUE) THEN
          wsql = wsql||'where FOLN.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim||' ';
       ELSE
          BEGIN
       wsql = wsql||'where ((FOLN.BDREFCOMP >= '||prrefini||' and FOLN.BDREFCOMP <= '||prreffim||') or ';
       wsql = wsql||'       (FOLN.BDREFCOMP <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||prrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) ';
          END

       wsql = wsql||'  and (COALESCE(PRESC.BDTIPOMOV, 0) = 0)';
     
       /*  #190667 Leonardo Schwab 28/02/2024  */
       IF (prvercalcrra >= 0) THEN
          wsql = wsql||' and COALESCE(FOLN.BDVERCALCRRA,0) = '||prvercalcrra;

       wsql = wsql||' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDREFFC ';
     END
  ELSE
     BEGIN
       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDREFFC,FO.BDCODVER,FO.BDVALVFC,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGFC, FOLN.BDDEPFC, VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC,FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
       ELSE
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDREFFC,FO.BDCODVER,FO.BDVALVFC,FOLN.BDDATAPAGFC, FOLN.BDDEPFC, VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC,FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

       wsql = wsql||'from ('||
                      'select R.BDCODEMP, R.BDCODCOL, max(R.BDDATAPAGRESCISAO) as BDDATAPAGRESCISAO, max(R.BDREFRESCISAO) as BDREFRESCISAO, max(R.BDCODPRES) as BDCODPRES, max(R.BDREFPAGRESCISAO) as BDREFPAGRESCISAO, max(R.BDREFPROJECAOAVISO) as BDREFPROJECAOAVISO from ( ' ||
                         'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDDATAPAGRESCISAO, FOL.BDREFRESCISAO, FOL.BDCODPRES, FOL.BDREFPAGRESCISAO, FOL.BDREFPROJECAOAVISO '||
                         'from vrh_emp_trescisao FOL '||WWHERERESCREINT||' '||
                         'union all '||
                         'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDDATAPAGRESCISAO, FOL.BDREFRESCISAO, FOL.BDCODPRES, FOL.BDREFPAGRESCISAO, FOL.BDREFPROJECAOAVISO '||
                         'from VRH_EMP_TRESCISAO_REINTEGRACAO FOL '||WWHERERESCREINT||' '||
                      ') R group by R.BDCODEMP, R.BDCODCOL) RESC  ';


       wsql = wsql||'join vrhf_emp_tfolhacomp FOLN on (FOLN.BDCODEMP = RESC.BDCODEMP and FOLN.BDCODCOL = RESC.BDCODCOL and ((FOLN.BDREFFN = RESC.BDREFRESCISAO) or (FOLN.BDREFFN = RESC.BDREFPROJECAOAVISO))) ';
       wsql = wsql||'join VRHF_EMP_TVERBAFC FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDREFFN = FOLN.BDREFFN and FO.BDREFFC = FOLN.BDREFFC) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrh_base_tprepresc PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES) ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  ';
       if (PRIRRFESOCIAL = TRUE) THEN
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
       ELSE
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFFC ORDER BY X.BDREFCOL DESC) ';
      
       WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

       IF (PRIRRFESOCIAL = TRUE) THEN
          wsql = wsql||'where FOLN.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim||' ';
       ELSE
          BEGIN
       wsql = wsql||'where ((FOLN.BDREFCOMP >= '||prrefini||' and FOLN.BDREFCOMP <= '||prreffim||') or ';
       wsql = wsql||'       (FOLN.BDREFCOMP <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||prrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) ';
          END

       wsql = wsql||        'and (COALESCE(PRESC.BDTIPOMOV, 0) = 0)';
     
      /*  #190667 Leonardo Schwab 28/02/2024  */
      IF (prvercalcrra >= 0) THEN
          wsql = wsql||' and COALESCE(FOLN.BDVERCALCRRA,0) = '||prvercalcrra;

       wsql = wsql||' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDREFFC ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wrefauxatu = 0;
  wbaseir13  = 0;
  winss13    = 0;
  wir13      = 0;
  wdataatu   = NULL;
  wprepri    = 0;
  wdataproca = NULL;
  whoraproca = NULL;
  wbolsamedico = 0;
  WINCIDESOCIAL = 0;
  WCODINCIDIRRF = 0;
  wcodacconvatu = -1;
  WREFIRRFESOCIALatu = -1;
  wdepatu = 0;

  FOR EXECUTE STATEMENT wsql INTO :WREFIRRFESOCIAL,:wcodemp,:wcodcol,:wref,:wrefaux,:wcodver,:wvalor,:wdatapgto,:wdep,:wclassif,:wdataproc,:whoraproc,:wcodacconv, :wcodcla, :wtributacaoexterior DO
  BEGIN
    BDCODTIPO = 272;    -- Cálculos gerados pelo Único Folha

    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end

    IF (wempatu = 0) THEN wempatu = wcodemp;
    IF (wcolatu = 0) THEN wcolatu = wcodcol;
    IF (wrefatu = 0) THEN wrefatu = wref;
    IF (wrefauxatu = 0) THEN wrefauxatu = wrefaux;
    if (WREFIRRFESOCIALatu = -1) then WREFIRRFESOCIALatu = WREFIRRFESOCIAL;
    if (wcodacconvatu = -1) then wcodacconvatu = wcodacconv;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wrefaux <> wrefauxatu)) THEN
       BEGIN
         wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);
         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              bdrefirrfesocial = WREFIRRFESOCIALatu;
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              BDREFPAG         = wrefpagto;
              BDREFFC          = wrefauxatu;
              BDRENDTRIBUTAVEL = wbaseir13;
              BDINSS           = winss13;
              BDIR             = wir13;
              BDDEP            = wdepatu;
              BDLUCROPJ        = 0;
              BDDESPMED        = 0;
              BDAJCUSTOS       = 0;
              BDPENJUD         = 0;
              BDPENALIM        = 0;
              BDPREVPRIV       = wprepri;
              BDVALABO         = 0;
              BDRENDISENTOS    = 0;
              BDDRENDISENTOS   = '';
              BDDATAPGTO       = wdataatu;
              BDTIPO           = 111;    -- 13º rescisão
              BDINFADIC        = '';
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;
              BDAUXILIOMORADIA = 0;
              BDDIARIA = 0;
              BDBOLSAMEDICO = wbolsamedico;
              BDJUROSMORA = 0;
              BDINCIDESOCIAL = WINCIDESOCIAL;
              BDCODACCONV = WCODACCONVATU;
              SUSPEND;
            END

         WREFIRRFESOCIALatu = WREFIRRFESOCIAL;
         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wrefatu    = wref;
         wrefauxatu = wrefaux;
         wbaseir13  = 0;
         winss13    = 0;
         wir13      = 0;
         wdataatu   = wdatapgto;
         wprepri    = 0;
         wbolsamedico = 0;
         WINCIDESOCIAL = 0;
         wcodacconvatu = wcodacconv;
         wdepatu = 0;
       END

    -- soma as bases
    WCODINCIDIRRF = 0;
    SELECT first 1 BDTIPOCODVER, BDIRVER, BDCODINCIDIRRF FROM VRH_BASE_TVERBAS_REF WHERE BDCODVER = :wcodver and BDREFVER <= :wrefatu order by BDCODVER desc, BDREFVER desc
    INTO :wtipocodver,:wirver,:WCODINCIDIRRF;

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end
   
    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
      begin
        wirver = 0;
      end
    else
      begin
        if (wtipocodver <= 1) then
          begin
            IF (wirver = 3) THEN -- 13º salário
               BEGIN
                 IF (wtipocodver = 0) THEN   -- provento
                    wbaseir13 = wbaseir13 + wvalor;
                 ELSE
                 IF (wtipocodver = 1) THEN   -- desconto
                    BEGIN
                      --                                      INSS                                              Obrigações IR
                      IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                         wbaseir13 = wbaseir13 - wvalor;
                    END
               END
          end

         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.7') THEN
            wir13 = wir13 + wvalor;
      end



    if (wtipocodver <= 1) then
       begin
         --                                     INSS folha normal
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.7') THEN
            winss13 = winss13 + wvalor;
         --                                     IR 13º salário rescisão
         --                                     Previdência privada
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.601.8.2') THEN
            wprepri = wprepri + wvalor;
         --
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '7.720.0.0') THEN
            WBOLSAMEDICO = WBOLSAMEDICO + WVALOR;

         if (COALESCE(WCODINCIDIRRF, 0) IN (11,12,13,14,41,42,43,51,52,53,54)) then
            WINCIDESOCIAL = 1;
       end

    wdepatu = wdep;
    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wrefauxatu <> 0) THEN
     BEGIN
       wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);
       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            bdREFIRRFESOCIAL = WREFIRRFESOCIALatu;
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDREFFC          = wrefauxatu;
            BDRENDTRIBUTAVEL = wbaseir13;
            BDINSS           = winss13;
            BDIR             = wir13;
            BDDEP            = wdepatu;
            BDLUCROPJ        = 0;
            BDDESPMED        = 0;
            BDAJCUSTOS       = 0;
            BDPENJUD         = 0;
            BDPENALIM        = 0;
            BDPREVPRIV       = wprepri;
            BDVALABO         = 0;
            BDRENDISENTOS    = 0;
            BDDRENDISENTOS   = '';
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 111;    -- 13º rescisão complementar
            BDINFADIC        = '';
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            BDAUXILIOMORADIA = 0;
            BDDIARIA = 0;
            BDBOLSAMEDICO = wbolsamedico;
            BDJUROSMORA = 0;
            BDINCIDESOCIAL = WINCIDESOCIAL;
            BDCODACCONV = WCODACCONVATU;
            SUSPEND;
          END
     END

  /*  FOLHA COMPLEMENTAR TOMADOR  */
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDREFFC,FOL.BDCODVER,FOL.BDVALVFC,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC,FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
       ELSE
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDREFFC,FOL.BDCODVER,FOL.BDVALVFC,FOLN.BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC,FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

       wsql = wsql||'from ('||
                      'select R.BDCODEMP, R.BDCODCOL, max(R.BDDATAPAGRESCISAO) as BDDATAPAGRESCISAO, max(R.BDREFRESCISAO) as BDREFRESCISAO, max(R.BDCODPRES) as BDCODPRES, max(R.BDREFPAGRESCISAO) as BDREFPAGRESCISAO, max(R.BDREFPROJECAOAVISO) as BDREFPROJECAOAVISO from ( ' ||
                         'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDDATAPAGRESCISAO, FOL.BDREFRESCISAO, FOL.BDCODPRES, FOL.BDREFPAGRESCISAO, FOL.BDREFPROJECAOAVISO '||
                         'from vrh_emp_trescisao FOL '||WWHERERESCREINT||' '||
                         'union all '||
                         'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDDATAPAGRESCISAO, FOL.BDREFRESCISAO, FOL.BDCODPRES, FOL.BDREFPAGRESCISAO, FOL.BDREFPROJECAOAVISO '||
                         'from VRH_EMP_TRESCISAO_REINTEGRACAO FOL '||WWHERERESCREINT||' '||
                      ') R group by R.BDCODEMP, R.BDCODCOL) RESC  ';

       wsql = wsql||'join vrhf_emp_tfoltomcomp FOLN on (FOLN.BDCODEMP = RESC.BDCODEMP and FOLN.BDCODCOL = RESC.BDCODCOL and ((FOLN.BDREFTOMADOR = RESC.BDREFRESCISAO) or (FOLN.BDREFTOMADOR = RESC.BDREFPROJECAOAVISO))) ';
       wsql = wsql||'join vrhf_emp_tverbafctomador FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDREFTOMADOR = FOLN.BDREFTOMADOR and FOL.BDORDEM = FOLN.BDORDEM and FOL.BDREFFC = FOLN.BDREFFC) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrh_base_tprepresc PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES) ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  ';
       if (PRIRRFESOCIAL = TRUE) THEN
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
       ELSE
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFFC ORDER BY X.BDREFCOL DESC) ';
      
       WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

       IF (PRIRRFESOCIAL = TRUE) THEN
          wsql = wsql||'where FOLN.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim||' ';
       ELSE
       wsql = wsql||'where FOLN.BDREFFC >= '||prrefini||'01 and FOLN.BDREFFC <= '||prreffim||'31 ';

       wsql = wsql||'  and (COALESCE(PRESC.BDTIPOMOV, 0) = 0)';

       /*  #190667 Leonardo Schwab 28/02/2024  */
       IF (prvercalcrra >= 0) THEN
          wsql = wsql||' and COALESCE(FOLN.BDVERCALCRRA,0) = '||prvercalcrra;

       wsql = wsql||' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDREFFC ';
     END
  ELSE
     BEGIN
       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDREFFC,FO.BDCODVER,FO.BDVALVFC,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC,FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
       ELSE
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDREFFC,FO.BDCODVER,FO.BDVALVFC,FOLN.BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC,FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

       wsql = wsql||'from ('||
                      'select R.BDCODEMP, R.BDCODCOL, max(R.BDDATAPAGRESCISAO) as BDDATAPAGRESCISAO, max(R.BDREFRESCISAO) as BDREFRESCISAO, max(R.BDCODPRES) as BDCODPRES, max(R.BDREFPAGRESCISAO) as BDREFPAGRESCISAO, max(R.BDREFPROJECAOAVISO) as BDREFPROJECAOAVISO from ( ' ||
                         'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDDATAPAGRESCISAO, FOL.BDREFRESCISAO, FOL.BDCODPRES, FOL.BDREFPAGRESCISAO, FOL.BDREFPROJECAOAVISO '||
                         'from vrh_emp_trescisao FOL '||WWHERERESCREINT||' '||
                         'union all '||
                         'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDDATAPAGRESCISAO, FOL.BDREFRESCISAO, FOL.BDCODPRES, FOL.BDREFPAGRESCISAO, FOL.BDREFPROJECAOAVISO '||
                         'from VRH_EMP_TRESCISAO_REINTEGRACAO FOL '||WWHERERESCREINT||' '||
                      ') R group by R.BDCODEMP, R.BDCODCOL) RESC  ';

       wsql = wsql||'join vrhf_emp_tfoltomcomp FOLN on (FOLN.BDCODEMP = RESC.BDCODEMP and FOLN.BDCODCOL = RESC.BDCODCOL and ((FOLN.BDREFTOMADOR = RESC.BDREFRESCISAO) or (FOLN.BDREFTOMADOR = RESC.BDREFPROJECAOAVISO))) ';
       wsql = wsql||'join vrhf_emp_tverbafctomador FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDREFTOMADOR = FOLN.BDREFTOMADOR and FO.BDORDEM = FOLN.BDORDEM and FO.BDREFFC = FOLN.BDREFFC) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrh_base_tprepresc PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES) ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  ';
       if (PRIRRFESOCIAL = TRUE) THEN
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
       ELSE
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFFC ORDER BY X.BDREFCOL DESC) ';
      
       WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

       IF (PRIRRFESOCIAL = TRUE) THEN
          wsql = wsql||'where FOLN.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim||' ';
       ELSE
       wsql = wsql||'where FOLN.BDREFFC >= '||prrefini||'01 and FOLN.BDREFFC <= '||prreffim||'31 ';

       wsql = wsql||        'and (COALESCE(PRESC.BDTIPOMOV, 0) = 0)';
     
       /*  #190667 Leonardo Schwab 28/02/2024  */
       IF (prvercalcrra >= 0) THEN
          wsql = wsql||' and COALESCE(FOLN.BDVERCALCRRA,0) = '||prvercalcrra;

       wsql = wsql||' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDREFFC ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wrefauxatu = 0;
  wordematu  = 0;
  wbaseir13  = 0;
  winss13    = 0;
  wir13      = 0;
  wdataatu   = NULL;
  wprepri    = 0;
  wdataproca = NULL;
  whoraproca = NULL;
  wbolsamedico = 0;
  WINCIDESOCIAL = 0;
  wcodacconvatu = -1;
  wrefirrfesocialatu = -1;
  wdepatu = 0;

  FOR EXECUTE STATEMENT wsql INTO :wrefirrfesocial,:wcodemp,:wcodcol,:wref,:wordem,:wrefaux,:wcodver,:wvalor,:wdatapgto,:wdep,:wclassif,:wdataproc,:whoraproc,:wcodacconv, :wcodcla, :wtributacaoexterior DO
  BEGIN
    BDCODTIPO = 272;    -- Cálculos gerados pelo Único Folha

    IF (wempatu = 0) THEN
       wempatu = wcodemp;
    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;
    IF (wrefatu = 0) THEN
       wrefatu = wref;
    IF (wrefauxatu = 0) THEN
       wrefauxatu = wrefaux;
    if (wrefirrfesocialatu = -1) then
       wrefirrfesocialatu = wrefirrfesocial;

    if (PRPORCC = 0) then
       WORDEMATU = coalesce(WORDEM, 0);
    else
    IF (wordematu = 0) THEN
       wordematu = wordem;

    if (wcodacconvatu = -1) then
       wcodacconvatu = wcodacconv;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wordem <> wordematu) OR (wrefaux <> wrefauxatu)) THEN
       BEGIN
         wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);
         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              bdrefirrfesocial = wrefirrfesocialatu;
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              BDREFPAG         = wrefpagto;
              BDREFFC          = wrefauxatu;
              BDRENDTRIBUTAVEL = wbaseir13;
              BDINSS           = winss13;
              BDIR             = wir13;
              BDDEP            = wdepatu;
              BDLUCROPJ        = 0;
              BDDESPMED        = 0;
              BDAJCUSTOS       = 0;
              BDPENJUD         = 0;
              BDPENALIM        = 0;
              BDPREVPRIV       = wprepri;
              BDVALABO         = 0;
              BDRENDISENTOS    = 0;
              BDDRENDISENTOS   = '';
              BDDATAPGTO       = wdataatu;
              BDTIPO           = 111;    -- 13º rescisão
              BDINFADIC        = '';
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;
              BDAUXILIOMORADIA = 0;
              BDDIARIA = 0;
              BDBOLSAMEDICO = wbolsamedico;
              BDJUROSMORA = 0;
              BDINCIDESOCIAL = WINCIDESOCIAL;
              BDCODACCONV = WCODACCONVATU;
              SUSPEND;
            END

         wrefirrfesocialatu = wrefirrfesocial;
         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wrefatu    = wref;
         wrefauxatu = wrefaux;
         wordematu  = wordem;
         wbaseir13  = 0;
         winss13    = 0;
         wir13      = 0;
         wdataatu   = wdatapgto;
         wprepri    = 0;
         wbolsamedico = 0;
         WINCIDESOCIAL = 0;
         WCODACCONVATU = WCODACCONV;
         wdepatu = 0;
       END

    -- soma as bases
    WCODINCIDIRRF = 0;
    SELECT first 1 BDTIPOCODVER, BDIRVER, BDCODINCIDIRRF
    FROM vrh_base_tverbas_ref WHERE BDCODVER = :wcodver and BDREFVER <= :wrefatu
    order by BDCODVER desc, BDREFVER desc
    INTO :wtipocodver,:wirver,:WCODINCIDIRRF;

    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
      begin
        wirver = 0;
      end
    else
      begin
        if (wtipocodver <= 1) then
          begin
             IF (wirver = 3) THEN -- 13º salário
                BEGIN
                  IF (wtipocodver = 0) THEN   -- provento
                     wbaseir13 = wbaseir13 + wvalor;
                  ELSE
                  IF (wtipocodver = 1) THEN   -- desconto
                     BEGIN
                       --                                      INSS                                              Obrigações IR
                       IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                          wbaseir13 = wbaseir13 - wvalor;
                     END
                END
             --                                     IR 13º salário rescisão
           end

          IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.7') THEN
             wir13 = wir13 + wvalor;
      end

     if (wtipocodver <= 1) then
       begin
         --                                     INSS 13º salário rescisão
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.7') THEN
            winss13 = winss13 + wvalor;
         --                                     Previdência privada
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.601.8.2') THEN
            wprepri = wprepri + wvalor;
         --
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '7.720.0.0') THEN
            WBOLSAMEDICO = WBOLSAMEDICO + WVALOR;
         --
         if (COALESCE(WCODINCIDIRRF, 0) IN (11,12,13,14,41,42,43,51,52,53,54)) then
            WINCIDESOCIAL = 1;
       end

    wdepatu = wdep;
    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wordematu <> 0 AND wrefauxatu <> 0) THEN
     BEGIN
       wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);
       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            bdrefirrfesocial = wrefirrfesocialatu;
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDREFFC          = wrefauxatu;
            BDRENDTRIBUTAVEL = wbaseir13;
            BDINSS           = winss13;
            BDIR             = wir13;
            BDDEP            = wdepatu;
            BDLUCROPJ        = 0;
            BDDESPMED        = 0;
            BDAJCUSTOS       = 0;
            BDPENJUD         = 0;
            BDPENALIM        = 0;
            BDPREVPRIV       = wprepri;
            BDVALABO         = 0;
            BDRENDISENTOS    = 0;
            BDDRENDISENTOS   = '';
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 111;    -- 13º rescisão complementar
            BDINFADIC        = '';
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            BDAUXILIOMORADIA = 0;
            BDDIARIA = 0;
            BDBOLSAMEDICO = wbolsamedico;
            BDJUROSMORA = 0;
            BDINCIDESOCIAL = WINCIDESOCIAL;
            BDCODACCONV = WCODACCONV;
            SUSPEND;
          END
     END
END^

/* Restore proc. body: SP_VRHF_DADOS_IR_13FC_INT */
create or alter procedure SP_VRHF_DADOS_IR_13FC_INT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRIRRFESOCIAL boolean = false,
    PRPORCC smallint = 1)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODCONTTI integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WCODCONTTI integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WCONTTIATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR13 numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WINSS13 numeric(18,6);
declare variable WIR13 numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WREFAUX integer;
declare variable WREFAUXATU integer;
declare variable WDATAPGTO date;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WGRAVARUBRICA integer;
BEGIN
  prcodemp = COALESCE(prcodemp,'');
  prcodcol = COALESCE(prcodcol,'');
  prcodmatriz = COALESCE(prcodmatriz,'');
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  WUSARTMP_COL_SELECT = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     BEGIN
       WUSARTMP_EMP_SELECT = 1;
       prcodemp    = '';
       prcodmatriz = '';
     END
  ELSE
     WUSARTMP_EMP_SELECT = 0;

  IF (UPPER(prcodcol) = 'TEMP_FILTRO_COLCON_REL') then
    WUSARTMP_COL_SELECT = 1;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  BDINDRESC = 0;
  BDORDEM   = NULL;

  /* FOLHA INTERMITENTE COMPLEMENTAR */
  wsql = 'select FO.BDREFIRRFESOCIAL,FOL.BDCODEMP, FO.BDCODCOL, FO.BDREFFN as BDREF, FO.BDCODCONTTI, NULL as BDORDEM, FO.BDREFFC,' ||
          ' FOLV.BDCODVER, FOLV.BDVALVFC, FO.BDDATAPAGFC, FO.BDDATAPROCFC, FO.BDHORAPROCFC, VINC.BDCODCLA, COALESCE(COL_HIST.BDTRIBUTACAOEXTERIOR, 0) BDTRIBUTACAOEXTERIOR';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
     wsql = wsql || ' from TMP_EMPRESAS_SELECT FOL' ||
                    ' inner join vrhf_emp_tfolhacompint FO on (FO.BDCODEMP = FOL.BDCODEMP)';
  ELSE
     wsql = wsql || ' from TEMPRESAS FOL' ||
                    ' join vrhf_emp_tfolhacompint FO on (FOL.BDCODEMP = FO.BDCODEMP)';

  wsql = wsql || ' inner join vrhf_emp_tverbafcint FOLV on (FOLV.BDCODEMP = FOL.BDCODEMP) and (FOLV.BDCODCOL = FO.BDCODCOL)' ||
                                                     ' and (FOLV.BDCODCONTTI = FO.BDCODCONTTI) and (FOLV.BDREFFN = FO.BDREFFN) and (FOLV.BDREFFC = FO.BDREFFC)';

  wsql = wsql||'left outer join VRH_EMP_TCOL_HIST COL_HIST ON (COL_HIST.BDCODEMP = FO.BDCODEMP AND COL_HIST.BDCODCOL = FO.BDCODCOL) ' ;
  WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FO.BDCODEMP) and (VINC.BDCODCOL = FO.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL  ';
       if (PRIRRFESOCIAL = TRUE) THEN
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FO.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
       ELSE
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FO.BDREFCOMP ORDER BY X.BDREFCOL DESC) ';
      
       WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL)) ';

  IF (WUSARTMP_COL_SELECT = 1) THEN
    wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FO.BDCODEMP and TEMP.BDCODCOL = FO.BDCODCOL) ';

  IF (PRIRRFESOCIAL = TRUE) THEN
     wsql = wsql || ' where FO.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim;
  ELSE
     wsql = wsql || ' where (FO.BDREFCOMP between '||prrefini||' and '||prreffim||')';

  IF (WUSARTMP_EMP_SELECT = 0) THEN
    BEGIN
  IF ((prpuxarfiliais <> 0) AND (prcodmatriz <> '') AND (prcodemp <> '')) THEN
     wsql = wsql || ' and (('||prcodemp||') or ('||prcodmatriz||'))';
  ELSE
  IF ((prpuxarfiliais <> 0) AND (prcodmatriz <> '')) THEN
     wsql = wsql || ' and ('||prcodmatriz||')';
  ELSE
  IF (prcodemp <> '') THEN
     wsql = wsql || ' and ('||prcodemp||')';
    
  IF (prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
         wsql = wsql || ' and ('||replace(upper(prcodcol), 'FOL.', 'FO.')||')';
    END

  /*  FOLHA INTERMITENTE COMPLEMENTAR TOMADOR  */
  wsql = wsql || ' union all' ||
                 ' select FO.BDREFIRRFESOCIAL,FOL.BDCODEMP, FO.BDCODCOL, FO.BDREFTOMADOR, FO.BDCODCONTTI, FO.BDORDEM, FO.BDREFFC,' ||
                   ' FOLV.BDCODVER, FOLV.BDVALVFC, FO.BDDATAPAGFC, FO.BDDATAPROCFC, FO.BDHORAPROCFC, VINC.BDCODCLA, COALESCE(COL_HIST.BDTRIBUTACAOEXTERIOR, 0) BDTRIBUTACAOEXTERIOR';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
     wsql = wsql || ' from TMP_EMPRESAS_SELECT FOL' ||
                    ' inner join vrhf_emp_tfoltomcompint FO on (FO.BDCODEMP = FOL.BDCODEMP)';
  ELSE
     wsql = wsql || ' from TEMPRESAS FOL' ||
                    ' join vrhf_emp_tfoltomcompint FO on (FOL.BDCODEMP = FO.BDCODEMP)';

  wsql = wsql || ' inner join vrhf_emp_tverbafctomint FOLV on (FOLV.BDCODEMP = FOL.BDCODEMP) and (FOLV.BDCODCOL = FO.BDCODCOL)' ||
                                                        ' and (FOLV.BDCODCONTTI = FO.BDCODCONTTI) and (FOLV.BDREFTOMADOR = FO.BDREFTOMADOR)' ||
                                                        ' and (FOLV.BDORDEM = FO.BDORDEM) and (FOLV.BDREFFC = FO.BDREFFC)';

  wsql = wsql||'left outer join VRH_EMP_TCOL_HIST COL_HIST ON (COL_HIST.BDCODEMP = FO.BDCODEMP AND COL_HIST.BDCODCOL = FO.BDCODCOL) ' ;
  WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FO.BDCODEMP) and (VINC.BDCODCOL = FO.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL  ';
       if (PRIRRFESOCIAL = TRUE) THEN
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FO.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
       ELSE
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FO.BDREFCOMP ORDER BY X.BDREFCOL DESC) ';
      
       WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL)) ';

  IF (WUSARTMP_COL_SELECT = 1) THEN
    wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FO.BDCODEMP and TEMP.BDCODCOL = FO.BDCODCOL) ';

  IF (PRIRRFESOCIAL = TRUE) THEN
     wsql = wsql || ' where FO.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim;
  ELSE
     wsql = wsql || ' where (FO.BDREFCOMP between '||prrefini||' and '||prreffim||')';

  IF (WUSARTMP_EMP_SELECT = 0) THEN
    BEGIN
  IF ((prpuxarfiliais <> 0) AND (prcodmatriz <> '') AND (prcodemp <> '')) THEN
     wsql = wsql || ' and (('||prcodemp||') or ('||prcodmatriz||'))';
  ELSE
  IF ((prpuxarfiliais <> 0) AND (prcodmatriz <> '')) THEN
     wsql = wsql || ' and ('||prcodmatriz||')';
  ELSE
  IF (prcodemp <> '') THEN
     wsql = wsql || ' and ('||prcodemp||')';
    
  IF (prcodcol <> '' and WUSARTMP_COL_SELECT = 0) THEN
         wsql = wsql || ' and ('||replace(upper(prcodcol), 'FOL.', 'FO.')||')';
    END

  wsql = 'select * from (' || wsql || ') order by BDCODEMP, BDCODCOL, BDREF, BDCODCONTTI, BDORDEM, BDREFFC';

  wempatu    = 0;
  wcolatu    = 0;
  wconttiatu = 0;
  wrefatu    = 0;
  wrefauxatu = 0;
  wordematu  = 0;
  wbaseir13  = 0;
  winss13    = 0;
  wir13      = 0;
  wdataatu   = NULL;
  wprepri    = 0;
  wdataproca = NULL;
  whoraproca = NULL;
  WBOLSAMEDICO = 0;
  WINCIDESOCIAL = 0;
  wrefirrfesocialatu = -1;

  FOR EXECUTE STATEMENT wsql INTO :wrefirrfesocial, :wcodemp, :wcodcol, :wref, :wcodcontti, :wordem, :wrefaux, :wcodver, :wvalor, :wdatapgto, :wdataproc, :whoraproc, :wcodcla, :wtributacaoexterior DO
  BEGIN
    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end
       
    BDCODTIPO = 272;    -- Cálculos gerado no único Folha
    IF (wempatu    = 0) THEN wempatu    = wcodemp;
    IF (wcolatu    = 0) THEN wcolatu    = wcodcol;
    IF (wrefatu    = 0) THEN wrefatu    = wref;
    IF (wconttiatu = 0) THEN wconttiatu = wcodcontti;
    if (wrefirrfesocialatu = -1) then wrefirrfesocialatu= wrefirrfesocial;

    if (PRPORCC = 0) then
       WORDEMATU = coalesce(WORDEM, 0);
    else
    IF (wordematu  = 0) THEN
       wordematu  = wordem;

    IF (wrefauxatu = 0) THEN wrefauxatu = wrefaux;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wcodcontti <> wconttiatu) OR (wordem <> wordematu) OR (wrefaux <> wrefauxatu)) THEN
       BEGIN
         wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);
         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              bdrefirrfesocial = wrefirrfesocialatu;
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDCODCONTTI      = wcodcontti;
              BDREF            = wrefatu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir13;
              BDINSS           = winss13;
              BDIR             = wir13;
              BDDEP            = 0;
              BDLUCROPJ        = 0;
              BDDESPMED        = 0;
              BDAJCUSTOS       = 0;
              BDPENJUD         = 0;
              BDPENALIM        = 0;
              BDPREVPRIV       = wprepri;
              BDVALABO         = 0;
              BDRENDISENTOS    = 0;
              BDDRENDISENTOS   = '';
              BDDATAPGTO       = wdataatu;
              BDTIPO           = 111;    -- 13 rescisao complementar
              BDINFADIC        = '';
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;
              BDAUXILIOMORADIA = 0;
              BDDIARIA         = 0;
              BDBOLSAMEDICO    = WBOLSAMEDICO;
              BDJUROSMORA      = 0;
              BDINCIDESOCIAL = WINCIDESOCIAL;
              SUSPEND;
            END

         wrefirrfesocialatu = wrefirrfesocial;
         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wconttiatu = wcodcontti;
         wrefatu    = wref;
         wrefauxatu = wrefaux;
         wordematu  = wordem;
         wbaseir13  = 0;
         winss13    = 0;
         wir13      = 0;
         wdataatu   = NULL;
         wprepri    = 0;
         WBOLSAMEDICO = 0;
         WINCIDESOCIAL = 0;
       END

    -- Soma bases
    WCODINCIDIRRF = 0;
    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, BDIRVER, BDCLAVER, BDCODINCIDIRRF FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver, :wirver, :wclassif, :WCODINCIDIRRF;

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end

    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
       begin
          wirver = 0;
       end
    else
--    IF (wtipocodver <= 1) THEN
       BEGIN
         IF (wirver = 3) THEN -- 13 salario
            BEGIN
              IF (wtipocodver = 0) THEN   -- provento
                 wbaseir13 = wbaseir13 + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN   -- desconto
                 BEGIN
                   IF ((SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0') AND -- INSS
                       (SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030')) THEN -- Obrigacoes IR
                      wbaseir13 = wbaseir13 - wvalor;
                 END
            END

          IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.7') THEN -- IR 13 salario rescisao
             wir13 = wir13 + wvalor;
       END

         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.7') OR    -- INSS folha normal
             (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.6')) THEN -- INSS 13 salario normal -- 27813 - Raphael Teodoro - 14/02/2020
            winss13 = winss13 + wvalor;

         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.601.8.2') THEN -- Previdencia privada
            wprepri = wprepri + wvalor;

         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '7.720.0.0') THEN
            WBOLSAMEDICO = WBOLSAMEDICO + WVALOR;

         if (COALESCE(WCODINCIDIRRF, 0) IN (11,12,13,14,41,42,43,51,52,53,54)) then
            WINCIDESOCIAL = 1;

    wdataatu   = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
  END

  IF ((wempatu <> 0) AND (wcolatu <> 0) AND (wrefatu <> 0) AND (wconttiatu <> 0) AND (COALESCE(wordematu,-1) <> 0) AND (wrefauxatu <> 0)) THEN
     BEGIN
       wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);
       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            bdrefirrfesocial = wrefirrfesocialatu;
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDCODCONTTI      = wcodcontti;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir13;
            BDINSS           = winss13;
            BDIR             = wir13;
            BDDEP            = 0;
            BDLUCROPJ        = 0;
            BDDESPMED        = 0;
            BDAJCUSTOS       = 0;
            BDPENJUD         = 0;
            BDPENALIM        = 0;
            BDPREVPRIV       = wprepri;
            BDVALABO         = 0;
            BDRENDISENTOS    = 0;
            BDDRENDISENTOS   = '';
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 111;    -- 13 rescisao complementar
            BDINFADIC        = '';
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            BDAUXILIOMORADIA = 0;
            BDDIARIA         = 0;
            BDBOLSAMEDICO    = WBOLSAMEDICO;
            BDJUROSMORA      = 0;
            BDINCIDESOCIAL = WINCIDESOCIAL;
            SUSPEND;
          END
     END
END^

/* Restore proc. body: SP_VRHF_DADOS_IR_13 */
create or alter procedure SP_VRHF_DADOS_IR_13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PR5002 boolean = false,
    PRVEIODOTOTALIZADOR integer = 0,
    PRPORCC smallint = 1,
    PRDECLARACAO integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,6),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WULTDIAMES integer;
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WDESCVER varchar(40);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR13 numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSS13 numeric(18,6);
declare variable WIR13 numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(999);
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WPREVPRIVCAD numeric(18,6);
declare variable WSQLAUX varchar(32700);
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WCATEGORIACOL integer;
declare variable WCATEGORIAESOCIAL integer;
declare variable WTIPODEDUCAO integer;
declare variable WVALORDESCSIMPL numeric(18,2);
declare variable WVALORDIFDESCSIMPL numeric(18,2);
declare variable WSQLAUXSIMPLI varchar(3000);
declare variable WTIPODEDUCAOATU integer;
declare variable WVALORDESCSIMPLATU numeric(18,2);
declare variable WVALORDIFDESCSIMPLATU numeric(18,2);
declare variable WREFPGTOAUX integer;
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
declare variable WRRADECLARACAO integer;
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WGRAVARUBRICA integer;
begin
  /*SP ESTA QUASE EXCEDENDO LIMITE DE TAMANHO DE 64KB SE PASSAR DA ERRO DE VERSÃO*/
  /* 13º SALÁRIO */
  BDBOLSAESTUDOS = 0;
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

--  WJOINTEMPCOL = 'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

  if (upper(PRCODEMP) = 'TMP_EMPRESAS_SELECT') then
    WUSARTMP_EMP_SELECT = 1;
  if (upper(PRCODCOL) = 'TEMP_FILTRO_COLCON_REL') then
    WUSARTMP_COL_SELECT = 1;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  if (PRPUXARFILIAIS = 0) then
  begin
    if (PRIRRFESOCIAL = true) then
      WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREF13,FOL.BDCODVER,FOL.BDVALV13,FOLN.BDDEP13,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAIRRFESOCIAL AS BDDATAPROC13,FOLN.BDHORAPROC13,FOLN.BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';
    else
      WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREF13,FOL.BDCODVER,FOL.BDVALV13,FOLN.BDDEP13,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROC13,FOLN.BDHORAPROC13,FOLN.BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';

    wsql = wsql||'from VRHF_EMP_T13SAL FOLN ';

    if (WUSARTMP_EMP_SELECT = 1) then
       WSQL = WSQL || 'INNER JOIN tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
       WSQL = WSQL || 'inner join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP and TEMP.BDCODCOL = FOLN.BDCODCOL) ';


    WSQL = WSQL || 'join VRHF_EMP_TVERBA13 FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDREF13 = FOLN.BDREF13) ';
    WSQL = WSQL || 'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';

    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOL.BDREF13 ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where FOLN.BDREFIRRFESOCIAL between ' || PRREFINI || ' and ' || PRREFFIM || ' ';
    else
      WSQL = WSQL || 'where FOL.BDREF13 between ' || PRREFINI || ' and ' || PRREFFIM || ' ';
    if (PRCODEMP is not null and
        PRCODEMP <> '' and
        WUSARTMP_EMP_SELECT = 0) then
      WSQL = WSQL || ' and ' || PRCODEMP;
    if (PRCODCOL is not null and
        PRCODCOL <> '' and
        WUSARTMP_COL_SELECT = 0) then
      WSQL = WSQL || ' and ' || PRCODCOL;

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREF13,FOL.BDCODVER ';
    else
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREF13 ';
  end
  else
  begin
    if (PRIRRFESOCIAL = true) then
      WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREF13,FO.BDCODVER,FO.BDVALV13,FOLN.BDDEP13,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAIRRFESOCIAL AS BDDATAPROC13,FOLN.BDHORAPROC13,FOLN.BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';
    else
      WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREF13,FO.BDCODVER,FO.BDVALV13,FOLN.BDDEP13,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROC13,FOLN.BDHORAPROC13,FOLN.BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';

    wsql = wsql||'from VRHF_EMP_T13SAL FOLN join TEMPRESAS EMAT on (EMAT.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_EMP_SELECT = 1) then
       wsql= wsql||'inner join TMP_EMPRESAS_SELECT TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
        WSQL = WSQL || 'inner join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FOLN.BDCODEMP and TEM.BDCODCOL = FOLN.BDCODCOL) ';

    wsql = wsql||'join VRHF_EMP_TVERBA13 FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDREF13 = FOLN.BDREF13) ';
    WSQL = WSQL || 'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver)  ';

    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOLN.BDREF13 ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where FOLN.BDREFIRRFESOCIAL between ' || PRREFINI || ' and ' || PRREFFIM || ' ';
    else
      WSQL = WSQL || 'where FOLN.BDREF13 between ' || PRREFINI || ' and ' || PRREFFIM || ' ';

    if (WUSARTMP_EMP_SELECT = 0) then
    begin
      if (PRCODEMP is not null and
          PRCODEMP <> '') then
        WSQL = WSQL || ' and ((' || replace(upper(PRCODEMP), 'FOL.', 'FOLN.') || ')';
      if (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '') then
        WSQL = WSQL || ' or (' || replace(upper(PRCODMATRIZ), 'FOL.', 'EMAT.') || ')';
      if ((PRCODEMP is not null and
          PRCODEMP <> '') or (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '')) then
        WSQL = WSQL || ') ';
    end
    if (PRCODCOL is not null and
        PRCODCOL <> '' and
        WUSARTMP_COL_SELECT = 0) then
      WSQL = WSQL || ' and ' || replace(upper(PRCODCOL), 'FOL.', 'FOLN.') || ' ';

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREF13,FO.BDCODVER ';
    else
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREF13 ';
  end

  WEMPATU = 0;
  WCOLATU = 0;
  WREFATU = 0;
  WBASEIR13 = 0;
  WINSS13 = 0;
  WIR13 = 0;
  WDEPATU = 0;
  WPENJUD = 0;
  WPENALIM = 0;
  WPREPRI = 0;
  WRENDIS = 0;
  WDRENDIS = '';
  WDATAPROCA = null;
  WHORAPROCA = null;
  BDVALABO = 0;
  BDLUCROPJ = 0;
  BDAJCUSTOS = 0;
  BDDESPMED = 0;
  BDINDRESC = 0;
  WORDEM = 0;
  WTIPODEDUCAO = 0;
  WVALORDESCSIMPL = 0;
  WVALORDIFDESCSIMPL = 0;
  WTIPODEDUCAOATU = 0;
  WVALORDESCSIMPLATU = 0;
  WVALORDIFDESCSIMPLATU = 0;
  WBOLSAMEDICO = 0;
  WINCIDESOCIAL = 0;
  WCODINCIDIRRF = 0;
  WREFIRRFESOCIALATU = -1;
  BDCODFIR = 0;

  for execute statement WSQL
          into :WREFIRRFESOCIAL, :WCODEMP, :WCODCOL, :WREF, :WCODVER, :WVALOR, :WDEP, :WCLASSIF, :WDESCVER, :WDATAPROC,
          :WHORAPROC, :WORDEM, :WTIPODEDUCAO, :WVALORDESCSIMPL, :WVALORDIFDESCSIMPL, :WCODCLA, :WTRIBUTACAOEXTERIOR
  do
  begin
    BDCODTIPO = 272;   -- Cálculos gerados no Único Folha

    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end

    if (WEMPATU = 0) then
      WEMPATU = WCODEMP;
    if (WCOLATU = 0) then
      WCOLATU = WCODCOL;
    if (WREFATU = 0) then
      WREFATU = WREF;
    if (WREFIRRFESOCIALATU = -1) then
      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;
    if ((WORDEMATU = 0) or (WORDEMATU is null)) then
      WORDEMATU = WORDEM;
    if (WVALORDESCSIMPLATU = 0) then
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
    if (WVALORDIFDESCSIMPLATU = 0) then
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
    if (WTIPODEDUCAOATU = 0) then
      WTIPODEDUCAOATU = WTIPODEDUCAO;

    if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WREF <> WREFATU)) then
    begin
      if (substring(cast(WREFATU as varchar(6)) from 5 for 2) = '12') then
      begin
        WDATAATU = cast((substring(WREFATU from 1 for 4) || '-12-20') as date);
        WREFPAGTO = cast((substring(cast(WDATAATU as varchar(10)) from 1 for 4) || substring(cast(WDATAATU as varchar(10)) from 6 for 2)) as integer);
      end
      else
      begin
        WREFPAGTO = WREFATU;
        WDATAATU = cast((substring(WREFATU from 1 for 4) || '-' || substring(cast(WREFATU as varchar(6)) from 5 for 2) || '-20') as date);
        WULTDIAMES = extract(day from (WDATAATU - extract(day from WDATAATU) + 32 - extract(day from WDATAATU - extract(day from WDATAATU) + 32)));
        WDATAATU = cast((substring(WREFATU from 1 for 4) || '-' || substring(cast(WREFATU as varchar(6)) from 5 for 2) || '-' || WULTDIAMES) as date);
      end

      if (WREFPAGTO >= PRREFINI and
          WREFPAGTO <= PRREFFIM) then
      begin
        WPREVPRIVCAD = 0;
        select sum(COALESCE(LANPREV.BDVAL13SAL,0)) from VRH_EMP_TLANCPREVCOMP LANPREV join VRH_BASE_TCADPREVCOMP CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV and CADPREV.BDNATPREV <> 2) /* 184717 Leonardo Schwab 16/11/2023 */
        where LANPREV.BDCODEMP = :WEMPATU and LANPREV.BDCODCOL = :WCOLATU and LANPREV.BDREFINI <= :WREFATU and ((COALESCE(LANPREV.BDREFFIN, 0) = 0) or (COALESCE(LANPREV.BDREFFIN, 0) >= :WREFATU)) and COALESCE(LANPREV.BDVAL13SAL,0) > 0
        into :WPREVPRIVCAD;
        WPREVPRIVCAD = coalesce(WPREVPRIVCAD, 0);
        BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
        BDCODEMP = WEMPATU;
        BDCODCOL = WCOLATU;
        BDREF = WREFATU;
        BDREFPAG = WREFPAGTO;
        BDRENDTRIBUTAVEL = WBASEIR13;
        BDINSS = WINSS13;
        BDIR = WIR13;
        BDDEP = WDEPATU;
        BDPENJUD = WPENJUD;
        BDPENALIM = WPENALIM;

        WPENALIM = 0;
        select sum(BDVALPEND)
        from VRHF_EMP_TA13PENSAO_DEP
        where BDCODEMP = :WEMPATU and
              BDCODCOL = :WCOLATU and
              cast(BDREFA13 as varchar(6)) starting with substring(cast(:WREFATU as varchar(6)) from 1 for 4)
        into :WPENALIM;
        WPENALIM = coalesce(WPENALIM, 0);

        if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = FALSE) then
           BDRENDTRIBUTAVEL = BDRENDTRIBUTAVEL + WPENALIM;

        if (WPREPRI <> 0) then
          BDPREVPRIV = WPREPRI;
        else
          BDPREVPRIV = WPREVPRIVCAD;

        BDAUXILIOMORADIA = 0;
        BDDIARIA = 0;
        BDJUROSMORA = 0;
        BDBOLSAMEDICO = WBOLSAMEDICO;
        BDRENDISENTOS = WRENDIS;
        BDDRENDISENTOS = WDRENDIS;
        BDDATAPGTO = WDATAATU;
        BDTIPO = 10;
        BDINFADIC = '';
        BDDATAPROC = WDATAPROCA;
        BDHORAPROC = WHORAPROCA;
        BDORDEM = WORDEMATU;
        BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPL;
        BDINCIDESOCIAL = WINCIDESOCIAL;

        if (PRATUALIZAINFODESCSIMPLE = true) then
        begin
          WREFPGTOAUX = cast((substring(WREFPAGTO from 1 for 4) || '13') as integer);
          WSQLAUXSIMPLI = 'update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPGTOAUX || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';
          execute statement WSQLAUXSIMPLI;
        end
        suspend;
      end

      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;
      WEMPATU = WCODEMP;
      WCOLATU = WCODCOL;
      WREFATU = WREF;
      WBASEIR13 = 0;
      WINSS13 = 0;
      WIR13 = 0;
      WDEPATU = 0;
      WPENJUD = 0;
      WPENALIM = 0;
      WPREPRI = 0;
      WRENDIS = 0;
      WDRENDIS = '';
      WORDEMATU = WORDEM;
      WTIPODEDUCAOATU = WTIPODEDUCAO;
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
      WBOLSAMEDICO = 0;
      WINCIDESOCIAL = 0;
    end

    WCODINCIDIRRF = 0;
    select first 1 BDTIPOCODVER, BDIRVER, BDRENDISENTOIRVER, BDCODINCIDIRRF
    from VRH_BASE_TVERBAS_REF
    where BDCODVER = :WCODVER and
          BDREFVER <= :WREFATU
    order by BDCODVER desc, BDREFVER desc
    into :WTIPOCODVER, :WIRVER, :WRENDISENTOVER, :WCODINCIDIRRF;

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end

    
    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
      begin
         WIRVER = 0;
      end
    else
    --    if (wtipocodver <= 1) then
    begin
      if (WIRVER = 3) then
      begin
        if (WTIPOCODVER = 0) then
          WBASEIR13 = WBASEIR13 + WVALOR;
        else
        if (WTIPOCODVER = 1) then
        begin
          if (substring(WCLASSIF from 1 for 7) <> '9.010.0' and
              substring(WCLASSIF from 1 for 5) <> '0.030' and
              substring(WCLASSIF from 1 for 7) <> '5.001.8') then
            WBASEIR13 = WBASEIR13 - WVALOR;
        end
      end


      if (substring(WCLASSIF from 1 for 7) = '9.010.1') then
          WIR13 = WIR13 + WVALOR;

    end

      if (substring(WCLASSIF from 1 for 7) = '9.010.0') then
        WINSS13 = WINSS13 + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '5.001.8.0') then
        WPENJUD = WPENJUD + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '5.001.8.1') then
        WPENALIM = WPENALIM + WVALOR;

      if (PR5002 = true and
          WCLASSIF = '5.080.0.0.031') then
        WPENALIM = WPENALIM + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '5.001.8.2') then
        WPREPRI = WPREPRI + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '5.009.0.0') then
        WPREPRI = WPREPRI + WVALOR;
      if (upper(WRENDISENTOVER) = 'TRUE') then
      begin
        WRENDIS = WRENDIS + WVALOR;

        if (PRVEIODOTOTALIZADOR = 1) then
          WDRENDIS = substring(WDRENDIS || WDESCVER from 1 for 999);
        else
          WDRENDIS = substring(WDRENDIS || WDESCVER from 1 for 200);
      end

      if (substring(WCLASSIF from 1 for 9) = '5.520.0.0') then
        WBOLSAMEDICO = WBOLSAMEDICO + WVALOR;

      if (coalesce(WCODINCIDIRRF, 0) in (11, 12, 13, 14, 41, 42, 43, 51, 52, 53, 54)) then
        WINCIDESOCIAL = 1;

    WDEPATU = WDEP;
    WDATAPROCA = WDATAPROC;
    WHORAPROCA = WHORAPROC;
  end

  if (WEMPATU <> 0 and
      WCOLATU <> 0 and
      WREFATU <> 0) then
  begin
    if (substring(cast(WREFATU as varchar(6)) from 5 for 2) = '12') then
    begin
      WDATAATU = cast((substring(WREFATU from 1 for 4) || '-12-20') as date);
      WREFPAGTO = cast((substring(cast(WDATAATU as varchar(10)) from 1 for 4) || substring(cast(WDATAATU as varchar(10)) from 6 for 2)) as integer);
    end
    else
    begin
      WREFPAGTO = WREFATU;
      WDATAATU = cast((substring(WREFATU from 1 for 4) || '-' || substring(cast(WREFATU as varchar(6)) from 5 for 2) || '-20') as date);
      WULTDIAMES = extract(day from (WDATAATU - extract(day from WDATAATU) + 32 - extract(day from WDATAATU - extract(day from WDATAATU) + 32)));
      WDATAATU = cast((substring(WREFATU from 1 for 4) || '-' || substring(cast(WREFATU as varchar(6)) from 5 for 2) || '-' || WULTDIAMES) as date);
    end

    if (WREFPAGTO >= PRREFINI and
        WREFPAGTO <= PRREFFIM) then
    begin
      WPREVPRIVCAD = 0;
      select sum(COALESCE(LANPREV.BDVAL13SAL,0)) from VRH_EMP_TLANCPREVCOMP LANPREV join VRH_BASE_TCADPREVCOMP CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV and CADPREV.BDNATPREV <> 2)  /* 184717 Leonardo Schwab 16/11/2023 */
      where LANPREV.BDCODEMP = :WEMPATU and LANPREV.BDCODCOL = :WCOLATU and LANPREV.BDREFINI <= :WREFATU and ((COALESCE(LANPREV.BDREFFIN, 0) = 0) or (COALESCE(LANPREV.BDREFFIN, 0) >= :WREFATU)) and COALESCE(LANPREV.BDVAL13SAL,0) > 0
      into :WPREVPRIVCAD;
      WPREVPRIVCAD = coalesce(WPREVPRIVCAD, 0);
      BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
      BDCODEMP = WEMPATU;
      BDCODCOL = WCOLATU;
      BDREF = WREFATU;
      BDREFPAG = WREFPAGTO;
      BDRENDTRIBUTAVEL = WBASEIR13;
      BDINSS = WINSS13;
      BDIR = WIR13;
      BDDEP = WDEPATU;
      BDPENJUD = WPENJUD;
      BDPENALIM = WPENALIM;

      WPENALIM = 0;
      select sum(BDVALPEND)
      from VRHF_EMP_TA13PENSAO_DEP
      where BDCODEMP = :WEMPATU and
            BDCODCOL = :WCOLATU and
            cast(BDREFA13 as varchar(6)) starting with substring(cast(:WREFATU as varchar(6)) from 1 for 4)
      into :WPENALIM;
      WPENALIM = coalesce(WPENALIM, 0);

      if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = FALSE) then
          BDRENDTRIBUTAVEL = BDRENDTRIBUTAVEL + WPENALIM;

      if (WPREPRI <> 0) then
        BDPREVPRIV = WPREPRI;
      else
        BDPREVPRIV = WPREVPRIVCAD;

      BDAUXILIOMORADIA = 0;
      BDDIARIA = 0;
      BDJUROSMORA = 0;
      BDBOLSAMEDICO = WBOLSAMEDICO;
      BDRENDISENTOS = WRENDIS;
      BDDRENDISENTOS = WDRENDIS;
      BDDATAPGTO = WDATAATU;
      BDTIPO = 10;
      BDINFADIC = '';
      BDDATAPROC = WDATAPROCA;
      BDHORAPROC = WHORAPROCA;
      BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
      BDINCIDESOCIAL = WINCIDESOCIAL;

      if (PRATUALIZAINFODESCSIMPLE = true) then
      begin
        WREFPGTOAUX = cast((substring(WREFPAGTO from 1 for 4) || '13') as integer);
        WSQLAUXSIMPLI = 'update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPGTOAUX || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';
        execute statement WSQLAUXSIMPLI;
      end
      suspend;
    end
  end
  /* 13º RESCISAO DA FOLHA NORMAL */
  for select bdrefirrfesocial,BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS,BDPENJUD,BDPENALIM,
             BDPREVPRIV,BDINDRESC,BDVALABO,BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,BDDATAPROC,BDHORAPROC,BDORDEM, BDBOLSAESTUDOS, BDVALORDESCONTOSIMPLIFICADO,
             BDAUXILIOMORADIA,BDDIARIA,BDBOLSAMEDICO,BDJUROSMORA,BDINCIDESOCIAL, BDCODTIPO
      from SP_VRHF_DADOS_IR_13FN(:prcodemp, :prcodcol, :prrefini, :prreffim, :prpuxarfiliais, :prcodmatriz, :prirrfesocial, :pratualizainfodescsimple,
                                 :prveiodototalizador, :prporcc)
   into :BDREFIRRFESOCIAL, :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR,
        :BDDEP, :BDLUCROPJ, :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM, :BDPREVPRIV, :BDINDRESC, :BDVALABO,
        :BDRENDISENTOS, :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDDATAPROC, :BDHORAPROC, :BDORDEM, :BDBOLSAESTUDOS,
        :BDVALORDESCONTOSIMPLIFICADO, :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA, :BDINCIDESOCIAL, :BDCODTIPO
  do
    suspend;

  WRRADECLARACAO = -1;
  if (coalesce(PRDECLARACAO, 0) = 1) then
    WRRADECLARACAO = 0;

  /*  13º RESC FOLHA COMP NORMAL E TOMADOR  */
  for select bdrefirrfesocial, BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS,BDPENJUD,BDPENALIM,
             BDPREVPRIV,BDINDRESC,BDVALABO,BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,BDDATAPROC,BDHORAPROC,BDORDEM,BDAUXILIOMORADIA,BDDIARIA,
             BDBOLSAMEDICO,BDJUROSMORA, BDINCIDESOCIAL, BDCODTIPO
      from SP_VRHF_DADOS_IR_13FC(:PRCODEMP, :PRCODCOL, :prrefini, :prreffim, :prpuxarfiliais, :prcodmatriz, false, :wrradeclaracao)
  into :BDREFIRRFESOCIAL, :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR,
       :BDDEP, :BDLUCROPJ, :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM, :BDPREVPRIV, :BDINDRESC, :BDVALABO,
       :BDRENDISENTOS, :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDDATAPROC, :BDHORAPROC, :BDORDEM,
       :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA, :BDINCIDESOCIAL, :BDCODTIPO
  do
    suspend;

  /*  DADOS DA FICHA  */
  if (PRPUXARFILIAIS = 0) then
  begin
    WSQL = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0) BDBASEIRFIR,COALESCE(FOL.BDVALINSSFIR,0) BDVALINSSFIR,COALESCE(FOL.BDVALIRFIR,0) BDVALIRFIR,COALESCE(FOL.BDVALDEPFIR,0) BDVALDEPFIR,COALESCE(FOL.BDDISTRLUCROFIR,0) BDDISTRLUCROFIR,' || 'COALESCE(FOL.BDDESPMEDFIR,0) BDDESPMEDFIR,COALESCE(FOL.BDAJUDACUSTOFIR,0) BDAJUDACUSTOFIR,COALESCE(FOL.BDDESPJUDFIR,0) BDDESPJUDFIR,COALESCE(FOL.BDPENALIMFIR,0) BDPENALIMFIR,COALESCE(FOL.BDPREVPRIVFIR,0) BDPREVPRIVFIR,COALESCE(FOL.BDVALINDFIR,0) BDVALINDFIR,COALESCE(FOL.BDVALABOFIR,0) BDVALABOFIR,COALESCE(FOL.BDRENDISENTOSFIR,0) BDRENDISENTOSFIR,FOL.BDDESCRENDISENTOSFIR,' || 'FOL.BDDATAFIR, ''' || ''' BDAUX, fol.BDVALORDESCONTOSIMPLIFICADO, COALESCE(fol.BDAUXILIOMORADIAFIR,0) BDAUXILIOMORADIAFIR, COALESCE(fol.BDDIARIAFIR,0) BDDIARIAFIR, COALESCE(fol.BDBOLSAMEDICOFIR,0) BDBOLSAMEDICOFIR, COALESCE(fol.BDJUROSMORAFIR,0) BDJUROSMORAFIR, fol.BDCODFIR, FOL.BDDEMDEV, COALESCE(FOL.BDCODTIPO, 201) BDCODTIPO, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';
    WSQL = WSQL || 'from VRHF_EMP_TFICHAIRRF FOL ';

    if (WUSARTMP_EMP_SELECT = 1) then
      WSQL = WSQL || 'inner join tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FOL.BDCODEMP) ';
    if (WUSARTMP_COL_SELECT = 1) then
      WSQL = WSQL || 'inner join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOL.BDCODEMP) and (HIST.BDCODCOL = FOL.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOL.BDCODEMP) and (VINC.BDCODCOL = FOL.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOL.BDREFIRFIR ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL)) ';

    WSQL = WSQL || 'where FOL.BDTIPOCALCFIR in (9002,9012,9099,9100) and FOL.BDREFIRFIR >= ' || PRREFINI || ' and FOL.BDREFIRFIR <= ' || PRREFFIM || ' and ' || 'not exists (select first 1 S13.BDCODEMP,S13.BDCODCOL,S13.BDREF13 from VRHF_EMP_T13SAL S13 where S13.BDCODEMP = FOL.BDCODEMP and S13.BDCODCOL = FOL.BDCODCOL and S13.BDREF13 = FOL.BDREFFIR) and ' || 'not exists (select first 1 A13.BDCODEMP,A13.BDCODCOL,A13.BDREFA13 from VRHF_EMP_TA13SAL A13 where A13.BDCODEMP = FOL.BDCODEMP and A13.BDCODCOL = FOL.BDCODCOL and A13.BDREFA13 = FOL.BDREFFIR) and ';

    WSQL = WSQL || ' not exists(select FTOR.BDCODEMP, FTOR.BDCODCOL, FTOR.BDREFTOMADOR, RESC.BDREFPAGRESCISAO ' || ' from VRHF_EMP_TFOLHATOMADOR FTOR ' || ' join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FTOR.BDCODEMP and ' || ' RESC.BDCODCOL = FTOR.BDCODCOL AND ftor.BDREFTOMADOR = resc.BDREFRESCISAO) ' || ' where ((FTOR.BDREFTOMADOR = RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= ' || PRREFINI || ' and  RESC.BDREFPAGRESCISAO <= ' || PRREFFIM || ')) and ' || ' FTOR.BDCODEMP = FOL.BDCODEMP and FTOR.BDCODCOL = FOL.BDCODCOL and RESC.BDREFPAGRESCISAO = FOL.BDREFFIR)  and ' || ' not exists(select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FN.BDCODEMP and ' || ' RESC.BDCODCOL = FN.BDCODCOL AND fn.BDREFFN = resc.BDREFRESCISAO) ' || ' where ((FN.BDREFFN = RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= ' || PRREFINI || ' and RESC.BDREFPAGRESCISAO <= ' || PRREFFIM || ')) and ' || ' FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and RESC.BDREFPAGRESCISAO  = FOL.BDREFFIR) ';

    if (PRCODEMP is not null and
        PRCODEMP <> '' and
        WUSARTMP_EMP_SELECT = 0) then
      WSQL = WSQL || ' and ' || PRCODEMP;
    if (PRCODCOL is not null and
        PRCODCOL <> '' and
        WUSARTMP_COL_SELECT = 0) then
      WSQL = WSQL || ' and ' || PRCODCOL;

    WSQL = WSQL || ' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDDATAFIR ';
  end
  else
  begin
    WSQL = 'select FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0) BDBASEIRFIR,COALESCE(FO.BDVALINSSFIR,0) BDVALINSSFIR,COALESCE(FO.BDVALIRFIR,0) BDVALIRFIR,COALESCE(FO.BDVALDEPFIR,0) BDVALDEPFIR,COALESCE(FO.BDDISTRLUCROFIR,0) BDDISTRLUCROFIR,' || 'COALESCE(FO.BDDESPMEDFIR,0) BDDESPMEDFIR,COALESCE(FO.BDAJUDACUSTOFIR,0) BDAJUDACUSTOFIR,COALESCE(FO.BDDESPJUDFIR,0) BDDESPJUDFIR,COALESCE(FO.BDPENALIMFIR,0) BDPENALIMFIR,COALESCE(FO.BDPREVPRIVFIR,0) BDPREVPRIVFIR,COALESCE(FO.BDVALINDFIR,0) BDVALINDFIR,COALESCE(FO.BDVALABOFIR,0) BDVALABOFIR,COALESCE(FO.BDRENDISENTOSFIR,0) BDRENDISENTOSFIR,FO.BDDESCRENDISENTOSFIR,' || 'FO.BDDATAFIR, ''' || ''' BDAUX, fo.BDVALORDESCONTOSIMPLIFICADO, COALESCE(fo.BDAUXILIOMORADIAFIR,0) BDAUXILIOMORADIAFIR, COALESCE(fo.BDDIARIAFIR,0) BDDIARIAFIR, COALESCE(fo.BDBOLSAMEDICOFIR,0) BDBOLSAMEDICOFIR, COALESCE(fo.BDJUROSMORAFIR,0) BDJUROSMORAFIR, fo.BDCODFIR, FO.BDDEMDEV, COALESCE(FO.BDCODTIPO, 201) BDCODTIPO, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';
    wsql = wsql||'from VRHF_EMP_TFICHAIRRF FO join TEMPRESAS EMAT on (EMAT.BDCODEMP = FO.BDCODEMP) ';

    if (WUSARTMP_EMP_SELECT = 1) then
      WSQL = WSQL || 'inner join tmp_empresas_select TEMP on (TEMP.BDCODEMP = FO.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
      WSQL = WSQL || 'inner join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FO.BDCODEMP and TEM.BDCODCOL = FO.BDCODCOL) ';

    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FO.BDCODEMP) and (HIST.BDCODCOL = FO.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FO.BDCODEMP) and (VINC.BDCODCOL = FO.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FO.BDREFIRFIR ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL)) ';

    WSQL = WSQL || 'where FO.BDTIPOCALCFIR in (9002,9012,9099,9100) and FO.BDREFIRFIR >= ' || PRREFINI || ' and FO.BDREFIRFIR <= ' || PRREFFIM || ' and ' || 'not exists (select first 1 S13.BDCODEMP,S13.BDCODCOL,S13.BDREF13 from VRHF_EMP_T13SAL S13 where S13.BDCODEMP = FO.BDCODEMP and S13.BDCODCOL = FO.BDCODCOL and S13.BDREF13 = FO.BDREFFIR) and ' || 'not exists (select first 1 A13.BDCODEMP,A13.BDCODCOL,A13.BDREFA13 from VRHF_EMP_TA13SAL A13 where A13.BDCODEMP = FO.BDCODEMP and A13.BDCODCOL = FO.BDCODCOL and A13.BDREFA13 = FO.BDREFFIR)  and ';
    WSQL = WSQL || ' not exists(select FTOR.BDCODEMP, FTOR.BDCODCOL, FTOR.BDREFTOMADOR, RESC.BDREFPAGRESCISAO ' || ' from VRHF_EMP_TFOLHATOMADOR FTOR ' || ' join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FTOR.BDCODEMP and RESC.BDCODCOL = FTOR.BDCODCOL AND ftor.BDREFTOMADOR = resc.BDREFRESCISAO) ' || ' where ((FTOR.BDREFTOMADOR = RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= ' || PRREFINI || ' and RESC.BDREFPAGRESCISAO <= ' || PRREFFIM || ')) and ' || ' FTOR.BDCODEMP = FO.BDCODEMP and FTOR.BDCODCOL = FO.BDCODCOL and RESC.BDREFPAGRESCISAO = FO.BDREFFIR)  and ' || ' not exists(select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FN.BDCODEMP and ' || ' RESC.BDCODCOL = FN.BDCODCOL AND fn.BDREFFN = resc.BDREFRESCISAO) ' || ' where ((FN.BDREFFN = RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= ' || PRREFINI || ' and  RESC.BDREFPAGRESCISAO <= ' || PRREFFIM || ')) and ' || ' FN.BDCODEMP = FO.BDCODEMP and  FN.BDCODCOL = FO.BDCODCOL and RESC.BDREFPAGRESCISAO  = FO.BDREFFIR) ';

    if (WUSARTMP_EMP_SELECT = 0) then
    begin
      if (PRCODEMP is not null and
          PRCODEMP <> '') then
         WSQL = WSQL || ' and ((' || replace(upper(PRCODEMP), 'FOL.', 'FO.') || ')';
      if (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '') then
         WSQL = WSQL || ' or (' || replace(upper(PRCODMATRIZ), 'FOL.', 'EMAT.') || ')';

      if (PRCODEMP is not null and
          PRCODEMP <> '') then
         WSQL = WSQL || ') ';
    end

    if (PRCODCOL is not null and
        PRCODCOL <> '' and
        WUSARTMP_COL_SELECT = 0) then
      WSQL = WSQL || ' and ' || replace(upper(PRCODCOL), 'FOL.', 'FO.') || ' ';

    WSQL = WSQL || ' order by FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDDATAFIR ';
  end
  WSQLAUX = 'Select FOL.*, COALESCE(CATEGORIAS.BDCATEGORIACOL,0) BDCATEGORIACOL, COALESCE(CATEGORIAS.BDCATEGORIAESOCIAL,0) BDCATEGORIAESOCIAL from (' || WSQL || ') FOL ';
  WSQLAUX = WSQLAUX || 'left outer join VRHF_EMP_TCOLCON_FGTSGPS CATEGORIAS on (CATEGORIAS.BDCODEMP = FOL.BDCODEMP and CATEGORIAS.BDCODCOL = FOL.BDCODCOL and CATEGORIAS.BDREFCOL = (SELECT COALESCE(MAX(X.BDREFCOL),0) BDREFCOL FROM VRHF_EMP_TCOLCON_FGTSGPS X ';
  WSQLAUX = WSQLAUX || ' WHERE (X.BDCODEMP = FOL.BDCODEMP) AND(X.BDCODCOL = FOL.BDCODCOL) AND (X.BDREFCOL <= (SELECT TRIM(rdb$get_context(' || '''' || 'USER_SESSION' || '''' || ', ' || '''' || 'W_ANOMES' || '''' || ')) BDREF FROM rdb$database))))';
  for execute statement WSQLAUX
          into :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR, :BDDEP, :BDLUCROPJ,
          :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM, :BDPREVPRIV, :BDINDRESC, :BDVALABO, :BDRENDISENTOS,
          :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDVALORDESCONTOSIMPLIFICADO, :BDAUXILIOMORADIA, :BDDIARIA,
          :BDBOLSAMEDICO, :BDJUROSMORA, :BDCODFIR, :BDDEMDEV, :BDCODTIPO, :WCODCLA,  :WTRIBUTACAOEXTERIOR, :WCATEGORIACOL, :WCATEGORIAESOCIAL
  do
  begin
    BDDATAPROC = BDDATAPGTO;
    BDHORAPROC = '00:00:00';
    BDREFIRRFESOCIAL = BDREFPAG;

    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
      begin
        BDRENDTRIBUTAVEL = 0;
        BDIR = 0;
      end

    if (PRATUALIZAINFODESCSIMPLE = true) then
    begin
      WSQLAUXSIMPLI = 'update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) values (' || current_connection || ', ' || :BDCODEMP || ', ' || :BDCODCOL || ', ' || :BDREFPAG || ', 0, ' || coalesce(:BDPENALIM, 0) || ', ' || coalesce(:BDDEP, 0) || ', ' || coalesce(:BDPREVPRIV, 0) || ', ' || coalesce(:BDINSS, 0) || ', ' || coalesce(:BDVALORDESCONTOSIMPLIFICADO, 0) || ', FALSE, ' || coalesce(:BDRENDTRIBUTAVEL, 0) || ')';
      execute statement WSQLAUXSIMPLI;
    end

    if (coalesce(BDRENDTRIBUTAVEL, 0) <> 0) then
      BDINCIDESOCIAL = 1;

    if ((WCATEGORIACOL <> 4) or (WCATEGORIAESOCIAL <> 111)) then
      suspend;
  end

  /*  PENSÕES DO ADIANTAMENTO DE 13º SALÁRIO  */
  for select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS,BDPENJUD,BDPENALIM,BDPREVPRIV,
             BDINDRESC,BDVALABO,BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,BDDATAPROC,BDHORAPROC,BDORDEM,BDAUXILIOMORADIA,BDDIARIA,BDBOLSAMEDICO,
             BDJUROSMORA,BDINCIDESOCIAL, BDCODTIPO
      from SP_VRHF_DADOS_IR_AD13(:PRCODEMP, :PRCODCOL, :PRREFINI, :PRREFFIM, :PRPUXARFILIAIS, :PRCODMATRIZ)
  into :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR, :BDDEP, :BDLUCROPJ,
       :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM, :BDPREVPRIV, :BDINDRESC, :BDVALABO, :BDRENDISENTOS,
       :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDDATAPROC, :BDHORAPROC, :BDORDEM, :BDAUXILIOMORADIA, :BDDIARIA,
       :BDBOLSAMEDICO, :BDJUROSMORA, :BDINCIDESOCIAL, :BDCODTIPO
  do
  begin
    BDREFIRRFESOCIAL = BDREFPAG;
    suspend;
  end
end^

/* Restore proc. body: SP_VRHF_DADOS_IR_AD */
create or alter procedure SP_VRHF_DADOS_IR_AD (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDTIPODEDUCAOFOLHA integer,
    BDVALORDESCONTOSIMPLIFICADO DM_NUMERIC_15_2,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WDATA date;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WDESCVER varchar(40);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WDATAATU date;
declare variable WBASEIR numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSSN numeric(18,6);
declare variable WIR numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(999);
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WORDEM integer;
declare variable WRUBRICA integer;
declare variable WCATEGORIAESOCIAL integer;
declare variable WBOLSAESTUDOS numeric(18,6);
declare variable WDRENDIS2 varchar(999);
declare variable WDRENDIS3 varchar(999);
declare variable WREFATU integer;
declare variable WORDEMATU integer;
declare variable WTIPODEDUCAO integer;
declare variable WVALORDESCSIMPL numeric(18,2);
declare variable WVALORDIFDESCSIMPL numeric(18,2);
declare variable WSQLAUX varchar(3000);
declare variable WTIPODEDUCAOATU integer;
declare variable WVALORDESCSIMPLATU numeric(18,2);
declare variable WVALORDIFDESCSIMPLATU numeric(18,2);
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WINCIDESOCIALFER integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WGRAVARUBRICA integer;
begin
  /*
      ADIANTAMENTO SALARIAL
  */

  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  if (upper(PRCODEMP) = 'TMP_EMPRESAS_SELECT') then
    WUSARTMP_EMP_SELECT = 1;

  if (upper(PRCODCOL) = 'TEMP_FILTRO_COLCON_REL') then
    WUSARTMP_COL_SELECT = 1;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  if (PRPUXARFILIAIS = 0) then
  begin
    if (PRIRRFESOCIAL = true) then
      WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDDATAAD,FOL.BDCODVER,FOL.BDVALVAD,FOLN.BDDEPIRAD,FOLN.BDREFAD,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAIRRFESOCIAL AS BDDATAPROCAD,FOLN.BDHORAPROCAD,FOLN.BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';
    else
      WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDDATAAD,FOL.BDCODVER,FOL.BDVALVAD,FOLN.BDDEPIRAD,FOLN.BDREFAD,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCAD,FOLN.BDHORAPROCAD,FOLN.BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';

    WSQL = WSQL || 'from VRHF_EMP_TADSAL FOLN ';

    if (WUSARTMP_EMP_SELECT = 1) then
      WSQL = WSQL || 'INNER JOIN tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
      WSQL = WSQL || 'JOIN TEMP_FILTRO_COLCON_REL TEM ON (TEM.BDCODEMP = FOLN.BDCODEMP AND TEM.BDCODCOL = FOLN.BDCODCOL) ';

    WSQL = WSQL || 'join VRHF_EMP_TVERBAAD FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDDATAAD = FOLN.BDDATAAD) ';

    WSQL = WSQL || 'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOLN.BDREFAD ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where FOLN.BDREFIRRFESOCIAL between ' || PRREFINI || ' and ' || PRREFFIM || ' ';
    else
      WSQL = WSQL || 'where FOLN.BDREFAD >= ' || PRREFINI || ' and FOLN.BDREFAD <= ' || PRREFFIM || ' ';

    if (PRCODEMP is not null and
        PRCODEMP <> '' and
        WUSARTMP_EMP_SELECT = 0) then
      WSQL = WSQL || ' and ' || REPLACE(UPPER(PRCODEMP), 'FOL.', 'FOLN.');

    if (PRCODCOL is not null and
        PRCODCOL <> '' and
        WUSARTMP_COL_SELECT = 0) then
      WSQL = WSQL || ' and ' || REPLACE(UPPER(PRCODCOL), 'FOL.', 'FOLN.');

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDDATAAD,FOL.BDCODVER ';
    else
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDDATAAD ';
  end
  else
  begin
    if (PRIRRFESOCIAL = true) then
      WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDDATAAD,FO.BDCODVER,FO.BDVALVAD,FOLN.BDDEPIRAD,FOLN.BDREFAD,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAIRRFESOCIAL AS BDDATAPROCAD,FOLN.BDHORAPROCAD,FOLN.BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';
    else
      WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDDATAAD,FO.BDCODVER,FO.BDVALVAD,FOLN.BDDEPIRAD,FOLN.BDREFAD,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCAD,FOLN.BDHORAPROCAD,FOLN.BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';

    wsql = wsql||'from VRHF_EMP_TADSAL FOLN join TEMPRESAS EMAT on (EMAT.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_EMP_SELECT = 1) then
       WSQL = WSQL || 'inner join TMP_EMPRESAS_SELECT TEMP on (TEMP.bdcodemp = FOLN.bdcodemp) ';

    if (WUSARTMP_COL_SELECT = 1) then
       WSQL = WSQL || 'join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FOLN.BDCODEMP and TEM.BDCODCOL = FOLN.BDCODCOL) ';

    WSQL = WSQL || 'join VRHF_EMP_TVERBAAD FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDDATAAD = FOLN.BDDATAAD) ';
    WSQL = WSQL || 'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOLN.BDREFAD ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where FOLN.BDREFIRRFESOCIAL between ' || PRREFINI || ' and ' || PRREFFIM || ' ';
    else
      WSQL = WSQL || 'where FOLN.BDREFAD >= ' || PRREFINI || ' and FOLN.BDREFAD <= ' || PRREFFIM || ' ';

    if (WUSARTMP_EMP_SELECT = 0) then
    begin
      if (PRCODEMP is not null and
          PRCODEMP <> '') then
        WSQL = WSQL || ' and ((' || REPLACE(UPPER(PRCODEMP), 'FOL.', 'FOLN.') || ')';

      if (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '') then
        WSQL = WSQL || ' or (' || REPLACE(UPPER(PRCODMATRIZ),'FOL.', 'EMAT.') || ')';

      if ((PRCODEMP is not null and
          PRCODEMP <> '') or (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '')) then
        WSQL = WSQL || ') ';
    end

    if (wusartmp_col_select = 0) then
       begin
         if (PRCODCOL is not null and PRCODCOL <> '') then
            WSQL = WSQL || ' and (' || REPLACE(UPPER(PRCODCOL), 'FOL.', 'FOLN.') || ')';
       end

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDDATAAD,FO.BDCODVER ';
    else
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDDATAAD ';
  end

  WEMPATU = 0;
  WCOLATU = 0;
  WDATAATU = null;

  WBASEIR = 0;
  WINSSN = 0;
  WIR = 0;
  WDEPATU = 0;
  WLUCROPJ = 0;
  WDESPMED = 0;
  WAJCUS = 0;
  WBOLSAESTUDOS = 0;
  WPENJUD = 0;
  WPENALIM = 0;
  WPREPRI = 0;
  WINDRESC = 0;
  WVALABO = 0;
  WRENDIS = 0;
  WDRENDIS = '';
  WDRENDIS2 = '';
  WDRENDIS3 = '';
  WDATAPROCA = null;
  WHORAPROCA = null;
  WORDEM = 0;
  WREFATU = 0;
  WTIPODEDUCAO = 0;
  WVALORDESCSIMPL = 0;
  WVALORDIFDESCSIMPL = 0;
  WTIPODEDUCAOATU = 0;
  WVALORDESCSIMPLATU = 0;
  WVALORDIFDESCSIMPLATU = 0;
  WINCIDESOCIAL = 0;
  WINCIDESOCIALFER = 0;
  WREFIRRFESOCIALATU = -1;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  BDCODFIR = 0;

  for execute statement WSQL
          into :WREFIRRFESOCIAL, :WCODEMP, :WCODCOL, :WDATA, :WCODVER, :WVALOR, :WDEP, :WREF, :WCLASSIF, :WDESCVER,
          :WDATAPROC, :WHORAPROC, :WORDEM, :WTIPODEDUCAO, :WVALORDESCSIMPL, :WVALORDIFDESCSIMPL, :WCODCLA, :WTRIBUTACAOEXTERIOR
  do
  begin
    BDCODTIPO = 272;   -- Cálculos gerados pelo Único Folha

    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end

    if (WEMPATU = 0) then
      WEMPATU = WCODEMP;

    if (WCOLATU = 0) then
      WCOLATU = WCODCOL;

    if (WDATAATU is null) then
      WDATAATU = WDATA;

    if (WREFATU = 0) then
      WREFATU = WREF;

    if ((WORDEMATU = 0) or (WORDEMATU is null)) then --173688 - João Victor - 02.02.23
      WORDEMATU = WORDEM;

    if (WVALORDESCSIMPLATU = 0) then
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
    if (WVALORDIFDESCSIMPLATU = 0) then
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
    if (WTIPODEDUCAOATU = 0) then
      WTIPODEDUCAOATU = WTIPODEDUCAO;

    if (WREFIRRFESOCIALATU = -1) then
      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;

    if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WDATA <> WDATAATU)) then
    begin
      WREFPAGTO = cast((substring(cast(WDATAATU as varchar(10)) from 1 for 4) || substring(cast(WDATAATU as varchar(10)) from 6 for 2)) as integer);

      if (WREFPAGTO >= PRREFINI and
          WREFPAGTO <= PRREFFIM) then
      begin
        WCATEGORIAESOCIAL = null;
        select first 1 BDCATEGORIAESOCIAL
        from VRHF_EMP_TCOLCON_FGTSGPS
        where BDCODEMP = :WEMPATU and
              BDCODCOL = :WCOLATU and
              BDREFCOL <= :WREFATU
        order by BDREFCOL desc
        into :WCATEGORIAESOCIAL;

        BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
        BDCODEMP = WEMPATU;
        BDCODCOL = WCOLATU;
        BDREF = WREFPAGTO;
        BDREFPAG = WREFPAGTO;
        BDRENDTRIBUTAVEL = WBASEIR;
        BDINSS = WINSSN;
        BDIR = WIR;
        BDDEP = WDEPATU;
        BDLUCROPJ = WLUCROPJ;
        BDDESPMED = WDESPMED;
        BDAJCUSTOS = WAJCUS;
        if (WCATEGORIAESOCIAL = 903) then
        begin
          BDBOLSAESTUDOS = WBOLSAESTUDOS;
          if (coalesce(WDRENDIS2, '') <> '') then
          begin
            if (coalesce(WDRENDIS, '') <> '') then
              WDRENDIS = WDRENDIS || ',';

            if (PRVEIODOTOTALIZADOR = 1) then
              WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 999);
            else
              WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 200);
          end
        end
        else
        begin
          BDAJCUSTOS = BDAJCUSTOS + WBOLSAESTUDOS;
          if (coalesce(WDRENDIS3, '') <> '') then
          begin
            if (coalesce(WDRENDIS, '') <> '') then
              WDRENDIS = WDRENDIS || ',';

            if (PRVEIODOTOTALIZADOR = 1) then
              WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 999);
            else
              WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 200);
          end
        end
        BDPENJUD = WPENJUD;
        BDPENALIM = WPENALIM;
        BDPREVPRIV = WPREPRI;
        BDINDRESC = WINDRESC;
        BDVALABO = WVALABO;
        BDRENDISENTOS = WRENDIS;
        BDDRENDISENTOS = WDRENDIS;
        BDDATAPGTO = WDATAATU;
        BDTIPO = 2; -- Adiantamento salarial
        BDINFADIC = 'Data: ' || substring(cast(WDATAATU as varchar(10)) from 9 for 2) || '/' || substring(cast(WDATAATU as varchar(10)) from 6 for 2) || '/' || substring(cast(WDATAATU as varchar(10)) from 1 for 4);
        BDDATAPROC = WDATAPROCA;
        BDHORAPROC = WHORAPROCA;
        BDORDEM = WORDEMATU; --173688 - João Victor - 02.02.23
        BDINCIDESOCIAL = WINCIDESOCIAL;
        BDINCIDESOCIALFER = WINCIDESOCIALFER;

        if (PRATUALIZAINFODESCSIMPLE = true) then
        begin
          WSQLAUX = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, ' || ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, ' || ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) ' || ' values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPAGTO || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';

          execute statement WSQLAUX;
        end
        BDTIPODEDUCAOFOLHA = WTIPODEDUCAOATU;
        BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
        BDAUXILIOMORADIA = 0;
        BDDIARIA = 0;
        BDBOLSAMEDICO = 0;
        BDJUROSMORA = 0;
        suspend;
      end

      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;
      WEMPATU = WCODEMP;
      WCOLATU = WCODCOL;
      WDATAATU = WDATA;
      WREFATU = WREF;
      WORDEMATU = WORDEM; --173688 - João Victor - 02.02.23

      WBASEIR = 0;
      WINSSN = 0;
      WIR = 0;
      WDEPATU = 0;
      WLUCROPJ = 0;
      WDESPMED = 0;
      WAJCUS = 0;
      WBOLSAESTUDOS = 0;
      WPENJUD = 0;
      WPENALIM = 0;
      WPREPRI = 0;
      WINDRESC = 0;
      WVALABO = 0;
      WRENDIS = 0;
      WDRENDIS = '';
      WTIPODEDUCAOATU = WTIPODEDUCAO;
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
      --  wordem     = 0;
      WINCIDESOCIAL = 0;
      WINCIDESOCIALFER = 0;
    end

    -- soma as bases
    WCODINCIDIRRF = 0;
    select first 1 BDTIPOCODVER, BDIRVER, BDRENDISENTOIRVER, BDCODINCIDIRRF
    from VRH_BASE_TVERBAS_REF
    where BDCODVER = :WCODVER and
          BDREFVER <= :WREFATU
    order by BDCODVER desc, BDREFVER desc
    into :WTIPOCODVER, :WIRVER, :WRENDISENTOVER, :WCODINCIDIRRF;

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end


    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
      begin
        WIRVER = 0;
      end
    else
    --    if (wtipocodver <= 1) then
    begin
      if (WIRVER = 1) then -- IR Folha normal
      begin
        if (WTIPOCODVER = 0) then -- provento
          WBASEIR = WBASEIR + WVALOR;
        else
        if (WTIPOCODVER = 1) then -- desconto
        begin
          --                                      INSS                                              Obrigações IR
          if (substring(WCLASSIF from 1 for 7) <> '9.010.0' and
              substring(WCLASSIF from 1 for 7) <> '2.001.1' and
              substring(WCLASSIF from 1 for 7) <> '2.002.1') then
            WBASEIR = WBASEIR - WVALOR;
        end
      end

       --                                     IR
       if (substring(WCLASSIF from 1 for 7) = '9.010.1') then
         WIR = WIR + WVALOR;
    end

      --                                     Lucro pessoa jurídica
      if (substring(WCLASSIF from 1 for 9) = '0.040.0.2') then
        WLUCROPJ = WLUCROPJ + WVALOR;
      --                                     Despesas médicas                                     Complemento de despesas médicas
      if ((substring(WCLASSIF from 1 for 9) = '0.030.1.0') or (substring(WCLASSIF from 1 for 9) = '0.420.0.2')) then
        WDESPMED = WDESPMED + WVALOR;
      --                                     Lucro pessoa jurídica
      if (substring(WCLASSIF from 1 for 9) = '0.040.0.2') then
        WLUCROPJ = WLUCROPJ + WVALOR;
      --                                     Ajuda de custos
      if (substring(WCLASSIF from 1 for 9) = '0.040.0.1') then
      begin
        WRUBRICA = null;
        select first 1 BDCHAVE
        from VRH_BASE_TRUBRICAESOCIAL_VER
        where BDCODVER = :WCODVER
        into :WRUBRICA;
        if (WRUBRICA = 1350) then -- Bolsa estudos
        begin
          WBOLSAESTUDOS = WBOLSAESTUDOS + WVALOR;
          if (WDRENDIS2 <> '') then
            WDRENDIS2 = WDRENDIS2 || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS2 = substring(WDRENDIS2 || 'Bolsa de estudos' from 1 for 999);
          else
            WDRENDIS2 = substring(WDRENDIS2 || 'Bolsa de estudos' from 1 for 200);

          if (WDRENDIS3 <> '') then
            WDRENDIS3 = WDRENDIS3 || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS3 = substring(WDRENDIS3 || WDESCVER from 1 for 999);
          else
            WDRENDIS3 = substring(WDRENDIS3 || WDESCVER from 1 for 200);
        end
        else
          WAJCUS = WAJCUS + WVALOR;
      end
      --                                     Pensões judiciais
      if ((substring(WCLASSIF from 1 for 9) = '2.001.1.0') or (substring(WCLASSIF from 1 for 9) = '2.002.1.0')) then
        WPENJUD = WPENJUD + WVALOR;
      --                                     Pensões alimentícias
      if ((substring(WCLASSIF from 1 for 9) = '2.001.1.1') or (substring(WCLASSIF from 1 for 9) = '2.002.1.1')) then
        WPENALIM = WPENALIM + WVALOR;
      --                                     Previdência privada
      if (substring(WCLASSIF from 1 for 9) = '0.030.1.2') then
        WPREPRI = WPREPRI + WVALOR;
      -- Rendimentos isentos
      if (upper(WRENDISENTOVER) = 'TRUE') then
      begin
        WRENDIS = WRENDIS + WVALOR;

        if (PRVEIODOTOTALIZADOR = 1) then
          WDRENDIS = substring(WDRENDIS || WDESCVER from 1 for 999);
        else
          WDRENDIS = substring(WDRENDIS || WDESCVER from 1 for 200);
      end

      if (coalesce(WCODINCIDIRRF, 0) in (11, 12, 14, 41, 42, 51, 52, 54)) then
        WINCIDESOCIAL = 1;

      if (coalesce(WCODINCIDIRRF, 0) in (13, 43, 53)) then
        WINCIDESOCIALFER = 1;
    end

    WDEPATU = WDEP;
    WDATAPROCA = WDATAPROC;
    WHORAPROCA = WHORAPROC;

  if (WEMPATU <> 0 and
      WCOLATU <> 0 and
      WDATAATU is not null) then
  begin
    WREFPAGTO = cast((substring(cast(WDATAATU as varchar(10)) from 1 for 4) || substring(cast(WDATAATU as varchar(10)) from 6 for 2)) as integer);

    if (WREFPAGTO >= PRREFINI and
        WREFPAGTO <= PRREFFIM) then
    begin
      select first 1 BDCATEGORIAESOCIAL
      from VRHF_EMP_TCOLCON_FGTSGPS
      where BDCODEMP = :WEMPATU and
            BDCODCOL = :WCOLATU and
            BDREFCOL <= :WREFATU
      order by BDREFCOL desc
      into :WCATEGORIAESOCIAL;

      BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
      BDCODEMP = WEMPATU;
      BDCODCOL = WCOLATU;
      BDREF = WREFPAGTO;
      BDREFPAG = WREFPAGTO;
      BDRENDTRIBUTAVEL = WBASEIR;
      BDINSS = WINSSN;
      BDIR = WIR;
      BDDEP = WDEPATU;
      BDLUCROPJ = WLUCROPJ;
      BDDESPMED = WDESPMED;
      BDAJCUSTOS = WAJCUS;
      if (WCATEGORIAESOCIAL = 903) then
      begin
        BDBOLSAESTUDOS = WBOLSAESTUDOS;
        if (coalesce(WDRENDIS2, '') <> '') then
        begin
          if (coalesce(WDRENDIS, '') <> '') then
            WDRENDIS = WDRENDIS || ',';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 999);
          else
            WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 200);
        end
      end
      else
      begin
        BDAJCUSTOS = BDAJCUSTOS + WBOLSAESTUDOS;
        if (coalesce(WDRENDIS3, '') <> '') then
        begin
          if (coalesce(WDRENDIS, '') <> '') then
            WDRENDIS = WDRENDIS || ',';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 999);
          else
            WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 200);
        end
      end
      BDPENJUD = WPENJUD;
      BDPENALIM = WPENALIM;
      BDPREVPRIV = WPREPRI;
      BDINDRESC = WINDRESC;
      BDVALABO = WVALABO;
      BDRENDISENTOS = WRENDIS;
      BDDRENDISENTOS = WDRENDIS;
      BDDATAPGTO = WDATAATU;
      BDTIPO = 2; -- Adiantamento salarial
      BDINFADIC = 'Data: ' || substring(cast(WDATAATU as varchar(10)) from 9 for 2) || '/' || substring(cast(WDATAATU as varchar(10)) from 6 for 2) || '/' || substring(cast(WDATAATU as varchar(10)) from 1 for 4);
      BDDATAPROC = WDATAPROCA;
      BDHORAPROC = WHORAPROCA;
      BDORDEM = WORDEM;
      BDINCIDESOCIAL = WINCIDESOCIAL;
      BDINCIDESOCIALFER = WINCIDESOCIALFER;

      if (PRATUALIZAINFODESCSIMPLE = true) then
      begin
        WSQLAUX = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, ' || ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, ' || ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) ' || ' values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPAGTO || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';

        execute statement WSQLAUX;
      end
      BDTIPODEDUCAOFOLHA = WTIPODEDUCAO;
      BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
      BDAUXILIOMORADIA = 0;
      BDDIARIA = 0;
      BDBOLSAMEDICO = 0;
      BDJUROSMORA = 0;
      suspend;
    end
  end

  /*
      DADOS IMPORTADOS OU CADASTRADOS NA FICHA
  */

  if (PRPUXARFILIAIS = 0) then
  begin
    WSQL = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),' || 'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,' || 'FOL.BDDATAFIR, ''' || ''' BDAUX, null BDORDEM, COALESCE(fol.BDAUXILIOMORADIAFIR,0), COALESCE(fol.BDDIARIAFIR,0), COALESCE(fol.BDBOLSAMEDICOFIR,0), COALESCE(fol.BDJUROSMORAFIR,0), fol.BDCODFIR, FOL.BDDEMDEV, COALESCE(FOL.BDCODTIPO, 201) BDCODTIPO ';
    WSQL = WSQL || 'from VRHF_EMP_TFICHAIRRF FOL ';

    if (WUSARTMP_EMP_SELECT = 1) then
      WSQL = WSQL || ' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

    if (WUSARTMP_COL_SELECT = 1) then
      WSQL = WSQL || 'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

    WSQL = WSQL || 'where FOL.BDTIPOCALCFIR = 9020 and FOL.BDREFIRFIR >= ' || PRREFINI || ' and FOL.BDREFIRFIR <= ' || PRREFFIM || ' and ' || 'not exists (select AD.BDCODEMP,AD.BDCODCOL,AD.BDDATAAD from VRHF_EMP_TADSAL AD where AD.BDCODEMP = FOL.BDCODEMP and AD.BDCODCOL = FOL.BDCODCOL and ' || 'AD.BDDATAAD = FOL.BDDATAFIR) ';

    if (PRCODEMP is not null and
        PRCODEMP <> '' and
        WUSARTMP_EMP_SELECT = 0) then
      WSQL = WSQL || ' and ' || PRCODEMP;

    if (PRCODCOL is not null and
        PRCODCOL <> '' and
        WUSARTMP_COL_SELECT = 0) then
      WSQL = WSQL || ' and ' || PRCODCOL;

    WSQL = WSQL || ' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDDATAFIR ';
  end
  else
  begin
    WSQL = 'select FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),' || 'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,' || 'FO.BDDATAFIR, ''' || ''' BDAUX, null BDORDEM, COALESCE(fo.BDAUXILIOMORADIAFIR,0), COALESCE(fo.BDDIARIAFIR,0), COALESCE(fo.BDBOLSAMEDICOFIR,0), COALESCE(fo.BDJUROSMORAFIR,0), fo.BDCODFIR, FO.BDDEMDEV, COALESCE(FO.BDCODTIPO, 201) BDCODTIPO ';
    wsql = wsql||'from VRHF_EMP_TFICHAIRRF FO join TEMPRESAS EMAT on (EMAT.BDCODEMP = FO.BDCODEMP) ';

    if (WUSARTMP_EMP_SELECT = 1) then
       WSQL = WSQL || 'inner join tmp_empresas_select TEMP on (TEMP.BDCODEMP = FO.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
       WSQL = WSQL || 'inner join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FO.BDCODEMP and TEM.BDCODCOL = FO.BDCODCOL) ';

    WSQL = WSQL || 'where FO.BDTIPOCALCFIR = 9020 and FO.BDREFIRFIR >= ' || PRREFINI || ' and FO.BDREFIRFIR <= ' || PRREFFIM || ' and ' || 'not exists (select AD.BDCODEMP,AD.BDCODCOL,AD.BDDATAAD from VRHF_EMP_TADSAL AD where AD.BDCODEMP = FO.BDCODEMP and AD.BDCODCOL = FO.BDCODCOL and ' || 'AD.BDDATAAD = FO.BDDATAFIR) ';

    if (WUSARTMP_EMP_SELECT = 0) then
    begin
      if (PRCODEMP is not null and
          PRCODEMP <> '') then
        WSQL = WSQL || ' and ((' || REPLACE(UPPER(PRCODEMP), 'FOL.', 'FO.') || ')';

      if (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '') then
        WSQL = WSQL || ' or (' || REPLACE(UPPER(PRCODMATRIZ), 'FOL.', 'EMAT.') || ')';

      if ((PRCODEMP is not null and
          PRCODEMP <> '') or (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '')) then
        WSQL = WSQL || ') ';
    end

    if (WUSARTMP_COL_SELECT = 0) then
    begin
      if (PRCODCOL is not null and PRCODCOL <> '') then
        WSQL = WSQL || ' and (' || REPLACE(UPPER(PRCODCOL), 'FOL.', 'FO.') || ')';
    end

    WSQL = WSQL || ' order by FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDDATAFIR ';
  end

  for execute statement WSQL
          into :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR, :BDDEP, :BDLUCROPJ,
          :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM, :BDPREVPRIV, :BDINDRESC, :BDVALABO, :BDRENDISENTOS,
          :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDORDEM, :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO,
          :BDJUROSMORA, :BDCODFIR, :BDDEMDEV, :BDCODTIPO
  do
  begin
    BDDATAPROC = BDDATAPGTO;
    BDHORAPROC = '00:00:00';
    BDREFIRRFESOCIAL = BDREFPAG;

    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
        begin
          BDRENDTRIBUTAVEL = 0;
          BDIR = 0;
        end      --                                     IR

    if (coalesce(BDRENDTRIBUTAVEL, 0) <> 0) then
      BDINCIDESOCIAL = 1;

    suspend;
  end
end^

/* Restore proc. body: SP_VRHF_DADOS_IR_C13 */
create or alter procedure SP_VRHF_DADOS_IR_C13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVERCALCRRA integer = 0,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDVERCALCRRA integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WDESCVER varchar(40);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR13 numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSS13 numeric(18,6);
declare variable WIR13 numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WINDRESC13 numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(999);
declare variable WREFC13 integer;
declare variable WREFC13ATU integer;
declare variable WREFINI integer;
declare variable WDATA date;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WTIPODEDUCAO integer;
declare variable WVALORDESCSIMPL numeric(18,2);
declare variable WVALORDIFDESCSIMPL numeric(18,2);
declare variable WSQLAUX varchar(3000);
declare variable WTIPODEDUCAOATU integer;
declare variable WVALORDESCSIMPLATU numeric(18,2);
declare variable WVALORDIFDESCSIMPLATU numeric(18,2);
declare variable WREFPGTOAUX integer;
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WGRAVARUBRICA integer;
BEGIN
  /*
      COMPLEMENTO DE 13º SALÁRIO
  */

  BDBOLSAESTUDOS = 0;
  BDCODFIR = 0;
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  IF (UPPER(prcodcol) = 'TEMP_FILTRO_COLCON_REL') THEN
     WUSARTMP_COL_SELECT = 1;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) = 1) THEN
     wrefini = CAST((CAST((CAST(SUBSTRING(prrefini FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
  ELSE
  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) <= 10) THEN
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1))) AS INTEGER);
  ELSE
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2))) AS INTEGER);

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select * from (';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql ||'select FOLN.BDREFIRRFESOCIAL, 0 BDVERCALCRRA,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREF13,FOL.BDREFC13,FOL.BDCODVER,FOL.BDVALVC13,0 BDDEP13,FOLN.BDDATAIRRFESOCIAL AS BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCC13,FOLN.BDHORAPROCC13,FOLN.BDORDEM, 0 BDTIPODEDUCAOFOLHA, 0 BDVALORDESCONTOSIMPLIFICADO, 0 BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
       ELSE
         wsql = wsql ||'select FOLN.BDREFIRRFESOCIAL, 0 BDVERCALCRRA,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREF13,FOL.BDREFC13,FOL.BDCODVER,FOL.BDVALVC13,0 BDDEP13,FOLN.BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCC13,FOLN.BDHORAPROCC13,FOLN.BDORDEM, 0 BDTIPODEDUCAOFOLHA, 0 BDVALORDESCONTOSIMPLIFICADO, 0 BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

       wsql = wsql||'from VRHF_EMP_TC13SAL FOLN ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'INNER JOIN tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FOLN.BDCODEMP) ';
       if (wusartmp_col_select = 1) then
          WSQL = WSQL||'inner JOIN TEMP_FILTRO_COLCON_REL TEM ON (TEM.BDCODEMP = FOLN.BDCODEMP AND TEM.BDCODCOL = FOLN.BDCODCOL) ';

       wsql = wsql||'join VRHF_EMP_TVERBAC13 FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDREF13 = FOLN.BDREF13 and FOL.BDREFC13 = FOLN.BDREFC13) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  ';
       if (PRIRRFESOCIAL = TRUE) THEN
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
       ELSE
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFC13 ORDER BY X.BDREFCOL DESC) ';
      
       WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'where FOLN.BDREFIRRFESOCIAL between '||wrefini||' and '||prreffim||' ';
       ELSE
         wsql = wsql||'where FOLN.BDREFC13 between '||wrefini||' and '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||' union all ';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql ||'select FOLN.BDREFIRRFESOCIAL, FOLN.BDVERCALCRRA,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN BDREF13,FOLN.BDREFCOMP BDREFC13,FOL.BDCODVER,FOL.BDVALVFC BDVALVC13,0 BDDEP13,FOLN.BDDATAIRRFESOCIAL BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER, FOLN.BDDATAPROCFC BDDATAPROCC13,FOLN.BDHORAPROCFC BDHORAPROCC13, cast(null as integer) BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
       ELSE
         wsql = wsql ||'select FOLN.BDREFIRRFESOCIAL, FOLN.BDVERCALCRRA,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN BDREF13,FOLN.BDREFCOMP BDREFC13,FOL.BDCODVER,FOL.BDVALVFC BDVALVC13,0 BDDEP13,FOLN.BDDATAPAGFC BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER, FOLN.BDDATAPROCFC BDDATAPROCC13,FOLN.BDHORAPROCFC BDHORAPROCC13, cast(null as integer) BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';

       wsql = wsql||'from VRHF_EMP_TFOLHACOMP FOLN ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'INNER JOIN tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FOLN.BDCODEMP) ';
       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'inner join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP and TEMP.BDCODCOL = FOLN.BDCODCOL) ';

       wsql = wsql||'join VRHF_EMP_TVERBAFC FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDREFFN = FOLN.BDREFFN and FOL.BDREFFC = FOLN.BDREFFC) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  ';
       if (PRIRRFESOCIAL = TRUE) THEN
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
       ELSE
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFCOMP ORDER BY X.BDREFCOL DESC) ';
      
       WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

       wsql = wsql||'where exists(select first 1 * from vrhf_emp_tverbafc fvaux '||
                                 'join vrh_base_tverbas fvver on fvver.bdcodver = fvaux.bdcodver '||
                                 'where fvaux.bdcodemp = FOLN.BDCODEMP and fvaux.bdcodcol = FOLN.BDCODCOL and fvaux.bdreffn = FOLN.BDREFFN and fvaux.bdreffc = FOLN.BDREFFC and fvver.bdclaver like ''0.601.%'') and ';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'FOLN.BDREFIRRFESOCIAL between '||wrefini||' and '||prreffim||' ';
       ELSE
         wsql = wsql||'FOLN.BDREFCOMP between '||wrefini||' and '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
          wsql = wsql||' and '||prcodcol;

       if (prvercalcrra >= 0) then
          wsql = wsql||' and COALESCE(FOLN.BDVERCALCRRA,0) = '||prvercalcrra;

       wsql = wsql||' union all ';

       wsql = wsql ||'select distinct FCTN.bdrefirrfesocial, FCTN.BDVERCALCRRA, FCT.BDCODEMP,FCT.BDCODCOL,FCT.BDREFTOMADOR BDREF13,FCTN.BDREFCOMP BDREFC13,FCT.BDCODVER,FCT.BDVALVFC BDVALVC13,0 BDDEP13,FCTN.BDDATAPAGFC BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER, FCTN.BDDATAPROCFC BDDATAPROCC13,FCTN.BDHORAPROCFC BDHORAPROCC13, cast(null as integer) BDORDEM, FCTN.BDTIPODEDUCAOFOLHA, FCTN.BDVALORDESCONTOSIMPLIFICADO, FCTN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
       wsql = wsql||'from VRHF_EMP_TFOLTOMCOMP FCTN ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'INNER JOIN tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FCTN.BDCODEMP) ';
       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FCTN.BDCODEMP and TEMP.BDCODCOL = FCTN.BDCODCOL) ';

       wsql = wsql||'join VRHF_EMP_TVERBAFCTOMADOR FCT on (FCT.BDCODEMP = FCTN.BDCODEMP and FCT.BDCODCOL = FCTN.BDCODCOL and FCT.BDREFTOMADOR = FCTN.BDREFTOMADOR and FCT.BDREFFC = FCTN.BDREFFC and FCT.BDORDEM = FCTN.BDORDEM) ';
       wsql = wsql||'join VRH_BASE_TVERBAS VER on (VER.bdcodver = FCT.bdcodver) ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FCTN.BDCODEMP) and (HIST.BDCODCOL = FCTN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FCTN.BDCODEMP) and (VINC.BDCODCOL = FCTN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FCTN.BDCODEMP and x.BDCODCOL = FCTN.BDCODCOL  ';
       if (PRIRRFESOCIAL = TRUE) THEN
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FCTN.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
       ELSE
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FCTN.BDREFCOMP ORDER BY X.BDREFCOL DESC) ';
      
       WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FCTN.BDCODEMP and x.BDCODCOL = FCTN.BDCODCOL)) ';

       wsql = wsql||'where exists(select first 1 * from VRHF_EMP_TVERBAFCTOMADOR fvaux '||
                                 'join VRH_BASE_TVERBAS fvver on fvver.bdcodver = fvaux.bdcodver '||
                                 'where fvaux.bdcodemp = FCTN.BDCODEMP and fvaux.bdcodcol = FCTN.BDCODCOL and fvaux.BDREFTOMADOR = FCTN.BDREFTOMADOR and fvaux.bdreffc = FCTN.BDREFFC and fvver.bdclaver like ''0.601.%'') and ';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'FCTN.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim||' ';
       ELSE
         wsql = wsql||'FCTN.BDREFCOMP between '||prrefini||' and '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||REPLACE(UPPER(prcodemp), 'FOL.BDCODEMP', 'FCT.BDCODEMP');
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
          wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'FOL.BDCODCOL', 'FCT.BDCODCOL');

       if (prvercalcrra >= 0) then
          wsql = wsql||' and COALESCE(FCTN.BDVERCALCRRA,0) = '||prvercalcrra;
     
       if (prveiodototalizador = 1) then
          wsql = wsql||') X order by X.BDCODEMP,X.BDCODCOL,X.BDREF13,X.BDREFC13,X.BDCODVER ';
       else
       wsql = wsql||') X order by X.BDCODEMP,X.BDCODCOL,X.BDREF13,X.BDREFC13 ';
     END
  ELSE
     BEGIN
       wsql = 'select * from (';
       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql || 'select FOLN.BDREFIRRFESOCIAL, 0 BDVERCALCRRA,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREF13,FO.BDREFC13,FO.BDCODVER,FO.BDVALVC13,0 BDDEP13,FOLN.BDDATAIRRFESOCIAL AS BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCC13,FOLN.BDHORAPROCC13,FOLN.BDORDEM, 0 BDTIPODEDUCAOFOLHA, 0 BDVALORDESCONTOSIMPLIFICADO, 0 BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
       ELSE
         wsql = wsql || 'select FOLN.BDREFIRRFESOCIAL, 0 BDVERCALCRRA,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREF13,FO.BDREFC13,FO.BDCODVER,FO.BDVALVC13,0 BDDEP13,FOLN.BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCC13,FOLN.BDHORAPROCC13,FOLN.BDORDEM, 0 BDTIPODEDUCAOFOLHA, 0 BDVALORDESCONTOSIMPLIFICADO, 0 BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

       wsql = wsql||'from VRHF_EMP_TC13SAL FOLN join TEMPRESAS EMAT on (EMAT.BDCODEMP = FOLN.BDCODEMP) ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'inner join TMP_EMPRESAS_SELECT TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP) ';

       IF (WUSARTMP_COL_SELECT = 1) THEN
          wsql = wsql||'inner join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FOLN.BDCODEMP and TEM.BDCODCOL = FOLN.BDCODCOL) ';

       wsql = wsql||'join VRHF_EMP_TVERBAC13 FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDREF13 = FOLN.BDREF13 and FO.BDREFC13 = FOLN.BDREFC13) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  ';
       if (PRIRRFESOCIAL = TRUE) THEN
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
       ELSE
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFC13 ORDER BY X.BDREFCOL DESC) ';
      
       WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'where FOLN.BDREFIRRFESOCIAL between '||wrefini||' and '||prreffim||' ';
       ELSE
         wsql = wsql||'where FOLN.BDREFC13 between '||wrefini||' and '||prreffim||' ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||REPLACE(UPPER(prcodemp), 'FOL.', 'FOLN.')||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||REPLACE(UPPER(prcodmatriz), 'FOL.', 'EMAT.')||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
          wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'FOL.', 'FOLN.')||' ';

       wsql = wsql||' union all ';

       wsql = wsql ||'select distinct FCTN.bdrefirrfesocial, FCTN.BDVERCALCRRA, FCT.BDCODEMP,FCT.BDCODCOL,FCT.BDREFTOMADOR BDREF13,FCTN.BDREFCOMP BDREFC13,FCT.BDCODVER,FCT.BDVALVFC BDVALVC13,0 BDDEP13,FCTN.BDDATAPAGFC BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER, FCTN.BDDATAPROCFC BDDATAPROCC13,FCTN.BDHORAPROCFC BDHORAPROCC13, cast(null as integer) BDORDEM, FCTN.BDTIPODEDUCAOFOLHA, FCTN.BDVALORDESCONTOSIMPLIFICADO, FCTN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
       wsql = wsql||'from VRHF_EMP_TFOLTOMCOMP FCTN join TEMPRESAS EMAT on (EMAT.BDCODEMP = FCTN.BDCODEMP) ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'INNER JOIN tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FCTN.BDCODEMP) ';
       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FCTN.BDCODEMP and TEMP.BDCODCOL = FCTN.BDCODCOL) ';

       wsql = wsql||'join VRHF_EMP_TVERBAFCTOMADOR FCT on (FCT.BDCODEMP = FCTN.BDCODEMP and FCT.BDCODCOL = FCTN.BDCODCOL and FCT.BDREFTOMADOR = FCTN.BDREFTOMADOR and FCT.BDREFFC = FCTN.BDREFFC and FCT.BDORDEM = FCTN.BDORDEM) ';
       wsql = wsql||'join VRH_BASE_TVERBAS VER on (VER.bdcodver = FCT.bdcodver) ';

       WSQL = WSQL||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FCTN.BDCODEMP) and (HIST.BDCODCOL = FCTN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FCTN.BDCODEMP) and (VINC.BDCODCOL = FCTN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FCTN.BDCODEMP and x.BDCODCOL = FCTN.BDCODCOL  ';
       if (PRIRRFESOCIAL = TRUE) THEN
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FCTN.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
       ELSE
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FCTN.BDREFCOMP ORDER BY X.BDREFCOL DESC) ';
      
       WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FCTN.BDCODEMP and x.BDCODCOL = FCTN.BDCODCOL)) ';

       wsql = wsql||'where exists(select first 1 * from VRHF_EMP_TVERBAFCTOMADOR fvaux '||
                                 'join VRH_BASE_TVERBAS fvver on fvver.bdcodver = fvaux.bdcodver '||
                                 'where fvaux.bdcodemp = FCTN.BDCODEMP and fvaux.bdcodcol = FCTN.BDCODCOL and fvaux.BDREFTOMADOR = FCTN.BDREFTOMADOR and fvaux.bdreffc = FCTN.BDREFFC and fvver.bdclaver like ''0.601.%'') and ';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'FCTN.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim||' ';
       ELSE
         wsql = wsql||'FCTN.BDREFCOMP between '||prrefini||' and '||prreffim||' ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||REPLACE(UPPER(prcodemp), 'FOL.', 'FCTN.')||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||REPLACE(UPPER(prcodmatriz), 'FOL.', 'EMAT.')||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
          wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'FOL.', 'FCTN.')||' ';

       if (prveiodototalizador = 1) then
          wsql = wsql||') X order by X.BDCODEMP,X.BDCODCOL,X.BDREF13,X.BDREFC13,X.BDCODVER ';
       else
          wsql = wsql||') X order by X.BDCODEMP,X.BDCODCOL,X.BDREF13,X.BDREFC13 ';

     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wrefc13atu = 0;
  wordematu  = 0;

  wbaseir13  = 0;
  winss13    = 0;
  wir13      = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc13 = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;
  wordem     = 0;
  wtipodeducao = 0;
  wvalordescsimpl = 0;
  wvalordifdescsimpl = 0;
  wtipodeducaoatu = 0;
  wvalordescsimplatu = 0;
  wvalordifdescsimplatu = 0;
  WBOLSAMEDICO = 0;
  WINCIDESOCIAL = 0;
  WCODINCIDIRRF = 0;
  wrefirrfesocialatu = -1;

  FOR EXECUTE STATEMENT wsql INTO :wrefirrfesocial, :BDVERCALCRRA, :wcodemp,:wcodcol,:wref,:wrefc13,:wcodver,:wvalor,:wdep,:wdata,:wclassif,:wdescver,:wdataproc,:whoraproc,:wordem,:wtipodeducao,:wvalordescsimpl,:wvalordifdescsimpl, :wcodcla,  :wtributacaoexterior DO
  BEGIN
    BDCODTIPO = 272;    -- Cálculos gerados pelo Único Folha

    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end

    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wrefatu = 0) THEN
       wrefatu = wref;

    IF (wrefc13atu = 0) THEN
       wrefc13atu = wrefc13;

    if (wrefirrfesocialatu= -1) then wrefirrfesocialatu = wrefirrfesocial;

    if (wvalordescsimplatu = 0) then
      wvalordescsimplatu = wvalordescsimpl;
    if (wvalordifdescsimplatu = 0) then
      wvalordifdescsimplatu = wvalordifdescsimpl;
    if (wtipodeducaoatu = 0) then
      wtipodeducaoatu = wtipodeducao;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wrefc13 <> wrefc13atu)) THEN
       BEGIN
         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

         IF ((wrefpagto >= prrefini AND wrefpagto <= prreffim) and
             ((wbaseir13 <> 0) or (winss13 <> 0) or (wir13 <> 0) or (wlucropj <> 0) or (wdespmed <> 0) or (wajcus <> 0) or
              (wpenjud <> 0) or (wpenalim <> 0) or (wprepri <> 0) or (windresc13 <> 0) or (wvalabo <> 0) or (wrendis <> 0) or (prveiodototalizador = 1))) THEN
            BEGIN
              bdrefirrfesocial = wrefirrfesocialatu;
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir13;
              BDINSS           = winss13;
              BDIR             = wir13;
              BDDEP            = wdepatu;
              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;
              BDPREVPRIV       = wprepri;
              BDINDRESC        = windresc13;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDTIPO           = 11;    -- Complemento 13º salário
              BDINFADIC        = '';
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;
              BDORDEM          = wordematu;

              if (pratualizainfodescsimple = TRUE) then
                begin
                  wrefpgtoaux = CAST((SUBSTRING(wrefpagto FROM 1 FOR 4)||'13')AS INTEGER);
                  wsqlaux = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, '||
                            ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, '||
                            ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) '||
                            ' values ('||current_connection||', '||wempatu||', '||wcolatu||', '||wrefpgtoaux||', 0, '||coalesce(bdpenalim, 0)||', '||coalesce(bddep, 0)||', '||coalesce(bdprevpriv, 0)||', '||coalesce(bdinss, 0)||', '||coalesce(wvalordescsimplatu, 0)||', FALSE, '||coalesce(bdrendtributavel, 0)||')';
          
                  execute statement wsqlaux;
                end

              BDVALORDESCONTOSIMPLIFICADO = wvalordescsimplatu;
              BDAUXILIOMORADIA = 0;
              BDDIARIA = 0;
              BDBOLSAMEDICO = WBOLSAMEDICO;
              BDJUROSMORA = 0;
              BDINCIDESOCIAL = WINCIDESOCIAL;
              SUSPEND;
            END

         wrefirrfesocialatu = wrefirrfesocial;
         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wrefatu    = wref;
         wrefc13atu = wrefc13;
         wordematu  = wordem;

         wbaseir13  = 0;
         winss13    = 0;
         wir13      = 0;
         wdepatu    = 0;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc13 = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
         wordem     = 0;
         wtipodeducaoatu = wtipodeducao;
         wvalordescsimplatu = wvalordescsimpl;
         wvalordifdescsimplatu = wvalordifdescsimpl;
         WBOLSAMEDICO = 0;
         WINCIDESOCIAL = 0;
       END

    -- soma as bases
    WCODINCIDIRRF = 0;
    SELECT first 1 BDTIPOCODVER, BDIRVER, BDRENDISENTOIRVER, BDCODINCIDIRRF
    FROM VRH_BASE_TVERBAS_REF
    WHERE BDCODVER = :wcodver and BDREFVER <= :wrefatu
    order by BDCODVER desc, BDREFVER DESC
    INTO :wtipocodver,:wirver,:wrendisentover,:WCODINCIDIRRF;

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end



    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
      begin
        WIRVER = 0;
      end
    else
--    if (wtipocodver <= 1) then
       begin
         IF (wirver = 3) THEN -- 13º salário
            BEGIN
              IF (wtipocodver = 0) THEN   -- provento
                 wbaseir13 = wbaseir13 + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN   -- desconto
                 BEGIN
                   --                                      INSS                                              Obrigações IR
                   IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030' AND SUBSTRING(wclassif FROM 1 FOR 7) <> '6.001.8') THEN
                      wbaseir13 = wbaseir13 - wvalor;
                 END
            END

         -- Desconto de 13º salário
         IF ((SUBSTRING(wclassif FROM 1 FOR 5) = '6.080') and (:WCODINCIDIRRF = 12) and (wtipocodver <= 1)) THEN
            wbaseir13 = wbaseir13 - wvalor;
         --                                     IR
         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.4') or (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.A')) THEN
            wir13 = wir13 + wvalor;
       end

         --                                     INSS
         IF ((SUBSTRING(wclassif FROM 1 FOR 7) = '9.010.0') and (wirver = 3)) THEN
            winss13 = winss13 + wvalor;
         --                                     Pensões judiciais
         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '6.001.8.0') and (wirver = 3)) THEN
            wpenjud = wpenjud + wvalor;
         --                                     Pensões alimentícias
         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '6.001.8.1') and (wirver = 3)) THEN
            wpenalim = wpenalim + wvalor;
         --                                     Previdência privada
         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '6.001.8.2') and (wirver = 3)) THEN
            wprepri = wprepri + wvalor;
         --                                     Previdência complementar 160514 LuizCovre 05/07/2022
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '6.009.0.0') THEN
            wprepri = wprepri + wvalor;
         -- Rendimentos isentos
         IF ((UPPER(wrendisentover) = 'TRUE') and ((SUBSTRING(wclassif FROM 1 FOR 7) = '0.601.0') or ((SUBSTRING(wclassif FROM 1 FOR 7) = '6.001.0')))) THEN  -- Sol. 133983 | Michel Luciano | Data 25/02/2020.
            BEGIN
              wrendis = wrendis + wvalor;

              if (prveiodototalizador = 1) then
                 wdrendis = SUBSTRING(wdrendis||wdescver FROM 1 FOR 999);
              else
              wdrendis = SUBSTRING(wdrendis||wdescver FROM 1 FOR 200);
            END
         --
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '6.620.0.0') THEN
            WBOLSAMEDICO = WBOLSAMEDICO + WVALOR;

         if (COALESCE(WCODINCIDIRRF, 0) IN (11,12,13,14,41,42,43,51,52,53,54)) then
            WINCIDESOCIAL = 1;

    wdepatu = wdep;
    wdataatu = wdata;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
  END

  IF ((wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wrefc13atu <> 0) AND
      ((wbaseir13 <> 0) or (winss13 <> 0) or (wir13 <> 0) or (wlucropj <> 0) or (wdespmed <> 0) or (wajcus <> 0) or
       (wpenjud <> 0) or (wpenalim <> 0) or (wprepri <> 0) or (windresc13 <> 0) or (wvalabo <> 0) or (wrendis <> 0) or (prveiodototalizador = 1))) THEN
     BEGIN
       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            bdrefirrfesocial = wrefirrfesocialatu;
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir13;
            BDINSS           = winss13;
            BDIR             = wir13;
            BDDEP            = wdepatu;
            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;
            BDPREVPRIV       = wprepri;
            BDINDRESC        = windresc13;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 11;    -- Complemento 13º salário
            BDINFADIC        = '';
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            BDORDEM          = wordematu;

            if (pratualizainfodescsimple = TRUE) then
              begin
                wrefpgtoaux = CAST((SUBSTRING(wrefpagto FROM 1 FOR 4)||'13')AS INTEGER);
                wsqlaux = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, '||
                          ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, '||
                          ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) '||
                          ' values ('||current_connection||', '||wempatu||', '||wcolatu||', '||wrefpgtoaux||', 0, '||coalesce(bdpenalim, 0)||', '||coalesce(bddep, 0)||', '||coalesce(bdprevpriv, 0)||', '||coalesce(bdinss, 0)||', '||coalesce(wvalordescsimplatu, 0)||', FALSE, '||coalesce(bdrendtributavel, 0)||')';
        
                execute statement wsqlaux;
              end

            BDVALORDESCONTOSIMPLIFICADO = wvalordescsimplatu;
            BDAUXILIOMORADIA = 0;
            BDDIARIA = 0;
            BDBOLSAMEDICO = WBOLSAMEDICO;
            BDJUROSMORA = 0;
            BDINCIDESOCIAL = WINCIDESOCIAL;
            SUSPEND;
          END
     END

  /*
      DADOS IMPORTADOS OU CADASTRADOS NA FICHA
  */
  BDVERCALCRRA = 0;
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),'||
              'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,'||
              'FOL.BDDATAFIR, '''||''' BDAUX, fol.BDVALORDESCONTOSIMPLIFICADO, COALESCE(fol.BDAUXILIOMORADIAFIR,0), COALESCE(fol.BDDIARIAFIR,0), COALESCE(fol.BDBOLSAMEDICOFIR,0), COALESCE(fol.BDJUROSMORAFIR,0), fol.BDCODFIR, FOL.BDDEMDEV, COALESCE(FOL.BDCODTIPO, 201) BDCODTIPO,'||
              'VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

       WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOL.BDCODEMP) and (HIST.BDCODCOL = FOL.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOL.BDCODEMP) and (VINC.BDCODCOL = FOL.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL  '||
                    '                                     AND X.BDREFCOL <= FOL.BDREFFIR ORDER BY X.BDREFCOL DESC) '||
                    '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL)) ';

       wsql = wsql||'where FOL.BDTIPOCALCFIR = 9110 and FOL.BDREFIRFIR >= '||prrefini||
              ' and FOL.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select C13.BDCODEMP,C13.BDCODCOL,C13.BDREF13,C13.BDREFC13 from VRHF_EMP_TC13SAL C13 where C13.BDCODEMP = FOL.BDCODEMP and C13.BDCODCOL = FOL.BDCODCOL and '||
                                'C13.BDREF13 = FOL.BDREFFIR) ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDDATAFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX, fo.BDVALORDESCONTOSIMPLIFICADO, COALESCE(fo.BDAUXILIOMORADIAFIR,0), COALESCE(fo.BDDIARIAFIR,0), COALESCE(fo.BDBOLSAMEDICOFIR,0), COALESCE(fo.BDJUROSMORAFIR,0), fo.BDCODFIR, FO.BDDEMDEV, COALESCE(FO.BDCODTIPO, 201) BDCODTIPO,'||
              'VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FO join TEMPRESAS EMAT on (EMAT.BDCODEMP = FO.BDCODEMP) ';
       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wsql = wsql||'inner join tmp_empresas_select TEMP on (TEMP.BDCODEMP = FO.BDCODEMP) ';

       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'inner join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FO.BDCODEMP and TEM.BDCODCOL = FO.BDCODCOL) ';

       WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FO.BDCODEMP) and (HIST.BDCODCOL = FO.BDCODCOL)  ';
       WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FO.BDCODEMP) and (VINC.BDCODCOL = FO.BDCODCOL)  '||
                      '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                      '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL  '||
                      '                                     AND X.BDREFCOL <= FO.BDREFFIR ORDER BY X.BDREFCOL DESC) '||
                      '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                      '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL)) ';

       wsql = wsql||'where FO.BDTIPOCALCFIR = 9110 and FO.BDREFIRFIR >= '||prrefini||
              ' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select C13.BDCODEMP,C13.BDCODCOL,C13.BDREF13,C13.BDREFC13 from VRHF_EMP_TC13SAL C13 where C13.BDCODEMP = FO.BDCODEMP and C13.BDCODCOL = FO.BDCODCOL and '||
                                'C13.BDREF13 = FO.BDREFFIR) ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||REPLACE(UPPER(prcodemp), 'FOL.', 'FO.')||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||REPLACE(UPPER(prcodmatriz), 'FOL.', 'EMAT.')||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
          wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'FOL.', 'FO.')||' ';

       wsql = wsql||' order by FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDDATAFIR ';
     END

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC,
    :BDVALORDESCONTOSIMPLIFICADO,
    :BDAUXILIOMORADIA,
    :BDDIARIA,
    :BDBOLSAMEDICO,
    :BDJUROSMORA,
    :BDCODFIR,
    :BDDEMDEV,
    :BDCODTIPO,
    :WCODCLA,
    :WTRIBUTACAOEXTERIOR
  DO
  BEGIN
    BDDATAPROC  = BDDATAPGTO;
    BDHORAPROC  = '00:00:00';

    bdrefirrfesocial = bdrefpag;

    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
    begin
        BDRENDTRIBUTAVEL = 0;
        BDIR = 0;
    end

    if (pratualizainfodescsimple = TRUE) then
      begin
        wsqlaux = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, '||
                  ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, '||
                  ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) '||
                  ' values ('||current_connection||', '||:BDCODEMP||', '||:BDCODCOL||', '||:BDREFPAG||', 0, '||coalesce(:BDPENALIM, 0)||', '||coalesce(:BDDEP, 0)||', '||coalesce(:BDPREVPRIV, 0)||', '||coalesce(:BDINSS, 0)||', '||coalesce(:BDVALORDESCONTOSIMPLIFICADO, 0)||', FALSE, '||coalesce(:BDRENDTRIBUTAVEL, 0)||')';
        
        execute statement wsqlaux;
      end

    if (COALESCE(BDRENDTRIBUTAVEL, 0) <> 0) then
       BDINCIDESOCIAL = 1;

    SUSPEND;
  END
END^

/* Restore proc. body: SP_VRHF_DADOS_IR_DARF */
create or alter procedure SP_VRHF_DADOS_IR_DARF (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '',
    PRPORCC smallint = 0,
    PRSEMPLR smallint = 0,
    PRIRRFESOCIAL boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFIR integer,
    BDREFIRFIR integer,
    BDTIPOCALCFIR integer,
    BDCCFIR integer,
    BDCODFERFIR integer,
    BDCODTCA integer,
    BDBASEIRFIR numeric(18,6),
    BDVALINSSFIR numeric(18,6),
    BDVALIRFIR numeric(18,6),
    BDVALDEPFIR numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDDATAFIR date)
as
declare variable WEMP varchar(20000);
declare variable WCOL varchar(30000);
declare variable WMAT varchar(15000);
declare variable WSQL varchar(10000);
declare variable WREF integer;
BEGIN
  SELECT CAST(TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) AS INTEGER) FROM rdb$database INTO wref;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wemp = ''''||prcodemp||'''';
  ELSE
     wemp = 'null';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wcol = ''''||prcodcol||'''';
  ELSE
     wcol = 'null';

  IF (prpuxarfiliais = 1) THEN
     wmat = ''''||prcodmatriz||'''';
  ELSE
     wmat = 'null';

  -- Folha normal
  wsql = 'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,coalesce(bdordem,0),0,0,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO '||
                'from SP_VRHF_DADOS_IR_FN('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||',0,0,'||prporcc||','||PRIRRFESOCIAL||') ' ;
  -- Folha complementar
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,coalesce(bdordem,0),0,0,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO '||
                'from SP_VRHF_DADOS_IR_FC('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||',0,0,'||prporcc||','||PRIRRFESOCIAL||') ' ;
  -- Adiantamento salarial
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,0,0,0,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO '||
                'from SP_VRHF_DADOS_IR_AD('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||','||PRIRRFESOCIAL||') ' ;
  -- Férias
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,0,BDCODFE,0,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO '||
                'from SP_VRHF_DADOS_IR_FE('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||', 0,'||PRIRRFESOCIAL||') ' ;
  -- 13º salário
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,coalesce(bdordem,0),0,0,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO '||
                'from SP_VRHF_DADOS_IR_13('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||','||PRIRRFESOCIAL||') ' ;

  -- Complemento de 13º salário
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,0,0,0,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO '||
                'from SP_VRHF_DADOS_IR_C13('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||','||PRIRRFESOCIAL||') ' ;

  -- Folha avulsa
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,0,0,BDCODTCA,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO '||
                'from SP_VRHF_DADOS_IR_FA('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||', 0, '||prsemplr||','||PRIRRFESOCIAL||') ' ;

  -- Folha intermitente
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,coalesce(bdordem, 0) bdordem,0,0,SUM(BDRENDTRIBUTAVEL),SUM(BDINSS),SUM(BDIR),MAX(BDDEP),SUM(BDPENJUD),SUM(BDPENALIM),MAX(BDDATAPGTO) '||
                'from SP_VRHF_DADOS_IR_INT('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||', 0, 0, 1,'||PRIRRFESOCIAL||') '||
                'group by BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,bdordem ';

  -- Folha intermitente complementar
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,coalesce(bdordem, 0) bdordem,0,0,SUM(BDRENDTRIBUTAVEL),SUM(BDINSS),SUM(BDIR),MAX(BDDEP),SUM(BDPENJUD),SUM(BDPENALIM),MAX(BDDATAPGTO) '||
                'from SP_VRHF_DADOS_IR_FC_INT('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||', 0, 0, 0,'||PRIRRFESOCIAL||') '||
                'group by BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,bdordem ';

  -- Folha intermitente 13º
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,coalesce(bdordem, 0) bdordem,0,0,SUM(BDRENDTRIBUTAVEL),SUM(BDINSS),SUM(BDIR),MAX(BDDEP),SUM(BDPENJUD),SUM(BDPENALIM),MAX(BDDATAPGTO) '||
                'from SP_VRHF_DADOS_IR_INT13('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||', 1,'||PRIRRFESOCIAL||') '||
                'group by BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,bdordem ';

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFFIR,
    :BDREFIRFIR,
    :BDTIPOCALCFIR,
    :BDCCFIR,
    :BDCODFERFIR,
    :BDCODTCA,
    :BDBASEIRFIR,
    :BDVALINSSFIR,
    :BDVALIRFIR,
    :BDVALDEPFIR,
    :BDPENJUD,
    :BDPENALIM,
    :BDDATAFIR
  DO
    SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
END^

/* Restore proc. body: SP_VRHF_DADOS_IR_C13_ESOCIAL */
create or alter procedure SP_VRHF_DADOS_IR_C13_ESOCIAL (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVERCALCRRA integer = -1)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDVERCALCRRA integer)
as
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WDESCVER varchar(40);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR13 numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSS13 numeric(18,6);
declare variable WIR13 numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WINDRESC13 numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(200);
declare variable WREFC13 integer;
declare variable WREFC13ATU integer;
declare variable WREFINI integer;
declare variable WDATA date;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WTIPODEDUCAO integer;
declare variable WVALORDESCSIMPL numeric(18,2);
declare variable WVALORDIFDESCSIMPL numeric(18,2);
declare variable WSQLAUX varchar(3000);
declare variable WTIPODEDUCAOATU integer;
declare variable WVALORDESCSIMPLATU numeric(18,2);
declare variable WVALORDIFDESCSIMPLATU numeric(18,2);
declare variable WREFPGTOAUX integer;
BEGIN
  /*
      COMPLEMENTO DE 13º SALÁRIO
  */

  BDBOLSAESTUDOS = 0;
  WUSARTMP_EMP_SELECT = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) = 1) THEN
     wrefini = CAST((CAST((CAST(SUBSTRING(prrefini FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
  ELSE
  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) <= 10) THEN
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1))) AS INTEGER);
  ELSE
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2))) AS INTEGER);

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select * from (';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql ||'select 0 BDVERCALCRRA,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREF13,FOL.BDREFC13,FOL.BDCODVER,FOL.BDVALVC13,0 BDDEP13,FOLN.BDDATAIRRFESOCIAL AS BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCC13,FOLN.BDHORAPROCC13,FOLN.BDORDEM, 0 BDTIPODEDUCAOFOLHA, 0 BDVALORDESCONTOSIMPLIFICADO, 0 BDVALORDIFERENCADEDUCOES ';
       ELSE
         wsql = wsql ||'select 0 BDVERCALCRRA,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREF13,FOL.BDREFC13,FOL.BDCODVER,FOL.BDVALVC13,0 BDDEP13,FOLN.BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCC13,FOLN.BDHORAPROCC13,FOLN.BDORDEM, 0 BDTIPODEDUCAOFOLHA, 0 BDVALORDESCONTOSIMPLIFICADO, 0 BDVALORDIFERENCADEDUCOES ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREF13, VFN.BDREFC13, VFN.bdcodver, VFN.BDVALVC13 FROM vrhf_emp_tverbac13 VFN INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
       ELSE
          wSQL = wSQL||'from vrhf_emp_tverbac13 FOL ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tc13sal FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREF13 = FOL.BDREF13 and FOLN.BDREFC13 = FOL.BDREFC13) ';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'where FOLN.BDREFIRRFESOCIAL between '||wrefini||' and '||prreffim||' ';
       ELSE
         wsql = wsql||'where FOL.BDREFC13 between '||wrefini||' and '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||' union all ';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql ||'select FOLN.BDVERCALCRRA,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN BDREF13,FOLN.BDREFCOMP BDREFC13,FOL.BDCODVER,FOL.BDVALVFC BDVALVC13,0 BDDEP13,FOLN.BDDATAIRRFESOCIAL BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER, FOLN.BDDATAPROCFC BDDATAPROCC13,FOLN.BDHORAPROCFC BDHORAPROCC13, cast(null as integer) BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES ';
       ELSE
         wsql = wsql ||'select FOLN.BDVERCALCRRA,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN BDREF13,FOLN.BDREFCOMP BDREFC13,FOL.BDCODVER,FOL.BDVALVFC BDVALVC13,0 BDDEP13,FOLN.BDDATAPAGFC BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER, FOLN.BDDATAPROCFC BDDATAPROCC13,FOLN.BDHORAPROCFC BDHORAPROCC13, cast(null as integer) BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN                                                                                                                          
             wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREFFN, VFN.BDREFFC, VFN.bdcodver, VFN.BDVALVFC FROM vrhf_emp_tverbafc VFN '||
                                  'INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
          END
       ELSE
         wsql = wsql||'from vrhf_emp_tverbafc FOL ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhacomp FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFFN = FOL.BDREFFN and FOLN.BDREFFC = FOL.BDREFFC) ';
       wsql = wsql||'where exists(select first 1 * from vrhf_emp_tverbafc fvaux '||
                                 'join vrh_base_tverbas fvver on fvver.bdcodver = fvaux.bdcodver '||
                                 'where fvaux.bdcodemp = FOLN.BDCODEMP and fvaux.bdcodcol = FOLN.BDCODCOL and fvaux.bdreffn = FOLN.BDREFFN and fvaux.bdreffc = FOLN.BDREFFC and fvver.bdclaver like ''0.601.%'') and ';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'FOLN.BDREFIRRFESOCIAL between '||wrefini||' and '||prreffim||' ';
       ELSE
         wsql = wsql||'FOLN.BDREFCOMP between '||wrefini||' and '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       if (COALESCE(prvercalcrra, -1) >= 0) then
          wsql = wsql||' and FOLN.BDVERCALCRRA = '||prvercalcrra;

       wsql = wsql||' union all ';

       wsql = wsql ||'select distinct FCTN.BDVERCALCRRA, FCT.BDCODEMP,FCT.BDCODCOL,FCT.BDREFTOMADOR BDREF13,FCTN.BDREFCOMP BDREFC13,FCT.BDCODVER,FCT.BDVALVFC BDVALVC13,0 BDDEP13,FCTN.BDDATAPAGFC BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER, FCTN.BDDATAPROCFC BDDATAPROCC13,FCTN.BDHORAPROCFC BDHORAPROCC13, cast(null as integer) BDORDEM, FCTN.BDTIPODEDUCAOFOLHA, FCTN.BDVALORDESCONTOSIMPLIFICADO, FCTN.BDVALORDIFERENCADEDUCOES ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN                                                                                                                          
             wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREFTOMADOR, VFN.BDREFFC, VFN.bdcodver, VFN.BDVALVFC FROM VRHF_EMP_TVERBAFCTOMADOR VFN '||
                                  'INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FCT ';
          END
       ELSE
         wsql = wsql||'from VRHF_EMP_TVERBAFCTOMADOR FCT ';

       wsql = wsql||'join VRH_BASE_TVERBAS VER on (VER.bdcodver = FCT.bdcodver) ';
       wsql = wsql||'join VRHF_EMP_TFOLTOMCOMP FCTN on (FCTN.BDCODEMP = FCT.BDCODEMP and FCTN.BDCODCOL = FCT.BDCODCOL and FCTN.BDREFTOMADOR = FCT.BDREFTOMADOR and FCTN.BDREFFC = FCT.BDREFFC) ';
       wsql = wsql||'where exists(select first 1 * from VRHF_EMP_TVERBAFCTOMADOR fvaux '||
                                 'join VRH_BASE_TVERBAS fvver on fvver.bdcodver = fvaux.bdcodver '||
                                 'where fvaux.bdcodemp = FCTN.BDCODEMP and fvaux.bdcodcol = FCTN.BDCODCOL and fvaux.BDREFTOMADOR = FCTN.BDREFTOMADOR and fvaux.bdreffc = FCTN.BDREFFC and fvver.bdclaver like ''0.601.%'') and ';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'FCTN.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim||' ';
       ELSE
         wsql = wsql||'FCTN.BDREFCOMP between '||prrefini||' and '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||REPLACE(UPPER(prcodemp), 'FOL.BDCODEMP', 'FCT.BDCODEMP');
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'FOL.BDCODCOL', 'FCT.BDCODCOL');

       if (COALESCE(prvercalcrra, -1) >= 0) then
          wsql = wsql||' and FCTN.BDVERCALCRRA = '||prvercalcrra;

       wsql = wsql||') X order by X.BDCODEMP,X.BDCODCOL,X.BDREF13,X.BDREFC13 ';
     END
  ELSE
     BEGIN
       wsql = 'select * from (';
       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql ||'select 0 BDVERCALCRRA,FOL.BDCODEMP,FO.BDCODCOL,FO.BDREF13,FO.BDREFC13,FO.BDCODVER,FO.BDVALVC13,0 BDDEP13,FOLN.BDDATAIRRFESOCIAL AS BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCC13,FOLN.BDHORAPROCC13,FOLN.BDORDEM, 0 BDTIPODEDUCAOFOLHA, 0 BDVALORDESCONTOSIMPLIFICADO, 0 BDVALORDIFERENCADEDUCOES ';
       ELSE
         wsql = wsql ||'select 0 BDVERCALCRRA,FOL.BDCODEMP,FO.BDCODCOL,FO.BDREF13,FO.BDREFC13,FO.BDCODVER,FO.BDVALVC13,0 BDDEP13,FOLN.BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCC13,FOLN.BDHORAPROCC13,FOLN.BDORDEM, 0 BDTIPODEDUCAOFOLHA, 0 BDVALORDESCONTOSIMPLIFICADO, 0 BDVALORDIFERENCADEDUCOES ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' from TMP_EMPRESAS_SELECT FOL INNER join (select VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDREF13, VFN.BDREFC13, VFN.BDCODVER,VFN.BDVALVC13 FROM vrhf_emp_tverbac13 VFN) FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       ELSE
          wSQL = wSQL ||' from TEMPRESAS FOL join vrhf_emp_tverbac13 FO on (FO.BDCODEMP = FOL.BDCODEMP) ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tc13sal FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREF13 = FO.BDREF13 and FOLN.BDREFC13 = FO.BDREFC13) ';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'where FOLN.BDREFIRRFESOCIAL between '||wrefini||' and '||prreffim||' ';
       ELSE
         wsql = wsql||'where FO.BDREFC13 between '||wrefini||' and '||prreffim||' ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' union all ';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql ||'select FOLN.BDVERCALCRRA,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN BDREF13,FOLN.BDREFCOMP BDREFC13,FOL.BDCODVER,FOL.BDVALVFC BDVALVC13,0 BDDEP13,FOLN.BDDATAIRRFESOCIAL BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER, FOLN.BDDATAPROCFC BDDATAPROCC13,FOLN.BDHORAPROCFC BDHORAPROCC13, cast(null as integer) BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES ';
       ELSE
         wsql = wsql ||'select FOLN.BDVERCALCRRA,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN BDREF13,FOLN.BDREFCOMP BDREFC13,FOL.BDCODVER,FOL.BDVALVFC BDVALVC13,0 BDDEP13,FOLN.BDDATAPAGFC BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER, FOLN.BDDATAPROCFC BDDATAPROCC13,FOLN.BDHORAPROCFC BDHORAPROCC13, cast(null as integer) BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN                                                                                                                          
             wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREFFN, VFN.BDREFFC, VFN.bdcodver, VFN.BDVALVFC FROM vrhf_emp_tverbafc VFN '||
                                  'INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
          END
       ELSE
         wsql = wsql||'from vrhf_emp_tverbafc FOL ';

       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhacomp FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFFN = FOL.BDREFFN and FOLN.BDREFFC = FOL.BDREFFC) ';
       wsql = wsql||'where exists(select first 1 * from vrhf_emp_tverbafc fvaux '||
                                 'join vrh_base_tverbas fvver on fvver.bdcodver = fvaux.bdcodver '||
                                 'where fvaux.bdcodemp = FOLN.BDCODEMP and fvaux.bdcodcol = FOLN.BDCODCOL and fvaux.bdreffn = FOLN.BDREFFN and fvaux.bdreffc = FOLN.BDREFFC and fvver.bdclaver like ''0.601.%'') and ';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'FOLN.BDREFIRRFESOCIAL between '||wrefini||' and '||prreffim||' ';
       ELSE
         wsql = wsql||'FOLN.BDREFCOMP between '||wrefini||' and '||prreffim||' ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       if (COALESCE(prvercalcrra, -1) >= 0) then
          wsql = wsql||' and FOLN.BDVERCALCRRA = '||prvercalcrra;

       wsql = wsql||' union all ';

       wsql = wsql ||'select distinct FCTN.BDVERCALCRRA, FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR BDREF13,FCTN.BDREFCOMP BDREFC13,FOL.BDCODVER,FOL.BDVALVFC BDVALVC13,0 BDDEP13,FCTN.BDDATAPAGFC BDDATAPGTOC13,VER.BDCLAVER,VER.BDDESCVER, FCTN.BDDATAPROCFC BDDATAPROCC13,FCTN.BDHORAPROCFC BDHORAPROCC13, cast(null as integer) BDORDEM, FCTN.BDTIPODEDUCAOFOLHA, FCTN.BDVALORDESCONTOSIMPLIFICADO, FCTN.BDVALORDIFERENCADEDUCOES ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN                                                                                                                          
             wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREFTOMADOR, VFN.BDREFFC, VFN.bdcodver, VFN.BDVALVFC FROM VRHF_EMP_TVERBAFCTOMADOR VFN '||
                                  'INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FCT ';
          END
       ELSE
         wsql = wsql||'from VRHF_EMP_TVERBAFCTOMADOR FOL ';

       wsql = wsql||'join VRH_BASE_TVERBAS VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join VRHF_EMP_TFOLTOMCOMP FCTN on (FCTN.BDCODEMP = FOL.BDCODEMP and FCTN.BDCODCOL = FOL.BDCODCOL and FCTN.BDREFTOMADOR = FOL.BDREFTOMADOR and FCTN.BDREFFC = FOL.BDREFFC) ';
       wsql = wsql||'where exists(select first 1 * from VRHF_EMP_TVERBAFCTOMADOR fvaux '||
                                 'join VRH_BASE_TVERBAS fvver on fvver.bdcodver = fvaux.bdcodver '||
                                 'where fvaux.bdcodemp = FCTN.BDCODEMP and fvaux.bdcodcol = FCTN.BDCODCOL and fvaux.BDREFTOMADOR = FCTN.BDREFTOMADOR and fvaux.bdreffc = FCTN.BDREFFC and fvver.bdclaver like ''0.601.%'') and ';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'FCTN.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim||' ';
       ELSE
         wsql = wsql||'FCTN.BDREFCOMP between '||prrefini||' and '||prreffim||' ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       if (COALESCE(prvercalcrra, -1) >= 0) then
          wsql = wsql||' and FCTN.BDVERCALCRRA = '||prvercalcrra;
     

       wsql = wsql||') X order by X.BDCODEMP,X.BDCODCOL,X.BDREF13,X.BDREFC13 ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wrefc13atu = 0;
  wordematu  = 0;

  wbaseir13  = 0;
  winss13    = 0;
  wir13      = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc13 = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;
  wordem     = 0;
  wtipodeducao = 0;
  wvalordescsimpl = 0;
  wvalordifdescsimpl = 0;
  wtipodeducaoatu = 0;
  wvalordescsimplatu = 0;
  wvalordifdescsimplatu = 0;

  FOR EXECUTE STATEMENT wsql INTO :BDVERCALCRRA, :wcodemp,:wcodcol,:wref,:wrefc13,:wcodver,:wvalor,:wdep,:wdata,:wclassif,:wdescver,:wdataproc,:whoraproc,:wordem,:wtipodeducao,:wvalordescsimpl,:wvalordifdescsimpl DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wrefatu = 0) THEN
       wrefatu = wref;

    IF (wrefc13atu = 0) THEN
       wrefc13atu = wrefc13;

    if (wvalordescsimplatu = 0) then
      wvalordescsimplatu = wvalordescsimpl;
    if (wvalordifdescsimplatu = 0) then
      wvalordifdescsimplatu = wvalordifdescsimpl;
    if (wtipodeducaoatu = 0) then
      wtipodeducaoatu = wtipodeducao;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wrefc13 <> wrefc13atu)) THEN
       BEGIN
         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

         IF ((wrefpagto >= prrefini AND wrefpagto <= prreffim) and
             ((wbaseir13 <> 0) or (winss13 <> 0) or (wir13 <> 0) or (wlucropj <> 0) or (wdespmed <> 0) or (wajcus <> 0) or
              (wpenjud <> 0) or (wpenalim <> 0) or (wprepri <> 0) or (windresc13 <> 0) or (wvalabo <> 0) or (wrendis <> 0))) THEN
            BEGIN
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir13;
              BDINSS           = winss13;
              BDIR             = wir13;
              BDDEP            = wdepatu;
              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;
              BDPREVPRIV       = wprepri;
              BDINDRESC        = windresc13;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDTIPO           = 11;    -- Complemento 13º salário
              BDINFADIC        = '';
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;
              BDORDEM          = wordematu;

              if (pratualizainfodescsimple = TRUE) then
                begin
                  wrefpgtoaux = CAST((SUBSTRING(wrefpagto FROM 1 FOR 4)||'13')AS INTEGER);
                  wsqlaux = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, '||
                            ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, '||
                            ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) '||
                            ' values ('||current_connection||', '||wempatu||', '||wcolatu||', '||wrefpgtoaux||', 0, '||coalesce(bdpenalim, 0)||', '||coalesce(bddep, 0)||', '||coalesce(bdprevpriv, 0)||', '||coalesce(bdinss, 0)||', '||coalesce(wvalordescsimplatu, 0)||', FALSE, '||coalesce(bdrendtributavel, 0)||')';
          
                  execute statement wsqlaux;
                end
              SUSPEND;
            END

         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wrefatu    = wref;
         wrefc13atu = wrefc13;
         wordematu  = wordem;

         wbaseir13  = 0;
         winss13    = 0;
         wir13      = 0;
         wdepatu    = 0;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc13 = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
         wordem     = 0;
         wtipodeducaoatu = wtipodeducao;
         wvalordescsimplatu = wvalordescsimpl;
         wvalordifdescsimplatu = wvalordifdescsimpl;
       END

    -- soma as bases
    SELECT first 1 BDTIPOCODVER, BDIRVER, BDRENDISENTOIRVER
    FROM VRH_BASE_TVERBAS_REF
    WHERE BDCODVER = :wcodver and BDREFVER <= :wrefatu
    order by BDREFVER DESC
    INTO :wtipocodver,:wirver,:wrendisentover;

--    if (wtipocodver <= 1) then
       begin
         IF (wirver = 3) THEN -- 13º salário
            BEGIN
              IF (wtipocodver = 0) THEN   -- provento
                 wbaseir13 = wbaseir13 + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN   -- desconto
                 BEGIN
                   --                                      INSS                                              Obrigações IR
                   IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030' AND SUBSTRING(wclassif FROM 1 FOR 7) <> '6.001.8') THEN
                      wbaseir13 = wbaseir13 - wvalor;
                 END
            END
     
         -- Desconto de 13º salário
         IF ((SUBSTRING(wclassif FROM 1 FOR 5) = '6.080') and (wirver <> 3) and (wtipocodver <= 1)) THEN
            wbaseir13 = wbaseir13 - wvalor;
         --                                     INSS
         IF ((SUBSTRING(wclassif FROM 1 FOR 7) = '9.010.0') and (wirver = 3)) THEN
            winss13 = winss13 + wvalor;
         --                                     IR
         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.4') or (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.A')) THEN
            wir13 = wir13 + wvalor;
         --                                     Pensões judiciais
         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '6.001.8.0') and (wirver = 3)) THEN
            wpenjud = wpenjud + wvalor;
         --                                     Pensões alimentícias
         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '6.001.8.1') and (wirver = 3)) THEN
            wpenalim = wpenalim + wvalor;
         --                                     Previdência privada
         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '6.001.8.2') and (wirver = 3)) THEN
            wprepri = wprepri + wvalor;
         --                                     Previdência complementar 160514 LuizCovre 05/07/2022
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '6.009.0.0') THEN
            wprepri = wprepri + wvalor;
         -- Rendimentos isentos
         IF ((UPPER(wrendisentover) = 'TRUE') and ((SUBSTRING(wclassif FROM 1 FOR 7) = '0.601.0') or ((SUBSTRING(wclassif FROM 1 FOR 7) = '6.001.0')))) THEN  -- Sol. 133983 | Michel Luciano | Data 25/02/2020.
            BEGIN
              wrendis = wrendis + wvalor;
              wdrendis = SUBSTRING(wdrendis||wdescver FROM 1 FOR 200);
            END
       end

    wdepatu = wdep;
    wdataatu = wdata;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
  END

  IF ((wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wrefc13atu <> 0) AND
      ((wbaseir13 <> 0) or (winss13 <> 0) or (wir13 <> 0) or (wlucropj <> 0) or (wdespmed <> 0) or (wajcus <> 0) or
       (wpenjud <> 0) or (wpenalim <> 0) or (wprepri <> 0) or (windresc13 <> 0) or (wvalabo <> 0) or (wrendis <> 0))) THEN
     BEGIN
       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir13;
            BDINSS           = winss13;
            BDIR             = wir13;
            BDDEP            = wdepatu;
            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;
            BDPREVPRIV       = wprepri;
            BDINDRESC        = windresc13;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 11;    -- Complemento 13º salário
            BDINFADIC        = '';
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            BDORDEM          = wordematu;

            if (pratualizainfodescsimple = TRUE) then
              begin
                wrefpgtoaux = CAST((SUBSTRING(wrefpagto FROM 1 FOR 4)||'13')AS INTEGER);
                wsqlaux = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, '||
                          ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, '||
                          ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) '||
                          ' values ('||current_connection||', '||wempatu||', '||wcolatu||', '||wrefpgtoaux||', 0, '||coalesce(bdpenalim, 0)||', '||coalesce(bddep, 0)||', '||coalesce(bdprevpriv, 0)||', '||coalesce(bdinss, 0)||', '||coalesce(wvalordescsimplatu, 0)||', FALSE, '||coalesce(bdrendtributavel, 0)||')';
        
                execute statement wsqlaux;
              end
            SUSPEND;
          END
     END

  /*
      DADOS IMPORTADOS OU CADASTRADOS NA FICHA
  */
  BDVERCALCRRA = 0;
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),'||
              'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,'||
              'FOL.BDDATAFIR, '''||''' BDAUX ';
       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       wsql = wsql||'where FOL.BDTIPOCALCFIR = 9110 and FOL.BDREFIRFIR >= '||prrefini||
              ' and FOL.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select C13.BDCODEMP,C13.BDCODCOL,C13.BDREF13,C13.BDREFC13 from VRHF_EMP_TC13SAL C13 where C13.BDCODEMP = FOL.BDCODEMP and C13.BDCODCOL = FOL.BDCODCOL and '||
                                'C13.BDREF13 = FOL.BDREFFIR) ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDDATAFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wsql = wsql||'from tmp_empresas_select FOL ';
       ELSE
          wsql = wsql||'from TEMPRESAS FOL ';

       wsql = wsql||'join VRHF_EMP_TFICHAIRRF FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'where FO.BDTIPOCALCFIR = 9110 and FO.BDREFIRFIR >= '||prrefini||
              ' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select C13.BDCODEMP,C13.BDCODCOL,C13.BDREF13,C13.BDREFC13 from VRHF_EMP_TC13SAL C13 where C13.BDCODEMP = FO.BDCODEMP and C13.BDCODCOL = FO.BDCODCOL and '||
                                'C13.BDREF13 = FO.BDREFFIR) ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||prcodemp||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||prcodmatriz||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDDATAFIR ';
     END

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC
  DO
  BEGIN
    BDDATAPROC  = BDDATAPGTO;
    BDHORAPROC  = '00:00:00';
    SUSPEND;
  END
END
^

/* Restore proc. body: SP_VRHF_DADOS_IR_5012 */
create or alter procedure SP_VRHF_DADOS_IR_5012 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPORCC smallint = 0,
    PRSEMPLR smallint = 0,
    PRCALCAPURANUAL integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFIR integer,
    BDREFIRFIR integer,
    BDTIPOCALCFIR integer,
    BDCCFIR integer,
    BDCODFERFIR integer,
    BDCODTCA integer,
    BDBASEIRFIR numeric(18,6),
    BDVALINSSFIR numeric(18,6),
    BDVALIRFIR numeric(18,6),
    BDVALDEPFIR numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDDATAFIR date,
    BDCODAUTONOMO integer,
    BDCONTRCOL integer,
    BDCPFCOL varchar(14),
    BDCODMATRIZ integer,
    BDCNPJEMP varchar(18),
    BDCODFILIAL integer,
    BDREFEMP integer,
    BDNOMEMP varchar(100),
    BDCODCLA integer,
    BDCODGRUPOCLA integer,
    BDCODCLATRI integer,
    BDCODESTAB varchar(30),
    BDTIPOCAEPF integer,
    BDESCOOPERATIVA integer,
    BDESCONSTRUTORA varchar(5),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDTIPOTOM integer,
    BDCODLOT integer,
    BDCNPJTOM varchar(18),
    BDNOMETOM varchar(100),
    BDTIPOIRRF integer)
as
declare variable WEMP varchar(20000);
declare variable WCOL varchar(30000);
declare variable WMAT varchar(15000);
declare variable WSQL varchar(30000);
declare variable WREF integer;
declare variable WSQLAUX varchar(30000);
declare variable WCODEMPS varchar(15000);
BEGIN 
    /*COLABORADORES E CONTRIBUINTES*/
     
    SELECT CAST(TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) AS INTEGER) FROM RDB$DATABASE INTO WREF;

    IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
    BEGIN
        WCODEMPS = PRCODEMP;
        WEMP = ''''||'FOL.BDCODEMP = '||PRCODEMP||'''';
    END
    ELSE
        WEMP = 'NULL';

    IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
        WCOL = ''''||PRCODCOL||'''';
    ELSE
        WCOL = 'NULL';

    IF (PRPUXARFILIAIS = 1) THEN
    BEGIN
        WMAT = ''''||'FOL.BDCODEMP IN ('||PRCODMATRIZ||')'||'''';
        WCODEMPS  = WCODEMPS ||', '|| PRCODMATRIZ;
    END
    ELSE
    BEGIN
        WMAT = 'NULL';
    END
    
    /*PRCALCAPURANUAL = 1 -> APURAÇÃO MENSAL
    PRCALCAPURANUAL = 0 -> APURAÇÃO ANUAL*/

    WSQL =     '    SELECT SP.*, TVINC.BDCONTRCOL, TVINC.BDCPFCOL, EMP.BDCODMATRIZ, EMP.BDCNPJEMP, '||
            '     CASE '||
            '        WHEN EMP.BDCODMATRIZ IS NOT NULL THEN SP.BDCODEMP '||
            '    ELSE 0 '||
            '    END AS BDCODFILIAL, '|| 
            '    TREF.BDREFEMP, TREF.BDNOMEMP, TVINC.BDCODCLA, GRUPCLA.BDCODGRUPOCLA, ESOCIAL.BDCODCLATRI, EMP.BDCODESTAB, EMP.BDTIPOCAEPF, '||
            '    ESOCIAL.BDESCOOPERATIVA, ESOCIAL.BDESCONSTRUTORA, COALESCE(SPTOR.BDCODCENTRO, 0) AS BDCODCENTRO, COALESCE (SPTOR.BDCODTPCC, 0) AS BDCODTPCC, '||
            '    COALESCE(CUS.BDTIPOTOM, -1) AS BDTIPOTOM, CUS.BDCODLOT, CUS.BDCNPJTOM, CUS.BDNOMETOM '||
            '    FROM  (';

    IF (PRCALCAPURANUAL = 1) THEN
    BEGIN
        -- FOLHA NORMAL                    -- MENSAL
        WSQLAUX =     ' SELECT BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,COALESCE(BDORDEM,0)AS BDORDEM,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO, 0 AS BDCODAUTONOMO, 0 AS BDTIPOIRRF '||
                    ' FROM SP_VRHF_DADOS_IR_FN('||WEMP||','||WCOL||','||PRREFINI||','||PRREFFIM||','||PRPUXARFILIAIS||','||WMAT||', 0, 0, 0, TRUE)';
        -- FOLHA COMPLEMENTAR              -- MENSAL
        WSQLAUX =     WSQLAUX ||'UNION ALL'|| 
                    ' SELECT BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,COALESCE(BDORDEM,0) AS BDORDEM,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO, 0 AS BDCODAUTONOMO, 0 AS BDTIPOIRRF '||
                    ' FROM SP_VRHF_DADOS_IR_FC('||WEMP||','||WCOL||','||PRREFINI||','||PRREFFIM||','||PRPUXARFILIAIS||','||WMAT||', 0, 0, 0, TRUE, FALSE, 0, 0)';

        -- ADIANTAMENTO SALARIAL           -- MENSAL
        WSQLAUX =     WSQLAUX ||'UNION ALL'||  
                    ' SELECT BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,0 AS BDORDEM,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO, 0 AS BDCODAUTONOMO, 0 AS BDTIPOIRRF '||
                    ' FROM SP_VRHF_DADOS_IR_AD('||WEMP||','||WCOL||','||PRREFINI||','||PRREFFIM||','||PRPUXARFILIAIS||','||WMAT||', TRUE) ';

        -- FÉRIAS                           -- MENSAL
        WSQLAUX =     WSQLAUX ||'UNION ALL'|| 
                    ' SELECT BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,0 AS BDORDEM,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO, 0 AS BDCODAUTONOMO, 0 AS BDTIPOIRRF '||
                    ' FROM SP_VRHF_DADOS_IR_FE('||WEMP||','||WCOL||','||PRREFINI||','||PRREFFIM||','||PRPUXARFILIAIS||','||WMAT||', 0, TRUE) ';

        -- FOLHA AVULSA ABONO               -- MENSAL
        WSQLAUX =     WSQLAUX ||'UNION ALL'|| 
                    ' SELECT BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,0 AS BDORDEM,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO, 0 AS BDCODAUTONOMO, 0 AS BDTIPOIRRF '||
                    ' FROM SP_VRHF_DADOS_IR_FA('||WEMP||','||WCOL||','||PRREFINI||','||PRREFFIM||','||PRPUXARFILIAIS||','||WMAT||', 0, 1, TRUE)';

        -- FOLHA INTERMITENTE               -- MENSAL
        WSQLAUX =     WSQLAUX ||'UNION ALL'|| 
                    ' SELECT BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,COALESCE(BDORDEM, 0) AS BDORDEM,SUM(BDRENDTRIBUTAVEL),SUM(BDINSS),SUM(BDIR),MAX(BDDEP),SUM(BDPENJUD),SUM(BDPENALIM),MAX(BDDATAPGTO), 0 AS BDCODAUTONOMO, 0 AS BDTIPOIRRF '||
                    ' FROM SP_VRHF_DADOS_IR_INT('||WEMP||','||WCOL||','||PRREFINI||','||PRREFFIM||','||PRPUXARFILIAIS||','||WMAT||', 0, 0, 0, TRUE, FALSE, 1)'||
                    ' GROUP BY BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDORDEM ';

        -- FOLHA INTERMITENTE COMPLEMENTAR  -- MENSAL
        WSQLAUX =     WSQLAUX ||'UNION ALL'|| 
                    ' SELECT BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,COALESCE(BDORDEM, 0) AS BDORDEM,SUM(BDRENDTRIBUTAVEL),SUM(BDINSS),SUM(BDIR),MAX(BDDEP),SUM(BDPENJUD),SUM(BDPENALIM),MAX(BDDATAPGTO), 0 AS BDCODAUTONOMO, 0 AS BDTIPOIRRF '||
                    ' FROM SP_VRHF_DADOS_IR_FC_INT('||WEMP||','||WCOL||','||PRREFINI||','||PRREFFIM||','||PRPUXARFILIAIS||','||WMAT||',0,0,0,TRUE)'||
                    ' GROUP BY BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDORDEM, BDCODAUTONOMO ';

        -- FOLHA AVULSA                     -- PLR
        WSQLAUX =     WSQLAUX ||'UNION ALL'|| 
                    ' SELECT BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,0 AS BDORDEM,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO, 0 AS BDCODAUTONOMO, 1 AS BDTIPOIRRF '||
                    ' FROM SP_VRHF_DADOS_IR_FA('||WEMP||','||WCOL||','||PRREFINI||','||PRREFFIM||','||PRPUXARFILIAIS||','||WMAT||', 1, 0, TRUE)';
            
        -- COMPLEMENTO DE 13º SALÁRIO       -- 13°
        WSQLAUX =     WSQLAUX||'UNION ALL '||
                    ' SELECT BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,0 AS BDORDEM,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO, 0 AS BDCODAUTONOMO, 2 AS BDTIPOIRRF '||
                    ' FROM SP_VRHF_DADOS_IR_C13('||WEMP||','||WCOL||','||PRREFINI||','||PRREFFIM||','||PRPUXARFILIAIS||','||WMAT||',TRUE) ' ;
            
        -- FOLHA INTERMITENTE 13º           -- 13°
        WSQLAUX =     WSQLAUX||'UNION ALL '||
                    ' SELECT BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,COALESCE(BDORDEM, 0) AS BDORDEM,SUM(BDRENDTRIBUTAVEL) AS BDRENDTRIBUTAVEL,SUM(BDINSS) AS BDINSS,SUM(BDIR) AS BDIR,MAX(BDDEP) AS BDDEP,SUM(BDPENJUD) AS BDPENJUD,SUM(BDPENALIM) AS BDPENALIM,MAX(BDDATAPGTO) AS BDDATAPGTO, 0 AS BDCODAUTONOMO, 2 AS BDTIPOIRRF '||
                    ' FROM SP_VRHF_DADOS_IR_INT13('||WEMP||','||WCOL||','||PRREFINI||','||PRREFFIM||','||PRPUXARFILIAIS||','||WMAT||',1,TRUE) '||
                    ' GROUP BY BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDORDEM ';

        -- 13º SALÁRIO / 13º RESCISÃO       -- 13°
        WSQLAUX =     WSQLAUX||'UNION ALL '||
                    ' SELECT BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,COALESCE(BDORDEM,0)AS BDORDEM,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO, 0 AS BDCODAUTONOMO, 2 AS BDTIPOIRRF '||
                    ' FROM SP_VRHF_DADOS_IR_13('||WEMP||','||WCOL||','||PRREFINI||','||PRREFFIM||','||PRPUXARFILIAIS||','||WMAT||',TRUE) SP13 ';
                    /*' WHERE SP13.BDTIPO = 101 ';*/

                                            -- RRA
        WSQLAUX =     WSQLAUX||'UNION ALL '||
                    ' SELECT BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,COALESCE(BDORDEM,0)AS BDORDEM,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO, 0 AS BDCODAUTONOMO, 3 AS BDTIPOIRRF '||
                    ' FROM  SP_VRHF_DADOS_IR_FC_RRA('||WEMP||','||WCOL||','||PRREFINI||','||PRREFFIM||','||PRPUXARFILIAIS||','||WMAT||',0,0,0,false, false,1,false,0) ';
    END
    ELSE
    BEGIN
        -- 13º SALÁRIO
        WSQLAUX =   ' SELECT BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,COALESCE(BDORDEM,0)AS BDORDEM,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDPENJUD,BDPENALIM,BDDATAPGTO, 0 AS BDCODAUTONOMO, 2 AS BDTIPOIRRF '||
                    ' FROM SP_VRHF_DADOS_IR_13('||WEMP||','||WCOL||','||PRREFINI||','||PRREFFIM||','||PRPUXARFILIAIS||','||WMAT||',TRUE) SP13 '||
                    ' WHERE SP13.BDTIPO = 10 ';

    END
    
    WSQLAUX =     WSQLAUX ||' )SP ';
    
    WSQL =    WSQL || WSQLAUX ||' JOIN ( '||
            '    SELECT BASE.BDCODEMP, BASE.BDCODCOL, BASE.BDREFCOL, BASE.BDCPFCOL, BASE.BDCONTRCOL, V.BDCODCLA '||
            '    FROM '||
            '    ( '||
            '      SELECT '||
            '          X.BDCODEMP, '||
            '          X.BDCODCOL, '||
            '          X.BDCPFCOL, '||
            '          X.BDCONTRCOL, '||
            '          COALESCE '||
            '      ( '||
            '          (SELECT MAX(D2.BDREFCOL) FROM VRH_EMP_TCOLCON_VINC D2 WHERE D2.BDCODEMP = X.BDCODEMP AND D2.BDCODCOL = X.BDCODCOL AND CAST(D2.BDREFCOL AS VARCHAR(6)) <= (SELECT TRIM(RDB$GET_CONTEXT('||'''USER_SESSION'''||', '||'''W_ANOMES'''||')) FROM RDB$DATABASE)), '||
            '          (SELECT MIN(D1.BDREFCOL) FROM VRH_EMP_TCOLCON_VINC D1 WHERE D1.BDCODEMP = X.BDCODEMP AND D1.BDCODCOL = X.BDCODCOL) '||
            '      ) AS BDREFCOL '||
            '      FROM VRH_EMP_TCOLCON X '||
            '      WHERE X.BDCODEMP IN ('||WCODEMPS||') '||
            '    ) AS BASE, VRH_EMP_TCOLCON_VINC V '||
            '    WHERE BASE.BDCODEMP = V.BDCODEMP AND BASE.BDCODCOL = V.BDCODCOL AND BASE.BDREFCOL = V.BDREFCOL '||
            '    )TVINC ON (TVINC.BDCODEMP = SP.BDCODEMP AND TVINC.BDCODCOL = SP.BDCODCOL) '||
            '    JOIN TEMPRESAS EMP ON (SP.BDCODEMP = EMP.BDCODEMP) '||
            '    JOIN VRH_BASE_TCLASSE CLAS ON (TVINC.BDCODCLA = CLAS.BDCODCLA) '||
            '    JOIN TGRUPOCLASSECOL GRUPCLA ON (GRUPCLA.BDCODGRUPOCLA = CLAS.BDGRUPOCLA) '||
            '    JOIN ( '||
            '        SELECT '||
            '        EMP.BDCODEMP, '||
            '        EMP.BDREFEMP, '||
            '        TEMP.BDCNPJEMP, '||
            '        DAD.BDNOMEMP, '||
            '        TEMP.BDCODMATRIZ '||
            '    FROM (SELECT '||
            '    EMP.BDCODEMP, '||
            '    COALESCE( '||
            '    (SELECT FIRST 1 X.BDREFEMP FROM TEMPRESAS_REF X '||
            '        WHERE X.BDCODEMP = EMP.BDCODEMP AND '||
            '        X.BDREFEMP <= (SELECT TRIM(RDB$GET_CONTEXT('||'''USER_SESSION'''||', '||'''W_ANOMES'''||')) FROM RDB$DATABASE) '||
            '        ORDER BY X.BDCODEMP DESC, X.BDREFEMP DESC), '||
            '    (SELECT FIRST 1 X.BDREFEMP FROM TEMPRESAS_REF X '||
            '        WHERE X.BDCODEMP = EMP.BDCODEMP '||
            '        AND X.BDCODPLAPADRAO IS NOT NULL '||
            '        AND X.BDCODHIST IS NOT NULL '||
            '        ORDER BY X.BDCODEMP, X.BDREFEMP), '||
            '    (SELECT FIRST 1 X.BDREFEMP FROM TEMPRESAS_REF X '||
            '        WHERE X.BDCODEMP = EMP.BDCODEMP '||
            '        ORDER BY X.BDCODEMP, X.BDREFEMP)) BDREFEMP '||
            '    FROM TEMPRESAS EMP) EMP '||
            '    INNER JOIN TEMPRESAS TEMP ON (TEMP.BDCODEMP = EMP.BDCODEMP) '||
            '    JOIN TEMPRESAS_REF DAD ON (DAD.BDCODEMP = EMP.BDCODEMP AND DAD.BDREFEMP = EMP.BDREFEMP) '||
            '    WHERE EMP.BDCODEMP IN ('||WCODEMPS||') AND ((TEMP.BDEXCLUIREMP IS NULL)OR(UPPER(TEMP.BDEXCLUIREMP)<>'||'''TRUE'''||')) '||
            '    ) TREF ON (TREF.BDCODEMP = SP.BDCODEMP) '||
            '    JOIN ( '||
            '        SELECT '||
            '        BASE.BDCODEMP, '||
            '        ESOCIAL.BDREFEMP, '||
            '        ESOCIAL.BDCODCLATRI, '||
            '        ESOCIAL.BDESCOOPERATIVA, '||
            '        ESOCIAL.BDESCONSTRUTORA '||
            '    FROM( '||
            '      SELECT '||
            '          X.BDCODEMP, '||
            '          COALESCE '||
            '      ( '||
            '          (SELECT MAX(D2.BDREFEMP) FROM VRHF_BASE_TEMPESOCIAL D2 WHERE D2.BDCODEMP = X.BDCODEMP AND CAST(D2.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(RDB$GET_CONTEXT('||'''USER_SESSION'''||', '||'''W_ANOMES'''||')) FROM RDB$DATABASE)), '||
            '          (SELECT MIN(D1.BDREFEMP) FROM VRHF_BASE_TEMPESOCIAL D1 WHERE D1.BDCODEMP = X.BDCODEMP) '||
            '      ) AS BDREFEMP '||
            '      FROM TEMPRESAS X '||
            '      WHERE X.BDCODEMP IN ('||WCODEMPS||') AND ((X.BDEXCLUIREMP IS NULL)OR(UPPER(X.BDEXCLUIREMP)<>'||'''TRUE'''||')) '||
            '    ) AS BASE, VRHF_BASE_TEMPESOCIAL ESOCIAL '||
            '    WHERE BASE.BDCODEMP = ESOCIAL.BDCODEMP AND BASE.BDREFEMP = ESOCIAL.BDREFEMP) ESOCIAL ON (ESOCIAL.BDCODEMP = SP.BDCODEMP) '||
            '    LEFT JOIN SP_VRHF_RETORNA_TOMADOR('''||'BDCODEMP IN ('||WCODEMPS||')'||''', NULL, '||PRREFINI||') SPTOR ON (SPTOR.BDCODEMP = SP.BDCODEMP AND SPTOR.BDCODCOL = SP.BDCODCOL AND SPTOR.BDORDEM = SP.BDORDEM) '||
            '    LEFT JOIN VRH_BASE_TCUSTOM CUS ON (CUS.BDCODCENTRO = SPTOR.BDCODCENTRO AND CUS.BDCODTPCC = SPTOR.BDCODTPCC)';
            
    FOR EXECUTE STATEMENT WSQL INTO
        :BDCODEMP,
        :BDCODCOL,
        :BDREFFIR,
        :BDREFIRFIR,
        :BDTIPOCALCFIR,
        :BDCODTCA,
        :BDBASEIRFIR,
        :BDVALINSSFIR,
        :BDVALIRFIR,
        :BDVALDEPFIR,
        :BDPENJUD,
        :BDPENALIM,
        :BDDATAFIR,
        :BDCODAUTONOMO,
        :BDTIPOIRRF,
        :BDCONTRCOL, 
        :BDCPFCOL, 
        :BDCODMATRIZ, 
        :BDCNPJEMP,           
        :BDCODFILIAL, 
        :BDREFEMP, 
        :BDNOMEMP,
        :BDCODCLA, 
        :BDCODGRUPOCLA, 
        :BDCODCLATRI, 
        :BDCODESTAB, 
        :BDTIPOCAEPF,
        :BDESCOOPERATIVA, 
        :BDESCONSTRUTORA, 
        :BDCODCENTRO, 
        :BDCODTPCC,
        :BDTIPOTOM,
        :BDCODLOT,
        :BDCNPJTOM,
        :BDNOMETOM

    DO
        SUSPEND;
        
    EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:WREF, NULL, NULL);
    
    SELECT CAST(TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) AS INTEGER) FROM RDB$DATABASE INTO WREF;
    WCODEMPS = '';
    WEMP     = '';
    WCOL     = '';
    WMAT     = '';
        
    IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
    BEGIN
        WCODEMPS = PRCODEMP;
        WEMP = ''''||'FOL.BDCODEMP = '||PRCODEMP||'''';
    END
    ELSE
        WEMP = 'NULL';

    IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
        WCOL = ''''||PRCODCOL||'''';
    ELSE
        WCOL = 'NULL';

    IF (PRPUXARFILIAIS = 1) THEN
    BEGIN
        WMAT = ''''||'FOL.BDCODEMP IN ('||PRCODMATRIZ||')'||'''';
        WCODEMPS  = WCODEMPS ||', '|| PRCODMATRIZ;
    END
    ELSE
    BEGIN
        WMAT = 'NULL';
    END

    WSQL     =    '    SELECT SP.BDCODEMP, SP.BDCODTER AS BDCODCOL, SP.BDREF, 0 AS BDREFPAG, 0 AS BDTIPO, 0 AS BDORDEM, BDBASEIRBRUTA, 0 AS BDINSS, SP.BDVALORIR, SP.BDVALORDEP, 0 AS BDPENJUD, 0 AS BDPENALIM, '||
                '    SP.BDDATAPAGSERV, COALESCE(SP.BDCODTER, 0) AS BDCODAUTONOMO,0 AS BDCONTROL, SP.BDCPFTER,  TECEMP.BDCODMATRIZ, TECEMP.BDCNPJEMP, '||
                '   CASE '||
                '         WHEN TECEMP.BDCODMATRIZ IS NOT NULL THEN SP.BDCODEMP '||
                '         ELSE 0 '||
                '       END AS BDCODFILIAL, TECEMP.BDREFEMP, TECEMP.BDNOMEMP, VINC.BDCODCLA, GRUPCLA.BDCODGRUPOCLA, ESOCIAL.BDCODCLATRI, TECEMP.BDCODESTAB, TECEMP.BDTIPOCAEPF, ESOCIAL.BDESCOOPERATIVA, ESOCIAL.BDESCONSTRUTORA '||
                '       , COALESCE(SPTOR.BDCODCENTRO, 0) AS BDCODCENTRO, COALESCE (SPTOR.BDCODTPCC, 0) AS BDCODTPCC, '||
                '       COALESCE(CUS.BDTIPOTOM, -1) AS BDTIPOTOM, CUS.BDCODLOT, CUS.BDCNPJTOM, CUS.BDNOMETOM, 4 BDTIPOIRRF '||
                '    FROM VRHF_SP_CONS_IR_TERCEIROS('''||'SERV.BDCODEMP IN ('||WCODEMPS||')'||''',NULL,'||PRREFINI||','||PRREFFIM||', TRUE) SP '||
                '    left JOIN ( '||
                '      SELECT BDCODTER, '||
                '        COALESCE ( '||
                '          (SELECT FIRST 1 RF2.BDREFEMP FROM TTERCEIRO_REF RF2 WHERE RF2.BDCODTER = X.BDCODTER AND RF2.BDREFEMP <= (SELECT TRIM(RDB$GET_CONTEXT('||'''USER_SESSION'''||', '||'''W_ANOMES'''||')) FROM RDB$DATABASE) ORDER BY RF2.BDCODTER DESC, RF2.BDREFEMP DESC), '||
                '          (SELECT FIRST 1 RF2.BDREFEMP FROM TTERCEIRO_REF RF2 WHERE RF2.BDCODTER = X.BDCODTER ORDER BY RF2.BDCODTER, RF2.BDREFEMP ) '||
                '        ) AS BDREFEMP '||
                '        FROM TTERCEIRO X '||
                '        GROUP BY X.BDCODTER '||
                '      ) TERCREF ON (TERCREF.BDCODTER = SP.BDCODTER) '||
                '    JOIN TTERCEIRO_REF TERC ON (TERCREF.BDCODTER = TERC.BDCODTER AND TERCREF.BDREFEMP = TERC.BDREFEMP ) '||
                '    JOIN ( '||
                '        SELECT '||
                '        EMP.BDCODEMP, '||
                '        EMP.BDREFEMP, '||
                '        TEMP.BDCNPJEMP, '||
                '        DAD.BDNOMEMP, '||
                '        TEMP.BDCODMATRIZ, '||
                '        EMP.BDCODESTAB, '||
                '        EMP.BDTIPOCAEPF '||
                '    FROM (SELECT '||
                '    EMP.BDCODEMP, '||
                '      COALESCE(( '||
                '          SELECT FIRST 1 X.BDREFEMP FROM TEMPRESAS_REF X '||
                '          WHERE X.BDCODEMP = EMP.BDCODEMP AND '||
                '          X.BDREFEMP <= (SELECT TRIM(RDB$GET_CONTEXT('||'''USER_SESSION'''||', '||'''W_ANOMES'''||')) FROM RDB$DATABASE) '||
                '          ORDER BY X.BDCODEMP DESC, X.BDREFEMP DESC), '||
                '         (SELECT FIRST 1 X.BDREFEMP FROM TEMPRESAS_REF X '||
                '           WHERE X.BDCODEMP = EMP.BDCODEMP '||
                '           AND X.BDCODPLAPADRAO IS NOT NULL '||
                '           AND X.BDCODHIST IS NOT NULL '||
                '           ORDER BY X.BDCODEMP, X.BDREFEMP), '||
                '         (SELECT FIRST 1 X.BDREFEMP FROM TEMPRESAS_REF X '||
                '           WHERE X.BDCODEMP = EMP.BDCODEMP '||
                '           ORDER BY X.BDCODEMP, X.BDREFEMP)) BDREFEMP, '||
                '        EMP.BDCODESTAB, '||
                '        EMP.BDTIPOCAEPF '||
                '    FROM TEMPRESAS EMP) EMP '||
                '    INNER JOIN TEMPRESAS TEMP ON (TEMP.BDCODEMP = EMP.BDCODEMP) '||
                '    JOIN TEMPRESAS_REF DAD ON (DAD.BDCODEMP = EMP.BDCODEMP AND DAD.BDREFEMP = EMP.BDREFEMP) '||
                '    WHERE EMP.BDCODEMP IN ('||WCODEMPS||') AND ((TEMP.BDEXCLUIREMP IS NULL)OR(UPPER(TEMP.BDEXCLUIREMP)<>'||'''TRUE'''||'))) TECEMP ON (TECEMP.BDCODEMP = SP.BDCODEMP) '||
                '    JOIN VRH_BASE_TTERC_VINC VINC ON (VINC.BDCODTER = SP.BDCODTER AND VINC.BDREFTERC = (select max(BDREFTERC) from VRH_BASE_TTERC_VINC VINC where VINC.BDCODTER = SP.BDCODTER)) '||--TERCREF.BDREFEMP) '||
                '    JOIN VRH_BASE_TCLASSE CLAS ON (VINC.BDCODCLA = CLAS.BDCODCLA) '||
                '    JOIN TGRUPOCLASSECOL GRUPCLA ON (GRUPCLA.BDCODGRUPOCLA = CLAS.BDGRUPOCLA) '||
                '    JOIN ( '||
                '        SELECT '||
                '        BASE.BDCODEMP, '||
                '        ESOCIAL.BDREFEMP, '||
                '        ESOCIAL.BDCODCLATRI, '||
                '        ESOCIAL.BDESCOOPERATIVA, '||
                '        ESOCIAL.BDESCONSTRUTORA '||
                '    FROM( '||
                '      SELECT '||
                '          X.BDCODEMP, '||
                '          COALESCE( '||
                '          (SELECT MAX(D2.BDREFEMP) FROM VRHF_BASE_TEMPESOCIAL D2 WHERE D2.BDCODEMP = X.BDCODEMP AND CAST(D2.BDREFEMP AS VARCHAR(6)) <= (SELECT TRIM(RDB$GET_CONTEXT('||'''USER_SESSION'''||', '||'''W_ANOMES'''||')) FROM RDB$DATABASE)), '||
                '          (SELECT MIN(D1.BDREFEMP) FROM VRHF_BASE_TEMPESOCIAL D1 WHERE D1.BDCODEMP = X.BDCODEMP) '||
                '      ) AS BDREFEMP '||
                '      FROM TEMPRESAS X '||
                '      WHERE X.BDCODEMP IN ('||WCODEMPS||') AND ((X.BDEXCLUIREMP IS NULL)OR(UPPER(X.BDEXCLUIREMP)<>'||'''TRUE'''||')) '||
                '    ) AS BASE, VRHF_BASE_TEMPESOCIAL ESOCIAL '||
                '    WHERE BASE.BDCODEMP = ESOCIAL.BDCODEMP AND BASE.BDREFEMP = ESOCIAL.BDREFEMP '||
                '    ) ESOCIAL ON (ESOCIAL.BDCODEMP = SP.BDCODEMP) '||
                '    LEFT OUTER JOIN SP_VRHF_RETORNA_TOMADOR_AUT('''||'BDCODEMP IN ('||WCODEMPS||')'||''', NULL, '||PRREFINI||') SPTOR ON (SPTOR.BDCODEMP = SP.BDCODEMP AND SPTOR.BDCODTER = SP.BDCODTER and SPTOR.bdcodserv = SP.BDCODSERV) '||
                '    LEFT OUTER JOIN VRH_BASE_TCUSTOM CUS ON (CUS.BDCODCENTRO = SPTOR.BDCODCENTRO AND CUS.BDCODTPCC = SPTOR.BDCODTPCC) ';
                
    FOR EXECUTE STATEMENT WSQL INTO
        :BDCODEMP,
        :BDCODCOL,
        :BDREFFIR,
        :BDREFIRFIR,
        :BDTIPOCALCFIR,
        :BDCODTCA,
        :BDBASEIRFIR,
        :BDVALINSSFIR,
        :BDVALIRFIR,
        :BDVALDEPFIR,
        :BDPENJUD,
        :BDPENALIM,
        :BDDATAFIR,
        :BDCODAUTONOMO,
        :BDCONTRCOL, 
        :BDCPFCOL, 
        :BDCODMATRIZ, 
        :BDCNPJEMP,           
        :BDCODFILIAL, 
        :BDREFEMP, 
        :BDNOMEMP,
        :BDCODCLA,
        :BDCODGRUPOCLA, 
        :BDCODCLATRI, 
        :BDCODESTAB, 
        :BDTIPOCAEPF,
        :BDESCOOPERATIVA, 
        :BDESCONSTRUTORA, 
        :BDCODCENTRO, 
        :BDCODTPCC,
        :BDTIPOTOM,
        :BDCODLOT,
        :BDCNPJTOM,
        :BDNOMETOM,
        :BDTIPOIRRF
    DO
        SUSPEND;
        
    EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:WREF, NULL, NULL);
END^

/* Restore proc. body: SP_VRHF_DADOS_IR_DIRF */
create or alter procedure SP_VRHF_DADOS_IR_DIRF (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PREXPORTACAO integer = 0,
    PRSEMPLR smallint = 0,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRTABTEMPRRA boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDCODTCA integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDAUXILIOMORADIA numeric(18,6))
as
declare variable WEMP varchar(20000);
declare variable WCOL varchar(30000);
declare variable WMAT varchar(15000);
declare variable WSQL varchar(30000);
declare variable WSQLAUX varchar(300);
declare variable WSQLAUXTABTEMP varchar(3000);
BEGIN
  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wemp = ''''||prcodemp||'''';
  ELSE
     wemp = 'null';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wcol = ''''||prcodcol||'''';
  ELSE
     wcol = 'null';

  IF (prpuxarfiliais = 1) THEN
     wmat = ''''||prcodmatriz||'''';
  ELSE
     wmat = 'null';

  IF (PRATUALIZAINFODESCSIMPLE = TRUE) THEN
    BEGIN
        wsqlaux = 'DELETE FROM VRHF_TINFO_DESC_SIMPLES WHERE BDSESSAO = ' || current_connection || ' and BDAUTONOMO = 0';
        EXECUTE STATEMENT WSQLAUX;
    END

  -- Folha normal
  wsql = 'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,SUM(BDRENDTRIBUTAVEL) BDRENDTRIBUTAVEL,SUM(BDINSS) BDINSS,SUM(BDIR) BDIR,SUM(BDDEP) BDDEP,SUM(BDLUCROPJ) BDLUCROPJ,'||
                'SUM(BDDESPMED) BDDESPMED,SUM(BDAJCUSTOS) + SUM(COALESCE(BDDIARIA, 0)) BDAJCUSTOS,SUM(BDPENJUD) BDPENJUD,SUM(BDPENALIM) BDPENALIM,SUM(BDPREVPRIV) BDPREVPRIV,SUM(BDINDRESC) BDINDRESC,'||
                'SUM(BDVALABO) BDVALABO,SUM(BDRENDISENTOS) BDRENDISENTOS,MAX(BDDRENDISENTOS) BDDRENDISENTOS,MAX(BDDATAPGTO) BDDATAPGTO, MAX(BDINFADIC) BDINFADIC,'||
                'CAST(0 as INTEGER) BDCODTCA,SUM(BDBOLSAESTUDOS) BDBOLSAESTUDOS, SUM(BDAUXILIOMORADIA) BDAUXILIOMORADIA from SP_VRHF_DADOS_IR_FN('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||',0,'||prexportacao||',0,'||false||','||pratualizainfodescsimple||') '||
                'group by BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO ' ;

  -- Folha intermitente
  wsql = wsql||'union all '||
        'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,SUM(BDRENDTRIBUTAVEL) BDRENDTRIBUTAVEL,SUM(BDINSS) BDINSS,SUM(BDIR) BDIR,MAX(BDDEP) BDDEP,SUM(BDLUCROPJ) BDLUCROPJ,'||
                'SUM(BDDESPMED) BDDESPMED,SUM(BDAJCUSTOS) + SUM(COALESCE(BDDIARIA, 0)) BDAJCUSTOS,SUM(BDPENJUD) BDPENJUD,SUM(BDPENALIM) BDPENALIM,SUM(BDPREVPRIV) BDPREVPRIV,SUM(BDINDRESC) BDINDRESC,'||
                'SUM(BDVALABO) BDVALABO,SUM(BDRENDISENTOS) BDRENDISENTOS,MAX(BDDRENDISENTOS) BDDRENDISENTOS,MAX(BDDATAPGTO) BDDATAPGTO, MAX(BDINFADIC) BDINFADIC,'||
                'CAST(0 as INTEGER) BDCODTCA, 0 BDBOLSAESTUDOS, SUM(BDAUXILIOMORADIA) BDAUXILIOMORADIA  from SP_VRHF_DADOS_IR_INT('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||',0,0,0, false,'||pratualizainfodescsimple||') '||
                'group by BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO ' ;

  -- Folha complementar
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS + COALESCE(BDDIARIA, 0),BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,BDVALABO,'||
                'BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,CAST(0 as INTEGER) BDCODTCA,BDBOLSAESTUDOS, BDAUXILIOMORADIA from SP_VRHF_DADOS_IR_FC('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||',0,'||prexportacao||', 0, false,'||pratualizainfodescsimple||',0,0'||') ' ;

  -- Adiantamento salarial
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS + COALESCE(BDDIARIA, 0),BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,BDVALABO,'||
                'BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,CAST(0 as INTEGER) BDCODTCA, BDBOLSAESTUDOS, BDAUXILIOMORADIA from SP_VRHF_DADOS_IR_AD('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||', false, '||pratualizainfodescsimple||') ' ;

  -- Férias
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS + COALESCE(BDDIARIA, 0),BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,BDVALABO,'||
                'BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,CAST(0 as INTEGER) BDCODTCA, 0 BDBOLSAESTUDOS, BDAUXILIOMORADIA from SP_VRHF_DADOS_IR_FE('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||','||prexportacao||', false, '||pratualizainfodescsimple||') ' ;

  -- 13º salário
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS + COALESCE(BDDIARIA, 0),BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,BDVALABO,'||
                'BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,CAST(0 as INTEGER) BDCODTCA, 0 BDBOLSAESTUDOS, BDAUXILIOMORADIA from SP_VRHF_DADOS_IR_13('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||', false, '||pratualizainfodescsimple||') ' ;

  -- Complemento de 13º salário
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS + COALESCE(BDDIARIA, 0),BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,BDVALABO,'||
                'BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,CAST(0 as INTEGER) BDCODTCA, 0 BDBOLSAESTUDOS, BDAUXILIOMORADIA from SP_VRHF_DADOS_IR_C13('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||', false, '||pratualizainfodescsimple||') ' ;

  -- 13º salário intermitente
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,sum(BDRENDTRIBUTAVEL),sum(BDINSS),sum(BDIR),max(BDDEP),sum(BDLUCROPJ),sum(BDDESPMED),sum(BDAJCUSTOS) + SUM(COALESCE(BDDIARIA, 0)),sum(BDPENJUD),'||
                'sum(BDPENALIM),sum(BDPREVPRIV),sum(BDINDRESC),sum(BDVALABO),sum(BDRENDISENTOS),max(BDDRENDISENTOS),max(BDDATAPGTO),max(BDINFADIC),CAST(0 as INTEGER) BDCODTCA, 0 BDBOLSAESTUDOS, SUM(BDAUXILIOMORADIA) BDAUXILIOMORADIA '||
         'from SP_VRHF_DADOS_IR_INT13('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||',0, false, '||pratualizainfodescsimple||') '||
         'group by BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO ' ;

  -- Folha avulsa
  wsql = wsql||'union all '||
         'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS + COALESCE(BDDIARIA, 0),BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,BDVALABO,'||
                'BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,BDCODTCA, 0 BDBOLSAESTUDOS, BDAUXILIOMORADIA from SP_VRHF_DADOS_IR_FA('||wemp||','||wcol||','||prrefini||','||prreffim||','||prpuxarfiliais||','||wmat||',0,'||prsemplr||', false,'||pratualizainfodescsimple||') ' ;

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC,
    :BDCODTCA,
    :BDBOLSAESTUDOS,
    :BDAUXILIOMORADIA
  DO
    begin
      if (prtabtemprra) then
         begin
           WSQLAUXTABTEMP = ' UPDATE OR INSERT INTO VRHF_TINFO_TEMP_RENDTRIBRRA (BDSESSAO,BDCODEMP, BDCODCOL,BDRENDIMENTOTRIBUTAVEL,BDIR,BDRENDTRIBNORMAL,BDIRNORMAL,BDRENDTRIBRT,BDIRRT) '||
                            ' VALUES ('||CURRENT_CONNECTION||','||BDCODEMP||','||BDCODCOL||',0,0,'||coalesce(BDRENDTRIBUTAVEL,0)||','||coalesce(BDIR, 0)||',0,0) MATCHING (BDSESSAO,BDCODEMP, BDCODCOL)';

           execute statement WSQLAUXTABTEMP;
         end
      if (coalesce(:BDRENDTRIBUTAVEL,0)=0) then
         :bddep = 0;
      SUSPEND;
    end
END^

/* Restore proc. body: SP_VRHF_DADOS_IR_FA */
create or alter procedure SP_VRHF_DADOS_IR_FA (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRSOMENTEPLR smallint = 0,
    PRSEMPLR smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDCODTCA integer,
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WCONTROL integer;
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WDESCVER varchar(40);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WDATAATU date;
declare variable WBASEIR numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSSN numeric(18,6);
declare variable WIR numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(999);
declare variable WCODTCA integer;
declare variable WCODTCAATU integer;
declare variable WDATA date;
declare variable WDESCTCA varchar(70);
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WORDEM integer;
declare variable WVALORDESCSIMPL numeric(9,2);
declare variable WVALORDIFDESCSIMPL numeric(9,2);
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WINCIDESOCIALFER integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WDIARIA numeric(18,6);
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
declare variable WTIPODEDUCAO integer;
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WGRAVARUBRICA integer;
BEGIN
  /*
      FOLHA AVULSA
  */

  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  IF (UPPER(prcodcol) = 'TEMP_FILTRO_COLCON_REL') THEN
     WUSARTMP_COL_SELECT = 1;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;


  IF (prpuxarfiliais = 0) THEN
     BEGIN
       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = 'select FOLN.BDREFIRRFESOCIAL, FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDCODTCA,FOL.BDDATAFA,FOL.BDCODVER,FOL.BDVALVFA,FOLN.BDDEPFA,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAIRRFESOCIAL AS BDDATAPROCFA,FOLN.BDHORAPROCFA,FOLN.BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
       ELSE
         wsql = 'select FOLN.BDREFIRRFESOCIAL, FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDCODTCA,FOL.BDDATAFA,FOL.BDCODVER,FOL.BDVALVFA,FOLN.BDDEPFA,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFA,FOLN.BDHORAPROCFA,FOLN.BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

       wsql = wsql||'from VRHF_EMP_TFOLHAAVULSA FOLN ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'INNER JOIN tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FOLN.BDCODEMP) ';
       IF (WUSARTMP_COL_SELECT = 1) THEN
          wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP and TEMP.BDCODCOL = FOLN.BDCODCOL) ';

       wsql = wsql||'join VRHF_EMP_TVERBAFA FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDCODTCA = FOLN.BDCODTCA and FOL.BDDATAFA = FOLN.BDDATAFA) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                    '                                     AND X.BDREFCOL <= FOLN.BDREF ORDER BY X.BDREFCOL DESC) '||
                    '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

       IF (prsomenteplr = 1) THEN
          wsql = wsql||'join vrh_base_ttipocalcavul CALCAVUL on (CALCAVUL.BDCODTCA = FOLN.BDCODTCA and CALCAVUL.BDCODCTP = 7) ';
       ELSE
       IF (prsemplr = 1) THEN
          wsql = wsql||'join vrh_base_ttipocalcavul CALCAVUL on (CALCAVUL.BDCODTCA = FOLN.BDCODTCA and CALCAVUL.BDCODCTP <> 7) ';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'where FOLN.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim||' ';
       ELSE
       wsql = wsql||'where FOLN.BDREF >= '||prrefini||' and FOLN.BDREF <= '||prreffim||' ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
          wsql = wsql||' and '||prcodcol;
     
       if (prveiodototalizador = 1) then
          wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDCODTCA,FOL.BDDATAFA,FOL.BDCODVER ';
       else
          wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDCODTCA,FOL.BDDATAFA ';
     END
  ELSE
     BEGIN
       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = 'select FOLN.BDREFIRRFESOCIAL, FOLN.BDCODEMP,FO.BDCODCOL,FO.BDCODTCA,FO.BDDATAFA,FO.BDCODVER,FO.BDVALVFA,FOLN.BDDEPFA,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAIRRFESOCIAL AS BDDATAPROCFA,FOLN.BDHORAPROCFA,FOLN.BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
       ELSE
         wsql = 'select FOLN.BDREFIRRFESOCIAL, FOLN.BDCODEMP,FO.BDCODCOL,FO.BDCODTCA,FO.BDDATAFA,FO.BDCODVER,FO.BDVALVFA,FOLN.BDDEPFA,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFA,FOLN.BDHORAPROCFA,FOLN.BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

       wsql = wsql||'from VRHF_EMP_TFOLHAAVULSA FOLN join TEMPRESAS EMAT on (EMAT.BDCODEMP = FOLN.BDCODEMP) ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'inner join TMP_EMPRESAS_SELECT TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP) ';
       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FOLN.BDCODEMP and TEM.BDCODCOL = FOLN.BDCODCOL) ';

       wsql = wsql||'join VRHF_EMP_TVERBAFA FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDCODTCA = FOLN.BDCODTCA and FO.BDDATAFA = FOLN.BDDATAFA) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                    '                                     AND X.BDREFCOL <= FOLN.BDREF ORDER BY X.BDREFCOL DESC) '||
                    '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

       IF (prsomenteplr = 1) THEN
          wsql = wsql||'join vrh_base_ttipocalcavul CALCAVUL on (CALCAVUL.BDCODTCA = FOLN.BDCODTCA and CALCAVUL.BDCODCTP = 7) ';
       ELSE
       IF (prsemplr = 1) THEN
          wsql = wsql||'join vrh_base_ttipocalcavul CALCAVUL on (CALCAVUL.BDCODTCA = FOLN.BDCODTCA and CALCAVUL.BDCODCTP <> 7) ';


       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'where FOLN.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim||' ';
       ELSE
       wsql = wsql||'where FOLN.BDREF >= '||prrefini||' and FOLN.BDREF <= '||prreffim||' ';
     
       wcontrol = 0;
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               BEGIN
                 wsql = wsql||' and (('||REPLACE(UPPER(prcodemp), 'FOL.', 'FOLN.')||')';
                 wcontrol = 1;
               END
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               BEGIN
                 wsql = wsql||' or ('||REPLACE(UPPER(prcodmatriz), 'FOL.', 'EMAT.')||')';
                 wcontrol = 1;
               END
          
            IF (wcontrol = 1) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
          wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'FOL.', 'FOLN.')||' ';

       if (prveiodototalizador = 1) then
          wsql = wsql||' order by FO.BDCODEMP,FO.BDCODCOL,FO.BDCODTCA,FO.BDDATAFA,FO.BDCODVER ';
       else
       wsql = wsql||' order by FO.BDCODEMP,FO.BDCODCOL,FO.BDCODTCA,FO.BDDATAFA ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wcodtcaatu = 0;
  wdataatu   = NULL;

  wbaseir    = 0;
  winssn     = 0;
  wir        = 0;
  wdepatu    = 0;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc   = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;
  wordem     = 0;
  wtipodeducao = 0;
  wvalordescsimpl = 0;
  wvalordifdescsimpl = 0;
  WINCIDESOCIAL = 0;
  WINCIDESOCIALFER = 0;
  wrefirrfesocialatu = -1;
  wdiaria = 0;

  BDCODFIR = 0;

  FOR EXECUTE STATEMENT wsql INTO :wrefirrfesocial,:wcodemp,:wcodcol,:wcodtca,:wdata,:wcodver,:wvalor,:wdep,:wclassif,:wdescver,:wdataproc,:whoraproc,:wordem,:wtipodeducao,:wvalordescsimpl,:wvalordifdescsimpl, :WCODCLA, :WTRIBUTACAOEXTERIOR DO
  BEGIN
    BDCODTIPO = 272;      -- Cálculos gerados pelo Único Folha

    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end

    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wcodtcaatu = 0) THEN
       wcodtcaatu = wcodtca;

    IF (wdataatu IS NULL) THEN
       wdataatu = wdata;

    if (wrefirrfesocialatu = -1) then
       wrefirrfesocialatu = wrefirrfesocial;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wcodtca <> wcodtcaatu) OR (wdata <> wdataatu)) THEN
       BEGIN
         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
         SELECT BDDESCTCA FROM VRH_BASE_TTIPOCALCAVUL WHERE BDCODTCA = :wcodtcaatu INTO :wdesctca;

         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              bdrefirrfesocial = wrefirrfesocialatu;
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefpagto;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir;
              BDINSS           = winssn;
              BDIR             = wir;
              BDDEP            = 0;

            IF (((wbaseir <> 0) or (PRVEIODOTOTALIZADOR > 0))  or (prveiodototalizador > 0))   THEN
               BDDEP            = wdepatu; -- Apenas incluir os dependentes se tiver base IR #11034

              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;
              BDPREVPRIV       = wprepri;
              BDINDRESC        = windresc;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDTIPO           = 50;    -- Folha avulsa
              BDINFADIC        = wcodtcaatu||' - '||wdesctca;
              BDCODTCA         = wcodtcaatu;
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;
              BDORDEM          = wordem;
              BDAUXILIOMORADIA = 0;
              BDDIARIA = WDIARIA;
              BDBOLSAMEDICO = 0;
              BDJUROSMORA = 0;
              BDINCIDESOCIAL = WINCIDESOCIAL;
              BDINCIDESOCIALFER = WINCIDESOCIALFER;
              SUSPEND;
            END

         wrefirrfesocialatu = wrefirrfesocial;
         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wcodtcaatu = wcodtca;
         wdataatu   = wdata;

         wbaseir    = 0;
         winssn     = 0;
         wir        = 0;
         wdepatu    = 0;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc   = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
         wordem     = 0;
         WINCIDESOCIAL = 0;
         WINCIDESOCIALFER = 0;
       END

    -- soma as bases
    wref = CAST((SUBSTRING(CAST(wdata AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdata AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

    WCODINCIDIRRF = 0;
    SELECT first 1 BDTIPOCODVER, BDIRVER, BDRENDISENTOIRVER, BDCODINCIDIRRF
    FROM vrh_base_tverbas_ref
    WHERE BDCODVER = :wcodver and BDREFVER <= :wref
    order by BDCODVER desc, BDREFVER desc
    INTO :wtipocodver,:wirver,:wrendisentover, :WCODINCIDIRRF;

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end



    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
       begin
          wirver = 0;
       end
    else
--    if (wtipocodver <= 1) then
       begin
         IF (wirver > 0) THEN -- IR
            BEGIN
              IF (wtipocodver = 0) THEN   -- provento
                 wbaseir = wbaseir + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN   -- desconto
                 BEGIN
                   --                                      INSS                                              Obrigações IR
                   IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '1.040') THEN
                      wbaseir = wbaseir - wvalor;
                 END
            END
         --                                     IR
         IF (SUBSTRING(wclassif FROM 1 FOR 7) = '9.010.1') THEN
            wir = wir + wvalor;
       end

         --                                     INSS
         IF (SUBSTRING(wclassif FROM 1 FOR 7) = '9.010.0') THEN
            winssn = winssn + wvalor;

         --                                     Lucro pessoa jurídica
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
            wlucropj = wlucropj + wvalor;
         --                                     Despesas médicas                                     Complemento de despesas médicas
         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.0') OR (SUBSTRING(wclassif FROM 1 FOR 9) = '0.420.0.2')) THEN
            wdespmed = wdespmed + wvalor;
         --                                     Ajuda de custos
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1') THEN
            wajcus = wajcus + wvalor;
         --                                     Pensões judiciais
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '1.040.0.0') THEN
            wpenjud = wpenjud + wvalor;
         --                                     Pensões alimentícias
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '1.040.0.1') THEN
            wpenalim = wpenalim + wvalor;
         --                                     Previdência privada
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.2') THEN
            wprepri = wprepri + wvalor;
         --                                     Diária
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.0' AND wirver = 0) THEN
            WDIARIA = WVALOR;
         --                                      Abono pec.                                      1/3 abono pec.                                  Abono pec. dobro                                1/3 abono pec.
         IF ((SUBSTRING(wclassif FROM 1 FOR 5) = '3.003') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.004') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.007') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.008')) THEN
                wvalabo = wvalabo + wvalor;
         -- Rendimentos isentos
         IF (UPPER(wrendisentover) = 'TRUE') THEN
            BEGIN
              wrendis = wrendis + wvalor;

              if (prveiodototalizador = 1) then
                 wdrendis = SUBSTRING(wdrendis||wdescver FROM 1 FOR 999);
              else
              wdrendis = SUBSTRING(wdrendis||wdescver FROM 1 FOR 200);
            END

         if (COALESCE(WCODINCIDIRRF, 0) IN (11,12,14,41,42,51,52,54)) then
            WINCIDESOCIAL = 1;

         if (COALESCE(WCODINCIDIRRF, 0) in (13,43,53)) then
            WINCIDESOCIALFER = 1;
       

    wdepatu = wdep;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wcodtcaatu <> 0 AND wdataatu IS NOT NULL) THEN
     BEGIN
       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
       SELECT BDDESCTCA FROM VRH_BASE_TTIPOCALCAVUL WHERE BDCODTCA = :wcodtcaatu INTO :wdesctca;

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            bdrefirrfesocial = wrefirrfesocialatu;
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefpagto;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir;
            BDINSS           = winssn;
            BDIR             = wir;
            BDDEP            = 0;

            IF (((wbaseir <> 0) or (PRVEIODOTOTALIZADOR > 0))  or (prveiodototalizador > 0))   THEN
               BDDEP            = wdepatu; -- Apenas incluir os dependentes se tiver base IR #11034

            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;
            BDPREVPRIV       = wprepri;
            BDINDRESC        = windresc;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 50;    -- Folha avulsa
            BDINFADIC        = wcodtcaatu||' - '||wdesctca;
            BDCODTCA         = wcodtcaatu;
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            BDAUXILIOMORADIA = 0;
            BDDIARIA = wdiaria;
            BDBOLSAMEDICO = 0;
            BDJUROSMORA = 0;
            BDINCIDESOCIAL = WINCIDESOCIAL;
            BDINCIDESOCIALFER = WINCIDESOCIALFER;
            SUSPEND;
          END
     END

  /*
      DADOS IMPORTADOS OU CADASTRADOS NA FICHA
  */

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),'||
              'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,'||
              'FOL.BDDATAFIR, '''||''' BDAUX, FOL.BDCODTCA, COALESCE(fol.BDAUXILIOMORADIAFIR,0), COALESCE(fol.BDDIARIAFIR,0), COALESCE(fol.BDBOLSAMEDICOFIR,0), COALESCE(fol.BDJUROSMORAFIR,0), fol.BDCODFIR, FOL.BDDEMDEV, COALESCE(FOL.BDCODTIPO, 201) BDCODTIPO,'||
              'VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FOL ';

       WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOL.BDCODEMP) and (HIST.BDCODCOL = FOL.BDCODCOL)  ';
       WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOL.BDCODEMP) and (VINC.BDCODCOL = FOL.BDCODCOL)  '||
                      '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                      '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL  '||
                      '                                     AND X.BDREFCOL <= FOL.BDREFIRFIR ORDER BY X.BDREFCOL DESC) '||
                      '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                      '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL)) ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       IF (prsomenteplr = 1) THEN
          wsql = wsql||'join vrh_base_ttipocalcavul CALCAVUL on (CALCAVUL.BDCODTCA = FOL.BDCODTCA and CALCAVUL.BDCODCTP = 7) ';
       ELSE
       IF (prsemplr = 1) THEN
          wsql = wsql||'join vrh_base_ttipocalcavul CALCAVUL on (CALCAVUL.BDCODTCA = FOL.BDCODTCA and CALCAVUL.BDCODCTP <> 7) ';

       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

       wsql = wsql||'where FOL.BDTIPOCALCFIR = 9500 and FOL.BDREFIRFIR >= '||prrefini||' and FOL.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select FA.BDCODEMP,FA.BDCODCOL,FA.BDCODTCA,FA.BDDATAFA from VRHF_EMP_TFOLHAAVULSA FA where FA.BDCODEMP = FOL.BDCODEMP and FA.BDCODCOL = FOL.BDCODCOL and '||
                                'FA.BDCODTCA = FOL.BDCODTCA and FA.BDDATAFA = FOL.BDDATAFIR) ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDDATAFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX, FO.BDCODTCA, COALESCE(fo.BDAUXILIOMORADIAFIR,0), COALESCE(fo.BDDIARIAFIR,0), COALESCE(fo.BDBOLSAMEDICOFIR,0), COALESCE(fo.BDJUROSMORAFIR,0), fo.BDCODFIR, FO.BDDEMDEV, COALESCE(FO.BDCODTIPO, 201) BDCODTIPO,'||
              'VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FO join TEMPRESAS EMAT on (EMAT.BDCODEMP = FO.BDCODEMP) ';

       WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FO.BDCODEMP) and (HIST.BDCODCOL = FO.BDCODCOL)  ';
       WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FO.BDCODEMP) and (VINC.BDCODCOL = FO.BDCODCOL)  '||
                      '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                      '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL  '||
                      '                                     AND X.BDREFCOL <= FO.BDREFIRFIR ORDER BY X.BDREFCOL DESC) '||
                      '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                      '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL)) ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wsql = wsql||'inner join tmp_empresas_select TEMP on (TEMP.BDCODEMP = FO.BDCODEMP) ';
       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FO.BDCODEMP and TEM.BDCODCOL = FO.BDCODCOL) ';

       IF (prsomenteplr = 1) THEN
          wsql = wsql||'join vrh_base_ttipocalcavul CALCAVUL on (CALCAVUL.BDCODTCA = FO.BDCODTCA and CALCAVUL.BDCODCTP = 7) ';
       ELSE
       IF (prsemplr = 1) THEN
          wsql = wsql||'join vrh_base_ttipocalcavul CALCAVUL on (CALCAVUL.BDCODTCA = FO.BDCODTCA and CALCAVUL.BDCODCTP <> 7) ';


       wsql = wsql||'where FO.BDTIPOCALCFIR = 9500 and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select FA.BDCODEMP,FA.BDCODCOL,FA.BDCODTCA,FA.BDDATAFA from VRHF_EMP_TFOLHAAVULSA FA where FA.BDCODEMP = FO.BDCODEMP and FA.BDCODCOL = FO.BDCODCOL and '||
                                'FA.BDCODTCA = FO.BDCODTCA and FA.BDDATAFA = FO.BDDATAFIR) ';
     
       wcontrol = 0;
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               BEGIN
                 wcontrol = 1;
                 wsql = wsql||' and (('||REPLACE(UPPER(prcodemp), 'FOL.', 'FO.')||')';
               END
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               BEGIN
                 wcontrol = 1;
                 wsql = wsql||' or ('||REPLACE(UPPER(prcodmatriz), 'FOL.', 'EMAT.')||')';
               END
     
            IF (wcontrol = 1) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
          wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'FOL.', 'FO.')||' ';

       wsql = wsql||' order by FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDDATAFIR ';
     END

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC,
    :BDCODTCA,
    :BDAUXILIOMORADIA,
    :BDDIARIA,
    :BDBOLSAMEDICO,
    :BDJUROSMORA,
    :BDCODFIR,
    :BDDEMDEV,
    :BDCODTIPO,
    :WCODCLA,
    :WTRIBUTACAOEXTERIOR
  DO
  BEGIN
    BDDATAPROC = BDDATAPGTO;
    BDHORAPROC = '00:00:00';

    bdrefirrfesocial = bdrefpag;

    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
       begin
          BDRENDTRIBUTAVEL = 0;
          BDIR = 0;
       end

    if (COALESCE(BDRENDTRIBUTAVEL, 0) <> 0) then
       BDINCIDESOCIAL = 1;

    SUSPEND;
  END
END^

/* Restore proc. body: SP_VRHF_DADOS_IR_FC_NORMAL */
create or alter procedure SP_VRHF_DADOS_IR_FC_NORMAL (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PREXPORTACAO integer = 0,
    PRPORCC smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVERCALCRRA integer = -1,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    WGCLASS varchar(13000),
    WDESCVER2 varchar(70),
    WI integer,
    BDORDEM integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDREFIRRFESOCIAL integer,
    BDVERCALCRRA integer,
    BDTIPODEDUCAOFOLHA integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(15,2),
    BDCODACCONV integer,
    BDMESESRRA numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFFC integer,
    BDINCIDESOCIALFER integer,
    BDCODTIPO integer)
as
declare variable WEHINDRESC varchar(5);
declare variable WISENTOABONO integer;
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WDATAPGTO date;
declare variable WCLASSIF varchar(20);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSSN numeric(18,6);
declare variable WIR numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(999);
declare variable WDATARESC date;
declare variable WCODPRES integer;
declare variable WDESCPRES varchar(110);
declare variable WREFAUXATU integer;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WBASEIRFE numeric(18,6);
declare variable WVALORIRFE numeric(18,6);
declare variable WRUBRICA integer;
declare variable WCATEGORIAESOCIAL integer;
declare variable WBOLSAESTUDOS numeric(18,6);
declare variable WDRENDIS2 varchar(999);
declare variable WDRENDIS3 varchar(999);
declare variable WREFIRRFESOCIAL integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WTIPODEDUCAO integer;
declare variable WVALORDESCSIMPL numeric(18,2);
declare variable WVALORDIFDESCSIMPL numeric(18,2);
declare variable WSQLAUX varchar(3000);
declare variable WTIPODEDUCAOATU integer;
declare variable WVALORDESCSIMPLATU numeric(18,2);
declare variable WVALORDIFDESCSIMPLATU numeric(18,2);
declare variable WVERCALCRRA integer;
declare variable WVERCALCRRAATU integer;
declare variable WCODACCONV integer;
declare variable WCODACCONVATU integer;
declare variable WREFAUX integer;
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WAUXILIOMORADIA numeric(18,6);
declare variable WDIARIA numeric(18,6);
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WJUROSMORA numeric(18,6);
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WINCIDESOCIALFER integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WGRAVARUBRICA integer;
begin
  /*
FOLHA COMPLEMENTAR NORMAL
*/
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  if (upper(PRCODEMP) = 'TMP_EMPRESAS_SELECT') then
    WUSARTMP_EMP_SELECT = 1;
  if (upper(PRCODCOL) = 'TEMP_FILTRO_COLCON_REL') then
    WUSARTMP_COL_SELECT = 1;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  if (PRPUXARFILIAIS = 0) then
  begin
    if (PRIRRFESOCIAL = true) then
      WSQL = 'select FOLN.bdrefirrfesocial, FOLN.BDVERCALCRRA,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDREFFC,FOL.BDCODVER,FOL.BDVALVFC,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
    else
      WSQL = 'select FOLN.bdrefirrfesocial, FOLN.BDVERCALCRRA,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDREFFC,FOL.BDCODVER,FOL.BDVALVFC,FOLN.BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

    wsql = wsql||'from VRHF_EMP_TFOLHACOMP FOLN ';

    if (WUSARTMP_EMP_SELECT = 1) then
      WSQL = WSQL || 'INNER JOIN tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
      WSQL = WSQL || 'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP and TEMP.BDCODCOL = FOLN.BDCODCOL) ';

    WSQL = WSQL || 'inner join VRHF_EMP_TVERBAFC FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDREFFN = FOLN.BDREFFN and FOL.BDREFFC = FOLN.BDREFFC) ';
    WSQL = WSQL || 'inner join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  ';
    if (PRIRRFESOCIAL = TRUE) THEN
       WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
    ELSE
       WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFCOMP ORDER BY X.BDREFCOL DESC) ';
     
    WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where FOLN.BDREFIRRFESOCIAL between ' || PRREFINI || ' and ' || PRREFFIM || ' ';
    else
      WSQL = WSQL || 'where FOLN.BDREFCOMP between ' || PRREFINI || ' and ' || PRREFFIM || ' ';

    if (PRCODEMP is not null and
        PRCODEMP <> '' and
        WUSARTMP_EMP_SELECT = 0) then
      WSQL = WSQL || ' and ' || PRCODEMP;

    if ((PRCODCOL is not null and
        PRCODCOL <> '') and
        (WUSARTMP_COL_SELECT = 0)) then
      WSQL = WSQL || ' and ' || PRCODCOL;

    if (coalesce(PRVERCALCRRA, -1) >= 0) then
      WSQL = WSQL || ' and FOLN.BDVERCALCRRA = ' || PRVERCALCRRA;

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDREFFC,FOL.BDCODVER ';
    else
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDREFFC ';
  end
  else
  begin
    if (PRIRRFESOCIAL = true) then
      WSQL = 'select FOLN.bdrefirrfesocial, FOLN.BDVERCALCRRA,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDREFFC,FO.BDCODVER,FO.BDVALVFC,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
    else
      WSQL = 'select FOLN.bdrefirrfesocial, FOLN.BDVERCALCRRA,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDREFFC,FO.BDCODVER,FO.BDVALVFC,FOLN.BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

    wsql = wsql||'from VRHF_EMP_TFOLHACOMP FOLN join TEMPRESAS EMAT on (EMAT.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_EMP_SELECT = 1) then
       WSQL = WSQL || 'inner join TMP_EMPRESAS_SELECT TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
      WSQL = WSQL || 'join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FOLN.BDCODEMP and TEM.BDCODCOL = FOLN.BDCODCOL) ';

    WSQL = WSQL || 'inner join VRHF_EMP_TVERBAFC FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDREFFN = FOLN.BDREFFN and FO.BDREFFC = FOLN.BDREFFC) ';
    WSQL = WSQL || 'inner join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  ';
    if (PRIRRFESOCIAL = TRUE) THEN
       WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
    ELSE
       WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFCOMP ORDER BY X.BDREFCOL DESC) ';
      
    WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                 '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where FOLN.BDREFIRRFESOCIAL between ' || PRREFINI || ' and ' || PRREFFIM || ' ';
    else
      WSQL = WSQL || 'where FOLN.BDREFCOMP >= ' || PRREFINI || ' and FOLN.BDREFCOMP <= ' || PRREFFIM || ' ';

    if (WUSARTMP_EMP_SELECT = 0) then
    begin
      if (PRCODEMP is not null and
          PRCODEMP <> '') then
        WSQL = WSQL || ' and ((' || REPLACE(UPPER(PRCODEMP), 'FOL.', 'FOLN.') || ')';

      if (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '') then
        WSQL = WSQL || ' or (' || REPLACE(UPPER(PRCODMATRIZ), 'FOL.', 'EMAT.') || ')';

      if ((PRCODEMP is not null and
          PRCODEMP <> '') or (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '')) then
        WSQL = WSQL || ') ';
    end

    if ((PRCODCOL is not null and
        PRCODCOL <> '') and
        (WUSARTMP_COL_SELECT = 0)) then
      WSQL = WSQL || ' and ' || REPLACE(UPPER(PRCODCOL), 'FOL.', 'FOLN.') || ' ';

    if (coalesce(PRVERCALCRRA, -1) >= 0) then
      WSQL = WSQL || ' and FOLN.BDVERCALCRRA = ' || PRVERCALCRRA;

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDREFFC,FO.BDCODVER ';
    else
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDREFFC ';
  end

  WEMPATU = 0;
  WCOLATU = 0;
  WREFATU = 0;
  WREFAUXATU = 0;
  WBASEIR = 0;
  WINSSN = 0;
  WIR = 0;
  WDEPATU = 0;
  WDATAATU = null;
  WLUCROPJ = 0;
  WDESPMED = 0;
  WAJCUS = 0;
  WBOLSAESTUDOS = 0;
  WPENJUD = 0;
  WPENALIM = 0;
  WPREPRI = 0;
  WINDRESC = 0;
  WVALABO = 0;
  WRENDIS = 0;
  WDRENDIS = '';
  WDRENDIS2 = '';
  WDRENDIS3 = '';
  WDATAPROCA = null;
  WHORAPROCA = null;
  WGCLASS = '';
  WBASEIRFE = 0;
  WVALORIRFE = 0;
  WREFIRRFESOCIALATU = 0;
  WTIPODEDUCAO = 0;
  WVALORDESCSIMPL = 0;
  WVALORDIFDESCSIMPL = 0;
  WTIPODEDUCAOATU = 0;
  WVALORDESCSIMPLATU = 0;
  WVALORDIFDESCSIMPLATU = 0;
  WVERCALCRRAATU = -1;
  WCODACCONVATU = -1;
  WAUXILIOMORADIA = 0;
  WDIARIA = 0;
  WBOLSAMEDICO = 0;
  WJUROSMORA = 0;
  WINCIDESOCIAL = 0;
  WINCIDESOCIALFER = 0;

  for execute statement WSQL
          into :WREFIRRFESOCIAL, :WVERCALCRRA, :WCODEMP, :WCODCOL, :WREF, :WREFAUX, :WCODVER, :WVALOR, :WDATAPGTO,
          :WDEP, :WCLASSIF, :WDATAPROC, :WHORAPROC, :WTIPODEDUCAO, :WVALORDESCSIMPL, :WVALORDIFDESCSIMPL, :WCODACCONV, :WCODCLA, :WTRIBUTACAOEXTERIOR
  do
  begin
    BDCODTIPO = 272; -- Cálculos do Único Folha

    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end

    if (WREFIRRFESOCIALATU = 0) then
      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;

    if (WVERCALCRRAATU = -1) then
      WVERCALCRRAATU = WVERCALCRRA;

    if (WCODACCONVATU = -1) then
      WCODACCONVATU = WCODACCONV;

    if (WEMPATU = 0) then
      WEMPATU = WCODEMP;

    if (WCOLATU = 0) then
      WCOLATU = WCODCOL;

    if (WREFATU = 0) then
      WREFATU = WREF;

    if (WREFAUXATU = 0) then
      WREFAUXATU = WREFAUX;

    if (WVALORDESCSIMPLATU = 0) then
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
    if (WVALORDIFDESCSIMPLATU = 0) then
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
    if (WTIPODEDUCAOATU = 0) then
      WTIPODEDUCAOATU = WTIPODEDUCAO;

    if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WREF <> WREFATU) or (WREFAUX <> WREFAUXATU)) then
    begin
      WCODPRES = null;
      WDESCPRES = null;
      WDATARESC = null;

      if (PRPREVIARESC = 1) then
      begin
        select X.BDDATARESCISAOPREV, X.BDCODPRES, Y.BDDESCPRES
        from VRH_EMP_TRESCISAO_PREVIA X
        join VRH_BASE_TPREPRESC Y on (Y.BDCODPRES = X.BDCODPRES)
        where X.BDCODEMP = :WEMPATU and
              X.BDCODCOL = :WCOLATU and
              X.BDREFRESCISAOPREV = :WREFATU
        into :WDATARESC, :WCODPRES, :WDESCPRES;
      end
      else
      begin
        select X.BDDATARESCISAO, X.BDCODPRES, Y.BDDESCPRES
        from VRH_EMP_TRESCISAO X
        join VRH_BASE_TPREPRESC Y on (Y.BDCODPRES = X.BDCODPRES)
        where X.BDCODEMP = :WEMPATU and
              X.BDCODCOL = :WCOLATU and
              X.BDREFRESCISAO = :WREFATU
        into :WDATARESC, :WCODPRES, :WDESCPRES;
      end

      WREFPAGTO = cast((substring(WREFAUXATU from 1 for 6)) as integer);

      if ((WREFPAGTO >= PRREFINI and
          WREFPAGTO <= PRREFFIM) or (PRIRRFESOCIAL = true)) then
      begin
        select first 1 BDCATEGORIAESOCIAL
        from VRHF_EMP_TCOLCON_FGTSGPS
        where BDCODEMP = :WEMPATU and
              BDCODCOL = :WCOLATU and
              BDREFCOL <= :WREFATU
        order by BDREFCOL desc
        into :WCATEGORIAESOCIAL;

        BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
        BDCODEMP = WEMPATU;
        BDCODCOL = WCOLATU;
        BDREF = WREFATU;
        BDREFPAG = WREFPAGTO;
        if (PRIRRFESOCIAL = true) then
          BDREFPAG = BDREFIRRFESOCIAL;
        BDREFFC = WREFAUXATU;
        BDRENDTRIBUTAVEL = WBASEIR;
        BDINSS = WINSSN;
        BDIR = WIR;
        BDDEP = WDEPATU;
        BDLUCROPJ = WLUCROPJ;
        BDDESPMED = WDESPMED;
        BDAJCUSTOS = WAJCUS;
        BDVERCALCRRA = WVERCALCRRAATU;
        BDTIPODEDUCAOFOLHA = WTIPODEDUCAOATU;
        BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
        if (WCATEGORIAESOCIAL = 903) then
        begin
          BDBOLSAESTUDOS = WBOLSAESTUDOS;
          if (coalesce(WDRENDIS2, '') <> '') then
          begin
            if (coalesce(WDRENDIS, '') <> '') then
              WDRENDIS = WDRENDIS || ', ';

            if (PRVEIODOTOTALIZADOR = 1) then
              WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 999);
            else
              WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 200);
          end
        end
        else
        begin
          BDAJCUSTOS = BDAJCUSTOS + WBOLSAESTUDOS;
          if (coalesce(WDRENDIS3, '') <> '') then
          begin
            if (coalesce(WDRENDIS, '') <> '') then
              WDRENDIS = WDRENDIS || ', ';

            if (PRVEIODOTOTALIZADOR = 1) then
              WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 999);
            else
              WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 200);
          end
        end
        BDPENJUD = WPENJUD;
        BDPENALIM = WPENALIM;
        BDPREVPRIV = WPREPRI;
        BDINDRESC = WINDRESC;
        BDVALABO = WVALABO;
        BDRENDISENTOS = WRENDIS;
        BDDRENDISENTOS = WDRENDIS;
        BDDATAPGTO = WDATAATU;
        BDDATAPROC = WDATAPROCA;
        BDHORAPROC = WHORAPROCA;
        BDCODACCONV = WCODACCONVATU;
        BDAUXILIOMORADIA = WAUXILIOMORADIA;
        BDDIARIA = WDIARIA;
        BDBOLSAMEDICO = WBOLSAMEDICO;
        BDJUROSMORA = WJUROSMORA;
        BDINCIDESOCIAL = WINCIDESOCIAL;
        BDINCIDESOCIALFER = WINCIDESOCIALFER;
        if (WDATARESC is not null) then
        begin
          BDTIPO = 110; -- Folha complementar rescisão
          BDINFADIC = WCODPRES || ' - ' || WDESCPRES;
        end
        else
        begin
          BDTIPO = 1; -- Folha complementar normal
          BDINFADIC = '';
        end
        BDMESESRRA = 0;
        if (PRATUALIZAINFODESCSIMPLE = true) then
        begin
          WSQLAUX = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, ' || ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, ' || ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) ' || ' values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPAGTO || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';

          execute statement WSQLAUX;
        end
        suspend;

        --              IF (((wvalorirfe >= 0) and (wbaseirfe > 0))  or (prveiodototalizador > 0)) THEN
        if ((WVALORIRFE >= 0) and
            (WBASEIRFE > 0)) then
        begin
          BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
          BDCODEMP = WEMPATU;
          BDCODCOL = WCOLATU;
          BDREF = WREFATU;
          BDORDEM = null;
          BDREFPAG = WREFPAGTO;
          if (PRIRRFESOCIAL = true) then
            BDREFPAG = BDREFIRRFESOCIAL;
          BDREFFC = WREFAUXATU;
          BDRENDTRIBUTAVEL = WBASEIRFE;
          BDINSS = 0;
          BDIR = WVALORIRFE;
          BDDEP = WDEPATU;
          BDLUCROPJ = 0;
          BDDESPMED = 0;
          BDAJCUSTOS = 0;
          BDPENJUD = 0;
          BDPENALIM = 0;
          BDPREVPRIV = 0;
          BDINDRESC = 0;
          BDVALABO = 0;
          BDRENDISENTOS = 0;
          BDDRENDISENTOS = '';
          BDDATAPGTO = WDATAATU;
          BDDATAPROC = WDATAPROCA;
          BDHORAPROC = WHORAPROCA;
          BDTIPO = 4;
          BDINFADIC = '';
          BDVERCALCRRA = WVERCALCRRAATU;
          BDTIPODEDUCAOFOLHA = WTIPODEDUCAOATU;
          BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
          BDAUXILIOMORADIA = 0;
          BDDIARIA = 0;
          BDBOLSAMEDICO = 0;
          BDJUROSMORA = 0;
          BDINCIDESOCIAL = 0;
          BDINCIDESOCIALFER = 0;
          suspend;
        end
      end
      WEMPATU = WCODEMP;
      WCOLATU = WCODCOL;
      WREFATU = WREF;
      WREFAUXATU = WREFAUX;
      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;
      WVERCALCRRAATU = WVERCALCRRA;
      WCODACCONVATU = WCODACCONV;
      WBASEIR = 0;
      WINSSN = 0;
      WIR = 0;
      WDEPATU = 0;
      WDATAATU = null;
      WLUCROPJ = 0;
      WDESPMED = 0;
      WAJCUS = 0;
      WBOLSAESTUDOS = 0;
      WPENJUD = 0;
      WPENALIM = 0;
      WPREPRI = 0;
      WINDRESC = 0;
      WVALABO = 0;
      WRENDIS = 0;
      WDRENDIS = '';
      WDRENDIS2 = '';
      WDRENDIS3 = '';
      WGCLASS = '';
      WBASEIRFE = 0;
      WVALORIRFE = 0;
      WTIPODEDUCAOATU = WTIPODEDUCAO;
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
      WAUXILIOMORADIA = 0;
      WDIARIA = 0;
      WBOLSAMEDICO = 0;
      WJUROSMORA = 0;
      WINCIDESOCIAL = 0;
      WINCIDESOCIALFER = 0;
    end

    -- soma as bases
    WCODINCIDIRRF = 0;
    select first 1 BDTIPOCODVER, coalesce(BDIRVER, 0), BDRENDISENTOIRVER, BDINDRESC, BDCODINCIDIRRF
    from VRH_BASE_TVERBAS_REF
    where BDCODVER = :WCODVER and
          BDREFVER <= :WREFATU
    order by BDCODVER desc, BDREFVER desc
    into :WTIPOCODVER, :WIRVER, :WRENDISENTOVER, WEHINDRESC, :WCODINCIDIRRF;

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end
    --    if (wtipocodver <= 1) then
    begin
     if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
       begin
         WIRVER = 0;
       end
     else
     begin
          --    if (wtipocodver <= 1) then
      if (WIRVER = 1) then -- IR Folha normal
      begin
        if (WTIPOCODVER = 0) then -- provento
          WBASEIR = WBASEIR + WVALOR;
        else
        if (WTIPOCODVER = 1) then -- desconto
        begin
          --                                      INSS                                              Obrigações IR
          if (substring(WCLASSIF from 1 for 7) <> '9.010.0' and
              substring(WCLASSIF from 1 for 5) <> '0.030') then
            WBASEIR = WBASEIR - WVALOR;
        end
      end

      if (WIRVER = 2) then -- IR Férias
      begin
        if (WTIPOCODVER = 0) then -- provento
          WBASEIRFE = WBASEIRFE + WVALOR;
        else
        if (WTIPOCODVER = 1) then -- desconto
        begin
          --                                      INSS                                              Obrigações IR
          if (substring(WCLASSIF from 1 for 7) <> '9.010.0' and
              substring(WCLASSIF from 1 for 5) <> '0.030' and
              substring(WCLASSIF from 1 for 7) <> '3.001.8') then
            WBASEIRFE = WBASEIRFE - WVALOR;
        end
      end

        -- IR folha normal
        if ((substring(WCLASSIF from 1 for 9) = '9.010.1.0') and
            (WDESCVER2 <> 'IR Férias (COVID-19)')) then
          WIR = WIR + WVALOR;
        -- IR férias
        if ((substring(WCLASSIF from 1 for 9) = '9.010.1.0') and
            (WDESCVER2 = 'IR Férias (COVID-19)')) then
          WVALORIRFE = WVALORIRFE + WVALOR;
     end

      WDESCVER2 = '';
      select first 1 BDDESCVER
      from VRH_BASE_TVERBAS
      where BDCODVER = :WCODVER
      into WDESCVER2;
      -- INSS folha normal
      if (substring(WCLASSIF from 1 for 9) = '9.010.0.0') then
        WINSSN = WINSSN + WVALOR;
      -- Lucro pessoa jurídica
      if (substring(WCLASSIF from 1 for 9) = '0.040.0.2') then
        WLUCROPJ = WLUCROPJ + WVALOR;
      -- Despesas médicas              Complemento de despesas médicas
      if ((substring(WCLASSIF from 1 for 9) = '0.030.1.0') or (substring(WCLASSIF from 1 for 9) = '0.420.0.2') or (substring(WCLASSIF from 1 for 9) = '3.010.0.0')) then
        WDESPMED = WDESPMED + WVALOR;
      -- Ajuda de custos
      if (substring(WCLASSIF from 1 for 9) = '0.040.0.1' and
          WIRVER = 0) then
      begin
        select first 1 BDCHAVE
        from VRH_BASE_TRUBRICAESOCIAL_VER
        where BDCODVER = :WCODVER
        into :WRUBRICA;
        if (WRUBRICA = 1350) then -- Bolsa estudos
        begin
          WBOLSAESTUDOS = WBOLSAESTUDOS + WVALOR;
          if (WDRENDIS2 <> '') then
            WDRENDIS2 = WDRENDIS2 || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS2 = substring(WDRENDIS2 || 'Bolsa de estudos' from 1 for 999);
          else
            WDRENDIS2 = substring(WDRENDIS2 || 'Bolsa de estudos' from 1 for 200);

          if (WDRENDIS3 <> '') then
            WDRENDIS3 = WDRENDIS3 || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS3 = substring(WDRENDIS3 || WDESCVER2 from 1 for 999);
          else
            WDRENDIS3 = substring(WDRENDIS3 || WDESCVER2 from 1 for 200);
        end
        else
          WAJCUS = WAJCUS + WVALOR;
      end
      -- Pensões judiciais
      if (substring(WCLASSIF from 1 for 9) = '0.030.0.0') then
        WPENJUD = WPENJUD + WVALOR;
      -- Pensões alimentícias
      if (substring(WCLASSIF from 1 for 9) = '0.030.0.1') then
        WPENALIM = WPENALIM + WVALOR;
      -- Previdência privada
      if (substring(WCLASSIF from 1 for 9) = '0.030.1.2') then
        WPREPRI = WPREPRI + WVALOR;

      if (upper(WEHINDRESC) = 'TRUE') then
      begin
        if (WTIPOCODVER in (0, 2)) then -- Provento
          WINDRESC = WINDRESC + WVALOR;
        else
        if (WTIPOCODVER in (1, 3)) then -- Desconto
          WINDRESC = WINDRESC - WVALOR;
      end

      if (substring(WCLASSIF from 1 for 9) = '0.040.0.3') then
        WAUXILIOMORADIA = WAUXILIOMORADIA + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.040.0.0' and
          WIRVER = 0) then
        WDIARIA = WDIARIA + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.910.0.0') then
        WBOLSAMEDICO = WBOLSAMEDICO + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.920.0.0') then
        WJUROSMORA = WJUROSMORA + WVALOR;

      if (coalesce(WCODINCIDIRRF, 0) in (11, 12, 14, 41, 42, 51, 52, 54)) then
        WINCIDESOCIAL = 1;

      if (coalesce(WCODINCIDIRRF, 0) in (13, 43, 53)) then
        WINCIDESOCIALFER = 1;

      WISENTOABONO = 0;
      --          Complemento de abono pecuniário                  Compl. 1/3 abono pecuniário
      if (((substring(WCLASSIF from 1 for 7) = '0.210.2') or (substring(WCLASSIF from 1 for 7) = '0.210.3')) and
          (WIRVER <> 1)) then
        WVALABO = WVALABO + WVALOR;
      else

      -- Rendimentos isentos
      if ((upper(WRENDISENTOVER) = 'TRUE') and
          (WISENTOABONO = 0)) then
      begin
        WRENDIS = WRENDIS + WVALOR;
        WI = 0;

        if (PRVEIODOTOTALIZADOR = 1) then
          select POS
          from POS(:WCLASSIF, :WGCLASS)
          into :WI;
        else
          select POS
          from POS(substring(:WCLASSIF from 1 for 5), :WGCLASS)
          into :WI;

        if (WI = 0) then
        begin
          WDESCVER2 = '';

          if (PRVEIODOTOTALIZADOR = 1) then
          begin
            select first 1 BDDESCVER
            from VRH_BASE_TVERBAS
            where BDCLAVER = :WCLASSIF
            into WDESCVER2;
            WGCLASS = WGCLASS || ';' || :WCLASSIF;
          end
          else
          begin
            select first 1 BDDESCVER
            from VRH_BASE_TVERBAS
            where BDCLAVER = substring(:WCLASSIF from 1 for 5)
            into WDESCVER2;
            WGCLASS = WGCLASS || ';' || substring(:WCLASSIF from 1 for 5);
          end

          if (WDRENDIS <> '') then
            WDRENDIS = WDRENDIS || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS = substring(WDRENDIS || WDESCVER2 from 1 for 999);
          else
            WDRENDIS = substring(WDRENDIS || WDESCVER2 from 1 for 200);
        end
      end
    end

    WDEPATU = WDEP;
    WDATAATU = WDATAPGTO;
    WDATAPROCA = WDATAPROC;
    WHORAPROCA = WHORAPROC;
  end

  if (WEMPATU <> 0 and
      WCOLATU <> 0 and
      WREFATU <> 0 and
      WREFAUXATU <> 0) then
  begin
    WCODPRES = null;
    WDESCPRES = null;
    WDATARESC = null;

    if (PRPREVIARESC = 1) then
    begin
      select X.BDDATARESCISAOPREV, X.BDCODPRES, Y.BDDESCPRES
      from VRH_EMP_TRESCISAO_PREVIA X
      join VRH_BASE_TPREPRESC Y on (Y.BDCODPRES = X.BDCODPRES)
      where X.BDCODEMP = :WEMPATU and
            X.BDCODCOL = :WCOLATU and
            X.BDREFRESCISAOPREV = :WREFATU
      into :WDATARESC, :WCODPRES, :WDESCPRES;
    end
    else
    begin
      select X.BDDATARESCISAO, X.BDCODPRES, Y.BDDESCPRES
      from VRH_EMP_TRESCISAO X
      join VRH_BASE_TPREPRESC Y on (Y.BDCODPRES = X.BDCODPRES)
      where X.BDCODEMP = :WEMPATU and
            X.BDCODCOL = :WCOLATU and
            X.BDREFRESCISAO = :WREFATU
      into :WDATARESC, :WCODPRES, :WDESCPRES;
    end

    WREFPAGTO = cast((substring(WREFAUXATU from 1 for 6)) as integer);

    if (((WREFPAGTO >= PRREFINI and
        WREFPAGTO <= PRREFFIM) or (PRIRRFESOCIAL = true)) or (PRVEIODOTOTALIZADOR > 0)) then
    begin
      select first 1 BDCATEGORIAESOCIAL
      from VRHF_EMP_TCOLCON_FGTSGPS
      where BDCODEMP = :WEMPATU and
            BDCODCOL = :WCOLATU and
            BDREFCOL <= :WREFATU
      order by BDREFCOL desc
      into :WCATEGORIAESOCIAL;

      BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
      BDCODEMP = WEMPATU;
      BDCODCOL = WCOLATU;
      BDREF = WREFATU;
      BDREFPAG = WREFPAGTO;
      if (PRIRRFESOCIAL = true) then
        BDREFPAG = BDREFIRRFESOCIAL;
      BDREFFC = WREFAUXATU;
      BDRENDTRIBUTAVEL = WBASEIR;
      BDINSS = WINSSN;
      BDIR = WIR;
      BDDEP = WDEPATU;
      BDLUCROPJ = WLUCROPJ;
      BDDESPMED = WDESPMED;
      BDAJCUSTOS = WAJCUS;
      if (WCATEGORIAESOCIAL = 903) then
      begin
        BDBOLSAESTUDOS = WBOLSAESTUDOS;
        if (coalesce(WDRENDIS2, '') <> '') then
        begin
          if (coalesce(WDRENDIS, '') <> '') then
            WDRENDIS = WDRENDIS || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 999);
          else
            WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 200);
        end
      end
      else
      begin
        BDAJCUSTOS = BDAJCUSTOS + WBOLSAESTUDOS;
        if (coalesce(WDRENDIS3, '') <> '') then
        begin
          if (coalesce(WDRENDIS, '') <> '') then
            WDRENDIS = WDRENDIS || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 999);
          else
            WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 200);
        end
      end
      BDPENJUD = WPENJUD;
      BDPENALIM = WPENALIM;
      BDPREVPRIV = WPREPRI;
      BDINDRESC = WINDRESC;
      BDVALABO = WVALABO;
      BDRENDISENTOS = WRENDIS;
      BDDRENDISENTOS = WDRENDIS;
      BDDATAPGTO = WDATAATU;
      BDDATAPROC = WDATAPROCA;
      BDHORAPROC = WHORAPROCA;
      BDVERCALCRRA = WVERCALCRRAATU;
      BDTIPODEDUCAOFOLHA = WTIPODEDUCAOATU;
      BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
      BDCODACCONV = WCODACCONVATU;
      BDAUXILIOMORADIA = WAUXILIOMORADIA;
      BDDIARIA = WDIARIA;
      BDBOLSAMEDICO = WBOLSAMEDICO;
      BDJUROSMORA = WJUROSMORA;
      BDINCIDESOCIAL = WINCIDESOCIAL;
      BDINCIDESOCIALFER = WINCIDESOCIALFER;
      if (WDATARESC is not null) then
      begin
        BDTIPO = 110; -- Folha complementar rescisão
        BDINFADIC = WCODPRES || ' - ' || WDESCPRES;
      end
      else
      begin
        BDTIPO = 1; -- Folha complementar normal
        BDINFADIC = '';
      end

      if (PRATUALIZAINFODESCSIMPLE = true) then
      begin
        WSQLAUX = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, ' || ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, ' || ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) ' || ' values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPAGTO || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';

        execute statement WSQLAUX;
      end
      BDMESESRRA = 0;
      suspend;

      if ((WVALORIRFE >= 0) and
          (WBASEIRFE > 0)) then
      begin
        BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
        BDCODEMP = WEMPATU;
        BDCODCOL = WCOLATU;
        BDREF = WREFATU;
        BDORDEM = null;
        BDREFPAG = WREFPAGTO;
        if (PRIRRFESOCIAL = true) then
          BDREFPAG = BDREFIRRFESOCIAL;
        BDREFFC = WREFAUXATU;
        BDRENDTRIBUTAVEL = WBASEIRFE;
        BDINSS = 0;
        BDIR = WVALORIRFE;
        BDDEP = WDEPATU;
        BDLUCROPJ = 0;
        BDDESPMED = 0;
        BDAJCUSTOS = 0;
        BDPENJUD = 0;
        BDPENALIM = 0;
        BDPREVPRIV = 0;
        BDINDRESC = 0;
        BDVALABO = 0;
        BDRENDISENTOS = 0;
        BDDRENDISENTOS = '';
        BDDATAPGTO = WDATAATU;
        BDDATAPROC = WDATAPROCA;
        BDHORAPROC = WHORAPROCA;
        BDTIPO = 4;
        BDINFADIC = '';
        BDTIPODEDUCAOFOLHA = WTIPODEDUCAOATU;
        BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
        BDAUXILIOMORADIA = 0;
        BDDIARIA = 0;
        BDBOLSAMEDICO = 0;
        BDJUROSMORA = 0;
        BDINCIDESOCIAL = 0;
        BDINCIDESOCIALFER = 0;
        suspend;
      end
    end
  end

end^

/* Restore proc. body: SP_VRHF_DADOS_IR_FICHAFC */
create or alter procedure SP_VRHF_DADOS_IR_FICHAFC (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRVERCALCRRA integer = -1)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDREFIRRFESOCIAL integer,
    BDVERCALCRRA integer,
    BDTIPODEDUCAOFOLHA integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(15,2),
    BDCODACCONV integer,
    BDMESESRRA numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFFC integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDCODTIPO integer)
as
declare variable WSQL varchar(32700);
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WVERCALCRRA integer;
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
BEGIN

  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  IF (UPPER(prcodcol) = 'TEMP_FILTRO_COLCON_REL') THEN
     WUSARTMP_COL_SELECT = 1;

  BDORDEM = null;
  BDBOLSAESTUDOS = null;
  BDTIPODEDUCAOFOLHA = null;
  BDVALORDESCONTOSIMPLIFICADO = null;
  BDCODACCONV = null;
  BDINCIDESOCIALFER = 0;
/*
DADOS IMPORTADOS OU CADASTRADOS NA FICHA
*/
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDREFIRFIR,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),'||
              'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,'||
              'FOL.BDDATAFIR, '''||''' BDAUX, COALESCE(RRA.BDCODPERRRA,-1) BDCODPERRRA, RRA.BDQTDMESESRRA, fol.BDAUXILIOMORADIAFIR, fol.BDDIARIAFIR, fol.BDBOLSAMEDICOFIR, fol.BDJUROSMORAFIR, fol.BDCODFIR, FOL.BDDEMDEV, COALESCE(FOL.BDCODTIPO, 201) BDCODTIPO, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

       wsql = wsql||'left outer join VRHF_EMP_TFOLHACOMP FC on (FC.BDCODEMP = FOL.BDCODEMP and '||
                         'FC.BDCODCOL = FOL.BDCODCOL and FC.BDREFFN = FOL.BDREFFIR and FC.BDDATAPAGFC = FOL.BDDATAFIR) '||
                    'left outer join VRHF_EMP_TFOLTOMCOMP FCT on (FCT.BDCODEMP = FOL.BDCODEMP and '||
                         'FCT.BDCODCOL = FOL.BDCODCOL and FCT.BDREFTOMADOR = FOL.BDREFFIR and FCT.BDDATAPAGFC = FOL.BDDATAFIR) '||
                    'left outer join VRHF_BASE_TPERIODORRA RRA ON FOL.BDCODPERRRA = RRA.BDCODPERRRA ';

       wsql = wsql||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOL.BDCODEMP) and (HIST.BDCODCOL = FOL.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOL.BDCODEMP) and (VINC.BDCODCOL = FOL.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL  '||
                    '                                     AND X.BDREFCOL <= FOL.BDREFFIR ORDER BY X.BDREFCOL DESC) '||
                    '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL)) ';

       wsql = wsql||'where FOL.BDTIPOCALCFIR in (9010,9011) and FOL.BDREFIRFIR >= '||prrefini||' and FOL.BDREFIRFIR <= '||prreffim||' and '||
                    'FC.BDDATAPAGFC is null and '||
                    'FCT.BDDATAPAGFC is null ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF ((prcodcol IS NOT NULL AND prcodcol <> '') AND (WUSARTMP_COL_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodcol;

      wsql = wsql||' and coalesce((select first 1 X.BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS X '||
                   ' where X.BDCODEMP = FOL.BDCODEMP and X.BDCODCOL = FOL.BDCODCOL and X.BDREFCOL <= FOl.BDREFIRFIR order by x.BDREFCOL desc), '||
                   '(select first 1 X.BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS X where X.BDCODEMP = FOL.BDCODEMP and '||
                   ' X.BDCODCOL = FOL.BDCODCOL order by x.BDREFCOL)) <> 111 ';

       if (COALESCE(prvercalcrra, -1) = 0) then
          wsql = wsql||' and COALESCE(RRA.BDCODPERRRA, -1) < 0 ';

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDDATAFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FO.BDREFIRFIR,FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX, COALESCE(RRA.BDCODPERRRA,-1) BDCODPERRRA, RRA.BDQTDMESESRRA, fo.BDAUXILIOMORADIAFIR, fo.BDDIARIAFIR, fo.BDBOLSAMEDICOFIR, fo.BDJUROSMORAFIR, fo.BDCODFIR, FO.BDDEMDEV, COALESCE(FO.BDCODTIPO, 201) BDCODTIPO, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FO join TEMPRESAS EMAT on (EMAT.BDCODEMP = FO.BDCODEMP) ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wsql = wsql||'inner join tmp_empresas_select TEMP on (TEMP.BDCODEMP = FO.BDCODEMP) ';

       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FO.BDCODEMP and TEM.BDCODCOL = FO.BDCODCOL) ';

       wsql = wsql||'left outer join VRHF_EMP_TFOLHACOMP FC on (FC.BDCODEMP = FO.BDCODEMP and '||
                         'FC.BDCODCOL = FO.BDCODCOL and FC.BDREFFN = FO.BDREFFIR and FC.BDDATAPAGFC = FO.BDDATAFIR) '||
                    'left outer join VRHF_EMP_TFOLTOMCOMP FCT on (FCT.BDCODEMP = FO.BDCODEMP and '||
                         'FCT.BDCODCOL = FO.BDCODCOL and FCT.BDREFTOMADOR = FO.BDREFFIR and FCT.BDDATAPAGFC = FO.BDDATAFIR) '||
                    'left outer join VRHF_BASE_TPERIODORRA RRA ON FO.BDCODPERRRA = RRA.BDCODPERRRA ';

       wsql = wsql||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FO.BDCODEMP) and (HIST.BDCODCOL = FO.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FO.BDCODEMP) and (VINC.BDCODCOL = FO.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL  '||
                    '                                     AND X.BDREFCOL <= FO.BDREFFIR ORDER BY X.BDREFCOL DESC) '||
                    '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL)) ';

       wsql = wsql||'where FO.BDTIPOCALCFIR in (9010,9011) and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    'FC.BDDATAPAGFC is null and '||
                    'FCT.BDDATAPAGFC is null ';

       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||REPLACE(UPPER(prcodemp), 'FOL.', 'FO.')||')';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||REPLACE(UPPER(prcodmatriz), 'FOL.', 'EMAT.')||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF ((prcodcol IS NOT NULL AND prcodcol <> '') AND (WUSARTMP_COL_SELECT = 0)) THEN
          wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'FOL.', 'FO.')||' ';

       if (COALESCE(prvercalcrra, -1) = 0) then
          wsql = wsql||' and COALESCE(RRA.BDCODPERRRA, -1) < 0 ';

      wsql = wsql||' and coalesce((select first 1 X.BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS X '||
                   ' where X.BDCODEMP = FO.BDCODEMP and X.BDCODCOL = FO.BDCODCOL and X.BDREFCOL <= FO.BDREFIRFIR order by x.BDREFCOL desc), '||
                   '(select first 1 X.BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS X where X.BDCODEMP = FO.BDCODEMP and '||
                   ' X.BDCODCOL = FO.BDCODCOL order by x.BDREFCOL)) <> 111 ';

       wsql = wsql||' order by FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDDATAFIR ';
     END

  FOR EXECUTE STATEMENT wsql INTO :bdrefirrfesocial,:BDCODEMP,:BDCODCOL,:BDREF,:BDREFPAG,:BDTIPO,:BDRENDTRIBUTAVEL,:BDINSS,:BDIR,:BDDEP,:BDLUCROPJ,:BDDESPMED,:BDAJCUSTOS,:BDPENJUD,:BDPENALIM,:BDPREVPRIV,:BDINDRESC,:BDVALABO,:BDRENDISENTOS,:BDDRENDISENTOS,:BDDATAPGTO,:BDINFADIC,:WVERCALCRRA,:BDMESESRRA, :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA, :BDCODFIR, :BDDEMDEV, :BDCODTIPO, :WCODCLA, :WTRIBUTACAOEXTERIOR
  DO
  BEGIN
    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
      begin
         BDRENDTRIBUTAVEL = 0;
         BDIR = 0;
      end

    BDDATAPROC = BDDATAPGTO;
    BDHORAPROC = '00:00:00';
    BDVERCALCRRA = 0;
    if (coalesce(wvercalcrra,-1) > 0) then
       BDVERCALCRRA = 1;

    if (COALESCE(BDRENDTRIBUTAVEL, 0) <> 0) then
       BDINCIDESOCIAL = 1;

    BDREFFC = null;

    SUSPEND;
  END
END^

/* Restore proc. body: SP_VRHF_DADOS_IR_FC */
create or alter procedure SP_VRHF_DADOS_IR_FC (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PREXPORTACAO integer = 0,
    PRPORCC smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVERCALCRRA integer = -1,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    WGCLASS varchar(13000),
    WDESCVER2 varchar(70),
    WI integer,
    BDORDEM integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDREFIRRFESOCIAL integer,
    BDVERCALCRRA integer,
    BDTIPODEDUCAOFOLHA integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(15,2),
    BDCODACCONV integer,
    BDMESESRRA numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFFC integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDCODTIPO integer)
as
declare variable WEHINDRESC varchar(5);
declare variable WISENTOABONO integer;
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WDATAPGTO date;
declare variable WCLASSIF varchar(20);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSSN numeric(18,6);
declare variable WIR numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(999);
declare variable WDATARESC date;
declare variable WCODPRES integer;
declare variable WDESCPRES varchar(110);
declare variable WREFAUXATU integer;
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WDESCCC varchar(100);
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WBASEIRFE numeric(18,6);
declare variable WVALORIRFE numeric(18,6);
declare variable WRUBRICA integer;
declare variable WCATEGORIAESOCIAL integer;
declare variable WBOLSAESTUDOS numeric(18,6);
declare variable WDRENDIS2 varchar(999);
declare variable WDRENDIS3 varchar(999);
declare variable WREFIRRFESOCIAL integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WTIPODEDUCAO integer;
declare variable WVALORDESCSIMPL numeric(18,2);
declare variable WVALORDIFDESCSIMPL numeric(18,2);
declare variable WSQLAUX varchar(3000);
declare variable WTIPODEDUCAOATU integer;
declare variable WVALORDESCSIMPLATU numeric(18,2);
declare variable WVALORDIFDESCSIMPLATU numeric(18,2);
declare variable WVERCALCRRA integer;
declare variable WVERCALCRRAATU integer;
declare variable WCODACCONV integer;
declare variable WCODACCONVATU integer;
declare variable WREFAUX integer;
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WAUXILIOMORADIA numeric(18,6);
declare variable WDIARIA numeric(18,6);
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WJUROSMORA numeric(18,6);
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WINCIDESOCIALFER integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WGRAVARUBRICA integer;
begin

  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  if (upper(PRCODEMP) = 'TMP_EMPRESAS_SELECT') then
    WUSARTMP_EMP_SELECT = 1;

  if (upper(PRCODCOL) = 'TEMP_FILTRO_COLCON_REL') then
    WUSARTMP_COL_SELECT = 1;

  BDCODFIR = 0;

  -- Folha complementar Normal
  for select BDCODEMP, BDCODCOL, BDREF, BDREFPAG, BDTIPO, BDRENDTRIBUTAVEL, BDINSS, BDIR, BDDEP, BDLUCROPJ, BDDESPMED,
             BDAJCUSTOS, BDPENJUD, BDPENALIM, BDPREVPRIV, BDINDRESC, BDVALABO, BDRENDISENTOS, BDDRENDISENTOS,
             BDDATAPGTO, BDINFADIC, BDDATAPROC, BDHORAPROC, WGCLASS, WDESCVER2, WI, BDORDEM, BDBOLSAESTUDOS,
             BDREFIRRFESOCIAL, BDVERCALCRRA, BDTIPODEDUCAOFOLHA, BDVALORDESCONTOSIMPLIFICADO, BDCODACCONV, BDMESESRRA,
             BDAUXILIOMORADIA, BDDIARIA, BDBOLSAMEDICO, BDJUROSMORA, BDINCIDESOCIAL, BDREFFC, BDINCIDESOCIALFER,
             BDCODTIPO
      from SP_VRHF_DADOS_IR_FC_NORMAL(:PRCODEMP, :PRCODCOL, :PRREFINI, :PRREFFIM, :PRPUXARFILIAIS, :PRCODMATRIZ, :PRPREVIARESC, :PREXPORTACAO, :PRPORCC, :PRIRRFESOCIAL, :PRATUALIZAINFODESCSIMPLE, :PRVERCALCRRA, :PRVEIODOTOTALIZADOR)
      into :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR, :BDDEP, :BDLUCROPJ,
           :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM, :BDPREVPRIV, :BDINDRESC, :BDVALABO, :BDRENDISENTOS,
           :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDDATAPROC, :BDHORAPROC, :WGCLASS, :WDESCVER2, :WI, :BDORDEM,
           :BDBOLSAESTUDOS, :BDREFIRRFESOCIAL, :BDVERCALCRRA, :BDTIPODEDUCAOFOLHA, :BDVALORDESCONTOSIMPLIFICADO,
           :BDCODACCONV, :BDMESESRRA, :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA, :BDINCIDESOCIAL,
           :BDREFFC, :BDINCIDESOCIALFER, :BDCODTIPO
  do
    suspend;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  /*
FOLHA COMPLEMENTAR TOMADOR
*/
  if (PRPUXARFILIAIS = 0) then
  begin
    if (PRIRRFESOCIAL = true) then
      WSQL = 'select FOLN.bdrefirrfesocial, FOLN.BDVERCALCRRA, FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDREFFC,FOL.BDCODVER,FOL.BDVALVFC,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';
    else
      WSQL = 'select FOLN.bdrefirrfesocial, FOLN.BDVERCALCRRA, FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDREFFC,FOL.BDCODVER,FOL.BDVALVFC,FOLN.BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';

    wsql = wsql||'from VRHF_EMP_TFOLTOMCOMP FOLN ';

    if (WUSARTMP_EMP_SELECT = 1) then
       WSQL = WSQL || 'INNER JOIN tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
       WSQL = WSQL || 'JOIN TEMP_FILTRO_COLCON_REL TEM ON (TEM.BDCODEMP = FOLN.BDCODEMP AND TEM.BDCODCOL = FOLN.BDCODCOL) ';

    WSQL = WSQL || 'inner join VRHF_EMP_TVERBAFCTOMADOR FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDREFTOMADOR = FOLN.BDREFTOMADOR and FOL.BDORDEM = FOLN.BDORDEM and FOL.BDREFFC = FOLN.BDREFFC) ';
    WSQL = WSQL || 'inner join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOLN.BDREFTOMADOR ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where FOLN.BDREFIRRFESOCIAL between ' || PRREFINI || ' and ' || PRREFFIM || ' ';
    else
      WSQL = WSQL || 'where FOLN.BDREFFC >= ' || PRREFINI || '01 and FOLN.BDREFFC <= ' || PRREFFIM || '31 ';

    if (PRCODEMP is not null and
        PRCODEMP <> '' and
        WUSARTMP_EMP_SELECT = 0) then
      WSQL = WSQL || ' and ' || PRCODEMP;

    if ((PRCODCOL is not null and
        PRCODCOL <> '') and
        (WUSARTMP_COL_SELECT = 0)) then
      WSQL = WSQL || ' and ' || PRCODCOL;

    if (coalesce(PRVERCALCRRA, -1) >= 0) then
      WSQL = WSQL || ' and FOLN.BDVERCALCRRA = ' || PRVERCALCRRA;

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDREFFC,FOL.BDCODVER ';
    else
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDREFFC ';
  end
  else
  begin
    if (PRIRRFESOCIAL = true) then
      WSQL = 'select FOLN.bdrefirrfesocial, FOLN.BDVERCALCRRA,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDREFFC,FO.BDCODVER,FO.BDVALVFC,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';
    else
      WSQL = 'select FOLN.bdrefirrfesocial, FOLN.BDVERCALCRRA,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDREFFC,FO.BDCODVER,FO.BDVALVFC,FOLN.BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';

    wsql = wsql||'from VRHF_EMP_TFOLTOMCOMP FOLN join TEMPRESAS EMAT on (EMAT.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_EMP_SELECT = 1) then
       WSQL = WSQL || 'inner join tmp_empresas_select TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
        WSQL = WSQL || 'inner join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FOLN.BDCODEMP and TEM.BDCODCOL = FOLN.BDCODCOL) ';

    WSQL = WSQL || 'inner join VRHF_EMP_TVERBAFCTOMADOR FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDREFTOMADOR = FOLN.BDREFTOMADOR and FO.BDORDEM = FOLN.BDORDEM and FO.BDREFFC = FOLN.BDREFFC) ';
    WSQL = WSQL || 'inner join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  ';
    if (PRIRRFESOCIAL = TRUE) THEN
       WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
    ELSE
       WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFFC ORDER BY X.BDREFCOL DESC) ';
      
    WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                 '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where FOLN.BDREFIRRFESOCIAL between ' || PRREFINI || ' and ' || PRREFFIM || ' ';
    else
      WSQL = WSQL || 'where FOLN.BDREFFC >= ' || PRREFINI || '01 and FOLN.BDREFFC <= ' || PRREFFIM || '31 ';

    if (WUSARTMP_EMP_SELECT = 0) then
    begin
      if (PRCODEMP is not null and
          PRCODEMP <> '') then
        WSQL = WSQL || ' and ((' || REPLACE(UPPER(PRCODEMP), 'FOL.', 'FOLN.') || ')';

      if (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '') then
        WSQL = WSQL || ' or (' || REPLACE(UPPER(PRCODMATRIZ), 'FOL.', 'EMAT.') || ')';

      if ((PRCODEMP is not null and
          PRCODEMP <> '') or (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '')) then
        WSQL = WSQL || ') ';
    end

    if ((PRCODCOL is not null and
        PRCODCOL <> '') and
        (WUSARTMP_COL_SELECT = 0)) then
      WSQL = WSQL || ' and ' || REPLACE(UPPER(PRCODCOL), 'FOL.', 'FOLN.') || ' ';

    if (coalesce(PRVERCALCRRA, -1) >= 0) then
      WSQL = WSQL || ' and FOLN.BDVERCALCRRA = ' || PRVERCALCRRA;

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDREFFC,FO.BDCODVER ';
    else
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDREFFC ';
  end

  WREFIRRFESOCIALATU = 0;
  WEMPATU = 0;
  WCOLATU = 0;
  WREFATU = 0;
  WREFAUXATU = 0;
  WORDEMATU = -1;
  WBASEIR = 0;
  WINSSN = 0;
  WIR = 0;
  WDEPATU = 0;
  WDATAATU = null;
  WLUCROPJ = 0;
  WDESPMED = 0;
  WAJCUS = 0;
  WBOLSAESTUDOS = 0;
  WPENJUD = 0;
  WPENALIM = 0;
  WPREPRI = 0;
  WINDRESC = 0;
  WVALABO = 0;
  WRENDIS = 0;
  WDRENDIS = '';
  WDRENDIS2 = '';
  WDRENDIS3 = '';
  WDATAPROCA = null;
  WHORAPROCA = null;
  WGCLASS = '';
  WBASEIRFE = 0;
  WVALORIRFE = 0;
  WTIPODEDUCAO = 0;
  WVALORDESCSIMPL = 0;
  WVALORDIFDESCSIMPL = 0;
  WTIPODEDUCAOATU = 0;
  WVALORDESCSIMPLATU = 0;
  WVALORDIFDESCSIMPLATU = 0;
  WVERCALCRRAATU = -1;
  WCODACCONVATU = -1;
  WAUXILIOMORADIA = 0;
  WDIARIA = 0;
  WBOLSAMEDICO = 0;
  WJUROSMORA = 0;
  WINCIDESOCIAL = 0;
  WINCIDESOCIALFER = 0;

  for execute statement WSQL
          into :WREFIRRFESOCIAL, :WVERCALCRRA, :WCODEMP, :WCODCOL, :WREF, :WORDEM, :WREFAUX, :WCODVER, :WVALOR,
          :WDATAPGTO, :WDEP, :WCLASSIF, :WDATAPROC, :WHORAPROC, :WTIPODEDUCAO, :WVALORDESCSIMPL, :WVALORDIFDESCSIMPL, :WCODACCONV,
          :WCODCLA, :WTRIBUTACAOEXTERIOR
  do
  begin
    BDCODTIPO = 272; -- Cálculos do Único Folha

    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end

    if (WREFIRRFESOCIALATU = 0) then
      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;

    if (WVERCALCRRAATU = -1) then
      WVERCALCRRAATU = WVERCALCRRA;

    if (WCODACCONVATU = -1) then
      WCODACCONVATU = WCODACCONV;

    if (WEMPATU = 0) then
      WEMPATU = WCODEMP;

    if (WCOLATU = 0) then
      WCOLATU = WCODCOL;

    if (WREFATU = 0) then
      WREFATU = WREF;

    if (WREFAUXATU = 0) then
      WREFAUXATU = WREFAUX;

    if (PRPORCC = 0) then
      WORDEMATU = coalesce(WORDEM, 0);
    else
    if (WORDEMATU = 0) then
      WORDEMATU = coalesce(WORDEM, 0);

    if (WVALORDESCSIMPLATU = 0) then
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
    if (WVALORDIFDESCSIMPLATU = 0) then
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
    if (WTIPODEDUCAOATU = 0) then
      WTIPODEDUCAOATU = WTIPODEDUCAO;

    if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WREF <> WREFATU) or (WREFAUX <> WREFAUXATU) or (WORDEMATU <> coalesce(WORDEM, 0))) then
    begin
      WCODPRES = null;
      WDESCPRES = null;
      WDATARESC = null;

      if (PRPREVIARESC = 1) then
      begin
        select X.BDDATARESCISAOPREV, X.BDCODPRES, Y.BDDESCPRES
        from VRH_EMP_TRESCISAO_PREVIA X
        join VRH_BASE_TPREPRESC Y on (Y.BDCODPRES = X.BDCODPRES)
        where X.BDCODEMP = :WEMPATU and
              X.BDCODCOL = :WCOLATU and
              X.BDREFRESCISAOPREV = :WREFATU
        into :WDATARESC, :WCODPRES, :WDESCPRES;
      end
      else
      begin
        select X.BDDATARESCISAO, X.BDCODPRES, Y.BDDESCPRES
        from VRH_EMP_TRESCISAO X
        join VRH_BASE_TPREPRESC Y on (Y.BDCODPRES = X.BDCODPRES)
        where X.BDCODEMP = :WEMPATU and
              X.BDCODCOL = :WCOLATU and
              X.BDREFRESCISAO = :WREFATU
        into :WDATARESC, :WCODPRES, :WDESCPRES;
      end

      WRUBRICA = null;
      select first 1 PFN.BDCODTPCC,
                     case
                       when coalesce(CUS.BDNOMETOM, '') <> '' then CUS.BDNOMETOM
                       when coalesce(CC.BDNOMCTA, '') <> '' then CC.BDNOMCTA
                       else CC.BDAPECTA
                     end
      from VRHF_EMP_TPREPFN PFN
      left outer join VRH_BASE_TCUSTOM CUS on (CUS.BDCODCENTRO = PFN.BDCODCENTRO and
            CUS.BDCODTPCC = PFN.BDCODTPCC)
      left outer join CENTROS_TPCC CC on (CC.BDCODCENTRO = PFN.BDCODCENTRO and
            CC.BDCODTPCC = PFN.BDCODTPCC)
      where PFN.BDCODEMP = :WEMPATU and
            PFN.BDCODCOL = :WCOLATU and
            PFN.BDORDEM = :WORDEMATU
      into :WRUBRICA, :WDESCCC;

      if (WRUBRICA is null) then
        select first 1 BDNOMEMP
        from TEMPRESAS_REF
        where BDCODEMP = :WEMPATU and
              BDREFEMP <= :WREFATU
        order by BDREFEMP desc
        into :WDESCCC;

      WREFPAGTO = cast((substring(WREFAUXATU from 1 for 6)) as integer);

      if ((WREFPAGTO >= PRREFINI and
          WREFPAGTO <= PRREFFIM) or (PRIRRFESOCIAL = true)) then
      begin
        select first 1 BDCATEGORIAESOCIAL
        from VRHF_EMP_TCOLCON_FGTSGPS
        where BDCODEMP = :WEMPATU and
              BDCODCOL = :WCODCOL and
              BDREFCOL <= :WREFATU
        order by BDREFCOL desc
        into :WCATEGORIAESOCIAL;

        BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
        BDCODEMP = WEMPATU;
        BDCODCOL = WCOLATU;
        BDREF = WREFATU;
        BDREFPAG = WREFPAGTO;
        if (PRIRRFESOCIAL = true) then
          BDREFPAG = BDREFIRRFESOCIAL;
        BDREFFC = WREFAUXATU;
        BDINSS = WINSSN;

        if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
           begin
              BDIR = 0;
              BDRENDTRIBUTAVEL = 0;
           end
        else
           begin
              BDIR = WIR;
              BDRENDTRIBUTAVEL = WBASEIR;
           end

        BDDEP = WDEPATU;
        BDLUCROPJ = WLUCROPJ;
        BDDESPMED = WDESPMED;
        BDAJCUSTOS = WAJCUS;
        BDVERCALCRRA = WVERCALCRRAATU;
        BDTIPODEDUCAOFOLHA = WTIPODEDUCAOATU;
        BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
        if (WCATEGORIAESOCIAL = 903) then
        begin
          BDBOLSAESTUDOS = WBOLSAESTUDOS;
          if (coalesce(WDRENDIS2, '') <> '') then
          begin
            if (coalesce(WDRENDIS, '') <> '') then
              WDRENDIS = WDRENDIS || ', ';

            if (PRVEIODOTOTALIZADOR = 1) then
              WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 999);
            else
              WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 200);
          end
        end
        else
        begin
          BDAJCUSTOS = BDAJCUSTOS + WBOLSAESTUDOS;
          if (coalesce(WDRENDIS3, '') <> '') then
          begin
            if (coalesce(WDRENDIS, '') <> '') then
              WDRENDIS = WDRENDIS || ', ';

            if (PRVEIODOTOTALIZADOR = 1) then
              WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 999);
            else
              WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 200);
          end
        end
        BDPENJUD = WPENJUD;
        BDPENALIM = WPENALIM;
        BDPREVPRIV = WPREPRI;
        BDINDRESC = WINDRESC;
        BDVALABO = WVALABO;
        BDRENDISENTOS = WRENDIS;
        BDDRENDISENTOS = WDRENDIS;
        BDDATAPGTO = WDATAATU;
        BDDATAPROC = WDATAPROCA;
        BDHORAPROC = WHORAPROCA;
        BDORDEM = WORDEMATU;
        BDCODACCONV = WCODACCONVATU;
        BDAUXILIOMORADIA = WAUXILIOMORADIA;
        BDDIARIA = WDIARIA;
        BDBOLSAMEDICO = WBOLSAMEDICO;
        BDJUROSMORA = WJUROSMORA;
        BDINCIDESOCIAL = WINCIDESOCIAL;
        BDINCIDESOCIALFER = WINCIDESOCIALFER;

        if (WDATARESC is not null) then
        begin
          BDTIPO = 110; -- Folha complementar rescisão
          BDINFADIC = WORDEMATU || ' - ' || WDESCCC || '; ' || WCODPRES || ' - ' || WDESCPRES;
        end
        else
        begin
          BDTIPO = 1; -- Folha complementar normal
          BDINFADIC = WORDEMATU || ' - ' || WDESCCC;
        end
        BDMESESRRA = 0;
        if (PRATUALIZAINFODESCSIMPLE = true) then
        begin
          WSQLAUX = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, ' || ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, ' || ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) ' || ' values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPAGTO || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';

          execute statement WSQLAUX;
        end
        suspend;

        --              IF (((wvalorirfe >= 0) and (wbaseirfe > 0))  or (prveiodototalizador > 0)) THEN
        if ((WVALORIRFE >= 0) and
            (WBASEIRFE > 0)) then
        begin
          BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
          BDCODEMP = WEMPATU;
          BDCODCOL = WCOLATU;
          BDREF = WREFATU;
          BDORDEM = WORDEMATU;
          BDREFPAG = WREFPAGTO;
          if (PRIRRFESOCIAL = true) then
            BDREFPAG = BDREFIRRFESOCIAL;
          BDREFFC = WREFAUXATU;
          BDRENDTRIBUTAVEL = WBASEIRFE;
          BDINSS = 0;
          BDIR = WVALORIRFE;
          BDDEP = WDEPATU;
          BDLUCROPJ = 0;
          BDDESPMED = 0;
          BDAJCUSTOS = 0;
          BDPENJUD = 0;
          BDPENALIM = 0;
          BDPREVPRIV = 0;
          BDINDRESC = 0;
          BDVALABO = 0;
          BDRENDISENTOS = 0;
          BDDRENDISENTOS = '';
          BDDATAPGTO = WDATAATU;
          BDDATAPROC = WDATAPROCA;
          BDHORAPROC = WHORAPROCA;
          BDTIPO = 4;
          BDINFADIC = '';
          BDVERCALCRRA = WVERCALCRRAATU;
          BDTIPODEDUCAOFOLHA = WTIPODEDUCAOATU;
          BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
          BDAUXILIOMORADIA = 0;
          BDDIARIA = 0;
          BDBOLSAMEDICO = 0;
          BDJUROSMORA = 0;
          BDINCIDESOCIAL = 0;
          BDINCIDESOCIALFER = 0;
          suspend;
        end
      end
      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;
      WEMPATU = WCODEMP;
      WCOLATU = WCODCOL;
      WVERCALCRRAATU = WVERCALCRRA;
      WREFATU = WREF;
      WREFAUXATU = WREFAUX;
      WORDEMATU = WORDEM;
      WCODACCONVATU = WCODACCONV;
      WBASEIR = 0;
      WINSSN = 0;
      WIR = 0;
      WDEPATU = 0;
      WDATAATU = null;
      WLUCROPJ = 0;
      WDESPMED = 0;
      WAJCUS = 0;
      WBOLSAESTUDOS = 0;
      WPENJUD = 0;
      WPENALIM = 0;
      WPREPRI = 0;
      WINDRESC = 0;
      WVALABO = 0;
      WRENDIS = 0;
      WDRENDIS = '';
      WDRENDIS2 = '';
      WDRENDIS3 = '';
      WGCLASS = '';
      WBASEIRFE = 0;
      WVALORIRFE = 0;
      WTIPODEDUCAOATU = WTIPODEDUCAO;
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
      WAUXILIOMORADIA = 0;
      WDIARIA = 0;
      WBOLSAMEDICO = 0;
      WJUROSMORA = 0;
      WINCIDESOCIAL = 0;
      WINCIDESOCIALFER = 0;
    end

    -- soma as bases
    WCODINCIDIRRF = 0;
    select first 1 BDTIPOCODVER, coalesce(BDIRVER, 0), BDRENDISENTOIRVER, BDINDRESC, BDCODINCIDIRRF
    from VRH_BASE_TVERBAS_REF
    where BDCODVER = :WCODVER and
          BDREFVER <= :WREFATU
    order by BDCODVER desc, BDREFVER desc
    into :WTIPOCODVER, :WIRVER, :WRENDISENTOVER, :WEHINDRESC, :WCODINCIDIRRF;

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end

    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
        WIRVER = 0;
    else
    begin

      if (WIRVER = 1) then -- IR Folha normal
      begin
        if (WTIPOCODVER = 0) then -- provento
          WBASEIR = WBASEIR + WVALOR;
        else
        if (WTIPOCODVER = 1) then -- desconto
        begin
          --                      INSS                                              Obrigações IR
          if (substring(WCLASSIF from 1 for 7) <> '9.010.0' and
              substring(WCLASSIF from 1 for 5) <> '0.030') then
            WBASEIR = WBASEIR - WVALOR;
        end
      end

      if (WIRVER = 2) then -- IR Férias
      begin
        if (WTIPOCODVER = 0) then -- provento
          WBASEIRFE = WBASEIRFE + WVALOR;
        else
        if (WTIPOCODVER = 1) then -- desconto
        begin
          --                         INSS                                              Obrigações IR
          if (substring(WCLASSIF from 1 for 7) <> '9.010.0' and
              substring(WCLASSIF from 1 for 5) <> '0.030' and
              substring(WCLASSIF from 1 for 7) <> '3.001.8') then
            WBASEIRFE = WBASEIRFE - WVALOR;
        end
      end

      --                    IR folha normal
      if ((substring(WCLASSIF from 1 for 9) = '9.010.1.0') and
          (WDESCVER2 <> 'IR Férias (COVID-19)')) then
        WIR = WIR + WVALOR;
      --                    IR férias
      if ((substring(WCLASSIF from 1 for 9) = '9.010.1.0') and
          (WDESCVER2 = 'IR Férias (COVID-19)')) then
        WVALORIRFE = WVALORIRFE + WVALOR;

      WDESCVER2 = '';
      select first 1 BDDESCVER
      from VRH_BASE_TVERBAS
      where BDCODVER = :WCODVER
      into WDESCVER2;
      --                    INSS folha normal
      if (substring(WCLASSIF from 1 for 9) = '9.010.0.0') then
        WINSSN = WINSSN + WVALOR;
      --                    Lucro pessoa jurídica
      if (substring(WCLASSIF from 1 for 9) = '0.040.0.2') then
        WLUCROPJ = WLUCROPJ + WVALOR;
      --                    Despesas médicas                                     Complemento de despesas médicas
      if ((substring(WCLASSIF from 1 for 9) = '0.030.1.0') or (substring(WCLASSIF from 1 for 9) = '0.420.0.2') or (substring(WCLASSIF from 1 for 9) = '3.010.0.0')) then
        WDESPMED = WDESPMED + WVALOR;
      --                             Ajuda de custos
      if (substring(WCLASSIF from 1 for 9) = '0.040.0.1' and
          WIRVER = 0) then
      begin
        select first 1 BDCHAVE
        from VRH_BASE_TRUBRICAESOCIAL_VER
        where BDCODVER = :WCODVER
        into :WRUBRICA;
        if (WRUBRICA = 1350) then -- Bolsa estudos
        begin
          WBOLSAESTUDOS = WBOLSAESTUDOS + WVALOR;
          if (WDRENDIS2 <> '') then
            WDRENDIS2 = WDRENDIS2 || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS2 = substring(WDRENDIS2 || 'Bolsa de estudos' from 1 for 999);
          else
            WDRENDIS2 = substring(WDRENDIS2 || 'Bolsa de estudos' from 1 for 200);

          if (WDRENDIS3 <> '') then
            WDRENDIS3 = WDRENDIS3 || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS3 = substring(WDRENDIS3 || WDESCVER2 from 1 for 999);
          else
            WDRENDIS3 = substring(WDRENDIS3 || WDESCVER2 from 1 for 200);
        end
        else
          WAJCUS = WAJCUS + WVALOR;
      end
      --                           Pensões judiciais
      if (substring(WCLASSIF from 1 for 9) = '0.030.0.0') then
        WPENJUD = WPENJUD + WVALOR;
      --                           Pensões alimentícias
      if (substring(WCLASSIF from 1 for 9) = '0.030.0.1') then
        WPENALIM = WPENALIM + WVALOR;
      --                           Previdência privada
      if (substring(WCLASSIF from 1 for 9) = '0.030.1.2') then
        WPREPRI = WPREPRI + WVALOR;

      if (upper(WEHINDRESC) = 'TRUE') then
      begin
        if (WTIPOCODVER in (0, 2)) then -- Provento
          WINDRESC = WINDRESC + WVALOR;
        else
        if (WTIPOCODVER in (1, 3)) then -- Desconto
          WINDRESC = WINDRESC - WVALOR;
      end

      if (substring(WCLASSIF from 1 for 9) = '0.040.0.3') then
        WAUXILIOMORADIA = WAUXILIOMORADIA + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.040.0.0' and
          WIRVER = 0) then
        WDIARIA = WDIARIA + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.910.0.0') then
        WBOLSAMEDICO = WBOLSAMEDICO + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.920.0.0') then
        WJUROSMORA = WJUROSMORA + WVALOR;

      if (coalesce(WCODINCIDIRRF, 0) in (11, 12, 14, 41, 42, 51, 52, 54)) then
        WINCIDESOCIAL = 1;

      if (coalesce(WCODINCIDIRRF, 0) in (13, 43, 53)) then
        WINCIDESOCIALFER = 1;

      WISENTOABONO = 0;
      --   Complemento de abono pecuniário                Compl. 1/3 abono pecuniário
      if (((substring(WCLASSIF from 1 for 7) = '0.210.2') or (substring(WCLASSIF from 1 for 7) = '0.210.3')) and
          (WIRVER <> 1)) then
        WVALABO = WVALABO + WVALOR;
      else

      -- Rendimentos isentos
      if ((upper(WRENDISENTOVER) = 'TRUE') and
          (WISENTOABONO = 0)) then
      begin
        WRENDIS = WRENDIS + WVALOR;
        WI = 0;

        if (PRVEIODOTOTALIZADOR = 1) then
          select POS
          from POS(:WCLASSIF, :WGCLASS)
          into :WI;
        else
          select POS
          from POS(substring(:WCLASSIF from 1 for 5), :WGCLASS)
          into :WI;

        if (WI = 0) then
        begin
          WDESCVER2 = '';

          if (PRVEIODOTOTALIZADOR = 1) then
          begin
            select first 1 BDDESCVER
            from VRH_BASE_TVERBAS
            where BDCLAVER = :WCLASSIF
            into WDESCVER2;

            WGCLASS = WGCLASS || ';' || :WCLASSIF;
          end
          else
          begin
            select first 1 BDDESCVER
            from VRH_BASE_TVERBAS
            where BDCLAVER = substring(:WCLASSIF from 1 for 5)
            into WDESCVER2;

            WGCLASS = WGCLASS || ';' || substring(:WCLASSIF from 1 for 5);
          end

          if (WDRENDIS <> '') then
            WDRENDIS = WDRENDIS || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS = substring(WDRENDIS || WDESCVER2 from 1 for 999);
          else
            WDRENDIS = substring(WDRENDIS || WDESCVER2 from 1 for 200);
        end
      end
    end

    WDEPATU = WDEP;
    WDATAATU = WDATAPGTO;
    WDATAPROCA = WDATAPROC;
    WHORAPROCA = WHORAPROC;
  end


  if (WEMPATU <> 0 and
      WCOLATU <> 0 and
      WREFATU <> 0 and
      WREFAUXATU <> 0) then
  begin
    WCODPRES = null;
    WDESCPRES = null;
    WDATARESC = null;
    if (PRPREVIARESC = 1) then
    begin
      select X.BDDATARESCISAOPREV, X.BDCODPRES, Y.BDDESCPRES
      from VRH_EMP_TRESCISAO_PREVIA X
      join VRH_BASE_TPREPRESC Y on (Y.BDCODPRES = X.BDCODPRES)
      where X.BDCODEMP = :WEMPATU and
            X.BDCODCOL = :WCOLATU and
            X.BDREFRESCISAOPREV = :WREFATU
      into :WDATARESC, :WCODPRES, :WDESCPRES;
    end
    else
    begin
      select X.BDDATARESCISAO, X.BDCODPRES, Y.BDDESCPRES
      from VRH_EMP_TRESCISAO X
      join VRH_BASE_TPREPRESC Y on (Y.BDCODPRES = X.BDCODPRES)
      where X.BDCODEMP = :WEMPATU and
            X.BDCODCOL = :WCOLATU and
            X.BDREFRESCISAO = :WREFATU
      into :WDATARESC, :WCODPRES, :WDESCPRES;
    end

    WRUBRICA = null;
    select first 1 PFN.BDCODTPCC,
                   case
                     when coalesce(CUS.BDNOMETOM, '') <> '' then CUS.BDNOMETOM
                     when coalesce(CC.BDNOMCTA, '') <> '' then CC.BDNOMCTA
                     else CC.BDAPECTA
                   end
    from VRHF_EMP_TPREPFN PFN
    left outer join VRH_BASE_TCUSTOM CUS on (CUS.BDCODCENTRO = PFN.BDCODCENTRO and
          CUS.BDCODTPCC = PFN.BDCODTPCC)
    left outer join CENTROS_TPCC CC on (CC.BDCODCENTRO = PFN.BDCODCENTRO and
          CC.BDCODTPCC = PFN.BDCODTPCC)
    where PFN.BDCODEMP = :WEMPATU and
          PFN.BDCODCOL = :WCOLATU and
          PFN.BDORDEM = :WORDEMATU
    into :WRUBRICA, :WDESCCC;

    if (WRUBRICA is null) then
      select first 1 BDNOMEMP
      from TEMPRESAS_REF
      where BDCODEMP = :WEMPATU and
            BDREFEMP <= :WREFATU
      order by BDREFEMP desc
      into :WDESCCC;

    WREFPAGTO = cast((substring(WREFAUXATU from 1 for 6)) as integer);

    if ((WREFPAGTO >= PRREFINI and
        WREFPAGTO <= PRREFFIM) or (PRIRRFESOCIAL = true)) then
    begin
      select first 1 BDCATEGORIAESOCIAL
      from VRHF_EMP_TCOLCON_FGTSGPS
      where BDCODEMP = :WEMPATU and
            BDCODCOL = :WCOLATU and
            BDREFCOL <= :WREFATU
      order by BDREFCOL desc
      into :WCATEGORIAESOCIAL;

      BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
      BDCODEMP = WEMPATU;
      BDCODCOL = WCOLATU;
      BDREF = WREFATU;
      BDREFPAG = WREFPAGTO;
      if (PRIRRFESOCIAL = true) then
        BDREFPAG = BDREFIRRFESOCIAL;
      BDREFFC = WREFAUXATU;
      BDRENDTRIBUTAVEL = WBASEIR;
      BDINSS = WINSSN;
      BDIR = WIR;
      BDDEP = WDEPATU;
      BDLUCROPJ = WLUCROPJ;
      BDDESPMED = WDESPMED;
      BDAJCUSTOS = WAJCUS;
      if (WCATEGORIAESOCIAL = 903) then
      begin
        BDBOLSAESTUDOS = WBOLSAESTUDOS;
        if (coalesce(WDRENDIS2, '') <> '') then
        begin
          if (coalesce(WDRENDIS, '') <> '') then
            WDRENDIS = WDRENDIS || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 999);
          else
            WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 200);
        end
      end
      else
      begin
        BDAJCUSTOS = BDAJCUSTOS + WBOLSAESTUDOS;
        if (coalesce(WDRENDIS3, '') <> '') then
        begin
          if (coalesce(WDRENDIS, '') <> '') then
            WDRENDIS = WDRENDIS || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 999);
          else
            WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 200);
        end
      end
      BDPENJUD = WPENJUD;
      BDPENALIM = WPENALIM;
      BDPREVPRIV = WPREPRI;
      BDINDRESC = WINDRESC;
      BDVALABO = WVALABO;
      BDRENDISENTOS = WRENDIS;
      BDDRENDISENTOS = WDRENDIS;
      BDDATAPGTO = WDATAATU;
      BDDATAPROC = WDATAPROCA;
      BDHORAPROC = WHORAPROCA;
      BDORDEM = WORDEMATU;
      BDVERCALCRRA = WVERCALCRRAATU;
      BDTIPODEDUCAOFOLHA = WTIPODEDUCAOATU;
      BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
      BDCODACCONV = WCODACCONVATU;
      BDAUXILIOMORADIA = WAUXILIOMORADIA;
      BDDIARIA = WDIARIA;
      BDBOLSAMEDICO = WBOLSAMEDICO;
      BDJUROSMORA = WJUROSMORA;
      BDINCIDESOCIAL = WINCIDESOCIAL;
      BDINCIDESOCIALFER = WINCIDESOCIALFER;
      if (WDATARESC is not null) then
      begin
        BDTIPO = 110; -- Folha complementar rescisão
        BDINFADIC = WORDEMATU || ' - ' || WDESCCC || '; ' || WCODPRES || ' - ' || WDESCPRES;
      end
      else
      begin
        BDTIPO = 1; -- Folha complementar normal
        BDINFADIC = WORDEMATU || ' - ' || WDESCCC;
      end

      if (PRATUALIZAINFODESCSIMPLE = true) then
      begin
        WSQLAUX = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, ' || ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, ' || ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) ' || ' values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPAGTO || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';

        execute statement WSQLAUX;
      end
      BDMESESRRA = 0;
      suspend;

      --            IF (((wvalorirfe >= 0) and (wbaseirfe > 0))  or (prveiodototalizador > 0)) THEN
      if ((WVALORIRFE >= 0) and
          (WBASEIRFE > 0)) then
      begin
        BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
        BDCODEMP = WEMPATU;
        BDCODCOL = WCOLATU;
        BDREF = WREFATU;
        BDORDEM = WORDEMATU;
        BDREFPAG = WREFPAGTO;
        if (PRIRRFESOCIAL = true) then
          BDREFPAG = BDREFIRRFESOCIAL;
        BDREFFC = WREFAUXATU;
        BDRENDTRIBUTAVEL = WBASEIRFE;
        BDINSS = 0;
        BDIR = WVALORIRFE;
        BDDEP = 0;
        BDLUCROPJ = 0;
        BDDESPMED = 0;
        BDAJCUSTOS = 0;
        BDPENJUD = 0;
        BDPENALIM = 0;
        BDPREVPRIV = 0;
        BDINDRESC = 0;
        BDVALABO = 0;
        BDRENDISENTOS = 0;
        BDDRENDISENTOS = '';
        BDDATAPGTO = WDATAATU;
        BDDATAPROC = WDATAPROCA;
        BDHORAPROC = WHORAPROCA;
        BDTIPO = 4;
        BDINFADIC = '';
        BDVERCALCRRA = WVERCALCRRAATU;
        BDTIPODEDUCAOFOLHA = WTIPODEDUCAOATU;
        BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
        BDAUXILIOMORADIA = 0;
        BDDIARIA = 0;
        BDBOLSAMEDICO = 0;
        BDJUROSMORA = 0;
        BDINCIDESOCIAL = 0;
        BDINCIDESOCIALFER = 0;
        suspend;
      end
    end
  end
  /*
DADOS IMPORTADOS OU CADASTRADOS NA FICHA
*/
  for select BDCODEMP, BDCODCOL, BDREF, BDREFPAG, BDTIPO, BDRENDTRIBUTAVEL, BDINSS, BDIR, BDDEP, BDLUCROPJ, BDDESPMED,
             BDAJCUSTOS, BDPENJUD, BDPENALIM, BDPREVPRIV, BDINDRESC, BDVALABO, BDRENDISENTOS, BDDRENDISENTOS,
             BDDATAPGTO, BDINFADIC, BDDATAPROC, BDHORAPROC, BDORDEM, BDBOLSAESTUDOS, BDREFIRRFESOCIAL, BDVERCALCRRA,
             BDTIPODEDUCAOFOLHA, BDVALORDESCONTOSIMPLIFICADO, BDCODACCONV, BDMESESRRA, BDAUXILIOMORADIA, BDDIARIA,
             BDBOLSAMEDICO, BDJUROSMORA, BDINCIDESOCIAL, BDREFFC, BDINCIDESOCIALFER, BDCODFIR, BDDEMDEV, BDCODTIPO
      from SP_VRHF_DADOS_IR_FICHAFC(:PRCODEMP, :PRCODCOL, :PRREFINI, :PRREFFIM, :PRPUXARFILIAIS, :PRCODMATRIZ, :PRVERCALCRRA)
      into :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR, :BDDEP, :BDLUCROPJ,
           :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM, :BDPREVPRIV, :BDINDRESC, :BDVALABO, :BDRENDISENTOS,
           :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDDATAPROC, :BDHORAPROC, :BDORDEM, :BDBOLSAESTUDOS,
           :BDREFIRRFESOCIAL, :BDVERCALCRRA, :BDTIPODEDUCAOFOLHA, :BDVALORDESCONTOSIMPLIFICADO, :BDCODACCONV,
           :BDMESESRRA, :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA, :BDINCIDESOCIAL, :BDREFFC,
           :BDINCIDESOCIALFER, :BDCODFIR, :BDDEMDEV, :BDCODTIPO
  do
    suspend;

end^

create or alter procedure SP_VRHF_DADOS_IR_TEMRRAANO (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer)
as
declare variable WSQL varchar(32700);
declare variable WEMP varchar(20000);
declare variable WCOL varchar(30000);
BEGIN
  /* PROCEDURE TEXT */

  IF ((PRCODEMP IS NOT NULL) AND (PRCODEMP <> '')) THEN
     WEMP = ''''||PRCODEMP||'''';
  ELSE
     WEMP = 'NULL';

  IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
     WCOL = ''''||PRCODCOL||'''';
  ELSE
     WCOL = 'NULL';

  WSQL = 'SELECT BDCODEMP, BDCODCOL FROM '||
         'SP_VRHF_DADOS_IR_FC_RRA('||WEMP||','||WCOL||','||PRREFINI||','||PRREFFIM||')';

  FOR EXECUTE STATEMENT WSQL INTO :BDCODEMP, :BDCODCOL DO
    BEGIN
      IF ((COALESCE(BDCODEMP,0) > 0) AND (COALESCE(BDCODCOL,0) > 0)) THEN
         SUSPEND;
    END

  WSQL = 'SELECT BDCODEMP, BDCODCOL FROM '||
         'SP_VRHF_DADOS_IR_RT('||replace(WEMP,'FOL.','')||','||REPLACE(WCOL,'FOL.','')||','||PRREFINI||','||PRREFFIM||')';

  FOR EXECUTE STATEMENT WSQL INTO :BDCODEMP, :BDCODCOL DO
    BEGIN
      IF ((COALESCE(BDCODEMP,0) > 0) AND (COALESCE(BDCODCOL,0) > 0)) THEN
         SUSPEND;
    END

END^

create or alter procedure SP_VRHF_DADOS_IR_FC_RRA (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PREXPORTACAO integer = 0,
    PRPORCC smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRMESESRRATOTAL integer = 0,
    PRGRAVATABTEMP boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    WGCLASS varchar(1000),
    WDESCVER2 varchar(70),
    WI integer,
    BDORDEM integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDREFIRRFESOCIAL integer,
    BDVERCALCRRA integer,
    BDTIPODEDUCAOFOLHA integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(15,2),
    BDCODACCONV integer,
    BDTOTALDESPJDC numeric(18,6),
    BDMESESRRA numeric(18,6),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDREFFC integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDCODTIPO integer)
as
declare variable WSQL varchar(32000);
declare variable WEMP varchar(20000);
declare variable WCOL varchar(30000);
declare variable WMAT varchar(15000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WREFPAG integer;
declare variable WCODACCONV integer;
declare variable WSQL2 varchar(32000);
declare variable WREFAUX integer;
declare variable WREFCOMP integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WBASEIR13 numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WPENJUD13 numeric(18,6);
declare variable WPENALIM13 numeric(18,6);
declare variable WRENDIS13 numeric(18,6);
declare variable WVERCALCRRA integer;
declare variable WCODEMPAUX integer;
declare variable WCODCOLAUX integer;
declare variable WRENDTRIBUTAVEL numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WIR numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUSTOS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREVPRIV numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDISENTOS numeric(18,6);
declare variable WSQLAUXTABTEMP varchar(32000);
declare variable WAUXILIOMORADIA numeric(18,6);
declare variable WDIARIA numeric(18,6);
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WJUROSMORA numeric(18,6);
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WGRAVARUBRICA integer;
begin
/*
   *****************************************************************************
   *****************************************************************************
   SP USADA PRA FAZER TRATAMENTOS NA DEMONSTRAÇÃO DA FICHA FINANCEIRA DE IRRF
   *****************************************************************************
   *****************************************************************************
*/
  if (prgravatabtemp) then
     begin
       WSQLAUXTABTEMP = ' DELETE FROM VRHF_TINFO_TEMP_RENDTRIBRRA WHERE BDSESSAO = '||CURRENT_CONNECTION;
       execute statement WSQLAUXTABTEMP;
     end

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wemp = ''''||prcodemp||'''';
  ELSE
     wemp = 'null';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wcol = ''''||prcodcol||'''';
  ELSE
     wcol = 'null';

  IF (prpuxarfiliais = 1) THEN
     wmat = ''''||prcodmatriz||'''';
  ELSE
     wmat = 'null';

  wSQL = 'select BDCODEMP, BDCODCOL, BDREF, BDREFPAG, BDTIPO, BDRENDTRIBUTAVEL, BDINSS, BDIR, BDDEP, BDLUCROPJ, BDDESPMED, BDAJCUSTOS, BDPENJUD, BDPENALIM, '||
         '       BDPREVPRIV, BDINDRESC, BDVALABO, BDRENDISENTOS, BDDRENDISENTOS, BDDATAPGTO, BDINFADIC, BDDATAPROC, BDHORAPROC, WGCLASS, WDESCVER2, WI, '||
         '       BDORDEM, BDBOLSAESTUDOS, BDREFIRRFESOCIAL, BDVERCALCRRA, BDTIPODEDUCAOFOLHA, BDVALORDESCONTOSIMPLIFICADO, BDCODACCONV, '||
         '       BDMESESRRA, BDAUXILIOMORADIA, BDDIARIA, BDBOLSAMEDICO, BDJUROSMORA, BDREFFC, BDCODFIR,BDDEMDEV, BDCODTIPO '||
         'from SP_VRHF_DADOS_IR_FC('||wemp||','||wcol||','||PRREFINI||','||PRREFFIM||','||PRPUXARFILIAIS||','||wmat||','||PRPREVIARESC||','||PREXPORTACAO||','||PRPORCC||','||PRIRRFESOCIAL||','||PRATUALIZAINFODESCSIMPLE||',1,'||PRVEIODOTOTALIZADOR||')';

  wcodemp = 0;
  wcodcol = 0;
  wref = 0;
  wrefpag = 0;
  wcodacconv = 0;
  
  wcpfcol = null;
  wcodempord = null;

  for execute statement wSQL INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR, :BDDEP, :BDLUCROPJ, :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM,
                                  :BDPREVPRIV, :BDINDRESC, :BDVALABO, :BDRENDISENTOS, :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDDATAPROC, :BDHORAPROC, :WGCLASS, :WDESCVER2, :WI,
                                  :BDORDEM, :BDBOLSAESTUDOS, :BDREFIRRFESOCIAL, :BDVERCALCRRA, :BDTIPODEDUCAOFOLHA, :BDVALORDESCONTOSIMPLIFICADO, :BDCODACCONV, :BDMESESRRA,
                                  :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA, :BDREFFC, :BDCODFIR, :BDDEMDEV, :BDCODTIPO DO
     begin
       if (COALESCE(BDVERCALCRRA,0) = 1) then
          begin
            if (BDTIPO >= 9000) then
               suspend;
            else
               begin
                 BDMESESRRA = 0;
                 BDDEP = 0;

                 if (wcodemp = 0) then
                    wcodemp = BDCODEMP;

                 if (wcodcol = 0) then
                    wcodcol = BDCODCOL;

                 if (wref = 0) then
                    wref = BDREF;

                 if (wrefpag = 0) then
                    wrefpag = BDREFPAG;

                 if (wcodacconv = 0) then
                    wcodacconv = bdcodacconv;

                 if ((COALESCE(BDCODACCONV,0) > 0) and (COALESCE(PRMESESRRATOTAL, 0) > 0)) then
                    begin
                      if (COALESCE(BDORDEM,0) > 0) then
                         begin
                           WSQL2 = 'select BDREFTOMADOR '||
                                   'from VRHF_EMP_TFOLTOMCOMP '||
                                   'where BDCODEMP = '||BDCODEMP||' and '||
                                   '      BDCODCOL = '||BDCODCOL||' and ';

                                   if (BDDATAPGTO IS NOT NULL) then
                                   begin
                                      if (PRIRRFESOCIAL = TRUE) then
                                         WSQL2 = WSQL2||' BDDATAIRRFESOCIAL = cast('''||BDDATAPGTO||''' as date) and ';
                                      else
                                         WSQL2 = WSQL2||' BDDATAPAGFC = cast('''||BDDATAPGTO||''' as date) and ';
                                   end

                                   WSQL2 = WSQL2||'      BDREFCOMP = '||BDREFPAG||' and '||
                                                  '      coalesce(BDCODACCONV, 0) = '||BDCODACCONV||' and '||
                                                  '      BDVERCALCRRA = 1 '||
                                                  'group by BDREFTOMADOR ';
                         end
                      else
                         begin
                           WSQL2 = 'select BDREFFN '||
                                   'from VRHF_EMP_TFOLHACOMP '||
                                   'where BDCODEMP = '||BDCODEMP||' and '||
                                   '      BDCODCOL = '||BDCODCOL||' and ';

                                   if (BDDATAPGTO IS NOT NULL) then
                                   begin
                                      if (PRIRRFESOCIAL = TRUE) then
                                         WSQL2 = WSQL2||' BDDATAIRRFESOCIAL = cast('''||BDDATAPGTO||''' as date) and ';
                                      else
                                         WSQL2 = WSQL2||' BDDATAPAGFC = cast('''||BDDATAPGTO||''' as date) and ';
                                   end

                                   WSQL2 = WSQL2||'    BDREFCOMP = '||BDREFPAG||' and '||
                                                  '    coalesce(BDCODACCONV, 0) = '||BDCODACCONV||' and '||
                                                  '    BDVERCALCRRA = 1 ';
                         end

                      WREFAUX = 0;
                      BDMESESRRA = 0;
                      for execute statement wsql2 into :WREFAUX do
                         begin
                           BDMESESRRA = BDMESESRRA + 1;

                           if (substring(cast(wrefaux as varchar(6)) from 5 for 2) = '12') then
                              BDMESESRRA = BDMESESRRA + 1;
                         end
                    end
                 else
                    begin
                      BDMESESRRA = 1;

                      if (substring(cast(BDREF as varchar(6)) from 5 for 2) = '12') then
                         BDMESESRRA = BDMESESRRA + 1;
                    end

                 BDTOTALDESPJDC = 0;
                 if ((coalesce(prmesesrratotal,0) = 0) and
                     (BDCODACCONV > 0) and
                     (((BDCODEMP <> wcodemp) or (BDCODCOL <> wcodcol) or (BDREFPAG <> wrefpag)) or
                      ((BDREF <> wref) and (BDCODACCONV = wcodacconv)))) then
                    begin
                      BDTOTALDESPJDC = 0;

                      wcodemp = BDCODEMP;
                      wcodcol = BDCODCOL;
                      wref = BDREF;
                      wrefpag = BDREFPAG;
                    end
                 else if (BDCODACCONV > 0) then
                    begin
                      WSQL2 = 'SELECT BDTOTALDESPJDC FROM VRH_EMP_TACCONV '||
                              'WHERE BDCODEMP = '||BDCODEMP||' AND '||
                              '      BDCODACCONV = '||BDCODACCONV;

                      EXECUTE STATEMENT WSQL2 INTO :BDTOTALDESPJDC;
                    end

                 BDPENJUD = BDPENJUD + BDTOTALDESPJDC;

                 if (BDCODACCONV <> wcodacconv) then
                    wcodacconv = bdcodacconv;

                 if (bdauxiliomoradia <> 0) then
                    begin
                       if ((bddrendisentos IS NULL) or (bddrendisentos = '')) then
                          begin
                             bddrendisentos = 'AUXÍLIO MORADIA';
                          end
                       else
                          begin
                            if ((POSITION('AUXÍLIO MORADIA', bddrendisentos) = 0)) then
                               bddrendisentos = bddrendisentos || ', AUXÍLIO MORADIA';
                          end
                    end

                 /*
                 COMPLEMENTO DE 13º
                 */
                 if (substring(cast(BDREF as varchar(6)) from 5 for 2) = '12') then
                    begin
                      wsql2 = 'select * from (';

                      WSQL2 = WSQL2 ||'select FOLN.BDVERCALCRRA,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN BDREF,FOLN.BDREFCOMP,FOL.BDCODVER,FOL.BDVALVFC,VER.BDCLAVER,FOLN.BDREFIRRFESOCIAL ';
                      WSQL2 = WSQL2||'from vrhf_emp_tverbafc FOL ';
                      WSQL2 = WSQL2||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
                      WSQL2 = WSQL2||'join vrhf_emp_tfolhacomp FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFFN = FOL.BDREFFN and FOLN.BDREFFC = FOL.BDREFFC) ';
                      WSQL2 = WSQL2||'where exists(select first 1 * from vrhf_emp_tverbafc fvaux '||
                                                'join vrh_base_tverbas fvver on fvver.bdcodver = fvaux.bdcodver '||
                                                'where fvaux.bdcodemp = FOLN.BDCODEMP and fvaux.bdcodcol = FOLN.BDCODCOL and fvaux.bdreffn = FOLN.BDREFFN and fvaux.bdreffc = FOLN.BDREFFC and fvver.bdclaver like ''0.601.%'') ';

                      WSQL2 = WSQL2||' and FOLN.BDCODEMP = '||BDCODEMP;
                      WSQL2 = WSQL2||' and FOLN.BDCODCOL = '||BDCODCOL;
                      WSQL2 = WSQL2||' and FOLN.BDREFFN  = '||BDREF;
                      WSQL2 = WSQL2||' and FOLN.BDREFCOMP = '||BDREFPAG;
                      WSQL2 = WSQL2||' and COALESCE(FOLN.BDVERCALCRRA,0) = 1 ';

                      WSQL2 = WSQL2||' union all ';

                      WSQL2 = WSQL2||'select distinct FCTN.BDVERCALCRRA, FCT.BDCODEMP,FCT.BDCODCOL,FCT.BDREFTOMADOR BDREF,FCTN.BDREFCOMP,FCT.BDCODVER,FCT.BDVALVFC,VER.BDCLAVER,FCTN.BDREFIRRFESOCIAL ';
                      WSQL2 = WSQL2||'from VRHF_EMP_TVERBAFCTOMADOR FCT ';
                      WSQL2 = WSQL2||'join VRH_BASE_TVERBAS VER on (VER.bdcodver = FCT.bdcodver) ';
                      WSQL2 = WSQL2||'join VRHF_EMP_TFOLTOMCOMP FCTN on (FCTN.BDCODEMP = FCT.BDCODEMP and FCTN.BDCODCOL = FCT.BDCODCOL and FCTN.BDREFTOMADOR = FCT.BDREFTOMADOR and FCTN.BDREFFC = FCT.BDREFFC) ';
                      WSQL2 = WSQL2||'where exists(select first 1 * from VRHF_EMP_TVERBAFCTOMADOR fvaux '||
                                                  'join VRH_BASE_TVERBAS fvver on fvver.bdcodver = fvaux.bdcodver '||
                                                  'where fvaux.bdcodemp = FCTN.BDCODEMP and fvaux.bdcodcol = FCTN.BDCODCOL and fvaux.BDREFTOMADOR = FCTN.BDREFTOMADOR and fvaux.bdreffc = FCTN.BDREFFC and fvver.bdclaver like ''0.601.%'') ';

                      WSQL2 = WSQL2||' and FCT.BDCODEMP = '||BDCODEMP;
                      WSQL2 = WSQL2||' and FCT.BDCODCOL = '||BDCODCOL;
                      WSQL2 = WSQL2||' and FCTN.BDREFCOMP = '||BDREFPAG||' ';
                      WSQL2 = WSQL2||' and FCTN.BDREFTOMADOR = '||BDREF||' ';
                      WSQL2 = WSQL2||' and COALESCE(FCTN.BDVERCALCRRA,0) = 1';
                      WSQL2 = WSQL2||') X order by X.BDCODEMP,X.BDCODCOL,X.BDREF,X.BDREFCOMP ';

                      wbaseir13 = 0;
                      winss13 = 0;
                      wvalor = 0;
                      wclassif = null;
                      wcodver = 0;
                      wpenjud13 = 0;
                      wpenalim13 = 0;
                      wrendis13 = 0;

                      WVERCALCRRA = 0;
                      WCODEMPAUX = 0;
                      WCODCOLAUX = 0;
                      WREFAUX = 0;
                      WREFCOMP = 0;

                      WEMPATU = 0;
                      WCOLATU = 0;
                      for execute statement wsql2 into :WVERCALCRRA,:WCODEMPAUX,:WCODCOLAUX,:WREFAUX,:WREFCOMP,:wcodver,:wvalor,:wclassif,:WREFIRRFESOCIAL do
                         begin
                            wtipocodver = 0;
                            wirver = 0;
                            wrendisentover = 0;

                            if ((WEMPATU <> WCODEMPAUX) or (WCOLATU <> WCODCOLAUX)) then
                               begin
                                 select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
                                 from VRH_EMP_TCOLCON_DOC DOC
                                 join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
                                 where DOC.BDCODEMP = :WCODEMPAUX and
                                       DOC.BDCODCOL = :WCODCOLAUX
                                 into :WCPFCOL, :WCODEMPORD;

                                 WEMPATU = WCODEMPAUX;
                                 WCOLATU = WCODCOLAUX;
                               end

                            -- soma as bases
                            SELECT first 1 BDTIPOCODVER, BDIRVER, BDRENDISENTOIRVER
                            FROM VRH_BASE_TVERBAS_REF
                            WHERE BDCODVER = :wcodver and BDREFVER <= :WREFAUX
                            order by BDREFVER DESC
                            INTO :wtipocodver,:wirver,:wrendisentover;

                            select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
                            if (wgravarubrica > 0) then
                               begin
                                 UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
                                 VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIAL,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
                                 MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
	                           end

--                            if (wtipocodver <= 1) then
                               begin
                                 IF (wirver = 3) THEN -- 13º salário
                                    BEGIN
                                      IF (wtipocodver = 0) THEN   -- provento
                                         wbaseir13 = wbaseir13 + wvalor;
                                      ELSE
                                      IF (wtipocodver = 1) THEN   -- desconto
                                         BEGIN
                                           --                                      INSS                                              Obrigações IR
                                           IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030' AND SUBSTRING(wclassif FROM 1 FOR 7) <> '6.001.8') THEN
                                              wbaseir13 = wbaseir13 - wvalor;
                                         END
                                    END
     
                                 -- Desconto de 13º salário
                                 IF ((SUBSTRING(wclassif FROM 1 FOR 5) = '6.080') and (wirver <> 3) and (wtipocodver <= 1)) THEN
                                    wbaseir13 = wbaseir13 - wvalor;
                                 --                                     INSS
                                 IF ((SUBSTRING(wclassif FROM 1 FOR 7) = '9.010.0') and (wirver = 3)) THEN
                                    winss13 = winss13 + wvalor;
                                 --                                     Pensões judiciais
                                 IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '6.001.8.0') and (wirver = 3)) THEN
                                    wpenjud13 = wpenjud13 + wvalor;
                                 --                                     Pensões alimentícias
                                 IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '6.001.8.1') and (wirver = 3)) THEN
                                    wpenalim13 = wpenalim13 + wvalor;
                                 -- Rendimentos isentos
                                 IF ((UPPER(wrendisentover) = 'TRUE') and ((SUBSTRING(wclassif FROM 1 FOR 7) = '0.601.0') or ((SUBSTRING(wclassif FROM 1 FOR 7) = '6.001.0')))) THEN
                                    BEGIN
                                      wrendis13 = wrendis13 + wvalor;
                                    END
                                 --
                                 IF (SUBSTRING(wclassif FROM 1 FOR 9) = '6.620.0.0') THEN
                                    WBOLSAMEDICO = WBOLSAMEDICO + WVALOR;
                               end
                         end

                      BDRENDTRIBUTAVEL = BDRENDTRIBUTAVEL + wbaseir13;
                      BDINSS = BDINSS + winss13;

                      BDPENALIM = BDPENALIM + wpenalim13;
                      BDPENJUD = BDPENJUD + wpenjud13;
                      BDRENDISENTOS = BDRENDISENTOS + wrendis13;
                      BDBOLSAMEDICO = BDBOLSAMEDICO + WBOLSAMEDICO;
                    end

                 /*
                 #190667 Leonardo Schwab 28/02/2024

                 13º DE RESCISÃO
                 */
                 if (BDTIPO = 110) then
                    begin
                      wsql = 'select BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS,BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,BDVALABO,BDRENDISENTOS, '||
                                     'BDAUXILIOMORADIA, BDDIARIA, BDBOLSAMEDICO, BDJUROSMORA '||
                             'from SP_VRHF_DADOS_IR_13FC(';

                      WSQL = WSQL || '''FOL.BDCODEMP = '||BDCODEMP||''',';

                      WSQL = WSQL || '''FOL.BDCODCOL = '||BDCODCOL||''',';

                      wsql = wsql||BDREFPAG||','||BDREFPAG||','||prpuxarfiliais||',';

                      if (coalesce(prcodmatriz, '') = '') then
                        wsql = wsql||'null, ';
                      else
                        wsql = wsql||''''||prcodmatriz||''', ';

                      wsql = wsql||PRIRRFESOCIAL||', 1, '||PRPORCC||')';

                     if (PRPORCC = 1) then
                        wsql = wsql||' where COALESCE(bdordem, 0) = '||COALESCE(BDORDEM, 0);

                      FOR EXECUTE STATEMENT wsql INTO :WRENDTRIBUTAVEL,:WINSS,:WIR,:WDEP,:WLUCROPJ,:WDESPMED,:WAJCUSTOS,:WPENJUD,:WPENALIM,:WPREVPRIV,
                                                      :WINDRESC,:WVALABO,:WRENDISENTOS,:WAUXILIOMORADIA,:WDIARIA,:WBOLSAMEDICO,:WJUROSMORA
                      DO
                      BEGIN
--                        if (PRVEIODOTOTALIZADOR = 1) then
--                           begin
                              BDRENDTRIBUTAVEL = BDRENDTRIBUTAVEL + WRENDTRIBUTAVEL;
                              BDINSS           = BDINSS + WINSS;
                              BDIR             = BDIR + WIR;
--                           end     
                        BDDEP            = BDDEP + WDEP;
                        BDLUCROPJ        = BDLUCROPJ + WLUCROPJ;
                        BDDESPMED        = BDDESPMED + WDESPMED;
                        BDAJCUSTOS       = BDAJCUSTOS + WAJCUSTOS;
                        BDPENJUD         = BDPENJUD + WPENJUD;
                        BDPENALIM        = BDPENALIM + WPENALIM;
                        BDPREVPRIV       = BDPREVPRIV + WPREVPRIV;
                        BDINDRESC        = BDINDRESC + WINDRESC;
                        BDVALABO         = BDVALABO + WVALABO;
                        BDRENDISENTOS    = BDRENDISENTOS + WRENDISENTOS;
                        BDAUXILIOMORADIA = BDAUXILIOMORADIA + WAUXILIOMORADIA;
                        BDDIARIA         = BDDIARIA + WDIARIA;
                        BDBOLSAMEDICO    = BDBOLSAMEDICO + WBOLSAMEDICO;
                        BDJUROSMORA      = BDJUROSMORA + WJUROSMORA;
                      END

                    end

                 if (prgravatabtemp) then
                    begin
                      INSERT INTO VRHF_TINFO_TEMP_RENDTRIBRRA (BDSESSAO,BDCODEMP,BDCODCOL,BDRENDIMENTOTRIBUTAVEL,BDIR,BDRENDTRIBNORMAL,BDIRNORMAL,BDRENDTRIBRT,BDIRRT) VALUES (CURRENT_CONNECTION,:WCODEMP,:WCODCOL,coalesce(:BDRENDTRIBUTAVEL, 0),coalesce(:BDIR, 0),0,0,0,0);
                    end
                 suspend;
               end
          end
     end
end^

create or alter procedure SP_VRHF_DADOS_IR_RT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRGRAVATEMPRENDTRIB boolean = false,
    PRRELATORIO boolean = false,
    PRFILTRORECEITA integer = 0,
    PRSEMRENDISENTO boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCHAVE integer,
    BDREFPGTO integer,
    BDIRRFMENSAL numeric(18,6),
    BDIRRFDECIMOTERC numeric(18,6),
    BDPREVIDENCIAOFICIAL numeric(18,6),
    BDCODRECEITAESOC varchar(6),
    BDTOTALDESPJUDICIAL numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDRENDNAPTRIBUT numeric(18,6),
    BDQTDMESESRRA numeric(18,6),
    BDVALORPAGOADVOGADO numeric(18,6),
    BDCPFADVOGADO varchar(18),
    BDNOMCOL varchar(70),
    BDCPF varchar(18),
    BDDESCRRA varchar(50),
    BDDESCRENDNAOTRIBUT varchar(60),
    BDJUROSMORA numeric(18,6),
    BDQTDDEP integer,
    BDNUMPROCESSO varchar(25),
    BDVALDEP numeric(18,6),
    BDTOTALPENSAO numeric(18,6),
    BDPENSAOMENSAL numeric(18,6),
    BDPENSAO13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDPREVIDENCIAOFICIAL13 numeric(18,6),
    BDJUROSMORA13 numeric(18,6))
as
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(32000);
declare variable WAUX varchar(32000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WRENDTRIBRT numeric(18,6);
declare variable WIRRT numeric(18,6);
declare variable WVALDEPIR numeric(18,6);
declare variable WDESCRENDNAOTRIBUT varchar(60);
declare variable WRENDNAPTRIBUT numeric(18,6);
declare variable WPENSAO numeric(18,6);
declare variable WPENSAO13 numeric(18,6);
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WUSARTMP_COL_SELECT smallint;
begin
  /***************************************************************************/
  /* SP USADA PARA RETORNAR OS VALORES DE RECLAMATORIA TRABALHISTA PARA DIRF */
  /***************************************************************************/

  WUSARTMP_EMP_SELECT = 0;
  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;
  WUSARTMP_COL_SELECT = 0;
  IF (UPPER(prcodcol) = 'TEMP_FILTRO_COLCON_REL') THEN
     WUSARTMP_COL_SELECT = 1;

  wsql = ' SELECT IR.BDCODEMP,REC.BDCODCOL,IR.BDCHAVE,IR.BDREFPGTO,IR.BDIRRFMENSAL,IR.BDIRRFDECIMOTERC,IR.BDPREVIDENCIAOFICIAL,CR.BDCODRECEITAESOC,RRA.BDTOTALDESPJUDICIAL,IR.BDVALORIRRF, '||
         ' IR.BDRENDNAPTRIBUT,RRA.BDQTDMESESRRA , '||
         ' case '||
           ' when count(ADV.BDCPFADVOGADO) > 1 then null '||
           ' else sum(ADV.BDVALORPAGOADVOGADO) '||
         ' end as BDVALORPAGOADVOGADO, '||
         ' case '||
           ' when count(ADV.BDCPFADVOGADO) > 1 then null '||
           ' else max(ADV.BDCPFADVOGADO) '||
         ' end as BDCPFADVOGADO, '||
         ' REC.BDNOMCOL,IR.BDCPF,RRA.BDDESCRRA,IR.BDDESCRENDNAOTRIBUT,IR.BDJUROSMORA, count(DEP.BDCPFDEPENDENTE) BDQTDDEP,BA.BDNUMEROPROCESSO,IR.BDVALORIRRF13,IR.BDPREVIDENCIAOFICIAL13,IR.BDJUROSMORA13 '||
         ' FROM VRH_EMP_IRRF_TENCARGOS_RT IR '||
         ' left outer join VRH_EMP_TRECLAMATORIA REC on (rec.bdcodemp = ir.bdcodemp and rec.bdcodrt = ir.bdchave and rec.bdcpfcol = ir.bdcpf) '||
         ' LEFT OUTER JOIN VRH_EMP_ADVOGADOS_TENCARGOS_RT ADV ON (ADV.BDCODEMP = IR.BDCODEMP AND ADV.BDCHAVE = IR.BDCHAVE AND ADV.BDREFPGTO = IR.BDREFPGTO AND ADV.BDCPF = IR.BDCPF AND ADV.BDCODCR = IR.BDCODCR) '||
         ' LEFT OUTER JOIN VRH_EMP_RRA_TENCARGOS_RT RRA ON (RRA.BDCODEMP = IR.BDCODEMP AND RRA.BDCHAVE = IR.BDCHAVE AND RRA.BDREFPGTO = IR.BDREFPGTO AND RRA.BDCPF = IR.BDCPF AND RRA.BDCODCR = IR.BDCODCR) '||
         ' LEFT OUTER JOIN VRH_EMP_DEPENDENTES_TENCARGOS_RT DEP ON (DEP.BDCODEMP = IR.BDCODEMP AND DEP.BDCHAVE = IR.BDCHAVE AND DEP.BDREFPGTO = IR.BDREFPGTO AND DEP.BDCPF = IR.BDCPF AND DEP.BDCODCR = IR.BDCODCR) '||
         ' LEFT OUTER JOIN TRT_CODIGORECEITA_IRRF CR ON (CR.BDCODRECEITA = IR.BDCODCR) '||
         ' LEFT OUTER JOIN VRH_BASE_TRECLAMATORIA BA on (BA.BDCODRT = IR.BDCHAVE) ';

  IF (WUSARTMP_EMP_SELECT = 1) THEN
    wSQL = wSQL||' INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = IR.BDCODEMP) ';

  IF (WUSARTMP_COL_SELECT = 1) THEN
      wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMPC on (TEMPC.BDCODEMP = REC.BDCODEMP AND ((TEMPC.BDCODCOL = REC.BDCODCOL) OR ((REC.BDCODCOL IS NULL) and TEMPC.bdcodter = 0 and TEMPC.bdcodcol = 0 AND (TEMPC.BDCPF = REC.BDCPFCOL)))) ';
   
  wwhere = '';

  if ((prcodemp <> '') and (prcodemp is not null) and (WUSARTMP_EMP_SELECT = 0)) then
     begin
       wwhere = replace(upper(prcodemp),  'FOL.BDCODEMP', 'BDCODEMP');
       wwhere = replace(upper(wwhere),  'BDCODEMP', 'IR.BDCODEMP');
     end

  if ((prcodcol <> '') and (prcodcol is not null) and (WUSARTMP_COL_SELECT=0)) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||replace(upper(prcodcol), 'BDCODCOL', 'REC.BDCODCOL');
     end

  if (prrefini > 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||' IR.BDREFPGTO >= '||prrefini;
     end

  if (prreffim > 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||' IR.BDREFPGTO <= '||prreffim;
     end

--  if (prrelatorio) then
--     begin
--       if (wwhere <> '') then
--          wwhere = wwhere||' and ';
--       wwhere = wwhere||' rec.bdcodcol is not null ';
--     end

  if (prfiltroreceita = 1) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||' CR.BDCODRECEITAESOC = 188951 ';
     end
--  else
--  if (prfiltroreceita = 2) then
--     begin
--       if (wwhere <> '') then
--          wwhere = wwhere||' and ';
--       wwhere = wwhere||' CR.BDCODRECEITAESOC <> 188951 ';
--     end

  if (wwhere <> '') then
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  wsql = wsql||' group by IR.BDCODEMP, REC.BDCODCOL, IR.BDCHAVE, IR.BDREFPGTO, IR.BDIRRFMENSAL, IR.BDIRRFDECIMOTERC,IR.BDPREVIDENCIAOFICIAL, CR.BDCODRECEITAESOC, RRA.BDTOTALDESPJUDICIAL, IR.BDVALORIRRF, IR.BDRENDNAPTRIBUT,RRA.BDQTDMESESRRA, REC.BDNOMCOL, IR.BDCPF, RRA.BDDESCRRA,IR.BDDESCRENDNAOTRIBUT, IR.BDJUROSMORA,BA.BDNUMEROPROCESSO,IR.BDVALORIRRF13,IR.BDPREVIDENCIAOFICIAL13,IR.BDJUROSMORA13 '||
               ' order by IR.BDCODEMP, REC.BDCODCOL, IR.BDCHAVE, IR.BDREFPGTO,CR.BDCODRECEITAESOC ';

  for execute statement wsql into :BDCODEMP,:BDCODCOL,:BDCHAVE,:BDREFPGTO,:BDIRRFMENSAL,:BDIRRFDECIMOTERC,:BDPREVIDENCIAOFICIAL,:BDCODRECEITAESOC,:BDTOTALDESPJUDICIAL,:BDVALORIRRF,
                                  :BDRENDNAPTRIBUT,:BDQTDMESESRRA ,:BDVALORPAGOADVOGADO,:BDCPFADVOGADO,:BDNOMCOL,:BDCPF,:BDDESCRRA,:BDDESCRENDNAOTRIBUT,:BDJUROSMORA,:BDQTDDEP,:BDNUMPROCESSO,:BDVALORIRRF13,:BDPREVIDENCIAOFICIAL13,:BDJUROSMORA13
  do
  begin
    wcodemp = BDCODEMP;
    wcodcol = BDCODCOL;
    wrendtribrt = BDIRRFMENSAL + BDIRRFDECIMOTERC;
    wirrt = BDVALORIRRF;

    if (prsemrendisento) then --USADO NA DECLARACAO DE RENDIMENTOS, POIS OS VALORES DE RENDIMENTOS ISENTOS SAO TRAZIDOS NA SP_VRH_DECLARACAO_RENDIMENTOS_7
       begin
         bdrendnaptribut = 0;
         bddescrendnaotribut = '';
       end

    if (bdcodreceitaesoc = '056152') then --O CÓDIGO DE RECEITA 056152 NAO POSSUI TAG PARA JUROS DE MORA
       bdjurosmora = 0;
    bdvaldep = 0;
    if (bdqtddep > 0) then
       begin
         SELECT FIRST 1 BDVALDEPIR FROM VRHF_TABELAS_TIRDADOS TB
         WHERE TB.BDREFIR <= :BDREFPGTO
         ORDER BY BDREFIR DESC INTO : wvaldepir;
     
         bdvaldep = wvaldepir * bdqtddep;
       end

    wrendnaptribut = 0;
    wdescrendnaotribut = 0;
    wpensao = 0;
    wpensao13 = 0;
    bdtotalpensao = 0;
    bdpensaomensal = 0;
    bdpensao13 = 0;
    waux = 'select PA.bdvalorpensaomensal, PA.bdvalorpensao13 '||
           ' FROM VRH_EMP_PENSAO_TENCARGOS_RT PA '||
           ' LEFT OUTER JOIN TRT_CODIGORECEITA_IRRF CR ON (CR.BDCODRECEITA = PA.BDCODCR) '||
           ' WHERE PA.BDCODEMP = '||bdcodemp||
           ' and PA.BDCHAVE = '||bdchave||
           ' and PA.BDREFPGTO =  '||bdrefpgto||
           ' and PA.BDCPF = '''||bdcpf||''''||
           ' and CR.bdcodreceitaesoc = '''||bdcodreceitaesoc||'''';

    for execute statement waux into :wpensao, :wpensao13 do
      begin
        bdpensaomensal = bdpensaomensal + wpensao;
        bdpensao13 = bdpensao13 + wpensao13;
        bdtotalpensao = bdtotalpensao + wpensao;
        bdtotalpensao = bdtotalpensao + wpensao13;
      end


    if ((bdcodreceitaesoc = '188951') and (bdrendnaptribut > 0) and (not prrelatorio)) then
       begin
         wrendnaptribut = bdrendnaptribut;
         wdescrendnaotribut = bddescrendnaotribut;
         bdrendnaptribut = null;
         bddescrendnaotribut = null;
       end

    if ((prgravatemprendtrib) AND (wcodcol > 0)) then
       begin
         INSERT INTO VRHF_TINFO_TEMP_RENDTRIBRRA (BDSESSAO,BDCODEMP,BDCODCOL,BDRENDIMENTOTRIBUTAVEL,BDIR,BDRENDTRIBNORMAL,BDIRNORMAL,BDRENDTRIBRT,BDIRRT)
VALUES (CURRENT_CONNECTION,:wcodemp,:wcodcol,0,0,0,0,:wrendtribrt,:wirrt);

       end

    if ((prfiltroreceita=2) and (BDCODRECEITAESOC=188951)) then
       begin
         bdirrfdecimoterc = null;
         bdirrfmensal = null;
         bdprevidenciaoficial = null;
         bdqtddep = null;
         bdqtdmesesrra = null;
         bdrendnaptribut = null;
         bdtotaldespjudicial = null;
         bdvaldep = null;
         bdvalorirrf = null;
         bdvalorpagoadvogado = null;
         bddescrra = null;
         bdrendnaptribut = null;
         bddescrendnaotribut = null;
         bdpensaomensal = null ;
         bdpensao13 = null ;
         bdtotalpensao = null;
         bdtotalpensao = null;
         bdprevidenciaoficial13= null;
         bdvalorirrf13 = null;
         suspend;
       end
    else
      begin
          suspend;
      end
    if (wrendnaptribut > 0) then
       begin
         bdcodreceitaesoc = '593656';
         bdirrfdecimoterc = null;
         bdirrfmensal = null;
         bdjurosmora = null;
         bdprevidenciaoficial = null;
         bdqtddep = null;
         bdqtdmesesrra = null;
         bdrendnaptribut = null;
         bdtotaldespjudicial = null;
         bdvaldep = null;
         bdvalorirrf = null;
         bdvalorpagoadvogado = null;
         bddescrra = null;
         bdrendnaptribut = wrendnaptribut;
         bddescrendnaotribut = wdescrendnaotribut;
         suspend;
       end
  end

end^

/* Restore proc. body: SP_VRHF_DADOS_IR_FICHAFCINT */
create or alter procedure SP_VRHF_DADOS_IR_FICHAFCINT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ )
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFFC integer,
    BDINCIDESOCIALFER integer,
    BDCODACCONV integer,
    BDCODFIR integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WSQL varchar(32700);
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WUSARTMP_COL_SELECT integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
BEGIN
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;
  IF (UPPER(prcodcol) = 'TEMP_FILTRO_COLCON_REL') THEN
     WUSARTMP_COL_SELECT = 1;

  /*
      DADOS IMPORTADOS OU CADASTRADOS NA FICHA
  */

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),'||
              'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,'||
              'FOL.BDDATAFIR, '''||''' BDAUX, COALESCE(fol.BDAUXILIOMORADIAFIR,0), COALESCE(fol.BDDIARIAFIR,0), COALESCE(fol.BDBOLSAMEDICOFIR,0), COALESCE(fol.BDJUROSMORAFIR,0), fol.BDCODFIR,COALESCE(FOL.BDCODTIPO,201) BDCODTIPO,'||
              'VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FOL ';
       wsql = wsql||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOL.BDCODEMP) and (HIST.BDCODCOL = FOL.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOL.BDCODEMP) and (VINC.BDCODCOL = FOL.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL  '||
                    '                                     AND X.BDREFCOL <= FOL.BDREFIRFIR ORDER BY X.BDREFCOL DESC) '||
                    '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL)) ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||' join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

       wsql = wsql||'where FOL.BDTIPOCALCFIR in (9010,9011) and FOL.BDREFIRFIR >= '||prrefini||' and FOL.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select FC.BDCODEMP,FC.BDCODCOL,FC.BDREFFN,FC.BDDATAPAGFC from VRHF_EMP_TFOLHACOMPINT FC where FC.BDCODEMP = FOL.BDCODEMP and FC.BDCODCOL = FOL.BDCODCOL and '||
                                'FC.BDREFFN = FOL.BDREFFIR and FC.BDDATAPAGFC = FOL.BDDATAFIR) and '||
                    'not exists (select FCT.BDCODEMP,FCT.BDCODCOL,FCT.BDREFTOMADOR, FCT.BDDATAPAGFC from VRHF_EMP_TFOLTOMCOMPINT FCT where FCT.BDCODEMP = FOL.BDCODEMP and FCT.BDCODCOL = FOL.BDCODCOL and '||
                                'FCT.BDREFTOMADOR = FOL.BDREFFIR and FCT.BDDATAPAGFC = FOL.BDDATAFIR) ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;

       IF ((WUSARTMP_COL_SELECT = 0) and (prcodcol IS NOT NULL AND prcodcol <> '')) THEN
          wsql = wsql||' and '||prcodcol;

      wsql = wsql||' and coalesce((select first 1 X.BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS X '||
                   ' where X.BDCODEMP = FOL.BDCODEMP and X.BDCODCOL = FOL.BDCODCOL and X.BDREFCOL <= FOL.BDREFIRFIR order by x.BDREFCOL desc), '||
                   '(select first 1 X.BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS X where X.BDCODEMP = FOL.BDCODEMP and '||
                   ' X.BDCODCOL = FOL.BDCODCOL order by x.BDREFCOL)) = 111 ';

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDDATAFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX, COALESCE(fo.BDAUXILIOMORADIAFIR,0), COALESCE(fo.BDDIARIAFIR,0), COALESCE(fo.BDBOLSAMEDICOFIR,0), COALESCE(fo.BDJUROSMORAFIR,0), fo.BDCODFIR, COALESCE(FO.BDCODTIPO,201) BDCODTIPO,'||
              'VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FO join TEMPRESAS EMAT on (EMAT.BDCODEMP = FO.BDCODEMP) ';
       wsql = wsql||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FO.BDCODEMP) and (HIST.BDCODCOL = FO.BDCODCOL)  ';

       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FO.BDCODEMP) and (VINC.BDCODCOL = FO.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL  '||
                    '                                     AND X.BDREFCOL <= FO.BDREFIRFIR ORDER BY X.BDREFCOL DESC) '||
                    '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL)) ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wsql = wsql||'inner join tmp_empresas_select TEMP on (TEMP.BDCODEMP = FO.BDCODEMP) ';
       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'inner join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FO.BDCODEMP and TEM.BDCODCOL = FO.BDCODCOL) ';

       wsql = wsql||'where FO.BDTIPOCALCFIR in (9010,9011) and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select FC.BDCODEMP,FC.BDCODCOL,FC.BDREFFN,FC.BDDATAPAGFC from VRHF_EMP_TFOLHACOMPINT FC where FC.BDCODEMP = FO.BDCODEMP and FC.BDCODCOL = FO.BDCODCOL and '||
                                'FC.BDREFFN = FO.BDREFFIR and FC.BDDATAPAGFC = FO.BDDATAFIR) and '||
                    'not exists (select FCT.BDCODEMP,FCT.BDCODCOL,FCT.BDREFTOMADOR, FCT.BDDATAPAGFC from VRHF_EMP_TFOLTOMCOMPINT FCT where FCT.BDCODEMP = FO.BDCODEMP and FCT.BDCODCOL = FO.BDCODCOL and '||
                                'FCT.BDREFTOMADOR = FO.BDREFFIR and FCT.BDDATAPAGFC = FO.BDDATAFIR) ';

       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||REPLACE(UPPER(prcodemp), 'FOL.', 'FO.')||')';

            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||REPLACE(UPPER(prcodmatriz), 'FOL.', 'EMAT.')||')';

            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF ((WUSARTMP_COL_SELECT = 0) and (prcodcol IS NOT NULL AND prcodcol <> '')) THEN
          wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'FOL.', 'FO.')||' ';

      wsql = wsql||' and coalesce((select first 1 X.BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS X '||
                   ' where X.BDCODEMP = FO.BDCODEMP and X.BDCODCOL = FO.BDCODCOL and X.BDREFCOL <= FO.BDREFIRFIR order by x.BDREFCOL desc), '||
                   '(select first 1 X.BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS X where X.BDCODEMP = FO.BDCODEMP and '||
                   ' X.BDCODCOL = FO.BDCODCOL order by x.BDREFCOL)) = 111 ';

       wsql = wsql||' order by FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDDATAFIR ';
     END

  BDORDEM = null;
  BDINCIDESOCIALFER = null;
  BDCODACCONV = null;

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC,
    :BDAUXILIOMORADIA,
    :BDDIARIA,
    :BDBOLSAMEDICO,
    :BDJUROSMORA,
    :BDCODFIR,
    :BDCODTIPO,
    :WCODCLA,
    :WTRIBUTACAOEXTERIOR
  DO
  BEGIN
    BDCODCONTTI = 0;
    BDDATAPROC = BDDATAPGTO;
    BDHORAPROC = '00:00:00';
    bdrefirrfesocial = bdrefpag;

    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
      begin
        BDRENDTRIBUTAVEL = 0;
        BDIR = 0;
      end

    if (COALESCE(BDRENDTRIBUTAVEL, 0) <> 0) then
       BDINCIDESOCIAL = 1;

    BDREFFC = null;

    SUSPEND;
  END
END^

/* Restore proc. body: SP_VRHF_DADOS_IR_FCT_INT */
create or alter procedure SP_VRHF_DADOS_IR_FCT_INT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PREXPORTACAO integer = 0,
    PRPORCC smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    WGCLASS varchar(13000),
    WDESCVER2 varchar(70),
    WI integer,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFFC integer,
    BDINCIDESOCIALFER integer,
    BDCODACCONV integer,
    BDCODFIR integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WEHINDRESC varchar(5);
declare variable WISENTOABONO integer;
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WDATAPGTO date;
declare variable WCLASSIF varchar(20);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WCODCONTTIATU integer;
declare variable WDATAATU date;
declare variable WBASEIR numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSSN numeric(18,6);
declare variable WIR numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(999);
declare variable WDATARESC date;
declare variable WCODPRES integer;
declare variable WDESCPRES varchar(110);
declare variable WREFAUX integer;
declare variable WREFAUXATU integer;
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WDESCCC varchar(100);
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WCODCONTTI integer;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WAUXILIOMORADIA numeric(18,6);
declare variable WDIARIA numeric(18,6);
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WJUROSMORA numeric(18,6);
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WINCIDESOCIALFER integer;
declare variable WCODACCONVATU integer;
declare variable WCODACCONV integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WUSARTMP_COL_SELECT integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WGRAVARUBRICA integer;
BEGIN
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;
  IF (UPPER(prcodcol) = 'TEMP_FILTRO_COLCON_REL') THEN
     WUSARTMP_COL_SELECT = 1;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  /*
      FOLHA COMPLEMENTAR TOMADOR
  */

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       if (PRIRRFESOCIAL = TRUE) THEN
          wsql = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDREFFC,FOL.BDCODVER,FOL.BDVALVFC,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC,FOLN.BDCODCONTTI,FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
       ELSE
          wsql = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDREFFC,FOL.BDCODVER,FOL.BDVALVFC,FOLN.BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC,FOLN.BDCODCONTTI,FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';

       wsql = wsql||'from VRHF_EMP_TFOLTOMCOMPINT FOLN ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'inner join tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FOLN.BDCODEMP) ';
       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'inner join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP and TEMP.BDCODCOL = FOLN.BDCODCOL) ';

       wsql = wsql||'join VRHF_EMP_TVERBAFCTOMINT FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDREFTOMADOR = FOLN.BDREFTOMADOR and FOL.BDORDEM = FOLN.BDORDEM and FOL.BDREFFC = FOLN.BDREFFC and FOL.BDCODCONTTI = FOLN.BDCODCONTTI) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  ';
       if (PRIRRFESOCIAL = TRUE) THEN
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
       ELSE
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFFC ORDER BY X.BDREFCOL DESC) ';
      
       WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

       if (PRIRRFESOCIAL = TRUE) THEN
          wsql = wsql||'where FOLN.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim||' ';
       ELSE
          wsql = wsql||'where FOLN.BDREFFC >= '||prrefini||'01 and FOLN.BDREFFC <= '||prreffim||'31 ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;

       IF ((WUSARTMP_COL_SELECT = 0) and (prcodcol IS NOT NULL AND prcodcol <> '')) THEN
          wsql = wsql||' and '||prcodcol;

       if (prveiodototalizador = 1) then
          wsql = wsql||' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDREFFC,FOL.BDCODVER ';
       else
       wsql = wsql||' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDREFFC ';
     END
  ELSE
     BEGIN
       if (PRIRRFESOCIAL = TRUE) THEN
          wsql = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDREFFC,FO.BDCODVER,FO.BDVALVFC,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC,FOLN.BDCODCONTTI,FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
       ELSE
          wsql = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDREFFC,FO.BDCODVER,FO.BDVALVFC,FOLN.BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC,FOLN.BDCODCONTTI,FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';

       wsql = wsql||'from VRHF_EMP_TFOLTOMCOMPINT FOLN join TEMPRESAS EMAT on (EMAT.BDCODEMP = FOLN.BDCODEMP) ';
       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'inner join tmp_empresas_select TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP) ';
       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'inner join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FOLN.BDCODEMP and TEM.BDCODCOL = FOLN.BDCODCOL) ';

       wsql = wsql||'join VRHF_EMP_TVERBAFCTOMINT FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDREFTOMADOR = FOLN.BDREFTOMADOR and FO.BDORDEM = FOLN.BDORDEM and FO.BDREFFC = FOLN.BDREFFC and FO.BDCODCONTTI = FOLN.BDCODCONTTI) ';
       wsql = wsql||'join VRH_BASE_TVERBAS VER on (VER.bdcodver = FO.bdcodver) ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  ';
       if (PRIRRFESOCIAL = TRUE) THEN
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
       ELSE
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFFC ORDER BY X.BDREFCOL DESC) ';
      
       WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

       if (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'where FOLN.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim||' ';
       ELSE
       wsql = wsql||'where FOLN.BDREFFC >= '||prrefini||'01 and FOLN.BDREFFC <= '||prreffim||'31 ';

       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||REPLACE(UPPER(prcodemp), 'FOL.', 'FOLN.')||')';

            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||REPLACE(UPPER(prcodmatriz), 'FOL.', 'EMAT.')||')';

            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF ((WUSARTMP_COL_SELECT = 0) and (prcodcol IS NOT NULL AND prcodcol <> '')) THEN
          wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'FOL.', 'FOLN.')||' ';

       if (prveiodototalizador = 1) then
          wsql = wsql||' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDREFFC,FO.BDCODVER ';
       else
       wsql = wsql||' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDREFFC ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wcodconttiatu = -1;
  wrefauxatu = 0;
  wordematu  = -1;

  wbaseir    = 0;
  winssn     = 0;
  wir        = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc   = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;
  wgclass    = '';
  WAUXILIOMORADIA = 0;
  WDIARIA = 0;
  WBOLSAMEDICO = 0;
  WJUROSMORA = 0;
  WINCIDESOCIAL = 0;
  WINCIDESOCIALFER = 0;
  wcodacconvatu = -1;
  wrefirrfesocialatu = -1;
  BDCODFIR = 0;

  FOR EXECUTE STATEMENT wsql INTO :wrefirrfesocial, :wcodemp,:wcodcol,:wref,:wordem,:wrefaux,:wcodver,:wvalor,:wdatapgto,:wdep,:wclassif,:wdataproc,:whoraproc,:wcodcontti,:wcodacconv, :wcodcla, :wtributacaoexterior  DO
  BEGIN
    BDCODTIPO = 272;    -- Cálculos gerados pelo Único Folha

    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end

    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wrefatu = 0) THEN
       wrefatu = wref;

    IF (wcodconttiatu = -1) THEN
       wcodconttiatu = wcodcontti;

    IF (wrefauxatu = 0) THEN
       wrefauxatu = wrefaux;

    IF (prporcc = 0) THEN
       wordematu = COALESCE(wordem, 0);
    ELSE
    IF (wordematu = 0) THEN
       wordematu = COALESCE(wordem, 0);

    if (wcodacconvatu = -1) then
       wcodacconvatu = wcodacconv;

    if (wrefirrfesocialatu = -1) then
       wrefirrfesocialatu = wrefirrfesocial;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wrefaux <> wrefauxatu) OR (wordematu <> COALESCE(wordem, 0)) OR (wcodconttiatu <> wcodcontti)) THEN
       BEGIN
         wcodpres     = NULL;
         wdescpres    = NULL;
         wdataresc    = NULL;

         IF (prpreviaresc = 1) THEN
            BEGIN
              SELECT X.bddatarescisaoprev,X.bdcodpres,Y.bddescpres FROM vrh_emp_trescisao_previa X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wcodpres,:wdescpres;
            END
         ELSE
            BEGIN
              SELECT X.BDDATARESCISAO,X.bdcodpres,Y.bddescpres FROM vrh_emp_trescisao X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wcodpres,:wdescpres;
            END

         SELECT
         CASE
           WHEN CC.BDCODTPCC IS NULL THEN CC.BDNOMEMP
           WHEN (CC.BDNOMETOM IS NOT NULL) AND (CC.BDNOMETOM <> '') THEN CC.BDNOMETOM
           WHEN (CC.BDNOMCTA IS NOT NULL) AND (CC.BDNOMCTA <> '') THEN CC.BDNOMCTA
           ELSE CC.BDAPECTA END BDNOMCC
         FROM (
           SELECT X.BDCODEMP,X.BDCODCOL,X.BDORDEM,X.bdcodtpcc,Y.bdnomcta,Y.bdapecta,Z.BDNOMETOM,E.bdnomemp
           FROM vrhf_emp_tprepfn X
           JOIN vw_tempresas_ref E ON (E.BDCODEMP = X.BDCODEMP)
           LEFT OUTER JOIN centros_tpcc Y ON (Y.bdcodcentro = X.bdcodcentro AND Y.bdcodtpcc = X.bdcodtpcc)
           LEFT OUTER JOIN vrh_base_tcustom Z ON (Z.bdcodcentro = X.bdcodcentro AND Z.bdcodtpcc = X.bdcodtpcc)
           WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDORDEM = :wordematu
         ) CC INTO :wdesccc;

         wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);

         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              bdrefirrfesocial = wrefirrfesocialatu;
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              BDREFPAG         = wrefpagto;
              BDREFFC          = wrefauxatu;
              BDRENDTRIBUTAVEL = wbaseir;
              BDINSS           = winssn;
              BDIR             = wir;
              BDDEP            = wdepatu;
              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;
              BDPREVPRIV       = wprepri;
              BDINDRESC        = windresc;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;
              BDORDEM          = wordematu;
              BDCODCONTTI      = wcodconttiatu;
              BDAUXILIOMORADIA = WAUXILIOMORADIA;
              BDDIARIA = WDIARIA;
              BDBOLSAMEDICO = WBOLSAMEDICO;
              BDJUROSMORA = WJUROSMORA;
              BDINCIDESOCIAL = WINCIDESOCIAL;
              BDINCIDESOCIALFER = WINCIDESOCIALFER;
              BDCODACCONV = WCODACCONVATU;

              IF (wdataresc IS NOT NULL) THEN
                 BEGIN
                   BDTIPO    = 110;    -- Folha complementar rescisão
                   BDINFADIC = wordematu||' - '||wdesccc||'; '||wcodpres||' - '||wdescpres;
                 END
              ELSE
                 BEGIN
                   BDTIPO    = 1;    -- Folha complementar normal
                   BDINFADIC = wordematu||' - '||wdesccc;
                 END

              SUSPEND;
            END

         wrefirrfesocialatu = wrefirrfesocial;
         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wrefatu    = wref;
         wcodconttiatu = wcodcontti;
         wrefauxatu = wrefaux;
         wordematu  = wordem;

         wbaseir    = 0;
         winssn     = 0;
         wir        = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc   = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
         wgclass    = '';
         WAUXILIOMORADIA = 0;
         WDIARIA = 0;
         WBOLSAMEDICO = 0;
         WJUROSMORA = 0;
         WINCIDESOCIAL = 0;
         WINCIDESOCIALFER = 0;
         wcodacconvatu = wcodacconv;
       END

    -- soma as bases
    SELECT first 1 BDTIPOCODVER, COALESCE(BDIRVER,0), BDRENDISENTOIRVER, bdindresc, BDCODINCIDIRRF
    FROM VRH_BASE_TVERBAS_REF
    WHERE BDCODVER = :wcodver and BDREFVER <= :wrefatu
    order by BDCODVER desc, BDREFVER DESC
    INTO :wtipocodver,:wirver,:wrendisentover, :wehindresc, :WCODINCIDIRRF;

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end

    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
      begin
        wirver = 0;
      end
    else
      begin
        --    if (wtipocodver <= 1) then
         IF (wirver = 1) THEN -- IR Folha normal
            BEGIN
              IF (wtipocodver = 0) THEN   -- provento
                 wbaseir = wbaseir + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN   -- desconto
                 BEGIN
                   --                                      INSS                                              Obrigações IR
                   IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                      wbaseir = wbaseir - wvalor;
                 END
            END

         --                                     IR folha normal
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.0') THEN
            wir = wir + wvalor;
      end

         --                                     INSS folha normal
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.0') THEN
            winssn = winssn + wvalor;

         --                                     Lucro pessoa jurídica
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
            wlucropj = wlucropj + wvalor;
         --                                     Despesas médicas                                     Complemento de despesas médicas
         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.0') OR (SUBSTRING(wclassif FROM 1 FOR 9) = '0.420.0.2')) THEN
            wdespmed = wdespmed + wvalor;
         --                                     Diárias
--         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.0' AND wirver = 0) THEN
--            wajcus = wajcus + wvalor;
         --                                     Ajuda de custos
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1' AND wirver = 0) THEN
            wajcus = wajcus + wvalor;
         --                                     Pensões judiciais
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.0') THEN
            wpenjud = wpenjud + wvalor;
         --                                     Pensões alimentícias
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.1') THEN
            wpenalim = wpenalim + wvalor;
         --                                     Previdência privada
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.2') THEN
            wprepri = wprepri + wvalor;

         IF (UPPER(wehindresc) = 'TRUE') THEN
            BEGIN
              IF (wtipocodver in (0, 2)) THEN   -- Provento
                 windresc = windresc + wvalor;
              ELSE
              IF (wtipocodver in (1, 3)) THEN   -- Desconto
                 windresc = windresc - wvalor;
            END

         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.3') THEN
            WAUXILIOMORADIA = WAUXILIOMORADIA + WVALOR;
        
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.0' AND wirver = 0) THEN
            WDIARIA = WDIARIA + WVALOR;
        
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.910.0.0') THEN
            WBOLSAMEDICO = WBOLSAMEDICO + WVALOR;
        
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.920.0.0') THEN
            WJUROSMORA = WJUROSMORA + WVALOR;

         if (COALESCE(WCODINCIDIRRF, 0) IN (11,12,14,41,42,51,52,54)) then
            WINCIDESOCIAL = 1;

         if (COALESCE(WCODINCIDIRRF, 0) in (13,43,53)) then
            WINCIDESOCIALFER = 1;

         WISENTOABONO = 0;
         --                                      Complemento de abono pecuniário                  Compl. 1/3 abono pecuniário
         IF ((SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.2') OR (SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.3')) THEN
            BEGIN
              wvalabo = wvalabo + wvalor;
            END
         ELSE
         -- Rendimentos isentos
         IF ((UPPER(wrendisentover) = 'TRUE') AND (wisentoabono = 0)) THEN
            BEGIN
              wrendis = wrendis + wvalor;

              wi = 0;

              if (prveiodototalizador = 1) then
                 SELECT POS FROM pos(:wclassif, :wgclass) INTO :wi;
              else
              SELECT POS FROM pos(SUBSTRING(:wclassif FROM 1 FOR 5), :wgclass) INTO :wi;

              IF (wi = 0) THEN
                 BEGIN
                   wdescver2 = '';

                   if (prveiodototalizador = 1) then
                      begin
                        SELECT FIRST 1 BDDESCVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = :wclassif INTO wdescver2;
                        wgclass = wgclass||';'||:wclassif;
                      end
                   else
                      begin
                   SELECT FIRST 1 BDDESCVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = SUBSTRING(:wclassif FROM 1 FOR 5) INTO wdescver2;
                   wgclass = wgclass||';'||SUBSTRING(:wclassif FROM 1 FOR 5);
                      end

                   IF (wdrendis <> '') THEN
                      wdrendis = wdrendis ||', ';

                   if (prveiodototalizador = 1) then
                      wdrendis = SUBSTRING(wdrendis||wdescver2 FROM 1 FOR 999);
                   else
                   wdrendis = SUBSTRING(wdrendis||wdescver2 FROM 1 FOR 200);
                 END
            END

    wdepatu = wdep;
    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wrefauxatu <> 0 AND (wcodconttiatu <> -1)) THEN
     BEGIN
       wcodpres     = NULL;
       wdescpres    = NULL;
       wdataresc    = NULL;
       IF (prpreviaresc = 1) THEN
          BEGIN
            SELECT X.bddatarescisaoprev,X.bdcodpres,Y.bddescpres FROM vrh_emp_trescisao_previa X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wcodpres,:wdescpres;
          END
       ELSE
          BEGIN
            SELECT X.BDDATARESCISAO,X.bdcodpres,Y.bddescpres FROM vrh_emp_trescisao X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wcodpres,:wdescpres;
          END

       SELECT
       CASE
         WHEN CC.BDCODTPCC IS NULL THEN CC.BDNOMEMP
         WHEN (CC.BDNOMETOM IS NOT NULL) AND (CC.BDNOMETOM <> '') THEN CC.BDNOMETOM
         WHEN (CC.BDNOMCTA IS NOT NULL) AND (CC.BDNOMCTA <> '') THEN CC.BDNOMCTA
         ELSE CC.BDAPECTA END BDNOMCC
       FROM (
         SELECT X.BDCODEMP,X.BDCODCOL,X.BDORDEM,X.bdcodtpcc,Y.bdnomcta,Y.bdapecta,Z.BDNOMETOM,E.bdnomemp
         FROM vrhf_emp_tprepfn X
         JOIN vw_tempresas_ref E ON (E.BDCODEMP = X.BDCODEMP)
         LEFT OUTER JOIN centros_tpcc Y ON (Y.bdcodcentro = X.bdcodcentro AND Y.bdcodtpcc = X.bdcodtpcc)
         LEFT OUTER JOIN vrh_base_tcustom Z ON (Z.bdcodcentro = X.bdcodcentro AND Z.bdcodtpcc = X.bdcodtpcc)
         WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDORDEM = :wordematu
       ) CC INTO :wdesccc;

       wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            bdrefirrfesocial = wrefirrfesocialatu;
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDREFFC          = wrefauxatu;
            BDRENDTRIBUTAVEL = wbaseir;
            BDINSS           = winssn;
            BDIR             = wir;
            BDDEP            = wdepatu;
            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;
            BDPREVPRIV       = wprepri;
            BDINDRESC        = windresc;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            BDORDEM          = wordematu;
            BDCODCONTTI      = wcodconttiatu;
            BDAUXILIOMORADIA = WAUXILIOMORADIA;
            BDDIARIA = WDIARIA;
            BDBOLSAMEDICO = WBOLSAMEDICO;
            BDJUROSMORA = WJUROSMORA;
            BDINCIDESOCIAL = WINCIDESOCIAL;
            BDINCIDESOCIALFER = WINCIDESOCIALFER;
            BDCODACCONV = WCODACCONVATU;

            IF (wdataresc IS NOT NULL) THEN
               BEGIN
                 BDTIPO    = 110;    -- Folha complementar rescisão
                 BDINFADIC = wordematu||' - '||wdesccc||'; '||wcodpres||' - '||wdescpres;
               END
            ELSE
               BEGIN
                 BDTIPO    = 1;    -- Folha complementar normal
                 BDINFADIC = wordematu||' - '||wdesccc;
               END
            SUSPEND;
          END
     END
END^

/* Restore proc. body: SP_VRHF_DADOS_IR_FC_INT */
create or alter procedure SP_VRHF_DADOS_IR_FC_INT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PREXPORTACAO integer = 0,
    PRPORCC smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    WGCLASS varchar(13000),
    WDESCVER2 varchar(70),
    WI integer,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDREFFC integer,
    BDINCIDESOCIALFER integer,
    BDCODACCONV integer,
    BDCODFIR integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WEHINDRESC varchar(5);
declare variable WISENTOABONO integer;
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WDATAPGTO date;
declare variable WCLASSIF varchar(20);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WCODCONTTIATU integer;
declare variable WDATAATU date;
declare variable WBASEIR numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSSN numeric(18,6);
declare variable WIR numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(999);
declare variable WDATARESC date;
declare variable WCODPRES integer;
declare variable WDESCPRES varchar(110);
declare variable WREFAUX integer;
declare variable WREFAUXATU integer;
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WDESCCC varchar(100);
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WCODCONTTI integer;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WAUXILIOMORADIA numeric(18,6);
declare variable WDIARIA numeric(18,6);
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WJUROSMORA numeric(18,6);
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WINCIDESOCIALFER integer;
declare variable WCODACCONVATU integer;
declare variable WCODACCONV integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WUSARTMP_COL_SELECT integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WGRAVARUBRICA integer;
BEGIN
  /*
      FOLHA COMPLEMENTAR NORMAL
  */

  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;
  IF (UPPER(prcodcol) = 'TEMP_FILTRO_COLCON_REL') THEN
     WUSARTMP_COL_SELECT = 1;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       if (PRIRRFESOCIAL = TRUE) THEN
          wsql = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDREFFC,FOL.BDCODVER,FOL.BDVALVFC,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC,FOLN.BDCODCONTTI, FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
       ELSE
          wsql = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDREFFC,FOL.BDCODVER,FOL.BDVALVFC,FOLN.BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC,FOLN.BDCODCONTTI, FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';

       wsql = wsql||'from VRHF_EMP_TFOLHACOMPINT FOLN ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'INNER JOIN tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FOLN.BDCODEMP) ';
       IF (WUSARTMP_COL_SELECT = 1) THEN
          wsql = wsql||'inner join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP and TEMP.BDCODCOL = FOLN.BDCODCOL) ';

       wsql = wsql||'join VRHF_EMP_TVERBAFCINT FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDREFFN = FOLN.BDREFFN and FOL.BDREFFC = FOLN.BDREFFC and FOL.BDCODCONTTI = FOLN.BDCODCONTTI) ';
       wsql = wsql||'join VRH_BASE_TVERBAS VER on (VER.bdcodver = FOL.bdcodver) ';

       WSQL = WSQL||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  ';
       if (PRIRRFESOCIAL = TRUE) THEN
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
       ELSE
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFCOMP ORDER BY X.BDREFCOL DESC) ';
      
       WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

       if (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'where FOLN.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim||' ';
       ELSE
         wsql = wsql||'where FOLN.BDREFCOMP between '||prrefini||' and '||prreffim||' ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;

       IF ((WUSARTMP_COL_SELECT <> 1) and (prcodcol IS NOT NULL AND prcodcol <> '')) THEN
          wsql = wsql||' and '||prcodcol;

       if (prveiodototalizador = 1) then
          wsql = wsql||' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDREFFC,FOL.BDCODVER ';
       else
       wsql = wsql||' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDREFFC ';
     END
  ELSE
     BEGIN
       if (PRIRRFESOCIAL = TRUE) THEN
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDREFFC,FO.BDCODVER,FO.BDVALVFC,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC,FOLN.BDCODCONTTI, FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
       ELSE
       wsql = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDREFFC,FO.BDCODVER,FO.BDVALVFC,FOLN.BDDATAPAGFC,FOLN.BDDEPFC,VER.BDCLAVER,FOLN.BDDATAPROCFC,FOLN.BDHORAPROCFC,FOLN.BDCODCONTTI, FOLN.BDCODACCONV, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

       wsql = wsql||'from VRHF_EMP_TFOLHACOMPINT FOLN join TEMPRESAS EMAT on (EMAT.BDCODEMP = FOLN.BDCODEMP) ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'inner join TMP_EMPRESAS_SELECT TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP) ';
       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'inner join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FOLN.BDCODEMP and TEM.BDCODCOL = FOLN.BDCODCOL) ';

       wsql = wsql||'join VRHF_EMP_TVERBAFCINT FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDREFFN = FOLN.BDREFFN and FO.BDREFFC = FOLN.BDREFFC and FO.BDCODCONTTI = FOLN.BDCODCONTTI) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';

       WSQL = WSQL||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  ';
       if (PRIRRFESOCIAL = TRUE) THEN
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFIRRFESOCIAL ORDER BY X.BDREFCOL DESC) ';  
       ELSE
          WSQL = WSQL||'                                     AND X.BDREFCOL <= FOLN.BDREFCOMP ORDER BY X.BDREFCOL DESC) ';
      
       WSQL = WSQL||'                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

       if (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'where FOLN.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim||' ';
       ELSE
         wsql = wsql||'where FOLN.BDREFCOMP between '||prrefini||' and '||prreffim||' ';

       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||REPLACE(UPPER(prcodemp), 'FOL.', 'FOLN.')||')';

            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||REPLACE(UPPER(prcodmatriz), 'FOL.', 'EMAT.')||')';

            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF ((WUSARTMP_COL_SELECT = 0) and (prcodcol IS NOT NULL AND prcodcol <> '')) THEN
          wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'FOL.', 'FOLN.')||' ';

       if (prveiodototalizador = 1) then
          wsql = wsql||' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDREFFC,FO.BDCODVER ';
       else
       wsql = wsql||' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDREFFC ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wcodconttiatu = -1;
  wrefauxatu = 0;

  wbaseir    = 0;
  winssn     = 0;
  wir        = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc   = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;
  wgclass    = '';
  WAUXILIOMORADIA = 0;
  WDIARIA = 0;
  WBOLSAMEDICO = 0;
  WJUROSMORA = 0;
  WINCIDESOCIAL = 0;
  WINCIDESOCIALFER = 0;
  WCODACCONVATU = -1;
  WREFIRRFESOCIALATU = -1;
  BDCODFIR = 0;

  FOR EXECUTE STATEMENT wsql INTO :wrefirrfesocial,:wcodemp,:wcodcol,:wref,:wrefaux,:wcodver,:wvalor,:wdatapgto,:wdep,:wclassif,:wdataproc,:whoraproc,:wcodcontti,:wcodacconv, :wcodcla, :wtributacaoexterior DO
  BEGIN
    BDCODTIPO = 272;     -- Cálculos gerados pelo Único Folha

    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end

    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wrefatu = 0) THEN
       wrefatu = wref;

    IF (wcodconttiatu = -1) THEN
       wcodconttiatu = wcodcontti;

    IF (wrefauxatu = 0) THEN
       wrefauxatu = wrefaux;

    if (wcodacconvatu = -1) then
       wcodacconvatu = wcodacconv;

    if (WREFIRRFESOCIALATU = -1) then
       WREFIRRFESOCIALATU = WREFIRRFESOCIAL;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wrefaux <> wrefauxatu) OR (wcodconttiatu <> wcodcontti)) THEN
       BEGIN
         wcodpres     = NULL;
         wdescpres    = NULL;
         wdataresc    = NULL;

         IF (prpreviaresc = 1) THEN
            BEGIN
              SELECT X.bddatarescisaoprev,X.bdcodpres,Y.bddescpres FROM vrh_emp_trescisao_previa X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wcodpres,:wdescpres;
            END
         ELSE
            BEGIN
              SELECT X.BDDATARESCISAO,X.bdcodpres,Y.bddescpres FROM vrh_emp_trescisao X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wcodpres,:wdescpres;
            END

         wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);

         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              bdrefirrfesocial = WREFIRRFESOCIALATU;
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              BDREFPAG         = wrefpagto;
              BDREFFC          = wrefauxatu;
              BDRENDTRIBUTAVEL = wbaseir;
              BDINSS           = winssn;
              BDIR             = wir;
              BDDEP            = wdepatu;
              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;
              BDPREVPRIV       = wprepri;
              BDINDRESC        = windresc;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;
              BDCODCONTTI      = wcodconttiatu;
              BDAUXILIOMORADIA = WAUXILIOMORADIA;
              BDDIARIA = WDIARIA;
              BDBOLSAMEDICO = WBOLSAMEDICO;
              BDJUROSMORA = WJUROSMORA;
              BDINCIDESOCIAL = WINCIDESOCIAL;
              BDINCIDESOCIALFER = WINCIDESOCIALFER;
              BDCODACCONV = WCODACCONVATU;
              IF (wdataresc IS NOT NULL) THEN
                 BEGIN
                   BDTIPO    = 110;    -- Folha complementar rescisão
                   BDINFADIC = wcodpres||' - '||wdescpres;
                 END
              ELSE
                 BEGIN
                   BDTIPO    = 1;    -- Folha complementar normal
                   BDINFADIC = '';
                 END

              SUSPEND;
            END

         WREFIRRFESOCIALATU = WREFIRRFESOCIAL;
         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wrefatu    = wref;
         wcodconttiatu = wcodcontti;
         wrefauxatu = wrefaux;

         wbaseir    = 0;
         winssn     = 0;
         wir        = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc   = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
         wgclass    = '';
         WAUXILIOMORADIA = 0;
         WDIARIA = 0;
         WBOLSAMEDICO = 0;
         WJUROSMORA = 0;
         WINCIDESOCIAL = 0;
         WINCIDESOCIALFER = 0;
         wcodacconvatu = wcodacconv;
       END

    -- soma as bases
    SELECT first 1 BDTIPOCODVER, COALESCE(BDIRVER,0), BDRENDISENTOIRVER, bdindresc, BDCODINCIDIRRF
    FROM VRH_BASE_TVERBAS_REF
    WHERE BDCODVER = :wcodver and BDREFVER <= :wrefatu
    order by BDCODVER desc, BDREFVER DESC
    INTO :wtipocodver,:wirver,:wrendisentover, :wehindresc, :WCODINCIDIRRF;

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end

    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
      begin
         wirver = 0;
      end
    else
     begin    
         --    if (wtipocodver <= 1) then
         IF (wirver = 1) THEN -- IR Folha normal
           BEGIN
             IF (wtipocodver = 0) THEN   -- provento
                wbaseir = wbaseir + wvalor;
             ELSE
             IF (wtipocodver = 1) THEN   -- desconto
                BEGIN
                  --                                      INSS                                              Obrigações IR
                  IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                     wbaseir = wbaseir - wvalor;
                END
           END
         --                                     IR folha normal
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.0') THEN
            wir = wir + wvalor;
      end

         --                                     INSS folha normal
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.0') THEN
            winssn = winssn + wvalor;
         --                                     Lucro pessoa jurídica
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
            wlucropj = wlucropj + wvalor;
         --                                     Despesas médicas                                     Complemento de despesas médicas
         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.0') OR (SUBSTRING(wclassif FROM 1 FOR 9) = '0.420.0.2')) THEN
            wdespmed = wdespmed + wvalor;
         --                                     Diárias
--         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.0' AND wirver = 0) THEN
--            wajcus = wajcus + wvalor;
         --                                     Ajuda de custos
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1' AND wirver = 0) THEN
            wajcus = wajcus + wvalor;
         --                                     Pensões judiciais
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.0') THEN
            wpenjud = wpenjud + wvalor;
         --                                     Pensões alimentícias
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.1') THEN
            wpenalim = wpenalim + wvalor;
         --                                     Previdência privada
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.2') THEN
            wprepri = wprepri + wvalor;

         IF (UPPER(wehindresc) = 'TRUE') THEN
            BEGIN
              IF (wtipocodver in (0, 2)) THEN   -- Provento
                 windresc = windresc + wvalor;
              ELSE
              IF (wtipocodver in (1, 3)) THEN   -- Desconto
                 windresc = windresc - wvalor;
            END

         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.3') THEN
            WAUXILIOMORADIA = WAUXILIOMORADIA + WVALOR;
        
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.0' AND wirver = 0) THEN
            WDIARIA = WDIARIA + WVALOR;
        
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.910.0.0') THEN
            WBOLSAMEDICO = WBOLSAMEDICO + WVALOR;
        
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.920.0.0') THEN
            WJUROSMORA = WJUROSMORA + WVALOR;

         if (COALESCE(WCODINCIDIRRF, 0) IN (11,12,14,41,42,51,52,54)) then
            WINCIDESOCIAL = 1;

         if (COALESCE(WCODINCIDIRRF, 0) in (13,43,53)) then
            WINCIDESOCIALFER = 1;

         WISENTOABONO = 0;
         --                                      Complemento de abono pecuniário                  Compl. 1/3 abono pecuniário
         IF ((SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.2') OR (SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.3')) THEN
            BEGIN
              wvalabo = wvalabo + wvalor;
            END
         ELSE
                  -- Rendimentos isentos
         IF ((UPPER(wrendisentover) = 'TRUE') AND (wisentoabono = 0)) THEN
            BEGIN
              wrendis = wrendis + wvalor;

              wi = 0;

              if (prveiodototalizador = 1) then
                 SELECT POS FROM pos(:wclassif, :wgclass) INTO :wi;
              else
              SELECT POS FROM pos(SUBSTRING(:wclassif FROM 1 FOR 5), :wgclass) INTO :wi;

              IF (wi = 0) THEN
                 BEGIN
                   wdescver2 = '';

                   if (prveiodototalizador = 1) then
                      begin
                        SELECT FIRST 1 BDDESCVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = :wclassif INTO wdescver2;
                        wgclass = wgclass||';'||:wclassif;
                      end
                   else
                      begin
                   SELECT FIRST 1 BDDESCVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = SUBSTRING(:wclassif FROM 1 FOR 5) INTO wdescver2;
                   wgclass = wgclass||';'||SUBSTRING(:wclassif FROM 1 FOR 5);
                      end

                   IF (wdrendis <> '') THEN
                      wdrendis = wdrendis ||', ';

                   if (prveiodototalizador = 1) then
                      wdrendis = SUBSTRING(wdrendis||wdescver2 FROM 1 FOR 999);
                   else
                   wdrendis = SUBSTRING(wdrendis||wdescver2 FROM 1 FOR 200);
                 END
            END

    wdepatu = wdep;
    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wrefauxatu <> 0 AND (wcodconttiatu <> -1)) THEN
     BEGIN
       wcodpres     = NULL;
       wdescpres    = NULL;
       wdataresc    = NULL;

       IF (prpreviaresc = 1) THEN
          BEGIN
            SELECT X.bddatarescisaoprev,X.bdcodpres,Y.bddescpres FROM vrh_emp_trescisao_previa X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wcodpres,:wdescpres;
          END
       ELSE
          BEGIN
            SELECT X.BDDATARESCISAO,X.bdcodpres,Y.bddescpres FROM vrh_emp_trescisao X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wcodpres,:wdescpres;
          END

       wrefpagto = CAST((SUBSTRING(wrefauxatu FROM 1 FOR 6)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDREFFC          = wrefauxatu;
            BDRENDTRIBUTAVEL = wbaseir;
            BDINSS           = winssn;
            BDIR             = wir;
            BDDEP            = wdepatu;
            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;
            BDPREVPRIV       = wprepri;
            BDINDRESC        = windresc;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            BDCODCONTTI      = wcodconttiatu;
            BDAUXILIOMORADIA = WAUXILIOMORADIA;
            BDDIARIA = WDIARIA;
            BDBOLSAMEDICO = WBOLSAMEDICO;
            BDJUROSMORA = WJUROSMORA;
            BDINCIDESOCIAL = WINCIDESOCIAL;
            BDINCIDESOCIALFER = WINCIDESOCIALFER;
            BDCODACCONV = WCODACCONVATU;

            IF (wdataresc IS NOT NULL) THEN
               BEGIN
                 BDTIPO    = 110;    -- Folha complementar rescisão
                 BDINFADIC = wcodpres||' - '||wdescpres;
               END
            ELSE
               BEGIN
                 BDTIPO    = 1;    -- Folha complementar normal
                 BDINFADIC = '';
               END
            SUSPEND;
          END
     END


  /*
      FOLHA COMPLEMENTAR TOMADOR
  */

  for select BDCODEMP, BDCODCOL, BDREF, BDREFPAG, BDTIPO, BDRENDTRIBUTAVEL, BDINSS, BDIR, BDDEP, BDLUCROPJ, BDDESPMED, BDAJCUSTOS, BDPENJUD, BDPENALIM, BDPREVPRIV, BDINDRESC,
             BDVALABO, BDRENDISENTOS, BDDRENDISENTOS, BDDATAPGTO, BDINFADIC, BDDATAPROC, BDHORAPROC, WGCLASS, WDESCVER2, WI, BDORDEM, BDCODCONTTI, BDAUXILIOMORADIA, BDDIARIA,
             BDBOLSAMEDICO, BDJUROSMORA, BDINCIDESOCIAL, BDREFFC, BDINCIDESOCIALFER, BDCODACCONV, BDCODFIR, BDREFIRRFESOCIAL, BDCODTIPO
      from SP_VRHF_DADOS_IR_FCT_INT(:prcodemp, :prcodcol, :prrefini, :prreffim, :prpuxarfiliais,:prcodmatriz, :prpreviaresc, :prexportacao, :prporcc, :prirrfesocial,
                                    :prveiodototalizador)
  into :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR, :BDDEP, :BDLUCROPJ, :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM, :BDPREVPRIV, :BDINDRESC,
       :BDVALABO, :BDRENDISENTOS, :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDDATAPROC, :BDHORAPROC, :WGCLASS, :WDESCVER2, :WI, :BDORDEM, :BDCODCONTTI, :BDAUXILIOMORADIA, :BDDIARIA,
       :BDBOLSAMEDICO, :BDJUROSMORA, :BDINCIDESOCIAL, :BDREFFC, :BDINCIDESOCIALFER, :BDCODACCONV, :BDCODFIR, :BDREFIRRFESOCIAL, :BDCODTIPO
   do
     suspend;

  /*
      DADOS IMPORTADOS OU CADASTRADOS NA FICHA
  */

  for select BDCODEMP, BDCODCOL, BDREF, BDREFPAG, BDTIPO, BDRENDTRIBUTAVEL, BDINSS, BDIR, BDDEP, BDLUCROPJ, BDDESPMED, BDAJCUSTOS, BDPENJUD, BDPENALIM, BDPREVPRIV,
             BDINDRESC, BDVALABO, BDRENDISENTOS, BDDRENDISENTOS, BDDATAPGTO, BDINFADIC, BDDATAPROC, BDHORAPROC, BDORDEM, BDCODCONTTI, BDAUXILIOMORADIA, BDDIARIA,
             BDBOLSAMEDICO, BDJUROSMORA, BDINCIDESOCIAL, BDREFFC, BDINCIDESOCIALFER, BDCODACCONV, BDCODFIR, BDREFIRRFESOCIAL, BDCODTIPO
  from SP_VRHF_DADOS_IR_FICHAFCINT(:prcodemp, :prcodcol, :prrefini, :prreffim, :prpuxarfiliais, :prcodmatriz)
  into :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR, :BDDEP, :BDLUCROPJ, :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM, :BDPREVPRIV,
       :BDINDRESC, :BDVALABO, :BDRENDISENTOS, :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDDATAPROC, :BDHORAPROC, :BDORDEM, :BDCODCONTTI, :BDAUXILIOMORADIA, :BDDIARIA,
       :BDBOLSAMEDICO, :BDJUROSMORA, :BDINCIDESOCIAL, :BDREFFC, :BDINCIDESOCIALFER, :BDCODACCONV, :BDCODFIR, :BDREFIRRFESOCIAL, :BDCODTIPO
  do
    suspend;

END^

/* Restore proc. body: SP_VRHF_DADOS_IR_FICHAFE */
create or alter procedure SP_VRHF_DADOS_IR_FICHAFE (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRATUALIZAINFODESCSIMPLE boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDREFINIGOZO integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDCODFE integer,
    BDINIPERAQUIS date,
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WSQL varchar(32700);
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WSQLAUX varchar(3000);
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
begin
  /*
      FERIAS
  */
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  if (upper(PRCODEMP) = 'TMP_EMPRESAS_SELECT') then
    WUSARTMP_EMP_SELECT = 1;

  if (upper(PRCODCOL) = 'TEMP_FILTRO_COLCON_REL') then
    WUSARTMP_COL_SELECT = 1;

  /*
      DADOS IMPORTADOS OU CADASTRADOS NA FICHA
  */

  BDREFINIGOZO = null;
  BDINCIDESOCIAL = null;

  if (PRPUXARFILIAIS = 0) then
  begin
    WSQL = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),' || 'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,' || 'FOL.BDDATAFIR, ''' || ''' BDAUX, FOL.BDCODFERFIR, FOL.BDINIPERAQUISFIR, null BDORDEM, FOL.BDVALORDESCONTOSIMPLIFICADO, COALESCE(fol.BDAUXILIOMORADIAFIR,0), COALESCE(fol.BDDIARIAFIR,0), COALESCE(fol.BDBOLSAMEDICOFIR,0), COALESCE(fol.BDJUROSMORAFIR,0), fol.BDCODFIR, FOL.BDDEMDEV, COALESCE(FOL.BDCODTIPO, 201) BDCODTIPO, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
    WSQL = WSQL || 'from VRHF_EMP_TFICHAIRRF FOL ';

    if (WUSARTMP_EMP_SELECT = 1) then
      WSQL = WSQL || ' inner join tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FOL.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
      WSQL = WSQL || 'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOL.BDCODEMP) and (HIST.BDCODCOL = FOL.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOL.BDCODEMP) and (VINC.BDCODCOL = FOL.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOL.BDREFIRFIR ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL)) ';

    WSQL = WSQL || 'where FOL.BDTIPOCALCFIR = 9030 and FOL.BDREFIRFIR >= ' || PRREFINI || ' and FOL.BDREFIRFIR <= ' || PRREFFIM || ' and ' || 'not exists (select FE.BDCODEMP,FE.BDCODCOL,FE.BDINIPERAQUISFE,FE.BDCODFE from VRHF_EMP_TVERBAFE FE where FE.BDCODEMP = FOL.BDCODEMP and FE.BDCODCOL = FOL.BDCODCOL and ' || 'FE.BDINIPERAQUISFE = FOL.BDINIPERAQUISFIR and FE.BDCODFE = FOL.BDCODFERFIR) ';

    if (PRCODEMP is not null and
        PRCODEMP <> '' and
        WUSARTMP_EMP_SELECT = 0) then
      WSQL = WSQL || ' and ' || PRCODEMP;

    if (PRCODCOL is not null and
        PRCODCOL <> '' and
        WUSARTMP_COL_SELECT = 0) then
      WSQL = WSQL || ' and ' || PRCODCOL;

    WSQL = WSQL || ' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDDATAFIR ';
  end
  else
  begin
    WSQL = 'select FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),' || 'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,' || 'FO.BDDATAFIR, ''' || ''' BDAUX, FO.BDCODFERFIR, FO.BDINIPERAQUISFIR, null BDORDEM, FO.BDVALORDESCONTOSIMPLIFICADO, COALESCE(fo.BDAUXILIOMORADIAFIR,0), COALESCE(fo.BDDIARIAFIR,0), COALESCE(fo.BDBOLSAMEDICOFIR,0), COALESCE(fo.BDJUROSMORAFIR,0), fo.BDCODFIR, FO.BDDEMDEV, COALESCE(FO.BDCODTIPO, 201) BDCODTIPO, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
    wsql = wsql||'from VRHF_EMP_TFICHAIRRF FO join TEMPRESAS EMAT on (EMAT.BDCODEMP = FO.BDCODEMP) ';

    if (WUSARTMP_EMP_SELECT = 1) then
       WSQL = WSQL || 'inner join tmp_empresas_select TEMP on (TEMP.BDCODEMP = FO.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
      WSQL = WSQL || 'join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FO.BDCODEMP and TEM.BDCODCOL = FO.BDCODCOL) ';

    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FO.BDCODEMP) and (HIST.BDCODCOL = FO.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FO.BDCODEMP) and (VINC.BDCODCOL = FO.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FO.BDREFIRFIR ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL)) ';

    WSQL = WSQL || 'where FO.BDTIPOCALCFIR = 9030 and FO.BDREFIRFIR >= ' || PRREFINI || ' and FO.BDREFIRFIR <= ' || PRREFFIM || ' and ' || 'not exists (select FE.BDCODEMP,FE.BDCODCOL,FE.BDINIPERAQUISFE,FE.BDCODFE from VRHF_EMP_TVERBAFE FE where FE.BDCODEMP = FO.BDCODEMP and FE.BDCODCOL = FO.BDCODCOL and ' || 'FE.BDINIPERAQUISFE = FO.BDINIPERAQUISFIR and FE.BDCODFE = FO.BDCODFERFIR) ';

    if (WUSARTMP_EMP_SELECT = 0) then
    begin
      if (PRCODEMP is not null and
          PRCODEMP <> '') then
        WSQL = WSQL || ' and ((' || REPLACE(UPPER(PRCODEMP), 'FOL.', 'FO.') || ')';

      if (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '') then
        WSQL = WSQL || ' or (' || REPLACE(UPPER(PRCODMATRIZ), 'FOL.', 'EMAT.') || ')';

      if ((PRCODEMP is not null and
          PRCODEMP <> '') or (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '')) then
        WSQL = WSQL || ') ';
    end

    if (PRCODCOL is not null and
        PRCODCOL <> '' and
        WUSARTMP_COL_SELECT = 0) then
      WSQL = WSQL || ' and ' || REPLACE(UPPER(PRCODCOL), 'FOL.', 'FO.') || ' ';

    WSQL = WSQL || ' order by FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDDATAFIR ';
  end

  for execute statement WSQL
          into :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR, :BDDEP, :BDLUCROPJ,
          :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM, :BDPREVPRIV, :BDINDRESC, :BDVALABO, :BDRENDISENTOS,
          :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDCODFE, :BDINIPERAQUIS, :BDORDEM, :BDVALORDESCONTOSIMPLIFICADO,
          :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA, :BDCODFIR, :BDDEMDEV, :BDCODTIPO, :WCODCLA, :WTRIBUTACAOEXTERIOR
  do
  begin
    BDDATAPROC = BDDATAPGTO;
    BDHORAPROC = '00:00:00';

    BDREFIRRFESOCIAL = BDREFPAG;

    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
      begin
        BDRENDTRIBUTAVEL = 0;
        BDIR = 0;
      end

    if (PRATUALIZAINFODESCSIMPLE = true) then
    begin
      WSQLAUX = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, ' || ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, ' || ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) ' || ' values (' || current_connection || ', ' || :BDCODEMP || ', ' || :BDCODCOL || ', ' || :BDREFPAG || ', 0, ' || coalesce(:BDPENALIM, 0) || ', ' || coalesce(:BDDEP, 0) || ', ' || coalesce(:BDPREVPRIV, 0) || ', ' || coalesce(:BDINSS, 0) || ', ' || coalesce(:BDVALORDESCONTOSIMPLIFICADO, 0) || ', FALSE, ' || coalesce(:BDRENDTRIBUTAVEL, 0) || ')';

      execute statement WSQLAUX;
    end

    if (coalesce(BDRENDTRIBUTAVEL, 0) <> 0) then
      BDINCIDESOCIALFER = 1;

    suspend;
  end
end^

/* Restore proc. body: SP_VRHF_DADOS_IR_FE */
create or alter procedure SP_VRHF_DADOS_IR_FE (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PREXPORTACAO integer = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDREFINIGOZO integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDCODFE integer,
    BDINIPERAQUIS date,
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WDATA date;
declare variable WREF integer;
declare variable WCODFE integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WDATAATU date;
declare variable WCODFEATU integer;
declare variable WBASEIR numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WREFINIGOZO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSSN numeric(18,6);
declare variable WIR numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(999);
declare variable WINIAQUIS date;
declare variable WINIAQUISATU date;
declare variable WDATAFE date;
declare variable WDATAFEATU date;
declare variable WREFABO integer;
declare variable WREFABOATU integer;
declare variable WDATAFEFIM date;
declare variable WDATAFEFIMATU date;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WGCLASS varchar(13000);
declare variable WDESCVER2 varchar(70);
declare variable WI integer;
declare variable WISENTOABONO integer;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WTIPODEDUCAO integer;
declare variable WVALORDESCSIMPL numeric(18,2);
declare variable WVALORDIFDESCSIMPL numeric(18,2);
declare variable WSQLAUX varchar(3000);
declare variable WTIPODEDUCAOATU integer;
declare variable WVALORDESCSIMPLATU numeric(18,2);
declare variable WVALORDIFDESCSIMPLATU numeric(18,2);
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WINCIDESOCIALFER integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WGRAVARUBRICA integer;
begin
  /*
      FERIAS
  */
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  if (upper(PRCODEMP) = 'TMP_EMPRESAS_SELECT') then
    WUSARTMP_EMP_SELECT = 1;

  if (upper(PRCODCOL) = 'TEMP_FILTRO_COLCON_REL') then
    WUSARTMP_COL_SELECT = 1;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  if (PRPUXARFILIAIS = 0) then
  begin
    if (PRIRRFESOCIAL = true) then
      WSQL = 'select FOLN.BDREFIRRFESOCIAL, FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDINIPERAQUISFE,FOL.BDCODFE,FOL.BDCODVER,FOL.BDVALVFE,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGFE,FOLN.BDDEPFE,FOLN.BDINIPERGOZOFE,' || 'COALESCE(FOLN.BDREFPAGABOFE, 0) BDREFPAGABOFE,FOLN.BDFIMPERGOZOFE,VER.BDCLAVER,FOLN.BDDATAPROCFE,FOLN.BDHORAPROCFE,FOLN.BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
    else
      WSQL = 'select FOLN.BDREFIRRFESOCIAL, FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDINIPERAQUISFE,FOL.BDCODFE,FOL.BDCODVER,FOL.BDVALVFE,FOLN.BDDATAPAGFE,FOLN.BDDEPFE,FOLN.BDINIPERGOZOFE,' || 'COALESCE(FOLN.BDREFPAGABOFE, 0) BDREFPAGABOFE,FOLN.BDFIMPERGOZOFE,VER.BDCLAVER,FOLN.BDDATAPROCFE,FOLN.BDHORAPROCFE,FOLN.BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

    wsql = wsql||'from VRH_EMP_TFERIAS FOLN ';

    if (WUSARTMP_EMP_SELECT = 1) then
       WSQL = WSQL || 'INNER JOIN tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FOLN.BDCODEMP ) ';

    if (WUSARTMP_COL_SELECT = 1) then
       WSQL = WSQL || 'inner join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP and TEMP.BDCODCOL = FOLN.BDCODCOL) ';

    WSQL = WSQL || 'join vrhf_emp_tverbafe FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDINIPERAQUISFE = FOLN.BDINIPERAQUISFE and FOL.BDCODFE = FOLN.BDCODFE) ';
    WSQL = WSQL || 'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOLN.BDREFPAGFE ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where FOLN.BDREFIRRFESOCIAL >= ' || PRREFINI || '  and FOLN.BDREFIRRFESOCIAL <= ' || PRREFFIM;
    else
      WSQL = WSQL || 'where ((CAST((SUBSTRING(CAST(FOLN.BDDATAPAGFE as VARCHAR(10)) from 1 for 4)|| SUBSTRING(CAST(FOLN.BDDATAPAGFE as VARCHAR(10)) from 6 for 2)) AS INTEGER) >= ' || PRREFINI || ' and CAST((SUBSTRING(CAST(FOLN.BDDATAPAGFE as VARCHAR(10)) from 1 for 4)|| SUBSTRING(CAST(FOLN.BDDATAPAGFE as VARCHAR(10)) from 6 for 2)) AS INTEGER) <= ' || PRREFFIM || ')) ';

    if (PRCODEMP is not null and
        PRCODEMP <> '' and
        WUSARTMP_EMP_SELECT = 0) then
      WSQL = WSQL || ' and ' || PRCODEMP;

    if (PRCODCOL is not null and
        PRCODCOL <> '' and
        WUSARTMP_COL_SELECT = 0) then
      WSQL = WSQL || ' and ' || PRCODCOL;

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDINIPERAQUISFE,FOLN.BDCODFE,FOL.BDCODVER ';
    else
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDINIPERAQUISFE,FOLN.BDCODFE ';
  end
  else
  begin
    if (PRIRRFESOCIAL = true) then
      WSQL = 'select FOLN.BDREFIRRFESOCIAL, FOLN.BDCODEMP,FO.BDCODCOL,FO.BDINIPERAQUISFE,FO.BDCODFE,FO.BDCODVER,FO.BDVALVFE,FOLN.BDDATAIRRFESOCIAL AS BDDATAPAGFE,FOLN.BDDEPFE,FOLN.BDINIPERGOZOFE,' || 'COALESCE(FOLN.BDREFPAGABOFE, 0) BDREFPAGABOFE,FOLN.BDFIMPERGOZOFE,VER.BDCLAVER,FOLN.BDDATAPROCFE,FOLN.BDHORAPROCFE,FOLN.BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
    else
      WSQL = 'select FOLN.BDREFIRRFESOCIAL, FOLN.BDCODEMP,FO.BDCODCOL,FO.BDINIPERAQUISFE,FO.BDCODFE,FO.BDCODVER,FO.BDVALVFE,FOLN.BDDATAPAGFE,FOLN.BDDEPFE,FOLN.BDINIPERGOZOFE,' || 'COALESCE(FOLN.BDREFPAGABOFE, 0) BDREFPAGABOFE,FOLN.BDFIMPERGOZOFE,VER.BDCLAVER,FOLN.BDDATAPROCFE,FOLN.BDHORAPROCFE,FOLN.BDORDEM, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

    wsql = wsql||'from VRH_EMP_TFERIAS FOLN join TEMPRESAS EMAT on (EMAT.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_EMP_SELECT = 1) then
       WSQL = WSQL || 'inner join TMP_EMPRESAS_SELECT TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
       WSQL = WSQL || 'join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FOLN.BDCODEMP and TEM.BDCODCOL = FOLN.BDCODCOL) ';

    WSQL = WSQL || 'join VRHF_EMP_TVERBAFE FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDINIPERAQUISFE = FOLN.BDINIPERAQUISFE and FO.BDCODFE = FOLN.BDCODFE) ';
    WSQL = WSQL || 'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';

    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOLN.BDREFPAGFE ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where FOLN.BDREFIRRFESOCIAL >= ' || PRREFINI || '  and FOLN.BDREFIRRFESOCIAL <= ' || PRREFFIM;
    else
      WSQL = WSQL || 'where ((CAST((SUBSTRING(CAST(FOLN.BDDATAPAGFE as VARCHAR(10)) from 1 for 4)|| SUBSTRING(CAST(FOLN.BDDATAPAGFE as VARCHAR(10)) from 6 for 2)) AS INTEGER) >= ' || PRREFINI || ' and CAST((SUBSTRING(CAST(FOLN.BDDATAPAGFE as VARCHAR(10)) from 1 for 4)|| SUBSTRING(CAST(FOLN.BDDATAPAGFE as VARCHAR(10)) from 6 for 2)) AS INTEGER) <= ' || PRREFFIM || ')) ';

    if (WUSARTMP_EMP_SELECT = 0) then
    begin
      if (PRCODEMP is not null and
          PRCODEMP <> '') then
        WSQL = WSQL || ' and ((' || REPLACE(UPPER(PRCODEMP), 'FOL.', 'FOLN.') || ')';

      if (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '') then
        WSQL = WSQL || ' or (' || REPLACE(UPPER(PRCODMATRIZ), 'FOL.', 'EMAT.') || ')';

      if ((PRCODEMP is not null and
          PRCODEMP <> '') or (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '')) then
        WSQL = WSQL || ') ';
    end

    if (PRCODCOL is not null and
        PRCODCOL <> '' and
        WUSARTMP_COL_SELECT = 0) then
      WSQL = WSQL || ' and ' || REPLACE(UPPER(PRCODCOL), 'FOL.', 'FOLN.') || ' ';

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDINIPERAQUISFE,FOLN.BDCODFE,FO.BDCODVER ';
    else
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDINIPERAQUISFE,FOLN.BDCODFE ';
  end

  WEMPATU = 0;
  WCOLATU = 0;
  WDATAATU = null;
  WINIAQUISATU = null;
  WDATAFEATU = null;
  WDATAFEFIMATU = null;
  WREFABOATU = 0;
  WCODFEATU = 0;
  WORDEMATU = 0; --173688 - João Victor - 02.02.23

  WBASEIR = 0;
  WINSSN = 0;
  WIR = 0;
  WDEPATU = 0;
  WLUCROPJ = 0;
  WDESPMED = 0;
  WAJCUS = 0;
  WPENJUD = 0;
  WPENALIM = 0;
  WPREPRI = 0;
  WINDRESC = 0;
  WVALABO = 0;
  WRENDIS = 0;
  WDRENDIS = '';
  WDATAPROCA = null;
  WHORAPROCA = null;
  WGCLASS = '';
  WORDEM = 0;
  WTIPODEDUCAO = 0;
  WVALORDESCSIMPL = 0;
  WVALORDIFDESCSIMPL = 0;
  WTIPODEDUCAOATU = 0;
  WVALORDESCSIMPLATU = 0;
  WVALORDIFDESCSIMPLATU = 0;
  WINCIDESOCIAL = 0;
  WINCIDESOCIALFER = 0;
  WREFIRRFESOCIALATU = -1;

  BDCODFIR = 0;

  for execute statement WSQL
          into :WREFIRRFESOCIAL, :WCODEMP, :WCODCOL, :WINIAQUIS, :WCODFE, :WCODVER, :WVALOR, :WDATA, :WDEP, :WDATAFE,
          :WREFABO, :WDATAFEFIM, :WCLASSIF, :WDATAPROC, :WHORAPROC, :WORDEM, :WTIPODEDUCAO, :WVALORDESCSIMPL, :WVALORDIFDESCSIMPL,
          :WCODCLA, :WTRIBUTACAOEXTERIOR
  do
  begin
    BDCODTIPO = 272; -- Cálculos gerados no Único Folha

    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end

    if (WEMPATU = 0) then
      WEMPATU = WCODEMP;

    if (WCOLATU = 0) then
      WCOLATU = WCODCOL;

    if ((WORDEMATU = 0) or (WORDEMATU is null)) then --173688 - João Victor - 02.02.23
      WORDEMATU = WORDEM;

    if (WINIAQUISATU is null) then
      WINIAQUISATU = WINIAQUIS;

    if (WCODFEATU = 0) then
      WCODFEATU = WCODFE;

    if (WDATAATU is null) then
      WDATAATU = WDATA;

    if (WDATAFEATU is null) then
      WDATAFEATU = WDATAFE;

    if (WREFABOATU = 0) then
      WREFABOATU = WREFABO;

    if (WREFIRRFESOCIALATU = -1) then
      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;

    if (WVALORDESCSIMPLATU = 0) then
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
    if (WVALORDIFDESCSIMPLATU = 0) then
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
    if (WTIPODEDUCAOATU = 0) then
      WTIPODEDUCAOATU = WTIPODEDUCAO;

    if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WINIAQUIS <> WINIAQUISATU) or (WCODFE <> WCODFEATU)) then
    begin
      if (WDATAATU is null) then
      begin
        if (WDATAFEATU is null) then
          WDATAATU = cast((substring(WREFABOATU from 1 for 4) || '-' || substring(WREFABOATU from 5 for 2) || '-01') as date);
        else
          WDATAATU = WDATAFEATU;
      end

      WREFPAGTO = cast((substring(cast(WDATAATU as varchar(10)) from 1 for 4) || substring(cast(WDATAATU as varchar(10)) from 6 for 2)) as integer);
      WREFINIGOZO = cast((substring(cast(WDATAFE as varchar(10)) from 1 for 4) || substring(cast(WDATAFE as varchar(10)) from 6 for 2)) as integer);

      if (WREFPAGTO >= PRREFINI and
          WREFPAGTO <= PRREFFIM) then
      begin

        if ((WEMPATU = BDCODEMP) and
            (WCOLATU = BDCODCOL) and
            (WREFPAGTO = BDREF) and
            (WCODFEATU <> BDCODFE)) then
          WDEPATU = 0;

        BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
        BDCODEMP = WEMPATU;
        BDCODCOL = WCOLATU;
        BDREF = WREFPAGTO;
        BDREFPAG = WREFPAGTO;
        BDREFINIGOZO = WREFINIGOZO;
        BDRENDTRIBUTAVEL = WBASEIR;
        BDINSS = WINSSN;
        BDIR = WIR;
        BDDEP = WDEPATU;
        BDLUCROPJ = WLUCROPJ;
        BDDESPMED = WDESPMED;
        BDAJCUSTOS = WAJCUS;
        BDPENJUD = WPENJUD;
        BDPENALIM = WPENALIM;
        BDPREVPRIV = WPREPRI;
        BDINDRESC = WINDRESC;
        BDVALABO = WVALABO;

        BDRENDISENTOS = WRENDIS;
        BDDRENDISENTOS = WDRENDIS;
        BDDATAPGTO = WDATAATU;
        BDTIPO = 3; -- Férias
        BDINFADIC = '';
        BDCODFE = WCODFEATU;
        BDINIPERAQUIS = WINIAQUISATU;
        BDDATAPROC = WDATAPROCA;
        BDHORAPROC = WHORAPROCA;
        BDORDEM = WORDEMATU; --173688 - João Victor - 02.02.23

        if (WDATAFEATU is not null) then
          BDINFADIC = BDINFADIC || 'Período de gozo: ' || substring(cast(WDATAFEATU as varchar(10)) from 9 for 2) || '/' || substring(cast(WDATAFEATU as varchar(10)) from 6 for 2) || '/' || substring(cast(WDATAFEATU as varchar(10)) from 1 for 4) || ' até ' || substring(cast(WDATAFEFIMATU as varchar(10)) from 9 for 2) || '/' || substring(cast(WDATAFEFIMATU as varchar(10)) from 6 for 2) || '/' || substring(cast(WDATAFEFIMATU as varchar(10)) from 1 for 4);

        if (BDINFADIC <> '') then
          BDINFADIC = BDINFADIC || '; ';

        BDINFADIC = BDINFADIC || 'Código: ' || WCODFEATU;

        if (BDVALABO > 0) then
        begin
          if (BDINFADIC <> '') then
            BDINFADIC = BDINFADIC || '; ';

          BDINFADIC = BDINFADIC || 'Abono: ' || substring(WREFABOATU from 5 for 2) || '/' || substring(WREFABOATU from 1 for 4);
        end

        if (PRATUALIZAINFODESCSIMPLE = true) then
        begin
          WSQLAUX = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, ' || ' BDPENSAOFERIAS, BDDEPFERIAS, BDPREVFERIAS, BDINSSFERIAS, ' || ' BDVALORSIMPLIUTILIZADOFERIAS, BDVALORESDEFERIAS, BDRENDTRIBUTAVELFERIAS) ' || ' values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPAGTO || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', TRUE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';

          execute statement WSQLAUX;
        end

        BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
        BDAUXILIOMORADIA = 0;
        BDDIARIA = 0;
        BDBOLSAMEDICO = 0;
        BDJUROSMORA = 0;
        BDINCIDESOCIAL = WINCIDESOCIAL;
        BDINCIDESOCIALFER = WINCIDESOCIALFER;
        suspend;
      end

      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;
      WEMPATU = WCODEMP;
      WCOLATU = WCODCOL;
      WDATAATU = WDATA;
      WINIAQUISATU = WINIAQUIS;
      WCODFEATU = WCODFE;
      WDATAFEATU = WDATAFE;
      WREFABOATU = WREFABO;
      WORDEMATU = WORDEM; --173688 - João Victor - 02.02.23

      WBASEIR = 0;
      WINSSN = 0;
      WIR = 0;
      WDEPATU = 0;
      WLUCROPJ = 0;
      WDESPMED = 0;
      WAJCUS = 0;
      WPENJUD = 0;
      WPENALIM = 0;
      WPREPRI = 0;
      WINDRESC = 0;
      WVALABO = 0;
      WRENDIS = 0;
      WDRENDIS = '';
      WGCLASS = '';
      -- wordem     = 0;
      WTIPODEDUCAOATU = WTIPODEDUCAO;
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
      WINCIDESOCIAL = 0;
      WINCIDESOCIALFER = 0;
    end

    if (WDATAFE is null) then
      WREF = WREFABO;
    else
      WREF = cast((substring(cast(WDATAFE as varchar(10)) from 1 for 4) || substring(cast(WDATAFE as varchar(10)) from 6 for 2)) as integer);

    -- soma as bases
    WCODINCIDIRRF = 0;
    select first 1 BDTIPOCODVER, BDIRVER, BDRENDISENTOIRVER, BDCODINCIDIRRF
    from VRH_BASE_TVERBAS_REF
    where BDCODVER = :WCODVER and BDREFVER <= :wref
    order by BDCODVER desc, BDREFVER desc
    into :WTIPOCODVER, :WIRVER, :WRENDISENTOVER, :WCODINCIDIRRF;

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end


    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
      begin
        WIRVER = 0;
      end
    else
    --    if (wtipocodver <= 1) then
    begin
      if (WIRVER = 2) then -- IR Férias
      begin
        if (WTIPOCODVER = 0) then -- provento
          WBASEIR = WBASEIR + WVALOR;
        else
        if (WTIPOCODVER = 1) then -- desconto
        begin
          --                                      INSS                                              Obrigações IR
          if (substring(WCLASSIF from 1 for 7) <> '9.010.0' and
              substring(WCLASSIF from 1 for 5) <> '0.030' and
              substring(WCLASSIF from 1 for 7) <> '3.001.8') then
            WBASEIR = WBASEIR - WVALOR;
        end
      end

      --                                     IR
      if (substring(WCLASSIF from 1 for 7) = '9.010.1') then
        WIR = WIR + WVALOR;
    end

      --                                     INSS
      if (substring(WCLASSIF from 1 for 7) = '9.010.0') then
        WINSSN = WINSSN + WVALOR;
      --                                     Lucro pessoa jurídica
      if (substring(WCLASSIF from 1 for 9) = '0.040.0.2') then
        WLUCROPJ = WLUCROPJ + WVALOR;
      --                                     Despesas médicas                                     Complemento de despesas médicas
      if ((substring(WCLASSIF from 1 for 9) = '0.030.1.0') or (substring(WCLASSIF from 1 for 9) = '0.420.0.2') or (substring(WCLASSIF from 1 for 9) = '3.010.0.0')) then
        WDESPMED = WDESPMED + WVALOR;
      --                                     Lucro pessoa jurídica
      if (substring(WCLASSIF from 1 for 9) = '0.040.0.2') then
        WLUCROPJ = WLUCROPJ + WVALOR;
      --                                     Ajuda de custos
      if (substring(WCLASSIF from 1 for 9) = '0.040.0.1') then
        WAJCUS = WAJCUS + WVALOR;
      --                                     Pensões judiciais
      if (substring(WCLASSIF from 1 for 9) = '3.001.8.0') then
        WPENJUD = WPENJUD + WVALOR;
      --                                     Pensões alimentícias
      if (substring(WCLASSIF from 1 for 9) = '3.001.8.1') then
        WPENALIM = WPENALIM + WVALOR;
      WISENTOABONO = 0;
      --                                      Abono pecuniário                                1/3 de abono pecuniário
      if ((substring(WCLASSIF from 1 for 5) = '3.003') or (substring(WCLASSIF from 1 for 5) = '3.004') and
          (WIRVER <> 2)) then
      begin
        WVALABO = WVALABO + WVALOR;
      end
      else

      --                                     Previdência complementar 160514 LuizCovre 05/07/2022
      if (substring(WCLASSIF from 1 for 9) = '3.009.0.0') then
        WPREPRI = WPREPRI + WVALOR;
      else

      -- Rendimentos isentos
      if ((upper(WRENDISENTOVER) = 'TRUE') and
          (WISENTOABONO = 0)) then
      begin
        WRENDIS = WRENDIS + WVALOR;
        WI = 0;

        if (PRVEIODOTOTALIZADOR = 1) then
          select POS
          from POS(:WCLASSIF, :WGCLASS)
          into :WI;
        else
          select POS
          from POS(substring(:WCLASSIF from 1 for 5), :WGCLASS)
          into :WI;

        if (WI = 0) then
        begin
          WDESCVER2 = '';

          if (PRVEIODOTOTALIZADOR = 1) then
          begin
            select first 1 BDDESCVER
            from VRH_BASE_TVERBAS
            where BDCLAVER = :WCLASSIF
            into WDESCVER2;
            WGCLASS = WGCLASS || ';' || :WCLASSIF;
          end
          else
          begin
            select first 1 BDDESCVER
            from VRH_BASE_TVERBAS
            where BDCLAVER = substring(:WCLASSIF from 1 for 5)
            into WDESCVER2;
            WGCLASS = WGCLASS || ';' || substring(:WCLASSIF from 1 for 5);
          end

          if (WDRENDIS <> '') then
            WDRENDIS = WDRENDIS || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS = substring(WDRENDIS || WDESCVER2 from 1 for 999);
          else
            WDRENDIS = substring(WDRENDIS || WDESCVER2 from 1 for 200);
        end

      if (coalesce(WCODINCIDIRRF, 0) in (11, 12, 14, 41, 42, 51, 52, 54)) then
        WINCIDESOCIAL = 1;

      if (coalesce(WCODINCIDIRRF, 0) in (13, 43, 53)) then
        WINCIDESOCIALFER = 1;
    end

    WDEPATU = WDEP;
    WDATAFEFIMATU = WDATAFEFIM;
    WDATAPROCA = WDATAPROC;
    WHORAPROCA = WHORAPROC;
  end

  if (WEMPATU <> 0 and
      WCOLATU <> 0 and
      WINIAQUISATU is not null and
      WCODFEATU <> 0) then
  begin
    if (WDATAATU is null) then
    begin
      if (WDATAFEATU is null) then
        WDATAATU = cast((substring(WREFABOATU from 1 for 4) || '-' || substring(WREFABOATU from 5 for 2) || '-01') as date);
      else
        WDATAATU = WDATAFEATU;
    end

    WREFPAGTO = cast((substring(cast(WDATAATU as varchar(10)) from 1 for 4) || substring(cast(WDATAATU as varchar(10)) from 6 for 2)) as integer);
    WREFINIGOZO = cast((substring(cast(WDATAFE as varchar(10)) from 1 for 4) || substring(cast(WDATAFE as varchar(10)) from 6 for 2)) as integer);

    if (WREFPAGTO >= PRREFINI and
        WREFPAGTO <= PRREFFIM) then
    begin
      if ((WEMPATU = BDCODEMP) and
          (WCOLATU = BDCODCOL) and
          (WREFPAGTO = BDREF) and
          (WCODFE <> BDCODFE)) then
        WDEPATU = 0;

      BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
      BDCODEMP = WEMPATU;
      BDCODCOL = WCOLATU;
      BDREF = WREFPAGTO;
      BDREFPAG = WREFPAGTO;
      BDREFINIGOZO = WREFINIGOZO;
      BDRENDTRIBUTAVEL = WBASEIR;
      BDINSS = WINSSN;
      BDIR = WIR;
      BDDEP = WDEPATU;
      BDLUCROPJ = WLUCROPJ;
      BDDESPMED = WDESPMED;
      BDAJCUSTOS = WAJCUS;
      BDPENJUD = WPENJUD;
      BDPENALIM = WPENALIM;
      BDPREVPRIV = WPREPRI;
      BDINDRESC = WINDRESC;
      BDRENDISENTOS = WRENDIS;
      BDDRENDISENTOS = WDRENDIS;
      BDDATAPGTO = WDATAATU;
      BDTIPO = 3; -- Férias
      BDINFADIC = '';
      BDCODFE = WCODFEATU;
      BDINIPERAQUIS = WINIAQUISATU;
      BDDATAPROC = WDATAPROCA;
      BDHORAPROC = WHORAPROCA;
      BDORDEM = WORDEM;

      if (WDATAFEATU is not null) then
        BDINFADIC = BDINFADIC || 'Período de gozo: ' || substring(cast(WDATAFEATU as varchar(10)) from 9 for 2) || '/' || substring(cast(WDATAFEATU as varchar(10)) from 6 for 2) || '/' || substring(cast(WDATAFEATU as varchar(10)) from 1 for 4) || ' até ' || substring(cast(WDATAFEFIMATU as varchar(10)) from 9 for 2) || '/' || substring(cast(WDATAFEFIMATU as varchar(10)) from 6 for 2) || '/' || substring(cast(WDATAFEFIMATU as varchar(10)) from 1 for 4);

      if (BDINFADIC <> '') then
        BDINFADIC = BDINFADIC || '; ';
      BDINFADIC = BDINFADIC || 'Código: ' || WCODFEATU;

      BDVALABO = WVALABO;

      if (BDVALABO > 0) then
      begin
        if (BDINFADIC <> '') then
          BDINFADIC = BDINFADIC || '; ';

        BDINFADIC = BDINFADIC || 'Abono: ' || substring(WREFABOATU from 5 for 2) || '/' || substring(WREFABOATU from 1 for 4);
      end

      if (PRATUALIZAINFODESCSIMPLE = true) then
      begin
        WSQLAUX = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, ' || ' BDPENSAOFERIAS, BDDEPFERIAS, BDPREVFERIAS, BDINSSFERIAS, ' || ' BDVALORSIMPLIUTILIZADOFERIAS, BDVALORESDEFERIAS, BDRENDTRIBUTAVELFERIAS) ' || ' values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPAGTO || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', TRUE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';

        execute statement WSQLAUX;
      end

      BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
      BDAUXILIOMORADIA = 0;
      BDDIARIA = 0;
      BDBOLSAMEDICO = 0;
      BDJUROSMORA = 0;
      BDINCIDESOCIAL = WINCIDESOCIAL;
      BDINCIDESOCIALFER = WINCIDESOCIALFER;
      suspend;
    end

  end

  /*
      DADOS IMPORTADOS OU CADASTRADOS NA FICHA
  */
  for select BDCODEMP, BDCODCOL, BDREF, BDREFPAG, BDTIPO, BDRENDTRIBUTAVEL, BDINSS, BDIR, BDDEP, BDLUCROPJ,
             BDDESPMED, BDAJCUSTOS, BDPENJUD, BDPENALIM, BDPREVPRIV, BDINDRESC, BDVALABO, BDRENDISENTOS,
             BDDRENDISENTOS, BDDATAPGTO, BDINFADIC, BDCODFE, BDINIPERAQUIS, BDORDEM, BDVALORDESCONTOSIMPLIFICADO,
             BDAUXILIOMORADIA, BDDIARIA, BDBOLSAMEDICO, BDJUROSMORA, BDCODFIR, BDDEMDEV, BDCODTIPO, bdrefirrfesocial
      from SP_VRHF_DADOS_IR_FICHAFE(:prcodemp, :prcodcol, :prrefini, :prreffim, :prpuxarfiliais, :prcodmatriz, :pratualizainfodescsimple)
  into :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR, :BDDEP, :BDLUCROPJ,
       :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM, :BDPREVPRIV, :BDINDRESC, :BDVALABO, :BDRENDISENTOS,
       :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDCODFE, :BDINIPERAQUIS, :BDORDEM, :BDVALORDESCONTOSIMPLIFICADO,
       :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA, :BDCODFIR, :BDDEMDEV, :BDCODTIPO, :bdrefirrfesocial
  do
    suspend;

end^

/* Restore proc. body: SP_VRHF_DADOS_IR_FT */
create or alter procedure SP_VRHF_DADOS_IR_FT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PREXPORTACAO integer = 0,
    PRPORCC smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBASE13 numeric(18,6),
    BDVALOR13 numeric(18,6),
    BDBOLSAESTUDOS numeric(18,6),
    BDTIPODEDUCAOFOLHA integer,
    BDVALORDIFERENCADEDUCOES numeric(9,2),
    BDVALORDESCONTOSIMPLIFICADO numeric(9,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WEHINDRESC varchar(5);
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WSQL varchar(32700);
declare variable WTIPODEDUCAO integer;
declare variable WVALORDIFDESCSIMPL numeric(18,2);
declare variable WVALORDESCSIMPL numeric(18,2);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WDESCVER varchar(40);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSSN numeric(18,6);
declare variable WIR numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(999);
declare variable WDATARESC date;
declare variable WDATAPAGRESC date;
declare variable WCODPRES integer;
declare variable WDESCPRES varchar(110);
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WDESCCC varchar(100);
declare variable WREFINI integer;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WTIPOMOV integer;
declare variable WGCLASS varchar(13000);
declare variable WDESCVER2 varchar(70);
declare variable WI integer;
declare variable WPREVPRIVCAD numeric(18,6);
declare variable WISENTOABONO integer;
declare variable WPALANCMANUAL numeric(18,6);
declare variable WBASE13 numeric(18,6);
declare variable WVALOR13 numeric(18,6);
declare variable WBASEIRFE numeric(18,6);
declare variable WVALORIRFE numeric(18,6);
declare variable WRUBRICA integer;
declare variable WCATEGORIAESOCIAL integer;
declare variable WBOLSAESTUDOS numeric(18,6);
declare variable WDRENDIS2 varchar(999);
declare variable WDRENDIS3 varchar(999);
declare variable WSQLAUXSIMPLI varchar(3000);
declare variable WTIPODEDUCAOATU integer;
declare variable WVALORDESCSIMPLATU numeric(18,2);
declare variable WVALORDIFDESCSIMPLATU numeric(18,2);
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WAUXILIOMORADIA numeric(18,6);
declare variable WDIARIA numeric(18,6);
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WJUROSMORA numeric(18,6);
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WINCIDESOCIALFER integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
declare variable WDTREFINI varchar(10);
declare variable WDTREFFIM varchar(10);
declare variable WULTDIA varchar(2);
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WGRAVARUBRICA integer;
begin
  /* FOLHA TOMADOR */
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  if (upper(PRCODEMP) = 'TMP_EMPRESAS_SELECT') then
    WUSARTMP_EMP_SELECT = 1;

  if (upper(PRCODCOL) = 'TEMP_FILTRO_COLCON_REL') then
    WUSARTMP_COL_SELECT = 1;

  if (cast(substring(PRREFINI from 5 for 2) as integer) = 1) then
    WREFINI = cast((cast((cast(substring(PRREFINI from 1 for 4) as integer) - 1) as varchar(4)) || '12') as integer);
  else
  if (cast(substring(PRREFINI from 5 for 2) as integer) <= 10) then
    WREFINI = cast((substring(PRREFINI from 1 for 4) || '0' || cast((cast((substring(PRREFINI from 5 for 2)) as integer) - 1) as varchar(1))) as integer);
  else
    WREFINI = cast((substring(PRREFINI from 1 for 4) || cast((cast((substring(PRREFINI from 5 for 2)) as integer) - 1) as varchar(2))) as integer);

  WDTREFINI = substring(PRREFINI from 1 for 4) || '-' || substring(PRREFINI from 5 for 2) || '-01';

  WULTDIA = '31';
  select first 1 cast(ULTDIA as varchar(20))
  from ULTIMO_DIA_MES(cast(substring(:PRREFFIM from 5 for 2) as smallint), cast(substring(:PRREFFIM from 1 for 4) as integer))
  into :WULTDIA;
  WULTDIA = lpad(trim(coalesce(WULTDIA, '00')), 2, '0');

  WDTREFFIM = substring(PRREFFIM from 1 for 4) || '-' || substring(PRREFFIM from 5 for 2) || '-' || WULTDIA;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  if (PRPUXARFILIAIS = 0) then
  begin
    WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDCODVER,FOL.BDVALVFT,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDTIPODEDUCAOFOLHA,FOLN.BDVALORDESCONTOSIMPLIFICADO,FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
    WSQL = WSQL || 'from VRHF_EMP_TFOLHATOMADOR FOLN ';

    if (WUSARTMP_EMP_SELECT = 1) then
       WSQL = WSQL || 'INNER JOIN tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FOLN.BDCODEMP) ';
    if (WUSARTMP_COL_SELECT = 1) then
       WSQL = WSQL || 'JOIN TEMP_FILTRO_COLCON_REL TEM ON (TEM.BDCODEMP = FOLN.BDCODEMP AND TEM.BDCODCOL = FOLN.BDCODCOL) ';


    WSQL = WSQL || 'inner join VRHF_EMP_TVERBATOMADOR FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDREFTOMADOR = FOLN.BDREFTOMADOR and FOL.BDORDEM = FOLN.BDORDEM) ';
    WSQL = WSQL || 'inner join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
    WSQL = WSQL || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOLN.BDCODEMP) and (RESC.BDCODCOL = FOLN.BDCODCOL) and (RESC.BDREFRESCISAO >= ' || PRREFFIM || ') ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOLN.BDREFTOMADOR ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where FOLN.BDREFIRRFESOCIAL between ' || PRREFINI || ' and ' || PRREFFIM || ' ';
    else
    begin
      WSQL = WSQL || 'where ((FOLN.BDREFTOMADOR between ' || WREFINI || ' and ' || PRREFFIM || ') or ';
      WSQL = WSQL || '       (FOLN.BDREFTOMADOR <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= ' || WREFINI || ' and RESC.BDREFPAGRESCISAO <= ' || PRREFFIM || ')) ';
      WSQL = WSQL || 'and (FOLN.BDDATAPGTOFT between ''' || WDTREFINI || ''' and ''' || WDTREFFIM || ''')';
    end


    if ((PRCODEMP is not null) and
        (PRCODEMP <> '') and
        (WUSARTMP_EMP_SELECT = 0)) then
      WSQL = WSQL || ' and ' || PRCODEMP;

    if ((PRCODCOL is not null and
        PRCODCOL <> '') and
        (WUSARTMP_COL_SELECT = 0)) then
      WSQL = WSQL || ' and ' || PRCODCOL;

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDCODVER ';
    else
      WSQL = WSQL || ' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM ';
  end
  else
  begin
    WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDCODVER,FO.BDVALVFT,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDTIPODEDUCAOFOLHA,FOLN.BDVALORDESCONTOSIMPLIFICADO,FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
    WSQL = WSQL || 'from VRHF_EMP_TFOLHATOMADOR FOLN join TEMPRESAS EMAT on (EMAT.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_EMP_SELECT = 1) then
      WSQL = WSQL || 'join tmp_empresas_select TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
      WSQL = WSQL || 'join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FOLN.BDCODEMP and TEM.BDCODCOL = FOLN.BDCODCOL) ';

    WSQL = WSQL || 'inner join VRHF_EMP_TVERBATOMADOR FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDREFTOMADOR = FOLN.BDREFTOMADOR and FO.BDORDEM = FOLN.BDORDEM) ';
    WSQL = WSQL || 'inner join VRH_BASE_TVERBAS VER on (VER.bdcodver = FO.bdcodver) ';
    WSQL = WSQL || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOLN.BDCODEMP) and (RESC.BDCODCOL = FOLN.BDCODCOL) and (RESC.BDREFRESCISAO >= ' || PRREFFIM || ') ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOLN.BDREFTOMADOR ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where FOLN.BDREFIRRFESOCIAL between ' || PRREFINI || ' and ' || PRREFFIM || ' ';
    else
    begin
      WSQL = WSQL || 'where ((FOLN.BDREFTOMADOR >= ' || WREFINI || ' and FOLN.BDREFTOMADOR <= ' || PRREFFIM || ') or ';
      WSQL = WSQL || '       (FOLN.BDREFTOMADOR <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= ' || WREFINI || ' and RESC.BDREFPAGRESCISAO <= ' || PRREFFIM || ')) and ';
      WSQL = WSQL || '      (FOLN.BDDATAPGTOFT between ''' || WDTREFINI || ''' and ''' || WDTREFFIM || ''')';
    end

    if (WUSARTMP_EMP_SELECT = 0) then
    begin
      if (PRCODEMP is not null and
          PRCODEMP <> '') then
        WSQL = WSQL || ' and ((' || REPLACE(UPPER(PRCODEMP), 'FOL.', 'FOLN.') || ')';

      if (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '') then
        WSQL = WSQL || ' or (' || REPLACE(UPPER(PRCODMATRIZ), 'FOL.', 'EMAT.') || ')';

      if ((PRCODEMP is not null and
          PRCODEMP <> '') or (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '')) then
        WSQL = WSQL || ') ';
    end

    if ((PRCODCOL is not null and
        PRCODCOL <> '') and
        (WUSARTMP_COL_SELECT = 0)) then
      WSQL = WSQL || ' and ' || REPLACE(upper(PRCODCOL), 'FOL.', 'FOLN.') || ' ';

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FO.BDCODVER ';
    else
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM ';
  end

  WEMPATU = 0;
  WCOLATU = 0;
  WREFATU = 0;
  WORDEMATU = -1;
  WBASEIR = 0;
  WINSSN = 0;
  WIR = 0;
  WDEPATU = 0;
  WDATAATU = null;
  WLUCROPJ = 0;
  WDESPMED = 0;
  WAJCUS = 0;
  WBOLSAESTUDOS = 0;
  WPENJUD = 0;
  WPENALIM = 0;
  WPREPRI = 0;
  WINDRESC = 0;
  WVALABO = 0;
  WRENDIS = 0;
  WDRENDIS = '';
  WDRENDIS2 = '';
  WDRENDIS3 = '';
  WDATAPROCA = null;
  WHORAPROCA = null;
  WGCLASS = '';
  WBASE13 = 0;
  WVALOR13 = 0;
  WBASEIRFE = 0;
  WVALORIRFE = 0;
  WVALORDESCSIMPL = 0;
  WVALORDIFDESCSIMPL = 0;
  WTIPODEDUCAO = 0;
  WVALORDESCSIMPLATU = 0;
  WVALORDIFDESCSIMPLATU = 0;
  WTIPODEDUCAOATU = 0;
  WAUXILIOMORADIA = 0;
  WDIARIA = 0;
  WBOLSAMEDICO = 0;
  WJUROSMORA = 0;
  WINCIDESOCIAL = 0;
  WINCIDESOCIALFER = 0;
  WREFIRRFESOCIALATU = -1;

  for execute statement WSQL
          into :WREFIRRFESOCIAL, :WCODEMP, :WCODCOL, :WREF, :WORDEM, :WCODVER, :WVALOR, :WCLASSIF, :WDESCVER,
          :WTIPODEDUCAO, :WVALORDESCSIMPL, :WVALORDIFDESCSIMPL, :WCODCLA, :WTRIBUTACAOEXTERIOR
  do
  begin
    BDCODTIPO = 272; -- Cálculos feitos no Único Folha

    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end

    if (WEMPATU = 0) then
      WEMPATU = WCODEMP;

    if (WCOLATU = 0) then
      WCOLATU = WCODCOL;

    if (WREFATU = 0) then
      WREFATU = WREF;

    if (PRPORCC = 0) then
      WORDEMATU = coalesce(WORDEM, 0);
    else
    if (WORDEMATU = -1) then
      WORDEMATU = coalesce(WORDEM, 0);

    if (WTIPODEDUCAOATU = 0) then
      WTIPODEDUCAOATU = WTIPODEDUCAO;

    if (WVALORDESCSIMPLATU = 0) then
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;

    if (WVALORDIFDESCSIMPLATU = 0) then
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;

    if (WREFIRRFESOCIALATU = -1) then
      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;

    if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WREF <> WREFATU) or (WORDEMATU <> coalesce(WORDEM, 0))) then
    begin
      if (PRIRRFESOCIAL = true) then
      begin
        select max(BDDATAIRRFESOCIAL), max(BDDATAPROCFT), max(BDHORAPROCFT), sum(BDDEPFT)
        from VRHF_EMP_TFOLHATOMADOR
        where BDREFTOMADOR = :WREFATU and
              BDCODEMP = :WEMPATU and
              BDCODCOL = :WCOLATU
        into :WDATAATU, :WDATAPROCA, :WHORAPROCA, :WDEPATU;
      end
      else
      begin
        select max(BDDATAPGTOFT), max(BDDATAPROCFT), max(BDHORAPROCFT), sum(BDDEPFT)
        from VRHF_EMP_TFOLHATOMADOR
        where BDREFTOMADOR = :WREFATU and
              BDCODEMP = :WEMPATU and
              BDCODCOL = :WCOLATU
        into :WDATAATU, :WDATAPROCA, :WHORAPROCA, :WDEPATU;
      end
      WCODPRES = null;
      WDESCPRES = null;
      WDATARESC = null;
      WDATAPAGRESC = null;
      WTIPOMOV = 0;

      if (PRPREVIARESC = 1) then
      begin
        select X.BDDATARESCISAOPREV, X.BDDATAPAGRESCISAOPREV, X.BDCODPRES, Y.BDDESCPRES, coalesce(Y.BDTIPOMOV, 0)
        from VRH_EMP_TRESCISAO_PREVIA X
        join VRH_BASE_TPREPRESC Y on (Y.BDCODPRES = X.BDCODPRES)
        where X.BDCODEMP = :WEMPATU and
              X.BDCODCOL = :WCOLATU and
              X.BDREFRESCISAOPREV = :WREFATU
        into :WDATARESC, :WDATAPAGRESC, :WCODPRES, :WDESCPRES, :WTIPOMOV;
      end
      else
      begin
        select X.BDDATARESCISAO, X.BDDATAPAGRESCISAO, X.BDCODPRES, Y.BDDESCPRES, coalesce(Y.BDTIPOMOV, 0)
        from VRH_EMP_TRESCISAO X
        join VRH_BASE_TPREPRESC Y on (Y.BDCODPRES = X.BDCODPRES)
        where X.BDCODEMP = :WEMPATU and
              X.BDCODCOL = :WCOLATU and
              X.BDREFRESCISAO = :WREFATU
        into :WDATARESC, :WDATAPAGRESC, :WCODPRES, :WDESCPRES, :WTIPOMOV;
      end

      WDESCCC = null;
      WI = null;
      select first 1 PFN.BDCODTPCC,
                     case
                       when coalesce(CUS.BDNOMETOM, '') <> '' then CUS.BDNOMETOM
                       when coalesce(CC.BDNOMCTA, '') <> '' then CC.BDNOMCTA
                       else CC.BDAPECTA
                     end
      from VRHF_EMP_TPREPFN PFN
      left outer join VRH_BASE_TCUSTOM CUS on (CUS.BDCODCENTRO = PFN.BDCODCENTRO and
            CUS.BDCODTPCC = PFN.BDCODTPCC)
      left outer join CENTROS_TPCC CC on (CC.BDCODCENTRO = PFN.BDCODCENTRO and
            CC.BDCODTPCC = PFN.BDCODTPCC)
      where PFN.BDCODEMP = :WEMPATU and
            PFN.BDCODCOL = :WCOLATU and
            PFN.BDORDEM = :WORDEMATU
      into :WI, :WDESCCC;

      if (WI is null) then
      begin
        select first 1 BDNOMEMP
        from TEMPRESAS_REF
        where BDCODEMP = :WEMPATU and
              BDREFEMP <= :WREFATU
        order by BDCODEMP desc, BDREFEMP desc
        into :WDESCCC;

        if (PRIRRFESOCIAL = false) then
        begin
          if ((WTIPOMOV < 1) and
              ((WDATAPAGRESC is not null) or (WDATARESC is not null))) then
          begin
            if (WDATAPAGRESC is not null) then
              WDATAATU = WDATAPAGRESC;
            else
              WDATAATU = WDATARESC;
          end
        end
      end

      WREFPAGTO = cast((substring(cast(WDATAATU as varchar(10)) from 1 for 4) || substring(cast(WDATAATU as varchar(10)) from 6 for 2)) as integer);

      if (WREFPAGTO >= PRREFINI and
          WREFPAGTO <= PRREFFIM) then
      begin
        WPREVPRIVCAD = 0;
        if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WREF <> WREFATU) or (WORDEMATU <> coalesce(WORDEM, 0))) then
        begin
          select sum(coalesce(LANPREV.BDVALMENSAL, 0))
          from VRH_EMP_TLANCPREVCOMP LANPREV join(select BDCODCADPREV
                                                  from VRH_BASE_TCADPREVCOMP
                                                  where BDNATPREV <> 2) CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV) /* 184717 Leonardo Schwab 16/11/2023 */
          where LANPREV.BDCODEMP = :WEMPATU and
                LANPREV.BDCODCOL = :WCOLATU and
                LANPREV.BDREFINI <= :WREFATU and
                ((coalesce(LANPREV.BDREFFIN, 0) = 0) or (coalesce(LANPREV.BDREFFIN, 0) >= :WREFATU))
          into :WPREVPRIVCAD;

          select sum(coalesce(BDBIRRF13FT, 0)) BDBIRRF13FT, sum(coalesce(BDIRRF13FT, 0)) BDIRRF13FT
          from VRHF_EMP_TFOLHATOMADOR
          where BDCODEMP = :WEMPATU and
                BDCODCOL = :WCOLATU and
                BDREFTOMADOR = :WREFATU
          into :WBASE13, :WVALOR13;
        end

        BDCODEMP = WEMPATU;
        BDCODCOL = WCOLATU;
        BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
        BDREF = WREFATU;
        BDORDEM = WORDEMATU;
        BDREFPAG = WREFPAGTO;
        BDRENDTRIBUTAVEL = WBASEIR;
        BDINSS = WINSSN;
        BDIR = WIR;


        if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = FALSE) then
           begin
              BDBASE13 = WBASE13;
              BDVALOR13 = WVALOR13;
           end

        if (WBASEIR + WINSSN + WIR > 0) then
          BDDEP = WDEPATU;
        else
          BDDEP = 0;

        WPALANCMANUAL = null;
        if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WREF <> WREFATU)) then
          select sum(BDVALDIRF)
          from VRH_EMP_TVALBENEF_DIRF
          where BDCODEMP = :WEMPATU and
                BDCODCOL = :WCOLATU and
                BDANODIRF = :WREFPAGTO
          into :WPALANCMANUAL;

        WCATEGORIAESOCIAL = null;
        select first 1 BDCATEGORIAESOCIAL
        from VRHF_EMP_TCOLCON_FGTSGPS
        where BDCODEMP = :WEMPATU and
              BDCODCOL = :WCOLATU and
              BDREFCOL <= :WREFATU
        order by BDCODEMP desc, BDCODCOL desc, BDREFCOL desc
        into :WCATEGORIAESOCIAL;
        WCATEGORIAESOCIAL = coalesce(WCATEGORIAESOCIAL, 0);

        if (WPALANCMANUAL is null) then
          WPALANCMANUAL = 0;

        BDLUCROPJ = WLUCROPJ;
        BDDESPMED = WDESPMED;
        BDAJCUSTOS = WAJCUS;
        if (WCATEGORIAESOCIAL = 903) then
        begin
          BDBOLSAESTUDOS = WBOLSAESTUDOS;
          if (WDRENDIS2 <> '') then
          begin
            if (WDRENDIS <> '') then
              WDRENDIS = WDRENDIS || ' ,';

            if (PRVEIODOTOTALIZADOR = 1) then
              WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 999);
            else
              WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 200);
          end
        end
        else
        begin
          BDAJCUSTOS = BDAJCUSTOS + WBOLSAESTUDOS;
          if (WDRENDIS3 <> '') then
          begin
            if (WDRENDIS <> '') then
              WDRENDIS = WDRENDIS || ' ,';

            if (PRVEIODOTOTALIZADOR = 1) then
              WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 999);
            else
              WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 200);
          end
        end
        BDPENJUD = WPENJUD;
        BDPENALIM = WPENALIM + WPALANCMANUAL;

        if (coalesce(:WPREVPRIVCAD, 0) > 0) then
        begin
          if (coalesce(:WPREPRI, 0) > 0) then
            BDPREVPRIV = WPREPRI;
          else
          if (coalesce(:WPREVPRIVCAD, 0) > 0) then
            BDPREVPRIV = WPREVPRIVCAD;
        end
        else
          BDPREVPRIV = 0;

        BDINDRESC = WINDRESC;
        BDVALABO = WVALABO;
        BDRENDISENTOS = WRENDIS;
        BDDRENDISENTOS = WDRENDIS;
        BDDATAPGTO = WDATAATU;
        BDDATAPROC = WDATAPROCA;
        BDHORAPROC = WHORAPROCA;
        BDBASE13 = WBASE13;
        BDVALOR13 = WVALOR13;
        BDTIPODEDUCAOFOLHA = WTIPODEDUCAO;
        BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPL;
        BDVALORDIFERENCADEDUCOES = WVALORDIFDESCSIMPL;

        BDAUXILIOMORADIA = WAUXILIOMORADIA;
        BDDIARIA = WDIARIA;
        BDBOLSAMEDICO = WBOLSAMEDICO;
        BDJUROSMORA = WJUROSMORA;
        BDINCIDESOCIAL = WINCIDESOCIAL;
        BDINCIDESOCIALFER = WINCIDESOCIALFER;

        if (WDATARESC is not null) then
        begin
          BDTIPO = 100; -- Folha normal rescisão
          BDINFADIC = substring(WORDEMATU || ' - ' || WDESCCC || '; ' || WCODPRES || ' - ' || WDESCPRES from 1 for 300);
        end
        else
        begin
          BDTIPO = 0; -- Folha normal
          BDINFADIC = substring(WORDEMATU || ' - ' || WDESCCC from 1 for 300);
        end

        if (PRATUALIZAINFODESCSIMPLE = true) then
        begin
          WSQLAUXSIMPLI = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, ' || ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, ' || ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) ' || ' values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPAGTO || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';

          execute statement WSQLAUXSIMPLI;
        end
        suspend;

        if ((WVALORIRFE >= 0) and
            (WBASEIRFE > 0)) then
        begin
          BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
          BDCODEMP = WEMPATU;
          BDCODCOL = WCOLATU;
          BDREF = WREFATU;
          BDORDEM = WORDEMATU;
          BDREFPAG = WREFPAGTO;
          BDRENDTRIBUTAVEL = WBASEIRFE;
          BDINSS = 0;
          BDIR = WVALORIRFE;
          BDBASE13 = 0;
          BDVALOR13 = 0;
          BDDEP = WDEPATU;
          BDLUCROPJ = 0;
          BDDESPMED = 0;
          BDAJCUSTOS = 0;
          BDPENJUD = 0;
          BDPENALIM = 0;
          BDPREVPRIV = 0;
          BDINDRESC = 0;
          BDVALABO = 0;
          BDRENDISENTOS = 0;
          BDDRENDISENTOS = '';
          BDDATAPGTO = WDATAATU;
          BDDATAPROC = WDATAPROCA;
          BDHORAPROC = WHORAPROCA;
          BDTIPO = 4;
          BDINFADIC = '';
          BDTIPODEDUCAOFOLHA = WTIPODEDUCAOATU;
          BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
          BDVALORDIFERENCADEDUCOES = WVALORDIFDESCSIMPLATU;
          BDAUXILIOMORADIA = 0;
          BDDIARIA = 0;
          BDBOLSAMEDICO = 0;
          BDJUROSMORA = 0;
          BDINCIDESOCIAL = 0;
          BDINCIDESOCIALFER = 0;
          suspend;
        end
      end

      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;
      WEMPATU = WCODEMP;
      WCOLATU = WCODCOL;
      WREFATU = WREF;
      WORDEMATU = WORDEM;

      WBASEIR = 0;
      WINSSN = 0;
      WIR = 0;
      WDEPATU = 0;
      WDATAATU = null;
      WLUCROPJ = 0;
      WDESPMED = 0;
      WAJCUS = 0;
      WBOLSAESTUDOS = 0;
      WPENJUD = 0;
      WPENALIM = 0;
      WPREPRI = 0;
      WINDRESC = 0;
      WVALABO = 0;
      WRENDIS = 0;
      WDRENDIS = '';
      WDRENDIS2 = '';
      WDRENDIS3 = '';
      WGCLASS = '';
      WBASE13 = 0;
      WVALOR13 = 0;
      WBASEIRFE = 0;
      WVALORIRFE = 0;
      WTIPODEDUCAOATU = WTIPODEDUCAO;
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
      WAUXILIOMORADIA = 0;
      WDIARIA = 0;
      WBOLSAMEDICO = 0;
      WJUROSMORA = 0;
      WINCIDESOCIAL = 0;
      WINCIDESOCIALFER = 0;
    end

    -- soma as bases
    WCODINCIDIRRF = 0;
    select first 1 BDTIPOCODVER, coalesce(BDIRVER, 0), BDRENDISENTOIRVER, BDINDRESC, BDCODINCIDIRRF
    from VRH_BASE_TVERBAS_REF
    where BDCODVER = :WCODVER and
          BDREFVER <= :WREFATU
    order by BDCODVER desc, BDREFVER desc
    into :WTIPOCODVER, :WIRVER, :WRENDISENTOVER, :WEHINDRESC, :WCODINCIDIRRF;
    begin

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end


    --    if (WTIPOCODVER <= 1) then
      if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
         WIRVER = 0;
      else
      begin
        --  IR Folha normal                                     IR VeA
        if ((WIRVER = 1) or (substring(WCLASSIF from 1 for 9) = '0.900.2.0')) then
        begin
          if (WTIPOCODVER = 0) then -- provento
            WBASEIR = WBASEIR + WVALOR;
          else
          if (WTIPOCODVER = 1) then -- desconto
          begin
            --                                      INSS                                              Obrigações IR
            if (substring(WCLASSIF from 1 for 7) <> '9.010.0' and
                substring(WCLASSIF from 1 for 5) <> '0.030') then
              WBASEIR = WBASEIR - WVALOR;
          end
        end

        if (WIRVER = 2) then -- IR Férias
        begin
          if (WTIPOCODVER = 0) then -- provento
            WBASEIRFE = WBASEIRFE + WVALOR;
          else
          if (WTIPOCODVER = 1) then -- desconto
          begin
            --                                      INSS                                              Obrigações IR
            if (substring(WCLASSIF from 1 for 7) <> '9.010.0' and
                substring(WCLASSIF from 1 for 5) <> '0.030' and
                substring(WCLASSIF from 1 for 7) <> '3.001.8') then
              WBASEIRFE = WBASEIRFE - WVALOR;
          end
        end


        if ((substring(WCLASSIF from 1 for 9) = '9.010.1.0') and
            (WDESCVER <> 'IR Férias (COVID-19)')) then -- IR folha normal
          WIR = WIR + WVALOR;

        if ((substring(WCLASSIF from 1 for 9) = '9.010.1.0') and
            (WDESCVER = 'IR Férias (COVID-19)')) then -- IR férias
          WVALORIRFE = WVALORIRFE + WVALOR;

      end

      if ((substring(WCLASSIF from 1 for 9) = '9.010.0.0') or (substring(WCLASSIF from 1 for 9) = '9.010.0.3')) then -- INSS folha normal / INSS 13º folha normal VeA
        WINSSN = WINSSN + WVALOR;


      if ((substring(WCLASSIF from 1 for 9) = '0.030.1.0') or (substring(WCLASSIF from 1 for 9) = '0.420.0.2') or (substring(WCLASSIF from 1 for 9) = '3.010.0.0')) then -- Despesas médicas / Complemento de despesas médicas
        WDESPMED = WDESPMED + WVALOR;

      --      if ((substring(WCLASSIF from 1 for 9) = '0.030.1.0') or (substring(WCLASSIF from 1 for 9) = '0.420.0.2')) then -- Despesas médicas / Complemento de despesas médicas
      --        WDESPMED = WDESPMED + WVALOR;

      --      if (substring(WCLASSIF from 1 for 9) = '0.040.0.3' and WIRVER = 0) then -- Diárias/Ajuda de custos
      --        WAJCUS = WAJCUS + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.040.0.1' and
          WIRVER = 0) then -- Ajuda de custos
      begin
        select first 1 BDCHAVE
        from VRH_BASE_TRUBRICAESOCIAL_VER
        where BDCODVER = :WCODVER
        into :WRUBRICA;

        if (WRUBRICA = 1350) then -- Bolsa estudos
          WBOLSAESTUDOS = WBOLSAESTUDOS + WVALOR;
        else
          WAJCUS = WAJCUS + WVALOR;
      end

      if (substring(WCLASSIF from 1 for 9) = '0.030.0.0') then -- Pensões judiciais
        WPENJUD = WPENJUD + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.030.0.1') then -- Pensões alimentícias
        WPENALIM = WPENALIM + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.030.1.2') then -- Previdência privada
        WPREPRI = WPREPRI + WVALOR;

      if (upper(WEHINDRESC) = 'TRUE') then
      begin
        if (WTIPOCODVER in (0, 2)) then -- Provento
          WINDRESC = WINDRESC + WVALOR;
        else
        if (WTIPOCODVER in (1, 3)) then -- Desconto
          WINDRESC = WINDRESC - WVALOR;
      end

      if (substring(WCLASSIF from 1 for 9) = '0.040.0.3') then
        WAUXILIOMORADIA = WAUXILIOMORADIA + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.040.0.0' and
          WIRVER = 0) then
        WDIARIA = WDIARIA + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.910.0.0') then
        WBOLSAMEDICO = WBOLSAMEDICO + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.920.0.0') then
        WJUROSMORA = WJUROSMORA + WVALOR;

      if (coalesce(WCODINCIDIRRF, 0) in (11, 12, 14, 41, 42, 51, 52, 54)) then
        WINCIDESOCIAL = 1;

      if (coalesce(WCODINCIDIRRF, 0) in (13, 43, 53)) then
        WINCIDESOCIALFER = 1;

      WISENTOABONO = 0;
      --                                      Complemento de abono pecuniário                  Compl. 1/3 abono pecuniário
      if ((substring(WCLASSIF from 1 for 7) = '0.210.2') or (substring(WCLASSIF from 1 for 7) = '0.210.3') and
          WIRVER <> 1) then
      begin
        WVALABO = WVALABO + WVALOR;
      end
      else


      -- Rendimentos isentos
      if ((upper(WRENDISENTOVER) = 'TRUE') and
          (WISENTOABONO = 0)) then
      begin
        WRENDIS = WRENDIS + WVALOR;

        WI = 0;

        if (PRVEIODOTOTALIZADOR = 1) then
          select POS
          from POS(:WCLASSIF, :WGCLASS)
          into :WI;
        else
          select POS
          from POS(substring(:WCLASSIF from 1 for 5), :WGCLASS)
          into :WI;

        if (WI = 0) then
        begin
          WDESCVER2 = '';
          select first 1 VERB.BDDESCVER
          from VRH_BASE_TVERBAS VERB
          left outer join VRH_BASE_TRUBRICAESOCIAL_VER RB on (RB.BDCODVER = VERB.BDCODVER)
          where VERB.BDCLAVER = substring(:WCLASSIF from 1 for 15) and
                RB.BDCHAVE = 1619
          into WDESCVER2;

          select first 1 BDCHAVE
          from VRH_BASE_TRUBRICAESOCIAL_VER
          where BDCODVER = :WCODVER
          into :WRUBRICA;
          if (coalesce(WDESCVER2, '') = '') then
          begin
            if (PRVEIODOTOTALIZADOR = 1) then
              select first 1 BDDESCVER
              from VRH_BASE_TVERBAS
              where BDCLAVER = :WCLASSIF
              into WDESCVER2;
            else
              select first 1 BDDESCVER
              from VRH_BASE_TVERBAS
              where BDCLAVER = substring(:WCLASSIF from 1 for 5)
              into WDESCVER2;
          end

          if (PRVEIODOTOTALIZADOR = 1) then
            WGCLASS = WGCLASS || ';' || :WCLASSIF;
          else
            WGCLASS = WGCLASS || ';' || substring(:WCLASSIF from 1 for 5);

          if (WDRENDIS <> '') then
            WDRENDIS = WDRENDIS || ', ';

          if (substring(WCLASSIF from 1 for 9) = '0.040.0.1' and
              WIRVER = 0 and
              WRUBRICA = 1350) then
          begin
            if (WDRENDIS2 <> '') then
              WDRENDIS2 = WDRENDIS2 || ', ';

            if (PRVEIODOTOTALIZADOR = 1) then
              WDRENDIS2 = substring(WDRENDIS2 || 'BOLSA DE ESTUDOS' from 1 for 999);
            else
              WDRENDIS2 = substring(WDRENDIS2 || 'BOLSA DE ESTUDOS' from 1 for 200);

            if (WDRENDIS3 <> '') then
              WDRENDIS3 = WDRENDIS3 || ', ';

            if (PRVEIODOTOTALIZADOR = 1) then
              WDRENDIS3 = substring(WDRENDIS3 || WDESCVER2 from 1 for 999);
            else
              WDRENDIS3 = substring(WDRENDIS3 || WDESCVER2 from 1 for 200);
          end
          else
          begin
            if (PRVEIODOTOTALIZADOR = 1) then
              WDRENDIS = substring(WDRENDIS || WDESCVER2 from 1 for 999);
            else
              WDRENDIS = substring(WDRENDIS || WDESCVER2 from 1 for 200);
          end
        end
      end
    end
  end

  if (WEMPATU <> 0 and
      WCOLATU <> 0 and
      WREFATU <> 0) then
  begin
    if (PRIRRFESOCIAL = true) then
    begin

      select max(BDDATAIRRFESOCIAL), max(BDDATAPROCFT), max(BDHORAPROCFT), sum(BDDEPFT)
      from VRHF_EMP_TFOLHATOMADOR
      where BDREFTOMADOR = :WREFATU and
            BDCODEMP = :WEMPATU and
            BDCODCOL = :WCOLATU
      into :WDATAATU, :WDATAPROCA, :WHORAPROCA, :WDEPATU;
    end
    else
    begin
      select max(BDDATAPGTOFT), max(BDDATAPROCFT), max(BDHORAPROCFT), sum(BDDEPFT)
      from VRHF_EMP_TFOLHATOMADOR
      where BDREFTOMADOR = :WREFATU and
            BDCODEMP = :WEMPATU and
            BDCODCOL = :WCOLATU
      into :WDATAATU, :WDATAPROCA, :WHORAPROCA, :WDEPATU;
    end

    WCODPRES = null;
    WDESCPRES = null;
    WDATARESC = null;
    WDATAPAGRESC = null;
    WTIPOMOV = 0;

    if (PRPREVIARESC = 1) then
    begin
      select X.BDDATARESCISAOPREV, X.BDDATAPAGRESCISAOPREV, X.BDCODPRES, Y.BDDESCPRES, coalesce(Y.BDTIPOMOV, 0)
      from VRH_EMP_TRESCISAO_PREVIA X
      join VRH_BASE_TPREPRESC Y on (Y.BDCODPRES = X.BDCODPRES)
      where X.BDCODEMP = :WEMPATU and
            X.BDCODCOL = :WCOLATU and
            X.BDREFRESCISAOPREV = :WREFATU
      into :WDATARESC, :WDATAPAGRESC, :WCODPRES, :WDESCPRES, :WTIPOMOV;
    end
    else
    begin
      select X.BDDATARESCISAO, X.BDDATAPAGRESCISAO, X.BDCODPRES, Y.BDDESCPRES, coalesce(Y.BDTIPOMOV, 0)
      from VRH_EMP_TRESCISAO X
      join VRH_BASE_TPREPRESC Y on (Y.BDCODPRES = X.BDCODPRES)
      where X.BDCODEMP = :WEMPATU and
            X.BDCODCOL = :WCOLATU and
            X.BDREFRESCISAO = :WREFATU
      into :WDATARESC, :WDATAPAGRESC, :WCODPRES, :WDESCPRES, :WTIPOMOV;
    end

    WDESCCC = null;
    WI = null;
    select first 1 PFN.BDCODTPCC,
                   case
                     when coalesce(CUS.BDNOMETOM, '') <> '' then CUS.BDNOMETOM
                     when coalesce(CC.BDNOMCTA, '') <> '' then CC.BDNOMCTA
                     else CC.BDAPECTA
                   end
    from VRHF_EMP_TPREPFN PFN
    left outer join VRH_BASE_TCUSTOM CUS on (CUS.BDCODCENTRO = PFN.BDCODCENTRO and
          CUS.BDCODTPCC = PFN.BDCODTPCC)
    left outer join CENTROS_TPCC CC on (CC.BDCODCENTRO = PFN.BDCODCENTRO and
          CC.BDCODTPCC = PFN.BDCODTPCC)
    where PFN.BDCODEMP = :WEMPATU and
          PFN.BDCODCOL = :WCOLATU and
          PFN.BDORDEM = :WORDEMATU
    into :WI, :WDESCCC;

    if (WI is null) then
      select first 1 BDNOMEMP
      from TEMPRESAS_REF
      where BDCODEMP = :WEMPATU and
            BDREFEMP <= :WREFATU
      order by BDCODEMP desc, BDREFEMP desc
      into :WDESCCC;

    if (PRIRRFESOCIAL = false) then
    begin
      if ((WTIPOMOV = 0) and
          ((WDATAPAGRESC is not null) or (WDATARESC is not null))) then
      begin
        if (WDATAPAGRESC is not null) then
        begin
          WDATAATU = WDATAPAGRESC;
        end
        else
        begin
          WDATAATU = WDATARESC;
        end
      end
    end

    WREFPAGTO = cast((substring(cast(WDATAATU as varchar(10)) from 1 for 4) || substring(cast(WDATAATU as varchar(10)) from 6 for 2)) as integer);

    if (WREFPAGTO >= PRREFINI and
        WREFPAGTO <= PRREFFIM) then
    begin
      WPREVPRIVCAD = 0;
      select sum(coalesce(LANPREV.BDVALMENSAL, 0))
      from VRH_EMP_TLANCPREVCOMP LANPREV join(select BDCODCADPREV
                                              from VRH_BASE_TCADPREVCOMP
                                              where BDNATPREV <> 2) CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV) /* 184717 Leonardo Schwab 16/11/2023 */
      where LANPREV.BDCODEMP = :WEMPATU and
            LANPREV.BDCODCOL = :WCOLATU and
            LANPREV.BDREFINI <= :WREFATU and
            ((coalesce(LANPREV.BDREFFIN, 0) = 0) or (coalesce(LANPREV.BDREFFIN, 0) >= :WREFATU))
      into :WPREVPRIVCAD;

      select sum(coalesce(BDBIRRF13FT, 0)) BDBIRRF13FT, sum(coalesce(BDIRRF13FT, 0)) BDIRRF13FT
      from VRHF_EMP_TFOLHATOMADOR
      where BDCODEMP = :WEMPATU and
            BDCODCOL = :WCOLATU and
            BDREFTOMADOR = :WREFATU
      into :WBASE13, :WVALOR13;

      BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
      BDCODEMP = WEMPATU;
      BDCODCOL = WCOLATU;
      BDREF = WREFATU;
      BDORDEM = WORDEMATU;
      BDREFPAG = WREFPAGTO;
      BDRENDTRIBUTAVEL = WBASEIR;
      BDINSS = WINSSN;
      BDIR = WIR;

      if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
         begin
            BDBASE13 = WBASE13;
            BDVALOR13 = WVALOR13;
         end

      if (WBASEIR + WINSSN + WIR > 0) then
        BDDEP = WDEPATU;
      else
        BDDEP = 0;

      WCATEGORIAESOCIAL = null;
      select first 1 BDCATEGORIAESOCIAL
      from VRHF_EMP_TCOLCON_FGTSGPS
      where BDCODEMP = :WEMPATU and
            BDCODCOL = :WCOLATU and
            BDREFCOL <= :WREFATU
      order by BDCODEMP desc, BDCODCOL desc, BDREFCOL desc
      into :WCATEGORIAESOCIAL;
      WCATEGORIAESOCIAL = coalesce(WCATEGORIAESOCIAL, 0);

      WPALANCMANUAL = null;
      if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WREF <> WREFATU)) then
        if (PREXPORTACAO <> 2) then
        begin
          select sum(BDVALDIRF)
          from VRH_EMP_TVALBENEF_DIRF
          where BDCODEMP = :WEMPATU and
                BDCODCOL = :WCOLATU and
                BDANODIRF = :WREFPAGTO
          into :WPALANCMANUAL;
        end

      if (WPALANCMANUAL is null) then
        WPALANCMANUAL = 0;

      BDLUCROPJ = WLUCROPJ;
      BDDESPMED = WDESPMED;
      BDAJCUSTOS = WAJCUS;
      if (WCATEGORIAESOCIAL = 903) then
      begin
        BDBOLSAESTUDOS = WBOLSAESTUDOS;
        if (WDRENDIS2 <> '') then
        begin
          if (WDRENDIS <> '') then
            WDRENDIS = WDRENDIS || ' ,';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 999);
          else
            WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 200);
        end
      end
      else
      begin
        BDAJCUSTOS = BDAJCUSTOS + WBOLSAESTUDOS;
        if (WDRENDIS3 <> '') then
        begin
          if (WDRENDIS <> '') then
            WDRENDIS = WDRENDIS || ' ,';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 999);
          else
            WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 200);
        end
      end
      BDPENJUD = WPENJUD;
      BDPENALIM = WPENALIM + WPALANCMANUAL;

      if (coalesce(:WPREVPRIVCAD, 0) > 0) then
      begin
        if (coalesce(:WPREPRI, 0) > 0) then
          BDPREVPRIV = WPREPRI;
        else
        if (coalesce(:WPREVPRIVCAD, 0) > 0) then
          BDPREVPRIV = WPREVPRIVCAD;
      end
      else
        BDPREVPRIV = 0;

      BDINDRESC = WINDRESC;
      BDVALABO = WVALABO;
      BDRENDISENTOS = WRENDIS;
      BDDRENDISENTOS = WDRENDIS;
      BDDATAPGTO = WDATAATU;
      BDDATAPROC = WDATAPROCA;
      BDHORAPROC = WHORAPROCA;
      BDTIPODEDUCAOFOLHA = WTIPODEDUCAO;
      BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPL;
      BDVALORDIFERENCADEDUCOES = WVALORDIFDESCSIMPL;
      BDAUXILIOMORADIA = WAUXILIOMORADIA;
      BDDIARIA = WDIARIA;
      BDBOLSAMEDICO = WBOLSAMEDICO;
      BDJUROSMORA = WJUROSMORA;
      BDINCIDESOCIAL = WINCIDESOCIAL;
      BDINCIDESOCIALFER = WINCIDESOCIALFER;

      if (WDATARESC is not null) then
      begin
        BDTIPO = 100; -- Folha normal rescisão
        BDINFADIC = substring(WORDEMATU || ' - ' || WDESCCC || '; ' || WCODPRES || ' - ' || WDESCPRES from 1 for 300);
      end
      else
      begin
        BDTIPO = 0; -- Folha normal
        BDINFADIC = substring(WORDEMATU || ' - ' || WDESCCC from 1 for 300);
      end

      if (PRATUALIZAINFODESCSIMPLE = true) then
      begin
        WSQLAUXSIMPLI = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, ' || ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, ' || ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) ' || ' values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPAGTO || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';

        execute statement WSQLAUXSIMPLI;
      end
      suspend;

      if ((WVALORIRFE >= 0) and
          (WBASEIRFE > 0)) then
      begin
        BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
        BDCODEMP = WEMPATU;
        BDCODCOL = WCOLATU;
        BDREF = WREFATU;
        BDORDEM = WORDEMATU;
        BDREFPAG = WREFPAGTO;
        BDRENDTRIBUTAVEL = WBASEIRFE;
        BDINSS = 0;
        BDIR = WVALORIRFE;
        BDBASE13 = 0;
        BDVALOR13 = 0;
        BDDEP = WDEPATU;
        BDLUCROPJ = 0;
        BDDESPMED = 0;
        BDAJCUSTOS = 0;
        BDPENJUD = 0;
        BDPENALIM = 0;
        BDPREVPRIV = 0;
        BDINDRESC = 0;
        BDVALABO = 0;
        BDRENDISENTOS = 0;
        BDDRENDISENTOS = '';
        BDDATAPGTO = WDATAATU;
        BDDATAPROC = WDATAPROCA;
        BDHORAPROC = WHORAPROCA;
        BDTIPO = 4;
        BDINFADIC = '';
        BDTIPODEDUCAOFOLHA = WTIPODEDUCAOATU;
        BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
        BDVALORDIFERENCADEDUCOES = WVALORDIFDESCSIMPLATU;
        BDAUXILIOMORADIA = 0;
        BDDIARIA = 0;
        BDBOLSAMEDICO = 0;
        BDJUROSMORA = 0;
        BDINCIDESOCIAL = 0;
        BDINCIDESOCIALFER = 0;
        suspend;
      end
    end
  end
end^

/* Restore proc. body: SP_VRHF_DADOS_IR_FICHA */
create or alter procedure SP_VRHF_DADOS_IR_FICHA (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PREXPORTACAO integer = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBASE13 numeric(18,6),
    BDVALORDIFERENCADEDUCOES numeric(18,2),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDVALOR13 numeric(18,6),
    BDTIPODEDUCAOFOLHA integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WSQL varchar(32700);
declare variable WPALANCMANUAL numeric(18,6);
declare variable WSQLAUXSIMPLI varchar(3000);
declare variable WUSARTMP_COL_SELECT smallint;
begin
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;

  if (upper(PRCODEMP) = 'TMP_EMPRESAS_SELECT') then
    WUSARTMP_EMP_SELECT = 1;
  if (upper(PRCODCOL) = 'TEMP_FILTRO_COLCON_REL') then
    WUSARTMP_COL_SELECT = 1;

  if (PRPUXARFILIAIS = 0) then
  begin
    WSQL = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),' || 'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,' || 'FOL.BDDATAFIR, ''' || ''' BDAUX, fol.BDVALORDESCONTOSIMPLIFICADO, COALESCE(fol.BDAUXILIOMORADIAFIR,0), COALESCE(fol.BDDIARIAFIR,0), COALESCE(fol.BDBOLSAMEDICOFIR,0), COALESCE(fol.BDJUROSMORAFIR,0), fol.BDCODFIR, fol.BDDEMDEV, coalesce(fol.BDCODTIPO, 201) BDCODTIPO ';
    WSQL = WSQL || 'from VRHF_EMP_TFICHAIRRF FOL ';

    if (WUSARTMP_EMP_SELECT = 1) then
      WSQL = WSQL || ' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

    if (WUSARTMP_COL_SELECT = 1) then
      WSQL = WSQL || 'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

    WSQL = WSQL || 'left outer join VRH_EMP_TRESCISAO R on (R.BDCODEMP = FOL.BDCODEMP and R.BDCODCOL = FOL.BDCODCOL) ';


    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where FOL.BDTIPOCALCFIR in (9000,9001) and FOL.BDREFIRFIR >= ' || PRREFINI || ' and FOL.BDREFIRFIR <= ' || PRREFFIM || ' and ' || '((coalesce(R.BDREFPAGRESCISAO, 0) = 0) or (coalesce(R.BDREFPAGRESCISAO, 0) >= FOL.BDREFIRFIR)) and ' || '((not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and ' || 'FN.BDREFIRRFESOCIAL = FOL.BDREFIRFIR) and ' || 'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = FOL.BDCODEMP and FT.BDCODCOL = FOL.BDCODCOL and ' || 'FT.BDREFIRRFESOCIAL = FOL.BDREFIRFIR) and ' || 'not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHAINT FN where FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and ' || 'FN.BDREFIRRFESOCIAL = FOL.BDREFIRFIR) and ' || 'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMINT FT where FT.BDCODEMP = FOL.BDCODEMP and FT.BDCODCOL = FOL.BDCODCOL and ' || 'FT.BDREFIRRFESOCIAL = FOL.BDREFIRFIR' || ')) or ( ';
    else
      WSQL = WSQL || 'where FOL.BDTIPOCALCFIR in (9000,9001) and FOL.BDREFIRFIR >= ' || PRREFINI || ' and FOL.BDREFIRFIR <= ' || PRREFFIM || ' and ' || '((coalesce(R.BDREFPAGRESCISAO, 0) = 0) or (coalesce(R.BDREFPAGRESCISAO, 0) >= FOL.BDREFIRFIR)) and ' || '((not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and ' || 'FN.BDREFFN = FOL.BDREFIRFIR) and ' || 'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = FOL.BDCODEMP and FT.BDCODCOL = FOL.BDCODCOL and ' || 'FT.BDREFTOMADOR = FOL.BDREFIRFIR) and ' || 'not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHAINT FN where FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and ' || 'FN.BDREFFN = FOL.BDREFFIR) and ' || 'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMINT FT where FT.BDCODEMP = FOL.BDCODEMP and FT.BDCODCOL = FOL.BDCODCOL and ' || 'FT.BDREFTOMADOR = FOL.BDREFFIR' || ')) or ( ';

    WSQL = WSQL || ' exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VW_UNION_FN_TOMADOR_VERBAS Y ' || 'where Y.BDCODEMP = FOL.BDCODEMP and Y.BDCODCOL = FOL.BDCODCOL and Y.BDREFFN = FOL.BDREFFIR ' || 'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02))) ';

    if ((PRCODEMP is not null) and
        (PRCODEMP <> '') and
        (WUSARTMP_EMP_SELECT = 0)) then
      WSQL = WSQL || ' and ' || PRCODEMP;

    if ((PRCODCOL is not null and
        PRCODCOL <> '') and
        (WUSARTMP_COL_SELECT = 0)) then
      WSQL = WSQL || ' and ' || PRCODCOL;

    WSQL = WSQL || ' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR ';
  end
  else
  begin
    WSQL = 'select FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),' || 'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,' || 'FO.BDDATAFIR, ''' || ''' BDAUX, COALESCE(fo.BDVALORDESCONTOSIMPLIFICADO,0), COALESCE(fo.BDAUXILIOMORADIAFIR,0), COALESCE(fo.BDDIARIAFIR,0), COALESCE(fo.BDBOLSAMEDICOFIR,0), COALESCE(fo.BDJUROSMORAFIR,0), fo.BDCODFIR, FO.BDDEMDEV, coalesce(FO.BDCODTIPO, 201) BDCODTIPO ';
    wsql = wsql||'from VRHF_EMP_TFICHAIRRF FO join TEMPRESAS EMAT on (EMAT.BDCODEMP = FO.BDCODEMP) ';

    if (WUSARTMP_EMP_SELECT = 1) then
       WSQL = WSQL || 'join tmp_empresas_select TEMP on (TEMP.BDCODEMP = FO.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
      WSQL = WSQL || 'join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FO.BDCODEMP and TEM.BDCODCOL = FO.BDCODCOL) ';

    WSQL = WSQL || 'left outer join VRH_EMP_TRESCISAO R on (R.BDCODEMP = FO.BDCODEMP and R.BDCODCOL = FO.BDCODCOL) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where FO.BDTIPOCALCFIR in (9000,9001) and FO.BDREFIRFIR >= ' || PRREFINI || ' and FO.BDREFIRFIR <= ' || PRREFFIM || ' and ' || '((coalesce(R.BDREFPAGRESCISAO, 0) = 0) or (coalesce(R.BDREFPAGRESCISAO, 0) >= FO.BDREFIRFIR)) and ' || '((not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = FO.BDCODEMP and FN.BDCODCOL = FO.BDCODCOL and FN.BDREFIRRFESOCIAL = FO.BDREFIRFIR) and not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = FO.BDCODEMP and FT.BDCODCOL = FO.BDCODCOL and FT.BDREFIRRFESOCIAL = FO.BDREFIRFIR) and ' || 'not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHAINT FN where FN.BDCODEMP = FO.BDCODEMP and FN.BDCODCOL = FO.BDCODCOL and FN.BDREFIRRFESOCIAL = FO.BDREFIRFIR) and not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMINT FT where FT.BDCODEMP = FO.BDCODEMP and FT.BDCODCOL = FO.BDCODCOL and FT.BDREFIRRFESOCIAL = FO.BDREFIRFIR)) or ( ';
    else
      WSQL = WSQL || 'where FO.BDTIPOCALCFIR in (9000,9001) and FO.BDREFIRFIR >= ' || PRREFINI || ' and FO.BDREFIRFIR <= ' || PRREFFIM || ' and ' || '((coalesce(R.BDREFPAGRESCISAO, 0) = 0) or (coalesce(R.BDREFPAGRESCISAO, 0) >= FO.BDREFIRFIR)) and ' || '((not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = FO.BDCODEMP and FN.BDCODCOL = FO.BDCODCOL and ' || 'FN.BDREFFN = FO.BDREFFIR) and ' || 'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = FO.BDCODEMP and FT.BDCODCOL = FO.BDCODCOL and ' || 'FT.BDREFTOMADOR = FO.BDREFFIR) and ' || 'not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHAINT FN where FN.BDCODEMP = FO.BDCODEMP and FN.BDCODCOL = FO.BDCODCOL and ' || 'FN.BDREFFN = FO.BDREFFIR) and ' || 'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMINT FT where FT.BDCODEMP = FO.BDCODEMP and FT.BDCODCOL = FO.BDCODCOL and FT.BDREFTOMADOR = FO.BDREFFIR)) or ( ';

    WSQL = WSQL || ' exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VW_UNION_FN_TOMADOR_VERBAS Y ' || 'where Y.BDCODEMP = FO.BDCODEMP and Y.BDCODCOL = FO.BDCODCOL and Y.BDREFFN = FO.BDREFFIR ' || 'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02))) ';

    if (WUSARTMP_EMP_SELECT = 0) then
    begin
      if (PRCODEMP is not null and
          PRCODEMP <> '') then
        WSQL = WSQL || ' and ((' || REPLACE(upper(PRCODEMP), 'FOL.', 'FO.') || ')';

      if (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '') then
        WSQL = WSQL || ' or (' || REPLACE(upper(PRCODMATRIZ), 'FOL.', 'EMAT.') || ')';

      if ((PRCODEMP is not null and
          PRCODEMP <> '') or (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '')) then
        WSQL = WSQL || ') ';
    end

    if ((PRCODCOL is not null and
        PRCODCOL <> '') and
        (WUSARTMP_COL_SELECT = 0)) then
      WSQL = WSQL || ' and ' || REPLACE(upper(PRCODCOL), 'FOL.', 'FO.') || ' ';

    WSQL = WSQL || ' order by FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR ';
  end

  BDORDEM = null;
  BDBASE13 = null;
  BDVALORDIFERENCADEDUCOES = null;
  BDVALOR13 = null;
  bdtipodeducaofolha = null;
  bdbolsaestudos = null;
  bdincidesocialfer = 0;
  for execute statement WSQL
          into :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR, :BDDEP, :BDLUCROPJ,
          :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM, :BDPREVPRIV, :BDINDRESC, :BDVALABO, :BDRENDISENTOS,
          :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDVALORDESCONTOSIMPLIFICADO, :BDAUXILIOMORADIA, :BDDIARIA,
          :BDBOLSAMEDICO, :BDJUROSMORA, :BDCODFIR, :BDDEMDEV, :BDCODTIPO
  do
  begin
    WPALANCMANUAL = null;
    if (PREXPORTACAO <> 2) then
      select sum(BDVALDIRF)
      from VRH_EMP_TVALBENEF_DIRF
      where BDCODEMP = :BDCODEMP and
            BDCODCOL = :BDCODCOL and
            BDANODIRF = :BDREFPAG
      into :WPALANCMANUAL;

    if (WPALANCMANUAL is null) then
      WPALANCMANUAL = 0;

    BDREFIRRFESOCIAL = BDREFPAG;
    BDPENALIM = BDPENALIM + WPALANCMANUAL;
    BDDATAPROC = BDDATAPGTO;
    BDHORAPROC = '00:00:00';

    if (PRATUALIZAINFODESCSIMPLE = true) then
    begin
      WSQLAUXSIMPLI = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, ' || ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, ' || ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) ' || ' values (' || current_connection || ', ' || :BDCODEMP || ', ' || :BDCODCOL || ', ' || :BDREFPAG || ', 0, ' || coalesce(:BDPENALIM, 0) || ', ' || coalesce(:BDDEP, 0) || ', ' || coalesce(:BDPREVPRIV, 0) || ', ' || coalesce(:BDINSS, 0) || ', ' || coalesce(:BDVALORDESCONTOSIMPLIFICADO, 0) || ', FALSE, ' || coalesce(:BDRENDTRIBUTAVEL, 0) || ')';

      execute statement WSQLAUXSIMPLI;
    end

    if (coalesce(BDRENDTRIBUTAVEL, 0) <> 0) then
      BDINCIDESOCIAL = 1;

    suspend;
  end
end^

/* Restore proc. body: SP_VRHF_DADOS_IR_SOCIO */
create or alter procedure SP_VRHF_DADOS_IR_SOCIO (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXAFILIAIS integer = null,
    PRCODMATRIZ varchar(15000) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDDATAPGTO date,
    BDLUCROPJ DM_NUMERIC_15_2,
    BDCODTIPO integer)
as
declare variable WUSARTMP_EMP_SELECT integer;
declare variable WUSARTMP_COL_SELECT integer;
declare variable WSQL varchar(32700);
begin
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;

  if (upper(PRCODEMP) = 'TMP_EMPRESAS_SELECT') then
    WUSARTMP_EMP_SELECT = 1;
  if (upper(PRCODCOL) = 'TEMP_FILTRO_COLCON_REL') then
    WUSARTMP_COL_SELECT = 1;

  prcodemp = replace(upper(coalesce(prcodemp, '')), 'FOL.', 'CT.');
  prcodcol = replace(upper(coalesce(prcodcol, '')), 'FOL.', 'COL.');

  prpuxafiliais = coalesce(prpuxafiliais, 0);
  prcodmatriz = replace(upper(coalesce(prcodmatriz, '')), 'FOL.', 'EMAT.');

  if (prpuxafiliais = 0) then
     begin
       wsql = 'select CT.BDCODEMP, COL.BDCODCOL, CT_VAL.BDREFCOTA, CT_VAL.BDREFCOTA, CT_VAL.BDVALORDISTRIBLUCRO '||
              'from EMPRESAS_TSOC CT '||
              'join EMPRESAS_TSOCCOTAS CT_VAL on (CT_VAL.BDCODEMP = CT.BDCODEMP and CT_VAL.BDCODSOC = CT.BDCODSOC) '||
              'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = CT.BDCODEMP and COL.BDCPFCOL = CT.BDCGCCEISOC) ';

       if (WUSARTMP_EMP_SELECT = 1) then
          wsql = wsql||'join TMP_EMPRESAS_SELECT F_EMP on (F_EMP.BDCODEMP = CT.BDCODEMP) ';
       if (WUSARTMP_COL_SELECT = 1) then
         begin
          wsql = wsql||'join (select BDCODEMP, BDCODCOL, row_number() over(partition by BDCPF order by BDCODEMP, BDCODCOL desc) as RN ';
          wsql = wsql||'from TEMP_FILTRO_COLCON_REL) F_COL ON (F_COL.BDCODEMP = CT.BDCODEMP and F_COL.BDCODCOL = COL.BDCODCOL) ';
         end

       wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = CT.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

       wsql = wsql||'where CT_VAL.BDREFCOTA between '||:prrefini||' and '||:prreffim||' and '||
              'COL.BDREFADMCOL <= '||prreffim||' and'||
              '((RESC.BDDATARESCISAO is null) or ((RESC.BDREFRESCISAO >= '||:prrefini||') and (F_COL.RN = 1))) and (COL.BDCONTRCOL = 1) '  ;

       if (prcodemp <> '' and WUSARTMP_EMP_SELECT = 0) then
          wsql = wsql || ' and ' || prcodemp;

       if (prcodcol <> '' and WUSARTMP_COL_SELECT = 0) then
          wsql = wsql || ' and ' || prcodcol;

     end
  else
     begin
       wsql = 'select CT.BDCODEMP, COL.BDCODCOL, CT_VAL.BDREFCOTA, CT_VAL.BDREFCOTA, CT_VAL.BDVALORDISTRIBLUCRO '||
              'from EMPRESAS_TSOC CT '||
              'join EMPRESAS_TSOCCOTAS CT_VAL on (CT_VAL.BDCODEMP = CT.BDCODEMP and CT_VAL.BDCODSOC = CT.BDCODSOC) '||
              'join TEMPRESAS EMAT on (EMAT.BDCODEMP = CT.BDCODEMP) '||
              'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = CT.BDCODEMP and COL.BDCPFCOL = CT.BDCGCCEISOC) ';

       if (WUSARTMP_EMP_SELECT = 1) then
          wsql = wsql||'join TMP_EMPRESAS_SELECT F_EMP on (F_EMP.BDCODEMP = CT.BDCODEMP) ';
       if (WUSARTMP_COL_SELECT = 1) then
         begin
          wsql = wsql||'join (select BDCODEMP, BDCODCOL, row_number() over(partition by BDCPF order by BDCODEMP, BDCODCOL desc) as RN ';
          wsql = wsql||'from TEMP_FILTRO_COLCON_REL) F_COL ON (F_COL.BDCODEMP = CT.BDCODEMP and F_COL.BDCODCOL = COL.BDCODCOL) ';
         end

       wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = CT.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

       wsql = wsql||'where CT_VAL.BDREFCOTA between '||:prrefini||' and '||:prreffim||' and '||
              'COL.BDREFADMCOL <= '||prreffim||' and '||
              '((RESC.BDDATARESCISAO is null) or ((RESC.BDREFRESCISAO >= '||:prrefini||') and (F_COL.RN = 1)))';


       if (WUSARTMP_EMP_SELECT = 0) then
       begin
         if (prcodemp <> '') then
           wsql = wsql || ' and ((' || prcodemp || ') ';
   
         if (prcodmatriz <> '' and prcodemp <> '') then
           wsql = wsql || ' or (' || prcodmatriz || ')) ';
   
         if ((prcodemp <> '') and (prcodmatriz = '')) then
           wsql = wsql || ') ';
       end
   
       if (prcodcol <> '' and WUSARTMP_COL_SELECT = 0) then
          wsql = wsql || ' and ' || prcodcol || ' ';
     end

  for execute statement wsql
  into :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDLUCROPJ
  do
    begin
      BDDATAPGTO = cast((substring(BDREF from 1 for 4)||'-'||substring(BDREF from 5 for 2)||'-01') as DATE);
      BDCODTIPO = 201;
      suspend;
    end
end^

/* Restore proc. body: SP_VRHF_DADOS_IR_FN */
create or alter procedure SP_VRHF_DADOS_IR_FN (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PREXPORTACAO integer = 0,
    PRPORCC smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0,
    PRFICHAFINANCEIRA smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBASE13 numeric(18,6),
    BDVALORDIFERENCADEDUCOES numeric(18,2),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDVALOR13 numeric(18,6),
    BDTIPODEDUCAOFOLHA integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WEHINDRESC varchar(5);
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WDATAPGTO date;
declare variable WCLASSIF varchar(20);
declare variable WDESCVER varchar(40);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSSN numeric(18,6);
declare variable WIR numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(999);
declare variable WDATARESC date;
declare variable WDATAPAGRESC date;
declare variable WCODPRES integer;
declare variable WDESCPRES varchar(110);
declare variable WREFINI integer;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WTIPOMOV integer;
declare variable WGCLASS varchar(13000);
declare variable WDESCVER2 varchar(70);
declare variable WI integer;
declare variable WPREVPRIVCAD numeric(18,6);
declare variable WSQLAUX varchar(1000);
declare variable WISENTOABONO integer;
declare variable WPALANCMANUAL numeric(18,6);
declare variable WBASE13 numeric(18,6);
declare variable WVALOR13 numeric(18,6);
declare variable WBASEIRFE numeric(18,6);
declare variable WVALORIRFE numeric(18,6);
declare variable WRUBRICA integer;
declare variable WCATEGORIAESOCIAL integer;
declare variable WBOLSAESTUDOS numeric(18,6);
declare variable WCODMATRIZ varchar(15000);
declare variable WTIPODEDUCAO integer;
declare variable WVALORDIFDESCSIMPL numeric(18,2);
declare variable WVALORDESCSIMPL numeric(18,2);
declare variable WEMPRESAS varchar(20000);
declare variable WCOLABORADORES varchar(30000);
declare variable WDRENDIS2 varchar(999);
declare variable WDRENDIS3 varchar(999);
declare variable WSQLAUXSIMPLI varchar(3000);
declare variable WTIPODEDUCAOATU integer;
declare variable WVALORDIFDESCSIMPLATU numeric(18,2);
declare variable WVALORDESCSIMPLATU numeric(18,2);
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WAUXILIOMORADIA numeric(18,6);
declare variable WDIARIA numeric(18,6);
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WJUROSMORA numeric(18,6);
declare variable WCODINCIDIRRF integer;
declare variable WINCIDESOCIAL integer;
declare variable WINCIDESOCIALFER integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WPERSONALIZACAO integer;
declare variable WTABRUBR varchar(8);
declare variable WGRAVARUBRICA integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
BEGIN
  PRIRRFESOCIAL = coalesce(PRIRRFESOCIAL, false);
  PRATUALIZAINFODESCSIMPLE = coalesce(PRATUALIZAINFODESCSIMPLE, false);

  /* FOLHA NORMAL */
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;
  IF (UPPER(prcodcol) = 'TEMP_FILTRO_COLCON_REL') THEN
     WUSARTMP_COL_SELECT = 1;

  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) = 1) THEN
     wrefini = CAST((CAST((CAST(SUBSTRING(prrefini FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
  ELSE
  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) <= 10) THEN
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1))) AS INTEGER);
  ELSE
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2))) AS INTEGER);

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODVER,FOL.BDVALVFN,FOLN.BDDATAIRRFESOCIAL AS BDDATAPGTOFN,FOLN.BDDEPFN,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
       ELSE
       wsql = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODVER,FOL.BDVALVFN,FOLN.BDDATAPGTOFN,FOLN.BDDEPFN,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN                                                                                                                          
             wSQL = wSQL ||'from (SELECT VFN.bdcodemp, VFN.BDCODCOL, VFN.BDREFFN, VFN.bdcodver,  VFN.BDVALVFN FROM vrhf_emp_tverbafn VFN '||
                                  'INNER JOIN tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = VFN.BDCODEMP ) FOL ';
          END
       ELSE
          wSQL = wSQL||'from vrhf_emp_tverbafn FOL ';

       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

       wsql = wsql||'inner join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'inner join vrhf_emp_tfolhanormal FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFFN = FOL.BDREFFN) ';
       wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOLN.BDCODEMP) and (RESC.BDCODCOL = FOLN.BDCODCOL) and (RESC.BDREFRESCISAO >= '||prreffim||') ';
       wsql = wsql||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL  '||
                    '                                     AND X.BDREFCOL <= FOL.BDREFFN ORDER BY X.BDREFCOL DESC) '||
                    '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL)) ';

--       IF (WUSARTMP_COL_SELECT = 1) THEN
--         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'where FOLN.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim||' ';
       ELSE
         BEGIN
       wsql = wsql||'where ((FOL.BDREFFN >= '||wrefini||' and FOL.BDREFFN <= '||prreffim||') or ';
       wsql = wsql||'       (FOL.BDREFFN <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||wrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) and ';
           wsql = wsql||'      ((select BDDATA from sp_parse_date(FOLN.BDDATAPGTOFN, ''YYYYMM'')) >= '||prrefini||' and ((select BDDATA from sp_parse_date(FOLN.BDDATAPGTOFN, ''YYYYMM'')) <= '||prreffim||'))';
         END

       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;
            
       IF ((prcodcol IS NOT NULL AND prcodcol <> '') AND (WUSARTMP_COL_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodcol;

       if (prveiodototalizador = 1) then
          wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODVER ';
       else
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN ';
     END
  ELSE
     BEGIN

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDCODVER,FO.BDVALVFN,FOLN.BDDATAIRRFESOCIAL AS BDDATAPGTOFN,FOLN.BDDEPFN,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
       ELSE
       wsql = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDCODVER,FO.BDVALVFN,FOLN.BDDATAPGTOFN,FOLN.BDDEPFN,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          BEGIN
             wSQL = wSQL ||'from TMP_EMPRESAS_SELECT FOL ';

             --wsql = wsql||'INNER join (select VFN.BDCODEMP, VFN.BDCODCOL, VFN.BDREFFN, VFN.BDCODVER, VFN.BDVALVFN FROM vrhf_emp_tverbafn VFN) FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
             wsql = wsql||'inner join VRHF_EMP_TFOLHANORMAL FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP)';
          END
       ELSE
          BEGIN
          wSQL = wSQL ||' from TEMPRESAS FOL ';
             --wsql = wsql||'join vrhf_emp_tverbafn FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
             wsql = wsql||'inner join VRHF_EMP_TFOLHANORMAL FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP) ';
          END
       
       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP and TEMP.BDCODCOL = FOLN.BDCODCOL) ';

       wsql = wsql||'inner join VRHF_EMP_TVERBAFN FO on (FO.BDCODEMP = FOLN.BDCODEMP) and (FO.BDCODCOL = FOLN.BDCODCOL) and (FO.BDREFFN = FOLN.BDREFFN) ';
       wsql = wsql||'inner join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOLN.BDCODEMP) and (RESC.BDCODCOL = FOLN.BDCODCOL) and (RESC.BDREFRESCISAO >= '||prreffim||') ';
       wsql = wsql||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                    '                                     AND X.BDREFCOL <= '||prreffim||' ORDER BY X.BDREFCOL DESC) '||
                    '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

--       IF (WUSARTMP_COL_SELECT = 1) THEN
--         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = wsql||'where FOLN.BDREFIRRFESOCIAL between '||prrefini||' and '||prreffim||' ';
       ELSE
         BEGIN
           wsql = wsql||'where ((FO.BDREFFN >= '||wrefini||' and FO.BDREFFN <= '||prreffim||') or ';
           wsql = wsql||'       (FO.BDREFFN <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= '||wrefini||' and RESC.BDREFPAGRESCISAO <= '||prreffim||')) ';
         END

       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
             IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
                wsql = wsql||' and (('||prcodemp||')';
         
             IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
                wsql = wsql||' or ('||prcodmatriz||')';
         
             IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
                wsql = wsql||') ';
          END

       IF ((prcodcol IS NOT NULL AND prcodcol <> '') AND (WUSARTMP_COL_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodcol||' ';

       if (prveiodototalizador = 1) then
          wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDCODVER ';
       else
       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFN ';
     END

  wempatu   = 0;
  wcolatu   = 0;
  wrefatu   = 0;
  wbaseir    = 0;
  winssn     = 0;
  wir        = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wbolsaestudos = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc   = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdrendis2  = '';
  wdrendis3  = '';
  wdataproca = NULL;
  whoraproca = NULL;
  wgclass    = '';
  wehindresc = '';
  wbase13    = 0;
  wvalor13   = 0;
  wbaseirfe  = 0;
  wvalorirfe = 0;
  wvalordescsimpl = 0;
  wvalordifdescsimpl = 0;
  wtipodeducao = 0;
  wtipodeducaoatu = -1;
  wvalordescsimplatu = 0;
  wvalordifdescsimplatu = 0;
  wREFIRRFESOCIALATU = -1;
  WAUXILIOMORADIA = 0;
  WDIARIA = 0;
  WBOLSAMEDICO = 0;
  WJUROSMORA = 0;
  WINCIDESOCIAL = 0;
  WINCIDESOCIALFER = 0;
  BDCODFIR = 0;
  WCPFCOL = NULL;
  WCODEMPORD = NULL;

  FOR EXECUTE STATEMENT wsql INTO :wREFIRRFESOCIAL,:wcodemp,:wcodcol,:wref,:wcodver,:wvalor,:wdatapgto,:wdep,:wclassif,:wdescver,:wdataproc,:whoraproc,:wtipodeducao,:wvalordescsimpl,:wvalordifdescsimpl,:wcodcla,:wtributacaoexterior  DO
  BEGIN
    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end

    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wrefatu = 0) THEN
       wrefatu = wref;

    if (wvalordescsimplatu = 0) then
       wvalordescsimplatu = wvalordescsimpl;

    if (wvalordifdescsimplatu = 0) then
       wvalordifdescsimplatu = wvalordifdescsimpl;

    if (wtipodeducaoatu = -1) then
       wtipodeducaoatu = wtipodeducao;

    if (wREFIRRFESOCIALATU = -1) then
       wREFIRRFESOCIALATU = wREFIRRFESOCIAL;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu)) THEN
       BEGIN
         wcodpres       = NULL;
         wdescpres      = NULL;
         wdataresc      = NULL;
         wdatapagresc   = NULL;
         wtipomov       = 0;

         IF (prpreviaresc = 1) THEN
            BEGIN
              SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END
         ELSE
            BEGIN
              SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END

         IF (PRIRRFESOCIAL = FALSE) THEN
            BEGIN
         IF ((wtipomov < 1) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
            BEGIN
              IF (wdatapagresc IS NOT NULL) THEN
                 BEGIN
                   wdataatu  = wdatapagresc;
                 END
              ELSE
                 BEGIN
                   wdataatu  = wdataresc;
                 END
            END
            END

         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              wprevprivcad = 0;
                   wsqlaux = 'select SUM(COALESCE(LANPREV.BDVALMENSAL,0)) from VRH_EMP_TLANCPREVCOMP LANPREV '||
                             ' join VRH_BASE_TCADPREVCOMP CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV and CADPREV.BDNATPREV <> 2) '||   /* 184717 Leonardo Schwab 16/11/2023 */
                             ' where LANPREV.BDCODEMP = '||wempatu||' and LANPREV.BDCODCOL = '||wcolatu||' and LANPREV.BDREFINI <= '||wrefatu||
                             ' and ((COALESCE(LANPREV.BDREFFIN,0) >= '||wrefatu||') or (COALESCE(LANPREV.BDREFFIN,0) = 0)) ';
                   EXECUTE STATEMENT wsqlaux INTO :wprevprivcad;

              wsqlaux = 'select SUM(COALESCE(BDBIRRF13FN,0)) BDBIRRF13FN, SUM(COALESCE(BDIRRF13FN,0)) BDIRRF13FN from VRHF_EMP_TFOLHANORMAL where BDCODEMP = '||wempatu||' and BDCODCOL = '||wcolatu||' and BDREFFN = '||wrefatu;
                   EXECUTE STATEMENT wsqlaux INTO :wbase13, :wvalor13;

              bdrefirrfesocial = wREFIRRFESOCIALATU;
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir;
              BDINSS           = winssn;
              BDIR             = wir;
              BDBASE13         = wbase13;
              BDVALOR13        = wvalor13;

              if (PRVEIODOTOTALIZADOR = 0) then
                 begin
                   IF (wbaseir + winssn + wir > 0)  THEN
                      BDDEP = wdepatu;
                   ELSE
                      BDDEP = 0;
                 end
              else
                 BDDEP = wdepatu;

              wpalancmanual = null;
              if (prexportacao<>2) then
                select SUM(BDVALDIRF) from VRH_EMP_TVALBENEF_DIRF where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDANODIRF = :wrefpagto into :wpalancmanual;

              wcategoriaesocial = null;
              select first 1 BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :wrefatu order by BDREFCOL DESC into :wcategoriaesocial;
              wcategoriaesocial = coalesce(wcategoriaesocial, 0);

              if (wpalancmanual is null) then
                 wpalancmanual = 0;

              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              if (wcategoriaesocial = 903) then
                 begin
              BDBOLSAESTUDOS   = wbolsaestudos;
                   if (wdrendis2 <> '') then
                      begin
                        if (wdrendis <> '') then
                           wdrendis = wdrendis||' ,';

                        if (prveiodototalizador = 1) then
                           wdrendis = substring(wdrendis||wdrendis2 from 1 for 999);
                        else
                        wdrendis = substring(wdrendis||wdrendis2 from 1 for 200);
                      end
                 end
              else
                 begin
                   BDAJCUSTOS = BDAJCUSTOS + wbolsaestudos;
                   if (wdrendis3 <> '') then
                      begin
                        if (wdrendis <> '') then
                           wdrendis = wdrendis||' ,';

                        if (prveiodototalizador = 1) then
                           wdrendis = substring(wdrendis||wdrendis3 from 1 for 999);
                        else
                        wdrendis = substring(wdrendis||wdrendis3 from 1 for 200);
                      end
                 end

              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim + wpalancmanual;

              if (COALESCE(:wprevprivcad, 0) > 0) then
                 begin
                   if (COALESCE(:wprepri, 0) > 0) then
                      BDPREVPRIV = wprepri;
              else  if (COALESCE(:wprevprivcad, 0) > 0) then
                      BDPREVPRIV = wprevprivcad;
                 end
              else
                 BDPREVPRIV = 0;

              BDINDRESC        = windresc;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;
              BDTIPODEDUCAOFOLHA = wtipodeducao;
              BDVALORDESCONTOSIMPLIFICADO = wvalordescsimpl;
              BDVALORDIFERENCADEDUCOES = wvalordifdescsimpl;
              BDAUXILIOMORADIA = WAUXILIOMORADIA;
              BDDIARIA = WDIARIA;
              BDBOLSAMEDICO = WBOLSAMEDICO;
              BDJUROSMORA = WJUROSMORA;
              BDINCIDESOCIAL = WINCIDESOCIAL;
              BDINCIDESOCIALFER = WINCIDESOCIALFER;

              if (BDBOLSAESTUDOS is null) then
                  BDBOLSAESTUDOS   = wbolsaestudos;

              IF (wdataresc IS NOT NULL) THEN
                 BEGIN
                   BDTIPO    = 100;    -- Folha normal rescisão
                   BDINFADIC = SUBSTRING(wcodpres||' - '||wdescpres FROM 1 FOR 300);
                 END
              ELSE
                 BEGIN
                   BDTIPO    = 0;    -- Folha normal
                   BDINFADIC = '';
                 END

              if (pratualizainfodescsimple = TRUE) then
                begin
                  wsqlauxsimpli = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, '||
                                  ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, '||
                                  ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) '||
                                  ' values ('||current_connection||', '||wempatu||', '||wcolatu||', '||wrefpagto||', 0, '||coalesce(bdpenalim, 0)||', '||coalesce(bddep, 0)||', '||coalesce(bdprevpriv, 0)||', '||coalesce(bdinss, 0)||', '||coalesce(wvalordescsimplatu, 0)||', FALSE, '||coalesce(bdrendtributavel, 0)||')';
              
                  execute statement wsqlauxsimpli;
                end
              SUSPEND;

--              IF (((wvalorirfe >= 0) and (wbaseirfe > 0)) or (PRVEIODOTOTALIZADOR > 0)) THEN
              IF ((wvalorirfe >= 0) and (wbaseirfe > 0)) THEN
                BEGIN
                  bdrefirrfesocial = wREFIRRFESOCIALATU;
                  BDCODEMP         = wempatu;
                  BDCODCOL         = wcolatu;
                  BDREF            = wrefatu;
                  BDORDEM          = null;
                  BDREFPAG         = wrefpagto;
                  BDRENDTRIBUTAVEL = wbaseirfe;
                  BDINSS           = 0;
                  BDIR             = wvalorirfe;
                  BDBASE13         = 0;
                  BDVALOR13        = 0;
                  BDDEP            = wdepatu;
                  BDLUCROPJ        = 0;
                  BDDESPMED        = 0;
                  BDAJCUSTOS       = 0;
                  BDPENJUD         = 0;
                  BDPENALIM        = 0;
                  BDPREVPRIV       = 0;
                  BDINDRESC        = 0;
                  BDVALABO         = 0;
                  BDRENDISENTOS    = 0;
                  BDDRENDISENTOS   = '';
                  BDDATAPGTO       = wdataatu;
                  BDDATAPROC       = wdataproca;
                  BDHORAPROC       = whoraproca;
                  BDTIPO           = 4;
                  BDINFADIC        = '';
                  BDTIPODEDUCAOFOLHA = wtipodeducao;
                  BDVALORDESCONTOSIMPLIFICADO = wvalordescsimpl;
                  BDVALORDIFERENCADEDUCOES = wvalordifdescsimpl;
                  BDAUXILIOMORADIA = 0;
                  BDDIARIA = 0;
                  BDBOLSAMEDICO = 0;
                  BDJUROSMORA = 0;
                  BDINCIDESOCIAL = 0;
                  BDINCIDESOCIALFER = 0;
                  SUSPEND;
            END
            END

         wempatu   = wcodemp;
         wcolatu   = wcodcol;
         wrefatu   = wref;
         wrefirrfesocialatu = wrefirrfesocial;

         wbaseir    = 0;
         winssn     = 0;
         wir        = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wbolsaestudos = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc   = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
         wdrendis2  = '';
         wdrendis3  = '';
         wgclass    = '';
         wbase13    = 0;
         wvalor13   = 0;
         wbaseirfe  = 0;
         wvalorirfe = 0;
         wvalordescsimplatu = wvalordescsimpl;
         wvalordifdescsimplatu = wvalordifdescsimpl;
         wtipodeducaoatu = wtipodeducao;
         WAUXILIOMORADIA = 0;
         WDIARIA = 0;
         WBOLSAMEDICO = 0;
         WJUROSMORA = 0;
         WINCIDESOCIAL = 0;
         WINCIDESOCIALFER = 0;
       END

    -- soma as bases
    wcodincidirrf = 0;
    SELECT first 1 BDTIPOCODVER, COALESCE(BDIRVER,0), BDRENDISENTOIRVER, bdindresc, BDCODINCIDIRRF
    FROM vrh_base_tverbas_ref
    WHERE BDCODVER = :wcodver and BDREFVER <= :wrefatu
    order by BDCODVER desc, BDREFVER DESC
    INTO :wtipocodver,:wirver,:wrendisentover, :wehindresc, :wcodincidirrf;
    begin
--    if (wtipocodver <= 1) then

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end

--    if (wtipocodver <= 1) then
         --  IR Folha normal                                     IR VeA
       if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = FALSE) then
       begin
          IF ((wirver = 1) or (SUBSTRING(wclassif FROM 1 FOR 9) = '0.900.2.0')) THEN
            BEGIN
              IF (wtipocodver = 0) THEN   -- provento
                 wbaseir = wbaseir + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN   -- desconto
                 BEGIN
                   --                                      INSS                                              Obrigações IR
                   IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                      wbaseir = wbaseir - wvalor;
                 END
            END

          IF (wirver = 2) THEN -- IR Férias
            BEGIN
              IF (wtipocodver = 0) THEN   -- provento
                 wbaseirfe = wbaseirfe + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN   -- desconto
                 BEGIN
                   --                                      INSS                                              Obrigações IR
                   IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030' AND SUBSTRING(wclassif FROM 1 FOR 7) <> '3.001.8') THEN
                      wbaseirfe = wbaseirfe - wvalor;
                 END
            END

         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.0') and (wdescver <> 'IR Férias (COVID-19)')) THEN -- IR folha normal
            wir = wir + wvalor;

         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.0') and (wdescver = 'IR Férias (COVID-19)')) THEN -- IR férias
            wvalorirfe = wvalorirfe + wvalor;
       end

         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.0') or (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.3'))  THEN -- INSS folha normal / INSS 13º folha normal VeA
            winssn = winssn + wvalor;


         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN -- Lucro pessoa jurídica
            wlucropj = wlucropj + wvalor;

         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.0') OR (SUBSTRING(wclassif FROM 1 FOR 9) = '0.420.0.2') or (SUBSTRING(wclassif FROM 1 FOR 9) = '3.010.0.0')) THEN -- Despesas médicas / Complemento de despesas médicas
            wdespmed = wdespmed + wvalor;

--         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.0' AND wirver = 0) THEN -- Diárias/Ajuda de custos
--            wajcus = wajcus + wvalor;

         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1' AND wirver = 0) THEN -- Ajuda de custos
            begin
              wrubrica = null;
              select first 1 BDCHAVE from VRH_BASE_TRUBRICAESOCIAL_VER where BDCODVER = :wcodver into :wrubrica;

              IF (wrubrica = 1350) THEN -- Bolsa estudos
                 wbolsaestudos = wbolsaestudos + wvalor;
              else
            wajcus = wajcus + wvalor;
            end

         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.0') THEN -- Pensões judiciais
            wpenjud = wpenjud + wvalor;

         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.1') THEN -- Pensões alimentícias
            wpenalim = wpenalim + wvalor;

         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.2') THEN -- Previdência privada
            wprepri = wprepri + wvalor;
     
         IF (UPPER(wehindresc) = 'TRUE') THEN
            BEGIN
              IF (wtipocodver in (0, 2)) THEN   -- Provento
                 windresc = windresc + wvalor;
              ELSE
              IF (wtipocodver in (1, 3)) THEN   -- Desconto
                 windresc = windresc - wvalor;
            END
     
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.3') THEN
            WAUXILIOMORADIA = WAUXILIOMORADIA + wvalor;

         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.0' AND wirver = 0) THEN
            WDIARIA = WDIARIA + WVALOR;

         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.910.0.0') THEN
            WBOLSAMEDICO = WBOLSAMEDICO + wvalor;

         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.920.0.0') THEN
            WJUROSMORA = WJUROSMORA + wvalor;

         if (COALESCE(WCODINCIDIRRF, 0) in (11,12,14,41,42,51,52,54)) then
            WINCIDESOCIAL = 1;

         if (COALESCE(WCODINCIDIRRF, 0) in (13,43,53)) then
            WINCIDESOCIALFER = 1;

         wisentoabono = 0;
         --                                      Complemento de abono pecuniário                  Compl. 1/3 abono pecuniário
         IF ((SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.2') OR (SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.3') and (WIRVER <> 1)) THEN
            BEGIN
                  wvalabo = wvalabo + wvalor;
            END
         ELSE
         -- Rendimentos isentos
         IF ((UPPER(wrendisentover) = 'TRUE') AND (wisentoabono = 0)) THEN
            BEGIN
              wrendis = wrendis + wvalor;
     
              wi = 0;

              if (prveiodototalizador = 1) then
                 SELECT POS FROM pos(:wclassif, :wgclass) INTO :wi;
              else
              SELECT POS FROM pos(SUBSTRING(:wclassif FROM 1 FOR 5), :wgclass) INTO :wi;
     
              IF (wi = 0) THEN
                 BEGIN
                   wdescver2 = '';
                   SELECT FIRST 1 VERB.BDDESCVER FROM VRH_BASE_TVERBAS VERB
                   LEFT OUTER JOIN VRH_BASE_TRUBRICAESOCIAL_VER RB on (RB.BDCODVER = VERB.BDCODVER)
                   WHERE VERB.BDCLAVER = SUBSTRING(:wclassif FROM 1 FOR 15) AND RB.BDCHAVE = 1619 INTO wdescver2;

                   select first 1 BDCHAVE from VRH_BASE_TRUBRICAESOCIAL_VER where BDCODVER = :wcodver into :wrubrica;

                   if (coalesce(wdescver2, '') = '') then
                      begin
                       if (prveiodototalizador = 1) then
                          SELECT FIRST 1 BDDESCVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = :wclassif INTO wdescver2;
                       else
                       SELECT FIRST 1 BDDESCVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = SUBSTRING(:wclassif FROM 1 FOR 5) INTO wdescver2;
                      end

                   if (prveiodototalizador = 1) then
                      wgclass = wgclass||';'||:wclassif;
                   else
                   wgclass = wgclass||';'||SUBSTRING(:wclassif FROM 1 FOR 5);
     
                   IF (wdrendis <> '') THEN
                      wdrendis = wdrendis ||', ';
     
                   IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1' AND wirver = 0 and
                       wrubrica = 1350) THEN
                       begin
                         IF (wdrendis2 <> '') THEN
                            wdrendis2 = wdrendis2 ||', ';

                         if (prveiodototalizador = 1) then
                            wdrendis2 = SUBSTRING(wdrendis2||'BOLSA DE ESTUDOS' FROM 1 FOR 999);
                         else
                         wdrendis2 = SUBSTRING(wdrendis2||'BOLSA DE ESTUDOS' FROM 1 FOR 200);

                         IF (wdrendis3 <> '') THEN
                            wdrendis3 = wdrendis3 ||', ';

                         if (prveiodototalizador = 1) then
                            wdrendis3 = SUBSTRING(wdrendis3||wdescver2 FROM 1 FOR 999);
                         else
                         wdrendis3 = SUBSTRING(wdrendis3||wdescver2 FROM 1 FOR 200);
                       end
                   else
                       begin
                         if (prveiodototalizador = 1) then
                            wdrendis = SUBSTRING(wdrendis||wdescver2 FROM 1 FOR 999);
                         else
                   wdrendis = SUBSTRING(wdrendis||wdescver2 FROM 1 FOR 200);
                       end
                 END
            END
       end

    wdepatu = wdep;
    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0) THEN
     BEGIN
       wcodpres       = NULL;
       wdescpres      = NULL;
       wdataresc      = NULL;
       wdatapagresc   = NULL;
       wtipomov       = 0;

       IF (prpreviaresc = 1) THEN
          BEGIN
            SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END
       ELSE
          BEGIN
            SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END

       IF (PRIRRFESOCIAL = FALSE) THEN
            BEGIN
       IF ((wtipomov < 1) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
          BEGIN
            IF (wdatapagresc IS NOT NULL) THEN
               BEGIN
                 wdataatu  = wdatapagresc;
               END
            ELSE
               BEGIN
                 wdataatu  = wdataresc;
               END
          END
            END

       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            wprevprivcad = 0;

            select SUM(COALESCE(LANPREV.BDVALMENSAL,0)) from VRH_EMP_TLANCPREVCOMP LANPREV
            join VRH_BASE_TCADPREVCOMP CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV and CADPREV.BDNATPREV <> 2)  /* 184717 Leonardo Schwab 16/11/2023 */
            where LANPREV.BDCODEMP = :wempatu and LANPREV.BDCODCOL = :wcolatu and LANPREV.BDREFINI <= :wrefatu
            and ((COALESCE(LANPREV.BDREFFIN, 0) = 0) or (COALESCE(LANPREV.BDREFFIN, 0) >= :wrefatu))
            INTO :wprevprivcad;

            if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = FALSE) then
               begin
                  select SUM(COALESCE(BDBIRRF13FN,0)) BDBIRRF13FN, SUM(COALESCE(BDIRRF13FN,0)) BDIRRF13FN from VRHF_EMP_TFOLHANORMAL where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFFN = :wrefatu
                  INTO :wbase13, :wvalor13;
               end

            bdrefirrfesocial = wREFIRRFESOCIALATU;
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir;
            BDINSS           = winssn;
            BDIR             = wir;
            BDBASE13         = COALESCE(wbase13, 0);
            BDVALOR13        = COALESCE(wvalor13, 0);

              if (PRVEIODOTOTALIZADOR = 0) then
                 begin
                   IF (wbaseir + winssn + wir > 0)  THEN
                      BDDEP = wdepatu;
                   ELSE
                      BDDEP = 0;
                 end
              else
                 BDDEP = wdepatu;
            wpalancmanual = null;
            if (prexportacao<>2) then
               select SUM(BDVALDIRF) from VRH_EMP_TVALBENEF_DIRF where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDANODIRF = :wrefpagto into :wpalancmanual;

            wcategoriaesocial = null;
            select first 1 BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :wrefatu order by BDREFCOL DESC into :wcategoriaesocial;
            wcategoriaesocial = coalesce(wcategoriaesocial, 0);

            if (wpalancmanual is null) then
               wpalancmanual = 0;

            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;

            if (wcategoriaesocial = 903) then
               begin
            BDBOLSAESTUDOS   = wbolsaestudos;
                 if (wdrendis2 <> '') then
                    begin
                      if (wdrendis <> '') then
                         wdrendis = wdrendis||' ,';

                      if (prveiodototalizador = 1) then
                         wdrendis = substring(wdrendis||wdrendis2 from 1 for 999);
                      else
                      wdrendis = substring(wdrendis||wdrendis2 from 1 for 200);
                    end
               end
            else
               begin
                 BDAJCUSTOS = BDAJCUSTOS + wbolsaestudos;
                   if (wdrendis3 <> '') then
                    begin
                      if (wdrendis <> '') then
                         wdrendis = wdrendis||' ,';

                      if (prveiodototalizador = 1) then
                         wdrendis = substring(wdrendis||wdrendis3 from 1 for 999);
                      else
                      wdrendis = substring(wdrendis||wdrendis3 from 1 for 200);
                    end
               end

            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim + wpalancmanual;

            if (COALESCE(:wprevprivcad, 0) > 0) then
               begin
                 if (COALESCE(:wprepri, 0) > 0) then
                    BDPREVPRIV = wprepri;
              else  if (COALESCE(:wprevprivcad, 0) > 0) then
                    BDPREVPRIV = wprevprivcad;
               end
            else
               BDPREVPRIV = 0;

            BDINDRESC        = windresc;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;
            BDTIPODEDUCAOFOLHA = wtipodeducaoatu;
            BDVALORDESCONTOSIMPLIFICADO = wvalordescsimplatu;
            BDVALORDIFERENCADEDUCOES = wvalordifdescsimplatu;
            BDAUXILIOMORADIA = WAUXILIOMORADIA;
            BDDIARIA = WDIARIA;
            BDBOLSAMEDICO = WBOLSAMEDICO;
            BDJUROSMORA = WJUROSMORA;
            BDINCIDESOCIAL = WINCIDESOCIAL;
            BDINCIDESOCIALFER = WINCIDESOCIALFER;
            BDCODTIPO = 272;

            IF (wdataresc IS NOT NULL) THEN
               BEGIN
                 BDTIPO    = 100;    -- Folha normal rescisão
                 BDINFADIC = SUBSTRING(wcodpres||' - '||wdescpres FROM 1 FOR 300);
               END
            ELSE
               BEGIN
                 BDTIPO    = 0;    -- Folha normal
                 BDINFADIC = '';
               END

            if (pratualizainfodescsimple = TRUE) then
              begin
                wsqlauxsimpli = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, '||
                                ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, '||
                                ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) '||
                                ' values ('||current_connection||', '||wempatu||', '||wcolatu||', '||wrefpagto||', 0, '||coalesce(bdpenalim, 0)||', '||coalesce(bddep, 0)||', '||coalesce(bdprevpriv, 0)||', '||coalesce(bdinss, 0)||', '||coalesce(wvalordescsimplatu, 0)||', FALSE, '||coalesce(bdrendtributavel, 0)||')';
              
                execute statement wsqlauxsimpli;
              end
            SUSPEND;

--            IF (((wvalorirfe >= 0) and (wbaseirfe > 0)) or (PRVEIODOTOTALIZADOR > 0)) THEN
            IF ((wvalorirfe >= 0) and (wbaseirfe > 0)) THEN
                BEGIN
                  bdrefirrfesocial = wREFIRRFESOCIALATU;
                  BDCODEMP         = wempatu;
                  BDCODCOL         = wcolatu;
                  BDREF            = wrefatu;
                  BDORDEM          = null;
                  BDREFPAG         = wrefpagto;
                  BDRENDTRIBUTAVEL = wbaseirfe;
                  BDINSS           = 0;
                  BDIR             = wvalorirfe;
                  BDBASE13         = 0;
                  BDVALOR13        = 0;
                  BDDEP            = wdepatu;
                  BDLUCROPJ        = 0;
                  BDDESPMED        = 0;
                  BDAJCUSTOS       = 0;
                  BDPENJUD         = 0;
                  BDPENALIM        = 0;
                  BDPREVPRIV       = 0;
                  BDINDRESC        = 0;
                  BDVALABO         = 0;
                  BDRENDISENTOS    = 0;
                  BDDRENDISENTOS   = '';
                  BDDATAPGTO       = wdataatu;
                  BDDATAPROC       = wdataproca;
                  BDHORAPROC       = whoraproca;
                  BDTIPO           = 4;
                  BDINFADIC        = '';
                  BDTIPODEDUCAOFOLHA = wtipodeducaoatu;
                  BDVALORDESCONTOSIMPLIFICADO = wvalordescsimplatu;
                  BDVALORDIFERENCADEDUCOES = wvalordifdescsimplatu;
                  BDAUXILIOMORADIA = 0;
                  BDDIARIA = 0;
                  BDBOLSAMEDICO = 0;
                  BDJUROSMORA = 0;
                  BDINCIDESOCIAL = 0;
                  BDINCIDESOCIALFER = 0;
                  SUSPEND;
          END
     END
     END

  /* FOLHA TOMADOR */
  IF ((prpuxarfiliais = 1) and (prcodmatriz is not null)) THEN
     WCODMATRIZ = prcodmatriz;
  ELSE
     WCODMATRIZ = null;
     
  if (prcodemp <> '') then
     wempresas = prcodemp;
  else
     wempresas = null;

  if (prcodcol <> '') then
     wcolaboradores = prcodcol;
  else
     wcolaboradores = null;

  FOR select
    BDCODEMP, BDCODCOL, BDREF, BDREFPAG, BDTIPO, BDRENDTRIBUTAVEL, BDINSS, BDIR, BDDEP, BDLUCROPJ, BDDESPMED, BDAJCUSTOS, BDPENJUD, BDPENALIM,
    BDPREVPRIV, BDINDRESC, BDVALABO, BDRENDISENTOS, BDDRENDISENTOS, BDDATAPGTO, BDINFADIC, BDDATAPROC, BDHORAPROC, BDORDEM, BDBASE13, BDVALOR13,
    BDBOLSAESTUDOS, BDTIPODEDUCAOFOLHA, BDVALORDESCONTOSIMPLIFICADO, BDVALORDIFERENCADEDUCOES, BDAUXILIOMORADIA, BDDIARIA, BDBOLSAMEDICO, BDJUROSMORA,
    BDINCIDESOCIAL, BDINCIDESOCIALFER, BDREFIRRFESOCIAL, bdcodtipo
  from SP_VRHF_DADOS_IR_FT(:WEMPRESAS, :WCOLABORADORES, :PRREFINI, :PRREFFIM, :PRPUXARFILIAIS, :WCODMATRIZ, :PRPREVIARESC, :PREXPORTACAO, :PRPORCC, :PRIRRFESOCIAL, :PRATUALIZAINFODESCSIMPLE, :PRVEIODOTOTALIZADOR)
  INTO
    :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR, :BDDEP, :BDLUCROPJ, :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM,
    :BDPREVPRIV, :BDINDRESC, :BDVALABO, :BDRENDISENTOS, :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDDATAPROC, :BDHORAPROC, :BDORDEM, :BDBASE13, :BDVALOR13,
    :BDBOLSAESTUDOS, :BDTIPODEDUCAOFOLHA, :BDVALORDESCONTOSIMPLIFICADO, :BDVALORDIFERENCADEDUCOES, :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA,
    :BDINCIDESOCIAL, :BDINCIDESOCIALFER, :bdrefirrfesocial, :bdcodtipo DO
  begin
    SUSPEND;
  end

  /* DADOS IMPORTADOS OU CADASTRADOS NA FICHA */
  for select BDCODEMP, BDCODCOL, BDREF, BDREFPAG, BDTIPO, BDRENDTRIBUTAVEL, BDINSS, BDIR, BDDEP, BDLUCROPJ, BDDESPMED, BDAJCUSTOS, BDPENJUD, BDPENALIM, BDPREVPRIV, BDINDRESC, BDVALABO, BDRENDISENTOS, BDDRENDISENTOS, BDDATAPGTO, BDINFADIC, BDVALORDESCONTOSIMPLIFICADO, BDAUXILIOMORADIA, BDDIARIA, BDBOLSAMEDICO, BDJUROSMORA, BDCODFIR, BDDEMDEV, BDCODTIPO
      from SP_VRHF_DADOS_IR_FN_FICHA(:prcodemp, :prcodcol, :prrefini, :prreffim, :prpuxarfiliais, :prcodmatriz, :prexportacao)
  into
    :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR, :BDDEP, :BDLUCROPJ, :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM, :BDPREVPRIV, :BDINDRESC, :BDVALABO, :BDRENDISENTOS, :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDVALORDESCONTOSIMPLIFICADO, :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA, :BDCODFIR, :BDDEMDEV, :BDCODTIPO
  DO
  BEGIN
    wpalancmanual = null;
    if (prexportacao<>2) then
       select SUM(BDVALDIRF) from VRH_EMP_TVALBENEF_DIRF where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDANODIRF = :BDREFPAG into :wpalancmanual;

    if (wpalancmanual is null) then
       wpalancmanual = 0;

    bdrefirrfesocial = bdrefpag;
    BDPENALIM = BDPENALIM + wpalancmanual;
    BDDATAPROC  = BDDATAPGTO;
    BDHORAPROC  = '00:00:00';

    if (pratualizainfodescsimple = TRUE) then
      begin
        wsqlauxsimpli = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, '||
                        ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, '||
                        ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) '||
                        ' values ('||current_connection||', '||:BDCODEMP||', '||:BDCODCOL||', '||:BDREFPAG||', 0, '||coalesce(:BDPENALIM, 0)||', '||coalesce(:BDDEP, 0)||', '||coalesce(:BDPREVPRIV, 0)||', '||coalesce(:BDINSS, 0)||', '||coalesce(:BDVALORDESCONTOSIMPLIFICADO, 0)||', FALSE, '||coalesce(:BDRENDTRIBUTAVEL, 0)||')';
        
        execute statement wsqlauxsimpli;
      end

    if (COALESCE(BDRENDTRIBUTAVEL, 0) <> 0) then
       BDINCIDESOCIAL = 1;

    SUSPEND;
  END


  if (coalesce(prfichafinanceira, 0) > 0) then
     begin
       for select BDCODEMP, BDCODCOL, BDREF, BDREFPAG, 0 BDTIPO, 0 BDRENDTRIBUTAVEL, 0 BDINSS, 0 BDIR, 0 BDDEP, BDLUCROPJ, 0 BDDESPMED,
                  0 BDAJCUSTOS, 0 BDPENJUD, 0 BDPENALIM, 0 BDPREVPRIV, 0 BDINDRESC, 0 BDVALABO, 0 BDRENDISENTOS, 0 BDDRENDISENTOS,
                  BDDATAPGTO, 0 BDINFADIC, null BDDATAPROC, null BDHORAPROC, null BDORDEM, 0 BDBASE13, 0 BDVALORDIFERENCADEDUCOES,
                  0 BDVALORDESCONTOSIMPLIFICADO, 0 BDVALOR13, 0 BDTIPODEDUCAOFOLHA, 0 BDBOLSAESTUDOS, 0 BDAUXILIOMORADIA, 0 BDDIARIA,
                  0 BDBOLSAMEDICO, 0 BDJUROSMORA, 0 BDINCIDESOCIAL, 0 BDINCIDESOCIALFER, 0 BDCODFIR, 0 BDDEMDEV, 0 BDREFIRRFESOCIAL,
                  BDCODTIPO
           from SP_VRHF_DADOS_IR_SOCIO(:prcodemp, :prcodcol, :prrefini, :prreffim, :prpuxarfiliais, :prcodmatriz)
       into :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR, :BDDEP, :BDLUCROPJ,
            :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM, :BDPREVPRIV, :BDINDRESC, :BDVALABO, :BDRENDISENTOS,
            :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDDATAPROC, :BDHORAPROC, :BDORDEM, :BDBASE13,
            :BDVALORDIFERENCADEDUCOES, :BDVALORDESCONTOSIMPLIFICADO, :BDVALOR13, :BDTIPODEDUCAOFOLHA, :BDBOLSAESTUDOS,
            :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA, :BDINCIDESOCIAL, :BDINCIDESOCIALFER, :BDCODFIR,
            :BDDEMDEV, :BDREFIRRFESOCIAL, :BDCODTIPO
       do
         suspend;
     end

end^


/* Restore proc. body: SP_VRHF_DADOS_IR_INTFT */
create or alter procedure SP_VRHF_DADOS_IR_INTFT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PRPORCC smallint = 0,
    PRINSSANTES smallint = 1,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WEHINDRESC varchar(5);
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WDATAPGTO date;
declare variable WCLASSIF varchar(20);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSSN numeric(18,6);
declare variable WIR numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(999);
declare variable WDATARESC date;
declare variable WCODPRES integer;
declare variable WDESCPRES varchar(110);
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WDESCCC varchar(100);
declare variable WREFINI integer;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WGCLASS varchar(13000);
declare variable WDESCVER2 varchar(70);
declare variable WI integer;
declare variable WPREVPRIVCAD numeric(18,6);
declare variable WISENTOABONO integer;
declare variable WCODCONTTI integer;
declare variable WCONTTIATU integer;
declare variable WINSSANTES numeric(18,6);
declare variable WPALANCMANUAL numeric(18,6);
declare variable WRUBRICA integer;
declare variable WCATEGORIAESOCIAL integer;
declare variable WBOLSAESTUDOS numeric(18,6);
declare variable WDRENDIS2 varchar(999);
declare variable WDRENDIS3 varchar(999);
declare variable WTIPODEDUCAO integer;
declare variable WVALORDESCSIMPL numeric(18,2);
declare variable WVALORDIFDESCSIMPL numeric(18,2);
declare variable WSQLAUXSIMPLI varchar(3000);
declare variable WTIPODEDUCAOATU integer;
declare variable WVALORDESCSIMPLATU numeric(18,2);
declare variable WVALORDIFDESCSIMPLATU numeric(18,2);
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WAUXILIOMORADIA numeric(18,6);
declare variable WDIARIA numeric(18,6);
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WJUROSMORA numeric(18,6);
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WINCIDESOCIALFER integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WGRAVARUBRICA integer;
begin
  /*FOLHA TOMADOR*/
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  if (upper(PRCODEMP) = 'TMP_EMPRESAS_SELECT') then
    WUSARTMP_EMP_SELECT = 1;

  if (upper(PRCODCOL) = 'TEMP_FILTRO_COLCON_REL') then
    WUSARTMP_COL_SELECT = 1;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  if (PRIRRFESOCIAL = true) then
    WREFINI = PRREFINI;
  else
  begin
    if (cast(substring(PRREFINI from 5 for 2) as integer) = 1) then
      WREFINI = cast((cast((cast(substring(PRREFINI from 1 for 4) as integer) - 1) as varchar(4)) || '12') as integer);
    else
    if (cast(substring(PRREFINI from 5 for 2) as integer) <= 10) then
      WREFINI = cast((substring(PRREFINI from 1 for 4) || '0' || cast((cast((substring(PRREFINI from 5 for 2)) as integer) - 1) as varchar(1))) as integer);
    else
      WREFINI = cast((substring(PRREFINI from 1 for 4) || cast((cast((substring(PRREFINI from 5 for 2)) as integer) - 1) as varchar(2))) as integer);
  end

  if (PRPUXARFILIAIS = 0) then
  begin
    WSQL = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDCODCONTTI,FOL.BDCODVER,FOL.BDVALVFT,FOLN.BDDATAPGTOFT,FOLN.BDDEPFT,VER.BDCLAVER,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT,VER.BDDESCVER, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ' ||
           'from VRHF_EMP_TFOLHATOMINT FOLN ';

    if (WUSARTMP_EMP_SELECT = 1) then
      WSQL = WSQL || ' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOLN.BDCODEMP ';

    if (WUSARTMP_COL_SELECT = 1) then
      WSQL = WSQL || 'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP and TEMP.BDCODCOL = FOLN.BDCODCOL) ';

    WSQL = WSQL || 'join VRHF_EMP_TVERBATOMINT FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDREFTOMADOR = FOLN.BDREFTOMADOR and FOL.BDORDEM = FOLN.BDORDEM and FOL.BDCODCONTTI = FOLN.BDCODCONTTI) ';
    WSQL = WSQL || 'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';

    WSQL = WSQL || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOLN.BDCODEMP) and (RESC.BDCODCOL = FOLN.BDCODCOL) and (RESC.BDREFRESCISAO >= ' || PRREFFIM || ') ';

    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOLN.BDREFTOMADOR ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    WSQL = WSQL || 'where ( ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || '(FOLN.BDREFIRRFESOCIAL between ' || WREFINI || ' and ' || PRREFFIM || ') or ';
    else
      WSQL = WSQL || ' (FOLN.BDREFTOMADOR >= ' || WREFINI || ' and FOLN.BDREFTOMADOR <= ' || PRREFFIM || ') or ';

    WSQL = WSQL || ' (FOLN.BDREFTOMADOR <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= ' || WREFINI || ' and RESC.BDREFPAGRESCISAO <= ' || PRREFFIM || ')) ';

    if ((PRCODEMP is not null) and
        (PRCODEMP <> '') and
        (WUSARTMP_EMP_SELECT = 0)) then
      WSQL = WSQL || ' and ' || PRCODEMP;

    if ((PRCODCOL is not null and
        PRCODCOL <> '') and
        (WUSARTMP_COL_SELECT = 0)) then
      WSQL = WSQL || ' and ' || PRCODCOL;

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDCODCONTTI,FOL.BDCODVER ';
    else
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDCODCONTTI ';
  end
  else
  begin
    WSQL = 'select FOLN.BDREFIRRFESOCIAL, FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDCODCONTTI,FO.BDCODVER,FO.BDVALVFT,FOLN.BDDATAPGTOFT,FOLN.BDDEPFT,VER.BDCLAVER,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT,VER.BDDESCVER, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';
    wsql = wsql||'from VRHF_EMP_TFOLHATOMINT FOLN join TEMPRESAS EMAT on (EMAT.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_EMP_SELECT = 1) then
       WSQL = WSQL || 'inner join TMP_EMPRESAS_SELECT TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
      WSQL = WSQL || 'join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FOLN.BDCODEMP and TEM.BDCODCOL = FOLN.BDCODCOL) ';

    WSQL = WSQL || 'join VRHF_EMP_TVERBATOMINT FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDREFTOMADOR = FOLN.BDREFTOMADOR and FO.BDORDEM = FOLN.BDORDEM and FO.BDCODCONTTI = FOLN.BDCODCONTTI) ';
    WSQL = WSQL || 'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';

    WSQL = WSQL || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOLN.BDCODEMP) and (RESC.BDCODCOL = FOLN.BDCODCOL) and (RESC.BDREFRESCISAO >= ' || PRREFFIM || ') ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOLN.BDREFTOMADOR ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    WSQL = WSQL || ' where ( ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || '(FOLN.BDREFIRRFESOCIAL between ' || WREFINI || ' and ' || PRREFFIM || ') or ';
    else
      WSQL = WSQL || '(FOLN.BDREFTOMADOR >= ' || WREFINI || ' and FOLN.BDREFTOMADOR <= ' || PRREFFIM || ') or ';

    WSQL = WSQL || ' (FOLN.BDREFTOMADOR <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= ' || WREFINI || ' and RESC.BDREFPAGRESCISAO <= ' || PRREFFIM || ')) ';

    if (WUSARTMP_EMP_SELECT = 0) then
    begin
      if (PRCODEMP is not null and
          PRCODEMP <> '') then
        WSQL = WSQL || ' and ((' || REPLACE(UPPER(PRCODEMP), 'FOL.', 'FOLN.') || ')';

      if (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '') then
        WSQL = WSQL || ' or (' || REPLACE(UPPER(PRCODMATRIZ), 'FOL.', 'EMAT.') || ')';

      if ((PRCODEMP is not null and
          PRCODEMP <> '') or (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '')) then
        WSQL = WSQL || ') ';
    end

    if ((PRCODCOL is not null and
        PRCODCOL <> '') and
        (WUSARTMP_COL_SELECT = 0)) then
      WSQL = WSQL || ' and ' || REPLACE(UPPER(PRCODCOL), 'FOL.', 'FOLN.') || ' ';

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDCODCONTTI,FO.BDCODVER ';
    else
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDCODCONTTI ';
  end

  WEMPATU = 0;
  WCOLATU = 0;
  WREFATU = 0;
  WCONTTIATU = 0;
  WORDEMATU = -1;

  WBASEIR = 0;
  WINSSN = 0;
  WIR = 0;
  WDEPATU = 0;
  WDATAATU = null;
  WLUCROPJ = 0;
  WDESPMED = 0;
  WAJCUS = 0;
  WBOLSAESTUDOS = 0;
  WPENJUD = 0;
  WPENALIM = 0;
  WPREPRI = 0;
  WINDRESC = 0;
  WVALABO = 0;
  WRENDIS = 0;
  WDRENDIS = '';
  WDATAPROCA = null;
  WHORAPROCA = null;
  WGCLASS = '';
  WVALORDESCSIMPLATU = 0;
  WVALORDIFDESCSIMPLATU = 0;
  WTIPODEDUCAOATU = 0;
  WAUXILIOMORADIA = 0;
  WDIARIA = 0;
  WBOLSAMEDICO = 0;
  WJUROSMORA = 0;
  WINCIDESOCIAL = 0;
  WINCIDESOCIALFER = 0;
  WREFIRRFESOCIALATU = -1;

  for execute statement WSQL
          into :WREFIRRFESOCIAL, :WCODEMP, :WCODCOL, :WREF, :WORDEM, :WCODCONTTI, :WCODVER, :WVALOR, :WDATAPGTO, :WDEP,
          :WCLASSIF, :WDATAPROC, :WHORAPROC, :WDESCVER2, :WTIPODEDUCAO, :WVALORDESCSIMPL, :WVALORDIFDESCSIMPL,
          :WCODCLA, :WTRIBUTACAOEXTERIOR
  do
  begin
    BDCODTIPO = 272; -- Cálculos do Único Folha

    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end

    if (WEMPATU = 0) then
      WEMPATU = WCODEMP;

    if (WCOLATU = 0) then
      WCOLATU = WCODCOL;

    if (WREFATU = 0) then
      WREFATU = WREF;

    if (WCONTTIATU = 0) then
      WCONTTIATU = WCODCONTTI;

    if (PRPORCC = 0) then
      WORDEMATU = coalesce(WORDEM, 0);
    else
    if (WORDEMATU = -1) then
      WORDEMATU = coalesce(WORDEM, 0);

    if (WVALORDESCSIMPLATU = 0) then
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;

    if (WVALORDIFDESCSIMPLATU = 0) then
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;

    if (WTIPODEDUCAOATU = 0) then
      WTIPODEDUCAOATU = WTIPODEDUCAO;

    if (WREFIRRFESOCIALATU = -1) then
      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;

    if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WREF <> WREFATU) or (WORDEMATU <> coalesce(WORDEM, 0)) or (WCODCONTTI <> WCONTTIATU)) then
    begin
      WCODPRES = null;
      WDESCPRES = null;
      WDATARESC = null;

      WDESCCC = null;
      WI = null;
      select first 1 PFN.BDCODTPCC,
                     case
                       when coalesce(CUS.BDNOMETOM, '') <> '' then CUS.BDNOMETOM
                       when coalesce(CC.BDNOMCTA, '') <> '' then CC.BDNOMCTA
                       else CC.BDAPECTA
                     end
      from VRHF_EMP_TPREPFN PFN
      left outer join VRH_BASE_TCUSTOM CUS on (CUS.BDCODCENTRO = PFN.BDCODCENTRO and
            CUS.BDCODTPCC = PFN.BDCODTPCC)
      left outer join CENTROS_TPCC CC on (CC.BDCODCENTRO = PFN.BDCODCENTRO and
            CC.BDCODTPCC = PFN.BDCODTPCC)
      where PFN.BDCODEMP = :WEMPATU and
            PFN.BDCODCOL = :WCOLATU and
            PFN.BDORDEM = :WORDEMATU
      into :WI, :WDESCCC;

      if (WI is null) then
        select first 1 BDNOMEMP
        from TEMPRESAS_REF
        where BDCODEMP = :WEMPATU and
              BDREFEMP <= :WREFATU
        order by BDREFEMP desc
        into :WDESCCC;

      WREFPAGTO = cast((substring(cast(WDATAATU as varchar(10)) from 1 for 4) || substring(cast(WDATAATU as varchar(10)) from 6 for 2)) as integer);

      if (WREFPAGTO >= PRREFINI and
          WREFPAGTO <= PRREFFIM) then
      begin
        WPREVPRIVCAD = 0;
        if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WREF <> WREFATU) or (WORDEMATU <> coalesce(WORDEM, 0))) then
        begin
          select sum(coalesce(LANPREV.BDVALMENSAL, 0))
          from VRH_EMP_TLANCPREVCOMP LANPREV
          join VRH_BASE_TCADPREVCOMP CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV and
                CADPREV.BDNATPREV <> 2) /* 184717 Leonardo Schwab 16/11/2023 */
          where LANPREV.BDCODEMP = :WEMPATU and
                LANPREV.BDCODCOL = :WCOLATU and
                LANPREV.BDREFINI <= :WREFATU and
                ((coalesce(LANPREV.BDREFFIN, 0) = 0) or (coalesce(LANPREV.BDREFFIN, 0) >= :WREFATU))
          into :WPREVPRIVCAD;
          WPREVPRIVCAD = coalesce(WPREVPRIVCAD, 0);
        end

        WINSSANTES = null;
        if (coalesce(PRINSSANTES, 0) = 1 and
            WREFPAGTO <> WREFATU) then
        begin
          select sum(BDINSSFT)
          from VRHF_EMP_TFOLHATOMINT
          where BDCODEMP = :WEMPATU and
                BDCODCOL = :WCOLATU and
                BDREFTOMADOR = :WREFATU and
                BDORDEM = :WORDEMATU and
                BDDATAPGTOFT < :WDATAATU and
                BDCODCONTTI <> :WCONTTIATU
          into :WINSSANTES;
        end

        if (WINSSANTES is null) then
          WINSSANTES = 0;

        BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
        BDCODEMP = WEMPATU;
        BDCODCOL = WCOLATU;
        BDREF = WREFATU;
        BDORDEM = WORDEMATU;
        BDCODCONTTI = WCONTTIATU;
        BDREFPAG = WREFPAGTO;
        BDRENDTRIBUTAVEL = WBASEIR;
        BDINSS = WINSSN + WINSSANTES;
        BDIR = WIR;

        if ((WBASEIR + WINSSN + WIR > 0) or (PRVEIODOTOTALIZADOR > 0)) then
          BDDEP = WDEPATU;
        else
          BDDEP = 0;

        WPALANCMANUAL = null;
        if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WREF <> WREFATU)) then
          select sum(BDVALDIRF)
          from VRH_EMP_TVALBENEF_DIRF
          where BDCODEMP = :WEMPATU and
                BDCODCOL = :WCOLATU and
                BDANODIRF = :WREFPAGTO
          into :WPALANCMANUAL;

        if (WPALANCMANUAL is null) then
          WPALANCMANUAL = 0;

        select first 1 BDCATEGORIAESOCIAL
        from VRHF_EMP_TCOLCON_FGTSGPS
        where BDCODEMP = :WEMPATU and
              BDCODCOL = :WCOLATU and
              BDREFCOL <= :WREFATU
        order by BDREFCOL desc
        into :WCATEGORIAESOCIAL;

        BDLUCROPJ = WLUCROPJ;
        BDDESPMED = WDESPMED;
        BDAJCUSTOS = WAJCUS;
        if (WCATEGORIAESOCIAL = 903) then
        begin
          BDBOLSAESTUDOS = WBOLSAESTUDOS;
          if (coalesce(WDRENDIS2, '') <> '') then
          begin
            if (coalesce(WDRENDIS, '') <> '') then
              WDRENDIS = WDRENDIS || ',';

            if (PRVEIODOTOTALIZADOR = 1) then
              WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 999);
            else
              WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 200);
          end
        end
        else
        begin
          BDAJCUSTOS = BDAJCUSTOS + WBOLSAESTUDOS;
          if (coalesce(WDRENDIS3, '') <> '') then
          begin
            if (coalesce(WDRENDIS, '') <> '') then
              WDRENDIS = WDRENDIS || ',';

            if (PRVEIODOTOTALIZADOR = 1) then
              WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 999);
            else
              WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 200);
          end
        end
        BDPENJUD = WPENJUD;
        BDPENALIM = WPENALIM + WPALANCMANUAL;

        if (coalesce(:WPREVPRIVCAD, 0) > 0) then
        begin
          if (coalesce(:WPREPRI, 0) > 0) then
            BDPREVPRIV = WPREPRI;
          else
          if (coalesce(:WPREVPRIVCAD, 0) > 0) then
            BDPREVPRIV = WPREVPRIVCAD;
        end
        else
          BDPREVPRIV = 0;

        BDINDRESC = WINDRESC;
        BDVALABO = WVALABO;
        BDRENDISENTOS = WRENDIS;
        BDDRENDISENTOS = WDRENDIS;
        BDDATAPGTO = WDATAATU;
        BDDATAPROC = WDATAPROCA;
        BDHORAPROC = WHORAPROCA;

        if (WDATARESC is not null) then
        begin
          BDTIPO = 100; -- Folha normal rescisão
          BDINFADIC = substring(WORDEMATU || ' - ' || WDESCCC || '; ' || WCODPRES || ' - ' || WDESCPRES from 1 for 300);
        end
        else
        begin
          BDTIPO = 0; -- Folha normal
          BDINFADIC = substring(WORDEMATU || ' - ' || WDESCCC from 1 for 300);
        end

        if (PRATUALIZAINFODESCSIMPLE = true) then
        begin
          WSQLAUXSIMPLI = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, ' || ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, ' || ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) ' || ' values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPAGTO || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(WBASEIR, 0) || ')';

          execute statement WSQLAUXSIMPLI;
        end

        BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
        BDAUXILIOMORADIA = WAUXILIOMORADIA;
        BDDIARIA = WDIARIA;
        BDBOLSAMEDICO = WBOLSAMEDICO;
        BDJUROSMORA = WJUROSMORA;
        BDINCIDESOCIAL = WINCIDESOCIAL;
        BDINCIDESOCIALFER = WINCIDESOCIALFER;
        suspend;
      end

      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;
      WEMPATU = WCODEMP;
      WCOLATU = WCODCOL;
      WREFATU = WREF;
      WORDEMATU = WORDEM;
      WCONTTIATU = WCODCONTTI;

      WBASEIR = 0;
      WINSSN = 0;
      WIR = 0;
      WDEPATU = 0;
      WDATAATU = null;
      WLUCROPJ = 0;
      WDESPMED = 0;
      WAJCUS = 0;
      WBOLSAESTUDOS = 0;
      WPENJUD = 0;
      WPENALIM = 0;
      WPREPRI = 0;
      WINDRESC = 0;
      WVALABO = 0;
      WRENDIS = 0;
      WDRENDIS = '';
      WGCLASS = '';
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
      WTIPODEDUCAOATU = WTIPODEDUCAO;
      WAUXILIOMORADIA = 0;
      WDIARIA = 0;
      WBOLSAMEDICO = 0;
      WJUROSMORA = 0;
      WINCIDESOCIAL = 0;
      WINCIDESOCIALFER = 0;
    end

    -- soma as bases
    select first 1 BDTIPOCODVER, coalesce(BDIRVER, 0), BDRENDISENTOIRVER, BDINDRESC, BDCODINCIDIRRF
    from VRH_BASE_TVERBAS_REF
    where BDCODVER = :WCODVER and
          BDREFVER <= :WREFATU
    order by BDCODVER desc, BDREFVER desc
    into :WTIPOCODVER, :WIRVER, :WRENDISENTOVER, :WEHINDRESC, :WCODINCIDIRRF;
    begin

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end


    --    if (wtipocodver <= 1) then
    begin

    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
      begin
        WIRVER = 0;
      end
   else
      begin
       --    if (wtipocodver <= 1) then

          if (WIRVER = 1) then -- IR Folha normal
          begin
            if (WTIPOCODVER = 0) then -- provento
              WBASEIR = WBASEIR + WVALOR;
            else
            if (WTIPOCODVER = 1) then -- desconto
            begin
              --                                      INSS                                              Obrigações IR
              if (substring(WCLASSIF from 1 for 7) <> '9.010.0' and
                  substring(WCLASSIF from 1 for 5) <> '0.030') then
                WBASEIR = WBASEIR - WVALOR;
            end
          end

        --                                     IR folha normal
        if (substring(WCLASSIF from 1 for 9) = '9.010.1.0') then
            WIR = WIR + WVALOR;
       end
      end
      --                                     INSS folha normal
      if (substring(WCLASSIF from 1 for 9) = '9.010.0.0') then
        WINSSN = WINSSN + WVALOR;
      --                                     Lucro pessoa jurídica
      if (substring(WCLASSIF from 1 for 9) = '0.040.0.2') then
        WLUCROPJ = WLUCROPJ + WVALOR;
      --                                     Despesas médicas                                     Complemento de despesas médicas
      if ((substring(WCLASSIF from 1 for 9) = '0.030.1.0') or (substring(WCLASSIF from 1 for 9) = '0.420.0.2')) then
        WDESPMED = WDESPMED + WVALOR;
      --                                     Ajuda de custos
      if (substring(WCLASSIF from 1 for 9) = '0.040.0.1' and
          WIRVER = 0) then
      begin
        select first 1 BDCHAVE
        from VRH_BASE_TRUBRICAESOCIAL_VER
        where BDCODVER = :WCODVER
        into :WRUBRICA;
        if (WRUBRICA = 1350) then -- Bolsa estudos
        begin
          WBOLSAESTUDOS = WBOLSAESTUDOS + WVALOR;
          if (WDRENDIS2 <> '') then
            WDRENDIS2 = WDRENDIS2 || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS2 = substring(WDRENDIS2 || 'BOLSA DE ESTUDOS' from 1 for 999);
          else
            WDRENDIS2 = substring(WDRENDIS2 || 'BOLSA DE ESTUDOS' from 1 for 200);

          if (WDRENDIS3 <> '') then
            WDRENDIS3 = WDRENDIS3 || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS3 = substring(WDRENDIS3 || WDESCVER2 from 1 for 999);
          else
            WDRENDIS3 = substring(WDRENDIS3 || WDESCVER2 from 1 for 200);
        end
        else
          WAJCUS = WAJCUS + WVALOR;
      end
      --                                     Pensões judiciais
      if (substring(WCLASSIF from 1 for 9) = '0.030.0.0') then
        WPENJUD = WPENJUD + WVALOR;
      --                                     Pensões alimentícias
      if (substring(WCLASSIF from 1 for 9) = '0.030.0.1') then
        WPENALIM = WPENALIM + WVALOR;
      --                                     Previdência privada
      if (substring(WCLASSIF from 1 for 9) = '0.030.1.2') then
        WPREPRI = WPREPRI + WVALOR;

      --    if ((substring(wclassif from 1 for 7) = '7.001.3') or (substring(wclassif from 1 for 5) = '7.020') or (substring(wclassif from 1 for 5) = '7.021')) then
      if (upper(WEHINDRESC) = 'TRUE') then
      begin
        if (WTIPOCODVER in (0, 2)) then -- Provento
          WINDRESC = WINDRESC + WVALOR;
        else
        if (WTIPOCODVER in (1, 3)) then -- Desconto
          WINDRESC = WINDRESC - WVALOR;
      end

      if (substring(WCLASSIF from 1 for 9) = '0.040.0.3') then
        WAUXILIOMORADIA = WAUXILIOMORADIA + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.040.0.0' and
          WIRVER = 0) then
        WDIARIA = WDIARIA + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.910.0.0') then
        WBOLSAMEDICO = WBOLSAMEDICO + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.920.0.0') then
        WJUROSMORA = WJUROSMORA + WVALOR;

      if (coalesce(WCODINCIDIRRF, 0) in (11, 12, 14, 41, 42, 51, 52, 54)) then
        WINCIDESOCIAL = 1;

      if (coalesce(WCODINCIDIRRF, 0) in (13, 43, 53)) then
        WINCIDESOCIALFER = 1;

      WISENTOABONO = 0;
      --                                      Complemento de abono pecuniário                  Compl. 1/3 abono pecuniário
      if ((substring(WCLASSIF from 1 for 7) = '0.210.2') or (substring(WCLASSIF from 1 for 7) = '0.210.3')) then
      begin
        WVALABO = WVALABO + WVALOR;
      end
      else

      -- Rendimentos isentos
      if ((upper(WRENDISENTOVER) = 'TRUE') and
          (WISENTOABONO = 0)) then
      begin
        WRENDIS = WRENDIS + WVALOR;

        WI = 0;

        if (PRVEIODOTOTALIZADOR = 1) then
          select POS
          from POS(:WCLASSIF, :WGCLASS)
          into :WI;
        else
          select POS
          from POS(substring(:WCLASSIF from 1 for 5), :WGCLASS)
          into :WI;

        if (WI = 0) then
        begin
          WDESCVER2 = '';

          if (PRVEIODOTOTALIZADOR = 1) then
          begin
            select first 1 BDDESCVER
            from VRH_BASE_TVERBAS
            where BDCLAVER = :WCLASSIF
            into WDESCVER2;
            WGCLASS = WGCLASS || ';' || :WCLASSIF;
          end
          else
          begin
            select first 1 BDDESCVER
            from VRH_BASE_TVERBAS
            where BDCLAVER = substring(:WCLASSIF from 1 for 5)
            into WDESCVER2;
            WGCLASS = WGCLASS || ';' || substring(:WCLASSIF from 1 for 5);
          end

          if (WDRENDIS <> '') then
            WDRENDIS = WDRENDIS || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS = substring(WDRENDIS || WDESCVER2 from 1 for 999);
          else
            WDRENDIS = substring(WDRENDIS || WDESCVER2 from 1 for 200);
        end
      end
    end

    WDEPATU = WDEP;
    WDATAATU = WDATAPGTO;
    WDATAPROCA = WDATAPROC;
    WHORAPROCA = WHORAPROC;
  end

  if (WEMPATU <> 0 and
      WCOLATU <> 0 and
      WREFATU <> 0 and
      WCONTTIATU <> 0) then
  begin
    WCODPRES = null;
    WDESCPRES = null;
    WDATARESC = null;

    WDESCCC = null;
    WI = null;
    select first 1 PFN.BDCODTPCC,
                   case
                     when coalesce(CUS.BDNOMETOM, '') <> '' then CUS.BDNOMETOM
                     when coalesce(CC.BDNOMCTA, '') <> '' then CC.BDNOMCTA
                     else CC.BDAPECTA
                   end
    from VRHF_EMP_TPREPFN PFN
    left outer join VRH_BASE_TCUSTOM CUS on (CUS.BDCODCENTRO = PFN.BDCODCENTRO and
          CUS.BDCODTPCC = PFN.BDCODTPCC)
    left outer join CENTROS_TPCC CC on (CC.BDCODCENTRO = PFN.BDCODCENTRO and
          CC.BDCODTPCC = PFN.BDCODTPCC)
    where PFN.BDCODEMP = :WEMPATU and
          PFN.BDCODCOL = :WCOLATU and
          PFN.BDORDEM = :WORDEMATU
    into :WI, :WDESCCC;

    if (WI is null) then
      select first 1 BDNOMEMP
      from TEMPRESAS_REF
      where BDCODEMP = :WEMPATU and
            BDREFEMP <= :WREFATU
      order by BDREFEMP desc
      into :WDESCCC;

    WREFPAGTO = cast((substring(cast(WDATAATU as varchar(10)) from 1 for 4) || substring(cast(WDATAATU as varchar(10)) from 6 for 2)) as integer);

    if (WREFPAGTO >= PRREFINI and
        WREFPAGTO <= PRREFFIM) then
    begin
      WPREVPRIVCAD = 0;
      select sum(coalesce(LANPREV.BDVALMENSAL, 0))
      from VRH_EMP_TLANCPREVCOMP LANPREV
      join VRH_BASE_TCADPREVCOMP CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV and
            CADPREV.BDNATPREV <> 2) /* 184717 Leonardo Schwab 16/11/2023 */
      where LANPREV.BDCODEMP = :WEMPATU and
            LANPREV.BDCODCOL = :WCOLATU and
            LANPREV.BDREFINI <= :WREFATU and
            ((coalesce(LANPREV.BDREFFIN, 0) = 0) or (coalesce(LANPREV.BDREFFIN, 0) >= :WREFATU))
      into :WPREVPRIVCAD;
      WPREVPRIVCAD = coalesce(WPREVPRIVCAD, 0);

      WINSSANTES = null;
      if (coalesce(PRINSSANTES, 0) = 1 and
          WREFPAGTO <> WREFATU) then
      begin
        select sum(BDINSSFT)
        from VRHF_EMP_TFOLHATOMINT
        where BDCODEMP = :WEMPATU and
              BDCODCOL = :WCOLATU and
              BDREFTOMADOR = :WREFATU and
              BDORDEM = :WORDEMATU and
              BDDATAPGTOFT < :WDATAATU and
              BDCODCONTTI <> :WCONTTIATU
        into :WINSSANTES;
      end

      if (WINSSANTES is null) then
        WINSSANTES = 0;

      BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
      BDCODEMP = WEMPATU;
      BDCODCOL = WCOLATU;
      BDREF = WREFATU;
      BDORDEM = WORDEMATU;
      BDCODCONTTI = WCONTTIATU;
      BDREFPAG = WREFPAGTO;
      BDRENDTRIBUTAVEL = WBASEIR;
      BDINSS = WINSSN + WINSSANTES;
      BDIR = WIR;

      if ((WBASEIR + WINSSN + WIR > 0) or (PRVEIODOTOTALIZADOR > 0)) then
        BDDEP = WDEPATU;
      else
        BDDEP = 0;

      WPALANCMANUAL = null;
      if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WREF <> WREFATU)) then
        select sum(BDVALDIRF)
        from VRH_EMP_TVALBENEF_DIRF
        where BDCODEMP = :WEMPATU and
              BDCODCOL = :WCOLATU and
              BDANODIRF = :WREFPAGTO
        into :WPALANCMANUAL;

      if (WPALANCMANUAL is null) then
        WPALANCMANUAL = 0;

      BDLUCROPJ = WLUCROPJ;
      BDDESPMED = WDESPMED;
      BDAJCUSTOS = WAJCUS;
      BDBOLSAESTUDOS = WBOLSAESTUDOS;
      BDPENJUD = WPENJUD;
      BDPENALIM = WPENALIM + WPALANCMANUAL;

      if (coalesce(:WPREVPRIVCAD, 0) > 0) then
      begin
        if (coalesce(:WPREPRI, 0) > 0) then
          BDPREVPRIV = WPREPRI;
        else
          BDPREVPRIV = WPREVPRIVCAD;
      end
      else
        BDPREVPRIV = 0;

      BDINDRESC = WINDRESC;
      BDVALABO = WVALABO;
      BDRENDISENTOS = WRENDIS;
      BDDRENDISENTOS = WDRENDIS;
      BDDATAPGTO = WDATAATU;
      BDDATAPROC = WDATAPROCA;
      BDHORAPROC = WHORAPROCA;

      if (WDATARESC is not null) then
      begin
        BDTIPO = 100; -- Folha normal rescisão
        BDINFADIC = substring(WORDEMATU || ' - ' || WDESCCC || '; ' || WCODPRES || ' - ' || WDESCPRES from 1 for 300);
      end
      else
      begin
        BDTIPO = 0; -- Folha normal
        BDINFADIC = substring(WORDEMATU || ' - ' || WDESCCC from 1 for 300);
      end

      if (PRATUALIZAINFODESCSIMPLE = true) then
      begin
        WSQLAUXSIMPLI = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, ' || ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, ' || ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) ' || ' values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPAGTO || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';

        execute statement WSQLAUXSIMPLI;
      end

      BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
      BDAUXILIOMORADIA = WAUXILIOMORADIA;
      BDDIARIA = WDIARIA;
      BDBOLSAMEDICO = WBOLSAMEDICO;
      BDJUROSMORA = WJUROSMORA;
      BDINCIDESOCIAL = WINCIDESOCIAL;
      BDINCIDESOCIALFER = WINCIDESOCIALFER;
      suspend;
    end
  end
end^

/* Restore proc. body: SP_VRHF_DADOS_IR_INT */
create or alter procedure SP_VRHF_DADOS_IR_INT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PRPORCC smallint = 0,
    PRINSSANTES smallint = 1,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WEHINDRESC varchar(5);
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WDATAPGTO date;
declare variable WCLASSIF varchar(20);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSSN numeric(18,6);
declare variable WIR numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(999);
declare variable WDATARESC date;
declare variable WDATAPAGRESC date;
declare variable WCODPRES integer;
declare variable WDESCPRES varchar(110);
declare variable WREFINI integer;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WTIPOMOV integer;
declare variable WGCLASS varchar(13000);
declare variable WDESCVER2 varchar(70);
declare variable WI integer;
declare variable WPREVPRIVCAD numeric(18,6);
declare variable WISENTOABONO integer;
declare variable WCODCONTTI integer;
declare variable WCONTTIATU integer;
declare variable WINSSANTES numeric(18,6);
declare variable WPALANCMANUAL numeric(18,6);
declare variable WRUBRICA integer;
declare variable WCATEGORIAESOCIAL integer;
declare variable WBOLSAESTUDOS numeric(18,6);
declare variable WDRENDIS2 varchar(999);
declare variable WDRENDIS3 varchar(999);
declare variable WTIPODEDUCAO integer;
declare variable WVALORDESCSIMPL numeric(18,2);
declare variable WVALORDIFDESCSIMPL numeric(18,2);
declare variable WSQLAUXSIMPLI varchar(3000);
declare variable WTIPODEDUCAOATU integer;
declare variable WVALORDESCSIMPLATU numeric(18,2);
declare variable WVALORDIFDESCSIMPLATU numeric(18,2);
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WAUXILIOMORADIA numeric(18,6);
declare variable WDIARIA numeric(18,6);
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WJUROSMORA numeric(18,6);
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WINCIDESOCIALFER integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WGRAVARUBRICA integer;
begin
  /*FOLHA NORMAL*/
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  if (upper(PRCODEMP) = 'TMP_EMPRESAS_SELECT') then
    WUSARTMP_EMP_SELECT = 1;

  if (upper(PRCODCOL) = 'TEMP_FILTRO_COLCON_REL') then
    WUSARTMP_COL_SELECT = 1;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  if (PRIRRFESOCIAL = true) then
    WREFINI = PRREFINI;
  else
  begin
    if (cast(substring(PRREFINI from 5 for 2) as integer) = 1) then
      WREFINI = cast((cast((cast(substring(PRREFINI from 1 for 4) as integer) - 1) as varchar(4)) || '12') as integer);
    else
    if (cast(substring(PRREFINI from 5 for 2) as integer) <= 10) then
      WREFINI = cast((substring(PRREFINI from 1 for 4) || '0' || cast((cast((substring(PRREFINI from 5 for 2)) as integer) - 1) as varchar(1))) as integer);
    else
      WREFINI = cast((substring(PRREFINI from 1 for 4) || cast((cast((substring(PRREFINI from 5 for 2)) as integer) - 1) as varchar(2))) as integer);
  end

  if (PRPUXARFILIAIS = 0) then
  begin
    if (PRIRRFESOCIAL = true) then
      WSQL = 'select FOLN.BDREFIRRFESOCIAL, FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODCONTTI,FOL.BDCODVER,FOL.BDVALVFN,FOLN.BDDATAIRRFESOCIAL AS BDDATAPGTOFN,FOLN.BDDEPFN,VER.BDCLAVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN,VER.BDDESCVER, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';
    else
      WSQL = 'select FOLN.BDREFIRRFESOCIAL, FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODCONTTI,FOL.BDCODVER,FOL.BDVALVFN,FOLN.BDDATAPGTOFN,FOLN.BDDEPFN,VER.BDCLAVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN,VER.BDDESCVER, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';

    WSQL = WSQL || 'from VRHF_EMP_TFOLHAINT FOLN ';

    if (WUSARTMP_EMP_SELECT = 1) then
      WSQL = WSQL || 'INNER JOIN tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
      WSQL = WSQL || 'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP and TEMP.BDCODCOL = FOLN.BDCODCOL) ';

    WSQL = WSQL || 'join VRHF_EMP_TVERBAINT FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDREFFN = FOLN.BDREFFN and FOL.BDCODCONTTI = FOLN.BDCODCONTTI) ';
    WSQL = WSQL || 'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';

    WSQL = WSQL || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOLN.BDCODEMP) and (RESC.BDCODCOL = FOLN.BDCODCOL) and (RESC.BDREFRESCISAO >= ' || PRREFFIM || ') ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOLN.BDREFFN ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where FOLN.BDREFIRRFESOCIAL between ' || WREFINI || ' and ' || PRREFFIM || ' ';
    else
    begin
      WSQL = WSQL || 'where ((FOLN.BDREFFN >= ' || WREFINI || ' and FOLN.BDREFFN <= ' || PRREFFIM || ') or ';
      WSQL = WSQL || '       (FOLN.BDREFFN <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO >= ' || WREFINI || ' and RESC.BDREFPAGRESCISAO <= ' || PRREFFIM || ')) ';
    end

    if ((PRCODEMP is not null) and
        (PRCODEMP <> '') and
        (WUSARTMP_EMP_SELECT = 0)) then
      WSQL = WSQL || ' and ' || PRCODEMP;

    if ((PRCODCOL is not null and
        PRCODCOL <> '') and
        (WUSARTMP_COL_SELECT = 0)) then
      WSQL = WSQL || ' and ' || PRCODCOL;

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' and FOLN.BDTIPODEDUCAOFOLHA = (SELECT first 1 FOLN1.BDTIPODEDUCAOFOLHA FROM  vrhf_emp_tfolhaint FOLN1 WHERE FOLN.BDCODEMP = FOLN1.BDCODEMP AND FOLN.BDCODCOL = FOLN1.bdcodcol AND FOLN.BDREFFN = FOLN1.BDREFFN AND FOLN.BDCODCONTTI = FOLN1.BDCODCONTTI ORDER BY FOLN1.bdtipodeducaofolha DESC) ';

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDCODCONTTI,FOL.BDCODVER ';
    else
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDCODCONTTI ';
  end
  else
  begin
    if (PRIRRFESOCIAL = true) then
      WSQL = 'select FOLN.BDREFIRRFESOCIAL, FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDCODCONTTI,FO.BDCODVER,FO.BDVALVFN,FOLN.BDDATAIRRFESOCIAL AS BDDATAPGTOFN,FOLN.BDDEPFN,VER.BDCLAVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN,VER.BDDESCVER, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';
    else
      WSQL = 'select FOLN.BDREFIRRFESOCIAL, FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDCODCONTTI,FO.BDCODVER,FO.BDVALVFN,FOLN.BDDATAPGTOFN,FOLN.BDDEPFN,VER.BDCLAVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN,VER.BDDESCVER, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR   ';

    wsql = wsql||'from VRHF_EMP_TFOLHAINT FOLN join TEMPRESAS EMAT on (EMAT.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_EMP_SELECT = 1) then
       WSQL = WSQL || 'inner join TMP_EMPRESAS_SELECT TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP) ';

    if (WUSARTMP_COL_SELECT = 1) then
      WSQL = WSQL || 'join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FOLN.BDCODEMP and TEM.BDCODCOL = FOLN.BDCODCOL) ';

    WSQL = WSQL || 'join VRHF_EMP_TVERBAINT FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDREFFN = FOLN.BDREFFN and FO.BDCODCONTTI = FOLN.BDCODCONTTI) ';
    WSQL = WSQL || 'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';

    WSQL = WSQL || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOLN.BDCODEMP) and (RESC.BDCODCOL = FOLN.BDCODCOL) and (RESC.BDREFRESCISAO >= ' || PRREFFIM || ') ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
    WSQL = WSQL || 'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                   '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                   '                                     AND X.BDREFCOL <= FOLN.BDREFFN ORDER BY X.BDREFCOL DESC) '||
                   '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                   '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

    if (PRIRRFESOCIAL = true) then
      WSQL = WSQL || 'where FOLN.BDREFIRRFESOCIAL between ' || WREFINI || ' and ' || PRREFFIM || ' ';
    else
    begin
      WSQL = WSQL || 'where ((FOLN.BDREFFN between ' || WREFINI || ' and ' || PRREFFIM || ') or ';
      WSQL = WSQL || '       (FOLN.BDREFFN <= RESC.BDREFRESCISAO and RESC.BDREFPAGRESCISAO between ' || WREFINI || ' and ' || PRREFFIM || ')) ';
    end

    if (WUSARTMP_EMP_SELECT = 0) then
    begin
      if (PRCODEMP is not null and
          PRCODEMP <> '') then
        WSQL = WSQL || ' and ((' || REPLACE(UPPER(PRCODEMP), 'FOL.', 'FOLN.') || ')';

      if (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '') then
        WSQL = WSQL || ' or (' || REPLACE(UPPER(PRCODMATRIZ), 'FOL.', 'EMAT.') || ')';

      if ((PRCODEMP is not null and
          PRCODEMP <> '') or (PRCODMATRIZ is not null and
          PRCODMATRIZ <> '')) then
        WSQL = WSQL || ') ';
    end

    if ((PRCODCOL is not null and
        PRCODCOL <> '') and
        (WUSARTMP_COL_SELECT = 0)) then
      WSQL = WSQL || ' and ' || REPLACE(UPPER(PRCODCOL), 'FOL.', 'FOLN.') || ' ';

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' and FOLN.BDTIPODEDUCAOFOLHA = (SELECT first 1 FOLN1.BDTIPODEDUCAOFOLHA FROM  vrhf_emp_tfolhaint FOLN1 WHERE FOLN.BDCODEMP = FOLN1.BDCODEMP AND FOLN.BDCODCOL = FOLN1.bdcodcol AND FOLN.BDREFFN = FOLN1.BDREFFN AND FOLN.BDCODCONTTI = FOLN1.BDCODCONTTI ORDER BY FOLN1.bdtipodeducaofolha DESC) ';

    if (PRVEIODOTOTALIZADOR = 1) then
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDCODCONTTI,FO.BDCODVER ';
    else
      WSQL = WSQL || ' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDCODCONTTI ';
  end

  WEMPATU = 0;
  WCOLATU = 0;
  WREFATU = 0;
  WCONTTIATU = 0;

  WBASEIR = 0;
  WINSSN = 0;
  WIR = 0;
  WDEPATU = 0;
  WDATAATU = null;
  WLUCROPJ = 0;
  WDESPMED = 0;
  WAJCUS = 0;
  WBOLSAESTUDOS = 0;
  WPENJUD = 0;
  WPENALIM = 0;
  WPREPRI = 0;
  WINDRESC = 0;
  WVALABO = 0;
  WRENDIS = 0;
  WDRENDIS = '';
  WDRENDIS2 = '';
  WDRENDIS3 = '';
  WDATAPROCA = null;
  WHORAPROCA = null;
  WGCLASS = '';
  WEHINDRESC = '';
  WVALORDESCSIMPL = 0;
  WVALORDIFDESCSIMPL = 0;
  WTIPODEDUCAO = 0;
  WVALORDESCSIMPLATU = 0;
  WVALORDIFDESCSIMPLATU = 0;
  WTIPODEDUCAOATU = 0;
  WAUXILIOMORADIA = 0;
  WDIARIA = 0;
  WBOLSAMEDICO = 0;
  WJUROSMORA = 0;
  WINCIDESOCIAL = 0;
  WINCIDESOCIALFER = 0;
  WREFIRRFESOCIALATU = -1;

  for execute statement WSQL
          into :WREFIRRFESOCIAL, :WCODEMP, :WCODCOL, :WREF, :WCODCONTTI, :WCODVER, :WVALOR, :WDATAPGTO, :WDEP,
          :WCLASSIF, :WDATAPROC, :WHORAPROC, :WDESCVER2, :WTIPODEDUCAO, :WVALORDESCSIMPL, :WVALORDIFDESCSIMPL,
          :WCODCLA, :WTRIBUTACAOEXTERIOR
  do
  begin
    BDCODTIPO = 272; -- Cálculos do Único Folha

    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end

    if (WEMPATU = 0) then
      WEMPATU = WCODEMP;

    if (WCOLATU = 0) then
      WCOLATU = WCODCOL;

    if (WREFATU = 0) then
      WREFATU = WREF;

    if (WCONTTIATU = 0) then
      WCONTTIATU = WCODCONTTI;

    if (WVALORDESCSIMPLATU = 0) then
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;

    if (WVALORDIFDESCSIMPLATU = 0) then
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;

    if (WTIPODEDUCAOATU = 0) then
      WTIPODEDUCAOATU = WTIPODEDUCAO;

    if (WREFIRRFESOCIALATU = -1) then
      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;

    if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WREF <> WREFATU) or (WCODCONTTI <> WCONTTIATU)) then
    begin
      WCODPRES = null;
      WDESCPRES = null;
      WDATARESC = null;
      WDATAPAGRESC = null;
      WTIPOMOV = 0;

      WREFPAGTO = cast((substring(cast(WDATAATU as varchar(10)) from 1 for 4) || substring(cast(WDATAATU as varchar(10)) from 6 for 2)) as integer);
      if (WREFPAGTO >= PRREFINI and
          WREFPAGTO <= PRREFFIM) then
      begin
        WPREVPRIVCAD = 0;
        select sum(coalesce(LANPREV.BDVALMENSAL, 0))
        from VRH_EMP_TLANCPREVCOMP LANPREV join(select BDCODCADPREV
                                                from VRH_BASE_TCADPREVCOMP
                                                where BDNATPREV <> 2) CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV) /* 184717 Leonardo Schwab 16/11/2023 */
        where LANPREV.BDCODEMP = :WEMPATU and
              LANPREV.BDCODCOL = :WCOLATU and
              LANPREV.BDREFINI <= :WREFATU and
              ((coalesce(LANPREV.BDREFFIN, 0) >= :WREFATU) or (coalesce(LANPREV.BDREFFIN, 0) = 0))
        into :WPREVPRIVCAD;
        WPREVPRIVCAD = coalesce(WPREVPRIVCAD, 0);

        WINSSANTES = null;
        if (coalesce(PRINSSANTES, 0) = 1 and
            WREFPAGTO <> WREFATU) then
        begin
          select sum(BDINSSFN)
          from VRHF_EMP_TFOLHAINT
          where BDCODEMP = :WEMPATU and
                BDCODCOL = :WCOLATU and
                BDREFFN = :WREFATU and
                BDDATAPGTOFN < :WDATAATU and
                BDCODCONTTI <> :WCONTTIATU
          into :WINSSANTES;
        end

        if (WINSSANTES is null) then
          WINSSANTES = 0;

        BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
        BDCODEMP = WEMPATU;
        BDCODCOL = WCOLATU;
        BDREF = WREFATU;
        BDCODCONTTI = WCONTTIATU;
        BDREFPAG = WREFPAGTO;
        BDINSS = WINSSN + WINSSANTES;

        if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
          begin
            BDRENDTRIBUTAVEL = 0;
            BDIR = 0;
          end
        else
          begin
            BDRENDTRIBUTAVEL = WBASEIR;
            BDIR = WIR;
          end

        if ((WBASEIR + WINSSN + WIR > 0) or (PRVEIODOTOTALIZADOR > 0)) then
          BDDEP = WDEPATU;
        else
          BDDEP = 0;

        select first 1 BDCATEGORIAESOCIAL
        from VRHF_EMP_TCOLCON_FGTSGPS
        where BDCODEMP = :WEMPATU and
              BDCODCOL = :WCOLATU and
              BDREFCOL <= :WREFATU
        order by BDREFCOL desc
        into :WCATEGORIAESOCIAL;

        WPALANCMANUAL = null;
        if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WREF <> WREFATU)) then
          select sum(BDVALDIRF)
          from VRH_EMP_TVALBENEF_DIRF
          where BDCODEMP = :WEMPATU and
                BDCODCOL = :WCOLATU and
                BDANODIRF = :WREFPAGTO
          into :WPALANCMANUAL;

        if (WPALANCMANUAL is null) then
          WPALANCMANUAL = 0;

        BDLUCROPJ = WLUCROPJ;
        BDDESPMED = WDESPMED;
        BDAJCUSTOS = WAJCUS;
        if (WCATEGORIAESOCIAL = 903) then
        begin
          BDBOLSAESTUDOS = WBOLSAESTUDOS;
          if (coalesce(WDRENDIS2, '') <> '') then
          begin
            if (coalesce(WDRENDIS, '') <> '') then
              WDRENDIS = WDRENDIS || ',';

            if (PRVEIODOTOTALIZADOR = 1) then
              WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 999);
            else
              WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 200);
          end
        end
        else
        begin
          BDAJCUSTOS = BDAJCUSTOS + WBOLSAESTUDOS;
          if (coalesce(WDRENDIS3, '') <> '') then
          begin
            if (coalesce(WDRENDIS, '') <> '') then
              WDRENDIS = WDRENDIS || ',';

            if (PRVEIODOTOTALIZADOR = 1) then
              WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 999);
            else
              WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 200);
          end
        end
        BDPENJUD = WPENJUD;
        BDPENALIM = WPENALIM + WPALANCMANUAL;

        if (coalesce(:WPREVPRIVCAD, 0) > 0) then
        begin
          if (coalesce(:WPREPRI, 0) > 0) then
            BDPREVPRIV = WPREPRI;
          else
          if (coalesce(:WPREVPRIVCAD, 0) > 0) then
            BDPREVPRIV = WPREVPRIVCAD;
        end
        else
          BDPREVPRIV = 0;

        BDINDRESC = WINDRESC;
        BDVALABO = WVALABO;
        BDRENDISENTOS = WRENDIS;
        BDDRENDISENTOS = WDRENDIS;
        BDDATAPGTO = WDATAATU;
        BDDATAPROC = WDATAPROCA;
        BDHORAPROC = WHORAPROCA;

        if (WDATARESC is not null) then
        begin
          BDTIPO = 100; -- Folha normal rescisão
          BDINFADIC = substring(WCODPRES || ' - ' || WDESCPRES from 1 for 300);
        end
        else
        begin
          BDTIPO = 0; -- Folha normal
          BDINFADIC = '';
        end

        if (PRATUALIZAINFODESCSIMPLE = true) then
        begin
          WSQLAUXSIMPLI = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, ' || ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, ' || ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) ' || ' values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPAGTO || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';

          execute statement WSQLAUXSIMPLI;
        end

        BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
        BDAUXILIOMORADIA = WAUXILIOMORADIA;
        BDDIARIA = WDIARIA;
        BDBOLSAMEDICO = WBOLSAMEDICO;
        BDJUROSMORA = WJUROSMORA;
        BDINCIDESOCIAL = WINCIDESOCIAL;
        BDINCIDESOCIALFER = WINCIDESOCIALFER;
        suspend;
      end

      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;
      WEMPATU = WCODEMP;
      WCOLATU = WCODCOL;
      WREFATU = WREF;
      WCONTTIATU = WCODCONTTI;

      WBASEIR = 0;
      WINSSN = 0;
      WIR = 0;
      WDEPATU = 0;
      WDATAATU = null;
      WLUCROPJ = 0;
      WDESPMED = 0;
      WAJCUS = 0;
      WBOLSAESTUDOS = 0;
      WPENJUD = 0;
      WPENALIM = 0;
      WPREPRI = 0;
      WINDRESC = 0;
      WVALABO = 0;
      WRENDIS = 0;
      WDRENDIS = '';
      WGCLASS = '';
      WTIPODEDUCAOATU = WTIPODEDUCAO;
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
      WAUXILIOMORADIA = 0;
      WDIARIA = 0;
      WBOLSAMEDICO = 0;
      WJUROSMORA = 0;
      WINCIDESOCIAL = 0;
      WINCIDESOCIALFER = 0;
    end

    -- soma as bases
    WCODINCIDIRRF = 0;
    select first 1 BDTIPOCODVER, coalesce(BDIRVER, 0), BDRENDISENTOIRVER, BDINDRESC, BDCODINCIDIRRF
    from VRH_BASE_TVERBAS_REF
    where BDCODVER = :WCODVER and
          BDREFVER <= :WREFATU
    order by BDCODVER desc, BDREFVER desc
    into :WTIPOCODVER, :WIRVER, :WRENDISENTOVER, :WEHINDRESC, :WCODINCIDIRRF;

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end


    --    if (wtipocodver <= 1) then

    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
      begin
        WIRVER = 0;
      end
    else
      begin
        --    if (wtipocodver <= 1) then
        if (WIRVER = 1) then -- IR Folha normal
         begin
           if (WTIPOCODVER = 0) then -- provento
             WBASEIR = WBASEIR + WVALOR;
           else
           if (WTIPOCODVER = 1) then -- desconto
           begin
             --                                      INSS                                              Obrigações IR
             if (substring(WCLASSIF from 1 for 7) <> '9.010.0' and
                 substring(WCLASSIF from 1 for 5) <> '0.030') then
               WBASEIR = WBASEIR - WVALOR;
           end
         end

         --                                     IR folha normal
         if (substring(WCLASSIF from 1 for 9) = '9.010.1.0') then
           WIR = WIR + WVALOR;
      end

      --                                     INSS folha normal
      if (substring(WCLASSIF from 1 for 9) = '9.010.0.0') then
        WINSSN = WINSSN + WVALOR;
      --                                     Lucro pessoa jurídica
      if (substring(WCLASSIF from 1 for 9) = '0.040.0.2') then
        WLUCROPJ = WLUCROPJ + WVALOR;
      --                                     Despesas médicas                                     Complemento de despesas médicas
      if ((substring(WCLASSIF from 1 for 9) = '0.030.1.0') or (substring(WCLASSIF from 1 for 9) = '0.420.0.2') or (substring(WCLASSIF from 1 for 9) = '3.010.0.0')) then
        WDESPMED = WDESPMED + WVALOR;

      --                                     Ajuda de custos
      if (substring(WCLASSIF from 1 for 9) = '0.040.0.1' and
          WIRVER = 0) then
      begin
        select first 1 BDCHAVE
        from VRH_BASE_TRUBRICAESOCIAL_VER
        where BDCODVER = :WCODVER
        into :WRUBRICA;
        if (WRUBRICA = 1350) then -- Bolsa estudos
        begin
          WBOLSAESTUDOS = WBOLSAESTUDOS + WVALOR;
          if (WDRENDIS2 <> '') then
            WDRENDIS2 = WDRENDIS2 || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS2 = substring(WDRENDIS2 || 'BOLSA DE ESTUDOS' from 1 for 999);
          else
            WDRENDIS2 = substring(WDRENDIS2 || 'BOLSA DE ESTUDOS' from 1 for 200);

          if (WDRENDIS3 <> '') then
            WDRENDIS3 = WDRENDIS3 || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS3 = substring(WDRENDIS3 || WDESCVER2 from 1 for 999);
          else
            WDRENDIS3 = substring(WDRENDIS3 || WDESCVER2 from 1 for 200);
        end
        else
          WAJCUS = WAJCUS + WVALOR;
      end
      --                                     Pensões judiciais
      if (substring(WCLASSIF from 1 for 9) = '0.030.0.0') then
        WPENJUD = WPENJUD + WVALOR;
      --                                     Pensões alimentícias
      if (substring(WCLASSIF from 1 for 9) = '0.030.0.1') then
        WPENALIM = WPENALIM + WVALOR;
      --                                     Previdência privada
      if (substring(WCLASSIF from 1 for 9) = '0.030.1.2') then
        WPREPRI = WPREPRI + WVALOR;

      if (upper(WEHINDRESC) = 'TRUE') then
      begin
        if (WTIPOCODVER in (0, 2)) then -- Provento
          WINDRESC = WINDRESC + WVALOR;
        else
        if (WTIPOCODVER in (1, 3)) then -- Desconto
          WINDRESC = WINDRESC - WVALOR;
      end

      if (substring(WCLASSIF from 1 for 9) = '0.040.0.3') then
        WAUXILIOMORADIA = WAUXILIOMORADIA + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.040.0.0' and
          WIRVER = 0) then
        WDIARIA = WDIARIA + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.910.0.0') then
        WBOLSAMEDICO = WBOLSAMEDICO + WVALOR;

      if (substring(WCLASSIF from 1 for 9) = '0.920.0.0') then
        WJUROSMORA = WJUROSMORA + WVALOR;

      if (coalesce(WCODINCIDIRRF, 0) in (11, 12, 14, 41, 42, 51, 52, 54)) then
        WINCIDESOCIAL = 1;

      if (coalesce(WCODINCIDIRRF, 0) in (13, 43, 53)) then
        WINCIDESOCIALFER = 1;

      WISENTOABONO = 0;
      --                                      Complemento de abono pecuniário                  Compl. 1/3 abono pecuniário
      if ((substring(WCLASSIF from 1 for 7) = '0.210.2') or (substring(WCLASSIF from 1 for 7) = '0.210.3')) then
      begin
        WVALABO = WVALABO + WVALOR;
      end
      else

      -- Rendimentos isentos
      if ((upper(WRENDISENTOVER) = 'TRUE') and
          (WISENTOABONO = 0)) then
      begin
        WRENDIS = WRENDIS + WVALOR;

        WI = 0;

        if (PRVEIODOTOTALIZADOR = 1) then
          select POS
          from POS(:WCLASSIF, :WGCLASS)
          into :WI;
        else
          select POS
          from POS(substring(:WCLASSIF from 1 for 5), :WGCLASS)
          into :WI;

        if (WI = 0) then
        begin
          WDESCVER2 = '';

          if (PRVEIODOTOTALIZADOR = 1) then
          begin
            select first 1 BDDESCVER
            from VRH_BASE_TVERBAS
            where BDCLAVER = :WCLASSIF
            into WDESCVER2;
            WGCLASS = WGCLASS || ';' || :WCLASSIF;
          end
          else
          begin
            select first 1 BDDESCVER
            from VRH_BASE_TVERBAS
            where BDCLAVER = substring(:WCLASSIF from 1 for 5)
            into WDESCVER2;
            WGCLASS = WGCLASS || ';' || substring(:WCLASSIF from 1 for 5);
          end

          if (WDRENDIS <> '') then
            WDRENDIS = WDRENDIS || ', ';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS = substring(WDRENDIS || WDESCVER2 from 1 for 999);
          else
            WDRENDIS = substring(WDRENDIS || WDESCVER2 from 1 for 200);
        end
      end
    end

    WDEPATU = WDEP;
    WDATAATU = WDATAPGTO;
    WDATAPROCA = WDATAPROC;
    WHORAPROCA = WHORAPROC;


  if (WEMPATU <> 0 and
      WCOLATU <> 0 and
      WREFATU <> 0 and
      WCONTTIATU <> 0) then
  begin
    WCODPRES = null;
    WDESCPRES = null;
    WDATARESC = null;
    WDATAPAGRESC = null;
    WTIPOMOV = 0;

    if (PRPREVIARESC = 1) then
    begin
      select X.BDDATARESCISAOPREV, X.BDDATAPAGRESCISAOPREV, X.BDCODPRES, Y.BDDESCPRES, coalesce(Y.BDTIPOMOV, 0)
      from VRH_EMP_TRESCISAO_PREVIA X
      join VRH_BASE_TPREPRESC Y on (Y.BDCODPRES = X.BDCODPRES)
      where X.BDCODEMP = :WEMPATU and
            X.BDCODCOL = :WCOLATU and
            X.BDREFRESCISAOPREV = :WREFATU
      into :WDATARESC, :WDATAPAGRESC, :WCODPRES, :WDESCPRES, :WTIPOMOV;
    end
    else
    begin
      select X.BDDATARESCISAO, X.BDDATAPAGRESCISAO, X.BDCODPRES, Y.BDDESCPRES, coalesce(Y.BDTIPOMOV, 0)
      from VRH_EMP_TRESCISAO X
      join VRH_BASE_TPREPRESC Y on (Y.BDCODPRES = X.BDCODPRES)
      where X.BDCODEMP = :WEMPATU and
            X.BDCODCOL = :WCOLATU and
            X.BDREFRESCISAO = :WREFATU
      into :WDATARESC, :WDATAPAGRESC, :WCODPRES, :WDESCPRES, :WTIPOMOV;
    end

    if ((WTIPOMOV < 1) and
        ((WDATAPAGRESC is not null) or (WDATARESC is not null))) then
    begin
      if (WDATAPAGRESC is not null) then
      begin
        WDATAATU = WDATAPAGRESC;
      end
      else
      begin
        WDATAATU = WDATARESC;
      end
    end

    WREFPAGTO = cast((substring(cast(WDATAATU as varchar(10)) from 1 for 4) || substring(cast(WDATAATU as varchar(10)) from 6 for 2)) as integer);

    if (WREFPAGTO >= PRREFINI and
        WREFPAGTO <= PRREFFIM) then
    begin
      WPREVPRIVCAD = 0;
      select sum(coalesce(LANPREV.BDVALMENSAL, 0))
      from VRH_EMP_TLANCPREVCOMP LANPREV join(select BDCODCADPREV
                                              from VRH_BASE_TCADPREVCOMP
                                              where BDNATPREV <> 2) CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV) /* 184717 Leonardo Schwab 16/11/2023 */
      where LANPREV.BDCODEMP = :WEMPATU and
            LANPREV.BDCODCOL = :WCOLATU and
            LANPREV.BDREFINI <= :WREFATU and
            ((coalesce(LANPREV.BDREFFIN, 0) = 0) or (coalesce(LANPREV.BDREFFIN, 0) >= :WREFATU))
      into :WPREVPRIVCAD;
      WPREVPRIVCAD = coalesce(WPREVPRIVCAD, 0);

      WINSSANTES = null;
      if (coalesce(PRINSSANTES, 0) = 1 and
          WREFPAGTO <> WREFATU) then
      begin
        select sum(BDINSSFN)
        from VRHF_EMP_TFOLHAINT
        where BDCODEMP = :WEMPATU and
              BDCODCOL = :WCOLATU and
              BDREFFN = :WREFATU and
              BDDATAPGTOFN < :WDATAATU and
              BDCODCONTTI <> :WCONTTIATU
        into :WINSSANTES;
      end

      if (WINSSANTES is null) then
        WINSSANTES = 0;

      select first 1 BDCATEGORIAESOCIAL
      from VRHF_EMP_TCOLCON_FGTSGPS
      where BDCODEMP = :WEMPATU and
            BDCODCOL = :WCOLATU and
            BDREFCOL <= :WREFATU
      order by BDREFCOL desc
      into :WCATEGORIAESOCIAL;

      BDREFIRRFESOCIAL = WREFIRRFESOCIALATU;
      BDCODEMP = WEMPATU;
      BDCODCOL = WCOLATU;
      BDREF = WREFATU;
      BDCODCONTTI = WCONTTIATU;
      BDREFPAG = WREFPAGTO;
      BDRENDTRIBUTAVEL = WBASEIR;
      BDINSS = WINSSN + WINSSANTES;
      BDIR = WIR;

      if ((WBASEIR + WINSSN + WIR > 0) or (PRVEIODOTOTALIZADOR > 0)) then
        BDDEP = WDEPATU;
      else
        BDDEP = 0;

      WPALANCMANUAL = null;
      if ((WCODEMP <> WEMPATU) or (WCODCOL <> WCOLATU) or (WREF <> WREFATU)) then
        select sum(BDVALDIRF)
        from VRH_EMP_TVALBENEF_DIRF
        where BDCODEMP = :WEMPATU and
              BDCODCOL = :WCOLATU and
              BDANODIRF = :WREFPAGTO
        into :WPALANCMANUAL;

      if (WPALANCMANUAL is null) then
        WPALANCMANUAL = 0;

      BDLUCROPJ = WLUCROPJ;
      BDDESPMED = WDESPMED;
      BDAJCUSTOS = WAJCUS;
      if (WCATEGORIAESOCIAL = 903) then
      begin
        BDBOLSAESTUDOS = WBOLSAESTUDOS;
        if (coalesce(WDRENDIS2, '') <> '') then
        begin
          if (coalesce(WDRENDIS, '') <> '') then
            WDRENDIS = WDRENDIS || ',';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 999);
          else
            WDRENDIS = substring(WDRENDIS || WDRENDIS2 from 1 for 200);
        end
      end
      else
      begin
        BDAJCUSTOS = BDAJCUSTOS + WBOLSAESTUDOS;
        if (coalesce(WDRENDIS3, '') <> '') then
        begin
          if (coalesce(WDRENDIS, '') <> '') then
            WDRENDIS = WDRENDIS || ',';

          if (PRVEIODOTOTALIZADOR = 1) then
            WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 999);
          else
            WDRENDIS = substring(WDRENDIS || WDRENDIS3 from 1 for 200);
        end
      end
      BDPENJUD = WPENJUD;
      BDPENALIM = WPENALIM + WPALANCMANUAL;

      if (coalesce(:WPREVPRIVCAD, 0) > 0) then
      begin
        if (coalesce(:WPREPRI, 0) > 0) then
          BDPREVPRIV = WPREPRI;
        else
        if (coalesce(:WPREVPRIVCAD, 0) > 0) then
          BDPREVPRIV = WPREVPRIVCAD;
      end
      else
        BDPREVPRIV = 0;

      BDINDRESC = WINDRESC;
      BDVALABO = WVALABO;
      BDRENDISENTOS = WRENDIS;
      BDDRENDISENTOS = WDRENDIS;
      BDDATAPGTO = WDATAATU;
      BDDATAPROC = WDATAPROCA;
      BDHORAPROC = WHORAPROCA;

      if (WDATARESC is not null) then
      begin
        BDTIPO = 100; -- Folha normal rescisão
        BDINFADIC = substring(WCODPRES || ' - ' || WDESCPRES from 1 for 300);
      end
      else
      begin
        BDTIPO = 0; -- Folha normal
        BDINFADIC = '';
      end

      if (PRATUALIZAINFODESCSIMPLE = true) then
      begin
        WSQLAUXSIMPLI = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, ' || ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, ' || ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) ' || ' values (' || current_connection || ', ' || WEMPATU || ', ' || WCOLATU || ', ' || WREFPAGTO || ', 0, ' || coalesce(BDPENALIM, 0) || ', ' || coalesce(BDDEP, 0) || ', ' || coalesce(BDPREVPRIV, 0) || ', ' || coalesce(BDINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(BDRENDTRIBUTAVEL, 0) || ')';

        execute statement WSQLAUXSIMPLI;
      end

      BDVALORDESCONTOSIMPLIFICADO = WVALORDESCSIMPLATU;
      BDAUXILIOMORADIA = WAUXILIOMORADIA;
      BDDIARIA = WDIARIA;
      BDBOLSAMEDICO = WBOLSAMEDICO;
      BDJUROSMORA = WJUROSMORA;
      BDINCIDESOCIAL = WINCIDESOCIAL;
      BDINCIDESOCIALFER = WINCIDESOCIALFER;
      suspend;
    end
  end

  /*
      FOLHA TOMADOR
  */
  for select BDREFIRRFESOCIAL, BDCODEMP, BDCODCOL, BDREF, BDREFPAG, BDTIPO, BDRENDTRIBUTAVEL, BDINSS, BDIR, BDDEP,
             BDLUCROPJ, BDDESPMED, BDAJCUSTOS, BDPENJUD, BDPENALIM, BDPREVPRIV, BDINDRESC, BDVALABO, BDRENDISENTOS,
             BDDRENDISENTOS, BDDATAPGTO, BDINFADIC, BDDATAPROC, BDHORAPROC, BDORDEM, BDCODCONTTI, BDBOLSAESTUDOS,
             BDVALORDESCONTOSIMPLIFICADO, BDAUXILIOMORADIA, BDDIARIA, BDBOLSAMEDICO, BDJUROSMORA, BDINCIDESOCIAL,
             BDINCIDESOCIALFER, BDCODTIPO
      from SP_VRHF_DADOS_IR_INTFT(:PRCODEMP, :PRCODCOL, :PRREFINI, :PRREFFIM, :PRPUXARFILIAIS, :PRCODMATRIZ, :PRPREVIARESC, :PRPORCC, :PRINSSANTES, :PRIRRFESOCIAL, :PRATUALIZAINFODESCSIMPLE, :PRVEIODOTOTALIZADOR)
      into :BDREFIRRFESOCIAL, :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR,
           :BDDEP, :BDLUCROPJ, :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM, :BDPREVPRIV, :BDINDRESC, :BDVALABO,
           :BDRENDISENTOS, :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDDATAPROC, :BDHORAPROC, :BDORDEM, :BDCODCONTTI,
           :BDBOLSAESTUDOS, :BDVALORDESCONTOSIMPLIFICADO, :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA,
           :BDINCIDESOCIAL, :BDINCIDESOCIALFER, :BDCODTIPO
  do
  begin
    suspend;
  end
end^

/* Restore proc. body: SP_VRHF_DADOS_IR_FICHA_INT13 */
create or alter procedure SP_VRHF_DADOS_IR_FICHA_INT13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRATUALIZAINFODESCSIMPLE boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WSQL varchar(32700);
declare variable WSQLAUX varchar(5000);
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WCATEGORIACOL integer;
declare variable WCATEGORIAESOCIAL integer;
declare variable WSQLAUXSIMPLI varchar(3000);
declare variable WREFPGTOAUX integer;
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
BEGIN
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  IF (UPPER(prcodcol) = 'TEMP_FILTRO_COLCON_REL') THEN
     WUSARTMP_COL_SELECT = 1;

  /*  DADOS IMPORTADOS OU CADASTRADOS NA FICHA  */
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0) BDBASEIRFIR,COALESCE(FOL.BDVALINSSFIR,0) BDVALINSSFIR,COALESCE(FOL.BDVALIRFIR,0) BDVALIRFIR,COALESCE(FOL.BDVALDEPFIR,0) BDVALDEPFIR,COALESCE(FOL.BDDISTRLUCROFIR,0) BDDISTRLUCROFIR,'||
              'COALESCE(FOL.BDDESPMEDFIR,0) BDDESPMEDFIR,COALESCE(FOL.BDAJUDACUSTOFIR,0) BDAJUDACUSTOFIR,COALESCE(FOL.BDDESPJUDFIR,0) BDDESPJUDFIR,COALESCE(FOL.BDPENALIMFIR,0) BDPENALIMFIR,COALESCE(FOL.BDPREVPRIVFIR,0) BDPREVPRIVFIR,COALESCE(FOL.BDVALINDFIR,0) BDVALINDFIR,COALESCE(FOL.BDVALABOFIR,0) BDVALABOFIR,COALESCE(FOL.BDRENDISENTOSFIR,0) BDRENDISENTOSFIR,FOL.BDDESCRENDISENTOSFIR,'||
              'FOL.BDDATAFIR, '''||''' BDAUX, fol.BDVALORDESCONTOSIMPLIFICADO, COALESCE(fol.BDAUXILIOMORADIAFIR,0) BDAUXILIOMORADIAFIR, COALESCE(fol.BDDIARIAFIR,0) BDDIARIAFIR, COALESCE(fol.BDBOLSAMEDICOFIR,0) BDBOLSAMEDICOFIR, COALESCE(fol.BDJUROSMORAFIR,0) BDJUROSMORAFIR, fol.BDCODFIR, FOL.BDDEMDEV, COALESCE(FOL.BDCODTIPO, 201) BDCODTIPO,'||
              'VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

       wsql = wsql||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOL.BDCODEMP) and (HIST.BDCODCOL = FOL.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOL.BDCODEMP) and (VINC.BDCODCOL = FOL.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL  '||
                    '                                     AND X.BDREFCOL <= FOL.BDREFIRFIR ORDER BY X.BDREFCOL DESC) '||
                    '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL)) ';

       wsql = wsql||'where FOL.BDTIPOCALCFIR in (9002,9012,9099,9100) and FOL.BDREFIRFIR >= '||prrefini||' and FOL.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select S13.BDCODEMP,S13.BDCODCOL,S13.BDREF13 from VRHF_EMP_T13SAL S13 where S13.BDCODEMP = FOL.BDCODEMP and S13.BDCODCOL = FOL.BDCODCOL and '||
                                'S13.BDREF13 = FOL.BDREFFIR) and '||
                    'not exists (select A13.BDCODEMP,A13.BDCODCOL,A13.BDREFA13 from VRHF_EMP_TA13SAL A13 where A13.BDCODEMP = FOL.BDCODEMP and A13.BDCODCOL = FOL.BDCODCOL and '||
                                'A13.BDREFA13 = FOL.BDREFFIR) ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
       IF (prcodcol IS NOT NULL AND prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
          wsql = wsql||' and '||prcodcol;
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDDATAFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0) BDBASEIRFIR,COALESCE(FO.BDVALINSSFIR,0) BDVALINSSFIR,COALESCE(FO.BDVALIRFIR,0) BDVALIRFIR,COALESCE(FO.BDVALDEPFIR,0) BDVALDEPFIR,COALESCE(FO.BDDISTRLUCROFIR,0) BDDISTRLUCROFIR,'||
              'COALESCE(FO.BDDESPMEDFIR,0) BDDESPMEDFIR,COALESCE(FO.BDAJUDACUSTOFIR,0) BDAJUDACUSTOFIR,COALESCE(FO.BDDESPJUDFIR,0) BDDESPJUDFIR,COALESCE(FO.BDPENALIMFIR,0) BDPENALIMFIR,COALESCE(FO.BDPREVPRIVFIR,0) BDPREVPRIVFIR,COALESCE(FO.BDVALINDFIR,0) BDVALINDFIR,COALESCE(FO.BDVALABOFIR,0) BDVALABOFIR,COALESCE(FO.BDRENDISENTOSFIR,0) BDRENDISENTOSFIR,FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX, fo.BDVALORDESCONTOSIMPLIFICADO, COALESCE(fo.BDAUXILIOMORADIAFIR,0) BDAUXILIOMORADIAFIR, COALESCE(fo.BDDIARIAFIR,0) BDDIARIAFIR, COALESCE(fo.BDBOLSAMEDICOFIR,0) BDBOLSAMEDICOFIR, COALESCE(fo.BDJUROSMORAFIR,0) BDJUROSMORAFIR, fo.BDCODFIR, FO.BDDEMDEV, COALESCE(FO.BDCODTIPO,201) BDCODTIPO,'||
              'VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';

       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FO join TEMPRESAS EMAT on (EMAT.BDCODEMP = FO.BDCODEMP) ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wsql = wsql||'inner join tmp_empresas_select TEMP on (TEMP.BDCODEMP = FO.BDCODEMP) ';
       ELSE
       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FO.BDCODEMP and TEM.BDCODCOL = FO.BDCODCOL) ';

       wsql = wsql||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FO.BDCODEMP) and (HIST.BDCODCOL = FO.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FO.BDCODEMP) and (VINC.BDCODCOL = FO.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL  '||
                    '                                     AND X.BDREFCOL <= FO.BDREFIRFIR ORDER BY X.BDREFCOL DESC) '||
                    '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL)) ';

       wsql = wsql||'where FO.BDTIPOCALCFIR in (9002,9012,9099,9100) and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    'not exists (select S13.BDCODEMP,S13.BDCODCOL,S13.BDREF13 from VRHF_EMP_T13SAL S13 where S13.BDCODEMP = FO.BDCODEMP and S13.BDCODCOL = FO.BDCODCOL and '||
                                'S13.BDREF13 = FO.BDREFFIR) and '||
                    'not exists (select A13.BDCODEMP,A13.BDCODCOL,A13.BDREFA13 from VRHF_EMP_TA13SAL A13 where A13.BDCODEMP = FO.BDCODEMP and A13.BDCODCOL = FO.BDCODCOL and '||
                                'A13.BDREFA13 = FO.BDREFFIR) ';
     
       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||REPLACE(UPPER(prcodemp), 'FOL.', 'FO.')||')';
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||REPLACE(UPPER(prcodmatriz), 'FOL.', 'EMAT.')||')';
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
          wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'FOL.', 'FO.')||' ';
       wsql = wsql||' order by FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDDATAFIR ';
     END

  --#Alt:95293. Incluído controle para colaborador que seja intermitente.
  wSQLAux = 'Select FOL.*, COALESCE(CATEGORIAS.BDCATEGORIACOL,0) BDCATEGORIACOL, COALESCE(CATEGORIAS.BDCATEGORIAESOCIAL,0) BDCATEGORIAESOCIAL ';
  wSQLAux = wSQLAux||'from ('||wSQL||') FOL ';
  wSQLAux = wSQLAux||'left outer join VRHF_EMP_TCOLCON_FGTSGPS CATEGORIAS on (CATEGORIAS.BDCODEMP = FOL.BDCODEMP and ';
  wSQLAux = wSQLAux||'                                                        CATEGORIAS.BDCODCOL = FOL.BDCODCOL and ';
  wSQLAux = wSQLAux||'                                                        CATEGORIAS.BDREFCOL = (SELECT COALESCE(MAX(X.BDREFCOL),0) BDREFCOL FROM VRHF_EMP_TCOLCON_FGTSGPS X ';
  wSQLAux = wSQLAux||'                                                                               WHERE ';
  wSQLAux = wSQLAux||'                                                                               (X.BDCODEMP = FOL.BDCODEMP) AND';
  wSQLAux = wSQLAux||'                                                                               (X.BDCODCOL = FOL.BDCODCOL) AND';
  wSQLAux = wSQLAux||'                                                                               (X.BDREFCOL <= (SELECT TRIM(rdb$get_context('||''''||'USER_SESSION'||''''||', '||''''||'W_ANOMES'||''''||')) BDREF FROM rdb$database))))';

  BDORDEM = null;

  FOR EXECUTE STATEMENT wSQLAux INTO :BDCODEMP,:BDCODCOL,:BDREF,:BDREFPAG,:BDTIPO,:BDRENDTRIBUTAVEL,:BDINSS,:BDIR,:BDDEP,:BDLUCROPJ,:BDDESPMED,:BDAJCUSTOS,:BDPENJUD,:BDPENALIM,
                                     :BDPREVPRIV,:BDINDRESC,:BDVALABO,:BDRENDISENTOS,:BDDRENDISENTOS,:BDDATAPGTO,:BDINFADIC,:BDVALORDESCONTOSIMPLIFICADO,
                                     :BDAUXILIOMORADIA,:BDDIARIA,:BDBOLSAMEDICO,:BDJUROSMORA,:BDCODFIR,:BDDEMDEV,:BDCODTIPO,
                                     :wcodcla, :wtributacaoexterior, :WCATEGORIACOL,:WCATEGORIAESOCIAL
  DO
  BEGIN
    BDDATAPROC = BDDATAPGTO;
    BDHORAPROC = '00:00:00';
    BDCODCONTTI = null;

    bdrefirrfesocial = bdrefpag;


    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
      begin
        BDRENDTRIBUTAVEl = 0;
        BDIR = 0;
      end

    if (pratualizainfodescsimple = TRUE) then
      begin
        wrefpgtoaux = CAST((SUBSTRING(bdrefpag FROM 1 FOR 4)||'13')AS INTEGER);
        wsqlauxsimpli = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, '||
                        ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, '||
                        ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) '||
                        ' values ('||current_connection||', '||bdcodemp||', '||bdcodcol||', '||wrefpgtoaux||', 0, '||coalesce(bdpenalim, 0)||', '||coalesce(bddep, 0)||', '||coalesce(bdprevpriv, 0)||', '||coalesce(bdinss, 0)||', '||coalesce(bdvalordescontosimplificado, 0)||', FALSE, '||coalesce(bdrendtributavel, 0)||')';
    
        execute statement wsqlauxsimpli;
      end

    if (COALESCE(BDRENDTRIBUTAVEL, 0) <> 0) then
       BDINCIDESOCIAL = 1;

    --#Alt:95293. Incluído controle para colaborador que seja intermitente.
    if ((wcategoriacol = 4) and (wcategoriaesocial = 111)) then
       SUSPEND;
  END

END^

/* Restore proc. body: SP_VRHF_DADOS_IR_INTFT13 */
create or alter procedure SP_VRHF_DADOS_IR_INTFT13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRINSSANTES smallint = 1,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0,
    PRPORCC smallint = 1)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR13 numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WINSS13 numeric(18,6);
declare variable WIR13 numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WREFINI integer;
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WDATAPGTO date;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WPREVPRIVCAD numeric(18,6);
declare variable WEXISTE13MES integer;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WCODCONTTI integer;
declare variable WCONTTIATU integer;
declare variable WINSS13ANTES numeric(18,6);
declare variable WTIPODEDUCAO integer;
declare variable WVALORDESCSIMPL numeric(18,2);
declare variable WVALORDIFDESCSIMPL numeric(18,2);
declare variable WSQLAUXSIMPLI varchar(3000);
declare variable WTIPODEDUCAOATU integer;
declare variable WVALORDESCSIMPLATU numeric(18,2);
declare variable WVALORDIFDESCSIMPLATU numeric(18,2);
declare variable WREFPGTOAUX integer;
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
BEGIN
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  IF (UPPER(prcodcol) = 'TEMP_FILTRO_COLCON_REL') THEN
     WUSARTMP_COL_SELECT = 1;

  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) = 1) THEN
     wrefini = CAST((CAST((CAST(SUBSTRING(prrefini FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
  ELSE
  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) <= 10) THEN
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1))) AS INTEGER);
  ELSE
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2))) AS INTEGER);

  /*  13º FOLHA TOMADOR  */
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDCODCONTTI,FOL.BDCODVER,FOL.BDVALVFT,FOLN.BDDEPFT,VER.BDCLAVER,FOLN.BDDATAIRRFESOCIAL AS BDDATAPROCFT,FOLN.BDHORAPROCFT,FOLN.BDDATAPGTOFT, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
       ELSE
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDORDEM,FOL.BDCODCONTTI,FOL.BDCODVER,FOL.BDVALVFT,FOLN.BDDEPFT,VER.BDCLAVER,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT,FOLN.BDDATAPGTOFT, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';

       wsql = wsql||'from VRHF_EMP_TFOLHATOMINT FOLN ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'INNER JOIN tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FOLN.BDCODEMP) ';
       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'inner join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP and TEMP.BDCODCOL = FOLN.BDCODCOL) ';


       wsql = wsql||'join VRHF_EMP_TVERBATOMINT FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDREFTOMADOR = FOLN.BDREFTOMADOR and FOL.BDORDEM = FOLN.BDORDEM and FOL.BDCODCONTTI = FOLN.BDCODCONTTI) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
       wsql = wsql||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                    '                                     AND X.BDREFCOL <= FOLN.BDREFTOMADOR ORDER BY X.BDREFCOL DESC) '||
                    '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

       IF (PRIRRFESOCIAL = TRUE) THEN
          wsql = wsql||'where COALESCE(COL.BDCONTRCOL,0) <> 1 and FOLN.BDREFIRRFESOCIAL between '||wrefini||' and '||prreffim;
       ELSE
          wsql = wsql||'where COALESCE(COL.BDCONTRCOL,0) <> 1 and FOLN.BDREFTOMADOR between '||wrefini||' and '||prreffim;

       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
       IF (prcodcol IS NOT NULL AND prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
          wsql = wsql||' and '||prcodcol;
       wsql = wsql||' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDCODCONTTI ';
     END
  ELSE
     BEGIN
       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDCODCONTTI,FO.BDCODVER,FO.BDVALVFT,FOLN.BDDEPFT,VER.BDCLAVER,FOLN.BDDATAIRRFESOCIAL AS BDDATAPROCFT,FOLN.BDHORAPROCFT,FOLN.BDDATAPGTOFT, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
       ELSE
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDCODCONTTI,FO.BDCODVER,FO.BDVALVFT,FOLN.BDDEPFT,VER.BDCLAVER,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT,FOLN.BDDATAPGTOFT, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';

       wsql = wsql||'from VRHF_EMP_TFOLHATOMINT FOLN join TEMPRESAS EMAT on (EMAT.BDCODEMP = FOLN.BDCODEMP) ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'inner join TMP_EMPRESAS_SELECT TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP) ';
       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'inner join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FOLN.BDCODEMP and TEM.BDCODCOL = FOLN.BDCODCOL) ';

       wsql = wsql||'join VRHF_EMP_TVERBATOMINT FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDREFTOMADOR = FOLN.BDREFTOMADOR and FO.BDORDEM = FOLN.BDORDEM and FO.BDCODCONTTI = FOLN.BDCODCONTTI) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FO.BDCODEMP and COL.BDCODCOL = FO.BDCODCOL) ';
       wsql = wsql||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                    '                                     AND X.BDREFCOL <= FOLN.BDREFTOMADOR ORDER BY X.BDREFCOL DESC) '||
                    '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

       IF (PRIRRFESOCIAL = TRUE) THEN
          wsql = wsql||'where COALESCE(COL.BDCONTRCOL,0) <> 1 and FOLN.BDREFIRRFESOCIAL between '||wrefini||' and '||prreffim;
       ELSE
          wsql = wsql||'where COALESCE(COL.BDCONTRCOL,0) <> 1 and FOLN.BDREFTOMADOR between '||wrefini||' and '||prreffim;

       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||REPLACE(UPPER(prcodemp), 'FOL.', 'FOLN.')||')';
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||REPLACE(UPPER(prcodmatriz), 'FOL.', 'EMAT.')||')';
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
          wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'FOL.', 'FOLN.')||' ';
       wsql = wsql||' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFTOMADOR,FOLN.BDORDEM,FOLN.BDCODCONTTI ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wordematu  = 0;
  wconttiatu = 0;
  wbaseir13  = 0;
  winss13    = 0;
  wir13      = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wprepri    = 0;
  wdataproca = NULL;
  whoraproca = NULL;
  wtipodeducao = 0;
  wvalordescsimpl = 0;
  wvalordifdescsimpl = 0;
  wtipodeducaoatu = 0;
  wvalordescsimplatu = 0;
  wvalordifdescsimplatu = 0;
  WBOLSAMEDICO = 0;
  WINCIDESOCIAL = 0;
  wrefirrfesocialatu = -1;
  BDINDRESC = 0;
  BDCODFIR = 0;
  BDDEMDEV = null;

  FOR EXECUTE STATEMENT wsql INTO :wrefirrfesocial,:wcodemp,:wcodcol,:wref,:wordem,:wcodcontti,:wcodver,:wvalor,:wdep,:wclassif,:wdataproc,:whoraproc,:wdatapgto,:wtipodeducao,:wvalordescsimpl,:wvalordifdescsimpl, :wcodcla, :wtributacaoexterior DO
  BEGIN
    BDCODTIPO = 272;    -- Cálculos gerados pelo Único Folha

    IF (wempatu = 0) THEN
       wempatu = wcodemp;
    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;
    IF (wrefatu = 0) THEN
       wrefatu = wref;

    if (wrefirrfesocialatu = -1) then wrefirrfesocialatu = wrefirrfesocial;

    if (PRPORCC = 0) then
       WORDEMATU = coalesce(WORDEM, 0);
    else
    IF (wordematu = 0) THEN
       wordematu = wordem;

    IF (wconttiatu = 0) THEN
       wconttiatu = wcodcontti;

    if (wvalordescsimplatu = 0) then
      wvalordescsimplatu = wvalordescsimpl;
    if (wvalordifdescsimplatu = 0) then
      wvalordifdescsimplatu = wvalordifdescsimpl;
    if (wtipodeducaoatu = 0) then
      wtipodeducaoatu = wtipodeducao;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wordem <> wordematu) OR (wcodcontti <> wconttiatu)) THEN
       BEGIN
         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              wprevprivcad = 0;
              select first 1 COALESCE(LANPREV.BDVAL13SAL,0) from VRH_EMP_TLANCPREVCOMP LANPREV
              join VRH_BASE_TCADPREVCOMP CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV and CADPREV.BDNATPREV <> 2)   /* 184717 Leonardo Schwab 16/11/2023 */
              where LANPREV.BDCODEMP = :wempatu and LANPREV.BDCODCOL = :wcolatu and LANPREV.BDREFINI <= :wrefatu
              and ((COALESCE(LANPREV.BDREFFIN, 0) = 0) or (COALESCE(LANPREV.BDREFFIN, 0) >= :wrefatu)) and COALESCE(LANPREV.BDVAL13SAL,0) > 0
              order by LANPREV.BDCODEMP desc, LANPREV.BDCODCOL desc, LANPREV.BDREFINI DESC
              INTO :wprevprivcad;
              wprevprivcad = coalesce(wprevprivcad, 0);
              winss13antes = null;
              if (coalesce(prinssantes, 0) = 1 and wrefpagto <> wrefatu) then
                 begin
                   select SUM(BDINSS13FT) from VRHF_EMP_TFOLHATOMINT where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFIRRFESOCIAL = :wrefpagto and bdordem = :wordematu and BDDATAPGTOFT < :wdataatu and BDCODCONTTI <> :wconttiatu
                   into :winss13antes;
                 end
   
              if (winss13antes is null) then
                 winss13antes = 0;

              winss13 = winss13 + winss13antes;

              if (wbaseir13 < 0) then
                 wbaseir13 = 0;

              if (winss13 < 0) then
                 winss13 = 0;

              if ((wbaseir13 <> 0) or (winss13 <> 0) or (wir13 <> 0) or (wprevprivcad <> 0)) then
                 begin
                   /*Se tiver 13º no mês da rescisão não deve considerar o dependente novamente*/
                   wexiste13mes = NULL;
                   select dt.bdcodemp from vrhf_emp_t13sal dt where dt.bdcodemp = :wempatu and dt.bdcodcol = :wcolatu and dt.bdref13 = :wrefpagto
                   INTO :wexiste13mes;
                   IF (wexiste13mes IS NOT NULL) THEN
                      wdepatu = 0;
          
                   BDrefirrfesocial = wrefirrfesocialatu;
                   BDCODEMP         = wempatu;
                   BDCODCOL         = wcolatu;
                   BDREF            = wrefatu;
                   BDREFPAG         = wrefpagto;
                   bdordem          = wordematu;
                   BDCODCONTTI      = wconttiatu;
                   BDRENDTRIBUTAVEL = wbaseir13;
                   BDINSS           = winss13;
                   BDIR             = wir13;
                   BDDEP            = wdepatu;
                   BDLUCROPJ        = 0;
                   BDDESPMED        = 0;
                   BDAJCUSTOS       = 0;
                   BDPENJUD         = 0;
                   BDPENALIM        = 0;

                   if (wprepri <> 0) then
                      BDPREVPRIV = wprepri;
                   else
                      BDPREVPRIV = wprevprivcad;

                   BDBOLSAMEDICO    = WBOLSAMEDICO;
                   BDINCIDESOCIAL = WINCIDESOCIAL;
                   BDAUXILIOMORADIA = 0;
                   BDDIARIA = 0;
                   BDJUROSMORA = 0;
                   BDVALABO         = 0;
                   BDRENDISENTOS    = 0;
                   BDDRENDISENTOS   = '';
                   BDDATAPGTO       = wdataatu;
                   BDTIPO           = 10;    -- 13º rescisão
                   BDINFADIC        = '';
                   BDDATAPROC       = wdataproca;
                   BDHORAPROC       = whoraproca;

                   if (pratualizainfodescsimple = TRUE) then
                     begin
                       wrefpgtoaux = CAST((SUBSTRING(wrefpagto FROM 1 FOR 4)||'13')AS INTEGER);
                       wsqlauxsimpli = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, '||
                                       ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, '||
                                       ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) '||
                                       ' values ('||current_connection||', '||wempatu||', '||wcolatu||', '||wrefpgtoaux||', 0, '||coalesce(bdpenalim, 0)||', '||coalesce(bddep, 0)||', '||coalesce(bdprevpriv, 0)||', '||coalesce(bdinss, 0)||', '||coalesce(wvalordescsimplatu, 0)||', FALSE, '||coalesce(bdrendtributavel, 0)||')';
               
                       execute statement wsqlauxsimpli;
                     end

                   BDVALORDESCONTOSIMPLIFICADO = wvalordescsimplatu;
                   SUSPEND;
                 end
            END

         wrefirrfesocialatu = wrefirrfesocial;
         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wrefatu    = wref;
         wordematu  = wordem;
         wconttiatu = wcodcontti;
         wbaseir13  = 0;
         winss13    = 0;
         wir13      = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wprepri    = 0;
         wtipodeducaoatu = wtipodeducao;
         wvalordescsimplatu = wvalordescsimpl;
         wvalordifdescsimplatu = wvalordifdescsimpl;
         WBOLSAMEDICO = 0;
         WINCIDESOCIAL = 0;
       END

    WCODINCIDIRRF = 0;
    SELECT first 1 BDTIPOCODVER, BDIRVER, BDCODINCIDIRRF
    FROM vrh_base_tverbas_ref
    WHERE BDCODVER = :wcodver and BDREFVER <= :wref
    order by BDCODVER desc, BDREFVER desc
    INTO :wtipocodver,:wirver, :WCODINCIDIRRF;

    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
       begin
          wirver = 0;
       end
    else
--    if (wtipocodver <= 1) then
       begin
         IF (wirver = 3) THEN -- 13º salário
            BEGIN
              IF (wtipocodver = 0) THEN   -- provento
                 wbaseir13 = wbaseir13 + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN   -- desconto
                 BEGIN
                   --                                      INSS                                              Obrigações IR
                   IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                      wbaseir13 = wbaseir13 - wvalor;
                 END
            END

             --                                     IR 13º salário rescisão
             IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.A') THEN
                wir13 = wir13 + wvalor;
        end

         --                                     INSS 13º salário rescisão
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.6') THEN
            winss13 = winss13 + wvalor;

         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '5.520.0.0') THEN
            WBOLSAMEDICO = WBOLSAMEDICO + WVALOR;
         --
         if (COALESCE(WCODINCIDIRRF, 0) IN (11,12,13,14,41,42,43,51,52,53,54)) then
            WINCIDESOCIAL = 1;

    wdepatu = wdep;
    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wordematu <> 0 and wconttiatu <> 0) THEN
     BEGIN
       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            wprevprivcad = 0;
            select first 1 COALESCE(LANPREV.BDVAL13SAL,0) from VRH_EMP_TLANCPREVCOMP LANPREV
            join VRH_BASE_TCADPREVCOMP CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV and CADPREV.BDNATPREV <> 2)   /* 184717 Leonardo Schwab 16/11/2023 */
            where LANPREV.BDCODEMP = :wempatu and LANPREV.BDCODCOL = :wcolatu and LANPREV.BDREFINI <= :wrefatu
            and ((COALESCE(LANPREV.BDREFFIN, 0) = 0) or (COALESCE(LANPREV.BDREFFIN, 0) >= :wrefatu)) and COALESCE(LANPREV.BDVAL13SAL,0) > 0
            order by LANPREV.BDCODEMP desc, LANPREV.BDCODCOL desc, LANPREV.BDREFINI DESC
            INTO :wprevprivcad;
            wprevprivcad = coalesce(wprevprivcad, 0);

            winss13antes = null;
            if (coalesce(prinssantes, 0) = 1 and wrefpagto <> wrefatu) then
               begin
                 select SUM(BDINSS13FT) from VRHF_EMP_TFOLHATOMINT where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFIRRFESOCIAL = :wrefpagto and bdordem = :wordematu and BDDATAPGTOFT < :wdataatu and BDCODCONTTI <> :wconttiatu
                 into :winss13antes;
               end
 
            if (winss13antes is null) then
               winss13antes = 0;

            winss13 = winss13 + winss13antes;

            if (wbaseir13 < 0) then
               wbaseir13 = 0;

            if (winss13 < 0) then
               winss13 = 0;

            if ((wbaseir13 <> 0) or (winss13 <> 0) or (wir13 <> 0) or (wprevprivcad <> 0)) then
               begin
            /*Se tiver 13º no mês da rescisão não deve considerar o dependente novamente*/
            wexiste13mes = NULL;
            select dt.bdcodemp from vrhf_emp_t13sal dt where dt.bdcodemp = :wempatu and dt.bdcodcol = :wcolatu and dt.bdref13 = :wrefpagto
            INTO :wexiste13mes;
            IF (wexiste13mes IS NOT NULL) THEN
               wdepatu = 0;

            BDrefirrfesocial = wrefirrfesocialatu;
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            bdordem          = wordematu;
            BDCODCONTTI      = wconttiatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir13;
            BDINSS           = winss13;
            BDIR             = wir13;
            BDDEP            = wdepatu;
            BDLUCROPJ        = 0;
            BDDESPMED        = 0;
            BDAJCUSTOS       = 0;
            BDPENJUD         = 0;
            BDPENALIM        = 0;

            if (wprepri <> 0) then
               BDPREVPRIV = wprepri;
            else
               BDPREVPRIV = wprevprivcad;

            BDBOLSAMEDICO    = WBOLSAMEDICO;
            BDINCIDESOCIAL = WINCIDESOCIAL;
            BDAUXILIOMORADIA = 0;
            BDDIARIA = 0;
            BDJUROSMORA = 0;
            BDVALABO         = 0;
            BDRENDISENTOS    = 0;
            BDDRENDISENTOS   = '';
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 10;    -- 13º rescisão
            BDINFADIC        = '';
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;

            if (pratualizainfodescsimple = TRUE) then
              begin
                wrefpgtoaux = CAST((SUBSTRING(wrefpagto FROM 1 FOR 4)||'13')AS INTEGER);
                wsqlauxsimpli = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, '||
                                ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, '||
                                ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) '||
                                ' values ('||current_connection||', '||wempatu||', '||wcolatu||', '||wrefpgtoaux||', 0, '||coalesce(bdpenalim, 0)||', '||coalesce(bddep, 0)||', '||coalesce(bdprevpriv, 0)||', '||coalesce(bdinss, 0)||', '||coalesce(wvalordescsimplatu, 0)||', FALSE, '||coalesce(bdrendtributavel, 0)||')';
        
                execute statement wsqlauxsimpli;
              end
            BDVALORDESCONTOSIMPLIFICADO = wvalordescsimplatu;
            SUSPEND;
               end
          END
     END
END^

/* Restore proc. body: SP_VRHF_DADOS_IR_INT13 */
create or alter procedure SP_VRHF_DADOS_IR_INT13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRINSSANTES smallint = 1,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRVEIODOTOTALIZADOR integer = 0,
    PRPORCC smallint = 1)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WBASEIR13 numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WINSS13 numeric(18,6);
declare variable WIR13 numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WREFINI integer;
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WDATAPGTO date;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WPREVPRIVCAD numeric(18,6);
declare variable WSQLAUX varchar(5000);
declare variable WEXISTE13MES integer;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WCODCONTTI integer;
declare variable WCONTTIATU integer;
declare variable WINSS13ANTES numeric(18,6);
declare variable WCATEGORIACOL integer;
declare variable WCATEGORIAESOCIAL integer;
declare variable WTIPODEDUCAO integer;
declare variable WVALORDESCSIMPL numeric(18,2);
declare variable WVALORDIFDESCSIMPL numeric(18,2);
declare variable WSQLAUXSIMPLI varchar(3000);
declare variable WTIPODEDUCAOATU integer;
declare variable WVALORDESCSIMPLATU numeric(18,2);
declare variable WVALORDIFDESCSIMPLATU numeric(18,2);
declare variable WREFPGTOAUX integer;
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WCPFCOL varchar(14);
declare variable WCODEMPORD integer;
declare variable WGRAVARUBRICA integer;
BEGIN
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;

  IF (UPPER(prcodcol) = 'TEMP_FILTRO_COLCON_REL') THEN
     WUSARTMP_COL_SELECT = 1;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  /* 13º FOLHA NORMAL */
  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) = 1) THEN
     wrefini = CAST((CAST((CAST(SUBSTRING(prrefini FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
  ELSE
  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) <= 10) THEN
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1))) AS INTEGER);
  ELSE
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2))) AS INTEGER);

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODCONTTI,FOL.BDCODVER,FOL.BDVALVFN,FOLN.BDDEPFN,VER.BDCLAVER,FOLN.BDDATAIRRFESOCIAL AS BDDATAPROCFN,FOLN.BDHORAPROCFN,FOLN.BDDATAPGTOFN, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
       ELSE
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODCONTTI,FOL.BDCODVER,FOL.BDVALVFN,FOLN.BDDEPFN,VER.BDCLAVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN,FOLN.BDDATAPGTOFN, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';

       wsql = wsql||'from VRHF_EMP_TFOLHAINT FOLN ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'inner join tmp_empresas_select EMPSEL ON (EMPSEL.BDCODEMP = FOLN.BDCODEMP) ';

       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP and TEMP.BDCODCOL = FOLN.BDCODCOL) ';

       wsql = wsql||'join VRHF_EMP_TVERBAINT FOL on (FOL.BDCODEMP = FOLN.BDCODEMP and FOL.BDCODCOL = FOLN.BDCODCOL and FOL.BDREFFN = FOLN.BDREFFN and FOL.BDCODCONTTI = FOLN.BDCODCONTTI) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
      WSQL = WSQL ||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                    '                                     AND X.BDREFCOL <= FOLN.BDREFFN ORDER BY X.BDREFCOL DESC) '||
                    '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

       IF (PRIRRFESOCIAL = TRUE) THEN
          wsql = wsql||'where COALESCE(COL.BDCONTRCOL,0) <> 1 and FOLN.BDREFIRRFESOCIAL between '||wrefini||' and '||prreffim;
       ELSE
          wsql = wsql||'where COALESCE(COL.BDCONTRCOL,0) <> 1 and FOL.BDREFFN between '||wrefini||' and '||prreffim;
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDCODCONTTI ';
     END
  ELSE
     BEGIN
       IF (PRIRRFESOCIAL = TRUE) THEN
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDCODCONTTI,FO.BDCODVER,FO.BDVALVFN,FOLN.BDDEPFN,VER.BDCLAVER,FOLN.BDDATAIRRFESOCIAL AS BDDATAPROCFN,FOLN.BDHORAPROCFN,FOLN.BDDATAPGTOFN, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
       ELSE
         wsql = 'select FOLN.BDREFIRRFESOCIAL,FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDCODCONTTI,FO.BDCODVER,FO.BDVALVFN,FOLN.BDDEPFN,VER.BDCLAVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN,FOLN.BDDATAPGTOFN, FOLN.BDTIPODEDUCAOFOLHA, FOLN.BDVALORDESCONTOSIMPLIFICADO, FOLN.BDVALORDIFERENCADEDUCOES, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';

       wsql = wsql||'from VRHF_EMP_TFOLHAINT FOLN join TEMPRESAS EMAT on (EMAT.BDCODEMP = FOLN.BDCODEMP) ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||'inner join TMP_EMPRESAS_SELECT TEMP on (TEMP.BDCODEMP = FOLN.BDCODEMP) ';

       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEM on (TEM.BDCODEMP = FOLN.BDCODEMP and TEM.BDCODCOL = FOLN.BDCODCOL) ';

       wsql = wsql||'join VRHF_EMP_TVERBAINT FO on (FO.BDCODEMP = FOLN.BDCODEMP and FO.BDCODCOL = FOLN.BDCODCOL and FO.BDREFFN = FOLN.BDREFFN and FO.BDCODCONTTI = FOLN.BDCODCONTTI) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FO.BDCODEMP and COL.BDCODCOL = FO.BDCODCOL) ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOLN.BDCODEMP) and (HIST.BDCODCOL = FOLN.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOLN.BDCODEMP) and (VINC.BDCODCOL = FOLN.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL  '||
                    '                                     AND X.BDREFCOL <= FOLN.BDREFFN ORDER BY X.BDREFCOL DESC) '||
                    '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOLN.BDCODEMP and x.BDCODCOL = FOLN.BDCODCOL)) ';

       IF (PRIRRFESOCIAL = TRUE) THEN
          wsql = wsql||'where COALESCE(COL.BDCONTRCOL,0) <> 1 and FOLN.BDREFIRRFESOCIAL between '||wrefini||' and '||prreffim;
       ELSE
          wsql = wsql||'where COALESCE(COL.BDCONTRCOL,0) <> 1 and FOLN.BDREFFN between '||wrefini||' and '||prreffim;

       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
            IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
               wsql = wsql||' and (('||REPLACE(UPPER(prcodemp), 'FOL.', 'FOLN.')||') ';
          
            IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
               wsql = wsql||' or ('||REPLACE(UPPER(prcodmatriz), 'FOL.', 'EMAT.')||')';
          
            IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
               wsql = wsql||') ';
          END

       IF (prcodcol IS NOT NULL AND prcodcol <> '' AND WUSARTMP_COL_SELECT = 0) THEN
          wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'FOL.', 'FOLN.')||' ';

       wsql = wsql||' order by FOLN.BDCODEMP,FOLN.BDCODCOL,FOLN.BDREFFN,FOLN.BDCODCONTTI ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wconttiatu = 0;
  wbaseir13  = 0;
  winss13    = 0;
  wir13      = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wprepri    = 0;
  wdataproca = NULL;
  whoraproca = NULL;
  wtipodeducao = 0;
  wvalordescsimpl = 0;
  wvalordifdescsimpl = 0;
  wtipodeducaoatu = 0;
  wvalordescsimplatu = 0;
  wvalordifdescsimplatu = 0;
  wbolsamedico = 0;
  WINCIDESOCIAL = 0;
  WCODINCIDIRRF = 0;
  wrefirrfesocialatu = -1;

  BDCODFIR = 0;

  FOR EXECUTE STATEMENT wsql INTO :wrefirrfesocialatu,:wcodemp,:wcodcol,:wref,:wcodcontti,:wcodver,:wvalor,:wdep,:wclassif,:wdataproc,:whoraproc,:wdatapgto,:wtipodeducao,:wvalordescsimpl,:wvalordifdescsimpl, :wcodcla, :wtributacaoexterior  DO
  BEGIN
    BDCODTIPO = 272;    -- Cálculos gerados no Único Folha

    if ((WEMPATU <> WCODEMP) or (WCOLATU <> WCODCOL)) then
       begin
         wcpfcol = null;
         wcodempord = null;

         select first 1 DOC.BDCPFCOL, coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)
         from VRH_EMP_TCOLCON_DOC DOC
         join TEMPRESAS EMP on EMP.BDCODEMP = DOC.BDCODEMP
         where DOC.BDCODEMP = :WCODEMP and
               DOC.BDCODCOL = :WCODCOL
         into :WCPFCOL, :WCODEMPORD;
       end

    IF (wempatu = 0) THEN
       wempatu = wcodemp;
    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;
    IF (wrefatu = 0) THEN
       wrefatu = wref;
    IF (wconttiatu = 0) THEN
       wconttiatu = wcodcontti;
    if (wrefirrfesocialatu = -1) then wrefirrfesocialatu = wrefirrfesocial;

    if (wvalordescsimplatu = 0) then
      wvalordescsimplatu = wvalordescsimpl;
    if (wvalordifdescsimplatu = 0) then
      wvalordifdescsimplatu = wvalordifdescsimpl;
    if (wtipodeducaoatu = 0) then
      wtipodeducaoatu = wtipodeducao;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wcodcontti <> wconttiatu)) THEN
       BEGIN
         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              wprevprivcad = 0;
              select first 1 COALESCE(LANPREV.BDVAL13SAL,0) from VRH_EMP_TLANCPREVCOMP LANPREV
              join VRH_BASE_TCADPREVCOMP CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV and CADPREV.BDNATPREV <> 2)     /* 184717 Leonardo Schwab 16/11/2023 */
              where LANPREV.BDCODEMP = :wempatu and LANPREV.BDCODCOL = :wcolatu and LANPREV.BDREFINI <= :wrefatu
              and ((COALESCE(LANPREV.BDREFFIN, 0) = 0) or (COALESCE(LANPREV.BDREFFIN, 0) >= :wrefatu)) and COALESCE(LANPREV.BDVAL13SAL,0) > 0
              order by LANPREV.BDCODEMP desc, LANPREV.BDCODCOL desc, LANPREV.BDREFINI DESC
              INTO :wprevprivcad;
              wprevprivcad = coalesce(wprevprivcad, 0);
              winss13antes = null;
              if (coalesce(prinssantes, 0) = 1 and wrefpagto <> wrefatu) then
                 begin
                   select SUM(BDINSS13FN) from VRHF_EMP_TFOLHAINT where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFFN = :wrefatu  and BDDATAPGTOFN < :wdataatu and BDCODCONTTI <> :wconttiatu
                   into :winss13antes;
                 end
   
              if (winss13antes is null) then
                 winss13antes = 0;

              winss13 = winss13 + winss13antes;

              if (wbaseir13 < 0) then
                 wbaseir13 = 0;

              if (winss13 < 0) then
                 winss13 = 0;

              if ((wbaseir13 <> 0) or (winss13 <> 0) or (wir13 <> 0) or (wprevprivcad <> 0)) then
                 begin
                   /*Se tiver 13º no mês da rescisão não deve considerar o dependente novamente*/
                   wexiste13mes = NULL;
                   select dt.bdcodemp from vrhf_emp_t13sal dt where dt.bdcodemp = :wempatu and dt.bdcodcol = :wcolatu and dt.bdref13 = :wrefpagto
                   INTO :wexiste13mes;
                   IF (wexiste13mes IS NOT NULL) THEN
                      wdepatu = 0;
          
                   bdrefirrfesocial = wrefirrfesocialatu;
                   BDCODEMP         = wempatu;
                   BDCODCOL         = wcolatu;
                   BDREF            = wrefatu;
                   BDCODCONTTI      = wconttiatu;
                   BDREFPAG         = wrefpagto;
                   BDRENDTRIBUTAVEL = wbaseir13;
                   BDINSS           = winss13;
                   BDIR             = wir13;
          
                   IF ((wbaseir13 <= 0 AND winss13 <= 0) or (prveiodototalizador = 0)) THEN
                      wdepatu = 0;
          
                   BDDEP            = wdepatu;
                   BDLUCROPJ        = 0;
                   BDDESPMED        = 0;
                   BDAJCUSTOS       = 0;
                   BDPENJUD         = 0;
                   BDPENALIM        = 0;
     
                   if (wprepri <> 0) then
                      BDPREVPRIV = wprepri;
                   else
                      BDPREVPRIV = wprevprivcad;
     
                   BDBOLSAMEDICO = WBOLSAMEDICO;
                   BDINCIDESOCIAL = WINCIDESOCIAL;
                   BDAUXILIOMORADIA = 0;
                   BDDIARIA = 0;
                   BDJUROSMORA = 0;
                   BDVALABO         = 0;
                   BDRENDISENTOS    = 0;
                   BDDRENDISENTOS   = '';
                   BDDATAPGTO       = wdataatu;
                   BDTIPO           = 10;    -- 13º rescisão
                   BDINFADIC        = '';
                   BDDATAPROC       = wdataproca;
                   BDHORAPROC       = whoraproca;

                   if (pratualizainfodescsimple = TRUE) then
                     begin
                       wrefpgtoaux = CAST((SUBSTRING(wrefpagto FROM 1 FOR 4)||'13')AS INTEGER);
                       wsqlauxsimpli = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, '||
                                       ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, '||
                                       ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) '||
                                       ' values ('||current_connection||', '||wempatu||', '||wcolatu||', '||wrefpgtoaux||', 0, '||coalesce(bdpenalim, 0)||', '||coalesce(bddep, 0)||', '||coalesce(bdprevpriv, 0)||', '||coalesce(bdinss, 0)||', '||coalesce(wvalordescsimplatu, 0)||', FALSE, '||coalesce(bdrendtributavel, 0)||')';
               
                       execute statement wsqlauxsimpli;
                     end

                   BDVALORDESCONTOSIMPLIFICADO = wvalordescsimplatu;
                   SUSPEND;
                 end
            END

         wrefirrfesocialatu = wrefirrfesocial;
         wempatu    = wcodemp;
         wcolatu    = wcodcol;
         wrefatu    = wref;
         wconttiatu = wcodcontti;
         wbaseir13  = 0;
         winss13    = 0;
         wir13      = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wprepri    = 0;
         wtipodeducaoatu = wtipodeducao;
         wvalordescsimplatu = wvalordescsimpl;
         wvalordifdescsimplatu = wvalordifdescsimpl;
         wbolsamedico = 0;
         WINCIDESOCIAL = 0;
       END

    WCODINCIDIRRF = 0;
    SELECT first 1 BDTIPOCODVER, BDIRVER, BDCODINCIDIRRF
    FROM vrh_base_tverbas_ref
    WHERE BDCODVER = :wcodver and BDREFVER <= :wref
    order by BDCODVER desc, BDREFVER desc
    INTO :wtipocodver,:wirver,:WCODINCIDIRRF;

    select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
    if (wgravarubrica > 0) then
       begin
         UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
         VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
         MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end


    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
       begin
          wirver = 0;
       end
    else
--    if (wtipocodver <= 1) then
       begin
         IF (wirver = 3) THEN -- 13º salário
            BEGIN
              IF (wtipocodver = 0) THEN   -- provento
                 wbaseir13 = wbaseir13 + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN   -- desconto
                 BEGIN
                   --                                      INSS                                              Obrigações IR
                   IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                      wbaseir13 = wbaseir13 - wvalor;
                 END
            END

         --                                     IR 13º salário rescisão
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.A') THEN
            wir13 = wir13 + wvalor;
       end

         --                                     INSS 13º salário rescisão
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.6') THEN
            winss13 = winss13 + wvalor;
         --                                     Previdência privada
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.601.8.2') THEN
            wprepri = wprepri + wvalor;

         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '5.520.0.0') THEN
            WBOLSAMEDICO = WBOLSAMEDICO + WVALOR;
         --
         if (COALESCE(WCODINCIDIRRF, 0) IN (11,12,13,14,41,42,43,51,52,53,54)) then
            WINCIDESOCIAL = 1;

    wdepatu = wdep;
    wdataatu = wdatapgto;

    wdataproca = wdataproc;
    whoraproca = whoraproc;

  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wconttiatu <> 0) THEN
     BEGIN
       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            wprevprivcad = 0;
            select first 1 COALESCE(LANPREV.BDVAL13SAL,0) from VRH_EMP_TLANCPREVCOMP LANPREV
            join VRH_BASE_TCADPREVCOMP CADPREV on (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV and CADPREV.BDNATPREV <> 2)   /* 184717 Leonardo Schwab 16/11/2023 */
            where LANPREV.BDCODEMP = :wempatu and LANPREV.BDCODCOL = :wcolatu and LANPREV.BDREFINI <= :wrefatu
            and ((COALESCE(LANPREV.BDREFFIN, 0) = 0) or (COALESCE(LANPREV.BDREFFIN, 0) >= :wrefatu)) and COALESCE(LANPREV.BDVAL13SAL,0) > 0
            order by LANPREV.BDCODEMP desc ,LANPREV.BDCODCOL desc, LANPREV.BDREFINI DESC
            INTO :wprevprivcad;
            wprevprivcad = coalesce(wprevprivcad, 0);

            winss13antes = null;
            if (coalesce(prinssantes, 0) = 1 and wrefpagto <> wrefatu) then
               begin
                 select SUM(BDINSS13FN) from VRHF_EMP_TFOLHAINT where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFFN = :wrefatu and BDDATAPGTOFN < :wdataatu and BDCODCONTTI <> :wconttiatu
                 into :winss13antes;
               end
 
            if (winss13antes is null) then
               winss13antes = 0;

            winss13 = winss13 + winss13antes;

            if (wbaseir13 < 0) then
               wbaseir13 = 0;

            if (winss13 < 0) then
               winss13 = 0;

            if ((wbaseir13 <> 0) or (winss13 <> 0) or (wir13 <> 0) or (wprevprivcad <> 0)) then
               begin
            /*Se tiver 13º no mês da rescisão não deve considerar o dependente novamente*/
            wexiste13mes = NULL;
            select dt.bdcodemp from vrhf_emp_t13sal dt where dt.bdcodemp = :wempatu and dt.bdcodcol = :wcolatu and dt.bdref13 = :wrefpagto
            INTO :wexiste13mes;
            IF (wexiste13mes IS NOT NULL) THEN
               wdepatu = 0;
     
            bdrefirrfesocial = wrefirrfesocialatu;
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDCODCONTTI      = wconttiatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir13;
            BDINSS           = winss13;
            BDIR             = wir13;
            BDDEP            = wdepatu;
            BDLUCROPJ        = 0;
            BDDESPMED        = 0;
            BDAJCUSTOS       = 0;
            BDPENJUD         = 0;
            BDPENALIM        = 0;

            if (wprepri <> 0) then
               BDPREVPRIV = wprepri;
            else
               BDPREVPRIV = wprevprivcad;

            BDBOLSAMEDICO    = WBOLSAMEDICO;
            BDINCIDESOCIAL = WINCIDESOCIAL;
            BDAUXILIOMORADIA = 0;
            BDDIARIA = 0;
            BDJUROSMORA = 0;
            BDVALABO         = 0;
            BDRENDISENTOS    = 0;
            BDDRENDISENTOS   = '';
            BDDATAPGTO       = wdataatu;
            BDTIPO           = 10;    -- 13º rescisão
            BDINFADIC        = '';
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;

            if (pratualizainfodescsimple = TRUE) then
              begin
                wrefpgtoaux = CAST((SUBSTRING(wrefpagto FROM 1 FOR 4)||'13')AS INTEGER);
                wsqlauxsimpli = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, '||
                                ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, '||
                                ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) '||
                                ' values ('||current_connection||', '||wempatu||', '||wcolatu||', '||wrefpgtoaux||', 0, '||coalesce(bdpenalim, 0)||', '||coalesce(bddep, 0)||', '||coalesce(bdprevpriv, 0)||', '||coalesce(bdinss, 0)||', '||coalesce(wvalordescsimplatu, 0)||', FALSE, '||coalesce(bdrendtributavel, 0)||')';
        
                execute statement wsqlauxsimpli;
              end

            BDVALORDESCONTOSIMPLIFICADO = wvalordescsimplatu;
            SUSPEND;
               end
          END
     END

  for select BDCODEMP, BDCODCOL, BDREF, BDREFPAG, BDTIPO, BDRENDTRIBUTAVEL, BDINSS, BDIR, BDDEP, BDLUCROPJ, BDDESPMED, BDAJCUSTOS, BDPENJUD, BDPENALIM,
             BDPREVPRIV, BDINDRESC, BDVALABO, BDRENDISENTOS, BDDRENDISENTOS, BDDATAPGTO, BDINFADIC, BDDATAPROC, BDHORAPROC, BDORDEM, BDCODCONTTI,
             BDVALORDESCONTOSIMPLIFICADO, BDAUXILIOMORADIA, BDDIARIA, BDBOLSAMEDICO, BDJUROSMORA, BDINCIDESOCIAL, BDCODFIR, BDDEMDEV,
             BDREFIRRFESOCIAL, BDCODTIPO
  from SP_VRHF_DADOS_IR_INTFT13(:prcodemp, :prcodcol, :prrefini, :prreffim, :prpuxarfiliais, :prcodmatriz, :prinssantes, :prirrfesocial, :pratualizainfodescsimple,
                                :prveiodototalizador, :prporcc)
  into :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR, :BDDEP, :BDLUCROPJ, :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM,
             :BDPREVPRIV, :BDINDRESC, :BDVALABO, :BDRENDISENTOS, :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDDATAPROC, :BDHORAPROC, :BDORDEM, :BDCODCONTTI,
             :BDVALORDESCONTOSIMPLIFICADO, :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA, :BDINCIDESOCIAL, :BDCODFIR, :BDDEMDEV,
             :BDREFIRRFESOCIAL, :BDCODTIPO
  do
    suspend;

  /*  13 RESCISAO FOLHA COMPLEMENTAR NORMAL E TOMADOR  */
  for select bdrefirrfesocial,BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS,BDPENJUD,
             BDPENALIM,BDPREVPRIV,BDINDRESC,BDVALABO,BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,BDDATAPROC,BDHORAPROC,BDORDEM,BDCODCONTTI,
             BDAUXILIOMORADIA,BDDIARIA,BDBOLSAMEDICO,BDJUROSMORA,BDINCIDESOCIAL, BDCODTIPO
  from SP_VRHF_DADOS_IR_13FC_INT(:prcodemp, :prcodcol, :prrefini, :prreffim, :prpuxarfiliais, :prcodmatriz, :prirrfesocial, :prporcc)
  INTO :bdrefirrfesocial,:BDCODEMP,:BDCODCOL,:BDREF,:BDREFPAG,:BDTIPO,:BDRENDTRIBUTAVEL,:BDINSS,:BDIR,:BDDEP,:BDLUCROPJ,:BDDESPMED,:BDAJCUSTOS,:BDPENJUD,:BDPENALIM,:BDPREVPRIV,
       :BDINDRESC,:BDVALABO,:BDRENDISENTOS,:BDDRENDISENTOS,:BDDATAPGTO,:BDINFADIC,:BDDATAPROC,:BDHORAPROC,:BDORDEM,:BDCODCONTTI,
       :BDAUXILIOMORADIA,:BDDIARIA,:BDBOLSAMEDICO,:BDJUROSMORA,:BDINCIDESOCIAL, :BDCODTIPO
  DO
    SUSPEND;

  /*  DADOS IMPORTADOS OU CADASTRADOS NA FICHA  */
  for select BDCODEMP, BDCODCOL, BDREF, BDREFPAG, BDTIPO, BDRENDTRIBUTAVEL, BDINSS, BDIR, BDDEP, BDLUCROPJ, BDDESPMED, BDAJCUSTOS, BDPENJUD, BDPENALIM, BDPREVPRIV,
             BDINDRESC, BDVALABO, BDRENDISENTOS, BDDRENDISENTOS, BDDATAPGTO, BDINFADIC, BDDATAPROC, BDHORAPROC, BDORDEM, BDCODCONTTI, BDVALORDESCONTOSIMPLIFICADO,
             BDAUXILIOMORADIA, BDDIARIA, BDBOLSAMEDICO, BDJUROSMORA, BDINCIDESOCIAL, BDCODFIR, BDDEMDEV, BDREFIRRFESOCIAL, BDCODTIPO
  from SP_VRHF_DADOS_IR_FICHA_INT13(:prcodemp, :prcodcol, :prrefini, :prreffim, :prpuxarfiliais, :prcodmatriz)
  into :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR, :BDDEP, :BDLUCROPJ, :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM, :BDPREVPRIV,
       :BDINDRESC, :BDVALABO, :BDRENDISENTOS, :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDDATAPROC, :BDHORAPROC, :BDORDEM, :BDCODCONTTI, :BDVALORDESCONTOSIMPLIFICADO,
       :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA, :BDINCIDESOCIAL, :BDCODFIR, :BDDEMDEV, :BDREFIRRFESOCIAL, :BDCODTIPO
  do
    suspend;
END^

/* Restore proc. body: SP_VRHF_DADOS_IR_FN_INT */
create or alter procedure SP_VRHF_DADOS_IR_FN_INT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0,
    PREXPORTACAO integer = 0,
    PRPORCC smallint = 0,
    PRIRRFESOCIAL boolean = false,
    PRFICHAFINANCEIRA smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDDEMDEV varchar(30),
    BDCODTIPO integer)
as
declare variable WSQL varchar(10000);
BEGIN
  wsql = 'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS,BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,'||
                'BDVALABO,BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,BDDATAPROC,BDHORAPROC,BDORDEM,BDBOLSAESTUDOS, BDVALORDESCONTOSIMPLIFICADO, '||
                'BDAUXILIOMORADIA, BDDIARIA, BDBOLSAMEDICO, BDJUROSMORA,BDDEMDEV, coalesce(BDCODTIPO, 201) BDCODTIPO '||
         'from SP_VRHF_DADOS_IR_FN(';

  if (coalesce(prcodemp, '') <> '') then
     wsql = wsql||''''||prcodemp||''',';
  else
     wsql = wsql||'null,';

  if (coalesce(prcodcol, '') <> '') then
     wsql = wsql||''''||prcodcol||''',';
  else
     wsql = wsql||'null,';

  wsql = wsql||prrefini||','||prreffim||',';

  if (coalesce(prpuxarfiliais, 0) = 0) then
     wsql = wsql||'0,';
  else
     wsql = wsql||prpuxarfiliais||',';

  if (coalesce(prcodmatriz, '') <> '') then
     wsql = wsql||''''||prcodmatriz||''',';
  else
     wsql = wsql||''''',';

  if (coalesce(prpreviaresc, 0) = 0) then
     wsql = wsql||'0,';
  else
     wsql = wsql||prpreviaresc||',';

  if (coalesce(prexportacao, 0) = 0) then
     wsql = wsql||'0,';
  else
     wsql = wsql||prexportacao||',';

  if (coalesce(prporcc, 0) = 0) then
     wsql = wsql||'0,';
  else
     wsql = wsql||prporcc||',';

  if (PRIRRFESOCIAL = TRUE) then
     wsql = wsql||'TRUE';
  else
     wsql = wsql||'FALSE';

  wsql = wsql||', FALSE, 0, '||prfichafinanceira||')';

  BDCODCONTTI = null;

  for execute statement wsql
  into
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC,
    :BDDATAPROC,
    :BDHORAPROC,
    :BDORDEM,
    :BDBOLSAESTUDOS,
    :BDVALORDESCONTOSIMPLIFICADO,
    :BDAUXILIOMORADIA,
    :BDDIARIA,
    :BDBOLSAMEDICO,
    :BDJUROSMORA,
    :BDDEMDEV,
    :BDCODTIPO
  do
    SUSPEND;


  wsql = 'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS,BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,'||
                'BDVALABO,BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,BDDATAPROC,BDHORAPROC,BDORDEM,BDCODCONTTI, 0 BDVALORDESCONTOSIMPLIFICADO, '||
                'BDAUXILIOMORADIA, BDDIARIA, BDBOLSAMEDICO, BDJUROSMORA, '''' BDDEMDEV, coalesce(BDCODTIPO, 201) BDCODTIPO '||
         'from SP_VRHF_DADOS_IR_INT(';

  if (coalesce(prcodemp, '') <> '') then
     wsql = wsql||''''||prcodemp||''',';
  else
     wsql = wsql||'null,';

  if (coalesce(prcodcol, '') <> '') then
     wsql = wsql||''''||prcodcol||''',';
  else
     wsql = wsql||'null,';

  wsql = wsql||prrefini||','||prreffim||',';

  if (coalesce(prpuxarfiliais, 0) = 0) then
     wsql = wsql||'0,';
  else
     wsql = wsql||prpuxarfiliais||',';

  if (coalesce(prcodmatriz, '') <> '') then
     wsql = wsql||''''||prcodmatriz||''',';
  else
     wsql = wsql||''''',';

  if (coalesce(prpreviaresc, 0) = 0) then
     wsql = wsql||'0,';
  else
     wsql = wsql||prpreviaresc||',';

  if (coalesce(prporcc, 0) = 0) then
     wsql = wsql||'0,';
  else
     wsql = wsql||prporcc||',';

  if (PRIRRFESOCIAL = TRUE) then
     wsql = wsql||'0, TRUE)';
  else
     wsql = wsql||'0, FALSE)';

  BDBOLSAESTUDOS = 0;

  for execute statement wsql
  into
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC,
    :BDDATAPROC,
    :BDHORAPROC,
    :BDORDEM,
    :BDCODCONTTI,
    :BDVALORDESCONTOSIMPLIFICADO,
    :BDAUXILIOMORADIA,
    :BDDIARIA,
    :BDBOLSAMEDICO,
    :BDJUROSMORA,
    :BDDEMDEV,
    :BDCODTIPO
  do
    SUSPEND;

END^

/* Restore proc. body: SP_VRHF_DADOS_IR_13_INT13 */
create or alter procedure SP_VRHF_DADOS_IR_13_INT13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRIRRFESOCIAL boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDCODCONTTI integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDDEMDEV varchar(30),
    BDCODTIPO integer)
as
declare variable WSQL varchar(32700);
BEGIN
  wsql = 'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS,BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,'||
                'BDVALABO,BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,BDDATAPROC,BDHORAPROC,BDORDEM, BDVALORDESCONTOSIMPLIFICADO, '||
                'BDAUXILIOMORADIA, BDDIARIA, BDBOLSAMEDICO, BDJUROSMORA,BDDEMDEV,BDCODTIPO '||
         'from SP_VRHF_DADOS_IR_13(';

  if (coalesce(prcodemp, '') <> '') then
     wsql = wsql||''''||prcodemp||''',';
  else
     wsql = wsql||'null,';

  if (coalesce(prcodcol, '') <> '') then
     wsql = wsql||''''||prcodcol||''',';
  else
     wsql = wsql||'null,';

  wsql = wsql||prrefini||','||prreffim||',';

  if (coalesce(prpuxarfiliais, 0) = 0) then
     wsql = wsql||'0,';
  else
     wsql = wsql||prpuxarfiliais||',';

  if (coalesce(prcodmatriz, '') <> '') then
     wsql = wsql||''''||prcodmatriz||'''';
  else
     wsql = wsql||'''''';

  if (PRIRRFESOCIAL = TRUE) then
     wsql = wsql||',TRUE';
  else
     wsql = wsql||',FALSE';

  wsql = wsql||')';

  BDCODCONTTI = null;
  BDBOLSAESTUDOS = 0;

  for execute statement wsql
  into
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC,
    :BDDATAPROC,
    :BDHORAPROC,
    :BDORDEM,
    :BDVALORDESCONTOSIMPLIFICADO,
    :BDAUXILIOMORADIA,
    :BDDIARIA,
    :BDBOLSAMEDICO,
    :BDJUROSMORA,
    :BDDEMDEV,
    :BDCODTIPO
  do
    SUSPEND;


  wsql = 'select BDCODEMP,BDCODCOL,BDREF,BDREFPAG,BDTIPO,BDRENDTRIBUTAVEL,BDINSS,BDIR,BDDEP,BDLUCROPJ,BDDESPMED,BDAJCUSTOS,BDPENJUD,BDPENALIM,BDPREVPRIV,BDINDRESC,'||
                'BDVALABO,BDRENDISENTOS,BDDRENDISENTOS,BDDATAPGTO,BDINFADIC,BDDATAPROC,BDHORAPROC,BDORDEM,BDCODCONTTI, BDVALORDESCONTOSIMPLIFICADO, '||
                'BDAUXILIOMORADIA, BDDIARIA, BDBOLSAMEDICO, BDJUROSMORA,BDDEMDEV,BDCODTIPO '||
         'from SP_VRHF_DADOS_IR_INT13(';

  if (coalesce(prcodemp, '') <> '') then
     wsql = wsql||''''||prcodemp||''',';
  else
     wsql = wsql||'null,';

  if (coalesce(prcodcol, '') <> '') then
     wsql = wsql||''''||prcodcol||''',';
  else
     wsql = wsql||'null,';

  wsql = wsql||prrefini||','||prreffim||',';

  if (coalesce(prpuxarfiliais, 0) = 0) then
     wsql = wsql||'0,';
  else
     wsql = wsql||prpuxarfiliais||',';

  if (coalesce(prcodmatriz, '') <> '') then
     wsql = wsql||''''||prcodmatriz||'''';
  else
     wsql = wsql||'''''';

  if (PRIRRFESOCIAL = TRUE) then
     wsql = wsql||',0, TRUE)';
  else
     wsql = wsql||',0, FALSE)';

  for execute statement wsql
  into
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC,
    :BDDATAPROC,
    :BDHORAPROC,
    :BDORDEM,
    :BDCODCONTTI,
    :BDVALORDESCONTOSIMPLIFICADO,
    :BDAUXILIOMORADIA,
    :BDDIARIA,
    :BDBOLSAMEDICO,
    :BDJUROSMORA,
    :BDDEMDEV,
    :BDCODTIPO
  do
    SUSPEND;
END^

/* Restore proc. body: SP_VRHF_DADOS_IR_FN2 */
create or alter procedure SP_VRHF_DADOS_IR_FN2 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRPREVIARESC smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer)
as
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCODVER integer;
declare variable WVALOR numeric(18,6);
declare variable WDATAPGTO date;
declare variable WCLASSIF varchar(20);
declare variable WDESCVER varchar(40);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WDATAATU date;
declare variable WPAGEMP integer;
declare variable WBASEIR numeric(18,6);
declare variable WREFPAGTO integer;
declare variable WTIPOCODVER integer;
declare variable WIRVER integer;
declare variable WRENDISENTOVER varchar(5);
declare variable WINSSN numeric(18,6);
declare variable WIR numeric(18,6);
declare variable WDEP numeric(18,6);
declare variable WDEPATU numeric(18,6);
declare variable WLUCROPJ numeric(18,6);
declare variable WDESPMED numeric(18,6);
declare variable WAJCUS numeric(18,6);
declare variable WPENJUD numeric(18,6);
declare variable WPENALIM numeric(18,6);
declare variable WPREPRI numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDIS numeric(18,6);
declare variable WDRENDIS varchar(200);
declare variable WDATARESC date;
declare variable WDATAPAGRESC date;
declare variable WCODPRES integer;
declare variable WDESCPRES varchar(110);
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WDESCCC varchar(100);
declare variable WREFINI integer;
declare variable WSIND integer;
declare variable WFERIADO varchar(5);
declare variable WI integer;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WDATAPROCA date;
declare variable WHORAPROCA time;
declare variable WTIPOMOV integer;
declare variable WTIPOCLASSECOL integer;
declare variable WGCLASS varchar(1000);
declare variable WDESCVER2 varchar(70);
BEGIN
  /*
      FOLHA NORMAL
  */

  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) = 1) THEN
     wrefini = CAST((CAST((CAST(SUBSTRING(prrefini FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
  ELSE
  IF (CAST(SUBSTRING(prrefini FROM 5 FOR 2) AS INTEGER) <= 10) THEN
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1))) AS INTEGER);
  ELSE
     wrefini = CAST((SUBSTRING(prrefini FROM 1 FOR 4)||CAST((CAST((SUBSTRING(prrefini FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2))) AS INTEGER);

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOt.BDREFFN,FOt.BDCODVER,FOt.BDVALVFN,FOLN.BDDATAPGTOFN,FOLN.BDDEPFN,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN '||
              'from (select BDCODEMPORIG, BDCODCOLORIG, BDCODEMPDEST BDCODEMP, BDCODCOLDEST BDCODCOL from VRH_EMP_TTRANSCOL) FOL ';
       wsql = wsql||'join vrhf_emp_tverbafn FOt on (FOt.BDCODEMP = FOL.BDCODEMPORIG and FOt.BDCODCOL = FOL.BDCODCOLORIG) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOt.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhanormal FOLN on (FOLN.BDCODEMP = FOt.BDCODEMP and FOLN.BDCODCOL = FOt.BDCODCOL and FOLN.BDREFFN = FOt.BDREFFN) ';
       wsql = wsql||'left outer join TEMPRESAS TEMP_DEST on (TEMP_DEST.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'left outer join TEMPRESAS TEMP_ORIG on (TEMP_ORIG.BDCODEMP = FOL.BDCODEMPORIG) ';
       wsql = wsql||'where FOt.BDREFFN >= '||wrefini||' and FOt.BDREFFN <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||' and SUBSTRING(TEMP_DEST.BDCNPJEMP FROM 1 FOR 10) = SUBSTRING(TEMP_ORIG.BDCNPJEMP FROM 1 FOR 10) ';

       wsql = wsql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VRHF_EMP_TVERBAFN Y '||
              'where Y.BDCODEMP = FOL.BDCODEMPORIG and Y.BDCODCOL = FOL.BDCODCOLORIG and Y.BDREFFN = FOt.BDREFFN '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02) ';

     
       wsql = wsql||' order by FOL.BDCODEMPORIG,FOL.BDCODCOLORIG,FOt.BDREFFN ';
     END
  ELSE
     BEGIN
       wsql = 'select fot.BDCODEMPDEST,fot.BDCODCOLDEST,FO.BDREFFN,FO.BDCODVER,FO.BDVALVFN,FOLN.BDDATAPGTOFN,FOLN.BDDEPFN,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFN,FOLN.BDHORAPROCFN '||
              'from TEMPRESAS FOL ';
       wsql = wsql||'join vrhf_emp_tverbafn FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'join VRH_EMP_TTRANSCOL fot on (fot.BDCODEMPDEST = FO.BDCODEMP and fot.BDCODCOLDEST = FO.BDCODCOL) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhanormal FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFFN = FO.BDREFFN) ';
       wsql = wsql||'left outer join TEMPRESAS TEMP_ORIG on (TEMP_ORIG.BDCODEMP = fot.BDCODEMPORIG) ';
       wsql = wsql||'where FO.BDREFFN >= '||wrefini||' and FO.BDREFFN <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       wsql = wsql||' and SUBSTRING(FOL.BDCNPJEMP FROM 1 FOR 10) = SUBSTRING(TEMP_ORIG.BDCNPJEMP FROM 1 FOR 10) ';

       wsql = wsql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VRHF_EMP_TVERBAFN Y '||
              'where Y.BDCODEMP = FO.BDCODEMP and Y.BDCODCOL = FO.BDCODCOL and Y.BDREFFN = FO.BDREFFN '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02) ';

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFFN ';
     END

  wempatu    = 0;
  wcolatu    = 0;
  wrefatu    = 0;
  wpagemp    = 0;

  wbaseir    = 0;
  winssn     = 0;
  wir        = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc   = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;
  wgclass    = '';

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wcodver,:wvalor,:wdatapgto,:wdep,:wclassif,:wdescver,:wdataproc,:whoraproc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wrefatu = 0) THEN
       wrefatu = wref;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu)) THEN
       BEGIN
         wpagemp        = 0;
         wcodpres       = NULL;
         wdescpres      = NULL;
         wdataresc      = NULL;
         wdatapagresc   = NULL;
         wtipomov       = 0;
         wtipoclassecol = 0;
         EXECUTE PROCEDURE sp_seta_competencia(:wrefatu, NULL, NULL);

         SELECT COALESCE(Y.BDGRUPOCLA,0) FROM vw_vrh_emp_tcolcon_vinc X
         JOIN vrh_base_tclasse Y ON (Y.BDCODCLA = X.BDCODCLA)
         WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu
         INTO :wtipoclassecol;

         IF (wtipoclassecol = 2) THEN   -- pro-labore
            SELECT COALESCE(BDPAGEMPCONTR, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;
         ELSE
            SELECT COALESCE(BDPAGEMP, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;

         IF (prpreviaresc = 1) THEN
            BEGIN
              SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END
         ELSE
            BEGIN
              SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END

         IF ((wtipomov < 1) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
            BEGIN
              IF (wdatapagresc IS NOT NULL) THEN
                 BEGIN
                   wdataatu  = wdatapagresc;
                 END
              ELSE
                 BEGIN
                   wdataatu  = wdataresc;
                 END
            END
         ELSE
            BEGIN
              IF (CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) = 12) THEN
                 wdataatu = CAST((CAST((CAST((SUBSTRING(wrefatu FROM 1 FOR 4)) AS INTEGER) + 1) AS VARCHAR(4))||'-01-01') AS DATE);
              ELSE
              IF (CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) < 9) THEN
                 wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-0'||CAST((CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(1))||'-01') AS DATE);
              ELSE
                 wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-'||CAST((CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(2))||'-01') AS DATE);
     
              IF (wpagemp = 0) THEN -- mês seguinte
                 BEGIN
                   wsind = NULL;
                   wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                   SELECT BDCODSINTRAB FROM VW_VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wsind;
     
                   wi = 1;
                   WHILE (wi <= 5) DO
                     BEGIN
                       SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wempatu, :wdataatu, :wrefpagto, :wsind) INTO wferiado;
                       IF (EXTRACT(WEEKDAY FROM wdataatu) IN (1,2,3,4,5,6) AND wferiado = 'FALSE') THEN
                          wi = wi + 1;
     
                       IF (wi <= 5) THEN
                          wdataatu = wdataatu + 1;
                     END
                 END
              ELSE
                 BEGIN
                   wdataatu = wdataatu - 1;
                   wi = 1;
                   WHILE (wi = 1) DO
                     BEGIN
                       SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wempatu, :wdataatu, :wrefatu, :wsind) INTO wferiado;
                       IF (EXTRACT(WEEKDAY FROM wdataatu) IN (1,2,3,4,5,6) AND wferiado = 'FALSE') THEN
                          wi = 0;
     
                       IF (wi = 1) THEN
                          wdataatu = wdataatu - 1;
                     END
                 END
            END

         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir;
              BDINSS           = winssn;
              BDIR             = wir;

              IF (wbaseir + winssn + wir > 0)  THEN
                 BDDEP = wdepatu;
              ELSE
                 BDDEP = 0;

              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;
              BDPREVPRIV       = wprepri;
              BDINDRESC        = windresc;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;

              IF (wdataresc IS NOT NULL) THEN
                 BEGIN
                   BDTIPO    = 100;    -- Folha normal rescisão
                   BDINFADIC = wcodpres||' - '||wdescpres;
                 END
              ELSE
                 BEGIN
                   BDTIPO    = 0;    -- Folha normal
                   BDINFADIC = '';
                 END

              SUSPEND;
            END

         wempatu   = wcodemp;
         wcolatu   = wcodcol;
         wrefatu   = wref;

         wbaseir    = 0;
         winssn     = 0;
         wir        = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc   = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
         wgclass    = '';
       END

    -- soma as bases
    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, COALESCE(BDIRVER,0), BDRENDISENTOIRVER FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover;

--    if (wtipocodver <= 1) then
       begin
         IF (wirver = 1) THEN -- IR Folha normal
            BEGIN
              IF (wtipocodver = 0) THEN   -- provento
                 wbaseir = wbaseir + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN   -- desconto
                 BEGIN
                   --                                      INSS                                              Obrigações IR
                   IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                      wbaseir = wbaseir - wvalor;
                 END
            END
     
         --                                     INSS folha normal
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.0') THEN
            winssn = winssn + wvalor;
         --                                     IR folha normal
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.0') THEN
            wir = wir + wvalor;
     
         --                                     Lucro pessoa jurídica
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
            wlucropj = wlucropj + wvalor;
         --                                     Despesas médicas                                     Complemento de despesas médicas
         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.0') OR (SUBSTRING(wclassif FROM 1 FOR 9) = '0.420.0.2') or (SUBSTRING(wclassif FROM 1 FOR 9) = '3.010.0.0')) THEN
            wdespmed = wdespmed + wvalor;
         --                                     Diárias
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.0' AND wirver = 0) THEN
            wajcus = wajcus + wvalor;
         --                                     Ajuda de custos
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1' AND wirver = 0) THEN
            wajcus = wajcus + wvalor;
         --                                     Pensões judiciais
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.0') THEN
            wpenjud = wpenjud + wvalor;
         --                                     Pensões alimentícias
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.1') THEN
            wpenalim = wpenalim + wvalor;
         --                                     Previdência privada
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.2') THEN
            wprepri = wprepri + wvalor;
     
         IF ((SUBSTRING(wclassif FROM 1 FOR 7) = '7.001.3') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '7.020') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '7.021')) THEN
            BEGIN
              IF (wtipocodver in (0, 2)) THEN   -- Provento
                 windresc = windresc + wvalor;
              ELSE
              IF (wtipocodver in (1, 3)) THEN   -- Desconto
                 windresc = windresc - wvalor;
            END
     
         --                                      Abono pec.                                      1/3 abono pec.                                  Abono pec. dobro                                1/3 abono pec.
         IF ((SUBSTRING(wclassif FROM 1 FOR 5) = '3.003') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.004') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.007') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.008') OR
         --                                      Complemento de abono pecuniário                  Compl. 1/3 abono pecuniário
             (SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.2') OR (SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.3')) THEN
            wvalabo = wvalabo + wvalor;
         -- Rendimentos isentos
         IF (UPPER(wrendisentover) = 'TRUE') THEN
            BEGIN
              wrendis = wrendis + wvalor;
     
              wi = 0;
              SELECT POS FROM pos(SUBSTRING(:wclassif FROM 1 FOR 5), :wgclass) INTO :wi;
     
              IF (wi = 0) THEN
                 BEGIN
                   wdescver2 = '';
                   SELECT FIRST 1 BDDESCVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = SUBSTRING(:wclassif FROM 1 FOR 5) INTO wdescver2;
                   wgclass = wgclass||';'||SUBSTRING(:wclassif FROM 1 FOR 5);
     
                   IF (wdrendis <> '') THEN
                      wdrendis = wdrendis ||', ';
     
                   wdrendis = SUBSTRING(wdrendis||wdescver2 FROM 1 FOR 200);
                 END
            END
       end

    wdepatu = wdep;
    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0) THEN
     BEGIN
       wpagemp        = 0;
       wcodpres       = NULL;
       wdescpres      = NULL;
       wdataresc      = NULL;
       wdatapagresc   = NULL;
       wtipomov       = 0;
       wtipoclassecol = 0;
       EXECUTE PROCEDURE sp_seta_competencia(:wrefatu, NULL, NULL);

       SELECT COALESCE(Y.BDGRUPOCLA,0) FROM vw_vrh_emp_tcolcon_vinc X
       JOIN vrh_base_tclasse Y ON (Y.BDCODCLA = X.BDCODCLA)
       WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu
       INTO :wtipoclassecol;

       IF (wtipoclassecol = 2) THEN  -- pro-labore
          SELECT COALESCE(BDPAGEMPCONTR, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;
       ELSE
          SELECT COALESCE(BDPAGEMP, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;

       IF (prpreviaresc = 1) THEN
          BEGIN
            SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END
       ELSE
          BEGIN
            SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END

       IF ((wtipomov < 1) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
          BEGIN
            IF (wdatapagresc IS NOT NULL) THEN
               BEGIN
                 wdataatu  = wdatapagresc;
               END
            ELSE
               BEGIN
                 wdataatu  = wdataresc;
               END
          END
       ELSE
          BEGIN
            IF (CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) = 12) THEN
               wdataatu = CAST((CAST((CAST((SUBSTRING(wrefatu FROM 1 FOR 4)) AS INTEGER) + 1) AS VARCHAR(4))||'-01-01') AS DATE);
            ELSE
            IF (CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) < 9) THEN
               wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-0'||CAST((CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(1))||'-01') AS DATE);
            ELSE
               wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-'||CAST((CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(2))||'-01') AS DATE);
   
            IF (wpagemp = 0) THEN -- mês seguinte
               BEGIN
                 wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                 wsind = NULL;
                 SELECT BDCODSINTRAB FROM VW_VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wsind;
   
                 wi = 1;
                 WHILE (wi <= 5) DO
                   BEGIN
                     SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wempatu, :wdataatu, :wrefpagto, :wsind) INTO wferiado;
                     IF (EXTRACT(WEEKDAY FROM wdataatu) IN (1,2,3,4,5,6) AND wferiado = 'FALSE') THEN
                        wi = wi + 1;
   
                     IF (wi <= 5) THEN
                        wdataatu = wdataatu + 1;
                   END
               END
            ELSE
               BEGIN
                 wdataatu = wdataatu - 1;
                 wi = 1;
                 WHILE (wi = 1) DO
                   BEGIN
                     SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wempatu, :wdataatu, :wrefatu, :wsind) INTO wferiado;
                     IF (EXTRACT(WEEKDAY FROM wdataatu) IN (1,2,3,4,5,6) AND wferiado = 'FALSE') THEN
                        wi = 0;
   
                     IF (wi = 1) THEN
                        wdataatu = wdataatu - 1;
                   END
               END
          END

       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir;
            BDINSS           = winssn;
            BDIR             = wir;

            IF (wbaseir + winssn + wir > 0)  THEN
               BDDEP = wdepatu;
            ELSE
               BDDEP = 0;

            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;
            BDPREVPRIV       = wprepri;
            BDINDRESC        = windresc;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;

            IF (wdataresc IS NOT NULL) THEN
               BEGIN
                 BDTIPO    = 100;    -- Folha normal rescisão
                 BDINFADIC = wcodpres||' - '||wdescpres;
               END
            ELSE
               BEGIN
                 BDTIPO    = 0;    -- Folha normal
                 BDINFADIC = '';
               END
            SUSPEND;
          END
     END

  /*
      FOLHA TOMADOR
  */

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOt.BDREFTOMADOR,FOt.BDORDEM,FOt.BDCODVER,FOt.BDVALVFT,FOLN.BDDATAPGTOFT,FOLN.BDDEPFT,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT '||
              'from (select BDCODEMPORIG, BDCODCOLORIG, BDCODEMPDEST BDCODEMP, BDCODCOLDEST BDCODCOL from VRH_EMP_TTRANSCOL) FOL ';

       wsql = wsql||'join vrhf_emp_tverbatomador FOt on (FOt.BDCODEMP = FOL.BDCODEMPORIG and FOt.BDCODCOL = BDCODCOLORIG) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOt.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhatomador FOLN on (FOLN.BDCODEMP = FOt.BDCODEMP and FOLN.BDCODCOL = FOt.BDCODCOL and FOLN.BDREFTOMADOR = FOt.BDREFTOMADOR and FOLN.BDORDEM = FOt.BDORDEM) ';
       wsql = wsql||'left outer join TEMPRESAS TEMP_DEST on (TEMP_DEST.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'left outer join TEMPRESAS TEMP_ORIG on (TEMP_ORIG.BDCODEMP = FOL.BDCODEMPORIG) ';
       wsql = wsql||'where FOt.BDREFTOMADOR >= '||wrefini||' and FOt.BDREFTOMADOR <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' and SUBSTRING(TEMP_DEST.BDCNPJEMP FROM 1 FOR 10) = SUBSTRING(TEMP_ORIG.BDCNPJEMP FROM 1 FOR 10) ';

       wsql = wsql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFTOMADOR, COUNT(*) BDTOT, SUM(Y.BDVALVFT) BDSOMA from VRHF_EMP_TVERBATOMADOR Y '||
              'where Y.BDCODEMP = FOL.BDCODEMPORIG and Y.BDCODCOL = FOL.BDCODCOLORIG and Y.BDREFTOMADOR = FOt.BDREFTOMADOR and Y.BDORDEM = FOt.BDORDEM '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFTOMADOR having COUNT(*) = 2 and SUM(Y.BDVALVFT) = 0.02) ';

       wsql = wsql||' order by FOL.BDCODEMPORIG,FOL.BDCODCOLORIG,FOt.BDREFTOMADOR,FOt.BDORDEM ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM,FO.BDCODVER,FO.BDVALVFT,FOLN.BDDATAPGTOFT,FOLN.BDDEPFT,VER.BDCLAVER,VER.BDDESCVER,FOLN.BDDATAPROCFT,FOLN.BDHORAPROCFT '||
              'from TEMPRESAS FOL ';
       wsql = wsql||'join vrhf_emp_tverbatomador FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'join VRH_EMP_TTRANSCOL fot on (fot.BDCODEMPDEST = FO.BDCODEMP and fot.BDCODCOLDEST = FO.BDCODCOL) ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhatomador FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFTOMADOR = FO.BDREFTOMADOR and FOLN.BDORDEM = FO.BDORDEM) ';
       wsql = wsql||'left outer join TEMPRESAS TEMP_ORIG on (TEMP_ORIG.BDCODEMP = fot.BDCODEMPORIG) ';
       wsql = wsql||'where FO.BDREFTOMADOR >= '||wrefini||' and FO.BDREFTOMADOR <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';
     
       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       wsql = wsql||' and SUBSTRING(FOL.BDCNPJEMP FROM 1 FOR 10) = SUBSTRING(TEMP_ORIG.BDCNPJEMP FROM 1 FOR 10) ';

       wsql = wsql||' and not exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFTOMADOR, COUNT(*) BDTOT, SUM(Y.BDVALVFT) BDSOMA from VRHF_EMP_TVERBATOMADOR Y '||
              'where Y.BDCODEMP = FO.BDCODEMP and Y.BDCODCOL = FO.BDCODCOL and Y.BDREFTOMADOR = FO.BDREFTOMADOR '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFTOMADOR having COUNT(*) = 2 and SUM(Y.BDVALVFT) = 0.02) ';

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDORDEM ';
     END

  wempatu   = 0;
  wcolatu   = 0;
  wrefatu   = 0;
  wordematu = 0;
  wpagemp   = 0;

  wbaseir    = 0;
  winssn     = 0;
  wir        = 0;
  wdepatu    = 0;
  wdataatu   = NULL;
  wlucropj   = 0;
  wdespmed   = 0;
  wajcus     = 0;
  wpenjud    = 0;
  wpenalim   = 0;
  wprepri    = 0;
  windresc   = 0;
  wvalabo    = 0;
  wrendis    = 0;
  wdrendis   = '';
  wdataproca = NULL;
  whoraproca = NULL;
  wgclass    = '';

  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wref,:wordem,:wcodver,:wvalor,:wdatapgto,:wdep,:wclassif,:wdescver,:wdataproc,:whoraproc DO
  BEGIN
    IF (wempatu = 0) THEN
       wempatu = wcodemp;

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wrefatu = 0) THEN
       wrefatu = wref;

    IF (wordematu = 0) THEN
       wordematu = wordem;

    IF ((wcodemp <> wempatu) OR (wcodcol <> wcolatu) OR (wref <> wrefatu) OR (wordem <> wordematu)) THEN
       BEGIN
         wpagemp        = 0;
         wcodpres       = NULL;
         wdescpres      = NULL;
         wdataresc      = NULL;
         wdatapagresc   = NULL;
         wtipomov       = 0;
         wtipoclassecol = 0;
         EXECUTE PROCEDURE sp_seta_competencia(:wrefatu, NULL, NULL);

         SELECT COALESCE(Y.BDGRUPOCLA,0) FROM vw_vrh_emp_tcolcon_vinc X
         JOIN vrh_base_tclasse Y ON (Y.BDCODCLA = X.BDCODCLA)
         WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu
         INTO :wtipoclassecol;

         IF (wtipoclassecol = 2) THEN   -- pro-labore
            SELECT COALESCE(BDPAGEMPCONTR, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;
         ELSE
            SELECT COALESCE(BDPAGEMP, 0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;

         IF (prpreviaresc = 1) THEN
            BEGIN
              SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END
         ELSE
            BEGIN
              SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
              JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
              WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
            END

         SELECT
         CASE
           WHEN CC.BDCODTPCC IS NULL THEN CC.BDNOMEMP
           WHEN (CC.BDNOMETOM IS NOT NULL) AND (CC.BDNOMETOM <> '') THEN CC.BDNOMETOM
           WHEN (CC.BDNOMCTA IS NOT NULL) AND (CC.BDNOMCTA <> '') THEN CC.BDNOMCTA
           ELSE CC.BDAPECTA END BDNOMCC
         FROM (
           SELECT X.BDCODEMP,X.BDCODCOL,X.BDORDEM,X.bdcodtpcc,Y.bdnomcta,Y.bdapecta,Z.BDNOMETOM,E.bdnomemp
           FROM vrhf_emp_tprepfn X
           JOIN vw_tempresas_ref E ON (E.BDCODEMP = X.BDCODEMP)
           LEFT OUTER JOIN centros_tpcc Y ON (Y.bdcodcentro = X.bdcodcentro AND Y.bdcodtpcc = X.bdcodtpcc)
           LEFT OUTER JOIN vrh_base_tcustom Z ON (Z.bdcodcentro = X.bdcodcentro AND Z.bdcodtpcc = X.bdcodtpcc)
           WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDORDEM = :wordematu
         ) CC INTO :wdesccc;

         IF ((wtipomov < 1) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
            BEGIN
              IF (wdatapagresc IS NOT NULL) THEN
                 BEGIN
                   wdataatu  = wdatapagresc;
                 END
              ELSE
                 BEGIN
                   wdataatu  = wdataresc;
                 END
            END
         ELSE
            BEGIN
              IF (CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) = 12) THEN
                 wdataatu = CAST((CAST((CAST((SUBSTRING(wrefatu FROM 1 FOR 4)) AS INTEGER) + 1) AS VARCHAR(4))||'-01-01') AS DATE);
              ELSE
              IF (CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) < 9) THEN
                 wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-0'||CAST((CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(1))||'-01') AS DATE);
              ELSE
                 wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-'||CAST((CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(2))||'-01') AS DATE);
     
              IF (wpagemp = 0) THEN -- mês seguinte
                 BEGIN
                   wsind = NULL;
                   wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                   SELECT BDCODSINTRAB FROM VW_VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wsind;
     
                   wi = 1;
                   WHILE (wi <= 5) DO
                     BEGIN
                       SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wempatu, :wdataatu, :wrefpagto, :wsind) INTO wferiado;
                       IF (EXTRACT(WEEKDAY FROM wdataatu) IN (1,2,3,4,5,6) AND wferiado = 'FALSE') THEN
                          wi = wi + 1;
     
                       IF (wi <= 5) THEN
                          wdataatu = wdataatu + 1;
                     END
                 END
              ELSE
                 BEGIN
                   wdataatu = wdataatu - 1;
                   wi = 1;
                   WHILE (wi = 1) DO
                     BEGIN
                       SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wempatu, :wdataatu, :wrefatu, :wsind) INTO wferiado;
                       IF (EXTRACT(WEEKDAY FROM wdataatu) IN (1,2,3,4,5,6) AND wferiado = 'FALSE') THEN
                          wi = 0;
     
                       IF (wi = 1) THEN
                          wdataatu = wdataatu - 1;
                     END
                 END
            END

         wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

         IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
            BEGIN
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREF            = wrefatu;
              bdordem          = wordematu;
              BDREFPAG         = wrefpagto;
              BDRENDTRIBUTAVEL = wbaseir;
              BDINSS           = winssn;
              BDIR             = wir;

              IF (wbaseir + winssn + wir > 0)  THEN
                 BDDEP = wdepatu;
              ELSE
                 BDDEP = 0;

              BDLUCROPJ        = wlucropj;
              BDDESPMED        = wdespmed;
              BDAJCUSTOS       = wajcus;
              BDPENJUD         = wpenjud;
              BDPENALIM        = wpenalim;
              BDPREVPRIV       = wprepri;
              BDINDRESC        = windresc;
              BDVALABO         = wvalabo;
              BDRENDISENTOS    = wrendis;
              BDDRENDISENTOS   = wdrendis;
              BDDATAPGTO       = wdataatu;
              BDDATAPROC       = wdataproca;
              BDHORAPROC       = whoraproca;

              IF (wdataresc IS NOT NULL) THEN
                 BEGIN
                   BDTIPO    = 100;    -- Folha normal rescisão
                   BDINFADIC = wordematu||' - '||wdesccc||'; '||wcodpres||' - '||wdescpres;
                 END
              ELSE
                 BEGIN
                   BDTIPO    = 0;    -- Folha normal
                   BDINFADIC = wordematu||' - '||wdesccc;
                 END

              SUSPEND;
            END

         wempatu   = wcodemp;
         wcolatu   = wcodcol;
         wrefatu   = wref;
         wordematu = wordem;

         wbaseir    = 0;
         winssn     = 0;
         wir        = 0;
         wdepatu    = 0;
         wdataatu   = NULL;
         wlucropj   = 0;
         wdespmed   = 0;
         wajcus     = 0;
         wpenjud    = 0;
         wpenalim   = 0;
         wprepri    = 0;
         windresc   = 0;
         wvalabo    = 0;
         wrendis    = 0;
         wdrendis   = '';
         wgclass    = '';
       END

    -- soma as bases
    EXECUTE PROCEDURE sp_seta_competencia(:wref, NULL, NULL);
    SELECT BDTIPOCODVER, COALESCE(BDIRVER,0), BDRENDISENTOIRVER FROM vw_vrh_base_tverbas_ref WHERE BDCODVER = :wcodver INTO :wtipocodver,:wirver,:wrendisentover;

--    if (wtipocodver <= 1) then
       begin
         IF (wirver = 1) THEN -- IR Folha normal
            BEGIN
              IF (wtipocodver = 0) THEN   -- provento
                 wbaseir = wbaseir + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN   -- desconto
                 BEGIN
                   --                                      INSS                                              Obrigações IR
                   IF (SUBSTRING(wclassif FROM 1 FOR 7) <> '9.010.0' AND SUBSTRING(wclassif FROM 1 FOR 5) <> '0.030') THEN
                      wbaseir = wbaseir - wvalor;
                 END
            END
     
         --                                     INSS folha normal
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.0.0') THEN
            winssn = winssn + wvalor;
         --                                     IR folha normal
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '9.010.1.0') THEN
            wir = wir + wvalor;
         --                                     Lucro pessoa jurídica
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.2') THEN
            wlucropj = wlucropj + wvalor;
         --                                     Despesas médicas                                     Complemento de despesas médicas
         IF ((SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.0') OR (SUBSTRING(wclassif FROM 1 FOR 9) = '0.420.0.2')) THEN
            wdespmed = wdespmed + wvalor;
         --                                     Diárias
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.0' AND wirver = 0) THEN
            wajcus = wajcus + wvalor;
         --                                     Ajuda de custos
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.040.0.1' AND wirver = 0) THEN
            wajcus = wajcus + wvalor;
         --                                     Pensões judiciais
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.0') THEN
            wpenjud = wpenjud + wvalor;
         --                                     Pensões alimentícias
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.0.1') THEN
            wpenalim = wpenalim + wvalor;
         --                                     Previdência privada
         IF (SUBSTRING(wclassif FROM 1 FOR 9) = '0.030.1.2') THEN
            wprepri = wprepri + wvalor;
     
         IF ((SUBSTRING(wclassif FROM 1 FOR 7) = '7.001.3') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '7.020') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '7.021')) THEN
            BEGIN
              IF (wtipocodver in (0, 2)) THEN   -- Provento
                 windresc = windresc + wvalor;
              ELSE
              IF (wtipocodver in (1, 3)) THEN   -- Desconto
                 windresc = windresc - wvalor;
            END
     
         --                                      Abono pec.                                      1/3 abono pec.                                  Abono pec. dobro                                1/3 abono pec.
         IF ((SUBSTRING(wclassif FROM 1 FOR 5) = '3.003') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.004') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.007') OR (SUBSTRING(wclassif FROM 1 FOR 5) = '3.008') OR
         --                                      Complemento de abono pecuniário                  Compl. 1/3 abono pecuniário
             (SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.2') OR (SUBSTRING(wclassif FROM 1 FOR 7) = '0.210.3')) THEN
            wvalabo = wvalabo + wvalor;
         -- Rendimentos isentos
         IF (UPPER(wrendisentover) = 'TRUE') THEN
            BEGIN
              wrendis = wrendis + wvalor;
     
              wi = 0;
              SELECT POS FROM pos(SUBSTRING(:wclassif FROM 1 FOR 5), :wgclass) INTO :wi;
     
              IF (wi = 0) THEN
                 BEGIN
                   wdescver2 = '';
                   SELECT FIRST 1 BDDESCVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = SUBSTRING(:wclassif FROM 1 FOR 5) INTO wdescver2;
                   wgclass = wgclass||';'||SUBSTRING(:wclassif FROM 1 FOR 5);
     
                   IF (wdrendis <> '') THEN
                      wdrendis = wdrendis ||', ';
     
                   wdrendis = SUBSTRING(wdrendis||wdescver2 FROM 1 FOR 200);
                 END
            END
       end

    wdepatu = wdep;
    wdataatu = wdatapgto;
    wdataproca = wdataproc;
    whoraproca = whoraproc;
  END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wordematu <> 0) THEN
     BEGIN
       wpagemp        = 0;
       wcodpres       = NULL;
       wdescpres      = NULL;
       wdataresc      = NULL;
       wdatapagresc   = NULL;
       wtipomov       = 0;
       wtipoclassecol = 0;
       EXECUTE PROCEDURE sp_seta_competencia(:wrefatu, NULL, NULL);

       SELECT COALESCE(Y.BDGRUPOCLA,0) FROM vw_vrh_emp_tcolcon_vinc X
       JOIN vrh_base_tclasse Y ON (Y.BDCODCLA = X.BDCODCLA)
       WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu
       INTO :wtipoclassecol;

       IF (wtipoclassecol = 2) THEN    -- pro-labore
          SELECT COALESCE(BDPAGEMPCONTR,0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;
       ELSE
          SELECT COALESCE(BDPAGEMP,0) FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wpagemp;

       IF (prpreviaresc = 1) THEN
          BEGIN
            SELECT X.bddatarescisaoprev,X.bddatapagrescisaoprev,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao_previa X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.bdrefrescisaoprev = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END
       ELSE
          BEGIN
            SELECT X.BDDATARESCISAO,X.BDDATAPAGRESCISAO,X.bdcodpres,Y.bddescpres,COALESCE(Y.bdtipomov,0) FROM vrh_emp_trescisao X
            JOIN vrh_base_tprepresc Y ON (Y.bdcodpres = X.bdcodpres)
            WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDREFRESCISAO = :wrefatu INTO :wdataresc,:wdatapagresc,:wcodpres,:wdescpres,:wtipomov;
          END

       SELECT
       CASE
         WHEN CC.BDCODTPCC IS NULL THEN CC.BDNOMEMP
         WHEN (CC.BDNOMETOM IS NOT NULL) AND (CC.BDNOMETOM <> '') THEN CC.BDNOMETOM
         WHEN (CC.BDNOMCTA IS NOT NULL) AND (CC.BDNOMCTA <> '') THEN CC.BDNOMCTA
         ELSE CC.BDAPECTA END BDNOMCC
       FROM (
         SELECT X.BDCODEMP,X.BDCODCOL,X.BDORDEM,X.bdcodtpcc,Y.bdnomcta,Y.bdapecta,Z.BDNOMETOM,E.bdnomemp
         FROM vrhf_emp_tprepfn X
         JOIN vw_tempresas_ref E ON (E.BDCODEMP = X.BDCODEMP)
         LEFT OUTER JOIN centros_tpcc Y ON (Y.bdcodcentro = X.bdcodcentro AND Y.bdcodtpcc = X.bdcodtpcc)
         LEFT OUTER JOIN vrh_base_tcustom Z ON (Z.bdcodcentro = X.bdcodcentro AND Z.bdcodtpcc = X.bdcodtpcc)
         WHERE X.BDCODEMP = :wempatu AND X.BDCODCOL = :wcolatu AND X.BDORDEM = :wordematu
       ) CC INTO :wdesccc;

       IF ((wtipomov = 0) AND ((wdatapagresc IS NOT NULL) OR (wdataresc IS NOT NULL))) THEN
          BEGIN
            IF (wdatapagresc IS NOT NULL) THEN
               BEGIN
                 wdataatu  = wdatapagresc;
               END
            ELSE
               BEGIN
                 wdataatu  = wdataresc;
               END
          END
       ELSE
          BEGIN
            IF (CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) = 12) THEN
               wdataatu = CAST((CAST((CAST((SUBSTRING(wrefatu FROM 1 FOR 4)) AS INTEGER) + 1) AS VARCHAR(4))||'-01-01') AS DATE);
            ELSE
            IF (CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) < 9) THEN
               wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-0'||CAST((CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(1))||'-01') AS DATE);
            ELSE
               wdataatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'-'||CAST((CAST((SUBSTRING(wrefatu FROM 5 FOR 2)) AS INTEGER) + 1) AS VARCHAR(2))||'-01') AS DATE);
   
            IF (wpagemp = 0) THEN -- mês seguinte
               BEGIN
                 wsind = NULL;
                 wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                 SELECT BDCODSINTRAB FROM VW_VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wsind;
   
                 wi = 1;
                 WHILE (wi <= 5) DO
                   BEGIN
                     SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wempatu, :wdataatu, :wrefpagto, :wsind) INTO wferiado;
                     IF (EXTRACT(WEEKDAY FROM wdataatu) IN (1,2,3,4,5,6) AND wferiado = 'FALSE') THEN
                        wi = wi + 1;
   
                     IF (wi <= 5) THEN
                        wdataatu = wdataatu + 1;
                   END
               END
            ELSE
               BEGIN
                 wdataatu = wdataatu - 1;
                 wi = 1;
                 WHILE (wi = 1) DO
                   BEGIN
                     SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wempatu, :wdataatu, :wrefatu, :wsind) INTO wferiado;
                     IF (EXTRACT(WEEKDAY FROM wdataatu) IN (1,2,3,4,5,6) AND wferiado = 'FALSE') THEN
                        wi = 0;
   
                     IF (wi = 1) THEN
                        wdataatu = wdataatu - 1;
                   END
               END
          END

       wrefpagto = CAST((SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataatu AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       IF (wrefpagto >= prrefini AND wrefpagto <= prreffim) THEN
          BEGIN
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREF            = wrefatu;
            bdordem          = wordematu;
            BDREFPAG         = wrefpagto;
            BDRENDTRIBUTAVEL = wbaseir;
            BDINSS           = winssn;
            BDIR             = wir;

            IF (wbaseir + winssn + wir > 0)  THEN
               BDDEP = wdepatu;
            ELSE
               BDDEP = 0;

            BDLUCROPJ        = wlucropj;
            BDDESPMED        = wdespmed;
            BDAJCUSTOS       = wajcus;
            BDPENJUD         = wpenjud;
            BDPENALIM        = wpenalim;
            BDPREVPRIV       = wprepri;
            BDINDRESC        = windresc;
            BDVALABO         = wvalabo;
            BDRENDISENTOS    = wrendis;
            BDDRENDISENTOS   = wdrendis;
            BDDATAPGTO       = wdataatu;
            BDDATAPROC       = wdataproca;
            BDHORAPROC       = whoraproca;

            IF (wdataresc IS NOT NULL) THEN
               BEGIN
                 BDTIPO    = 100;    -- Folha normal rescisão
                 BDINFADIC = wordematu||' - '||wdesccc||'; '||wcodpres||' - '||wdescpres;
               END
            ELSE
               BEGIN
                 BDTIPO    = 0;    -- Folha normal
                 BDINFADIC = wordematu||' - '||wdesccc;
               END
            SUSPEND;
          END
     END


  /*
      DADOS IMPORTADOS OU CADASTRADOS NA FICHA
  */

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX ';
       wsql = wsql||' from (select BDCODEMPORIG BDCODEMP, BDCODCOLORIG BDCODCOL, BDCODEMPDEST, BDCODCOLDEST from VRH_EMP_TTRANSCOL) FOL ';
       wsql = wsql||'join VRHF_EMP_TFICHAIRRF FO on (FO.BDCODEMP = FOL.BDCODEMP and FO.BDCODCOL = FOL.BDCODCOL) ';
       wsql = wsql||'where FO.BDTIPOCALCFIR in (9000,9001) and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    '((not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and '||
                                  'FN.BDREFFN = FO.BDREFFIR) and '||
                      'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = FOL.BDCODEMP and FT.BDCODCOL = FOL.BDCODCOL and '||
                                  'FT.BDREFTOMADOR = FO.BDREFFIR)) or ( ';

       wsql = wsql||' exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VW_UNION_FN_TOMADOR_VERBAS Y '||
              'where Y.BDCODEMP = FOL.BDCODEMP and Y.BDCODCOL = FOL.BDCODCOL and Y.BDREFFN = FO.BDREFFIR '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02))) ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FO.BDREFFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX ';
       wsql = wsql||'from TEMPRESAS FOL ';
       wsql = wsql||'join VRHF_EMP_TFICHAIRRF FO on (FO.BDCODEMP = FOL.BDCODEMP) ';
       wsql = wsql||'join (select BDCODEMPORIG, BDCODCOLORIG, BDCODEMPDEST BDCODEMP, BDCODCOLDEST BDCODCOL from VRH_EMP_TTRANSCOL) XX on (XX.BDCODEMP = FO.BDCODEMP and XX.BDCODCOL = FO.BDCODCOL) ';
       wsql = wsql||'where FO.BDTIPOCALCFIR in (9000,9001) and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
                    '((not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = FO.BDCODEMP and FN.BDCODCOL = FO.BDCODCOL and '||
                                  'FN.BDREFFN = FO.BDREFFIR) and '||
                      'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = FO.BDCODEMP and FT.BDCODCOL = FO.BDCODCOL and '||
                                  'FT.BDREFTOMADOR = FO.BDREFFIR)) or ( ';
     
       wsql = wsql||' exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VW_UNION_FN_TOMADOR_VERBAS Y '||
              'where Y.BDCODEMP = FO.BDCODEMP and Y.BDCODCOL = FO.BDCODCOL and Y.BDREFFN = FO.BDREFFIR '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02))) ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';
     
       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFFIR ';
     END

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDREFPAG,
    :BDTIPO,
    :BDRENDTRIBUTAVEL,
    :BDINSS,
    :BDIR,
    :BDDEP,
    :BDLUCROPJ,
    :BDDESPMED,
    :BDAJCUSTOS,
    :BDPENJUD,
    :BDPENALIM,
    :BDPREVPRIV,
    :BDINDRESC,
    :BDVALABO,
    :BDRENDISENTOS,
    :BDDRENDISENTOS,
    :BDDATAPGTO,
    :BDINFADIC
  DO
  BEGIN
    BDDATAPROC  = BDDATAPGTO;
    BDHORAPROC  = '00:00:00';
    SUSPEND;
  END
END^

/* Restore proc. body: SP_VRHF_DADOS_PIS_13 */
ALTER PROCEDURE SP_VRHF_DADOS_PIS_13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '')
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODVER integer,
    BDBASEPISFE numeric(15,6),
    BDBASEPIS13 numeric(15,6),
    BDBASEPISFN numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCTALON varchar(20))
as
declare variable WTIPOVER integer;
declare variable WBASEPIS varchar(10);
declare variable WSQL varchar(5000);
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
BEGIN
  /* Procedure Text */
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREF13,FOL.BDCODVER,FOL.BDVALV13,VER.BDCLAVER,CC.BDCODCENTRO,CEN.BDCODTPCC,CEN.BDCTALON '||
              'from vrhf_emp_tverba_13_rat FOL ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_t13sal_rat FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREF13 = FOL.BDREF13 and FOLN.BDCHAVE = FOL.BDCHAVE) ';
       wsql = wsql||'left outer join VRHF_EMP_TPREPFN CC on (CC.BDCODEMP = FOLN.BDCODEMP and CC.BDCODCOL = FOLN.BDCODCOL and CC.BDORDEM = FOLN.BDORDEM) ';
       wsql = wsql||'left outer join CENTROS_TPCC CEN on (CEN.BDCODCENTRO = CC.BDCODCENTRO and CEN.BDCODTPCC = CC.BDCODTPCC) ';
       wsql = wsql||'where FOL.BDREF13 >= '||prrefini||' and FOL.BDREF13 <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREF13 ';
     END
  ELSE
     BEGIN
       wsql = 'select '||
              'FOL.BDCODEMP,FO.BDCODCOL,FO.BDREF13,FO.BDCODVER,FO.BDVALV13,VER.BDCLAVER,CC.BDCODCENTRO,CEN.BDCODTPCC,CEN.BDCTALON '||
              'from TEMPRESAS FOL '||
              'join vrhf_emp_tverba_13_rat FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) '||
              'join vrhf_emp_t13sal_rat FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREF13 = FO.BDREF13 and FOLN.BDCHAVE = FO.BDCHAVE) '||
              'left outer join VRHF_EMP_TPREPFN CC on (CC.BDCODEMP = FOLN.BDCODEMP and CC.BDCODCOL = FOLN.BDCODCOL and CC.BDORDEM = FOLN.BDORDEM) '||
              'left outer join CENTROS_TPCC CEN on (CEN.BDCODCENTRO = CC.BDCODCENTRO and CEN.BDCODTPCC = CC.BDCODTPCC) '||
              'where FO.BDREF13 >= '||prrefini||' and FO.BDREF13 <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREF13 ';
     END

--  suspend;

  FOR EXECUTE STATEMENT wSql INTO :bdcodemp,:bdcodcol,:bdref,:bdcodver,:wvalor,:wclassif, :bdcodcentro, :bdcodtpcc, :bdctalon DO
    BEGIN
      EXECUTE PROCEDURE sp_seta_competencia(:bdref,NULL,NULL);
      wBasePis = 'FALSE';
      SELECT COALESCE(BDPISVER,'FALSE'),BDTIPOCODVER FROM VW_VERBAS_REF_ATUAL WHERE bdcodver = :bdcodver INTO wbasepis,WTIPOVER;

      IF (wtipover IN (0,1)) THEN
         BEGIN
           IF ((UPPER(wbasepis) = 'TRUE') OR (UPPER(wbasepis) = 'T')) THEN
              BEGIN
                IF (wtipover = 1) THEN
                   wvalor = wvalor * -1;

                 bdbasepis13 = 0;
                 bdbasepisfe = 0;
                 bdbasepisfn = 0;

                -- Verifica se a verba é base 13º
                IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('4','5','6')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.200','7.050','7.060','7.061','7.070','7.071','7.080'))) THEN
                   bdbasepis13 = wvalor;
                -- Verifica se a verba é base FEr
                ELSE IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('3')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.100','0.110','0.120','0.130','0.140','0.150','0.160',
                                                         '0.170','0.180','0.190','7.010','7.011','7.012','7.020','7.021',
                                                         '7.030','7.031','7.032','7.033'))) THEN
                   bdbasepisfe = wvalor;
                ELSE -- Senão é base FN
                    bdbasepisfn = wvalor;

                SUSPEND;
              END
         END

    END

END
^

/* Restore proc. body: SP_VRHF_DADOS_PIS_C13 */
ALTER PROCEDURE SP_VRHF_DADOS_PIS_C13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '')
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODVER integer,
    BDBASEPISFE numeric(15,6),
    BDBASEPIS13 numeric(15,6),
    BDBASEPISFN numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCTALON varchar(20))
as
declare variable WTIPOVER integer;
declare variable WBASEPIS varchar(10);
declare variable WSQL varchar(5000);
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WDATAAUX varchar(10);
BEGIN
  /* Procedure Text */
  select first 1 ULTDIA
  from ULTIMO_DIA_MES(CAST(SUBSTRING(:PRREFINI FROM 5 FOR 2) AS SMALLINT), CAST(SUBSTRING(:PRREFINI FROM 1 FOR 4) AS INTEGER))
  into :WDATAAUX;
  WDATAAUX = SUBSTRING(:PRREFINI FROM 5 FOR 2)||'-'||lpad(WDATAAUX,  2, '0')||'-'||SUBSTRING(:PRREFINI FROM 1 FOR 4);

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFC13,FOL.BDCODVER,FOL.BDVALVC13,VER.BDCLAVER, '||
              'CC.BDCODCENTRO, CC.BDCODTPCC, CC.BDCTALON '||
              'from vrhf_emp_tverbac13 FOL ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tc13sal FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFC13 = FOL.BDREFC13) ';
       wsql = wsql||'LEFT OUTER JOIN SP_VRH_CC_DATA(FOL.BDCODEMP,FOL.BDCODCOL,CAST('''||WDATAAUX||''' AS DATE)) CCCOL ON (CCCOL.BDCODEMP = FOL.BDCODEMP AND CCCOL.BDCODCOL = FOL.BDCODCOL) ';
       wsql = wsql||'LEFT OUTER JOIN CENTROS_TPCC CC ON (CC.BDCODCENTRO = CCCOL.BDCODCENTRO AND CC.BDCODTPCC = CCCOL.BDCODTPCC) ';
       wsql = wsql||'where FOL.BDREFC13 >= '||prrefini||' and FOL.BDREFC13 <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFC13 ';
     END
  ELSE
     BEGIN
       wsql = 'select '||
              'FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFC13,FO.BDCODVER,FO.BDVALVC13,VER.BDCLAVER, '||
              'CC.BDCODCENTRO, CC.BDCODTPCC, CC.BDCTALON '||
              'from TEMPRESAS FOL '||
              'join vrhf_emp_tverbac13 FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) '||
              'join vrhf_emp_tc13sal FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFC13 = FO.BDREFC13) '||
              'LEFT OUTER JOIN SP_VRH_CC_DATA(FO.BDCODEMP,FO.BDCODCOL,CAST('''||WDATAAUX||''' AS DATE)) CCCOL ON (CCCOL.BDCODEMP = FO.BDCODEMP AND CCCOL.BDCODCOL = FO.BDCODCOL) '||
              'LEFT OUTER JOIN CENTROS_TPCC CC ON (CC.BDCODCENTRO = CCCOL.BDCODCENTRO AND CC.BDCODTPCC = CCCOL.BDCODTPCC) ';
       wsql = wsql||'where FO.BDREFC13 >= '||prrefini||' and FO.BDREFC13 <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREF13 ';
     END

--  suspend;

  FOR EXECUTE STATEMENT wSql INTO :bdcodemp,:bdcodcol,:bdref,:bdcodver,:wvalor,:wclassif,:bdcodcentro,:bdcodtpcc,:bdctalon DO
    BEGIN
      EXECUTE PROCEDURE sp_seta_competencia(:bdref,NULL,NULL);
      wBasePis = 'FALSE';
      SELECT COALESCE(BDPISVER,'FALSE'),BDTIPOCODVER FROM VW_VERBAS_REF_ATUAL WHERE bdcodver = :bdcodver INTO wbasepis,WTIPOVER;

      IF (wtipover IN (0,1)) THEN
         BEGIN
           IF ((UPPER(wbasepis) = 'TRUE') OR (UPPER(wbasepis) = 'T')) THEN
              BEGIN
                IF (wtipover = 1) THEN
                   wvalor = wvalor * -1;

                 bdbasepis13 = 0;
                 bdbasepisfe = 0;
                 bdbasepisfn = 0;

                -- Verifica se a verba é base 13º
                IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('4','5','6')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.200','7.050','7.060','7.061','7.070','7.071','7.080'))) THEN
                   bdbasepis13 = wvalor;
                -- Verifica se a verba é base FEr
                ELSE IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('3')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.100','0.110','0.120','0.130','0.140','0.150','0.160',
                                                         '0.170','0.180','0.190','7.010','7.011','7.012','7.020','7.021',
                                                         '7.030','7.031','7.032','7.033'))) THEN
                   bdbasepisfe = wvalor;
                ELSE -- Senão é base FN
                    bdbasepisfn = wvalor;

                SUSPEND;
              END
         END

    END

END
^

/* Restore proc. body: SP_VRHF_DADOS_PIS_FC */
CREATE OR ALTER procedure SP_VRHF_DADOS_PIS_FC (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '')
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODVER integer,
    BDBASEPISFE numeric(15,6),
    BDBASEPIS13 numeric(15,6),
    BDBASEPISFN numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCTALON varchar(20))
as
declare variable WTIPOVER integer;
declare variable WBASEPIS varchar(10);
declare variable WSQL varchar(5000);
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
BEGIN
  /* Procedure Text */
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFCOMP,FOL.BDCODVER,FOL.BDVALVFC,VER.BDCLAVER '||
              'from vrhf_emp_tverbafc FOL ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfolhacomp FOLN on (fol.BDREFFC = foln.BDREFFC and FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFfn = FOL.BDREFfn) ';
       wsql = wsql||'where FOL.BDREFCOMP >= '||prrefini||' and FOL.BDREFCOMP <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFCOMP ';
     END
  ELSE
     BEGIN
       wsql = 'select '||
                'FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFCOMP,FO.BDCODVER,FO.BDVALVFC,VER.BDCLAVER '||
              'from TEMPRESAS FOL '||
              'join vrhf_emp_tverbafc FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) '||
              'join vrhf_emp_tfolhacomp FOLN on (fo.BDREFFC = foln.BDREFFC and foln.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFfn = FO.BDREFfn) ';
       wsql = wsql||'where FO.BDREFCOMP >= '||prrefini||' and FO.BDREFCOMP <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFCOMP ';
     END

--  suspend;

  bdcodcentro = NULL;
  bdcodtpcc = NULL;
  bdctalon = NULL;

  FOR EXECUTE STATEMENT wSql INTO :bdcodemp,:bdcodcol,:bdref,:bdcodver,:wvalor,:wclassif DO
    BEGIN
      EXECUTE PROCEDURE sp_seta_competencia(:bdref,NULL,NULL);
      wBasePis = 'FALSE';
      SELECT COALESCE(BDPISVER,'FALSE'),BDTIPOCODVER FROM VW_VERBAS_REF_ATUAL WHERE bdcodver = :bdcodver INTO wbasepis,WTIPOVER;

      IF (wtipover IN (0,1)) THEN
         BEGIN
           IF ((UPPER(wbasepis) = 'TRUE') OR (UPPER(wbasepis) = 'T')) THEN
              BEGIN
                IF (wtipover = 1) THEN
                   wvalor = wvalor * -1;

                 bdbasepis13 = 0;
                 bdbasepisfe = 0;
                 bdbasepisfn = 0;

                -- Verifica se a verba é base 13º
                IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('4','5','6')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.200','7.050','7.060','7.061','7.070','7.071','7.080'))) THEN
                   bdbasepis13 = wvalor;
                -- Verifica se a verba é base FEr
                ELSE IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('3')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.100','0.110','0.120','0.130','0.140','0.150','0.160',
                                                         '0.170','0.180','0.190','7.010','7.011','7.012','7.020','7.021',
                                                         '7.030','7.031','7.032','7.033'))) THEN
                   bdbasepisfe = wvalor;
                ELSE -- Senão é base FN
                    bdbasepisfn = wvalor;

                SUSPEND;
              END
         END

    END

   /******************************************************/
   /******************************************************/
   /******************************************************/
   /******************************************************/
   /* Folha por tomador */
   /******************************************************/
   /******************************************************/
   /******************************************************/
   /******************************************************/

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFCOMP,FOL.BDCODVER,FOL.BDVALVFC,VER.BDCLAVER,prep.BDCODCENTRO,prep.bdcodtpcc, cen.bdctalon '||
              'from vrhf_emp_tverbafctomador FOL ';
       wsql = wsql||'join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join vrhf_emp_tfoltomcomp FOLN on (fol.BDREFFC = foln.BDREFFC and FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFTOMADOR = FOL.BDREFTOMADOR and fol.bdordem = foln.bdordem) ';
       wsql = wsql||'join VRHF_EMP_TPREPFN prep on (FOLN.BDCODEMP = prep.BDCODEMP and FOLN.BDCODCOL = prep.BDCODCOL and prep.bdordem = foln.bdordem) ';
       wsql = wsql||'left outer join CENTROS_TPCC cen on (cen.BDCODCENTRO = prep.BDCODCENTRO and cen.BDCODTPCC = prep.bdcodtpcc) ';
       wsql = wsql||'where FOL.BDREFCOMP >= '||prrefini||' and FOL.BDREFCOMP <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFCOMP ';
     END
  ELSE
     BEGIN
       wsql = 'select '||
                'FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFCOMP,FO.BDCODVER,FO.BDVALVFC,VER.BDCLAVER,prep.BDCODCENTRO,prep.bdcodtpcc, cen.bdctalon '||
              'from TEMPRESAS FOL '||
              'join VRHF_EMP_TVERBAFCTOMADOR FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) '||
              'join vrhf_emp_tfoltomcomp FOLN on (fo.BDREFFC = foln.BDREFFC and FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFTOMADOR = FO.BDREFTOMADOR and fo.bdordem = foln.bdordem) ';
       wsql = wsql||'join VRHF_EMP_TPREPFN prep on (FOLN.BDCODEMP = prep.BDCODEMP and FOLN.BDCODCOL = prep.BDCODCOL and prep.bdordem = foln.bdordem) ';
       wsql = wsql||'left outer join CENTROS_TPCC cen on (cen.BDCODCENTRO = prep.BDCODCENTRO and cen.BDCODTPCC = prep.bdcodtpcc) ';
       wsql = wsql||'where FO.BDREFCOMP >= '||prrefini||' and FO.BDREFCOMP <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFCOMP ';
     END

--  suspend;

  bdcodcentro = NULL;
  bdcodtpcc = NULL;
  bdctalon = NULL;

  FOR EXECUTE STATEMENT wSql INTO :bdcodemp,:bdcodcol,:bdref,:bdcodver,:wvalor,:wclassif,:BDCODCENTRO,:bdcodtpcc, :bdctalon DO
    BEGIN
      EXECUTE PROCEDURE sp_seta_competencia(:bdref,NULL,NULL);
      wBasePis = 'FALSE';
      SELECT COALESCE(BDPISVER,'FALSE'),BDTIPOCODVER FROM VW_VERBAS_REF_ATUAL WHERE bdcodver = :bdcodver INTO wbasepis,WTIPOVER;

      IF (wtipover IN (0,1)) THEN
         BEGIN
           IF ((UPPER(wbasepis) = 'TRUE') OR (UPPER(wbasepis) = 'T')) THEN
              BEGIN
                IF (wtipover = 1) THEN
                   wvalor = wvalor * -1;

                 bdbasepis13 = 0;
                 bdbasepisfe = 0;
                 bdbasepisfn = 0;

                -- Verifica se a verba é base 13º
                IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('4','5','6')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.200','7.050','7.060','7.061','7.070','7.071','7.080'))) THEN
                   bdbasepis13 = wvalor;
                -- Verifica se a verba é base FEr
                ELSE IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('3')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.100','0.110','0.120','0.130','0.140','0.150','0.160',
                                                         '0.170','0.180','0.190','7.010','7.011','7.012','7.020','7.021',
                                                         '7.030','7.031','7.032','7.033'))) THEN
                   bdbasepisfe = wvalor;
                ELSE -- Senão é base FN
                    bdbasepisfn = wvalor;

                SUSPEND;
              END
         END

    END

END
^

/* Restore proc. body: SP_VRHF_DADOS_FGTS_FN */
CREATE OR ALTER procedure SP_VRHF_DADOS_FGTS_FN (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer,
    PRCODMATRIZ varchar(15000))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBFGTSRESC numeric(18,6),
    BDFGTSRESC numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDBFGTS13RESC numeric(18,6),
    BDFGTS13RESC numeric(18,6),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBFGTSINDESOCIAL numeric(18,6),
    BDFGTSINDESOCIAL numeric(18,6),
    BDBFGTSMESESOCIAL numeric(18,6),
    BDFGTSMESESOCIAL numeric(18,6),
    BDBFGTS13ESOCIAL numeric(18,6),
    BDFGTS13ESOCIAL numeric(18,6))
as
declare variable WSQL varchar(32700);
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WBASEFGTS numeric(18,6);
declare variable WVALORFGTS numeric(18,6);
declare variable WBASEFGTS13 numeric(18,6);
declare variable WVALORFGTS13 numeric(18,6);
declare variable WBASEFGTSRESC numeric(18,6);
declare variable WVALORFGTSRESC numeric(18,6);
declare variable WBASEFGTS13RESC numeric(18,6);
declare variable WVALORFGTS13RESC numeric(18,6);
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WORDEM integer;
declare variable WBASEFGTSINDESOCIAL numeric(18,6);
declare variable WVALORFGTSINDESOCIAL numeric(18,6);
declare variable WBASEFGTSMESESOCIAL numeric(18,6);
declare variable WVALORFGTSMESESOCIAL numeric(18,6);
declare variable WBASEFGTS13ESOCIAL numeric(18,6);
declare variable WVALORFGTS13ESOCIAL numeric(18,6);
begin
/*
  FOLHA NORMAL
*/

  WUSARTMP_EMP_SELECT = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
    WUSARTMP_EMP_SELECT = 1;

  IF (prpuxarfiliais = 0) THEN
    BEGIN
      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDBFGTSFN'
                 || '   else 0'
                 || ' end BDBFGTSFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDFGTSFN'
                 || '   else 0'
                 || ' end BDFGTSFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDBFGTSFN'
                 || '   else 0'
                 || ' end BDBFGTSRESCFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDFGTSFN'
                 || '   else 0'
                 || ' end BDFGTSRESCFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDBFGTS13FN'
                 || '   else 0'
                 || ' end BDBFGTS13FN,'
                 || ' case'
                 || '   when (Resc.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDFGTS13FN'
                 || '   else 0'
                 || ' end BDFGTS13FN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDBFGTS13FN'
                 || '   else 0'
                 || ' end BDBFGTS13RESCFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDFGTS13FN'
                 || '   else 0'
                 || ' end BDFGTS13RESCFN,'
                 || ' FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, '
                 || ' FOL.BDBASEFGTS13ESOCIAL,  FOL.BDVALORFGTS13ESOCIAL, '
                 || ' FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, '
                 || ' FOL.BDDATAPROCFN, FOL.BDHORAPROCFN, 0 BDORDEMFN ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from (select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFN, FN.BDBFGTSFN, FN.BDFGTSFN, FN.BDBFGTS13FN, FN.BDFGTS13FN, FN.BDDATAPROCFN, FN.BDHORAPROCFN, FN.BDBASEFGTSINDESOCIAL, FN.BDVALORFGTSINDESOCIAL, FN.BDBASEFGTSMESESOCIAL, FN.BDVALORFGTSMESESOCIAL, FN.BDBASEFGTS13ESOCIAL, FN.BDVALORFGTS13ESOCIAL from VRHF_EMP_TFOLHANORMAL FN' || ' inner join TMP_EMPRESAS_SELECT EMPSEL on EMPSEL.BDCODEMP = FN.BDCODEMP ) FOL ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from VRHF_EMP_TFOLHANORMAL FOL ';
        END

      wsql = wsql || ' left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >=' || prrefini || ' ) ';
      wsql = wsql || ' where (FOL.BDREFFN >= ' || prrefini || ' and FOL.BDREFFN <=' || prreffim || ')';

      IF((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
        wsql = wsql || ' and ' || prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN ';
    END
  ELSE
    BEGIN
      wsql = ' select EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN,'
                 || ' case'
                 || '   when (Resc.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDBFGTSFN'
                 || '   else 0'
                 || ' end BDBFGTSFN,'
                 || ' case'
                 || '   when (Resc.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDFGTSFN'
                 || '   else 0'
                 || ' end BDFGTSFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDBFGTSFN'
                 || '   else 0'
                 || ' end BDBFGTSRESCFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDFGTSFN'
                 || '   else 0'
                 || ' end BDFGTSRESCFN,'
                 || ' case'
                 || '   when (Resc.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDBFGTS13FN'
                 || '   else 0'
                 || ' end BDBFGTS13FN,'
                 || ' case'
                 || '   when (Resc.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDFGTS13FN'
                 || '   else 0'
                 || ' end BDFGTS13FN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDBFGTS13FN'
                 || '   else 0'
                 || ' end BDBFGTS13RESCFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDFGTS13FN'
                 || '   else 0'
                 || ' end BDFGTS13RESCFN,'
                 || ' FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, '
                 || ' FOL.BDBASEFGTS13ESOCIAL,  FOL.BDVALORFGTS13ESOCIAL, '
                 || ' FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, '
                 || ' FOL.BDDATAPROCFN, FOL.BDHORAPROCFN, 0 BDORDEMFN ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from TMP_EMPRESAS_SELECT EMP '
                      || ' inner join (SELECT FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFN, FN.BDBFGTSFN, FN.BDFGTSFN, FN.BDBFGTS13FN, FN.BDFGTS13FN, FN.BDDATAPROCFN, FN.BDHORAPROCFN, FN.BDBASEFGTSINDESOCIAL, FN.BDVALORFGTSINDESOCIAL, FN.BDBASEFGTSMESESOCIAL, FN.BDVALORFGTSMESESOCIAL, FN.BDBASEFGTS13ESOCIAL, FN.BDVALORFGTS13ESOCIAL FROM VRHF_EMP_TFOLHANORMAL FN) FOL ON (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from TEMPRESAS EMP ';
          wsql = wsql || ' join VRHF_EMP_TFOLHANORMAL FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END

      wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC on (Resc.BDCODEMP = EMP.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >= '||prrefini||') ';
      wsql = wsql || 'where (FOL.BDREFFN >= ' || prrefini || ' and FOL.BDREFFN <= ' || prreffim || ')';
     
      IF (WUSARTMP_EMP_SELECT = 0) THEN
        BEGIN
          IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            wsql = wsql || ' and ((' || prcodemp || ') ';

          IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
            wsql = wsql || ' or (' || prcodmatriz || ') ';
        
          IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
            wsql = wsql || ') ';
        END

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN ';
    END

  wcodemp              = 0;
  wcodcol              = 0;
  wref                 = 0;
  wbasefgts            = 0;
  wvalorfgts           = 0;
  wbasefgts13          = 0;
  wvalorfgts13         = 0;
  wbasefgtsresc        = 0;
  wvalorfgtsresc       = 0;
  wbasefgts13resc      = 0;
  wvalorfgts13resc     = 0;
  wbasefgtsindesocial  = 0;
  wvalorfgtsindesocial = 0;
  wbasefgtsmesesocial  = 0;
  wvalorfgtsmesesocial = 0;
  wbasefgts13esocial   = 0;
  wvalorfgts13esocial  = 0;

  wdataproc            = NULL;
  whoraproc            = NULL;
  wordem               = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wref, :wbasefgts, :wvalorfgts, :wbasefgtsresc, :wvalorfgtsresc, :wbasefgts13, :wvalorfgts13, :wbasefgts13resc, :wvalorfgts13resc, :wbasefgtsindesocial, :wvalorfgtsindesocial, :wbasefgts13esocial, :wvalorfgts13esocial, :wbasefgtsmesesocial, :wvalorfgtsmesesocial, :wdataproc, :whoraproc, :wordem DO
    BEGIN
      BDCODEMP          = wcodemp;
      BDCODCOL          = wcodcol;
      BDREF             = wref;
      BDBFGTS           = wbasefgts;
      BDFGTS            = wvalorfgts;
      BDBFGTS13         = wbasefgts13;
      BDFGTS13          = wvalorfgts13;
      BDBFGTSRESC       = wbasefgtsresc;
      BDFGTSRESC        = wvalorfgtsresc;
      BDBFGTS13RESC     = wbasefgts13resc;
      BDFGTS13RESC      = wvalorfgts13resc;
      BDBFGTSINDESOCIAL = wbasefgtsindesocial;
      BDFGTSINDESOCIAL  = wvalorfgtsindesocial;
      BDBFGTS13ESOCIAL  = wbasefgts13esocial;
      BDFGTS13ESOCIAL   = wvalorfgts13esocial;
      BDBFGTSMESESOCIAL = wbasefgtsmesesocial;
      BDFGTSMESESOCIAL  = wvalorfgtsmesesocial;
      BDDATAPROC        = wdataproc;
      BDHORAPROC        = whoraproc;
      BDORDEM           = wordem;
      SUSPEND;
    END

/*
  FOLHA TOMADOR
*/

  IF (prpuxarfiliais = 0) THEN
    BEGIN
      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR,'
                 || ' case'
                 || '   when (Resc.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDBFGTSFT'
                 || '   else 0'
                 || ' end BDBFGTSFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDFGTSFT'
                 || '   else 0'
                 || ' end BDFGTSFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDBFGTSFT'
                 || '   else 0'
                 || ' end BDBFGTSRESCFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDFGTSFT'
                 || '   else 0'
                 || ' end BDFGTSRESCFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDBFGTS13FT'
                 || '   else 0'
                 || ' end BDBFGTS13FT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDFGTS13FT'
                 || '   else 0'
                 || ' end BDFGTS13FT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDBFGTS13FT'
                 || '   else 0'
                 || ' end BDBFGTS13RESCFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDFGTS13FT'
                 || '   else 0'
                 || ' end BDFGTS13RESCFT,'
                 || ' FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, '
                 || ' FOL.BDBASEFGTS13ESOCIAL,  FOL.BDVALORFGTS13ESOCIAL, '
                 || ' FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, '
                 || ' FOL.BDDATAPROCFT, FOL.BDHORAPROCFT, FOL.BDORDEM BDORDEMFT ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from (select FT.BDCODEMP, FT.BDCODCOL, FT.BDREFTOMADOR, FT.BDBFGTSFT, FT.BDFGTSFT, FT.BDBFGTS13FT, FT.BDFGTS13FT, FT.BDDATAPROCFT, FT.BDHORAPROCFT, FT.BDORDEM, FT.BDBASEFGTSINDESOCIAL, FT.BDVALORFGTSINDESOCIAL, FT.BDBASEFGTSMESESOCIAL, FT.BDVALORFGTSMESESOCIAL, FT.BDBASEFGTS13ESOCIAL, FT.BDVALORFGTS13ESOCIAL from VRHF_EMP_TFOLHATOMADOR FT' || ' inner join TMP_EMPRESAS_SELECT EMPSEL on EMPSEL.BDCODEMP = FT.BDCODEMP ) fol ';
        END
      ELSE
        wsql = wsql || ' from VRHF_EMP_TFOLHATOMADOR FOL ';

      wsql = wsql || ' left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >=' || prreffim || ' ) ';
      wsql = wsql || ' where (FOL.BDREFTOMADOR >= ' || prrefini || ' and FOL.BDREFTOMADOR <=' || prreffim || ')';

      IF((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
        wsql = wsql || ' and ' || prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR ';
    END
  ELSE
    BEGIN
      wsql = ' select EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDBFGTSFT'
                 || '   else 0'
                 || ' end BDBFGTSFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDFGTSFT'
                 || '   else 0'
                 || ' end BDFGTSFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDBFGTSFT'
                 || '   else 0'
                 || ' end BDBFGTSRESCFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDFGTSFT'
                 || '   else 0'
                 || ' end BDFGTSRESCFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDBFGTS13FT'
                 || '   else 0'
                 || ' end BDBFGTS13FT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDFGTS13FT'
                 || '   else 0'
                 || ' end BDFGTS13FT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDBFGTS13FT'
                 || '   else 0'
                 || ' end BDBFGTSRESC13FT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDFGTS13FT'
                 || '   else 0'
                 || ' end BDFGTSRESC13FT,'
                 || ' FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, '
                 || ' FOL.BDBASEFGTS13ESOCIAL,  FOL.BDVALORFGTS13ESOCIAL, '
                 || ' FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, '
                 || ' FOL.BDDATAPROCFT, FOL.BDHORAPROCFT, FOL.BDORDEM BDORDEMFT';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from TMP_EMPRESAS_SELECT EMP ' ||
                         ' inner join (SELECT FT.BDCODEMP, FT.BDCODCOL, FT.BDREFTOMADOR, FT.BDBFGTSFT, FT.BDFGTSFT, FT.BDBFGTS13FT, FT.BDFGTS13FT, FT.BDDATAPROCFT, FT.BDHORAPROCFT, FT.BDORDEM, FT.BDBASEFGTSINDESOCIAL, FT.BDVALORFGTSINDESOCIAL, FT.BDBASEFGTSMESESOCIAL, FT.BDVALORFGTSMESESOCIAL, FT.BDBASEFGTS13ESOCIAL, FT.BDVALORFGTS13ESOCIAL from VRHF_EMP_TFOLHATOMADOR FT) FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from TEMPRESAS EMP ';
          wsql = wsql || ' join VRHF_EMP_TFOLHATOMADOR FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END

      wsql = wsql || ' left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = EMP.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >= ' || prrefini || ') ';
      wsql = wsql || ' where (FOL.BDREFTOMADOR >= ' || prrefini || ' and FOL.BDREFTOMADOR <= ' || prreffim || ')';
     
      IF (WUSARTMP_EMP_SELECT = 0) THEN
        BEGIN
          IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            wsql = wsql || ' and (('||prcodemp || ') ';

          IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
            wsql = wsql || ' or ('||prcodmatriz || ') ';
        
          IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
            wsql = wsql || ') ';
        END

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR ';
  END

  wcodemp              = 0;
  wcodcol              = 0;
  wref                 = 0;
  wbasefgts            = 0;
  wvalorfgts           = 0;
  wbasefgts13          = 0;
  wvalorfgts13         = 0;
  wbasefgtsresc        = 0;
  wvalorfgtsresc       = 0;
  wbasefgts13resc      = 0;
  wvalorfgts13resc     = 0;
  wbasefgtsindesocial  = 0;
  wvalorfgtsindesocial = 0;
  wbasefgtsmesesocial  = 0;
  wvalorfgtsmesesocial = 0;
  wbasefgts13esocial   = 0;
  wvalorfgts13esocial  = 0;
  wdataproc            = NULL;
  whoraproc            = NULL;
  wordem               = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wref, :wbasefgts, :wvalorfgts, :wbasefgtsresc, :wvalorfgtsresc, :wbasefgts13, :wvalorfgts13, :wbasefgts13resc, :wvalorfgts13resc, :wbasefgtsindesocial, :wvalorfgtsindesocial, :wbasefgts13esocial, :wvalorfgts13esocial, :wbasefgtsmesesocial, :wvalorfgtsmesesocial, :wdataproc, :whoraproc, :wordem DO
    BEGIN
      BDCODEMP          = wcodemp;
      BDCODCOL          = wcodcol;
      BDREF             = wref;
      BDBFGTS           = wbasefgts;
      BDFGTS            = wvalorfgts;
      BDBFGTS13         = wbasefgts13;
      BDFGTS13          = wvalorfgts13;
      BDBFGTSRESC       = wbasefgtsresc;
      BDFGTSRESC        = wvalorfgtsresc;
      BDBFGTS13RESC     = wbasefgts13resc;
      BDFGTS13RESC      = wvalorfgts13resc;
      BDBFGTSINDESOCIAL = wbasefgtsindesocial;
      BDFGTSINDESOCIAL  = wvalorfgtsindesocial;
      BDBFGTS13ESOCIAL  = wbasefgts13esocial;
      BDFGTS13ESOCIAL   = wvalorfgts13esocial;
      BDBFGTSMESESOCIAL = wbasefgtsmesesocial;
      BDFGTSMESESOCIAL  = wvalorfgtsmesesocial;
      BDDATAPROC        = wdataproc;
      BDHORAPROC        = whoraproc;
      BDORDEM           = wordem;
      SUSPEND;
    END

/* FOLHA INTERMITENTE */

  IF (prpuxarfiliais = 0) THEN
    BEGIN
      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDBFGTSFN'
                 || '   else 0'
                 || ' end BDBFGTSFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDFGTSFN'
                 || '   else 0'
                 || ' end BDFGTSFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDBFGTSFN'
                 || '   else 0'
                 || ' end BDBFGTSRESCFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDFGTSFN'
                 || '   else 0'
                 || ' end BDFGTSRESCFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDBFGTS13FN'
                 || '   else 0'
                 || ' end BDBFGTS13FN,'
                 || ' case'
                 || '   when (Resc.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDFGTS13FN'
                 || '   else 0'
                 || ' end BDFGTS13FN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDBFGTS13FN'
                 || '   else 0'
                 || ' end BDBFGTS13RESCFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDFGTS13FN'
                 || '   else 0'
                 || ' end BDFGTS13RESCFN,'
                 || ' FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, '
                 || ' FOL.BDBASEFGTS13ESOCIAL,  FOL.BDVALORFGTS13ESOCIAL, '
                 || ' FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, '
                 || ' FOL.BDDATAPROCFN, FOL.BDHORAPROCFN, 0 BDORDEMFN ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from (select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFN, FN.BDBFGTSFN, FN.BDFGTSFN, FN.BDBFGTS13FN, FN.BDFGTS13FN, FN.BDDATAPROCFN, FN.BDHORAPROCFN, FN.BDBASEFGTSINDESOCIAL, FN.BDVALORFGTSINDESOCIAL, FN.BDBASEFGTSMESESOCIAL, FN.BDVALORFGTSMESESOCIAL, FN.BDBASEFGTS13ESOCIAL, FN.BDVALORFGTS13ESOCIAL from VRHF_EMP_TFOLHAINT FN' || ' inner join TMP_EMPRESAS_SELECT EMPSEL on EMPSEL.BDCODEMP = FN.BDCODEMP ) FOL ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from VRHF_EMP_TFOLHAINT FOL ';
        END

      wsql = wsql || ' left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >=' || prrefini || ' ) ';
      wsql = wsql || ' where (FOL.BDREFFN >= ' || prrefini || ' and FOL.BDREFFN <=' || prreffim || ')';

      IF((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
        wsql = wsql || ' and ' || prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN ';
    END
  ELSE
    BEGIN
      wsql = ' select EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN,'
                 || ' case'
                 || '   when (Resc.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDBFGTSFN'
                 || '   else 0'
                 || ' end BDBFGTSFN,'
                 || ' case'
                 || '   when (Resc.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDFGTSFN'
                 || '   else 0'
                 || ' end BDFGTSFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDBFGTSFN'
                 || '   else 0'
                 || ' end BDBFGTSRESCFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDFGTSFN'
                 || '   else 0'
                 || ' end BDFGTSRESCFN,'
                 || ' case'
                 || '   when (Resc.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDBFGTS13FN'
                 || '   else 0'
                 || ' end BDBFGTS13FN,'
                 || ' case'
                 || '   when (Resc.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDFGTS13FN'
                 || '   else 0'
                 || ' end BDFGTS13FN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDBFGTS13FN'
                 || '   else 0'
                 || ' end BDBFGTS13RESCFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDFGTS13FN'
                 || '   else 0'
                 || ' end BDFGTS13RESCFN,'
                 || ' FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, '
                 || ' FOL.BDBASEFGTS13ESOCIAL,  FOL.BDVALORFGTS13ESOCIAL, '
                 || ' FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, '
                 || ' FOL.BDDATAPROCFN, FOL.BDHORAPROCFN, 0 BDORDEMFN ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from TMP_EMPRESAS_SELECT EMP '
                      || ' inner join (SELECT FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFN, FN.BDBFGTSFN, FN.BDFGTSFN, FN.BDBFGTS13FN, FN.BDFGTS13FN, FN.BDDATAPROCFN, FN.BDHORAPROCFN, FN.BDBASEFGTSINDESOCIAL, FN.BDVALORFGTSINDESOCIAL, FN.BDBASEFGTSMESESOCIAL, FN.BDVALORFGTSMESESOCIAL, FN.BDBASEFGTS13ESOCIAL, FN.BDVALORFGTS13ESOCIAL  FROM VRHF_EMP_TFOLHAINT FN) FOL ON (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from TEMPRESAS EMP ';
          wsql = wsql || ' join VRHF_EMP_TFOLHAINT FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END

      wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC on (Resc.BDCODEMP = EMP.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >= '||prrefini||') ';
      wsql = wsql || 'where (FOL.BDREFFN >= ' || prrefini || ' and FOL.BDREFFN <= ' || prreffim || ')';
     
      IF (WUSARTMP_EMP_SELECT = 0) THEN
        BEGIN
          IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            wsql = wsql || ' and ((' || prcodemp || ') ';

          IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
            wsql = wsql || ' or (' || prcodmatriz || ') ';
        
          IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
            wsql = wsql || ') ';
        END

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN ';
    END

  wcodemp              = 0;
  wcodcol              = 0;
  wref                 = 0;
  wbasefgts            = 0;
  wvalorfgts           = 0;
  wbasefgts13          = 0;
  wvalorfgts13         = 0;
  wbasefgtsresc        = 0;
  wvalorfgtsresc       = 0;
  wbasefgts13resc      = 0;
  wvalorfgts13resc     = 0;
  wbasefgtsindesocial  = 0;
  wvalorfgtsindesocial = 0;
  wbasefgtsmesesocial  = 0;
  wvalorfgtsmesesocial = 0;
  wbasefgts13esocial   = 0;
  wvalorfgts13esocial  = 0;
  wdataproc            = NULL;
  whoraproc            = NULL;
  wordem               = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wref, :wbasefgts, :wvalorfgts, :wbasefgtsresc, :wvalorfgtsresc, :wbasefgts13, :wvalorfgts13, :wbasefgts13resc, :wvalorfgts13resc, :wbasefgtsindesocial, :wvalorfgtsindesocial, :wbasefgts13esocial, :wvalorfgts13esocial, :wbasefgtsmesesocial, :wvalorfgtsmesesocial, :wdataproc, :whoraproc, :wordem DO
    BEGIN
      BDCODEMP      = wcodemp;
      BDCODCOL      = wcodcol;
      BDREF         = wref;
      BDBFGTS       = wbasefgts;
      BDFGTS        = wvalorfgts;
      BDBFGTS13     = wbasefgts13;
      BDFGTS13      = wvalorfgts13;
      BDBFGTSRESC   = wbasefgtsresc;
      BDFGTSRESC    = wvalorfgtsresc;
      BDBFGTS13RESC = wbasefgts13resc;
      BDFGTS13RESC  = wvalorfgts13resc;
      BDBFGTSINDESOCIAL = wbasefgtsindesocial;
      BDFGTSINDESOCIAL  = wvalorfgtsindesocial;
      BDBFGTS13ESOCIAL  = wbasefgts13esocial;
      BDFGTS13ESOCIAL   = wvalorfgts13esocial;
      BDBFGTSMESESOCIAL = wbasefgtsmesesocial;
      BDFGTSMESESOCIAL  = wvalorfgtsmesesocial;
      BDDATAPROC    = wdataproc;
      BDHORAPROC    = whoraproc;
      BDORDEM       = wordem;
      SUSPEND;
    END

/*
  FOLHA TOMADOR INTERMITENTE
*/

  IF (prpuxarfiliais = 0) THEN
    BEGIN
      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR,'
                 || ' case'
                 || '   when (Resc.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDBFGTSFT'
                 || '   else 0'
                 || ' end BDBFGTSFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDFGTSFT'
                 || '   else 0'
                 || ' end BDFGTSFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDBFGTSFT'
                 || '   else 0'
                 || ' end BDBFGTSRESCFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDFGTSFT'
                 || '   else 0'
                 || ' end BDFGTSRESCFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDBFGTS13FT'
                 || '   else 0'
                 || ' end BDBFGTS13FT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDFGTS13FT'
                 || '   else 0'
                 || ' end BDFGTS13FT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDBFGTS13FT'
                 || '   else 0'
                 || ' end BDBFGTS13RESCFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDFGTS13FT'
                 || '   else 0'
                 || ' end BDFGTS13RESCFT,'
                 || ' FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, '
                 || ' FOL.BDBASEFGTS13ESOCIAL,  FOL.BDVALORFGTS13ESOCIAL, '
                 || ' FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, '
                 || ' FOL.BDDATAPROCFT, FOL.BDHORAPROCFT, FOL.BDORDEM BDORDEMFT ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from (select FT.BDCODEMP, FT.BDCODCOL, FT.BDREFTOMADOR, FT.BDBFGTSFT, FT.BDFGTSFT, FT.BDBFGTS13FT, FT.BDFGTS13FT, FT.BDDATAPROCFT, FT.BDHORAPROCFT, FT.BDORDEM, FT.BDBASEFGTSINDESOCIAL, FT.BDVALORFGTSINDESOCIAL, FT.BDBASEFGTSMESESOCIAL, FT.BDVALORFGTSMESESOCIAL, FT.BDBASEFGTS13ESOCIAL, FT.BDVALORFGTS13ESOCIAL  from VRHF_EMP_TFOLHATOMINT FT' || ' inner join TMP_EMPRESAS_SELECT EMPSEL on EMPSEL.BDCODEMP = FT.BDCODEMP ) fol ';
        END
      ELSE
        wsql = wsql || ' from VRHF_EMP_TFOLHATOMINT FOL ';

      wsql = wsql || ' left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >=' || prreffim || ' ) ';
      wsql = wsql || ' where (FOL.BDREFTOMADOR >= ' || prrefini || ' and FOL.BDREFTOMADOR <=' || prreffim || ')';

      IF((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
        wsql = wsql || ' and ' || prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR ';
    END
  ELSE
    BEGIN
      wsql = ' select EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDBFGTSFT'
                 || '   else 0'
                 || ' end BDBFGTSFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDFGTSFT'
                 || '   else 0'
                 || ' end BDFGTSFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDBFGTSFT'
                 || '   else 0'
                 || ' end BDBFGTSRESCFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDFGTSFT'
                 || '   else 0'
                 || ' end BDFGTSRESCFT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDBFGTS13FT'
                 || '   else 0'
                 || ' end BDBFGTS13FT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDFGTS13FT'
                 || '   else 0'
                 || ' end BDFGTS13FT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDBFGTS13FT'
                 || '   else 0'
                 || ' end BDBFGTSRESC13FT,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDFGTS13FT'
                 || '   else 0'
                 || ' end BDFGTSRESC13FT,'
                 || ' FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, '
                 || ' FOL.BDBASEFGTS13ESOCIAL,  FOL.BDVALORFGTS13ESOCIAL, '
                 || ' FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, '
                 || ' FOL.BDDATAPROCFT, FOL.BDHORAPROCFT, FOL.BDORDEM BDORDEMFT';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from TMP_EMPRESAS_SELECT EMP ' ||
                         ' inner join (SELECT FT.BDCODEMP, FT.BDCODCOL, FT.BDREFTOMADOR, FT.BDBFGTSFT, FT.BDFGTSFT, FT.BDBFGTS13FT, FT.BDFGTS13FT, FT.BDDATAPROCFT, FT.BDHORAPROCFT, FT.BDORDEM, FT.BDBASEFGTSINDESOCIAL, FT.BDVALORFGTSINDESOCIAL, FT.BDBASEFGTSMESESOCIAL, FT.BDVALORFGTSMESESOCIAL, FT.BDBASEFGTS13ESOCIAL, FT.BDVALORFGTS13ESOCIAL from VRHF_EMP_TFOLHATOMINT FT) FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from TEMPRESAS EMP ';
          wsql = wsql || ' join VRHF_EMP_TFOLHATOMINT FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END

      wsql = wsql || ' left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = EMP.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >= ' || prrefini || ') ';
      wsql = wsql || ' where (FOL.BDREFTOMADOR >= ' || prrefini || ' and FOL.BDREFTOMADOR <= ' || prreffim || ')';
     
      IF (WUSARTMP_EMP_SELECT = 0) THEN
        BEGIN
          IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            wsql = wsql || ' and (('||prcodemp || ') ';

          IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
            wsql = wsql || ' or ('||prcodmatriz || ') ';
        
          IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
            wsql = wsql || ') ';
        END

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR ';
  END

  wcodemp              = 0;
  wcodcol              = 0;
  wref                 = 0;
  wbasefgts            = 0;
  wvalorfgts           = 0;
  wbasefgts13          = 0;
  wvalorfgts13         = 0;
  wbasefgtsresc        = 0;
  wvalorfgtsresc       = 0;
  wbasefgts13resc      = 0;
  wvalorfgts13resc     = 0;
  wbasefgtsindesocial  = 0;
  wvalorfgtsindesocial = 0;
  wbasefgtsmesesocial  = 0;
  wvalorfgtsmesesocial = 0;
  wbasefgts13esocial   = 0;
  wvalorfgts13esocial  = 0;
  wdataproc            = NULL;
  whoraproc            = NULL;
  wordem               = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wref, :wbasefgts, :wvalorfgts, :wbasefgtsresc, :wvalorfgtsresc, :wbasefgts13, :wvalorfgts13, :wbasefgts13resc, :wvalorfgts13resc, :wbasefgtsindesocial, :wvalorfgtsindesocial, :wbasefgts13esocial, :wvalorfgts13esocial, :wbasefgtsmesesocial, :wvalorfgtsmesesocial, :wdataproc, :whoraproc, :wordem DO
    BEGIN
      BDCODEMP          = wcodemp;
      BDCODCOL          = wcodcol;
      BDREF             = wref;
      BDBFGTS           = wbasefgts;
      BDFGTS            = wvalorfgts;
      BDBFGTS13         = wbasefgts13;
      BDFGTS13          = wvalorfgts13;
      BDBFGTSRESC       = wbasefgtsresc;
      BDFGTSRESC        = wvalorfgtsresc;
      BDBFGTS13RESC     = wbasefgts13resc;
      BDFGTS13RESC      = wvalorfgts13resc;
      BDBFGTSINDESOCIAL = wbasefgtsindesocial;
      BDFGTSINDESOCIAL  = wvalorfgtsindesocial;
      BDBFGTS13ESOCIAL  = wbasefgts13esocial;
      BDFGTS13ESOCIAL   = wvalorfgts13esocial;
      BDBFGTSMESESOCIAL = wbasefgtsmesesocial;
      BDFGTSMESESOCIAL  = wvalorfgtsmesesocial;
      BDDATAPROC        = wdataproc;
      BDHORAPROC        = whoraproc;
      BDORDEM           = wordem;
      SUSPEND;
    END

end^

/* Restore proc. body: SP_VRHF_DADOS_FGTS_FC */
create or alter procedure SP_VRHF_DADOS_FGTS_FC (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer,
    PRCODMATRIZ varchar(15000),
    PRADC boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBFGTSRESC numeric(18,6),
    BDFGTSRESC numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDBFGTS13RESC numeric(18,6),
    BDFGTS13RESC numeric(18,6),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDTIPOEVT integer,
    BDBFGTSINDESOCIAL numeric(18,6),
    BDFGTSINDESOCIAL numeric(18,6),
    BDBFGTSMESESOCIAL numeric(18,6),
    BDFGTSMESESOCIAL numeric(18,6),
    BDBFGTS13ESOCIAL numeric(18,6),
    BDFGTS13ESOCIAL numeric(18,6))
as
declare variable WSQL varchar(32700);
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WBASEFGTS numeric(18,6);
declare variable WVALORFGTS numeric(18,6);
declare variable WBASEFGTS13 numeric(18,6);
declare variable WVALORFGTS13 numeric(18,6);
declare variable WBASEFGTSRESC numeric(18,6);
declare variable WVALORFGTSRESC numeric(18,6);
declare variable WBASEFGTS13RESC numeric(18,6);
declare variable WVALORFGTS13RESC numeric(18,6);
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WORDEM integer;
declare variable WTIPOEVT integer;
declare variable WBASEFGTSINDESOCIAL numeric(18,6);
declare variable WVALORFGTSINDESOCIAL numeric(18,6);
declare variable WBASEFGTSMESESOCIAL numeric(18,6);
declare variable WVALORFGTSMESESOCIAL numeric(18,6);
declare variable WBASEFGTS13ESOCIAL numeric(18,6);
declare variable WVALORFGTS13ESOCIAL numeric(18,6);
begin
/*
  FOLHA NORMAL
*/

  WUSARTMP_EMP_SELECT = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
    WUSARTMP_EMP_SELECT = 1;

  IF (prpuxarfiliais = 0) THEN
    BEGIN
      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDBFGTSFC'
                 || '   else 0'
                 || ' end BDBFGTSFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDFGTSFC'
                 || '   else 0'
                 || ' end BDFGTSFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDBFGTSFC'
                 || '   else 0'
                 || ' end BDBFGTSRESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDFGTSFC'
                 || '   else 0'
                 || ' end BDFGTSRESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDBFGTS13FC'
                 || '   else 0'
                 || ' end BDBFGTS13FC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDFGTS13FC'
                 || '   else 0'
                 || ' end BDFGTS13FC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDBFGTS13FC'
                 || '   else 0'
                 || ' end BDBFGTS13RESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDFGTS13FC'
                 || '   else 0'
                 || ' end BDFGTS13RESCFC,'
                 || ' FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, '
                 || ' FOL.BDBASEFGTS13ESOCIAL,  FOL.BDVALORFGTS13ESOCIAL, '
                 || ' FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, '
                 || ' FOL.BDDATAPROCFC, FOL.BDHORAPROCFC, 0 BDORDEMFC, FOL.BDTIPOEVT ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from (select FO.BDCODEMP, FO.BDCODCOL, FO.BDREFFN, FO.BDBFGTSFC, FO.BDFGTSFC, FO.BDBFGTS13FC, FO.BDFGTS13FC, FO.BDDATAPROCFC, FO.BDHORAPROCFC, FO.BDTIPOEVT, FO.BDBASEFGTSINDESOCIAL, FO.BDVALORFGTSINDESOCIAL, FO.BDBASEFGTSMESESOCIAL, FO.BDVALORFGTSMESESOCIAL, FO.BDBASEFGTS13ESOCIAL, FO.BDVALORFGTS13ESOCIAL from VRHF_EMP_TFOLHACOMP FO' || ' inner join TMP_EMPRESAS_SELECT EMPSEL on EMPSEL.BDCODEMP = FO.BDCODEMP ) FOL ';
        END
      ELSE
        wsql = wsql || ' from VRHF_EMP_TFOLHACOMP FOL ';

      wsql = wsql || ' left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >=' || prrefini || ' ) ';

      IF (PRADC = TRUE) THEN
        BEGIN
          wsql = wsql || ' LEFT OUTER JOIN VRH_EMP_TACCONV A ON A.BDCODEMP = FOL.BDCODEMP AND A.BDCODACCONV = FOL.BDCODACCONV ';
          wsql = wsql || ' where CASE WHEN FOL.BDCODACCONV IS NOT NULL THEN COALESCE((SELECT BDAAAAMM FROM AAAAMM(A.BDDTACCONV)), FOL.BDREFFN) ELSE FOL.BDREFFN END between '|| prrefini ||' AND '||prreffim;
        END
      ELSE
      wsql = wsql || ' where (FOL.BDREFFN >= ' || prrefini || ' and FOL.BDREFFN <=' || prreffim || ') ';

      IF((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
        wsql = wsql || ' and ' || prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN ';
    END
  ELSE
    BEGIN
      wsql = ' select EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDBFGTSFC'
                 || '   else 0'
                 || ' end BDBFGTSFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDFGTSFC'
                 || '   else 0'
                 || ' end BDFGTSFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDBFGTSFC'
                 || '   else 0'
                 || ' end BDBFGTSRESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDFGTSFC'
                 || '   else 0'
                 || ' end BDFGTSRESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDBFGTS13FC'
                 || '   else 0'
                 || ' end BDBFGTS13FC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDFGTS13FC'
                 || '   else 0'
                 || ' end BDFGTS13FC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDBFGTS13FC'
                 || '   else 0'
                 || ' end BDBFGTS13RESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDFGTS13FC'
                 || '   else 0'
                 || ' end BDFGTS13RESCFC,'
                 || ' FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, '
                 || ' FOL.BDBASEFGTS13ESOCIAL,  FOL.BDVALORFGTS13ESOCIAL, '
                 || ' FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, '
                 || ' FOL.BDDATAPROCFC, FOL.BDHORAPROCFC, 0 BDORDEMFC, FOL.BDTIPOEVT  ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from TMP_EMPRESAS_SELECT EMP '
                      || ' inner join (select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFFN, FC.BDBFGTSFC, FC.BDFGTSFC, FC.BDBFGTS13FC, FC.BDFGTS13FC, FC.BDDATAPROCFC, FC.BDHORAPROCFC, FC.BDCODACCONV, FC.BDTIPOEVT, FC.BDBASEFGTSINDESOCIAL, FC.BDVALORFGTSINDESOCIAL, FC.BDBASEFGTSMESESOCIAL, FC.BDVALORFGTSMESESOCIAL, FC.BDBASEFGTS13ESOCIAL, FC.BDVALORFGTS13ESOCIAL from VRHF_EMP_TFOLHACOMP FC) FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from TEMPRESAS EMP '
                      || ' join VRHF_EMP_TFOLHACOMP FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END

      wsql = wsql || ' left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >=' || prrefini || ' ) ';

      IF (PRADC = TRUE) THEN
        BEGIN
          wsql = wsql || ' LEFT OUTER JOIN VRH_EMP_TACCONV A ON A.BDCODEMP = FOL.BDCODEMP AND A.BDCODACCONV = FOL.BDCODACCONV ';
          wsql = wsql || ' where CASE WHEN FOL.BDCODACCONV IS NOT NULL THEN COALESCE((SELECT BDAAAAMM FROM AAAAMM(A.BDDTACCONV)), FOL.BDREFFN) ELSE FOL.BDREFFN END between '|| prrefini ||' AND '||prreffim;
        END
      ELSE
        wsql = wsql || ' where (FOL.BDREFFN >= ' || prrefini || ' and FOL.BDREFFN <= '||prreffim||')';
            
      IF (WUSARTMP_EMP_SELECT = 0) THEN
        BEGIN
          IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            wsql = wsql || ' and (('||prcodemp || ') ';

          IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
            wsql = wsql || ' or ('||prcodmatriz || ') ';
        
          IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
            wsql = wsql || ') ';
        END

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN ';
    END

  wcodemp              = 0;
  wcodcol              = 0;
  wref                 = 0;
  wbasefgts            = 0;
  wvalorfgts           = 0;
  wbasefgts13          = 0;
  wvalorfgts13         = 0;
  wbasefgtsresc        = 0;
  wvalorfgtsresc       = 0;
  wbasefgts13resc      = 0;
  wvalorfgts13resc     = 0;
  wbasefgtsindesocial  = 0;
  wvalorfgtsindesocial = 0;
  wbasefgtsmesesocial  = 0;
  wvalorfgtsmesesocial = 0;
  wbasefgts13esocial   = 0;
  wvalorfgts13esocial  = 0;
  wdataproc            = NULL;
  whoraproc            = NULL;
  wordem               = 0;
  wtipoevt             = 0;



  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wref, :wbasefgts, :wvalorfgts, :wbasefgtsresc, :wvalorfgtsresc, :wbasefgts13, :wvalorfgts13, :wbasefgts13resc, :wvalorfgts13resc, :wbasefgtsindesocial, :wvalorfgtsindesocial, :wbasefgts13esocial, :wvalorfgts13esocial, :wbasefgtsmesesocial, :wvalorfgtsmesesocial, :wdataproc, :whoraproc, :wordem, :wtipoevt DO
    BEGIN
      BDCODEMP          = wcodemp;
      BDCODCOL          = wcodcol;
      BDREF             = wref;
      BDBFGTS           = wbasefgts;
      BDFGTS            = wvalorfgts;
      BDBFGTS13         = wbasefgts13;
      BDFGTS13          = wvalorfgts13;
      BDBFGTSRESC       = wbasefgtsresc;
      BDFGTSRESC        = wvalorfgtsresc;
      BDBFGTS13RESC     = wbasefgts13resc;
      BDFGTS13RESC      = wvalorfgts13resc;
      BDBFGTSINDESOCIAL = wbasefgtsindesocial;
      BDFGTSINDESOCIAL  = wvalorfgtsindesocial;
      BDBFGTS13ESOCIAL  = wbasefgts13esocial;
      BDFGTS13ESOCIAL   = wvalorfgts13esocial;
      BDBFGTSMESESOCIAL = wbasefgtsmesesocial;
      BDFGTSMESESOCIAL  = wvalorfgtsmesesocial;
      BDDATAPROC        = wdataproc;
      BDHORAPROC        = whoraproc;
      BDORDEM           = wordem;
      BDTIPOEVT         = wtipoevt;
      SUSPEND;
    END

  /*FOLHA INTERMITENTE*/

  IF (prpuxarfiliais = 0) THEN
    BEGIN
      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDBFGTSFC'
                 || '   else 0'
                 || ' end BDBFGTSFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDFGTSFC'
                 || '   else 0'
                 || ' end BDFGTSFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDBFGTSFC'
                 || '   else 0'
                 || ' end BDBFGTSRESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDFGTSFC'
                 || '   else 0'
                 || ' end BDFGTSRESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDBFGTS13FC'
                 || '   else 0'
                 || ' end BDBFGTS13FC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDFGTS13FC'
                 || '   else 0'
                 || ' end BDFGTS13FC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDBFGTS13FC'
                 || '   else 0'
                 || ' end BDBFGTS13RESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDFGTS13FC'
                 || '   else 0'
                 || ' end BDFGTS13RESCFC,'
                 || ' FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, '
                 || ' FOL.BDBASEFGTS13ESOCIAL,  FOL.BDVALORFGTS13ESOCIAL, '
                 || ' FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, '
                 || ' FOL.BDDATAPROCFC, FOL.BDHORAPROCFC, 0 BDORDEMFC, FOL.BDTIPOEVT  ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from (select FO.BDCODEMP, FO.BDCODCOL, FO.BDREFFN, FO.BDBFGTSFC, FO.BDFGTSFC, FO.BDBFGTS13FC, FO.BDFGTS13FC, FO.BDDATAPROCFC, FO.BDHORAPROCFC, FO.BDCODACCONV, FO.BDTIPOEVT, FO.BDBASEFGTSINDESOCIAL, FO.BDVALORFGTSINDESOCIAL, FO.BDBASEFGTSMESESOCIAL, FO.BDVALORFGTSMESESOCIAL, FO.BDBASEFGTS13ESOCIAL, FO.BDVALORFGTS13ESOCIAL  from VRHF_EMP_TFOLHACOMPINT FO' || ' inner join TMP_EMPRESAS_SELECT EMPSEL on EMPSEL.BDCODEMP = FO.BDCODEMP ) FOL ';
        END
      ELSE
        wsql = wsql || ' from VRHF_EMP_TFOLHACOMPINT FOL ';

      wsql = wsql || ' left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >=' || prrefini || ' ) ';

      IF (PRADC = TRUE) THEN
        BEGIN
          wsql = wsql || ' LEFT OUTER JOIN VRH_EMP_TACCONV A ON A.BDCODEMP = FOL.BDCODEMP AND A.BDCODACCONV = FOL.BDCODACCONV ';
          wsql = wsql || ' where CASE WHEN FOL.BDCODACCONV IS NOT NULL THEN COALESCE((SELECT BDAAAAMM FROM AAAAMM(A.BDDTACCONV)), FOL.BDREFFN) ELSE FOL.BDREFFN END between '|| prrefini ||' AND '||prreffim;
        END
      ELSE
      wsql = wsql || ' where (FOL.BDREFFN >= ' || prrefini || ' and FOL.BDREFFN <=' || prreffim || ') ';

      IF((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
        wsql = wsql || ' and ' || prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN ';
    END
  ELSE
    BEGIN
      wsql = ' select EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDBFGTSFC'
                 || '   else 0'
                 || ' end BDBFGTSFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDFGTSFC'
                 || '   else 0'
                 || ' end BDFGTSFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDBFGTSFC'
                 || '   else 0'
                 || ' end BDBFGTSRESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDFGTSFC'
                 || '   else 0'
                 || ' end BDFGTSRESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDBFGTS13FC'
                 || '   else 0'
                 || ' end BDBFGTS13FC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFFN) then FOL.BDFGTS13FC'
                 || '   else 0'
                 || ' end BDFGTS13FC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDBFGTS13FC'
                 || '   else 0'
                 || ' end BDBFGTS13RESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFFN) then FOL.BDFGTS13FC'
                 || '   else 0'
                 || ' end BDFGTS13RESCFC,'
                 || ' FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, '
                 || ' FOL.BDBASEFGTS13ESOCIAL,  FOL.BDVALORFGTS13ESOCIAL, '
                 || ' FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, '
                 || ' FOL.BDDATAPROCFC, FOL.BDHORAPROCFC, 0 BDORDEMFC, FOL.BDTIPOEVT  ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from TMP_EMPRESAS_SELECT EMP '
                      || ' inner join (select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFFN, FC.BDBFGTSFC, FC.BDFGTSFC, FC.BDBFGTS13FC, FC.BDFGTS13FC, FC.BDDATAPROCFC, FC.BDHORAPROCFC, FC.BDCODACCONV, FC.BDTIPOEVT, FC.BDBASEFGTSINDESOCIAL, FC.BDVALORFGTSINDESOCIAL, FC.BDBASEFGTSMESESOCIAL, FC.BDVALORFGTSMESESOCIAL, FC.BDBASEFGTS13ESOCIAL, FC.BDVALORFGTS13ESOCIAL  from VRHF_EMP_TFOLHACOMPINT FC) FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from TEMPRESAS EMP '
                      || ' join VRHF_EMP_TFOLHACOMPINT FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END

      wsql = wsql || ' left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >=' || prrefini || ' ) ';

      IF (PRADC = TRUE) THEN
        BEGIN
          wsql = wsql || ' LEFT OUTER JOIN VRH_EMP_TACCONV A ON A.BDCODEMP = FOL.BDCODEMP AND A.BDCODACCONV = FOL.BDCODACCONV ';
          wsql = wsql || ' where CASE WHEN FOL.BDCODACCONV IS NOT NULL THEN COALESCE((SELECT BDAAAAMM FROM AAAAMM(A.BDDTACCONV)), FOL.BDREFFN) ELSE FOL.BDREFFN END between '|| prrefini ||' AND '||prreffim;
        END
      ELSE
        wsql = wsql || ' where (FOL.BDREFFN >= ' || prrefini || ' and FOL.BDREFFN <= '||prreffim||')';
     
      IF (WUSARTMP_EMP_SELECT = 0) THEN
        BEGIN
          IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            wsql = wsql || ' and (('||prcodemp || ') ';

          IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
            wsql = wsql || ' or ('||prcodmatriz || ') ';
        
          IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
            wsql = wsql || ') ';
        END

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN ';
    END

  wcodemp          = 0;
  wcodcol          = 0;
  wref             = 0;
  wbasefgts        = 0;
  wvalorfgts       = 0;
  wbasefgts13      = 0;
  wvalorfgts13     = 0;
  wbasefgtsresc    = 0;
  wvalorfgtsresc   = 0;
  wbasefgts13resc  = 0;
  wvalorfgts13resc = 0;
  wbasefgtsindesocial  = 0;
  wvalorfgtsindesocial = 0;
  wbasefgtsmesesocial  = 0;
  wvalorfgtsmesesocial = 0;
  wbasefgts13esocial   = 0;
  wvalorfgts13esocial  = 0;
  wdataproc        = NULL;
  whoraproc        = NULL;
  wordem           = 0;
  wtipoevt         = 0;
  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wref, :wbasefgts, :wvalorfgts, :wbasefgtsresc, :wvalorfgtsresc, :wbasefgts13, :wvalorfgts13, :wbasefgts13resc, :wvalorfgts13resc, :wbasefgtsindesocial, :wvalorfgtsindesocial, :wbasefgts13esocial, :wvalorfgts13esocial, :wbasefgtsmesesocial, :wvalorfgtsmesesocial, :wdataproc, :whoraproc, :wordem, :wtipoevt DO
    BEGIN
      BDCODEMP          = wcodemp;
      BDCODCOL          = wcodcol;
      BDREF             = wref;
      BDBFGTS           = wbasefgts;
      BDFGTS            = wvalorfgts;
      BDBFGTS13         = wbasefgts13;
      BDFGTS13          = wvalorfgts13;
      BDBFGTSRESC       = wbasefgtsresc;
      BDFGTSRESC        = wvalorfgtsresc;
      BDBFGTS13RESC     = wbasefgts13resc;
      BDFGTS13RESC      = wvalorfgts13resc;
      BDBFGTSINDESOCIAL = wbasefgtsindesocial;
      BDFGTSINDESOCIAL  = wvalorfgtsindesocial;
      BDBFGTS13ESOCIAL  = wbasefgts13esocial;
      BDFGTS13ESOCIAL   = wvalorfgts13esocial;
      BDBFGTSMESESOCIAL = wbasefgtsmesesocial;
      BDFGTSMESESOCIAL  = wvalorfgtsmesesocial;
      BDDATAPROC        = wdataproc;
      BDHORAPROC        = whoraproc;
      BDORDEM           = wordem;
      BDTIPOEVT         = wtipoevt;
      SUSPEND;
    END

/*
  FOLHA TOMADOR
*/
  IF (prpuxarfiliais = 0) THEN
    BEGIN
      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDBFGTSFC'
                 || '   else 0'
                 || ' end BDBFGTSFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDFGTSFC'
                 || '   else 0'
                 || ' end BDFGTSFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDBFGTSFC'
                 || '   else 0'
                 || ' end BDBFGTSRESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDFGTSFC'
                 || '   else 0'
                 || ' end BDFGTSRESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDBFGTS13FC'
                 || '   else 0'
                 || ' end BDBFGTS13FC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDFGTS13FC'
                 || '   else 0'
                 || ' end BDFGTS13FC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDBFGTS13FC'
                 || '   else 0'
                 || ' end BDBFGTS13RESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDFGTS13FC'
                 || '   else 0'
                 || ' end BDFGTS13RESCFC,'
                 || ' FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, '
                 || ' FOL.BDBASEFGTS13ESOCIAL,  FOL.BDVALORFGTS13ESOCIAL, '
                 || ' FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, '
                 || ' FOL.BDDATAPROCFC, FOL.BDHORAPROCFC, FOL.BDORDEM BDORDEMFC, FOL.BDTIPOEVT ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from (select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFTOMADOR, FC.BDBFGTSFC, FC.BDFGTSFC, FC.BDBFGTS13FC, FC.BDFGTS13FC, FC.BDDATAPROCFC, FC.BDHORAPROCFC, FC.BDORDEM, FC.BDCODACCONV, FC.BDTIPOEVT, FC.BDBASEFGTSINDESOCIAL, FC.BDVALORFGTSINDESOCIAL, FC.BDBASEFGTSMESESOCIAL, FC.BDVALORFGTSMESESOCIAL, FC.BDBASEFGTS13ESOCIAL, FC.BDVALORFGTS13ESOCIAL from VRHF_EMP_TFOLTOMCOMP FC' || ' inner join TMP_EMPRESAS_SELECT EMPSEL on EMPSEL.BDCODEMP = FC.BDCODEMP ) FOL ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from VRHF_EMP_TFOLTOMCOMP FOL ';
        END

      wsql = wsql || ' left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >=' || prrefini || ' ) ';

      IF (PRADC = TRUE) THEN
        BEGIN
          wsql = wsql || ' LEFT OUTER JOIN VRH_EMP_TACCONV A ON A.BDCODEMP = FOL.BDCODEMP AND A.BDCODACCONV = FOL.BDCODACCONV ';
          wsql = wsql || ' where CASE WHEN FOL.BDCODACCONV IS NOT NULL THEN COALESCE((SELECT BDAAAAMM FROM AAAAMM(A.BDDTACCONV)), FOL.BDREFTOMADOR) ELSE FOL.BDREFTOMADOR END between '|| prrefini ||' AND '||prreffim;
        END
      ELSE
      wsql = wsql || ' where (FOL.BDREFTOMADOR >= ' || prrefini || ' and FOL.BDREFTOMADOR <=' || prreffim || ')';


      IF ((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
        wsql = wsql || ' and ' || prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR ';
    END
  ELSE
    BEGIN
      wsql = 'select EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDBFGTSFC'
                 || '   else 0'
                 || ' end BDBFGTSFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDFGTSFC'
                 || '   else 0'
                 || ' end BDFGTSFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDBFGTSFC'
                 || '   else 0'
                 || ' end BDBFGTSRESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDFGTSFC'
                 || '   else 0'
                 || ' end BDFGTSRESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDBFGTS13FC'
                 || '   else 0'
                 || ' end BDBFGTS13FC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDFGTS13FC'
                 || '   else 0'
                 || ' end BDFGTS13FC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDBFGTS13FC'
                 || '   else 0'
                 || ' end BDBFGTS13RESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDFGTS13FC'
                 || '   else 0'
                 || ' end BDFGTS13RESCFC,'
                 || ' FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, '
                 || ' FOL.BDBASEFGTS13ESOCIAL,  FOL.BDVALORFGTS13ESOCIAL, '
                 || ' FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, '
                 || ' FOL.BDDATAPROCFC, FOL.BDHORAPROCFC, FOL.BDORDEM BDORDEMFC, FOL.BDTIPOEVT ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from TMP_EMPRESAS_SELECT EMP ' ||
                         ' inner join (select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDBFGTSFC, FOL.BDFGTSFC, FOL.BDBFGTS13FC, FOL.BDFGTS13FC, FOL.BDDATAPROCFC, FOL.BDHORAPROCFC, FOL.BDORDEM, FOL.BDCODACCONV, FOL.BDTIPOEVT, FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, FOL.BDBASEFGTS13ESOCIAL, FOL.BDVALORFGTS13ESOCIAL from VRHF_EMP_TFOLTOMCOMP FOL) FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from TEMPRESAS EMP ';
          wsql = wsql || ' join VRHF_EMP_TFOLTOMCOMP FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END

      wsql = wsql || ' left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >=' || prrefini || ' ) ';

      IF (PRADC = TRUE) THEN
        BEGIN
          wsql = wsql || ' LEFT OUTER JOIN VRH_EMP_TACCONV A ON A.BDCODEMP = FOL.BDCODEMP AND A.BDCODACCONV = FOL.BDCODACCONV ';
          wsql = wsql || ' where CASE WHEN FOL.BDCODACCONV IS NOT NULL THEN COALESCE((SELECT BDAAAAMM FROM AAAAMM(A.BDDTACCONV)), FOL.BDREFTOMADOR) ELSE FOL.BDREFTOMADOR END between '|| prrefini ||' AND '||prreffim;
        END
      ELSE
        wsql = wsql || ' where (FOL.BDREFTOMADOR >= ' || prrefini || ' and FOL.BDREFTOMADOR <= '||prreffim||')';
     
      IF (WUSARTMP_EMP_SELECT = 0) THEN
        BEGIN
          IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            wsql = wsql || ' and ((' || prcodemp || ') ';

          IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
            wsql = wsql || ' or ('||prcodmatriz || ') ';
        
          IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
            wsql = wsql || ') ';
        END

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR ';
  END

  wcodemp              = 0;
  wcodcol              = 0;
  wref                 = 0;
  wbasefgts            = 0;
  wvalorfgts           = 0;
  wbasefgts13          = 0;
  wvalorfgts13         = 0;
  wbasefgtsresc        = 0;
  wvalorfgtsresc       = 0;
  wbasefgts13resc      = 0;
  wvalorfgts13resc     = 0;
  wbasefgtsindesocial  = 0;
  wvalorfgtsindesocial = 0;
  wbasefgtsmesesocial  = 0;
  wvalorfgtsmesesocial = 0;
  wbasefgts13esocial   = 0;
  wvalorfgts13esocial  = 0;
  wdataproc            = NULL;
  whoraproc            = NULL;
  wordem               = 0;
  wtipoevt             = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wref, :wbasefgts, :wvalorfgts, :wbasefgtsresc, :wvalorfgtsresc, :wbasefgts13, :wvalorfgts13, :wbasefgts13resc, :wvalorfgts13resc, :wbasefgtsindesocial, :wvalorfgtsindesocial, :wbasefgts13esocial, :wvalorfgts13esocial, :wbasefgtsmesesocial, :wvalorfgtsmesesocial, :wdataproc, :whoraproc, :wordem, :wtipoevt DO
    BEGIN
      BDCODEMP          = wcodemp;
      BDCODCOL          = wcodcol;
      BDREF             = wref;
      BDBFGTS           = wbasefgts;
      BDFGTS            = wvalorfgts;
      BDBFGTS13         = wbasefgts13;
      BDFGTS13          = wvalorfgts13;
      BDBFGTSRESC       = wbasefgtsresc;
      BDFGTSRESC        = wvalorfgtsresc;
      BDBFGTS13RESC     = wbasefgts13resc;
      BDFGTS13RESC      = wvalorfgts13resc;
      BDBFGTSINDESOCIAL = wbasefgtsindesocial;
      BDFGTSINDESOCIAL  = wvalorfgtsindesocial;
      BDBFGTS13ESOCIAL  = wbasefgts13esocial;
      BDFGTS13ESOCIAL   = wvalorfgts13esocial;
      BDBFGTSMESESOCIAL = wbasefgtsmesesocial;
      BDFGTSMESESOCIAL  = wvalorfgtsmesesocial;
      BDDATAPROC        = wdataproc;
      BDHORAPROC        = whoraproc;
      BDORDEM           = wordem;
      BDTIPOEVT         = wtipoevt;
      SUSPEND;
    END

  /*FOLHA TOMADOR INTERMITENTE */

  IF (prpuxarfiliais = 0) THEN
    BEGIN
      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDBFGTSFC'
                 || '   else 0'
                 || ' end BDBFGTSFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDFGTSFC'
                 || '   else 0'
                 || ' end BDFGTSFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDBFGTSFC'
                 || '   else 0'
                 || ' end BDBFGTSRESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDFGTSFC'
                 || '   else 0'
                 || ' end BDFGTSRESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDBFGTS13FC'
                 || '   else 0'
                 || ' end BDBFGTS13FC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDFGTS13FC'
                 || '   else 0'
                 || ' end BDFGTS13FC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDBFGTS13FC'
                 || '   else 0'
                 || ' end BDBFGTS13RESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDFGTS13FC'
                 || '   else 0'
                 || ' end BDFGTS13RESCFC,'
                 || ' FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, '
                 || ' FOL.BDBASEFGTS13ESOCIAL,  FOL.BDVALORFGTS13ESOCIAL, '
                 || ' FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, '
                 || ' FOL.BDDATAPROCFC, FOL.BDHORAPROCFC, FOL.BDORDEM BDORDEMFC, FOL.BDTIPOEVT ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from (select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFTOMADOR, FC.BDBFGTSFC, FC.BDFGTSFC, FC.BDBFGTS13FC, FC.BDFGTS13FC, FC.BDDATAPROCFC, FC.BDHORAPROCFC, FC.BDORDEM, FC.BDCODACCONV, FC.BDTIPOEVT, FC.BDBASEFGTSINDESOCIAL, FC.BDVALORFGTSINDESOCIAL, FC.BDBASEFGTSMESESOCIAL, FC.BDVALORFGTSMESESOCIAL, FC.BDBASEFGTS13ESOCIAL, FC.BDVALORFGTS13ESOCIAL from VRHF_EMP_TFOLTOMCOMPINT FC' || ' inner join TMP_EMPRESAS_SELECT EMPSEL on EMPSEL.BDCODEMP = FC.BDCODEMP ) FOL ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from VRHF_EMP_TFOLTOMCOMPINT FOL ';
        END

      wsql = wsql || ' left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >=' || prrefini || ' ) ';

      IF (PRADC = TRUE) THEN
        BEGIN
          wsql = wsql || ' LEFT OUTER JOIN VRH_EMP_TACCONV A ON A.BDCODEMP = FOL.BDCODEMP AND A.BDCODACCONV = FOL.BDCODACCONV ';
          wsql = wsql || ' where CASE WHEN FOL.BDCODACCONV IS NOT NULL THEN COALESCE((SELECT BDAAAAMM FROM AAAAMM(A.BDDTACCONV)), FOL.BDREFTOMADOR) ELSE FOL.BDREFTOMADOR END between '|| prrefini ||' AND '||prreffim;
        END
      ELSE
      wsql = wsql || ' where (FOL.BDREFTOMADOR >= ' || prrefini || ' and FOL.BDREFTOMADOR <=' || prreffim || ')';

      IF ((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
        wsql = wsql || ' and ' || prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR ';
    END
  ELSE
    BEGIN
      wsql = 'select EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDBFGTSFC'
                 || '   else 0'
                 || ' end BDBFGTSFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDFGTSFC'
                 || '   else 0'
                 || ' end BDFGTSFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDBFGTSFC'
                 || '   else 0'
                 || ' end BDBFGTSRESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDFGTSFC'
                 || '   else 0'
                 || ' end BDFGTSRESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDBFGTS13FC'
                 || '   else 0'
                 || ' end BDBFGTS13FC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDFGTS13FC'
                 || '   else 0'
                 || ' end BDFGTS13FC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDBFGTS13FC'
                 || '   else 0'
                 || ' end BDBFGTS13RESCFC,'
                 || ' case'
                 || '   when (RESC.BDREFRESCISAO = FOL.BDREFTOMADOR) then FOL.BDFGTS13FC'
                 || '   else 0'
                 || ' end BDFGTS13RESCFC,'
                 || ' FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, '
                 || ' FOL.BDBASEFGTS13ESOCIAL,  FOL.BDVALORFGTS13ESOCIAL, '
                 || ' FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, '
                 || ' FOL.BDDATAPROCFC, FOL.BDHORAPROCFC, FOL.BDORDEM BDORDEMFC, FOL.BDTIPOEVT ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from TMP_EMPRESAS_SELECT EMP ' ||
                         ' inner join (select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDBFGTSFC, FOL.BDFGTSFC, FOL.BDBFGTS13FC, FOL.BDFGTS13FC, FOL.BDDATAPROCFC, FOL.BDHORAPROCFC, FOL.BDORDEM, FOL.BDCODACCONV, FOL.BDTIPOEVT, FOL.BDBASEFGTSINDESOCIAL, FOL.BDVALORFGTSINDESOCIAL, FOL.BDBASEFGTSMESESOCIAL, FOL.BDVALORFGTSMESESOCIAL, FOL.BDBASEFGTS13ESOCIAL, FOL.BDVALORFGTS13ESOCIAL from VRHF_EMP_TFOLTOMCOMPINT FOL) FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from TEMPRESAS EMP ';
          wsql = wsql || ' join VRHF_EMP_TFOLTOMCOMPINT FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END

      wsql = wsql || ' left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >=' || prrefini || ' ) ';

      IF (PRADC = TRUE) THEN
        BEGIN
          wsql = wsql || ' LEFT OUTER JOIN VRH_EMP_TACCONV A ON A.BDCODEMP = FOL.BDCODEMP AND A.BDCODACCONV = FOL.BDCODACCONV ';
          wsql = wsql || ' where CASE WHEN FOL.BDCODACCONV IS NOT NULL THEN COALESCE((SELECT BDAAAAMM FROM AAAAMM(A.BDDTACCONV)), FOL.BDREFTOMADOR) ELSE FOL.BDREFTOMADOR END between '|| prrefini ||' AND '||prreffim;
        END
      ELSE
        wsql = wsql || ' where (FOL.BDREFTOMADOR >= ' || prrefini || ' and FOL.BDREFTOMADOR <= '||prreffim||')';
     
      IF (WUSARTMP_EMP_SELECT = 0) THEN
        BEGIN
          IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            wsql = wsql || ' and ((' || prcodemp || ') ';

          IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
            wsql = wsql || ' or ('||prcodmatriz || ') ';
        
          IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
            wsql = wsql || ') ';
        END

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR ';
  END

  wcodemp              = 0;
  wcodcol              = 0;
  wref                 = 0;
  wbasefgts            = 0;
  wvalorfgts           = 0;
  wbasefgts13          = 0;
  wvalorfgts13         = 0;
  wbasefgtsresc        = 0;
  wvalorfgtsresc       = 0;
  wbasefgts13resc      = 0;
  wvalorfgts13resc     = 0;
  wbasefgtsindesocial  = 0;
  wvalorfgtsindesocial = 0;
  wbasefgtsmesesocial  = 0;
  wvalorfgtsmesesocial = 0;
  wbasefgts13esocial   = 0;
  wvalorfgts13esocial  = 0;
  wdataproc            = NULL;
  whoraproc            = NULL;
  wordem               = 0;
  wtipoevt             = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wref, :wbasefgts, :wvalorfgts, :wbasefgtsresc, :wvalorfgtsresc, :wbasefgts13, :wvalorfgts13, :wbasefgts13resc, :wvalorfgts13resc, :wbasefgtsindesocial, :wvalorfgtsindesocial, :wbasefgts13esocial, :wvalorfgts13esocial, :wbasefgtsmesesocial, :wvalorfgtsmesesocial, :wdataproc, :whoraproc, :wordem, :wtipoevt DO
    BEGIN
      BDCODEMP          = wcodemp;
      BDCODCOL          = wcodcol;
      BDREF             = wref;
      BDBFGTS           = wbasefgts;
      BDFGTS            = wvalorfgts;
      BDBFGTS13         = wbasefgts13;
      BDFGTS13          = wvalorfgts13;
      BDBFGTSRESC       = wbasefgtsresc;
      BDFGTSRESC        = wvalorfgtsresc;
      BDBFGTS13RESC     = wbasefgts13resc;
      BDFGTS13RESC      = wvalorfgts13resc;
      BDBFGTSINDESOCIAL = wbasefgtsindesocial;
      BDFGTSINDESOCIAL  = wvalorfgtsindesocial;
      BDBFGTS13ESOCIAL  = wbasefgts13esocial;
      BDFGTS13ESOCIAL   = wvalorfgts13esocial;
      BDBFGTSMESESOCIAL = wbasefgtsmesesocial;
      BDFGTSMESESOCIAL  = wvalorfgtsmesesocial;
      BDDATAPROC        = wdataproc;
      BDHORAPROC        = whoraproc;
      BDORDEM           = wordem;
      BDTIPOEVT         = wtipoevt;
      SUSPEND;
    END
end^

/* Restore proc. body: SP_VRHF_DADOS_FGTS_13 */
CREATE OR ALTER procedure SP_VRHF_DADOS_FGTS_13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer,
    PRCODMATRIZ varchar(15000))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer)
as
declare variable WSQL varchar(32700);
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WBASEFGTS numeric(18,6);
declare variable WVALORFGTS numeric(18,6);
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WORDEM integer;
BEGIN
/*
  13º SALÁRIO
*/

  wusartmp_emp_select = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
    wusartmp_emp_select = 1;

  IF (prpuxarfiliais = 0) THEN
    BEGIN
      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13, FOL.BDBASEFGTS13, FOL.BDFGTS13, FOL.BDDATAPROC13, FOL.BDHORAPROC13, FOL.BDORDEM BDORDEMC13 ';
      IF (wusartmp_emp_select = 1) THEN
        BEGIN
          wsql = wsql || ' from (select FO.BDCODEMP, FO.BDCODCOL, FO.BDREF13, FO.BDBASEFGTS13, FO.BDFGTS13, FO.BDDATAPROC13, FO.BDHORAPROC13, FO.BDORDEM from VRHF_EMP_T13SAL FO' || ' inner join TMP_EMPRESAS_SELECT EMPSEL on EMPSEL.BDCODEMP = FO.BDCODEMP ) FOL ';
        END
      ELSE
        wsql = wsql || ' from VRHF_EMP_T13SAL FOL ';

      wsql = wsql || ' where ((FOL.BDREF13 >= ' || prrefini || ' and FOL.BDREF13 <=' || prreffim || ')';

      IF((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
        wsql = wsql || ' and ' || prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ') order by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13 ';
    END
  ELSE
    BEGIN
      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13, FOL.BDBASEFGTS13, FOL.BDFGTS13, FOL.BDDATAPROC13, FOL.BDHORAPROC13, FOL.BDORDEM BDORDEMC13';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from TMP_EMPRESAS_SELECT EMP ' ||
                         ' inner join (select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13, FOL.BDBASEFGTS13, FOL.BDFGTS13, FOL.BDDATAPROC13, FOL.BDHORAPROC13, FOL.BDORDEM from VRHF_EMP_T13SAL FOL) FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from TEMPRESAS EMP ';
          wsql = wsql || ' join VRHF_EMP_T13SAL FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END

      wsql = wsql || 'where ((FOL.BDREF13 >= ' || prrefini || ' and FOL.BDREF13 <= '||prreffim||')';
     
      IF (WUSARTMP_EMP_SELECT = 0) THEN
        BEGIN
          IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            wsql = wsql || ' and (('||prcodemp || ') ';

          IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
            wsql = wsql || ' or ('||prcodmatriz || ') ';
        
          IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
            wsql = wsql || ') ';
        END

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql||') order by EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13 ';
    END

  wcodemp    = 0;
  wcodcol    = 0;
  wref       = 0;
  wbasefgts  = 0;
  wvalorfgts = 0;
  wordem     = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wref, :wbasefgts, :wvalorfgts, :wdataproc, :whoraproc, :wordem DO
    BEGIN
      BDCODEMP   = wcodemp;
      BDCODCOL   = wcodcol;
      BDREF      = wref;
      BDBFGTS    = wbasefgts;
      BDFGTS     = wvalorfgts;
      BDDATAPROC = wdataproc;
      BDHORAPROC = whoraproc;
      BDORDEM    = wordem;
      SUSPEND;
    END

/* FOLHA INTERMITENTE */

  IF (prpuxarfiliais = 0) THEN
    BEGIN
      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDBFGTS13FN, FOL.BDFGTS13FN, FOL.BDDATAPROCFN, FOL.BDHORAPROCFN, 0 BDORDEMC13 ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from (select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFN, FN.BDBFGTSFN, FN.BDFGTSFN, FN.BDBFGTS13FN, FN.BDFGTS13FN, FN.BDDATAPROCFN, FN.BDHORAPROCFN from VRHF_EMP_TFOLHAINT FN' || ' inner join TMP_EMPRESAS_SELECT EMPSEL on EMPSEL.BDCODEMP = FN.BDCODEMP ) FOL ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from VRHF_EMP_TFOLHAINT FOL ';
        END

      wsql = wsql || ' left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >=' || prrefini || ' ) ';
      wsql = wsql || ' where (FOL.BDREFFN >= ' || prrefini || ' and FOL.BDREFFN <=' || prreffim || ')';

      IF((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
        wsql = wsql || ' and ' || prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN ';
    END
  ELSE
    BEGIN
      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDBFGTS13FN, FOL.BDFGTS13FN, FOL.BDDATAPROCFN, FOL.BDHORAPROCFN, 0 BDORDEMC13 ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from TMP_EMPRESAS_SELECT EMP '
                      || ' inner join (SELECT FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFN, FN.BDBFGTSFN, FN.BDFGTSFN, FN.BDBFGTS13FN, FN.BDFGTS13FN, FN.BDDATAPROCFN, FN.BDHORAPROCFN FROM VRHF_EMP_TFOLHAINT FN) FOL ON (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from TEMPRESAS EMP ';
          wsql = wsql || ' join VRHF_EMP_TFOLHAINT FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END

      wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC on (Resc.BDCODEMP = EMP.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >= '||prrefini||') ';
      wsql = wsql || 'where (FOL.BDREFFN >= ' || prrefini || ' and FOL.BDREFFN <= ' || prreffim || ')';
     
      IF (WUSARTMP_EMP_SELECT = 0) THEN
        BEGIN
          IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            wsql = wsql || ' and ((' || prcodemp || ') ';

          IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
            wsql = wsql || ' or (' || prcodmatriz || ') ';
        
          IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
            wsql = wsql || ') ';
        END

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN ';
    END

  wcodemp    = 0;
  wcodcol    = 0;
  wref       = 0;
  wbasefgts  = 0;
  wvalorfgts = 0;
  wordem     = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wref, :wbasefgts, :wvalorfgts, :wdataproc, :whoraproc, :wordem DO
    BEGIN
      BDCODEMP   = wcodemp;
      BDCODCOL   = wcodcol;
      BDREF      = wref;
      BDBFGTS    = wbasefgts;
      BDFGTS     = wvalorfgts;
      BDDATAPROC = wdataproc;
      BDHORAPROC = whoraproc;
      BDORDEM    = wordem;
      SUSPEND;
    END

/* FOLHA TOMADOR INTERMITENTE */

  IF (prpuxarfiliais = 0) THEN
    BEGIN
--      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDBFGTS13FT, FOL.BDFGTS13FT, FOL.BDDATAPROCFT, FOL.BDHORAPROCFT, FOL.BDORDEM BDORDEMC13 ';

      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, '
          || ' case'
          || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDBFGTS13FT'
          || '   else 0 '
          || ' end BDBFGTS13FT,'
          || ' case'
          || '   when (RESC.BDREFRESCISAO is null) or (RESC.BDREFRESCISAO <> FOL.BDREFTOMADOR) then FOL.BDFGTS13FT'
          || '   else 0 '
          || ' end BDFGTS13FT,'
          || ' FOL.BDDATAPROCFT, FOL.BDHORAPROCFT, FOL.BDORDEM BDORDEMC13 ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from (select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFTOMADOR, FN.BDBFGTS13FT, FN.BDFGTS13FT, FN.BDDATAPROCFT, FN.BDHORAPROCFT, FN.BDORDEM from VRHF_EMP_TFOLHATOMINT FN' || ' inner join TMP_EMPRESAS_SELECT EMPSEL on EMPSEL.BDCODEMP = FN.BDCODEMP ) FOL ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from VRHF_EMP_TFOLHATOMINT FOL ';
        END

      wsql = wsql || ' left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >=' || prrefini || ' ) ';
      wsql = wsql || ' where (FOL.BDREFTOMADOR >= ' || prrefini || ' and FOL.BDREFTOMADOR <=' || prreffim || ')';

      IF((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
        wsql = wsql || ' and ' || prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR ';
    END
  ELSE
    BEGIN
      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDBFGTS13FT, FOL.BDFGTS13FT, FOL.BDDATAPROCFT, FOL.BDHORAPROCFT, FOL.BDORDEM BDORDEMC13 ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from TMP_EMPRESAS_SELECT EMP '
                      || ' inner join (SELECT FN.BDCODEMP, FN.BDCODCOL, FN.BDREFTOMADOR, FN.BDBFGTS13FT, FN.BDFGTS13FT, FN.BDDATAPROCFT, FN.BDHORAPROCFT, FN.BDORDEM FROM VRHF_EMP_TFOLHATOMINT FN) FOL ON (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from TEMPRESAS EMP ';
          wsql = wsql || ' join VRHF_EMP_TFOLHATOMINT FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END

      wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC on (Resc.BDCODEMP = EMP.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL) and (RESC.BDREFRESCISAO >= '||prrefini||') ';
      wsql = wsql || 'where (FOL.BDREFTOMADOR >= ' || prrefini || ' and FOL.BDREFTOMADOR <= ' || prreffim || ')';
     
      IF (WUSARTMP_EMP_SELECT = 0) THEN
        BEGIN
          IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            wsql = wsql || ' and ((' || prcodemp || ') ';

          IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
            wsql = wsql || ' or (' || prcodmatriz || ') ';
        
          IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
            wsql = wsql || ') ';
        END

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR ';
    END

  wcodemp    = 0;
  wcodcol    = 0;
  wref       = 0;
  wbasefgts  = 0;
  wvalorfgts = 0;
  wordem     = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wref, :wbasefgts, :wvalorfgts, :wdataproc, :whoraproc, :wordem DO
    BEGIN
      BDCODEMP   = wcodemp;
      BDCODCOL   = wcodcol;
      BDREF      = wref;
      BDBFGTS    = wbasefgts;
      BDFGTS     = wvalorfgts;
      BDDATAPROC = wdataproc;
      BDHORAPROC = whoraproc;
      BDORDEM    = wordem;
      SUSPEND;
    END
END^

/* Restore proc. body: SP_VRHF_DADOS_FGTS_A13 */
CREATE OR ALTER procedure SP_VRHF_DADOS_FGTS_A13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer,
    PRCODMATRIZ varchar(15000))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDORDEM integer)
as
declare variable WSQL varchar(32700);
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WBASEFGTS numeric(18,6);
declare variable WVALORFGTS numeric(18,6);
declare variable WORDEM integer;
begin
/*
  13º SALÁRIO
*/

  WUSARTMP_EMP_SELECT = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
    WUSARTMP_EMP_SELECT = 1;

  IF (prpuxarfiliais = 0) THEN
    BEGIN
      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFA13, FOL.BDBASEFGTSA13, FOL.BDFGTSA13, FOL.BDORDEM ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from (select FO.BDCODEMP, FO.BDCODCOL, FO.BDREFA13, FO.BDBASEFGTSA13, FO.BDFGTSA13, FO.BDORDEM from VRHF_EMP_TA13SAL FO' || ' inner join TMP_EMPRESAS_SELECT EMPSEL on EMPSEL.BDCODEMP = FO.BDCODEMP ) FOL ';
        END
      ELSE
        wsql = wsql || ' from VRHF_EMP_TA13SAL FOL ';

      wsql = wsql || ' where ((FOL.BDREFA13 >= ' || prrefini || ' and FOL.BDREFA13 <=' || prreffim || ')';

      IF((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
        wsql = wsql || ' and ' || prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ') order by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFA13 ';
    END
  ELSE
    BEGIN
      wsql = 'select EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFA13, FOL.BDBASEFGTSA13, FOL.BDFGTSA13, FOL.BDORDEM ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from TMP_EMPRESAS_SELECT EMP ' ||
                         ' inner join (select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFA13, FOL.BDBASEFGTSA13, FOL.BDFGTSA13, FOL.BDORDEM from VRHF_EMP_TA13SAL FOL) FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from TEMPRESAS EMP ';
          wsql = wsql || ' join VRHF_EMP_TA13SAL FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END

      wsql = wsql || 'where ((FOL.BDREFA13 >= ' || prrefini || ' and FOL.BDREFA13 <= '||prreffim||')';
     
      IF (WUSARTMP_EMP_SELECT = 0) THEN
        BEGIN
          IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            wsql = wsql || ' and (('||prcodemp || ') ';

          IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
            wsql = wsql || ' or ('||prcodmatriz || ') ';
        
          IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
            wsql = wsql || ') ';
        END

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ') order by EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFA13 ';
    END

  WCODEMP    = 0;
  WCODCOL    = 0;
  WREF       = 0;
  WBASEFGTS  = 0;
  WVALORFGTS = 0;
  WORDEM     = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wref, :wbasefgts, :wvalorfgts, :wordem DO
    BEGIN
      BDCODEMP = wcodemp;
      BDCODCOL = wcodcol;
      BDREF    = wref;
      BDBFGTS  = wbasefgts;
      BDFGTS   = wvalorfgts;
      BDORDEM  = wordem;
      SUSPEND;
    END

end^

/* Restore proc. body: SP_VRHF_DADOS_FGTS_C13 */
CREATE OR ALTER procedure SP_VRHF_DADOS_FGTS_C13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '')
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDTIPO integer,
    BDFGTS numeric(18,6),
    BDBFGTS numeric(18,6),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer)
as
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WBASEFGTS13 numeric(18,6);
declare variable WVALORFGTS13 numeric(18,6);
declare variable WREFC13 integer;
declare variable WDATAPROC date;
declare variable WHORAPROC time;
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WORDEM integer;
BEGIN
  /*
      COMPLEMENTO DE 13º SALÁRIO
  */
  WUSARTMP_EMP_SELECT = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
    WUSARTMP_EMP_SELECT = 1;

  IF (prpuxarfiliais = 0) THEN
    BEGIN
      wsql = 'select * from (';

      wsql = wsql || 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13, FOL.BDREFC13, FOL.BDBASEFGTSC13, FOL.BDFGTSC13, FOL.BDDATAPROCC13,FOL.BDHORAPROCC13, FOL.BDORDEM BDORDEMC13 ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        wSQL = wSQL || ' from (select FO.BDCODEMP, FO.BDCODCOL, FO.BDREF13, FO.BDREFC13, FO.BDBASEFGTSC13, FO.BDFGTSC13, FO.BDDATAPROCC13, FO.BDHORAPROCC13, FO.BDORDEM  from vrhf_emp_tc13sal FO inner join TMP_EMPRESAS_SELECT EMPSEL on EMPSEL.BDCODEMP = FO.BDCODEMP) FOL ';
      ELSE
        wSQL = wSQL || 'from VRHF_EMP_TC13SAL FOL ';

      wsql = wsql || 'where FOL.BDREFC13 >= ' || prrefini || ' and FOL.BDREFC13 <= ' || prreffim || ' ';
     
      IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
        wsql = wsql || ' and ' || prcodemp;
     
      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;
     
      wsql = wsql || ' union all ';
      wsql = wsql || 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN BDREF13, FOL.BDREFFC BDREFC13, FOL.BDBFGTS13FC BDBASEFGTSC13, FOL.BDFGTS13FC BDFGTSC13, FOL.BDDATAPROCFC BDDATAPROCC13, FOL.BDHORAPROCFC BDHORAPROCC13, 0 BDORDEM';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wSQL = wSQL || ' from (select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDREFCOMP BDREFFC, FOL.BDBFGTS13FC, FOL.BDFGTS13FC, FOL.BDDATAPROCFC, FOL.BDHORAPROCFC, 0 BDORDEM from VRHF_EMP_TFOLHACOMP FOL '||
                         ' inner join TMP_EMPRESAS_SELECT EMPSEL on EMPSEL.BDCODEMP = FOL.BDCODEMP ) FOL ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from VRHF_EMP_TFOLHACOMP FOL ';
        END

      wsql = wsql || ' where exists(select first 1 * from VRHF_EMP_TVERBAFC FVAUX ' ||
                                  ' join VRH_BASE_TVERBAS FVVER on FVVER.BDCODVER = FVAUX.BDCODVER ' ||
                                  ' where FVAUX.BDCODEMP = FOL.BDCODEMP and' ||
                                        ' FVAUX.BDCODCOL = FOL.BDCODCOL and' ||
                                        ' FVAUX.BDREFFN  = FOL.BDREFFN and' ||
                                        ' FVAUX.BDREFFC  = FOL.BDREFFC and' ||
                                        ' FVVER.BDCLAVER like ''0.601.%'' ) and' ||
                           ' FOL.BDREFFC >= '||prrefini||' and FOL.BDREFFC <= ' || prreffim || ' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '' AND WUSARTMP_EMP_SELECT = 0) THEN
          wsql = wsql || ' and ' || prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql || ' and ' || prcodcol;
     
       wsql = wsql || ') X order by X.BDCODEMP, X.BDCODCOL, X.BDREF13, X.BDREFC13 ';
     END
  ELSE
    BEGIN
      wsql = 'select EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13, FOL.BDREFC13, FOL.BDBASEFGTSC13, FOL.BDFGTSC13, FOL.BDDATAPROCC13, FOL.BDHORAPROCC13, FOL.BDORDEM BDORDEMFC13 ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        wSQL = wSQL || ' from TMP_EMPRESAS_SELECT EMP INNER join (select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13, FOL.BDREFC13, FOL.BDBASEFGTSC13, FOL.BDFGTSC13, FOL.BDDATAPROCC13, FOL.BDHORAPROCC13, FOL.BDORDEM from VRHF_EMP_TC13SAL FOL) FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
      ELSE
        wSQL = wSQL || ' from TEMPRESAS EMP join VRHF_EMP_TC13SAL FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';

      wsql = wsql || ' where FOL.BDREFC13 >= ' || prrefini || ' and FOL.BDREFC13 <= ' || prreffim || ' ';

      IF (WUSARTMP_EMP_SELECT = 0) THEN
        BEGIN
          IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            wsql = wsql||' and (('||prcodemp||')';
          
          IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
            wsql = wsql||' or ('||prcodmatriz||')';
          
          IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
            wsql = wsql||') ';
        END

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol||' ';

      wsql = wsql||' order by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13, FOL.BDREFC13 ';
    END

  wcodemp      = 0;
  wcodcol      = 0;
  wref         = 0;
  wbasefgts13  = 0;
  wvalorfgts13 = 0;
  wrefc13      = 0;
  wdataproc    = NULL;
  whoraproc    = NULL;
  wordem       = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wref, :wrefc13, :wbasefgts13, :wvalorfgts13, :wdataproc, :whoraproc, :wordem DO
    BEGIN
      --EXECUTE PROCEDURE sp_seta_competencia(:wrefc13, NULL, NULL);

      IF ((wref >= prrefini AND wref <= prreffim) and
          ((wbasefgts13 > 0) OR (wvalorfgts13 > 0))) THEN
        BEGIN
          BDCODEMP   = wcodemp;
          BDCODCOL   = wcodcol;
          BDREF      = wref;
          BDTIPO     = 11;         -- Complemento 13º salário
          BDBFGTS    = wbasefgts13;
          BDFGTS     = wvalorfgts13;
          BDDATAPROC = wdataproc;
          BDHORAPROC = whoraproc;
          BDORDEM    = wOrdem;
          SUSPEND;
        END
    END
END^

/* Restore proc. body: SP_VRHF_DADOS_FGTS_FER */
CREATE OR ALTER PROCEDURE SP_VRHF_DADOS_FGTS_FER (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(30000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRPUXARFILIAIS INTEGER,
    PRCODMATRIZ VARCHAR(15000))
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREF INTEGER,
    BDBFGTS NUMERIC(18,6),
    BDFGTS NUMERIC(18,6),
    BDORDEM INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WUSARTMP_EMP_SELECT SMALLINT;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WREF INTEGER;
DECLARE VARIABLE WBASEFGTS NUMERIC(18,6);
DECLARE VARIABLE WVALORFGTS NUMERIC(18,6);
DECLARE VARIABLE WORDEM INTEGER;
BEGIN

/*
  FÉRIAS
*/

  WUSARTMP_EMP_SELECT = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
    WUSARTMP_EMP_SELECT = 1;

  IF (prpuxarfiliais = 0) THEN
    BEGIN
      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFE, FOL.BDBASEFGTSRFE, FOL.BDVALORFGTSRFE, 0 BDORDEMFER ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from (select FER.BDCODEMP, FER.BDCODCOL, FER.BDREFFE, FER.BDBASEFGTSRFE, FER.BDVALORFGTSRFE from VRH_EMP_TFERIASREF FER' || ' inner join TMP_EMPRESAS_SELECT EMPSEL on EMPSEL.BDCODEMP = FER.BDCODEMP ) FOL ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from VRH_EMP_TFERIASREF FOL ';
        END

      wsql = wsql || ' where (FOL.BDREFFE >= ' || prrefini || ' and FOL.BDREFFE <=' || prreffim || ')';

      IF((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
        wsql = wsql || ' and ' || prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFE ';
    END
  ELSE
    BEGIN
      wsql = ' select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFE, FOL.BDBASEFGTSRFE, FOL.BDVALORFGTSRFE, 0 BDORDEMFER ';

      IF (WUSARTMP_EMP_SELECT = 1) THEN
        BEGIN
          wsql = wsql || ' from TMP_EMPRESAS_SELECT EMP '
                      || ' inner join (select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFE, FOL.BDBASEFGTSRFE, FOL.BDVALORFGTSRFE FROM VRH_EMP_TFERIASREF FOL) FOL ON (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END
      ELSE
        BEGIN
          wsql = wsql || ' from TEMPRESAS EMP ';
          wsql = wsql || ' join VRH_EMP_TFERIASREF FOL on (FOL.BDCODEMP = EMP.BDCODEMP) ';
        END

      wsql = wsql || 'where (FOL.BDREFFE >= ' || prrefini || ' and FOL.BDREFFE <= ' || prreffim || ')';
     
      IF (WUSARTMP_EMP_SELECT = 0) THEN
        BEGIN
          IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            wsql = wsql || ' and ((' || prcodemp || ') ';

          IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
            wsql = wsql || ' or (' || prcodmatriz || ') ';
        
          IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
            wsql = wsql || ') ';
        END

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql || ' and ' || prcodcol;

      wsql = wsql || ' order by EMP.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFE ';
    END

  WCODEMP    = 0;
  WCODCOL    = 0;
  WREF       = 0;
  WBASEFGTS  = 0;
  WVALORFGTS = 0;
  WORDEM     = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wref, :wbasefgts, :wvalorfgts, :wordem DO
    BEGIN
      BDCODEMP = wcodemp;
      BDCODCOL = wcodcol;
      BDREF    = wref;
      BDBFGTS  = wbasefgts;
      BDFGTS   = wvalorfgts;
      BDORDEM  = wordem;
      SUSPEND;
    END
END^

/* Restore proc. body: SP_VRHF_DADOS_PIS_FN */
CREATE OR ALTER procedure SP_VRHF_DADOS_PIS_FN (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '')
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODVER integer,
    BDBASEPISFE numeric(15,6),
    BDBASEPIS13 numeric(15,6),
    BDBASEPISFN numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCTALON varchar(20),
    BDCODTER integer)
as
declare variable WTIPOVER integer;
declare variable WBASEPIS varchar(10);
declare variable WSQL varchar(5000);
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
BEGIN
  /* Procedure Text */
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODVER,FOL.BDVALVFN,VER.BDCLAVER from (';

       wsql = wsql||'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODVER,FOL.BDVALVFN '||
              'from vrhf_emp_tverbafn FOL ';
       wsql = wsql||'join vrhf_emp_tfolhanormal FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFfn = FOL.BDREFfn) ';
       wsql = wsql||'where FOL.BDREFfn >= '||prrefini||' and FOL.BDREFfn <= '||prreffim||' ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||' union all select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFN,FOL.BDCODVER,FOL.BDVALVFN '||
              'from vrhf_emp_tverbaint FOL ';
       wsql = wsql||'join vrhf_emp_tfolhaint FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFfn = FOL.BDREFfn and FOLN.BDCODCONTTI = FOL.BDCODCONTTI) ';
       wsql = wsql||'where FOL.BDREFfn >= '||prrefini||' and FOL.BDREFfn <= '||prreffim||' ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||') FOL join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFfn ';
     END
  ELSE
     BEGIN
       wsql = 'select FO.BDCODEMP,FO.BDCODCOL,FO.BDREFFN,FO.BDCODVER,FO.BDVALVFN,VER.BDCLAVER from (';

       wsql = wsql||'select '||
                'FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFFN,FO.BDCODVER,FO.BDVALVFN '||
              'from TEMPRESAS FOL '||
              'join vrhf_emp_tverbafn FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join vrhf_emp_tfolhanormal FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFfn = FO.BDREFfn) ';
       wsql = wsql||'where FO.BDREFfn >= '||prrefini||' and FO.BDREFfn <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' union all select '||
                'FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFFN,FO.BDCODVER,FO.BDVALVFN '||
              'from TEMPRESAS FOL '||
              'join vrhf_emp_tverbaint FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join vrhf_emp_tfolhaint FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFfn = FO.BDREFfn and FOLN.BDCODCONTTI = FO.BDCODCONTTI) ';
       wsql = wsql||'where FO.BDREFfn >= '||prrefini||' and FO.BDREFfn <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||') FO join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||' order by FO.BDCODEMP,FO.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFfn ';
     END

--  suspend;

  bdcodcentro = NULL;
  bdcodtpcc = NULL;
  bdctalon = NULL;

  FOR EXECUTE STATEMENT wSql INTO :bdcodemp,:bdcodcol,:bdref,:bdcodver,:wvalor,:wclassif DO
    BEGIN
      EXECUTE PROCEDURE sp_seta_competencia(:bdref,NULL,NULL);
      wBasePis = 'FALSE';
      SELECT COALESCE(BDPISVER,'FALSE'),BDTIPOCODVER FROM VW_VERBAS_REF_ATUAL WHERE bdcodver = :bdcodver INTO wbasepis,WTIPOVER;

      IF (wtipover IN (0,1)) THEN
         BEGIN
           IF ((UPPER(wbasepis) = 'TRUE') OR (UPPER(wbasepis) = 'T')) THEN
              BEGIN
                IF (wtipover = 1) THEN
                   wvalor = wvalor * -1;

                 bdbasepis13 = 0;
                 bdbasepisfe = 0;
                 bdbasepisfn = 0;

                -- Verifica se a verba é base 13º
                IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('4','5','6')) OR
                    (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.200','7.050','7.060','7.061','7.070','7.071','7.080')) OR
                    (SUBSTRING(wclassif FROM 1 FOR 9) = '0.800.6.2')) THEN
                   bdbasepis13 = wvalor;
                -- Verifica se a verba é base FEr
                ELSE IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('3')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.100','0.110','0.120','0.130','0.140','0.150','0.160',
                                                         '0.170','0.180','0.190','7.010','7.011','7.012','7.020','7.021',
                                                         '7.030','7.031','7.032','7.033'))) THEN
                   bdbasepisfe = wvalor;
                ELSE -- Senão é base FN
                    bdbasepisfn = wvalor;

                SUSPEND;
              END
         END

    END

   /******************************************************/
   /******************************************************/
   /******************************************************/
   /******************************************************/
   /* Folha por tomador */
   /******************************************************/
   /******************************************************/
   /******************************************************/
   /******************************************************/

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDCODVER,FOL.BDVALVFT,VER.BDCLAVER,prep.BDCODCENTRO,prep.bdcodtpcc, cen.BDCTALON from (';
       wsql = wsql||'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDCODVER,FOL.BDVALVFT, FOL.BDORDEM '||
              'from vrhf_emp_tverbatomador FOL ';
       wsql = wsql||'join vrhf_emp_tfolhatomador FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFTOMADOR = FOL.BDREFTOMADOR and fol.bdordem = foln.bdordem) ';
       wsql = wsql||'where FOL.BDREFTOMADOR >= '||prrefini||' and FOL.BDREFTOMADOR <= '||prreffim||' ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||' union all select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR,FOL.BDCODVER,FOL.BDVALVFT,FOL.BDORDEM '||
              'from vrhf_emp_tverbatomint FOL ';
       wsql = wsql||'join vrhf_emp_tfolhatomint FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFTOMADOR = FOL.BDREFTOMADOR and fol.bdordem = foln.bdordem and FOLN.BDCODCONTTI = FOL.BDCODCONTTI) ';
       wsql = wsql||'where FOL.BDREFTOMADOR >= '||prrefini||' and FOL.BDREFTOMADOR <= '||prreffim||' ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       wsql = wsql||') FOL join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join VRHF_EMP_TPREPFN prep on (FOL.BDCODEMP = prep.BDCODEMP and FOL.BDCODCOL = prep.BDCODCOL and prep.bdordem = fol.bdordem) ';
       wsql = wsql||'left outer join CENTROS_TPCC cen on (cen.BDCODCENTRO = prep.BDCODCENTRO and cen.BDCODTPCC = prep.BDCODTPCC) ';
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFTOMADOR ';
     END
  ELSE
     BEGIN
       wsql = 'select FO.BDCODEMP,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDCODVER,FO.BDVALVFT,VER.BDCLAVER,prep.BDCODCENTRO,prep.bdcodtpcc, cen.BDCTALON from (';
       wsql = wsql||'select FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDCODVER,FO.BDVALVFT,FO.BDORDEM '||
              'from TEMPRESAS FOL '||
              'join vrhf_emp_tverbatomador FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join vrhf_emp_tfolhatomador FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFTOMADOR = FO.BDREFTOMADOR and fo.bdordem = foln.bdordem) ';
       wsql = wsql||'where FO.BDREFTOMADOR >= '||prrefini||' and FO.BDREFTOMADOR <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' union all select FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFTOMADOR,FO.BDCODVER,FO.BDVALVFT,FO.BDORDEM '||
              'from TEMPRESAS FOL '||
              'join vrhf_emp_tverbatomint FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join vrhf_emp_tfolhatomint FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFTOMADOR = FO.BDREFTOMADOR and fo.bdordem = foln.bdordem and FOLN.BDCODCONTTI = FO.BDCODCONTTI) ';
       wsql = wsql||'where FO.BDREFTOMADOR >= '||prrefini||' and FO.BDREFTOMADOR <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';


       wsql = wsql||') FO join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join VRHF_EMP_TPREPFN prep on (FO.BDCODEMP = prep.BDCODEMP and FO.BDCODCOL = prep.BDCODCOL and prep.bdordem = fo.bdordem) ';
       wsql = wsql||'left outer join CENTROS_TPCC cen on (cen.BDCODCENTRO = prep.BDCODCENTRO and cen.BDCODTPCC = prep.BDCODTPCC) ';
       wsql = wsql||' order by FO.BDCODEMP,FO.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFTOMADOR ';
     END

--  suspend;

  bdcodcentro = NULL;
  bdcodtpcc = NULL;
  bdctalon = NULL;

  FOR EXECUTE STATEMENT wSql INTO :bdcodemp,:bdcodcol,:bdref,:bdcodver,:wvalor,:wclassif,:BDCODCENTRO,:bdcodtpcc,:bdctalon DO
    BEGIN
      EXECUTE PROCEDURE sp_seta_competencia(:bdref,NULL,NULL);
      wBasePis = 'FALSE';
      SELECT COALESCE(BDPISVER,'FALSE'),BDTIPOCODVER FROM VW_VERBAS_REF_ATUAL WHERE bdcodver = :bdcodver INTO wbasepis,WTIPOVER;

      IF (wtipover IN (0,1)) THEN
         BEGIN
           IF ((UPPER(wbasepis) = 'TRUE') OR (UPPER(wbasepis) = 'T')) THEN
              BEGIN
                IF (wtipover = 1) THEN
                   wvalor = wvalor * -1;

                 bdbasepis13 = 0;
                 bdbasepisfe = 0;
                 bdbasepisfn = 0;

                -- Verifica se a verba é base 13º
                IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('4','5','6')) OR
                    (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.200','7.050','7.060','7.061','7.070','7.071','7.080')) OR
                    (SUBSTRING(wclassif FROM 1 FOR 9) = '0.800.6.2')) THEN
                   bdbasepis13 = wvalor;
                -- Verifica se a verba é base FEr
                ELSE IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('3')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.100','0.110','0.120','0.130','0.140','0.150','0.160',
                                                         '0.170','0.180','0.190','7.010','7.011','7.012','7.020','7.021',
                                                         '7.030','7.031','7.032','7.033'))) THEN
                   bdbasepisfe = wvalor;
                ELSE -- Senão é base FN
                    bdbasepisfn = wvalor;

                SUSPEND;
              END
         END

    END

   /******************************************************/
   /******************************************************/
   /******************************************************/
   /******************************************************/
   /* Folha de autônomos */
   /******************************************************/
   /******************************************************/
   /******************************************************/
   /******************************************************/

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP, FO.BDREFINSSSERV, FO.BDCODVER, FO.BDVALOR, VER.BDCLAVER, PREP.BDCODCENTRO, PREP.BDCODTPCC, CEN.BDCTALON from (';
       wsql = wsql||'select FOL.BDCODEMP, FOL.BDCODMATRIZ, FO.BDCODTER, FOLN.BDREFINSSSERV, FO.BDCODVER, FO.BDVALOR, FO.BDCODSERV '||
              'from VRHF_BASE_ITEMS_CALCTERC FOL ';
       wsql = wsql||'join VRHF_BASE_CALC_TERC FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODTER = FOL.BDCODTER and FOLN.BDCODSERV = FOL.BDCODSERV) ';
       wsql = wsql||'where FOL.BDREFINSSSERV >= '||prrefini||' and FOL.BDREFINSSSERV <= '||prreffim||' ';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;

       wsql = wsql||') FOL join vrh_base_tverbas VER on (VER.bdcodver = FOL.bdcodver) ';
       wsql = wsql||'join VRH_BASE_TSERVTERC prep on (FOL.BDCODEMP = prep.BDCODEMP and FOL.BDCODTER = prep.BDCODTER and prep.BDCODSERV = fol.BDCODSERV) ';
       wsql = wsql||'left outer join CENTROS_TPCC cen on (cen.BDCODCENTRO = prep.BDCODCENTRO and cen.BDCODTPCC = prep.BDCODTPCC) ';
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODTER,FOL.BDREFINSSSERV ';
     END
  ELSE
     BEGIN
       wsql = 'select FO.BDCODEMP, FO.BDCODTER, FO.BDREFINSSSERV, FO.BDCODVER, FO.BDVALOR, VER.BDCLAVER, PREP.BDCODCENTRO, PREP.BDCODTPCC, CEN.BDCTALON from (';
       wsql = wsql||'select FOL.BDCODEMP, FOL.BDCODMATRIZ, FO.BDCODTER, FOLN.BDREFINSSSERV, FO.BDCODVER, FO.BDVALOR, FO.BDCODSERV '||
              'from TEMPRESAS FOL '||
              'join VRHF_BASE_ITEMS_CALCTERC FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join VRHF_BASE_CALC_TERC FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODTER = FO.BDCODTER and FO.BDCODSERV = FOLN.BDCODSERV) ';
       wsql = wsql||'where FOLN.BDREFINSSSERV >= '||prrefini||' and FOLN.BDREFINSSSERV <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       wsql = wsql||') FO join vrh_base_tverbas VER on (VER.bdcodver = FO.bdcodver) ';
       wsql = wsql||'join VRH_BASE_TSERVTERC PREP on (FO.BDCODEMP = PREP.BDCODEMP and FO.BDCODTER = PREP.BDCODTER and PREP.BDCODSERV = FO.BDCODSERV) ';
       wsql = wsql||'left outer join CENTROS_TPCC cen on (cen.BDCODCENTRO = prep.BDCODCENTRO and cen.BDCODTPCC = prep.BDCODTPCC) ';
       wsql = wsql||' order by FO.BDCODEMP, FO.BDCODMATRIZ, FO.BDCODTER, FO.BDREFINSSSERV ';
     END

--  suspend;

  bdcodcentro = NULL;
  bdcodtpcc = NULL;
  bdctalon = NULL;
  bdcodcol = NULL;

  FOR EXECUTE STATEMENT wSql INTO :bdcodemp,:bdcodter,:bdref,:bdcodver,:wvalor,:wclassif,:BDCODCENTRO,:bdcodtpcc,:bdctalon DO
    BEGIN
      EXECUTE PROCEDURE sp_seta_competencia(:bdref,NULL,NULL);
      wBasePis = 'FALSE';
      SELECT COALESCE(BDPISVER,'FALSE'),BDTIPOCODVER FROM VW_VERBAS_REF_ATUAL WHERE bdcodver = :bdcodver INTO wbasepis,WTIPOVER;

      IF (wtipover IN (0,1)) THEN
         BEGIN
           IF ((UPPER(wbasepis) = 'TRUE') OR (UPPER(wbasepis) = 'T')) THEN
              BEGIN
                IF (wtipover = 1) THEN
                   wvalor = wvalor * -1;

                 bdbasepis13 = 0;
                 bdbasepisfe = 0;
                 bdbasepisfn = 0;

                -- Verifica se a verba é base 13º
                IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('4','5','6')) OR
                    (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.200','7.050','7.060','7.061','7.070','7.071','7.080')) OR
                    (SUBSTRING(wclassif FROM 1 FOR 9) = '0.800.6.2')) THEN
                   bdbasepis13 = wvalor;
                -- Verifica se a verba é base FEr
                ELSE IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('3')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.100','0.110','0.120','0.130','0.140','0.150','0.160',
                                                         '0.170','0.180','0.190','7.010','7.011','7.012','7.020','7.021',
                                                         '7.030','7.031','7.032','7.033'))) THEN
                   bdbasepisfe = wvalor;
                ELSE -- Senão é base FN
                    bdbasepisfn = wvalor;

                SUSPEND;
              END
         END
    END

END^


/* Restore proc. body: SP_VRHF_DADOS_PIS_AD13 */
CREATE OR ALTER procedure SP_VRHF_DADOS_PIS_AD13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '')
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODVER integer,
    BDBASEPISFE numeric(15,6),
    BDBASEPIS13 numeric(15,6),
    BDBASEPISFN numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCTALON varchar(20))
as
declare variable WTIPOVER integer;
declare variable WBASEPIS varchar(10);
declare variable WSQL varchar(5000);
declare variable WVALOR numeric(18,6);
declare variable WCLASSIF varchar(20);
declare variable WDATAAUX varchar(10);
BEGIN
  /* Procedure Text */
  select first 1 ULTDIA
  from ULTIMO_DIA_MES(CAST(SUBSTRING(:PRREFINI FROM 5 FOR 2) AS SMALLINT), CAST(SUBSTRING(:PRREFINI FROM 1 FOR 4) AS INTEGER))
  into :WDATAAUX;
  WDATAAUX = SUBSTRING(:PRREFINI FROM 5 FOR 2)||'-'||lpad(WDATAAUX,  2, '0')||'-'||SUBSTRING(:PRREFINI FROM 1 FOR 4);

  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = ' select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFA13,FOL.BDCODVER,FOL.BDVALVA13,VER.BDCLAVER, ' ||
              ' CC.BDCODCENTRO, CC.BDCODTPCC, CC.BDCTALON ' ||
              ' from VRHF_EMP_TVERBAA13 FOL ' ||
              ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) ' ||
              ' join VRHF_EMP_TA13SAL FOLN on (FOLN.BDCODEMP = FOL.BDCODEMP and FOLN.BDCODCOL = FOL.BDCODCOL and FOLN.BDREFA13 = FOL.BDREFA13) ' ||
              ' left outer join SP_VRH_CC_DATA(FOL.BDCODEMP, FOL.BDCODCOL, cast('''||WDATAAUX||''' as date)) CCCOL on (CCCOL.BDCODEMP = FOL.BDCODEMP and CCCOL.BDCODCOL = FOL.BDCODCOL) ' ||
              ' left outer join CENTROS_TPCC CC on (CC.BDCODCENTRO = CCCOL.BDCODCENTRO and CC.BDCODTPCC = CCCOL.BDCODTPCC) ' ||
              ' where FOL.BDREFA13 >= '||prrefini||' and FOL.BDREFA13 <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and '||prcodemp;
     
       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFA13 ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFA13,FO.BDCODVER,FO.BDVALVA13,VER.BDCLAVER, '||
              'CC.BDCODCENTRO, CC.BDCODTPCC, CC.BDCTALON ' ||
              'from TEMPRESAS FOL '||
              'join VRHF_EMP_TVERBAA13 FO on (FO.BDCODEMP = FOL.BDCODEMP) '||
              'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FO.BDCODVER) '||
              'join VRHF_EMP_TA13SAL FOLN on (FOLN.BDCODEMP = FO.BDCODEMP and FOLN.BDCODCOL = FO.BDCODCOL and FOLN.BDREFA13 = FO.BDREFA13) '||
              'left outer join SP_VRH_CC_DATA(FO.BDCODEMP, FO.BDCODCOL, cast('''||WDATAAUX||''' as date)) CCCOL on (CCCOL.BDCODEMP = FO.BDCODEMP and CCCOL.BDCODCOL = FO.BDCODCOL) ' ||
              'left outer join CENTROS_TPCC CC on (CC.BDCODCENTRO = CCCOL.BDCODCENTRO and CC.BDCODTPCC = CCCOL.BDCODTPCC) ';
       wsql = wsql||'where FO.BDREFA13 >= '||prrefini||' and FO.BDREFA13 <= '||prreffim||' ';
     
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          wsql = wsql||' and (('||prcodemp||')';
     
       IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
          wsql = wsql||' or ('||prcodmatriz||')';

       IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
          wsql = wsql||') ';

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODMATRIZ,FO.BDCODCOL,FO.BDREFA13 ';
     END

  FOR EXECUTE STATEMENT wSql INTO :BDCODEMP,:BDCODCOL,:BDREF,:BDCODVER,:WVALOR,:WCLASSIF,:BDCODCENTRO,:BDCODTPCC,:BDCTALON DO
    BEGIN
      EXECUTE PROCEDURE sp_seta_competencia(:BDREF,NULL,NULL);
      wBasePis = 'FALSE';
      SELECT COALESCE(BDPISVER,'FALSE'),BDTIPOCODVER FROM VW_VERBAS_REF_ATUAL WHERE BDCODVER = :BDCODVER INTO wBasePis,WTIPOVER;

      IF (wtipover IN (0,1)) THEN
         BEGIN
           IF ((UPPER(wBasePis) = 'TRUE') OR (UPPER(wBasePis) = 'T')) THEN
              BEGIN
                IF (wtipover = 1) THEN
                   wvalor = wvalor * -1;

                 bdbasepis13 = 0;
                 bdbasepisfe = 0;
                 bdbasepisfn = 0;

                -- Verifica se a verba é base 13º
                IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('4','5','6')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.200','7.050','7.060','7.061','7.070','7.071','7.080'))) THEN
                   bdbasepis13 = wvalor;
                -- Verifica se a verba é base FEr
                ELSE IF ((SUBSTRING(wclassif FROM 1 FOR 1) IN ('3')) OR
                   (SUBSTRING(wclassif FROM 1 FOR 5) IN ('0.100','0.110','0.120','0.130','0.140','0.150','0.160',
                                                         '0.170','0.180','0.190','7.010','7.011','7.012','7.020','7.021',
                                                         '7.030','7.031','7.032','7.033'))) THEN
                   bdbasepisfe = wvalor;
                ELSE -- Senão é base FN
                    bdbasepisfn = wvalor;

                SUSPEND;
              END
         END

    END

END^

/* Restore proc. body: SP_VRHF_EMP_BASES_RESCISAO */
create or alter procedure SP_VRHF_EMP_BASES_RESCISAO (
    PRCODEMP varchar(25000),
    PRCODCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFAUXVFN numeric(15,6),
    BDREFVFN numeric(15,6),
    BDVALVFN numeric(15,6),
    BDIGNREFVFN varchar(5),
    BDIGNVALVFN varchar(5),
    BDSALBASEFN numeric(15,6),
    BDMAIORREMFN numeric(15,6),
    BDBFGTSFN numeric(15,6),
    BDFGTSFN numeric(15,6),
    BDFGTSCSFN numeric(15,6),
    BDBFGTS13FN numeric(15,6),
    BDFGTS13FN numeric(15,6),
    BDFGTS13CSFN numeric(15,6),
    BDCLAVER varchar(20),
    BDORDEMVER integer,
    BDCNPJEMP varchar(18),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP varchar(9),
    BDDDDEMP integer,
BDFONEEMP DM_BDTELEFONE,
    BDDDDFAXEMP integer,
BDFAXEMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDNOMCOL DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDDATANASCCOL date,
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL varchar(10),
    BDDSERIECTPSCOL varchar(1),
    BDDATAOPCAOFGTSCOL date,
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
    BDSIGLAUFCTPS varchar(2),
    BDDATARESCISAO date,
    BDDATAAVPREVIO date,
    BDDATAPAGRESCISAO date,
    BDMAIORREMUNERACAO numeric(15,6),
    BDCODPRES integer,
    BDSALDOFGTS numeric(15,6),
    BDDESCPRES varchar(110),
    BDPERCMULTAFGTS numeric(15,6),
    BDPERCMULTAFGTSCS numeric(15,6),
    BDGRRFPRES integer)
as
declare variable WSQL varchar(32700);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wsql = 'select '||
            'FN.BDCODEMP, '||
            'FN.BDCODCOL, '||
            'FN.BDCODVER, '||
            'FN.BDREFFN, '||
            'FN.BDREFAUXVFN, '||
            'FN.BDREFVFN, '||
            'FN.BDVALVFN, '||
            'FN.BDIGNREFVFN, '||
            'FN.BDIGNVALVFN, '||
            'FNB.BDSALBASEFN, '||
            'FNB.BDMAIORREMFN, '||
            'FNB.BDBFGTSFN, '||
            'FNB.BDFGTSFN, '||
            'FNB.BDFGTSCSFN, '||
            'FNB.BDBFGTS13FN, '||
            'FNB.BDFGTS13FN, '||
            'FNB.BDFGTS13CSFN, '||
            'VERBAS.BDCLAVER, '||
            'VERBAS.BDORDEMVER, '||
            'EMP.BDCNPJEMP, '||
            'EMPR.BDLOGREMP, '||
            'EMPR.BDENDEMP, '||
            'EMPR.BDNUMEMP, '||
            'EMPR.BDCOMPLEMP, '||
            'EMPR.BDBAIEMP, '||
            'EMPR.BDCEPEMP, '||
            'EMPR.BDDDDEMP, '||
            'EMPR.BDFONEEMP, '||
            'EMPR.BDDDDFAXEMP, '||
            'EMPR.BDFAXEMP, '||
            'EMPR.BDEMAILEMP, '||
            'COLCAD.BDNOMCOL, '||
            'COLCON.BDDATAADMCOL, '||
            'COLCON.BDDATANASCCOL, '||
            'COLCONDOC.BDCPFCOL, '||
            'DOCREF.BDPISCOL, '||
            'DOCREF.BDCTPSCOL, '||
            'DOCREF.BDSERIECTPSCOL, '||
            'DOCREF.BDDSERIECTPSCOL, '||
            'COLCONFGTS.BDDATAOPCAOFGTSCOL, '||
            'CID.BDNOMCID, '||
            'UF.BDSIGLAUF, '||
            'UFCTPS.BDSIGLAUF, '||
            'RESC.BDDATARESCISAO, '||
            'RESC.BDDATAAVPREVIO, '||
            'RESC.BDDATAPAGRESCISAO, '||
            'RESC.BDMAIORREMUNERACAO, '||
            'RESC.BDCODPRES, '||
            'RESC.BDSALDOFGTS, '||
            'PRESC.BDDESCPRES, '||
            'PRESC.BDPERCMULTAFGTS, '||
            'PRESC.BDPERCMULTAFGTSCS, '||
            'PRESC.BDGRRFPRES ';
            
  wsql = wsql||'from VRHF_SP_TVERBAFN(null, null, '||prref||', '||prref||', 1) FN '||
               'join VRHF_SP_TFOLHA_NORMAL(null, null, '||prref||', '||prref||', 1) FNB on (FNB.BDCODEMP = FN.BDCODEMP and FNB.BDCODCOL = FN.BDCODCOL and FNB.BDREFFN = FN.BDREFFN) '||
               'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FN.BDCODVER ) '||
               'join TEMPRESAS EMP on (EMP.BDCODEMP = FN.BDCODEMP) '||
               'join VW_TEMPRESAS_REF EMPR on (EMPR.BDCODEMP = FN.BDCODEMP and EMPR.BDCODEMP = EMP.BDCODEMP) '||
               'join VRH_EMP_TCOLCON COLCON on (COLCON.BDCODEMP = FN.BDCODEMP and COLCON.BDCODCOL = FN.BDCODCOL) '||
               'join VRH_EMP_TCOLCON_DOC COLCONDOC on (COLCONDOC.BDCODEMP = FN.BDCODEMP and COLCONDOC.BDCODCOL = FN.BDCODCOL) '||
               'join VRH_EMP_TCOL_DOC COLDOC on (COLDOC.BDCODEMP = FN.BDCODEMP and COLDOC.BDCODCOL = FN.BDCODCOL) '||
               'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS COLCONFGTS on (COLCONFGTS.BDCODEMP = FN.BDCODEMP and COLCONFGTS.BDCODCOL = FN.BDCODCOL) '||
               'left outer join TCIDADE CID on (CID.BDCODCID = EMPR.BDCODCID) '||
               'left outer join TUF UF on (UF.BDCODUF = CID.BDCODUF) '||
               'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FN.BDCODEMP and DOCREF.BDCODCOL = FN.BDCODCOL) '||
               'left outer join TUF UFCTPS on (UFCTPS.BDCODUF = DOCREF.BDCODUF) '||
               'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FN.BDCODEMP and RESC.BDCODCOL = FN.BDCODCOL) '||
               'left outer join VRH_BASE_TPREPRESC PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES) '||
               'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FN.BDCODEMP and COLCAD.BDCODCOL = FN.BDCODCOL) '
               ;

  wsql = wsql||'where exists(select X.BDCODEMP, X.BDCODCOL from VRH_EMP_TRESCISAO X where FN.BDCODEMP = X.BDCODEMP and FN.BDCODCOL = X.BDCODCOL and X.BDREFRESCISAO = '||prref||') ';
  
  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||' and '||prcodcol;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFAUXVFN,
    :BDREFVFN,
    :BDVALVFN,
    :BDIGNREFVFN,
    :BDIGNVALVFN,
    :BDSALBASEFN,
    :BDMAIORREMFN,
    :BDBFGTSFN,
    :BDFGTSFN, 
    :BDFGTSCSFN,
    :BDBFGTS13FN,
    :BDFGTS13FN, 
    :BDFGTS13CSFN,
    :BDCLAVER,
    :BDORDEMVER,
    :BDCNPJEMP,
    :BDLOGREMP,
    :BDENDEMP,
    :BDNUMEMP,
    :BDCOMPLEMP,
    :BDBAIEMP,
    :BDCEPEMP,
    :BDDDDEMP,
    :BDFONEEMP,
    :BDDDDFAXEMP,
    :BDFAXEMP,
    :BDEMAILEMP,
    :BDNOMCOL,
    :BDDATAADMCOL,
    :BDDATANASCCOL,
    :BDCPFCOL,
    :BDPISCOL,
    :BDCTPSCOL,
    :BDSERIECTPSCOL,
    :BDDSERIECTPSCOL,
    :BDDATAOPCAOFGTSCOL,
    :BDNOMCID,
    :BDSIGLAUF,
    :BDSIGLAUFCTPS,
    :BDDATARESCISAO,
    :BDDATAAVPREVIO,
    :BDDATAPAGRESCISAO,
    :BDMAIORREMUNERACAO,
    :BDCODPRES,
    :BDSALDOFGTS,
    :BDDESCPRES,
    :BDPERCMULTAFGTS,
    :BDPERCMULTAFGTSCS,
    :BDGRRFPRES
  DO
  SUSPEND;
END
^

/* Restore proc. body: SP_VRHF_EMP_TFOLHANORMAL_ANT */
create or alter procedure SP_VRHF_EMP_TFOLHANORMAL_ANT (
    PRREF integer,
    PRCODEMP varchar(20000) = null,
    PRCODCOL varchar(32700) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDDATABAIXAFN date,
    BDBFGTSFN numeric(15,6),
    BDFGTSFN numeric(15,6),
    BDFGTSCSFN numeric(15,6),
    BDBFGTS13FN numeric(15,6),
    BDFGTS13FN numeric(15,6),
    BDFGTS13CSFN numeric(15,6),
    BDMAIORREMFN numeric(15,6),
    BDBINSSFN numeric(15,6),
    BDALIQINSSFN numeric(15,6),
    BDINSSFN numeric(15,6),
    BDBIRRFFN numeric(15,6),
    BDALIQIRRFFN numeric(15,6),
    BDIRRFFN numeric(15,6),
    BDBINSS13FN numeric(15,6),
    BDALIQINSS13FN numeric(15,6),
    BDINSS13FN numeric(15,6),
    BDBIRRF13FN numeric(15,6),
    BDALIQIRRF13FN numeric(15,6),
    BDIRRF13FN numeric(15,6),
    BDBSALFAMFN numeric(15,6),
    BDSALFAMFN numeric(15,6),
    BDBRAISFN numeric(15,6),
    BDSALBASEFN numeric(15,6),
    BDDEPFN numeric(15,6),
    BDBASEPISFN numeric(15,6),
    BDBASEPISFEFN numeric(15,6),
    BDBASEPIS13FN numeric(15,6),
    BDBSALMATEMPFN numeric(15,6),
    BDSALMATEMPFN numeric(15,6),
    BDBRATAPOFN numeric(15,6),
    BDBINSSFEFOLFN numeric(15,6),
    BDINSSFEFOLFN numeric(15,6),
    BDALIQINSSFEFOLFN numeric(15,6),
    BDDEBITOFN numeric(15,6),
    BDCREDITOFN numeric(15,6),
    BDBFGTSFEFN numeric(15,6),
    BDFGTSFEFN numeric(15,6),
    BDBRATAPOFEFN numeric(15,6),
    BDBRATAPO13FN numeric(15,6))
as
declare variable WSQL varchar(32700);
declare variable WANOMES integer;
declare variable WANO varchar(4);
declare variable WMES varchar(2);
declare variable WCODEMP varchar(20000);
declare variable WCODCOL varchar(32700);
BEGIN
  if (substring(prref from 5 for 2) = '01') then
     begin
       wmes = '12';
       wano = CAST((CAST(substring(prref from 1 for 4) as INTEGER) - 1) AS VARCHAR(4));
     end
  else
     begin
       wmes = TRIM(CAST((CAST(substring(prref from 5 for 2) as INTEGER) - 1) AS VARCHAR(2)));
       wano = substring(prref from 1 for 4);

       WHILE (STRLEN(wmes) < 2) DO
         wmes = '0'||wmes;
     end

  wanomes = CAST((wano||wmes) AS INTEGER);

  IF (prcodemp IS NULL OR (prcodemp = '')) THEN
     wcodemp = 'null';
  ELSE
     wcodemp = ''''||prcodemp||'''';

  IF (prcodcol IS NULL OR (prcodcol = '')) THEN
     wcodcol = 'null';
  ELSE
     wcodcol = ''''||prcodcol||'''';

  wsql = 'select COLCON.BDCODEMP, '||
                'COLCON.BDCODCOL, '||
                'COLCON.BDREFFN, '||
                'COLCON.BDDATABAIXAFN, '||
                'COLCON.BDBFGTSFN, '||
                'COLCON.BDFGTSFN, '||
                'COLCON.BDFGTSCSFN, '||
                'COLCON.BDBFGTS13FN, '||
                'COLCON.BDFGTS13FN, '||
                'COLCON.BDFGTS13CSFN, '||
                'COLCON.BDMAIORREMFN, '||
                'COLCON.BDBINSSFN, '||
                'COLCON.BDALIQINSSFN, '||
                'COLCON.BDINSSFN, '||
                'COLCON.BDBIRRFFN, '||
                'COLCON.BDALIQIRRFFN, '||
                'COLCON.BDIRRFFN, '||
                'COLCON.BDBINSS13FN, '||
                'COLCON.BDALIQINSS13FN, '||
                'COLCON.BDINSS13FN, '||
                'COLCON.BDBIRRF13FN, '||
                'COLCON.BDALIQIRRF13FN, '||
                'COLCON.BDIRRF13FN, '||
                'COLCON.BDBSALFAMFN, '||
                'COLCON.BDSALFAMFN, '||
                'COLCON.BDBRAISFN, '||
                'COLCON.BDSALBASEFN, '||
                'COLCON.BDDEPFN, '||
                'COLCON.BDBASEPISFN, '||
                'COLCON.BDBASEPISFEFN, '||
                'COLCON.BDBASEPIS13FN, '||
                'COLCON.BDBSALMATEMPFN, '||
                'COLCON.BDSALMATEMPFN, '||
                'COLCON.BDBRATAPOFN, '||
                'COLCON.BDBRATAPOFEFN, '||
                'COLCON.BDBRATAPO13FN, '||
                'COLCON.BDBINSSFEFOLFN, '||
                'COLCON.BDINSSFEFOLFN, '||
                'COLCON.BDALIQINSSFEFOLFN, '||
                'COLCON.BDBFGTSFEFN, '||
                'COLCON.BDFGTSFEFN, '||
                'COLCON.BDCREDITOFN, '||
                'COLCON.BDDEBITOFN ';
      wsql = wsql||'from VRHF_SP_TFOLHA_NORMAL('||wcodemp||','||wcodcol||','||wanomes||','||wanomes||',1) COLCON '||
               'where COLCON.BDREFFN = '||wanomes;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFFN,
    :BDDATABAIXAFN,
    :BDBFGTSFN,
    :BDFGTSFN,
    :BDFGTSCSFN,
    :BDBFGTS13FN,
    :BDFGTS13FN,
    :BDFGTS13CSFN,
    :BDMAIORREMFN,
    :BDBINSSFN,
    :BDALIQINSSFN,
    :BDINSSFN,
    :BDBIRRFFN,
    :BDALIQIRRFFN,
    :BDIRRFFN,
    :BDBINSS13FN,
    :BDALIQINSS13FN,
    :BDINSS13FN,
    :BDBIRRF13FN,
    :BDALIQIRRF13FN,
    :BDIRRF13FN,
    :BDBSALFAMFN,
    :BDSALFAMFN,
    :BDBRAISFN,
    :BDSALBASEFN,
    :BDDEPFN,
    :BDBASEPISFN,
    :BDBASEPISFEFN,
    :BDBASEPIS13FN,
    :BDBSALMATEMPFN,
    :BDSALMATEMPFN,
    :BDBRATAPOFN,
    :BDBRATAPOFEFN,
    :BDBRATAPO13FN,
    :BDBINSSFEFOLFN,
    :BDINSSFEFOLFN,
    :BDALIQINSSFEFOLFN,
    :bdbfgtsfefn,
    :bdfgtsfefn,
    :bdcreditofn,
    :bddebitofn
  DO
  SUSPEND;
END^

/* Restore proc. body: SP_VRHF_EMP_TPROVISAO13 */
create or alter procedure SP_VRHF_EMP_TPROVISAO13 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32700),
    PRANOMES integer,
    PRTIPOPROV integer,
    PRDESCAD13 smallint = 0,
    PRMESATUAL smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFP13 integer,
    BDLINHAP13 integer,
    BDPROPP13 integer,
    BDADICIONAISP13 numeric(15,6),
    BDMEDIASP13 numeric(15,6),
    BDSALBASEP13 numeric(15,6),
    BDPLANOCC integer,
    BDORDEMCCP13 integer,
    BDVLR13SALP13 numeric(15,6),
    BDFGTSP13 numeric(15,6),
    BDINSSP13 numeric(15,6),
    BDTERCFPASP13 numeric(15,6),
    BDCNAERATP13 numeric(15,6),
    BDRATAPOP13 numeric(15,6),
    BDPISP13 numeric(15,6),
    BDTOTP13 numeric(15,6))
as
declare variable WSQL varchar(32700);
declare variable WVLR13 numeric(18,6);
declare variable WTOTP13 numeric(18,6);
declare variable WFGTS13 numeric(18,6);
BEGIN
  wsql = 'select p13.bdcodemp, '||
                'p13.bdcodcol, '||
                'p13.bdrefp13, '||
                'p13.bdlinhap13, '||
                'p13.bdpropp13, '||
                'p13.bdadicionaisp13, '||
                'p13.bdmediasp13, '||
                'p13.bdsalbasep13, '||
                'p13.bdplanocc, '||
                'p13.bdordemccp13, '||
                'p13.bdvlr13salp13, '||
                'p13.bdfgtsp13, '||
                'p13.bdinssp13, '||
                'p13.bdtercfpasp13, '||
                'p13.bdcnaeratp13, '||
                'p13.bdratapop13, '||
                'p13.bdpisp13, '||
                'p13.bdtotp13 '||
         'from (select p13.bdcodemp, p13.bdcodcol, max(p13.bdrefp13) bdrefp13 '||
               'from VRHF_EMP_TPROVISAO13 p13 '||
               'where p13.BDREFP13 ';

  if (coalesce(prmesatual, 0) = 1) then
     wsql = wsql||' <= ';
  else
     wsql = wsql||' < ';

  wsql = wsql||pranomes;

  IF (coalesce(prcodemp, '') <> '') THEN
       wsql = wsql||' and '||prcodemp||' ';

  IF (coalesce(prcodcol, '') <> '') THEN
     wsql = wsql||' and '||prcodcol||' ';

  wsql = wsql||
               'group by p13.bdcodemp, p13.bdcodcol) P13_2 '||
         'join VRHF_EMP_TPROVISAO13 P13 on (P13.BDCODEMP = P13_2.BDCODEMP and P13.BDCODCOL = P13_2.BDCODCOL and P13.BDREFP13 = P13_2.BDREFP13) ';

  IF (prtipoprov IS NOT NULL) THEN
     wsql = wsql||' where p13.BDLINHAP13 = '||prtipoprov;

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :bdcodcol,
    :bdrefp13,
    :bdlinhap13,
    :bdpropp13,
    :bdadicionaisp13,
    :bdmediasp13,
    :bdsalbasep13,
    :bdplanocc,
    :bdordemccp13,
    :bdvlr13salp13,
    :bdfgtsp13,
    :bdinssp13,
    :bdtercfpasp13,
    :bdcnaeratp13,
    :bdratapop13,
    :bdpisp13,
    :bdtotp13
  DO
    begin
      if (coalesce(prdescad13, 0) = 1) then
         begin
           select SUM(COALESCE(A.BDVLR13SALP13, 0)), SUM(COALESCE(A.BDTOTP13, 0)), SUM(COALESCE(A.BDFGTSP13, 0))
           from VRHF_EMP_TPROVISAO13 A
           where A.BDLINHAP13 = 2 and
                 A.BDREFP13 = :BDREFP13 and
                 A.BDCODEMP = :BDCODEMP and A.BDCODCOL = :BDCODCOL and
                 not exists(select B.BDCODEMP, B.BDCODCOL, B.BDREFP13
                            from VRHF_EMP_TPROVISAO13 B
                            where B.BDLINHAP13 in (3, 4) and
                                  B.BDREFP13 = :BDREFP13 and
                                  A.BDCODEMP = B.BDCODEMP and
                                  A.BDCODCOL = B.BDCODCOL)
           into :wvlr13, :wtotp13, :wfgts13;

           wvlr13  = COALESCE(wvlr13, 0);
           wtotp13 = COALESCE(wtotp13, 0);
           wfgts13 = COALESCE(wfgts13, 0);

           BDVLR13SALP13 = COALESCE(BDVLR13SALP13, 0) + wvlr13;
           BDTOTP13      = COALESCE(BDTOTP13, 0) + wtotp13 - wfgts13;
         end

       SUSPEND;
    end
END^

/* Restore proc. body: SP_VRHF_EMP_TPROVISAOFERIAS */
create or alter procedure SP_VRHF_EMP_TPROVISAOFERIAS (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32700),
    PRANOMES integer,
    PRTIPOPROV integer,
    PRMESATUAL smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDLINHAPFER integer,
    BDINIPERAQUISPFER date,
    BDORDEMCCPFER integer,
    BDPLANOCC integer,
    BDREFPFER integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDSALBASEPFER numeric(15,6),
    BDADICIONAISPFER numeric(15,6),
    BDMEDIASPFER numeric(15,6),
    BDOUTRASBASESPFER numeric(15,6),
    BDFERIASPFER numeric(15,6),
    BDUMTERCOPFER numeric(15,6),
    BDFGTSPFER numeric(15,6),
    BDINSSPFER numeric(15,6),
    BDTERCFPASPFER numeric(15,6),
    BDCNAERATPFER numeric(15,6),
    BDRATAPOPFER numeric(15,6),
    BDPISPFER numeric(15,6),
    BDTOTPFER numeric(15,6),
    BDPROPPFER numeric(15,6),
    BDBASEFGTSPFER numeric(15,6),
    BDBASEINSSPFER numeric(15,6),
    BDBASEPISPFER numeric(15,6),
    BDRESCISAOPFER varchar(5),
    BDPORTOMADORPFER varchar(5),
    BDFALTASPFER numeric(15,6),
    BDDATAVENCPFER date,
    BDMVPFER numeric(15,6),
    BDPRPFER numeric(15,6),
    BDSDPFER numeric(15,6))
as
declare variable WSQL varchar(32700);
BEGIN
  wsql = 'select PFER.BDCODEMP, '||
                'PFER.BDCODCOL, '||
                'PFER.BDLINHAPFER, '||
                'PFER.BDINIPERAQUISPFER, '||
                'PFER.BDORDEMCCPFER, '||
                'PFER.BDPLANOCC, '||
                'PFER.BDREFPFER, '||
                'PFER.BDCODCENTRO, '||
                'PFER.BDCODTPCC, '||
                'PFER.BDSALBASEPFER, '||
                'PFER.BDADICIONAISPFER, '||
                'PFER.BDMEDIASPFER, '||
                'PFER.BDOUTRASBASESPFER, '||
                'PFER.BDFERIASPFER, '||
                'PFER.BDUMTERCOPFER, '||
                'PFER.BDFGTSPFER, '||
                'PFER.BDINSSPFER, '||
                'PFER.BDTERCFPASPFER, '||
                'PFER.BDCNAERATPFER, '||
                'PFER.BDRATAPOPFER, '||
                'PFER.BDPISPFER, '||
                'PFER.BDTOTPFER, '||
                'PFER.BDPROPPFER, '||
                'PFER.BDBASEFGTSPFER, '||
                'PFER.BDBASEINSSPFER, '||
                'PFER.BDBASEPISPFER, '||
                'PFER.BDRESCISAOPFER, '||
                'PFER.BDPORTOMADORPFER, '||
                'PFER.BDFALTASPFER, '||
                'PFER.BDDATAVENCPFER, '||
                'PFER.BDMVPFER, '||
                'PFER.BDPRPFER, '||
                'PFER.BDSDPFER '||
         'from (select PFER.BDCODEMP, PFER.BDCODCOL, MAX(PFER.BDREFPFER) BDREFPFER from VRHF_EMP_TPROVISAOFERIAS PFER where PFER.BDREFPFER ';

  if (coalesce(prmesatual, 0) = 1) then
     wsql = wsql||' <= ';
  else
     wsql = wsql||' < ';

  wsql = wsql||pranomes;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||' and '||prcodemp||' ';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||' and '||prcodcol||' ';

  IF (prtipoprov IS NOT NULL) THEN
     wsql = wsql||' and PFER.BDLINHAPFER = '||prtipoprov;

  wsql = wsql||' group by PFER.BDCODEMP, PFER.BDCODCOL) PFERUNICO '||
         'join vrhf_emp_tprovisaoferias PFER on (PFER.BDCODEMP = PFERUNICO.BDCODEMP and PFER.BDCODCOL = PFERUNICO.BDCODCOL and PFER.BDREFPFER = PFERUNICO.BDREFPFER) ';

  IF (prtipoprov IS NOT NULL) THEN
     wsql = wsql||' where PFER.BDLINHAPFER = '||prtipoprov;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP, 
    :BDCODCOL, 
    :BDLINHAPFER, 
    :BDINIPERAQUISPFER, 
    :BDORDEMCCPFER, 
    :BDPLANOCC, 
    :BDREFPFER, 
    :BDCODCENTRO, 
    :BDCODTPCC, 
    :BDSALBASEPFER, 
    :BDADICIONAISPFER, 
    :BDMEDIASPFER, 
    :BDOUTRASBASESPFER, 
    :BDFERIASPFER, 
    :BDUMTERCOPFER, 
    :BDFGTSPFER, 
    :BDINSSPFER, 
    :BDTERCFPASPFER, 
    :BDCNAERATPFER, 
    :BDRATAPOPFER, 
    :BDPISPFER, 
    :BDTOTPFER, 
    :BDPROPPFER, 
    :BDBASEFGTSPFER, 
    :BDBASEINSSPFER, 
    :BDBASEPISPFER, 
    :BDRESCISAOPFER, 
    :BDPORTOMADORPFER, 
    :BDFALTASPFER, 
    :BDDATAVENCPFER, 
    :BDMVPFER, 
    :BDPRPFER, 
    :BDSDPFER 
  DO
  SUSPEND;

END^

/* Restore proc. body: SP_VRHF_FC_VALORES_INDENIZADOS */
CREATE OR ALTER PROCEDURE SP_VRHF_FC_VALORES_INDENIZADOS (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRANOMES INTEGER,
    PRDATAGRRF DATE)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREFFN INTEGER,
    BDDATAGRRFFC DATE,
    BDVALOR NUMERIC(15,6))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  /* tem que executar a procedure que seta a competência */

  wsql = 'select COLCON.BDCODEMP, '||
                'COLCON.BDCODCOL, '||
                'COLCON.BDREFFN, '||
                'COLCON.BDDATAGRRFFC, '||
                'Sum(COLCON.BDVALVFC) BDVALOR '||
         'from (select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFFN, FOLC.BDDATAGRRFFC, COLCON.BDVALVFC '||
               'from VRHF_EMP_TVERBAFC COLCON '||
               'join VRHF_EMP_TFOLHACOMP FOLC on (FOLC.BDCODEMP = COLCON.BDCODEMP and FOLC.BDCODCOL = COLCON.BDCODCOL and FOLC.BDREFFN = COLCON.BDREFFN and FOLC.BDREFFC = COLCON.BDREFFC) '||
               'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = COLCON.BDCODVER) '||
               'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = COLCON.BDCODVER) '||
               'where COLCON.BDREFFN = '||pranomes;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wsql = wsql||' and '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     END

  wsql = wsql||' and (VER.BDCLAVER like ''7.001.3%'' or VER.BDCLAVER like ''7.020%'' or VER.BDCLAVER like ''7.021%'' or VER.BDCLAVER like ''7.060%'') '||
                 'and VERF.BDFGTSVER > 0 '||
                 'and FOLC.BDDATAGRRFFC = '''||prdatagrrf||''' ';

  wsql = wsql||' union all '||
               'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, FOLC.BDDATAGRRFFC, COLCON.BDVALVFC '||
               'from VRHF_EMP_TVERBAFCTOMADOR COLCON '||
               'join VRHF_EMP_TFOLTOMCOMP FOLC on (FOLC.BDCODEMP = COLCON.BDCODEMP and FOLC.BDCODCOL = COLCON.BDCODCOL and FOLC.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLC.BDREFFC = COLCON.BDREFFC and FOLC.BDORDEM = COLCON.BDORDEM) '||
               'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = COLCON.BDCODVER) '||
               'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = COLCON.BDCODVER) '||
               'where COLCON.BDREFTOMADOR = '||pranomes;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wsql = wsql||' and '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     END

  wsql = wsql||' and (VER.BDCLAVER like ''7.001.3%'' or VER.BDCLAVER like ''7.020%'' or VER.BDCLAVER like ''7.021%'' or VER.BDCLAVER like ''7.060%'') '||
                 'and VERF.BDFGTSVER > 0 '||
                 'and FOLC.BDDATAGRRFFC = '''||prdatagrrf||''' ';

  wsql = wsql||') COLCON group by COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFFN, COLCON.BDDATAGRRFFC ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFFN,
    :BDDATAGRRFFC,
    :BDVALOR
  DO
  SUSPEND;
END
^

/* Restore proc. body: SP_VRHF_FN_VALORES_INDENIZADOS */
create or alter procedure SP_VRHF_FN_VALORES_INDENIZADOS (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32700),
    PRANOMES integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDVALOR numeric(18,6),
    BDVALOR13 numeric(18,6))
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(20000);
declare variable WCODEMP varchar(20000);
declare variable WCODCOL varchar(32700);
BEGIN
  /* tem que executar a procedure que seta a competência */

  IF (prcodemp IS NULL OR (prcodemp = '')) THEN
     wcodemp = 'null';
  ELSE
     wcodemp = ''''||prcodemp||'''';

  IF (prcodcol IS NULL OR (prcodcol = '')) THEN
     wcodcol = 'null';
  ELSE
     wcodcol = ''''||prcodcol||'''';


  wsql = 'select COLCON.BDCODEMP, '||
                'COLCON.BDCODCOL, '||
                'COLCON.BDREFFN, '||
                'Sum(COLCON.BDVALVFN) BDVALOR, '||
                'Sum(COLCON.BDVALV13) BDVALOR13 '||
         'from ('||
           'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFFN, '||
              'case when VER.BDCLAVER starting with ''7.060'' then 0 else COLCON.BDVALVFN end BDVALVFN, '||
              'case when VER.BDCLAVER starting with ''7.060'' then COLCON.BDVALVFN else 0 end BDVALV13 '||
           'from vrhf_sp_tverbafn('||wcodemp||','||wcodcol||','||pranomes||','||pranomes||',1) COLCON '||
           'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = COLCON.BDCODVER) '||
           'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = COLCON.BDCODVER) ';

  wwhere = 'where '||
                 '((VER.BDCLAVER like ''7.001.3%'') or (VER.BDCLAVER like ''7.020%'') or (VER.BDCLAVER like ''7.021%'') or (VER.BDCLAVER like ''7.060%'')) '||
                 'and VERF.BDFGTSVER > 0 ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||'and '||prcodemp||' ';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||'and '||prcodcol||' ';

  IF (pranomes IS NOT NULL AND pranomes <> 0) THEN
     wwhere = wwhere||'and COLCON.BDREFFN = '||pranomes||' ';

  wsql = wsql||wwhere||') COLCON group by COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFFN ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFFN,
    :BDVALOR,
    :BDVALOR13
  DO
  SUSPEND;
END^

/* Restore proc. body: SP_VRHF_FOLHACOMPLEMENTAR */
ALTER PROCEDURE SP_VRHF_FOLHACOMPLEMENTAR RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPO INTEGER,
BDBFGTSFEFC NUMERIC(15,6),
BDFGTSFEFC NUMERIC(15,6),
BDDATAPAGFC date)
 AS
DECLARE VARIABLE WSQL VARCHAR(3000);
BEGIN
  /* Procedure Text */
  wsql = 'select '||
         ' VFOLC.BDCODEMP,'||
         ' VFOLC.BDCODCOL,'||
         ' VFOLC.BDREFCOMP,'||
         ' VFOLC.BDCODVER,'||
         ' VFOLC.BDREFVFC,'||
         ' VFOLC.BDREFAUXVFC,'||
         ' VFOLC.BDVALVFC,'||
         ' DFOLC.BDBFGTSFC,'||
         ' DFOLC.BDFGTSFC,'||
         ' DFOLC.BDFGTSCSFC,'||
         ' DFOLC.BDBFGTS13FC,'||
         ' DFOLC.BDFGTS13FC,'||
         ' DFOLC.BDFGTS13CSFC,'||
         ' DFOLC.BDMAIORREMFC,'||
         ' DFOLC.BDBINSSFC,'||
         ' DFOLC.BDALIQINSSFC,'||
         ' DFOLC.BDINSSFC,'||
         ' DFOLC.BDBIRRFFC,'||
         ' DFOLC.BDALIQIRRFFC,'||
         ' DFOLC.BDIRRFFC,'||
         ' DFOLC.BDBINSS13FC,'||
         ' DFOLC.BDALIQINSS13FC,'||
         ' DFOLC.BDINSS13FC,'||
         ' DFOLC.BDBIRRF13FC,'||
         ' DFOLC.BDALIQIRRF13FC,'||
         ' DFOLC.BDIRRF13FC,'||
         ' DFOLC.BDBSALFAMFC,'||
         ' DFOLC.BDSALFAMFC,'||
         ' DFOLC.BDBRAISFC,'||
         ' DFOLC.BDSALBASEFC,'||
         ' DFOLC.BDDEPFC,'||
         ' VFOLC.BDIGNREFVFC,'||
         ' VFOLC.BDIGNREFAVFC,'||
         ' VFOLC.BDIGNVALVFC,'||
         ' 1 BDTIPO, '||
         ' DFOLC.bdbfgtsfefc,'||
         ' DFOLC.bdfgtsfefc, '||
         ' DFOLC.BDDATAPAGFC '||
         ' from vrhf_sp_tverbafc(null,null,null,null,null,null,1) VFOLC, '||
         '  vrhf_sp_tfolhacomp(null,null,null,null,null,null,1) DFOLC'||
         '   where (DFOLC.BDCODEMP = VFOLC.BDCODEMP and DFOLC.BDCODCOL = VFOLC.BDCODCOL and DFOLC.BDREFFC = VFOLC.BDREFFC)';

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDCODVER,
    :BDREFV,
    :BDREFAUXV,
    :BDVALV,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDIGNREFV,
    :BDIGNREFAV,
    :BDIGNVALV,
    :BDTIPO,
    :bdbfgtsfefc,
    :bdfgtsfefc,
    :BDDATAPAGFC
  DO
    SUSPEND;
END
^

/* Restore proc. body: SP_VRHF_FOLHANORMAL */
ALTER PROCEDURE SP_VRHF_FOLHANORMAL RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPO INTEGER,
BDBFGTSFEFN NUMERIC(15,6),
BDFGTSFEFN NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(3000);
BEGIN
  /* Procedure Text */

wsql = ' select'||
       '  VFOL.BDCODEMP,'||
       '  VFOL.BDCODCOL,'||
       '  VFOL.BDREFFN,'||
       '  VFOL.BDCODVER,'||
       '  VFOL.BDREFVFN,'||
       '  VFOL.BDREFAUXVFN,'||
       '  VFOL.BDVALVFN,'||
       '  DFOL.BDBFGTSFN,'||
       '  DFOL.BDFGTSFN,'||
       '  DFOL.BDFGTSCSFN,'||
       '  DFOL.BDBFGTS13FN,'||
       '  DFOL.BDFGTS13FN,'||
       '  DFOL.BDFGTS13CSFN,'||
       '  DFOL.BDMAIORREMFN,'||
       '  DFOL.BDBINSSFN,'||
       '  DFOL.BDALIQINSSFN,'||
       '  DFOL.BDINSSFN,'||
       '  DFOL.BDBIRRFFN,'||
       '  DFOL.BDALIQIRRFFN,'||
       '  DFOL.BDIRRFFN,'||
       '  DFOL.BDBINSS13FN,'||
       '  DFOL.BDALIQINSS13FN,'||
       '  DFOL.BDINSS13FN,'||
       '  DFOL.BDBIRRF13FN,'||
       '  DFOL.BDALIQIRRF13FN,'||
       '  DFOL.BDIRRF13FN,'||
       '  DFOL.BDBSALFAMFN,'||
       '  DFOL.BDSALFAMFN,'||
       '  DFOL.BDBRAISFN,'||
       '  DFOL.BDSALBASEFN,'||
       '  DFOL.BDDEPFN,'||
       '  VFOL.BDIGNREFVFN,'||
       '  VFOL.BDIGNREFAVFN,'||
       '  VFOL.BDIGNVALVFN,'||
       '  0 BDTIPO,'||
       '  DFOL.BDBFGTSFEFN,'||
       '  DFOL.BDFGTSFEFN'||
       '  from vrhf_sp_tverbafn(null,null,null,null,1) VFOL, '||
       '       vrhf_sp_tfolha_normal(null,null,null,null,1) DFOL'||
       '  where (DFOL.BDCODEMP = VFOL.BDCODEMP and DFOL.BDCODCOL = VFOL.BDCODCOL and DFOL.BDREFFN = VFOL.BDREFFN)';

   FOR EXECUTE STATEMENT wsql INTO
     :BDCODEMP,
     :BDCODCOL,
     :BDREF,
     :BDCODVER,
     :BDREFV,
     :BDREFAUXV,
     :BDVALV,
     :BDBFGTS,
     :BDFGTS,
     :BDFGTSCS,
     :BDBFGTS13,
     :BDFGTS13,
     :BDFGTS13CS,
     :BDMAIORREM,
     :BDBINSS,
     :BDALIQINSS,
     :BDINSS,
     :BDBIRRF,
     :BDALIQIRRF,
     :BDIRRF,
     :BDBINSS13,
     :BDALIQINSS13,
     :BDINSS13,
     :BDBIRRF13,
     :BDALIQIRRF13,
     :BDIRRF13,
     :BDBSALFAM,
     :BDSALFAM,
     :BDBRAIS,
     :BDSALBASE,
     :BDDEP,
     :BDIGNREFV,
     :BDIGNREFAV,
     :BDIGNVALV,
     :BDTIPO,
     :BDBFGTSFEFN,
     :BDFGTSFEFN
   DO
   SUSPEND;
END
^

/* Restore proc. body: SP_VRHF_TCOL_VINC_REF */
ALTER PROCEDURE SP_VRHF_TCOL_VINC_REF(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFCOL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFCOL INTEGER,
BDCODSINTRAB INTEGER)
 AS
DECLARE VARIABLE wsql VARCHAR(15000);
BEGIN
  if ((PRCODEMP is null) or (PRCODCOL is null) or (PRREFCOL is null))  then
     suspend;
  else
    begin
      EXECUTE PROCEDURE sp_seta_competencia(prREFCOL, NULL, NULL);
      wsql = 'select BDCODEMP, BDCODCOL, BDREFCOL, BDCODSINTRAB '||
             'from vw_vrh_emp_tcol_vinc '||
             'where BDCODEMP = '||prCODEMP||' and BDCODCOL = '||prCODCOL;
      FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :BDCODCOL,
        :BDREFCOL,
        :BDCODSINTRAB
      DO
      SUSPEND;
    end
END
^

/* Restore proc. body: SP_VRHF_VERBAS_AGRUPADAS_FN */
ALTER PROCEDURE SP_VRHF_VERBAS_AGRUPADAS_FN(PRCODEMP VARCHAR(32700),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRAGRUPACC INTEGER)
 RETURNS(BDCODVER INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDREFVFN NUMERIC(18,6),
BDREFAUXVFN NUMERIC(18,6),
BDVALVFN NUMERIC(18,6),
BDIGNREFVFN DM_BOOLEAN,
BDIGNVALVFN DM_BOOLEAN,
BDORVERBAFN INTEGER,
BDVALVIFN NUMERIC(18,6),
BDIGNREFAVFN DM_BOOLEAN,
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODVER INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODEMPA INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WCODCOLA INTEGER;
DECLARE VARIABLE WREFFN INTEGER;
DECLARE VARIABLE WREFFNA INTEGER;
DECLARE VARIABLE WREFVFN NUMERIC(18,6);
DECLARE VARIABLE WREFAUXVFN NUMERIC(18,6);
DECLARE VARIABLE WVALVFN NUMERIC(18,6);
DECLARE VARIABLE WIGNREFVFN DM_BOOLEAN;
DECLARE VARIABLE WIGNVALVFN DM_BOOLEAN;
DECLARE VARIABLE WORVERBAFN INTEGER;
DECLARE VARIABLE WVALVIFN NUMERIC(18,6);
DECLARE VARIABLE WIGNREFAVFN DM_BOOLEAN;
DECLARE VARIABLE WCLAVER VARCHAR(20);
DECLARE VARIABLE WCLAVERA VARCHAR(20);
DECLARE VARIABLE WNIVELAGRUPEMP INTEGER;
DECLARE VARIABLE WNIVEL INTEGER;
DECLARE VARIABLE WSQL2 VARCHAR(1000);
BEGIN


  wsql = 'select '||
            'FN.BDCODVER, '||
            'FN.BDCODEMP, '||
            'FN.BDCODCOL, '||
            'FN.BDREFFN, '||
            'FN.BDREFVFN, '||
            'FN.BDREFAUXVFN, '||
            'FN.BDVALVFN, '||
            'FN.BDIGNREFVFN, '||
            'FN.BDIGNVALVFN, '||
            'FN.BDORVERBAFN, '||
            'FN.BDVALVIFN, '||
            'FN.BDIGNREFAVFN, '||
            'VERB.BDCLAVER, '||
            'EMPR.BDNIVELAGRUPEMP, '||
            'FN.BDCOMPESP, '||
            'FN.BDFORMREFAUX, '||
            'FN.BDFORMREF, '||
            'FN.BDFORMVAL ';

  wsql = wsql||'from ('||
         'select * from VRHF_EMP_TVERBAFN';

       wsql = wsql||' where BDREFFN = '||pranomes;
       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
          BEGIN
            wsql = wsql||' and '||prcodemp;
     
            IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
               wsql = wsql||' and '||prcodcol;
          END

  wsql = wsql||') FN ';
  wsql = wsql||' join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = FN.BDCODVER) ';
  wsql = wsql||' left outer join VW_VRHF_BASE_TEMPPAR EMPR on (EMPR.BDCODEMP = FN.BDCODEMP) ';

  wsql = wsql||' order by FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN,VERB.BDCLAVER';

  wcodempa    = 0;
  wcodcola    = 0;
  wreffna     = 0;
  wclavera    = NULL;
  bdrefvfn     = 0;
  bdrefauxvfn  = 0;
  bdvalvfn     = 0;
  bdignrefvfn  = 'FALSE';
  bdignvalvfn  = 'FALSE';
  bdorverbafn  = 0;
  bdvalvifn    = 0;
  bdignrefavfn = 'FALSE';

  FOR EXECUTE STATEMENT wsql INTO :wcodver, :wcodemp, :wcodcol, :wreffn, :wrefvfn, :wrefauxvfn, :wvalvfn, :wignrefvfn, :wignvalvfn, :worverbafn, :wvalvifn, :wignrefavfn, :wclaver, :wnivelagrupemp, :BDCOMPESP, :BDFORMREFAUX, :BDFORMREF, :BDFORMVAL DO
    BEGIN
      IF (wcodempa = 0) THEN
         wcodempa = wcodemp;

      IF (wcodcola = 0) THEN
         wcodcola = wcodcol;

      IF (wreffna = 0) THEN
         wreffna = wreffn;

      IF (wnivelagrupemp = 1) THEN
         BEGIN
           wnivel = 7;
           IF (wclavera IS NULL) THEN
              wclavera = SUBSTRING(wclaver FROM 1 FOR :wnivel);
         END
      ELSE
      IF (wnivelagrupemp = 2) THEN
         BEGIN
           wnivel = 5;
           IF (wclavera IS NULL) THEN
              wclavera = SUBSTRING(wclaver FROM 1 FOR :wnivel);
         END
      ELSE
         BEGIN
           wnivel = 20;
           IF (wclavera IS NULL) THEN
              wclavera = wclaver;
         END

      IF ((wcodemp <> wcodempa) OR (wcodcol <> wcodcola) OR (wreffn <> wreffna) OR (SUBSTRING(wclaver FROM 1 FOR :wnivel) <> wclavera)) THEN
         BEGIN
           wsql2 = 'select first 1 BDCODVER from VRH_BASE_TVERBAS where BDCLAVER starting with '''||wclavera||'.9'||''' and strlen(BDCLAVER) > 9 order by BDCLAVER DESC';
           EXECUTE STATEMENT wsql2 INTO :wcodver;

           bdcodver = wcodver;
           bdcodemp = wcodempa;
           bdcodcol = wcodcola;
           bdreffn  = wreffna;

           SUSPEND;
           bdrefvfn     = 0;
           bdrefauxvfn  = 0;
           bdvalvfn     = 0;
           bdignrefvfn  = 'FALSE';
           bdignvalvfn  = 'FALSE';
           bdorverbafn  = 0;
           bdvalvifn    = 0;
           bdignrefavfn = 'FALSE';

           wcodempa = wcodemp;
           wcodcola = wcodcol;
           wreffna  = wreffn;
           wclavera = SUBSTRING(wclaver FROM 1 FOR : wnivel);
         END

      bdrefvfn     = bdrefvfn + wrefvfn;
      bdrefauxvfn  = bdrefauxvfn + wrefauxvfn;
      bdvalvfn     = bdvalvfn + wvalvfn;

      IF (bdignrefvfn = 'FALSE') THEN
         bdignrefvfn  = wignrefvfn;

      IF (bdignvalvfn = 'FALSE') THEN
         bdignvalvfn  = wignvalvfn;

      bdorverbafn  = worverbafn;
      bdvalvifn    = bdvalvifn + wvalvifn;

      IF (bdignrefavfn = 'FALSE') THEN
         bdignrefavfn = wignrefavfn;
    END

  IF ((wcodemp <> wcodempa) OR (wcodcol <> wcodcola) OR (wreffn <> wreffna) OR (SUBSTRING(wclaver FROM 1 FOR :wnivel) <> wclavera)) THEN
     BEGIN
       wsql2 = 'select first 1 BDCODVER from VRH_BASE_TVERBAS where BDCLAVER starting with '''||wclavera||'.9'||''' and strlen(BDCLAVER) > 9 order by BDCLAVER DESC';
       EXECUTE STATEMENT wsql2 INTO :wcodver;

       bdcodver = wcodver;
       bdcodemp = wcodempa;
       bdcodcol = wcodcola;
       bdreffn  = wreffna;

       SUSPEND;
     END
END
^

/* Restore proc. body: SP_VRHF_VERBAS_FN_FC */
ALTER PROCEDURE SP_VRHF_VERBAS_FN_FC RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDCODVER INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDIGNREFAV VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPO INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(3000);
BEGIN
  /* Procedure Text */

 wsql = ' select'||
        '    BDCODEMP,'||
        '    BDCODCOL,'||
        '    BDREF,'||
        '    BDCODVER,'||
        '    BDREFV,'||
        '    BDREFAUXV,'||
        '    BDVALV,'||
        '    BDBFGTS,'||
        '    BDFGTS,'||
        '    BDFGTSCS,'||
        '    BDBFGTS13,'||
        '    BDFGTS13,'||
        '    BDFGTS13CS,'||
        '    BDMAIORREM,'||
        '    BDBINSS,'||
        '    BDALIQINSS,'||
        '    BDINSS,'||
        '    BDBIRRF,'||
        '    BDALIQIRRF,'||
        '    BDIRRF,'||
        '    BDBINSS13,'||
        '    BDALIQINSS13,'||
        '    BDINSS13,'||
        '    BDBIRRF13,'||
        '    BDALIQIRRF13,'||
        '    BDIRRF13,'||
        '    BDBSALFAM,'||
        '    BDSALFAM,'||
        '    BDBRAIS,'||
        '    BDSALBASE,'||
        '    BDDEP,'||
        '    BDIGNREFAV,'||
        '    BDIGNREFV,'||
        '    BDIGNVALV,'||
        '    BDTIPO'||
        ' from SP_VRHF_FOLHANORMAL';

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDCODVER,
    :BDREFV,
    :BDREFAUXV,
    :BDVALV,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDIGNREFAV,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDTIPO
  DO
  SUSPEND;

 wsql = ' select'||
        '    BDCODEMP,'||
        '    BDCODCOL,'||
        '    BDREF,'||
        '    BDCODVER,'||
        '    BDREFV,'||
        '    BDREFAUXV,'||
        '    BDVALV,'||
        '    BDBFGTS,'||
        '    BDFGTS,'||
        '    BDFGTSCS,'||
        '    BDBFGTS13,'||
        '    BDFGTS13,'||
        '    BDFGTS13CS,'||
        '    BDMAIORREM,'||
        '    BDBINSS,'||
        '    BDALIQINSS,'||
        '    BDINSS,'||
        '    BDBIRRF,'||
        '    BDALIQIRRF,'||
        '    BDIRRF,'||
        '    BDBINSS13,'||
        '    BDALIQINSS13,'||
        '    BDINSS13,'||
        '    BDBIRRF13,'||
        '    BDALIQIRRF13,'||
        '    BDIRRF13,'||
        '    BDBSALFAM,'||
        '    BDSALFAM,'||
        '    BDBRAIS,'||
        '    BDSALBASE,'||
        '    BDDEP,'||
        '    BDIGNREFAV,'||
        '    BDIGNREFV,'||
        '    BDIGNVALV,'||
        '    BDTIPO'||
        ' from SP_VRHF_FOLHACOMPLEMENTAR';

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDCODVER,
    :BDREFV,
    :BDREFAUXV,
    :BDVALV,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDIGNREFAV,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDTIPO
  DO
  SUSPEND;

  wsql = 'select '||
/*01*/        ' BDCODEMP,'||
/*02*/        '     BDCODCOL,'||
/*03*/        '     BDREF,'||
/*04*/        '     BDCODVER,'||
/*05*/        '     BDREFV,'||
/*06*/        '     BDVALV'||
        '     from VW_VRHF_FICHAHE';

  BDREFAUXV = 0;
  BDBFGTS = 0;
  BDFGTS = 0;
  BDFGTSCS = 0;
  BDBFGTS13 = 0;
  BDFGTS13 = 0;
  BDFGTS13CS = 0;
  BDMAIORREM = 0;
  BDBINSS = 0;
  BDALIQINSS = 0;
  BDINSS = 0;
  BDBIRRF = 0;
  BDALIQIRRF = 0;
  BDIRRF = 0;
  BDBINSS13 = 0;
  BDALIQINSS13 = 0;
  BDINSS13 = 0;
  BDBIRRF13 = 0;
  BDALIQIRRF13 = 0;
  BDIRRF13 = 0;
  BDBSALFAM = 0;
  BDSALFAM = 0;
  BDBRAIS = 0;
  BDSALBASE = 0;
  BDDEP = 0;
  BDIGNREFV = 'FALSE';
  BDIGNVALV = 'FALSE';
  BDTIPO = 1;
  FOR EXECUTE STATEMENT wsql INTO
/*01*/    :BDCODEMP,
/*02*/    :BDCODCOL,
/*03*/    :BDREF,
/*04*/    :BDCODVER,
/*05*/    :BDREFV,
/*06*/    :BDVALV
  DO
  SUSPEND;

  wsql = 'select '||
/*01*/        ' BDCODEMP,'||
/*02*/        '     BDCODCOL,'||
/*03*/        '     BDREF,'||
/*04*/        '     BDCODVER,'||
/*05*/        '     BDREFV,'||
/*06*/        '     BDVALV'||
        '     from VW_VRHF_FICHARV';

  FOR EXECUTE STATEMENT wsql INTO
/*01*/    :BDCODEMP,
/*02*/    :BDCODCOL,
/*03*/    :BDREF,
/*04*/    :BDCODVER,
/*05*/    :BDREFV,
/*06*/    :BDVALV
  DO
  SUSPEND;


  wsql = 'select '||
/*01*/        ' BDCODEMP,'||
/*02*/        '     BDCODCOL,'||
/*03*/        '     BDREF,'||
/*04*/        '     BDCODVER,'||
/*05*/        '     BDREFV,'||
/*06*/        '     BDVALV'||
        '     from VW_VRHF_FICHAHN';

  FOR EXECUTE STATEMENT wsql INTO
/*01*/    :BDCODEMP,
/*02*/    :BDCODCOL,
/*03*/    :BDREF,
/*04*/    :BDCODVER,
/*05*/    :BDREFV,
/*06*/    :BDVALV
  DO
  SUSPEND;

END
^

/* Restore proc. body: SP_VRHF_DADOS_SAUDE */
create or alter procedure SP_VRHF_DADOS_SAUDE (
    PREMP varchar(20000),
    PRCOL varchar(32000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPORCOMPETENCIA smallint = 0,
    PRPORFICHA smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDREF integer,
    BDREFPAG integer)
as
declare variable WSQL varchar(32700);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WPODE integer;
begin
  wsql = 'select FN.BDCODEMP, FN.BDCODCOL';
  
  PREMP = 'FOL.'||substring(PREMP from 5 for 20000); --Sol.148965 esse parametro passa por 3 SP's...
                                                     --somente aqui precisa ser FOL. ao invés de TAB.
  
  if (coalesce(prporcompetencia, 0) = 1) then
     wsql = wsql||', FN.BDREFFN, FN.BDREFPAG ';
  else
     wsql = wsql||', 0 BDREFFN, 0 BDREFPAG ';

  wsql = wsql||
         'from ( ';

  if (coalesce(prporficha, 0) in (0,1)) then
     begin
       wsql = wsql||
                'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, CAST((substring(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) from 1 for 4)||substring(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) from 6 for 2)) AS INTEGER) BDREFPAG '||
                'from VRHF_EMP_TVERBAFN FOL '||
                'join VRHF_EMP_TFOLHANORMAL FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREFFN = FOL.BDREFFN) '||
                'join VRH_BASE_TVERBAS V on (V.BDCODVER = FOL.BDCODVER) '||
                'where ((V.BDCLAVER starting with ''0.030.1.0'') or (V.BDCLAVER starting with ''0.420.0.2'')) and '||
                      'substring(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) from 1 for 4)||substring(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) from 6 for 2) between '||prrefini||' and '||prreffim;
     
       if (coalesce(premp, '') <> '') then
          begin
            wsql = wsql||' and '||premp;
     
            if (coalesce(prcol, '') <> '') then
               wsql = wsql||' and '||prcol;
          end
     
       wsql = wsql||
                ' union all '||
                'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, CAST((substring(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) from 1 for 4)||substring(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) from 6 for 2)) AS INTEGER) BDREFPAG '||
                'from VRHF_EMP_TVERBAINT FOL '||
                'join VRHF_EMP_TFOLHAINT FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREFFN = FOL.BDREFFN and FN.BDCODCONTTI = FOL.BDCODCONTTI) '||
                'join VRH_BASE_TVERBAS V on (V.BDCODVER = FOL.BDCODVER) '|| 
                'where ((V.BDCLAVER starting with ''0.030.1.0'') or (V.BDCLAVER starting with ''0.420.0.2'')) and '||
                       'substring(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) from 1 for 4)||substring(CAST(FN.BDDATAPGTOFN AS VARCHAR(10)) from 6 for 2) between '||prrefini||' and '||prreffim;
     
       if (coalesce(premp, '') <> '') then
          begin
            wsql = wsql||' and '||premp;
     
            if (coalesce(prcol, '') <> '') then
               wsql = wsql||' and '||prcol;
          end
     
       wsql = wsql||
                ' union all '||
                'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, CAST((substring(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) from 1 for 4)||substring(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) from 6 for 2)) AS INTEGER) BDREFPAG '||
                'from VRHF_EMP_TVERBATOMADOR FOL '||
                'join VRHF_EMP_TFOLHATOMADOR FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREFTOMADOR = FOL.BDREFTOMADOR and FN.BDORDEM = FOL.BDORDEM) '||
                'join VRH_BASE_TVERBAS V on (V.BDCODVER = FOL.BDCODVER) '|| 
                'where ((V.BDCLAVER starting with ''0.030.1.0'') or (V.BDCLAVER starting with ''0.420.0.2'')) and '||
                       'substring(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) from 1 for 4)||substring(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) from 6 for 2) between '||prrefini||' and '||prreffim;
     
       if (coalesce(premp, '') <> '') then
          begin
            wsql = wsql||' and '||premp;
     
            if (coalesce(prcol, '') <> '') then
               wsql = wsql||' and '||prcol;
          end
     
       wsql = wsql||
                ' union all '||
                'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, CAST((substring(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) from 1 for 4)||substring(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) from 6 for 2)) AS INTEGER) BDREFPAG '||
                'from VRHF_EMP_TVERBATOMINT FOL '||
                'join VRHF_EMP_TFOLHATOMINT FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREFTOMADOR = FOL.BDREFTOMADOR and FN.BDORDEM = FOL.BDORDEM and FN.BDCODCONTTI = FOL.BDCODCONTTI) '||
                'join VRH_BASE_TVERBAS V on (V.BDCODVER = FOL.BDCODVER) '|| 
                'where ((V.BDCLAVER starting with ''0.030.1.0'') or (V.BDCLAVER starting with ''0.420.0.2'')) and '||
                       'substring(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) from 1 for 4)||substring(CAST(FN.BDDATAPGTOFT AS VARCHAR(10)) from 6 for 2) between '||prrefini||' and '||prreffim;
     
       if (coalesce(premp, '') <> '') then
          begin
            wsql = wsql||' and '||premp;
     
            if (coalesce(prcol, '') <> '') then
               wsql = wsql||' and '||prcol;
          end
     
       wsql = wsql||
                ' union all '||
                'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, CAST((substring(FN.BDREFFC from 1 for 6)) AS INTEGER) BDREFPAG '||
                'from VRHF_EMP_TVERBAFC FOL '||
                'join VRHF_EMP_TFOLHACOMP FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREFFN = FOL.BDREFFN and FN.BDREFFC = FOL.BDREFFC) '||
                'join VRH_BASE_TVERBAS V on (V.BDCODVER = FOL.BDCODVER) '|| 
                'where ((V.BDCLAVER starting with ''0.030.1.0'') or (V.BDCLAVER starting with ''0.420.0.2'')) and '||
                       'substring(FN.BDREFFC from 1 for 6) between '||prrefini||' and '||prreffim;
     
       if (coalesce(premp, '') <> '') then
          begin
            wsql = wsql||' and '||premp;
     
            if (coalesce(prcol, '') <> '') then
               wsql = wsql||' and '||prcol;
          end
     
       wsql = wsql||
                ' union all '||
                'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, CAST((substring(FN.BDREFFC from 1 for 6)) AS INTEGER) BDREFPAG '||
                'from VRHF_EMP_TVERBAFCTOMADOR FOL '||
                'join VRHF_EMP_TFOLTOMCOMP FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDREFTOMADOR = FOL.BDREFTOMADOR and FN.BDREFFC = FOL.BDREFFC and FN.BDORDEM = FOL.BDORDEM) '||
                'join VRH_BASE_TVERBAS V on (V.BDCODVER = FOL.BDCODVER) '|| 
                'where ((V.BDCLAVER starting with ''0.030.1.0'') or (V.BDCLAVER starting with ''0.420.0.2'')) and '||
                   'substring(FN.BDREFFC from 1 for 6) between '||prrefini||' and '||prreffim;
     
       if (coalesce(premp, '') <> '') then
          begin
            wsql = wsql||' and '||premp;
     
            if (coalesce(prcol, '') <> '') then
               wsql = wsql||' and '||prcol;
          end
     
       wsql = wsql||
                ' union all '||
                'select FOL.BDCODEMP, FOL.BDCODCOL, FN.BDREF, FN.BDREF BDREFPAG '||
                'from VRHF_EMP_TVERBAFA FOL '||
                'join VRHF_EMP_TFOLHAAVULSA FN on (FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and FN.BDCODTCA = FOL.BDCODTCA and FN.BDDATAFA = FOL.BDDATAFA) '||
                'join VRH_BASE_TVERBAS V on (V.BDCODVER = FOL.BDCODVER) '|| 
                'where ((V.BDCLAVER starting with ''0.030.1.0'') or (V.BDCLAVER starting with ''0.420.0.2'')) and '||
                   'FN.BDREF between '||prrefini||' and '||prreffim;
     
       if (coalesce(premp, '') <> '') then
          begin
            wsql = wsql||' and '||premp;
     
            if (coalesce(prcol, '') <> '') then
               wsql = wsql||' and '||prcol;
          end
     end

  if (coalesce(prporficha, 0) in (0,2)) then
     begin
       if (coalesce(prporficha, 0) = 0) then
          wsql = wsql||' union all ';

       wsql = wsql||
                'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFIR BDREFFN, FOL.BDREFIRFIR BDREFPAG '||
                'from VRHF_EMP_TFICHAIRRF FOL '||
                'where coalesce(FOL.BDDESPMEDFIR, 0) > 0 and FOL.BDREFIRFIR between '||prrefini||' and '||prreffim;
     
       if (coalesce(premp, '') <> '') then
          begin
            wsql = wsql||' and '||premp;
     
            if (coalesce(prcol, '') <> '') then
               wsql = wsql||' and '||prcol;
          end
     end

  wsql = wsql||
         ') FN '|| 
--         'left outer join VW_EMPRESAS_USU TEMP_U on TEMP_U.BDCODEMP = FN.BDCODEMP '||
--         'where TEMP_U.BDCODEMP is not null '||
         'group by FN.BDCODEMP, FN.BDCODCOL ';

  if (coalesce(prporcompetencia, 0) = 1) then
     wsql = wsql||', FN.BDREFFN, FN.BDREFPAG ';

  wsql = wsql||
         'order by FN.BDCODEMP, FN.BDCODCOL';

  wempatu = 0;
  wcolatu = 0;

  wpode = 0;

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG do
    begin
      if ((wempatu <> BDCODEMP) or (wcolatu <> BDCODCOL)) then
         begin
           if (wempatu <> BDCODEMP) then
              select BDCODEMP from VW_EMPRESAS_USU where BDCODEMP = :BDCODEMP into :wpode;

         select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prreffim order by BDREFCOL DESC into :BDNOMCOL;
           wempatu = bdcodemp;
           wcolatu = bdcodcol;
         end

      if (coalesce(wpode, 0) > 0) then
      suspend;
    end
end^


/* Restore proc. body: SP_VRHM_FF_OP_ANO */
create or alter procedure SP_VRHM_FF_OP_ANO (
    PREMP varchar(32000) = '' /* COLLATE WIN1252 - default */ ,
    PRCOL varchar(32000) = '' /* COLLATE WIN1252 - default */ ,
    PRANO integer = 0,
    PROPER integer = 0,
    PRCONV integer = 0,
    PRREFPAG integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDREF integer,
    BDREFPAG integer,
    BDNOME varchar(70),
    BDTIPO integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDMENSALIDADE numeric(15,6),
    BDCOPARTICIPACAO numeric(15,6))
as
declare variable WDATA varchar(10);
declare variable WINI integer;
declare variable WFIM integer;
declare variable WCOMPANT integer;
declare variable WSQL varchar(5000);
declare variable WEMP varchar(20000);
declare variable WCOL varchar(30000);
declare variable WSQL2 varchar(5000);
declare variable WPLASAUDE integer = 0;
declare variable WCODDPN integer = 0;
declare variable WOK integer = 0;
declare variable WSQL3 varchar(5000);
declare variable WTEMCALCULO integer = 0;
BEGIN
  /* Procedure Text */
--  suspend;

 if (prANO = 0) then
    begin
        wIni = 190001;
        wFim = 209901;
    end
  else
    begin
        wIni = CAST(CAST(prano AS VARCHAR(4))||'01' AS INTEGER);
        wFim = CAST(CAST(prano AS VARCHAR(4))||'12' AS INTEGER);
     end
 WCOMPANT = 0;
 WPLASAUDE = 0;

 IF ((premp IS NULL) OR (premp = '')) THEN
    wemp = 'null';
 ELSE
    wemp = ''''||SUBSTRING(premp FROM 1 FOR 20000)||'''';

 IF ((prcol IS NULL) OR (prcol = '')) THEN
    wcol = 'null';
 ELSE
    wcol = ''''||SUBSTRING(prcol FROM 1 FOR 30000)||'''';

 wsql = ' select a.bdref,a.bdrefpag,a.bdcodemp,a.bdcodcol '||
          ' from SP_VRHF_DADOS_SAUDE('||wemp||','||wcol||','||wini||','||wfim||', 1, 1) a ';

 if (COALESCE(prrefpag, 0) > 0) then
    wsql = wsql||' where bdrefpag = '||prrefpag;

 wsql = wsql||' group by a.bdref, a.bdrefpag, a.bdcodemp, a.bdcodcol ';
 wsql = wsql||' order by a.bdref, a.bdrefpag';

 FOR EXECUTE STATEMENT wsql INTO
   :bdref,:bdrefpag,:bdcodemp,:bdcodcol DO
   BEGIN
     wtemcalculo = 0;
   /* Sol.149866 Leonardo Schwab 21/05/2021
      Chamada da SP_VRH_CONVSAU_DIRF trocada pela chamada das SPs, sp_vrhm_emp_val_col_op_atu e sp_vrhm_emp_val_dep_op_atu.
      Adicionado os parâmetros PROPER, PRCONV, PRREFPAG para filtro. Para reduzir um pouco da lentidão.
   */
/*     wsql2 = 'select bdnome, bdtipo, bdcodplaconvsau, bdcodoperadora, bdcodconvenio, bdvalormensalidade, bdvalorcopar '||
             'from SP_VRH_CONVSAU_DIRF('||bdcodemp||', '||bdcodcol||', '||bdref||', 0, '||prano||') ';


     for execute statement wsql2 
     into :BDNOME, :BDTIPO, :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDMENSALIDADE, :BDCOPARTICIPACAO
     do
        SUSPEND;
*/
     wsql2 = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP ='||bdcodemp||' and BDCODCOL = '||bdcodcol;
     execute statement wsql2 into : BDNOME;
     BDCODDPN = 0;

     wsql2 = 'select first 1 BDCODPLACONVSAU from VRHF_BASE_TEMPVINC where BDCODEMP = '||bdcodemp||' and BDREFEMP <= '||bdref||' order by BDREFEMP DESC';
     execute statement wsql2 into :WPLASAUDE;

     if (WPLASAUDE is null) then
        WPLASAUDE = 0;

     wsql2 = 'SELECT BDCODPLACONVSAU, BDCODOPERADORA, BDCODCONVENIO, BDVALORMENSALIDADEFUN, BDVALORCOPARFUN FROM sp_vrhm_emp_val_col_op_atu('||bdcodemp||','||bdcodcol||','||bdref||','||wplasaude||','||proper||','||prconv||')';

     for execute statement wsql2
     into :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDMENSALIDADE, :BDCOPARTICIPACAO
     do
     begin
       BDTIPO = 0;
       suspend;
       wtemcalculo = 1;
     end

     wsql2 = 'SELECT BDCODPLACONVSAU, BDCODOPERADORA, BDCODCONVENIO, BDVALORMENSALIDADEDEP, BDVALORCOPARDEP, BDCODDPN FROM sp_vrhm_emp_val_dep_op_atu('||bdcodemp||','||bdref||','||bdcodcol||',null,'||wplasaude||','||proper||','||prconv||')';

     WCODDPN = 0;
     for execute statement wsql2
     into :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDMENSALIDADE, :BDCOPARTICIPACAO, :WCODDPN
     do
     begin
       BDTIPO = 1;
       wok = null;

       if (coalesce(prano, 0) > 0) then
         wsql3 = 'select first 1 BDCODDPN, BDNOMEDPN from VRH_EMP_TDEP_REF where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||
                ' and BDCODDPN = '||WCODDPN||' and BDREFDPN <= '||prano||'12 and upper(coalesce(BDCONVMEDDPN, ''FALSE'')) = ''TRUE'' order by BDREFDPN DESC';
       else
         wsql3 = 'select first 1 BDCODDPN, BDNOMEDPN from VRH_EMP_TDEP_REF where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||
             ' and BDCODDPN = '||WCODDPN||' and BDREFDPN <= '||bdref||' and upper(coalesce(BDCONVMEDDPN, ''FALSE'')) = ''TRUE'' order by BDREFDPN DESC';

       execute statement wsql3 into :wok, :BDNOME;
       BDCODDPN = wok;

       if (coalesce(wok, 0) > 0) then
         begin
         suspend;
           wtemcalculo = 1;
         end
       else
         begin
           wok = null;
           wsql3 = 'select first 1 BDCODDPN, BDNOMEDPN from VRH_EMP_TDEP_REF where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||
                  ' and BDCODDPN = '||WCODDPN||' and upper(coalesce(BDCONVMEDDPN, ''FALSE'')) = ''TRUE'' order by BDREFDPN DESC ';
     
           execute statement wsql3 into :wok, :BDNOME;
           BDCODDPN = wOk;

           if (coalesce(wok, 0) > 0) then
              begin
              suspend;
                wtemcalculo = 1;
         end
     end
     end
   END

   --if (wtemcalculo = 0) then
      --begin
 wIni = CAST(CAST(prano AS VARCHAR(4))||'01' AS INTEGER);
 wfim = CAST(CAST(prano AS VARCHAR(4))||'12' AS INTEGER);
 WCOMPANT = 0;
       
 IF ((premp IS NULL) OR (premp = '')) THEN
    wemp = 'null';
 ELSE
    wemp = ''''||SUBSTRING(premp FROM 1 FOR 20000)||'''';
       
 IF ((prcol IS NULL) OR (prcol = '')) THEN
    wcol = 'null';
 ELSE
    wcol = ''''||SUBSTRING(prcol FROM 1 FOR 30000)||'''';
       
 wsql = ' select a.bdref,a.bdrefpag,a.bdcodemp,a.bdcodcol '||
          ' from ('||
              'select * from SP_VRHF_DADOS_SAUDE('||wemp||','||wcol||','||wini||','||wfim||', 1, 2)) a ';
        wsql = wsql||' where A.bdref not in (select BDREF from SP_VRHF_DADOS_SAUDE('||wemp||','||wcol||','||wini||','||wfim||', 1, 1)) ';
 wsql = wsql||' group by a.bdref,a.bdrefpag,a.bdcodemp,a.bdcodcol ';
 wsql = wsql||' order by a.bdref,a.bdrefpag';
       
 FOR EXECUTE STATEMENT wsql INTO
   :bdref,:bdrefpag,:bdcodemp,:bdcodcol DO
   BEGIN
     IF (wcompant <> bdref) THEN
        BEGIN
          wData = SUBSTRING(''||:bdref FROM 5 FOR 2)||'/01/'||SUBSTRING(''||:bdref FROM 1 FOR 4);
          EXECUTE PROCEDURE sp_seta_competencia(:bdref,:wData,NULL);
          wcompant = bdref;
        END
     /* Sol.149866 Leonardo Schwab 21/05/2021
       Chamada da SP_VRH_CONVSAU_DIRF trocada pela chamada das SPs, sp_vrhm_emp_val_col_op_atu e sp_vrhm_emp_val_dep_op_atu.
       Adicionado os parâmetros PROPER, PRCONV, PRREFPAG para filtro. Para reduzir um pouco da lentidão.
     */
       /*     wsql2 = 'select bdnome, 9000, bdcodplaconvsau, bdcodoperadora, bdcodconvenio, bdvalormensalidade, bdvalorcopar '||
             'from SP_VRH_CONVSAU_DIRF('||bdcodemp||', '||bdcodcol||', '||bdref||', 0, '||prano||') ';
     for execute statement wsql2
     into :BDNOME, :BDTIPO, :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDMENSALIDADE, :BDCOPARTICIPACAO
     do
        SUSPEND;*/
       
     wsql2 = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP ='||bdcodemp||' and BDCODCOL = '||bdcodcol;
     execute statement wsql2 into :BDNOME;
     BDCODDPN = 0;
       
     wsql2 = 'select first 1 BDCODPLACONVSAU from VRHF_BASE_TEMPVINC where BDCODEMP = '||bdcodemp||' and BDREFEMP <= '||bdref||' order by BDREFEMP DESC';
     execute statement wsql2 into :WPLASAUDE;
       
     if (WPLASAUDE is null) then
        WPLASAUDE = 0;
       
     wsql2 = 'SELECT BDCODPLACONVSAU, BDCODOPERADORA, BDCODCONVENIO, BDVALORMENSALIDADEFUN, BDVALORCOPARFUN FROM sp_vrhm_emp_val_col_op_atu('||bdcodemp||','||bdcodcol||','||bdref||','||wplasaude||','||proper||','||prconv||')';
       
     for execute statement wsql2
     into :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDMENSALIDADE, :BDCOPARTICIPACAO
     do
     begin
       BDTIPO = 9000;
       suspend;
     end
       
     wsql2 = 'SELECT BDCODPLACONVSAU, BDCODOPERADORA, BDCODCONVENIO, BDVALORMENSALIDADEDEP, BDVALORCOPARDEP, BDCODDPN FROM sp_vrhm_emp_val_dep_op_atu('||bdcodemp||','||bdref||','||bdcodcol||',null,'||wplasaude||','||proper||','||prconv||')';
       
     for execute statement wsql2
     into :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDMENSALIDADE, :BDCOPARTICIPACAO, :WCODDPN
     do
     begin
       BDTIPO = 9000;
       wok = null;
       
       if (coalesce(prano, 0) > 0) then
         wsql3 = 'select first 1 BDCODDPN, BDNOMEDPN from VRH_EMP_TDEP_REF where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||
                ' and BDCODDPN = '||WCODDPN||' and BDREFDPN <= '||prano||'12 and upper(coalesce(BDCONVMEDDPN, ''FALSE'')) = ''TRUE'' order by BDREFDPN DESC';
       else
         wsql3 = 'select first 1 BDCODDPN, BDNOMEDPN from VRH_EMP_TDEP_REF where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||
             ' and BDCODDPN = '||WCODDPN||' and BDREFDPN <= '||bdref||' and upper(coalesce(BDCONVMEDDPN, ''FALSE'')) = ''TRUE'' order by BDREFDPN DESC';
       
       execute statement wsql3 into :wok, :BDNOME;
       BDCODDPN = wok;
       
       if (coalesce(wok, 0) > 0) then
         suspend;
       else
         begin
           wok = null;
           wsql3 = 'select first 1 BDCODDPN, BDNOMEDPN, BDPARENESCODPN, BDDATANASCDPN, BDCPFDPN from VRH_EMP_TDEP_REF where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||
                  ' and BDCODDPN = '||WCODDPN||' and upper(coalesce(BDCONVMEDDPN, ''FALSE'')) = ''TRUE'' order by BDREFDPN DESC ';
     
           execute statement wsql3 into :wok, :BDNOME;
           BDCODDPN = wok;

           if (coalesce(wok, 0) > 0) then
              suspend;
         end
     end
   END
      --end
END^

/* Restore proc. body: SP_VRHM_FF_OP_REF */
create or alter procedure SP_VRHM_FF_OP_REF (
    PREMP varchar(32000) = '',
PRCOL VARCHAR(32000) = '',
PRREFINI INTEGER = 0,
PRREFFIM INTEGER = 0)
returns (
    BDCODEMP integer,
BDCODCOL INTEGER,
BDREF INTEGER,
    BDREFPAG integer,
BDNOME VARCHAR(70),
BDTIPO INTEGER,
BDCODPLACONVSAU INTEGER,
BDCODOPERADORA INTEGER,
BDCODCONVENIO INTEGER,
BDMENSALIDADE NUMERIC(15,6),
BDCOPARTICIPACAO NUMERIC(15,6))
 AS
DECLARE VARIABLE WANOINI INTEGER;
DECLARE VARIABLE WANOFIM INTEGER;
BEGIN
  /* Procedure Text */

  wAnoIni = CAST(SUBSTRING(CAST(prrefini AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wAnoFim = CAST(SUBSTRING(CAST(prreffim AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);

  WHILE (wanoini <= wanofim) DO
    BEGIN
      FOR SELECT BDCODEMP, BDCODCOL, BDREF, BDREFPAG, BDNOME, BDTIPO, BDCODPLACONVSAU, BDCODOPERADORA, BDCODCONVENIO, BDMENSALIDADE, BDCOPARTICIPACAO
      FROM sp_vrhm_ff_op_ano(:premp,:prcol,:wanoini)
         INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDNOME, :BDTIPO, :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDMENSALIDADE, :BDCOPARTICIPACAO DO
        BEGIN
          IF ((bdref >= prrefini) AND (bdref <= prreffim)) THEN
             SUSPEND;

        END



      wanoini = wanoini + 1;
    END

--  suspend;
END^


/* Restore proc. body: SP_VRHM_VAL_PS_COL */
CREATE OR ALTER procedure SP_VRHM_VAL_PS_COL (
    PRCODEMP varchar(32000),
    PRCODCOL varchar(32000),
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDREF integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDVALORMENSALIDADE numeric(15,6),
    BDVALLORCOPAR numeric(15,6),
    BDCODTIPOCONV integer,
    BDCODEMP integer)
as
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(30000);
declare variable WREFINI varchar(6);
declare variable WREFFIM varchar(6);
declare variable WAUX varchar(2);
declare variable WEMP integer;
declare variable WCODEMP varchar(30000);
BEGIN
  /* Procedure Text */
--  suspend;
  IF (prcodemp IS NULL) THEN
     prcodemp = '';

  IF (prcodcol IS NULL) THEN
     prcodcol = '';

  IF (prrefini IS NULL) THEN
     prrefini = 0;

  IF (prreffim IS NULL) THEN
     prreffim = prrefini;

  SELECT str FROM strzero(:prrefini,6) INTO wrefini;
  SELECT str FROM strzero(:prreffim,6) INTO wreffim;

  wemp = 0;
  IF (wrefini <> 0) THEN
     BEGIN
       WHILE (wrefini <= wreffim) DO
         BEGIN
          wcodemp = 'select tab.BDCODEMP from tempresas tab '; -- #161614 LuizCovre 02/08/2022
          IF (prcodemp <> '') THEN                             -- faz um select das empresas com ou sem where(todas)
            wcodemp = wcodemp || 'where '||prcodemp;           -- dependendo do filtro que vem no relat?rio
                                                               -- usa o código da empresa no param?tro da SP_VRHM_EMP_VAL_COL_OP_ATU
          wcodemp = wcodemp || ' order by tab.BDCODEMP';       -- logo abaixo, melhorando a performance principalmente para bases grandes(MG)
                                                               -- segue a rotina com cada código de empresa, principalmente quando no
          FOR EXECUTE STATEMENT wcodemp INTO :wemp DO          -- filtro vem todas(''), IN ou num select de tabela tempor?ria(TMP_EMPRESAS_SELECT)
            BEGIN
           bdref = wrefini;
     
              wsql = 'select x.bdcodplaconvsau,x.bdcodoperadora, x.bdcodconvenio, tab.bdcodemp, tab.bdcodcol, tab.bdnomcol, '||
                     'coalesce(x.BDVALORMENSALIDADEFUN,0) bdvalormensalidade, x.bdvalorcoparfun bdvalorcopar, y.bdcodtipoconv '||
                   --' from vw_vrh_emp_tcolcon_cad tab '|| #161614 LuizCovre 02/08/2022 removido para ser usado o código abaixo--
                     'from VRH_EMP_TCOLCON_CAD TAB '||
                     'join(select X.BDCODEMP, X.BDCODCOL, max(X.BDREFCOL) BDREFCOL from VRH_EMP_TCOLCON_CAD X '||
                     'group by X.BDCODEMP, X.BDCODCOL) CADX on (TAB.BDCODEMP = CADX.BDCODEMP and TAB.BDCODCOL = CADX.BDCODCOL and TAB.BDREFCOL = CADX.BDREFCOL) '||
                   --------------------------------------------------------------------------------------------------------------
                   --'join SP_VRHM_EMP_VAL_COL_OP_ATU(0, 0, '||wrefini||') x on (tab.bdcodemp = x.bdcodemp and tab.bdcodcol = x.bdcodcol) '|| #161614 LuizCovre 02/08/2022
                     'join SP_VRHM_EMP_VAL_COL_OP_ATU('||wemp||', 0, '||wrefini||') x on (tab.bdcodemp = x.bdcodemp and tab.bdcodcol = x.bdcodcol) '||
                     'join VRH_BASE_CONVENIO_OPERADORAS y on (y.bdcodplaconvsau = x.bdcodplaconvsau and y.bdcodoperadora = x.bdcodoperadora and y.bdcodconvenio = x.bdcodconvenio) ';


           EXECUTE PROCEDURE sp_seta_competencia(:wrefini,NULL,NULL);

           wwhere = '';
           IF (prcodemp <> '') THEN
              BEGIN
                wwhere = wwhere||' where '||prcodemp;

                IF (prcodcol <> '') THEN
                   wwhere = wwhere||' and '||prcodcol;
              END

           wsql = wsql||wwhere;

           FOR EXECUTE STATEMENT wsql INTO
             :bdcodplaconvsau,
             :bdcodoperadora,
             :bdcodconvenio,
             :bdcodemp,
             :bdcodcol,
             :bdnomcol,
             :bdvalormensalidade,
             :bdvallorcopar,
             :bdcodtipoconv DO
             BEGIN
               SUSPEND;
             END
           --suspend;
           IF (SUBSTRING(wrefini FROM 5 FOR 2) = '12') THEN
              BEGIN
                wrefini = (CAST(SUBSTRING(wrefini FROM 1 FOR 4) AS INTEGER)+1)||'01';
              END
           ELSE
              BEGIN
                waux = (CAST(SUBSTRING(wrefini FROM 5 FOR 2) AS INTEGER)+1);
                wrefini = SUBSTRING(wrefini FROM 1 FOR 4);

                IF (CAST(waux AS INTEGER) >= 10) THEN
                   wrefini = wrefini||waux;
                ELSE
                   wrefini = wrefini||'0'||waux;
              END
         END
     END
    END
END^

/* Restore proc. body: SP_VRHM_VAL_PS_DEP */
create or alter procedure SP_VRHM_VAL_PS_DEP (
    PRCODEMP varchar(32000),
    PRCODCOL varchar(32000),
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDREF integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDVALORMENSALIDADE numeric(15,6),
    BDVALLORCOPAR numeric(15,6),
    BDCODEMP integer,
    BDCODDPN integer,
    BDNOMDEP varchar(70))
as
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(30000);
declare variable WREFINI varchar(6);
declare variable WREFFIM varchar(6);
declare variable WAUX varchar(2);
BEGIN
  /* Procedure Text */
--  suspend;
  IF (prcodemp IS NULL) THEN
     prcodemp = '';

  IF (prcodcol IS NULL) THEN
     prcodcol = '';

  IF (prrefini IS NULL) THEN
     prrefini = 0;

  IF (prreffim IS NULL) THEN
     prreffim = prrefini;

  SELECT str FROM strzero(:prrefini,6) INTO wrefini;
  SELECT str FROM strzero(:prreffim,6) INTO wreffim;

  IF (wrefini <> 0) THEN
     BEGIN
       WHILE (wrefini <= wreffim) DO
         BEGIN
           bdref = wrefini;
     
          wsql = 'select tab.bdcodemp, tab.bdcodcol, tab.bdcoddpn, tab.bdcodplaconvsau, '||
                 'tab.bdcodoperadora,tab.bdcodconvenio, '||
                 'col.bdnomcol, dep.bdnomedpn '||
                 'from SP_VRHM_EMP_VINC_DEP_CONV_ATU(';

           if (coalesce(prcodemp, '') <> '') then
              wsql = wsql||''''||replace(upper(prcodemp), 'TAB.BDCODEMP', 'BDCODEMP')||''', ';
           else
              wsql = wsql||'null, ';

           wsql = wsql||wrefini||', ';

           if (coalesce(prcodcol, '') <> '') then
              wsql = wsql||''''||replace(upper(prcodcol), 'TAB.BDCODCOL', 'BDCODCOL')||'''';
           else
              wsql = wsql||'null';

           wsql = wsql||') tab '||
                --'left outer join VW_VRH_EMP_TCOLCON_CAD col on (tab.bdcodemp = col.bdcodemp and tab.bdcodcol = col.bdcodcol) '|| #161614 LuizCovre 02/08/2022 removido para ser usado o código abaixo--
                  'left outer join(select CAD.BDCODEMP, CAD.BDCODCOL, CAD.BDNOMCOL '||                                           --   melhorando a performance principalmente para bases grandes(MG)   --
                  '     from VRH_EMP_TCOLCON_CAD CAD join(select X.BDCODEMP, X.BDCODCOL, max(X.BDREFCOL) BDREFCOL '||
                  '                                     from VRH_EMP_TCOLCON_CAD X '||
                  '                                     group by X.BDCODEMP, X.BDCODCOL) CADX on (CAD.BDCODEMP = CADX.BDCODEMP '||
                  '                                                                           and CAD.BDCODCOL = CADX.BDCODCOL '||
                  '                                                                           and CAD.BDREFCOL = CADX.BDREFCOL)) COL on (TAB.BDCODEMP = COL.BDCODEMP '||
                  '                                                                                                                  and TAB.BDCODCOL = COL.BDCODCOL) '||
                -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
                  ' join vw_vrh_emp_tdep_ref dep on (tab.bdcodemp = dep.bdcodemp and tab.bdcodcol = dep.bdcodcol and tab.bdcoddpn = dep.bdcoddpn) ';

           EXECUTE PROCEDURE sp_seta_competencia(:wrefini,NULL,NULL);

           wwhere = ' where upper(coalesce(dep.BDCONVMEDDPN, ''FALSE'')) = ''TRUE'' ';
           IF (prcodemp <> '') THEN
              BEGIN
                wwhere = wwhere||' and '||prcodemp;

                IF (prcodcol <> '') THEN
                   wwhere = wwhere||' and '||prcodcol;
              END

           wsql = wsql||wwhere;

           FOR EXECUTE STATEMENT wsql INTO
             :bdcodemp,
             :bdcodcol,
             :bdcoddpn,
             :bdcodplaconvsau,
             :bdcodoperadora,
             :bdcodconvenio,
             :bdnomcol,
             :bdnomdep DO
             BEGIN
               select first 1 coalesce(bdvalorcopardep, 0) from SP_VRHM_EMP_DEP_COP_OP_SAU(:BDCODEMP, :wrefini, :BDCODCOL, :BDCODDPN) into :BDVALLORCOPAR;

               for select BDMENSALIDADE from SP_VRHM_EMP_DEP_VAL_OP_SAU(:BDCODEMP, :wrefini, :BDCODCOL, :BDCODDPN) into :BDVALORMENSALIDADE do
                 SUSPEND;
             END

           --suspend;
           IF (SUBSTRING(wrefini FROM 5 FOR 2) = '12') THEN
              BEGIN
                wrefini = (CAST(SUBSTRING(wrefini FROM 1 FOR 4) AS INTEGER)+1)||'01';
              END
           ELSE
              BEGIN
                waux = (CAST(SUBSTRING(wrefini FROM 5 FOR 2) AS INTEGER)+1);
                wrefini = SUBSTRING(wrefini FROM 1 FOR 4);

                IF (CAST(waux AS INTEGER) >= 10) THEN
                   wrefini = wrefini||waux;
                ELSE
                   wrefini = wrefini||'0'||waux;
              END
         END
     END
END^



/* Restore proc. body: SP_VSUC_COPIA_CT_PLANO_DFIS */
ALTER PROCEDURE SP_VSUC_COPIA_CT_PLANO_DFIS(CODIGOPLANOCOPIAR INTEGER,
ANOCOPIAR INTEGER,
ANONOVO INTEGER)
 AS
DECLARE VARIABLE WCODPLA_DFIS INTEGER;
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WCODTPLA_DFIS INTEGER;
DECLARE VARIABLE WTIPOCONTA_DFIS INTEGER;
DECLARE VARIABLE WTIPOEXPORTA_DFIS INTEGER;
DECLARE VARIABLE WANO INTEGER;
BEGIN
  DELETE FROM PLANOS_TPLA_DFIS WHERE BDCODPLAPADRAO = :codigoplanocopiar AND bdano = :anonovo;

  FOR SELECT BDCODPLA_DFIS   , BDCODTPLA,  BDCODTPLA_DFIS, BDTIPOCONTA_DFIS, BDTIPOEXPORTA_DFIS, bdano FROM planos_tpla_DFIS  WHERE bdCODPLAPADRAO = :codigoplanocopiar
              AND bdano = :anocopiar INTO :wcodpla_DFIS, wcodtpla, :wcodtpla_DFIS, :WTIPOCONTA_DFIS, :WTIPOEXPORTA_DFIS, :wano DO
     BEGIN
        INSERT INTO planos_tpla_DFIS (bdCODPLAPADRAO, BDCODPLA_DFIS, BDCODTPLA, BDCODTPLA_DFIS, BDTIPOCONTA_DFIS, BDTIPOEXPORTA_DFIS, bdano) VALUES
                                     (:codigoplanocopiar, :wcodpla_DFIS, :wcodtpla,  :wcodtpla_DFIS, :WTIPOCONTA_DFIS, :WTIPOEXPORTA_DFIS, :anonovo);
     END
END
^

/* Restore proc. body: SP_VSUC_COPIA_CT_PLANO_FCONT */
ALTER PROCEDURE SP_VSUC_COPIA_CT_PLANO_FCONT(CODIGOPLANOCOPIAR INTEGER,
ANOCOPIAR INTEGER,
ANONOVO INTEGER)
 AS
DECLARE VARIABLE WCODPLA_FCONT INTEGER;
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WCODTPLA_FCONT INTEGER;
DECLARE VARIABLE WCODGRUPOCONTA_FCONT INTEGER;
DECLARE VARIABLE WANO INTEGER;
BEGIN
  DELETE FROM PLANOS_TPLA_FCONT WHERE BDCODPLAPADRAO = :codigoplanocopiar AND bdano = :anonovo;

  FOR SELECT BDCODPLA_FCONT   , BDCODTPLA,  BDCODTPLA_FCONT, BDCODGRUPOCONTA_FCONT , bdano FROM planos_tpla_FCONT  WHERE bdCODPLAPADRAO = :codigoplanocopiar
              AND bdano = :anocopiar INTO :wcodpla_FCONT   , wcodtpla,  :wcodtpla_FCONT, :wcodgrupoconta_FCONT, :wano DO
     BEGIN
        INSERT INTO planos_tpla_FCONT (bdCODPLAPADRAO,      BDCODPLA_FCONT, BDCODTPLA,  BDCODTPLA_FCONT, BDCODGRUPOCONTA_FCONT,    bdano) VALUES
                                     (:codigoplanocopiar   ,:wcodpla_FCONT, :wcodtpla,  :wcodtpla_FCONT, :wcodgrupoconta_FCONT, :anonovo);
     END
END
^

/* Restore proc. body: SPCLASSVERBAONLINE */
ALTER PROCEDURE SPCLASSVERBAONLINE(PRCLAANT VARCHAR(100),
PRCLANOVA VARCHAR(100))
 RETURNS(BDCLAANTVERBA VARCHAR(100),
BDCLAANTVERBARESC VARCHAR(100),
BDCLANOVAVERBA VARCHAR(100),
BDCLANOVAVERBARESC VARCHAR(100))
 AS
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WADD VARCHAR(10);
BEGIN
  /* Procedure Text */
  -- 02.004.000000001.000000000.000000001.000000000.000000000.000000001 {Verba }
  -- 02.004.000000002.000000000.000000001.000000000.000000000.000000001 {Verba Rescisao}

  IF (prclaant IS NOT NULL) THEN
     BEGIN
       wsql = 'select x.pos from pos('||''''||'.'||''''||','||''''||prclaant||''''||') x';
       EXECUTE STATEMENT wsql INTO wpos;

       bdclaantverba = '';
       WHILE (wpos > 0) DO
         BEGIN
           wsql = SUBSTRING(prclaant FROM 1 FOR wpos-1);
           wsql = 'select x.bdretorno from preenche_esquerda('||''''||wsql||''''||',9,'||''''||'0'||''''||') x';

           EXECUTE STATEMENT wsql INTO wadd;
           IF (bdclaantverba <> '') THEN
              bdclaantverba = bdclaantverba||'.';

           bdclaantverba = bdclaantverba||wadd;

           prclaant = SUBSTRING(prclaant FROM wpos+1);
           wsql = 'select x.pos from pos('||''''||'.'||''''||','||''''||prclaant||''''||') x';
           EXECUTE STATEMENT wsql INTO wpos;
         END

       wsql = prclaant;
       wsql = 'select x.bdretorno from preenche_esquerda('||''''||wsql||''''||',9,'||''''||'0'||''''||') x';

       EXECUTE STATEMENT wsql INTO wadd;
       IF (bdclaantverba <> '') THEN
          bdclaantverba = bdclaantverba||'.';
       bdclaantverba = bdclaantverba||wadd;

       bdclaantverbaresc = '02.004.000000002.'||bdclaantverba;
       bdclaantverba = '02.004.000000001.'||bdclaantverba;
     END

  IF (prclanova IS NOT NULL) THEN
     BEGIN
       wsql = 'select x.pos from pos('||''''||'.'||''''||','||''''||prclanova||''''||') x';
       EXECUTE STATEMENT wsql INTO wpos;

       bdclanovaverba = '';
       WHILE (wpos > 0) DO
         BEGIN
           wsql = SUBSTRING(prclanova FROM 1 FOR wpos-1);
           wsql = 'select x.bdretorno from preenche_esquerda('||''''||wsql||''''||',9,'||''''||'0'||''''||') x';

           EXECUTE STATEMENT wsql INTO wadd;
           IF (bdclanovaverba <> '') THEN
              bdclanovaverba = bdclanovaverba||'.';

           bdclanovaverba = bdclanovaverba||wadd;

           prclanova = SUBSTRING(prclanova FROM wpos+1);
           wsql = 'select x.pos from pos('||''''||'.'||''''||','||''''||prclanova||''''||') x';
           EXECUTE STATEMENT wsql INTO wpos;
         END

       wsql = prclanova;
       wsql = 'select x.bdretorno from preenche_esquerda('||''''||wsql||''''||',9,'||''''||'0'||''''||') x';

       EXECUTE STATEMENT wsql INTO wadd;
       IF (bdclanovaverba <> '') THEN
          bdclanovaverba = bdclanovaverba||'.';
       bdclanovaverba = bdclanovaverba||wadd;

       bdclanovaverbaresc = '02.004.000000002.'||bdclanovaverba;
       bdclanovaverba = '02.004.000000001.'||bdclanovaverba;
     END

  SUSPEND;
END
^

/* Restore proc. body: SP_DADOS_GPS_COMP */
create or alter procedure SP_DADOS_GPS_COMP (
    WEMP varchar(30000),
    WCOL varchar(30000),
    FANOMES integer,
    FANOMESFIM integer,
    FANOMESPAG integer,
    FPUXAFILIAIS integer,
    PRGPSSEFIP integer,
    PRCODIMP integer,
    TIPOFC integer,
    FJOINFILTROCOL varchar(5000) = '',
    FJOINEMPIMP varchar(5000) = '',
    FJOINFILTROSITCOL varchar(5000) = '',
    FCODCLA varchar(5000) = '',
    PRCOMPLEESOCIAL integer = 0)
returns (
    BDBASEFUNC13 numeric(15,2),
    BDBASEFUN13 numeric(15,2),
    BDBASERATAPOC13 numeric(15,2),
    BDBASERATAPO13 numeric(15,2),
    BDBASEFUNFN numeric(15,2),
    BDPERCDESCFPASCOL numeric(15,2),
    BDPERCRATCOL numeric(15,2),
    BDDESCENQFED varchar(10),
    BDISENFILEMP numeric(15,2),
    BDCATSEFIPEMP integer,
    BDCODENQFED integer,
    BDDATAINIPERIOD date,
    BDREFINIDCTFWEB integer,
    BDOPCAOESOCIAL integer,
    BDNOMEMP varchar(100),
    BDCNPJEMP varchar(18),
    BDDESONTOMAEMP varchar(10),
    BDCODTRIBRUR integer,
    BDBASEFUNFERFC numeric(15,2),
    BDBASEFUNFC numeric(15,2),
    BDBASEINSS13 numeric(15,2),
    BDBASEINSS numeric(15,2),
    BDBASERAT numeric(15,2),
    BDNOMETOM varchar(100),
    BDCNPJTOM varchar(18),
    BDBINSS13INDFN numeric(15,2),
    BDTIPOTOM integer,
    BDVALINDEVIDOSF numeric(15,2),
    BDVALINDEVIDO numeric(15,2),
    BDGPSSEFIP integer,
    BDSESCOOP numeric(15,2),
    BDSENAT numeric(15,2),
    BDSEST numeric(15,2),
    BDSENAR numeric(15,2),
    BDFUNAERO numeric(15,2),
    BDDPC numeric(15,2),
    BDSEBRAE numeric(15,2),
    BDSESC numeric(15,2),
    BDSENAC numeric(15,2),
    BDSESI numeric(15,2),
    BDSENAI numeric(15,2),
    BDINCRA numeric(15,2),
    BDSALEDU numeric(15,2),
    BDATUTAB varchar(10),
    BDDESONOBRA varchar(10),
    BDINDUSTRIA varchar(10),
    BDCOMERCIO varchar(10),
    BDANEXOVI varchar(10),
    BDANEXOV varchar(10),
    BDANEXOIII varchar(10),
    BDANEXOIV varchar(10),
    BDPERCFPAS numeric(15,2),
    BDPERCAUT numeric(15,2),
    BDPERCPRO numeric(15,2),
    BDPERCFUN numeric(15,2),
    BDSIMPLESGPS integer,
    BDCODEMP integer,
    BDREFPAG integer,
    BDREFFN integer,
    BDBASEFUN13RFN numeric(15,2),
    BDBASEFUNFERFN numeric(15,2),
    BDCCATVCONCOM varchar(10),
    BDBASEFUN13RFC numeric(15,2),
    BDINSS13FN numeric(15,2),
    BDINSSFEFOLFN numeric(15,2),
    BDINSSFN numeric(15,2),
    BDCODTPCC integer,
    BDCODFPAS integer,
    BDCODCENTRO integer,
    BDCODCOL integer,
    BDCODTOMADOR integer,
    BDBASERATAPO13RFN numeric(15,2),
    BDBASERATAPOFERFN numeric(15,2),
    BDBASERATAPOFN numeric(15,2),
    VALOUTENTIDADE integer,
    SALMATERNIDADE numeric(15,2),
    SALFAM numeric(15,2),
    BDGRUPOCLA integer,
    BDCODTER integer,
    BDBINSSMV13FN numeric(15,2),
    BDBINSSMVFN numeric(15,2),
    BDBASERATAPO13RFC numeric(15,2),
    BDBASERATAPOFERFC numeric(15,2),
    BDTIPO_TPCC integer,
    BDBASERATAPOFC numeric(15,2),
    BDCODMATRIZ integer,
    BDCODEMPCOL integer,
    BDREFPAGTC integer,
    BDPERCRAT numeric(15,4),
    BDPERCFAPCAD numeric(15,4),
    BDPERCRATCAD numeric(15,4),
    BDCODTIPOFC integer,
    BDBASEPIS numeric(18,6),
    BDBASEPIS13 numeric(18,6),
    BDCATEGORIAESOCIAL integer)
as
declare variable WPERCDESCFPASCOL numeric(15,2);
declare variable WPERCRATCOL numeric(15,4);
declare variable WCOLREF varchar(30);
declare variable WISENFILEMP numeric(15,2);
declare variable WCATSEFIPEMP integer;
declare variable WCODENQFED integer;
declare variable WDESCENQFED varchar(10);
declare variable WDATAINIPERIOD date;
declare variable WREFINIDCTFWEB integer;
declare variable WOPCAOESOCIAL integer;
declare variable WNOMEEMP varchar(100);
declare variable WCNPJEMP varchar(18);
declare variable WCEIEMP varchar(18);
declare variable WDESONTOMAEMP varchar(10);
declare variable WCODTRIBRUR integer;
declare variable WCCATVCONCOM varchar(10);
declare variable WATUTABEMP varchar(10);
declare variable WATUTABCC varchar(10);
declare variable WDESONOBRA varchar(10);
declare variable WINDUSTRIAEMP varchar(10);
declare variable WINDUSTRIACC varchar(10);
declare variable WCOMERCIOEMP varchar(10);
declare variable WCOMERCIOCC varchar(10);
declare variable WANEXOVICC varchar(10);
declare variable WANEXOVIEMP varchar(10);
declare variable WANEXOVEMP varchar(10);
declare variable WANEXOVCC varchar(10);
declare variable WANEXOIIIEMP varchar(10);
declare variable WANEXOIIICC varchar(10);
declare variable WANEXOIVEMP varchar(10);
declare variable WSALEDUCC numeric(15,2);
declare variable WSEBRAEEMP numeric(15,2);
declare variable WFUNAEROEMP numeric(15,2);
declare variable WTAXACNAEEMP numeric(15,4);
declare variable WFAPEMP numeric(15,4);
declare variable WFUNAEROCC numeric(15,2);
declare variable WDPCCC numeric(15,2);
declare variable WDPCEMP numeric(15,2);
declare variable WANEXOIVCC varchar(10);
declare variable WINCRAEMP numeric(15,2);
declare variable WINCRACC numeric(15,2);
declare variable WSALEDUEMP numeric(15,2);
declare variable WNAOAPLICAMP932 varchar(10);
declare variable WSENAC numeric(15,2);
declare variable WSESI numeric(15,2);
declare variable WSENAI numeric(15,2);
declare variable WSESCOOPCC numeric(15,2);
declare variable WSENATCC numeric(15,2);
declare variable WSESTCC numeric(15,2);
declare variable WSENARCC numeric(15,2);
declare variable WSESCOOP numeric(15,2);
declare variable WSENAT numeric(15,2);
declare variable WSEST numeric(15,2);
declare variable WSENAR numeric(15,2);
declare variable WSESC numeric(15,2);
declare variable WSESCCC numeric(15,2);
declare variable WCODCNAEEMP integer;
declare variable WCODCNAECC integer;
declare variable WSENACCC numeric(15,2);
declare variable WSESICC numeric(15,2);
declare variable WSENAICC numeric(15,2);
declare variable WSEBRAECC numeric(15,2);
declare variable WPERTERCEMP numeric(15,4);
declare variable WPERTERCCC numeric(15,2);
declare variable WEMPREF varchar(20);
declare variable WCCREF varchar(30);
declare variable WDADPERTOM integer;
declare variable WSQL varchar(30000);
declare variable WEMPMATRIZ integer;
declare variable WSIMPLESGPSEMPRESA integer;
declare variable WSIMPLESGPSCC integer;
declare variable WCODFPASEMP integer;
declare variable WAUTTOMCC integer;
declare variable WEMPTOMCC numeric(15,2);
declare variable WCOLTOMCC numeric(15,2);
declare variable WAUTEMP numeric(15,2);
declare variable WEMPEMP numeric(15,2);
declare variable WFUNEMP numeric(15,2);
declare variable WFAPTOMCC numeric(15,4);
declare variable WTAXACNAECC numeric(15,2);
declare variable WCODFPASCC numeric(15,2);
declare variable WCATEGORIAESOCIAL integer;
begin
  /*
  Fpuxafiliais = 0 -> Puxa filiais / 1 -> Não puxa filiais
  FANOMES - Competnecia inicial
  FAnoMesFim - Competencia final
  Fanomespag - Referencia de pagamento
  prGPSSEFIP = 0 -> SIM 1-> NAO

  */
  if (coalesce(FJOINFILTROCOL, '') <> '') then
     FJOINFILTROCOL = ' JOIN TEMP_FILTRO_COLCON_REL TFILTRO ON  ( TFILTRO.BDCOMP = '||''''||'EDCODCOLCON'||''''||' AND colcon.BDCODEMP = TFILTRO.BDCODEMP AND colcon.BDCODCOL = TFILTRO.BDCODCOL ) ' ;


  if (wemp is null) then
     wemp = ' null ';
  else
     wemp = ''''||wemp||'''';

  if (wcol is null) then
     wcol = ' null ';
  else
     wcol = ''''||wcol||'''';



  /* SQL de consulta nos cálculos */
  wsql = 'select  fn.bdreffn, fn.bdrefpag, fn.bdcodcentro, fn.bdcodtpcc, fn.bdinssfn, fn.bdinssfefolfn, '||
         'fn.bdinss13fn, fn.BDBASEFUNFC, fn.BDBASEFUNFERFC, fn.BDBASEFUN13RFC,  fn.BDBASERATAPOFC, fn.BDBASERATAPOFERFC, fn.BDBASERATAPO13RFC, '||
         'fn.salfam, fn.salMaternidade, fn.valOutentidade,  fn.bdcodtomador, fn.bdcodcol, fn.bdcodter,  f.bdgrupocla, '||
         'fn.BDBINSSMVFN, fn.BDBINSSMV13FN, fn.bdcodemp, fn.BDREFPAGTC, fn.BDCODTIPOFC, fn.BDTIPO_TPCC, fn.bdgpssefip, fn.bdvalindevido, fn.bdvalindevidosf, '||
         'FN.bdtipotom, fn.BDBINSS13INDFN, fn.BDCNPJTOM, fn.BDNOMETOM, FN.BDBASERAT, FN.BDBASEINSS, FN.BDBASEINSS13, 0.0 BDBASERATAPO13, 0.0 BDBASERATAPOC13, '||
         '0.0 BDBASEFUN13, 0.0 BDBASEFUNC13, FN.BDBASEPIS, FN.BDBASEPIS13 '||
         'from (';

   -- Folha complementar normal
   wSql = wsql||' select ';

   if (Fpuxafiliais = 0) then
      wSql = wsql||' impemp.bdempimp bdcodemp, fn.bdcodemp bdcodempcol,';
   else
   wSql = wsql||' fn.bdcodemp bdcodemp, fn.bdcodemp bdcodempcol,';

   wSql = wsql||' fn.bdreffn, fn.bdrefcomp bdrefpag,';
   wSql = wsql||' null bdcodcentro, null bdcodtpcc,  coalesce(fn.bdinssfn,0) bdinssfn,';
   wSql = wsql||' coalesce(fn.bdinssfefolfn,0) bdinssfefolfn, coalesce(fn.bdinss13fn,0) bdinss13fn,';
   wSql = wsql||' coalesce(fn.bdbinssfn,0) BDBASEFUNFC, coalesce(fn.bdbinssfefolfn,0) BDBASEFUNFERFC, coalesce(fn.bdbinss13fn,0) BDBASEFUN13RFC,';
   wSql = wsql||' coalesce(fn.bdbratapofn,0) BDBASERATAPOFC, coalesce(fn.bdbratapofefn,0) BDBASERATAPOFERFC, coalesce(fn.bdbratapo13fn,0) BDBASERATAPO13RFC,';
   wSql = wsql||' coalesce(fn.bdsalfamfn,0) salfam, coalesce(fn.bdsalmatempfn,0) salMaternidade, 0 valOutentidade,';
   wSql = wsql||' null bdcodtomador, fn.bdcodcol, null bdcodter, FN.BDBINSSMVFn BDBINSSMVFN, fN.BDBINSSMV13Fn BDBINSSMV13FN, fn.bdgpssefip,';
   wSql = wsql||' fn.bdvalindevido, fn.bdvalindevidosf, ';
   wSql = wsql||' -1 BDTIPO_TPCC, ';
   wSql = wsql||' 1 bdtipotom,';
   wSql = wsql||' coalesce(fn.BDBINSS13INDFN, 0) BDBINSS13INDFN, ';
   wSql = wsql||' cast(null as varchar(18)) BDCNPJTOM, cast(null as varchar(100)) BDNOMETOM, FN.BDBASERAT, FN.BDBASEINSS, FN.BDBASEINSS13 ';
   wSql = wsql||' , FN.BDCODTIPOFC, case when coalesce(FN.BDCODTIPOFC, 0) > 1 then FN.BDREFCOMP else FN.BDREFFN end BDREFPAGTC, FN.BDBASEPIS, FN.BDBASEPIS13 ';
   wSql = wsql||' from sp_vrhf_dados_inss_fc('||wEmp||', '||wCol||', '||FAnoMes||', '||Fanomespag||',';

   if (prGPSSEFIP = 0) then
      wSql = wsql||'1';
   else
      wSql = wsql||'0';

   if (Fpuxafiliais = 0) then
      wSql = wsql||',1';
   else
      wSql = wsql||',0';

   wSql = wsql||','||FAnoMesFim;

   if(PRCOMPLEESOCIAL = 1) then
       wSql = wsql||', 1';


   wSql = wsql||') fn ';

   if (FJOINFILTROCOL <> '') then
      wsql = wsql||trim(replace(upper(FJOINFILTROCOL),'COLCON.','FN.'));

   if ((Fpuxafiliais = 0) and (FJOINEMPIMP <> '')) then
     wSql = wsql||FJOINEMPIMP||' on (impemp.bdcodemp = fn.bdcodemp) ';


   if (TipoFC > 0) then
     wSql = wsql||' where fn.BDCODTIPOFC = '||TipoFC;

   -- Folha complementar tomador
   wsql = wsql||' union all ';

   wsql = wsql||' select ';

   if (Fpuxafiliais = 0) then
      wsql = wsql||' impemp.bdempimp bdcodemp, ft.bdcodemp bdcodempcol,';
   else
      wsql = wsql||' ft.bdcodemp bdcodemp, ft.bdcodemp bdcodempcol,';

   wsql = wsql||' ft.bdreffn, ft.bdrefcomp, ft.bdcodcentro,';
   wsql = wsql||' ft.bdcodtpcc,  coalesce(ft.bdinssfn,0) bdinssfn, coalesce(ft.bdinssfefolfn,0) bdinssfefolf,';
   wsql = wsql||' coalesce(ft.bdinss13fn,0) bdinss13ft,  coalesce(ft.bdbinssfn,0) bdbinssfn,';
   wsql = wsql||' coalesce(ft.bdbinssfefolfn,0) bdbinssfefolfn, coalesce(ft.bdbinss13fn,0) bdbinss13ft,';
   wsql = wsql||' coalesce(ft.bdbratapofn,0) bdbratapofn, coalesce(ft.bdbratapofefn,0) bdbratapofefn, coalesce(ft.bdbratapo13fn,0) bdbratapo13ft,';
   wsql = wsql||' coalesce(ft.bdsalfamfn,0) salfam, coalesce(ft.bdsalmatempfn,0) salMaternidade, 0 valOutentidade,';
   wsql = wsql||' toma.bdcodtpcc bdcodtomador, ft.bdcodcol, null bdcodter, FT.BDBINSSMVFn BDBINSSMVFN, ft.BDBINSSMV13Fn BDBINSSMV13FN, ft.bdgpssefip,';
   wsql = wsql||' ft.bdvalindevido, ft.bdvalindevidosf, ';
   wsql = wsql||' coalesce(toma.BDTIPO, cc.BDTIPO, -1) BDTIPO_TPCC, ';
   wsql = wsql||' coalesce(toma.bdtipotom, 1) bdtipotom,';
   wsql = wsql||' coalesce(ft.BDBINSS13INDFN, 0) BDBINSS13INDFN, ';
   wsql = wsql||' toma.BDCNPJTOM, toma.BDNOMETOM, FT.BDBASERAT, FT.BDBASEINSS, FT.BDBASEINSS13 ';
   wsql = wsql||' , FT.BDCODTIPOFC, case when coalesce(FT.BDCODTIPOFC, 0) > 1 then FT.BDREFCOMP else FT.BDREFFN end BDREFPAGTC, FT.BDBASEPIS, FT.BDBASEPIS13  ';
   wsql = wsql||' from sp_vrhf_dados_inss_ftc('||wEmp||', '||wCol||', '||FAnoMes||', '||Fanomespag||',';

   if (prGPSSEFIP = 0) then
      wsql = wsql|| '1';
   else
      wsql = wsql|| '0';

   if (Fpuxafiliais = 0) then
      wsql = wsql|| ', 1';
   else
      wsql = wsql|| ', 0';

   wsql = wsql|| ', '||FAnoMesFim;

   if(PRCOMPLEESOCIAL = 1) then
       wSql = wsql||', 1';

   wsql = wsql||') ft';

   if (fjoinfiltrocol <> '') then
      begin
--        wsql = wsql||' '||replace(upper(fjoinfiltrocol),'FN.BDCODCOL','FT.BDCODCOL');
        wsql = wsql||' '||trim(replace(upper(fjoinfiltrocol),'COLCON.','FT.'));
      end

   if ((Fpuxafiliais = 0) AND (fjoinempimp <> '')) then
      begin
        wsql = wsql||' '||fjoinempimp||' on (impemp.bdcodemp = ft.bdcodemp) ';
      end

   wsql = wsql||' left outer join VRHF_SP_TIPO_TOMADOR_GPS(ft.bdcodtpcc,ft.bdcodcentro,ft.bdreffn) toma on (toma.bdcodcencus = ft.bdcodtpcc and toma.bdcodcentro = ft.bdcodcentro)';
   wsql = wsql||' left outer join CENTROS_TPCC cc on (cc.BDCODCENTRO = ft.BDCODCENTRO and cc.bdcodtpcc = ft.BDCODTPCC) ';

   if (TipoFC > 0) then
      begin
         wsql = wsql||' where ft.BDCODTIPOFC = ' ||TipoFC;
      end

   wsql = wsql||') FN ';

   if (FJOINFILTROSITCOL <> '') then
      wsql = wsql||' '||FJOINFILTROSITCOL;

   wsql = wsql||' left outer join VW_VRH_EMP_TCOLCON_VINC X on (x.bdcodemp = fn.bdcodempcol and x.bdcodcol = fn.bdcodcol) '||
            ' join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) ';

   if (FCodCla <> '') then
      wsql = wsql||'and ('||FCodCla||')';


   wsql = wsql||' order by fn.bdcodemp, fn.BDCODTIPOFC, fn.bdreffn, fn.bdrefpag';

   --Inicialização de variáveis
   WEMPMATRIZ        = 0;
   bdbasefun13rfn    = 0;
   bdbaseratapoferfc = 0;
   BDBASERATAPO13RFC = 0;
   bdbaseratapofc    = 0;
   BDTIPO_TPCC       = 0;
   BDSIMPLESGPS      = 0;
   BDCODFPAS         = 0;
   WEMPREF = '';
   WCCREF = '';

   for execute statement wsql into
        :bdreffn, :bdrefpag, :bdcodcentro, :bdcodtpcc, :bdinssfn, :bdinssfefolfn, :bdinss13fn, :bdbasefunfc, :bdbasefunferfc, :bdbasefun13rfc, :bdbaseratapofc, :bdbaseratapoferfc, :bdbaseratapo13rfc,
        :salfam, :salmaternidade, :valoutentidade, :bdcodtomador, :bdcodcol, :bdcodter, :bdgrupocla, :bdbinssmvfn, :bdbinssmv13fn, :bdcodemp, :bdrefpagtc, :bdcodtipofc, :bdtipo_tpcc, :bdgpssefip,
        :bdvalindevido, :bdvalindevidosf, :bdtipotom, :bdbinss13indfn, :bdcnpjtom, :bdnometom, :bdbaserat, :bdbaseinss, :bdbaseinss13, :bdbaseratapo13, :bdbaseratapoc13, :bdbasefun13, :bdbasefunc13,
        :BDBASEPIS, :BDBASEPIS13
    do
   begin
     BDCODEMPCOL = bdcodemp;
     BDBASEFUNFN = 0;

     --Atribuição da empresa
     if (WEMPMATRIZ <> coalesce(bdcodemp,0)) then
        begin
          WEMPMATRIZ = bdcodemp;
          select first 1 coalesce(a.bdcodmatriz,a.bdcodemp), a.bdceiemp, a.bdcnpjemp from tempresas a where a.bdcodemp = :bdcodemp into :bdcodmatriz, :wceiemp, :wcnpjemp;

          if (:wceiemp is not null) then
             bdcnpjemp = wceiemp;
          else
             bdcnpjemp = wcnpjemp;
        end

     -- Dados mensais por empresa
     if (wempref <> :bdcodemp||'.'||BDREFPAGTC) then
        begin
          wempref = :bdcodemp||'.'||BDREFPAGTC;

          select first 1 gps.bdSIMPLESGPS, w.BDCODFPAS, gps.bdfunemp, gps.bdempemp, gps.bdautemp, gps.bdperterc,
          case when coalesce(:bdrefpagtc, 0) between 202004 and 202006 then coalesce(w.BDSENAI, 0) * 0.5 else coalesce(w.BDSENAI, 0) end,
          case when coalesce(:bdrefpagtc, 0) between 202004 and 202006 then coalesce(w.BDSESI, 0) * 0.5 else coalesce(w.BDSESI, 0) end,
          case when coalesce(:bdrefpagtc, 0) between 202004 and 202006 then coalesce(w.BDSENAC, 0) * 0.5 else coalesce(w.BDSENAC, 0) end,
          case when coalesce(:bdrefpagtc, 0) between 202004 and 202006 then coalesce(w.BDSESC, 0) * 0.5 else coalesce(w.BDSESC, 0) end,
          case when coalesce(:bdrefpagtc, 0) between 202004 and 202006 then coalesce(w.BDSENAR, 0) * 0.5 else coalesce(w.BDSENAR, 0) end,
          case when coalesce(:bdrefpagtc, 0) between 202004 and 202006 then coalesce(w.BDSEST, 0) * 0.5 else coalesce(w.BDSEST, 0) end,
          case when coalesce(:bdrefpagtc, 0) between 202004 and 202006 then coalesce(w.BDSENAT, 0) * 0.5 else coalesce(w.BDSENAT, 0) end,
          case when coalesce(:bdrefpagtc, 0) between 202004 and 202006 then coalesce(w.BDSESCOOP, 0) * 0.5 else coalesce(w.BDSESCOOP, 0) end,
          MP932.bdnaoaplicamp932, w.bdsaledu, w.bdincra, w.bddpc, w.bdfunaero, w.bdsebrae, gps.bdfap, cnae.bdcodcnae, TEMPITEMSATV.bdanexoiv,
          TEMPITEMSATV.bdanexoiii, TEMPITEMSATV.bdanexov, TEMPITEMSATV.bdanexovi, TEMPCADATV.bdcomercio, TEMPCADATV.bdindustria, w.bdatutab, gps.bdccatvconcom,
          gps.bdcodtribrur, gps.bddesontomaemp, empref.bdnomemp, FASEAMENTO.bdopcaoesocial, FASEAMENTO.bdrefinidctfweb, FASEAMENTO.bddatainiperiod,
          DESCFED.bddescenqfed, DESCFED.bdcodenqfed, TEMPSEFIP.bdcatsefipemp, TEMPSEFIP.bdisenfilemp
          from VRHF_BASE_TEMPGPS gps
          LEFT OUTER JOIN VRH_BASE_TFPAS_TERCEIROS w ON (w.bdcodfpasterc = gps.bdcodfpasterc)
          LEFT OUTER JOIN VRHF_BASE_TEMPMP932 MP932 ON (MP932.BDCODEMP = gps.bdcodemp)
          LEFT OUTER JOIN TEMPRESAS_REF EMPREF ON (EMPREF.bdcodemp = GPS.bdcodemp) AND (EMPREF.bdrefemp = GPS.bdrefemp)
          LEFT OUTER JOIN TENQFED TENQ ON (TENQ.bdcodemp = GPS.bdcodemp) and (TENQ.bdrefemp = EMPREF.bdrefemp)
          LEFT OUTER JOIN TCADENQFED DESCFED ON (TENQ.bdcodenqfed = DESCFED.bdcodenqfed)
          LEFT OUTER JOIN TCNAE CNAE ON (CNAE.bdcodcnae = EMPREF.bdcodcnae)
          LEFT OUTER JOIN VRH_ESOCIAL_TFASEAMENTO FASEAMENTO ON (FASEAMENTO.bdcodemp = GPS.bdcodemp)
          LEFT OUTER JOIN VW_VRHF_BASE_TEMPSEFIP TEMPSEFIP ON (TEMPSEFIP.bdcodemp = GPS.bdcodemp)
          LEFT OUTER JOIN VEF_BASE_TEMPITEMSATV TEMPITEMSATV ON (TEMPITEMSATV.bdcodemp = GPS.bdcodemp) AND (TEMPITEMSATV.bdrefemp = GPS.bdrefemp)
          LEFT OUTER JOIN VEF_BASE_TEMPCADATV TEMPCADATV ON (TEMPCADATV.bdcodemp = GPS.bdcodemp) AND (TEMPCADATV.bdrefemp = GPS.bdrefemp)
          where gps.BDCODEMP = :bdcodemp and gps.BDREFEMP <= :BDREFPAGTC order by gps.BDCODEMP desc, gps.BDREFEMP desc
          into :WSIMPLESGPSEMPRESA, :wCODFPASEmp, :wfunemp, :wempemp, :wautemp, :wpertercemp, :wsenai, :wsesi, :wsenac, :wsesc, :wsenar, :wsest, :wsenat, :wsescoop, :wnaoaplicamp932, :wsaleduemp, :wincraemp,
               :wdpcemp, wfunaeroemp, :wsebraeemp, :wfapemp, :wcodcnaeemp, :wanexoivemp, :wanexoiiiemp, :wanexovemp, :wanexoviemp, :wcomercioemp, :windustriaemp, :watutabemp, :wccatvconcom,
               :wcodtribrur, :wdesontomaemp, :wnomeemp, :wopcaoesocial, :wrefinidctfweb, :wdatainiperiod, :wdescenqfed, :wcodenqfed, :wcatsefipemp, :wisenfilemp;

          wtaxacnaeemp = (select first 1 x.bdtaxacnae from TCNAE_REF x where (x.bdcodcnae = :wcodcnaeemp) AND (x.bdrefcnae <= :BDREFPAGTC) order by x.bdrefcnae desc);
        end

     -- Dados mensaisa por Centro de custo/Tomador
     if (WCCREF <> :bdcodemp||'.'||BDREFPAGTC||'.'||coalesce(bdcodcentro,0)||'.'||coalesce(BDCODTOMADOR,0)) then
        begin
          WCCREF = :bdcodemp||'.'||BDREFPAGTC||'.'||coalesce(bdcodcentro,0)||'.'||coalesce(BDCODTOMADOR,0);

          if ((coalesce(BDCODTOMADOR,0) = 0) or (coalesce(bdcodcentro,0) = 0))  then
             begin
               wsimplesgpscc = -1;
               wcodfpascc = -1;
               wdadpertom = -1;
               wcoltomcc  = -1;
               wemptomcc  = -1;
               wauttomcc  = -1;
             end
          else
             begin
               select first 1 gps.bdsimplesgpstom, w.BDCODFPAS, gps.bddadpertom, gps.bdcoltom, gps.bdemptom, gps.bdauttom,
               case when coalesce(:bdrefpagtc, 0) between 202004 and 202006 then coalesce(w.BDSENAI, 0) * 0.5 else w.BDSENAI end,
               case when coalesce(:bdrefpagtc, 0) between 202004 and 202006 then coalesce(w.BDSESI, 0) * 0.5 else w.BDSESI end,
               case when coalesce(:bdrefpagtc, 0) between 202004 and 202006 then coalesce(w.BDSENAC, 0) * 0.5 else w.BDSENAC end,
               case when coalesce(:bdrefpagtc, 0) between 202004 and 202006 then coalesce(w.BDSESC, 0) * 0.5 else w.BDSESC end,
               case when coalesce(:bdrefpagtc, 0) between 202004 and 202006 then coalesce(w.BDSENAR, 0) * 0.5 else w.BDSENAR end,
               case when coalesce(:bdrefpagtc, 0) between 202004 and 202006 then coalesce(w.BDSEST, 0) * 0.5 else w.BDSEST end,
               case when coalesce(:bdrefpagtc, 0) between 202004 and 202006 then coalesce(w.BDSENAT, 0) * 0.5 else w.BDSENAT end,
               case when coalesce(:bdrefpagtc, 0) between 202004 and 202006 then coalesce(w.BDSESCOOP, 0) * 0.5 else w.BDSESCOOP end,
               w.bdperterc, w.bdsaledu, w.bdincra, w.bddpc, w.bdfunaero, w.bdsebrae, cnae.bdcodcnae, gps.bdfaptom, gps.bdanexoiv, gps.bdanexoiii,
               gps.bdanexov, gps.bdanexovi, gps.bdcomercio, gps.bdindustria, gps.bddesonobra, w.bdatutab
               from vrh_base_tcustom_gps gps
               LEFT OUTER JOIN VRH_BASE_TFPAS_TERCEIROS w ON (w.bdcodfpasterc = gps.bdcodfpasterc)
               LEFT OUTER JOIN TCNAE CNAE ON (CNAE.bdcodcnae = GPS.bdcodcnae)
               where gps.bdcodcentro = :bdcodcentro and gps.bdcodtpcc = :BDCODTOMADOR and
--                     gps.bdrefcusto <= :BDREFPAGTC
                     gps.bdrefcusto <= Coalesce((select first 1 bdrefcusto from vrh_base_tcustom_gps
                                                 where bdcodcentro = gps.bdcodcentro and
                                                       bdcodtpcc = gps.bdcodtpcc and
                                                       bdrefcusto <= :BDREFPAGTC
                                                       order by bdrefcusto desc),
                                                 (select min(bdrefcusto) from vrh_base_tcustom_gps
                                                 where bdcodcentro = gps.bdcodcentro and
                                                       bdcodtpcc = gps.bdcodtpcc))
               order by gps.bdrefcusto desc
               into :wsimplesgpscc, :wcodfpascc, :wdadpertom, :wcoltomcc, :wemptomcc, :wauttomcc, :wsenaicc, :wsesicc, :wsenaccc, :wsesccc, :wsenarcc, :wsestcc,
                    :wsenatcc, :wsescoopcc, :wperterccc, :wsaleducc, :wincracc, :wdpccc, :wfunaerocc, :wsebraecc, :wcodcnaecc, :wfaptomcc, :wanexoivcc, :wanexoiiicc,
                    :wanexovcc, :wanexovicc, :wcomerciocc, :windustriacc, :wdesonobra, :watutabcc;

               wtaxacnaecc =  (select first 1 x.bdtaxacnae from TCNAE_REF x where (x.bdcodcnae = :wcodcnaecc) AND (x.bdrefcnae <= :BDREFPAGTC) order by x.bdrefcnae desc);
             end
        end

     wcolref = '';

     --Dados mensais colaborador
     if (wcolref <> :bdcodcol||'.'||:bdcodemp||'.'||BDREFPAGTC) then
        begin
           wcolref = :bdcodcol||'.'||:bdcodemp||'.'||BDREFPAGTC;

           select first 1 colfgts.bdpercratcol, colfgts.bdpercdescfpascol, colfgts.bdcategoriaesocial from VRHF_EMP_TCOLCON_FGTSGPS colfgts
           where (colfgts.bdcodemp = :bdcodemp) and (colfgts.bdcodcol = :bdcodcol) and (colfgts.bdrefcol <= :BDREFPAGTC)
           order by colfgts.bdrefcol desc
           into :wpercratcol, :wpercdescfpascol, :wcategoriaesocial;
        end


     bdpercratcol       = wpercratcol;
     bdpercdescfpascol  = wpercdescfpascol;
     bdcategoriaesocial = wcategoriaesocial;

     -- Utiliza dados da empresa
     if (wdadpertom not in (1,4,6)) then
        begin
          bdsimplesgps    = wsimplesgpsempresa;
          bdcodfpas       = wcodfpasemp;
          BDANEXOIV       = wanexoivemp;
          bdanexoiii      = wanexoiiiemp;
          bdanexov        = wanexovemp;
          bdanexovi       = wanexoviemp;
          bdcomercio      = wcomercioemp;
          bdindustria     = windustriaemp;
          bdccatvconcom   = wccatvconcom;
          bdcodtribrur    = wcodtribrur;
          bddesontomaemp  = wdesontomaemp;
          bdnomemp        = wnomeemp;
          bdopcaoesocial  = wopcaoesocial;
          bdrefinidctfweb = wrefinidctfweb;
          bddatainiperiod = wdatainiperiod;
          bddescenqfed    = wdescenqfed;
          bdcodenqfed     = wcodenqfed;
          bdcatsefipemp   = wcatsefipemp;
          bdisenfilemp    = wisenfilemp;
        end
     else -- Utiliza dados do centro de custo
        begin
          bdsimplesgps = wsimplesgpscc;
          bdcodfpas = wcodfpascc;
          BDANEXOIV    = wanexoivcc;
          bdanexoiii   = wanexoiiicc;
          bdanexov     = wanexovcc;
          bdanexovi    = wanexovicc;
          bdcomercio   = wcomerciocc;
          bdindustria  = windustriacc;
        end

     -- Utiliza dados da empresa
     if ((wdadpertom not in (1,4,6)) or (BDTIPO_TPCC = 0)) then
        begin
          bdpercfun    = wfunemp;
          BDPERCPRO    = wempemp;
          BDPERCAUT    = wautemp;
          BDPERCFPAS   = wpertercemp;
          BDPERCRATCAD = wtaxacnaeemp;
          BDPERCFAPCAD = wfapemp;
          bdsaledu     = wsaleduemp;
          bdincra      = wincraemp;
          bdsenai      = wsenai;
          BDSESI       = wsesi;
          bdsenac      = wsenac;
          bdsesc       = wsesc;
          bdsebrae     = wsebraeemp;
          bddpc        = wdpcemp;
          bdfunaero    = wfunaeroemp;
          bdsenar      = wsenar;
          bdsest       = wsest;
          bdsenat      = wsenat;
          bdsescoop    = wsescoop;

          if ((watutabemp = '') or (watutabemp = null)) then
             bdatutab = 'FALSE';
          else
             bdatutab = watutabemp;


          select bdvalor from truncar(coalesce(:wtaxacnaeemp,0)*coalesce(:wfapemp,0),4) into :BDPERCRAT;
        end
     else -- Utiliza dados do centro de custo
        begin
          bdpercfun    = wcoltomcc;
          BDPERCPRO    = wemptomcc;
          BDPERCAUT    = wauttomcc;
          BDPERCRATCAD = wtaxacnaecc;
          BDPERCFAPCAD = wfaptomcc;
          bdsaledu     = wsaleducc;
          bdincra      = wincracc;
          bdsebrae     = wsebraecc;
          bddpc        = wdpccc;
          bdfunaero    = wfunaerocc;

          select bdvalor from truncar(coalesce(:wtaxacnaecc,0)*(coalesce(:wfaptomcc,0)),4) INTO :BDPERCRAT;

          if ((wdesonobra = '') or (wdesonobra = null))  then
             bddesonobra = 'FALSE';
          else
             bddesonobra = wdesonobra;

          if ((watutabcc = '') or (watutabcc = null))  then
             bdatutab = 'FALSE';
          else
             bdatutab = watutabcc;

          if ((bdrefpagtc in (202004, 202005, 202006)) and (upper(coalesce(wnaoaplicamp932, 'FALSE')) = 'TRUE')) then
             begin
               BDPERCFPAS = (wsaleducc + wincracc + (wsenaicc * 2) + (wsesicc * 2) + (wsenaccc * 2) + (wsesccc * 2) + wsebraecc + wdpccc + wfunaerocc + (wsenarcc * 2) + (wsestcc * 2) + (wsenatcc * 2) + (wsescoopcc * 2));
               bdsenai    = coalesce(wsenaicc, 0) * 2;
               bdsesi     = coalesce(wsesicc, 0) * 2;
               bdsenac    = coalesce(wsenaccc, 0) * 2;
               bdsesc     = coalesce(wsesccc, 0) * 2;
               bdsenar    = coalesce(wsenarcc, 0) * 2;
               bdsest     = coalesce(wsestcc, 0) * 2;
               bdsenat    = coalesce(wsenatcc, 0) * 2;
               bdsescoop  = coalesce(wsescoopcc, 0) * 2;
             end
          else
            begin
               BDPERCFPAS = coalesce(wperterccc, 0);
               bdsenai    = coalesce(wsenaicc, 0);
               bdsesi     = coalesce(wsesicc, 0);
               bdsenac    = coalesce(wsenaccc, 0);
               bdsesc     = coalesce(wsesccc, 0);
               bdsenar    = coalesce(wsenarcc, 0);
               bdsest     = coalesce(wsestcc, 0);
               bdsenat    = coalesce(wsenatcc, 0);
               bdsescoop  = coalesce(wsescoopcc, 0);
            end

        end

     suspend;
   end

  ---suspend;
end^

create or alter procedure SP_DADOS_REL_QTDFOLHAS (
    PREMPRESA varchar(20000),
    PRREFINICIAL varchar(15),
    PRREFFINAL varchar(15),
    PREMITIREMPSEMFOLHAS integer,
    PRTIPOCALCULO integer,
    PRTIPODEFOLHAAVULSA integer = -1,
    PRFILTROSITUACAO integer = -1,
    PRCENTROCUSTO varchar(20000) = '' /* COLLATE WIN1252 - default */ ,
    PRCLASSECOLABORADOR varchar(20000) = '' /* COLLATE WIN1252 - default */ ,
    PRSINDICATOCOLABORADOR varchar(20000) = '' /* COLLATE WIN1252 - default */ ,
    PRFUNCAOCOLABORADOR varchar(20000) = '' /* COLLATE WIN1252 - default */ )
returns (
    BDCODEMPRESA integer,
    BDNOMEEMPRESA varchar(1000),
    BDCNPJEMPRESA varchar(30),
    BD01 integer,
    BD02 integer,
    BD03 integer,
    BD04 integer,
    BD05 integer,
    BD06 integer,
    BD07 integer,
    BD08 integer,
    BD09 integer,
    BD10 integer,
    BD11 integer,
    BD12 integer,
    BDREF01 integer,
    BDREF02 integer,
    BDREF03 integer,
    BDREF04 integer,
    BDREF05 integer,
    BDREF06 integer,
    BDREF07 integer,
    BDREF08 integer,
    BDREF09 integer,
    BDREF10 integer,
    BDREF11 integer,
    BDREF12 integer,
    BD01COL integer,
    BD02COL integer,
    BD03COL integer,
    BD04COL integer,
    BD05COL integer,
    BD06COL integer,
    BD07COL integer,
    BD08COL integer,
    BD09COL integer,
    BD10COL integer,
    BD11COL integer,
    BD12COL integer,
    BD01INTER integer,
    BD02INTER integer,
    BD03INTER integer,
    BD04INTER integer,
    BD05INTER integer,
    BD06INTER integer,
    BD07INTER integer,
    BD08INTER integer,
    BD09INTER integer,
    BD10INTER integer,
    BD11INTER integer,
    BD12INTER integer,
    BD01CONTR integer,
    BD02CONTR integer,
    BD03CONTR integer,
    BD04CONTR integer,
    BD05CONTR integer,
    BD06CONTR integer,
    BD07CONTR integer,
    BD08CONTR integer,
    BD09CONTR integer,
    BD10CONTR integer,
    BD11CONTR integer,
    BD12CONTR integer,
    BD01TER integer,
    BD02TER integer,
    BD03TER integer,
    BD04TER integer,
    BD05TER integer,
    BD06TER integer,
    BD07TER integer,
    BD08TER integer,
    BD09TER integer,
    BD10TER integer,
    BD11TER integer,
    BD12TER integer)
as
declare variable WREFERENCIAATUAL integer;
declare variable WDATAINICIAL date;
declare variable WDATAFINAL date;
declare variable WSQL varchar(30000);
declare variable WREFERENCIACALCULO integer;
declare variable WVALORLIQUIDOCALCULO numeric(18,6);
declare variable WSQLEMPRESAS varchar(30000);
declare variable WCODIGOEMPRESA integer;
declare variable WCNPJEMPRESA varchar(30);
declare variable WNOMEEMPRESA varchar(100);
declare variable WMESDOCALCULO integer;
declare variable WANODOCALCULO integer;
declare variable WANOATUAL integer;
declare variable W01 integer;
declare variable W02 integer;
declare variable W03 integer;
declare variable W04 integer;
declare variable W05 integer;
declare variable W06 integer;
declare variable W07 integer;
declare variable W08 integer;
declare variable W09 integer;
declare variable W10 integer;
declare variable W11 integer;
declare variable W12 integer;
declare variable WCONTRCOL integer;
declare variable WINTER integer;
declare variable WCODCOL integer;
declare variable WCODTER integer;
declare variable WCODCOLATUAL integer;
declare variable WCODTERATUAL integer;
declare variable WREFINICIAL integer;
declare variable WREFFINAL integer;
declare variable WSITUACAOCOL varchar(20000);
declare variable WCENTROCUSTO varchar(20000);
declare variable WCLASSECOLABORADOR varchar(20000);
declare variable WSINDICATOCOLABORADOR varchar(20000);
declare variable WFUNCAOCOLABORADOR varchar(20000);
begin
  /* SP responsável por retornar a quantidade de cálculos na referência para o relatório "QUANTIDADE DE FOLHAS" */

   --Inicialização de outputs da SP
   BDCODEMPRESA  = 0;
   BDNOMEEMPRESA = '';
   BDCNPJEMPRESA = '';

   --Quantidade de cálculos somados de cada coluna
   BD01          = 0;
   BD02          = 0;
   BD03          = 0;
   BD04          = 0;
   BD05          = 0;
   BD06          = 0;
   BD07          = 0;
   BD08          = 0;
   BD09          = 0;
   BD10          = 0;
   BD11          = 0;
   BD12          = 0;

   --Referência de cada coluna
   BDREF01       = 0;
   BDREF02       = 0;
   BDREF03       = 0;
   BDREF04       = 0;
   BDREF05       = 0;
   BDREF06       = 0;
   BDREF07       = 0;
   BDREF08       = 0;
   BDREF09       = 0;
   BDREF10       = 0;
   BDREF11       = 0;
   BDREF12       = 0;


   BD01Col       = 0;
   BD02Col       = 0;
   BD03Col       = 0;
   BD04Col       = 0;
   BD05Col       = 0;
   BD06Col       = 0;
   BD07Col       = 0;
   BD08Col       = 0;
   BD09Col       = 0;
   BD10Col       = 0;
   BD11Col       = 0;
   BD12Col       = 0;

   BD01Inter     = 0;
   BD02Inter     = 0;
   BD03Inter     = 0;
   BD04Inter     = 0;
   BD05Inter     = 0;
   BD06Inter     = 0;
   BD07Inter     = 0;
   BD08Inter     = 0;
   BD09Inter     = 0;
   BD10Inter     = 0;
   BD11Inter     = 0;
   BD12Inter     = 0;

   BD01Contr     = 0;
   BD02Contr     = 0;
   BD03Contr     = 0;
   BD04Contr     = 0;
   BD05Contr     = 0;
   BD06Contr     = 0;
   BD07Contr     = 0;
   BD08Contr     = 0;
   BD09Contr     = 0;
   BD10Contr     = 0;
   BD11Contr     = 0;
   BD12Contr     = 0;

   BD01Ter       = 0;
   BD02Ter       = 0;
   BD03Ter       = 0;
   BD04Ter       = 0;
   BD05Ter       = 0;
   BD06Ter       = 0;
   BD07Ter       = 0;
   BD08Ter       = 0;
   BD09Ter       = 0;
   BD10Ter       = 0;
   BD11Ter       = 0;
   BD12Ter       = 0;

   --Inicialização de variáveis
   WREFERENCIAATUAL     = 0;
   WREFERENCIACALCULO   = 0;
   WVALORLIQUIDOCALCULO = 0;
   WSQL                 = '';
   WANODOCALCULO        = 0;
   WMESDOCALCULO        = 0;
   WANOATUAL            = 0;
   W01                  = 0;
   W02                  = 0;
   W03                  = 0;
   W04                  = 0;
   W05                  = 0;
   W06                  = 0;
   W07                  = 0;
   W08                  = 0;
   W09                  = 0;
   W10                  = 0;
   W11                  = 0;
   W12                  = 0;
   wsituacaocol         = '';

   wContrCol            = -1;
   wInter               = -1;
   wCodCol              = 0;
   wCodTer              = 0;
   wCodColAtual         = 0;
   wCodTerAtual         = 0;

   -- Laço para separar as referências e consultar os cálculos
   WDATAINICIAL = CAST(PRREFINICIAL as DATE);
   WDATAFINAL   = CAST(PRREFFINAL   as DATE);
 
   WREFINICIAL = extract(YEAR from WDATAINICIAL)||LPAD(extract(MONTH from WDATAINICIAL), 2, '0');
   WREFFINAL   = extract(YEAR from WDATAFINAL)||LPAD(extract(MONTH from WDATAFINAL), 2, '0');

  execute procedure sp_seta_competencia(WREFINICIAL);

   WHILE (WREFINICIAL <= WREFFINAL) DO
   BEGIN
      WMESDOCALCULO = MOD(WREFINICIAL, 100);
      WANODOCALCULO = WREFINICIAL / 100;

      -- Quando chegar ao mês 12 faz a troca do ano
      if (WMESDOCALCULO > 12) then
         begin
           WMESDOCALCULO = 1;
           WANODOCALCULO = WANODOCALCULO + 1;
           WREFINICIAL   = (WANODOCALCULO * 100) + WMESDOCALCULO;
         end

      if (w01 = 0) then
        w01 = (WANODOCALCULO * 100) + WMESDOCALCULO;
      else if (w02 = 0) then
        w02 = (WANODOCALCULO * 100) + WMESDOCALCULO;
      else if (w03 = 0) then
        w03 = (WANODOCALCULO * 100) + WMESDOCALCULO;
      else if (w04 = 0) then
        w04 = (WANODOCALCULO * 100) + WMESDOCALCULO;
      else if (w05 = 0) then
        w05 = (WANODOCALCULO * 100) + WMESDOCALCULO;
      else if (w06 = 0) then
        w06 = (WANODOCALCULO * 100) + WMESDOCALCULO;
      else if (w07 = 0) then
        w07 = (WANODOCALCULO * 100) + WMESDOCALCULO;
      else if (w08 = 0) then
        w08 = (WANODOCALCULO * 100) + WMESDOCALCULO;
      else if (w09 = 0) then
        w09 = (WANODOCALCULO * 100) + WMESDOCALCULO;
      else if (w10 = 0) then
        w10 = (WANODOCALCULO * 100) + WMESDOCALCULO;
      else if (w11 = 0) then
        w11 = (WANODOCALCULO * 100) + WMESDOCALCULO;
      else if (w12 = 0) then
        w12 = (WANODOCALCULO * 100) + WMESDOCALCULO;

      WREFINICIAL = WREFINICIAL +1;
   END

   WREFINICIAL = extract(YEAR from WDATAINICIAL)||LPAD(extract(MONTH from WDATAINICIAL), 2, '0');
   WREFFINAL   = extract(YEAR from WDATAFINAL)||LPAD(extract(MONTH from WDATAFINAL), 2, '0');

   wsqlempresas = 'select E.BDCODEMP, E.BDCNPJEMP, F.BDNOMEMP '||
                  'from TEMPRESAS E '||
                  'left join TEMPRESAS_REF F on (F.BDCODEMP = E.BDCODEMP) and '||
                                                '(F.BDREFEMP = (select first 1 max(X.BDREFEMP) '||
                                                               'from TEMPRESAS_REF X '||
                                                               'where X.BDCODEMP = E.BDCODEMP)) ';

   if (PREMPRESA <> '') then
      wsqlempresas =  wsqlempresas || ' where '||PREMPRESA;

   for execute statement wsqlempresas into :WCODIGOEMPRESA, :WCNPJEMPRESA, :WNOMEEMPRESA do
    begin
      BDCODEMPRESA  = WCODIGOEMPRESA;
      BDNOMEEMPRESA = WNOMEEMPRESA;
      BDCNPJEMPRESA = WCNPJEMPRESA;

      BD01          = 0;
      BD02          = 0;
      BD03          = 0;
      BD04          = 0;
      BD05          = 0;
      BD06          = 0;
      BD07          = 0;
      BD08          = 0;
      BD09          = 0;
      BD10          = 0;
      BD11          = 0;
      BD12          = 0;

      BDREF01       = w01;
      BDREF02       = w02;
      BDREF03       = w03;
      BDREF04       = w04;
      BDREF05       = w05;
      BDREF06       = w06;
      BDREF07       = w07;
      BDREF08       = w08;
      BDREF09       = w09;
      BDREF10       = w10;
      BDREF11       = w11;
      BDREF12       = w12;

      BD01Col       = 0;
      BD02Col       = 0;
      BD03Col       = 0;
      BD04Col       = 0;
      BD05Col       = 0;
      BD06Col       = 0;
      BD07Col       = 0;
      BD08Col       = 0;
      BD09Col       = 0;
      BD10Col       = 0;
      BD11Col       = 0;
      BD12Col       = 0;

      BD01Inter     = 0;
      BD02Inter     = 0;
      BD03Inter     = 0;
      BD04Inter     = 0;
      BD05Inter     = 0;
      BD06Inter     = 0;
      BD07Inter     = 0;
      BD08Inter     = 0;
      BD09Inter     = 0;
      BD10Inter     = 0;
      BD11Inter     = 0;
      BD12Inter     = 0;

      BD01Contr     = 0;
      BD02Contr     = 0;
      BD03Contr     = 0;
      BD04Contr     = 0;
      BD05Contr     = 0;
      BD06Contr     = 0;
      BD07Contr     = 0;
      BD08Contr     = 0;
      BD09Contr     = 0;
      BD10Contr     = 0;
      BD11Contr     = 0;
      BD12Contr     = 0;

      BD01Ter       = 0;
      BD02Ter       = 0;
      BD03Ter       = 0;
      BD04Ter       = 0;
      BD05Ter       = 0;
      BD06Ter       = 0;
      BD07Ter       = 0;
      BD08Ter       = 0;
      BD09Ter       = 0;
      BD10Ter       = 0;
      BD11Ter       = 0;
      BD12Ter       = 0;


      wsituacaocol          = '';
      WCENTROCUSTO          = '';
      WSINDICATOCOLABORADOR = '';
      WCLASSECOLABORADOR    = '';
      WFUNCAOCOLABORADOR    = '';

      --SITUAÇÃO
      if ((PRFILTROSITUACAO <> -1) and (PRFILTROSITUACAO <> 1)) then
        begin
          if (PRFILTROSITUACAO = 0) then
             WSITUACAOCOL = ' join SP_SOMENTE_ATIVOS('''||prrefinicial||''', '''||PRREFFINAL||''', '||WCODIGOEMPRESA||') atv on (atv.bdcodemp = *.bdcodemp) and (atv.bdcodcol = *.bdcodcol) ';
          else
          if (PRFILTROSITUACAO = 2) then
             WSITUACAOCOL = '  join SP_SOMENTE_DEMITIDOS('''||PRREFFINAL||''', '||WCODIGOEMPRESA||') atv on (atv.bdcodemp = *.bdcodemp) and (atv.bdcodcol = *.bdcodcol) ';
          else
          if (PRFILTROSITUACAO = 3) then
             WSITUACAOCOL = ' join SP_SOMENTE_ADMITIDOS_MES('''||prrefinicial||''', '''||PRREFFINAL||''', '||WCODIGOEMPRESA||') atv on (atv.bdcodemp = *.bdcodemp) and (atv.bdcodcol = *.bdcodcol) ';
          else
          if (PRFILTROSITUACAO = 4) then
             WSITUACAOCOL = ' join SP_SOMENTE_DEMITIDOS_MES('''||prrefinicial||''', '''||PRREFFINAL||''', '||WCODIGOEMPRESA||') atv on (atv.bdcodemp = *.bdcodemp) and (atv.bdcodcol = *.bdcodcol) ';
          else
          if (PRFILTROSITUACAO = 5) then
             WSITUACAOCOL = ' join SP_ATIVOS_SEM_DEMITIDOS_MES('''||prrefinicial||''', '''||PRREFFINAL||''', '||WCODIGOEMPRESA||') atv on (atv.bdcodemp = *.bdcodemp) and (atv.bdcodcol = *.bdcodcol) ';
          else
          if (PRFILTROSITUACAO = 5) then
             WSITUACAOCOL = ' join SP_AFASTADOS_MES_INTEIRO('''||prrefinicial||''', '''||PRREFFINAL||''', '||WCODIGOEMPRESA||') atv on (atv.bdcodemp = *.bdcodemp) and (atv.bdcodcol = *.bdcodcol) ';
        end

      -- CENTRO/TOMADOR
      if (PRCENTROCUSTO <> '') then
          WCENTROCUSTO = ' join VRHF_EMP_TPREPFN prepfn on (prepfn.bdcodemp = *.bdcodemp) and (prepfn.bdcodcol = *.bdcodcol) and (prepfn.bdrefentrada = (select first 1 max(I.bdrefentrada) from VRHF_EMP_TPREPFN I where I.bdcodemp = prepfn.bdcodemp and I.bdcodcol = prepfn.bdcodcol)) and '||PRCENTROCUSTO||' ';

      --SINDICATO
      if (PRSINDICATOCOLABORADOR <> '') then
          WSINDICATOCOLABORADOR = ' join VRH_EMP_TCOL_VINC SIND on (SIND.bdcodemp = *.bdcodemp) and (SIND.bdcodcol = *.bdcodcol) and (SIND.bdrefcol = (select first 1 max(I.BDREFCOL) from VRH_EMP_TCOL_VINC I where I.bdcodemp = SIND.bdcodemp and I.bdcodcol = SIND.bdcodcol and I.bdcodsintrab = SIND.bdcodsintrab)) and '||PRSINDICATOCOLABORADOR||' ';

      --CLASSE
      if (PRCLASSECOLABORADOR <> '') then
           WCLASSECOLABORADOR = ' join VRH_EMP_TCOLCON_VINC VINC on (VINC.bdcodemp = *.bdcodemp) and (VINC.bdcodcol = *.bdcodcol) and (VINC.bdrefcol = (select first 1 max(I.bdrefcol) from VRH_EMP_TCOLCON_VINC I where I.bdcodemp = VINC.bdcodemp and I.bdcodcol = VINC.bdcodcol)) and '||PRCLASSECOLABORADOR||' ';

      --FUNÇÃO
      if (PRFUNCAOCOLABORADOR <> '') then
           WFUNCAOCOLABORADOR = ' join VW_VRH_EMP_TCOL_VINCDIA FUNC on (FUNC.bdcodemp = *.bdcodemp) and (FUNC.bdcodcol = *.bdcodcol) and '||PRFUNCAOCOLABORADOR||' ';

      if (prtipocalculo = 0) then   -- Folha normal e tomador | Intermitente e Intermitente tomador
        begin
           wSQL = 'SELECT * FROM (select X.bdreffn, X.bdliquido, V.BDCONTRCOL, 0 BDINTERM, X.bdcodcol, 0 bdcodter '||
                  'from VRHF_EMP_TFOLHANORMAL X '||
                  'LEFT OUTER JOIN VRH_EMP_TCOLCON_VINC V ON X.BDCODEMP = V.BDCODEMP AND X.BDCODCOL = V.BDCODCOL ' ||
                  '             AND V.BDREFCOL = (SELECT FIRST 1 VZ.BDREFCOL FROM VRH_EMP_TCOLCON_VINC VZ ' ||
                  '                                  WHERE VZ.BDCODEMP = X.BDCODEMP AND VZ.BDCODCOL = X.BDCODCOL ORDER BY VZ.BDREFCOL DESC) ' ||
                  replace(wsituacaocol, '*.', 'X.')||
                  replace(WCENTROCUSTO, '*.', 'X.')||
                  replace(WSINDICATOCOLABORADOR, '*.', 'X.')||
                  replace(WCLASSECOLABORADOR, '*.', 'X.')||
                  replace(WFUNCAOCOLABORADOR, '*.', 'X.')||
                  'where X.BDCODEMP = '||WCODIGOEMPRESA||' and '||
                        'X.BDREFFN between '||WREFINICIAL||' and '||WREFFINAL||' '||
                  'union all '||
                  'select Y.bdreftomador, SUM(Y.bdliquido), V.BDCONTRCOL, 0 BDINTERM, Y.bdcodcol, 0 bdcodter ' ||
                  'from VRHF_EMP_TFOLHATOMADOR Y '||
                  'LEFT OUTER JOIN VRH_EMP_TCOLCON_VINC V ON Y.BDCODEMP = V.BDCODEMP AND Y.BDCODCOL = V.BDCODCOL ' ||
                  '             AND V.BDREFCOL = (SELECT FIRST 1 VZ.BDREFCOL FROM VRH_EMP_TCOLCON_VINC VZ ' ||
                  '                                  WHERE VZ.BDCODEMP = Y.BDCODEMP AND VZ.BDCODCOL = Y.BDCODCOL ORDER BY VZ.BDREFCOL DESC) ' ||
                  replace(wsituacaocol, '*.', 'Y.')||
                  replace(WCENTROCUSTO, '*.', 'Y.')||
                  replace(WSINDICATOCOLABORADOR, '*.', 'y.')||
                  replace(WCLASSECOLABORADOR, '*.', 'Y.')||
                  replace(WFUNCAOCOLABORADOR, '*.', 'Y.')||
                  'where Y.BDCODEMP = '||WCODIGOEMPRESA||' and '||
                        'Y.BDREFTOMADOR between '||WREFINICIAL||' and '||WREFFINAL||' '||
                  'group by y.bdcodcol, y.bdreftomador, V.BDCONTRCOL, Y.bdcodcol '||
                  'union all '||
                  'select Z.BDREFFN, Z.BDLIQUIDO, 0 BDCONTRCOL, 1 BDINTERM, Z.bdcodcol, 0 bdcodter  ' ||
                  'from VRHF_EMP_TFOLHAINT Z '||
                  replace(wsituacaocol, '*.', 'Z.')||
                  replace(WCENTROCUSTO, '*.', 'Z.')||
                  replace(WSINDICATOCOLABORADOR, '*.', 'z.')||
                  replace(WCLASSECOLABORADOR, '*.', 'Z.')||
                  replace(WFUNCAOCOLABORADOR, '*.', 'Z.')||
                  'where Z.BDCODEMP = '||WCODIGOEMPRESA||' and '||
                        'Z.BDREFFN between '||WREFINICIAL||' and '||WREFFINAL||' '||
                  'union all '||
                  'select A.BDREFTOMADOR as BDREFFN, SUM(A.BDLIQUIDO), 0 BDCONTRCOL, 1 BDINTERM, A.bdcodcol, 0 bdcodter ' ||
                  'from VRHF_EMP_TFOLHATOMINT A '||
                  replace(wsituacaocol, '*.', 'A.')||
                  replace(WCENTROCUSTO, '*.', 'A.')||
                  replace(WSINDICATOCOLABORADOR, '*.', 'A.')||
                  replace(WCLASSECOLABORADOR, '*.', 'A.')||
                  replace(WFUNCAOCOLABORADOR, '*.', 'A.')||
                  'where A.BDCODEMP = '||WCODIGOEMPRESA||' and '||
                        'A.BDREFTOMADOR between '||WREFINICIAL||' and '||WREFFINAL||' '||
                  'group by a.bdreftomador, a.bdcodcontti, A.bdcodcol ' ||
                  'union all '||
                  'select A.BDREFSERV as BDREFFN, A.BDVALORSERV, 2 BDCONTRCOL, 0 BDINTERM, 0 bdcodcol, A.bdcodter ' ||
                  'from VRH_BASE_TSERVTERC A '||
                  'where A.BDCODEMP = '||WCODIGOEMPRESA||' and '||
                        'A.BDREFSERV between '||WREFINICIAL||' and '||WREFFINAL||' '||
                  ') order by 1, 3, 4, 5, 6 ';
        end
      else if (prtipocalculo = 1) then -- Complementar normal e tomador
        begin
           wSQL = 'select Z.bdrefcomp, SUM(Z.bdliquido), V.BDCONTRCOL, 0 BDINTERM, Z.bdcodcol, 0 bdcodter ' ||
                  'from VRHF_EMP_TFOLHACOMP Z '||
                  'LEFT OUTER JOIN VRH_EMP_TCOLCON_VINC V ON Z.BDCODEMP = V.BDCODEMP AND Z.BDCODCOL = V.BDCODCOL ' ||
                  '             AND V.BDREFCOL = (SELECT FIRST 1 VZ.BDREFCOL FROM VRH_EMP_TCOLCON_VINC VZ ' ||
                  '                                  WHERE VZ.BDCODEMP = Z.BDCODEMP AND VZ.BDCODCOL = Z.BDCODCOL ORDER BY VZ.BDREFCOL DESC) ' ||
                  replace(wsituacaocol, '*.', 'Z.')||
                  replace(WCENTROCUSTO, '*.', 'Z.')||
                  replace(WSINDICATOCOLABORADOR, '*.', 'Z.')||
                  replace(WCLASSECOLABORADOR, '*.', 'Z.')||
                  replace(WFUNCAOCOLABORADOR, '*.', 'Z.')||
                  'where Z.BDCODEMP = '||WCODIGOEMPRESA||' and '||
                        'Z.BDREFCOMP between '||WREFINICIAL||' and '||WREFFINAL||' '||
                  'Group by Z.bdcodemp, Z.bdreffn, Z.bdrefcomp, V.BDCONTRCOL, Z.bdcodcol '||
                  'union all '||
                  'select A.bdrefcomp, SUM(A.bdliquido), V.BDCONTRCOL, 0 BDINTERM, A.bdcodcol, 0 bdcodter '||
                  'from VRHF_EMP_TFOLTOMCOMP A '||
                  'LEFT OUTER JOIN VRH_EMP_TCOLCON_VINC V ON A.BDCODEMP = V.BDCODEMP AND A.BDCODCOL = V.BDCODCOL ' ||
                  '             AND V.BDREFCOL = (SELECT FIRST 1 VZ.BDREFCOL FROM VRH_EMP_TCOLCON_VINC VZ ' ||
                  '                                  WHERE VZ.BDCODEMP = A.BDCODEMP AND VZ.BDCODCOL = A.BDCODCOL ORDER BY VZ.BDREFCOL DESC) ' ||
                  replace(wsituacaocol, '*.', 'A.')||
                  replace(WCENTROCUSTO, '*.', 'A.')||
                  replace(WSINDICATOCOLABORADOR, '*.', 'A.')||
                  replace(WCLASSECOLABORADOR, '*.', 'A.')||
                  replace(WFUNCAOCOLABORADOR, '*.', 'A.')||
                  'where A.BDCODEMP = '||WCODIGOEMPRESA||' and '||
                        'A.BDREFCOMP between '||WREFINICIAL||' and '||WREFFINAL||' '||
                  'Group by A.bdcodemp, A.bdreftomador, A.bdrefcomp, V.BDCONTRCOL, A.bdcodcol '||
                  'order by 1, 3, 4, 5, 6 ';
        end
      else if (prtipocalculo = 2) then -- Férias
        begin
           wSQL = 'select F.bdrefpagfe, F.bdliquido, V.BDCONTRCOL, 0 BDINTERM, F.bdcodcol, 0 bdcodter ' ||
                  'from VRH_EMP_TFERIAS F '||
                  'LEFT OUTER JOIN VRH_EMP_TCOLCON_VINC V ON F.BDCODEMP = V.BDCODEMP AND F.BDCODCOL = V.BDCODCOL ' ||
                  '             AND V.BDREFCOL = (SELECT FIRST 1 VZ.BDREFCOL FROM VRH_EMP_TCOLCON_VINC VZ '  ||
                  '                                  WHERE VZ.BDCODEMP = F.BDCODEMP AND VZ.BDCODCOL = F.BDCODCOL ORDER BY VZ.BDREFCOL DESC) ' ||
                  replace(wsituacaocol, '*.', 'F.')||
                  replace(WCENTROCUSTO, '*.', 'F.')||
                  replace(WSINDICATOCOLABORADOR, '*.', 'F.')||
                  replace(WCLASSECOLABORADOR, '*.', 'F.')||
                  replace(WFUNCAOCOLABORADOR, '*.', 'F.')||
                  'where F.BDCODEMP = '||WCODIGOEMPRESA||' and '||
                        'F.BDREFPAGFE between '||WREFINICIAL||' and '||WREFFINAL||
                  ' order by F.bdrefpagfe, 3, 4, 5, 6 ';
        end
      else if (prtipocalculo = 3) then -- Décimo terceiro
        begin
           wSQL = 'select D.bdref13, D.BDLIQUIDO, V.BDCONTRCOL, 0 BDINTERM, D.bdcodcol, 0 bdcodter ' ||
                  'from VRHF_EMP_T13SAL D '||
                  'LEFT OUTER JOIN VRH_EMP_TCOLCON_VINC V ON D.BDCODEMP = V.BDCODEMP AND D.BDCODCOL = V.BDCODCOL ' ||
                  '             AND V.BDREFCOL = (SELECT FIRST 1 VZ.BDREFCOL FROM VRH_EMP_TCOLCON_VINC VZ '  ||
                  '                                  WHERE VZ.BDCODEMP = D.BDCODEMP AND VZ.BDCODCOL = D.BDCODCOL ORDER BY VZ.BDREFCOL DESC) ' ||
                  replace(wsituacaocol, '*.', 'D.')||
                  replace(WCENTROCUSTO, '*.', 'D.')||
                  replace(WSINDICATOCOLABORADOR, '*.', 'D.')||
                  replace(WCLASSECOLABORADOR, '*.', 'D.')||
                  replace(WFUNCAOCOLABORADOR, '*.', 'D.')||
                  'where D.BDCODEMP = '||WCODIGOEMPRESA||' and '||
                        'D.BDREF13 between '||WREFINICIAL||' and '||WREFFINAL||
                  ' order by D.bdref13, 3, 4, 5, 6 ';
        end
      else if (prtipocalculo = 4) then -- Adiantamento décimo terceiro
        begin
           wSQL = 'select AD13.BDREFA13, AD13.BDLIQUIDO, V.BDCONTRCOL, 0 BDINTERM, AD13.bdcodcol, 0 bdcodter ' ||
                  'from VRHF_EMP_TA13SAL AD13 '||
                  'LEFT OUTER JOIN VRH_EMP_TCOLCON_VINC V ON AD13.BDCODEMP = V.BDCODEMP AND AD13.BDCODCOL = V.BDCODCOL ' ||
                  '             AND V.BDREFCOL = (SELECT FIRST 1 VZ.BDREFCOL FROM VRH_EMP_TCOLCON_VINC VZ '  ||
                  '                                  WHERE VZ.BDCODEMP = AD13.BDCODEMP AND VZ.BDCODCOL = AD13.BDCODCOL ORDER BY VZ.BDREFCOL DESC) ' ||
                  replace(wsituacaocol, '*.', 'AD13.')||
                  replace(WCENTROCUSTO, '*.', 'AD13.')||
                  replace(WSINDICATOCOLABORADOR, '*.', 'AD13.')||
                  replace(WCLASSECOLABORADOR, '*.', 'AD13.')||
                  replace(WFUNCAOCOLABORADOR, '*.', 'AD13.')||
                  'where AD13.BDCODEMP = '||WCODIGOEMPRESA||' and '||
                        'AD13.BDREFA13 between '||WREFINICIAL||' and '||WREFFINAL||
                  ' order by AD13.BDREFA13, 3, 4, 5, 6 ';
        end
      else if (prtipocalculo = 5) then -- Complemento de décimo terceiro
        begin
           wSQL = 'select B.bdrefc13, B.bdliquido, V.BDCONTRCOL, 0 BDINTERM, B.bdcodcol, 0 bdcodter ' ||
                  'from VRHF_EMP_TC13SAL B '||
                  'LEFT OUTER JOIN VRH_EMP_TCOLCON_VINC V ON B.BDCODEMP = V.BDCODEMP AND B.BDCODCOL = V.BDCODCOL ' ||
                  '             AND V.BDREFCOL = (SELECT FIRST 1 VZ.BDREFCOL FROM VRH_EMP_TCOLCON_VINC VZ '  ||
                  '                                  WHERE VZ.BDCODEMP = B.BDCODEMP AND VZ.BDCODCOL = B.BDCODCOL ORDER BY VZ.BDREFCOL DESC) ' ||
                  replace(wsituacaocol, '*.', 'B.')||
                  replace(WCENTROCUSTO, '*.', 'B.')||
                  replace(WSINDICATOCOLABORADOR, '*.', 'B.')||
                  replace(WCLASSECOLABORADOR, '*.', 'B.')||
                  replace(WFUNCAOCOLABORADOR, '*.', 'B.')||
                  'where B.BDCODEMP = '||WCODIGOEMPRESA||' and '||
                        'B.BDREFC13 between '||WREFINICIAL||' and '||WREFFINAL||
                  ' order by B.bdrefc13, 3, 4, 5, 6 ';
        end
      else if (prtipocalculo = 6) then -- Adiantamento salarial
        begin
           wSQL =  'select ADSAL.bdrefad, ADSAL.bdliquido, V.BDCONTRCOL, 0 BDINTERM, ADSAL.bdcodcol, 0 bdcodter ' ||
                   'from VRHF_EMP_TADSAL ADSAL '||
                   'LEFT OUTER JOIN VRH_EMP_TCOLCON_VINC V ON ADSAL.BDCODEMP = V.BDCODEMP AND ADSAL.BDCODCOL = V.BDCODCOL ' ||
                   '             AND V.BDREFCOL = (SELECT FIRST 1 VZ.BDREFCOL FROM VRH_EMP_TCOLCON_VINC VZ '  ||
                   '                                  WHERE VZ.BDCODEMP = ADSAL.BDCODEMP AND VZ.BDCODCOL = ADSAL.BDCODCOL ORDER BY VZ.BDREFCOL DESC) ' ||
                   replace(wsituacaocol, '*.', 'ADSAL.')||
                   replace(WCENTROCUSTO, '*.', 'ADSAL.')||
                   replace(WSINDICATOCOLABORADOR, '*.', 'ADSAL.')||
                   replace(WCLASSECOLABORADOR, '*.', 'ADSAL.')||
                   replace(WFUNCAOCOLABORADOR, '*.', 'ADSAL.')||
                   'where ADSAL.BDCODEMP = '||WCODIGOEMPRESA||' and '||
                         'ADSAL.BDDATAAD between '''||PRREFINICIAL||''' and '''||PRREFFINAL||''''||
                   ' order by ADSAL.bdrefad, 3, 4, 5, 6 ';
        end
      else if (prtipocalculo = 7) then -- Folha avulsa
        begin
           wSQL = 'select AV.BDREF, AV.BDLIQUIDO, V.BDCONTRCOL, 0 BDINTERM, AV.bdcodcol, 0 bdcodter ' ||
                  'from VRHF_EMP_TFOLHAAVULSA AV '||
                  'LEFT OUTER JOIN VRH_EMP_TCOLCON_VINC V ON AV.BDCODEMP = V.BDCODEMP AND AV.BDCODCOL = V.BDCODCOL ' ||
                  '             AND V.BDREFCOL = (SELECT FIRST 1 VZ.BDREFCOL FROM VRH_EMP_TCOLCON_VINC VZ '   ||
                  '                                  WHERE VZ.BDCODEMP = AV.BDCODEMP AND VZ.BDCODCOL = AV.BDCODCOL ORDER BY VZ.BDREFCOL DESC) ' ||
                  replace(wsituacaocol, '*.', 'AV.')||
                  replace(WCENTROCUSTO, '*.', 'AV.')||
                  replace(WSINDICATOCOLABORADOR, '*.', 'AV.')||
                  replace(WCLASSECOLABORADOR, '*.', 'AV.')||
                  replace(WFUNCAOCOLABORADOR, '*.', 'AV.')||
                  'where AV.BDCODEMP = '||WCODIGOEMPRESA||' and '||
                        'AV.BDDATAFA between '''||PRREFINICIAL||''' and '''||PRREFFINAL||''' and '||
                        'AV.bdcodtca = '||PRTIPODEFOLHAAVULSA||
                  ' order by AV.BDREF, 3, 4, 5, 6 ';
        end
   
      for execute statement wSQL into :WREFERENCIACALCULO, :WVALORLIQUIDOCALCULO, :wContrCol, :wInter, :wCodCol, :wCodTer do
      begin
        if (WREFERENCIAATUAL <> WREFERENCIACALCULO) then
            begin
               wCodColAtual   = 0;
               wCodTerAtual   = 0;
            end

        WREFERENCIAATUAL = WREFERENCIACALCULO;

        if (wreferenciaatual = W01) then
          begin
            BD01    = BD01 + 1;
            if ((wCodCol <> wCodColAtual) or (wCodTer <> wCodTerAtual))  then
                begin
                    wCodColAtual = wCodCol;
                    wCodTerAtual = wCodTer;

                    if (wCodTer > 0) then
                       BD01Ter = BD01Ter + 1;
                    else
                    if (wContrCol = 1) then
                       BD01Contr = BD01Contr + 1;
                    else
                    if (wInter = 1) then
                       BD01Inter = BD01Inter + 1;
                    else
                       BD01Col = BD01Col + 1;
          end
          end
        else if (wreferenciaatual = W02) then
          begin
            BD02    = BD02 + 1;
            if ((wCodCol <> wCodColAtual) or (wCodTer <> wCodTerAtual))  then
                begin
                    wCodColAtual = wCodCol;
                    wCodTerAtual = wCodTer;

                    if (wCodTer > 0) then
                       BD02Ter = BD02Ter + 1;
                    else
                    if (wContrCol = 1) then
                       BD02Contr = BD02Contr + 1;
                    else
                    if (wInter = 1) then
                       BD02Inter = BD02Inter + 1;
                    else
                       BD02Col = BD02Col + 1;
          end
          end
        else if (wreferenciaatual = W03) then
          begin
            BD03    = BD03 + 1;
            if ((wCodCol <> wCodColAtual) or (wCodTer <> wCodTerAtual))  then
                begin
                    wCodColAtual = wCodCol;
                    wCodTerAtual = wCodTer;

                    if (wCodTer > 0) then
                       BD03Ter = BD03Ter + 1;
                    else
                    if (wContrCol = 1) then
                       BD03Contr = BD03Contr + 1;
                    else
                    if (wInter = 1) then
                       BD03Inter = BD03Inter + 1;
                    else
                       BD03Col = BD03Col + 1;
          end
          end
        else if (wreferenciaatual = W04) then
          begin
            BD04    =  BD04 + 1;
            if ((wCodCol <> wCodColAtual) or (wCodTer <> wCodTerAtual))  then
                begin
                    wCodColAtual = wCodCol;
                    wCodTerAtual = wCodTer;

                    if (wCodTer > 0) then
                       BD04Ter = BD04Ter + 1;
                    else
                    if (wContrCol = 1) then
                       BD04Contr = BD04Contr + 1;
                    else
                    if (wInter = 1) then
                       BD04Inter = BD04Inter + 1;
                    else
                       BD04Col = BD04Col + 1;
          end
          end
        else if (wreferenciaatual = W05) then
          begin
            BD05    = BD05 + 1;
            if ((wCodCol <> wCodColAtual) or (wCodTer <> wCodTerAtual))  then
                begin
                    wCodColAtual = wCodCol;
                    wCodTerAtual = wCodTer;

                    if (wCodTer > 0) then
                       BD05Ter = BD05Ter + 1;
                    else
                    if (wContrCol = 1) then
                       BD05Contr = BD05Contr + 1;
                    else
                    if (wInter = 1) then
                       BD05Inter = BD05Inter + 1;
                    else
                       BD05Col = BD05Col + 1;
          end
          end
        else if (wreferenciaatual = W06) then
          begin
            BD06    = BD06 + 1;
            if ((wCodCol <> wCodColAtual) or (wCodTer <> wCodTerAtual))  then
                begin
                    wCodColAtual = wCodCol;
                    wCodTerAtual = wCodTer;

                    if (wCodTer > 0) then
                       BD06Ter = BD06Ter + 1;
                    else
                    if (wContrCol = 1) then
                       BD06Contr = BD06Contr + 1;
                    else
                    if (wInter = 1) then
                       BD06Inter = BD06Inter + 1;
                    else
                       BD06Col = BD06Col + 1;
          end
          end
        else if (wreferenciaatual = W07) then
          begin
            BD07    = BD07 + 1;
            if ((wCodCol <> wCodColAtual) or (wCodTer <> wCodTerAtual))  then
                begin
                    wCodColAtual = wCodCol;
                    wCodTerAtual = wCodTer;

                    if (wCodTer > 0) then
                       BD07Ter = BD07Ter + 1;
                    else
                    if (wContrCol = 1) then
                       BD07Contr = BD07Contr + 1;
                    else
                    if (wInter = 1) then
                       BD07Inter = BD07Inter + 1;
                    else
                       BD07Col = BD07Col + 1;
          end
          end
        else if (wreferenciaatual = W08) then
          begin
            BD08    = BD08 + 1;
            if ((wCodCol <> wCodColAtual) or (wCodTer <> wCodTerAtual))  then
                begin
                    wCodColAtual = wCodCol;
                    wCodTerAtual = wCodTer;

                    if (wCodTer > 0) then
                       BD08Ter = BD08Ter + 1;
                    else
                    if (wContrCol = 1) then
                       BD08Contr = BD08Contr + 1;
                    else
                    if (wInter = 1) then
                       BD08Inter = BD08Inter + 1;
                    else
                       BD08Col = BD08Col + 1;
          end
          end
        else if (wreferenciaatual = W09) then
          begin
            BD09    = BD09 + 1;
            if ((wCodCol <> wCodColAtual) or (wCodTer <> wCodTerAtual))  then
                begin
                    wCodColAtual = wCodCol;
                    wCodTerAtual = wCodTer;

                    if (wCodTer > 0) then
                       BD09Ter = BD09Ter + 1;
                    else
                    if (wContrCol = 1) then
                       BD09Contr = BD09Contr + 1;
                    else
                    if (wInter = 1) then
                       BD09Inter = BD09Inter + 1;
                    else
                       BD09Col = BD09Col + 1;
          end
          end
        else if (wreferenciaatual = W10) then
          begin
            BD10    = BD10 + 1;
            if ((wCodCol <> wCodColAtual) or (wCodTer <> wCodTerAtual))  then
                begin
                    wCodColAtual = wCodCol;
                    wCodTerAtual = wCodTer;

                    if (wCodTer > 0) then
                       BD10Ter = BD10Ter + 1;
                    else
                    if (wContrCol = 1) then
                       BD10Contr = BD10Contr + 1;
                    else
                    if (wInter = 1) then
                       BD10Inter = BD10Inter + 1;
                    else
                       BD10Col = BD10Col + 1;
          end
          end
        else if (wreferenciaatual = W11) then
          begin
            BD11    = BD11 + 1;
            if ((wCodCol <> wCodColAtual) or (wCodTer <> wCodTerAtual))  then
                begin
                    wCodColAtual = wCodCol;
                    wCodTerAtual = wCodTer;

                    if (wCodTer > 0) then
                       BD11Ter = BD11Ter + 1;
                    else
                    if (wContrCol = 1) then
                       BD11Contr = BD11Contr + 1;
                    else
                    if (wInter = 1) then
                       BD11Inter = BD11Inter + 1;
                    else
                       BD11Col = BD11Col + 1;
          end
          end
        else if (wreferenciaatual = W12) then
          begin
            BD12    = BD12 + 1;
            if ((wCodCol <> wCodColAtual) or (wCodTer <> wCodTerAtual))  then
                begin
                    wCodColAtual = wCodCol;
                    wCodTerAtual = wCodTer;

                    if (wCodTer > 0) then
                       BD12Ter = BD12Ter + 1;
                    else
                    if (wContrCol = 1) then
                       BD12Contr = BD12Contr + 1;
                    else
                    if (wInter = 1) then
                       BD12Inter = BD12Inter + 1;
                    else
                       BD12Col  = BD12Col + 1;
          end
      end
      end
   
      if ((BD01 = 0) and (BD02 = 0) and (BD03 = 0) and (BD04 = 0) and (BD05 = 0) and (BD06 = 0) and
          (BD07 = 0) and (BD08 = 0) and (BD09 = 0) and (BD10 = 0) and (BD11 = 0) and (BD12 = 0)) then
        begin
          if (PREMITIREMPSEMFOLHAS = 1) then
            SUSPEND;
        end
      else
       SUSPEND;
    end
end^


create or alter procedure SP_BUSCA_VALOR_PIS_VERBAS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFFOLHA integer,
    PRTIPOFOLHA integer,
    PRDIFERENCIADORDATE date,
    PRDIFERENCIADORINTEGER integer)
returns (
    BDBDVALORPISPASEP numeric(18,6),
    BDVALORPISPASEP13 numeric(18,6))
as
declare variable WSQL varchar(30000);
declare variable WVALORVERBA numeric(18,6);
declare variable WINCIDENCIAPIS integer;
declare variable WTIPOVERBA integer;
begin
  --Inicialização de variáveis
  WSQL = '';

  --Inicialização dos outputs
  BDBDVALORPISPASEP = 0;
  BDVALORPISPASEP13 = 0;

   if (PRTIPOFOLHA = 1) then -- folha normal
     begin
        WSQL = 'select X.BDVALVFN, Y.BDINCIDPISVER, Y.BDTIPOCODVER '||
               'from VRHF_EMP_TVERBAFN X '||
               'join VRH_BASE_TVERBAS_REF Y on (Y.BDCODVER = X.BDCODVER) and '||
                                              '(Y.bdrefver = (select max(C.BDREFVER) from VRH_BASE_TVERBAS_REF C where C.BDCODVER = X.BDCODVER and C.BDREFVER <= '||PRREFFOLHA||')) '||
               'where X.BDCODEMP = '||PRCODEMP||' and '||
                     'X.BDCODCOL = '||PRCODCOL||' and '||
                     'X.BDREFFN = '||PRREFFOLHA;
     end
   else if (PRTIPOFOLHA = 2) then -- Folha tomador
     begin
       WSQL = 'select A.BDVALVFT, B.BDINCIDPISVER, B.BDTIPOCODVER '||
              'from VRHF_EMP_TVERBATOMADOR A '||
              'join VRH_BASE_TVERBAS_REF B on (B.BDCODVER = A.BDCODVER) and '||
                                             '(B.BDREFVER = (select max(C.BDREFVER) from VRH_BASE_TVERBAS_REF C where C.BDCODVER = A.BDCODVER and C.BDREFVER <= '||PRREFFOLHA||')) '||
              'where A.BDCODEMP = '||PRCODEMP||' and '||
                    'A.BDCODCOL = '||PRCODCOL||' and '||
                    'A.BDREFTOMADOR = '||PRREFFOLHA;
     end
   else if (PRTIPOFOLHA = 3) then -- Adiantamento décimo terceiro
     begin
       WSQL = 'select AD13.BDVALVA13, B.BDINCIDPISVER, B.BDTIPOCODVER '||
              'from VRHF_EMP_TVERBAA13 AD13 '||
              'join VRH_BASE_TVERBAS_REF B on (B.BDCODVER = AD13.BDCODVER) and '||
                                             '(B.BDREFVER = (select max(C.BDREFVER) from VRH_BASE_TVERBAS_REF C where C.BDCODVER = AD13.BDCODVER and C.BDREFVER <= '||PRREFFOLHA||')) '||
              'where AD13.BDCODEMP = '||PRCODEMP||' and '||
                    'AD13.BDCODCOL = '||PRCODCOL||' and '||
                    'AD13.BDREFA13 = '||PRREFFOLHA;
     end
   else if (PRTIPOFOLHA = 4) then -- Complemento décimo terceiro
     begin
       WSQL = 'select C13.BDVALVC13, B.BDINCIDPISVER, B.BDTIPOCODVER '||
              'from VRHF_EMP_TVERBAC13 C13 '||
              'join VRH_BASE_TVERBAS_REF B on (B.BDCODVER = C13.BDCODVER) and '||
                                             '(B.BDREFVER = (select max(C.BDREFVER) from VRH_BASE_TVERBAS_REF C where C.BDCODVER = C13.BDCODVER and C.BDREFVER <= '||PRREFFOLHA||')) '||
              'where C13.BDCODEMP = '||PRCODEMP||' and '||
                    'C13.BDCODCOL = '||PRCODCOL||' and '||
                    'C13.BDREFC13 = '||PRREFFOLHA;
     end
   else if (PRTIPOFOLHA in (5, 7)) then -- Folha complementar
     begin
       WSQL = 'select FC.BDVALVFC, B.BDINCIDPISVER, B.BDTIPOCODVER '||
              'from VRHF_EMP_TVERBAFC FC '||
              'join VRH_BASE_TVERBAS_REF B on (B.BDCODVER = FC.BDCODVER) and '||
                                             '(B.BDREFVER = (select max(C.BDREFVER) from VRH_BASE_TVERBAS_REF C where C.BDCODVER = FC.BDCODVER and C.BDREFVER <= '||PRREFFOLHA||')) '||
              'where FC.BDCODEMP = '||PRCODEMP||' and '||
                    'FC.BDCODCOL = '||PRCODCOL||' and '||
                    'FC.BDREFFC = '||PRDIFERENCIADORINTEGER||' and '||
                    'FC.BDREFFN = '||PRREFFOLHA;
     end
   else if (PRTIPOFOLHA in (6, 8)) then -- Folha complementar tomador
     begin
       WSQL = 'select FCT.BDVALVFC, B.BDINCIDPISVER, B.BDTIPOCODVER '||
              'from VRHF_EMP_TVERBAFCTOMADOR FCT '||
              'join VRH_BASE_TVERBAS_REF B on (B.BDCODVER = FCT.BDCODVER) and '||
                                             '(B.BDREFVER = (select max(C.BDREFVER) from VRH_BASE_TVERBAS_REF C where C.BDCODVER = FCT.BDCODVER and C.BDREFVER <= '||PRREFFOLHA||')) '||
             'where FCT.BDCODEMP = '||PRCODEMP||' and '||
                   'FCT.BDCODCOL = '||PRCODCOL||' and '||
                   'FCT.BDREFFC = '||PRDIFERENCIADORINTEGER||' AND '||
                   'FCT.BDREFTOMADOR = '||PRREFFOLHA;
     end
   else if (PRTIPOFOLHA = 9) then -- Folha avulsa
     begin
       WSQL = 'select FA.BDVALVFA, B.BDINCIDPISVER, B.BDTIPOCODVER '||
              'from VRHF_EMP_TVERBAFA FA '||
              'join VRH_BASE_TVERBAS_REF B on (B.BDCODVER = FA.BDCODVER) and '||
                                             '(B.BDREFVER = (select max(C.BDREFVER) from VRH_BASE_TVERBAS_REF C where C.BDCODVER = FA.BDCODVER and C.BDREFVER <= '||PRREFFOLHA||')) '||
              'where FA.BDCODEMP = '||PRCODEMP||' and '||
                    'FA.BDCODCOL = '||PRCODCOL||' and '||
                    '(EXTRACT(YEAR from FA.BDDATAFA)||LPAD(EXTRACT(MONTH from FA.BDDATAFA), 2, '||'0'||')) = '||PRREFFOLHA||' AND '||
                    'FA.BDDATAFA = '||''''||PRDIFERENCIADORDATE||''''||' and '||
                    'FA.BDCODTCA = '||PRDIFERENCIADORINTEGER||
                    ' order by FA.BDDATAFA';
     end
   else if (PRTIPOFOLHA = 10) then -- Folha intermitente
     begin
       WSQL = 'select FINT.BDVALVFN, B.BDINCIDPISVER, B.BDTIPOCODVER '||
              'from VRHF_EMP_TVERBAINT FINT '||
              'join VRH_BASE_TVERBAS_REF B on (B.BDCODVER = FINT.BDCODVER) and '||
                                              '(B.BDREFVER = (select max(C.BDREFVER) from VRH_BASE_TVERBAS_REF C where C.BDCODVER = FINT.BDCODVER and C.BDREFVER <= '||PRREFFOLHA||')) '||
             'where FINT.BDCODEMP = '||PRCODEMP||' and '||
                   'FINT.BDCODCOL = '||PRCODCOL||' and '||
                   'FINT.BDREFFN = '||PRREFFOLHA||' and '||
                   'FINT.BDCODCONTTI = '||PRDIFERENCIADORINTEGER;
     end
   else if (PRTIPOFOLHA = 11) then -- Folha tomador intermitente
     begin
       WSQL = 'select FTINT.BDVALVFT, B.BDINCIDPISVER, B.BDTIPOCODVER '||
              'from VRHF_EMP_TVERBATOMINT FTINT '||
              'join VRH_BASE_TVERBAS_REF B on (B.BDCODVER = FTINT.BDCODVER) and '||
                                             '(B.BDREFVER = (select max(C.BDREFVER) from VRH_BASE_TVERBAS_REF C where C.BDCODVER = FTINT.BDCODVER and C.BDREFVER <= '||PRREFFOLHA||')) '||
              'where FTINT.BDCODEMP = '||PRCODEMP||' and '||
                    'FTINT.BDCODCOL = '||PRCODCOL||' and '||
                    'FTINT.BDREFTOMADOR = '||PRREFFOLHA||' and '||
                    'FTINT.BDCODCONTTI = '||PRDIFERENCIADORINTEGER;
     end
   else if (PRTIPOFOLHA in (12, 14)) then -- Folha complementar intermitente
     begin
       WSQL = 'select FCINT.BDVALVFC, B.BDINCIDPISVER, B.BDTIPOCODVER '||
              'from VRHF_EMP_TVERBAFCINT FCINT '||
              'join VRH_BASE_TVERBAS_REF B on (B.BDCODVER = FCINT.BDCODVER) and '||
                                             '(B.BDREFVER = (select max(C.BDREFVER) from VRH_BASE_TVERBAS_REF C where C.BDCODVER = FCINT.BDCODVER and C.BDREFVER <= '||PRREFFOLHA||')) '||
              'where FCINT.BDCODEMP = '||PRCODEMP||' and '||
              'FCINT.BDCODCOL = '||PRCODCOL||' and '||
              'FCINT.BDREFFC = '||extract(year from PRDIFERENCIADORDATE)||LPAD(extract(month from PRDIFERENCIADORDATE),2,'0')||LPAD(extract(day from PRDIFERENCIADORDATE),2,'0')||' and '||
              'FCINT.BDCODCONTTI = '||PRDIFERENCIADORINTEGER||' and '||
              'FCINT.BDREFFN = '||PRREFFOLHA;
     end
   else if (PRTIPOFOLHA in (13, 15)) then -- Folha complementar tomador intermitente
     begin
       WSQL = 'select FCTOMINT.BDVALVFC, B.BDINCIDPISVER, B.BDTIPOCODVER '||
              'from VRHF_EMP_TVERBAFCTOMINT FCTOMINT '||
              'join VRH_BASE_TVERBAS_REF B on (B.BDCODVER = FCTOMINT.BDCODVER) and '||
                                             '(B.BDREFVER = (select max(C.BDREFVER) from VRH_BASE_TVERBAS_REF C where C.BDCODVER = FCTOMINT.BDCODVER and C.BDREFVER <= '||PRREFFOLHA||')) '||
              'where FCTOMINT.BDCODEMP = '||PRCODEMP||' and '||
                    'FCTOMINT.BDCODCOL = '||PRCODCOL||' and '||
                    'FCTOMINT.BDREFFC = '||extract(year from PRDIFERENCIADORDATE)||LPAD(extract(month from PRDIFERENCIADORDATE),2,'0')||LPAD(extract(day from PRDIFERENCIADORDATE),2,'0')||' and '||
                    'FCTOMINT.BDCODCONTTI = '||PRDIFERENCIADORINTEGER||' and '||
                    'FCTOMINT.BDREFTOMADOR = '||PRREFFOLHA;
     end
   else if (PRTIPOFOLHA = 16) then -- Autônomos
     begin
        WSQL = 'select T.BDVALOR, VR.BDINCIDPISVER, VR.BDTIPOCODVER '||
               'from VRHF_BASE_ITEMS_CALCTERC T '||
               'join VRH_BASE_TVERBAS_REF VR on (VR.BDCODVER = T.BDCODVER) and '||
                                               '(VR.BDREFVER = (select max(X.BDREFVER) from VRH_BASE_TVERBAS_REF X where (X.BDCODVER = VR.BDCODVER) and (X.BDREFVER <= '||PRREFFOLHA||'))) '||
               'where T.BDCODEMP = '||PRCODEMP||' and '||
                     'T.BDCODTER = '||PRCODCOL||' and '||
                     'T.BDCODSERV = '||PRDIFERENCIADORINTEGER;
     end

   for execute statement WSQL into :WVALORVERBA, :WINCIDENCIAPIS, :WTIPOVERBA do
   begin
     if (WINCIDENCIAPIS <> 0) then
       begin
         if (WTIPOVERBA IN (1,3)) then
            WVALORVERBA = WVALORVERBA * -1;

         if (WINCIDENCIAPIS = 3) then
            BDVALORPISPASEP13 = BDVALORPISPASEP13 + WVALORVERBA;
         else
            BDBDVALORPISPASEP = BDBDVALORPISPASEP + WVALORVERBA;
       end
   end

   suspend;
end^

create or alter procedure SP_RETORNA_TAGSTR_TOTALIZADORES (
    PRCODEMPRESA integer,
    PRCODCOLABORADOR integer,
    PRREFFOLHA integer,
    PRTIPOFOLHA integer,
    PRDIFERENCIADORDATE date,
    PRDIFERENCIADORINTEGER integer,
    PRCONVERTTIPO integer = 0,
    PRINTERMITENTE integer = 0,
    PRORDEM integer = 0,
    PRFC integer = 0,
    PRREFDATAFC integer = 0)
returns (
    BDDESCRICAOCALCULO varchar(10000),
    BDTAGSTR varchar(10000))
as
declare variable WTIPO integer;
declare variable WTIPOPROPA13 integer;
declare variable WPERCA13 numeric(18,6);
declare variable WDESCRICAOFOLHA varchar(10000);
declare variable WTAGSTR varchar(10000);
declare variable WCODIGOADC integer;
declare variable WCODCONTRATO integer;
declare variable WREFFOLHA integer;
declare variable WDESCRICAOAVULSA varchar(10000);
begin
   if (PRCONVERTTIPO = 1) then
      begin
        if (PRTIPOFOLHA in (0,100,101)) then
           begin
             PRTIPOFOLHA = 1;
             if (PRORDEM > 0) then
                PRTIPOFOLHA = 2;

             if (PRINTERMITENTE = 1) then
                begin
                  PRTIPOFOLHA = 10;

                  if (PRORDEM > 0) then
                     PRTIPOFOLHA = 11;
                end
           end
        else if (PRTIPOFOLHA in (9)) then
           PRTIPOFOLHA = 3;
        else if (PRTIPOFOLHA in (11)) then
           PRTIPOFOLHA = 4;
        else if (PRTIPOFOLHA in (1,110,111)) then
           begin
             PRTIPOFOLHA = 5;

             if (PRORDEM > 0) then
                PRTIPOFOLHA = 6;

             if (PRINTERMITENTE = 1) then
                begin
                  PRTIPOFOLHA = 12;

                  if (PRORDEM > 0) then
                     PRTIPOFOLHA = 13;
                end
           end
        else if (PRTIPOFOLHA in (50)) then
           PRTIPOFOLHA = 9;
        else if (PRTIPOFOLHA in (2)) then
           PRTIPOFOLHA = 18;
        else if (PRTIPOFOLHA in (3)) then
           PRTIPOFOLHA = 19;
        else if (PRTIPOFOLHA in (10)) then
           begin
             PRTIPOFOLHA = 16;
             if (PRINTERMITENTE = 1) then
                PRTIPOFOLHA = 10;
           end
        else if (PRTIPOFOLHA >= 9000) then
           PRTIPOFOLHA = 20;
        else if (PRTIPOFOLHA = 4) then
           begin
             if (prfc = 0) then
                begin
                  PRTIPOFOLHA = 1;
                  if (PRORDEM > 0) then
                     PRTIPOFOLHA = 2;
    
                  if (PRINTERMITENTE = 1) then
                     begin
                       PRTIPOFOLHA = 10;
    
                       if (PRORDEM > 0) then
                          PRTIPOFOLHA = 11;
                     end
                end
             else
                begin
                  PRTIPOFOLHA = 5;

                  if (PRORDEM > 0) then
                     PRTIPOFOLHA = 6;

                  if (PRINTERMITENTE = 1) then
                     begin
                       PRTIPOFOLHA = 12;

                       if (PRORDEM > 0) then
                          PRTIPOFOLHA = 13;
                     end
                end
           end

--  C_FICHA_IMPORTACAO_FN         = 9000;
--  C_FICHA_IMPORTACAO_FN_RESC    = 9001;
--  C_FICHA_IMPORTACAO_FN_RESC_13 = 9002;
--  C_FICHA_IMPORTACAO_FC         = 9010;
--  C_FICHA_IMPORTACAO_FC_RESC    = 9011;
--  C_FICHA_IMPORTACAO_FC_RESC_13 = 9012;
--  C_FICHA_IMPORTACAO_AD_SAL     = 9020;
--  C_FICHA_IMPORTACAO_FERIAS     = 9030;
--  C_FICHA_IMPORTACAO_AD13       = 9099;    { 13101 Denicio 16/12/2015 }
--  C_FICHA_IMPORTACAO_13         = 9100;
--  C_FICHA_IMPORTACAO_C13        = 9110;
--  C_FICHA_IMPORTACAO_FA         = 9500;
      end
   else if (prconverttipo = 2) then  -- Autônomo
      begin
        if (prtipofolha = 1) then
           prtipofolha = 17;
        else if (prtipofolha = 2) then
           prtipofolha = 21;
      end

   if (PRTIPOFOLHA = 1) then -- folha normal
     begin
       WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||PRREFFOLHA;
       WDESCRICAOFOLHA = 'Folha normal '||(SUBSTRING(CAST(PRREFFOLHA AS VARCHAR(6)) FROM 5 FOR 2))||'/'||(PRREFFOLHA/100);
     end
   else if (PRTIPOFOLHA = 2) then -- Folha tomador
     begin
        WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||PRREFFOLHA;
        WDESCRICAOFOLHA = 'Folha normal '||(SUBSTRING(CAST(PRREFFOLHA AS VARCHAR(6)) FROM 5 FOR 2))||'/'||(PRREFFOLHA/100);
     end
   else if (PRTIPOFOLHA = 3) then -- Adiantamento décimo terceiro
     begin
      select FA13.BDPERCA13, FA13.BDTIPOPROPA13 from VRHF_EMP_TA13SAL FA13 where FA13.BDCODEMP = :PRCODEMPRESA and FA13.BDREFA13 = :PRREFFOLHA AND FA13.BDCODCOL = :PRCODCOLABORADOR
      into :WPERCA13, :WTIPOPROPA13;

        WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||PRREFFOLHA||'|'||WPERCA13||'|'||WTIPOPROPA13;
        WDESCRICAOFOLHA = 'Adiantamento 13° salário';
     end
   else if (PRTIPOFOLHA = 4) then -- Complemento décimo terceiro
     begin
        WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||(PRREFFOLHA / 100);
        WDESCRICAOFOLHA = 'Complemento 13° salário';
     end
   else if (PRTIPOFOLHA in (5, 7)) then -- Folha complementar
     begin
       if ((PRREFDATAFC = NULL) or (PRREFDATAFC = 0)) then
       select FIRST 1 X.BDCODTIPOFC, coalesce(X.BDCODACCONV, 0), X.BDREFFN from VRHF_EMP_TFOLHACOMP X where (X.BDCODEMP = :PRCODEMPRESA) and (X.BDCODCOL = :PRCODCOLABORADOR) and (X.BDREFFN = :PRREFFOLHA) AND (X.BDDATAPAGFC = :PRDIFERENCIADORDATE)
       into  :WTIPO, :WCODIGOADC, :WREFFOLHA;
       else
          select FIRST 1 X.BDCODTIPOFC, coalesce(X.BDCODACCONV, 0), X.BDREFFN from VRHF_EMP_TFOLHACOMP X where (X.BDCODEMP = :PRCODEMPRESA) and (X.BDCODCOL = :PRCODCOLABORADOR) and (X.BDREFFN = :PRREFFOLHA) AND (X.BDREFFC = :PRREFDATAFC)
          into  :WTIPO, :WCODIGOADC, :WREFFOLHA;

       if (WCODIGOADC <> 0) then
          begin
            WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|0|'||WTIPO||'|'||WCODIGOADC||'|'||PRDIFERENCIADORDATE;
            WDESCRICAOFOLHA = 'Complementar ADC - '||WCODIGOADC;
          end
       else
          begin
            WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||WREFFOLHA||'|'||WTIPO||'|'||WCODIGOADC||'|'||PRDIFERENCIADORDATE;
            WDESCRICAOFOLHA = 'Complementar '||SUBSTRING(CAST(:WREFFOLHA AS VARCHAR(6)) FROM 5 FOR 2)||'/'||(WREFFOLHA / 100)||' pagamento '||LPAD((EXTRACT(DAY FROM :PRDIFERENCIADORDATE)), 2, '0')||'/'||LPAD((EXTRACT(MONTH FROM :PRDIFERENCIADORDATE)),2,'0')||'/'||EXTRACT(YEAR FROM :PRDIFERENCIADORDATE);
          end
     end
   else if (PRTIPOFOLHA in (6, 8)) then --***FOLHA COMPLEMENTAR TOMADOR***--
     begin
       if ((PRREFDATAFC = null) or (PRREFDATAFC = 0)) then
       select FIRST 1 X.BDCODTIPOFC, coalesce(X.BDCODACCONV, 0), X.BDREFTOMADOR from VRHF_EMP_TFOLTOMCOMP X where (X.BDCODEMP = :PRCODEMPRESA) and (X.BDCODCOL = :PRCODCOLABORADOR)  and (X.BDREFTOMADOR = :PRREFFOLHA) AND (X.BDDATAPAGFC = :PRDIFERENCIADORDATE)
       into :WTIPO, :WCODIGOADC, :WREFFOLHA;
       else
          select FIRST 1 X.BDCODTIPOFC, coalesce(X.BDCODACCONV, 0), X.BDREFTOMADOR from VRHF_EMP_TFOLTOMCOMP X where (X.BDCODEMP = :PRCODEMPRESA) and (X.BDCODCOL = :PRCODCOLABORADOR)  and (X.BDREFTOMADOR = :PRREFFOLHA) AND (X.BDREFFC = :PRREFDATAFC)
          into :WTIPO, :WCODIGOADC, :WREFFOLHA;

       if (WCODIGOADC <> 0) then
          begin
            WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|0|'||WTIPO||'|'||WCODIGOADC||'|'||PRDIFERENCIADORDATE;
            WDESCRICAOFOLHA = 'Complementar ADC - '||WCODIGOADC;
          end
       else
          begin
            WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||WREFFOLHA||'|'||WTIPO||'|'||WCODIGOADC||'|'||PRDIFERENCIADORDATE;
            WDESCRICAOFOLHA = 'Complementar '||SUBSTRING(CAST(:WREFFOLHA AS VARCHAR(6)) FROM 5 FOR 2)||'/'||(WREFFOLHA / 100)||' pagamento '||LPAD((EXTRACT(DAY FROM :PRDIFERENCIADORDATE)), 2, '0')||'/'||LPAD((EXTRACT(MONTH FROM :PRDIFERENCIADORDATE)),2,'0')||'/'||EXTRACT(YEAR FROM :PRDIFERENCIADORDATE);
          end
     end
   else if (PRTIPOFOLHA = 9) then -- Folha avulsa
     begin
       select X.BDDESCTCA from VRH_BASE_TTIPOCALCAVUL X where X.BDCODTCA = :PRDIFERENCIADORINTEGER into :WDESCRICAOAVULSA;

       WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||PRDIFERENCIADORINTEGER||'|'||PRDIFERENCIADORDATE;
       WDESCRICAOFOLHA = WDESCRICAOAVULSA||' '||LPAD((EXTRACT(DAY FROM :PRDIFERENCIADORDATE)), 2, '0')||'/'||LPAD((EXTRACT(MONTH FROM :PRDIFERENCIADORDATE)),2,'0')||'/'||EXTRACT(YEAR FROM :PRDIFERENCIADORDATE);
     end
   else if (PRTIPOFOLHA = 10) then -- Folha intermitente
     begin
       WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||PRREFFOLHA||'|'||PRDIFERENCIADORINTEGER;
       WDESCRICAOFOLHA = 'Intermitente - contrato '||PRDIFERENCIADORINTEGER;
     end
   else if (PRTIPOFOLHA = 11) then -- Folha tomador intermitente
     begin
       WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||PRREFFOLHA||'|'||PRDIFERENCIADORINTEGER;
       WDESCRICAOFOLHA = 'Intermitente - contrato '||PRDIFERENCIADORINTEGER;
     end
   else if (PRTIPOFOLHA in (12, 14)) then -- Folha complementar intermitente
     begin
       WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||PRREFFOLHA||'|'||PRDIFERENCIADORINTEGER||'|'||PRDIFERENCIADORDATE;
       WDESCRICAOFOLHA = 'Complementar intermitente - contrato '||PRDIFERENCIADORINTEGER;
     end
   else if (PRTIPOFOLHA in (13, 15)) then -- Folha complementar tomador intermitente
     begin
       WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||PRREFFOLHA||'|'||PRDIFERENCIADORINTEGER||'|'||PRDIFERENCIADORDATE;
       WDESCRICAOFOLHA = 'Complementar intermitente - contrato '||PRDIFERENCIADORINTEGER;
     end
   else if (PRTIPOFOLHA = 16) then -- Folha décimo terceiro salário
     begin
       WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||PRREFFOLHA;
       WDESCRICAOFOLHA = 'Folha 13° salário';
     end
   else if (PRTIPOFOLHA = 17) then -- Terceiro
     begin
       WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||PRREFFOLHA||'|'||PRDIFERENCIADORINTEGER;
       WDESCRICAOFOLHA = 'Autônomos serviço '||PRDIFERENCIADORINTEGER;
     end
   else if (PRTIPOFOLHA = 18) then -- Adiantamento salárial
     begin
       WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||PRDIFERENCIADORDATE;
       WDESCRICAOFOLHA = 'Adiantamento salárial '||LPAD((EXTRACT(DAY FROM :PRDIFERENCIADORDATE)), 2, '0')||'/'||LPAD((EXTRACT(MONTH FROM :PRDIFERENCIADORDATE)),2,'0')||'/'||EXTRACT(YEAR FROM :PRDIFERENCIADORDATE);
     end
   else if (PRTIPOFOLHA = 19) then -- Férias
     begin
       WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||PRDIFERENCIADORDATE||'|'||PRDIFERENCIADORINTEGER;
       WDESCRICAOFOLHA = 'Férias '||LPAD((EXTRACT(DAY FROM :PRDIFERENCIADORDATE)), 2, '0')||'/'||LPAD((EXTRACT(MONTH FROM :PRDIFERENCIADORDATE)),2,'0')||'/'||EXTRACT(YEAR FROM :PRDIFERENCIADORDATE)||' código '||PRDIFERENCIADORINTEGER;
     end
   else if (PRTIPOFOLHA = 20) then -- Ficha financeira
     begin
       WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||PRDIFERENCIADORINTEGER;
       WDESCRICAOFOLHA = 'Ficha financeira ';
     end
   else if (PRTIPOFOLHA = 21) then
     begin
       WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||PRDIFERENCIADORINTEGER;
       WDESCRICAOFOLHA = 'Ficha financeira autônomo ';
     end

   if (WTAGSTR IS NULL) then
      WTAGSTR = PRTIPOFOLHA||'|'||PRCODEMPRESA||'|'||PRCODCOLABORADOR||'|'||PRREFFOLHA;

   BDDESCRICAOCALCULO = WDESCRICAOFOLHA;
   BDTAGSTR           = WTAGSTR;
   suspend;
end^

create or alter procedure SP_HORARIOS_INTERMITENTES (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDDATA date,
    BDHORAINICIAL time,
    BDHORAFINAL time)
as
declare variable WDATAINI date;
declare variable WDATAFIM date;
declare variable WTIPO integer;
declare variable WCODHOR_CON_INT integer;
declare variable WCODCONTRATO integer;
declare variable WDIACOMPENSADO integer;
declare variable WDIADEDESCANSO integer;
begin
  /* Procedure Text */
  --suspend;
  bdcodemp = prcodemp;
  bdcodcol = prcodcol;
  bdref = prref;

  for select contrato.bdcodcontti,CONTRATO.BDDATAINISERVTI, CONTRATO.BDDATAFIMSERVTI, CONTRATO.BDTIPOHORARIOTI as BDTIPO, CONTRATO.bdcodqhh, CONTRATO.bddiacompensado, CONTRATO.bddiadescanso
  from VRH_EMP_TINTERMITENTE CONTRATO
  where CONTRATO.BDCODEMP = :prcodemp and
      CONTRATO.BDCODCOL = :prcodcol and
      cast(extract(year from CONTRATO.BDDATAINISERVTI) as varchar(4)) || lpad(cast(extract(month from CONTRATO.BDDATAINISERVTI) as varchar(2)), 2, '0') = :prref
  into :wcodcontrato, :wdataini, :wdatafim, :wtipo, :wcodhor_con_int, :wdiacompensado, :wdiadedescanso do
    begin
      if (wcodhor_con_int is not null) then
         begin
           while (wdataini <= wdatafim) do
             begin
               if ((not(EXTRACT(WEEKDAY FROM :wdataini) = wdiadedescanso -1)) and (not(EXTRACT(WEEKDAY FROM :wdataini) = wdiacompensado -1)))  then
                 begin
                   bddata = wdataini;
                   for select horas.bdqhhsent, horas.bdqhhssai from VRH_BASE_TQH_HORAS horas where horas.bdcodqhh = :wcodhor_con_int and horas.bdqhhsent is not null
                   into :bdhorainicial, :bdhorafinal do
                     suspend;
                 end

               wdataini = wdataini + 1;
             end
         end
      else if (:wtipo = 0) then
         begin
           for select diasint.bddatadti, diasint.bdcodqhh from VRH_EMP_TINTERMITENTE_QHDIAS diasint
               where diasint.bdcodemp = :prcodemp and diasint.bdcodcol = :prcodcol and diasint.bdcodcontti = :wcodcontrato
               into :bddata, :wcodhor_con_int do
               begin
                 if (wcodhor_con_int is not null) then
                    begin
                      for select horas.bdqhhsent, horas.bdqhhssai from VRH_BASE_TQH_HORAS horas where horas.bdcodqhh = :wcodhor_con_int and horas.bdqhhsent is not null
                          into :bdhorainicial, :bdhorafinal do
                          suspend;
                    end
                 else
                    begin
                      for select x.bdinicio,x.bdfim from SP_HORARIO_INTERMITENTES_DIARIO(:prcodemp,:prcodcol,:bddata) x into :bdhorainicial,:bdhorafinal do
                        suspend;
                    end
               end
         end
      else
         begin
           while (wdataini <= wdatafim) do
             begin
               if ((not(EXTRACT(WEEKDAY FROM :wdataini) = wdiadedescanso -1)) and (not(EXTRACT(WEEKDAY FROM :wdataini) = wdiacompensado -1))) then
                 begin
                   bddata = wdataini;
                   bdhorainicial = null;
                   bdhorafinal = null;
                   for select x.bdinicio,x.bdfim from SP_HORARIO_INTERMITENTES_DIARIO(:prcodemp,:prcodcol,:bddata) x into :bdhorainicial,:bdhorafinal do
                     begin
                        if (bdhorainicial is not null) then
                           suspend;
                     end
                 end

               wdataini = wdataini + 1;
             end
         end
    end

end^

create or alter procedure SP_HORARIO_INTERMITENTES_DIARIO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRDATA date)
returns (
    BDINICIO time,
    BDFIM time)
as
declare variable WPLANO integer;
declare variable WQUADRO integer;
declare variable WHORAS numeric(15,6);
declare variable WSTRHORA varchar(10);
declare variable WSTRMIN varchar(10);
begin
  /* Procedure Text */
--  suspend;
  wplano = null;
  wquadro = null;
  select first 1 vd.bdcodqh,vd.bdcodpqua from VRH_EMP_TCOL_VINCDIA vd
  where vd.bdcodemp =:prcodemp and vd.bdcodcol =:prcodcol and vd.bddatacol <= :prdata order by vd.bddatacol desc
  into :wquadro, :wplano;

  if ((wquadro is not null) and (wplano is not null)) then
     begin
       for select hora.bdqhhsent, hora.bdqhhssai from VRH_BASE_TQH_DIAS dia
       join VRH_BASE_TQH_HORAS hora on dia.bdcodqhh = hora.bdcodqhh
       where dia.bdcodqh = :wquadro and dia.bdcodpqua = :wplano and dia.bddiasemqh = EXTRACT(WEEKDAY FROM :prdata) into
         :bdinicio, :bdfim do
         suspend;
     end
  else
     begin
       select first 1 cal.bdhorasdiariascol from VRHF_EMP_TCOL_CALC cal where cal.bdcodemp = :prcodemp and cal.bdcodcol = :prcodcol
           and cal.bdrefcol <= cast(extract(year from :prdata) as varchar(4)) || lpad(cast(extract(month from :prdata) as varchar(2)), 2, '0')
       into whoras;
       WSTRHORA = cast(cast(whoras - 0.5 as integer) as varchar(2));
       WSTRMIN = cast(whoras - cast(wstrhora as integer) as varchar(10));
       whoras = cast(wstrmin as numeric(15,6)) * 60;
       wstrhora = wstrhora||':'||cast(cast(whoras as integer) as varchar(2));
       bdinicio = cast('00:00' as time);
       bdfim = cast(:wstrhora as time);
       suspend;
     end
end^


create or alter procedure SP_RH_UNION_FC_FCT_MES (
    PRCODEMP varchar(3000),
    PRCODCOL varchar(3000),
    PRCODADC integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRREFPAG date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFC integer,
    BDREFCOMP integer,
    BDCODVER integer,
    BDREFVFN_SUM numeric(15,2),
    BDREFAUXVFN_SUM numeric(15,2),
    BDREFVFN_MAX numeric(15,2),
    BDREFAUXVFN_MAX numeric(15,2),
    BDVALVFN numeric(15,2),
    BDVALIFN numeric(15,2),
    BDIGNREFAVFN varchar(3000),
    BDIGNREFVFN varchar(3000),
    BDIGNVALVFN varchar(3000),
    BDORVERBAFC integer,
    BDCOMPESP varchar(3000),
    BDFORMREFAUX varchar(3000),
    BDFORMREF varchar(3000),
    BDFORMVAL varchar(3000),
    BDDESCVER varchar(3000),
    BDTIPOCODVER integer,
    BDCLAVER varchar(3000),
    BDORDEMVER integer,
    BDTIPOREFVER integer,
    BDREFFN integer)
as
declare variable WTIPOREFVER integer;
declare variable WORDEMVER integer;
declare variable WCLAVER varchar(3000);
declare variable WTIPOCODVER integer;
declare variable WDESCVER varchar(3000);
declare variable WCOLABORADOR varchar(3000);
declare variable WEMPRESA varchar(3000);
declare variable WSQL varchar(32000);
begin
  /* Procedure Text */
  if (coalesce(prcodemp, '') <> '') then
     wempresa = upper(prcodemp)||' and ';
  else
     wempresa = '';

  if (coalesce(prcodcol, '') <> '') then
     wcolaborador = upper(prcodcol)||' and ';
  else
     wcolaborador = '';

  wsql = 'select DADOS.BDCODEMP, DADOS.BDCODCOL, DADOS.BDREFFC, DADOS.BDREFCOMP, DADOS.BDCODVER, sum(DADOS.BDREFVFC) BDREFVFC, '||
         '       sum(DADOS.BDREFAUXVFC) BDREFAUXVFC, max(DADOS.BDREFVFC) BDREFVFC, max(DADOS.BDREFAUXVFC) BDREFAUXVFC, '||
         '       sum(DADOS.BDVALVFC) BDVALVFC, sum(DADOS.BDVALIFC) BDVALIFC, max(DADOS.BDIGNREFAVFC) BDIGNREFAVFC, '||
         '       max(DADOS.BDIGNREFVFC) BDIGNREFVFC, max(DADOS.BDIGNVALVFC) BDIGNVALVFC, max(DADOS.BDORVERBAFC) BDORVERBAFC, '||
         '       max(DADOS.BDCOMPESP) BDCOMPESP, max(DADOS.BDFORMREFAUX) BDFORMREFAUX, max(DADOS.BDFORMREF) BDFORMREF, '||
         '       max(DADOS.BDFORMVAL) BDFORMVAL, max(DADOS.BDREFFN) BDREFFN '||
         '       from (select CALC.BDCODEMP, CALC.BDCODCOL, CALC.BDREFFC, CALC.BDREFCOMP, VERBA.BDCODVER, VERBA.BDREFVFC, '||
         '             VERBA.BDREFAUXVFC, VERBA.BDVALVFC, VERBA.BDVALIFC, VERBA.BDIGNREFAVFC, VERBA.BDIGNREFVFC, '||
         '             VERBA.BDIGNVALVFC, VERBA.BDORVERBAFC, VERBA.BDCOMPESP, VERBA.BDFORMREFAUX, VERBA.BDFORMREF, '||
         '             VERBA.BDFORMVAL, CALC.BDREFFN '||
         '      from VRHF_EMP_TFOLHACOMP CALC '||
         '      left join VRHF_EMP_TVERBAFC VERBA on (CALC.BDCODEMP = VERBA.BDCODEMP) and '||
         '            (CALC.BDCODCOL = VERBA.BDCODCOL) and '||
         '            (CALC.BDREFFN = VERBA.BDREFFN) and '||
         '            (CALC.BDREFFC = VERBA.BDREFFC) '||
         '      where '||wempresa||
         '            '||wcolaborador||
         '            CALC.BDCODACCONV = '||prcodadc||' and '||
         '            CALC.BDREFFN >= '||prrefini||' and '||
         '            CALC.BDREFFNFIM <= '||prreffim||
         '      union all '||
         '      select CALC.BDCODEMP, CALC.BDCODCOL, CALC.BDREFFC, CALC.BDREFCOMP, VERBA.BDCODVER, VERBA.BDREFVFC, '||
         '             VERBA.BDREFAUXVFC, VERBA.BDVALVFC, VERBA.BDVALIFC, VERBA.BDIGNREFAVFC, VERBA.BDIGNREFVFC, '||
         '             VERBA.BDIGNVALVFC, VERBA.BDORVERBAVFC BDORVERBAFC, VERBA.BDCOMPESP, VERBA.BDFORMREFAUX, VERBA.BDFORMREF, '||
         '             VERBA.BDFORMVAL, CALC.BDREFTOMADOR BDREFFN '||
         '      from VRHF_EMP_TFOLTOMCOMP CALC '||
         '      left join VRHF_EMP_TVERBAFCTOMADOR VERBA on (CALC.BDCODEMP = VERBA.BDCODEMP) and '||
         '            (CALC.BDCODCOL = VERBA.BDCODCOL) and '||
         '            (CALC.BDORDEM = VERBA.BDORDEM) and '||
         '            (CALC.BDREFTOMADOR = VERBA.BDREFTOMADOR) and '||
         '            (CALC.BDREFFC = VERBA.BDREFFC) '||
         '      where '||wempresa||
         '            '||wcolaborador||
         '            CALC.BDCODACCONV = '||prcodadc||' and '||
         '            CALC.BDREFTOMADOR >= '||prrefini||' and '||
         '            CALC.BDREFTOMADOR <= '||prreffim||
         ') DADOS '||
         'group by DADOS.BDCODEMP, DADOS.BDCODCOL, DADOS.BDREFFC, DADOS.BDREFCOMP, DADOS.BDCODVER ';

 for execute statement wsql into
        :bdcodemp, :bdcodcol, :bdreffc, :bdrefcomp, :bdcodver, :bdrefauxvfn_sum, :bdrefvfn_sum, :bdrefvfn_max, :bdrefauxvfn_max, :bdvalvfn, :bdvalifn, :BDIGNREFAVFN, :BDIGNREFVFN,
        :BDIGNVALVFN, :BDORVERBAFC, :BDCOMPESP, :BDFORMREFAUX, :BDFORMREF, :BDFORMVAL, :bdreffn
 do
 begin
   /**/



    select first 1 verbas.bddescver, verbasref.BDTIPOCODVER, verbas.BDCLAVER, verbas.BDORDEMVER, verbasref.BDTIPOREFVER
    from VRH_BASE_TVERBAS verbas
    left join VRH_BASE_TVERBAS_REF verbasref on (verbasref.bdcodver = verbas.bdcodver) and (verbasref.bdrefver <= :prreffim)
    where (verbas.bdcodver = :bdcodver)
    into :wdescver, :wtipocodver, :wclaver, :wordemver, :wtiporefver;

    bddescver     = wdescver;
    bdtipocodver  = wtipocodver;
    bdclaver      = wclaver;
    bdordemver    = wordemver;
    bdtiporefver  = wtiporefver;

    suspend;
 end
end^



/* Restore proc. body: SPCODIMPGPSCOMPLEMENTAR */
create or alter procedure SPCODIMPGPSCOMPLEMENTAR (
    PRCODEMP varchar(32000),
    PRREF integer,
    PRREFPAG integer,
    PRREFFIM integer)
returns (
    BDCODEMP integer,
    BDCODTIPOFC integer,
    BDCODIMP integer,
    BDCODMATRIZ integer,
    BDEMPIMP integer,
    BDLIMITEISENCAO numeric(15,6))
as
declare variable WSQLCALC varchar(32000);
declare variable WSQLIMP varchar(3000);
declare variable WWHEREEMP varchar(3000);
BEGIN
  /* Procedure Text */
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
     wwhereemp = ' and '||prcodemp;

/*  wsqlcalc = 'select emp.bdcodemp,emp.bdcodtipofc from VRHF_EMP_TFOLHACOMP emp '||
             ' where emp.bdreffn = '||prref||' and emp.bdrefcomp = '||prrefpag||wwhereemp||
             ' union '||
             ' select emp.bdcodemp,emp.bdcodtipofc from VRHF_EMP_TFOLTOMCOMP emp '||
             ' where emp.bdreftomador = '||prref||' and emp.bdrefcomp = '||prrefpag||wwhereemp||
             ' union'||
             ' select emp.bdcodemp,emp.bdcodtipofc from VRHF_EMP_TFOLHACOMPINT emp '||
             ' where emp.bdreffn = '||prref||' and emp.bdrefcomp = '||prrefpag||wwhereemp||
             ' union'||
             ' select emp.bdcodemp,emp.bdcodtipofc from VRHF_EMP_TFOLTOMCOMPINT emp '||
             ' where emp.bdreftomador = '||prref||' and emp.bdrefcomp = '||prrefpag||wwhereemp;
*/
  wsqlcalc = 'select emp.bdcodemp,emp.bdcodtipofc from VRHF_EMP_TFOLHACOMP emp '||
             ' left outer join VRH_EMP_TACCONV ACCONV ON (emp.BDCODEMP = ACCONV.BDCODEMP AND emp.BDCODACCONV = ACCONV.BDCODACCONV)'||                          /* 158041 Leonardo Schwab 05/06/2023 */
             ' where ';

             IF (prref > 200001) THEN
                wsqlcalc = wsqlcalc||'emp.bdreffn >= '||prref||' and emp.bdreffn <= '||prreffim||' and ';

             wsqlcalc = wsqlcalc||'       ((EMP.BDCODTIPOFC <> 3 AND emp.bdrefcomp = '||prrefpag||') OR '||                                                                         /* 158041 Leonardo Schwab 05/06/2023 */
             '        (EMP.BDCODACCONV IS NOT NULL AND EMP.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = '||prrefpag||')) '||           /* 158041 Leonardo Schwab 05/06/2023 */
             wwhereemp||
             ' union '||
             ' select emp.bdcodemp,emp.bdcodtipofc from VRHF_EMP_TFOLTOMCOMP emp '||
             ' left outer join VRH_EMP_TACCONV ACCONV ON (emp.BDCODEMP = ACCONV.BDCODEMP AND emp.BDCODACCONV = ACCONV.BDCODACCONV)'||                          /* 158041 Leonardo Schwab 05/06/2023 */
             ' where ';

             IF (prref > 200001) THEN
                wsqlcalc = wsqlcalc||'emp.bdreftomador >= '||prref||' and emp.bdreftomador <= '||prreffim||' and ';

             wsqlcalc = wsqlcalc||'       ((EMP.BDCODTIPOFC <> 3 AND emp.bdrefcomp = '||prrefpag||') OR '||                                                                         /* 158041 Leonardo Schwab 05/06/2023 */
             '        (EMP.BDCODACCONV IS NOT NULL AND EMP.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = '||prrefpag||')) '||           /* 158041 Leonardo Schwab 05/06/2023 */
             wwhereemp||
             ' union'||
             ' select emp.bdcodemp,emp.bdcodtipofc from VRHF_EMP_TFOLHACOMPINT emp '||
             ' left outer join VRH_EMP_TACCONV ACCONV ON (emp.BDCODEMP = ACCONV.BDCODEMP AND emp.BDCODACCONV = ACCONV.BDCODACCONV)'||                          /* 158041 Leonardo Schwab 05/06/2023 */
             ' where ';

             IF (prref > 200001) THEN
                wsqlcalc = wsqlcalc||'emp.bdreffn >= '||prref||' and emp.bdreffn <= '||prreffim||' and ';

             wsqlcalc = wsqlcalc||'       ((EMP.BDCODTIPOFC <> 3 AND emp.bdrefcomp = '||prrefpag||') OR '||                                                                         /* 158041 Leonardo Schwab 05/06/2023 */
             '        (EMP.BDCODACCONV IS NOT NULL AND EMP.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = '||prrefpag||')) '||           /* 158041 Leonardo Schwab 05/06/2023 */
             wwhereemp||
             ' union'||
             ' select emp.bdcodemp,emp.bdcodtipofc from VRHF_EMP_TFOLTOMCOMPINT emp '||
             ' left outer join VRH_EMP_TACCONV ACCONV ON (emp.BDCODEMP = ACCONV.BDCODEMP AND emp.BDCODACCONV = ACCONV.BDCODACCONV)'||                          /* 158041 Leonardo Schwab 05/06/2023 */
             ' where ';

             IF (prref > 200001) THEN
                wsqlcalc = wsqlcalc||'emp.bdreftomador >= '||prref||' and emp.bdreftomador <= '||prreffim||' and ';

             wsqlcalc = wsqlcalc||'       ((EMP.BDCODTIPOFC <> 3 AND emp.bdrefcomp = '||prrefpag||') OR '||                                                                         /* 158041 Leonardo Schwab 05/06/2023 */
             '        (EMP.BDCODACCONV IS NOT NULL AND EMP.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = '||prrefpag||')) '||           /* 158041 Leonardo Schwab 05/06/2023 */
             wwhereemp;

  EXECUTE PROCEDURE sp_seta_competencia(:prrefpag,NULL,NULL);

  FOR EXECUTE STATEMENT wsqlcalc INTO bdcodemp, bdcodtipofc DO
    BEGIN
      bdcodimp = NULL;
      bdcodmatriz = NULL;
      bdempimp = NULL;

      /* Verifica se existe um imposto para GPS complementar de dissidio e convenção */
      IF ((COALESCE(bdcodtipofc,1)) <> 1) THEN
         BEGIN
           wsqlimp = ' select first 1 impemp.bdcodemp bdempimp, emp.bdcodmatriz, impemp.bdcodimp, IMP.BDLIMITEISENCAO '||
                     ' from tempresas emp '||
                     ' join vw_tempresaimpostoref impemp on ((impemp.bdcodemp in (emp.bdcodemp,emp.bdcodmatriz)) and impemp.BDDOCARRECADACAO = 12) '||
                     ' left outer join TIMPOSTO IMP on (IMP.BDCODIMP = impemp.bdcodimp) '||
                     ' where emp.bdcodemp = '||bdcodemp||' and impemp.BDGPSPRINCIPAL <> '||'''TRUE'''||' and impemp.BDTIPOIMPDOC = 23 ';

           EXECUTE STATEMENT wsqlimp INTO bdempimp,bdcodmatriz,bdcodimp,bdlimiteisencao;

           IF (bdcodimp = 0) THEN
              bdcodimp = NULL;
         END

      /* Verifica o codigo da gps padrao */
      IF (bdcodimp IS NULL) THEN
         BEGIN
           wsqlimp = ' select first 1 impemp.bdcodemp bdempimp, emp.bdcodmatriz, impemp.bdcodimp, IMP.BDLIMITEISENCAO '||
                     ' from tempresas emp '||
                     ' join vw_tempresaimpostoref impemp on ((impemp.bdcodemp in (emp.bdcodemp,emp.bdcodmatriz)) and impemp.BDDOCARRECADACAO = 12) '||
                     ' left outer join TIMPOSTO IMP on (IMP.BDCODIMP = impemp.BDCODIMP) '||
                     ' where emp.bdcodemp = '||bdcodemp||' and impemp.BDGPSPRINCIPAL = '||'''TRUE''';

           EXECUTE STATEMENT wsqlimp INTO bdempimp,bdcodmatriz,bdcodimp,bdlimiteisencao;

           IF (bdcodimp = 0) THEN
              bdcodimp = NULL;
         END


      IF (bdcodimp IS NOT NULL) THEN
         SUSPEND;
    END

--  suspend;
END^


/* Restore proc. body: SPCODIMPGPSCOMPLEMENTAR_ESOCIAL */
create or alter procedure SPCODIMPGPSCOMPLEMENTAR_ESOCIAL (
    PRCODEMP varchar(32000),
    PRREFCOMP integer,
    PRPUXARFILIAL integer)
returns (
    BDCODEMP integer,
    BDCODTIPOFC integer,
    BDCODIMP integer,
    BDCODMATRIZ integer,
    BDEMPIMP integer,
    BDLIMITEISENCAO numeric(15,6))
as
declare variable WSQLCALC varchar(32000);
declare variable WSQLIMP varchar(3000);
declare variable WWHEREEMP varchar(3000);
BEGIN
  /* Procedure Text */
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
    BEGIN
      if (prpuxarfilial = 0) then
     wwhereemp = ' and '||prcodemp;
      else
      if (prpuxarfilial = 1) then
        wwhereemp = ' and '||' EMP.BDCODEMP in (select BDCODEMP from TEMPRESAS where BDCODEMP = '||prcodemp||' or BDCODMATRIZ = '||prcodemp||') ';
    END

  wsqlcalc = 'select emp.bdcodemp,emp.bdcodtipofc from VRHF_EMP_TFOLHACOMP emp '||
             ' left outer join VRH_EMP_TACCONV AC on AC.BDCODEMP = EMP.BDCODEMP and AC.BDCODACCONV = EMP.BDCODACCONV '||
             ' where ((emp.bdreffn = '||prrefcomp||' and emp.bdcodacconv is null) or '||
             '       ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = '||prrefcomp||' and emp.bdcodacconv is not null))'||wwhereemp||
             ' union '||
             ' select emp.bdcodemp,emp.bdcodtipofc from VRHF_EMP_TFOLTOMCOMP emp '||
             ' left outer join VRH_EMP_TACCONV AC on AC.BDCODEMP = EMP.BDCODEMP and AC.BDCODACCONV = EMP.BDCODACCONV '||
             ' where ((emp.bdreftomador = '||prrefcomp||' and emp.bdcodacconv is null) or ' ||
             '       ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = '||prrefcomp||' and emp.bdcodacconv is not null))'||wwhereemp||
             ' union'||
             ' select emp.bdcodemp,emp.bdcodtipofc from VRHF_EMP_TFOLHACOMPINT emp '||
             ' left outer join VRH_EMP_TACCONV AC on AC.BDCODEMP = EMP.BDCODEMP and AC.BDCODACCONV = EMP.BDCODACCONV '||
             ' where ((emp.bdreffn = '||prrefcomp||' and emp.bdcodacconv is null) or ' ||
             '       ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = '||prrefcomp||' and emp.bdcodacconv is not null))'||wwhereemp||
             ' union'||
             ' select emp.bdcodemp,emp.bdcodtipofc from VRHF_EMP_TFOLTOMCOMPINT emp '||
             ' left outer join VRH_EMP_TACCONV AC on AC.BDCODEMP = EMP.BDCODEMP and AC.BDCODACCONV = EMP.BDCODACCONV '||
             ' where ((emp.bdreftomador = '||prrefcomp||' and emp.bdcodacconv is null) or '||
             '       ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = '||prrefcomp||' and emp.bdcodacconv is not null))'||wwhereemp;

  EXECUTE PROCEDURE sp_seta_competencia(:PRREFCOMP,NULL,NULL);

  FOR EXECUTE STATEMENT wsqlcalc INTO bdcodemp, bdcodtipofc DO
    BEGIN
      bdcodimp = NULL;
      bdcodmatriz = NULL;
      bdempimp = NULL;

      /* Verifica se existe um imposto para GPS complementar de dissidio e convenção */
      IF ((COALESCE(bdcodtipofc,1)) <> 1) THEN
         BEGIN
           wsqlimp = ' select first 1 impemp.bdcodemp bdempimp, emp.bdcodmatriz, impemp.bdcodimp, IMP.BDLIMITEISENCAO '||
                     ' from tempresas emp '||
                     ' join vw_tempresaimpostoref impemp on ((impemp.bdcodemp in (emp.bdcodemp,emp.bdcodmatriz)) and impemp.BDDOCARRECADACAO = 12) '||
                     ' left outer join TIMPOSTO IMP on (IMP.BDCODIMP = impemp.bdcodimp) '||
                     ' where emp.bdcodemp = '||bdcodemp||' and impemp.BDGPSPRINCIPAL <> '||'''TRUE'''||' and impemp.BDTIPOIMPDOC = 23 ';

           EXECUTE STATEMENT wsqlimp INTO bdempimp,bdcodmatriz,bdcodimp,bdlimiteisencao;

           IF (bdcodimp = 0) THEN
              bdcodimp = NULL;
         END

      /* Verifica o codigo da gps padrao */
      IF (bdcodimp IS NULL) THEN
         BEGIN
           wsqlimp = ' select first 1 impemp.bdcodemp bdempimp, emp.bdcodmatriz, impemp.bdcodimp, IMP.BDLIMITEISENCAO '||
                     ' from tempresas emp '||
                     ' join vw_tempresaimpostoref impemp on ((impemp.bdcodemp in (emp.bdcodemp,emp.bdcodmatriz)) and impemp.BDDOCARRECADACAO = 12) '||
                     ' left outer join TIMPOSTO IMP on (IMP.BDCODIMP = impemp.BDCODIMP) '||
                     ' where emp.bdcodemp = '||bdcodemp||' and impemp.BDGPSPRINCIPAL = '||'''TRUE''';

           EXECUTE STATEMENT wsqlimp INTO bdempimp,bdcodmatriz,bdcodimp,bdlimiteisencao;

           IF (bdcodimp = 0) THEN
              bdcodimp = NULL;
         END


      IF (bdcodimp IS NOT NULL) THEN
         SUSPEND;
    END

--  suspend;
END^

/* Restore proc. body: SPCORACENTOS */
ALTER PROCEDURE SPCORACENTOS(PRTXT VARCHAR(1000))
 RETURNS(BDTXT VARCHAR(1000))
 AS
BEGIN
  /* Procedure Text */

  -- Caracteres especiais estão em hex pois daí não falha na validação se o arquivo é ANSI
  bdtxt = REPLACE(prtxt, x'C3A7C3A3', 'çã');
  bdtxt = REPLACE(bdtxt, x'C3B3', 'ó');
  bdtxt = REPLACE(bdtxt, x'C3A3', 'ã');
  bdtxt = REPLACE(bdtxt, x'C3AD', 'í');
  bdtxt = REPLACE(bdtxt, x'C3A9', 'é');
  bdtxt = REPLACE(bdtxt, x'C3AA', 'ê');
  bdtxt = REPLACE(bdtxt, x'C2BA', 'º');
  bdtxt = REPLACE(bdtxt, x'C3A1', 'á');
  bdtxt = REPLACE(bdtxt, x'C3BA', 'ú');
  bdtxt = REPLACE(bdtxt, x'C3A7', 'ç');

  SUSPEND;
END
^

/* Restore proc. body: SPCORRIGEACENTOS */
ALTER PROCEDURE SPCORRIGEACENTOS AS
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WNOME VARCHAR(1000);
DECLARE VARIABLE WDESC VARCHAR(1000);
DECLARE VARIABLE WFIELD VARCHAR(1000);
BEGIN
  /* Procedure Text */
  wsql = 'select rdb$relation_name "NOME", rdb$description "DESC" from rdb$relations'||
         ' where rdb$description is not null';

  FOR EXECUTE STATEMENT wsql INTO
    wnome,
    wdesc
  DO
    BEGIN
      SELECT bdtxt FROM SPCORACENTOS(:wdesc) INTO wdesc;
      wSQL =  'comment on table '||Trim(:wNome)||' is '||''''||replace(:wDesc,'''','''''')||'''';
      execute statement wSQL;
    END

  wsql = 'select RDB$FIELD_NAME,RDB$RELATION_NAME,rdb$description from RDB$RELATION_FIELDS'||
         ' where rdb$description is not null';

  FOR EXECUTE STATEMENT wsql INTO
    wfield,
    wnome,
    wdesc
  DO
    BEGIN
      SELECT bdtxt FROM SPCORACENTOS(:wdesc) INTO wdesc;
      wSQL =  'comment on column '||Trim(:wNome)||'.'||Trim(:wField)||' is '||''''||:wDesc||'''';
      execute statement wSQL;
    END

--  suspend;
END
^

/* Restore proc. body: SPRH_CALC_13SALARIO */
create or alter procedure SPRH_CALC_13SALARIO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFERENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFV_MAX numeric(15,6),
    BDREFV_SUM numeric(15,6),
    BDREFAUXV_MAX numeric(15,6),
    BDREFAUXV_SUM numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNREFAV varchar(5),
    BDIGNVALV varchar(5),
    BDORVERBA integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDALTINT boolean,
    BDBASEIR13BRUTARED DM_NUMERIC_15_2,
    BDVALORIR13BRUTARED DM_NUMERIC_15_2,
    BDVALOR13RED DM_NUMERIC_15_2)
as
declare variable WSQL varchar(32700);
declare variable WEMPREF DM_BOOLEAN;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIA, NULL, NULL);

  wsql = 'select ';
  wsql = wsql||'S13.BDCODEMP, '||
               'S13.BDCODCOL, '||
               'S13.BDCODVER, '||
               'S13.BDREF13, '||
               'S13.BDREFV13, '||
               'S13.BDREFV13, '||
               'S13.BDREFAUXV13, '||
               'S13.BDREFAUXV13, '||
               'S13.BDVALV13, '||
               'S13.BDIGNREFV13, '||
               'S13.BDIGNREFAV13, '||
               'S13.BDIGNVALV13, '||
               'S13.BDORVERBA13, '||
               'S13.BDALTINT, '||
               'FS13.BDDATABAIXA13, '||
               'FS13.BDBASEFGTS13, '||
               'FS13.BDFGTS13, '||
               'FS13.BDFGTSCS13, '||
               '0.0 BDBFGTS13_, '||
               '0.0 BDFGTS13_, '||
               '0.0 BDFGTSCS13_, '||
               '0.0 BDMAIORREM13, '||
               'FS13.BDBASEINSS13, '||
               'FS13.BDPERCINSS13, '||
               'FS13.BDVALORINSS13, '||
               'FS13.BDBASEIR13, '||
               'FS13.BDPERCIR13, '||
               'FS13.BDVALORIR13, '||
               '0.0 BDBINSS1313, '||
               '0.0 BDALIQINSS1313, '||
               '0.0 BDINSS1313, '||
               '0.0 BDBASEIR1313, '||
               '0.0 BDPERCIR1313, '||
               '0.0 BDVALORIR1313, '||
               '0.0 BDBSALFAM1313, '||
               '0.0 BDSALFAM1313, '||
               'FS13.BDBRAIS13, '||
               'FS13.BDSALBASE13, '||
               'FS13.BDDEP13, '||
               '0.0 BDAPE01, '||
               '0.0 BDAPE02, '||
               '0.0 BDAPE03, '||
               'FS13.BDCREDITO13, '||
               'FS13.BDDEBITO13, '||
               'S13.BDCOMPESP, '||
               'S13.BDFORMREFAUX, '||
               'S13.BDFORMREF, '||
               'S13.BDFORMVAL, '||
               'FS13.BDBASEIR13BRUTARED, '||
               'FS13.BDVALORIR13BRUTARED, '||
               'FS13.BDVALOR13RED ';

  wsql = wsql||'from VRHF_EMP_TVERBA13 S13 '||
               'join VRHF_EMP_T13SAL FS13 on (S13.BDCODEMP = FS13.BDCODEMP and S13.BDCODCOL = FS13.BDCODCOL and S13.BDREF13 = FS13.BDREF13) ';

  wsql = wsql||'where S13.BDCODEMP = '||PRCODEMP||' and S13.BDCODCOL = '||PRCODCOL||' and S13.BDREF13 = '||PRREFERENCIA;
--  wsql = wsql||' order by RVA.BDTIPOCODVER, S13.BDCODVER ';

  wempref = null;
  select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = :prcodemp and BDREFEMP <= :prreferencia order by BDCODEMP desc, BDREFEMP desc into :wempref;

  wempref = upper(coalesce(wempref, 'FALSE'));

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFV_MAX,
    :BDREFV_SUM,
    :BDREFAUXV_MAX,
    :BDREFAUXV_SUM,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNREFAV,
    :BDIGNVALV,
    :BDORVERBA,
    :BDALTINT,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDCREDITO,
    :BDDEBITO,
    :BDCOMPESP,
    :BDFORMREFAUX,
    :BDFORMREF,
    :BDFORMVAL,
    :BDBASEIR13BRUTARED,
    :BDVALORIR13BRUTARED,
    :BDVALOR13RED
  DO
    begin
      BDREFHOREMP = :wempref;
      SUSPEND;
    end

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

/* Restore proc. body: SPRH_CALC_AD13SALARIO */
create or alter procedure SPRH_CALC_AD13SALARIO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFERENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFV_MAX numeric(15,6),
    BDREFV_SUM numeric(15,6),
    BDREFAUXV_MAX numeric(15,6),
    BDREFAUXV_SUM numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNREFAV varchar(5),
    BDIGNVALV varchar(5),
    BDORVERBA integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDALTINT boolean)
as
declare variable WSQL varchar(32700);
declare variable WREFEMP DM_BOOLEAN;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIA, NULL, NULL);

  wsql = 'select ';
  wsql = wsql||'A13.BDCODEMP, '||
               'A13.BDCODCOL, '||
               'A13.BDCODVER, '||
               'A13.BDREFA13, '||
               'A13.BDREFVA13, '||
               'A13.BDREFVA13, '||
               'A13.BDREFAUXVA13, '||
               'A13.BDREFAUXVA13, '||
               'A13.BDVALVA13, '||
               'A13.BDIGNREFVA13, '||
               'A13.BDIGNREFAVA13, '||
               'A13.BDIGNVALVA13, '||
               'A13.BDORVERBAA13, '||
               'A13.BDALTINT, '||
               'FA13.BDDATABAIXAA13, '||
               '0.0 BDBFGTSA13, '||
               '0.0 BDFGTSA13, '||
               '0.0 BDFGTSCSA13, '||
               'FA13.BDBASEFGTSA13, '||
               'FA13.BDFGTSA13, '||
               'FA13.BDFGTSCSA13, '||
               '0.0 BDMAIORREMA13, '||
               '0.0 BDBINSSA13, '||
               '0.0 BDALIQINSSA13, '||
               '0.0 BDINSSA13, '||
               '0.0 BDBIRRFA13, '||
               '0.0 BDALIQIRRFA13, '||
               '0.0 BDIRRFA13, '||
               '0.0 BDBINSS13A13, '||
               '0.0 BDALIQINSS13A13, '||
               '0.0 BDINSS13A13, '||
               'FA13.BDBASEIRA13, '||
               'FA13.BDPERCIRA13, '||
               'FA13.BDVALORIRA13, '||
               'FA13.BDBSALFAMA13, '||
               'FA13.BDSALFAMA13, '||
               'FA13.BDBRAISA13, '||
               'FA13.BDSALBASEA13, '||
               'FA13.BDDEPA13, '||
               '0.0 BDAPE01, '||
               '0.0 BDAPE02, '||
               '0.0 BDAPE03, '||
               'FA13.BDCREDITOA13, '||
               'FA13.BDDEBITOA13, '||
               'A13.BDCOMPESP, '||
               'A13.BDFORMREFAUX, '||
               'A13.BDFORMREF, '||
               'A13.BDFORMVAL ';

  wsql = wsql||'from VRHF_EMP_TVERBAA13 A13 '||
               'join VRHF_EMP_TA13SAL FA13 on (A13.BDCODEMP = FA13.BDCODEMP and A13.BDCODCOL = FA13.BDCODCOL and A13.BDREFA13 = FA13.BDREFA13) ';

  wsql = wsql||'where A13.BDCODEMP = '||PRCODEMP||' and A13.BDCODCOL = '||PRCODCOL||' and A13.BDREFA13 = '||PRREFERENCIA;
--  wsql = wsql||' order by RVA.BDTIPOCODVER, A13.BDCODVER ';

  wrefemp = null;
  select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = :prcodemp and BDREFEMP <= :prreferencia order by BDCODEMP desc, BDREFEMP desc into :wrefemp;
  wrefemp = upper(coalesce(wrefemp, 'FALSE'));

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFV_MAX,
    :BDREFV_SUM,
    :BDREFAUXV_MAX,
    :BDREFAUXV_SUM,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNREFAV,
    :BDIGNVALV,
    :BDORVERBA,
    :BDALTINT,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDCREDITO,
    :BDDEBITO,
    :BDCOMPESP,
    :BDFORMREFAUX,
    :BDFORMREF,
    :BDFORMVAL
  DO
    begin
      BDREFHOREMP = wrefemp;
      SUSPEND;
    end

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

/* Restore proc. body: SPRH_CALC_ADSAL */
create or alter procedure SPRH_CALC_ADSAL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFERENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDDATAAD date,
    BDREFV_MAX numeric(15,6),
    BDREFV_SUM numeric(15,6),
    BDREFAUXV_MAX numeric(15,6),
    BDREFAUXV_SUM numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNREFAV varchar(5),
    BDIGNVALV varchar(5),
    BDORVERBA integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDALTINT boolean)
as
declare variable WSQL varchar(32700);
declare variable WREFEMP DM_BOOLEAN;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIA, NULL, NULL);

  wsql = 'select ';
  wsql = wsql||'ASAL.BDCODEMP, '||
               'ASAL.BDCODCOL, '||
               'ASAL.BDCODVER, '||
               'FASAL.BDREFAD, '||
               'ASAL.BDDATAAD, '||
               'ASAL.BDREFVAD, '||
               'ASAL.BDREFVAD, '||
               'ASAL.BDREFAUXVAD, '||
               'ASAL.BDREFAUXVAD, '||
               'ASAL.BDVALVAD, '||
               'ASAL.BDIGNREFVAD, '||
               'ASAL.BDIGNREFAVAD, '||
               'ASAL.BDIGNVALVAD, '||
               'ASAL.BDORVERBAAD, '||
               'ASAL.BDALTINT, '||
               'FASAL.BDDATABAIXAAD, '||
               '0.0 BDBFGTSA13, '||
               '0.0 BDFGTSA13, '||
               '0.0 BDFGTSCSA13, '||
               '0.0 BDBASEFGTSA13, '||
               '0.0 BDFGTSA13, '||
               '0.0 BDFGTSCSA13, '||
               '0.0 BDMAIORREMA13, '||
               '0.0 BDBINSSA13, '||
               '0.0 BDALIQINSSA13, '||
               '0.0 BDINSSA13, '||
               'FASAL.BDBASEIRAD, '||
               'FASAL.BDPERCIRAD, '||
               'FASAL.BDVALORIRAD, '||
               '0.0 BDBINSS13A13, '||
               '0.0 BDALIQINSS13A13, '||
               '0.0 BDINSS13A13, '||
               '0.0 BDBIRRFA13, '||
               '0.0 BDALIQIRRFA13, '||
               '0.0 BDIRRFA13, '||
               '0.0 BDBSALFAMA13, '||
               '0.0 BDSALFAMA13, '||
               '0.0 BDBRAISA13, '||
               'FASAL.BDSALBASEAD, '||
               'FASAL.BDDEPIRAD, '||
               '0.0 BDAPE01, '||
               '0.0 BDAPE02, '||
               '0.0 BDAPE03, '||
               'FASAL.BDCREDITOAD, '||
               'FASAL.BDDEBITOAD, '||
               'ASAL.BDCOMPESP, '||
               'ASAL.BDFORMREFAUX, '||
               'ASAL.BDFORMREF, '||
               'ASAL.BDFORMVAL ';

  wsql = wsql||'from VRHF_EMP_TVERBAAD ASAL '||
               'join VRHF_EMP_TADSAL FASAL on (FASAL.BDCODEMP = ASAL.BDCODEMP and FASAL.BDCODCOL = ASAL.BDCODCOL and FASAL.BDDATAAD = ASAL.BDDATAAD) ';

  wsql = wsql||'where ASAL.BDCODEMP = '||PRCODEMP||' and ASAL.BDCODCOL = '||PRCODCOL||' and FASAL.BDREFAD = '||PRREFERENCIA;
--  wsql = wsql||' order by RVA.BDTIPOCODVER, A13.BDCODVER ';

  wrefemp = null;
  select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = :prcodemp and BDREFEMP <= :prreferencia order by BDCODEMP desc, BDREFEMP desc into :wrefemp;
  wrefemp = upper(coalesce(wrefemp, 'FALSE'));

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDDATAAD,
    :BDREFV_MAX,
    :BDREFV_SUM,
    :BDREFAUXV_MAX,
    :BDREFAUXV_SUM,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNREFAV,
    :BDIGNVALV,
    :BDORVERBA,
    :BDALTINT,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDCREDITO,
    :BDDEBITO,
    :BDCOMPESP,
    :BDFORMREFAUX,
    :BDFORMREF,
    :BDFORMVAL
  DO
    begin
      BDREFHOREMP = wrefemp;
      SUSPEND;
    end

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

/* Restore proc. body: SPRH_CALC_AUTONOMO */
create or alter procedure SPRH_CALC_AUTONOMO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFERENCIA integer,
    PRCODSERV integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFV_MAX numeric(15,6),
    BDREFV_SUM numeric(15,6),
    BDREFAUXV_MAX numeric(15,6),
    BDREFAUXV_SUM numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNREFAV varchar(5),
    BDIGNVALV varchar(5),
    BDORVERBA integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDBASEINSSNMVNOVO numeric(18,6),
    BDINCIRVER integer,
    BDTIPOCODVER integer,
    BDBASEIRBRUTO numeric(17,4),
    BDALTINT boolean,
    BDBASEIRBRUTARED DM_NUMERIC_15_2,
    BDBASEIR13BRUTARED DM_NUMERIC_15_2,
    BDVALORIRBRUTARED DM_NUMERIC_15_2,
    BDVALORIR13BRUTARED DM_NUMERIC_15_2,
    BDVALORRED DM_NUMERIC_15_2,
    BDVALOR13RED DM_NUMERIC_15_2)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(20000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIA, NULL, NULL);
  wsql = 'select ';
/*01*/  wsql = wsql||'FN.BDCODEMP, '||
/*02*/               'FN.BDCODTER, '||
/*03*/               'FN.BDCODVER, '||
/*04*/               'FN.BDCODSERV, '||
/*05*/               'FN.BDREFERENCIA, '||
                     'FN.BDREFERENCIA, '||
/*06*/               'FN.BDREFAUXILIAR, '||
                     'FN.BDREFAUXILIAR, '||
/*07*/               'FN.BDVALOR, '||
/*08*/               'FN.BDIGNFORREF, '||
                     'FN.BDIGNFORREFA, '||
/*09*/               'FN.BDIGNFORVAL, '||
                     'FN.BDORVERBATERC, '||
                     'FN.BDALTINT, '||
/*40*/               'EMPREF.BDREFHOREMP, '||
/*41*/               'SERV.BDDATABAIXA,'||/*'FOLN.BDDATABAIXAFN, '|| CRIAR CAMPO TABELA*/
/*42*/               '0.0, '|| /*FOLN.BDBFGTSFN*/
/*43*/               '0.0, '|| /*FOLN.BDFGTSFN*/
/*44*/               '0.0, '|| /*FOLN.BDFGTSCSFN*/
/*45*/               '0.0, '|| /*FOLN.BDBFGTS13FN*/
/*46*/               '0.0, '|| /*FOLN.BDFGTS13FN*/
/*47*/               '0.0, '|| /*FOLN.BDFGTS13CSFN*/
/*48*/               '0.0, '|| /*FOLN.BDMAIORREMFN*/
/*49*/               'FOLN.BDBASEINSS, '||
/*50*/               'FOLN.BDFAIXAINSS, '||
/*51*/               'FOLN.BDVALORINSS, '||
/*52*/               'FOLN.BDBASEIR, '||
/*53*/               'FOLN.BDFAIXAIR, '||
/*54*/               'FOLN.BDVALORIR, '||
/*55*/               '0.0, '|| /*FOLN.BDBINSS13FN*/
/*56*/               '0.0, '|| /*FOLN.BDALIQINSS13FN*/
/*57*/               '0.0, '|| /*FOLN.BDINSS13FN*/
/*58*/               '0.0, '|| /*FOLN.BDBIRRF13FN*/
/*59*/               '0.0, '|| /*FOLN.BDALIQIRRF13FN*/
/*60*/               '0.0, '|| /*FOLN.BDIRRF13FN*/
/*61*/               '0.0, '|| /*FOLN.BDBSALFAMFN*/
/*62*/               '0.0, '|| /*FOLN.BDSALFAMFN*/
/*63*/               '0.0, '|| /*FOLN.BDBRAISFN*/
/*64*/               'SERV.BDVALORSERV, '||
/*65*/               'FOLN.BDVALORDEP, '||
/*67*/               '0.0, '|| /*FOLN.BDBINSSFEFOLFN*/
/*68*/               '0.0, '|| /*FOLN.BDINSSFEFOLFN*/
/*69*/               '0.0, '|| /*FOLN.BDALIQINSSFEFOLFN*/
/*70*/               'FOLN.BDCREDITOSERV, '||
/*71*/               'FOLN.BDDEBITOSERV, '||
                     'FN.BDCOMPESP, '||
                     'FN.BDFORMREFAUX, '||
                     'FN.BDFORMREF, '||
                     'FN.BDFORMVAL, '||
                     'FOLN.BDBASEINSSNMVNOVO, '||
                     'VREF.BDIRVER, '||
                     'VREF.BDTIPOCODVER, '||
                     'mva.BDBASEBRUTAIR, '||
                     'FOLN.BDBASEIRBRUTARED, '||
                     'FOLN.BDBASEIR13BRUTARED, '||
                     'FOLN.BDVALORIRBRUTARED, '||
                     'FOLN.BDVALORIR13BRUTARED, '||
                     'FOLN.BDVALORRED, '||
                     'FOLN.BDVALOR13RED ';

  wsql = wsql||'from VRHF_BASE_ITEMS_CALCTERC FN '; /*OK*/
  wsql = wsql||' join VRH_BASE_TSERVTERC SERV on (SERV.BDCODEMP = FN.BDCODEMP and SERV.BDCODTER = FN.BDCODTER and SERV.BDCODSERV = FN.BDCODSERV) ';
  wsql = wsql||' join VW_VRHF_EMPRESAS_REF_ATUAL EMPREF on (EMPREF.BDCODEMP = FN.BDCODEMP) ';
  wsql = wsql||' join VRHF_BASE_CALC_TERC FOLN on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODTER = FN.BDCODTER and FOLN.BDCODSERV = FN.BDCODSERV) ';
  wsql = wsql||' join VRH_BASE_TVERBAS_REF VREF on (VREF.BDCODVER = FN.BDCODVER and VREF.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF ';
  wsql = wsql||'                        where BDCODVER = VREF.BDCODVER and ';
  wsql = wsql||'                              BDREFVER <=  '||prreferencia||')   ) ';

  wsql = wsql||' join VRHF_EMP_MV_AUT_CALC mva on (mva.bdcodemp = FN.BDCODEMP and mva.bdcodter = FN.BDCODTER and mva.bdcodcontrato = FN.BDCODSERV) ';
  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wwhere = wwhere||' where FN.BDCODEMP = '||PRCODEMP;

  IF (prcodcol IS NOT NULL AND prcodcol <> 0) THEN
     wwhere = wwhere||' and FN.BDCODTER = '||PRCODCOL;

  IF (prcodserv IS NOT NULL AND prcodserv <> 0) THEN
     wwhere = wwhere||' and FN.BDCODSERV = '||prcodserv;

  IF (prreferencia IS NOT NULL AND prreferencia <> 0) THEN
     wwhere = wwhere||' and (select bdaaaamm from aaaamm(SERV.bddataserv) ) = '||prreferencia;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFV_MAX,
    :BDREFV_SUM,
    :BDREFAUXV_MAX,
    :BDREFAUXV_SUM,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNREFAV,
    :BDIGNVALV,
    :BDORVERBA,
    :BDALTINT,
    :BDREFHOREMP,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDCREDITO,
    :BDDEBITO,
    :BDCOMPESP,
    :BDFORMREFAUX,
    :BDFORMREF,
    :BDFORMVAL,
    :BDBASEINSSNMVNOVO,
    :BDINCIRVER,
    :BDTIPOCODVER,
    :BDBASEIRBRUTO,
    :BDBASEIRBRUTARED,
    :BDBASEIR13BRUTARED,
    :BDVALORIRBRUTARED,
    :BDVALORIR13BRUTARED,
    :BDVALORRED,
    :BDVALOR13RED
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(:prreferencia, NULL, NULL);
END^


/* Restore proc. body: SPRH_CALC_COMP13SALARIO */
create or alter procedure SPRH_CALC_COMP13SALARIO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFERENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFV_MAX numeric(15,6),
    BDREFV_SUM numeric(15,6),
    BDREFAUXV_MAX numeric(15,6),
    BDREFAUXV_SUM numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNREFAV varchar(5),
    BDIGNVALV varchar(5),
    BDORVERBA integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDALTINT boolean,
    BDBASEIR13BRUTARED DM_NUMERIC_15_2,
    BDVALORIR13BRUTARED DM_NUMERIC_15_2,
    BDVALOR13RED DM_NUMERIC_15_2)
as
declare variable WSQL varchar(32700);
declare variable WREFEMP DM_BOOLEAN;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIA, NULL, NULL);

  wsql = 'select ';
  wsql = wsql||'C13.BDCODEMP, '||
               'C13.BDCODCOL, '||
               'C13.BDCODVER, '||
               'C13.BDREFC13, '||
               'C13.BDREFVC13, '||
               'C13.BDREFVC13, '||
               'C13.BDREFAUXVC13, '||
               'C13.BDREFAUXVC13, '||
               'C13.BDVALVC13, '||
               'C13.BDIGNREFVC13, '||
               'C13.BDIGNREFAVC13, '||
               'C13.BDIGNVALVC13, '||
               'C13.BDORVERBAC13, '||
               'C13.BDALTINT, '||
               'FC13.BDDATABAIXAC13, '||
               'FC13.BDBASEFGTSC13, '||
               'FC13.BDFGTSC13, '||
               'FC13.BDFGTSCSC13, '||
               '0.0 BDBFGTS13_, '||
               '0.0 BDFGTS13_, '||
               '0.0 BDFGTSCS13_, '||
               '0.0 BDMAIORREM13, '||
               'FC13.BDBASEINSSC13, '||
               'FC13.BDPERCINSSC13, '||
               'FC13.BDVALORINSSC13, '||
               'FC13.BDBASEIRC13, '||
               'FC13.BDPERCIRC13, '||
               'FC13.BDVALORIRC13, '||
               '0.0 BDBINSS1313, '||
               '0.0 BDALIQINSS1313, '||
               '0.0 BDINSS1313, '||
               '0.0 BDBASEIR1313, '||
               '0.0 BDPERCIR1313, '||
               '0.0 BDVALORIR1313, '||
               'BDBSALFAMC13, '||
               'BDSALFAMC13, '||
               'FC13.BDBRAISC13, '||
               'FC13.BDSALBASEC13, '||
               'S13.BDDEP13, '||
               '0.0 BDAPE01, '||
               '0.0 BDAPE02, '||
               '0.0 BDAPE03, '||
               'FC13.BDCREDITOC13, '||
               'FC13.BDDEBITOC13, '||
               'C13.BDCOMPESP, '||
               'C13.BDFORMREFAUX, '||
               'C13.BDFORMREF, '||
               'C13.BDFORMVAL, '||
               'FC13.BDBASEIR13BRUTARED, '||
               'FC13.BDVALORIR13BRUTARED, '||
               'FC13.BDVALOR13RED ';

  wsql = wsql||'from VRHF_EMP_TVERBAC13 C13 '||
               'join VRHF_EMP_TC13SAL FC13 on (FC13.BDCODEMP = C13.BDCODEMP and FC13.BDCODCOL = C13.BDCODCOL and FC13.BDREFC13 = C13.BDREFC13 and FC13.BDREF13 = C13.BDREF13) '||
               'join VRHF_EMP_T13SAL S13 on (S13.BDCODEMP = C13.BDCODEMP and S13.BDCODCOL = C13.BDCODCOL and S13.BDREF13 = C13.BDREF13) ';

  wsql = wsql||'where C13.BDCODEMP = '||PRCODEMP||' and C13.BDCODCOL = '||PRCODCOL||' and C13.BDREFC13 = '||PRREFERENCIA;
--  wsql = wsql||' order by RVA.BDTIPOCODVER, C13.BDCODVER ';

  wrefemp = null;
  select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = :prcodemp and BDREFEMP <= :prreferencia order by BDCODEMP desc, BDREFEMP desc into :wrefemp;
  wrefemp = upper(coalesce(wrefemp, 'FALSE'));

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFV_MAX,
    :BDREFV_SUM,
    :BDREFAUXV_MAX,
    :BDREFAUXV_SUM,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNREFAV,
    :BDIGNVALV,
    :BDORVERBA,
    :BDALTINT,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDCREDITO,
    :BDDEBITO,
    :BDCOMPESP,
    :BDFORMREFAUX,
    :BDFORMREF,
    :BDFORMVAL,
    :BDBASEIR13BRUTARED,
    :BDVALORIR13BRUTARED,
    :BDVALOR13RED
  DO
    begin
      BDREFHOREMP = wrefemp;
      SUSPEND;
    end

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

/* Restore proc. body: SPRH_CALC_FERIAS */
create or alter procedure SPRH_CALC_FERIAS (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRCODFE integer,
    PRINIPERAQUISFE date,
    PRREFERENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFV_MAX numeric(15,6),
    BDREFV_SUM numeric(15,6),
    BDREFAUXV_MAX numeric(15,6),
    BDREFAUXV_SUM numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNREFAV varchar(5),
    BDIGNVALV varchar(5),
    BDORVERBA integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDDETALHE varchar(255),
    BDREFFN integer,
    BDCODFE integer,
    BDINIPERAQUISFE date,
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDBASEIROUT numeric(15,6),
    BDVALORIROUT numeric(15,6),
    BDDEPIROUT numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDALTINT boolean,
    BDBASEIRBRUTARED DM_NUMERIC_15_2,
    BDVALORIRBRUTARED DM_NUMERIC_15_2,
    BDVALORRED DM_NUMERIC_15_2)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(15000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIA, NULL, NULL);

  wsql = 'select ';
  wsql = wsql||'FE.BDCODEMP, '||
               'FE.BDCODCOL, '||
               'FE.BDCODVER, '||
               'FE.BDREFVFE, '||
               'FE.BDREFVFE, '||
               'FE.BDREFAUXVFE, '||
               'FE.BDREFAUXVFE, '||
               'FE.BDVALVFE, '||
               'FE.BDIGNREFVFE, '||
               'FE.BDIGNREFAVFE, '||
               'FE.BDIGNVALVFE, '||
               'FE.BDORVERBAFE, '||
               'FE.BDALTINT, '||
               'EMPREF.BDREFHOREMP, '||
               'FE.BDDATABAIXAFE, '||
               'FE.BDBASEFGTSFE, '||
               'FE.BDVALORFGTSFE, '||
               'FE.BDVALORFGTSCSFE, '||
               'FE.BDBFGTS13, '||
               'FE.BDFGTS13, '||
               '0.0 BDAPE03, '||
               'FE.BDMAIORREMFE, '||
               'FE.BDBASEINSSFE, '||
               'FE.BDALIQINSSFE, '||
               'FE.BDVALORINSSFE, '||
               'FE.BDBASEIRFE, '||
               'FE.BDALIQIRFE, '||
               'FE.BDVALORIRFE, '||
               '0.0 BDAPE04, '||
               '0.0 BDAPE05, '||
               '0.0 BDAPE06, '||
               '0.0 BDAPE07, '||
               '0.0 BDAPE08, '||
               '0.0 BDAPE09, '||
               'FE.BDBSALFAMFE, '||
               'FE.BDSALFAMFE, '||
               '0.0 BDAPE10, '||
               'FE.BDSALBASEFE, '||
               'FE.BDDEPFE, '||
               'FE.BDDETALHE, '||
               'FE.BDREFFN, '||
               'FE.BDCODFE, '||
               'FE.BDINIPERAQUISFE, '||
               '0.0 BDAPE11, '||
               '0.0 BDAPE12, '||
               '0.0 BDAPE13, '||
               'FE.BDBASEIROUTFE, '||
               'FE.BDVALORIROUTFE, '||
               'FE.BDDEPIROUTFE, '||
               'FE.BDCREDITOFE, '||
               'FE.BDDEBITOFE, '||
               'FE.BDCOMPESP, '||
               'FE.BDFORMREFAUX, '||
               'FE.BDFORMREF, '||
               'FE.BDFORMVAL, '||
               'FE.BDBASEIRBRUTARED, '||
               'FE.BDVALORIRBRUTARED, '||
               'FE.BDVALORRED ';

  wsql = wsql||'from VW_VRHF_EMP_FERIAS FE '||
               'left outer join VW_VRHF_BASE_TEMPCALC EMPREF on (EMPREF.BDCODEMP = FE.BDCODEMP) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL) THEN
     wwhere = wwhere||PRCODEMP;

  IF (prcodcol IS NOT NULL) THEN
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||PRCODCOL;
     end

  IF (prcodfe IS NOT NULL AND prcodfe <> 0) THEN
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||' FE.BDCODFE = '||PRCODFE;
     end

  IF (priniperaquisfe IS NOT NULL) THEN
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

        wwhere = wwhere||' FE.BDINIPERAQUISFE = '||''''||priniperaquisfe||'''';
     end

  if (wwhere <> '') then
     wwhere  = ' where '||wwhere;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFV_MAX,
    :BDREFV_SUM,
    :BDREFAUXV_MAX,
    :BDREFAUXV_SUM,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNREFAV,
    :BDIGNVALV,
    :BDORVERBA,
    :BDALTINT,
    :BDREFHOREMP,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDDETALHE,
    :BDREFFN,
    :BDCODFE,
    :BDINIPERAQUISFE,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDBASEIROUT,
    :BDVALORIROUT,
    :BDDEPIROUT,
    :BDCREDITO,
    :BDDEBITO,
    :BDCOMPESP,
    :BDFORMREFAUX,
    :BDFORMREF,
    :BDFORMVAL,
    :BDBASEIRBRUTARED,
    :BDVALORIRBRUTARED,
    :BDVALORRED

  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

/* Restore proc. body: SPRH_CALC_FOLHACOMP */
ALTER PROCEDURE SPRH_CALC_FOLHACOMP(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV_MAX NUMERIC(15,6),
BDREFV_SUM NUMERIC(15,6),
BDREFAUXV_MAX NUMERIC(15,6),
BDREFAUXV_SUM NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDORVERBA INTEGER,
BDREFHOREMP VARCHAR(5),
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDETALHE VARCHAR(255),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCOMPESP VARCHAR(300),
BDFORMREFAUX VARCHAR(5000),
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIA, NULL, NULL);

  wsql = 'select ';
  wsql = wsql||'FC.BDCODEMP, '||
               'FC.BDCODCOL, '||
               'FC.BDCODVER, '||
               'FC.BDREFFN, '||
               'FC.BDREFVFN_MAX, '||
               'FC.BDREFVFN_SUM, '||
               'FC.BDREFAUXVFN_MAX, '||
               'FC.BDREFAUXVFN_SUM, '||
               'FC.BDVALVFN, '||
               'FC.BDIGNREFVFN, '||
               'FC.BDIGNVALVFN, '||
               'FC.BDORVERBAFC, '||
               'EMPREF.BDREFHOREMP, '||
               'FOLC.BDDATABAIXA, '||
               'FOLC.BDBFGTS, '||
               'FOLC.BDFGTS, '||
               'FOLC.BDFGTSCS, '||
               'FOLC.BDBFGTS13, '||
               'FOLC.BDFGTS13, '||
               'FOLC.BDFGTS13CS, '||
               'FOLC.BDMAIORREM, '||
               'FOLC.BDBINSS, '||
               'FOLC.BDALIQINSS, '||
               'FOLC.BDINSS, '||
               'FOLC.BDBIRRF, '||
               'FOLC.BDALIQIRRF, '||
               'FOLC.BDIRRF, '||
               'FOLC.BDBINSS13, '||
               'FOLC.BDALIQINSS13, '||
               'FOLC.BDINSS13, '||
               'FOLC.BDBIRRF13, '||
               'FOLC.BDALIQIRRF13, '||
               'FOLC.BDIRRF13, '||
               'FOLC.BDBSALFAM, '||
               'FOLC.BDSALFAM, '||
               'FOLC.BDBRAIS, '||
               'FOLC.BDSALBASE, '||
               'FOLC.BDDEP, '||
               '''Competencia: '''||'||substring(FC.BDREFFN from 5 for 2)||'||'''/'''||'||substring(FC.BDREFFN from 1 for 4) BDDETALHE, '||
               'FOLC.BDBINSSFEFOL, '||
               'FOLC.BDINSSFEFOL, '||
               'FOLC.BDALIQINSSFEFOL, '||
               'FOLC.BDCREDITO, '||
               'FOLC.BDDEBITO, '||
               'FC.BDCOMPESP, '||
               'FC.BDFORMREFAUX, '||
               'FC.BDFORMREF, '||
               'FC.BDFORMVAL ';

  wsql = wsql||'from VWRH_UNION_FC_FCT_MES FC, '||
               'VW_VRHF_BASE_TEMPCALC EMPREF, '||
               'VWRH_UNION_FC_FCT_MES_BASES FOLC ';

  wsql = wsql||'where EMPREF.BDCODEMP = FC.BDCODEMP and FOLC.BDCODEMP = FC.BDCODEMP and FOLC.BDCODCOL = FC.BDCODCOL and FOLC.BDREFFN = FC.BDREFFN and '||
               'FC.BDCODEMP = '||PRCODEMP||' and FC.BDCODCOL = '||PRCODCOL||' and FC.BDREFFN = '||PRREFERENCIA;
--  wsql = wsql||' order by RVA.BDTIPOCODVER, FC.BDCODVER ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFV_MAX,
    :BDREFV_SUM,
    :BDREFAUXV_MAX,
    :BDREFAUXV_SUM,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDORVERBA,
    :BDREFHOREMP,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDDETALHE,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDCREDITO,
    :BDDEBITO,
    :BDCOMPESP,
    :BDFORMREFAUX,
    :BDFORMREF,
    :BDFORMVAL
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: SPRH_CONS_CALC_13SALARIO */
ALTER PROCEDURE SPRH_CONS_CALC_13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDMESESPROP13 INTEGER,
BDBASEIR13 NUMERIC(15,6),
BDBASEFGTS13 NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS13 NUMERIC(15,6),
BDDATABAIXA13 DATE,
BDREFBAIXA13 INTEGER,
BDPERCIR13 NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDPERCINSS13 NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6))
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  IF (:PRANOMES IS NOT NULL AND :PRANOMES <> 0) THEN
     wsql = :PRANOMES;
  ELSE
     wsql = :PRANO||'12';

  EXECUTE PROCEDURE sp_seta_competencia(CAST(wsql AS INTEGER), NULL, NULL);

  wsql = 'select GRUPOVERBAS.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'GRUPOVERBAS.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'GRUPOVERBAS.BDCODVER, '||
                'VERREF.BDDESCVER, '||
                'VERREF.bddescredver, '||
                'GRUPOVERBAS.BDREFV13, '||
                'GRUPOVERBAS.BDREFAUXV13, '||
                'case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.BDVALV13 '||
                     'when (VERREF.BDTIPOCODVER <> 0) then 0 end BDPROVENTO, '||
                'case when (VERREF.BDTIPOCODVER > 0) then GRUPOVERBAS.BDVALV13 '||
                     'when (VERREF.BDTIPOCODVER <= 0) then 0 end BDDESCONTO, '||
                'VERREF.BDTIPOCODVER, '||
                'case when VERREF.BDTIPOCODVER = 1 then 2 when VERREF.BDTIPOCODVER = 2 then 1 else coalesce(VERREF.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, '||
                'VERREF.BDINSSVER, '||
                'VERREF.BDFGTSVER, '||
                'VERREF.BDIRVER, '||
                'VERREF.BDTIPOREFVER, '||
                'VERREF.BDBASESFVER, '||
                'VERREF.BDPISVER, '||
                'VERREF.BDBASEHEVER, '||
                'VERREF.BDBASEMAIORVER, '||
                'VERREF.BDRAISVER, '||
                'VERREF.BDBASEGPSVER, '||
                'GRUPOVERBAS.BDIGNREFAV13, '||
                'GRUPOVERBAS.BDIGNREFV13, '||
                'GRUPOVERBAS.BDIGNVALV13, '||
                'VERREF.BDCLAVER, '||
                'VERREF.BDORDEMVER, '||
                'GRUPOVERBAS.BDREF13, '||
                'EMPCALC.BDREFHOREMP, '||
                'Y.BDMESESPROP13, '||
                'Y.BDBASEIR13, '||
                'Y.BDBASEFGTS13, '||
                'Y.BDFGTS13, '||
                'Y.BDFGTSCS13, '||
                'Y.BDDATABAIXA13, '||
                'Y.BDREFBAIXA13, '||
                'Y.BDPERCIR13, '||
                'Y.BDVALORIR13, '||
                'Y.BDBASEINSS13, '||
                'Y.BDPERCINSS13, '||
                'Y.BDVALORINSS13, '||
                'Y.BDSALBASE13, '||
                'Y.BDDEP13, '||
                'Y.BDCREDITO13, '||
                'Y.BDDEBITO13 '||
         'from vrhf_emp_tverba13 GRUPOVERBAS, '||
         'VW_TEMPRESAS_REF EMP, '||
         'VW_VRH_EMP_TCOLCON_CAD COL, '||
         'VW_TVERBAS_REF VERREF, '||
         'VW_VRHF_BASE_TEMPCALC EMPCALC, '||
         'VRHF_EMP_T13SAL Y ';

  wwhere = 'where GRUPOVERBAS.BDCODEMP = EMP.BDCODEMP and COL.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODCOL = GRUPOVERBAS.BDCODCOL and VERREF.BDCODVER = GRUPOVERBAS.BDCODVER '||
           'and EMPCALC.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODCOL = GRUPOVERBAS.BDCODCOL and Y.BDREF13 = GRUPOVERBAS.BDREF13 and '||
           'GRUPOVERBAS.BDREF13 = '||:PRANOMES||' ';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODEMP;

  IF (:PRCODCOL IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODCOL;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCODVER,
    :BDDESCVER,
    :bddescredver,
    :BDREFV,
    :BDREFAUXV,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDTIPOCODVER,
    :BDORDEMTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDIGNREFAV,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDCLAVER,
    :BDORDEMVER,
    :BDREF,
    :BDREFHOREMP,
    :bdmesesprop13,
    :bdbaseir13,
    :bdbasefgts13,
    :bdfgts,
    :bdfgtscs13,
    :bddatabaixa13,
    :bdrefbaixa13,
    :bdpercir13,
    :bdirrf,
    :bdbaseinss13,
    :bdpercinss13,
    :bdinss,
    :BDSALBASE,
    :bddep,
    :bdcredito,
    :bddebito
  DO
  SUSPEND;
END
^

/* Restore proc. body: SPRH_CONS_CALC_AD13SALARIO */
ALTER PROCEDURE SPRH_CONS_CALC_AD13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRANO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDPERC NUMERIC(15,6),
BDVAL NUMERIC(15,6),
BDTIPOPROP INTEGER,
BDMESESPROP INTEGER,
BDBASEIR NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBASEFGTS NUMERIC(15,6),
BDDATABAIXA DATE,
BDREFBAIXA INTEGER,
BDPERCIR NUMERIC(15,6),
BDVALORIR NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6))
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  wsql = 'select GRUPOVERBAS.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'GRUPOVERBAS.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'GRUPOVERBAS.BDCODVER, '||
                'VERREF.BDDESCVER, '||
                'VERREF.bddescredver, '||
                'GRUPOVERBAS.BDREFVA13, '||
                'GRUPOVERBAS.BDREFAUXVA13, '||
                'case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.BDVALVA13 '||
                     'when (VERREF.BDTIPOCODVER <> 0) then 0 end BDPROVENTO, '||
                'case when (VERREF.BDTIPOCODVER > 0) then GRUPOVERBAS.BDVALVA13 '||
                     'when (VERREF.BDTIPOCODVER <= 0) then 0 end BDDESCONTO, '||
                'VERREF.BDTIPOCODVER, '||
                'case when VERREF.BDTIPOCODVER = 1 then 2 when VERREF.BDTIPOCODVER = 2 then 1 else coalesce(VERREF.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, '||
                'VERREF.BDINSSVER, '||
                'VERREF.BDFGTSVER, '||
                'VERREF.BDIRVER, '||
                'VERREF.BDTIPOREFVER, '||
                'VERREF.BDBASESFVER, '||
                'VERREF.BDPISVER, '||
                'VERREF.BDBASEHEVER, '||
                'VERREF.BDBASEMAIORVER, '||
                'VERREF.BDRAISVER, '||
                'VERREF.BDBASEGPSVER, '||
                'GRUPOVERBAS.BDIGNREFVA13, '||
                'GRUPOVERBAS.BDIGNVALVA13, '||
                'VERREF.BDCLAVER, '||
                'VERREF.BDORDEMVER, '||
                'GRUPOVERBAS.BDREFA13, '||
                'EMPCALC.BDREFHOREMP, '||
                'Y.BDPERCA13, '||
                'Y.BDVALA13, '||
                'Y.BDTIPOPROPA13, '||
                'Y.BDMESESPROPA13, '||
                'Y.BDBASEIRA13, '||
                'Y.BDFGTSA13, '||
                'Y.BDFGTSCSA13, '||
                'Y.BDBASEFGTSA13, '||
                'Y.BDDATABAIXAA13, '||
                'Y.BDREFBAIXAA13, '||
                'Y.BDPERCIRA13, '||
                'Y.BDVALORIRA13, '||
                'Y.BDSALBASEA13, '||
                'Y.BDDEPA13, '||
                '0.0 BDINSSA13, '||
                '0.0 BDIRRFA13, '||
                'Y.BDCREDITOA13, '||
                'Y.BDDEBITOA13 '||
         'from vrhf_emp_tverbaa13 GRUPOVERBAS, '||
         'VW_TEMPRESAS_REF EMP, '||
         'VW_VRH_EMP_TCOLCON_CAD COL, '||
         'VW_TVERBAS_REF VERREF, '||
         'VW_VRHF_BASE_TEMPCALC EMPCALC, '||
         'VRHF_EMP_TA13SAL Y ';

  wwhere = 'where GRUPOVERBAS.BDCODEMP = EMP.BDCODEMP and GRUPOVERBAS.BDCODEMP = COl.BDCODEMP and GRUPOVERBAS.BDCODCOL = COL.BDCODCOL and '||
           'VERREF.BDCODVER = GRUPOVERBAS.BDCODVER and EMPCALC.BDCODEMP = GRUPOVERBAS.BDCODEMP and '||
           'Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODCOL = GRUPOVERBAS.BDCODCOL and Y.BDREFA13 = GRUPOVERBAS.BDREFA13 and GRUPOVERBAS.BDREFA13 = '||:PRANOMES||' ';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODEMP;

  IF (:PRCODCOL IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODCOL;

  wsql = wsql||wwhere;

  EXECUTE PROCEDURE sp_seta_competencia(:PRANOMES, NULL, NULL);

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCODVER,
    :BDDESCVER,
    :bddescredver,
    :BDREFV,
    :BDREFAUXV,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDTIPOCODVER,
    :BDORDEMTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDCLAVER,
    :BDORDEMVER,
    :BDREF,
    :BDREFHOREMP,
    :BDPERC,
    :BDVAL,
    :BDTIPOPROP,
    :BDMESESPROP,
    :BDBASEIR,
    :BDFGTS,
    :BDFGTSCS,
    :BDBASEFGTS,
    :BDDATABAIXA,
    :BDREFBAIXA,
    :BDPERCIR,
    :BDVALORIR,
    :BDSALBASE,
    :bddep,
    :bdinss,
    :bdirrf,
    :BDCREDITO,
    :BDDEBITO
  DO
  SUSPEND;
END
^

/* Restore proc. body: SPRH_MENSAGENS_RECIBO */
CREATE OR ALTER procedure SPRH_MENSAGENS_RECIBO (
    PRREF integer,
    PRCODEMP varchar(10000),
    PRCODCOL varchar(10000),
    PRTIPOFOLHA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDTXTMEN varchar(2000))
as
declare variable WSQL varchar(32700);
declare variable WMES integer;
declare variable WWHERE varchar(10000);
BEGIN
  /*
    Não se esqueça de executar a procedure para setar a competência.
  */

  wmes = CAST((SUBSTRING(CAST(:prref AS VARCHAR(6)) FROM 5 FOR 2)) AS INTEGER);
  wwhere = '';

  /*Solicitação: 152645 - André Cursino - 27/10/2021 - wMes estava virando um mês posterior ao mês
                                                       de nascimento do colaborador e para encontrar as
                                                       mensagem para esse mês deve ser usar o mês da referência
                                                       sem modificar*/
  /*IF (wmes = 12) THEN
     BEGIN
       wmes = 1;
     END
  ELSE
     BEGIN
       wmes = wmes + 1;
     END*/

  IF (PRCODCOL <> '') THEN
    BEGIN
        wwhere = wwhere || ' and ' || PRCODCOL;
    END
    
  IF (PRCODEMP <> '') THEN
    BEGIN
        wwhere = wwhere || ' and ' || PRCODEMP;
    END
    
  wsql = 'select '  ||
            'list(BDTXTMEN, ''. '') as BDTXTMEN, ' ||
            'BDCODCOL, ' ||
            'BDCODEMP '  ||
         'from (' ||
            'select ' || 
                'COL.BDCODEMP, ' ||
                'COL.BDCODCOL, ' ||
                'MSG.BDTXTMEN ' ||
            'from ' ||
                'VRH_EMP_TCOLCON COL ' ||
            'join ' ||
                'VW_VRHF_BASE_TEMPVINC EMP on (EMP.BDCODEMP = COL.BDCODEMP) ' ||
            'join ' || 
                'VRH_BASE_TMENSAGENS MSG on (MSG.BDCODMEN = EMP.BDCODMEN) ' ||
            'where ' ||
                'MSG.BDTXTMEN <> '''' and ' ||
                'COALESCE(EXTRACT(MONTH FROM COL.BDDATANASCCOL), 0) = ' || wmes ||
                wwhere ||
            ' union all select ' ||
                'COL.BDCODEMP, ' ||
                'COL.BDCODCOL, ' ||
                'MSG.BDTXTMEN ' ||
            'from ' ||
                'VRH_EMP_TLANMENSAGENS COL ' ||
            'join ' ||
                'VRH_BASE_TMENSAGENS MSG on (COL.BDCODMEN = MSG.BDCODMEN) ' ||
            'where ' ||
                'MSG.BDTXTMEN <> '''' and ' ||
                'COL.BDREFLAN = '|| prRef || ' and ' ||
                'COL.BDTIPOFOLHA = ' || prtipofolha ||
                wwhere ||
         ') ' ||
         'group by ' ||
            'BDCODEMP, ' ||
            'BDCODCOL ';

  FOR EXECUTE STATEMENT wsql INTO    -- Mensagens de aniversário    
    BDTXTMEN,
    BDCODCOL,
    BDCODEMP

    DO
      SUSPEND;
END
^

/* Restore proc. body: SPRH_TREEVIEW_CONS_13SAL */
/*alt:13612 - 23/03/2016 - Parametro de entrada PRANO teve alterado o nome para PRMESESANTERIORES e o tipo para SMALLINT e alterei a procedure para:
Se o parâmetro de entrada PRMESESANTERIORES for igual a 0 (zero), retornar todos os cálculos de 13º salário da COMPETÊNCIA (AAAAMM), PRANOMES
Se for igual a 1 (um) retornar todos os cálculos de 13º salário do ANO, PRANOMES
Senão, retornar todos os cálculos de 13º salário da base - Bruno L. R.*/
CREATE OR ALTER PROCEDURE SPRH_TREEVIEW_CONS_13SAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRMESESANTERIORES SMALLINT,
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDREF13 INTEGER)
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  IF (:PRANOMES IS NOT NULL AND :PRANOMES <> 0) THEN
     wsql = :PRANOMES;
  --ELSE
     --wsql = :PRANO||'12';

  EXECUTE PROCEDURE sp_seta_competencia(CAST(wsql AS INTEGER), NULL, NULL);

  wsql = 'select DECTERC.BDCODEMP, EMP.BDNOMEMP, '||
                'DECTERC.BDCODCOL, COL.BDNOMCOL, '||
                'DECTERC.BDREF13 '||
         'from VRHF_EMP_T13SAL DECTERC, '||
         'VW_TEMPRESAS_REF EMP, '||
         'VW_VRH_EMP_TCOLCON_CAD COL ';

  wwhere = ' where DECTERC.BDCODEMP = EMP.BDCODEMP and DECTERC.BDCODEMP = COL.BDCODEMP and DECTERC.BDCODCOL = COL.BDCODCOL ';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODEMP;

  IF (:PRCODCOL IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODCOL;

  /*IF (:PRANO IS NOT NULL AND :PRANO <> 0) THEN
     wwhere = wwhere||' and DECTERC.BDANO13 = '||:PRANO;
  ELSE
  IF (:PRANOMES IS NOT NULL AND :PRANOMES <> 0) THEN
     wwhere = wwhere||' and DECTERC.BDREF13 = '||:PRANOMES;*/

  IF (:PRANOMES IS NOT NULL AND :PRANOMES <> 0) THEN
     BEGIN
       IF (:PRMESESANTERIORES = 0) THEN
          wwhere = wwhere||' and DECTERC.BDREF13 = '||:PRANOMES;
       ELSE
         IF (:PRMESESANTERIORES = 1) THEN
            wwhere = wwhere||' and substring(DECTERC.BDREF13 from 1 for 4) = '||SUBSTRING(:PRANOMES FROM 1 FOR 4)||' ';
     END 

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :bdnomemp,
    :bdcodcol,
    :bdnomcol,
    :bdref13
  DO
  SUSPEND;
END
^

/* Restore proc. body: SPRH_TREEVIEW_CONS_AD13SAL */
/*alt:13612 - 23/03/2016 - Parametro de entrada PRANO teve alterado o nome para PRMESESANTERIORES e o tipo para SMALLINT e alterei a procedure para:
Se o parâmetro de entrada PRMESESANTERIORES for igual a 0 (zero), retornar todos os cálculos de adiantamentos 13º salário da COMPETÊNCIA (AAAAMM), PRANOMES
Se for igual a 1 (um) retornar todos os cálculos de adiantamentos de 13º salário do ANO, PRANOMES.
Senão, retornar todos os cálculos de adiantamentos de 13º salário da base - Bruno L. R.*/ 
ALTER PROCEDURE SPRH_TREEVIEW_CONS_AD13SAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRMESESANTERIORES SMALLINT,
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDREFA13 INTEGER)
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  IF (:PRANOMES IS NOT NULL AND :PRANOMES <> 0) THEN
     wsql = :PRANOMES;
  --ELSE
     --wsql = :PRANO||'12';

  EXECUTE PROCEDURE sp_seta_competencia(CAST(wsql AS INTEGER), NULL, NULL);

  wsql = 'select A13.BDCODEMP, EMP.BDNOMEMP, '||
                'A13.BDCODCOL, COL.BDNOMCOL, '||
                'A13.BDREFA13 '||
         'from VRHF_EMP_TA13SAL A13, '||
         'VW_TEMPRESAS_REF EMP, '||
         'VW_VRH_EMP_TCOLCON_CAD COL ';

  wwhere = ' where A13.BDCODEMP = EMP.BDCODEMP and COL.BDCODEMP = A13.BDCODEMP and COL.BDCODCOL = A13.BDCODCOL ';

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODEMP;

  IF (:PRCODCOL IS NOT NULL) THEN
     wwhere = wwhere||' and '||:PRCODCOL;

  /*IF (:PRANO IS NOT NULL AND :PRANO <> 0) THEN
     wwhere = wwhere||' and A13.BDANOA13 = '||:PRANO;
  ELSE
  IF (:PRANOMES IS NOT NULL AND :PRANOMES <> 0) THEN
     wwhere = wwhere||' and A13.BDREFA13 = '||:PRANOMES;*/

  IF (:PRANOMES IS NOT NULL AND :PRANOMES <> 0) THEN
     BEGIN
       IF (:PRMESESANTERIORES = 0) THEN
          wwhere = wwhere||' and A13.BDREFA13 = '||:PRANOMES;
       ELSE
         IF (:PRMESESANTERIORES = 1) THEN
            wwhere = wwhere||' and substring(A13.BDREFA13 from 1 for 4) = '||SUBSTRING(:PRANOMES FROM 1 FOR 4)||' ';
     END    

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDREFA13
  DO
  SUSPEND;
END
^

/* Restore proc. body: SPVAL_ITINERARIO */
ALTER PROCEDURE SPVAL_ITINERARIO(PRITI INTEGER,
PRREF INTEGER)
 RETURNS(BDITI INTEGER,
BDVALOR NUMERIC(15,6))
 AS
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(prref,NULL,NULL);

  SELECT bdcoditi,BDVALITI FROM VW_VRHF_BASE_TITINERARIOS_REF WHERE bdcoditi = :priti INTO :bditi,:bdvalor;

  SUSPEND;
END
^

/* Restore proc. body: STRTRAN */
ALTER PROCEDURE STRTRAN(PRTEXTO VARCHAR(30000),
PRSUBSTR VARCHAR(1024),
PRSTR VARCHAR(1024))
 RETURNS(BDRESULT VARCHAR(30000))
 AS
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WSTRLEN INTEGER;
BEGIN
  -- Gilberto - 29/10/2011 - implementado o laço do STRTRAN
  wpos = 1;
  wstrlen = strlen(prsubstr);
  bdresult = '';
  WHILE (wpos <= strlen(prtexto)) DO
    BEGIN
      IF (SUBSTRING(prtexto FROM wpos FOR wstrlen) = prsubstr) THEN
         BEGIN
           bdresult = bdresult||prstr;
           wpos = wpos + wstrlen - 1;
         END
      ELSE
         bdresult = bdresult||SUBSTRING(prtexto FROM wpos FOR 1);
      wpos = wpos + 1;
    END
  SUSPEND;
END
^

/* Restore proc. body: STRZERO */
ALTER PROCEDURE STRZERO(PRSTR INTEGER,
PRTAM INTEGER)
 RETURNS(STR VARCHAR(50))
 AS
BEGIN

  str = prstr || '';

  WHILE (strlen(str) < prtam) DO
    BEGIN
      str = '0' || str;
    END

   SUSPEND;

END
^

/* Restore proc. body: TRUNCAR */
ALTER PROCEDURE TRUNCAR(PRVALOR NUMERIC(15,6),
PRCASAS SMALLINT)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE wvaldim VARCHAR(10);
DECLARE VARIABLE wsql VARCHAR(300);
BEGIN
  /* Procedure Text */
  IF (prcasas IS NULL) THEN
     prcasas = 0;

  IF (prvalor IS NULL) THEN
     prvalor = 0;

  wvaldim = '';
  WHILE (CHAR_LENGTH(wvaldim) < prcasas) DO
    BEGIN
      wvaldim = wvaldim||'0';
    END
  wvaldim = '0.'||wvaldim||'5';

  IF (prvalor < 0) THEN
     wsql = 'select cast('||prvalor||' + '||wvaldim||' as numeric(15,'||prcasas||')) from rdb$database';
  ELSE
     wsql = 'select cast('||prvalor||' - '||wvaldim||' as numeric(15,'||prcasas||')) from rdb$database';

  IF (prvalor = 0) THEN
     bdvalor = 0;
  ELSE
     EXECUTE STATEMENT wsql INTO bdvalor;

  SUSPEND;
END
^

/* Restore proc. body: ULTIMO_DIA_MES */
ALTER PROCEDURE ULTIMO_DIA_MES(PRMES SMALLINT,
PRANO INTEGER)
 RETURNS(ULTDIA INTEGER)
 AS
DECLARE VARIABLE wanobisexto SMALLINT;
BEGIN

  IF (prmes = 2) THEN
     BEGIN

       SELECT prBisexto FROM ano_bisexto(:prano) INTO wanobisexto;

       IF (wanobisexto = 1) THEN
          ultdia = 29;
       ELSE
          ultdia = 28;

     END
  ELSE
     BEGIN
       IF ((prmes = 4) OR (prmes = 6) OR (prmes = 9) OR (prmes = 11)) THEN
          ultdia = 30;
       ELSE
          ultdia = 31;
     END

  SUSPEND;

END
^

/* Restore proc. body: VCT_SERVICO_SUBORDINADO */
CREATE OR ALTER PROCEDURE VCT_SERVICO_SUBORDINADO(PRCODSER INTEGER,
PRCODSUB INTEGER)
 RETURNS(BDCODSER INTEGER)
 AS
DECLARE VARIABLE wcodser INTEGER;
BEGIN
  FOR SELECT tser.bdcodsersub FROM vct_base_servicosubordinado tser
      WHERE tser.bdcodobrser = :prcodsub
      INTO :wcodser DO
      BEGIN
        IF (wcodser = prcodser) THEN
           BEGIN
             bdcodser = wcodser;
             SUSPEND;
             BREAK;
           END
        ELSE
           BEGIN
             SELECT FIRST 1 bdcodser FROM vct_servico_subordinado(:prcodser, :wcodser) WHERE bdcodser IS NOT NULL INTO :wcodser;
             IF (wcodser = prcodser) THEN
                BEGIN
                  bdcodser = wcodser;
                  SUSPEND;
                  BREAK;
                END
           END
      END
END
^

/* Restore proc. body: VCT_TAREFA_SUBORDINADA */
CREATE OR ALTER PROCEDURE VCT_TAREFA_SUBORDINADA(PRCODST INTEGER,
PRCODSUB INTEGER)
 RETURNS(BDCODST INTEGER)
 AS
DECLARE VARIABLE wcodst INTEGER;
BEGIN
  FOR SELECT task.bdcodstsub FROM vct_empresa_tarefasubordinada task
      WHERE task.bdcodst = :prcodsub
      INTO :wcodst DO
      BEGIN
        IF (wcodst = prcodst) THEN
           BEGIN
             bdcodst = wcodst;
             SUSPEND;
             BREAK;
           END
        ELSE
           BEGIN
             SELECT FIRST 1 bdcodst FROM vct_tarefa_subordinada(:prcodst, :wcodst) WHERE bdcodst IS NOT NULL INTO :wcodst;
             IF (wcodst = prcodst) THEN
                BEGIN
                  bdcodst = wcodst;
                  SUSPEND;
                  BREAK;
                END
           END
      END
END
^

/* Restore proc. body: VEF_COPIA_PLANO_BLOCOP */
ALTER PROCEDURE VEF_COPIA_PLANO_BLOCOP(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
DECLARE VARIABLE FSQL VARCHAR(1000);
DECLARE VARIABLE WBDCODCONF INTEGER;
DECLARE VARIABLE WBDCODQ INTEGER;
DECLARE VARIABLE WBDNUMCAMPO INTEGER;
DECLARE VARIABLE WBDNUMITEM INTEGER;
DECLARE VARIABLE WBDDESCFORM VARCHAR(60);
DECLARE VARIABLE WBDCAMPOINATIVO VARCHAR(5);
DECLARE VARIABLE WBDFORMULA VARCHAR(30000);
BEGIN
  --Alt.:5806 estava deletando da tabela vef_base_tconfblocop, modificado para vef_base_tconfBLOCOPform
  FSQL = 'delete from vef_base_tconfBLOCOPform form WHERE BDCODCONFBLOCOP = '||:codigonovo;
  EXECUTE STATEMENT FSQL;

  IF ((codigonovo IS NULL) OR (codigonovo = 0)) THEN
     BEGIN
        FSQL = 'SELECT max(BDCODCONFBLOCOP) from vef_base_tconfblocop';
        EXECUTE STATEMENT fsql INTO codigonovo;
     END

  fsql = ' select BDCODCONFBLOCOP, bdcodqBLOCOP,bdnumcampoBLOCOP,BDDESCFORMBLOCOP,BDFORMULABLOCOP,BDNUMITEM, BDCAMPOINATIVO ';
  FSQL = fsql ||' from vef_base_tconfBLOCOPform ';
  fsql = fsql || ' where BDCODCONFBLOCOP = '|| :codigocopiar;

  FOR EXECUTE STATEMENT fsql
      INTO
        wBDCODCONF,
        wBDCODQ,
        wBDNUMCAMPO,
        wBDDESCFORM,
        wBDFORMULA,
        wBDNUMITEM,
        wBDCAMPOINATIVO DO
     BEGIN
        IF ((:wbdFORMULA IS NOT NULL) AND (:wbdFORMULA <> '')) THEN
          wbdFORMULA = REPLACE(:wbdFORMULA, '''', ''''''); -- Alt.: #75653 - Quando a formula vinha com "'" montava o script com erro...

        FSQL = 'UPDATE OR INSERT INTO vef_base_tconfBLOCOPFORM (BDCODCONFBLOCOP, bdcodqBLOCOP,bdnumcampoBLOCOP,BDDESCFORMBLOCOP,BDFORMULABLOCOP,BDNUMITEM, BDCAMPOINATIVO)';
        fsql = fsql || ' values ('||:codigonovo||','||wBDCODQ||','||wBDNUMCAMPO||','''||:wBDDESCFORM||''','''||:wbdformula||''','||:wBDNUMITEM||','''||:wBDCAMPOINATIVO||''')';

        FSQL = FSQL||' MATCHING (BDCODCONFBLOCOP, BDCODQBLOCOP, BDNUMCAMPOBLOCOP)';


        EXECUTE STATEMENT fsql;
     END


END
^

/* Restore proc. body: VEF_COPIA_PLANO_DACON */
ALTER PROCEDURE VEF_COPIA_PLANO_DACON(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER,
COPIARFORMULA INTEGER)
 AS
DECLARE VARIABLE FSQL VARCHAR(10000);
DECLARE VARIABLE WBDCODQ INTEGER;
DECLARE VARIABLE WBDNUMCAMPO INTEGER;
DECLARE VARIABLE WBDNUMITEM INTEGER;
DECLARE VARIABLE WBDDESCFORM VARCHAR(300);
DECLARE VARIABLE WBDCAMPOINATIVO VARCHAR(5);
DECLARE VARIABLE WBDFORMULA VARCHAR(30000);
DECLARE VARIABLE WBDFORMULA2 VARCHAR(30000);
DECLARE VARIABLE WBDFORMULA3 VARCHAR(30000);
DECLARE VARIABLE WBDCODITEMONLINE INTEGER;
DECLARE VARIABLE WTIPO INTEGER;
DECLARE VARIABLE WCLASS VARCHAR(100);
DECLARE VARIABLE WORDEMQ INTEGER;
DECLARE VARIABLE WCODTIPO INTEGER;
DECLARE VARIABLE WDESCFORMQ VARCHAR(300);
DECLARE VARIABLE WBDCODTIPOCRE INTEGER;
BEGIN
  IF ((codigonovo IS NULL) OR (codigonovo = 0)) THEN
     BEGIN
        FSQL = 'SELECT max(BDCODCONFDACON) from vef_base_tconfdacon';
        EXECUTE STATEMENT fsql INTO codigonovo;
     END

  FSQL = 'delete from VEF_BASE_TCONFDACONQ WHERE BDCODCONFDACON = '||:codigonovo;
  EXECUTE STATEMENT FSQL;

  FSQL = 'SELECT max(BDCODQDACON) from VEF_BASE_TCONFDACONQ';
  EXECUTE STATEMENT fsql INTO wordemq;
  FSQL = 'delete from vef_base_tconfdaconform WHERE BDCODCONFDACON = '||:codigonovo;
  EXECUTE STATEMENT FSQL;
  FSQL = 'delete from VEF_BASE_TCONFDACONF1424 WHERE BDCODCONFDACON = '||:codigonovo;
  EXECUTE STATEMENT FSQL;

  FSQL = 'select BDCODQDACON,BDDESCQDACON,BDCLASSIFICACAO,BDCODTIPO,BDTIPO from VEF_BASE_TCONFDACONQ ';
  FSQL = FSQL ||'  WHERE BDCODCONFDACON = '||:codigocopiar || ' order by bdcodconfdacon,bdclassificacao ';


  FOR EXECUTE STATEMENT fsql
      INTO
        WBDCODQ,
        wdescFormq,
        wClass,
        wCodTipo,
        wtipo  DO
     BEGIN
        wordemq = wordemq +1;

        FSQL = 'UPDATE OR INSERT INTO VEF_BASE_TCONFDACONQ (BDCODQDACON ,BDDESCQDACON,BDCLASSIFICACAO,BDCODCONFDACON,BDCODTIPO,BDTIPO)';
        fsql = fsql ||' values ('||wordemq||','''||:wdescFormq||''','''||:wclass||''','||:codigonovo||','||:wCodTipo||','||:wtipo||')';
        FSQL = FSQL ||' MATCHING (BDCODQDACON);';
        EXECUTE STATEMENT fsql;



        fsql = ' select bdnumcampoDACON,BDDESCFORMDACON,BDFORMULADACON,BDFORMULADACON2,BDFORMULADACON3,BDNUMITEM, BDCAMPOINATIVO,BDCODITEMONLINE ';
        FSQL = fsql ||' from vef_base_tconfdaconform ';
        fsql = fsql || ' where BDCODCONFDACON = '|| :codigocopiar;
        fsql = fsql || ' and BDCODQDACON = '|| :WBDCODQ;

        FOR EXECUTE STATEMENT fsql
          INTO
--            wBDCODQ,
            wBDNUMCAMPO,
            wBDDESCFORM,
            wBDFORMULA,
            WBDFORMULA2,
            WBDFORMULA3,
            wBDNUMITEM,
            wBDCAMPOINATIVO,
            wBDCODITEMONLINE  DO
         BEGIN
        
            FSQL = 'UPDATE OR INSERT INTO vef_base_tconfdaconform (BDCODCONFDACON, BDCODQDACON,BDNUMCAMPODACON,BDDESCFORMDACON,BDFORMULADACON,BDFORMULADACON2,BDFORMULADACON3,BDNUMITEM, BDCAMPOINATIVO,BDCODITEMONLINE)';
            fsql = fsql || ' values ('||:codigonovo||','||wordemq||','||wBDNUMCAMPO||','''||:wBDDESCFORM||''',';

            IF ((:wbdformula IS NULL) OR (:COPIARFORMULA = 0)) THEN
              BEGIN
                fsql = fsql ||'null,';
              END
            ELSE
              BEGIN
                IF ((:wbdFORMULA IS NOT NULL) AND (:wbdFORMULA <> '')) THEN
                  wbdFORMULA = REPLACE(:wbdFORMULA, '''', ''''''); -- Alt.: #75653 - Quando a formula vinha com "'" montava o script com erro...

                fsql = fsql ||''''|| :wbdformula||''',';
              END
            IF ((:wbdformula2 IS NULL) OR (COPIARFORMULA = 0)) THEN
              BEGIN
                fsql = fsql ||'null,';
              END
            ELSE
              BEGIN
                IF ((:wbdFORMULA2 IS NOT NULL) AND (:wbdFORMULA2 <> '')) THEN
                  wbdFORMULA2 = REPLACE(:wbdFORMULA2, '''', ''''''); -- Alt.: #75653 - Quando a formula vinha com "'" montava o script com erro...

                fsql = fsql||''''||:wbdformula2||''',';
              END
        
            IF ((:wbdformula3 IS NULL) OR (COPIARFORMULA = 0)) THEN
              BEGIN
                fsql = fsql ||'null,';
              END
            ELSE
              BEGIN
                IF ((:wbdFORMULA3 IS NOT NULL) AND (:wbdFORMULA3 <> '')) THEN
                  wbdFORMULA3 = REPLACE(wbdFORMULA3, '''', ''''''); -- Alt.: #75653 - Quando a formula vinha com "'" montava o script com erro...

                fsql = fsql||''''||:wbdformula3||''',';
              END

            IF (wBDNUMITEM IS NULL) THEN
              BEGIN
                fsql = fsql ||'null,''';
              END
            ELSE
              BEGIN
                fsql = fsql ||:wBDNUMITEM||',''';
              END

            IF (wBDCAMPOINATIVO IS NULL) THEN
              BEGIN
                fsql = fsql ||'null'',';
              END
            ELSE
              BEGIN
                fsql = fsql ||:wBDCAMPOINATIVO||''',';
              END


            IF (wBDCODITEMONLINE IS NULL) THEN
              BEGIN
                fsql = fsql ||'null)';
              END
            ELSE
              BEGIN
                fsql = fsql ||:wBDCODITEMONLINE||')';
              END
        
            FSQL = FSQL||' MATCHING (BDCODCONFDACON, BDCODQDACON, BDNUMCAMPODACON)';
        
        
            EXECUTE STATEMENT fsql;
         END

        IF ((wCodTipo = 36) OR (wcodtipo = 55) ) THEN
          BEGIN
            fsql = ' select bdnumcampoDACON,BDDESCFORMDACON,BDFORMULADACON,BDCODTIPOCRE,BDNUMITEM, BDCAMPOINATIVO ';
            FSQL = fsql ||' from VEF_BASE_TCONFDACONF1424 ';
            fsql = fsql || ' where BDCODCONFDACON = '|| :codigocopiar;
            fsql = fsql || ' and BDCODQDACON = '|| :WBDCODQ;
            
            FOR EXECUTE STATEMENT fsql
              INTO
    --            wBDCODQ,
                wBDNUMCAMPO,
                wBDDESCFORM,
                wBDFORMULA,
                WBDCODTIPOCRE,
                wBDNUMITEM,
                wBDCAMPOINATIVO  DO
             BEGIN
            
                FSQL = 'UPDATE OR INSERT INTO VEF_BASE_TCONFDACONF1424 (BDCODCONFDACON, BDCODQDACON,BDNUMCAMPODACON,BDDESCFORMDACON,BDFORMULADACON,BDCODTIPOCRE,BDNUMITEM, BDCAMPOINATIVO)';
                fsql = fsql || ' values ('||:codigonovo||','||wordemq||','||wBDNUMCAMPO||','''||:wBDDESCFORM||''','''||:wbdformula||''','||:WBDCODTIPOCRE||','||:wBDNUMITEM||','''||:wBDCAMPOINATIVO||''')';
            
                FSQL = FSQL||' MATCHING (BDCODCONFDACON, BDCODQDACON, BDCODTIPOCRE, BDNUMCAMPODACON)';
            
            
                EXECUTE STATEMENT fsql;
            END
          END
     END
END
^

/* Restore proc. body: VEF_COPIA_PLANO_DIME */
ALTER PROCEDURE VEF_COPIA_PLANO_DIME(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WCAMPOSINSERT VARCHAR(1000);
DECLARE VARIABLE WCAMPO VARCHAR(64);
BEGIN
  /* Insere as formulas */
  EXECUTE STATEMENT 'EXECUTE PROCEDURE VEF_COPIA_PLANO('||CodigoNovo||','||CodigoCopiar||',''DIME'')' INTO CodigoNovo;

  /*** VEF_ESTADOS_TCONFDIMEFQ46 ***/
  /* Deleta os registros do quadro 46 */
  wSQL = 'DELETE FROM VEF_ESTADOS_TCONFDIMEFQ46 WHERE BDCODCONFDIMESC = '||:CodigoNovo;
  EXECUTE STATEMENT wSQL;

  /* Obtém os campos da tabela "VEF_ESTADOS_TCONFDIMEFQ46" */
  wSQL = 'SELECT r.RDB$FIELD_NAME as BDCAMPO '||
         'FROM RDB$RELATION_FIELDS r '||
         'WHERE r.RDB$RELATION_NAME = ''VEF_ESTADOS_TCONFDIMEFQ46''';
  wCamposInsert = '';
  FOR EXECUTE STATEMENT wSQL
  INTO wCampo DO
    BEGIN
      IF (wCampo <> 'BDCODCONFDIMESC') THEN
        wCamposInsert = wCamposInsert||','||TRIM(wCampo);
    END
  /* Cria insert da tabela "VEF_ESTADOS_TCONFDIMEFQ46" */
  wSQL = 'INSERT INTO VEF_ESTADOS_TCONFDIMEFQ46 (BDCODCONFDIMESC'||wCamposInsert||') '||
         ' SELECT '||CodigoNovo||wCamposInsert||' FROM VEF_ESTADOS_TCONFDIMEFQ46 WHERE BDCODCONFDIMESC = '||CODIGOCOPIAR;
  EXECUTE STATEMENT wSQL;


  /*** VEF_ESTADOS_TCONFDIMEFQ12 ***/
  /* Deleta os registros do quadro 12 */
  wSQL = 'DELETE FROM VEF_ESTADOS_TCONFDIMEFQ12 WHERE BDCODCONFDIMESC = '||:CodigoNovo;
  EXECUTE STATEMENT wSQL;

  /* Obtém os campos da tabela "VEF_ESTADOS_TCONFDIMEFQ12" */
  wSQL = 'SELECT r.RDB$FIELD_NAME as BDCAMPO '||
         'FROM RDB$RELATION_FIELDS r '||
         'WHERE r.RDB$RELATION_NAME = ''VEF_ESTADOS_TCONFDIMEFQ12''';
  wCamposInsert = '';
  FOR EXECUTE STATEMENT wSQL
  INTO wCampo DO
    BEGIN
      IF (wCampo <> 'BDCODCONFDIMESC') THEN
        wCamposInsert = wCamposInsert||','||TRIM(wCampo);
    END
  /* Cria insert da tabela "VEF_ESTADOS_TCONFDIMEFQ12" */
  wSQL = 'INSERT INTO VEF_ESTADOS_TCONFDIMEFQ12 (BDCODCONFDIMESC'||wCamposInsert||') '||
         ' SELECT '||CodigoNovo||wCamposInsert||' FROM VEF_ESTADOS_TCONFDIMEFQ12 WHERE BDCODCONFDIMESC = '||CODIGOCOPIAR;
  EXECUTE STATEMENT wSQL;
END
^

/* Restore proc. body: VEF_COPIA_PLANO_GIA */
ALTER PROCEDURE VEF_COPIA_PLANO_GIA (
    CODIGONOVO INTEGER,
    CODIGOCOPIAR INTEGER,
    TIPOGIA VARCHAR(10))
AS
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WINSERT VARCHAR(1000);
DECLARE VARIABLE WBDCODCONF INTEGER;
DECLARE VARIABLE WBDCODQ INTEGER;
DECLARE VARIABLE WBDNUMCAMPO INTEGER;
DECLARE VARIABLE WBDNUMITEM VARCHAR(5); --integer
DECLARE VARIABLE WBDDESCFORM VARCHAR(60);
DECLARE VARIABLE WBDCAMPOINATIVO VARCHAR(5);
DECLARE VARIABLE WBDFORMULA VARCHAR(30000);
DECLARE VARIABLE WBDCODITEMONLINE INTEGER;
DECLARE VARIABLE WBDCODIMP INTEGER;
DECLARE VARIABLE WBDSEQLIVRO VARCHAR(3);
DECLARE VARIABLE WBDINIVALIDADE DATE;
DECLARE VARIABLE WBDFIMVALIDADE DATE;
BEGIN

  WSQL = 'delete from VEF_ESTADOS_TCONFGIA'||TIPOGIA||'FORM WHERE BDCODCONF = '||:codigonovo;
  EXECUTE STATEMENT WSQL;

  IF ((codigonovo IS NULL) OR (codigonovo = 0)) THEN
     BEGIN
        WSQL = 'SELECT max(BDCODCONF) from VEF_ESTADOS_TCONFGIA'||TIPOGIA;
        EXECUTE STATEMENT WSQL INTO codigonovo;
     END

  WSQL = ' select BDCODCONF, BDCODQUADRO,bdnumcampo,BDDESCFORM,BDFORMULA,BDNUMITEM, BDCAMPOINATIVO,BDCODITEMONLINE ';
  IF (TIPOGIA = 'MG') THEN
    WSQL = WSQL || ', BDCODIMP, BDSEQLIVRO, BDINIVALIDADE, BDFIMVALIDADE ';
  WSQL = WSQL || ' from VEF_ESTADOS_TCONFGIA'||TIPOGIA||'form ';
  WSQL = WSQL || ' where BDCODCONF = '|| :codigocopiar;

  IF (TIPOGIA = 'MG') THEN
    BEGIN -- Alt.: 11211 - Não estava levando as informações de código de imposto e sequêncial do livro na cópia do MG.
      FOR EXECUTE STATEMENT WSQL
          INTO
            wBDCODCONF,
            wBDCODQ,
            wBDNUMCAMPO,
            wBDDESCFORM,
            wBDFORMULA,
            wBDNUMITEM,
            wBDCAMPOINATIVO,
            wBDCODITEMONLINE,
            wBDCODIMP,
            wBDSEQLIVRO,
            WBDINIVALIDADE,
            WBDFIMVALIDADE  DO
         BEGIN
            IF ((:wbdFORMULA IS NOT NULL) AND (:wbdFORMULA <> '')) THEN
              wbdFORMULA = REPLACE(:wbdFORMULA, '''', ''''''); -- Alt.: #75653 - Quando a formula vinha com "'" montava o script com erro...

            WINSERT = 'UPDATE OR INSERT INTO VEF_ESTADOS_TCONFGIA'||TIPOGIA||'FORM (BDCODCONF, bdcodquadro,bdnumcampo,BDDESCFORM,BDFORMULA,BDNUMITEM, BDCAMPOINATIVO,BDCODITEMONLINE, BDCODIMP, BDSEQLIVRO, BDINIVALIDADE, BDFIMVALIDADE)';
            WINSERT = WINSERT || ' values ('||:codigonovo||','||wBDCODQ||','||wBDNUMCAMPO||','''||:wBDDESCFORM||''','''||Coalesce(:wbdformula,'')||''','||:wBDNUMITEM||','''||:wBDCAMPOINATIVO||''',';
    
            IF (wBDCODITEMONLINE IS NULL) THEN
              WINSERT = WINSERT ||'null,';
            ELSE
              WINSERT = WINSERT ||:wBDCODITEMONLINE||',';

            IF (wBDCODIMP IS NULL) THEN
              WINSERT = WINSERT ||'null,';
            ELSE
              WINSERT = WINSERT ||:wBDCODIMP||',';

            IF (wBDSEQLIVRO IS NULL) THEN
              WINSERT = WINSERT ||'null,';
            ELSE
              WINSERT = WINSERT ||''''||:wBDSEQLIVRO||''',';

            --sol:10586
            IF (WBDINIVALIDADE IS NULL) THEN
              WINSERT = WINSERT ||'null,';
            ELSE
              WINSERT = WINSERT ||''''||:WBDINIVALIDADE||''',';

            --sol:10586
            IF (WBDFIMVALIDADE IS NULL) THEN
              WINSERT = WINSERT ||'null)';
            ELSE
              WINSERT = WINSERT ||''''||:WBDFIMVALIDADE||''')';

            WINSERT = WINSERT||' MATCHING (BDCODCONF, BDCODQUADRO, BDNUMCAMPO)';
    
            EXECUTE STATEMENT WINSERT;
         END
    END
  ELSE
    BEGIN
      FOR EXECUTE STATEMENT WSQL
          INTO
            wBDCODCONF,
            wBDCODQ,
            wBDNUMCAMPO,
            wBDDESCFORM,
            wBDFORMULA,
            wBDNUMITEM,
            wBDCAMPOINATIVO,
            wBDCODITEMONLINE  DO
         BEGIN
            IF ((:wbdFORMULA IS NOT NULL) AND (:wbdFORMULA <> '')) THEN
              wbdFORMULA = REPLACE(:wbdFORMULA, '''', ''''''); -- Alt.: #75653 - Quando a formula vinha com "'" montava o script com erro...

            WINSERT = 'UPDATE OR INSERT INTO VEF_ESTADOS_TCONFGIA'||TIPOGIA||'FORM (BDCODCONF, bdcodquadro,bdnumcampo,BDDESCFORM,BDFORMULA,BDNUMITEM, BDCAMPOINATIVO,BDCODITEMONLINE)';
            WINSERT = WINSERT || ' values ('||:codigonovo||','||wBDCODQ||','||wBDNUMCAMPO||','''||:wBDDESCFORM||''','''||:wbdformula||''','||:wBDNUMITEM||','''||:wBDCAMPOINATIVO||''',';
    
            IF (wBDCODITEMONLINE IS NULL) THEN
              BEGIN
                WINSERT = WINSERT ||'null)';
              END
            ELSE
              BEGIN
                WINSERT = WINSERT ||:wBDCODITEMONLINE||')';
              END
    
            WINSERT = WINSERT||' MATCHING (BDCODCONF, BDCODQUADRO, BDNUMCAMPO)';
    
            EXECUTE STATEMENT WINSERT;
         END
    END

END
^

CREATE OR ALTER PROCEDURE VEF_COPIA_PLANO_IMPOSTOS (
    CODIGONOVO INTEGER,
    CODIGOCOPIAR INTEGER,
    TIPOIMP VARCHAR(10)) 
AS
DECLARE VARIABLE FSQL VARCHAR(1000);
BEGIN
  FSQL = 'delete from vef_base_tconf'||tipoimp||'form WHERE BDCODCONF'||TIPOIMP||' = '||:codigonovo;
  EXECUTE STATEMENT FSQL;

  IF ((codigonovo IS NULL) OR (codigonovo = 0)) THEN
     BEGIN
        FSQL = 'SELECT max(BDCODCONF'||TIPOIMP||') from vef_base_tconf'||tipoimp;
        EXECUTE STATEMENT fsql INTO codigonovo;
     END

  FSQL = 'INSERT INTO vef_base_tconf'||tipoimp||'FORM (BDCODCONF'||tipoimp||', bdcodq'||tipoimp||',bdnumcampo'||tipoimp||',BDDESCFORM'||tipoimp||',BDFORMULA'||tipoimp||',BDNUMITEM, BDCAMPOINATIVO';
  
        IF (TIPOIMP = 'IRLP') THEN
           fsql = fsql || ',BDCODITEMONLINE, BDCODREGECF, BDCODTABDIN, BDCHAVEVINCITEM)';
        ELSE
        IF ((TIPOIMP <> 'DAMEF') AND (TIPOIMP <> 'DOT')) THEN
           fsql = fsql || ',BDCODITEMONLINE)';
        ELSE
           fsql = fsql || ')';

  fsql =  fsql || ' select '||:codigonovo||' as BDCODCONF'||tipoimp||', bdcodq'||tipoimp||',bdnumcampo'||tipoimp||',BDDESCFORM'||tipoimp||',BDFORMULA'||tipoimp||',BDNUMITEM, BDCAMPOINATIVO';

        IF (TIPOIMP = 'IRLP') THEN
          FSQL = fsql ||',BDCODITEMONLINE, BDCODREGECF, BDCODTABDIN, BDCHAVEVINCITEM ';
        ELSE
        IF ((TIPOIMP <> 'DAMEF') AND (TIPOIMP <> 'DOT')) THEN
          FSQL = fsql ||',BDCODITEMONLINE ';

  FSQL = fsql ||' from vef_base_tconf'||tipoimp||'form ';
  fsql = fsql || ' where BDCODCONF'||tipoimp|| ' = '|| :codigocopiar;
        EXECUTE STATEMENT fsql;
END^
/* Restore proc. body: VEF_COPIA_PLANO */
CREATE OR ALTER PROCEDURE VEF_COPIA_PLANO (
    CODIGONOVO INTEGER,
    CODIGOCOPIAR INTEGER,
    IMPOSTO VARCHAR(10))
RETURNS (
    CODIGONOVORETORNO INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WTABCONF VARCHAR(32);
DECLARE VARIABLE WTABQUADROS VARCHAR(32);
DECLARE VARIABLE WTABFORMULA VARCHAR(32);
DECLARE VARIABLE WCAMPO VARCHAR(64);
DECLARE VARIABLE WCAMPOSINSERT VARCHAR(1000);
DECLARE VARIABLE WCAMPOPK VARCHAR(10);
BEGIN
  /* Zera os nomes das tabelas */
  wCampoPK    = '';
  wTabConf    = '';
  wTabQuadros = '';
  wTabFormula = '';
  /* Obtém as tabelas do plano */
  IF (IMPOSTO = 'DASN') THEN
    BEGIN
      wCampoPK    = IMPOSTO;
      wTabConf    = 'VEF_BASE_TCONFDASN';
      wTabQuadros = 'VEF_BASE_TCONFDASNQ';
      wTabFormula = 'VEF_BASE_TCONFDASNFORM';
    END
  ELSE
    IF (IMPOSTO = 'DIME') THEN
      BEGIN
        wCampoPK    = 'DIMESC';
        wTabConf    = 'VEF_ESTADOS_TCONFDIMESC';
        wTabQuadros = 'VEF_ESTADOS_TCONFDIMEQ';
        wTabFormula = 'VEF_ESTADOS_TCONFDIMEFORM';
      END
  ELSE
  IF (imposto = 'ST') THEN
    BEGIN
       wCampoPK = 'GIAST';
       wTabConf =    'VEF_BASE_TCONFGIAST';
       wTabQuadros = 'VEF_BASE_TCONFGIASTQ';
       wTabFormula = 'VEF_BASE_TCONFGIASTFORM';
     END
  ELSE
  IF (imposto = 'DECLANRJ') THEN
    BEGIN
       wCampoPK = 'DECLANRJ';
       wTabConf =    'VEF_BASE_TCONFDECLANRJ';
       wTabQuadros = 'VEF_BASE_TCONFDECLANRJQ';
       wTabFormula = 'VEF_BASE_TCONFDECLANRJFORM';
     END

  /* Insere os registros das formulas */
  IF ((wTabConf <> '') AND (wTabQuadros <> '') AND (wTabFormula <> '')) THEN
    BEGIN
      /* Caso o código novo seja zero, obtém o código novo */
      IF ((CodigoNovo IS NULL) OR (CodigoNovo = 0)) THEN
        BEGIN
          wSQL = 'SELECT MAX(BDCODCONF'||wCampoPK||') FROM '||wTabConf;
          EXECUTE STATEMENT wSQL INTO CodigoNovo;
        END
      /* Retorno o código novo */
      CodigoNovoRetorno = CodigoNovo;
      /* Limpa a tabela de formulas no código novo */
      wSQL = 'DELETE FROM '||wTabFormula||' WHERE BDCODCONF'||wCampoPK||' = '||:CodigoNovo;
      EXECUTE STATEMENT wSQL;
      /* Obtém os campos da tabela de formulas */
      wSQL = 'SELECT r.RDB$FIELD_NAME as BDCAMPO '||
             'FROM RDB$RELATION_FIELDS r '||
             'WHERE r.RDB$RELATION_NAME = '''||wTabFormula||'''';
      wCamposInsert = '';
      FOR EXECUTE STATEMENT wSQL
      INTO wCampo DO
        BEGIN
          IF ((wCampo <> 'BDCODCONF'||wCampoPK) AND (wCampo <> 'BDREADONLY')) THEN
            wCamposInsert = wCamposInsert||','||TRIM(wCampo);
        END
      /* Cria insert da tabela de formulas */
      wSQL = 'INSERT INTO '||wTabFormula||' ('||'BDCODCONF'||wCampoPK||wCamposInsert||') '||
             ' SELECT '||CodigoNovo||wCamposInsert||' FROM '||wTabFormula||' WHERE '||'BDCODCONF'||wCampoPK||' = '||CODIGOCOPIAR;
      EXECUTE STATEMENT wSQL;
    END
END^

/* Restore proc. body: VEF_SP_BASE_CONFBASESN */
ALTER PROCEDURE VEF_SP_BASE_CONFBASESN(PRATV VARCHAR(15),
PRNAT INTEGER,
PRCID INTEGER,
PRATVM INTEGER)
 RETURNS(BDCODCONFSN INTEGER,
BDDESCIMP VARCHAR(200),
BDDESCTIPOIMP VARCHAR(200),
BDDESC VARCHAR(500),
BDCODNAT INTEGER,
BDCODATIVSIMPNAC INTEGER,
BDCODCONFSNREAL INTEGER,
BDATIVIDADE INTEGER,
BDCODIMPOSTO INTEGER,
BDCODTIPOIMPOSTO INTEGER,
BDCODBASESN INTEGER,
BDCODCONFATVMSN INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE FORDEM INTEGER;
BEGIN
  /* Procedure Text */

--  execute procedure sp_seta_competencia(pranomesinicial, null, null);

  wsql = '';

  wSql = wSql || ' select SN.bdcodconfsn, SNI.bddescimp, SNIT.bddesctipoimp ,snb.BDDESC, SN.bdcodnat,sn.BDCODATIVSIMPNAC, SN.bdcodconfsn bdcodconfsnReal, 0 BDATIVIDADE,SNI.BDCODIMPOSTO,SN.BDCODTIPOIMPOSTO,sn.bdcodbasesn, 0 BDCODCONFATVMSN ';
  wSql = wSql || ' from VEF_BASE_TNATOPCONFSN sn ';
  wSql = wSql || ' left outer join VEF_BASE_TCADIMPOSTOSN SNI on (sni.bdcodimposto = sn.bdcodimposto) ';
  wSql = wSql || ' left outer join VEF_BASE_TCADTIPOIMPOSTO SNIT on (snit.bdcodtipoimposto = sn.bdcodtipoimposto) ';
  wsql = wsql || ' left outer join VEF_BASE_TCADBASESN SNb on (snb.bdcodbasesn = sn.bdcodbasesn) ';

  IF ((prAtv IS NOT NULL) AND (prAtv <> ''))  THEN
    BEGIN
      wsql = wsql || ' where sn.BDCODATIVSIMPNAC in('||pratv||') ';
    END

  IF ((prNat IS NOT NULL) AND (prNat <> 0))  THEN
    BEGIN
      wsql = wsql || ' and sn.BDCODNAT = '||prNat;
    END

  IF ((prCid IS NOT NULL) AND (prCid <> 0) AND (prATVM IS NOT NULL) AND (prATVM <> 0))  THEN
    BEGIN

      wsql = wsql || ' union ';
    
      wsql = wsql || ' select SN.bdcodconfatvmsn bdcodconfsn, SNI.bddescimp, SNIT.bddesctipoimp, snb.BDDESC, 0 bdcodnat,sn.BDCODATIVSIMPNAC, SN.bdcodconfatvmsn bdcodconfsnReal, 1 BDATIVIDADE,SNI.BDCODIMPOSTO,SN.BDCODTIPOIMPOSTO,sn.bdcodbasesn, SN.BDCODCONFATVMSN ';
      wsql = wsql || ' from VEF_BASE_TCONFATVMSN sn';
      wsql = wsql || ' left outer join VEF_BASE_TCADIMPOSTOSN SNI on (sni.bdcodimposto = sn.bdcodimposto)';
      wsql = wsql || ' left outer join VEF_BASE_TCADTIPOIMPOSTO SNIT on (snit.bdcodtipoimposto = sn.bdcodtipoimposto)';
      wsql = wsql || ' left outer join VEF_BASE_TCADBASESN SNb on (snb.bdcodbasesn = sn.bdcodbasesn)';
    
      IF ((prAtv IS NOT NULL) AND (prAtv <> ''))  THEN
        BEGIN
          wsql = wsql || ' where sn.BDCODATIVSIMPNAC in('||pratv||') ';
        END
      IF ((prCid IS NOT NULL) AND (prCid <> 0))  THEN
        BEGIN
          wsql = wsql || ' and sn.BDCODCID = '||prCid;
        END
      IF ((prATVM IS NOT NULL) AND (prATVM <> 0))  THEN
        BEGIN
          wsql = wsql || ' and sn.BDCODATVM = '||prATVM;
        END
    END

  Fordem = 0;
  FOR EXECUTE STATEMENT wsql
    INTO
      :bdcodconfsn,
      :bddescimp,
      :bddesctipoimp,
      :BDDESC,
      :bdcodnat,
      :BDCODATIVSIMPNAC,
      :bdcodconfsnReal,
      :BDATIVIDADE,
      :BDCODIMPOSTO,
      :BDCODTIPOIMPOSTO,
      :bdcodbasesn,
      :BDCODCONFATVMSN
    DO
    BEGIN
      Fordem = FOrdem + 1;
      bdcodconfsn = fordem;
      SUSPEND;
  
    END
  
END
^

/* Restore proc. body: VEF_SP_BASE_CONFBASESNATVM */
CREATE OR ALTER procedure VEF_SP_BASE_CONFBASESNATVM (
    PRATV varchar(15),
    PRCID integer,
    PRATVM integer,
    PRCODPLANOSN integer)
returns (
    BDCODCONFSN integer,
    BDCODNAT integer,
    BDCODATIVSIMPNAC integer,
    BDCODCONFSNREAL integer,
    BDATIVIDADE integer,
    BDCODTIPOIMPPIS integer,
    BDCODTIPOIMPCOFINS integer,
    BDCODTIPOIMPCSLL integer,
    BDCODTIPOIMPICMS integer,
    BDCODTIPOIMPINSSCPP integer,
    BDCODTIPOIMPIRPJ integer,
    BDCODTIPOIMPIPI integer,
    BDCODTIPOIMPISS integer,
    BDCODPLANOCONFSN integer,
    BDCODBASESN integer,
    BDCODCONFATVMSN integer,
    BDPREPONDERANTE varchar(5),
    BDCODCID integer,
    BDCODATVM integer)
as
declare variable WSQL varchar(10000);
declare variable FORDEM integer;
declare variable WCODIMPOSTO integer;
declare variable WCODTIPOIMPOSTO integer;
BEGIN
  /* Procedure Text */

  wsql = '';

--  IF ((prCid IS NOT NULL) AND (prCid <> 0) AND (prATVM IS NOT NULL) AND (prATVM <> 0))  THEN
    BEGIN
      wsql = wsql || ' select SN.bdcodconfatvmsn bdcodconfsn, /*SNI.bddescimp, SNIT.bddesctipoimp, snb.BDDESC,*/ 0 bdcodnat,sn.BDCODATIVSIMPNAC, ';
      wsql = wsql || ' SN.bdcodconfatvmsn bdcodconfsnReal, 1 BDATIVIDADE, ';
      --SNI.BDCODIMPOSTO,SN.BDCODTIPOIMPOSTO,
      wsql = wsql || ' sn.bdcodbasesn, SN.BDCODCONFATVMSN, SN.BDPREPONDERANTE,sn.BDCODPLANOCONFSN,SN.BDCODCID,SN.bdcodatvM ';
      wsql = wsql || ' from VEF_BASE_TCONFATVMSN sn';
      wsql = wsql || ' left outer join VEF_BASE_TCADIMPOSTOSN SNI on (sni.bdcodimposto = sn.bdcodimposto)';
      wsql = wsql || ' left outer join VEF_BASE_TCADTIPOIMPOSTO SNIT on (snit.bdcodtipoimposto = sn.bdcodtipoimposto)';
      wsql = wsql || ' left outer join VEF_BASE_TCADBASESN SNb on (snb.bdcodbasesn = sn.bdcodbasesn)';
    
      IF ((prCodPlanosn IS NOT NULL) AND (prCodPlanosn <> 0))  THEN
        BEGIN
          wsql = wsql || ' where sn.BDCODPLANOCONFSN  = '||prCodPlanosn||' ';
        END

      IF ((prAtv IS NOT NULL) AND (prAtv <> ''))  THEN
        BEGIN
          wsql = wsql || ' and sn.BDCODATIVSIMPNAC in('||pratv||') ';
        END
      IF ((prCid IS NOT NULL) AND (prCid <> 0))  THEN
        BEGIN
          wsql = wsql || ' and sn.BDCODCID = '||prCid;
        END
      IF ((prATVM IS NOT NULL) AND (prATVM <> 0))  THEN
        BEGIN
          wsql = wsql || ' and sn.BDCODATVM = '||prATVM;
        END
    END

  Fordem = 0;
  FOR EXECUTE STATEMENT wsql
    INTO
      :bdcodconfsn,
      :bdcodnat,
      :BDCODATIVSIMPNAC,
      :bdcodconfsnReal,
      :BDATIVIDADE,
      :bdcodbasesn,
      :BDCODCONFATVMSN,
      :BDPREPONDERANTE,
      :BDCODPLANOCONFSN,
      :BDCODCID ,
      :bdcodatvm
    DO
    BEGIN


      bdcodtipoimpcofins  = 1;
      bdcodtipoimpcsll    = 1;
      bdcodtipoimpicms    = 1;
      bdcodtipoimpinsscpp = 1;
      bdcodtipoimpirpj    = 1;
      bdcodtipoimppis     = 1;
      bdcodtipoimpipi     = 1;
      bdcodtipoimpiss     = 1;


      Fordem = FOrdem + 1;
      bdcodconfsn = fordem;

      wsql =  ' select bdcodimposto,bdcodtipoimposto from vef_base_tconfatvmsn_trib t ';
      IF ((prCodPlanosn IS NOT NULL) AND (prCodPlanosn <> 0))  THEN
        BEGIN
          wsql = wsql || ' where t.BDCODPLANOCONFSN  = '||prCodPlanosn||' ';
        END

      wsql = wsql || ' and t.BDCODATIVSIMPNAC =('||BDCODATIVSIMPNAC||') ';
      wsql = wsql || ' and t.BDCODCID = '||BDCODCID;
      wsql = wsql || ' and t.BDCODATVM = '||bdcodatvm;

      FOR EXECUTE STATEMENT wsql
        INTO :wCodImposto,:wcodtipoimposto do
        begin


          if (:wCodImposto = 1) then
            bdcodtipoimpcofins = wcodtipoimposto;
          else
          if (:wCodImposto = 2) then
            bdcodtipoimpcsll = wcodtipoimposto;
          else
          if (:wCodImposto = 3) then
            bdcodtipoimpicms = wcodtipoimposto;
          else
          if (:wCodImposto = 4) then
            bdcodtipoimpinsscpp = wcodtipoimposto;
          else
          if (:wCodImposto = 5) then
            bdcodtipoimpirpj = wcodtipoimposto;
          else
          if (:wCodImposto = 6) then
            bdcodtipoimppis = wcodtipoimposto;
          else
          if (:wCodImposto = 7) then
            bdcodtipoimpipi = wcodtipoimposto;
          else
          if (:wCodImposto = 8) then
            bdcodtipoimpiss = wcodtipoimposto;

--//  BDCODIMPOSTO    BDDESCIMP                         BDIGNORACALCULO
--//               1  Cofins                            BDCOFINS
--//               2  CSLL                              BDCSLL
--//               3  ICMS                              BDICMS
--//               4  INSS/CPP                          BDCPP
--//               5  IRPJ                              BDIRPJ
--//               6  PIS                               BDPIS_PASEP
--//               7  IPI                               BDIPI
--//               8  ISS                               BDISS

        end

      SUSPEND;
  
    END
  
END^

CREATE OR ALTER procedure VEF_SP_BASE_CONFBASESNNATOP (
    PRATV varchar(15),
    PRNAT integer,
    PRFORMASEQUENCIA integer,
    PRCODPLANOSN integer)
returns (
    BDCODCONFSN integer,
    BDCODNAT integer,
    BDCODATIVSIMPNAC integer,
    BDCODCONFSNREAL integer,
    BDATIVIDADE integer,
    BDCODTIPOIMPPIS integer,
    BDCODTIPOIMPCOFINS integer,
    BDCODTIPOIMPCSLL integer,
    BDCODTIPOIMPICMS integer,
    BDCODTIPOIMPINSSCPP integer,
    BDCODTIPOIMPIRPJ integer,
    BDCODTIPOIMPIPI integer,
    BDCODTIPOIMPISS integer,
    BDCODBASESN integer,
    BDCODCONFATVMSN integer,
    BDPREPONDERANTE varchar(5),
    BDCODCONFSNTAB integer,
    BDCODPLANOCONFSN integer)
as
declare variable WSQL varchar(10000);
declare variable FORDEM integer;
declare variable WCODIMPOSTO integer;
declare variable WCODTIPOIMPOSTO integer;
BEGIN
  /* Procedure Text */

--  execute procedure sp_seta_competencia(pranomesinicial, null, null);

  wsql = '';

  wSql = wSql || ' select SN.bdcodconfsn, /*SNI.bddescimp, SNIT.bddesctipoimp ,snb.BDDESC,*/ SN.bdcodnat,sn.BDCODATIVSIMPNAC, SN.bdcodconfsn bdcodconfsnReal, ';
  wSql = wSql || ' 0 BDATIVIDADE,sn.bdcodbasesn, 0 BDCODCONFATVMSN, sn.bdpreponderante, SN.bdcodconfsn bdcodconfsntab,sn.BDCODPLANOCONFSN ';
  wSql = wSql || ' from VEF_BASE_TNATOPCONFSN sn ';
  wSql = wSql || ' left outer join VEF_BASE_TCADIMPOSTOSN SNI on (sni.bdcodimposto = sn.bdcodimposto) ';
  wSql = wSql || ' left outer join VEF_BASE_TCADTIPOIMPOSTO SNIT on (snit.bdcodtipoimposto = sn.bdcodtipoimposto) ';
  wsql = wsql || ' left outer join VEF_BASE_TCADBASESN SNb on (snb.bdcodbasesn = sn.bdcodbasesn) ';

  IF ((prCodPlanosn IS NOT NULL) AND (prCodPlanosn <> 0))  THEN
    BEGIN
      wsql = wsql || ' where sn.BDCODPLANOCONFSN  = '||prCodPlanosn||' ';
    END

  IF ((prAtv IS NOT NULL) AND (prAtv <> ''))  THEN
    BEGIN
      wsql = wsql || ' and sn.BDCODATIVSIMPNAC in('||pratv||') ';
    END

  IF ((prNat IS NOT NULL) AND (prNat <> 0))  THEN
    BEGIN
      wsql = wsql || ' and sn.BDCODNAT = '||prNat;
    END

  Fordem = 0;
  FOR EXECUTE STATEMENT wsql
    INTO
      :bdcodconfsn,
--      :bddescimp,
--      :bddesctipoimp,
--      :BDDESC,
      :bdcodnat,
      :BDCODATIVSIMPNAC,
      :bdcodconfsnReal,
      :BDATIVIDADE,
--      :BDCODIMPOSTO,
--      :BDCODTIPOIMPOSTO,
      :bdcodbasesn,
      :BDCODCONFATVMSN,
      :bdpreponderante,
      :bdcodconfsntab,
      :BDCODPLANOCONFSN
    DO
    BEGIN
      bdcodtipoimpcofins  = 1;
      bdcodtipoimpcsll    = 1;
      bdcodtipoimpicms    = 1;
      bdcodtipoimpinsscpp = 1;
      bdcodtipoimpirpj    = 1;
      bdcodtipoimppis     = 1;
      bdcodtipoimpipi     = 1;
      bdcodtipoimpiss     = 1;

      wsql =  ' select bdcodimposto,bdcodtipoimposto from VEF_BASE_TNATOPCONFSN_trib t ';
      IF ((prCodPlanosn IS NOT NULL) AND (prCodPlanosn <> 0))  THEN
        BEGIN
          wsql = wsql || ' where t.BDCODPLANOCONFSN  = '||prCodPlanosn||' ';
        END

      wsql = wsql || ' and t.BDCODATIVSIMPNAC =('||BDCODATIVSIMPNAC||') ';
      wsql = wsql || ' and t.BDCODNAT = '||bdcodnat;
      wsql = wsql || ' and t.bdcodconfsn = '||bdcodconfsn;



      /* se tem so uma atividade não vai forma outra sequencia*/
      IF (prFormaSequencia = 1)  THEN
        BEGIN
          Fordem = FOrdem + 1;
          bdcodconfsn = fordem;
        END


      FOR EXECUTE STATEMENT wsql
        INTO :wCodImposto,:wcodtipoimposto do
        begin
          if (:wCodImposto = 1) then
            bdcodtipoimpcofins = wcodtipoimposto;
          else
          if (:wCodImposto = 2) then
            bdcodtipoimpcsll = wcodtipoimposto;
          else
          if (:wCodImposto = 3) then
            bdcodtipoimpicms = wcodtipoimposto;
          else
          if (:wCodImposto = 4) then
            bdcodtipoimpinsscpp = wcodtipoimposto;
          else
          if (:wCodImposto = 5) then
            bdcodtipoimpirpj = wcodtipoimposto;
          else
          if (:wCodImposto = 6) then
            bdcodtipoimppis = wcodtipoimposto;
          else
          if (:wCodImposto = 7) then
            bdcodtipoimpipi = wcodtipoimposto;
          else
          if (:wCodImposto = 8) then
            bdcodtipoimpiss = wcodtipoimposto;

--//  BDCODIMPOSTO    BDDESCIMP                         BDIGNORACALCULO
--//               1  Cofins                            BDCOFINS
--//               2  CSLL                              BDCSLL
--//               3  ICMS                              BDICMS
--//               4  INSS/CPP                          BDCPP
--//               5  IRPJ                              BDIRPJ
--//               6  PIS                               BDPIS_PASEP
--//               7  IPI                               BDIPI
--//               8  ISS                               BDISS

        end


      SUSPEND;
  
    END
END^


/* Restore proc. body: VEF_SP_CONSULTA_CONFATIVA */
ALTER PROCEDURE VEF_SP_CONSULTA_CONFATIVA(PRCODCONFATIVO INTEGER,
PRNUMCAMPO INTEGER,
PRWHERE VARCHAR(5000))
 RETURNS(BDCODCONFATIVO INTEGER,
BDDESCCONF VARCHAR(100),
BDNUMCAMPO INTEGER,
BDNUMITEM INTEGER,
BDDESCFORM VARCHAR(100),
BDFORMULA VARCHAR(30000),
BDINATIVO VARCHAR(5))
 AS
DECLARE VARIABLE wsql VARCHAR(20000);
DECLARE VARIABLE wwhere VARCHAR(10000);
BEGIN
  wSql = ' select ';
  wSql = wSql || 'BDCODCONFATIVO, ';
  wSql = wSql || 'BDDESCCONF, ';
  wSql = wSql || 'BDNUMCAMPO, ';
  wSql = wSql || 'BDNUMITEM, ';
  wSql = wSql || 'BDDESCFORM, ';
  wSql = wSql || 'BDFORMULA, ';
  wSql = wSql || 'BDINATIVO ';
    
   wSql = wsql || ' FROM VW_VEF_BASE_TCONFATIVA ';

  wwhere = '';

  IF (prcodconfativo IS NOT NULL AND prcodconfativo <> 0) THEN
     wwhere = wwhere || ' BDCODCONFATIVO = '||prcodconfativo;

  IF (prnumcampo IS NOT NULL AND prnumcampo <> 0) THEN
     wwhere = wwhere || ' BDNUMCAMPO = '||prnumcampo;

  IF (prwhere IS NOT NULL AND prwhere <> '' AND prwhere <> '0')  THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere ||prwhere;
    END


  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By BDCODCONFATIVO, BDNUMCAMPO ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODCONFATIVO,
    :BDDESCCONF,
    :BDNUMCAMPO,
    :BDNUMITEM,
    :BDDESCFORM,
    :BDFORMULA,
    :BDINATIVO
  DO
  SUSPEND;
END
^

/* Restore proc. body: VEF_SP_CONSULTA_VINCULOISS */
ALTER procedure VEF_SP_CONSULTA_VINCULOISS (
    PRCODCID integer,
    PRREFATUAL integer)
returns (
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDREFVINCISS integer,
    BDCODTIPOISS integer,
    BDDESTIPOISS varchar(50),
    BDCODTIPOISSEXP integer,
    BDDESTIPOISSEXP varchar(50),
BDPERISS DM_NUMERIC_7_4_ALIQ,
BDVALORLIMISS DM_NUMERIC_15_2,
    BDCODTIPORPS integer,
    BDDESTIPORPS varchar(50),
    BDCODIBGE integer,
    BDDEDISS varchar(5))
as
declare variable WSQL varchar(15000);
declare variable WWHERE varchar(3000);
BEGIN
    EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

    wSql = ' select ';
    wSql = wSql || 'BDCODCID, ';
    wSql = wSql || 'BDNOMCID, ';
    wSql = wSql || 'BDREFVINCISS, ';
    wSql = wSql || 'BDCODTIPOISS, ';
    wSql = wSql || 'BDDESTIPOISS, ';
    wSql = wSql || 'BDCODTIPOISSEXP, ';
    wSql = wSql || 'BDDESTIPOISSEXP, ';
    wSql = wSql || 'BDPERISS, ';
    wSql = wSql || 'BDVALORLIMISS, ';
    wSql = wSql || 'BDCODTIPORPS, ';
    wSql = wSql || 'BDDESTIPORPS, ';
    wSql = wSql || 'bdCODIBGE, ';
    wSql = wSql || 'BDDEDISS ';
    wSql = wsql || 'from vw_vef_base_tvinculoiss ';

    wwhere = '';

    IF (prCODCID >  0) THEN
       wWhere = 'where BDCODCID = '||prcodcid||' ';

    wsql = wsql||wwhere||'order by BDCODCID, BDREFVINCISS';
    FOR EXECUTE STATEMENT wsql
    INTO
      :BDCODCID,
      :BDNOMCID ,
      :BDREFVINCISS,
      :BDCODTIPOISS,
      :BDDESTIPOISS,
      :BDCODTIPOISSEXP,
      :BDDESTIPOISSEXP,
      :BDPERISS,
      :BDVALORLIMISS,
      :BDCODTIPORPS,
      :BDDESTIPORPS,
      :bdCODIBGE,
      :bddediss
    DO
    SUSPEND;
END
^

ALTER PROCEDURE VEF_SP_JOINNATPREPONDERANTE (
    PRCODATIVSIMPNAC INTEGER,
    PRCODBASESN INTEGER,
    PRISSRET NUMERIC(15,2))
RETURNS (
    BDCODATIVSIMPNAC INTEGER,
    BDCODCID INTEGER,
    BDCODATVM INTEGER,
    BDCODCONFATVMSN INTEGER,
    BDCODNAT INTEGER,
    BDCODCONFSN INTEGER,
    BDCODBASESN INTEGER,
    BDCODIMPOSTO INTEGER,
    BDCODTIPOIMPOSTO INTEGER,
    BDPREPONDERANTE VARCHAR(5))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  /* Procedure Text */

  wsql = 'select P.BDCODATIVSIMPNAC, null BDCODCID, null BDCODATVM, null BDCODCONFATVMSN, P.BDCODNAT, P.BDCODCONFSN,
                 S.BDCODBASESN, S.BDCODIMPOSTO, S.BDCODTIPOIMPOSTO, S.BDPREPONDERANTE
          from (select C.BDCODNAT, C.BDCODATIVSIMPNAC, C.BDCODPLANOCONFSN, min(C.BDCODCONFSN) "BDCODCONFSN"
                from VEF_BASE_TNATOPCONFSN C
                where (C.BDPREPONDERANTE = '||'''TRUE'''||') and
                      (C.BDCODATIVSIMPNAC = '||:prcodativsimpnac||') and
                      (('||:prissret||' = 0) or (('||:prissret||' > 0) and (C.BDCODBASESN = '||prCODBASESN||')))
                     group by C.BDCODNAT, C.BDCODATIVSIMPNAC, C.BDCODPLANOCONFSN) P
          left outer join VEF_BASE_TNATOPCONFSN S on (S.BDCODNAT = P.BDCODNAT) and (S.BDCODATIVSIMPNAC = P.BDCODATIVSIMPNAC) and (S.BDCODCONFSN = P.BDCODCONFSN) and (S.BDCODPLANOCONFSN = P.BDCODPLANOCONFSN)
          inner join VEF_BASE_TNATOP N on (N.BDCODNAT = P.BDCODNAT) and (upper(N.BDNAOLEVARSN) <> '||'''TRUE'''||')';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODATIVSIMPNAC,
    :BDCODCID,
    :BDCODATVM,
    :BDCODCONFATVMSN,
    :BDCODNAT,
    :BDCODCONFSN,
    :BDCODBASESN,
    :BDCODIMPOSTO,
    :BDCODTIPOIMPOSTO,
    :BDPREPONDERANTE
  DO
     BEGIN
        SUSPEND;

     END
END
^

CREATE OR ALTER procedure VEF_SP_JOINNATNAOPREPONDERANTE (
    PRCODATIVSIMPNAC integer,
    PRCODBASESN integer,
    PRISSRET numeric(15,2),
    PRCODPLANOSN integer)
returns (
    BDCODATIVSIMPNAC integer,
    BDCODCID integer,
    BDCODATVM integer,
    BDCODCONFATVMSN integer,
    BDCODNAT integer,
    BDCODCONFSN integer,
    BDCODBASESN integer,
    BDPREPONDERANTE varchar(5),
    BDCODTIPOIMPPIS integer,
    BDCODTIPOIMPCOFINS integer,
    BDCODTIPOIMPCSLL integer,
    BDCODTIPOIMPICMS integer,
    BDCODTIPOIMPINSSCPP integer,
    BDCODTIPOIMPIRPJ integer,
    BDCODTIPOIMPIPI integer,
    BDCODTIPOIMPISS integer,
    BDCODPLANOCONFSN integer)
as
declare variable WSQL varchar(32700);
declare variable WCODIMPOSTO integer;
declare variable WCODTIPOIMPOSTO integer;
BEGIN
  /* Procedure Text */

   wsql = 'select p.bdcodativsimpnac, null bdcodcid    , null bdcodatvm, null bdcodconfatvmsn,
                 p.bdcodnat        , p.bdcodconfsn    , s.bdcodbasesn , s.bdpreponderante , s.BDCODPLANOCONFSN
          from
          (
              select c.bdcodnat, c.bdcodativsimpnac, min(c.bdcodconfsn) "BDCODCONFSN", c.BDCODPLANOCONFSN
              from VEF_BASE_TNATOPCONFSN c
              where (c.bdpreponderante <> '||'''TRUE'''||') and
                    (c.bdcodativsimpnac = '||:prcodativsimpnac||') and  (('||:prissret||' > 0) and (c.BDCODBASESN = '||prCODBASESN||')) and
                    (c.BDCODPLANOCONFSN = '||:prCodPlanosn||') and
                    not exists
                    (
                        select n.bdcodnat, n.bdcodativsimpnac from VEF_BASE_TNATOPCONFSN n
                        where (n.bdpreponderante = '||'''TRUE'''||') and
                              (n.BDCODPLANOCONFSN = '||:prCodPlanosn||') and (n.bdcodativsimpnac = '||:prcodativsimpnac||') and  (('||:prissret||' > 0) and (n.BDCODBASESN = '||prCODBASESN||')) and
                              (n.bdcodnat = c.bdcodnat) and
                              (n.bdcodativsimpnac = c.bdcodativsimpnac)
                        group by n.bdcodnat, n.bdcodativsimpnac
                    )
              group by c.bdcodnat, c.bdcodativsimpnac, c.BDCODPLANOCONFSN
          ) p
          left outer join VEF_BASE_TNATOPCONFSN s on (s.bdcodnat = p.bdcodnat) and (s.bdcodativsimpnac = p.bdcodativsimpnac) and (s.bdcodconfsn = p.bdcodconfsn) and  (s.BDCODPLANOCONFSN = p.BDCODPLANOCONFSN)
          inner join VEF_BASE_TNATOP n on (n.bdcodnat = p.bdcodnat) and (upper(n.bdnaolevarsn) <> '||'''TRUE'''||')';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODATIVSIMPNAC,
    :BDCODCID,
    :BDCODATVM,
    :BDCODCONFATVMSN,
    :BDCODNAT,
    :BDCODCONFSN,
    :BDCODBASESN,
--    :BDCODIMPOSTO,
--    :BDCODTIPOIMPOSTO,
    :BDPREPONDERANTE,
    :BDCODPLANOCONFSN
  DO
     BEGIN

      bdcodtipoimpcofins  = 1;
      bdcodtipoimpcsll    = 1;
      bdcodtipoimpicms    = 1;
      bdcodtipoimpinsscpp = 1;
      bdcodtipoimpirpj    = 1;
      bdcodtipoimppis     = 1;
      bdcodtipoimpipi     = 1;
      bdcodtipoimpiss     = 1;


      wsql =  ' select bdcodimposto,bdcodtipoimposto from VEF_BASE_TNATOPCONFSN_trib t ';
      IF ((prCodPlanosn IS NOT NULL) AND (prCodPlanosn <> 0))  THEN
        BEGIN
          wsql = wsql || ' where t.BDCODPLANOCONFSN  = '||prCodPlanosn||' ';
        END
      IF ((:BDCODATIVSIMPNAC IS NOT NULL) AND (:BDCODATIVSIMPNAC <> 0))  THEN
        BEGIN
          wsql = wsql || ' and t.BDCODATIVSIMPNAC in('||:BDCODATIVSIMPNAC||') ';
        END
      IF ((:BDCODCID IS NOT NULL) AND (:BDCODCID <> 0))  THEN
        BEGIN
          wsql = wsql || ' and t.BDCODCID = '||:BDCODCID;
        END
      IF ((:BDCODATVM IS NOT NULL) AND (:BDCODATVM <> 0))  THEN
        BEGIN
          wsql = wsql || ' and t.BDCODATVM = '||:BDCODATVM;
        END

      FOR EXECUTE STATEMENT wsql
        INTO :wCodImposto,:wcodtipoimposto do
        begin

          if (:wCodImposto = 1) then
            bdcodtipoimpcofins = wcodtipoimposto;
          else
          if (:wCodImposto = 2) then
            bdcodtipoimpcsll = wcodtipoimposto;
          else
          if (:wCodImposto = 3) then
            bdcodtipoimpicms = wcodtipoimposto;
          else
          if (:wCodImposto = 4) then
            bdcodtipoimpinsscpp = wcodtipoimposto;
          else
          if (:wCodImposto = 5) then
            bdcodtipoimpirpj = wcodtipoimposto;
          else
          if (:wCodImposto = 6) then
            bdcodtipoimppis = wcodtipoimposto;
          else
          if (:wCodImposto = 7) then
            bdcodtipoimpipi = wcodtipoimposto;
          else
          if (:wCodImposto = 8) then
            bdcodtipoimpiss = wcodtipoimposto;

--//  BDCODIMPOSTO    BDDESCIMP                         BDIGNORACALCULO
--//               1  Cofins                            BDCOFINS
--//               2  CSLL                              BDCSLL
--//               3  ICMS                              BDICMS
--//               4  INSS/CPP                          BDCPP
--//               5  IRPJ                              BDIRPJ
--//               6  PIS                               BDPIS_PASEP
--//               7  IPI                               BDIPI
--//               8  ISS                               BDISS

        end



        SUSPEND;

     END
END^



ALTER PROCEDURE VEF_SP_JOINATVPREPONDERANTE (
    PRCODATIVSIMPNAC INTEGER,
    PRCODBASESN INTEGER,
    PRISSRET NUMERIC(15,2))
RETURNS (
    BDCODATIVSIMPNAC INTEGER,
    BDCODCID INTEGER,
    BDCODATVM INTEGER,
    BDCODMUNATVM VARCHAR(20), 
    BDCODCONFATVMSN INTEGER,
    BDCODNAT INTEGER,
    BDCODCONFSN INTEGER,
    BDCODBASESN INTEGER,
    BDCODIMPOSTO INTEGER,
    BDCODTIPOIMPOSTO INTEGER,
    BDPREPONDERANTE VARCHAR(5))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  /* Procedure Text */

  wsql = 'select p.bdcodativsimpnac, p.bdcodcid ,  p.BDCODATVM, p.BDCODMUNATVM  , p.bdcodconfatvmsn, 
              null "BDCODNAT"   , null "BDCODCONFSN", 
              s.bdcodbasesn, s.bdcodimposto, s.bdcodtipoimposto, s.bdpreponderante 
       from 
           ( 
            select a.bdcodativsimpnac, a.bdcodcid,atv.BDCODATVM, atv.BDCODMUNATVM, min(a.bdcodconfatvmsn) "BDCODCONFATVMSN", A.BDCODPLANOCONFSN
            from VEF_BASE_TCONFATVMSN a 
            left outer join tatvmunicipal atv on (a.bdcodatvm = atv.BDCODATVM) 
            where (a.bdcodativsimpnac = '||:prcodativsimpnac||') and
                  (('||:prissret||' = 0) or (('||:prissret||' > 0) and (a.BDCODBASESN = '||prCODBASESN||')))
            group by a.bdcodativsimpnac, a.bdcodcid,atv.BDCODATVM, atv.BDCODMUNATVM, A.BDCODPLANOCONFSN
          ) p 
      left outer join ( 
                       select c.*, a.BDCODMUNATVM from VEF_BASE_TCONFATVMSN c 
                       left outer join tatvmunicipal a on (c.bdcodatvm = a.BDCODATVM) 
                      ) s on (s.bdcodativsimpnac = p.bdcodativsimpnac) and (s.bdcodcid = p.bdcodcid) and (s.BDCODMUNATVM = p.BDCODMUNATVM) and (s.bdcodconfatvmsn = p.bdcodconfatvmsn) and (S.BDCODPLANOCONFSN = P.BDCODPLANOCONFSN)';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODATIVSIMPNAC,
    :BDCODCID,
    :BDCODATVM,
    :BDCODMUNATVM,
    :BDCODCONFATVMSN,
    :BDCODNAT,
    :BDCODCONFSN,
    :BDCODBASESN,
    :BDCODIMPOSTO,
    :BDCODTIPOIMPOSTO,
    :BDPREPONDERANTE
  DO
     BEGIN
        SUSPEND;

     END
END
^

CREATE OR ALTER PROCEDURE VEF_SP_JOINATVNAOPREPONDERANTE (
    PRCODATIVSIMPNAC INTEGER,
    PRCODBASESN INTEGER,
    PRISSRET NUMERIC(15,2),
    PRCODPLANOSN INTEGER,
    PRCODBASESN2 INTEGER = 0)
RETURNS (
    BDCODATIVSIMPNAC INTEGER,
    BDCODCID INTEGER,
    BDCODATVM INTEGER,
    BDCODCONFATVMSN INTEGER,
    BDCODNAT INTEGER,
    BDCODCONFSN INTEGER,
    BDCODBASESN INTEGER,
    BDPREPONDERANTE VARCHAR(5),
    BDCODTIPOIMPPIS INTEGER,
    BDCODTIPOIMPCOFINS INTEGER,
    BDCODTIPOIMPCSLL INTEGER,
    BDCODTIPOIMPICMS INTEGER,
    BDCODTIPOIMPINSSCPP INTEGER,
    BDCODTIPOIMPIRPJ INTEGER,
    BDCODTIPOIMPIPI INTEGER,
    BDCODTIPOIMPISS INTEGER,
    BDCODPLANOCONFSN INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODIMPOSTO INTEGER;
DECLARE VARIABLE WCODTIPOIMPOSTO INTEGER;
BEGIN
  /* Procedure Text */

 wsql = 'select p.bdcodativsimpnac, p.bdcodcid        , p.bdcodatvm  , p.bdcodconfatvmsn, 
           null "BDCODNAT"   , null "BDCODCONFSN", s.bdcodbasesn,  s.bdpreponderante, s.BDCODPLANOCONFSN
    from 
    ( 
        select a.BDCODPLANOCONFSN,a.bdcodativsimpnac, a.bdcodcid, a.bdcodatvm, min(a.bdcodconfatvmsn) "BDCODCONFATVMSN"
        from VEF_BASE_TCONFATVMSN a 
        where (a.bdpreponderante <> '||'''TRUE'''||') and
              (a.bdcodativsimpnac = '||:prcodativsimpnac||') and
              (a.BDCODPLANOCONFSN = '||:prCodPlanosn||') and ';

 if (:prCODBASESN2 > 0) then
    wsql = wsql||' ( ';

 wsql = wsql||' (('||:prissret||' > 0) and (a.BDCODBASESN = '||prCODBASESN||')) ';

 if (:prCODBASESN2 > 0) then
    wsql = wsql||' OR (('||:prissret||' > 0) and (a.BDCODBASESN = '||prCODBASESN2||'))) ';

 wsql = wsql||' and
              not exists 
              ( 
                  select b.BDCODPLANOCONFSN,b.bdcodativsimpnac, b.bdcodcid, b.bdcodatvm from VEF_BASE_TCONFATVMSN b
                  where (b.bdpreponderante = '||'''TRUE'''||') and
                        (b.bdcodativsimpnac = '||:prcodativsimpnac||') and
                        (('||:prissret||' > 0) and (b.BDCODBASESN = '||prCODBASESN||')) and
                        (('||:prissret||' > 0) and (b.BDCODBASESN = '||prCODBASESN2||')) and
                        (b.bdcodcid = a.bdcodcid) and 
                        (b.bdcodatvm = a.bdcodatvm) 
                  group by b.BDCODPLANOCONFSN,b.bdcodativsimpnac, b.bdcodcid, b.bdcodatvm
          ) 
    group by a.BDCODPLANOCONFSN,a.bdcodativsimpnac, a.bdcodcid, a.bdcodatvm
    ) p 
    left outer join VEF_BASE_TCONFATVMSN s on (s.bdcodativsimpnac = p.bdcodativsimpnac) and (s.bdcodcid = p.bdcodcid) and  (s.bdcodatvm = p.bdcodatvm) and (s.bdcodconfatvmsn = p.bdcodconfatvmsn) and (s.BDCODPLANOCONFSN = p.BDCODPLANOCONFSN) ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODATIVSIMPNAC,
    :BDCODCID,
    :BDCODATVM,
    :BDCODCONFATVMSN,
    :BDCODNAT,
    :BDCODCONFSN,
    :BDCODBASESN,
--    :BDCODIMPOSTO,
--    :BDCODTIPOIMPOSTO,
    :BDPREPONDERANTE,
    :BDCODPLANOCONFSN
  DO
     BEGIN



      bdcodtipoimpcofins  = 1;
      bdcodtipoimpcsll    = 1;
      bdcodtipoimpicms    = 1;
      bdcodtipoimpinsscpp = 1;
      bdcodtipoimpirpj    = 1;
      bdcodtipoimppis     = 1;
      bdcodtipoimpipi     = 1;
      bdcodtipoimpiss     = 1;


      wsql =  ' select bdcodimposto,bdcodtipoimposto from vef_base_tconfatvmsn_trib t ';
      IF ((prCodPlanosn IS NOT NULL) AND (prCodPlanosn <> 0))  THEN
        BEGIN
          wsql = wsql || ' where t.BDCODPLANOCONFSN  = '||prCodPlanosn||' ';
        END
      IF ((:BDCODATIVSIMPNAC IS NOT NULL) AND (:BDCODATIVSIMPNAC <> 0))  THEN
        BEGIN
          wsql = wsql || ' and t.BDCODATIVSIMPNAC in('||:BDCODATIVSIMPNAC||') ';
        END
      IF ((:BDCODCID IS NOT NULL) AND (:BDCODCID <> 0))  THEN
        BEGIN
          wsql = wsql || ' and t.BDCODCID = '||:BDCODCID;
        END
      IF ((:BDCODATVM IS NOT NULL) AND (:BDCODATVM <> 0))  THEN
        BEGIN
          wsql = wsql || ' and t.BDCODATVM = '||:BDCODATVM;
        END

      FOR EXECUTE STATEMENT wsql
        INTO :wCodImposto,:wcodtipoimposto do
        begin

          if (:wCodImposto = 1) then
            bdcodtipoimpcofins = wcodtipoimposto;
          else
          if (:wCodImposto = 2) then
            bdcodtipoimpcsll = wcodtipoimposto;
          else
          if (:wCodImposto = 3) then
            bdcodtipoimpicms = wcodtipoimposto;
          else
          if (:wCodImposto = 4) then
            bdcodtipoimpinsscpp = wcodtipoimposto;
          else
          if (:wCodImposto = 5) then
            bdcodtipoimpirpj = wcodtipoimposto;
          else
          if (:wCodImposto = 6) then
            bdcodtipoimppis = wcodtipoimposto;
          else
          if (:wCodImposto = 7) then
            bdcodtipoimpipi = wcodtipoimposto;
          else
          if (:wCodImposto = 8) then
            bdcodtipoimpiss = wcodtipoimposto;

--//  BDCODIMPOSTO    BDDESCIMP                         BDIGNORACALCULO
--//               1  Cofins                            BDCOFINS
--//               2  CSLL                              BDCSLL
--//               3  ICMS                              BDICMS
--//               4  INSS/CPP                          BDCPP
--//               5  IRPJ                              BDIRPJ
--//               6  PIS                               BDPIS_PASEP
--//               7  IPI                               BDIPI
--//               8  ISS                               BDISS

        end


        SUSPEND;

     END
END^


/* Restore proc. body: VEF_SP_CONSULTALAN_ENT */
ALTER PROCEDURE VEF_SP_CONSULTALAN_ENT(PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
 RETURNS(BDCODTER INTEGER,
BDNUMDOCINI INTEGER,
BDDATAEMISSAO DATE,
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6),
BDNUMDOCFIM INTEGER,
BDMODELO INTEGER,
BDEMITENTE INTEGER,
BDDATAENTRADAENT DATE,
BDCODSITNF INTEGER,
BDORDEMINFCOM_D500 INTEGER,
BDCODCTA INTEGER,
BDTIPOASSINANTE INTEGER,
BDVLRSER NUMERIC(15,6),
BDVLRSERNTRIB NUMERIC(15,6),
BDVLRCOBTERC NUMERIC(15,6),
BDVLROUTDESP_D500 NUMERIC(15,6),
BDVLRPIS_D500 NUMERIC(15,6),
BDVLRCOFINS_D500 NUMERIC(15,6),
BDCODTENSAO INTEGER,
BDORDEMINFCOM_C500 INTEGER,
BDORDEMCONS INTEGER,
BDVLRCONSFOR NUMERIC(15,6),
BDVLRCOBTER NUMERIC(15,6),
BDVLRDESPACE NUMERIC(15,6),
BDVLRPIS_C500 NUMERIC(15,6),
BDVLRCOFINS_C500 NUMERIC(15,6),
BDTIPOLIGACAO INTEGER,
BDCHAVENFE VARCHAR(44),
BDINDFRETE INTEGER,
BDVLRFRETE NUMERIC(15,6),
BDVLRSEGURO NUMERIC(15,6),
BDVLROUTDESP_C100 NUMERIC(15,6),
BDVLRTOTPIS NUMERIC(15,6),
BDVLRTOTCOFINS NUMERIC(15,6),
BDVLRTOTPISST NUMERIC(15,6),
BDVLRTOTCOFINSST NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN


    wSql = ' select ';
    wSql = wSql || 'ENT.BDCODTER ,';
    wSql = wSql || 'ENT.BDNUMDOCINI ,';
    wSql = wSql || 'ENT.BDDATAEMISSAO ,';
    wSql = wSql || 'ENT.BDESPECIE ,';
    wSql = wSql || 'ENT.BDSERIE ,';
    wSql = wSql || 'ENT.BDNUMDOCFIM ,';
    wSql = wSql || 'ENT.BDMODELO ,';
    wSql = wSql || 'ENT.BDEMITENTE ,';
    wSql = wSql || 'ENT.BDDATAENTRADAENT ,';
    wSql = wSql || 'ENT.BDCODSITNF ,';
    
    wSql = wSql || 'ENT.BDORDEMINFCOM_D500 ,';
    wSql = wSql || 'ENT.BDCODCTA ,';
    wSql = wSql || 'ENT.BDTIPOASSINANTE ,';
    wSql = wSql || 'ENT.BDVLRSER ,';
    wSql = wSql || 'ENT.BDVLRSERNTRIB ,';
    wSql = wSql || 'ENT.BDVLRCOBTERC ,';
    wSql = wSql || 'ENT.BDVLROUTDESP_D500 ,';
    wSql = wSql || 'ENT.BDVLRPIS_D500 ,';
    wSql = wSql || 'ENT.BDVLRCOFINS_D500 ,';
    
    wSql = wSql || 'ENT.BDCODTENSAO ,';
    wSql = wSql || 'ENT.BDORDEMINFCOM_C500 ,';
    wSql = wSql || 'ENT.BDORDEMCONS ,';
    wSql = wSql || 'ENT.BDVLRCONSFOR ,';
    wSql = wSql || 'ENT.BDVLRCOBTER ,';
    wSql = wSql || 'ENT.BDVLRDESPACE ,';
    wSql = wSql || 'ENT.BDVLRPIS_C500 ,';
    wSql = wSql || 'ENT.BDVLRCOFINS_C500 ,';
    wSql = wSql || 'ENT.BDTIPOLIGACAO ,';
    
    wSql = wSql || 'ENT.BDCHAVENFE ,';
    wSql = wSql || 'ENT.BDINDFRETE ,';
    wSql = wSql || 'ENT.BDVLRFRETE ,';
    wSql = wSql || 'ENT.BDVLRSEGURO ,';
    wSql = wSql || 'ENT.BDVLROUTDESP_C100 ,';
    wSql = wSql || 'ENT.BDVLRTOTPIS ,';
    wSql = wSql || 'ENT.BDVLRTOTCOFINS ,';
    wSql = wSql || 'ENT.BDVLRTOTPISST ,';
    wSql = wSql || 'ENT.BDVLRTOTCOFINSST ';

    wSql = wsql || ' FROM vw_vef_emp_tmovent ENT ';

--    wSql = wsql || ' left outer join tuf UF';
--    wSql = wsql || '  on (TCID.BDCODUF = UF.bdCODUF)';

  wwhere = '';
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
    wwhere = wwhere || ' ENT.bdcodemp = '||prcodemp;

  IF (prwhereemp IS NOT NULL AND prwhereemp = '')  THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere ||prwhereemp;
    END

  IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'ENT.BDDATAENTRADAENT between '||''''||prdataini||''' and '||''''||prdatafim||'''';
     END



  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By ENT.bdcodemp';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODTER ,
    :BDNUMDOCINI,
    :BDDATAEMISSAO,
    :BDESPECIE,
    :BDSERIE,
    :BDNUMDOCFIM,
    :BDMODELO,
    :BDEMITENTE,
    :BDDATAENTRADAENT,
    :BDCODSITNF,
    
    :BDORDEMINFCOM_D500,
    :BDCODCTA,
    :BDTIPOASSINANTE,
    :BDVLRSER,
    :BDVLRSERNTRIB,
    :BDVLRCOBTERC,
    :BDVLROUTDESP_D500,
    :BDVLRPIS_D500,
    :BDVLRCOFINS_D500,
    
    :BDCODTENSAO,
    :BDORDEMINFCOM_C500,
    :BDORDEMCONS,
    :BDVLRCONSFOR,
    :BDVLRCOBTER,
    :BDVLRDESPACE,
    :BDVLRPIS_C500,
    :BDVLRCOFINS_C500,
    :BDTIPOLIGACAO,
    
    :BDCHAVENFE,
    :BDINDFRETE,
    :BDVLRFRETE,
    :BDVLRSEGURO,
    :BDVLROUTDESP_C100,
    :BDVLRTOTPIS,
    :BDVLRTOTCOFINS,
    :BDVLRTOTPISST,
    :BDVLRTOTCOFINSST
  DO
  SUSPEND;

END
^

/* Restore proc. body: VEF_SP_CONSULTALAN_SAI */
ALTER PROCEDURE VEF_SP_CONSULTALAN_SAI(PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
 RETURNS(BDCODTER INTEGER,
BDNUMDOCINI INTEGER,
BDDATAEMISSAO DATE,
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6),
BDNUMDOCFIM INTEGER,
BDMODELO INTEGER,
BDEMITENTE INTEGER,
BDDATASAIDA DATE,
BDCODSITNF INTEGER,
BDORDEMINFCOM_D500 INTEGER,
BDCODCTA INTEGER,
BDTIPOASSINANTE INTEGER,
BDVLRSER NUMERIC(15,6),
BDVLRSERNTRIB NUMERIC(15,6),
BDVLRCOBTERC NUMERIC(15,6),
BDVLROUTDESP_D500 NUMERIC(15,6),
BDVLRPIS_D500 NUMERIC(15,6),
BDVLRCOFINS_D500 NUMERIC(15,6),
BDCODTENSAO INTEGER,
BDORDEMINFCOM_C500 INTEGER,
BDORDEMCONS INTEGER,
BDVLRCONSFOR NUMERIC(15,6),
BDVLRCOBTER NUMERIC(15,6),
BDVLRDESPACE NUMERIC(15,6),
BDVLRPIS_C500 NUMERIC(15,6),
BDVLRCOFINS_C500 NUMERIC(15,6),
BDTIPOLIGACAO INTEGER,
BDCHAVENFE VARCHAR(44),
BDINDFRETE INTEGER,
BDVLRFRETE NUMERIC(15,6),
BDVLRSEGURO NUMERIC(15,6),
BDVLROUTDESP_C100 NUMERIC(15,6),
BDVLRTOTPIS NUMERIC(15,6),
BDVLRTOTCOFINS NUMERIC(15,6),
BDVLRTOTPISST NUMERIC(15,6),
BDVLRTOTCOFINSST NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN


    wSql = ' select ';
    wSql = wSql || 'SAI.BDCODTER ,';
    wSql = wSql || 'SAI.BDNUMDOCINI ,';
    wSql = wSql || 'SAI.BDDATAEMISSAO ,';
    wSql = wSql || 'SAI.BDESPECIE ,';
    wSql = wSql || 'SAI.BDSERIE ,';
    wSql = wSql || 'SAI.BDNUMDOCFIM ,';
    wSql = wSql || 'SAI.BDMODELO ,';
    wSql = wSql || 'SAI.BDEMITENTE ,';
    wSql = wSql || 'SAI.BDDATASAIDA ,';
    wSql = wSql || 'SAI.BDCODSITNF ,';
    
    wSql = wSql || 'SAI.BDORDEMINFCOM_D500 ,';
    wSql = wSql || 'SAI.BDCODCTA ,';
    wSql = wSql || 'SAI.BDTIPOASSINANTE ,';
    wSql = wSql || 'SAI.BDVLRSER ,';
    wSql = wSql || 'SAI.BDVLRSERNTRIB ,';
    wSql = wSql || 'SAI.BDVLRCOBTERC ,';
    wSql = wSql || 'SAI.BDVLROUTDESP_D500 ,';
    wSql = wSql || 'SAI.BDVLRPIS_D500 ,';
    wSql = wSql || 'SAI.BDVLRCOFINS_D500 ,';
    
    wSql = wSql || 'SAI.BDCODTENSAO ,';
    wSql = wSql || 'SAI.BDORDEMINFCOM_C500 ,';
    wSql = wSql || 'SAI.BDORDEMCONS ,';
    wSql = wSql || 'SAI.BDVLRCONSFOR ,';
    wSql = wSql || 'SAI.BDVLRCOBTER ,';
    wSql = wSql || 'SAI.BDVLRDESPACE ,';
    wSql = wSql || 'SAI.BDVLRPIS_C500 ,';
    wSql = wSql || 'SAI.BDVLRCOFINS_C500 ,';
    wSql = wSql || 'SAI.BDTIPOLIGACAO ,';
    
    wSql = wSql || 'SAI.BDCHAVENFE ,';
    wSql = wSql || 'SAI.BDINDFRETE ,';
    wSql = wSql || 'SAI.BDVLRFRETE ,';
    wSql = wSql || 'SAI.BDVLRSEGURO ,';
    wSql = wSql || 'SAI.BDVLROUTDESP_C100 ,';
    wSql = wSql || 'SAI.BDVLRTOTPIS ,';
    wSql = wSql || 'SAI.BDVLRTOTCOFINS ,';
    wSql = wSql || 'SAI.BDVLRTOTPISST ,';
    wSql = wSql || 'SAI.BDVLRTOTCOFINSST ';

    wSql = wsql || ' FROM vw_vef_emp_tmovsai SAI ';

--    wSql = wsql || ' left outer join tuf UF';
--    wSql = wsql || '  on (TCID.BDCODUF = UF.bdCODUF)';

  wwhere = '';
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
    wwhere = wwhere || ' SAI.bdcodemp = '||prcodemp;

  IF (prwhereemp IS NOT NULL AND prwhereemp = '')  THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere ||prwhereemp;
    END

  IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'SAI.BDDATAEMISSAO between '||''''||prdataini||''' and '||''''||prdatafim||'''';
     END



  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By SAI.bdcodemp';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODTER ,
    :BDNUMDOCINI,
    :BDDATAEMISSAO,
    :BDESPECIE,
    :BDSERIE,
    :BDNUMDOCFIM,
    :BDMODELO,
    :BDEMITENTE,
    :BDDATASAIDA,
    :BDCODSITNF,
    
    :BDORDEMINFCOM_D500,
    :BDCODCTA,
    :BDTIPOASSINANTE,
    :BDVLRSER,
    :BDVLRSERNTRIB,
    :BDVLRCOBTERC,
    :BDVLROUTDESP_D500,
    :BDVLRPIS_D500,
    :BDVLRCOFINS_D500,
    
    :BDCODTENSAO,
    :BDORDEMINFCOM_C500,
    :BDORDEMCONS,
    :BDVLRCONSFOR,
    :BDVLRCOBTER,
    :BDVLRDESPACE,
    :BDVLRPIS_C500,
    :BDVLRCOFINS_C500,
    :BDTIPOLIGACAO,
    
    :BDCHAVENFE,
    :BDINDFRETE,
    :BDVLRFRETE,
    :BDVLRSEGURO,
    :BDVLROUTDESP_C100,
    :BDVLRTOTPIS,
    :BDVLRTOTCOFINS,
    :BDVLRTOTPISST,
    :BDVLRTOTCOFINSST
  DO
  SUSPEND;

END
^

/* Restore proc. body: VEF_SP_DADOS_ISS_EXP */
ALTER PROCEDURE VEF_SP_DADOS_ISS_EXP(PRWHEREISS VARCHAR(10000) = NULL,
PRWHERECID VARCHAR(10000) = NULL,
PRWHEREEMP VARCHAR(32000) = NULL,
PRREFINI INTEGER = 0,
PRREFFIN INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDREFEMP INTEGER,
BDCODCID INTEGER,
BDCODTIPOISSEXP INTEGER)
 AS
DECLARE VARIABLE WWHERE VARCHAR(32000);
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WMES VARCHAR(2);
DECLARE VARIABLE WANO VARCHAR(4);
BEGIN
  /*
    Data última alteração: 02/08/2013 11:54
    para cada referencia entre a ref. inicial e final,
    cria um registro com:
      -código da empresa
      -código da cidade
      -referencia atual
      -código do tipo de ISS
  */

  IF (NOT ((prwhereiss IS NULL) OR (prwherecid IS NULL) OR (PRWHEREEMP IS NULL) OR (PRREFINI = 0) OR (PRREFFIN = 0))) THEN
    BEGIN
      WWHERE  = '';
      WREFATU = PRREFINI;

      IF (PRWHEREEMP <> '') THEN
         WWHERE = ' WHERE '||PRWHEREEMP;
    
      WHILE (:WREFATU <= PRREFFIN) DO
        BEGIN
          --seta competencia para a referencia atual
          EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:WREFATU);

          /*se na tabela do vinculoISS existe cadastrado algum registro com referencia menor do que a referencia atual, utiliza esse registro,
            caso contrario, procura pelo registro com a menor referencia que seja maior do que a referencia atual*/
          WSQL = 'SELECT I.BDCODEMP, I.BDCODCID, ISS.BDCODTIPOISSEXP, i.BDREFVINCISS FROM ';
          WSQL = WSQL||'( ';
          WSQL = WSQL||'SELECT I.BDCODEMP, I.BDCODCID, MIN(I.BDREFVINCISS) BDREFVINCISS FROM ';
          WSQL = WSQL||'     ( ';

          --pega o registro com a maior referencia, menor ou igual a referencia atual
          WSQL = WSQL||'         SELECT E.BDCODEMP, I.BDCODCID, MAX(I.BDREFVINCISS) BDREFVINCISS FROM VEF_BASE_TVINCULOISS I ';
          WSQL = WSQL||'         INNER JOIN (SELECT E.BDCODEMP, E.BDCODCID, E.BDREFEMP FROM VW_TEMPRESAS_REF E'||WWHERE||') E ON E.BDCODCID = I.BDCODCID ';
          WSQL = WSQL||'         WHERE I.BDREFVINCISS <= '||WREFATU;
          WSQL = WSQL||'         GROUP BY E.BDCODEMP, I.BDCODCID ';

          WSQL = WSQL||'         UNION ALL ';

          --pega o registro com a menor referencia, maior do que a referencia atual
          WSQL = WSQL||'         SELECT E.BDCODEMP, I.BDCODCID, MIN(I.BDREFVINCISS) BDREFVINCISS FROM VEF_BASE_TVINCULOISS I ';
          WSQL = WSQL||'         INNER JOIN (SELECT E.BDCODEMP, E.BDCODCID, E.BDREFEMP FROM VW_TEMPRESAS_REF E'||WWHERE||') E ON E.BDCODCID = I.BDCODCID ';
          WSQL = WSQL||'         WHERE I.BDREFVINCISS >  '||WREFATU;
          WSQL = WSQL||'         GROUP by e.bdcodemp, i.bdcodcid ';

          wsql = wsql||'     ) i ';
          wsql = wsql||'group by i.bdcodemp, i.bdcodcid ';
          wsql = wsql||') i ';
          wsql = wsql||'LEFT outer join VEF_BASE_TVINCULOISS ISS ON ISS.BDCODCID = I.BDCODCID AND ISS.BDREFVINCISS = I.BDREFVINCISS ';

          IF (prwherecid <> '') THEN
             wsql = 'select * from ('||wsql||') i where '||prwherecid;

          IF (prwhereiss <> '') THEN
             wsql = 'select * from ('||wsql||') i where '||prwhereiss;

          FOR EXECUTE STATEMENT WSQL
          INTO
            :BDCODEMP,
            :BDCODCID,
            :BDCODTIPOISSEXP,
            :BDREFEMP
          DO
            BEGIN
              BDREFEMP = WREFATU;
              SUSPEND;
            END

          /*pegar próxima referencia*/
          WANO = SUBSTRING(:WREFATU FROM 1 FOR 4);
          WMES = SUBSTRING(:WREFATU FROM 5 FOR 2);

          SELECT R.ANO, R.MES FROM REF_SEGUINTE(:WMES, :WANO) R INTO :WANO, :WMES;

          IF (CHAR_LENGTH(:WMES) < 2) THEN
             WMES = '0'||:WMES;

          WREFATU = :WANO||:WMES;
        END
    END
END
^

/* Restore proc. body: VEF_SP_DADOSQ46 */
ALTER PROCEDURE VEF_SP_DADOSQ46 RETURNS(BDCODPERIODO INTEGER,
BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDCODQDIME INTEGER,
BDNUMCAMPO INTEGER,
BDCODNAT INTEGER,
BDVALOR NUMERIC(18,6),
BDCODCID INTEGER,
BDCODCIDTOT INTEGER,
BDCODUF INTEGER,
BDDATAREC DATE,
BDCLAVENDIMEGERQ12 INTEGER,
BDCODRECDIMEGERQ12 INTEGER,
BDORIGEMDIMEGERQ46 INTEGER,
BDIDENTIFICACAOREGESP VARCHAR(15),
BDQ12 VARCHAR(5),
BDQ46 VARCHAR(5))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODQDIME INTEGER;
BEGIN
  wsql = 'SELECT BDCODQDIME from VEF_ESTADOS_TCONFDIMEQ WHERE BDCODTIPO = 72';

  EXECUTE STATEMENT wsql INTO WCODQDIME;

  wsql = 'select  7 BDCODPERIODO, d.BDCODEMP, d.bdrefregesp BDREFERENCIA, '||WCODQDIME||' BDCODQDIME, 1 BDNUMCAMPO, null BDCODNAT,';
  wsql = wsql || ' d.bdvalorregesp BDVALOR, null BDCODCID, null BDCODCIDTOT,null BDCODUF,null BDDATAREC,null BDCLAVENDIMEGERQ12,';
  wsql = wsql || ' null BDCODRECDIMEGERQ12, t.bdcodigoexp BDORIGEMDIMEGERQ46,d.BDIDENTIFICACAOREGESP, ';
  wsql = wsql || ' ''FALSE'' BDQ12,';
  wsql = wsql || ' ''TRUE'' BDQ46 ';
  wsql = wsql || ' from VEF_EMP_TDIMEGERREGESP d, VEF_BASE_TTABORIGREGESP t';
  wsql = wsql || ' where d.bdorigemregesp = t.bdorigemregesp';

  wsql = wsql || ' UNION ';

  wsql = wsql || 'select  BDCODPERIODO,BDCODEMP,BDREFERENCIA,BDCODQDIME,BDNUMCAMPO,null BDCODNAT,BDVALOR,';
  wsql = wsql || ' null BDCODCID,null BDCODCIDTOT,null BDCODUF,null BDDATAREC, null BDCLAVENDIMEGERQ12,';
  wsql = wsql || ' null BDCODRECDIMEGERQ12,BDORIGEMDIMEGERQ46,null BDIDENTIFICACAOREGESP,''FALSE'' BDQ12,''TRUE'' BDQ46';
  wsql = wsql || ' from VEF_EMP_TDIMEGERQ46';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODPERIODO,
    BDCODEMP,
    BDREFERENCIA,
    BDCODQDIME,
    BDNUMCAMPO,
    BDCODNAT,
    BDVALOR,
    BDCODCID,
    BDCODCIDTOT,
    BDCODUF,
    BDDATAREC,
    BDCLAVENDIMEGERQ12,
    BDCODRECDIMEGERQ12,
    BDORIGEMDIMEGERQ46,
    BDIDENTIFICACAOREGESP,
    BDQ12,
    BDQ46
  DO
  BEGIN

    SUSPEND;
  END

END
^

/* Restore proc. body: VEF_SP_DIMEQ46 */
ALTER PROCEDURE VEF_SP_DIMEQ46 RETURNS(BDCODPERIODO INTEGER,
BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDCODQDIME INTEGER,
BDNUMCAMPO INTEGER,
BDCODNAT INTEGER,
BDVALOR NUMERIC(18,6),
BDCODCID INTEGER,
BDCODCIDTOT INTEGER,
BDCODUF INTEGER,
BDDATAREC DATE,
BDCLAVENDIMEGERQ12 INTEGER,
BDCODRECDIMEGERQ12 INTEGER,
BDORIGEMDIMEGERQ46 INTEGER,
BDIDENTIFICACAOREGESP VARCHAR(15),
BDQ12 VARCHAR(5),
BDQ46 VARCHAR(5))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCONT INTEGER;
DECLARE VARIABLE WCODPERIODOAUX INTEGER;
DECLARE VARIABLE WCODEMPAUX INTEGER;
DECLARE VARIABLE WREFERENCIAAUX INTEGER;
DECLARE VARIABLE WTOTAL NUMERIC(18,6);
DECLARE VARIABLE WCODPERIODO INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WCODQDIME INTEGER;
DECLARE VARIABLE WCODPERIODOBKP INTEGER;
DECLARE VARIABLE WCODEMPBKP INTEGER;
DECLARE VARIABLE WREFERENCIABKP INTEGER;
DECLARE VARIABLE WCODQDIMEBKP INTEGER;
DECLARE VARIABLE WNUMCAMPOBKP INTEGER;
DECLARE VARIABLE WCODNATBKP INTEGER;
DECLARE VARIABLE WVALORBKP NUMERIC(18,6);
DECLARE VARIABLE WCODCIDBKP INTEGER;
DECLARE VARIABLE WCODCIDTOTBKP INTEGER;
DECLARE VARIABLE WCODUFBKP INTEGER;
DECLARE VARIABLE WDATARECBKP DATE;
DECLARE VARIABLE WCLAVENDIMEGERQ12BKP INTEGER;
DECLARE VARIABLE WCODRECDIMEGERQ12BKP INTEGER;
DECLARE VARIABLE WORIGEMDIMEGERQ46BKP INTEGER;
DECLARE VARIABLE WIDENTIFICACAOREGESPBKP VARCHAR(15);
DECLARE VARIABLE WQ12BKP VARCHAR(5);
DECLARE VARIABLE WQ46BKP VARCHAR(5);
BEGIN
  wsql = 'select BDCODPERIODO,BDCODEMP,BDREFERENCIA,BDCODQDIME,BDNUMCAMPO,BDCODNAT,BDVALOR,BDCODCID,';
  wsql = wsql || ' BDCODCIDTOT,BDCODUF,BDDATAREC,BDCLAVENDIMEGERQ12,BDCODRECDIMEGERQ12,BDORIGEMDIMEGERQ46,BDIDENTIFICACAOREGESP,BDQ12,BDQ46';
  wsql = wsql || ' from VEF_SP_DADOSQ46 ';
  wsql = wsql || ' WHERE BDVALOR > 0';

  wsql = wsql || ' ORDER BY BDCODPERIODO,BDCODEMP,BDREFERENCIA';--FOI NECESSÁRIO CRIAR OUTRA STORE PROCEDURE POIS NÃO TEM COMO COLOCAR ORDER BY NO UNION
  WCont = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODPERIODO,
    BDCODEMP,
    BDREFERENCIA,
    BDCODQDIME,
    BDNUMCAMPO,
    BDCODNAT,
    BDVALOR,
    BDCODCID,
    BDCODCIDTOT,
    BDCODUF,
    BDDATAREC,
    BDCLAVENDIMEGERQ12,
    BDCODRECDIMEGERQ12,
    BDORIGEMDIMEGERQ46,
    BDIDENTIFICACAOREGESP,
    BDQ12,
    BDQ46
  DO
  BEGIN
    IF (wCont = 0) THEN
      BEGIN
         WCODPERIODOAUX = BDCODPERIODO;
         wcodempaux = BDCODEMP;
         wreferenciaaux = BDREFERENCIA;
         WTOTAL = 0;
      END

    wCont = 1;

    IF ((WCODPERIODOAUX <> BDCODPERIODO) OR (wcodempaux <> BDCODEMP) OR (wreferenciaaux <> BDREFERENCIA)) THEN--990
       BEGIN
        WCODPERIODOBKP = BDCODPERIODO;
        WCODEMPBKP = BDCODEMP;
        WREFERENCIABKP = BDREFERENCIA;
        WCODQDIMEBKP = BDCODQDIME;
        WNUMCAMPOBKP = BDNUMCAMPO;
        WCODNATBKP = BDCODNAT;
        WVALORBKP = BDVALOR;
        WCODCIDBKP = BDCODCID;
        WCODCIDTOTBKP = BDCODCIDTOT;
        WCODUFBKP = BDCODUF;
        WDATARECBKP = BDDATAREC;
        WCLAVENDIMEGERQ12BKP = BDCLAVENDIMEGERQ12;
        WCODRECDIMEGERQ12BKP = BDCODRECDIMEGERQ12;
        WORIGEMDIMEGERQ46BKP = BDORIGEMDIMEGERQ46;
        WIDENTIFICACAOREGESPBKP = BDIDENTIFICACAOREGESP;
        WQ12BKP = BDQ12;
        WQ46BKP = BDQ46;

        BDCODPERIODO = wCODPERIODO;
        BDCODEMP = wCODEMP;
        BDREFERENCIA = wREFERENCIA;
        BDCODQDIME = wCODQDIME;
        BDNUMCAMPO = 990;
        BDCODNAT = NULL;
        BDVALOR = WTOTAL;
        BDCODCID = NULL;
        BDCODCIDTOT = NULL;
        BDCODUF = NULL;
        BDDATAREC = NULL;
        BDCLAVENDIMEGERQ12 = NULL;
        BDCODRECDIMEGERQ12 = NULL;
        BDORIGEMDIMEGERQ46 = NULL;
        BDIDENTIFICACAOREGESP = NULL;
        BDQ12 = 'FALSE';
        BDQ46 = 'TRUE';

        SUSPEND;

        WTOTAL = 0;

        BDCODPERIODO = WCODPERIODOBKP;
        BDCODEMP = WCODEMPBKP;
        BDREFERENCIA = WREFERENCIABKP;
        BDCODQDIME = WCODQDIMEBKP;
        BDNUMCAMPO = WNUMCAMPOBKP;
        BDCODNAT = WCODNATBKP;
        BDVALOR = WVALORBKP;
        BDCODCID = WCODCIDBKP;
        BDCODCIDTOT = WCODCIDTOTBKP;
        BDCODUF = WCODUFBKP;
        BDDATAREC = WDATARECBKP;
        BDCLAVENDIMEGERQ12 = WCLAVENDIMEGERQ12BKP;
        BDCODRECDIMEGERQ12 = WCODRECDIMEGERQ12BKP;
        BDORIGEMDIMEGERQ46 = WORIGEMDIMEGERQ46BKP;
        BDIDENTIFICACAOREGESP = WIDENTIFICACAOREGESPBKP;
        BDQ12 = WQ12BKP;
        BDQ46 = WQ46BKP;
       END

    WTOTAL = WTOTAL + BDVALOR;

    SUSPEND;

    WCODPERIODO = BDCODPERIODO;
    WCODEMP = BDCODEMP;
    WREFERENCIA = BDREFERENCIA;
    WCODQDIME = BDCODQDIME;

    WCODPERIODOAUX = BDCODPERIODO;
    wcodempaux = BDCODEMP;
    wreferenciaaux = BDREFERENCIA;
  END

  IF (wCont > 0) THEN--990
    BEGIN
      BDCODPERIODO = wCODPERIODO;
      BDCODEMP = wCODEMP;
      BDREFERENCIA = wREFERENCIA;
      BDCODQDIME = wCODQDIME;
      BDNUMCAMPO = 990;
      BDCODNAT = NULL;
      BDVALOR = WTOTAL;
      BDCODCID = NULL;
      BDCODCIDTOT = NULL;
      BDCODUF = NULL;
      BDDATAREC = NULL;
      BDCLAVENDIMEGERQ12 = NULL;
      BDCODRECDIMEGERQ12 = NULL;
      BDORIGEMDIMEGERQ46 = NULL;
      BDIDENTIFICACAOREGESP = NULL;
      BDQ12 = 'FALSE';
      BDQ46 = 'TRUE';

      SUSPEND;
    END
END
^

/* Restore proc. body: VEF_SP_DIRF */
ALTER PROCEDURE VEF_SP_DIRF(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PREXPORTARNOTAS INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODRECIVSUP INTEGER,
BDREFLAN INTEGER,
BDCODTER INTEGER,
BDCNPJIVSUP VARCHAR(18),
BDNOMEEMPIVSUP VARCHAR(100),
BDIRJANIVSUP NUMERIC(18,6),
BDIRFEVIVSUP NUMERIC(18,6),
BDIRMARIVSUP NUMERIC(18,6),
BDIRABRIVSUP NUMERIC(18,6),
BDIRMAIIVSUP NUMERIC(18,6),
BDIRJUNIVSUP NUMERIC(18,6),
BDIRJULIVSUP NUMERIC(18,6),
BDIRAGOIVSUP NUMERIC(18,6),
BDIRSETIVSUP NUMERIC(18,6),
BDIROUTIVSUP NUMERIC(18,6),
BDIRNOVIVSUP NUMERIC(18,6),
BDIRDEZIVSUP NUMERIC(18,6),
BDRENJANIVSUP NUMERIC(18,6),
BDRENFEVIVSUP NUMERIC(18,6),
BDRENMARIVSUP NUMERIC(18,6),
BDRENABRIVSUP NUMERIC(18,6),
BDRENMAIIVSUP NUMERIC(18,6),
BDRENJUNIVSUP NUMERIC(18,6),
BDRENJULIVSUP NUMERIC(18,6),
BDRENAGOIVSUP NUMERIC(18,6),
BDRENSETIVSUP NUMERIC(18,6),
BDRENOUTIVSUP NUMERIC(18,6),
BDRENNOVIVSUP NUMERIC(18,6),
BDRENDEZIVSUP NUMERIC(18,6),
BDACREDEDUIRSERJAN NUMERIC(18,6),
BDACREDEDUIRSERFEV NUMERIC(18,6),
BDACREDEDUIRSERMAR NUMERIC(18,6),
BDACREDEDUIRSERABR NUMERIC(18,6),
BDACREDEDUIRSERMAIO NUMERIC(18,6),
BDACREDEDUIRSERJUN NUMERIC(18,6),
BDACREDEDUIRSERJUL NUMERIC(18,6),
BDACREDEDUIRSERAGO NUMERIC(18,6),
BDACREDEDUIRSERSET NUMERIC(18,6),
BDACREDEDUIRSEROUT NUMERIC(18,6),
BDACREDEDUIRSERNOV NUMERIC(18,6),
BDACREDEDUIRSERDEZ NUMERIC(18,6),
BDINDIMUNEISE INTEGER)
AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WGROUPBY VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
DECLARE VARIABLE WULTCODREC INTEGER;
DECLARE VARIABLE WULTCODEMP INTEGER;
DECLARE VARIABLE WULTCODTER INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMETER VARCHAR(100);
DECLARE VARIABLE WCGCTER VARCHAR(18);
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WCODREC INTEGER;
DECLARE VARIABLE WREFLAN INTEGER;
DECLARE VARIABLE WVLRCONTAB NUMERIC(18,6);
DECLARE VARIABLE WVLRIMPOSTO NUMERIC(18,6);
DECLARE VARIABLE WVLRACREDEDUIRSER NUMERIC(18,6);
DECLARE VARIABLE WINDIMUNEISE INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

  wSql = 'select temp.BDCODEMP, ';
  wSql = wSql || 'vwterc.bdcodter, ';
  wSql = wSql || 'vwterc.bdcgcter, ';
  wSql = wSql || 'vwterc.bdnometer, ';
  wSql = wSql || 'vwterc.BDINDIMUNEISE, ';
  wSql = wSql || 'vwunionrec.BDCODREC, ';
  wSql = wSql || 'vwunionrec.BDREFLAN, ';
  wSql = wSql || 'sum(BDVLRCONTAB) SUMVLRCONTAB, ';
  wSql = wSql || 'sum(BDACREDEDUIRSER) SUMACREDEDUIRSER, ';
  wSql = wSql || 'sum(BDVLRIMPOSTO) SUMVLRIMPOSTO ';  
  IF (prempresas IS NOT NULL) THEN
    wSql = wSql || 'from (SELECT BDCODEMP FROM TEMPRESAS WHERE '||PREMPRESAS||') temp ';
  ELSE                              
    wSql = wSql || 'from TEMPRESAS temp ';
    
  --wSql = wSql || 'left outer join vw_unionrec_ir_pis_cofins_csll vwunionrec on (vwunionrec.bdcodemp = temp.bdcodemp) ';
  wSql = wSql || 'left outer join VW_REC_IR_PIS_COFINS_CSLL_Aux vwunionrec on (vwunionrec.bdcodemp = temp.bdcodemp) ';
  wSql = wSql || 'left outer join vw_tterceiro vwterc on (vwterc.bdcodter = vwunionrec.bdCODTER ) ';

  wwhere = '';

     --wwhere = wWhere||prempresas||' ';

  IF ((prrefini IS NOT NULL) AND (prrefini > 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'vwunionrec.BDREFLAN >= '||prrefini||' ';
     END

  IF ((prreffin IS NOT NULL) AND (prreffin > 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'vwunionrec.BDREFLAN <= '||prreffin||' ';
     END

  IF ((prexportarnotas IS NOT NULL) AND (prexportarnotas = 0)) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'vwunionrec.BDVLRIMPOSTO > 0 ';
     END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';

  wwhere = wwhere||'vwunionrec.BDTIPLAN = 1 ';

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';

  wwhere = wwhere||'vwunionrec.BDTIPIMPOSTO in (2,11,12)';


  IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

  wgroupby = 'group by temp.BDCODEMP,
                       vwterc.bdcodter,
                       vwterc.bdcgcter,
                       vwterc.bdnometer,
                       vwterc.bdindimuneise,
                       vwunionrec.BDCODREC,
                       vwunionrec.BDREFLAN ';

  worderby = 'order by temp.bdcodemp, vwterc.bdCODTER, vwunionrec.bdcodrec, vwunionrec.bdreflan ';

  wsql = wsql||wwhere||wgroupby||worderby;
  wultcodemp = 0;
  wultcodrec = 0;
  wultcodter = 0;
  FOR EXECUTE STATEMENT wsql
    INTO
      :wCODEMP,
      :wCODTER,
      :wCGCTER,
      :wNOMETER,
      :wINDIMUNEISE,
      :wCODREC,
      :wREFLAN,
      :wVLRCONTAB,
      :wVLRACREDEDUIRSER,
      :wVLRIMPOSTO
     DO
     BEGIN
        BDINDIMUNEISE   = wINDIMUNEISE;
        IF ((wultcodemp <> wcodemp) OR (wultcodter <> wcodter) OR (wultcodrec <> wcodrec))THEN
           BEGIN
              IF (wultcodrec <> 0) THEN
                 SUSPEND;
              bdcodemp       = wcodemp;
              bdcodter       = wcodter;
              bdcnpjivsup    = wcgcter;
              bdnomeempivsup = wnometer;
              bdcodrecivsup  = wcodrec;
              bdreflan       = wreflan;

              bdirJANivsup        = 0;
              bdrenJANivsup       = 0;
              bdacrededuirserjan  = 0;

              bdirFEVivsup        = 0;
              bdrenFEVivsup       = 0;
              bdacrededuirserfev  = 0;

              bdirMARivsup        = 0;
              bdrenMARivsup       = 0;
              bdacrededuirsermar  = 0;

              bdirABRivsup        = 0;
              bdrenABRivsup       = 0;
              bdacrededuirserabr  = 0;

              bdirMAIivsup        = 0;
              bdrenMAIivsup       = 0;
              bdacrededuirsermaio = 0;

              bdirJUNivsup        = 0;
              bdrenJUNivsup       = 0;
              bdacrededuirserjun  = 0;

              bdirJULivsup        = 0;
              bdrenJULivsup       = 0;
              bdacrededuirserjul  = 0;

              bdirAGOivsup        = 0;
              bdrenAGOivsup       = 0;
              bdacrededuirserago  = 0;

              bdirSETivsup        = 0;
              bdrenSETivsup       = 0;
              bdacrededuirserset  = 0;

              bdirOUTivsup        = 0;
              bdrenOUTivsup       = 0;
              bdacrededuirserout  = 0;

              bdirNOVivsup        = 0;
              bdrenNOVivsup       = 0;
              bdacrededuirsernov  = 0;

              bdirDEZivsup        = 0;
              bdrenDEZivsup       = 0;
              bdacrededuirserdez  = 0;

           END
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '01') THEN
             BEGIN
               bdirJANivsup       = wVLRIMPOSTO;
               bdrenJANivsup      = wvlrcontab;
               bdacrededuirserjan = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '02') THEN
             BEGIN
               bdirFEVivsup       = wVLRIMPOSTO;
               bdrenFEVivsup      = wvlrcontab;
               bdacrededuirserfev = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '03') THEN
             BEGIN
               bdirMARivsup       = wVLRIMPOSTO;
               bdrenMARivsup      = wvlrcontab;
               bdacrededuirsermar = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '04') THEN
             BEGIN
               bdirABRivsup       = wVLRIMPOSTO;
               bdrenABRivsup      = wvlrcontab;
               bdacrededuirserabr = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '05') THEN
             BEGIN
               bdirMAIivsup        = wVLRIMPOSTO;
               bdrenMAIivsup       = wvlrcontab;
               bdacrededuirsermaio = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '06') THEN
             BEGIN
               bdirJUNivsup       = wVLRIMPOSTO;
               bdrenJUNivsup      = wvlrcontab;
               bdacrededuirserjun = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '07') THEN
             BEGIN
               bdirJULivsup       = wVLRIMPOSTO;
               bdrenJULivsup      = wvlrcontab;
               bdacrededuirserjul = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '08') THEN
             BEGIN
               bdirAGOivsup       = wVLRIMPOSTO;
               bdrenAGOivsup      = wvlrcontab;
               bdacrededuirserago = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '09') THEN
             BEGIN
               bdirSETivsup       = wVLRIMPOSTO;
               bdrenSETivsup      = wvlrcontab;
               bdacrededuirserset = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '10') THEN
             BEGIN
               bdirOUTivsup       = wVLRIMPOSTO;
               bdrenOUTivsup      = wvlrcontab;
               bdacrededuirserout = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '11') THEN
             BEGIN
               bdirNOVivsup       = wVLRIMPOSTO;
               bdrenNOVivsup      = wvlrcontab;
               bdacrededuirsernov = wvlracrededuirser;
             END
           ELSE
           IF (SUBSTRING(wreflan FROM 5 FOR 2) = '12') THEN
             BEGIN
               bdirDEZivsup       = wVLRIMPOSTO;
               bdrenDEZivsup      = wvlrcontab;
               bdacrededuirserdez = wvlracrededuirser;
             END
           wultcodrec = wcodrec;
           wultcodemp = wcodemp;
           wultcodter = wcodter;
     END
   IF (:bdcodemp <> 0) THEN
      SUSPEND;
END
^

/* Restore proc. body: VEF_SP_DIRF_RTIRF */
ALTER PROCEDURE VEF_SP_DIRF_RTIRF (
    PREMPRESAS VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER,
    PRREFATUAL INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCODRECIVSUP INTEGER,
    BDCODTER INTEGER,
    BDCNPJIVSUP VARCHAR(18),
    BDNOMEEMPIVSUP VARCHAR(100),
    BDIRJANIVSUP NUMERIC(18,6),
    BDIRFEVIVSUP NUMERIC(18,6),
    BDIRMARIVSUP NUMERIC(18,6),
    BDIRABRIVSUP NUMERIC(18,6),
    BDIRMAIIVSUP NUMERIC(18,6),
    BDIRJUNIVSUP NUMERIC(18,6),
    BDIRJULIVSUP NUMERIC(18,6),
    BDIRAGOIVSUP NUMERIC(18,6),
    BDIRSETIVSUP NUMERIC(18,6),
    BDIROUTIVSUP NUMERIC(18,6),
    BDIRNOVIVSUP NUMERIC(18,6),
    BDIRDEZIVSUP NUMERIC(18,6),
    BDINDIMUNEISE INTEGER)
AS
DECLARE VARIABLE WSUBSELECTSER VARCHAR(5000);
DECLARE VARIABLE WSUBSELECTDEM VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(1000);
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WVLRIMPOSTO NUMERIC(18,6);
DECLARE VARIABLE WCNPJIVSUP VARCHAR(18);
DECLARE VARIABLE WNOMEEMPIVSUP VARCHAR(100);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODREC INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WINDIMUNEISE INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

  wsubselectSer = 'select bdcodemp, bdchave, bdreflan, bdcodter from vef_emp_tmovser where (bdcodsitnf not in (2,3,4,5)) and (bdtiplan = 1)';
  WSUBSELECTDem = 'select bdcodemp, bdchave, bdreflan, bdcodter from VEF_EMP_TMOVDEMAISDOC_F100 where (BDIND_OPER = 1) ';
  wWhere = '';
  IF ((:prempresas IS NOT NULL) AND (:prempresas <> '')) THEN
    wWhere = :wWhere || ' and (' || :prempresas || ')';

  IF ((:prrefini IS NOT NULL) AND (:prrefini > 0)) THEN
    wWhere = :wWhere || ' and (bdreflan >= ' || :prrefini || ')';

  IF ((:prreffin IS NOT NULL) AND (:prreffin > 0)) THEN
    wWhere = :wWhere || ' and (bdreflan <= ' || :prreffin || ')';

  wsubselectser = wsubselectser || wwhere;
  WSUBSELECTDem = WSUBSELECTDem || wwhere;


  wsql = '';
  wsql = wsql || ' select s.bdcodemp, s.bdcodrec, s.bdcodter, t.bdcgcter, t.bdnometer, t.bdindimuneise, s.bdreflan, sum(s.bdvlrimposto) bdvlrimposto ';
  wsql = wsql || ' from ';
  wsql = wsql || ' ( ';
                       /*PIS*/
  wsql = wsql || '     select mov.bdcodemp, ret.bdcodrecpis bdcodrec, mov.bdcodter, mov.bdreflan, ret.bdvlrpis bdvlrimposto ';
  wsql = wsql || '     from (' || wsubselectSer || ') mov ';
  wsql = wsql || '     inner join vef_emp_tmovserret ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodrecpis > 0) and (ret.bdvlrpis > 0) ';

  wsql = wsql || '     union all  ';
                       /*Cofins*/
  wsql = wsql || '     select mov.bdcodemp, ret.bdcodreccofins bdcodrec, mov.bdcodter, mov.bdreflan, ret.bdvlrcofins bdvlrimposto ';
  wsql = wsql || '     from (' || wsubselectSer || ') mov ';
  wsql = wsql || '     inner join vef_emp_tmovserret ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodreccofins > 0) and (ret.bdvlrcofins > 0) ';

  wsql = wsql || '     union all ';
                       /*Contribuição Social*/
  wsql = wsql || '     select mov.bdcodemp, ret.bdcodreccsocial bdcodrec, mov.bdcodter, mov.bdreflan, ret.bdvlrcsocial bdvlrimposto ';
  wsql = wsql || '     from (' || wsubselectSer || ') mov ';
  wsql = wsql || '     inner join vef_emp_tmovserret ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodreccsocial > 0) and (ret.bdvlrcsocial > 0) ';

  wsql = wsql || '     union all ';
                       /*IRRF*/
  wsql = wsql || '     select mov.bdcodemp, itens.bdcodrec, mov.bdcodter, mov.bdreflan, itens.bdvlrirser bdvlrimposto ';
  wsql = wsql || '     from (' || wsubselectSer || ') mov ';
  wsql = wsql || '     inner join vef_emp_tmovseritens itens on (itens.bdcodemp = mov.bdcodemp) and (itens.bdchave = mov.bdchave) and (itens.bdcodrec > 0) and (itens.bdvlrirser > 0) ';

--demais documentos
  wsql = wsql || '     union all ';
                       /*PIS*/
  wsql = wsql || '     select mov.bdcodemp, ret.bdcodrecpis bdcodrec, mov.bdcodter, mov.bdreflan, ret.bdvlrpis bdvlrimposto ';
  wsql = wsql || '     from (' || WSUBSELECTDem || ') mov ';
  wsql = wsql || '     inner join VEF_EMP_TMOVDEMRET ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodrecpis > 0) and (ret.bdvlrpis > 0) ';

  wsql = wsql || '     union all  ';
                       /*Cofins*/
  wsql = wsql || '     select mov.bdcodemp, ret.bdcodreccofins bdcodrec, mov.bdcodter, mov.bdreflan, ret.bdvlrcofins bdvlrimposto ';
  wsql = wsql || '     from (' || WSUBSELECTDem || ') mov ';
  wsql = wsql || '     inner join VEF_EMP_TMOVDEMRET ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodreccofins > 0) and (ret.bdvlrcofins > 0) ';

  wsql = wsql || '     union all ';
                       /*Contribuição Social*/
  wsql = wsql || '     select mov.bdcodemp, ret.bdcodreccsocial bdcodrec, mov.bdcodter, mov.bdreflan, ret.bdvlrcsocial bdvlrimposto ';
  wsql = wsql || '     from (' || WSUBSELECTDem || ') mov ';
  wsql = wsql || '     inner join VEF_EMP_TMOVDEMRET ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodreccsocial > 0) and (ret.bdvlrcsocial > 0) ';

  wsql = wsql || '     union all ';
                       /*IRRF*/
  wsql = wsql || '     select MOV.BDCODEMP, ret.BDCODRECIR bdcodrec, MOV.BDCODTER, MOV.BDREFLAN, RET.BDVLRIR BDVLRIMPOSTO ';
  wsql = wsql || '     from (' || WSUBSELECTDem || ') mov ';
  wsql = wsql || '     inner join VEF_EMP_TMOVDEMRET RET on (RET.BDCODEMP = MOV.BDCODEMP) and (RET.BDCHAVE = MOV.BDCHAVE) and (RET.BDCODRECIR > 0) and (RET.bdvlrir > 0) ';

  wsql = wsql || ' ) s ';
  wsql = wsql || ' inner join tcodrec r on (r.bdcodrec = s.bdcodrec) and (r.bdtipoimposto in (2, 11, 12)) ';
  wsql = wsql || ' left outer join vw_tterceiro t on t.bdcodter = s.bdcodter ';
  wsql = wsql || ' group by s.bdcodemp, s.bdcodrec, s.bdcodter, t.bdcgcter, t.bdnometer, s.bdreflan, t.bdindimuneise ';

  /*garantir que é nulo antes de entrar no for*/
  bdcodemp = NULL;
  bdcodrecivsup = NULL;
  bdcodter = NULL;
  FOR EXECUTE STATEMENT wsql 
      INTO :wcodemp,
           :wcodrec,
           :wcodter,
           :wcnpjivsup,
           :wnomeempivsup,
           :wINDIMUNEISE,
           :wmes,
           :wvlrimposto 
  DO
  BEGIN 
    /*
      se bdcodemp ou bdcodter for nulo, é o primeiro registro e deve inicializar os totais
    */
    IF (((:wcodemp <> :bdcodemp) OR (:wcodter <> :bdcodter) OR (:wcodrec <> :bdcodrecivsup)) OR ((:bdcodemp IS NULL) AND (:bdcodter IS NULL) AND (:bdcodrecivsup IS NULL))) THEN
      BEGIN
        /*só da suspend se os valores para o codigo da empresa e terceiro estiverem preenchidos*/
        IF ((:bdcodemp IS NOT NULL) AND (:bdcodter IS NOT NULL) AND (:bdcodrecivsup IS NOT NULL) AND ((bdcodemp > 0) AND (:bdcodter > 0) AND (:bdcodrecivsup > 0))) THEN
          SUSPEND;

        /*limpa os totais*/
        bdirjanivsup = 0;
        bdirfevivsup = 0;
        bdirmarivsup = 0;
        bdirabrivsup = 0;
        bdirmaiivsup = 0;
        bdirjunivsup = 0;
        bdirjulivsup = 0;
        bdiragoivsup = 0;
        bdirsetivsup = 0;
        bdiroutivsup = 0;
        bdirnovivsup = 0;
        bdirdezivsup = 0;
      END

    /*pega so o mes do reflan*/
    wmes = CAST(SUBSTRING(:wmes FROM 5 FOR 2) AS INTEGER);

    IF (:wmes = 1) THEN
      bdirjanivsup = :wvlrimposto;
    ELSE IF (:wmes = 2) THEN
      bdirfevivsup = :wvlrimposto;
    ELSE IF (:wmes = 3) THEN
      bdirmarivsup = :wvlrimposto;
    ELSE IF (:wmes = 4) THEN
      bdirabrivsup = :wvlrimposto;
    ELSE IF (:wmes = 5) THEN
      bdirmaiivsup = :wvlrimposto;
    ELSE IF (:wmes = 6) THEN
      bdirjunivsup = :wvlrimposto;
    ELSE IF (:wmes = 7) THEN
      bdirjulivsup = :wvlrimposto;
    ELSE IF (:wmes = 8) THEN
      bdiragoivsup = :wvlrimposto;
    ELSE IF (:wmes = 9) THEN
      bdirsetivsup = :wvlrimposto;
    ELSE IF (:wmes = 10) THEN
      bdiroutivsup = :wvlrimposto;
    ELSE IF (:wmes = 11) THEN
      bdirnovivsup = :wvlrimposto;
    ELSE IF (:wmes = 12) THEN
      bdirdezivsup = :wvlrimposto;
    
    bdcodemp = :wcodemp;
    bdcodrecivsup = :wcodrec;
    bdcodter = :wcodter;
    bdcnpjivsup = :wcnpjivsup;
    bdnomeempivsup = :wnomeempivsup;
    bdindimuneise = :windimuneise;
  END 
  /*suspend do ultimo registro*/
  IF ((:bdcodemp > 0) AND (:bdcodrecivsup > 0) AND (:bdcodter > 0)) THEN
    SUSPEND;
END
^

/* Restore proc. body: VEF_SP_DIRF_RTRT */
ALTER PROCEDURE VEF_SP_DIRF_RTRT(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER,
PREXPORTARNOTAS INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDRENJANIVSUP NUMERIC(18,6),
BDRENFEVIVSUP NUMERIC(18,6),
BDRENMARIVSUP NUMERIC(18,6),
BDRENABRIVSUP NUMERIC(18,6),
BDRENMAIIVSUP NUMERIC(18,6),
BDRENJUNIVSUP NUMERIC(18,6),
BDRENJULIVSUP NUMERIC(18,6),
BDRENAGOIVSUP NUMERIC(18,6),
BDRENSETIVSUP NUMERIC(18,6),
BDRENOUTIVSUP NUMERIC(18,6),
BDRENNOVIVSUP NUMERIC(18,6),
BDRENDEZIVSUP NUMERIC(18,6))
 AS
DECLARE VARIABLE WSUBSELECT VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WVLRCONTAB NUMERIC(18,6);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

  wsubselect = 'select bdcodemp, bdchave, bdreflan, bdcodter from vef_emp_tmovser where (bdcodsitnf not in (2,3,4,5)) and (bdtiplan = 1)';

  IF ((prempresas IS NOT NULL) AND (prempresas <> '')) THEN
    wsubselect = wsubselect || ' and (' || prempresas || ')';

  IF ((prrefini IS NOT NULL) AND (prrefini > 0)) THEN
    wsubselect = wsubselect || ' and (bdreflan >= ' || prrefini || ')';

  IF ((prreffin IS NOT NULL) AND (prreffin > 0)) THEN
    wsubselect = wsubselect || ' and (bdreflan <= ' || prreffin || ')';

  wsql = '';
  wsql = '          SELECT MOV.BDCODEMP, MOV.BDCODTER, MOV.BDREFLAN, SUM(COALESCE(MOV.BDVLRCONTAB, 0)) AS BDVLRCONTAB ';
  wsql = wsql || '  FROM ( ';
  wsql = wsql ||        ' select mov.bdcodemp, ';
  wsql = wsql ||        '        mov.bdcodter, ';
  wsql = wsql ||        '        mov.bdreflan, ';
  wsql = wsql ||        '        sum(itens.bdvlrcontab) bdvlrcontab  ';
  wsql = wsql ||        ' from (' || wsubselect || ') mov  ';
  wsql = wsql ||        ' inner join vef_emp_tmovseritens itens on (itens.bdcodemp = mov.bdcodemp) and (itens.bdchave = mov.bdchave)  ';
  wsql = wsql ||        ' where (exists(select * from vef_emp_tmovseritens i ';
  wsql = wsql ||        '               inner join tcodrec r on (r.bdcodrec = i.bdcodrec) and (r.bdtipoimposto in (2, 11, 12)) ';
  wsql = wsql ||        '               where (i.bdcodemp = mov.bdcodemp) and ';
  wsql = wsql ||        '                     (i.bdchave = mov.bdchave) and ';
  wsql = wsql ||        '                     (i.bdcodrec > 0)) or ';
  wsql = wsql ||        '        exists(select * from vef_emp_tmovserret r';
  wsql = wsql ||        '               inner join tcodrec c on (c.bdtipoimposto in (2, 11, 12)) and ((c.bdcodrec = r.bdcodrecpis) or (c.bdcodrec = r.bdcodreccofins) or (c.bdcodrec = r.bdcodreccsocial)) ';
  wsql = wsql ||        '               where (r.bdcodemp = mov.bdcodemp) and ';
  wsql = wsql ||        '                    (r.bdchave = mov.bdchave) and ';
  wsql = wsql ||        '                    ((r.bdcodrecpis > 0) or ';
  wsql = wsql ||        '                    (r.bdcodreccofins > 0) or ';
  wsql = wsql ||        '                    (r.bdcodreccsocial > 0)))) ';

  IF ((:prexportarnotas IS NOT NULL) AND (:prexportarnotas = 1)) THEN /*1 = todas as notas de participantes que tiveram retenção no periodo*/
    BEGIN
      wsql = wsql ||    '       or (mov.bdcodter in (select distinct bdcodter ';
      wsql = wsql ||    '                            from ';
      wsql = wsql ||    '                            ( ';
      wsql = wsql ||    '                                select s.bdcodter, s.bdcodrec ';
      wsql = wsql ||    '                                from ';
      wsql = wsql ||    '                                ( ';
      wsql = wsql ||    '                                 select mov.bdcodter, itens.bdcodrec from (' || wsubselect || ') mov ';
      wsql = wsql ||    '                                 inner join vef_emp_tmovseritens itens on itens.bdcodemp = mov.bdcodemp and itens.bdchave = mov.bdchave and itens.bdcodrec > 0  ';
                                                       
      wsql = wsql ||    '                                 union ';

      wsql = wsql ||    '                                 select mov.bdcodter, ret.bdcodrecpis bdcodrec from (' || wsubselect || ') mov ';
      wsql = wsql ||    '                                 inner join vef_emp_tmovserret ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodrecpis > 0) and (ret.bdvlrpis > 0) ';
      
      wsql = wsql ||    '                                 union ';

      wsql = wsql ||    '                                 select mov.bdcodter, ret.bdcodreccofins bdcodrec from (' || wsubselect || ') mov ';
      wsql = wsql ||    '                                 inner join vef_emp_tmovserret ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodreccofins > 0) and (ret.bdvlrcofins > 0) ';

      wsql = wsql ||    '                                 union ';
      
      wsql = wsql ||    '                                 select mov.bdcodter, ret.bdcodreccsocial bdcodrec from (' || wsubselect || ') mov ';
      wsql = wsql ||    '                                 inner join vef_emp_tmovserret ret on (ret.bdcodemp = mov.bdcodemp) and (ret.bdchave = mov.bdchave) and (ret.bdcodreccsocial > 0) and (ret.bdvlrcsocial > 0) ';
      wsql = wsql ||    '                                ) s ';
      wsql = wsql ||    '                                inner join tcodrec r on (r.bdcodrec = s.bdcodrec) and (r.bdtipoimposto in (2, 11, 12)) ';
      wsql = wsql ||    '                            ))) ';
    END
    
  wsql = wsql ||        ' group by mov.bdcodemp, mov.bdcodter, mov.bdreflan ';
  
  wsubselect = 'SELECT f100.bdcodemp, f100.bdchave, f100.bdreflan, f100.bdcodter, F100.bdvl_oper FROM VEF_EMP_TMOVDEMAISDOC_F100 f100 WHERE (f100.BDIND_OPER = 1) ';
  IF ((prempresas IS NOT NULL) AND (prempresas <> '')) THEN
    wsubselect = wsubselect || ' AND (' || prempresas || ')';
  IF ((prrefini IS NOT NULL) AND (prrefini > 0)) THEN
    wsubselect = wsubselect || ' AND (bdreflan >= ' || prrefini || ')';

  IF ((prreffin IS NOT NULL) AND (prreffin > 0)) THEN
    wsubselect = wsubselect || ' AND (bdreflan <= ' || prreffin || ')';

  wsql = wsql ||        'UNION ALL ';
  wsql = wsql ||        ' SELECT D.BDCODEMP, D.BDCODTER, D.BDREFLAN, SUM(D.bdvl_oper) BDVLRCONTAB ';
  wsql = wsql ||        ' FROM ('||wsubselect||') D ';
  wsql = wsql ||        ' WHERE (EXISTS(SELECT * FROM VEF_EMP_TMOVDEMRET R ';
  wsql = wsql ||        '               INNER JOIN TCODREC C ON (C.BDTIPOIMPOSTO IN (2, 11, 12)) AND ((C.BDCODREC = R.BDCODRECPIS) OR (C.BDCODREC = R.BDCODRECCOFINS) OR (C.BDCODREC = R.BDCODRECCSOCIAL) OR (C.BDCODREC = R.BDCODRECIR)) ';
  wsql = wsql ||        '               WHERE (R.BDCODEMP = D.BDCODEMP) ';
  wsql = wsql ||        '               AND (R.BDCHAVE = D.BDCHAVE) ';
  wsql = wsql ||        '               AND ((R.BDCODRECPIS > 0) OR (R.BDCODRECCOFINS > 0) OR (R.BDCODRECCSOCIAL > 0) OR (R.BDCODRECIR > 0))) ';
  wsql = wsql ||        '       ) ';

  IF ((:prexportarnotas IS NOT NULL) AND (:prexportarnotas = 1)) THEN /*1 = todas as notas de participantes que tiveram retenção no periodo*/
    BEGIN
      wsql = wsql ||    ' OR (D.bdcodter in ( ';
      wsql = wsql ||    '                    SELECT DISTINCT BDCODTER ';
      wsql = wsql ||    '                    FROM ( ';
      wsql = wsql ||    '                          SELECT F100.BDCODTER, F100.BDCODREC ';
      wsql = wsql ||    '                          FROM ( ';
      wsql = wsql ||    '                                SELECT MOV.BDCODTER, DEM.bdcodrecpis BDCODREC ';
      wsql = wsql ||    '                                FROM ('||wsubselect||') MOV ';
      wsql = wsql ||    '                                INNER JOIN VEF_EMP_TMOVDEMRET DEM ON (DEM.BDCODEMP = MOV.BDCODEMP) AND (DEM.BDCHAVE = MOV.BDCHAVE) AND (DEM.BDCODRECPIS > 0) AND (DEM.BDVLRPIS > 0) ';
      wsql = wsql ||    '                                UNION ';
      wsql = wsql ||    '                                SELECT MOV.BDCODTER, DEM.bdcodreccofins BDCODREC ';
      wsql = wsql ||    '                                FROM ('||wsubselect||') MOV ';
      wsql = wsql ||    '                                INNER JOIN VEF_EMP_TMOVDEMRET DEM ON (DEM.BDCODEMP = MOV.BDCODEMP) AND (DEM.BDCHAVE = MOV.BDCHAVE) AND (DEM.bdcodreccofins > 0) AND (DEM.bdvlrcofins > 0) ';
      wsql = wsql ||    '                                UNION ';
      wsql = wsql ||    '                                SELECT MOV.BDCODTER, DEM.bdcodreccsocial BDCODREC ';
      wsql = wsql ||    '                                FROM ('||wsubselect||') MOV ';
      wsql = wsql ||    '                                INNER JOIN VEF_EMP_TMOVDEMRET DEM ON (DEM.BDCODEMP = MOV.BDCODEMP) AND (DEM.BDCHAVE = MOV.BDCHAVE) AND (DEM.bdcodreccsocial > 0) AND (DEM.bdvlrcsocial > 0) ';
      wsql = wsql ||    '                                UNION ';
      wsql = wsql ||    '                                SELECT MOV.BDCODTER, DEM.bdcodrecir BDCODREC ';
      wsql = wsql ||    '                                FROM ('||wsubselect||') MOV ';
      wsql = wsql ||    '                                INNER JOIN VEF_EMP_TMOVDEMRET DEM ON (DEM.BDCODEMP = MOV.BDCODEMP) AND (DEM.BDCHAVE = MOV.BDCHAVE) AND (DEM.bdcodrecir > 0) AND (DEM.bdvlrir > 0) ';
      wsql = wsql ||    '                               ) F100 ';
      wsql = wsql ||    '                         ) ';
      wsql = wsql ||    '                   ) ';
      wsql = wsql ||    '    ) ';
    END

  wsql = wsql ||        ' GROUP BY D.BDCODEMP, D.BDCODTER, D.BDREFLAN ';

  wsql = wsql ||       ' ) MOV ';
  wsql = wsql || ' GROUP BY mov.bdcodemp, mov.bdcodter, mov.bdreflan ';
  wsql = wsql || ' ORDER BY mov.bdcodemp, mov.bdcodter, mov.bdreflan ';

  bdcodemp = NULL;
  bdcodter = NULL;
  FOR EXECUTE STATEMENT wsql
      INTO :wcodemp,
           :wcodter,
           :wmes,
           :wvlrcontab
  DO
  BEGIN
    /*
      se bdcodemp ou bdcodter for nulo, é o primeiro registro e deve inicializar os totais
    */
    IF (((:wcodemp <> :bdcodemp) OR (:wcodter <> :bdcodter)) OR ((:bdcodemp IS NULL) AND (:bdcodter IS NULL))) THEN
      BEGIN
        /*só da suspend se os valores para o codigo da empresa e terceiro estiverem preenchidos*/
        IF ((:bdcodemp IS NOT NULL) AND (:bdcodter IS NOT NULL) AND (:bdcodemp > 0) AND (:bdcodter > 0)) THEN
          SUSPEND;

        /*limpa os totais*/
        bdrenjanivsup = 0;
        bdrenfevivsup = 0;
        bdrenmarivsup = 0;
        bdrenabrivsup = 0;
        bdrenmaiivsup = 0;
        bdrenjunivsup = 0;
        bdrenjulivsup = 0;
        bdrenagoivsup = 0;
        bdrensetivsup = 0;
        bdrenoutivsup = 0;
        bdrennovivsup = 0;
        bdrendezivsup = 0;
      END
  
    wmes = CAST(SUBSTRING(:wmes FROM 5 FOR 2) AS INTEGER);
    
    IF (:wmes = 1) THEN
      bdrenjanivsup = :wvlrcontab;
    ELSE IF (:wmes = 2) THEN
      bdrenfevivsup = :wvlrcontab;
    ELSE IF (:wmes = 3) THEN
      bdrenmarivsup = :wvlrcontab;
    ELSE IF (:wmes = 4) THEN
      bdrenabrivsup = :wvlrcontab;
    ELSE IF (:wmes = 5) THEN
      bdrenmaiivsup = :wvlrcontab;
    ELSE IF (:wmes = 6) THEN
      bdrenjunivsup = :wvlrcontab;
    ELSE IF (:wmes = 7) THEN
      bdrenjulivsup = :wvlrcontab;
    ELSE IF (:wmes = 8) THEN
      bdrenagoivsup = :wvlrcontab;
    ELSE IF (:wmes = 9) THEN
      bdrensetivsup = :wvlrcontab;
    ELSE IF (:wmes = 10) THEN
      bdrenoutivsup = :wvlrcontab;
    ELSE IF (:wmes = 11) THEN
      bdrennovivsup = :wvlrcontab;
    ELSE IF (:wmes = 12) THEN
      bdrendezivsup = :wvlrcontab;
      
    bdcodemp = :wcodemp;
    bdcodter = :wcodter;
  END
  /*suspend do último registro*/
  IF ((:bdcodemp > 0) AND (:bdcodter > 0)) THEN
    SUSPEND;
END
^

/* Restore proc. body: VEF_SP_EXCLUI_REDZVARCFOP_PLANO */
ALTER PROCEDURE VEF_SP_EXCLUI_REDZVARCFOP_PLANO (
PRSQL   VARCHAR(4000),
PREMP   INTEGER,
PRCHAVE INTEGER) 
 AS
DECLARE VARIABLE WSQL VARCHAR(6000);
DECLARE VARIABLE WQTDEVAR INTEGER;
DECLARE VARIABLE WQTDE INTEGER;
DECLARE VARIABLE WORDEMVARCFOP INTEGER;
DECLARE VARIABLE WFIRST INTEGER;
DECLARE VARIABLE WSKIP INTEGER;
BEGIN
  /*
   Alt.: 11421 - Procedure para ser utilizada nos Plano de trocas.
   Verifica diferença de quantos registros foram inseridos no 490/470(dependendo do perfil) e registros existentes nas várias CFOPs, excluindo essa diferença.
   Pode sempre excluir sem verificar a CFOPs das várias CFOPs, pois executa um Insert/Select antes nas acões dos plano de trocas.
   */
  EXECUTE STATEMENT 'select count(*) from ( '||prSQL||') ' INTO :wQtde;

  EXECUTE STATEMENT 'select count(*) from VEF_EMP_TREDZVARCFOP '||
                    'where BDCODEMP = '||prEMP||
                    '  and BDCHAVE  = '||prCHAVE||
                    '  and BDCODNAT in ( select BDCODNAT from ( '||prSQL||') ) ' INTO :wQtdeVar;

  IF ((wQtdeVar - wQtde) > 0) THEN
    BEGIN
      wSQL = 'Delete from VEF_EMP_TREDZVARCFOP '||
             'Where BDCODEMP = '||prEMP||
             '  and BDCHAVE  = '||prCHAVE||
             ' and BDORDEMVARCFOP in ( Select first '||(wQtdeVar - wQtde)||' skip '||(wQtde)||' BDORDEMVARCFOP from VEF_EMP_TREDZVARCFOP '||
             '                         Where bdcodemp = '||prEMP||
             '                           and bdchave  = '||prCHAVE||
             '                           and BDCODNAT in ( select BDCODNAT from ( '||prSQL||') ) '||
             '                         Order by BDORDEMVARCFOP desc )';
      EXECUTE STATEMENT wSQL;
    END
END^

/* Restore proc. body: VEF_SP_EXP_DIME */
CREATE OR ALTER PROCEDURE VEF_SP_EXP_DIME (
    PRCODEMP VARCHAR(10000),
    PRREFERENCIAINICIAL INTEGER,
    PRREFERENCIAFINAL INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDREFERENCIA INTEGER,
    BDNUMCAMPO INTEGER,
    BDCLASSIFICACAO VARCHAR(5),
    BDDESCCAMPO VARCHAR(150),
    BDVALOR NUMERIC(15,6),
    BDCODCID INTEGER,
    BDCODCIDTOT INTEGER,
    BDCODNAT INTEGER,
    BDDATAREC DATE,
    BDCLAVENDIMEGERQ12 INTEGER,
    BDCODRECDIMEGERQ12 INTEGER,
    BDORIGEMDIMEGERQ46 INTEGER,
    BDIDENTIFICACAOREGESP VARCHAR(15),
    BDSIGLAUF VARCHAR(2),
    BDVLRCONT NUMERIC(15,6),
    BDVLRBC NUMERIC(15,6),
    BDVLRIMPOSTO NUMERIC(15,6),
    BDVLRISENTRIB NUMERIC(15,6),
    BDVLROUTRAS NUMERIC(15,6),
    BDVLRICMSSTPE NUMERIC(15,6),
    BDVLRICMSSTOP NUMERIC(15,6),
    BDVLRCONTCONT NUMERIC(15,6),
    BDVLRBCCONT NUMERIC(15,6),
    BDVLRICMSST NUMERIC(15,6),
    BDNUMITEM INTEGER,
    BDCODTIPO INTEGER,
    BDBASEST NUMERIC(15,6),
    BDICMSRETST NUMERIC(15,6),
    BDDIFALIQENT NUMERIC(15,6),
    BDALIMPREP VARCHAR(5),
    BDCODEXP48 VARCHAR(3),
    BDNUMACORDOQ12 varchar(15),
    BDCODBENEFTTD integer,
    BDNUMCONCTTD varchar(20),
    BDCODTIPCRED integer,
    BDVLRBCICMS numeric(15,2),
    BDVLRICMSEXON numeric(15,2),
    BDORDEMFUMDES integer,
    BDVLRFUMDES numeric(15,2),
    BDORDEMFUNSOC integer,
    BDVLRFUNSOC numeric(15,2),
    BDVLRBCICMSDEV numeric(15,2),
    BDVLRICMSEXONDEV numeric(15,2),
    BDVLRFUMDESDEV numeric(15,2),
    BDVLRFUNSOCDEV numeric(15,2),
    BDEXPQUAD16 integer)
AS
DECLARE VARIABLE WSQL VARCHAR(32765);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WNAT INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WNUMCAMPO INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(5);
DECLARE VARIABLE WDESCCAMPO VARCHAR(150);
DECLARE VARIABLE WVALOR NUMERIC(15,6);
DECLARE VARIABLE WCODCID INTEGER;
DECLARE VARIABLE WCODCIDTOT INTEGER;
DECLARE VARIABLE WCODNAT INTEGER;
DECLARE VARIABLE WDATAREC DATE;
DECLARE VARIABLE WCLAVENDIMEGERQ12 INTEGER;
DECLARE VARIABLE WCODRECDIMEGERQ12 INTEGER;
DECLARE VARIABLE WORIGEMDIMEGERQ46 INTEGER;
DECLARE VARIABLE WIDENTIFICACAOREGESP VARCHAR(15);
DECLARE VARIABLE WSIGLAUF VARCHAR(2);
DECLARE VARIABLE WVLRCONT NUMERIC(15,6);
DECLARE VARIABLE WVLRBC NUMERIC(15,6);
DECLARE VARIABLE WVLRIMPOSTO NUMERIC(15,6);
DECLARE VARIABLE WVLRISENTRIB NUMERIC(15,6);
DECLARE VARIABLE WVLROUTRAS NUMERIC(15,6);
DECLARE VARIABLE WVLRICMSSTPE NUMERIC(15,6);
DECLARE VARIABLE WVLRICMSSTOP NUMERIC(15,6);
DECLARE VARIABLE WCODUF INTEGER;
DECLARE VARIABLE WUF INTEGER;
DECLARE VARIABLE WVLRCONTCONT NUMERIC(15,6);
DECLARE VARIABLE WVLRBCCONT NUMERIC(15,6);
DECLARE VARIABLE WVLRICMSST NUMERIC(15,6);
DECLARE VARIABLE WNUMITEMAUX INTEGER;
DECLARE VARIABLE WVLRCONTAUX NUMERIC(15,6);
DECLARE VARIABLE WVLRBCAUX NUMERIC(15,6);
DECLARE VARIABLE WVLRIMPOSTOAUX NUMERIC(15,6);
DECLARE VARIABLE WVLRISENTRIBAUX NUMERIC(15,6);
DECLARE VARIABLE WVLROUTRASAUX NUMERIC(15,6);
DECLARE VARIABLE WVLRICMSSTPEAUX NUMERIC(15,6);
DECLARE VARIABLE WVLRICMSSTOPAUX NUMERIC(15,6);
DECLARE VARIABLE WVLRCONTCONTAUX NUMERIC(15,6);
DECLARE VARIABLE WVLRBCCONTAUX NUMERIC(15,6);
DECLARE VARIABLE WVLRICMSSTAUX NUMERIC(15,6);
DECLARE VARIABLE WNUMITEM46 INTEGER;
DECLARE VARIABLE WCODTIPO INTEGER;
DECLARE VARIABLE WCODREGAPU INTEGER;
DECLARE VARIABLE WBASEST NUMERIC(15,6);
DECLARE VARIABLE WICMSRETST NUMERIC(15,6);
DECLARE VARIABLE WDIFALIQENT NUMERIC(15,6);
DECLARE VARIABLE wTodasAsEmpresa dm_boolean;
BEGIN
  DELETE FROM TMP_EMPRESAS_SELECT;

  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIAFINAL, NULL, NULL);
  wTodasAsEmpresa = 'FALSE';
  IF ((prcodemp IS NULL) OR (prcodemp = '') OR (prcodemp = '''''')) THEN
    wTodasAsEmpresa = 'TRUE';
  ELSE
    BEGIN -- Alt.: #215698
      wsql =       'INSERT INTO TMP_EMPRESAS_SELECT (bdCODEMP)';
      wsql = wsql||'SELECT bdCODEMP FROM TEMPRESAS dime WHERE '||:prCODEMP;
      EXECUTE STATEMENT wsql;
    END

  wsql = 'select DIME.BDCODEMP,';
  wsql = wsql||'DIME.BDREFERENCIA,';
  wsql = wsql||'DIME.BDNUMCAMPO,';
  wsql = wsql||'TCONF.bdclassificacao,';
  wsql = wsql||'TCONFDIMEFORMQ46.bddescformDIMEq46 BDDESCCAMPO,';
  wsql = wsql||'DIME.BDVALOR BDVALOR,';
  wsql = wsql||'TCID.BDCODEST bdcodcid,';
  wsql = wsql||'DIME.bdcodcidtot,';
  wsql = wsql||'DIME.BDCODNAT,';
  wsql = wsql||'DIME.BDDATAREC,';
  wsql = wsql||'DIME.BDCLAVENDIMEGERQ12,';
  wsql = wsql||'DIME.BDCODRECDIMEGERQ12,';
  wsql = wsql||'DIME.BDORIGEMDIMEGERQ46,';
  wsql = wsql||'DIME.BDIDENTIFICACAOREGESP, ';
  wsql = wsql||'UF.BDSIGLAUF,';
  wsql = wsql||' 0 BDVLRCONT,';
  wsql = wsql||' 0 BDVLRBC,';
  wsql = wsql||' 0 BDVLRIMPOSTO,';
  wsql = wsql||' 0 BDVLRISENTRIB,';
  wsql = wsql||' 0 BDVLROUTRAS,';
  wsql = wsql||' TCONFDIMEFORM.bdnumitem,';
  wsql = wsql||' 0 BDVLRICMSSTPE,';
  wsql = wsql||' 0 BDVLRICMSSTOP,';
  wsql = wsql||' TCONFDIMEFORMQ46.BDNUMITEM BDNUMITEM46,';
  wsql = wsql||'TCONF.bdCODTIPO, ';
  wsql = wsql||'TCONFDIME.BDCODREGAPU, ';
  wsql = wsql||'DIME.BDALIMPREP, ';
  wsql = wsql||'CASE WHEN ((DIME.BDALIMPREP = ''TRUE'') and (Coalesce(DIME.bdcodcidtot,0) <> 99999)) THEN ''008'' ELSE DIME.BDCODEXP48 END BDCODEXP48, ';
  wsql = wsql||' dime.bdNUMACORDOQ12, ';
  WSQL = WSQL||' DIME.BDCODBENEFTTD, '; /*Q15*/
  WSQL = WSQL||' DIME.BDNUMCONCTTD, ';
  WSQL = WSQL||' DIME.BDCODTIPCRED, ';
  WSQL = WSQL||' DIME.BDVLRBCICMS, ';
  WSQL = WSQL||' DIME.BDVLRICMSEXON, ';
  WSQL = WSQL||' DIME.BDORDEMFUMDES, ';
  WSQL = WSQL||' DIME.BDVLRFUMDES, ';
  WSQL = WSQL||' DIME.BDORDEMFUNSOC, ';
  WSQL = WSQL||' DIME.BDVLRFUNSOC, ';
  WSQL = WSQL||' DIME.BDVLRBCICMSDEV, ';
  WSQL = WSQL||' DIME.BDVLRICMSEXONDEV, ';
  WSQL = WSQL||' DIME.BDVLRFUMDESDEV, ';
  WSQL = WSQL||' DIME.BDVLRFUNSOCDEV, ';
  WSQL = WSQL||' DIME.BDEXPQUAD16 ';
  wsql = wsql||' from ( ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               BDPREFIXONAT as BDCODNAT, ';
  wsql = wsql||'               SUM(COALESCE(BDVALOR,0)) as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, /* Q 47, Q48 BDCODCID */ ';
  wsql = wsql||'               NULL as BDCODCIDTOT, /* Q 47, Q48 BDCODCIDTOT */ ';
  wsql = wsql||'               NULL as BDCODUF, /* Q 49 BDCODUF */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'NULL as BDCODBENEFTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDNUMCONCTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDCODTIPCRED, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMS, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXON, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMSDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXONDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDESDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOCDEV /* Q15 */, NULL AS BDEXPQUAD16  ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERNAT dime ';
  IF (wTodasAsEmpresa = 'FALSE') THEN
    wsql = wsql||'        WHERE dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF ((wTodasAsEmpresa = 'FALSE')) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR
           (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  IF (((wTodasAsEmpresa = 'FALSE')) OR
      (:PRREFERENCIAINICIAL IS NOT NULL) OR
      (:PRREFERENCIAFINAL IS NOT NULL)) THEN
     wsql = wsql||' and bdvalor > 0 ';
  ELSE
     wsql = wsql||' where bdvalor > 0 ';

  wsql = wsql||' AND DIME.BDCODPERIODO = 7 ';
  wsql = wsql||'        GROUP BY BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQDIME, BDNUMCAMPO, BDPREFIXONAT ';
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               BDCODCID as BDCODCID, ';
  wsql = wsql||'               BDCODCIDTOT as BDCODCIDTOT, ';
  wsql = wsql||'               NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'NULL as BDCODBENEFTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDNUMCONCTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDCODTIPCRED, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMS, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXON, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMSDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXONDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDESDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOCDEV /* Q15 */, NULL AS BDEXPQUAD16  ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ47 dime ';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wsql = wsql||'        WHERE dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF ((wTodasAsEmpresa = 'FALSE')) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR
           (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  wsql = wsql||' AND DIME.BDCODPERIODO = 7 ';
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               dime.BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL  as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               BDCODCID as BDCODCID, ';
  wsql = wsql||'               BDCODCIDTOT as BDCODCIDTOT, ';
  wsql = wsql||'               NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               CASE WHEN bdcodcidtot = 99999 THEN 999 /* Q48 */ ';
  wsql = wsql||'                    WHEN BDTROCAEXP = ''TRUE'' then (select BDCODEXPEXT from VEF_BASE_TTABATIVQ48 where BDCODATIVQ48 = DIME.BDCODATIVQ48) ELSE BDCODEXP END as BDCODEXP48,  /* Q48 */ ';
  wsql = wsql||'               ALIM.BDALIMPREP as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'NULL as BDCODBENEFTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDNUMCONCTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDCODTIPCRED, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMS, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXON, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMSDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXONDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDESDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOCDEV /* Q15 */, NULL AS BDEXPQUAD16  ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ48 dime ';
  wsql = wsql||'        JOIN  VW_VEF_BASE_TEMPPARESTSC Alim ON (alim.bdcodemp = dime.bdcodemp) ';
  wsql = wsql||'        LEFT OUTER JOIN VEF_BASE_TTABATIVQ48 exp48 ON (dime.bdcodativq48 = exp48.bdcodativq48) ';
  wsql = wsql||'        WHERE (dime.bdcodativq48 IS NOT NULL OR alim.bdALIMPREP = ''TRUE'' OR BDCODCIDTOT = 99999) '; -- Alt.: #120134 - Quando a estiver marcada com "Fornecedor de alimentos preparados" deve levar no quadro 48
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wsql = wsql||'        AND dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    wsql = wsql||'        AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
  wsql = wsql||' AND DIME.BDCODPERIODO = 7 ';
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, ';
  wsql = wsql||'               NULL as BDCODCIDTOT, ';
  wsql = wsql||'               bdcoduf as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46,  /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'NULL as BDCODBENEFTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDNUMCONCTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDCODTIPCRED, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMS, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXON, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMSDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXONDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDESDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOCDEV /* Q15 */, NULL AS BDEXPQUAD16  ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ49 dime ';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wsql = wsql||'        WHERE dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF ((wTodasAsEmpresa = 'FALSE')) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR
           (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  wsql = wsql||' AND DIME.BDCODPERIODO = 7 ';
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               SUM(COALESCE(BDVALOR,0)) as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, ';
  wsql = wsql||'               NULL as BDCODCIDTOT, ';
  wsql = wsql||'               bdcoduf as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'NULL as BDCODBENEFTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDNUMCONCTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDCODTIPCRED, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMS, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXON, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMSDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXONDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDESDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOCDEV /* Q15 */, NULL AS BDEXPQUAD16  ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ50 dime ';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wsql = wsql||'        WHERE dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF ((wTodasAsEmpresa = 'FALSE')) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR
           (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  wsql = wsql||' AND DIME.BDCODPERIODO = 7 ';
  wsql = wsql||'        GROUP BY BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQDIME, BDNUMCAMPO, BDCODNAT, BDCODCID, BDCODCIDTOT,bdcoduf, BDDATAREC, BDCLAVENDIMEGERQ12, BDCODRECDIMEGERQ12, BDORIGEMDIMEGERQ46,BDQ12, BDQ46 ';
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               NULL as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               NULL as BDCODCID, ';
  wsql = wsql||'               NULL as BDCODCIDTOT, ';
  wsql = wsql||'               NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               NULL as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               NULL as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'NULL as BDCODBENEFTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDNUMCONCTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDCODTIPCRED, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMS, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXON, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMSDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXONDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDESDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOCDEV /* Q15 */ , ';

  wsql = wsql||'IIF(BDCODQDIME IN (123, 124),(SELECT IIF(SUM(DIME.BDVALOR) > 0, 1, 0) BDEXPQUAD16 ';
  wsql = wsql||'        FROM VEF_EMP_TDIMESCGERREG dime ';
  wsql = wsql||'        WHERE (((bdCODQDIME <> 104) OR (bdCODQDIME = 104 AND bdNUMCAMPO NOT IN (19, 20))) OR '; -- 104 = Demonstração do Resultado
  wsql = wsql||'               ((bdCODQDIME = 104 AND bdNUMCAMPO = 19 AND (bdVALOR IS NOT NULL AND bdVALOR <> 0)) OR '; -- (=) Prejuízo do exercício
  wsql = wsql||'                (bdCODQDIME = 104 AND bdNUMCAMPO = 20 AND (bdVALOR IS NOT NULL /*AND bdVALOR <> 0*/)))) ';   -- (=) Lucro do exercício
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wsql = wsql||'AND dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
     wsql = wsql||'AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
     wsql = wsql||'AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  wsql = wsql||' AND DIME.BDCODPERIODO = 7 AND ';
  wsql = wsql||'BDCODQDIME IN (123, 124)),NULL) AS BDEXPQUAD16 ';

  wsql = wsql||'FROM VEF_EMP_TDIMESCGERREG dime ';
  wsql = wsql||'WHERE (((bdCODQDIME <> 104) OR (bdCODQDIME = 104 AND bdNUMCAMPO NOT IN (19, 20))) OR '; -- 104 = Demonstração do Resultado
  wsql = wsql||'((bdCODQDIME = 104 AND bdNUMCAMPO = 19 AND (bdVALOR IS NOT NULL AND bdVALOR <> 0)) OR '; -- (=) Prejuízo do exercício
  wsql = wsql||' (bdCODQDIME = 104 AND bdNUMCAMPO = 20 AND (bdVALOR IS NOT NULL /*AND bdVALOR <> 0*/)))) ';   -- (=) Lucro do exercício
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wsql = wsql||'        AND dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      wsql = wsql||'        AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      wsql = wsql||'        AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  wsql = wsql||' AND DIME.BDCODPERIODO = 7 ';
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT dime.bdCODPERIODO, ';
  wsql = wsql||'               dime.bdCODEMP, ';
  wsql = wsql||'               dime.bdREFERENCIA, ';
  wsql = wsql||'               dime.bdCODQDIME, ';
  wsql = wsql||'               dime.bdNUMCAMPO, ';
  wsql = wsql||'               null as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               null as BDCODCID, ';
  wsql = wsql||'               null as BDCODCIDTOT, ';
  wsql = wsql||'               null as BDCODUF, /* Q49 */ ';
  wsql = wsql||'               BDDATAREC as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               dime.bdCLAVENDIMEGERQ12 as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||' r.BDCODRECOF as BDCODRECDIMEGERQ12, /* Q12 */ '; --#167218 - Matheus Fritzen - 26/10/2022
  wsql = wsql||'                NULL AS BDORIGEMDIMEGERQ46, /* Q46 */ ';    
  wsql = wsql||'               NULL AS bdIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               ''TRUE'' AS bdQ12, /* Q12 */ ';
  wsql = wsql||'               ''FALSE'' AS bdQ46, /* Q46 */ ';
  wsql = wsql||'               '''' AS bdCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' AS BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'COALESCE(dime.bdNUMACORDO, fq12.bdNUMACORDODIMEQ12) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'NULL as BDCODBENEFTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDNUMCONCTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDCODTIPCRED, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMS, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXON, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMSDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXONDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDESDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOCDEV /* Q15 */, NULL AS BDEXPQUAD16  ';
  wsql = wsql||'        FROM VEF_EMP_TDIMEGERQ12 dime ';
  wsql = wsql||'left outer join TCODREC r on (r.BDCODREC = dime.BDCODRECDIMEGERQ12) '; --#167218
  wsql = wsql||'        LEFT OUTER JOIN ( ';
  wsql = wsql||'                         SELECT FIRST 1 dime.* ';
  wsql = wsql||'                         FROM VEF_BASE_TEMPPARESTSC dime ';
  IF (wTodasAsEmpresa = 'FALSE') THEN
    wsql = wsql||'                       WHERE dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF (wTodasAsEmpresa = 'FALSE') THEN
        wsql = wsql||'                     AND dime.bdREFEMP >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'                   WHERE dime.bdREFEMP >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'                     AND dime.bdREFEMP <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'                   WHERE dime.bdREFEMP <= '||:PRREFERENCIAFINAL;
    END
  wsql = wsql||'ORDER BY dime.bdREFEMP DESC) ';
  wsql = wsql||'emp ON (emp.bdCODEMP = dime.bdCODEMP) ';
  wsql = wsql||'        LEFT OUTER JOIN VEF_ESTADOS_TCONFDIMEFQ12 fq12 ON (fq12.bdCODQDIME = 48 AND fq12.bdCODCONFDIMESC = emp.bdCODCONFDIMESC AND fq12.bdNUMCAMPODIMEQ12 = dime.bdNUMCAMPO) ';
  IF (wTodasAsEmpresa = 'FALSE') THEN
    wsql = wsql||'        WHERE dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF (wTodasAsEmpresa = 'FALSE') THEN
        wsql = wsql||'        AND dime.bdREFERENCIA >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'        WHERE dime.bdREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR
           (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND dime.bdREFERENCIA <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'        WHERE dime.bdREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  wsql = wsql||' AND DIME.BDCODPERIODO = 7 ';
  wsql = wsql||'      UNION ';
  wsql = wsql||'SELECT 7 BDCODPERIODO, ';
  wsql = wsql||'                 DIME.BDCODEMP AS BDCODEMP, ';
  wsql = wsql||'                 DIME.BDREFERENCIA AS BDREFERENCIA, ';
  wsql = wsql||'120 BDCODQDIME, ';
  wsql = wsql||'AP.BDNUMCAMPO AS BDNUMCAMPO, ';
  wsql = wsql||'NULL as BDCODNAT, ';
  wsql = wsql||'NULL as BDVALOR, ';
  wsql = wsql||'NULL as BDCODCID, ';
  wsql = wsql||'NULL as BDCODCIDTOT, ';
  wsql = wsql||'NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'null as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'null as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||''''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||''''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'dime.BDCODBENEFTTD, /* Q15 */ ';
  wsql = wsql||'dime.BDNUMCONCTTD, /* Q15 */ ';
  wsql = wsql||'dime.BDCODTIPCRED, /* Q15 */ ';
  wsql = wsql||'dime.BDVLRBCICMS, /* Q15 */ ';
  wsql = wsql||'dime.BDVLRICMSEXON, /* Q15 */ ';
  wsql = wsql||'FDS.BDCODFUMDES AS BDORDEMFUMDES, /* Q15 */ ';
  wsql = wsql||'dime.BDVLRFUMDES, /* Q15 */ ';
  wsql = wsql||'FSC.BDCODFUNSOC AS BDORDEMFUNSOC, /* Q15 */ ';
  wsql = wsql||'dime.BDVLRFUNSOC, /* Q15 */ ';
  wsql = wsql||'dime.BDVLRBCICMSDEV, /* Q15 */ ';
  wsql = wsql||'dime.BDVLRICMSEXONDEV, /* Q15 */ ';
  wsql = wsql||'dime.BDVLRFUMDESDEV, /* Q15 */ ';
  wsql = wsql||'dime.BDVLRFUNSOCDEV /* Q15 */, NULL AS BDEXPQUAD16  ';
  wsql = wsql||'from VEF_EMP_TDIMEGERQ15 dime ';
  wsql = wsql||'LEFT OUTER JOIN VEF_EMP_TDIMEGERVLRQ15 AP ON (AP.BDORDEMLANQ15 = dime.BDORDEM) AND (AP.BDCODEMP = DIME.BDCODEMP) ';
  wsql = wsql||'LEFT OUTER JOIN VEF_BASE_TTABFUMDES FDS ON (FDS.BDORDEMFUMDES = dime.BDORDEMFUMDES) ';
  wsql = wsql||'LEFT OUTER JOIN VEF_BASE_TTABFUNDOSOCIAL FSC ON (FSC.BDORDEMFUNSOC = dime.BDORDEMFUNSOC) ';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wsql = wsql||'        WHERE dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF ((wTodasAsEmpresa = 'FALSE')) THEN
        wsql = wsql||'AND DIME.BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'WHERE DIME.BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR
           (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'AND DIME.BDREFERENCIA <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'WHERE DIME.BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  wsql = wsql||' AND AP.BDCODPERIODO = 7 ';
  wsql = wsql||'UNION ';
  wsql = wsql||'SELECT 7 BDCODPERIODO, ';
  wsql = wsql||'                 DIME.BDCODEMP AS BDCODEMP, ';
  wsql = wsql||'                 DIME.BDREFERENCIA AS BDREFERENCIA, ';
  wsql = wsql||'120 BDCODQDIME, ';
  wsql = wsql||'999 as BDNUMCAMPO, ';
  wsql = wsql||'NULL as BDCODNAT, ';
  wsql = wsql||'NULL as BDVALOR, ';
  wsql = wsql||'NULL as BDCODCID, ';
  wsql = wsql||'NULL as BDCODCIDTOT, ';
  wsql = wsql||'NULL as BDCODUF, /* Q49 */ ';
  wsql = wsql||'NULL as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'NULL as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'NULL as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'null as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'null as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'''FALSE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||''''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||''''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'9999 BDCODBENEFTTD, /* Q15 */ ';
  wsql = wsql||'999999999999999 BDNUMCONCTTD, /* Q15 */ ';
  wsql = wsql||'9999 BDCODTIPCRED, /* Q15 */ ';
  wsql = wsql||'sum(DIME.BDVLRBCICMS) BDVLRBCICMS, /* Q15 */ ';
  wsql = wsql||'SUM(DIME.BDVLRICMSEXON) BDVLRICMSEXON, /* Q15 */ ';
  wsql = wsql||'9 BDORDEMFUMDES, /* Q15 */ ';
  wsql = wsql||'SUM(DIME.BDVLRFUMDES) BDVLRFUMDES, /* Q15 */ ';
  wsql = wsql||'9 BDORDEMFUNSOC, /* Q15 */ ';
  wsql = wsql||'SUM(DIME.BDVLRFUNSOC) BDVLRFUNSOC, /* Q15 */ ';
  wsql = wsql||'SUM(DIME.BDVLRBCICMSDEV) BDVLRBCICMSDEV, /* Q15 */ ';
  wsql = wsql||'SUM(DIME.BDVLRICMSEXONDEV) BDVLRICMSEXONDEV, /* Q15 */ ';
  wsql = wsql||'SUM(DIME.BDVLRFUMDESDEV) BDVLRFUMDESDEV, /* Q15 */ ';
  wsql = wsql||'SUM(DIME.BDVLRFUNSOCDEV) BDVLRFUNSOCDEV /* Q15 */, NULL AS BDEXPQUAD16  ';
  wsql = wsql||'from VEF_EMP_TDIMEGERQ15 dime ';
  wsql = wsql||'LEFT OUTER JOIN VEF_BASE_TTABFUMDES FDS ON (FDS.BDORDEMFUMDES = dime.BDORDEMFUMDES) ';
  wsql = wsql||'LEFT OUTER JOIN VEF_BASE_TTABFUNDOSOCIAL FSC ON (FSC.BDORDEMFUNSOC = dime.BDORDEMFUNSOC) ';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wsql = wsql||'        WHERE dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF ((wTodasAsEmpresa = 'FALSE')) THEN
        wsql = wsql||'AND DIME.BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'WHERE DIME.BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR
           (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'AND DIME.BDREFERENCIA <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'WHERE DIME.BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  wsql = wsql||'GROUP BY BDCODPERIODO, BDCODEMP, BDREFERENCIA, BDCODQDIME ';
  wsql = wsql||'UNION ';
  wsql = wsql||'      select /*null*/7 BDCODPERIODO, ';
  wsql = wsql||'             BDCODEMP, ';
  wsql = wsql||'             BDREFERENCIA, ';
  wsql = wsql||'             /*39*/48 BDCODQDIME, /* Q10*/ ';
  wsql = wsql||'             (BDITEMDEBESP+100) BDNUMCAMPO, /* Q10*/ ';
  wsql = wsql||'             null as BDCODNAT, ';
  wsql = wsql||'             BDVALOR as BDVALOR, ';
  wsql = wsql||'             null as BDCODCID, ';
  wsql = wsql||'             null as BDCODCIDTOT, ';
  wsql = wsql||'             null as BDCODUF, /* Q49 */ ';
  wsql = wsql||'             BDDATAVENCTO as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'             BDCLAVENC as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||' r.BDCODRECOF as BDCODRECDIMEGERQ12, /* Q12 */ '; --#167218
  wsql = wsql||' case when r.BDCODRECOF in (''1449'',''1600'',''1619'',''1627'', ';
  wsql = wsql||'                          ''1643'',''1651'',''1716'',''1759'', ';
  wsql = wsql||'                          ''1767'',''1791'',''2140'',''2496'') then 3 ';
  wsql = wsql||' else null end BDORIGEMDIMEGERQ46, ';
  wsql = wsql||'             null as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'             ''TRUE'' as BDQ12, /* Q12 */ ';
  wsql = wsql||'             ''FALSE'' as BDQ46, /* Q46 */ ';
  wsql = wsql||'             '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'             '''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'NULL as BDCODBENEFTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDNUMCONCTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDCODTIPCRED, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMS, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXON, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMSDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXONDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDESDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOCDEV /* Q15 */, NULL AS BDEXPQUAD16  ';
  wsql = wsql||'      from VEF_EMP_TDIMEGERDEBESP dime ';
  wsql = wsql||'left outer join TCODREC r on (r.BDCODREC = dime.BDCODREC) '; --#167218
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wsql = wsql||'        WHERE dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF ((wTodasAsEmpresa = 'FALSE')) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR
           (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  wsql = wsql||'        UNION ';
  wsql = wsql||'        SELECT BDCODPERIODO, ';
  wsql = wsql||'               BDCODEMP, ';
  wsql = wsql||'               BDREFERENCIA, ';
  wsql = wsql||'               BDCODQDIME, ';
  wsql = wsql||'               BDNUMCAMPO, ';
  wsql = wsql||'               BDCODNAT as BDCODNAT, ';
  wsql = wsql||'               BDVALOR as BDVALOR, ';
  wsql = wsql||'               BDCODCID as BDCODCID, ';
  wsql = wsql||'               BDCODCIDTOT as BDCODCIDTOT, ';
  wsql = wsql||'               BDCODUF as BDCODUF, ';
  wsql = wsql||'               BDDATAREC as BDDATAREC, /* Q12 */ ';
  wsql = wsql||'               BDCLAVENDIMEGERQ12 as BDCLAVENDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               BDCODRECDIMEGERQ12 as BDCODRECDIMEGERQ12, /* Q12 */ ';
  wsql = wsql||'               BDORIGEMDIMEGERQ46 as BDORIGEMDIMEGERQ46, /* Q46 */ ';
  wsql = wsql||'               BDIDENTIFICACAOREGESP as BDIDENTIFICACAOREGESP, /* Q46 */ ';
  wsql = wsql||'               BDQ12 as BDQ12, /* Q12 */ ';
  wsql = wsql||'               BDQ46 as BDQ46,  /* Q46 */ ';
  wsql = wsql||'               '''' as BDCODEXP48, /* Q48 */ ';
  wsql = wsql||'               '''' as BDALIMPREP, /* Q48 */ ';
  wsql = wsql||'CAST(NULL AS VARCHAR(15)) AS bdNUMACORDOQ12, /* Q12 */ ';
  wsql = wsql||'NULL as BDCODBENEFTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDNUMCONCTTD, /* Q15 */ ';
  wsql = wsql||'NULL as BDCODTIPCRED, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMS, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXON, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDES, /* Q15 */ ';
  wsql = wsql||'NULL as BDORDEMFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOC, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRBCICMSDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRICMSEXONDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUMDESDEV, /* Q15 */ ';
  wsql = wsql||'NULL as BDVLRFUNSOCDEV /* Q15 */, NULL AS BDEXPQUAD16  ';
  wsql = wsql||'        FROM VEF_SP_DIMEQ46 dime ';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wsql = wsql||'        WHERE dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
    BEGIN
      IF ((wTodasAsEmpresa = 'FALSE')) THEN
        wsql = wsql||'        AND BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    END
  IF (:PRREFERENCIAFINAL IS NOT NULL) THEN
    BEGIN
      IF ( ((wTodasAsEmpresa = 'FALSE')) OR
           (:PRREFERENCIAINICIAL IS NOT NULL) ) THEN
        wsql = wsql||'        AND BDREFERENCIA <= '||:PRREFERENCIAFINAL;
      ELSE
        wsql = wsql||'        WHERE BDREFERENCIA <= '||:PRREFERENCIAFINAL;
    END
  wsql = wsql||' AND DIME.BDCODPERIODO = 7 ';
  wsql = wsql||') dime ';
  wsql = wsql||' left outer join VW_EMP_REF_TOTAL empresas on (empresas.bdcodemp = DIME.bdcodemp )';
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFDIMESC TCONFDIME ON (empresas.bdcodconfdimesc = TCONFDIME.BDCODCONFDIMESC) ';
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFDIMEQ TCONF on (TCONF.bdcodqdime = DIME.bdcodqdime)';
  wsql = wsql||' left outer join VEF_ESTADOS_TCONFDIMEFORM TCONFDIMEFORM on (TCONFDIMEFORM.bdcodconfdimesc = empresas.bdcodconfdimesc and  TCONFDIMEFORM.bdcodqdime = DIME.BDCODQDIME and TCONFDIMEFORM.bdnumcampodime = DIME.BDNUMCAMPO)';
  wsql = wsql||'left outer join ( ';
  wsql = wsql||'                 select BDCODCONFDIMESC, BDCODQDIME, BDNUMCAMPODIMEQ12, BDDESCFORMDIMEQ12 from VEF_ESTADOS_TCONFDIMEFQ12 ';
  wsql = wsql||'                 union all ';
  wsql = wsql||'                 select f.BDCODCONFDIMESC, 48 as BDCODQDIME, (esp.BDITEMDEBESP+100) as BDNUMCAMPODIMEQ12, esp.BDDESCRICAO ';
  wsql = wsql||'                 from VEF_ESTADOS_TCONFDIMEFORM f ';
  wsql = wsql||'                 join VEF_BASE_TTABITEMDEBESP esp on ( esp.bdcodexportar = f.bdnumitem ) ';
  wsql = wsql||'                 where /*f.BDCODCONFDIMESC = EMPRESAS.BDCODCONFDIMESC and*/ f.BDCODQDIME = 39 ';
  wsql = wsql||'                 ) TCONFDIMEFORMQ12 on (TCONFDIMEFORMQ12.BDCODCONFDIMESC = EMPRESAS.BDCODCONFDIMESC and TCONFDIMEFORMQ12.BDCODQDIME = dime.BDCODQDIME and TCONFDIMEFORMQ12.BDNUMCAMPODIMEQ12 = dime.BDNUMCAMPO) ';
  wsql = wsql||' left outer join vef_estados_tconfdimefq46 TCONFDIMEFORMQ46 on (TCONFDIMEFORMQ46.bdcodconfdimesc = empresas.bdcodconfdimesc and  TCONFDIMEFORMQ46.bdcodqdime = DIME.BDCODQDIME and TCONFDIMEFORMQ46.bdnumcampodimeq46 = DIME.BDNUMCAMPO)';
  wsql = wsql||' left outer join TCIDADE TCID on (tcid.bdcodcid = DIME.bdcodcid) ';
  wsql = wsql||' left outer join TUF UF on (UF.bdcoduf = DIME.BDCODUF) ';
  wwhere = ' where (TCONF.BDCODTIPO <> 2) AND (TCONF.BDCODTIPO <> 3) and (TCONF.BDCODTIPO <> 72) ';
  wwhere = wwhere||' and (TCONF.BDCODTIPO <> 78) AND (TCONF.BDCODTIPO <> 80)';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
     wwhere = wwhere||' AND dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';
       wwhere = wwhere||'DIME.BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       wwhere = wwhere||'DIME.BDREFERENCIA <= '||:PRREFERENCIAFINAL;
     END
  wsql = wsql||wwhere;
  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDREFERENCIA,
    :BDNUMCAMPO,
    :BDCLASSIFICACAO,
    :BDDESCCAMPO,
    :BDVALOR,
    :BDCODCID,
    :BDCODCIDTOT,
    :BDCODNAT,
    :BDDATAREC,
    :BDCLAVENDIMEGERQ12,
    :BDCODRECDIMEGERQ12,
    :BDORIGEMDIMEGERQ46,
    :BDIDENTIFICACAOREGESP,
    :BDSIGLAUF,
    :BDVLRCONT,
    :BDVLRBC,
    :BDVLRIMPOSTO,
    :BDVLRISENTRIB,
    :BDVLROUTRAS,
    :BDNUMITEM,
    :BDVLROUTRAS,
    :BDVLROUTRAS,
    :WNUMITEM46,
    :BDCODTIPO,
    :WCODREGAPU,
    :BDALIMPREP,
    :BDCODEXP48,
    :BDNUMACORDOQ12,
    :BDCODBENEFTTD,
    :BDNUMCONCTTD,
    :BDCODTIPCRED,
    :BDVLRBCICMS,
    :BDVLRICMSEXON,
    :BDORDEMFUMDES,
    :BDVLRFUMDES,
    :BDORDEMFUNSOC,
    :BDVLRFUNSOC,
    :BDVLRBCICMSDEV,
    :BDVLRICMSEXONDEV,
    :BDVLRFUMDESDEV,
    :BDVLRFUNSOCDEV,
    :BDEXPQUAD16
  DO
  BEGIN
    IF (BDCODCID IS NULL) THEN
       IF (BDCODCIDTOT = 99999) THEN
       BDCODCID = 99999;
    IF (BDCODCID IS NULL) THEN
       IF (BDCODCIDTOT = 80047) THEN
       BDCODCID = 80047;
    IF (BDNUMITEM IS NULL) THEN
       BDNUMITEM = WNUMITEM46;
    IF ((WCODREGAPU <> 3) OR ((WCODREGAPU = 3) AND (CAST(SUBSTRING(bdclassificacao FROM 1 FOR 2) AS INTEGER) <> 8))) THEN
       SUSPEND;
  END
  wsql = 'select DIME.BDCODEMP,';
  wsql = wsql||' DIME.BDREFERENCIA,';
  wsql = wsql||' DIME.BDNUMCAMPO,';
  wsql = wsql||'''46'' bdclassificacao,';
  wsql = wsql||' NULL BDDESCCAMPO, DIME.bdvalor BDVALOR, null bdcodcid, null bdcodcidtot, null BDCODNAT, null BDDATAREC, null BDCLAVENDIMEGERQ12, null BDCODRECDIMEGERQ12,';
  wsql = wsql||' DIME.bdorigemdimegerq46 BDORIGEMDIMEGERQ46, DIME.BDIDENTIFICACAOREGESP, null BDSIGLAUF, 0 BDVLRCONT, 0 BDVLRBC,';
  wsql = wsql||' 0 BDVLRIMPOSTO, 0 BDVLRISENTRIB, 0 BDVLROUTRAS, DIME.BDNUMCAMPO bdnumitem, 0 BDVLRICMSSTPE, 0 BDVLRICMSSTOP';
  wsql = wsql||' from VEF_SP_DIMEQ46 DIME';
  wwhere = '';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
     wwhere = ' where dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';
       wwhere = wwhere||'DIME.BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       wwhere = wwhere||'DIME.BDREFERENCIA <= '||:PRREFERENCIAFINAL;
     END
  wsql = wsql||wwhere;
  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDREFERENCIA,
    :BDNUMCAMPO,
    :BDCLASSIFICACAO,
    :BDDESCCAMPO,
    :BDVALOR,
    :BDCODCID,
    :BDCODCIDTOT,
    :BDCODNAT,
    :BDDATAREC,
    :BDCLAVENDIMEGERQ12,
    :BDCODRECDIMEGERQ12,
    :BDORIGEMDIMEGERQ46,
    :BDIDENTIFICACAOREGESP,
    :BDSIGLAUF,
    :BDVLRCONT,
    :BDVLRBC,
    :BDVLRIMPOSTO,
    :BDVLRISENTRIB,
    :BDVLROUTRAS,
    :BDNUMITEM,
    :BDVLROUTRAS,
    :BDVLROUTRAS
  DO
  BEGIN
    SUSPEND;
  END
  wsql = 'select DIME.BDCODEMP,';
  wsql = wsql||' DIME.BDREFERENCIA,';
  wsql = wsql||' DIME.BDORDEM BDNUMCAMPO,';
  wsql = wsql||'''12'' bdclassificacao,';
  wsql = wsql||' DIME.BDNUMACORDO BDDESCCAMPO,';
  wsql = wsql||' DIME.BDVALOR,';
  wsql = wsql||' null bdcodcid,';
  wsql = wsql||' null bdcodcidtot,';
  wsql = wsql||' null BDCODNAT,';
  wsql = wsql||' DIME.BDDATAVENCTO BDDATAREC,';
  wsql = wsql||' DIME.BDCLAVENC BDCLAVENDIMEGERQ12,';
  wsql = wsql||' r.BDCODRECOF as BDCODRECDIMEGERQ12, ';
  wsql = wsql||' CASE WHEN ((r.BDCODRECOF = ''3662'') OR (r.BDCODRECOF = ''7137'')) THEN ''4'' ELSE DIME.BDORIGPAGTOIMP END BDORIGEMDIMEGERQ46,'; --#167218
  wsql = wsql||' NULL BDIDENTIFICACAOREGESP, ';
  wsql = wsql||' null BDSIGLAUF,';
  wsql = wsql||' 0 BDVLRCONT,';
  wsql = wsql||' 0 BDVLRBC,';
  wsql = wsql||' 0 BDVLRIMPOSTO,';
  wsql = wsql||' 0 BDVLRISENTRIB,';
  wsql = wsql||' 0 BDVLROUTRAS,';
  wsql = wsql||' 0 bdnumitem,';
  wsql = wsql||' 0 BDVLRICMSSTPE,';
  wsql = wsql||' 0 BDVLRICMSSTOP';
  wsql = wsql||' from VEF_EMP_TDIMEGERPAGTOIMP DIME';
  wsql = wsql||' left outer join TCODREC r on (r.BDCODREC = dime.BDCODRECCLAVENC) ';
  wwhere = '';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
     wwhere = ' where dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';
       wwhere = wwhere||'DIME.BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       wwhere = wwhere||'DIME.BDREFERENCIA <= '||:PRREFERENCIAFINAL;
     END  
  wsql = wsql||wwhere;
  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDREFERENCIA,
    :BDNUMCAMPO,
    :BDCLASSIFICACAO,
    :BDDESCCAMPO,
    :BDVALOR,
    :BDCODCID,
    :BDCODCIDTOT,
    :BDCODNAT,
    :BDDATAREC,
    :BDCLAVENDIMEGERQ12,
    :BDCODRECDIMEGERQ12,
    :BDORIGEMDIMEGERQ46,
    :BDIDENTIFICACAOREGESP,
    :BDSIGLAUF,
    :BDVLRCONT,
    :BDVLRBC,
    :BDVLRIMPOSTO,
    :BDVLRISENTRIB,
    :BDVLROUTRAS,
    :bdnumitem,
    :BDVLROUTRAS,
    :BDVLROUTRAS
  DO
  BEGIN
    SUSPEND;
  END
  wwhere = NULL;
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
    wwhere = ' where dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
 IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
  BEGIN
    IF (wwhere IS NULL) THEN
       wwhere = ' where ';
    ELSE
       wwhere = wwhere||' and ';
    wwhere = wwhere||' DIME.BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
    wwhere = wwhere||'  and ';
    wwhere = wwhere||' DIME.BDREFERENCIA <= '||:PRREFERENCIAFINAL;
  END
  wsql =       'select '; 
  wsql = wsql||'    DIME.BDCODEMP, ';
  wsql = wsql||'    DIME.BDREFERENCIA, ';
  wsql = wsql||'    DIME.BDNUMCAMPO, ';
  wsql = wsql||'    Q.bdclassificacao, ';
  wsql = wsql||'    null BDDESCCAMPO, ';
  wsql = wsql||'    DIME.BDVALOR, ';
  wsql = wsql||'    null bdcodcid, ';
  wsql = wsql||'    null bdcodcidtot, ';
  wsql = wsql||'    DIME.BDPREFIXONAT BDCODNAT, ';
  wsql = wsql||'    NULL BDDATAREC, ';
  wsql = wsql||'    NULL BDCLAVENDIMEGERQ12, ';
  wsql = wsql||'    NULL BDCODRECDIMEGERQ12, ';
  wsql = wsql||'    NULL BDORIGEMDIMEGERQ46, ';
  wsql = wsql||'    NULL BDIDENTIFICACAOREGESP, ';
  wsql = wsql||'    null BDSIGLAUF, ';
  wsql = wsql||'    0 BDVLRCONT, ';
  wsql = wsql||'    0 BDVLRBC, ';
  wsql = wsql||'    0 BDVLRIMPOSTO, ';
  wsql = wsql||'    0 BDVLRISENTRIB, ';
  wsql = wsql||'    0 BDVLROUTRAS, ';
  wsql = wsql||'    C.bdnumitem, ';
  wsql = wsql||'    0 BDVLRICMSSTPE, ';
  wsql = wsql||'    0 BDVLRICMSSTOP, ';
  wsql = wsql||'    Q.BDCODTIPO ';
  wsql = wsql||'from ( ';
  wsql = wsql||'    select ';
  wsql = wsql||'        DIME.bdcodemp, ';
  wsql = wsql||'        DIME.bdcodperiodo, ';
  wsql = wsql||'        DIME.bdreferencia, ';
  wsql = wsql||'        DIME.bdcodqdime, ';
  wsql = wsql||'        DIME.bdprefixonat, ';
  wsql = wsql||'        DIME.bdnumcampo, ';
  wsql = wsql||'        sum(DIME.bdvalor) bdvalor ';
  wsql = wsql||'    from vef_emp_tdimegernat DIME ';
  wsql = wsql||     wwhere;
  IF (wwhere = '') THEN
     wsql = wsql||' where bdvalor > 0 ';
  ELSE
     wsql = wsql||' and bdvalor > 0 ';
  wsql = wsql||' AND DIME.BDCODPERIODO = 7 ';
  wsql = wsql||'    group by ';
  wsql = wsql||'        DIME.bdcodemp, ';
  wsql = wsql||'        DIME.bdcodperiodo, ';
  wsql = wsql||'        DIME.bdreferencia, ';
  wsql = wsql||'        DIME.bdcodqdime, ';
  wsql = wsql||'        DIME.bdprefixonat,';
  wsql = wsql||'        DIME.bdnumcampo ';
  wsql = wsql||'      ) DIME, vef_estados_tconfdimeform C, VEF_EMP_TDIMESCGER D, vef_estados_tconfdimeq Q ';
  wsql = wsql||'WHERE ';
  wsql = wsql||'    D.bdcodemp = DIME.bdcodemp AND ';
  wsql = wsql||'    D.bdreferencia = DIME.bdreferencia AND ';
  wsql = wsql||'    D.bdcodperiodo = DIME.bdcodperiodo AND ';
  wsql = wsql||'    D.bdcodconf = C.bdcodconfdimesc AND ';
  wsql = wsql||'    DIME.bdnumcampo = C.bdnumcampodime AND ';
  wsql = wsql||'    DIME.bdcodqdime= C.bdcodqdime AND ';
  wsql = wsql||'    Q.bdcodqdime = DIME.bdcodqdime ';
  wnat = 0;
  wVLRCONTAux = 0;
  wVLRBCAux = 0;
  wVLRIMPOSTOAux = 0;
  wVLRISENTRIBAux = 0;
  wVLROUTRASAux = 0;
  wbasest = 0;
  wicmsretst = 0;
  wdifaliqent = 0;
  FOR EXECUTE STATEMENT wsql
  INTO
    :wCODEMP,
    :wREFERENCIA,
    :wNUMCAMPO,
    :wCLASSIFICACAO,
    :wDESCCAMPO,
    :wVALOR,
    :wCODCID,
    :wCODCIDTOT,
    :wCODNAT,
    :wDATAREC,
    :wCLAVENDIMEGERQ12,
    :wCODRECDIMEGERQ12,
    :wORIGEMDIMEGERQ46,
    :wIDENTIFICACAOREGESP,
    :wSIGLAUF,
    :wVLRCONT,
    :wVLRBC,
    :wVLRIMPOSTO,
    :wVLRISENTRIB,
    :wVLROUTRAS,
    :wnumitemaux,
    :wVLRICMSSTPE,
    :wVLRICMSSTOP,
    :wCODTIPO
  DO
  BEGIN
    IF (wnat = 0) THEN
       wnat = :wCODNAT;
    IF (wnat <> :wCODNAT) THEN
      BEGIN
       wVLRCONTAux = 0;
       wVLRBCAux = 0;
       wVLRIMPOSTOAux = 0;
       wVLRISENTRIBAux = 0;
       wVLROUTRASAux = 0;
       wbasest = 0;
       wicmsretst = 0;
       wdifaliqent = 0;
      END
    IF (wnumitemaux =  4) THEN
       wVLRCONTAux = WVALOR;
    ELSE
    IF (wnumitemaux =  5) THEN
       wVLRBCAux = wVALOR;
    ELSE
    IF (wnumitemaux =  6) THEN
       wVLRIMPOSTOAux = wVALOR;
    ELSE
    IF (wnumitemaux =  7) THEN
       wVLRISENTRIBAux = wVALOR;
    ELSE
    IF (wnumitemaux =  8) THEN
       wVLROUTRASAux = wVALOR;
    ELSE
    IF (wnumitemaux =  9) THEN
       wbasest = wvalor;
    ELSE
    IF (wnumitemaux = 10) THEN
       wicmsretst = wvalor;
    ELSE
    IF (wnumitemaux = 11) THEN
       wdifaliqent = wvalor;
    IF (wnat <> :wCODNAT) THEN
      BEGIN
        wnat = :wCODNAT;
        SUSPEND;
      END
    bdCODEMP = wCODEMP;
    bdREFERENCIA = wREFERENCIA;
    bdNUMCAMPO = wNUMCAMPO;
    bdCLASSIFICACAO = wCLASSIFICACAO;
    bdDESCCAMPO = wDESCCAMPO;
    bdVALOR = wVALOR;
    bdCODCID = wCODCID;
    bdCODCIDTOT = wCODCIDTOT;
    BDcodnat = wCODNAT;
    bdDATAREC = wDATAREC;
    bdCLAVENDIMEGERQ12 = wCLAVENDIMEGERQ12;
    bdCODRECDIMEGERQ12 = wCODRECDIMEGERQ12;
    bdORIGEMDIMEGERQ46 = wORIGEMDIMEGERQ46;
    BDIDENTIFICACAOREGESP = wIDENTIFICACAOREGESP;
    bdSIGLAUF = wSIGLAUF;
    bdVLRCONT = wVLRCONTAux;
    bdVLRBC = wVLRBCAux;
    bdVLRIMPOSTO = wVLRIMPOSTOAux;
    bdVLRISENTRIB = wVLRISENTRIBAux;
    bdVLROUTRAS = wVLROUTRASAux;
    bdbasest = wbasest;
    bdicmsretst = wicmsretst;
    bddifaliqent = wdifaliqent;
    BDNUMITEM = wnumitemaux;
    BDVLRICMSSTPE = wVLRICMSSTPE;
    BDVLRICMSSTOP = wVLRICMSSTOP;
    BDCODTIPO = wCODTIPO;
    IF (wCLASSIFICACAO = '01.02') THEN--alt:#7162
      BEGIN
        wdifaliqent = 0;
        wicmsretst  = 0;
      END
  END
  IF (bdCODNAT > 0) THEN
     SUSPEND;
  wsql = 'select  DIME.BDCODEMP,';
  wsql = wsql||' DIME.BDREFERENCIA,';
  wsql = wsql||' BDNUMCAMPO,';
  wsql = wsql||' Q.bdclassificacao,';
  wsql = wsql||' null BDDESCCAMPO,';
  wsql = wsql||' DIME.BDVALOR,';
  wsql = wsql||' null bdcodcid,';
  wsql = wsql||' null bdcodcidtot,';
  wsql = wsql||' null BDCODNAT,';
  wsql = wsql||' NULL BDDATAREC,';
  wsql = wsql||' NULL BDCLAVENDIMEGERQ12,';
  wsql = wsql||' NULL BDCODRECDIMEGERQ12,';
  wsql = wsql||' NULL BDORIGEMDIMEGERQ46,';
  wsql = wsql||' NULL BDIDENTIFICACAOREGESP, ';
  wsql = wsql||' U.BDSIGLAUF,';
  wsql = wsql||' 0 BDVLRCONT,';
  wsql = wsql||' 0 BDVLRBC,';
  wsql = wsql||' 0 BDVLRIMPOSTO,';
  wsql = wsql||' 0 BDVLRISENTRIB,';
  wsql = wsql||' 0 BDVLROUTRAS,';
  wsql = wsql||' C.bdnumitem,';
  wsql = wsql||' 0 BDVLRICMSSTPE,';
  wsql = wsql||' 0 BDVLRICMSSTOP,';
  wsql = wsql||' DIME.BDCODUF,';
  wsql = wsql||' Q.BDCODTIPO';
  wsql = wsql||' FROM VEF_EMP_TDIMEGERQ49 DIME';
  wsql = wsql||' LEFT OUTER JOIN TUF U ON (U.bdcoduf = DIME.BDCODUF) ';
  wsql = wsql||' INNER JOIN VEF_EMP_TDIMESCGER D ON (D.bdcodemp = DIME.bdcodemp AND D.bdreferencia = DIME.bdreferencia AND D.bdcodperiodo = DIME.bdcodperiodo)';
  wsql = wsql||' INNER JOIN vef_estados_tconfdimeform C ON (D.bdcodconf = C.bdcodconfdimesc AND DIME.bdnumcampo = C.bdnumcampodime AND  DIME.bdcodqdime= C.bdcodqdime)';
  wsql = wsql||' INNER JOIN vef_estados_tconfdimeq Q ON (Q.bdcodqdime = DIME.bdcodqdime)';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
     wwhere = ' AND dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||' and ';
       wwhere = wwhere||'DIME.BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
       wwhere = wwhere||' and ';
       wwhere = wwhere||'DIME.BDREFERENCIA <= '||:PRREFERENCIAFINAL;
     END
  wsql = wsql||wwhere;
  wsql = wsql||' AND DIME.BDCODPERIODO = 7 ';
  wsql = wsql||' ORDER BY DIME.bdcodemp,DIME.bdcodperiodo, DIME.bdreferencia, DIME.bdcodqdime,DIME.bdcoduf desc, C.bdnumitem';
  wuf = 0;
  wVLRCONTAux = 0;
  wVLRBCAux = 0;
  wVLROUTRASAux = 0;
  wVLRICMSSTPEAux = 0;
  wVLRICMSSTOPAux = 0;
  FOR EXECUTE STATEMENT wsql
  INTO
    :wCODEMP,
    :wREFERENCIA,
    :wNUMCAMPO,
    :wCLASSIFICACAO,
    :wDESCCAMPO,
    :wVALOR,
    :wCODCID,
    :wCODCIDTOT,
    :wCODNAT,
    :wDATAREC,
    :wCLAVENDIMEGERQ12,
    :wCODRECDIMEGERQ12,
    :wORIGEMDIMEGERQ46,
    :wIDENTIFICACAOREGESP,
    :wSIGLAUF,
    :wVLRCONT,
    :wVLRBC,
    :wVLRIMPOSTO,
    :wVLRISENTRIB,
    :wVLROUTRAS,
    :wnumitemaux,
    :wVLRICMSSTPE,
    :wVLRICMSSTOP,
    :wCODUF,
    :wCODTIPO
  DO
  BEGIN
    IF (wuf = 0) THEN
       wuf = :wCODUF;
    IF (wnumitemaux = 1) THEN
       wVLRCONTAux = wVALOR;
    ELSE
    IF (wnumitemaux = 2) THEN
       wVLRBCAux = wVALOR;
    ELSE
    IF (wnumitemaux = 3) THEN
       wVLROUTRASAux = wVALOR;
    ELSE
    IF (wnumitemaux = 4) THEN
       wVLRICMSSTPEAux = wVALOR;
    ELSE
    IF (wnumitemaux = 5) THEN
       wVLRICMSSTOPAux = wVALOR;
    IF ((wuf = 99999) AND (wSIGLAUF IS NULL)) THEN
       wSIGLAUF = 'TT';
    IF ((wSIGLAUF IS NULL) AND (wuf <> 99999)) THEN
       BEGIN
          SUSPEND;
          wSIGLAUF = 'TT';
          wuf = 99999;
       END
    ELSE
    IF (:wSIGLAUF <> 'TT') THEN
       IF ((wuf <> :wCODUF) OR (:wCODUF IS NULL)) THEN
          BEGIN
             wuf = :wCODUF;
             SUSPEND;
          END
    IF ((:wSIGLAUF = 'TT') AND ((wVLRCONTAux > 0) OR (wVLRBCAux > 0) OR (wVLROUTRASAux > 0) OR (wVLRICMSSTPEAux > 0) OR (wVLRICMSSTOPAux > 0)) AND
       ((bdCODEMP <> wCODEMP) OR (bdREFERENCIA <> wREFERENCIA))) THEN
       SUSPEND;
    bdCODEMP = wCODEMP;
    bdREFERENCIA = wREFERENCIA;
    bdNUMCAMPO = wNUMCAMPO;
    bdCLASSIFICACAO = wCLASSIFICACAO;
    bdDESCCAMPO = wDESCCAMPO;
    bdVALOR = wVALOR;
    bdCODCID = wCODCID;
    bdCODCIDTOT = wCODCIDTOT;
    bdcodnat = wCODNAT;
    bdDATAREC = wDATAREC;
    bdCLAVENDIMEGERQ12 = wCLAVENDIMEGERQ12;
    bdCODRECDIMEGERQ12 = wCODRECDIMEGERQ12;
    bdORIGEMDIMEGERQ46 = wORIGEMDIMEGERQ46;
    BDIDENTIFICACAOREGESP = wIDENTIFICACAOREGESP;
    bdSIGLAUF = wSIGLAUF;
    bdVLRCONT = wVLRCONTAux;
    bdVLRBC = wVLRBCAux;
    bdVLRIMPOSTO = wVLRIMPOSTOAux;
    bdVLRISENTRIB = wVLRISENTRIBAux;
    bdVLROUTRAS = wVLROUTRASAux;
    BDNUMITEM = wnumitemaux;
    BDVLRICMSSTPE = wVLRICMSSTPEAUX;
    BDVLRICMSSTOP = wVLRICMSSTOPAUX;
    BDCODTIPO = wCODTIPO;
  END
  IF ((wSIGLAUF = 'TT') AND ((wVLRCONTAux > 0) OR (wVLRBCAux > 0) OR (wVLROUTRASAux > 0) OR (wVLRICMSSTPEAux > 0) OR (wVLRICMSSTOPAux > 0)))THEN
     SUSPEND;
  wsql = 'select  DIME.BDCODEMP,';
  wsql = wsql||' DIME.BDREFERENCIA,';
  wsql = wsql||' BDNUMCAMPO,';
  wsql = wsql||' Q.bdclassificacao,';
  wsql = wsql||' null BDDESCCAMPO,';
  wsql = wsql||' DIME.BDVALOR,';
  wsql = wsql||' null bdcodcid,';
  wsql = wsql||' null bdcodcidtot,';
  wsql = wsql||' null BDCODNAT,';
  wsql = wsql||' NULL BDDATAREC,';
  wsql = wsql||' NULL BDCLAVENDIMEGERQ12,';
  wsql = wsql||' NULL BDCODRECDIMEGERQ12,';
  wsql = wsql||' NULL BDORIGEMDIMEGERQ46,';
  wsql = wsql||' NULL BDIDENTIFICACAOREGESP, ';
  wsql = wsql||' U.BDSIGLAUF,';
  wsql = wsql||' 0 BDVLRCONT,';
  wsql = wsql||' 0 BDVLRBC,';
  wsql = wsql||' 0 BDVLRIMPOSTO,';
  wsql = wsql||' 0 BDVLRISENTRIB,';
  wsql = wsql||' 0 BDVLROUTRAS,';
  wsql = wsql||' C.bdnumitem,';
  wsql = wsql||' 0 BDVLRICMSSTPE,';
  wsql = wsql||' 0 BDVLRICMSSTOP,';
  wsql = wsql||' DIME.BDCODUF,';
  wsql = wsql||' 0 BDVLRCONTCONT,';
  wsql = wsql||' 0 BDVLRBCCONT,';
  wsql = wsql||' 0 BDVLRICMSST,';
  wsql = wsql||' Q.BDCODTIPO';
  wsql = wsql||' FROM VEF_EMP_TDIMEGERQ50 DIME';
  wsql = wsql||' LEFT OUTER JOIN TUF U ON (U.bdcoduf = DIME.BDCODUF) ';
  wsql = wsql||' INNER JOIN VEF_EMP_TDIMESCGER D ON (D.bdcodemp = DIME.bdcodemp AND D.bdreferencia = DIME.bdreferencia AND D.bdcodperiodo = DIME.bdcodperiodo)';
  wsql = wsql||' INNER JOIN vef_estados_tconfdimeform C ON (D.bdcodconf = C.bdcodconfdimesc AND DIME.bdnumcampo = C.bdnumcampodime AND  DIME.bdcodqdime= C.bdcodqdime)';
  wsql = wsql||' INNER JOIN vef_estados_tconfdimeq Q ON (Q.bdcodqdime = DIME.bdcodqdime)';
  IF ((wTodasAsEmpresa = 'FALSE')) THEN
     wwhere = ' AND dime.BDCODEMP IN (SELECT t.bdCODEMP FROM TMP_EMPRESAS_SELECT t)';
  IF (:PRREFERENCIAINICIAL IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||' and ';
       wwhere = wwhere||'DIME.BDREFERENCIA >= '||:PRREFERENCIAINICIAL;
       wwhere = wwhere||' and ';
       wwhere = wwhere||'DIME.BDREFERENCIA <= '||:PRREFERENCIAFINAL;
     END
  wsql = wsql||wwhere;
  wsql = wsql||' AND DIME.BDCODPERIODO = 7 ';
  wsql = wsql||' ORDER BY DIME.bdcodemp,DIME.bdcodperiodo, DIME.bdreferencia, DIME.bdcodqdime,DIME.bdcoduf desc, C.bdnumitem';
  wuf = 0;
  wVLRCONTAux = 0;
  wVLRCONTCONTAux = 0;
  wVLRBCAux = 0;
  wVLRBCCONTAux = 0;
  wVLROUTRASAux = 0;
  wVLRICMSSTAux = 0;
  FOR EXECUTE STATEMENT wsql
  INTO
    :wCODEMP,
    :wREFERENCIA,
    :wNUMCAMPO,
    :wCLASSIFICACAO,
    :wDESCCAMPO,
    :wVALOR,
    :wCODCID,
    :wCODCIDTOT,
    :wCODNAT,
    :wDATAREC,
    :wCLAVENDIMEGERQ12,
    :wCODRECDIMEGERQ12,
    :wORIGEMDIMEGERQ46,
    :wIDENTIFICACAOREGESP,
    :wSIGLAUF,
    :wVLRCONT,
    :wVLRBC,
    :wVLRIMPOSTO,
    :wVLRISENTRIB,
    :wVLROUTRAS,
    :wnumitemaux,
    :wVLRICMSSTPE,
    :wVLRICMSSTOP,
    :wCODUF,
    :wVLRCONTCONT,
    :wVLRBCCONT,
    :wVLRICMSST,
    :wCODTIPO
  DO
  BEGIN
    IF (wuf = 0) THEN
       wuf = :wCODUF;
    IF (wnumitemaux = 1) THEN
       wVLRCONTAux = wVALOR;
    ELSE
    IF (wnumitemaux = 2) THEN
       wVLRCONTCONTAux = wVALOR;
    ELSE
    IF (wnumitemaux = 3) THEN
       wVLRBCAux = wVALOR;
    ELSE
    IF (wnumitemaux = 4) THEN
       wVLRBCCONTAux = wVALOR;
    ELSE
    IF (wnumitemaux = 5) THEN
       wVLROUTRASAux = wVALOR;
    ELSE
    IF (wnumitemaux = 6) THEN
       wVLRICMSSTAux = wVALOR;
    IF ((wuf = 99999) AND (wSIGLAUF IS NULL)) THEN
       wSIGLAUF = 'TT';
    IF ((wSIGLAUF IS NULL) AND (wuf <> 99999)) THEN
       BEGIN
          SUSPEND;
          wSIGLAUF = 'TT';
          wuf = 99999;
       END
    ELSE
    IF (:wSIGLAUF <> 'TT') THEN
       IF ((wuf <> :wCODUF) OR (:wCODUF IS NULL)) THEN
          BEGIN
             wuf = :wCODUF;
             SUSPEND;
          END
    IF ((:wSIGLAUF = 'TT') AND ((wVLRCONTAux > 0) OR (wVLRCONTCONTAux > 0) OR(wVLRBCAux > 0) OR(wVLRBCCONTAux > 0) OR(wVLROUTRASAux > 0) OR(wVLRICMSSTAux > 0)) AND
       ((bdCODEMP <> wCODEMP) OR (bdREFERENCIA <> wREFERENCIA))) THEN
       SUSPEND;
    bdCODEMP = wCODEMP;
    bdREFERENCIA = wREFERENCIA;
    bdNUMCAMPO = wNUMCAMPO;
    bdCLASSIFICACAO = wCLASSIFICACAO;
    bdDESCCAMPO = wDESCCAMPO;
    bdVALOR = wVALOR;
    bdCODCID = wCODCID;
    bdCODCIDTOT = wCODCIDTOT;
    BDCODNAT = wCODNAT;
    bdDATAREC = wDATAREC;
    bdCLAVENDIMEGERQ12 = wCLAVENDIMEGERQ12;
    bdCODRECDIMEGERQ12 = wCODRECDIMEGERQ12;
    bdORIGEMDIMEGERQ46 = wORIGEMDIMEGERQ46;
    BDIDENTIFICACAOREGESP = wIDENTIFICACAOREGESP;
    bdSIGLAUF = wSIGLAUF;
    bdVLRCONT = wVLRCONTAux;
    bdVLRBC = wVLRBCAux;
    bdVLRIMPOSTO = wVLRIMPOSTOAux;
    bdVLRISENTRIB = wVLRISENTRIBAux;
    bdVLROUTRAS = wVLROUTRASAux;
    BDNUMITEM = wnumitemaux;
    BDVLRICMSSTPE = wVLRICMSSTPEAUX;
    BDVLRICMSSTOP = wVLRICMSSTOPAUX;
    BDVLRCONTCONT = WVLRCONTCONTAUX;
    BDVLRBCCONT = WVLRBCCONTAUX;
    BDVLRICMSST = WVLRICMSSTAUX;
    BDCODTIPO = wCODTIPO;
  END
  IF (((wVLRCONTAux > 0) OR (wVLRCONTCONTAux > 0) OR(wVLRBCAux > 0) OR (wVLRBCCONTAux > 0) OR(wVLROUTRASAux > 0) OR(wVLRICMSSTAux > 0)) AND (wSIGLAUF = 'TT')) THEN
     SUSPEND;
END^

/* Restore proc. body: VEF_SP_EXP_DIPJ_REG1_18 */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG1_18(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDNOMEMP DM_BDNOMEMP,
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDSIGLAUFEMP VARCHAR(2),
BDCODCIDEMP INTEGER,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDDDDFAXEMP INTEGER,
BDFAXEMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDNOMSOC VARCHAR(80),
BDDDDSOC INTEGER,
BDTELRESSOC VARCHAR(15),
BDDDDFAXSOC INTEGER,
BDFAXSOC VARCHAR(9),
BDCGCCEISOC VARCHAR(18),
BDEMAILSOC DM_BDEMAIL,
BDCODCONT INTEGER,
BDNOMECONT VARCHAR(40),
BDCRCCONT VARCHAR(15),
BDSIGLAUFCONT VARCHAR(2),
BDCPFCONT VARCHAR(14),
BDDDDCONT INTEGER,
BDFONECONT DM_BDTELEFONE,
BDDDDFAXCONT INTEGER,
BDFAXCONT DM_BDTELEFONE,
BDEMAILCONT DM_BDEMAIL,
BDVLRRECBRU1_6_IRLP NUMERIC(15,6),
BDVLRRECBRU8_IRLP NUMERIC(15,6),
BDVLRRECBRU16_IRLP NUMERIC(15,6),
BDVLRRECBRU32_IRLP NUMERIC(15,6),
BDVLRLUCROPRESUMIDO_IRLP NUMERIC(15,6),
BDVLRADICIONAL_IRLP NUMERIC(15,6),
BDVLRIMPOSTOPAGAR_IRLP NUMERIC(15,6),
BDVLRIMPOSTORETIDO_IRLP NUMERIC(15,6),
BDVLRALIQ15_IRLP NUMERIC(15,6),
BDVLRCSLLAPAGAR_IRLP NUMERIC(15,6),
BDVLRRECBRU12_IRLP NUMERIC(15,6),
BDVLRRECBRUAJUST_IRLP NUMERIC(15,6),
BDVLRCSLLAPURADA_IRLP NUMERIC(15,6),
BDVLRCSLLRETPJ NUMERIC(15,6),
BDREFERENCIA INTEGER,
BDTRIMESTRE INTEGER,
BDVLRRECBRU32_CSLL NUMERIC(15,6))
 AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
DECLARE VARIABLE WNUMITEM INTEGER;
DECLARE VARIABLE WCODQIRLP INTEGER;
DECLARE VARIABLE WVALORIRLPGER NUMERIC(15,6);
DECLARE VARIABLE WSEQREG INTEGER;
DECLARE VARIABLE WULTREFERENCIA INTEGER;
DECLARE VARIABLE WULTTRIMESTRE INTEGER;
DECLARE VARIABLE WTRIMESTREAUX INTEGER;
BEGIN
    EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);
  
/*$$IBEC$$     wSql = 'select temp.bdcodemp, ';
    wSql = wSql || 'temp.bdcnpjemp, ';
    wSql = wSql || 'trefemp.bdnomemp, ';
    wSql = wSql || 'trefemp.bdcodnatjur, ';
    wSql = wSql || 'trefemp.bdcodcnae, ';
    wSql = wSql || 'trefemp.bdlogremp, ';
    wSql = wSql || 'trefemp.bdendemp, ';
    wSql = wSql || 'trefemp.bdnumemp, ';
    wSql = wSql || 'trefemp.bdcomplemp, ';
    wSql = wSql || 'trefemp.bdbaiemp, ';
    wSql = wSql || 'tufemp.bdsiglauf, ';
    wSql = wSql || 'tcidemp.bdcodfed, ';
    wSql = wSql || 'trefemp.bdcepemp, ';
    wSql = wSql || 'trefemp.bddddemp, ';
    wSql = wSql || 'trefemp.bdfoneemp, ';
    wSql = wSql || 'trefemp.bddddfaxemp, ';
    wSql = wSql || 'trefemp.bdfaxemp, ';
    wSql = wSql || 'trefemp.bdemailemp, ';
    wSql = wSql || 'tsoc.bdnomsoc, ';
    wSql = wSql || 'tsoc.bdcgcceisoc, ';
    wSql = wSql || 'tsoc.bdddsoc, ';
    wSql = wSql || 'tsoc.bdtelressoc, ';
    wSql = wSql || 'tsoc.bddddfaxsoc, ';
    wSql = wSql || 'tsoc.bdfaxsoc, ';
    wSql = wSql || 'tsoc.bdcgcceisoc, ';
    wSql = wSql || 'tsoc.bdemailsoc, ';
    wSql = wSql || 'tcon.bdcodcont, ';
    wSql = wSql || 'tcon.bdnomecont, ';
    wSql = wSql || 'tcon.bdcrccont, ';
    wSql = wSql || 'tufcont.bdsiglauf, ';
    wSql = wSql || 'tcon.bdcpfcont, ';
    wSql = wSql || 'tcon.bddddcont, ';
    wSql = wSql || 'tcon.bdfonecont, ';
    wSql = wSql || 'tcon.bddddfaxcont, ';
    wSql = wSql || 'tcon.bdfaxcont, ';
    wSql = wSql || 'tcon.bdemailcont, ';
    wSql = wSql || 'tconfirlpform.bdnumitem, ';
    wSql = wSql || 'tirlpgerreg.bdReferencia, ';
    wSql = wSql || 'tirlpgerreg.bdvalor ';
    wSql = wSql || 'from TEMPRESAS temp ';
    wSql = wSql || 'left outer join vw_tempresas_ref trefemp on (trefemp.bdCODEMP = temp.bdCODEMP) ';
    wSql = wSql || 'left outer join tcidade tcidemp on (tcidemp.bdcodcid = trefemp.bdcodcid) ';
    wSql = wSql || 'left outer join tuf tufemp on (tufemp.bdcoduf = tcidemp.bdcoduf) ';
    wSql = wSql || 'left outer join TCONTADOR_PADRAO tcon on (tcon.BDCODCONT = trefemp.BDCODCONT) ';
    wSql = wSql || 'left outer join tcidade tcidcont on (tcidcont.bdcodcid = tcon.bdcodcid) ';
    wSql = wSql || 'left outer join tuf tufcont on (tufcont.bdcoduf = tcidcont.bdcoduf) ';
    wSql = wSql || 'left outer join EMPRESAS_TSOC tsoc on (tsoc.bdcodemp = temp.bdcodemp and upper(tsoc.bdresponsavelsoc) = '''||'TRUE'||''') ';
    wSql = wSql || 'left outer join VEF_EMP_TIRLPGER tirlpger on (tirlpger.bdcodperiodo in (8,9,10) and tirlpger.bdcodemp = temp.bdcodemp) and
                                                                  tirlpger.bdREFERENCIA >= '||prrefini||' and '||'tirlpger.bdREFERENCIA <= '||prreffin||' ';
    wSql = wSql || 'left outer join vef_emp_tirlpgerreg tirlpgerreg on (tirlpgerreg.bdcodemp = tirlpger.bdcodemp and tirlpgerreg.bdcodperiodo = tirlpger.bdcodperiodo and
                                                                        tirlpgerreg.bdreferencia = tirlpger.bdreferencia) ';
    wSql = wSql || 'left outer join vef_base_tconfirlpform tconfirlpform on tconfirlpform.bdcodconfirlp = tirlpger.bdcodconfirlp and tconfirlpform.bdcodqirlp = tirlpgerreg.bdcodqirlp and tconfirlpform.bdnumcampoirlp = tirlpgerreg.bdnumcampo '; $$IBEC$$*/

  wsql = ' select first 1 temp.bdcodemp, temp.bdcnpjemp, trefemp.bdnomemp, trefemp.bdcodnatjur, ';
  wsql = wsql||'          trefemp.bdcodcnae, trefemp.bdlogremp, trefemp.bdendemp, trefemp.bdnumemp, ';
  wsql = wsql||'          trefemp.bdcomplemp, trefemp.bdbaiemp, tufemp.bdsiglauf, tcidemp.bdcodfed, ';
  wsql = wsql||'          trefemp.bdcepemp, trefemp.bddddemp, trefemp.bdfoneemp, trefemp.bddddfaxemp, ';
  wsql = wsql||'          trefemp.bdfaxemp, trefemp.bdemailemp, tsoc.bdnomsoc, tsoc.bdcgcceisoc, ';
  wsql = wsql||'          tsoc.bddddsoc, tsoc.bdtelressoc, tsoc.bddddfaxsoc, tsoc.bdfaxsoc, ';
  wsql = wsql||'          tsoc.bdcgcceisoc, tsoc.bdemailsoc, tcon.bdcodcont, tcon.bdnomecont, ';
  wsql = wsql||'          tcon.bdcrccont, tufcont.bdsiglauf, tcon.bdcpfcont, tcon.bddddcont, ';
  wsql = wsql||'          tcon.bdfonecont, tcon.bddddfaxcont, tcon.bdfaxcont, tcon.bdemailcont ';
  wsql = wsql||'   from TEMPRESAS temp ';
  wsql = wsql||'   left outer join vw_tempresas_ref trefemp on (trefemp.bdCODEMP = temp.bdCODEMP) ';
  wsql = wsql||'   left outer join tcidade tcidemp on (tcidemp.bdcodcid = trefemp.bdcodcid) ';
  wsql = wsql||'   left outer join tuf tufemp on (tufemp.bdcoduf = tcidemp.bdcoduf) ';
  wsql = wsql||'   left outer join TCONTADOR_PADRAO tcon on (tcon.BDCODCONT = trefemp.BDCODCONT) ';
  wsql = wsql||'   left outer join tcidade tcidcont on (tcidcont.bdcodcid = tcon.bdcodcid) ';
  wsql = wsql||'   left outer join tuf tufcont on (tufcont.bdcoduf = tcidcont.bdcoduf) ';
  wsql = wsql||'   left outer join VW_EMPRESAS_TSOC_REF tsoc on (tsoc.bdcodemp = temp.bdcodemp and upper(tsoc.bdresponsavelsoc) = ''TRUE'') ';

  wwhere = '';
  
  IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
    wwhere = wWhere||'('||prempresas||') ';
  
  IF (wwhere <> '') THEN
    wwhere = 'where '||wwhere||' ';
  
  /*definir na aplicação*/
--  worderby = 'order by bdcodemp, bdreferencia ';

  wsql = wsql||wwhere;--||worderby;

  EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :bdcnpjemp,
    :bdnomemp,
    :bdcodnatjur,
    :bdcodcnae,
    :bdlogremp,
    :bdendemp,
    :bdnumemp,
    :bdcomplemp,
    :bdbaiemp,
    :bdsiglaufemp,
    :bdcodcidemp,
    :bdcepemp,
    :bddddemp,
    :bdfoneemp,
    :bddddfaxemp,
    :bdfaxemp,
    :bdemailemp,
    :bdnomsoc,
    :bdcgcceisoc,
    :bddddsoc,
    :bdtelressoc,
    :bddddfaxsoc,
    :bdfaxsoc,
    :bdcgcceisoc,
    :bdemailsoc,
    :bdcodcont,
    :bdnomecont,
    :bdcrccont,
    :bdsiglaufcont,
    :bdcpfcont,
    :bddddcont,
    :bdfonecont,
    :bddddfaxcont,
    :bdfaxcont,
    :bdemailcont;

  wsql = ' select ger.bdcodemp, tri.bdtrimestre, reg.bdnumcampo, reg.bdcodqirlp, sum(reg.bdvalor) bdvalor ';
  wsql = wsql||' from (select ger.bdcodemp, ger.bdcodperiodo, ger.bdreferencia, ger.bdcodconfirlp from vef_emp_tirlpger ger where ger.bdcodperiodo in (8,10) and ger.bdcodemp = '|| bdcodemp ||'and ger.bdreferencia >= '|| prrefini ||' and ger.bdreferencia <= '|| prreffin ||' order by ger.bdreferencia) ger ';
  wsql = wsql||' left outer join vef_emp_tirlpgerreg reg on reg.bdcodemp = ger.bdcodemp and reg.bdcodperiodo = ger.bdcodperiodo and reg.bdreferencia = ger.bdreferencia ';
  wsql = wsql||' left outer join vef_base_tconfirlpform frm on frm.bdcodconfirlp = ger.bdcodconfirlp and frm.bdcodqirlp = reg.bdcodqirlp and frm.bdnumcampoirlp = reg.bdnumcampo ';
  wsql = wsql||' left outer join sp_ref_trimestre(reg.bdreferencia) tri on tri.bdref = reg.bdreferencia ';
  --wsql = wsql||' where reg.bdnumcampo in (1,2,3,4,5,9,11,14,16,19,21,22,27,29) ';
  wsql = wsql||' where reg.bdnumcampo in (1,2,3,4,5,7,8,9,10,11,14) ';
  wsql = wsql||' group by bdcodemp, bdtrimestre, bdnumcampo, bdcodqirlp ';

  wSeqReg = 0;
  wulttrimestre = 0;
  bdvlrrecbru1_6_irlp      = 0;
  bdvlrrecbru8_irlp        = 0;
  bdvlrrecbru16_irlp       = 0;
  bdvlrrecbru32_irlp       = 0;
  bdvlrrecbru32_csll       = 0;
  bdvlrlucropresumido_irlp = 0;
  bdvlradicional_irlp      = 0;
  bdvlraliq15_irlp         = 0;
  bdvlrimpostopagar_irlp   = 0;
  bdvlrimpostoretido_irlp  = 0;
  bdvlrcsllapagar_irlp     = 0;
  bdvlrrecbru12_irlp       = 0;
  bdvlrrecbruajust_irlp    = 0;
  bdvlrcsllapurada_irlp    = 0;
  bdvlrcsllretpj           = 0;

  FOR EXECUTE STATEMENT wsql
    INTO
      :bdcodemp,
      :bdtrimestre,
      :wnumitem,
      :wcodqirlp,
      :wvalorirlpger
  DO
  BEGIN
    IF ((wulttrimestre IS NOT NULL) AND (wulttrimestre > 0) AND (wulttrimestre <> bdtrimestre)) THEN
      BEGIN
        wtrimestreaux = bdtrimestre;
        bdtrimestre = wulttrimestre;
        SUSPEND;
        bdtrimestre = wtrimestreaux;
        wultreferencia = wulttrimestre;
        bdvlrrecbru1_6_irlp      = 0;
        bdvlrrecbru8_irlp        = 0;
        bdvlrrecbru16_irlp       = 0;
        bdvlrrecbru32_irlp       = 0;
        bdvlrrecbru32_csll       = 0;
        bdvlrlucropresumido_irlp = 0;
        bdvlradicional_irlp      = 0;
        bdvlraliq15_irlp         = 0;
        bdvlrimpostopagar_irlp   = 0;
        bdvlrimpostoretido_irlp  = 0;


        bdvlrrecbru12_irlp       = 0;
        bdvlrrecbruajust_irlp    = 0;
        bdvlrcsllapurada_irlp    = 0;
        bdvlrcsllretpj           = 0;
        bdvlrcsllapagar_irlp     = 0;
      END

    IF ((:wnumitem = 1) AND (:wcodqirlp = 2)) THEN
      bdvlrrecbru1_6_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 2) AND (:wcodqirlp = 2)) THEN
      bdvlrrecbru8_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 3) AND (:wcodqirlp = 2)) THEN
      bdvlrrecbru16_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 4) AND (:wcodqirlp = 2)) THEN
      bdvlrrecbru32_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 5) AND (:wcodqirlp = 2)) THEN
      bdvlrlucropresumido_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 9) AND (:wcodqirlp = 2)) THEN
      BEGIN
        bdvlrimpostopagar_irlp = wvalorirlpger;
        bdvlraliq15_irlp = wvalorirlpger;
      END
    ELSE IF ((:wnumitem = 11) AND (:wcodqirlp = 2)) THEN
      bdvlradicional_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 14) AND (:wcodqirlp = 2)) THEN
      bdvlrimpostoretido_irlp = wvalorirlpger;

    /*sol:7885
    else if (:wnumitem = 29) then
       bdvlrrecbru12_irlp = wvalorirlpger;
    else if (:wnumitem = 27) then
      bdvlrrecbruajust_irlp = wvalorirlpger;
    else if (:wnumitem = 19) then
      bdvlrcsllapurada_irlp = wvalorirlpger;
    else if (:wnumitem = 21) then
      bdvlrcsllretpj = wvalorirlpger;
    else if (:wnumitem = 22) then
      bdvlrcsllapagar_irlp = wvalorirlpger;*/

    ELSE IF ((:wnumitem = 1) AND (:wcodqirlp = 3))  THEN
       bdvlrrecbru12_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 2) AND (:wcodqirlp = 3)) THEN
      bdvlrrecbru32_csll = wvalorirlpger;
    ELSE IF ((:wnumitem = 3) AND (:wcodqirlp = 3)) THEN
      bdvlrrecbruajust_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 7) AND (:wcodqirlp = 3)) THEN
      bdvlrcsllapurada_irlp = wvalorirlpger;
    ELSE IF ((:wnumitem = 8) AND (:wcodqirlp = 3)) THEN
      bdvlrcsllretpj = wvalorirlpger;
    ELSE IF ((:wnumitem = 10) AND (:wcodqirlp = 3)) THEN
      bdvlrcsllapagar_irlp = wvalorirlpger;

    wulttrimestre = bdtrimestre;
  END

  IF ((bdtrimestre > wultreferencia) OR ((wultreferencia IS NULL) AND (bdtrimestre > 0))) THEN
    SUSPEND;

/*$$IBEC$$    for execute statement wsql
     into
       :bdcodemp,
       :bdcnpjemp,
       :bdnomemp,
       :bdcodnatjur,
       :bdcodcnae,
       :bdlogremp,
       :bdendemp,
       :bdnumemp,
       :bdcomplemp,
       :bdbaiemp,
       :bdsiglaufemp,
       :bdcodcidemp,
       :bdcepemp,
       :bddddemp,
       :bdfoneemp,
       :bddddfaxemp,
       :bdfaxemp,
       :bdemailemp,
       :bdnomsoc,
       :bdcgcceisoc,
       :bddddsoc,
       :bdtelressoc,
       :bddddfaxsoc,
       :bdfaxsoc,
       :bdcgcceisoc,
       :bdemailsoc,
       :bdcodcont,
       :bdnomecont,
       :bdcrccont,
       :bdsiglaufcont,
       :bdcpfcont,
       :bddddcont,
       :bdfonecont,
       :bddddfaxcont,
       :bdfaxcont,
       :bdemailcont,
       :wnumitem,
       :bdReferencia,
       :wvalorirlpger
     do
     begin
        wref = cast(substring(bdreferencia from 5 for 2) as integer);

--       if ((wultreferencia <> bdreferencia) and (wSeqReg <> 1)) then
        if ((wulttrimestre <> 0) and (wulttrimestre <> bdtrimestre) and (wseqreg <> 1)) then
          begin
            if (bdtrimestre is not null) then
              begin
                suspend;
                bdvlrrecbru1_6_irlp      = 0;
                bdvlrrecbru8_irlp        = 0;
                bdvlrrecbru16_irlp       = 0;
                bdvlrrecbru32_irlp       = 0;
                bdvlrrecbru32_irlp       = 0;
                bdvlrlucropresumido_irlp = 0;
                bdvlradicional_irlp      = 0;
                bdvlraliq15_irlp         = 0;
                bdvlrimpostopagar_irlp   = 0;
                bdvlrimpostoretido_irlp  = 0;
                bdvlrcsllapagar_irlp     = 0;
                bdvlrrecbru12_irlp       = 0;
                bdvlrrecbruajust_irlp    = 0;
                bdvlrcsllapurada_irlp    = 0;
                bdvlrcsllretpj           = 0;
              end
          end

       if (wref <= 3) then
          bdtrimestre = 1;
       else
       if (wref <= 6) then
          bdtrimestre = 2;
       else
       if (wref <= 9) then
          bdtrimestre = 3;
       else
       if (wref <= 12) then
          bdtrimestre = 4;

       if (wref is not null) then
          begin
            wSeqReg = wSeqReg + 1;
            wulttrimestre = bdtrimestre;
          end

       if (:wnumitem = 1) then
          bdvlrrecbru1_6_irlp = bdvlrrecbru1_6_irlp + wvalorirlpger;
       else
       if (:wnumitem = 2) then
          bdvlrrecbru8_irlp = bdvlrrecbru8_irlp + wvalorirlpger;
       else
       if (:wnumitem = 3) then
          bdvlrrecbru16_irlp = bdvlrrecbru16_irlp + wvalorirlpger;
       if (:wnumitem = 4) then
          bdvlrrecbru32_irlp = bdvlrrecbru32_irlp + wvalorirlpger;
       else
       if (:wnumitem = 5) then
          bdvlrlucropresumido_irlp = bdvlrlucropresumido_irlp + wvalorirlpger;
       else
       if (:wnumitem = 9) then
          begin
            bdvlrimpostopagar_irlp = bdvlrimpostopagar_irlp + wvalorirlpger;
            bdvlraliq15_irlp       = bdvlraliq15_irlp + wvalorirlpger;
          end
       else
       if (:wnumitem = 11) then
          bdvlradicional_irlp = bdvlradicional_irlp + wvalorirlpger;
       else
       if (:wnumitem = 14) then
          bdvlrimpostoretido_irlp = bdvlrimpostoretido_irlp + wvalorirlpger;
       else
       if (:wnumitem = 24) then
          bdvlrcsllapagar_irlp = bdvlrcsllapagar_irlp + wvalorirlpger;

       wultreferencia = BDREFERENCIA;
     end $$IBEC$$*/
END
^

/* Restore proc. body: VEF_SP_EXP_DIPJ_REG1_3 */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG1_3(PREMPRESAS VARCHAR(10000),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDNOMEMP DM_BDNOMEMP,
BDCODNATJUR INTEGER,
BDCODCNAE INTEGER,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDSIGLAUFEMP VARCHAR(2),
BDCODCIDEMP INTEGER,
BDCEPEMP VARCHAR(9),
BDDDDEMP INTEGER,
BDFONEEMP DM_BDTELEFONE,
BDDDDFAXEMP INTEGER,
BDFAXEMP DM_BDTELEFONE,
BDEMAILEMP DM_BDEMAIL,
BDNOMSOC VARCHAR(80),
BDDDDSOC INTEGER,
BDTELRESSOC VARCHAR(15),
BDDDDFAXSOC INTEGER,
BDFAXSOC VARCHAR(9),
BDCGCCEISOC VARCHAR(18),
BDEMAILSOC DM_BDEMAIL,
BDCODCONT INTEGER,
BDNOMECONT VARCHAR(40),
BDCRCCONT VARCHAR(15),
BDSIGLAUFCONT VARCHAR(2),
BDCPFCONT VARCHAR(14),
BDDDDCONT INTEGER,
BDFONECONT DM_BDTELEFONE,
BDDDDFAXCONT INTEGER,
BDFAXCONT DM_BDTELEFONE,
BDEMAILCONT DM_BDEMAIL,
BDVLRRECBRU1_6_IRLP NUMERIC(15,6),
BDVLRRECBRU8_IRLP NUMERIC(15,6),
BDVLRRECBRU16_IRLP NUMERIC(15,6),
BDVLRRECBRU32_IRLP NUMERIC(15,6),
BDVLRLUCROPRESUMIDO_IRLP NUMERIC(15,6),
BDVLRADICIONAL_IRLP NUMERIC(15,6),
BDVLRIMPOSTOPAGAR_IRLP NUMERIC(15,6),
BDVLRIMPOSTORETIDO_IRLP NUMERIC(15,6),
BDVLRALIQ15_IRLP NUMERIC(15,6),
BDVLRCSLLAPAGAR_IRLP NUMERIC(15,6),
BDVLRRECBRU12_IRLP NUMERIC(15,6),
BDVLRRECBRUAJUST_IRLP NUMERIC(15,6),
BDVLRCSLLAPURADA_IRLP NUMERIC(15,6),
BDVLRCSLLRETPJ NUMERIC(15,6),
BDREFERENCIA INTEGER,
BDTRIMESTRE INTEGER)
 AS
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
BEGIN
    EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);
  
/*$$IBEC$$     wSql = 'select temp.bdcodemp, ';
    wSql = wSql || 'temp.bdcnpjemp, ';
    wSql = wSql || 'trefemp.bdnomemp, ';
    wSql = wSql || 'trefemp.bdcodnatjur, ';
    wSql = wSql || 'trefemp.bdcodcnae, ';
    wSql = wSql || 'trefemp.bdlogremp, ';
    wSql = wSql || 'trefemp.bdendemp, ';
    wSql = wSql || 'trefemp.bdnumemp, ';
    wSql = wSql || 'trefemp.bdcomplemp, ';
    wSql = wSql || 'trefemp.bdbaiemp, ';
    wSql = wSql || 'tufemp.bdsiglauf, ';
    wSql = wSql || 'tcidemp.bdcodfed, ';
    wSql = wSql || 'trefemp.bdcepemp, ';
    wSql = wSql || 'trefemp.bddddemp, ';
    wSql = wSql || 'trefemp.bdfoneemp, ';
    wSql = wSql || 'trefemp.bddddfaxemp, ';
    wSql = wSql || 'trefemp.bdfaxemp, ';
    wSql = wSql || 'trefemp.bdemailemp, ';
    wSql = wSql || 'tsoc.bdnomsoc, ';
    wSql = wSql || 'tsoc.bdcgcceisoc, ';
    wSql = wSql || 'tsoc.bdddsoc, ';
    wSql = wSql || 'tsoc.bdtelressoc, ';
    wSql = wSql || 'tsoc.bddddfaxsoc, ';
    wSql = wSql || 'tsoc.bdfaxsoc, ';
    wSql = wSql || 'tsoc.bdcgcceisoc, ';
    wSql = wSql || 'tsoc.bdemailsoc, ';
    wSql = wSql || 'tcon.bdcodcont, ';
    wSql = wSql || 'tcon.bdnomecont, ';
    wSql = wSql || 'tcon.bdcrccont, ';
    wSql = wSql || 'tufcont.bdsiglauf, ';
    wSql = wSql || 'tcon.bdcpfcont, ';
    wSql = wSql || 'tcon.bddddcont, ';
    wSql = wSql || 'tcon.bdfonecont, ';
    wSql = wSql || 'tcon.bddddfaxcont, ';
    wSql = wSql || 'tcon.bdfaxcont, ';
    wSql = wSql || 'tcon.bdemailcont, ';
    wSql = wSql || 'tconfirlpform.bdnumitem, ';
    wSql = wSql || 'tirlpgerreg.bdReferencia, ';
    wSql = wSql || 'tirlpgerreg.bdvalor ';
    wSql = wSql || 'from TEMPRESAS temp ';
    wSql = wSql || 'left outer join vw_tempresas_ref trefemp on (trefemp.bdCODEMP = temp.bdCODEMP) ';
    wSql = wSql || 'left outer join tcidade tcidemp on (tcidemp.bdcodcid = trefemp.bdcodcid) ';
    wSql = wSql || 'left outer join tuf tufemp on (tufemp.bdcoduf = tcidemp.bdcoduf) ';
    wSql = wSql || 'left outer join TCONTADOR_PADRAO tcon on (tcon.BDCODCONT = trefemp.BDCODCONT) ';
    wSql = wSql || 'left outer join tcidade tcidcont on (tcidcont.bdcodcid = tcon.bdcodcid) ';
    wSql = wSql || 'left outer join tuf tufcont on (tufcont.bdcoduf = tcidcont.bdcoduf) ';
    wSql = wSql || 'left outer join VW_EMPRESAS_TSOC_REF tsoc on (tsoc.bdcodemp = temp.bdcodemp and upper(tsoc.bdresponsavelsoc) = '''||'TRUE'||''') ';
    wSql = wSql || 'left outer join VEF_EMP_TIRLPGER tirlpger on (tirlpger.bdcodperiodo in (8,9,10) and tirlpger.bdcodemp = temp.bdcodemp) and
                                                                  tirlpger.bdREFERENCIA >= '||prrefini||' and '||'tirlpger.bdREFERENCIA <= '||prreffin||' ';
    wSql = wSql || 'left outer join vef_emp_tirlpgerreg tirlpgerreg on (tirlpgerreg.bdcodemp = tirlpger.bdcodemp and tirlpgerreg.bdcodperiodo = tirlpger.bdcodperiodo and
                                                                        tirlpgerreg.bdreferencia = tirlpger.bdreferencia) ';
    wSql = wSql || 'left outer join vef_base_tconfirlpform tconfirlpform on tconfirlpform.bdcodconfirlp = tirlpger.bdcodconfirlp and tconfirlpform.bdcodqirlp = tirlpgerreg.bdcodqirlp and tconfirlpform.bdnumcampoirlp = tirlpgerreg.bdnumcampo '; $$IBEC$$*/

  wsql = ' select first 1 temp.bdcodemp, temp.bdcnpjemp, trefemp.bdnomemp, trefemp.bdcodnatjur, ';
  wsql = wsql||'          trefemp.bdcodcnae, trefemp.bdlogremp, trefemp.bdendemp, trefemp.bdnumemp, ';
  wsql = wsql||'          trefemp.bdcomplemp, trefemp.bdbaiemp, tufemp.bdsiglauf, tcidemp.bdcodfed, ';
  wsql = wsql||'          trefemp.bdcepemp, trefemp.bddddemp, trefemp.bdfoneemp, trefemp.bddddfaxemp, ';
  wsql = wsql||'          trefemp.bdfaxemp, trefemp.bdemailemp, tsoc.bdnomsoc, tsoc.bdcgcceisoc, ';
  wsql = wsql||'          tsoc.bddddsoc, tsoc.bdtelressoc, tsoc.bddddfaxsoc, tsoc.bdfaxsoc, ';
  wsql = wsql||'          tsoc.bdcgcceisoc, tsoc.bdemailsoc, tcon.bdcodcont, tcon.bdnomecont, ';
  wsql = wsql||'          tcon.bdcrccont, tufcont.bdsiglauf, tcon.bdcpfcont, tcon.bddddcont, ';
  wsql = wsql||'          tcon.bdfonecont, tcon.bddddfaxcont, tcon.bdfaxcont, tcon.bdemailcont ';
  wsql = wsql||'   from TEMPRESAS temp ';
  wsql = wsql||'   left outer join vw_tempresas_ref trefemp on (trefemp.bdCODEMP = temp.bdCODEMP) ';
  wsql = wsql||'   left outer join tcidade tcidemp on (tcidemp.bdcodcid = trefemp.bdcodcid) ';
  wsql = wsql||'   left outer join tuf tufemp on (tufemp.bdcoduf = tcidemp.bdcoduf) ';
  wsql = wsql||'   left outer join TCONTADOR_PADRAO tcon on (tcon.BDCODCONT = trefemp.BDCODCONT) ';
  wsql = wsql||'   left outer join tcidade tcidcont on (tcidcont.bdcodcid = tcon.bdcodcid) ';
  wsql = wsql||'   left outer join tuf tufcont on (tufcont.bdcoduf = tcidcont.bdcoduf) ';
  wsql = wsql||'   left outer join VW_EMPRESAS_TSOC_REF tsoc on (tsoc.bdcodemp = temp.bdcodemp and upper(tsoc.bdresponsavelsoc) = ''TRUE'') ';

  wwhere = '';
  
  IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
    wwhere = wWhere||'('||prempresas||') ';
  
  IF (wwhere <> '') THEN
    wwhere = 'where '||wwhere||' ';
  
  /*definir na aplicação*/
--  worderby = 'order by bdcodemp, bdreferencia ';

  wsql = wsql||wwhere;--||worderby;

  EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :bdcnpjemp,
    :bdnomemp,
    :bdcodnatjur,
    :bdcodcnae,
    :bdlogremp,
    :bdendemp,
    :bdnumemp,
    :bdcomplemp,
    :bdbaiemp,
    :bdsiglaufemp,
    :bdcodcidemp,
    :bdcepemp,
    :bddddemp,
    :bdfoneemp,
    :bddddfaxemp,
    :bdfaxemp,
    :bdemailemp,
    :bdnomsoc,
    :bdcgcceisoc,
    :bddddsoc,
    :bdtelressoc,
    :bddddfaxsoc,
    :bdfaxsoc,
    :bdcgcceisoc,
    :bdemailsoc,
    :bdcodcont,
    :bdnomecont,
    :bdcrccont,
    :bdsiglaufcont,
    :bdcpfcont,
    :bddddcont,
    :bdfonecont,
    :bddddfaxcont,
    :bdfaxcont,
    :bdemailcont;

  /*wsql = ' select ger.bdcodemp, tri.bdtrimestre, reg.bdnumcampo, sum(reg.bdvalor) bdvalor ';
  wsql = wsql||' from (select ger.bdcodemp, ger.bdcodperiodo, ger.bdreferencia, ger.bdcodconfirlp from vef_emp_tirlpger ger where ger.bdcodperiodo in (8,10) and ger.bdcodemp = '|| bdcodemp ||'and ger.bdreferencia >= '|| prrefini ||' and ger.bdreferencia <= '|| prreffin ||' order by ger.bdreferencia) ger ';
  wsql = wsql||' left outer join vef_emp_tirlpgerreg reg on reg.bdcodemp = ger.bdcodemp and reg.bdcodperiodo = ger.bdcodperiodo and reg.bdreferencia = ger.bdreferencia ';
  wsql = wsql||' left outer join vef_base_tconfirlpform frm on frm.bdcodconfirlp = ger.bdcodconfirlp and frm.bdcodqirlp = reg.bdcodqirlp and frm.bdnumcampoirlp = reg.bdnumcampo ';
  wsql = wsql||' left outer join sp_ref_trimestre(reg.bdreferencia) tri on tri.bdref = reg.bdreferencia ';
  wsql = wsql||' where reg.bdnumcampo in (1,2,3,4,5,9,11,14,16,19,21,22,27,29) ';
  wsql = wsql||' group by bdcodemp, bdtrimestre, bdnumcampo ';

  wSeqReg = 0;
  wulttrimestre = 0;
  bdvlrrecbru1_6_irlp      = 0;
  bdvlrrecbru8_irlp        = 0;
  bdvlrrecbru16_irlp       = 0;
  bdvlrrecbru32_irlp       = 0;
  bdvlrrecbru32_irlp       = 0;
  bdvlrlucropresumido_irlp = 0;
  bdvlradicional_irlp      = 0;
  bdvlraliq15_irlp         = 0;
  bdvlrimpostopagar_irlp   = 0;
  bdvlrimpostoretido_irlp  = 0;
  bdvlrcsllapagar_irlp     = 0;
  bdvlrrecbru12_irlp       = 0;
  bdvlrrecbruajust_irlp    = 0;
  bdvlrcsllapurada_irlp    = 0;
  bdvlrcsllretpj           = 0;

  for execute statement wsql
    into
      :bdcodemp,
      :bdtrimestre,
      :wnumitem,
      :wvalorirlpger
  do
  begin
    if ((wulttrimestre is not null) and (wulttrimestre > 0) and (wulttrimestre <> bdtrimestre)) then
      begin
        wtrimestreaux = bdtrimestre;
        bdtrimestre = wulttrimestre;
        suspend;
        bdtrimestre = wtrimestreaux;
        wultreferencia = wulttrimestre;
        bdvlrrecbru1_6_irlp      = 0;
        bdvlrrecbru8_irlp        = 0;
        bdvlrrecbru16_irlp       = 0;
        bdvlrrecbru32_irlp       = 0;
        bdvlrrecbru32_irlp       = 0;
        bdvlrlucropresumido_irlp = 0;
        bdvlradicional_irlp      = 0;
        bdvlraliq15_irlp         = 0;
        bdvlrimpostopagar_irlp   = 0;
        bdvlrimpostoretido_irlp  = 0;


        bdvlrrecbru12_irlp       = 0;
        bdvlrrecbruajust_irlp    = 0;
        bdvlrcsllapurada_irlp    = 0;
        bdvlrcsllretpj           = 0;
        bdvlrcsllapagar_irlp     = 0;
      end

    if (:wnumitem = 1) then
      bdvlrrecbru1_6_irlp = wvalorirlpger;
    else if (:wnumitem = 2) then
      bdvlrrecbru8_irlp = wvalorirlpger;
    else if (:wnumitem = 3) then
      bdvlrrecbru16_irlp = wvalorirlpger;
    else if (:wnumitem = 4) then
      bdvlrrecbru32_irlp = wvalorirlpger;
    else if (:wnumitem = 5) then
      bdvlrlucropresumido_irlp = wvalorirlpger;
    else if (:wnumitem = 9) then
      begin
        bdvlrimpostopagar_irlp = wvalorirlpger;
        bdvlraliq15_irlp = wvalorirlpger;
      end
    else if (:wnumitem = 11) then
      bdvlradicional_irlp = wvalorirlpger;
    else if (:wnumitem = 14) then
      bdvlrimpostoretido_irlp = wvalorirlpger;


    else if (:wnumitem = 29) then
       bdvlrrecbru12_irlp = wvalorirlpger;
    else if (:wnumitem = 27) then
      bdvlrrecbruajust_irlp = wvalorirlpger;
    else if (:wnumitem = 19) then
      bdvlrcsllapurada_irlp = wvalorirlpger;
    else if (:wnumitem = 21) then
      bdvlrcsllretpj = wvalorirlpger;
    else if (:wnumitem = 22) then
      bdvlrcsllapagar_irlp = wvalorirlpger;

    wulttrimestre = bdtrimestre;
  end

  if (bdtrimestre > wultreferencia) then*/
    SUSPEND;

/*$$IBEC$$    for execute statement wsql
     into
       :bdcodemp,
       :bdcnpjemp,
       :bdnomemp,
       :bdcodnatjur,
       :bdcodcnae,
       :bdlogremp,
       :bdendemp,
       :bdnumemp,
       :bdcomplemp,
       :bdbaiemp,
       :bdsiglaufemp,
       :bdcodcidemp,
       :bdcepemp,
       :bddddemp,
       :bdfoneemp,
       :bddddfaxemp,
       :bdfaxemp,
       :bdemailemp,
       :bdnomsoc,
       :bdcgcceisoc,
       :bddddsoc,
       :bdtelressoc,
       :bddddfaxsoc,
       :bdfaxsoc,
       :bdcgcceisoc,
       :bdemailsoc,
       :bdcodcont,
       :bdnomecont,
       :bdcrccont,
       :bdsiglaufcont,
       :bdcpfcont,
       :bddddcont,
       :bdfonecont,
       :bddddfaxcont,
       :bdfaxcont,
       :bdemailcont,
       :wnumitem,
       :bdReferencia,
       :wvalorirlpger
     do
     begin
        wref = cast(substring(bdreferencia from 5 for 2) as integer);

--       if ((wultreferencia <> bdreferencia) and (wSeqReg <> 1)) then
        if ((wulttrimestre <> 0) and (wulttrimestre <> bdtrimestre) and (wseqreg <> 1)) then
          begin
            if (bdtrimestre is not null) then
              begin
                suspend;
                bdvlrrecbru1_6_irlp      = 0;
                bdvlrrecbru8_irlp        = 0;
                bdvlrrecbru16_irlp       = 0;
                bdvlrrecbru32_irlp       = 0;
                bdvlrrecbru32_irlp       = 0;
                bdvlrlucropresumido_irlp = 0;
                bdvlradicional_irlp      = 0;
                bdvlraliq15_irlp         = 0;
                bdvlrimpostopagar_irlp   = 0;
                bdvlrimpostoretido_irlp  = 0;
                bdvlrcsllapagar_irlp     = 0;
                bdvlrrecbru12_irlp       = 0;
                bdvlrrecbruajust_irlp    = 0;
                bdvlrcsllapurada_irlp    = 0;
                bdvlrcsllretpj           = 0;
              end
          end

       if (wref <= 3) then
          bdtrimestre = 1;
       else
       if (wref <= 6) then
          bdtrimestre = 2;
       else
       if (wref <= 9) then
          bdtrimestre = 3;
       else
       if (wref <= 12) then
          bdtrimestre = 4;

       if (wref is not null) then
          begin
            wSeqReg = wSeqReg + 1;
            wulttrimestre = bdtrimestre;
          end

       if (:wnumitem = 1) then
          bdvlrrecbru1_6_irlp = bdvlrrecbru1_6_irlp + wvalorirlpger;
       else
       if (:wnumitem = 2) then
          bdvlrrecbru8_irlp = bdvlrrecbru8_irlp + wvalorirlpger;
       else
       if (:wnumitem = 3) then
          bdvlrrecbru16_irlp = bdvlrrecbru16_irlp + wvalorirlpger;
       if (:wnumitem = 4) then
          bdvlrrecbru32_irlp = bdvlrrecbru32_irlp + wvalorirlpger;
       else
       if (:wnumitem = 5) then
          bdvlrlucropresumido_irlp = bdvlrlucropresumido_irlp + wvalorirlpger;
       else
       if (:wnumitem = 9) then
          begin
            bdvlrimpostopagar_irlp = bdvlrimpostopagar_irlp + wvalorirlpger;
            bdvlraliq15_irlp       = bdvlraliq15_irlp + wvalorirlpger;
          end
       else
       if (:wnumitem = 11) then
          bdvlradicional_irlp = bdvlradicional_irlp + wvalorirlpger;
       else
       if (:wnumitem = 14) then
          bdvlrimpostoretido_irlp = bdvlrimpostoretido_irlp + wvalorirlpger;
       else
       if (:wnumitem = 24) then
          bdvlrcsllapagar_irlp = bdvlrcsllapagar_irlp + wvalorirlpger;

       wultreferencia = BDREFERENCIA;
     end $$IBEC$$*/
END
^

/* Restore proc. body: VEF_SP_EXP_DIPJ_REG19 */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG19(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18))
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL SMALLINT)
 AS
DECLARE VARIABLE worderby VARCHAR(5000);
DECLARE VARIABLE wwhere VARCHAR(5000);
DECLARE VARIABLE wsql VARCHAR(25000);
DECLARE VARIABLE wcnpjemp VARCHAR(18);
BEGIN
   wSql = 'select bdcodemp, ';
   wSql = wSql || 'bdcnpjemp ';
   wSql = wSql || 'from tempresas temp ';

   wwhere = '';
  
   IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
      wwhere = wWhere||'('||prempresas||') ';
 
   IF (wWhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   /*definir na aplicação*/
   worderby = 'order by bdcodemp ';

   wsql = wsql||wwhere||worderby;
 
   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :wcnpjemp
     DO
     BEGIN
        bdcnpjempmatriz = prcnpjmatriz;
        bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);

        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;
        SUSPEND;
     END
END
^

/* Restore proc. body: VEF_SP_EXP_DIPJ_REG20 */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG20(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDEXISTEMOV INTEGER,
BDPERIODO INTEGER,
BDMES INTEGER,
BDVLRSALDOCREANT NUMERIC(15,6),
BDVLRDEBITO NUMERIC(15,6),
BDVLRCREDITO NUMERIC(15,6),
BDVLRSALDO NUMERIC(15,6),
BDCREDORDEVEDOR INTEGER,
BDSEQUENCIAL INTEGER,
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18))
 AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
DECLARE VARIABLE WNUMITEM INTEGER;
DECLARE VARIABLE WULTREFERENCIA INTEGER;
DECLARE VARIABLE WULTCODPERIODO INTEGER;
DECLARE VARIABLE WCODPERIODO INTEGER;
DECLARE VARIABLE WVLRIPIGER NUMERIC(15,6);
DECLARE VARIABLE WSEQREG INTEGER;
DECLARE VARIABLE WVLRNUMITEM13 NUMERIC(15,6);
DECLARE VARIABLE WVLRNUMITEM14 NUMERIC(15,2);
DECLARE VARIABLE WVLRNUMITEM01 NUMERIC(15,6);
DECLARE VARIABLE WVLRNUMITEM06 NUMERIC(15,6);
DECLARE VARIABLE WVLRNUMITEM09 NUMERIC(15,6);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
BEGIN
    EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

    
    wSql = 'select temp.bdcodemp, ';
    wSql = wSql || 'temp.bdcnpjemp, ';
    wSql = wSql || 'tconfipiform.bdnumitem, ';
    wSql = wSql || 'tipigerreg.bdcodperiodo, ';
    wSql = wSql || 'tipigerreg.bdReferencia, ';
    wSql = wSql || 'tipigerreg.bdvalor ';
    wSql = wSql || 'from TEMPRESAS temp ';
    wSql = wSql || 'left outer join vef_emp_tipiger tipiger on (tipiger.bdcodemp = temp.bdcodemp and tipiger.bdREFERENCIA >= '||prrefini||' and tipiger.bdREFERENCIA <= '||prreffin||') ';
    wSql = wSql || 'left outer join vef_emp_tipigerreg tipigerreg on (tipigerreg.bdcodemp = tipiger.bdcodemp and tipigerreg.bdcodperiodo = tipiger.bdcodperiodo and
                                                                      tipigerreg.bdreferencia = tipiger.bdreferencia) ';
    wSql = wSQl || 'left outer join vef_base_tconfipiform tconfipiform on (tconfipiform.bdcodconfipi  = tipiger.bdcodconfipi and tconfipiform.bdcodqipi = tipigerreg.bdcodqipi and
                                                           tconfipiform.bdnumcampoipi = tipigerreg.bdnumcampo) ';

    wwhere = '';
  
    IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
       wwhere = wWhere||'('||prempresas||') ';
  
    IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

    worderby = 'order by temp.bdcodemp, bdreferencia, bdcodperiodo, bdnumitem ';

    wsql = wsql||wwhere||worderby;


     wSeqReg = 0;
     bdsequencial = 0;

    FOR EXECUTE STATEMENT wsql
     INTO
        :bdcodemp,
        :wcnpjemp,
        :wnumitem,
        :wcodperiodo,
        :bdreferencia,
        :wvlripiger
     DO
     BEGIN
     IF (((wultreferencia <> bdreferencia) OR (wultcodperiodo <> wcodperiodo)) AND (wSeqReg <> 1)) THEN
          BEGIN
            IF (wvlrnumitem13 > 0) THEN
               bdvlrsaldo = wvlrnumitem13;
            ELSE
               bdvlrsaldo = wvlrnumitem14;

            IF (wvlrnumitem01 > wvlrnumitem06) THEN
               bdcredordevedor = 2;
            ELSE
               bdcredordevedor = 1;

            --if ((wvlrnumitem09 - wvlrnumitem14) = 0) then
            IF ((bdvlrdebito = 0) AND (bdvlrcredito = 0)) THEN
               bdexistemov = 2;
            ELSE
               bdexistemov = 1;
            bdsequencial = bdsequencial + 1;
            SUSPEND;
            BDVLRSALDOCREANT = 0;
            BDVLRDEBITO      = 0;
            BDVLRCREDITO     = 0;
            BDVLRSALDO       = 0;
            BDCREDORDEVEDOR  = 0;
            wvlrnumitem01    = 0;
            wvlrnumitem06    = 0;
            wvlrnumitem13    = 0;
            wvlrnumitem14    = 0;
            wvlrnumitem09    = 0;
          END

       wSeqReg          = wSeqReg + 1;

       bdmes = (SUBSTRING(bdreferencia FROM 5 FOR 2));
       bdcnpjempmatriz = prcnpjmatriz;
       bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);

        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;


       -- definição dos valores de saldos, débito e crédito
       IF (wnumitem = 5) THEN
          bdvlrdebito = wvlripiger;
       ELSE
       IF (wnumitem = 9) THEN
          BEGIN
            bdvlrsaldocreant = wvlripiger;
            --bdvlrcredito     = wvlripiger;
            wvlrnumitem09    = wvlripiger;
          END
       ELSE
       IF (wnumitem = 11) THEN
          bdvlrcredito = wvlripiger - bdvlrsaldocreant;
       ELSE
       IF (wnumitem = 1) THEN
          wvlrnumitem01  = wvlripiger;
       ELSE
       IF (wnumitem = 6) THEN
          wvlrnumitem06  = wvlripiger;
       ELSE
       IF (wnumitem = 13) THEN
          wvlrnumitem13  = wvlripiger;
       ELSE
       IF (wnumitem = 14) THEN
          wvlrnumitem14  = wvlripiger;

       -- definição do período
       IF (wcodperiodo = 7) THEN
           bdperiodo = 0;
       ELSE
       IF (wcodperiodo = 2) THEN
           bdperiodo = 1;
       ELSE
       IF (wcodperiodo = 3) THEN
           bdperiodo = 2;
       ELSE
       IF (wcodperiodo = 4) THEN
           bdperiodo = 3;
       wultreferencia = bdreferencia;
       wultcodperiodo = wcodperiodo;
     END

     -- último registro - suspend
     IF (wvlrnumitem13 > 0) THEN
        bdvlrsaldo = wvlrnumitem13;
     ELSE
        bdvlrsaldo = wvlrnumitem14;

     IF (wvlrnumitem01 > wvlrnumitem06) THEN
        bdcredordevedor = 2;
     ELSE
        bdcredordevedor = 1;

     --if ((wvlrnumitem09 - wvlrnumitem14) = 0) then
     IF ((bdvlrdebito = 0) AND (bdvlrcredito = 0)) THEN
        bdexistemov = 2;
     ELSE
        bdexistemov = 1;

     bdsequencial = bdsequencial + 1;

     SUSPEND;
END
^

/* Restore proc. body: VEF_SP_EXP_DIPJ_REG21 */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG21(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDVLRINSUMOSNACIONAL NUMERIC(15,6),
BDVLRMERCADORIASNACIONAL NUMERIC(15,6),
BDVLRINDUSTOUTRASEMPNACIONAL NUMERIC(15,6),
BDVLRDEVVENDASNACIONAL NUMERIC(15,6),
BDVLROUTRASENTNACIONAL NUMERIC(15,6),
BDVLRINSUMOSEXTERIOR NUMERIC(15,6),
BDVLRMERCADORIASEXTERIOR NUMERIC(15,6),
BDVLRDEVVENDASEXTERIOR NUMERIC(15,6),
BDVLROUTRASENTEXTERIOR NUMERIC(15,6),
BDCOLUNA INTEGER,
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL INTEGER)
 AS
DECLARE VARIABLE worderby VARCHAR(5000);
DECLARE VARIABLE wwhere VARCHAR(5000);
DECLARE VARIABLE wsql VARCHAR(25000);
DECLARE VARIABLE wgroupby VARCHAR(5000);
DECLARE VARIABLE wvlrcontab NUMERIC(15,6);
DECLARE VARIABLE wvlripi NUMERIC(15,6);
DECLARE VARIABLE woutrasipi NUMERIC(15,6);
DECLARE VARIABLE wisentasipi NUMERIC(15,6);
DECLARE VARIABLE wprefixonat INTEGER;
DECLARE VARIABLE wcnpjemp VARCHAR(18);
DECLARE VARIABLE i INTEGER;
BEGIN
   /*agrupar na aplicação desta forma. Exemplo
     select bdcodemp,
            bdtipomatrizfilial,
            bdcnpjempmatriz,
            bdcnpjestab,
            bdcoluna,
            sum(bdvlrinsumosnacional),
            sum(bdvlrmercadoriasnacional),
            sum(bdvlrindustoutrasempnacional),
            sum(bdvlrdevvendasnacional),
            sum(bdvlroutrasentnacional),
            sum(bdvlrinsumosexterior),
            sum(bdvlrmercadoriasexterior),
            sum(bdvlrindustoutrasempexterior),
            sum(bdvlrdevvendasexterior),
            sum(bdvlroutrasentexterior)
            from vef_sp_exp_dipj_reg21('tnatent.bdcodemp = 1 or tnatent.bdcodemp = 2','00.190.373/0001-72', '01/01/2010', '04/30/2010', 201011)
            group by bdcodemp, bdcnpjempmatriz, BDcnpjestab, bdcoluna
            order by bdtipomatrizfilial, bdcodemp, bdcoluna
   */

   --PREMPRESAS   - empresa matriz + filiias
   --PRCNPJMATRIZ - saber o CNP da matriz previamente para atribuir para todos registros, inclusive os das filiais

   EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

   wSql = 'select tnatent.bdcodemp, ';
   wSql = wSql || 'temp.bdcnpjemp, ';
   wSql = wSql || 'tnatent.bdprefixonat, ';
   wSql = wSql || 'sum(tnatent.bdvlrcontab)  bdvlrcontab, ';
   wSql = wSql || 'sum(tnatent.bdvlripi)     bdvlripi, ';
   wSql = wSql || 'sum(tnatent.bdoutrasipi)  bdoutrasipi, ';
   wSql = wSql || 'sum(tnatent.bdisentasipi) bdisentasipi ';
   wSql = wSql || 'from vw_vef_tot_nat_ent_date tnatent ';
   wSql = wSql || 'left outer join tempresas temp on (temp.bdcodemp = tnatent.bdcodemp) ';

   wwhere = '';
  
   IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
      wwhere = wWhere||'('||prempresas||') ';
 
   IF (prdataini IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatent.bddataentradaent >= '||''''||prdataini||''''||' ';
      END
 
   IF (prdatafin IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatent.bddataentradaent <= '||''''||prdatafin||''''||' ';
      END

   IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   wGroupBy = 'group by tnatent.bdcodemp, tnatent.bdprefixonat, temp.bdcnpjemp ';
   /*definir na aplicação*/
   worderby = '';

   wsql = wsql||wwhere||wgroupby||worderby;
 
   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :wcnpjemp,
       :wprefixonat,
       :wvlrcontab,
       :wvlripi,
       :woutrasipi,
       :wisentasipi
     DO
     BEGIN
        i = 1;
        bdcnpjempmatriz = prcnpjmatriz;
        bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);

        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;

        --carregar dados para cada uma das três colunas do registro
        WHILE (i <= 3) DO
          BEGIN
            bdcoluna = i;
            bdvlrinsumosnacional         = 0;
            bdvlrmercadoriasnacional     = 0;
            bdvlrindustoutrasempnacional = 0;
            bdvlrdevvendasnacional       = 0;
            bdvlroutrasentnacional       = 0;
            bdvlrinsumosexterior         = 0;
            bdvlrmercadoriasexterior     = 0;
            bdvlrdevvendasexterior       = 0;
            bdvlroutrasentexterior       = 0;

            IF (wprefixonat IN (1101, 1111, 1116, 1120, 1122, 1151, 1401, 1408, 2101, 2111, 2116, 2120, 2122, 2151, 2401, 2408)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrinsumosnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrinsumosnacional = wvlrcontab;
                  ELSE
                     bdvlrinsumosnacional = wvlripi;
               END

            IF (wprefixonat IN (1102, 1113, 1117, 1118, 1121, 1152, 1403, 1409, 2102, 2113, 2117, 2118, 2121, 2152, 2403, 2409)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrmercadoriasnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrmercadoriasnacional = wvlrcontab;
                  ELSE
                     bdvlrmercadoriasnacional = wvlripi;
               END

            IF (wprefixonat IN (1124, 1125, 2124, 2125)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrindustoutrasempnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrindustoutrasempnacional = wvlrcontab;
                  ELSE
                     bdvlrindustoutrasempnacional = wvlripi;
               END

            IF (wprefixonat IN (1201, 1202, 1203, 1204, 1208, 1209, 1410, 1411, 1918, 1919, 2201, 2202, 2203, 2204, 2208, 2209, 2410, 2411, 2918, 2919)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrdevvendasnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrdevvendasnacional = wvlrcontab;
                  ELSE
                     bdvlrdevvendasnacional = wvlripi;
               END

            IF (wprefixonat IN (1126, 1154, 1207, 1252, 1256, 1302, 1352, 1356, 1406, 1407, 1414, 1415, 1452, 1501, 1503, 1504, 1505, 1506, 1551, 1552, 1553, 1554, 1555,
                                1556, 1557, 1601, 1602, 1603, 1653, 1658, 1660, 1662, 1901, 1902, 1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1914,
                                1915, 1916, 1917, 1920, 1921, 1922, 1923, 1924, 1925, 1926, 1949, 2126, 2154, 2252, 2256, 2302, 2352, 2356, 2406, 2407, 2414, 2415, 2501,
                                2503, 2504, 2505, 2506, 2551, 2552, 2553, 2554, 2555, 2556, 2557, 2651, 2653, 2658, 2660, 2662, 2901, 2902, 2903, 2904, 2905, 2906, 2907,
                                2908, 2909, 2910, 2911, 2912, 2913, 2914, 2915, 2916, 2917, 2920, 2921, 2922, 2923, 2924, 2925, 2949)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlroutrasentnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlroutrasentnacional = wvlrcontab;
                  ELSE
                     bdvlroutrasentnacional = wvlripi;
               END

            IF (wprefixonat IN (3101, 3127)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrinsumosexterior = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrinsumosexterior = wvlrcontab;
                  ELSE
                     bdvlrinsumosexterior = wvlripi;
               END

            IF (wprefixonat IN (3102)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrmercadoriasexterior = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrmercadoriasexterior = wvlrcontab;
                  ELSE
                     bdvlrmercadoriasexterior = wvlripi;
               END

            IF (wprefixonat IN (3201, 3202, 3211, 3503, 3553)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrdevvendasexterior = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrdevvendasexterior = wvlrcontab;
                  ELSE
                     bdvlrdevvendasexterior = wvlripi;
               END

            IF (wprefixonat IN (3126, 3352, 3356, 3551, 3556, 3651, 3653, 3930, 3949)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlroutrasentexterior = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlroutrasentexterior = wvlrcontab;
                  ELSE
                     bdvlroutrasentexterior = wvlripi;
               END

            i = i + 1;
            SUSPEND;
          END
     END
END
^

/* Restore proc. body: VEF_SP_EXP_DIPJ_REG22 */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG22(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDVLRPRODNACIONAL NUMERIC(15,6),
BDVLRMERCADORIASNACIONAL NUMERIC(15,6),
BDVLRINDUSTOUTRASEMPNACIONAL NUMERIC(15,6),
BDVLRDEVCOMPRASNACIONAL NUMERIC(15,6),
BDVLROUTRASSAINACIONAL NUMERIC(15,6),
BDVLRPRODEXTERIOR NUMERIC(15,6),
BDVLRMERCADORIASEXTERIOR NUMERIC(15,6),
BDVLRINDUSTOUTRASEMPEXTERIOR NUMERIC(15,6),
BDVLRDEVCOMPRASEXTERIOR NUMERIC(15,6),
BDVLROUTRASSAIEXTERIOR NUMERIC(15,6),
BDCOLUNA INTEGER,
BDCNPJESTAB VARCHAR(7),
BDTIPOMATRIZFILIAL INTEGER)
 AS
DECLARE VARIABLE worderby VARCHAR(5000);
DECLARE VARIABLE wwhere VARCHAR(5000);
DECLARE VARIABLE wsql VARCHAR(25000);
DECLARE VARIABLE wgroupby VARCHAR(5000);
DECLARE VARIABLE wvlrcontab NUMERIC(15,6);
DECLARE VARIABLE wvlripi NUMERIC(15,6);
DECLARE VARIABLE woutrasipi NUMERIC(15,6);
DECLARE VARIABLE wisentasipi NUMERIC(15,6);
DECLARE VARIABLE wprefixonat INTEGER;
DECLARE VARIABLE wcnpjemp VARCHAR(18);
DECLARE VARIABLE i INTEGER;
BEGIN
   /* agrupar na aplicação desta forma. Exemplo:
     select bdcodemp,
       bdcnpjempmatriz,
       bdcnpjestab,
       bdcoluna,
       sum(bdvlrprodnacional) bdvlrprodnacional,
       sum(bdvlrmercadoriasnacional) bdvlrmercadoriasnacional,
       sum(bdvlrindustoutrasempnacional) bdvlrindustoutrasempnacional,
       sum(bdvlrdevcomprasnacional) bdvlrdevcomprasnacional,
       sum(bdvlroutrassainacional) bdvlroutrassainacional,
       sum(bdvlrprodexterior) bdvlrprodsexterior,
       sum(bdvlrmercadoriasexterior) bdvlrmercadoriasexterior,
       sum(bdvlrindustoutrasempexterior) bdvlrindustoutrasempexterior,
       sum(bdvlrdevcomprasexterior) bdvlrdevcomprasexterior,
       sum(bdvlroutrassaiexterior) bdvlroutrassaiexterior
       from vef_sp_exp_dipj_reg22('tnatsai.bdcodemp = 1 or tnatsai.bdcodemp = 2','00.190.373/0001-72', '01/01/2010', '12/31/2010', 201011)
       group by bdcodemp, bdcnpjempmatriz, bdcnpjestab, bdcoluna
   */

   --PREMPRESAS   - empresa matriz + filiais
   --PRCNPJMATRIZ - saber o CNP da matriz previamente para atribuir para todos registros, inclusive os das filiais

   EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

   wSql = 'select tnatsai.bdcodemp, ';
   wSql = wSql || 'temp.bdcnpjemp, ';
   wSql = wSql || 'tnatsai.bdprefixonat, ';
   wSql = wSql || 'sum(tnatsai.bdvlrcontab)  bdvlrcontab, ';
   wSql = wSql || 'sum(tnatsai.bdvlripi)     bdvlripi, ';
   wSql = wSql || 'sum(tnatsai.bdoutrasipi)  bdoutrasipi, ';
   wSql = wSql || 'sum(tnatsai.bdisentasipi) bdisentasipi ';
   wSql = wSql || 'from vw_vef_tot_nat_sai_date tnatsai ';
   wSql = wSql || 'left outer join tempresas temp on (temp.bdcodemp = tnatsai.bdcodemp) ';

   wwhere = '';
  
   IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
      wwhere = wWhere||'('||prempresas||') ';
 
   IF (prdataini IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatsai.bddataemissao >= '||''''||prdataini||''''||' ';
      END
 
   IF (prdatafin IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatsai.bddataemissao <= '||''''||prdatafin||''''||' ';
      END

   IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   /*definir na aplicação*/
   wGroupBy = 'group by tnatsai.bdcodemp, tnatsai.bdprefixonat, temp.bdcnpjemp ';
   worderby = '';

   wsql = wsql||wwhere||wgroupby||worderby;
 
   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :wcnpjemp,
       :wprefixonat,
       :wvlrcontab,
       :wvlripi,
       :woutrasipi,
       :wisentasipi
     DO
     BEGIN
        i = 1;
        bdcnpjempmatriz = prcnpjmatriz;
        bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);

        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;

        --carregar dados para cada uma das três colunas do registro
        WHILE (i <= 3) DO
          BEGIN
            bdcoluna = i;
            bdvlrprodnacional            = 0;
            bdvlrmercadoriasnacional     = 0;
            bdvlrindustoutrasempnacional = 0;
            bdvlrdevcomprasnacional      = 0;
            bdvlroutrassainacional       = 0;
            bdvlrprodexterior            = 0;
            bdvlrmercadoriasexterior     = 0;
            bdvlrindustoutrasempexterior = 0;
            bdvlrdevcomprasexterior      = 0;
            bdvlroutrassaiexterior       = 0;

            IF (wprefixonat IN (5101, 5103, 5105, 5109, 5111, 5113, 5116, 5118, 5122, 5151, 5155, 5401, 5402, 5408, 5501, 5904, 6101, 6103, 6105, 6107, 6109,
                                6111, 6113, 6116, 6118, 6122, 6151, 6155, 6401, 6402, 6408, 6501, 6904)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrprodnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrprodnacional = wvlrcontab;
                  ELSE
                     bdvlrprodnacional = wvlripi;
               END

            IF (wprefixonat IN (5102, 5104, 5106, 5110, 5112, 5114, 5115, 5117, 5119, 5120, 5123, 5152, 5156, 5403, 5405, 5409, 5502, 6102, 6104, 6106, 6108,
                                6110, 6114, 6115, 6117, 6119, 6120, 6123, 6152, 6156, 6403, 6404, 6409, 6502)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrmercadoriasnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrmercadoriasnacional = wvlrcontab;
                  ELSE
                     bdvlrmercadoriasnacional = wvlripi;
               END

            IF (wprefixonat IN (5124, 5125, 6124, 6125)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrindustoutrasempnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrindustoutrasempnacional = wvlrcontab;
                  ELSE
                     bdvlrindustoutrasempnacional = wvlripi;
               END

            IF (wprefixonat IN (5201, 5202, 5206, 5207, 5208, 5209, 5210, 5410, 5411, 5412, 5413, 5503, 5553, 5555, 5556, 5918, 5919, 6201, 6202, 6206, 6208, 6209,
                                6210, 6410, 6411, 6412, 6413, 6503, 6553, 6555, 6556, 6918, 6919)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrdevcomprasnacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrdevcomprasnacional = wvlrcontab;
                  ELSE
                     bdvlrdevcomprasnacional = wvlripi;
               END

            IF (wprefixonat IN (5205, 5251, 5252, 5254, 5255, 5256, 5258, 5302, 5303, 5304, 5305, 5306, 5307, 5351, 5352, 5353, 5354, 5355, 5356, 5357, 5408, 5409,
                                5414, 5415, 5451, 5551, 5552, 5554, 5557, 5601, 5602, 5603, 5901, 5902, 5903, 5905, 5906, 5907, 5908, 5909, 5910, 5911, 5912, 5913,
                                5914, 5915, 5916, 5917, 5920, 5921, 5922, 5923, 5924, 5925, 5926, 5927, 5928, 5929, 5931, 5932, 5949, 6205, 6207, 6251, 6252, 6253,
                                6254, 6255, 6256, 6258, 6302, 6303, 6304, 6305, 6306, 6307, 6351, 6352, 6353, 6354, 6355, 6356, 6357, 6408, 6414, 6415, 6551, 6552,
                                6554, 6557, 6603, 6901, 6902, 6903, 6904, 6905, 6906, 6907, 6908, 6909, 6910, 6911, 6912, 6913, 6914, 6915, 6916, 6917, 6920, 6921,
                                6922, 6923, 6924, 6925, 6929, 6931, 6932, 6949)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlroutrassainacional = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlroutrassainacional = wvlrcontab;
                  ELSE
                     bdvlroutrassainacional = wvlripi;
               END

            IF (wprefixonat IN (7101, 7105, 7127, 7501)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrprodexterior = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrprodexterior = wvlrcontab;
                  ELSE
                     bdvlrprodexterior = wvlripi;
               END

            IF (wprefixonat IN (7102, 7106)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrmercadoriasexterior = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrmercadoriasexterior = wvlrcontab;
                  ELSE
                     bdvlrmercadoriasexterior = wvlripi;
               END

            IF (wprefixonat IN (7201, 7202, 7210, 7211, 7553, 7556, 7930)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlrdevcomprasexterior = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlrdevcomprasexterior = wvlrcontab;
                  ELSE
                     bdvlrdevcomprasexterior = wvlripi;
               END

            IF (wprefixonat IN (7206, 7207, 7551, 7949)) THEN
               BEGIN
                  IF (bdcoluna = 1) THEN
                     bdvlroutrassaiexterior = wvlrcontab - wvlripi - woutrasipi - wisentasipi;
                  ELSE
                  IF (bdcoluna = 2) THEN
                     bdvlroutrassaiexterior = wvlrcontab;
                  ELSE
                     bdvlroutrassaiexterior = wvlripi;
               END

            i = i + 1;
            SUSPEND;
          END
     END
END
^

/* Restore proc. body: VEF_SP_EXP_DIPJ_REG23 */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG23(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDCGCTER VARCHAR(18),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
DECLARE VARIABLE WGROUPBY VARCHAR(5000);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WVLRST NUMERIC(15,6);
DECLARE VARIABLE WSEQUENCIAL INTEGER;
BEGIN
   --PREMPRESAS   - empresa matriz + filiias
   --PRCNPJMATRIZ - saber o CNP da matriz previamente para atribuir para todos registros, inclusive os das filiais

  /* utilizar na aplicação desta forma. Exemplo:
  select  bdcodemp,
        bdcodter,
        bdcnpjempmatriz,
        bdcnpjestab,
        bdcgcter,
        bdvalor,
        bdusast,
        bdtipomatrizfilial
  from VEF_SP_EXP_DIPJ_REG23('tnatent.bdcodemp = 1 or tnatent.bdcodemp = 2','00.190.373/0001-72','01/01/2010','04/30/2010', 201011)
  order by BDTIPOMATRIZFILIAL, bdValor desc*/


   EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

   IF (prlevartodos = 'TRUE') THEN
      wSql = 'select tnatent.BDCODEMP, ';
   ELSE
      wSql = 'select first 100 tnatent.BDCODEMP, ';
   wSql = wSql || 'tnatent.BDCODTER, ';
   wSql = wSql || 'temp.bdcnpjemp, ';
   wSql = wSql || 'tterc.bdcgcter, ';
   wSql = wSql || 'sum(tnatent.BDVLRCONTAB) - sum(tnatent.BDVLRIPI) bdVALOR, ';
   wSql = wSql || 'sum(BDVLRST) bdVALORST ';
   wSql = wSql || 'from vw_vef_tot_nat_ent_date_terc tnatent ';
   wSql = wSql || 'left outer join tempresas temp on (temp.bdcodemp = tnatent.BDCODEMP) ';
   wSql = wSql || 'left outer join tterceiro tterc on (tterc.bdcodter = tnatent.bdcodter) ';

   wwhere = '';
  
   IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
      wwhere = wWhere||'('||prempresas||') ';
 
   IF (prdataini IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatent.bddataentradaent >= '||''''||prdataini||''''||' ';
      END
 
   IF (prdatafin IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatent.bddataentradaent <= '||''''||prdatafin||''''||' ';
      END


   IF (wWhere <> '') THEN
      wWhere = wwhere || ' and ';

   wwhere = wwhere || 'BDPREFIXONAT in (1101, 1102, 1111, 1113, 1116, 1117, 1118, 1120, 1121, 1122, 1124, 1125, 1126, 1151, 1152,
                                       1154, 1401, 1403, 1408, 1409, 1410, 1411, 1414, 1415, 1501, 1503, 1504, 1901, 1902, 1903,
                                       1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1918,
                                       1919, 1920, 1921, 1922, 1923, 1924, 1925, 1926, 1949, 2101, 2102, 2111, 2113, 2116, 2117,
                                       2118, 2120, 2121, 2122, 2124, 2125, 2126, 2151, 2152, 2154, 2401, 2403, 2408, 2409, 2410,
                                       2411, 2414, 2415, 2501, 2503, 2504, 2901, 2902, 2903, 2904, 2905, 2906, 2907, 2908, 2909,
                                       2910, 2911, 2912, 2913, 2914, 2915, 2916, 2917, 2918, 2919, 2920, 2921, 2922, 2923, 2924,
                                       2925, 2949, 3101, 3102, 3126, 3127, 3503, 3949)';


   IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   /*definir na aplicação*/

   wGroupBy = 'group by tnatent.BDCODEMP, tnatent.BDCODTER, temp.bdcnpjemp, tterc.bdcgcter ';
   worderby = 'order by tnatent.BDCODEMP, BDVALOR desc ';

   wsql = wsql||wwhere||wgroupby||worderby;

   wsequencial = 0;
 
   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bdcodter,
       :wcnpjemp,
       :bdcgcter,
       :bdVALOR,
       :wvlrst
     DO
     BEGIN
        wsequencial     = wSequencial + 1;
        IF (prlevartodos = 'TRUE') THEN
           bdsequencial = 101;
        ELSE
           bdsequencial = wsequencial;
        bdcnpjempmatriz = prcnpjmatriz;
        bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);

        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;

        IF (bdcgcter =   '  .   .   /    -') THEN
            bdcgcter = '00000000000000';

        IF (wvlrst > 0) THEN
           bdusast = 1;
        ELSE
           bdusast = 0;
        SUSPEND;
     END
END
^

/* Restore proc. body: VEF_SP_EXP_DIPJ_REG24 */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG24(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDNCMPROD INTEGER,
BDCODPROD INTEGER,
BDCODSAIDA VARCHAR(60),
BDCODIGOEAN VARCHAR(20),
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDDESCPROD VARCHAR(200),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
DECLARE VARIABLE WGROUPBY VARCHAR(5000);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WVLRST NUMERIC(15,6);
DECLARE VARIABLE WSEQUENCIAL INTEGER;
BEGIN

   EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

   IF (prlevartodos = 'TRUE') THEN
      wSql = 'select ';
   ELSE
      wSql = 'select first 50 ';
   wSql = wSql || 'tnatprod.BDCODEMP, ';
   wSql = wSql || 'tnatprod.bdncmprod, ';
   wSql = wSql || 'tnatprod.bdcodprod, ';
   wSql = wSql || 'tnatprod.BDCODSAIDA, ';
   wSql = wSql || 'tnatprod.bdcodigoean, ';
   wSql = wSql || 'tnatprod.bddescprod, ';
   wSql = wSql || 'temp.bdcnpjemp, ';
   wSql = wSql || 'sum(tnatprod.bdvlritemprod - tnatprod.bdvlripi) bdvalor, ';
   wSql = wSql || 'sum(tnatprod.bdvlrstprod) bdVALORSTPROD ';
   wSql = wSql || 'from vw_vef_tot_nat_ent_date_prod tnatprod ';
   wSQl = wSQl || 'left outer join tempresas temp on (temp.bdcodemp = tnatprod.BDCODEMP) ';

   wwhere = '';
  
   IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
      wwhere = wWhere||'('||prempresas||') ';
 
   IF (prdataini IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatprod.bddataentradaent >= '||''''||prdataini||''''||' ';
      END
 
   IF (prdatafin IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatprod.bddataentradaent <= '||''''||prdatafin||''''||' ';
      END


   IF (wWhere <> '') THEN
      wWhere = wwhere || ' and ';

   wwhere = wwhere || 'tnatprod.BDPREFIXONAT in (1101, 1102, 1111, 1113, 1116, 1117, 1118, 1120, 1121, 1122,
                                                 1124, 1125, 1126, 1151, 1152, 1154, 1401, 1403, 1408, 1409,
                                                 1410, 1411, 1414, 1415, 1501, 1503, 1504, 1901, 1902, 1903,
                                                 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913,
                                                 1914, 1915, 1916, 1917, 1918, 1919, 1920, 1921, 1922, 1923,
                                                 1924, 1925, 1926, 1934, 1949, 2101, 2102, 2111, 2113, 2116,
                                                 2117, 2118, 2120, 2121, 2122, 2124, 2125, 2126, 2151, 2152,
                                                 2154, 2401, 2403, 2408, 2409, 2410, 2411, 2414, 2415, 2501,
                                                 2503, 2504, 2901, 2902, 2903, 2904, 2905, 2906, 2907, 2908,
                                                 2909, 2910, 2911, 2912, 2913, 2914, 2915, 2916, 2917, 2918,
                                                 2919, 2920, 2921, 2922, 2923, 2924, 2925, 2934, 2949, 3101,
                                                 3102, 3126, 3127, 3503, 3949)';


   IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   /*definir na aplicação*/

   wGroupBy = 'group by tnatprod.BDCODEMP, tnatprod.bdncmprod, tnatprod.bdcodprod, tnatprod.BDCODSAIDA, tnatprod.bdcodigoean, tnatprod.bddescprod, temp.bdcnpjemp ';
   wOrderBy = 'order by tnatprod.BDCODEMP, bdvalor desc, bdncmprod ';

   wsql = wsql||wwhere||wgroupby||worderby;

   wsequencial = 0;
 
   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bdncmprod,
       :bdcodprod,
       :BDCODSAIDA,
       :bdcodigoean,
       :bddescprod,
       :wcnpjemp,
       :bdVALOR,
       :wvlrst
     DO
     BEGIN
        bddescprod = SUBSTRING(bddescprod FROM 1 FOR 55);
        BDCODSAIDA = SUBSTRING(BDCODSAIDA FROM 1 FOR 20);

        bdcnpjempmatriz = prcnpjmatriz;
        bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);

        wsequencial  = wsequencial + 1;
        IF (prlevartodos = 'TRUE') THEN
           bdsequencial = 51;
        ELSE
           bdsequencial = wsequencial;

        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;

        IF (wvlrst > 0) THEN
           bdusast = 1;
        ELSE
           bdusast = 0;
        SUSPEND;
     END
END
^

/* Restore proc. body: VEF_SP_EXP_DIPJ_REG25 */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG25(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDCGCTER VARCHAR(18),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
DECLARE VARIABLE WGROUPBY VARCHAR(5000);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WVLRST NUMERIC(15,6);
DECLARE VARIABLE WSEQUENCIAL INTEGER;
BEGIN
   --PREMPRESAS   - empresa matriz + filiias
   --PRCNPJMATRIZ - saber o CNP da matriz previamente para atribuir para todos registros, inclusive os das filiais

  /* utilizar na aplicação desta forma. Exemplo:
  select bdcodemp,
         bdcodter,
         bdcnpjempmatriz,
         bdcnpjestab,
         bdcgcter,
         bdvalor,
         bdusast,
         bdtipomatrizfilial
  from VEF_SP_EXP_DIPJ_REG25('tnatsai.bdcodemp = 1 or tnatsai.bdcodemp = 2','00.190.373/0001-72','01/01/2010','04/30/2010', 201011)
  order by BDTIPOMATRIZFILIAL, bdValor desc*/
  EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

  IF (prlevartodos = 'TRUE') THEN
      wSql = 'select ';
   ELSE
      wSql = 'select first 100 ';
  wSql = wSql || 'tnatsai.bdcodemp, ';
  wSql = wSql || 'tnatsai.bdcodter, ';
  wSql = wSql || 'temp.bdcnpjemp, ';
  wSql = wSql || 'tterc.bdcgcter, ';
  wSql = wSql || 'sum(tnatsai.BDVLRCONTAB) - sum(tnatsai.BDVLRIPI) bdVALOR, ';
  wSql = wSql || 'sum(BDVLRST) bdVALORST ';
  wSql = wSql || 'from vw_vef_tot_nat_sai_date_terc tnatsai ';
  wSql = wSql || 'left outer join tempresas temp on (temp.bdcodemp = tnatsai.BDCODEMP) ';
  wSql = wSql || 'left outer join tterceiro tterc on (tterc.bdcodter = tnatsai.bdcodter) ';

   wwhere = '';
  
   IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
      wwhere = wWhere||'('||prempresas||') ';
 
   IF (prdataini IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatsai.bddataemissao >= '||''''||prdataini||''''||' ';
      END
 
   IF (prdatafin IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatsai.bddataemissao <= '||''''||prdatafin||''''||' ';
      END


   IF (wWhere <> '') THEN
      wWhere = wwhere || ' and ';

   wwhere = wwhere || 'tnatsai.BDPREFIXONAT in (5101, 5102, 5103, 5104, 5105, 5106, 5109, 5110, 5111, 5112,
                                                5113, 5114, 5115, 5116, 5117, 5118, 5119, 5120, 5122, 5123,
                                                5124, 5125, 5151, 5152, 5155, 5156, 5401, 5402, 5403, 5405,
                                                5408, 5409, 5414, 5415, 5501, 5502, 5503, 5667, 5901, 5902,
                                                5903, 5904, 5905, 5906, 5907, 5908, 5909, 5910, 5911, 5912,
                                                5913, 5914, 5915, 5916, 5917, 5918, 5919, 5920, 5921, 5922,
                                                5923, 5924, 5925, 5934, 5949, 6101, 6102, 6103, 6104, 6105,
                                                6106, 6107, 6108, 6109, 6110, 6111, 6112, 6113, 6114, 6115,
                                                6116, 6117, 6118, 6119, 6120, 6122, 6123, 6124, 6125, 6151,
                                                6152, 6155, 6156, 6401, 6402, 6403, 6404, 6408, 6409, 6502,
                                                6503, 6505, 6667, 6901, 6902, 6903, 6904, 6905, 6906, 6907,
                                                6908, 6909, 6910, 6911, 6912, 6913, 6914, 6915, 6916, 6917,
                                                6918, 6919, 6920, 6921, 6922, 6923, 6924, 6925, 6934, 6949,
                                                7101, 7102, 7105, 7106, 7127, 7501, 7667, 7949)';


   IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   /*definir na aplicação*/
   wgroupby = 'group by tnatsai.bdcodemp, tnatsai.bdcodter, temp.bdcnpjemp, tterc.bdcgcter ';
   worderby = 'order by tnatsai.bdcodemp, bdvalor desc ';

   wsql = wsql||wwhere||wgroupby||worderby;

   wsequencial = 0;
 
   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bdcodter,
       :wcnpjemp,
       :bdcgcter,
       :bdvalor,
       :wvlrst
     DO
     BEGIN
        bdcnpjempmatriz = prcnpjmatriz;
        bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);
        wsequencial  = wsequencial + 1;
        IF (prlevartodos = 'TRUE') THEN
           bdsequencial = 101;
        ELSE
           bdsequencial = wsequencial;

        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;

        IF (bdcgcter =   '  .   .   /    -') THEN
            bdcgcter = '00000000000000';

        IF (wvlrst > 0) THEN
           bdusast = 1;
        ELSE
           bdusast = 0;
        SUSPEND;
     END
END
^

/* Restore proc. body: VEF_SP_EXP_DIPJ_REG26 */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG26(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRLEVARTODOS VARCHAR(5))
 RETURNS(BDCODEMP INTEGER,
BDNCMPROD INTEGER,
BDCODPROD INTEGER,
BDCODSAIDA VARCHAR(60),
BDCODIGOEAN VARCHAR(20),
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDDESCPROD VARCHAR(200),
BDVALOR NUMERIC(15,6),
BDUSAST SMALLINT,
BDTIPOMATRIZFILIAL INTEGER,
BDSEQUENCIAL INTEGER)
 AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
DECLARE VARIABLE WGROUPBY VARCHAR(5000);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WVLRST NUMERIC(15,6);
DECLARE VARIABLE WSEQUENCIAL INTEGER;
BEGIN

   EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

   IF (prlevartodos = 'TRUE') THEN
      wSql = 'select ';
   ELSE
      wSql = 'select first 50 ';
   wSql = wSql || 'tnatprod.bdcodemp, ';
   wSql = wSql || 'tnatprod.bdncmprod, ';
   wSql = wSql || 'tnatprod.bdcodprod, ';
   wSql = wSql || 'tnatprod.BDCODSAIDA, ';
   wSql = wSql || 'tnatprod.bdcodigoean, ';
   wSql = wSql || 'tnatprod.bddescprod, ';
   wSql = wSql || 'temp.bdcnpjemp, ';
   wSql = wSql || 'sum(tnatprod.bdvlritemprod - tnatprod.bdvlripi) bdvalor, ';
   wSql = wSql || 'sum(tnatprod.bdvlrstprod) bdvalorstprod ';
   wSql = wSql || 'from vw_vef_tot_nat_sai_date_prod tnatprod ';
   wSQl = wSQl || 'left outer join tempresas temp on (temp.bdcodemp = tnatprod.BDCODEMP) ';

   wwhere = '';
  
   IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
      wwhere = wWhere||'('||prempresas||') ';
 
   IF (prdataini IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatprod.bddataemissao >= '||''''||prdataini||''''||' ';
      END
 
   IF (prdatafin IS NOT NULL) THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
 
        wwhere = wwhere||'tnatprod.bddataemissao <= '||''''||prdatafin||''''||' ';
      END


   IF (wWhere <> '') THEN
      wWhere = wwhere || ' and ';

   wwhere = wwhere || 'tnatprod.BDPREFIXONAT in (5101, 5102, 5103, 5104, 5105, 5106, 5109, 5110, 5111, 5112, 5113, 5114, 5115,
                                                 5116, 5117, 5118, 5119, 5120, 5122, 5123, 5124, 5125, 5151, 5152, 5155, 5156,
                                                 5401, 5402, 5403, 5405, 5408, 5409, 5414, 5415, 5501, 5502, 5503, 5901, 5902,
                                                 5903, 5904, 5905, 5906, 5907, 5908, 5909, 5910, 5911, 5912, 5913, 5914, 5915,
                                                 5916, 5917, 5918, 5919, 5920, 5921, 5922, 5923, 5924, 5925, 5949, 6101, 6102,
                                                 6103, 6104, 6105, 6106, 6107, 6108, 6109, 6110, 6111, 6112, 6113, 6114, 6115,
                                                 6116, 6117, 6118, 6119, 6120, 6122, 6123, 6124, 6125, 6151, 6152, 6155, 6156,
                                                 6401, 6402, 6403, 6404, 6408, 6409, 6502, 6503, 6505, 6901, 6902, 6903, 6904,
                                                 6905, 6906, 6907, 6908, 6909, 6910, 6911, 6912, 6913, 6914, 6915, 6916, 6917,
                                                 6918, 6919, 6920, 6921, 6922, 6923, 6924, 6925, 6949, 7101, 7102, 7105, 7106,
                                                 7127, 7501, 7949)';

   IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   /*definir na aplicação*/

   wGroupBy = 'group by tnatprod.BDCODEMP, tnatprod.bdncmprod, tnatprod.bdcodprod, tnatprod.BDCODSAIDA, tnatprod.bdcodigoean, tnatprod.bddescprod, temp.bdcnpjemp ';
   wOrderBy = 'order by tnatprod.BDCODEMP, bdvalor desc, bdncmprod ';

   wsql = wsql||wwhere||wgroupby||worderby;

   wsequencial = 0;
 
   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bdncmprod,
       :bdcodprod,
       :BDCODSAIDA,
       :bdcodigoean,
       :bddescprod,
       :wcnpjemp,
       :bdVALOR,
       :wvlrst
     DO
     BEGIN
        bddescprod = SUBSTRING(bddescprod FROM 1 FOR 55);
        BDCODSAIDA = SUBSTRING(BDCODSAIDA FROM 1 FOR 20);

        bdcnpjempmatriz = prcnpjmatriz;
        bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);

        wsequencial  = wsequencial + 1;
        IF (prlevartodos = 'TRUE') THEN
           bdsequencial = 51;
        ELSE
           bdsequencial = wsequencial;


        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;

        IF (wvlrst > 0) THEN
           bdusast = 1;
        ELSE
           bdusast = 0;
        SUSPEND;
     END
END
^

/* Restore proc. body: VEF_SP_EXP_DIPJ_REG54 */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG54(PREMPRESAS VARCHAR(10000),
PRCNPJMATRIZ VARCHAR(18),
PRREFERENCIA INTEGER,
PRREFINI INTEGER = 0,
PRREFFIN INTEGER = 0)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMPMATRIZ VARCHAR(18),
BDCNPJESTAB VARCHAR(7),
BDCNAEPREP INTEGER,
BDTIPOMATRIZFILIAL INTEGER,
BDRECEITA NUMERIC(15,6))
 AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
BEGIN
   wSql = 'select temp.bdcodemp, ';
   wSql = wSql || 'temp.bdcnpjemp, ';
   wSql = wSql || 'tempref.BDCODCNAE ';
   wSql = wSql || 'from tempresas temp ';
   wsql = wSql || 'left outer join SP_CONSULTAEMPRESAS('||prReferencia||', 0,  NULL) tempref on (tempref.bdCodemp =  temp.bdcodemp) ';

   wwhere = '';
  
   IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
      wwhere = wWhere||'('||prempresas||') ';
 
   IF (wWhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   worderby = 'order by bdcodemp ';

   wsql = wsql||wwhere||worderby;
   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :wcnpjemp,
       :bdcnaeprep
     DO
     BEGIN
        bdcnpjempmatriz = prcnpjmatriz;
        bdcnpjestab     = SUBSTRING(wcnpjemp FROM 12 FOR 7);

        IF (bdcnpjempmatriz = wcnpjemp) THEN
           bdtipomatrizfilial = 0;
        ELSE
           bdtipomatrizfilial = 1;

        --somar campos 1,2,3,4 da apuração IRLP
        wwhere = '';

        IF (((prrefini IS NOT NULL) AND (prrefini > 0)) AND ((prreffin IS NOT NULL) AND (prreffin >= prrefini))) THEN
          BEGIN
            IF ((bdcodemp IS NOT NULL) AND (bdcodemp > 0)) THEN
              wwhere = wwhere||' ger.bdcodemp = '||bdcodemp||' ';

            IF ((wwhere IS NOT NULL) AND (prempresas <> '')) THEN
               wwhere = wwhere||' and ';

            wwhere = wwhere||' ger.bdreferencia between '||prrefini||' and '||prreffin||' ';
          END

        IF ((wwhere IS NOT NULL) AND (wwhere <> '')) THEN
          wwhere = ' and '||wwhere||' ';

        wsql = ' select sum(reg.bdvalor) bdreceita ';
        wsql = wsql||' from (select * from vef_emp_tirlpger ger where ger.bdcodperiodo in (8, 10) '||wwhere||' ) ger ';
        wsql = wsql||' left outer join vef_emp_tirlpgerreg reg on reg.bdcodemp = ger.bdcodemp and reg.bdcodperiodo = ger.bdcodperiodo and reg.bdreferencia = ger.bdreferencia ';
        wsql = wsql||' where reg.bdnumcampo between 1 and 4 ';

        IF ((wwhere IS NOT NULL) AND (wwhere <> '')) THEN
          EXECUTE STATEMENT wsql INTO :bdreceita;
        ELSE
          bdreceita = 0;

        SUSPEND;
     END
END
^

/* Restore proc. body: VEF_SP_EXP_DIPJ_REG59 */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG59(PREMPRESAS VARCHAR(10000),
PRCODPAISBRASIL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODBEM INTEGER,
BDNOMBEM VARCHAR(200),
BDCODATVEXT INTEGER,
BDCODFED INTEGER,
BDVALAQUIBEMINI NUMERIC(15,6),
BDVALAQUIBEMFIN NUMERIC(15,6),
BDSEQUENCIAL INTEGER)
 AS
DECLARE VARIABLE wsql VARCHAR(30000);
DECLARE VARIABLE worderby VARCHAR(5000);
DECLARE VARIABLE wwhere VARCHAR(5000);
DECLARE VARIABLE wsequencial INTEGER;
DECLARE VARIABLE wvalaquibem NUMERIC(15,6);
BEGIN
    wSql = 'select temp.bdcodemp, ';
    wSql = wSql || 'temp.bdcnpjemp, ';
    wSql = wSql || 'tbem.bdcodbem, ';
    wSql = wSql || 'tbem.bdnombem, ';
    wSql = wSql || 'tbem.bdvalaquibem, ';
    wSql = wSql || 'tbem.bdcodatvext, ';
    wSql = wSql || 'tpais.bdcodfed ';
    wSql = wSql || 'from empresas_tbem tbem ';
    wSql = wSql || 'left outer join tpais on (tpais.bdcodpais = tbem.bdcodpais) ';
    wSql = wSql || 'left outer join tempresas temp on (temp.bdcodemp = tbem.bdcodemp) ';

    wwhere = '';
  
    IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
       wwhere = wWhere||'('||prempresas||') ';

    --bem somente do exterior
    IF (wWhere <> '') THEN
       wWhere = wWhere || ' and ';

    wWhere = wWhere || '(tbem.bdcodpais is not null) and (tbem.bdcodpais <> '||prcodpaisbrasil||') ';

    IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

    worderby = 'order by temp.bdcodemp, tbem.bdcodbem';

    wsql = wsql||wwhere||worderby;

    wsequencial = 0;

    FOR EXECUTE STATEMENT wsql
      INTO
        :bdcodemp,
        :bdcnpjemp,
        :bdcodbem,
        :bdnombem,
        :wvalaquibem,
        :bdcodatvext,
        :bdcodfed
      DO
      BEGIN
        wsequencial  = wsequencial + 1;
        bdsequencial = wsequencial;
        bdvalaquibemini = wvalaquibem;
        bdvalaquibemfin = wvalaquibem;
        SUSPEND;
      END
END
^

/* Restore proc. body: VEF_SP_EXP_DIPJ_REG60_61A */
ALTER PROCEDURE VEF_SP_EXP_DIPJ_REG60_61A(PREMPRESAS VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRCODPAISBRASIL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODFED INTEGER,
BDTIPOPESSOA INTEGER,
BDCGCCEISOC VARCHAR(18),
BDCODSOC INTEGER,
BDNOMSOC VARCHAR(200),
BDEXPQUALISOC INTEGER,
BDCAPTOTCOTA NUMERIC(15,6),
BDCAPVOLCOTA NUMERIC(15,6),
BDCPFRESPLEGALSOC VARCHAR(14),
BDEXPQUALIRESPSOC INTEGER,
BDREMTRACOTA NUMERIC(15,6),
BDRENISECOTA NUMERIC(15,6),
BDRENTRICOTA NUMERIC(15,6),
BDDEMRENCOTA NUMERIC(15,6),
BDIRFONTCOTA NUMERIC(15,6),
BDSEQUENCIAL INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSEQUENCIAL INTEGER;
BEGIN
    EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);

    wSql = 'select temp.bdcodemp, ';
    wSql = wSql || 'temp.bdcnpjemp, ';
    wSQl = wsql || 'tsoc.bdcodsoc, ';
    wSql = wSql || 'tsoc.bdnomsoc, ';
    wSql = wSql || 'tsoc.bdcgcceisoc, ';
    wSql = wSql || 'tsoc.bdcpfresplegalsoc, ';
    wSql = wSql || 'tqsoc.BDEXPQUALISOC, ';
    wSql = wSql || 'tqrespsoc.BDEXPQUALISOC BDEXPQUALIRESPSOC, ';
    wSql = wSql || 'tsoccotas.bdcaptotcota, ';
    wSql = wSql || 'tsoccotas.bdcapvolcota, ';
    wSql = wSql || 'tsoccotas.bdremtracota, ';
    wSql = wSql || 'tsoccotas.bdrenisecota, ';
    wSql = wSql || 'tsoccotas.bdrentricota, ';
    wSql = wSql || 'tsoccotas.bddemrencota, ';
    wSql = wSql || 'tsoccotas.bdirfontcota, ';
    wSql = wSql || 'tpais.bdcodfed ';
    wSql = wSql || 'from vw_empresas_tsoc_ref tsoc ';
    wSql = wSql || 'left outer join tpais on (tpais.bdcodpais = tsoc.bdcodpais) ';
    wSql = wSql || 'left outer join tempresas temp on (temp.bdcodemp = tsoc.bdcodemp) ';
    wSql = wSql || 'left outer join tqualificacaosoc tqsoc on (tqsoc.bdqualificacaosoc = tsoc.BDQUALILEGALDIPJSOC) and character_length(tsoc.bdcgcceisoc) = 14 '; --and (tsoc.bdcodpais is null or tsoc.bdcodpais = 30)
    wSql = wSql || 'left outer join tqualificacaosoc tqrespsoc on (tqrespsoc.bdqualificacaosoc = tsoc.BDQUALIRESPLEGALSOC) and character_length(tsoc.bdcpfresplegalsoc) = 14 ';
    wSql = wSql || 'left outer join vw_empresas_tsoccotas tsoccotas on (tsoccotas.bdcodemp = tsoc.bdcodemp and tsoccotas.bdcodsoc = tsoc.bdcodsoc) ';

    wwhere = '';
  
    IF (prempresas IS NOT NULL AND prempresas <> '')  THEN
       wwhere = wWhere||'('||prempresas||') ';

    IF (wWhere <> '') THEN
       wWhere = wWhere || ' and ';

    wWhere = wWhere || '((tsoc.bddatasaisoc is null) or (tsoc.bddatasaisoc >= '||''''||prdataini||''''||')) ';

    IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

    worderby = 'order by tsoc.bdcodemp, tsoc.bdcodsoc ';

    wsql = wsql||wwhere||worderby;

    wSequencial = 0;
 
    FOR EXECUTE STATEMENT wsql
      INTO
        :bdcodemp,
        :bdcnpjemp,
        :bdcodsoc,
        :bdnomsoc,
        :bdcgcceisoc,
        :bdcpfresplegalsoc,
        :bdexpqualisoc,
        :bdexpqualirespsoc,
        :bdcaptotcota,
        :bdcapvolcota,
        :bdremtracota,
        :bdrenisecota,
        :bdrentricota,
        :bddemrencota,
        :bdirfontcota,
        :bdcodfed
      DO
      BEGIN
        IF (CHARACTER_LENGTH(bdcgcceisoc) > 14) THEN
           bdtipopessoa = 1;
        ELSE
           bdtipopessoa = 2;

        wsequencial  = wsequencial + 1;
        bdsequencial = wsequencial;

        IF (BDCODFED IS NULL OR BDCODFED = 0) THEN
           SELECT FIRST 1 p.bdcodfed FROM tpais p WHERE p.bdcodpais = :prcodpaisbrasil INTO bdcodfed;

        IF (bdcpfresplegalsoc = '000.000.000-00') THEN
           bdcpfresplegalsoc = '';
        SUSPEND;
      END
END
^

/* Restore proc. body: VEF_SP_EXP_GIASP */
CREATE OR ALTER PROCEDURE VEF_SP_EXP_GIASP (
    PRCODEMP VARCHAR(10000),
    PRANOMESINICIAL INTEGER,
    PRANOMESFINAL INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCONF INTEGER,
    BDREFERENCIA INTEGER,
    BDNUMCAMPO INTEGER,
    BDCODQUADRO INTEGER,
    BDCLASSIFICACAO VARCHAR(5),
    BDDESCFORM VARCHAR(150),
    BDCODNAT INTEGER,
    BDVALOR NUMERIC(18,6),
    BDVLRCONT NUMERIC(18,6),
    BDBASEICMS NUMERIC(18,6),
    BDVLRICMS NUMERIC(18,6),
    BDISENTASICMS NUMERIC(18,6),
    BDOUTRASICMS NUMERIC(18,6),
    BDVLRST NUMERIC(18,6),
    BDIMPSUBSTITUTO NUMERIC(18,6),
    BDIMPSUBSTITUIDO NUMERIC(18,6),
    BDOUTROSIMPOSTOS NUMERIC(18,6),
    BDUF_R14 VARCHAR(2),
    BDVALOR_CONTABIL_1_R14 NUMERIC(18,6),
    BDBASECALCULO_1_R14 NUMERIC(18,6),
    BDVALOR_CONTABIL_2_R14 NUMERIC(18,6),
    BDBASECALCULO_2_R14 NUMERIC(18,6),
    BDIMPOSTO_R14 NUMERIC(18,6),
    BDOUTRAS_R14 NUMERIC(18,6),
    BDICMSCOBRADOST_R14 NUMERIC(18,6),
    BDPETROLEOENERGIA_R14 NUMERIC(18,6),
    BDOUTROS_PRODUTOS_R14 NUMERIC(18,6),
    BDCODIGO_R20 INTEGER,
    BDOPERACAO_R20 INTEGER,
    BDFUNLEGAL_R20 VARCHAR(250),
    BDDESCRICAO_R20 VARCHAR(250),
    BDINSCESTREM_R25 VARCHAR(15),
    BDCODAUTORIZACAO_R28 VARCHAR(14),
    BDVLRCONT1 NUMERIC(18,6),
    BDBASEICMS1 NUMERIC(18,6),
    BDVLRCONT2 NUMERIC(18,6),
    BDBASEICMS2 NUMERIC(18,6),
    BDNRDOC INTEGER)
AS
DECLARE VARIABLE WUFEMP VARCHAR(5);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WSQLOCO VARCHAR(32700);
DECLARE VARIABLE WSQLR14 VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WCONTADOR INTEGER;
DECLARE VARIABLE WCODNATANT INTEGER;
DECLARE VARIABLE WCODNATAUT INTEGER;
DECLARE VARIABLE WVLRCONT NUMERIC(18,6);
DECLARE VARIABLE WBASEICMS NUMERIC(18,6);
DECLARE VARIABLE WVLRICMS NUMERIC(18,6);
DECLARE VARIABLE WISENTASICMS NUMERIC(18,6);
DECLARE VARIABLE WOUTRASICMS NUMERIC(18,6);
DECLARE VARIABLE WVLRST NUMERIC(18,6);
DECLARE VARIABLE WIMPSUBSTITUTO NUMERIC(18,6);
DECLARE VARIABLE WIMPSUBSTITUIDO NUMERIC(18,6);
DECLARE VARIABLE WOUTROSIMPOSTOS NUMERIC(18,6);
DECLARE VARIABLE WTIPORETENT INTEGER;
DECLARE VARIABLE WVALOR_CONTABIL_1_R14 NUMERIC(18,6);
DECLARE VARIABLE WBASECALCULO_1_R14 NUMERIC(18,6);
DECLARE VARIABLE WVALOR_CONTABIL_2_R14 NUMERIC(18,6);
DECLARE VARIABLE WBASECALCULO_2_R14 NUMERIC(18,6);
DECLARE VARIABLE WIMPOSTO_R14 NUMERIC(18,6);
DECLARE VARIABLE WOUTRAS_R14 NUMERIC(18,6);
DECLARE VARIABLE WICMSCOBRADOST_R14 NUMERIC(18,6);
DECLARE VARIABLE WPETROLEOENERGIA_R14 NUMERIC(18,6);
DECLARE VARIABLE WOUTROS_PRODUTOS_R14 NUMERIC(18,6);
DECLARE VARIABLE WVALOR_CONTABIL_1_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WBASECALCULO_1_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WVALOR_CONTABIL_2_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WBASECALCULO_2_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WIMPOSTO_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WOUTRAS_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WICMSCOBRADOST_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WPETROLEOENERGIA_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WOUTROS_PRODUTOS_R14AUX NUMERIC(18,6);
DECLARE VARIABLE WUFAUX VARCHAR(2);
DECLARE VARIABLE WUFAUXANT VARCHAR(2);
DECLARE VARIABLE WPASSOUUF INTEGER;
DECLARE VARIABLE WCODEMPOCO INTEGER;
DECLARE VARIABLE WREFOCO INTEGER;
DECLARE VARIABLE WCODEMPBKP INTEGER;
DECLARE VARIABLE WNOMEMPBKP DM_BDNOMEMP;
DECLARE VARIABLE WCODCONFBKP INTEGER;
DECLARE VARIABLE WREFERENCIABKP INTEGER;
DECLARE VARIABLE WNUMCAMPOBKP INTEGER;
DECLARE VARIABLE WCODQUADROBKP INTEGER;
DECLARE VARIABLE WCLASSIFICACAOBKP VARCHAR(5);
DECLARE VARIABLE WDESCFORMBKP VARCHAR(150);
DECLARE VARIABLE WCODNATBKP INTEGER;
DECLARE VARIABLE WVALORBKP NUMERIC(18,6);
DECLARE VARIABLE WVLRCONTBKP NUMERIC(18,6);
DECLARE VARIABLE WBASEICMSBKP NUMERIC(18,6);
DECLARE VARIABLE WVLRICMSBKP NUMERIC(18,6);
DECLARE VARIABLE WISENTASICMSBKP NUMERIC(18,6);
DECLARE VARIABLE WOUTRASICMSBKP NUMERIC(18,6);
DECLARE VARIABLE WVLRSTBKP NUMERIC(18,6);
DECLARE VARIABLE WIMPSUBSTITUTOBKP NUMERIC(18,6);
DECLARE VARIABLE WIMPSUBSTITUIDOBKP NUMERIC(18,6);
DECLARE VARIABLE WOUTROSIMPOSTOSBKP NUMERIC(18,6);
DECLARE VARIABLE WUF_R14BKP VARCHAR(2);
DECLARE VARIABLE WVALOR_CONTABIL_1_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WBASECALCULO_1_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WVALOR_CONTABIL_2_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WBASECALCULO_2_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WIMPOSTO_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WOUTRAS_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WICMSCOBRADOST_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WPETROLEOENERGIA_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WOUTROS_PRODUTOS_R14BKP NUMERIC(18,6);
DECLARE VARIABLE WCODIGO_R20BKP INTEGER;
DECLARE VARIABLE WOPERACAO_R20BKP INTEGER;
DECLARE VARIABLE WFUNLEGAL_R20BKP VARCHAR(250);
DECLARE VARIABLE WDESCRICAO_R20BKP VARCHAR(250);
DECLARE VARIABLE WINSCESTREM_R25BKP VARCHAR(12);
DECLARE VARIABLE WCODAUTORIZACAO_R28BKP VARCHAR(250);
DECLARE VARIABLE WVALORESEXTRAIDOS INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

  /*Matheus Amaral - Esse trecho estava dando erro de multiple rows, quando exportava com mais de 1 empresa selecionada. Vou passar essa parte para
   o select abaixo, pois ele é executado em um for select, ai nesse caso cada empresa vai pegar o seu parâmetro certinho.
   Solicitação #162864 | Título: GIA SP - Exportação em lote*/
  --WSQL = ' SELECT COALESCE(UF.BDFCPOP,''FALSE'') FROM VW_TEMPRESAS_REF T
  --         LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = T.BDCODCID)
  --         LEFT OUTER JOIN TUF UF ON (CID.BDCODUF = UF.BDCODUF)
  --         WHERE '||:PRCODEMP;

  --EXECUTE STATEMENT wsql
  --INTO :WUFEMP; --Matheus Amaral - FCP OP - Parâmetro usado para saber se soma o FCP ao ICMS.

  WSQL = '';

  wwhere = '';

  wcodempOCO = 0;
  wrefOCO = 0;

  IF (:PRCODEMP IS NOT NULL) THEN
     wwhere = 'where '||:PRCODEMP;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFERENCIA >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFERENCIA <= '||:pranomesfinal;

     END
--elizeu - 04-02-19 - a ordenação das empresas vai ser pela inscrição municipal, senão da erro no validador - cartão Arquivo GIA SP várias empresas #95810
  wsql =         'select T.BDCODEMP, EMPRESAS.BDNOMEMP, EMPRESAS.BDCODCONFGIASP BDCODCONF, T.BDREFERENCIA, T.BDNUMCAMPO, T.BDCODQUADRO, ';
  wsql = wsql || '        TCONF.BDCLASSIFICACAO, TCONFGIASPFORM.BDDESCFORM, T.BDPREFIXONAT BDCODNAT, sum(T.BDVALOR) BDVALOR,null BDVLRCONT, null BDBASEICMS, null BDVLRICMS, null BDISENTASICMS, null BDOUTRASICMS, null BDVLRST, ';
  wsql = wsql || '        null BDIMPSUBSTITUTO, null BDIMPSUBSTITUIDO, null BDOUTROSIMPOSTOS, null BDUF_R14, null BDTIPORETENT,null BDVALOR_CONTABIL_1_R14, null BDBASECALCULO_1_R14, null BDVALOR_CONTABIL_2_R14, null BDBASECALCULO_2_R14, ';
  wsql = wsql || '        null BDIMPOSTO_R14, null BDOUTRAS_R14, null BDICMSCOBRADOST_R14, null BDPETROLEOENERGIA_R14, ';
  wsql = wsql || '        null BDOUTROS_PRODUTOS_R14, null BDCODIGO_R20, null BDOPERACAO_R20, null BDFUNLEGAL_R20, null BDDESCRICAO_R20, ';
  wsql = wsql || '        null BDINSCESTREM_R25, null BDCODAUTORIZACAO_R28, ';
  --Solicitação #162864 | Título: GIA SP - Exportação em lote
  wsql = wsql || '        COALESCE(UF.BDFCPOP,''FALSE'') BDFCPOP';
  wsql = wsql || ' from ( ';
  wsql = wsql || '       select * ';
  wsql = wsql || '       from VEF_EMP_TGIASPGERNAT t ';
  wsql = wsql || wwhere;
  wsql = wsql || '       )T ';
  wsql = wsql || ' LEFT OUTER JOIN VW_EMP_REF_TOTAL EMPRESAS ON (t.bdcodemp = empresas.bdcodemp) ';
  wsql = wsql || ' left outer join VW_TEMPRESAS_REF EMPREF on (t.bdcodemp = empref.bdcodemp) ';
  wsql = wsql || ' LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = EMPREF.BDCODCID) ';
  wsql = wsql || ' LEFT OUTER JOIN TUF UF ON (CID.BDCODUF = UF.BDCODUF) ';
  wsql = wsql || ' left outer join VEF_ESTADOS_TCONFGIASPQ TCONF on (TCONF.BDCODQUADRO = T.BDCODQUADRO) ';
  wsql = wsql || ' left outer join  VEF_ESTADOS_TCONFGIASPFORM TCONFGIASPFORM on (TCONFGIASPFORM.BDCODCONF = EMPRESAS.BDCODCONFGIASP and TCONFGIASPFORM.BDCODQUADRO = T.BDCODQUADRO and TCONFGIASPFORM.BDNUMCAMPO = T.BDNUMCAMPO) ';
  wsql = wsql || ' group by T.BDCODEMP,empref.bdimemp,EMPRESAS.BDNOMEMP, BDCODCONF, T.BDREFERENCIA, BDCODNAT, TCONFGIASPFORM.BDDESCFORM, T.BDCODQUADRO, TCONF.BDCLASSIFICACAO, T.BDNUMCAMPO, UF.BDFCPOP ';
  wsql = wsql || ' order by T.BDCODEMP, empref.bdimemp, BDCODCONF, T.BDREFERENCIA, BDCODNAT, T.BDNUMCAMPO, TCONFGIASPFORM.BDDESCFORM, T.BDCODQUADRO, TCONF.BDCLASSIFICACAO ';

  wcontador = 1;

  wVLRCONT = 0;
  wBASEICMS = 0;
  wVLRICMS = 0;
  wISENTASICMS = 0;
  wOUTRASICMS = 0;
  wVLRST = 0;
  wIMPSUBSTITUTO = 0;
  wIMPSUBSTITUIDO = 0;
  wOUTROSIMPOSTOS = 0;

  WVALOR_CONTABIL_1_R14 = 0;
  WBASECALCULO_1_R14 = 0;
  WVALOR_CONTABIL_2_R14 = 0;
  WBASECALCULO_2_R14 = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    bdnomemp, 
    BDCODCONF ,
    BDREFERENCIA ,
    BDNUMCAMPO ,
    BDCODQUADRO,
    BDCLASSIFICACAO ,
    BDDESCFORM ,
    BDCODNAT,
    BDVALOR,
    BDVLRCONT,
    BDBASEICMS,
    BDVLRICMS,
    BDISENTASICMS,
    BDOUTRASICMS,
    BDVLRST,
    BDIMPSUBSTITUTO,
    BDIMPSUBSTITUIDO,
    BDOUTROSIMPOSTOS,
    BDUF_R14 ,
    WTIPORETENT,
    BDVALOR_CONTABIL_1_R14 ,
    BDBASECALCULO_1_R14,
    BDVALOR_CONTABIL_2_R14,
    BDBASECALCULO_2_R14,
    BDIMPOSTO_R14,
    BDOUTRAS_R14,
    BDICMSCOBRADOST_R14,
    BDPETROLEOENERGIA_R14,
    BDOUTROS_PRODUTOS_R14,
    BDCODIGO_R20,
    BDOPERACAO_R20,
    BDFUNLEGAL_R20,
    BDDESCRICAO_R20,
    BDINSCESTREM_R25,
    BDCODAUTORIZACAO_R28,
    WUFEMP
  DO
  BEGIN

    wcodnataut = BDCODNAT;
    wValoresExtraidos = 0;
    IF (BDCODQUADRO = 2) THEN
       BEGIN
        IF (wcontador = 1) THEN wVLRCONT = BDVALOR;     ELSE
        IF (wcontador = 2) THEN wBASEICMS = BDVALOR;    ELSE
        IF (wcontador = 3) THEN wVLRICMS = BDVALOR;     ELSE
        IF (wcontador = 4) THEN wISENTASICMS = BDVALOR; ELSE
        IF (wcontador = 5) THEN wOUTRASICMS = BDVALOR;  ELSE
        IF (wcontador = 6) THEN wVLRST = BDVALOR;       ELSE
        IF (wcontador = 7) THEN wIMPSUBSTITUTO = BDVALOR; ELSE
        IF (wcontador = 8) THEN wIMPSUBSTITUIDO = BDVALOR; ELSE
        IF (wcontador = 9) THEN
           wValoresExtraidos = 1;
      END
    ELSE
       BEGIN
        IF (wcontador = 1) THEN wVLRCONT = BDVALOR;     ELSE
        IF (wcontador = 2) THEN wBASEICMS = BDVALOR;    ELSE
        IF (wcontador = 3) THEN wVLRICMS = BDVALOR;     ELSE
        IF (wcontador = 4) THEN wISENTASICMS = BDVALOR; ELSE
        IF (wcontador = 5) THEN wOUTRASICMS = BDVALOR;  ELSE
        IF (wcontador = 6) THEN wVLRST = BDVALOR;       ELSE
        IF (wcontador = 7) THEN wIMPSUBSTITUTO = BDVALOR; ELSE
        IF (wcontador = 8) THEN wIMPSUBSTITUIDO = BDVALOR; ELSE
        IF (wcontador = 9) THEN
           wValoresExtraidos = 1;
      END

    IF (wValoresExtraidos = 1) THEN
    BEGIN
      wcontador = 0;
      wOUTROSIMPOSTOS = BDVALOR;

      WCODEMPBKP = BDCODEMP;
      WNOMEMPBKP = BDNOMEMP;
      WCODCONFBKP = BDCODCONF;
      WREFERENCIABKP = BDREFERENCIA;
      WNUMCAMPOBKP = BDNUMCAMPO;
      WCODQUADROBKP = BDCODQUADRO;
      WCLASSIFICACAOBKP = BDCLASSIFICACAO;
      WDESCFORMBKP = BDDESCFORM;
      WCODNATBKP = BDCODNAT;
      WVALORBKP = BDVALOR;
      WVLRCONTBKP = BDVLRCONT;
      WBASEICMSBKP = BDBASEICMS;
      WVLRICMSBKP = BDVLRICMS;
      WISENTASICMSBKP = BDISENTASICMS;
      WOUTRASICMSBKP = BDOUTRASICMS;
      WVLRSTBKP = BDVLRST;
      WIMPSUBSTITUTOBKP = BDIMPSUBSTITUTO;
      WIMPSUBSTITUIDOBKP = BDIMPSUBSTITUIDO;
      WOUTROSIMPOSTOSBKP = BDOUTROSIMPOSTOS;
      WUF_R14BKP = BDUF_R14;
      WVALOR_CONTABIL_1_R14BKP = BDVALOR_CONTABIL_1_R14;
      WBASECALCULO_1_R14BKP = BDBASECALCULO_1_R14;
      WVALOR_CONTABIL_2_R14BKP = BDVALOR_CONTABIL_2_R14;
      WBASECALCULO_2_R14BKP = BDBASECALCULO_2_R14;
      WIMPOSTO_R14BKP = BDIMPOSTO_R14;
      WOUTRAS_R14BKP = BDOUTRAS_R14;
      WICMSCOBRADOST_R14BKP = BDICMSCOBRADOST_R14;
      WPETROLEOENERGIA_R14BKP = BDPETROLEOENERGIA_R14;
      WOUTROS_PRODUTOS_R14BKP = BDOUTROS_PRODUTOS_R14;
      WCODIGO_R20BKP = BDCODIGO_R20;
      WOPERACAO_R20BKP = BDOPERACAO_R20;
      WFUNLEGAL_R20BKP = BDFUNLEGAL_R20;
      WDESCRICAO_R20BKP = BDDESCRICAO_R20;
      WINSCESTREM_R25BKP = BDINSCESTREM_R25;
      WCODAUTORIZACAO_R28BKP = BDCODAUTORIZACAO_R28;

      /*IF ((wcodempOCO > 0) AND ((wcodempOCO <> bdcodemp) OR (wrefOCO <> bdreferencia))) THEN
        BEGIN
          wsqloco = 'select t.BDCODEMP, NULL BDNOMEMP,NULL bdCODCONF,t.BDREFERENCIA, NULL BDNUMCAMPO, NULL BDCODQUADRO,NULL bdclassificacao, NULL bddescform,NULL BDCODNAT, BDVALOR,';
          wsqloco = wsqloco||' NULL BDVLRCONT,NULL BDBASEICMS,NULL BDVLRICMS,NULL BDISENTASICMS,NULL BDOUTRASICMS,NULL BDVLRST,NULL BDIMPSUBSTITUTO,NULL BDIMPSUBSTITUIDO,NULL BDOUTROSIMPOSTOS, ';
          wsqloco = wsqloco||' NULL BDSIGLAUF,NULL BDTIPORETENT,NULL BDVLRCONTAB,null BDVLRCONTAB2,NULL BDBASEICMS,NULL BDBASEICMS2,NULL BDVLRICMS,NULL BDOUTRASICMS,NULL BDVLRST,NULL bdicmsret,NULL BDOUTROSIMPOSTOS, ';
          wsqloco = wsqloco||'l.bdcodigo, l.bdoperacao -1 bdoperacao, l.bdfunlegal, l.bddescricao, T.BDINSCESTREM, T.BDCODAUTORIZACAO ';
          wsqloco = wsqloco||' from ( ';
          wsqloco = wsqloco||'       select BDCODEMP,BDCODTIPOOCOGIA,BDCODLISOCOGIASP,BDREFERENCIA,BDINSCESTREM,BDCODAUTORIZACAO,sum(BDVALOR) bdvalor ';
          wsqloco = wsqloco||'       from VEF_EMP_TMOVOCO_GIASP ';
          wsqloco = wsqloco||'       where bdcodemp = '||wcodempOCO;
          wsqloco = wsqloco||'       and bdreferencia = '||wrefOCO;
          wsqloco = wsqloco||'       group by BDCODEMP,BDCODTIPOOCOGIA,BDCODLISOCOGIASP,BDREFERENCIA,BDINSCESTREM,BDCODAUTORIZACAO ';
          wsqloco = wsqloco||' ) t, VEF_BASE_TTAB_LISTAOCO_GIASP l ';
          wsqloco = wsqloco||' where bdcodemp = '||wcodempOCO;
          wsqloco = wsqloco||' and bdreferencia = '||wrefOCO;
          wsqloco = wsqloco||' and (t.bdcodlisocogiasp = l.bdcodlisocogiasp) ';
          wsqloco = wsqloco||' order by t.bdcodemp, t.bdreferencia,l.bdcodigo,t.BDINSCESTREM ';

          FOR EXECUTE STATEMENT wsqloco
          INTO
            BDCODEMP,
            bdnomemp,
            BDCODCONF ,
            BDREFERENCIA ,
            BDNUMCAMPO ,
            BDCODQUADRO,
            BDCLASSIFICACAO ,
            BDDESCFORM ,
            BDCODNAT,
            BDVALOR,
            BDVLRCONT,
            BDBASEICMS,
            BDVLRICMS,
            BDISENTASICMS,
            BDOUTRASICMS,
            BDVLRST,
            BDIMPSUBSTITUTO,
            BDIMPSUBSTITUIDO,
            BDOUTROSIMPOSTOS,
            BDUF_R14 ,
            WTIPORETENT,
            BDVALOR_CONTABIL_1_R14 ,
            BDBASECALCULO_1_R14,
            BDVALOR_CONTABIL_2_R14,
            BDBASECALCULO_2_R14,
            BDIMPOSTO_R14,
            BDOUTRAS_R14,
            BDICMSCOBRADOST_R14,
            BDPETROLEOENERGIA_R14,
            BDOUTROS_PRODUTOS_R14,
            BDCODIGO_R20,
            BDOPERACAO_R20,
            BDFUNLEGAL_R20,
            BDDESCRICAO_R20,
            BDINSCESTREM_R25,
            BDCODAUTORIZACAO_R28
          DO
          BEGIN
            bddescform = 'R20';
        
            SUSPEND;
        
            IF ((BDCODIGO_R20 = 218) OR (BDCODIGO_R20 = 219) OR (BDCODIGO_R20 = 225) OR (BDCODIGO_R20 = 704) OR (BDCODIGO_R20 = 705) OR
                (BDCODIGO_R20 = 706) OR (BDCODIGO_R20 = 707) OR (BDCODIGO_R20 = 729) OR (BDCODIGO_R20 = 730) OR (BDCODIGO_R20 = 747)) THEN
               BEGIN
                  bddescform = 'R25';
                  SUSPEND;
               END
        
            IF ((BDCODIGO_R20 = 220) OR (BDCODIGO_R20 = 221) OR (BDCODIGO_R20 = 223) OR (BDCODIGO_R20 = 740) OR (BDCODIGO_R20 = 741) OR (BDCODIGO_R20 = 744) OR (BDCODIGO_R20 = 745)) THEN
               BEGIN
                  bddescform = 'R28';
                  SUSPEND;
               END
          END

          BDCODEMP = WCODEMPBKP;
          bdnomemp = wnomempbkp;
          BDCODCONF = WCODCONFBKP;
          BDREFERENCIA = WREFERENCIABKP;
          BDNUMCAMPO = WNUMCAMPOBKP;
          BDCODQUADRO = WCODQUADROBKP;
          BDCLASSIFICACAO = WCLASSIFICACAOBKP;
          BDDESCFORM = WDESCFORMBKP;
          BDCODNAT = WCODNATBKP;
          BDVALOR = WVALORBKP;
          BDVLRCONT = WVLRCONTBKP;
          BDBASEICMS = WBASEICMSBKP;
          BDVLRICMS = WVLRICMSBKP;
          BDISENTASICMS = WISENTASICMSBKP;
          BDOUTRASICMS = WOUTRASICMSBKP;
          BDVLRST = WVLRSTBKP;
          BDIMPSUBSTITUTO = WIMPSUBSTITUTOBKP;
          BDIMPSUBSTITUIDO = WIMPSUBSTITUIDOBKP;
          BDOUTROSIMPOSTOS = WOUTROSIMPOSTOSBKP;
          BDUF_R14 = WUF_R14BKP;
          BDVALOR_CONTABIL_1_R14 = WVALOR_CONTABIL_1_R14BKP;
          BDBASECALCULO_1_R14 = WBASECALCULO_1_R14BKP;
          BDVALOR_CONTABIL_2_R14 = WVALOR_CONTABIL_2_R14BKP;
          BDBASECALCULO_2_R14 = WBASECALCULO_2_R14BKP;
          BDIMPOSTO_R14 = WIMPOSTO_R14BKP;
          BDOUTRAS_R14 = WOUTRAS_R14BKP;
          BDICMSCOBRADOST_R14 = WICMSCOBRADOST_R14BKP;
          BDPETROLEOENERGIA_R14 = WPETROLEOENERGIA_R14BKP;
          BDOUTROS_PRODUTOS_R14 = WOUTROS_PRODUTOS_R14BKP;
          BDCODIGO_R20 = WCODIGO_R20BKP;
          BDOPERACAO_R20 = WOPERACAO_R20BKP;
          BDFUNLEGAL_R20 = WFUNLEGAL_R20BKP;
          BDDESCRICAO_R20 = WDESCRICAO_R20BKP;
          BDINSCESTREM_R25 = WINSCESTREM_R25BKP;
          BDCODAUTORIZACAO_R28 = WCODAUTORIZACAO_R28BKP;
        END*/

      wcodempOCO = bdcodemp;
      wrefOCO = bdreferencia;

      BDCODNAT = wcodnatant;
      BDVLRCONT = wVLRCONT;
      BDBASEICMS = wBASEICMS;
      BDVLRICMS = wVLRICMS;
      BDISENTASICMS = wISENTASICMS;
      BDOUTRASICMS = wOUTRASICMS;
      BDVLRST = wVLRST;
      BDIMPSUBSTITUTO = wIMPSUBSTITUTO;
      BDIMPSUBSTITUIDO = wIMPSUBSTITUIDO;
      BDOUTROSIMPOSTOS = wOUTROSIMPOSTOS;
      bddescform = 'R10';
      SUSPEND;

      wPassouUF = 0;

      IF (((wcodnatant >= 2000) AND (wcodnatant < 2999)) OR ((wcodnatant >= 6000) AND (wcodnatant < 6999))) THEN
        BEGIN

          WSQLR14 = 'select BDCODEMP, NULL BDNOMEMP, NULL bdCODCONF,BDREFERENCIA, NULL BDNUMCAMPO, NULL BDCODQUADRO,NULL bdclassificacao, NULL bddescform,NULL BDCODNAT, 0 BDVALOR,';
          WSQLR14 = WSQLR14||' BDVLRCONTAB,BDBASEICMS,0 BDVLRICMS,0 BDISENTASICMS,0 BDOUTRASICMS,0 BDVLRST, BDIMPSUBSTITUTO, BDIMPSUBSTITUIDO,0 BDOUTROSIMPOSTOS, ';
          WSQLR14 = WSQLR14||' BDSIGLAUF,BDTIPORETENT,0 BDVLRCONTAB,0 BDVLRCONTAB2,0 BDBASEICMS,0 BDBASEICMS2,BDVLRICMS,BDOUTRASICMS,BDVLRST,BDVLRST, BDVLRST, ';--BDOUTROSIMPOSTOS, ';
          WSQLR14 = WSQLR14||' NULL bdcodigo_R20, NULL bdoperacao_R20, NULL bdfunlegal_R20, NULL bddescricao_R20, NULL BDINSCESTREM_R25, NULL BDCODAUTORIZACAO_R28 ';

          IF ((wcodnatant >= 2000) AND (wcodnatant < 2999)) THEN
             WSQLR14 = WSQLR14||' , NULL BDVLRCONT1, NULL BDBASEICMS1, NULL BDVLRCONT2, NULL BDBASEICMS2 FROM ';
          ELSE
             WSQLR14 = WSQLR14||' , BDVLRCONT1, BDBASEICMS1, BDVLRCONT2, BDBASEICMS2 FROM ';
    
          IF ((wcodnatant >= 2000) AND (wcodnatant < 2999)) THEN -- Alt.: 15863 - Ver código abaixo da mesma solicitação, deve sempre verificar entradas...
            BEGIN
              /* Elizeu - 09-10-18 - Feito buscar o estado da GRF e do D100 - NOVA GIA CR 14 Entradas #88630*/
              WSQLR14 = WSQLR14||' (SELECT  m.bdcodemp, ';
              WSQLR14 = WSQLR14||' m.bdreflan BDREFERENCIA, ';
              WSQLR14 = WSQLR14||' IIF(uf.bdSIGLAUF <> '''||'SP'||''', uf.bdSIGLAUF, ';
              WSQLR14 = WSQLR14||'     IIF(ufgrf.bdSIGLAUF IS NOT NULL AND ufgrf.bdSIGLAUF <> '''||'SP'||''', ufgrf.bdSIGLAUF, ';
              WSQLR14 = WSQLR14||'         IIF(ufd100.bdSIGLAUF IS NOT NULL AND ufd100.bdSIGLAUF <> '''||'SP'||''', ufd100.bdSIGLAUF, ufd100orig.bdSIGLAUF))) AS BDSIGLAUF, '; -- Alt.: #123606 - Incluido a verificação da cidade de origem para o R14...
              WSQLR14 = WSQLR14||' m.bdTIPORETENT, ';
              WSQLR14 = WSQLR14||' SUM(COALESCE(m.bdvlrcontab,0)) BDVLRCONTAB, ';
              WSQLR14 = WSQLR14||' SUM(COALESCE(m.BDBASEICMS,0)) BDBASEICMS, ';
              WSQLR14 = WSQLR14||' SUM(COALESCE(m.bdvlricms,0)) bdvlricms, ';
              WSQLR14 = WSQLR14||' SUM(COALESCE(m.BDOUTRASICMS,0)) BDOUTRASICMS, ';
              WSQLR14 = WSQLR14||' SUM(COALESCE(m.bdvlrst,0)) BDVLRST, ';
              WSQLR14 = WSQLR14||' SUM(COALESCE(m.bdimpsubstituto,0)) bdimpsubstituto, ';
              WSQLR14 = WSQLR14||' SUM(COALESCE(m.bdimpsubstituido,0)) bdimpsubstituido ';
              WSQLR14 = WSQLR14||' FROM ( ';
              WSQLR14 = WSQLR14||'       select m.bdcodemp,bdreflan,m.bdcodter,itens.bdvlrcontab,itens.bdbaseicms, IIF('''||:WUFEMP||''' = ''TRUE'',COALESCE(ITENS.bdvlricms,0) + COALESCE(ITENS.BDVLRFCP,0), ITENS.BDVLRICMS) BDVLRICMS,itens.bdoutrasicms,COALESCE(ITENS.BDVLRST, 0) + COALESCE(ITENS.BDFCPRETIDO, 0) BDVLRST, ';
              WSQLR14 = WSQLR14||'              impret.bdimpsubstituto,impret.bdimpsubstituido,itens.bdcodnat,itens.bdtiporetent,M.bdcodterent,M.BDCIDDESTD100, M.BDCIDORIGD100 ';
              WSQLR14 = WSQLR14||'       from ( ';
              WSQLR14 = WSQLR14||'              select m.bdcodemp,m.bdchave,m.bdreflan,m.bdcodter,G.bdcodterent,D.BDCIDDEST BDCIDDESTD100, d.bdCIDORIGEM BDCIDORIGD100 ';
              WSQLR14 = WSQLR14||'              from vef_emp_tmovent m ';
              WSQLR14 = WSQLR14||'              LEFT OUTER JOIN VEF_EMP_TMOVENTGRF g on (m.bdcodemp = g.bdcodemp and m.bdchave = g.bdchave) ';
              WSQLR14 = WSQLR14||'              left outer join VEF_EMP_TD100ENT d on (m.bdcodemp = d.bdcodemp and m.bdchave = d.bdchave) ';
              WSQLR14 = WSQLR14||'              where m.BDCODEMP = '||bdcodemp;
              WSQLR14 = WSQLR14||'              and m.bdreflan = '||bdreferencia;
              WSQLR14 = WSQLR14||'              and m.bdcodsitnf NOT IN (2,3,4,5) ';
              WSQLR14 = WSQLR14||'            ) m ';
              WSQLR14 = WSQLR14||'       LEFT OUTER JOIN vef_emp_tmoventitens itens ON (m.bdcodemp = itens.bdcodemp AND m.bdchave = itens.bdchave) ';
              WSQLR14 = WSQLR14||'       LEFT OUTER JOIN VEF_EMP_TMOVENTIMPRETSP impret ON (impret.bdcodemp = itens.bdcodemp AND impret.bdchave = itens.bdchave AND impret.bdordem = itens.bdordem) ';
              WSQLR14 = WSQLR14||'       where itens.BDPREFIXONAT = '||wcodnatant;
              WSQLR14 = WSQLR14||'      ) m ';
              WSQLR14 = WSQLR14||' LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.bdcodter = m.bdcodter) ';
              WSQLR14 = WSQLR14||' LEFT OUTER JOIN tcidade cidade ON (cidade.bdcodcid = ter.bdcodcid) ';
              WSQLR14 = WSQLR14||' LEFT OUTER JOIN TUF uf ON (uf.bdcoduf = cidade.bdcoduf) ';
              WSQLR14 = WSQLR14||' LEFT OUTER JOIN VW_TTERCEIRO terGRF ON (M.bdcodterent = terGRF.bdcodter) ';
              WSQLR14 = WSQLR14||' LEFT OUTER JOIN TCIDADE CIDGRF ON (CIDGRF.bdcodcid = terGRF.bdcodcid) ';
              WSQLR14 = WSQLR14||' LEFT OUTER JOIN TUF ufGRF ON (ufGRF.bdcoduf = CIDGRF.bdcoduf) ';
              WSQLR14 = WSQLR14||' LEFT OUTER JOIN TCIDADE CIDD100 ON (CIDD100.bdcodcid = M.BDCIDDESTD100) ';
              WSQLR14 = WSQLR14||' LEFT OUTER JOIN TUF ufD100 ON (ufD100.bdcoduf = CIDD100.bdcoduf) ';
              WSQLR14 = WSQLR14||' LEFT OUTER JOIN TCIDADE cidd100orig ON (cidd100orig.bdCODCID = m.bdCIDORIGD100) '; -- Alt.: #123606 - Incluido a verificação da cidade de origem para o R14...
              WSQLR14 = WSQLR14||' LEFT OUTER JOIN TUF ufd100orig ON (ufd100orig.bdCODUF = cidd100orig.bdCODUF) ';
              WSQLR14 = WSQLR14||'      where (UF.BDSIGLAUF <> '''||'SP'||''') or ';
              WSQLR14 = WSQLR14||'            ((UFGRF.BDSIGLAUF is not null) and (UFGRF.BDSIGLAUF <> '''||'SP'||''')) or ';
              WSQLR14 = WSQLR14||'            ((UFD100.BDSIGLAUF is not null) and (UFD100.BDSIGLAUF <> '''||'SP'||''')) or ';
              WSQLR14 = WSQLR14||'            ((ufd100orig.bdSIGLAUF IS NOT NULL) and (ufd100orig.bdSIGLAUF <> '''||'SP'||''')) ';
              WSQLR14 = WSQLR14||' GROUP BY m.bdcodemp, m.bdreflan, /*Uf.bdsiglauf,UfGRF.bdsiglauf,UfD100.bdsiglauf*/ BDSIGLAUF,m.bdcodnat, m.bdtiporetent ';
              WSQLR14 = WSQLR14||' ) mov ';

--             WSQLR14 = WSQLR14||' VW_VEF_TOTEXP_UF_ENT_GIASP ';
--             WSQLR14 = WSQLR14||' where bdcodemp = '||bdcodemp||' and bdreferencia = '||bdreferencia||' and bdSIGLAUF <> '''||'SP'||''' and BDPREFIXONAT = '||wcodnatant;
            END
          ELSE
            BEGIN
--             WSQLR14 = WSQLR14||' VW_VEF_TOTEXP_UF_GIASP ';
--             WSQLR14 = WSQLR14||' where bdcodemp = '||bdcodemp||' and bdreferencia = '||bdreferencia||' and bdSIGLAUF <> '''||'SP'||''' and BDPREFIXONAT = '||wcodnatant;
            --ALT:16719 - FEITO PEGAR O D160 O PARTICIPNATE QUANDO HOUVER
             WSQLR14 = WSQLR14||' ( ';
             /* Quando a cidade do lançamento for de fora de SP então pega essa cidade do lançamento.
                Verifica a inscrição estadual do participante para saber se lança o valor como contribuinte ou não contribuinte. */
             WSQLR14 = WSQLR14||'                SELECT  MOV.bdcodemp,mov.bdreflan BDREFERENCIA ,mov.bdsiglauf,mov.BDTIPORETENT, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.bdvlrcontab,0)) BDVLRCONTAB, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.BDBASEICMS,0)) BDBASEICMS, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.bdvlricms,0)) bdvlricms, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.BDOUTRASICMS,0)) BDOUTRASICMS, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.bdvlrst,0)) BDVLRST, ';
             WSQLR14 = WSQLR14||'                        SUM(0) bdicmsret, ';
             WSQLR14 = WSQLR14||'                        SUM(0) BDOUTROSIMPOSTOS, ';
             WSQLR14 = WSQLR14||'                        SUM(0) BDVLRCONT1, ';
             WSQLR14 = WSQLR14||'                        SUM(0) BDBASEICMS1, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.bdvlrcontab,0)) BDVLRCONT2, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.BDBASEICMS,0)) BDBASEICMS2, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.bdIMPSUBSTITUTO,0)) BDIMPSUBSTITUTO, ';
             WSQLR14 = WSQLR14||'                        SUM(COALESCE(MOV.bdIMPSUBSTITUIDO,0)) BDIMPSUBSTITUIDO ';
             WSQLR14 = WSQLR14||'                FROM ( ';
             WSQLR14 = WSQLR14||'                      select mov.bdcodemp,mov.bdchave,mov.bdreflan,mov.bdordem,MOV.BDPREFIXONAT,null BDTIPORETENT, ';
             WSQLR14 = WSQLR14||'                             UF.BDSIGLAUF, mov.bdvlrcontab,mov.BDBASEICMS,mov.bdvlricms,mov.BDOUTRASICMS,MOV.bdvlrst, ';
             WSQLR14 = WSQLR14||'                             coalesce(impret.bdIMPSUBSTITUTO,0) bdIMPSUBSTITUTO,coalesce(impret.bdIMPSUBSTITUIDO,0) bdIMPSUBSTITUIDO ';
             WSQLR14 = WSQLR14||'                      from ( ';
             WSQLR14 = WSQLR14||'                              select sai.bdcodemp,sai.bdchave,sai.bdcodter,sai.bdreflan,itens.bdordem,d160.bdcodterdestinatario,ITENS.BDPREFIXONAT, ';
             WSQLR14 = WSQLR14||'                                     ITENS.bdvlrcontab,ITENS.BDBASEICMS,IIF('''||:WUFEMP||''' = ''TRUE'',COALESCE(ITENS.bdvlricms,0) + COALESCE(ITENS.BDVLRFCP,0), ITENS.BDVLRICMS) BDVLRICMS, ITENS.BDOUTRASICMS,COALESCE(ITENS.BDVLRST, 0) + COALESCE(ITENS.BDFCPRETIDO, 0) BDVLRST, SAI.BDCODCID, Coalesce(D160.BDCODCIDDESTINATARIO,D100.BDCIDDEST) bdCODCIDDESTINATARIO ';
             WSQLR14 = WSQLR14||'                              from ( ';
             WSQLR14 = WSQLR14||'                                    select sai.bdcodemp,sai.bdchave,sai.bdcodter,sai.bdreflan, SAI.BDCODCID ';
             WSQLR14 = WSQLR14||'                                    from vef_emp_tmovsai sai ';
             WSQLR14 = WSQLR14||'                                    where sai.bdcodemp = '||bdcodemp;
             WSQLR14 = WSQLR14||'                                    and  sai.bdcodsitnf not in (2,3,4,5) ';
             WSQLR14 = WSQLR14||'                                    and sai.BDREFLAN =  '||bdreferencia;
             WSQLR14 = WSQLR14||'                                    ) sai ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN vef_emp_tmovsaiitens itens ON (SAI.bdcodemp = itens.bdcodemp AND SAI.bdchave = itens.bdchave) '; 
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN VEF_EMP_TD100SAI D100 on (SAI.BDCODEMP = D100.BDCODEMP and SAI.BDCHAVE = D100.BDCHAVE) ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN vef_emp_td160cargatrans d160 ON (SAI.bdcodemp = d160.bdcodemp AND SAI.bdchave = D160.bdchave) ';
             WSQLR14 = WSQLR14||'                              where itens.BDPREFIXONAT = '||wcodnatant ;
             WSQLR14 = WSQLR14||'                            ) mov ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN VEF_EMP_TMOVSAIIMPRETSP impret ON (impret.bdcodemp = MOV.bdcodemp AND impret.bdchave = MOV.bdchave AND impret.bdordem = MOV.bdordem) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.bdcodter = MOV.bdcodter) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN tcidade cidade ON (cidade.bdcodcid = mov.bdcodcid) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN TUF uf ON (uf.bdcoduf = cidade.bdcoduf) ';
             WSQLR14 = WSQLR14||'                        WHERE ((ter.bdIETER IS NULL) OR (ter.bdIETER = '''') OR (UPPER(ter.bdIETER) = ''ISENTO'')) AND (uf.bdSIGLAUF <> ''SP'') ';
             WSQLR14 = WSQLR14||'                          AND (uf.bdSIGLAUF <> ''SP'') ';
             WSQLR14 = WSQLR14||'                        UNION ALL ';
             /* Quando a cidade do lançamento for de SP então pega essa cidade do destinatario no D160.
                Verifica a inscrição estadual do destinatario para saber se lança o valor como contribuinte ou não contribuinte. */
             WSQLR14 = WSQLR14||'                      select mov.bdcodemp,mov.bdchave,mov.bdreflan,mov.bdordem,MOV.BDPREFIXONAT,null BDTIPORETENT, ';
             WSQLR14 = WSQLR14||'                             ufd160.bdSIGLAUF, mov.bdvlrcontab,mov.BDBASEICMS,mov.bdvlricms,mov.BDOUTRASICMS,MOV.bdvlrst, ';
             WSQLR14 = WSQLR14||'                             coalesce(impret.bdIMPSUBSTITUTO,0) bdIMPSUBSTITUTO,coalesce(impret.bdIMPSUBSTITUIDO,0) bdIMPSUBSTITUIDO ';
             WSQLR14 = WSQLR14||'                      from ( ';
             WSQLR14 = WSQLR14||'                              select sai.bdcodemp,sai.bdchave,sai.bdcodter,sai.bdreflan,itens.bdordem,ITENS.BDPREFIXONAT, ';
             WSQLR14 = WSQLR14||'                                     ITENS.bdvlrcontab,ITENS.BDBASEICMS,IIF('''||:WUFEMP||''' = ''TRUE'',COALESCE(ITENS.bdvlricms,0) + COALESCE(ITENS.BDVLRFCP,0), ITENS.BDVLRICMS) BDVLRICMS,ITENS.BDOUTRASICMS,COALESCE(ITENS.BDVLRST, 0) + COALESCE(ITENS.BDFCPRETIDO, 0) BDVLRST, SAI.BDCODCID, ';
             WSQLR14 = WSQLR14||'                                     IIF(cidD160.bdCODUF <> 26, d160.bdCODTERDESTINATARIO, d160.bdCODTERREMETENTE) AS BDCODTERD160, '; -- Alt.: #123606 - Incluido a verificação da cidade de origem para o R14...
             WSQLR14 = WSQLR14||'                                     IIF(cidD160.bdCODUF <> 26, Coalesce(D160.BDCODCIDDESTINATARIO,D100.BDCIDDEST), Coalesce(D160.BDCODCIDREMETENTE,D100.BDCIDORIGEM)) AS BDCODCIDD160 '; -- Alt.: #123606 - Incluido a verificação da cidade de origem para o R14...
             WSQLR14 = WSQLR14||'                              from ( ';
             WSQLR14 = WSQLR14||'                                    select sai.bdcodemp,sai.bdchave,sai.bdcodter,sai.bdreflan, SAI.BDCODCID ';
             WSQLR14 = WSQLR14||'                                    from vef_emp_tmovsai sai ';
             WSQLR14 = WSQLR14||'                                    where sai.bdcodemp = '||bdcodemp;
             WSQLR14 = WSQLR14||'                                    and  sai.bdcodsitnf not in (2,3,4,5) ';
             WSQLR14 = WSQLR14||'                                    and sai.BDREFLAN =  '||bdreferencia;
             WSQLR14 = WSQLR14||'                                    ) sai ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN vef_emp_tmovsaiitens itens ON (SAI.bdcodemp = itens.bdcodemp AND SAI.bdchave = itens.bdchave) ';     
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN VEF_EMP_TD100SAI D100 on (SAI.BDCODEMP = D100.BDCODEMP and SAI.BDCHAVE = D100.BDCHAVE) ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN vef_emp_td160cargatrans d160 ON (SAI.bdcodemp = d160.bdcodemp AND SAI.bdchave = D160.bdchave) '; -- Alt.: 23787 - Deve usar o participante do destinatário do D160 e não do lançamento...
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN TCIDADE cidD160 ON (cidD160.bdCODCID = Coalesce(D160.BDCODCIDDESTINATARIO,D100.BDCIDDEST)) ';
             WSQLR14 = WSQLR14||'                              where itens.BDPREFIXONAT = '||wcodnatant ;
             WSQLR14 = WSQLR14||'                            ) mov ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN VEF_EMP_TMOVSAIIMPRETSP impret ON (impret.bdcodemp = MOV.bdcodemp AND impret.bdchave = MOV.bdchave AND impret.bdordem = MOV.bdordem) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN tcidade cidade ON (cidade.bdcodcid = mov.bdcodcid) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN TUF uf ON (uf.bdcoduf = cidade.bdcoduf) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN VW_TTERCEIRO terd160 ON (terd160.bdCODTER = mov.bdCODTERD160) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN TCIDADE cidd160 ON (cidd160.bdCODCID = mov.bdCODCIDD160) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN TUF ufd160 ON (ufd160.bdCODUF = cidd160.bdCODUF) ';
             WSQLR14 = WSQLR14||'                        where ((terd160.bdIETER IS NULL) or (terd160.bdIETER = '''') or (upper(terd160.bdIETER) = ''ISENTO'')) and ';
             WSQLR14 = WSQLR14||'                              (ufd160.bdSIGLAUF <> ''SP'') and ';
             WSQLR14 = WSQLR14||'                              (UF.BDSIGLAUF = ''SP'') ';
             WSQLR14 = WSQLR14||'                    ) MOV ';
             WSQLR14 = WSQLR14||'                GROUP BY MOV.bdcodemp, mov.bdreflan,mov.bdsiglauf,mov.BDTIPORETENT ';
             WSQLR14 = WSQLR14||'                union ';   
             WSQLR14 = WSQLR14||'                select MOV.BDCODEMP, MOV.BDREFLAN BDREFERENCIA, MOV.BDSIGLAUF, MOV.BDTIPORETENT,';
             WSQLR14 = WSQLR14||'                        sum(MOV.BDVLRCONTAB) BDVLRCONTAB, sum(MOV.BDBASEICMS) BDBASEICMS, sum(MOV.BDVLRICMS) BDVLRICMS, SUM(COALESCE(MOV.BDOUTRASICMS,0)) BDOUTRASICMS, ';
             WSQLR14 = WSQLR14||'                        sum(MOV.BDVLRST) BDVLRST, sum(0) BDICMSRET, sum(0) BDOUTROSIMPOSTOS, sum(MOV.BDVLRCONTAB) BDVLRCONT1, ';
             WSQLR14 = WSQLR14||'                        sum(MOV.BDBASEICMS) BDBASEICMS1, sum(0) BDVLRCONT2, sum(0) BDBASEICMS2, ';
             WSQLR14 = WSQLR14||'                        sum(MOV.BDIMPSUBSTITUTO) BDIMPSUBSTITUTO, sum(MOV.BDIMPSUBSTITUIDO) BDIMPSUBSTITUIDO ';
             WSQLR14 = WSQLR14||'                FROM ( ';
             /* Quando a cidade do lançamento for de fora de SP então pega essa cidade do lançamento.
                Verifica a inscrição estadual do participante para saber se lança o valor como contribuinte ou não contribuinte. */
             WSQLR14 = WSQLR14||'                       select MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDORDEM, MOV.BDPREFIXONAT, null BDTIPORETENT, UF.BDSIGLAUF, ';
             WSQLR14 = WSQLR14||'                             MOV.BDVLRCONTAB, MOV.BDBASEICMS, MOV.BDVLRICMS, MOV.BDOUTRASICMS, MOV.BDVLRST,';
             WSQLR14 = WSQLR14||'                             coalesce(IMPRET.BDIMPSUBSTITUTO, 0) BDIMPSUBSTITUTO, coalesce(IMPRET.BDIMPSUBSTITUIDO, 0) BDIMPSUBSTITUIDO ';
             WSQLR14 = WSQLR14||'                       from ( ';
             WSQLR14 = WSQLR14||'                              select SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDCODTER, SAI.BDREFLAN, ITENS.BDORDEM, D160.BDCODTERDESTINATARIO, ';
             WSQLR14 = WSQLR14||'                                     ITENS.BDPREFIXONAT, ITENS.BDVLRCONTAB, ITENS.BDBASEICMS, IIF('''||:WUFEMP||''' = ''TRUE'', COALESCE(ITENS.BDVLRICMS, 0) + COALESCE(ITENS.BDVLRFCP, 0), ITENS.BDVLRICMS) BDVLRICMS, ITENS.BDOUTRASICMS, COALESCE(ITENS.BDVLRST, 0) + COALESCE(ITENS.BDFCPRETIDO, 0) BDVLRST, ';
             WSQLR14 = WSQLR14||'                                     SAI.BDCODCID, Coalesce(D160.BDCODCIDDESTINATARIO,D100.BDCIDDEST) bdCODCIDDESTINATARIO ';
             WSQLR14 = WSQLR14||'                              from ( ';
             WSQLR14 = WSQLR14||'                                    select SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDCODTER, SAI.BDREFLAN, SAI.BDCODCID ';
             WSQLR14 = WSQLR14||'                                    from vef_emp_tmovsai sai ';
             WSQLR14 = WSQLR14||'                                    where sai.bdcodemp = '||bdcodemp;
             WSQLR14 = WSQLR14||'                                    and  sai.bdcodsitnf not in (2,3,4,5) ';
             WSQLR14 = WSQLR14||'                                    and sai.BDREFLAN =  '||bdreferencia;
             WSQLR14 = WSQLR14||'                                    ) sai ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN vef_emp_tmovsaiitens itens ON (SAI.bdcodemp = itens.bdcodemp AND SAI.bdchave = itens.bdchave) ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN VEF_EMP_TD100SAI D100 on (SAI.BDCODEMP = D100.BDCODEMP and SAI.BDCHAVE = D100.BDCHAVE) ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN vef_emp_td160cargatrans d160 ON (SAI.bdcodemp = d160.bdcodemp AND SAI.bdchave = D160.bdchave) ';
        /*Sol. 19711 Gabriel Ariel (11/08/17) - Nao estava exportando R14 com notas de valor contabil zerado*/
             WSQLR14 = WSQLR14||'                              where /*ITENS.BDVLRCONTAB > 0 and*/ itens.BDPREFIXONAT = '||wcodnatant ;
             WSQLR14 = WSQLR14||'                            ) mov ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN VEF_EMP_TMOVSAIIMPRETSP impret ON (impret.bdcodemp = MOV.bdcodemp AND impret.bdchave = MOV.bdchave AND impret.bdordem = MOV.bdordem) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.bdcodter = MOV.bdcodter) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN tcidade cidade ON (cidade.bdcodcid = MOV.bdcodcid) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN TUF uf ON (uf.bdcoduf = cidade.bdcoduf) ';
             WSQLR14 = WSQLR14||'                        WHERE ((ter.bdIETER IS NOT NULL) AND (ter.bdIETER <> '''') AND (UPPER(ter.bdIETER) <> ''ISENTO'')) ';
             WSQLR14 = WSQLR14||'                          AND (uf.bdSIGLAUF <> ''SP'') ';
             WSQLR14 = WSQLR14||'                       union all ';
             /* Quando a cidade do lançamento for de SP então pega essa cidade do destinatario no D160.
                Verifica a inscrição estadual do destinatario para saber se lança o valor como contribuinte ou não contribuinte. */
             WSQLR14 = WSQLR14||'                       select MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDORDEM, MOV.BDPREFIXONAT, null BDTIPORETENT, ufd160.bdSIGLAUF,';
             WSQLR14 = WSQLR14||'                              MOV.BDVLRCONTAB, MOV.BDBASEICMS, MOV.BDVLRICMS, MOV.BDOUTRASICMS, MOV.BDVLRST, ';
             WSQLR14 = WSQLR14||'                              coalesce(IMPRET.BDIMPSUBSTITUTO, 0) BDIMPSUBSTITUTO, coalesce(IMPRET.BDIMPSUBSTITUIDO, 0) BDIMPSUBSTITUIDO ';
             WSQLR14 = WSQLR14||'                       from ( ';
             WSQLR14 = WSQLR14||'                              select SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDCODTER, SAI.BDREFLAN, ITENS.BDORDEM, SAI.BDCODCID, ';
             WSQLR14 = WSQLR14||'                                     ITENS.BDPREFIXONAT, ITENS.BDVLRCONTAB, ITENS.BDBASEICMS, IIF('''||:WUFEMP||''' = ''TRUE'',COALESCE(ITENS.bdvlricms,0) + COALESCE(ITENS.BDVLRFCP,0), ITENS.BDVLRICMS) BDVLRICMS, ITENS.BDOUTRASICMS, COALESCE(ITENS.BDVLRST, 0) + COALESCE(ITENS.BDFCPRETIDO, 0) BDVLRST, ';
             WSQLR14 = WSQLR14||'                                     IIF(cidd160.bdCODUF <> 26, d160.bdCODTERDESTINATARIO, d160.bdCODTERREMETENTE) AS bdCODTERD160, '; -- Alt.: #123606 - Incluido a verificação da cidade de origem para o R14...
             WSQLR14 = WSQLR14||'                                     IIF(cidd160.bdCODUF <> 26, Coalesce(D160.BDCODCIDDESTINATARIO,D100.BDCIDDEST), Coalesce(D160.BDCODCIDREMETENTE,D100.BDCIDORIGEM)) AS bdCODCIDD160 '; -- Alt.: #123606 - Incluido a verificação da cidade de origem para o R14...
             WSQLR14 = WSQLR14||'                              from ( ';
             WSQLR14 = WSQLR14||'                                    select SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDCODTER, SAI.BDREFLAN, SAI.BDCODCID ';
             WSQLR14 = WSQLR14||'                                    from vef_emp_tmovsai sai ';
             WSQLR14 = WSQLR14||'                                    where sai.bdcodemp = '||bdcodemp;
             WSQLR14 = WSQLR14||'                                    and  sai.bdcodsitnf not in (2,3,4,5) ';
             WSQLR14 = WSQLR14||'                                    and sai.BDREFLAN =  '||bdreferencia;
             WSQLR14 = WSQLR14||'                                    ) sai ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN vef_emp_tmovsaiitens itens ON (SAI.bdcodemp = itens.bdcodemp AND SAI.bdchave = itens.bdchave) ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN VEF_EMP_TD100SAI D100 on (SAI.BDCODEMP = D100.BDCODEMP and SAI.BDCHAVE = D100.BDCHAVE) ';
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN vef_emp_td160cargatrans d160 ON (SAI.bdcodemp = d160.bdcodemp AND SAI.bdchave = D160.bdchave) '; -- Alt.: 23787 - Deve usar o participante do destinatário do D160 e não do lançamento...
             WSQLR14 = WSQLR14||'                              LEFT OUTER JOIN TCIDADE cidd160 ON (cidd160.bdCODCID = Coalesce(D160.BDCODCIDDESTINATARIO,D100.BDCIDDEST)) ';
             WSQLR14 = WSQLR14||'                              where itens.BDPREFIXONAT = '||wcodnatant ;
             WSQLR14 = WSQLR14||'                            ) mov ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN VEF_EMP_TMOVSAIIMPRETSP impret ON (impret.bdcodemp = MOV.bdcodemp AND impret.bdchave = MOV.bdchave AND impret.bdordem = MOV.bdordem) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN tcidade cidade ON (cidade.bdcodcid = MOV.bdcodcid) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN TUF uf ON (uf.bdcoduf = cidade.bdcoduf) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN VW_TTERCEIRO terD160 ON (terD160.bdCODTER = mov.bdCODTERD160) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN TCIDADE cidd160 ON (cidd160.bdCODCID = mov.bdCODCIDD160) ';
             WSQLR14 = WSQLR14||'                        LEFT OUTER JOIN TUF ufd160 ON (ufd160.bdCODUF = cidd160.bdCODUF) ';
             WSQLR14 = WSQLR14||'                        WHERE ((terd160.bdIETER IS NOT NULL) AND (terd160.bdIETER <> '''') AND (upper(terd160.bdIETER) <> ''ISENTO'')) AND ';
             WSQLR14 = WSQLR14||'                              (ufd160.bdSIGLAUF <> ''SP'') AND ';
             WSQLR14 = WSQLR14||'                              (UF.BDSIGLAUF = ''SP'') ';
             WSQLR14 = WSQLR14||'                    ) MOV ';
             WSQLR14 = WSQLR14||'                group by MOV.BDCODEMP, MOV.BDREFLAN, MOV.BDSIGLAUF, MOV.BDTIPORETENT ';
             WSQLR14 = WSQLR14||'  )';
            END

          wufaux = '';
          wufauxAnt = '';

          wVALOR_CONTABIL_1_R14 = 0;
          wBASECALCULO_1_R14 = 0;
          wVALOR_CONTABIL_2_R14 = 0;
          wBASECALCULO_2_R14 = 0;
          wIMPOSTO_R14 = 0;
          wOUTRAS_R14 = 0;
          wICMSCOBRADOST_R14 = 0;
          wPETROLEOENERGIA_R14 = 0;
          wOUTROS_PRODUTOS_R14 = 0;

          FOR EXECUTE STATEMENT WSQLR14
          INTO
            BDCODEMP,
            bdnomemp, 
            BDCODCONF,
            BDREFERENCIA,
            BDNUMCAMPO ,
            BDCODQUADRO,
            BDCLASSIFICACAO ,
            BDDESCFORM ,
            BDCODNAT,
            BDVALOR,
            BDVLRCONT,
            BDBASEICMS,
            BDVLRICMS,
            BDISENTASICMS,
            BDOUTRASICMS,
            BDVLRST,
            BDIMPSUBSTITUTO,
            BDIMPSUBSTITUIDO,
            BDOUTROSIMPOSTOS,
            BDUF_R14 ,
            WTIPORETENT,
            BDVALOR_CONTABIL_1_R14 ,
            BDBASECALCULO_1_R14,
            BDVALOR_CONTABIL_2_R14,
            BDBASECALCULO_2_R14,
            BDIMPOSTO_R14,
            BDOUTRAS_R14,
            BDICMSCOBRADOST_R14,
            BDPETROLEOENERGIA_R14,
            BDOUTROS_PRODUTOS_R14,
            BDCODIGO_R20,
            BDOPERACAO_R20,
            BDFUNLEGAL_R20,
            BDDESCRICAO_R20,
            BDINSCESTREM_R25,
            BDCODAUTORIZACAO_R28,
            BDVLRCONT1,
            BDBASEICMS1,
            BDVLRCONT2,
            BDBASEICMS2
          DO
          BEGIN
            bddescform = 'R14';
            bdcodnat = wcodnatant;
            wPassouUF = 1;

            IF ((wufaux <> '') AND (wufaux <> BDUF_R14)) THEN
               BEGIN
                  /*wVALOR_CONTABIL_1_R14Aux = 0;
                  wBASECALCULO_1_R14Aux = 0;
                  wVALOR_CONTABIL_2_R14Aux = 0;
                  wBASECALCULO_2_R14Aux = 0;*/

                  IF ((wcodnatant >= 2000) AND (wcodnatant < 2999)) THEN
                     BEGIN
                        wVALOR_CONTABIL_1_R14Aux = BDVLRCONT;
                        wBASECALCULO_1_R14Aux = BDBASEICMS;
                     END
                  ELSE
                     BEGIN
                        --if ((wIETER is null) or (wieter = '') or (Upper(wieter) = 'ISENTO')) then
                           BEGIN
                             wVALOR_CONTABIL_2_R14Aux = BDVLRCONT2;
                             wBASECALCULO_2_R14Aux = BDBASEICMS2;
                           /*end
                        else
                           begin*/
                             wVALOR_CONTABIL_1_R14Aux = BDVLRCONT1;
                             wBASECALCULO_1_R14Aux = BDBASEICMS1;
                           END
                     END

                  wIMPOSTO_R14Aux = BDIMPOSTO_R14;
                  wOUTRAS_R14Aux = BDOUTRAS_R14;
                  wICMSCOBRADOST_R14Aux = BDICMSCOBRADOST_R14;
                  wPETROLEOENERGIA_R14Aux = BDPETROLEOENERGIA_R14;
                  wOUTROS_PRODUTOS_R14Aux = BDOUTROS_PRODUTOS_R14;

                  wufauxant = BDUF_R14;
                  BDUF_R14 = wufaux;
                  BDVALOR_CONTABIL_1_R14 = wVALOR_CONTABIL_1_R14;
                  BDBASECALCULO_1_R14 = wBASECALCULO_1_R14;
                  BDVALOR_CONTABIL_2_R14 = wVALOR_CONTABIL_2_R14;
                  BDBASECALCULO_2_R14 = wBASECALCULO_2_R14;
                  BDIMPOSTO_R14 = wIMPOSTO_R14;
                  BDOUTRAS_R14 = wOUTRAS_R14;
                  BDICMSCOBRADOST_R14 = wICMSCOBRADOST_R14;
                  BDPETROLEOENERGIA_R14 = wPETROLEOENERGIA_R14;
                  BDOUTROS_PRODUTOS_R14 = wOUTROS_PRODUTOS_R14;

                  SUSPEND;

                  --Adilson - sol. 5664 - inicializado variávies para o R14
                  wVALOR_CONTABIL_1_R14 = 0;
                  wBASECALCULO_1_R14 = 0;
                  wVALOR_CONTABIL_2_R14 = 0;
                  wBASECALCULO_2_R14 = 0;
                  wIMPOSTO_R14 = 0;
                  wOUTRAS_R14 = 0;
                  wICMSCOBRADOST_R14 = 0;
                  wPETROLEOENERGIA_R14 = 0;
                  wOUTROS_PRODUTOS_R14 = 0;

                  BDUF_R14 = wufauxant;
                  BDVALOR_CONTABIL_1_R14 = wVALOR_CONTABIL_1_R14Aux;
                  BDBASECALCULO_1_R14 = wBASECALCULO_1_R14Aux;
                  BDVALOR_CONTABIL_2_R14 = wVALOR_CONTABIL_2_R14Aux;
                  BDBASECALCULO_2_R14 = wBASECALCULO_2_R14Aux;
                  BDIMPOSTO_R14 = wIMPOSTO_R14Aux;
                  BDOUTRAS_R14 = wOUTRAS_R14Aux;
                  BDICMSCOBRADOST_R14 = wICMSCOBRADOST_R14Aux;
                  BDPETROLEOENERGIA_R14 = wPETROLEOENERGIA_R14Aux;
                  BDOUTROS_PRODUTOS_R14 = wOUTROS_PRODUTOS_R14Aux;

               END

            wufaux = BDUF_R14;

            /*wVALOR_CONTABIL_1_R14 = 0;
            wBASECALCULO_1_R14 = 0;
            wVALOR_CONTABIL_2_R14 = 0;
            wBASECALCULO_2_R14 = 0;*/

            IF ((wcodnatant >= 2000) AND (wcodnatant < 2999)) THEN
               BEGIN
                  --Adilson - sol. 5664
                  --wVALOR_CONTABIL_1_R14 = /*wVALOR_CONTABIL_1_R14 + */BDVLRCONT;
                  --wBASECALCULO_1_R14 = /*wBASECALCULO_1_R14 + */BDBASEICMS;
                  wVALOR_CONTABIL_1_R14 = wVALOR_CONTABIL_1_R14 + BDVLRCONT;
                  wBASECALCULO_1_R14 = wBASECALCULO_1_R14 + BDBASEICMS;
               END
            ELSE
               BEGIN
                  --if ((wIETER is null) or (wieter = '') or (Upper(wieter) = 'ISENTO')) then
                     BEGIN
                       --Adilson - sol. 5664
                       --wVALOR_CONTABIL_2_R14 = /*wVALOR_CONTABIL_2_R14 + */BDVLRCONT2;
                       --wBASECALCULO_2_R14 = /*wBASECALCULO_2_R14 + */BDBASEICMS2;
                       wVALOR_CONTABIL_2_R14 = wVALOR_CONTABIL_2_R14 + BDVLRCONT2;
                       wBASECALCULO_2_R14 = wBASECALCULO_2_R14 + BDBASEICMS2;
                     /*end
                  else
                     begin*/
                       --Adilson - sol. 5664
                       --wVALOR_CONTABIL_1_R14 = /*wVALOR_CONTABIL_1_R14 + */BDVLRCONT1;
                       --wBASECALCULO_1_R14 = /*wBASECALCULO_1_R14 + */BDBASEICMS1;
                       wVALOR_CONTABIL_1_R14 = wVALOR_CONTABIL_1_R14 + BDVLRCONT1;
                       wBASECALCULO_1_R14    = wBASECALCULO_1_R14 + BDBASEICMS1;
                     END
               END
            --Adilson - sol. 5664
            --wIMPOSTO_R14 = /*wIMPOSTO_R14 + */BDIMPOSTO_R14;
            --wOUTRAS_R14 = /*wOUTRAS_R14 +*/ BDOUTRAS_R14;
            wIMPOSTO_R14 = wIMPOSTO_R14 + BDIMPOSTO_R14;
            wOUTRAS_R14  = wOUTRAS_R14  + BDOUTRAS_R14;

            IF ((wcodnatant >= 6000) AND (wcodnatant < 6999)) THEN
               --Adilson - sol. 5664
               --wICMSCOBRADOST_R14 = /*wICMSCOBRADOST_R14 + */BDICMSCOBRADOST_R14;
               wICMSCOBRADOST_R14 = wICMSCOBRADOST_R14 + BDICMSCOBRADOST_R14;

            --alt:15582 - elizeu - 31-08-16 - não tendo o tiporet não jogava o valor em nada, deve jogar em outros
            IF ((WTIPORETENT IS NOT NULL) OR ((wcodnatant >= 2000) AND (wcodnatant < 2999))) THEN -- Alt.: 15863 - Deve sempre verificar as entradas ou se tem retenção
               BEGIN
                IF ((WTIPORETENT = 0) OR (WTIPORETENT = 1)) THEN
                  BEGIN
                    IF (BDIMPSUBSTITUIDO > 0) THEN
                       --Adilson - sol. 5664
                       --wpetroleoenergia_r14 = BDIMPSUBSTITUIDO;
                       wpetroleoenergia_r14 = wpetroleoenergia_r14 + BDIMPSUBSTITUIDO;
                    ELSE
                    IF (BDIMPSUBSTITUTO > 0) THEN
                       --Adilson - sol. 5664
                       --wpetroleoenergia_r14 = BDIMPSUBSTITUTO;
                       wpetroleoenergia_r14 = wpetroleoenergia_r14 + BDIMPSUBSTITUTO;
                    wOUTROS_PRODUTOS_R14 = wOUTROS_PRODUTOS_R14;
                  END
                ELSE
                  BEGIN
                    --wOUTROS_PRODUTOS_R14 = wOUTROS_PRODUTOS_R14 + BDOUTROS_PRODUTOS_R14;
                    IF (BDIMPSUBSTITUIDO > 0) THEN
                       --Adilson - sol. 5664
                       --woutros_produtos_r14 = BDIMPSUBSTITUIDO;
                       woutros_produtos_r14 = woutros_produtos_r14 + BDIMPSUBSTITUIDO;
                    ELSE
                    IF (BDIMPSUBSTITUTO > 0) THEN
                       --Adilson - sol. 5664
                       --woutros_produtos_r14 = BDIMPSUBSTITUTO;
                       woutros_produtos_r14 = woutros_produtos_r14 + BDIMPSUBSTITUTO;
                    wPETROLEOENERGIA_R14 = wPETROLEOENERGIA_R14;
                  END
              END
          END
        END

      IF (wPassouUF = 1) THEN
        BEGIN

          /*wVALOR_CONTABIL_1_R14Aux = 0;
          wBASECALCULO_1_R14Aux = 0;
          wVALOR_CONTABIL_2_R14Aux = 0;
          wBASECALCULO_2_R14Aux = 0;*/

          IF ((wcodnatant >= 2000) AND (wcodnatant < 2999)) THEN
             BEGIN
                wVALOR_CONTABIL_1_R14Aux = BDVLRCONT;
                wBASECALCULO_1_R14Aux = BDBASEICMS;
             END
          ELSE
             BEGIN
                --if ((wIETER is null) or (wieter = '') or (Upper(wieter) = 'ISENTO')) then
                   BEGIN
                     wVALOR_CONTABIL_2_R14Aux = BDVLRCONT2;
                     wBASECALCULO_2_R14Aux = BDBASEICMS2;
                   /*end
                else
                   begin*/
                     wVALOR_CONTABIL_1_R14Aux = BDVLRCONT1;
                     wBASECALCULO_1_R14Aux = BDBASEICMS1;
                   END
             END

          wIMPOSTO_R14Aux = BDIMPOSTO_R14;
          wOUTRAS_R14Aux = BDOUTRAS_R14;
          wICMSCOBRADOST_R14Aux = BDICMSCOBRADOST_R14;
          wPETROLEOENERGIA_R14Aux = BDPETROLEOENERGIA_R14;
          wOUTROS_PRODUTOS_R14Aux = BDOUTROS_PRODUTOS_R14;

          wufauxant = BDUF_R14;
          BDUF_R14 = wufaux;
          BDVALOR_CONTABIL_1_R14 = wVALOR_CONTABIL_1_R14;
          BDBASECALCULO_1_R14 = wBASECALCULO_1_R14;
          BDVALOR_CONTABIL_2_R14 = wVALOR_CONTABIL_2_R14;
          BDBASECALCULO_2_R14 = wBASECALCULO_2_R14;
          BDIMPOSTO_R14 = wIMPOSTO_R14;
          BDOUTRAS_R14 = wOUTRAS_R14;
          BDICMSCOBRADOST_R14 = wICMSCOBRADOST_R14;
          BDPETROLEOENERGIA_R14 = wPETROLEOENERGIA_R14;
          BDOUTROS_PRODUTOS_R14 = wOUTROS_PRODUTOS_R14;

          SUSPEND;

          BDUF_R14 = wufauxant;
          BDVALOR_CONTABIL_1_R14 = wVALOR_CONTABIL_1_R14Aux;
          BDBASECALCULO_1_R14 = wBASECALCULO_1_R14Aux;
          BDVALOR_CONTABIL_2_R14 = wVALOR_CONTABIL_2_R14Aux;
          BDBASECALCULO_2_R14 = wBASECALCULO_2_R14Aux;
          BDIMPOSTO_R14 = wIMPOSTO_R14Aux;
          BDOUTRAS_R14 = wOUTRAS_R14Aux;
          BDICMSCOBRADOST_R14 = wICMSCOBRADOST_R14Aux;
          BDPETROLEOENERGIA_R14 = wPETROLEOENERGIA_R14Aux;
          BDOUTROS_PRODUTOS_R14 = wOUTROS_PRODUTOS_R14Aux;
        END

      BDCODEMP = WCODEMPBKP;
      bdnomemp = wnomempbkp;
      BDCODCONF = WCODCONFBKP;
      BDREFERENCIA = WREFERENCIABKP;
      BDNUMCAMPO = WNUMCAMPOBKP;
      BDCODQUADRO = WCODQUADROBKP;
      BDCLASSIFICACAO = WCLASSIFICACAOBKP;
      BDDESCFORM = WDESCFORMBKP;
      BDCODNAT = WCODNATBKP;
      BDVALOR = WVALORBKP;
      BDVLRCONT = WVLRCONTBKP;
      BDBASEICMS = WBASEICMSBKP;
      BDVLRICMS = WVLRICMSBKP;
      BDISENTASICMS = WISENTASICMSBKP;
      BDOUTRASICMS = WOUTRASICMSBKP;
      BDVLRST = WVLRSTBKP;
      BDIMPSUBSTITUTO = WIMPSUBSTITUTOBKP;
      BDIMPSUBSTITUIDO = WIMPSUBSTITUIDOBKP;
      BDOUTROSIMPOSTOS = WOUTROSIMPOSTOSBKP;
      BDUF_R14 = WUF_R14BKP;
      BDVALOR_CONTABIL_1_R14 = WVALOR_CONTABIL_1_R14BKP;
      BDBASECALCULO_1_R14 = WBASECALCULO_1_R14BKP;
      BDVALOR_CONTABIL_2_R14 = WVALOR_CONTABIL_2_R14BKP;
      BDBASECALCULO_2_R14 = WBASECALCULO_2_R14BKP;
      BDIMPOSTO_R14 = WIMPOSTO_R14BKP;
      BDOUTRAS_R14 = WOUTRAS_R14BKP;
      BDICMSCOBRADOST_R14 = WICMSCOBRADOST_R14BKP;
      BDPETROLEOENERGIA_R14 = WPETROLEOENERGIA_R14BKP;
      BDOUTROS_PRODUTOS_R14 = WOUTROS_PRODUTOS_R14BKP;
      BDCODIGO_R20 = WCODIGO_R20BKP;
      BDOPERACAO_R20 = WOPERACAO_R20BKP;
      BDFUNLEGAL_R20 = WFUNLEGAL_R20BKP;
      BDDESCRICAO_R20 = WDESCRICAO_R20BKP;
      BDINSCESTREM_R25 = WINSCESTREM_R25BKP;
      BDCODAUTORIZACAO_R28 = WCODAUTORIZACAO_R28BKP;

      --wcontador = 1;
      BDCODNAT = wcodnataut;
      wVLRCONT = BDVALOR;
      wBASEICMS = 0;
      wVLRICMS = 0;
      wISENTASICMS = 0;
      wOUTRASICMS = 0;
      wVLRST = 0;
      wIMPSUBSTITUTO = 0;
      wIMPSUBSTITUIDO = 0;
      wOUTROSIMPOSTOS = 0;
    END

    wcontador = wcontador + 1;
    wcodnatant = BDCODNAT;

  END

  wsqloco = 'select t.BDCODEMP, NULL BDNOMEMP,NULL bdCODCONF,t.BDREFERENCIA, NULL BDNUMCAMPO, NULL BDCODQUADRO,NULL bdclassificacao, NULL bddescform,NULL BDCODNAT, BDVALOR,';
  wsqloco = wsqloco||' NULL BDVLRCONT,NULL BDBASEICMS,NULL BDVLRICMS,NULL BDISENTASICMS,NULL BDOUTRASICMS,NULL BDVLRST,NULL BDIMPSUBSTITUTO,NULL BDIMPSUBSTITUIDO,NULL BDOUTROSIMPOSTOS, ';
  wsqloco = wsqloco||' NULL BDSIGLAUF,NULL BDTIPORETENT,NULL BDVLRCONTAB,null BDVLRCONTAB2,NULL BDBASEICMS,NULL BDBASEICMS2,NULL BDVLRICMS,NULL BDOUTRASICMS,NULL BDVLRST,NULL bdicmsret,NULL BDOUTROSIMPOSTOS, ';
  wsqloco = wsqloco||' l.bdcodigo, l.bdoperacao -1 bdoperacao, IIF(SUBSTRING(REVERSE(L.BDCODIGO) FROM 1 FOR 2) = ''99'', T.BDOBSERVACAO, l.bdfunlegal) bdfunlegal, L.BDDESCRICAO BDDESCRICAO, ';
  wsqloco = wsqloco||' T.BDINSCESTREM, T.BDCODAUTORIZACAO, T.BDNRDOC ';
  wsqloco = wsqloco||' from ( ';
  wsqloco = wsqloco||'       select T.BDCODEMP, T.BDCODTIPOOCOGIA, T.BDCODLISOCOGIASP, T.BDREFERENCIA, T.BDINSCESTREM, ';
  wsqloco = wsqloco||'              T.BDCODAUTORIZACAO, SUM(COALESCE(T.BDVALOR, 0)) BDVALOR, T.BDNRDOC, T.BDOBSERVACAO ';
  wsqloco = wsqloco||'       from VEF_EMP_TMOVOCO_GIASP t ';
  --Solicitação #162864 / Exportação - GIA, foi comentado IF abaixo pois agora estamos exportando uma empresa por arquivo, caso o IF abaixo,
  --não for comentado o WCODEMPBKP sempre vai trazer a última empresa dos SQL's executados acima, por exemplo temos 3 empresas, 1, 2 e 3.
  --Nesse caso vai sempre trazer a empresa 3 fazendo com que as empresas 1 e 2 possivelmente fiquem sem r25, r27 e r28
  --IF (WCODEMPBKP IS NOT NULL) THEN
  --  wsqloco = wsqloco||' where t.bdcodemp = '||WCODEMPBKP;
  --ELSE
  IF (:PRCODEMP IS NOT NULL) THEN
     wsqloco = wsqloco||' where '||:PRCODEMP;

  --Solicitação #162864 / Exportação - GIA, foi comentado IF abaixo pois agora estamos exportando uma empresa por arquivo, caso o IF abaixo,
  --não for comentado o WREFERENCIABKP sempre vai trazer a última referência dos SQL's executados acima, por exemplo temos 3 empresas, 1, 2 e 3.
  --Nesse caso vai sempre trazer a referência da empresa 3 fazendo com que as empresas 1 e 2 possivelmente fiquem sem r25, r27 e r28
  --IF(WREFERENCIABKP IS NOT NULL) THEN
   --  wsqloco = wsqloco||' and t.bdreferencia = '||WREFERENCIABKP;
  --ELSE
  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       wsqloco = wsqloco||' and t.BDREFERENCIA >= '||:pranomesinicial;
       wsqloco = wsqloco||' and t.BDREFERENCIA <= '||:pranomesfinal;
     END
  wsqloco = wsqloco||'       group by T.BDCODEMP, T.BDCODTIPOOCOGIA, T.BDCODLISOCOGIASP, T.BDREFERENCIA, ';
  wsqloco = wsqloco||'                T.BDINSCESTREM, T.BDCODAUTORIZACAO, T.BDNRDOC, T.BDOBSERVACAO ';

  wsqloco = wsqloco|| ') t ';
  wSqlOco = wSqlOco|| ' LEFT OUTER JOIN VEF_BASE_TTAB_LISTAOCO_GIASP L ON(L.BDCODLISOCOGIASP = T.BDCODLISOCOGIASP) ';
  wsqloco = wsqloco|| ' order by t.bdcodemp, t.bdreferencia, l.bdcodigo, l.bdoperacao, t.BDINSCESTREM, t.BDNRDOC ';

  FOR EXECUTE STATEMENT wsqloco
  INTO
    BDCODEMP,
    bdnomemp,
    BDCODCONF ,
    BDREFERENCIA ,
    BDNUMCAMPO ,
    BDCODQUADRO,
    BDCLASSIFICACAO ,
    BDDESCFORM ,
    BDCODNAT,
    BDVALOR,
    BDVLRCONT,
    BDBASEICMS,
    BDVLRICMS,
    BDISENTASICMS,
    BDOUTRASICMS,
    BDVLRST,
    BDIMPSUBSTITUTO,
    BDIMPSUBSTITUIDO,
    BDOUTROSIMPOSTOS,
    BDUF_R14 ,
    WTIPORETENT,
    BDVALOR_CONTABIL_1_R14 ,
    BDBASECALCULO_1_R14,
    BDVALOR_CONTABIL_2_R14,
    BDBASECALCULO_2_R14,
    BDIMPOSTO_R14,
    BDOUTRAS_R14,
    BDICMSCOBRADOST_R14,
    BDPETROLEOENERGIA_R14,
    BDOUTROS_PRODUTOS_R14,
    BDCODIGO_R20,
    BDOPERACAO_R20,
    BDFUNLEGAL_R20,
    BDDESCRICAO_R20,
    BDINSCESTREM_R25,
    BDCODAUTORIZACAO_R28,
    BDNRDOC
  DO
  BEGIN
    bddescform = 'R20';

    SUSPEND;

    IF ((BDCODIGO_R20 = 218) OR (BDCODIGO_R20 = 219) OR (BDCODIGO_R20 = 225) /*OR (BDCODIGO_R20 = 704)*/ OR (BDCODIGO_R20 = 705) OR
        (BDCODIGO_R20 = 706) OR (BDCODIGO_R20 = 707) OR (BDCODIGO_R20 = 729) OR (BDCODIGO_R20 = 730) OR (BDCODIGO_R20 = 747)) THEN
       BEGIN
          bddescform = 'R25';
          SUSPEND;
       END

    IF ((BDCODIGO_R20 IN (701, 702)) AND (BDOPERACAO_R20 = 1)) THEN /*ST*/
       BEGIN
          bddescform = 'R27';
          SUSPEND;
       END

    IF ((BDCODIGO_R20 = 220) OR (BDCODIGO_R20 = 221) OR (BDCODIGO_R20 = 223) OR (BDCODIGO_R20 = 740) OR (BDCODIGO_R20 = 741) OR (BDCODIGO_R20 = 744) OR (BDCODIGO_R20 = 745) OR (BDCODIGO_R20 = 749)) THEN
       BEGIN
          bddescform = 'R28';
          SUSPEND;
       END
  END
END^

/* Restore proc. body: VEF_SP_EXP_GISSONLINE */
ALTER PROCEDURE VEF_SP_EXP_GISSONLINE(PREMPRESAS VARCHAR(10000),
PRTIPOLANC SMALLINT,
PRDATAINI DATE,
PRDATAFIN DATE,
PRREFATUAL INTEGER,
PRIGNORACID varchar(5))
 RETURNS(BDCODEMP INTEGER,
BDCNPJEMP VARCHAR(18),
BDNOMEMP DM_BDNOMEMP,
BDCODCIDEMP INTEGER,
BDNUMDOCINI VARCHAR(15),
BDNUMDOCFIN VARCHAR(15),
BDSERIE VARCHAR(6),
BDDATAEMISSAO DATE,
BDVLRCONTAB NUMERIC(15,6),
BDCODMUNATVM VARCHAR(20),
BDCODLOCEXP VARCHAR(1),
BDCODTPNFEXP VARCHAR(2),
BDCODOBRA VARCHAR(10),
BDCONSTCIVIL VARCHAR(5),
BDCODTER INTEGER,
BDCGCTER VARCHAR(18),
BDNOMETER VARCHAR(100),
BDCEPTER VARCHAR(9),
BDLOGRTER DM_LOGRADOURO,
BDENDTER DM_BDENDERECO,
BDNUMTER DM_NUMEND,
BDCOMPTER DM_BDCOMPENDERECO,
BDBAITER VARCHAR(60),
BDCODCIDTER INTEGER,
BDIMTER VARCHAR(16),
BDIETER VARCHAR(20),
BDSIGLAUFTER VARCHAR(2),
BDNOMCIDTER VARCHAR(40),
BDCODENQFEDTER INTEGER,
BDTIPOREG VARCHAR(1),
BDTIPLAN VARCHAR(1),
BDCODSITNF INTEGER,
BDBCISSSER NUMERIC(15,2))
 AS
DECLARE VARIABLE WORDERBY VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(25000);
BEGIN
    /* BDTIPOREG
       1 : Serviço emitido para peessoa física
       2 : Serviço emitido para tomador fora do país
       3 : Serviço emitido para pessoa jurídica
       4 : Serviço tomado de prestador residente no país com nota fiscal*/
    EXECUTE PROCEDURE sp_seta_competencia(prrefatual, NULL, NULL);
  
    wSql = 'select temp.bdcodemp, ';
    wSql = wSql || 'temp.bdcnpjemp, ';
    wSql = wSql || 'trefemp.bdnomemp, ';
    wSql = wSql || 'trefemp.bdcodcid, ';
    wSql = wSql || 'tmovser.bdnumdocini, ';
    wSql = wSql || 'tmovser.bdnumdocfim, ';
    wSql = wSql || 'tmovser.bdserie, ';
    wSql = wSql || 'tmovser.bddataemissao, ';
    wSql = wSql || 'tmovseritens.bdvlrcontab, ';
    wSql = wSql || 'tatvm.bdcodmunatvm, ';
    WSQL = WSQL || 'coalesce(ttablocpreser.bdcodlocexp, case when trefemp.bdcodcid = tmovser.bdcodcid then ''D'' else ''F'' end) bdcodlocexp, ';
    wSql = wSql || 'ttabtpnf.bdcodtpnfexp, ';
    wSql = wSql || 'tgisson.bdcodobra, ';
    wSql = wSql || 'tgisson.bdconstcivil, ';
    wSql = wSql || 'vwterc.bdcodter, ';
    wSql = wSql || 'vwterc.bdcgcter, ';
    wSql = wSql || 'vwterc.bdnometer, ';
    wSql = wSql || 'vwterc.bdcepter, ';
    wSql = wSql || 'vwterc.bdlogrter, ';
    wSql = wSql || 'vwterc.bdendter, ';
    wSql = wSql || 'vwterc.bdnumter, ';
    wSql = wSql || 'vwterc.bdcompter, ';
    wSql = wSql || 'vwterc.bdbaiter, ';
    wSql = wSql || 'vwterc.bdcodcid, ';
    wSql = wSql || 'vwterc.bdimter, ';
    wSql = wSql || 'vwterc.bdieter, ';
    wSql = wSql || 'tufterc.bdsiglauf, ';
    wSql = wSql || 'tcidterc.bdnomcid, ';
    wSql = wSql || 'vwterc.bdenqsimplesfedter, ';
    wSql = wsql || 'tmovser.bdtiplan, ';
    wsql = wsql || ''''||'0'||''' as bdtiporeg, ';
    wSql = wSql || 'ttabtpnf.BDTIPONF, ';
    wSql = wSql || 'tmovseritens.BDBCISSSER ';
    wSql = wSql || 'from tempresas temp ';
    wSql = wSql || 'left outer join vw_empresas_ref_atual trefemp on (trefemp.bdCODEMP = temp.bdCODEMP) ';
    wSql = wSql || 'left outer join vef_emp_tmovser tmovser on (tmovser.bdcodemp = temp.bdCODEMP) ';
    wSql = wSql || 'left outer join vef_emp_tmovseritens tmovseritens on (tmovseritens.bdcodemp = tmovser.bdcodemp and tmovseritens.bdchave = tmovser.bdchave) ';
    wSql = wSql || 'left outer join vef_emp_tmovsergissonline tgisson on (tgisson.bdcodemp = tmovser.bdCodemp and tgisson.bdchave = tmovser.bdchave) ';
    wSql = wSql || 'left outer join vef_base_ttablocpreser ttablocpreser on (ttablocpreser.bdcodlocpreser = tgisson.bdcodlocpreser) ';
    wSql = wSql || 'left outer join vef_base_ttabtpnf ttabtpnf on (ttabtpnf.bdcodtpnf = tmovser.bdcodtpnf) ';
    wSql = wSql || 'left outer join vw_tterceiro vwterc on (vwterc.bdcodter = tmovser.bdcodter) ';
    wSql = wSql || 'left outer join tcidade tcidterc on (tcidterc.bdcodcid = vwterc.bdcodcid) ';
    wSql = wSql || 'left outer join tuf tufterc on (tufterc.bdcoduf = tcidterc.bdcoduf) ';
    wSql = wSql || 'left outer join tatvmunicipal tatvm on (tatvm.bdcodatvm = tmovseritens.bdcodatvm) ';

    --alt:7633 - não exportar notas que foram lançadas pela folha e não foram conferidas pela escrita
    wSql = wSql || 'left outer join ( ';
    wSql = wSql || '                 select statusaux.* from VEF_EMP_TMOVSERSTATUS statusaux ';
    wSql = wSql || '                 where exists( ';
    wSql = wSql || '                              select MAX(aux.bdordemstatus) bdmaxordem from VEF_EMP_TMOVSERSTATUS aux ';
    wSql = wSql || '                              where statusaux.bdcodemp = aux.bdcodemp and statusaux.bdchave = aux.bdchave ';
    wSql = wSql || '                              having statusaux.bdordemstatus = MAX(aux.bdordemstatus) ';
    wSql = wSql || '                             ) ';
    wSql = wSql || '                ) status on (status.bdcodemp = tmovser.bdcodemp and status.bdchave = tmovser.bdchave) ';
    wwhere = '((status.bdcodjus is null) or (status.bdcodjus <> 25)) and ';
  

    IF (prempresas IS NOT NULL) THEN
       wwhere = wWhere||prempresas||' ';
  
    IF (prdataini IS NOT NULL) THEN
       BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
  
         wwhere = wwhere||'tmovser.bddataemissao >= '||''''||prdataini||''''||' ';
       END
  
    IF (prdatafin IS NOT NULL) THEN
       BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
  
         wwhere = wwhere||'tmovser.bddataemissao <= '||''''||prdatafin||''''||' ';
       END
  

   /*prtipolanc       : 0- ambos     ; 1 - emitido  ; 2 - recebidos
     tmovser.bdtiplan : 0 - emitidos ; 1 - recebidos*/
   IF ((prtipolanc IS NOT NULL) AND (prTipoLanc > 0)) THEN
      BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
         IF (prtipolanc = 1) THEN
            wwhere = wWhere||' tmovser.bdtiplan = 0 ';
         ELSE
         IF (prtipolanc = 2) THEN
            wwhere = wWhere||' tmovser.bdtiplan = 1 ';
      END

   if (:PRIGNORACID = 'TRUE') then   
      BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
         wwhere = wWhere||' trefemp.bdcodcid <> vwterc.bdcodcid ';
      END


   IF (wwhere <> '') THEN
      wwhere = 'where '||wwhere||' ';

   /*definir na aplicação*/
   worderby = '';

   wsql = wsql||wwhere||worderby;
 
   FOR EXECUTE STATEMENT wsql
     INTO
        :bdcodemp,
        :bdcnpjemp,
        :bdnomemp,
        :bdcodcidemp,
        :bdnumdocini,
        :bdnumdocfin,
        :bdserie,
        :bddataemissao,
        :bdvlrcontab,
        :bdcodmunatvm,
        :bdcodlocexp,
        :bdcodtpnfexp,
        :bdcodobra,
        :bdconstcivil,
        :bdcodter,
        :bdcgcter,
        :bdnometer,
        :bdcepter,
        :bdlogrter,
        :bdendter,
        :bdnumter,
        :bdcompter,
        :bdbaiter,
        :bdcodcidter,
        :bdimter,
        :bdieter,
        :bdsiglaufter,
        :bdnomcidter,
        :bdcodenqfedter,
        :bdtiplan,
        :bdtiporeg,
        :BDCODSITNF,
        :BDBCISSSER
     DO
      BEGIN
        IF (bdcodsitnf IN (2,3,4,5)) THEN
           BEGIN
              BDVLRCONTAB = 0;
              BDBCISSSER = 0;
           END

        IF ((strlen(bdcgcter) = 14) AND (UPPER(bdsiglaufter) <> 'EX') AND (bdtiplan = 0)) THEN
           bdtiporeg = 1;
        ELSE
        IF ((UPPER(bdsiglaufter) = 'EX') AND (bdtiplan = 0)) THEN
           bdtiporeg = 2;
        ELSE
        IF ((strlen(bdcgcter) = 18) AND (UPPER(bdsiglaufter) <> 'EX') AND (bdtiplan = 0)) THEN
           bdtiporeg = 3;
        ELSE
        IF ((UPPER(bdsiglaufter) <> 'EX') AND (bdtiplan = 1)) THEN
           bdtiporeg = 4;
        SUSPEND;
      END
END
^

/* Restore proc. body: VEF_SP_EXP_SPEDCONTRIBUICAO */
create or alter procedure VEF_SP_EXP_SPEDCONTRIBUICAO (
    PRCODEMP varchar(10000),
    PRDATAINI date,
    PRDATAFIN date,
    PREXPORTAPORSCP varchar(5))
returns (
    BDCODEMP integer,
    BDCNPJEMP varchar(18),
    BDCODBEM integer,
    NAT_BC_CRED varchar(2),
    IDENT_BEM_IMOB varchar(2),
    IND_ORIG_CRED integer,
    IND_UTIL_BEM_IMOB integer,
    MES_OPER_AQUIS varchar(6),
    VL_OPER_AQUIS numeric(18,2),
    VL_OPER_DEP numeric(18,2),
    PARC_OPER_NAO_BC_CRED numeric(18,2),
    VL_BC_CRED numeric(18,2),
    IND_NR_PARC integer,
    CST_PIS varchar(2),
    VL_BC_PIS numeric(18,2),
    ALIQ_PIS numeric(18,4),
    VL_PIS numeric(18,2),
    CST_COFINS varchar(2),
    VL_BC_COFINS numeric(18,2),
    ALIQ_COFINS numeric(18,4),
    VL_COFINS numeric(18,2),
    COD_CTA varchar(255),
    COD_PLAPADRAO integer,
    ANO integer,
    COD_CCUS varchar(1000),
    DESC_BEM_IMOB varchar(300),
    BDDATABAIXA date,
    BDDATORIAQUIBEM date,
    COD_CTA_REF varchar(60),
    COD_PLAPADRAOREF integer,
    NUMPARC integer,
    BDCODCCSPED integer,
    BDDEPDIARIA varchar(5),
    BDNUMDIAS integer,
    BDDEPDIADATA integer,
    BDDEPMESBAIXABEM varchar(5),
    BDCALCPATRIMONIO varchar(5),
    BDCTALON varchar(40),
    BDCODCTA integer,
    BDCODMATRIZ integer,
    BDCODEMPDEPRE integer)
as
declare variable WSQL varchar(30000);
declare variable WSUBSELECT varchar(30000);
declare variable WVALORBASECALCATIVA numeric(18,2);
declare variable WDATAAUX varchar(10);
declare variable WDATAINI varchar(10);
declare variable WDATAFIN varchar(10);
declare variable WSEPARADOR varchar(1);
declare variable WTIPOAPROCRED integer;
declare variable WCOD_PLA_PADRAO_REF integer;
declare variable WCODNRPARC integer;
declare variable WCONTACONTABF120 DM_BOOLEAN;
declare variable COD_CTAN integer;
declare variable COD_PLAPADRAON integer;
declare variable COD_CTA_REFN integer;
declare variable BDCTALONN varchar(40);
declare variable COD_PLAPADRAOREFN integer;
BEGIN
  WDATAAUX = CAST(PRDATAINI AS VARCHAR(10));
  EXECUTE PROCEDURE sp_seta_competencia(CAST(SUBSTRING(WDATAAUX FROM 1 FOR 4) || SUBSTRING(WDATAAUX FROM 6 FOR 2) AS INTEGER));
  --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a versão com a alteração abaixo corretamente.
  WSEPARADOR = '/';
  WDATAINI = SUBSTRING(WDATAAUX FROM 6 FOR 2) || WSEPARADOR || SUBSTRING(WDATAAUX FROM 9 FOR 2) || WSEPARADOR || SUBSTRING(WDATAAUX FROM 1 FOR 4);

  WDATAAUX = CAST(PRDATAFIN AS VARCHAR(10));
  WDATAFIN = SUBSTRING(WDATAAUX FROM 6 FOR 2) || WSEPARADOR || SUBSTRING(WDATAAUX FROM 9 FOR 2) || WSEPARADOR || SUBSTRING(WDATAAUX FROM 1 FOR 4);

  WSUBSELECT = ' select tbem.*, ';
  --Sol. 22905 - Pega a data da primeira e ultima parcela, para verificar se o bem está no primeiro ou último mês, onde o cálculo é diferente
  WSUBSELECT = WSUBSELECT||   'dateadd(iif(TBEM.BDDEPDIADATA = 2, 0, -1) day to (CASE ';
  WSUBSELECT = WSUBSELECT||        'WHEN ((BDDEPMESAQUIBEM = ''TRUE'') and (BDDEPDIARIA <> ''TRUE'')) OR (tbem.BDTIPOAPROCRED = 0) THEN dateadd(tbem.BDNUMPARC - 1 month to tbem.BDDATORIAQUIBEM) ';
  WSUBSELECT = WSUBSELECT||        'else DATEADD(tbem.BDNUMPARC MONTH to tbem.BDDATORIAQUIBEM) ';
  WSUBSELECT = WSUBSELECT||    'end)) BDDTFIM,';
  WSUBSELECT = WSUBSELECT||   'dateadd(iif(TBEM.BDDEPDIADATA = 2, 0, -1) day to (CASE ';
  WSUBSELECT = WSUBSELECT||        'WHEN ((BDDEPMESAQUIBEM = ''TRUE'')) OR (tbem.BDTIPOAPROCRED = 0) THEN tbem.BDDATORIAQUIBEM ';
  WSUBSELECT = WSUBSELECT||        'else DATEADD(1 MONTH to tbem.BDDATORIAQUIBEM) ';
  WSUBSELECT = WSUBSELECT||    'end)) BDDTINI ';
  WSUBSELECT = WSUBSELECT||  ' from empresas_tbem tbem ';
  WSUBSELECT = WSUBSELECT||  ' INNER JOIN TMP_EMPRESAS_SELECT ON (TMP_EMPRESAS_SELECT.BDCODEMP = tbem.BDCODEMP) ';

  /*sol:15691 - deve trazer os registros sem data de baixa OU
               (se tiver baixa) todos que a baixa seja posterior ao periodo de apuração OU
               (se a baixa for menor que a data final da apuração) os registros em que o mes da baixa seja igual ao da apuração E estiver parametrizado para depreciar no mes da baixa
  WSUBSELECT = WSUBSELECT || ' and ((tbem.bddatabaixa is null) or (tbem.bddatabaixa > ''' || WDATAFIN || ''')) ';*/
  WSUBSELECT = WSUBSELECT || ' where ((tbem.bddatabaixa is null) or ';
  WSUBSELECT = WSUBSELECT || '      (tbem.bddatabaixa > ''' || WDATAFIN || ''') or ';
  WSUBSELECT = WSUBSELECT || '      ((BDDEPMESBAIXABEM = '||'''TRUE'''||') and (EXTRACT(MONTH FROM tbem.bddatabaixa) = EXTRACT(MONTH FROM cast(''' || WDATAFIN || ''' as date))) ';
  WSUBSELECT = WSUBSELECT || '                                             and (EXTRACT(YEAR FROM tbem.bddatabaixa)  = EXTRACT(YEAR FROM cast(''' || WDATAFIN || ''' as date))) and ';
  WSUBSELECT = WSUBSELECT || '      (tbem.bdtipoaprocred <> 0))) '; --sol:15691 - não levar no mes da baixa se for bdtipoaprocred = 0(10), que é do F130
--sol:15691 - obedecer o parametro BDDEPMESAQUIBEM que diz se deve depreciar no mes da aquisição ou no próximo
--WSUBSELECT = WSUBSELECT || ' and ((dateadd(tbem.bdnumparc - 1 month to tbem.bddatoriaquibem) >= ''' || WDATAINI || ''') and (tbem.bddatoriaquibem <= ''' || WDATAFIN || ''')) ';
  WSUBSELECT = WSUBSELECT || ' and (((case ';
  WSUBSELECT = WSUBSELECT || '          when ((BDDEPMESAQUIBEM = '||'''TRUE'''||') and (BDDEPDIARIA <> ''TRUE'')) or  (tbem.bdtipoaprocred = 0) then dateadd(TBEM.BDNUMPARC - 1 month to TBEM.BDDATORIAQUIBEM) ';
  WSUBSELECT = WSUBSELECT || '          else dateadd(TBEM.BDNUMPARC - 1 + 1 month to TBEM.BDDATORIAQUIBEM) ';
  WSUBSELECT = WSUBSELECT || '        end) >= ''' || WDATAINI || ''') ';
  WSUBSELECT = WSUBSELECT || ' and ((case ';
  WSUBSELECT = WSUBSELECT || '         when (BDDEPMESAQUIBEM = '||'''TRUE'''||') or (tbem.bdtipoaprocred = 0) then TBEM.BDDATORIAQUIBEM ';
  WSUBSELECT = WSUBSELECT || '         else dateadd(1 month to TBEM.BDDATORIAQUIBEM) ';
  WSUBSELECT = WSUBSELECT || '       end) <= ''' || WDATAFIN || ''')) ';
  --sol:15653 - somente se cst for diferente de 70
  WSUBSELECT = WSUBSELECT || ' and (tbem.bdcodcstpis <> 70) and (tbem.bdcodcstcof <> 70) ';


 /* WSQL = 'SELECT FIRST 1 tbem.BDCODPLAPADRAOREF ';
  WSQL = WSQL || '  FROM TEMPRESAS_REF tbem ';
  WSQL = WSQL || '  WHERE tbem.BDCODPLAPADRAOREF IS NOT NULL AND ';
  WSQL = WSQL || '    '||PRCODEMP||' AND ';
  WSQL = WSQL || '    tbem.BDREFEMP <= cast(''' || CAST(EXTRACT(YEAR FROM PRDATAINI) AS VARCHAR(4) ) || '''|| substring(''0''||'''||CAST(EXTRACT(MONTH FROM PRDATAINI) AS VARCHAR(2))||''' from (char_length(''0''||'''||CAST(EXTRACT(MONTH FROM PRDATAINI) AS VARCHAR(2))||''')-1)) as integer)';
  WSQL = WSQL || '  ORDER BY tbem.BDREFEMP DESC';*/
/*  WSQL = 'Select BDCODPLAPADRAOREF FROM vw_tempresas_ref tbem where ' || PRCODEMP;*/

  /*Sol: 21960 Patrick T. Sá 21/03/2018. Estava dando erro com o select acima porque o
    :PRCODEMP vinha com a matriz e filial, dando erro de multiple rows no into do select.
    Conforme visto com o Elizeu, deve pegar o plano da matriz*/
  wSQL =          'SELECT VW.BDCODPLAPADRAOREF ';
  wSQL = :wSQL || 'FROM ( ';
  wSQL = :wSQL || '      SELECT COALESCE(E.BDCODMATRIZ, E.BDCODEMP) BDCODMATRIZ ';
  wSQL = :wSQL || '      FROM vw_tempresas_ref tbem ';                                   
  wSQL = :wSQL || '      INNER JOIN TMP_EMPRESAS_SELECT ON (TMP_EMPRESAS_SELECT.BDCODEMP = tbem.BDCODEMP) ';
  wSQL = :wSQL || '      JOIN TEMPRESAS E ON(E.BDCODEMP = TBEM.BDCODEMP) ';
  wSQL = :wSQL || '      GROUP BY BDCODMATRIZ ';
  wSQL = :wSQL || '     ) EMP ';
  wSQL = :wSQL || 'JOIN VW_TEMPRESAS_REF VW ON(VW.BDCODEMP = EMP.BDCODMATRIZ) ';

  EXECUTE STATEMENT WSQL INTO WCOD_PLA_PADRAO_REF;

  WSQL = ' select ';
  WSQL = WSQL || '     COALESCE(EMPSCP.BDCODEMPSCP, BEM.BDCODEMP), ';
  WSQL = WSQL || '     emp.bdcnpjemp, ';
  WSQL = WSQL || '     bem.bdcodbem, ';

  WSQL = WSQL || '     case bem.bdtipoaprocred ';
  WSQL = WSQL || '         when 0 then ''10'' ';
  WSQL = WSQL || '         when 1 then ''09'' ';
  WSQL = WSQL || '         when 2 then ''11'' ';
  WSQL = WSQL || '     end NAT_BC_CRED, ';

  WSQL = WSQL || '     case bem.bdcodtipbem ';
  WSQL = WSQL || '         when 0 then ''01'' ';
  WSQL = WSQL || '         when 1 then ''03'' ';
  WSQL = WSQL || '         when 2 then ''04'' ';
  WSQL = WSQL || '         when 3 then ''05'' ';
  WSQL = WSQL || '         when 4 then ''06'' ';
  WSQL = WSQL || '         when 5 then ''99'' ';
  WSQL = WSQL || '     end IDENT_BEM_IMOB, ';

  WSQL = WSQL || '     case ';
  WSQL = WSQL || '         when bem.bdcodpais = 30 then 0 ';
  WSQL = WSQL || '         when bem.bdcodpais <> 30 and bem.bdcodpais is not null then 1 ';
  WSQL = WSQL || '     end IND_ORIG_CRED, ';

  WSQL = WSQL || '     case bem.bdcodutilbem ';
  WSQL = WSQL || '         when 0 then 1 ';
  WSQL = WSQL || '         when 1 then 2 ';
  WSQL = WSQL || '         when 2 then 3 ';
  WSQL = WSQL || '         when 3 then 9 ';
  WSQL = WSQL || '     end IND_UTIL_BEM_IMOB, ';

  WSQL = WSQL || '     substring(''0''||cast(extract(month from bem.bddatoriaquibem) as varchar(2)) from (char_length(''0''||cast(extract(month from bem.bddatoriaquibem) as varchar(2)))-1))||cast(extract(year from bem.bddatoriaquibem) as varchar(4)) MES_OPER_AQUIS, ';

  WSQL = WSQL || '    case bem.bdtipoaprocred ';
  WSQL = WSQL || '         when 0 then bem.BDVALAQUIBEMORIGINAL '; -- 1 - Valor da aquisição
  WSQL = WSQL || '         else bem.bdvalaquibem ';
  WSQL = WSQL || '    end VL_OPER_AQUIS, ';
  
--WSQL = WSQL || '     bem.bdbasecalc VL_OPER_DEP, ';   
  --Sol. 22905 - Faz a proporcao para o primeiro e ultimo mes, que dependerá dos parâmetros do bem, antes era feito na aplicação
  wSQL = wSQL||               'CASE WHEN (BDDEPDIARIA = ''TRUE'') THEN CASE WHEN ('||EXTRACT(YEAR FROM :PRDATAINI) || EXTRACT(MONTH FROM :PRDATAINI)||' = extract(year from BDDTINI) || extract(month from BDDTINI)) then cast(cast(BEM.BDBASECALC * (iif(BDNUMDIAS <= 1, 30, (select ULTDIA  from ULTIMO_DIA_MES(extract(month from BDDTINI), extract(year from BDDTINI)))) - iif((BDNUMDIAS <= 1) and ((extract(day from BDDTINI) ) > 30), 30, (extract(day from BDDTINI) ))) as numeric(15,3)) / iif(BDNUMDIAS <= 1, 30, (select ULTDIA from ULTIMO_DIA_MES(extract(month from BDDTINI), extract(year from BDDTINI)))) as numeric(15,2))';
  wSQL = wSQL||               '                                             WHEN ('||EXTRACT(YEAR FROM :PRDATAFIN) || EXTRACT(MONTH FROM :PRDATAFIN)||' = extract(year from BDDTFIM) || extract(month from BDDTFIM)) then cast(cast(BEM.BDBASECALC * (iif((BDNUMDIAS <= 1) and (extract(day from BDDTFIM) > 30), 30, extract(day from BDDTFIM) )) as numeric(15,3)) / iif(BDNUMDIAS <= 1, 30, (select ULTDIA from ULTIMO_DIA_MES(extract(month from BDDTFIM), extract(year from BDDTFIM)))) as numeric(15,2))';
  wSQL = wSQL||               '                                             ELSE BEM.BDBASECALC ';
  wSQL = wSQL||               '                                        END ';
  wSQL = wSQL||               '     ELSE BEM.BDBASECALC ';
  wSQL = wSQL||               'END VL_OPER_DEP, ';

  WSQL = WSQL || '     bem.bdexcbase PARC_OPER_NAO_BC_CRED, ';
  WSQL = WSQL || '     bem.bdbasecalc VL_BC_CRED, ';

  WSQL = WSQL || '     case bem.bdcodnrparc ';
  WSQL = WSQL || '         when 0 then 1 ';
  WSQL = WSQL || '         when 1 then 2 ';
  WSQL = WSQL || '         when 2 then 3 ';
  WSQL = WSQL || '         when 3 then 4 ';
  WSQL = WSQL || '         when 4 then 5 ';
  WSQL = WSQL || '         when 5 then 9 ';
  WSQL = WSQL || '     end IND_NR_PARC, ';

  WSQL = WSQL || '     pis.bdcstpis CST_PIS, ';
  WSQL = WSQL || '     0 vl_bc_pis, ';
  WSQL = WSQL || '     coalesce(bem.bdaliqpis, 0) ALIQ_PIS, ';
  WSQL = WSQL || '     0 vl_pis, ';

  WSQL = WSQL || '     cof.bdcstcof CST_COFINS, ';
  WSQL = WSQL || '     0 vl_bc_cofins, ';
  WSQL = WSQL || '     coalesce(bem.bdaliqcofins, 0) ALIQ_COFINS, ';
  WSQL = WSQL || '     0 vl_cofins, ';
                                                    
  WSQL = WSQL || '     bem.bdcodtpla as COD_CTA, ';
  WSQL = WSQL || '     bem.bdcodplapadrao as COD_PLAPADRAO, ';
--alt22357 - ajuste para pegar a data da tela ao inves da data de aquisição do bem
  WSQL = WSQL || '     ' || CAST(EXTRACT(YEAR FROM PRDATAINI) AS INTEGER ) || ' as ANO, ';
--  WSQL = WSQL || '     coalesce(ccle.bdano, cast(extract(year from bem.bddatoriaquibem) as Integer)) 2017 as ANO, ';
  WSQL = WSQL || '     bem.bdcodtpcc COD_CCUS, ';
  WSQL = WSQL || '     bem.bdnombem DESC_BEM_IMOB, ';
  WSQL = WSQL || '     bem.bddatabaixa, ';
  WSQL = WSQL || '     bem.bddatoriaquibem, ';   
  WSQL = WSQL || '     (CCLep.bdcodtplaref) COD_CTA_REF, ';
  WSQL = WSQL || '     (cclep.bdcodplapadraoref) COD_PLAPADRAOREF, ';

  WSQL = WSQL || '     case ';
  WSQL = WSQL || '         when (bem.bdtipoaprocred = 0) and (bem.bdcodnrparc = 0) then 1 ';
  WSQL = WSQL || '         when (bem.bdtipoaprocred = 0) and (bem.bdcodnrparc = 1) then 12 ';
  WSQL = WSQL || '         when (bem.bdtipoaprocred = 0) and (bem.bdcodnrparc = 2) then 24 ';
  WSQL = WSQL || '         when (bem.bdtipoaprocred = 0) and (bem.bdcodnrparc = 3) then 48 ';
  WSQL = WSQL || '         when (bem.bdtipoaprocred = 0) and (bem.bdcodnrparc = 4) then 6 ';
  WSQL = WSQL || '         else bem.bdnumparc ';
  WSQL = WSQL || '     end numparc, ';

  WSQL = WSQL || '     vefbem.bdcodccsped, ';
  WSQL = WSQL || '     bem.bdtipoaprocred, ';

  WSQL = WSQL || '     bem.BDDEPDIARIA, ';
  WSQL = WSQL || '     bem.BDNUMDIAS, ';
  WSQL = WSQL || '     bem.BDDEPDIADATA, ';
  WSQL = WSQL || '     bem.BDDEPMESBAIXABEM, ';
  WSQL = WSQL || '     CASE WHEN (exists (select dep.bdcodemp from EMPRESAS_TDEPRECIACAO dep where dep.bdcodemp = BEM.BDCODEMP and dep.bdcodbem = BEM.BDCODBEM)) THEN ''TRUE'' ELSE ''FALSE'' END bdcalcpatrimonio, ';
  WSQL = WSQL || '     bem.BDCODNRPARC, ';
  WSQL = WSQL || '     CCL.BDCTALON, ';
  WSQL = WSQL || '     CCL.BDCODTPLA as BDCODCTA, ';
  WSQL = WSQL || '     COALESCE(EMPSCP.BDCODEMPSCP, COALESCE(EMP.BDCODMATRIZ, BEM.BDCODEMP)) BDCODMATRIZ, BEM.BDCODEMP BDCODEMPDEPRE ';

  WSQL = WSQL || ' from (' || WSUBSELECT || ') bem ';

  WSQL = WSQL || ' left outer join planos_tpla ccl on (bem.BDCODPLAPADRAO = ccl.bdcodplapadrao and bem.bdcodtpla = ccl.bdcodtpla)';
  WSQL = WSQL || ' left outer join PLANOS_TPLA_ECF ccle on (ccle.bdcodplapadrao = ccl.bdcodplapadrao and ccle.bdcodtpla = ccl.bdcodtpla and ccle.bdcodplapadraoref '||IIF((WCOD_PLA_PADRAO_REF IS NULL), ' IS NULL ', ' = ' || WCOD_PLA_PADRAO_REF)||' and ';
  WSQL = WSQL || '                    ccle.bdano = (SELECT FIRST 1 BDANO ';
  WSQL = WSQL || '                                  FROM  PLANOS_TPLA_ECF ';
  --alt22357 - ajuste para pegar a data da tela ao inves da data de aquisição do bem
  WSQL = WSQL || '                                  WHERE BDANO <= ' || CAST(EXTRACT(YEAR FROM PRDATAINI) AS INTEGER ) || ' AND ';
--  WSQL = WSQL || '                                  WHERE BDANO <= cast(extract(year from bem.bddatoriaquibem) as Integer) AND ';
  WSQL = WSQL || '                                    BDCODTPLAREF IS NOT NULL AND ';
  WSQL = WSQL || '                                    CCLE.BDCODPLAPADRAO = BDCODPLAPADRAO AND ';
  WSQL = WSQL || '                                    CCLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF AND ';
  WSQL = WSQL || '                                    CCLE.BDCODTPLA = BDCODTPLA ';
  WSQL = WSQL || '                                  ORDER BY BDANO DESC)';
  WSQL = WSQL || '                                 ) ';
  WSQL = WSQL || ' left outer join vef_emp_tbem vefbem on ((vefbem.bdcodemp = bem.bdcodemp) and (vefbem.bdcodbem = bem.bdcodbem)) ';
  WSQL = WSQL || ' left outer join PLANOS_TPLA_ECF_PADRAO cclep on (ccle.BDCODPLAPADRAOref = cclep.BDCODPLAPADRAOREF and ccle.BDCODTPLAREF = cclep.BDCODTPLAREF)';
  WSQL = WSQL || ' left outer join vef_base_ttabcstpis pis on (pis.bdcodcstpis = bem.bdcodcstpis) ';
  WSQL = WSQL || ' left outer join vef_base_ttabcstcof cof on (cof.bdcodcstcof = bem.bdcodcstcof) ';
  WSQL = WSQL || ' left outer join TEMPRESAS_SCP EMPSCP on (''' || PREXPORTAPORSCP || ''' = ''TRUE'') and (EMPSCP.BDCODEMP = BEM.BDCODEMP) and (EMPSCP.BDREFEMP = BEM.BDREFSOC) and (EMPSCP.BDCODSCP = BEM.BDCODSCP) ';
  WSQL = WSQL || ' join tempresas emp on emp.bdcodemp = COALESCE(EMPSCP.BDCODEMPSCP, bem.bdcodemp) ';

  FOR EXECUTE STATEMENT WSQL 
  INTO
    :BDCODEMP,
    :BDCNPJEMP,
    :BDCODBEM,
    :NAT_BC_CRED,
    :IDENT_BEM_IMOB,
    :IND_ORIG_CRED,
    :IND_UTIL_BEM_IMOB,
    :MES_OPER_AQUIS,
    :VL_OPER_AQUIS,
    :VL_OPER_DEP,
    :PARC_OPER_NAO_BC_CRED,
    :VL_BC_CRED,
    :IND_NR_PARC,
    :CST_PIS,
    :VL_BC_PIS,
    :ALIQ_PIS,
    :VL_PIS,
    :CST_COFINS,
    :VL_BC_COFINS,
    :ALIQ_COFINS,
    :VL_COFINS,
    :COD_CTA,
    :COD_PLAPADRAO,
    :ANO,
    :COD_CCUS,
    :DESC_BEM_IMOB,
    :BDDATABAIXA,
    :BDDATORIAQUIBEM,
    :COD_CTA_REF,
    :COD_PLAPADRAOREF,
    :NUMPARC,
    :BDCODCCSPED,
    :WTIPOAPROCRED,
    :BDDEPDIARIA,
    :BDNUMDIAS,
    :BDDEPDIADATA,
    :BDDEPMESBAIXABEM,
    :BDCALCPATRIMONIO,
    :wCODNRPARC,
    :BDCTALON,
    :BDCODCTA,
    :BDCODMATRIZ,
    :BDCODEMPDEPRE
  DO
    BEGIN
      /*pega o valor do calculo de depreciação do ATIVA para o registro F120*/
      WSQL = 'select coalesce(PRDEPRECIACAOPERIODO, 0) PRDEPRECIACAOPERIODO from ';
      WSQL = WSQL || 'sp_cons_calc_dep(' || :BDCODEMPDEPRE || ', ' || :BDCODBEM || ', ''' || :PRDATAINI || ''', ''' || :PRDATAFIN || ''', 0,0)';
      EXECUTE STATEMENT WSQL 
          INTO WVALORBASECALCATIVA;
  
      /*se for registro do F130*/
      IF (:NAT_BC_CRED = '10') THEN
        BEGIN
          IF (:wtipoaprocred <> 0) THEN
            BEGIN
              VL_BC_CRED = :VL_OPER_AQUIS - :PARC_OPER_NAO_BC_CRED;
              VL_BC_PIS = VL_BC_CRED;
              VL_BC_COFINS = VL_BC_CRED;
            END
        END
      ELSE
        BEGIN
          /*se for F120 verifica qual valor esta preenchido, bdbasecalc (cadbem) ou o calculo do ATIVA para a depreciação*/
          /*Sol. 22905 Gabriel Ariel (06/03/2018) - Estava levando o valor da depreciacao apenas quando fosse menor que o valor da base, o que não é correto*/
          if (BDCALCPATRIMONIO = 'TRUE') then
            VL_OPER_DEP = WVALORBASECALCATIVA;

          IF (:VL_OPER_DEP = :WVALORBASECALCATIVA) THEN
            BDCALCPATRIMONIO = 'TRUE';
    
          /*exclusão da base dividido pelo numero de parcelas*/
          PARC_OPER_NAO_BC_CRED = :PARC_OPER_NAO_BC_CRED / :NUMPARC;
    
          /*Base de calculo dividido pelo numero de parcelas menos a exclusão da base*/
          VL_BC_CRED =(:VL_OPER_DEP / :NUMPARC) - :PARC_OPER_NAO_BC_CRED;
        END 
  
      /*Base de calc PIS e Cofins dividido pelo numero de parcelas (para ambos os registros F120, F130)*/
      VL_BC_PIS = :VL_BC_CRED / :NUMPARC;
      VL_BC_COFINS = /*:VL_BC_COFINS*/:VL_BC_CRED / :NUMPARC;
  
      IF ((wTIPOAPROCRED = 0) AND (wCODNRPARC = 4)) THEN -- F130 / 5 - 6 Meses (Embalagens de bebidas frias)
        BEGIN
          VL_PIS    = :VL_BC_PIS * :ALIQ_PIS;
          VL_COFINS = :VL_BC_COFINS * :ALIQ_COFINS;
        END
      ELSE
        BEGIN
      VL_PIS = :VL_BC_PIS * :ALIQ_PIS / 100;
      VL_COFINS = :VL_BC_COFINS * :ALIQ_COFINS / 100;
        END

      /*se o centro de custos da aba EFD PIS/Cofins estiver vazio pegar o CC da aba EFD Fiscal*/
      COD_CCUS = IIF(:COD_CCUS IS NOT NULL, :COD_CCUS, 'i' ||(:BDCODCCSPED + 1));

      /*#129827 Se o cliente escolher pegar a conta da preparação do patrimonio, vamos setar as contas aqui novamente */
      SELECT BDCONTACONTABF120 /*CONTA CONTÁBIL */
      FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :BDCODEMPDEPRE
      INTO :WCONTACONTABF120;

      if ((:WCONTACONTABF120 = 'TRUE') AND (:NAT_BC_CRED <> '10')) then
         BEGIN
           SELECT FIRST 1 TIBE.BDDEPCREIBE, CCL.BDCODPLAPADRAO, (cclep.bdcodtplaref) COD_CTA_REF, (cclep.bdcodplapadraoref) COD_PLAPADRAOREF, CCL.BDCTALON
           FROM EMPRESAS_TIBE TIBE
           left outer join planos_tpla ccl on (TIBE.BDCODPLAPADRAO = ccl.bdcodplapadrao and TIBE.BDDEPCREIBE = ccl.bdcodtpla)
           left outer join PLANOS_TPLA_ECF ccle on (ccle.bdcodplapadrao = ccl.bdcodplapadrao and ccle.bdcodtpla = ccl.bdcodtpla
                                                    and ccle.bdcodplapadraoref = iif(:WCOD_PLA_PADRAO_REF IS NULL, NULL, :WCOD_PLA_PADRAO_REF) and
                                                    ccle.bdano = (SELECT FIRST 1 BDANO
                                                    FROM  PLANOS_TPLA_ECF
                                                    WHERE BDANO <= 2020 AND
                                                    BDCODTPLAREF IS NOT NULL AND
                                                    CCLE.BDCODPLAPADRAO = BDCODPLAPADRAO AND
                                                    CCLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF AND
                                                    CCLE.BDCODTPLA = BDCODTPLA
                                                    ORDER BY BDANO DESC)
                                                   )
           left outer join PLANOS_TPLA_ECF_PADRAO cclep on (ccle.BDCODPLAPADRAOref = cclep.BDCODPLAPADRAOREF and ccle.BDCODTPLAREF = CCLEP.BDCODTPLAREF)
           WHERE BDCODEMP = :BDCODEMPDEPRE AND
           TIBE.BDCODTPLA = :COD_CTA AND TIBE.BDCODPLAPADRAO = :COD_PLAPADRAO
           ORDER BY TIBE.BDCONTABILIZACAO -- Alt.: #147834 - Vai ordernar pelo campo "Contabilização" e trazer apenas o primeiro, pois devemos priorizar o "0 = Fiscal"...
           INTO :COD_CTAN,:COD_PLAPADRAON, :COD_CTA_REFN, :COD_PLAPADRAOREFN, :BDCTALONN;

           if (:COD_CTAN > 0) then
              BEGIN
                COD_CTA = :COD_CTAN;
                COD_PLAPADRAO = :COD_PLAPADRAON;
                COD_CTA_REF = :COD_CTA_REFN;
                BDCTALON  = :BDCTALONN;
                COD_PLAPADRAOREF = :COD_PLAPADRAOREFN;
              END

         END

      /*#129827*/

      SUSPEND;
    END
END
^

/* Restore proc. body: VEF_SP_EXP_TERCEIRO */
ALTER PROCEDURE VEF_SP_EXP_TERCEIRO(PREMPRESA VARCHAR(2048),
PRCODTER INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRWHERETER VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCODTER INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCGCTER VARCHAR(18),
BDREFEMP INTEGER,
BDAPELIDOTER VARCHAR(20),
BDNOMETER VARCHAR(100),
BDLOGRTER DM_LOGRADOURO,
BDENDTER DM_BDENDERECO,
BDNUMTER DM_NUMEND,
BDCOMPTER DM_BDCOMPENDERECO,
BDCEPTER VARCHAR(9),
BDBAITER DM_BDBAIRRO,
BDDDDTER VARCHAR(3),
BDFONETER DM_BDTELEFONE,
BDFAXTER DM_BDTELEFONE,
BDEMAILTER DM_BDEMAIL,
BDIETER VARCHAR(20),
BDDATACADTER DATE,
BDIMTER VARCHAR(16),
BDPRURALTER VARCHAR(5),
BDENQSIMPLESFEDTER INTEGER,
BDINSCSUFRAMATER VARCHAR(10),
BDCODGPS INTEGER,
BDCODCID INTEGER,
BDNOMCID VARCHAR(40),
BDCODPAIS INTEGER,
BDDESCPAIS VARCHAR(60),
BDDDDFAXTER VARCHAR(3),
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2))
 AS
DECLARE VARIABLE WSQLEMP VARCHAR(10240);
DECLARE VARIABLE WSQLTER VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WSQLCAD VARCHAR(10240);
BEGIN
    IF (pranomesfinal IS NOT NULL) THEN
        EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal,NULL,NULL);

    wsqlemp = 'select distinct(t.bdcodemp) ';
    wsqlemp = wsqlemp||' from tempresas t ';


  IF (:prempresa IS NOT NULL) THEN
     wsqlemp =   wsqlemp|| ' where ' || :prempresa;

    wsqlemp = wsqlemp||' order by t.bdcodemp asc ';

-- executa o sql das empresas
FOR EXECUTE STATEMENT wsqlemp
    INTO :bdcodemp  DO
  BEGIN

  wsqlter = '';
  wsqlter = wsqlter || ' select ENT.BDCODTER ';
  wsqlter = wsqlter || ' from vef_emp_tmovent ent ';

  wwhere = '';
  IF (prcodter IS NOT NULL AND prcodter <> 0) THEN
    wwhere = wwhere || ' ENT.bdcodTER = '||prcodter;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'ENT.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'ENT.BDREFLAN <= '||:pranomesfinal;

     END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';

  wwhere = wwhere||'ENT.BDCODEMP = '||:bdcodemp;

  IF (wwhere <> '') THEN
     wsqlter = wsqlter||' where '||wwhere;


-- inicio saidas.....................................

  wsqlter = wsqlter || ' union select SAI.BDCODTER ';
  wsqlter = wsqlter || ' from vef_emp_tmovsai sai ';

  wwhere = '';
  IF (prcodter IS NOT NULL AND prcodter <> 0) THEN
    wwhere = wwhere || ' SAI.bdcodTER = '||prcodter;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'SAI.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'SAI.BDREFLAN <= '||:pranomesfinal;

     END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';

  wwhere = wwhere||'SAI.BDCODEMP = '||:bdcodemp;

  IF (wwhere <> '') THEN
     wsqlter = wsqlter||' where '||wwhere;

-- inicio servicos.............................

  wsqlter = wsqlter || ' union select SER.BDCODTER ';
  wsqlter = wsqlter || ' from vef_emp_tmovser ser ';

  wwhere = '';
  IF (prcodter IS NOT NULL AND prcodter <> 0) THEN
    wwhere = wwhere || ' SER.bdcodTER = '||prcodter;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'SER.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'SER.BDREFLAN <= '||:pranomesfinal;

     END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';

  wwhere = wwhere||'SER.BDCODEMP = '||:bdcodemp;

  IF (wwhere <> '') THEN
     wsqlter = wsqlter||' where '||wwhere;

  FOR EXECUTE STATEMENT wsqlter
  INTO :BDCODTER DO

  BEGIN

    wsqlcad = '';
    wsqlcad = wsqlcad || ' select distinct ';
    wsqlcad = wsqlcad || ' TER.BDCODPLAPADRAO, ';
    wsqlcad = wsqlcad || ' TER.BDCODTPLA, ';
    wsqlcad = wsqlcad || ' TER.BDCGCTER, ';
    wsqlcad = wsqlcad || ' TER.BDREFEMP, ';
    wsqlcad = wsqlcad || ' TER.BDAPELIDOTER, ';
    wsqlcad = wsqlcad || ' TER.BDNOMETER, ';
    wsqlcad = wsqlcad || ' TER.BDLOGRTER, ';
    wsqlcad = wsqlcad || ' TER.BDENDTER, ';
    wsqlcad = wsqlcad || ' TER.BDNUMTER, ';
    wsqlcad = wsqlcad || ' TER.BDCOMPTER, ';
    wsqlcad = wsqlcad || ' TER.BDCEPTER, ';
    wsqlcad = wsqlcad || ' TER.BDBAITER, ';
    wsqlcad = wsqlcad || ' TER.BDDDDTER, ';
    wsqlcad = wsqlcad || ' TER.BDFONETER, ';
    wsqlcad = wsqlcad || ' TER.BDFAXTER, ';
    wsqlcad = wsqlcad || ' TER.BDEMAILTER, ';
    wsqlcad = wsqlcad || ' TER.BDIETER, ';
    wsqlcad = wsqlcad || ' TER.BDDATACADTER, ';
    wsqlcad = wsqlcad || ' TER.BDIMTER, ';
    wsqlcad = wsqlcad || ' TER.BDPRURALTER, ';
    wsqlcad = wsqlcad || ' TER.BDENQSIMPLESFEDTER, ';
    wsqlcad = wsqlcad || ' TER.BDINSCSUFRAMATER, ';
    wsqlcad = wsqlcad || ' TER.BDCODGPS, ';
    wsqlcad = wsqlcad || ' TER.BDCODCID, ';
    wsqlcad = wsqlcad || ' CID.bdnomcid, ';
    wsqlcad = wsqlcad || ' TER.BDCODPAIS, ';
    wsqlcad = wsqlcad || ' TER.BDDESCPAIS, ';
    wsqlcad = wsqlcad || ' TER.BDDDDFAXTER, ';
    wsqlcad = wsqlcad || ' CID.BDCODUF, ';
    wsqlcad = wsqlcad || ' UF.BDSIGLAUF ';
    wsqlcad = wsqlcad || ' from VW_TTERCEIRO ter ';
    wsqlcad = wsqlcad || ' left outer join tcidade CID';
    wsqlcad = wsqlcad || ' on (TER.BDCODCID = CID.bdCODCID)';
    wsqlcad = wsqlcad || ' left outer join tuf UF';
    wsqlcad = wsqlcad || ' on (CID.BDCODUF = UF.bdCODUF)';

    wwhere = '';
    wwhere = wwhere||'BDCODTER = '||:bdcodter;

    IF (wwhere <> '') THEN
       wsqlcad = wsqlcad||' where '||wwhere;

    FOR EXECUTE STATEMENT wsqlcad
    INTO
      :BDCODPLAPADRAO,
      :BDCODTPLA,
      :BDCGCTER,
      :BDREFEMP,
      :BDAPELIDOTER,
      :BDNOMETER,
      :BDLOGRTER,
      :BDENDTER,
      :BDNUMTER,
      :BDCOMPTER,
      :BDCEPTER,
      :BDBAITER,
      :BDDDDTER,
      :BDFONETER,
      :BDFAXTER,
      :BDEMAILTER,
      :BDIETER,
      :BDDATACADTER,
      :BDIMTER,
      :BDPRURALTER,
      :BDENQSIMPLESFEDTER,
      :BDINSCSUFRAMATER,
      :BDCODGPS,
      :BDCODCID,
      :bdnomcid,
      :BDCODPAIS,
      :bddescpais,
      :BDDDDFAXTER,
      :BDCODUF,
      :BDSIGLAUF
    DO
    SUSPEND;
  END

  END
END
^

/* Restore proc. body: VEF_SP_EXP_TNATOP */
ALTER PROCEDURE VEF_SP_EXP_TNATOP(PREMPRESA VARCHAR(2048),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODNAT INTEGER,
BDNOMENAT VARCHAR(255))
 AS
DECLARE VARIABLE wsqlnat VARCHAR(10240);
DECLARE VARIABLE wwhere VARCHAR(20000);
DECLARE VARIABLE wsqlcad VARCHAR(10240);
BEGIN


  IF (pranomesfinal IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal,NULL,NULL);


  -- naturezas usadas no movimento de ENTRADAS...

  wsqlnat = '';
  wsqlnat = wsqlnat || ' select t.bdcodemp, t.bdcodnat  ';
  wsqlnat = wsqlnat || ' from vef_emp_tmoventitens t, vef_emp_tmovent mov  ';

  wwhere = '';

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN <= '||:pranomesfinal;

     END

  IF (:prempresa IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere || :prempresa;
    END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';
  ELSE
    wwhere = wwhere||' ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';

  IF (wwhere <> '') THEN
     wsqlnat = wsqlnat||' where '||wwhere ;

  -- naturezas usadas no movimento de SAIDAS...

  wsqlnat = wsqlnat || ' union select t.bdcodemp, t.bdcodnat  ';
  wsqlnat = wsqlnat || ' from vef_emp_tmovsaiitens t, vef_emp_tmovsai mov  ';

  wwhere = '';

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN <= '||:pranomesfinal;

     END

  IF (:prempresa IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere || :prempresa;
    END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';
  ELSE
    wwhere = wwhere||' ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';

  IF (wwhere <> '') THEN
     wsqlnat = wsqlnat||' where '||wwhere ;

  -- naturezas usadas no movimento de SERVICOS...

  wsqlnat = wsqlnat || ' union select t.bdcodemp, t.bdcodnat  ';
  wsqlnat = wsqlnat || ' from vef_emp_tmovseritens t, vef_emp_tmovser mov  ';

  wwhere = '';

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN <= '||:pranomesfinal;

     END

  IF (:prempresa IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere || :prempresa;
    END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';
  ELSE
    wwhere = wwhere||' ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';

  IF (wwhere <> '') THEN
     wsqlnat = wsqlnat||' where '||wwhere ;


  FOR EXECUTE STATEMENT wsqlnat
  INTO :bdcodemp, :bdcodnat DO

  BEGIN

    wsqlcad = '';
    wsqlcad = wsqlcad || ' select  ';
    wsqlcad = wsqlcad || ' tnatop.bdnomenat ';
    wsqlcad = wsqlcad || ' from vef_base_tnatop tnatop';

    wwhere = '';

    wwhere = wwhere||'TNATOP.BDCODNAT = '||:bdcodnat;

    IF (wwhere <> '') THEN
       wsqlcad = wsqlcad||' where '||wwhere;

    FOR EXECUTE STATEMENT wsqlcad
    INTO
      :bdnomenat
    DO

    SUSPEND;


  END

END
^

/* Restore proc. body: VEF_SP_EXP_TPRODUTOS */
ALTER PROCEDURE VEF_SP_EXP_TPRODUTOS(PREMPRESA VARCHAR(2048),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODPROD INTEGER,
BDNOMEPROD VARCHAR(255))
 AS
DECLARE VARIABLE WSQLPRO VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WSQLCAD VARCHAR(10240);
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WDATAINI VARCHAR(10);
DECLARE VARIABLE WDATAFIM VARCHAR(10);
DECLARE VARIABLE WAUX INTEGER;
BEGIN


  IF (pranomesfinal IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal,NULL,NULL);

 wmes = CAST(SUBSTRING(CAST(pranomesfinal AS VARCHAR(6)) FROM 5) AS SMALLINT);
 wano = CAST(SUBSTRING(CAST(pranomesfinal AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
 SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO waux;

 wdataini = SUBSTRING(CAST(pranomesinicial AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(pranomesinicial AS VARCHAR(6)) FROM 1 FOR 4);
 wdatafim = SUBSTRING(CAST(pranomesfinal AS VARCHAR(6)) FROM 5)||'/'||
             waux|| '/'||SUBSTRING(CAST(pranomesfinal AS VARCHAR(6)) FROM 1 FOR 4);



  -- produtos usados no movimento de ENTRADAS...

  wsqlpro = '';
  wsqlpro = wsqlpro || ' select t.bdcodemp, t.bdcodprod  ';
  wsqlpro = wsqlpro || ' from vef_emp_tmovproent t,  vef_emp_tmovent mov  ';

  wwhere = '';

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN <= '||:pranomesfinal;

     END

  IF (:prempresa IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere || :prempresa;
    END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';
  ELSE
    wwhere = wwhere||' ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and (MOV.bdcodsitnf not in (2,3,4,5)) ';
  ELSE
    wwhere = wwhere||' (MOV.bdcodsitnf not in (2,3,4,5)) ';

  IF (wwhere <> '') THEN
     wsqlpro = wsqlpro||' where '||wwhere ;

  -- produtos usados no movimento de saidas...

  wsqlpro = wsqlpro || ' union select t.bdcodemp, t.bdcodprod  ';
  wsqlpro = wsqlpro || ' from vef_emp_tmovprosai t, vef_emp_tmovsai mov  ';

  wwhere = '';

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'mov.BDREFLAN <= '||:pranomesfinal;

     END

  IF (:prempresa IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere || :prempresa;
    END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';
  ELSE
    wwhere = wwhere||' ((t.bdcodemp = MOV.bdcodemp) and (t.bdchave = MOV.bdchave)) ';

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and (MOV.bdcodsitnf not in (2,3,4,5)) ';
  ELSE
    wwhere = wwhere||' (MOV.bdcodsitnf not in (2,3,4,5)) ';

  IF (wwhere <> '') THEN
     wsqlpro = wsqlpro||' where '||wwhere ;


  -- produtos usados no movimento de reducao z...

  wsqlpro = wsqlpro || ' union select t.bdcodemp, t.bdcodprod     ';
  wsqlpro = wsqlpro || ' from VW_VEF_EMP_TREDZ_EXP_SVA t  ';

  wwhere = '';

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere|| ' BDDATAREDZ between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)';

     END

  IF (:prempresa IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere || :prempresa;
    END

  IF (wwhere <> '') THEN
     wsqlpro = wsqlpro||' where '||wwhere ;


  FOR EXECUTE STATEMENT wsqlpro
  INTO :bdcodemp, :bdcodprod DO

  BEGIN

    wsqlcad = '';
    wsqlcad = wsqlcad || ' select  ';
    wsqlcad = wsqlcad || ' bddescprod ';
    wsqlcad = wsqlcad || ' from TCADPRO_VINC ';

    wwhere = '';

    wwhere = wwhere||'BDCODEMP = '||:bdcodemp;

    wwhere = wwhere||' AND bdcodprod = '||:bdcodprod;

    IF (wwhere <> '') THEN
       wsqlcad = wsqlcad||' where '||wwhere;

    FOR EXECUTE STATEMENT wsqlcad
    INTO
      :bdnomeprod
    DO

    SUSPEND;
  END
END
^

/* Restore proc. body: VEF_SP_LANCAMENTOS */
ALTER PROCEDURE VEF_SP_LANCAMENTOS(PRREFMICRO INTEGER,
PRCODEMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDPERCISS NUMERIC(15,6),
BDRETINSS VARCHAR(5),
BDVLRMININSS NUMERIC(15,2),
BDCODPLANOONLINE INTEGER,
BDLANPROENT VARCHAR(5),
BDLANPROSAI VARCHAR(5),
BDLANBCICMSISEOUT INTEGER,
BDALIQINSS NUMERIC(7,4))
AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WPAR VARCHAR(50);
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);

  wSql = ' select ';

  wSql = wsql || 'Tref.BDCODEMP, ';
  wSql = wsql || 'trefsis.BDPERCISS, ';
  wSql = wsql || 'trefsis.BDALIQINSS, ';
  wSql = wsql || 'trefsis.BDRETINSS, ';
  wSql = wsql || 'trefsis.BDVLRMININSS, ';
  wSql = wsql || 'Tref.BDCODPLANOONLINE, ';
  wSql = wsql || 'trefsis.BDLANPROENT, ';
  wSql = wsql || 'trefsis.BDLANPROSAI, ';
  wSql = wsql || 'trefsis.BDLANBCICMSISEOUT ';

  WPAR = 'from vw_tempresas_ref tref';

  wSql = wsql || wpar;

  wSql = wsql || ' left outer join vw_VEF_BASE_TEMPPARGER TREFSIS on (TREFSIS.bdcodemp = tref.bdcodemp) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     wwhere = wwhere || ' tref.bdcodemp = '||prcodemp;

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By tref.BDCODEMP';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDPERCISS,
    :bdaliqinss,
    :BDRETINSS,
    :BDVLRMININSS,
    :BDCODPLANOONLINE,
    :BDLANPROENT,
    :BDLANPROSAI,
    :BDLANBCICMSISEOUT
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

CREATE OR ALTER PROCEDURE VEF_SP_REL_CONFERENCIA_ICMSST (
    PRCODEMP VARCHAR(2500),
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRTIPOLAN INTEGER,
    PRTOTAIS VARCHAR(5) = 'FALSE')
RETURNS (
    BDCODEMP INTEGER,
    BDCHAVE INTEGER,
    BDORDEM INTEGER,
    BDCODMOV INTEGER,
    BDMOVIMENTO VARCHAR(7),
    BDTIPOMOV VARCHAR(4),
    BDDATA DATE,
    BDDATAIMP VARCHAR(10),
    BDNUMDOCINI INTEGER,
    BDCODTER INTEGER,
    BDNOMETER VARCHAR(47),
    BDCODUFTER INTEGER,
    BDUFTER VARCHAR(2),
    BDCODNAT VARCHAR(9),
    BDVLRCONTAB NUMERIC(15,2),
    BDBASE NUMERIC(15,2),
    BDALIQ NUMERIC(7,4),
    BDVALOR NUMERIC(15,2),
    BDOUTRAS NUMERIC(15,2),
    BDVARALIQ VARCHAR(5),
    BDIMPLINHA VARCHAR(5))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCHAVEANTERIOR VARCHAR(50);
DECLARE VARIABLE WPREF VARCHAR(3000);
DECLARE VARIABLE WSUF VARCHAR(3000);
BEGIN
  wPref = '';
  wSuf  = '';
  IF (:prTOTAIS = 'TRUE') THEN
    BEGIN
      wPref =          'SELECT tot.bdCODEMP, NULL AS bdCHAVE, NULL AS bdORDEM, tot.bdCODMOV, NULL AS bdDATA, ';
      wPref = wPref || '       NULL AS bdDATAIMP, NULL AS bdNUMDOCINI, NULL AS bdCODTER, NULL AS bdNOMETER, tot.bdCODUFTER, tot.bdUFTER, ';
      wPref = wPref || '       NULL AS bdCODNAT, tot.bdTIPOICMS, SUM(tot.bdVLRCONTAB) AS bdVLRCONTAB, SUM(tot.bdBASE) AS bdBASE, NULL AS bdALIQ, ';
      wPref = wPref || '       SUM(tot.bdVALOR) AS bdVALOR, SUM(tot.bdOUTRAS) AS bdOUTRAS, NULL bdVARALIQ ';
      wPref = wPref || 'FROM ( ';
      
      wSuf =         '     ) tot ';
      wSuf = wSuf || 'GROUP BY tot.bdCODEMP, tot.bdCODMOV, tot.bdCODUFTER, tot.bdUFTER, tot.bdTIPOICMS ';
      wSuf = wSuf || 'ORDER BY tot.bdCODEMP, tot.bdCODMOV, tot.bdUFTER, tot.bdTIPOICMS ';
    END


  wSQL =         'SELECT aux.bdCODEMP, aux.bdCHAVE, aux.bdORDEM, aux.bdCODMOV, aux.bdDATAEMISSAO AS bdDATA, aux.bdDATAEMISSAO AS bdDATAIMP, aux.bdNUMDOCINI, aux.bdCODTER, ';
  wSQL = wSQL || '       SUBSTRING(aux.bdNOMETER FROM 1 FOR 47) AS bdNOMETER, aux.bdCODUFTER, aux.bdUFTER, aux.bdCODNAT, aux.bdTIPOICMS, ';
  wSQL = wSQL || '       aux.bdVLRCONTAB, aux.bdBASE, aux.bdALIQ, aux.bdVALOR, aux.bdOUTRAS, aux.bdVARALIQ ';
  wSQL = wSQL || 'FROM (';
  IF (prTIPOLAN IN (0,1)) THEN -- 1 - Ambos (entrada/saída) - 2 - Somente entradas
    BEGIN
      -- ICMS
      wSQL = wSQL || 'SELECT m.bdCODEMP, m.bdCHAVE, i.bdORDEM, 0 AS bdCODMOV, m.bdDATAEMISSAO, m.bdNUMDOCINI, m.bdCODTER, ';
      wSQL = wSQL || '       ter.bdNOMETER, ufTer.bdCODUF AS bdCODUFTER, ufTer.bdSIGLAUF AS bdUFTER, i.bdCODNAT, i.bdPREFIXONAT, ';
      wSQL = wSQL || '       i.bdVLRCONTAB, ';
      wSQL = wSQL || '       COALESCE(var.bdBASEREDICMS, i.bdBASEICMS) AS bdBASE, ';
      wSQL = wSQL || '       COALESCE(var.bdALIQICMS, i.bdALIQICMS) AS bdALIQ, ';
      wSQL = wSQL || '       COALESCE(var.bdVLRICMS, i.bdVLRICMS) AS bdVALOR, ';
      wSQL = wSQL || '       COALESCE(var.bdISENTASICMS, i.bdISENTASICMS, 0) + COALESCE(var.bdOUTRASICMS, i.bdOUTRASICMS, 0) AS bdOUTRAS, ';
      wSQL = wSQL || '       ''ICMS'' AS bdTIPOICMS, IIF(var.bdCODEMP IS NOT NULL, ''TRUE'', ''FALSE'') AS bdVARALIQ ';
      wSQL = wSQL || 'FROM (';
      wSQL = wSQL || '      SELECT mov.bdCODEMP, mov.bdCHAVE, mov.bdDATAENTRADAENT AS bdDATAEMISSAO, mov.bdCODTER, mov.bdNUMDOCINI ';
      wSQL = wSQL || '      FROM VEF_EMP_TMOVENT mov ';
      wSQL = wSQL || '      WHERE '||:prCODEMP||' ';
      wSQL = wSQL || '        AND mov.bdDATAENTRADAENT BETWEEN '''||:prDATAINI||''' AND '''||:prDATAFIM||'''';
      wSQL = wSQL || '        AND mov.BDCODSITNF NOT IN (2, 3, 4, 5) ';
      wSQL = wSQL || '      ) m ';
      wSQL = wSQL || 'JOIN VEF_EMP_TMOVENTITENS i ON (i.bdCODEMP = m.bdCODEMP AND i.bdCHAVE = m.bdCHAVE) ';
      wSQL = wSQL || 'LEFT OUTER JOIN VEF_EMP_TMOVENTVARALIQ var ON (var.bdCODEMP = i.bdCODEMP AND var.bdCHAVE = i.bdCHAVE AND var.bdORDEM = i.bdORDEM) ';
      wSQL = wSQL || 'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT) ';
      wSQL = wSQL || 'LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.BDCODTER = m.bdcodter) ';
      wSQL = wSQL || 'LEFT OUTER JOIN TCIDADE cidTer ON (cidTer.bdCODCID = ter.bdCODCID) ';
      wSQL = wSQL || 'LEFT OUTER JOIN TUF ufTer ON (ufTer.bdCODUF = cidTer.bdCODUF) ';
      wSQL = wSQL || 'WHERE  i.bdBASEICMS > 0 ';
      wSQL = wSQL || '   OR  i.bdALIQICMS > 0 ';
      wSQL = wSQL || '   OR  i.bdVLRICMS  > 0 ';
      wSQL = wSQL || '   OR  i.bdISENTASICMS > 0 ';
      wSQL = wSQL || '   OR i.bdOUTRASICMS > 0 ';
 
      wSQL = wSQL || 'UNION ALL ';
      -- ICMS ST
      wSQL = wSQL || 'SELECT m.bdCODEMP, m.bdCHAVE, i.bdORDEM, 0 AS bdCODMOV, m.bdDATAEMISSAO, m.bdNUMDOCINI, m.bdCODTER, ';
      wSQL = wSQL || '       ter.bdNOMETER, ufTer.bdCODUF AS bdCODUFTER, ufTer.bdSIGLAUF AS bdUFTER, i.bdCODNAT, i.bdPREFIXONAT, i.bdVLRCONTAB, ';
      wSQL = wSQL || '       i.bdBASEST AS bdBASE, i.bdALIQST AS bdALIQ, ';
      wSQL = wSQL || '       COALESCE(i.bdVALNTRIBST,0) AS bdVALOR, ';
      wSQL = wSQL || '       0 AS bdOUTRAS, ''ST'' AS bdTIPOICMS, ''FALSE'' AS bdVARALIQ  ';
      wSQL = wSQL || 'FROM (';
      wSQL = wSQL || '      SELECT mov.bdCODEMP, mov.bdCHAVE, mov.bdDATAENTRADAENT AS bdDATAEMISSAO, mov.bdCODTER, mov.bdNUMDOCINI ';
      wSQL = wSQL || '      FROM VEF_EMP_TMOVENT mov ';
      wSQL = wSQL || '      WHERE '||:prCODEMP||' ';
      wSQL = wSQL || '        AND mov.bdDATAENTRADAENT BETWEEN '''||:prDATAINI||''' AND '''||:prDATAFIM||'''';       
      wSQL = wSQL || '        AND mov.BDCODSITNF NOT IN (2, 3, 4, 5) ';
      wSQL = wSQL || '      ) m ';
      wSQL = wSQL || 'JOIN VEF_EMP_TMOVENTITENS i ON (i.bdCODEMP = m.bdCODEMP AND i.bdCHAVE = m.bdCHAVE) ';
      wSQL = wSQL || 'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT) ';
      wSQL = wSQL || 'LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.BDCODTER = m.bdcodter) ';
      wSQL = wSQL || 'LEFT OUTER JOIN TCIDADE cidTer ON (cidTer.bdCODCID = ter.bdCODCID) ';
      wSQL = wSQL || 'LEFT OUTER JOIN TUF ufTer ON (ufTer.bdCODUF = cidTer.bdCODUF) ';
      wSQL = wSQL || 'WHERE i.bdVALNTRIBST > 0 ';
    END
    
  IF (prTIPOLAN IN (0)) THEN -- 1 - Ambos (entrada/saída)
    wSQL = wSQL || '      UNION ALL ';
 
  IF (prTIPOLAN IN (0,2)) then -- 1 - Ambos (entrada/saída) - 3 - Somente saídas
    BEGIN
      -- ICMS
      wSQL = wSQL || 'SELECT m.bdCODEMP, m.bdCHAVE, i.bdORDEM, 1 AS bdCODMOV, m.bdDATAEMISSAO, m.bdNUMDOCINI, m.bdCODTER, ';
      wSQL = wSQL || '       ter.bdNOMETER, ufTer.bdCODUF AS bdCODUFTER, ufTer.bdSIGLAUF AS bdUFTER, i.bdCODNAT, i.bdPREFIXONAT, ';
      wSQL = wSQL || '       i.bdVLRCONTAB, ';
      wSQL = wSQL || '       COALESCE(var.bdBASEREDICMS, i.bdBASEICMS) AS bdBASE, ';
      wSQL = wSQL || '       COALESCE(var.bdALIQICMS, i.bdALIQICMS) AS bdALIQ, ';
      wSQL = wSQL || '       COALESCE(var.bdVLRICMS, i.bdVLRICMS) AS bdVALOR, ';
      wSQL = wSQL || '       COALESCE(var.bdISENTASICMS, i.bdISENTASICMS, 0) + COALESCE(var.bdOUTRASICMS, i.bdOUTRASICMS, 0) AS bdOUTRAS, ';
      wSQL = wSQL || '       ''ICMS'' AS bdTIPOICMS, IIF(var.bdCODEMP IS NOT NULL, ''TRUE'', ''FALSE'') AS bdVARALIQ ';
      wSQL = wSQL || 'FROM (';
      wSQL = wSQL || '      SELECT mov.bdCODEMP, mov.bdCHAVE, mov.BDDATAEMISSAO AS bdDATAEMISSAO, mov.bdCODTER, mov.bdNUMDOCINI ';
      wSQL = wSQL || '      FROM VEF_EMP_TMOVSAI mov ';
      wSQL = wSQL || '      WHERE '||:prCODEMP||' ';
      wSQL = wSQL || '        AND mov.BDDATAEMISSAO BETWEEN '''||:prDATAINI||''' AND '''||:prDATAFIM||'''';       
      wSQL = wSQL || '        AND mov.BDCODSITNF NOT IN (2, 3, 4, 5) ';
      wSQL = wSQL || '      ) m ';
      wSQL = wSQL || 'JOIN VEF_EMP_TMOVSAIITENS i ON (i.bdCODEMP = m.bdCODEMP AND i.bdCHAVE = m.bdCHAVE) ';
      wSQL = wSQL || 'LEFT OUTER JOIN VEF_EMP_TMOVSAIVARALIQ var ON (var.bdCODEMP = i.bdCODEMP AND var.bdCHAVE = i.bdCHAVE AND var.bdORDEM = i.bdORDEM) ';
      wSQL = wSQL || 'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT) ';
      wSQL = wSQL || 'LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.BDCODTER = m.bdcodter) ';
      wSQL = wSQL || 'LEFT OUTER JOIN TCIDADE cidTer ON (cidTer.bdCODCID = ter.bdCODCID) ';
      wSQL = wSQL || 'LEFT OUTER JOIN TUF ufTer ON (ufTer.bdCODUF = cidTer.bdCODUF) ';
      wSQL = wSQL || 'WHERE i.bdBASEICMS > 0 ';
      wSQL = wSQL || '   OR i.bdALIQICMS > 0 ';
      wSQL = wSQL || '   OR i.bdVLRICMS  > 0 ';
      wSQL = wSQL || '   OR i.bdISENTASICMS > 0 ';
      wSQL = wSQL || '   OR i.bdOUTRASICMS > 0 ';
 
      wSQL = wSQL || 'UNION ALL ';
      -- ICMS ST
      wSQL = wSQL || 'SELECT m.bdCODEMP, m.bdCHAVE, i.bdORDEM, 1 AS bdCODMOV, m.bdDATAEMISSAO, m.bdNUMDOCINI, m.bdCODTER, ';
      wSQL = wSQL || '       ter.bdNOMETER, ufTer.bdCODUF AS bdCODUFTER, ufTer.bdSIGLAUF AS bdUFTER, i.bdCODNAT, i.bdPREFIXONAT, i.bdVLRCONTAB, ';
      wSQL = wSQL || '       i.bdBASEST AS bdBASE, i.bdALIQST AS bdALIQ, ';
      wSQL = wSQL || '       COALESCE(i.bdVLRST,0)+COALESCE(i.bdFCPRETIDO,0) AS bdVALOR, ';
      wSQL = wSQL || '       0 AS bdOUTRAS, ''ST'' AS bdTIPOICMS, ''FALSE'' AS bdVARALIQ  ';
      wSQL = wSQL || 'FROM (';
      wSQL = wSQL || '      SELECT mov.bdCODEMP, mov.bdCHAVE, mov.BDDATAEMISSAO AS bdDATAEMISSAO, mov.bdCODTER, mov.bdNUMDOCINI ';
      wSQL = wSQL || '      FROM VEF_EMP_TMOVSAI mov ';
      wSQL = wSQL || '      WHERE '||:prCODEMP||' ';
      wSQL = wSQL || '        AND mov.BDDATAEMISSAO BETWEEN '''||:prDATAINI||''' AND '''||:prDATAFIM||'''';     
      wSQL = wSQL || '        AND mov.BDCODSITNF NOT IN (2, 3, 4, 5) ';
      wSQL = wSQL || '      ) m ';
      wSQL = wSQL || 'JOIN VEF_EMP_TMOVSAIITENS i ON (i.bdCODEMP = m.bdCODEMP AND i.bdCHAVE = m.bdCHAVE) ';
      wSQL = wSQL || 'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT) ';
      wSQL = wSQL || 'LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.BDCODTER = m.bdcodter) ';
      wSQL = wSQL || 'LEFT OUTER JOIN TCIDADE cidTer ON (cidTer.bdCODCID = ter.bdCODCID) ';
      wSQL = wSQL || 'LEFT OUTER JOIN TUF ufTer ON (ufTer.bdCODUF = cidTer.bdCODUF) ';
      wSQL = wSQL || 'WHERE i.bdVLRST > 0 OR i.bdFCPRETIDO > 0 ';
    END
 
  wSQL = wSQL || '     ) aux ';
  IF (:prTOTAIS <> 'TRUE') THEN
    wSQL = wSQL || 'ORDER BY aux.bdCODEMP, aux.bdCODMOV, aux.bdCODUFTER, aux.bdDATAEMISSAO, aux.bdCHAVE, aux.bdORDEM, aux.bdTIPOICMS ';

  wSQL = wPref || wSQL || wSuf;

  FOR
      EXECUTE STATEMENT :wSQL
      INTO :bdCODEMP, :bdCHAVE, :bdORDEM, :bdCODMOV, :bdDATA, :bdDATAIMP, :bdNUMDOCINI, :bdCODTER,
           :bdNOMETER, :bdCODUFTER, :bdUFTER, :bdCODNAT, :bdTIPOMOV,
           :bdVLRCONTAB, :bdBASE, :bdALIQ, :bdVALOR, :bdOUTRAS, :bdVARALIQ
  DO
    BEGIN
      bdIMPLINHA = 'TRUE';
      bdDATAIMP = LPAD(EXTRACT(DAY FROM :bdDATA),2,'0')||'/'||LPAD(EXTRACT(MONTH FROM :bdDATA),2,'0')||'/'||EXTRACT(YEAR FROM :bdDATA);
      bdCODNAT  = SUBSTRING(:bdCODNAT FROM 1 FOR 1)||'.'||SUBSTRING(:bdCODNAT FROM 2 FOR 3)||'-'||SUBSTRING(:bdCODNAT FROM 5 FOR 3);

      IF (bdCODMOV = 0) THEN
        bdMOVIMENTO = 'Entrada';
      ELSE
        bdMOVIMENTO = 'Saída';
                                        
      IF (:prTOTAIS <> 'TRUE') THEN
        BEGIN
      IF (wChaveAnterior = :bdCODEMP||'.'||:bdCHAVE||'.'||:bdORDEM) THEN
        bdIMPLINHA = 'FALSE';
    
      wChaveAnterior = :bdCODEMP||'.'||:bdCHAVE||'.'||:bdORDEM;
        END
      ELSE
        BEGIN
          IF (wChaveAnterior = :bdCODEMP||'.'||:bdCODMOV||'.'||:bdCODUFTER||'.'||:bdUFTER) THEN
            bdIMPLINHA = 'FALSE';
        
          wChaveAnterior = :bdCODEMP||'.'||:bdCODMOV||'.'||:bdCODUFTER||'.'||:bdUFTER;
        END
        
      SUSPEND;
    END
    
END
^

create or alter procedure SP_GET_R1050_ENVIADO (
    PRCODEMP integer,
    PRREFFIM integer,
    PRBDCNPJSCP varchar(21))
returns (
    BDEXISTE DM_BOOLEAN)
as
declare variable WCODEVT integer;
BEGIN

  SELECT FIRST 1 EVT.BDCODEVT
  FROM (
        SELECT FIRST 1 EVT.BDCODEVT, SUBSTRING(EVT.bdparametros FROM 31 for 18) BDCNPJSCP
        FROM VEF_REINF_EVT EVT
        WHERE EVT.BDCODEMP = :PRCODEMP
        AND EVT.BDCODTIPO = 24 /*R-1070*/
        AND EVT.BDCODSTATUS IN(1,2,3,9) 
        AND EVT.BDREFERENCIA <= :PRREFFIM
       ) EVT
  WHERE EVT.BDCNPJSCP = Coalesce(:PRBDCNPJSCP, '0')
  INTO :wCodEvt;

  IF (ROW_COUNT > 0) THEN
    BDEXISTE = 'TRUE';
  ELSE
    BDEXISTE = 'FALSE';

  SUSPEND;
END^


/* Restore proc. body: VEF_SP_RET_TOT_NAT_ENT */
ALTER PROCEDURE VEF_SP_RET_TOT_NAT_ENT(PRREF INTEGER,
PREMP INTEGER,
PRWHERE VARCHAR(20000))
 RETURNS(BDREFLAN INTEGER,
BDCODEMP INTEGER,
BDCODNAT INTEGER,
BDVLRCONTAB NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDIMPEXCLUIDAS NUMERIC(15,6),
BDOUTROSIMP NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDICMSRETENT NUMERIC(15,6),
BDDIFALIQENT NUMERIC(15,6))
 AS
DECLARE VARIABLE wsql VARCHAR(1000);
DECLARE VARIABLE wwhere VARCHAR(1000);
BEGIN

    wSql = ' select  ';
    wSql = wSql || 'TOT.BDREFLAN,';
    wSql = wSql || 'TOT.BDCODEMP,';
    wSql = wSql || 'TOT.BDCODNAT,';
    wSql = wSql || 'TOT.BDVLRCONTAB,';
    wSql = wSql || 'TOT.BDBASEICMS,';
    wSql = wSql || 'TOT.BDVLRICMS,';
    wSql = wSql || 'TOT.BDBASEIPI,';
    wSql = wSql || 'TOT.BDBASEST,';
    wSql = wSql || 'TOT.BDISENTASICMS,';
    wSql = wSql || 'TOT.BDISENTASIPI,';
    wSql = wSql || 'TOT.BDOUTRASICMS,';
    wSql = wSql || 'TOT.BDOUTRASIPI,';
    wSql = wSql || 'TOT.BDVLRIPI,';
    wSql = wSql || 'TOT.BDVLRST,';
    wSql = wSql || 'TOT.BDIMPEXCLUIDAS,';
    wSql = wSql || 'TOT.BDOUTROSIMP,';
    wSql = wSql || 'TOT.BDDESCONTO,';
    wSql = wSql || 'TOT.BDICMSRETENT,';
    wSql = wSql || 'TOT.BDDIFALIQENT';

    wSql = wsql || ' FROM vw_vef_tot_nat_ent TOT ';


    wwhere = '';
    IF (prEmp IS NOT NULL AND prEmp <> 0) THEN
       wwhere = wwhere || 'WHERE TOT.bdcodemp = '||prEmp;
    
    IF (prref IS NOT NULL)  THEN
       BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';

          wwhere = wwhere||' TOT.BDREFLAN = '||prref;
       END
    
    
    IF (prwhere IS NOT NULL AND prwhere <> '')  THEN
       BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';

         wwhere = wwhere ||prwhere;
       END

  WSQL = WSQL || wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDREFLAN,
    :BDCODEMP,
    :BDCODNAT,
    :BDVLRCONTAB,
    :BDBASEICMS,
    :BDVLRICMS,
    :BDBASEIPI,
    :BDBASEST,
    :BDISENTASICMS,
    :BDISENTASIPI,
    :BDOUTRASICMS,
    :BDOUTRASIPI,
    :BDVLRIPI,
    :BDVLRST,
    :BDIMPEXCLUIDAS,
    :BDOUTROSIMP,
    :BDDESCONTO,
    :BDICMSRETENT,
    :BDDIFALIQENT
 DO
  SUSPEND;

END
^

/* Restore proc. body: VEF_SP_RET_TOT_NAT_SAI */
ALTER PROCEDURE VEF_SP_RET_TOT_NAT_SAI(PRREF INTEGER,
PREMP INTEGER,
PRWHERE VARCHAR(20000))
 RETURNS(BDREFLAN INTEGER,
BDCODEMP INTEGER,
BDCODNAT INTEGER,
BDVLRCONTAB NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDIMPEXCLUIDAS NUMERIC(15,6),
BDOUTROSIMP NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDICMSFRETESAI NUMERIC(15,6),
BDACRECFINSAI NUMERIC(15,6))
 AS
DECLARE VARIABLE wsql VARCHAR(1000);
DECLARE VARIABLE wwhere VARCHAR(1000);
BEGIN

    wSql = ' select  ';
    wSql = wSql || 'TOT.BDREFLAN,';
    wSql = wSql || 'TOT.BDCODEMP,';
    wSql = wSql || 'TOT.BDCODNAT,';
    wSql = wSql || 'TOT.BDVLRCONTAB,';
    wSql = wSql || 'TOT.BDBASEICMS,';
    wSql = wSql || 'TOT.BDVLRICMS,';
    wSql = wSql || 'TOT.BDBASEIPI,';
    wSql = wSql || 'TOT.BDBASEST,';
    wSql = wSql || 'TOT.BDISENTASICMS,';
    wSql = wSql || 'TOT.BDISENTASIPI,';
    wSql = wSql || 'TOT.BDOUTRASICMS,';
    wSql = wSql || 'TOT.BDOUTRASIPI,';
    wSql = wSql || 'TOT.BDVLRIPI,';
    wSql = wSql || 'TOT.BDVLRST,';
    wSql = wSql || 'TOT.BDIMPEXCLUIDAS,';
    wSql = wSql || 'TOT.BDOUTROSIMP,';
    wSql = wSql || 'TOT.BDDESCONTO,';
    wSql = wSql || 'TOT.BDICMSFRETESAI,';
    wSql = wSql || 'TOT.BDACRECFINSAI';

    wSql = wsql || ' FROM vw_vef_tot_nat_sai TOT ';


    wwhere = '';
    IF (prEmp IS NOT NULL AND prEmp <> 0) THEN
       wwhere = wwhere || 'WHERE TOT.bdcodemp = '||prEmp;
    
    IF (prref IS NOT NULL)  THEN
       BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';

          wwhere = wwhere||' TOT.BDREFLAN = '||prref;
       END
    
    
    IF (prwhere IS NOT NULL AND prwhere <> '')  THEN
       BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';

         wwhere = wwhere ||prwhere;
       END

  WSQL = WSQL || wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDREFLAN,
    :BDCODEMP,
    :BDCODNAT,
    :BDVLRCONTAB,
    :BDBASEICMS,
    :BDVLRICMS,
    :BDBASEIPI,
    :BDBASEST,
    :BDISENTASICMS,
    :BDISENTASIPI,
    :BDOUTRASICMS,
    :BDOUTRASIPI,
    :BDVLRIPI,
    :BDVLRST,
    :BDIMPEXCLUIDAS,
    :BDOUTROSIMP,
    :BDDESCONTO,
    :BDICMSFRETESAI,
    :BDACRECFINSAI
 DO
  SUSPEND;

END
^

/* Restore proc. body: VEF_SP_RETORNA_DIME_Q47 */
create or alter procedure VEF_SP_RETORNA_DIME_Q47 (
    PRCODEMP varchar(2048),
    PRREFINI integer,
    PRREFFIM integer,
    PRSIMPLIFICADO integer)
returns (
    BDCODEMP integer,
    BDREF integer,
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDVALOR numeric(15,2),
    BDCODCIDTOT integer)
as
declare variable WSQL varchar(10480);
declare variable WWHERE varchar(10480);
declare variable VTOTCIDREF numeric(15,2);
declare variable WREFAUX integer;
declare variable WCODEMPAUX integer;
declare variable WCODEMPANT integer;
declare variable WREFANT integer;
declare variable WCODCIDANT integer;
declare variable WNOMCIDANT varchar(40);
declare variable WVALORANT numeric(15,2);
BEGIN

  IF (prreffim IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);
  ELSE
     EXECUTE PROCEDURE sp_seta_competencia(prrefini, NULL, NULL);

  IF (prsimplificado  IS NULL OR prsimplificado = 0) THEN
    BEGIN



      wsql = 'select ent.BDCODEMP, ent.BDREFLAN, ter.BDCODCID, CID.BDNOMCID, sum(ent.BDVLRCONTAB) BDVLRCONTAB ';
      wsql = wsql||' from ( ';
      wsql = wsql||'       select ent.bdcodemp,ent.bdreflan,ent.bdcodter,ITENS.BDVLRCONTAB ';
      wsql = wsql||'       FROM ( ';
      wsql = wsql||'           select bdcodemp,bdchave,bdreflan,bdcodter ';
      wsql = wsql||'           from VEF_EMP_TMOVENT ';
      IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN --Alt.: #6420 não estava validando se prcodemp era dif. de vazio, quando gerava DIME de todas as empresas não funcionava
         wwhere = ' where ' || :PRCODEMP;

      IF (wwhere <> '') THEN
         wwhere = wwhere||' and (BDREFLAN between '||prrefini||' and '||prreffim||') ';
      ELSE
         wwhere = ' where (BDREFLAN between '||prrefini||' and '||prreffim||') ';
--          where BDCODEMP = 67 and (BDREFLAN between 201607 and 201607)
      wsql = wsql|| wwhere;
      wsql = wsql||'           ) ENT ';
      wsql = wsql||'       JOIN VEF_EMP_TMOVENTITENS ITENS ON ENT.BDCODEMP = ITENS.BDCODEMP AND ENT.BDCHAVE = ITENS.BDCHAVE ';
      wsql = wsql||'       where cast(substring(itens.BDCODNAT from 1 for 4) as integer) in (1101, 1102, 1151, 1451, 1556, 1116, 1152) ';
      wsql = wsql||'     ) ent ';
      wsql = wsql||' LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = ent.BDCODTER) ';
      wsql = wsql||' LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = TER.BDCODCID) ';
      wsql = wsql||' where TER.BDPRURALTER = ''TRUE'' and cid.bdcoduf = 24 ';
      wsql = wsql||' GROUP BY ENT.BDCODEMP, ENT.BDREFLAN, TER.BDCODCID, CID.BDNOMCID ';
      wsql = wsql||' order by BDCODEMP, BDREFLAN, BDCODCID  ';

      vtotcidref = 0;
      wrefant = 0;
      wrefaux = 0;
      wcodempaux = 0;
      FOR EXECUTE STATEMENT wsql
          INTO :bdcodemp, :bdref, : bdcodcid, :bdnomcid, :bdvalor  DO
          BEGIN

            IF ((wrefaux <> bdref AND wrefaux > 0) OR (wcodempaux <> bdcodemp AND wcodempaux > 0))  THEN
              BEGIN
                wcodempant = bdcodemp;
                wrefant = bdref;
                wcodcidant = BDCODCID;
                wnomcidant = bdnomcid;
                wvalorant = bdvalor;

                bdcodemp = wcodempaux;
                bdref = wrefaux;
                bdcodcid = NULL;
                bdcodcidtot = 99999;
                bdnomcid = 'TOTALIZADOR';
                bdvalor = vtotcidref;
                SUSPEND;

                vtotcidref = 0;
                bdcodemp = wcodempant;
                bdref = wrefant;
                bdcodcid = wcodcidant;
                bdnomcid = wnomcidant;
                bdvalor = wvalorant;
                bdcodcidtot = NULL;

              END

            bdcodcidtot = NULL;
            wrefaux = bdref;
            wcodempaux = bdcodemp;
            vtotcidref = vtotcidref + bdvalor;

            SUSPEND;

          END

      IF (vtotcidref > 0) THEN
          BEGIN
            bdcodemp = bdcodemp;
            bdref = wrefaux;
            bdcodcid = NULL;
            bdcodcidtot = 99999;
            bdnomcid = 'TOTALIZADOR';
            bdvalor = vtotcidref;
            SUSPEND;
            vtotcidref = 0;
          END

    END
END^

CREATE OR ALTER procedure VEF_SP_RETORNA_DIME_Q48 (
    PRCODEMP varchar(2048),
    PRREFINI integer,
    PRREFFIM integer,
    PRSIMPLIFICADO integer)
returns (
    BDCODEMP integer,
    BDREF integer,
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDCODCIDTOT integer,
    BDALIMPREP varchar(5),
    BDCODEXP varchar(3),
    BDCODATIVQ48 varchar(3),
    BDVALOR numeric(15,2))
as
declare variable WSQL varchar(10480);
declare variable VTOTCIDREF numeric(15,2);
declare variable WREFAUX integer;
declare variable WCODEMPAUX integer;
declare variable WCODEMPANT integer;
declare variable WREFANT integer;
declare variable WCODCIDANT integer;
declare variable WNOMCIDANT varchar(40);
declare variable WVALORANT numeric(15,2);
declare variable WBDALIMPREPANT varchar(5);
declare variable WBDCODEXPANT varchar(3);
declare variable WBDCODATIVQ48ANT varchar(3);
BEGIN


  IF (prreffim IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);
  ELSE
     EXECUTE PROCEDURE sp_seta_competencia(prrefini, NULL, NULL);

  IF (prsimplificado  IS NULL OR prsimplificado = 0) THEN
    BEGIN

       wsql = '        select SAID.BDCODEMP, SAID.BDREFLAN, SAID.BDCODCID, SAID.BDNOMCID, null BDCODCIDTOT, BDALIMPREP, BDCODEXP, BDCODATIVQ48, ';
       wsql = wsql||'               sum(SAID.BDVLRCONTAB) BDVLRCONTAB ';
       wsql = wsql||'        from ( ';
       wsql = wsql||'             select S.BDCODEMP, S.BDREFLAN, s.BDCODCID, s.BDNOMCID, s.BDCODUF,S.BDVLRCONTAB, ALIM.BDALIMPREP, ';
       wsql = wsql||'                     case ';
       wsql = wsql||'                       when ALIM.BDALIMPREP = ''TRUE''then ''008''';
       wsql = wsql||'                       else Q48.BDCODEXP ';
       wsql = wsql||'                     end BDCODEXP, ';
       wsql = wsql||'                     Q48.BDCODATIVQ48 ';
       wsql = wsql||'              from ( ';
       wsql = wsql||'                     select mov.BDCODEMP, mov.BDREFLAN, Coalesce(Q48.BDCODCID,mov.BDCODCID) BDCODCID, CID.BDNOMCID, CID.BDCODUF, ITENS.BDCODNAT, ITENS.BDPREFIXONAT,nat.BDCODATIVQ48, ';
       wsql = wsql||'                             sum(Coalesce(Q48.BDVLRTOTALLIQUIDO,ITENS.BDVLRCONTAB)) BDVLRCONTAB ';
        
       wsql = wsql||'                      from ( ';
       wsql = wsql||'                            select S.BDCODEMP, S.BDCHAVE, S.BDREFLAN, S.BDCODTER, COALESCE(CID_D100.BDCODCID, CID_D160.BDCODCID, CID.BDCODCID) BDCODCID ';
       wsql = wsql||'                            from VEF_EMP_TMOVSAI S ';
       wsql = wsql||'                            LEFT OUTER JOIN VEF_EMP_TD100SAI D100 ON(D100.BDCODEMP = S.BDCODEMP AND D100.BDCHAVE = S.BDCHAVE) ';
       wsql = wsql||'                            LEFT OUTER JOIN VEF_EMP_TD160CARGATRANS D160 ON(D160.BDCODEMP = S.BDCODEMP AND D160.BDCHAVE = S.BDCHAVE AND D160.BDORDEMCARTRANS = (SELECT FIRST 1 D.BDORDEMCARTRANS FROM VEF_EMP_TD160CARGATRANS D WHERE D.BDCODEMP = S.BDCODEMP AND D.BDCHAVE = S.BDCHAVE ORDER BY D.BDORDEMCARTRANS)) ';
       wsql = wsql||'                            LEFT OUTER JOIN TCIDADE CID_D100 ON(CID_D100.BDCODCID = D100.BDCIDORIGEM AND CID_D100.BDCODUF = 24) ';
       wsql = wsql||'                            LEFT OUTER JOIN TCIDADE CID_D160 ON(CID_D160.BDCODCID = D160.BDCODCIDREMETENTE AND CID_D160.BDCODUF = 24) ';
       wsql = wsql||'                            LEFT OUTER JOIN TCIDADE CID ON(CID.BDCODCID = S.BDCODCID AND CID.BDCODUF = 24) ';
       wsql = wsql||'where (S.bdcodsitnf not in (2,3,4,5)) and (S.BDREFLAN between '||prrefini||' and '||prreffim||') ';
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          wsql = wsql||'and '||:prcodemp||'';
       wsql = wsql||'                            ) mov ';
       wsql = wsql||'                      join VEF_EMP_TMOVSAIITENS ITENS on (mov.BDCODEMP = ITENS.BDCODEMP and mov.BDCHAVE = ITENS.BDCHAVE) ';  
       wsql = wsql||'                      left outer join VEF_EMP_TMOVSAIQ48 Q48 on (Q48.BDCODEMP = ITENS.BDCODEMP AND Q48.BDCHAVE = ITENS.BDCHAVE AND Q48.BDORDEM = ITENS.BDORDEM) ';
--       wsql = wsql||'                      left outer join VW_TTERCEIRO TER on (TER.BDCODTER = mov.BDCODTER) ';
       wsql = wsql||'                      join TCIDADE CID on (CID.BDCODCID = Coalesce(Q48.BDCODCID,mov.BDCODCID) AND BDCODUF = 24 /* estado de SC*/) ';
       wsql = wsql||'                      left outer join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = ITENS.BDCODNAT) ';
       wsql = wsql||'                      group by mov.BDCODEMP, mov.BDREFLAN,ITENS.BDCODNAT,ITENS.BDPREFIXONAT,CID.BDCODUF, BDCODCID, CID.BDNOMCID,nat.BDCODATIVQ48 ';
       wsql = wsql||'                   )s ';
       wsql = wsql||'              left outer join VEF_BASE_TTABATIVQ48 Q48 on (s.BDCODATIVQ48 = Q48.BDCODATIVQ48) ';
       wsql = wsql||'              left outer join VW_VEF_BASE_TEMPPARESTSC ALIM on (ALIM.BDCODEMP = S.BDCODEMP) ';
       wsql = wsql||'              ) SAID ';
       wsql = wsql||'        group by SAID.BDCODEMP, SAID.BDREFLAN, SAID.BDCODCID, SAID.BDNOMCID, SAID.BDCODEXP, SAID.BDALIMPREP, BDCODCIDTOT, BDALIMPREP, BDCODEXP, BDCODATIVQ48 ';
       wsql = wsql||' union all ';
       wsql = wsql||'        select ENT.BDCODEMP, ENT.BDREFLAN, ENT.BDCODCID, ENT.BDNOMCID, null BDCODCIDTOT, BDALIMPREP, iif(BDCODEXP = 506, 507, BDCODEXP), BDCODATIVQ48, ';
       wsql = wsql||'               sum(ENT.BDVLRCONTAB) BDVLRCONTAB ';
       wsql = wsql||'        from ( ';
       wsql = wsql||'             select S.BDCODEMP, S.BDREFLAN, s.BDCODCID, s.BDNOMCID, s.BDCODUF,S.BDVLRCONTAB, ALIM.BDALIMPREP, ';
       wsql = wsql||'                     case ';
       wsql = wsql||'                       when ALIM.BDALIMPREP = ''TRUE''then ''008''';
       wsql = wsql||'                       else Q48.BDCODEXP ';
       wsql = wsql||'                     end BDCODEXP, ';
       wsql = wsql||'                     Q48.BDCODATIVQ48 ';
       wsql = wsql||'              from ( ';
       wsql = wsql||'                     select mov.BDCODEMP, mov.BDREFLAN, Coalesce(Q48.BDCODCID,mov.BDCODCID) BDCODCID, CID.BDNOMCID, CID.BDCODUF, ITENS.BDCODNAT, ITENS.BDPREFIXONAT, NAT.BDCODATIVQ48, ';
       wsql = wsql||'                             sum(Coalesce(Q48.BDVLRTOTALLIQUIDO,ITENS.BDVLRCONTAB)) BDVLRCONTAB ';
        
       wsql = wsql||'                      from ( ';
       wsql = wsql||'                            select S.BDCODEMP, S.BDCHAVE, S.BDREFLAN, S.BDCODTER, COALESCE(CID_D100.BDCODCID, CID_D160.BDCODCID) BDCODCID ';
       wsql = wsql||'                            from vef_emp_tmovent S ';
       wsql = wsql||'                            LEFT OUTER JOIN VEF_EMP_TD100SAI D100 ON(D100.BDCODEMP = S.BDCODEMP AND D100.BDCHAVE = S.BDCHAVE) ';
       wsql = wsql||'                            LEFT OUTER JOIN VEF_EMP_TD160CARGATRANS D160 ON(D160.BDCODEMP = S.BDCODEMP AND D160.BDCHAVE = S.BDCHAVE AND D160.BDORDEMCARTRANS = (SELECT FIRST 1 D.BDORDEMCARTRANS FROM VEF_EMP_TD160CARGATRANS D WHERE D.BDCODEMP = S.BDCODEMP AND D.BDCHAVE = S.BDCHAVE ORDER BY D.BDORDEMCARTRANS)) ';
       wsql = wsql||'                            LEFT OUTER JOIN TCIDADE CID_D100 ON(CID_D100.BDCODCID = D100.BDCIDORIGEM AND CID_D100.BDCODUF = 24) ';
       wsql = wsql||'                            LEFT OUTER JOIN TCIDADE CID_D160 ON(CID_D160.BDCODCID = D160.BDCODCIDREMETENTE AND CID_D160.BDCODUF = 24) ';
       wsql = wsql||'where (S.bdcodsitnf not in (2,3,4,5)) and (S.BDREFLAN between '||prrefini||' and '||prreffim||') ';
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          wsql = wsql||'and '||:prcodemp||'';
       wsql = wsql||'                            ) mov ';
       wsql = wsql||'                      join VEF_EMP_TMOVENTITENS ITENS on (mov.BDCODEMP = ITENS.BDCODEMP and mov.BDCHAVE = ITENS.BDCHAVE) ';
       wsql = wsql||'                      left outer join VEF_EMP_TMOVENTQ48 Q48 on (Q48.BDCODEMP = ITENS.BDCODEMP AND Q48.BDCHAVE = ITENS.BDCHAVE AND Q48.BDORDEM = ITENS.BDORDEM) ';
--       wsql = wsql||'                      left outer join VW_TTERCEIRO TER on (TER.BDCODTER = mov.BDCODTER) ';
       wsql = wsql||'                      join TCIDADE CID on (CID.BDCODCID = Coalesce(Q48.BDCODCID,mov.BDCODCID) AND BDCODUF = 24 /* estado de SC*/) ';
       wsql = wsql||'                      left outer join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = ITENS.BDCODNAT) ';
       wsql = wsql||'                      group by mov.BDCODEMP, mov.BDREFLAN,ITENS.BDCODNAT,ITENS.BDPREFIXONAT,CID.BDCODUF, BDCODCID, CID.BDNOMCID,nat.BDCODATIVQ48 ';
       wsql = wsql||'                   )s ';
       wsql = wsql||'              left outer join VEF_BASE_TTABATIVQ48 Q48 on (s.BDCODATIVQ48 = Q48.BDCODATIVQ48) ';
       wsql = wsql||'              left outer join VW_VEF_BASE_TEMPPARESTSC ALIM on (ALIM.BDCODEMP = S.BDCODEMP) ';
       wsql = wsql||'              ) ENT ';
       wsql = wsql||'        group by ENT.BDCODEMP, ENT.BDREFLAN, ENT.BDCODCID, ENT.BDNOMCID, ENT.BDCODEXP, ENT.BDALIMPREP, BDCODCIDTOT, BDALIMPREP, BDCODEXP, BDCODATIVQ48 '; 


      vtotcidref = 0;
      wrefaux = 0;
      wrefant = 0;
      wcodempaux = 0;

      FOR EXECUTE STATEMENT wsql
      INTO
        bdcodemp,
        bdref,
        bdcodcid,
        bdnomcid,
        bdcodcidtot,
        bdalimprep,
        bdcodexp,
        bdcodativq48,
        bdvalor DO
      BEGIN

        IF ((wrefaux <> bdref AND wrefaux > 0) OR (wcodempaux <> bdcodemp AND wcodempaux > 0))  THEN
          BEGIN
            wcodempant = bdcodemp;
            wrefant = bdref;
            wcodcidant = BDCODCID;
            wnomcidant = bdnomcid;
            wvalorant = bdvalor;
            wBDALIMPREPant = bdalimprep;
            wBDCODEXPant   = bdcodexp;
            wBDCODATIVQ48ant = bdcodativq48;


            bdcodemp = wcodempaux;
            bdref = wrefaux;
            bdcodcid = NULL;
            bdcodcidtot = 99999;
            bdnomcid = 'TOTALIZADOR';
            bdvalor = vtotcidref;
            IF (bdvalor > 0) THEN
              SUSPEND;

            vtotcidref = 0;
            bdcodemp = wcodempant;
            bdref = wrefant;
            bdcodcid = wcodcidant;
            bdnomcid = wnomcidant;
            bdvalor = wvalorant;
            bdalimprep = wBDALIMPREPant;
            bdcodexp = wBDCODEXPant;
            bdcodativq48 = wBDCODATIVQ48ant;
            bdcodcidtot = NULL;

          END

        bdcodcidtot = NULL;
        wrefaux = bdref;
        wcodempaux = bdcodemp;
        IF (bdcodexp IS NOT NULL) THEN
          vtotcidref = vtotcidref + bdvalor;

        SUSPEND;
      END

      IF (vtotcidref > 0) THEN
          BEGIN
            bdcodexp = 999;
            bdcodemp = bdcodemp;
            bdref = wrefaux;
            bdcodcid = NULL;
            bdcodcidtot = 99999;
            bdnomcid = 'TOTALIZADOR';
            bdvalor = vtotcidref;
            SUSPEND;
            vtotcidref = 0;
          END



    END
END^

/* Restore proc. body: VEF_SP_RETORNA_DIME_VENC_PRODEC */
ALTER PROCEDURE VEF_SP_RETORNA_DIME_VENC_PRODEC(PRCODEMP INTEGER,
PRREF INTEGER)
 RETURNS(BDDATAVENC DATE)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WNRPARPRODEC INTEGER;
DECLARE VARIABLE WDIAVCTOEMPSC INTEGER;
DECLARE VARIABLE WCONTPRODEC VARCHAR(5);
DECLARE VARIABLE WDATA DATE;
BEGIN

/* giovanni */


  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  --select BDNRPARPRODEC, BDDIAVCTOEMPSC, BDCONTPRODEC from SP_CONSULTAEMPRESAS_SIS...
  wsql = 'select BDNRPARPRODEC, BDCONTPRODEC from SP_CONSULTAEMPRESAS_SIS('|| prref || ', '|| prcodemp || ', null) ' ;

  FOR EXECUTE STATEMENT wsql
  INTO
      wnrparprodec,
      --wdiavctoempsc,
      wcontprodec

  DO
    BEGIN
     IF (wdiavctoempsc > 0) THEN
        BEGIN
         wdata = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 5 FOR 2)||'-'||15||'-'||SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 1 FOR 4) AS DATE);
    
    
         IF ((UPPER(wcontprodec) = 'TRUE') OR (wnrparprodec > 0)) THEN
           BEGIN
              wdata = addmonth(wdata, wnrparprodec);
              bddatavenc = wdata;
           END
         ELSE
           BEGIN
              wdata = addmonth(wdata, 1);
              bddatavenc = wdata;
           END
    
          SUSPEND;
        END
    END
END
^

/* Restore proc. body: VEF_SP_RETVLRSTSP */
ALTER PROCEDURE VEF_SP_RETVLRSTSP(PRCODEMP VARCHAR(30000),
PRREFERENCIA INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFERENCIA INTEGER,
BDVLRSTSAI NUMERIC(15,2),
BDVLRSTENT NUMERIC(15,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WEMP VARCHAR(30000);
BEGIN
  wemp = '';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> ''))  THEN
     wemp = ' and '||prcodemp;

   /*
   wSql = 'select m.bdcodemp, m.bdreflan, SUM(i.bdimpsubstituto) bdvlrstsai, SUM(0) bdvlrstent from vef_emp_tmovsai m, vef_emp_tmovsaiimpretsp i, vw_tterceiro t, tcidade c, tuf u'||
          ' where (m.bdcodemp = i.bdcodemp and m.bdchave = i.bdchave) and (m.bdcodsitnf not in (2,3,4,5)) and (bdimpsubstituto > 0) and (m.bdreflan = '||:prreferencia||')'|| --Sol. 18329 Gabriel Ariel (11/09/17) - Adicionada verificação para notas canceladas
          ' and (m.bdcodter = t.bdcodter and t.bdcodcid = c.bdcodcid and c.bdcoduf = u.bdcoduf and u.bdsiglauf = '||''''||'SP'||''''||') '||:wemp||
          ' group by m.bdcodemp, m.bdreflan'||
          ' union all '||
          ' select m.bdcodemp, m.bdreflan, SUM(0) bdvlrstsai, SUM(i.bdimpsubstituto) bdvlrstent from vef_emp_tmovent m, vef_emp_tmoventimpretsp i, vw_tterceiro t, tcidade c, tuf u'||
          ' where (m.bdcodemp = i.bdcodemp and m.bdchave = i.bdchave) and (bdimpsubstituto > 0) and (m.bdreflan = '||:prreferencia||')'||
          ' and (m.bdcodter = t.bdcodter and t.bdcodcid = c.bdcodcid and c.bdcoduf = u.bdcoduf and u.bdsiglauf = '||''''||'SP'||''''||') '||:wemp||
          ' group by m.bdcodemp, m.bdreflan';
  */

  wSql =       ' SELECT m.bdCODEMP, m.bdREFLAN, SUM(i.bdIMPSUBSTITUTO) AS BDVLRSTSAI, SUM(0) AS BDVLRSTENT ';
  wSql = wSQL||' FROM ( ';
  wSql = wSQL||'       SELECT m.bdCODEMP, m.bdCHAVE, m.bdREFLAN, m.bdCODTER ';
  wSql = wSQL||'       FROM VEF_EMP_TMOVSAI m ';
  wSql = wSQL||'       WHERE (m.bdCODSITNF NOT IN (2,3,4,5)) '; --Sol. 18329 Gabriel Ariel (11/09/17) - Adicionada verificacao para notas canceladas
  wSql = wSQL||'      '||:wemp||' ';
  wSql = wSQL||'         AND (m.bdREFLAN = '||:prREFERENCIA||') ';
  wSql = wSQL||'       ) m ';
  wSql = wSQL||' JOIN VEF_EMP_TMOVSAIIMPRETSP i ON (i.bdCODEMP = m.bdCODEMP AND i.bdCHAVE = m.bdCHAVE) ';
  wSql = wSQL||' LEFT OUTER JOIN VW_TTERCEIRO t ON (t.bdCODTER = m.bdCODTER) ';
  wSql = wSQL||' LEFT OUTER JOIN TCIDADE c ON (c.bdCODCID = t.bdCODCID) ';
  wSql = wSQL||' LEFT OUTER JOIN TUF u ON (u.bdCODUF = c.bdCODUF) ';
  wSql = wSQL||' WHERE (i.bdIMPSUBSTITUTO > 0) ';
  wSql = wSQL||'   AND (u.bdSIGLAUF = '||''''||'SP'||''''||') ';
  wSql = wSQL||' GROUP BY m.bdCODEMP, m.bdREFLAN ';
  wSql = wSQL||' UNION ALL ';
  wSql = wSQL||' SELECT m.bdCODEMP, m.bdREFLAN, SUM(0) AS bdVLRSTSAI, SUM(i.bdIMPSUBSTITUTO) AS bdVLRSTENT ';
  wSql = wSQL||' FROM ( ';
  wSql = wSQL||'       SELECT m.bdCODEMP, m.bdCHAVE, m.bdREFLAN, m.bdCODTER ';
  wSql = wSQL||'       FROM VEF_EMP_TMOVENT m ';
  wSql = wSQL||'       WHERE (m.bdCODSITNF NOT IN (2,3,4,5)) '; --Sol. 18329 Gabriel Ariel (11/09/17) - Adicionada verificacao para notas canceladas
  wSql = wSQL||'         '||:wemp||' ';
  wSql = wSQL||'         AND (m.bdREFLAN = '||:prREFERENCIA||') ';
  wSql = wSQL||'      ) m ';
  wSql = wSQL||' JOIN VEF_EMP_TMOVENTIMPRETSP i ON (i.bdCODEMP = m.bdCODEMP AND i.bdCHAVE = m.bdCHAVE) ';
  wSql = wSQL||' LEFT OUTER JOIN VW_TTERCEIRO t ON (t.bdCODTER = m.bdCODTER) ';
  wSql = wSQL||' LEFT OUTER JOIN TCIDADE c ON (c.bdCODCID = t.bdCODCID) ';
  wSql = wSQL||' LEFT OUTER JOIN TUF u ON (c.bdCODUF = u.bdCODUF) ';
  wSql = wSQL||' WHERE (i.bdIMPSUBSTITUTO > 0) ';
  wSql = wSQL||'   AND (u.bdSIGLAUF = '||''''||'SP'||''''||') ';
  wSql = wSQL||' GROUP BY m.bdCODEMP, m.bdREFLAN ';

  FOR EXECUTE STATEMENT wSql
  INTO
    :BDCODEMP,
    :BDREFERENCIA,
    :BDVLRSTSAI,
    :BDVLRSTENT
  DO
  SUSPEND;

END
^

/* Restore proc. body: VEF_SP_SPED_LAN_ENT */
ALTER PROCEDURE VEF_SP_SPED_LAN_ENT(PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDCODTER INTEGER,
BDNUMDOCINI INTEGER,
BDDATAEMISSAO DATE,
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6),
BDSUBSERIE VARCHAR(3),
BDNUMDOCFIM INTEGER,
BDMODELO INTEGER,
BDEMITENTE INTEGER,
BDDATAENTRADAENT DATE,
BDCODSITNF INTEGER,
BDCODCTA INTEGER,
BDTIPOASSINANTE INTEGER,
BDVLRSER NUMERIC(15,6),
BDVLRSERNTRIB NUMERIC(15,6),
BDVLRCOBTERC NUMERIC(15,6),
BDVLROUTDESP_D500 NUMERIC(15,6),
BDVLRPIS_D500 NUMERIC(15,6),
BDVLRCOFINS_D500 NUMERIC(15,6),
BDCODTENSAO INTEGER,
BDVLRCONSFOR NUMERIC(15,6),
BDVLRCOBTER NUMERIC(15,6),
BDVLRDESPACE NUMERIC(15,6),
BDVLRPIS_C500 NUMERIC(15,6),
BDVLRCOFINS_C500 NUMERIC(15,6),
BDTIPOLIGACAO INTEGER,
BDCHAVENFE VARCHAR(60),
BDINDFRETE INTEGER,
BDVLRFRETE NUMERIC(15,6),
BDVLRSEGURO NUMERIC(15,6),
BDVLROUTDESP_C100 NUMERIC(15,6),
BDVLRTOTPIS NUMERIC(15,6),
BDVLRTOTCOFINS NUMERIC(15,6),
BDVLRTOTPISST NUMERIC(15,6),
BDVLRTOTCOFINSST NUMERIC(15,6),
BDCODOBS INTEGER,
BDCODNAT INTEGER,
BDALIQICMS NUMERIC(15,6),
BDALIQST NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDIMPEXCLUIDAS NUMERIC(15,6),
BDOUTROSIMP NUMERIC(15,6),
BDREDBCICMS NUMERIC(15,6),
BDVLRCONTAB NUMERIC(15,6),
BDCONDPGTO INTEGER,
BDDESCONTO NUMERIC(15,6),
BDTIPOLANENT VARCHAR(1),
BDICMSRETENT NUMERIC(15,6),
BDTIPORETENT INTEGER,
BDDIFALIQENT NUMERIC(15,6),
BDVLRPISRET NUMERIC(15,6),
BDVLRCOFINSRET NUMERIC(15,6),
BDVLRCSOCIALRET NUMERIC(15,6),
BDIMPSUBSTITUIDORET NUMERIC(15,6),
BDIMPSUBSTITUTORET NUMERIC(15,6),
BDCODCTA_C300 INTEGER,
BDVLRTOTPIS_C300 NUMERIC(15,6),
BDVLRTOTCOFINS_C300 NUMERIC(15,6),
BDCODCONS INTEGER,
BDCODINFCOM_C500 VARCHAR(6),
BDCODINFCOM_D500 VARCHAR(6),
BDCODCTA_D100 INTEGER,
BDORDEMINFCOM_D100 VARCHAR(6),
BDCHAVECTE_D100 VARCHAR(44),
BDTIPOCTE_D100 INTEGER,
BDCHAVECTEREF_D100 VARCHAR(44),
BDINDFRETE_D100 INTEGER,
BDCSTICMS VARCHAR(3),
BDPREFIXONAT INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
    wSql = ' select ';
--    wSql = wSql || 'cast('||'''C100'''||' as varchar(4)) as "BDTIPOREG" ,';

    wSql = wSql || 'ENT.BDCODEMP ,';
    wSql = wSql || 'ENT.BDCHAVE ,';
    wSql = wSql || 'ENTITENS.BDORDEM ,';

    wSql = wSql || 'ENT.BDCODTER ,';
    wSql = wSql || 'ENT.BDNUMDOCINI ,';
    wSql = wSql || 'ENT.BDDATAEMISSAO ,';
    wSql = wSql || 'ENT.BDESPECIE ,';
    wSql = wSql || 'ENT.BDSERIE ,';
    wSql = wSql || 'ENT.BDSUBSERIE ,';

    wSql = wSql || 'ENT.BDNUMDOCFIM ,';
    wSql = wSql || 'ENT.BDMODELO ,';
    wSql = wSql || 'ENT.BDEMITENTE ,';
    wSql = wSql || 'ENT.BDDATAENTRADAENT ,';
    wSql = wSql || 'ENT.BDCODSITNF ,';

--    wSql = wSql || 'ENT.BDORDEMINFCOM_D500 ,';
    wSql = wSql || 'ENT.BDCODCTA ,';
    wSql = wSql || 'ENT.BDTIPOASSINANTE ,';
    wSql = wSql || 'ENT.BDVLRSER ,';
    wSql = wSql || 'ENT.BDVLRSERNTRIB ,';
    wSql = wSql || 'ENT.BDVLRCOBTERC ,';
    wSql = wSql || 'ENT.BDVLROUTDESP_D500 ,';
    wSql = wSql || 'ENT.BDVLRPIS_D500 ,';
    wSql = wSql || 'ENT.BDVLRCOFINS_D500 ,';
    
    wSql = wSql || 'ENT.BDCODTENSAO ,';
--    wSql = wSql || 'ENT.BDORDEMINFCOM_C500 ,';
--    wSql = wSql || 'ENT.BDORDEMCONS ,';
    wSql = wSql || 'ENT.BDVLRCONSFOR ,';
    wSql = wSql || 'ENT.BDVLRCOBTER ,';
    wSql = wSql || 'ENT.BDVLRDESPACE ,';
    wSql = wSql || 'ENT.BDVLRPIS_C500 ,';
    wSql = wSql || 'ENT.BDVLRCOFINS_C500 ,';
    wSql = wSql || 'ENT.BDTIPOLIGACAO ,';
    
    wSql = wSql || 'ENT.BDCHAVENFE ,';
    wSql = wSql || 'ENT.BDINDFRETE ,';
    wSql = wSql || 'ENT.BDVLRFRETE ,';
    wSql = wSql || 'ENT.BDVLRSEGURO ,';
    wSql = wSql || 'ENT.BDVLROUTDESP_C100 ,';
    wSql = wSql || 'ENT.BDVLRTOTPIS ,';
    wSql = wSql || 'ENT.BDVLRTOTCOFINS ,';
    wSql = wSql || 'ENT.BDVLRTOTPISST ,';
    wSql = wSql || 'ENT.BDVLRTOTCOFINSST, ';


    wSql = wSql || 'ENTITENS.BDCODOBS ,';
    wSql = wSql || 'ENTITENS.BDCODNAT ,';
    wSql = wSql || 'ENTITENS.BDALIQICMS ,';
    wSql = wSql || 'ENTITENS.BDALIQST ,';
    wSql = wSql || 'ENTITENS.BDBASEICMS ,';
    wSql = wSql || 'ENTITENS.BDBASEIPI ,';
    wSql = wSql || 'ENTITENS.BDBASEST ,';
    wSql = wSql || 'ENTITENS.BDISENTASICMS ,';
    wSql = wSql || 'ENTITENS.BDISENTASIPI ,';
    wSql = wSql || 'ENTITENS.BDOUTRASICMS ,';
    wSql = wSql || 'ENTITENS.BDOUTRASIPI ,';
    wSql = wSql || 'ENTITENS.BDVLRICMS ,';
    wSql = wSql || 'ENTITENS.BDVLRIPI ,';
    wSql = wSql || 'ENTITENS.BDVLRST  ,';
    wSql = wSql || 'ENTITENS.BDIMPEXCLUIDAS ,';
    wSql = wSql || 'ENTITENS.BDOUTROSIMP ,';
    wSql = wSql || 'ENTITENS.BDREDBCICMS ,';
    wSql = wSql || 'ENTITENS.BDVLRCONTAB ,';
    wSql = wSql || 'ENT.BDCONDPGTO ,';
    wSql = wSql || 'ENT.BDDESCONTONOTA as BDDESCONTO ,';
    wSql = wSql || 'ENTITENS.BDTIPOLANENT ,';
    wSql = wSql || 'ENTITENS.BDICMSRETENT ,';
    wSql = wSql || 'ENTITENS.BDTIPORETENT ,';
    wSql = wSql || 'ENTITENS.BDDIFALIQENT, ';

    wSql = wSql || 'ENTITENS.BDVLRPISRET ,';
    wSql = wSql || 'ENTITENS.BDVLRCOFINSRET ,';
    wSql = wSql || 'ENTITENS.BDVLRCSOCIALRET ,';
    wSql = wSql || 'ENTITENS.BDIMPSUBSTITUIDORET ,';
    wSql = wSql || 'ENTITENS.BDIMPSUBSTITUTORET, ';

    wSql = wSql || 'ENT.bdcodcta_C300, ';
    wSql = wSql || 'ENT.bdvlrtotpis_C300, ';
    wSql = wSql || 'ENT.bdvlrtotcofins_C300, ';

    wSql = wSql || 'ENT.bdcodcons , ';
    wSql = wSql || 'ENT.bdcodinfcom_c500 ,';
    wSql = wSql || 'ENT.bdcodinfcom_d500, ';

    --D100
    wSql = wSql || 'ENT.BDCODCTA_D100, ';
    wSql = wSql || 'ENT.BDORDEMINFCOM_D100, ';
    wSql = wSql || 'ENT.BDCHAVECTE_D100, ';
    wSql = wSql || 'ENT.BDTIPOCTE_D100, ';
    wSql = wSql || 'ENT.BDCHAVECTEREF_D100, ';
    wSql = wSql || 'ENT.BDINDFRETE_D100, ';
    wSql = wSql || 'ENTITENS.BDCSTICMS, ';
    wSql = wSql || 'ENTITENS.bdprefixonat ';


    wSql = wsql || ' FROM vw_vef_emp_tmovent ENT , vw_vef_emp_tmovent_itens ENTITENS';

    wSql = wsql || ' where ENT.BDCODEMP = ENTITENS.BDCODEMP AND ENT.BDCHAVE = ENTITENS.BDCHAVE ';

  wwhere = '';
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
    wwhere = wwhere || ' AND ENT.bdcodemp = '||prcodemp;

  IF (prwhereemp IS NOT NULL AND prwhereemp = '')  THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere ||prwhereemp;
    END

  IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'ENT.BDDATAENTRADAENT between '||''''||prdataini||''' and '||''''||prdatafim||'''';
     END

  IF (wwhere <> '') THEN
     wsql = wsql||wwhere;

  wSql = wsql || ' order By ENT.bdCODEMP,ENT.bdCHAVE, ENTITENS.BDORDEM';

  FOR EXECUTE STATEMENT wsql
  INTO
--    :bdtiporeg,
    :BDCODEMP,
    :bdchave,
    :BDORDEM,
    :BDCODTER ,
    :BDNUMDOCINI,
    :BDDATAEMISSAO,
    :BDESPECIE,
    :BDSERIE,
    :BDSUBSERIE,
    :BDNUMDOCFIM,
    :BDMODELO,
    :BDEMITENTE,
    :BDDATAENTRADAENT,
    :BDCODSITNF,
    
--    :BDORDEMINFCOM_D500,
    :BDCODCTA,
    :BDTIPOASSINANTE,
    :BDVLRSER,
    :BDVLRSERNTRIB,
    :BDVLRCOBTERC,
    :BDVLROUTDESP_D500,
    :BDVLRPIS_D500,
    :BDVLRCOFINS_D500,
    
    :BDCODTENSAO,
--    :BDORDEMINFCOM_C500,
--    :BDORDEMCONS,
    :BDVLRCONSFOR,
    :BDVLRCOBTER,
    :BDVLRDESPACE,
    :BDVLRPIS_C500,
    :BDVLRCOFINS_C500,
    :BDTIPOLIGACAO,
    
    :BDCHAVENFE,
    :BDINDFRETE,
    :BDVLRFRETE,
    :BDVLRSEGURO,
    :BDVLROUTDESP_C100,
    :BDVLRTOTPIS,
    :BDVLRTOTCOFINS,
    :BDVLRTOTPISST,
    :BDVLRTOTCOFINSST,

    -- ITENS LAN
    :BDCODOBS ,
    :BDCODNAT ,
    :BDALIQICMS ,
    :BDALIQST ,
    :BDBASEICMS ,
    :BDBASEIPI ,
    :BDBASEST ,
    :BDISENTASICMS ,
    :BDISENTASIPI ,
    :BDOUTRASICMS ,
    :BDOUTRASIPI ,
    :BDVLRICMS ,
    :BDVLRIPI ,
    :BDVLRST  ,
    :BDIMPEXCLUIDAS ,
    :BDOUTROSIMP ,
    :BDREDBCICMS ,
    :BDVLRCONTAB ,
    :BDCONDPGTO ,
    :BDDESCONTO ,
    :BDTIPOLANENT ,
    :BDICMSRETENT ,
    :BDTIPORETENT ,
    :BDDIFALIQENT ,
    --ret itens
    :BDVLRPISRET,
    :BDVLRCOFINSRET,
    :BDVLRCSOCIALRET,
    :BDIMPSUBSTITUIDORET,
    :BDIMPSUBSTITUTORET,

    :bdcodcta_C300,
    :bdvlrtotpis_C300,
    :bdvlrtotcofins_C300,
    :BDCODCONS,
    :bdcodinfcom_C500,
    :bdcodinfcom_d500,
    --D100
    :BDCODCTA_D100 ,
    :BDORDEMINFCOM_D100 ,
    :BDCHAVECTE_D100 ,
    :BDTIPOCTE_D100 ,
    :BDCHAVECTEREF_D100 ,
    :BDINDFRETE_D100,
    :BDCSTICMS,
    :bdprefixonat

  DO
     BEGIN
        SUSPEND;

     END

END
^

/* Restore proc. body: VEF_SP_SPED_LAN_ENT_PRO */
ALTER PROCEDURE VEF_SP_SPED_LAN_ENT_PRO(PRREF INTEGER,
PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDORDEMPRO INTEGER,
BDCODCTA INTEGER,
BDCODPROD INTEGER,
BDCODCSTCOF INTEGER,
BDCODCSTICMS INTEGER,
BDCODCSTPIS INTEGER,
BDCODCSTIPI INTEGER,
BDMOVFISICO VARCHAR(5),
BDQTDITEM NUMERIC(15,6),
BDVLRITEM NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRDESPACESSORIA NUMERIC(15,6),
BDREDBCICMS NUMERIC(15,6),
BDBCICMS NUMERIC(15,6),
BDBCPIS NUMERIC(15,6),
BDBCST NUMERIC(15,6),
BDBCIPI NUMERIC(15,6),
BDBCCOFINS NUMERIC(15,6),
BDBCISSQN NUMERIC(15,6),
BDALIQICMS NUMERIC(15,6),
BDALIQPIS NUMERIC(15,6),
BDALIQST NUMERIC(15,6),
BDALIQIPI NUMERIC(15,6),
BDALIQCOFINS NUMERIC(15,6),
BDALIQISSQN NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRPIS NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRCOFINS NUMERIC(15,6),
BDVLRISSQN NUMERIC(15,6),
BDDESCPROD VARCHAR(200),
BDCSTICMS VARCHAR(3),
BDCODEXPCSTIPI INTEGER,
BDAPEUNIMEDFAT VARCHAR(5))
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN

    IF (prref IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

    wSql = ' select ';
    wSql = wSql || 'ENT.BDCODEMP ,';
    wSql = wSql || 'ENT.BDCHAVE ,';
    wSql = wSql || 'ENTITENS.BDORDEM ,';
    wSql = wSql || 'ENTPRO.BDORDEMPRO ,';
    wSql = wSql || 'ENTPRO.BDCODCTA ,';
    wSql = wSql || 'ENTPRO.BDCODPROD  ,';
    wSql = wSql || 'ENTPRO.BDCODCSTCOF  ,';
    wSql = wSql || 'ENTPRO.BDCODCSTICMS  ,';
    wSql = wSql || 'ENTPRO.BDCODCSTPIS  ,';
    wSql = wSql || 'ENTPRO.BDCODCSTIPI  ,';
    wSql = wSql || 'ENTPRO.BDMOVFISICO  ,';
    wSql = wSql || 'ENTPRO.BDQTDITEM  ,';
    wSql = wSql || 'ENTPRO.BDVLRITEM  ,';
    wSql = wSql || 'ENTPRO.BDVLRDESC  ,';
    wSql = wSql || 'ENTPRO.BDVLRDESPACESSORIA  ,';
    wSql = wSql || 'ENTPRO.BDREDBCICMS  ,';
    wSql = wSql || 'ENTPRO.BDBCICMS  ,';
    wSql = wSql || 'ENTPRO.BDBCPIS  ,';
    wSql = wSql || 'ENTPRO.BDBCST  ,';
    wSql = wSql || 'ENTPRO.BDBCIPI  ,';
    wSql = wSql || 'ENTPRO.BDBCCOFINS  ,';
    wSql = wSql || 'ENTPRO.BDBCISSQN  ,';
    wSql = wSql || 'ENTPRO.BDALIQICMS  ,';
    wSql = wSql || 'ENTPRO.BDALIQPIS  ,';
    wSql = wSql || 'ENTPRO.BDALIQST  ,';
    wSql = wSql || 'ENTPRO.BDALIQIPI  ,';
    wSql = wSql || 'ENTPRO.BDALIQCOFINS  ,';
    wSql = wSql || 'ENTPRO.BDALIQISSQN  ,';
    wSql = wSql || 'ENTPRO.BDVLRICMS  ,';
    wSql = wSql || 'ENTPRO.BDVLRPIS  ,';
    wSql = wSql || 'ENTPRO.BDVLRST   ,';
    wSql = wSql || 'ENTPRO.BDVLRIPI  ,';
    wSql = wSql || 'ENTPRO.BDVLRCOFINS  ,';
    wSql = wSql || 'ENTPRO.BDVLRISSQN  ,';
    wSql = wSql || 'PRO.BDDESCPROD, ';
    wSql = wSql || 'ENTPRO.BDCSTICMS, ';
    wSql = wSql || 'ENTPRO.BDCODEXPCSTIPI, ';
    wSql = wSql || 'ENTPRO.BDAPEUNIMEDFAT ';


    wSql = wsql || ' FROM vw_vef_emp_tmovent_pro_expnfp ENTPRO , vw_vef_emp_tmovent_itens ENTITENS , vw_vef_emp_tmovent ENT ,  tcadpro_VINC PRO ';

    wSql = wsql || ' where (ENTPRO.BDCODEMP = ENTITENS.BDCODEMP AND ENTPRO.bdchave = ENTITENS.BDCHAVE AND ENTPRO.bdordem = ENTITENS.BDORDEM) ';
    wsql = wsql || ' and (ENTITENS.BDCODEMP = ENT.BDCODEMP AND ENTITENS.BDCHAVE = ENT.BDCHAVE) ';
    wsql = wsql || ' and (ENTPRO.BDCODEMP = PRO.BDCODEMP AND ENTPRO.BDCODPROD = PRO.BDCODPROD)';


  wwhere = '';
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
    wwhere = wwhere || ' AND ENT.bdcodemp = '||prcodemp;

  IF (prwhereemp IS NOT NULL AND prwhereemp = '')  THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere ||prwhereemp;
    END

  IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'ENT.BDDATAENTRADAENT between '||''''||prdataini||''' and '||''''||prdatafim||'''';
     END

  IF (wwhere <> '') THEN
     wsql = wsql||wwhere;

  wSql = wsql || ' order By ENT.bdCODEMP,ENT.bdCHAVE, ENTITENS.BDORDEM, ENTPRO.BDORDEMPRO';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdchave,
    :BDORDEM,
    :BDORDEMPRO,
    :BDCODCTA ,
    :BDCODPROD ,
    :BDCODCSTCOF ,
    :BDCODCSTICMS ,
    :BDCODCSTPIS ,
    :BDCODCSTIPI ,
    :BDMOVFISICO ,
    :BDQTDITEM ,
    :BDVLRITEM ,
    :BDVLRDESC ,
    :BDVLRDESPACESSORIA ,
    :BDREDBCICMS ,
    :BDBCICMS ,
    :BDBCPIS ,
    :BDBCST ,
    :BDBCIPI ,
    :BDBCCOFINS ,
    :BDBCISSQN ,
    :BDALIQICMS ,
    :BDALIQPIS ,
    :BDALIQST ,
    :BDALIQIPI ,
    :BDALIQCOFINS ,
    :BDALIQISSQN ,
    :BDVLRICMS ,
    :BDVLRPIS ,
    :BDVLRST  ,
    :BDVLRIPI ,
    :BDVLRCOFINS ,
    :BDVLRISSQN ,
    :BDDESCPROD,
    :BDCSTICMS,
    :BDCODEXPCSTIPI,
    :BDAPEUNIMEDFAT

  DO
  BEGIN
   SUSPEND;
  END

END
^

/* Restore proc. body: VEF_SP_SPED_LAN_SAI */
ALTER PROCEDURE VEF_SP_SPED_LAN_SAI (
    PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
RETURNS (
    BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDCODTER INTEGER,
BDNUMDOCINI INTEGER,
BDDATAEMISSAO DATE,
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6),
BDSUBSERIE VARCHAR(3),
BDNUMDOCFIM INTEGER,
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDEMITENTE INTEGER,
BDDATASAIDA DATE,
BDCODSITNF INTEGER,
BDCODCTA INTEGER,
BDTIPOASSINANTE INTEGER,
BDVLRSER NUMERIC(15,6),
BDVLRSERNTRIB NUMERIC(15,6),
BDVLRCOBTERC NUMERIC(15,6),
BDVLROUTDESP_D500 NUMERIC(15,6),
BDVLRPIS_D500 NUMERIC(15,6),
BDVLRCOFINS_D500 NUMERIC(15,6),
BDCODTENSAO INTEGER,
BDVLRCONSFOR NUMERIC(15,6),
BDVLRCOBTER NUMERIC(15,6),
BDVLRDESPACE NUMERIC(15,6),
BDVLRPIS_C500 NUMERIC(15,6),
BDVLRCOFINS_C500 NUMERIC(15,6),
BDTIPOLIGACAO INTEGER,
BDCHAVENFE VARCHAR(60),
BDINDFRETE INTEGER,
BDVLRFRETE NUMERIC(15,6),
BDVLRSEGURO NUMERIC(15,6),
BDVLROUTDESP_C100 NUMERIC(15,6),
BDVLRTOTPIS NUMERIC(15,6),
BDVLRTOTCOFINS NUMERIC(15,6),
BDVLRTOTPISST NUMERIC(15,6),
BDVLRTOTCOFINSST NUMERIC(15,6),
BDCODTER_VLTRAN INTEGER,
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2),
BDQTDVOLTRAN NUMERIC(15,6),
BDPESOBRUTO NUMERIC(15,6),
BDPESOLIQUIDO NUMERIC(15,6),
BDPLACAID VARCHAR(8),
BDCODOBS INTEGER,
BDCODNAT INTEGER,
BDALIQICMS NUMERIC(15,6),
BDALIQST NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDIMPEXCLUIDAS NUMERIC(15,6),
BDOUTROSIMP NUMERIC(15,6),
BDREDBCICMS NUMERIC(15,6),
BDVLRCONTAB NUMERIC(15,6),
BDCONDPGTO INTEGER,
BDDESCONTO NUMERIC(15,6),
BDICMSFRETESAI NUMERIC(15,6),
BDACRECFINSAI NUMERIC(15,6),
BDREGEXPSAI VARCHAR(16),
BDVLRPISRET NUMERIC(15,6),
BDVLRCOFINSRET NUMERIC(15,6),
BDVLRCSOCIALRET NUMERIC(15,6),
BDIMPSUBSTITUIDORET NUMERIC(15,6),
BDIMPSUBSTITUTORET NUMERIC(15,6),
BDVLRIRRET NUMERIC(15,6),
    BDRETINSS NUMERIC(15,6),
BDISSRET NUMERIC(15,6),
BDCGCTER VARCHAR(18),
BDCODCTA_C300 INTEGER,
BDVLRTOTPIS_C300 NUMERIC(15,6),
BDVLRTOTCOFINS_C300 NUMERIC(15,6),
BDCODCONS INTEGER,
BDCODINFCOM_C500 VARCHAR(6),
BDCODINFCOM_D500 VARCHAR(6),
BDCODCTA_D100 INTEGER,
BDORDEMINFCOM_D100 VARCHAR(6),
BDCHAVECTE_D100 VARCHAR(44),
BDTIPOCTE_D100 INTEGER,
BDCHAVECTEREF_D100 VARCHAR(44),
BDINDFRETE_D100 INTEGER,
BDCSTICMS VARCHAR(3),
BDPREFIXONAT INTEGER,
BDVALORTOTALNOTA NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
    wSql = ' select ';
--    wSql = wSql || 'cast('||'''C100'''||' as varchar(4)) as "BDTIPOREG" ,';

    wSql = wSql || 'SAI.BDCODEMP ,';
    wSql = wSql || 'SAI.BDCHAVE ,';
    wSql = wSql || 'SAIITENS.BDORDEM ,';

    wSql = wSql || 'SAI.BDCODTER ,';
    wSql = wSql || 'SAI.BDNUMDOCINI ,';
    wSql = wSql || 'SAI.BDDATAEMISSAO ,';
    wSql = wSql || 'SAI.BDESPECIE ,';
    wSql = wSql || 'SAI.BDSERIE ,';
    wSql = wSql || 'SAI.BDSUBSERIE ,';

    wSql = wSql || 'SAI.BDNUMDOCFIM ,';
    wSql = wSql || 'SAI.BDMODELO ,';
    wSql = wSql || 'SAI.BDMODELOSTR,';
    wSql = wSql || 'SAI.BDEMITENTE ,';
    wSql = wSql || 'SAI.BDDATASAIDA ,';
    wSql = wSql || 'SAI.BDCODSITNF ,';

--    wSql = wSql || 'SAI.BDORDEMINFCOM_D500 ,';
    wSql = wSql || 'SAI.BDCODCTA ,';
    wSql = wSql || 'SAI.BDTIPOASSINANTE ,';
    wSql = wSql || 'SAI.BDVLRSER ,';
    wSql = wSql || 'SAI.BDVLRSERNTRIB ,';
    wSql = wSql || 'SAI.BDVLRCOBTERC ,';
    wSql = wSql || 'SAI.BDVLROUTDESP_D500 ,';
    wSql = wSql || 'SAI.BDVLRPIS_D500 ,';
    wSql = wSql || 'SAI.BDVLRCOFINS_D500 ,';
    
    wSql = wSql || 'SAI.BDCODTENSAO ,';
--    wSql = wSql || 'SAI.BDORDEMINFCOM_C500 ,';
--    wSql = wSql || 'SAI.BDORDEMCONS ,';
    wSql = wSql || 'SAI.BDVLRCONSFOR ,';
    wSql = wSql || 'SAI.BDVLRCOBTER ,';
    wSql = wSql || 'SAI.BDVLRDESPACE ,';
    wSql = wSql || 'SAI.BDVLRPIS_C500 ,';
    wSql = wSql || 'SAI.BDVLRCOFINS_C500 ,';
    wSql = wSql || 'SAI.BDTIPOLIGACAO ,';
    
    wSql = wSql || 'SAI.BDCHAVENFE ,';
    wSql = wSql || 'SAI.BDINDFRETE ,';
    wSql = wSql || 'SAI.BDVLRFRETE ,';
    wSql = wSql || 'SAI.BDVLRSEGURO ,';
    wSql = wSql || 'SAI.BDVLROUTDESP_C100 ,';
    wSql = wSql || 'SAI.BDVLRTOTPIS ,';
    wSql = wSql || 'SAI.BDVLRTOTCOFINS ,';
    wSql = wSql || 'SAI.BDVLRTOTPISST ,';
    wSql = wSql || 'SAI.BDVLRTOTCOFINSST, ';

    wSql = wSql || 'SAI.BDCODTER_VLTRAN, ';
    wSql = wSql || 'SAI.BDCODUF, ';
    wSql = wSql || 'SAI.bdsiglauf, ';
    wSql = wSql || 'SAI.BDQTDVOLTRAN, ';
    wSql = wSql || 'SAI.BDPESOBRUTO, ';
    wSql = wSql || 'SAI.BDPESOLIQUIDO, ';
    wSql = wSql || 'SAI.BDPLACAID, ';


    wSql = wSql || 'SAIITENS.BDCODOBS ,';
    wSql = wSql || 'SAIITENS.BDCODNAT ,';
    wSql = wSql || 'SAIITENS.BDALIQICMS ,';
    wSql = wSql || 'SAIITENS.BDALIQST ,';
    wSql = wSql || 'SAIITENS.BDBASEICMS ,';
    wSql = wSql || 'SAIITENS.BDBASEIPI ,';
    wSql = wSql || 'SAIITENS.BDBASEST ,';
    wSql = wSql || 'SAIITENS.BDISENTASICMS ,';
    wSql = wSql || 'SAIITENS.BDISENTASIPI ,';
    wSql = wSql || 'SAIITENS.BDOUTRASICMS ,';
    wSql = wSql || 'SAIITENS.BDOUTRASIPI ,';
    wSql = wSql || 'SAIITENS.BDVLRICMS ,';
    wSql = wSql || 'SAIITENS.BDVLRIPI ,';
    wSql = wSql || 'SAIITENS.BDVLRST  ,';
    wSql = wSql || 'SAIITENS.BDIMPEXCLUIDAS ,';
    wSql = wSql || 'SAIITENS.BDOUTROSIMP ,';
    wSql = wSql || 'SAIITENS.BDREDBCICMS ,';
    wSql = wSql || 'SAIITENS.BDVLRCONTAB ,';
    wSql = wSql || 'SAI.BDCONDPGTO ,';
    wSql = wSql || 'SAI.BDDESCONTONOTA as BDDESCONTO ,';

    wSql = wSql || 'SAIITENS.BDICMSFRETESAI ,';
    wSql = wSql || 'SAIITENS.BDACRECFINSAI ,';
    wSql = wSql || 'SAIITENS.BDREGEXPSAI ,';

    wSql = wSql || 'SAIITENS.BDVLRPISRET ,';
    wSql = wSql || 'SAIITENS.BDVLRCOFINSRET ,';
    wSql = wSql || 'SAIITENS.BDVLRCSOCIALRET ,';
    wSql = wSql || 'SAIITENS.BDIMPSUBSTITUIDORET ,';
    wSql = wSql || 'SAIITENS.BDIMPSUBSTITUTORET ,';

    wSql = wSql || 'SAIITENS.BDVLRIRRET ,';
    wSql = wSql || 'SAIITENS.BDRETINSS ,';
    wSql = wSql || 'SAIITENS.BDISSRET, ';
    wSql = wSql || 'SAI.BDCGCTER, ';

    wSql = wSql || 'SAI.bdcodcta_C300, ';
    wSql = wSql || 'SAI.bdvlrtotpis_C300, ';
    wSql = wSql || 'SAI.bdvlrtotcofins_C300, ';

    wSql = wSql || 'SAI.bdcodcons , ';
    wSql = wSql || 'SAI.bdcodinfcom_c500 ,';
    wSql = wSql || 'SAI.bdcodinfcom_d500, ';
    --D100
    wSql = wSql || 'SAI.BDCODCTA_D100, ';
    wSql = wSql || 'SAI.BDORDEMINFCOM_D100, ';
    wSql = wSql || 'SAI.BDCHAVECTE_D100, ';
    wSql = wSql || 'SAI.BDTIPOCTE_D100, ';
    wSql = wSql || 'SAI.BDCHAVECTEREF_D100, ';
    wSql = wSql || 'SAI.BDINDFRETE_D100, ';
    wSql = wSql || 'SAIITENS.bdcsticms, ';
    wSql = wSql || 'SAIITENS.bdprefixonat, ';
    wSql = wSql || 'SAI.bdvalornota ';

    wSql = wsql || ' FROM vw_vef_emp_tmovsai SAI , vw_vef_emp_tmovsai_itens SAIITENS';

    wSql = wsql || ' where SAI.BDCODEMP = SAIITENS.BDCODEMP AND SAI.BDCHAVE = SAIITENS.BDCHAVE ';

  wwhere = '';
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
    wwhere = wwhere || ' AND SAI.bdcodemp = '||prcodemp;

  IF (prwhereemp IS NOT NULL AND prwhereemp = '')  THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere ||prwhereemp;
    END

  IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'SAI.BDDATAEMISSAO between '||''''||prdataini||''' and '||''''||prdatafim||'''';
     END

  IF (wwhere <> '') THEN
     wsql = wsql||wwhere;

  wSql = wsql || ' order By SAI.bdCODEMP,SAI.bdCHAVE, SAIITENS.BDORDEM';

  FOR EXECUTE STATEMENT wsql
  INTO
--    :bdtiporeg,
    :BDCODEMP,
    :bdchave,
    :BDORDEM,
    :BDCODTER ,
    :BDNUMDOCINI,
    :BDDATAEMISSAO,
    :BDESPECIE,
    :BDSERIE,
    :BDSUBSERIE,
    :BDNUMDOCFIM,
    :BDMODELO,
    :BDMODELOSTR,
    :BDEMITENTE,
    :BDDATASAIDA,
    :BDCODSITNF,
    
--    :BDORDEMINFCOM_D500,
    :BDCODCTA,
    :BDTIPOASSINANTE,
    :BDVLRSER,
    :BDVLRSERNTRIB,
    :BDVLRCOBTERC,
    :BDVLROUTDESP_D500,
    :BDVLRPIS_D500,
    :BDVLRCOFINS_D500,
    
    :BDCODTENSAO,
--    :BDORDEMINFCOM_C500,
--    :BDORDEMCONS,
    :BDVLRCONSFOR,
    :BDVLRCOBTER,
    :BDVLRDESPACE,
    :BDVLRPIS_C500,
    :BDVLRCOFINS_C500,
    :BDTIPOLIGACAO,
    
    :BDCHAVENFE,
    :BDINDFRETE,
    :BDVLRFRETE,
    :BDVLRSEGURO,
    :BDVLROUTDESP_C100,
    :BDVLRTOTPIS,
    :BDVLRTOTCOFINS,
    :BDVLRTOTPISST,
    :BDVLRTOTCOFINSST,

    --vltran
    :BDCODTER_VLTRAN,
    :BDCODUF,
    :bdsiglauf,
    :BDQTDVOLTRAN,
    :BDPESOBRUTO,
    :BDPESOLIQUIDO,
    :BDPLACAID,


    -- ITENS LAN
    :BDCODOBS ,
    :BDCODNAT ,
    :BDALIQICMS ,
    :BDALIQST ,
    :BDBASEICMS ,
    :BDBASEIPI ,
    :BDBASEST ,
    :BDISENTASICMS ,
    :BDISENTASIPI ,
    :BDOUTRASICMS ,
    :BDOUTRASIPI ,
    :BDVLRICMS ,
    :BDVLRIPI ,
    :BDVLRST  ,
    :BDIMPEXCLUIDAS ,
    :BDOUTROSIMP ,
    :BDREDBCICMS ,
    :BDVLRCONTAB ,
    :BDCONDPGTO ,
    :BDDESCONTO ,

    :BDICMSFRETESAI ,
    :BDACRECFINSAI ,
    :BDREGEXPSAI   ,

    --ret itens
    :BDVLRPISRET,
    :BDVLRCOFINSRET,
    :BDVLRCSOCIALRET,
    :BDIMPSUBSTITUIDORET,
    :BDIMPSUBSTITUTORET,
    :BDVLRIRRET ,
    :BDRETINSS ,
    :BDISSRET ,
    :BDCGCTER,
    :bdcodcta_C300,
    :bdvlrtotpis_C300,
    :bdvlrtotcofins_C300,
    :BDCODCONS,
    :bdcodinfcom_C500,
    :bdcodinfcom_d500,

    --D100
    :BDCODCTA_D100 ,
    :BDORDEMINFCOM_D100 ,
    :BDCHAVECTE_D100 ,
    :BDTIPOCTE_D100 ,
    :BDCHAVECTEREF_D100 ,
    :BDINDFRETE_D100,
    --D190
    :bdcsticms,
    :bdprefixonat,
    :bdvalortotalnota

  DO
     BEGIN
        SUSPEND;

     END

END
^

/* Restore proc. body: VEF_SP_SPED_LAN_SAI_PRO */
ALTER PROCEDURE VEF_SP_SPED_LAN_SAI_PRO(PRREF INTEGER,
PRCODEMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHEREEMP VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDORDEM INTEGER,
BDORDEMPRO INTEGER,
BDCODCTA INTEGER,
BDCODPROD INTEGER,
BDCODCSTCOF INTEGER,
BDCODCSTICMS INTEGER,
BDCODCSTPIS INTEGER,
BDCODCSTIPI INTEGER,
BDMOVFISICO VARCHAR(5),
BDQTDITEM NUMERIC(15,6),
BDVLRITEM NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRDESPACESSORIA NUMERIC(15,6),
BDREDBCICMS NUMERIC(15,6),
BDBCICMS NUMERIC(15,6),
BDBCPIS NUMERIC(15,6),
BDBCST NUMERIC(15,6),
BDBCIPI NUMERIC(15,6),
BDBCCOFINS NUMERIC(15,6),
BDBCISSQN NUMERIC(15,6),
BDALIQICMS NUMERIC(15,6),
BDALIQPIS NUMERIC(15,6),
BDALIQST NUMERIC(15,6),
BDALIQIPI NUMERIC(15,6),
BDALIQCOFINS NUMERIC(15,6),
BDALIQISSQN NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRPIS NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRCOFINS NUMERIC(15,6),
BDVLRISSQN NUMERIC(15,6),
BDDESCPROD VARCHAR(200),
BDCSTICMS VARCHAR(3),
BDCODEXPCSTIPI INTEGER,
BDCODCLAENETEL INTEGER,
BDINDREC INTEGER,
BDCODCLAENETELGAS INTEGER,
BDINDRECGAS INTEGER,
BDCODSELOIPI INTEGER,
BDQTDSELOIPI INTEGER,
BDCODCLASSEIPI VARCHAR(5),
BDVLRUNIDADE NUMERIC(15,6),
BDQTDUNIDADE NUMERIC(15,6),
BDAPEUNIMEDFAT VARCHAR(5),
BDCODSAIDA VARCHAR(60))
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN

    IF (prref IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

    wSql = ' select ';
    wSql = wSql || 'SAI.BDCODEMP ,';
    wSql = wSql || 'SAI.BDCHAVE ,';
    wSql = wSql || 'SAIITENS.BDORDEM ,';
    wSql = wSql || 'SAIPRO.BDORDEMPRO ,';
    wSql = wSql || 'SAIPRO.BDCODCTA ,';
    wSql = wSql || 'SAIPRO.BDCODPROD  ,';
    wSql = wSql || 'SAIPRO.BDCODCSTCOF  ,';
    wSql = wSql || 'SAIPRO.BDCODCSTICMS  ,';
    wSql = wSql || 'SAIPRO.BDCODCSTPIS  ,';
    wSql = wSql || 'SAIPRO.BDCODCSTIPI  ,';
    wSql = wSql || 'SAIPRO.BDMOVFISICO  ,';
    wSql = wSql || 'SAIPRO.BDQTDITEM  ,';
    wSql = wSql || 'SAIPRO.BDVLRITEM  ,';
    wSql = wSql || 'SAIPRO.BDVLRDESC  ,';
    wSql = wSql || 'SAIPRO.BDVLRDESPACESSORIA  ,';
    wSql = wSql || 'SAIPRO.BDREDBCICMS  ,';
    wSql = wSql || 'SAIPRO.BDBCICMS  ,';
    wSql = wSql || 'SAIPRO.BDBCPIS  ,';
    wSql = wSql || 'SAIPRO.BDBCST  ,';
    wSql = wSql || 'SAIPRO.BDBCIPI  ,';
    wSql = wSql || 'SAIPRO.BDBCCOFINS  ,';
    wSql = wSql || 'SAIPRO.BDBCISSQN  ,';
    wSql = wSql || 'SAIPRO.BDALIQICMS  ,';
    wSql = wSql || 'SAIPRO.BDALIQPIS  ,';
    wSql = wSql || 'SAIPRO.BDALIQST  ,';
    wSql = wSql || 'SAIPRO.BDALIQIPI  ,';
    wSql = wSql || 'SAIPRO.BDALIQCOFINS  ,';
    wSql = wSql || 'SAIPRO.BDALIQISSQN  ,';
    wSql = wSql || 'SAIPRO.BDVLRICMS  ,';
    wSql = wSql || 'SAIPRO.BDVLRPIS  ,';
    wSql = wSql || 'SAIPRO.BDVLRST   ,';
    wSql = wSql || 'SAIPRO.BDVLRIPI  ,';
    wSql = wSql || 'SAIPRO.BDVLRCOFINS  ,';
    wSql = wSql || 'SAIPRO.BDVLRISSQN  ,';
    wSql = wSql || 'PRO.BDDESCPROD, ';
    wSql = wSql || 'SAIPRO.BDCSTICMS, ';
    wSql = wSql || 'SAIPRO.BDCODEXPCSTIPI , ';

    wSql = wSql || 'SAIPRO.BDCODCLAENETEL  ,';
    wSql = wSql || 'SAIPRO.BDINDREC  ,';
    wSql = wSql || 'SAIPRO.BDCODCLAENETELGAS  ,';
    wSql = wSql || 'SAIPRO.BDINDRECGAS, ';

    wSql = wSql || 'SAIPRO.BDCODSELOIPI, ';
    wSql = wSql || 'SAIPRO.BDQTDSELOIPI, ';
    wSql = wSql || 'SAIPRO.BDCODCLASSEIPI, ';
    wSql = wSql || 'SAIPRO.BDVLRUNIDADE, ';
    wSql = wSql || 'SAIPRO.BDQTDUNIDADE, ';

--    wSql = wSql || 'SAIPRO.bdapeunimed, ';
    wSql = wSql || 'SAIPRO.BDAPEUNIMEDFAT, ';
    wSql = wSql || 'PRO.BDCODSAIDA ';


    wSql = wsql || ' FROM vw_vef_emp_tmovsai SAI , vw_vef_emp_tmovsai_itens SAIITENS, VW_VEF_EMP_TMOVSAI_PRO_EXPNFP SAIPRO , tcadpro_VINC PRO ';

    wSql = wsql || ' where (SAIPRO.BDCODEMP = PRO.BDCODEMP AND SAIPRO.BDCODPROD = PRO.BDCODPROD) AND (SAI.BDCODEMP = SAIITENS.BDCODEMP AND SAI.BDCHAVE = SAIITENS.BDCHAVE) ';
    wsql = wsql || ' and (SAI.BDCODEMP = SAIPRO.BDCODEMP AND SAI.BDCHAVE = SAIPRO.bdchave AND SAIITENS.BDORDEM = SAIPRO.bdordem)';

  wwhere = '';
  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
    wwhere = wwhere || ' AND SAI.bdcodemp = '||prcodemp;

  IF (prwhereemp IS NOT NULL AND prwhereemp = '')  THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere ||prwhereemp;
    END

  IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'SAI.BDDATAEMISSAO between '||''''||prdataini||''' and '||''''||prdatafim||'''';
     END

  IF (wwhere <> '') THEN
     wsql = wsql||wwhere;

  wSql = wsql || ' order By SAI.bdCODEMP,SAI.bdCHAVE, SAIITENS.BDORDEM, SAIPRO.BDORDEMPRO';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdchave,
    :BDORDEM,
    :BDORDEMPRO,
    :BDCODCTA ,
    :BDCODPROD ,
    :BDCODCSTCOF ,
    :BDCODCSTICMS ,
    :BDCODCSTPIS ,
    :BDCODCSTIPI ,
    :BDMOVFISICO ,
    :BDQTDITEM ,
    :BDVLRITEM ,
    :BDVLRDESC ,
    :BDVLRDESPACESSORIA ,
    :BDREDBCICMS ,
    :BDBCICMS ,
    :BDBCPIS ,
    :BDBCST ,
    :BDBCIPI ,
    :BDBCCOFINS ,
    :BDBCISSQN ,
    :BDALIQICMS ,
    :BDALIQPIS ,
    :BDALIQST ,
    :BDALIQIPI ,
    :BDALIQCOFINS ,
    :BDALIQISSQN ,
    :BDVLRICMS ,
    :BDVLRPIS ,
    :BDVLRST  ,
    :BDVLRIPI ,
    :BDVLRCOFINS ,
    :BDVLRISSQN ,
    :BDDESCPROD,
    :BDCSTICMS,
    :BDCODEXPCSTIPI,

    :BDCODCLAENETEL ,
    :BDINDREC       ,
    :BDCODCLAENETELGAS ,
    :BDINDRECGAS,

    :BDCODSELOIPI,
    :BDQTDSELOIPI,
    :BDCODCLASSEIPI,
    :BDVLRUNIDADE,
    :BDQTDUNIDADE,
--    :bdapeunimed,
    :BDAPEUNIMEDFAT,
    :BDCODSAIDA


  DO
  BEGIN
   SUSPEND;
  END

END
^

/* Restore proc. body: VEF_SP_SPED_TERCEIRO */
ALTER PROCEDURE VEF_SP_SPED_TERCEIRO(PRCODTER INTEGER,
PRREF INTEGER,
PRWHERETER VARCHAR(20000))
 RETURNS(BDCODTER INTEGER,
BDCGCTER VARCHAR(18),
BDREFEMP INTEGER,
BDAPELIDOTER VARCHAR(20),
BDNOMETER VARCHAR(100),
BDLOGRTER DM_LOGRADOURO,
BDENDTER DM_BDENDERECO,
BDNUMTER DM_NUMEND,
BDCOMPTER DM_BDCOMPENDERECO,
BDCEPTER VARCHAR(9),
BDBAITER DM_BDBAIRRO,
BDDDDTER VARCHAR(3),
BDFONETER DM_BDTELEFONE,
BDFAXTER DM_BDTELEFONE,
BDEMAILTER DM_BDEMAIL,
BDIETER VARCHAR(20),
BDDATACADTER DATE,
BDIMTER VARCHAR(16),
BDPRURALTER VARCHAR(5),
BDENQSIMPLESFEDTER INTEGER,
BDINSCSUFRAMATER VARCHAR(10),
BDCODGPS INTEGER,
BDCODCID INTEGER,
BDCODPAIS INTEGER,
BDDDDFAXTER VARCHAR(3),
BDCODUF INTEGER,
BDSIGLAUF VARCHAR(2),
BDCODSPED INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN

    wSql = ' select distinct ';
    wSql = wSql || 'TER.BDCODTER, ';
    wSql = wSql || 'TER.BDCGCTER, ';
    wSql = wSql || 'TER.BDREFEMP, ';
    wSql = wSql || 'TER.BDAPELIDOTER, ';
    wSql = wSql || 'TER.BDNOMETER, ';
    wSql = wSql || 'TER.BDLOGRTER, ';
    wSql = wSql || 'TER.BDENDTER, ';
    wSql = wSql || 'TER.BDNUMTER, ';
    wSql = wSql || 'TER.BDCOMPTER, ';
    wSql = wSql || 'TER.BDCEPTER, ';
    wSql = wSql || 'TER.BDBAITER, ';
    wSql = wSql || 'TER.BDDDDTER, ';
    wSql = wSql || 'TER.BDFONETER, ';
    wSql = wSql || 'TER.BDFAXTER, ';
    wSql = wSql || 'TER.BDEMAILTER, ';
    wSql = wSql || 'TER.BDIETER, ';
    wSql = wSql || 'TER.BDDATACADTER, ';
    wSql = wSql || 'TER.BDIMTER, ';
    wSql = wSql || 'TER.BDPRURALTER, ';
    wSql = wSql || 'TER.BDENQSIMPLESFEDTER, ';
    wSql = wSql || 'TER.BDINSCSUFRAMATER, ';
    wSql = wSql || 'TER.BDCODGPS, ';
    wSql = wSql || 'TER.BDCODCID, ';
    wSql = wSql || 'TER.BDCODPAIS, ';
    wSql = wSql || 'TER.BDDDDFAXTER, ';
    wSql = wSql || 'TER.BDCODUF, ';
    wSql = wSql || 'TER.BDSIGLAUF, ';
    wSql = wSql || 'PAIS.BDCODSPED ';

  wwhere = '';
  IF (prcodter IS NOT NULL AND prcodter <> 0) THEN
    wwhere = wwhere ||prcodter||',';
  ELSE
    wwhere = wwhere ||'null,';

  IF (prref IS NOT NULL)  THEN
    wwhere = wwhere ||prref||',';
  ELSE
    wwhere = wwhere ||'null,';

  IF (prwhereTER IS NOT NULL AND prwhereTER <> '')  THEN
    wwhere = wwhere ||''''||prwhereTER||'''';
  ELSE
    wwhere = wwhere ||'null';

  wSql = wsql || ' FROM sp_consulta_terceiro('||wwhere||') TER ';

  wSql = wsql || ' left outer join tpais PAIS';
  wSql = wsql || ' on (TER.BDCODPAIS = PAIS.bdCODPAIS)';
--    wSql = wsql || ' left outer join tuf UF';
--    wSql = wsql || ' on (CID.BDCODUF = UF.bdCODUF)';

/*  wwhere = '';
  if (prcodter is not null and prcodter <> 0) then
    wwhere = wwhere || ' TER.bdcodTER = '||prcodter;

  if (prwhereTER is not null and prwhereTER <> '')  then
    BEGIN
       if (wwhere <> '') then
          wwhere = wwhere||' and (';

        wwhere = wwhere ||prwhereTER||')';
    END

  if (wwhere <> '') then
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By TER.bdcodTER';
*/
  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODTER,
    :BDCGCTER,

    :BDREFEMP,
    :BDAPELIDOTER,
    :BDNOMETER, 
    :BDLOGRTER, 
    :BDENDTER, 
    :BDNUMTER, 
    :BDCOMPTER,
    :BDCEPTER, 
    :BDBAITER, 
    :BDDDDTER, 
    :BDFONETER,
    :BDFAXTER,
    :BDEMAILTER,
    :BDIETER,
    :BDDATACADTER,
    :BDIMTER,
    :BDPRURALTER,
    :BDENQSIMPLESFEDTER,
    :BDINSCSUFRAMATER,
    :BDCODGPS,
    :BDCODCID,
    :BDCODPAIS,
    :BDDDDFAXTER,
    :BDCODUF,
    :BDSIGLAUF,
    :BDCODSPED
  DO
  SUSPEND;
END
^

/* Restore proc. body: VEF_SP_SVA_431 */
ALTER PROCEDURE VEF_SP_SVA_431 (
    PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRENTRADA VARCHAR(5),
PRSAIDA VARCHAR(5))
RETURNS (
    BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDMODELOAUX VARCHAR(15),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
    BDCODSITNFAUX CHAR(1),
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDORDEM INTEGER,
BDVLRCONTAB NUMERIC(15,6),
BDBASEICMS NUMERIC(15,6),
BDBASEIPI NUMERIC(15,6),
BDBASEST NUMERIC(15,6),
BDISENTASICMS NUMERIC(15,6),
BDISENTASIPI NUMERIC(15,6),
BDOUTRASICMS NUMERIC(15,6),
BDOUTRASIPI NUMERIC(15,6),
BDVLRICMS NUMERIC(15,6),
BDVLRIPI NUMERIC(15,6),
BDVLRST NUMERIC(15,6),
BDIMPEXCLUIDAS NUMERIC(15,6),
BDOUTROSIMP NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDICMSRETENT NUMERIC(15,6),
BDCONDPGTO INTEGER,
    BDCONDPGTOAUX CHAR(1),
BDVLRITEMPRO NUMERIC(15,6),
BDVLRDESC NUMERIC(15,6),
BDVLRIPIPRO NUMERIC(15,6),
BDVLRICMSPRO NUMERIC(15,6),
BDVLRFRETEC100 NUMERIC(15,6),
BDVLRSEGUROC100 NUMERIC(15,6),
BDVLROUTDESPC100 NUMERIC(15,6),
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDVLRCSOCIAL NUMERIC(15,2),
BDVLRIR NUMERIC(15,2),
    BDRETINSS NUMERIC(15,2),
BDCGCTER VARCHAR(18),
BDORDEMPRO INTEGER,
BDTIPOREG VARCHAR(10),
BDALIQPIS NUMERIC(5,2),
BDALIQCOFINS NUMERIC(5,2),
BDALIQIR NUMERIC(5,2),
BDALIQCSOCIAL NUMERIC(5,2),
    BDBRETINSS NUMERIC(15,2),
BDRETVAZIO VARCHAR(1),
BDVLRCONTAB2 NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
BEGIN
  /* Procedure Text */

 EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

 IF (UPPER(PRENTRADA) = 'TRUE') THEN
    BEGIN

 wsql = 'SELECT t.bdcodemp,  t.bdchave,  t.bdreflan, t.bdtipomov, t.bdmodelo, t.BDMODELOSTR, t.BDSERIE, t.BDNUMDOCINI, t.BDDATAEMISSAO, t.BDDATAENTSAI, t.BDCODTER,
         t.BDESPECIE, t.BDEMITENTE, t.BDCODSITNF, t.BDCIFFOB, t.bdordem, t.BDVLRCONTAB, t.BDBASEICMS,
         t.BDBASEIPI, t.BDBASEST, t.BDISENTASICMS, t.BDISENTASIPI, t.BDOUTRASICMS, t.BDOUTRASIPI, t.BDVLRICMS, t.BDVLRIPI,  t.BDVLRST, t.BDIMPEXCLUIDAS,
         t.BDOUTROSIMP, t.BDDESCONTO, t.BDICMSRETENTSAI, t.bdcondpgto,
         coalesce(RET.bdvlrpis,0.0) BDVLRPIS,
         coalesce(RET.bdvlrcofins,0.0) BDVLRCOFINS,
         coalesce(RET.bdvlrcsocial,0.0) BDVLRCSOCIAL,
         coalesce(0,0.0)  BDVLRIR,
         coalesce(0,0.0)  BDRETINSS ,
         ter.bdcgcter,

         sum(pro.BDVLRITEM) BDVLRITEMPRO, sum(pro.BDVLRDESC) BDVLRDESCPRO, sum(pro.bdvlripi) bdvlripipro,
         sum(pro.bdvlricms) bdvlricmspro, sum(C100.bdvlrfrete) bdvlrfretec100, sum(C100.bdvlrseguro) bdvlrseguroc100, sum(C100.bdvlroutdesp) bdvlroutdespc100';

  wsql = wsql || ' from VW_VEF_EMP_TMOVENT_EXP_SVA T';

  wsql = wsql || ' left outer join vef_emp_tmovproENT pro on (pro.bdcodemp = t.bdcodemp and pro.bdchave = t.bdchave and pro.bdordem = t.bdordem) ';

  wsql = wsql || ' left outer join vef_emp_tc100ENT C100 on (C100.BDCODEMP = t.BDCODEMP and C100.bdchave = t.bdchave)';

  /*wsql = wsql || ' left outer join VEF_EMP_TMOVENTRET ret on (ret.bdcodemp = t.bdcodemp and ret.bdchave = t.bdchave and ret.bdordem = t.bdordem) ';*/
  wsql = wsql || ' left outer join VEF_EMP_TMOVENTRET ret on (ret.bdcodemp = t.bdcodemp and ret.bdchave = t.bdchave) ';

  wsql = wsql || ' left outer join TTERCEIRO ter on (ter.bdcodter = t.bdcodter) ';



  wwhere = ' where bdemitente = 0 ';

  IF (:prempresa IS NOT NULL) THEN
     wwhere = wwhere || ' and '||:prempresa;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN <= '||:pranomesfinal;

     END

  wsql = wsql||wwhere || ' group by t.BDCODEMP,  t.BDCHAVE,  t.BDREFLAN, t.bdtipomov, t.BDMODELO, t.BDMODELOSTR, t.BDSERIE,
                           BDNUMDOCINI, BDDATAEMISSAO, BDDATAENTSAI, t.BDCODTER,
                           BDESPECIE, BDEMITENTE, BDCODSITNF, BDCIFFOB, t.bdordem,
                           BDVLRCONTAB, BDBASEICMS, BDBASEIPI, BDBASEST, BDISENTASICMS, BDISENTASIPI, BDOUTRASICMS,
                           BDOUTRASIPI, BDVLRICMS, BDVLRIPI, BDVLRST, BDIMPEXCLUIDAS, BDOUTROSIMP, BDDESCONTO,
                           BDICMSRETENTSAI, bdcondpgto, bdvlrpis, bdvlrcofins, bdvlrcsocial, BDVLRIR, BDRETINSS,bdcgcter ' ;

--  wsql = wsql || ' order by t.bdcodemp, t.bdreflan, t.bdtipomov ';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    bdtipomov,
    BDMODELO,
    bdmodelostr, 
    BDSERIE,
    bdnumdoc,
    BDDATAEMISSAO,
    BDDATAENTSAI,
    BDCODTER,
    BDESPECIE,
    BDEMITENTE,
    BDCODSITNF,
    BDCIFFOB,
    bdordem,
    BDVLRCONTAB,
    BDBASEICMS,
    BDBASEIPI,
    BDBASEST,
    BDISENTASICMS,
    BDISENTASIPI,
    BDOUTRASICMS,
    BDOUTRASIPI,
    BDVLRICMS,
    BDVLRIPI,
    BDVLRST,
    BDIMPEXCLUIDAS,
    BDOUTROSIMP,
    BDDESCONTO,
    BDICMSRETENT,
    bdcondpgto,
    bdvlrpis,
    bdvlrcofins,
    bdvlrcsocial,
    BDVLRIR,
    BDRETINSS,
    bdcgcter,
    BDVLRITEMPRO,
    BDVLRDESC,
    bdvlripipro,
    bdvlricmspro,
    bdvlrfretec100,
    bdvlrseguroc100,
    bdvlroutdespc100
  DO
  BEGIN

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       BEGIN
          BDVLRCONTAB = 0;
          BDBASEICMS = 0;
          BDBASEIPI = 0;
          BDBASEST = 0;
          BDISENTASICMS = 0;
          BDISENTASIPI = 0;
          BDOUTRASICMS = 0;
          BDOUTRASIPI = 0;
          BDVLRICMS = 0;
          BDVLRIPI = 0;
          BDVLRST = 0;
          BDIMPEXCLUIDAS = 0;
          BDOUTROSIMP = 0;
          BDDESCONTO = 0;
          BDICMSRETENT = 0;
          bdvlrpis = 0;
          bdvlrcofins = 0;
          bdvlrcsocial = 0;
          BDVLRIR = 0;
          BDRETINSS = 0;
          BDVLRITEMPRO = 0;
          BDVLRDESC = 0;
          bdvlripipro = 0;
          bdvlricmspro = 0;
          bdvlrfretec100 = 0;
          bdvlrseguroc100 = 0;
          bdvlroutdespc100 = 0;
       END

     bdtiporeg = '4_3_1';

    IF (bdciffob = 0) THEN
       bdciffobaux = 'CIF';
    ELSE
    IF (bdciffob = 1) THEN
       bdciffobaux = 'FOB';
    ELSE
    IF (bdciffob IS NULL) THEN
       bdciffobaux = '';

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       bdcodsitnfaux = 'S';
    ELSE
       bdcodsitnfaux = 'N';

    IF (BDCONDPGTO = 0)  THEN
       bdcondpgtoaux = '1';
    ELSE
       bdcondpgtoaux = '2';

    IF (bdmodelo IN (7,8)) THEN
       bdmodeloaux = 'RODOVIARIO';
    ELSE
    IF (bdmodelo = 9) THEN
       bdmodeloaux = 'AQUAVIARIO';
    ELSE
    IF (bdmodelo = 10) THEN
       bdmodeloaux = 'AEREO';
    ELSE
    IF (bdmodelo = 11) THEN
       bdmodeloaux = 'FERROVIARIO';
    ELSE
       bdmodeloaux = ' ';


    IF (bdvlrcontab <> 0) THEN
      BEGIN
        bdaliqpis = (bdvlrpis * 100) / bdvlrcontab;
        bdaliqcofins = (bdvlrcofins * 100) / bdvlrcontab;
        bdaliqir = (bdvlrir * 100) / bdvlrcontab;
        bdaliqcsocial = (bdvlrcsocial * 100) / bdvlrcontab;
      END
    ELSE
      BEGIN
        bdaliqpis = 0;
        bdaliqcofins = 0;
        bdaliqir = 0;
        bdaliqcsocial = 0;

      END

    IF (bdretinss <> 0) THEN
       bdbretinss = bdvlrcontab;
    ELSE
       bdbretinss = 0;

    IF (BDVLRITEMPRO IS NULL) THEN
       BDVLRITEMPRO = 0;
    IF (BDVLRDESC IS NULL) THEN
       BDVLRDESC = 0;
    IF (bdvlrfretec100 IS NULL) THEN
       bdvlrfretec100 = 0;
    IF (bdvlrseguroc100 IS NULL) THEN
       bdvlrseguroc100 = 0;
    IF (bdvlroutdespc100 IS NULL) THEN
       bdvlroutdespc100 = 0;
    IF (bdvlripipro IS NULL) THEN
       bdvlripipro = 0;
    IF (BDVLRST IS NULL) THEN
       BDVLRST = 0;
    BDVLRCONTAB2 = (BDVLRITEMPRO + BDVLRDESC + bdvlrfretec100 + bdvlrseguroc100 + bdvlroutdespc100 + bdvlripipro + BDVLRST);

    SUSPEND;
  END

    END

 IF (UPPER(PRSAIDA) = 'TRUE') THEN
    BEGIN

 wsql = 'SELECT t.bdcodemp,  t.bdchave,  t.bdreflan, t.bdtipomov, t.bdmodelo, t.bdmodelostr, t.BDSERIE, t.BDNUMDOCINI, t.BDDATAEMISSAO, t.BDDATAENTSAI, t.BDCODTER,
         t.BDESPECIE, t.BDEMITENTE, t.BDCODSITNF, t.BDCIFFOB, t.bdordem, t.BDVLRCONTAB, t.BDBASEICMS,
         t.BDBASEIPI, t.BDBASEST, t.BDISENTASICMS, t.BDISENTASIPI, t.BDOUTRASICMS, t.BDOUTRASIPI, t.BDVLRICMS, t.BDVLRIPI,  t.BDVLRST, t.BDIMPEXCLUIDAS,
         t.BDOUTROSIMP, t.BDDESCONTO, t.BDICMSRETENTSAI, t.bdcondpgto,
         coalesce(RET.bdvlrpis,0.0) BDVLRPIS,
         coalesce(RET.bdvlrcofins,0.0) BDVLRCOFINS,
         coalesce(RET.bdvlrcsocial,0.0) BDVLRCSOCIAL,
         coalesce(RET.BDVLRIR,0.0) BDVLRIR,
         coalesce(DED.BDRETINSS,0.0) BDRETINSS,
         ter.bdcgcter,

         sum(pro.BDVLRITEM) BDVLRITEMPRO, sum(pro.BDVLRDESC) BDVLRDESCPRO, sum(pro.bdvlripi) bdvlripipro,
         sum(pro.bdvlricms) bdvlricmspro, sum(C100.bdvlrfrete) bdvlrfretec100, sum(C100.bdvlrseguro) bdvlrseguroc100, sum(C100.bdvlroutdesp) bdvlroutdespc100 ';


  wsql = wsql || ' from VW_VEF_EMP_TMOVSAI_EXP_SVA T';

  wsql = wsql || ' left outer join vef_emp_tmovprosai pro on (pro.bdcodemp = t.bdcodemp and pro.bdchave = t.bdchave and pro.bdordem = t.bdordem) ';

  wsql = wsql || ' left outer join vef_emp_tc100SAI C100 on (C100.BDCODEMP = t.BDCODEMP and C100.bdchave = t.bdchave)';

  /*wsql = wsql || ' left outer join VEF_EMP_TMOVSAIRET ret on (ret.bdcodemp = t.bdcodemp and ret.bdchave = t.bdchave and ret.bdordem = t.bdordem) ';*/
  wsql = wsql || ' left outer join VEF_EMP_TMOVSAIRET ret on (ret.bdcodemp = t.bdcodemp and ret.bdchave = t.bdchave) ';

  wsql = wsql || ' left outer join VEF_EMP_TMOVSAIDED ded on (ded.bdcodemp = t.bdcodemp and ded.bdchave = t.bdchave) ';

  wsql = wsql || ' left outer join TTERCEIRO ter on (ter.bdcodter = t.bdcodter) ';


  wwhere = ' where bdemitente = 0 ';

  IF (:prempresa IS NOT NULL) THEN
     wwhere = wwhere || ' and '||:prempresa;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN <= '||:pranomesfinal;

     END

  wsql = wsql||wwhere || ' group by t.BDCODEMP,  t.BDCHAVE,  t.BDREFLAN, t.bdtipomov, t.BDMODELO, t.bdmodelostr, t.BDSERIE,
                           BDNUMDOCINI, BDDATAEMISSAO, BDDATAENTSAI, t.BDCODTER,
                           BDESPECIE, BDEMITENTE, BDCODSITNF, BDCIFFOB, t.bdordem,
                           BDVLRCONTAB, BDBASEICMS, BDBASEIPI, BDBASEST, BDISENTASICMS, BDISENTASIPI, BDOUTRASICMS,
                           BDOUTRASIPI, BDVLRICMS, BDVLRIPI, BDVLRST, BDIMPEXCLUIDAS, BDOUTROSIMP, BDDESCONTO,
                           BDICMSRETENTSAI, bdcondpgto , bdvlrpis, bdvlrcofins, bdvlrcsocial ,BDVLRIR, BDRETINSS, bdcgcter ' ;
                                   

--  wsql = wsql || ' order by t.bdcodemp, t.bdreflan, t.bdtipomov ';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    bdtipomov,
    BDMODELO,
    bdmodelostr, 
    BDSERIE,
    bdnumdoc,
    BDDATAEMISSAO,
    BDDATAENTSAI,
    BDCODTER,
    BDESPECIE,
    BDEMITENTE,
    BDCODSITNF,
    BDCIFFOB,
    bdordem,
    BDVLRCONTAB,
    BDBASEICMS,
    BDBASEIPI,
    BDBASEST,
    BDISENTASICMS,
    BDISENTASIPI,
    BDOUTRASICMS,
    BDOUTRASIPI,
    BDVLRICMS,
    BDVLRIPI,
    BDVLRST,
    BDIMPEXCLUIDAS,
    BDOUTROSIMP,
    BDDESCONTO,
    BDICMSRETENT,
    bdcondpgto,
    bdvlrpis,
    bdvlrcofins,
    bdvlrcsocial,
    BDVLRIR,
    BDRETINSS,
    bdcgcter,
    BDVLRITEMPRO,
    BDVLRDESC,
    bdvlripipro,
    bdvlricmspro,
    bdvlrfretec100,
    bdvlrseguroc100,
    bdvlroutdespc100
  DO
  BEGIN

     IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       BEGIN
          BDVLRCONTAB = 0;
          BDBASEICMS = 0;
          BDBASEIPI = 0;
          BDBASEST = 0;
          BDISENTASICMS = 0;
          BDISENTASIPI = 0;
          BDOUTRASICMS = 0;
          BDOUTRASIPI = 0;
          BDVLRICMS = 0;
          BDVLRIPI = 0;
          BDVLRST = 0;
          BDIMPEXCLUIDAS = 0;
          BDOUTROSIMP = 0;
          BDDESCONTO = 0;
          BDICMSRETENT = 0;
          bdvlrpis = 0;
          bdvlrcofins = 0;
          bdvlrcsocial = 0;
          BDVLRIR = 0;
          BDRETINSS = 0;
          BDVLRITEMPRO = 0;
          BDVLRDESC = 0;
          bdvlripipro = 0;
          bdvlricmspro = 0;
          bdvlrfretec100 = 0;
          bdvlrseguroc100 = 0;
          bdvlroutdespc100 = 0;
       END


     bdtiporeg = '4_3_1';

    IF (bdciffob = 0) THEN
       bdciffobaux = 'CIF';
    ELSE
    IF (bdciffob = 1) THEN
       bdciffobaux = 'FOB';
    ELSE
    IF (bdciffob IS NULL) THEN
       bdciffobaux = '';

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       bdcodsitnfaux = 'S';
    ELSE
         bdcodsitnfaux = 'N';

    IF (BDCONDPGTO = 0)  THEN
       bdcondpgtoaux = '1';
    ELSE
       bdcondpgtoaux = '2';

    IF (bdmodelo IN (7,8)) THEN
       bdmodeloaux = 'RODOVIARIO';
    ELSE
    IF (bdmodelo = 9) THEN
       bdmodeloaux = 'AQUAVIARIO';
    ELSE
    IF (bdmodelo = 10) THEN
       bdmodeloaux = 'AEREO';
    ELSE
    IF (bdmodelo = 11) THEN
       bdmodeloaux = 'FERROVIARIO';
    ELSE
       bdmodeloaux = ' ';


    IF (bdvlrcontab <> 0) THEN
      BEGIN
        bdaliqpis = (bdvlrpis * 100) / bdvlrcontab;
        bdaliqcofins = (bdvlrcofins * 100) / bdvlrcontab;
        bdaliqir = (bdvlrir * 100) / bdvlrcontab;
        bdaliqcsocial = (bdvlrcsocial * 100) / bdvlrcontab;
      END
    ELSE
      BEGIN
        bdaliqpis = 0;
        bdaliqcofins = 0;
        bdaliqir = 0;
        bdaliqcsocial = 0;

      END

    IF (bdretinss <> 0) THEN
       bdbretinss = bdvlrcontab;
    ELSE
       bdbretinss = 0;

    IF (BDVLRITEMPRO IS NULL) THEN
       BDVLRITEMPRO = 0;
    IF (BDVLRDESC IS NULL) THEN
       BDVLRDESC = 0;
    IF (bdvlrfretec100 IS NULL) THEN
       bdvlrfretec100 = 0;
    IF (bdvlrseguroc100 IS NULL) THEN
       bdvlrseguroc100 = 0;
    IF (bdvlroutdespc100 IS NULL) THEN
       bdvlroutdespc100 = 0;
    IF (bdvlripipro IS NULL) THEN
       bdvlripipro = 0;
    IF (BDVLRST IS NULL) THEN
       BDVLRST = 0;
    BDVLRCONTAB2 = (BDVLRITEMPRO + BDVLRDESC + bdvlrfretec100 + bdvlrseguroc100 + bdvlroutdespc100 + bdvlripipro + BDVLRST);

    SUSPEND;
  END

    END

END
^

ALTER PROCEDURE VEF_SP_SPED_D600 (
    PREMPRESA INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE)
RETURNS (
    BDCHAVES VARCHAR(20000),
    BDQUANTIDADE INTEGER,
    BDMODELO INTEGER,
    BDCODIBGE INTEGER,
    BDSERIE VARCHAR(6),
    BDSUBSERIE VARCHAR(6),
    BDCODEXP VARCHAR(2),
    BDDATAEMISSAO DATE,
    BDVALORNOTA NUMERIC(15,6),
    BDVLRSER NUMERIC(15,6),
    BDVLRSERNTRIB NUMERIC(15,6),
    BDVLRCOBTERC NUMERIC(15,6),
    BDVLROUTDESP NUMERIC(15,6))
AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
BEGIN

  --EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wsql = 'select substring(list(M.BDCHAVE) from 1 for 20000) BDCHAVES, count(M.BDCHAVE) BDQUANTIDADE, M.BDMODELO, CID.BDCODIBGE, M.BDSERIE, M.BDSUBSERIE, TELCOM.BDCODEXP, M.BDDATAEMISSAO, ';
  wsql = wsql||'       sum(M.BDVALORNOTA) BDVALORNOTA, sum(D500.BDVLRSER) BDVLRSER, sum(D500.BDVLRSERNTRIB) BDVLRSERNTRIB, ';
  wsql = wsql||'       sum(D500.BDVLRCOBTERC) BDVLRCOBTERC, sum(D500.BDVLROUTDESP) BDVLROUTDESP from VEF_EMP_TMOVSAI M ';
  wsql = wsql||'left outer join TCIDADE CID on (CID.BDCODCID = M.BDCODCID) ';
  wsql = wsql||'left outer join VEF_EMP_TD500SAI D500 on (D500.BDCODEMP = M.BDCODEMP and D500.BDCHAVE = M.BDCHAVE) ';
  wsql = wsql||'left outer join VEF_BASE_TTABCLASSCONS TELCOM on (TELCOM.BDCODCONS = D500.BDCODCONS) ';
  wsql = wsql||'where (M.BDCODEMP = '||PREMPRESA||') and ';
  wsql = wsql||'      (M.BDDATAEMISSAO between '''||prdataini||''' and '''||prdatafim||''') and ';
  wsql = wsql||'      (M.BDMODELO in (21, 22)) ';
  wsql = wsql||'group by M.BDMODELO, CID.BDCODIBGE, M.BDSERIE, M.BDSUBSERIE, TELCOM.BDCODEXP, M.BDDATAEMISSAO ';
  wsql = wsql||'order by M.BDMODELO, CID.BDCODIBGE, M.BDSERIE, M.BDSUBSERIE, TELCOM.BDCODEXP, M.BDDATAEMISSAO ';

  FOR EXECUTE STATEMENT wsql
  INTO  :BDCHAVES,
        :BDQUANTIDADE,
        :BDMODELO,
        :BDCODIBGE,
        :BDSERIE,
        :BDSUBSERIE,
        :BDCODEXP,
        :BDDATAEMISSAO,
        :BDVALORNOTA,
        :BDVLRSER,
        :BDVLRSERNTRIB,
        :BDVLRCOBTERC,
        :BDVLROUTDESP DO
  BEGIN
    SUSPEND;
  END
END
^

ALTER PROCEDURE VEF_SP_SPED_D610 (
    PREMPRESA INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE)
RETURNS (
    BDCHAVES VARCHAR(20000),
    BDMODELO INTEGER,
    BDCODIBGE INTEGER,
    BDSERIE VARCHAR(6),
    BDSUBSERIE VARCHAR(6),
    BDCODEXP VARCHAR(2),
    BDDATAEMISSAO DATE,
    BDCODNAT VARCHAR(4),
    BDCODPROD INTEGER,
    BDCODSAIDA VARCHAR(60),
    BDCODCSTICMS INTEGER,
    BDALIQICMS NUMERIC(15,6),
    BDCLASSENETEL VARCHAR(4),
    BDQTDITEM INTEGER,
    BDAPEUNIMED VARCHAR(20),
    BDVLRITEM NUMERIC(15,6),
    BDVLRDESC NUMERIC(15,6),
    BDCSTICMS VARCHAR(3),
    BDBCICMS NUMERIC(15,6),
    BDVLRICMS NUMERIC(15,6),
    BDVLRPRODPIS NUMERIC(15,6),
    BDVLRPRODCOFINS NUMERIC(15,6),
    BDVLRDESPACESSORIA NUMERIC(15,6),
    BDBCST NUMERIC(15,6),
    BDVLRST NUMERIC(15,6))
AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
BEGIN

  --EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wsql = 'select substring(list(M.BDCHAVE) from 1 for 20000) BDCHAVES, M.BDMODELO, CID.BDCODIBGE, M.BDSERIE, M.BDSUBSERIE, ';
  wsql = wsql||'         TELCOM.BDCODEXP, M.BDDATAEMISSAO, substring(cast(I.BDCODNAT as varchar(7)) from 1 for 4) BDCODNAT, P.BDCODPROD, VINC.BDCODSAIDA, ';
  wsql = wsql||'         P.BDCODCSTICMS, P.BDALIQICMS, ';
  wsql = wsql||'         ENETEL.BDCODEXP BDCLASSENETEL, sum(P.BDQTDITEM) BDQTDITEM, UNIMED.BDAPEUNIMED, sum(P.BDVLRITEM) BDVLRITEM, ';
  wsql = wsql||'         sum(P.BDVLRDESC) BDVLRDESC, ICMS.BDCSTICMS, sum(P.BDBCICMS) BDBCICMS, sum(P.BDVLRICMS) BDVLRICMS, ';
  wsql = wsql||'         sum(P.BDVLRPIS) BDVLRPRODPIS, sum(P.BDVLRCOFINS) BDVLRPRODCOFINS, sum(P.BDVLRDESPACESSORIA) + sum(P.BDVLRIPI) + sum(P.BDVLRST) BDVLRDESPACESSORIA, ';
  wsql = wsql||'         sum(P.BDBCST) BDBCST, sum(P.BDVLRST) BDVLRST ';
  wsql = wsql||'  from (select * ';
  wsql = wsql||'        from VEF_EMP_TMOVSAI ';
  wsql = wsql||'        where (BDCODEMP = '||PREMPRESA||') and ';
  wsql = wsql||'              (BDDATAEMISSAO between '''||prdataini||''' and '''||prdatafim||''') and ';
  wsql = wsql||'              (BDMODELO in (21, 22))) M ';
  wsql = wsql||'  left outer join VEF_EMP_TMOVSAIITENS I on (M.BDCODEMP = I.BDCODEMP and M.BDCHAVE = I.BDCHAVE) ';
  wsql = wsql||'  left outer join TCIDADE CID on (CID.BDCODCID = M.BDCODCID) ';
  wsql = wsql||'  left outer join VEF_EMP_TD500SAI D500 on (D500.BDCODEMP = M.BDCODEMP and D500.BDCHAVE = M.BDCHAVE) ';
  wsql = wsql||'  left outer join VEF_BASE_TTABCLASSCONS TELCOM on (TELCOM.BDCODCONS = D500.BDCODCONS) ';
  wsql = wsql||'  left outer join VEF_EMP_TMOVPROSAI P on (P.BDCODEMP = I.BDCODEMP and P.BDCHAVE = I.BDCHAVE and P.BDORDEM = I.BDORDEM) ';
  wsql = wsql||'  left outer join TCADPRO_VINC VINC on (VINC.BDCODPROD = P.BDCODPROD and VINC.BDCODEMP = M.BDCODEMP) ';
  wsql = wsql||'  left outer join TUNIDADEMEDIDA UNIMED on (UNIMED.BDCODUNIMED = VINC.BDCODUNIMED) ';
  wsql = wsql||'  left outer join VEF_BASE_TTABCSTICMS ICMS on (ICMS.BDCODCSTICMS = P.BDCODCSTICMS) ';
  wsql = wsql||'  left outer join VEF_EMP_TENETELE D610 on (P.BDCODEMP = D610.BDCODEMP and P.BDCHAVE = D610.BDCHAVE and P.BDORDEM = D610.BDORDEM and P.BDORDEMPRO = D610.BDORDEMPRO) ';
  wsql = wsql||'  left outer join VEF_BASE_TTABCLASSENETEL ENETEL on (ENETEL.BDORDEM = D610.BDCODCLAENETEL) ';
  wsql = wsql||'  group by M.BDDATAEMISSAO, M.BDMODELO, CID.BDCODIBGE, M.BDSERIE, M.BDSUBSERIE, TELCOM.BDCODEXP, M.BDDATAEMISSAO, I.BDCODNAT, P.BDCODPROD, VINC.BDCODSAIDA, P.BDCODCSTICMS, P.BDALIQICMS, ENETEL.BDCODEXP, UNIMED.BDAPEUNIMED, ICMS.BDCSTICMS ';
  wsql = wsql||'  order by M.BDDATAEMISSAO, M.BDMODELO, CID.BDCODIBGE, M.BDSERIE, M.BDSUBSERIE, TELCOM.BDCODEXP, M.BDDATAEMISSAO, I.BDCODNAT, P.BDCODPROD, VINC.BDCODSAIDA, P.BDCODCSTICMS, P.BDALIQICMS ';

  FOR EXECUTE STATEMENT wsql
  INTO  :BDCHAVES,
        :BDMODELO,
        :BDCODIBGE,
        :BDSERIE,
        :BDSUBSERIE,
        :BDCODEXP,
        :BDDATAEMISSAO,
        :BDCODNAT,
        :BDCODPROD,
        :BDCODSAIDA,
        :BDCODCSTICMS,
        :BDALIQICMS,
        :BDCLASSENETEL,
        :BDQTDITEM,
        :BDAPEUNIMED,
        :BDVLRITEM,
        :BDVLRDESC,
        :BDCSTICMS,
        :BDBCICMS,
        :BDVLRICMS,
        :BDVLRPRODPIS,
        :BDVLRPRODCOFINS,
        :BDVLRDESPACESSORIA,
        :BDBCST,
        :BDVLRST DO
  BEGIN
    SUSPEND;
  END
END
^

CREATE OR ALTER procedure VEF_SP_SPED_D696 (
    PREMPRESA integer,
    PRDATAINI date,
    PRDATAFIM date)
returns (
    BDCHAVES varchar(10000),
    BDMODELO integer,
    BDSERIE varchar(6),
    BDCODNAT varchar(4),
    BDCODCSTICMS integer,
    BDALIQICMS numeric(15,6),
    BDVLRITEM numeric(15,6),
    BDCSTICMS varchar(3),
    BDBCICMS numeric(15,6),
    BDVLRICMS numeric(15,6),
    BDBCST numeric(15,6),
    BDVLRST numeric(15,6))
as
declare variable WSQL varchar(10480);
declare variable WDATINI varchar(10);
declare variable WDATFIN varchar(10);
BEGIN

  --EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

    wsql = 'select substring(list(M.BDCHAVE) from 1 for 3000) BDCHAVES, M.BDMODELO, M.BDSERIE, ';
    wsql = wsql||'     substring(cast(I.BDCODNAT as varchar(7)) from 1 for 4) BDCODNAT, P.BDCODCSTICMS, P.BDALIQICMS, ';
    wsql = wsql||'     sum(P.BDVLRITEM) + sum(P.BDVLRDESPACESSORIA) + sum(P.BDVLRIPI) + sum(P.BDVLRST) BDVLRITEM, ICMS.BDCSTICMS, ';
    wsql = wsql||'     sum(P.BDBCICMS) BDBCICMS, sum(P.BDVLRICMS) BDVLRICMS, sum(P.BDBCST) BDBCST, sum(P.BDVLRST) BDVLRST ';
    wsql = wsql||'from (select * ';
    wsql = wsql||'      from VEF_EMP_TMOVSAI ';
    wsql = wsql||'      where BDCODEMP = '||PREMPRESA||' and ';
    wsql = wsql||'            (BDDATAEMISSAO between '''||prdataini||''' and '''||prdatafim||''') and ';
    wsql = wsql||'            BDMODELO in (21, 22)) M ';
    wsql = wsql||'left outer join VEF_EMP_TMOVSAIITENS I on (M.BDCODEMP = I.BDCODEMP and M.BDCHAVE = I.BDCHAVE) ';
    wsql = wsql||'left outer join VEF_EMP_TMOVPROSAI P on (P.BDCODEMP = I.BDCODEMP and P.BDCHAVE = I.BDCHAVE and P.BDORDEM = I.BDORDEM) ';
    wsql = wsql||'left outer join VEF_BASE_TTABCSTICMS ICMS on (ICMS.BDCODCSTICMS = P.BDCODCSTICMS) ';
    wsql = wsql||'group by M.BDMODELO, M.BDSERIE, I.BDCODNAT, P.BDCODCSTICMS, P.BDALIQICMS, ICMS.BDCSTICMS ';
    wsql = wsql||'order by M.BDMODELO, M.BDSERIE, I.BDCODNAT, P.BDCODCSTICMS, P.BDALIQICMS ';

  FOR EXECUTE STATEMENT wsql
  INTO  :BDCHAVES,
        :BDMODELO,
        :BDSERIE,
        :BDCODNAT,
        :BDCODCSTICMS,
        :BDALIQICMS,
        :BDVLRITEM,
        :BDCSTICMS,
        :BDBCICMS,
        :BDVLRICMS,
        :BDBCST,
        :BDVLRST DO
  BEGIN
    SUSPEND;
  END
END
^

/* Restore proc. body: VEF_SP_SVA_4310_TREDZ */
ALTER PROCEDURE VEF_SP_SVA_4310_TREDZ(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDDATAREDZ DATE,
BDCODPROD INTEGER,
BDQTDITEM NUMERIC(15,3),
BDALIQICMS NUMERIC(15,2),
BDCAMPO8 NUMERIC(15,2),
BDVLRTOTPRO NUMERIC(15,2),
BDALIQPIS NUMERIC(15,4),
BDVLRPIS NUMERIC(15,2),
BDALIQCOFINS NUMERIC(15,4),
BDVLRCOFINS NUMERIC(15,2),
BDNCMPROD INTEGER,
BDTIPOREG VARCHAR(10))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WMES SMALLINT;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WAUX INTEGER;
DECLARE VARIABLE WDATAINI VARCHAR(10);
DECLARE VARIABLE WDATAFIM VARCHAR(10);
BEGIN
  /* Procedure Text */

  /* giovanni ultimo dia...*/

 EXECUTE PROCEDURE sp_seta_competencia(pranomesfinal, NULL, NULL);

 wmes = CAST(SUBSTRING(CAST(pranomesfinal AS VARCHAR(6)) FROM 5) AS SMALLINT);
 wano = CAST(SUBSTRING(CAST(pranomesfinal AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
 SELECT ultdia FROM ULTIMO_DIA_MES(:wmes,:wano) INTO waux;

 wdataini = SUBSTRING(CAST(pranomesinicial AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(pranomesinicial AS VARCHAR(6)) FROM 1 FOR 4);
 wdatafim = SUBSTRING(CAST(pranomesfinal AS VARCHAR(6)) FROM 5)||'/'||
             waux|| '/'||SUBSTRING(CAST(pranomesfinal AS VARCHAR(6)) FROM 1 FOR 4);

 wsql = ' select t.BDCODEMP, t.BDDATAREDZ, t.BDCODPROD, CADPRO.bdncmprod, t.BDQTDITEM, t.BDALIQICMS, t.bdvlrtotpro  ';

 wsql = wsql || ' from VW_VEF_EMP_TREDZ_EXP_SVA T,  tcadpro_VINC CADPRO ';


 wwhere = '';

  IF (:prempresa IS NOT NULL) THEN
     wwhere = wwhere || :prempresa;

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';

  wwhere = wwhere|| ' (CADPRO.BDCODEMP = T.BDCODEMP AND cadpro.bdcodprod = t.bdcodprod) ';

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere|| ' BDDATAREDZ between cast('||''''||wdataini||''''||' as date) and cast('||''''||wdatafim||''''||' as date)';

     END


  IF (wwhere <> TRIM('')) THEN
     wsql = wsql||' where ' || wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDDATAREDZ,
    BDCODPROD,
    bdncmprod,
    BDQTDITEM,
    BDALIQICMS,
    bdvlrtotpro
  DO

  BEGIN
    IF ((bdvlrtotpro > 0) AND (bdaliqicms > 0)) THEN
       bdcampo8 = bdvlrtotpro * bdaliqicms / 100;
    ELSE
       bdcampo8 = 0;

    bdreflan = EXTRACT(YEAR FROM bddataredz)||SUBSTRING(bddataredz FROM 6 FOR 2);
    bdtiporeg = '4_3_10';

    bdaliqpis = 0.65;

    bdvlrpis =  bdvlrtotpro * bdaliqpis / 100;

    bdaliqcofins = 3;

    bdvlrcofins = bdvlrtotpro * bdaliqcofins / 100;

    SUSPEND;
  END
END
^

/* Restore proc. body: VEF_SP_SVA_432 */
ALTER PROCEDURE VEF_SP_SVA_432(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRENTRADA VARCHAR(5),
PRSAIDA VARCHAR(5),
PRODFRETE INTEGER,
PRODENERGIA INTEGER,
PRODAGUA INTEGER,
PRODTELECOM INTEGER,
PRODGENERICO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDORDEM INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDBASEICMS NUMERIC(15,2),
BDBASEIPI NUMERIC(15,2),
BDBASEST NUMERIC(15,2),
BDISENTASICMS NUMERIC(15,2),
BDISENTASIPI NUMERIC(15,2),
BDOUTRASICMS NUMERIC(15,2),
BDOUTRASIPI NUMERIC(15,2),
BDVLRICMS NUMERIC(15,2),
BDVLRIPI NUMERIC(15,2),
BDVLRST NUMERIC(15,2),
BDIMPEXCLUIDAS NUMERIC(15,2),
BDOUTROSIMP NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDICMSRETENT NUMERIC(15,2),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,2),
BDVLRDESC NUMERIC(15,2),
BDVLRIPIPRO NUMERIC(15,2),
BDVLRICMSPRO NUMERIC(15,2),
BDVLRFRETEC100 NUMERIC(15,2),
BDVLRSEGUROC100 NUMERIC(15,2),
BDVLROUTDESPC100 NUMERIC(15,2),
BDORDEMPRO INTEGER,
BDCODPROD INTEGER,
BDDESCPROD VARCHAR(200),
BDCODNAT INTEGER,
BDNCMPROD INTEGER,
BDQTDITEM NUMERIC(15,3),
BDAPEUNIMED VARCHAR(3),
BDALIQIPIPRO NUMERIC(15,2),
BDBCIPIPRO NUMERIC(15,2),
BDCODCSTICMS VARCHAR(3),
BDALIQICMSPRO NUMERIC(15,2),
BDBCICMSPRO NUMERIC(15,2),
BDBCSTPRO NUMERIC(15,2),
BDVLRSTMOVPRO NUMERIC(15,2),
BDMOVFISICO VARCHAR(5),
BDCODEXPCSTIPI INTEGER,
BDCODCSTPIS INTEGER,
BDALIQPIS NUMERIC(15,4),
BDBCPIS NUMERIC(15,3),
BDVLRPIS NUMERIC(15,2),
BDCODCSTCOF INTEGER,
BDALIQCOFINS NUMERIC(15,4),
BDBCCOFINS NUMERIC(15,3),
BDVLRCOFINS NUMERIC(15,2),
BDCSTPIS VARCHAR(3),
BDCSTCOF VARCHAR(3),
BDVLRUNITARIO NUMERIC(15,4),
BDVLRCOFINSEXP NUMERIC(15,2),
BDVLRCOFINSTRIBINT NUMERIC(15,2),
BDVLRCOFINSNTRIBINT NUMERIC(15,2),
BDVLRPISEXP NUMERIC(15,2),
BDVLRPISTRIBINT NUMERIC(15,2),
BDVLRPISNTRIBINT NUMERIC(15,2),
BDLANBCICMSISEOUT INTEGER,
BDTIPOREG VARCHAR(10),
BDPRODFRETE VARCHAR(5),
BDPRODENERGIA VARCHAR(5),
BDPRODAGUA VARCHAR(5),
BDPRODTELECOM VARCHAR(5),
BDPRODGENERICO VARCHAR(5))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQLAUX VARCHAR(32700);
DECLARE VARIABLE WLANBCICMSISEOUT INTEGER;
DECLARE VARIABLE WCODNATAUX CHAR(1);
DECLARE VARIABLE WCSTIPI VARCHAR(2);
DECLARE VARIABLE WCSTIPIAUX VARCHAR(1);
BEGIN
  /* Procedure Text */

 EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

 BDPRODFRETE = 'FALSE';
 BDPRODENERGIA  = 'FALSE';
 BDPRODAGUA  = 'FALSE';
 BDPRODTELECOM  = 'FALSE';
 BDPRODGENERICO  = 'FALSE';

 IF (UPPER(PRENTRADA) = 'TRUE') THEN
    BEGIN

 wsql = 'SELECT t.bdcodemp,  t.bdchave,  t.bdreflan, t.bdtipomov, t.bdmodelo, t.bdmodelostr, t.BDSERIE, t.BDNUMDOCINI, t.BDDATAEMISSAO, t.BDDATAENTSAI, t.BDCODTER,
         t.BDESPECIE, t.BDEMITENTE, t.BDCODSITNF, t.BDCIFFOB, t.bdordem, t.BDVLRCONTAB, t.BDBASEICMS,
         t.BDBASEIPI, t.BDBASEST, t.BDISENTASICMS, t.BDISENTASIPI, t.BDOUTRASICMS, t.BDOUTRASIPI, t.BDVLRICMS, t.BDVLRIPI,  t.BDVLRST, t.BDIMPEXCLUIDAS,
         t.BDOUTROSIMP, t.BDDESCONTO, t.BDICMSRETENTSAI, t.bdcondpgto,

         pro.BDVLRITEM BDVLRITEMPRO, pro.BDVLRDESC BDVLRDESCPRO, pro.bdvlripi bdvlripipro, pro.bdvlricms bdvlricmspro,
         c100.bdvlrfrete, c100.bdvlrseguro, c100.bdvlroutdesp,

         pro.bdordempro , pro.BDCODPROD, CADPRO.BDDESCPROD, bdcodnat, BDNCMPROD, BDQTDITEM, BDAPEUNIMED, pro.BDALIQIPI, BDBCIPI,
         CSTICMS.BDCSTICMS, pro.BDALIQICMS, BDBCICMS, bdbcst, pro.BDVLRST BDVLRSTMOVPRO, bdmovfisico, CSTIPI.BDCODEXPCSTIPI,
         pro.BDCODCSTPIS, pro.BDALIQPIS, BDBCPIS, BDVLRPIS, pro.BDCODCSTCOF , BDALIQCOFINS , BDBCCOFINS, BDVLRCOFINS, pis.bdcstpis, cof.bdcstcof ';

  wsql = wsql || ' from VW_VEF_EMP_TMOVENT_EXP_SVA T';
  wsql = wsql || ' left outer join vef_emp_tmovproENT pro on (pro.bdcodemp = t.bdcodemp and pro.bdchave = t.bdchave and pro.bdordem = t.bdordem) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTIPI CSTIPI ON ( PRO.bdcodcstipi = CSTIPI.bdcodcstipi) ';
  wsql = wsql || ' left outer join vef_emp_tc100ENT C100 on (C100.BDCODEMP = t.BDCODEMP and C100.bdchave = t.bdchave)';
  wsql = wsql || ' left outer join TCADPRO_VINC CADPRO on (CADPRO.BDCODEMP = PRO.BDCODEMP AND cadpro.bdcodprod = pro.bdcodprod)';
  wsql = wsql || ' left outer join tunidademedida UM on (UM.bdcodunimed = CADPRO.bdcodunimed) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTPIS pis on (pis.BDCODCSTPIS = pro.BDCODCSTPIS) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTCOF cof on (cof.BDCODCSTCOF = pro.BDCODCSTCOF) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTICMS CSTICMS ON ( PRO.bdcodcstICMS = CSTICMS.bdcodcstICMS) ';

  wwhere = ' where bdemitente = 0 and bdordempro is not null ';

  IF (:prempresa IS NOT NULL) THEN
     wwhere = wwhere || ' and '||:prempresa;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN <= '||:pranomesfinal;

     END

  wsql = wsql||wwhere; --|| ' order by bdcodemp, bdreflan, bdtipomov  ' ;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    bdtipomov,
    BDMODELO,
    BDMODELOSTR,
    BDSERIE,
    bdnumdoc,
    BDDATAEMISSAO,
    BDDATAENTSAI,
    BDCODTER,
    BDESPECIE,
    BDEMITENTE,
    BDCODSITNF,
    BDCIFFOB,
    bdordem,
    BDVLRCONTAB,
    BDBASEICMS,
    BDBASEIPI,
    BDBASEST,
    BDISENTASICMS,
    BDISENTASIPI,
    BDOUTRASICMS,
    BDOUTRASIPI,
    BDVLRICMS,
    BDVLRIPI,
    BDVLRST,
    BDIMPEXCLUIDAS,
    BDOUTROSIMP,
    BDDESCONTO,
    BDICMSRETENT,
    bdcondpgto,
    BDVLRITEMPRO,
    BDVLRDESC,
    bdvlripipro,
    bdvlricmspro,
    bdvlrfretec100,
    bdvlrseguroc100,
    bdvlroutdespc100,
    bdordempro,
    bdcodprod,
    BDDESCPROD,
    bdcodnat,
    BDNCMPROD,
    BDQTDITEM,
    BDAPEUNIMED,
    bdaliqipipro,
    bdbcipipro,
    BDCODCSTICMS,
    bdaliqicmspro,
    bdbcicmspro,
    bdbcstpro,
    bdvlrstmovpro,
    bdmovfisico,
    BDCODEXPCSTIPI,
    BDCODCSTPIS,
    BDALIQPIS,
    BDBCPIS,
    BDVLRPIS,
    BDCODCSTCOF ,
    BDALIQCOFINS ,
    BDBCCOFINS,
    BDVLRCOFINS,
    bdcstpis,
    bdcstcof

  DO

  BEGIN

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       BEGIN
          BDVLRCONTAB = 0;
          BDBASEICMS = 0;
          BDBASEIPI = 0;
          BDBASEST = 0;
          BDISENTASICMS = 0;
          BDISENTASIPI = 0;
          BDOUTRASICMS = 0;
          BDOUTRASIPI = 0;
          BDVLRICMS = 0;
          BDVLRIPI = 0;
          BDVLRST = 0;
          BDIMPEXCLUIDAS = 0;
          BDOUTROSIMP = 0;
          BDDESCONTO = 0;
          BDICMSRETENT = 0;
          BDVLRITEMPRO = 0;
          BDVLRDESC = 0;
          bdvlripipro = 0;
          bdvlricmspro = 0;
          bdvlrfretec100 = 0;
          bdvlrseguroc100 = 0;
          bdvlroutdespc100 = 0;
          BDQTDITEM = 0;
          bdaliqipipro = 0;
          bdbcipipro = 0;
          bdaliqicmspro = 0;
          bdbcicmspro = 0;
          bdbcstpro = 0;
          bdvlrstmovpro = 0;
          BDALIQPIS = 0;
          BDBCPIS = 0;
          BDVLRPIS = 0;
          BDALIQCOFINS  = 0;
          BDBCCOFINS = 0;
          BDVLRCOFINS = 0;
       END

    IF (UPPER(bdmovfisico) = 'TRUE') THEN
       bdmovfisico = 'S';
    ELSE
       bdmovfisico = 'N';

    IF (bdqtditem > 0)  THEN
       bdvlrunitario = bdvlritempro / bdqtditem;

    bdtiporeg = '4_3_2';

    IF (bdciffob = 0) THEN
       bdciffobaux = 'CIF';
    ELSE
    IF (bdciffob = 1) THEN
       bdciffobaux = 'FOB';
    ELSE
    IF (bdciffob IS NULL) THEN
       bdciffobaux = '';

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       bdcodsitnfaux = 'S';
    ELSE
         bdcodsitnfaux = 'N';

    IF (BDCONDPGTO = 0)  THEN
       bdcondpgtoaux = '1';
    ELSE
       bdcondpgtoaux = '2';

--    if (wlanbcicmsiseout is null) then
--      begin
--        wsqlaux = 'select bdlanbcicmsiseout from VW_VEF_BASE_TEMPPARGER where bdcodemp = ' || :bdcodemp;
--        execute statement wsqlaux into wlanbcicmsiseout;
--      end

    IF (bdaliqipipro > 0) THEN
       wlanbcicmsiseout = 1;
    ELSE
      BEGIN
        IF (wlanbcicmsiseout = 0) THEN
           wlanbcicmsiseout = 1;
        ELSE
           wlanbcicmsiseout = 2;
      END

    bdlanbcicmsiseout = wlanbcicmsiseout;
    wcodnataux =  SUBSTRING(CAST(bdcodnat AS VARCHAR(10)) FROM 1 FOR 1);

    bdvlrcofinsexp = 0;
    IF (((bdcodcstcof IN (52,62)) OR (bdcodcstcof IN (54,55,56,64,65,66,73,75,67,98)) AND  wcodnataux = '3')) THEN
       bdvlrcofinsexp = bdvlrcofins;

    BDVLRCOFINSTRIBINT = 0;
    IF (((bdcodcstcof IN (50,53,60,63)) OR (bdcodcstcof IN (54,64,73,75,56,66,67,98)) AND  (wcodnataux <> '3'))) THEN
       BDVLRCOFINSTRIBINT = bdvlrcofins;

    BDVLRCOFINSNTRIBINT = 0;
    IF (((bdcodcstcof IN (51,61,70,71,72,74,53,63)) OR (bdcodcstcof IN (55,65,56,66,67,98)) AND  (wcodnataux <> '3'))) THEN
       BDVLRCOFINSNTRIBINT = bdvlrcofins;


    bdvlrpisexp = 0;
    IF (((bdcodcstcof IN (52,62)) OR (bdcodcstcof IN (54,55,56,64,65,66,73,75,67,98)) AND  wcodnataux = '3')) THEN
       bdvlrpisexp = bdvlrpis;

    bdvlrpistribint = 0;
    IF (((bdcodcstcof IN (50,53,60,63)) OR (bdcodcstcof IN (54,64,73,75,56,66,67,98)) AND  (wcodnataux <> '3'))) THEN
       bdvlrpistribint = bdvlrpis;

    bdvlrpisntribint = 0;
    IF (((bdcodcstcof IN (51,61,70,71,72,74,53,63)) OR (bdcodcstcof IN (55,65,56,66,67,98)) AND  (wcodnataux <> '3'))) THEN
       bdvlrpisntribint = bdvlrpis;

    --rotina usada no suprema...
    WCSTIPI = CAST(BDCODEXPCSTIPI AS VARCHAR(2));
    IF (WCSTIPI IS NULL) THEN
       WCSTIPI = '00';
    WCSTIPIaux = SUBSTRING(WCSTIPI FROM 1 FOR 1);
    IF (WCSTIPIaux <> '0' AND WCSTIPIaux <> '4')  THEN
       BEGIN
         IF (WCSTIPIaux = '5') THEN
            WCSTIPIaux = '0';
         ELSE
            WCSTIPIaux = '4';
       END
    WCSTIPI = WCSTIPIaux || SUBSTRING(WCSTIPI FROM 2 FOR 1);
    BDCODEXPCSTIPI = CAST(WCSTIPI AS INTEGER);

    -- se produto for vazio, deve lançar o produto default informado na tela do sva
    IF (bdcodprod IS NULL) THEN
       BEGIN
         IF (bdmodelo IN (21,22)) THEN -- telecom
            BEGIN
              IF (PRODTELECOM IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODTELECOM;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODTELECOM  = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo IN (7,8,9,10,11,12,13,14,15,16,27,27,57)) THEN -- frete
            BEGIN
              IF (PRODFRETE IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = '|| :PRODFRETE;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODFRETE = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo = 6) THEN -- energia
            BEGIN
              IF (PRODENERGIA IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODENERGIA;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODENERGIA  = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo IN (28,29)) THEN -- agua
            BEGIN
              IF (PRODAGUA IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODAGUA;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODAGUA  = 'TRUE';
                 END
            END

         IF (bdcodprod IS NULL) THEN -- generico
            BEGIN
              IF (PRODGENERICO IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODGENERICO;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODGENERICO  = 'TRUE';
                 END
            END

         bdapeunimed = 'UN';
         bdordempro = 1;
         bdqtditem = 1;
         bdvlritempro = bdvlrcontab;
         bdvlrunitario = bdvlritempro;
         bdvlrdesc = bddesconto;
         bdbcicmspro = bdbaseicms;
         bdbcipipro = bdbaseipi;
         bdbcstpro = bdbasest;
         bdvlricmspro = bdvlricms;
         bdvlripipro = bdvlripi;
         bdvlrstmovpro = bdvlrst;
       END


    SUSPEND;


  END

    END

 IF (UPPER(PRSAIDA) = 'TRUE') THEN
    BEGIN

 wsql = 'SELECT t.bdcodemp,  t.bdchave,  t.bdreflan, t.bdtipomov, t.bdmodelo, t.bdmodelostr, t.BDSERIE, t.BDNUMDOCINI, t.BDDATAEMISSAO, t.BDDATAENTSAI, t.BDCODTER,
         t.BDESPECIE, t.BDEMITENTE, t.BDCODSITNF, t.BDCIFFOB, t.bdordem, t.BDVLRCONTAB, t.BDBASEICMS,
         t.BDBASEIPI, t.BDBASEST, t.BDISENTASICMS, t.BDISENTASIPI, t.BDOUTRASICMS, t.BDOUTRASIPI, t.BDVLRICMS, t.BDVLRIPI,  t.BDVLRST, t.BDIMPEXCLUIDAS,
         t.BDOUTROSIMP, t.BDDESCONTO, t.BDICMSRETENTSAI, t.bdcondpgto,

         pro.BDVLRITEM BDVLRITEMPRO, pro.BDVLRDESC BDVLRDESCPRO, pro.bdvlripi bdvlripipro, pro.bdvlricms bdvlricmspro,
         c100.bdvlrfrete, c100.bdvlrseguro, c100.bdvlroutdesp,

         pro.bdordempro , pro.BDCODPROD, CADPRO.BDDESCPROD, bdcodnat, BDNCMPROD, BDQTDITEM, BDAPEUNIMED, pro.BDALIQIPI, BDBCIPI,
         CSTICMS.BDCSTICMS, pro.BDALIQICMS, BDBCICMS, bdbcst, pro.BDVLRST BDVLRSTMOVPRO, bdmovfisico , CSTIPI.BDCODEXPCSTIPI,
         pro.BDCODCSTPIS, pro.BDALIQPIS, BDBCPIS, BDVLRPIS, pro.BDCODCSTCOF , BDALIQCOFINS , BDBCCOFINS, BDVLRCOFINS, pis.bdcstpis, cof.bdcstcof ';


  wsql = wsql || ' from VW_VEF_EMP_TMOVSAI_EXP_SVA T';

  wsql = wsql || ' left outer join vef_emp_tmovproSAI pro on (pro.bdcodemp = t.bdcodemp and pro.bdchave = t.bdchave and pro.bdordem = t.bdordem) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTIPI CSTIPI ON ( PRO.bdcodcstipi = CSTIPI.bdcodcstipi) ';
  wsql = wsql || ' left outer join vef_emp_tc100SAI C100 on (C100.BDCODEMP = t.BDCODEMP and C100.bdchave = t.bdchave)';
  wsql = wsql || ' left outer join TCADPRO_vinc CADPRO on (cadpro.bdcodemp = pro.bdcodemp and cadpro.bdcodprod = pro.bdcodprod)';
  wsql = wsql || ' left outer join tunidademedida UM on (UM.bdcodunimed = CADPRO.bdcodunimed) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTPIS pis on (pis.BDCODCSTPIS = pro.BDCODCSTPIS) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTCOF cof on (cof.BDCODCSTCOF = pro.BDCODCSTCOF) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTICMS CSTICMS ON ( PRO.bdcodcstICMS = CSTICMS.bdcodcstICMS) ';

  wwhere = ' where bdemitente = 0 and bdordempro is not null ';

  IF (:prempresa IS NOT NULL) THEN
     wwhere = wwhere || ' and '||:prempresa;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN <= '||:pranomesfinal;

     END

  wsql = wsql||wwhere; --|| ' order by bdcodemp, bdreflan, bdtipomov  ' ;

  wlanbcicmsiseout = NULL;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    bdtipomov,
    BDMODELO,
    BDMODELOSTR,
    BDSERIE,
    bdnumdoc,
    BDDATAEMISSAO,
    BDDATAENTSAI,
    BDCODTER,
    BDESPECIE,
    BDEMITENTE,
    BDCODSITNF,
    BDCIFFOB,
    bdordem,
    BDVLRCONTAB,
    BDBASEICMS,
    BDBASEIPI,
    BDBASEST,
    BDISENTASICMS,
    BDISENTASIPI,
    BDOUTRASICMS,
    BDOUTRASIPI,
    BDVLRICMS,
    BDVLRIPI,
    BDVLRST,
    BDIMPEXCLUIDAS,
    BDOUTROSIMP,
    BDDESCONTO,
    BDICMSRETENT,
    bdcondpgto,
    BDVLRITEMPRO,
    BDVLRDESC,
    bdvlripipro,
    bdvlricmspro,
    bdvlrfretec100,
    bdvlrseguroc100,
    bdvlroutdespc100,
    bdordempro,
    bdcodprod,
    BDDESCPROD,
    bdcodnat,
    BDNCMPROD,
    BDQTDITEM,
    BDAPEUNIMED,
    bdaliqipipro,
    bdbcipipro,
    BDCODCSTICMS,
    bdaliqicmspro,
    bdbcicmspro,
    bdbcstpro,
    bdvlrstmovpro,
    bdmovfisico,
    BDCODEXPCSTIPI,
    BDCODCSTPIS,
    BDALIQPIS,
    BDBCPIS,
    BDVLRPIS,
    BDCODCSTCOF ,
    BDALIQCOFINS ,
    BDBCCOFINS,
    BDVLRCOFINS,
    bdcstpis,
    bdcstcof

  DO

  BEGIN

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       BEGIN
          BDVLRCONTAB = 0;
          BDBASEICMS = 0;
          BDBASEIPI = 0;
          BDBASEST = 0;
          BDISENTASICMS = 0;
          BDISENTASIPI = 0;
          BDOUTRASICMS = 0;
          BDOUTRASIPI = 0;
          BDVLRICMS = 0;
          BDVLRIPI = 0;
          BDVLRST = 0;
          BDIMPEXCLUIDAS = 0;
          BDOUTROSIMP = 0;
          BDDESCONTO = 0;
          BDICMSRETENT = 0;
          BDVLRITEMPRO = 0;
          BDVLRDESC = 0;
          bdvlripipro = 0;
          bdvlricmspro = 0;
          bdvlrfretec100 = 0;
          bdvlrseguroc100 = 0;
          bdvlroutdespc100 = 0;
          BDQTDITEM = 0;
          bdaliqipipro = 0;
          bdbcipipro = 0;
          bdaliqicmspro = 0;
          bdbcicmspro = 0;
          bdbcstpro = 0;
          bdvlrstmovpro = 0;
          BDALIQPIS = 0;
          BDBCPIS = 0;
          BDVLRPIS = 0;
          BDALIQCOFINS  = 0;
          BDBCCOFINS = 0;
          BDVLRCOFINS = 0;
       END


    IF (UPPER(bdmovfisico) = 'TRUE') THEN
       bdmovfisico = 'S';
    ELSE
       bdmovfisico = 'N';

    IF (bdqtditem > 0) THEN
       bdvlrunitario = bdvlritempro / bdqtditem;

    bdtiporeg = '4_3_2';

    IF (bdciffob = 0) THEN
       bdciffobaux = 'CIF';
    ELSE
    IF (bdciffob = 1) THEN
       bdciffobaux = 'FOB';
    ELSE
    IF (bdciffob IS NULL) THEN
       bdciffobaux = '';

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       bdcodsitnfaux = 'S';
    ELSE
         bdcodsitnfaux = 'N';

    IF (BDCONDPGTO = 0)  THEN
       bdcondpgtoaux = '1';
    ELSE
       bdcondpgtoaux = '2';

--    if (wlanbcicmsiseout is null)  then
--      begin
--        wsqlaux = 'select bdlanbcicmsiseout from VW_VEF_BASE_TEMPPARGER where bdcodemp = ' || :bdcodemp;
--        execute statement wsqlaux into wlanbcicmsiseout;
--      end

    IF (bdaliqipipro > 0) THEN
       wlanbcicmsiseout = 1;
    ELSE
      BEGIN
        IF (wlanbcicmsiseout = 0) THEN
           wlanbcicmsiseout = 1;
        ELSE
           wlanbcicmsiseout = 2;
      END

    bdlanbcicmsiseout = wlanbcicmsiseout;
    wcodnataux =  SUBSTRING(CAST(bdcodnat AS VARCHAR(10)) FROM 1 FOR 1);

    bdvlrcofinsexp = 0;
    IF (wcodnataux = '7') THEN
       bdvlrcofinsexp = bdvlrcofins;

    BDVLRCOFINSTRIBINT = 0;

    BDVLRCOFINSNTRIBINT = 0;
    IF (wcodnataux <> '7') THEN
       BDVLRCOFINSNTRIBINT = bdvlrcofins;


    bdvlrpisexp = 0;
    IF (wcodnataux = '7') THEN
       bdvlrpisexp = bdvlrpis;

    bdvlrpistribint = 0;

    bdvlrpisntribint = 0;
    IF (wcodnataux <> '7') THEN
       bdvlrpisntribint = bdvlrpis;

    --rotina usada no suprema...
    WCSTIPI = CAST(BDCODEXPCSTIPI AS VARCHAR(2));
    IF (WCSTIPI IS NULL) THEN
       WCSTIPI = '00';
    WCSTIPIaux = SUBSTRING(WCSTIPI FROM 1 FOR 1);
    IF (WCSTIPIaux <> '5' AND WCSTIPIaux <> '9')  THEN
       BEGIN
         IF (WCSTIPIaux = '0') THEN
            WCSTIPIaux = '5';
         ELSE
            WCSTIPIaux = '9';
       END
    WCSTIPI = WCSTIPIaux || SUBSTRING(WCSTIPI FROM 2 FOR 1);
    BDCODEXPCSTIPI = CAST(WCSTIPI AS INTEGER);

    -- se produto for vazio, deve lançar o produto default informado na tela do sva
    IF (bdcodprod IS NULL) THEN
       BEGIN
         IF (bdmodelo IN (21,22)) THEN -- telecom
            BEGIN
              IF (PRODTELECOM IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODTELECOM;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODTELECOM  = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo IN (7,8,9,10,11,12,13,14,15,16,27,27,57)) THEN -- frete
            BEGIN
              IF (PRODFRETE IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODFRETE;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODFRETE = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo = 6) THEN -- energia
            BEGIN
              IF (PRODENERGIA IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODENERGIA;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODENERGIA  = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo IN (28,29)) THEN -- agua
            BEGIN
              IF (PRODAGUA IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODAGUA;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODAGUA  = 'TRUE';
                 END
            END

         IF (bdcodprod IS NULL) THEN -- generico
            BEGIN
              IF (PRODGENERICO IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP ='||:bdcodemp||' AND bdcodprod = ' || :PRODGENERICO;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODGENERICO  = 'TRUE';
                 END
            END

         bdapeunimed = 'UN';
         bdordempro = 1;
         bdqtditem = 1;
         bdvlritempro = bdvlrcontab;
         bdvlrunitario = bdvlritempro;
         bdvlrdesc = bddesconto;
         bdbcicmspro = bdbaseicms;
         bdbcipipro = bdbaseipi;
         bdbcstpro = bdbasest;
         bdvlricmspro = bdvlricms;
         bdvlripipro = bdvlripi;
         bdvlrstmovpro = bdvlrst;
       END


    SUSPEND;
  END
    END
END
^

/* Restore proc. body: VEF_SP_SVA_433 */
CREATE OR ALTER PROCEDURE VEF_SP_SVA_433 (
    PREMPRESA VARCHAR(10000),
    PRANOMESINICIAL INTEGER,
    PRANOMESFINAL INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCHAVE INTEGER,
    BDREFLAN INTEGER,
    BDTIPOMOV VARCHAR(3),
    BDMODELO INTEGER,
    BDMODELOSTR VARCHAR(2),
    BDSERIE VARCHAR(6),
    BDNUMDOC INTEGER,
    BDDATAEMISSAO DATE,
    BDDATAENTSAI DATE,
    BDCODTER INTEGER,
    BDCGCTER VARCHAR(18),
    BDESPECIE VARCHAR(5),
    BDEMITENTE INTEGER,
    BDCODSITNF INTEGER,
    BDCODSITNFAUX CHAR(1),
    BDCIFFOB INTEGER,
    BDCIFFOBAUX VARCHAR(3),
    BDVLRCONTAB NUMERIC(15,6),
    BDBASEICMS NUMERIC(15,6),
    BDBASEIPI NUMERIC(15,6),
    BDBASEST NUMERIC(15,6),
    BDISENTASICMS NUMERIC(15,6),
    BDISENTASIPI NUMERIC(15,6),
    BDOUTRASICMS NUMERIC(15,6),
    BDOUTRASIPI NUMERIC(15,6),
    BDVLRICMS NUMERIC(15,6),
    BDVLRIPI NUMERIC(15,6),
    BDVLRST NUMERIC(15,6),
    BDIMPEXCLUIDAS NUMERIC(15,6),
    BDOUTROSIMP NUMERIC(15,6),
    BDDESCONTO NUMERIC(15,6),
    BDICMSRETENT NUMERIC(15,6),
    BDCONDPGTO INTEGER,
    BDCONDPGTOAUX CHAR(1),
    BDVLRITEMPRO NUMERIC(15,6),
    BDVLRDESC NUMERIC(15,6),
    BDVLRDESPACESSORIAPRO NUMERIC(15,6),
    BDVLRIPIPRO NUMERIC(15,6),
    BDVLRICMSPRO NUMERIC(15,6),
    BDTIPOREG VARCHAR(10),
    BDVLRPIS NUMERIC(15,2),
    BDVLRCOFINS NUMERIC(15,2),
    BDVLRCSOCIAL NUMERIC(15,2),
    BDALIQPIS NUMERIC(5,2),
    BDALIQCOFINS NUMERIC(5,2),
    BDALIQIR NUMERIC(5,2),
    BDALIQCSOCIAL NUMERIC(5,2),
    BDVLRIR NUMERIC(15,2),
    BDRETINSS NUMERIC(15,2),
    BDVLRPISRET NUMERIC(15,2),
    BDVLRCOFINSRET NUMERIC(15,2),
    BDVLRCSLLRET NUMERIC(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);




  wsql =  'select mov.BDCODEMP, mov.BDCHAVE, mov.BDREFLAN, ''ENT'', BDMODELO, mov.BDMODELOSTR, BDSERIE, BDNUMDOCINI, BDDATAEMISSAO, ';
  wsql = wsql || '       BDDATAENTRADAENT BDDATAENTSAI, mov.BDCODTER, TER.BDCGCTER, BDESPECIE, BDEMITENTE, BDCODSITNF, BDCIFFOB, ';
  wsql = wsql || '       sum(BDVLRCONTAB) BDVLRCONTAB, sum(BDBASEICMS) BDBASEICMS, sum(BDBASEIPI) BDBASEIPI, sum(BDBASEST) BDBASEST, ';
  wsql = wsql || '       sum(BDISENTASICMS) BDISENTASICMS, sum(BDISENTASIPI) BDISENTASIPI, sum(BDOUTRASICMS) BDOUTRASICMS, ';
  wsql = wsql || '       sum(BDOUTRASIPI) BDOUTRASIPI, sum(BDVLRICMS) BDVLRICMS, sum(BDVLRIPI) BDVLRIPI, sum(BDVLRST) BDVLRST, ';
  wsql = wsql || '       sum(BDIMPEXCLUIDAS) BDIMPEXCLUIDAS, sum(BDOUTROSIMP) BDOUTROSIMP, sum(BDDESCONTO) BDDESCONTO, ';
  wsql = wsql || '       sum(BDICMSRETENT) BDICMSRETENTSAI, BDCONDPGTO, coalesce(RET.BDVLRPIS, 0.0) BDVLRPIS, ';
  wsql = wsql || '       coalesce(RET.BDVLRCOFINS, 0.0) BDVLRCOFINS, coalesce(RET.BDVLRCSOCIAL, 0.0) BDVLRCSOCIAL, ';
  wsql = wsql || '       coalesce(0, 0.0) BDVLRIR, coalesce(0, 0.0) BDRETINSS, ';

  wsql = wsql || '       sum(mov.BDVLRITEMPRO) BDVLRITEMPRO, sum(mov.BDVLRDESCPRO) BDVLRDESCPRO, ';
  wsql = wsql || '       sum(mov.BDVLRDESPACESSORIAPRO) BDVLRDESPACESSORIAPRO, sum(mov.BDVLRIPIPRO) BDVLRIPIPRO, ';
  wsql = wsql || '       sum(mov.BDVLRICMSPRO) BDVLRICMSPRO ';
  wsql = wsql || 'from ( ';
  wsql = wsql || '        select mov.bdcodemp,mov.bdchave,mov.BDCODTER,mov.BDREFLAN,modlan.BDMODELOSTR,mov.bDMODELO, ';
  wsql = wsql || '               mov.BDSERIE, mov.BDNUMDOCINI, mov.BDDATAEMISSAO,mov.BDCONDPGTO, ';
  wsql = wsql || '               mov.BDDATAENTRADAENT, mov.BDESPECIE, mov.BDEMITENTE, mov.BDCODSITNF, mov.BDCIFFOB, ';

  wsql = wsql || '               sum(PRO.BDVLRITEM) BDVLRITEMPRO, sum(PRO.BDVLRDESC) BDVLRDESCPRO, ';
  wsql = wsql || '               sum(PRO.BDVLRDESPACESSORIA) BDVLRDESPACESSORIAPRO, sum(PRO.BDVLRIPI) BDVLRIPIPRO, ';
  wsql = wsql || '               sum(PRO.BDVLRICMS) BDVLRICMSPRO ';
  wsql = wsql || '        from ( ';
  wsql = wsql || '                select * FROM vef_emp_tmovent t ';
              -- SOMENTE TERCEIROS ENTRADAS...
  wsql = wsql || '                where bdemitente = 1 ';
            
              IF (:prempresa IS NOT NULL) THEN
                   wsql = wsql || ' and '||:prempresa;
            
              IF (:pranomesinicial IS NOT NULL) THEN
                 BEGIN
                   wsql = wsql ||'AND T.BDREFLAN >= '||:pranomesinicial;
                   wsql = wsql ||'AND T.BDREFLAN <= '||:pranomesfinal;
                 END
  wsql = wsql || '              ) mov ';
  wsql = wsql || '        LEFT OUTER JOIN vef_emp_tmoventitens i ON (mov.bdcodemp = i.bdcodemp AND mov.bdchave = i.bdchave) ';
  wsql = wsql || '        LEFT OUTER JOIN vef_base_ttabmodelolan modlan ON (modlan.bdmodelo = mov.bdmodelo) ';
  wsql = wsql || '        left outer join VEF_EMP_TMOVPROENT PRO on (PRO.BDCODEMP = mov.BDCODEMP and PRO.BDCHAVE = mov.BDCHAVE and PRO.BDORDEM = i.BDORDEM) ';
  wsql = wsql || '        group by mov.bdcodemp,mov.bdchave,mov.BDCODTER,mov.BDREFLAN,modlan.BDMODELOSTR,mov.bDMODELO, ';
  wsql = wsql || '                 mov.BDSERIE, mov.BDNUMDOCINI, mov.BDDATAEMISSAO,mov.BDCONDPGTO, mov.BDDATAENTRADAENT, mov.BDESPECIE, mov.BDEMITENTE, mov.BDCODSITNF, mov.BDCIFFOB ';

  wsql = wsql || ') mov ';
  wsql = wsql || 'LEFT OUTER JOIN vef_emp_tmoventitens i ON (mov.bdcodemp = i.bdcodemp AND mov.bdchave = i.bdchave) ';
  wsql = wsql || 'left outer join VW_TTERCEIRO TER on (TER.BDCODTER = mov.BDCODTER) ';
  wsql = wsql || 'left outer join VEF_EMP_TMOVENTRET RET on (RET.BDCODEMP = mov.BDCODEMP and RET.BDCHAVE = mov.BDCHAVE) ';
  wsql = wsql || 'group by BDCODEMP, BDCHAVE, BDREFLAN, ''ENT'', BDMODELO, mov.BDMODELOSTR, BDSERIE, BDNUMDOCINI, BDDATAEMISSAO, BDDATAENTRADAENT, mov.BDCODTER, TER.BDCGCTER, BDESPECIE, BDEMITENTE, BDCODSITNF, BDCIFFOB, BDCONDPGTO, BDVLRPIS, BDVLRCOFINS, BDVLRCSOCIAL ';
  wsql = wsql || 'order by BDCODEMP, BDREFLAN ';



  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    bdtipomov,
    BDMODELO,
    BDMODELOSTR,
    BDSERIE,
    bdnumdoc,
    BDDATAEMISSAO,
    BDDATAENTSAI,
    BDCODTER,
    bdcgcter,
    BDESPECIE,
    BDEMITENTE,
    BDCODSITNF,
    BDCIFFOB,
    --bdordem,
    BDVLRCONTAB,
    BDBASEICMS,
    BDBASEIPI,
    BDBASEST,
    BDISENTASICMS,
    BDISENTASIPI,
    BDOUTRASICMS,
    BDOUTRASIPI,
    BDVLRICMS,
    BDVLRIPI,
    BDVLRST ,
    BDIMPEXCLUIDAS,
    BDOUTROSIMP,
    BDDESCONTO,
    BDICMSRETENT,
    bdcondpgto,
    bdvlrpis,
    bdvlrcofins,
    bdvlrcsocial,
    bdvlrir,
    bdretinss,

    BDVLRITEMPRO,
    BDVLRDESC,
    bdvlrdespacessoriapro,
    bdvlripipro,
    bdvlricmspro
  DO
  BEGIN

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       BEGIN
          BDVLRCONTAB = 0;
          BDBASEICMS = 0;
          BDBASEIPI = 0;
          BDBASEST = 0;
          BDISENTASICMS = 0;
          BDISENTASIPI = 0;
          BDOUTRASICMS = 0;
          BDOUTRASIPI = 0;
          BDVLRICMS = 0;
          BDVLRIPI = 0;
          BDVLRST  = 0;
          BDIMPEXCLUIDAS = 0;
          BDOUTROSIMP = 0;
          BDDESCONTO = 0;
          BDICMSRETENT = 0;
          bdvlrpis = 0;
          bdvlrcofins = 0;
          bdvlrcsocial = 0;
          bdvlrir = 0;
          bdretinss = 0;
          BDVLRITEMPRO = 0;
          BDVLRDESC = 0;
          bdvlrdespacessoriapro = 0;
          bdvlripipro = 0;
          bdvlricmspro = 0;
       END

    bdtiporeg = '4_3_3';

    IF (bdciffob = 0) THEN
       bdciffobaux = 'CIF';
    ELSE
    IF (bdciffob = 1) THEN
       bdciffobaux = 'FOB';
    ELSE
    IF (bdciffob IS NULL) THEN
       bdciffobaux = '';

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       bdcodsitnfaux = 'S';
    ELSE
         bdcodsitnfaux = 'N';

    IF (BDCONDPGTO = 0)  THEN
       bdcondpgtoaux = '1';
    ELSE
       bdcondpgtoaux = '2';

    IF (bdvlrcontab <> 0) THEN
      BEGIN
        bdaliqpis = (bdvlrpis * 100) / bdvlrcontab;
        bdaliqcofins = (bdvlrcofins * 100) / bdvlrcontab;
        bdaliqir = (bdvlrir * 100) / bdvlrcontab;
        bdaliqcsocial = (bdvlrcsocial * 100) / bdvlrcontab;
      END
    ELSE
      BEGIN
        bdaliqpis = 0;
        bdaliqcofins = 0;
        bdaliqir = 0;
        bdaliqcsocial = 0;
      END

    IF (bdvlrpis = 0) THEN
       bdvlrpisret = 0;
    ELSE
       bdvlrpisret = bdvlrcontab;

    IF (bdvlrcofins = 0) THEN
       bdvlrcofinsret = 0;
    ELSE
       bdvlrcofinsret = bdvlrcontab;

    IF (bdvlrcsocial = 0) THEN
       bdvlrcsllret = 0;
    ELSE
       bdvlrcsllret = bdvlrcontab;

    SUSPEND;
  END
END^

/* Restore proc. body: VEF_SP_SVA_434 */
ALTER PROCEDURE VEF_SP_SVA_434(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRODFRETE INTEGER,
PRODENERGIA INTEGER,
PRODAGUA INTEGER,
PRODTELECOM INTEGER,
PRODGENERICO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDMODELO INTEGER,
BDMODELOSTR VARCHAR(2),
BDSERIE VARCHAR(6),
BDNUMDOC INTEGER,
BDDATAEMISSAO DATE,
BDDATAENTSAI DATE,
BDCODTER INTEGER,
BDESPECIE VARCHAR(5),
BDEMITENTE INTEGER,
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDCIFFOB INTEGER,
BDCIFFOBAUX VARCHAR(3),
BDORDEM INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDBASEICMS NUMERIC(15,2),
BDBASEIPI NUMERIC(15,2),
BDBASEST NUMERIC(15,2),
BDISENTASICMS NUMERIC(15,2),
BDISENTASIPI NUMERIC(15,2),
BDOUTRASICMS NUMERIC(15,2),
BDOUTRASIPI NUMERIC(15,2),
BDVLRICMS NUMERIC(15,2),
BDVLRIPI NUMERIC(15,2),
BDVLRST NUMERIC(15,2),
BDIMPEXCLUIDAS NUMERIC(15,2),
BDOUTROSIMP NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDICMSRETENT NUMERIC(15,2),
BDCONDPGTO INTEGER,
BDCONDPGTOAUX CHAR,
BDVLRITEMPRO NUMERIC(15,2),
BDVLRDESC NUMERIC(15,2),
BDVLRIPIPRO NUMERIC(15,2),
BDVLRICMSPRO NUMERIC(15,2),
BDVLRFRETEC100 NUMERIC(15,2),
BDVLRSEGUROC100 NUMERIC(15,2),
BDVLROUTDESPC100 NUMERIC(15,2),
BDORDEMPRO INTEGER,
BDCODPROD INTEGER,
BDDESCPROD VARCHAR(200),
BDCODNAT INTEGER,
BDNCMPROD INTEGER,
BDQTDITEM NUMERIC(15,3),
BDAPEUNIMED VARCHAR(5),
BDALIQIPIPRO NUMERIC(15,2),
BDBCIPIPRO NUMERIC(15,2),
BDCODCSTICMS VARCHAR(3),
BDALIQICMSPRO NUMERIC(15,2),
BDBCICMSPRO NUMERIC(15,2),
BDBCSTPRO NUMERIC(15,2),
BDVLRSTMOVPRO NUMERIC(15,2),
BDMOVFISICO VARCHAR(5),
BDCODEXPCSTIPI INTEGER,
BDCODCSTPIS INTEGER,
BDALIQPIS NUMERIC(15,4),
BDBCPIS NUMERIC(15,3),
BDVLRPIS NUMERIC(15,2),
BDCODCSTCOF INTEGER,
BDALIQCOFINS NUMERIC(15,4),
BDBCCOFINS NUMERIC(15,3),
BDVLRCOFINS NUMERIC(15,2),
BDCGCTER VARCHAR(18),
BDCAMPO10 NUMERIC(15,2),
BDCAMPO11 NUMERIC(15,2),
BDCAMPO12 NUMERIC(15,2),
BDCAMPO17 NUMERIC(15,2),
BDCAMPO18 NUMERIC(15,2),
BDCAMPO19 NUMERIC(15,2),
BDVLRUNITARIO NUMERIC(15,4),
BDLANBCICMSISEOUT INTEGER,
BDTIPOREG VARCHAR(10),
BDPRODFRETE VARCHAR(5),
BDPRODENERGIA VARCHAR(5),
BDPRODAGUA VARCHAR(5),
BDPRODTELECOM VARCHAR(5),
BDPRODGENERICO VARCHAR(5))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQLAUX VARCHAR(32700);
DECLARE VARIABLE WLANBCICMSISEOUT INTEGER;
DECLARE VARIABLE WCSTIPI VARCHAR(2);
DECLARE VARIABLE WCSTIPIAUX VARCHAR(1);
DECLARE VARIABLE WCSTPIS VARCHAR(2);
DECLARE VARIABLE WCSTPISAUX VARCHAR(1);
DECLARE VARIABLE WCSTCOF VARCHAR(2);
DECLARE VARIABLE WCSTCOFAUX VARCHAR(1);
DECLARE VARIABLE WVLRITEMPRO NUMERIC(15,2);
DECLARE VARIABLE WSERIE VARCHAR(6);
DECLARE VARIABLE WNUMDOC INTEGER;
DECLARE VARIABLE WDATAEMISSAO DATE;
DECLARE VARIABLE WORDEMPRO INTEGER;
BEGIN
  /* Procedure Text */

 EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

 BDPRODFRETE = 'FALSE';
 BDPRODENERGIA  = 'FALSE';
 BDPRODAGUA  = 'FALSE';
 BDPRODTELECOM  = 'FALSE';
 BDPRODGENERICO  = 'FALSE';

 wsql = 'SELECT t.bdcodemp,  t.bdchave,  t.bdreflan, t.bdtipomov, t.bdmodelo, t.bdMODELOSTR, t.BDSERIE, t.BDNUMDOCINI, t.BDDATAEMISSAO, t.BDDATAENTSAI, t.BDCODTER,
         t.BDESPECIE, t.BDEMITENTE, t.BDCODSITNF, t.BDCIFFOB, t.bdordem, t.BDVLRCONTAB, t.BDBASEICMS,
         t.BDBASEIPI, t.BDBASEST, t.BDISENTASICMS, t.BDISENTASIPI, t.BDOUTRASICMS, t.BDOUTRASIPI, t.BDVLRICMS, t.BDVLRIPI,  t.BDVLRST, t.BDIMPEXCLUIDAS,
         t.BDOUTROSIMP, t.BDDESCONTO, t.BDICMSRETENTSAI, t.bdcondpgto,

         pro.BDVLRITEM BDVLRITEMPRO, pro.BDVLRDESC BDVLRDESCPRO, pro.bdvlripi bdvlripipro, pro.bdvlricms bdvlricmspro,
         c100.bdvlrfrete, c100.bdvlrseguro, c100.bdvlroutdesp,

         pro.bdordempro , pro.BDCODPROD, CADPRO.BDDESCPROD, bdcodnat, BDNCMPROD, BDQTDITEM, BDAPEUNIMED, pro.BDALIQIPI, BDBCIPI,
         CSTICMS.BDCSTICMS, pro.BDALIQICMS, BDBCICMS, bdbcst, pro.BDVLRST BDVLRSTMOVPRO, bdmovfisico, CSTIPI.BDCODEXPCSTIPI ,
         BDCODCSTPIS , pro.BDALIQPIS, BDBCPIS, BDVLRPIS, BDCODCSTCOF , BDALIQCOFINS , BDBCCOFINS, BDVLRCOFINS, ter.bdcgcter ';

  wsql = wsql || ' from VW_VEF_EMP_TMOVENT_EXP_SVA T';
  wsql = wsql || ' left outer join vef_emp_tmovproENT pro on (pro.bdcodemp = t.bdcodemp and pro.bdchave = t.bdchave and pro.bdordem = t.bdordem) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTIPI CSTIPI ON ( PRO.bdcodcstipi = CSTIPI.bdcodcstipi) ';
  wsql = wsql || ' left outer join vef_emp_tc100ENT C100 on (C100.BDCODEMP = t.BDCODEMP and C100.bdchave = t.bdchave)';
  wsql = wsql || ' left outer join TCADPRO_VINC CADPRO on (cadpro.bdcodemp = pro.bdcodemp and cadpro.bdcodprod = pro.bdcodprod)';
  wsql = wsql || ' left outer join tunidademedida UM on (UM.bdcodunimed = CADPRO.bdcodunimed) ';
  wsql = wsql || ' left outer join TTERCEIRO ter on (ter.bdcodter = t.bdcodter) ';
  wsql = wsql || ' left outer join VEF_BASE_TTABCSTICMS CSTICMS ON ( PRO.bdcodcstICMS = CSTICMS.bdcodcstICMS) ';

  /*wwhere = ' where bdemitente = 1 and bdordempro is not null';*/
  wwhere = ' where bdemitente = 1 ';

  IF (:prempresa IS NOT NULL) THEN
     wwhere = wwhere || ' and '||:prempresa;

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = wwhere||' where ';

       wwhere = wwhere||'T.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN <= '||:pranomesfinal;

     END

  wsql = wsql||wwhere || ' order by bdcodemp, bdreflan, bdtipomov  ' ;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    bdtipomov,
    BDMODELO,
    bdmodelostr, 
    BDSERIE,
    bdnumdoc,
    BDDATAEMISSAO,
    BDDATAENTSAI,
    BDCODTER,
    BDESPECIE,
    BDEMITENTE,
    BDCODSITNF,
    BDCIFFOB,
    bdordem,
    BDVLRCONTAB,
    BDBASEICMS,
    BDBASEIPI,
    BDBASEST,
    BDISENTASICMS,
    BDISENTASIPI,
    BDOUTRASICMS,
    BDOUTRASIPI,
    BDVLRICMS,
    BDVLRIPI,
    BDVLRST,
    BDIMPEXCLUIDAS,
    BDOUTROSIMP,
    BDDESCONTO,
    BDICMSRETENT,
    bdcondpgto,
    BDVLRITEMPRO,
    BDVLRDESC,
    bdvlripipro,
    bdvlricmspro,
    bdvlrfretec100,
    bdvlrseguroc100,
    bdvlroutdespc100,
    bdordempro,
    bdcodprod,
    BDDESCPROD,
    bdcodnat,
    BDNCMPROD,
    BDQTDITEM,
    BDAPEUNIMED,
    bdaliqipipro,
    bdbcipipro,
    BDCODCSTICMS,
    bdaliqicmspro,
    bdbcicmspro,
    bdbcstpro,
    bdvlrstmovpro,
    bdmovfisico,
    BDCODEXPCSTIPI,
    BDCODCSTPIS,
    BDALIQPIS,
    BDBCPIS,
    BDVLRPIS,
    BDCODCSTCOF ,
    BDALIQCOFINS ,
    BDBCCOFINS,
    BDVLRCOFINS,
    BDCGCTER

  DO

  BEGIN

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       BEGIN
          BDVLRCONTAB = 0;
          BDBASEICMS = 0;
          BDBASEIPI = 0;
          BDBASEST = 0;
          BDISENTASICMS = 0;
          BDISENTASIPI = 0;
          BDOUTRASICMS = 0;
          BDOUTRASIPI = 0;
          BDVLRICMS = 0;
          BDVLRIPI = 0;
          BDVLRST = 0;
          BDIMPEXCLUIDAS = 0;
          BDOUTROSIMP = 0;
          BDDESCONTO = 0;
          BDICMSRETENT = 0;
          BDVLRITEMPRO = 0;
          BDVLRDESC = 0;
          bdvlripipro = 0;
          bdvlricmspro = 0;
          bdvlrfretec100 = 0;
          bdvlrseguroc100 = 0;
          bdvlroutdespc100 = 0;
          BDQTDITEM = 0;
          bdaliqipipro = 0;
          bdbcipipro = 0;
          bdaliqicmspro = 0;
          bdbcicmspro = 0;
          bdbcstpro = 0;
          bdvlrstmovpro = 0;
          BDALIQPIS = 0;
          BDBCPIS = 0;
          BDVLRPIS = 0;
          BDALIQCOFINS  = 0;
          BDBCCOFINS = 0;
          BDVLRCOFINS = 0;
       END

    IF (((wSERIE <> bdserie) AND (wNUMDOC <> bdnumdoc) AND (wdataemissao <> bddataemissao)) OR ((wSERIE IS NULL) AND (wNUMDOC IS NULL) AND (wdataemissao IS NULL)))  THEN
       BEGIN
         wSERIE = bdserie;
         wNUMDOC = bdnumdoc;
         wdataemissao = bddataemissao;

         wordempro = 1;
       END
    ELSE
       wordempro = wordempro + 1;

    bdordempro = wordempro;

    wvlritempro = 0;

    IF (UPPER(bdmovfisico) = 'TRUE') THEN
       bdmovfisico = 'S';
    ELSE
       bdmovfisico = 'N';

    bdvlrunitario = bdvlritempro / bdqtditem;

    bdtiporeg = '4_3_4';

    IF (bdciffob = 0) THEN
       bdciffobaux = 'CIF';
    ELSE
    IF (bdciffob = 1) THEN
       bdciffobaux = 'FOB';
    ELSE
    IF (bdciffob IS NULL) THEN
       bdciffobaux = '';

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       bdcodsitnfaux = 'S';
    ELSE
         bdcodsitnfaux = 'N';

    IF (BDCONDPGTO = 0)  THEN
       bdcondpgtoaux = '1';
    ELSE
       bdcondpgtoaux = '2';

    IF (wlanbcicmsiseout IS NULL) THEN
      BEGIN
        wsqlaux = 'select bdlanbcicmsiseout from VW_VEF_BASE_TEMPPARGER where bdcodemp = ' || :bdcodemp;
        EXECUTE STATEMENT wsqlaux INTO wlanbcicmsiseout;
      END

    IF (bdaliqipipro > 0) THEN
       wlanbcicmsiseout = 1;
    ELSE
      BEGIN
        IF (wlanbcicmsiseout = 0) THEN
           wlanbcicmsiseout = 2;
        ELSE
           wlanbcicmsiseout = 3;
      END

    bdlanbcicmsiseout = wlanbcicmsiseout;


    /*if (bdcodcstpis = 7) then
       bdcampo10 = BDVLRPIS;
    else
       bdcampo10 =  0;

    if ((bdcodcstpis = 50) or (bdcodcstpis = 53) or (bdcodcstpis = 54)) then
       bdcampo11 = BDVLRPIS;
    else
       bdcampo11 =  0;

    if ((bdcodcstpis = 51) or (bdcodcstpis = 55) or (bdcodcstpis = 56)) then
       bdcampo12 = BDVLRPIS;
    else
       bdcampo12 =  0;

    if (BDCODCSTCOF = 52) then
       bdcampo17 = BDVLRCOFINS;
    else
       bdcampo17 =  0;

    if ((BDCODCSTCOF = 50) or (bdcodcstpis = 53) or (bdcodcstpis = 54)) then
       bdcampo18 = BDVLRPIS;
    else
       bdcampo18 =  0;

    if ((BDCODCSTCOF = 51) or (bdcodcstpis = 55) or (bdcodcstpis = 56)) then
       bdcampo19 = BDVLRPIS;
    else
       bdcampo19 =  0;*/


    --rotina usada no suprema...
    WCSTIPI = CAST(BDCODEXPCSTIPI AS VARCHAR(2));
    IF (WCSTIPI IS NULL) THEN
       WCSTIPI = '00';
    WCSTIPIaux = SUBSTRING(WCSTIPI FROM 1 FOR 1);
    IF (WCSTIPIaux <> '0' AND WCSTIPIaux <> '4')  THEN
       BEGIN
         IF (WCSTIPIaux = '5') THEN
            WCSTIPIaux = '0';
         ELSE
            WCSTIPIaux = '4';
       END
    WCSTIPI = WCSTIPIaux || SUBSTRING(WCSTIPI FROM 2 FOR 1);
    BDCODEXPCSTIPI = CAST(WCSTIPI AS INTEGER);

    -- se produto for vazio, deve lançar o produto default informado na tela do sva
    IF (bdcodprod IS NULL) THEN
       BEGIN
         IF (bdmodelo IN (21,22)) THEN -- telecom
            BEGIN
              IF (PRODTELECOM IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP = '||:bdcodemp||' AND bdcodprod = ' || :PRODTELECOM;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODTELECOM  = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo IN (7,8,9,10,11,12,13,14,15,16,27,27,57)) THEN -- frete
            BEGIN
              IF (PRODFRETE IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP = '||:bdcodemp||' AND bdcodprod = ' || :PRODFRETE;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODFRETE = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo = 6) THEN -- energia
            BEGIN
              IF (PRODENERGIA IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP = '||:bdcodemp||' AND bdcodprod = ' || :PRODENERGIA;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODENERGIA  = 'TRUE';
                 END
            END
         ELSE
         IF (bdmodelo IN (28,29)) THEN -- agua
            BEGIN
              IF (PRODAGUA IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP = '||:bdcodemp||' AND bdcodprod = ' || :PRODAGUA;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODAGUA  = 'TRUE';
                 END
            END

         IF (bdcodprod IS NULL) THEN -- generico
            BEGIN
              IF (PRODGENERICO IS NOT NULL) THEN
                 BEGIN
                   wsqlaux = 'select bdcodprod, bddescprod, bdncmprod, bdcodcstpisent, bdcodcstcofent from TCADPRO_VINC where BDCODEMP = '||:bdcodemp||' AND bdcodprod = ' || :PRODGENERICO;
                   EXECUTE STATEMENT wsqlaux INTO BDCODPROD, BDDESCPROD, BDNCMPROD, BDCODCSTPIS, BDCODCSTCOF;
                   BDPRODGENERICO  = 'TRUE';
                 END
            END

         bdapeunimed = 'UN';
         bdordempro = 1;
         bdqtditem = 1;
         wvlritempro = bdvlrcontab;
         bdvlrunitario = bdvlritempro;
         bdvlrdesc = bddesconto;
         bdbcicmspro = bdbaseicms;
         bdbcipipro = bdbaseipi;
         bdbcstpro = bdbasest;
         bdvlricmspro = bdvlricms;
         bdvlripipro = bdvlripi;
         bdvlrstmovpro = bdvlrst;
       END


    WCSTPIS = CAST(bdcodcstpis AS VARCHAR(2));
    IF ((WCSTpis IS NULL) OR (TRIM(WCSTpis) = '')) THEN
       WCSTpis = '00';
    WCSTpisaux = SUBSTRING(WCSTpis FROM 1 FOR 1);
    IF (WCSTpisaux <> '9') THEN
        WCSTpisaux = '5';
    WCSTpis = WCSTpisaux || SUBSTRING(WCSTpis FROM 2 FOR 1);
    BDCODCSTPIS = CAST(WCSTpis AS INTEGER);

    IF ((BDCODCSTPIS = '50') AND ((bdbcpis = 0) OR (bdbcpis IS NULL))) THEN
       BDCODCSTPIS = '98';

    IF (BDCODCSTPIS = '57') THEN
       BDCODCSTPIS = '71';


    WCSTcof = CAST(bdcodcstcof AS VARCHAR(2));
    IF ((WCSTcof IS NULL) OR (TRIM(WCSTcof) = '')) THEN
       WCSTcof = '00';
    WCSTcofaux = SUBSTRING(WCSTcof FROM 1 FOR 1);
    IF (WCSTcofaux <> '9') THEN
        WCSTcofaux = '5';
    WCSTcof = WCSTcofaux || SUBSTRING(WCSTcof FROM 2 FOR 1);
    BDCODCSTcof = CAST(WCSTcof AS INTEGER);

    IF ((BDCODCSTcof = '50') AND ((bdbccofins = 0) OR (bdbccofins IS NULL))) THEN
       BDCODCSTcof = '98';

    IF (BDCODCSTcof = '57') THEN
       BDCODCSTcof = '71';


    IF ((bdbcpis IS NULL) OR (bdbcpis = 0)) THEN
       bdbcpis = BDVLRITEMPRO;

    IF ((bdaliqpis IS NULL) OR (bdaliqpis = 0)) THEN
       bdaliqpis = 0.65;

    IF ((bdvlrpis IS NULL) OR (bdvlrpis = 0)) THEN
       bdvlrpis = (bdbcpis * bdaliqpis / 100);

    IF ((bdbccofins IS NULL) OR (bdbccofins = 0)) THEN
       bdbccofins = BDVLRITEMPRO;

    IF ((bdaliqcofins IS NULL) OR (bdaliqcofins = 0)) THEN
       bdaliqcofins = 3;

    IF ((bdvlrcofins IS NULL) OR (bdvlrcofins = 0)) THEN
       bdvlrcofins = (bdbccofins * bdaliqcofins / 100);


    IF (bdcodcstpis = 52) THEN
       bdcampo10 = BDVLRPIS;
    ELSE
       bdcampo10 =  0;

    IF ((bdcodcstpis = 50) OR (bdcodcstpis = 53) OR (bdcodcstpis = 54)) THEN
       bdcampo11 = BDVLRPIS;
    ELSE
       bdcampo11 =  0;

    IF ((bdcodcstpis = 51) OR (bdcodcstpis = 55) OR (bdcodcstpis = 56)) THEN
       bdcampo12 = BDVLRPIS;
    ELSE
       bdcampo12 =  0;

    IF (BDCODCSTCOF = 52) THEN
       bdcampo17 = BDVLRCOFINS;
    ELSE
       bdcampo17 =  0;

    IF ((BDCODCSTCOF = 50) OR (BDCODCSTCOF = 53) OR (BDCODCSTCOF = 54)) THEN
       bdcampo18 = BDVLRCOFINS;
    ELSE
       bdcampo18 =  0;

    IF ((BDCODCSTCOF = 51) OR (BDCODCSTCOF = 55) OR (BDCODCSTCOF = 56)) THEN
       bdcampo19 = BDVLRCOFINS;
    ELSE
       bdcampo19 =  0;

    IF ((wvlritempro IS NOT NULL) AND (wvlritempro > 0)) THEN
    BDVLRITEMPRO = wvlritempro;

    SUSPEND;
  END

END
^

/* Restore proc. body: VEF_SP_SVA_491 */
ALTER PROCEDURE VEF_SP_SVA_491(PREMPRESA VARCHAR(10000),
PRCODTER INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDDATACADTER DATE,
BDCODTER INTEGER,
BDCGCTER VARCHAR(18),
BDIETER VARCHAR(20),
BDIMTER VARCHAR(16),
BDNOMETER VARCHAR(100),
BDLOGRTER DM_LOGRADOURO,
BDENDTER DM_BDENDERECO,
BDENDEXPTER DM_BDENDERECO,
BDNUMTER DM_NUMEND,
BDCOMPTER DM_BDCOMPENDERECO,
BDBAITER VARCHAR(60),
BDNOMCID VARCHAR(40),
BDSIGLAUF VARCHAR(2),
BDCEPTER VARCHAR(9),
BDDESCPAIS VARCHAR(60),
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDCODCGCTER VARCHAR(18))
 AS
DECLARE VARIABLE WAUX VARCHAR(1000);
DECLARE VARIABLE WRETORNO VARCHAR(1000);
DECLARE VARIABLE WPARSQLCALC VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

  wsql = '';

  wSql = wSql || ' select ';
  wSql = wSql || 'BDCODEMP, ';
  wSql = wSql || 'BDDATACADTER, ';
  wSql = wSql || 'BDCODTER, ';
  wSql = wSql || 'BDCGCTER, ';
  wSql = wSql || 'BDIETER, ';
  wSql = wSql || 'BDIMTER, ';
  wSql = wSql || 'BDNOMETER, ';
  wSql = wSql || 'BDLOGRTER, ';
  wSql = wSql || 'BDENDTER, ';
  wSql = wSql || 'BDNUMTER, ';
  wSql = wSql || 'BDCOMPTER, ';
  wSql = wSql || 'BDBAITER, ';
  wSql = wSql || 'bdnomcid, ';
  wSql = wSql || 'BDSIGLAUF, ';
  wSql = wSql || 'BDCEPTER, ';
  wSql = wSql || 'bddescpais ';


  wsql = wsql || ' from VEF_SP_EXP_TERCEIRO(';

  wparsqlcalc = '';

   IF (prempresa IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

   IF (prcodter IS NULL) THEN
      wparsqlcalc = wparsqlcalc||',null';
   ELSE
      wparsqlcalc = wparsqlcalc||','||''''||prcodter||'''';

   wparsqlcalc = wparsqlcalc||','||pranomesinicial;
   wparsqlcalc = wparsqlcalc||','||pranomesfinal;

   wparsqlcalc = wparsqlcalc||',null';

   wsql = wsql||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bddatacadter,
       :bdcodter,
       :bdcgcter,
       :bdieter,
       :bdimter,
       :bdnometer,
       :bdlogrter,
       :bdendter,
       :bdnumter,
       :bdcompter,
       :bdbaiter,
       :bdnomcid,
       :bdsiglauf,
       :bdcepter,
       :bddescpais
     DO
     BEGIN
       bdordemreg = 4;
       bdtiporeg = '4_9_1';
       bdreflan = NULL;
       bdendexpter = bdlogrter || ' ' || bdendter || ' ' || bdnumter || ' ' || bdcompter ;

       IF (UPPER(bddescpais) = 'BRASIL') THEN
          bddescpais = '';

       IF (UPPER(bdsiglauf) = 'EX') THEN
          bdcodcgcter = bdcodter;
       ELSE
          bdcodcgcter = bdcgcter;

       IF (UPPER(bdsiglauf) = 'EX') THEN
          bdsiglauf = '';

       BDDATACADTER = CAST((SUBSTRING((CAST(PRANOMESINICIAL AS VARCHAR(6))) FROM 5 FOR 2)||'/'||'01/'||SUBSTRING((CAST(PRANOMESINICIAL AS VARCHAR(6))) FROM 1 FOR 4)) AS DATE);

       SUSPEND;
     END
END
^

/* Restore proc. body: VEF_SP_SVA_494 */
ALTER PROCEDURE VEF_SP_SVA_494(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDCODNAT INTEGER,
BDNOMENAT VARCHAR(255),
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER)
 AS
DECLARE VARIABLE WPARSQLCALC VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

  wsql = '';

  wSql = wSql || ' select distinct ';
  wSql = wSql || 'BDCODEMP, ';
  wSql = wSql || 'CAST(substring(BDCODNAT FROM 1 FOR 6) as Integer), ';
  wSql = wSql || 'substring(BDNOMENAT FROM 1 FOR 45) ';

  wsql = wsql || ' from VEF_SP_EXP_TNATOP(';

  wparsqlcalc = '';

   IF (prempresa IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

   wparsqlcalc = wparsqlcalc||','||pranomesinicial;
   wparsqlcalc = wparsqlcalc||','||pranomesfinal;

   wsql = wsql||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bdcodnat,
       :bdnomenat
     DO
     BEGIN
       bdordemreg = 5;
       bdtiporeg = '4_9_4';
       bdreflan = NULL;

       SUSPEND;

      END

END
^

/* Restore proc. body: VEF_SP_SVA_495 */
ALTER PROCEDURE VEF_SP_SVA_495(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRPROD VARCHAR(10000))
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDCODPROD INTEGER,
BDNOMEPROD VARCHAR(255),
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER)
 AS
DECLARE VARIABLE WPARSQLCALC VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WEMP INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

  wsql = '';

  wSql = wSql || ' select ';
  wSql = wSql || 'BDCODEMP, ';
  wSql = wSql || 'BDCODPROD, ';
  wSql = wSql || 'BDNOMEPROD ';

  wsql = wsql || ' from VEF_SP_EXP_TPRODUTOS(';

  wparsqlcalc = '';

  IF (prempresa IS NULL) THEN
     wparsqlcalc = wparsqlcalc||'null';
  ELSE
     wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

  wparsqlcalc = wparsqlcalc||','||pranomesinicial;
  wparsqlcalc = wparsqlcalc||','||pranomesfinal;

  wsql = wsql||wparsqlcalc||')';

  FOR EXECUTE STATEMENT wsql
    INTO
      :bdcodemp,
      :bdcodprod,
      :bdnomeprod
    DO
    BEGIN
      bdordemreg = 6;
      bdtiporeg = '4_9_5';
      bdreflan = NULL;
  
      wemp = bdcodemp;

      SUSPEND;

    END

  IF (prprod <> '') THEN
     BEGIN
       wsql = 'select bdcodprod, bddescprod from TCADPRO_vinc where bdcodemp = '||:PREMPRESA||' bdcodprod in (' || :PRPROD || ')';

       FOR EXECUTE STATEMENT wsql
         INTO
           :bdcodprod,
           :bdnomeprod
         DO
         BEGIN
           bdcodemp = wemp; --0
           bdordemreg = 6;
           bdtiporeg = '4_9_5';
           bdreflan = NULL;

           SUSPEND;

         END
     END
END
^

/* Restore proc. body: VEF_SP_SVA_EXP_491 */
ALTER PROCEDURE VEF_SP_SVA_EXP_491(PREMPRESA VARCHAR(10000),
PRCODTER INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
DECLARE VARIABLE WAUX VARCHAR(1000);
DECLARE VARIABLE WRETORNO VARCHAR(1000);
DECLARE VARIABLE WPARSQLCALC VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WDATACADTER DATE;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WCGCTER VARCHAR(18);
DECLARE VARIABLE WIETER VARCHAR(20);
DECLARE VARIABLE WIMTER VARCHAR(16);
DECLARE VARIABLE WNOMETER VARCHAR(100);
DECLARE VARIABLE WLOGRTER VARCHAR(15);
DECLARE VARIABLE WENDTER VARCHAR(60);
DECLARE VARIABLE WNUMTER DM_NUMEND;
DECLARE VARIABLE WCOMPTER VARCHAR(60);
DECLARE VARIABLE WBAITER VARCHAR(60);
DECLARE VARIABLE WNOMCID VARCHAR(40);
DECLARE VARIABLE WSIGLAUF VARCHAR(2);
DECLARE VARIABLE WCEPTER VARCHAR(9);
DECLARE VARIABLE WDESCPAIS VARCHAR(60);
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

  wsql = '';

  wSql = wSql || ' select ';
  wSql = wSql || 'BDCODEMP, ';
  wSql = wSql || 'BDDATACADTER, ';
  wSql = wSql || 'BDCODTER, ';
  wSql = wSql || 'BDCGCTER, ';
  wSql = wSql || 'BDIETER, ';
  wSql = wSql || 'BDIMTER, ';
  wSql = wSql || 'BDNOMETER, ';
  wSql = wSql || 'BDLOGRTER, ';
  wSql = wSql || 'BDENDTER, ';
  wSql = wSql || 'BDNUMTER, ';
  wSql = wSql || 'BDCOMPTER, ';
  wSql = wSql || 'BDBAITER, ';
  wSql = wSql || 'bdnomcid, ';
  wSql = wSql || 'BDSIGLAUF, ';
  wSql = wSql || 'BDCEPTER, ';
  wSql = wSql || 'bddescpais ';

  wsql = wsql || ' from VEF_SP_EXP_TERCEIRO(';

  wparsqlcalc = '';

   IF (prempresa IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

   IF (prcodter IS NULL) THEN
      wparsqlcalc = wparsqlcalc||',null';
   ELSE
      wparsqlcalc = wparsqlcalc||','||''''||prcodter||'''';

   wparsqlcalc = wparsqlcalc||','||pranomesinicial;
   wparsqlcalc = wparsqlcalc||','||pranomesfinal;

   wparsqlcalc = wparsqlcalc||',null';

   wsql = wsql||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :wdatacadter,
       :wcodter,
       :wcgcter,
       :wieter,
       :wimter,
       :wnometer,
       :wlogrter,
       :wendter,
       :wnumter,
       :wcompter,
       :wbaiter,
       :wnomcid,
       :wsiglauf,
       :wcepter,
       :wdescpais
     DO
     BEGIN
       wRetorno = '';
       bdordemreg = 4;
       bdtiporeg = '4_9_1';
       bdreflan = NULL;

       -- Ord   Inicio / Fim / Tamanho

       --  01 -    001 a 008   008 Data de Data de Atualização
       IF (wdatacadter IS NULL) THEN
          SELECT bdretorno FROM preenche_direita('',8,' ') INTO waux;
       ELSE
          waux = SUBSTRING(CAST(wdatacadter AS VARCHAR(10)) FROM 9 FOR 2)||SUBSTRING(CAST(wdatacadter AS VARCHAR(10)) FROM 6 FOR 2)||SUBSTRING(CAST(wdatacadter AS VARCHAR(10)) FROM 1 FOR 4);
       wRetorno = wRetorno||waux;

       --  02 -    009 a 022   014 Código do Participante
       wsql = 'select bdretorno from preenche_direita('||''''||wcodter||''''||',14,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  03 -    023 a 036   014 CNPJ / CPF
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wcgcter||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_direita('||''''||TRIM(waux)||''''||',14,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  04 -    037 a 050   014 Inscrição Estadual
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wieter||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_direita('||''''||TRIM(waux)||''''||',14,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  05 -    051 a 064   014 Inscrição Municipal
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wimter||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_direita('||''''||TRIM(waux)||''''||',14,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  06 -    065 a 134   070 Nome ou Razão Socia
       wsql = 'select bdretorno from preenche_direita('||''''||wnometer||''''||',70,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  07 -    135 a 194   070 Endereço
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wlogrter||' '|| wendter||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',60,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  08 -    195 a 214   020 Bairro
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wbaiter||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  09 -    215 a 234   020 Municipio
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wnomcid||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',20,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  10 -    235 a 236   002 Unidade da Federação
       IF (wsiglauf = 'EX') THEN
          wsiglauf = ' ';
       wsql = 'select bdretorno from preenche_direita('||''''||wsiglauf||''''||',2,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  11 -    237 a 256   020 País
       IF (wdescpais = 'BRASIL') THEN
          wdescpais = ' ';
       wsql = 'select bdretorno from preenche_direita('||''''||wdescpais||''''||',20,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  12 -    257 a 264   008 Cep
       wsql = 'select bdretorno from RETIRA_CHAR_ESPECIAL('||''''||wcepter||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from retira_acento('||''''||waux||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wsql = 'select bdretorno from preenche_direita('||''''||waux||''''||',8,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       bdreg = wretorno;
       SUSPEND;
      END
END
^

/* Restore proc. body: VEF_SP_SVA_EXP_494 */
ALTER PROCEDURE VEF_SP_SVA_EXP_494(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
DECLARE VARIABLE WAUX VARCHAR(1000);
DECLARE VARIABLE WRETORNO VARCHAR(1000);
DECLARE VARIABLE WPARSQLCALC VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WDATACADNAT VARCHAR(8);
DECLARE VARIABLE WCODNAT INTEGER;
DECLARE VARIABLE WNOMENAT VARCHAR(255);
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

  wsql = '';

  wSql = wSql || ' select ';
  wSql = wSql || 'BDCODEMP, ';
  wSql = wSql || 'BDCODNAT, ';
  wSql = wSql || 'BDNOMENAT ';

  wsql = wsql || ' from VEF_SP_EXP_TNATOP(';


  wparsqlcalc = '';

   IF (prempresa IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

   wparsqlcalc = wparsqlcalc||','||pranomesinicial;
   wparsqlcalc = wparsqlcalc||','||pranomesfinal;

   wsql = wsql||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :wcodnat,
       :wnomenat
     DO
     BEGIN
       wRetorno = '';
       bdordemreg = 5;
       bdtiporeg = '4_9_4';
       bdreflan = NULL;

       -- Ord   Inicio / Fim / Tamanho

       --  01 -    001 a 008   008 Data de Atualização
       wdatacadnat = '01'||SUBSTRING(CAST(pranomesinicial AS VARCHAR(6)) FROM  5 FOR 2)||SUBSTRING(CAST(pranomesinicial AS VARCHAR(10)) FROM 1 FOR 4);  --pranomesinicial || '01';
       IF (wdatacadnat IS NULL) THEN
          SELECT bdretorno FROM preenche_direita('',8,' ') INTO waux;
       ELSE
          waux = wdatacadnat;
       wRetorno = wRetorno||waux;

       --  02 -    009 a 014   006 Código da Natureza da Operação
       wsql = 'select bdretorno from preenche_direita('||''''||wcodnat||''''||',6,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  03 -    015 a 059   045 Descrição
       wsql = 'select bdretorno from preenche_direita('||''''||wnomenat||''''||',44,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;
       wRetorno = wRetorno||' ';


       bdreg = wretorno;
       SUSPEND;


      END

END
^

/* Restore proc. body: VEF_SP_SVA_EXP_495 */
ALTER PROCEDURE VEF_SP_SVA_EXP_495(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
DECLARE VARIABLE WAUX VARCHAR(1000);
DECLARE VARIABLE WRETORNO VARCHAR(1000);
DECLARE VARIABLE WPARSQLCALC VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WDATACADPROD VARCHAR(8);
DECLARE VARIABLE WCODPROD INTEGER;
DECLARE VARIABLE WNOMEPROD VARCHAR(255);
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

  wsql = '';

  wSql = wSql || ' select ';
  wSql = wSql || 'BDCODEMP, ';
  wSql = wSql || 'BDCODPROD, ';
  wSql = wSql || 'BDNOMEPROD ';

  wsql = wsql || ' from VEF_SP_EXP_TPRODUTOS(';


  wparsqlcalc = '';

   IF (prempresa IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

   wparsqlcalc = wparsqlcalc||','||pranomesinicial;
   wparsqlcalc = wparsqlcalc||','||pranomesfinal;

   wsql = wsql||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :wcodprod,
       :wnomeprod
     DO
     BEGIN
       wRetorno = '';
       bdordemreg = 6;
       bdtiporeg = '4_9_5';
       bdreflan = NULL;

       -- Ord   Inicio / Fim / Tamanho

       --  01 -    001 a 008   008 Data de Atualização
       wdatacadprod =  '01'||SUBSTRING(CAST(pranomesinicial AS VARCHAR(6)) FROM  5 FOR 2)||SUBSTRING(CAST(pranomesinicial AS VARCHAR(10)) FROM 1 FOR 4);  --pranomesinicial || '01'; --pranomesinicial || '01';
       IF (wdatacadprod IS NULL) THEN
          SELECT bdretorno FROM preenche_direita('',8,' ') INTO waux;
       ELSE
          waux = wdatacadprod;
       wRetorno = wRetorno||waux;

       --  02 -    009 a 014   020 Código da Mercadoria /Produto /
       wsql = 'select bdretorno from preenche_direita('||''''||wcodprod||''''||',20,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;

       --  03 -    015 a 059   045 Descrição
       wsql = 'select bdretorno from preenche_direita('||''''||wnomeprod||''''||',45,'||''''||' '||''''||')';
       EXECUTE STATEMENT wsql INTO waux;
       wRetorno = wRetorno||waux;


       bdreg = wretorno;
       SUSPEND;


      END

END
^

/* Restore proc. body: VEF_SP_SVA_EXP_CAD */
ALTER PROCEDURE VEF_SP_SVA_EXP_CAD(PREMPRESA VARCHAR(10000),
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRTIPOEXP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDREFLAN INTEGER,
BDTIPOREG VARCHAR(10),
BDORDEMREG INTEGER,
BDREG VARCHAR(1000))
 AS
DECLARE VARIABLE waux VARCHAR(1000);
DECLARE VARIABLE wretorno VARCHAR(1000);
DECLARE VARIABLE wparsqlcalc VARCHAR(32700);
DECLARE VARIABLE wsql VARCHAR(32700);
BEGIN
  /* Procedure Text */

  EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

  -- Inicio do registro 4.9.1 --------------------------------------------------------------------------------------------------------

  wsql = 'select bdcodemp, bdreflan, bdtiporeg, bdordemreg,  bdreg ';
  wsql = wsql || ' from VEF_SP_SVA_EXP_491(';

  wparsqlcalc = '';

   IF (prempresa IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

   wparsqlcalc = wparsqlcalc||',null';
   wparsqlcalc = wparsqlcalc||','||pranomesinicial;
   wparsqlcalc = wparsqlcalc||','||pranomesfinal;
   wparsqlcalc = wparsqlcalc||','||prtipoexp;

   wsql = wsql||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bdreflan,
       :bdtiporeg,
       :bdordemreg,
       :bdreg
     DO

    SUSPEND;

  -- Inicio do registro 4.9.4 --------------------------------------------------------------------------------------------------------

  wsql = 'select bdcodemp, bdreflan, bdtiporeg, bdordemreg,  bdreg ';
  wsql = wsql || ' from VEF_SP_SVA_EXP_494(';

  wparsqlcalc = '';

   IF (prempresa IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

   wparsqlcalc = wparsqlcalc||','||pranomesinicial;
   wparsqlcalc = wparsqlcalc||','||pranomesfinal;
   wparsqlcalc = wparsqlcalc||','||prtipoexp;

   wsql = wsql||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bdreflan,
       :bdtiporeg,
       :bdordemreg,
       :bdreg
     DO

    SUSPEND;

  -- Inicio do registro 4.9.5 --------------------------------------------------------------------------------------------------------

  wsql = 'select bdcodemp, bdreflan, bdtiporeg, bdordemreg,  bdreg ';
  wsql = wsql || ' from VEF_SP_SVA_EXP_495(';

  wparsqlcalc = '';

   IF (prempresa IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||''''||prempresa||'''';

   wparsqlcalc = wparsqlcalc||','||pranomesinicial;
   wparsqlcalc = wparsqlcalc||','||pranomesfinal;
   wparsqlcalc = wparsqlcalc||','||prtipoexp;

   wsql = wsql||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsql
     INTO
       :bdcodemp,
       :bdreflan,
       :bdtiporeg,
       :bdordemreg,
       :bdreg
     DO

    SUSPEND;
END
^

/* Restore proc. body: VEF_SP_SVA_SERVICOS_ITENS */
ALTER PROCEDURE VEF_SP_SVA_SERVICOS_ITENS(PREMPRESA VARCHAR(10000),
PRTIPOLAN INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER,
PRODSERVICO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDCODCID INTEGER,
BDTIPOMOV VARCHAR(3),
BDDATAEMISSAO DATE,
BDCODTER INTEGER,
BDNUMDOC INTEGER,
BDTIPLAN VARCHAR(1),
BDESPECIE VARCHAR(6),
BDSERIE VARCHAR(5),
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDORDEM INTEGER,
BDCODNAT INTEGER,
BDVLRCONTAB NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDALIQIRSER NUMERIC(15,2),
BDBCIRSER NUMERIC(15,2),
BDVLRIRSER NUMERIC(15,2),
BDVLRISSSER NUMERIC(15,2),
BDIDCFPS INTEGER,
BDCODREC INTEGER,
BDCODOBS INTEGER,
BDIDCST INTEGER,
BDCONDPGTO INTEGER,
BDCONDPGTOAUX VARCHAR(1),
BDALIQREDBCISSSER NUMERIC(15,2),
BDBCISSSER NUMERIC(15,2),
BDALIQREDISSSER NUMERIC(15,2),
BDISENTASISSSER NUMERIC(15,2),
BDOUTRASISSSER NUMERIC(15,2),
BDACREDEDUIRSER NUMERIC(15,2),
BDACRECFINSER NUMERIC(15,2),
BDDIGOPERNAT INTEGER,
BDPREFIXONAT INTEGER,
BDCODATVM INTEGER,
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDCAMPO10 VARCHAR(1),
BDTIPOREG VARCHAR(10),
BDCODCSTPIS VARCHAR(2),
BDALIQPIS NUMERIC(15,4),
BDBCPIS NUMERIC(15,3),
BDCODCSTCOF VARCHAR(2),
BDALIQCOFINS NUMERIC(15,4),
BDBCCOFINS NUMERIC(15,3),
BDCAMPO07_4106 NUMERIC(15,2),
BDCAMPO14_4106 NUMERIC(15,2),
BDVLRCONTAB_4106 NUMERIC(15,3),
BDCAMPO10_4106 NUMERIC(15,2),
BDCAMPO17_4106 NUMERIC(15,2),
BDDESCPROD VARCHAR(45),
BDPRODSERVICO VARCHAR(5))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQLAUX VARCHAR(32700);
BEGIN
  /* Procedure Text */

 EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);

 BDPRODSERVICO = 'FALSE';

 wsql = 'SELECT  t.BDCODEMP, t.BDCHAVE, BDREFLAN, BDCODCIC, bddataemissao, bdcodter, bdnumdocini, bdtiplan, bdespecie, bdserie, bdcodsitnf, t.bdordem,
        bdcodnat, bdvlrcontab, BDDESCONTO, bdaliqirser, bdbcirser, bdvlrirser, bdvlrissser, bdidcfps, bdcodrec, bdcodobs, bdidcst, bdcondpgto, bdaliqredbcissser,
        bdbcissser, bdaliqredissser, bdisentasissser, bdoutrasissser, bdacrededuirser, bdacrecfinser, bddigopernat, bdprefixonat, bdcodatvm,
        coalesce(RET.bdvlrpis,0.0) BDVLRPIS, coalesce(RET.bdvlrcofins,0.0) BDVLRCOFINS, BDTIPOMOV ';

  wsql = wsql || ' from VW_VEF_EMP_TMOVSER_EXP_SVA T';
  /*wsql = wsql || ' left outer join VEF_EMP_TMOVSERRET ret on (ret.bdcodemp = t.bdcodemp and ret.bdchave = t.bdchave and ret.bdordem = t.bdordem) ';*/
  wsql = wsql || ' left outer join VEF_EMP_TMOVSERRET ret on (ret.bdcodemp = t.bdcodemp and ret.bdchave = t.bdchave) ';

  wwhere = '';

  IF (:prempresa IS NOT NULL) THEN
     wwhere = wwhere || :prempresa;

  IF (prtipolan IS NOT NULL) THEN
      BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
         IF (prtipolan = 0) THEN
            wwhere = wWhere||' bdtiplan = 0 ';
         ELSE
         IF (prtipolan = 1) THEN
            wwhere = wWhere||' bdtiplan = 1 ';
      END

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN <= '||:pranomesfinal;

     END

  wsql = wsql|| ' where ' || wwhere || ' order by bdcodemp, bdreflan, bdtiplan ' ;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    bdcodcid,
    bddataemissao,
    bdcodter,
    bdnumdoc,
    bdtiplan,
    bdespecie,
    bdserie,
    bdcodsitnf,

    bdordem,
    bdcodnat,
    bdvlrcontab,
    BDDESCONTO,
    bdaliqirser,
    bdbcirser,
    bdvlrirser,
    bdvlrissser,
    bdidcfps,
    bdcodrec,
    bdcodobs,
    bdidcst,
    bdcondpgto,
    bdaliqredbcissser,
    bdbcissser,
    bdaliqredissser,
    bdisentasissser,
    bdoutrasissser,
    bdacrededuirser,
    bdacrecfinser,
    bddigopernat,
    bdprefixonat,
    bdcodatvm,
    bdvlrpis,
    bdvlrcofins,

    BDTIPOMOV
  DO

  BEGIN

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       BEGIN
          bdvlrcontab = 0;
          BDDESCONTO = 0;
          bdaliqirser = 0;
          bdbcirser = 0;
          bdvlrirser = 0;
          bdvlrissser = 0;
          bdaliqredbcissser = 0;
          bdbcissser = 0;
          bdaliqredissser = 0;
          bdisentasissser = 0;
          bdoutrasissser = 0;
          bdacrededuirser = 0;
          bdacrecfinser = 0;
          bdvlrpis = 0;
          bdvlrcofins = 0;
       END

    IF (bdtiplan = 0) THEN
       bdtiporeg = '4_3_6';
    ELSE
       bdtiporeg = '4_3_9';

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       bdcodsitnfaux = 'S';
    ELSE
       bdcodsitnfaux = 'N';

    IF (BDCONDPGTO = 0)  THEN
       bdcondpgtoaux = '1';
    ELSE
       bdcondpgtoaux = '2';

    IF (((bdvlrcontab = 0) OR (bdvlrcontab IS NULL)) AND ((bdvlrirser = 0) OR (bdvlrissser IS NULL)))   THEN
        bdcampo10 = 'S';
    ELSE
        bdcampo10 = 'N';

    IF (bdvlrpis <> 0) THEN
      BEGIN
        bdcodcstpis = '01';
        bdbcpis = bdvlrcontab;
        IF (bdvlrcontab > 0) THEN
           bdaliqpis = bdvlrpis * 100 / bdvlrcontab;
        ELSE
           bdaliqpis = bdvlrpis * 100 / 1;
      END
    ELSE
      BEGIN
        bdcodcstpis = '07';
        bdbcpis = 0;
        bdaliqpis = 0;
      END

    IF (bdvlrcofins <> 0) THEN
      BEGIN
        bdcodcstcof = '01';
        bdbccofins = bdvlrcontab;
        IF (bdvlrcontab > 0) THEN
           bdaliqcofins = bdvlrcofins * 100 / bdvlrcontab;
        ELSE
           bdaliqcofins = bdvlrcofins * 100 / 1;
      END
    ELSE
      BEGIN
        bdcodcstcof = '07';
        bdbccofins = 0;
        bdaliqcofins = 0;
      END

    bdvlrcontab_4106 = bdvlrcontab;


    bdcampo07_4106 = 0.65;
    bdcampo14_4106 = 3;

    bdcampo10_4106 = bdvlrcontab_4106 * bdcampo07_4106 / 100;
    bdcampo17_4106 = bdvlrcontab_4106 * bdcampo14_4106 / 100;

    IF (bdcodatvm IS NULL) THEN
       IF (PRODSERVICO IS NOT NULL) THEN
          BEGIN
            wsqlaux = 'select bdcodprod, bddescprod from TCADPRO_vinc where bdcodemp = '||:BDCODEMP||' and bdcodprod = ' || :PRODSERVICO;
            EXECUTE STATEMENT wsqlaux INTO bdcodatvm, bddescprod;
            BDPRODSERVICO = 'TRUE';
          END


    SUSPEND;
  END
END
^

/* Restore proc. body: VEF_SP_SVA_SERVICOS_MOV */
ALTER PROCEDURE VEF_SP_SVA_SERVICOS_MOV(PREMPRESA VARCHAR(10000),
PRTIPOLAN INTEGER,
PRANOMESINICIAL INTEGER,
PRANOMESFINAL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDREFLAN INTEGER,
BDTIPOMOV VARCHAR(3),
BDDATAEMISSAO DATE,
BDCODTER INTEGER,
BDNUMDOC INTEGER,
BDTIPLAN VARCHAR(1),
BDESPECIE VARCHAR(5),
BDSERIE VARCHAR(6),
BDCODSITNF INTEGER,
BDCODSITNFAUX CHAR,
BDVLRCONTAB NUMERIC(15,2),
BDDESCONTO NUMERIC(15,2),
BDALIQIRSER NUMERIC(15,2),
BDBCIRSER NUMERIC(15,2),
BDVLRIRSER NUMERIC(15,2),
BDVLRISSSER NUMERIC(15,2),
BDIDCFPS INTEGER,
BDCODREC INTEGER,
BDIDCST INTEGER,
BDALIQREDBCISSSER NUMERIC(15,2),
BDBCISSSER NUMERIC(15,2),
BDALIQREDISSSER NUMERIC(15,2),
BDISENTASISSSER NUMERIC(15,2),
BDOUTRASISSSER NUMERIC(15,2),
BDACREDEDUIRSER NUMERIC(15,2),
BDACRECFINSER NUMERIC(15,2),
BDDIGOPERNAT INTEGER,
BDPREFIXONAT INTEGER,
BDCODATVM INTEGER,
BDCAMPO10 VARCHAR(1),
BDTIPOREG VARCHAR(10),
BDVLRPIS NUMERIC(15,2),
BDVLRCOFINS NUMERIC(15,2),
BDVLRCSOCIAL NUMERIC(15,2),
BDALIQPIS NUMERIC(5,2),
BDALIQCOFINS NUMERIC(5,2),
BDALIQCSOCIAL NUMERIC(5,2))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQLAUX VARCHAR(32700);
DECLARE VARIABLE WLANBCICMSISEOUT INTEGER;
BEGIN
  /* Procedure Text */

 EXECUTE PROCEDURE sp_seta_competencia(pranomesinicial, NULL, NULL);


 wsql = 'SELECT  T.BDCODEMP, T.BDCHAVE, T.BDREFLAN, T.BDTIPOMOV , T.bddataemissao, T.bdcodter, T.bdnumdocini, T.bdtiplan, T.bdespecie, T.bdserie, T.bdcodsitnf, T.bdaliqirser,
         sum(coalesce(RET.bdvlrpis,0.0)) BDVLRPIS,
         sum(coalesce(RET.bdvlrcofins,0.0)) BDVLRCOFINS,
         sum(coalesce(RET.bdvlrcsocial,0.0)) BDVLRCSOCIAL,
         sum(T.bdvlrcontab) bdvlrcontab, sum(T.BDDESCONTO) BDDESCONTO, sum(T.bdbcirser) bdbcirser , sum(T.bdvlrirser) bdvlrirser, sum(T.bdvlrissser) bdvlrissser ';

 wsql = wsql || ' from VW_VEF_EMP_TMOVSER_EXP_SVA T';

 /*wsql = wsql || ' left outer join VEF_EMP_TMOVSERRET ret on (ret.bdcodemp = t.bdcodemp and ret.bdchave = t.bdchave and ret.bdordem = t.bdordem) ';*/
 wsql = wsql || ' left outer join VEF_EMP_TMOVSERRET ret on (ret.bdcodemp = t.bdcodemp and ret.bdchave = t.bdchave) ';

 wwhere = '';

  IF (:prempresa IS NOT NULL) THEN
     wwhere = wwhere || :prempresa;

  IF (prtipolan IS NOT NULL) THEN
      BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
         IF (prtipolan = 0) THEN
            wwhere = wWhere||' bdtiplan = 0 ';
         ELSE
         IF (prtipolan = 1) THEN
            wwhere = wWhere||' bdtiplan = 1 ';
      END

  IF (:pranomesinicial IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN >= '||:pranomesinicial;

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'T.BDREFLAN <= '||:pranomesfinal;

     END

  wsql = wsql||' where ' || wwhere || ' group by BDCODEMP, BDCHAVE, BDREFLAN, BDTIPOMOV , bddataemissao, bdcodter, bdnumdocini, bdtiplan, bdespecie, bdserie, bdcodsitnf, bdaliqirser
                                        order by bdcodemp, bdreflan, bdtiplan ' ;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDCHAVE,
    BDREFLAN,
    BDTIPOMOV ,
    bddataemissao,
    bdcodter,
    bdnumdoc,
    bdtiplan,
    bdespecie,
    bdserie,
    bdcodsitnf,
    bdaliqirser,
    bdvlrpis,
    bdvlrcofins,
    bdvlrcsocial,

    bdvlrcontab,
    BDDESCONTO,
    bdbcirser,
    bdvlrirser,
    bdvlrissser

  DO

  BEGIN

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       BEGIN
          bdaliqirser = 0;
          bdvlrpis = 0;
          bdvlrcofins = 0;
          bdvlrcsocial = 0;
          bdvlrcontab = 0;
          BDDESCONTO = 0;
          bdbcirser = 0;
          bdvlrirser = 0;
          bdvlrissser = 0;
       END

    IF (bdtiplan = 0) THEN
       bdtiporeg = '4_3_5';
    ELSE
       bdtiporeg = '4_3_8';

    IF (bdcodsitnf IN (2,3,4,5)) THEN--alt.:7817
       bdcodsitnfaux = 'S';
    ELSE
       bdcodsitnfaux = 'N';

    IF (((bdvlrcontab = 0) OR (bdvlrcontab IS NULL)) AND ((bdvlrirser = 0) OR (bdvlrissser IS NULL)))   THEN
        bdcampo10 = 'S';
    ELSE
        bdcampo10 = 'N';

    IF (bdvlrcontab <> 0) THEN
      BEGIN
        bdaliqpis = (bdvlrpis * 100) / bdvlrcontab;
        bdaliqcofins = (bdvlrcofins * 100) / bdvlrcontab;
        bdaliqcsocial = (bdvlrcsocial * 100) / bdvlrcontab;
      END
    ELSE
      BEGIN
        bdaliqpis = 0;
        bdaliqcofins = 0;
        bdaliqcsocial = 0;

      END



    SUSPEND;
  END


END
^

/* Restore proc. body: VEF_SP_TREEVIEW_CONS_ANUAL_CONF */
ALTER PROCEDURE VEF_SP_TREEVIEW_CONS_ANUAL_CONF(PRCODEMP VARCHAR(10000),
PRREF INTEGER,
PRCODPLANO INTEGER,
PRCODQUADRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDREF INTEGER,
BDCODQUADRO INTEGER,
BDDESCQUADRO VARCHAR(80),
BDORDEM INTEGER,
BDDESCRICAO VARCHAR(80),
BDVALOR NUMERIC(15,6),
BDTOTAL NUMERIC(15,6),
BDJAN NUMERIC(15,6),
BDFEV NUMERIC(15,6),
BDMAR NUMERIC(15,6),
BDABR NUMERIC(15,6),
BDMAI NUMERIC(15,6),
BDJUN NUMERIC(15,6),
BDJUL NUMERIC(15,6),
BDAGO NUMERIC(15,6),
BDSET NUMERIC(15,6),
BDOUT NUMERIC(15,6),
BDNOV NUMERIC(15,6),
BDDEZ NUMERIC(15,6),
BDCODMATRIZ INTEGER,
BDREGAUX INTEGER)
 AS
DECLARE VARIABLE WCODEMPANTERIOR INTEGER;
DECLARE VARIABLE WNOMEEMPANTERIOR DM_BDNOMEMP;
DECLARE VARIABLE WREFANTERIOR INTEGER;
DECLARE VARIABLE WCODQUADROANTERIOR INTEGER;
DECLARE VARIABLE WDESCQUADROANTERIOR VARCHAR(80);
DECLARE VARIABLE WORDEMANTERIOR INTEGER;
DECLARE VARIABLE WDESCRICAOANTERIOR VARCHAR(80);
DECLARE VARIABLE WCODMATRIZANTERIOR INTEGER;
DECLARE VARIABLE WCODEMPAUX INTEGER;
DECLARE VARIABLE WNOMEEMPAUX DM_BDNOMEMP;
DECLARE VARIABLE WREFAUX INTEGER;
DECLARE VARIABLE WCODQUADROAUX INTEGER;
DECLARE VARIABLE WDESCQUADROAUX VARCHAR(80);
DECLARE VARIABLE WORDEMAUX INTEGER;
DECLARE VARIABLE WDESCRICAOAUX VARCHAR(80);
DECLARE VARIABLE WCODMATRIZAUX INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WWHERE VARCHAR(32000);
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WORDEMTOT NUMERIC(15,6);
DECLARE VARIABLE WORDEMJAN NUMERIC(15,6);
DECLARE VARIABLE WORDEMFEV NUMERIC(15,6);
DECLARE VARIABLE WORDEMMAR NUMERIC(15,6);
DECLARE VARIABLE WORDEMABR NUMERIC(15,6);
DECLARE VARIABLE WORDEMMAI NUMERIC(15,6);
DECLARE VARIABLE WORDEMJUN NUMERIC(15,6);
DECLARE VARIABLE WORDEMJUL NUMERIC(15,6);
DECLARE VARIABLE WORDEMAGO NUMERIC(15,6);
DECLARE VARIABLE WORDEMSET NUMERIC(15,6);
DECLARE VARIABLE WORDEMOUT NUMERIC(15,6);
DECLARE VARIABLE WORDEMNOV NUMERIC(15,6);
DECLARE VARIABLE WORDEMDEZ NUMERIC(15,6);
DECLARE VARIABLE WCODQUADROANTERIOR_CONTROLE INTEGER;
DECLARE VARIABLE WCODEMPANTERIOR_CONTROLE INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql||'empresas.BDNOMEMP, ';
  wsql = wsql||'T.BDREF, ';
  wsql = wsql||'T.BDCODQPLACONSCONF, ';
  wsql = wsql||'QUADRO.BDDESCRICAO, ';
  wsql = wsql||'T.BDORDEM, ';
  wsql = wsql||'T.BDDESCRICAO, ';
  wsql = wsql||'T.BDVALOR, ';
  wsql = wsql||'T.BDCODMATRIZ ';
  wsql = wsql||'from VEF_REL_CONS_ANUAL_CONF T '; --tabela por sessão
  wsql = wsql||' left outer join VW_EMPRESAS_REF_ATUAL empresas on (empresas.bdcodemp = t.bdcodemp) ';
  wsql = wsql||' left outer join TPLANOCONSCONF_Q QUADRO on (QUADRO.BDCODQPLACONSCONF = t.BDCODQPLACONSCONF AND QUADRO.BDCODPLACONSCONF = T.BDCODPLACONSCONF) ';

  wwhere = '';

  IF (:prcodemp IS NOT NULL) THEN
    wwhere = :prcodemp;

  IF ((:prCodPlano IS NOT NULL) AND (:prCodPlano > 0)) THEN
    BEGIN
      IF (wWhere <> '') THEN
        wWhere = wWhere||' and ';
      ELSE
        wWhere = wWhere||' where ';

      wWhere = wWhere||'T.BDCODPLACONSCONF  = '||:prCodPlano;
    END

  IF (:prcodquadro IS NOT NULL) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      ELSE
        wwhere = wwhere||' where ';

      wwhere = wwhere||'T.BDCODQPLACONSCONF  = '||:prcodquadro;
    END

  IF (:prRef IS NOT NULL) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      ELSE
        wwhere = wwhere||' where ';

      wwhere = wwhere||'T.BDREF Between '||SUBSTRING(:prRef FROM 1 FOR 4)||'01 and '||SUBSTRING(:prRef FROM 1 FOR 4)||'12 ';
    END

  IF (wwhere <> '') THEN
    wwhere = 'where '||wwhere||' and QUADRO.bdcodsis = 3';
  ELSE
    wwhere = wwhere||' where QUADRO.bdcodsis = 3';

  wsql = wsql||wwhere||' order by t.bdcodmatriz, t.bdcodemp, t.bdcodqplaconsconf, t.bdordem, t.bdref ';

  /*inicializa variaveis*/
  wcodmatrizanterior = 0;
  wcodempanterior = 0;
  wcodquadroanterior = 0;
  wordemanterior = 0;
  wcodquadroanterior_controle = 0;
  wcodempanterior_controle = 0;

  wordemtot = 0;
  wordemjan = 0;
  wordemfev = 0;
  wordemmar = 0;
  wordemabr = 0;
  wordemmai = 0;
  wordemjun = 0;
  wordemjul = 0;
  wordemago = 0;
  wordemset = 0;
  wordemout = 0;
  wordemnov = 0;
  wordemdez = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDNOMEMP,
    BDREF,
    BDCODQUADRO,
    BDDESCQUADRO,
    BDORDEM,
    BDDESCRICAO,
    BDVALOR,
    BDCODMATRIZ
  DO
    BEGIN
      IF ((wcodempanterior_controle = 0) OR (wcodempanterior_controle <> wcodempanterior)) THEN
        BEGIN
         wordemaux = :bdordem;
         wdescricaoaux = :bddescricao;
 
         bdordem = NULL;
         bddescricao = LPAD(:bdcodemp||' - '||:bdnomemp, 80);
 
         bdregaux = 2;
         SUSPEND;
 
         wcodempanterior_controle = :bdcodemp;
         bdordem = wordemaux;
         bddescricao = wdescricaoaux;
        END
 
      IF ((wcodquadroanterior_controle = 0) OR (wcodquadroanterior_controle <> wcodquadroanterior) ) THEN
        BEGIN
          wordemaux = :bdordem;
          wdescricaoaux = :bddescricao;
 
          bdordem = NULL;
          bddescricao = :bddescquadro;
 
          bdregaux = 1;
          SUSPEND;
 
          wcodquadroanterior_controle = :bdcodquadro;
          bdordem = wordemaux;
          bddescricao = wdescricaoaux;
        END

      IF ((wordemanterior <> :bdordem) OR (wcodquadroanterior <> :bdcodquadro) OR (wcodempanterior <> :bdcodemp) OR (wcodmatrizanterior <> :bdcodmatriz)) THEN
        BEGIN
          IF (wordemanterior <> 0) THEN
            BEGIN
              --guarda o conteudo em uma variavel auxiliar
              wcodempaux = :bdcodemp;
              wnomeempaux = :bdnomemp;
              wrefaux = :bdref;
              wcodquadroaux = :bdcodquadro;
              wdescquadroaux = :bddescquadro;
              wordemaux = :bdordem;
              wdescricaoaux = :bddescricao;
              wcodmatrizaux = :bdcodmatriz;

              --pega o valor anterior e aplica nos campos de saída
              bdcodemp = wcodempanterior;
              bdnomemp = wnomeempanterior;
              bdref = wrefanterior;
              bdcodquadro = wcodquadroanterior;
              bddescquadro = wdescquadroanterior;
              bdordem = wordemanterior;
              bddescricao = wdescricaoanterior;
              bdcodmatriz = wcodmatrizanterior;

              --passa os totalizadores para os campos de saída
              bdtotal = wordemtot;
              bdjan = wordemjan;
              bdfev = wordemfev;
              bdmar = wordemmar;
              bdabr = wordemabr;
              bdmai = wordemmai;
              bdjun = wordemjun;
              bdjul = wordemjul;
              bdago = wordemago;
              bdset = wordemset;
              bdout = wordemout;
              bdnov = wordemnov;
              bddez = wordemdez;

              bdregaux = 0;
              SUSPEND;

              bdtotal = NULL;
              bdjan = NULL;
              bdfev = NULL;
              bdmar = NULL;
              bdabr = NULL;
              bdmai = NULL;
              bdjun = NULL;
              bdjul = NULL;
              bdago = NULL;
              bdset = NULL;
              bdout = NULL;
              bdnov = NULL;
              bddez = NULL;

              --retorna os valores originais dos campos de saida
              bdcodemp = wcodempaux;
              bdnomemp = wnomeempaux;
              bdref = wrefaux;
              bdcodquadro = wcodquadroaux;
              bddescquadro = wdescquadroaux;
              bdordem = wordemaux;
              bddescricao = wdescricaoaux;
              bdcodmatriz = wcodmatrizaux;
            END

          wcodempanterior = :bdcodemp;
          wnomeempanterior = :bdnomemp;
          wrefanterior = :bdref;
          wcodquadroanterior = :bdcodquadro;
          wdescquadroanterior = :bddescquadro;
          wordemanterior = :bdordem;
          wdescricaoanterior = :bddescricao;
          wcodmatrizanterior = :bdcodmatriz;

          wordemtot = 0;
          wordemjan = 0;
          wordemfev = 0;
          wordemmar = 0;
          wordemabr = 0;
          wordemmai = 0;
          wordemjun = 0;
          wordemjul = 0;
          wordemago = 0;
          wordemset = 0;
          wordemout = 0;
          wordemnov = 0;
          wordemdez = 0;
        END

      wmes = CAST(SUBSTRING(:bdref FROM 5 FOR 2) AS INTEGER);

      wordemtot = wordemtot + :bdvalor;

      IF (wmes = 1) THEN
        wordemjan = :bdvalor;
      ELSE IF (wmes = 2) THEN
        wordemfev = :bdvalor;
      ELSE IF (wmes = 3) THEN
        wordemmar = :bdvalor;
      ELSE IF (wmes = 4) THEN
        wordemabr = :bdvalor;
      ELSE IF (wmes = 5) THEN
        wordemmai = :bdvalor;
      ELSE IF (wmes = 6) THEN
        wordemjun = :bdvalor;
      ELSE IF (wmes = 7) THEN
        wordemjul = :bdvalor;
      ELSE IF (wmes = 8) THEN
        wordemago = :bdvalor;
      ELSE IF (wmes = 9) THEN
        wordemset = :bdvalor;
      ELSE IF (wmes = 10) THEN
        wordemout = :bdvalor;
      ELSE IF (wmes = 11) THEN
        wordemnov = :bdvalor;
      ELSE IF (wmes = 12) THEN
        wordemdez = :bdvalor;
    END

    IF (:bdordem IS NOT NULL) THEN
      BEGIN
        IF (wcodempanterior_controle <> :bdcodemp) THEN
          BEGIN
            wordemaux = :bdordem;
            wdescricaoaux = :bddescricao;

            bdordem = NULL;
            bddescricao = :bdnomemp;

            bdregaux = 2;
            SUSPEND;

            bdordem = wordemaux;
            bddescricao = wdescricaoaux;
          END

        IF (wcodquadroanterior_controle <> :bdcodquadro) THEN
          BEGIN
            wordemaux = :bdordem;
            wdescricaoaux = :bddescricao;

            bdordem = NULL;
            bddescricao = :bddescquadro;

            bdregaux = 1;
            SUSPEND;

            bdordem = wordemaux;
            bddescricao = wdescricaoaux;
          END

        bdtotal = wordemtot;
        bdjan = wordemjan;
        bdfev = wordemfev;
        bdmar = wordemmar;
        bdabr = wordemabr;
        bdmai = wordemmai;
        bdjun = wordemjun;
        bdjul = wordemjul;
        bdago = wordemago;
        bdset = wordemset;
        bdout = wordemout;
        bdnov = wordemnov;
        bddez = wordemdez;

        bdregaux = 0;
        SUSPEND;
      END
END
^

/* Restore proc. body: VLAL_CONSULTA_APU_TREEWIEW */
ALTER PROCEDURE VLAL_CONSULTA_APU_TREEWIEW(PRCODEMP VARCHAR(2048),
PRDATAINI DATE,
PRDATAFIM DATE,
PRPERAPU INTEGER)
 RETURNS(BDDATA VARCHAR(10),
BDSAIDA VARCHAR(30))
 AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WDATFINAPU DATE;
DECLARE VARIABLE WTIPAPU INTEGER;
DECLARE VARIABLE WDATASAIDA VARCHAR(10);
BEGIN

  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  wsql = ' select distinct(tapu.bddatfinapu) , tapu.bdtipapu ';
  wsql = wsql||' from vlal_empresas_apuracao tapu ';

  IF (prcodemp IS NOT NULL) THEN
     wsql = wsql||'where tapu.bdcodemp = ('||prcodemp||') ';

  IF (prcodemp IS NOT NULL) THEN
     wsql = wsql||' and tapu.bdperapu = ('||prperapu||') ';


  IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
     wsql = wsql ||' and (bddatfinapu between '''||wdatini||''' and '''||wdatfin||''') ';


  wsql = wsql||' order by tapu.bddatfinapu ';

  -- executa o sql das empresas
  FOR EXECUTE STATEMENT wsql
      INTO :wdatfinapu, :wtipapu  DO
      BEGIN
        wdatasaida = SUBSTRING(CAST(wdatfinapu AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
                     SUBSTRING(CAST(wdatfinapu AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
                     SUBSTRING(CAST(wdatfinapu AS VARCHAR(10)) FROM 1 FOR 4);

        bddata  = :wdatasaida;

        IF (wtipapu <=0) THEN
           bdsaida = :wdatasaida || ' - Presumido';
        ELSE
           bdsaida = :wdatasaida || ' - Real';




        SUSPEND;
      END

END
^

/* Restore proc. body: VLAL_COPIA_PARTEA_PLANO */
ALTER PROCEDURE VLAL_COPIA_PARTEA_PLANO (APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
DECLARE VARIABLE WAPELPA VARCHAR(20);
DECLARE VARIABLE WCTALONLPA VARCHAR(40);
DECLARE VARIABLE WNOMLPA VARCHAR(60);
DECLARE VARIABLE WTIPCTALPA SMALLINT;
DECLARE VARIABLE WFORLPA VARCHAR(200);
DECLARE VARIABLE WCONLPA VARCHAR(200);
DECLARE VARIABLE WCOLLPA INTEGER;
DECLARE VARIABLE WIMPZEROLPA VARCHAR(5);
DECLARE VARIABLE WIMPNEGROLPA VARCHAR(5);
DECLARE VARIABLE WSOTEXTOLPA VARCHAR(5);
DECLARE VARIABLE WZERASALDOLPA VARCHAR(5);
DECLARE VARIABLE WNAOACUMULALPA VARCHAR(5);
DECLARE VARIABLE WTIPOCONTA INTEGER;
DECLARE VARIABLE WTIPOTRIBUTO INTEGER;
declare variable WCODLPA integer;
BEGIN
  DELETE FROM VLAL_PLANOS_TLPA WHERE BDCODPARTEA = :codigonovo;

  IF ((codigonovo IS NULL) OR (codigonovo = 0))  THEN
     BEGIN
       --#alt:85809 . Estava pegando o código a partir do apelido, mas o apelido não estava sendo tratado para ser exclusivo. Ana - 22/06/2018
       SELECT MAX(BDCODPARTEA) FROM VLAL_BASE_LALUR_PARTEA INTO codigonovo;
     END
  --#alt:85809 . Incluído campo do código, pois o código deve ser o mesmo para as fórmulas. Ana - 22/06/2018
  --Incluido campos "Tipo tributo" e "Tipo conta ECF" - Carlos Machado - 12/06/2018 - Sol. 84867
  FOR SELECT BDCODLPA, bdctalonlpa,bdnomlpa,bdapelpa,bdtipctalpa,bdforlpa,bdconlpa,
             bdcollpa,bdimpzerolpa,bdimpnegrolpa,bdsotextolpa,bdzerasaldolpa,bdnaoacumulalpa,BDTIPOTRIBUTO,BDTIPOCONTA FROM VLAL_PLANOS_TLPA
             WHERE BDCODPARTEA = : codigocopiar INTO
             :WCODLPA, :wctalonlpa,:wnomlpa,:wapelpa,:wtipctalpa,:wforlpa,:wconlpa,
             :wcollpa,:wimpnegrolpa,:wimpnegrolpa,:wsotextolpa,:wzerasaldolpa,:wnaoacumulalpa,:wtipotributo,wtipoconta DO
     BEGIN
        INSERT INTO VLAL_PLANOS_TLPA (BDCODPARTEA,BDCODLPA, bdctalonlpa,bdnomlpa,bdapelpa,
                                 bdtipctalpa,bdforlpa,bdconlpa,
                                 bdcollpa,bdimpzerolpa,bdimpnegrolpa,bdsotextolpa,bdzerasaldolpa,bdnaoacumulalpa,BDTIPOTRIBUTO,BDTIPOCONTA) VALUES
                                 (:codigonovo,:WCODLPA, :wctalonlpa,:wnomlpa,:wapelpa,:wtipctalpa,:wforlpa,:wconlpa,
                                  :wcollpa,:wimpzerolpa,:wimpnegrolpa,:wsotextolpa,:wzerasaldolpa,:wnaoacumulalpa,:wtipotributo,:wtipoconta);
     END
END
^

/* Restore proc. body: VLAL_COPIA_PARTEB_PLANO */
ALTER PROCEDURE VLAL_COPIA_PARTEB_PLANO(APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
DECLARE VARIABLE WAPELPB VARCHAR(20);
DECLARE VARIABLE WCTALONLPB VARCHAR(40);
DECLARE VARIABLE WNOMLPB VARCHAR(60);
DECLARE VARIABLE WTIPCTALPB SMALLINT;
DECLARE VARIABLE WFORLPB VARCHAR(200);
DECLARE VARIABLE WCONLPB VARCHAR(200);
DECLARE VARIABLE WPRESLPB INTEGER;
DECLARE VARIABLE WHISTANTLPB VARCHAR(100);
DECLARE VARIABLE WHISTDEBLPB VARCHAR(100);
DECLARE VARIABLE WHISTCRELPB VARCHAR(100);
DECLARE VARIABLE WBDCODLPB INTEGER;
BEGIN
  DELETE FROM VLAL_PLANOS_TLPB WHERE BDCODPARTEB = :codigonovo;

  IF ((codigonovo IS NULL) OR (codigonovo = 0))  THEN
     BEGIN
        SELECT BDCODPARTEB FROM VLAL_BASE_LALUR_PARTEB WHERE bdapePARTEB = :apelido_novo_plano INTO codigonovo;
     END

  FOR SELECT bdcodlPB, bdctalonlPB,bdnomlPB,bdapelPB,bdtipctalPB,bdforlPB,bdconlPB,
             bdpreslpb,bdhistantlpb,bdhistdeblpb , bdhistcrelpb FROM VLAL_PLANOS_TLPB
             WHERE BDCODPARTEB = : codigocopiar INTO
                   :wbdcodlPB,:wctalonlPB,:wnomlpb,:wapelpb,:wtipctalPB,:wforlPB,:wconlPB,
                   :wpreslpb,:whistantlpb,:whistdeblpb , :whistcrelpb DO
     BEGIN
        INSERT INTO VLAL_PLANOS_TLPB (BDCODPARTEB,bdcodlPB,bdctalonlPB,bdnomlPB,bdapelPB,
                                 bdtipctalPB,bdforlPB,bdconlPB,
                                 bdpreslpb,bdhistantlpb,bdhistdeblpb , bdhistcrelpb) VALUES
                                 (:codigonovo,:wbdcodlPB,:wctalonlPB,:wnomlPB,:wapelPB,:wtipctalPB,:wforlPB,:wconlPB,
                                  :wpreslpb,:whistantlpb,:whistdeblpb , :whistcrelpb);
     END
END
^

/* Restore proc. body: VLAL_SP_CONS_ACUM_PARTEA */
ALTER PROCEDURE VLAL_SP_CONS_ACUM_PARTEA(PRCODEMP INTEGER,
PRCODLPA INTEGER,
PRCODTIPO INTEGER,
PRREFLANAN VARCHAR(10))
 RETURNS(BDREFLANAN INTEGER,
BDCODTHPI INTEGER,
BDNOME VARCHAR(40),
BDVALLANAN NUMERIC(15,2))
 AS
DECLARE VARIABLE wvalant NUMERIC(15,2);
DECLARE VARIABLE wvalor NUMERIC(15,2);
BEGIN
  wvalant = 0;
  FOR SELECT tlanParteAAnual.bdREFLANAN,
             tlanParteAAnual.bdcodtphi, this.bdnome,
             tlanParteAAnual.bdVALLANAN
      FROM VLAL_EMPRESAS_TLLA_ANUAL tlanParteAAnual
      LEFT OUTER JOIN hist_tphi this ON (this.bdcodhist = tlanParteAAnual.bdcodhist AND this.bdcodtphi = tlanParteAAnual.bdcodtphi)
      WHERE bdCODEMP = :prcodemp AND bdCODLPA = :prCodLPA
      AND bdCODTIPO = :prCodTipo
      AND SUBSTRING(CAST(bdreflanan AS VARCHAR(6)) FROM 1 FOR 4) = SUBSTRING(:prreflanan FROM 4 FOR 4)
      ORDER BY tlanParteAAnual.bdCODEMP, tlanParteAAnual.bdCODTIPO, tlanParteAAnual.bdCODLPA,tlanParteAAnual.bdREFLANAN
      INTO :bdreflanan, :bdcodthpi, :bdnome, :wvalor DO
      BEGIN
        IF (prcodtipo = 17) THEN
           bdvallanan = wvalant + wvalor;
        ELSE
           bdvallanan = wvalor;
         wvalant = wvalant + wvalor;
        SUSPEND;
      END
END
^

/* Restore proc. body: VLAL_SP_LAN_PARTEA */
ALTER PROCEDURE VLAL_SP_LAN_PARTEA(PREMPRESA INTEGER,
PRCODLLA INTEGER,
PRCODUSU INTEGER,
PRANOBASE INTEGER,
PRCODPARTEA INTEGER,
PRCODLPA INTEGER,
PRCODTPHI INTEGER,
PRANUALACUMULADO SMALLINT,
PRVALOR1 NUMERIC(15,2),
PRCOMPL1 VARCHAR(200),
PRVALOR2 NUMERIC(15,2),
PRCOMPL2 VARCHAR(200),
PRVALOR3 NUMERIC(15,2),
PRCOMPL3 VARCHAR(200),
PRVALOR4 NUMERIC(15,2),
PRCOMPL4 VARCHAR(200),
PRVALOR5 NUMERIC(15,2),
PRCOMPL5 VARCHAR(200),
PRVALOR6 NUMERIC(15,2),
PRCOMPL6 VARCHAR(200),
PRVALOR7 NUMERIC(15,2),
PRCOMPL7 VARCHAR(200),
PRVALOR8 NUMERIC(15,2),
PRCOMPL8 VARCHAR(200),
PRVALOR9 NUMERIC(15,2),
PRCOMPL9 VARCHAR(200),
PRVALOR10 NUMERIC(15,2),
PRCOMPL10 VARCHAR(200),
PRVALOR11 NUMERIC(15,2),
PRCOMPL11 VARCHAR(200),
PRVALOR12 NUMERIC(15,2),
PRCOMPL12 VARCHAR(200),
PRREFEMP INTEGER)
 AS
DECLARE VARIABLE wanolan INTEGER;
DECLARE VARIABLE wcodpartea INTEGER;
DECLARE VARIABLE wcodhist INTEGER;
DECLARE VARIABLE wdia INTEGER;
DECLARE VARIABLE wmes INTEGER;
DECLARE VARIABLE wano INTEGER;
DECLARE VARIABLE wdatalanc DATE;
DECLARE VARIABLE wcodusu INTEGER;
BEGIN
  --SELECT BDCODPARTEA FROM VLAL_BASE_TEMP WHERE BDCODEMP = :PREMPRESA INTO :WCODPARTEA;
  SELECT TEMP.BDCODPARTEA, TREF.BDCODHIST FROM VLAL_BASE_TEMP TEMP
  INNER JOIN tempresas_ref tref ON (tref.bdcodemp = temp.bdcodemp)
  WHERE TEMP.BDCODEMP = :PREMPRESA
  AND tref.bdrefemp = (SELECT FIRST 1 tempresas_ref.bdrefemp FROM tempresas_ref
                       WHERE tempresas_ref.bdcodemp = temp.bdcodemp
                       AND tempresas_ref.bdrefemp <= :prrefemp
                       ORDER BY tempresas_ref.bdrefemp)
  INTO WCODPARTEA, WCODHIST;

  WANO = :PRANOBASE;

  --alt:11995 - 21/08/2015 - Carrega o código do usuário para ser inserido nos lançamentos. Pedro
  SELECT BDCODUSU FROM SP_GET_USUARIO INTO :wCodUsu;

  /*SELECT CAST(SUBSTRING(LLA.BDDATLLA FROM 1 FOR 4) AS INTEGER) AS ANO FROM VLAL_EMPRESAS_TLLA LLA
  WHERE (SUBSTRING(LLA.BDDATLLA FROM 1 FOR 4) = :PRANOBASE)
  AND   (LLA.BDCODPARTEA = :WCODPARTEA)
  AND   (LLA.BDCODLPA = :PRCODLPA)
  GROUP BY ANO
  INTO WANOLAN;

  IF ((:WANOLAN IS NOT NULL) AND (WANOLAN <> 0)) THEN
    EXCEPTION EX_DATE;*/

  /* MÊS 01 */
  IF (PRVALOR1 <> 0) THEN
    BEGIN
      WMES = 1;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR1, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL1);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR1, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL1);
        END
    END

  /* MÊS 02 */
  IF (PRVALOR2 <> 0) THEN
    BEGIN
      WMES = 2;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR2, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL2);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR2, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL2);
        END
    END

  /* MÊS 03 */
  IF (PRVALOR3 <> 0) THEN
    BEGIN
      WMES = 3;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR3, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL3);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR3, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL3);
        END
    END

  /* MÊS 04 */
  IF (PRVALOR4 <> 0) THEN
    BEGIN
      WMES = 4;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR4, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL4);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR4, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL4);
        END
    END

  /* MÊS 05 */
  IF (PRVALOR5 <> 0) THEN
    BEGIN
      WMES = 5;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR5, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL5);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR5, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL5);
        END
    END

  /* MÊS 06 */
  IF (PRVALOR6 <> 0) THEN
    BEGIN
      WMES = 6;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR6, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL6);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR6, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL6);
        END
    END

  /* MÊS 07 */
  IF (PRVALOR7 <> 0) THEN
    BEGIN
      WMES = 7;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR7, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL7);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR7, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL7);
        END
    END

  /* MÊS 08 */
  IF (PRVALOR8 <> 0) THEN
    BEGIN
      WMES = 8;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR8, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL8);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR8, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL8);
        END
    END

  /* MÊS 09 */
  IF (PRVALOR9 <> 0) THEN
    BEGIN
      WMES = 9;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR9, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL9);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR9, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL9);
        END
    END

  /* MÊS 10 */
  IF (PRVALOR10 <> 0) THEN
    BEGIN
      WMES = 10;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR10, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL10);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR10, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL10);
        END
    END

  /* MÊS 11 */
  IF (PRVALOR11 <> 0) THEN
    BEGIN
      WMES = 11;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR11, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL11);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR11, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL11);
        END
    END

  /* MÊS 12 */
  IF (PRVALOR12 <> 0) THEN
    BEGIN
      WMES = 12;
      SELECT ULTDIA FROM ULTIMO_DIA_MES(:WMES, :PRANOBASE) INTO :WDIA;
      WDATALANC = CAST(WMES||'/'||WDIA||'/'||WANO AS DATE);
      IF (:PRANUALACUMULADO = 0) THEN
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :WCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR12, CURRENT_DATE, CURRENT_TIME, 17, :PRCOMPL12);
        END
      ELSE
        BEGIN
          INSERT INTO VLAL_EMPRESAS_TLLA (BDCODEMP, BDCODLLA, BDCODUSU, BDCODPARTEA, BDCODLPA, BDCODHIST, BDCODTPHI,
                                          BDDATLLA, BDVALLLA, BDDATALANLLA, BDHORALANLLA, BDTIPLAN, BDCOMPLLLA)
          VALUES
            (:PREMPRESA, :PRCODLLA, :wCodUsu, :PRCODPARTEA, :PRCODLPA, :WCODHIST, :PRCODTPHI,
             :WDATALANC, :PRVALOR12, CURRENT_DATE, CURRENT_TIME, 16, :PRCOMPL12);
        END
    END
END
^

/* Restore proc. body: VLAL_SP_RETORNA_INT_CONTABLALUR */
create or alter procedure VLAL_SP_RETORNA_INT_CONTABLALUR (
    PRCODEMP varchar(2048),
    PRMATRIZFILIAL varchar(2048),
    PRCODCONTABLALUR integer,
    PRDATAINI date,
    PRDATAFIM date,
    PRACUMULADO integer,
    PRDATALANC date,
    PRCONTAINICIAL integer,
    PRCONTAFINAL integer,
    PRTIPOLANC integer,
    PRIGNORAZERAMENTO integer,
    PRREFERENCIA integer,
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRINTCONTABILLALUR integer = 0,
    PRPERIODO integer = 1,
    PRCODPLAHISTLALUR integer = 0)
returns (
    BDCODEMP integer,
    BDREFERENCIA varchar(21),
    BDMESANO integer,
    BDDATA date,
    BDCONTA integer,
    BDNOMLPA varchar(60),
    BDVALOR numeric(15,2),
    BDTIPOLANC integer,
    BDCODTPLA integer,
    BDCHAVELAN integer)
as
declare variable WSQL varchar(10480);
declare variable WEXPORTAR integer;
declare variable WINVERTESINAL integer;
declare variable WCLASSINI varchar(50);
declare variable WCLASSFIN varchar(50);
declare variable WTOTAL integer;
declare variable WDATA_INICIAL date;
declare variable WDATA_FINAL date;
declare variable WCOUNT integer;
declare variable WANTERIOR numeric(15,2);
declare variable WDEBITO numeric(15,2);
declare variable WCREDITO numeric(15,2);
declare variable WSALDOATUAL numeric(15,2);
declare variable WMOVIMENTO numeric(15,2);
declare variable WCTALON varchar(50);
declare variable WCTALONANT varchar(50);
declare variable WTIPCTA integer;
declare variable WCODPLAPADRAO integer;
declare variable WTIPOCONTALALUR integer;
declare variable WDATINI_TRIM date;
declare variable WCODHISTLALUR integer;
BEGIN
  -- trimestral ________________________________________________________________ Carlos Machado - 06/12/2019 - #alt:126497
  IF (PRPERIODO = 0) THEN
    BEGIN
      --Calcula trimestres (mes - 1)/3 + 1 = (1..3, 4..6, 7..9, 10..12) - 1 divint 3 + 1
      wcount = (CAST(SUBSTRING(prdataini FROM 6 FOR 2) AS INTEGER) - 1) / 3 + 1;
      wtotal = (CAST(SUBSTRING(PRDATAFIM FROM 6 FOR 2) AS INTEGER) - 1) / 3 + 1;

      --Calcula quantidade de trimestres baseado no mes
      wtotal = wtotal - wcount + 1;
      --Calcula quantidade de trimestres baseado no ano (4 por ano)
      wtotal = wtotal + (CAST(SUBSTRING(PRDATAFIM FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdataini FROM 1 FOR 4) AS INTEGER)) * 4;
      WDATINI_TRIM = PRDATAINI;

      wcount = (CAST(SUBSTRING(prdataini FROM 6 FOR 2) AS INTEGER) - 1);
     --Diz qual a data inicial do trimestre
      WDATINI_TRIM = ADDMONTH(WDATINI_TRIM, - MOD(wcount, 3));
    END
  ELSE
  /* se for mensal */
  IF (pracumulado = 0) THEN
     BEGIN
       wtotal = 0;
       wdata_inicial = prdataini;
       WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatafim FROM 1 FOR 4)||SUBSTRING(prdatafim FROM 6 FOR 2) AS INTEGER)) DO
         BEGIN
           wtotal = wtotal + 1;
           wdata_inicial = addmonth(prdataini, wtotal);
         END
     END
  ELSE
  -- acumulado _____________________________________________________________________
     BEGIN
       wtotal = 1;
     END

  SELECT planos_tpla.bdctalon, planos_tpla.bdcodplapadrao FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao =  (SELECT FIRST 1 tref.bdcodplapadrao
                                       FROM tempresas_ref tref
                                       WHERE tref.bdcodemp = :prcodemp
                                       AND tref.bdrefemp <= :prreferencia
                                       ORDER BY tref.bdcodemp DESC, tref.bdrefemp DESC)
  AND planos_tpla.bdcodtpla = :prcontainicial
  INTO :wclassini, :wcodplapadrao;

  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
  AND planos_tpla.bdcodtpla = :prcontafinal
  INTO :wclassfin;

  SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
  AND SUBSTRING(planos_tpla.bdctalon FROM 1 FOR CHARACTER_LENGTH(:wclassfin)) = :wclassfin
  ORDER BY planos_tpla.bdcodplapadrao DESC, planos_tpla.bdctalon DESC
  INTO :wclassfin;

  --#Alt:100735. Melhoria de performance. Carlos Mello - 17/05/2019 - Início
  /*
  --alt:15116 - 26/08/2016 - Alterado join para corrigir erro na integração, estava trazendo Lucro Real e Presumido juntos quando há uma conta preparada com ambos mesmo que selecionado na filtragem apenas um dos dois. Pedro
  --wSql = ' select integra.bdcodtpla, planoA.BDNOMLPA, integra.BDCODLPALEST, planoReal.BDCODLPA as BDCODLPALR, integra.bdexportar, integra.bdinvertesinal ';
  wSql = ' select distinct integra.bdcodtpla, planoA.BDNOMLPA, PlanoA.BDCODLPA, PlanoPadraoA.BDTIPO, integra.bdexportar, integra.bdinvertesinal ';
  wSql = wSql || ' from VLAL_BASE_TCONTAS_CONTAB_LALUR Integra ';
  wSql = wSql || ' left outer join PLANOS_TPLA tpla on tpla.bdcodplapadrao = Integra.bdcodplapadrao and tpla.bdcodtpla = Integra.bdcodtpla ';
  wSql = wSql || ' left outer join VLAL_BASE_TCONF_CONTAB_LALUR IntegraConf on IntegraConf.BDCODCONTABLALUR = Integra.BDCODCONTABLALUR ';
  --alt:13903 - 31/03/2016 - Alterado join, um apenas para as informações da conta do lalur e outro apenas para trazer o IR e CSLL na mesma coluna (ambos são Lucro Real). Pedro
  wSql = wSql || ' left outer join VLAL_PLANOS_TLPA PlanoReal on PlanoReal.BDCODPARTEA = IntegraConf.BDCODPARTEALR and ((PlanoReal.BDCODLPA = Integra.BDCODLPALRIR) or (PlanoReal.BDCODLPA = Integra.BDCODLPALRCSLL))';
  wSql = wSql || ' join VLAL_BASE_LALUR_PARTEA PlanoPadraoA on (PlanoPadraoA.BDCODPARTEA = IntegraConf.BDCODPARTEALR) or (PlanoPadraoA.BDCODPARTEA = IntegraConf.BDCODPARTEALP) ';
  --alt:15116 - 26/08/2016 - Alterado join para corrigir erro na integração, estava trazendo Lucro Real e Presumido juntos quando há uma conta preparada com ambos mesmo que selecionado na filtragem apenas um dos dois. Pedro
  --wSql = wSql || ' join VLAL_PLANOS_TLPA PlanoA on ((PlanoA.BDCODPARTEA = IntegraConf.BDCODPARTEALR) and (PlanoA.BDCODLPA = PLANOREAL.BDCODLPA)) or ((PlanoA.BDCODPARTEA = IntegraConf.BDCODPARTEALP) and (PlanoA.BDCODLPA = Integra.BDCODLPALEST))';
  wSql = wSql || ' join VLAL_PLANOS_TLPA PlanoA on (PlanoA.BDCODPARTEA = PlanoPadraoA.BDCODPARTEA) and '||
                                                  '(((PlanoA.BDCODLPA = PlanoReal.BDCODLPA) and (PlanoPadraoA.BDTIPO = 0)) or'||
                                                  ' ((PlanoA.BDCODLPA = Integra.BDCODLPALEST) and (PlanoPadraoA.BDTIPO = 1)))';
  wSql = wSql || ' where (integra.BDCODCONTABLALUR = '||prcodcontablalur||')';
  wSql = wSql || '   and (tpla.bdctalon between '''||:wclassini||''' and  '''||:wclassfin||''')';
  wSQL = wSQL || '   and (integra.bdexportar is not null)';
  wSql = wSql || ' order by tpla.bdctalon ';
  --FOR EXECUTE STATEMENT wsql INTO :wcodtpla, :bdnomlpa, :wcodlpalest, :wcodlpalr, :wexportar, :winvertesinal DO   */
  wSql = 'Select * from (Select distinct INTEGRA.BDCODTPLA, PLANOA.BDNOMLPA, PLANOA.BDCODLPA, PLANOPADRAOA.BDTIPO, INTEGRA.BDEXPORTAR, ';
  wSql = wSql||'          INTEGRA.BDINVERTESINAL, TPLA.BDCTALON, TPLA.BDTIPCTA, PLANOA.BDTIPOCONTA ';
  wSql = wSql||', coalesce(HISTCONTABLALUR.BDCODTPHI,0) as BDCODTPHI ';

  wSql = wSql||'from ( ';
  wSql = wSql||'        Select INTEGRA.BDCODTPLA, INTEGRA.BDEXPORTAR, INTEGRA.BDINVERTESINAL, INTEGRA.BDCODPLAPADRAO, INTEGRA.BDCODCONTABLALUR, ';
  wSql = wSql||'               INTEGRA.BDCODLPALRIR, INTEGRA.BDCODLPALRCSLL, INTEGRA.BDCODLPALEST ';
  wSql = wSql||'        from VLAL_BASE_TCONTAS_CONTAB_LALUR INTEGRA ';
  wSql = wSql||'        where ';
  wSql = wSql||'        (INTEGRA.BDCODCONTABLALUR = '||prcodcontablalur||') and ';
  wSql = wSql||'        (INTEGRA.BDEXPORTAR is not null) ';
  wSql = wSql||'     ) INTEGRA ';
  wSql = wSql||'left outer join PLANOS_TPLA TPLA on TPLA.BDCODPLAPADRAO = INTEGRA.BDCODPLAPADRAO and TPLA.BDCODTPLA = INTEGRA.BDCODTPLA ';
  wSql = wSql||'left outer join VLAL_BASE_TCONTAS_CONTAB_HIST_LALUR HISTCONTABLALUR on (HISTCONTABLALUR.BDCODCONTABLALUR = INTEGRA.BDCODCONTABLALUR and ';
  wSql = wSql||'HISTCONTABLALUR.BDCODPLAPADRAO = INTEGRA.BDCODPLAPADRAO and ';
  wSql = wSql||'HISTCONTABLALUR.BDCODTPLA = INTEGRA.BDCODTPLA) and ';
  wSql = wSql||'HISTCONTABLALUR.BDCODHIST = '||coalesce(prcodplahistlalur,0)||' ';
  wSql = wSql||'left outer join VLAL_BASE_TCONF_CONTAB_LALUR INTEGRACONF on INTEGRACONF.BDCODCONTABLALUR = INTEGRA.BDCODCONTABLALUR ';
  wSql = wSql||'left outer join VLAL_PLANOS_TLPA PLANOREAL on PLANOREAL.BDCODPARTEA = INTEGRACONF.BDCODPARTEALR and ((PLANOREAL.BDCODLPA = INTEGRA.BDCODLPALRIR) or (PLANOREAL.BDCODLPA = INTEGRA.BDCODLPALRCSLL)) ';
  wSql = wSql||'join VLAL_BASE_LALUR_PARTEA PLANOPADRAOA on (PLANOPADRAOA.BDCODPARTEA = INTEGRACONF.BDCODPARTEALR) or (PLANOPADRAOA.BDCODPARTEA = INTEGRACONF.BDCODPARTEALP) ';
  wSql = wSql||'join VLAL_PLANOS_TLPA PLANOA on (PLANOA.BDCODPARTEA = PLANOPADRAOA.BDCODPARTEA) and (((PLANOA.BDCODLPA = PLANOREAL.BDCODLPA) and (PLANOPADRAOA.BDTIPO = 0)) or ((PLANOA.BDCODLPA = INTEGRA.BDCODLPALEST) and (PLANOPADRAOA.BDTIPO = 1))) ';
  wSql = wSql||'where ';
  wSql = wSql||'(TPLA.BDCTALON between '''||:wclassini||''' and  '''||:wclassfin||''') ';
  wSql = wSql||'order by TPLA.BDCTALON)';

  wSql = wSql||'UNION';
  wSql = wSql||' SELECT * FROM (select distinct MULT.BDCODTPLA, PLANOA.BDNOMLPA, PLANOA.BDCODLPA, PLANOPADRAOA.BDTIPO, MULT.BDEXPORTAR,';
  wSql = wSql||'               MULT.BDINVERTER, TPLA.BDCTALON, TPLA.BDTIPCTA, PLANOA.BDTIPOCONTA,';
  wSql = wSql||'                 coalesce(HIST.BDCODTPHI, 0) as BDCODTPHI';
  wSql = wSql||' from (select MULT.BDCODTPLA, MULT.BDEXPORTAR, MULT.BDINVERTER, MULT.BDCODPLAPADRAO, MULT.BDCODCONTABLALUR,';
  wSql = wSql||'              MULT.BDCTAIRA, MULT.BDCTACSLLA, MULT.BDCTAESTIMATIVA';
  wSql = wSql||'       from VLAL_EMPRESAS_PREP_CONT MULT';
  wSql = wSql||'       where (MULT.BDCODCONTABLALUR = '||prcodcontablalur||') and';
  wSql = wSql||'             (MULT.BDEXPORTAR is not null)) MULT';
  wSql = wSql||' left join PLANOS_TPLA TPLA on TPLA.BDCODPLAPADRAO = MULT.BDCODPLAPADRAO and';
  wSql = wSql||'       TPLA.BDCODTPLA = MULT.BDCODTPLA';
  wSql = wSql||' left join VLAL_EMPRESAS_PREP_CONT_HIST HIST on (HIST.BDCODCONTABLALUR = MULT.BDCODCONTABLALUR and';
  wSql = wSql||'             HIST.BDCODPLAPADRAO = MULT.BDCODPLAPADRAO and';
  wSql = wSql||'             HIST.BDCODTPLA = MULT.BDCODTPLA) and';
  wSql = wSql||'             HIST.BDCODHIST = '||coalesce(prcodplahistlalur,0)||' ';
  wSql = wSql||' left join VLAL_BASE_TCONF_CONTAB_LALUR INTEGRACONF on INTEGRACONF.BDCODCONTABLALUR = MULT.BDCODCONTABLALUR';
  wSql = wSql||' left join VLAL_PLANOS_TLPA PLANOREAL on PLANOREAL.BDCODPARTEA = INTEGRACONF.BDCODPARTEALR and';
  wSql = wSql||'       ((PLANOREAL.BDCODLPA = MULT.bdctaira) or (PLANOREAL.BDCODLPA = MULT.bdctacslla))';
  wSql = wSql||' join VLAL_BASE_LALUR_PARTEA PLANOPADRAOA on (PLANOPADRAOA.BDCODPARTEA = INTEGRACONF.BDCODPARTEALR) or (PLANOPADRAOA.BDCODPARTEA = INTEGRACONF.BDCODPARTEALP)';
  wSql = wSql||' join VLAL_PLANOS_TLPA PLANOA on (PLANOA.BDCODPARTEA = PLANOPADRAOA.BDCODPARTEA) and';
  wSql = wSql||'       (((PLANOA.BDCODLPA = PLANOREAL.BDCODLPA) and';
  wSql = wSql||'       (PLANOPADRAOA.BDTIPO = 0)) or ((PLANOA.BDCODLPA = MULT.bdctaestimativa) and';
  wSql = wSql||'       (PLANOPADRAOA.BDTIPO = 1)))';
  wSql = wSql||' where (TPLA.BDCTALON between '''||:wclassini||''' and '''||:wclassfin||''')';
  wSql = wSql||' order by TPLA.BDCTALON)';



  --#Alt:100735. Melhoria de performance. Carlos Mello - 17/05/2019 - Fim

  WCTALONANT = '';
  FOR EXECUTE STATEMENT wSQL INTO :BDCODTPLA, :BDNOMLPA, :BDCONTA, :BDTIPOLANC, :WEXPORTAR, :WINVERTESINAL, :WCTALON, :WTIPCTA, :WTIPOCONTALALUR, :wcodhistlalur DO
    BEGIN
      if ((WTIPOCONTALALUR is null or WTIPOCONTALALUR = 0) and (PRINTCONTABILLALUR = 1)) then
        continue; --Esses caras não vão pra ECF, com isso não são necessarios no vinculo com o lalur, isso faz com que o processo fique mais rapido -#223816 2025 Machado
      --#Alt:100735. Melhoria de performance. Carlos Mello - 20/05/2019
      if ((WCTALONANT <> WCTALON) and (WTIPCTA = 0)) then -- Conta título
         begin
           EXECUTE STATEMENT ' delete from VSUC_SELECT_CONTAS ';
    
           EXECUTE STATEMENT ' insert into VSUC_SELECT_CONTAS (BDCODPLAPADRAO, BDCODTPLA) '||
                             ' select BDCODPLAPADRAO, BDCODTPLA from PLANOS_TPLA where BDCTALON like '''||:WCTALON||'%''  and BDCODPLAPADRAO = '||:WCODPLAPADRAO||' and BDTIPCTA = 1';
         end

      wcount = 1;
      WHILE (wcount -1 < wtotal) DO
        BEGIN
          -- trimestral ____________________________________________________ Carlos Machado - 06/12/2019 - #alt:126497
          IF (PRPERIODO = 0) THEN
            BEGIN
              wdata_inicial = addmonth(WDATINI_TRIM, (wcount - 1) * 3);
              if (PRDATAINI > WDATA_INICIAL) then
                WDATA_INICIAL = PRDATAINI;
              wdata_final   = addmonth(WDATINI_TRIM, (wcount - 1) * 3 + 3) - 1;
              if (PRDATAFIM < WDATA_FINAL) then
                WDATA_FINAL = PRDATAFIM;
            END
          ELSE
          -- Mensal ________________________________________________________
          IF (pracumulado = 0) THEN
            BEGIN
              wdata_inicial = addmonth(prdataini, wcount-1);
              wdata_final   = addmonth(prdataini, wcount)-1;
            END
          ELSE
            BEGIN
              wdata_inicial = prdataini;
              wdata_final   = prdatafim;
            END

          bdvalor = 0;
          --alt:11995 - 12/08/2015 - Adicionados novos parâmetros e variáveis de retorno (CHAVELAN e CODEMP). Pedro
          FOR SELECT SUM(SALDO_ANTERIOR), SUM(SALDO_DEB), SUM(SALDO_CRE), SUM(SALDO_ATUAL),
              CASE WHEN (:printcontabillalur = 1) THEN CHAVELAN ELSE NULL END AS CHAVELAN,
              CASE WHEN (:printcontabillalur = 1) THEN CODEMP ELSE NULL END AS CODEMP
              FROM SP_RETORNA_SALDO_MATRIZFILIAL_X(:prcodemp, :prmatrizfilial, :BDCODTPLA, :wdata_inicial, :wdata_final, :prignorazeramento,NULL,NULL,
                                                   :prreferencia, 0, :prcontabilizacao, :prmatrizfilialconsolidado, :prIntContabilLalur,0,1,:wcodhistlalur) tsal
              GROUP BY CHAVELAN, CODEMP
              INTO :wanterior, :wdebito, :wcredito, :wsaldoatual, :BDCHAVELAN, :BDCODEMP DO
           BEGIN
             wmovimento = :wsaldoatual - :wanterior;

             --alt:15116 - 26/08/2016 - Alterado método de tratamento dos dados. Mais simples e corrigindo erro de estar integrando Lucro
             --Real e Presumido juntos quando há uma conta preparada com ambos mesmo que selecionado na filtragem apenas um dos dois. Pedro
             BDDATA = CASE WHEN prAcumulado = 0 THEN wData_Final ELSE prDataLanc END;
             --Carlos Machado - 06/12/2019 - #alt:126497
             IF (PRPERIODO = 0) THEN
              begin
                 BDREFERENCIA = SUBSTRING(CAST(WDATA_INICIAL AS VARCHAR(10)) FROM 6 FOR 2)||'/'||SUBSTRING(CAST(WDATA_INICIAL AS VARCHAR(10)) FROM 1 FOR 4)
                       ||' - '||SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 6 FOR 2)||'/'||SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 1 FOR 4);
              end
             else
              begin
                 BDREFERENCIA = SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
                  SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 1 FOR 4);
              end
             BDMESANO = SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(wdata_final AS VARCHAR(10)) FROM 6 FOR 2);

             IF (wexportar = 0) THEN
                bdvalor = wmovimento;
             ELSE
             IF (wexportar = 1) THEN
                bdvalor = wdebito;
             ELSE
             IF (wexportar = 2) THEN
                bdvalor = wcredito;
             ELSE
             IF (wexportar = 3) THEN
                bdvalor = wsaldoatual;
             ELSE
             IF (wexportar = 4) THEN
                bdvalor = wanterior;

             IF (winvertesinal = 0) THEN
                bdvalor = bdvalor * -1;

             --alt:18994 - 07/06/2017 - Se for integração do Lalur, também deve retornar o registro, porque sempre terá o valor zerado. Pedro
             --alt:15116 - 26/08/2016 - Adicionado filtro para a forma de apuração do lucro. Pedro
             --alt:13903 - 31/03/2016 - Só deve integrar se tiver algum valor. Pedro
             IF (((prIntContabilLalur = 1) OR (BDVALOR <> 0)) AND ((BDTIPOLANC = prTipoLanc) OR (prTipoLanc = 2))) THEN
               SUSPEND;
           END

          wcount = wcount + 1;
        END

      WCTALONANT = WCTALON;
    END

  --#Alt:100735. Melhoria de performance. Carlos Mello - 20/05/2019
  EXECUTE STATEMENT ' delete from VSUC_SELECT_CONTAS ';
END
^

create or alter procedure VLAL_SP_DEMONSTRACAO_PARTEB (
    PRCODEMP integer,
    PRDATAINICIALREL date,
    PRDATAINICIAL date,
    PRDATAFINAL date,
    PRMODELOREL integer,
    PRREFERENCIA integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODLLB integer,
    BDCODPARTEB integer,
    BDNOMPARTEB varchar(40),
    BDINDICE integer,
    BDDEBCODLPB integer,
    BDCTALONLPBDEB varchar(20),
    BDNOMLPBDEB varchar(60),
    BDDEBVALLLB numeric(15,2),
    BDCRECODPLB integer,
    BDCTALONLPBCRE varchar(20),
    BDNOMLPBCRE varchar(60),
    BDCREVALLLB numeric(15,2),
    BDCODLPB integer,
    BDCTALONLPB varchar(20),
    BDNOMLPB varchar(60),
    BDDATLLB date,
    BDVALLLB numeric(15,2),
    BDSALANT numeric(15,2),
    BDSALATU numeric(15,2),
    BDCOMPLLLB varchar(200),
    BDCOMPENSACAO DM_BOOLEAN,
    BDMODELO varchar(10))
as
declare variable WSQL varchar(10000);
declare variable WSALDOANTERIOR numeric(15,2);
declare variable WCONTAANTERIOR integer;
declare variable WDATAANTERIOR date;
declare variable WMODELO varchar(10);
declare variable WMODELOANT varchar(10);
declare variable WCODEMP integer;
declare variable WNOMEMP DM_BDNOMEMP;
declare variable WCODLLB integer;
declare variable WCODPARTEB integer;
declare variable WNOMPARTEB varchar(40);
declare variable WINDICE integer;
declare variable WDEBCODLPB integer;
declare variable WCTALONLPBDEB varchar(20);
declare variable WNOMLPBDEB varchar(60);
declare variable WDEBVALLLB numeric(15,2);
declare variable WCRECODPLB integer;
declare variable WCTALONLPBCRE varchar(20);
declare variable WNOMLPBCRE varchar(60);
declare variable WCREVALLLB numeric(15,2);
declare variable WCODLPB integer;
declare variable WCTALONLPB varchar(20);
declare variable WNOMLPB varchar(60);
declare variable WDATLLB date;
declare variable WVALLLB numeric(15,2);
declare variable WSALANT numeric(15,2);
declare variable WSALATU numeric(15,2);
declare variable WCOMPLLLB varchar(200);
declare variable WDATASALANT date;
declare variable WSUSPEND integer;
declare variable WDATAANTANT date;
BEGIN
  wcontaanterior = 0;
  WSUSPEND = 1;
  wdataanterior  = '01/01/1700';
  WDATAANTANT    = '01/01/1700';

  --Os valores necessários para fazer a compensação mês a mês já ficam lançados na parte A
  wsql = ' select * from (select distinct TLAN.BDCODEMP, TREF.BDNOMEMP, TLAN.BDCODLLB, TLAN.BDCODPARTEB, TLPB.BDNOMPARTEB, TLAN.BDINDICE, ';
  wsql = wsql || '                        TLAN.BDDEBCODLPB, TDEBPB.BDCTALONLPB "bdctalonlpbdeb", TDEBPB.BDNOMLPB "bdnomlpbdeb", ';
  wsql = wsql || '                        case ';
  wsql = wsql || '                          when (TLAN.BDDEBCODLPB is null) then null ';
  wsql = wsql || '                          when (TLAN.BDDEBCODLPB is not null) then TLAN.BDVALLLB ';
  wsql = wsql || '                        end "bddebvalllb", ';
  wsql = wsql || '                        TLAN.BDCRECODPLB, TCREPB.BDCTALONLPB "bdctalonlpbcre", TCREPB.BDNOMLPB "bdnomlpbcre", ';
  wsql = wsql || '                        case ';
  wsql = wsql || '                          when (TLAN.BDCRECODPLB is null) then null ';
  wsql = wsql || '                          when (TLAN.BDCRECODPLB is not null) then TLAN.BDVALLLB ';
  wsql = wsql || '                        end "bdcrevalllb", ';
  wsql = wsql || '                        case ';
  wsql = wsql || '                          when (TLAN.BDDEBCODLPB is null) then TLAN.BDCRECODPLB ';
  wsql = wsql || '                          when (TLAN.BDCRECODPLB is null) then TLAN.BDDEBCODLPB ';
  wsql = wsql || '                        end "bdcodlpb", ';
  wsql = wsql || '                        case ';
  wsql = wsql || '                          when (TLAN.BDDEBCODLPB is null) then TCREPB.BDCTALONLPB ';
  wsql = wsql || '                          when (TLAN.BDCRECODPLB is null) then TDEBPB.BDCTALONLPB ';
  wsql = wsql || '                        end BDCTALONLPB, ';
  wsql = wsql || '                        case ';
  wsql = wsql || '                          when (TLAN.BDDEBCODLPB is null) then TCREPB.BDNOMLPB ';
  wsql = wsql || '                          when (TLAN.BDCRECODPLB is null) then TDEBPB.BDNOMLPB ';
  wsql = wsql || '                        end "bdnomlpb", ';
  wsql = wsql || '                        TLAN.BDDATLLB, ';
  wsql = wsql || '                        case ';
  wsql = wsql || '                          when (TLAN.BDDEBCODLPB is null) then TLAN.BDVALLLB * -1 ';
  wsql = wsql || '                          when (TLAN.BDCRECODPLB is null) then TLAN.BDVALLLB ';
  wsql = wsql || '                        end "bdvalllb", ';
  wsql = wsql || '                        TLAN.BDVALLLB BDSALANT, TLAN.BDVALLLB BDSALATU, TLAN.BDCOMPLLLB, ''PARTEA'' as BDMODELO';
  wsql = wsql || '        from VLAL_EMPRESAS_TLLB TLAN ';
  wsql = wsql || '        inner join TEMPRESAS TEMP on (TEMP.BDCODEMP = TLAN.BDCODEMP) ';
  wsql = wsql || '        left outer join TEMPRESAS_REF TREF on (TREF.BDCODEMP = TEMP.BDCODEMP and TREF.BDREFEMP = (select first 1 TER.BDREFEMP ';
  wsql = wsql || '                                                                                                  from TEMPRESAS_REF TER ';
  wsql = wsql || '                                                                                                  where TER.BDCODEMP = TEMP.BDCODEMP and ';
  wsql = wsql || '                                                                                                        TER.BDREFEMP <= '||prreferencia;
  wsql = wsql || '                                                                                                  order by TER.BDREFEMP desc)) ';
  wsql = wsql || '        inner join VLAL_BASE_LALUR_PARTEB TLPB on (TLPB.BDCODPARTEB = TLAN.BDCODPARTEB) ';
  wsql = wsql || '        inner join VLAL_BASE_TEMP TEMPL on (TEMPL.BDCODEMP = TEMP.BDCODEMP and TEMPL.BDCODPARTEB = TLAN.BDCODPARTEB) ';
  wsql = wsql || '        left outer join VLAL_PLANOS_TLPB TDEBPB on (TDEBPB.BDCODPARTEB = TLAN.BDCODPARTEB and TDEBPB.BDCODLPB = TLAN.BDDEBCODLPB) ';
  wsql = wsql || '        left outer join VLAL_PLANOS_TLPB TCREPB on (TCREPB.BDCODPARTEB = TLAN.BDCODPARTEB and TCREPB.BDCODLPB = TLAN.BDCRECODPLB) ';
  wsql = wsql || '        where TLAN.BDCODEMP = '||prcodemp||' and ';
  wsql = wsql || '              TLAN.BDDATLLB between '''||prdatainicialrel||''' and '''||prdatafinal||'''';
  wsql = wsql || '        union all ';
  wsql = wsql || '        select distinct TLAN.BDCODEMP, TREF.BDNOMEMP, TLAN.BDCODLPB as BDCODLLB, TEMPL.BDCODPARTEB, TLPB.BDNOMPARTEB, ';
  wsql = wsql || '                        null as BDINDICE, TLAN.BDCODLPB as BDDEBCODLPB, TDEBPB.BDCTALONLPB "bdctalonlpbdeb", ';
  wsql = wsql || '                        TDEBPB.BDHISTDEBLPB "bdnomlpbdeb", TLAN.BDVALLLA "bddebvalllb", null as BDCRECODPLB, ';
  wsql = wsql || '                        null "bdctalonlpbcre", null "bdnomlpbcre", null "bdcrevalllb", TLAN.BDCODLPB "bdcodlpb", ';
  wsql = wsql || '                        TDEBPB.BDCTALONLPB, TDEBPB.BDNOMLPB "bdnomlpb", TLAN.BDDATLLA as BDDATLLB, ';
  wsql = wsql || '                        TLAN.BDVALLLA "bdvalllb", TLAN.BDVALLLA BDSALANT, TLAN.BDVALLLA BDSALATU, ';
  wsql = wsql || '                        null as BDCOMPLLLB, ''PARTEB'' as BDMODELO';
  wsql = wsql || '        from VLAL_EMPRESAS_TLLA TLAN ';
  wsql = wsql || '        inner join TEMPRESAS TEMP on (TEMP.BDCODEMP = TLAN.BDCODEMP) ';
  wsql = wsql || '        left outer join TEMPRESAS_REF TREF on (TREF.BDCODEMP = TEMP.BDCODEMP and TREF.BDREFEMP = (select first 1 TER.BDREFEMP ';
  wsql = wsql || '                                                                                                  from TEMPRESAS_REF TER ';
  wsql = wsql || '                                                                                                  where TER.BDCODEMP = TEMP.BDCODEMP and ';
  wsql = wsql || '                                                                                                        TER.BDREFEMP <= '||prreferencia;
  wsql = wsql || '                                                                                                  order by TER.BDREFEMP desc)) ';
  wsql = wsql || '        inner join VLAL_BASE_TEMP TEMPL on (TEMPL.BDCODEMP = TEMP.BDCODEMP and TEMPL.BDREFEMP = TREF.BDREFEMP) ';
  wsql = wsql || '        inner join VLAL_BASE_LALUR_PARTEB TLPB on (TLPB.BDCODPARTEB = TEMPL.BDCODPARTEB) ';
  wsql = wsql || '        left outer join VLAL_PLANOS_TLPB TDEBPB on (TDEBPB.BDCODPARTEB = TEMPL.BDCODPARTEB and TDEBPB.BDCODLPB = TLAN.BDCODLPB) ';
  wsql = wsql || '        where TLAN.BDCODEMP = '||prcodemp||' and ';
  wsql = wsql || '              TLAN.BDDATLLA between '''||prdatainicialrel||''' and '''||prdatafinal||''' and ';
  wsql = wsql || '              TLAN.BDTIPLAN = 20 /*lançamento automático*/ and ';
  wsql = wsql || '              TLAN.BDTIPORELACIONAMENTO = 1 /*lançamento com conta da parte B*/) ';
  wsql = wsql || '  order by BDCTALONLPB, BDDATLLB, BDCODLLB      ';

  FOR EXECUTE STATEMENT wsql
  INTO :wcodemp, :wnomemp, :wcodllb, :wcodparteb, :wnomparteb, :windice, :wdebcodlpb, :wctalonlpbdeb,
       :wnomlpbdeb, :wdebvalllb, :wcrecodplb, :wctalonlpbcre, :wnomlpbcre, :wcrevalllb, :wcodlpb,
       :wctalonlpb, :wnomlpb, :wdatllb, :wvalllb, :wsalant, :wsalatu, :wcomplllb, :wmodelo DO
  BEGIN
    IF (wcontaanterior <> wcodlpb) THEN
      BEGIN
        wcontaanterior = wcodlpb;
        wmodeloant     = '';

        IF (wmodelo = 'PARTEA') THEN
          wdatasalant = wdatllb;
        ELSE
          wdatasalant = prdatafinal;

        SELECT SUM(CASE
                   WHEN (tlan.bddebcodlpb = :wcodlpb) THEN
                        tlan.bdvalllb
                   WHEN (tlan.bdcrecodplb = :wcodlpb) THEN
                        tlan.bdvalllb * -1
                   END) bdvalor
        FROM VLAL_EMPRESAS_TLLB tlan
        WHERE tlan.bdcodemp = :wcodemp
        AND tlan.bddatllb < '01/01/'||EXTRACT(YEAR FROM :wdatasalant)
        INTO :wsaldoanterior;

        IF (wsaldoanterior IS NULL) THEN
          wsaldoanterior = 0;
       END
    ELSE
    IF (((bdmodelo = 'PARTEA') OR (wmodelo = 'PARTEA')) AND ((wmodeloant = 'PARTEA') OR (wmodeloant = '')))  THEN
      wsaldoanterior = bdsalatu;

    --NÃO deve mostrar os lançamentos que sejam da parte A, anteriores a data do relatório e que as contas sejam de compensação
    --NÃO deve mostrar quando for o mês de dezembro e for a conta de compensação, pois ele duplica estes valores
    --NÃO deve detalhar a ultima PARTE B, já que tem um lançamento exatamente igual na parte A #125825 - Carlos Machado
    IF ((NOT ((wmodelo = 'PARTEB') AND (bdmodelo = 'PARTEA') AND (EXTRACT(YEAR FROM :bddatllb) < EXTRACT(YEAR FROM :prdatafinal)))) AND (bdmodelo IS NOT NULL) AND
        (NOT ((bdmodelo = 'PARTEB') AND (EXTRACT(MONTH FROM :bddatllb) = 12) AND (EXTRACT(DAY FROM :bddatllb) <> 1))) AND WSUSPEND = 1) THEN
      SUSPEND;
    if (WSUSPEND = 0) then
      WSUSPEND = 1;
    IF (NOT (WCODLPB is null or (WCODLPB <> BDCODLPB) or (WVALLLB <> BDVALLLB) or (WDATLLB <> BDDATLLB) or (bdmodelo = WMODELO))) THEN
      WSUSPEND = 0;

    bdcompensacao = 'FALSE';
    bdcodemp = wcodemp;
    bdnomemp = wnomemp;
    bdcodllb = wcodllb;
    bdcodparteb = wcodparteb;
    bdnomparteb = wnomparteb;
    bdindice = windice;
    bddebcodlpb = wdebcodlpb;
    bdctalonlpbdeb = wctalonlpbdeb;
    bdnomlpbdeb = wnomlpbdeb;
    bddebvalllb = wdebvalllb;
    bdcrecodplb = wcrecodplb;
    bdctalonlpbcre = wctalonlpbcre;
    bdnomlpbcre = wnomlpbcre;
    bdcrevalllb = wcrevalllb;
    bdcodlpb = wcodlpb;
    bdctalonlpb = wctalonlpb;
    bdnomlpb = wnomlpb;
    bddatllb = wdatllb;
    bdvalllb = wvalllb;
    bdsalant = wsalant;
    bdsalatu = wsalatu;
    bdcomplllb = wcomplllb;
    bdmodelo = wmodelo;

    IF ((wmodelo = 'PARTEB') OR (wmodeloant = 'PARTEB')) THEN
      bdcompensacao = 'TRUE';

    bdsalant   = wsaldoanterior;
    bdsalatu   = wsaldoanterior + bdvalllb;
        wmodeloant = wmodelo;

    IF (bdcomplllb IS NULL) THEN
      bdcomplllb = REPLACE(bdnomlpbdeb, '#2', LPAD(EXTRACT(MONTH FROM :bddatllb), 2, '0')||'/'||EXTRACT(YEAR FROM :bddatllb));

        --Tratamento para não mostrar lançamentos de compensação que já foram efetivamente lançados na Parte B
      IF (((wdataanterior <> bddatllb AND WSUSPEND = 1) or (WDATAANTANT <> BDDATLLB AND WSUSPEND = 0)) OR (wmodelo = 'PARTEA')) THEN
      BEGIN
          WDATAANTANT = wdataanterior;
          wdataanterior = bddatllb;
        --**ESTORNO**
            IF ((prmodelorel = 2) AND (EXTRACT(MONTH FROM :bddatllb) <> 12) AND (wmodelo = 'PARTEB')) THEN
          BEGIN
            if (WSUSPEND = 1) then
              SUSPEND;   
            if (WSUSPEND = 0) then
              WSUSPEND = 1;

            bdsalant = bdsalatu;
            bdsalatu = bdsalant + (bdvalllb* -1);

            IF (bddebvalllb IS NULL) THEN
              BEGIN
                bddebvalllb    = bdcrevalllb;
                bdcrevalllb    = NULL;
              END
            ELSE
              BEGIN
                bdcrevalllb    = bddebvalllb;
                bddebvalllb    = NULL;
              END

            bdcomplllb = 'ESTORNO COMP PREJU REF '|| LPAD(EXTRACT(MONTH FROM :bddatllb), 2, '0')||'/'||EXTRACT(YEAR FROM :bddatllb);
            bddatllb   = addday(bddatllb, 1);
          END
      END
  END
  if (WSUSPEND = 1 AND BDMODELO IS NOT NULL) then
    SUSPEND;
END
^

/* Restore proc. body: VRH_COPIA_FUNCOES_PLANO */
ALTER PROCEDURE VRH_COPIA_FUNCOES_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
DECLARE VARIABLE WCODPLAFUC INTEGER;
DECLARE VARIABLE WCODTFUC INTEGER;
DECLARE VARIABLE WCODCBO INTEGER;
DECLARE VARIABLE WDESCTFUC VARCHAR(40);
BEGIN
  DELETE FROM vrh_funcoes_tfuc WHERE bdCODPLAFUC = :codigonovo;

  IF (:codigonovo IS NULL OR (:codigonovo = 0)) THEN
     SELECT COALESCE(MAX(BDCODPLAFUC), 1) FROM vrh_base_tfuncoes INTO :wcodplafuc;
  ELSE
     wcodplafuc = :codigonovo;

  FOR SELECT BDCODTFUC,BDCODCBO,BDDESCTFUC FROM vrh_funcoes_tfuc
             WHERE bdCODPLAFUC = :codigocopiar INTO
             :wcodtfuc,:wcodcbo,:wdesctfuc DO
     BEGIN
        UPDATE OR INSERT INTO vrh_funcoes_tfuc(bdCODPLAFUC,bdCODTFUC,bdCODCBO,bdDESCTFUC) VALUES
                                              (:wcodplafuc,:wcodtfuc,:wcodcbo,:wdesctfuc) MATCHING (bdCODPLAFUC,bdCODTFUC);
     END
END
^

/* Restore proc. body: VRH_COPIA_LAYOUT_PLALANC */
CREATE OR ALTER PROCEDURE VRH_COPIA_LAYOUT_PLALANC (
    CODIGONOVO INTEGER,
    CODIGOCOPIAR INTEGER)
AS
DECLARE VARIABLE WCODVER INTEGER;
DECLARE VARIABLE WDESCCOL VARCHAR(20);
BEGIN
  IF ((codigonovo IS NULL) OR (codigonovo = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(BDCODPLPL), 1) FROM VRH_BASE_TPLANO_LPL INTO :codigonovo;
    END

  DELETE FROM VRH_BASE_TPLANO_LPL_ITEM WHERE BDCODPLPL = :codigonovo;

  FOR SELECT BDCODVER,BDDESCCOL FROM VRH_BASE_TPLANO_LPL_ITEM WHERE BDCODPLPL = :codigocopiar INTO :wcodver, :wdesccol DO
    BEGIN
      INSERT INTO VRH_BASE_TPLANO_LPL_ITEM (BDCODPLPL,BDCODVER,BDDESCCOL) VALUES (:codigonovo,:wcodver,:wdesccol);
    END

END
^

/* Restore proc. body: VRH_COPIA_VERBASBS_PLANO */
ALTER PROCEDURE VRH_COPIA_VERBASBS_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
DECLARE VARIABLE WCODPLABS INTEGER;
DECLARE VARIABLE WCODVERBS INTEGER;
DECLARE VARIABLE WDESCVERBS VARCHAR(50);
DECLARE VARIABLE WTIPOVERBS INTEGER;
DECLARE VARIABLE WFGTSFNBS DM_BOOLEAN;
DECLARE VARIABLE WFGTSFEBS DM_BOOLEAN;
DECLARE VARIABLE WFGTS13BS DM_BOOLEAN;
DECLARE VARIABLE WCODIGOBS INTEGER;
DECLARE VARIABLE WCODVER INTEGER;
BEGIN
  DELETE FROM VRH_BASE_TVERBASBLUESOFT WHERE bdCODPLABS = :codigonovo;

  IF (:codigonovo IS NULL OR (:codigonovo = 0)) THEN
     SELECT COALESCE(MAX(BDCODPLABS), 1) FROM VRH_BASE_TPLANOBLUESOFT INTO :wcodplabs;
  ELSE
     wcodplabs = :codigonovo;

  FOR SELECT BDCODVERBS, BDDESCVERBS, BDTIPOVERBS, BDFGTSFNBS, BDFGTSFEBD, BDFGTS13BS, BDCODIGOBS FROM VRH_BASE_TVERBASBLUESOFT WHERE BDCODPLABS = :codigocopiar
       INTO :wcodverbs, :wdescverbs, :wtipoverbs, :wfgtsfnbs, :wfgtsfebs, :wfgts13bs, :wcodigobs DO
    BEGIN
      UPDATE OR INSERT INTO VRH_BASE_TVERBASBLUESOFT (BDCODPLABS, BDCODVERBS, BDDESCVERBS, BDTIPOVERBS, BDFGTSFNBS, BDFGTSFEBD, BDFGTS13BS, BDCODIGOBS) VALUES
                                                     (:wcodplabs, :wcodverbs, :wdescverbs, :wtipoverbs, :wfgtsfnbs, :wfgtsfebs, :wfgts13bs, :wcodigobs) MATCHING (BDCODPLABS, BDCODVERBS);


      FOR SELECT BDCODVER FROM VRH_BASE_TITENSBLUESOFT WHERE BDCODPLABS = :codigocopiar AND BDCODVERBS = :wcodverbs
           INTO :wcodver DO
        BEGIN
          UPDATE OR INSERT INTO VRH_BASE_TITENSBLUESOFT (BDCODPLABS, BDCODVERBS, BDCODVER) VALUES
                                                         (:wcodplabs, :wcodverbs, :wcodver) MATCHING (BDCODPLABS, BDCODVERBS, BDCODVER);
        END
    END
END
^

/* Restore proc. body: VRH_INS_VERBA */
CREATE OR ALTER PROCEDURE VRH_INS_VERBA (
    PRCLASS VARCHAR(9))
RETURNS (
    VERBATITULO INTEGER,
    NOVAVERBA INTEGER,
    NOVACLASS VARCHAR(20))
AS
DECLARE VARIABLE WAUX INTEGER;
DECLARE VARIABLE WEXISTEVERBA INTEGER;
DECLARE VARIABLE WCONTA INTEGER;
BEGIN
  IF (CHAR_LENGTH(:PRCLASS) < 9) THEN
     BEGIN
       SELECT FIRST 1 BDCLAVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER STARTING WITH :prclass AND CHAR_LENGTH(BDCLAVER) = 9 INTO :prclass;
     END

  SELECT BDCODVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = :PRCLASS INTO :verbatitulo;
  novaverba = verbatitulo + 1;

  WHILE (novaverba < 1000000) DO
    BEGIN

      wexisteverba = 0;
      FOR SELECT BDCODVER FROM VRH_BASE_TVERBAS WHERE BDCODVER = :novaverba INTO :wconta DO
        BEGIN
          wexisteverba = 1;
        END

      IF (wexisteverba = 0) THEN
         BEGIN
           BREAK;
         END

      novaverba = novaverba +1;
    END

  wconta = 1;
  WHILE (wconta < 1000000) DO
    BEGIN

      SELECT str FROM strzero(:wconta,3) INTO :novaclass;

      novaclass = prclass || '.' || novaclass;

      wexisteverba = 0;
      FOR SELECT BDCODVER FROM VRH_BASE_TVERBAS WHERE BDCLAVER = :novaclass INTO :waux DO
        BEGIN
          wexisteverba = 1;
        END

      IF (wexisteverba = 0) THEN
         BEGIN
           BREAK;
         END

      wconta = wconta +1;

    END

  SUSPEND;

END
^

/* Restore proc. body: VRH_SP_ADMITIDOS_NO_MES */
ALTER PROCEDURE VRH_SP_ADMITIDOS_NO_MES(PRCODEMP VARCHAR(15000),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDADMITIDOS INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
  wsql = 'select X.BDCODEMP, Count(X.BDCODCOL) '||
         'from vrh_emp_tcolcon X ';

  wsql = wsql||'join vw_vrh_emp_tcolcon_vinc colcon_vinc on (colcon_vinc.bdcodemp = X.bdcodemp and colcon_vinc.bdcodcol = X.bdcodcol) ';
  wsql = wsql||'join vrh_base_tclasse classe on (colcon_vinc.bdcodcla = classe.bdcodcla and classe.bdgrupocla <> 5) ';

  wwhere = 'where X.BDCONTRCOL <> 1 and '||
           'CAST((SUBSTRING( CAST(X.BDDATAADMCOL as VARCHAR(10)) from 1 for 4)||SUBSTRING( CAST(X.BDDATAADMCOL as VARCHAR(10)) from 6 for 2)) As INTEGER) = '||pranomes||' ';



  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and ('||prcodemp||') ';

  wsql = wsql||wwhere;
  wsql = wsql||'group by X.bdcodemp ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDADMITIDOS
  DO

  SUSPEND;
END
^

/* Restore proc. body: VRH_SP_ALTERACAOSALARIAL */
create or alter procedure VRH_SP_ALTERACAOSALARIAL (
    PREMPRESA varchar(15000),
    PRCOLABORADOR varchar(15000),
    PRDATAINICIAL date,
    PRDATAFINAL date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDDATACOL date,
    BDCODMAS integer,
    BDSALBASECOL numeric(15,6),
    BDDESCMAS varchar(50),
    BDCODTFUC integer,
    BDDESCTFUC varchar(40),
    BDCODCBO integer,
    BDTIPOCOL integer,
    BDSALINICOL numeric(15,6))
as
declare variable WSQL varchar(30000);
declare variable WCODEMPAUX integer;
declare variable WCODCOLAUX integer;
declare variable WCODTFUC integer;
declare variable WSALBASECOLAUX numeric(18,6);
BEGIN
   wcodempaux = 0;
   wcodcolaux = 0;
   wsalbasecolaux = 0;
   wcodtfuc = 0;

 FOR SELECT 
  colcon_dia.bdcodemp,
  colcon_dia.bdcodcol,
  vw_col.bdnomcol,
  colcon_dia.bddatacol,
  colcon_dia.bdcodmas,
  colcon_dia.bdsalbasecol,
  tmotaumsal.bddescmas,
  tcolfunc.bdcodtfuc,
  tcolfunc.bddesctfuc,
  tcolfunc.bdcodcbo,
  tcolcalc.bdtipocol,
  vw_col.bdsalinicol

 FROM 
  VRH_SP_COLCON_DIA(:prempresa, :prcolaborador, :prdatainicial, :prdatafinal) colcon_dia
 LEFT OUTER JOIN  
  vw_colaboradores vw_col ON (vw_col.bdcodemp = colcon_dia.BDCODEMP AND vw_col.bdcodcol = colcon_dia.BDCODCOL)
 LEFT OUTER JOIN 
  vrh_base_tmotaumsal tmotaumsal ON (tmotaumsal.bdcodmas = colcon_dia.bdcodmas)
 LEFT OUTER JOIN 
  VRH_FUNCOES_TFUC tcolfunc ON (tcolfunc.bdcodplafuc = colcon_dia.bdcodplafuc AND 
           tcolfunc.bdcodtfuc = colcon_dia.bdcodtfuc)
 LEFT OUTER JOIN 
  vrhf_emp_tcol_calc tcolcalc ON (tcolcalc.BDCODEMP = colcon_dia.BDCODEMP AND tcolcalc.BDCODCOL = colcon_dia.BDCODCOL AND
          tcolcalc.bdrefcol = (select first 1 bdrefcol from vrhf_emp_tcol_calc where BDCODEMP = colcon_dia.BDCODEMP
          AND BDCODCOL = colcon_dia.BDCODCOL and bdrefcol <= extract(year from colcon_dia.bddatacol) || lpad(extract(month from COLCON_DIA.BDDATACOL),2,0) order by BDREFCOL desc)
          )
 WHERE coalesce(tcolcalc.bdtipocol, 0) <> 4 and tcolcalc.bdcodcol is not null
   INTO
    :bdcodemp,
    :bdcodcol,
    :bdnomcol,
    :bddatacol,
    :bdcodmas,
    :bdsalbasecol,
    :bddescmas,
    :bdcodtfuc,
    :bddesctfuc,
    :bdcodcbo,
    :bdtipocol,
    :bdsalinicol DO
   BEGIN
     IF ((bdcodemp <> wcodempaux) OR (bdcodcol <> wcodcolaux) OR (bdsalbasecol <> wsalbasecolaux) OR (WCODTFUC <> bdcodtfuc)) THEN --Caso o mesmo colaborador tenha 2 ou mais vezes 'alteração salarial' com o mesmo salário.
        BEGIN
          wcodempaux = bdcodemp;
          wcodcolaux = bdcodcol;
          wsalbasecolaux = bdsalbasecol;
          WCODTFUC = bdcodtfuc;
          SUSPEND;
        END
   END

  wcodempaux = 0;
  wcodcolaux = 0;
  wsalbasecolaux = 0;
  wcodtfuc = 0;

  wsql = 'SELECT '||
            'dia.bdcodemp, '||
            'dia.bdcodcol, '||
            'vw_col.bdnomcol, '||
            'colcon_dia.BDDATASHE, '||
            'colcon_dia.bdcodmas, '||
            'colcon_dia.bdsalshe, '||
            'tmotaumsal.bddescmas, '||
            'tcolfunc.bdcodtfuc, '||
            'tcolfunc.bddesctfuc, '||
            'tcolfunc.bdcodcbo, '||
            'tcolcalc.bdtipocol, '||
            'colpartida.BDSALINICOL '||
          'FROM '||
            'VRH_EMP_TCOLCON dia '||
          'LEFT OUTER JOIN '||
            'VRH_EMP_TCOL_SHE colcon_dia on (colcon_dia.BDCODEMP = dia.bdcodemp and colcon_dia.BDCODCOL = dia.bdcodcol) '||
          'LEFT OUTER JOIN '||
            'VRH_EMP_TCOL_VINCDIA col_dia on (col_dia.BDCODEMP = dia.bdcodemp and col_dia.BDCODCOL = dia.BDCODCOL and COL_DIA.BDDATACOL = COLCON_DIA.BDDATASHE) '||
          'LEFT OUTER JOIN '||
            'vw_vrh_emp_tcolcon_cad vw_col ON (vw_col.bdcodemp = dia.BDCODEMP AND vw_col.bdcodcol = dia.BDCODCOL) '||
          'LEFT OUTER JOIN '||
            'vrh_base_tmotaumsal tmotaumsal ON (tmotaumsal.bdcodmas = colcon_dia.bdcodmas) '||
          'LEFT OUTER JOIN '||
            'VRH_FUNCOES_TFUC tcolfunc ON (tcolfunc.bdcodplafuc = col_dia.bdcodplafuc AND tcolfunc.bdcodtfuc = col_dia.bdcodtfuc) '||
          'LEFT OUTER JOIN '||
            'VRH_EMP_TCOLCON_PARTIDA colpartida on (colpartida.BDCODEMP = dia.BDCODEMP and colpartida.BDCODCOL = dia.BDCODCOL) '||
          'LEFT OUTER JOIN '||
            'VRH_EMP_TCOLCON_CALCDIA colcon_calc on (colcon_calc.BDCODEMP = dia.BDCODEMP and colcon_calc.BDCODCOL = dia.BDCODCOL and colcon_calc.BDDATACOL = colcon_dia.BDDATASHE) '||
          'LEFT OUTER JOIN '||
           'vrhf_emp_tcol_calc tcolcalc ON (tcolcalc.BDCODEMP = dia.BDCODEMP AND tcolcalc.BDCODCOL = dia.BDCODCOL AND '||
                   'tcolcalc.bdrefcol = (select first 1 bdrefcol from vrhf_emp_tcol_calc where BDCODEMP = dia.BDCODEMP '||
                   'AND BDCODCOL = dia.BDCODCOL and bdrefcol <= extract(year from colcon_dia.BDDATASHE) || lpad(extract(month from colcon_dia.BDDATASHE),2,0) order by BDREFCOL desc) '||
                   ') '||
          'WHERE '||
            'coalesce(tcolcalc.bdtipocol, 0) = 4 and tcolcalc.bdcodcol is not null ';

  if (coalesce(prempresa, '') <> '') then
     wsql = wsql||' and '||prempresa||' ';

  if (coalesce(prcolaborador, '') <> '') then
     wsql = wsql||' and '||prcolaborador;

   FOR EXECUTE STATEMENT wsql
   INTO
    :bdcodemp,
    :bdcodcol,
    :bdnomcol,
    :bddatacol,
    :bdcodmas,
    :bdsalbasecol,
    :bddescmas,
    :bdcodtfuc,
    :bddesctfuc,
    :bdcodcbo,
    :bdtipocol,
    :bdsalinicol DO
   BEGIN
     IF ((bdcodemp <> wcodempaux) OR (bdcodcol <> wcodcolaux) OR (bdsalbasecol <> wsalbasecolaux) OR (WCODTFUC <> bdcodtfuc)) THEN --Caso o mesmo colaborador tenha 2 ou mais vezes 'alteração salarial' com o mesmo salário.
        BEGIN
          wcodempaux = bdcodemp;
          wcodcolaux = bdcodcol;
          wsalbasecolaux = bdsalbasecol;
          WCODTFUC = bdcodtfuc;
          SUSPEND;
        END
   END

END^

/* Restore proc. body: VRH_SP_ATIVOS_NO_MES */
CREATE OR ALTER procedure VRH_SP_ATIVOS_NO_MES (
    PRCODEMP varchar(15000),
    PRANOMES integer)
returns (
    BDCODEMP integer,
    BDATIVOS integer)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(20000);
BEGIN
  wsql = 'select X.BDCODEMP, Count(X.BDCODCOL) '||
         'from vrh_emp_tcolcon X '||
         'join VW_VRH_EMP_TCOLCON_VINC COLCON_VINC on (COLCON_VINC.BDCODEMP = X.BDCODEMP and COLCON_VINC.BDCODCOL = X.BDCODCOL) '||
         'join VRH_BASE_TCLASSE CLASSE on (COLCON_VINC.BDCODCLA = CLASSE.BDCODCLA and CLASSE.BDCODCLA <> 5) ';

  wwhere = 'where X.BDCONTRCOL <> 1 and '||
           'CAST((SUBSTRING( CAST(X.BDDATAADMCOL as VARCHAR(10)) from 1 for 4)||SUBSTRING( CAST(X.BDDATAADMCOL as VARCHAR(10)) from 6 for 2)) As INTEGER) <= '||pranomes||' and '||
           'not exists(select Y.BDCODEMP, Y.BDCODCOL '||
                      'from vrh_emp_trescisao Y '||
                      'where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and '||
                      'CAST((SUBSTRING( CAST(Y.BDDATARESCISAO as VARCHAR(10)) from 1 for 4)||SUBSTRING( CAST(Y.BDDATARESCISAO as VARCHAR(10)) from 6 for 2)) As INTEGER) <= '||pranomes||' ) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and ('||prcodemp||') ';

  wsql = wsql||wwhere;
  wsql = wsql||'group by X.bdcodemp ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDATIVOS
  DO

  SUSPEND;
END
^

/* Restore proc. body: VRH_SP_AUMENTOSALARIO */
ALTER PROCEDURE VRH_SP_AUMENTOSALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDATAADMCOL DATE,
BDDATACOL DATE,
BDSALBASECOLANT NUMERIC(15,2),
BDSALBASECOLATU NUMERIC(15,2),
BDCODMAS INTEGER,
BDDESCMAS VARCHAR(50),
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDCODTFUC INTEGER,
BDDESCTFUC VARCHAR(40),
BDHORASMENSAISCOL NUMERIC(15,2),
BDTIPOCOL INTEGER)
 AS
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WDIA INTEGER;
DECLARE VARIABLE WULTDIA VARCHAR(10);
BEGIN

--  execute procedure sp_seta_competencia(PRANOMES, null, null);

  wmes = CAST(SUBSTRING(CAST(:pranomes AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:pranomes AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wultdia = wmes||'/'||wdia||'/'||wano;


  wwhere = 'select COL.bdcodemp, empresas.bdnomemp, COL.bdcodcol , COL.bdnomcol , COL.bddataadmcol, col.bdcodcla, classe.BDDESCCLA, col.bdcodtfuc, colfunc.BDDESCTFUC, col.bdHORASMENSAISCOL, col.bdTIPOCOL ';
  wwhere = wwhere||'from vrh_sp_colcon(null,null,null,null,null, ' || pranomes || ' , '''||wultdia||''' , 1,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0) col ';
  wwhere = wwhere||'join VRH_BASE_TCLASSE classe on (col.bdcodcla = classe.bdcodcla)';
  wwhere = wwhere||'left outer join VRH_FUNCOES_TFUC colfunc on  (col.BDCODPLAFUC = colfunc.BDCODPLAFUC and col.BDCODTFUC = colfunc.BDCODTFUC) ';

  IF (prcodemp > 0) THEN
    BEGIN
      wwhere = wwhere||'left outer join sp_consultaempresas(' || pranomes || ' , ' || prCodEmp || '  ,null) empresas on (col.bdcodemp = empresas.bdcodemp)';
      wwhere = wwhere||'where col.bdcodemp in ('||prcodemp||') ';
    END
  ELSE
      wwhere = wwhere||'left outer join sp_consultaempresas(' || pranomes || ' , ' || ' null ' || '  ,null) empresas on (col.bdcodemp = empresas.bdcodemp)';

  IF (prcodcol > 0) THEN
     wwhere = wwhere||'and col.bdcodcol in ('||prcodcol||') ';

  FOR EXECUTE STATEMENT wwhere
      INTO :bdcodemp, :bdnomemp,  :bdcodcol , :bdnomcol , :bddataadmcol, :bdcodcla , :bddesccla, :bdcodtfuc, :bddesctfuc, :bdhorasmensaiscol, :bdtipocol  DO
      BEGIN
        bdsalbasecolant = 0;
        bdsalbasecolatu = 0;

        FOR SELECT FIRST 2 COLDIA.bddatacol,  COLDIA.bdsalbasecol, COLDIA.bdcodmas, codmas.bddescmas
            FROM VRH_EMP_TCOLCON_CALCDIA COLDIA
            LEFT OUTER JOIN VRH_BASE_TMOTAUMSAL codmas ON (coldia.bdcodmas = codmas.bdcodmas)
            WHERE coldia.bdcodemp = :bdcodemp
            AND coldia.bdcodcol = :bdcodcol
            AND coldia.bddatacol <= :wultdia
            ORDER BY coldia.bddatacol DESC
            INTO :bddatacol, :wvalor, :bdcodmas, :bddescmas DO
            BEGIN
              IF (bdsalbasecolatu = 0) THEN
                 bdsalbasecolatu = wvalor;
              ELSE
                 bdsalbasecolant = wvalor;
            END

         IF (bdsalbasecolant <> 0) THEN
            BEGIN


              SUSPEND;
            END
      END
END
^

/* Restore proc. body: VRH_SP_CAD_TERC */
create or alter procedure VRH_SP_CAD_TERC (
    PRCODCOL varchar(32700),
    PRCODCLA varchar(1000),
    PRREF integer,
    PRCOLCON smallint,
    PRCOLCON_DOC smallint,
    PRCOLCON_VINC smallint,
    PRCOLCON_BANCO smallint,
    PRCOLCON_CALC smallint,
    PRCOLCON_FGTSGPS smallint,
    PRCOLCON_MVINC smallint,
    PRCOLCON_DIA smallint)
returns (
    BDCODCOL integer,
    BDCODMCAG integer,
    BDCODCID integer,
    BDCODCSEG integer,
    BDREFCSEG integer,
    BDCODCIDNASC integer,
    BDCODUF integer,
    BDNOMCOL DM_BDNOMCOL,
    BDLOGRCOL varchar(15),
    BDENDCOL DM_BDENDERECO,
    BDNUMCOL DM_NUMEND,
    BDCOMPLCOL DM_BDCOMPENDERECO,
    BDBAICOL DM_BDBAIRRO,
    BDCEPCOL varchar(9),
    BDDDDCOL integer,
    BDFONECOL DM_BDTELEFONE,
    BDCELCOL DM_BDTELEFONE,
    BDEMAILCOL DM_BDEMAIL,
    BDSEXOCOL integer,
    BDDATANASCCOL date,
    BDDATACADCOL date,
    BDGRAUINSTCOL integer,
    BDESTCIVCOL integer,
    BDDATAADMCOL date,
    BDDATAADICCOL date,
    BDRGCOL varchar(13),
    BDORGEMIRGCOL DM_ORGAOEMISSOR,
    BDDATAEMIRGCOL date,
    BDCPFCOL varchar(14),
    BDRESERVISTACOL varchar(16),
    BDPISCOL varchar(14),
    BDDATAEMIPISCOL date,
    BDCODUF_COL_DOC integer,
    BDTITELEICOL varchar(13),
    BDZONAELEICOL integer,
    BDSECAOELEICOL integer,
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDDATAEMICTPSCOL date,
    BDCNHCOL varchar(11),
    BDVENCCNHCOL date,
    BDCATCNHCOL varchar(2),
    BDCODCID_HIST integer,
    BDCODPAIS integer,
    BDNATURALIZADOCOL varchar(5),
    BDDATACHEBRASILCOL date,
    BDCODCIDNASCCONJ integer,
    BDNOMPAICOL varchar(70),
    BDNOMMAECOL varchar(70),
    BDNOMCONJCOL varchar(70),
    BDDATANASCCONJCOL date,
    BDCORCOL integer,
    BDCABELOSCOL integer,
    BDOLHOSCOL integer,
    BDALTURACOL numeric(15,6),
    BDPESOCOL numeric(15,6),
    BDSINAISCOL varchar(5),
    BDDEFFISICOCOL integer,
    BDTIPOSANGUECOL integer,
    BDNROCONSPROCOL varchar(20),
    BDSIGLACONSPROCOL varchar(5),
    BDCODCCMPROCOL varchar(15),
    BDCODCLA integer,
    BDGRUPOCLA integer,
    BDCODMEN integer,
    BDCODSINTRAB integer,
    BDCODBAN integer,
    BDCODAG integer,
    BDCTADEPCOL varchar(15),
    BDDIGCTADEPCOL varchar(2),
    BDTIPOCTACOL integer,
    BDMODOPAGTOCOL integer,
    BDCARTAOSALCOL varchar(7),
    BDFORMAPAGTOCOL integer,
    BDNRODEPIRCOL integer,
    BDBASEIRRFADCOL numeric(15,6),
    BDVALORPREVPRIVNCOL numeric(15,6),
    BDVALORPREVPRIV13COL numeric(15,6),
    BDDATAOPCAOFGTSCOL date,
    BDCTAFGTSCOL varchar(11),
    BDCATEGORIACOL integer,
    BDPERCFGTSCOL numeric(15,6),
    BDOCORRENCIACOL integer,
    BDPERCRATCOL numeric(15,6),
    BDPERCDESCFPASCOL numeric(15,6),
    BDBASEINSSNCOL numeric(15,6),
    BDVALORINSSNCOL numeric(15,6),
    BDBASEIRRFNCOL numeric(15,6),
    BDVALORIRRFNCOL numeric(15,6),
    BDBASEINSS13COL numeric(15,6),
    BDVALORINSS13COL numeric(15,6),
    BDBASEIRRF13COL numeric(15,6),
    BDVALORIRRF13COL numeric(15,6),
    BDTIPOADMCOL integer,
    BDNATUOCUPCOL integer,
    BDDATAINIAQUICOL date,
    BDSALINICOL numeric(15,6),
    BDDIASPRAZO1COL integer,
    BDDATAFIMPRAZO1COL date,
    BDDIASPRAZO2COL integer,
    BDDATAFIMPRAZO2COL date,
    BDDESCCONTSINCOL varchar(5),
    BDVINCEMPCOL integer,
    BDALVARACOL varchar(5),
    BDSINDICALIZADOCOL varchar(5),
    BDREGIMEPARCIALCOL varchar(5),
    BDFICHAREGCOL varchar(12),
    BDLIVROREGCOL varchar(10),
    BDNROFOLHAREGCOL integer,
    BDTIPOCOL integer,
    BDHORASMENSAISCOL numeric(15,6),
    BDHORASSEMANAISCOL numeric(15,6),
    BDHORASDIARIASCOL numeric(15,6),
    BDPERCINSALUBCOL numeric(15,6),
    BDINCIDINSALUBCOL integer,
    BDPERCPERCULCOL numeric(15,6),
    BDINCIDPERICULCOL integer,
    BDPERCNOTURNOCOL numeric(15,6),
    BDINCIDNOTURNOCOL integer,
    BDNRODEPSALFAMCOL integer,
    BDIGNORAFALTASFERCOL varchar(5),
    BDCALCADIANTACOL varchar(5),
    BDNAOARREDONDARCOL varchar(5),
    BDIMPETIQUETACOL varchar(5),
    BDCALCDSRRVCOL varchar(5),
    BDCALCDSRHECOL varchar(5),
    BDCALCDSRSALCOL varchar(5),
    BDCALCVALTRANSCOL varchar(5),
    BDCALCVALREFCOL varchar(5),
    BDOBSCOL blob sub_type 0 segment size 80,
    BDCODGPS integer,
    BDDESCINSSDOIRCOL varchar(5),
    BDCODMAS integer,
    BDSALBASECOL numeric(15,6),
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDCODCBO integer,
    BDCODCBOTSIN integer,
    BDCODQH integer,
    BDCODPRES integer,
    BDDATARESCISAO date,
    BDDATAAVPREVIO date,
    BDDATAHOM date,
    BDDATAPAGRESCISAO date,
    BDSALDOFGTS numeric(15,6),
    BDCALCFGTSMESANT varchar(5),
    BDMAIORREMUNERACAO numeric(15,6),
    BDCHAVEINDENTIFICACAO varchar(49),
    BDDATAPAGGRFC date,
    BDREPOSICAOVAGA varchar(5),
    BDDISSIDIO varchar(5),
    BDDATADISSIDIO date,
    BDDESCANSOINDENIZADO varchar(5),
    BDCODMFGRESC integer,
    BDCODSAQUERESC integer,
    BDCODMRAISRESC integer,
    BDCODMCAGRESC integer,
    BDDESCPRES varchar(110),
    BDINIPRES integer,
    BDJCPRES varchar(5),
    BDAVPREPRES integer,
    BDGRRFPRES integer,
    BDESTPRES varchar(5),
    BDINDFER13 varchar(5),
    BDTERMCONTRPRES varchar(5),
    BDMULTAPRES varchar(5),
    BDDIASAVPREPRES integer,
    BDDIASPAGPRES integer,
    BDCODSEFMFGRESC varchar(5),
    BDDESCMFGRESC varchar(255),
    BDDESCSAQUERESC varchar(60),
    BDDESCMRAISRESC varchar(255),
    BDDESCMCAGEDRESC varchar(255),
    BDCODEMPDESTTRAN integer,
    BDCODPTRAN integer,
    BDCODCOLTRANS integer,
    BDDATATRANS date,
    BDCODMCAGENTTRANS integer,
    BDCODMCAGSAITRANS integer,
    BDCODMFGTRANS integer,
    BDCODMRAISTRANS integer,
    BDDESCPTRANS varchar(60),
    BDCODSEFMFGTRANS varchar(5),
    BDDESCMFGTRANS varchar(255),
    BDDESCRAISTRANS varchar(255),
    BDDESCMCAGEDENTTRANS varchar(255),
    BDDESCMCAGEDSAITRANS varchar(255))
as
declare variable WCAM varchar(20000);
declare variable WWHE varchar(10000);
declare variable WV varchar(30);
declare variable WI varchar(3);
declare variable WD varchar(30);
declare variable WB varchar(30);
declare variable WN varchar(30);
declare variable WTRUE varchar(5);
declare variable WDATA varchar(10);
BEGIN
   -- Seta a competência atual.
   -- Algumas View's utilizam essas variáveis de contexto para filtrar e agrupar tabelas.
   wdata = CAST(prref AS VARCHAR(6));
   wdata = SUBSTRING(wdata FROM 5 FOR 2)||'-01-'||SUBSTRING(wdata FROM 1 FOR 4);
   EXECUTE PROCEDURE sp_seta_competencia(prref, CAST(wdata AS DATE), CAST(wdata AS DATE));

   /* Retorna o usuário logado */
--   for select BDCODUSU from sp_get_usuario
--     into
--       :wcodusu
--     do

   wtrue = '(0=0)';
   prcodcol = COALESCE(prcodcol,wtrue);
   prcodcla = COALESCE(prcodcla,wtrue);

   wv = ', CAST(NULL AS varchar(1))';
   wi = ', 0';
   wd = ', CAST(NULL AS DATE)';
   wb = ', CAST(NULL AS BLOB)';
   wn = ', CAST(NULL AS NUMERIC(15,6))';

   wcam = 'select COLCON.BDCODTER ';

   -- CAMPOS
   IF (:PRCOLCON = 0) THEN
      wcam = wcam||wi||wi||wi||wi||
                   wi||wi||wv||wv||wv||
                   wi||wv||wv||wv||wi||
                   wv||wv||wv||wi||
                   wd||wd||wi||wi||
                   wd||wd;
   ELSE
      wcam = wcam||wi||', COLCON.BDCODCID'||wi||wi||
                   ', COLCON.BDCODCIDNASCTER'||wi||', COLCON.BDNOMTER, COLCON.BDLOGRTER, COLCON.BDENDTER '||
                   ', COLCON.BDNUMTER, COLCON.BDCOMPLTER, SUBSTRING(COLCON.BDBAITER FROM 1 FOR 50), COLCON.BDCEPTER, COLCON.BDDDDTER '||
                   ', COLCON.BDFONETER, COLCON.BDCELTER, COLCON.BDEMAILTER, COLCON.BDSEXOTER '||
                   ', COLCON.BDDATANASCTER, COLCON.BDDATACADTER, TTERCREF.bdgrauinstter BDGRAUINSTRUCAO, TTERCREF.bdestcivter BDESTADOCIVIL '||
                   wd||wd;

   IF (:PRCOLCON_DOC = 0) THEN
      wcam = wcam||wv||wv||wd||
                   wv||wv||wv||wd;
   ELSE
      wcam = wcam||', COLCON_DOC.bdrgter, COLCON_DOC.BDORGEMIRGTER, COLCON_DOC.BDDATAEMIRGTER '||
                   ', case ' ||
                   ' when (char_length(COLCON_DOC.BDCPFMEI) = 14) then COLCON_DOC.BDCPFMEI '||
                   ' else COLCON_DOC.BDCPFTER ' ||
                   ' end BDCPFTER, COLCON_DOC.BDRESERVISTATER, COLCON_DOC.BDPISTER'||wd;

   /*Dados não existentes no terceiro
   if (:PRCOL_DOC = 0) then*/
      wcam = wcam||wi||wv||
                   wi||wi||wi||wi||
                   wv||wd||wv||wd||
                   wv;

/* Dados nao existentes para o terceiro
   if (:PRCOL_HIST = 0) then*/
      wcam = wcam||wi||wi||wv||wd;

--   if (:PRCOL_PARENT = 0) then
      wcam = wcam||wi||wv||wv||wv||wd;

--   if (:PRCOL_FIS = 0) then
      wcam = wcam||wi||wi||wi||wn||wn||wv||wi||wi;

--   if (:PRCON_DOC = 0) then
   IF (:PRCOLCON_DOC = 0) THEN
      wcam = wcam||wv||wv||wv;
   ELSE
      wcam = wcam||', COLCON_DOC.BDNROCONSPROTER, COLCON_DOC.BDSIGLACONSPROTER, COLCON_DOC.BDCODCCMPROTER';

   IF (:PRCOLCON_VINC = 0 AND :PRCODCLA IS NULL) THEN
      wcam = wcam||wi||wi;
   ELSE
      wcam = wcam||', COLCON_VINC.BDCODCLA, CLASSE.BDGRUPOCLA';

   /*SINDICATO terceiro nao possui*/
   wcam = wcam||wi||wi;

   IF (:PRCOLCON_BANCO = 0) THEN
      wcam = wcam||wi||wi||wv||wv||wi||wi||wv;
   ELSE
      wcam = wcam||', COLCON_BANCO.BDCODBAN, COLCON_BANCO.BDCODAG, COLCON_BANCO.BDCTADEPCOL, COLCON_BANCO.BDDIGCTADEPCOL '||
                   ', COLCON_BANCO.BDTIPOCTACOL, COLCON_BANCO.BDMODOPAGTOCOL, COLCON_BANCO.BDCARTAOSALCOL';

   IF (:PRCOLCON_CALC = 0) THEN
      wcam = wcam||wi||wi||wn||wn||wn;
   ELSE
      wcam = wcam||wi||', TTERCREF.bdnrodepircol'||wn||wn||wn;

   /*Terceiro nao tem dados de fgts apenas de gps*/
   IF (:PRCOLCON_FGTSGPS = 0) THEN
      wcam = wcam||wd||wv||wi||wn||wi||wn||wn;
   ELSE
      wcam = wcam||wd||wv||', COLCON_FGTSGPS.BDCATEGORIACOL '||
                   ', COLCON_FGTSGPS.BDPERCFGTSCOL, COLCON_FGTSGPS.BDOCORRENCIACOL '||
                   ', COLCON_FGTSGPS.BDPERCRATCOL, COLCON_FGTSGPS.BDPERCDESCFPASCOL';

   IF (:PRCOLCON_MVINC = 0) THEN
      wcam = wcam||wn||wn||wn||wn||wn||wn||wn||wn;
   ELSE
      wcam = wcam||', COLCON_MVINC.BDBASEINSSNCOL, COLCON_MVINC.BDVALORINSSNCOL, COLCON_MVINC.BDBASEIRRFNCOL '||
                   ', COLCON_MVINC.BDVALORIRRFNCOL'||wn||wn||
                   wn||wn;

--   if (:PRCOL_ADM = 0) then
      wcam = wcam||wi||wi||wd||wn||wi||wd||wi||wd||wv||wi||wv||wv||wv||wv||wv||wi;

--   if (:PRCOL_CALC = 0) then
      wcam = wcam||wi||wn||wn||wn||wn||wi||wn||wi||wn||wi||wi||wv||wv||wv||wv||wv||wv||wv||wv||wv;

--   if (:PRCOL_HISTF = 0) then
      wcam = wcam||wb;

--   if (:PRCON_VINC = 0) then
      wcam = wcam||wi||wv;

   IF (:prcolcon_dia = 0) THEN
      wcam = wcam||wi||wn||wi||wi||wi||wi||wi;
   ELSE
      wcam = wcam||wi||wn||wi||wi||', COLCON_VINC.BDCODCBO, COLCON_VINC.BDCODCBOTSIN'||wi;


   /* Tabela de Rescisao nao existe para terceiros*/
    wcam = wcam||wi||wd||wd||wd||wd||
                 wn||wv||wn||wv||
                 wd||wv||wv||wd||wv;

    /* Motivos de rescisão nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wi||wv||wi||
                 wv||wi||wi||wv||wv||wv||
                 wv||wi||wi||
                 wv||wv||
                 wv||
                 wv||
                 wv;


   /* Tabela de Transferencias nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wd;

    /* Motivos de transferência nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wi||wv||
                 wv||wv||
                 wv||
                 wv||
                 wv;

   -- TABELAS
   wcam = wcam||' from vrh_base_tterc COLCON ';
   WCAM = WCAM||' join vrh_base_tterc_ref TTERCREF on (TTERCREF.BDCODTER = COLCON.BDCODTER and TTERCREF.BDREFTERC = (select max(BDREFTERC) from vrh_base_tterc_ref REF where ref.BDCODTER = colcon.BDCODTER and ref.bdrefterc <= '||PRREF||')) ';
   --wcam = wcam||' join VW_VRH_BASE_TTERC_REF TTERCREF on (TTERCREF.bdcodCOL = COLCON.bdcodter) ';

   IF (:PRCOLCON_DOC <> 0) THEN
      wcam = wcam||' join vw_VRH_BASE_TTERC_DOC  COLCON_DOC on (COLCON_DOC.bdcodter = COLCON.bdcodter) ';

   IF (:PRCOLCON_VINC = 1 OR :PRCODCLA IS NOT NULL)  THEN
      BEGIN
        wcam = wcam||' join VW_VRH_BASE_TTERC_VINC COLCON_VINC '||
                         'on (COLCON_VINC.BDCODCOL = COLCON.bdcodter) ';

        -- Grupo da Classe
        wcam = wcam||' join VRH_BASE_TCLASSE CLASSE '||
                            'on (CLASSE.BDCODCLA = COLCON_VINC.BDCODCLA) ';
      END

   IF (:PRCOLCON_BANCO = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_BASE_TTERC_BANCO '||
                            'COLCON_BANCO on (COLCON_BANCO.BDCODCOL = COLCON.bdcodter) ';
      END

   IF (:PRCOLCON_FGTSGPS = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_BASE_TTERC_FGTSGPS '||
                            'COLCON_FGTSGPS on (COLCON_FGTSGPS.BDCODCOL = COLCON.bdcodter) ';
      END

   IF (:PRCOLCON_MVINC = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_BASE_TTERC_MVINC '||
                            'COLCON_MVINC on (COLCON_MVINC.BDCODCOL = COLCON.BDCODTER) ';
      END

   -- WHERE
   wwhe = '';
   IF (:prCODCOL IS NOT NULL) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';
        wwhe = wwhe||prcodcol;

      END

   IF (:PRCODCLA IS NOT NULL) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';
        wwhe = wwhe||prcodcla;
      END

  /* filtra as empresas por usuario */
/*  if (wcodusu is not null and wcodusu <> 0) then
     begin
       if (wwhe <> '') then
          wwhe = wwhe||' and ';

       wwhe = wwhe||'((exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||') and '||
                        'exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||' and Y.BDCODEMP = TSERV.BDCODEMP)) '||
                       'or '||
                       '(not exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||'))'||
                       ') ';
     end*/

   IF ((wwhe <> '') AND (:wwhe IS NOT NULL)) THEN
      wwhe = ' where '||wwhe;
      
   wcam = wcam||wwhe;

   FOR EXECUTE STATEMENT wcam
      INTO :
           -- VRH_EMP_TCOLCON
           BDCODCOL, :BDCODMCAG, :BDCODCID, :BDCODCSEG, :BDREFCSEG,
           :BDCODCIDNASC, :BDCODUF, :BDNOMCOL, :BDLOGRCOL, :BDENDCOL,
           :BDNUMCOL, :BDCOMPLCOL, :BDBAICOL, :BDCEPCOL, :BDDDDCOL,
           :BDFONECOL, :BDCELCOL, :BDEMAILCOL, :BDSEXOCOL,
           :BDDATANASCCOL, :BDDATACADCOL, :BDGRAUINSTCOL, :BDESTCIVCOL,
           :BDDATAADMCOL, :BDDATAADICCOL,

           :BDRGCOL, :BDORGEMIRGCOL, :BDDATAEMIRGCOL, :BDCPFCOL,
           :BDRESERVISTACOL, :BDPISCOL, :BDDATAEMIPISCOL,

           :BDCODUF_COL_DOC, :BDTITELEICOL, :BDZONAELEICOL,
           :BDSECAOELEICOL, :BDCTPSCOL, :BDSERIECTPSCOL, :BDDSERIECTPSCOL, :BDDATAEMICTPSCOL,
           :BDCNHCOL, :BDVENCCNHCOL, :BDCATCNHCOL,

           :BDCODCID_HIST, :BDCODPAIS, :BDNATURALIZADOCOL, :BDDATACHEBRASILCOL,

           :BDCODCIDNASCCONJ, :BDNOMPAICOL, :BDNOMMAECOL, :BDNOMCONJCOL, :BDDATANASCCONJCOL,

           :BDCORCOL, :BDCABELOSCOL, :BDOLHOSCOL, :BDALTURACOL,:BDPESOCOL, :BDSINAISCOL,
           :BDDEFFISICOCOL, :BDTIPOSANGUECOL,

           :BDNROCONSPROCOL, :BDSIGLACONSPROCOL, :BDCODCCMPROCOL,

           :BDCODCLA, :BDGRUPOCLA,

           :BDCODMEN, :BDCODSINTRAB,

           :BDCODBAN, :BDCODAG, :BDCTADEPCOL, :BDDIGCTADEPCOL, :BDTIPOCTACOL, :BDMODOPAGTOCOL, :BDCARTAOSALCOL,

           :BDFORMAPAGTOCOL, :BDNRODEPIRCOL, :BDBASEIRRFADCOL, :BDVALORPREVPRIVNCOL, :BDVALORPREVPRIV13COL,

           :BDDATAOPCAOFGTSCOL, :BDCTAFGTSCOL, :BDCATEGORIACOL, :BDPERCFGTSCOL,
           :BDOCORRENCIACOL, :BDPERCRATCOL, :BDPERCDESCFPASCOL,

           :BDBASEINSSNCOL, :BDVALORINSSNCOL, :BDBASEIRRFNCOL, :BDVALORIRRFNCOL, :BDBASEINSS13COL,
           :BDVALORINSS13COL, :BDBASEIRRF13COL, :BDVALORIRRF13COL,

           :BDTIPOADMCOL, :BDNATUOCUPCOL, :BDDATAINIAQUICOL, :BDSALINICOL, :BDDIASPRAZO1COL,
           :BDDATAFIMPRAZO1COL, :BDDIASPRAZO2COL, :BDDATAFIMPRAZO2COL, :BDDESCCONTSINCOL, :BDVINCEMPCOL,
           :BDALVARACOL, :BDSINDICALIZADOCOL, :BDREGIMEPARCIALCOL, :BDFICHAREGCOL, :BDLIVROREGCOL,
           :BDNROFOLHAREGCOL,

           :BDTIPOCOL, :BDHORASMENSAISCOL, :BDHORASSEMANAISCOL, :BDHORASDIARIASCOL,
           :BDPERCINSALUBCOL , :BDINCIDINSALUBCOL, :BDPERCPERCULCOL, :BDINCIDPERICULCOL,
           :BDPERCNOTURNOCOL, :BDINCIDNOTURNOCOL, :BDNRODEPSALFAMCOL, :BDIGNORAFALTASFERCOL,
           :BDCALCADIANTACOL, :BDNAOARREDONDARCOL, :BDIMPETIQUETACOL, :BDCALCDSRRVCOL,
           :BDCALCDSRHECOL, :BDCALCDSRSALCOL, :BDCALCVALTRANSCOL, :BDCALCVALREFCOL,

           :BDOBSCOL,

           :BDCODGPS, :BDDESCINSSDOIRCOL,

           :BDCODMAS, :BDSALBASECOL,
           :BDCODPLAFUC, :BDCODTFUC, :BDCODCBO, :BDCODCBOTSIN, :BDCODQH,

           -- Rescisao
           :BDCODPRES,
           :BDDATARESCISAO,
           :BDDATAAVPREVIO,
           :BDDATAHOM,
           :BDDATAPAGRESCISAO,
           :BDSALDOFGTS,
           :BDCALCFGTSMESANT,
           :BDMAIORREMUNERACAO,
           :BDCHAVEINDENTIFICACAO,
           :BDDATAPAGGRFC,
           :BDREPOSICAOVAGA,
           :BDDISSIDIO,
           :BDDATADISSIDIO,
           :BDDESCANSOINDENIZADO,
           :BDCODMFGRESC,
           :BDCODSAQUERESC,
           :BDCODMRAISRESC,
           :BDCODMCAGRESC,
           :bddescpres,
           :BDINIPRES,
           :BDJCPRES,
           :BDAVPREPRES,
           :BDGRRFPRES,
           :BDESTPRES,
           :BDINDFER13,
           :BDTERMCONTRPRES,
           :BDMULTAPRES,
           :BDDIASAVPREPRES,
           :BDDIASPAGPRES,
           :BDCODSEFMFGRESC,
           :BDDESCMFGRESC,
           :BDDESCSAQUERESC,
           :BDDESCMRAISRESC,
           :BDDESCMCAGEDRESC,

           --Transferencia
           :BDCODEMPDESTTRAN,
           :BDCODPTRAN,
           :BDCODCOLTRANS,
           :BDDATATRANS,
           :BDCODMCAGENTTRANS,
           :BDCODMCAGSAITRANS,
           :BDCODMFGTRANS,
           :BDCODMRAISTRANS,
           :BDDESCPTRANS,
           :BDCODSEFMFGTRANS,
           :BDDESCMFGTRANS,
           :BDDESCRAISTRANS,
           :BDDESCMCAGEDENTTRANS,
           :BDDESCMCAGEDSAITRANS
           DO

    SUSPEND;

   EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

/* Restore proc. body: VRH_SP_COLCON */
CREATE OR ALTER PROCEDURE VRH_SP_COLCON (
    PRCODEMP VARCHAR(10000),
    PRCODCOL VARCHAR(32700),
    PRCODSIN VARCHAR(1000),
    PRCODCLA VARCHAR(1000),
    PRCODFUC VARCHAR(1000),
    PRREF INTEGER,
    PRULTDIA DATE,
    PRCOLCON SMALLINT,
    PRCOLCON_DOC SMALLINT,
    PRCOL_DOC SMALLINT,
    PRCOL_HIST SMALLINT,
    PRCOL_PARENT SMALLINT,
    PRCOL_FIS SMALLINT,
    PRCON_DOC SMALLINT,
    PRCOLCON_VINC SMALLINT,
    PRCOL_VINC SMALLINT,
    PRCOLCON_BANCO SMALLINT,
    PRCOLCON_CALC SMALLINT,
    PRCOLCON_FGTSGPS SMALLINT,
    PRCOLCON_MVINC SMALLINT,
    PRCOL_ADM SMALLINT,
    PRCOL_CALC SMALLINT,
    PRCOL_HISTF SMALLINT,
    PRCON_VINC SMALLINT,
    PRCOLCON_DIA SMALLINT,
    PRFILTRARESC SMALLINT,
    PRFILTRATRANS SMALLINT,
    PRFILTRASIT SMALLINT,
    PRFILTRAFERIAS SMALLINT,
    PRFILTRA13SALARIO SMALLINT,
    PRFILTRAFOLHANORMAL SMALLINT,
    PRREFFOLHANORMAL INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODMCAG INTEGER,
    BDCODCID INTEGER,
    BDCODCSEG INTEGER,
    BDREFCSEG INTEGER,
    BDCODCIDNASC INTEGER,
    BDCODUF INTEGER,
    BDNOMCOL DM_BDNOMCOL,
    BDLOGRCOL VARCHAR(15),
    BDENDCOL DM_BDENDERECO,
    BDNUMCOL DM_NUMEND,
    BDCOMPLCOL DM_BDCOMPENDERECO,
    BDBAICOL DM_BDBAIRRO,
    BDCEPCOL VARCHAR(9),
    BDDDDCOL INTEGER,
    BDFONECOL DM_BDTELEFONE,
    BDCELCOL DM_BDTELEFONE,
    BDEMAILCOL DM_BDEMAIL,
    BDSEXOCOL INTEGER,
    BDDATANASCCOL DATE,
    BDDATACADCOL DATE,
    BDGRAUINSTCOL INTEGER,
    BDESTCIVCOL INTEGER,
    BDDATAADMCOL DATE,
    BDDATAADICCOL DATE,
    BDCONTRCOL INTEGER,
    BDRGCOL VARCHAR(13),
    BDORGEMIRGCOL DM_ORGAOEMISSOR,
    BDDATAEMIRGCOL DATE,
    BDCPFCOL VARCHAR(14),
    BDRESERVISTACOL VARCHAR(16),
    BDPISCOL VARCHAR(14),
    BDDATAEMIPISCOL DATE,
    BDCODUF_COL_DOC INTEGER,
    BDTITELEICOL VARCHAR(13),
    BDZONAELEICOL INTEGER,
    BDSECAOELEICOL INTEGER,
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL VARCHAR(1),
    BDDATAEMICTPSCOL DATE,
    BDCNHCOL VARCHAR(11),
    BDVENCCNHCOL DATE,
    BDCATCNHCOL VARCHAR(2),
    BDCODCID_HIST INTEGER,
    BDCODPAIS INTEGER,
    BDNATURALIZADOCOL VARCHAR(5),
    BDDATACHEBRASILCOL DATE,
    BDCODCIDNASCCONJ INTEGER,
    BDNOMPAICOL VARCHAR(70),
    BDNOMMAECOL VARCHAR(70),
    BDNOMCONJCOL VARCHAR(70),
    BDDATANASCCONJCOL DATE,
    BDCORCOL INTEGER,
    BDCABELOSCOL INTEGER,
    BDOLHOSCOL INTEGER,
    BDALTURACOL NUMERIC(15,6),
    BDPESOCOL NUMERIC(15,6),
    BDSINAISCOL VARCHAR(5),
    BDDEFFISICOCOL INTEGER,
    BDTIPOSANGUECOL INTEGER,
    BDNROCONSPROCOL VARCHAR(20),
    BDSIGLACONSPROCOL VARCHAR(5),
    BDCODCCMPROCOL VARCHAR(15),
    BDCODCLA INTEGER,
    BDGRUPOCLA INTEGER,
    BDCODMEN INTEGER,
    BDCODSINTRAB INTEGER,
    BDCODBAN INTEGER,
    BDCODAG INTEGER,
    BDCTADEPCOL VARCHAR(15),
    BDDIGCTADEPCOL VARCHAR(2),
    BDTIPOCTACOL INTEGER,
    BDMODOPAGTOCOL INTEGER,
    BDCARTAOSALCOL VARCHAR(7),
    BDFORMAPAGTOCOL INTEGER,
    BDNRODEPIRCOL INTEGER,
    BDBASEIRRFADCOL NUMERIC(15,6),
    BDVALORPREVPRIVNCOL NUMERIC(15,6),
    BDVALORPREVPRIV13COL NUMERIC(15,6),
    BDDATAOPCAOFGTSCOL DATE,
    BDCTAFGTSCOL VARCHAR(11),
    BDCATEGORIACOL INTEGER,
    BDPERCFGTSCOL NUMERIC(15,6),
    BDOCORRENCIACOL INTEGER,
    BDPERCRATCOL NUMERIC(15,6),
    BDPERCDESCFPASCOL NUMERIC(15,6),
    BDBASEINSSNCOL NUMERIC(15,6),
    BDVALORINSSNCOL NUMERIC(15,6),
    BDBASEIRRFNCOL NUMERIC(15,6),
    BDVALORIRRFNCOL NUMERIC(15,6),
    BDBASEINSS13COL NUMERIC(15,6),
    BDVALORINSS13COL NUMERIC(15,6),
    BDBASEIRRF13COL NUMERIC(15,6),
    BDVALORIRRF13COL NUMERIC(15,6),
    BDTIPOADMCOL INTEGER,
    BDNATUOCUPCOL INTEGER,
    BDDATAINIAQUICOL DATE,
    BDSALINICOL NUMERIC(15,6),
    BDDIASPRAZO1COL INTEGER,
    BDDATAFIMPRAZO1COL DATE,
    BDDIASPRAZO2COL INTEGER,
    BDDATAFIMPRAZO2COL DATE,
    BDDESCCONTSINCOL VARCHAR(5),
    BDVINCEMPCOL INTEGER,
    BDALVARACOL VARCHAR(5),
    BDSINDICALIZADOCOL VARCHAR(5),
    BDREGIMEPARCIALCOL VARCHAR(5),
    BDFICHAREGCOL VARCHAR(12),
    BDLIVROREGCOL VARCHAR(10),
    BDNROFOLHAREGCOL INTEGER,
    BDTIPOCOL INTEGER,
    BDHORASMENSAISCOL NUMERIC(15,6),
    BDHORASSEMANAISCOL NUMERIC(15,6),
    BDHORASDIARIASCOL NUMERIC(15,6),
    BDPERCINSALUBCOL NUMERIC(15,6),
    BDINCIDINSALUBCOL INTEGER,
    BDPERCPERCULCOL NUMERIC(15,6),
    BDINCIDPERICULCOL INTEGER,
    BDPERCNOTURNOCOL NUMERIC(15,6),
    BDINCIDNOTURNOCOL INTEGER,
    BDNRODEPSALFAMCOL INTEGER,
    BDIGNORAFALTASFERCOL VARCHAR(5),
    BDCALCADIANTACOL VARCHAR(5),
    BDNAOARREDONDARCOL VARCHAR(5),
    BDIMPETIQUETACOL VARCHAR(5),
    BDCALCDSRRVCOL VARCHAR(5),
    BDCALCDSRHECOL VARCHAR(5),
    BDCALCDSRSALCOL VARCHAR(5),
    BDCALCVALTRANSCOL VARCHAR(5),
    BDCALCVALREFCOL VARCHAR(5),
    BDOBSCOL BLOB SUB_TYPE 1 SEGMENT SIZE 5000,
    BDCODGPS INTEGER,
    BDDESCINSSDOIRCOL VARCHAR(5),
    BDCODMAS INTEGER,
    BDSALBASECOL NUMERIC(18,6),
    BDCODPLAFUC INTEGER,
    BDCODTFUC INTEGER,
    BDCODQH INTEGER,
    BDCODPRES INTEGER,
    BDDATARESCISAO DATE,
    BDDATAAVPREVIO DATE,
    BDDATAHOM DATE,
    BDDATAPAGRESCISAO DATE,
    BDSALDOFGTS NUMERIC(15,6),
    BDCALCFGTSMESANT VARCHAR(5),
    BDMAIORREMUNERACAO NUMERIC(15,6),
    BDCHAVEINDENTIFICACAO VARCHAR(49),
    BDDATAPAGGRFC DATE,
    BDREPOSICAOVAGA VARCHAR(5),
    BDDISSIDIO VARCHAR(5),
    BDDATADISSIDIO DATE,
    BDDESCANSOINDENIZADO VARCHAR(5),
    BDCODMFGRESC INTEGER,
    BDCODSAQUERESC INTEGER,
    BDCODMRAISRESC INTEGER,
    BDCODMCAGRESC INTEGER,
    BDDESCPRES VARCHAR(110),
    BDINIPRES INTEGER,
    BDJCPRES VARCHAR(5),
    BDAVPREPRES INTEGER,
    BDGRRFPRES INTEGER,
    BDESTPRES VARCHAR(5),
    BDINDFER13 VARCHAR(5),
    BDTERMCONTRPRES VARCHAR(5),
    BDMULTAPRES VARCHAR(5),
    BDDIASAVPREPRES INTEGER,
    BDDIASPAGPRES INTEGER,
    BDCODSEFMFGRESC VARCHAR(5),
    BDDESCMFGRESC VARCHAR(255),
    BDDESCSAQUERESC VARCHAR(60),
    BDDESCMRAISRESC VARCHAR(255),
    BDDESCMCAGEDRESC VARCHAR(255),
    BDCODEMPDESTTRAN INTEGER,
    BDCODPTRAN INTEGER,
    BDCODCOLTRANS INTEGER,
    BDDATATRANS DATE,
    BDCODMCAGENTTRANS INTEGER,
    BDCODMCAGSAITRANS INTEGER,
    BDCODMFGTRANS INTEGER,
    BDCODMRAISTRANS INTEGER,
    BDDESCPTRANS VARCHAR(60),
    BDCODSEFMFGTRANS VARCHAR(5),
    BDDESCMFGTRANS VARCHAR(255),
    BDDESCRAISTRANS VARCHAR(255),
    BDDESCMCAGEDENTTRANS VARCHAR(255),
    BDDESCMCAGEDSAITRANS VARCHAR(255))
AS
DECLARE VARIABLE WCAM VARCHAR(20000);
DECLARE VARIABLE WWHE VARCHAR(10000);
DECLARE VARIABLE WV VARCHAR(30);
DECLARE VARIABLE WI VARCHAR(3);
DECLARE VARIABLE WD VARCHAR(30);
DECLARE VARIABLE WB VARCHAR(30);
DECLARE VARIABLE WN VARCHAR(30);
DECLARE VARIABLE WTRUE VARCHAR(5);
DECLARE VARIABLE WDATA VARCHAR(10);
DECLARE VARIABLE WCODUSU INTEGER;
BEGIN
   -- Seta a competencia atual.
   -- Algumas Views utilizam essas variaveis de contexto para filtrar e agrupar tabelas.
   wdata = CAST(prref AS VARCHAR(6));
   wdata = SUBSTRING(wdata FROM 5 FOR 2)||'-01-'||SUBSTRING(wdata FROM 1 FOR 4);
   EXECUTE PROCEDURE sp_seta_competencia(prref, CAST(wdata AS DATE), prultdia);

   /* Retorna o usuario logado */
   FOR SELECT BDCODUSU FROM sp_get_usuario
     INTO
       :wcodusu
     DO

   wtrue = '(0=0)';
   prcodemp = COALESCE(prcodemp,wtrue);
   prcodcol = COALESCE(prcodcol,wtrue);
   prcodcla = COALESCE(prcodcla,wtrue);
   prcodsin = COALESCE(prcodsin,wtrue);
   prcodfuc = COALESCE(prcodfuc,wtrue);

   wv = ', CAST(NULL AS varchar(1))';
   wi = ', 0';
   wd = ', CAST(NULL AS DATE)';
   wb = ', CAST(NULL AS BLOB)';
   wn = ', CAST(NULL AS NUMERIC(15,6))';

   wcam = 'select COLCON.BDCODEMP, COLCON.BDCODCOL ';

   -- CAMPOS
   IF (:PRCOLCON = 0) THEN
      wcam = wcam||wi||wi||wi||wi||
                   wi||wi||wv||wv||wv||
                   wi||wv||wv||wv||wi||
                   wv||wv||wv||wi||
                   wd||wd||wi||wi||
                   wd||wd||wi;
   ELSE
      wcam = wcam||', COLCON.BDCODMCAG, COLCAD.BDCODCID, COLCON.BDCODCSEG, COLCON.BDREFCSEG '||
                   ', COLCON.BDCODCIDNASC, DOCREF.BDCODUF, COLCAD.BDNOMCOL, COLCAD.BDLOGRCOL, COLCAD.BDENDCOL '||
                   ', COLCAD.BDNUMCOL, COLCAD.BDCOMPLCOL, COLCAD.BDBAICOL, COLCAD.BDCEPCOL, COLCAD.BDDDDCOL '||
                   ', COLCAD.BDFONECOL, COLCAD.BDCELCOL, COLCAD.BDEMAILCOL, COLCAD.BDSEXOCOL '||
                   ', COLCON.BDDATANASCCOL, COLCON.BDDATACADCOL, COLCAD.BDGRAUINSTCOL, COLCAD.BDESTCIVCOL '||
                   ', COLCON.BDDATAADMCOL, COLCON.BDDATAADICCOL, COLCON.BDCONTRCOL ';

   IF (:PRCOLCON_DOC = 0) THEN
      wcam = wcam||wv||wv||wd||
                   wv||wv||wv||wd;
   ELSE
      wcam = wcam||', DOCREF.BDRGCOL, DOCREF.BDORGEMIRGCOL, DOCREF.BDDATAEMIRGCOL '||
                   ', COLCON_DOC.BDCPFCOL, COLCON_DOC.BDRESERVISTACOL, DOCREF.BDPISCOL, DOCREF.BDDATAEMIPISCOL';

   IF (:PRCOL_DOC = 0) THEN
      wcam = wcam||wi||wv||
                   wi||wi||wi||wi||
                   wv||wd||wv||wd||
                   wv;
   ELSE
      wcam = wcam||', DOCREF.BDCODUF, COL_DOC.BDTITELEICOL '||
                   ', COL_DOC.BDZONAELEICOL, COL_DOC.BDSECAOELEICOL, DOCREF.BDCTPSCOL, DOCREF.BDSERIECTPSCOL '||
                   ', DOCREF.BDDSERIECTPSCOL, DOCREF.BDDATAEMICTPSCOL, DOCREF.BDCNHCOL, DOCREF.BDVENCCNHCOL '||
                   ', DOCREF.BDCATCNHCOL';

   IF (:PRCOL_HIST = 0) THEN
      wcam = wcam||wi||wi||wv||wd;
   ELSE
      wcam = wcam||', COLCON.BDCODCIDNASC, COL_HIST.BDCODPAIS, COL_HIST.BDNATURALIZADOCOL, COLCAD.BDDATACHEBRASILCOL';

   IF (:PRCOL_PARENT = 0) THEN
      wcam = wcam||wi||wv||wv||wv||wd;
   ELSE
      wcam = wcam||', COL_PARENT.BDCODCIDNASCCONJ, COL_PARENT.BDNOMPAICOL, COL_PARENT.BDNOMMAECOL, COL_PARENT.BDNOMCONJCOL, COL_PARENT.BDDATANASCCONJCOL';

   IF (:PRCOL_FIS = 0) THEN
      wcam = wcam||wi||wi||wi||wn||wn||wv||wi||wi;
   ELSE
      wcam = wcam||', CFIS.BDCORCOL, COL_FIS.BDCABELOSCOL, COL_FIS.BDOLHOSCOL, COL_FIS.BDALTURACOL, COL_FIS.BDPESOCOL '||
                   ', COL_FIS.BDSINAISCOL, COL_FIS.BDDEFFISICOCOL, COL_FIS.BDTIPOSANGUECOL';

   IF (:PRCON_DOC = 0) THEN
      wcam = wcam||wv||wv||wv;
   ELSE
      wcam = wcam||', CON_DOC.BDNROCONSPROCOL, CON_DOC.BDSIGLACONSPROCOL, CON_DOC.BDCODCCMPROCOL';

--   wcam = wcam||', COLCON_REF.BDREFCOL';

   IF (:PRCOLCON_VINC = 0 AND :PRCODCLA IS NULL) THEN
      wcam = wcam||wi||wi;
   ELSE
      wcam = wcam||', COLCON_VINC.BDCODCLA, CLASSE.BDGRUPOCLA';

   IF (:PRCOL_VINC = 0 AND :PRCODSIN IS NULL) THEN
      wcam = wcam||wi||wi;
   ELSE
      wcam = wcam||', COL_VINC.BDCODMEN, COL_VINC.BDCODSINTRAB';

   IF (:PRCOLCON_BANCO = 0) THEN
      wcam = wcam||wi||wi||wv||wv||wi||wi||wv;
   ELSE
      wcam = wcam||', COLCON_BANCO.BDCODBAN, COLCON_BANCO.BDCODAG, COLCON_BANCO.BDCTADEPCOL, COLCON_BANCO.BDDIGCTADEPCOL '||
                   ', COLCON_BANCO.BDTIPOCTACOL, COLCON_BANCO.BDMODOPAGTOCOL, COLCON_BANCO.BDCARTAOSALCOL';

   IF (:PRCOLCON_CALC = 0) THEN
      wcam = wcam||wi||wi||wn||wn||wn;
   ELSE
      wcam = wcam||', COLCON_CALC.BDFORMAPAGTOCOL, COLCON_CALC.BDNRODEPIRCOL, COLCON_CALC.BDBASEIRRFADCOL '||
                   ', COLCON_CALC.BDVALORPREVPRIVNCOL, COLCON_CALC.BDVALORPREVPRIV13COL';

   IF (:PRCOLCON_FGTSGPS = 0) THEN
      wcam = wcam||wd||wv||wi||wn||wi||wn||wn;
   ELSE
      wcam = wcam||', COLCON_FGTSGPS.BDDATAOPCAOFGTSCOL, COLCON_FGTSGPS.BDCTAFGTSCOL, COLCON_FGTSGPS.BDCATEGORIACOL '||
                   ', COLCON_FGTSGPS.BDPERCFGTSCOL, COLCON_FGTSGPS.BDOCORRENCIACOL '||
                   ', COLCON_FGTSGPS.BDPERCRATCOL, COLCON_FGTSGPS.BDPERCDESCFPASCOL';

   IF (:PRCOLCON_MVINC = 0) THEN
      wcam = wcam||wn||wn||wn||wn||wn||wn||wn||wn;
   ELSE
      wcam = wcam||', COLCON_MVINC.BDBASEINSSNCOL, COLCON_MVINC.BDVALORINSSNCOL, COLCON_MVINC.BDBASEIRRFNCOL '||
                   ', COLCON_MVINC.BDVALORIRRFNCOL, COLCON_MVINC.BDBASEINSS13COL, COLCON_MVINC.BDVALORINSS13COL '||
                   ', COLCON_MVINC.BDBASEIRRF13COL, COLCON_MVINC.BDVALORIRRF13COL';

   IF (:PRCOL_ADM = 0) THEN
      BEGIN
        wcam = wcam||wi||wi||wd||wn||wi||wd||wi||wd||wv||wi||wv||wv;

        IF (:PRCOL_CALC = 0) THEN
           wcam = wcam||wv;
        ELSE
           wcam = wcam||', COL_CALC.BDREGIMEPARCIALCOL';

        wcam = wcam||wv||wv||wi;

      END
   ELSE
      BEGIN
        wcam = wcam||', COL_ADM.BDTIPOADMCOL, COL_ADM.BDNATUOCUPCOL, COL_ADM.BDDATAINIAQUICOL, COL_ADM.BDSALINICOL '||
                     ', COL_ADM.BDDIASPRAZO1COL, COL_ADM.BDDATAFIMPRAZO1COL, COL_ADM.BDDIASPRAZO2COL, COL_ADM.BDDATAFIMPRAZO2COL '||
                     ', COL_ADM.BDDESCCONTSINCOL, ADMREF.BDVINCEMPCOL, ADMREF.BDALVARACOL, ADMREF.BDSINDICALIZADOCOL ';

        IF (:PRCOL_CALC = 0) THEN
           wcam = wcam||wv;
        ELSE
           wcam = wcam||', COL_CALC.BDREGIMEPARCIALCOL';

        wcam = wcam||', COL_ADM.BDFICHAREGCOL, COL_ADM.BDLIVROREGCOL, COL_ADM.BDNROFOLHAREGCOL';
      END

   IF (:PRCOL_CALC = 0) THEN
      wcam = wcam||wi||wn||wn||wn||wn||wi||wn||wi||wn||wi||wi||wv||wv||wv||wv||wv||wv||wv||wv||wv;
   ELSE
      wcam = wcam||', COL_CALC.BDTIPOCOL, COL_CALC.BDHORASMENSAISCOL, COL_CALC.BDHORASSEMANAISCOL, COL_CALC.BDHORASDIARIASCOL '||
                   ', COL_CALC.BDPERCINSALUBCOL, COL_CALC.BDINCIDINSALUBCOL, COL_CALC.BDPERCPERCULCOL, COL_CALC.BDINCIDPERICULCOL '||
                   ', COL_CALC.BDPERCNOTURNOCOL, COL_CALC.BDINCIDNOTURNOCOL, COL_CALC.BDNRODEPSALFAMCOL, COL_CALC.BDIGNORAFALTASFERCOL '||
                   ', COL_CALC.BDCALCADIANTACOL, COL_CALC.BDNAOARREDONDARCOL, COL_CALC.BDIMPETIQUETACOL, COL_CALC.BDCALCDSRRVCOL  '||
                   ', COL_CALC.BDCALCDSRHECOL, COL_CALC.BDCALCDSRSALCOL, COL_CALC.BDCALCVALTRANSCOL, COL_CALC.BDCALCVALREFCOL';

   IF (:PRCOL_HISTF = 0) THEN
      wcam = wcam||wb;
   ELSE
      wcam = wcam||', COL_HISTF.BDOBSCOL';

   IF (:PRCON_VINC = 0) THEN
      wcam = wcam||wi||wv;
   ELSE
      wcam = wcam||', CON_VINC.BDCODGPS, CON_VINC.BDDESCINSSDOIRCOL';

   IF (:prcolcon_dia = 0) THEN
      wcam = wcam||wi||wn||wi||wi||wi;
   ELSE
      wcam = wcam||', COLCON_DIACALC.BDCODMAS, COLCON_DIACALC.BDSALBASECOL, '||
                   'COL_DIAVINC.BDCODPLAFUC, COL_DIAVINC.BDCODTFUC, COL_DIAVINC.BDCODQH ';


   /* Tabela de Rescisao */
   IF (:prfiltraresc = 0) THEN
      BEGIN
        wcam = wcam||wi||wd||wd||wd||wd||
                     wn||wv||wn||wv||
                     wd||wv||wv||wd||wv;

        /* Motivos de rescisao */
        wcam = wcam||wi||wi||wi||wi||wv||wi||
                     wv||wi||wi||wv||wv||wv||
                     wv||wi||wi||
                     wv||wv||
                     wv||
                     wv||
                     wv;
      END
   ELSE
      BEGIN

        wcam = wcam||', RESC.BDCODPRES, RESC.BDDATARESCISAO, RESC.BDDATAAVPREVIO, RESC.BDDATAHOM, RESC.BDDATAPAGRESCISAO'||
                     ', RESC.BDSALDOFGTS, RESC.BDCALCFGTSMESANT, RESC.BDMAIORREMUNERACAO, RESC.BDCHAVEINDENTIFICACAO'||
                     ', RESC.BDDATAPAGGRFC, RESC.BDREPOSICAOVAGA, RESC.BDDISSIDIO, RESC.BDDATADISSIDIO, RESC.BDDESCANSOINDENIZADO';
        wcam = wcam||', RESC.BDCODMFG, RESC.BDCODSAQUE, RESC.BDCODMRAIS, RESC.BDCODMCAG, RESC.BDDESCPRES, RESC.BDINIPRES'||
                     ', RESC.BDJCPRES, RESC.BDAVPREPRES, RESC.BDGRRFPRES, RESC.BDESTPRES, RESC.BDINDFER13, RESC.BDTERMCONTRPRES'||
                     ', RESC.BDMULTAPRES, RESC.BDDIASAVPREPRES, RESC.BDDIASPAGPRES'||
                     ', RESC.BDCODSEFMFG, RESC.BDDESCMFG'||
                     ', RESC.BDDESCSAQUE'||
                     ', RESC.BDDESCMRAIS'||
                     ', RESC.BDDESCMCAGED ';

      END

   /* Tabela de Transferencias */
   IF (:prfiltratrans = 0) THEN
      BEGIN
        wcam = wcam||wi||wi||wi||wd;

        /* Motivos de transferencia */
        wcam = wcam||wi||wi||wi||wi||wv||
                     wv||wv||
                     wv||
                     wv||
                     wv;
      END
   ELSE
      BEGIN
        wcam = wcam||', TRANS.BDCODEMPDEST, TRANS.BDCODPTRAN, TRANS.BDCODCOLDEST, TRANS.BDDATATRF';
        wcam = wcam||', TRANS.BDCODMCAGENT, TRANS.BDCODMCAGSAI, TRANS.BDCODMFG, TRANS.BDCODMRAIS, TRANS.BDDESCPTRAN'||
                     ', TRANS.BDCODSEFMFG, TRANS.BDDESCMFG'||
                     ', TRANS.BDDESCMRAIS'||
                     ', TRANS.BDDESCMCAGED_TE'||
                     ', TRANS.BDDESCMCAGED_TS ';
      END

   -- TABELAS
   wcam = wcam||' from VRH_EMP_TCOLCON COLCON ';
   wcam = wcam||' left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COLCON.BDCODEMP and COLCAD.BDCODCOL = COLCON.BDCODCOL) ';
   wcam = wcam||' left outer join VW_VRH_EMP_TCOLCON_FIS CFIS on (CFIS.BDCODEMP = COLCON.BDCODEMP and CFIS.BDCODCOL = COLCON.BDCODCOL) ';
   wcam = wcam||' left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = COLCON.BDCODEMP and DOCREF.BDCODCOL = COLCON.BDCODCOL) ';

   IF (:PRCOLCON_DOC = 1) THEN
      wcam = wcam||' left outer join VRH_EMP_TCOLCON_DOC  COLCON_DOC on (COLCON_DOC.BDCODEMP = COLCON.BDCODEMP and COLCON_DOC.BDCODCOL = COLCON.BDCODCOL) ';

   IF (:PRCOL_DOC = 1) THEN
      wcam = wcam||' left outer join VRH_EMP_TCOL_DOC     COL_DOC on (COL_DOC.BDCODEMP = COLCON.BDCODEMP and COL_DOC.BDCODCOL = COLCON.BDCODCOL)';

   IF (:PRCOL_HIST = 1) THEN
      wcam = wcam||' left outer join VRH_EMP_TCOL_HIST    COL_HIST on (COL_HIST.BDCODEMP = COLCON.BDCODEMP and COL_HIST.BDCODCOL = COLCON.BDCODCOL)';

   IF (:PRCOL_PARENT = 1) THEN
      wcam = wcam||' left outer join VRH_EMP_TCOL_PARENT  COL_PARENT on (COL_PARENT.BDCODEMP = COLCON.BDCODEMP and COL_PARENT.BDCODCOL = COLCON.BDCODCOL)';

   IF (:PRCOL_FIS = 1) THEN
      wcam = wcam||' left outer join VRH_EMP_TCOL_FIS     COL_FIS on (COL_FIS.BDCODEMP = COLCON.BDCODEMP and COL_FIS.BDCODCOL = COLCON.BDCODCOL)';

   IF (:PRCON_DOC = 1) THEN
      wcam = wcam||' left outer join VRH_EMP_TCON_DOC     CON_DOC on (CON_DOC.BDCODEMP = COLCON.BDCODEMP and CON_DOC.BDCODCOL = COLCON.BDCODCOL)';

   IF (:PRCOL_ADM = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRH_EMP_TCOL_ADM '||
                           'COL_ADM on (COL_ADM.BDCODEMP = COLCON.BDCODEMP and '||
                                       'COL_ADM.BDCODCOL = COLCON.BDCODCOL) ';
        wcam = wcam||' left outer join VW_VRH_EMP_TCOL_ADMREF '||
                           'ADMREF on (ADMREF.BDCODEMP = COLCON.BDCODEMP and '||
                                       'ADMREF.BDCODCOL = COLCON.BDCODCOL) ';
      END

   --wcam = wcam||' left outer join VW_TCOLCON_REF_ATUAL COLCON_REF '||
   --                 'on (COLCON_REF.BDCODEMP = COLCON.BDCODEMP and COLCON_REF.BDCODCOL = COLCON.BDCODCOL) ';

   IF (:PRCOLCON_VINC = 1 OR :PRCODCLA IS NOT NULL)  THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRH_EMP_TCOLCON_VINC COLCON_VINC '||
                         'on (COLCON_VINC.BDCODEMP = COLCON.BDCODEMP and '||
                             'COLCON_VINC.BDCODCOL = COLCON.BDCODCOL) ';

        -- Grupo da Classe
        wcam = wcam||' left outer join VRH_BASE_TCLASSE CLASSE '||
                            'on (CLASSE.BDCODCLA = COLCON_VINC.BDCODCLA) ';
      END

   IF (:PRCOL_VINC = 1 OR :PRCODSIN IS NOT NULL) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRH_EMP_TCOL_VINC '||
                            'COL_VINC on (COL_VINC.BDCODEMP = COLCON.BDCODEMP and '||
                                         'COL_VINC.BDCODCOL = COLCON.BDCODCOL) ';

      END

   IF (:PRCOLCON_BANCO = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_EMP_TCOLCON_BANCO '||
                            'COLCON_BANCO on (COLCON_BANCO.BDCODEMP = COLCON.BDCODEMP and '||
                                             'COLCON_BANCO.BDCODCOL = COLCON.BDCODCOL) ';
      END
   IF (:PRCOLCON_CALC = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_EMP_TCOLCON_CALC '||
                            'COLCON_CALC on (COLCON_CALC.BDCODEMP = COLCON.BDCODEMP and '||
                                            'COLCON_CALC.BDCODCOL = COLCON.BDCODCOL) ';
      END

   IF (:PRCOLCON_FGTSGPS = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS '||
                            'COLCON_FGTSGPS on (COLCON_FGTSGPS.BDCODEMP = COLCON.BDCODEMP and '||
                                               'COLCON_FGTSGPS.BDCODCOL = COLCON.BDCODCOL) ';
      END

   IF (:PRCOLCON_MVINC = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_EMP_TCOLCON_MVINC '||
                            'COLCON_MVINC on (COLCON_MVINC.BDCODEMP = COLCON.BDCODEMP and '||
                                             'COLCON_MVINC.BDCODCOL = COLCON.BDCODCOL) ';
      END

   IF (:PRCOL_CALC = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_EMP_TCOL_CALC '||
                            'COL_CALC on (COL_CALC.BDCODEMP = COLCON.BDCODEMP and '||
                                         'COL_CALC.BDCODCOL = COLCON.BDCODCOL) ';
      END

   IF (:PRCOL_HISTF = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_EMP_TCOL_HIST '||
                            'COL_HISTF on (COL_HISTF.BDCODEMP = COLCON.BDCODEMP and '||
                                          'COL_HISTF.BDCODCOL = COLCON.BDCODCOL) ';
      END

   IF (:PRCON_VINC = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRHF_EMP_TCON_VINC '||
                            'CON_VINC on (CON_VINC.BDCODEMP = COLCON.BDCODEMP and '||
                                         'CON_VINC.BDCODCOL = COLCON.BDCODCOL) ';
      END

   IF (:prcolcon_dia = 1) THEN
      BEGIN
        wcam = wcam||' left outer join VW_VRH_EMP_TCOLCON_CALCDIA '||
                            'COLCON_DIACALC on (COLCON_DIACALC.BDCODEMP = COLCON.BDCODEMP and '||
                                               'COLCON_DIACALC.BDCODCOL = COLCON.BDCODCOL) ';

        wcam = wcam||' left outer join VW_TCOLCON_VINCDIA '||
                            'COL_DIAVINC on (COL_DIAVINC.BDCODEMP = COLCON.BDCODEMP and '||
                                            'COL_DIAVINC.BDCODCOL = COLCON.BDCODCOL) ';

      END


   IF (:prfiltraresc > 0) THEN
      BEGIN
        IF (prfiltraresc > 3) THEN
           BEGIN
             wcam = wcam||' left outer join VW_RESCISAO_PREVIA '||
                                 'RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and '||
                                          'RESC.BDCODCOL = COLCON.BDCODCOL) ';
           END
        ELSE
           BEGIN
             wcam = wcam||' left outer join VW_RESCISAO '||
                                 'RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and '||
                                          'RESC.BDCODCOL = COLCON.BDCODCOL) ';
           END

      END


   IF (:prfiltratrans > 0) THEN
      BEGIN
        wcam = wcam||' left outer join vw_transf '||
                            'TRANS on (TRANS.BDCODEMPORIG = COLCON.BDCODEMP and TRANS.BDCODCOLORIG = COLCON.BDCODCOL) ';
      END


   -- WHERE
   wwhe = '';
   IF (:prCODEMP IS NOT NULL) THEN
      BEGIN
        wwhe = prcodemp;
      END

   IF (:prCODCOL IS NOT NULL) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';
        wwhe = wwhe||prcodcol;

      END

   IF (:PRCODSIN IS NOT NULL) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';
        wwhe = wwhe||prcodsin;
      END

   IF (:PRCODCLA IS NOT NULL) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';
        wwhe = wwhe||prcodcla;
      END

   IF (:prcolcon_dia <> 0 AND :prcodfuc IS NOT NULL) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';
        wwhe = wwhe||prcodfuc;
      END

   -- Retira admitidos posteriores
   IF (:PRCOLCON <> 0) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||' COLCON.BDDATAADMCOL <= '''||:prultdia||'''';
      END

   -- Faz filtro para retirar colaboradores transferidos
   IF (:PRFILTRATRANS = 2) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||
               '((TRANS.BDDATATRF is null) or '||
                '(TRANS.BDDATATRF >= '''||wdata||''')) ';

               --'((TRANS.BDDATATRF is null) or '||
               --'(cast((substring(cast(TRANS.BDDATATRF as VARCHAR(10)) from 1 for 4)||substring(cast(TRANS.BDDATATRF as VARCHAR(10)) from 6 for 2)) as INTEGER) >= '||:PRREF||')) ';
      END

   IF (:PRFILTRATRANS = 3) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||
               '((TRANS.BDDATATRF is null) or '||
                '(TRANS.BDDATATRF > '''||prultdia||''')) ';
      END

   -- Faz filtro para retirar colaboradores demitidos
   -- Elimina recisoes anteriores ao ano/mes atual
   IF (:PRFILTRARESC = 2) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||
               '((RESC.BDDATARESCISAO is null) or '||
                '(RESC.BDDATARESCISAO >= '''||wdata||''')) ';

      END

   -- Elimina rescisoes a partir do mes atual, ou seja,
   -- nao inclui no resultado do select os demitidos no mes.
   IF (:PRFILTRARESC = 3) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||
              '((RESC.BDDATARESCISAO is null) or '||
               '(RESC.BDDATARESCISAO > '''||prultdia||''')) ';

      END

   -- Faz filtro para retirar colaboradores demitidos   PREVIA
   -- Elimina recisoes anteriores ao ano/mes atual
   IF (:PRFILTRARESC = 4) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||
               '((RESC.BDDATARESCISAO is null) or '||
                '(RESC.BDDATARESCISAO >= '''||wdata||''')) ';

      END

   -- Elimina rescisoes a partir do mes atual, ou seja,
   -- nao inclui no resultado do select os demitidos no mes.       PREVIA
   IF (:PRFILTRARESC = 5) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||
              '((RESC.BDDATARESCISAO is null) or '||
               '(RESC.BDDATARESCISAO > '''||prultdia||''')) ';

      END


   IF (:PRFILTRASIT = 1) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||'not exists(select SIT.* from vrh_emp_tsitcol SIT '||
                                'where SIT.BDCODEMP = COLCON.BDCODEMP and '||
                                      'SIT.BDCODCOL = COLCON.BDCODCOL and '||
                                      'SIT.BDDATAINISIT <= '''||prultdia||''' and '||
                                      '(SIT.BDDATAFIMSIT is null or '||
                                       'SIT.BDDATAFIMSIT >= '''||wdata||'''))';
                                      --'cast((substring(cast(bddatainisit as varchar(10)) from 1 for 4) || substring(cast(bddatainisit as varchar(10)) from 6 for 2)) as Integer) <= '||:PRREF||' and '||
                                      --'(bddatafimsit is null or '||
                                      --     'cast((substring(cast(bddatafimsit as varchar(10)) from 1 for 4) || substring(cast(bddatafimsit as varchar(10)) from 6 for 2)) as Integer) >= '||:PRREF||'))';
      END

   IF (:PRFILTRAFERIAS = 1) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||'not exists(select FER.* from vrh_emp_tferias FER '||
                                'where FER.BDCODEMP = COLCON.BDCODEMP and '||
                                      'FER.BDCODCOL = COLCON.BDCODCOL and '||
                                     '((FER.BDINIPERGOZOFE is not null and FER.BDINIPERGOZOFE between '''||wdata||''' and '''||prultdia||''') or '||
                                      '(FER.BDFIMPERGOZOFE is not null and FER.BDFIMPERGOZOFE between '''||wdata||''' and '''||prultdia||''')'||
                                     ')'||
                               ') ';
                  --'(CAST((SUBSTRING(CAST(FER.BDINIPERGOZOFE as VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(FER.BDINIPERGOZOFE as VARCHAR(10)) FROM 6 FOR 2)) as INTEGER) = '||:PRREF||') or (CAST((SUBSTRING(CAST(FER.BDFIMPERGOZOFE as VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(FER.BDFIMPERGOZOFE as VARCHAR(10)) FROM 6 FOR 2)) as INTEGER) = '||:PRREF||')) or '||
                  --'(FER.BDINIABONOFE is not null and (CAST((SUBSTRING(CAST(FER.BDINIABONOFE as VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(FER.BDINIABONOFE as VARCHAR(10)) FROM 6 FOR 2)) as INTEGER) = '||:PRREF||') or (CAST((SUBSTRING(CAST(FER.BDFIMABONOFE as VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(FER.BDFIMABONOFE as VARCHAR(10)) FROM 6 FOR 2)) as INTEGER) = '||:PRREF||')))) ';
      END

   IF (:PRFILTRA13SALARIO = 1) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||'exists(select T13SAL.BDCODEMP from vrhf_emp_t13sal T13SAL '||
                                'where T13SAL.BDCODEMP = COLCON.BDCODEMP and '||
                                      'T13SAL.BDCODCOL = COLCON.BDCODCOL and '||
                                      '(substring(cast(T13SAL.BDREF13 as integer) from 1 for 4)) =  (substring(cast('||:PRREF||' as integer) from 1 for 4) '||')) ';
      END

   IF (prfiltrafolhanormal IS NOT NULL AND prfiltrafolhanormal = 1) THEN
      BEGIN
        IF (PRREFFOLHANORMAL IS NOT NULL AND PRREFFOLHANORMAL <> 0) THEN
           BEGIN
             IF (wwhe <> '') THEN
                 wwhe = wwhe||' and ';
     
             wwhe = wwhe||'exists(select TFOLHANORMAL.BDCODEMP from vrhf_emp_tfolhanormal TFOLHANORMAL '||
                                     'where TFOLHANORMAL.BDCODEMP = COLCON.BDCODEMP and '||
                                           'TFOLHANORMAL.BDCODCOL = COLCON.BDCODCOL and '||
                                           'TFOLHANORMAL.BDREFFN = ' ||:PRREFFOLHANORMAL|| ') ';
           END
      END

  /* filtra as empresas por usuario */
  IF (wcodusu IS NOT NULL AND wcodusu <> 0) THEN
     BEGIN
       IF (wwhe <> '') THEN
          wwhe = wwhe||' and ';

       wwhe = wwhe||'((exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||') and '||
                        'exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||' and Y.BDCODEMP = COLCON.BDCODEMP)) '||
                       'or '||
                       '(not exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||'))'||
                       ') ';
     END

   IF ((wwhe <> '') AND (:wwhe IS NOT NULL)) THEN
      wwhe = ' where '||wwhe;
      
   wcam = wcam||wwhe;

   FOR EXECUTE STATEMENT wcam
      INTO :BDCODEMP,
           -- VRH_EMP_TCOLCON
           :BDCODCOL, :BDCODMCAG, :BDCODCID, :BDCODCSEG, :BDREFCSEG,
           :BDCODCIDNASC, :BDCODUF, :BDNOMCOL, :BDLOGRCOL, :BDENDCOL,
           :BDNUMCOL, :BDCOMPLCOL, :BDBAICOL, :BDCEPCOL, :BDDDDCOL,
           :BDFONECOL, :BDCELCOL, :BDEMAILCOL, :BDSEXOCOL,
           :BDDATANASCCOL, :BDDATACADCOL, :BDGRAUINSTCOL, :BDESTCIVCOL,
           :BDDATAADMCOL, :BDDATAADICCOL, :BDCONTRCOL,

           :BDRGCOL, :BDORGEMIRGCOL, :BDDATAEMIRGCOL, :BDCPFCOL,
           :BDRESERVISTACOL, :BDPISCOL, :BDDATAEMIPISCOL,

           :BDCODUF_COL_DOC, :BDTITELEICOL, :BDZONAELEICOL,
           :BDSECAOELEICOL, :BDCTPSCOL, :BDSERIECTPSCOL, :BDDSERIECTPSCOL, :BDDATAEMICTPSCOL,
           :BDCNHCOL, :BDVENCCNHCOL, :BDCATCNHCOL,

           :BDCODCID_HIST, :BDCODPAIS, :BDNATURALIZADOCOL, :BDDATACHEBRASILCOL,

           :BDCODCIDNASCCONJ, :BDNOMPAICOL, :BDNOMMAECOL, :BDNOMCONJCOL, :BDDATANASCCONJCOL,

           :BDCORCOL, :BDCABELOSCOL, :BDOLHOSCOL, :BDALTURACOL,:BDPESOCOL, :BDSINAISCOL,
           :BDDEFFISICOCOL, :BDTIPOSANGUECOL,

           :BDNROCONSPROCOL, :BDSIGLACONSPROCOL, :BDCODCCMPROCOL,

           :BDCODCLA, :BDGRUPOCLA,

           :BDCODMEN, :BDCODSINTRAB,

           :BDCODBAN, :BDCODAG, :BDCTADEPCOL, :BDDIGCTADEPCOL, :BDTIPOCTACOL, :BDMODOPAGTOCOL, :BDCARTAOSALCOL,

           :BDFORMAPAGTOCOL, :BDNRODEPIRCOL, :BDBASEIRRFADCOL, :BDVALORPREVPRIVNCOL, :BDVALORPREVPRIV13COL,

           :BDDATAOPCAOFGTSCOL, :BDCTAFGTSCOL, :BDCATEGORIACOL, :BDPERCFGTSCOL,
           :BDOCORRENCIACOL, :BDPERCRATCOL, :BDPERCDESCFPASCOL,

           :BDBASEINSSNCOL, :BDVALORINSSNCOL, :BDBASEIRRFNCOL, :BDVALORIRRFNCOL, :BDBASEINSS13COL,
           :BDVALORINSS13COL, :BDBASEIRRF13COL, :BDVALORIRRF13COL,

           :BDTIPOADMCOL, :BDNATUOCUPCOL, :BDDATAINIAQUICOL, :BDSALINICOL, :BDDIASPRAZO1COL,
           :BDDATAFIMPRAZO1COL, :BDDIASPRAZO2COL, :BDDATAFIMPRAZO2COL, :BDDESCCONTSINCOL, :BDVINCEMPCOL,
           :BDALVARACOL, :BDSINDICALIZADOCOL, :BDREGIMEPARCIALCOL, :BDFICHAREGCOL, :BDLIVROREGCOL,
           :BDNROFOLHAREGCOL,

           :BDTIPOCOL, :BDHORASMENSAISCOL, :BDHORASSEMANAISCOL, :BDHORASDIARIASCOL,
           :BDPERCINSALUBCOL , :BDINCIDINSALUBCOL, :BDPERCPERCULCOL, :BDINCIDPERICULCOL,
           :BDPERCNOTURNOCOL, :BDINCIDNOTURNOCOL, :BDNRODEPSALFAMCOL, :BDIGNORAFALTASFERCOL,
           :BDCALCADIANTACOL, :BDNAOARREDONDARCOL, :BDIMPETIQUETACOL, :BDCALCDSRRVCOL,
           :BDCALCDSRHECOL, :BDCALCDSRSALCOL, :BDCALCVALTRANSCOL, :BDCALCVALREFCOL,

           :BDOBSCOL,

           :BDCODGPS, :BDDESCINSSDOIRCOL,

           :BDCODMAS, :BDSALBASECOL,
           :BDCODPLAFUC, :BDCODTFUC, :BDCODQH,

           -- Rescisao
           :BDCODPRES,
           :BDDATARESCISAO,
           :BDDATAAVPREVIO,
           :BDDATAHOM,
           :BDDATAPAGRESCISAO,
           :BDSALDOFGTS,
           :BDCALCFGTSMESANT,
           :BDMAIORREMUNERACAO,
           :BDCHAVEINDENTIFICACAO,
           :BDDATAPAGGRFC,
           :BDREPOSICAOVAGA,
           :BDDISSIDIO,
           :BDDATADISSIDIO,
           :BDDESCANSOINDENIZADO,
           :BDCODMFGRESC,
           :BDCODSAQUERESC,
           :BDCODMRAISRESC,
           :BDCODMCAGRESC,
           :BDDESCPRES,
           :BDINIPRES,
           :BDJCPRES,
           :BDAVPREPRES,
           :BDGRRFPRES,
           :BDESTPRES,
           :BDINDFER13,
           :BDTERMCONTRPRES,
           :BDMULTAPRES,
           :BDDIASAVPREPRES,
           :BDDIASPAGPRES,
           :BDCODSEFMFGRESC,
           :BDDESCMFGRESC,
           :BDDESCSAQUERESC,
           :BDDESCMRAISRESC,
           :BDDESCMCAGEDRESC,

           --Transferencia
           :BDCODEMPDESTTRAN,
           :BDCODPTRAN,
           :BDCODCOLTRANS,
           :BDDATATRANS,
           :BDCODMCAGENTTRANS,
           :BDCODMCAGSAITRANS,
           :BDCODMFGTRANS,
           :BDCODMRAISTRANS,
           :BDDESCPTRANS,
           :BDCODSEFMFGTRANS,
           :BDDESCMFGTRANS,
           :BDDESCRAISTRANS,
           :BDDESCMCAGEDENTTRANS,
           :BDDESCMCAGEDSAITRANS
           DO

    SUSPEND;

   EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: VRH_SP_COLCON_DIA */
create or alter procedure VRH_SP_COLCON_DIA (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRDATINI date,
    PRDATFIM date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATACOL date,
    BDCODMAS integer,
    BDSALBASECOL numeric(15,6),
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDCODQH integer,
    BDTIPOESCALA integer)
as
declare variable WSQL varchar(32700);
BEGIN

  wsql = 'select DIA.BDCODEMP, DIA.bdcodcol, DIA.bddatacol, '||
                'DIACALC.BDCODMAS, DIACALC.BDSALBASECOL, '||
                'DIAVINC.BDCODPLAFUC, DIAVINC.BDCODTFUC, DIAVINC.BDCODQH, DIAVINC.BDTIPOESCALA ';

  wsql = wsql||'from VRH_EMP_TCOLCON_DIA DIA '||
               'left outer join VRH_EMP_TCOLCON_CALCDIA DIACALC on (DIA.BDCODEMP = DIACALC.BDCODEMP and DIA.BDCODCOL = DIACALC.BDCODCOL and DIA.bddatacol = DIACALC.BDDATACOL) '||
               'left outer join VRH_EMP_TCOL_VINCDIA DIAVINC on (DIA.BDCODEMP = DIAVINC.BDCODEMP and DIA.BDCODCOL = DIAVINC.BDCODCOL and DIA.bddatacol = DIAVINC.BDDATACOL) ';

  wsql = wsql||'where ((DIA.bddatacol between '''||prdatini||''' and '''||prdatfim||''') or ';

  wsql = wsql       ||'(DIA.bddatacol = (select max(bddatacol) '||
                                        'from VRH_EMP_TCOLCON_DIA S_DIA '||
                                        'where (S_DIA.BDCODEMP = DIA.BDCODEMP and '||
                                               'S_DIA.BDCODCOL = DIA.BDCODCOL and '||
                                               'S_DIA.bddatacol < '''||prdatini||''')))) ';

  IF (:prCODEMP IS NOT NULL) THEN
     BEGIN
--       wsql = wsql||' and (DIA.BDCODEMP in ('||prcodemp||'))';
       wsql = wsql||' and '||prcodemp;
     END

  IF (:prCODCOL IS NOT NULL) THEN
     BEGIN
--       wsql = wsql||' and (DIA.bdcodcol in ('||prcodcol||'))';
       wsql = wsql||' and '||prcodcol;
     END

  wsql = wsql||' order by DIA.BDCODEMP, DIA.bdcodcol, DIA.bddatacol';

   FOR EXECUTE STATEMENT wsql
     INTO
       :BDCODEMP, :bdcodcol, :bddatacol,
       :BDCODMAS, :BDSALBASECOL,
       :BDCODPLAFUC, :BDCODTFUC, :BDCODQH, :BDTIPOESCALA
     DO

  SUSPEND;

END^

/* Restore proc. body: VRH_SP_COLCON_EDIT */
ALTER PROCEDURE VRH_SP_COLCON_EDIT(BDCOL SMALLINT,
BDCON SMALLINT,
BDTER SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(100),
BDTIPO VARCHAR(15))
 AS
BEGIN

  IF (:bdcol IS NOT NULL AND :bdcon IS NOT NULL) THEN
     BEGIN
       FOR SELECT c.bdcodemp, c.bdcodcol, CAD.bdnomcol, CASE WHEN c.bdcontrcol = 0 THEN 'Colaborador' ELSE 'Contribuinte' END AS bdtipo
           FROM vrh_emp_tcolcon c
           LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD CAD ON CAD.BDCODEMP = C.BDCODEMP AND CAD.BDCODCOL = C.BDCODCOL
       INTO :bdcodemp, :bdcodcol, :bdnomcol, :bdtipo DO
       SUSPEND;
     END
  ELSE
     BEGIN
       IF (:bdcol IS NOT NULL) THEN
          BEGIN
            FOR SELECT c.bdcodemp, c.bdcodcol, CAD.bdnomcol, 'Colaborador' AS bdtipo
                FROM vrh_emp_tcolcon c
                LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD CAD ON CAD.BDCODEMP = C.BDCODEMP AND CAD.BDCODCOL = C.BDCODCOL
                WHERE c.bdcontrcol = 0
            INTO :bdcodemp, :bdcodcol, :bdnomcol, :bdtipo DO
            SUSPEND;
          END
    
       IF (:bdcon IS NOT NULL) THEN
          BEGIN
            FOR SELECT c.bdcodemp, c.bdcodcol, CAD.bdnomcol, 'Contribuinte' AS bdtipo
                FROM vrh_emp_tcolcon c
                LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD CAD ON CAD.BDCODEMP = C.BDCODEMP AND CAD.BDCODCOL = C.BDCODCOL
                WHERE c.bdcontrcol = 1
            INTO :bdcodemp, :bdcodcol, :bdnomcol, :bdtipo DO
            SUSPEND;
          END
     END

  IF (:bdter IS NOT NULL) THEN
     BEGIN
       FOR SELECT 0 AS bdcodemp, bdcodter, bdnomter, 'Terceiro' AS tipo FROM vw_vrh_base_tterc
           ORDER BY bdcodter
       INTO :bdcodemp, :bdcodcol, :bdnomcol, :bdtipo DO
       SUSPEND;
     END
END
^

/* Restore proc. body: VRH_SP_COLCON_VERBAS_ASS */
ALTER PROCEDURE VRH_SP_COLCON_VERBAS_ASS(PRDIAINI INTEGER,
PRMESINI INTEGER,
PRANOINI INTEGER,
PRDIAFIM INTEGER,
PRMESFIM INTEGER,
PRANOFIM INTEGER)
 RETURNS(BDDIAINI INTEGER,
BDMESINI INTEGER,
BDANOINI INTEGER,
BDDIAFIM INTEGER,
BDMESFIM INTEGER,
BDANOFIM INTEGER,
BDCODVER INTEGER,
BDFORMREF BLOB,
BDFORMVAL BLOB)
 AS
BEGIN
  /* Procedure Text */
  SUSPEND;
END
^

/* Restore proc. body: VRH_SP_CONS_CBO_SIN */
ALTER PROCEDURE VRH_SP_CONS_CBO_SIN RETURNS(BDCODCBO INTEGER,
BDCODCBOTSIN INTEGER,
BDDESCCBO VARCHAR(70))
 AS
BEGIN
  FOR SELECT CBO, SIN, DESCR FROM (
      SELECT C.bdcodcbo AS CBO, 0 AS SIN, C.bddesccbo AS DESCR
             FROM VRH_BASE_TCBO C
      UNION
      SELECT CS.bdcodcbo AS CBO, CS.bdcodcbotsin AS SIN, CS.bddesccbotsin AS DESCR
             FROM VRH_BASE_CBO_TSIN CS )

  ORDER BY CBO, SIN
  INTO :BDCODCBO, :BDCODCBOTSIN, :BDDESCCBO DO

  SUSPEND;

END
^

/* Restore proc. body: VRH_SP_CONS_COL */
ALTER PROCEDURE VRH_SP_CONS_COL(WREFERENCIA INTEGER,
WEMPRESA INTEGER,
WFILTRO VARCHAR(500),
PRULTDIAMES DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDCODCLA INTEGER,
BDDATAADMCOL DATE,
BDGRUPOCLA INTEGER,
BDTIPOCOL INTEGER,
BDDATARESCISAO DATE,
BDDESCCLA VARCHAR(40),
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDSALBASECOL NUMERIC(15,6),
BDCODSIT INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(2000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(wReferencia, NULL, prultdiames);


  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCAD.BDNOMCOL, COLCON.BDDATAADMCOL, COLCON_REF.BDCODCLA, COLCON_REF.BDGRUPOCLA, COLCON_REF.BDTIPOCOL, RESC.BDDATARESCISAO, CLA.BDDESCCLA, '||
         'COLCON_DOC.BDCPFCOL, DOCREF.BDPISCOL, COLCON_DIA.BDSALBASECOL, sit.bdcodsit ' ;
  wsql = wsql || 'from VRH_EMP_TCOLCON COLCON ';
  wsql = wsql || 'left outer join VRH_EMP_TCOLCON_DOC COLCON_DOC on (COLCON_DOC.BDCODEMP = COLCON.BDCODEMP and COLCON_DOC.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VW_COLABORADORES_REF_ATUAL COLCON_REF ';
  wsql = wsql || 'on (COLCON_REF.BDCODEMP = COLCON.BDCODEMP and COLCON_REF.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VW_TCOLCON_CALCDIA COLCON_DIA ';
  wsql = wsql || 'on (COLCON_DIA.BDCODEMP = COLCON.BDCODEMP and COLCON_DIA.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC ';
  wsql = wsql || 'on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VRH_BASE_TCLASSE CLA ';
  wsql = wsql || 'on (CLA.BDCODCLA = COLCON_REF.BDCODCLA) ';
  wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COLCON.BDCODEMP and COLCAD.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = COLCON.BDCODEMP and DOCREF.BDCODCOL = COLCON.BDCODCOL) ';


  wsql = wsql||'left outer join (select sit.bdcodemp,sit.bdcodcol, max(sit.bdcodsit) bdcodsit from vrh_sp_dados_situacao(';

  IF ((wempresa IS NOT NULL) OR (wempresa <> 0)) THEN
     wsql = wsql||''''||'sit.BDCODEMP = '||wempresa||''''; /* empresa sit */
  ELSE
     wsql = wsql||''''||''''; /* empresa sit */

  wsql = wsql||','||''''||''''||','; /* colaborador sit */
  wsql = wsql||''''||SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 1 FOR 4)||''''||',';   /* data inicial  */
  wsql = wsql||''''||prultdiames||''''||') sit group by sit.bdcodemp,sit.bdcodcol) sit on (colcon.bdcodemp = sit.bdcodemp and colcon.bdcodcol = sit.bdcodcol) ';

  wsql = wsql || 'where ';
  wsql = wsql || '(COLCON.bdcodemp = ' || :wempresa || ' or ' || :wempresa || '= 0) ';

  IF (wfiltro IS NOT NULL) THEN
     wsql = wsql || ' and ' || wfiltro;

  wsql = wsql || 'order by COLCON.BDCODCOL';

  FOR EXECUTE STATEMENT
    wSQL
  INTO
    :bdcodemp, :BDCODCOL, :BDNOMCOL, :BDDATAADMCOL, :BDCODCLA, :BDGRUPOCLA, :BDTIPOCOL, :BDDATARESCISAO, :BDDESCCLA, :BDCPFCOL, :BDPISCOL, :BDSALBASECOL, :bdcodsit
  DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: VRH_SP_CONS_COL_NOVO */
create or alter procedure VRH_SP_CONS_COL_NOVO (
    WREFERENCIA integer,
    WEMPRESA integer,
    WFILTRO varchar(500),
    PRULTDIAMES date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDCODCLA integer,
    BDDATAADMCOL date,
    BDGRUPOCLA integer,
    BDTIPOCOL integer,
    BDDATARESCISAO date,
    BDDESCCLA varchar(40),
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDSALBASECOL numeric(15,6),
    BDCODSIT integer,
    BDCODPRES integer,
    BDDESCPRES varchar(110),
    BDCODTFUC integer,
    BDDESCTFUC varchar(40),
    BDSTATUSQC integer,
    BDSTATUS_ES integer,
    BDCODTIPO integer,
    BDINTESOCIAL integer,
    BDDATAEVENTO date,
    BDMATRICULA varchar(30),
    BDDATAENTRADA date,
    BDGERARNMSOCIAL varchar(5),
    BDNMSOCIAL varchar(100),
    BDNOVADATAADMRT date,
    BDNOVADATARESCISAO date,
    BDNOVOCODPRES integer,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
declare variable WSQL varchar(30000);
declare variable WDIA varchar(10);
declare variable WMES varchar(10);
declare variable WANO varchar(10);
declare variable WMMDDAAAA varchar(10);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(wReferencia, NULL, prultdiames);


  WDIA = substring(prultdiames from 9);
  WMES = substring(wreferencia from 5 for 2);
  WANO = substring(wreferencia from 1 for 4);
  WMMDDAAAA = WMES||'-'||WDIA||'-'||WANO; --data completa com o ultimo dia do mês, subsitui onde estava o "prULTDIAMES" nos substrings abaixo
                                          --também servem nos "where" ao decorrer

  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCAD.BDNOMCOL, COLCON.BDDATAADMCOL, COLCON_REF.BDCODCLA, '||
                'COLCON_REF.BDGRUPOCLA, calc.BDTIPOCOL, RESC.BDDATARESCISAO, COLCON_REF.BDDESCCLA, COLCON_DOC.BDCPFCOL, '||
                'DOCREF.BDPISCOL, CDIA.BDSALBASECOL, ';

  wsql = wsql || '(';
  wsql = wsql || 'select max(bdcodsit) from VRH_EMP_TSITCOL SIT where ';
  IF (wempresa IS NOT NULL AND wempresa <> 0) THEN
     wsql = wsql||'BDCODEMP = '||wempresa||' and ';

  wsql = wsql||'SIT.bdCODEMP = COLCON.BDCODEMP and SIT.bdCODCOL = COLCON.BDCODCOL ' ;
  wsql = wsql || '  and ' ;
  wsql = wsql || ' ((sit.BDDATAINISEFIP between ''' || SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 1 FOR 4)|| ''' AND ''' || WMMDDAAAA || ''') or ' ;
  wsql = wsql || '  (sit.BDDATAFIMSIT   between ''' || SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 1 FOR 4)|| ''' AND ''' || WMMDDAAAA || ''') or ' ;
  wsql = wsql || '  (sit.BDDATAINISEFIP < '''       || SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 1 FOR 4)|| ''' and (sit.BDDATAFIMSIT is null or sit.BDDATAFIMSIT > ''' || WMMDDAAAA || '''))) ' ;
  wsql = wsql || ') as bdCODSIT, RESC.BDCODPRES, PRESC.BDDESCPRES, VDIA.BDCODTFUC, FUC.BDDESCTFUC, COLCON.BDSTATUSQC, COLCON.BDSTATUS_ES, COLCON.BDCODTIPO, ';
  wsql = wsql || 'case when not INTES.BDDATACONS is null then 3 else 2 end BDINTESOCIAL, ';
  wsql = wsql || '(select max(ESOCIAL.BDDATAEVENTO) BDDATAEVENTO';
  wsql = wsql || '       from VRH_ESOCIAL_TARQUIVO ESOCIAL';
  wsql = wsql || '       where ESOCIAL.BDCODEMP = COLCON.BDCODEMP and';
  wsql = wsql || '             ESOCIAL.BDCODCOL = COLCON.BDCODCOL and';
  wsql = wsql || '             ESOCIAL.BDCODTIPO = 26 and';
  wsql = wsql || '             ESOCIAL.BDDATAEVENTO = TRANS.BDDATATRF and';
  wsql = wsql || '             ESOCIAL.BDSTATUS = 2) BDDATAEVENTO, ';
  wsql = wsql || 'COLCON.BDMATRICULA, TRANS.BDDATATRF, case when FIS.BDGERARNMSOCIAL = ''TRUE'' then ''Sim'' else ''Não'' end BDGERARNMSOCIAL, FIS.BDNMSOCIAL, adm.BDNOVADATAADMRT, RESC.BDNOVADATARESCISAO, RESC.BDNOVOCODPRES, ';
  wsql = wsql || 'vinc.BDCODCENTRO, vinc.BDCODTPCC ';
  wsql = wsql || 'from (select COLCON.* from VRH_EMP_TCOLCON COLCON ';

  IF (wempresa IS NOT NULL AND wempresa <> 0) THEN
     wsql = wsql||' where COLCON.BDCODEMP = '||wempresa;

  wsql = wsql||') COLCON ';
  wsql = wsql || 'left outer join VRH_EMP_TCOLCON_DOC COLCON_DOC on (COLCON_DOC.BDCODEMP = COLCON.BDCODEMP and COLCON_DOC.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join (select BDCODEMP, BDCODCOL, max(BDREFCOL) as BDREFCOL ';
  wsql = wsql ||                  'from VRH_EMP_TCOLCON_VINC ';

  if (:wempresa > 0) then
    wsql = wsql || 'where BDCODEMP = '||:wempresa;

  wsql = wsql || 'group by BDCODEMP, BDCODCOL) vinc_x on (vinc_x.BDCODEMP = COLCON.BDCODEMP and vinc_x.BDCODCOL = COLCON.BDCODCOL) ';

  wsql = wsql || 'left outer join VRH_EMP_TCOLCON_VINC vinc on (vinc.BDCODEMP = COLCON.BDCODEMP and vinc.BDCODCOL = COLCON.BDCODCOL and vinc.BDREFCOL = vinc_x.BDREFCOL) ';

  wsql = wsql || 'left outer join (select BDCODEMP, BDCODCOL, max(BDREFCOL) as BDREFCOL ';
  wsql = wsql ||                  'from VRHF_EMP_TCOL_CALC ';

  if (:wempresa > 0) then
    wsql = wsql || 'where BDCODEMP = '||:wempresa;

  wsql = wsql || 'group by BDCODEMP, BDCODCOL) calc_x on (calc_x.BDCODEMP = COLCON.BDCODEMP and calc_x.BDCODCOL = COLCON.BDCODCOL) ';

  wsql = wsql || 'left outer join VRHF_EMP_TCOL_CALC calc on (calc.BDCODEMP = COLCON.BDCODEMP and calc.BDCODCOL = COLCON.BDCODCOL and calc.BDREFCOL = calc_x.BDREFCOL) ';
  wsql = wsql || 'left outer join VRH_EMP_TCOL_ADM adm on (ADM.BDCODEMP = COLCON.BDCODEMP and ADM.BDCODCOL = COLCON.BDCODCOL) ';

  wsql = wsql || 'left join(select BDCODEMP, BDCODCOL, max(BDDATACOL) BDDATACOL ';
  wsql = wsql ||      'from VRH_EMP_TCOLCON_DIA COLCON_DIA ';

  if (:wempresa > 0) then
    wsql = wsql || 'where BDCODEMP = '||:wempresa;

  wsql = wsql ||      ' group by BDCODEMP, BDCODCOL) DIA_X on (DIA_X.BDCODEMP = COLCON.BDCODEMP and DIA_X.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VRH_EMP_TCOLCON_DIA COLCON_DIA on (COLCON_DIA.BDCODEMP = COLCON.BDCODEMP and ';
  wsql = wsql ||                                                    'COLCON_DIA.BDCODCOL = COLCON.BDCODCOL and ';
  wsql = wsql ||                                                    'COLCON_DIA.BDDATACOL = DIA_X.BDDATACOL) ';
--wsql = wsql || 'left outer join VW_TCOLCON_DIA_ATUAL COLCON_DIA on (COLCON_DIA.BDCODEMP = COLCON.BDCODEMP and COLCON_DIA.BDCODCOL = COLCON.BDCODCOL) ';
-- substituido a view pela tabela

  wsql = wsql || 'left outer join VRH_EMP_TCOLCON_CALCDIA CDIA on (CDIA.BDCODEMP = COLCON_DIA.BDCODEMP and CDIA.BDCODCOL = COLCON_DIA.BDCODCOL and CDIA.BDDATACOL = (select max(BDDATACOL) from VRH_EMP_TCOLCON_CALCDIA DD where DD.BDCODEMP = CDIA.BDCODEMP and DD.BDCODCOL = CDIA.BDCODCOL and DD.BDDATACOL <= DIA_X.BDDATACOL ) and '||
                                                                  'CDIA.BDDATAEFEITO = (SELECT max(BDDATAEFEITO) FROM VRH_EMP_TCOLCON_CALCDIA where BDCODEMP = CDIA.BDCODEMP and BDCODCOL = CDIA.BDCODCOL and BDDATACOL = CDIA.BDDATACOL)) ';
  wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VRH_BASE_TCLASSE COLCON_REF on (COLCON_REF.BDCODCLA = vinc.BDCODCLA) ';
  wsql = wsql || 'left outer join VRH_BASE_TPREPRESC PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES) ';
  wsql = wsql || 'left outer join VRH_EMP_TCOL_VINCDIA VDIA on (VDIA.BDCODEMP = COLCON.BDCODEMP) and (VDIA.BDCODCOL = COLCON.BDCODCOL) and (VDIA.BDDATACOL = COLCON_DIA.BDDATACOL) ';
  wsql = wsql || 'left outer join VRH_FUNCOES_TFUC FUC on (FUC.BDCODPLAFUC = VDIA.BDCODPLAFUC) and (FUC.BDCODTFUC = VDIA.BDCODTFUC) ';

  wsql = wsql || 'left outer join(select BDCODEMP, BDCODCOL, max(BDREFCOL) BDREFCOL ';
  wsql = wsql ||                 'from VRH_EMP_TCOLCON_CAD ';

  if (:wempresa > 0) then
    wsql = wsql || 'where BDCODEMP = '||:wempresa;

  wsql = wsql ||                 ' group by BDCODEMP, BDCODCOL) CAD_X on (CAD_X.BDCODEMP = COLCON.bdcodemp and CAD_X.BDCODCOL = COLCON.bdcodcol) ';
  wsql = wsql || 'left outer join VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.bdcodemp = COLCON.bdcodemp ';
  wsql = wsql ||                                            'and COLCAD.bdcodcol = COLCON.bdcodcol ';
  wsql = wsql ||                                            'and COLCAD.bdrefcol = CAD_X.bdrefcol) ';

  wsql = wsql || 'left outer join(select BDCODEMP, BDCODCOL, max(BDREFCOL) BDREFCOL ';
  wsql = wsql ||                 'from VRH_EMP_TCOLCON_DOCREF ';

   if (:wempresa > 0) then
    wsql = wsql || 'where BDCODEMP = '||:wempresa;

  wsql = wsql ||                 ' group by BDCODEMP, BDCODCOL) REF_X on (REF_X.BDCODEMP = COLCON.BDCODEMP ';
  wsql = wsql ||                                                              'and REF_X.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left join VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = COLCON.BDCODEMP ';
  wsql = wsql ||                                    'and DOCREF.BDCODCOL = COLCON.BDCODCOL ';
  wsql = wsql ||                                    'and DOCREF.BDREFCOL = REF_X.BDREFCOL) ';

  wsql = wsql || 'left outer join (select BDCODEMP, BDCODCOL, max(BDREFCOL) as BDREFCOL ';
  wsql = wsql ||                  'from VRH_EMP_TCOLCON_FIS ';

   if (:wempresa > 0) then
    wsql = wsql || 'where BDCODEMP = '||:wempresa;

  wsql = wsql || 'group by BDCODEMP, BDCODCOL) fis_x on (fis_x.BDCODEMP = COLCON.BDCODEMP and fis_x.BDCODCOL = COLCON.BDCODCOL) ';

  wsql = wsql || 'left join VRH_EMP_TCOLCON_FIS FIS on (FIS.BDCODEMP = COLCON.BDCODEMP and FIS.BDCODCOL = COLCON.BDCODCOL and FIS.BDREFCOL = fis_x.BDREFCOL) ';

  wsql = wsql || 'left outer join VRH_EMP_TCOLCON_ES INTES on (INTES.BDCODEMP = COLCON.BDCODEMP and INTES.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || 'left outer join VRH_EMP_TTRANSCOL TRANS on (TRANS.BDCODEMPDEST = COLCON.BDCODEMP and TRANS.BDCODCOLDEST = COLCON.BDCODCOL) ';

  IF ((wempresa IS NOT NULL) OR (wempresa <> 0)) THEN
  BEGIN
    wsql = wsql || 'where ';
    wsql = wsql || '(COLCON.bdcodemp = ' || :wempresa || ' or ' || :wempresa || '= 0) ';

    IF ((wfiltro IS NOT NULL) AND (wfiltro <> '')) THEN
       wsql = wsql || ' and ' || wfiltro;
  END
  ELSE
  BEGIN
    IF ((wfiltro IS NOT NULL) AND (wfiltro <> '')) THEN
       wsql = wsql || ' where ' || wfiltro;
  END

  FOR EXECUTE STATEMENT
    wSQL
  INTO
    :bdcodemp, :BDCODCOL , :BDNOMCOL  , :BDDATAADMCOL, :BDCODCLA  , :BDGRUPOCLA, :BDTIPOCOL  , :BDDATARESCISAO, :BDDESCCLA   , :BDCPFCOL, :BDPISCOL, :BDSALBASECOL,
    :BDCODSIT, :BDCODPRES, :BDDESCPRES, :BDCODTFUC   , :BDDESCTFUC, :BDSTATUSQC, :BDSTATUS_ES, :BDCODTIPO     , :BDINTESOCIAL, :BDDATAEVENTO, :BDMATRICULA, :BDDATAENTRADA,
    :BDGERARNMSOCIAL, :BDNMSOCIAL,
    :BDNOVADATAADMRT, :BDNOVADATARESCISAO, :BDNOVOCODPRES, :BDCODCENTRO, :BDCODTPCC
  DO
    BEGIN
      if (:BDDATAEVENTO is not null) then
         BDINTESOCIAL = 3;

  SUSPEND;
    END

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

/* Restore proc. body: VRH_SP_CONS_COLCON */
ALTER PROCEDURE VRH_SP_CONS_COLCON(WREFERENCIA INTEGER,
WEMPRESA INTEGER,
PRULTDIAMES DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADMCOL DATE,
BDTIPOCOL INTEGER,
BDCODCLA INTEGER,
BDDATARESCISAO DATE,
BDDESCCLA VARCHAR(40),
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDSALBASECOL NUMERIC(15,6),
BDCODSIT INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WWHERE VARCHAR(5000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(wreferencia, NULL, prultdiames);

  wsql = 'select ' ||
         'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCAD.BDNOMCOL, COLCON.BDDATAADMCOL, COLCON_CALC.BDTIPOCOL, COLVINC.BDCODCLA, RESC.BDDATARESCISAO, ' ||
         'CLA.BDDESCCLA, COLCON_DOC.BDCPFCOL, DOCREF.BDPISCOL, COLCON_DIA.BDSALBASECOL, ';

wsql = wsql || '( ';
wsql = wsql || '  select max(bdcodsit) from VRH_EMP_TSITCOL SIT where SIT.bdCODEMP= COLCON.BDCODEMP and SIT.bdCODCOL=COLCON.BDCODCOL ' ;
wsql = wsql || '  and ' ;
wsql = wsql || '  ((sit.BDDATAINISEFIP between ''' || SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 1 FOR 4)||''' AND ''' || prultdiames || ''') or ' ;
wsql = wsql || '  (sit.BDDATAFIMSIT between ''' || SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 1 FOR 4)|| ''' AND ''' || prultdiames || ''') or ' ;
wsql = wsql || '  (sit.BDDATAINISEFIP < ''' || SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wreferencia AS VARCHAR(6)) FROM 1 FOR 4)|| ''' and (sit.BDDATAFIMSIT is null or sit.BDDATAFIMSIT > ''' || prultdiames || '''))) ' ;
wsql = wsql || ') as bdCODSIT ';

wsql = wsql || 'from vrh_emp_tcolcon COLCON ' ||
         'join VRH_EMP_TCOLCON_DOC COLCON_DOC on (COLCON_DOC.BDCODEMP = COLCON.BDCODEMP and COLCON_DOC.BDCODCOL = COLCON.BDCODCOL) ' ||
         'left outer join VW_VRHF_EMP_TCOL_CALC COLCON_CALC on (COLCON_CALC.bdcodemp = COLCON.bdCODEMP and COLCON_CALC.bdcodcol = COLCON.bdCODCOL) ' ||
         'left outer join VW_VRH_EMP_TCOLCON_VINC COLVINC on (COLVINC.bdcodemp = COLCON.bdcodemp and COLVINC.bdcodcol = COLCON.bdcodcol) ' ||
         'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ' ||
         'left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = COLVINC.BDCODCLA) ' ||
         'left outer join VW_TCOLCON_CALCDIA COLCON_DIA on (COLCON_DIA.BDCODEMP = COLCON.BDCODEMP and COLCON_DIA.BDCODCOL = COLCON.BDCODCOL) ' ||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COLCON.BDCODEMP and COLCAD.BDCODCOL = COLCON.BDCODCOL) ' ||
         'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = COLCON.BDCODEMP and DOCREF.BDCODCOL = COLCON.BDCODCOL) ';

  wwhere = '';

  IF (wempresa IS NOT NULL AND wempresa <> 0) THEN
     wwhere = wwhere||'COLCON.BDCODEMP = '||wempresa;

  IF (wwhere <> '') THEN
     wwhere = 'where '||wwhere;

  wsql = wsql||wwhere;
  --wsql = wsql||'order by COLCON.BDCODCOL ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :BDCODCOL,
    :BDNOMCOL,
    :BDDATAADMCOL,
    :BDTIPOCOL,
    :BDCODCLA,
    :BDDATARESCISAO,
    :BDDESCCLA,
    :BDCPFCOL,
    :BDPISCOL,
    :BDSALBASECOL,
    :BDCODSIT
  DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
/*
  execute procedure sp_seta_competencia(wreferencia, null, prultdiames);

 wsql = 'select ' ||
         'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDNOMCOL, COLCON.BDDATAADMCOL, COLCON_CALC.BDTIPOCOL, COLVINC.BDCODCLA, RESC.BDDATARESCISAO, ' ||
         'CLA.BDDESCCLA, COLCON_DOC.BDCPFCOL, COLCON_DOC.BDPISCOL, COLCON_DIA.BDSALBASECOL, sit.bdcodsit ' ||
         'from vrh_emp_tcolcon COLCON ' ||
         'join VRH_EMP_TCOLCON_DOC COLCON_DOC on (COLCON_DOC.BDCODEMP = COLCON.BDCODEMP and COLCON_DOC.BDCODCOL = COLCON.BDCODCOL) ' ||
         'left outer join VW_VRHF_EMP_TCOL_CALC COLCON_CALC on (COLCON_CALC.bdcodemp = COLCON.bdCODEMP and COLCON_CALC.bdcodcol = COLCON.bdCODCOL) ' ||
         'left outer join VW_VRH_EMP_TCOLCON_VINC COLVINC on (COLVINC.bdcodemp = COLCON.bdcodemp and COLVINC.bdcodcol = COLCON.bdcodcol) ' ||
         'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COLCON.BDCODEMP and RESC.BDCODCOL = COLCON.BDCODCOL) ' ||
         'left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = COLVINC.BDCODCLA) ' ||
         'left outer join VW_TCOLCON_CALCDIA COLCON_DIA on (COLCON_DIA.BDCODEMP = COLCON.BDCODEMP and COLCON_DIA.BDCODCOL = COLCON.BDCODCOL) ';

  wsql = wsql||'left outer join (select sit.bdcodemp,sit.bdcodcol, max(sit.bdcodsit) bdcodsit from vrh_sp_dados_situacao(';

  if ((wempresa is not null) or (wempresa <> 0)) then
     wsql = wsql||''''||'sit.BDCODEMP = '||wempresa||''''; -- empresa sit
  else
     wsql = wsql||''''||''''; -- empresa sit

  wsql = wsql||','||''''||''''||','; -- colaborador sit
  wsql = wsql||''''||substring(cast(wreferencia as varchar(6)) from 5 for 2)||'-01-'||substring(cast(wreferencia as varchar(6)) from 1 for 4)||''''||',';   -- data inicial
  wsql = wsql||''''||prultdiames||''''||') sit group by sit.bdcodemp,sit.bdcodcol) sit on (colcon.bdcodemp = sit.bdcodemp and colcon.bdcodcol = sit.bdcodcol) ';

  wwhere = '';

  if (wempresa is not null and wempresa <> 0) then
     wwhere = wwhere||'COLCON.BDCODEMP = '||wempresa;

  if (wwhere <> '') then
     wwhere = 'where '||wwhere;

  wsql = wsql||wwhere;
  wsql = wsql||'order by COLCON.BDCODCOL ';

  for execute statement wsql
  into
    :bdcodemp,
    :BDCODCOL,
    :BDNOMCOL,
    :BDDATAADMCOL,
    :BDTIPOCOL,
    :BDCODCLA,
    :BDDATARESCISAO,
    :BDDESCCLA,
    :BDCPFCOL,
    :BDPISCOL,
    :BDSALBASECOL,
    :BDCODSIT
  do

  suspend;

  execute procedure sp_seta_competencia(null, null, null);
  */
END
^

/* Restore proc. body: VRH_SP_CONS_CON */
create or alter procedure VRH_SP_CONS_CON (
    WREFERENCIA integer,
    WEMPRESA integer,
    WFILTRO varchar(500))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDDATAADMCOL date,
    BDCODCLA integer,
    BDGRUPOCLA integer,
    BDDESCCLA varchar(40),
    BDDATARESCISAO date,
    BDSALBASECOL numeric(18,6),
    BDCODPRES integer,
    BDDESCPRES varchar(110),
    BDSTATUSQC integer,
    BDSTATUS_ES integer,
    BDCODTIPO integer,
    BDPISCOL varchar(14),
    BDCPFCOL varchar(14),
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
declare variable WWHERE varchar(1000);
declare variable WSQL varchar(3000);
BEGIN
  wsql = 'select ';
  wsql = wsql || ' COLCON.BDCODEMP, COLCON.BDCODCOL, COLCAD.BDNOMCOL, COLCON.BDDATAADMCOL, COLCON_VINC.BDCODCLA, COLCONV.bdgrupocla, COLCONV.BDDESCCLA,';
  wsql = wsql || ' RESC.BDDATARESCISAO, RESC.BDCODPRES, PRESC.BDDESCPRES, COLCON.BDSTATUSQC, COLCON.BDSTATUS_ES, COLSAL.BDSALBASECOL, COLCON.BDCODTIPO,DOCREF.BDPISCOL,DOC.BDCPFCOL, ';
  wsql = wsql || ' COLCON_VINC.BDCODCENTRO, COLCON_VINC.BDCODTPCC ';
  wsql = wsql || ' from vrh_emp_tcolcon COLCON';
  wsql = wsql || ' left outer join VW_VRH_EMP_TCOLCON_VINC COLCON_VINC on (COLCON_VINC.BDCODEMP = COLCON.BDCODEMP and COLCON_VINC.BDCODCOL = COLCON.BDCODCOL)';
  wsql = wsql || ' left outer join VRH_BASE_TCLASSE COLCONV on (COLCON_VINC.bdcodcla = COLCONV.bdcodcla)';
  wsql = wsql || ' left outer join vrh_emp_trescisao RESC on (COLCON.bdcodemp = RESC.bdcodemp and COLCON.BDCODCOL = RESC.BDCODCOL)';
  wsql = wsql || ' left outer join vrh_base_tprepresc PRESC on (PRESC.bdcodpres = RESC.bdcodpres)';
  wsql = wsql || ' left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COLCON.BDCODEMP and COLCAD.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || ' left outer join VW_TCOLCON_CALCDIA COLSAL on (COLSAL.BDCODEMP = COLCON.BDCODEMP and COLSAL.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || ' left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = COLCON.BDCODEMP and DOCREF.BDCODCOL = COLCON.BDCODCOL) ';
  wsql = wsql || ' left outer join VRH_EMP_TCOLCON_DOC DOC on (DOC.BDCODEMP = COLCON.BDCODEMP and DOC.BDCODCOL = COLCON.BDCODCOL) ';


  wWhere = '';
  IF ((wempresa IS NOT NULL) OR (wempresa > 0)) THEN
    wWhere = wWhere || 'COLCON.bdcodemp = ' || :wempresa;

  IF ((wFiltro IS NOT NULL) AND (wFiltro <> '')) THEN
  BEGIN
    IF (wWhere <> '') THEN
      wWhere = wWhere || ' and ';

    wWhere = wWhere || wfiltro;
  END

  IF (wWhere <> '') THEN
    wsql = wsql || ' where ' || wWhere;

  FOR EXECUTE STATEMENT
    wSQL
  INTO
    :BDCODEMP, :BDCODCOL, :BDNOMCOL, :BDDATAADMCOL, :BDCODCLA, :BDGRUPOCLA, :BDDESCCLA, :BDDATARESCISAO, :BDCODPRES, :BDDESCPRES, :BDSTATUSQC, :BDSTATUS_ES, :BDSALBASECOL, :BDCODTIPO, :bdpiscol, :bdcpfcol, :BDCODCENTRO, :BDCODTPCC
  DO

  SUSPEND;
END^



/* Restore proc. body: VRH_SP_CONS_FERIAS_PER_AQUIS */
create or alter procedure VRH_SP_CONS_FERIAS_PER_AQUIS (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDINIPERGOZOFE date,
    BDFIMPERAQUISFE date,
    BDFIMPERGOZOFE date,
    BDDATAPAGFE date,
    BDQTDGOZOFE numeric(18,6),
    BDQTDABONOFE numeric(18,6),
    BDSALDOINIFE numeric(15,6),
    BDSALDOFIMFE numeric(15,6),
    BDBASEIRFE numeric(15,6),
    BDALIQIRFE numeric(15,6),
    BDVALORIRFE numeric(15,6),
    BDBASEINSSFE numeric(15,6),
    BDALIQINSSFE numeric(15,6),
    BDVALORINSSFE numeric(15,6),
    BDDEPFE numeric(15,6),
    BDSALBASEFE numeric(15,6),
    BDSALBASEHEFE numeric(15,6),
    BDDATABAIXAFE date,
    BDCOLETIVASFE varchar(5),
    BDREFPAGABOFE integer,
    BDFALTASFE numeric(15,6),
    BDNOMEMP DM_BDNOMEMP,
    BDNOMCOL DM_BDNOMCOL,
    BDSALDOFINALSINDFE numeric(18,6),
    BDCALCA13FE varchar(5),
    BDTIPOA13FE integer,
    BDPERCA13FE numeric(18,6),
    BDRECIBOESOCIAL varchar(30),
    BDINIGOZORECIBOFE date,
    BDFIMGOZORECIBOFE date,
    BDQTDGOZORECIBOFE numeric(18,6),
    BDISTRANSFERENCIA boolean)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(15000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref,  NULL, NULL);

  wsql = 'select FER.BDCODEMP, FER.BDCODCOL, FER.BDINIPERAQUISFE, FER.BDCODFE, FER.BDINIPERGOZOFE, FER.BDFIMPERAQUISFE, '||
                'FER.BDFIMPERGOZOFE, FER.BDDATAPAGFE, FER.BDQTDGOZOFE, FER.BDQTDABONOFE, FER.BDSALDOINIFE, '||
                'FER.BDSALDOFIMFE, FER.BDBASEIRFE, FER.BDALIQIRFE, FER.BDVALORIRFE, FER.BDBASEINSSFE, FER.BDALIQINSSFE, '||
                'FER.BDVALORINSSFE, FER.BDDEPFE, FER.BDSALBASEFE, FER.BDSALBASEHEFE, FER.BDDATABAIXAFE, FER.BDCOLETIVASFE, '||
                'FER.BDREFPAGABOFE, FER.BDFALTASFE, EMP.BDNOMEMP, COL.BDNOMCOL, FER.BDSALDOFINALSINDFE, '||
                'FER.BDCALCA13FE, FER.BDTIPOA13FE, FER.BDPERCA13FE, ARQ.BDRECIBO BDRECIBOESOCIAL, '||
                'FER.BDINIGOZORECIBOFE, FER.BDFIMGOZORECIBOFE, FER.BDQTDGOZORECIBOFE, FER.BDISTRANSFERENCIA ';

  wsql = wsql || 'from VRH_EMP_TFERIAS FER '||
                 'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
                    'on (EMP.BDCODEMP = FER.BDCODEMP) '||
                 'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
                    'on (COL.BDCODEMP = FER.BDCODEMP and COL.BDCODCOL = FER.BDCODCOL) '||
                 'left outer join VRH_ESOCIAL_TARQUIVO ARQ ' || 
                    ' on ARQ.BDCODEMP = FER.BDCODEMP and ARQ.BDCODCOL = FER.BDCODCOL and ARQ.BDCODIGO = FER.BDCODEVT';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (wwhere <> '') THEN
     BEGIN
       wwhere = ' where '||wwhere;
       wsql = wsql||wwhere;
     END

  FOR EXECUTE STATEMENT wsql
  INTO :BDCODEMP, :BDCODCOL, :BDINIPERAQUISFE, :BDCODFE, :BDINIPERGOZOFE, :BDFIMPERAQUISFE,
       :BDFIMPERGOZOFE, :BDDATAPAGFE, :BDQTDGOZOFE, :BDQTDABONOFE, :BDSALDOINIFE,
       :BDSALDOFIMFE, :BDBASEIRFE, :BDALIQIRFE, :BDVALORIRFE, :BDBASEINSSFE, :BDALIQINSSFE,
       :BDVALORINSSFE, :BDDEPFE, :BDSALBASEFE, :BDSALBASEHEFE, :BDDATABAIXAFE, :BDCOLETIVASFE,
       :BDREFPAGABOFE, :BDFALTASFE, :BDNOMEMP, :BDNOMCOL, :BDSALDOFINALSINDFE,
       :BDCALCA13FE, :BDTIPOA13FE, :BDPERCA13FE, :BDRECIBOESOCIAL,
       :BDINIGOZORECIBOFE, :BDFIMGOZORECIBOFE, :BDQTDGOZORECIBOFE, :BDISTRANSFERENCIA
  DO

  SUSPEND;

END^

/* Restore proc. body: VRH_SP_CONS_VERBAS */
create or alter procedure VRH_SP_CONS_VERBAS (
    WREFERENCIA integer,
    WVERBAS varchar(32700),
    WTAMANHOCLASSE integer)
returns (
    BDCODVER integer,
    BDCLAVER varchar(20),
    BDAPEVER varchar(20),
    BDDESCVER varchar(40),
    BDDESCREDVER varchar(20),
    BDORDEMVER integer,
    BDINATIVAVER varchar(5),
    BDSITVER integer,
    BDTIPOVER integer,
    BDTIPOCODVER integer,
    BDINSSVER integer,
    BDIRVER integer,
    BDFGTSVER integer,
    BDTIPOREFVER integer,
    BDBASESFVER integer,
    BDPISVER varchar(5),
    BDBASEHEVER varchar(5),
    BDBASEMAIORVER varchar(5),
    BDRAISVER varchar(5),
    BDBASEGPSVER varchar(5),
    BDMENORESVER varchar(5),
    BDPROPVER varchar(5),
    BDBASEVTVER varchar(5),
    BDREEMBGPSVER varchar(5),
    BDHEVER numeric(15,6),
    BDGRAVAFICHAHNVER varchar(5),
    BDCCPRINCIPALVER varchar(5),
    BDFORMREFVER varchar(5000),
    BDFORMVALVER varchar(5000),
    BDFORMINTVER varchar(5000),
    BDBASEDSRHEVER varchar(5),
    BDBASEDSRRVVER varchar(5),
    BDREFVER integer,
    BDFORMREFAUXVER varchar(5000),
    BDDEDFORMREFAUXVER varchar(5),
    BDDEDFORMREFVER varchar(5),
    BDDEDFORMVALVER varchar(5),
    BDRENDISENTOIRVER varchar(5),
    BDSITMATVER varchar(5),
    BDSITDOEVER varchar(5),
    BDSITACITRABVER varchar(5),
    BDSITMILITARVER varchar(5),
    BDSITMATEMPVER varchar(5),
    BDSITACITRAB15VER varchar(5),
    BDSITDOETRABVER varchar(5),
    BDSITLICVENCVER varchar(5),
    BDSITDOE15VER varchar(5),
    BDSITSINDICALVER varchar(5),
    BDSITAPOINVVER varchar(5),
    BDSITOUTRASVER varchar(5),
    BDPAGAESTOUROVER DM_BOOLEAN,
    BDGARANTIAMINVER DM_BOOLEAN,
    BDINDRESC DM_BOOLEAN,
    BDNAOCONVHORASVER DM_BOOLEAN,
    BDBASEDSRHNVER DM_BOOLEAN,
    BDBASEDSROUVER DM_BOOLEAN,
    BDCODINCIDFGTS integer,
    BDCODINCIDINSS integer,
    BDCODINCIDIRRF integer)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(15000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(wreferencia,  NULL, NULL);

  wsql = 'select VR.BDCODVER, V.BDCLAVER, V.BDAPEVER, V.BDDESCVER, V.BDDESCREDVER, V.BDORDEMVER, V.BDINATIVAVER, V.BDSITVER, V.BDTIPOVER, VR.BDTIPOCODVER, VR.BDINSSVER, VR.BDIRVER, ';
  wsql = wsql || 'VR.BDFGTSVER, VR.BDTIPOREFVER, VR.BDBASESFVER, VR.BDPISVER, VR.BDBASEHEVER, VR.BDBASEMAIORVER, VR.BDRAISVER, VR.BDBASEGPSVER, ';
  wsql = wsql || 'VR.BDMENORESVER, VR.BDPROPVER, VR.BDBASEVTVER, VR.BDREEMBGPSVER, VR.BDHEVER, VR.BDGRAVAFICHAHNVER, VR.BDCCPRINCIPALVER, ';
  wsql = wsql || 'VR.BDFORMREFVER, VR.BDFORMVALVER, VR.BDFORMINTVER, VR.BDBASEDSRHEVER, VR.BDBASEDSRRVVER, VR.BDREFVER, VR.BDFORMREFAUXVER, ';
  wsql = wsql || 'VR.BDDEDFORMREFAUXVER, VR.BDDEDFORMREFVER, ';
  wsql = wsql || 'VR.BDDEDFORMVALVER, VR.BDRENDISENTOIRVER, ';
  wsql = wsql || 'V.BDSITMATVER,V.BDSITDOEVER,V.BDSITACITRABVER,V.BDSITMILITARVER,V.BDSITMATEMPVER,V.BDSITACITRAB15VER,V.BDSITDOETRABVER,V.BDSITLICVENCVER,V.BDSITDOE15VER,';
  wsql = wsql || 'V.BDSITSINDICALVER,V.BDSITAPOINVVER,V.BDSITOUTRASVER, VR.BDPAGAESTOUROVER , VR.BDGARANTIAMINVER, VR.BDINDRESC, VR.BDNAOCONVHORASVER, VR.BDBASEDSRHNVER, ';
  wsql = wsql || 'VR.BDBASEDSROUVER, VR.BDCODINCIDFGTS, VR.BDCODINCIDINSS, VR.BDCODINCIDIRRF ';

  wsql = wsql || 'from VW_VERBAS_REF_ATUAL VR, ';
  wsql = wsql || 'vrh_base_tverbas V ';

  wwhere = ' where (v.bdcodver = vr.bdcodver) ';

  IF (wverbas IS NOT NULL AND wverbas <> '') THEN
     wwhere = wwhere||' and (' || wverbas || ')';

  IF (WTAMANHOCLASSE IS NOT NULL) THEN
     wwhere = wwhere||' and (strlen(v.bdclaver) > '||WTAMANHOCLASSE||')';

  wsql = wsql||wwhere;   --||' order by V.BDCODVER';

  FOR EXECUTE STATEMENT wsql
    INTO
      :BDCODVER, :BDCLAVER, :BDAPEVER, :BDDESCVER, :BDDESCREDVER, :BDORDEMVER, :BDINATIVAVER, :BDSITVER, :BDTIPOVER, :BDTIPOCODVER, :BDINSSVER,
      :BDIRVER, :BDFGTSVER, :BDTIPOREFVER, :BDBASESFVER, :BDPISVER, :BDBASEHEVER, :BDBASEMAIORVER,
      :BDRAISVER, BDBASEGPSVER, :BDMENORESVER, :BDPROPVER, :BDBASEVTVER, :BDREEMBGPSVER, :BDHEVER,
      :BDGRAVAFICHAHNVER, :BDCCPRINCIPALVER, :BDFORMREFVER, :BDFORMVALVER, :BDFORMINTVER, :BDBASEDSRHEVER,
      :BDBASEDSRRVVER, :BDREFVER, : BDFORMREFAUXVER,
      :BDDEDFORMREFAUXVER, :BDDEDFORMREFVER, :BDDEDFORMVALVER, :BDRENDISENTOIRVER,
      :BDSITMATVER, :BDSITDOEVER, :BDSITACITRABVER, :BDSITMILITARVER, :BDSITMATEMPVER, :BDSITACITRAB15VER, :BDSITDOETRABVER, :BDSITLICVENCVER,
      :BDSITDOE15VER, :BDSITSINDICALVER, :BDSITAPOINVVER, :BDSITOUTRASVER, :BDPAGAESTOUROVER , :BDGARANTIAMINVER, :BDINDRESC, :BDNAOCONVHORASVER,
      :BDBASEDSRHNVER, :BDBASEDSROUVER, :BDCODINCIDFGTS, :BDCODINCIDINSS, :BDCODINCIDIRRF
    DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL,  NULL, NULL);
END^

--Sol. 15188 - 22/08/2016 - Alterada a procedure VRH_SP_CONSULTA_SITUACAO para retornar todos os campos da tabela VRH_EMP_TSITCOL corretamente - Bruno L. R.
/* Restore proc. body: VRH_SP_CONSULTA_SITUACAO */
CREATE OR ALTER procedure VRH_SP_CONSULTA_SITUACAO (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRREF integer,
    PRTRANSFERENCIA smallint = 0)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCODSIT integer,
    BDDESCSIT varchar(70),
    BDDATAINISEFIP date,
    BDDATAINISIT date,
    BDDATAFIMSIT date,
    BDDIASSIT integer,
    BDNBENEFICIOSIT varchar(20),
    BDDATAPERICIASIT date,
    BDDATAPARTOSIT date,
    BDDATAESTAB date,
    BDCODDOE integer,
    BDDESCDOE varchar(300),
    BDTIPOACID varchar(50),
    BDCODMED integer,
    BDNOMMED varchar(60),
    BDCODSINTRAB integer,
    BDDESCSINTRAB varchar(60),
    BDOBSERVACAO varchar(255),
    BDGRUPOSIT integer,
    BDCODEVTINICIO integer,
    BDCODEVTFIM integer,
    BDRECIBOESOCIALINICIO char(30),
    BDRECIBOESOCIALFIM char(30),
    BDCOVID19 DM_BOOLEAN,
    BDBENEFDEFERIDO DM_BOOLEAN,
    BDCODSITAUX integer,
    BDDESCSITAUX varchar(70),
    BDGRUPOSITAUX integer,
    BDDATAINIATESTADOAUX date,
    BDDATAFIMATESTADOAUX date,
    BDDATAINIAFASTAUX date,
    BDDATAFIMAFASTAUX date,
    BDDIASDOCUMENTO integer,
    BDDIASATESTADOAUX integer,
    BDDIASAFASTAUX integer,
    BDAFASDECORRENTE boolean)
as
declare variable WFROM varchar(5000);
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(20000);
declare variable WANOMES integer;
declare variable WCODSIND integer;
declare variable WSQLAUX varchar(1000);
declare variable WDIASETB integer;
declare variable WGRUPOETBSIT integer;
declare variable WDATAESTAB date;
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WEMPORIG integer;
declare variable WCOLORIG integer;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wsql = 'select SIT.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'SIT.BDCODCOL, '||
                'SIT.BDCODSIT, '||
                'PSIT.BDDESCSIT, '||
                'SIT.BDDATAINISEFIP, '||
                'SIT.BDDATAINISIT, '||
                'SIT.BDDATAFIMSIT, '||
                'SIT.BDDIASSIT, '||
                'SIT.BDNBENEFICIOSIT, '||
                'SIT.BDDATAPERICIASIT, '||
                'SIT.BDDATAPARTOSIT, '||
                'SIT.BDCODDOE, '||
                'DOE.BDDESCDOE, '||
                'case when (SIT.BDTIPOACID = 0) then '''' '||
                'when (SIT.BDTIPOACID = 1) then ''1 - Atropelamento'' '||
                'when (SIT.BDTIPOACID = 2) then ''2 - Colisão'' '||
                'when (SIT.BDTIPOACID = 3) then ''3 - Outros'' '||
                'end BDTIPOACID, '||
                'SIT.BDCODMED, '||
                'MED.BDNOMMED, '||
                'SIT.BDCODSINTRAB, '||
                'SIND.BDDESCSINTRAB, '||
                'SIT.BDOBSERVACAO, '||
                'PSIT.BDGRUPOSIT, ' ||
                'SIT.BDCODEVTINICIO, ' ||
                'SIT.BDCODEVTFIM, ' ||
                'ARQINI.BDRECIBO BDRECIBOESOCIALINICIO, ' ||
                'ARQFIM.BDRECIBO BDRECIBOESOCIALFIM, '||
                'case when (coalesce(SIT.BDCOVID19,''FALSE'') = ''TRUE'') then ''Sim'' '||
                'else ''Não'' '||
                'end BDCOVID19, '||
                'case when (coalesce(SIT.BDBENEFDEFERIDO,''FALSE'') = ''TRUE'') then ''Sim'' '||
                'else ''Não'' '||
                'end BDBENEFDEFERIDO, '||
                'SIT.BDCODSITAUX, '||
                'PSITA.BDDESCSIT as BDDESCSITAUX, '||
                'PSITA.BDGRUPOSIT as BDGRUPOSITAUX, '||
                'SIT.BDDATAINIATESTADOAUX, '||
                'SIT.BDDATAFIMATESTADOAUX, '||
                'case when (SIT.BDDATAINIAFASTAUX is null) and (SIT.BDDATAINIATESTADOAUX is null) then SIT.bddatainisit else SIT.BDDATAINIAFASTAUX end BDDATAINIAFASTAUX, '||
                'case when (SIT.BDDATAFIMAFASTAUX is null) and (SIT.BDDATAFIMATESTADOAUX is null) then SIT.bddatafimsit else SIT.BDDATAFIMAFASTAUX end BDDATAFIMAFASTAUX, '||
                'SIT.BDDIASDOCUMENTO, '||
                'SIT.BDDIASATESTADOAUX, '||
                'case when (SIT.BDDIASAFASTAUX is null) and (SIT.BDDIASATESTADOAUX is null) then SIT.bddiassit else SIT.BDDIASAFASTAUX end BDDIASAFASTAUX, FALSE BDAFASDECORRENTE ';

  wfrom = 'from VW_EMPRESAS_REF_ATUAL EMP '||
          'join VRH_EMP_TSITCOL SIT on (SIT.BDCODEMP = EMP.BDCODEMP) '||
          'join VRH_BASE_TPREPSIT PSIT on (PSIT.BDCODSIT = SIT.BDCODSIT) '||
          'join VRH_BASE_TPREPSIT PSITA on (PSITA.BDCODSIT = SIT.BDCODSITAUX) '||
          'left outer join VRH_BASE_TDOENCAS DOE on (SIT.BDCODDOE=DOE.BDCODDOE) '||
          'left outer join VRH_BASE_TMEDICOS MED on (SIT.BDCODMED=MED.BDCODMED) '||
          'left outer join VRH_BASE_TSINDTRAB SIND on (SIT.BDCODSINTRAB=SIND.BDCODSINTRAB) ' ||
          'left outer join VRH_ESOCIAL_TARQUIVO ARQINI on ARQINI.BDCODEMP = SIT.BDCODEMP and ARQINI.BDCODCOL = SIT.BDCODCOL and ARQINI.BDCODIGO = SIT.BDCODEVTINICIO ' ||
          'left outer join VRH_ESOCIAL_TARQUIVO ARQFIM on ARQFIM.BDCODEMP = SIT.BDCODEMP and ARQFIM.BDCODCOL = SIT.BDCODCOL and ARQFIM.BDCODIGO = SIT.BDCODEVTFIM ';

  wwhere = ' where EMP.BDCODEMP is not null ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||' and '||prcodcol;

  wsql = wsql||wfrom||wwhere;
  wsql = wsql||' order by SIT.BDCODEMP, SIT.BDCODCOL, '||
                         'SIT.BDDATAINISIT desc, SIT.BDCODSIT';

  wempatu = 0;
  wcolatu = 0;
  prtransferencia = coalesce(prtransferencia, 0);

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDCODSIT,
    :BDDESCSIT,
    :BDDATAINISEFIP,
    :BDDATAINISIT,
    :BDDATAFIMSIT,
    :BDDIASSIT,
    :BDNBENEFICIOSIT,
    :BDDATAPERICIASIT,
    :BDDATAPARTOSIT,
    :BDCODDOE,
    :BDDESCDOE,
    :BDTIPOACID,
    :BDCODMED,
    :BDNOMMED,
    :BDCODSINTRAB,
    :BDDESCSINTRAB,
    :BDOBSERVACAO,
    :BDGRUPOSIT,
    :BDCODEVTINICIO,
    :BDCODEVTFIM,
    :BDRECIBOESOCIALINICIO,
    :BDRECIBOESOCIALFIM,
    :BDCOVID19,
    :BDBENEFDEFERIDO,
    :BDCODSITAUX,
    :BDDESCSITAUX,
    :BDGRUPOSITAUX,
    :BDDATAINIATESTADOAUX,
    :BDDATAFIMATESTADOAUX,
    :BDDATAINIAFASTAUX,
    :BDDATAFIMAFASTAUX,
    :BDDIASDOCUMENTO,
    :BDDIASATESTADOAUX,
    :BDDIASAFASTAUX,
    :BDAFASDECORRENTE
  DO
    BEGIN
      BDDATAESTAB = NULL;

      if ((wempatu <> BDCODEMP) or (wcolatu <> BDCODCOL)) then
         begin
           if (wempatu <> 0 and wcolatu <> 0) then
              begin
                if (prtransferencia = 1) then
                   begin
                     for select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = :wempatu and BDCODCOLDEST = :wcolatu
                     into :wemporig, :wcolorig
                     do
                       begin
                         for select BDNOMEMP, BDNOMCOL, BDCODSIT, BDDESCSIT, BDDATAINISEFIP, BDDATAINISIT, BDDATAFIMSIT, BDDIASSIT, BDNBENEFICIOSIT,
                                    BDDATAPERICIASIT, BDDATAPARTOSIT, BDDATAESTAB, BDCODDOE, BDDESCDOE, BDTIPOACID, BDCODMED, BDNOMMED, BDCODSINTRAB, BDDESCSINTRAB, BDOBSERVACAO,
                                    BDGRUPOSIT, BDCODEVTINICIO, BDCODEVTFIM, BDRECIBOESOCIALINICIO, BDRECIBOESOCIALFIM, BDCOVID19, BDBENEFDEFERIDO, BDCODSITAUX, BDDESCSITAUX,
                                    BDGRUPOSITAUX, BDDATAINIATESTADOAUX, BDDATAFIMATESTADOAUX, BDDATAINIAFASTAUX, BDDATAFIMAFASTAUX, BDDIASDOCUMENTO, BDDIASATESTADOAUX,
                                    BDDIASAFASTAUX, BDAFASDECORRENTE
                             from VRH_SP_CONSULTA_SITUACAO('SIT.BDCODEMP = '||:wemporig, 'SIT.BDCODCOL = '||:wcolorig, :prref, :prtransferencia)
                         into
                           :BDNOMEMP, :BDNOMCOL, :BDCODSIT, :BDDESCSIT, :BDDATAINISEFIP, :BDDATAINISIT, :BDDATAFIMSIT, :BDDIASSIT, :BDNBENEFICIOSIT,
                           :BDDATAPERICIASIT, :BDDATAPARTOSIT, :BDDATAESTAB, :BDCODDOE, :BDDESCDOE, :BDTIPOACID, :BDCODMED, :BDNOMMED, :BDCODSINTRAB, :BDDESCSINTRAB, :BDOBSERVACAO,
                           :BDGRUPOSIT, :BDCODEVTINICIO, :BDCODEVTFIM, :BDRECIBOESOCIALINICIO, :BDRECIBOESOCIALFIM, :BDCOVID19, :BDBENEFDEFERIDO, :BDCODSITAUX, :BDDESCSITAUX,
                           :BDGRUPOSITAUX, :BDDATAINIATESTADOAUX, :BDDATAFIMATESTADOAUX, :BDDATAINIAFASTAUX, :BDDATAFIMAFASTAUX, :BDDIASDOCUMENTO, :BDDIASATESTADOAUX,
                           :BDDIASAFASTAUX, :BDAFASDECORRENTE
                         do
                           begin
                             suspend;
                           end
                       end
                   end
              end

           wempatu = BDCODEMP;
           wcolatu = BDCODCOL;
           select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL into :BDNOMCOL;
         end

      IF (BDDATAFIMSIT IS NOT NULL) THEN
         BEGIN
           wdataestab = BDDATAFIMSIT + 1; -- Sol. 125461 | Michel Luciano | 05/03/2020.
           wAnoMes = CAST((SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

           wsqlaux = 'select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFCOL <= '||wanomes||
                     ' order by BDREFCOL DESC ';

           wcodsind = NULL;
           EXECUTE STATEMENT wsqlaux INTO :wcodsind;

           IF (wcodsind IS NOT NULL) THEN
              BEGIN
                FOR SELECT PE.BDGRUPOSITETB, PE.BDDIASETB FROM VRH_BASE_TPREPESTAB PE WHERE COALESCE(PE.BDTIPOETB,0) = 0 AND PE.BDCODSINTRAB = :wcodsind INTO :wgrupoetbsit, :wdiasetb DO
                  BEGIN
                    IF (COALESCE(wgrupoetbsit, 0) = COALESCE(BDGRUPOSIT, 0) AND COALESCE(wdiasetb, 0) > 0) THEN
                       BEGIN
                         IF (BDGRUPOSIT IN (0,4)) THEN   -- Maternidade
                            BEGIN
                              IF (BDDATAPARTOSIT IS NOT NULL) THEN
                                 wdataestab = BDDATAPARTOSIT;
                              ELSE
                                 wdataestab = BDDATAINISIT;
                            END

                         wdataestab = wdataestab + wdiasetb - 1;
                         BDDATAESTAB = wdataestab;
                       END
                  END
              END
         END

      SUSPEND;
    END

  if (wempatu <> 0 and wcolatu <> 0) then
     begin
       if (prtransferencia = 1) then
          begin
            for select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = :wempatu and BDCODCOLDEST = :wcolatu
            into :wemporig, :wcolorig
            do
              begin
                for select BDNOMEMP, BDNOMCOL, BDCODSIT, BDDESCSIT, BDDATAINISEFIP, BDDATAINISIT, BDDATAFIMSIT, BDDIASSIT, BDNBENEFICIOSIT,
                           BDDATAPERICIASIT, BDDATAPARTOSIT, BDDATAESTAB, BDCODDOE, BDDESCDOE, BDTIPOACID, BDCODMED, BDNOMMED, BDCODSINTRAB, BDDESCSINTRAB, BDOBSERVACAO,
                           BDGRUPOSIT, BDCODEVTINICIO, BDCODEVTFIM, BDRECIBOESOCIALINICIO, BDRECIBOESOCIALFIM, BDCOVID19, BDBENEFDEFERIDO, BDCODSITAUX, BDDESCSITAUX,
                           BDGRUPOSITAUX, BDDATAINIATESTADOAUX, BDDATAFIMATESTADOAUX, BDDATAINIAFASTAUX, BDDATAFIMAFASTAUX, BDDIASDOCUMENTO, BDDIASATESTADOAUX,
                           BDDIASAFASTAUX, BDAFASDECORRENTE
                    from VRH_SP_CONSULTA_SITUACAO('SIT.BDCODEMP = '||:wemporig, 'SIT.BDCODCOL = '||:wcolorig, :prref, :prtransferencia)
                into
                  :BDNOMEMP, :BDNOMCOL, :BDCODSIT, :BDDESCSIT, :BDDATAINISEFIP, :BDDATAINISIT, :BDDATAFIMSIT, :BDDIASSIT, :BDNBENEFICIOSIT,
                  :BDDATAPERICIASIT, :BDDATAPARTOSIT, :BDDATAESTAB, :BDCODDOE, :BDDESCDOE, :BDTIPOACID, :BDCODMED, :BDNOMMED, :BDCODSINTRAB, :BDDESCSINTRAB, :BDOBSERVACAO,
                  :BDGRUPOSIT, :BDCODEVTINICIO, :BDCODEVTFIM, :BDRECIBOESOCIALINICIO, :BDRECIBOESOCIALFIM, :BDCOVID19, :BDBENEFDEFERIDO, :BDCODSITAUX, :BDDESCSITAUX,
                  :BDGRUPOSITAUX, :BDDATAINIATESTADOAUX, :BDDATAFIMATESTADOAUX, :BDDATAINIAFASTAUX, :BDDATAFIMAFASTAUX, :BDDIASDOCUMENTO, :BDDIASATESTADOAUX,
                  :BDDIASAFASTAUX, :BDAFASDECORRENTE
                do
                  begin
                    suspend;
                  end
              end
          end
     end

END
^


/* Restore proc. body: VRH_SP_DADOS_FALTAS */
ALTER PROCEDURE VRH_SP_DADOS_FALTAS(PRCODEMP VARCHAR(1000),
PRCODCOL VARCHAR(32700),
PRDATINI DATE,
PRDATFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFAL INTEGER,
BDDATAFAL DATE,
BDTIPOFAL INTEGER,
BDHORASFAL NUMERIC(15,6),
BDCODVERFAL INTEGER,
BDCODVERDSRFAL INTEGER,
BDTIPOVERFAL INTEGER)
 AS
DECLARE VARIABLE WWHERE VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(20000);
BEGIN

  wsql = 'select bdcodemp, bdcodcol, BDREFFAL, BDDATAFAL, BDTIPOFAL, BDHORASFAL, BDCODVERFAL, BDCODVERDSRFAL, BDTIPOVERFAL ' ||
         'from VRH_EMP_TFALTAS_ITENS ';

  wwhere = '';

  IF (prcodemp IS NOT NULL) THEN
     wwhere = wwhere || prcodemp;

  IF (prcodcol IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere || prcodcol;
     END

  IF (prdatini IS NOT NULL AND prdatfim IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'(BDDATAFAL between '''||:PRDATINI||''' AND '''||:PRDATFIM||''')';

     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql INTO
     :bdcodemp, :bdcodcol, :BDREFFAL, :BDDATAFAL, :BDTIPOFAL, :BDHORASFAL, :BDCODVERFAL, : BDCODVERDSRFAL, :BDTIPOVERFAL
  DO

  SUSPEND;

END
^
/* Restore proc. body: VRH_SP_DADOS_FERIAS */
ALTER PROCEDURE VRH_SP_DADOS_FERIAS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATINI DATE,
PRDATFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDINIPERAQUISFE DATE,
BDCODFE INTEGER,
BDINIPERGOZOFE DATE,
BDFIMPERAQUISFE DATE,
BDFIMPERGOZOFE DATE,
BDDATAPAGFE DATE,
BDQTDGOZOFE INTEGER,
BDQTDABONOFE INTEGER,
BDSALDOINIFE NUMERIC(15,6),
BDSALDOFIMFE NUMERIC(15,6),
BDBASEIRFE NUMERIC(15,6),
BDALIQIRFE NUMERIC(15,6),
BDVALORIRFE NUMERIC(15,6),
BDBASEINSSFE NUMERIC(15,6),
BDALIQINSSFE NUMERIC(15,6),
BDVALORINSSFE NUMERIC(15,6),
BDDEPFE NUMERIC(15,6),
BDSALBASEFE NUMERIC(15,6),
BDSALBASEHEFE NUMERIC(15,6),
BDDATABAIXAFE DATE,
BDCOLETIVASFE VARCHAR(5),
BDREFPAGABOFE INTEGER,
BDFALTASFE NUMERIC(15,6),
BDSALDOFINALSINDFE NUMERIC(18,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(15000);
BEGIN

  wsql = 'select BDCODEMP, BDCODCOL, BDINIPERAQUISFE, BDCODFE, BDINIPERGOZOFE, '||
                'BDFIMPERAQUISFE, BDFIMPERGOZOFE, BDDATAPAGFE, BDQTDGOZOFE, BDQTDABONOFE, '||
                'BDSALDOINIFE, BDSALDOFIMFE, BDBASEIRFE, BDALIQIRFE, BDVALORIRFE, '||
                'BDBASEINSSFE, BDALIQINSSFE, BDVALORINSSFE, BDDEPFE, BDSALBASEFE, '||
                'BDSALBASEHEFE, BDDATABAIXAFE, BDCOLETIVASFE, BDREFPAGABOFE, BDFALTASFE, BDSALDOFINALSINDFE ';

  wsql = wsql || 'from VRH_EMP_TFERIAS ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (prdatIni IS NOT NULL AND prdatfim IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'((BDINIPERGOZOFE between '''||:PRDATINI||''' AND '''||:PRDATFIM||''') or ';
       wwhere = wwhere||'(BDFIMPERGOZOFE between '''||:PRDATINI||''' AND '''||:PRDATFIM||''') or ';
       wwhere = wwhere||'(BDINIPERGOZOFE < '''||:PRDATINI||''' and BDFIMPERGOZOFE > '''||:PRDATFIM||'''))';
     END

  IF (wwhere <> '') THEN
     BEGIN
       wwhere = ' where '||wwhere;
       wsql = wsql||wwhere;
     END

  FOR EXECUTE STATEMENT wsql
  INTO :BDCODEMP, :BDCODCOL, :BDINIPERAQUISFE, :BDCODFE, :BDINIPERGOZOFE,
       :BDFIMPERAQUISFE, :BDFIMPERGOZOFE, :BDDATAPAGFE, :BDQTDGOZOFE, :BDQTDABONOFE,
       :BDSALDOINIFE, :BDSALDOFIMFE, :BDBASEIRFE, :BDALIQIRFE, :BDVALORIRFE,
       :BDBASEINSSFE, :BDALIQINSSFE, :BDVALORINSSFE, :BDDEPFE, :BDSALBASEFE,
       :BDSALBASEHEFE, :BDDATABAIXAFE, :BDCOLETIVASFE, :BDREFPAGABOFE, :BDFALTASFE,
       :BDSALDOFINALSINDFE
  DO

  SUSPEND;

END
^

/* Restore proc. body: VRH_SP_DADOS_FERIAS_RESCISAO */
ALTER PROCEDURE VRH_SP_DADOS_FERIAS_RESCISAO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATARESC DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDINIPERAQUISFE DATE,
BDCODFE INTEGER,
BDINIPERGOZOFE DATE,
BDFIMPERAQUISFE DATE,
BDFIMPERGOZOFE DATE,
BDDATAPAGFE DATE,
BDQTDGOZOFE NUMERIC(18,6),
BDQTDABONOFE NUMERIC(18,6),
BDREFPAGABOFE INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(15000);
DECLARE VARIABLE WAAAAMM VARCHAR(6);
DECLARE VARIABLE WSDATA VARCHAR(10);
BEGIN

  wsql = 'select BDCODEMP, BDCODCOL, BDINIPERAQUISFE, BDCODFE, BDINIPERGOZOFE, '||
                'BDFIMPERAQUISFE, BDFIMPERGOZOFE, BDDATAPAGFE, BDQTDGOZOFE, BDQTDABONOFE, '||
                'BDREFPAGABOFE ';

  wsql = wsql || 'from VRH_EMP_TFERIAS ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (prdataresc IS NOT NULL) THEN
     BEGIN
       wsdata = CAST(prdataresc AS VARCHAR(10));
       waaaamm = SUBSTRING(wsdata FROM 1 FOR 4)||SUBSTRING(wsdata FROM 6 FOR 2);

       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'(BDFIMPERGOZOFE >= '''||PRDATARESC||''' or BDREFPAGABOFE > '||waaaamm||')';
     END

  IF (wwhere <> '') THEN
     BEGIN
       wwhere = ' where '||wwhere;
       wsql = wsql||wwhere;
     END

  FOR EXECUTE STATEMENT wsql
  INTO :BDCODEMP, :BDCODCOL, :BDINIPERAQUISFE, :BDCODFE, :BDINIPERGOZOFE,
       :BDFIMPERAQUISFE, :BDFIMPERGOZOFE, :BDDATAPAGFE, :BDQTDGOZOFE, :BDQTDABONOFE,
       :BDREFPAGABOFE
  DO

  SUSPEND;

END
^

/* Restore proc. body: VRH_SP_DADOS_SITUACAO */
create or alter procedure VRH_SP_DADOS_SITUACAO (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRDATINI date,
    PRDATFIM date,
    PRRETONARSITEMPORIG varchar(5) = 'FALSE' /* COLLATE WIN1252 - default */ ,
    PRPREVRESC varchar(5) = 'FALSE' /* COLLATE WIN1252 - default */ )
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODSIT integer,
    BDDATAINISEFIP date,
    BDDATAINISIT date,
    BDDATAFIMSIT date,
    BDDIASSIT integer,
    BDNBENEFICIOSIT varchar(20),
    BDDATAPERICIASIT date,
    BDDATAPARTOSIT date,
    BDDESCSIT varchar(70),
    BDGRUPOSIT integer,
    BDCODVER integer,
    BDCODMFGENT integer,
    BDCODMFGSAI integer,
    BDCARENSIT integer,
    BDCODVER15DIAS integer,
    BDTIPOPERDESIT integer,
    BDSALFAMSIT varchar(5),
    BDCODSEFENT varchar(5),
    BDCODSEFSAI varchar(5),
    BDRELSIT integer,
    BDINSSINTSIT DM_BOOLEAN,
    BDDIASATESTADO integer,
    BDNAOPRORROGAFERIAS varchar(5),
    BDCOVID19 DM_BOOLEAN,
    BDSUSPENSAO DM_BOOLEAN,
    BDNAOALTPERAQUIMP936 DM_BOOLEAN,
    BDBENEFDEFERIDO DM_BOOLEAN,
    BDDATAINIATESTADOAUX date,
    BDDATAFIMATESTADOAUX date,
    BDDATAINIAFASTAUX date,
    BDDATAFIMAFASTAUX date,
    BDDIASPERDEPERAQUI integer,
    BDDIASATESTADOAUX integer,
    BDCODSITAUX integer,
    BDSUBGRUPOSIT integer)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(30000);
declare variable WEMPORIG integer;
declare variable WCOLORIG integer;
declare variable WEMPX integer;
declare variable WCOLX integer;
declare variable WFIMMESANT date;
declare variable WREF integer;
declare variable WCODCONTROLE integer;
BEGIN
  wsql = 'select SIT.BDCODEMP, SIT.BDCODCOL, SIT.BDCODSIT, SIT.BDDATAINISEFIP, SIT.BDDATAINISIT, SIT.BDDATAFIMSIT, '||
                'SIT.BDDIASSIT, SIT.BDNBENEFICIOSIT, SIT.BDDATAPERICIASIT, SIT.BDDATAPARTOSIT, PSIT.BDDESCSIT, '||
                'PSIT.BDGRUPOSIT, PSITDIA.BDCODVER, PSITDIA.BDCODMFGENT, PSITDIA.BDCODMFGSAI, PSITDIA.BDCARENSIT, '||
                'PSITDIA.BDCODVER15DIAS, PSIT.BDTIPOPERDESIT, PSITDIA.BDSALFAMSIT, FGTSENT.BDCODSEFMFG BDCODSEFENT, '||
                'FGTSSAI.BDCODSEFMFG BDCODSEFSAI, PSIT.BDRELSIT, PSITDIA.BDINSSINTSIT, SIT.BDDIASATESTADO, PSITDIA.BDNAOPRORROGAFERIAS, SIT.BDCOVID19, SIT.BDBENEFDEFERIDO, COALESCE(PSIT.BDSUSPMP,''FALSE'') BDSUSPMP, '||
                'SIT.BDDATAINIATESTADOAUX, SIT.BDDATAFIMATESTADOAUX, SIT.BDDATAINIAFASTAUX, SIT.BDDATAFIMAFASTAUX, PSIT.BDDIASPERDEPERAQUI, '||
                'SIT.BDDIASATESTADOAUX, SIT.BDCODSITAUX, PSIT.BDSUBGRUPOSIT ' || /*158332 - André Cursino*/

         'from ';

  wsql = wsql||'VRH_EMP_TSITCOL sit ';
  wsql = wsql||'join VRH_BASE_TPREPSIT pSit on (psit.BDCODSIT = sit.BDCODSIT) ';
  wsql = wsql||'join VRH_BASE_TPREPSIT_DIA PSITDIA on (PSITDIA.BDCODSIT = PSIT.BDCODSIT';

  wsql = wsql ||' and PSITDIA.BDDATASTD = (select MAX(X.BDDATASTD) from VRH_BASE_TPREPSIT_DIA X where X.BDCODSIT = SIT.BDCODSIT and X.BDDATASTD <= SIT.BDDATAINISEFIP))';

  wsql = wsql||' left outer join VRH_BASE_TMOTFGTS fgtsent on (psit.BDCODMFGENT = fgtsent.BDCODMFG)';
  wsql = wsql||' left outer join VRH_BASE_TMOTFGTS fgtssai on (psit.BDCODMFGSAI = fgtssai.BDCODMFG)';

  wwhere = ' where bdcodemp is not null ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||' and '||prcodcol;

  IF (prdatini IS NOT NULL AND prdatfim IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||' and ';
       wwhere = wwhere||'((sit.BDDATAINISEFIP between '''||:PRDATINI||''' AND '''||:PRDATFIM||''') or ';
       wwhere = wwhere||'(sit.BDDATAFIMSIT between '''||:PRDATINI||''' AND '''||:PRDATFIM||''') or ';
       wwhere = wwhere||'(sit.BDDATAINISEFIP < '''||:PRDATINI||''' and (sit.BDDATAFIMSIT is null or sit.BDDATAFIMSIT > '''||:PRDATFIM||'''))) ';

       wfimmesant = DATEADD(-1 DAY to PRDATINI);
     END
  ELSE
     wfimmesant = CAST(NULL as DATE);

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP, :BDCODCOL, :BDCODSIT, :BDDATAINISEFIP,
    :BDDATAINISIT, :BDDATAFIMSIT, :BDDIASSIT, :BDNBENEFICIOSIT, :BDDATAPERICIASIT, :BDDATAPARTOSIT,
    :BDDESCSIT, :BDGRUPOSIT, :BDCODVER, :BDCODMFGENT, :BDCODMFGSAI, :BDCARENSIT, :BDCODVER15DIAS,
    :BDTIPOPERDESIT, :BDSALFAMSIT, :bdcodsefent, :bdcodsefsai, :bdrelsit, :BDINSSINTSIT, :BDDIASATESTADO,
    :BDNAOPRORROGAFERIAS, :BDCOVID19, :BDBENEFDEFERIDO, :BDSUSPENSAO, :BDDATAINIATESTADOAUX, :BDDATAFIMATESTADOAUX,
    :BDDATAINIAFASTAUX, :BDDATAFIMAFASTAUX, :BDDIASPERDEPERAQUI, :BDDIASATESTADOAUX, :BDCODSITAUX, :BDSUBGRUPOSIT              /*158332 - André Cursino*/
  DO
    BEGIN
      execute statement 'select first 1 BDNAOALTPERAQUIMP936 from VRHF_BASE_TEMPPAR where bdcodemp = ' || :BDCODEMP into BDNAOALTPERAQUIMP936;

      if (UPPER(PRPREVRESC) = 'TRUE') then
        begin
          if ((:BDDATAFIMSIT is null) or ((:BDDATAFIMSIT > :PRDATFIM) and (:BDDATAINISEFIP < :PRDATFIM))) then
            begin
              BDDATAFIMSIT = dateadd(-1 day to :PRDATFIM);
            end
        end

    SUSPEND;
    END

  IF (UPPER(PRRETONARSITEMPORIG) = 'TRUE') THEN
     begin
       wwhere = 'select SIT.BDCODEMPORIG, SIT.BDCODCOLORIG, SIT.BDCODEMPDEST, SIT.BDCODCOLDEST from VRH_EMP_TTRANSCOL SIT ';

       IF (coalesce(prcodemp, '') <> '') THEN
          begin
            wwhere = wwhere||' where '||REPLACE(UPPER(prcodemp), 'BDCODEMP', 'BDCODEMPDEST');
     
            IF (coalesce(prcodcol, '') <> '') THEN
               wwhere = wwhere||' and '||REPLACE(UPPER(prcodcol), 'BDCODCOL', 'BDCODCOLDEST');
          end

       for execute statement wwhere into :wemporig, :wcolorig, :BDCODEMP, :BDCODCOL do
         begin
           while (coalesce(wemporig, 0) <> 0 and coalesce(wcolorig, 0) <> 0) do
             begin
               wsql = 'select SIT.BDCODSIT, SIT.BDDATAINISEFIP, SIT.BDDATAINISIT, SIT.BDDATAFIMSIT, '||
                             'SIT.BDDIASSIT, SIT.BDNBENEFICIOSIT, SIT.BDDATAPERICIASIT, SIT.BDDATAPARTOSIT, PSIT.BDDESCSIT, '||
                             'PSIT.BDGRUPOSIT, PSITDIA.BDCODVER, PSITDIA.BDCODMFGENT, PSITDIA.BDCODMFGSAI, PSITDIA.BDCARENSIT, '||
                             'PSITDIA.BDCODVER15DIAS, PSIT.BDTIPOPERDESIT, PSITDIA.BDSALFAMSIT, FGTSENT.BDCODSEFMFG BDCODSEFENT, '||
                             'FGTSSAI.BDCODSEFMFG BDCODSEFSAI, PSIT.BDRELSIT, PSITDIA.BDINSSINTSIT, SIT.BDDIASATESTADO, PSITDIA.BDNAOPRORROGAFERIAS, SIT.BDCOVID19, SIT.BDBENEFDEFERIDO, COALESCE(PSIT.BDSUSPMP,''FALSE'') BDSUSPMP, '||
                             'SIT.BDDATAINIATESTADOAUX, SIT.BDDATAFIMATESTADOAUX, SIT.BDDATAINIAFASTAUX, SIT.BDDATAFIMAFASTAUX, PSIT.BDDIASPERDEPERAQUI, '||
                             'SIT.BDDIASATESTADOAUX, SIT.BDCODSITAUX, PSIT.BDSUBGRUPOSIT ' ||      /*158332 - André Cursino*/
                      'from ';
             
               wsql = wsql||'VRH_EMP_TSITCOL sit ';
               wsql = wsql||'join VRH_BASE_TPREPSIT pSit on (psit.BDCODSIT = sit.BDCODSIT) ';
               wsql = wsql||'join VRH_BASE_TPREPSIT_DIA PSITDIA on (PSITDIA.BDCODSIT = PSIT.BDCODSIT ';
               wsql = wsql||'and PSITDIA.BDDATASTD = (select MAX(X.BDDATASTD) from VRH_BASE_TPREPSIT_DIA X where X.BDCODSIT = SIT.BDCODSIT and X.BDDATASTD <= SIT.BDDATAINISEFIP)) ';
               wsql = wsql||'left outer join VRH_BASE_TMOTFGTS fgtsent on (psit.BDCODMFGENT = fgtsent.BDCODMFG) ';
               wsql = wsql||'left outer join VRH_BASE_TMOTFGTS fgtssai on (psit.BDCODMFGSAI = fgtssai.BDCODMFG) ';
             
               wsql = wsql||' where SIT.BDCODEMP = '||wemporig||' and SIT.BDCODCOL = '||wcolorig||' and';
               wsql = wsql||'       not exists(select *';
               wsql = wsql||'                  from VRH_EMP_TSITCOL SIT2';
               wsql = wsql||'                  where';

               IF (Coalesce(BDCODEMP,0) > 0) THEN
                 wsql = wsql||'                      SIT2.BDCODEMP = '||BDCODEMP||' and';

               IF (Coalesce(BDCODCOL,0) > 0) THEN
                 wsql = wsql||'                      SIT2.BDCODCOL = '||BDCODCOL||' and';

               wsql = wsql||'                        SIT2.BDDATAINISEFIP = SIT.BDDATAINISEFIP and';
               wsql = wsql||'                        SIT2.BDDATAFIMSIT = SIT.BDDATAFIMSIT)';
             
               IF (prdatini IS NOT NULL AND prdatfim IS NOT NULL) THEN
                  BEGIN
                    wsql = wsql||' and ';
                    wsql = wsql||'((sit.BDDATAINISEFIP between '''||:PRDATINI||''' AND '''||:PRDATFIM||''') or ';
                    wsql = wsql||'(sit.BDDATAFIMSIT between '''||:PRDATINI||''' AND '''||:PRDATFIM||''')) ';
                  END
             
               wsql = wsql||'  and (sit.BDDATAFIMSIT is not null) ';
             
               FOR EXECUTE STATEMENT wsql INTO
                 :BDCODSIT, :BDDATAINISEFIP,
                 :BDDATAINISIT, :BDDATAFIMSIT, :BDDIASSIT, :BDNBENEFICIOSIT, :BDDATAPERICIASIT, :BDDATAPARTOSIT,
                 :BDDESCSIT, :BDGRUPOSIT, :BDCODVER, :BDCODMFGENT, :BDCODMFGSAI, :BDCARENSIT, :BDCODVER15DIAS,
                 :BDTIPOPERDESIT, :BDSALFAMSIT, :bdcodsefent, :bdcodsefsai, :bdrelsit, :BDINSSINTSIT, :BDDIASATESTADO,
                 :BDNAOPRORROGAFERIAS, :BDCOVID19, :BDBENEFDEFERIDO, :BDSUSPENSAO, :BDDATAINIATESTADOAUX, :BDDATAFIMATESTADOAUX,
                 :BDDATAINIAFASTAUX, :BDDATAFIMAFASTAUX, :BDDIASPERDEPERAQUI, :BDDIASATESTADOAUX, :BDCODSITAUX, BDSUBGRUPOSIT    /*158332 - André Cursino*/
               DO
                 begin
                   if (BDDATAINISIT is not null) then
                      wfimmesant = BDDATAINISIT;
                   else
                   if (BDDATAINIAFASTAUX is not null) then
                      wfimmesant = BDDATAINIAFASTAUX;
                   else
                   if (BDDATAINIATESTADOAUX is not null) then
                      wfimmesant = BDDATAINIATESTADOAUX;
                   else
                      select CURRENT_DATE from RDB$DATABASE into :wfimmesant;

                   wref = CAST((SUBSTRING(CAST(:wfimmesant as varchar(10)) from 1 for 4)||SUBSTRING(CAST(:wfimmesant as varchar(10)) from 6 for 2)) AS INTEGER);
                   select first 1 BDNAOALTPERAQUIMP936 from VRHF_BASE_TEMPPAR where bdcodemp = :BDCODEMP and bdrefemp <= :wref order by BDREFEMP desc into :BDNAOALTPERAQUIMP936;

                   if (UPPER(coalesce(PRPREVRESC, 'FALSE')) = 'TRUE') then
                     begin
                      if ((:BDDATAFIMSIT is null) or ((:BDDATAFIMSIT > :PRDATFIM) and (:BDDATAINISEFIP < :PRDATFIM))) then
                        begin
                          BDDATAFIMSIT = dateadd(-1 day to :PRDATFIM);
                        end
                     end

                 SUSPEND;
                 end

               wempx = null;
               wcolx = null;

               select bdcodemp from TMP_CONTROLE_PERAQUISFE where BDSPINSERIU = 4 AND bdcodemp = :wemporig and bdcodcol = :wcolorig and bdsessao = current_connection into :wcodcontrole;
               if (wcodcontrole is null) then
                  begin
               select first 1 BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = :wemporig and BDCODCOLDEST = :wcolorig into :wempx, :wcolx;
               wemporig = wempx;
               wcolorig = wcolx;
                    insert into TMP_CONTROLE_PERAQUISFE (BDCODEMP,BDCODCOL,BDSESSAO,BDSPINSERIU) values (:wemporig,:wcolorig,current_connection,4);
             end
               else
                  begin
                    wemporig = null;
                    wcolorig = null;
         end
   end
         end
   end
  delete from TMP_CONTROLE_PERAQUISFE where BDSPINSERIU = 4 AND bdsessao = current_connection;
END^

/* Restore proc. body: VRH_SP_DADOS_SITUACAO_RESCISAO */
create or alter procedure VRH_SP_DADOS_SITUACAO_RESCISAO (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRDATARESC date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODSIT integer,
    BDDATAINISEFIP date,
    BDDATAINISIT date,
    BDDATAFIMSIT date,
    BDDIASSIT integer,
    BDNBENEFICIOSIT varchar(20),
    BDDATAPERICIASIT date,
    BDDATAPARTOSIT date,
    BDDESCSIT varchar(70),
    BDGRUPOSIT integer,
    BDCODVER integer,
    BDCARENSIT integer,
    BDTIPOPERDESIT integer,
    BDDIASATESTADO integer,
    BDNAOPRORROGAFERIAS varchar(5),
    BDSUSPMP DM_BOOLEAN,
    BDNAOALTPERAQUIMP936 DM_BOOLEAN,
    BDBENEFDEFERIDO DM_BOOLEAN,
    BDDATAINIATESTADOAUX date,
    BDDATAFIMATESTADOAUX date,
    BDDATAINIAFASTAUX date,
    BDDATAFIMAFASTAUX date,
    BDDIASPERDEPERAQUI integer,
    BDSUBGRUPOSIT integer)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(15000);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
declare variable WEMPX integer;
declare variable WCOLX integer;
declare variable WFIMMESANT date;
declare variable WCODCONTROLE integer;
BEGIN

  wsql = 'select sit.BDCODEMP, sit.BDCODCOL, sit.BDCODSIT, sit.BDDATAINISEFIP, '||
                'sit.BDDATAINISIT, sit.BDDATAFIMSIT, sit.BDDIASSIT, sit.BDNBENEFICIOSIT, sit.BDDATAPERICIASIT, sit.BDDATAPARTOSIT, '||
                'pSit.BDDESCSIT, pSit.BDGRUPOSIT, pSitDia.BDCODVER, pSitDia.BDCARENSIT, pSit.BDTIPOPERDESIT, SIT.BDDIASATESTADO, PSITDIA.BDNAOPRORROGAFERIAS, pSit.BDSUSPMP, SIT.BDBENEFDEFERIDO, '||
                'sit.BDDATAINIATESTADOAUX, sit.BDDATAFIMATESTADOAUX, sit.BDDATAINIAFASTAUX, sit.BDDATAFIMAFASTAUX, PSIT.BDDIASPERDEPERAQUI, '||
                'psit.BDSUBGRUPOSIT ';

  wsql = wsql||'from VRH_EMP_TSITCOL sit '||
               'join VRH_BASE_TPREPSIT pSit on (pSit.BDCODSIT = sit.BDCODSIT) '||
               'join VRH_BASE_TPREPSIT_DIA pSitDia on (pSitDia.BDCODSIT = sit.BDCODSIT and pSitDia.BDDATASTD = (select MAX(X.BDDATASTD) from VRH_BASE_TPREPSIT_DIA X where X.BDCODSIT = sit.BDCODSIT and X.BDDATASTD <= sit.BDDATAINISEFIP)) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
    BEGIN
      wwhere = wwhere||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wwhere = wwhere||' and '||prcodcol;
    END

  IF (prdataresc IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
         wwhere = wwhere||' and ';
       wwhere = wwhere||' (sit.BDDATAFIMSIT is null or sit.BDDATAFIMSIT >= '''||PRDATARESC||''')';

       wfimmesant = DATEADD(-EXTRACT(DAY FROM prdataresc) DAY TO prdataresc);
     END
  ELSE
     wfimmesant = CAST(NULL as DATE);

  IF (wwhere <> '') THEN
    wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP, :BDCODCOL, :BDCODSIT, :BDDATAINISEFIP,
    :BDDATAINISIT, :BDDATAFIMSIT, : BDDIASSIT, :BDNBENEFICIOSIT, :BDDATAPERICIASIT, :BDDATAPARTOSIT,
    :BDDESCSIT, :BDGRUPOSIT, :BDCODVER, :BDCARENSIT, :BDTIPOPERDESIT, :BDDIASATESTADO, :BDNAOPRORROGAFERIAS, :BDSUSPMP,
    :BDBENEFDEFERIDO, :BDDATAINIATESTADOAUX, :BDDATAFIMATESTADOAUX, :BDDATAINIAFASTAUX, :BDDATAFIMAFASTAUX, :BDDIASPERDEPERAQUI, :BDSUBGRUPOSIT
  DO
    BEGIN
      execute statement 'select first 1 BDNAOALTPERAQUIMP936 from VRHF_BASE_TEMPPAR where bdcodemp = ' || :BDCODEMP into BDNAOALTPERAQUIMP936;
    SUSPEND;
    END

-- informações vindas de transferência
  wwhere = 'select BDCODEMPORIG, BDCODCOLORIG, BDCODEMPDEST, BDCODCOLDEST from VRH_EMP_TTRANSCOL ';

  if (coalesce(prcodemp, '') <> '') then
     begin
       wwhere = wwhere||' where '||REPLACE(REPLACE(UPPER(prcodemp), 'BDCODEMP', 'BDCODEMPDEST'), 'SIT.', '');

       if (coalesce(prcodcol, '') <> '') then
          wwhere = wwhere||' and '||REPLACE(REPLACE(UPPER(prcodcol), 'BDCODCOL', 'BDCODCOLDEST'), 'SIT.', '');
     end

  for execute statement wwhere into :wcodemporig, :wcodcolorig, :BDCODEMP, :BDCODCOL do
    begin
      while (coalesce(wcodemporig, 0) <> 0 and coalesce(wcodcolorig, 0) <> 0) do
        begin
          wsql = 'select sit.BDCODSIT, sit.BDDATAINISEFIP, '||
                        'sit.BDDATAINISIT, sit.BDDATAFIMSIT, sit.BDDIASSIT, sit.BDNBENEFICIOSIT, sit.BDDATAPERICIASIT, sit.BDDATAPARTOSIT, '||
                        'pSit.BDDESCSIT, pSit.BDGRUPOSIT, pSitDia.BDCODVER, pSitDia.BDCARENSIT, pSit.BDTIPOPERDESIT, SIT.BDDIASATESTADO, PSITDIA.BDNAOPRORROGAFERIAS, pSit.BDSUSPMP, SIT.BDBENEFDEFERIDO, '||
                        'sit.BDDATAINIATESTADOAUX, sit.BDDATAFIMATESTADOAUX, sit.BDDATAINIAFASTAUX, sit.BDDATAFIMAFASTAUX, PSIT.BDDIASPERDEPERAQUI, '||
                        'psit.BDSUBGRUPOSIT ';
        
          wsql = wsql||'from VRH_EMP_TSITCOL sit '||
                       'join VRH_BASE_TPREPSIT pSit on (pSit.BDCODSIT = sit.BDCODSIT) '||
                       'join VRH_BASE_TPREPSIT_DIA pSitDia on (pSitDia.BDCODSIT = sit.BDCODSIT and pSitDia.BDDATASTD = (select MAX(X.BDDATASTD) from VRH_BASE_TPREPSIT_DIA X where X.BDCODSIT = sit.BDCODSIT and X.BDDATASTD <= sit.BDDATAINISEFIP)) ';
        
          wsql = wsql||'where sit.BDCODEMP = '||wcodemporig||' and sit.BDCODCOL = '||wcodcolorig;

          IF (prdataresc IS NOT NULL) THEN
             wsql = wsql||' and ((sit.BDDATAFIMSIT >= '''||PRDATARESC||''')) ';

          wsql = wsql||' and (sit.BDDATAFIMSIT is not null) ';

          FOR EXECUTE STATEMENT wsql INTO
            :BDCODSIT, :BDDATAINISEFIP,
            :BDDATAINISIT, :BDDATAFIMSIT, : BDDIASSIT, :BDNBENEFICIOSIT, :BDDATAPERICIASIT, :BDDATAPARTOSIT,
            :BDDESCSIT, :BDGRUPOSIT, :BDCODVER, :BDCARENSIT, :BDTIPOPERDESIT, :BDDIASATESTADO, :BDNAOPRORROGAFERIAS, :BDSUSPMP,
            :BDBENEFDEFERIDO, :BDDATAINIATESTADOAUX, :BDDATAFIMATESTADOAUX, :BDDATAINIAFASTAUX, :BDDATAFIMAFASTAUX, :BDDIASPERDEPERAQUI, :BDSUBGRUPOSIT
          DO
            BEGIN
              execute statement 'select first 1 BDNAOALTPERAQUIMP936 from VRHF_BASE_TEMPPAR where bdcodemp = ' || :BDCODEMP into BDNAOALTPERAQUIMP936;
              SUSPEND;
            END

          wempx = null;
          wcolx = null;

          select bdcodemp from TMP_CONTROLE_PERAQUISFE where BDSPINSERIU = 6 AND bdcodemp = :wcodemporig and bdcodcol = :wcodcolorig and bdsessao = current_connection into :wcodcontrole;
          if (wcodcontrole is null) then
             begin
          select first 1 BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = :wcodemporig and BDCODCOLDEST = :wcodcolorig into :wempx, :wcolx;
          wcodemporig = wempx;
          wcodcolorig = wcolx;
               insert into TMP_CONTROLE_PERAQUISFE (BDCODEMP,BDCODCOL,BDSESSAO,BDSPINSERIU) values (:wcodemporig,:wcodcolorig,current_connection,6);
        end
          else
             begin
               wcodemporig = null;
               wcodcolorig = null;
    end
        end
    end
  delete from TMP_CONTROLE_PERAQUISFE where BDSPINSERIU = 6 AND bdsessao = current_connection;
END^

/* Restore proc. body: VRH_SP_DADOS_SITUACAO2 */
create or alter procedure VRH_SP_DADOS_SITUACAO2 (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRREFERENCIA integer,
    PRPREVIARESCISAO integer = 0,
    PRRETONARSITEMPORIG varchar(5) = 'FALSE' /* COLLATE WIN1252 - default */ )
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODSIT integer,
    BDDATAINISEFIP date,
    BDDATAINISIT date,
    BDDATAFIMSIT date,
    BDDIASSIT integer,
    BDNBENEFICIOSIT varchar(20),
    BDDATAPERICIASIT date,
    BDDATAPARTOSIT date,
    BDDESCSIT varchar(70),
    BDGRUPOSIT integer,
    BDCODVER integer,
    BDCODMFGENT integer,
    BDCODMFGSAI integer,
    BDCARENSIT integer,
    BDCODVER15DIAS integer,
    BDTIPOPERDESIT integer,
    BDINSSINTSIT DM_BOOLEAN,
    BDDIASATESTADO integer,
    BDNAOPRORROGAFERIAS varchar(5),
    BDSUSPENSAO DM_BOOLEAN,
    BDNAOALTPERAQUIMP936 DM_BOOLEAN,
    BDBENEFDEFERIDO DM_BOOLEAN,
    BDDATAINIATESTADOAUX date,
    BDDATAFIMATESTADOAUX date,
    BDDATAINIAFASTAUX date,
    BDDATAFIMAFASTAUX date,
    BDDIASPERDEPERAQUI integer,
    BDSUBGRUPOSIT integer)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(15000);
declare variable WEMPORIG integer;
declare variable WCOLORIG integer;
declare variable WEMPX integer;
declare variable WCOLX integer;
declare variable WDATARESC date;
declare variable WFIMMESANT date;
declare variable WSQL2 varchar(32700);
declare variable WCODCONTROLE integer;
BEGIN
  wsql = 'select sit.BDCODEMP, sit.BDCODCOL, sit.BDCODSIT, sit.BDDATAINISEFIP, '||
                'sit.BDDATAINISIT, sit.BDDATAFIMSIT, sit.BDDIASSIT, sit.BDNBENEFICIOSIT, sit.BDDATAPERICIASIT, sit.BDDATAPARTOSIT, '||
                'pSit.BDDESCSIT, pSit.BDGRUPOSIT, pSitDia.BDCODVER, pSitDia.BDCODMFGENT, pSitDia.BDCODMFGSAI, pSitDia.BDCARENSIT, pSitDia.BDCODVER15DIAS, pSit.BDTIPOPERDESIT, pSitDia.BDINSSINTSIT, SIT.BDDIASATESTADO, PSITDIA.BDNAOPRORROGAFERIAS, '||
                'COALESCE(PSIT.BDSUSPMP,''FALSE'') BDSUSPMP, sit.BDBENEFDEFERIDO, ' ||
                'SIT.BDDATAINIATESTADOAUX, SIT.BDDATAFIMATESTADOAUX, SIT.BDDATAINIAFASTAUX, SIT.BDDATAFIMAFASTAUX, psit.BDDIASPERDEPERAQUI, '||
                'psit.BDSUBGRUPOSIT '||
               'from ';
  wsql = wsql||'VRH_EMP_TSITCOL sit ';
  wsql = wsql||'join VRH_BASE_TPREPSIT pSit on (pSit.BDCODSIT = sit.BDCODSIT) ';
  wsql = wsql||'join VRH_BASE_TPREPSIT_DIA pSitDia on (pSitDia.BDCODSIT = sit.BDCODSIT and pSitDia.BDDATASTD = (select MAX(X.BDDATASTD) from VRH_BASE_TPREPSIT_DIA X where X.BDCODSIT = sit.BDCODSIT and X.BDDATASTD <= sit.BDDATAINISEFIP)) ';

  wwhere = '';
  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
    BEGIN
      wwhere = wwhere||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wwhere = wwhere||' and '||prcodcol;
    END

  IF (prreferencia IS NOT NULL AND prreferencia <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
         wwhere = wwhere||' and ';
       IF (prpreviarescisao = 1) THEN
          wwhere = wwhere||' (exists (select RESC.BDCODEMP, RESC.BDCODCOL from vrh_emp_trescisao_previa RESC where RESC.BDCODEMP = sit.BDCODEMP and '||
                           'RESC.BDCODCOL = sit.BDCODCOL and RESC.BDREFRESCISAOPREV = '||prreferencia||')) ';
       ELSE
          wwhere = wwhere||' (exists (select RESC.BDCODEMP, RESC.BDCODCOL from vrh_emp_trescisao RESC where RESC.BDCODEMP = sit.BDCODEMP and '||
                           'RESC.BDCODCOL = sit.BDCODCOL and RESC.BDREFRESCISAO = '||prreferencia||')) ';

       wfimmesant = CAST(SUBSTRING(PRREFERENCIA FROM 5 FOR 2)||'-01-'||SUBSTRING(PRREFERENCIA FROM 1 FOR 4) as DATE);
       wfimmesant = DATEADD(-1 DAY to wfimmesant);
     END
  ELSE
     wfimmesant = CAST(NULL as DATE);

  IF (wwhere <> '') THEN
    wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP, :BDCODCOL, :BDCODSIT, :BDDATAINISEFIP,
    :BDDATAINISIT, :BDDATAFIMSIT, :BDDIASSIT, :BDNBENEFICIOSIT, :BDDATAPERICIASIT, :BDDATAPARTOSIT,
    :BDDESCSIT, :BDGRUPOSIT, :BDCODVER, :BDCODMFGENT, :BDCODMFGSAI, :BDCARENSIT, :BDCODVER15DIAS,
    :BDTIPOPERDESIT, :BDINSSINTSIT, :BDDIASATESTADO, :BDNAOPRORROGAFERIAS, :BDSUSPENSAO, :BDBENEFDEFERIDO,
    :BDDATAINIATESTADOAUX, :BDDATAFIMATESTADOAUX, :BDDATAINIAFASTAUX, :BDDATAFIMAFASTAUX, :BDDIASPERDEPERAQUI,
    :BDSUBGRUPOSIT
  DO
    begin
      execute statement 'select first 1 BDNAOALTPERAQUIMP936 from VRHF_BASE_TEMPPAR where bdcodemp = ' || :BDCODEMP into BDNAOALTPERAQUIMP936;
      SUSPEND;
    end

  if (coalesce(upper(prretonarsitemporig), 'FALSE') = 'TRUE') then
     begin
       wwhere = 'select BDCODEMPORIG, BDCODCOLORIG, BDCODEMPDEST, BDCODCOLDEST from VRH_EMP_TTRANSCOL ';

       if (coalesce(prcodemp, '') <> '') then
          begin
            wwhere = wwhere||' where '||REPLACE(REPLACE(UPPER(prcodemp), 'BDCODEMP', 'BDCODEMPDEST'), 'SIT.', '');

            if (coalesce(prcodcol, '') <> '') then
               wwhere = wwhere||' and '||REPLACE(REPLACE(UPPER(prcodcol), 'BDCODCOL', 'BDCODCOLDEST'), 'SIT.', '');
          end

       for execute statement wwhere into :wemporig, :wcolorig, :BDCODEMP, :BDCODCOL do
         begin
           wdataresc = null;
           IF (prpreviarescisao = 1) THEN
              select first 1 BDDATARESCISAOPREV from VRH_EMP_TRESCISAO_PREVIA where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFRESCISAOPREV = :prreferencia into :wdataresc;
           else
              select first 1 BDDATARESCISAO from VRH_EMP_TRESCISAO where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFRESCISAO = :prreferencia into :wdataresc;

           if (wdataresc is not null) then
              begin
                while (coalesce(wemporig, 0) <> 0 and coalesce(wcolorig, 0) <> 0) do
                  begin
                    wsql = 'select sit.BDCODSIT, sit.BDDATAINISEFIP, '||
                                  'sit.BDDATAINISIT, sit.BDDATAFIMSIT, sit.BDDIASSIT, sit.BDNBENEFICIOSIT, sit.BDDATAPERICIASIT, sit.BDDATAPARTOSIT, '||
                                  'pSit.BDDESCSIT, pSit.BDGRUPOSIT, pSitDia.BDCODVER, pSitDia.BDCODMFGENT, pSitDia.BDCODMFGSAI, pSitDia.BDCARENSIT, pSitDia.BDCODVER15DIAS, pSit.BDTIPOPERDESIT, pSitDia.BDINSSINTSIT, SIT.BDDIASATESTADO, PSITDIA.BDNAOPRORROGAFERIAS, '||
                                  'COALESCE(PSIT.BDSUSPMP,''FALSE'') BDSUSPMP, sit.BDBENEFDEFERIDO, ' ||
                                  'sit.BDDATAINIATESTADOAUX, sit.BDDATAFIMATESTADOAUX, sit.BDDATAINIAFASTAUX, sit.BDDATAFIMAFASTAUX, psit.BDDIASPERDEPERAQUI, '||
                                  'psit.BDSUBGRUPOSIT '||
                                 'from ';
                  
                    wsql = wsql||'VRH_EMP_TSITCOL sit ';
                    wsql = wsql||'join VRH_BASE_TPREPSIT pSit on (pSit.BDCODSIT = sit.BDCODSIT) ';
                    wsql = wsql||'join VRH_BASE_TPREPSIT_DIA pSitDia on (pSitDia.BDCODSIT = sit.BDCODSIT and pSitDia.BDDATASTD = (select MAX(X.BDDATASTD) from VRH_BASE_TPREPSIT_DIA X where X.BDCODSIT = sit.BDCODSIT and X.BDDATASTD <= sit.BDDATAINISEFIP)) ';
                    wsql = wsql||'where SIT.BDCODEMP = '||wemporig||' and SIT.BDCODCOL = '||wcolorig;
     
                    FOR EXECUTE STATEMENT wsql INTO
                      :BDCODSIT, :BDDATAINISEFIP,
                      :BDDATAINISIT, :BDDATAFIMSIT, :BDDIASSIT, :BDNBENEFICIOSIT, :BDDATAPERICIASIT, :BDDATAPARTOSIT,
                      :BDDESCSIT, :BDGRUPOSIT, :BDCODVER, :BDCODMFGENT, :BDCODMFGSAI, :BDCARENSIT, :BDCODVER15DIAS,
                      :BDTIPOPERDESIT, :BDINSSINTSIT, :BDDIASATESTADO, :BDNAOPRORROGAFERIAS, :BDSUSPENSAO, :BDBENEFDEFERIDO,
                      :BDDATAINIATESTADOAUX, :BDDATAFIMATESTADOAUX, :BDDATAINIAFASTAUX, :BDDATAFIMAFASTAUX, :BDDIASPERDEPERAQUI, :BDSUBGRUPOSIT
                    DO
                      begin
                        if (:bddatafimsit is null) then
                          begin
                           wsql2 = 'select BDDATAFIMSIT from VRH_EMP_TSITCOL where BDCODEMP = '||:BDCODEMP||' and BDCODCOL = '||:BDCODCOL||' and BDDATAINISIT = '||''''||:BDDATAINISIT||'''';
                           execute statement wsql2 into :BDDATAFIMSIT;
                          end

                        execute statement 'select first 1 BDNAOALTPERAQUIMP936 from VRHF_BASE_TEMPPAR where bdcodemp = ' || :BDCODEMP into BDNAOALTPERAQUIMP936;
                        SUSPEND;
                      end

                    wempx = null;
                    wcolx = null;

                    select bdcodemp from TMP_CONTROLE_PERAQUISFE where BDSPINSERIU = 5 AND bdcodemp = :wemporig and bdcodcol = :wcolorig and bdsessao = current_connection into :wcodcontrole;
                    if (wcodcontrole is null) then
                       begin
                    select first 1 BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = :wemporig and BDCODCOLDEST = :wcolorig into :wempx, :wcolx;
                    wemporig = wempx;
                    wcolorig = wcolx;
                         insert into TMP_CONTROLE_PERAQUISFE (BDCODEMP,BDCODCOL,BDSESSAO,BDSPINSERIU) values (:wemporig,:wcolorig,current_connection,5);
                  end
                    else
                       begin
                         wemporig = null;
                         wcolorig = null;
              end
         end
     end
         end
     end
  delete from TMP_CONTROLE_PERAQUISFE where BDSPINSERIU = 5 AND bdsessao = current_connection;
END^

/* Restore proc. body: VRH_SP_DEMITIDOS_NO_MES */
ALTER PROCEDURE VRH_SP_DEMITIDOS_NO_MES(PRCODEMP VARCHAR(15000),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDDEMITIDOS INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
  wsql = 'select X.BDCODEMP, Count(X.BDCODCOL) '||
         'from vrh_emp_trescisao X '||
         'join VRH_EMP_TCOLCON Y on (Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL) ';
  wsql = wsql||'join vw_vrh_emp_tcolcon_vinc colcon_vinc on (colcon_vinc.bdcodemp = X.bdcodemp and colcon_vinc.bdcodcol = X.bdcodcol) ';
  wsql = wsql||'join vrh_base_tclasse classe on (colcon_vinc.bdcodcla = classe.bdcodcla and classe.bdgrupocla <> 5) ';

  wwhere = 'where Y.BDCONTRCOL <> 1 and '||
           'CAST((SUBSTRING( CAST(X.BDDATARESCISAO as VARCHAR(10)) from 1 for 4)||SUBSTRING( CAST(X.BDDATARESCISAO as VARCHAR(10)) from 6 for 2)) As INTEGER) = '||pranomes||' ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and ('||prcodemp||') ';

  wsql = wsql||wwhere;
  wsql = wsql||'group by X.bdcodemp ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDDEMITIDOS
  DO

  SUSPEND;
END
^

/* Restore proc. body: VRH_SP_EMPRESAS */
create or alter procedure VRH_SP_EMPRESAS (
    PREMP varchar(10000),
    PRREF integer,
    PRPROVISAO smallint = 0)
returns (
    BDCODMATRIZ integer,
    BDCODEMP integer,
    BDCODCID integer,
    BDCODUF integer,
    BDCODPLAFUC integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCENTROS integer,
    BDPAGEMP integer,
    BDFECHAMESEMP integer,
    BDFECHAVTEMP integer,
    BDARREMP integer,
    BDTIPOARREMP integer,
    BDTIPOFEREMP integer,
    BDSOMSALFEREMP varchar(5),
    BDTIPOAD13EMP integer,
    BDSOMSALAD13EMP varchar(5),
    BDPERCADSALEMP numeric(15,6),
    BDREFHOREMP varchar(5),
    BDLICREMFEREMP varchar(5),
    BDESTOUROEMP varchar(5),
    BDESTOURORESEMP varchar(5),
    BDFALFEREMP varchar(5),
    BDFALHORFEREMP varchar(5),
    BDDEPIRRESCEMP varchar(5),
    BDCODGPS integer,
    BDCODTERC integer,
    BDCODFPAS integer,
    BDCNAERATEMP numeric(15,6),
    BDEMPEMP numeric(15,6),
    BDAUTEMP numeric(15,6),
    BDFUNEMP numeric(15,6),
    BDCODSINPAT integer,
    BDCAPSOCEMP numeric(15,6),
    BDETIQEMP varchar(5),
    BDTAXSEREMP numeric(15,6),
    BDREFCAGEDEMP integer,
    BDPROPADMEMP integer,
    BDPROPRESEMP integer,
    BDPROPFEREMP integer,
    BDPROPSITEMP integer,
    BDCALCMEDIASTEMP integer,
    BDNATESTEMP integer,
    BDDATABASEEMP integer,
    BDPATEMP varchar(5),
    BDNROPROPEMP integer,
    BDSERPROPRIOPATEMP integer,
    BDPATREFCONVENIOEMP integer,
    BDPATCESTAALIMENTOEMP integer,
    BDPATADMCOZINHAEMP integer,
    BDPATREFTRANSPEMP integer,
    BDPATALICONVENIOEMP integer,
    BDSINDICALIZEMP varchar(5),
    BDCODBAN integer,
    BDCODAG integer,
    BDIDENTEMP varchar(14),
    BDCATSEFIPEMP integer,
    BDISENFILEMP numeric(15,6),
    BDCETRTALIZAEMP integer,
    BDCODIR integer,
    BDCODINSS integer,
    BDCODMEN integer,
    BDCALCFCNAFNEMP varchar(5),
    BDCALCC13NAFNEMP varchar(5),
    BDTIPOCONTAB integer,
    BDTIPOEMIGUIAS integer,
    BDFAP numeric(15,6),
    BDTAXACNAEEMP numeric(15,6),
    BDPERTERC numeric(15,6),
    BDPERCPIS numeric(15,6),
    BDLIMINARAVPREVEMP integer,
    BDSIMPLESGPS integer,
    BDMESDSREMP integer,
    BDCODPLACONVSAU integer,
    BDARREDONDAFN DM_BOOLEAN,
    BDARREDONDAFC DM_BOOLEAN,
    BDARREDONDAFE DM_BOOLEAN,
    BDARREDONDAA13 DM_BOOLEAN,
    BDARREDONDA13 DM_BOOLEAN,
    BDARREDONDAC13 DM_BOOLEAN,
    BDARREDONDAAD DM_BOOLEAN,
    BDARREDONDAAU DM_BOOLEAN,
    BDARREDONDAFA DM_BOOLEAN,
    BDPAGEMPCONTR integer,
    BDDESCFALHORASDIAS DM_BOOLEAN,
    BDPERCLIMIDESCPAR numeric(15,6),
    BDCALCC13FNNEGEMP DM_BOOLEAN,
    BDDSRMEDATUSAL DM_BOOLEAN,
    BDDATAINITABELA date,
    BDDATAININAOPERIOD date,
    BDDATAINIPERIOD date,
    BDDATAINISST date,
    BDREFINITABELA integer,
    BDREFININAOPERIOD integer,
    BDREFINIPERIOD integer,
    BDREFINISST integer,
    BDOPCAOESOCIAL integer,
    BDGRUPO integer,
    BDREFINIDCTFWEB integer,
    BDDATAINIRT date,
    BDDATAFGTSDIGITAL date,
    BDCODCLATRI integer,
    BDCONSIDERAFERICIDADETOM boolean)
as
declare variable WSQL varchar(10000);
declare variable WTAB varchar(10000);
declare variable WCODUSU integer;
declare variable WWHE varchar(10000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  /*
  for select BDCODUSU from sp_get_usuario
  into
    wcodusu
  do  */

  wsql = 'select temp.BDCODEMP, coalesce(temp.BDCODMATRIZ, temp.BDCODEMP) BDCODMATRIZ, temp_ref.BDCODCID, cid.bdcoduf, temp_ref.BDCODPLAFUC, temp_ref.BDNOMEMP, temp_ref.BDCODCENTROS, ';

  wsql = wsql || 'vrhf_temp_ref.bdpagemp, vrhf_temp_ref.bdfechamesemp, vrhf_temp_ref.bdfechavtemp, '||                   --'vrhf_tcal.bdpagemp, vrhf_tcal.bdfechamesemp, vrhf_tcal.bdfechavtemp, '||
                 'vrhf_temp_ref.bdarremp, vrhf_temp_ref.bdtipoarremp, vrhf_temp_ref.bdtipoferemp, '||                    --'vrhf_tcal.bdarremp, vrhf_tcal.bdtipoarremp, vrhf_tcal.bdtipoferemp, '||
                 'vrhf_temp_ref.bdsomsalferemp, vrhf_temp_ref.bdtipoad13emp, vrhf_temp_ref.bdsomsalad13emp, '||          --'vrhf_tcal.bdsomsalferemp, vrhf_tcal.bdtipoad13emp, vrhf_tcal.bdsomsalad13emp, '||
--                 'vrhf_temp_ref.bdpercadsalemp, vrhf_temp_ref.bdiradsalemp, vrhf_temp_ref.bdrefhoremp, '||               --'vrhf_tcal.bdpercadsalemp, vrhf_tcal.bdiradsalemp, vrhf_tcal.bdrefhoremp, '||
                 'vrhf_temp_ref.bdpercadsalemp, vrhf_temp_ref.bdrefhoremp, '||
                 'vrhf_temp_ref.bdlicremferemp, vrhf_temp_ref.bdestouroemp, vrhf_temp_ref.bdestouroresemp, '||           --'vrhf_tcal.bdlicremferemp, vrhf_tcal.bdestouroemp, vrhf_tcal.bdestouroresemp, '||
                 'vrhf_temp_ref.bdfalferemp, vrhf_temp_ref.bdfalhorferemp, vrhf_temp_ref.bddepirrescemp, ';              --'vrhf_tcal.bdfalferemp, vrhf_tcal.bdfalhorferemp, vrhf_tcal.bddepirrescemp, ';

  wsql = wsql || 'vrhf_temp_ref.BDCODGPS, vrhf_temp_ref.BDCODTERC,'||                                                                            --'vrhf_tgps.BDCODGPS, vrhf_tgps.BDCODGPSFUNEMP, vrhf_tgps.BDCODTERC, '||
                 'vrhf_temp_ref.BDCODFPAS, '||                                                                           --'vrhf_tgps.BDCODFPAS, vrhf_tgps.BDCODGPSTRANEMP, vrhf_tgps.BDFUNCOMPRAEMP, '||
                 'vrhf_temp_ref.BDCNAERATEMP, '||                                                                        --'vrhf_tgps.BDFUNVENDAEMP, vrhf_tgps.BDRETNFEMP, vrhf_tgps.BDCNAERATEMP, '||
                 'vrhf_temp_ref.BDEMPEMP, vrhf_temp_ref.BDAUTEMP, vrhf_temp_ref.BDFUNEMP, ';                             --'vrhf_tgps.BDEMPEMP, vrhf_tgps.BDAUTEMP, vrhf_tgps.BDFUNEMP, ';

  wsql = wsql || 'vrhf_temp_ref.BDCODSINPAT, vrhf_temp_ref.BDCAPSOCEMP, ';                                               --'vrhf_tgrc.BDCODSINPAT, vrhf_tgrc.BDCAPSOCEMP, ';

  wsql = wsql || 'vrhf_temp_ref.BDETIQEMP, vrhf_temp_ref.BDTAXSEREMP, '||                                                --'vrhf_tpar.BDPISDARFEMP, vrhf_tpar.BDETIQEMP, vrhf_tpar.BDTAXSEREMP, vrhf_tpar.BDREFCAGEDEMP, ';
                 'vrhf_temp_ref.BDREFCAGEDEMP, ';                                                                        --'vrhf_tpar.BDREFCAGEDEMP, ';

--  wsql = wsql || 'vrhf_temp_ref.BDPROPADMEMP, vrhf_temp_ref.BDPROPRESEMP, vrhf_temp_ref.BDPROPFEREMP, ' ||               --'vrhf_tpro.BDPROPADMEMP, vrhf_tpro.BDPROPRESEMP, vrhf_tpro.BDPROPFEREMP, ' ||
--                 'vrhf_temp_ref.BDPROPSITEMP, vrhf_temp_ref.BDCALCMEDIASTEMP, ';                                         --'vrhf_tpro.BDPROPSITEMP, vrhf_tpro.BDCALCMEDIASTEMP, ';

  if (coalesce(prprovisao, 0) > 0) then
     wsql = wsql || '1 BDPROPADMEMP, 1 BDPROPRESEMP, 1 BDPROPFEREMP, ' ||
                    '1 BDPROPSITEMP, vrhf_temp_ref.BDCALCMEDIASTEMP, ';
  else
     wsql = wsql || 'vrhf_temp_ref.BDPROPADMEMP, vrhf_temp_ref.BDPROPRESEMP, vrhf_temp_ref.BDPROPFEREMP, ' ||
                    'vrhf_temp_ref.BDPROPSITEMP, vrhf_temp_ref.BDCALCMEDIASTEMP, ';

  wsql = wsql || 'vrhf_temp_ref.BDNATESTEMP, vrhf_temp_ref.BDDATABASEEMP, vrhf_temp_ref.BDPATEMP, '||                    --'vrhf_trai.BDNATESTEMP, vrhf_trai.BDDATABASEEMP, vrhf_trai.BDPATEMP, '||
                 'vrhf_temp_ref.BDNROPROPEMP, vrhf_temp_ref.BDSERPROPRIOPATEMP, vrhf_temp_ref.BDPATREFCONVENIOEMP, '||   --'vrhf_trai.BDNROPROPEMP, vrhf_trai.BDSERPROPRIOPATEMP, vrhf_trai.BDPATREFCONVENIOEMP, '||
                 'vrhf_temp_ref.BDPATCESTAALIMENTOEMP, vrhf_temp_ref.BDPATADMCOZINHAEMP, '||                             --'vrhf_trai.BDPATCESTAALIMENTOEMP, vrhf_trai.BDPATADMCOZINHAEMP, '||
                 'vrhf_temp_ref.BDPATREFTRANSPEMP, vrhf_temp_ref.BDPATALICONVENIOEMP, vrhf_temp_ref.BDSINDICALIZEMP, ';  --'vrhf_trai.BDPATREFTRANSPEMP, vrhf_trai.BDPATALICONVENIOEMP, vrhf_trai.BDSINDICALIZEMP, ';

  wsql = wsql || 'vrhf_temp_ref.BDCODBAN, vrhf_temp_ref.BDCODAG, '||                       --'vrhf_tsef.BDCODBAN, vrhf_tsef.BDCODAG, vrhf_tsef.BDNAOCALC10EMP, vrhf_tsef.BDIDENTEMP, '||
                 'vrhf_temp_ref.BDIDENTEMP, vrhf_temp_ref.BDCATSEFIPEMP, vrhf_temp_ref.BDISENFILEMP, '||                 --'vrhf_tsef.BDIDENTEMP, vrhf_tsef.BDCATSEFIPEMP, vrhf_tsef.BDISENFILEMP, '||
                 'vrhf_temp_ref.BDCETRTALIZAEMP, ';                                                                      --'vrhf_tsef.BDCETRTALIZAEMP, ';

  wsql = wsql || 'vrhf_temp_ref.BDCODIR, vrhf_temp_ref.BDCODINSS, vrhf_temp_ref.BDCODMEN, ';--vrhf_temp_ref.BDCASASDECEMP,';                              --'vrhf_tvin.BDCODIR, vrhf_tvin.BDCODINSS, vrhf_tvin.BDCODMEN ';

  wsql = wsql || 'vrhf_temp_ref.BDCALCFCNAFNEMP,vrhf_temp_ref.BDCALCC13NAFNEMP,vrhf_temp_ref.BDTIPOCONTAB,vrhf_temp_ref.BDTIPOEMIGUIAS, vrhf_temp_ref.BDFAP, ';
  wsql = wsql || 'CNAE1.BDTAXACNAE BDTAXACNAEEMP, vrhf_temp_ref.BDPERTERC, COALESCE(IMPPIS.BDALIQIMPOSTO, 0.0) BDALIQIMPOSTO, vrhf_temp_ref.BDLIMINARAVPREVEMP, ';
  wsql = wsql || 'vrhf_temp_ref.BDSIMPLESGPS, vrhf_temp_ref.BDMESDSREMP, vrhf_temp_ref.BDCODPLACONVSAU, vrhf_temp_ref.Bdarredondafn, vrhf_temp_ref.Bdarredondafc,';
  wsql = wsql || 'vrhf_temp_ref.Bdarredondafe, vrhf_temp_ref.Bdarredondaa13, vrhf_temp_ref.Bdarredonda13, vrhf_temp_ref.Bdarredondac13, vrhf_temp_ref.Bdarredondaad,';
  wsql = wsql || 'vrhf_temp_ref.Bdarredondaau, vrhf_temp_ref.Bdarredondafa, vrhf_temp_ref.BDPAGEMPCONTR, vrhf_temp_ref.BDDESCFALHORASDIAS, vrhf_temp_ref.BDPERCLIMIDESCPAR, ';    --Sol. 14911 - Bruno L. R. - 23/03/2017
  wsql = wsql || 'vrhf_temp_ref.BDCALCC13FNNEGEMP, vrhf_temp_ref.bddsrmedatusal, ';

  wsql = wsql || 'faseamento.BDDATAINITABELA     , ';
  wsql = wsql || 'faseamento.BDDATAININAOPERIOD  , ';
  wsql = wsql || 'faseamento.BDDATAINIPERIOD     , ';
  wsql = wsql || 'faseamento.BDDATAINISST        , ';
  wsql = wsql || 'faseamento.BDREFINITABELA      , ';
  wsql = wsql || 'faseamento.BDREFININAOPERIOD   , ';
  wsql = wsql || 'faseamento.BDREFINIPERIOD      , ';
  wsql = wsql || 'faseamento.BDREFINISST         , ';
  wsql = wsql || 'faseamento.BDOPCAOESOCIAL      , ';
  wsql = wsql || 'faseamento.BDGRUPO             , ';
  wsql = wsql || 'faseamento.BDREFINIDCTFWEB     , ';
  wsql = wsql || 'faseamento.BDDATAINIRT         , ';
  wsql = wsql || 'faseamento.BDDATAFGTSDIGITAL, ';
  wsql = wsql || 'esocial.BDCODCLATRI, ';
  wsql = wsql || 'vrhf_temp_ref.BDCONSIDERAFERICIDADETOM ';

  wsql = wsql || 'from TEMPRESAS temp ';
  wsql = wsql || 'left outer join VW_EMPRESAS_REF_ATUAL temp_ref ';    --wsql = wsql || 'left outer join tempresas_ref temp_ref ';
  wsql = wsql ||   'on (temp_ref.BDCODEMP = temp.BDCODEMP) ';     --wsql = wsql || 'on ((temp.bdcodemp = temp_ref.bdcodemp) and (temp_ref.bdrefemp = (select max(bdrefemp) from tempresas_ref x where temp.bdcodemp = x.bdcodemp and x.bdrefemp <= '||:prref||'))) ';

  wsql = wsql || 'left outer join tcidade cid ';
  wsql = wsql || 'on (temp_ref.bdcodcid = cid.bdcodcid) ';

  wtab = 'left outer join VW_VRHF_EMPRESAS_REF_ATUAL vrhf_temp_ref ';
  wtab = wtab ||   'on (vrhf_temp_ref.BDCODEMP = temp.BDCODEMP) ';
  wtab = wtab ||'left outer join vw_tcnae_ref CNAE1 ';
  wtab = wtab ||   'on (CNAE1.BDCODCNAE = temp_ref.BDCODCNAE) ';
--  wtab = wtab ||'left outer join vrh_base_tterceiros TERC ';
--  wtab = wtab ||   'on (TERC.BDCODTERC = vrhf_temp_ref.BDCODTERC) ';
--  wtab = wtab ||'left outer join SP_TEMPRESAIMPOSTO_REF(null, '||prref||', 1) IMPPIS ';
--  wtab = wtab ||   'on (IMPPIS.BDCODEMP = TEMP.BDCODEMP and IMPPIS.bdtiporetencao = 1) ';
  wTab = wTab|| ' left outer join SP_IMPOSTO_EMPRESA(coalesce(temp.bdcodmatriz, temp.bdcodemp),2,1,'||prref||',1) IMPPIS on (IMPPIS.BDCODEMP = coalesce(TEMP.BDCODMATRIZ, TEMP.BDCODEMP) and IMPPIS.bdtiporetencao = 1) ';
  wTab = wTab|| ' left outer join VRH_ESOCIAL_TFASEAMENTO faseamento on faseamento.BDCODEMP = tEMP.BDCODEMP ';
  wTab = wTab|| ' LEFT OUTER JOIN VRHF_BASE_TEMPESOCIAL esocial ON (esocial.bdcodemp = temp_ref.bdcodemp AND esocial.bdrefemp = temp_ref.BDEMPREF) ';

  wwhe = '';

  /* filtra as empresas por usuario
  if (wcodusu is not null and wcodusu <> 0) then
     begin
       wwhe = wwhe||'((exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||') and '||
                        'exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||' and Y.BDCODEMP = temp.BDCODEMP)) '||
                       'or '||
                       '(not exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||'))'||
                       ') ';
     end   */

  IF (premp IS NOT NULL) THEN
     BEGIN
       IF (wwhe <> '') THEN
          wwhe = wwhe||' and ';

       wwhe = wwhe ||premp ;
     END

  IF (wwhe <> '') THEN
     wwhe = ' where '||wwhe;

  --wtab = wtab || ' order by temp.BDCODEMP ';

     /*temp.bdcodemp*/
   
  FOR EXECUTE STATEMENT wsql||wtab||wwhe
  INTO
    :BDCODEMP,
    :BDCODMATRIZ,
    :BDCODCID,
    :bdcoduf, 
    :BDCODPLAFUC,
    :BDNOMEMP,
    :BDCODCENTROS,

    :bdpagemp,
    :bdfechamesemp,
    :bdfechavtemp,
    :bdarremp,
    :bdtipoarremp,
    :bdtipoferemp,
    :bdsomsalferemp,
    :bdtipoad13emp,
    :bdsomsalad13emp,
    :bdpercadsalemp,
--    :bdiradsalemp,
    :bdrefhoremp,
    :bdlicremferemp,
    :bdestouroemp,
    :bdestouroresemp,
    :bdfalferemp,
    :bdfalhorferemp,
    :bddepirrescemp,

    :BDCODGPS,
    :BDCODTERC,
    :BDCODFPAS,
    :BDCNAERATEMP,
    :BDEMPEMP,
    :BDAUTEMP,
    :BDFUNEMP,

    :BDCODSINPAT,
    :BDCAPSOCEMP,

    :BDETIQEMP,
    :BDTAXSEREMP,
    :BDREFCAGEDEMP,

    :BDPROPADMEMP,
    :BDPROPRESEMP,
    :BDPROPFEREMP,
    :BDPROPSITEMP,
    :BDCALCMEDIASTEMP,

    :BDNATESTEMP,
    :BDDATABASEEMP,
    :BDPATEMP,
    :BDNROPROPEMP,
    :BDSERPROPRIOPATEMP,
    :BDPATREFCONVENIOEMP,
    :BDPATCESTAALIMENTOEMP,
    :BDPATADMCOZINHAEMP,
    :BDPATREFTRANSPEMP,
    :BDPATALICONVENIOEMP,
    :BDSINDICALIZEMP,

    :BDCODBAN,
    :BDCODAG,
    :BDIDENTEMP,
    :BDCATSEFIPEMP,
    :BDISENFILEMP,
    :BDCETRTALIZAEMP,

    :BDCODIR,
    :BDCODINSS,
    :BDCODMEN,
--    :BDCASASDECEMP,
    :BDCALCFCNAFNEMP,
    :BDCALCC13NAFNEMP,
    :BDTIPOCONTAB,
    :BDTIPOEMIGUIAS,
    :BDFAP,
    :BDTAXACNAEEMP,
    :BDPERTERC,
    :BDPERCPIS,
    :BDLIMINARAVPREVEMP,
    :BDSIMPLESGPS,
    :BDMESDSREMP,
    :BDCODPLACONVSAU,
    :BDARREDONDAFN,
    :BDARREDONDAFC,
    :BDARREDONDAFE,
    :BDARREDONDAA13,
    :BDARREDONDA13,
    :BDARREDONDAC13,
    :BDARREDONDAAD,
    :BDARREDONDAAU,
    :BDARREDONDAFA,
    :BDPAGEMPCONTR,
    :BDDESCFALHORASDIAS,
    :BDPERCLIMIDESCPAR,  --Sol. 14911 - Bruno L. R. - 23/03/2017
    :BDCALCC13FNNEGEMP,
    :BDDSRMEDATUSAL,
    :BDDATAINITABELA     ,
    :BDDATAININAOPERIOD  ,
    :BDDATAINIPERIOD     ,
    :BDDATAINISST        ,
    :BDREFINITABELA      ,
    :BDREFININAOPERIOD   ,
    :BDREFINIPERIOD      ,
    :BDREFINISST         ,
    :BDOPCAOESOCIAL      ,
    :BDGRUPO             ,
    :BDREFINIDCTFWEB     ,
    :BDDATAINIRT         ,
    :BDDATAFGTSDIGITAL   ,
    :BDCODCLATRI         ,
    :BDCONSIDERAFERICIDADETOM

  DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

--Sol. 17580 - Bruno L. R. - 17/07/2017 - Criação do campo BDVALSALMINVIGENTE para retornar o valor do salário mínimo vigente. 
/* Restore proc. body: VRH_SP_FERIAS_PER_AQUIS */
create or alter procedure VRH_SP_FERIAS_PER_AQUIS (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREF integer,
    PRDATAPREVRESC date = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDINIPERGOZOFE date,
    BDFIMPERAQUISFE date,
    BDFIMPERGOZOFE date,
    BDDATAPAGFE date,
    BDQTDGOZOFE numeric(18,6),
    BDQTDABONOFE numeric(18,6),
    BDSALDOINIFE numeric(15,6),
    BDSALDOFIMFE numeric(15,6),
    BDBASEIRFE numeric(15,6),
    BDALIQIRFE numeric(15,6),
    BDVALORIRFE numeric(15,6),
    BDBASEINSSFE numeric(15,6),
    BDALIQINSSFE numeric(15,6),
    BDVALORINSSFE numeric(15,6),
    BDDEPFE numeric(15,6),
    BDSALBASEFE numeric(15,6),
    BDSALBASEHEFE numeric(15,6),
    BDDATABAIXAFE date,
    BDCOLETIVASFE varchar(5),
    BDREFPAGABOFE integer,
    BDFALTASFE numeric(15,6),
    BDFERIADOSFE integer,
    BDSALDOFINALSINDFE numeric(18,6),
    BDVALSALMINVIGENTE numeric(18,6),
    BDMIGRACAO DM_BOOLEAN,
    BDPAGO DM_BOOLEAN,
    BDCALCA13FE DM_BOOLEAN,
    BDTEMPOSERVFE integer,
    BDQTDGOZORECIBOFE numeric(18,6),
    BDISTRANSFERENCIA boolean)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(30000);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
declare variable WDATAAUX date;
declare variable WFALTAS integer;
declare variable WREFPAG integer;
declare variable WEMPX integer;
declare variable WCOLX integer;
declare variable WCODCONTROLE integer;
BEGIN

  wsql = 'select BDCODEMP, BDCODCOL, BDINIPERAQUISFE, BDCODFE, BDINIPERGOZOFE, BDFIMPERAQUISFE, '||
                'BDFIMPERGOZOFE, BDDATAPAGFE, BDQTDGOZOFE, BDQTDABONOFE, BDSALDOINIFE, '||
                'BDSALDOFIMFE, BDBASEIRFE, BDALIQIRFE, BDVALORIRFE, BDBASEINSSFE, BDALIQINSSFE, '||
                'BDVALORINSSFE, BDDEPFE, BDSALBASEFE, BDSALBASEHEFE, BDDATABAIXAFE, BDCOLETIVASFE, '||
                'BDREFPAGABOFE, BDFALTASFE, BDFERIADOSFE, BDSALDOFINALSINDFE, BDVALSALMINVIGENTE, BDCALCA13FE, BDTEMPOSERVFE, BDQTDGOZORECIBOFE, BDISTRANSFERENCIA ';

  wsql = wsql || 'from VRH_EMP_TFERIAS ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (prref IS NOT NULL AND prref <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'((extract(YEAR from BDINIPERAQUISFE)||substring(BDINIPERAQUISFE from 6 for 2) <= '||prref||') or (BDREFINIFE = '||prref||') or (BDREFFIMFE = '||prref||'))';
     END

  IF (wwhere <> '') THEN
     BEGIN
       wwhere = ' where '||wwhere;
       wsql = wsql||wwhere;
     END

  FOR EXECUTE STATEMENT wsql
  INTO :BDCODEMP, :BDCODCOL, :BDINIPERAQUISFE, :BDCODFE, :BDINIPERGOZOFE, :BDFIMPERAQUISFE,
       :BDFIMPERGOZOFE, :BDDATAPAGFE, :BDQTDGOZOFE, :BDQTDABONOFE, :BDSALDOINIFE,
       :BDSALDOFIMFE, :BDBASEIRFE, :BDALIQIRFE, :BDVALORIRFE, :BDBASEINSSFE, :BDALIQINSSFE,
       :BDVALORINSSFE, :BDDEPFE, :BDSALBASEFE, :BDSALBASEHEFE, :BDDATABAIXAFE, :BDCOLETIVASFE,
       :BDREFPAGABOFE, :BDFALTASFE, :BDFERIADOSFE,
       :BDSALDOFINALSINDFE, :BDVALSALMINVIGENTE, :BDCALCA13FE, :BDTEMPOSERVFE, :BDQTDGOZORECIBOFE, :BDISTRANSFERENCIA
  DO
    begin
      wdataaux = null;
      select first 1 BDINIPERAQUISFE from VRHF_EMP_TVERBAFE where BDCODEMP = :bdcodemp and BDCODCOL = :bdcodcol and BDINIPERAQUISFE = :bdiniperaquisfe and BDCODFE = :bdcodfe into :wdataaux;

      if (wdataaux is null) then
         BDMIGRACAO = 'TRUE';
      else
         BDMIGRACAO = 'FALSE';

      BDPAGO = 'FALSE';

      if (bdfimpergozofe is not null) then
         begin
           wrefpag = CAST((SUBSTRING(CAST(bdfimpergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdfimpergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
           if (wrefpag <= prref) then
              BDPAGO = 'TRUE';
         end

      if (BDPAGO = 'FALSE') then
         begin
           if (bdinipergozofe is not null) then
              begin
                wrefpag = CAST((SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                if (wrefpag <= prref) then
                   BDPAGO = 'TRUE';
              end
         end

      if (BDPAGO = 'FALSE') then
         begin
           if (coalesce(bdrefpagabofe, 0) > 0) then
              begin
                if (bdrefpagabofe <= prref) then
                   BDPAGO = 'TRUE';
              end
         end

      wfaltas = null;
      select count(*)
      from VRH_EMP_TFALTAS_ITENS
      where BDCODEMP = :bdcodemp and
            BDCODCOL = :bdcodcol and
            BDDATAFAL between :bdiniperaquisfe and :bdfimperaquisfe and
                  coalesce(BDTIPOFAL, 0) = 1 and
                  coalesce(BDTIPODESCFAL, 0) = 0
      into :wfaltas;

      if (coalesce(wfaltas, 0) <> 0) then
         BDFALTASFE = wfaltas;

      if (:PRDATAPREVRESC is not null) then
        begin
          if ((:BDFIMPERGOZOFE is null) or ((:BDFIMPERGOZOFE > :PRDATAPREVRESC) and (:BDINIPERGOZOFE < :PRDATAPREVRESC))) then
            begin
              BDFIMPERGOZOFE = :PRDATAPREVRESC;
            end
        end

      SUSPEND;
    end

-- Informações de férias de transferidos da empresa origem

  wwhere = 'select BDCODEMPORIG, BDCODCOLORIG, BDCODEMPDEST, BDCODCOLDEST from VRH_EMP_TTRANSCOL ';

  if (coalesce(prcodemp, '') <> '') then
     begin
       wwhere = wwhere||' where '||REPLACE(UPPER(prcodemp), 'BDCODEMP', 'BDCODEMPDEST');

       if ((coalesce(prcodcol, '') <> '') and (not position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0)) then
          wwhere = wwhere||' and '||REPLACE(UPPER(prcodcol), 'BDCODCOL', 'BDCODCOLDEST');

       else if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
          wwhere = wwhere||' and '||'BDCODCOLDEST'||substring(PRCODCOL from 9);
     end

  for execute statement wwhere into :wcodemporig, :wcodcolorig, :BDCODEMP, :BDCODCOL do
    begin
      while (coalesce(wcodemporig, 0) <> 0 and coalesce(wcodcolorig, 0) <> 0) do
        begin
          wsql = 'select FER.BDINIPERAQUISFE, FER.BDCODFE, FER.BDINIPERGOZOFE, FER.BDFIMPERAQUISFE, '||
                        'FER.BDFIMPERGOZOFE, FER.BDDATAPAGFE, FER.BDQTDGOZOFE, FER.BDQTDABONOFE, FER.BDSALDOINIFE, '||
                        'FER.BDSALDOFIMFE, FER.BDBASEIRFE, FER.BDALIQIRFE, FER.BDVALORIRFE, FER.BDBASEINSSFE, FER.BDALIQINSSFE, '||
                        'FER.BDVALORINSSFE, FER.BDDEPFE, FER.BDSALBASEFE, FER.BDSALBASEHEFE, FER.BDDATABAIXAFE, FER.BDCOLETIVASFE, '||
                        'FER.BDREFPAGABOFE, FER.BDFALTASFE, FER.BDFERIADOSFE, FER.BDSALDOFINALSINDFE, FER.BDVALSALMINVIGENTE, FER.BDCALCA13FE, '||
                        'FER.BDTEMPOSERVFE, FER.BDQTDGOZORECIBOFE, True ';
        
          wsql = wsql||
                 'from VRH_EMP_TFERIAS FER ';
        
          wsql = wsql||'where FER.BDCODEMP = '||wcodemporig||' and FER.BDCODCOL = '||wcodcolorig;

          IF (coalesce(prref, 0) <> 0) THEN
             wsql = wsql||' and ((extract(YEAR from FER.BDINIPERAQUISFE)||substring(FER.BDINIPERAQUISFE from 6 for 2) <= '||prref||') or (FER.BDREFINIFE = '||prref||') or (FER.BDREFFIMFE = '||prref||'))';

          FOR EXECUTE STATEMENT wsql
          INTO :BDINIPERAQUISFE, :BDCODFE, :BDINIPERGOZOFE, :BDFIMPERAQUISFE,
               :BDFIMPERGOZOFE, :BDDATAPAGFE, :BDQTDGOZOFE, :BDQTDABONOFE, :BDSALDOINIFE,
               :BDSALDOFIMFE, :BDBASEIRFE, :BDALIQIRFE, :BDVALORIRFE, :BDBASEINSSFE, :BDALIQINSSFE,
               :BDVALORINSSFE, :BDDEPFE, :BDSALBASEFE, :BDSALBASEHEFE, :BDDATABAIXAFE, :BDCOLETIVASFE,
               :BDREFPAGABOFE, :BDFALTASFE, :BDFERIADOSFE,
               :BDSALDOFINALSINDFE, :BDVALSALMINVIGENTE, :BDCALCA13FE, :BDTEMPOSERVFE, :BDQTDGOZORECIBOFE, :BDISTRANSFERENCIA
          DO
            begin
              wdataaux = null;
              select first 1 BDINIPERAQUISFE
              from VRHF_EMP_TVERBAFE
              where BDCODEMP = :wcodemporig and BDCODCOL = :wcodcolorig and BDINIPERAQUISFE = :bdiniperaquisfe and BDCODFE = :bdcodfe
              into :wdataaux;
        
              if (wdataaux is null) then
                 BDMIGRACAO = 'TRUE';
              else
                 BDMIGRACAO = 'FALSE';
        
              BDPAGO = 'FALSE';
        
              if (bdfimpergozofe is not null) then
                 begin
                   wrefpag = CAST((SUBSTRING(CAST(bdfimpergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdfimpergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                   if (wrefpag <= prref) then
                      BDPAGO = 'TRUE';
                 end
        
              if (BDPAGO = 'FALSE') then
                 begin
                   if (bdinipergozofe is not null) then
                      begin
                        wrefpag = CAST((SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                        if (wrefpag <= prref) then
                           BDPAGO = 'TRUE';
                      end
                 end
        
              if (BDPAGO = 'FALSE') then
                 begin
                   if (coalesce(bdrefpagabofe, 0) > 0) then
                      begin
                        if (bdrefpagabofe <= prref) then
                           BDPAGO = 'TRUE';
                      end
                 end
        
              wfaltas = null;
              select count(*)
              from VRH_EMP_TFALTAS_ITENS
              where BDCODEMP = :wcodemporig and
                    BDCODCOL = :wcodcolorig and
                    BDDATAFAL between :bdiniperaquisfe and :bdfimperaquisfe and
                          coalesce(BDTIPOFAL, 0) = 1 and
                          coalesce(BDTIPODESCFAL, 0) = 0
              into :wfaltas;
        
              if (coalesce(wfaltas, 0) <> 0) then
                 BDFALTASFE = wfaltas;

              if (:PRDATAPREVRESC is not null) then
                begin
                  if ((:BDFIMPERGOZOFE is null) or ((:BDFIMPERGOZOFE > :PRDATAPREVRESC) and (:BDINIPERGOZOFE < :PRDATAPREVRESC))) then
                    begin
                      BDFIMPERGOZOFE = :PRDATAPREVRESC;
                    end
                end
        
              SUSPEND;
            end

          wempx = null;
          wcolx = null;

          select bdcodemp from TMP_CONTROLE_PERAQUISFE where BDSPINSERIU = 7 AND bdcodemp = :wcodemporig and bdcodcol = :wcodcolorig and bdsessao = current_connection into :wcodcontrole;
          if (wcodcontrole is null) then
             begin
          select first 1 BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = :wcodemporig and BDCODCOLDEST = :wcodcolorig into :wempx, :wcolx;
          wcodemporig = wempx;
          wcodcolorig = wcolx;
               insert into TMP_CONTROLE_PERAQUISFE (BDCODEMP,BDCODCOL,BDSESSAO,BDSPINSERIU) values (:wcodemporig,:wcodcolorig,current_connection,7);
        end
          else
             begin
               wcodemporig = null;
               wcodcolorig = null;
    end
        end
    end
  delete from TMP_CONTROLE_PERAQUISFE where BDSPINSERIU = 7 AND  bdsessao = current_connection;
END^

/* Restore proc. body: VRH_SP_FERIAS_PER_AQUIS_RESC */
create or alter procedure VRH_SP_FERIAS_PER_AQUIS_RESC (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREF integer,
    PRPROVISAO integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDINIPERGOZOFE date,
    BDFIMPERAQUISFE date,
    BDFIMPERGOZOFE date,
    BDDATAPAGFE date,
    BDQTDGOZOFE numeric(18,6),
    BDQTDABONOFE numeric(18,6),
    BDSALDOINIFE numeric(15,6),
    BDSALDOFIMFE numeric(15,6),
    BDBASEIRFE numeric(15,6),
    BDALIQIRFE numeric(15,6),
    BDVALORIRFE numeric(15,6),
    BDBASEINSSFE numeric(15,6),
    BDALIQINSSFE numeric(15,6),
    BDVALORINSSFE numeric(15,6),
    BDDEPFE numeric(15,6),
    BDSALBASEFE numeric(15,6),
    BDSALBASEHEFE numeric(15,6),
    BDDATABAIXAFE date,
    BDCOLETIVASFE varchar(5),
    BDREFPAGABOFE integer,
    BDFALTASFE numeric(15,6),
    BDFERIADOSFE integer,
    BDSALDOFINALSINDFE numeric(18,6),
    BDVALSALMINVIGENTE numeric(18,6),
    BDMIGRACAO DM_BOOLEAN,
    BDPAGO DM_BOOLEAN,
    BDFERIASMES numeric(15,6),
    BDQTDGOZORECIBOFE numeric(18,6),
    BDISTRANSFERENCIA boolean)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(15000);
declare variable WDATAAUX date;
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
declare variable WFALTAS integer;
declare variable WREFPAG integer;
declare variable WEMPX integer;
declare variable WCOLX integer;
declare variable WCODCONTROLE integer;
begin
  prprovisao = coalesce(prprovisao, 0);

  wsql = 'select FE.BDCODEMP, FE.BDCODCOL, FE.BDINIPERAQUISFE, FE.BDCODFE, FE.BDINIPERGOZOFE, FE.BDFIMPERAQUISFE, '||
                'FE.BDFIMPERGOZOFE, FE.BDDATAPAGFE, FE.BDQTDGOZOFE, FE.BDQTDABONOFE, FE.BDSALDOINIFE, '||
                'FE.BDSALDOFIMFE, FE.BDBASEIRFE, FE.BDALIQIRFE, FE.BDVALORIRFE, FE.BDBASEINSSFE, '||
                'FE.BDALIQINSSFE, FE.BDVALORINSSFE, FE.BDDEPFE, FE.BDSALBASEFE, FE.BDSALBASEHEFE, FE.BDDATABAIXAFE, '||
                'FE.BDCOLETIVASFE, FE.BDREFPAGABOFE, FE.BDFERIADOSFE, FE.BDSALDOFINALSINDFE, FE.BDVALSALMINVIGENTE, '||
                'FE.BDQTDGOZORECIBOFE, FE.BDISTRANSFERENCIA '; -- 81269 - Raphael Teodoro - 10/11/2022

  wsql = wsql || 'from VRH_EMP_TFERIAS FE ';

  wwhere = '';

  if (prcodemp is not null and prcodemp <> '') then
     wwhere = wwhere||prcodemp;

  if (prcodcol is not null and prcodcol <> '') then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     end

  if (prref is not null and prref <> 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       if (prprovisao <> 2) then
          wwhere = wwhere||'extract(YEAR from FE.BDINIPERAQUISFE)||substring(FE.BDINIPERAQUISFE from 6 for 2) <= '||prref||' and ';

       wwhere = wwhere||'((FE.BDINIPERGOZOFE is not null and (extract(YEAR from FE.BDINIPERGOZOFE)||substring(FE.BDINIPERGOZOFE from 6 for 2) <= '||prref||' or extract(YEAR from FE.BDFIMPERGOZOFE)||substring(FE.BDFIMPERGOZOFE from 6 for 2) <= '||prref||'))'||
                        ' or '||
                        '(FE.BDINIPERGOZOFE is null and BDREFPAGABOFE <= '||prref||')) ';
     end

  if (wwhere <> '') then
     wwhere = wwhere||' and ';

  if (prprovisao in (0, 2)) then
     begin
       wwhere = wwhere||'exists(select X.BDCODEMP, X.BDCODCOL, X.BDINIPERAQUISFE, MAX(X.BDCODFE) BDCODF '||
                               'from VRH_EMP_TFERIAS X '||
                               'where ';

       if (prprovisao = 0) then
          wwhere = wwhere||'extract(year from X.BDINIPERAQUISFE) || substring(X.BDINIPERAQUISFE from 6 for 2) <= '||prref||' and ';

       wwhere = wwhere||
                                '((X.BDINIPERGOZOFE is not null and '||
                                  '((extract(year from X.BDINIPERGOZOFE) || substring(X.BDINIPERGOZOFE from 6 for 2) <= '||prref||') or '||
                                   '(extract(year from X.BDFIMPERGOZOFE) || substring(X.BDFIMPERGOZOFE from 6 for 2) <= '||prref||'))) or (X.BDINIPERGOZOFE is null and '||
                                    'BDREFPAGABOFE <= '||prref||')) '||
                               'group by X.BDCODEMP, X.BDCODCOL, X.BDINIPERAQUISFE '||
                               'having X.BDCODEMP = FE.BDCODEMP and X.BDCODCOL = FE.BDCODCOL and X.BDINIPERAQUISFE = FE.BDINIPERAQUISFE and MAX(X.BDCODFE) = FE.BDCODFE'||
                              ') ';
     end
  else
     begin
        wwhere = wwhere||'exists(select X.BDCODEMP, X.BDCODCOL, X.BDINIPERAQUISFE, X.BDCODFE BDCODF '||
                                'from VRH_EMP_TFERIAS X '||
                                'where X.BDCODEMP = FE.BDCODEMP and X.BDCODCOL = FE.BDCODCOL and X.BDINIPERAQUISFE = FE.BDINIPERAQUISFE and X.BDCODFE = FE.BDCODFE'||
                               ') ';
     end

  wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  for execute statement wsql
  into :BDCODEMP, :BDCODCOL, :BDINIPERAQUISFE, :BDCODFE, :BDINIPERGOZOFE, :BDFIMPERAQUISFE,
       :BDFIMPERGOZOFE, :BDDATAPAGFE, :BDQTDGOZOFE, :BDQTDABONOFE, :BDSALDOINIFE,
       :BDSALDOFIMFE, :BDBASEIRFE, :BDALIQIRFE, :BDVALORIRFE, :BDBASEINSSFE, :BDALIQINSSFE,
       :BDVALORINSSFE, :BDDEPFE, :BDSALBASEFE, :BDSALBASEHEFE, :BDDATABAIXAFE, :BDCOLETIVASFE,
       :BDREFPAGABOFE, :BDFERIADOSFE, :BDSALDOFINALSINDFE, :BDVALSALMINVIGENTE, :BDQTDGOZORECIBOFE,
       :BDISTRANSFERENCIA
  do
    begin
      wdataaux = null;
      select first 1 BDINIPERAQUISFE from VRHF_EMP_TVERBAFE where BDCODEMP = :bdcodemp and BDCODCOL = :bdcodcol and BDINIPERAQUISFE = :bdiniperaquisfe and BDCODFE = :bdcodfe into :wdataaux;

      if (wdataaux is null) then
         BDMIGRACAO = 'TRUE';
      else
         BDMIGRACAO = 'FALSE';

      wfaltas = null;
      select count(*)
      from VRH_EMP_TFALTAS_ITENS
      where BDCODEMP = :bdcodemp and
            BDCODCOL = :bdcodcol and
            BDDATAFAL between :bdiniperaquisfe and :bdfimperaquisfe and
                  coalesce(BDTIPOFAL, 0) = 1 and
                  coalesce(BDTIPODESCFAL, 0) = 0
      into :wfaltas;

      if (coalesce(wfaltas, 0) <> 0) then
         BDFALTASFE = wfaltas;
      else
         select sum(coalesce(BDFALTASFE, 0)) from VRH_EMP_TFERIAS where BDCODEMP = :bdcodemp and BDCODCOL = :bdcodcol and BDINIPERAQUISFE = :bdiniperaquisfe into :BDFALTASFE;

      BDFALTASFE = coalesce(BDFALTASFE, 0);

      BDPAGO = 'FALSE';

      if (bdfimpergozofe is not null) then
         begin
           wrefpag = CAST((SUBSTRING(CAST(bdfimpergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdfimpergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
           if (wrefpag <= prref) then
              BDPAGO = 'TRUE';
         end

      if (BDPAGO = 'FALSE') then
         begin
           if (bdinipergozofe is not null) then
              begin
                wrefpag = CAST((SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                if (wrefpag <= prref) then
                   BDPAGO = 'TRUE';
              end
         end

      if (BDPAGO = 'FALSE') then
         begin
           if (coalesce(bdrefpagabofe, 0) > 0) then
              begin
                if (bdrefpagabofe <= prref) then
                   BDPAGO = 'TRUE';
              end
         end

      BDFERIASMES = 0;
      if (upper(coalesce(BDCOLETIVASFE, 'FALSE')) = 'TRUE') then
         begin
           select first 1 coalesce(BDDIASFERFE, 0) + coalesce(BDDIASABOFE, 0)
           from VRH_EMP_TFERIASREF
           where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDINIPERAQUISFE = :BDINIPERAQUISFE and BDCODFE = :BDCODFE and BDREFFE <= :prref
           into :BDFERIASMES;
           BDFERIASMES = coalesce(BDFERIASMES, 0);
         end

      suspend;
    end

  -- Informações de transferências, empresa origem
  wwhere = 'select FE.BDCODEMPORIG, FE.BDCODCOLORIG, FE.BDCODEMPDEST, FE.BDCODCOLDEST from VRH_EMP_TTRANSCOL FE ';

  if (coalesce(prcodemp, '') <> '') then
     begin
       wwhere = wwhere||' where '||REPLACE(UPPER(prcodemp), 'BDCODEMP', 'BDCODEMPDEST');

       if (coalesce(prcodcol, '') <> '') then
          wwhere = wwhere||' and '||REPLACE(UPPER(prcodcol), 'BDCODCOL', 'BDCODCOLDEST');
     end

  for execute statement wwhere into :wcodemporig, :wcodcolorig, :BDCODEMP, :BDCODCOL do
    begin
      while (coalesce(wcodemporig, 0) <> 0 and coalesce(wcodcolorig, 0) <> 0) do
        begin
          wsql = 'select FE.BDINIPERAQUISFE, FE.BDCODFE, FE.BDINIPERGOZOFE, FE.BDFIMPERAQUISFE, '||
                        'FE.BDFIMPERGOZOFE, FE.BDDATAPAGFE, FE.BDQTDGOZOFE, FE.BDQTDABONOFE, FE.BDSALDOINIFE, '||
                        'FE.BDSALDOFIMFE, FE.BDBASEIRFE, FE.BDALIQIRFE, FE.BDVALORIRFE, FE.BDBASEINSSFE, '||
                        'FE.BDALIQINSSFE, FE.BDVALORINSSFE, FE.BDDEPFE, FE.BDSALBASEFE, FE.BDSALBASEHEFE, FE.BDDATABAIXAFE, '||
                        'FE.BDCOLETIVASFE, FE.BDREFPAGABOFE, FE.BDFERIADOSFE, FE.BDSALDOFINALSINDFE, FE.BDVALSALMINVIGENTE, '||
                        'FE.BDQTDGOZORECIBOFE, True '; -- 81269 - Raphael Teodoro - 10/11/2022
          wsql = wsql||'from VRH_EMP_TFERIAS FE ';
          wsql = wsql||'where FE.BDCODEMP = '||wcodemporig||' and FE.BDCODCOL = '||wcodcolorig;

          if (coalesce(prref, 0) <> 0) then
             begin
               wsql = wsql||' and extract(YEAR from FE.BDINIPERAQUISFE)||substring(FE.BDINIPERAQUISFE from 6 for 2) <= '||prref||' and ';
               wsql = wsql||'((FE.BDINIPERGOZOFE is not null and (extract(YEAR from FE.BDINIPERGOZOFE)||substring(FE.BDINIPERGOZOFE from 6 for 2) <= '||prref||' or extract(YEAR from FE.BDFIMPERGOZOFE)||substring(FE.BDFIMPERGOZOFE from 6 for 2) <= '||prref||'))'||
                            ' or '||
                            '(FE.BDINIPERGOZOFE is null and BDREFPAGABOFE <= '||prref||')) ';
             end
        
          if (PRPROVISAO = 0) then
             begin
                wsql = wsql||' and exists(select X.BDCODEMP, X.BDCODCOL, X.BDINIPERAQUISFE, MAX(X.BDCODFE) BDCODF '||
                                    'from VRH_EMP_TFERIAS X '||
                                    'where '||
                                    'extract(year from X.BDINIPERAQUISFE) || substring(X.BDINIPERAQUISFE from 6 for 2) <= '||prref||' and '||
                                     '((X.BDINIPERGOZOFE is not null and '||
                                       '((extract(year from X.BDINIPERGOZOFE) || substring(X.BDINIPERGOZOFE from 6 for 2) <= '||prref||') or '||
                                        '(extract(year from X.BDFIMPERGOZOFE) || substring(X.BDFIMPERGOZOFE from 6 for 2) <= '||prref||'))) or (X.BDINIPERGOZOFE is null and '||
                                         'BDREFPAGABOFE <= '||prref||')) '||
                                    'group by X.BDCODEMP, X.BDCODCOL, X.BDINIPERAQUISFE '||
                                    'having X.BDCODEMP = FE.BDCODEMP and X.BDCODCOL = FE.BDCODCOL and X.BDINIPERAQUISFE = FE.BDINIPERAQUISFE and MAX(X.BDCODFE) = FE.BDCODFE'||
                                   ') ';
             end
          else
             begin
                wsql = wsql||' and exists(select X.BDCODEMP, X.BDCODCOL, X.BDINIPERAQUISFE, X.BDCODFE BDCODF '||
                                    'from VRH_EMP_TFERIAS X '||
                                    'where X.BDCODEMP = FE.BDCODEMP and X.BDCODCOL = FE.BDCODCOL and X.BDINIPERAQUISFE = FE.BDINIPERAQUISFE and X.BDCODFE = FE.BDCODFE'||
                                   ') ';
             end
        
          for execute statement wsql
          into :BDINIPERAQUISFE, :BDCODFE, :BDINIPERGOZOFE, :BDFIMPERAQUISFE,
               :BDFIMPERGOZOFE, :BDDATAPAGFE, :BDQTDGOZOFE, :BDQTDABONOFE, :BDSALDOINIFE,
               :BDSALDOFIMFE, :BDBASEIRFE, :BDALIQIRFE, :BDVALORIRFE, :BDBASEINSSFE, :BDALIQINSSFE,
               :BDVALORINSSFE, :BDDEPFE, :BDSALBASEFE, :BDSALBASEHEFE, :BDDATABAIXAFE, :BDCOLETIVASFE,
               :BDREFPAGABOFE, :BDFERIADOSFE, :BDSALDOFINALSINDFE, :BDVALSALMINVIGENTE, :BDQTDGOZORECIBOFE,
               :BDISTRANSFERENCIA
          do
            begin
              wdataaux = null;
              select first 1 BDINIPERAQUISFE from VRHF_EMP_TVERBAFE where BDCODEMP = :wcodemporig and BDCODCOL = :wcodcolorig and BDINIPERAQUISFE = :bdiniperaquisfe and BDCODFE = :bdcodfe into :wdataaux;
        
              if (wdataaux is null) then
                 BDMIGRACAO = 'TRUE';
              else
                 BDMIGRACAO = 'FALSE';
        
              wfaltas = null;
              select count(*)
              from VRH_EMP_TFALTAS_ITENS
              where BDCODEMP = :wcodemporig and
                    BDCODCOL = :wcodcolorig and
                    BDDATAFAL between :bdiniperaquisfe and :bdfimperaquisfe and
                          coalesce(BDTIPOFAL, 0) = 1 and
                          coalesce(BDTIPODESCFAL, 0) = 0
              into :wfaltas;
        
              if (coalesce(wfaltas, 0) <> 0) then
                 BDFALTASFE = wfaltas;
              else
                 select sum(coalesce(BDFALTASFE, 0)) from VRH_EMP_TFERIAS where BDCODEMP = :wcodemporig and BDCODCOL = :wcodcolorig and BDINIPERAQUISFE = :bdiniperaquisfe into :BDFALTASFE;
        
              BDFALTASFE = coalesce(BDFALTASFE, 0);
        
              BDPAGO = 'FALSE';
        
              if (bdinipergozofe is not null) then
                 begin
                   wrefpag = CAST((SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                   if (wrefpag = prref) then
                      BDPAGO = 'TRUE';
                 end
        
              if (bdfimpergozofe is not null) then
                 begin
                   wrefpag = CAST((SUBSTRING(CAST(bdfimpergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdfimpergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                   if (wrefpag <= prref) then
                      BDPAGO = 'TRUE';
                 end
        
              if (BDPAGO = 'FALSE') then
                 begin
                   if (bdinipergozofe is not null) then
                      begin
                        wrefpag = CAST((SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
                        if (wrefpag <= prref) then
                           BDPAGO = 'TRUE';
                      end
                 end
        
              if (BDPAGO = 'FALSE') then
                 begin
                   if (coalesce(bdrefpagabofe, 0) > 0) then
                      begin
                        if (bdrefpagabofe <= prref) then
                           BDPAGO = 'TRUE';
                      end
                 end
        
              BDFERIASMES = 0;
              if (upper(coalesce(BDCOLETIVASFE, 'FALSE')) = 'TRUE') then
                 begin
                   select first 1 coalesce(BDDIASFERFE, 0) + coalesce(BDDIASABOFE, 0)
                   from VRH_EMP_TFERIASREF
                   where BDCODEMP = :wcodemporig and BDCODCOL = :wcodcolorig and BDINIPERAQUISFE = :BDINIPERAQUISFE and BDCODFE = :BDCODFE and BDREFFE <= :prref
                   into :BDFERIASMES;
                   BDFERIASMES = coalesce(BDFERIASMES, 0);
                 end
              suspend;
            end

          wempx = null;
          wcolx = null;

          select bdcodemp from TMP_CONTROLE_PERAQUISFE where BDSPINSERIU = 8 AND  bdcodemp = :wcodemporig and bdcodcol = :wcodcolorig and bdsessao = current_connection into :wcodcontrole;
          if (wcodcontrole is null) then
             begin
          select first 1 BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = :wcodemporig and BDCODCOLDEST = :wcodcolorig into :wempx, :wcolx;
          wcodemporig = wempx;
          wcodcolorig = wcolx;
               insert into TMP_CONTROLE_PERAQUISFE (BDCODEMP,BDCODCOL,BDSESSAO,BDSPINSERIU) values (:wcodemporig,:wcodcolorig,current_connection,8);
        end
          else
             begin
               wcodemporig = null;
               wcodcolorig = null;
     end
        end
     end
  delete from TMP_CONTROLE_PERAQUISFE where BDSPINSERIU = 8 AND  bdsessao = current_connection;
end^

/* Restore proc. body: VRH_SP_GRRF */
create or alter procedure VRH_SP_GRRF (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32700),
    PRANOMES integer,
    PRDATAPAGTO date,
    PRPRIDIA date,
    PRULTDIA date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODPRES integer,
    BDREFRESCISAO integer,
    BDDATARESCISAO date,
    BDDATAAVPREVIO date,
    BDREPOSICAOVAGA varchar(5),
    BDSALDOFGTS numeric(15,6),
    BDDATAHOM date,
    BDDATAPAGGRFC date,
    BDDATADISSIDIO date,
    BDAVPREPRES integer,
    BDCODSEFMFG varchar(5),
    BDCODSAQUE integer,
    BDBFGTS numeric(15,6),
    BDBFGTSMESANT numeric(15,6),
    BDVALINDEN numeric(15,6),
    BDCNPJEMP varchar(18),
    BDNOMEMP DM_BDNOMEMP,
    BDLOGREMP varchar(15),
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP varchar(9),
    BDDDDEMP integer,
    BDFONEEMP DM_BDTELEFONE,
    BDCODCNAE integer,
    BDCODCONT integer,
    BDSIMPLESGPS integer,
    BDCODFPAS integer,
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
    BDNOMCOL DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDSEXOCOL integer,
    BDGRAUINSTCOL integer,
    BDDATANASCCOL date,
    BDCONTRCOL integer,
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDCATEGORIACOL integer,
    BDOCORRENCIACOL integer,
    BDDATAOPCAOFGTSCOL date,
    BDHORASSEMANAISCOL numeric(15,6),
    BDCODCBO varchar(4),
    BDTAMCNPJ integer,
    BDNOMREDUZEMP DM_BDNOMREDUZEMP,
    BDFGTSSEMIND numeric(15,6),
    BDSITEMP DM_BOOLEAN,
    BDBLOQUEIOGRRF DM_BOOLEAN)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(20000);
declare variable WCODEMP varchar(20000);
declare variable WCODCOL varchar(32700);
declare variable WBFGTSFN numeric(15,6);
declare variable WFGTSFN numeric(15,6);
declare variable WBFGTS13 numeric(15,6);
declare variable WFGTS13 numeric(15,6);
declare variable WINDFN numeric(15,6);
declare variable WIND13 numeric(15,6);
declare variable WDATAFGTSDIGITAL date;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(pranomes, prpridia, prultdia);

  IF (prcodemp IS NULL OR (prcodemp = '')) THEN
     wcodemp = 'null';
  ELSE
     wcodemp = ''''||prcodemp||'''';

  IF (prcodcol IS NULL OR (prcodcol = '')) THEN
     wcodcol = 'null';
  ELSE
     wcodcol = ''''||prcodcol||'''';

  wsql = 'select '||
/*00*/                'COLCON.BDCODEMP, '||
/*01*/                'COLCON.BDCODCOL, '||
/*02*/                'COLCON.BDCODPRES, '||

/*03*/                'COLCON.BDREFRESCISAO, '||

/*03*/                'COLCON.BDDATARESCISAO, '||
/*04*/                'COLCON.BDDATAAVPREVIO, '||
/*05*/                'COLCON.BDREPOSICAOVAGA, '||
/*06*/                'COLCON.BDSALDOFGTS, '||
/*07*/                'COLCON.BDDATAHOM, '||
/*08*/                'COLCON.BDDATAPAGGRFC, '||
/*09*/                'COLCON.BDDATADISSIDIO, '||
/*10*/                'PRES.BDAVPREPRES, '||
/*11*/                'MFGT.BDCODSEFMFG, '||
/*12*/                'SAQU.BDCODSAQUE, '||
/*13*/                'coalesce(FOLH.BDBFGTSFN, 0.0) + coalesce(FOLH.BDBFGTSFEFN, 0.0) - coalesce(VALIND.BDVALOR, 0.0) BDBFGTS, '||
                      'coalesce(FOLH.BDBFGTS13FN, 0.0) + COALESCE(SAL13.BDBASEFGTS13,0.0) + COALESCE(AD13.BDBASEFGTSA13,0.0) - coalesce(VALIND.BDVALOR13, 0.0) BDBFGTS13, '|| -- Sol. 146948 Jarde 09/06/2021
--                      'coalesce(FOLH.BDBFGTS13FN, 0.0) + COALESCE(AD13.BDBASEFGTSA13,0.0) - coalesce(VALIND.BDVALOR13, 0.0) BDBFGTS13, '||                                      -- Sol. 146948 Jarde 09/06/2021
/*14*/                'coalesce(FOLA.BDBFGTSFN, 0.0) + coalesce(FOLA.BDBFGTSFEFN, 0.0) BDBFGTSMESANT, '||
                      'coalesce(FOLA.BDBFGTS13FN, 0.0) + COALESCE(SAL13_ANT.BDBASEFGTS13,0.0) + COALESCE(AD13_ANT.BDBASEFGTSA13,0.0) BDBFGTSMESANT13, '||
/*15*/                'coalesce(VALIND.BDVALOR, 0.0) BDVALINDEN, '||
                      'coalesce(VALIND.BDVALOR13, 0.0) BDVALINDEN13, '||
/*16*/                'case when EMP.BDCEIEMP IS NOT null then EMP.BDCEIEMP else EMP.BDCNPJEMP end BDCNPJEMP, '||
/*17*/                'EMPR.BDNOMEMP, '||
/*18*/                'EMPR.BDLOGREMP, '||
/*19*/                'EMPR.BDENDEMP, '||
/*20*/                'EMPR.BDNUMEMP, '||
/*21*/                'EMPR.BDCOMPLEMP, '||
/*22*/                'EMPR.BDBAIEMP, '||
/*23*/                'EMPR.BDCEPEMP, '||
/*24*/                'EMPR.BDDDDEMP, '||
/*25*/                'EMPR.BDFONEEMP, '||
/*26*/   --             'EMPR.BDCNAEPREP, '||
/*27*/                'EMPR.BDCODCNAE, '||
/*28*/                'EMPR.BDCODCONTRH BDCODCONT, '||
/*29*/                'EMPG.BDSIMPLESGPS, '||
/*30*/                'EMPG.BDCODFPAS, '||
/*31*/                'CIDEMP.BDNOMCID, '||
/*32*/                'UFEMP.BDSIGLAUF, '||
/*33*/                'COLCAD.BDNOMCOL, '||
/*34*/                'COL.BDDATAADMCOL, '||
/*35*/                'COLCAD.BDSEXOCOL, '||
/*36*/                'COLCAD.BDGRAUINSTCOL, '||
/*37*/                'COL.BDDATANASCCOL, '||
/*38*/                'COL.BDCONTRCOL, '||
/*39*/                'COLDOC.BDCPFCOL, '||
/*40*/                'DOCREF.BDPISCOL, '||
/*41*/                'DOCREF.BDCTPSCOL, '||
/*42*/                'DOCREF.BDSERIECTPSCOL, '||
/*43*/                'DOCREF.BDDSERIECTPSCOL, '||
/*44*/                'COLFGTS.BDCATEGORIACOL, '||
/*45*/                'COLFGTS.BDOCORRENCIACOL, '||
/*46*/                'COLFGTS.BDDATAOPCAOFGTSCOL, '||
/*47*/                'COLCALC.BDHORASSEMANAISCOL, '||
/*48*/                'SUBSTRING((CAST(FUC.BDCODCBO AS VARCHAR(10))) from 1 for 4) BDCODCBO, '||
/*49*/                'STRLEN(TRIM(case when EMP.BDCEIEMP IS NOT null then EMP.BDCEIEMP else EMP.BDCNPJEMP end)) BDTAMCNPJ, '||
/*50*/                'EMPR.BDNOMREDUZEMP, '||
/*51*/                'EMPR.BDSITEMP, fase.bddatafgtsdigital ';

  wsql = wsql||' from VRH_EMP_TRESCISAO COLCON '||
               'join tempresas EMP on (EMP.BDCODEMP = COLCON.BDCODEMP) '||
               'join VRH_BASE_TPREPRESC PRES on (PRES.BDCODPRES = COLCON.BDCODPRES) '||
               'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = COLCON.BDCODEMP and COL.BDCODCOL = COLCON.BDCODCOL) '||
               'join VRH_BASE_TMOTFGTS MFGT on (MFGT.BDCODMFG = PRES.BDCODMFG) '||
               'join VRH_BASE_TSAQUE SAQU on (SAQU.BDCODSAQUE = PRES.BDCODSAQUE) ';

  IF (prdatapagto IS NOT NULL) THEN
     BEGIN
       wsql = wsql||'join (select BDCODEMP, BDCODCOL, BDREFFN, SUM(BDBFGTSFN) BDBFGTSFN, SUM(BDBFGTSFEFN) BDBFGTSFEFN, SUM(BDBFGTS13FN) BDBFGTS13FN '||
                          'from VRHF_SP_TFOLHA_NORMAL('||wcodemp||','||wcodcol||', null, null,1) '||
                          'group by BDCODEMP, BDCODCOL, BDREFFN'||
                    ') FOLH on (FOLH.BDCODEMP = COLCON.BDCODEMP and FOLH.BDCODCOL = COLCON.BDCODCOL and FOLH.BDREFFN = COLCON.BDREFRESCISAO) ';
     END
  ELSE
     BEGIN
       wsql = wsql||'join (select BDCODEMP, BDCODCOL, BDREFFN, SUM(BDBFGTSFN) BDBFGTSFN, SUM(BDBFGTSFEFN) BDBFGTSFEFN, SUM(BDBFGTS13FN) BDBFGTS13FN '||
                          'from VRHF_SP_TFOLHA_NORMAL('||wcodemp||','||wcodcol||','||pranomes||','||pranomes||',1) '||
                          'group by BDCODEMP, BDCODCOL, BDREFFN'||
                    ') FOLH on (FOLH.BDCODEMP = COLCON.BDCODEMP and FOLH.BDCODCOL = COLCON.BDCODCOL and FOLH.BDREFFN = COLCON.BDREFRESCISAO)';
     END

  wsql = wsql||'left outer join (select BDCODEMP, BDCODCOL, BDREFFN, SUM(BDBFGTSFN) BDBFGTSFN, SUM(BDBFGTSFEFN) BDBFGTSFEFN, SUM(BDBFGTS13FN) BDBFGTS13FN '||
                                'from SP_VRHF_EMP_TFOLHANORMAL_ANT('||pranomes||','||wcodemp||','||wcodcol||') '||
                                'group by BDCODEMP, BDCODCOL, BDREFFN '||
               ') FOLA on (FOLA.BDCODEMP = COLCON.BDCODEMP and FOLA.BDCODCOL = COLCON.BDCODCOL and COLCON.BDCALCFGTSMESANT = '||'''TRUE'''||') ';

  wsql = wsql||'left outer join SP_VRHF_FN_VALORES_INDENIZADOS('||wcodemp||', '||wcodcol||', COLCON.BDREFRESCISAO) VALIND on (VALIND.BDCODEMP = COLCON.BDCODEMP and VALIND.BDCODCOL = COLCON.BDCODCOL) '||
               'left outer join VW_TEMPRESAS_REF EMPR on (EMPR.BDCODEMP = COLCON.BDCODEMP) '||
               'left outer join VW_VRHF_BASE_TEMPGPS EMPG on (EMPG.BDCODEMP = COLCON.BDCODEMP) '||
               'left outer join TCIDADE CIDEMP on (CIDEMP.BDCODCID = EMPR.BDCODCID) '||
               'left outer join TUF UFEMP on (UFEMP.BDCODUF = CIDEMP.BDCODUF) '||
               'left outer join VRH_EMP_TCOLCON_DOC COLDOC on (COLDOC.BDCODEMP = COLCON.BDCODEMP and COLDOC.BDCODCOL = COLCON.BDCODCOL) '||
               'left outer join VRH_EMP_TCOL_DOC COL2DOC on (COL2DOC.BDCODEMP = COLCON.BDCODEMP and COL2DOC.BDCODCOL = COLCON.BDCODCOL) '||
               'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS COLFGTS on (COLFGTS.BDCODEMP = COLCON.BDCODEMP and COLFGTS.BDCODCOL = COLCON.BDCODCOL) '||
               'left outer join VW_VRHF_EMP_TCOL_CALC COLCALC on (COLCALC.BDCODEMP = COLCON.BDCODEMP and COLCALC.BDCODCOL = COLCON.BDCODCOL) '||
               'left outer join VW_VRH_EMP_TCOL_VINCDIA COLVDIA on (COLVDIA.BDCODEMP = COLCON.BDCODEMP and COLVDIA.BDCODCOL = COLCON.BDCODCOL) '||
               'left outer join VRH_FUNCOES_TFUC FUC on (FUC.BDCODPLAFUC = COLVDIA.BDCODPLAFUC and FUC.BDCODTFUC = COLVDIA.BDCODTFUC) '||
               'left outer join VRHF_EMP_T13SAL SAL13 on (SAL13.BDCODEMP = COLCON.BDCODEMP and SAL13.BDCODCOL = COLCON.BDCODCOL and SAL13.BDREF13 = BDREFRESCISAO)'||
               'left outer join VRHF_EMP_TA13SAL AD13 on (AD13.BDCODEMP = COLCON.BDCODEMP and AD13.BDCODCOL = COLCON.BDCODCOL and AD13.BDREFA13 = BDREFRESCISAO)'||
               'left outer join VRHF_EMP_T13SAL SAL13_ANT on (SAL13_ANT.BDCODEMP = COLCON.BDCODEMP and SAL13_ANT.BDCODCOL = COLCON.BDCODCOL and SAL13_ANT.BDREF13 = FOLA.BDREFFN and COLCON.BDCALCFGTSMESANT = '||'''TRUE'''||') '||
               'left outer join VRHF_EMP_TA13SAL AD13_ANT on (AD13_ANT.BDCODEMP = COLCON.BDCODEMP and AD13_ANT.BDCODCOL = COLCON.BDCODCOL and AD13_ANT.BDREFA13 = FOLA.BDREFFN and COLCON.BDCALCFGTSMESANT = '||'''TRUE'''||') '||
               'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COLCON.BDCODEMP and COLCAD.BDCODCOL = COLCON.BDCODCOL) '||
               'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = COLCON.BDCODEMP and DOCREF.BDCODCOL = COLCON.BDCODCOL) '||
               'left outer join VRH_ESOCIAL_TFASEAMENTO fase on (fase.bdcodemp = colcon.bdcodemp)';

  wwhere = 'where PRES.BDGRRFPRES is not null and PRES.BDGRRFPRES > 0 ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||'and '||prcodemp||' ';
  ELSE
     wwhere = wwhere||' and UPPER(COALESCE(EMPR.BDSITEMP, ''FALSE'')) = ''FALSE'' and EMPG.BDCODFPAS <> 868 ';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||'and '||prcodcol||' ';

  IF (prdatapagto IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||'and COLCON.BDDATAPAGGRFC = '''||prdatapagto||''' ';
     END
  ELSE
     BEGIN
       wwhere = wwhere||'and COLCON.BDDATARESCISAO between '''||prpridia||''' and  '''||prultdia||''' ';
     END

  wsql = wsql||wwhere||'order by EMPR.BDCODCONTRH, COLCON.BDDATAPAGGRFC, BDTAMCNPJ DESC, EMP.BDCNPJEMP, DOCREF.BDPISCOL, COL.BDDATAADMCOL, COLFGTS.BDCATEGORIACOL';

  BDFGTSSEMIND = 0;
  FOR EXECUTE STATEMENT wsql
  INTO
/*00*/    :BDCODEMP,
/*01*/    :BDCODCOL,
/*02*/    :BDCODPRES,

/*03*/    :BDREFRESCISAO,

/*03*/    :BDDATARESCISAO,
/*04*/    :BDDATAAVPREVIO,
/*05*/    :BDREPOSICAOVAGA,
/*06*/    :BDSALDOFGTS,
/*07*/    :BDDATAHOM,
/*08*/    :BDDATAPAGGRFC,
/*09*/    :BDDATADISSIDIO,
/*10*/    :BDAVPREPRES,
/*11*/    :BDCODSEFMFG,
/*12*/    :BDCODSAQUE,
/*13*/    :wbfgtsfn,
          :wbfgts13,
/*14*/    :wfgtsfn,
          :wfgts13,
/*15*/    :windfn,
          :wind13,
/*16*/    :BDCNPJEMP,
/*17*/    :BDNOMEMP,
/*18*/    :BDLOGREMP,
/*19*/    :BDENDEMP,
/*20*/    :BDNUMEMP,
/*21*/    :BDCOMPLEMP,
/*22*/    :BDBAIEMP,
/*23*/    :BDCEPEMP,
/*24*/    :BDDDDEMP,
/*25*/    :BDFONEEMP,
/*26*/--    :BDCNAEPREP,
/*27*/    :BDCODCNAE,
/*28*/    :BDCODCONT,
/*29*/    :BDSIMPLESGPS,
/*30*/    :BDCODFPAS,
/*31*/    :BDNOMCID,
/*32*/    :BDSIGLAUF,
/*33*/    :BDNOMCOL,
/*34*/    :BDDATAADMCOL,
/*35*/    :BDSEXOCOL,
/*36*/    :BDGRAUINSTCOL,
/*37*/    :BDDATANASCCOL,
/*38*/    :BDCONTRCOL,
/*39*/    :BDCPFCOL,
/*40*/    :BDPISCOL,
/*41*/    :BDCTPSCOL,
/*42*/    :BDSERIECTPSCOL,
/*43*/    :BDDSERIECTPSCOL,
/*44*/    :BDCATEGORIACOL,
/*45*/    :BDOCORRENCIACOL,
/*46*/    :BDDATAOPCAOFGTSCOL,
/*47*/    :BDHORASSEMANAISCOL,
/*48*/    :BDCODCBO,
/*49*/    :BDTAMCNPJ,
/*50*/    :BDNOMREDUZEMP,
/*51*/    :BDSITEMP,
/*52*/    :wdatafgtsdigital
  DO
  BEGIN
    if (wbfgtsfn < 0) then
       begin
         wbfgtsfn = 0;
         windfn   = 0;
      end

    if (wbfgts13 < 0) then
       begin
         wbfgts13 = 0;
         wind13   = 0;
       end

    BDBFGTS       = wbfgtsfn + wbfgts13;
    BDBFGTSMESANT = wfgtsfn + wfgts13;
    BDVALINDEN    = windfn + wind13;

    if ((BDCTPSCOL = '') and (BDSERIECTPSCOL = '')) then
      begin
        wsql = 'select substring(bdretorno from 1 for 7) bdretorno from RETIRA_CHAR_ESPECIAL('||''''||BDCPFCOL||''''||')';
        EXECUTE STATEMENT wsql INTO BDCTPSCOL;

        wsql = 'select substring(bdretorno from 8 for 4) bdretorno from RETIRA_CHAR_ESPECIAL('||''''||BDCPFCOL||''''||')';
        EXECUTE STATEMENT wsql INTO BDSERIECTPSCOL;
      end

    if (wdatafgtsdigital is not null) then
       begin
        if (BDREFRESCISAO >= (select * from aaaamm(:wdatafgtsdigital))) then
           begin
               bdbloqueiogrrf = 'TRUE';
           end
        else
           begin
              bdbloqueiogrrf = 'FALSE';
           end
       end
     else
       bdbloqueiogrrf = 'FALSE';

    SUSPEND;
  END
END^

/* Restore proc. body: VRH_SP_GRRF_FC */
create or alter procedure VRH_SP_GRRF_FC (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32700),
    PRANOMES integer,
    PRDATAPAGTO date,
    PRCODTIPOFC integer = null,
    PRCHAVEDARF integer = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODPRES integer,
    BDDATARESCISAO date,
    BDDATAAVPREVIO date,
    BDREPOSICAOVAGA varchar(5),
    BDSALDOFGTS numeric(15,6),
    BDDATAHOM date,
    BDDATAPAGGRFC date,
    BDDATADISSIDIO date,
    BDAVPREPRES integer,
    BDCODSEFMFG varchar(5),
    BDCODSAQUE integer,
    BDBFGTS numeric(15,6),
    BDBFGTSMESANT numeric(15,6),
    BDVALINDEN numeric(15,6),
    BDCNPJEMP varchar(18),
    BDNOMEMP DM_BDNOMEMP,
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP varchar(9),
    BDDDDEMP integer,
    BDFONEEMP DM_BDTELEFONE,
    BDCODCNAE integer,
    BDCODCONT integer,
    BDSIMPLESGPS integer,
    BDCODFPAS integer,
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
    BDNOMCOL DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDSEXOCOL integer,
    BDGRAUINSTCOL integer,
    BDDATANASCCOL date,
    BDCONTRCOL integer,
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDCATEGORIACOL integer,
    BDOCORRENCIACOL integer,
    BDDATAOPCAOFGTSCOL date,
    BDHORASSEMANAISCOL numeric(15,6),
    BDCODCBO varchar(4),
    BDTAMCNPJ integer,
    BDNOMREDUZEMP DM_BDNOMREDUZEMP,
    BDFGTSSEMIND numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDVALOR numeric(15,6),
    BDSITEMP DM_BOOLEAN,
    BDBLOQUEIOGRRF DM_BOOLEAN)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(20000);
declare variable WPERCFGTSCOL numeric(15,6);
declare variable WCHAVEDARF varchar(3000);
declare variable WCONDICAOCHAVEDARF varchar(3000);
declare variable WANOMES integer;
declare variable WDTAPURACAOIMPADC date;
declare variable WDATAFGTSDIGITAL date;
declare variable WTIPOFC integer;
BEGIN
  wanomes = pranomes;
  wsql = 'select '||
/*00*/                'COLCON.BDCODEMP, '||
/*01*/                'COLCON.BDCODCOL, '||
/*02*/                'COLCON.BDCODPRES, '||
/*03*/                'COLCON.BDDATARESCISAO, '||
/*04*/                'COLCON.BDDATAAVPREVIO, '||
/*05*/                'COLCON.BDREPOSICAOVAGA, '||
/*06*/                'case when FOLH.BDCODTIPOFC > 1 then 0.0 else COALESCE(FOLH.BDFGTSFC, 0.0) + COALESCE(FOLH.BDFGTS13FC, 0.0) + COALESCE(FOLH.BDFGTSFEFC, 0.0) end BDSALDOFGTS, '||
/*07*/                'COLCON.BDDATAHOM, '||
/*08*/                'folh.BDDATAGRRFFC, '||
/*09*/                'COLCON.BDDATADISSIDIO, '||
/*10*/                'PRES.BDAVPREPRES, '||
/*11*/                'MFGT.BDCODSEFMFG, '||
/*12*/                'SAQU.BDCODSAQUE, '||
/*13*/                'coalesce(FOLH.bdbfgtsfc, 0.0) + coalesce(FOLH.bdbfgtsfefc, 0.0) + coalesce(FOLH.bdbfgts13fc, 0.0) - coalesce(VALIND.BDVALOR, 0.0) BDBFGTS, '||
/*14*/                '0.0 BDBFGTSMESANT, '||
/*15*/                'coalesce(VALIND.BDVALOR, 0.0) BDVALINDEN, '||
/*16*/                'EMP.BDCNPJEMP, '||
/*17*/                'EMPR.BDNOMEMP, '||
/*18*/                'EMPR.BDLOGREMP, '||
/*19*/                'EMPR.BDENDEMP, '||
/*20*/                'EMPR.BDNUMEMP, '||
/*21*/                'EMPR.BDCOMPLEMP, '||
/*22*/                'EMPR.BDBAIEMP, '||
/*23*/                'EMPR.BDCEPEMP, '||
/*24*/                'EMPR.BDDDDEMP, '||
/*25*/                'EMPR.BDFONEEMP, '||
/*26*/   --             'EMPR.BDCNAEPREP, '||
/*27*/                'EMPR.BDCODCNAE, '||
/*28*/                'EMPR.BDCODCONTRH BDCODCONT, '||
/*29*/                'EMPG.BDSIMPLESGPS, '||
/*30*/                'EMPG.BDCODFPAS, '||
/*31*/                'CIDEMP.BDNOMCID, '||
/*32*/                'UFEMP.BDSIGLAUF, '||
/*33*/                'COLCAD.BDNOMCOL, '||
/*34*/                'COL.BDDATAADMCOL, '||
/*35*/                'COLCAD.BDSEXOCOL, '||
/*36*/                'COLCAD.BDGRAUINSTCOL, '||
/*37*/                'COL.BDDATANASCCOL, '||
/*38*/                'COL.BDCONTRCOL, '||
/*39*/                'COLDOC.BDCPFCOL, '||
/*40*/                'DOCREF.BDPISCOL, '||
/*41*/                'DOCREF.BDCTPSCOL, '||
/*42*/                'DOCREF.BDSERIECTPSCOL, '||
/*43*/                'DOCREF.BDDSERIECTPSCOL, '||
/*44*/                'COLFGTS.BDCATEGORIACOL, '||
/*45*/                'COLFGTS.BDOCORRENCIACOL, '||
/*46*/                'COLFGTS.BDDATAOPCAOFGTSCOL, '||
/*47*/                'COLCALC.BDHORASSEMANAISCOL, '||
/*48*/                'SUBSTRING((CAST(FUC.BDCODCBO AS VARCHAR(10))) from 1 for 4) BDCODCBO, '||
/*49*/                'STRLEN(TRIM(EMP.BDCNPJEMP)) BDTAMCNPJ, '||
/*50*/                'EMPR.BDNOMREDUZEMP,'||
/*51*/                'COLFGTS.BDPERCFGTSCOL,'||
/*52*/                'CC.BDCODCENTRO,'||
/*53*/                'CC.BDCODTPCC,'||
/*54*/                'DARF.BDVALOR, '||
                      'EMPR.BDSITEMP, '||
                      'folh.bddtacconv, '||
                      'fase.bddatafgtsdigital, '||
                      'FOLH.BDCODTIPOFC ';

  wchavedarf = COALESCE(prchavedarf,'');

  IF (wchavedarf <> '') THEN
     wcondicaochavedarf = ' and DARF.BDCHAVEDARF = '||wchavedarf;

  wcondicaochavedarf = COALESCE(wcondicaochavedarf,'');

  wsql = wsql||' from VRH_EMP_TRESCISAO COLCON '||
               'join tempresas EMP on (EMP.BDCODEMP = COLCON.BDCODEMP) '||
               'join VRH_BASE_TPREPRESC PRES on (PRES.BDCODPRES = COLCON.BDCODPRES) '||
               'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = COLCON.BDCODEMP and COL.BDCODCOL = COLCON.BDCODCOL) '||
               'left outer join VRH_BASE_TMOTFGTS MFGT on (MFGT.BDCODMFG = PRES.BDCODMFG) '||
               'left outer join VRH_BASE_TSAQUE SAQU on (SAQU.BDCODSAQUE = PRES.BDCODSAQUE) '||
               'left outer join SP_VRH_CC_DATA(COLCON.BDCODEMP,COLCON.BDCODCOL,COLCON.BDDATARESCISAO) CC on (COLCON.BDCODEMP = CC.BDCODEMP and COLCON.BDCODCOL = CC.BDCODCOL) '||
               'left outer join TDARFPADRAO DARF on (COLCON.BDCODEMP = DARF.BDCODEMP and COLCON.BDCODCOL = DARF.BDCODCOL and COLCON.BDREFRESCISAO = DARF.BDREFERENCIA '||wcondicaochavedarf||') '||
               'join (select bdcodemp, bdcodcol, bdreffn, bdcodtipofc, bddatagrrffc, SUM(bdfgtsfc) bdfgtsfc, SUM(bdfgts13fc) bdfgts13fc, SUM(bdfgtsfefc) bdfgtsfefc, '||
                        'SUM(bdbfgtsfc) bdbfgtsfc, SUM(bdbfgtsfefc) bdbfgtsfefc, SUM(bdbfgts13fc) bdbfgts13fc, bddtacconv from ('||
                        'select colcon.bdcodemp, colcon.bdcodcol, colcon.bdcodtipofc, colcon.bdfgtsfc, colcon.bdfgts13fc, colcon.bdfgtsfefc, colcon.bddatagrrffc,'||
                        'colcon.bdbfgtsfc, colcon.bdbfgtsfefc, colcon.bdbfgts13fc, colcon.bdreffn, ADC.bddtacconv '||
                     'from vrhf_emp_tfolhacomp colcon '||
                     'left outer join VRH_EMP_TACCONV ADC on (ADC.bdcodemp = colcon.bdcodemp) and (ADC.bdcodacconv = Colcon.bdcodacconv)'||
                     'where colcon.bdreffn = '||pranomes;

         IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            BEGIN
              wsql = wsql||' and '||prcodemp;

              IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
                 wsql = wsql||' and '||prcodcol;
            END

         wsql = wsql||' and colcon.bddatagrrffc = '''||prdatapagto||''' ';

         wsql = wsql||
               ' union all select colcon.bdcodemp, colcon.bdcodcol, colcon.bdcodtipofc, colcon.bdfgtsfc, colcon.bdfgts13fc, colcon.bdfgtsfefc, colcon.bddatagrrffc,'||
                        'colcon.bdbfgtsfc, colcon.bdbfgtsfefc, colcon.bdbfgts13fc, colcon.bdreftomador, ADC.bddtacconv '||
                     'from vrhf_emp_tfoltomcomp colcon '||
                     'left outer join VRH_EMP_TACCONV ADC on (ADC.bdcodemp = colcon.bdcodemp) and (ADC.bdcodacconv = Colcon.bdcodacconv)'||
                     'where colcon.bdreftomador = '||pranomes;

         IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            BEGIN
              wsql = wsql||' and '||prcodemp;

              IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
                 wsql = wsql||' and '||prcodcol;
            END

         wsql = wsql||' and colcon.bddatagrrffc = '''||prdatapagto||''' ';

         wsql = wsql||
               ' union all select colcon.bdcodemp, colcon.bdcodcol, colcon.bdcodtipofc, colcon.bdfgtsfc, colcon.bdfgts13fc, colcon.bdfgtsfefc, colcon.bddatagrrffc,'||
                        'colcon.bdbfgtsfc, colcon.bdbfgtsfefc, colcon.bdbfgts13fc, colcon.bdreffn, ADC.bddtacconv  '||
                     'from vrhf_emp_tfolhacompint colcon '||
                     'left outer join VRH_EMP_TACCONV ADC on (ADC.bdcodemp = colcon.bdcodemp) and (ADC.bdcodacconv = Colcon.bdcodacconv)'||
                     'where colcon.bdreffn = '||pranomes;

         IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            BEGIN
              wsql = wsql||' and '||prcodemp;

              IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
                 wsql = wsql||' and '||prcodcol;
            END

         wsql = wsql||' and colcon.bddatagrrffc = '''||prdatapagto||''' ';

         wsql = wsql||
               ' union all select colcon.bdcodemp, colcon.bdcodcol, colcon.bdcodtipofc, colcon.bdfgtsfc, colcon.bdfgts13fc, colcon.bdfgtsfefc, colcon.bddatagrrffc,'||
                        'colcon.bdbfgtsfc, colcon.bdbfgtsfefc, colcon.bdbfgts13fc, colcon.bdreftomador, ADC.bddtacconv '||
                     'from vrhf_emp_tfoltomcompint colcon '||
                     'left outer join VRH_EMP_TACCONV ADC on (ADC.bdcodemp = colcon.bdcodemp) and (ADC.bdcodacconv = Colcon.bdcodacconv)'||
                     'where colcon.bdreftomador = '||pranomes;

         IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            BEGIN
              wsql = wsql||' and '||prcodemp;

              IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
                 wsql = wsql||' and '||prcodcol;
            END

         wsql = wsql||' and colcon.bddatagrrffc = '''||prdatapagto||''') ';

         wsql = wsql||' group by bdcodemp, bdcodcol, bdcodtipofc, bddatagrrffc, bdreffn, bddtacconv ';

  wsql = wsql||') FOLH on (FOLH.BDCODEMP = COLCON.BDCODEMP and FOLH.BDCODCOL = COLCON.BDCODCOL and ((FOLH.BDREFFN = COLCON.BDREFRESCISAO) or (FOLH.BDREFFN = COLCON.BDREFPROJECAOAVISO)))'||
               'left outer join SP_VRHF_FC_VALORES_INDENIZADOS(';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||''''||prcodemp||''',';
  ELSE
     wsql = wsql||'null,';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||''''||prcodcol||''',';
  ELSE
     wsql = wsql||'null,';

  wsql = wsql||pranomes||',';
  wsql = wsql||''''||prdatapagto||''') VALIND '||
         'on (VALIND.BDCODEMP = COLCON.BDCODEMP and VALIND.BDCODCOL = COLCON.BDCODCOL and ((VALIND.BDREFFN = COLCON.BDREFRESCISAO) or (VALIND.BDREFFN = COLCON.BDREFPROJECAOAVISO))) '||
         'left outer join VW_TEMPRESAS_REF EMPR on (EMPR.BDCODEMP = COLCON.BDCODEMP) '||
         'left outer join VW_VRHF_BASE_TEMPGPS EMPG on (EMPG.BDCODEMP = COLCON.BDCODEMP) '||
         'left outer join TCIDADE CIDEMP on (CIDEMP.BDCODCID = EMPR.BDCODCID) '||
         'left outer join TUF UFEMP on (UFEMP.BDCODUF = CIDEMP.BDCODUF) '||
         'left outer join VRH_EMP_TCOLCON_DOC COLDOC on (COLDOC.BDCODEMP = COLCON.BDCODEMP and COLDOC.BDCODCOL = COLCON.BDCODCOL) '||
         'left outer join VRH_EMP_TCOL_DOC COL2DOC on (COL2DOC.BDCODEMP = COLCON.BDCODEMP and COL2DOC.BDCODCOL = COLCON.BDCODCOL) '||
         'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS COLFGTS on (COLFGTS.BDCODEMP = COLCON.BDCODEMP and COLFGTS.BDCODCOL = COLCON.BDCODCOL) '||
         'left outer join VW_VRHF_EMP_TCOL_CALC COLCALC on (COLCALC.BDCODEMP = COLCON.BDCODEMP and COLCALC.BDCODCOL = COLCON.BDCODCOL) '||
         'left outer join VW_VRH_EMP_TCOL_VINCDIA COLVDIA on (COLVDIA.BDCODEMP = COLCON.BDCODEMP and COLVDIA.BDCODCOL = COLCON.BDCODCOL) '||
         'left outer join VRH_FUNCOES_TFUC FUC on (FUC.BDCODPLAFUC = COLVDIA.BDCODPLAFUC and FUC.BDCODTFUC = COLVDIA.BDCODTFUC) '||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COLCON.BDCODEMP and COLCAD.BDCODCOL = COLCON.BDCODCOL) '||
         'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = COLCON.BDCODEMP and DOCREF.BDCODCOL = COLCON.BDCODCOL) '||
         'left outer join VRH_ESOCIAL_TFASEAMENTO fase on (colcon.bdcodemp = fase.bdcodemp) ';

  wwhere = 'where COALESCE(PRES.BDGRRFPRES,0) > 0 ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||'and '||prcodemp||' ';
  ELSE
     wwhere = wwhere||' and UPPER(COALESCE(EMPR.BDSITEMP, ''FALSE'')) = ''FALSE'' and EMPG.BDCODFPAS <> 868 ';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||'and '||prcodcol||' ';

  wsql = wsql||wwhere||'order by EMPR.BDCODCONTRH, folh.BDDATAGRRFFC, BDTAMCNPJ DESC, EMP.BDCNPJEMP, DOCREF.BDPISCOL, COL.BDDATAADMCOL, COLFGTS.BDCATEGORIACOL';

  FOR EXECUTE STATEMENT wsql
  INTO
/*00*/    :BDCODEMP,
/*01*/    :BDCODCOL,
/*02*/    :BDCODPRES,
/*03*/    :BDDATARESCISAO,
/*04*/    :BDDATAAVPREVIO,
/*05*/    :BDREPOSICAOVAGA,
/*06*/    :BDSALDOFGTS,
/*07*/    :BDDATAHOM,
/*08*/    :BDDATAPAGGRFC,
/*09*/    :BDDATADISSIDIO,
/*10*/    :BDAVPREPRES,
/*11*/    :BDCODSEFMFG,
/*12*/    :BDCODSAQUE,
/*13*/    :BDBFGTS,
/*14*/    :BDBFGTSMESANT,
/*15*/    :BDVALINDEN,
/*16*/    :BDCNPJEMP,
/*17*/    :BDNOMEMP,
/*18*/    :BDLOGREMP,
/*19*/    :BDENDEMP,
/*20*/    :BDNUMEMP,
/*21*/    :BDCOMPLEMP,
/*22*/    :BDBAIEMP,
/*23*/    :BDCEPEMP,
/*24*/    :BDDDDEMP,
/*25*/    :BDFONEEMP,
/*26*/--    :BDCNAEPREP,
/*27*/    :BDCODCNAE,
/*28*/    :BDCODCONT,
/*29*/    :BDSIMPLESGPS,
/*30*/    :BDCODFPAS,
/*31*/    :BDNOMCID,
/*32*/    :BDSIGLAUF,
/*33*/    :BDNOMCOL,
/*34*/    :BDDATAADMCOL,
/*35*/    :BDSEXOCOL,
/*36*/    :BDGRAUINSTCOL,
/*37*/    :BDDATANASCCOL,
/*38*/    :BDCONTRCOL,
/*39*/    :BDCPFCOL,
/*40*/    :BDPISCOL,
/*41*/    :BDCTPSCOL,
/*42*/    :BDSERIECTPSCOL,
/*43*/    :BDDSERIECTPSCOL,
/*44*/    :BDCATEGORIACOL,
/*45*/    :BDOCORRENCIACOL,
/*46*/    :BDDATAOPCAOFGTSCOL,
/*47*/    :BDHORASSEMANAISCOL,
/*48*/    :BDCODCBO,
/*49*/    :BDTAMCNPJ,
/*50*/    :BDNOMREDUZEMP,
/*51*/    :wpercfgtscol,
/*52*/    :bdcodcentro,
/*53*/    :bdcodtpcc,
/*54*/    :bdvalor,
/*55*/    :bdsitemp,
/*56*/    :wdtapuracaoimpadc,
/*57*/    :wdatafgtsdigital,
/*58*/    :wtipofc

  DO
  BEGIN
    IF (prcodtipofc IS NOT NULL) THEN
       BEGIN
         wwhere = 'select SUM(COALESCE(bdfgtsfc,0)+COALESCE(bdfgts13fc,0)+COALESCE(bdfgtsfefc,0)) '||
                  'from ('||
                     'select bdfgtsfc, bdfgts13fc, bdfgtsfefc from VRHF_EMP_TFOLHACOMP '||
                     'where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFFN < '||pranomes||' and '||
                     'BDDATAGRRFFC = '''||prdatapagto||''''||
                     ' and BDCODTIPOFC = '||prcodtipofc||
                     ' union all '||
                     'select bdfgtsfc, bdfgts13fc, bdfgtsfefc from VRHF_EMP_TFOLTOMCOMP '||
                     'where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFTOMADOR < '||pranomes||' and '||
                     'BDDATAGRRFFC = '''||prdatapagto||''''||
                     ' and BDCODTIPOFC = '||prcodtipofc||
                     ' union all '||
                     'select bdfgtsfc, bdfgts13fc, bdfgtsfefc from VRHF_EMP_TFOLHACOMPINT '||
                     'where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFFN < '||pranomes||' and '||
                     'BDDATAGRRFFC = '''||prdatapagto||''''||
                     ' and BDCODTIPOFC = '||prcodtipofc||
                     ' union all '||
                     'select bdfgtsfc, bdfgts13fc, bdfgtsfefc from VRHF_EMP_TFOLTOMCOMPINT '||
                     'where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFTOMADOR < '||pranomes||' and '||
                     'BDDATAGRRFFC = '''||prdatapagto||''''||
                     ' and BDCODTIPOFC = '||prcodtipofc||
                  ')';
     
         EXECUTE STATEMENT wwhere INTO :BDFGTSSEMIND;

         IF (BDFGTSSEMIND IS NULL) THEN
            BDFGTSSEMIND = 0;

         IF (BDFGTSSEMIND < 0) THEN
            BDFGTSSEMIND = 0;
     
         IF (BDBFGTS < 0) THEN
            BEGIN
              BDBFGTS = 0;
              BDFGTSSEMIND = 0;
            END
         ELSE
            BDFGTSSEMIND = BDFGTSSEMIND + CAST((((BDBFGTS + BDVALINDEN) * wpercfgtscol / 100) - 0.005) AS NUMERIC(15,2)) - CAST(((BDVALINDEN * wpercfgtscol / 100) - 0.005) AS NUMERIC(15,2));

         IF (BDFGTSSEMIND < 0) THEN
            BDFGTSSEMIND = 0;
       END

    if ((BDCTPSCOL = '') and (BDSERIECTPSCOL = '')) then
      begin
        wsql = 'select substring(bdretorno from 1 for 7) bdretorno from RETIRA_CHAR_ESPECIAL('||''''||BDCPFCOL||''''||')';
        EXECUTE STATEMENT wsql INTO BDCTPSCOL;

        wsql = 'select substring(bdretorno from 8 for 4) bdretorno from RETIRA_CHAR_ESPECIAL('||''''||BDCPFCOL||''''||')';
        EXECUTE STATEMENT wsql INTO BDSERIECTPSCOL;
      end

    if (wdatafgtsdigital is not null) then
       begin
        if (wtipofc = 1) then
           begin
             if (wanomes >= (select * from aaaamm(:wdatafgtsdigital))) then
                 bdbloqueiogrrf = 'TRUE';
              else
                 bdbloqueiogrrf = 'FALSE';
           end
        else
           begin
              if (wdtapuracaoimpadc >= wdatafgtsdigital) then
                 bdbloqueiogrrf = 'TRUE';
              else
                 bdbloqueiogrrf = 'FALSE';
           end
       end
     else
       bdbloqueiogrrf = 'FALSE';

    SUSPEND;
  END
END^

/* Restore proc. body: VRH_SP_LISTAADM_RESC */
create or alter procedure VRH_SP_LISTAADM_RESC (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32700),
    PRANOMESINI integer,
    PRANOMESFIM integer,
    PRFUNCAO integer,
    PRSINDICATO integer,
    PRCLASSE integer,
    PRFILTRAADM integer,
    PRFILTRARESC integer,
    PRLISTAESTAGIARIOS integer,
    PRTPCC varchar(32700) = '')
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDDATAADM date,
    BDDATARESCISAO date,
    BDDATATRF date)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WANO varchar(4);
declare variable WPRIDIA varchar(10);
declare variable WULTDIA varchar(10);
declare variable WMES varchar(2);
declare variable WDIA varchar(2);
BEGIN
  wmes = SUBSTRING(CAST(:pranomesfim AS VARCHAR(6)) FROM 5 FOR 2) ;
  wano = CAST(SUBSTRING(CAST(:pranomesfim AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wultdia = wmes||'/'||wdia||'/'||wano;

  wmes = CAST(SUBSTRING(CAST(:pranomesini AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:pranomesini AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);

  wpridia = wmes||'/'||'01'||'/'||wano;

  EXECUTE PROCEDURE sp_seta_competencia(pranomesfim, NULL, wultdia);

  wsql = 'select COLCON.bdcodemp, COLCON.bdcodcol, COLCAD.bdnomcol, COLCAD.bdnomcolupper , COLCON.BDDATAADMCOL, T.BDDATATRF ';

  IF (prfiltraresc IS NOT NULL AND prfiltraresc = 1) THEN
     wsql = wsql||', rescisao.bddatarescisao ';
  ELSE
     wsql = wsql||', CAST(null as date) BDDATARESCISAO ';

  wsql = wsql||'from VRH_EMP_TCOLCON COLCON
          left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COLCON.BDCODEMP and COLCAD.BDCODCOL = COLCON.BDCODCOL)
          left outer join VRH_EMP_TTRANSCOL T on (T.BDCODEMPDEST = COLCON.BDCODEMP and T.BDCODCOLDEST = COLCON.BDCODCOL) ';


  wsql = wsql||' join vw_vrh_emp_tcolcon_vinc colcon_vinc on (colcon_vinc.bdcodemp = colcon.bdcodemp and colcon_vinc.bdcodcol = colcon.bdcodcol';

  IF (prclasse IS NOT NULL AND prclasse <> 0) THEN
     BEGIN
       wsql = wsql||' and colcon_vinc.bdcodcla = '||prclasse;
     END

  wsql = wsql||') ';
  wsql = wsql||'join vrh_base_tclasse classe on (colcon_vinc.bdcodcla = classe.bdcodcla) ';

  IF (prfuncao IS NOT NULL AND prfuncao <> 0) THEN
     BEGIN
       wsql = wsql||' join vw_vrh_emp_tcol_vincdia col_vincdia on (col_vincdia.bdcodemp = colcon.bdcodemp and col_vincdia.bdcodcol = colcon.bdcodcol and col_vincdia.bdcodtfuc = '||prfuncao||') ';
     END

  IF (prsindicato IS NOT NULL AND prsindicato <> 0) THEN
     BEGIN
       wsql = wsql||' join VW_VRH_EMP_TCOL_VINC col_vinc on (col_vinc.bdcodemp = colcon.bdcodemp and col_vinc.bdcodcol = colcon.bdcodcol and col_vinc.bdcodsintrab = '||prsindicato||') ';
     END


  IF (prfiltraresc IS NOT NULL AND prfiltraresc = 1) THEN
     wsql = wsql||'join vrh_emp_trescisao RESCISAO on (rescisao.bdcodemp = colcon.bdcodemp and rescisao.bdcodcol = colcon.bdcodcol and
           rescisao.bddatarescisao >= '''||:wpridia||''' AND rescisao.bddatarescisao <= '''||:wultdia||''') ';

  IF (prtpcc <> '') then
    begin
      wsql = wsql||' join VRHF_EMP_TPREPFN CC on (CC.BDCODEMP = COLCON.BDCODEMP and CC.BDCODCOL = COLCON.BDCODCOL and '||
                                                  ' CC.BDDATAENTRADA = (select max(BDDATAENTRADA) '||
                                                                       'from VRHF_EMP_TPREPFN '||
                                                                       'where BDCODEMP = COLCON.BDCODEMP and '||
                                                                             'BDCODCOL = COLCON.BDCODCOL and '||prtpcc;

      IF (prfiltraresc IS NOT NULL AND prfiltraresc = 1) THEN
        wsql = wsql||' and EXTRACT(MONTH FROM BDDATAENTRADA) = EXTRACT(month from RESCISAO.BDDATARESCISAO))) ';
      else IF (PRFILTRAADM IS NOT NULL AND PRFILTRAADM = 1) THEN
        wsql = wsql||' and EXTRACT(MONTH FROM BDDATAENTRADA) = EXTRACT(month from COLCON.BDDATAADMCOL))) ';
    end

  wwhere = ' where COLCON.BDCONTRCOL <> 1';

  IF (:prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and '||prcodemp;

  IF (:prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||' and '||prcodcol;

  IF (prfiltraadm = 1 ) THEN
     wwhere = wwhere||' and ((COLCON.bddataadmcol between '''||:wpridia||''' AND '''||:wultdia||''') or (T.BDDATATRF between '''||:wpridia||''' and '''||:wultdia||'''))';

  /*155981 - André Cursino - 04/11/2021*/
  IF (prListaEstagiarios <> 1) then
  wwhere = wwhere||' and classe.bdgrupocla <> 5 ';
  -- oder by
  wwhere = wwhere|| ' order by colcon.bdcodemp, colcon.bdcodcol  ';

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :BDCODCOL,
        :bdnomcol,
        :bdnomcolupper,
        :bddataadm,
        :bddatatrf,
        :bddatarescisao
      DO

    SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

/* Restore proc. body: VRH_SP_LISTAADM_RESC_TOT_EMP */
ALTER PROCEDURE VRH_SP_LISTAADM_RESC_TOT_EMP(PRCODEMP VARCHAR(10000),
PRANOMESANT INTEGER,
PRANOMESATU INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRFILTRAADM INTEGER,
PRFILTRARESC INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCAMPOC INTEGER,
BDCAMPOD INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WANO VARCHAR(4);
DECLARE VARIABLE WPRIDIA VARCHAR(10);
DECLARE VARIABLE WULTDIA VARCHAR(10);
DECLARE VARIABLE WMES VARCHAR(2);
DECLARE VARIABLE WDIA VARCHAR(2);
BEGIN

  wmes = SUBSTRING(CAST(:pranomesatu AS VARCHAR(6)) FROM 5 FOR 2) ;
  wano = CAST(SUBSTRING(CAST(:pranomesatu AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wultdia = wmes||'/'||wdia||'/'||wano;
  wpridia = wmes||'/'||'01'||'/'||wano;

  EXECUTE PROCEDURE sp_seta_competencia(pranomesatu, NULL, wultdia);

  wsql = 'select COLCON.bdcodemp, EMPRESAS.bdnomemp , count(COLCON.bdcodemp) BDCAMPO from VRH_EMP_TCOLCON COLCON
          left outer join vrh_sp_colcon(null,null,null,null,null, ' || pranomesatu || ' , '''||wultdia||''' , 1,1,1,1,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0) spcolcon  on (COLCON.BDCODEMP = spcolcon.BDCODEMP and COLCON.BDCODCOL = spcolcon.BDCODCOL)
          left outer join ](' || pranomesatu || ', null, null) empresas on (empresas.bdcodemp = COLCON.bdcodemp )
          left outer join vrh_emp_trescisao RESCISAO on (rescisao.bdcodemp = colcon.bdcodemp and rescisao.bdcodcol = colcon.bdcodcol)';

  wwhere = '';

  IF (:prcodemp IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and (colcon.bdcodemp = ' || prcodemp || ')';
       ELSE
          wwhere = wwhere || '(colcon.bdcodemp = ' || prcodemp || ')';
     END

  IF (prfiltraadm = 1 ) THEN
    BEGIN
      IF (wwhere <> '') THEN
          wwhere = wwhere||' and (COLCON.bddataadmcol between '''||:wpridia||''' AND '''||:wultdia||''')';
      ELSE
          wwhere = wwhere||'(COLCON.bddataadmcol between '''||:wpridia||''' AND '''||:wultdia||''')';
    END

  IF (prfiltraresc = 1 ) THEN
    BEGIN
      IF (wwhere <> '') THEN
          wwhere = wwhere||' and (rescisao.bddatarescisao between '''||:wpridia||''' AND '''||:wultdia||''')';
      ELSE
          wwhere = wwhere||'(rescisao.bddatarescisao between '''||:wpridia||''' AND '''||:wultdia||''')';
    END

  IF (prfuncao > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'spcolcon.bdcodtfuc = '||prfuncao||' ';  -- funcionario
     END

  IF (prsindicato > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere||'spcolcon.bdCODSINTRAB = '||prsindicato||' ';  -- TCOLVINC.
     END

  IF (prclasse > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'spcolcon.bdCODCLA = '||prclasse||' '; -- tcolcon_vinc
     END



  IF (wwhere <> '') THEN
     wwhere = 'where '||wwhere;

  -- oder by
  wwhere = wwhere|| ' order by colcon.bdcodemp, colcon.bdcodcol  ';

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :bdnomemp
      DO

     bdcampoc = 0;
     bdcampod = 0;

    SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);


END
^

/* Restore proc. body: VRH_SP_REL_RECIBO_13SAL */
create or alter procedure VRH_SP_REL_RECIBO_13SAL (
    PRCODEMP integer,
    PRREF integer,
    PRCODCLA varchar(10000),
    PRCODTPCC varchar(10000) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFV13 numeric(15,6),
    BDREFAUXV13 numeric(15,6),
    BDVALV13 numeric(15,6),
    BDDATAFN integer,
    BDSALBASE numeric(15,6),
    BDBINSS numeric(15,6),
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDCNPJEMP varchar(18),
    BDDESCVER varchar(40),
    BDDESCREDVER varchar(20),
    BDORDEMVER integer,
    BDNOMCOL varchar(70),
    BDDATAADMCOL date,
    BDPISCOL varchar(14),
    BDCPFCOL varchar(14),
    BDRG varchar(13),
    BDTIPOCODVER integer,
    BDORDEMTIPOCODVER integer,
    BDTIPOREFVER integer,
    BDCODBAN integer,
    BDCODAG integer,
    BDCTADEPCOL varchar(15),
    BDDIGCTADEPCOL varchar(2),
    BDMODOPAGTOCOL integer,
    BDCLAVER varchar(20),
    BDEMAILCOL varchar(400),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDQTDSALARIOHE integer)
as
declare variable WSQL varchar(10000);
declare variable WEMAIL1 varchar(200);
declare variable WEMAIL2 varchar(200);
BEGIN

  wSql = '';
  wSql = wSql||'select ';
  wSql = wSql||'  FOL.BDCODEMP, ';
  wSql = wSql||'  FOL.BDCODCOL, ';
  wSql = wSql||'  FOL.BDCODVER, ';
  wSql = wSql||'  FOL.BDREF13, ';
  wSql = wSql||'  FOL.BDREFV13, ';
  wSql = wSql||'  FOL.BDREFAUXV13, ';
  wSql = wSql||'  FOL.BDVALV13, ';
  wSql = wSql||'  FOL.BDREF13, ';
  wSql = wSql||'  FOLB.BDSALBASE13, ';
  wSql = wSql||'  FOLB.BDBASEINSS13, ';
  wSql = wSql||'  FOLB.BDBASEFGTS13, ';
  wSql = wSql||'  FOLB.BDFGTS13, ';
  wSql = wSql||'  FOLB.BDBASEIR13, ';
  wSql = wSql||'  EMP.BDCNPJEMP, ';
  wSql = wSql||'  VERB.BDDESCVER, ';
  wSql = wSql||'  VERB.BDDESCREDVER, ';
  wSql = wSql||'  VERB.BDORDEMVER, ';
  wSql = wSql||'  COLCAD.BDNOMCOL, ';
  wSql = wSql||'  COL.BDDATAADMCOL, ';
  wSql = wSql||'  DOCREF.BDPISCOL, ';
  wSql = wSql||'  COLDOC.BDCPFCOL, ';
  wSql = wSql||'  DOCREF.BDRGCOL, ';
  wSql = wSql||'  VERR.BDTIPOCODVER, ';
  wSql = wSql||'  case when VERR.BDTIPOCODVER = 1 then 2 when VERR.BDTIPOCODVER = 2 then 1 else coalesce(VERR.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, ';
  wSql = wSql||'  VERR.BDTIPOREFVER, ';
  wSql = wSql||'  COLBANCO.BDCODBAN, ';
  wSql = wSql||'  COLBANCO.BDCODAG, ';
  wSql = wSql||'  COLBANCO.BDCTADEPCOL, ';
  wSql = wSql||'  COLBANCO.BDDIGCTADEPCOL, ';
  wSql = wSql||'  COLBANCO.BDMODOPAGTOCOL, ';
  wSql = wSql||'  VERB.BDCLAVER, ';
  wSql = wSql||'  coalesce(COLCAD.BDEMAILCOL, '''') BDEMAIL1, ';
  wSql = wSql||'  coalesce(COLCAD.BDEMAIL2COL, '''') BDEMAIL2, ';
  wSql = wSql||'  DOCREF.BDCTPSCOL, ';
  wSql = wSql||'  DOCREF.BDSERIECTPSCOL, ';
  wSql = wSql||'  DOCREF.BDDSERIECTPSCOL ';
    
  wSql = wSql||'from VRHF_EMP_TVERBA13 FOL ';

  IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
     BEGIN
       wsql = wsql||'join (select BDCODEMP, BDCODCOL, BDCODCENTRO, BDCODTPCC '||
              'from VRHF_SP_TPREPFN_REF('||prref||','''||'COLCON.BDCODEMP = '||prcodemp||''',null,'''||
              SUBSTRING(prref FROM 5 FOR 2)||'-01-'||SUBSTRING(prref FROM 1 FOR 4)||''',null) '||
              ' where '||prcodtpcc||' ) H on (H.BDCODEMP = FOL.BDCODEMP and H.BDCODCOL = FOL.BDCODCOL) ';
     END

  wSql = wSql||'join VRHF_EMP_T13SAL FOLB on (FOLB.BDCODEMP = FOL.BDCODEMP and FOLB.BDCODCOL = FOL.BDCODCOL and FOLB.BDREF13 = FOL.BDREF13) ';

  IF (prCODCLA IS NOT NULL AND prCODCLA <> '') THEN
     begin
       wSql = wSql||'left outer join (select * from VW_VRH_EMP_TCOLCON_VINC '||
                          'where '||prcodcla||'';

       IF (PRCODEMP > 0) THEN
          wSql = wSql||' and BDCODEMP = '||prcodemp;

       wSql = wSql||') COLCON_VIN on (COLCON_VIN.BDCODEMP = FOL.BDCODEMP and COLCON_VIN.BDCODCOL = FOL.BDCODCOL) ';
     end

  wSql = wSql||'join TEMPRESAS EMP on (EMP.BDCODEMP = FOL.BDCODEMP) ';
  wSql = wSql||'join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = FOL.BDCODVER) ';
  wSql = wSql||'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FOL.BDCODEMP and DOCREF.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'join VRH_EMP_TCOLCON_DOC COLDOC on (COLDOC.BDCODEMP = FOL.BDCODEMP and COLDOC.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'left outer join VW_VRH_BASE_TVERBAS_REF VERR on (VERR.BDCODVER = FOL.BDCODVER) ';
  wSql = wSql||'left outer join VW_VRHF_EMP_TCOLCON_BANCO COLBANCO on (COLBANCO.BDCODEMP = FOL.BDCODEMP and COLBANCO.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'where FOL.BDREF13 = '||:PRREF;

  IF (PRCODEMP > 0) THEN
     wSql = wSql||' and FOL.BDCODEMP = '||:PRCODEMP;

  IF (prCODCLA IS NOT NULL AND prCODCLA <> '') THEN
     wSql = wSql||' and COLCON_VIN.BDCODCLA is not null';

  FOR EXECUTE STATEMENT wSql
    INTO :BDCODEMP,
         :BDCODCOL,
         :BDCODVER,
         :BDREFFN,
         :BDREFV13,
         :BDREFAUXV13,
         :BDVALV13,
         :BDDATAFN,
         :BDSALBASE,
         :BDBINSS,
         :BDBFGTS,
         :BDFGTS,
         :BDBIRRF,
         :BDCNPJEMP,
         :BDDESCVER,
         :BDDESCREDVER,
         :BDORDEMVER,
         :BDNOMCOL,
         :BDDATAADMCOL,
         :BDPISCOL,
         :BDCPFCOL,
         :BDRG,
         :BDTIPOCODVER,
         :BDORDEMTIPOCODVER,
         :BDTIPOREFVER,
         :BDCODBAN,
         :BDCODAG,
         :BDCTADEPCOL,
         :BDDIGCTADEPCOL,
         :BDMODOPAGTOCOL,
         :BDCLAVER,
         :wemail1,
         :wemail2,
         :BDCTPSCOL,
         :BDSERIECTPSCOL,
         :BDDSERIECTPSCOL
  DO
  BEGIN
    wemail1 = REPLACE(wemail1, ';', ',');
    wemail1 = REPLACE(wemail1, ' ', ',');

    wemail2 = REPLACE(wemail2, ';', ',');
    wemail2 = REPLACE(wemail2, ' ', ',');

    BDEMAILCOL = '';

    if (TRIM(wemail1) <> '') then
       begin
         BDEMAILCOL = TRIM(wemail1);

         if (TRIM(wemail2) <> '') then
            BDEMAILCOL = BDEMAILCOL||','||TRIM(wemail2);
       end
    else
    if (TRIM(wemail2) <> '') then
       BDEMAILCOL = TRIM(wemail2);

    /*  Sol.152518 Leonardo Schwab 15/07/2021
        Adicionado campo para controlar quantos salários tem o horista especial,
        caso tenha mais de um não irá aparecer o salário base no recibo de salário.
    */
    SELECT COUNT(*)
    FROM (select BDCODEMP, BDCODCOL, BDCODSHE, max(BDDATASHE) BDDATASHE
          from VRH_EMP_TCOL_SHE
    WHERE BDCODEMP = :BDCODEMP AND
          BDCODCOL = :BDCODCOL AND
                BDREFSHE <= :BDREFFN
          group by BDCODEMP, BDCODCOL, BDCODSHE
    )
    INTO :BDQTDSALARIOHE;

    SUSPEND;
  END
END^

/* Restore proc. body: VRH_SP_REL_RECIBO_AD13 */
create or alter procedure VRH_SP_REL_RECIBO_AD13 (
    PRCODEMP integer,
    PRREF integer,
    PRCODCLA varchar(10000),
    PRCODTPCC varchar(10000) = null,
    PR13FERIAS smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFVA13 numeric(18,6),
    BDREFAUXVA13 numeric(18,6),
    BDVALVA13 numeric(18,6),
    BDDATAFN integer,
    BDSALBASE numeric(18,6),
    BDBINSS numeric(18,4),
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBIRRF numeric(18,6),
    BDCALCFERA13 varchar(5),
    BDCNPJEMP varchar(18),
    BDDESCVER varchar(40),
    BDDESCREDVER varchar(20),
    BDORDEMVER integer,
    BDNOMCOL varchar(70),
    BDDATAADMCOL date,
    BDPISCOL varchar(14),
    BDCPFCOL varchar(14),
    BDRG varchar(13),
    BDTIPOCODVER integer,
    BDORDEMTIPOCODVER integer,
    BDTIPOREFVER integer,
    BDCODBAN integer,
    BDCODAG integer,
    BDCTADEPCOL varchar(15),
    BDDIGCTADEPCOL varchar(2),
    BDMODOPAGTOCOL integer,
    BDCLAVER varchar(20),
    BDEMAILCOL varchar(400),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDQTDSALARIOHE integer)
as
declare variable WSQL varchar(10000);
declare variable WEMAIL1 varchar(200);
declare variable WEMAIL2 varchar(200);
BEGIN

  wSql = '';
  wSql = wSql||'select ';
  wSql = wSql||'  FOL.BDCODEMP, ';
  wSql = wSql||'  FOL.BDCODCOL, ';
  wSql = wSql||'  FOL.BDCODVER, ';
  wSql = wSql||'  FOL.BDREFA13, ';
  wSql = wSql||'  FOL.BDREFVA13, ';
  wSql = wSql||'  FOL.BDREFAUXVA13, ';
  wSql = wSql||'  FOL.BDVALVA13, ';
  wSql = wSql||'  FOL.BDREFA13, ';
  wSql = wSql||'  FOLB.BDSALBASEA13, ';
  wSql = wSql||'  0.0000, ';
  wSql = wSql||'  FOLB.BDBASEFGTSA13, ';
  wSql = wSql||'  FOLB.BDFGTSA13, ';
  wSql = wSql||'  FOLB.BDBASEIRA13, ';
  wSql = wSql||'  FOLB.BDCALCFERA13, ';
  wSql = wSql||'  EMP.BDCNPJEMP, ';
  wSql = wSql||'  VERB.BDDESCVER, ';
  wSql = wSql||'  VERB.BDDESCREDVER, ';
  wSql = wSql||'  VERB.BDORDEMVER, ';
  wSql = wSql||'  COLCAD.BDNOMCOL, ';
  wSql = wSql||'  COL.BDDATAADMCOL, ';
  wSql = wSql||'  DOCREF.BDPISCOL, ';
  wSql = wSql||'  COLDOC.BDCPFCOL, ';
  wSql = wSql||'  DOCREF.BDRGCOL, ';
  wSql = wSql||'  VERR.BDTIPOCODVER, ';
  wSql = wSql||'  case when VERR.BDTIPOCODVER = 1 then 2 when VERR.BDTIPOCODVER = 2 then 1 else coalesce(VERR.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, ';
  wSql = wSql||'  VERR.BDTIPOREFVER, ';
  wSql = wSql||'  COLBANCO.BDCODBAN, ';
  wSql = wSql||'  COLBANCO.BDCODAG, ';
  wSql = wSql||'  COLBANCO.BDCTADEPCOL, ';
  wSql = wSql||'  COLBANCO.BDDIGCTADEPCOL, ';
  wSql = wSql||'  COLBANCO.BDMODOPAGTOCOL, ';
  wSql = wSql||'  VERB.BDCLAVER, ';
  wSql = wSql||'  coalesce(COLCAD.BDEMAILCOL, '''') BDEMAIL1, ';
  wSql = wSql||'  coalesce(COLCAD.BDEMAIL2COL, '''') BDEMAIL2, ';
  wSql = wSql||'  DOCREF.BDCTPSCOL, ';
  wSql = wSql||'  DOCREF.BDSERIECTPSCOL, ';
  wSql = wSql||'  DOCREF.BDDSERIECTPSCOL ';
    
  wSql = wSql||'from VRHF_EMP_TVERBAA13 FOL ';

  IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
     BEGIN
       wsql = wsql||'join (select BDCODEMP, BDCODCOL, BDCODCENTRO, BDCODTPCC '||
              'from VRHF_SP_TPREPFN_REF('||prref||','''||'COLCON.BDCODEMP = '||prcodemp||''',null,'''||
              SUBSTRING(prref FROM 5 FOR 2)||'-01-'||SUBSTRING(prref FROM 1 FOR 4)||''',null) '||
              ' where '||prcodtpcc||' ) H on (H.BDCODEMP = FOL.BDCODEMP and H.BDCODCOL = FOL.BDCODCOL) ';
     END

  IF (prCODCLA IS NOT NULL AND prCODCLA <> '') THEN
     begin
       wSql = wSql||'left outer join (select * from VW_VRH_EMP_TCOLCON_VINC '||
                          'where '||prcodcla||'';

       IF (PRCODEMP > 0) THEN
          wSql = wSql||' and BDCODEMP = '||prcodemp;

       wSql = wSql||') COLCON_VIN on (COLCON_VIN.BDCODEMP = FOL.BDCODEMP and COLCON_VIN.BDCODCOL = FOL.BDCODCOL) ';
     end

  wSql = wSql||'join VRHF_EMP_TA13SAL FOLB on (FOLB.BDCODEMP = FOL.BDCODEMP and FOLB.BDCODCOL = FOL.BDCODCOL and FOLB.BDREFA13 = FOL.BDREFA13) ';
  wSql = wSql||'join TEMPRESAS EMP on (EMP.BDCODEMP = FOL.BDCODEMP) ';
  wSql = wSql||'join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = FOL.BDCODVER) ';
  wSql = wSql||'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FOL.BDCODEMP and DOCREF.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'join VRH_EMP_TCOLCON_DOC COLDOC on (COLDOC.BDCODEMP = FOL.BDCODEMP and COLDOC.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'left outer join VW_VRH_BASE_TVERBAS_REF VERR on (VERR.BDCODVER = FOL.BDCODVER) ';
  wSql = wSql||'left outer join VW_VRHF_EMP_TCOLCON_BANCO COLBANCO on (COLBANCO.BDCODEMP = FOL.BDCODEMP and COLBANCO.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'where FOL.bdrefa13 = '||:PRREF||' ';

  IF (PRCODEMP > 0) THEN
     wSql = wSql||' and FOL.BDCODEMP = '||:PRCODEMP;

  IF (prCODCLA IS NOT NULL AND prCODCLA <> '') THEN
     wSql = wSql||' and COLCON_VIN.BDCODCLA is not null';

  if (coalesce(pr13ferias, 0) = 0) then
     wSql = wSql||' and UPPER(COALESCE(FOLB.BDCALCFERA13, ''FALSE'')) <> ''TRUE'' ';

  FOR EXECUTE STATEMENT wSql
    INTO :BDCODEMP,
         :BDCODCOL,
         :BDCODVER,
         :BDREFFN,
         :BDREFVA13,
         :BDREFAUXVA13,
         :BDVALVA13,
         :BDDATAFN,
         :BDSALBASE,
         :BDBINSS,
         :BDBFGTS,
         :BDFGTS,
         :BDBIRRF,
         :BDCALCFERA13,
         :BDCNPJEMP,
         :BDDESCVER,
         :BDDESCREDVER,
         :BDORDEMVER,
         :BDNOMCOL,
         :BDDATAADMCOL,
         :BDPISCOL,
         :BDCPFCOL,
         :BDRG,
         :BDTIPOCODVER,
         :BDORDEMTIPOCODVER,
         :BDTIPOREFVER,
         :BDCODBAN,
         :BDCODAG,
         :BDCTADEPCOL,
         :BDDIGCTADEPCOL,
         :BDMODOPAGTOCOL,
         :BDCLAVER,
         :wemail1,
         :wemail2,
         :BDCTPSCOL,
         :BDSERIECTPSCOL,
         :BDDSERIECTPSCOL
  DO
  BEGIN
    wemail1 = REPLACE(wemail1, ';', ',');
    wemail1 = REPLACE(wemail1, ' ', ',');

    wemail2 = REPLACE(wemail2, ';', ',');
    wemail2 = REPLACE(wemail2, ' ', ',');

    BDEMAILCOL = '';

    if (TRIM(wemail1) <> '') then
       begin
         BDEMAILCOL = TRIM(wemail1);

         if (TRIM(wemail2) <> '') then
            BDEMAILCOL = BDEMAILCOL||','||TRIM(wemail2);
       end
    else
    if (TRIM(wemail2) <> '') then
       BDEMAILCOL = TRIM(wemail2);

    /*  Sol.152518 Leonardo Schwab 15/07/2021
        Adicionado campo para controlar quantos salários tem o horista especial,
        caso tenha mais de um não irá aparecer o salário base no recibo de salário.
    */
    SELECT COUNT(*)
    FROM (select BDCODEMP, BDCODCOL, BDCODSHE, max(BDDATASHE) BDDATASHE
          from VRH_EMP_TCOL_SHE
    WHERE BDCODEMP = :BDCODEMP AND
          BDCODCOL = :BDCODCOL AND
                BDREFSHE <= :BDREFFN
          group by BDCODEMP, BDCODCOL, BDCODSHE
    )
    INTO :BDQTDSALARIOHE;

    SUSPEND;
  END
END^

/* Restore proc. body: VRH_SP_REL_RECIBO_ADIANTAMENTO */
create or alter procedure VRH_SP_REL_RECIBO_ADIANTAMENTO (
    PRCODEMP integer,
    PRDATAINI varchar(10),
    PRDATAFIM varchar(10),
    PRCODCLA varchar(10000),
    PRCODTPCC varchar(10000) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDDATA date,
    BDREFVAD numeric(15,6),
    BDREFAUXVAD numeric(15,6),
    BDVALVAD numeric(15,6),
    BDDATAFN date,
    BDBINSS numeric(15,2),
    BDBFGTS numeric(15,2),
    BDFGTS numeric(15,2),
    BDBIRRF numeric(15,6),
    BDCNPJEMP varchar(18),
    BDDESCVER varchar(40),
    BDDESCREDVER varchar(20),
    BDORDEMVER integer,
    BDNOMCOL varchar(70),
    BDDATAADMCOL date,
    BDPISCOL varchar(14),
    BDCPFCOL varchar(14),
    BDRG varchar(13),
    BDTIPOCODVER integer,
    BDORDEMTIPOCODVER integer,
    BDTIPOREFVER integer,
    BDCODBAN integer,
    BDCODAG integer,
    BDCTADEPCOL varchar(15),
    BDDIGCTADEPCOL varchar(2),
    BDMODOPAGTOCOL integer,
    BDSALBASE numeric(15,6),
    BDCLAVER varchar(20),
    BDEMAILCOL varchar(400),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDQTDSALARIOHE integer)
as
declare variable WSQL varchar(10000);
declare variable WREF integer;
declare variable WEMAIL1 varchar(200);
declare variable WEMAIL2 varchar(200);
BEGIN

  wSql = '';
  wSql = wSql||'select ';
  wSql = wSql||'  FOL.BDCODEMP, ';
  wSql = wSql||'  FOL.BDCODCOL, ';
  wSql = wSql||'  FOL.BDCODVER, ';
  wSql = wSql||'  CAST((SUBSTRING(CAST(FOL.BDDATAAD AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FOL.BDDATAAD AS VARCHAR(10)) FROM 6 FOR 2)||SUBSTRING(CAST(FOL.BDDATAAD AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER), ';
  wSql = wSql||'  FOL.BDDATAAD, ';
  wSql = wSql||'  FOL.BDREFVAD, ';
  wSql = wSql||'  FOL.BDREFAUXVAD, ';
  wSql = wSql||'  FOL.BDVALVAD, ';
  wSql = wSql||'  FOL.BDDATAAD, ';
  wSql = wSql||'  0.00, ';
  wSql = wSql||'  0.00, ';
  wSql = wSql||'  0.00, ';
  wSql = wSql||'  FOLB.BDBASEIRAD, ';
  wSql = wSql||'  EMP.BDCNPJEMP, ';
  wSql = wSql||'  VERB.BDDESCVER, ';
  wSql = wSql||'  VERB.BDDESCREDVER, ';
  wSql = wSql||'  VERB.BDORDEMVER, ';
  wSql = wSql||'  COL.BDDATAADMCOL, ';
  wSql = wSql||'  COLDOC.BDCPFCOL, ';
  wSql = wSql||'  DOCREF.BDRGCOL, ';
  wSql = wSql||'  VERR.BDTIPOCODVER, ';
  wSql = wSql||'  case when VERR.BDTIPOCODVER = 1 then 2 when VERR.BDTIPOCODVER = 2 then 1 else coalesce(VERR.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, ';
  wSql = wSql||'  VERR.BDTIPOREFVER, ';
  wSql = wSql||'  VERB.BDCLAVER, ';
  wSql = wSql||'  FOLB.BDSALBASEAD, ';
  wSql = wSql||'  DOCREF.BDCTPSCOL, ';
  wSql = wSql||'  DOCREF.BDSERIECTPSCOL, ';
  wSql = wSql||'  DOCREF.BDDSERIECTPSCOL ';
    
  wSql = wSql||'from VRHF_EMP_TVERBAAD FOL ';
  wSql = wSql||'join VRHF_EMP_TADSAL FOLB on (FOLB.BDCODEMP = FOL.BDCODEMP and FOLB.BDCODCOL = FOL.BDCODCOL and FOLB.BDDATAAD = FOL.BDDATAAD) ';

  IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
     BEGIN
       wsql = wsql||'join (select BDCODEMP, BDCODCOL, BDCODCENTRO, BDCODTPCC '||
              'from VRHF_SP_TPREPFN_REF('||SUBSTRING(prdatafim FROM 7 FOR 4)||SUBSTRING(prdatafim FROM 1 FOR 2)||
              ','''||'COLCON.BDCODEMP = '||prcodemp||''',null,'''||prdataini||''','''||prdatafim||''')'||
              ' where '||prcodtpcc||') H on (H.BDCODEMP = FOL.BDCODEMP and H.BDCODCOL = FOL.BDCODCOL) ';
     END

  IF (prCODCLA IS NOT NULL AND prCODCLA <> '') THEN
     begin
       wSql = wSql||'left outer join (select * from VW_VRH_EMP_TCOLCON_VINC '||
                          'where '||prcodcla||'';

       IF (PRCODEMP > 0) THEN
          wSql = wSql||' and BDCODEMP = '||prcodemp;

       wSql = wSql||') COLCON_VIN on (COLCON_VIN.BDCODEMP = FOL.BDCODEMP and COLCON_VIN.BDCODCOL = FOL.BDCODCOL) ';
     end

  wSql = wSql||'join TEMPRESAS EMP on (EMP.BDCODEMP = FOL.BDCODEMP) ';
  wSql = wSql||'join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = FOL.BDCODVER) ';
  wSql = wSql||'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'join VRH_EMP_TCOLCON_DOC COLDOC on (COLDOC.BDCODEMP = FOL.BDCODEMP and COLDOC.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FOL.BDCODEMP and DOCREF.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'left outer join VW_VRH_BASE_TVERBAS_REF VERR on (VERR.BDCODVER = FOL.BDCODVER) ';
  wSql = wSql||'where FOL.BDDATAAD between '''||:PRDATAINI||''' and '''||:PRDATAFIM||''' ';

  IF (PRCODEMP > 0) THEN
     wSql = wSql||' and FOL.BDCODEMP = '||:PRCODEMP;

  IF (prCODCLA IS NOT NULL AND prCODCLA <> '') THEN
     wSql = wSql||' and COLCON_VIN.BDCODCLA is not null';

  FOR EXECUTE STATEMENT wSql
    INTO :BDCODEMP,
         :BDCODCOL,
         :BDCODVER,
         :BDREFFN,
         :BDDATA,
         :BDREFVAD,
         :BDREFAUXVAD,
         :BDVALVAD,
         :BDDATAFN,
         :BDBINSS,
         :BDBFGTS,
         :BDFGTS,
         :BDBIRRF,
         :BDCNPJEMP,
         :BDDESCVER,
         :BDDESCREDVER,
         :BDORDEMVER,
         :BDDATAADMCOL,
         :BDCPFCOL,
         :BDRG,
         :BDTIPOCODVER,
         :BDORDEMTIPOCODVER,
         :BDTIPOREFVER,
         :BDCLAVER,
         :BDSALBASE,
         :BDCTPSCOL,
         :BDSERIECTPSCOL,
         :BDDSERIECTPSCOL
  DO
  BEGIN
    wref = CAST((SUBSTRING(:prdatafim from 7 for 4)||SUBSTRING(:prdatafim from 1 for 2)) as INTEGER);

    select first 1 BDCODBAN,BDCODAG,BDCTADEPCOL,BDDIGCTADEPCOL,BDMODOPAGTOCOL
    from VRHF_EMP_TCOLCON_BANCO
    where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :wref
    order by BDREFCOL DESC into :BDCODBAN,:BDCODAG,:BDCTADEPCOL,:BDDIGCTADEPCOL,:BDMODOPAGTOCOL;


    select first 1 CASE WHEN (FIS.BDNMSOCIAL <> '' and PAR.bdusanomesocial = 'TRUE') THEN FIS.BDNMSOCIAL ELSE cad.BDNOMCOL END BDNOMCOL, coalesce(BDEMAILCOL, '') BDEMAIL1 from VRH_EMP_TCOLCON_CAD cad
    left outer join VRH_EMP_TCOLCON_FIS FIS ON (FIS.BDCODEMP = cad.BDCODEMP AND FIS.BDCODCOL = cad.BDCODCOL AND FIS.bdrefcol=cad.bdrefcol)
    left outer join(select a.bdcodemp,max(a.bdrefemp)bdrefemp from VRHF_BASE_TEMPPAR a group by a.bdcodemp) pmax on  (pmax.BDCODEMP = cad.BDCODEMP)
    left outer join VRHF_BASE_TEMPPAR PAR  on (par.bdcodemp=pmax.bdcodemp and par.bdrefemp=pmax.bdrefemp)
    where CAD.BDCODEMP = :BDCODEMP and CAD.BDCODCOL = :BDCODCOL and CAD.BDREFCOL <= :wref
    order by CAD.BDREFCOL DESC
    into :Bdnomcol, :wemail1; 

    select first 1 coalesce(BDEMAIL2COL, '') BDEMAIL2
    from VRH_EMP_TCOLCON
    where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL
    into :wemail2;

    wemail1 = REPLACE(wemail1, ';', ',');
    wemail1 = REPLACE(wemail1, ' ', ',');

    wemail2 = REPLACE(wemail2, ';', ',');
    wemail2 = REPLACE(wemail2, ' ', ',');

    BDEMAILCOL = '';

    if (TRIM(wemail1) <> '') then
       begin
         BDEMAILCOL = TRIM(wemail1);

         if (TRIM(wemail2) <> '') then
            BDEMAILCOL = BDEMAILCOL||','||TRIM(wemail2);
       end
    else
    if (TRIM(wemail2) <> '') then
       BDEMAILCOL = TRIM(wemail2);

    select first 1 BDPISCOL
    from VRH_EMP_TCOLCON_DOCREF
    where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :wref
    order by BDREFCOL DESC
    into :BDPISCOL;

    /*  Sol.152518 Leonardo Schwab 15/07/2021
        Adicionado campo para controlar quantos salários tem o horista especial,
        caso tenha mais de um não irá aparecer o salário base no recibo de salário.
    */
    SELECT COUNT(*)
    FROM (select BDCODEMP, BDCODCOL, BDCODSHE, max(BDDATASHE) BDDATASHE
          from VRH_EMP_TCOL_SHE
    WHERE BDCODEMP = :BDCODEMP AND
          BDCODCOL = :BDCODCOL AND
                BDREFSHE <= :BDREFFN
          group by BDCODEMP, BDCODCOL, BDCODSHE
    )
    INTO :BDQTDSALARIOHE;

    SUSPEND;
  END
END^

/* Restore proc. body: VRH_SP_REL_RECIBO_C13SAL */
create or alter procedure VRH_SP_REL_RECIBO_C13SAL (
    PRCODEMP integer,
    PRREF integer,
    PRCODCLA varchar(10000),
    PRCODTPCC varchar(10000) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFVC13 numeric(18,6),
    BDREFAUXVC13 numeric(18,6),
    BDVALVC13 numeric(18,6),
    BDDATAFN integer,
    BDSALBASE numeric(18,6),
    BDBINSS numeric(18,6),
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBIRRF numeric(18,6),
    BDCNPJEMP varchar(18),
    BDDESCVER varchar(40),
    BDDESCREDVER varchar(20),
    BDORDEMVER integer,
    BDNOMCOL varchar(70),
    BDDATAADMCOL date,
    BDPISCOL varchar(14),
    BDCPFCOL varchar(14),
    BDRG varchar(13),
    BDTIPOCODVER integer,
    BDORDEMTIPOCODVER integer,
    BDTIPOREFVER integer,
    BDCODBAN integer,
    BDCODAG integer,
    BDCTADEPCOL varchar(15),
    BDDIGCTADEPCOL varchar(2),
    BDMODOPAGTOCOL integer,
    BDCLAVER varchar(20),
    BDEMAILCOL varchar(400),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDQTDSALARIOHE integer)
as
declare variable WSQL varchar(10000);
declare variable WEMAIL1 varchar(200);
declare variable WEMAIL2 varchar(200);
BEGIN

  wSql = '';
  wSql = wSql||'select ';
  wSql = wSql||'  FOL.BDCODEMP, ';
  wSql = wSql||'  FOL.BDCODCOL, ';
  wSql = wSql||'  FOL.BDCODVER, ';
  wSql = wSql||'  FOL.BDREFC13, ';
  wSql = wSql||'  FOL.BDREFVC13, ';
  wSql = wSql||'  FOL.BDREFAUXVC13, ';
  wSql = wSql||'  FOL.BDVALVC13, ';
  wSql = wSql||'  FOL.BDREFC13, ';
  wSql = wSql||'  FOLB.BDSALBASEC13, ';
  wSql = wSql||'  COALESCE(FOLB.BDBASEINSSC13, 0) + COALESCE(FOLB.BDBINSS13C13, 0), ';
  wSql = wSql||'  FOLB.BDBASEFGTSC13, ';
  wSql = wSql||'  FOLB.BDFGTSC13, ';
  wSql = wSql||'  FOLB.BDBASEIRC13, ';
  wSql = wSql||'  EMP.BDCNPJEMP, ';
  wSql = wSql||'  VERB.BDDESCVER, ';
  wSql = wSql||'  VERB.BDDESCREDVER, ';
  wSql = wSql||'  VERB.BDORDEMVER, ';
  wSql = wSql||'  COLCAD.BDNOMCOL, ';
  wSql = wSql||'  COL.BDDATAADMCOL, ';
  wSql = wSql||'  DOCREF.BDPISCOL, ';
  wSql = wSql||'  COLDOC.BDCPFCOL, ';
  wSql = wSql||'  DOCREF.BDRGCOL, ';
  wSql = wSql||'  VERR.BDTIPOCODVER, ';
  wSql = wSql||'  case when VERR.BDTIPOCODVER = 1 then 2 when VERR.BDTIPOCODVER = 2 then 1 else coalesce(VERR.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, ';
  wSql = wSql||'  VERR.BDTIPOREFVER, ';
  wSql = wSql||'  COLBANCO.BDCODBAN, ';
  wSql = wSql||'  COLBANCO.BDCODAG, ';
  wSql = wSql||'  COLBANCO.BDCTADEPCOL, ';
  wSql = wSql||'  COLBANCO.BDDIGCTADEPCOL, ';
  wSql = wSql||'  COLBANCO.BDMODOPAGTOCOL, ';
  wSql = wSql||'  VERB.BDCLAVER, ';
  wSql = wSql||'  coalesce(COLCAD.BDEMAILCOL, '''') BDEMAIL1, ';
  wSql = wSql||'  coalesce(COLCAD.BDEMAIL2COL, '''') BDEMAIL2, ';
  wSql = wSql||'  DOCREF.BDCTPSCOL, ';
  wSql = wSql||'  DOCREF.BDSERIECTPSCOL, ';
  wSql = wSql||'  DOCREF.BDDSERIECTPSCOL ';
    
  wSql = wSql||'from VRHF_EMP_TVERBAC13 FOL ';
  wSql = wSql||'join VRHF_EMP_TC13SAL FOLB on (FOLB.BDCODEMP = FOL.BDCODEMP and FOLB.BDCODCOL = FOL.BDCODCOL and FOLB.BDREFC13 = FOL.BDREFC13) ';

  IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
     BEGIN
       wsql = wsql||'join (select BDCODEMP, BDCODCOL, BDCODCENTRO, BDCODTPCC '||
              'from VRHF_SP_TPREPFN_REF('||prref||','''||'COLCON.BDCODEMP = '||prcodemp||''',null,'''||
              SUBSTRING(prref FROM 5 FOR 2)||'-01-'||SUBSTRING(prref FROM 1 FOR 4)||''',null) '||
              ' where '||prcodtpcc||' ) H on (H.BDCODEMP = FOL.BDCODEMP and H.BDCODCOL = FOL.BDCODCOL) ';
     END

  IF (prCODCLA IS NOT NULL AND prCODCLA <> '') THEN
     begin
       wSql = wSql||'left outer join (select * from VW_VRH_EMP_TCOLCON_VINC '||
                          'where '||prcodcla||'';

       IF (PRCODEMP > 0) THEN
          wSql = wSql||' and BDCODEMP = '||prcodemp;

       wSql = wSql||') COLCON_VIN on (COLCON_VIN.BDCODEMP = FOL.BDCODEMP and COLCON_VIN.BDCODCOL = FOL.BDCODCOL) ';
     end

  wSql = wSql||'join TEMPRESAS EMP on (EMP.BDCODEMP = FOL.BDCODEMP) ';
  wSql = wSql||'join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = FOL.BDCODVER) ';
  wSql = wSql||'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FOL.BDCODEMP and DOCREF.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'join VRH_EMP_TCOLCON_DOC COLDOC on (COLDOC.BDCODEMP = FOL.BDCODEMP and COLDOC.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'left outer join VW_VRH_BASE_TVERBAS_REF VERR on (VERR.BDCODVER = FOL.BDCODVER) ';
  wSql = wSql||'left outer join VW_VRHF_EMP_TCOLCON_BANCO COLBANCO on (COLBANCO.BDCODEMP = FOL.BDCODEMP and COLBANCO.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'where FOLB.BDPAGOFNC13 <> '''||'TRUE'||'''';

  IF (PRCODEMP > 0) THEN
     wSql = wSql||' and FOL.BDCODEMP = '||:PRCODEMP;

  IF (prCODCLA IS NOT NULL AND prCODCLA <> '') THEN
     wSql = wSql||' and COLCON_VIN.BDCODCLA is not null';

  FOR EXECUTE STATEMENT wSql
    INTO :BDCODEMP,
         :BDCODCOL,
         :BDCODVER,
         :BDREFFN,
         :BDREFVC13,
         :BDREFAUXVC13,
         :BDVALVC13,
         :BDDATAFN,
         :BDSALBASE,
         :BDBINSS,
         :BDBFGTS,
         :BDFGTS,
         :BDBIRRF,
         :BDCNPJEMP,
         :BDDESCVER,
         :BDDESCREDVER,
         :BDORDEMVER,
         :BDNOMCOL,
         :BDDATAADMCOL,
         :BDPISCOL,
         :BDCPFCOL,
         :BDRG,
         :BDTIPOCODVER,
         :BDORDEMTIPOCODVER,
         :BDTIPOREFVER,
         :BDCODBAN,
         :BDCODAG,
         :BDCTADEPCOL,
         :BDDIGCTADEPCOL,
         :BDMODOPAGTOCOL,
         :BDCLAVER,
         :wemail1,
         :wemail2,
         :BDCTPSCOL,
         :BDSERIECTPSCOL,
         :BDDSERIECTPSCOL
  DO
  BEGIN
    wemail1 = REPLACE(wemail1, ';', ',');
    wemail1 = REPLACE(wemail1, ' ', ',');

    wemail2 = REPLACE(wemail2, ';', ',');
    wemail2 = REPLACE(wemail2, ' ', ',');

    BDEMAILCOL = '';

    if (TRIM(wemail1) <> '') then
       begin
         BDEMAILCOL = TRIM(wemail1);

         if (TRIM(wemail2) <> '') then
            BDEMAILCOL = BDEMAILCOL||','||TRIM(wemail2);
       end
    else
    if (TRIM(wemail2) <> '') then
       BDEMAILCOL = TRIM(wemail2);

    /*  Sol.152518 Leonardo Schwab 15/07/2021
        Adicionado campo para controlar quantos salários tem o horista especial,
        caso tenha mais de um não irá aparecer o salário base no recibo de salário.
    */
    SELECT COUNT(*)
    FROM (select BDCODEMP, BDCODCOL, BDCODSHE, max(BDDATASHE) BDDATASHE
          from VRH_EMP_TCOL_SHE
    WHERE BDCODEMP = :BDCODEMP AND
          BDCODCOL = :BDCODCOL AND
                BDREFSHE <= :BDREFFN
          group by BDCODEMP, BDCODCOL, BDCODSHE
    )
    INTO :BDQTDSALARIOHE;

    SUSPEND;
  END
END^

/* Restore proc. body: VRH_SP_REL_RECIBO_FOLCOMP */
create or alter procedure VRH_SP_REL_RECIBO_FOLCOMP (
    PRCODEMP integer,
    PRREF integer,
    PRREFPAG integer,
    PRCODCLA varchar(10000),
    PRCODTPCC varchar(20000) = null /* COLLATE WIN1252 - default */ ,
    PRSITCOL smallint = 1,
    PRVINCFN integer = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFFC integer,
    BDREFVFN_SUM numeric(18,6),
    BDREFVFN_MAX numeric(18,6),
    BDREFAUXVFN_SUM numeric(18,6),
    BDREFAUXVFN_MAX numeric(18,6),
    BDVALVFN numeric(18,6),
    BDDATAFN integer,
    BDSALBASE numeric(18,6),
    BDBINSS numeric(18,6),
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBIRRF numeric(18,6),
    BDCNPJEMP varchar(18),
    BDDESCVER varchar(40),
    BDDESCREDVER varchar(20),
    BDORDEMVER integer,
    BDNOMCOL varchar(70),
    BDDATAADMCOL date,
    BDPISCOL varchar(14),
    BDCPFCOL varchar(14),
    BDRG varchar(13),
    BDTIPOCODVER integer,
    BDORDEMTIPOCODVER integer,
    BDTIPOREFVER integer,
    BDCODBAN integer,
    BDCODAG integer,
    BDCTADEPCOL varchar(15),
    BDDIGCTADEPCOL varchar(2),
    BDMODOPAGTOCOL integer,
    BDCLAVER varchar(20),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDEMAILCOL varchar(400),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDQTDSALARIOHE integer,
    BDVERCALCRRA integer,
    BDBASETOTAL DM_BOOLEAN,
    BDORDEM integer)
as
declare variable WSQL varchar(20000);
declare variable WEMAIL1 varchar(200);
declare variable WEMAIL2 varchar(200);
declare variable WFILTROFN varchar(200);
declare variable WFILTROFT varchar(200);
declare variable WFILTROSIT varchar(5000);
BEGIN
/*
   O parâmetro prsitcol filtra os colaboradores conforme o combobox de situação

   0 = Somente ativos
   1 = Todos
   2 = Somente admitidos no mês
   3 = Somente demitidos no mês (Estagiários)
   4 = Ativos sem os demitidos no mês   (Estagiários demitidos no mês)
   5 = Ativos sem os transferidos no mês
   6 = Ativos sem os afastados o mês inteiro
   7 = Afastados o mês inteiro.

 */
  prcodtpcc = COALESCE(prcodtpcc,'');

  /* FILTROS */

  wfiltrofn = '';
  wfiltroft = '';

  -- Empresa
  IF (PRCODEMP > 0) THEN
     BEGIN
       wfiltrofn = wfiltrofn||'(X.BDCODEMP = '||:prcodemp||') and ';
       wfiltroft = wfiltroft||'(X.BDCODEMP = '||:PRCODEMP||') and ';
     END

  -- Competencia
  IF (prref <> 0) THEN
     BEGIN
       wfiltrofn = wfiltrofn||'(X.BDREFFN = '||:prref||') and ';
       wfiltroft = wfiltroft||'(X.BDREFTOMADOR = '||:PRREF||') and ';
     END

  -- Pagamento
  IF (PRREFPAG > 1000000) THEN -- Data completa
     BEGIN
       wfiltrofn = wfiltrofn||'(X.BDREFFC = '||:prrefpag||') ';
       wfiltroft = wfiltroft||'(X.BDREFFC = '||:PRREFPAG||') ';
     END
  ELSE
     BEGIN
       wfiltrofn = wfiltrofn||'(X.BDREFCOMP = '||:prrefpag||') ';
       wfiltroft = wfiltroft||'(X.BDREFCOMP = '||:Prrefpag||') ';
     END

  -- Tomador
  IF (prcodtpcc <> '') THEN
     wfiltroft = wfiltroft||' and '||prcodtpcc;


  /* SITUACAO */

  -- Competencia em branco
  IF (COALESCE(prref,0) = 0) THEN
     wfiltrosit = '';
  ELSE
  -- Somente ativos e todos  (nunca entram demitidos que não sejam estagiários)
  IF (prsitcol IN (0, 1, 2)) THEN
     wfiltrosit = ' and not exists(select RESC.BDCODEMP, RESC.BDCODCOL '||
                                  'from VRH_EMP_TRESCISAO RESC '||
                                  'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES) and (PRES.BDTIPOMOV <> 1) '||
                                  'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = RESC.bdcodemp) and (vd.bdcodcol = RESC.bdcodcol) '||
                                  'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                  'where (RESC.BDCODEMP = X.BDCODEMP) and (RESC.BDCODCOL = X.BDCODCOL) '||
                                    'and ((RESC.BDREFRESCISAO < '||prref||') '||
                                      'or ((RESC.BDREFRESCISAO = '||prref||') and (cla.bdgrupocla <> 5))))';
  ELSE
  -- Somente estagiários demitidos no mês
  IF (prsitcol = 3) THEN
     wfiltrosit = ' and exists(select RESC.BDCODEMP, RESC.BDCODCOL '||
                              'from VRH_EMP_TRESCISAO RESC '||
                              'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES) and (PRES.BDTIPOMOV <> 1) '||
                              'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = RESC.bdcodemp) and (vd.bdcodcol = RESC.bdcodcol) '||
                              'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                              'where (RESC.BDCODEMP = X.BDCODEMP) and (RESC.BDCODCOL = X.BDCODCOL) '||
                                'and (RESC.BDREFRESCISAO = '||prref||') and (cla.bdgrupocla = 5))';
  ELSE
  -- Ativos sem demitidos
  IF (prsitcol = 4) THEN
     wfiltrosit = ' and not exists(select RESC.BDCODEMP, RESC.BDCODCOL '||
                                  'from VRH_EMP_TRESCISAO RESC '||
                                  'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES) and (PRES.BDTIPOMOV <> 1) '||
                                  'where (RESC.BDCODEMP = X.BDCODEMP) and (RESC.BDCODCOL = X.BDCODCOL) '||
                                    'and (RESC.BDREFRESCISAO < '||prref||'))';
  ELSE
  -- Ativos sem transferidos
  IF (prsitcol = 5) THEN
     wfiltrosit = ' and not exists(select RESC.BDCODEMP, RESC.BDCODCOL '||
                                  'from VRH_EMP_TRESCISAO RESC '||
                                  'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES) and (PRES.BDTIPOMOV <> 1) '||
                                  'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = RESC.bdcodemp) and (vd.bdcodcol = RESC.bdcodcol) '||
                                  'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                  'where (RESC.BDCODEMP = X.BDCODEMP) and (RESC.BDCODCOL = X.BDCODCOL) '||
                                    'and ((RESC.BDREFRESCISAO < '||prref||') '||
                                      'or ((RESC.BDREFRESCISAO = '||prref||') and (cla.bdgrupocla <> 5)))) ' ||
                  ' and not exists(select RESC.BDCODEMP, RESC.BDCODCOL '||
                                  'from VRH_EMP_TRESCISAO RESC '||
                                  'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES) and (PRES.BDTIPOMOV = 1) '||
                                  'where (RESC.BDCODEMP = X.BDCODEMP) and (RESC.BDCODCOL = X.BDCODCOL) '||
                                    'and (RESC.BDREFRESCISAO = '||prref||'))';
  ELSE
  -- Ativos sem os afastados o mês inteiro
  IF (prsitcol = 6) THEN
     wfiltrosit = ' and not exists(select RESC.BDCODEMP, RESC.BDCODCOL '||
                                  'from VRH_EMP_TRESCISAO RESC '||
                                  'join vrh_base_tprepresc PRES on (PRES.BDCODPRES = RESC.BDCODPRES) and (PRES.BDTIPOMOV <> 1) '||
                                  'left outer join vw_vrh_emp_tcolcon_vinc vd on (vd.bdcodemp = RESC.bdcodemp) and (vd.bdcodcol = RESC.bdcodcol) '||
                                  'left outer join vrh_base_tclasse cla on (cla.bdcodcla = vd.bdcodcla) '||
                                  'where (RESC.BDCODEMP = X.BDCODEMP) and (RESC.BDCODCOL = X.BDCODCOL) '||
                                    'and ((RESC.BDREFRESCISAO < '||prref||') '||
                                      'or ((RESC.BDREFRESCISAO = '||prref||') and (cla.bdgrupocla <> 5)))) ' ||
                  ' and not exists(select SIT.BDCODEMP, SIT.BDCODCOL '||
                                  'from VRH_EMP_TSITCOL SIT '||
                                  'join VRH_BASE_TPREPSIT PSIT on (PSIT.BDCODSIT = SIT.BDCODSIT) '||
                                  'where (SIT.BDCODEMP = X.BDCODEMP) and (SIT.BDCODCOL = X.BDCODCOL) '||
                                    'and (SIT.BDCODVER is not null) '||
                                    'and (((EXTRACT(YEAR FROM SIT.BDDATAINISIT) * 100) + EXTRACT(MONTH FROM SIT.BDDATAINISIT)) <= '||prref||') '||
                                    'and ((SIT.BDDATAFIMSIT is null) '||
                                      'or (((EXTRACT(YEAR FROM SIT.BDDATAFIMSIT) * 100) + EXTRACT(MONTH FROM SIT.BDDATAFIMSIT)) >= '||prref||'))) ';
  ELSE
  -- Afastados o mês inteiro
  IF (prsitcol = 7) THEN
     wfiltrosit = ' and exists(select SIT.BDCODEMP, SIT.BDCODCOL '||
                              'from VRH_EMP_TSITCOL SIT '||
                              'join VRH_BASE_TPREPSIT PSIT on (PSIT.BDCODSIT = SIT.BDCODSIT) '||
                              'where (SIT.BDCODEMP = X.BDCODEMP) and (SIT.BDCODCOL = X.BDCODCOL) '||
                                'and (SIT.BDCODVER is not null) '||
                                'and (((EXTRACT(YEAR FROM SIT.BDDATAINISIT) * 100) + EXTRACT(MONTH FROM SIT.BDDATAINISIT)) <= '||prref||') '||
                                'and ((SIT.BDDATAFIMSIT is null) '||
                                  'or (((EXTRACT(YEAR FROM SIT.BDDATAFIMSIT) * 100) + EXTRACT(MONTH FROM SIT.BDDATAFIMSIT)) >= '||prref||'))) ';
  ELSE
     wfiltrosit = '';

  /* SQL RETORNO */

  wSql = '';
  wSql = wSql||'select ';
  wSql = wSql||'  FOL.BDCODEMP, ';
  wSql = wSql||'  FOL.BDCODCOL, ';
  wSql = wSql||'  FOL.BDCODVER, ';
  wSql = wSql||'  FOL.BDREFFN, ';
  wSql = wSql||'  FOL.BDREFFC, ';
  wSql = wSql||'  FOL.BDREFVFN_SUM, ';
  wSql = wSql||'  FOL.BDREFVFN_MAX, ';
  wSql = wSql||'  FOL.BDREFAUXVFN_SUM, ';
  wSql = wSql||'  FOL.BDREFAUXVFN_MAX, ';
  wSql = wSql||'  FOL.BDVALVFN, ';
  wSql = wSql||'  FOL.BDREFFC as BDDATAFN, ';
  wSql = wSql||'  FOLB.BDSALBASE, ';
  wSql = wSql||'  FOLB.BDBINSS, ';
  wSql = wSql||'  FOLB.BDBFGTS, ';
  wSql = wSql||'  FOLB.BDFGTS, ';
  wSql = wSql||'  FOLB.BDBIRRF, ';
  wSql = wSql||'  EMP.BDCNPJEMP, ';
  wSql = wSql||'  VERB.BDDESCVER, ';
  wSql = wSql||'  VERB.BDDESCREDVER, ';
  wSql = wSql||'  VERB.BDORDEMVER, ';
  wSql = wSql||'  COLCAD.BDNOMCOL, ';
  wSql = wSql||'  COL.BDDATAADMCOL, ';
  wSql = wSql||'  DOCREF.BDPISCOL, ';
  wSql = wSql||'  COLDOC.BDCPFCOL, ';
  wSql = wSql||'  DOCREF.BDRGCOL, ';
  wSql = wSql||'  VERR.BDTIPOCODVER, ';
  wSql = wSql||'  case when VERR.BDTIPOCODVER = 1 then 2 when VERR.BDTIPOCODVER = 2 then 1 else coalesce(VERR.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, ';
  wSql = wSql||'  VERR.BDTIPOREFVER, ';
  wSql = wSql||'  COLBANCO.BDCODBAN, ';
  wSql = wSql||'  COLBANCO.BDCODAG, ';
  wSql = wSql||'  COLBANCO.BDCTADEPCOL, ';
  wSql = wSql||'  COLBANCO.BDDIGCTADEPCOL, ';
  wSql = wSql||'  COLBANCO.BDMODOPAGTOCOL, ';
  wSql = wSql||'  VERB.BDCLAVER, ';
  wSql = wSql||'  FOL.BDCODCENTRO, ';
  wSql = wSql||'  FOL.BDCODTPCC, ';
  wSql = wSql||'  coalesce(COLCAD.BDEMAILCOL, '''') BDEMAIL1, ';
  wSql = wSql||'  coalesce(COLCAD.BDEMAIL2COL, '''') BDEMAIL2, ';
  wSql = wSql||'  DOCREF.BDCTPSCOL, ';
  wSql = wSql||'  DOCREF.BDSERIECTPSCOL, ';
  wSql = wSql||'  DOCREF.BDDSERIECTPSCOL, ';
  wSql = wSql||'  FOLB.BDVERCALCRRA, FOLB.BDBASETOTAL, FOL.BDORDEM ';

  /* VERBAS FOLHA COMPLEMENTAR */
  wSql = wSql||'from (select ';
  IF (prcodtpcc <> '') THEN
     wSql = wSql||'first 0 ';

  wSql = wSql||'          X.BDCODEMP, ';
  wSql = wSql||'          X.BDCODCOL, ';
  wSql = wSql||'          X.BDREFFN, ';
  wSql = wSql||'          X.BDREFFC, ';
  wSql = wSql||'          X.BDREFCOMP, ';
  wSql = wSql||'          X.BDCODVER, ';
  wSql = wSql||'          X.BDREFVFC as BDREFVFN_SUM, ';
  wSql = wSql||'          X.BDREFVFC as BDREFVFN_MAX, ';
  wSql = wSql||'          X.BDREFAUXVFC as BDREFAUXVFN_SUM, ';
  wSql = wSql||'          X.BDREFAUXVFC as BDREFAUXVFN_MAX, ';
  wSql = wSql||'          X.BDVALVFC as BDVALVFN, ';
  wSql = wSql||'          0 as BDCODCENTRO, ';
  wSql = wSql||'          0 as BDCODTPCC, 0 BDORDEM ';
  wSql = wSql||'      from VRHF_EMP_TVERBAFC X ';

  IF (prsitcol = 2) THEN
     wSql = wSql||'      join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = X.BDCODEMP) and (COL.BDCODCOL = X.BDCODCOL) and (((EXTRACT(YEAR FROM COL.BDDATAADMCOL) * 100) + EXTRACT(MONTH FROM COL.BDDATAADMCOL)) = '||prref||')';

  wSql = wSql||'      where '||wfiltrofn||wfiltrosit;

  /* VERBAS FOLHA COMPLEMENTAR POR TOMADOR */
  wSql = wSql||'      UNION ';
       wSql = wSql||'      select ';
       wSql = wSql||'          X.BDCODEMP, ';
       wSql = wSql||'          X.BDCODCOL, ';
       wSql = wSql||'          X.BDREFTOMADOR, ';
       wSql = wSql||'          X.BDREFFC, ';
       wSql = wSql||'          X.BDREFCOMP, ';
       wSql = wSql||'          X.BDCODVER, ';
       wSql = wSql||'          sum(X.BDREFVFC) as BDREFVFN_SUM, ';
       wSql = wSql||'          max(X.BDREFVFC) as BDREFVFN_MAX, ';
       wSql = wSql||'          sum(X.BDREFAUXVFC) as BDREFAUXVFN_SUM, ';
       wSql = wSql||'          max(X.BDREFAUXVFC) as BDREFAUXVFN_MAX, ';
       wSql = wSql||'          sum(X.BDVALVFC) as BDVALVFN, ';

  IF (prcodtpcc <> '') THEN
     BEGIN
       wSql = wSql||'          Y.BDCODCENTRO, ';
       wSql = wSql||'          Y.BDCODTPCC, MAX(X.BDORDEM) ';
     END
  ELSE
     BEGIN
       wSql = wSql||'          0 BDCODCENTRO, ';
       wSql = wSql||'          0 BDCODTPCC, 0 BDORDEM ';
     END

  wSql = wSql||'      from VRHF_EMP_TVERBAFCTOMADOR X ';

  IF (prcodtpcc <> '') THEN
     wSql = wSql||'      join VRHF_EMP_TPREPFN Y on (Y.BDCODEMP = X.BDCODEMP) and (Y.BDCODCOL = X.BDCODCOL) and (Y.BDORDEM = X.BDORDEM) ';

       IF (prsitcol = 2) THEN
     wSql = wSql||'      join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = X.BDCODEMP) and (COL.BDCODCOL = X.BDCODCOL) and (((EXTRACT(YEAR FROM COL.BDDATAADMCOL) * 100) + EXTRACT(MONTH FROM COL.BDDATAADMCOL)) = '||prref||')';

  wSql = wSql||'      where '||wfiltroft||wfiltrosit;
  wSql = wSql||'      group by X.BDCODEMP, X.BDCODCOL, X.BDREFTOMADOR, X.BDREFFC, X.BDREFCOMP, X.BDCODVER';

  IF (prcodtpcc <> '') THEN
     wSql = wSql||', Y.BDCODCENTRO, BDCODTPCC';

  wSql = wSql||') FOL ';

  -- Pagamento em folha normal
  IF (PRVINCFN = 0) THEN
     BEGIN
       wfiltrofn = wfiltrofn||' and (COALESCE(X.BDREFVINCFN,0) = 0) ';
       wfiltroft = wfiltroft||' and (COALESCE(X.BDREFVINCFN,0) = 0) ';
     END
--       ELSE
--  IF (PRVINCFN = 1) THEN
--     BEGIN
--       wfiltrofn = wfiltrofn||' and (COALESCE(X.BDREFVINCFN,0) <> 0) ';
--       wfiltroft = wfiltroft||' and (COALESCE(X.BDREFVINCFN,0) <> 0) ';
--     END

  wSql = wSQL||'INNER JOIN ';
  /* FOLHA COMPLEMENTAR */
  wSql = wSql||'     (select ';
       wSql = wSql||'          X.BDCODEMP, ';
       wSql = wSql||'          X.BDCODCOL, ';
  wSql = wSql||'          X.BDREFFN, ';
       wSql = wSql||'          X.BDREFFC, ';
       wSql = wSql||'          X.BDREFCOMP, ';
  wSql = wSql||'          X.BDBFGTSFC + X.BDBFGTS13FC as BDBFGTS, ';
  wSql = wSql||'          X.BDFGTSFC + X.BDFGTS13FC as BDFGTS, ';
  wSql = wSql||'          X.BDBINSSFC + X.BDBINSS13FC as BDBINSS, ';
  wSql = wSql||'          X.BDBIRRFFC + X.BDBIRRF13FC as BDBIRRF, ';
  wSql = wSql||'          X.BDSALBASEFC as BDSALBASE, ';
  wSql = wSql||'          X.BDDATAPAGFC, ';
  wSql = wSql||'          0 BDCODCENTRO, ';
  wSql = wSql||'          0 BDCODTPCC, ';
  wSql = wSql||'          BDVERCALCRRA, BDBASETOTAL, 0 BDORDEM ';
  wSql = wSql||'      from VRHF_EMP_TFOLHACOMP X ';
  wSql = wSql||'      where '||wfiltrofn;

  /* FOLHA COMPLEMENTAR TOMADOR */
  wSql = wSql||'      UNION ';
       wSql = wSql||'      select ';
       wSql = wSql||'          X.BDCODEMP, ';
       wSql = wSql||'          X.BDCODCOL, ';
       wSql = wSql||'          X.BDREFTOMADOR, ';
       wSql = wSql||'          X.BDREFFC, ';
       wSql = wSql||'          X.BDREFCOMP, ';
       wSql = wSql||'          SUM(X.BDBFGTSFC + X.BDBFGTS13FC), ';
       wSql = wSql||'          SUM(X.BDFGTSFC + X.BDFGTS13FC), ';
       wSql = wSql||'          SUM(X.BDBINSSFC + X.BDBINSS13FC), ';
       wSql = wSql||'          SUM(X.BDBIRRFFC + X.BDBIRRF13FC), ';
       wSql = wSql||'          MAX(X.BDSALBASEFC), ';
       wSql = wSql||'          X.BDDATAPAGFC, ';

  IF (prcodtpcc <> '') THEN
     BEGIN
       wSql = wSql||'          Y.BDCODCENTRO, ';
       wSql = wSql||'          Y.BDCODTPCC ';
     END
  ELSE
     BEGIN
       wSql = wSql||'          0 BDCODCENTRO, ';
       wSql = wSql||'          0 BDCODTPCC ';
     END

  wSql = wSql||'      ,MAX(BDVERCALCRRA) BDVERCALCRRA, MAX(BDBASETOTAL) BDBASETOTAL, MAX(X.BDORDEM) ';

  wSql = wSql||'      from VRHF_EMP_TFOLTOMCOMP X ';

  IF (prcodtpcc <> '') THEN
     wSql = wSql||'      join VRHF_EMP_TPREPFN Y on (Y.BDCODEMP = X.BDCODEMP) and (Y.BDCODCOL = X.BDCODCOL) and (Y.BDORDEM = X.BDORDEM) ';

  wSql = wSql||'      where '||wfiltroft;

       wSql = wSql||'      group by ';
       wSql = wSql||'          X.BDCODEMP, ';
       wSql = wSql||'          X.BDCODCOL, ';
       wSql = wSql||'          X.BDREFTOMADOR, ';
       wSql = wSql||'          X.BDREFFC, ';
       wSql = wSql||'          X.BDREFCOMP, ';
  wSql = wSql||'          X.BDDATAPAGFC';

  IF (prcodtpcc <> '') THEN
     wSql = wSql||', Y.BDCODCENTRO, Y.BDCODTPCC';

  wSql = wSql||'     ) FOLB ON (FOL.BDCODEMP = FOLB.BDCODEMP) and (FOL.BDCODCOL = FOLB.BDCODCOL) and (FOL.BDREFFN = FOLB.BDREFFN) and (FOL.BDREFFC = FOLB.BDREFFC)';

  /* JOIN DE CAMPOS RETORNADOS */
  IF (COALESCE(PRCODCLA,'') <> '') THEN
     wSql = wSql||' INNER JOIN VRH_EMP_TCOLCON_VINC COLCON_VIN ON (COLCON_VIN.BDCODEMP = FOL.BDCODEMP) and (COLCON_VIN.BDCODCOL = FOL.BDCODCOL) and ('||:PRCODCLA||') '||
                     'and (COLCON_VIN.BDREFCOL = (select coalesce((select max(d2.BDREFCOL) from VRH_EMP_TCOLCON_VINC d2 where (d2.BDCODEMP = FOL.BDCODEMP) and (d2.BDCODCOL = FOL.BDCODCOL) and (d2.bdrefcol <= (select TRIM(rdb$get_context(''USER_SESSION'', ''W_ANOMES'')) from rdb$database))), '||
                                                                 '(select min(d1.BDREFCOL) from VRH_EMP_TCOLCON_VINC d1 where (d1.bdcodemp = FOL.BDCODEMP) and (d1.bdcodcol = FOL.BDCODCOL))) as bdREF '||
                                                 'from RDB$DATABASE)) ';

  wSql = wSql||' inner join TEMPRESAS EMP on (FOL.BDCODEMP = EMP.BDCODEMP)';
  wSql = wSql||' inner join VRH_BASE_TVERBAS VERB on (FOL.BDCODVER = VERB.BDCODVER)';
  wSql = wSql||' inner join VRH_EMP_TCOLCON COL on (FOL.BDCODEMP = COL.BDCODEMP) and (FOL.BDCODCOL = COL.BDCODCOL)';
  wSql = wSql||' left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (FOL.BDCODEMP = COLCAD.BDCODEMP) and (FOL.BDCODCOL = COLCAD.BDCODCOL)';
  wSql = wSql||' inner join VRH_EMP_TCOLCON_DOCREF DOCREF on (FOL.BDCODEMP = DOCREF.BDCODEMP) and (FOL.BDCODCOL = DOCREF.BDCODCOL) '||
                  'and (DOCREF.BDREFCOL = (select coalesce((select max(D2.BDREFCOL) from VRH_EMP_TCOLCON_DOCREF D2 where (D2.BDCODEMP = FOL.BDCODEMP) and (D2.BDCODCOL = FOL.BDCODCOL) and (D2.BDREFCOL <= (select trim(RDB$GET_CONTEXT(''USER_SESSION'', ''W_ANOMES'')) from RDB$DATABASE))), '||
                                                          '(select min(D1.BDREFCOL) from VRH_EMP_TCOLCON_DOCREF D1 where (D1.BDCODEMP = FOL.BDCODEMP) and (D1.BDCODCOL = FOL.BDCODCOL))) as BDREF '||
                                                                                                                                          'from RDB$DATABASE))';
  wSql = wSql||' inner join VRH_EMP_TCOLCON_DOC COLDOC on (FOL.BDCODEMP = COLDOC.BDCODEMP) and (FOL.BDCODCOL = COLDOC.BDCODCOL)';
  wSql = wSql||' inner join VRH_BASE_TVERBAS_REF VERR on (FOL.BDCODVER = VERR.BDCODVER) and (VERB.BDCODVER = VERR.BDCODVER) '||
                  'and (VERR.BDREFVER = (select coalesce((select max(D2.BDREFVER) from VRH_BASE_TVERBAS_REF D2 where (D2.BDCODVER = FOL.BDCODVER) and (D2.BDREFVER <= (select trim(RDB$GET_CONTEXT(''USER_SESSION'', ''W_ANOMES'')) from RDB$DATABASE))), '||
                                                        '(select min(D1.BDREFVER) from VRH_BASE_TVERBAS_REF D1 where (D1.BDCODVER = FOL.BDCODVER))) as BDREF '||
                                                                                                                                 'from RDB$DATABASE))';
  wSql = wSql||' inner join VRHF_EMP_TCOLCON_BANCO COLBANCO on (FOL.BDCODEMP = COLBANCO.BDCODEMP) and (FOL.BDCODCOL = COLBANCO.BDCODCOL) '||
                 'and (COLBANCO.BDREFCOL = (select coalesce((select max(D2.BDREFCOL) from VRHF_EMP_TCOLCON_BANCO D2 where (D2.BDCODEMP = FOL.BDCODEMP) and (D2.BDCODCOL = FOL.BDCODCOL) and (D2.BDREFCOL <= (select trim(RDB$GET_CONTEXT(''USER_SESSION'', ''W_ANOMES'')) from RDB$DATABASE))), '||
                                                           '(select min(D1.BDREFCOL) from VRHF_EMP_TCOLCON_BANCO D1 where (D1.BDCODEMP = FOL.BDCODEMP) and (D1.BDCODCOL = FOL.BDCODCOL))) as BDREFCOL '||
                                                                                                                                                  'from RDB$DATABASE))';
  FOR EXECUTE STATEMENT wSql
    INTO :BDCODEMP,
         :BDCODCOL,
         :BDCODVER,
         :BDREFFN,
         :BDREFFC,
         :BDREFVFN_SUM,
         :BDREFVFN_MAX,
         :BDREFAUXVFN_SUM,
         :BDREFAUXVFN_MAX,
         :BDVALVFN,
         :BDDATAFN,
         :BDSALBASE,
         :BDBINSS,
         :BDBFGTS,
         :BDFGTS,
         :BDBIRRF,
         :BDCNPJEMP,
         :BDDESCVER,
         :BDDESCREDVER,
         :BDORDEMVER,
         :BDNOMCOL,
         :BDDATAADMCOL,
         :BDPISCOL,
         :BDCPFCOL,
         :BDRG,
         :BDTIPOCODVER,
         :BDORDEMTIPOCODVER,
         :BDTIPOREFVER,
         :BDCODBAN,
         :BDCODAG,
         :BDCTADEPCOL,
         :BDDIGCTADEPCOL,
         :BDMODOPAGTOCOL,
         :BDCLAVER,
         :BDCODCENTRO,
         :BDCODTPCC,
         :wemail1,
         :wemail2,
         :BDCTPSCOL,
         :BDSERIECTPSCOL,
         :BDDSERIECTPSCOL,
         :BDVERCALCRRA,
         :BDBASETOTAL,
         :BDORDEM
  DO
  BEGIN
    wemail1 = REPLACE(wemail1, ';', ',');
    wemail1 = REPLACE(wemail1, ' ', ',');

    wemail2 = REPLACE(wemail2, ';', ',');
    wemail2 = REPLACE(wemail2, ' ', ',');

    BDEMAILCOL = '';

    if (TRIM(wemail1) <> '') then
       begin
         BDEMAILCOL = TRIM(wemail1);

         if (TRIM(wemail2) <> '') then
            BDEMAILCOL = BDEMAILCOL||','||TRIM(wemail2);
       end
    else
    if (TRIM(wemail2) <> '') then
       BDEMAILCOL = TRIM(wemail2);

    /*  Sol.152518 Leonardo Schwab 15/07/2021
        Adicionado campo para controlar quantos salários tem o horista especial,
        caso tenha mais de um não irá aparecer o salário base no recibo de salário.
    */
    SELECT COUNT(*)
    FROM (select BDCODEMP, BDCODCOL, BDCODSHE, max(BDDATASHE) BDDATASHE
          from VRH_EMP_TCOL_SHE
    WHERE BDCODEMP = :BDCODEMP AND
          BDCODCOL = :BDCODCOL AND
                BDREFSHE <= :BDREFFN
          group by BDCODEMP, BDCODCOL, BDCODSHE
    )
    INTO :BDQTDSALARIOHE;

    SUSPEND;
  END
END^

/* Restore proc. body: VRH_SP_REL_RECIBO_FOLHA_AVULSA */
create or alter procedure VRH_SP_REL_RECIBO_FOLHA_AVULSA (
    PRCODEMP integer,
    PRCODTCA varchar(20000),
    PRDATAINI varchar(10),
    PRDATAFIM varchar(10),
    PRCODCLA varchar(10000),
    PRCODTPCC varchar(10000) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODTCA integer,
    BDCODVER integer,
    BDREFFN integer,
    BDDATA date,
    BDREFVAD numeric(15,6),
    BDREFAUXVAD numeric(15,6),
    BDVALVAD numeric(15,6),
    BDDATAFN date,
    BDBINSS numeric(15,2),
    BDBFGTS numeric(15,2),
    BDFGTS numeric(15,2),
    BDBIRRF numeric(15,6),
    BDCNPJEMP varchar(18),
    BDDESCVER varchar(40),
    BDDESCREDVER varchar(20),
    BDORDEMVER integer,
    BDNOMCOL varchar(70),
    BDDATAADMCOL date,
    BDPISCOL varchar(14),
    BDCPFCOL varchar(14),
    BDRG varchar(13),
    BDTIPOCODVER integer,
    BDORDEMTIPOCODVER integer,
    BDTIPOREFVER integer,
    BDCODBAN integer,
    BDCODAG integer,
    BDCTADEPCOL varchar(15),
    BDDIGCTADEPCOL varchar(2),
    BDMODOPAGTOCOL integer,
    BDSALBASE numeric(15,6),
    BDDESCTCA varchar(50),
    BDCLAVER varchar(20),
    BDEMAILCOL varchar(400),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDQTDSALARIOHE integer)
as
declare variable WSQL varchar(10000);
declare variable WEMAIL1 varchar(200);
declare variable WEMAIL2 varchar(200);
BEGIN

  wSql = '';
  wSql = wSql||'select ';
  wSql = wSql||'  FOL.BDCODEMP, ';
  wSql = wSql||'  FOL.BDCODCOL, ';
  wSql = wSql||'  FOL.BDCODTCA, ';
  wSql = wSql||'  FOL.BDCODVER, ';
  /* SOL.190746 - 21/11/2023 - Nathan de Faria - Foi removido o campo FOL.BDCODTCA POIS QUANDO EXISTIA TIPOS DE FOLHAS COM CÓDIGO SUPERIOR A 3 CARACTERES ESTOURAVA ERRO, PELO OQUE FOI IDENTIFICADO NÃO HAVIA NECESSIDADE DE CONCATENAR ESSE CAMPO COM A REFERÊNCIA
  wSql = wSql||'  CAST((FOL.BDCODTCA||SUBSTRING(CAST(FOL.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FOL.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)||SUBSTRING(CAST(FOL.BDDATAFA AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER), ';
  */
  wSql = wSql||'  CAST((SUBSTRING(CAST(FOL.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FOL.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)||SUBSTRING(CAST(FOL.BDDATAFA AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER), ';
  wSql = wSql||'  FOL.BDDATAFA, ';
  wSql = wSql||'  FOL.BDREFVFA, ';
  wSql = wSql||'  FOL.BDREFAUXVFA, ';
  wSql = wSql||'  FOL.BDVALVFA, ';
  wSql = wSql||'  FOL.BDDATAFA, ';
  wSql = wSql||'  coalesce(FOLB.BDBINSSFA, 0) + coalesce(FOLB.BDBINSS13FA, 0) + coalesce(FOLB.BDBINSSFEFOLFA, 0),';
  wSql = wSql||'  coalesce(FOLB.BDBFGTSFA, 0) + coalesce(FOLB.BDBFGTS13FA, 0) + coalesce(FOLB.BDBFGTSFEFA, 0), ';
  wSql = wSql||'  coalesce(FOLB.BDFGTSFA, 0) + coalesce(FOLB.BDFGTS13FA, 0) + coalesce(FOLB.BDFGTSFEFA, 0), ';
  wSql = wSql||'  coalesce(FOLB.BDBIRRFFA, 0) + coalesce(FOLB.BDBIRRF13FA, 0) + coalesce(FOLB.BDDIRRFFA, 0), ';
  wSql = wSql||'  EMP.BDCNPJEMP, ';
  wSql = wSql||'  VERB.BDDESCVER, ';
  wSql = wSql||'  VERB.BDDESCREDVER, ';
  wSql = wSql||'  VERB.BDORDEMVER, ';
  wSql = wSql||'  COLCAD.BDNOMCOL, ';
  wSql = wSql||'  COL.BDDATAADMCOL, ';
  wSql = wSql||'  DOCREF.BDPISCOL, ';
  wSql = wSql||'  COLDOC.BDCPFCOL, ';
  wSql = wSql||'  DOCREF.BDRGCOL, ';
  wSql = wSql||'  VERR.BDTIPOCODVER, ';
  wSql = wSql||'  case when VERR.BDTIPOCODVER = 1 then 2 when VERR.BDTIPOCODVER = 2 then 1 else coalesce(VERR.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, ';
  wSql = wSql||'  VERR.BDTIPOREFVER, ';
  wSql = wSql||'  COLBANCO.BDCODBAN, ';
  wSql = wSql||'  COLBANCO.BDCODAG, ';
  wSql = wSql||'  COLBANCO.BDCTADEPCOL, ';
  wSql = wSql||'  COLBANCO.BDDIGCTADEPCOL, ';
  wSql = wSql||'  COLBANCO.BDMODOPAGTOCOL, ';
  wSql = wSql||'  COLDIA.BDSALBASECOL, ';
  wSql = wSql||'  TCA.BDDESCTCA, ';
  wSql = wSql||'  VERB.BDCLAVER, ';
  wSql = wSql||'  coalesce(COLCAD.BDEMAILCOL, '''') BDEMAIL1, ';
  wSql = wSql||'  coalesce(COLCAD.BDEMAIL2COL, '''') BDEMAIL2, ';
  wSql = wSql||'  DOCREF.BDCTPSCOL, ';
  wSql = wSql||'  DOCREF.BDSERIECTPSCOL, ';
  wSql = wSql||'  DOCREF.BDDSERIECTPSCOL ';
    
  wSql = wSql||'from VRHF_EMP_TVERBAFA FOL ';

  wSql = wSql||'join VRHF_EMP_TFOLHAAVULSA FOLB on (FOLB.BDCODEMP = FOL.BDCODEMP and FOLB.BDCODCOL = FOL.BDCODCOL and FOLB.BDDATAFA = FOL.BDDATAFA and FOLB.BDCODTCA = FOL.BDCODTCA) ';

  -- alt:15921 - 19/10/2016 - novo campo filtro por centro de custo - Marcelo B. M.
  IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
     BEGIN
       wsql = wsql||'join (select BDCODEMP, BDCODCOL, BDCODCENTRO, BDCODTPCC '||
              'from VRHF_SP_TPREPFN_REF('||SUBSTRING(prdatafim FROM 7 FOR 4)||SUBSTRING(prdatafim FROM 1 FOR 2)||
              ','''||'COLCON.BDCODEMP = '||prcodemp||''',null,'''||prdataini||''','''||prdatafim||''',''TRUE'')'|| --Sol:232973 - Davi - 10/12/2025 - Permitindo busca de demitidos
              ' where '||prcodtpcc||' ) H on (H.BDCODEMP = FOL.BDCODEMP and H.BDCODCOL = FOL.BDCODCOL) ';
     END

  IF (prCODCLA IS NOT NULL AND prCODCLA <> '') THEN
     begin
       wSql = wSql||'left outer join (select * from VW_VRH_EMP_TCOLCON_VINC '||
                          'where '||prcodcla||'';

       IF (PRCODEMP > 0) THEN
          wSql = wSql||' and BDCODEMP = '||prcodemp;

       wSql = wSql||') COLCON_VIN on (COLCON_VIN.BDCODEMP = FOL.BDCODEMP and COLCON_VIN.BDCODCOL = FOL.BDCODCOL) ';
     end

  wSql = wSql||'join TEMPRESAS EMP on (EMP.BDCODEMP = FOL.BDCODEMP) ';
  wSql = wSql||'join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = FOL.BDCODVER) ';
  wSql = wSql||'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FOL.BDCODEMP and DOCREF.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'join VRH_EMP_TCOLCON_DOC COLDOC on (COLDOC.BDCODEMP = FOL.BDCODEMP and COLDOC.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'left outer join VW_VRH_BASE_TVERBAS_REF VERR on (VERR.BDCODVER = FOL.BDCODVER) ';
  wSql = wSql||'left outer join VW_VRHF_EMP_TCOLCON_BANCO COLBANCO on (COLBANCO.BDCODEMP = FOL.BDCODEMP and COLBANCO.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'left outer join VW_VRH_EMP_TCOLCON_CALCDIA COLDIA on (COLDIA.BDCODEMP = FOL.BDCODEMP and COLDIA.BDCODCOL = FOL.BDCODCOL) ';
  wSql = wSql||'join VRH_BASE_TTIPOCALCAVUL TCA on (TCA.BDCODTCA = FOL.BDCODTCA) ';
  wSql = wSql||'where FOL.BDDATAFA between '''||:PRDATAINI||''' and '''||:PRDATAFIM||'''';


  IF (PRCODEMP > 0) THEN
     wSql = wSql||' and FOL.BDCODEMP = '||:PRCODEMP;

  IF (prCODCLA IS NOT NULL AND prCODCLA <> '') THEN
     wSql = wSql||' and COLCON_VIN.BDCODCLA is not null';

  IF (PRCODTCA IS NOT NULL AND PRCODTCA <> '') THEN
     wsql = wsql||' and '||prcodtca;

  FOR EXECUTE STATEMENT wSql
    INTO :BDCODEMP,
         :BDCODCOL,
         :BDCODTCA,
         :BDCODVER,
         :BDREFFN,
         :BDDATA,
         :BDREFVAD,
         :BDREFAUXVAD,
         :BDVALVAD,
         :BDDATAFN,
         :BDBINSS,
         :BDBFGTS,
         :BDFGTS,
         :BDBIRRF,
         :BDCNPJEMP,
         :BDDESCVER,
         :BDDESCREDVER,
         :BDORDEMVER,
         :BDNOMCOL,
         :BDDATAADMCOL,
         :BDPISCOL,
         :BDCPFCOL,
         :BDRG,
         :BDTIPOCODVER,
         :BDORDEMTIPOCODVER,
         :BDTIPOREFVER,
         :BDCODBAN,
         :BDCODAG,
         :BDCTADEPCOL,
         :BDDIGCTADEPCOL,
         :BDMODOPAGTOCOL,
         :BDSALBASE,
         :BDDESCTCA,
         :BDCLAVER,
         :wemail1, 
         :wemail2,
         :BDCTPSCOL,
         :BDSERIECTPSCOL,
         :BDDSERIECTPSCOL
  DO
  BEGIN
    wemail1 = REPLACE(wemail1, ';', ',');
    wemail1 = REPLACE(wemail1, ' ', ',');

    wemail2 = REPLACE(wemail2, ';', ',');
    wemail2 = REPLACE(wemail2, ' ', ',');

    BDEMAILCOL = '';

    if (TRIM(wemail1) <> '') then
       begin
         BDEMAILCOL = TRIM(wemail1);

         if (TRIM(wemail2) <> '') then
            BDEMAILCOL = BDEMAILCOL||','||TRIM(wemail2);
       end
    else
    if (TRIM(wemail2) <> '') then
       BDEMAILCOL = TRIM(wemail2);

    /*  Sol.152518 Leonardo Schwab 15/07/2021
        Adicionado campo para controlar quantos salários tem o horista especial,
        caso tenha mais de um não irá aparecer o salário base no recibo de salário.
    */
    SELECT COUNT(*)
    FROM (select BDCODEMP, BDCODCOL, BDCODSHE, max(BDDATASHE) BDDATASHE
          from VRH_EMP_TCOL_SHE
    WHERE BDCODEMP = :BDCODEMP AND
          BDCODCOL = :BDCODCOL AND
                BDREFSHE <= :BDREFFN
          group by BDCODEMP, BDCODCOL, BDCODSHE
    )
    INTO :BDQTDSALARIOHE;

    SUSPEND;
  END
END^

/* Restore proc. body: SP_VRHF_UNION_FT_MES */
create or alter procedure SP_VRHF_UNION_FT_MES (
    PRCODEMP integer,
    PRANOMES integer,
    PRFILTROCC varchar(20000) = null /* COLLATE WIN1252 - default */ )
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFTOMADOR integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCODVER integer,
    BDREFVFN_SUM numeric(15,6),
    BDREFAUXVFN_SUM numeric(15,6),
    BDREFVFN_MAX numeric(15,6),
    BDREFAUXVFN_MAX numeric(15,6),
    BDVALVFT numeric(15,6),
    BDORDEM integer)
as
declare variable WSQL varchar(32700);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WVERATU integer;
declare variable WCODCENTROANT integer;
declare variable WCODTPCCATU integer;
declare variable WHOREMP DM_BOOLEAN;
declare variable WTIPOREFVER integer;
declare variable WCODCENTRO integer;
declare variable WCODTPCC integer;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREFFN integer;
declare variable WCODVER integer;
declare variable WREFVSUM numeric(15,6);
declare variable WREFAUXVSUM numeric(15,6);
declare variable WREFVMAX numeric(15,6);
declare variable WREFAUXVMAX numeric(15,6);
declare variable WVALV numeric(15,6);
declare variable WREFVSUMANT numeric(15,6);
declare variable WREFAUXVSUMANT numeric(15,6);
declare variable WVALVANT numeric(15,6);
declare variable WFRACAO numeric(15,6);
declare variable WORDEM integer;
declare variable WORDEMATU integer;
BEGIN
  wsql = 'select * from ('||
         'SELECT '||
           'FN.BDCODEMP, '||
           'FN.BDCODCOL, '||
           'FN.BDREFTOMADOR, ';

  IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
    wsql = wsql||
           'Y.BDCODCENTRO, '||
           'COALESCE(Y.BDCODTPCC,0) BDCODTPCC, ';
  ELSE
    wsql = wsql||
           '0 BDCODCENTRO, '||
           '0 BDCODTPCC, ';

  wsql = wsql||
           'FN.BDCODVER, '||
           'FN.BDREFVFT, '||
           'FN.BDREFAUXVFT, '||
           'FN.BDVALVFT, '||
           'EMPCALC.BDREFHOREMP, '||
           'VERREF.BDTIPOREFVER, FN.BDORDEM '||
         'FROM '||
           'VRHF_EMP_TVERBATOMADOR FN '||
         'left outer join VW_VRHF_BASE_TEMPCALC EMPCALC on (EMPCALC.BDCODEMP = FN.BDCODEMP) '||
         'left outer join VW_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';

  IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
    wsql = wsql||
         'left outer join VRHF_EMP_TPREPFN Y on (Y.BDCODEMP = FN.BDCODEMP and Y.BDCODCOL = FN.BDCODCOL and Y.BDORDEM = FN.BDORDEM) ';

  wsql = wsql||
         'where FN.BDREFTOMADOR = '||pranomes;

  IF (prcodemp IS NOT NULL AND prcodemp <> 0) THEN
     BEGIN
       wsql = wsql||' and FN.BDCODEMP = '||prcodemp;
     END

  IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
     wsql = wsql||' and '||:prfiltrocc;

  wsql = wsql||') order by BDCODEMP, BDCODCOL, BDREFTOMADOR, BDCODTPCC, BDCODVER ';

  wempatu     = 0;
  wcolatu     = 0;
  wrefatu     = 0;
  wveratu     = 0;
  wcodtpccatu = -1;
  wrefvsum    = 0;
  wrefauxvsum = 0;
  wrefvmax    = 0;
  wrefauxvmax = 0;
  wvalv       = 0;
  wordematu   = 0;

  FOR EXECUTE STATEMENT wsql INTO
    :wcodemp,
    :wcodcol,
    :wreffn,
    :wcodcentro,
    :wcodtpcc,
    :wcodver,
    :wrefvsumant,
    :wrefauxvsumant,
    :wvalvant,
    :whoremp,
    :wtiporefver,
    :wordem
  DO
    BEGIN
      IF (wempatu = 0) THEN
         wempatu = wcodemp;

      IF (wcolatu = 0) THEN
         wcolatu = wcodcol;

      IF (wrefatu = 0) THEN
         wrefatu = wreffn;

      IF (wveratu = 0) THEN
         wveratu = wcodver;

      IF (wcodtpccatu = -1) THEN
         wcodtpccatu = wcodtpcc;

      if (wordematu = 0) then
         wordematu = wordem;

      IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wrefatu <> wreffn) OR (wcodtpccatu <> wcodtpcc) OR (wveratu <> wcodver)) THEN
         BEGIN
           BDCODEMP        = wempatu;
           BDCODCOL        = wcolatu;
           BDREFTOMADOR    = wrefatu;
           BDCODCENTRO     = wcodcentroant;
           BDCODTPCC       = wcodtpccatu;
           BDORDEM         = wordematu;
           BDCODVER        = wveratu;
           BDREFVFN_SUM    = wrefvsum;
           BDREFAUXVFN_SUM = wrefauxvsum;
           BDREFVFN_MAX    = wrefvmax;
           BDREFAUXVFN_MAX = wrefauxvmax;
           BDVALVFT        = wvalv;
           SUSPEND;

           wempatu     = wcodemp;
           wcolatu     = wcodcol;
           wrefatu     = wreffn;
           wcodtpccatu = wcodtpcc;
           wordematu   = wordem;
           wveratu     = wcodver;
           wrefvsum    = 0;
           wrefauxvsum = 0;
           wrefvmax    = 0;
           wrefauxvmax = 0;
           wvalv       = 0;
         END

      -- Converte horas e tipo de referência da verba é Horas
      IF (UPPER(whoremp) = 'TRUE' AND wtiporefver = 1 AND wrefvsumant > 0) THEN
         BEGIN
           -- Converte a referencia atual de Horas para Valor
           wfracao      = wrefvsumant - CAST((wrefvsumant - 0.5) AS INTEGER);
           IF (wrefvsumant > 0) THEN
              BEGIN
                wrefvsumant = wrefvsumant - wfracao;
                wfracao     = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                wrefvsumant = wrefvsumant + wfracao;
              END

           -- Converte a soma atual de Horas para Valor
           wfracao  = wrefvsum - CAST((wrefvsum - 0.5) AS INTEGER);
           IF (wrefvsum > 0) THEN
              BEGIN
                wrefvsum = wrefvsum - wfracao;
                wfracao  = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                wrefvsum = wrefvsum + wfracao;
              END

           -- Soma os VALORES
           wrefvsum = wrefvsum +  wrefvsumant;

           -- Converte o resultado novamente em Horas
           wfracao  = wrefvsum - CAST((wrefvsum - 0.5) AS INTEGER);
           IF (wrefvsum > 0) THEN
              BEGIN
                wrefvsum = wrefvsum - wfracao;
                wfracao  = CAST((wfracao / 100 * 60) AS NUMERIC(15,2));
                wrefvsum = wrefvsum + wfracao;
              END
         END
      ELSE
         wrefvsum = wrefvsum + wrefvsumant;

      wrefauxvsum = wrefauxvsum + wrefauxvsumant;

      IF (wrefvmax < wrefvsumant) THEN
         wrefvmax    = wrefvsumant;

      IF (wrefauxvmax < wrefauxvsumant) THEN
         wrefauxvmax = wrefauxvsumant;

      wvalv         = wvalv + wvalvant;
      wcodcentroant = wcodcentro;
    END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wcodtpccatu <> -1 AND wveratu <> 0) THEN
     BEGIN
       BDCODEMP        = wempatu;
       BDCODCOL        = wcolatu;
       BDREFTOMADOR    = wrefatu;
       BDCODCENTRO     = wcodcentroant;
       BDCODTPCC       = wcodtpccatu;
       BDORDEM         = wordematu;
       BDCODVER        = wveratu;
       BDREFVFN_SUM    = wrefvsum;
       BDREFAUXVFN_SUM = wrefauxvsum;
       BDREFVFN_MAX    = wrefvmax;
       BDREFAUXVFN_MAX = wrefauxvmax;
       BDVALVFT        = wvalv;
       SUSPEND;
     END
END^


/* Restore proc. body: VRH_SP_REL_RECIBO_FOLHA_NORMAL */
create or alter procedure VRH_SP_REL_RECIBO_FOLHA_NORMAL (
    PRCODEMP integer,
    PRREF integer,
    PRCODCLA varchar(10000),
    PRCODTPCC varchar(20000) = null /* COLLATE WIN1252 - default */ ,
    PRDATAINI date = null,
    PRDATAFIM date = null,
    PRSEMFERIAS smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFVFN_SUM numeric(15,6),
    BDREFVFN_MAX numeric(15,6),
    BDREFAUXVFN_SUM numeric(15,6),
    BDREFAUXVFN_MAX numeric(15,6),
    BDVALVFN numeric(15,6),
    BDDATAFN integer,
    BDSALBASE numeric(15,6),
    BDBINSS numeric(15,6),
    BDBINSSAP numeric(15,6),
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDCNPJEMP varchar(18),
    BDDESCVER varchar(40),
    BDDESCREDVER varchar(20),
    BDORDEMVER integer,
    BDNOMCOL varchar(70),
    BDDATAADMCOL date,
    BDPISCOL varchar(14),
    BDCPFCOL varchar(14),
    BDRG varchar(13),
    BDTIPOCODVER integer,
    BDORDEMTIPOCODVER integer,
    BDTIPOREFVER integer,
    BDCODBAN integer,
    BDCODAG integer,
    BDCTADEPCOL varchar(15),
    BDDIGCTADEPCOL varchar(2),
    BDMODOPAGTOCOL integer,
    BDCLAVER varchar(20),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDEMAILCOL varchar(400),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDQTDSALARIOHE integer,
    BDORDEM integer,
    BDNIVELORDEM integer,
    BDIMPCOD DM_BOOLEAN)
as
declare variable WSQL varchar(10000);
declare variable WDTI varchar(20);
declare variable WDTF varchar(20);
declare variable WMES varchar(2); /* Para filtrar os somente demitidos no mês */
declare variable WANO varchar(4);
declare variable WULTDIA varchar(2);
declare variable WEMAIL1 varchar(200);
declare variable WEMAIL2 varchar(200);
declare variable WVALFN DM_NUMERIC_15_2;
declare variable WVALAD DM_NUMERIC_15_2;
declare variable WVALFE DM_NUMERIC_15_2;
declare variable WCONTRATO varchar(30);
declare variable WVALPARC DM_NUMERIC_15_2;
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WCOMFERIAS smallint;
declare variable WPARCELAPI integer;
declare variable WVALORVEFN DM_NUMERIC_15_2;
declare variable WVALORVEFE DM_NUMERIC_15_2;
declare variable WVALORVEAD DM_NUMERIC_15_2;
begin
  prsemferias = coalesce(prsemferias, 0);

  if (PRREF is not null) then
    execute procedure SP_SETA_COMPETENCIA(PRREF, null, null);

  WSQL = '';
  WSQL = WSQL || 'select ';
  WSQL = WSQL || '      FOL.BDCODEMP, ';
  WSQL = WSQL || '      FOL.BDCODCOL, ';
  WSQL = WSQL || '      FOL.BDCODVER, ';
  WSQL = WSQL || '      FOL.BDREFFN, ';
  WSQL = WSQL || '      FOL.BDREFVFN_SUM, ';
  WSQL = WSQL || '      FOL.BDREFVFN_MAX, ';
  WSQL = WSQL || '      FOL.BDREFAUXVFN_SUM, ';
  WSQL = WSQL || '      FOL.BDREFAUXVFN_MAX, ';
  WSQL = WSQL || '      FOL.BDVALVFN, ';
  WSQL = WSQL || '      FOL.BDREFFN, ';
  WSQL = WSQL || '      FOLB.BDSALBASE, ';
  WSQL = WSQL || '      FOLB.BDBINSS, ';
  WSQL = WSQL || '      FOLB.BDBINSSAP, ';
  WSQL = WSQL || '      FOLB.BDBFGTS, ';
  WSQL = WSQL || '      FOLB.BDFGTS, ';
  WSQL = WSQL || '      FOLB.BDBIRRF, ';
  WSQL = WSQL || '      EMP.BDCNPJEMP, ';
  WSQL = WSQL || '      VERB.BDDESCVER, ';
  WSQL = WSQL || '      VERB.BDDESCREDVER, ';
  WSQL = WSQL || '      VERB.BDORDEMVER, ';
  WSQL = WSQL || '      COLCAD.BDNOMCOL, ';
  WSQL = WSQL || '      COL.BDDATAADMCOL, ';
  WSQL = WSQL || '      DOCREF.BDPISCOL, ';
  WSQL = WSQL || '      COLDOC.BDCPFCOL, ';
  WSQL = WSQL || '      DOCREF.BDRGCOL, ';
  WSQL = WSQL || '      VERR.BDTIPOCODVER, ';
  WSQL = WSQL || '      case when VERR.BDTIPOCODVER = 1 then 2 when VERR.BDTIPOCODVER = 2 then 1 else coalesce(VERR.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, ';
  WSQL = WSQL || '      VERR.BDTIPOREFVER, ';
  WSQL = WSQL || '      COLBANCO.BDCODBAN, ';
  WSQL = WSQL || '      COLBANCO.BDCODAG, ';
  WSQL = WSQL || '      COLBANCO.BDCTADEPCOL, ';
  WSQL = WSQL || '      COLBANCO.BDDIGCTADEPCOL, ';
  WSQL = WSQL || '      COLBANCO.BDMODOPAGTOCOL, ';
  WSQL = WSQL || '      VERB.BDCLAVER, ';
  WSQL = WSQL || '      FOL.BDCODCENTRO, ';
  WSQL = WSQL || '      FOL.BDCODTPCC, ';
  WSQL = WSQL || '      coalesce(COLCAD.BDEMAILCOL, '''') BDEMAIL1, ';
  WSQL = WSQL || '      coalesce(COL.BDEMAIL2COL, '''') BDEMAIL2, ';
  WSQL = WSQL || '      DOCREF.BDCTPSCOL, ';
  WSQL = WSQL || '      DOCREF.BDSERIECTPSCOL, ';
  WSQL = WSQL || '      DOCREF.BDDSERIECTPSCOL, FOL.BDORDEM ';
  WSQL = WSQL || 'from (select ';

  if (PRCODTPCC is not null and
      PRCODTPCC <> '') then
    WSQL = WSQL || 'first 0 ';

  WSQL = WSQL || '            X.BDCODEMP, ';
  WSQL = WSQL || '            X.BDCODCOL, ';
  WSQL = WSQL || '            X.BDREFFN, ';
  WSQL = WSQL || '            X.BDCODVER, ';
  WSQL = WSQL || '            X.BDREFVFN as BDREFVFN_SUM, ';
  WSQL = WSQL || '            X.BDREFAUXVFN as BDREFAUXVFN_SUM, ';
  WSQL = WSQL || '            X.BDREFVFN as BDREFVFN_MAX, ';
  WSQL = WSQL || '            X.BDREFAUXVFN as BDREFAUXVFN_MAX, ';
  WSQL = WSQL || '            X.BDVALVFN, ';
  WSQL = WSQL || '            0 BDCODCENTRO, ';
  WSQL = WSQL || '            0 BDCODTPCC, 0 BDORDEM ';
  WSQL = WSQL || '      from ';
  WSQL = WSQL || '            VRHF_EMP_TVERBAFN X ';

  if (PRCODEMP > 0) then
    WSQL = WSQL || '      where X.BDCODEMP = ' || :PRCODEMP || ' and X.BDREFFN = ' || PRREF || ' ';
  else
    WSQL = WSQL || '      where X.BDREFFN = ' || PRREF || ' ';

  -- Esse trecho é para incluir a verba de crédito do trabalhador, caso não tenha sido feito desconto nenhum na folha

  WSQL = WSQL ||
         ' union all '||
         'select P.BDCODEMP, P.BDCODCOL, PI.BDREFPI, P.BDCODVER, 0, 0, 0, 0, 0, 0, 0, 0 '||
         'from VRH_EMP_TPARCELAMENTOS P '||
         'join VRH_EMP_TPARCELAMENTOS_ITENS PI on (PI.BDCODEMP = P.BDCODEMP and PI.BDCODCOL = P.BDCODCOL and PI.BDCODPARC = P.BDCODPARC) ';

  if (PRCODEMP > 0) then
    WSQL = WSQL || '      where P.BDCODEMP = ' || :PRCODEMP || ' and PI.BDREFPI = ' || PRREF || ' ';
  else
    WSQL = WSQL || '      where PI.BDREFPI = ' || PRREF || ' ';

  WSQL = wSQL || ' and P.BDECONSIGNADO ';
  WSQL = WSQL || ' and not exists('||
                   'select D.BDCODVER '||
                   'from VRHF_EMP_TVERBAFN D '||
                   'where D.BDCODEMP = P.BDCODEMP and D.BDCODCOL = P.BDCODCOL and D.BDREFFN = PI.BDREFPI and D.BDCODVER = P.BDCODVER '||
                   'union all '||
                   'select D.BDCODVER '||
                   'from VRHF_EMP_TVERBATOMADOR D '||
                   'where D.BDCODEMP = P.BDCODEMP and D.BDCODCOL = P.BDCODCOL and D.BDREFTOMADOR = PI.BDREFPI and D.BDCODVER = P.BDCODVER '||
                 ')';
  WSQL = WSQL || 'group by P.BDCODEMP, P.BDCODCOL, PI.BDREFPI, P.BDCODVER ';

  WMES = substring(cast(PRREF as varchar(6)) from 5 for 2);
  WANO = substring(cast(PRREF as varchar(6)) from 1 for 4);

  select cast(ULTDIA as varchar(2))
  from ULTIMO_DIA_MES(cast(:WMES as smallint), cast(:WANO as integer))
  into :WULTDIA;

  if (STRLEN(WMES) = 1) then
    WMES = '0' || WMES;

  if (STRLEN(WULTDIA) = 1) then
    WULTDIA = '0' || WULTDIA;

  WDTI = '''' || WMES || '/01/' || WANO || '''';
  WDTF = '''' || WMES || '/' || WULTDIA || '/' || WANO || '''';

  WSQL = WSQL || '      UNION ALL ';

  if (PRCODTPCC is not null and
      PRCODTPCC <> '') then
  begin
    WSQL = WSQL || '      select ';
    WSQL = WSQL || '            X.BDCODEMP, ';
    WSQL = WSQL || '            X.BDCODCOL, ';
    WSQL = WSQL || '            X.BDREFTOMADOR, ';
    WSQL = WSQL || '            X.BDCODVER, ';
    WSQL = WSQL || '            X.BDREFVFN_SUM, ';
    WSQL = WSQL || '            X.BDREFAUXVFN_SUM, ';
    WSQL = WSQL || '            X.BDREFVFN_MAX, ';
    WSQL = WSQL || '            X.BDREFAUXVFN_MAX, ';
    WSQL = WSQL || '            X.BDVALVFT, ';
    WSQL = WSQL || '            X.BDCODCENTRO, ';
    WSQL = WSQL || '            X.BDCODTPCC, X.BDORDEM ';
    WSQL = WSQL || '      from ';
    WSQL = WSQL || '            SP_VRHF_UNION_FT_MES(' || PRCODEMP || ',' || PRREF || ',''' || PRCODTPCC || ''') X ';

    WSQL = WSQL || '      where X.BDREFTOMADOR = ' || PRREF || ' ';

    WSQL = WSQL || '     ) FOL ';
  end
  else
  begin
    WSQL = WSQL || '      select ';
    WSQL = WSQL || '            X.BDCODEMP, ';
    WSQL = WSQL || '            X.BDCODCOL, ';
    WSQL = WSQL || '            X.BDREFTOMADOR, ';
    WSQL = WSQL || '            X.BDCODVER, ';
    WSQL = WSQL || '            X.BDREFVFN_SUM, ';
    WSQL = WSQL || '            X.BDREFAUXVFN_SUM, ';
    WSQL = WSQL || '            X.BDREFVFN_MAX, ';
    WSQL = WSQL || '            X.BDREFAUXVFN_MAX, ';
    WSQL = WSQL || '            X.BDVALVFT, ';
    WSQL = WSQL || '            X.BDCODCENTRO, ';
    WSQL = WSQL || '            X.BDCODTPCC, X.BDORDEM ';
    WSQL = WSQL || '      from ';
    WSQL = WSQL || '            SP_VRHF_UNION_FT_MES(' || PRCODEMP || ',' || PRREF || ') X ';

    WSQL = WSQL || '      where X.BDREFTOMADOR = ' || PRREF || ' ';

    WSQL = WSQL || '     ) FOL ';
  end
  --Sol. 127109 - Paulo Nunes - 02/12/2019 - Ajustado o recibo para trazer o valor da base e o valor do FGTS do 13º da folha normal e da folha de tomador.
  WSQL = WSQL || 'join (select ';
  WSQL = WSQL || '            BDCODEMP, ';
  WSQL = WSQL || '            BDCODCOL, ';
  WSQL = WSQL || '            BDREFFN, ';
  WSQL = WSQL || '            coalesce(BDBFGTSFN,0) + coalesce(BDBFGTSFEFN,0) + coalesce(BDBFGTS13FN,0)  as BDBFGTS, ';
  WSQL = WSQL || '            coalesce(BDFGTSFN,0) + coalesce(BDFGTSFEFN,0) + coalesce(BDFGTS13FN,0) as BDFGTS, ';
  WSQL = WSQL || '            coalesce(BDBINSSFN,0) + coalesce(BDBINSSFEFOLFN,0) + coalesce(BDBINSS13FN,0) as BDBINSS, ';
  WSQL = WSQL || '            coalesce(BDBINSSAPFN,0) as BDBINSSAP,';
  WSQL = WSQL || '            coalesce(BDBIRRFFN,0)+coalesce(BDBIRRF13FN,0) as BDBIRRF, ';
  WSQL = WSQL || '            BDSALBASEFN as BDSALBASE, ';
  WSQL = WSQL || '            0 BDCODCENTRO, ';
  WSQL = WSQL || '            0 BDCODTPCC, 0 BDORDEM ';

  WSQL = WSQL || '      from ';
  WSQL = WSQL || '            VRHF_EMP_TFOLHANORMAL X ';

  WSQL = WSQL || 'where exists (select Y.BDCODEMP from VRHF_EMP_TVERBAFN Y where Y.BDCODEMP = X.BDCODEMP and Y.BDCODCOL = X.BDCODCOL and Y.BDREFFN = X.BDREFFN) ';

  if (PRCODEMP > 0) then
    WSQL = WSQL || '      and BDCODEMP = ' || :PRCODEMP || ' and BDREFFN = ' || PRREF || ' ';
  else
    WSQL = WSQL || '      and BDREFFN = ' || PRREF || ' ';

  WSQL = WSQL || '      UNION All ';

  if (PRCODTPCC is not null and
      PRCODTPCC <> '') then
  begin
    WSQL = WSQL || '      select ';
    WSQL = WSQL || '            X.BDCODEMP, ';
    WSQL = WSQL || '            X.BDCODCOL, ';
    WSQL = WSQL || '            X.BDREFTOMADOR BDREFFN, ';
    WSQL = WSQL || '            sum(X.BDBFGTSFT) + sum(x.BDBFGTSFEFT) + sum(x.BDBFGTS13FT), ';
    WSQL = WSQL || '            sum(X.BDFGTSFT)  + sum(x.BDFGTSFEFT)  + sum(x.BDFGTS13FT), ';

    WSQL = WSQL || '            sum(X.BDBINSSFT) + sum(x.BDBINSSFEFOLFT) + sum(x.BDBINSS13FT), ';
    WSQL = WSQL || '            sum(X.BDBINSSAPFT), ';
    WSQL = WSQL || '            sum(X.BDBIRRFFT) + sum(x.BDBIRRF13FT), ';
    WSQL = WSQL || '            max(X.BDSALBASEFT), ';
    WSQL = WSQL || '            Y.BDCODCENTRO, ';
    WSQL = WSQL || '            Y.BDCODTPCC, MAX(X.BDORDEM) ';
    WSQL = WSQL || '      from ';
    WSQL = WSQL || '            VRHF_EMP_TFOLHATOMADOR X, ';
    WSQL = WSQL || '            VRHF_EMP_TPREPFN Y ';

    if (PRCODEMP > 0) then
      WSQL = WSQL || '      where X.BDCODEMP = ' || :PRCODEMP || ' and X.BDREFTOMADOR = ' || PRREF || ' and X.BDCODEMP = Y.BDCODEMP and X.BDCODCOL = Y.BDCODCOL and X.BDORDEM = Y.BDORDEM ';
    else
      WSQL = WSQL || '      where X.BDREFTOMADOR = ' || PRREF || ' and X.BDCODEMP = Y.BDCODEMP and X.BDCODCOL = Y.BDCODCOL and X.BDORDEM = Y.BDORDEM ';

    WSQL = WSQL || ' and ' || PRCODTPCC;

    WSQL = WSQL || ' group by X.BDCODEMP,X.BDCODCOL,X.BDREFTOMADOR,Y.BDCODCENTRO,Y.BDCODTPCC ';

    WSQL = WSQL || ') FOLB on (FOLB.BDCODEMP = FOL.BDCODEMP and FOLB.BDCODCOL = FOL.BDCODCOL and FOLB.BDREFFN = FOL.BDREFFN) ';
  end
  else
  begin
    WSQL = WSQL || '      select ';
    WSQL = WSQL || '            X.BDCODEMP, ';
    WSQL = WSQL || '            X.BDCODCOL, ';
    WSQL = WSQL || '            X.BDREFTOMADOR BDREFFN, ';
    WSQL = WSQL || '            sum(X.BDBFGTSFT) + sum(x.BDBFGTSFEFT) + sum(x.BDBFGTS13FT), ';
    WSQL = WSQL || '            sum(X.BDFGTSFT)  + sum(x.BDFGTSFEFT)  + sum(x.BDFGTS13FT), ';
    WSQL = WSQL || '            sum(x.bdbinssft) + sum(x.BDBINSSFEFOLFT)  + sum(x.BDBINSS13FT), ';
    WSQL = WSQL || '            sum(x.BDBINSSAPFT), ';
    WSQL = WSQL || '            SUM(X.BDBIRRFFT) + sum(x.BDBIRRF13FT), ';
    WSQL = WSQL || '            MAX(X.BDSALBASEFT), ';
    WSQL = WSQL || '            0 BDCODCENTRO, ';
    WSQL = WSQL || '            0 BDCODTPCC, MAX(X.BDORDEM) ';
    WSQL = WSQL || '      from ';
    WSQL = WSQL || '            VRHF_EMP_TFOLHATOMADOR X, ';
    WSQL = WSQL || '            VRHF_EMP_TPREPFN Y ';

    if (PRCODEMP > 0) then
      WSQL = WSQL || '      where X.BDCODEMP = ' || :PRCODEMP || ' and X.BDREFTOMADOR = ' || PRREF || ' and X.BDCODEMP = Y.BDCODEMP and X.BDCODCOL = Y.BDCODCOL and X.BDORDEM = Y.BDORDEM ';
    else
      WSQL = WSQL || '      where X.BDREFTOMADOR = ' || PRREF || ' and X.BDCODEMP = Y.BDCODEMP and X.BDCODCOL = Y.BDCODCOL and X.BDORDEM = Y.BDORDEM ';

    WSQL = WSQL || '      group by ';
    WSQL = WSQL || '            X.BDCODEMP, ';
    WSQL = WSQL || '            X.BDCODCOL, ';
    WSQL = WSQL || '            X.BDREFTOMADOR) FOLB on (FOLB.BDCODEMP = FOL.BDCODEMP and FOLB.BDCODCOL = FOL.BDCODCOL and FOLB.BDREFFN = FOL.BDREFFN) ';
  end

  if (PRCODCLA is not null and
      PRCODCLA <> '') then
  begin
    PRCODCLA = replace(upper(:PRCODCLA), 'BDCODCLA', 'COLCON_VIN.BDCODCLA');
    WSQL = WSQL || ' join VRH_EMP_TCOLCON_VINC COLCON_VIN on (COLCON_VIN.BDCODEMP = FOL.BDCODEMP and COLCON_VIN.BDCODCOL = FOL.BDCODCOL and ' || PRCODCLA || ' and ' || 'COLCON_VIN.BDREFCOL = (select first 1 bdrefcol from vrh_emp_tcolcon_vinc where bdcodemp = COLCON_VIN.bdcodemp and bdcodcol = COLCON_VIN.bdcodcol and bdrefcol <= ' || PRREF || ' order by bdcodemp desc, bdcodcol desc, bdrefcol desc)) ';
  end

  WSQL = WSQL || ' left outer join TEMPRESAS EMP on (EMP.BDCODEMP = FOL.BDCODEMP) ';
  WSQL = WSQL || ' left outer join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = FOL.BDCODVER) ';
  WSQL = WSQL || ' left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
  WSQL = WSQL || ' left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';
  WSQL = WSQL || ' left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FOL.BDCODEMP and DOCREF.BDCODCOL = FOL.BDCODCOL) ';
  WSQL = WSQL || ' left outer join VRH_EMP_TCOLCON_DOC COLDOC on (COLDOC.BDCODEMP = FOL.BDCODEMP and COLDOC.BDCODCOL = FOL.BDCODCOL) ';
  WSQL = WSQL || ' left outer join VW_VRH_BASE_TVERBAS_REF VERR on (VERR.BDCODVER = FOL.BDCODVER) ';
  WSQL = WSQL || ' left outer join VW_VRHF_EMP_TCOLCON_BANCO COLBANCO on (COLBANCO.BDCODEMP = FOL.BDCODEMP and COLBANCO.BDCODCOL = FOL.BDCODCOL) ';

  -- Elimina situação
  if (PRDATAINI is not null and PRDATAFIM is not null) then
  begin
    WDTI = '''' || cast(PRDATAINI as varchar(10)) || '''';
    WDTF = '''' || cast(PRDATAFIM as varchar(10)) || '''';

    /*161036 - Paulo Nunes - Ajuste para melhorar performance - Inicio */
    WSQL = WSQL || 'left outer join ( ' ||
                   'select SIT.BDCODEMP, SIT.BDCODCOL ' ||
                   'from VRH_EMP_TSITCOL SIT ' ||
                   'join VRH_BASE_TPREPSIT PSIT on (PSIT.BDCODSIT = SIT.BDCODSIT) ' ||
                   'where BDCODEMP is not null and ' ||
                         'SIT.BDCODEMP =  ' || PRCODEMP || ' and ' ||
                         '(SIT.BDDATAINISIT <= ' || WDTI || ' and ((SIT.BDDATAFIMSIT is null) or (SIT.BDDATAFIMSIT >= ' || WDTF || '))) ' ||
                         'and PSIT.BDRELSIT = 1 ' ||
                   'group by SIT.BDCODEMP, SIT.BDCODCOL ' ||
                   ') FILTROSIT on (FILTROSIT.bdcodemp = fol.bdcodemp and FILTROSIT.bdcodcol = fol.bdcodcol) '||
                   'where FILTROSIT.BDCODEMP is null ';
 /*161036 - Paulo Nunes - Ajuste para melhorar performance - Fim */
  end

  wsql = wsql||' order by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN ';

  wempatu = 0;
  wcolatu = 0;
  wrefatu = 0;
  wcomferias = 1;

  for execute statement WSQL
          into :BDCODEMP, :BDCODCOL, :BDCODVER, :BDREFFN, :BDREFVFN_SUM, :BDREFVFN_MAX, :BDREFAUXVFN_MAX,
          :BDREFAUXVFN_SUM, :BDVALVFN, :BDDATAFN, :BDSALBASE, :BDBINSS, :BDBINSSAP, :BDBFGTS, :BDFGTS, :BDBIRRF,
          :BDCNPJEMP, :BDDESCVER, :BDDESCREDVER, :BDORDEMVER, :BDNOMCOL, :BDDATAADMCOL, :BDPISCOL, :BDCPFCOL, :BDRG,
          :BDTIPOCODVER, :BDORDEMTIPOCODVER, :BDTIPOREFVER, :BDCODBAN, :BDCODAG, :BDCTADEPCOL, :BDDIGCTADEPCOL,
          :BDMODOPAGTOCOL, :BDCLAVER, :BDCODCENTRO, :BDCODTPCC, :WEMAIL1, :WEMAIL2, :BDCTPSCOL, :BDSERIECTPSCOL, :BDDSERIECTPSCOL, :BDORDEM
  do
  begin
    if (prsemferias > 0) then
       begin
         if ((wempatu <> BDCODEMP) or (wcolatu <> BDCODCOL) or (wrefatu <> BDREFFN)) then
            begin
              wcomferias = 0;
              wparcelapi = null;
              select first 1 BDPARCELAPI
              from VRHF_EMP_TPARCDETCALC
              where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCALC = :BDREFFN and coalesce(BDDESCFER, 0) > 0 and BDTIPOCALC = 1
              into :wparcelapi;

              if (coalesce(wparcelapi, 0) > 0) then
                 wcomferias = 1;

              wempatu = BDCODEMP;
              wcolatu = BDCODCOL;
              wrefatu = BDREFFN;
            end
       end
    else
       wcomferias = 1;

    if (wcomferias = 0) then
       begin
         if (substring(BDCLAVER from 1 for 5) >= '0.100' and substring(BDCLAVER from 1 for 5) < '0.200') then
            Continue;

         if ((substring(BDCLAVER from 1 for 9) = '9.010.0.2') or (substring(BDCLAVER from 1 for 9) = '9.010.1.2') or
             (substring(BDCLAVER from 1 for 5) = '0.710')) then
            Continue;
       end

    BDNIVELORDEM = 0;
    BDIMPCOD = 'TRUE';
    WEMAIL1 = replace(WEMAIL1, ';', ',');
    WEMAIL1 = replace(WEMAIL1, ' ', ',');

    WEMAIL2 = replace(WEMAIL2, ';', ',');
    WEMAIL2 = replace(WEMAIL2, ' ', ',');

    BDEMAILCOL = '';

    if (trim(WEMAIL1) <> '') then
       begin
      BDEMAILCOL = trim(WEMAIL1);

      if (trim(WEMAIL2) <> '') then
        BDEMAILCOL = BDEMAILCOL || ',' || trim(WEMAIL2);
       end
    else
    if (trim(WEMAIL2) <> '') then
      BDEMAILCOL = trim(WEMAIL2);

    if (BDBINSSAP < 0) then
      BDBINSS = BDBINSS + BDBINSSAP;

    /*  Sol.152518 Leonardo Schwab 15/07/2021
        Adicionado campo para controlar quantos salários tem o horista especial,
        caso tenha mais de um não irá aparecer o salário base no recibo de salário.
    */
    SELECT COUNT(*)
    FROM (select BDCODEMP, BDCODCOL, BDCODSHE, max(BDDATASHE) BDDATASHE
          from VRH_EMP_TCOL_SHE
    WHERE BDCODEMP = :BDCODEMP AND
          BDCODCOL = :BDCODCOL AND
                BDREFSHE <= :BDREFFN
          group by BDCODEMP, BDCODCOL, BDCODSHE
    )
    INTO :BDQTDSALARIOHE;

    -- Crédito consignado
    if ((substring(BDCLAVER from 1 for 9) = '0.070.1.1') or (substring(BDCLAVER from 1 for 9) = '0.009.1.1') or
        (substring(BDCLAVER from 1 for 9) = '0.009.1.2') or (substring(BDCLAVER from 1 for 9) = '0.100.4.1') or
        (substring(BDCLAVER from 1 for 9) = '7.001.4.1')) then
       begin
         BDVALVFN = 0;  -- Atribui 0 para a verba principal. Apenas o detalhamento terá valor
    suspend;

         if ((coalesce(BDORDEM, 0 ) <= 0) or (coalesce(prcodtpcc, '') = '')) then   -- Não tem alocação
            begin
              for select SUM(DT.BDDESCFN), SUM(DT.BDDESCADS), SUM(DT.BDDESCFER), P.BDCONTRATOPAR, max(cast(PI.BDVALORPI as dm_numeric_15_2)),
                         SUM(PI.bdvalordesc_fer), sum(pi.bdvalordesc_ads), sum(pi.bdvalordesc_nor)
                  from VRH_EMP_TPARCELAMENTOS P
                  join VRH_EMP_TPARCELAMENTOS_ITENS PI on (PI.BDCODEMP = P.BDCODEMP and PI.BDCODCOL = P.BDCODCOL and PI.BDCODPARC = P.BDCODPARC)
                  left outer join VRHF_EMP_TPARCDETCALC DT on (DT.BDCODEMP = P.BDCODEMP and DT.BDCODCOL = P.BDCODCOL and DT.BDCODPARC = P.BDCODPARC and DT.BDPARCELAPI = PI.BDPARCELAPI)
                  where P.BDCODEMP = :BDCODEMP and P.BDCODCOL = :BDCODCOL and PI.BDREFPI = :BDREFFN and P.BDECONSIGNADO
                  group by P.BDCONTRATOPAR
              into :wvalfn, :wvalad, :wvalfe, :wcontrato, :wvalparc, :wvalorvefe, :wvalorvead, :wvalorvefn
              do
                begin
                  if (wvalfn is null and wvalad is null and wvalfe is null) then
                     begin
                       wvalfn = coalesce(wvalorvefn, 0.00);
                       wvalad = coalesce(wvalorvead, 0.00);
                       wvalfe = coalesce(wvalorvefe, 0.00);
        
                       BDDESCVER = ' ';
                       BDDESCREDVER = ' ';
        
                       if (wvalfn + wvalad + wvalfe < wvalparc) then
                          begin
                            BDDESCVER = '*';
                            BDDESCREDVER = '*';
  end
        
                       BDDESCVER = substring(BDDESCVER||'  Nº '||wcontrato from 1 for 40);
                       BDDESCREDVER = substring(BDDESCREDVER||'  '||wcontrato from 1 for 20);
        
                       BDNIVELORDEM = BDNIVELORDEM + 1;
                       BDIMPCOD = 'FALSE';
        
                       -- Adiantamento salarial
                       if (((substring(BDCLAVER from 1 for 9) = '0.009.1.1') or
                            (substring(BDCLAVER from 1 for 9) = '0.009.1.2')) and
                           (wvalad > 0)) then
                          begin
                            BDVALVFN = wvalad;
                            suspend;
                          end
                       else
                       if ((substring(BDCLAVER from 1 for 9) = '0.100.4.1') and
                           (wvalfe > 0)) then   -- Demonstrativo de férias
                          begin
                            BDVALVFN = wvalfe;
                            suspend;
                          end
                       else
                       if (((substring(BDCLAVER from 1 for 9) = '0.070.1.1') or (substring(BDCLAVER from 1 for 9) = '7.001.4.1')) and
                           (wvalad + wvalfe < wvalparc)) then
                          begin
                            BDVALVFN = wvalfn;
                            suspend;
                          end
                     end
                  else
                     begin
                       wvalfn = coalesce(wvalfn, 0.00);
                       wvalad = coalesce(wvalad, 0.00);
                       wvalfe = coalesce(wvalfe, 0.00);
        
                       BDDESCVER = ' ';
                       BDDESCREDVER = ' ';
        
                       if (wvalfn + wvalad + wvalfe < wvalparc) then
                          begin
                            BDDESCVER = '*';
                            BDDESCREDVER = '*';
                          end
        
                       BDDESCVER = substring(BDDESCVER||'  Nº '||wcontrato from 1 for 40);
                       BDDESCREDVER = substring(BDDESCREDVER||'  '||wcontrato from 1 for 20);
        
                       BDNIVELORDEM = BDNIVELORDEM + 1;
                       BDIMPCOD = 'FALSE';
        
                       -- Adiantamento salarial
                       if (((substring(BDCLAVER from 1 for 9) = '0.009.1.1') or
                            (substring(BDCLAVER from 1 for 9) = '0.009.1.2')) and
                           (wvalad > 0)) then
                          begin
                            BDVALVFN = wvalad;
                            suspend;
                          end
                       else
                       if ((substring(BDCLAVER from 1 for 9) = '0.100.4.1') and
                           (wvalfe > 0)) then   -- Demonstrativo de férias
                          begin
                            BDVALVFN = wvalfe;
                            suspend;
                          end
                       else
                       if (((substring(BDCLAVER from 1 for 9) = '0.070.1.1') or (substring(BDCLAVER from 1 for 9) = '7.001.4.1')) and
                           (wvalad + wvalfe < wvalparc)) then
                          begin
                            BDVALVFN = wvalfn;
                            suspend;
                          end
                     end
                end
            end
         else
            begin
              for select DT.BDDESCFN, DT.BDDESCADS, DT.BDDESCFER, P.BDCONTRATOPAR, cast(PI.BDVALORPI as dm_numeric_15_2),(PI.bdvalordesc_fer), (pi.bdvalordesc_ads), (pi.bdvalordesc_nor)
                  from VRH_EMP_TPARCELAMENTOS P
                  join VRH_EMP_TPARCELAMENTOS_ITENS PI on (PI.BDCODEMP = P.BDCODEMP and PI.BDCODCOL = P.BDCODCOL and PI.BDCODPARC = P.BDCODPARC)
                  left outer join VRHF_EMP_TPARCDETCALC DT on (DT.BDCODEMP = P.BDCODEMP and DT.BDCODCOL = P.BDCODCOL and DT.BDCODPARC = P.BDCODPARC and DT.BDPARCELAPI = PI.BDPARCELAPI)
                  where P.BDCODEMP = :BDCODEMP and P.BDCODCOL = :BDCODCOL and PI.BDREFPI = :BDREFFN and ((DT.BDORDEM = :BDORDEM) or (dt.bdordem is null) ) and P.BDECONSIGNADO
                  order by DT.BDCODPARCCALC
              into :wvalfn, :wvalad, :wvalfe, :wcontrato, :wvalparc, :wvalorvefe, :wvalorvead, :wvalorvefn
              do
                begin
                  if (wvalfn is null and wvalad is null and wvalfe is null) then
                     begin
                       wvalfn = coalesce(wvalorvefn, 0.00);
                       wvalad = coalesce(wvalorvead, 0.00);
                       wvalfe = coalesce(wvalorvefe, 0.00);

                     end
                   else
                     begin
                  wvalfn = coalesce(wvalfn, 0.00);
                  wvalad = coalesce(wvalad, 0.00);
                  wvalfe = coalesce(wvalfe, 0.00);
                     end

                  BDDESCVER = ' ';
                  BDDESCREDVER = ' ';

                  if (wvalfn + wvalad + wvalfe < wvalparc) then
                     begin
                       BDDESCVER = '*';
                       BDDESCREDVER = '*';
                     end

                  BDDESCVER = substring(BDDESCVER||'  Nº '||wcontrato from 1 for 40);
                  BDDESCREDVER = substring(BDDESCREDVER||'  '||wcontrato from 1 for 20);

                  BDNIVELORDEM = BDNIVELORDEM + 1;
                  BDIMPCOD = 'FALSE';

                  -- Adiantamento salarial
                  if (((substring(BDCLAVER from 1 for 9) = '0.009.1.1') or
                       (substring(BDCLAVER from 1 for 9) = '0.009.1.2')) and
                      (wvalad > 0)) then
                     begin
                       BDVALVFN = wvalad;
                       suspend;
                     end
                  else
                  if ((substring(BDCLAVER from 1 for 9) = '0.100.4.1') and
                      (wvalfe > 0)) then   -- Demonstrativo de férias
                     begin
                       BDVALVFN = wvalfe;
                       suspend;
                     end
                  else
                  if (((substring(BDCLAVER from 1 for 9) = '0.070.1.1') or (substring(BDCLAVER from 1 for 9) = '7.001.4.1')) and
                      (wvalad + wvalfe < wvalparc)) then
                     begin
                       BDVALVFN = wvalfn;
                       suspend;
                     end
                end
            end
       end
    else
       suspend;
  end
end^


/* Restore proc. body: VRH_SP_RELATORIO_CAT_AGCAUSA */
ALTER PROCEDURE VRH_SP_RELATORIO_CAT_AGCAUSA(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRCHAVE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCHAVE INTEGER,
BDOBJETOCAUSADORACID VARCHAR(300))
 AS
DECLARE VARIABLE WSQL VARCHAR(15000);
DECLARE VARIABLE WCODPCORPO INTEGER;
DECLARE VARIABLE WOBJCAUSAACID VARCHAR(300);
BEGIN
  wSql = 'select CAT.BDCODAGCAUSA, AGCAUSA.BDDESCAGCAUSA from VRH_EMP_TCAT_AGCAUSADOR CAT ';
  wSql = wSql || 'left outer join TCAT_AGENTECAUSADOR AGCAUSA on AGCAUSA.BDCODAGCAUSA = CAT.BDCODAGCAUSA ';
  wSql = wSql || 'where CAT.BDCODEMP = '||prcodemp||' and CAT.BDCODCOL = '||prcodcol||' and CAT.BDCHAVE = '||prchave||' ';

  BDOBJETOCAUSADORACID = '';
  FOR EXECUTE STATEMENT wsql INTO :wcodpcorpo, :wobjcausaacid DO
  BEGIN
    BDCODEMP = prcodemp;
    BDCODCOL = prcodcol;
    BDCHAVE = prchave;

    IF (BDOBJETOCAUSADORACID = '') THEN
    BEGIN
      BDOBJETOCAUSADORACID = wobjcausaacid;
    END
    ELSE
    BEGIN
      BDOBJETOCAUSADORACID = BDOBJETOCAUSADORACID || '; ' || wobjcausaacid;
    END
  END

  SUSPEND;
END
^

/* Restore proc. body: VRH_SP_RELATORIO_CAT_PCORPO */
CREATE OR ALTER PROCEDURE VRH_SP_RELATORIO_CAT_PCORPO(PRCODEMP INTEGER,
PRCODCOL INTEGER,
PRCHAVE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCHAVE INTEGER,
BDPARTESATINGIDAS VARCHAR(400))
 AS
DECLARE VARIABLE WSQL VARCHAR(15000);
DECLARE VARIABLE WCODPCORPO INTEGER;
DECLARE VARIABLE WDESCPCORPO VARCHAR(400);
BEGIN
  wSql = 'select CAT.BDCODPCORPO, PCORPO.BDDESCPCORPO from VRH_EMP_TCAT_PATINGIDAS CAT ';
  wSql = wSql || 'left outer join TCAT_PCORPOATINGIDA PCORPO on PCORPO.BDCODPCORPO = CAT.BDCODPCORPO ';
  wSql = wSql || 'where CAT.BDCODEMP = '||prcodemp||' and CAT.BDCODCOL = '||prcodcol||' and CAT.BDCHAVE = '||prchave||' ';

  BDPARTESATINGIDAS = '';
  FOR EXECUTE STATEMENT wsql INTO :wcodpcorpo, :wdescpcorpo DO
  BEGIN
    BDCODEMP = prcodemp;
    BDCODCOL = prcodcol;
    BDCHAVE = prchave;

    IF (BDPARTESATINGIDAS = '') THEN
    BEGIN
      BDPARTESATINGIDAS = wdescpcorpo;
    END
    ELSE
    BEGIN
      BDPARTESATINGIDAS = BDPARTESATINGIDAS || '; ' || wdescpcorpo;
    END
  END

  SUSPEND;
END
^

/* Restore proc. body: VRH_SP_RELATORIO_CAT2 */
CREATE OR ALTER procedure VRH_SP_RELATORIO_CAT2 (
    PRCODEMP varchar(32000),
    PRCODCOL varchar(32000),
    PRCHAVE integer,
    PRULTIMODIA date,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCHAVE integer,
    BDCODCID integer,
    BDDATAACIDENTE date,
    BDDATAEMISSAO date,
    BDDATAULTIMODIA date,
    BDDATAOBITO date,
    BDEMITENTE integer,
    BDNRCAT varchar(25),
    BDCATORIGEM varchar(25),
    BDTIPOAFAST integer,
    BDREGPOLICIAL varchar(5),
    BDAFASTAMENTO varchar(5),
    BDHORAACIDENTE time,
    BDTIPOCAT integer,
    BDLOCALACIDENTE integer,
    BDESPLOCALACIDENTE varchar(255),
    BDOBJETOCAUSADORACID varchar(10000),
    BDDESCACIDENTE blob sub_type 1 segment size 210,
    BDPARTESATINGIDAS varchar(10000),
    BDAREAACIDENTE integer,
    BDHOUVEOBITO varchar(5),
    BDREMUNMENSAL integer,
    BDNOMEMP DM_BDNOMEMP,
    BDBAIEMP DM_BDBAIRRO,
    BDCODCNAE integer,
    BDNUMEMP DM_NUMEND,
    BDENDEMP DM_BDENDERECO,
    BDLOGREMP varchar(15),
    BDCEPEMP varchar(9),
    BDDDDEMP integer,
    BDFONEEMP DM_BDTELEFONE,
    BDCNPJEMP varchar(18),
    BDNOMCOL DM_BDNOMCOL,
    BDNOMMAECOL varchar(70),
    BDDATANASCCOL date,
    BDCPFCOL varchar(14),
    BDSEXOCOL integer,
    BDESTCIVCOL integer,
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDDATAEMICTPSCOL date,
    BDRGCOL varchar(13),
    BDDATAEMIRGCOL date,
    BDORGEMIRGCOL varchar(30),
    BDPISCOL varchar(14),
    BDLOGRCOL varchar(15),
    BDENDCOL DM_BDENDERECO,
    BDNUMCOL DM_NUMEND,
    BDBAICOL DM_BDBAIRRO,
    BDCEPCOL varchar(9),
    BDDDDCOL integer,
    BDFONECOL DM_BDTELEFONE,
    BDFILIACAOPREV integer,
    BDAPOSENTADO integer,
    BDNOMCIDACID varchar(40),
    BDUFACID varchar(2),
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
    BDNOMECIDCOL varchar(40),
    BDUFCOL varchar(2),
    BDUFCTPS varchar(2),
    BDDESCCBO varchar(150),
    BDCODCBO integer,
    BDSALBASECOL numeric(15,6),
    BDUFRG varchar(2),
    BDDDDCELCOL integer,
    BDCELCOL DM_BDTELEFONE,
    BDTIPOCOL integer,
    BDHORASMENSAISCOL numeric(15,6),
    BDDTAPOSENT date,
    BDDATARETORNO date,
    BDLATERALIDADE integer,
    BDINICIATIVA integer,
    BDEXCLUIDO DM_BOOLEAN,
    BDRECIBOESOC varchar(30),
    BDRECIBORETEXC varchar(30),
    BDSITUACAOGERADORA varchar(210))
as
declare variable WSQL varchar(32000);
declare variable WSQLA varchar(5000);
declare variable WDESC varchar(1000);
declare variable WVALUE numeric(18,6);
declare variable WCODPCORPOESOC varchar(9);
declare variable WDATAINISST date;
declare variable WCODSITGER integer;
BEGIN

  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, prultimodia);

    wSql = 'select ';
    wSql = wSql || 'CAT.BDCODEMP, ';
    wSql = wSql || 'CAT.BDCODCOL, ';
    wSql = wSql || 'CAT.BDCHAVE, ';
    wSql = wSql || 'CAT.BDCODCID, ';
    wSql = wSql || 'CAT.BDDATAACIDENTE, ';
    wSql = wSql || 'CAT.BDDATAEMISSAO, ';
    wSql = wSql || 'CAT.BDDATAULTIMODIA, ';
    wSql = wSql || 'CAT.BDDATAOBITO, ';
    wSql = wSql || 'case when (CAT.BDEMITENTE = 5) then 3 else CAT.BDEMITENTE end BDEMITENTE, ';
    wSql = wSql || 'CAT.BDNRCAT, ';
    wSql = wSql || 'coalesce(CAT.BDCATORIGEM, 0),';
    wSql = wSql || 'CAT.BDTIPOAFAST, ';
    wSql = wSql || 'CAT.BDREGPOLICIAL, ';
    wSql = wSql || 'CAT.BDAFASTAMENTO, ';
    wSql = wSql || 'CAT.BDHORAACIDENTE, ';
    wSql = wSql || 'CAT.BDTIPOCAT, ';
    wSql = wSql || 'CAT.BDLOCALACIDENTE, ';
    wSql = wSql || 'CAT.BDESPLOCALACIDENTE, ';
    wSql = wSql || 'CAT.BDOBJETOCAUSADORACID, ';
    wSql = wSql || 'CAT.BDDESCACIDENTE, ';
    wSql = wSql || 'CAT.BDPARTESATINGIDAS, ';
    wSql = wSql || 'coalesce(CAT.BDAREAACIDENTE, 0) + 1, ';
    wSql = wSql || 'CAT.BDHOUVEOBITO, ';
    wSql = wSql || 'CAT.BDREMUNMENSAL, ';
    wSql = wSql || 'CAT.BDINICIATIVA, ';
    wSql = wSql || 'EMPR.BDNOMEMP, ';
    wSql = wSql || 'EMPR.BDBAIEMP, ';
    wSql = wSql || 'EMPR.BDCODCNAE, ';
    wSql = wSql || 'EMPR.BDNUMEMP, ';
    wSql = wSql || 'EMPR.BDENDEMP, ';
    wSql = wSql || 'EMPR.BDLOGREMP, ';
    wSql = wSql || 'EMPR.BDCEPEMP, ';
    wSql = wSql || 'EMPR.BDDDDEMP, ';
    wSql = wSql || 'EMPR.BDFONEEMP, ';
    wSql = wSql || 'EMP.BDCNPJEMP, ';
    wSql = wSql || 'CAD.BDNOMCOL, ';
    wSql = wSql || 'PAR.BDNOMMAECOL, ';
    wSql = wSql || 'COL.BDDATANASCCOL, ';
    wSql = wSql || 'COL.BDCPFCOL, ';
    wSql = wSql || 'CAD.BDSEXOCOL, ';
    wSql = wSql || 'CAD.BDESTCIVCOL, ';
    wSql = wSql || 'case when coalesce(DOCR.BDCTPSCOL, '''') = '''' and coalesce(DOCR.BDSERIECTPSCOL, '''') = '''' then substring(replace(replace(COL.BDCPFCOL, ''.'', ''''), ''-'', '''') from 1 for 7) else DOCR.BDCTPSCOL end BDCTPSCOL, ';
    wSql = wSql || 'case when coalesce(DOCR.BDCTPSCOL, '''') = '''' and coalesce(DOCR.BDSERIECTPSCOL, '''') = '''' then substring(replace(replace(COL.BDCPFCOL, ''.'', ''''), ''-'', '''') from 8 for 4) else DOCR.BDSERIECTPSCOL end BDSERIECTPSCOL, ';
    wSql = wSql || 'DOCR.BDDSERIECTPSCOL, ';
    wSql = wSql || 'case when coalesce(DOCR.BDCTPSCOL, '''') = '''' and coalesce(DOCR.BDSERIECTPSCOL, '''') = '''' then COL.BDDATACADCOL else DOCR.BDDATAEMICTPSCOL end BDDATAEMICTPSCOL, ';
    wSql = wSql || 'DOCR.BDRGCOL, ';
    wSql = wSql || 'DOCR.BDDATAEMIRGCOL, ';
    wSql = wSql || 'DOCR.BDORGEMIRGCOL, ';
    wSql = wSql || 'DOCR.BDPISCOL, ';
    wSql = wSql || 'CAD.BDLOGRCOL, ';
    wSql = wSql || 'CAD.BDENDCOL, ';
    wSql = wSql || 'CAD.BDNUMCOL, ';
    wSql = wSql || 'CAD.BDBAICOL, ';
    wSql = wSql || 'CAD.BDCEPCOL, ';
    wSql = wSql || 'CAD.BDDDDCOL, ';
    wSql = wSql || 'CAD.BDFONECOL, ';
    wSql = wSql || 'CLA.BDGRUPOCLA BDFILIACAOPREV, ';
    wSql = wSql || 'CLA.BDGRUPOCLA BDAPOSENTADO, ';
    wSql = wSql || 'CID_CAT.BDNOMCID BDNOMCIDACID, ';
    wSql = wSql || 'UF_CAT.BDSIGLAUF BDUFACID, ';
    wSql = wSql || 'CID_EMP.BDNOMCID, ';
    wSql = wSql || 'UF_EMP.BDSIGLAUF, ';
    wSql = wSql || 'CID_COL.BDNOMCID BDNOMECIDCOL, ';
    wSql = wSql || 'UF_COL.BDSIGLAUF BDUFCOL, ';
    wSql = wSql || 'case when coalesce(DOCR.BDCTPSCOL, '''') = '''' and coalesce(DOCR.BDSERIECTPSCOL, '''') = '''' then case when CID_EMP.BDCODUF between 1 and 27 then UF_EMP.BDSIGLAUF when CIDEMPM.BDCODUF between 1 and 27 then UFMAT.BDSIGLAUF else '''' end else UF_CTPS.BDSIGLAUF end BDUFCTPS, ';
    wSql = wSql || 'case when ((CBO_TSIN.BDDESCCBOTSIN is null) or (CBO_TSIN.BDDESCCBOTSIN = '''||''||''')) then CBO.BDDESCCBO else CBO_TSIN.BDDESCCBOTSIN end BDDESCCBO, ';
    wSql = wSql || 'CBO.BDCODCBO, ';
    wSql = wSql || 'COL_CALCDIA.BDSALBASECOL, ';
    wSql = wSql || 'UF_RG.BDSIGLAUF, ';
    wSql = wSql || 'CAD.BDDDDCELCOL, ';
    wSql = wSql || 'CAD.BDCELCOL, ';
    wSql = wSql || 'CALC.BDTIPOCOL, ';
    wSql = wSql || 'CALC.BDHORASMENSAISCOL, ';
    wSql = wSql || 'HIST.BDDTAPOSENT, ';
    wSql = wSql || 'ARQ.BDDATARETORNO, ';
    wSql = wSql || 'CAT.BDRECIBOESOC, ';
    wSql = wSql || 'CAT.BDRECIBORETEXC, ';
    wSql = wSql || 'COALESCE(CAT.BDEXCLUIDO, ''FALSE''), ';
    wSql = wSql || 'CAT.BDCODSITGER ';
    wSql = wSql || 'from (select * from VRH_EMP_TCAT ';

    IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
       BEGIN
         wSql = wSql||' where '||prcodemp;

         IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
           wSql = wSql||' and '||prcodcol;

         IF (COALESCE(prchave, 0) <> 0) THEN
           wSql = wSql||' and BDCHAVE = '||prchave;
         ELSE
           wSql = wSql||' and BDREFCAT = '||prref;
       END
    ELSE
       IF (COALESCE(prchave, 0) <> 0) THEN 
         wSql = wSql||' where BDREFCAT = '||prchave;

    wSql = wSql||') CAT ';

    wSql = wSql || 'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = CAT.BDCODEMP and COL.BDCODCOL = CAT.BDCODCOL) ';
    wSql = wSql || 'left outer join VRH_EMP_TCOL_PARENT PAR on (PAR.BDCODEMP = COL.BDCODEMP and PAR.BDCODCOL = COL.BDCODCOL) ';
    wSql = wSql || 'left outer join VRH_EMP_TCOL_HIST HIST on (HIST.BDCODEMP = COL.BDCODEMP and HIST.BDCODCOL = COL.BDCODCOL) ';
    wSql = wSql || 'left outer join VW_VRH_EMP_TCOLCON_REF COLR on (COLR.BDCODEMP = CAT.BDCODEMP and COLR.BDCODCOL = CAT.BDCODCOL) ';
    wSql = wSql || 'left outer join VRH_EMP_TCOLCON_CAD CAD on (CAD.BDCODEMP = COLR.BDCODEMP and CAD.BDCODCOL = COLR.BDCODCOL and CAD.BDREFCOL = COLR.BDREFCOL) ';
    wSql = wSql || 'left outer join VRH_EMP_TCOLCON_DOCREF DOCR on (DOCR.BDCODEMP = COLR.BDCODEMP and DOCR.BDCODCOL = COLR.BDCODCOL and DOCR.BDREFCOL = COLR.BDREFCOL) ';
    wSql = wSql || 'left outer join VRHF_EMP_TCOL_CALC CALC on (CALC.BDCODEMP = COLR.BDCODEMP and CALC.BDCODCOL = COLR.BDCODCOL and CALC.BDREFCOL = COLR.BDREFCOL) ';
    wSql = wSql || 'left outer join VRH_EMP_TCOLCON_VINC VINC on (VINC.BDCODEMP = COLR.BDCODEMP and VINC.BDCODCOL = COLR.BDCODCOL and VINC.BDREFCOL = COLR.BDREFCOL) ';
    wSql = wSql || 'left outer join TEMPRESAS EMP on (EMP.BDCODEMP = CAT.BDCODEMP) ';
    wSql = wSql || 'left outer join VW_EMPRESAS_REF_ATUAL EMPR on (EMPR.BDCODEMP = CAT.BDCODEMP) ';
    wSql = wSql || 'left outer join VW_TCOLCON_DIA_ATUAL COLDIA on (COLDIA.BDCODEMP = CAT.BDCODEMP and COLDIA.BDCODCOL = CAT.BDCODCOL) ';
    wSql = wSql || 'left outer join VRH_EMP_TCOL_VINCDIA COL_DIAVINC on (COL_DIAVINC.BDCODEMP = COLDIA.BDCODEMP and COL_DIAVINC.BDCODCOL = COLDIA.BDCODCOL and COL_DIAVINC.BDDATACOL = COLDIA.BDDATACOL) ';
    wSql = wSql || 'left outer join VRH_EMP_TCOLCON_CALCDIA COL_CALCDIA on (COL_CALCDIA.BDCODEMP = COLDIA.BDCODEMP and COL_CALCDIA.BDCODCOL = COLDIA.BDCODCOL and COL_CALCDIA.BDDATACOL = COLDIA.BDDATACOL) ';
    wSql = wSql || 'left outer join TCIDADE CID_CAT on (CID_CAT.BDCODCID = CAT.BDCODCID) ';
    wSql = wSql || 'left outer join TUF UF_CAT on (UF_CAT.BDCODUF = CID_CAT.BDCODUF) ';
    wSql = wSql || 'left outer join TCIDADE CID_EMP on (CID_EMP.BDCODCID = EMPR.BDCODCID) ';
    wSql = wSql || 'left outer join TUF UF_EMP on (UF_EMP.BDCODUF = CID_EMP.BDCODUF) ';
    wSql = wSql || 'left outer join TCIDADE CID_COL on (CID_COL.BDCODCID = CAD.BDCODCID) ';
    wSql = wSql || 'left outer join TUF UF_COL on (UF_COL.BDCODUF = CID_COL.BDCODUF) ';
    wSql = wSql || 'left outer join TUF UF_CTPS on (UF_CTPS.BDCODUF = DOCR.BDCODUF) ';
    wSql = wSql || 'left outer join TUF UF_RG on (UF_RG.BDCODUF = DOCR.BDCODUFRG) ';
    wSql = wSql || 'left outer join VRH_FUNCOES_TFUC TFUC on (TFUC.BDCODPLAFUC = COL_DIAVINC.BDCODPLAFUC and TFUC.BDCODTFUC = COL_DIAVINC.BDCODTFUC) ';
    wSql = wSql || 'left outer join VRH_BASE_TCBO CBO on (CBO.BDCODCBO = TFUC.BDCODCBO) ';
    wSql = wSql || 'left outer join VRH_BASE_CBO_TSIN CBO_TSIN on (CBO_TSIN.BDCODCBO = TFUC.BDCODCBO and CBO_TSIN.BDCODCBOTSIN = TFUC.BDCODCBOTSIN) ';
    wSql = wSql || 'left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA) ';
    wSql = wSql || 'left outer join TEMPRESAS EMPM on (EMPM.BDCODEMP = EMP.BDCODMATRIZ) ';
    wSql = wSql || 'left outer join TEMPRESAS_REF EMPRM on (EMPRM.BDCODEMP = EMPM.BDCODEMP and EMPRM.BDREFEMP = (select first 1 BDREFEMP from TEMPRESAS_REF where BDCODEMP = EMPRM.BDCODEMP and BDREFEMP <= ' || :prref || ' order by BDCODEMP desc, BDREFEMP desc)) ';
    wSql = wSql || 'left outer join TCIDADE CIDEMPM on (CIDEMPM.BDCODCID = EMPRM.BDCODCID) ';
    wSql = wSql || 'left outer join TUF UFMAT on (UFMAT.BDCODUF = CIDEMPM.BDCODUF) ';
    wSql = wSql || 'left outer join VRH_ESOCIAL_TARQUIVO ARQ on (ARQ.BDCODIGO = (select max(BDCODIGO) ' ||
                                                                                'from VRH_ESOCIAL_TARQUIVO ' ||
                                                                                'where BDCODEMP = CAT.BDCODEMP and ' ||
                                                                                      'BDCODCOL = CAT.BDCODCOL and ' ||
                                                                                      'BDCHAVECAT = CAT.BDCHAVE and ' ||
                                                                                      'BDCODTIPO = 27) and ' ||
                                                                                'ARQ.BDCODEMP = CAT.BDCODEMP) ';
    wSql = wSql || 'order by CAT.BDCODEMP,CAT.BDCODCOL,CAT.BDCHAVE ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCHAVE,
    :BDCODCID,
    :BDDATAACIDENTE,
    :BDDATAEMISSAO,
    :BDDATAULTIMODIA,
    :BDDATAOBITO,
    :BDEMITENTE,
    :BDNRCAT,
    :BDCATORIGEM,
    :BDTIPOAFAST,
    :BDREGPOLICIAL,
    :BDAFASTAMENTO,
    :BDHORAACIDENTE,
    :BDTIPOCAT,
    :BDLOCALACIDENTE,
    :BDESPLOCALACIDENTE,
    :BDOBJETOCAUSADORACID,
    :BDDESCACIDENTE,
    :BDPARTESATINGIDAS,
    :BDAREAACIDENTE,
    :BDHOUVEOBITO,
    :BDREMUNMENSAL,
    :BDINICIATIVA,
    :BDNOMEMP,
    :BDBAIEMP,
    :BDCODCNAE,
    :BDNUMEMP,
    :BDENDEMP,
    :BDLOGREMP,
    :BDCEPEMP,
    :BDDDDEMP,
    :BDFONEEMP,
    :BDCNPJEMP,
    :BDNOMCOL,
    :BDNOMMAECOL,
    :BDDATANASCCOL,
    :BDCPFCOL,
    :BDSEXOCOL,
    :BDESTCIVCOL,
    :BDCTPSCOL,
    :BDSERIECTPSCOL,
    :BDDSERIECTPSCOL,
    :BDDATAEMICTPSCOL,
    :BDRGCOL,
    :BDDATAEMIRGCOL,
    :BDORGEMIRGCOL,
    :BDPISCOL,
    :BDLOGRCOL,
    :BDENDCOL,
    :BDNUMCOL,
    :BDBAICOL,
    :BDCEPCOL,
    :BDDDDCOL,
    :BDFONECOL,
    :BDFILIACAOPREV,
    :BDAPOSENTADO,
    :BDNOMCIDACID,
    :BDUFACID,
    :BDNOMCID,
    :BDSIGLAUF,
    :BDNOMECIDCOL,
    :BDUFCOL,
    :BDUFCTPS,
    :BDDESCCBO,
    :BDCODCBO,
    :BDSALBASECOL,
    :BDUFRG,
    :BDDDDCELCOL,
    :BDCELCOL,
    :BDTIPOCOL,
    :BDHORASMENSAISCOL,
    :BDDTAPOSENT,
    :BDDATARETORNO,
    :BDRECIBOESOC,
    :BDRECIBORETEXC,
    :BDEXCLUIDO,
    :WCODSITGER
  DO
    BEGIN
      IF ((bdpartesatingidas) IS NULL OR (bdpartesatingidas = '')) THEN
         BEGIN
           bdpartesatingidas = '';

           wsqla = 'select Y.BDCODPCORPOESOC, Y.BDDESCPCORPO, X.BDLATERALIDADE from TCAT_PCORPOATINGIDA Y join VRH_EMP_TCAT_PATINGIDAS X on (X.BDCODPCORPO = Y.BDCODPCORPO and X.BDCODEMP = '||bdcodemp||
                   ' and X.BDCODCOL = '||bdcodcol||' and X.BDCHAVE = '||bdchave||') ';

           FOR EXECUTE STATEMENT wsqla INTO :wcodpcorpoesoc, :wdesc, :bdlateralidade DO
             BEGIN
               IF (bdpartesatingidas <> '') THEN
                  bdpartesatingidas = bdpartesatingidas||', ';

               bdpartesatingidas = bdpartesatingidas|| TRIM(wcodpcorpoesoc) || ' - ' || TRIM(wdesc);
             END
         END

      IF ((bdobjetocausadoracid) IS NULL OR (bdobjetocausadoracid = '')) THEN
         BEGIN
           bdobjetocausadoracid = '';

           wsqla = 'select Y.BDCODAGCAUSAESOC, Y.BDDESCAGCAUSA from TCAT_AGENTECAUSADOR Y join VRH_EMP_TCAT_AGCAUSADOR X on (X.BDCODAGCAUSA = Y.BDCODAGCAUSA and X.BDCODEMP = '||bdcodemp||
                   ' and X.BDCODCOL = '||bdcodcol||' and X.BDCHAVE = '||bdchave||') ';

           FOR EXECUTE STATEMENT wsqla INTO :wcodpcorpoesoc, :wdesc DO
             BEGIN
               IF (bdobjetocausadoracid <> '') THEN
                  bdobjetocausadoracid = bdobjetocausadoracid||', ';

               bdobjetocausadoracid = bdobjetocausadoracid||TRIM(WCODPCORPOESOC) || ' - ' || TRIM(wdesc);
             END
         END

      IF ((WCODSITGER IS NOT NULL) AND (WCODSITGER > 0)) THEN
         BEGIN
           bdsituacaogeradora = '';

           wsqla = 'select Y.BDCODSITGERESOC, Y.BDDESCSITGERACTRAB from TCAT_SITGERACTRAB Y ' ||
                   'where Y.BDCODSITGER = ' ||WCODSITGER;

           FOR EXECUTE STATEMENT wsqla INTO :wcodpcorpoesoc, :wdesc DO
             BEGIN
               IF (bdsituacaogeradora <> '') THEN
                  bdsituacaogeradora = bdsituacaogeradora||', ';

               bdsituacaogeradora = bdsituacaogeradora|| TRIM(wcodpcorpoesoc) || ' - ' || TRIM(wdesc);
             END
         END

      IF (bdtipocol = 2) THEN 
         BEGIN
           bdsalbasecol = bdsalbasecol * bdhorasmensaiscol;
         END

      IF (bdtipocol = 4) THEN
         BEGIN
           SELECT COALESCE(SUM(X.BDSALSHE),0)
           FROM VRH_EMP_TCOL_SHE X
           JOIN (
              SELECT BDCODEMP, BDCODCOL, BDCODSHE, MAX(BDDATASHE) BDDATASHE
              FROM VRH_EMP_TCOL_SHE
              WHERE BDCODEMP = :bdcodemp AND BDCODCOL = :bdcodcol AND BDDATASHE <= :prultimodia
              GROUP BY BDCODEMP, BDCODCOL, BDCODSHE
           ) Y ON (Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDCODSHE = X.BDCODSHE AND Y.BDDATASHE = X.BDDATASHE)
           INTO :wvalue;

           bdsalbasecol = CAST((wvalue * bdhorasmensaiscol) AS NUMERIC(15,6));
           -- DSR
           bdsalbasecol = CAST((bdsalbasecol + (bdsalbasecol / 6)) AS NUMERIC(15,6));
         END

      IF ((bdaposentado = 4) OR (bddtaposent IS NOT NULL)) THEN
        bdaposentado = 1;
      ELSE
        bdaposentado = 0;

      select BDDATAINISST from VRH_ESOCIAL_TFASEAMENTO where BDCODEMP = :BDCODEMP into :WDATAINISST;
      if (not ((WDATAINISST is not null) and (BDDATAACIDENTE >= WDATAINISST) and ((BDRECIBOESOC is null) or (BDRECIBOESOC = '')) )) then
      SUSPEND;
    END

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

/* Restore proc. body: VRH_SP_SERV_TERC */
create or alter procedure VRH_SP_SERV_TERC (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRSERV varchar(1000),
    PRCODCLA varchar(1000),
    PRREF integer,
    PRINICIO date,
    PRFIM date,
    PRCOLCON smallint,
    PRCOLCON_DOC smallint,
    PRCOLCON_VINC smallint,
    PRCOLCON_BANCO smallint,
    PRCOLCON_CALC smallint,
    PRCOLCON_FGTSGPS smallint,
    PRCOLCON_MVINC smallint,
    PRCOLCON_DIA smallint,
    PRLOTEIMPORTACAO integer = 0)
returns (
    BDCODSERV integer,
    BDDATASERV date,
    BDDATAPAGSERV date,
    BDHORASERV time,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODMCAG integer,
    BDCODCID integer,
    BDCODCSEG integer,
    BDREFCSEG integer,
    BDCODCIDNASC integer,
    BDCODUF integer,
    BDNOMCOL DM_BDNOMTER,
    BDLOGRCOL varchar(15),
    BDENDCOL DM_BDENDERECO,
    BDNUMCOL DM_NUMEND,
    BDCOMPLCOL DM_BDCOMPENDERECO,
    BDBAICOL DM_BDBAIRRO,
    BDCEPCOL varchar(9),
    BDDDDCOL integer,
    BDFONECOL DM_BDTELEFONE,
    BDCELCOL DM_BDTELEFONE,
    BDEMAILCOL DM_BDEMAIL,
    BDSEXOCOL integer,
    BDDATANASCCOL date,
    BDDATACADCOL date,
    BDGRAUINSTCOL integer,
    BDESTCIVCOL integer,
    BDDATAADMCOL date,
    BDDATAADICCOL date,
    BDRGCOL varchar(13),
    BDORGEMIRGCOL DM_ORGAOEMISSOR,
    BDDATAEMIRGCOL date,
    BDCPFCOL varchar(14),
    BDRESERVISTACOL varchar(16),
    BDPISCOL varchar(14),
    BDDATAEMIPISCOL date,
    BDCODUF_COL_DOC integer,
    BDTITELEICOL varchar(13),
    BDZONAELEICOL integer,
    BDSECAOELEICOL integer,
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDDATAEMICTPSCOL date,
    BDCNHCOL varchar(11),
    BDVENCCNHCOL date,
    BDCATCNHCOL varchar(2),
    BDCODCID_HIST integer,
    BDCODPAIS integer,
    BDNATURALIZADOCOL varchar(5),
    BDDATACHEBRASILCOL date,
    BDCODCIDNASCCONJ integer,
    BDNOMPAICOL varchar(70),
    BDNOMMAECOL varchar(70),
    BDNOMCONJCOL varchar(70),
    BDDATANASCCONJCOL date,
    BDCORCOL integer,
    BDCABELOSCOL integer,
    BDOLHOSCOL integer,
    BDALTURACOL numeric(15,6),
    BDPESOCOL numeric(15,6),
    BDSINAISCOL varchar(5),
    BDDEFFISICOCOL integer,
    BDTIPOSANGUECOL integer,
    BDNROCONSPROCOL varchar(20),
    BDSIGLACONSPROCOL varchar(5),
    BDCODCCMPROCOL varchar(15),
    BDCODCLA integer,
    BDGRUPOCLA integer,
    BDCODMEN integer,
    BDCODSINTRAB integer,
    BDCODBAN integer,
    BDCODAG integer,
    BDCTADEPCOL varchar(15),
    BDDIGCTADEPCOL varchar(2),
    BDTIPOCTACOL integer,
    BDMODOPAGTOCOL integer,
    BDCARTAOSALCOL varchar(7),
    BDFORMAPAGTOCOL integer,
    BDNRODEPIRCOL integer,
    BDBASEIRRFADCOL numeric(15,6),
    BDVALORPREVPRIVNCOL numeric(15,6),
    BDVALORPREVPRIV13COL numeric(15,6),
    BDDATAOPCAOFGTSCOL date,
    BDCTAFGTSCOL varchar(11),
    BDCATEGORIACOL integer,
    BDPERCFGTSCOL numeric(15,6),
    BDOCORRENCIACOL integer,
    BDPERCRATCOL numeric(15,6),
    BDPERCDESCFPASCOL numeric(15,6),
    BDBASEINSSNCOL numeric(15,6),
    BDVALORINSSNCOL numeric(15,6),
    BDBASEIRRFNCOL numeric(15,6),
    BDVALORIRRFNCOL numeric(15,6),
    BDBASEINSS13COL numeric(15,6),
    BDVALORINSS13COL numeric(15,6),
    BDBASEIRRF13COL numeric(15,6),
    BDVALORIRRF13COL numeric(15,6),
    BDTIPOADMCOL integer,
    BDNATUOCUPCOL integer,
    BDDATAINIAQUICOL date,
    BDSALINICOL numeric(15,6),
    BDDIASPRAZO1COL integer,
    BDDATAFIMPRAZO1COL date,
    BDDIASPRAZO2COL integer,
    BDDATAFIMPRAZO2COL date,
    BDDESCCONTSINCOL varchar(5),
    BDVINCEMPCOL integer,
    BDALVARACOL varchar(5),
    BDSINDICALIZADOCOL varchar(5),
    BDREGIMEPARCIALCOL varchar(5),
    BDFICHAREGCOL varchar(12),
    BDLIVROREGCOL varchar(10),
    BDNROFOLHAREGCOL integer,
    BDTIPOCOL integer,
    BDHORASMENSAISCOL numeric(15,6),
    BDHORASSEMANAISCOL numeric(15,6),
    BDHORASDIARIASCOL numeric(15,6),
    BDPERCINSALUBCOL numeric(15,6),
    BDINCIDINSALUBCOL integer,
    BDPERCPERCULCOL numeric(15,6),
    BDINCIDPERICULCOL integer,
    BDPERCNOTURNOCOL numeric(15,6),
    BDINCIDNOTURNOCOL integer,
    BDNRODEPSALFAMCOL integer,
    BDIGNORAFALTASFERCOL varchar(5),
    BDCALCADIANTACOL varchar(5),
    BDNAOARREDONDARCOL varchar(5),
    BDIMPETIQUETACOL varchar(5),
    BDCALCDSRRVCOL varchar(5),
    BDCALCDSRHECOL varchar(5),
    BDCALCDSRSALCOL varchar(5),
    BDCALCVALTRANSCOL varchar(5),
    BDCALCVALREFCOL varchar(5),
    BDOBSCOL blob sub_type 0 segment size 80,
    BDCODGPS integer,
    BDDESCINSSDOIRCOL varchar(5),
    BDCODMAS integer,
    BDSALBASECOL numeric(15,6),
    BDCODCBO integer,
    BDCODQH integer,
    BDCODPRES integer,
    BDDATARESCISAO date,
    BDDATAAVPREVIO date,
    BDDATAHOM date,
    BDDATAPAGRESCISAO date,
    BDSALDOFGTS numeric(15,6),
    BDCALCFGTSMESANT varchar(5),
    BDMAIORREMUNERACAO numeric(15,6),
    BDCHAVEINDENTIFICACAO varchar(49),
    BDDATAPAGGRFC date,
    BDREPOSICAOVAGA varchar(5),
    BDDISSIDIO varchar(5),
    BDDATADISSIDIO date,
    BDDESCANSOINDENIZADO varchar(5),
    BDCODMFGRESC integer,
    BDCODSAQUERESC integer,
    BDCODMRAISRESC integer,
    BDCODMCAGRESC integer,
    BDDESCPRES varchar(110),
    BDINIPRES integer,
    BDJCPRES varchar(5),
    BDAVPREPRES integer,
    BDGRRFPRES integer,
    BDESTPRES varchar(5),
    BDINDFER13 varchar(5),
    BDTERMCONTRPRES varchar(5),
    BDMULTAPRES varchar(5),
    BDDIASAVPREPRES integer,
    BDDIASPAGPRES integer,
    BDCODSEFMFGRESC varchar(5),
    BDDESCMFGRESC varchar(255),
    BDDESCSAQUERESC varchar(60),
    BDDESCMRAISRESC varchar(255),
    BDDESCMCAGEDRESC varchar(255),
    BDCODEMPDESTTRAN integer,
    BDCODPTRAN integer,
    BDCODCOLTRANS integer,
    BDDATATRANS date,
    BDCODMCAGENTTRANS integer,
    BDCODMCAGSAITRANS integer,
    BDCODMFGTRANS integer,
    BDCODMRAISTRANS integer,
    BDDESCPTRANS varchar(60),
    BDCODSEFMFGTRANS varchar(5),
    BDDESCMFGTRANS varchar(255),
    BDDESCRAISTRANS varchar(255),
    BDDESCMCAGEDENTTRANS varchar(255),
    BDDESCMCAGEDSAITRANS varchar(255),
    BDCONTRCOL integer,
    BDPERTRANSPINSSTER numeric(15,6),
    BDPERTRANSPIRTER numeric(15,6),
    BDACORDOINSSTERC DM_BOOLEAN,
    BDPERCIRTERC numeric(18,6),
    BDPIRTERC DM_BOOLEAN,
    BDCODMULTVINC integer,
    BDCATEGORIAESOCIAL integer,
    BDTRIBUTACAOEXTERIOR integer)
as
declare variable WCAM varchar(20000);
declare variable WWHE varchar(10000);
declare variable WV varchar(30);
declare variable WI varchar(3);
declare variable WD varchar(30);
declare variable WB varchar(30);
declare variable WN varchar(30);
declare variable WTRUE varchar(5);
declare variable WDATA varchar(10);
declare variable WCODUSU integer;
declare variable WTABELA varchar(300);
declare variable WAPELIDO varchar(300);
declare variable WJOINREF varchar(3200);
BEGIN
   -- Seta a competencia atual.
   -- Algumas Views utilizam essas variaveis de contexto para filtrar e agrupar tabelas.
   wdata = CAST(prref AS VARCHAR(6));
   wdata = SUBSTRING(wdata FROM 5 FOR 2)||'-01-'||SUBSTRING(wdata FROM 1 FOR 4);
   EXECUTE PROCEDURE sp_seta_competencia(prref, CAST(wdata AS DATE), prfim);

   /* Retorna o usuario logado */
   FOR SELECT BDCODUSU FROM sp_get_usuario
     INTO
       :wcodusu
     DO

   wtrue = '(0=0)';
   prcodemp = COALESCE(prcodemp,wtrue);
   prcodcol = COALESCE(prcodcol,wtrue);
   prcodcla = COALESCE(prcodcla,wtrue);

   wv = ', CAST(NULL AS varchar(1))';
   wi = ', 0';
   wd = ', CAST(NULL AS DATE)';
   wb = ', CAST(NULL AS BLOB)';
   wn = ', CAST(NULL AS NUMERIC(15,6))';

   wcam = 'select TSERV.BDCODSERV, TSERV.BDDATASERV, TSERV.BDDATAPAGSERV, TSERV.BDHORASERV, TSERV.BDCODEMP, TSERV.BDCODTER, COLCON.BDTRIBUTACAOEXTERIOR ';

   -- CAMPOS
   IF (:PRCOLCON = 0) THEN
      wcam = wcam||wi||wi||wi||wi||
                   wi||wi||wv||wv||wv||
                   wv||wv||wv||wv||wi||
                   wv||wv||wv||wi||
                   wd||wd||wi||wi||
                   wd||wd;
   ELSE
      wcam = wcam||wi||', COLCON.BDCODCID'||wi||wi||
                   ', COLCON.BDCODCIDNASCTER'||wi||', COLCON.BDNOMTER, COLCON.BDLOGRTER, COLCON.BDENDTER '||
                   ', COLCON.BDNUMTER, COLCON.BDCOMPLTER, SUBSTRING(COLCON.BDBAITER FROM 1 FOR 50), COLCON.BDCEPTER, COLCON.BDDDDTER '||
                   ', COLCON.BDFONETER, COLCON.BDCELTER, COLCON.BDEMAILTER, COLCON.BDSEXOTER '||
                   ', COLCON.BDDATANASCTER, COLCON.BDDATACADTER, TTERCREF.BDGRAUINSTTER, TTERCREF.BDESTCIVTER '||
                   wd||wd;

   IF (:PRCOLCON_DOC = 0) THEN
      wcam = wcam||wv||wv||wd||
                   wv||wv||wv||wd;
   ELSE
      wcam = wcam||', COLCON_DOCREF.bdrgter, COLCON_DOCREF.BDORGEMIRGTER, COLCON_DOCREF.BDDATAEMIRGTER '||
                   ', case ' ||
                   ' when (char_length(TERCRH.BDCPFMEITER) = 14) then TERCRH.BDCPFMEITER '||
                   ' else TER.BDCGCTER ' ||
                   ' end BDCPFTER, COLCON_DOC.BDRESERVISTATER, COLCON_DOCREF.BDPISTER'||wd;

   /*Dados nao existentes no terceiro
   if (:PRCOL_DOC = 0) then*/
      wcam = wcam||wi||wv||
                   wi||wi||wi||wi||
                   wv||wd||wv||wd||
                   wv;

/* Dados nao existentes para o terceiro
   if (:PRCOL_HIST = 0) then*/
      wcam = wcam||wi||wi||wv||wd;

--   if (:PRCOL_PARENT = 0) then
      wcam = wcam||wi||wv||wv||wv||wd;

--   if (:PRCOL_FIS = 0) then
      wcam = wcam||wi||wi||wi||wn||wn||wv||wi||wi;

--   if (:PRCON_DOC = 0) then
   IF (:PRCOLCON_DOC = 0) THEN
      wcam = wcam||wv||wv||wv;
   ELSE
      wcam = wcam||', COLCON_DOCREF.BDNROCONSPROTER, COLCON_DOCREF.BDSIGLACONSPROTER, COLCON_DOCREF.BDCODCCMPROTER';

   IF (:PRCOLCON_VINC = 0 AND :PRCODCLA IS NULL) THEN
      wcam = wcam||wi||wi;
   ELSE
      wcam = wcam||', coalesce(COLCON_VINC.BDCODCLA, COLCON_VINC2.BDCODCLA, 0), coalesce(CLASSE.BDGRUPOCLA, CLASSE2.BDGRUPOCLA, 0)';

   /*SINDICATO terceiro nao possui*/
   wcam = wcam||wi||wi;

   IF (:PRCOLCON_BANCO = 0) THEN
      wcam = wcam||wi||wi||wv||wv||wi||wi||wv;
   ELSE
      wcam = wcam||', COLCON_BANCO.BDCODBAN, COLCON_BANCO.BDCODAG, COLCON_BANCO.BDCTADEPTER, COLCON_BANCO.BDDIGCTADEPTER '||
                   ', COLCON_BANCO.BDTIPOCTATER, COLCON_BANCO.BDMODOPAGTOTER, COLCON_BANCO.BDCARTAOSALTER';

   IF (:PRCOLCON_CALC = 0) THEN
      wcam = wcam||wi||wi||wn||wn||wn;
   ELSE
      wcam = wcam||wi||', TTERCREF.BDNRODEPIRTER'||wn||wn||wn;

   /*Terceiro nao tem dados de fgts apenas de gps*/
   IF (:PRCOLCON_FGTSGPS = 0) THEN
      wcam = wcam||wd||wv||wi||wn||wi||wn||wn;
   ELSE
      wcam = wcam||wd||wv||', COLCON_FGTSGPS.BDCATEGORIATER '||wn||
                   ', COLCON_FGTSGPS.BDOCORRENCIATER '||
                   ', COLCON_FGTSGPS.BDPERCRATTER'||wn;

   IF (:PRCOLCON_MVINC = 0) THEN
      wcam = wcam||wn||wn||wn||wn||wn||wn||wn||wn;
   ELSE
      wcam = wcam||', COLCON_MVINC.BDBASEINSSNTER, COLCON_MVINC.BDVALORINSSNTER, COLCON_MVINC.BDBASEIRRFNTER '||
                   ', COLCON_MVINC.BDVALORIRRFNTER'||wn||wn||
                   wn||wn;

--   if (:PRCOL_ADM = 0) then
      wcam = wcam||wi||wi||wd||wn||wi||wd||wi||wd||wv||wi||wv||wv||wv||wv||wv||wi;

--   if (:PRCOL_CALC = 0) then
      wcam = wcam||wi||wn||wn||wn||wn||wi||wn||wi||wn||wi||wi||wv||wv||wv||wv||wv||wv||wv||wv||wv;

--   if (:PRCOL_HISTF = 0) then
      wcam = wcam||wb;

--   if (:PRCON_VINC = 0) then
      wcam = wcam||wi||wv;

   IF (:prcolcon_dia = 0) THEN
      wcam = wcam||wi||wn||wi||wv||wn||wv||wi;
   ELSE
      wcam = wcam||wi||', TSERV.bdvalorserv, COLCON_VINC.BDCODCBO, COLCON_VINC.BDACORDOINSSTERC, COLCON_VINC.BDPERCIRTERC, COLCON_VINC.BDPIRTERC'||wi; --Sol. 14603 - Marcelo B. M. - 26/08/2016


   /* Tabela de Rescisao nao existe para terceiros*/
    wcam = wcam||wi||wd||wd||wd||wd||
                 wn||wv||wn||wv||
                 wd||wv||wv||wd||wv;

    /* Motivos de rescisao nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wi||wv||wi||
                 wv||wi||wi||wv||wv||wv||
                 wv||wi||wi||
                 wv||wv||
                 wv||
                 wv||
                 wv;


   /* Tabela de Transferencias nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wd;

    /* Motivos de transferencia nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wi||wv||
                 wv||wv||
                 wv||
                 wv||
                 wv;

   wcam = wcam||', 2';

   /*Terceiro nao tem dados de fgts apenas de gps*/
   IF (:PRCOLCON_FGTSGPS = 0) THEN
      wcam = wcam||wn||wn||', CAST(NULL AS INTEGER) ';
   ELSE
      wcam = wcam||', COLCON_FGTSGPS.BDPERTRANSPINSSTER, COLCON_FGTSGPS.BDPERTRANSPIRTER, COLCON_FGTSGPS.BDCODMULTVINC, COLCON_FGTSGPS.BDCATEGORIAESOCIAL ';

   -- TABELAS
   wtabela = 'vrh_base_tterc_ref';
   WAPELIDO = 'TTERCREF.';
   wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
                ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= (select bdaaaamm from aaaamm(TSERV.bddataserv)))';

   wcam = wcam||' from vrh_base_tservterc TSERV ';
   wcam = wcam||' left outer join vrh_base_tterc COLCON on (COLCON.bdcodter = TSERV.bdcodter) ';
   wcam = wcam||' left outer join VRH_BASE_TTERC_REF TTERCREF on (TTERCREF.bdcodter = TSERV.bdcodter'||wjoinref||') ';

--   IF (:PRCOLCON_DOC <> 0) THEN
--      wcam = wcam||' left outer join vw_VRH_BASE_TTERC_DOC COLCON_DOC on (COLCON_DOC.bdcodter = COLCON.bdcodter) ';
   IF (:PRCOLCON_DOC <> 0) THEN
      BEGIN
        wcam = wcam||' left outer join VRH_BASE_TTERC_DOCREF COLCON_DOCREF ON (COLCON_DOCREF.bdcodter = TSERV.bdcodter and ';
        wcam = wcam||'                                 COLCON_DOCREF.bdrefterc = (select max(Y.BDREFTERC) from VRH_BASE_TTERC_DOCREF Y ';
        wcam = wcam||'                                                            where Y.BDCODTER = COLCON_DOCREF.BDCODTER and';
        wcam = wcam||'                                                            Y.BDREFTERC <= (select BDAAAAMM from AAAAMM(TSERV.BDDATASERV)))) ';
        wcam = wcam||' left outer join vrh_base_tterc_doc COLCON_DOC ON (COLCON_DOC.bdcodter = TSERV.bdcodter)';
        wcam = wcam||' left outer join TTERCEIRO TER ON (TER.bdcodter = TSERV.bdcodter)';
        wcam = wcam||' left outer join TTERCEIRO_rh TERCRH ON (TERCRH.bdcodter = TSERV.bdcodter) ';
      END



   IF (:PRCOLCON_VINC = 1 OR :PRCODCLA IS NOT NULL)  THEN
      BEGIN
        wtabela = 'VRH_BASE_TTERC_VINC';
        WAPELIDO = 'COLCON_VINC.';
        wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
                    ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= (select bdaaaamm from aaaamm(TSERV.bddataserv)))';

        wcam = wcam||' left outer join VRH_BASE_TTERC_VINC COLCON_VINC '||
                         'on (COLCON_VINC.BDCODTER = TSERV.bdcodter'||wjoinref||') ';

        -- Grupo da Classe
        wcam = wcam||' left outer join VRH_BASE_TCLASSE CLASSE '||
                            'on (CLASSE.BDCODCLA = COLCON_VINC.BDCODCLA) ';


        wtabela = 'VRH_BASE_TTERC_VINC';
        WAPELIDO = 'COLCON_VINC2.';
        wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MIN(Y.bdrefterc) from '||wtabela||
                    ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc > (select bdaaaamm from aaaamm(TSERV.bddataserv)))';

        wcam = wcam||' left outer join VRH_BASE_TTERC_VINC COLCON_VINC2 '||
                         'on (COLCON_VINC2.BDCODTER = COLCON.bdcodter'||wjoinref||') ';

        -- Grupo da Classe
        wcam = wcam||' left outer join VRH_BASE_TCLASSE CLASSE2 '||
                            'on (CLASSE2.BDCODCLA = COLCON_VINC2.BDCODCLA) ';
      END

   IF (:PRCOLCON_BANCO = 1) THEN
      BEGIN
        wtabela = 'VRHF_BASE_TTERC_BANCO';
        WAPELIDO = 'COLCON_BANCO.';
        wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
                    ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= (select bdaaaamm from aaaamm(TSERV.bddataserv)))';

        wcam = wcam||' left outer join VRHF_BASE_TTERC_BANCO '||
                            'COLCON_BANCO on (COLCON_BANCO.BDCODter = COLCON.bdcodter'||wjoinref||') ';
      END

   IF (:PRCOLCON_FGTSGPS = 1) THEN
      BEGIN
        wtabela = 'VRHF_BASE_TTERC_FGTSGPS';
        WAPELIDO = 'COLCON_FGTSGPS.';
        wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
                    ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= (select bdaaaamm from aaaamm(TSERV.bddataserv)))';

        wcam = wcam||' left outer join VRHF_BASE_TTERC_FGTSGPS '||
                            'COLCON_FGTSGPS on (COLCON_FGTSGPS.BDCODter = COLCON.bdcodter'||wjoinref||') ';
      END

   IF (:PRCOLCON_MVINC = 1) THEN
      BEGIN
        wtabela = 'VRHF_BASE_TTERC_MVINC';
        WAPELIDO = 'COLCON_MVINC.';
        wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
                    ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= (select bdaaaamm from aaaamm(TSERV.bddataserv)))';

        wcam = wcam||' left outer join VRHF_BASE_TTERC_MVINC '||
                            'COLCON_MVINC on (COLCON_MVINC.BDCODTER = TSERV.BDCODTER and COLCON_MVINC.BDCODEMP = TSERV.BDCODEMP'||wjoinref||') ';
      END

   -- WHERE
   wwhe = '';
   IF (:prCODEMP IS NOT NULL) THEN
      BEGIN
        wwhe = prcodemp;
      END

   IF ((:prserv IS NOT NULL) AND (prserv <> '')) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||prserv;
      END
   ELSE
      BEGIN
        IF ((:prfim IS NOT NULL) AND (:prinicio IS NOT NULL)) THEN
           BEGIN
              IF (wwhe <> '') THEN
                 wwhe = wwhe||' and ';
    
              wwhe = wwhe||'tserv.bddataserv >= '''||prinicio||'''';
              wwhe = wwhe||' and ';
              wwhe = wwhe||'tserv.bddataserv <= '''||prfim||'''';
           END
      END

   IF (:prCODCOL IS NOT NULL) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';
        wwhe = wwhe||prcodcol;

      END

   IF (:PRCODCLA IS NOT NULL) THEN
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';
        wwhe = wwhe||prcodcla;
      END

  IF (:PRLOTEIMPORTACAO <> 0) THEN   /*204881 Antonio J Brogni 14/06/2024*/
      BEGIN
        IF (wwhe <> '') THEN
            wwhe = wwhe||' and ';

        wwhe = wwhe||' TSERV.BDLOTEIMPORTACAO = '||prloteimportacao ;
      END

  /* filtra as empresas por usuario */
  IF (wcodusu IS NOT NULL AND wcodusu <> 0) THEN
     BEGIN
       IF (wwhe <> '') THEN
          wwhe = wwhe||' and ';

       wwhe = wwhe||'((exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||') and '||
                        'exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||' and Y.BDCODEMP = TSERV.BDCODEMP)) '||
                       'or '||
                       '(not exists (select Y.BDCODUSU '||
                                'from TEMPRESA_USUARIO Y '||
                                'where Y.BDCODUSU = '||wcodusu||'))'||
                       ') ';
     END

   IF ((wwhe <> '') AND (:wwhe IS NOT NULL)) THEN
      wwhe = ' where '||wwhe;
      
   wcam = wcam||wwhe;

   wcam = wcam||' order by TSERV.BDCODEMP, TSERV.BDCODTER, TSERV.BDDATASERV, TSERV.BDHORASERV';

   FOR EXECUTE STATEMENT wcam
      INTO :BDCODSERV, BDDATASERV, BDDATAPAGSERV, BDHORASERV,
            BDCODEMP,
           -- VRH_EMP_TCOLCON
           :BDCODCOL, :BDTRIBUTACAOEXTERIOR, :BDCODMCAG, :BDCODCID, :BDCODCSEG, :BDREFCSEG,
           :BDCODCIDNASC, :BDCODUF, :BDNOMCOL, :BDLOGRCOL, :BDENDCOL,
           :BDNUMCOL, :BDCOMPLCOL, :BDBAICOL, :BDCEPCOL, :BDDDDCOL,
           :BDFONECOL, :BDCELCOL, :BDEMAILCOL, :BDSEXOCOL,
           :BDDATANASCCOL, :BDDATACADCOL, :BDGRAUINSTCOL, :BDESTCIVCOL,
           :BDDATAADMCOL, :BDDATAADICCOL,

           :BDRGCOL, :BDORGEMIRGCOL, :BDDATAEMIRGCOL, :BDCPFCOL,
           :BDRESERVISTACOL, :BDPISCOL, :BDDATAEMIPISCOL,

           :BDCODUF_COL_DOC, :BDTITELEICOL, :BDZONAELEICOL,
           :BDSECAOELEICOL, :BDCTPSCOL, :BDSERIECTPSCOL, :BDDSERIECTPSCOL, :BDDATAEMICTPSCOL,
           :BDCNHCOL, :BDVENCCNHCOL, :BDCATCNHCOL,

           :BDCODCID_HIST, :BDCODPAIS, :BDNATURALIZADOCOL, :BDDATACHEBRASILCOL,

           :BDCODCIDNASCCONJ, :BDNOMPAICOL, :BDNOMMAECOL, :BDNOMCONJCOL, :BDDATANASCCONJCOL,

           :BDCORCOL, :BDCABELOSCOL, :BDOLHOSCOL, :BDALTURACOL,:BDPESOCOL, :BDSINAISCOL,
           :BDDEFFISICOCOL, :BDTIPOSANGUECOL,

           :BDNROCONSPROCOL, :BDSIGLACONSPROCOL, :BDCODCCMPROCOL,

           :BDCODCLA, :BDGRUPOCLA,

           :BDCODMEN, :BDCODSINTRAB,

           :BDCODBAN, :BDCODAG, :BDCTADEPCOL, :BDDIGCTADEPCOL, :BDTIPOCTACOL, :BDMODOPAGTOCOL, :BDCARTAOSALCOL,

           :BDFORMAPAGTOCOL, :BDNRODEPIRCOL, :BDBASEIRRFADCOL, :BDVALORPREVPRIVNCOL, :BDVALORPREVPRIV13COL,

           :BDDATAOPCAOFGTSCOL, :BDCTAFGTSCOL, :BDCATEGORIACOL, :BDPERCFGTSCOL,
           :BDOCORRENCIACOL, :BDPERCRATCOL, :BDPERCDESCFPASCOL,

           :BDBASEINSSNCOL, :BDVALORINSSNCOL, :BDBASEIRRFNCOL, :BDVALORIRRFNCOL, :BDBASEINSS13COL,
           :BDVALORINSS13COL, :BDBASEIRRF13COL, :BDVALORIRRF13COL,

           :BDTIPOADMCOL, :BDNATUOCUPCOL, :BDDATAINIAQUICOL, :BDSALINICOL, :BDDIASPRAZO1COL,
           :BDDATAFIMPRAZO1COL, :BDDIASPRAZO2COL, :BDDATAFIMPRAZO2COL, :BDDESCCONTSINCOL, :BDVINCEMPCOL,
           :BDALVARACOL, :BDSINDICALIZADOCOL, :BDREGIMEPARCIALCOL, :BDFICHAREGCOL, :BDLIVROREGCOL,
           :BDNROFOLHAREGCOL,

           :BDTIPOCOL, :BDHORASMENSAISCOL, :BDHORASSEMANAISCOL, :BDHORASDIARIASCOL,
           :BDPERCINSALUBCOL , :BDINCIDINSALUBCOL, :BDPERCPERCULCOL, :BDINCIDPERICULCOL,
           :BDPERCNOTURNOCOL, :BDINCIDNOTURNOCOL, :BDNRODEPSALFAMCOL, :BDIGNORAFALTASFERCOL,
           :BDCALCADIANTACOL, :BDNAOARREDONDARCOL, :BDIMPETIQUETACOL, :BDCALCDSRRVCOL,
           :BDCALCDSRHECOL, :BDCALCDSRSALCOL, :BDCALCVALTRANSCOL, :BDCALCVALREFCOL,

           :BDOBSCOL,

           :BDCODGPS, :BDDESCINSSDOIRCOL,

           :BDCODMAS, :BDSALBASECOL,
           :BDCODCBO, :BDACORDOINSSTERC, :BDPERCIRTERC, :BDPIRTERC, :BDCODQH,  --Sol. 14603 - Marcelo B. M. - 26/08/2016

           -- Rescisao
           :BDCODPRES,
           :BDDATARESCISAO,
           :BDDATAAVPREVIO,
           :BDDATAHOM,
           :BDDATAPAGRESCISAO,
           :BDSALDOFGTS,
           :BDCALCFGTSMESANT,
           :BDMAIORREMUNERACAO,
           :BDCHAVEINDENTIFICACAO,
           :BDDATAPAGGRFC,
           :BDREPOSICAOVAGA,
           :BDDISSIDIO,
           :BDDATADISSIDIO,
           :BDDESCANSOINDENIZADO,
           :BDCODMFGRESC,
           :BDCODSAQUERESC,
           :BDCODMRAISRESC,
           :BDCODMCAGRESC,
           :BDDESCPRES,
           :BDINIPRES,
           :BDJCPRES,
           :BDAVPREPRES,
           :BDGRRFPRES,
           :BDESTPRES,
           :BDINDFER13,
           :BDTERMCONTRPRES,
           :BDMULTAPRES,
           :BDDIASAVPREPRES,
           :BDDIASPAGPRES,
           :BDCODSEFMFGRESC,
           :BDDESCMFGRESC,
           :BDDESCSAQUERESC,
           :BDDESCMRAISRESC,
           :BDDESCMCAGEDRESC,

           --Transferencia
           :BDCODEMPDESTTRAN,
           :BDCODPTRAN,
           :BDCODCOLTRANS,
           :BDDATATRANS,
           :BDCODMCAGENTTRANS,
           :BDCODMCAGSAITRANS,
           :BDCODMFGTRANS,
           :BDCODMRAISTRANS,
           :BDDESCPTRANS,
           :BDCODSEFMFGTRANS,
           :BDDESCMFGTRANS,
           :BDDESCRAISTRANS,
           :BDDESCMCAGEDENTTRANS,
           :BDDESCMCAGEDSAITRANS,
           :BDCONTRCOL,
           :BDPERTRANSPINSSTER,
           :BDPERTRANSPIRTER,
           :BDCODMULTVINC,
           :BDCATEGORIAESOCIAL
           DO

    SUSPEND;

   EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^


/* Restore proc. body: VRH_SP_SERV_TERC_MANUAL */
create or alter procedure VRH_SP_SERV_TERC_MANUAL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRSERV integer,
    PRDATA date,
    PRREF integer,
    PRDATAPAG date,
    PRHORA varchar(10),
    PRVALOR numeric(15,2),
    PRDATACONTABILIZACAO date)
returns (
    BDCODSERV integer,
    BDDATASERV date,
    BDDATAPAGSERV date,
    BDDATACONTABILIZACAO date,
    BDHORASERV time,
    BDCODEMP integer,
    BDCODCOL integer,
    BDTRIBUTACAOEXTERIOR integer,
    BDCODMCAG integer,
    BDCODCID integer,
    BDCODCSEG integer,
    BDREFCSEG integer,
    BDCODCIDNASC integer,
    BDCODUF integer,
    BDNOMCOL DM_BDNOMCOL,
    BDLOGRCOL DM_LOGRADOURO,
    BDENDCOL DM_BDENDERECO,
    BDNUMCOL DM_NUMEND,
    BDCOMPLCOL DM_BDCOMPENDERECO,
    BDBAICOL DM_BDBAIRRO,
    BDCEPCOL varchar(9),
    BDDDDCOL integer,
    BDFONECOL DM_BDTELEFONE,
    BDCELCOL DM_BDTELEFONE,
    BDEMAILCOL DM_BDEMAIL,
    BDSEXOCOL integer,
    BDDATANASCCOL date,
    BDDATACADCOL date,
    BDGRAUINSTCOL integer,
    BDESTCIVCOL integer,
    BDDATAADMCOL date,
    BDDATAADICCOL date,
    BDRGCOL varchar(13),
    BDORGEMIRGCOL DM_ORGAOEMISSOR,
    BDDATAEMIRGCOL date,
    BDCPFCOL varchar(14),
    BDRESERVISTACOL varchar(16),
    BDPISCOL varchar(14),
    BDDATAEMIPISCOL date,
    BDCODUF_COL_DOC integer,
    BDTITELEICOL varchar(13),
    BDZONAELEICOL integer,
    BDSECAOELEICOL integer,
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDDATAEMICTPSCOL date,
    BDCNHCOL varchar(11),
    BDVENCCNHCOL date,
    BDCATCNHCOL varchar(2),
    BDCODCID_HIST integer,
    BDCODPAIS integer,
    BDNATURALIZADOCOL varchar(5),
    BDDATACHEBRASILCOL date,
    BDCODCIDNASCCONJ integer,
    BDNOMPAICOL varchar(70),
    BDNOMMAECOL varchar(70),
    BDNOMCONJCOL varchar(70),
    BDDATANASCCONJCOL date,
    BDCORCOL integer,
    BDCABELOSCOL integer,
    BDOLHOSCOL integer,
    BDALTURACOL numeric(15,6),
    BDPESOCOL numeric(15,6),
    BDSINAISCOL varchar(5),
    BDDEFFISICOCOL integer,
    BDTIPOSANGUECOL integer,
    BDNROCONSPROCOL varchar(20),
    BDSIGLACONSPROCOL varchar(5),
    BDCODCCMPROCOL varchar(15),
    BDCODCLA integer,
    BDGRUPOCLA integer,
    BDCODMEN integer,
    BDCODSINTRAB integer,
    BDCODBAN integer,
    BDCODAG integer,
    BDCTADEPCOL varchar(15),
    BDDIGCTADEPCOL varchar(2),
    BDTIPOCTACOL integer,
    BDMODOPAGTOCOL integer,
    BDCARTAOSALCOL varchar(7),
    BDFORMAPAGTOCOL integer,
    BDNRODEPIRCOL integer,
    BDBASEIRRFADCOL numeric(15,6),
    BDVALORPREVPRIVNCOL numeric(15,6),
    BDVALORPREVPRIV13COL numeric(15,6),
    BDDATAOPCAOFGTSCOL date,
    BDCTAFGTSCOL varchar(11),
    BDCATEGORIACOL integer,
    BDPERCFGTSCOL numeric(15,6),
    BDOCORRENCIACOL integer,
    BDPERCRATCOL numeric(15,6),
    BDPERCDESCFPASCOL numeric(15,6),
    BDBASEINSSNCOL numeric(15,6),
    BDVALORINSSNCOL numeric(15,6),
    BDBASEIRRFNCOL numeric(15,6),
    BDVALORIRRFNCOL numeric(15,6),
    BDBASEINSS13COL numeric(15,6),
    BDVALORINSS13COL numeric(15,6),
    BDBASEIRRF13COL numeric(15,6),
    BDVALORIRRF13COL numeric(15,6),
    BDTIPOADMCOL integer,
    BDNATUOCUPCOL integer,
    BDDATAINIAQUICOL date,
    BDSALINICOL numeric(15,6),
    BDDIASPRAZO1COL integer,
    BDDATAFIMPRAZO1COL date,
    BDDIASPRAZO2COL integer,
    BDDATAFIMPRAZO2COL date,
    BDDESCCONTSINCOL varchar(5),
    BDVINCEMPCOL integer,
    BDALVARACOL varchar(5),
    BDSINDICALIZADOCOL varchar(5),
    BDREGIMEPARCIALCOL varchar(5),
    BDFICHAREGCOL varchar(12),
    BDLIVROREGCOL varchar(10),
    BDNROFOLHAREGCOL integer,
    BDTIPOCOL integer,
    BDHORASMENSAISCOL numeric(15,6),
    BDHORASSEMANAISCOL numeric(15,6),
    BDHORASDIARIASCOL numeric(15,6),
    BDPERCINSALUBCOL numeric(15,6),
    BDINCIDINSALUBCOL integer,
    BDPERCPERCULCOL numeric(15,6),
    BDINCIDPERICULCOL integer,
    BDPERCNOTURNOCOL numeric(15,6),
    BDINCIDNOTURNOCOL integer,
    BDNRODEPSALFAMCOL integer,
    BDIGNORAFALTASFERCOL varchar(5),
    BDCALCADIANTACOL varchar(5),
    BDNAOARREDONDARCOL varchar(5),
    BDIMPETIQUETACOL varchar(5),
    BDCALCDSRRVCOL varchar(5),
    BDCALCDSRHECOL varchar(5),
    BDCALCDSRSALCOL varchar(5),
    BDCALCVALTRANSCOL varchar(5),
    BDCALCVALREFCOL varchar(5),
    BDOBSCOL blob sub_type 0 segment size 80,
    BDCODGPS integer,
    BDDESCINSSDOIRCOL varchar(5),
    BDCODMAS integer,
    BDSALBASECOL numeric(15,6),
    BDCODCBO integer,
    BDCODQH integer,
    BDCODPRES integer,
    BDDATARESCISAO date,
    BDDATAAVPREVIO date,
    BDDATAHOM date,
    BDDATAPAGRESCISAO date,
    BDSALDOFGTS numeric(15,6),
    BDCALCFGTSMESANT varchar(5),
    BDMAIORREMUNERACAO numeric(15,6),
    BDCHAVEINDENTIFICACAO varchar(49),
    BDDATAPAGGRFC date,
    BDREPOSICAOVAGA varchar(5),
    BDDISSIDIO varchar(5),
    BDDATADISSIDIO date,
    BDDESCANSOINDENIZADO varchar(5),
    BDCODMFGRESC integer,
    BDCODSAQUERESC integer,
    BDCODMRAISRESC integer,
    BDCODMCAGRESC integer,
    BDDESCPRES varchar(110),
    BDINIPRES integer,
    BDJCPRES varchar(5),
    BDAVPREPRES integer,
    BDGRRFPRES integer,
    BDESTPRES varchar(5),
    BDINDFER13 varchar(5),
    BDTERMCONTRPRES varchar(5),
    BDMULTAPRES varchar(5),
    BDDIASAVPREPRES integer,
    BDDIASPAGPRES integer,
    BDCODSEFMFGRESC varchar(5),
    BDDESCMFGRESC varchar(255),
    BDDESCSAQUERESC varchar(60),
    BDDESCMRAISRESC varchar(255),
    BDDESCMCAGEDRESC varchar(255),
    BDCODEMPDESTTRAN integer,
    BDCODPTRAN integer,
    BDCODCOLTRANS integer,
    BDDATATRANS date,
    BDCODMCAGENTTRANS integer,
    BDCODMCAGSAITRANS integer,
    BDCODMFGTRANS integer,
    BDCODMRAISTRANS integer,
    BDDESCPTRANS varchar(60),
    BDCODSEFMFGTRANS varchar(5),
    BDDESCMFGTRANS varchar(255),
    BDDESCRAISTRANS varchar(255),
    BDDESCMCAGEDENTTRANS varchar(255),
    BDDESCMCAGEDSAITRANS varchar(255),
    BDCONTRCOL integer,
    BDPERTRANSPINSSTER numeric(15,6),
    BDPERTRANSPIRTER numeric(15,6),
    BDCODMULTVINC integer,
    BDCATEGORIAESOCIAL integer)
as
declare variable WCAM varchar(20000);
declare variable WWHE varchar(10000);
declare variable WV varchar(30);
declare variable WI varchar(3);
declare variable WD varchar(30);
declare variable WB varchar(30);
declare variable WN varchar(30);
declare variable WDATA varchar(10);
declare variable WTABELA varchar(300);
declare variable WAPELIDO varchar(300);
declare variable WJOINREF varchar(3200);
BEGIN
   -- Seta a competencia atual.
   -- Algumas Views utilizam essas variaveis de contexto para filtrar e agrupar tabelas.
   wdata = CAST(prref AS VARCHAR(6));
   wdata = SUBSTRING(wdata FROM 5 FOR 2)||'-01-'||SUBSTRING(wdata FROM 1 FOR 4);
   EXECUTE PROCEDURE sp_seta_competencia(prref, CAST(wdata AS DATE), PRDATA);

   wv = ', CAST(NULL AS varchar(1))';
   wi = ', 0';
   wd = ', CAST(NULL AS DATE)';
   wb = ', CAST(NULL AS BLOB)';
   wn = ', CAST(NULL AS NUMERIC(15,6))';

   IF (PRHORA IS NULL) THEN
      PRHORA = 'null';

   wcam = 'select first 1 ' ||prserv||' BDCODSERV, cast('||''''||PRDATA||''''||' as date) BDDATASERV, '||''''||PRDATAPAG||''''||' BDDATAPAGSERV, '||
                              ''''||prhora||''''||' BDHORASERV, cast('||''''||PRDATACONTABILIZACAO||''''||' as date) BDDATACONTABILIZACAO, ' ||
                              prcodemp||' BDCODEMP, '||prcodcol||'BDCODTER, RH.BDTRIBUTACAOEXTERIOR ';

   -- CAMPOS
   wcam = wcam||wi||', COLCON.BDCODCID'||wi||wi||
                   ', COLCON.BDCODCIDNASCTER'||wi||', COLCON.BDNOMTER, COLCON.BDLOGRTER, COLCON.BDENDTER '||
                   ', COLCON.BDNUMTER, COLCON.BDCOMPLTER, SUBSTRING(COLCON.BDBAITER FROM 1 FOR 50), COLCON.BDCEPTER, COLCON.BDDDDTER '||
                   ', COLCON.BDFONETER, COLCON.BDCELTER, COLCON.BDEMAILTER, COLCON.BDSEXOTER '||
                   ', COLCON.BDDATANASCTER, COLCON.BDDATACADTER, TTERCREF.BDGRAUINSTTER, TTERCREF.BDESTCIVTER '||
                   wd||wd;

   wcam = wcam||', COLCON_DOC.bdrgter, COLCON_DOC.BDORGEMIRGTER, COLCON_DOC.BDDATAEMIRGTER '||
                   ', case ' ||
                   ' when (char_length(COLCON_DOC.BDCPFMEI) = 14) then COLCON_DOC.BDCPFMEI '||
                   ' else COLCON_DOC.BDCPFTER ' ||
                   ' end BDCPFTER, COLCON_DOC.BDRESERVISTATER, COLCON_DOC.BDPISTER'||wd;

   wcam = wcam||wi||wv||
                   wi||wi||wi||wi||
                   wv||wd||wv||wd||
                   wv;

   wcam = wcam||wi||wi||wv||wd;
   wcam = wcam||wi||wv||wv||wv||wd;
   wcam = wcam||wi||wi||wi||wn||wn||wv||wi||wi;
   wcam = wcam||', COLCON_DOC.BDNROCONSPROTER, COLCON_DOC.BDSIGLACONSPROTER, COLCON_DOC.BDCODCCMPROTER';
   wcam = wcam||', COLCON_VINC.BDCODCLA, CLASSE.BDGRUPOCLA';

   /*SINDICATO terceiro nao possui*/
   wcam = wcam||wi||wi;

   wcam = wcam||', COLCON_BANCO.BDCODBAN, COLCON_BANCO.BDCODAG, COLCON_BANCO.BDCTADEPTER, COLCON_BANCO.BDDIGCTADEPTER '||
                   ', COLCON_BANCO.BDTIPOCTATER, COLCON_BANCO.BDMODOPAGTOTER, COLCON_BANCO.BDCARTAOSALTER';

   wcam = wcam||wi||', TTERCREF.BDNRODEPIRTER'||wn||wn||wn;

   /*Terceiro nao tem dados de fgts apenas de gps*/
   wcam = wcam||wd||wv||', COLCON_FGTSGPS.BDCATEGORIATER '||wn||
                   ', COLCON_FGTSGPS.BDOCORRENCIATER '||
                   ', COLCON_FGTSGPS.BDPERCRATTER'||wn;

      wcam = wcam||', COLCON_MVINC.BDBASEINSSNTER, COLCON_MVINC.BDVALORINSSNTER, COLCON_MVINC.BDBASEIRRFNTER '||
                   ', COLCON_MVINC.BDVALORIRRFNTER'||wn||wn||
                   wn||wn;

      wcam = wcam||wi||wi||wd||wn||wi||wd||wi||wd||wv||wi||wv||wv||wv||wv||wv||wi;

      wcam = wcam||wi||wn||wn||wn||wn||wi||wn||wi||wn||wi||wi||wv||wv||wv||wv||wv||wv||wv||wv||wv;

      wcam = wcam||wb;

      wcam = wcam||wi||wv;

      wcam = wcam||wi||', '||prvalor||' bdvalorserv'||', COLCON_VINC.BDCODCBO'||wi;


   /* Tabela de Rescisao nao existe para terceiros*/
    wcam = wcam||wi||wd||wd||wd||wd||
                 wn||wv||wn||wv||
                 wd||wv||wv||wd||wv;

    /* Motivos de rescisao nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wi||wv||wi||
                 wv||wi||wi||wv||wv||wv||
                 wv||wi||wi||
                 wv||wv||
                 wv||
                 wv||
                 wv;


   /* Tabela de Transferencias nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wd;

    /* Motivos de transferencia nao existe para terceiros*/
    wcam = wcam||wi||wi||wi||wi||wv||
                 wv||wv||
                 wv||
                 wv||
                 wv;

   wcam = wcam||', 2';

   /*Terceiro nao tem dados de fgts apenas de gps*/
      wcam = wcam||', COLCON_FGTSGPS.BDPERTRANSPINSSTER, COLCON_FGTSGPS.BDPERTRANSPIRTER, COLCON_FGTSGPS.BDCODMULTVINC, COLCON_FGTSGPS.BDCATEGORIAESOCIAL ';

   -- TABELAS
   wtabela = 'vrh_base_tterc_ref';
   WAPELIDO = 'TTERCREF.';
   wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
                ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= '||prref||')';

   wcam = wcam||' from vrh_base_tterc COLCON ';
--   wcam = wcam||' left outer join vrh_base_tterc COLCON on (COLCON.bdcodter = TSERV.bdcodter) ';
   wcam = wcam||' left outer join VRH_BASE_TTERC_REF TTERCREF on (TTERCREF.bdcodter = COLCON.bdcodter'||wjoinref||') ';
   wcam = wcam||' left outer join TTERCEIRO_RH RH ON RH.BDCODTER = colcon.BDCODTER ';
   wcam = wcam||' left outer join vw_VRH_BASE_TTERC_DOC COLCON_DOC on (COLCON_DOC.bdcodter = COLCON.bdcodter) ';

   wtabela = 'VRH_BASE_TTERC_VINC';
   WAPELIDO = 'COLCON_VINC.';
   wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
               ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= '||prref||')';

   wcam = wcam||' left outer join VRH_BASE_TTERC_VINC COLCON_VINC '||
                    'on (COLCON_VINC.BDCODTER = COLCON.bdcodter'||wjoinref||') ';

   -- Grupo da Classe
   wcam = wcam||' left outer join VRH_BASE_TCLASSE CLASSE '||
                       'on (CLASSE.BDCODCLA = COLCON_VINC.BDCODCLA) ';

   wtabela = 'VRHF_BASE_TTERC_BANCO';
   WAPELIDO = 'COLCON_BANCO.';
   wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
               ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= '||prref||')';

   wcam = wcam||' left outer join VRHF_BASE_TTERC_BANCO '||
                       'COLCON_BANCO on (COLCON_BANCO.BDCODter = COLCON.bdcodter'||wjoinref||') ';

   wtabela = 'VRHF_BASE_TTERC_FGTSGPS';
   WAPELIDO = 'COLCON_FGTSGPS.';
   wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
               ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= '||prref||')';

   wcam = wcam||' left outer join VRHF_BASE_TTERC_FGTSGPS '||
                       'COLCON_FGTSGPS on (COLCON_FGTSGPS.BDCODter = COLCON.bdcodter'||wjoinref||') ';

   wtabela = 'VRHF_BASE_TTERC_MVINC';
   WAPELIDO = 'COLCON_MVINC.';
   wJOINREF = ' and '||WAPELIDO||'bdrefterc = ( select MAX(Y.bdrefterc) from '||wtabela||
               ' Y where Y.bdcodter = '||wapelido||'bdcodter and Y.bdrefterc <= '||prref||')';

   wcam = wcam||' left outer join VRHF_BASE_TTERC_MVINC '||
                       'COLCON_MVINC on (COLCON_MVINC.BDCODTER = COLCON.BDCODTER and COLCON_MVINC.BDCODEMP = '||prcodemp||wjoinref||') ';

   IF (:prCODCOL IS NOT NULL) THEN
      BEGIN
        wwhe = ' COLCON.BDCODTER = '||prcodcol;

      END

   IF ((wwhe <> '') AND (:wwhe IS NOT NULL)) THEN
      wwhe = ' where '||wwhe;
      
   wcam = wcam||wwhe;

   FOR EXECUTE STATEMENT wcam
      INTO :BDCODSERV, BDDATASERV, BDDATAPAGSERV, BDHORASERV, :BDDATACONTABILIZACAO,
            BDCODEMP,
           -- VRH_EMP_TCOLCON
           :BDCODCOL, :BDTRIBUTACAOEXTERIOR, :BDCODMCAG, :BDCODCID, :BDCODCSEG, :BDREFCSEG,
           :BDCODCIDNASC, :BDCODUF, :BDNOMCOL, :BDLOGRCOL, :BDENDCOL,
           :BDNUMCOL, :BDCOMPLCOL, :BDBAICOL, :BDCEPCOL, :BDDDDCOL,
           :BDFONECOL, :BDCELCOL, :BDEMAILCOL, :BDSEXOCOL,
           :BDDATANASCCOL, :BDDATACADCOL, :BDGRAUINSTCOL, :BDESTCIVCOL,
           :BDDATAADMCOL, :BDDATAADICCOL,

           :BDRGCOL, :BDORGEMIRGCOL, :BDDATAEMIRGCOL, :BDCPFCOL,
           :BDRESERVISTACOL, :BDPISCOL, :BDDATAEMIPISCOL,

           :BDCODUF_COL_DOC, :BDTITELEICOL, :BDZONAELEICOL,
           :BDSECAOELEICOL, :BDCTPSCOL, :BDSERIECTPSCOL, :BDDSERIECTPSCOL, :BDDATAEMICTPSCOL,
           :BDCNHCOL, :BDVENCCNHCOL, :BDCATCNHCOL,

           :BDCODCID_HIST, :BDCODPAIS, :BDNATURALIZADOCOL, :BDDATACHEBRASILCOL,

           :BDCODCIDNASCCONJ, :BDNOMPAICOL, :BDNOMMAECOL, :BDNOMCONJCOL, :BDDATANASCCONJCOL,

           :BDCORCOL, :BDCABELOSCOL, :BDOLHOSCOL, :BDALTURACOL,:BDPESOCOL, :BDSINAISCOL,
           :BDDEFFISICOCOL, :BDTIPOSANGUECOL,

           :BDNROCONSPROCOL, :BDSIGLACONSPROCOL, :BDCODCCMPROCOL,

           :BDCODCLA, :BDGRUPOCLA,

           :BDCODMEN, :BDCODSINTRAB,

           :BDCODBAN, :BDCODAG, :BDCTADEPCOL, :BDDIGCTADEPCOL, :BDTIPOCTACOL, :BDMODOPAGTOCOL, :BDCARTAOSALCOL,

           :BDFORMAPAGTOCOL, :BDNRODEPIRCOL, :BDBASEIRRFADCOL, :BDVALORPREVPRIVNCOL, :BDVALORPREVPRIV13COL,

           :BDDATAOPCAOFGTSCOL, :BDCTAFGTSCOL, :BDCATEGORIACOL, :BDPERCFGTSCOL,
           :BDOCORRENCIACOL, :BDPERCRATCOL, :BDPERCDESCFPASCOL,

           :BDBASEINSSNCOL, :BDVALORINSSNCOL, :BDBASEIRRFNCOL, :BDVALORIRRFNCOL, :BDBASEINSS13COL,
           :BDVALORINSS13COL, :BDBASEIRRF13COL, :BDVALORIRRF13COL,

           :BDTIPOADMCOL, :BDNATUOCUPCOL, :BDDATAINIAQUICOL, :BDSALINICOL, :BDDIASPRAZO1COL,
           :BDDATAFIMPRAZO1COL, :BDDIASPRAZO2COL, :BDDATAFIMPRAZO2COL, :BDDESCCONTSINCOL, :BDVINCEMPCOL,
           :BDALVARACOL, :BDSINDICALIZADOCOL, :BDREGIMEPARCIALCOL, :BDFICHAREGCOL, :BDLIVROREGCOL,
           :BDNROFOLHAREGCOL,

           :BDTIPOCOL, :BDHORASMENSAISCOL, :BDHORASSEMANAISCOL, :BDHORASDIARIASCOL,
           :BDPERCINSALUBCOL , :BDINCIDINSALUBCOL, :BDPERCPERCULCOL, :BDINCIDPERICULCOL,
           :BDPERCNOTURNOCOL, :BDINCIDNOTURNOCOL, :BDNRODEPSALFAMCOL, :BDIGNORAFALTASFERCOL,
           :BDCALCADIANTACOL, :BDNAOARREDONDARCOL, :BDIMPETIQUETACOL, :BDCALCDSRRVCOL,
           :BDCALCDSRHECOL, :BDCALCDSRSALCOL, :BDCALCVALTRANSCOL, :BDCALCVALREFCOL,

           :BDOBSCOL,

           :BDCODGPS, :BDDESCINSSDOIRCOL,

           :BDCODMAS, :BDSALBASECOL,
           :BDCODCBO, :BDCODQH,

           -- Rescisao
           :BDCODPRES,
           :BDDATARESCISAO,
           :BDDATAAVPREVIO,
           :BDDATAHOM,
           :BDDATAPAGRESCISAO,
           :BDSALDOFGTS,
           :BDCALCFGTSMESANT,
           :BDMAIORREMUNERACAO,
           :BDCHAVEINDENTIFICACAO,
           :BDDATAPAGGRFC,
           :BDREPOSICAOVAGA,
           :BDDISSIDIO,
           :BDDATADISSIDIO,
           :BDDESCANSOINDENIZADO,
           :BDCODMFGRESC,
           :BDCODSAQUERESC,
           :BDCODMRAISRESC,
           :BDCODMCAGRESC,
           :BDDESCPRES,
           :BDINIPRES,
           :BDJCPRES,
           :BDAVPREPRES,
           :BDGRRFPRES,
           :BDESTPRES,
           :BDINDFER13,
           :BDTERMCONTRPRES,
           :BDMULTAPRES,
           :BDDIASAVPREPRES,
           :BDDIASPAGPRES,
           :BDCODSEFMFGRESC,
           :BDDESCMFGRESC,
           :BDDESCSAQUERESC,
           :BDDESCMRAISRESC,
           :BDDESCMCAGEDRESC,

           --Transferencia
           :BDCODEMPDESTTRAN,
           :BDCODPTRAN,
           :BDCODCOLTRANS,
           :BDDATATRANS,
           :BDCODMCAGENTTRANS,
           :BDCODMCAGSAITRANS,
           :BDCODMFGTRANS,
           :BDCODMRAISTRANS,
           :BDDESCPTRANS,
           :BDCODSEFMFGTRANS,
           :BDDESCMFGTRANS,
           :BDDESCRAISTRANS,
           :BDDESCMCAGEDENTTRANS,
           :BDDESCMCAGEDSAITRANS,
           :BDCONTRCOL,
           :BDPERTRANSPINSSTER,
           :BDPERTRANSPIRTER,
           :BDCODMULTVINC,
           :BDCATEGORIAESOCIAL
           DO

    SUSPEND;

   EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

/* Restore proc. body: VRH_SP_SINDTRAB */
ALTER PROCEDURE VRH_SP_SINDTRAB(PRSIND VARCHAR(10000),
PRREF INTEGER)
 RETURNS(BDCODSINTRAB INTEGER,
BDCODCID INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDAPESINTRAB VARCHAR(15),
BDENTSINTRAB VARCHAR(15),
BDLOGRSINTRAB DM_LOGRADOURO,
BDENDSINTRAB DM_BDENDERECO,
BDNROSINTRAB DM_NUMEND,
BDCOMPLSINTRAB DM_BDCOMPENDERECO,
BDBAISINTRAB DM_BDBAIRRO,
BDDDDSINTRAB INTEGER,
BDFONESINTRAB DM_BDTELEFONE,
BDCNPJSINTRAB VARCHAR(18),
BDCEPSINTRAB VARCHAR(9),
BDREFST INTEGER,
BDCODIND INTEGER,
BDVERFERIST INTEGER,
BDVERMULRESST INTEGER,
BDCODPMS INTEGER,
BDPERABFERST NUMERIC(15,6),
BDDATBASEST INTEGER,
BDESTABST INTEGER,
BDPERCNOTST NUMERIC(15,6),
BDMESCSST INTEGER,
BDFERRESCST INTEGER,
BDFERDOBST INTEGER,
BDFERJCST INTEGER,
BDLIMITE13ST INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(25000);
BEGIN

  wsql = 'select s.BDCODSINTRAB , s.BDCODCID, s.BDDESCSINTRAB, s.BDAPESINTRAB, s.BDENTSINTRAB, '||
         's.BDLOGRSINTRAB, s.BDENDSINTRAB, s.BDNROSINTRAB, s.BDCOMPLSINTRAB, s.BDBAISINTRAB, '||
         's.BDDDDSINTRAB, s.BDFONESINTRAB, s.BDCNPJSINTRAB, s.BDCEPSINTRAB, ';

  wsql = wsql||'sr.BDREFST, sr.BDCODIND, sr.BDVERFERIST, sr.BDVERMULRESST, sr.BDCODPMS, '||
         'sr.BDPERABFERST, sr.BDDATBASEST, sr.BDESTABST, sr.BDPERCNOTST, sr.BDMESCSST, sr.BDFERRESCST, '||
         'sr.BDFERDOBST, sr.BDFERJCST, sr.BDLIMITE13ST ';

  wsql = wsql||'from VRH_BASE_TSINDTRAB s '||
         'left outer join VRH_BASE_TSINDTREF sr ';


  wsql = wsql||'on (sr.bdcodsintrab = s.bdcodsintrab and '||
                    '((exists (select Y.BDCODSINTRAB, max(Y.bdrefst) '||
                             'from VRH_BASE_TSINDTREF Y '||
                             'where Y.BDCODSINTRAB = S.BDCODSINTRAB and Y.BDREFST <= '||:prref||' '||
                             'group by Y.BDCODSINTRAB '||
                             'having max(Y.bdrefst) = SR.bdrefst)) or '||
                    '(exists (select H.BDCODSINTRAB, H.BDREFST '||
                             'from VW_VRH_BASE_TSINDTREF_MINREF H '||
                             'where not exists (select J.BDCODSINTRAB, max(J.BDREFST) '||
                                               'from VRH_BASE_TSINDTREF J '||
                                               'where J.BDREFST <= '||:prref||' and J.BDCODSINTRAB = H.BDCODSINTRAB '||
                                               'group by J.BDCODSINTRAB) and '||
                             'H.BDCODSINTRAB = S.BDCODSINTRAB and H.BDREFST = SR.BDREFST)))) ';

  IF (prsind IS NOT NULL) THEN
     wsql = wsql||' where '||prsind;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODSINTRAB ,
    :BDCODCID,
    :BDDESCSINTRAB,
    :BDAPESINTRAB,
    :BDENTSINTRAB,
    :BDLOGRSINTRAB,
    :BDENDSINTRAB,
    :BDNROSINTRAB,
    :BDCOMPLSINTRAB,
    :BDBAISINTRAB,
    :BDDDDSINTRAB,
    :BDFONESINTRAB,
    :BDCNPJSINTRAB,
    :BDCEPSINTRAB,

    :BDREFST,
    :BDCODIND,
    :BDVERFERIST,
    :BDVERMULRESST,
    :BDCODPMS,
    :BDPERABFERST,
    :BDDATBASEST,
    :BDESTABST,
    :BDPERCNOTST,
    :BDMESCSST,
    :BDFERRESCST,
    :BDFERDOBST,
    :BDFERJCST,
    :BDLIMITE13ST

  DO

  SUSPEND;

END
^

/* Restore proc. body: VRH_SP_TSITCOL */
ALTER PROCEDURE VRH_SP_TSITCOL(PREMPRESA VARCHAR(15000),
PRCOLABORADOR VARCHAR(30000),
PRULTDIA VARCHAR(10))
 RETURNS(BDCODSIT INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDDATAINISEFIP DATE,
BDDATAINISIT DATE,
BDDATAFIMSIT DATE,
BDDIASSIT INTEGER,
BDNBENEFICIOSIT VARCHAR(20),
BDDATAPERICIASIT DATE,
BDDATAPARTOSIT DATE,
BDDESCSIT VARCHAR(70))
 AS
DECLARE VARIABLE WORDERBY VARCHAR(15000);
DECLARE VARIABLE WWHERE VARCHAR(15000);
DECLARE VARIABLE WSQL VARCHAR(15000);
BEGIN
  wSql = 'select ';
  wSql = wSql || 'tsitcol.bdcodsit, ';
  wSql = wSql || 'tsitcol.bdcodemp, ';
  wSql = wSql || 'tsitcol.bdcodcol, ';
  wSql = wSql || 'tsitcol.bddatainisefip, ';
  wSql = wSql || 'tsitcol.bddatainisit, ';
  wSql = wSql || 'tsitcol.bddatafimsit, ';
  wSql = wSql || 'tsitcol.bddiassit, ';
  wsql = wsql || 'tsitcol.bdnbeneficiosit, ';
  wsql = wsql || 'tsitcol.bddatapericiasit, ';
  wsql = wsql || 'tsitcol.bddatapartosit, ';
  wSql = wSQl || 'tprepsit.bddescsit ';
  wSql = wSql || 'from vrh_emp_tsitcol tsitcol, ';
  wSql = wSql || 'vrh_base_tprepsit tprepsit ';

  wwhere = ' where tprepsit.bdCODSIT = tsitcol.BDCODSIT ';

  IF (prempresa <> '' AND prempresa IS NOT NULL) THEN
     wwhere = wwhere||' and '||prempresa||' ';

  IF (prcolaborador <> '' AND prcolaborador IS NOT NULL) THEN
     wwhere = wwhere||' and '||prcolaborador||' ';

  IF (prultdia <> '' AND prultdia IS NOT NULL) THEN
     wwhere = wwhere||' and tsitcol.bddatainisit <= '''||prultdia||''' ';


  worderby = 'order by tsitcol.bdcodemp,  tsitcol.bdCODCOL, tsitcol.bddatainisit ';

  wsql = wsql||wwhere||worderby;

  FOR EXECUTE STATEMENT wsql
      INTO
         :bdcodsit,
         :bdcodemp,
         :bdcodcol,
         :bddatainisefip,
         :bddatainisit,
         :bddatafimsit,
         :bddiassit,
         :bdnbeneficiosit,
         :bddatapericiasit,
         :bddatapartosit,
         :bddescsit
       DO
       BEGIN
         SUSPEND;
       END
END
^

/* Restore proc. body: VRH_SP_VERBA_ASSOC_TAB */
ALTER PROCEDURE VRH_SP_VERBA_ASSOC_TAB(PRDIAINI INTEGER,
PRMESINI INTEGER,
PRANOINI INTEGER,
PRDIAFIM INTEGER,
PRMESFIM INTEGER,
PRANOFIM INTEGER,
PRCHAVE VARCHAR(100),
PRWHERE VARCHAR(5000),
PRPRE VARCHAR(5),
PRPRETAB VARCHAR(5),
PRSIMNAO VARCHAR(1))
 RETURNS(BDMASTER INTEGER,
BDDETAIL INTEGER,
BDDIAINI INTEGER,
BDMESINI INTEGER,
BDANOINI INTEGER,
BDDIAFIM INTEGER,
BDMESFIM INTEGER,
BDANOFIM INTEGER,
BDCODVER INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000),
BDFORMREFAUX VARCHAR(5000))
 AS
DECLARE VARIABLE wsql VARCHAR(10000);
DECLARE VARIABLE wdataini VARCHAR(8);
DECLARE VARIABLE wdatafim VARCHAR(8);
BEGIN

  IF (:prsimnao IS NULL) THEN
     prsimnao = 's';

  wdataini = pranoini;

  IF (prmesini < 10) THEN
     wdataini = wdataini||'0'||prmesini;
  ELSE
     wdataini = wdataini||prmesini;

  IF (prdiaini < 10) THEN
     wdataini = wdataini||'0'||prdiaini;
  ELSE
     wdataini = wdataini||prdiaini;


  wdatafim = pranofim;

  IF (prmesfim < 10) THEN
     wdatafim = wdatafim||'0'||prmesfim;
  ELSE
     wdatafim = wdatafim||prmesfim;

  IF (prdiafim < 10) THEN
     wdatafim = wdatafim||'0'||prdiafim;
  ELSE
     wdatafim = wdatafim||prdiafim;

  IF (prwhere IS NULL) THEN
     prwhere = 'null';
  ELSE
     prwhere = ''''||prwhere||'''';

  wsql = 'select bdmaster,bddetail,'||
                'bddiaini,bdmesini,bdanoini,'||
                'bddiafim,bdmesfim,bdanofim,'||
                'bdcodver,bdformref,bdformval,bdformrefaux ';

--  wsql = wsql || 'from vrh_sp_verba_assoc_tab_prep('''||prchave||''','||prwhere||','''||prpre||''','''||prpretab||''') ';

  wsql = wsql || 'from vrh_sp_verba_assoc_tab_prep('||pranoini||','||pranofim||','''||prchave||''','||prwhere||','''||prpre||''','''||prpretab||''','''||prsimnao||''') ';

  wsql = wsql || 'where (bddataini >= '||wdataini||' and bddataini <= '||wdatafim||') or ';
  wsql = wsql ||       '(bddatafim >= '||wdataini||' and bddatafim <= '||wdatafim||') or ';
  wsql = wsql ||       '(bddataini <= '||wdataini||' and bddatafim >= '||wdatafim||') ';
                         
  wsql = wsql || 'order by bdmaster, bddetail, bddataini, bdcodver';

  FOR EXECUTE STATEMENT wsql
      INTO :bdmaster, :bddetail,
           :bddiaini, :bdmesini, :bdanoini,
           :bddiafim, :bdmesfim, :bdanofim,
           :bdcodver, :bdformref, :bdformval,
           :bdformrefaux
  DO

  SUSPEND;

END
^

/* Restore proc. body: VRH_SP_VERBA_ASSOC_TAB_PREP */
ALTER PROCEDURE VRH_SP_VERBA_ASSOC_TAB_PREP(PRANOINI INTEGER,
PRANOFIM INTEGER,
PRCHAVE VARCHAR(100),
PRWHERE VARCHAR(32700),
PRPRE VARCHAR(5),
PRPRETAB VARCHAR(5),
PRSIMNAO VARCHAR(1))
 RETURNS(BDMASTER INTEGER,
BDDETAIL INTEGER,
BDDATAINI VARCHAR(8),
BDDATAFIM VARCHAR(8),
BDDIAINI INTEGER,
BDMESINI INTEGER,
BDANOINI INTEGER,
BDDIAFIM INTEGER,
BDMESFIM INTEGER,
BDANOFIM INTEGER,
BDCODVER INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000),
BDFORMREFAUX VARCHAR(5000))
 AS
DECLARE VARIABLE wsql VARCHAR(10000);
DECLARE VARIABLE wanoini VARCHAR(40);
DECLARE VARIABLE wmesini VARCHAR(40);
DECLARE VARIABLE wdiaini VARCHAR(40);
DECLARE VARIABLE wanofim VARCHAR(40);
DECLARE VARIABLE wmesfim VARCHAR(40);
DECLARE VARIABLE wdiafim VARCHAR(40);
BEGIN

      wanoini = 'bdanoiniv'||:prsimnao||:prpre;
      wmesini = 'bdmesiniv'||:prsimnao||:prpre;
      wdiaini = 'bddiainiv'||:prsimnao||:prpre;
      wanofim = 'bdanofimv'||:prsimnao||:prpre;
      wmesfim = 'bdmesfimv'||:prsimnao||:prpre;
      wdiafim = 'bddiafimv'||:prsimnao||:prpre;

--select * from vrh_sp_verba_assoc_tab_prep('col','bdcodemp, bdcodcol',null);

  wsql = 'select '||prchave||', '||
         'case when (('||wanoini||' = 0) or ('||wanoini||' is null)) and ('||wmesini||' > 0) then '||''''||pranoini||''''||
             ' when ('||wanoini||' = 0) or ('||wanoini||' is null) then '||'''0000'''||
             ' when ('||wanoini||' > 0) then cast('||wanoini||' as varchar(4)) '||
         'end||'||
         'case when ('||wmesini||' = 0) or ('||wmesini||' is null) then '||'''00'''||
             ' when ('||wmesini||' < 10) then ''0'' ||'||wmesini||
             ' when ('||wmesini||' > 10) then cast('||wmesini||' as varchar(2)) '||
         'end||'||
         'case when ('||wdiaini||' = 0) or ('||wdiaini||' is null) then '||'''00'''||
             ' when ('||wdiaini||' < 10) then ''0'' ||'||wdiaini||
             ' when ('||wdiaini||' > 10) then cast('||wdiaini||' as varchar(2)) '||
         'end, '||
         'case when (('||wanofim||' = 0) or ('||wanofim||' is null)) and ('||wmesfim||' > 0) then '||''''||pranofim||''''||
             ' when ('||wanofim||' = 0) or ('||wanofim||' is null) then '||'''9999'''||
             ' when ('||wanofim||' > 0) then cast('||wanofim||' as varchar(4)) '||
         'end||'||
         'case when ('||wmesfim||' = 0) or ('||wmesfim||' is null) then '||'''99'''||
             ' when ('||wmesfim||' < 10) then ''0'' ||'||wmesfim||
             ' when ('||wmesfim||' > 10) then cast('||wmesfim||' as varchar(2)) '||
         'end||'||
         'case when ('||wdiafim||' = 0) or ('||wdiafim||' is null) then '||'''99'''||
             ' when ('||wdiafim||' < 10) then ''0'' ||'||wdiafim||
             ' when ('||wdiafim||' > 10) then cast('||wdiafim||' as varchar(2)) '||
         'end, '||

         wdiaini||','||wmesini||','||wanoini||','||
         wdiafim||','||wmesfim||','||wanofim||','||
         'bdcodver , ';

         IF ((prsimnao = 'n') OR (prsimnao = 'N')) THEN
           wsql = wsql || ' CAST(NULL AS VARCHAR(5000)), CAST(NULL AS VARCHAR(5000)), CAST(NULL AS VARCHAR(5000)) ';
         ELSE
           wsql = wsql || 'bdformularef'||:prpre||', bdformulaval'||:prpre||', bdformularefaux'||:prpre||' ';

     wsql = wsql||'from vrhf_'||:prpretab||'_tv'||:prsimnao||:prpre||' ';

  IF (prwhere IS NULL) THEN
     prwhere = '';
  ELSE
     prwhere = ' where '||prwhere;

--  prwhere = prWhere || ' order by bdcodemp, bdcodcol';

  FOR EXECUTE STATEMENT wsql||prwhere
      INTO :bdmaster, :bddetail,
           :bddataini, :bddatafim,
           :bddiaini, :bdmesini, :bdanoini,
           :bddiafim, :bdmesfim, :bdanofim,
           :bdcodver, :bdformref, :bdformval,
           :bdformrefaux
  DO

  SUSPEND;

END
^

/* Restore proc. body: VRHF_EMP_VAL_GRRF */
create or alter procedure VRHF_EMP_VAL_GRRF (
    PREMPRESA integer,
    PRCOLABORADOR integer,
    PRANOMES integer,
    PRANOMESPAG integer,
    PRTIPOCALCULO integer,
    PRCODTIPOFC integer = null,
    PRCHAVEDARF integer = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDBFGTSMESANT numeric(15,6),
    BDFGTSMESANT numeric(15,6),
    BDBFGTSMES numeric(15,6),
    BDFGTSMES numeric(15,6),
    BDSALDO numeric(15,6),
    BDFGTS40 numeric(15,6),
    BDFGTS10 numeric(15,6),
    BDTOTAL numeric(15,6),
    BDFGTSIND numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDVALOR numeric(15,6),
    BDPERCMULTA40 numeric(15,2),
    BDPERCMULTA10 numeric(15,2),
    BDBFGTSIND numeric(18,2),
    BDBFGTSMESFN numeric(18,2),
    BDBFGTSMES13 numeric(18,2),
    BDPOSSUIDATAFGTSDIGITAL DM_BOOLEAN,
    BDFGTS13 numeric(18,2))
as
declare variable WSQL varchar(6000);
declare variable WSQLAUX varchar(6000);
declare variable WFGTSMESANT varchar(5);
declare variable WANOMES integer;
declare variable WPERCFGTSCOL numeric(15,6);
declare variable WFGTSIND numeric(15,6);
declare variable WCHAVEDARF varchar(3000);
declare variable WCONDICAOCHAVEDARF varchar(3000);
declare variable WBFGTSIND13 numeric(18,6);
declare variable WBFGTS13 numeric(18,6);
declare variable WFGTS13 numeric(18,6);
declare variable WDATAFGTSDIGITAL date;
BEGIN
  /*PRTIPOCALCULO
    0 = normal
    1 = folha complementar
    2 = previa
  */

  IF (prtipocalculo IS NULL) THEN
     prtipocalculo = 0;

  IF (PRANOMESPAG IS NULL) THEN
     pranomespag = pranomes;

  /* Procedure Text */
  bdcodemp = prempresa;
  bdcodcol = prcolaborador;
  bdbfgtsmesant = 0;
  bdfgtsmesant = 0;
  bdbfgtsmes = 0;
  bdfgtsmes = 0;
  bdSaldo = 0;
  bdfgts40 = 0;
  bdfgts10 = 0;
  bdtotal = 0;
  bdfgtsind = 0;
  wfgtsind = 0;
  wbfgtsind13 = 0;
  wchavedarf = COALESCE(prchavedarf,'');

  wsqlaux = 'Select bddatafgtsdigital from VRH_ESOCIAL_TFASEAMENTO where bdcodemp = '||prempresa;
     EXECUTE STATEMENT wsqlaux INTO :WDATAFGTSDIGITAL;

  if ((WDATAFGTSDIGITAL is not null) and (:pranomes >= (select * from aaaamm(:WDATAFGTSDIGITAL)))) then
     bdpossuidatafgtsdigital = 'TRUE';
  else
     bdpossuidatafgtsdigital = 'FALSE';


  IF (wchavedarf <> '') THEN
     wcondicaochavedarf = ' and DARF.BDCHAVEDARF = '||wchavedarf;

  wcondicaochavedarf = COALESCE(wcondicaochavedarf,'');

  IF (PRTIPOCALCULO = 2) THEN
     BEGIN
       wsqlaux = 'select p.BDPERCMULTAFGTS,p.BDPERCMULTAFGTSCS,x.bdcalcfgtsmesantprev,x.bdsaldofgtsprev, FGTSCOL.BDPERCFGTSCOL, CC.BDCODCENTRO, CC.BDCODTPCC, DARF.BDVALOR '||
                 'from vrh_emp_trescisao_previa x '||
                 'join vrh_base_tprepresc p on (x.bdcodpres = p.bdcodpres) '||
                 'left outer join VW_VRHF_BASE_TEMPGPS EMP on (EMP.BDCODEMP = X.BDCODEMP) '||
                 'left outer join VRH_BASE_TFPAS_TERCEIROS FPTER on (FPTER.BDCODFPASTERC = EMP.BDCODFPASTERC) and '||
                 '     ((FPTER.BDCODFPAS <> 868) or ((FPTER.BDCODFPAS = 868) and (X.BDREFRESCISAOPREV < 201510))) '||
                 'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS FGTSCOL on (FGTSCOL.BDCODEMP = x.bdcodemp and FGTSCOL.BDCODCOL = x.bdcodcol) '||
                 'left outer join SP_VRH_CC_DATA(X.BDCODEMP,X.BDCODCOL,X.BDDATARESCISAOPREV) CC on (X.BDCODEMP = CC.BDCODEMP and X.BDCODCOL = CC.BDCODCOL) '||
                 'left outer join TDARFPADRAO DARF on (X.BDCODEMP = DARF.BDCODEMP and X.BDCODCOL = DARF.BDCODCOL and X.BDREFRESCISAOPREV = DARF.BDREFERENCIA '||wcondicaochavedarf||') '||
                 ' where (case when x.bddatarescisaoprev is null then ''0'''||
                 '             when x.bddatarescisaoprev is not null then (select bdaaaamm from aaaamm(x.bddatarescisaoprev)) '||
                 '       end) = '''||pranomes||''''||
                 '   and p.bdgrrfpres = 2'||
                 '   and x.bdcodcol = '||prcolaborador||
                 '   and x.bdcodemp = '||prempresa;
     END
  ELSE
  IF (PRTIPOCALCULO = 1) THEN
    wsqlaux = 'select p.BDPERCMULTAFGTS,p.BDPERCMULTAFGTSCS,X.BDCALCFGTSMESANT, X.BDSALDOFGTS, FGTSCOL.BDPERCFGTSCOL, CC.BDCODCENTRO, CC.BDCODTPCC, DARF.BDVALOR '||
              'from VRH_EMP_TRESCISAO X '||
              'join VRH_BASE_TPREPRESC P on (X.BDCODPRES = P.BDCODPRES) '||
              'left outer join VW_VRHF_BASE_TEMPGPS EMP on (EMP.BDCODEMP = X.BDCODEMP) '||
              'left outer join VRH_BASE_TFPAS_TERCEIROS FPTER on (FPTER.BDCODFPASTERC = EMP.BDCODFPASTERC) and '||
              '     ((FPTER.BDCODFPAS <> 868) or ((FPTER.BDCODFPAS = 868) and (X.BDREFRESCISAO < 201510))) '||
              'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS FGTSCOL on (FGTSCOL.BDCODEMP = x.bdcodemp and FGTSCOL.BDCODCOL = x.bdcodcol) '||
              'left outer join SP_VRH_CC_DATA(X.BDCODEMP,X.BDCODCOL,X.BDDATARESCISAO) CC on (X.BDCODEMP = CC.BDCODEMP and X.BDCODCOL = CC.BDCODCOL) '||
              'left outer join TDARFPADRAO DARF on (X.BDCODEMP = DARF.BDCODEMP and X.BDCODCOL = DARF.BDCODCOL and X.BDREFRESCISAO = DARF.BDREFERENCIA '||wcondicaochavedarf||') '||
              'where X.BDREFRESCISAO <= '||pranomes||
              '  and P.BDGRRFPRES = 2'||
              '  and X.BDCODCOL = '||prcolaborador||
              '  and X.BDCODEMP = '||prempresa;
  ELSE
    wsqlaux = 'select p.BDPERCMULTAFGTS,p.BDPERCMULTAFGTSCS,X.BDCALCFGTSMESANT, X.BDSALDOFGTS, FGTSCOL.BDPERCFGTSCOL, CC.BDCODCENTRO, CC.BDCODTPCC, DARF.BDVALOR '||
              'from VRH_EMP_TRESCISAO X '||
              'join VRH_BASE_TPREPRESC P on (X.BDCODPRES = P.BDCODPRES) '||
              'left outer join VW_VRHF_BASE_TEMPGPS EMP on (EMP.BDCODEMP = X.BDCODEMP) '||
              'left outer join VRH_BASE_TFPAS_TERCEIROS FPTER on (FPTER.BDCODFPASTERC = EMP.BDCODFPASTERC) and '||
              '     ((FPTER.BDCODFPAS <> 868) or ((FPTER.BDCODFPAS = 868) and (X.BDREFRESCISAO < 201510))) '||
              'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS FGTSCOL on (FGTSCOL.BDCODEMP = x.bdcodemp and FGTSCOL.BDCODCOL = x.bdcodcol) '||
              'left outer join SP_VRH_CC_DATA(X.BDCODEMP,X.BDCODCOL,X.BDDATARESCISAO) CC on (X.BDCODEMP = CC.BDCODEMP and X.BDCODCOL = CC.BDCODCOL) '||
              'left outer join TDARFPADRAO DARF on (X.BDCODEMP = DARF.BDCODEMP and X.BDCODCOL = DARF.BDCODCOL and X.BDREFRESCISAO = DARF.BDREFERENCIA '||wcondicaochavedarf||') '||
              'where X.BDREFRESCISAO = '''||pranomes||''''||
              '  and P.BDGRRFPRES = 2 '||
              '  and X.BDCODCOL = '||prcolaborador||
              '  and X.BDCODEMP = '||prempresa;

  FOR EXECUTE STATEMENT wsqlaux INTO :bdpercmulta40, :bdpercmulta10, :wfgtsmesant, :bdSaldo, :wpercfgtscol, :bdcodcentro, :bdcodtpcc, :bdvalor DO
    BEGIN
      IF (prtipocalculo = 2) THEN
         BEGIN
           wsql = 'select SUM(coalesce(x.BDBFGTS,0)+coalesce(x.BDBFGTSFEFOL,0)),SUM(coalesce(x.BDBFGTS13,0)),SUM(coalesce(x.BDFGTS,0)+coalesce(x.BDFGTSFEFOL,0)),SUM(coalesce(x.BDFGTS13,0)), MAX(FGTSI.BDFGTSIND), MAX(FGTSI.BDFGTSIND13) ';

           if (bdpossuidatafgtsdigital = 'TRUE') then
               wsql = 'select max(X.BDBASEFGTSMESESOCIAL), max(X.BDBASEFGTS13ESOCIAL), max(X.BDVALORFGTSMESESOCIAL), max(X.BDVALORFGTS13ESOCIAL), max(X.BDVALORFGTSINDESOCIAL), max(X.BDBASEFGTSINDESOCIAL) ';

           wsql = wsql ||' from VWRH_UNION_FNPR_FTPR_MES_BASES x '||
                  'left outer join ('||
                    'select '||prempresa||' BDCODEMP, '||prcolaborador||' BDCODCOL, SUM(BDVALVFNPR) BDFGTSIND, SUM(BDVALVFNPR13) BDFGTSIND13 from ('||
                        'select case when VER.BDCLAVER starting with ''7.060'' then 0 else FN.BDVALVFNPR end BDVALVFNPR, '||
                               'case when VER.BDCLAVER starting with ''7.060'' then FN.BDVALVFNPR else 0 end BDVALVFNPR13 '||
                        'from VRHF_EMP_TVERBAFN_PREV_RESC FN '||
                        'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) '||
                        'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FN.BDCODVER) '||
                        'where FN.BDCODEMP = '||prempresa||' and FN.BDCODCOL = '||prcolaborador||
                        ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                        'and VERF.BDFGTSVER > 0 '||
                        'union all '||
                        'select case when VER.BDCLAVER starting with ''7.060'' then 0 else FN.BDVALVFTPR end BDVALVFTPR, '||
                               'case when VER.BDCLAVER starting with ''7.060'' then FN.BDVALVFTPR else 0 end BDVALVFTPR13 '||
                        'from VRHF_EMP_TVERBAFT_PREV_RESC FN '||
                        'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) '||
                        'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FN.BDCODVER) '||
                        'where FN.BDCODEMP = '||prempresa||' and FN.BDCODCOL = '||prcolaborador||
                        ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                        'and VERF.BDFGTSVER > 0 '||
                  ')) FGTSI on (FGTSI.BDCODEMP = x.bdcodemp and FGTSI.BDCODCOL = x.bdcodcol) '||
                  ' where x.bdcodemp = '||prempresa||' and x.bdcodcol = '||prcolaborador||' and x.bdreffn = '||pranomes;
         END
      ELSE
      IF (prtipocalculo = 0) THEN
         BEGIN
           wsql = 'select SUM(x.bdbfgtsfn+x.bdbfgtsfefn),sum(x.bdbfgts13fn+COALESCE(sal13.bdbasefgts13,0)+COALESCE(ad13.bdbasefgtsa13,0)),SUM(x.bdfgtsfn+x.bdfgtsfefn),sum(x.bdfgts13fn+COALESCE(sal13.bdfgts13,0)+COALESCE(ad13.bdfgtsa13,0)), MAX(FGTSI.BDFGTSIND), MAX(FGTSI.BDFGTSIND13) ';

           if (bdpossuidatafgtsdigital = 'TRUE') then
               wsql = 'select max(X.BDBASEFGTSMESESOCIAL), max(coalesce(X.BDBASEFGTS13ESOCIAL, 0) + coalesce(SAL13.BDBASEFGTS13, 0) + coalesce(AD13.BDBASEFGTSA13,0)), max(X.BDVALORFGTSMESESOCIAL), max(Coalesce(X.BDVALORFGTS13ESOCIAL, 0) + coalesce(SAL13.BDFGTS13, 0) + coalesce(AD13.BDFGTSA13, 0)), max(X.BDVALORFGTSINDESOCIAL), max(X.BDBASEFGTSINDESOCIAL)';

           wsql = wsql||'from vrhf_sp_tfolha_normal('||''''||'colcon.bdcodemp = '||prempresa||''',''colcon.bdcodcol = '||prcolaborador||''','||pranomes||','||pranomes||',1) x';

           wsql = wsql||' left outer join vrhf_emp_t13sal sal13 on (sal13.bdcodemp = x.bdcodemp and sal13.bdcodcol = x.bdcodcol and sal13.bdref13 = '||:pranomes||')';
           wsql = wsql||' left outer join vrhf_emp_ta13sal ad13 on (ad13.bdcodemp = x.bdcodemp and ad13.bdcodcol = x.bdcodcol and ad13.bdrefa13 = '||:pranomes||')';

           wsql = wsql||' left outer join ('||
                     'select '||prempresa||' BDCODEMP, '||prcolaborador||' BDCODCOL, SUM(BDVALVFN) BDFGTSIND, SUM(BDVALVFN13) BDFGTSIND13 from ('||
                       'select case when VER.BDCLAVER starting with ''7.060'' then 0 else FN.BDVALVFN end BDVALVFN, '||
                              'case when VER.BDCLAVER starting with ''7.060'' then FN.BDVALVFN else 0 end BDVALVFN13 '||
                       'from VRHF_EMP_TVERBAFN FN '||
                       'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) '||
                       'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FN.BDCODVER) '||
                       'where FN.BDCODEMP = '||prempresa||' and FN.BDCODCOL = '||prcolaborador||' and FN.BDREFFN = '||pranomes||
                       ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                       'and VERF.BDFGTSVER > 0 '||
                       'union all '||
                       'select case when VER.BDCLAVER starting with ''7.060'' then 0 else FN.BDVALVFN end BDVALVFN, '||
                              'case when VER.BDCLAVER starting with ''7.060'' then FN.BDVALVFN else 0 end BDVALVFN13 '||
                       'from VRHF_EMP_TVERBAINT FN '||
                       'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) '||
                       'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FN.BDCODVER) '||
                       'join VRH_EMP_TINTERMITENTE CONV on (CONV.BDCODEMP = FN.BDCODEMP and CONV.BDCODCOL = FN.BDCODCOL and CONV.BDCODCONTTI = FN.BDCODCONTTI) '||
                       'where FN.BDCODEMP = '||prempresa||' and FN.BDCODCOL = '||prcolaborador||' and FN.BDREFFN = '||pranomes||
                       ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                       'and VERF.BDFGTSVER > 0 '||
                       'and upper(coalesce(CONV.BDCONVRESCTI, ''FALSE'')) = ''TRUE'' '||
                       'union all '||
                       'select case when VER.BDCLAVER starting with ''7.060'' then 0 else FN.BDVALVFT end BDVALVFT, '||
                              'case when VER.BDCLAVER starting with ''7.060'' then FN.BDVALVFT else 0 end BDVALVFT13 '||
                       'from VRHF_EMP_TVERBATOMADOR FN '||
                       'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) '||
                       'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FN.BDCODVER) '||
                       'where FN.BDCODEMP = '||prempresa||' and FN.BDCODCOL = '||prcolaborador||' and FN.BDREFTOMADOR = '||pranomes||
                       ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                       'and VERF.BDFGTSVER > 0 '||
                       'union all '||
                       'select case when VER.BDCLAVER starting with ''7.060'' then 0 else FN.BDVALVFT end BDVALVFT, '||
                              'case when VER.BDCLAVER starting with ''7.060'' then FN.BDVALVFT else 0 end BDVALVFT13 '||
                       'from VRHF_EMP_TVERBATOMINT FN '||
                       'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) '||
                       'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FN.BDCODVER) '||
                       'join VRH_EMP_TINTERMITENTE CONV on (CONV.BDCODEMP = FN.BDCODEMP and CONV.BDCODCOL = FN.BDCODCOL and CONV.BDCODCONTTI = FN.BDCODCONTTI) '||
                       'where FN.BDCODEMP = '||prempresa||' and FN.BDCODCOL = '||prcolaborador||' and FN.BDREFTOMADOR = '||pranomes||
                       ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                       'and VERF.BDFGTSVER > 0 '||
                       'and upper(coalesce(CONV.BDCONVRESCTI, ''FALSE'')) = ''TRUE'')) FGTSI on (FGTSI.BDCODEMP = x.bdcodemp and FGTSI.BDCODCOL = x.bdcodcol) ';
         END
      ELSE
      IF (prcodtipofc IS NOT NULL AND prcodtipofc = 3) THEN   -- Dissidio
         BEGIN
           wsql = 'select SUM(COALESCE(bdbfgtsfc,0)+COALESCE(bdbfgtsfefc,0)),sum(COALESCE(bdbfgts13fc,0)),SUM(COALESCE(bdfgtsfc,0)+COALESCE(bdfgtsfefc,0)),sum(COALESCE(bdfgts13fc,0)), MAX(BDFGTSIND), MAX(BDFGTSIND13) '||
                  'from ('||
                     'select bdbfgtsfc, bdbfgts13fc, bdbfgtsfefc, bdfgtsfc, bdfgts13fc, bdfgtsfefc, 0 bdfgtsind, 0 bdfgtsind13 from VRHF_EMP_TFOLHACOMP '||
                     'where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDREFCOMP = '||pranomespag||' and BDREFFN <= '||pranomes||' and BDCODTIPOFC = 3 '||
                     'union all '||
                     'select bdbfgtsfc, bdbfgts13fc, bdbfgtsfefc, bdfgtsfc, bdfgts13fc, bdfgtsfefc, 0 bdfgtsind, 0 bdfgtsind13 from VRHF_EMP_TFOLTOMCOMP '||
                     'where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDREFCOMP = '||pranomespag||' and BDREFTOMADOR <= '||pranomes||' and BDCODTIPOFC = 3 '||
                     'union all '||
                     'select 0 bdbfgtsfc, 0 bdbfgts13fc, 0 bdbfgtsfefc, 0 bdfgtsfc, 0 bdfgts13fc, 0 bdfgtsfefc, '||
                         'case when VER.BDCLAVER starting with ''7.060'' then 0 else FN.BDVALVFC end BDVALVFC, '||
                         'case when VER.BDCLAVER starting with ''7.060'' then FN.BDVALVFC else 0 end BDVALVFC13 '||
                     'from VRHF_EMP_TVERBAFC FN '||
                     'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) '||
                     'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FN.BDCODVER) '||
                     'where FN.BDCODEMP = '||prempresa||' and FN.BDCODCOL = '||prcolaborador||' and FN.BDREFFN <= '||pranomes||' and FN.BDREFCOMP = '||pranomespag||
                     ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                     'and VERF.BDFGTSVER > 0 '||
                     'union all '||
                     'select 0 bdbfgtsfc, 0 bdbfgts13fc, 0 bdbfgtsfefc, 0 bdfgtsfc, 0 bdfgts13fc, 0 bdfgtsfefc, '||
                         'case when VER.BDCLAVER starting with ''7.060'' then 0 else FN.BDVALVFC end BDVALVFC, '||
                         'case when VER.BDCLAVER starting with ''7.060'' then FN.BDVALVFC else 0 end BDVALVFC13 '||
                     'from VRHF_EMP_TVERBAFCTOMADOR FN '||
                     'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) '||
                     'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FN.BDCODVER) '||
                     'where FN.BDCODEMP = '||prempresa||' and FN.BDCODCOL = '||prcolaborador||' and FN.BDREFTOMADOR <= '||pranomes||' and FN.BDREFCOMP = '||pranomespag||
                     ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                     'and VERF.BDFGTSVER > 0 '||
                  ')';
         END
      ELSE
         BEGIN
           wsql = 'select SUM(COALESCE(x.bdbfgtsfc,0)+COALESCE(x.bdbfgtsfefc,0)),sum(COALESCE(x.bdbfgts13fc,0)),SUM(COALESCE(x.bdfgtsfc,0)+COALESCE(x.bdfgtsfefc,0)),sum(COALESCE(x.bdfgts13fc,0)), MAX(FGTSI.BDFGTSIND), MAX(FGTSI.BDFGTSIND13) '||
                  'from vrhf_sp_tfolhacomp('||''''||'colcon.bdcodemp = '||prempresa||''''||','
                                                                                                    ||''''||'colcon.bdcodcol = '||prcolaborador||''''||','||
                                                                                                    pranomes||','||pranomes||
                                                                                                    ','||pranomespag||','||pranomespag||',1) x';
           wsql = wsql||' left outer join ('||
                     'select '||prempresa||' BDCODEMP, '||prcolaborador||' BDCODCOL, SUM(BDVALVFC) BDFGTSIND, SUM(BDVALVFC13) BDFGTSIND13 from ('||
                       'select case when VER.BDCLAVER starting with ''7.060'' then 0 else FN.BDVALVFC end BDVALVFC, '||
                              'case when VER.BDCLAVER starting with ''7.060'' then FN.BDVALVFC else 0 end BDVALVFC13 '||
                       'from VRHF_EMP_TVERBAFC FN '||
                       'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) '||
                       'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FN.BDCODVER) '||
                       'where FN.BDCODEMP = '||prempresa||' and FN.BDCODCOL = '||prcolaborador||' and FN.BDREFFN = '||pranomes||' and FN.BDREFCOMP = '||pranomespag||
                       ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                       'and VERF.BDFGTSVER > 0 '||
                       'union all '||
                       'select case when VER.BDCLAVER starting with ''7.060'' then 0 else FN.BDVALVFC end BDVALVFC, '||
                              'case when VER.BDCLAVER starting with ''7.060'' then FN.BDVALVFC else 0 end BDVALVFC13 '||
                       'from VRHF_EMP_TVERBAFCTOMADOR FN '||
                       'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) '||
                       'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FN.BDCODVER) '||
                       'where FN.BDCODEMP = '||prempresa||' and FN.BDCODCOL = '||prcolaborador||' and FN.BDREFTOMADOR = '||pranomes||' and FN.BDREFCOMP = '||pranomespag||
                       ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                       'and VERF.BDFGTSVER > 0)) FGTSI on (FGTSI.BDCODEMP = x.bdcodemp and FGTSI.BDCODCOL = x.bdcodcol) ';
         END

      IF (prtipocalculo IN (0,1,2)) THEN
         EXECUTE STATEMENT wsql INTO : bdbfgtsmes, :wbfgts13, : bdfgtsmes, :wfgts13, :wfgtsind, :wbfgtsind13;

      IF ((wfgtsmesant = 'TRUE') AND (prtipocalculo IN (0,2))) THEN
         BEGIN
           IF (SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 5 FOR 2) = '01') THEN
              wanomes = CAST((CAST((SUBSTRING(pranomes FROM 1 FOR 4)) AS INTEGER) - 1) AS VARCHAR(4))||'12';
           ELSE
              wanomes = pranomes - 1;

           wsql = 'select SUM(COALESCE(x.bdbfgtsfn,0)+COALESCE(x.bdbfgts13fn,0)+COALESCE(x.bdbfgtsfefn,0)+COALESCE(sal13.bdbasefgts13,0)+COALESCE(ad13.bdbasefgtsa13,0)),'||
                         'SUM(COALESCE(x.bdfgtsfn,0)+COALESCE(x.bdfgts13fn,0)+COALESCE(x.bdfgtsfefn,0)+COALESCE(sal13.bdfgts13,0)+COALESCE(ad13.bdfgtsa13,0)) '||
                  'from vrhf_sp_tfolha_normal('||''''||'colcon.bdcodemp = '||prempresa||''''||','
                                                                                                        ||''''||'colcon.bdcodcol = '||prcolaborador||''''||','||
                                                                                                        wanomes||','||wanomes||',1) x';
           wsql = wsql||' left outer join vrhf_emp_t13sal sal13 on (sal13.bdcodemp = x.bdcodemp and sal13.bdcodcol = x.bdcodcol and sal13.bdref13 = '||:wanomes||')';
           wsql = wsql||' left outer join vrhf_emp_ta13sal ad13 on (ad13.bdcodemp = x.bdcodemp and ad13.bdcodcol = x.bdcodcol and ad13.bdrefa13 = '||:wanomes||')';
           EXECUTE STATEMENT wsql INTO : bdbfgtsmesant, : bdfgtsmesant;
         END


      IF (prtipocalculo = 1) THEN
         bdsaldo = 0;

      bdbfgtsmesant = COALESCE(bdbfgtsmesant, 0);
      bdfgtsmesant  = COALESCE(bdfgtsmesant,0);
      bdpercmulta40 = COALESCE(bdpercmulta40, 0);
      bdpercmulta10 = COALESCE(bdpercmulta10, 0);
      wfgtsind      = COALESCE(wfgtsind, 0);
      wfgts13       = COALESCE(wfgts13, 0);

      bdfgts10 = 0;
      bdfgts40 = 0;
--      IF ((prtipocalculo IN (0,1,2)) AND (UPPER(BDMULTAPRES) = 'FALSE')) THEN
      IF ((prtipocalculo IN (0,1,2)) AND (bdpercmulta40 > 0)) THEN
         BEGIN
           if (bdpossuidatafgtsdigital = 'TRUE') then
              begin
                 bdfgts40 = CAST(((bdsaldo) * (bdpercmulta40 / 100)) AS NUMERIC(15,4));
                 bdfgts40 = bdfgts40 + CAST(((bdfgtsmes+wfgts13+bdfgtsmesant+wfgtsind) * (bdpercmulta40 / 100)) AS NUMERIC(15,4));
              end
           else
              begin
                --           bdfgts40 = CAST(((bdsaldo+bdfgtsmes+bdfgtsmesant) * 0.40)-0.005 AS NUMERIC(15,2));
           bdfgts40 = CAST(((bdsaldo+bdfgtsmes+wfgts13+bdfgtsmesant) * (bdpercmulta40 / 100))-0.005 AS NUMERIC(15,2));
                --           bdfgts10 = CAST(((bdsaldo+bdfgtsmes+bdfgtsmesant) * 0.50)-0.005 AS NUMERIC(15,2)) - bdfgts40;
           bdfgts10 = CAST(((bdsaldo+bdfgtsmes+wfgts13+bdfgtsmesant) * ((bdpercmulta40 + bdpercmulta10) / 100))-0.005 AS NUMERIC(15,2)) - bdfgts40;
              end

--           IF (UPPER(BDMULTA10PRES) <> 'TRUE') THEN
           IF (bdpercmulta10 = 0) THEN
              bdfgts10 = 0;
         END
-- Se for maior ou igual a 01/2020 não deve somar o 10%. {131392 - Paulo Nunes - 06/01/2020}
      IF (PRANOMES >= 202001) THEN
        bdfgts10 = 0;

      if (bdfgts40 < 0) then
         bdfgts40 = 0;

      if (bdfgts10 < 0) then
         bdfgts10 = 0;

      if (bdpossuidatafgtsdigital = 'TRUE') then
         begin
            BDBFGTSIND    = wbfgtsind13;
            BDBFGTSMESFN  = bdbfgtsmes;
            BDBFGTSMES13  = wbfgts13;
            bdfgtsind     = wfgtsind;
            bdfgts13      = wfgts13;

            bdtotal       = bdfgts10+bdfgts40+bdfgtsmes+wfgts13+bdfgtsmesant+wfgtsind;
         end
      else
         begin
      bdtotal = bdfgts10+bdfgts40+bdfgtsmes+wfgts13+bdfgtsmesant;

      IF (wfgtsind IS NULL) THEN
         wfgtsind = 0;
    
      IF (wbfgtsind13 IS NULL) THEN
         wbfgtsind13 = 0;
    
      BDBFGTSIND = 0;
      if (bdbfgtsmes > 0) then
         BDBFGTSIND = BDBFGTSIND + wfgtsind;
      else
         wfgtsind = 0;
    
      if (wbfgts13 > 0) then
         begin
           BDBFGTSIND = BDBFGTSIND + wbfgtsind13;
           wfgtsind = wfgtsind + wbfgtsind13;
         end
      else
         wbfgtsind13 = 0;
    
      BDBFGTSMES13 = wbfgtsind13;
    
           BDBFGTSMESFN = bdbfgtsmes;
      bdbfgtsmes = bdbfgtsmes + wbfgts13;
    
    --      bdbfgtsmes = bdbfgtsmes + wbfgtsind13;
    
      wfgtsind = CAST(((wfgtsind * wpercfgtscol / 100) - 0.005) AS NUMERIC(15, 2));
    
      IF (wfgtsind >= 0) THEN -- Sol:16614 - Marcelo B. M. - 08/12/2016 - Em caso de numero negativo, recebe zero
         bdfgtsind = wfgtsind;
      ELSE
         bdfgtsind = 0;
    
    --      bdfgtsmes = bdfgtsmes - bdfgtsind;
      bdfgtsmes = bdfgtsmes + wfgts13;
      if (bdfgtsind > 0) then
            begin
        bdfgtsmes = CAST(((bdbfgtsmes - BDBFGTSIND) * (wpercfgtscol / 100)- 0.005) AS NUMERIC(15, 2));
            end
    
      IF (bdfgtsmes < 0) THEN
         bdfgtsmes = 0;
    
      bdtotal = bdfgts10+bdfgts40+bdfgtsmes+bdfgtsind+bdfgtsmesant;
         end
    END

  SUSPEND;
END^

/* Restore proc. body: VRHF_EMP_VAL_GRRF_FC */
create or alter procedure VRHF_EMP_VAL_GRRF_FC (
    PREMPRESA integer,
    PRCOLABORADOR integer,
    PRANOMES integer,
    PRDATAPGTO date,
    PRCODTIPOFC integer = null,
    PRRELGRRF DM_BOOLEAN = 'FALSE',
    PRFILTRARDATA DM_BOOLEAN = 'TRUE')
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDBFGTSMESANT numeric(15,6),
    BDFGTSMESANT numeric(15,6),
    BDBFGTSMES numeric(15,6),
    BDFGTSMES numeric(15,6),
    BDSALDO numeric(15,6),
    BDFGTS40 numeric(15,6),
    BDFGTS10 numeric(15,6),
    BDTOTAL numeric(15,6),
    BDFGTSIND numeric(15,6),
    BDBFGTSMESSEFIP numeric(15,6),
    BDFGTSMESSEFIP numeric(15,6),
    BDPERCMULTA40 numeric(15,2),
    BDPERCMULTA10 numeric(15,2),
    BDBFGTSIND numeric(18,2),
    BDFGTS13 numeric(9,2),
    BDBASEFGTS13 numeric(9,2),
    BDPOSSUIDATAFGTSDIGITAL varchar(5),
    BDSALDOTOTAL numeric(15,6))
as
declare variable WVALORMULTA numeric(15,6);
declare variable WSQL varchar(3000);
declare variable WSQLAUX varchar(3000);
declare variable WPERCFGTSCOL numeric(15,6);
declare variable WFGTSIND numeric(15,6);
declare variable WBFGTSIND numeric(15,6);
declare variable WINTERMITENTE integer;
declare variable WDATAFGTSDIGITAL date;
declare variable WREFFGTSDIGITAL integer;
declare variable WSALDOTOTAL numeric(15,6);
declare variable WREFFC integer;
declare variable WREFFCANT integer;
declare variable WCOL integer;
declare variable WCALCULOU varchar(5);
declare variable WDATACOMPAUX date;
declare variable WDATAAUX date;
declare variable WANOMESCOMPLEMENTAR integer;
BEGIN
  /* Procedure Text */
  bdcodemp = prempresa;
  bdcodcol = prcolaborador;
  bdbfgtsmesant = 0;
  bdfgtsmesant = 0;
  bdbfgtsmes = 0;
  bdfgtsmes = 0;
  bdSaldo = 0;
  bdfgts40 = 0;
  bdfgts10 = 0;
  bdtotal = 0;
  bdfgtsind = 0;
  bdbfgtsmessefip = 0;
  bdfgtsmessefip = 0;
  WREFFGTSDIGITAL = 0;
  bdfgts13         = 0;
  wcalculou = 'FALSE';
  wcol = 0;

  if (PRFILTRARDATA = 'FALSE') then
    BEGIN
      WDATACOMPAUX = CAST(
                     SUBSTRING(CAST(PRANOMES AS VARCHAR(6)) FROM 1 FOR 4) || '-' ||
                     SUBSTRING(CAST(PRANOMES AS VARCHAR(6)) FROM 5 FOR 2) || '-01' AS DATE);

      select BDNOVADATA from DIMINUI_MESES(:WDATACOMPAUX, 1) into : WDATAAUX;

      WANOMESCOMPLEMENTAR = extract(YEAR FROM WDATAAUX) * 100 + EXTRACT(MONTH FROM WDATAAUX);
    END

  select BDDATAFGTSDIGITAL from VRH_ESOCIAL_TFASEAMENTO where BDCODEMP = :PREMPRESA into :WDATAFGTSDIGITAL;

  if (WDATAFGTSDIGITAL is not null) then
     select * from AAAAMM(:WDATAFGTSDIGITAL) into :WREFFGTSDIGITAL;

  wsqlaux = 'select p.BDPERCMULTAFGTS,p.BDPERCMULTAFGTSCS,x.bdsaldofgts,fgts.bdpercfgtscol '||
            'from vrh_emp_trescisao x '||
            'join vrh_base_tprepresc p on (p.bdcodpres = x.bdcodpres) '||
            'join vw_vrhf_emp_tcolcon_fgtsgps fgts on (fgts.bdcodemp = x.bdcodemp and fgts.bdcodcol = x.bdcodcol) '||
            'where x.bdrefrescisao = '||pranomes||
               ' and p.bdgrrfpres = 2'||
               ' and x.bdcodcol = '||prcolaborador||
               ' and x.bdcodemp = '||prempresa;

  wsqlaux = wsqlaux||' union all '||
      'select p.BDPERCMULTAFGTS,p.BDPERCMULTAFGTSCS,x.bdsaldofgts,fgts.bdpercfgtscol '||
      'from vrh_emp_trescisao x '||
      'join vrh_base_tprepresc p on (p.bdcodpres = x.bdcodpres) '||
      'join vw_vrhf_emp_tcolcon_fgtsgps fgts on (fgts.bdcodemp = x.bdcodemp and fgts.bdcodcol = x.bdcodcol) '||
      'where x.bdrefprojecaoaviso = '||pranomes||' and x.bdrefrescisao < '||pranomes||
         ' and p.bdgrrfpres = 2'||
         ' and x.bdcodcol = '||prcolaborador||
         ' and x.bdcodemp = '||prempresa;

  FOR EXECUTE STATEMENT wsqlaux INTO :bdpercmulta40, :bdpercmulta10, :bdSaldo,:wpercfgtscol DO
    BEGIN
      bdfgtsind = 0;
      bdbfgtsmessefip = 0;
      bdfgtsmessefip = 0;

      bdpercmulta40 = COALESCE(bdpercmulta40, 0);
      bdpercmulta10 = COALESCE(bdpercmulta10, 0);
      wintermitente = null;

      select first 1 BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS where BDCODEMP = :prempresa and BDCODCOL = :prcolaborador and BDREFCOL <= :pranomes order by BDREFCOL DESC into :wintermitente;

      wintermitente = coalesce(wintermitente, 0);


      if (wcol <> prcolaborador) then
      begin
          WCOL = prcolaborador;

          BDSALDOTOTAL = 0;
          WSALDOTOTAL  = 0;
          WREFFC       = 0;
          WREFFCANT    = 0;

          IF ((COALESCE(prcodtipofc,1) = 3) and ((WREFFGTSDIGITAL > 0) and (pranomes >= WREFFGTSDIGITAL))) THEN
             begin
               wsql = 'select sum(BDVALORFGTSMESESOCIAL) + sum(BDVALORFGTS13ESOCIAL), BDREF '||
                      'from (select COALESCE(BDFGTSFC, 0)BDVALORFGTSMESESOCIAL, '||
                      '      COALESCE(BDFGTS13FC, 0)BDVALORFGTS13ESOCIAL, BDREFFN BDREF '||
                      '      from VRHF_EMP_TFOLHACOMP where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDDATAGRRFFC = '''||prdatapgto||''' and BDCODTIPOFC = '||prcodtipofc||
                      '      union all '||
                      '      select COALESCE(BDFGTSFC, 0)BDVALORFGTSMESESOCIAL, '||
                      '             COALESCE(BDFGTS13FC, 0)BDVALORFGTS13ESOCIAL, BDREFTOMADOR BDREF '||
                      '      from VRHF_EMP_TFOLTOMCOMP where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDDATAGRRFFC = '''||prdatapgto||''' and BDCODTIPOFC = '||prcodtipofc||
                      '      union all '||
                      '      select COALESCE(BDFGTSFC, 0)BDVALORFGTSMESESOCIAL,'||
                      '             COALESCE(BDFGTS13FC, 0)BDVALORFGTS13ESOCIAL, BDREFFN BDREF '||
                      '      from VRHF_EMP_TFOLHACOMPINT where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDDATAGRRFFC = '''||prdatapgto||''' and BDCODTIPOFC = '||prcodtipofc||
                      '      union all '||
                      '      select COALESCE(BDFGTSFC, 0)BDVALORFGTSMESESOCIAL, '||
                      '             COALESCE(BDFGTS13FC, 0)BDVALORFGTS13ESOCIAL, BDREFTOMADOR BDREF '||
                      '      from VRHF_EMP_TFOLTOMCOMPINT where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDDATAGRRFFC = '''||prdatapgto||''' and BDCODTIPOFC = '||prcodtipofc||')'||
                      ' group by BDREF';

              for EXECUTE STATEMENT wsql INTO :wSALDOTOTAL, :wREFFC do
                 begin
                   if (wREFFC <> wREFFCANT) then
                     begin
                       BDSALDOTOTAL = BDSALDOTOTAL + wSALDOTOTAL;
                       BDFGTS40 = CAST(((BDSALDOTOTAL) * (bdpercmulta40 / 100))-0.005 AS NUMERIC(15,2));
                       WCALCULOU = 'TRUE';
                     end
                    wREFFCANT = wREFFC;
                 end
              end
      end

      IF (COALESCE(prcodtipofc,1) <> 1) THEN
         BEGIN
           if ((WREFFGTSDIGITAL > 0) and (pranomes >= WREFFGTSDIGITAL)) then
               begin
                   bdpossuidatafgtsdigital = 'True';

                   wsql = 'select sum(BDBASEFGTSMESESOCIAL), sum(BDBASEFGTS13ESOCIAL), sum(BDBASEFGTSINDESOCIAL), sum(BDVALORFGTSMESESOCIAL), sum(BDVALORFGTS13ESOCIAL), sum(BDVALORFGTSINDESOCIAL), '||
                          '       sum(BDVALORFGTSMESESOCIAL) + sum(BDVALORFGTS13ESOCIAL)'||
                          'from (select COALESCE(BDBASEFGTSMESESOCIAL, 0)BDBASEFGTSMESESOCIAL, COALESCE(BDVALORFGTSMESESOCIAL, 0)BDVALORFGTSMESESOCIAL, COALESCE(BDBASEFGTS13ESOCIAL, 0)BDBASEFGTS13ESOCIAL, '||
                          '      COALESCE(BDVALORFGTS13ESOCIAL, 0)BDVALORFGTS13ESOCIAL, COALESCE(BDBASEFGTSINDESOCIAL, 0)BDBASEFGTSINDESOCIAL, COALESCE(BDVALORFGTSINDESOCIAL, 0)BDVALORFGTSINDESOCIAL '||
                          '      from VRHF_EMP_TFOLHACOMP where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDDATAGRRFFC = '''||prdatapgto||''' and BDREFFN = '||pranomes||' and BDCODTIPOFC = '||prcodtipofc||
                          '      union all '||
                          '      select COALESCE(BDBASEFGTSMESESOCIAL, 0)BDBASEFGTSMESESOCIAL, COALESCE(BDVALORFGTSMESESOCIAL, 0)BDVALORFGTSMESESOCIAL, COALESCE(BDBASEFGTS13ESOCIAL, 0)BDBASEFGTS13ESOCIAL, '||
                          '             COALESCE(BDVALORFGTS13ESOCIAL, 0)BDVALORFGTS13ESOCIAL, COALESCE(BDBASEFGTSINDESOCIAL, 0)BDBASEFGTSINDESOCIAL, COALESCE(BDVALORFGTSINDESOCIAL, 0)BDVALORFGTSINDESOCIAL '||
                          '      from VRHF_EMP_TFOLTOMCOMP where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDDATAGRRFFC = '''||prdatapgto||''' and BDREFTOMADOR = '||pranomes||' and BDCODTIPOFC = '||prcodtipofc||
                          '      union all '||
                          '      select COALESCE(BDBASEFGTSMESESOCIAL, 0)BDBASEFGTSMESESOCIAL, COALESCE(BDVALORFGTSMESESOCIAL, 0)BDVALORFGTSMESESOCIAL, COALESCE(BDBASEFGTS13ESOCIAL, 0)BDBASEFGTS13ESOCIAL, '||
                          '             COALESCE(BDVALORFGTS13ESOCIAL, 0)BDVALORFGTS13ESOCIAL, COALESCE(BDBASEFGTSINDESOCIAL, 0)BDBASEFGTSINDESOCIAL, COALESCE(BDVALORFGTSINDESOCIAL, 0)BDVALORFGTSINDESOCIAL '||
                          '      from VRHF_EMP_TFOLHACOMPINT where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDDATAGRRFFC = '''||prdatapgto||''' and BDREFFN = '||pranomes||' and BDCODTIPOFC = '||prcodtipofc||
                          '      union all '||
                          '      select COALESCE(BDBASEFGTSMESESOCIAL, 0)BDBASEFGTSMESESOCIAL, COALESCE(BDVALORFGTSMESESOCIAL, 0)BDVALORFGTSMESESOCIAL, COALESCE(BDBASEFGTS13ESOCIAL, 0)BDBASEFGTS13ESOCIAL, '||
                          '             COALESCE(BDVALORFGTS13ESOCIAL, 0)BDVALORFGTS13ESOCIAL, COALESCE(BDBASEFGTSINDESOCIAL, 0)BDBASEFGTSINDESOCIAL, COALESCE(BDVALORFGTSINDESOCIAL, 0)BDVALORFGTSINDESOCIAL '||
                          '      from VRHF_EMP_TFOLTOMCOMPINT where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDDATAGRRFFC = '''||prdatapgto||''' and BDREFTOMADOR = '||pranomes||' and BDCODTIPOFC = '||prcodtipofc||')';

                   EXECUTE STATEMENT wsql INTO :bdbfgtsmes, :bdbasefgts13, :BDBFGTSIND, :bdfgtsmes, :bdfgts13, :bdfgtsind,  :bdsaldo;
               end
           else
               begin
                   bdpossuidatafgtsdigital = 'False';

                   wsql = 'select SUM(COALESCE(bdbfgtsfc,0)+COALESCE(bdbfgts13fc,0)+COALESCE(bdbfgtsfefc,0)),SUM(COALESCE(bdfgtsfc,0)+COALESCE(bdfgts13fc,0)+COALESCE(bdfgtsfefc,0)) '||
                          'from ('||
                             'select coalesce(bdbfgtsfc,0) bdbfgtsfc, coalesce(bdbfgts13fc,0) bdbfgts13fc, coalesce(bdbfgtsfefc,0) bdbfgtsfefc, coalesce(bdfgtsfc,0) bdfgtsfc, coalesce(bdfgts13fc,0) bdfgts13fc, coalesce(bdfgtsfefc,0) bdfgtsfefc from VRHF_EMP_TFOLHACOMP '||
                             'where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDDATAGRRFFC = '''||prdatapgto||''' and BDREFFN = '||pranomes||
                             ' and BDCODTIPOFC = '||prcodtipofc||
                             ' union all '||
                             'select coalesce(bdbfgtsfc,0), coalesce(bdbfgts13fc,0), coalesce(bdbfgtsfefc,0), coalesce(bdfgtsfc,0), coalesce(bdfgts13fc,0), coalesce(bdfgtsfefc,0) from VRHF_EMP_TFOLTOMCOMP '||
                             'where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDDATAGRRFFC = '''||prdatapgto||''' and BDREFTOMADOR = '||pranomes||
                             ' and BDCODTIPOFC = '||prcodtipofc||
                             ' union all '||
                             'select coalesce(bdbfgtsfc,0) bdbfgtsfc, coalesce(bdbfgts13fc,0) bdbfgts13fc, coalesce(bdbfgtsfefc,0) bdbfgtsfefc, coalesce(bdfgtsfc,0) bdfgtsfc, coalesce(bdfgts13fc,0) bdfgts13fc, coalesce(bdfgtsfefc,0) bdfgtsfefc from VRHF_EMP_TFOLHACOMPINT '||
                             'where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDDATAGRRFFC = '''||prdatapgto||''' and BDREFFN = '||pranomes||
                             ' and BDCODTIPOFC = '||prcodtipofc||
                             ' union all '||
                             'select coalesce(bdbfgtsfc,0), coalesce(bdbfgts13fc,0), coalesce(bdbfgtsfefc,0), coalesce(bdfgtsfc,0), coalesce(bdfgts13fc,0), coalesce(bdfgtsfefc,0) from VRHF_EMP_TFOLTOMCOMPINT '||
                             'where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDDATAGRRFFC = '''||prdatapgto||''' and BDREFTOMADOR = '||pranomes||
                             ' and BDCODTIPOFC = '||prcodtipofc||
        
                          ')';

                   EXECUTE STATEMENT wsql INTO :bdbfgtsmes, :bdfgtsmes;

                   wsql = 'select SUM(BDVALVFC) from ('||
                             'select FC.BDVALVFC from VRHF_EMP_TVERBAFC FC '||
                             'join VRHF_EMP_TFOLHACOMP FCN on (FCN.BDCODEMP = FC.BDCODEMP and FCN.BDCODCOL = FC.BDCODCOL and FCN.BDREFFN = FC.BDREFFN and FCN.BDREFFC = FC.BDREFFC) '||
                             'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FC.BDCODVER) '||
                             'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FC.BDCODVER) '||
                             'where FC.BDCODEMP = '||prempresa||' and FC.BDCODCOL = '||prcolaborador||' and FC.BDREFFN <= '||pranomes||' and FCN.BDDATAGRRFFC = '''||prdatapgto||''''||
                             ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                             'and VERF.BDFGTSVER > 0 '||
                             'union all '||
                             'select FC.BDVALVFC from VRHF_EMP_TVERBAFCTOMADOR FC '||
                             'join VRHF_EMP_TFOLTOMCOMP FCN on (FCN.BDCODEMP = FC.BDCODEMP and FCN.BDCODCOL = FC.BDCODCOL and FCN.BDREFTOMADOR = FC.BDREFTOMADOR and FCN.BDREFFC = FC.BDREFFC and FCN.BDORDEM = FC.BDORDEM) '||
                             'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FC.BDCODVER) '||
                             'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FC.BDCODVER) '||
                             'where FC.BDCODEMP = '||prempresa||' and FC.BDCODCOL = '||prcolaborador||' and FC.BDREFTOMADOR <= '||pranomes||' and FCN.BDDATAGRRFFC = '''||prdatapgto||''''||
                             ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                             'and VERF.BDFGTSVER > 0'||
                             'union all '||
                             'select FC.BDVALVFC from VRHF_EMP_TVERBAFCINT FC '||
                             'join VRHF_EMP_TFOLHACOMPINT FCN on (FCN.BDCODEMP = FC.BDCODEMP and FCN.BDCODCOL = FC.BDCODCOL and FCN.BDREFFN = FC.BDREFFN and FCN.BDREFFC = FC.BDREFFC and FCN.BDCODCONTTI = FC.BDCODCONTTI) '||
                             'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FC.BDCODVER) '||
                             'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FC.BDCODVER) '||
                             'where FC.BDCODEMP = '||prempresa||' and FC.BDCODCOL = '||prcolaborador||' and FC.BDREFFN <= '||pranomes||' and FCN.BDDATAGRRFFC = '''||prdatapgto||''''||
                             ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                             'and VERF.BDFGTSVER > 0 '||
                             'union all '||
                             'select FC.BDVALVFC from VRHF_EMP_TVERBAFCTOMINT FC '||
                             'join VRHF_EMP_TFOLTOMCOMPINT FCN on (FCN.BDCODEMP = FC.BDCODEMP and FCN.BDCODCOL = FC.BDCODCOL and FCN.BDREFTOMADOR = FC.BDREFTOMADOR and FCN.BDREFFC = FC.BDREFFC and FCN.BDORDEM = FC.BDORDEM and FCN.BDCODCONTTI = FC.BDCODCONTTI) '||
                             'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FC.BDCODVER) '||
                             'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FC.BDCODVER) '||
                             'where FC.BDCODEMP = '||prempresa||' and FC.BDCODCOL = '||prcolaborador||' and FC.BDREFTOMADOR <= '||pranomes||' and FCN.BDDATAGRRFFC = '''||prdatapgto||''''||
                             ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                             'and VERF.BDFGTSVER > 0'||
                          ')';

                   EXECUTE STATEMENT wsql INTO :wfgtsind;

                   IF (wfgtsind IS NULL) THEN
                      wfgtsind = 0;
            
                   BDBFGTSIND = wfgtsind;
            
                   bdbfgtsmessefip = bdbfgtsmes - wfgtsind;
            
                   IF (bdbfgtsmessefip < 0) THEN
                      bdbfgtsmessefip = 0;
            
                   wfgtsind = CAST(((wfgtsind * wpercfgtscol / 100) - 0.005) AS NUMERIC(15,2));
            
                   IF (wfgtsind < 0) THEN
                      wfgtsind = 0;

                   wsql = 'select SUM(COALESCE(bdfgtsfc,0)+COALESCE(bdfgts13fc,0)+COALESCE(bdfgtsfefc,0)) '||
                          'from ('||
                             'select bdfgtsfc, bdfgts13fc, bdfgtsfefc from VRHF_EMP_TFOLHACOMP '||
                             'where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDDATAGRRFFC = '''||prdatapgto||''' and BDREFFN < '||pranomes||
                             ' and BDCODTIPOFC = '||prcodtipofc||
                             ' union all '||
                             'select bdfgtsfc, bdfgts13fc, bdfgtsfefc from VRHF_EMP_TFOLTOMCOMP '||
                             'where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDDATAGRRFFC = '''||prdatapgto||''' and BDREFTOMADOR < '||pranomes||
                             ' and BDCODTIPOFC = '||prcodtipofc||
                             ' union all '||
                             'select bdfgtsfc, bdfgts13fc, bdfgtsfefc from VRHF_EMP_TFOLHACOMPINT '||
                             'where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDDATAGRRFFC = '''||prdatapgto||''' and BDREFFN < '||pranomes||
                             ' and BDCODTIPOFC = '||prcodtipofc||
                             ' union all '||
                             'select bdfgtsfc, bdfgts13fc, bdfgtsfefc from VRHF_EMP_TFOLTOMCOMPINT '||
                             'where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador||' and BDDATAGRRFFC = '''||prdatapgto||''' and BDREFTOMADOR < '||pranomes||
                             ' and BDCODTIPOFC = '||prcodtipofc||
                          ')';
             
                   EXECUTE STATEMENT wsql INTO :bdsaldo;
               end

           bdbfgtsmes = COALESCE(bdbfgtsmes, 0);
           bdfgtsmes  = COALESCE(bdfgtsmes , 0);
           BDBFGTSIND = COALESCE(BDBFGTSIND, 0);
           bdsaldo    = COALESCE(bdsaldo, 0);
     
           bdfgts10 = 0;
           if (WCALCULOU = 'FALSE') then
             bdfgts40 = 0;

           if ((WREFFGTSDIGITAL > 0) and (pranomes >= WREFFGTSDIGITAL)) then
              begin
                 if (WCALCULOU = 'FALSE') then
                   bdfgts40 = CAST(((bdfgtsmes + bdfgts13 + bdfgtsind) * (bdpercmulta40 / 100))-0.005 AS NUMERIC(15,2));
                 bdtotal  = bdfgts40+bdfgtsmes+bdfgts13+bdfgtsmesant+bdfgtsind;
              end
           else
              begin
                   IF (bdpercmulta40 > 0) THEN
                      BEGIN
                        WVALORMULTA = CAST(((bdsaldo + bdfgtsmes + bdfgtsmesant) * (bdpercmulta40 / 100))-0.005 AS NUMERIC(15,2));
                        IF (WVALORMULTA > 0) THEN
                           BEGIN
                             IF (bdpercmulta10 > 0) THEN
                                bdfgts10 = CAST(((bdsaldo + bdfgtsmes + bdfgtsmesant) * ((bdpercmulta40 + bdpercmulta10) / 100))-0.005 AS NUMERIC(15,2)) - wvalormulta;
             
                             bdfgts40 = wvalormulta;
                           END
                      END

                   bdfgtsmes = bdfgtsmes - wfgtsind;

                   IF (bdfgtsmessefip < 0) THEN
                      bdfgtsmessefip = 0;

                   bdfgtsmessefip = 0;
                   bdfgtsmesant = 0;
                   bdfgtsind = wfgtsind;

                   IF ((bdfgtsmessefip <= 0) AND (bdfgtsmes > 0) AND (prcodtipofc = 3)) THEN
                     BEGIN
                       if (wintermitente = 111) then
                          begin
                             bdfgtsmessefip = bdfgtsmes + bdfgtsind;
                             bdfgtsind = 0;
                             wfgtsind = wfgtsind + bdfgtsmes;
                          end
                       else
                          bdfgtsmessefip = bdfgtsmes;
        
                       bdfgtsmes = 0;
                     end

                   IF ((pranomes < 202001) AND (prdatapgto < '01/01/2020')) THEN
                     BEGIN
                       bdtotal = bdfgts10+bdfgts40+bdfgtsmes+bdfgtsmesant+wfgtsind;
                     END
                   ELSE
                    BEGIN
                      bdfgts10 = 0;
                      bdtotal = bdfgts40+bdfgts10+bdfgtsmes+bdfgtsmesant+wfgtsind;
                    END
              end
         END
      ELSE
         BEGIN
           if ((WREFFGTSDIGITAL > 0) and (pranomes >= WREFFGTSDIGITAL)) then
               begin
                   bdpossuidatafgtsdigital = 'True';

                   wsql = 'select sum(BDBASEFGTSMESESOCIAL), sum(BDBASEFGTS13ESOCIAL), sum(BDBASEFGTSINDESOCIAL), sum(BDVALORFGTSMESESOCIAL), sum(BDVALORFGTS13ESOCIAL), sum(BDVALORFGTSINDESOCIAL), '||
                          '       sum(BDVALORFGTSMESESOCIAL) + sum(BDVALORFGTS13ESOCIAL)'||
                          'from (select COALESCE(BDBASEFGTSMESESOCIAL, 0)BDBASEFGTSMESESOCIAL, COALESCE(BDVALORFGTSMESESOCIAL, 0)BDVALORFGTSMESESOCIAL, COALESCE(BDBASEFGTS13ESOCIAL, 0)BDBASEFGTS13ESOCIAL, '||
                          '      COALESCE(BDVALORFGTS13ESOCIAL, 0)BDVALORFGTS13ESOCIAL, COALESCE(BDBASEFGTSINDESOCIAL, 0)BDBASEFGTSINDESOCIAL, COALESCE(BDVALORFGTSINDESOCIAL, 0)BDVALORFGTSINDESOCIAL '||
                          '      from VRHF_EMP_TFOLHACOMP where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador;

                    if (PRFILTRARDATA = 'TRUE') then
                        wsql = wsql ||' and BDREFFN = '||pranomes||' and BDCODTIPOFC = '||prcodtipofc||' and BDDATAGRRFFC = '''||prdatapgto||'''';
                    else
                        wsql = wsql || ' and BDREFCOMP = ' || WANOMESCOMPLEMENTAR;

                    wsql = wsql ||' union all '||
                          '      select COALESCE(BDBASEFGTSMESESOCIAL, 0)BDBASEFGTSMESESOCIAL, COALESCE(BDVALORFGTSMESESOCIAL, 0)BDVALORFGTSMESESOCIAL, COALESCE(BDBASEFGTS13ESOCIAL, 0)BDBASEFGTS13ESOCIAL, '||
                          '             COALESCE(BDVALORFGTS13ESOCIAL, 0)BDVALORFGTS13ESOCIAL, COALESCE(BDBASEFGTSINDESOCIAL, 0)BDBASEFGTSINDESOCIAL, COALESCE(BDVALORFGTSINDESOCIAL, 0)BDVALORFGTSINDESOCIAL '||
                          '      from VRHF_EMP_TFOLTOMCOMP where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador;

                    if (PRFILTRARDATA = 'TRUE') then
                        wsql = wsql ||' and BDREFTOMADOR = '||pranomes||' and BDCODTIPOFC = '||prcodtipofc||' and BDDATAGRRFFC = '''||prdatapgto||'''';
                    else
                        wsql = wsql || ' and BDREFCOMP = ' || WANOMESCOMPLEMENTAR;

                    wsql = wsql ||' union all '||
                          '      select COALESCE(BDBASEFGTSMESESOCIAL, 0)BDBASEFGTSMESESOCIAL, COALESCE(BDVALORFGTSMESESOCIAL, 0)BDVALORFGTSMESESOCIAL, COALESCE(BDBASEFGTS13ESOCIAL, 0)BDBASEFGTS13ESOCIAL, '||
                          '             COALESCE(BDVALORFGTS13ESOCIAL, 0)BDVALORFGTS13ESOCIAL, COALESCE(BDBASEFGTSINDESOCIAL, 0)BDBASEFGTSINDESOCIAL, COALESCE(BDVALORFGTSINDESOCIAL, 0)BDVALORFGTSINDESOCIAL '||
                          '      from VRHF_EMP_TFOLHACOMPINT where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador;

                    if (PRFILTRARDATA = 'TRUE') then
                        wsql = wsql ||' and BDREFFN = '||pranomes||' and BDCODTIPOFC = '||prcodtipofc||' and BDDATAGRRFFC = '''||prdatapgto||'''';
                    else
                        wsql = wsql || ' and BDREFCOMP = ' || WANOMESCOMPLEMENTAR;

                    wsql = wsql ||' union all '||
                          '      select COALESCE(BDBASEFGTSMESESOCIAL, 0)BDBASEFGTSMESESOCIAL, COALESCE(BDVALORFGTSMESESOCIAL, 0)BDVALORFGTSMESESOCIAL, COALESCE(BDBASEFGTS13ESOCIAL, 0)BDBASEFGTS13ESOCIAL, '||
                          '             COALESCE(BDVALORFGTS13ESOCIAL, 0)BDVALORFGTS13ESOCIAL, COALESCE(BDBASEFGTSINDESOCIAL, 0)BDBASEFGTSINDESOCIAL, COALESCE(BDVALORFGTSINDESOCIAL, 0)BDVALORFGTSINDESOCIAL '||
                          '      from VRHF_EMP_TFOLTOMCOMPINT where BDCODEMP = '||prempresa||' and BDCODCOL = '||prcolaborador;
                          
                    if (PRFILTRARDATA = 'TRUE') then
                        wsql = wsql ||' and BDREFTOMADOR = '||pranomes||' and BDCODTIPOFC = '||prcodtipofc||' and BDDATAGRRFFC = '''||prdatapgto||''')';
                    else
                        wsql = wsql || ' and BDREFCOMP = ' || WANOMESCOMPLEMENTAR || ')';

                   EXECUTE STATEMENT wsql INTO :bdbfgtsmes, :bdbasefgts13, :BDBFGTSIND, :bdfgtsmes, :bdfgts13, :bdfgtsind,  :bdsaldo;

                   bdfgts40 = CAST(((bdfgtsmes + bdfgts13 + bdfgtsind) * (bdpercmulta40 / 100))-0.005 AS NUMERIC(15,2));
                   bdtotal  = bdfgts40+bdfgtsmes+bdfgts13+bdfgtsmesant+bdfgtsind;
               end
           else
               begin
                   bdpossuidatafgtsdigital = 'False';

                   wsql = 'select sum(bdbfgtsfc) + sum(bdbfgts13fc) + sum(bdbfgtsfefc), sum(bdfgtsfc) + sum(bdfgts13fc) + sum(bdfgtsfefc) '||
                          'from (select coalesce(bdbfgtsfc,0) bdbfgtsfc, coalesce(bdbfgts13fc,0) bdbfgts13fc, coalesce(bdbfgtsfefc,0) bdbfgtsfefc, coalesce(bdfgtsfc,0) bdfgtsfc, coalesce(bdfgts13fc,0) bdfgts13fc, coalesce(bdfgtsfefc,0) bdfgtsfefc '||
                                'from vrhf_emp_tfolhacomp '||
                                'where bdcodemp = '||prempresa||' and bdcodcol = '||prcolaborador;

                    if (PRFILTRARDATA = 'TRUE') then
                        wsql = wsql ||' and bdreffn = '||pranomes||' and bddatagrrffc = '''||prdatapgto||'''';
                    else
                        wsql = wsql || ' and BDREFCOMP = ' || WANOMESCOMPLEMENTAR;

                    wsql = wsql || ' union all '||
                                'select coalesce(bdbfgtsfc,0), coalesce(bdbfgts13fc,0), coalesce(bdbfgtsfefc,0), coalesce(bdfgtsfc,0), coalesce(bdfgts13fc,0), coalesce(bdfgtsfefc,0) '||
                                'from vrhf_emp_tfoltomcomp '||
                                'where bdcodemp = '||prempresa||' and bdcodcol = '||prcolaborador;

                    if (PRFILTRARDATA = 'TRUE') then
                        wsql = wsql ||' and bdreftomador = '||pranomes||' and bddatagrrffc = '''||prdatapgto||'''';
                    else
                        wsql = wsql || ' and BDREFCOMP = ' || WANOMESCOMPLEMENTAR;

                    wsql = wsql || ' union all '||
                                'select coalesce(bdbfgtsfc,0) bdbfgtsfc, coalesce(bdbfgts13fc,0) bdbfgts13fc, coalesce(bdbfgtsfefc,0) bdbfgtsfefc, coalesce(bdfgtsfc,0) bdfgtsfc, coalesce(bdfgts13fc,0) bdfgts13fc, coalesce(bdfgtsfefc,0) bdfgtsfefc '||
                                'from vrhf_emp_tfolhacompint '||
                                'where bdcodemp = '||prempresa||' and bdcodcol = '||prcolaborador;

                    if (PRFILTRARDATA = 'TRUE') then
                        wsql = wsql ||' and bdreffn = '||pranomes||' and bddatagrrffc = '''||prdatapgto||'''';
                    else
                        wsql = wsql || ' and BDREFCOMP = ' || WANOMESCOMPLEMENTAR;

                    wsql = wsql || ' union all '||
                                'select coalesce(bdbfgtsfc,0), coalesce(bdbfgts13fc,0), coalesce(bdbfgtsfefc,0), coalesce(bdfgtsfc,0), coalesce(bdfgts13fc,0), coalesce(bdfgtsfefc,0) '||
                                'from vrhf_emp_tfoltomcompint '||
                                'where bdcodemp = '||prempresa||' and bdcodcol = '||prcolaborador;

                    if (PRFILTRARDATA = 'TRUE') then
                        wsql = wsql ||' and bdreftomador = '||pranomes||' and bddatagrrffc = '''||prdatapgto||''')';
                    else
                        wsql = wsql || ' and BDREFCOMP = ' || WANOMESCOMPLEMENTAR||')';
        
                   EXECUTE STATEMENT wsql INTO : bdbfgtsmes, : bdfgtsmes;
             
                   bdsaldo = 0;
                   bdfgts10 = 0;
                   bdfgts40 = 0;
                   wfgtsind = 0;
        
                   wsql = 'select SUM(BDVALVFC) from ('||
                             'select FC.BDVALVFC from VRHF_EMP_TVERBAFC FC '||
                             'join VRHF_EMP_TFOLHACOMP FCN on (FCN.BDCODEMP = FC.BDCODEMP and FCN.BDCODCOL = FC.BDCODCOL and FCN.BDREFFN = FC.BDREFFN and FCN.BDREFFC = FC.BDREFFC) '||
                             'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FC.BDCODVER) '||
                             'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FC.BDCODVER) '||
                             'where FC.BDCODEMP = '||prempresa||' and FC.BDCODCOL = '||prcolaborador;

                    if (PRFILTRARDATA = 'TRUE') then
                        wsql = wsql ||' and FC.BDREFFN <= '||pranomes||' and FCN.BDDATAGRRFFC = '''||prdatapgto||'''';
                    else
                        wsql = wsql || ' and FCN.BDREFCOMP = ' || WANOMESCOMPLEMENTAR;

                    wsql = wsql || ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                             'and VERF.BDFGTSVER > 0 '||
                             'union all '||
                             'select FC.BDVALVFC from VRHF_EMP_TVERBAFCTOMADOR FC '||
                             'join VRHF_EMP_TFOLTOMCOMP FCN on (FCN.BDCODEMP = FC.BDCODEMP and FCN.BDCODCOL = FC.BDCODCOL and FCN.BDREFTOMADOR = FC.BDREFTOMADOR and FCN.BDREFFC = FC.BDREFFC and FCN.BDORDEM = FC.BDORDEM) '||
                             'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FC.BDCODVER) '||
                             'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FC.BDCODVER) '||
                             'where FC.BDCODEMP = '||prempresa||' and FC.BDCODCOL = '||prcolaborador;

                    if (PRFILTRARDATA = 'TRUE') then
                        wsql = wsql ||' and FC.BDREFTOMADOR <= '||pranomes||' and FCN.BDDATAGRRFFC = '''||prdatapgto||'''';
                    else
                        wsql = wsql || ' and FCN.BDREFCOMP = ' || WANOMESCOMPLEMENTAR;

                    wsql = wsql || ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                             'and VERF.BDFGTSVER > 0'||
                             'union all '||
                             'select FC.BDVALVFC from VRHF_EMP_TVERBAFCINT FC '||
                             'join VRHF_EMP_TFOLHACOMPINT FCN on (FCN.BDCODEMP = FC.BDCODEMP and FCN.BDCODCOL = FC.BDCODCOL and FCN.BDREFFN = FC.BDREFFN and FCN.BDREFFC = FC.BDREFFC and FCN.BDCODCONTTI = FC.BDCODCONTTI) '||
                             'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FC.BDCODVER) '||
                             'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FC.BDCODVER) '||
                             'where FC.BDCODEMP = '||prempresa||' and FC.BDCODCOL = '||prcolaborador;

                    if (PRFILTRARDATA = 'TRUE') then
                        wsql = wsql ||' and FC.BDREFFN <= '||pranomes||' and FCN.BDDATAGRRFFC = '''||prdatapgto||'''';
                    else
                        wsql = wsql || ' and FCN.BDREFCOMP = ' || WANOMESCOMPLEMENTAR;

                    wsql = wsql || ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                             'and VERF.BDFGTSVER > 0 '||
                             'union all '||
                             'select FC.BDVALVFC from VRHF_EMP_TVERBAFCTOMINT FC '||
                             'join VRHF_EMP_TFOLTOMCOMPINT FCN on (FCN.BDCODEMP = FC.BDCODEMP and FCN.BDCODCOL = FC.BDCODCOL and FCN.BDREFTOMADOR = FC.BDREFTOMADOR and FCN.BDREFFC = FC.BDREFFC and FCN.BDORDEM = FC.BDORDEM and FCN.BDCODCONTTI = FC.BDCODCONTTI) '||
                             'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FC.BDCODVER) '||
                             'join VW_VERBAS_REF_ATUAL VERF on (VERF.BDCODVER = FC.BDCODVER) '||
                             'where FC.BDCODEMP = '||prempresa||' and FC.BDCODCOL = '||prcolaborador;

                    if (PRFILTRARDATA = 'TRUE') then
                        wsql = wsql ||' and FC.BDREFTOMADOR <= '||pranomes||' and FCN.BDDATAGRRFFC = '''||prdatapgto||'''';
                    else
                        wsql = wsql || ' and FCN.BDREFCOMP = ' || WANOMESCOMPLEMENTAR;

                    wsql = wsql || ' and (VER.BDCLAVER like '''||'7.001.3%'||''' or VER.BDCLAVER like '''||'7.020%'||''' or VER.BDCLAVER like '''||'7.021%'||''' or VER.BDCLAVER like '''||'7.060%'''||') '||
                             'and VERF.BDFGTSVER > 0'||
                          ') ';
        
                   EXECUTE STATEMENT wsql INTO :wbfgtsind;
        
                   IF (wfgtsind IS NULL) THEN
                      wfgtsind = 0;
        
                   BDBFGTSIND = wbfgtsind;
        
                   IF (wbfgtsind > 0) THEN
                      BEGIN
                        bdbfgtsmes = bdbfgtsmes - wbfgtsind;
        
                        bdfgtsmes = CAST(((bdbfgtsmes * wpercfgtscol / 100) - 0.005) AS NUMERIC(15,2));
                        wfgtsind = CAST(((wbfgtsind * wpercfgtscol / 100) - 0.005) AS NUMERIC(15,2));
                      END
        
                   IF (bdpercmulta40 > 0) THEN
                      BEGIN
                        WVALORMULTA = CAST(((bdsaldo + bdfgtsmes + bdfgtsmesant + wfgtsind) * (bdpercmulta40 / 100))-0.005 AS NUMERIC(15,2));
                        IF (WVALORMULTA > 0) THEN
                           BEGIN
                             IF (bdpercmulta10 > 0) THEN
                                bdfgts10 = CAST(((bdsaldo + bdfgtsmes + bdfgtsmesant + wfgtsind) * ((bdpercmulta40 + bdpercmulta10) / 100))-0.005 AS NUMERIC(15,2)) - wvalormulta;
             
                             bdfgts40 = wvalormulta;
                           END
                      END
        
                   bdfgtsind = wfgtsind;
                   bdbfgtsmes = bdbfgtsmes + wbfgtsind;


                   IF ((pranomes < 202001) and (prdatapgto < '01/01/2020')) then
                     BEGIN
                        bdtotal = bdfgts10+bdfgts40+bdfgtsmes+bdfgtsmesant+wfgtsind;
                     END
                   ELSE
                    BEGIN
                       bdfgts10 = 0;
                       if (COALESCE(PRRELGRRF, 'FALSE') = 'FALSE') then
                          bdtotal = bdfgts10+bdfgts40+bdfgtsmes+bdfgtsmesant+wfgtsind;
                       else
                          bdtotal = bdfgts10+bdfgts40+bdfgtsmes+bdfgtsmesant;
                    END
               end
         END
    END
         
  SUSPEND;
END^

/* Restore proc. body: VRHF_MEDIAS */
ALTER PROCEDURE VRHF_MEDIAS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATAINICIO DATE,
PRDATAFINAL DATE,
PRFILTROCLASS VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDDATALANC DATE,
BDREFLANC NUMERIC(15,6),
BDVALLANC NUMERIC(15,6),
BDREFCONGLANC VARCHAR(5),
BDVALCONGLANC VARCHAR(5),
BDORIGEMLANC INTEGER,
BDCOMPLANC INTEGER,
BDCLAVER VARCHAR(20))
 AS
DECLARE VARIABLE wsql VARCHAR(32700);
DECLARE VARIABLE wfrom VARCHAR(1000);
DECLARE VARIABLE wwhere VARCHAR(15000);
BEGIN
  wsql = 'select PL.BDCODEMP, '||
                'PL.BDCODCOL, '||
                'PL.BDCODVER, '||
                'PL.BDDATA, '||
                'PL.BDREFV, '||
                'PL.BDVALV, '||
                'PL.BDREFCONG, '||
                'PL.BDVALCONG, '||
                'PL.BDORIGEM, '||
                'PL.BDCOMP, '||
                'VR.BDCLAVER ';

  wfrom = 'from VW_UNION_PL_VERBAS_FF PL, VRH_BASE_TVERBAS VR ';

  wwhere = ' where PL.BDCODVER = VR.BDCODVER ';

  IF (prfiltroclass IS NOT NULL AND prfiltroclass <> '') THEN
     wwhere = wwhere||' and ('||prfiltroclass||') ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and '||prcodemp;


  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||' and '||prcodcol;

  IF (prdatainicio IS NOT NULL AND prdatafinal IS NOT NULL) THEN
     wwhere = wwhere||' and PL.BDDATA between '''||prdatainicio||''' and '''||prdatafinal||'''';

  wsql = wsql||wfrom||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDDATALANC,
    :BDREFLANC,
    :BDVALLANC,
    :BDREFCONGLANC,
    :BDVALCONGLANC,
    :BDORIGEMLANC,
    :BDCOMPLANC,
    :BDCLAVER
  DO
  SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_ACU_GPS_FUNRURAL */
CREATE OR ALTER procedure VRHF_SP_ACU_GPS_FUNRURAL (
    PRCODIMP integer,
    PRCODEMP varchar(30000),
    PRREFERENCIA integer,
    PRLISTANOTAS varchar(30000) = null)
returns (
    BDCODEMP integer,
    BDTIPO integer,
    BDVALACU numeric(15,6),
    BDVALACUTER numeric(15,6))
as
declare variable WSQLEMP varchar(32000);
declare variable WIMP integer;
declare variable WSQL varchar(30000);
declare variable WOPCAOESOCIAL integer;
declare variable WREFINIDCTFWEB integer;
BEGIN
  /* Procedure Text */

  IF (prcodemp IS NULL) THEN
     prcodemp = 'null';
  ELSE
     prcodemp = ''''||prcodemp||'''';

  IF (prreferencia IS NULL) THEN
     prreferencia = 0;

  wsqlemp = 'select EMP.bdCODIMP,EMP.BDCODEMP, FASEMP.BDOPCAOESOCIAL, FASEMP.BDREFINIDCTFWEB '||
            'from sp_tempresaimposto_ref('||prcodemp||','||prreferencia||',0) EMP '||
            'join VRH_ESOCIAL_TFASEAMENTO FASEMP on (FASEMP.BDCODEMP = EMP.BDCODEMP) '||
            'where EMP.BDDOCARRECADACAO = 21 ';

  IF (prcodimp IS NOT NULL) THEN
     wsqlemp = wsqlemp||' and EMP.bdcodimp = '||prcodimp;

  wsqlemp = wsqlemp||' order by EMP.bdCODIMP, EMP.BDCODEMP';

  FOR EXECUTE STATEMENT wsqlemp INTO :wimp, :bdcodemp, :wopcaoesocial, :wrefinidctfweb DO
    BEGIN
      if ((coalesce(wopcaoesocial, 0) = 0) or (coalesce(wrefinidctfweb, 0) = 0) or (coalesce(wopcaoesocial, 0) = 1 and coalesce(wrefinidctfweb, 0) > 0 and :prreferencia < coalesce(wrefinidctfweb, 0))) then
         begin
           bdtipo = 1;
           bdvalacu = 0;
           bdvalacuter = 0;
           wsql = 'SELECT FIRST 1 darf.bdvlracumulo,darf.bdvlracuoutent '||
                  'FROM tdarfpadrao darf '||
                  'WHERE darf.bdcodemp = '||BDCODEMP||
                   ' AND darf.bdcodimp = '||wimp||
                   ' AND darf.bdreferencia <= '||prreferencia;
     
          if (coalesce(prlistanotas,  '') <> '') then
             begin
                -- wsql = wsql||' AND '||replace(upper(prlistanotas), 'BDNOTAFISCAL', 'DARF.BDNOTAFISCAL');
                wsql = wsql || ' and (POSITION('','||prlistanotas||','' IN '','' || REPLACE(BDNOTAFISCAL, '' '', '''') || '','') = 0 '||
                               ' AND POSITION('''||prlistanotas||','' IN REPLACE(BDNOTAFISCAL, '' '', '''') || '','') = 0 ' ||
                               ' AND POSITION('','||prlistanotas||''' IN '','' || REPLACE(BDNOTAFISCAL, '' '', '''') || '','') = 0)';
             end
     
     
          wsql = wsql||' ORDER BY darf.bdreferencia DESC, darf.bdchavedarf DESC ';
     
          execute statement wsql INTO bdvalacu, bdvalacuter;
          IF ((bdvalacu <> 0) OR (bdvalacuter <> 0)) THEN
             SUSPEND;
        end
   END
END^


/* Restore proc. body: VRHF_SP_ARREDONDAMENTOS */
ALTER PROCEDURE VRHF_SP_ARREDONDAMENTOS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRTIPOCALCULO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFARRE INTEGER,
BDVALARRE NUMERIC(15,6))
 AS
DECLARE VARIABLE WREF VARCHAR(50);
DECLARE VARIABLE WTABLE VARCHAR(255);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(25000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, NULL);

  wsql = 'select FOL.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'FOL.BDCODCOL, '||
                'COL.BDNOMCOL, ';

  /* Tipos de calculo:
     -----------------
     0 - Todos; (nAo pode ser todos)
     1 - Folha normal;
     2 - Adiantamento salarial;
     3 - Adiantamento de 13o. salario;
     4 - 13o. salario;
     5 - Complemento de 13o. salario;
     6 - Ferias;
     7 - PLR;
     8 - Folha complementar;
     9 - Rescisao. (folha normal)
  */

  IF (prtipocalculo = 2) THEN
     BEGIN
       wsql = wsql||'cast((substring((cast(FOL.BDDATAAD as VARCHAR(10))) from 1 for 4)||substring((cast(FOL.BDDATAAD as VARCHAR(10))) from 6 for 2)) as INTEGER) BDREF, '||
                    'FOL.BDVALVAD ';
       wTable = 'VRHF_EMP_TVERBAAD';
       wref = 'FOL.BDDATAAD';
     END
  ELSE
  IF (prtipocalculo = 3) THEN
     BEGIN
       wsql = wsql||'FOL.BDREFA13, '||
                    'FOL.BDVALVA13 ';
       wTable = 'VRHF_EMP_TVERBAA13';
       wref = 'FOL.BDREFA13';
     END
  ELSE
  IF (prtipocalculo = 4) THEN
     BEGIN
       wsql = wsql||'FOL.BDREF13, '||
                    'FOL.BDVALV13 ';
       wTable = 'VRHF_EMP_TVERBA13';
       wref = 'FOL.BDREF13';
     END
  ELSE
  IF (prtipocalculo = 5) THEN
     BEGIN
       wsql = wsql||'FOL.BDREFC13, '||
                    'FOL.BDVALVC13 ';
       wTable = 'VRHF_EMP_TVERBAC13';
       wref = 'FOL.BDREFC13';
     END
  ELSE
  IF (prtipocalculo = 6) THEN
     BEGIN
       wsql = wsql||'FOL.BDREFFE, '||
                    'FOL.BDVALVRFE ';
       wTable = 'VRHF_EMP_TVERBAFE';
       wref = 'FOL.BDREFFE';
     END
  ELSE
  IF (prtipocalculo = 8) THEN
     BEGIN
       wsql = wsql||'FOL.BDREFCOMP, '||
                    'FOL.BDVALVFC ';
       wTable = 'VRHF_EMP_TVERBAFC';
       wref = 'FOL.BDREFCOMP';
     END
  ELSE
     BEGIN
       wsql = wsql||'FOL.BDREFFN, '||
                    'FOL.BDVALVFN ';
       wTable = 'VWRH_UNION_FN_FT_MES';
       wref = 'FOL.BDREFFN';
     END

  wsql = wsql||
         'from '||wtable||' FOL '||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
         'on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) '||
         'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
         'on (EMP.BDCODEMP = FOL.BDCODEMP) '||
         'left outer join VW_VRHF_EMPRESAS_REF_ATUAL ARRED '||
         'on (ARRED.BDCODEMP = FOL.BDCODEMP) '||
         'left outer join vrh_base_tverbas VERBAS '||
         'on (VERBAS.BDCODVER = FOL.BDCODVER) ';

  wwhere = 'where ((ARRED.bdtipoarremp < 2 and VERBAS.BDCLAVER like '''||'9.001.0%'||''') or '||
                  '(ARRED.bdtipoarremp >= 2 and VERBAS.BDCLAVER like '''||'9.001.1%'||''')) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||' and '||prcodcol;

  wsql = wsql||wwhere||' order by FOL.BDCODEMP, FOL.BDCODCOL, '||wref||' DESC ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDREFARRE,
    :BDVALARRE
  DO

  SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_BANCO_HORAS */
CREATE OR ALTER PROCEDURE VRHF_SP_BANCO_HORAS (
    PREMPRESAS VARCHAR(30000),
    PRCOLAB VARCHAR(30000),
    PRREFFIM INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDREFERENCIA INTEGER,
    BDSALDOINICIAL NUMERIC(18,6),
    BDCREDITO NUMERIC(18,6),
    BDDEBITO NUMERIC(18,6),
    BDSALDOFINAL NUMERIC(18,6))
AS
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WREFHOREMP VARCHAR(5);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WCOLATU INTEGER;
DECLARE VARIABLE WREF INTEGER;
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WDEB NUMERIC(18,6);
DECLARE VARIABLE WDEBATU NUMERIC(18,6);
DECLARE VARIABLE WCRE NUMERIC(18,6);
DECLARE VARIABLE WCREATU NUMERIC(18,6);
DECLARE VARIABLE WSQLAUX VARCHAR(1000);
DECLARE VARIABLE WAUX NUMERIC(18,6);
DECLARE VARIABLE WTOTDEB NUMERIC(18,6);
DECLARE VARIABLE WTOTCRE NUMERIC(18,6);
BEGIN
  /* Procedure Text */
  wsql = 'select bdcodemp, bdcodcol, bdreferencia, bddebito, bdcredito from vrhf_emp_tlanbancohoras ';

  IF (prempresas IS NOT NULL AND prempresas <> '') THEN
     BEGIN
       wsql = wsql||' where '||prempresas;

       IF ((prcolab IS NOT NULL) AND (prcolab <> '')) THEN
          wsql = wsql||' and '||prcolab;
     END

  IF (prreffim IS NOT NULL AND prreffim <> 0) THEN
     BEGIN
       IF (prempresas IS NOT NULL AND prempresas <> '') THEN
          wsql = wsql||' and ';
       ELSE
          wsql = wsql||' where ';
       wsql = wsql||' bdreferencia <= '||prreffim;

     END

  wsql = wsql||' order by bdcodemp, bdcodcol, bdreferencia';

  wempatu = 0;
  wcolatu = 0;
  wrefatu = 0;
  wdebatu = 0;
  wcreatu = 0;
  wtotdeb = 0;
  wtotcre = 0;
  wrefhoremp = 'FALSE';

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wref, :wdeb, :wcre DO
    BEGIN
      IF (wempatu = 0) THEN
         BEGIN
           wempatu = wcodemp;
           wsqlaux = 'SELECT first 1 bdrefhoremp FROM VRHF_BASE_TEMPCALC WHERE BDCODEMP = '||wcodemp||' and BDREFEMP <= '||prreffim||' order by BDREFEMP DESC ';
           EXECUTE STATEMENT wsqlaux INTO :wrefhoremp;
         END

      IF (wcolatu = 0) THEN
         wcolatu = wcodcol;

      IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol)) THEN
         BEGIN
           BDCODEMP       = wempatu;
           BDCODCOL       = wcolatu;
           BDREFERENCIA   = wrefatu;

           IF (UPPER(wrefhoremp) = 'TRUE') THEN
              BEGIN
                waux = CAST((wtotdeb - TRUNC(wtotdeb)) AS NUMERIC(18,6));
                waux = CAST((waux / 60 * 100) AS NUMERIC(18,6));
                wtotdeb = CAST((TRUNC(wtotdeb) + waux) AS NUMERIC(18,6));

                waux = CAST((wtotcre - TRUNC(wtotcre)) AS NUMERIC(18,6));
                waux = CAST((waux / 60 * 100) AS NUMERIC(18,6));
                wtotcre = CAST((TRUNC(wtotcre) + waux) AS NUMERIC(18,6));
     
                BDSALDOINICIAL = CAST((wtotcre - wtotdeb) AS NUMERIC(18,2));

                waux = CAST((wdebatu - TRUNC(wdebatu)) AS NUMERIC(18,6));
                waux = CAST((waux / 60 * 100) AS NUMERIC(18,6));
                wdebatu = CAST((TRUNC(wdebatu) + waux) AS NUMERIC(18,6));

                waux = CAST((wcreatu - TRUNC(wcreatu)) AS NUMERIC(18,6));
                waux = CAST((waux / 60 * 100) AS NUMERIC(18,6));
                wcreatu = CAST((TRUNC(wcreatu) + waux) AS NUMERIC(18,6));

                IF (wrefatu = prreffim) THEN
                   BDSALDOINICIAL = CAST((BDSALDOINICIAL - wcreatu + wdebatu) AS NUMERIC(18,2));

                IF (wrefatu < prreffim) THEN
                   BEGIN
                     wdebatu = 0;
                     wcreatu = 0;
                     BDDEBITO  = 0;
                     BDCREDITO = 0;
                   END
                ELSE
                   BEGIN
                     waux = CAST((wdebatu - TRUNC(wdebatu)) AS NUMERIC(18,6));
                     waux = CAST((waux / 100 * 60) AS NUMERIC(18,6));
                     BDDEBITO = CAST((TRUNC(wdebatu) + waux) AS NUMERIC(18,2));

                     waux = CAST((wcreatu - TRUNC(wcreatu)) AS NUMERIC(18,6));
                     waux = CAST((waux / 100 * 60) AS NUMERIC(18,6));
                     BDCREDITO = CAST((TRUNC(wcreatu) + waux) AS NUMERIC(18,2));
                   END

                BDSALDOFINAL = CAST((BDSALDOINICIAL + wcreatu - wdebatu) AS NUMERIC(18,2));

                waux = CAST((BDSALDOINICIAL - TRUNC(BDSALDOINICIAL)) AS NUMERIC(18,6));
                waux = CAST((waux / 100 * 60) AS NUMERIC(18,6));
                BDSALDOINICIAL = CAST((TRUNC(BDSALDOINICIAL) + waux) AS NUMERIC(18,2));

                waux = CAST((BDSALDOFINAL - TRUNC(BDSALDOFINAL)) AS NUMERIC(18,6));
                waux = CAST((waux / 100 * 60) AS NUMERIC(18,6));
                BDSALDOFINAL = CAST((TRUNC(BDSALDOFINAL) + waux) AS NUMERIC(18,2));
              END
           ELSE
              BEGIN
                BDSALDOINICIAL = wtotcre - wtotdeb;

                IF (wrefatu = prreffim) THEN
                   BDSALDOINICIAL = BDSALDOINICIAL - wcreatu + wdebatu;

                IF (wrefatu < prreffim) THEN
                   BEGIN
                     wdebatu = 0;
                     wcreatu = 0;
                   END

                BDDEBITO     = wdebatu;
                BDCREDITO    = wcreatu;

                BDSALDOFINAL = BDSALDOINICIAL + wcreatu - wdebatu;
              END

           SUSPEND;
           wempatu = wcodemp;
           wcolatu = wcodcol;
           wtotcre = 0;
           wtotdeb = 0;

           wsqlaux = 'SELECT first 1 bdrefhoremp FROM VRHF_BASE_TEMPCALC WHERE BDCODEMP = '||wcodemp||' and BDREFEMP <= '||prreffim||' order by BDREFEMP DESC ';
           EXECUTE STATEMENT wsqlaux INTO :wrefhoremp;
         END

      wdebatu = wdeb;
      wcreatu = wcre;
      wrefatu = wref;

      IF (wrefhoremp IS NULL) THEN
          wrefhoremp = 'FALSE';

      IF (UPPER(wrefhoremp) = 'TRUE') THEN
         BEGIN
           -- convertendo para decimal
           waux = CAST((wtotdeb - TRUNC(wtotdeb)) AS NUMERIC(18,6));
           waux = CAST((waux / 60 * 100) AS NUMERIC(18,6));
           wtotdeb = CAST((TRUNC(wtotdeb) + waux) AS NUMERIC(18,6));

           waux = CAST((wdebatu - TRUNC(wdebatu)) AS NUMERIC(18,6));
           waux = CAST((waux / 60 * 100) AS NUMERIC(18,6));
           wdebatu = CAST((TRUNC(wdebatu) + waux) AS NUMERIC(18,6));

           waux = CAST((wtotcre - TRUNC(wtotcre)) AS NUMERIC(18,6));
           waux = CAST((waux / 60 * 100) AS NUMERIC(18,6));
           wtotcre = CAST((TRUNC(wtotcre) + waux) AS NUMERIC(18,6));

           waux = CAST((wcreatu - TRUNC(wcreatu)) AS NUMERIC(18,6));
           waux = CAST((waux / 60 * 100) AS NUMERIC(18,6));
           wcreatu = CAST((TRUNC(wcreatu) + waux) AS NUMERIC(18,6));

           wtotdeb = wtotdeb + wdebatu;
           wtotcre = wtotcre + wcreatu;

           -- convertendo para horas
           waux = CAST((wtotdeb - TRUNC(wtotdeb)) AS NUMERIC(18,6));
           waux = CAST((waux / 100 * 60) AS NUMERIC(18,6));
           wtotdeb = CAST((TRUNC(wtotdeb) + waux) AS NUMERIC(18,2));

           waux = CAST((wtotcre - TRUNC(wtotcre)) AS NUMERIC(18,6));
           waux = CAST((waux / 100 * 60) AS NUMERIC(18,6));
           wtotcre = CAST((TRUNC(wtotcre) + waux) AS NUMERIC(18,2));

           wdebatu = wdeb;
           wcreatu = wcre;
         END
      ELSE
         BEGIN
           wtotdeb = wtotdeb + wdebatu;
           wtotcre = wtotcre + wcreatu;
         END
    END


  IF (wempatu <> 0 AND wcolatu <> 0) THEN
     BEGIN
       BDCODEMP       = wempatu;
       BDCODCOL       = wcolatu;
       BDREFERENCIA   = wrefatu;

       IF (UPPER(wrefhoremp) = 'TRUE') THEN
          BEGIN
            waux = CAST((wtotdeb - TRUNC(wtotdeb)) AS NUMERIC(18,6));
            waux = CAST((waux / 60 * 100) AS NUMERIC(18,6));
            wtotdeb = CAST((TRUNC(wtotdeb) + waux) AS NUMERIC(18,6));

            waux = CAST((wtotcre - TRUNC(wtotcre)) AS NUMERIC(18,6));
            waux = CAST((waux / 60 * 100) AS NUMERIC(18,6));
            wtotcre = CAST((TRUNC(wtotcre) + waux) AS NUMERIC(18,6));
 
            BDSALDOINICIAL = CAST((wtotcre - wtotdeb) AS NUMERIC(18,2));

            waux = CAST((wdebatu - TRUNC(wdebatu)) AS NUMERIC(18,6));
            waux = CAST((waux / 60 * 100) AS NUMERIC(18,6));
            wdebatu = CAST((TRUNC(wdebatu) + waux) AS NUMERIC(18,6));

            waux = CAST((wcreatu - TRUNC(wcreatu)) AS NUMERIC(18,6));
            waux = CAST((waux / 60 * 100) AS NUMERIC(18,6));
            wcreatu = CAST((TRUNC(wcreatu) + waux) AS NUMERIC(18,6));

            IF (wrefatu = prreffim) THEN
               BDSALDOINICIAL = CAST((BDSALDOINICIAL + wdebatu - wcreatu) AS NUMERIC(18,2));

            IF (wrefatu < prreffim) THEN
               BEGIN
                 wdebatu = 0;
                 wcreatu = 0;
                 BDDEBITO  = 0;
                 BDCREDITO = 0;
               END
            ELSE
               BEGIN
                 waux = CAST((wdebatu - TRUNC(wdebatu)) AS NUMERIC(18,6));
                 waux = CAST((waux / 100 * 60) AS NUMERIC(18,6));
                 BDDEBITO = CAST((TRUNC(wdebatu) + waux) AS NUMERIC(18,2));

                 waux = CAST((wcreatu - TRUNC(wcreatu)) AS NUMERIC(18,6));
                 waux = CAST((waux / 100 * 60) AS NUMERIC(18,6));
                 BDCREDITO = CAST((TRUNC(wcreatu) + waux) AS NUMERIC(18,2));
               END

            BDSALDOFINAL = CAST((BDSALDOINICIAL + wcreatu - wdebatu) AS NUMERIC(18,2));

            waux = CAST((BDSALDOINICIAL - TRUNC(BDSALDOINICIAL)) AS NUMERIC(18,6));
            waux = CAST((waux / 100 * 60) AS NUMERIC(18,6));
            BDSALDOINICIAL = CAST((TRUNC(BDSALDOINICIAL) + waux) AS NUMERIC(18,2));

            waux = CAST((BDSALDOFINAL - TRUNC(BDSALDOFINAL)) AS NUMERIC(18,6));
            waux = CAST((waux / 100 * 60) AS NUMERIC(18,6));
            BDSALDOFINAL = CAST((TRUNC(BDSALDOFINAL) + waux) AS NUMERIC(18,2));
          END
       ELSE
          BEGIN
            BDSALDOINICIAL = wtotcre - wtotdeb;

            IF (wrefatu = prreffim) THEN
               BDSALDOINICIAL = BDSALDOINICIAL - wcreatu + wdebatu;

           IF (wrefatu < prreffim) THEN
              BEGIN
                wdebatu = 0;
                wcreatu = 0;
              END

            BDDEBITO     = wdebatu;
            BDCREDITO    = wcreatu;
            BDSALDOFINAL = BDSALDOINICIAL + wcreatu - wdebatu;
          END

       SUSPEND;
     END
END
^

/* Restore proc. body: VRHF_SP_CALC_AUTONOMO */
create or alter procedure VRHF_SP_CALC_AUTONOMO (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFERENCIA integer,
    PRSERVICO integer,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(2788) = null,
    PRCODTPCC varchar(10000) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFV numeric(15,6),
    BDREFAUXV numeric(15,6),
    BDVALV numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNVALV varchar(5),
    BDTIPOCODVER integer,
    BDORDEMTIPOCODVER integer,
    BDINSSVER integer,
    BDFGTSVER integer,
    BDIRVER integer,
    BDTIPOREFVER integer,
    BDBASESFVER integer,
    BDPISVER varchar(5),
    BDBASEHEVER varchar(5),
    BDBASEMAIORVER varchar(5),
    BDRAISVER varchar(5),
    BDBASEGPSVER varchar(5),
    BDMENORESVER varchar(5),
    BDPROPVER varchar(5),
    BDBASEVTVER varchar(5),
    BDREEMBGPSVER varchar(5),
    BDHEVER numeric(15,6),
    BDGRAVAFICHAHNVER varchar(5),
    BDCCPRINCIPALVER varchar(5),
    BDFORMREFAUXVER varchar(5000),
    BDFORMREFVER varchar(5000),
    BDFORMVALVER varchar(5000),
    BDBASEDSRHEVER varchar(5),
    BDBASEDSRRVVER varchar(5),
    BDDEDFORMREFAUXVER varchar(5),
    BDDEDFORMREFVER varchar(5),
    BDDEDFORMVALVER varchar(5),
    BDDESCVER varchar(40),
    BDDESCREDVER varchar(20),
    BDCLAVER varchar(20),
    BDORDEMVER integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDDETALHE varchar(255),
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDBINSSCALC numeric(15,6),
    BDBIRCALC numeric(15,6),
    BDDATAPGTO date)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WEMPATU integer;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRREFERENCIA, NULL, NULL);

  wsql = 'select ';
/*01*/  wsql = wsql||'FN.BDCODEMP, '||
/*02*/               'FN.BDCODTER, '||
/*03*/               'FN.BDCODVER, '||
/*04*/               'FN.BDCODSERV, '||
/*05*/               'FN.BDREFERENCIA, '||
/*06*/               'FN.BDREFAUXILIAR, '||
/*07*/               'FN.BDVALOR, '||
/*08*/               'FN.BDIGNFORREF, '||
/*09*/               'FN.BDIGNFORVAL, '||
/*41*/               'SERV.BDDATABAIXA,'||/*'FOLN.BDDATABAIXAFN, '|| */ /*CRIAR CAMPO TABELA*/
/*42*/               '0.0, '|| /*FOLN.BDBFGTSFN*/
/*43*/               '0.0, '|| /*FOLN.BDFGTSFN*/
/*44*/               '0.0, '|| /*FOLN.BDFGTSCSFN*/
/*45*/               '0.0, '|| /*FOLN.BDBFGTS13FN*/
/*46*/               '0.0, '|| /*FOLN.BDFGTS13FN*/
/*47*/               '0.0, '|| /*FOLN.BDFGTS13CSFN*/
/*48*/               '0.0, '|| /*FOLN.BDMAIORREMFN*/
/*49*/               'FOLN.BDBASEINSS, '||
/*50*/               'FOLN.BDFAIXAINSS, '||
/*51*/               'FOLN.BDVALORINSS, '||
/*52*/               'FOLN.BDBASEIR, '||
/*53*/               'FOLN.BDFAIXAIR, '||
/*54*/               'FOLN.BDVALORIR, '||
/*55*/               '0.0, '|| /*FOLN.BDBINSS13FN*/
/*56*/               '0.0, '|| /*FOLN.BDALIQINSS13FN*/
/*57*/               '0.0, '|| /*FOLN.BDINSS13FN*/
/*58*/               '0.0, '|| /*FOLN.BDBIRRF13FN*/
/*59*/               '0.0, '|| /*FOLN.BDALIQIRRF13FN*/
/*60*/               '0.0, '|| /*FOLN.BDIRRF13FN*/
/*61*/               '0.0, '|| /*FOLN.BDBSALFAMFN*/
/*62*/               '0.0, '|| /*FOLN.BDSALFAMFN*/
/*63*/               '0.0, '|| /*FOLN.BDBRAISFN*/
/*64*/               'SERV.BDVALORSERV, '||
/*65*/               'FOLN.BDVALORDEP, '||
/*67*/               '0.0, '|| /*FOLN.BDBINSSFEFOLFN*/
/*68*/               '0.0, '|| /*FOLN.BDINSSFEFOLFN*/
/*69*/               '0.0, '|| /*FOLN.BDALIQINSSFEFOLFN*/
/*70*/               'FOLN.BDCREDITOSERV, '||
/*71*/               'FOLN.BDDEBITOSERV, '||
                     'FOLN.BDBASEIRCALC, '||
--                     'case when coalesce(FOLN.BDBASEINSSNMVNOVO, 0) <> 0 then FOLN.BDBASEINSSNMVNOVO else FOLN.BDBINSSCALC end BDBINSSCALC, '||       /* 163256 Leonardo Schwab - Não deve utilizar o campo de INSSMVNOVO */
                     'FOLN.BDBINSSCALC, '||                                                                                                             /* 163256 Leonardo Schwab */
                     'SERV.BDDATAPAGSERV ';

  wsql = wsql||'from VRHF_BASE_ITEMS_CALCTERC FN '|| /*OK*/
--               ' join VW_VERBAS_REF_ATUAL RVA '|| /*OK*/
--                 'on (RVA.BDCODVER = FN.BDCODVER) '||
               ' join VRH_BASE_TSERVTERC SERV '||
                 'on (SERV.BDCODEMP = FN.BDCODEMP and SERV.BDCODTER = FN.BDCODTER and SERV.BDCODSERV = FN.BDCODSERV) '||
--               ' join VRH_BASE_TVERBAS VER '|| /*OK*/
--                 'on (VER.BDCODVER = FN.BDCODVER) '||
--               ' join VW_VRHF_BASE_TEMPCALC EMPREF '|| /*OK*/
--                 'on (EMPREF.BDCODEMP = FN.BDCODEMP) '||
               ' join VRHF_BASE_CALC_TERC FOLN '|| /*OK*/
                 'on (FOLN.BDCODEMP = FN.BDCODEMP and FOLN.BDCODTER = FN.BDCODTER and FOLN.BDCODSERV = FN.BDCODSERV) ';

  if (position(upper('tmp_empresas_select'), upper(prcodemp)) > 0) then
    wsql = wsql||' '||prcodemp;

  IF (prpuxafiliais = 1) THEN
     BEGIN
       wsql = wsql||' join tempresas emp on (fn.bdcodemp = emp.bdcodemp) ';

       prcodemp = UPPER(prcodemp);

       IF ((prfiliais IS NOT NULL) AND (prfiliais <> '')) THEN
          BEGIN
            SELECT bdresult FROM strtran(:prcodemp,'FN.BDCODEMP','EMP.BDCODMATRIZ') INTO wwhere;
            prcodemp = '('||prcodemp||' or (('||wwhere||') and (emp.bdcodemp in ('||prfiliais||'))))';
          END
       ELSE
          BEGIN
            SELECT bdresult FROM strtran(:prcodemp,'FN.BDCODEMP','coalesce(emp.bdcodmatriz,emp.bdcodemp)') INTO prcodemp;
          END
     END

  wwhere = '';

  IF ((prcodemp IS NOT NULL) and (position(upper('tmp_empresas_select'), upper(prcodemp)) <= 0)) THEN
     wwhere = wwhere||PRCODEMP;

  IF (prcodcol IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||PRCODCOL;
     END

  IF (prservico IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'FN.BDCODSERV = '||prservico;
     END

  IF (prreferencia IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'(select bdaaaamm from aaaamm(SERV.bddataserv) ) = '||prreferencia;
     END

  IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       wwhere = wwhere||prcodtpcc;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  wsql = wsql||' order by FN.BDCODEMP, FN.BDCODVER ';

  wempatu = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
/*01*/    :BDCODEMP,
/*02*/    :BDCODCOL,
/*03*/    :BDCODVER,
/*04*/    :BDREFFN, /* :bdcodserv, */
/*05*/    :BDREFV,
/*06*/    :BDREFAUXV,
/*07*/    :BDVALV,
/*08*/    :BDIGNREFV,
/*09*/    :BDIGNVALV,
/*41*/    :BDDATABAIXA,
/*42*/    :BDBFGTS,
/*43*/    :BDFGTS,
/*44*/    :BDFGTSCS,
/*45*/    :BDBFGTS13,
/*46*/    :BDFGTS13,
/*47*/    :BDFGTS13CS,
/*48*/    :BDMAIORREM,
/*49*/    :BDBINSS,
/*50*/    :BDALIQINSS,
/*51*/    :BDINSS,
/*52*/    :BDBIRRF,
/*53*/    :BDALIQIRRF,
/*54*/    :BDIRRF,
/*55*/    :BDBINSS13,
/*56*/    :BDALIQINSS13,
/*57*/    :BDINSS13,
/*58*/    :BDBIRRF13,
/*59*/    :BDALIQIRRF13,
/*60*/    :BDIRRF13,
/*61*/    :BDBSALFAM,
/*62*/    :BDSALFAM,
/*63*/    :BDBRAIS,
/*64*/    :BDSALBASE,
/*65*/    :BDDEP,
/*67*/    :BDBINSSFEFOL,
/*68*/    :BDINSSFEFOL,
/*69*/    :BDALIQINSSFEFOL,
/*70*/    :bdcredito,
/*71*/    :bddebito,
          :bdbircalc,
          :bdbinsscalc,
          :bddatapgto
  DO
    begin
       if (wempatu <> BDCODEMP) then
          select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = :BDCODEMP and BDREFEMP <= :prreferencia order by BDREFEMP desc into :BDREFHOREMP;

       select first 1 VER.BDDESCVER, VER.BDDESCREDVER, VER.BDCLAVER, VER.BDORDEMVER, VER.BDAPEVER,
                      RVA.BDTIPOCODVER, CASE WHEN RVA.BDTIPOCODVER = 1 THEN 2 WHEN RVA.BDTIPOCODVER = 2 THEN 1 ELSE COALESCE(RVA.BDTIPOCODVER, 0) END,
                      RVA.BDINSSVER, RVA.BDFGTSVER,
                      RVA.BDIRVER, RVA.BDTIPOREFVER, RVA.BDBASESFVER, RVA.BDPISVER, RVA.BDBASEHEVER,
                      RVA.BDBASEMAIORVER, RVA.BDRAISVER, RVA.BDBASEGPSVER, RVA.BDMENORESVER,
                      RVA.BDPROPVER, RVA.BDBASEVTVER, RVA.BDREEMBGPSVER, RVA.BDHEVER, RVA.BDGRAVAFICHAHNVER,
                      RVA.BDCCPRINCIPALVER, RVA.BDFORMREFAUXVER, RVA.BDFORMREFVER, RVA.BDFORMVALVER, RVA.BDBASEDSRHEVER,
                      RVA.BDBASEDSRRVVER, RVA.BDDEDFORMREFAUXVER, RVA.BDDEDFORMREFVER, RVA.BDDEDFORMVALVER
       from VRH_BASE_TVERBAS VER
       join VRH_BASE_TVERBAS_REF RVA on (RVA.BDCODVER = VER.BDCODVER)
       where VER.BDCODVER = :BDCODVER and RVA.BDREFVER <= :prreferencia
       order by RVA.BDREFVER desc
       into :BDDESCVER, :BDDESCREDVER, :BDCLAVER, :BDORDEMVER, :BDDETALHE, 
            :BDTIPOCODVER, :BDORDEMTIPOCODVER, :BDINSSVER, :BDFGTSVER, :BDIRVER, :BDTIPOREFVER, :BDBASESFVER, :BDPISVER, :BDBASEHEVER,
            :BDBASEMAIORVER, :BDRAISVER, :BDBASEGPSVER, :BDMENORESVER, :BDPROPVER, :BDBASEVTVER, :BDREEMBGPSVER, :BDHEVER, :BDGRAVAFICHAHNVER,
            :BDCCPRINCIPALVER, :BDFORMREFAUXVER, :BDFORMREFVER, :BDFORMVALVER, :BDBASEDSRHEVER, :BDBASEDSRRVVER, :BDDEDFORMREFAUXVER,
            :BDDEDFORMREFVER, :BDDEDFORMVALVER;

  SUSPEND;
    end

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^


/* Restore proc. body: VRHF_SP_CALC_FN_AUT */
ALTER PROCEDURE VRHF_SP_CALC_FN_AUT(PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER,
PRTIPOCOL INTEGER,
PRCODAUT VARCHAR(10000))
 RETURNS(BDGRUPOCLA INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDORDEM INTEGER,
BDCODSERV INTEGER,
BDREFFN INTEGER,
BDBFGTSFN NUMERIC(15,6),
BDFGTSFN NUMERIC(15,6),
BDFGTSCSFN NUMERIC(15,6),
BDBFGTS13FN NUMERIC(15,6),
BDFGTS13FN NUMERIC(15,6),
BDFGTS13CSFN NUMERIC(15,6),
BDMAIORREMFN NUMERIC(15,6),
BDBINSSFN NUMERIC(15,6),
BDALIQINSSFN NUMERIC(15,6),
BDINSSFN NUMERIC(15,6),
BDBIRRFFN NUMERIC(15,6),
BDALIQIRRFFN NUMERIC(15,6),
BDIRRFFN NUMERIC(15,6),
BDBINSS13FN NUMERIC(15,6),
BDALIQINSS13FN NUMERIC(15,6),
BDINSS13FN NUMERIC(15,6),
BDBIRRF13FN NUMERIC(15,6),
BDALIQIRRF13FN NUMERIC(15,6),
BDIRRF13FN NUMERIC(15,6),
BDBSALFAMFN NUMERIC(15,6),
BDSALFAMFN NUMERIC(15,6),
BDBRAISFN NUMERIC(15,6),
BDSALBASEFN NUMERIC(15,6),
BDDEPFN NUMERIC(15,6),
BDBASEPISFN NUMERIC(15,6),
BDBASEPISFEFN NUMERIC(15,6),
BDBASEPIS13FN NUMERIC(15,6),
BDBSALMATEMPFN NUMERIC(15,6),
BDSALMATEMPFN NUMERIC(15,6),
BDBRATAPOFN NUMERIC(15,6),
BDBRATAPOFEFN NUMERIC(15,6),
BDBRATAPO13FN NUMERIC(15,6),
BDBINSSFEFOLFN NUMERIC(15,6),
BDINSSFEFOLFN NUMERIC(15,6),
BDALIQINSSFEFOLFN NUMERIC(15,6),
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCALCTOMADOR VARCHAR(5),
BDCALCAUTONOMO VARCHAR(5),
BDVALOUTENTIDADE NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32000);
BEGIN
/*  PRTIPOCOL
   0 = todos
   1 = funcionarios
   2 = autonomos

*/
  IF (prtipocol IS NULL) THEN
     prtipocol = 0;

  /* Procedure Text */
  wsql = 'select bdgrupocla, bdcodemp, bdcodcol, bdordem, bdreffn, '||
         'bdbfgtsfn, bdfgtsfn, bdfgtscsfn, bdbfgts13fn, bdfgts13fn,'||
         'bdfgts13csfn, bdmaiorremfn, bdbinssfn, bdaliqinssfn, bdinssfn,'||
         'bdbirrffn, bdaliqirrffn, bdirrffn, bdbinss13fn, bdaliqinss13fn,'||
         'bdinss13fn, bdbirrf13fn, bdaliqirrf13fn, bdirrf13fn, bdbsalfamfn,'||
         'bdsalfamfn, bdbraisfn, bdsalbasefn, bddepfn, bdbasepisfn, bdbasepisFEfn, bdbasepis13fn, bdbsalmatempfn,'||
         'bdsalmatempfn, bdbratapofn, bdbratapoFEfn, bdbratapo13fn,'||
         'bdbinssfefolfn, bdinssfefolfn, bdaliqinssfefolfn,'||
         'bdcodcentro, bdcodtpcc, bdcalctomador from vrhf_sp_tfolha_normal(';

  IF (prcodemp IS NULL) THEN
     wsql = wsql||'null,';
  ELSE
     wsql = wsql||''''||prcodemp||''''||',';

  IF (prcodcol IS NULL) THEN
     wsql = wsql||'null,';
  ELSE
     wsql = wsql||''''||prcodcol||''''||',';

  IF (prrefini IS NULL) THEN
     wsql = wsql||'null,';
  ELSE
     wsql = wsql||prrefini||',';

  IF (prreffim IS NULL) THEN
     wsql = wsql||'null,';
  ELSE
     wsql = wsql||prreffim||',';

  IF (pragrupatomador IS NULL) THEN
     wsql = wsql||'null';
  ELSE
     wsql = wsql||pragrupatomador;

  wsql = wsql||')';

  bdcodter = NULL;
  bdcalcautonomo = 'FALSE';
  bdcodserv = NULL;
  bdvaloutentidade = 0;

  IF (prtipocol <> 2) THEN
  FOR EXECUTE STATEMENT wsql
  INTO
    : bdgrupocla,
    : bdcodemp,
    : bdcodcol,
    : bdordem,
    : bdreffn,
    : bdbfgtsfn,
    : bdfgtsfn,
    : bdfgtscsfn,
    : bdbfgts13fn,
    : bdfgts13fn,
    : bdfgts13csfn,
    : bdmaiorremfn,
    : bdbinssfn,
    : bdaliqinssfn,
    : bdinssfn,
    : bdbirrffn,
    : bdaliqirrffn,
    : bdirrffn,
    : bdbinss13fn,
    : bdaliqinss13fn,
    : bdinss13fn,
    : bdbirrf13fn,
    : bdaliqirrf13fn,
    : bdirrf13fn,
    : bdbsalfamfn,
    : bdsalfamfn,
    : bdbraisfn,
    : bdsalbasefn,
    : bddepfn,
    : bdbasepisfn,
    : bdbasepisFEfn,
    : bdbasepis13fn,
    : bdbsalmatempfn,
    : bdsalmatempfn,
    : bdbratapofn,
    : bdbratapoFEfn,
    : bdbratapo13fn,
    : bdbinssfefolfn,
    : bdinssfefolfn,
    : bdaliqinssfefolfn,
    : bdcodcentro,
    : bdcodtpcc,
    : bdcalctomador DO
  BEGIN
    SUSPEND;
  END

  wsql = 'select bdgrupocla,bdcodemp, bdcodter, bdcodserv, cast(null as integer), bdanomes, '||
         'cast(null as numeric(15,6)), cast(null as numeric(15,6)), cast(null as numeric(15,6)), cast(null as numeric(15,6)), cast(null as numeric(15,6)),'||
         'cast(null as numeric(15,6)), cast(null as numeric(15,6)), bdbaseinss, bdfaixainss, bdvalorinss,'||
         'bdbaseir, bdfaixair, bdvalorir, cast(null as numeric(15,6)), cast(null as numeric(15,6)),'||
         'cast(null as numeric(15,6)), cast(null as numeric(15,6)), cast(null as numeric(15,6)), cast(null as numeric(15,6)), cast(null as numeric(15,6)),'||
         'cast(null as numeric(15,6)), cast(null as numeric(15,6)), cast(null as numeric(15,6)), bdvalordep, cast(null as numeric(15,6)), cast(null as numeric(15,6)),'||
         'cast(null as numeric(15,6)), bdbaseratapo, cast(null as numeric(15,6)), cast(null as numeric(15,6)), cast(null as numeric(15,6)), BDVALOUTENTIDADES,'||
         'bdcodcentro, bdcodtpcc, cast(null as varchar(5)) from VRHF_SP_TCALC_AUTONOMO(';

  IF (prcodemp IS NULL) THEN
     wsql = wsql||'null,';
  ELSE
     wsql = wsql||''''||prcodemp||''''||',';


  IF ((prcodaut IS NULL)) THEN
     wsql = wsql||'null,';
  ELSE
     wsql = wsql||''''||prcodaut||''''||',';

  IF (prrefini IS NULL) THEN
     wsql = wsql||'null,';
  ELSE
     wsql = wsql||prrefini||',';

  IF (prreffim IS NULL) THEN
     wsql = wsql||'null,';
  ELSE
     wsql = wsql||prreffim||',';

  IF (pragrupatomador IS NULL) THEN
     wsql = wsql||'null';
  ELSE
     wsql = wsql||pragrupatomador;

  wsql = wsql||')';

  bdcodcol = NULL;
  bdcalcautonomo = 'TRUE';
  bdbratapoFEfn = 0;
  bdbratapo13fn = 0;
  bdbasepisfn = 0;
  bdbasepisfn = 0;
  IF (prtipocol <> 1) THEN
  FOR EXECUTE STATEMENT wsql
  INTO
    : bdgrupocla,
    : bdcodemp,
    : bdcodter,
    : bdcodserv,
    : bdordem,
    : bdreffn,
    : bdbfgtsfn,
    : bdfgtsfn,
    : bdfgtscsfn,
    : bdbfgts13fn,
    : bdfgts13fn,
    : bdfgts13csfn,
    : bdmaiorremfn,
    : bdbinssfn,
    : bdaliqinssfn,
    : bdinssfn,
    : bdbirrffn,
    : bdaliqirrffn,
    : bdirrffn,
    : bdbinss13fn,
    : bdaliqinss13fn,
    : bdinss13fn,
    : bdbirrf13fn,
    : bdaliqirrf13fn,
    : bdirrf13fn,
    : bdbsalfamfn,
    : bdsalfamfn,
    : bdbraisfn,
    : bdsalbasefn,
    : bddepfn,
    : bdbasepisfn,
    : bdbsalmatempfn,
    : bdsalmatempfn,
    : bdbratapofn,
    : bdbinssfefolfn,
    : bdinssfefolfn,
    : bdaliqinssfefolfn,
    : bdvaloutentidade,
    : bdcodcentro,
    : bdcodtpcc,
    : bdcalctomador DO
  BEGIN
    SUSPEND;
  END

END
^

/* Restore proc. body: VRHF_SP_CALC_FN_AUT_PREV */
CREATE OR ALTER PROCEDURE VRHF_SP_CALC_FN_AUT_PREV (
    PRCODEMP VARCHAR(22000),
    PRCODCOL VARCHAR(32700),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRAGRUPATOMADOR INTEGER,
    PRTIPOCOL INTEGER,
    PRCODAUT VARCHAR(10000))
RETURNS (
    BDGRUPOCLA INTEGER,
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODTER INTEGER,
    BDORDEM INTEGER,
    BDCODSERV INTEGER,
    BDREFFN INTEGER,
    BDBFGTSFN NUMERIC(18,6),
    BDFGTSFN NUMERIC(18,6),
    BDFGTSCSFN NUMERIC(18,6),
    BDBFGTS13FN NUMERIC(18,6),
    BDFGTS13FN NUMERIC(18,6),
    BDFGTS13CSFN NUMERIC(18,6),
    BDMAIORREMFN NUMERIC(18,6),
    BDBINSSFN NUMERIC(18,6),
    BDALIQINSSFN NUMERIC(18,6),
    BDINSSFN NUMERIC(18,6),
    BDBIRRFFN NUMERIC(18,6),
    BDALIQIRRFFN NUMERIC(18,6),
    BDIRRFFN NUMERIC(18,6),
    BDBINSS13FN NUMERIC(18,6),
    BDALIQINSS13FN NUMERIC(18,6),
    BDINSS13FN NUMERIC(18,6),
    BDBIRRF13FN NUMERIC(18,6),
    BDALIQIRRF13FN NUMERIC(18,6),
    BDIRRF13FN NUMERIC(18,6),
    BDBSALFAMFN NUMERIC(18,6),
    BDSALFAMFN NUMERIC(18,6),
    BDBRAISFN NUMERIC(18,6),
    BDSALBASEFN NUMERIC(18,6),
    BDDEPFN NUMERIC(18,6),
    BDBASEPISFN NUMERIC(18,6),
    BDBASEPISFEFN NUMERIC(18,6),
    BDBASEPIS13FN NUMERIC(18,6),
    BDBSALMATEMPFN NUMERIC(18,6),
    BDSALMATEMPFN NUMERIC(18,6),
    BDBRATAPOFN NUMERIC(18,6),
    BDBRATAPOFEFN NUMERIC(18,6),
    BDBRATAPO13FN NUMERIC(18,6),
    BDBINSSFEFOLFN NUMERIC(18,6),
    BDINSSFEFOLFN NUMERIC(18,6),
    BDALIQINSSFEFOLFN NUMERIC(18,6),
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDCALCTOMADOR VARCHAR(5),
    BDCALCAUTONOMO VARCHAR(5),
    BDVALOUTENTIDADE NUMERIC(18,6))
AS
DECLARE VARIABLE WSQL VARCHAR(32000);
BEGIN
/*  PRTIPOCOL
   0 = todos
   1 = funcionarios
   2 = autonomos

*/
  IF (prtipocol IS NULL) THEN
     prtipocol = 0;

  /* Procedure Text */
  wsql = '';
  wsql = wsql||
  'select colcon.bdgrupocla, colcon.BDCODEMP, colcon.BDCODCOL, colcon.BDBFGTSFN, '||
  'colcon.BDFGTSFN, colcon.BDFGTSCSFN, colcon.BDBFGTS13FN, colcon.BDFGTS13FN, colcon.BDFGTS13CSFN, colcon.BDMAIORREMFN, '||
  'colcon.BDBINSSFN, colcon.BDALIQINSSFN, colcon.BDINSSFN, colcon.BDBIRRFFN, colcon.BDALIQIRRFFN, colcon.BDIRRFFN, '||
  'colcon.BDBINSS13FN, colcon.BDALIQINSS13FN, colcon.BDINSS13FN, colcon.BDBIRRF13FN, colcon.BDALIQIRRF13FN, '||
  'colcon.BDIRRF13FN, colcon.BDBSALFAMFN, colcon.BDSALFAMFN, colcon.BDBRAISFN, colcon.BDSALBASEFN, colcon.BDDEPFN, '||
  'colcon.BDBASEPISFN, 0.0000, 0.0000, colcon.BDBSALMATEMPFN, colcon.BDSALMATEMPFN, colcon.BDBRATAPOFN, 0.0000, '||
  '0.0000, colcon.BDBINSSFEFOLFN, colcon.BDINSSFEFOLFN, colcon.BDALIQINSSFEFOLFN, colcon.bdreffn, '||
  'colcon.bdcodcentro, colcon.bdcodtpcc, colcon.bdcalctomador, colcon.bdordem '||
  'from VRHF_SP_TFOLHA_NORMAL_PREV_RESC(';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
    wsql = wsql||''''||prcodemp||''',';
  ELSE
    wsql = wsql||'null,';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||''''||prcodcol||''',';
  ELSE
    wsql = wsql||'null,';

  wsql = wsql||prrefini||','||prreffim||','||pragrupatomador;

  wsql = wsql||') COLCON ';


  bdcalcautonomo = 'FALSE';
  bdcodserv = NULL;
  bdvaloutentidade = 0.000000;
  bdcodter = NULL;

--  IF (prtipocol <> 2) THEN
  FOR EXECUTE STATEMENT wsql
  INTO
    : bdgrupocla,
    : bdcodemp,
    : bdcodcol,
    : bdbfgtsfn,
    : bdfgtsfn,
    : bdfgtscsfn,
    : bdbfgts13fn,
    : bdfgts13fn,
    : bdfgts13csfn,
    : bdmaiorremfn,
    : bdbinssfn,
    : bdaliqinssfn,
    : bdinssfn,
    : bdbirrffn,
    : bdaliqirrffn,
    : bdirrffn,
    : bdbinss13fn,
    : bdaliqinss13fn,
    : bdinss13fn,
    : bdbirrf13fn,
    : bdaliqirrf13fn,
    : bdirrf13fn,
    : bdbsalfamfn,
    : bdsalfamfn,
    : bdbraisfn,
    : bdsalbasefn,
    : bddepfn,
    : bdbasepisfn,
    : bdbasepisFEfn,
    : bdbasepis13fn,
    : bdbsalmatempfn,
    : bdsalmatempfn,
    : bdbratapofn,
    : bdbratapoFEfn,
    : bdbratapo13fn,
    : bdbinssfefolfn,
    : bdinssfefolfn,
    : bdaliqinssfefolfn,
    : bdreffn,
    : bdcodcentro,
    : bdcodtpcc,
    : bdcalctomador,
    : bdordem
    DO
  BEGIN
    SUSPEND;
  END

END
^

/* Restore proc. body: VRHF_SP_CALC_FOLHANORMAL */
create or alter procedure VRHF_SP_CALC_FOLHANORMAL (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(2788) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFV numeric(15,6),
    BDREFAUXV numeric(15,6),
    BDVALV numeric(15,6),
    BDPROVENTO numeric(15,6),
    BDDESCONTO numeric(15,6),
    BDIGNREFV varchar(5),
    BDIGNVALV varchar(5),
    BDTIPOCODVER integer,
    BDORDEMTIPOCODVER integer,
    BDINSSVER integer,
    BDFGTSVER integer,
    BDIRVER integer,
    BDTIPOREFVER integer,
    BDBASESFVER integer,
    BDPISVER varchar(5),
    BDBASEHEVER varchar(5),
    BDBASEMAIORVER varchar(5),
    BDRAISVER varchar(5),
    BDBASEGPSVER varchar(5),
    BDMENORESVER varchar(5),
    BDPROPVER varchar(5),
    BDBASEVTVER varchar(5),
    BDREEMBGPSVER varchar(5),
    BDHEVER numeric(15,6),
    BDGRAVAFICHAHNVER varchar(5),
    BDCCPRINCIPALVER varchar(5),
    BDFORMREFAUXVER varchar(5000),
    BDFORMREFVER varchar(5000),
    BDFORMVALVER varchar(5000),
    BDBASEDSRHEVER varchar(5),
    BDBASEDSRRVVER varchar(5),
    BDDEDFORMREFAUXVER varchar(5),
    BDDEDFORMREFVER varchar(5),
    BDDEDFORMVALVER varchar(5),
    BDDESCVER varchar(40),
    BDDESCREDVER varchar(20),
    BDCLAVER varchar(20),
    BDORDEMVER integer,
    BDREFHOREMP varchar(5),
    BDDATABAIXA date,
    BDBFGTS numeric(15,6),
    BDFGTS numeric(15,6),
    BDFGTSCS numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDFGTS13 numeric(15,6),
    BDFGTS13CS numeric(15,6),
    BDMAIORREM numeric(15,6),
    BDBINSS numeric(15,6),
    BDALIQINSS numeric(15,6),
    BDINSS numeric(15,6),
    BDBIRRF numeric(15,6),
    BDALIQIRRF numeric(15,6),
    BDIRRF numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDALIQINSS13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDBIRRF13 numeric(15,6),
    BDALIQIRRF13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDBSALFAM numeric(15,6),
    BDSALFAM numeric(15,6),
    BDBRAIS numeric(15,6),
    BDSALBASE numeric(15,6),
    BDDEP numeric(15,6),
    BDDETALHE varchar(255),
    BDBINSSFEFOL numeric(15,6),
    BDINSSFEFOL numeric(15,6),
    BDALIQINSSFEFOL numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDBFGTSFEFOL numeric(15,6),
    BDFGTSFEFOL numeric(15,6),
    BDDATAPGTO date,
    BDBINSSAPFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDBASEPISFN numeric(18,6),
    BDBASEPISFEFN numeric(18,6),
    BDBASEPIS13FN numeric(18,6),
    BDCODCONTTI integer)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WPARAUX varchar(32700);
declare variable WORDEM varchar(300);
declare variable WEMPATU integer;
declare variable WREFATU integer;
BEGIN

  IF (prreffim IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);
  ELSE IF (prrefini IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prrefini, NULL, NULL);

  wsql = 'select ';
  wsql = wsql||'COLCON.BDCODEMP, '||
               'COLCON.BDCODCOL, '||
               'COLCON.BDCODVER, '||
               'COLCON.BDREFFN, '||
               'COLCON.BDREFVFN, '||
               'COLCON.BDREFAUXVFN, '||
               'COLCON.BDVALVFN, '||
                'case when (RVA.BDTIPOCODVER in (0, 2)) then COLCON.BDVALVFN '||
                     'else 0 end BDPROVENTO, '||
                'case when (RVA.BDTIPOCODVER in (0, 2)) then 0 '||
                     'else COLCON.BDVALVFN end BDDESCONTO, '||
               'COLCON.BDIGNREFVFN, '||
               'COLCON.BDIGNVALVFN, '||
               'RVA.BDTIPOCODVER, '||
               'RVA.BDORDEMTIPOCODVER, '||
               'RVA.BDINSSVER, '||
               'RVA.BDFGTSVER, '||
               'RVA.BDIRVER, '||
               'RVA.BDTIPOREFVER, '||
               'RVA.BDBASESFVER, '||
               'RVA.BDPISVER, '||
               'RVA.BDBASEHEVER, '||
               'RVA.BDBASEMAIORVER, '||
               'RVA.BDRAISVER, '||
               'RVA.BDBASEGPSVER, '||
               'RVA.BDMENORESVER, '||
               'RVA.BDPROPVER, '||
               'RVA.BDBASEVTVER, '||
               'RVA.BDREEMBGPSVER, '||
               'RVA.BDHEVER, '||
               'RVA.BDGRAVAFICHAHNVER, '||
               'RVA.BDCCPRINCIPALVER, '||
               'RVA.BDFORMREFAUXVER, '||
               'RVA.BDFORMREFVER, '||
               'RVA.BDFORMVALVER, '||
               'RVA.BDBASEDSRHEVER, '||
               'RVA.BDBASEDSRRVVER, '||
               'RVA.BDDEDFORMREFAUXVER, '||
               'RVA.BDDEDFORMREFVER, '||
               'RVA.BDDEDFORMVALVER, '||
               'RVA.BDDESCVER, '||
               'RVA.BDDESCREDVER, '||
               'RVA.BDCLAVER, '||
               'RVA.BDORDEMVER, '||
               'FOLN.BDDATABAIXAFN, '||
               'FOLN.BDBFGTSFN, '||
               'FOLN.BDFGTSFN, '||
               'FOLN.BDFGTSCSFN, '||
               'FOLN.BDBFGTS13FN, '||
               'FOLN.BDFGTS13FN, '||
               'FOLN.BDFGTS13CSFN, '||
               'FOLN.BDMAIORREMFN, '||
               'FOLN.BDBINSSFN, '||
               'FOLN.BDALIQINSSFN, '||
               'FOLN.BDINSSFN, '||
               'FOLN.BDBIRRFFN, '||
               'FOLN.BDALIQIRRFFN, '||
               'FOLN.BDIRRFFN, '||
               'FOLN.BDBINSS13FN, '||
               'FOLN.BDALIQINSS13FN, '||
               'FOLN.BDINSS13FN, '||
               'FOLN.BDBIRRF13FN, '||
               'FOLN.BDALIQIRRF13FN, '||
               'FOLN.BDIRRF13FN, '||
               'FOLN.BDBSALFAMFN, '||
               'FOLN.BDSALFAMFN, '||
               'FOLN.BDBRAISFN, '||
               'FOLN.BDSALBASEFN, '||
               'FOLN.BDDEPFN, '||
               '''Competência: '''||'||substring(COLCON.BDREFFN from 5 for 2)||'||'''/'''||'||substring(COLCON.BDREFFN from 1 for 4) BDDETALHE, '||
               'FOLN.BDBINSSFEFOLFN, '||
               'FOLN.BDINSSFEFOLFN, '||
               'FOLN.BDALIQINSSFEFOLFN, '||
               'FOLN.BDCREDITOFN, '||
               'FOLN.BDDEBITOFN, '||
               'FOLN.BDBFGTSFEFN, '||
               'FOLN.BDFGTSFEFN, '||
               'COLCON.BDCODCENTRO, '||
               'COLCON.BDCODTPCC, '||
               'FOLN.BDDATAPGTO, '||
               'FOLN.BDBINSSAPFN, '||
               'FOLN.BDINSSAPFN, '||
               'FOLN.BDBINSS13APFN, '||
               'FOLN.BDINSS13APFN, '||
               'FOLN.BDBASEPISFN, '||
               'FOLN.BDBASEPISFEFN, '||
               'FOLN.BDBASEPIS13FN, '||
               'COLCON.BDCODCONTTI ';

  wparaux = '';
  IF (prcodemp IS NOT NULL) THEN
     wparaux = wparaux||''''||PRCODEMP||''''||',';
  ELSE
     wparaux = wparaux||'null'||',';

  IF (prcodcol IS NOT NULL) THEN
     wparaux = wparaux||''''||prcodcol||''''||',';
  ELSE
     wparaux = wparaux||'null'||',';

  IF (prrefini IS NOT NULL) THEN
     wparaux = wparaux||prrefini||',';
  ELSE
     wparaux = wparaux||'null'||',';

  IF (prreffim IS NOT NULL) THEN
     wparaux = wparaux||prreffim||',';
  ELSE
     wparaux = wparaux||'null'||',';

  -- wparaux = wparaux||'null'||',';

  wparaux = wparaux||pragrupatomador ;

  IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
     wparaux = wparaux||', '''||prcodtpcc||'''';
  ELSE
     wparaux = wparaux||', null';

  IF (prpuxafiliais IS NULL) THEN
     prpuxafiliais = 0;

  wparaux = wparaux||' ,'||prpuxafiliais;

  IF (prfiliais IS NOT NULL AND prfiliais <> '') THEN
     wparaux = wparaux||', '''||prfiliais||'''';
  ELSE
     wparaux = wparaux||', null';

  wordem = '';

  IF (pragrupatomador = 0) THEN
     wordem = ' ((FOLN.BDORDEM = COLCON.BDORDEM) or (foln.bdordem is null and colcon.bdordem is null))';
  ELSE
  IF (pragrupatomador = 2) THEN
     wordem = ' ((FOLN.BDCODTPCC = COLCON.BDCODTPCC) or ((FOLN.BDCODTPCC is null) and (COLCON.BDCODTPCC is null)))';
  ELSE IF ((pragrupatomador = 3) OR (pragrupatomador = 4))  THEN
     wordem = ' ((FOLN.BDCODTPCC = COLCON.BDCODTPCC) or ((FOLN.BDCODTPCC is null) and (COLCON.BDCODTPCC is null)))';


  wsql = wsql||'from VRHF_SP_TVERBAFN('||wparaux||') COLCON '||
               'join SP_VRH_VERBAS('||:prrefini||') RVA on (RVA.BDCODVER = COLCON.BDCODVER) '||
               ' join VRHF_SP_TFOLHA_NORMAL('||wparaux||') FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFFN = COLCON.BDREFFN and FOLN.BDCODCONTTI = COLCON.BDCODCONTTI) ';

  wwhere = '';
  IF (wordem <> '') THEN
    wwhere = wwhere||wordem;


  /*wsql = wsql||'from VRHF_SP_TVERBAFN('||wparaux||') COLCON '||
               ' join VW_VERBAS_REF_ATUAL RVA '||
                 'on (RVA.BDCODVER = COLCON.BDCODVER) '||
               ' join VRH_BASE_TVERBAS VER '||
                 'on (VER.BDCODVER = COLCON.BDCODVER) '||
               ' join VW_VRHF_EMPRESAS_REF_ATUAL EMPREF '||
                 'on (EMPREF.BDCODEMP = COLCON.BDCODEMP) '||
               ' join VRHF_SP_TFOLHA_NORMAL('||wparaux||') FOLN '||
                 'on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFFN = COLCON.BDREFFN ' ||wordem|| ') ';*/

  IF ((prcodemp IS NOT NULL) AND (prpuxafiliais = 0) and (position('tmp_empresas_select', prcodemp) <= 0)) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      wwhere = wwhere||PRCODEMP;
    END

  IF (prcodcol IS NOT NULL) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      wwhere = wwhere||PRCODCOL;
    END

--  if (prcodtpcc is not null) then
--     wwhere = wwhere||' and '||prcodtpcc;

  -- verficar se precisa aqui tambem ja que tem la em cima na  RHF_SP_TVERBAFN

/*
  if (prrefini is not null) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||'COLCON.BDREFFN = '||prrefini;
     end
*/


  IF ((prrefini IS NOT NULL) AND (prreffim IS NOT NULL)) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      wwhere = wwhere||'COLCON.BDREFFN >= '||prrefini||' and '||'COLCON.BDREFFN <= '||prreffim;
    END
  ELSE
     BEGIN
       IF (prrefini IS NOT NULL) THEN
         BEGIN
           IF (wwhere <> '') THEN
             wwhere = wwhere||' and ';
           wwhere = wwhere||'COLCON.BDREFFN = '||prrefini;
         END
       ELSE
          BEGIN
            IF (prreffim IS NOT NULL) THEN
              BEGIN
                IF (wwhere <> '') THEN
                  wwhere = wwhere||' and ';
                wwhere = wwhere||'COLCON.BDREFFN = '||prreffim;
              END
          END
     END

  IF (wwhere <> '') THEN
    wwhere  = ' where '||wwhere;

  wsql = wsql||wwhere;

  wsql = wsql||' order by RVA.BDTIPOCODVER, COLCON.BDCODVER ';

  wempatu = 0;
  wrefatu = 0;
  BDREFHOREMP = 'FALSE';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFV,
    :BDREFAUXV,
    :BDVALV,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDTIPOCODVER,
    :BDORDEMTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDMENORESVER,
    :BDPROPVER,
    :BDBASEVTVER,
    :BDREEMBGPSVER,
    :BDHEVER,
    :BDGRAVAFICHAHNVER,
    :BDCCPRINCIPALVER,
    :BDFORMREFAUXVER,
    :BDFORMREFVER,
    :BDFORMVALVER,
    :BDBASEDSRHEVER,
    :BDBASEDSRRVVER,
    :BDDEDFORMREFAUXVER,
    :BDDEDFORMREFVER,
    :BDDEDFORMVALVER,
    :BDDESCVER,
    :BDDESCREDVER,
    :BDCLAVER,
    :BDORDEMVER,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDDETALHE,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :bdcredito,
    :bddebito,
    :bdbfgtsfefol,
    :bdfgtsfefol,
    :bdcodcentro,
    :bdcodtpcc,
    :bddatapgto,
    :bdbinssapfn,
    :bdinssapfn,
    :bdbinss13apfn,
    :bdinss13apfn,
    :bdbasepisfn,
    :bdbasepisfefn,
    :bdbasepis13fn, 
    :bdcodcontti
  DO
    begin
      if (coalesce(BDINSS, 0) <= 0 and coalesce(BDINSSFEFOL, 0) >= 0 and coalesce(BDINSSFEFOL, 0) + coalesce(BDINSS, 0) < 0) then
         BDBINSS = 0;

      if ((wempatu <> BDCODEMP) or (wrefatu <> BDREFFN)) then
         begin
           select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = :BDCODEMP and BDREFEMP <= :BDREFFN order by BDREFEMP DESC into :BDREFHOREMP;
           wempatu = BDCODEMP;
           wrefatu = BDREFFN;
         end

  SUSPEND;
    end

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

/* Restore proc. body: VRHF_SP_CALC_GPS */
ALTER PROCEDURE VRHF_SP_CALC_GPS(PRCODIMP INTEGER,
PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRAPENASGPS INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER)
 RETURNS(BDTIPOREG INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDCODCENTRO INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDVALFUNEMP NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDVALPROEMP NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDVALAUTEMP NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDVALORFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALORRAT NUMERIC(15,6),
BDVALORBRUTO NUMERIC(15,6),
BDVALORLIQUIDO NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6),
BDCHAVE INTEGER,
BDVALCOMPENSADO NUMERIC(15,6),
BDVALACOMPENSAR NUMERIC(15,6),
BDVALORACUMULADO NUMERIC(15,6),
BDVALORACUMULADOUSADO NUMERIC(15,6),
BDVALORACUMUTERCEIRO NUMERIC(15,6),
BDVALORACUTERCEIROSUSADO NUMERIC(15,6),
BDCODEMPANT INTEGER,
BDCODIMPANT INTEGER,
BDCHAVEDARFANT INTEGER,
BDCODPERIODOANT INTEGER,
BDORDEMANT INTEGER,
BDREFERENCIAANT INTEGER,
BDQUOTAANT INTEGER,
BDDESCACUMDET VARCHAR(3000),
BDDESCACU VARCHAR(3000),
BDVALORCAMPO6 NUMERIC(15,6),
BDVALORNOTAS NUMERIC(15,6),
BDTOTVALORACUMULADO NUMERIC(15,6),
BDTOTVALORACUMULADOTERC NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDTOTCOMPENSACAO NUMERIC(15,6),
BDDESCNOTAS NUMERIC(15,6),
BDTOTDESCCOMP NUMERIC(15,6),
BDDESCSALFAM NUMERIC(15,6),
BDDESCDEDGPS NUMERIC(15,6),
BDVALOUTENTIDADES NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDVALFUNEMPFN NUMERIC(15,6),
BDVALFUNEMPFC NUMERIC(15,6),
BDVALFUNEMPFERFN NUMERIC(15,6),
BDVALFUNEMPFERFC NUMERIC(15,6),
BDVALFUNEMP13FN NUMERIC(15,6),
BDVALFUNEMP13FC NUMERIC(15,6),
BDVALFUNEMP13 NUMERIC(15,6),
BDVALFUNEMPC13 NUMERIC(15,6),
BDVALPROEMPFN NUMERIC(15,6),
BDVALPROEMPFC NUMERIC(15,6),
BDVALPROEMPFERFN NUMERIC(15,6),
BDVALPROEMPFERFC NUMERIC(15,6),
BDVALPROEMP13FN NUMERIC(15,6),
BDVALPROEMP13FC NUMERIC(15,6),
BDVALPROEMP13 NUMERIC(15,6),
BDVALPROEMPC13 NUMERIC(15,6),
BDVALAUTEMPFN NUMERIC(15,6),
BDVALAUTEMPFC NUMERIC(15,6),
BDVALAUTEMPFERFN NUMERIC(15,6),
BDVALAUTEMPFERFC NUMERIC(15,6),
BDVALAUTEMP13FN NUMERIC(15,6),
BDVALAUTEMP13FC NUMERIC(15,6),
BDVALAUTEMP13 NUMERIC(15,6),
BDVALAUTEMPC13 NUMERIC(15,6),
BDVALFPASEMPFN NUMERIC(15,6),
BDVALFPASEMPFC NUMERIC(15,6),
BDVALFPASEMPFERFN NUMERIC(15,6),
BDVALFPASEMPFERFC NUMERIC(15,6),
BDVALFPASEMP13FN NUMERIC(15,6),
BDVALFPASEMP13FC NUMERIC(15,6),
BDVALFPASEMP13 NUMERIC(15,6),
BDVALFPASEMPC13 NUMERIC(15,6),
BDVALRATEMPFN NUMERIC(15,6),
BDVALRATEMPFC NUMERIC(15,6),
BDVALRATEMPFERFN NUMERIC(15,6),
BDVALRATEMPFERFC NUMERIC(15,6),
BDVALRATEMP13FN NUMERIC(15,6),
BDVALRATEMP13FC NUMERIC(15,6),
BDVALRATEMP13 NUMERIC(15,6),
BDVALRATEMPC13 NUMERIC(15,6),
BDVALRATAPOEMPFN NUMERIC(15,6),
BDVALRATAPOEMPFC NUMERIC(15,6),
BDVALRATAPOEMPFERFN NUMERIC(15,6),
BDVALRATAPOEMPFERFC NUMERIC(15,6),
BDVALRATAPOEMP13FN NUMERIC(15,6),
BDVALRATAPOEMP13FC NUMERIC(15,6),
BDVALRATAPOEMP13 NUMERIC(15,6),
BDVALRATAPOEMPC13 NUMERIC(15,6),
BDCHAVEDARF INTEGER)
 AS
DECLARE VARIABLE WSQLEMP VARCHAR(32000);
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WTIPOEMISSAO INTEGER;
DECLARE VARIABLE WTIPOEMISSAOANT INTEGER;
DECLARE VARIABLE WWHEREEMP VARCHAR(10000);
DECLARE VARIABLE WSQLCALC VARCHAR(32000);
DECLARE VARIABLE WPARSQLCALC VARCHAR(32000);
DECLARE VARIABLE WMATRIZ INTEGER;
BEGIN
  /* prtipogps
     0 = normal
     1 = folha complementar
     2 = 13 sal
     3 = comp. 13 sal
     4 = prévia de rescisão
  */
  /* prtipoemissao
     0 = por cc
     1 = agrupado
  */
  /* prapenasgps
     0 = apenas gps
     1 = historicos compensacoes/nf/gps
  */
  /* PRPUXAFILIAIS
     0 = Nao
     1 = Sim
  */
  /*
    BDTIPOREG
    0 = GPS
    1 = nf
    2 = gps comp
    3 = compensacao
    4 = historico comp
    5 = historico nf
    6 = historico gps
    7 = registro acumulados
    8 = contabilizacao
  */
  /* Procedure Text */


--  pranomes = 201005;
  EXECUTE PROCEDURE sp_seta_competencia(pranomes,NULL,NULL);

--  wsqlemp = 'select colcon.bdcodemp,coalesce(colcon.BDTIPOEMIGUIAS,1) xtipoguia,temp.bdcodmatriz from VW_VRHF_EMPRESAS_REF_ATUAL colcon ';
--  wsqlemp = wsqlemp||' join tempresas temp on (colcon.bdcodemp = temp.bdcodemp)';
  wsqlemp = 'select colcon.bdcodemp,coalesce(colcon.BDTIPOEMIGUIAS,1) xtipoguia,temp.bdcodmatriz from tempresas temp ';
  wsqlemp = wsqlemp||' left outer join VW_VRHF_BASE_TEMPPAR colcon on (colcon.bdcodemp = temp.bdcodemp)';
  IF (prcodemp IS NOT NULL) THEN
     wsqlemp = wsqlemp||' where '||prcodemp;

  wsqlemp = wsqlemp||' order by xtipoguia, colcon.bdcodemp';

  wwhereemp = '';
  wtipoemissaoant = -1;
  wmatriz = NULL;

  IF (prpuxafiliais IS NULL) THEN
     prpuxafiliais = 0;

  FOR EXECUTE STATEMENT wsqlemp
  INTO
    : wempatu,
    : wtipoemissao,
    : wmatriz
  DO
    BEGIN
      IF ((prpuxafiliais <> 1) OR (wmatriz IS NULL)) THEN
         BEGIN
              IF ((wtipoemissao IS NULL) OR (wtipoemissao < 0) ) THEN
                 wtipoemissao = 0;
              IF ((wtipoemissao = wtipoemissaoant) OR (wtipoemissaoant = -1)) THEN
                 BEGIN
                   wtipoemissaoant = wtipoemissao;
                   IF (CHAR_LENGTH(wwhereemp)>0) THEN
                      wwhereemp = wwhereemp||',';
                   wwhereemp = wwhereemp||CAST(wempatu AS VARCHAR(10));
                 END
              ELSE
                 BEGIN
                   wsqlcalc = 'select '||
                        'bdtiporeg, '||
                        'bdcodemp , '||
                        'bdcodcol,'||
                        'bdcodter,'||
                        'bdreffn , '||
                        'bdrefpag , '||
                        'bdcodcentro, '||
                        'bdcodtpcc , '||
                        'bdtotseg , '||
                        'bdtotbase , '||
                        'bdsegfun , '||
                        'bdbasefun , '||
                        'bdpercfun , '||
                        'bdvalfunemp , '||
                        'bdsegpro , '||
                        'bdbasepro , '||
                        'bdpercpro , '||
                        'bdvalproemp , '||
                        'bdsegaut , '||
                        'bdbaseaut , '||
                        'bdpercaut , '||
                        'bdvalautemp , '||
                        'bdsalfam , '||
                        'bdsalmaternidade , '||
                        'bdbaseratapo , '||
                        'bdvalorratapo , '||
                        'bdbasefpas , '||
                        'bdpercfpas , '||
                        'bdvalorfpas , '||
                        'bdpercrat , '||
                        'bdvalorrat , '||
                        'bdvalorbruto , '||
                        'bdvalorliquido , '||
                        'bdnfcoop , '||
                        'bdchave , '||
                        'bdvalcompensado , '||
                        'bdvalacompensar , '||
                        'bdvaloracumulado , '||
                        'bdvaloracumuladousado , '||
                        'bdvaloracuterceiros , '||
                        'bdvaloracuterceirosusado , '||
                        'bdcodempant , '||
                        'BDCHAVEDARFANT , '||
                        'bdcodimpant , '||
                        'bdcodperiodoant , '||
                        'bdordemant , '||
                        'bdreferenciaant , '||
                        'bdquotaant , '||
                        'bddescacumdet , '||
                        'bddescacum , '||
                        'bdvalorcampo6 , '||
                        'bdvalnotas , '||
                        'bddescnotas , '||
                        'bdtotdesccomp , '||
                        'bdtotvaloracumulado , '||
                        'bdtotvaloracumuladoterc , '||
                        'bdinicomp , '||
                        'bdfimcomp , '||
                        'bdtotcompensacao , '||
                        'bddescsalfam , '||
                        'bddescdedgps , '||
                        'bdvaloutentidade, '||
                        'bdsimplesgps, '||
                        'bdcodenqfed, '||
                        'bddescenqfed, '||
                        'BDVALFUNEMPFN, '||
                        'BDVALFUNEMPFC, '||
                        'BDVALFUNEMPFERFN, '||
                        'BDVALFUNEMPFERFC, '||
                        'BDVALFUNEMP13FN, '||
                        'BDVALFUNEMP13FC, '||
                        'BDVALFUNEMP13, '||
                        'BDVALFUNEMPC13, '||
                        'BDVALPROEMPFN, '||
                        'BDVALPROEMPFC, '||
                        'BDVALPROEMPFERFN, '||
                        'BDVALPROEMPFERFC, '||
                        'BDVALPROEMP13FN, '||
                        'BDVALPROEMP13FC, '||
                        'BDVALPROEMP13, '||
                        'BDVALPROEMPC13, '||
                        'BDVALAUTEMPFN, '||
                        'BDVALAUTEMPFC, '||
                        'BDVALAUTEMPFERFN, '||
                        'BDVALAUTEMPFERFC, '||
                        'BDVALAUTEMP13FN, '||
                        'BDVALAUTEMP13FC, '||
                        'BDVALAUTEMP13, '||
                        'BDVALAUTEMPC13, '||
                        'BDVALFPASEMPFN, '||
                        'BDVALFPASEMPFC, '||
                        'BDVALFPASEMPFERFN, '||
                        'BDVALFPASEMPFERFC, '||
                        'BDVALFPASEMP13FN, '||
                        'BDVALFPASEMP13FC, '||
                        'BDVALFPASEMP13, '||
                        'BDVALFPASEMPC13, '||
                        'BDVALRATEMPFN, '||
                        'BDVALRATEMPFC, '||
                        'BDVALRATEMPFERFN, '||
                        'BDVALRATEMPFERFC, '||
                        'BDVALRATEMP13FN, '||
                        'BDVALRATEMP13FC, '||
                        'BDVALRATEMP13, '||
                        'BDVALRATEMPC13, '||
                        'BDVALRATAPOEMPFN, '||
                        'BDVALRATAPOEMPFC, '||
                        'BDVALRATAPOEMPFERFN, '||
                        'BDVALRATAPOEMPFERFC, '||
                        'BDVALRATAPOEMP13FN, '||
                        'BDVALRATAPOEMP13FC, '||
                        'BDVALRATAPOEMP13, '||
                        'BDVALRATAPOEMPC13, '||
                        'BDCHAVEDARF '||
                        'from vrhf_sp_gps(';
        
                   IF (prcodimp IS NULL) THEN
                      wparsqlcalc = 'null,';
                   ELSE
                      wparsqlcalc = prcodimp||',';
        
                   --prcodemp varchar(32000),
                   IF (prpuxafiliais = 1) THEN
                      WPARSQLCALC = wparsqlcalc||''''||'(colcon.bdcodemp in ('||wwhereemp||') or temp.bdcodmatriz in ('||wwhereemp||'))'||'''';
                   ELSE
                      WPARSQLCALC = wparsqlcalc||''''||'colcon.bdcodemp in ('||wwhereemp||')'||'''';
        
                   --prcodcol varchar(32000),
                   wparsqlcalc = wparsqlcalc||',';
                   IF (prcodcol IS NULL) THEN
                      wparsqlcalc = wparsqlcalc||'null';
                   ELSE
                       wparsqlcalc = wparsqlcalc||''''||prcodcol||'''';
        
                   --prcodaut varchar(32000),
                   wparsqlcalc = wparsqlcalc||',';
                   IF (prcodaut IS NULL) THEN
                      wparsqlcalc = wparsqlcalc||'null';
                   ELSE
                       wparsqlcalc = wparsqlcalc||''''||prcodaut||'''';
        
                   wparsqlcalc = wparsqlcalc||',';

                   --prtipocol integer,
                   IF (prtipocol IS NULL) THEN
                      wparsqlcalc = wparsqlcalc||'null';
                   ELSE
                      wparsqlcalc = wparsqlcalc||prtipocol;

                   wparsqlcalc = wparsqlcalc||',';

                   --pranomes integer,
                   IF (pranomes IS NULL) THEN
                      wparsqlcalc = wparsqlcalc||'null';
                   ELSE
                      wparsqlcalc = wparsqlcalc||pranomes;
        
                   wparsqlcalc = wparsqlcalc||',';
        
                   --pranomespag integer,
                   IF (pranomespag IS NULL) THEN
                      wparsqlcalc = wparsqlcalc||'null';
                   ELSE
                      wparsqlcalc = wparsqlcalc||pranomespag;
        
                   wparsqlcalc = wparsqlcalc||',';
        
                   --prtipoemissao integer,
                   /* na tabela
                      0 = centro custo
                      1 = agrupada
                   */
                   wparsqlcalc = wparsqlcalc||CAST(wtipoemissaoant AS VARCHAR(10));
                   wparsqlcalc = wparsqlcalc||',';
        
                   --prapenasgps integer,
                   IF (prapenasgps IS NULL) THEN
                      wparsqlcalc = wparsqlcalc||'null';
                   ELSE
                      wparsqlcalc = wparsqlcalc||prapenasgps;
                   wparsqlcalc = wparsqlcalc||',';
        
                   --prtipogps integer)
                   IF (prtipogps IS NULL) THEN
                      wparsqlcalc = wparsqlcalc||'null';
                   ELSE
                      wparsqlcalc = wparsqlcalc||prtipogps;
                   wparsqlcalc = wparsqlcalc||',';
        
                   -- puxa filiais
                   IF (prpuxafiliais IS NULL) THEN
                      wparsqlcalc = wparsqlcalc||'null';
                   ELSE
                      wparsqlcalc = wparsqlcalc||prpuxafiliais;
        
        
                   wsqlcalc = wsqlcalc||wparsqlcalc||')';
        
                   FOR EXECUTE STATEMENT wsqlcalc
                   INTO
                     :bdtiporeg,
                     :bdcodemp,
                     :bdcodcol, 
                     :bdcodter,
                     :bdreffn,
                     :bdrefpag,
                     :bdcodcentro,
                     :bdcodtpcc,
                     :bdtotseg,
                     :bdtotbase,
                     :bdsegfun,
                     :bdbasefun,
                     :bdpercfun,
                     :bdvalfunemp,
                     :bdsegpro,
                     :bdbasepro,
                     :bdpercpro,
                     :bdvalproemp,
                     :bdsegaut,
                     :bdbaseaut,
                     :bdpercaut,
                     :bdvalautemp,
                     :bdsalfam,
                     :bdsalmaternidade,
                     :bdbaseratapo,
                     :bdvalorratapo,
                     :bdbasefpas,
                     :bdpercfpas,
                     :bdvalorfpas,
                     :bdpercrat,
                     :bdvalorrat,
                     :bdvalorbruto,
                     :bdvalorliquido,
                     :bdnfcoop,
                     :bdchave,
                     :bdvalcompensado,
                     :bdvalacompensar,
                     :bdvaloracumulado,
                     :bdvaloracumuladousado ,
                     :bdvaloracumuterceiro,
                     :bdvaloracuterceirosusado ,
                     :bdcodempant ,
                     :BDCHAVEDARFANT,
                     :bdcodimpant ,
                     :bdcodperiodoant,
                     :bdordemant ,
                     :bdreferenciaant ,
                     :bdquotaant,
                     :bddescacumdet,
                     :bddescacu,
                     :bdvalorcampo6,
                     :BDVALORNOTAS,
                     :bddescnotas,
                     :bdtotdesccomp,
                     :bdtotvaloracumulado,
                     :bdtotvaloracumuladoTerc,
                     :bdinicomp,
                     :bdfimcomp,
                     :bdtotcompensacao,
                     :bddescsalfam,
                     :bddescdedgps,
                     :BDVALOUTENTIDADES,
                     :bdsimplesgps,
                     :bdcodenqfed,
                     :bddescenqfed,
                     :BDVALFUNEMPFN,
                     :BDVALFUNEMPFC,
                     :BDVALFUNEMPFERFN,
                     :BDVALFUNEMPFERFC,
                     :BDVALFUNEMP13FN,
                     :BDVALFUNEMP13FC,
                     :BDVALFUNEMP13,
                     :BDVALFUNEMPC13,
                     :BDVALPROEMPFN,
                     :BDVALPROEMPFC,
                     :BDVALPROEMPFERFN,
                     :BDVALPROEMPFERFC,
                     :BDVALPROEMP13FN,
                     :BDVALPROEMP13FC,
                     :BDVALPROEMP13,
                     :BDVALPROEMPC13,
                     :BDVALAUTEMPFN,
                     :BDVALAUTEMPFC,
                     :BDVALAUTEMPFERFN,
                     :BDVALAUTEMPFERFC,
                     :BDVALAUTEMP13FN,
                     :BDVALAUTEMP13FC,
                     :BDVALAUTEMP13,
                     :BDVALAUTEMPC13,
                     :BDVALFPASEMPFN,
                     :BDVALFPASEMPFC,
                     :BDVALFPASEMPFERFN,
                     :BDVALFPASEMPFERFC,
                     :BDVALFPASEMP13FN,
                     :BDVALFPASEMP13FC,
                     :BDVALFPASEMP13,
                     :BDVALFPASEMPC13,
                     :BDVALRATEMPFN,
                     :BDVALRATEMPFC,
                     :BDVALRATEMPFERFN,
                     :BDVALRATEMPFERFC,
                     :BDVALRATEMP13FN,
                     :BDVALRATEMP13FC,
                     :BDVALRATEMP13,
                     :BDVALRATEMPC13,
                     :BDVALRATAPOEMPFN,
                     :BDVALRATAPOEMPFC,
                     :BDVALRATAPOEMPFERFN,
                     :BDVALRATAPOEMPFERFC,
                     :BDVALRATAPOEMP13FN,
                     :BDVALRATAPOEMP13FC,
                     :BDVALRATAPOEMP13,
                     :BDVALRATAPOEMPC13,
                     :BDCHAVEDARF
                   DO
                     SUSPEND;
        
                   /*proximo sql*/
                   wtipoemissaoant = wtipoemissao;
                   wwhereemp = CAST(wempatu AS VARCHAR(10));
                 END
         END
    END

   wsqlcalc = 'select '||
                'bdtiporeg, '||
                'bdcodemp , '||
                'bdcodcol,'||
                'bdcodter,'||
                'bdreffn , '||
                'bdrefpag , '||
                'bdcodcentro, '||
                'bdcodtpcc , '||
                'bdtotseg , '||
                'bdtotbase , '||
                'bdsegfun , '||
                'bdbasefun , '||
                'bdpercfun , '||
                'bdvalfunemp , '||
                'bdsegpro , '||
                'bdbasepro , '||
                'bdpercpro , '||
                'bdvalproemp , '||
                'bdsegaut , '||
                'bdbaseaut , '||
                'bdpercaut , '||
                'bdvalautemp , '||
                'bdsalfam , '||
                'bdsalmaternidade , '||
                'bdbaseratapo , '||
                'bdvalorratapo , '||
                'bdbasefpas , '||
                'bdpercfpas , '||
                'bdvalorfpas , '||
                'bdpercrat , '||
                'bdvalorrat , '||
                'bdvalorbruto , '||
                'bdvalorliquido , '||
                'bdnfcoop , '||
                'bdchave , '||
                'bdvalcompensado , '||
                'bdvalacompensar , '||
                'bdvaloracumulado , '||
                'bdvaloracumuladousado , '||
                'bdvaloracuterceiros , '||
                'bdvaloracuterceirosusado , '||
                'bdcodempant , '||
                'BDCHAVEDARFANT , '||
                'bdcodimpant , '||
                'bdcodperiodoant , '||
                'bdordemant , '||
                'bdreferenciaant , '||
                'bdquotaant , '||
                'bddescacumdet , '||
                'bddescacum , '||
                'bdvalorcampo6 , '||
                'bdvalnotas , '||
                'bddescnotas , '||
                'bdtotdesccomp , '||
                'bdtotvaloracumulado , '||
                'bdtotvaloracumuladoterc , '||
                'bdinicomp , '||
                'bdfimcomp , '||
                'bdtotcompensacao , '||
                'bddescsalfam , '||
                'bddescdedgps , '||
                'bdvaloutentidade, '||
                'bdsimplesgps, '||
                'bdcodenqfed, '||
                'bddescenqfed, '||
                'BDVALFUNEMPFN, '||
                'BDVALFUNEMPFC, '||
                'BDVALFUNEMPFERFN, '||
                'BDVALFUNEMPFERFC, '||
                'BDVALFUNEMP13FN, '||
                'BDVALFUNEMP13FC, '||
                'BDVALFUNEMP13, '||
                'BDVALFUNEMPC13, '||
                'BDVALPROEMPFN, '||
                'BDVALPROEMPFC, '||
                'BDVALPROEMPFERFN, '||
                'BDVALPROEMPFERFC, '||
                'BDVALPROEMP13FN, '||
                'BDVALPROEMP13FC, '||
                'BDVALPROEMP13, '||
                'BDVALPROEMPC13, '||
                'BDVALAUTEMPFN, '||
                'BDVALAUTEMPFC, '||
                'BDVALAUTEMPFERFN, '||
                'BDVALAUTEMPFERFC, '||
                'BDVALAUTEMP13FN, '||
                'BDVALAUTEMP13FC, '||
                'BDVALAUTEMP13, '||
                'BDVALAUTEMPC13, '||
                'BDVALFPASEMPFN, '||
                'BDVALFPASEMPFC, '||
                'BDVALFPASEMPFERFN, '||
                'BDVALFPASEMPFERFC, '||
                'BDVALFPASEMP13FN, '||
                'BDVALFPASEMP13FC, '||
                'BDVALFPASEMP13, '||
                'BDVALFPASEMPC13, '||
                'BDVALRATEMPFN, '||
                'BDVALRATEMPFC, '||
                'BDVALRATEMPFERFN, '||
                'BDVALRATEMPFERFC, '||
                'BDVALRATEMP13FN, '||
                'BDVALRATEMP13FC, '||
                'BDVALRATEMP13, '||
                'BDVALRATEMPC13, '||
                'BDVALRATAPOEMPFN, '||
                'BDVALRATAPOEMPFC, '||
                'BDVALRATAPOEMPFERFN, '||
                'BDVALRATAPOEMPFERFC, '||
                'BDVALRATAPOEMP13FN, '||
                'BDVALRATAPOEMP13FC, '||
                'BDVALRATAPOEMP13, '||
                'BDVALRATAPOEMPC13, '||
                'BDCHAVEDARF '||
                ' from vrhf_sp_gps(';

   IF (prcodimp IS NULL) THEN
      wparsqlcalc = 'null,';
   ELSE
      wparsqlcalc = prcodimp||',';

   --prcodemp varchar(32000),
    IF (prpuxafiliais = 1) THEN
       WPARSQLCALC = wparsqlcalc||''''||'(colcon.bdcodemp in ('||wwhereemp||') or temp.bdcodmatriz in ('||wwhereemp||'))'||'''';
    ELSE
       WPARSQLCALC = wparsqlcalc||''''||'colcon.bdcodemp in ('||wwhereemp||')'||'''';

   --prcodcol varchar(32000),
   wparsqlcalc = wparsqlcalc||',';
   IF (prcodcol IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
       wparsqlcalc = wparsqlcalc||''''||prcodcol||'''';

   --prcodaut varchar(32000),
   wparsqlcalc = wparsqlcalc||',';
   IF (prcodaut IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
       wparsqlcalc = wparsqlcalc||''''||prcodaut||'''';

   wparsqlcalc = wparsqlcalc||',';

   --prtipocol integer,
   IF (prtipocol IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||prtipocol;

   wparsqlcalc = wparsqlcalc||',';

   --pranomes integer,
   IF (pranomes IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||pranomes;

   wparsqlcalc = wparsqlcalc||',';

   --pranomespag integer,
   IF (pranomespag IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||pranomespag;

   wparsqlcalc = wparsqlcalc||',';

   --prtipoemissao integer,
   wparsqlcalc = wparsqlcalc||CAST(wtipoemissaoant AS VARCHAR(10));
   wparsqlcalc = wparsqlcalc||',';

   --prapenasgps integer,
   IF (prapenasgps IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||prapenasgps;
   wparsqlcalc = wparsqlcalc||',';

   --prtipogps integer)
   IF (prtipogps IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||prtipogps;
   wparsqlcalc = wparsqlcalc||',';

   -- puxa filiais
   IF (prpuxafiliais IS NULL) THEN
      wparsqlcalc = wparsqlcalc||'null';
   ELSE
      wparsqlcalc = wparsqlcalc||prpuxafiliais;

   wsqlcalc = wsqlcalc||wparsqlcalc||')';

   FOR EXECUTE STATEMENT wsqlcalc
   INTO
     :bdtiporeg,
     :bdcodemp,
     :bdcodcol,
     :bdcodter,
     :bdreffn,
     :bdrefpag,
     :bdcodcentro,
     :bdcodtpcc,
     :bdtotseg,
     :bdtotbase,
     :bdsegfun,
     :bdbasefun,
     :bdpercfun,
     :bdvalfunemp,
     :bdsegpro,
     :bdbasepro,
     :bdpercpro,
     :bdvalproemp,
     :bdsegaut,
     :bdbaseaut,
     :bdpercaut,
     :bdvalautemp,
     :bdsalfam,
     :bdsalmaternidade,
     :bdbaseratapo,
     :bdvalorratapo,
     :bdbasefpas,
     :bdpercfpas,
     :bdvalorfpas,
     :bdpercrat,
     :bdvalorrat,
     :bdvalorbruto,
     :bdvalorliquido,
     :bdnfcoop,
     :bdchave,
     :bdvalcompensado,
     :bdvalacompensar,
     :bdvaloracumulado,
     :bdvaloracumuladousado ,
     :bdvaloracumuterceiro,
     :bdvaloracuterceirosusado ,
     :bdcodempant ,
     :BDCHAVEDARFANT,
     :bdcodimpant ,
     :bdcodperiodoant,
     :bdordemant ,
     :bdreferenciaant ,
     :bdquotaant,
     :bddescacumdet,
     :bddescacu,
     :bdvalorcampo6,
     :BDVALORNOTAS,
     :bddescnotas,
     :bdtotdesccomp,
     :bdtotvaloracumulado,
     :bdtotvaloracumuladoTerc,
     :bdinicomp,
     :bdfimcomp,
     :bdtotcompensacao,
     :bddescsalfam,
     :bddescdedgps,
     :BDVALOUTENTIDADES,
     :bdsimplesgps,
     :bdcodenqfed,
     :bddescenqfed,
     :BDVALFUNEMPFN,
     :BDVALFUNEMPFC,
     :BDVALFUNEMPFERFN,
     :BDVALFUNEMPFERFC,
     :BDVALFUNEMP13FN,
     :BDVALFUNEMP13FC,
     :BDVALFUNEMP13,
     :BDVALFUNEMPC13,
     :BDVALPROEMPFN,
     :BDVALPROEMPFC,
     :BDVALPROEMPFERFN,
     :BDVALPROEMPFERFC,
     :BDVALPROEMP13FN,
     :BDVALPROEMP13FC,
     :BDVALPROEMP13,
     :BDVALPROEMPC13,
     :BDVALAUTEMPFN,
     :BDVALAUTEMPFC,
     :BDVALAUTEMPFERFN,
     :BDVALAUTEMPFERFC,
     :BDVALAUTEMP13FN,
     :BDVALAUTEMP13FC,
     :BDVALAUTEMP13,
     :BDVALAUTEMPC13,
     :BDVALFPASEMPFN,
     :BDVALFPASEMPFC,
     :BDVALFPASEMPFERFN,
     :BDVALFPASEMPFERFC,
     :BDVALFPASEMP13FN,
     :BDVALFPASEMP13FC,
     :BDVALFPASEMP13,
     :BDVALFPASEMPC13,
     :BDVALRATEMPFN,
     :BDVALRATEMPFC,
     :BDVALRATEMPFERFN,
     :BDVALRATEMPFERFC,
     :BDVALRATEMP13FN,
     :BDVALRATEMP13FC,
     :BDVALRATEMP13,
     :BDVALRATEMPC13,
     :BDVALRATAPOEMPFN,
     :BDVALRATAPOEMPFC,
     :BDVALRATAPOEMPFERFN,
     :BDVALRATAPOEMPFERFC,
     :BDVALRATAPOEMP13FN,
     :BDVALRATAPOEMP13FC,
     :BDVALRATAPOEMP13,
     :BDVALRATAPOEMPC13,
     :BDCHAVEDARF
   DO
     SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_CONS_13SALARIO */
ALTER PROCEDURE VRHF_SP_CONS_13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF13 INTEGER,
BDMESESPROP13 INTEGER,
BDBASEIR13 NUMERIC(15,6),
BDBASEFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTSCS13 NUMERIC(15,6),
BDPERCIR13 NUMERIC(15,6),
BDVALORIR13 NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDPERCINSS13 NUMERIC(15,6),
BDVALORINSS13 NUMERIC(15,6))
 AS
DECLARE VARIABLE wsql VARCHAR(32700);
DECLARE VARIABLE wwhere VARCHAR(32700);
BEGIN
  wsql = 'select BDCODEMP, '||
                'BDCODCOL, '||
                'BDREF13, '||
                'coalesce(sum(BDMESESPROP13), 0), '||
                'coalesce(sum(BDBASEIR13), 0), '||
                'coalesce(sum(BDBASEFGTS13), 0), '||
                'coalesce(sum(BDFGTS13), 0), '||
                'coalesce(sum(BDFGTSCS13), 0), '||
                'coalesce(sum(BDPERCIR13), 0), '||
                'coalesce(sum(BDVALORIR13), 0), '||
                'coalesce(sum(BDBASEINSS13), 0), '||
                'coalesce(sum(BDPERCINSS13), 0), '||
                'coalesce(sum(BDVALORINSS13), 0) '||
         'from VRHF_EMP_T13SAL ';

  wsql = wsql||' where ';
  wwhere = '';


  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||:PRCODEMP;
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODCOL;
     END

  IF (:PRANOMES IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDREF13 = '||:PRANOMES;
     END

  wsql = wsql||wwhere;

  wsql = wsql||'group by BDCODEMP, '||
                        'BDCODCOL, '||
                        'BDREF13 ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF13,
    :BDMESESPROP13,
    :BDBASEIR13,
    :BDBASEFGTS13,
    :BDFGTS13,
    :BDFGTSCS13,
    :BDPERCIR13,
    :BDVALORIR13,
    :BDBASEINSS13,
    :BDPERCINSS13,
    :BDVALORINSS13
  DO

  SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_CONS_AD13SALARIO */
ALTER PROCEDURE VRHF_SP_CONS_AD13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFA13 INTEGER,
BDPERCA13 NUMERIC(15,6),
BDVALA13 NUMERIC(15,6),
BDBASEIRA13 NUMERIC(15,6),
BDFGTSA13 NUMERIC(15,6),
BDFGTSCSA13 NUMERIC(15,6),
BDBASEFGTSA13 NUMERIC(15,6),
BDPERCIRA13 NUMERIC(15,6),
BDVALORIRA13 NUMERIC(15,6),
BDREF INTEGER,
BDSALBASE NUMERIC(15,6),
BDPROVENTO INTEGER,
BDDESCONTO NUMERIC(15,6))
 AS
DECLARE VARIABLE wsql VARCHAR(32700);
DECLARE VARIABLE wwhere VARCHAR(32700);
BEGIN
  wsql = 'select BDCODEMP, '||
                'BDCODCOL, '||
                'BDREFA13, '||
                'coalesce(sum(BDPERCA13), 0), '||
                'coalesce(sum(BDVALA13), 0), '||
                'coalesce(sum(BDBASEIRA13), 0), '||
                'coalesce(sum(BDFGTSA13), 0), '||
                'coalesce(sum(BDFGTSCSA13), 0), '||
                'coalesce(sum(BDBASEFGTSA13), 0), '||
                'coalesce(sum(BDPERCIRA13), 0), '||
                'coalesce(sum(BDVALORIRA13), 0) '||
         'from VRHF_EMP_TA13SAL ';

  wsql = wsql||' where ';
  wwhere = '';


  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||:PRCODEMP;
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODCOL;
     END

  IF (:PRANOMES IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDREFA13 = '||:PRANOMES;
     END

  wsql = wsql||wwhere;

  wsql = wsql||'group by BDCODEMP, '||
                        'BDCODCOL, '||
                        'BDREFA13 ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFA13,
    :BDPERCA13,
    :BDVALA13,
    :BDBASEIRA13,
    :BDFGTSA13,
    :BDFGTSCSA13,
    :BDBASEFGTSA13,
    :BDPERCIRA13,
    :BDVALORIRA13
  DO
     BEGIN
       bdref = bdrefa13;
       SUSPEND;
     END
END
^

/* Restore proc. body: VRHF_SP_CONS_ADIANTA_SAL */
ALTER PROCEDURE VRHF_SP_CONS_ADIANTA_SAL(PRCODEMP VARCHAR(32700),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFAD INTEGER,
BDCODVER INTEGER,
BDREFVAD NUMERIC(15,6),
BDREFAUXVAD NUMERIC(15,6),
BDVALVAD NUMERIC(15,6),
BDIGNREFAVAD VARCHAR(5),
BDIGNREFVAD VARCHAR(5),
BDIGNVALVAD VARCHAR(5),
BDDATAAD DATE,
BDBASEAD INTEGER,
BDTIPOAD INTEGER,
BDVALPERCAD NUMERIC(15,6),
BDBASEIRAD NUMERIC(15,6),
BDDATABAIXAAD DATE,
BDREFBAIXAAD INTEGER,
BDVALORIRAD NUMERIC(15,6),
BDPERCIRAD NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(4000);
DECLARE VARIABLE WWHERE VARCHAR(32700);
BEGIN
  wsql = 'select BDCODEMP, '||
         'BDCODCOL, '||
         'BDREFAD, '||
         'BDCODVER, '||
         'BDREFVAD, '||
         'BDREFAUXVAD, '||
         'BDVALVAD, '||
         'BDIGNREFAVAD, '||
         'BDIGNREFVAD, '||
         'BDIGNVALVAD, '||
         'BDDATAAD, '||
         'BDBASEAD, '||
         'BDTIPOAD, '||
         'BDVALPERCAD, '||
         'BDBASEIRAD, '||
         'BDDATABAIXAAD, '||
         'BDREFBAIXAAD, '||
         'BDVALORIRAD, '||
         'BDPERCIRAD ';
  wsql = wsql||'from vw_vrhf_adiantamento_sal ';

  wwhere = '';

  IF (:PRANOMES IS NOT NULL AND (:PRANOMES <> 0)) THEN
     BEGIN
       wwhere = wwhere||'where BDREFAD = '||:PRANOMES;
     END

  IF (:PRCODEMP IS NOT NULL AND (:PRCODEMP <> '')) THEN
     BEGIN
       IF (wwhere = '') THEN
          wwhere = wwhere||'where '||:PRCODEMP;
       ELSE
          wwhere = wwhere||' and '||:PRCODEMP;
     END

  IF (:PRCODCOL IS NOT NULL AND (:PRCODCOL <> '')) THEN
     BEGIN
       IF (wwhere = '') THEN
          wwhere = wwhere||'where '||:PRCODCOL;
       ELSE
          wwhere = wwhere||' and '||:PRCODCOL;
     END

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFAD,
    :BDCODVER,
    :BDREFVAD,
    :BDREFAUXVAD,
    :BDVALVAD,
    :BDIGNREFAVAD,
    :BDIGNREFVAD,
    :BDIGNVALVAD,
    :BDDATAAD,
    :BDBASEAD,
    :BDTIPOAD,
    :BDVALPERCAD,
    :BDBASEIRAD,
    :BDDATABAIXAAD,
    :BDREFBAIXAAD,
    :BDVALORIRAD,
    :BDPERCIRAD
  DO

  SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_CONS_CALC_13SALARIO */
ALTER PROCEDURE VRHF_SP_CONS_CALC_13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFAV VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDMESESPROP13 INTEGER,
BDBASEIR13 NUMERIC(15,6),
BDBASEFGTS13 NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS13 NUMERIC(15,6),
BDDATABAIXA13 DATE,
BDREFBAIXA13 INTEGER,
BDPERCIR13 NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDPERCINSS13 NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6))
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  wsql = 'select GRUPOVERBAS.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'GRUPOVERBAS.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'GRUPOVERBAS.BDCODVER, '||
                'VERREF.BDDESCVER, '||
                'VERREF.bddescredver, '||
                'GRUPOVERBAS.BDREFV13, '||
                'GRUPOVERBAS.BDREFAUXV13, '||
                'case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.BDVALV13 '||
                     'when (VERREF.BDTIPOCODVER <> 0) then 0 end BDPROVENTO, '||
                'case when (VERREF.BDTIPOCODVER > 0) then GRUPOVERBAS.BDVALV13 '||
                     'when (VERREF.BDTIPOCODVER <= 0) then 0 end BDDESCONTO, '||
                'VERREF.BDTIPOCODVER, '||
                'VERREF.BDINSSVER, '||
                'VERREF.BDFGTSVER, '||
                'VERREF.BDIRVER, '||
                'VERREF.BDTIPOREFVER, '||
                'VERREF.BDBASESFVER, '||
                'VERREF.BDPISVER, '||
                'VERREF.BDBASEHEVER, '||
                'VERREF.BDBASEMAIORVER, '||
                'VERREF.BDRAISVER, '||
                'VERREF.BDBASEGPSVER, '||
                'GRUPOVERBAS.BDIGNREFAV13, '||
                'GRUPOVERBAS.BDIGNREFV13, '||
                'GRUPOVERBAS.BDIGNVALV13, '||
                'VERREF.BDCLAVER, '||
                'VERREF.BDORDEMVER, '||
                'GRUPOVERBAS.BDREF13, '||
                'EMPCALC.BDREFHOREMP, '||
                'Y.BDMESESPROP13, '||
                'Y.BDBASEIR13, '||
                'Y.BDBASEFGTS13, '||
                'Y.BDFGTS13, '||
                'Y.BDFGTSCS13, '||
                'Y.BDDATABAIXA13, '||
                'Y.BDREFBAIXA13, '||
                'Y.BDPERCIR13, '||
                'Y.BDVALORIR13, '||
                'Y.BDBASEINSS13, '||
                'Y.BDPERCINSS13, '||
                'Y.BDVALORINSS13, '||
                'Y.BDSALBASE13, '||
                'Y.BDDEP13, '||
                'Y.BDCREDITO13, '||
                'Y.BDDEBITO13 '||
         'from vrhf_emp_tverba13 GRUPOVERBAS '||
         'join TEMPRESAS_REF EMP '||
           'on (CAST(EMP.BDCODEMP AS VARCHAR(5)) || CAST(EMP.BDREFEMP as VARCHAR(6)) in '||
                      '(select CAST(X.BDCODEMP AS VARCHAR(5)) || CAST(Max(X.BDREFEMP) as VARCHAR(6)) '||
                       'from TEMPRESAS_REF X '||
                       'where X.BDCODEMP = GRUPOVERBAS.BDCODEMP and X.BDCODEMP = EMP.BDCODEMP '||
                       'group by X.BDCODEMP '||
                      ') '||
              ') '||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
            'on (COL.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODCOL = GRUPOVERBAS.BDCODCOL) '||
         'join (select * from VRH_SP_CONS_VERBAS('||:PRANOMES||', null, 8)) VERREF '||
            'on (VERREF.BDCODVER = GRUPOVERBAS.BDCODVER) '||
         'left outer join VRHF_BASE_TEMPCALC EMPCALC '||
            'on (EMPCALC.BDCODEMP = GRUPOVERBAS.BDCODEMP and EMPCALC.BDREFEMP = EMP.BDREFEMP) '||
         'left outer join VRHF_EMP_T13SAL Y '||
            'on (Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODCOL = GRUPOVERBAS.BDCODCOL and Y.BDREF13 = GRUPOVERBAS.BDREF13) ';

  wwhere = 'where GRUPOVERBAS.BDREF13 = '||:PRANOMES||' ';

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODEMP;
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODCOL;
     END

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCODVER,
    :BDDESCVER,
    :bddescredver,
    :BDREFV,
    :BDREFAUXV,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDIGNREFAV,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDCLAVER,
    :BDORDEMVER,
    :BDREF,
    :BDREFHOREMP,
    :bdmesesprop13,
    :bdbaseir13,
    :bdbasefgts13,
    :bdfgts,
    :bdfgtscs13,
    :bddatabaixa13,
    :bdrefbaixa13,
    :bdpercir13,
    :bdirrf,
    :bdbaseinss13,
    :bdpercinss13,
    :bdinss,
    :BDSALBASE,
    :bddep,
    :bdcredito,
    :bddebito
  DO
  SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_CONS_CALC_AUTONOMOS */
ALTER PROCEDURE VRHF_SP_CONS_CALC_AUTONOMOS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODSERV INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFE NUMERIC(15,6),
BDFGTSFE NUMERIC(15,6))
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  /*
    Retorna os dados da tabela de verbas folha normal, junto com os dados do colaborador
    e empresa.
    Retorna tambem os parametros de cada verba lancada.
    Retorna os Valores e bases de INSS, FGTS, IRRF, Dependentes, Maior remuneracao,
    Salario familia, etc.
    Salario base
  */

  EXECUTE PROCEDURE sp_seta_competencia(pranomes,  NULL, NULL);

  wsql = 'select GRUPOVERBAS.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'GRUPOVERBAS.BDCODTER, '||
                'COL.BDNOMTER, '||
                'GRUPOVERBAS.BDCODSERV, '||
                'GRUPOVERBAS.BDCODVER, '||
                'VERB.BDDESCVER, '||
                'VERB.BDDESCREDVER, '||
                'GRUPOVERBAS.BDREFERENCIA, '||
                'GRUPOVERBAS.BDREFAUXILIAR, '||
                'case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.BDVALOR '||
                     'when (VERREF.BDTIPOCODVER <> 0) then 0 end BDPROVENTO, '||
                'case when (VERREF.BDTIPOCODVER > 0) then GRUPOVERBAS.BDVALOR '||
                     'when (VERREF.BDTIPOCODVER <= 0) then 0 end BDDESCONTO, '||
                'VERREF.BDTIPOCODVER, '||
                'case when VERREF.BDTIPOCODVER = 1 then 2 when VERREF.BDTIPOCODVER = 2 then 1 else coalesce(VERREF.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, '||
                'VERREF.BDINSSVER, '||
                'VERREF.BDFGTSVER, '||
                'VERREF.BDIRVER, '||
                'VERREF.BDTIPOREFVER, '||
                'VERREF.BDBASESFVER, '||
                'VERREF.BDPISVER, '||
                'VERREF.BDBASEHEVER, '||
                'VERREF.BDBASEMAIORVER, '||
                'VERREF.BDRAISVER, '||
                'VERREF.BDBASEGPSVER, '||
                'GRUPOVERBAS.BDIGNFORREF, '||
                'GRUPOVERBAS.BDIGNFORVAL, '||
                'VERB.BDCLAVER, '||
                'VERB.BDORDEMVER, '||
                'Y.BDREFINSSSERV, '||
                'EMPCALC.BDREFHOREMP, '||
                '0.0 BDBFGTSFN, '||
                '0.0 BDFGTSFN, '||
                '0.0 BDFGTSCSFN, '||
                '0.0 BDBFGTS13FN, '||
                '0.0 BDFGTS13FN, '||
                '0.0 BDFGTS13CSFN, '||
                '0.0 BDMAIORREMFN, '||
                'Y.BDBASEINSS, '||
                'Y.BDFAIXAINSS, '||
                'Y.BDVALORINSS, '||
                'Y.BDBASEIR, '||
                'Y.BDFAIXAIR, '||
                'Y.BDVALORIR, '||
                '0.0 BDBINSS13FN, '||
                '0.0 BDALIQINSS13FN, '||
                '0.0 BDINSS13FN, '||
                '0.0 BDBIRRF13FN, '||
                '0.0 BDALIQIRRF13FN, '||
                '0.0 BDIRRF13FN, '||
                '0.0 BDBSALFAMFN, '||
                '0.0 BDSALFAMFN, '||
                '0.0 BDBRAISFN, '||
                '0.0 BDSALBASEFN, '||
                '0.0 BDDEPFN, '||
                '0.0 BDBFGTSFEFN, '||
                '0.0 BDFGTSFEFN, '||
                'Y.BDCREDITOSERV, '||
                'Y.BDDEBITOSERV '||
         'from VRHF_BASE_ITEMS_CALCTERC GRUPOVERBAS, '||
         'VW_TEMPRESAS_REF EMP, '||
         'VRH_BASE_TTERC COL, '||
         'VRH_BASE_TVERBAS VERB, '||
         'VW_VERBAS_REF_ATUAL VERREF, '||
         'VW_VRHF_BASE_TEMPCALC EMPCALC, '||
         'VRHF_BASE_CALC_TERC Y ';

  wwhere = 'where EMP.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODTER = GRUPOVERBAS.BDCODTER and '||
           'VERB.BDCODVER = GRUPOVERBAS.BDCODVER and VERREF.BDCODVER = GRUPOVERBAS.BDCODVER and EMPCALC.BDCODEMP = GRUPOVERBAS.BDCODEMP and '||
           'Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODTER = GRUPOVERBAS.BDCODTER and Y.BDCODSERV = GRUPOVERBAS.BDCODSERV';

  IF (pranomes IS NOT NULL) THEN
     wwhere = wwhere||' and Y.BDREFINSSSERV = '||:PRANOMES||' ';

  wsql = wsql || wwhere;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = ' and ';
       wwhere = wwhere || ' GRUPOVERBAS.' || :PRCODEMP || ' ';
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere = '') THEN
          wwhere = ' and ';

       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || 'GRUPOVERBAS.'||:PRCODCOL || ' ';
     END

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCODSERV,
    :BDCODVER,
    :BDDESCVER,
    :BDDESCREDVER,
    :BDREFV,
    :BDREFAUXV,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDTIPOCODVER,
    :BDORDEMTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDCLAVER,
    :BDORDEMVER,
    :BDREF,
    :BDREFHOREMP,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :bdbfgtsfe,
    :BDFGTSFE,
    :bdcredito,
    :bddebito
  DO
  SUSPEND;
END
^

--#alt:16965. Alterei o cast do código da empresa para 9 digitos. Ana - 24/01/2018
/* Restore proc. body: VRHF_SP_CONS_CALC_COMP13SALARIO */
/* alt:13612 - 18/04/2016 - Alterado SQL para que na hora de fazer o CAST do campo BDCODEMP faça "AS VARCHAR(6)",
pois sempre que o código da empresa tinha mais de 5 caracteres ocorria um erro de conversão de dados - Bruno L. R.*/
ALTER PROCEDURE VRHF_SP_CONS_CALC_COMP13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBASEIRC13 NUMERIC(15,6),
BDBASEINSSC13 NUMERIC(15,6),
BDBASEFGTSC13 NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCSC13 NUMERIC(15,6),
BDDATABAIXAC13 DATE,
BDREFBAIXAC13 INTEGER,
BDPERCIRC13 NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDPERCINSSC13 NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6))
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  wsql = 'select GRUPOVERBAS.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'GRUPOVERBAS.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'GRUPOVERBAS.BDCODVER, '||
                'VERREF.BDDESCVER, '||
                'VERREF.bddescredver, '||
                'GRUPOVERBAS.BDREFVC13, '||
                'GRUPOVERBAS.BDREFAUXVC13, '||
                'case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.BDVALVC13 '||
                     'when (VERREF.BDTIPOCODVER <> 0) then 0 end BDPROVENTO, '||
                'case when (VERREF.BDTIPOCODVER > 0) then GRUPOVERBAS.BDVALVC13 '||
                     'when (VERREF.BDTIPOCODVER <= 0) then 0 end BDDESCONTO, '||
                'VERREF.BDTIPOCODVER, '||
                'case when VERREF.BDTIPOCODVER = 1 then 2 when VERREF.BDTIPOCODVER = 2 then 1 else coalesce(VERREF.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, '||
                'VERREF.BDINSSVER, '||
                'VERREF.BDFGTSVER, '||
                'VERREF.BDIRVER, '||
                'VERREF.BDTIPOREFVER, '||
                'VERREF.BDBASESFVER, '||
                'VERREF.BDPISVER, '||
                'VERREF.BDBASEHEVER, '||
                'VERREF.BDBASEMAIORVER, '||
                'VERREF.BDRAISVER, '||
                'VERREF.BDBASEGPSVER, '||
                'GRUPOVERBAS.BDIGNREFVC13, '||
                'GRUPOVERBAS.BDIGNVALVC13, '||
                'VERREF.BDCLAVER, '||
                'VERREF.BDORDEMVER, '||
                'GRUPOVERBAS.BDREFC13, '||
                'EMPCALC.BDREFHOREMP, '||
                'Y.BDBASEIRC13, '||
                'Y.BDBASEINSSC13, '||
                'Y.BDBASEFGTSC13, '||
                'Y.BDFGTSC13, '||
                'Y.BDFGTSCSC13, '||
                'Y.BDDATABAIXAC13, '||
                'Y.BDREFBAIXAC13, '||
                'Y.BDPERCIRC13, '||
                'Y.BDVALORIRC13, '||
                'Y.BDPERCINSSC13, '||
                'Y.BDVALORINSSC13, '||
                '0.0 BDSALBASE13, '||
                '0.0 BDDEP13, '||
                'Y.BDCREDITOC13, '||
                'Y.BDDEBITOC13 '||

         'from vrhf_emp_tverbaC13 GRUPOVERBAS '||
         'join TEMPRESAS_REF EMP '||
           'on (CAST(EMP.BDCODEMP AS VARCHAR(9)) || CAST(EMP.BDREFEMP as VARCHAR(6)) in '||
                      '(select CAST(X.BDCODEMP AS VARCHAR(9)) || CAST(Max(X.BDREFEMP) as VARCHAR(6)) '||
                       'from TEMPRESAS_REF X '||
                       'where X.BDCODEMP = GRUPOVERBAS.BDCODEMP and X.BDCODEMP = EMP.BDCODEMP '||
                       'group by X.BDCODEMP '||
                      ') '||
              ') '||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
            'on (COL.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODCOL = GRUPOVERBAS.BDCODCOL) '||
         'join (select * from VRH_SP_CONS_VERBAS('||:PRANOMES||', null, 8)) VERREF '||
            'on (VERREF.BDCODVER = GRUPOVERBAS.BDCODVER) '||
         'left outer join VRHF_BASE_TEMPCALC EMPCALC '||
            'on (EMPCALC.BDCODEMP = GRUPOVERBAS.BDCODEMP and EMPCALC.BDREFEMP = EMP.BDREFEMP) '||
         'left outer join VRHF_EMP_TC13SAL Y '||
            'on (Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODCOL = GRUPOVERBAS.BDCODCOL and Y.bdrefc13 = GRUPOVERBAS.bdrefc13) ';

  wwhere = 'where GRUPOVERBAS.BDREFC13 = '||:PRANOMES||' ';

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODEMP;
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODCOL;
     END

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCODVER,
    :BDDESCVER,
    :bddescredver,
    :BDREFV,
    :BDREFAUXV,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDTIPOCODVER,
    :BDORDEMTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDCLAVER,
    :BDORDEMVER,
    :BDREF,
    :BDREFHOREMP,
    :bdbaseirc13,
    :bdbaseinssc13,
    :bdbasefgtsc13,
    :bdfgts,
    :bdfgtscsc13,
    :bddatabaixac13,
    :bdrefbaixac13,
    :bdpercirc13,
    :bdirrf,
    :bdpercinssc13,
    :BDINSS,
    :bdsalbase,
    :bddep,
    :bdcredito,
    :bddebito
  DO
  SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_CONS_CALC_FERIAS */
create or alter procedure VRHF_SP_CONS_CALC_FERIAS (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRDATAINI date,
    PRDATAFIM date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDINIPERGOZOFE date,
    BDFIMPERAQUISFE date,
    BDFIMPERGOZOFE date,
    BDDATAPAGFE date,
    BDQTDGOZOFE integer,
    BDQTDABONOFE integer,
    BDSALDOINIFE numeric(15,6),
    BDSALDOFIMFE numeric(15,6),
    BDBASEIRFE numeric(15,6),
    BDALIQIRFE numeric(15,6),
    BDVALORIRFE numeric(15,6),
    BDBASEINSSFE numeric(15,6),
    BDALIQINSSFE numeric(15,6),
    BDVALORINSSFE numeric(15,6),
    BDDEPFE numeric(15,6),
    BDSALBASEFE numeric(15,6),
    BDSALBASEHEFE numeric(15,6),
    BDDATABAIXAFE date,
    BDCOLETIVASFE varchar(5),
    BDREFPAGABOFE integer,
    BDCODVER integer,
    BDREFVFE numeric(15,6),
    BDREFAUXVFE numeric(15,6),
    BDVALVFE numeric(15,6),
    BDIGNREFAVFE varchar(5),
    BDIGNREFVFE varchar(5),
    BDIGNVALVFE varchar(5),
    BDSALDOFINALSINDFE numeric(18,6),
    BDINIGOZORECIBOFE DATE,
    BDFIMGOZORECIBOFE DATE,
    BDQTDGOZORECIBOFE NUMERIC(18,6),
    BDMIGRACAO DM_BOOLEAN)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
BEGIN
  wsql = '';
  wwhere = '';

  wsql = wsql||'select BDCODEMP, '||
                      'BDCODCOL, '||
                      'BDINIPERAQUISFE, '||
                      'BDCODFE, '||
                      'BDINIPERGOZOFE, '||
                      'BDFIMPERAQUISFE, '||
                      'BDFIMPERGOZOFE, '||
                      'BDDATAPAGFE, '||
                      'BDQTDGOZOFE, '||
                      'BDQTDABONOFE, '||
                      'BDSALDOINIFE, '||
                      'BDSALDOFIMFE, '||
                      'BDBASEIRFE, '||
                      'BDALIQIRFE, '||
                      'BDVALORIRFE, '||
                      'BDBASEINSSFE, '||
                      'BDALIQINSSFE, '||
                      'BDVALORINSSFE, '||
                      'BDDEPFE, '||
                      'BDSALBASEFE, '||
                      'BDSALBASEHEFE, '||
                      'BDDATABAIXAFE, '||
                      'BDCOLETIVASFE, '||
                      'BDREFPAGABOFE, '||
                      'BDCODVER, '||
                      'BDREFVFE, '||
                      'BDREFAUXVFE, '||
                      'BDVALVFE, '||
                      'BDIGNREFAVFE, '||
                      'BDIGNREFVFE, '||
                      'BDIGNVALVFE, '||
                      'BDSALDOFINALSINDFE, '||
                      'BDINIGOZORECIBOFE, '||
                      'BDFIMGOZORECIBOFE, '||
                      'BDQTDGOZORECIBOFE, '||
                      'BDMIGRACAO ';

  wsql = wsql||'from VW_VRHF_FERIAS ';

  IF (:PRCODEMP IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||:PRCODEMP;

  IF (:PRCODCOL IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODCOL;
     END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';

  wwhere = wwhere||'((BDINIPERGOZOFE between '''||:PRDATAINI||''' AND '''||:PRDATAFIM||''') or ';
  wwhere = wwhere||'(BDFIMPERGOZOFE between '''||:PRDATAINI||''' AND '''||:PRDATAFIM||''') or ';
  wwhere = wwhere||'(BDINIPERGOZOFE < '''||:PRDATAINI||''' and BDFIMPERGOZOFE > '''||:PRDATAFIM||''') or ';
  wwhere = wwhere||'(BDREFPAGABOFE >= substring('''||:PRDATAINI||''' from 1 for 4)||'||' substring('''||:PRDATAINI||''' from 6 for 2) and ';
  wwhere = wwhere|| 'BDREFPAGABOFE <= substring('''||:PRDATAFIM||''' from 1 for 4)||'||' substring('''||:PRDATAFIM||''' from 6 for 2))) ';

  wsql = wsql||' where '||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDINIPERAQUISFE,
    :BDCODFE,
    :BDINIPERGOZOFE,
    :BDFIMPERAQUISFE,
    :BDFIMPERGOZOFE,
    :BDDATAPAGFE,
    :BDQTDGOZOFE,
    :BDQTDABONOFE,
    :BDSALDOINIFE,
    :BDSALDOFIMFE,
    :BDBASEIRFE,
    :BDALIQIRFE,
    :BDVALORIRFE,
    :BDBASEINSSFE,
    :BDALIQINSSFE,
    :BDVALORINSSFE,
    :BDDEPFE,
    :BDSALBASEFE,
    :BDSALBASEHEFE,
    :BDDATABAIXAFE,
    :BDCOLETIVASFE,
    :BDREFPAGABOFE,
    :BDCODVER,
    :BDREFVFE,
    :BDREFAUXVFE,
    :BDVALVFE,
    :BDIGNREFAVFE,
    :BDIGNREFVFE,
    :BDIGNVALVFE,
    :BDSALDOFINALSINDFE,
    :BDINIGOZORECIBOFE,
    :BDFIMGOZORECIBOFE,
    :BDQTDGOZORECIBOFE,
    :BDMIGRACAO
  DO

  SUSPEND;
END^

--#alt:16965. Alterei o cast do código da empresa para 9 digitos. Ana - 24/01/2018
/* Restore proc. body: VRHF_SP_CONS_CALC_FOLHACOMP */
ALTER PROCEDURE VRHF_SP_CONS_CALC_FOLHACOMP(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCREDITO NUMERIC(15,6))
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  /*
    Retorna os dados da tabela de verbas folha normal, junto com os dados do colaborador
    e empresa.
    Retorna tambem os parametros de cada verba lancada.
    Retorna os Valores e bases de INSS, FGTS, IRRF, Dependentes, Maior remuneracao,
    Salario familia, etc.
    Salario base
  */

  wsql = 'select GRUPOVERBAS.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'GRUPOVERBAS.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'GRUPOVERBAS.BDCODVER, '||
                'VERREF.BDDESCVER, '||
                'VERREF.bddescredver, '||
                'GRUPOVERBAS.BDREFVFC, '||
                'GRUPOVERBAS.BDREFAUXVFC, '||
                'case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.BDVALVFC '||
                     'when (VERREF.BDTIPOCODVER <> 0) then 0 end BDPROVENTO, '||
                'case when (VERREF.BDTIPOCODVER > 0) then GRUPOVERBAS.BDVALVFC '||
                     'when (VERREF.BDTIPOCODVER <= 0) then 0 end BDDESCONTO, '||
                'VERREF.BDTIPOCODVER, '||
                'VERREF.BDINSSVER, '||
                'VERREF.BDFGTSVER, '||
                'VERREF.BDIRVER, '||
                'VERREF.BDTIPOREFVER, '||
                'VERREF.BDBASESFVER, '||
                'VERREF.BDPISVER, '||
                'VERREF.BDBASEHEVER, '||
                'VERREF.BDBASEMAIORVER, '||
                'VERREF.BDRAISVER, '||
                'VERREF.BDBASEGPSVER, '||
                'GRUPOVERBAS.BDIGNREFVFC, '||
                'GRUPOVERBAS.BDIGNVALVFC, '||
                'VERREF.BDCLAVER, '||
                'VERREF.BDORDEMVER, '||
                'GRUPOVERBAS.BDREFCOMP, '||
                'EMPCALC.BDREFHOREMP, '||
                'Y.BDBFGTSFC, '||
                'Y.BDFGTSFC, '||
                'Y.BDFGTSCSFC, '||
                'Y.BDBFGTS13FC, '||
                'Y.BDFGTS13FC, '||
                'Y.BDFGTS13CSFC, '||
                'Y.BDMAIORREMFC, '||
                'Y.BDBINSSFC, '||
                'Y.BDALIQINSSFC, '||
                'Y.BDINSSFC, '||
                'Y.BDBIRRFFC, '||
                'Y.BDALIQIRRFFC, '||
                'Y.BDIRRFFC, '||
                'Y.BDBINSS13FC, '||
                'Y.BDALIQINSS13FC, '||
                'Y.BDINSS13FC, '||
                'Y.BDBIRRF13FC, '||
                'Y.BDALIQIRRF13FC, '||
                'Y.BDIRRF13FC, '||
                'Y.BDBSALFAMFC, '||
                'Y.BDSALFAMFC, '||
                'Y.BDBRAISFC, '||
                'Y.BDSALBASEFC, '||
                'Y.BDDEPFC, '||
                'Y.BDCREDITOFC, '||
                'Y.BDDEBITOFC '||
         'from VRHF_EMP_TVERBAFC GRUPOVERBAS '||
         'join TEMPRESAS_REF EMP '||
           'on (CAST(EMP.BDCODEMP AS VARCHAR(9)) || CAST(EMP.BDREFEMP as VARCHAR(6)) in '||
                      '(select CAST(X.BDCODEMP AS VARCHAR(9)) || CAST(Max(X.BDREFEMP) as VARCHAR(6)) '||
                       'from TEMPRESAS_REF X '||
                       'where X.BDCODEMP = GRUPOVERBAS.BDCODEMP and X.BDCODEMP = EMP.BDCODEMP '||
                       'group by X.BDCODEMP '||
                      ') '||
              ') '||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
            'on (COL.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODCOL = GRUPOVERBAS.BDCODCOL) '||
         'join (select * from VRH_SP_CONS_VERBAS('||:PRANOMES||', null, 8)) VERREF '||
            'on (VERREF.BDCODVER = GRUPOVERBAS.BDCODVER) '||
         'left outer join VRHF_BASE_TEMPCALC EMPCALC '||
            'on (EMPCALC.BDCODEMP = GRUPOVERBAS.BDCODEMP and EMPCALC.BDREFEMP = EMP.BDREFEMP) '||
         'left outer join VRHF_EMP_TFOLHACOMP Y '||
            'on (Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODCOL = GRUPOVERBAS.BDCODCOL and Y.BDREFCOMP = GRUPOVERBAS.BDREFCOMP) ';

  wwhere = 'where GRUPOVERBAS.BDREFCOMP = '||:PRANOMES||' ';

  wsql = wsql || wwhere;

  wsql = 'select BDCODEMP, '||
                'BDNOMEMP, '||
                'BDCODCOL, '||
                'BDNOMCOL, '||
                'BDCODVER, '||
                'BDDESCVER, '||
                'bddescredver, '||
                'BDREFVFC, '||
                'BDREFAUXVFC, '||
                'BDPROVENTO, '||
                'BDDESCONTO, '||
                'BDTIPOCODVER, '||
                'BDINSSVER, '||
                'BDFGTSVER, '||
                'BDIRVER, '||
                'BDTIPOREFVER, '||
                'BDBASESFVER, '||
                'BDPISVER, '||
                'BDBASEHEVER, '||
                'BDBASEMAIORVER, '||
                'BDRAISVER, '||
                'BDBASEGPSVER, '||
                'BDIGNREFVFC, '||
                'BDIGNVALVFC, '||
                'BDCLAVER, '||
                'BDORDEMVER, '||
                'BDREFCOMP, '||
                'BDREFHOREMP, '||
                'BDBFGTSFC, '||
                'BDFGTSFC, '||
                'BDFGTSCSFC, '||
                'BDBFGTS13FC, '||
                'BDFGTS13FC, '||
                'BDFGTS13CSFC, '||
                'BDMAIORREMFC, '||
                'BDBINSSFC, '||
                'BDALIQINSSFC, '||
                'BDINSSFC, '||
                'BDBIRRFFC, '||
                'BDALIQIRRFFC, '||
                'BDIRRFFC, '||
                'BDBINSS13FC, '||
                'BDALIQINSS13FC, '||
                'BDINSS13FC, '||
                'BDBIRRF13FC, '||
                'BDALIQIRRF13FC, '||
                'BDIRRF13FC, '||
                'BDBSALFAMFC, '||
                'BDSALFAMFC, '||
                'BDBRAISFC, '||
                'BDSALBASEFC, '||
                'BDDEPFC, '||
                'BDCREDITOFC, '||
                'BDDEBITOFC '||
         'from ('||
         wsql||
         ') '||
         'where ';

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere || ' ' || :PRCODEMP || ' ';
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || :PRCODCOL || ' ';
     END

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCODVER,
    :BDDESCVER,
    :bddescredver,
    :BDREFV,
    :BDREFAUXV,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDCLAVER,
    :BDORDEMVER,
    :BDREF,
    :BDREFHOREMP,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :bdcredito,
    :bddebito
  DO
  SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_CONS_CALC_FOLHANORMAL */
ALTER PROCEDURE VRHF_SP_CONS_CALC_FOLHANORMAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDBFGTSFE NUMERIC(15,6),
BDFGTSFE NUMERIC(15,6))
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WSUM NUMERIC(15,6);
DECLARE VARIABLE WMAX NUMERIC(15,6);
BEGIN
  /*
    Retorna os dados da tabela de verbas folha normal, junto com os dados do colaborador
    e empresa.
    Retorna tambem os parametros de cada verba lancada.
    Retorna os Valores e bases de INSS, FGTS, IRRF, Dependentes, Maior remuneracao,
    Salario familia, etc.
    Salario base
  */

  EXECUTE PROCEDURE sp_seta_competencia(pranomes,  NULL, NULL);

  wsql = 'select GRUPOVERBAS.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'GRUPOVERBAS.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'GRUPOVERBAS.BDCODVER, '||
                'VERB.BDDESCVER, '||
                'VERB.BDDESCREDVER, '||
                'GRUPOVERBAS.BDREFVFN, '||
                'GRUPOVERBAS.BDREFAUXVFN, '||
                'case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.BDVALVFN '||
                     'when (VERREF.BDTIPOCODVER = 2) then GRUPOVERBAS.BDVALVFN '||
                     'else 0.00 end BDPROVENTO, '||
                'case when (VERREF.BDTIPOCODVER = 1) then GRUPOVERBAS.BDVALVFN '||
                     'when (VERREF.BDTIPOCODVER = 3) then GRUPOVERBAS.BDVALVFN '||
                     'else 0.00 end BDDESCONTO, '||
                'VERREF.BDTIPOCODVER, '||
                'case when VERREF.BDTIPOCODVER = 1 then 2 when VERREF.BDTIPOCODVER = 2 then 1 else coalesce(VERREF.BDTIPOCODVER, 0) end BDORDEMTIPOCODVER, '||
                'VERREF.BDINSSVER, '||
                'VERREF.BDFGTSVER, '||
                'VERREF.BDIRVER, '||
                'VERREF.BDTIPOREFVER, '||
                'VERREF.BDBASESFVER, '||
                'VERREF.BDPISVER, '||
                'VERREF.BDBASEHEVER, '||
                'VERREF.BDBASEMAIORVER, '||
                'VERREF.BDRAISVER, '||
                'VERREF.BDBASEGPSVER, '||
                'GRUPOVERBAS.BDIGNREFVFN, '||
                'GRUPOVERBAS.BDIGNVALVFN, '||
                'VERB.BDCLAVER, '||
                'VERB.BDORDEMVER, '||
                'GRUPOVERBAS.BDREFFN, '||
                'EMPCALC.BDREFHOREMP, '||
                'Y.BDBFGTSFN, '||
                'Y.BDFGTSFN, '||
                'Y.BDFGTSCSFN, '||
                'Y.BDBFGTS13FN, '||
                'Y.BDFGTS13FN, '||
                'Y.BDFGTS13CSFN, '||
                'Y.BDMAIORREMFN, '||
                'Y.BDBINSSFN, '||
                'Y.BDALIQINSSFN, '||
                'Y.BDINSSFN, '||
                'Y.BDBIRRFFN, '||
                'Y.BDALIQIRRFFN, '||
                'Y.BDIRRFFN, '||
                'Y.BDBINSS13FN, '||
                'Y.BDALIQINSS13FN, '||
                'Y.BDINSS13FN, '||
                'Y.BDBIRRF13FN, '||
                'Y.BDALIQIRRF13FN, '||
                'Y.BDIRRF13FN, '||
                'Y.BDBSALFAMFN, '||
                'Y.BDSALFAMFN, '||
                'Y.BDBRAISFN, '||
                'Y.BDSALBASEFN, '||
                'Y.BDDEPFN, '||
                'Y.BDBFGTSFEFN, '||
                'Y.BDFGTSFEFN, '||
                'Y.BDCREDITOFN, '||
                'Y.BDDEBITOFN '||
         'from VRHF_EMP_TVERBAFN GRUPOVERBAS, '||
         'VW_TEMPRESAS_REF EMP, '||
         'VW_VRH_EMP_TCOLCON_CAD COL, '||
         'VRH_BASE_TVERBAS VERB, '||
         'VW_VERBAS_REF_ATUAL VERREF, '||
         'VW_VRHF_BASE_TEMPCALC EMPCALC, '||
         'VRHF_EMP_TFOLHANORMAL Y ';

  wwhere = 'where EMP.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODCOL = GRUPOVERBAS.BDCODCOL and '||
           'VERB.BDCODVER = GRUPOVERBAS.BDCODVER and VERREF.BDCODVER = GRUPOVERBAS.BDCODVER and EMPCALC.BDCODEMP = GRUPOVERBAS.BDCODEMP and '||
           'Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODCOL = GRUPOVERBAS.BDCODCOL and Y.BDREFFN = GRUPOVERBAS.BDREFFN';

  IF (pranomes IS NOT NULL) THEN
     wwhere = wwhere||' and GRUPOVERBAS.BDREFFN = '||:PRANOMES||' ';

  wsql = wsql || wwhere;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = ' and ';
       wwhere = wwhere || ' GRUPOVERBAS.' || :PRCODEMP || ' ';
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere = '') THEN
          wwhere = ' and ';

       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || 'GRUPOVERBAS.'||:PRCODCOL || ' ';
     END

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCODVER,
    :BDDESCVER,
    :BDDESCREDVER,
    :BDREFV,
    :BDREFAUXV,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDTIPOCODVER,
    :BDORDEMTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDCLAVER,
    :BDORDEMVER,
    :BDREF,
    :BDREFHOREMP,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :bdbfgtsfe,
    :BDFGTSFE,
    :bdcredito,
    :bddebito
  DO
  SUSPEND;

  wwhere = '';

  -- folha por tomador
/*00*/  wsql = 'select GRUPOVERBAS.BDCODEMP,'||
/*01*/                'EMP.BDNOMEMP,'||
/*02*/                'GRUPOVERBAS.BDCODCOL,'||
/*03*/                'COL.BDNOMCOL,'||
/*04*/                'GRUPOVERBAS.BDCODVER,'||
/*05*/                'VERB.BDDESCVER,'||
/*06*/                'VERB.BDDESCREDVER,'||
/*07*/                'sum(GRUPOVERBAS.bdrefvft),'|| -- aki
/*08*/                'max(GRUPOVERBAS.bdrefvft),'|| -- aki
/*09*/                'sum(GRUPOVERBAS.bdrefauxvft),'||
/*10*/                'sum(case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.bdvalvft'||
                      '     when (VERREF.BDTIPOCODVER <> 0) then 0 end) BDPROVENTO,'||
/*11*/                'sum(case when (VERREF.BDTIPOCODVER > 0) then GRUPOVERBAS.bdvalvft'||
                      '     when (VERREF.BDTIPOCODVER <= 0) then 0 end) BDDESCONTO,'||
/*12*/                'max(VERREF.BDTIPOCODVER),'||
/*13*/                'max(VERREF.BDINSSVER),'||
/*14*/                'max(VERREF.BDFGTSVER),'||
/*15*/                'max(VERREF.BDIRVER),'||
/*16*/                'max(VERREF.BDTIPOREFVER),'||
/*17*/                'max(VERREF.BDBASESFVER),'||
/*18*/                'VERREF.BDPISVER,'||
/*19*/                'VERREF.BDBASEHEVER,'||
/*20*/                'VERREF.BDBASEMAIORVER,'||
/*21*/                'VERREF.BDRAISVER,'||
/*22*/                'VERREF.BDBASEGPSVER,'||
/*23*/                'GRUPOVERBAS.bdignrefvft,'||
/*24*/                'GRUPOVERBAS.bdignvalvft,'||
/*25*/                'VERB.BDCLAVER,'||
/*26*/                'max(VERB.BDORDEMVER),'||
/*27*/                'GRUPOVERBAS.bdreftomador,'||
/*28*/                'EMPCALC.BDREFHOREMP,'||
/*29*/                'sum(Y.bdbfgtsft),'||
/*30*/                'sum(Y.bdfgtsft),'||
/*31*/                'sum(Y.bdfgtscsft),'||
/*32*/                'sum(Y.bdbfgts13ft),'||
/*33*/                'sum(Y.bdfgts13ft),'||
/*34*/                'sum(Y.bdfgts13csft),'||
/*35*/                'sum(Y.bdmaiorremft),'||
/*36*/                'sum(Y.bdbinssft),'||
/*37*/                'sum(Y.bdaliqinssft),'||
/*38*/                'sum(Y.bdinssft),'||
/*39*/                'sum(Y.bdbirrfft),'||
/*40*/                'sum(Y.bdaliqirrfft),'||
/*41*/                'sum(Y.bdirrfft),'||
/*42*/                'sum(Y.bdbinss13ft),'||
/*43*/                'sum(Y.bdaliqinss13ft),'||
/*44*/                'sum(Y.bdinss13ft),'||
/*45*/                'sum(Y.bdbirrf13ft),'||
/*46*/                'sum(Y.bdaliqirrf13ft),'||
/*47*/                'sum(Y.bdirrf13ft),'||
/*48*/                'sum(Y.bdbsalfamft),'||
/*49*/                'sum(Y.bdsalfamft),'||
/*50*/                'sum(Y.bdbraisft),'||
/*51*/                'max(Y.bdsalbaseft),'||  --162930 Valmor 04/05/2022 
/*52*/                'sum(Y.bddepft), '||
/*53*/                'sum(Y.BDBFGTSFEFT), '||
/*54*/                'sum(Y.BDFGTSFEFT), '||
/*55*/                'sum(Y.BDCREDITOFT), '||
/*56*/                'sum(Y.BDDEBITOFT) '||
         ' from vrhf_emp_tverbatomador GRUPOVERBAS,'||
         ' VW_TEMPRESAS_REF EMP,'||
         ' VW_VRH_EMP_TCOLCON_CAD COL,'||
         ' VRH_BASE_TVERBAS VERB,'||
         ' VW_VERBAS_REF_ATUAL VERREF,'||
         ' VW_VRHF_BASE_TEMPCALC EMPCALC,'||
         ' vrhf_emp_tfolhatomador Y'||
' where EMP.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODEMP = GRUPOVERBAS.BDCODEMP and COL.BDCODCOL = GRUPOVERBAS.BDCODCOL and'||
' VERB.BDCODVER = GRUPOVERBAS.BDCODVER and VERREF.BDCODVER = GRUPOVERBAS.BDCODVER and EMPCALC.BDCODEMP = GRUPOVERBAS.BDCODEMP and'||
' Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODCOL = GRUPOVERBAS.BDCODCOL and Y.bdreftomador = GRUPOVERBAS.bdreftomador and Y.bdordem = GRUPOVERBAS.bdordem';

  IF (pranomes IS NOT NULL) THEN
     wwhere = wwhere||' and GRUPOVERBAS.bdreftomador = '||:PRANOMES||' ';

  wsql = wsql || wwhere;

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = ' and ';
       wwhere = wwhere || ' GRUPOVERBAS.' || :PRCODEMP || ' ';
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere = '') THEN
          wwhere = ' and ';

       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || 'GRUPOVERBAS.'||:PRCODCOL || ' ';
     END

  wsql = wsql||wwhere;

  wsql = wsql||' group by GRUPOVERBAS.BDCODEMP,'||
                'EMP.BDNOMEMP,'||
                'GRUPOVERBAS.BDCODCOL,'||
                'COL.BDNOMCOL,'||
                'GRUPOVERBAS.BDCODVER,'||
                'GRUPOVERBAS.bdreftomador,'||
                'VERB.BDDESCVER,'||
                'VERB.BDDESCREDVER,'||
                'GRUPOVERBAS.bdignrefvft,'||
                'GRUPOVERBAS.bdignvalvft,'||
                'VERREF.BDPISVER,'||
                'VERREF.BDBASEHEVER,'||
                'VERREF.BDBASEMAIORVER,'||
                'VERREF.BDRAISVER,'||
                'VERREF.BDBASEGPSVER,'||
                'VERB.BDCLAVER,'||
                'EMPCALC.BDREFHOREMP';

  FOR EXECUTE STATEMENT wsql
  INTO
/*00*/    :BDCODEMP,
/*01*/    :BDNOMEMP,
/*02*/    :BDCODCOL,
/*03*/    :BDNOMCOL,
/*04*/    :BDCODVER,
/*05*/    :BDDESCVER,
/*06*/    :BDDESCREDVER,
/*07*/    :wsum,
/*08*/    :wmax,
/*09*/    :BDREFAUXV,
/*10*/    :BDPROVENTO,
/*11*/    :BDDESCONTO,
/*12*/    :BDTIPOCODVER,
/*13*/    :BDINSSVER,
/*14*/    :BDFGTSVER,
/*15*/    :BDIRVER,
/*16*/    :BDTIPOREFVER,
/*17*/    :BDBASESFVER,
/*18*/    :BDPISVER,
/*19*/    :BDBASEHEVER,
/*20*/    :BDBASEMAIORVER,
/*21*/    :BDRAISVER,
/*22*/    :BDBASEGPSVER,
/*23*/    :BDIGNREFV,
/*24*/    :BDIGNVALV,
/*25*/    :BDCLAVER,
/*26*/    :BDORDEMVER,
/*27*/    :BDREF,
/*28*/    :BDREFHOREMP,
/*29*/    :BDBFGTS,
/*30*/    :BDFGTS,
/*31*/    :BDFGTSCS,
/*32*/    :BDBFGTS13,
/*33*/    :BDFGTS13,
/*34*/    :BDFGTS13CS,
/*35*/    :BDMAIORREM,
/*36*/    :BDBINSS,
/*37*/    :BDALIQINSS,
/*38*/    :BDINSS,
/*39*/    :BDBIRRF,
/*40*/    :BDALIQIRRF,
/*41*/    :BDIRRF,
/*42*/    :BDBINSS13,
/*43*/    :BDALIQINSS13,
/*44*/    :BDINSS13,
/*45*/    :BDBIRRF13,
/*46*/    :BDALIQIRRF13,
/*47*/    :BDIRRF13,
/*48*/    :BDBSALFAM,
/*49*/    :BDSALFAM,
/*50*/    :BDBRAIS,
/*51*/    :BDSALBASE,
/*52*/    :BDDEP,
/*53*/    :bdbfgtsfe,
/*54*/    :BDFGTSFE,
/*55*/    :bdcredito,
/*56*/    :bddebito
  DO
    BEGIN
      IF (BDTIPOREFVER = 4) THEN
         BDREFV = wmax;
      ELSE
         BDREFV = wsum;
      SUSPEND;
    END

END
^


/* Restore proc. body: VRHF_SP_CONS_CALC_FOLHANORMALPR */
ALTER PROCEDURE VRHF_SP_CONS_CALC_FOLHANORMALPR(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDTIPOCODVER INTEGER,
BDORDEMTIPOCODVER INTEGER,
BDINSSVER INTEGER,
BDFGTSVER INTEGER,
BDIRVER INTEGER,
BDTIPOREFVER INTEGER,
BDBASESFVER INTEGER,
BDPISVER VARCHAR(5),
BDBASEHEVER VARCHAR(5),
BDBASEMAIORVER VARCHAR(5),
BDRAISVER VARCHAR(5),
BDBASEGPSVER VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDCLAVER VARCHAR(20),
BDORDEMVER INTEGER,
BDREF INTEGER,
BDREFHOREMP VARCHAR(5),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDEBITO NUMERIC(15,6),
BDCREDITO NUMERIC(15,6),
BDBFGTSFE NUMERIC(15,6),
BDFGTSFE NUMERIC(15,6),
BDDATARESCISAOPREV DATE)
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  /*
    Retorna os dados da tabela de verbas folha normal, junto com os dados do colaborador
    e empresa.
    Retorna tambem os parametros de cada verba lanCada.
    Retorna os Valores e bases de INSS, FGTS, IRRF, Dependentes, Maior remuneracao,
    Salario familia, etc.
    Salario base
  */

  wsql = 'select '||
           'GRUPOVERBAS.BDCODEMP, EMP.BDNOMEMP, GRUPOVERBAS.BDCODCOL, COL.BDNOMCOL, GRUPOVERBAS.BDCODVER, VERREF.BDDESCVER, VERREF.BDDESCREDVER, GRUPOVERBAS.BDREFVFN_SUM as BDREFVFNPR,'||
           'GRUPOVERBAS.BDREFAUXVFN_SUM as BDREFAUXVFNPR, case when (VERREF.BDTIPOCODVER = 0) then GRUPOVERBAS.BDVALVFN when (VERREF.BDTIPOCODVER <> 0) then 0 end BDPROVENTO,'||
           'case when (VERREF.BDTIPOCODVER > 0) then GRUPOVERBAS.BDVALVFN when (VERREF.BDTIPOCODVER <= 0) then 0 end BDDESCONTO, '||
           'VERREF.BDORDEMTIPOCODVER,'||
           'VERREF.BDINSSVER, VERREF.BDFGTSVER,'||
           'VERREF.BDIRVER, VERREF.BDTIPOREFVER, VERREF.BDBASESFVER, VERREF.BDPISVER, VERREF.BDBASEHEVER, VERREF.BDBASEMAIORVER, VERREF.BDRAISVER, VERREF.BDBASEGPSVER,'||
           'GRUPOVERBAS.BDIGNREFVFN as BDIGNREFVFNPR, GRUPOVERBAS.BDIGNVALVFN as BDIGNVALVFNPR, VERREF.BDCLAVER, VERREF.BDORDEMVER, VERREF.BDTIPOCODVER, '||
           'RESC.BDREFRESCISAOPREV BDREFFNPR,'||
           'EMPCALC.BDREFHOREMP, Y.BDBFGTS BDBFGTSFNPR, Y.BDFGTS BDFGTSFNPR, Y.BDFGTSCS BDFGTSCSFNPR, Y.BDBFGTS13 BDBFGTS13FNPR, Y.bdfgts13 BDFGTS13FNPR, Y.bdfgts13cs BDFGTS13CSFNPR,'||
           'Y.bdmaiorrem BDMAIORREMFNPR, Y.bdbinss BDBINSSFNPR, Y.bdaliqinss BDALIQINSSFNPR, Y.bdinss BDINSSFNPR,'||
           'Y.bdbirrf BDBIRRFFNPR, Y.bdaliqirrf BDALIQIRRFFNPR, Y.bdirrf BDIRRFFNPR, Y.bdinss13 BDBINSS13FNPR, Y.bdaliqinss13 BDALIQINSS13FNPR, Y.bdinss13 BDINSS13FNPR,'||
           'Y.bdbirrf13 BDBIRRF13FNPR, Y.bdaliqirrf13 BDALIQIRRF13FNPR, Y.bdirrf13 BDIRRF13FNPR, Y.bdbsalfam BDBSALFAMFNPR,'||
           'Y.bdsalfam BDSALFAMFNPR, Y.bdbrais BDBRAISFNPR, Y.bdsalbase BDSALBASEFNPR, Y.bddep BDDEPFNPR, Y.bdbfgtsfefol BDBFGTSFEFN, Y.bdfgtsfefol BDFGTSFEFN, RESC.BDDATARESCISAOPREV '||
         'from '||
           '(select * '||
            'from vrh_emp_trescisao_previa  ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wsql = wsql||
         ') RESC '||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COL on (COL.BDCODEMP = RESC.BDCODEMP and COL.BDCODCOL = RESC.BDCODCOL) '||
         'join vwrh_union_fnpr_ftpr_mes GRUPOVERBAS on (GRUPOVERBAS.BDCODEMP = RESC.BDCODEMP and GRUPOVERBAS.BDCODCOL = RESC.BDCODCOL) '||
         'join VWRH_UNION_FNPR_FTPR_MES_BASES Y on (Y.BDCODEMP = GRUPOVERBAS.BDCODEMP and Y.BDCODCOL = GRUPOVERBAS.BDCODCOL) '||
         'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = RESC.BDCODEMP) '||
         'join VW_TVERBAS_REF VERREF on (VERREF.BDCODVER = GRUPOVERBAS.BDCODVER) '||
         'left outer join VW_VRHF_BASE_TEMPCALC EMPCALC on (EMPCALC.BDCODEMP = RESC.BDCODEMP) ';


  /* Select principal */
  wsql = 'select BDCODEMP, '||
                'BDNOMEMP, '||
                'BDCODCOL, '||
                'BDNOMCOL, '||
                'BDCODVER, '||
                'BDDESCVER, '||
                'BDDESCREDVER, '||
                'BDREFVFNPR, '||
                'BDREFAUXVFNPR, '||
                'BDPROVENTO, '||
                'BDDESCONTO, '||
                'BDTIPOCODVER, '||
                'BDORDEMTIPOCODVER, '||
                'BDINSSVER, '||
                'BDFGTSVER, '||
                'BDIRVER, '||
                'BDTIPOREFVER, '||
                'BDBASESFVER, '||
                'BDPISVER, '||
                'BDBASEHEVER, '||
                'BDBASEMAIORVER, '||
                'BDRAISVER, '||
                'BDBASEGPSVER, '||
                'BDIGNREFVFNPR, '||
                'BDIGNVALVFNPR, '||
                'BDCLAVER, '||
                'BDORDEMVER, '||
                'BDREFFNPR, '||
                'BDREFHOREMP, '||
                'BDBFGTSFNPR, '||
                'BDFGTSFNPR, '||
                'BDFGTSCSFNPR, '||
                'BDBFGTS13FNPR, '||
                'BDFGTS13FNPR, '||
                'BDFGTS13CSFNPR, '||
                'BDMAIORREMFNPR, '||
                'BDBINSSFNPR, '||
                'BDALIQINSSFNPR, '||
                'BDINSSFNPR, '||
                'BDBIRRFFNPR, '||
                'BDALIQIRRFFNPR, '||
                'BDIRRFFNPR, '||
                'BDBINSS13FNPR, '||
                'BDALIQINSS13FNPR, '||
                'BDINSS13FNPR, '||
                'BDBIRRF13FNPR, '||
                'BDALIQIRRF13FNPR, '||
                'BDIRRF13FNPR, '||
                'BDBSALFAMFNPR, '||
                'BDSALFAMFNPR, '||
                'BDBRAISFNPR, '||
                'BDSALBASEFNPR, '||
                'BDDEPFNPR, '||
                'BDBFGTSFEFN, '||
                'BDFGTSFEFN, '||
                'BDDATARESCISAOPREV '||
         'from ('||
         wsql||
         ') ';

  wwhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = ' where ';
       wwhere = wwhere || ' ' || :PRCODEMP || ' ';
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere = '') THEN
          wwhere = ' where ';

       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and ';

       wwhere = wwhere || :PRCODCOL || ' ';
     END

  wsql = wsql||wwhere;

  EXECUTE PROCEDURE sp_seta_competencia(:pranomes);

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCODVER,
    :BDDESCVER,
    :BDDESCREDVER,
    :BDREFV,
    :BDREFAUXV,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDTIPOCODVER,
    :BDORDEMTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDCLAVER,
    :BDORDEMVER,
    :BDREF,
    :BDREFHOREMP,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :bdbfgtsfe, 
    :bdfgtsfe,
    :bddatarescisaoprev
  DO
  SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_CONS_CALCTERC */
create or alter procedure VRHF_SP_CONS_CALCTERC (
    PRCODEMP varchar(10000),
    PRCODSERV varchar(500),
    PRCODTER varchar(32700),
    PRDATAINI date,
    PRDATAFIM date,
    PRCODCC varchar(500),
    PRVERBASDEM smallint = 1)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(100),
    BDLOGEMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDCODCID integer,
    BDNOMCID varchar(100),
    BDCODTER integer,
    BDNOMTER varchar(100),
    BDCPFTER varchar(100),
    BDPISTER varchar(100),
    BDRGTER varchar(100),
    BDNROCONSPROTER varchar(100),
    BDCODSERV integer,
    BDDATASERV date,
    BDCODVER integer,
    BDDESCVER varchar(100),
    BDREFERENCIA numeric(18,6),
    BDDESCTIPOSERV varchar(500),
    BDPROVENTO numeric(18,6),
    BDDESCONTO numeric(18,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDNOMCTACC varchar(100),
    BDAPECTACC varchar(20),
    BDLOGRTER DM_LOGRADOURO,
    BDENDTER DM_BDENDERECO,
    BDNUMTER DM_NUMEND,
    BDCOMPLTER DM_BDCOMPENDERECO,
    BDBAITER varchar(60),
    BDCEPTER varchar(9),
    BDCODCIDTER integer,
    BDNOMCIDTER varchar(100),
    BDUFTER varchar(2),
    BDINFPROVENTO numeric(18,6),
    BDINFDESCONTO numeric(18,6),
    BDORDEM integer,
    BDCOMPETENCIA integer,
    BDOBSSERV varchar(500),
    BDEMAILTER varchar(200))
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
BEGIN
  wsql = 'select CALCTERC.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'TEMP.bdcnpjemp, '||
                'emp.bdlogremp, '||
                'emp.bdendemp, '||
                'emp.bdnumemp, '||
                'EMP.bdcodcid, ' ||
                'TCID.bdnomcid, ' ||
                'CALCTERC.BDCODTER, '||
                'TTERC.BDNOMETER BDNOMTER, '||
        'case ' ||
                    'when (char_length(RH.BDCPFMEITER) = 14) then RH.BDCPFMEITER ' ||
                'else TTERC.BDCGCTER ' ||
                'end BDCPFTER, '||
                'TTERC_DOC.bdpister, '||
                'TTERC_DOC.BDRGTER, '||
                'TTERC_DOC.BDNROCONSPROTER, '||
                'CALCTERC.BDCODSERV, '||
                'TSERVTERC.BDDATASERV, '||
                'CALCTERC.BDCODVER, '||
                'VERBAS.BDDESCVER, '||
                'CALCTERC.BDREFERENCIA, '||
                'case '||
                  'when TIPOSERV.BDDESCTIPOSERV is not null then TIPOSERV.BDDESCTIPOSERV '||
                  'else AM.bddescatvm end BDDESCTIPOSERV, '||
                'case when (VERBAS.BDTIPOCODVER = 0) then CALCTERC.BDVALOR '||
                     'when (VERBAS.BDTIPOCODVER <> 0) then 0 end BDPROVENTO, '||
                'case when (VERBAS.BDTIPOCODVER = 1) then CALCTERC.BDVALOR '||
                     'when (VERBAS.BDTIPOCODVER <> 1) then 0 end BDDESCONTO, '||
                'TSERVTERC.BDCODCENTRO, '||
                'TSERVTERC.BDCODTPCC, '||
                'case when (TCUSTOM.BDNOMETOM <> '''||''||''') then TCUSTOM.BDNOMETOM else TPCC.BDNOMCTA end BDNOMCTACC, '||
                'TPCC.BDAPECTA as BDAPECTACC, '||
                'TTERC.BDLOGRTER, '||
                'TTERC.BDENDTER, '||
                'TTERC.BDNUMTER, '||
                'TTERC.BDCOMPTER BDCOMPLTER, '||
                'TTERC.BDBAITER, '||
                'TTERC.BDCEPTER, '||
                'TTERC.BDCODCID as BDCODCIDTER, '||
                'TCIDTER.BDNOMCID as BDNOMCIDTER, '||
                'TUF.BDSIGLAUF as BDSIGLAUFTER, '||
                'case when (VERBAS.BDTIPOCODVER = 2) then CALCTERC.BDVALOR '||
                     'when (VERBAS.BDTIPOCODVER <> 2) then 0 end BDINFPROVENTO, '||
                'case when (VERBAS.BDTIPOCODVER = 3) then CALCTERC.BDVALOR '||
                     'when (VERBAS.BDTIPOCODVER <> 3) then 0 end BDINFDESCONTO, '||
                'case when VERBAS.BDTIPOCODVER = 0 then 0 '||
                     'when VERBAS.BDTIPOCODVER = 1 then 2 '||
                     'when VERBAS.BDTIPOCODVER = 2 then 1 '||
                     'when VERBAS.BDTIPOCODVER = 3 then 3 end BDORDEM, '||
                'TSERVTERC.BDREFSERV, '||
                'TSERVTERC.BDOBSSERV, ' ||
                'CASE ' ||
                ' WHEN ((TTERC.BDEMAILTER = '''||''||''') OR (TTERC.BDEMAILTER IS NULL)) THEN TTERC.BDEMAIL2TER ' ||
                ' ELSE TTERC.BDEMAILTER '||
                'END BDEMAIL ' ||
                'from ('||
                   'select CALCTERC.BDCODEMP,CALCTERC.BDCODTER,CALCTERC.BDCODSERV,CALCTERC.BDCODVER,CALCTERC.BDREFERENCIA,CALCTERC.BDVALOR from '||
                   'VRHF_BASE_ITEMS_CALCTERC CALCTERC ';

  wwhere = '';
  IF (NOT prcodemp IS NULL AND prcodemp <> '') THEN
     wwhere= wwhere||prcodemp;

  IF (NOT prcodserv IS NULL AND prcodserv <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
       wwhere= wwhere||' and '||prcodserv;
     END

  IF (NOT prcodter IS NULL AND prcodter <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
       wwhere= wwhere||' and '||prcodter;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  wsql = wsql||') CALCTERC '||
--                'join TEMPRESAS_REF EMP '||
--                'on (CAST(EMP.BDCODEMP AS VARCHAR(6)) || CAST(EMP.BDREFEMP as VARCHAR(6)) in '||
--                      '(select CAST(X.BDCODEMP AS VARCHAR(6)) || CAST(Max(X.BDREFEMP) as VARCHAR(6)) '||
--                       'from TEMPRESAS_REF X '||
--                       'where X.BDCODEMP = CALCTERC.BDCODEMP and X.BDCODEMP = EMP.BDCODEMP '||
--                       'group by X.BDCODEMP '||
--                      ') '||
--              ') '||
         'join VRH_BASE_TSERVTERC TSERVTERC on (TSERVTERC.BDCODEMP = CALCTERC.BDCODEMP and TSERVTERC.BDCODTER = CALCTERC.BDCODTER and TSERVTERC.BDCODSERV = CALCTERC.BDCODSERV) '||
         'join TEmpresas TEMP on (CALCTERC.bdcodemp = TEmp.bdcodemp) ' ||
         'join TEMPRESAS_REF EMP on (EMP.BDCODEMP = CALCTERC.BDCODEMP and EMP.BDREFEMP = (select first 1 BDREFEMP from TEMPRESAS_REF where BDCODEMP = EMP.BDCODEMP order by BDREFEMP desc)) '||
         'left outer join TTERCEIRO_RH RH on (RH.BDCODTER = CALCTERC.BDCODTER) ' ||
         'left outer join TCIDADE TCID on (TCID.BDCODCID = Emp.BDCODCID) ' ||
         'left outer join VRH_BASE_TTERC_DOCREF TTERC_DOC on (TTERC_DOC.BDCODTER = CALCTERC.BDCODTER and TTERC_DOC.BDREFTERC = (select first 1 BDREFTERC from VRH_BASE_TTERC_DOCREF where BDCODTER = TTERC_DOC.BDCODTER order by TTERC_DOC.BDREFTERC desc)) '||
         'join VW_TVERBAS_ref VERBAS on (VERBAS.BDCODVER = CALCTERC.BDCODVER) '||
         'join TTERCEIRO_REF TTERC on (TTERC.BDCODTER = CALCTERC.BDCODTER and TTERC.BDREFEMP = (select first 1 BDREFEMP from TTERCEIRO_REF where BDCODTER = TTERC.BDCODTER order by BDREFEMP desc)) '||
         'left outer join TTIPOSERVICO TIPOSERV on (TIPOSERV.BDCODTIPOSERV = TSERVTERC.BDCODTIPOSERV) '||
         'left outer join VW_TATVMUNICIPAL AM on (AM.BDCODATVM = TSERVTERC.BDCODATVM and AM.bdcodcid = TSERVTERC.bdcodcid) '||
         'left outer join CENTROS_TPCC TPCC on (TPCC.BDCODCENTRO = TSERVTERC.BDCODCENTRO and TPCC.BDCODTPCC = TSERVTERC.BDCODTPCC) '||
         'left outer join VRH_BASE_TCUSTOM TCUSTOM on (TCUSTOM.BDCODCENTRO = TSERVTERC.BDCODCENTRO and TCUSTOM.BDCODTPCC = TSERVTERC.BDCODTPCC) '||
         'left outer join TCIDADE TCIDTER on (TCIDTER.BDCODCID = TTERC.BDCODCID) '||
         'left outer join TUF TUF on (TUF.BDCODUF = TCIDTER.BDCODUF) ';

  wwhere = '';

--  if (:PRCODEMP is not null) then
--     begin
--       wwhere = ' and ';
--       wwhere = wwhere || '  ' || :PRCODEMP || ' ';
--     end

--  if (:prcodserv is not null) then
--     begin
--       if (wwhere = '') then
--          wwhere = ' and ';

--       if (wwhere <> '') then
--          wwhere = wwhere || ' and ';

--       wwhere = wwhere || ' ' || :prcodserv || ' ';
--     end


--  if (:prcodter is not null) then
--     begin
--       if (wwhere = '') then
--          wwhere = ' and ';

--       if (wwhere <> '') then
--          wwhere = wwhere || ' and ';

--       wwhere = wwhere || ' ' || :prcodter || ' ';
--     end


  IF (:prdataini IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere || ' TSERVTERC.BDDATASERV >= '''|| prdataini || '''' || ' ';
     END


  IF (:prdatafim IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere || ' TSERVTERC.BDDATASERV <= '''|| prdatafim || '''' || ' ';
     END

  IF (coalesce(prverbasdem, 0) = 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere || ' COALESCE(VERBAS.BDTIPOCODVER, 0) in (0,1) ';
     END

  IF (:prcodcc IS NOT NULL and :prcodcc > 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
                                                                              
       wwhere = wwhere || ' TSERVTERC.BDCODCENTRO = EMP.BDCODCENTROS and TSERVTERC.BDCODTPCC = '''|| prcodcc || '''' || ' ';
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  wSql = wsql|| 'order by bdcodemp, bdcodter, bdcodserv, BDORDEM ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :bdnomemp,
    :bdcnpjemp,
    :bdlogemp,
    :bdendemp,
    :bdnumemp,
    :bdcodcid,
    :bdnomcid,
    :bdcodter,
    :bdnomter,
    :bdcpfter,
    :bdpister,
    :bdrgter,
    :bdnroconsproter,
    :bdcodserv,
    :bddataserv,
    :bdcodver,
    :bddescver,
    :bdreferencia,
    :bddesctiposerv,
    :bdprovento,
    :bddesconto,
    :bdcodcentro,
    :bdcodtpcc,
    :bdnomctacc,
    :bdapectacc,
    :bdlogrter,
    :bdendter,
    :bdnumter,
    :bdcomplter,
    :bdbaiter,
    :bdcepter,
    :bdcodcidter,
    :bdnomcidter,
    :bdufter,
    :bdinfprovento,
    :bdinfdesconto,
    :bdordem,
    :bdcompetencia,
    :bdobsserv,
 :BDEMAILTER
  DO
  SUSPEND;
END^

/* Restore proc. body: VRHF_SP_CONS_COMP13SALARIO */
ALTER PROCEDURE VRHF_SP_CONS_COMP13SALARIO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFC13 INTEGER,
BDBASEIRC13 NUMERIC(15,6),
BDBASEINSSC13 NUMERIC(15,6),
BDBASEFGTSC13 NUMERIC(15,6),
BDFGTSC13 NUMERIC(15,6),
BDFGTSCSC13 NUMERIC(15,6),
BDPERCIRC13 NUMERIC(15,6),
BDVALORIRC13 NUMERIC(15,6),
BDPERCINSSC13 NUMERIC(15,6),
BDVALORINSSC13 NUMERIC(15,6))
 AS
DECLARE VARIABLE wsql VARCHAR(32700);
DECLARE VARIABLE wwhere VARCHAR(32700);
BEGIN
  wsql = 'select BDCODEMP, '||
                'BDCODCOL, '||
                'BDREFC13, '||
                'coalesce(sum(BDBASEIRC13), 0), '||
                'coalesce(sum(BDBASEINSSC13), 0), '||
                'coalesce(sum(BDBASEFGTSC13), 0), '||
                'coalesce(sum(BDFGTSC13), 0), '||
                'coalesce(sum(BDFGTSCSC13), 0), '||
                'coalesce(sum(BDPERCIRC13), 0), '||
                'coalesce(sum(BDVALORIRC13), 0), '||
                'coalesce(sum(BDPERCINSSC13), 0), '||
                'coalesce(sum(BDVALORINSSC13), 0) '||
         'from VRHF_EMP_TC13SAL ';

  wsql = wsql||' where ';
  wwhere = '';


  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||:PRCODEMP;
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODCOL;
     END

  IF (:PRANOMES IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDREFC13 = '||:PRANOMES;
     END

  wsql = wsql||wwhere;

  wsql = wsql||'group by BDCODEMP, '||
                        'BDCODCOL, '||
                        'BDREFC13 ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFC13,
    :BDBASEIRC13,
    :BDBASEINSSC13,
    :BDBASEFGTSC13,
    :BDFGTSC13,
    :BDFGTSCSC13,
    :BDPERCIRC13,
    :BDVALORIRC13,
    :BDPERCINSSC13,
    :BDVALORINSSC13
  DO

  SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_CONS_FOLHANORMAL */
ALTER PROCEDURE VRHF_SP_CONS_FOLHANORMAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFN INTEGER,
BDBFGTSFN NUMERIC(15,6),
BDFGTSFN NUMERIC(15,6),
BDFGTSCSFN NUMERIC(15,6),
BDBFGTS13FN NUMERIC(15,6),
BDFGTS13FN NUMERIC(15,6),
BDFGTS13CSFN NUMERIC(15,6),
BDMAIORREMFN NUMERIC(15,6),
BDBINSSFN NUMERIC(15,6),
BDALIQINSSFN NUMERIC(15,6),
BDINSSFN NUMERIC(15,6),
BDBIRRFFN NUMERIC(15,6),
BDALIQIRRFFN NUMERIC(15,6),
BDIRRFFN NUMERIC(15,6),
BDBINSS13FN NUMERIC(15,6),
BDALIQINSS13FN NUMERIC(15,6),
BDINSS13FN NUMERIC(15,6),
BDBIRRF13FN NUMERIC(15,6),
BDALIQIRRF13FN NUMERIC(15,6),
BDIRRF13FN NUMERIC(15,6),
BDBSALFAMFN NUMERIC(15,6),
BDSALFAMFN NUMERIC(15,6),
BDBRAISFN NUMERIC(15,6),
BDSALBASEFN NUMERIC(15,6),
BDDEPFN NUMERIC(15,6),
BDCREDITOFN NUMERIC(15,6),
BDDEBITOFN NUMERIC(15,6),
BDBFGTSFEFN NUMERIC(15,6),
BDFGTSFEFN NUMERIC(15,6))
 AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  wsql = 'select BDCODEMP, '||
                'BDCODCOL, '||
                'BDREFFN, '||
                'coalesce(BDSALBASEFN, 0), '||
                'coalesce(sum(BDBFGTSFN), 0), '||
                'coalesce(sum(BDFGTSFN), 0), '||
                'coalesce(sum(BDFGTSCSFN), 0), '||
                'coalesce(sum(BDBFGTS13FN), 0), '||
                'coalesce(sum(BDFGTS13FN), 0), '||
                'coalesce(sum(BDFGTS13CSFN), 0), '||
                'coalesce(sum(BDMAIORREMFN), 0), '||
                'coalesce(sum(BDBINSSFN), 0), '||
                'coalesce(sum(BDALIQINSSFN), 0), '||
                'coalesce(sum(BDINSSFN), 0), '||
                'coalesce(sum(BDBIRRFFN), 0), '||
                'coalesce(sum(BDALIQIRRFFN), 0), '||
                'coalesce(sum(BDIRRFFN), 0), '||
                'coalesce(sum(BDBINSS13FN), 0), '||
                'coalesce(sum(BDALIQINSS13FN), 0), '||
                'coalesce(sum(BDINSS13FN), 0), '||
                'coalesce(sum(BDBIRRF13FN), 0), '||
                'coalesce(sum(BDALIQIRRF13FN), 0), '||
                'coalesce(sum(BDIRRF13FN), 0), '||
                'coalesce(sum(BDBSALFAMFN), 0), '||
                'coalesce(sum(BDSALFAMFN), 0), '||
                'coalesce(sum(BDBRAISFN), 0), '||
                'coalesce(sum(BDDEPFN), 0), '||
                'coalesce(sum(BDBFGTSFEFN), 0), '||
                'coalesce(sum(BDFGTSFEFN), 0), '||
                'coalesce(sum(BDCREDITOFN), 0), '||
                'coalesce(sum(BDDEBITOFN), 0) '||
         'from VRHF_EMP_TFOLHANORMAL ';

  wsql = wsql||' where ';
  wwhere = '';


  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||:PRCODEMP;
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODCOL;
     END

  IF (:PRANOMES IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'BDREFFN <= '||:PRANOMES;
     END

  wsql = wsql||wwhere;

  wsql = wsql||'group by BDCODEMP, '||
                        'BDCODCOL, '||
                        'BDREFFN, '||
                        'BDSALBASEFN ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFFN,
    :BDSALBASEFN,
    :BDBFGTSFN,
    :BDFGTSFN,
    :BDFGTSCSFN,
    :BDBFGTS13FN,
    :BDFGTS13FN,
    :BDFGTS13CSFN,
    :BDMAIORREMFN,
    :BDBINSSFN,
    :BDALIQINSSFN,
    :BDINSSFN,
    :BDBIRRFFN,
    :BDALIQIRRFFN,
    :BDIRRFFN,
    :BDBINSS13FN,
    :BDALIQINSS13FN,
    :BDINSS13FN,
    :BDBIRRF13FN,
    :BDALIQIRRF13FN,
    :BDIRRF13FN,
    :BDBSALFAMFN,
    :BDSALFAMFN,
    :BDBRAISFN,
    :BDDEPFN,
    :BDBFGTSFEFN,
    :BDFGTSFEFN,
    :bdcreditofn,
    :bddebitofn
  DO

  SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_CONS_IR_TERCEIROS */
create or alter procedure VRHF_SP_CONS_IR_TERCEIROS (
    PRCODEMP varchar(10000),
    PRCODTER varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false,
    PRFICHADEC smallint = 0)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP VARCHAR(18),
    BDCODTER integer,
    BDNOMTER varchar(100),
    BDCODSERV integer,
    BDDATASERV date,
    BDDATAPAGSERV date,
    BDREF varchar(6),
    BDBASEIR numeric(15,6),
    BDVALORIR numeric(15,6),
    BDVALORDEP numeric(15,6),
    BDBASEINSS numeric(15,6),
    BDVALORINSS numeric(15,6),
    BDCPFTER varchar(14),
    BDCODRECOF DM_CODRECOF,
    BDBASEIRTOT numeric(18,6),
    BDDESCIRTOT varchar(50),
    BDTIPO integer,
    BDINCIDESOCIAL integer,
    BDBASEIRBRUTA numeric(15,6),
    BDREFIRRFESOCIAL integer)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WBDCATEGORIATER integer;
declare variable WBDPERTRANSPIRTER numeric(15,2);
declare variable WQTDVERBAS integer;
declare variable WREM numeric(18,6);
declare variable WCODVER integer;
declare variable WTOTISENTO numeric(18,6);
declare variable WTERCMEI varchar(5);
declare variable WREFPAGSERV integer;
declare variable WVALORDESCSIMPL numeric(18,6);
declare variable WUTILIZADESCONTOSIPLIFICADO varchar(5);
declare variable WBASEIRBRUTA numeric(18,6);
declare variable WSQL2 varchar(32700);
declare variable WAUX varchar(32700);
declare variable WEMPATU integer;
declare variable WTERATU integer;
declare variable WREFPAGATU integer;
declare variable WTIPOINFO integer;
declare variable WTIPOINFOATU integer;
declare variable WTIPODEDUCAOFOLHA integer;
declare variable WVALORDIFDESCSIMPL numeric(18,2);
declare variable WSQLAUX varchar(3000);
declare variable WTIPODEDUCAOFOLHAATU integer;
declare variable WVALORDIFDESCSIMPLATU numeric(18,2);
declare variable WVALORDESCSIMPLATU numeric(18,2);
declare variable WVALORDEP numeric(18,2);
declare variable WVALORINSS numeric(18,2);
declare variable WBASEIR numeric(18,2);
declare variable WCODSERVATU integer;
declare variable WRENDISENTO varchar(5);
declare variable WINCIDESOCIAL integer;
declare variable WCODINCIDIRRF integer;
declare variable WUSARTMP_TER_SELECT smallint;
declare variable WREFIRRFESOCIALATU integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WUSARTMP_EMP_SELECT integer;
declare variable WTABRUBR varchar(8);
declare variable WPERSONALIZACAO integer;
declare variable WGRAVARUBRICA integer;
declare variable WCPFCOL varchar(18);
declare variable WCODEMPORD integer;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
begin
  PRFICHADEC = coalesce(PRFICHADEC, 0);
  execute procedure SP_SETA_COMPETENCIA(:PRREFFIM, null, null);
  WUSARTMP_TER_SELECT = 0;

  WUSARTMP_EMP_SELECT = 0;
  if (upper(PRCODEMP) = 'TMP_EMPRESAS_SELECT') then
    WUSARTMP_EMP_SELECT = 1;

  if (PRCODTER = 'TEMP_FILTRO_COLCON_REL') then
    WUSARTMP_TER_SELECT = 1;

  WTABRUBR = NULL;
  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;
  SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBR;

  if (PRATUALIZAINFODESCSIMPLE = true) then
  begin
    WSQLAUX = 'DELETE FROM VRHF_TINFO_DESC_SIMPLES WHERE BDSESSAO = ' || current_connection || ' and BDAUTONOMO = 1';
    execute statement WSQLAUX;
  end

  --  wsql = 'select SERVICO.bdcodemp, empresas.bdnomemp , SERVICO.bdcodter, tterc.bdnometer, SERVICO.BDCODSERV, SERVICO.bddataserv , SERVICO.BDDATAPAGSERV, SERVICO.bdbaseir, ' ||
  WSQL = 'select SERVICO.BDREFIRRFESOCIAL, WTIPOINFO, SERVICO.bdcodemp, SERVICO.bdcodter, SERVICO.BDCODSERV, SERVICO.bddataserv , SERVICO.BDDATAPAGSERV, SERVICO.bdbaseir, ' || ' SERVICO.bdvalorir, SERVICO.bdvalordep , SERVICO.bdbaseinss , SERVICO.bdvalorinss, case when  char_length(TTERC_DOC.BDCPFMEITER) = 14 then TTERC_DOC.BDCPFMEITER else TERC.BDCGCTER end BDCPFTER,' || ' SERVICO.BDBASEIRTOT, ' || ' case when char_length(TTERC_DOC.BDCPFMEITER) = 14 then ' || '''TRUE''' || ' else ' || '''FALSE''' || ' end BDTERCMEI, SERVICO.BDREFPAGSERV, SERVICO.BDTIPODEDUCAOFOLHA, SERVICO.BDVALORDESCONTOSIMPLIFICADO, SERVICO.BDVALORDIFERENCADEDUCOES, SERVICO.BDBASEIRBRUTA ' || 'from (';

  WWHERE = '';
  WAUX = '';
  if (PRIRRFESOCIAL = true) then
  begin
    WSQL = WSQL || 'select calc_terc.BDREFIRRFESOCIAL, 1 WTIPOINFO, ' || 'calc_terc.bdcodemp, calc_terc.bdcodter, calc_terc.BDCODSERV, Serv.bddataserv , calc_terc.BDDATAIRRFESOCIAL BDDATAPAGSERV, calc_terc.bdbaseir , calc_terc.bdvalorir, ' || 'calc_terc.bdvalordep , calc_terc.bdbaseinss , calc_terc.bdvalorinss, calc_terc.BDBASEIRTOT, Serv.BDREFPAGSERV, CALC_TERC.BDTIPODEDUCAOFOLHA, CALC_TERC.BDVALORDESCONTOSIMPLIFICADO, CALC_TERC.BDVALORDIFERENCADEDUCOES, calc_terc.bdbaseir BDBASEIRBRUTA ' || 'from VRH_BASE_TSERVTERC SERV ' || 'join VRHF_BASE_CALC_TERC calc_terc on (SERV.BDCODEMP = calc_terc.BDCODEMP and SERV.BDCODTER = calc_terc.BDCODTER and SERV.BDCODSERV = calc_terc.BDCODSERV) ';

    if (WUSARTMP_TER_SELECT = 1) then
      WSQL = WSQL || ' join TEMP_FILTRO_COLCON_REL FIL on (serv.bdcodemp=fil.bdcodemp and serv.bdcodter=fil.bdcodter) ';

    if (:PRREFINI is not null) then
      WWHERE = WWHERE || ' calc_terc.BDREFIRRFESOCIAL >= ' || PRREFINI || ' ';

    if (:PRREFFIM is not null) then
    begin
      if (WWHERE <> '') then
        WWHERE = WWHERE || ' and ';

      WWHERE = WWHERE || 'calc_terc.BDREFIRRFESOCIAL <= ' || PRREFFIM || ' ';
    end
  end
  else
  begin
    WSQL = WSQL || 'select calc_terc.BDREFIRRFESOCIAL, 1 WTIPOINFO, ' || 'calc_terc.bdcodemp, calc_terc.bdcodter, calc_terc.BDCODSERV, Serv.bddataserv , Serv.BDDATAPAGSERV, calc_terc.bdbaseir , calc_terc.bdvalorir, ' || 'calc_terc.bdvalordep , calc_terc.bdbaseinss , calc_terc.bdvalorinss, calc_terc.BDBASEIRTOT, Serv.BDREFPAGSERV, CALC_TERC.BDTIPODEDUCAOFOLHA, CALC_TERC.BDVALORDESCONTOSIMPLIFICADO, CALC_TERC.BDVALORDIFERENCADEDUCOES, calc_terc.bdbaseir BDBASEIRBRUTA ' || 'from VRH_BASE_TSERVTERC SERV ' || 'join VRHF_BASE_CALC_TERC calc_terc on (SERV.BDCODEMP = calc_terc.BDCODEMP and SERV.BDCODTER = calc_terc.BDCODTER and SERV.BDCODSERV = calc_terc.BDCODSERV) ';
    if (WUSARTMP_EMP_SELECT = 1) then
      WSQL = WSQL || ' JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = calc_terc.BDCODEMP) ';

    if (WUSARTMP_TER_SELECT = 1) then
      WSQL = WSQL || ' join TEMP_FILTRO_COLCON_REL FIL on (serv.bdcodemp=fil.bdcodemp and serv.bdcodter=fil.bdcodter) ';

    if (:PRREFINI is not null) then
      WWHERE = WWHERE || ' Serv.BDREFPAGSERV >= ' || PRREFINI || ' ';

    if (:PRREFFIM is not null) then
    begin
      if (WWHERE <> '') then
        WWHERE = WWHERE || ' and ';

      WWHERE = WWHERE || 'Serv.BDREFPAGSERV <= ' || PRREFFIM || ' ';
    end
  end

  if ((:PRCODEMP is not null) and
      (:PRCODEMP <> '') and
      (WUSARTMP_EMP_SELECT = 0)) then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';

    WWHERE = WWHERE || :PRCODEMP;
  end

  if ((:PRCODTER is not null) and
      (:PRCODTER <> '') and
      (WUSARTMP_TER_SELECT = 0)) then
  begin
    if (WWHERE <> '') then
      WWHERE = WWHERE || ' and ';

    WWHERE = WWHERE || :PRCODTER;
  end

  if (WWHERE <> '') then
    WWHERE = ' where ' || WWHERE;

  WSQL = WSQL || WWHERE || WAUX;

  WSQL = WSQL || ' union all ';

  WSQL = WSQL || 'select SERV.BDREFPAGSERV BDREFIRRFESOCIAL, 2 WTIPOINFO, ' || 'calc_terc.bdcodemp, calc_terc.bdcodter, calc_terc.bdcodserv, SERV.bddataserv, SERV.bddatapagserv, ' || 'calc_terc.bdbaseir - calc_terc.bdvalordep - calc_terc.bdvalorinss, calc_terc.bdvalorir, calc_terc.bdvalordep, calc_terc.bdbaseinss, calc_terc.bdvalorinss, ' || 'calc_terc.BDBASEIRTOT, Serv.BDREFPAGSERV, 0 as BDTIPODEDUCAOFOLHA, 0 as BDVALORDESCONTOSIMPLIFICADO, 0 as BDVALORDESCONTOSIMPLIFICADO, calc_terc.bdbaseir BDBASEIRBRUTA ' || 'from VRH_BASE_TSERVTERC SERV ' || 'join vrhf_emp_tfichairrf_terc calc_terc on (SERV.BDCODEMP = calc_terc.BDCODEMP and SERV.BDCODTER = calc_terc.BDCODTER and SERV.BDCODSERV = calc_terc.BDCODSERV) ' || 'left join VRHF_BASE_CALC_TERC CALC on (SERV.BDCODEMP = CALC.BDCODEMP and SERV.BDCODTER = CALC.BDCODTER and SERV.BDCODSERV = CALC.BDCODSERV) ';

  if (WUSARTMP_TER_SELECT = 1) then
    WSQL = WSQL || ' join TEMP_FILTRO_COLCON_REL FIL on (serv.bdcodemp=fil.bdcodemp and serv.bdcodter=fil.bdcodter) ';

  if (WWHERE <> '') then
    WWHERE = WWHERE || ' and ';
  else
    WWHERE = ' where ';

  WWHERE = WWHERE || ' CALC.BDCODEMP IS NULL ';

  WWHERE = replace(upper(WWHERE), upper('calc_terc.BDREFIRRFESOCIAL'), upper('Serv.BDREFPAGSERV'));

  if (PRIRRFESOCIAL = true) then
  /* 190084 LuizCovre 04/01/2024 */
  begin
    if (:PRREFINI is not null) then
      WWHERE = WWHERE || ' and Serv.BDREFPAGSERV >= ' || PRREFINI || ' ';

    if (:PRREFFIM is not null) then
    begin
      if (WWHERE <> '') then
        WWHERE = WWHERE || ' and ';

      WWHERE = WWHERE || 'Serv.BDREFPAGSERV <= ' || PRREFFIM || ' ';
    end
  end

  WSQL = WSQL || WWHERE;
  WSQL = WSQL || ') SERVICO ';

  WSQL = WSQL || 'left outer join TTERCEIRO TERC ON (TERC.BDCODTER = SERVICO.BDCODTER) ';
  WSQL = WSQL || --         'join VRH_BASE_TTERC TTERC on (TTERC.bdcodter = SERVICO.BDCODTER) '||

  /*         'join (select X.* from tterceiro_ref X '||
           'join '||
             '( '||
               'select serv.BDCODTER, MAX(serv.BDREFEMP) BDREFEMP from tterceiro_ref serv where serv.BDREFEMP <= '||
                      'COALESCE ( '||
                      '(SELECT MAX(rf2.bdrefemp) FROM TTERCEIRO_REF rf2 WHERE rf2.BDREFEMP <= (SELECT TRIM(rdb$get_context(''USER_SESSION'', ''W_ANOMES'')) FROM rdb$database) AND rf2.bdcodter = SERV.BDCODTER), '||
                      '(SELECT MIN(rf2.bdrefemp) FROM TTERCEIRO_REF rf2 WHERE rf2.bdcodter = SERV.BDCODTER) '||
                      ') ';

  if (prcodter is not null and prcodter <> '') then
     wsql = wsql||' and '||prcodter||' ';

  wsql = wsql||
               'group by serv.BDCODTER '||
             ') Y on (Y.BDCODTER = X.BDCODTER and Y.BDREFEMP = X.BDREFEMP) '||
         ') TTERC on (TTERC.BDCODTER = SERVICO.BDCODTER) '|| */
  --         'left outer join VW_VRH_BASE_TTERC_DOC TTERC_DOC on (TTERC_DOC.bdcodter = SERVICO.BDCODTER) '||
  --         'left outer join VW_VRH_BASE_TTERC_VINC TTERC_VINC on (TTERC_VINC.bdcodcol = SERVICO.BDCODTER) '||
  'left outer join TTERCEIRO_RH TTERC_DOC on (TTERC_DOC.bdcodter = SERVICO.BDCODTER) ' || --         'left outer join (select BDCODTER,max(BDREFEMP)BDREFEMP from TTERCEIRO_REF a where A.BDREFEMP<='||prreffim||' group by A.BDCODTER  )TERCMAX  on TERCMAX.BDCODTER= SERVICO.BDCODTER '||
  --         'left outer join  TTERCEIRO_REF TTERC_REF ON (TTERC_REF.bdcodter=TERCMAX.bdcodter and TTERC_REF.BDREFEMP= TERCMAX.BDREFEMP) '||
  --         'left outer join VRH_BASE_TCLASSE CLASSE on (CLASSE.BDCODCLA = TTERC_VINC.BDCODCLA) '||
  --         'left outer join TCODREC CODREC on (CODREC.BDCODREC = CLASSE.BDCODREC) '||
  --         'left outer join vw_tempresas_ref empresas on (empresas.bdcodemp = SERVICO.bdcodemp ) '||
  ' where (STRLEN(TERC.BDCGCTER) = 14 or STRLEN(TTERC_DOC.BDCPFMEITER) = 14)' || 'order by SERVICO.bdcodemp, SERVICO.bdcodter, SERVICO.BDDATAPAGSERV ';

  WEMPATU = 0;
  WTERATU = 0;
  WREFPAGATU = 0;
  WTIPOINFOATU = 0;
  WCODSERVATU = 0;
  WINCIDESOCIAL = 0;
  WCODINCIDIRRF = 0;
  WREFIRRFESOCIALATU = -1;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;


  for execute statement WSQL
          into WREFIRRFESOCIAL, :WTIPOINFO, :BDCODEMP, :BDCODTER,
          --    :bdnomter,
          :BDCODSERV, :BDDATASERV, :BDDATAPAGSERV, :BDBASEIR, :BDVALORIR, :BDVALORDEP, :BDBASEINSS, :BDVALORINSS,
          :BDCPFTER, :BDBASEIRTOT, :WTERCMEI, :WREFPAGSERV, :WTIPODEDUCAOFOLHA, :WVALORDESCSIMPL, :WVALORDIFDESCSIMPL, :BDBASEIRBRUTA
  do
  begin
    BDDESCIRTOT = '';/*Solicitação 161694 - André Cursino*/

    BDTIPO = WTIPOINFO;

    if ((PRATUALIZAINFODESCSIMPLE = true) and
        (((WEMPATU > 0) and
        (WEMPATU <> BDCODEMP)) or ((WTERATU > 0) and
        (WTERATU <> BDCODTER)) or ((WCODSERVATU > 0) and
        (WCODSERVATU <> BDCODSERV)))) then
    begin
      WSQLAUX = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, ' || ' BDPREVOUTRASFOLHAS, BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) ' || ' values (' || current_connection || ', ' || WEMPATU || ', ' || WTERATU || ', ' || WREFPAGATU || ', 1, 0, ' || coalesce(WVALORDEP, 0) || ', 0, ' || coalesce(WVALORINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(WBASEIR, 0) || ')';

      execute statement WSQLAUX;
    end

    WCODSERVATU = BDCODSERV;
    if (WREFIRRFESOCIALATU = -1) then
      WREFIRRFESOCIALATU = WREFIRRFESOCIAL;
    BDREFIRRFESOCIAL = WREFIRRFESOCIAL;

    if ((WEMPATU <> BDCODEMP) or (WREFPAGATU <> WREFPAGSERV)) then
    begin
      WTERATU = 0;
      WEMPATU = BDCODEMP;
      WREFPAGATU = WREFPAGSERV;
      WTIPODEDUCAOFOLHAATU = WTIPODEDUCAOFOLHA;
      WVALORDESCSIMPLATU = WVALORDESCSIMPL;
      WVALORDIFDESCSIMPLATU = WVALORDIFDESCSIMPL;
      select first 1 e.BDCNPJEMP, r.BDNOMEMP
      from TEMPRESAS e
      join TEMPRESAS_REF r on e.BDCODEMP = r.bdcodemp
      where e.BDCODEMP = :BDCODEMP and
            r.BDREFEMP = --<= :wrefpagserv /*Sol.195190 - Nathan de Faria - 07/02/2024*/
            coalesce((select first 1 B.BDREFEMP
                      from TEMPRESAS_REF B
                      where B.BDCODEMP = :BDCODEMP and
                            B.BDREFEMP <= :WREFPAGSERV
                      order by BDREFEMP desc), (select first 1 B.BDREFEMP
                                                from TEMPRESAS_REF B
                                                where B.BDCODEMP = :BDCODEMP and
                                                      B.BDREFEMP > :WREFPAGSERV
                                                order by BDREFEMP))
      order by BDREFEMP desc
      into :BDCNPJEMP, :BDNOMEMP;
    end

    if ((WTERATU <> BDCODTER) or (WTIPOINFOATU <> WTIPOINFO)) then
    begin
      select first 1 BDCATEGORIATER, BDPERTRANSPIRTER
      from VRHF_BASE_TTERC_FGTSGPS
      where BDCODTER = :BDCODTER and
            BDREFTERC = --<= :wrefpagserv /*Sol.195190 - Nathan de Faria - 07/02/2024*/
            coalesce((select first 1 B.BDREFTERC
                      from VRHF_BASE_TTERC_FGTSGPS B
                      where B.BDCODTER = :BDCODTER and
                            B.BDREFTERC <= :WREFPAGSERV
                      order by BDREFTERC desc), (select first 1 B.BDREFTERC
                                                 from VRHF_BASE_TTERC_FGTSGPS B
                                                 where B.BDCODTER = :BDCODTER and
                                                       B.BDREFTERC > :WREFPAGSERV
                                                 order by BDREFTERC))

      order by BDREFTERC desc
      into :WBDCATEGORIATER, :WBDPERTRANSPIRTER;

      WBDCATEGORIATER = coalesce(WBDCATEGORIATER, 0);
      WBDPERTRANSPIRTER = coalesce(WBDPERTRANSPIRTER, 0);

      select first 1 BDNOMETER, BDUTILIZADESCSIMPLIFICADO
      from TTERCEIRO_REF
      where BDCODTER = :BDCODTER and
            BDREFEMP = --<= :wrefpagserv  /*Sol.195190 - Nathan de Faria - 07/02/2024*/
            coalesce((select first 1 B.BDREFEMP
                      from TTERCEIRO_REF B
                      where B.BDCODTER = :BDCODTER and
                            B.BDREFEMP <= :WREFPAGSERV
                      order by BDREFEMP desc), (select first 1 B.BDREFEMP
                                                from TTERCEIRO_REF B
                                                where B.BDCODTER = :BDCODTER and
                                                      B.BDREFEMP > :WREFPAGSERV
                                                order by BDREFEMP))

      order by BDREFEMP desc
      into :BDNOMTER, :WUTILIZADESCONTOSIPLIFICADO;

      BDCODRECOF = null;
      select first 1 REC.BDCODRECOF, VINC.BDCODCLA
      from VRH_BASE_TTERC_VINC VINC
      join VRH_BASE_TCLASSE CLASSE on (CLASSE.BDCODCLA = VINC.BDCODCLA)
      join TCODREC REC on (REC.BDCODREC = CLASSE.BDCODREC)
      where VINC.BDCODTER = :BDCODTER and
            VINC.BDREFTERC = --<= :wrefpagserv  /*Sol.195190 - Nathan de Faria - 07/02/2024*/
            coalesce((select first 1 B.BDREFTERC
                      from VRH_BASE_TTERC_VINC B
                      where B.BDCODTER = :BDCODTER and
                            B.BDREFTERC <= :WREFPAGSERV
                      order by BDREFTERC desc), (select first 1 B.BDREFTERC
                                                 from VRH_BASE_TTERC_VINC B
                                                 where B.BDCODTER = :BDCODTER and
                                                       B.BDREFTERC > :WREFPAGSERV
                                                 order by BDREFTERC))
      order by VINC.BDREFTERC desc
      into :BDCODRECOF, :WCODCLA;

      WCPFCOL = NULL;
      WCODEMPORD = NULL;

      SELECT COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP)
      FROM TEMPRESAS EMP
      WHERE EMP.BDCODEMP = :BDCODEMP
      INTO :WCODEMPORD;

      SELECT FIRST 1 RH.bdcpfmeiter, RH.BDTRIBUTACAOEXTERIOR
      FROM TTERCEIRO_RH RH
      WHERE RH.BDCODTER = :BDCODTER
      INTO :WCPFCOL, :WTRIBUTACAOEXTERIOR;

      if (char_length(WCPFCOL) <> 14) then
         WCPFCOL = NULL;


      if ((WCPFCOL IS NULL) OR (TRIM(WCPFCOL) = '')) then
         begin
           SELECT FIRST 1 TER.BDCGCTER
           FROM TTERCEIRO TER
           WHERE TER.BDCODTER = :BDCODTER
           INTO :WCPFCOL;
         end

      WTERATU = BDCODTER;
      WTIPOINFOATU = WTIPOINFO;
    end

    /*185447 - Inicio - Deve ser utilizado a base bruta(verbas com incidência), mas na tabela do cálculo, a base de IR ta gravando já com o desconto simplificado*/
    if (WTIPOINFO = 1) then
    begin
      WBASEIRBRUTA = 0;

      WSQL2 = 'select coalesce(sum(case ' || ' when REF.BDTIPOCODVER = 0 then  SERV.BDVALOR ' || /*Provento*/
      ' when REF.BDTIPOCODVER = 1 then ';

      if (PRFICHADEC <= 0) then
        WSQL2 = WSQL2 || '-SERV.BDVALOR ';/*Desconto*/
      else
        WSQL2 = WSQL2 || '0 ';/*Desconto*/

      WSQL2 = WSQL2 || ' else 0 end), 0) as BDBASEIRBRUTO ' || 'from VRHF_BASE_ITEMS_CALCTERC SERV ' || 'join VRH_BASE_TVERBAS V on (V.BDCODVER = SERV.BDCODVER) ' || 'join VRH_BASE_TVERBAS_REF REF on (REF.BDCODVER = V.BDCODVER and REF.BDREFVER = (select max(R.BDREFVER) from VRH_BASE_TVERBAS_REF R where R.BDCODVER = REF.BDCODVER and R.BDREFVER <= ' || :WREFPAGSERV || ')) ' || 'where SERV.BDCODEMP = ' || :BDCODEMP || ' and SERV.BDCODTER = ' || :BDCODTER || ' and SERV.BDCODSERV = ' || :BDCODSERV || ' and REF.BDIRVER > 0';

      execute statement WSQL2
          into :WBASEIRBRUTA;

      BDBASEIR = WBASEIRBRUTA;
      BDBASEIRBRUTA = WBASEIRBRUTA;
    end
    /*185447 - Fim*/

    if ((WBDCATEGORIATER in (15, 16, 18, 23, 25)) and
        (WTERCMEI = 'FALSE')) then
    begin
      WQTDVERBAS = null;
      select count(*) BDQTDVERBAS, sum(SERV.BDVALOR)
      from VRHF_BASE_ITEMS_CALCTERC SERV
      join VRH_BASE_TVERBAS V on (V.BDCODVER = SERV.BDCODVER)
      where SERV.BDCODEMP = :BDCODEMP and
            SERV.BDCODTER = :BDCODTER and
            SERV.BDCODSERV = :BDCODSERV and
            V.BDCLAVER starting with '0.001.0.0'
      into :WQTDVERBAS, :WREM;

      if ((WTIPOINFO = 2) and
          (coalesce(WQTDVERBAS, 0) = 0)) then
      begin
        select SERV.BDBASEIR
        from VRHF_EMP_TFICHAIRRF_TERC SERV
        where SERV.BDCODEMP = :BDCODEMP and
              SERV.BDCODTER = :BDCODTER and
              SERV.BDCODSERV = :BDCODSERV
        into :WBASEIRBRUTA;
        BDBASEIR = WBASEIRBRUTA * (WBDPERTRANSPIRTER / 100);
      end
      else
      if (coalesce(WQTDVERBAS, 0) > 1) then
      begin
        if (PRFICHADEC <= 0) then
          BDBASEIR = BDBASEIR + BDVALORINSS;

        BDBASEIRTOT = WREM - BDBASEIR;

        if (PRFICHADEC <= 0) then
          BDBASEIRBRUTA = BDBASEIRBRUTA + BDVALORINSS;
      end
      else
      begin
        BDBASEIRTOT = BDBASEIR;

        BDBASEIR = BDBASEIRTOT * (WBDPERTRANSPIRTER / 100);
        BDBASEIRTOT = BDBASEIRTOT - BDBASEIR;
      end
    end
    else
    if (WTERCMEI = 'FALSE') then
    begin
      --        if (((wutilizadescontosiplificado= 'TRUE')) and ((coalesce(wvalordescontosimplificado,0)>0))) then
      --           begin
      --             bdbaseir = bdbaseir + wvalordescontosimplificado;
      --           end
      --        else

      if (PRFICHADEC <= 0) then
        BDBASEIR = BDBASEIR + BDVALORINSS;
      if (WTIPOINFO = 1) then
      begin
        if (PRFICHADEC <= 0) then
          BDBASEIRBRUTA = BDBASEIRBRUTA + BDVALORINSS;
      end
    end
    else
    if (WTIPOINFO = 1) then
    begin
      if (PRFICHADEC <= 0) then
        BDBASEIRBRUTA = BDBASEIRBRUTA + BDVALORINSS;
    end

    BDREF = substring(cast(BDDATAPAGSERV as varchar(10)) from 1 for 4) || substring(cast(BDDATAPAGSERV as varchar(10)) from 6 for 2);

    WTOTISENTO = 0;
    for select BDCODVER, SERV.BDVALOR
        from VRHF_BASE_ITEMS_CALCTERC SERV
        where SERV.BDCODEMP = :BDCODEMP and
              SERV.BDCODTER = :BDCODTER and
              SERV.BDCODSERV = :BDCODSERV
        into :WCODVER, :WREM
    do
    begin
      WCODINCIDIRRF = 0;
      select first 1 BDRENDISENTOIRVER, BDCODINCIDIRRF
      from VRH_BASE_TVERBAS_REF
      where BDCODVER = :WCODVER and
            BDREFVER <= :BDREF
      order by BDREFVER desc

      into :WRENDISENTO, :WCODINCIDIRRF;

      select coalesce(rdb$get_context('USER_SESSION', 'W_GRAVA_RUBRICA_5002'),0) from rdb$database into :wgravarubrica;
      if (wgravarubrica > 0) then
         begin
           UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRUBICA5002 (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDCODVER,BDTABRUBRICA,BDCODRUBRICA)
           VALUES (CURRENT_CONNECTION,:WCODEMPORD,:WCPFCOL,:WREFIRRFESOCIALATU,:WCODVER,:WTABRUBR,cast(:WCODVER as varchar(30)))
           MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
      end

      if (coalesce(WRENDISENTO, 'FALSE') = 'TRUE') then
        WTOTISENTO = WTOTISENTO + WREM;

      if (coalesce(WCODINCIDIRRF, 0) in (11, 12, 13, 14, 41, 42, 43, 51, 52, 53, 54)) then
        WINCIDESOCIAL = 1;
    end

    if ((WTIPOINFO = 2) and
        (BDBASEIR > 0)) then
      WINCIDESOCIAL = 1;

    BDBASEIRTOT = coalesce(BDBASEIRTOT, 0) + WTOTISENTO;
    BDINCIDESOCIAL = WINCIDESOCIAL;

    /*inicio - Solicitação 161694 - André Cursino - adicionado descrição para o bdbaseirtot*/
    if (BDBASEIRTOT > 0) then
    begin
      if (WBDCATEGORIATER in (13, 14)) then
        BDDESCIRTOT = 'Trabalhador autônomo isento';
      else
      if (WBDCATEGORIATER in (15, 16)) then
        BDDESCIRTOT = 'Contribuição transportador autônomo isento';
      else
      if (WBDCATEGORIATER in (17, 18, 22, 23, 24, 25)) then
        BDDESCIRTOT = 'Contribuinte individual isento';
    end
    /*fim - Solicitação 161694 - André Cursino*/

    if (PRATUALIZAINFODESCSIMPLE = true) then
    begin
      WVALORDEP = BDVALORDEP;
      WVALORINSS = BDVALORINSS;
      WBASEIR = BDBASEIR;

      /*        wsqlaux = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, '||
                  ' BDPREVOUTRASFOLHAS, BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) '||
                  ' values ('||current_connection||', '||wempatu||', '||wteratu||', '||wrefpagatu||', 1, 0, '||coalesce(bdvalordep, 0)||', 0, '||coalesce(bdvalorinss, 0)||', '||coalesce(wvalordescsimplatu, 0)||', FALSE, '||coalesce(bdbaseir, 0)||')';
    
        execute statement wsqlaux;*/
    end


     if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
       begin
          BDBASEIR = 0;
          BDBASEIRBRUTA = 0;
          BDBASEIRTOT = 0;
       end

    suspend;

    WINCIDESOCIAL = 0;
  end

  if ((PRATUALIZAINFODESCSIMPLE = true) and
      (WEMPATU > 0)) then
  begin
    WSQLAUX = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, ' || ' BDPREVOUTRASFOLHAS, BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) ' || ' values (' || current_connection || ', ' || WEMPATU || ', ' || WTERATU || ', ' || WREFPAGATU || ', 1, 0, ' || coalesce(WVALORDEP, 0) || ', 0, ' || coalesce(WVALORINSS, 0) || ', ' || coalesce(WVALORDESCSIMPLATU, 0) || ', FALSE, ' || coalesce(WBASEIR, 0) || ')';

    execute statement WSQLAUX;
  end

end^

/* Restore proc. body: VRHF_SP_DADOS_BAIXA_CALCULO */
ALTER PROCEDURE VRHF_SP_DADOS_BAIXA_CALCULO(PRCODEMP INTEGER,
PRCODTER INTEGER,
PRCODSERV INTEGER,
PRCODCOL INTEGER,
PRTIPOCALC INTEGER,
PRREFERENCIA INTEGER,
PRDATA DATE,
PRREFCOMP INTEGER,
PRINIPERAQUI DATE,
PRCODFER INTEGER,
PRLIQUIDO NUMERIC(18,6),
PRINIGOZO DATE,
PRREFABONO INTEGER)
 AS
DECLARE VARIABLE WEXISTE INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
BEGIN
/*  wexiste = 0;

  prliquido = cast(prliquido as numeric(18,2));*/

  /* Procedure Text */
/*  if (prtipocalc = 1) then -- Servico
     begin*/
       /* busca a data do servico */
/*       select x.bddataserv from vrh_base_tservterc x where x.bdcodter = :prcodter and x.bdcodemp = :prcodemp and x.bdcodserv = :prcodserv into prdata;

       select count(*),max(bdchave) from vrhf_emp_tdadoscalc_baixa x
         where x.bdcodemp = :prcodemp and x.bdcodter = : prcodter and
               x.bdcodserv = :prcodserv and
               x.bdtipocalc = 1
         into wexiste,wchave;

       if (wexiste > 0) then
          delete from vrhf_emp_tdadoscalc_baixa x where x.bdcodemp = :prcodemp and x.bdchave = :wchave;
       wexiste = 0;
     end
  else
  if (prtipocalc = 7) then */ /* folha normal tomador */
/*     begin
       select count(*),max(bdchave) from vrhf_emp_tdadoscalc_baixa x
          where x.bdcodemp = :prcodemp and x.bdcodcol = : prcodcol and x.bdreferencia = :prreferencia and
                x.bdtipocalc = 7
         into wexiste,wchave;
     end
  else
  if (prtipocalc = 9) then */ /* folha complementar tomador */
/*     begin
       select count(*),max(bdchave) from vrhf_emp_tdadoscalc_baixa x
         where x.bdcodemp = :prcodemp and x.bdcodcol = : prcodcol and
               x.bdreferencia = :prreferencia and x.bddata = :prdata and
               x.bdtipocalc = 9
         into wexiste,wchave;
     end
  else
  if (prtipocalc in (2,3,6)) then */ /* folha normal / 13º / Adiantamento 13º */
/*     begin
       select count(*),max(bdchave) from vrhf_emp_tdadoscalc_baixa x
         where x.bdcodemp = :prcodemp and x.bdcodcol = : prcodcol and
               x.bdreferencia = :prreferencia and
               x.bdtipocalc = :prtipocalc
         into wexiste,wchave;

       if (wexiste > 0) then
          delete from vrhf_emp_tdadoscalc_baixa x where x.bdcodemp = :prcodemp and x.bdchave = :wchave;
       wexiste = 0;
     end
  else
  if (prtipocalc in (5,8)) then */ /* folha complementar / complemento 13º */
/*     begin
       select count(*),max(bdchave) from vrhf_emp_tdadoscalc_baixa x
         where x.bdcodemp = :prcodemp and x.bdcodcol = : prcodcol and
               x.bdreferencia = :prreferencia and x.bdrefcomp = :prrefcomp and
               x.bdtipocalc = :prtipocalc
         into wexiste,wchave;

       if (wexiste > 0) then
          delete from vrhf_emp_tdadoscalc_baixa x where x.bdcodemp = :prcodemp and x.bdchave = :wchave;
       wexiste = 0;
     end
  else
  if (prtipocalc = 4) then */ /* adiantamento salarial */
/*     begin
       select count(*),max(bdchave) from vrhf_emp_tdadoscalc_baixa x
         where x.bdcodemp = :prcodemp and x.bdcodcol = : prcodcol and
               x.bdreferencia = :prreferencia and x.bddata = :prdata and
               x.bdtipocalc = 4
         into wexiste,wchave;

       if (wexiste > 0) then
          delete from vrhf_emp_tdadoscalc_baixa x where x.bdcodemp = :prcodemp and x.bdchave = :wchave;
       wexiste = 0;
     end
  else
  if (prtipocalc = 10) then */ /* férias */
/*     begin
       select count(*),max(bdchave) from vrhf_emp_tdadoscalc_baixa x
         where x.bdcodemp = :prcodemp and x.bdcodcol = : prcodcol and
               x.bdreferencia = :prreferencia and x.bdiniperaqui = :priniperaqui and
               x.bdcodfer = :prcodfer and
               x.bdtipocalc = 10
         into wexiste,wchave;

       if (wexiste > 0) then
          delete from vrhf_emp_tdadoscalc_baixa x where x.bdcodemp = :prcodemp and x.bdchave = :wchave;
       wexiste = 0;
     end


--  if (prliquido <> 0) then
     begin
       if (wexiste = 0) then
          begin
            insert into vrhf_emp_tdadoscalc_baixa(BDCHAVE,BDCODTER,BDCODEMP,BDCODSERV,BDCODCOL,BDTIPOCALC,BDREFERENCIA,BDDATA,
                                                  BDREFCOMP,BDINIPERAQUI,BDCODFER,BDLIQUIDO,BDINIGOZO,BDREFABONO) values(
                                                  null,:prcodter,:prcodemp,:prcodserv,:prcodcol,:prtipocalc,:prreferencia,:prdata,
                                                  :prrefcomp,:priniperaqui,:prcodfer,coalesce(:prliquido,0),:prinigozo,:prrefabono);
          end
       else
          begin
            update vrhf_emp_tdadoscalc_baixa x set x.bdliquido = x.bdliquido + coalesce(:prliquido,0)
                   where x.bdcodemp = :prcodemp and x.bdchave = :wchave;
          end
     end*/
END
^

/* Restore proc. body: VRHF_SP_DADOS_CALC_GPS */
ALTER PROCEDURE VRHF_SP_DADOS_CALC_GPS(PRCODEMP VARCHAR(22000),
PRCODCOL VARCHAR(32000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRTIPOEMISSAO INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER,
PRAPENAGPS INTEGER)
 RETURNS(BDTIPO INTEGER,
BDCODEMP INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALOUTENTIDADE NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCODTOMADOR INTEGER,
BDCODCOL INTEGER,
BDCODTER INTEGER,
BDBASEFUNFN NUMERIC(15,6),
BDBASEFUNFC NUMERIC(15,6),
BDBASEFUNFERFN NUMERIC(15,6),
BDBASEFUNFERFC NUMERIC(15,6),
BDBASEFUN13RFN NUMERIC(15,6),
BDBASEFUN13RFC NUMERIC(15,6),
BDBASEFUN13 NUMERIC(15,6),
BDBASEFUNC13 NUMERIC(15,6),
BDBASEPROFN NUMERIC(15,6),
BDBASEPROFC NUMERIC(15,6),
BDBASEPROFERFN NUMERIC(15,6),
BDBASEPROFERFC NUMERIC(15,6),
BDBASEPRO13RFN NUMERIC(15,6),
BDBASEPRO13RFC NUMERIC(15,6),
BDBASEPRO13 NUMERIC(15,6),
BDBASEPROC13 NUMERIC(15,6),
BDBASEAUTFN NUMERIC(15,6),
BDBASEAUTFC NUMERIC(15,6),
BDBASEAUTFERFN NUMERIC(15,6),
BDBASEAUTFERFC NUMERIC(15,6),
BDBASEAUT13RFN NUMERIC(15,6),
BDBASEAUT13RFC NUMERIC(15,6),
BDBASEAUT13 NUMERIC(15,6),
BDBASEAUTC13 NUMERIC(15,6),
BDBASEFPASFN NUMERIC(15,6),
BDBASEFPASFC NUMERIC(15,6),
BDBASEFPASFERFN NUMERIC(15,6),
BDBASEFPASFERFC NUMERIC(15,6),
BDBASEFPAS13RFN NUMERIC(15,6),
BDBASEFPAS13RFC NUMERIC(15,6),
BDBASEFPAS13 NUMERIC(15,6),
BDBASEFPASC13 NUMERIC(15,6),
BDBASERATAPOFN NUMERIC(15,6),
BDBASERATAPOFC NUMERIC(15,6),
BDBASERATAPOFERFN NUMERIC(15,6),
BDBASERATAPOFERFC NUMERIC(15,6),
BDBASERATAPO13RFN NUMERIC(15,6),
BDBASERATAPO13RFC NUMERIC(15,6),
BDBASERATAPO13 NUMERIC(15,6),
BDBASERATAPOC13 NUMERIC(15,6))
 AS
DECLARE VARIABLE WSCODEMP INTEGER;
DECLARE VARIABLE WEXISTE INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WSALVATIPO INTEGER;
DECLARE VARIABLE WTIPOANT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WCODTOMADOR INTEGER;
DECLARE VARIABLE WCODTOMADORANT INTEGER;
DECLARE VARIABLE WEMPRESAANT INTEGER;
DECLARE VARIABLE WBDTOTSEG NUMERIC(15,6);
DECLARE VARIABLE WBDTOTBASE NUMERIC(15,6);
DECLARE VARIABLE WSUMTOTSEG NUMERIC(15,6);
DECLARE VARIABLE WSUMTOTBASE NUMERIC(15,6);
DECLARE VARIABLE WBDSEGFUN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUN NUMERIC(15,6);
DECLARE VARIABLE WBDPERCFUN NUMERIC(15,6);
DECLARE VARIABLE WSUMSEGFUN NUMERIC(15,6);
DECLARE VARIABLE WSUMBASEFUN NUMERIC(15,6);
DECLARE VARIABLE WSUMPERCFUN NUMERIC(15,6);
DECLARE VARIABLE WBDSEGPRO NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPRO NUMERIC(15,6);
DECLARE VARIABLE WBDPERCPRO NUMERIC(15,6);
DECLARE VARIABLE WSUMSEGPRO NUMERIC(15,6);
DECLARE VARIABLE WSUMBASEPRO NUMERIC(15,6);
DECLARE VARIABLE WSUMPERCPRO NUMERIC(15,6);
DECLARE VARIABLE WBDSEGAUT NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUT NUMERIC(15,6);
DECLARE VARIABLE WBDPERCAUT NUMERIC(15,6);
DECLARE VARIABLE WSUMSEGAUT NUMERIC(15,6);
DECLARE VARIABLE WSUMBASEAUT NUMERIC(15,6);
DECLARE VARIABLE WSUMPERCAUT NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPO NUMERIC(15,6);
DECLARE VARIABLE WBDVALORRATAPO NUMERIC(15,6);
DECLARE VARIABLE WSUMBASERATAPO NUMERIC(15,6);
DECLARE VARIABLE WSUMVALORRATAPO NUMERIC(15,6);
DECLARE VARIABLE WBDSALFAM NUMERIC(15,6);
DECLARE VARIABLE WBDSALMATERNIDADE NUMERIC(15,6);
DECLARE VARIABLE WSUMSALFAM NUMERIC(15,6);
DECLARE VARIABLE WSUMSALMATERNIDADE NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPAS NUMERIC(15,6);
DECLARE VARIABLE WBDPERCFPAS NUMERIC(15,6);
DECLARE VARIABLE WSUMBASEFPAS NUMERIC(15,6);
DECLARE VARIABLE WSUMPERCFPAS NUMERIC(15,6);
DECLARE VARIABLE WBDPERCRAT NUMERIC(15,6);
DECLARE VARIABLE WBDVALOUTENTIDADE NUMERIC(15,6);
DECLARE VARIABLE WSUMPERCRAT NUMERIC(15,6);
DECLARE VARIABLE WSUMVALOUTENTIDADE NUMERIC(15,6);
DECLARE VARIABLE WBDSIMPLESGPS INTEGER;
DECLARE VARIABLE WBDCODENQFED INTEGER;
DECLARE VARIABLE WBDDESCENQFED VARCHAR(10);
DECLARE VARIABLE WSUMSIMPLESGPS INTEGER;
DECLARE VARIABLE WSUMCODENQFED INTEGER;
DECLARE VARIABLE WSUMDESCENQFED VARCHAR(10);
DECLARE VARIABLE WGERAGUIA INTEGER;
DECLARE VARIABLE WEMISSAO INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WCODTOMADORAUX INTEGER;
DECLARE VARIABLE WBDBASEFUNFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUNFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUNFERFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUNFERFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUN13RFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUN13RFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUN13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFUNC13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPROFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPROFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPROFERFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPROFERFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPRO13RFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPRO13RFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPRO13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEPROC13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUTFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUTFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUTFERFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUTFERFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUT13RFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUT13RFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUT13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEAUTC13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPASFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPASFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPASFERFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPASFERFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPAS13RFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPAS13RFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPAS13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASEFPASC13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPOFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPOFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPOFERFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPOFERFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPO13RFN NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPO13RFC NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPO13 NUMERIC(15,6);
DECLARE VARIABLE WBDBASERATAPOC13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUNFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUNFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUNFERFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUNFERFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUN13RFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUN13RFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUN13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFUNC13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPROFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPROFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPROFERFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPROFERFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPRO13RFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPRO13RFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPRO13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEPROC13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUTFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUTFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUTFERFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUTFERFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUT13RFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUT13RFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUT13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEAUTC13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPASFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPASFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPASFERFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPASFERFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPAS13RFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPAS13RFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPAS13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASEFPASC13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPOFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPOFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPOFERFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPOFERFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPO13RFN NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPO13RFC NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPO13 NUMERIC(15,6);
DECLARE VARIABLE WSUMBDBASERATAPOC13 NUMERIC(15,6);
BEGIN
  /* prtipogps
     0 = normal
     1 = folha complementar
     2 = 13 sal
     3 = comp. 13 sal
     4 = prévia de rescisão
  */
  /* prtipoemissao
     0 = por cc
     1 = agrupado
     3 = por tomador (utilizado na SEFIP)
  */
  /* prapenasgps
     0 = apenas gps
     1 = historicos compensacoes/nf/gps
  */
  /* PRPUXAFILIAIS
     0 = Nao
     1 = Sim
  */
  /*
    BDTIPOREG
    0 = GPS
    1 = nf
    2 = gps comp
    3 = compensacao
    4 = historico comp
    5 = historico nf
    6 = historico gps
    7 = registro acumulados
    8 = contabilizacao
  */

  IF (prtipogps IS NULL) THEN
     prtipogps = 0;

  IF (prcodemp IS NULL) THEN
     prcodemp = 'null';
  ELSE
     BEGIN
       prcodemp = ''''||prcodemp||'''';
     END

  IF (prcodcol IS NULL) THEN
     prcodcol = 'null';
  ELSE
     prcodcol = ''''||prcodcol||'''';

  IF (prcodaut IS NULL) THEN
     prcodaut = 'null';
  ELSE
     prcodaut = ''''||prcodaut||'''';

  IF (prtipocol IS NULL) THEN
     prtipocol = 0;

  IF (pranomes IS NULL) THEN
     pranomes = 0;

  wemissao = prtipoemissao;
  prtipoemissao = 0;

  IF (prpuxafiliais IS NULL) THEN
     prpuxafiliais = 0;

  IF (pranomespag IS NULL) THEN
     pranomespag = pranomes;

  IF (prpuxafiliais IS NULL) THEN
     prpuxafiliais = 0;

  IF (pranomespag IS NULL) THEN
     pranomespag = pranomes;

  IF (prapenagps IS NULL) THEN
     prapenagps = 1;

  EXECUTE PROCEDURE sp_seta_competencia(pranomes,NULL,NULL);

  wsql = 'SELECT bdcodemp, bdtipo, bdreffn, bdrefpag, bdcodcentro, bdcodtpcc, bdtotSeg, bdtotBase, bdSEGFUN, bdBaseFun, bdPercFun, bdSegPro, bdBasePro, bdPercPro, bdSegAut, bdBaseAut,'||
         'bdPercAut, bdbaseratapo, bdvalorratapo, bdsalfam, bdsalmaternidade, bdbasefpas, bdpercfpas, bdpercrat, BDVALOUTENTIDADE, bddescenqfed, bdsimplesgps,'||
         'bdcodenqfed, bdcodtomador, bdcodcol, bdcodter, ';

  wsql =   wsql||'BDBASEFUNFN,    BDBASEFUNFC,    BDBASEFUNFERFN,    BDBASEFUNFERFC,    BDBASEFUN13RFN,    BDBASEFUN13RFC,    BDBASEFUN13,    BDBASEFUNC13,'||
                 'BDBASEPROFN,    BDBASEPROFC,    BDBASEPROFERFN,    BDBASEPROFERFC,    BDBASEPRO13RFN,    BDBASEPRO13RFC,    BDBASEPRO13,    BDBASEPROC13,'||
                 'BDBASEAUTFN,    BDBASEAUTFC,    BDBASEAUTFERFN,    BDBASEAUTFERFC,    BDBASEAUT13RFN,    BDBASEAUT13RFC,    BDBASEAUT13,    BDBASEAUTC13,'||
                 'BDBASEFPASFN,   BDBASEFPASFC,   BDBASEFPASFERFN,   BDBASEFPASFERFC,   BDBASEFPAS13RFN,   BDBASEFPAS13RFC,   BDBASEFPAS13,   BDBASEFPASC13,'||
                 'BDBASERATAPOFN, BDBASERATAPOFC, BDBASERATAPOFERFN, BDBASERATAPOFERFC, BDBASERATAPO13RFN, BDBASERATAPO13RFC, BDBASERATAPO13, BDBASERATAPOC13';

  wsql = wsql||' FROM VRHF_SP_DADOS_IND_CALC_GPS('||prcodemp||','||prcodcol||','||prcodaut||','||prtipocol||','||pranomes||','||pranomespag||',0,'||prtipogps||','||prpuxafiliais||','||prapenagps||')';

  IF (prapenagps = 0) THEN
     wsql = wsql||' where bdtipo <> 2';

  wcodtomadorant = -1;
  wsumtotSeg = 0;
  wsumtotBase = 0;
  wSUMSEGFUN = 0;
  wSUMBaseFun = 0;
  wSUMPercFun = 0;
  wSumSegPro = 0;
  wSumBasePro = 0;
  wSumPercPro = 0;
  wSumSegAut = 0;
  wSumBaseAut = 0;
  wSumPercAut = 0;
  wSumbaseratapo = 0;
  wSumvalorratapo = 0;
  wSumsalfam = 0;
  wSumsalmaternidade = 0;
  wSumbasefpas = 0;
  wSumpercfpas = 0;
  wSumpercrat = 0;
  wSumVALOUTENTIDADE = 0;
  wSumdescenqfed = NULL;
  wSumsimplesgps = NULL;
  wSumcodenqfed = NULL;

  wsumBDBASEFUNFN = 0;
  wsumBDBASEFUNFC = 0;
  wsumBDBASEFUNFERFN = 0;
  wsumBDBASEFUNFERFC = 0;
  wsumBDBASEFUN13RFN = 0;
  wsumBDBASEFUN13RFC = 0;
  wsumBDBASEFUN13 = 0;
  wsumBDBASEFUNC13 = 0;
  wsumBDBASEPROFN = 0;
  wsumBDBASEPROFC = 0;
  wsumBDBASEPROFERFN = 0;
  wsumBDBASEPROFERFC = 0;
  wsumBDBASEPRO13RFN = 0;
  wsumBDBASEPRO13RFC = 0;
  wsumBDBASEPRO13 = 0;
  wsumBDBASEPROC13 = 0;
  wsumBDBASEAUTFN = 0;
  wsumBDBASEAUTFC = 0;
  wsumBDBASEAUTFERFN = 0;
  wsumBDBASEAUTFERFC = 0;
  wsumBDBASEAUT13RFN = 0;
  wsumBDBASEAUT13RFC = 0;
  wsumBDBASEAUT13 = 0;
  wsumBDBASEAUTC13 = 0;
  wsumBDBASEFPASFN = 0;
  wsumBDBASEFPASFC = 0;
  wsumBDBASEFPASFERFN = 0;
  wsumBDBASEFPASFERFC = 0;
  wsumBDBASEFPAS13RFN = 0;
  wsumBDBASEFPAS13RFC = 0;
  wsumBDBASEFPAS13 = 0;
  wsumBDBASEFPASC13 = 0;
  wsumBDBASERATAPOFN = 0;
  wsumBDBASERATAPOFC = 0;
  wsumBDBASERATAPOFERFN = 0;
  wsumBDBASERATAPOFERFC = 0;
  wsumBDBASERATAPO13RFN = 0;
  wsumBDBASERATAPO13RFC = 0;
  wsumBDBASERATAPO13 = 0;
  wsumBDBASERATAPOC13 = 0;

  bdtipo = 0;
  WEXISTE = 0;
  FOR EXECUTE STATEMENT wsql INTO
      : bdcodemp, --bdcodemp,
      : bdtipo, -- bdtipo,
      : bdreffn, -- bdreffn,
      : bdrefpag, --bdrefpag,
      : bdcodcentro,
      : bdcodtpcc, -- bdcodtpcc,

      /*totais*/
      : wbdtotSeg, -- bdtotSeg,
      : wbdtotBase, -- bdtotBase,

      /*colaboradores*/
      : wbdSEGFUN, -- bdSEGFUN,
      : wbdBaseFun, -- bdBaseFun,
      : wbdPercFun, -- bdPercFun,

       /*prolaboristas*/
      : wbdSegPro, -- bdSegPro,
      : wbdBasePro, -- bdBasePro,
      : wbdPercPro, -- bdPercPro,

      /*autonomos*/
      : wbdSegAut, --bdSegAut,
      : wbdBaseAut, -- bdBaseAut
      : wbdPercAut, -- bdPercAut,

      /* rat aposentadoria*/
      : wbdbaseratapo, -- bdbaseratapo,
      : wbdvalorratapo, -- bdvalorratapo,

      : wbdsalfam, -- bdsalfam,
      : wbdsalmaternidade, -- bdsalmaternidade,

      /* base fpas*/
      : wbdbasefpas, -- bdbasefpas,
      : wbdpercfpas, -- bdpercfpas,

      /* rat */
      : wbdpercrat, -- bdpercrat,
      : wBDVALOUTENTIDADE, -- BDVALOUTENTIDADE,

      : wbddescenqfed, --bddescenqfed,
      : wbdsimplesgps, -- bdsimplesgps,
      : wbdcodenqfed, -- bdcodenqfed,
      : bdcodtomador, -- bdcodtomador

      : wcodcol, -- bdcodcol
      : wcodter, -- bdcodter

      : wBDBASEFUNFN,
      : wBDBASEFUNFC,
      : wBDBASEFUNFERFN,
      : wBDBASEFUNFERFC,
      : wBDBASEFUN13RFN,
      : wBDBASEFUN13RFC,
      : wBDBASEFUN13,
      : wBDBASEFUNC13,
      : wBDBASEPROFN,
      : wBDBASEPROFC,
      : wBDBASEPROFERFN,
      : wBDBASEPROFERFC,
      : wBDBASEPRO13RFN,
      : wBDBASEPRO13RFC,
      : wBDBASEPRO13,
      : wBDBASEPROC13,
      : wBDBASEAUTFN,
      : wBDBASEAUTFC,
      : wBDBASEAUTFERFN,
      : wBDBASEAUTFERFC,
      : wBDBASEAUT13RFN,
      : wBDBASEAUT13RFC,
      : wBDBASEAUT13,
      : wBDBASEAUTC13,
      : wBDBASEFPASFN,
      : wBDBASEFPASFC,
      : wBDBASEFPASFERFN,
      : wBDBASEFPASFERFC,
      : wBDBASEFPAS13RFN,
      : wBDBASEFPAS13RFC,
      : wBDBASEFPAS13,
      : wBDBASEFPASC13,
      : wBDBASERATAPOFN,
      : wBDBASERATAPOFC,
      : wBDBASERATAPOFERFN,
      : wBDBASERATAPOFERFC,
      : wBDBASERATAPO13RFN,
      : wBDBASERATAPO13RFC,
      : wBDBASERATAPO13,
      : wBDBASERATAPOC13
      DO
  BEGIN
    WEXISTE = 1;
    wsalvatipo = bdtipo;
    bdcodter = NULL;
    bdcodcol = NULL;
    IF ((wsalvatipo <> 2) OR (wtipoant <> 2)) THEN
       BEGIN
         wcodtomador = bdcodtomador;
         IF (wcodtomador IS NULL) THEN
            wcodtomador = 0;
     
         wgeraguia = 0;
         IF ((wemissao IS NULL) OR (wemissao = 1)) THEN
            BEGIN
              IF ((wempresaant <> bdcodemp) AND (wcodtomadorant <> -1)) THEN
                 wgeraguia = 1;
            END
         ELSE
            BEGIN
              IF (((wempresaant <> bdcodemp) OR (wcodtomadorant <> wcodtomador)) AND (wcodtomadorant <> -1)) THEN
                 wgeraguia = 1;
            END
     
         IF (wgeraguia = 1) THEN
            BEGIN
              bdtipo = 1;
              wscodemp = bdcodemp;
              bdcodemp = wempresaant;
              wcodtomadoraux = wcodtomador;
              wcodtomador = bdcodtpcc;
              IF (wcodtomadorant = 0) THEN
                 bdcodtpcc = NULL;
              ELSE
                 bdcodtpcc = wcodtomadorant;

              IF (wcodtomadorant = 0) THEN
                 bdcodtomador = NULL;
              ELSE
                 bdcodtomador = wcodtomadorant;
     
              bdtotSeg = wsumtotSeg;
              bdtotBase = wsumtotBase;
              bdSEGFUN = wSUMSEGFUN;
              bdBaseFun = wSUMBaseFun;
              bdPercFun = wSUMPercFun;
              bdSegPro = wSumSegPro;
              bdBasePro = wSumBasePro;
              bdPercPro = wSumPercPro;
              bdSegAut = wSumSegAut;
              bdBaseAut = wSumBaseAut;
              bdPercAut = wSumPercAut;
              bdbaseratapo = wSumbaseratapo;
              bdvalorratapo = wSumvalorratapo;
              bdsalfam = wSumsalfam;
              bdsalmaternidade = wSumsalmaternidade;
              bdbasefpas = wSumbasefpas;
              bdpercfpas = wSumpercfpas;
              bdpercrat = wSumpercrat;
              BDVALOUTENTIDADE = wSumVALOUTENTIDADE;
              bddescenqfed = wSumdescenqfed;
              bdsimplesgps = wSumsimplesgps;
              bdcodenqfed = wSumcodenqfed;
              bdcodcol = NULL;

              BDBASEFUNFN = wsumBDBASEFUNFN;
              BDBASEFUNFC = wsumBDBASEFUNFC;
              BDBASEFUNFERFN = wsumBDBASEFUNFERFN;
              BDBASEFUNFERFC = wsumBDBASEFUNFERFC;
              BDBASEFUN13RFN = wsumBDBASEFUN13RFN;
              BDBASEFUN13RFC = wsumBDBASEFUN13RFC;
              BDBASEFUN13 = wsumBDBASEFUN13;
              BDBASEFUNC13 = wsumBDBASEFUNC13;
              BDBASEPROFN = wsumBDBASEPROFN;
              BDBASEPROFC = wsumBDBASEPROFC;
              BDBASEPROFERFN = wsumBDBASEPROFERFN;
              BDBASEPROFERFC = wsumBDBASEPROFERFC;
              BDBASEPRO13RFN = wsumBDBASEPRO13RFN;
              BDBASEPRO13RFC = wsumBDBASEPRO13RFC;
              BDBASEPRO13 = wsumBDBASEPRO13;
              BDBASEPROC13 = wsumBDBASEPROC13;
              BDBASEAUTFN = wsumBDBASEAUTFN;
              BDBASEAUTFC = wsumBDBASEAUTFC;
              BDBASEAUTFERFN = wsumBDBASEAUTFERFN;
              BDBASEAUTFERFC = wsumBDBASEAUTFERFC;
              BDBASEAUT13RFN = wsumBDBASEAUT13RFN;
              BDBASEAUT13RFC = wsumBDBASEAUT13RFC;
              BDBASEAUT13 = wsumBDBASEAUT13;
              BDBASEAUTC13 = wsumBDBASEAUTC13;
              BDBASEFPASFN = wsumBDBASEFPASFN;
              BDBASEFPASFC = wsumBDBASEFPASFC;
              BDBASEFPASFERFN = wsumBDBASEFPASFERFN;
              BDBASEFPASFERFC = wsumBDBASEFPASFERFC;
              BDBASEFPAS13RFN = wsumBDBASEFPAS13RFN;
              BDBASEFPAS13RFC = wsumBDBASEFPAS13RFC;
              BDBASEFPAS13 = wsumBDBASEFPAS13;
              BDBASEFPASC13 = wsumBDBASEFPASC13;
              BDBASERATAPOFN = wsumBDBASERATAPOFN;
              BDBASERATAPOFC = wsumBDBASERATAPOFC;
              BDBASERATAPOFERFN = wsumBDBASERATAPOFERFN;
              BDBASERATAPOFERFC = wsumBDBASERATAPOFERFC;
              BDBASERATAPO13RFN = wsumBDBASERATAPO13RFN;
              BDBASERATAPO13RFC = wsumBDBASERATAPO13RFC;
              BDBASERATAPO13 = wsumBDBASERATAPO13;
              BDBASERATAPOC13 = wsumBDBASERATAPOC13;

              SUSPEND;

              bdcodemp = wscodemp;

              bdcodtpcc = wcodtomador;
              wsumtotbase = 0;
              wsumtotseg = 0;
              wSUMSEGFUN = 0;
              wSUMBaseFun = 0;
              wSUMPercFun = 0;
              wSumSegPro = 0;
              wSumBasePro = 0;
              wSumPercPro = 0;
              wSumSegAut = 0;
              wSumBaseAut = 0;
              wSumPercAut = 0;
              wSumbaseratapo = 0;
              wSumvalorratapo = 0;
              wSumsalfam = 0;
              wSumsalmaternidade = 0;
              wSumbasefpas = 0;
              wSumpercfpas = 0;
              wSumpercrat = 0;
              wSumVALOUTENTIDADE = 0;
              wSumdescenqfed = NULL;
              wSumsimplesgps = NULL;
              wSumcodenqfed = NULL;

              wsumBDBASEFUNFN = 0;
              wsumBDBASEFUNFC = 0;
              wsumBDBASEFUNFERFN = 0;
              wsumBDBASEFUNFERFC = 0;
              wsumBDBASEFUN13RFN = 0;
              wsumBDBASEFUN13RFC = 0;
              wsumBDBASEFUN13 = 0;
              wsumBDBASEFUNC13 = 0;
              wsumBDBASEPROFN = 0;
              wsumBDBASEPROFC = 0;
              wsumBDBASEPROFERFN = 0;
              wsumBDBASEPROFERFC = 0;
              wsumBDBASEPRO13RFN = 0;
              wsumBDBASEPRO13RFC = 0;
              wsumBDBASEPRO13 = 0;
              wsumBDBASEPROC13 = 0;
              wsumBDBASEAUTFN = 0;
              wsumBDBASEAUTFC = 0;
              wsumBDBASEAUTFERFN = 0;
              wsumBDBASEAUTFERFC = 0;
              wsumBDBASEAUT13RFN = 0;
              wsumBDBASEAUT13RFC = 0;
              wsumBDBASEAUT13 = 0;
              wsumBDBASEAUTC13 = 0;
              wsumBDBASEFPASFN = 0;
              wsumBDBASEFPASFC = 0;
              wsumBDBASEFPASFERFN = 0;
              wsumBDBASEFPASFERFC = 0;
              wsumBDBASEFPAS13RFN = 0;
              wsumBDBASEFPAS13RFC = 0;
              wsumBDBASEFPAS13 = 0;
              wsumBDBASEFPASC13 = 0;
              wsumBDBASERATAPOFN = 0;
              wsumBDBASERATAPOFC = 0;
              wsumBDBASERATAPOFERFN = 0;
              wsumBDBASERATAPOFERFC = 0;
              wsumBDBASERATAPO13RFN = 0;
              wsumBDBASERATAPO13RFC = 0;
              wsumBDBASERATAPO13 = 0;
              wsumBDBASERATAPOC13 = 0;
            END
     
         IF (wsalvatipo <> 2) THEN
            BEGIN
              wsumtotbase = wsumtotbase + wbdtotBase;
              wsumtotseg = wsumtotseg + wbdtotseg;
              wSUMSEGFUN = wSUMSEGFUN + wbdSEGFUN;
              wSUMBaseFun = wSUMBaseFun + wbdBaseFun;
              wSUMPercFun = wbdPercFun;
              wSumSegPro = wSumSegPro + wbdSegPro;
              wSumBasePro = wSumBasePro + wbdBasePro;
              wSumPercPro = wbdPercPro;
              wSumSegAut = wSumSegAut + wbdSegAut;
              wSumBaseAut = wSumBaseAut + wbdBaseAut;
              wSumPercAut = wbdPercAut;
              wSumbaseratapo = wSumbaseratapo + wbdbaseratapo;
              wSumvalorratapo = wSumvalorratapo + wbdvalorratapo;
              wSumsalfam = wSumsalfam + wbdsalfam;
              wSumsalmaternidade = wSumsalmaternidade + wbdsalmaternidade;
              wSumbasefpas = wSumbasefpas + wbdbasefpas;
              wSumpercfpas = wbdpercfpas;
              wSumpercrat = wbdpercrat;
              wsumvaloutentidade = wsumvaloutentidade + wbdvaloutentidade;
              wsumdescenqfed = wbddescenqfed;
              wsumsimplesgps = wbdsimplesgps;
              wsumcodenqfed = wbdcodenqfed;
          
              wSumBDBASEFUNFN = wSumBDBASEFUNFN + wBDBASEFUNFN;
              wSumBDBASEFUNFC = wSumBDBASEFUNFC + wBDBASEFUNFC;
              wSumBDBASEFUNFERFN = wSumBDBASEFUNFERFN + wBDBASEFUNFERFN;
              wSumBDBASEFUNFERFC = wSumBDBASEFUNFERFC + wBDBASEFUNFERFC;
              wSumBDBASEFUN13RFN = wSumBDBASEFUN13RFN + wBDBASEFUN13RFN;
              wSumBDBASEFUN13RFC = wSumBDBASEFUN13RFC + wBDBASEFUN13RFC;
              wSumBDBASEFUN13 = wSumBDBASEFUN13 + wBDBASEFUN13;
              wSumBDBASEFUNC13 = wSumBDBASEFUNC13 + wBDBASEFUNC13;
              wSumBDBASEPROFN = wSumBDBASEPROFN + wBDBASEPROFN;
              wSumBDBASEPROFC = wSumBDBASEPROFC + wBDBASEPROFC;
              wSumBDBASEPROFERFN = wSumBDBASEPROFERFN + wBDBASEPROFERFN;
              wSumBDBASEPROFERFC = wSumBDBASEPROFERFC + wBDBASEPROFERFC;
              wSumBDBASEPRO13RFN = wSumBDBASEPRO13RFN + wBDBASEPRO13RFN;
              wSumBDBASEPRO13RFC = wSumBDBASEPRO13RFC + wBDBASEPRO13RFC;
              wSumBDBASEPRO13 = wSumBDBASEPRO13 + wBDBASEPRO13;
              wSumBDBASEPROC13 = wSumBDBASEPROC13 + wBDBASEPROC13;
              wSumBDBASEAUTFN = wSumBDBASEAUTFN + wBDBASEAUTFN;
              wSumBDBASEAUTFC = wSumBDBASEAUTFC + wBDBASEAUTFC;
              wSumBDBASEAUTFERFN = wSumBDBASEAUTFERFN + wBDBASEAUTFERFN;
              wSumBDBASEAUTFERFC = wSumBDBASEAUTFERFC + wBDBASEAUTFERFC;
              wSumBDBASEAUT13RFN = wSumBDBASEAUT13RFN + wBDBASEAUT13RFN;
              wSumBDBASEAUT13RFC = wSumBDBASEAUT13RFC + wBDBASEAUT13RFC;
              wSumBDBASEAUT13 = wSumBDBASEAUT13 + wBDBASEAUT13;
              wSumBDBASEAUTC13 = wSumBDBASEAUTC13 + wBDBASEAUTC13;
              wSumBDBASEFPASFN = wSumBDBASEFPASFN + wBDBASEFPASFN;
              wSumBDBASEFPASFC = wSumBDBASEFPASFC + wBDBASEFPASFC;
              wSumBDBASEFPASFERFN = wSumBDBASEFPASFERFN + wBDBASEFPASFERFN;
              wSumBDBASEFPASFERFC = wSumBDBASEFPASFERFC + wBDBASEFPASFERFC;
              wSumBDBASEFPAS13RFN = wSumBDBASEFPAS13RFN + wBDBASEFPAS13RFN;
              wSumBDBASEFPAS13RFC = wSumBDBASEFPAS13RFC + wBDBASEFPAS13RFC;
              wSumBDBASEFPAS13 = wSumBDBASEFPAS13 + wBDBASEFPAS13;
              wSumBDBASEFPASC13 = wSumBDBASEFPASC13 + wBDBASEFPASC13;
              wSumBDBASERATAPOFN = wSumBDBASERATAPOFN + wBDBASERATAPOFN;
              wSumBDBASERATAPOFC = wSumBDBASERATAPOFC + wBDBASERATAPOFC;
              wSumBDBASERATAPOFERFN = wSumBDBASERATAPOFERFN + wBDBASERATAPOFERFN;
              wSumBDBASERATAPOFERFC = wSumBDBASERATAPOFERFC + wBDBASERATAPOFERFC;
              wSumBDBASERATAPO13RFN = wSumBDBASERATAPO13RFN + wBDBASERATAPO13RFN;
              wSumBDBASERATAPO13RFC = wSumBDBASERATAPO13RFC + wBDBASERATAPO13RFC;
              wSumBDBASERATAPO13 = wSumBDBASERATAPO13 + wBDBASERATAPO13;
              wSumBDBASERATAPOC13 = wSumBDBASERATAPOC13 + wBDBASERATAPOC13;

              bdtotSeg = wbdtotSeg;
              bdtotBase = wbdtotBase;
              bdSEGFUN = wbdSEGFUN;
              bdBaseFun = wbdBaseFun;
              bdPercFun = wbdPercFun;
              bdSegPro = wbdSegPro;
              bdBasePro = wbdBasePro;
              bdPercPro = wbdPercPro;
              bdSegAut = wbdSegAut;
              bdBaseAut = wbdBaseAut;
              bdPercAut = wbdPercAut;
              bdbaseratapo = wbdbaseratapo;
              bdvalorratapo = wbdvalorratapo;
              bdsalfam = wbdsalfam;
              bdsalmaternidade = wbdsalmaternidade;
              bdbasefpas = wbdbasefpas;
              bdpercfpas = wbdpercfpas;
              bdpercrat = wbdpercrat;
              bdvaloutentidade = wbdvaloutentidade;
              bddescenqfed = wbddescenqfed;
              bdsimplesgps = wbdsimplesgps;
              bdcodenqfed = wbdcodenqfed;
          
              BDBASEFUNFN = wBDBASEFUNFN;
              BDBASEFUNFC = wBDBASEFUNFC;
              BDBASEFUNFERFN = wBDBASEFUNFERFN;
              BDBASEFUNFERFC = wBDBASEFUNFERFC;
              BDBASEFUN13RFN = wBDBASEFUN13RFN;
              BDBASEFUN13RFC = wBDBASEFUN13RFC;
              BDBASEFUN13 = wBDBASEFUN13;
              BDBASEFUNC13 = wBDBASEFUNC13;
              BDBASEPROFN = wBDBASEPROFN;
              BDBASEPROFC = wBDBASEPROFC;
              BDBASEPROFERFN = wBDBASEPROFERFN;
              BDBASEPROFERFC = wBDBASEPROFERFC;
              BDBASEPRO13RFN = wBDBASEPRO13RFN;
              BDBASEPRO13RFC = wBDBASEPRO13RFC;
              BDBASEPRO13 = wBDBASEPRO13;
              BDBASEPROC13 = wBDBASEPROC13;
              BDBASEAUTFN = wBDBASEAUTFN;
              BDBASEAUTFC = wBDBASEAUTFC;
              BDBASEAUTFERFN = wBDBASEAUTFERFN;
              BDBASEAUTFERFC = wBDBASEAUTFERFC;
              BDBASEAUT13RFN = wBDBASEAUT13RFN;
              BDBASEAUT13RFC = wBDBASEAUT13RFC;
              BDBASEAUT13 = wBDBASEAUT13;
              BDBASEAUTC13 = wBDBASEAUTC13;
              BDBASEFPASFN = wBDBASEFPASFN;
              BDBASEFPASFC = wBDBASEFPASFC;
              BDBASEFPASFERFN = wBDBASEFPASFERFN;
              BDBASEFPASFERFC = wBDBASEFPASFERFC;
              BDBASEFPAS13RFN = wBDBASEFPAS13RFN;
              BDBASEFPAS13RFC = wBDBASEFPAS13RFC;
              BDBASEFPAS13 = wBDBASEFPAS13;
              BDBASEFPASC13 = wBDBASEFPASC13;
              BDBASERATAPOFN = wBDBASERATAPOFN;
              BDBASERATAPOFC = wBDBASERATAPOFC;
              BDBASERATAPOFERFN = wBDBASERATAPOFERFN;
              BDBASERATAPOFERFC = wBDBASERATAPOFERFC;
              BDBASERATAPO13RFN = wBDBASERATAPO13RFN;
              BDBASERATAPO13RFC = wBDBASERATAPO13RFC;
              BDBASERATAPO13 = wBDBASERATAPO13;
              BDBASERATAPOC13 = wBDBASERATAPOC13;

              IF ((wcodtomador = 0) OR ((wemissao IS NULL) OR (wemissao = 1))) THEN
                bdcodtomador = NULL;
              ELSE
                bdcodtomador = wcodtomador;
              bdtipo = 0;
              bdcodcol = NULL;
          
              IF (prapenagps = 1) THEN
                SUSPEND;
            END
       END

     IF (wsalvatipo = 2) THEN
       BEGIN
         bdtipo = 2;
         wcodtomador = wcodtomadoraux;
         bdtotSeg = wbdtotSeg;
         bdtotBase = wbdtotBase;
         bdSEGFUN = wbdSEGFUN;
         bdBaseFun = wbdBaseFun;
         bdPercFun = wbdPercFun;
         bdSegPro = wbdSegPro;
         bdBasePro = wbdBasePro;
         bdPercPro = wbdPercPro;
         bdSegAut = wbdSegAut;
         bdBaseAut = wbdBaseAut;
         bdPercAut = wbdPercAut;
         bdbaseratapo = wbdbaseratapo;
         bdvalorratapo = wbdvalorratapo;
         bdsalfam = wbdsalfam;
         bdsalmaternidade = wbdsalmaternidade;
         bdbasefpas = wbdbasefpas;
         bdpercfpas = wbdpercfpas;
         bdpercrat = wbdpercrat;
         bdvaloutentidade = wbdvaloutentidade;
         bddescenqfed = wbddescenqfed;
         bdsimplesgps = wbdsimplesgps;
         bdcodenqfed = wbdcodenqfed;
     
         IF ((wcodtomador = 0) OR ((wemissao IS NULL) OR (wemissao = 1))) THEN
           bdcodtomador = NULL;
         ELSE
           bdcodtomador = wcodtomador;

         bdcodcol = wcodcol;
         bdcodter = wcodter;

         BDBASEFUNFN = wBDBASEFUNFN;
         BDBASEFUNFC = wBDBASEFUNFC;
         BDBASEFUNFERFN = wBDBASEFUNFERFN;
         BDBASEFUNFERFC = wBDBASEFUNFERFC;
         BDBASEFUN13RFN = wBDBASEFUN13RFN;
         BDBASEFUN13RFC = wBDBASEFUN13RFC;
         BDBASEFUN13 = wBDBASEFUN13;
         BDBASEFUNC13 = wBDBASEFUNC13;
         BDBASEPROFN = wBDBASEPROFN;
         BDBASEPROFC = wBDBASEPROFC;
         BDBASEPROFERFN = wBDBASEPROFERFN;
         BDBASEPROFERFC = wBDBASEPROFERFC;
         BDBASEPRO13RFN = wBDBASEPRO13RFN;
         BDBASEPRO13RFC = wBDBASEPRO13RFC;
         BDBASEPRO13 = wBDBASEPRO13;
         BDBASEPROC13 = wBDBASEPROC13;
         BDBASEAUTFN = wBDBASEAUTFN;
         BDBASEAUTFC = wBDBASEAUTFC;
         BDBASEAUTFERFN = wBDBASEAUTFERFN;
         BDBASEAUTFERFC = wBDBASEAUTFERFC;
         BDBASEAUT13RFN = wBDBASEAUT13RFN;
         BDBASEAUT13RFC = wBDBASEAUT13RFC;
         BDBASEAUT13 = wBDBASEAUT13;
         BDBASEAUTC13 = wBDBASEAUTC13;
         BDBASEFPASFN = wBDBASEFPASFN;
         BDBASEFPASFC = wBDBASEFPASFC;
         BDBASEFPASFERFN = wBDBASEFPASFERFN;
         BDBASEFPASFERFC = wBDBASEFPASFERFC;
         BDBASEFPAS13RFN = wBDBASEFPAS13RFN;
         BDBASEFPAS13RFC = wBDBASEFPAS13RFC;
         BDBASEFPAS13 = wBDBASEFPAS13;
         BDBASEFPASC13 = wBDBASEFPASC13;
         BDBASERATAPOFN = wBDBASERATAPOFN;
         BDBASERATAPOFC = wBDBASERATAPOFC;
         BDBASERATAPOFERFN = wBDBASERATAPOFERFN;
         BDBASERATAPOFERFC = wBDBASERATAPOFERFC;
         BDBASERATAPO13RFN = wBDBASERATAPO13RFN;
         BDBASERATAPO13RFC = wBDBASERATAPO13RFC;
         BDBASERATAPO13 = wBDBASERATAPO13;
         BDBASERATAPOC13 = wBDBASERATAPOC13;

         SUSPEND;
       END

     wcodtomadorant = wcodtomador;
     wempresaant = bdcodemp;
     wtipoant = bdtipo;
   END
     
   bdtipo = 1;
   IF (wcodtomador = 0) THEN
      bdcodtpcc = NULL;
   ELSE
      bdcodtpcc = wcodtomador;
 
   IF ((wcodtomador = 0) OR ((wemissao IS NULL) OR (wemissao = 1))) THEN
     bdcodtomador = NULL;
   ELSE
     bdcodtomador = wcodtomador;
 
   bdtotSeg = wsumtotSeg;
   bdtotBase = wsumtotBase;
   bdSEGFUN = wSUMSEGFUN;
   bdBaseFun = wSUMBaseFun;
   bdPercFun = wSUMPercFun;
   bdSegPro = wSumSegPro;
   bdBasePro = wSumBasePro;
   bdPercPro = wSumPercPro;
   bdSegAut = wSumSegAut;
   bdBaseAut = wSumBaseAut;
   bdPercAut = wSumPercAut;
   bdbaseratapo = wSumbaseratapo;
   bdvalorratapo = wSumvalorratapo;
   bdsalfam = wSumsalfam;
   bdsalmaternidade = wSumsalmaternidade;
   bdbasefpas = wSumbasefpas;
   bdpercfpas = wSumpercfpas;
   bdpercrat = wSumpercrat;
   bdvaloutentidade = wsumvaloutentidade;
   bddescenqfed = wSumdescenqfed;
   bdsimplesgps = wSumsimplesgps;
   bdcodenqfed = wSumcodenqfed;

   BDBASEFUNFN = wsumBDBASEFUNFN;
   BDBASEFUNFC = wsumBDBASEFUNFC;
   BDBASEFUNFERFN = wsumBDBASEFUNFERFN;
   BDBASEFUNFERFC = wsumBDBASEFUNFERFC;
   BDBASEFUN13RFN = wsumBDBASEFUN13RFN;
   BDBASEFUN13RFC = wsumBDBASEFUN13RFC;
   BDBASEFUN13 = wsumBDBASEFUN13;
   BDBASEFUNC13 = wsumBDBASEFUNC13;
   BDBASEPROFN = wsumBDBASEPROFN;
   BDBASEPROFC = wsumBDBASEPROFC;
   BDBASEPROFERFN = wsumBDBASEPROFERFN;
   BDBASEPROFERFC = wsumBDBASEPROFERFC;
   BDBASEPRO13RFN = wsumBDBASEPRO13RFN;
   BDBASEPRO13RFC = wsumBDBASEPRO13RFC;
   BDBASEPRO13 = wsumBDBASEPRO13;
   BDBASEPROC13 = wsumBDBASEPROC13;
   BDBASEAUTFN = wsumBDBASEAUTFN;
   BDBASEAUTFC = wsumBDBASEAUTFC;
   BDBASEAUTFERFN = wsumBDBASEAUTFERFN;
   BDBASEAUTFERFC = wsumBDBASEAUTFERFC;
   BDBASEAUT13RFN = wsumBDBASEAUT13RFN;
   BDBASEAUT13RFC = wsumBDBASEAUT13RFC;
   BDBASEAUT13 = wsumBDBASEAUT13;
   BDBASEAUTC13 = wsumBDBASEAUTC13;
   BDBASEFPASFN = wsumBDBASEFPASFN;
   BDBASEFPASFC = wsumBDBASEFPASFC;
   BDBASEFPASFERFN = wsumBDBASEFPASFERFN;
   BDBASEFPASFERFC = wsumBDBASEFPASFERFC;
   BDBASEFPAS13RFN = wsumBDBASEFPAS13RFN;
   BDBASEFPAS13RFC = wsumBDBASEFPAS13RFC;
   BDBASEFPAS13 = wsumBDBASEFPAS13;
   BDBASEFPASC13 = wsumBDBASEFPASC13;
   BDBASERATAPOFN = wsumBDBASERATAPOFN;
   BDBASERATAPOFC = wsumBDBASERATAPOFC;
   BDBASERATAPOFERFN = wsumBDBASERATAPOFERFN;
   BDBASERATAPOFERFC = wsumBDBASERATAPOFERFC;
   BDBASERATAPO13RFN = wsumBDBASERATAPO13RFN;
   BDBASERATAPO13RFC = wsumBDBASERATAPO13RFC;
   BDBASERATAPO13 = wsumBDBASERATAPO13;
   BDBASERATAPOC13 = wsumBDBASERATAPOC13;

   IF (WEXISTE = 1) THEN
     SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_DADOS_IND_CALC_GPS */
create or alter procedure VRHF_SP_DADOS_IND_CALC_GPS (
    PRCODEMP varchar(22000),
    PRCODCOL varchar(32000),
    PRCODAUT varchar(10000),
    PRTIPOCOL integer,
    PRANOMES integer,
    PRANOMESPAG integer,
    PRTIPOEMISSAO integer,
    PRTIPOGPS integer,
    PRPUXAFILIAIS integer,
    PRAPENASGPS integer)
returns (
    BDCODCENTRO integer,
    BDTIPO integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODTER integer,
    BDREFFN integer,
    BDREFPAG integer,
    BDCODTPCC integer,
    BDTOTSEG numeric(15,6),
    BDTOTBASE numeric(15,6),
    BDSEGFUN numeric(15,6),
    BDBASEFUN numeric(15,6),
    BDPERCFUN numeric(15,6),
    BDSEGPRO numeric(15,6),
    BDBASEPRO numeric(15,6),
    BDPERCPRO numeric(15,6),
    BDBASEAUT numeric(15,6),
    BDSEGAUT numeric(15,6),
    BDPERCAUT numeric(15,6),
    BDBASERATAPO numeric(15,6),
    BDVALORRATAPO numeric(15,6),
    BDSALFAM numeric(15,6),
    BDSALMATERNIDADE numeric(15,6),
    BDBASEFPAS numeric(15,6),
    BDPERCFPAS numeric(15,6),
    BDPERCRAT numeric(15,6),
    BDVALOUTENTIDADE numeric(15,6),
    BDSIMPLESGPS integer,
    BDCODENQFED integer,
    BDDESCENQFED varchar(10),
    BDCODTOMADOR integer,
    BDBASEFUNFN numeric(15,6),
    BDBASEFUNFC numeric(15,6),
    BDBASEFUNFERFN numeric(15,6),
    BDBASEFUNFERFC numeric(15,6),
    BDBASEFUN13RFN numeric(15,6),
    BDBASEFUN13RFC numeric(15,6),
    BDBASEFUN13 numeric(15,6),
    BDBASEFUNC13 numeric(15,6),
    BDBASEPROFN numeric(15,6),
    BDBASEPROFC numeric(15,6),
    BDBASEPROFERFN numeric(15,6),
    BDBASEPROFERFC numeric(15,6),
    BDBASEPRO13RFN numeric(15,6),
    BDBASEPRO13RFC numeric(15,6),
    BDBASEPRO13 numeric(15,6),
    BDBASEPROC13 numeric(15,6),
    BDBASEAUTFN numeric(15,6),
    BDBASEAUTFC numeric(15,6),
    BDBASEAUTFERFN numeric(15,6),
    BDBASEAUTFERFC numeric(15,6),
    BDBASEAUT13RFN numeric(15,6),
    BDBASEAUT13RFC numeric(15,6),
    BDBASEAUT13 numeric(15,6),
    BDBASEAUTC13 numeric(15,6),
    BDBASEFPASFN numeric(15,6),
    BDBASEFPASFC numeric(15,6),
    BDBASEFPASFERFN numeric(15,6),
    BDBASEFPASFERFC numeric(15,6),
    BDBASEFPAS13RFN numeric(15,6),
    BDBASEFPAS13RFC numeric(15,6),
    BDBASEFPAS13 numeric(15,6),
    BDBASEFPASC13 numeric(15,6),
    BDBASERATAPOFN numeric(15,6),
    BDBASERATAPOFC numeric(15,6),
    BDBASERATAPOFERFN numeric(15,6),
    BDBASERATAPOFERFC numeric(15,6),
    BDBASERATAPO13RFN numeric(15,6),
    BDBASERATAPO13RFC numeric(15,6),
    BDBASERATAPO13 numeric(15,6),
    BDBASERATAPOC13 numeric(15,6))
as
declare variable WSCODEMP integer;
declare variable WEXISTE integer;
declare variable WCODTER integer;
declare variable WCODCOL integer;
declare variable WCASEAUT varchar(300);
declare variable WCASEPRO varchar(300);
declare variable WCASEFUN varchar(300);
declare variable WTIPOFUN varchar(4);
declare variable WCAMPOEMP varchar(1000);
declare variable WAUXCAMPO varchar(10);
declare variable WAUXWHEREEMP varchar(32000);
declare variable WAUXWHEREFUN varchar(32000);
declare variable WSQL varchar(32000);
declare variable WAUX numeric(15,6);
declare variable WSQLFROM varchar(32000);
declare variable WTPCC integer;
declare variable WTPCCANT integer;
declare variable WCODTOMADOR integer;
declare variable WCODTOMADORANT integer;
declare variable WEMPRESAANT integer;
declare variable WBDTOTSEG numeric(15,6);
declare variable WBDTOTBASE numeric(15,6);
declare variable WSUMTOTSEG numeric(15,6);
declare variable WSUMTOTBASE numeric(15,6);
declare variable WBDSEGFUN numeric(15,6);
declare variable WBDBASEFUN numeric(15,6);
declare variable WBDPERCFUN numeric(15,6);
declare variable WSUMSEGFUN numeric(15,6);
declare variable WSUMBASEFUN numeric(15,6);
declare variable WSUMPERCFUN numeric(15,6);
declare variable WBDSEGPRO numeric(15,6);
declare variable WBDBASEPRO numeric(15,6);
declare variable WBDPERCPRO numeric(15,6);
declare variable WSUMSEGPRO numeric(15,6);
declare variable WSUMBASEPRO numeric(15,6);
declare variable WSUMPERCPRO numeric(15,6);
declare variable WBDSEGAUT numeric(15,6);
declare variable WBDBASEAUT numeric(15,6);
declare variable WBDPERCAUT numeric(15,6);
declare variable WSUMSEGAUT numeric(15,6);
declare variable WSUMBASEAUT numeric(15,6);
declare variable WSUMPERCAUT numeric(15,6);
declare variable WBDBASERATAPO numeric(15,6);
declare variable WBDVALORRATAPO numeric(15,6);
declare variable WSUMBASERATAPO numeric(15,6);
declare variable WSUMVALORRATAPO numeric(15,6);
declare variable WBDSALFAM numeric(15,6);
declare variable WBDSALMATERNIDADE numeric(15,6);
declare variable WSUMSALFAM numeric(15,6);
declare variable WSUMSALMATERNIDADE numeric(15,6);
declare variable WBDBASEFPAS numeric(15,6);
declare variable WBDPERCFPAS numeric(15,6);
declare variable WSUMBASEFPAS numeric(15,6);
declare variable WSUMPERCFPAS numeric(15,6);
declare variable WBDPERCRAT numeric(15,6);
declare variable WBDVALOUTENTIDADE numeric(15,6);
declare variable WSUMPERCRAT numeric(15,6);
declare variable WSUMVALOUTENTIDADE numeric(15,6);
declare variable WBDSIMPLESGPS integer;
declare variable WBDCODENQFED integer;
declare variable WBDDESCENQFED varchar(10);
declare variable WSUMSIMPLESGPS integer;
declare variable WSUMCODENQFED integer;
declare variable WSUMDESCENQFED varchar(10);
declare variable WGERAGUIA integer;
declare variable WEMISSAO integer;
declare variable WBDBASEFUNFN numeric(15,6);
declare variable WBDBASEFUNFERFN numeric(15,6);
declare variable WBDBASEFUN13RFN numeric(15,6);
declare variable WBDBASEFUNFC numeric(15,6);
declare variable WBDBASEFUNFERFC numeric(15,6);
declare variable WBDBASEFUN13RFC numeric(15,6);
declare variable WBDBASEFUN13 numeric(15,6);
declare variable WBDBASEFUNC13 numeric(15,6);
declare variable WSUMBDBASEFUNFN numeric(15,6);
declare variable WSUMBDBASEFUNFERFN numeric(15,6);
declare variable WSUMBDBASEFUN13RFN numeric(15,6);
declare variable WSUMBDBASEFUNFC numeric(15,6);
declare variable WSUMBDBASEFUNFERFC numeric(15,6);
declare variable WSUMBDBASEFUN13RFC numeric(15,6);
declare variable WSUMBDBASEFUN13 numeric(15,6);
declare variable WSUMBDBASEFUNC13 numeric(15,6);
declare variable WBDBASEPROFN numeric(15,6);
declare variable WBDBASEPROFERFN numeric(15,6);
declare variable WBDBASEPRO13RFN numeric(15,6);
declare variable WBDBASEPROFC numeric(15,6);
declare variable WBDBASEPROFERFC numeric(15,6);
declare variable WBDBASEPRO13RFC numeric(15,6);
declare variable WBDBASEPRO13 numeric(15,6);
declare variable WBDBASEPROC13 numeric(15,6);
declare variable WSUMBDBASEPROFN numeric(15,6);
declare variable WSUMBDBASEPROFERFN numeric(15,6);
declare variable WSUMBDBASEPRO13RFN numeric(15,6);
declare variable WSUMBDBASEPROFC numeric(15,6);
declare variable WSUMBDBASEPROFERFC numeric(15,6);
declare variable WSUMBDBASEPRO13RFC numeric(15,6);
declare variable WSUMBDBASEPRO13 numeric(15,6);
declare variable WSUMBDBASEPROC13 numeric(15,6);
declare variable WBDBASEAUTFN numeric(15,6);
declare variable WBDBASEAUTFERFN numeric(15,6);
declare variable WBDBASEAUT13RFN numeric(15,6);
declare variable WBDBASEAUTFC numeric(15,6);
declare variable WBDBASEAUTFERFC numeric(15,6);
declare variable WBDBASEAUT13RFC numeric(15,6);
declare variable WBDBASEAUT13 numeric(15,6);
declare variable WBDBASEAUTC13 numeric(15,6);
declare variable WSUMBDBASEAUTFN numeric(15,6);
declare variable WSUMBDBASEAUTFERFN numeric(15,6);
declare variable WSUMBDBASEAUT13RFN numeric(15,6);
declare variable WSUMBDBASEAUTFC numeric(15,6);
declare variable WSUMBDBASEAUTFERFC numeric(15,6);
declare variable WSUMBDBASEAUT13RFC numeric(15,6);
declare variable WSUMBDBASEAUT13 numeric(15,6);
declare variable WSUMBDBASEAUTC13 numeric(15,6);
declare variable WBDBASEFPASFN numeric(15,6);
declare variable WBDBASEFPASFERFN numeric(15,6);
declare variable WBDBASEFPAS13RFN numeric(15,6);
declare variable WBDBASEFPASFC numeric(15,6);
declare variable WBDBASEFPASFERFC numeric(15,6);
declare variable WBDBASEFPAS13RFC numeric(15,6);
declare variable WBDBASEFPAS13 numeric(15,6);
declare variable WBDBASEFPASC13 numeric(15,6);
declare variable WSUMBDBASEFPASFN numeric(15,6);
declare variable WSUMBDBASEFPASFERFN numeric(15,6);
declare variable WSUMBDBASEFPAS13RFN numeric(15,6);
declare variable WSUMBDBASEFPASFC numeric(15,6);
declare variable WSUMBDBASEFPASFERFC numeric(15,6);
declare variable WSUMBDBASEFPAS13RFC numeric(15,6);
declare variable WSUMBDBASEFPAS13 numeric(15,6);
declare variable WSUMBDBASEFPASC13 numeric(15,6);
declare variable WBDBASERATAPOFN numeric(15,6);
declare variable WBDBASERATAPOFERFN numeric(15,6);
declare variable WBDBASERATAPO13RFN numeric(15,6);
declare variable WBDBASERATAPOFC numeric(15,6);
declare variable WBDBASERATAPOFERFC numeric(15,6);
declare variable WBDBASERATAPO13RFC numeric(15,6);
declare variable WBDBASERATAPO13 numeric(15,6);
declare variable WBDBASERATAPOC13 numeric(15,6);
declare variable WSUMBDBASERATAPOFN numeric(15,6);
declare variable WSUMBDBASERATAPOFERFN numeric(15,6);
declare variable WSUMBDBASERATAPO13RFN numeric(15,6);
declare variable WSUMBDBASERATAPOFC numeric(15,6);
declare variable WSUMBDBASERATAPOFERFC numeric(15,6);
declare variable WSUMBDBASERATAPO13RFC numeric(15,6);
declare variable WSUMBDBASERATAPO13 numeric(15,6);
declare variable WSUMBDBASERATAPOC13 numeric(15,6);
BEGIN
  /* Procedure Text */
  /* prtipogps
     0 = normal
     1 = folha complementar
     2 = 13 sal
     3 = comp. 13 sal
     4 = prévia de rescisão
  */
  /* prtipoemissao
     0 = por cc
     1 = agrupado
     3 = por tomador (utilizado na SEFIP)
  */
  /* prapenasgps
     0 = apenas gps
     1 = historicos compensacoes/nf/gps
  */
  /* PRPUXAFILIAIS
     0 = Nao
     1 = Sim
  */

  /*
  bdtipo
    0 = contabilizacao
    1 = para calculo da gps
    2 = individual
  */

  IF (prtipogps IS NULL) THEN
     prtipogps = 0;

  wauxwhereemp = prcodemp;
  IF (prcodemp IS NULL) THEN
     prcodemp = 'null';
  ELSE
     BEGIN
       wauxwhereemp =  'calc.'||SUBSTRING(prcodemp FROM 8);
       prcodemp = ''''||prcodemp||'''';
     END

  wauxwherefun = prcodcol;
--  wauxwhereaut = prcodaut;

  wtipofun = prtipocol;
  IF (prtipocol IS NULL) THEN
     wtipofun = '0';

  IF (prcodcol IS NULL) THEN
     prcodcol = 'null';
  ELSE
     prcodcol = ''''||prcodcol||'''';

  IF (pranomes IS NULL) THEN
     pranomes = 0;

  wemissao = prtipoemissao;
  prtipoemissao = 0;

  IF (prpuxafiliais IS NULL) THEN
     prpuxafiliais = 0;

  IF (prpuxafiliais = 0) THEN
     wcampoemp = 'calc.bdcodemp xbdcodemp';
  ELSE
     wcampoemp = 'case when temp.bdcodmatriz is not null then temp.bdcodmatriz else temp.bdcodemp end xbdcodemp';

  IF (pranomespag IS NULL) THEN
     pranomespag = pranomes;

  EXECUTE PROCEDURE sp_seta_competencia(pranomes,NULL,NULL);

  wauxcampo = '13';
  IF (prtipogps = 2) THEN
     wauxcampo = '13';
  ELSE IF (prtipogps = 3) THEN
     wauxcampo = 'C13';

  IF (prtipogps IN (0,4)) THEN
     wcasefun = 'calc.bdgrupocla in (1,4,5,7,8)';
  ELSE
     wcasefun = 'f.bdgrupocla in (1,4,5,7,8)';

  IF (prtipogps IN (0,4)) THEN
     WCASEPRO = 'calc.bdgrupocla in (2)';
  ELSE
     WCASEPRO = 'f.bdgrupocla in (2)';

  IF (prtipogps IN (0,4)) THEN
     WCASEAUT = 'calc.bdgrupocla in (3,6)';
  ELSE
     WCASEAUT = 'f.bdgrupocla in (3,6)';

  /* Procedure Text */
  IF (prtipogps IN (0,4)) THEN
     wsql = 'select '||wcampoemp||',calc.bdreffn, calc.bdreffn, calc.bdcodcentro, calc.bdcodtpcc, ';
--  ELSE IF (prtipogps = 4) THEN
--     wsql = 'select '||wcampoemp||','||pranomes||' bdreffn, calc.bdreffn, calc.bdcodcentro, calc.bdcodtpcc, ';
  ELSE IF (prtipogps = 1) THEN
     wsql = 'select '||wcampoemp||',calc.bdreffn, calc.BDREFCOMP, calc.bdcodcentro, calc.bdcodtpcc,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = 'select '||wcampoemp||', calc.bdref13,'||
            ' calc.bdref13 refpag, cast(null as integer), cast(null as integer),';

       /*totais*/
  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' coalesce(calc.bdinssfn,0)+coalesce(calc.bdinssfefolfn,0)+coalesce(calc.bdinss13fn,0)  totSeg,'||
       ' coalesce(calc.bdbinssfn,0)+coalesce(calc.bdbinssfefolfn,0)+coalesce(calc.bdbinss13fn,0)  totBase,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||'  coalesce(calc.bdinssfc,0)+coalesce(calc.bdinssfefolfc,0)+coalesce(calc.bdinss13fc,0)  totSeg,'||
       ' coalesce(calc.bdbinssfc,0)+coalesce(calc.bdbinssfefolfc,0)+coalesce(calc.bdbinss13fc,0)  totBase,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||'  coalesce(calc.bdvalorinss'||wauxcampo||',0)  totSeg,'||
       '  coalesce(calc.bdbaseinss'||wauxcampo||',0)  totBase,';

       /*colaboradores*/
  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' case when ('||wcasefun||') then'||
       ' (coalesce(calc.bdinssfn,0)+coalesce(calc.bdinssfefolfn,0)+coalesce(calc.bdinss13fn,0))'||
       ' else 0 end SEGFUN,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||' case when ('||wcasefun||') then'||
       ' (coalesce(calc.bdinssfc,0)+coalesce(calc.bdinssfefolfc,0)+coalesce(calc.bdinss13fc,0))'||
       ' else 0 end SEGFUN,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||' case when ('||wcasefun||') then'||
       ' (coalesce(calc.bdvalorinss'||wauxcampo||',0))'||
       ' else 0 end SEGFUN,';

  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' case when ('||wcasefun||') then'||
       ' (coalesce(calc.bdbinssfn,0)+coalesce(calc.bdbinssfefolfn,0)+coalesce(calc.bdbinss13fn,0))'||
       ' else 0 end BaseFun,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||' case when ('||wcasefun||') then'||
       ' (coalesce(calc.bdbinssfc,0)+coalesce(calc.bdbinssfefolfc,0)+coalesce(calc.bdbinss13fc,0))'||
       ' else 0 end BaseFun,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||'   case when ('||wcasefun||') then'||
       ' (coalesce(calc.bdbaseinss'||wauxcampo||',0))'||
       ' else 0 end BaseFun,';

  wsql = wsql||' coalesce(emp.bdfunemp,0) PercFun,';

       /*prolaboristas*/
  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' case when ('||WCASEPRO||') then'||
       ' coalesce(calc.bdinssfn,0)+coalesce(calc.bdinssfefolfn,0)+coalesce(calc.bdinss13fn,0)'||
       ' else 0 end SegPro,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||'   case when ('||WCASEPRO||') then'||
       ' coalesce(calc.bdinssfc,0)+coalesce(calc.bdinssfefolfc,0)+coalesce(calc.bdinss13fc,0)'||
       ' else 0 end SegPro,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||'   case when ('||WCASEPRO||') then'||
       ' coalesce(calc.bdvalorinss'||wauxcampo||',0)'||
       ' else 0 end SegPro,';

  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' case when ('||WCASEPRO||') then'||
       ' (coalesce(calc.bdbinssfn,0)+coalesce(calc.bdbinssfefolfn,0)+coalesce(calc.bdbinss13fn,0))'||
       ' else 0 end BasePro,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||' case when ('||WCASEPRO||') then'||
       ' (coalesce(calc.bdbinssfc,0)+coalesce(calc.bdbinssfefolfc,0)+coalesce(calc.bdbinss13fc,0))'||
       ' else 0 end BasePro,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||'   case when ('||WCASEPRO||') then'||
       ' (coalesce(calc.bdbaseinss'||wauxcampo||',0))'||
       ' else 0 end BasePro,';

  wsql = wsql||' coalesce(emp.bdempemp,0) PercPro,';

       /*autonomos*/
  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' case when ('||WCASEAUT||') then'||
       ' (coalesce(calc.bdinssfn,0)+coalesce(calc.bdinssfefolfn,0)+coalesce(calc.bdinss13fn,0))'||
       ' else 0 end SegAut,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||' case when ('||WCASEAUT||') then'||
       ' (coalesce(calc.bdinssfc,0)+coalesce(calc.bdinssfefolfc,0)+coalesce(calc.bdinss13fc,0))'||
       ' else 0 end SegAut,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||' case when ('||WCASEAUT||') then'||
       ' (coalesce(calc.bdvalorinss'||wauxcampo||',0))'||
       ' else 0 end SegAut,';

  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' case when ('||WCASEAUT||') then'||
       ' (coalesce(calc.bdbinssfn,0)+coalesce(calc.bdbinssfefolfn,0)+coalesce(calc.bdbinss13fn,0))'||
       ' else 0 end BaseAut,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||'   case when ('||WCASEAUT||') then'||
       ' (coalesce(calc.bdbinssfc,0)+coalesce(calc.bdbinssfefolfc,0)+coalesce(calc.bdbinss13fc,0))'||
       ' else 0 end BaseAut,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||' case when ('||WCASEAUT||') then'||
       ' (coalesce(calc.bdbaseinss'||wauxcampo||',0))'||
       ' else 0 end BaseAut,';

  wsql = wsql||' coalesce(emp.bdautemp,0) PercAut,';

       /* rat aposentadoria*/
  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
       ' (coalesce(calc.bdbratapofn,0)+coalesce(calc.bdbratapofefn,0)+coalesce(calc.bdbratapo13fn,0))'||
       ' else 0 end bratapo,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
       ' (coalesce(calc.bdbratapofc,0)+coalesce(calc.bdbratapofefc,0)+coalesce(calc.bdbratapo13fc,0))'||
       ' else 0 end bratapo,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
       ' (coalesce(calc.bdbratapo'||wauxcampo||',0))'||
       ' else 0 end bratapo,';

  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' (select bdvalor from truncar((coalesce(calc.bdbratapofn,0)+coalesce(calc.bdbratapofefn,0)+coalesce(calc.bdbratapo13fn,0))*(coalesce(colgps.bdpercratcol,0)/100),2)) vratapo,';
  ELSE IF (prtipogps = 1) THEN
    wsql = wsql||' (select bdvalor from truncar((coalesce(calc.bdbratapofc,0)+coalesce(calc.bdbratapofefc,0)+coalesce(calc.bdbratapo13fc,0))*(coalesce(colgps.bdpercratcol,0)/100),2)) vratapo,';
  ELSE IF (prtipogps IN (2,3)) THEN
    wsql = wsql||' (select bdvalor from truncar(coalesce(calc.bdbratapo'||wauxcampo||',0)*(coalesce(colgps.bdpercratcol,0)/100),2)) vratapo,';

       /* salario familia*/
  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' coalesce(calc.bdsalfamfn,0) salfam,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||' coalesce(calc.bdsalfamfc,0) salfam,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||' coalesce(calc.bdsalfam'||wauxcampo||',0) salfam,';

       /* salario maternidade */
  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' coalesce(calc.bdsalmatempfn,0) salMaternidade,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||' coalesce(calc.bdsalmatempfc,0) salMaternidade,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||' coalesce(calc.bdsalmatemp'||wauxcampo||',0) salMaternidade,';

       /* base para fpas e rat com ded.fpas*/
  IF (prtipogps IN (0,4)) THEN
     wsql = wsql||' case when ('||wcasefun||') then'||
       ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
       ' (select bdvalor from truncar((coalesce(calc.bdbinssfn,0)+coalesce(calc.bdbinssfefolfn,0)+coalesce(calc.bdbinss13fn,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
       ' else'||
       ' (coalesce(calc.bdbinssfn,0)+coalesce(calc.bdbinssfefolfn,0)+coalesce(calc.bdbinss13fn,0))'||
       ' end'||
       ' else 0 end BASFPAS,';
  ELSE IF (prtipogps = 1) THEN
     wsql = wsql||' case when ('||wcasefun||') then'||
       ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
       ' (select bdvalor from truncar((coalesce(calc.bdbinssfc,0)+coalesce(calc.bdbinssfefolfc,0)+coalesce(calc.bdbinss13fc,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
       ' else'||
       ' (coalesce(calc.bdbinssfc,0)+coalesce(calc.bdbinssfefolfc,0)+coalesce(calc.bdbinss13fc,0))'||
       ' end'||
       ' else 0 end BASFPAS,';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsql = wsql||' case when ('||wcasefun||') then'||
       ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
       ' (select bdvalor from truncar((coalesce(calc.bdbaseinss'||wauxcampo||',0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
       ' else'||
       ' (coalesce(calc.bdbaseinss'||wauxcampo||',0))'||
       ' end'||
       ' else 0 end BASFPAS,';

  wsql = wsql||' coalesce(emp.bdperterc,0) PercFPAS,';

  wsql = wsql||' (select bdvalor from truncar(coalesce(ratemp.bdtaxacnae,0)*(coalesce(emp.bdfap,0)),4)) PercRat, ';

  IF (prtipogps IN (0,4)) THEN
      wsql = wsql||' calc.BDVALOUTENTIDADE valOutentidade, ';
  ELSE
      wsql = wsql||' cast(null as numeric(15,6)) valOutentidade, ';

   wsql = wsql||' DESCFED.BDDESCENQFED,'||
                ' emp.bdsimplesgps,'||
                ' DESCFED.BDCODENQFED,';


   IF (prtipogps IN (0,1,4)) THEN
      wsql = wsql||' toma.bdcodtpcc bdcodtomador,';
   ELSE
      wsql = wsql||' 0 bdcodtomador,';

   IF (prtipogps IN (0,4)) THEN
      wsql = wsql||' calc.bdcodcol, calc.bdcodter, ';
   ELSE
      wsql = wsql||' calc.bdcodcol, cast(null as integer) bdcodter, ';

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

   /* BASE FUN SEPARADO TIPO CALCULO*/
  IF (prtipogps IN (0,4)) THEN  /* Folha normal */
     BEGIN
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' (coalesce(calc.bdbinssfn,0))'||
         ' else 0 end BaseFunFN,';
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' (coalesce(calc.bdbinssfefolfn,0))'||
         ' else 0 end BaseFunFER,';
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' (coalesce(calc.bdbinss13fn,0))'||
         ' else 0 end BaseFun13RFN,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEFUNFN,';
       wsql = wsql||' 0 BASEFUNFER,';
       wsql = wsql||' 0 BASEFUNF13RFN,';
     END

  IF (prtipogps = 1) THEN /* folha complementar */
     BEGIN
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' (coalesce(calc.bdbinssfc,0))'||
         ' else 0 end BaseFunFC,';
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' (coalesce(calc.bdbinssfefolfc,0))'||
         ' else 0 end BaseFunFERFC,';
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' (coalesce(calc.bdbinss13fc,0))'||
         ' else 0 end BaseFun13RFC,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEFUNFC,';
       wsql = wsql||' 0 BASEFUNFERFC,';
       wsql = wsql||' 0 BaseFun13RFC,';
     END

  IF (prtipogps = 2) THEN /* 13 salario */
     BEGIN
       wsql = wsql||'   case when ('||wcasefun||') then'||
                    ' (coalesce(calc.bdbaseinss13,0))'||
                    ' else 0 end BASEFUN13,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEFUN13,';
     END

  IF (prtipogps = 3) THEN /* complemento 13 salario */
     BEGIN
       wsql = wsql||'   case when ('||wcasefun||') then'||
                    ' (coalesce(calc.bdbaseinssc13,0))'||
                    ' else 0 end BASEFUNC13';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEFUNC13';
     END
  wsql = wsql||',';

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

   /* BASE PRO SEPARADO TIPO CALCULO*/
  IF (prtipogps IN (0,4)) THEN  /* Folha normal */
     BEGIN
       wsql = wsql||' case when ('||wcasepro||') then'||
         ' (coalesce(calc.bdbinssfn,0))'||
         ' else 0 end BasePROFN,';
       wsql = wsql||' case when ('||wcasepro||') then'||
         ' (coalesce(calc.bdbinssfefolfn,0))'||
         ' else 0 end BasePROFER,';
       wsql = wsql||' case when ('||wcasepro||') then'||
         ' (coalesce(calc.bdbinss13fn,0))'||
         ' else 0 end BasePRO13RFN,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEPROFN,';
       wsql = wsql||' 0 BASEPROFER,';
       wsql = wsql||' 0 BASEPROF13RFN,';
     END

  IF (prtipogps = 1) THEN /* folha complementar */
     BEGIN
       wsql = wsql||' case when ('||wcasepro||') then'||
         ' (coalesce(calc.bdbinssfc,0))'||
         ' else 0 end BasePROFC,';
       wsql = wsql||' case when ('||wcasepro||') then'||
         ' (coalesce(calc.bdbinssfefolfc,0))'||
         ' else 0 end BasePROFERFC,';
       wsql = wsql||' case when ('||wcasepro||') then'||
         ' (coalesce(calc.bdbinss13fc,0))'||
         ' else 0 end BasePRO13RFC,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEPROFC,';
       wsql = wsql||' 0 BASEPROFERFC,';
       wsql = wsql||' 0 BasePRO13RFC,';
     END

  IF (prtipogps = 2) THEN /* 13 salario */
     BEGIN
       wsql = wsql||'   case when ('||wcasepro||') then'||
                    ' (coalesce(calc.bdbaseinss13,0))'||
                    ' else 0 end BASEPRO13,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEPRO13,';
     END

  IF (prtipogps = 3) THEN /* complemento 13 salario */
     BEGIN
       wsql = wsql||'   case when ('||wcasepro||') then'||
                    ' (coalesce(calc.bdbaseinssc13,0))'||
                    ' else 0 end BASEPROC13';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEPROC13';
     END
  wsql = wsql||',';

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
   /* BASE AUT SEPARADO TIPO CALCULO*/
  IF (prtipogps IN (0,4)) THEN  /* Folha normal */
     BEGIN
       wsql = wsql||' case when ('||wcaseaut||') then'||
         ' (coalesce(calc.bdbinssfn,0))'||
         ' else 0 end BaseAUTFN,';
       wsql = wsql||' case when ('||wcaseaut||') then'||
         ' (coalesce(calc.bdbinssfefolfn,0))'||
         ' else 0 end BaseAUTFER,';
       wsql = wsql||' case when ('||wcaseaut||') then'||
         ' (coalesce(calc.bdbinss13fn,0))'||
         ' else 0 end BaseAUT13RFN,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEAUTFN,';
       wsql = wsql||' 0 BASEAUTFER,';
       wsql = wsql||' 0 BASEAUTF13RFN,';
     END

  IF (prtipogps = 1) THEN /* folha complementar */
     BEGIN
       wsql = wsql||' case when ('||wcaseaut||') then'||
         ' (coalesce(calc.bdbinssfc,0))'||
         ' else 0 end BaseAUTFC,';
       wsql = wsql||' case when ('||wcaseaut||') then'||
         ' (coalesce(calc.bdbinssfefolfc,0))'||
         ' else 0 end BaseAUTFERFC,';
       wsql = wsql||' case when ('||wcaseaut||') then'||
         ' (coalesce(calc.bdbinss13fc,0))'||
         ' else 0 end BaseAUT13RFC,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEAUTFC,';
       wsql = wsql||' 0 BASEAUTFERFC,';
       wsql = wsql||' 0 BaseAUT13RFC,';
     END

  IF (prtipogps = 2) THEN /* 13 salario */
     BEGIN
       wsql = wsql||'   case when ('||wcaseaut||') then'||
                    ' (coalesce(calc.bdbaseinss13,0))'||
                    ' else 0 end BASEAUT13,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEAUT13,';
     END

  IF (prtipogps = 3) THEN /* complemento 13 salario */
     BEGIN
       wsql = wsql||'   case when ('||wcaseaut||') then'||
                    ' (coalesce(calc.bdbaseinssc13,0))'||
                    ' else 0 end BASEAUTC13';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASEAUTC13';
     END
  wsql = wsql||',';
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--  BASE FPAS POR TIPO DE CALCULO
  IF (prtipogps IN (0,4)) THEN
     BEGIN
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
         ' (select bdvalor from truncar((coalesce(calc.bdbinssfn,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
         ' else'||
         ' (coalesce(calc.bdbinssfn,0))'||
         ' end'||
         ' else 0 end BASFPASFN,';
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
         ' (select bdvalor from truncar((coalesce(calc.bdbinssfefolfn,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
         ' else'||
         ' (coalesce(calc.bdbinssfefolfn,0))'||
         ' end'||
         ' else 0 end BASFPASFERFN,';
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
         ' (select bdvalor from truncar((coalesce(calc.bdbinss13fn,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
         ' else'||
         ' (coalesce(calc.bdbinss13fn,0))'||
         ' end'||
         ' else 0 end BASFPAS13RFN,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASFPASFN,';
       wsql = wsql||' 0 BASFPASFERFN,';
       wsql = wsql||' 0 BASFPAS13RFN,';
     END

  IF (prtipogps = 1) THEN
     BEGIN
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
         ' (select bdvalor from truncar((coalesce(calc.bdbinssfc,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
         ' else'||
         ' (coalesce(calc.bdbinssfc,0))'||
         ' end'||
         ' else 0 end BASFPASFC,';
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
         ' (select bdvalor from truncar((coalesce(calc.bdbinssfefolfc,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
         ' else'||
         ' (coalesce(calc.bdbinssfefolfc,0))'||
         ' end'||
         ' else 0 end BASFPASFERFC,';
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
         ' (select bdvalor from truncar((coalesce(calc.bdbinss13fc,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
         ' else'||
         ' (coalesce(calc.bdbinss13fc,0))'||
         ' end'||
         ' else 0 end BASFPAS13RFC,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASFPASFC,';
       wsql = wsql||' 0 BASFPASFERFC,';
       wsql = wsql||' 0 BASFPAS13RFC,';
     END

  IF (prtipogps = 2) THEN
     BEGIN
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
         ' (select bdvalor from truncar((coalesce(calc.bdbaseinss13,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
         ' else'||
         ' (coalesce(calc.bdbaseinss13,0))'||
         ' end'||
         ' else 0 end BASFPAS13,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASFPAS13,';
     END

  IF (prtipogps = 3) THEN
     BEGIN
       wsql = wsql||' case when ('||wcasefun||') then'||
         ' case when coalesce(colgps.bdpercdescfpascol,0) <> 0 then'||
         ' (select bdvalor from truncar((coalesce(calc.bdbaseinssC13,0))*coalesce(colgps.bdpercdescfpascol,0),2))'||
         ' else'||
         ' (coalesce(calc.bdbaseinssC13,0))'||
         ' end'||
         ' else 0 end BASFPASC13';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 BASFPASC13';
     END
  wsql = wsql||',';

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- base rat aposentadoria por tipo de calculo
  IF (prtipogps IN (0,4)) THEN
     BEGIN
       wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
         ' (coalesce(calc.bdbratapofn,0))'||
         ' else 0 end bratapofn,';
       wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
         ' (coalesce(calc.bdbratapofefn,0))'||
         ' else 0 end bratapofefn,';
       wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
         ' (coalesce(calc.bdbratapo13fn,0))'||
         ' else 0 end bratapo13fn,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 bratapofn,';
       wsql = wsql||' 0 bratapofefn,';
       wsql = wsql||' 0 bratapo13fn,';
     END

  IF (prtipogps = 1) THEN
     BEGIN
       wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
         ' (coalesce(calc.bdbratapofc,0))'||
         ' else 0 end bratapofc,';
       wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
         ' (coalesce(calc.bdbratapofefc,0))'||
         ' else 0 end bratapofefc,';
       wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
         ' (coalesce(calc.bdbratapo13fc,0))'||
         ' else 0 end bratapo13fc,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 bratapofc,';
       wsql = wsql||' 0 bratapofefc,';
       wsql = wsql||' 0 bratapo13fc,';
     END

  IF (prtipogps = 2) THEN
     BEGIN
       wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
         ' (coalesce(calc.bdbratapo13,0))'||
         ' else 0 end bratapo13,';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 bratapo13,';
     END

  IF (prtipogps = 3) THEN
     BEGIN
       wsql = wsql||' case when (coalesce(colgps.bdpercratcol,0) <> 0) then'||
         ' (coalesce(calc.bdbratapoc13,0))'||
         ' else 0 end bratapoc13';
     END
  ELSE
     BEGIN
       wsql = wsql||' 0 bratapoc13';
     END

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
  IF (prcodaut IS NULL) THEN
     prcodaut = 'null';
  ELSE
     prcodaut = ''''||prcodaut||'''';


       /*tabelas*/
  IF (prtipogps = 0) THEN
     wsqlfrom = '  from vrhf_sp_calc_fn_aut('||prcodemp||','||prcodcol||','||pranomes||',null,'||prtipoemissao||','||wtipofun||','||prcodaut||') calc'||
       ' left outer join vrh_emp_tcolcon colcon on (colcon.bdcodemp = calc.bdcodemp and colcon.bdcodcol = calc.bdcodcol)'||
--       ' left outer join VW_VRHF_BASE_TEMPGPS emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' join vw_vrhf_base_tempgps_join emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' left outer join vw_vrhf_emp_tcolcon_fgtsgps colgps on (calc.bdcodemp = colgps.bdcodemp and calc.bdcodcol = colgps.bdcodcol)'||
--       ' left outer join vrh_base_tterceiros empfpas on (empfpas.bdcodterc = emp.bdcodterc)'||
--       ' left outer join vw_tempresas_ref empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' join vw_tempresas_ref_join empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' left outer join VW_TCNAE_REF ratemp on (ratemp.bdcodcnae = empref.bdcodcnae)'||
       ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(calc.bdcodtpcc,calc.bdcodcentro, '||pranomes||') toma on (toma.bdcodcencus = calc.bdcodtpcc and toma.bdcodcentro = calc.bdcodcentro)';
  ELSE IF (prtipogps = 4) THEN
     wsqlfrom = '  from vrhf_sp_calc_fn_aut_prev('||prcodemp||','||prcodcol||','||pranomes||',null,'||prtipoemissao||','||wtipofun||','||prcodaut||') calc'||
       ' left outer join vrh_emp_tcolcon colcon on (colcon.bdcodemp = calc.bdcodemp and colcon.bdcodcol = calc.bdcodcol)'||
       ' join vw_vrhf_base_tempgps_join emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' left outer join vw_vrhf_emp_tcolcon_fgtsgps colgps on (calc.bdcodemp = colgps.bdcodemp and calc.bdcodcol = colgps.bdcodcol)'||
       ' join vw_tempresas_ref_join empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' left outer join VW_TCNAE_REF ratemp on (ratemp.bdcodcnae = empref.bdcodcnae)'||
       ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(calc.bdcodtpcc,calc.bdcodcentro,'||pranomes||') toma on (toma.bdcodcencus = calc.bdcodtpcc and toma.bdcodcentro = calc.bdcodcentro)';
  ELSE IF (prtipogps = 1) THEN
     wsqlfrom = ' from vrhf_sp_tfolhacomp('||prcodemp||','||prcodcol||','||pranomes||',null,'||pranomespag||',null,'||prtipoemissao||') calc'||
       ' left outer join vrh_emp_tcolcon colcon on (colcon.bdcodemp = calc.bdcodemp and colcon.bdcodcol = calc.bdcodcol)'||
--       ' left outer join VW_VRHF_BASE_TEMPGPS emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' join vw_vrhf_base_tempgps_join emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' left outer join vw_vrhf_emp_tcolcon_fgtsgps colgps on (calc.bdcodemp = colgps.bdcodemp and calc.bdcodcol = colgps.bdcodcol)'||
--       ' left outer join vrh_base_tterceiros empfpas on (empfpas.bdcodterc = emp.bdcodterc)'||
--       ' left outer join vw_tempresas_ref empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' join vw_tempresas_ref_join empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' left outer join VW_TCNAE_REF ratemp on (ratemp.bdcodcnae = empref.bdcodcnae)'||
       ' join vw_colaboradores_ref_atual f on (calc.bdcodemp = f.bdcodemp and calc.bdcodcol = f.bdcodcol)'||
       ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(calc.bdcodtpcc,calc.bdcodcentro,'||pranomes||') toma on (toma.bdcodcencus = calc.bdcodtpcc and toma.bdcodcentro = calc.bdcodcentro)';
  ELSE IF (prtipogps = 2) THEN
     wsqlfrom = ' from vrhf_emp_t13sal calc'||
       ' left outer join vrh_emp_tcolcon colcon on (colcon.bdcodemp = calc.bdcodemp and colcon.bdcodcol = calc.bdcodcol)'||
--       ' left outer join VW_VRHF_BASE_TEMPGPS emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' join vw_vrhf_base_tempgps_join emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' left outer join vw_vrhf_emp_tcolcon_fgtsgps colgps on (calc.bdcodemp = colgps.bdcodemp and calc.bdcodcol = colgps.bdcodcol)'||
--       ' left outer join vrh_base_tterceiros empfpas on (empfpas.bdcodterc = emp.bdcodterc)'||
--       ' left outer join vw_tempresas_ref empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' join vw_tempresas_ref_join empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' left outer join VW_TCNAE_REF ratemp on (ratemp.bdcodcnae = empref.bdcodcnae)'||
       ' join vw_colaboradores_ref_atual f on (calc.bdcodemp = f.bdcodemp and calc.bdcodcol = f.bdcodcol)';
  ELSE IF (prtipogps = 3) THEN
     wsqlfrom = ' from vrhf_emp_tc13sal calc'||
       ' left outer join vrh_emp_tcolcon colcon on (colcon.bdcodemp = calc.bdcodemp and colcon.bdcodcol = calc.bdcodcol)'||
--       ' left outer join VW_VRHF_BASE_TEMPGPS emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' join vw_vrhf_base_tempgps_join emp on (calc.bdcodemp = emp.bdcodemp)'||
       ' left outer join vw_vrhf_emp_tcolcon_fgtsgps colgps on (calc.bdcodemp = colgps.bdcodemp and calc.bdcodcol = colgps.bdcodcol)'||
--       ' left outer join vrh_base_tterceiros empfpas on (empfpas.bdcodterc = emp.bdcodterc)'||
--       ' left outer join vw_tempresas_ref empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' join vw_tempresas_ref_join empref on (calc.bdcodemp = empref.bdcodemp)'||
       ' left outer join VW_TCNAE_REF ratemp on (ratemp.bdcodcnae = empref.bdcodcnae)'||
       ' join vw_colaboradores_ref_atual f on (calc.bdcodemp = f.bdcodemp and calc.bdcodcol = f.bdcodcol)';

  wsqlfrom = wsqlfrom||' join tempresas temp on (calc.bdcodemp = temp.bdcodemp)';
  wsqlfrom = wsqlfrom||' left outer join vw_tenqfed TENQ on (TENQ.bdcodemp = temp.bdcodemp)';
  wsqlfrom = wsqlfrom||' left outer join TCADENQFED DESCFED on (TENQ.BDCODENQFED = DESCFED.BDCODENQFED)';

  /* monta where quando necessario */
    waux = 0;
    IF (wauxwhereemp IS NOT NULL) THEN
      BEGIN
        wsqlfrom = wsqlfrom||'  where ';
        waux = 1;
        wsqlfrom = wsqlfrom||wauxwhereemp;
      END
    
  IF (prtipogps NOT IN (0,4)) THEN
     BEGIN
       IF (wauxwherefun IS NOT NULL) THEN
         BEGIN
           IF (waux = 0) THEN
              wsqlfrom = wsqlfrom||'  where ';
           ELSE
              wsqlfrom = wsqlfrom||' and ';
       
           waux = 1;
           wsqlfrom = wsqlfrom||wauxwherefun;
         END
     END

  IF (prtipogps IN (3)) THEN
     BEGIN
       IF (waux = 0) THEN
          wsqlfrom = wsqlfrom||'  where ';
       ELSE
          wsqlfrom = wsqlfrom||' and ';
       waux = CAST(SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 1 FOR 4)||'01' AS INTEGER);
       wsqlfrom = wsqlfrom||' calc.bdref13 >= '||waux;
       waux = CAST(SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 1 FOR 4)||'12' AS INTEGER);
       wsqlfrom = wsqlfrom||' and calc.bdref13 <= '||waux;
     END
  ELSE IF (prtipogps IN (2)) THEN
     BEGIN
       IF (waux = 0) THEN
          wsqlfrom = wsqlfrom||'  where ';
       ELSE
          wsqlfrom = wsqlfrom||' and ';
       wsqlfrom = wsqlfrom||' calc.bdref13 = '||pranomes;
     END

       /* group by */
  IF (prtipogps IN (0,4)) THEN
     wsqlfrom = wsqlfrom||'  order by xbdcodemp, calc.bdreffn, toma.bdcodtpcc, calc.bdcodtpcc, DESCFED.BDDESCENQFED';
  ELSE IF (prtipogps = 1) THEN
     wsqlfrom = wsqlfrom||'  order by xbdcodemp, calc.bdreffn, calc.BDREFCOMP, toma.bdcodtpcc, calc.bdcodtpcc, DESCFED.BDDESCENQFED';
  ELSE IF (prtipogps IN (2,3)) THEN
     wsqlfrom = wsqlfrom||'  order by xbdcodemp, cast(substring(cast(calc.bdref13 as varchar(6)) from 1 for 4)||'||''''||'13'||''''||' as integer), DESCFED.BDDESCENQFED';

  wcodtomadorant = -1;
  wsumtotSeg = 0;
  wsumtotBase = 0;
  wSUMSEGFUN = 0;
  wSUMBaseFun = 0;
  wSUMPercFun = 0;
  wSumSegPro = 0;
  wSumBasePro = 0;
  wSumPercPro = 0;
  wSumSegAut = 0;
  wSumBaseAut = 0;
  wSumPercAut = 0;
  wSumbaseratapo = 0;
  wSumvalorratapo = 0;
  wSumsalfam = 0;
  wSumsalmaternidade = 0;
  wSumbasefpas = 0;
  wSumpercfpas = 0;
  wSumpercrat = 0;
  wSumVALOUTENTIDADE = 0;
  wSumdescenqfed = NULL;
  wSumsimplesgps = NULL;
  wSumcodenqfed = NULL;

  wSumbdBASEFUNFN = 0;
  wSumbdbasefunferfn  = 0;
  wSumbdBASEFUN13RFN  = 0;
  wSumbdBASEFUNFC  = 0;
  wSumbdBASEFUNFERFC = 0;
  wSumbdBaseFun13RFC = 0;
  wSumbdBASEFUN13 = 0;
  wSumbdBASEFUNC13 = 0;

  wSumbdBASEPROFN = 0;
  wSumbdbasePROferfn  = 0;
  wSumbdBASEPRO13RFN  = 0;
  wSumbdBASEPROFC  = 0;
  wSumbdBASEPROFERFC = 0;
  wSumbdBasePRO13RFC = 0;
  wSumbdBASEPRO13 = 0;
  wSumbdBASEPROC13 = 0;

  wSumbdBASEAUTFN = 0;
  wSumbdbaseAUTferfn  = 0;
  wSumbdBASEAUT13RFN  = 0;
  wSumbdBASEAUTFC  = 0;
  wSumbdBASEAUTFERFC = 0;
  wSumbdBaseAUT13RFC = 0;
  wSumbdBASEAUT13 = 0;
  wSumbdBASEAUTC13 = 0;

  wSumbdBASEFPASFN = 0;
  wSumbdbaseFPASferfn  = 0;
  wSumbdBASEFPAS13RFN  = 0;
  wSumbdBASEFPASFC  = 0;
  wSumbdBASEFPASFERFC = 0;
  wSumbdBaseFPAS13RFC = 0;
  wSumbdBASEFPAS13 = 0;
  wSumbdBASEFPASC13 = 0;

  wSumbdBASERATAPOFN = 0;
  wSumbdbaseRATAPOferfn  = 0;
  wSumbdBASERATAPO13RFN  = 0;
  wSumbdBASERATAPOFC  = 0;
  wSumbdBASERATAPOFERFC = 0;
  wSumbdBaseRATAPO13RFC = 0;
  wSumbdBASERATAPO13 = 0;
  wSumbdBASERATAPOC13 = 0;

  wtpccant = -1;
  WEXISTE = 0;
  FOR EXECUTE STATEMENT wsql||wsqlfrom INTO
      : bdcodemp,
      : bdreffn,
      : bdrefpag,
      : bdcodcentro,
      : wtpcc,

      /*totais*/
      : wbdtotSeg,
      : wbdtotBase,

      /*colaboradores*/
      : wbdSEGFUN,
      : wbdBaseFun,
      : wbdPercFun,

       /*prolaboristas*/
      : wbdSegPro,
      : wbdBasePro,
      : wbdPercPro,

      /*autonomos*/
      : wbdSegAut,
      : wbdBaseAut,
      : wbdPercAut,

      /* rat aposentadoria*/
      : wbdbaseratapo,
      : wbdvalorratapo,

      : wbdsalfam,
      : wbdsalmaternidade,

      /* base fpas*/
      : wbdbasefpas,
      : wbdpercfpas,

      /* rat */
      : wbdpercrat,
      : wBDVALOUTENTIDADE,

      : wbddescenqfed,
      : wbdsimplesgps,
      : wbdcodenqfed,
      : wcodtomador,

      : wcodcol,
      : wcodter,

      : wbdBASEFUNFN,
      : wbdbasefunferfn,
      : wbdBASEFUN13RFN,
      : wbdBASEFUNFC,
      : wbdBASEFUNFERFC,
      : wbdBaseFun13RFC,
      : wbdBASEFUN13,
      : wbdBASEFUNC13,

      : wbdBASEPROFN,
      : wbdbasePROferfn,
      : wbdBASEPRO13RFN,
      : wbdBASEPROFC,
      : wbdBASEPROFERFC,
      : wbdBasePRO13RFC,
      : wbdBASEPRO13,
      : wbdBASEPROC13,

      : wbdBASEAUTFN,
      : wbdbaseAUTferfn,
      : wbdBASEAUT13RFN,
      : wbdBASEAUTFC,
      : wbdBASEAUTFERFC,
      : wbdBaseAUT13RFC,
      : wbdBASEAUT13,
      : wbdBASEAUTC13,

      : wbdBASEFPASFN,
      : wbdbaseFPASferfn,
      : wbdBASEFPAS13RFN,
      : wbdBASEFPASFC,
      : wbdBASEFPASFERFC,
      : wbdBaseFPAS13RFC,
      : wbdBASEFPAS13,
      : wbdBASEFPASC13,

      : wbdBASERATAPOFN,
      : wbdbaseRATAPOferfn,
      : wbdBASERATAPO13RFN,
      : wbdBASERATAPOFC,
      : wbdBASERATAPOFERFC,
      : wbdBaseRATAPO13RFC,
      : wbdBASERATAPO13,
      : wbdBASERATAPOC13
      DO
  BEGIN
    WEXISTE = 1;
    bdcodter = NULL;
    bdcodcol = NULL;
    IF (wtpcc IS NULL) THEN
       wtpcc = 0;

    IF (wcodtomador IS NULL) THEN
       wcodtomador = 0;

    wgeraguia = 0;
    IF ((wemissao IS NULL) OR (wemissao = 1)) THEN
       BEGIN
         IF ((wempresaant <> bdcodemp) AND (wcodtomadorant <> -1)) THEN
            wgeraguia = 1;
       END
    ELSE
       BEGIN
         IF (((wempresaant <> bdcodemp) OR (wcodtomadorant <> wcodtomador) OR (wtpccant <> wtpcc)) AND (wcodtomadorant <> -1)) THEN
            wgeraguia = 1;
       END

    IF (wgeraguia = 1) THEN
       BEGIN
         bdtipo = 0;
         bdcodcol = NULL;
--         wcodtomador = bdcodtomador;
         IF (wcodtomadorant = 0) THEN
            bdcodtomador = NULL;
         ELSE
            bdcodtomador = wcodtomadorant;

         IF (wtpccant = 0) THEN
            bdcodtpcc = NULL;
         ELSE
            bdcodtpcc = wtpccant;

         WSCODEMP = bdcodemp;
         bdcodemp = wempresaant;

         bdtotSeg = wsumtotSeg;
         bdtotBase = wsumtotBase;
         bdSEGFUN = wSUMSEGFUN;
         bdBaseFun = wSUMBaseFun;
         bdPercFun = wSUMPercFun;
         bdSegPro = wSumSegPro;
         bdBasePro = wSumBasePro;
         bdPercPro = wSumPercPro;
         bdSegAut = wSumSegAut;
         bdBaseAut = wSumBaseAut;
         bdPercAut = wSumPercAut;
         bdbaseratapo = wSumbaseratapo;
         bdvalorratapo = wSumvalorratapo;
         bdsalfam = wSumsalfam;
         bdsalmaternidade = wSumsalmaternidade;
         bdbasefpas = wSumbasefpas;
         bdpercfpas = wSumpercfpas;
         bdpercrat = wSumpercrat;
         BDVALOUTENTIDADE = wSumVALOUTENTIDADE;
         bddescenqfed = wSumdescenqfed;
         bdsimplesgps = wSumsimplesgps;
         bdcodenqfed = wSumcodenqfed;

         bdBASEFUNFN = wSumbdBASEFUNFN;
         bdbasefunferfn = wSumbdbasefunferfn;
         bdBASEFUN13RFN = wSumbdBASEFUN13RFN;
         bdBASEFUNFC = wSumbdBASEFUNFC;
         bdBASEFUNFERFC = wSumbdBASEFUNFERFC;
         bdBaseFun13RFC = wSumbdBaseFun13RFC;
         bdBASEFUN13 = wSumbdBASEFUN13;
         bdBASEFUNC13 = wSumbdBASEFUNC13;

         bdBASEPROFN    = wSumbdBASEPROFN;
         bdbasePROferfn = wSumbdbasePROferfn;
         bdBASEPRO13RFN = wSumbdBASEPRO13RFN;
         bdBASEPROFC    = wSumbdBASEPROFC;
         bdBASEPROFERFC = wSumbdBASEPROFERFC;
         bdBasePRO13RFC = wSumbdBasePRO13RFC;
         bdBASEPRO13    = wSumbdBASEPRO13;
         bdBASEPROC13   = wSumbdBASEPROC13;

         bdBASEAUTFN    = wSumbdBASEAUTFN;
         bdbaseAUTferfn = wSumbdbaseAUTferfn;
         bdBASEAUT13RFN = wSumbdBASEAUT13RFN;
         bdBASEAUTFC    = wSumbdBASEAUTFC;
         bdBASEAUTFERFC = wSumbdBASEAUTFERFC;
         bdBaseAUT13RFC = wSumbdBaseAUT13RFC;
         bdBASEAUT13    = wSumbdBASEAUT13;
         bdBASEAUTC13   = wSumbdBASEAUTC13;

         bdBASEFPASFN    = wSumbdBASEFPASFN;
         bdbaseFPASferfn = wSumbdbaseFPASferfn;
         bdBASEFPAS13RFN = wSumbdBASEFPAS13RFN;
         bdBASEFPASFC    = wSumbdBASEFPASFC;
         bdBASEFPASFERFC = wSumbdBASEFPASFERFC;
         bdBaseFPAS13RFC = wSumbdBaseFPAS13RFC;
         bdBASEFPAS13    = wSumbdBASEFPAS13;
         bdBASEFPASC13   = wSumbdBASEFPASC13;

         bdBASERATAPOFN    = wSumbdBASERATAPOFN;
         bdbaseRATAPOferfn = wSumbdbaseRATAPOferfn;
         bdBASERATAPO13RFN = wSumbdBASERATAPO13RFN;
         bdBASERATAPOFC    = wSumbdBASERATAPOFC;
         bdBASERATAPOFERFC = wSumbdBASERATAPOFERFC;
         bdBaseRATAPO13RFC = wSumbdBaseRATAPO13RFC;
         bdBASERATAPO13    = wSumbdBASERATAPO13;
         bdBASERATAPOC13   = wSumbdBASERATAPOC13;

         SUSPEND;

         bdcodemp = WSCODEMP;

         wsumtotbase = 0;
         wsumtotseg = 0;
         wSUMSEGFUN = 0;
         wSUMBaseFun = 0;
         wSUMPercFun = 0;
         wSumSegPro = 0;
         wSumBasePro = 0;
         wSumPercPro = 0;
         wSumSegAut = 0;
         wSumBaseAut = 0;
         wSumPercAut = 0;
         wSumbaseratapo = 0;
         wSumvalorratapo = 0;
         wSumsalfam = 0;
         wSumsalmaternidade = 0;
         wSumbasefpas = 0;
         wSumpercfpas = 0;
         wSumpercrat = 0;
         wSumVALOUTENTIDADE = 0;
         wSumdescenqfed = NULL;
         wSumsimplesgps = NULL;
         wSumcodenqfed = NULL;

         wSumbdBASEFUNFN = 0;
         wSumbdbasefunferfn  = 0;
         wSumbdBASEFUN13RFN  = 0;
         wSumbdBASEFUNFC  = 0;
         wSumbdBASEFUNFERFC = 0;
         wSumbdBaseFun13RFC = 0;
         wSumbdBASEFUN13 = 0;
         wSumbdBASEFUNC13 = 0;

         wSumbdBASEPROFN = 0;
         wSumbdbasePROferfn  = 0;
         wSumbdBASEPRO13RFN  = 0;
         wSumbdBASEPROFC  = 0;
         wSumbdBASEPROFERFC = 0;
         wSumbdBasePRO13RFC = 0;
         wSumbdBASEPRO13 = 0;
         wSumbdBASEPROC13 = 0;

         wSumbdBASEAUTFN = 0;
         wSumbdbaseAUTferfn  = 0;
         wSumbdBASEAUT13RFN  = 0;
         wSumbdBASEAUTFC  = 0;
         wSumbdBASEAUTFERFC = 0;
         wSumbdBaseAUT13RFC = 0;
         wSumbdBASEAUT13 = 0;
         wSumbdBASEAUTC13 = 0;

         wSumbdBASEFPASFN = 0;
         wSumbdbaseFPASferfn  = 0;
         wSumbdBASEFPAS13RFN  = 0;
         wSumbdBASEFPASFC  = 0;
         wSumbdBASEFPASFERFC = 0;
         wSumbdBaseFPAS13RFC = 0;
         wSumbdBASEFPAS13 = 0;
         wSumbdBASEFPASC13 = 0;

         wSumbdBASERATAPOFN = 0;
         wSumbdbaseRATAPOferfn  = 0;
         wSumbdBASERATAPO13RFN  = 0;
         wSumbdBASERATAPOFC  = 0;
         wSumbdBASERATAPOFERFC = 0;
         wSumbdBaseRATAPO13RFC = 0;
         wSumbdBASERATAPO13 = 0;
         wSumbdBASERATAPOC13 = 0;
       END

    wsumtotbase = wsumtotbase + wbdtotBase;
    wsumtotseg = wsumtotseg + wbdtotseg;
    wSUMSEGFUN = wSUMSEGFUN + wbdSEGFUN;
    wSUMBaseFun = wSUMBaseFun + wbdBaseFun;
    wSUMPercFun = wbdPercFun;
    wSumSegPro = wSumSegPro + wbdSegPro;
    wSumBasePro = wSumBasePro + wbdBasePro;
    wSumPercPro = wbdPercPro;
    wSumSegAut = wSumSegAut + wbdSegAut;
    wSumBaseAut = wSumBaseAut + wbdBaseAut;
    wSumPercAut = wbdPercAut;
    wSumbaseratapo = wSumbaseratapo + wbdbaseratapo;
    wSumvalorratapo = wSumvalorratapo + wbdvalorratapo;
    wSumsalfam = wSumsalfam + wbdsalfam;
    wSumsalmaternidade = wSumsalmaternidade + wbdsalmaternidade;
    wSumbasefpas = wSumbasefpas + wbdbasefpas;
    wSumpercfpas = wbdpercfpas;
    wSumpercrat = wbdpercrat;
    wsumvaloutentidade = wsumvaloutentidade + wbdvaloutentidade;
    wsumdescenqfed = wbddescenqfed;
    wsumsimplesgps = wbdsimplesgps;
    wsumcodenqfed = wbdcodenqfed;

    wSumbdBASEFUNFN = wSumbdBASEFUNFN + wbdBASEFUNFN;
    wSumbdbasefunferfn  = wSumbdbasefunferfn  + wbdbasefunferfn;
    wSumbdBASEFUN13RFN  = wSumbdBASEFUN13RFN  + wbdBASEFUN13RFN;
    wSumbdBASEFUNFC  = wSumbdBASEFUNFC  + wbdBASEFUNFC;
    wSumbdBASEFUNFERFC = wSumbdBASEFUNFERFC + wbdBASEFUNFERFC;
    wSumbdBaseFun13RFC = wSumbdBaseFun13RFC + wbdBaseFun13RFC;
    wSumbdBASEFUN13 = wSumbdBASEFUN13 + wbdBASEFUN13;
    wSumbdBASEFUNC13 = wSumbdBASEFUNC13 + wbdBASEFUNC13;

    wSumbdBASEPROFN     = wSumbdBASEPROFN     + wbdBASEPROFN;
    wSumbdbasePROferfn  = wSumbdbasePROferfn  + wbdbasePROferfn;
    wSumbdBASEPRO13RFN  = wSumbdBASEPRO13RFN  + wbdBASEPRO13RFN;
    wSumbdBASEPROFC     = wSumbdBASEPROFC     + wbdBASEPROFC;
    wSumbdBASEPROFERFC  = wSumbdBASEPROFERFC  + wbdBASEPROFERFC;
    wSumbdBasePRO13RFC  = wSumbdBasePRO13RFC  + wbdBasePRO13RFC;
    wSumbdBASEPRO13     = wSumbdBASEPRO13     + wbdBASEPRO13;
    wSumbdBASEPROC13    = wSumbdBASEPROC13    + wbdBASEPROC13;

    wSumbdBASEAUTFN     = wSumbdBASEAUTFN     + wbdBASEAUTFN;
    wSumbdbaseAUTferfn  = wSumbdbaseAUTferfn  + wbdbaseAUTferfn;
    wSumbdBASEAUT13RFN  = wSumbdBASEAUT13RFN  + wbdBASEAUT13RFN;
    wSumbdBASEAUTFC     = wSumbdBASEAUTFC     + wbdBASEAUTFC;
    wSumbdBASEAUTFERFC  = wSumbdBASEAUTFERFC  + wbdBASEAUTFERFC;
    wSumbdBaseAUT13RFC  = wSumbdBaseAUT13RFC  + wbdBaseAUT13RFC;
    wSumbdBASEAUT13     = wSumbdBASEAUT13     + wbdBASEAUT13;
    wSumbdBASEAUTC13    = wSumbdBASEAUTC13    + wbdBASEAUTC13;

    wSumbdBASEFPASFN     = wSumbdBASEFPASFN     + wbdBASEFPASFN;
    wSumbdbaseFPASferfn  = wSumbdbaseFPASferfn  + wbdbaseFPASferfn;
    wSumbdBASEFPAS13RFN  = wSumbdBASEFPAS13RFN  + wbdBASEFPAS13RFN;
    wSumbdBASEFPASFC     = wSumbdBASEFPASFC     + wbdBASEFPASFC;
    wSumbdBASEFPASFERFC  = wSumbdBASEFPASFERFC  + wbdBASEFPASFERFC;
    wSumbdBaseFPAS13RFC  = wSumbdBaseFPAS13RFC  + wbdBaseFPAS13RFC;
    wSumbdBASEFPAS13     = wSumbdBASEFPAS13     + wbdBASEFPAS13;
    wSumbdBASEFPASC13    = wSumbdBASEFPASC13    + wbdBASEFPASC13;

    wSumbdBASERATAPOFN     = wSumbdBASERATAPOFN     + wbdBASERATAPOFN;
    wSumbdbaseRATAPOferfn  = wSumbdbaseRATAPOferfn  + wbdbaseRATAPOferfn;
    wSumbdBASERATAPO13RFN  = wSumbdBASERATAPO13RFN  + wbdBASERATAPO13RFN;
    wSumbdBASERATAPOFC     = wSumbdBASERATAPOFC     + wbdBASERATAPOFC;
    wSumbdBASERATAPOFERFC  = wSumbdBASERATAPOFERFC  + wbdBASERATAPOFERFC;
    wSumbdBaseRATAPO13RFC  = wSumbdBaseRATAPO13RFC  + wbdBaseRATAPO13RFC;
    wSumbdBASERATAPO13     = wSumbdBASERATAPO13     + wbdBASERATAPO13;
    wSumbdBASERATAPOC13    = wSumbdBASERATAPOC13    + wbdBASERATAPOC13;

    bdtotSeg = wbdtotSeg;
    bdtotBase = wbdtotBase;
    bdSEGFUN = wbdSEGFUN;
    bdBaseFun = wbdBaseFun;
    bdPercFun = wbdPercFun;
    bdSegPro = wbdSegPro;
    bdBasePro = wbdBasePro;
    bdPercPro = wbdPercPro;
    bdSegAut = wbdSegAut;
    bdBaseAut = wbdBaseAut;
    bdPercAut = wbdPercAut;
    bdbaseratapo = wbdbaseratapo;
    bdvalorratapo = wbdvalorratapo;
    bdsalfam = wbdsalfam;
    bdsalmaternidade = wbdsalmaternidade;
    bdbasefpas = wbdbasefpas;
    bdpercfpas = wbdpercfpas;
    bdpercrat = wbdpercrat;
    bdvaloutentidade = wbdvaloutentidade;
    bddescenqfed = wbddescenqfed;
    bdsimplesgps = wbdsimplesgps;
    bdcodenqfed = wbdcodenqfed;

    bdBASEFUNFN = wbdBASEFUNFN;
    bdbasefunferfn  = wbdbasefunferfn;
    bdBASEFUN13RFN  = wbdBASEFUN13RFN;
    bdBASEFUNFC  = wbdBASEFUNFC;
    bdBASEFUNFERFC = wbdBASEFUNFERFC;
    bdBaseFun13RFC = wbdBaseFun13RFC;
    bdBASEFUN13 = wbdBASEFUN13;
    bdBASEFUNC13 = wbdBASEFUNC13;

    bdBASEPROFN     = wbdBASEPROFN;
    bdbasePROferfn  = wbdbasePROferfn;
    bdBASEPRO13RFN  = wbdBASEPRO13RFN;
    bdBASEPROFC     = wbdBASEPROFC;
    bdBASEPROFERFC  = wbdBASEPROFERFC;
    bdBasePRO13RFC  = wbdBasePRO13RFC;
    bdBASEPRO13     = wbdBASEPRO13;
    bdBASEPROC13    = wbdBASEPROC13;

    bdBASEAUTFN     = wbdBASEAUTFN;
    bdbaseAUTferfn  = wbdbaseAUTferfn;
    bdBASEAUT13RFN  = wbdBASEAUT13RFN;
    bdBASEAUTFC     = wbdBASEAUTFC;
    bdBASEAUTFERFC  = wbdBASEAUTFERFC;
    bdBaseAUT13RFC  = wbdBaseAUT13RFC;
    bdBASEAUT13     = wbdBASEAUT13;
    bdBASEAUTC13    = wbdBASEAUTC13;

    bdBASEFPASFN     = wbdBASEFPASFN;
    bdbaseFPASferfn  = wbdbaseFPASferfn;
    bdBASEFPAS13RFN  = wbdBASEFPAS13RFN;
    bdBASEFPASFC     = wbdBASEFPASFC;
    bdBASEFPASFERFC  = wbdBASEFPASFERFC;
    bdBaseFPAS13RFC  = wbdBaseFPAS13RFC;
    bdBASEFPAS13     = wbdBASEFPAS13;
    bdBASEFPASC13    = wbdBASEFPASC13;

    bdBASERATAPOFN     = wbdBASERATAPOFN;
    bdbaseRATAPOferfn  = wbdbaseRATAPOferfn;
    bdBASERATAPO13RFN  = wbdBASERATAPO13RFN;
    bdBASERATAPOFC     = wbdBASERATAPOFC;
    bdBASERATAPOFERFC  = wbdBASERATAPOFERFC;
    bdBaseRATAPO13RFC  = wbdBaseRATAPO13RFC;
    bdBASERATAPO13     = wbdBASERATAPO13;
    bdBASERATAPOC13    = wbdBASERATAPOC13;

    IF ((wcodtomador = 0) OR ((wemissao IS NULL) OR (wemissao = 1))) THEN
      bdcodtomador = NULL;
    ELSE
      bdcodtomador = wcodtomador;

    IF (wtpcc = 0) THEN
      bdcodtpcc = NULL;
    ELSE
      bdcodtpcc = wtpcc;
    bdtipo = 2;
    bdcodcol = wcodcol;
    bdcodter = wcodter;

    IF (prapenasgps = 1) THEN
      SUSPEND;

    wcodtomadorant = wcodtomador;
    wtpccant = wtpcc;
    wempresaant = bdcodemp;
  END

  bdtipo = 0;
  IF (wcodtomadorant = 0) THEN
     bdcodtomador = NULL;
  ELSE
     bdcodtomador = wcodtomadorant;

  IF (wtpccant = 0) THEN
     bdcodtpcc = NULL;
  ELSE
     bdcodtpcc = wtpccant;

  bdtotSeg = wsumtotSeg;
  bdtotBase = wsumtotBase;
  bdSEGFUN = wSUMSEGFUN;
  bdBaseFun = wSUMBaseFun;
  bdPercFun = wSUMPercFun;
  bdSegPro = wSumSegPro;
  bdBasePro = wSumBasePro;
  bdPercPro = wSumPercPro;
  bdSegAut = wSumSegAut;
  bdBaseAut = wSumBaseAut;
  bdPercAut = wSumPercAut;
  bdbaseratapo = wSumbaseratapo;
  bdvalorratapo = wSumvalorratapo;
  bdsalfam = wSumsalfam;
  bdsalmaternidade = wSumsalmaternidade;
  bdbasefpas = wSumbasefpas;
  bdpercfpas = wSumpercfpas;
  bdpercrat = wSumpercrat;
  bdvaloutentidade = wsumvaloutentidade;
  bddescenqfed = wSumdescenqfed;
  bdsimplesgps = wSumsimplesgps;
  bdcodenqfed = wSumcodenqfed;
  bdcodcol = NULL;

  bdBASEFUNFN = wSumbdBASEFUNFN;
  bdbasefunferfn = wSumbdbasefunferfn;
  bdBASEFUN13RFN = wSumbdBASEFUN13RFN;
  bdBASEFUNFC = wSumbdBASEFUNFC;
  bdBASEFUNFERFC = wSumbdBASEFUNFERFC;
  bdBaseFun13RFC = wSumbdBaseFun13RFC;
  bdBASEFUN13 = wSumbdBASEFUN13;
  bdBASEFUNC13 = wSumbdBASEFUNC13;

  bdBASEPROFN    = wSumbdBASEPROFN;
  bdbasePROferfn = wSumbdbasePROferfn;
  bdBASEPRO13RFN = wSumbdBASEPRO13RFN;
  bdBASEPROFC    = wSumbdBASEPROFC;
  bdBASEPROFERFC = wSumbdBASEPROFERFC;
  bdBasePRO13RFC = wSumbdBasePRO13RFC;
  bdBASEPRO13    = wSumbdBASEPRO13;
  bdBASEPROC13   = wSumbdBASEPROC13;

  bdBASEAUTFN    = wSumbdBASEAUTFN;
  bdbaseAUTferfn = wSumbdbaseAUTferfn;
  bdBASEAUT13RFN = wSumbdBASEAUT13RFN;
  bdBASEAUTFC    = wSumbdBASEAUTFC;
  bdBASEAUTFERFC = wSumbdBASEAUTFERFC;
  bdBaseAUT13RFC = wSumbdBaseAUT13RFC;
  bdBASEAUT13    = wSumbdBASEAUT13;
  bdBASEAUTC13   = wSumbdBASEAUTC13;

  bdBASEFPASFN    = wSumbdBASEFPASFN;
  bdbaseFPASferfn = wSumbdbaseFPASferfn;
  bdBASEFPAS13RFN = wSumbdBASEFPAS13RFN;
  bdBASEFPASFC    = wSumbdBASEFPASFC;
  bdBASEFPASFERFC = wSumbdBASEFPASFERFC;
  bdBaseFPAS13RFC = wSumbdBaseFPAS13RFC;
  bdBASEFPAS13    = wSumbdBASEFPAS13;
  bdBASEFPASC13   = wSumbdBASEFPASC13;

  bdBASERATAPOFN    = wSumbdBASERATAPOFN;
  bdbaseRATAPOferfn = wSumbdbaseRATAPOferfn;
  bdBASERATAPO13RFN = wSumbdBASERATAPO13RFN;
  bdBASERATAPOFC    = wSumbdBASERATAPOFC;
  bdBASERATAPOFERFC = wSumbdBASERATAPOFERFC;
  bdBaseRATAPO13RFC = wSumbdBaseRATAPO13RFC;
  bdBASERATAPO13    = wSumbdBASERATAPO13;
  bdBASERATAPOC13   = wSumbdBASERATAPOC13;
  IF (WEXISTE = 1) THEN
    SUSPEND;
END^

/* Restore proc. body: VRHF_SP_ESTOUROS */
ALTER PROCEDURE VRHF_SP_ESTOUROS(PRCODEMP VARCHAR(20000),
PRCODCOL VARCHAR(32700),
PRREFERENCIA INTEGER,
PRTIPOCALCULO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREFEST INTEGER,
BDVALEST NUMERIC(15,6),
BDTIPO INTEGER)
 AS
DECLARE VARIABLE WREF VARCHAR(50);
DECLARE VARIABLE WTABLE VARCHAR(255);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(25000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, NULL);

  wsql = 'select FOL.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'FOL.BDCODCOL, '||
                'COL.BDNOMCOL, ';

  /* Tipos de calculo:
     -----------------
     0 - Todos; (nao pode ser todos)
     1 - Folha normal;
     2 - Adiantamento salarial;
     3 - Adiantamento de 13o. salario;
     4 - 13o. salario;
     5 - Complemento de 13o. salario;
     6 - Ferias;
     7 - PLR;
     8 - Folha complementar;
     9 - Rescisao. (folha normal)
  */

  IF (prtipocalculo = 2) THEN
     BEGIN
       wsql = wsql||'cast((substring((cast(FOL.BDDATAAD as VARCHAR(10))) from 1 for 4)||substring((cast(FOL.BDDATAAD as VARCHAR(10))) from 6 for 2)) as INTEGER) BDREF, '||
                    'FOL.BDVALVAD, 2';
       wTable = 'VRHF_EMP_TVERBAAD';
       wref = 'FOL.BDDATAAD';
     END
  ELSE
  IF (prtipocalculo = 3) THEN
     BEGIN
       wsql = wsql||'FOL.BDREFA13, '||
                    'FOL.BDVALVA13, 3 ';
       wTable = 'VRHF_EMP_TVERBAA13';
       wref = 'FOL.BDREFA13';
     END
  ELSE
  IF (prtipocalculo = 4) THEN
     BEGIN
       wsql = wsql||'FOL.BDREF13, '||
                    'FOL.BDVALV13, 4 ';
       wTable = 'VRHF_EMP_TVERBA13';
       wref = 'FOL.BDREF13';
     END
  ELSE
  IF (prtipocalculo = 5) THEN
     BEGIN
       wsql = wsql||'FOL.BDREFC13, '||
                    'FOL.BDVALVC13, 5 ';
       wTable = 'VRHF_EMP_TVERBAC13';
       wref = 'FOL.BDREFC13';
     END
  ELSE
  IF (prtipocalculo = 6) THEN
     BEGIN
       wsql = wsql||'FOL.BDREFFE, '||
                    'FOL.BDVALVRFE, 6 ';
       wTable = 'VRHF_EMP_TVERBAFE';
       wref = 'FOL.BDREFFE';
     END
  ELSE
  IF (prtipocalculo = 8) THEN
     BEGIN
       wsql = wsql||'FOL.BDREFCOMP, '||
                    'FOL.BDVALVFC, 8 ';
       wTable = 'VRHF_EMP_TVERBAFC';
       wref = 'FOL.BDREFCOMP';
     END
  ELSE
     BEGIN
       wsql = wsql||'FOL.BDREFFN, '||
                    'FOL.BDVALVFN, '||
                    'FOL.BDTIPO ';
       wTable = 'VWRH_UNION_MES_VERBAS';
       wref = 'FOL.BDREFFN';
     END

  wsql = wsql||
         'from '||wtable||' FOL '||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
         'on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) '||
         'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
         'on (EMP.BDCODEMP = FOL.BDCODEMP) '||
         'left outer join vrh_base_tverbas VERBAS '||
         'on (VERBAS.BDCODVER = FOL.BDCODVER) ';

  wwhere = 'where VERBAS.BDCLAVER like '''||'9.002.0.%'||'''';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||' and '||prcodcol;

  wsql = wsql||wwhere||' order by FOL.BDCODEMP, FOL.BDCODCOL, '||wref||' DESC ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDREFEST,
    :BDVALEST,
    :BDTIPO
  DO

  SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_EXTRATO_FGTS */
create or alter procedure VRHF_SP_EXTRATO_FGTS (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(10000),
    PRREFFIM integer,
    PRCC varchar(10000) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATA integer,
    BDMOVIMENTACAO varchar(200),
    BDVALOR numeric(15,6),
    BDACUMULADO numeric(15,6),
    BDVALORJAM numeric(15,6),
    BDVALORDEPOSITO numeric(15,6),
    BDSALDOTOT numeric(15,6),
    BDJAMTOT numeric(15,6),
    BDDEPOSITADOTOT numeric(15,6))
as
declare variable WSQL varchar(32000);
declare variable WSQL2 varchar(1024);
declare variable WDATA varchar(8);
declare variable WVALORJAM numeric(15,6);
declare variable WINDICEJAM numeric(15,6);
declare variable WSOMAFGTS numeric(15,6);
declare variable WSALDOFGTS numeric(15,6);
declare variable WSQLTOT varchar(2000);
declare variable WSALDOTOT numeric(15,6);
declare variable WCOLANT integer;
declare variable WEMPANT integer;
BEGIN
  WEMPANT = 0;
  WCOLANT = 0;

  /* Procedure Text */
  IF (prcodemp IS NULL) THEN
     prcodemp = 'null';
  ELSE
     prcodemp = ''''||upper(prcodemp)||'''';

  IF (prcodcol IS NULL) THEN
     prcodcol = 'null';
  ELSE
     prcodcol = ''''||upper(prcodcol)||'''';

  if (prcc is null) then
     prcc = 'null';
  else
     prcc = ''''||upper(prcc)||'''';

  wsql2 = NULL;

  IF (prreffim IS NULL) THEN
     BEGIN
       wsql = 'select rdb$get_context('||''''||'USER_SESSION'||''''||', '||''''||'W_ANOMES'||''''||') from rdb$database';
       EXECUTE STATEMENT wsql INTO wsql2;
     END

  IF (wsql2 IS NOT NULL) THEN
     prreffim = CAST(wsql2 AS INTEGER);


  IF (prreffim IS NULL) THEN
     prreffim = '999999';

  wsql = ' select x.bdcodemp,x.bdcodcol,x.bdref,x.bdvalorjam,x.bdindicejam,x.bdsomafgts,x.bdsaldofgts from VRHF_SP_FICHAFGTS2('||prcodemp||','||prcodcol||','||prreffim||','||prcc||',1) x';

  FOR EXECUTE STATEMENT wsql INTO
    bdcodemp,
    bdcodcol,
    wdata,
    wvalorjam,
    windicejam,
    wsomafgts,
    wsaldofgts DO
  BEGIN

    if ((BDCODEMP <> WEMPANT) or (BDCODCOL <> WCOLANT)) then /*Soma o total depositado pra cada colaborador*/
      begin
        WSQLTOT = 'select SUM(BDSOMAFGTS) BDSOMAFGTS, SUM(BDVALORJAM) BDSOMAJAM, SUM(BDSOMAFGTS) BDDEPOSITADOTOT  from VRHF_SP_FICHAFGTS2(''TEMP.BDCODEMP = '||BDCODEMP||''', ''TEMP.BDCODCOL = '||BDCODCOL||''','||prreffim||','||prcc||', 1) ';

        execute statement WSQLTOT into BDSALDOTOT, BDJAMTOT, BDDEPOSITADOTOT;

        WEMPANT = BDCODEMP;
        WCOLANT = BDCODCOL;
       end

    bddata = CAST(wdata AS VARCHAR(6))||'00';
    bdmovimentacao = 'Depósito '||SUBSTRING(bddata FROM 5 FOR 2)||'/'||SUBSTRING(bddata FROM 1 FOR 4);
    IF (SUBSTRING(bddata FROM 5 FOR 2) = '12') THEN
       bddata = (CAST(SUBSTRING(bddata FROM 1 FOR 4) AS INTEGER)+1)||'0100';
    ELSE
       BEGIN
         IF ((SUBSTRING(bddata FROM 5 FOR 2) < '09')) THEN
            bddata = SUBSTRING(bddata FROM 1 FOR 4)||'0'||(CAST(SUBSTRING(bddata FROM 5 FOR 2) AS INTEGER)+1)||'00';
         ELSE
            bddata = SUBSTRING(bddata FROM 1 FOR 4)||(CAST(SUBSTRING(bddata FROM 5 FOR 2) AS INTEGER)+1)||'00';
       END
    bdvalor = wsomafgts;
    bdvalordeposito = bdvalor;
    bdvalorjam = 0;
    bdacumulado = wsaldofgts;
    SUSPEND;

    IF ((wvalorjam IS NOT NULL) AND (wvalorjam > 0)) THEN
       BEGIN
         wsql2 = CAST(windicejam AS VARCHAR(1024));
         SELECT bdresult FROM STRTRAN(:wsql2,'.',',') INTO wsql2;

         bddata = CAST(wdata AS VARCHAR(6))||'10';
         bdmovimentacao = 'Crédito de JAM '||wsql2;
         bdvalor = wvalorjam;
         bdvalordeposito = 0;
         bdvalorjam = bdvalor;
         bdacumulado = wsaldofgts - wsomafgts;
         SUSPEND;
       END
  END
END^

create or alter procedure SP_TCOLCON_VINCDIA_ADM (
    PRCODEMP integer,
    PRCODCOL integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATACOL date,
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDCODPQUA integer,
    BDDATAINICIALESCALA date,
    BDCODREVEZAMENTO integer,
    BDTIPOESCALA integer,
    BDCODQH integer)
as
declare variable WSQL varchar(5000);
declare variable WWHERE varchar(500);
begin
  wWhere = '';
  if (prCODEMP > 0) then
     wWhere = wWhere||'(Col.BDCODEMP = '||:PRCODEMP||')';
  if (prCODCOL > 0) then
     begin
       if (wWhere <> '') then
          wWhere = wWhere||' and ';

       wWhere = wWhere||'(Col.BDCODCOL = '||:PRCODCOL||')';
     end
  if (wWhere <> '') then
     wWhere = ' where '||wWhere;

  wSQL = 'Select Base.BDCODEMP, Base.BDCODCOL, Base.BDDATACOL, VincDia.BDCODPLAFUC, VincDia.BDCODTFUC, VincDia.BDCODPQUA, VincDia.BDCODQH, VincDia.BDTIPOESCALA, VincDia.BDCODREVEZAMENTO, VincDia.BDDATAINICIALESCALA ';
  wSQL = wSQL||'from ( Select Col.BDCODEMP, Col.BDCODCOL, ';
  wSQL = wSQL||'              (Select Min(VD.BDDATACOL) from VRH_EMP_TCOL_VINCDIA VD where VD.BDCODEMP = Col.BDCODEMP AND VD.BDCODCOL = Col.BDCODCOL) AS BDDATACOL ';
  wSQL = wSQL||'       from ( Select Col.BDCODEMP, Col.BDCODCOL ';
  wSQL = wSQL||'              from VRH_EMP_TCOLCON col ';
  if (wWhere <> '') then
     wSQL = wSQL||wWhere;
  wSQL = wSQL||'            ) Col ';
  wSQL = wSQL||'     ) Base ';
  wSQL = wSQL||'inner join VRH_EMP_TCOL_VINCDIA VincDia on (VincDia.BDCODEMP = Base.BDCODEMP and VincDia.bdcodcol = Base.BDCODCOL and VincDia.BDDATACOL = Base.BDDATACOL)';

  For execute statement wSQL
  Into :BDCODEMP, :BDCODCOL, :BDDATACOL, :BDCODPLAFUC, :BDCODTFUC, :BDCODPQUA, :BDCODQH, :BDTIPOESCALA, :BDCODREVEZAMENTO, :BDDATAINICIALESCALA Do
  Begin
    suspend;
  End
end^


/* Restore proc. body: VRHF_SP_FICHA_REG_COLABORADOR */
create or alter procedure VRHF_SP_FICHA_REG_COLABORADOR (
    PREMPRESA varchar(15000),
    PRCOLABORADOR varchar(30000),
    PRMODELO integer,
    PRORDEMIMP integer,
    PRCLASSE varchar(10000),
    PRFUNCAO varchar(10000),
    PRCENTROCUSTO varchar(10000),
    PRSINDICATO varchar(10000),
    PRREFERENCIA integer,
    PRULTIMODIA date,
    PROBS integer,
    PRSITCOL integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(18),
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDBAIEMP DM_BDBAIRRO,
    BDCIDADEEMP varchar(40),
    BDUFEMP varchar(2),
    BDCEPEMP varchar(9),
    BDFONEEMP DM_BDTELEFONE,
    BDDDDEMP integer,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLORDEM DM_BDNOMCOL,
    BDNOMPAICOL varchar(70),
    BDNOMMAECOL varchar(70),
    BDNOMCONJCOL varchar(70),
    BDDATANASCCOL date,
    BDCORCOL integer,
    BDSEXOCOL integer,
    BDPAISCOL varchar(40),
    BDNACIONALIDADE varchar(30),
    BDDATACHEBRASILCOL date,
    BDCIDADENASCCOL varchar(40),
    BDUFNASCCOL varchar(2),
    BDTIPOSANGUECOL integer,
    BDCPFCOL varchar(14),
    BDRGCOL varchar(13),
    BDDATAEMIREGCOL date,
    BDORGEMIRGCOL DM_ORGAOEMISSOR,
    BDCNHCOL varchar(11),
    BDCATCNHCOL varchar(2),
    BDVENCNHCOL date,
    BDCTPSCOL DM_BDCTPS,
    BDSERIECOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDRESERVISTACOL varchar(20),
    BDTITELEICOL varchar(20),
    BDGRAUINSTCOL integer,
    BDZONAELEICOL integer,
    BDSECAOELEICOL integer,
    BDPISCOL varchar(14),
    BDDATAEMIPISCOL date,
    BDESTCIVCOL integer,
    BDLOGRCOL DM_LOGRADOURO,
    BDENDCOL DM_BDENDERECO,
    BDNUMCOL DM_NUMEND,
    BDCOMPLCOL DM_BDCOMPENDERECO,
    BDBAICOL DM_BDBAIRRO,
    BDCIDADECOL varchar(40),
    BDUFCOL varchar(2),
    BDCEPCOL varchar(9),
    BDFONECOL DM_BDTELEFONE,
    BDDDDCOL integer,
    BDEMAILCOL DM_BDEMAIL,
    BDCELCOL DM_BDTELEFONE,
    BDDATAADMCOL date,
    BDDATACADCOL date,
    BDSALINICOL numeric(15,2),
    BDFORMAPAGTOCOL integer,
    BDPERCINSALUBCOL numeric(15,6),
    BDPERCPERCULCOL numeric(15,2),
    BDCATEGORIACOL integer,
    BDCODSINTRAB integer,
    BDDESCSINTRAB varchar(60),
    BDDEFCOL DM_BOOLEAN,
    BDDEFFISICOCOL integer,
    BDREAB DM_BOOLEAN,
    BDTIPOCOL integer,
    BDCTAFGTSCOL varchar(20),
    BDDATAOPCAOFGTSCOL date,
    BDCTADEPCOL varchar(20),
 BDDIGCTADEPCOL varchar(2),
    BDCODTFUC integer,
    BDDESCTFUC varchar(40),
    BDCODCBO integer,
    BDDATARESCISAO date,
    BDDATAAVPREVIO date,
    BDSALDOFGTS numeric(15,6),
    BDMAIORREMUNERACAO numeric(15,6),
    BDDATAPAGGRFC date,
    BDCODPRES integer,
    BDDESCPRES varchar(110),
    BDFOTOCOL blob sub_type 0 segment size 80,
    BDFICHAREGCOL varchar(12),
    BDLIVROREGCOL varchar(10),
    BDNROFOLHAREGCOL integer,
    BDUFCTPS varchar(2),
    BDDESCCATEGORIA varchar(300),
    BDNOMBAN varchar(60),
    BDCODBAN integer,
    BDNOMAG varchar(40),
    BDCODAG integer,
    BDNATURALIZADOCOL varchar(5),
    BDCABELOSCOL integer,
    BDOLHOSCOL integer,
    BDALTURACOL numeric(15,6),
    BDPESOCOL numeric(15,6),
    BDSINAISCOL varchar(5),
    BDOBSCOL blob sub_type 1 segment size 5000,
    BDDDDCELCOL integer,
    BDSIGLAUFRG varchar(2),
    BDDIANASC varchar(2),
    BDMESNASC varchar(2),
    BDANONASC varchar(10),
    BDCONTRCOL integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDNOMTPCC DM_BDNOMEMP,
    BDNOMCIDTPCC varchar(40),
    BDUFTPCC varchar(2),
    BDCODCLA integer,
    BDTIPOESCALA integer)
as
declare variable WORDERBY varchar(15000);
declare variable WSQL varchar(32700);
declare variable WDTINI varchar(10);
declare variable WCODCENTRO integer;
declare variable WCODTPCC integer;
declare variable WNOMTPCC DM_BDNOMEMP;
declare variable WNOMCIDTPCC varchar(40);
declare variable WUFTPCC varchar(2);
declare variable WORDEMTPCC integer;
declare variable WWHERE varchar(32700);
BEGIN
  wsql = 'select VW_COL_REF_ATUAL.BDCODEMP, '||
                'EMP_REF.BDNOMEMP, '||
                'EMP.BDCNPJEMP, '||
                'EMP_REF.BDLOGREMP, '||
                'EMP_REF.BDENDEMP, '||
                'EMP_REF.BDNUMEMP, '||
                'EMP_REF.BDCOMPLEMP, '||
                'EMP_REF.BDBAIEMP, '||
                'TCIDEMP.BDNOMCID, '||
                'TUFEMP.BDSIGLAUF, '||
                'EMP_REF.BDCEPEMP, '||
                'EMP_REF.BDFONEEMP, '||
                'EMP_REF.BDDDDEMP, '||
                'VW_COL_REF_ATUAL.BDCODCOL, '||
                'CASE WHEN (FIS.BDNMSOCIAL <> '''' and PAR.bdusanomesocial = ''TRUE'') THEN FIS.BDNMSOCIAL ELSE COL_CAD.BDNOMCOL END BDNOMCOL,'||
                'CASE WHEN (FIS.BDNMSOCIAL <> '''' and PAR.bdusanomesocial = ''TRUE'') THEN UPPER(FIS.BDNMSOCIAL) ELSE COL_CAD.BDNOMCOLUPPER END BDNOMCOLORDEM,'||
                'CAD_PARENT.BDNOMPAICOL, '||
                'CAD_PARENT.BDNOMMAECOL, '||
                'CAD_PARENT.BDNOMCONJCOL, '||
                'VW_COL_REF_ATUAL.BDDATANASCCOL, '||
                'COL_RFIS.BDCORCOL, '||
                'COL_CAD.BDSEXOCOL, '||
                'COL_CAD.BDDATACHEBRASILCOL, '||
                'TPAISCOL.BDDESCPAIS, '||
                'TPAISCOL.BDNACIONALIDADE, '||
                'TCIDNASCCOL.BDNOMCID, '||
                'TUFNASCCOL.BDSIGLAUF, '||
                'COL_FIS.BDTIPOSANGUECOL, '||
                'VW_COL_REF_ATUAL.BDCPFCOL, '||
                'CAD_DOC.BDRGCOL, '||
                'CAD_DOC.BDDATAEMIRGCOL, '||
                'CAD_DOC.BDORGEMIRGCOL, '||
                'CAD_DOC.BDCNHCOL, '||
                'CAD_DOC.BDCATCNHCOL, '||
                'CAD_DOC.BDVENCCNHCOL, '||
                'CAD_DOC.BDCTPSCOL, '||
                'CAD_DOC.BDSERIECTPSCOL, '||
                'CAD_DOC.BDDSERIECTPSCOL, '||
                'DOC_COL.BDRESERVISTACOL, '||
                'DOCC_COL.BDTITELEICOL, '||
                'COL_CAD.BDGRAUINSTCOL, '||
                'DOCC_COL.BDZONAELEICOL, '||
                'DOCC_COL.BDSECAOELEICOL, '||
                'CAD_DOC.BDPISCOL, '||
                'CAD_DOC.BDDATAEMIPISCOL, '||
                'COL_CAD.BDESTCIVCOL, '||
                'COL_CAD.BDLOGRCOL, '||
                'COL_CAD.BDENDCOL, '||
                'COL_CAD.BDNUMCOL, '||
                'COL_CAD.BDCOMPLCOL, '||
                'COL_CAD.BDBAICOL, '||
                'TCIDCOL.BDNOMCID, '||
                'TUFCOL.BDSIGLAUF, '||
                'COL_CAD.BDCEPCOL, '||
                'COL_CAD.BDFONECOL, '||
                'COL_CAD.BDDDDCOL, '||
                'COL_CAD.BDEMAILCOL, '||
                'COL_CAD.BDCELCOL, '||
                'case '||
                    'when COL_ADM.BDNOVADATAADMRT is not null then COL_ADM.BDNOVADATAADMRT '||
                    'else VW_COL_REF_ATUAL.BDDATAADMCOL end BDDATAADMCOL, '||
                'VW_COL_REF_ATUAL.BDDATACADCOL, '||
                'COL_ADM.BDSALINICOL, '||
                'COL_CALC.BDFORMAPAGTOCOL, '||
                'COL_RCALC.BDPERCINSALUBCOL, '||
                'COL_RCALC.BDPERCPERCULCOL, '||
                'CAD_FGTS.BDCATEGORIACOL, '||
                'TSINTRAB.BDCODSINTRAB, '||
                'TSINTRAB.BDDESCSINTRAB, '||
                'COL_RFIS.BDDEFCOL, '||
                'case '||
                  'when (COL_RFIS.BDDEFCOL = ''FALSE'') then 0 '||
                  'else case '||
                         'when (COL_RFIS.BDDEFFIS = ''TRUE'') and (COL_RFIS.BDDEFVIS = ''TRUE'' or COL_RFIS.BDDEFAUD = ''TRUE'' or COL_RFIS.BDDEFMEN = ''TRUE'' or COL_RFIS.BDREAB = ''TRUE'') or '||
                              '(COL_RFIS.BDDEFVIS = ''TRUE'') and (COL_RFIS.BDDEFFIS = ''TRUE'' or COL_RFIS.BDDEFAUD = ''TRUE'' or COL_RFIS.BDDEFMEN = ''TRUE'' or COL_RFIS.BDREAB = ''TRUE'') or '||
                              '(COL_RFIS.BDDEFAUD = ''TRUE'') and (COL_RFIS.BDDEFFIS = ''TRUE'' or COL_RFIS.BDDEFVIS = ''TRUE'' or COL_RFIS.BDDEFMEN = ''TRUE'' or COL_RFIS.BDREAB = ''TRUE'') or '||
                              '(COL_RFIS.BDDEFMEN = ''TRUE'' or COL_RFIS.BDDEFINT = ''TRUE'') and (COL_RFIS.BDDEFFIS = ''TRUE'' or COL_RFIS.BDDEFAUD = ''TRUE'' or COL_RFIS.BDDEFVIS = ''TRUE'' or '||
                                'COL_RFIS.BDREAB = ''TRUE'') or (COL_RFIS.BDREAB = ''TRUE'') and (COL_RFIS.BDDEFFIS = ''TRUE'' or COL_RFIS.BDDEFAUD = ''TRUE'' or COL_RFIS.BDDEFMEN = ''TRUE'' or '||
                                'COL_RFIS.BDDEFVIS = ''TRUE'') then 6 '||
                         'else case '||
                                'when (COL_RFIS.BDDEFFIS = ''TRUE'') then 1 '||
                                'else case '||
                                       'when (COL_RFIS.BDDEFAUD = ''TRUE'') then 2 '||
                                       'else case '||
                                              'when (COL_RFIS.BDDEFVIS = ''TRUE'') then 3 '||
                                              'else case '||
                                                     'when (COL_RFIS.BDDEFMEN = ''TRUE'' or COL_RFIS.BDDEFINT = ''TRUE'') then 4 '||
                                                     'else case '||
                                                            'when (COL_RFIS.BDREAB = ''TRUE'') then 5 '||
                                                          'end '||
                                                   'end '||
                                            'end '||
                                     'end '||
                              'end '||
                       'end '||
                'end BDDEFFISICOCOL, '||
                'COL_RCALC.BDTIPOCOL, '||
                'CAD_FGTS.BDCTAFGTSCOL, '||
                'CAD_FGTS.BDDATAOPCAOFGTSCOL, '||
                'COL_BANCO.BDCTADEPCOL, '||
    'COL_BANCO.BDDIGCTADEPCOL, '||
                'COL_DIAVINC.BDCODTFUC, '||
                'TFUC.BDDESCTFUC, '||
                'TFUC.BDCODCBO, '||
                'COALESCE(VW_RESCISAO.BDNOVADATARESCISAO, VW_RESCISAO.BDDATARESCISAO) AS BDDATARESCISAO, '||
                'VW_RESCISAO.BDDATAAVPREVIO, '||
                'VW_RESCISAO.BDSALDOFGTS, '||
                'VW_RESCISAO.BDMAIORREMUNERACAO, '||
                'VW_RESCISAO.BDDATAPAGGRFC, '||
                'COALESCE(VW_RESCISAO.BDNOVOCODPRES,  VW_RESCISAO.BDCODPRES) AS BDCODPRES, '||
                'VW_RESCISAO.BDDESCPRES, '||
                'TCOLCON_IMG.BDFOTOCOL_IMG, '||
                'COL_ADM.BDFICHAREGCOL, '||
                'COL_ADM.BDLIVROREGCOL, '||
                'COL_ADM.BDNROFOLHAREGCOL, '||
                'TUFCTPS.BDSIGLAUF, '||
                'TCATEG.BDDESCCATEGORIA, '||
                'TBAN.BDNOMBAN, '||
                'TBAN.BDCODBAN, '||
                'TBANAG.BDNOMAG, '||
                'TBANAG.BDCODAG, '||
                'COL_HIST.BDNATURALIZADOCOL, '||
                'COL_FIS.BDCABELOSCOL, '||
                'COL_FIS.BDOLHOSCOL, '||
                'COL_FIS.BDALTURACOL, '||
                'COL_FIS.BDPESOCOL, '||
                'COL_FIS.BDSINAISCOL, '||
                'VW_COL_REF_ATUAL.BDCONTRCOL, ';

  IF (probs IS NOT NULL AND probs = 1) THEN
     wSql = wSql || 'CHIST.bdobscol, ';
  ELSE
     wSql = wSql || 'CAST(null as BLOB) bdobscol, ';

  wSql = wSql||
               'COL_CAD.BDDDDCELCOL, '||
               'UF_RG.BDSIGLAUF, '||
               'COL_RFIS.BDREAB, '||
               'CLA.BDCODCLA, '||
               'COL_DIAVINC.BDTIPOESCALA '||
         'from VRH_EMP_TCOLCON VW_COL_REF_ATUAL ';

  wdtini = CAST(prultimodia AS VARCHAR(10));
  wdtini = SUBSTRING(wdtini FROM 1 FOR 8)||'01';

  IF (prsitcol IS NOT NULL AND prsitcol = 0) THEN  -- somente ativos
     wsql = wsql || 'join sp_somente_ativos('''||wdtini||''','''||prultimodia||''') filtro on (filtro.bdcodemp = vw_col_ref_atual.bdcodemp and filtro.bdcodcol = vw_col_ref_atual.bdcodcol) ';
  ELSE
  IF (prsitcol IS NOT NULL AND prsitcol = 2) THEN  -- somente demitidos
     wsql = wsql || 'join sp_somente_demitidos('''||prultimodia||''') filtro on (filtro.bdcodemp = vw_col_ref_atual.bdcodemp and filtro.bdcodcol = vw_col_ref_atual.bdcodcol) ';
  ELSE
  IF (prsitcol IS NOT NULL AND prsitcol = 3) THEN  -- admitidos no mês
     wsql = wsql || 'join sp_somente_admitidos_mes('''||wdtini||''','''||prultimodia||''') filtro on (filtro.bdcodemp = vw_col_ref_atual.bdcodemp and filtro.bdcodcol = vw_col_ref_atual.bdcodcol) ';
  ELSE
  IF (prsitcol IS NOT NULL AND prsitcol = 4) THEN  -- demitidos no mês
     wsql = wsql || 'join sp_somente_demitidos_mes('''||wdtini||''','''||prultimodia||''') filtro on (filtro.bdcodemp = vw_col_ref_atual.bdcodemp and filtro.bdcodcol = vw_col_ref_atual.bdcodcol) ';
  ELSE
  IF (prsitcol IS NOT NULL AND prsitcol = 5) THEN  -- ativos sem demitidos no mês
     wsql = wsql || 'join sp_ativos_sem_demitidos_mes('''||wdtini||''','''||prultimodia||''') filtro on (filtro.bdcodemp = vw_col_ref_atual.bdcodemp and filtro.bdcodcol = vw_col_ref_atual.bdcodcol) ';
  ELSE
  IF (prsitcol IS NOT NULL AND prsitcol = 6) THEN  -- ativos sem demitidos no mês, com transferidos
     wsql = wsql || 'join sp_ati_sem_dem_com_transf('''||wdtini||''','''||prultimodia||''') filtro on (filtro.bdcodemp = vw_col_ref_atual.bdcodemp and filtro.bdcodcol = vw_col_ref_atual.bdcodcol) ';
  ELSE
  IF (prsitcol IS NOT NULL AND prsitcol = 7) THEN  -- ativos sem afastados o mês inteiro
     wsql = wsql || 'join sp_ati_sem_afast_mes_int('''||wdtini||''','''||prultimodia||''') filtro on (filtro.bdcodemp = vw_col_ref_atual.bdcodemp and filtro.bdcodcol = vw_col_ref_atual.bdcodcol) ';
  ELSE
  IF (prsitcol IS NOT NULL AND prsitcol = 8) THEN  -- afastados o mês inteiro
     wsql = wsql || 'join sp_afastados_mes_inteiro('''||wdtini||''','''||prultimodia||''') filtro on (filtro.bdcodemp = vw_col_ref_atual.bdcodemp and filtro.bdcodcol = vw_col_ref_atual.bdcodcol) ';

  wSql = wSql||
         'join TEMPRESAS EMP on (EMP.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP) '||
         'left outer join ( '||
           'select VW_COL_REF_ATUAL.BDCODEMP, max(VW_COL_REF_ATUAL.BDREFEMP) BDREFEMP '||
           'from TEMPRESAS_REF VW_COL_REF_ATUAL '||
           'where VW_COL_REF_ATUAL.BDREFEMP <= '||prreferencia||' '||
           'group by VW_COL_REF_ATUAL.BDCODEMP) EMP_REF2 on (EMP_REF2.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP) '||
         'left outer join TEMPRESAS_REF EMP_REF on (EMP_REF.BDCODEMP = EMP_REF2.BDCODEMP and EMP_REF.BDREFEMP = EMP_REF2.BDREFEMP) '||
         'left outer join ( '||
           'select VW_COL_REF_ATUAL.BDCODEMP, VW_COL_REF_ATUAL.BDCODCOL, max(VW_COL_REF_ATUAL.BDREFCOL) BDREFCOL '||
           'from VRH_EMP_TCOLCON_CAD VW_COL_REF_ATUAL '||
           'where VW_COL_REF_ATUAL.BDREFCOL <= '||prreferencia||' '||
           'group by VW_COL_REF_ATUAL.BDCODEMP, VW_COL_REF_ATUAL.BDCODCOL '||
         ') COL_CAD2 on (COL_CAD2.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and COL_CAD2.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) '||
         'left outer join VRH_EMP_TCOLCON_CAD COL_CAD on (COL_CAD.BDCODEMP = COL_CAD2.BDCODEMP and COL_CAD.BDCODCOL = COL_CAD2.BDCODCOL and COL_CAD.BDREFCOL = COL_CAD2.BDREFCOL) '||
         'left outer join VRH_EMP_TCOL_PARENT CAD_PARENT on (CAD_PARENT.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and CAD_PARENT.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) '||
         'left outer join ( '||
           'select VW_COL_REF_ATUAL.BDCODEMP, VW_COL_REF_ATUAL.BDCODCOL, max(VW_COL_REF_ATUAL.BDREFCOL) BDREFCOL '||
           'from VRH_EMP_TCOL_VINC VW_COL_REF_ATUAL '||
           'where VW_COL_REF_ATUAL.BDREFCOL <= '||prreferencia||' '||
           'group by VW_COL_REF_ATUAL.BDCODEMP, VW_COL_REF_ATUAL.BDCODCOL '||
         ') CVINC2 on (CVINC2.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and CVINC2.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) '||
         'left outer join VRH_EMP_TCOL_VINC CAD_VINC on (CAD_VINC.BDCODEMP = CVINC2.BDCODEMP and CAD_VINC.BDCODCOL = CVINC2.BDCODCOL and CAD_VINC.BDREFCOL = CVINC2.BDREFCOL) '||

         'left outer join VRH_EMP_TCOLCON_VINC EMP_VINC on (EMP_VINC.BDCODEMP = CAD_VINC.BDCODEMP and '||
         'EMP_VINC.BDCODCOL = CAD_VINC.BDCODCOL and '||
         'EMP_VINC.BDREFCOL = CAD_VINC.BDREFCOL) '||
         'left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = EMP_VINC.BDCODCLA) '||

         'left outer join VRHF_EMP_TPREPFN CC on (CC.BDCODCENTRO = EMP_VINC.BDCODCENTRO) '||

         'left outer join ( '||
           'select VW_COL_REF_ATUAL.BDCODEMP, VW_COL_REF_ATUAL.BDCODCOL, max(VW_COL_REF_ATUAL.BDREFCOL) BDREFCOL '||
           'from VRHF_EMP_TCOLCON_FGTSGPS VW_COL_REF_ATUAL '||
           'where VW_COL_REF_ATUAL.BDREFCOL <= '||prreferencia||' '||
           'group by VW_COL_REF_ATUAL.BDCODEMP, VW_COL_REF_ATUAL.BDCODCOL '||
         ') CFGTS2 on (CFGTS2.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and CFGTS2.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) '||
         'left outer join VRHF_EMP_TCOLCON_FGTSGPS CAD_FGTS on (CAD_FGTS.BDCODEMP = CFGTS2.BDCODEMP and CAD_FGTS.BDCODCOL = CFGTS2.BDCODCOL and CAD_FGTS.BDREFCOL = CFGTS2.BDREFCOL) '||
         'left outer join VRH_EMP_TCOL_FIS COL_FIS on (COL_FIS.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and COL_FIS.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) '||
         'left outer join ( '||
           'select VW_COL_REF_ATUAL.BDCODEMP, VW_COL_REF_ATUAL.BDCODCOL, max(VW_COL_REF_ATUAL.BDREFCOL) BDREFCOL '||
           'from VRH_EMP_TCOLCON_DOCREF VW_COL_REF_ATUAL '||
           'where VW_COL_REF_ATUAL.BDREFCOL <= '||prreferencia||' '||
           'group by VW_COL_REF_ATUAL.BDCODEMP, VW_COL_REF_ATUAL.BDCODCOL '||
         ') CDOC2 on (CDOC2.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and CDOC2.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) '||
         'left outer join VRH_EMP_TCOLCON_DOCREF CAD_DOC on (CAD_DOC.BDCODEMP = CDOC2.BDCODEMP and CAD_DOC.BDCODCOL = CDOC2.BDCODCOL and CAD_DOC.BDREFCOL = CDOC2.BDREFCOL) '||
         'left outer join VRH_EMP_TCOLCON_DOC DOC_COL on (DOC_COL.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and DOC_COL.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) '||
         'left outer join VRH_EMP_TCOL_DOC DOCC_COL on (DOCC_COL.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and DOCC_COL.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) '||
         'left outer join VRH_EMP_TCOL_ADM COL_ADM on (COL_ADM.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and COL_ADM.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) '||
         'left outer join ( '||
           'select VW_COL_REF_ATUAL.BDCODEMP, VW_COL_REF_ATUAL.BDCODCOL, max(VW_COL_REF_ATUAL.BDREFCOL) BDREFCOL '||
           'from VRHF_EMP_TCOLCON_CALC VW_COL_REF_ATUAL '||
           'where VW_COL_REF_ATUAL.BDREFCOL <= '||prreferencia||' '||
           'group by VW_COL_REF_ATUAL.BDCODEMP, VW_COL_REF_ATUAL.BDCODCOL '||
         ') CCALC2 on (CCALC2.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and CCALC2.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) '||
         'left outer join VRHF_EMP_TCOLCON_CALC COL_CALC on (COL_CALC.BDCODEMP = CCALC2.BDCODEMP and COL_CALC.BDCODCOL = CCALC2.BDCODCOL and COL_CALC.BDREFCOL = CCALC2.BDREFCOL) '||
         'left outer join ( '||
           'select VW_COL_REF_ATUAL.BDCODEMP, VW_COL_REF_ATUAL.BDCODCOL, max(VW_COL_REF_ATUAL.BDREFCOL) BDREFCOL '||
           'from VRH_EMP_TCOLCON_FIS VW_COL_REF_ATUAL '||
           'where VW_COL_REF_ATUAL.BDREFCOL <= '||prreferencia||' '||
           'group by VW_COL_REF_ATUAL.BDCODEMP, VW_COL_REF_ATUAL.BDCODCOL '||
         ') CRFIS2 on (CRFIS2.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and CRFIS2.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) '||
         'left outer join VRH_EMP_TCOLCON_FIS COL_RFIS on (COL_RFIS.BDCODEMP = CRFIS2.BDCODEMP and COL_RFIS.BDCODCOL = CRFIS2.BDCODCOL and COL_RFIS.BDREFCOL = CRFIS2.BDREFCOL) '||
         'left outer join ( '||
           'select VW_COL_REF_ATUAL.BDCODEMP, VW_COL_REF_ATUAL.BDCODCOL, max(VW_COL_REF_ATUAL.BDREFCOL) BDREFCOL '||
           'from VRHF_EMP_TCOL_CALC VW_COL_REF_ATUAL '||
           'where VW_COL_REF_ATUAL.BDREFCOL <= '||prreferencia||' '||
           'group by VW_COL_REF_ATUAL.BDCODEMP, VW_COL_REF_ATUAL.BDCODCOL '||
         ') CRCALC2 on (CRCALC2.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and CRCALC2.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) '||
         'left outer join VRHF_EMP_TCOL_CALC COL_RCALC on (COL_RCALC.BDCODEMP = CRCALC2.BDCODEMP and COL_RCALC.BDCODCOL = CRCALC2.BDCODCOL and COL_RCALC.BDREFCOL = CRCALC2.BDREFCOL) '||
         'left outer join VRH_EMP_TCOL_HIST COL_HIST on (COL_HIST.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and COL_HIST.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) '||
         'left outer join ( '||
           'select VW_COL_REF_ATUAL.BDCODEMP, VW_COL_REF_ATUAL.BDCODCOL, max(VW_COL_REF_ATUAL.BDREFCOL) BDREFCOL '||
           'from VRHF_EMP_TCOLCON_BANCO VW_COL_REF_ATUAL '||
           'where VW_COL_REF_ATUAL.BDREFCOL <= '||prreferencia||' '||
           'group by VW_COL_REF_ATUAL.BDCODEMP, VW_COL_REF_ATUAL.BDCODCOL '||
         ') CBAN2 on (CBAN2.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and CBAN2.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) '||
         'left outer join VRHF_EMP_TCOLCON_BANCO COL_BANCO on (COL_BANCO.BDCODEMP = CBAN2.BDCODEMP and COL_BANCO.BDCODCOL = CBAN2.BDCODCOL and COL_BANCO.BDREFCOL = CBAN2.BDREFCOL) '||
         'left outer join TCIDADE TCIDEMP on (TCIDEMP.BDCODCID = EMP_REF.BDCODCID) '||
         'left outer join TUF TUFEMP on (TUFEMP.BDCODUF = TCIDEMP.BDCODUF) '||
         'left outer join TCIDADE TCIDNASCCOL on (TCIDNASCCOL.BDCODCID = VW_COL_REF_ATUAL.BDCODCIDNASC) '||
         'left outer join TUF TUFNASCCOL on (TUFNASCCOL.BDCODUF = TCIDNASCCOL.BDCODUF) '||
         'left outer join TCIDADE TCIDCOL on (TCIDCOL.BDCODCID = COL_CAD.BDCODCID) '||
         'left outer join TUF TUFCOL on (TUFCOL.BDCODUF = TCIDCOL.BDCODUF) '||
         'left outer join TPAIS TPAISCOL on (TPAISCOL.BDCODPAIS = COL_HIST.BDCODPAIS) '||
         'left outer join VRH_BASE_TSINDTRAB TSINTRAB on (TSINTRAB.BDCODSINTRAB = CAD_VINC.BDCODSINTRAB) '||
         'left outer join SP_TCOLCON_VINCDIA_ADM(VW_COL_REF_ATUAL.BDCODEMP, VW_COL_REF_ATUAL.BDCODCOL) COL_DIAVINC on (COL_DIAVINC.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and '||
               'COL_DIAVINC.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) '||
         'left outer join VRH_FUNCOES_TFUC TFUC on (TFUC.BDCODPLAFUC = COL_DIAVINC.BDCODPLAFUC and '||
               'TFUC.BDCODTFUC = COL_DIAVINC.BDCODTFUC) '||
         'left outer join VW_RESCISAO on (VW_RESCISAO.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and '||
               'VW_RESCISAO.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) '||
         'left outer join VRH_EMP_TCOLCON_IMG TCOLCON_IMG on (TCOLCON_IMG.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and '||
               'TCOLCON_IMG.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) '||
         'left outer join TUF TUFCTPS on (TUFCTPS.BDCODUF = CAD_DOC.BDCODUF) '||
         'left outer join VRH_BASE_TCATEGORIA TCATEG on (TCATEG.BDCODCATEGORIA = CAD_FGTS.BDCATEGORIACOL) '||
         'left outer join ( '||
           'select VW_COL_REF_ATUAL.BDCODEMP, max(VW_COL_REF_ATUAL.BDREFEMP) BDREFEMP '||
           'from VRHF_BASE_TEMPSEFIP VW_COL_REF_ATUAL '||
           'where VW_COL_REF_ATUAL.BDREFEMP <= '||prreferencia||' '||
           'group by VW_COL_REF_ATUAL.BDCODEMP '||
         ') ESEFIP2 on (ESEFIP2.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP) '||
         'left outer join VRHF_BASE_TEMPSEFIP EMPSEFIP on (EMPSEFIP.BDCODEMP = ESEFIP2.BDCODEMP and EMPSEFIP.BDREFEMP = ESEFIP2.BDREFEMP) '||
         'left outer join TBANCOS TBAN on (TBAN.BDCODBAN = EMPSEFIP.BDCODBAN) '||
         'left outer join TBANCOS_AG TBANAG on (TBANAG.BDCODBAN = EMPSEFIP.BDCODBAN and '||
               'TBANAG.BDCODAG = EMPSEFIP.BDCODAG) '||
         'left outer join TUF UF_RG on (UF_RG.BDCODUF = CAD_DOC.BDCODUFRG) ' ||
         'left outer join VRH_EMP_TCOLCON_FIS FIS ON (FIS.BDCODEMP = COL_CAD.BDCODEMP AND FIS.BDCODCOL = COL_CAD.BDCODCOL AND FIS.bdrefcol=COL_CAD.bdrefcol) '||
         'left outer join VRHF_BASE_TEMPPAR PAR ON (EMP_REF2.BDCODEMP = PAR.BDCODEMP AND EMP_REF2.bdrefemp=PAR.bdrefemp)';
         
  IF (probs IS NOT NULL AND probs = 1) THEN
     wSql = wSql || 'left outer join VRHF_EMP_TCOL_HIST CHIST on (CHIST.BDCODEMP = VW_COL_REF_ATUAL.BDCODEMP and CHIST.BDCODCOL = VW_COL_REF_ATUAL.BDCODCOL) ';

  wwhere = '';

  IF (prempresa <> '') THEN
     wwhere = wwhere||prempresa||' ';
  /*Wesley Kowalsi - 18/05/2018 - Solicitação: 23914 -  Corrigindo erro com o filtro do colaborador*/
  IF ((prcolaborador <> '') and (prcolaborador <> '''''')) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador||' ';
     END

  IF (prfuncao <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prfuncao||' ';
     END

  IF (prSindicato <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prsindicato||' ';
     END

  IF (prclasse <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prClasse||' ';
     END

  IF (prcentrocusto <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcentrocusto||' ';
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;


  worderby = '';
  IF (prordemimp IS NOT NULL) THEN
     BEGIN
        worderby = 'order by ';
        
        IF (prordemimp = 0) THEN
           worderby = wOrderBy||'vw_col_ref_atual.bdcodemp, vw_col_ref_atual.bdcodcol ';
        ELSE
           IF (prordemimp = 1) THEN
              worderby = wOrderBy||'vw_col_ref_atual.bdcodemp, BDNOMCOLORDEM, vw_col_ref_atual.bdcodcol ';
     END

  wsql = wsql||wwhere||worderby;

  FOR EXECUTE STATEMENT wsql
      INTO
           :bdcodemp,
           :bdnomemp,
           :bdcnpjemp,
           :bdlogremp,
           :bdendemp,
           :bdnumemp,
           :bdcomplemp,
           :bdbaiemp,
           :bdcidadeemp,
           :bdufemp,
           :bdcepemp,
           :bdfoneemp,
           :bddddemp,
           :bdcodcol,
           :bdnomcol,
           :bdnomcolordem,
           :bdnompaicol,
           :bdnommaecol,
           :bdnomconjcol,
           :bddatanasccol,
           :bdcorcol,
           :bdsexocol, 
           :bddatachebrasilcol,
           :bdpaiscol,
           :bdnacionalidade,
           :bdcidadenasccol,
           :bdufnasccol,
           :bdtiposanguecol,
           :bdcpfcol,
           :bdrgcol,
           :bddataemiregcol,
           :bdorgemirgcol,
           :bdcnhcol,
           :bdcatcnhcol,
           :bdvencnhcol,
           :bdctpscol,
           :bdseriecol,
           :bddseriectpscol,
           :bdreservistacol,
           :bdtiteleicol,
           :bdgrauinstcol,
           :bdzonaeleicol,
           :bdsecaoeleicol,
           :bdpiscol,
           :bddataemipiscol,
           :bdestcivcol,
           :bdlogrcol,
           :bdendcol,
           :bdnumcol,
           :bdcomplcol,
           :bdbaicol,
           :bdcidadecol,
           :bdufcol,
           :bdcepcol,
           :bdfonecol,
           :bddddcol,
           :bdemailcol,
           :bdcelcol,
           :bddataadmcol,
           :bddatacadcol,
           :bdsalinicol,
           :bdformapagtocol,
           :bdpercinsalubcol,
           :bdpercperculcol,
           :bdcategoriacol,
           :bdcodsintrab,
           :bddescsintrab,
           :bddefcol,
           :bddeffisicocol,
           :bdtipocol,
           :bdctafgtscol,
           :bddataopcaofgtscol,
           :bdctadepcol,
     :bddigctadepcol,
           :bdcodtfuc,
           :bddesctfuc,
           :bdcodcbo,
           :bddatarescisao,
           :bddataavprevio,
           :bdsaldofgts,
           :bdmaiorremuneracao,
           :bddatapaggrfc,
           :bdcodpres,
           :bddescpres,
           :bdfotocol,
           :bdficharegcol,
           :bdlivroregcol,
           :bdnrofolharegcol,
           :bdufctps,
           :bddesccategoria,
           :bdnomban,
           :bdcodban,
           :bdnomag,
           :bdcodag,
           :bdnaturalizadocol,
           :bdcabeloscol,
           :bdolhoscol,
           :bdalturacol,
           :bdpesocol,
           :bdsinaiscol,
           :bdcontrcol,
           :bdobscol,
           :bddddcelcol,
           :bdsiglaufrg,
           :bdreab,
           :bdcodcla,
           :BDTIPOESCALA
         DO
       BEGIN

         IF (bddatanasccol IS NOT NULL) THEN
            BEGIN
              bddianasc = SUBSTRING(CAST(bddatanasccol AS VARCHAR(10)) FROM 9 FOR 2);
              bdmesnasc = SUBSTRING(CAST(bddatanasccol AS VARCHAR(10)) FROM 6 FOR 2);
              bdanonasc = SUBSTRING(CAST(bddatanasccol AS VARCHAR(10)) FROM 1 FOR 4);
            END

         wcodcentro = NULL;
         wcodtpcc = NULL;
         wnomtpcc = NULL;
         wnomcidtpcc = NULL;
         wuftpcc = NULL;
         wordemtpcc = NULL;
         
        /*Wesley Kowalski - 18/05/2018 - Solicitação: 23914 - 
          Alterado o sql para pegar o último centro de custo lançado no colaborador, antes não estava trazendo corretamente o último centro de custo.*/    
          select first 1 BDCODCENTRO, BDCODTPCC, BDORDEM
          from (select BDCODCENTRO, BDCODTPCC, BDORDEM
                from VRHF_EMP_TPREPFN
                where BDCODEMP = :bdcodemp and
                      BDCODCOL = :bdcodcol
                order by BDCODCOL ASC, BDORDEM DESC
               ) as X
          ORDER BY BDORDEM DESC
          into :wcodcentro, :wcodtpcc, :wordemtpcc;

         /* verifica se o lançamento é para a empresa */
         IF ((wcodtpcc IS NULL) AND (wordemtpcc IS NOT NULL)) THEN
            BEGIN
              wnomtpcc    = BDNOMEMP;
              wnomcidtpcc = BDCIDADEEMP;
              wuftpcc     = BDUFEMP;
            END
         ELSE
         IF (wcodtpcc IS NOT NULL AND wcodcentro IS NOT NULL) THEN
            BEGIN
              select first 1 COALESCE(CID.BDNOMCID, :BDCIDADEEMP) BDNOMCID,
                     case when ((CID.BDNOMCID = '') or (CID.BDNOMCID is null)) then :BDUFEMP else UF.BDSIGLAUF end BDSIGLAUF,
                     case when ((CT.BDNOMETOM = '') or (CT.BDNOMETOM is null)) then CUS.BDNOMCTA else CT.BDNOMETOM end BDNOMTPCC
              from CENTROS_TPCC CUS
              left outer join VRH_BASE_TCUSTOM CT on (CT.BDCODCENTRO = CUS.BDCODCENTRO and CT.BDCODTPCC = CUS.BDCODTPCC)
              left outer join VRH_BASE_TCUSTOM_END CC on (CC.BDCODCENTRO = CUS.BDCODCENTRO AND CC.BDCODTPCC = CUS.BDCODTPCC AND CC.bdrefcusto=(Select bdrefcusto from (Select BDCODCENTRO,BDCODTPCC, max(bdrefcusto) bdrefcusto from VRH_BASE_TCUSTOM_END where bdrefcusto<=:prreferencia and BDCODCENTRO=CUS.BDCODCENTRO and BDCODTPCC=CUS.BDCODTPCC  group by BDCODCENTRO,BDCODTPCC)))
              left outer join TCIDADE CID on (CID.BDCODCID = CC.BDCODCID)
              left outer join TUF UF on (UF.BDCODUF = CID.BDCODUF)
              where CUS.BDCODCENTRO = :wcodcentro and CUS.BDCODTPCC = :wcodtpcc
              INTO :wnomcidtpcc, :wuftpcc, :wnomtpcc;
            END

         bdcodcentro = wcodcentro;
         bdcodtpcc = wcodtpcc;
         bdnomtpcc = wnomtpcc;
         bdnomcidtpcc = wnomcidtpcc;
         bduftpcc = wuftpcc;
         SUSPEND;
       END
 END^

--Sol. 15882 - Adicionado campo de retorno BDTIPO - Bruno L. R. - 27/10/2016
/* Restore proc. body: VRHF_SP_FICHAFGTS2 */

CREATE OR ALTER procedure VRHF_SP_FICHAFGTS2 (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFFIM integer,
    PRCC varchar(15000) = null,
    PRCALCFERA smallint = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODIND integer,
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBFGTSFC numeric(18,6),
    BDFGTSFC numeric(18,6),
    BDBASEFGTSA13 numeric(18,6),
    BDFGTSA13 numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDBASEFGTSC13 numeric(18,6),
    BDFGTSC13 numeric(18,6),
    BDINDICEJAM numeric(18,6),
    BDSALDOANTFGTS numeric(18,6),
    BDVALORJAM numeric(18,6),
    BDSALDOFGTS numeric(18,6),
    BDSOMAFGTS numeric(18,6),
    BDPERCINDCOMP numeric(18,6),
    BDVALORINDCOMP numeric(18,6),
    BDTIPO integer)
as
declare variable WSQLAUX varchar(3000);
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WANO integer;
declare variable WMES integer;
declare variable WDATA date;
declare variable WTOTALFGTS numeric(15,6);
declare variable WCONTAJAM integer;
declare variable WVALORMES1 numeric(15,6);
declare variable WVALORMES2 numeric(15,6);
declare variable WINDJAMANT numeric(15,6);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WCODIND integer;
declare variable WTEMEMP integer;
declare variable WEMPATU integer;
declare variable WREFATU integer;
declare variable WEMPATU2 integer;
declare variable WREFATU2 integer;
declare variable WCALCFERA13 varchar(5);
declare variable WSQL2 varchar(32700);
declare variable WREFAUX integer;
declare variable WDTGOZO date;
declare variable WVALVERBA numeric(15,6);
declare variable WJOINCOL varchar(300);
declare variable WDATARES date;
BEGIN
  IF (prreffim IS NULL) THEN
     BEGIN
       FOR SELECT CURRENT_DATE FROM rdb$database INTO :wdata DO
       wano = EXTRACT(YEAR FROM :wdata);
       wmes = EXTRACT(MONTH FROM :wdata);
       prreffim = CAST((wano||LPAD(wmes, 2, '0')) as INTEGER);
     END

  EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);

  IF ((PRCODEMP IS NOT NULL) AND (prcodemp <> '')) THEN
       prcodemp = UPPER(prcodemp);

  /*André Cursino - 13/10/2022 - Solicitação 168872 - Comentado o trecho abaixo:
  IF (substring(prcodemp from 1 for 4) = 'TAB.') THEN --SOL.154124 LuizCovre -> Quando no filtro vem TAB. gera erro de Unknown column(tem mais de um apelido de tabela sendo utilizado em vários lugares),
    prcodemp = substring(prcodemp from 5 for 10000);  --mas só assim, outras utilizações dessa SP, vem outros tipos de filtro corretamente
                                                      --caso futuramente ou em algum outro processo der erro etc, basta remover ou comentar esse IF, mas terá de achar outra solução para o problema dessa Solicitção.*/
  prCodEmp = replace(prCodEmp, 'TAB', 'TEMP'); /*André Cursino - 13/10/2022 - Solicitação 168872 - o tab vem do gerador de relatórios*/

  wsql = 'select TEMP.BDCODEMP, '||
                'TEMP.BDCODCOL, '||
                'TEMP.BDREF, '||
                'SUM(TEMP.BDBFGTSFN), '||
                'SUM(TEMP.BDFGTSFN), '||
                'SUM(TEMP.BDBFGTSFC), '||
                'SUM(TEMP.BDFGTSFC), '||
                'SUM(TEMP.BDBASEFGTSA13), '||
                'SUM(TEMP.BDFGTSA13), '||
                'SUM(TEMP.BDBASEFGTS13), '||
                'SUM(TEMP.BDFGTS13), '||
                'SUM(TEMP.BDBASEFGTSC13), '||
                'SUM(TEMP.BDFGTSC13), '||
                'case when COALESCE(TEMP.BDTIPO,0) = 9 then 9 else 0 end BDTIPO, ' || --15882 - Bruno L. R. - 27/10/2016
                'RES.BDDATARESCISAO '; -- Sol.198539 Jackson Nunes 04/04/2024

  if (COALESCE(prCC, '') <> '') then
     begin
       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'Y.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'Y.BDCODCOL');
         end

       wsql = wsql||'from ( '||
                       'SELECT '||
                         'Y.BDCODEMP, '||
                         'Y.BDCODCOL, '||
                         'Y.BDREFFN BDREF, '||
                         'cast(null as integer) BDCODCENTRO, '||
                         'cast(null as integer) BDCODTPCC, '||
                         'Y.BDBFGTSFN + Y.BDBFGTS13FN + COALESCE(Y.bdbfgtsfefn,0) BDBFGTSFN, '||
                         'Y.BDFGTSFN + Y.BDFGTS13FN + COALESCE(Y.bdfgtsfefn,0) BDFGTSFN, '||
                         '0.0 BDBFGTSFC, '||
                         '0.0 BDFGTSFC, '||
                         '0.0 BDBASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '0 BDTIPO '||
                       'FROM VRHF_EMP_TFOLHANORMAL Y '||
                       WJOINCOL||
                       ' where y.bdreffn <= '||prreffim;


       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'Y.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'Y.BDCODCOL');
          end



       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'Y.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'Y.BDCODCOL');
         end

       wsql = wsql||   ' UNION '||
                       'SELECT '||
                         'Y.BDCODEMP, '||
                         'Y.BDCODCOL, '||
                         'Y.BDREFFN, '||
                         'cast(null as integer), '||
                         'cast(null as integer), '||
                         'Y.BDBFGTSFN + COALESCE(Y.bdbfgtsfefn,0), '||
                         'Y.BDFGTSFN + COALESCE(Y.bdfgtsfefn,0), '||
                         '0.0 BDBFGTSFC, '||
                         '0.0 BDFGTSFC, '||
                         'Y.BDBFGTS13FN, '||
                         'Y.BDFGTS13FN, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '0 BDTIPO '||
                       'FROM VRHF_EMP_TFOLHAINT Y '||
                       WJOINCOL||
                       ' where y.bdreffn <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'Y.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'Y.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql||   ' UNION '||
                       'SELECT '||
                         'X.bdcodemp, '||
                         'X.bdcodcol, '||
                         'X.bdreftomador, '||
                         'pfn.bdcodcentro, '||
                         'pfn.bdcodtpcc, '||
                         'X.bdbfgtsft + X.bdbfgts13ft + COALESCE(X.bdbfgtsFEft,0), '||
                         'X.bdfgtsft + X.bdfgts13ft + COALESCE(x.bdfgtsFEft,0), '||
                         '0.0 BDBFGTSFC, '||
                         '0.0 BDFGTSFC, '||
                         '0.0 BDBASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '0 BDTIPO '||
                       'FROM vrhf_emp_tfolhatomador x '||
                       'join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = x.bdcodemp and pfn.bdcodcol = x.bdcodcol and pfn.bdordem = x.bdordem) '||
                       WJOINCOL||
                       ' where x.bdreftomador <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'X.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'X.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end

       wsql = wsql||   ' UNION '||
                       'SELECT '||
                         'X.bdcodemp, '||
                         'X.bdcodcol, '||
                         'X.bdreftomador, '||
                         'pfn.bdcodcentro, '||
                         'pfn.bdcodtpcc, '||
                         'X.bdbfgtsft + COALESCE(X.bdbfgtsFEft,0), '||
                         'X.bdfgtsft + COALESCE(x.bdfgtsFEft,0), '||
                         '0.0 BDBFGTSFC, '||
                         '0.0 BDFGTSFC, '||
                         'X.bdbfgts13ft, '||
                         'X.bdfgts13ft, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '0 BDTIPO '||
                       'FROM vrhf_emp_tfolhatomint x '||
                       'join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = x.bdcodemp and pfn.bdcodcol = x.bdcodcol and pfn.bdordem = x.bdordem) '||
                       WJOINCOL||
                       ' where x.bdreftomador <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'X.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'X.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'C.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'C.BDCODCOL');
         end
       wsql = wsql||   ' UNION '||
                       'SELECT '||
                         'C.BDCODEMP, '||
                         'C.BDCODCOL, '||
                         'C.BDREFCOMP, '||
                         'cast(null as integer), '||
                         'cast(null as integer), '||
                         '0.0 BDBFGTSXX, '||
                         '0.0 BDFGTSXX, '||
                         'C.BDBFGTSFC + C.BDBFGTS13FC + COALESCE(C.BDBFGTSFEFC,0), '||
                         'C.BDFGTSFC + C.BDFGTS13FC + COALESCE(C.BDFGTSFEFC,0), '||
                         '0.0 BDBASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '6 BDTIPO '||
                       'FROM VRHF_EMP_TFOLHACOMP C '||
                       WJOINCOL||
                       ' where C.BDREFCOMP <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'C.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'C.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql||   ' UNION '||
                       'SELECT '||
                         'X.bdcodemp, '||
                         'X.bdcodcol, '||
                         'X.bdrefcomp, '||
                         'pfn.bdcodcentro, '||
                         'pfn.bdcodtpcc, '||
                         '0.0 BDBFGTSXX, '||
                         '0.0 BDFGTSXX, '||
                         'X.bdbfgtsfc + X.bdbfgts13fc + COALESCE(BDBFGTSFEFC,0), '||
                         'X.bdfgtsfC + X.bdfgts13fC + COALESCE(BDFGTSFEFC,0), '||
                         '0.0 BDBASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '6 BDTIPO '||
                       'FROM vrhf_emp_tfoltomcomp x '||
                       'join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = x.bdcodemp and pfn.bdcodcol = x.bdcodcol and pfn.bdordem = x.bdordem) '||
                       WJOINCOL||
                       ' where x.bdrefcomp <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'X.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'X.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'C.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'C.BDCODCOL');
         end
       wsql = wsql||   ' UNION '||
                       'SELECT '||
                         'C.BDCODEMP, '||
                         'C.BDCODCOL, '||
                         'C.BDREFCOMP, '||
                         'cast(null as integer), '||
                         'cast(null as integer), '||
                         '0.0 BDBFGTSXX, '||
                         '0.0 BDFGTSXX, '||
                         'COALESCE(C.BDBFGTSFC, 0) + COALESCE(C.BDBFGTS13FC, 0) + COALESCE(C.BDBFGTSFEFC,0), '||
                         'COALESCE(C.BDFGTSFC, 0) + COALESCE(C.BDFGTS13FC, 0) + COALESCE(C.BDFGTSFEFC,0), '||
                         '0.0 BDBASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '6 BDTIPO '||
                       'FROM VRHF_EMP_TFOLHACOMPINT C '||
                       WJOINCOL||
                       ' where C.BDREFCOMP <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'C.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'C.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql||   ' UNION '||
                       'SELECT '||
                         'X.bdcodemp, '||
                         'X.bdcodcol, '||
                         'X.bdrefcomp, '||
                         'pfn.bdcodcentro, '||
                         'pfn.bdcodtpcc, '||
                         '0.0 BDBFGTSXX, '||
                         '0.0 BDFGTSXX, '||
                         'X.bdbfgtsfc + X.bdbfgts13fc + COALESCE(BDBFGTSFEFC,0), '||
                         'X.bdfgtsfC + X.bdfgts13fC + COALESCE(BDFGTSFEFC,0), '||
                         '0.0 BDBASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '6 BDTIPO '||
                       'FROM VRHF_EMP_TFOLTOMCOMPINT X '||
                       'join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = x.bdcodemp and pfn.bdcodcol = x.bdcodcol and pfn.bdordem = x.bdordem) '||
                       WJOINCOL||
                       ' where X.BDREFCOMP <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'X.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'X.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'A13.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'A13.BDCODCOL');
         end
       wsql = wsql||   ' UNION '||
                       'SELECT '||
                         'A13.BDCODEMP, '||
                         'A13.BDCODCOL, '||
                         'A13.BDREFA13, '||
                         'pfn.BDCODCENTRO, '||
                         'pfn.BDCODTPCC, '||
                         '0.0 BDBFGTSFN, '||
                         '0.0 BDFGTSFN, '||
                         '0.0 BDBFGTSFC, '||
                         '0.0 BDFGTSFC, '||
                         '0.0 BDBASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         'A13.BDBASEFGTSA13, '||
                         'A13.BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '2 BDTIPO '||
                       'FROM VRHF_EMP_TA13SAL A13 '||
                       'left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = a13.bdcodemp and pfn.bdcodcol = a13.bdcodcol and pfn.bdordem = a13.bdordem) '||
                       WJOINCOL||
                       ' where A13.BDREFA13 <= '||prreffim;
                       if (prcalcfera is not null) then
                          wsql = wSql ||' AND a13.bdcalcfera13 <> ''TRUE'''; --30535 Valmor h Junior - Adicionado filtro bdcalcfera13, para verificar se o o adiantamento de 13 foi calculado junto as ferias.

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'A13.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'A13.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'S13.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'S13.BDCODCOL');
         end
       wsql = wsql||   ' UNION '||
                       'SELECT '||
                         'S13.BDCODEMP, '||
                         'S13.BDCODCOL, '||
                         'S13.BDREF13, '||
                         'pfn.BDCODCENTRO, '||
                         'pfn.BDCODTPCC, '||
                         '0.0 BDBFGTSFN, '||
                         '0.0 BDFGTSFN, '||
                         '0.0 BDBFGTSFC, '||
                         '0.0 BDFGTSFC, '||
                         'S13.BDBASEFGTS13, '||
                         'S13.BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '3 BDTIPO '||
                       'FROM VRHF_EMP_T13SAL S13 '||
                       'left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = s13.bdcodemp and pfn.bdcodcol = s13.bdcodcol and pfn.bdordem = s13.bdordem) '||
                       WJOINCOL||
                       ' where S13.BDREF13 <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'S13.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'S13.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'C13.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'C13.BDCODCOL');
         end
       wsql = wsql||   ' UNION '||
                       'SELECT '||
                         'C13.BDCODEMP, '||
                         'C13.BDCODCOL, '||
                         'C13.BDREFC13, '||
                         'pfn.BDCODCENTRO, '||
                         'pfn.BDCODTPCC, '||
                         '0.0 BDBFGTSFN, '||
                         '0.0 BDFGTSFN, '||
                         '0.0 BDBFGTSFC, '||
                         '0.0 BDFGTSFC, '||
                         '0.0 BDBASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         'C13.BDBASEFGTSC13, '||
                         'C13.BDFGTSC13, '||
                         '4 BDTIPO '||
                       'FROM VRHF_EMP_TC13SAL C13 '||
                       'left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = c13.bdcodemp and pfn.bdcodcol = c13.bdcodcol and pfn.bdordem = c13.bdordem) '||
                       WJOINCOL||
                       ' where C13.BDREFC13 <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'C13.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'C13.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'FA.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'FA.BDCODCOL');
         end
       wsql = wsql||   ' UNION '||
                       'SELECT '||
                         'FA.BDCODEMP, '||
                         'FA.BDCODCOL, '||
                         'CAST((SUBSTRING(CAST(FA.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FA.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) BDREFFA, '||
                         'pfn.BDCODCENTRO, '||
                         'pfn.BDCODTPCC, '||
                         'FA.BDBFGTSFA + FA.BDBFGTS13FA + COALESCE(FA.bdbfgtsfefa,0), '||
                         'FA.BDFGTSFA + FA.BDFGTS13FA + COALESCE(FA.bdfgtsfefa,0), '||
                         '0.0 BDBFGTSFC, '||
                         '0.0 BDFGTSFC, '||
                         '0.0 BDBFGTS13FAASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '5 BDTIPO '||
                       'FROM VRHF_EMP_TFOLHAAVULSA FA '||
                       'left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = fa.bdcodemp and pfn.bdcodcol = fa.bdcodcol and pfn.bdordem = fa.bdordem) '||
                       WJOINCOL||
                       ' where FA.BDREF <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'FA.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'FA.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql||   ' UNION '||
                       'SELECT '||
                         'X.BDCODEMP, '||
                         'X.BDCODCOL, '||
                         'X.BDREF_FFGTS, '||
                         'cast(null as integer), cast(null as integer), '||
                         'case when X.BDTIPO_FFGTS not in (3, 4, 5, 7) then X.BDBFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS not in (3, 4, 5, 7) then X.BDFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS = 7 then X.BDBFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS = 7 then X.BDFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS = 4 then X.BDBFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS = 4 then X.BDFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS = 3 then X.BDBFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS = 3 then X.BDFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS = 5 then X.BDBFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS = 5 then X.BDFGTS_FFGTS else 0.00 end, '||
                         '9 BDTIPO '||
                       'FROM VRHF_EMP_TFICHAFGTS X '||
                       WJOINCOL||
                       ' WHERE X.BDREF_FFGTS <= '||prreffim||' AND '||
                             '((X.BDTIPO_FFGTS = 1 AND  '||-- Folha normal
                              'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhanormal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREF_FFGTS) AND '||
                              'NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfolhatomador Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFTOMADOR = X.BDREF_FFGTS) AND '||
                              'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhaint Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREF_FFGTS) AND '||
                              'NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfolhatomint Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFTOMADOR = X.BDREF_FFGTS)) '||
                             'OR (X.BDTIPO_FFGTS = 3 AND  '||-- Adiantamento de 13 salario
                                 'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_ta13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFA13 = X.BDREF_FFGTS)) '||
                             'OR (X.BDTIPO_FFGTS = 4 AND  '||-- 13 salario
                                 'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_t13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREF13 = X.BDREF_FFGTS)) '||
                             'OR (X.BDTIPO_FFGTS = 5 AND  '||-- Complemento de 13 salario
                                 'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tc13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFC13 = X.BDREF_FFGTS)) '||
                             'OR (X.BDTIPO_FFGTS = 7 AND  '||-- Folha complementar
                                 'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhacomp Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFCOMP = X.BDREF_FFGTS) AND '||
                                 'NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfoltomcomp Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFCOMP = X.BDREF_FFGTS) AND '||
                                 'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhacompint Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFCOMP = X.BDREF_FFGTS) AND '||
                                 'NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfoltomcompint Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFCOMP = X.BDREF_FFGTS))) ';

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'X.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'X.BDCODCOL');
          end

       wsql = wsql||') TEMP ';
     end
  else
     begin

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'Y.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'Y.BDCODCOL');
         end
       wsql = wsql||'from (select '||
                       'Y.BDCODEMP, '||
                       'Y.BDCODCOL, '||
                       'Y.BDREFFN BDREF, '||
                       'Y.BDBFGTSFN + Y.BDBFGTS13FN + COALESCE(Y.bdbfgtsfefn,0) BDBFGTSFN, '||
                       'Y.BDFGTSFN + Y.BDFGTS13FN + COALESCE(Y.bdfgtsfefn,0) BDFGTSFN, '||
                       '0.0 BDBFGTSFC, '||
                       '0.0 BDFGTSFC, '||
                       '0.0 BDBASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '0 BDTIPO '||
                     'FROM VRHF_EMP_TFOLHANORMAL Y '||
                     WJOINCOL||
                     ' where Y.bdreffn <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'Y.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'Y.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'Y.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'Y.BDCODCOL');
         end
       wsql = wsql|| ' UNION '||
                     'SELECT '||
                       'Y.BDCODEMP, '||
                       'Y.BDCODCOL, '||
                       'Y.BDREFFN, '||
                       'Y.BDBFGTSFN + COALESCE(Y.bdbfgtsfefn,0), '||
                       'Y.BDFGTSFN + COALESCE(Y.bdfgtsfefn,0), '||
                       '0.0 BDBFGTSFC, '||
                       '0.0 BDFGTSFC, '||
                       'Y.BDBFGTS13FN, '||
                       'Y.BDFGTS13FN, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '0 BDTIPO '||
                     'FROM VRHF_EMP_TFOLHAINT Y '||
                     replace(WJOINCOL, 'TEMP.BDCODCOL', 'Y.BDCODCOL')||
                     ' where y.bdreffn <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'Y.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'Y.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql|| ' UNION '||
                     'SELECT '||
                       'X.bdcodemp, '||
                       'X.bdcodcol, '||
                       'X.bdreftomador, '||
                       'X.bdbfgtsft + X.bdbfgts13ft + COALESCE(X.bdbfgtsFEft,0), '||
                       'X.bdfgtsft + X.bdfgts13ft + COALESCE(x.bdfgtsFEft,0), '||
                       '0.0 BDBFGTSFC, '||
                       '0.0 BDFGTSFC, '||
                       '0.0 BDBASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '0 BDTIPO '||
                     'FROM vrhf_emp_tfolhatomador x '||
                     WJOINCOL||
                     ' where x.bdreftomador <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'x.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'x.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql|| ' UNION '||
                     'SELECT '||
                       'X.bdcodemp, '||
                       'X.bdcodcol, '||
                       'X.bdreftomador, '||
                       'X.bdbfgtsft + COALESCE(X.bdbfgtsFEft,0), '||
                       'X.bdfgtsft + COALESCE(x.bdfgtsFEft,0), '||
                       '0.0 BDBFGTSFC, '||
                       '0.0 BDFGTSFC, '||
                       'X.bdbfgts13ft, '||
                       'X.bdfgts13ft, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '0 BDTIPO '||
                     'FROM vrhf_emp_tfolhatomint x '||
                     WJOINCOL||
                     ' where x.bdreftomador <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'x.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'x.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'C.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'C.BDCODCOL');
         end
       wsql = wsql|| ' UNION '||
                     'SELECT '||
                       'C.BDCODEMP, '||
                       'C.BDCODCOL, '||
                       'C.BDREFCOMP, '||
                       '0.0 BDBFGTSXX, '||
                       '0.0 BDFGTSXX, '||
                       'C.BDBFGTSFC + C.BDBFGTS13FC + COALESCE(C.BDBFGTSFEFC,0), '||
                       'C.BDFGTSFC + C.BDFGTS13FC + COALESCE(C.BDFGTSFEFC,0), '||
                       '0.0 BDBASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '6 BDTIPO '||
                     'FROM VRHF_EMP_TFOLHACOMP C '||
                     WJOINCOL||
                     ' where C.BDREFCOMP <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'C.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'C.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql|| ' UNION '||
                     'SELECT '||
                       'X.bdcodemp, '||
                       'X.bdcodcol, '||
                       'X.bdrefcomp, '||
                       '0.0 BDBFGTSXX, '||
                       '0.0 BDFGTSXX, '||
                       'X.bdbfgtsfc + X.bdbfgts13fc + COALESCE(BDBFGTSFEFC,0), '||
                       'X.bdfgtsfC + X.bdfgts13fC + COALESCE(BDFGTSFEFC,0), '||
                       '0.0 BDBASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '6 BDTIPO '||
                     'FROM vrhf_emp_tfoltomcomp x '||
                     WJOINCOL||
                     ' where x.bdrefCOMP <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'x.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'x.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'C.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'C.BDCODCOL');
         end
       wsql = wsql|| ' UNION '||
                     'SELECT '||
                       'C.BDCODEMP, '||
                       'C.BDCODCOL, '||
                       'C.BDREFCOMP, '||
                       '0.0 BDBFGTSXX, '||
                       '0.0 BDFGTSXX, '||
                       'C.BDBFGTSFC + C.BDBFGTS13FC + COALESCE(C.BDBFGTSFEFC,0), '||
                       'C.BDFGTSFC + C.BDFGTS13FC + COALESCE(C.BDFGTSFEFC,0), '||
                       '0.0 BDBASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '6 BDTIPO '||
                     'FROM VRHF_EMP_TFOLHACOMPINT C '||
                     WJOINCOL||
                     ' where C.BDREFCOMP <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'C.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'C.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql|| ' UNION '||
                     'SELECT '||
                       'X.bdcodemp, '||
                       'X.bdcodcol, '||
                       'X.bdrefcomp, '||
                       '0.0 BDBFGTSXX, '||
                       '0.0 BDFGTSXX, '||
                       'X.bdbfgtsfc + X.bdbfgts13fc + COALESCE(BDBFGTSFEFC,0), '||
                       'X.bdfgtsfC + X.bdfgts13fC + COALESCE(BDFGTSFEFC,0), '||
                       '0.0 BDBASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '6 BDTIPO '||
                     'FROM VRHF_EMP_TFOLTOMCOMPINT X '||
                     WJOINCOL||
                     ' where x.bdrefCOMP <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'x.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'x.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'A.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'A.BDCODCOL');
         end
       wsql = wsql|| ' UNION '||
                     'SELECT '||
                       'A.BDCODEMP, '||
                       'A.BDCODCOL, '||
                       'A.BDREFA13, '||
                       '0.0 BDBFGTSFN, '||
                       '0.0 BDFGTSFN, '||
                       '0.0 BDBFGTSFC, '||
                       '0.0 BDFGTSFC, '||
                       '0.0 BDBASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       'A.BDBASEFGTSA13, '||
                       'A.BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '2 BDTIPO '||
                     'FROM VRHF_EMP_TA13SAL A '||
                     WJOINCOL||
                     ' where A.BDREFA13 <= '||prreffim;
                      if (prcalcfera is not null) then
                          wsql = wSql ||' AND A.bdcalcfera13 <> ''TRUE'''; --30535 Valmor h Junior - Adicionado filtro bdcalcfera13, para verificar se o o adiantamento de 13 foi calculado junto as ferias.

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'A.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'A.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'D.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'D.BDCODCOL');
         end
       wsql = wsql|| ' UNION '||
                     'SELECT '||
                       'D.BDCODEMP, '||
                       'D.BDCODCOL, '||
                       'D.BDREF13, '||
                       '0.0 BDBFGTSFN, '||
                       '0.0 BDFGTSFN, '||
                       '0.0 BDBFGTSFC, '||
                       '0.0 BDFGTSFC, '||
                       'D.BDBASEFGTS13, '||
                       'D.BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '3 BDTIPO '||
                     'FROM VRHF_EMP_T13SAL D '||
                     WJOINCOL||
                     ' where D.BDREF13 <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'D.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'D.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'C.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'C.BDCODCOL');
         end
       wsql = wsql|| ' UNION '||
                     'SELECT '||
                       'C.BDCODEMP, '||
                       'C.BDCODCOL, '||
                       'C.BDREFC13, '||
                       '0.0 BDBFGTSFN, '||
                       '0.0 BDFGTSFN, '||
                       '0.0 BDBFGTSFC, '||
                       '0.0 BDFGTSFC, '||
                       '0.0 BDBASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       'C.BDBASEFGTSC13, '||
                       'C.BDFGTSC13, '||
                       '4 BDTIPO '||
                     'FROM VRHF_EMP_TC13SAL C '||
                     WJOINCOL||
                     ' where C.BDREFC13 <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'C.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'C.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'A.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'A.BDCODCOL');
         end
       wsql = wsql|| ' UNION '||
                     'SELECT '||
                       'A.BDCODEMP, '||
                       'A.BDCODCOL, '||
                       'A.BDREF, '||
                       'A.BDBFGTSFA + A.BDBFGTS13FA + COALESCE(A.bdbfgtsfefa,0), '||
                       'A.BDFGTSFA + A.BDFGTS13FA + COALESCE(A.bdfgtsfefa,0), '||
                       '0.0 BDBFGTSFC, '||
                       '0.0 BDFGTSFC, '||
                       '0.0 BDBFGTS13FAASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '5 BDTIPO '||
                     'FROM VRHF_EMP_TFOLHAAVULSA A '||
                     WJOINCOL||
                     ' where A.BDREF <= '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'A.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'A.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql|| ' UNION '||
                     'SELECT '||
                       'X.BDCODEMP, '||
                       'X.BDCODCOL, '||
                       'X.BDREF_FFGTS, '||
                       'case when X.BDTIPO_FFGTS not in (3, 4, 5, 7) then X.BDBFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS not in (3, 4, 5, 7) then X.BDFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS = 7 then X.BDBFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS = 7 then X.BDFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS = 4 then X.BDBFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS = 4 then X.BDFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS = 3 then X.BDBFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS = 3 then X.BDFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS = 5 then X.BDBFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS = 5 then X.BDFGTS_FFGTS else 0.00 end, '||
                       '9 BDTIPO '||
                     'FROM VRHF_EMP_TFICHAFGTS X '||
                     WJOINCOL||
                     ' WHERE X.BDREF_FFGTS <= '||prreffim||
                            ' and ((X.BDTIPO_FFGTS = 1 AND  '||-- Folha normal
                            'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhanormal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREF_FFGTS) AND '||
                            'NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfolhatomador Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFTOMADOR = X.BDREF_FFGTS) AND '||
                            'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhaint Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREF_FFGTS) AND '||
                            'NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfolhatomint Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFTOMADOR = X.BDREF_FFGTS)) '||
                           'OR (X.BDTIPO_FFGTS = 3 AND  '||-- Adiantamento de 13 salario
                               'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_ta13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFA13 = X.BDREF_FFGTS)) '||
                           'OR (X.BDTIPO_FFGTS = 4 AND   '||-- 13 salario
                               'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_t13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREF13 = X.BDREF_FFGTS)) '||
                           'OR (X.BDTIPO_FFGTS = 5 AND   '||-- Complemento de 13 salario
                               'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tc13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFC13 = X.BDREF_FFGTS)) '||
                           'OR (X.BDTIPO_FFGTS = 7 AND  '||-- Folha complementar
                               'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhacomp Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFCOMP = X.BDREF_FFGTS) AND '||
                               'NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfoltomcomp Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFCOMP = X.BDREF_FFGTS) AND '||
                               'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhacompint Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFCOMP = X.BDREF_FFGTS) AND '||
                               'NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfoltomcompint Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFCOMP = X.BDREF_FFGTS))) ';

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'X.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'X.BDCODCOL');
          end

       wsql = wsql||') TEMP ';
     end
  wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RES on (RES.BDCODEMP = TEMP.BDCODEMP and  RES.BDCODCOL = TEMP.BDCODCOL)';  -- Sol.198539 Jackson Nunes 04/04/2024
  wwhere = '';

  if (COALESCE(prCC, '') <> '') then
     begin
       prcc = UPPER(prcc);
       wwhere = wwhere||' where '||replace(prcc, 'BDCODTPCC', 'TEMP.BDCODTPCC')||' ';
     end

  -- Group by
  wwhere = wwhere||
           ' group by TEMP.BDCODEMP, TEMP.BDCODCOL, TEMP.BDREF, BDTIPO, RES.BDDATARESCISAO '; -- Sol.198539 Jackson Nunes 04/04/2024

  wsql = wsql||wwhere;
  wsql = wsql||' order by TEMP.BDCODEMP, TEMP.BDCODCOL, TEMP.BDREF, BDTIPO ';

  windjamant = 0;
  wcodemp = 0;
  wcodcol = 0;

  wtememp  = 0;
  wempatu  = 0;
  wrefatu  = 999999;
  wrefatu2 = 999999;
  wempatu2 = 0;

  FOR EXECUTE STATEMENT wsql
    INTO
      :BDCODEMP,
      :BDCODCOL,
      :BDREF,
      :BDBFGTS,
      :BDFGTS,
      :BDBFGTSFC,
      :BDFGTSFC,
      :BDBASEFGTSA13,
      :BDFGTSA13,
      :BDBASEFGTS13,
      :BDFGTS13,
      :BDBASEFGTSC13,
      :BDFGTSC13,
      :BDTIPO,
      :WDATARES
    DO
      BEGIN
        if (wempatu <> bdcodemp) then
           begin
             -- Filtra permissões por empresas
             wtememp = null;
             execute statement 'select first 1 BDCODEMP from VW_EMPRESAS_REF_ATUAL where BDCODEMP = '||:BDCODEMP into :wtememp;
             wtememp = coalesce(wtememp, 0);
             wempatu = bdcodemp;
           end

        if (wtememp > 0) then
           begin
             if ((wempatu2 <> BDCODEMP) or (BDREF < wrefatu) or (BDREF < wrefatu2)) then
                begin
                  if ((wempatu2 <> BDCODEMP) or (BDREF < wrefatu)) then
                     begin
                       wsqlAux = 'select first 1 BDCODIND, BDREFEMP from VRHF_BASE_TEMPVINC where BDCODEMP = '||bdcodemp||' and BDREFEMP <= '||bdref||' order by BDREFEMP DESC ';
        wcodind = NULL;
                       EXECUTE STATEMENT wsqlaux INTO :wcodind, :wrefatu;
        BDCODIND = wcodind;
                     end

                  if ((wempatu2 <> BDCODEMP) or (BDREF < wrefatu)) then
                     begin
                       wsqlaux = 'select first 1 coalesce(bdindcomp, 0) bdindcomp, BDREFEMP from VRHF_BASE_TEMPGPS x where x.bdcodemp = '||wcodemp||' and x.bdrefemp <= '||:bdref||' order by bdcodemp, bdrefemp desc';
                       EXECUTE STATEMENT wsqlaux INTO :BDPERCINDCOMP, :wrefatu2;
                     end

                  wempatu2 = BDCODEMP;
                end
     
        IF (wcodemp <> :bdcodemp OR (wcodcol <> :bdcodcol)) THEN
           BEGIN
             wtotalfgts = 0;
             wcontajam = 0;
             wvalormes1 = NULL;
             wvalormes2 = NULL;
      
             wcodemp = :bdcodemp;
             wcodcol = :bdcodcol;
           END
    
     
        wcontajam = wcontajam + 1;
    
        bdindicejam = 0;
    

    
      --IF (wcontajam > 2) THEN Sol.154642 LuizCovre 08/11/21
        IF (wcontajam > 0) THEN
        BEGIN
          IF ((bdcodind IS NOT NULL) AND (:bdcodind > 0) AND (:bdref > 0)) THEN
          BEGIN
            wsqlaux = 'select x.bdvalind from TINDVAL x where x.bdcodind = '||:bdcodind||' and x.bdrefind = '||:bdref;

            if (:wdatares is not null) then      -- Sol.198539 Jackson Nunes 04/04/2024
               begin
                 wsqlaux = wsqlaux || ' and x.bddataind <= ''' || :wdatares || '''';
               end

            EXECUTE STATEMENT wsqlaux INTO :bdindicejam;
          END
          ELSE
          BEGIN
            bdindicejam = 0;
          END
        END

        IF (BDTIPO = 0) then                  -- 167754 JoãoVictor 10/01/23
          begin
            if (BDBASEFGTSA13 > 0) then
              begin
                select A13.BDCALCFERA13
                from VRHF_EMP_TA13SAL A13
                WHERE A13.BDCODEMP = :BDCODEMP and A13.BDCODCOL = :BDCODCOL and A13.BDREFA13 = :BDREF
                  into :WCALCFERA13;

                 select max(BDINIPERGOZOFE) from SP_VRHF_GETFERIAS(:BDCODEMP, :BDCODCOL, :BDREF) where BDCALCA13FE = 'TRUE' into :WDTGOZO;
                 WREFAUX = extract (year from WDTGOZO) || RIGHT('0'||trim(EXTRACT(MONTH from WDTGOZO)), 2);

                 if ((:WCALCFERA13 = 'TRUE') and (WREFAUX is not null)) then
                   begin
                     WSQL2 =  '  select FOL.BDVALVFN '||
                              '  from VRHF_EMP_TVERBAFN FOL '||
                              '  join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                              '  left outer join VRH_BASE_TVERBAS_REF REF on REF.BDCODVER = VER.BDCODVER and '||
                                                 ' REF.BDREFVER = (select max(BDREFVER) '||
                                                               '  from VRH_BASE_TVERBAS_REF '||
                                                               ' where BDCODVER = VER.BDCODVER and '||
                                                               ' BDREFVER <= '||:WREFAUX||') '||
                              ' where (FOL.BDCODEMP = '||:BDCODEMP||') and '||
                                    ' (FOL.BDCODCOL in ('||:BDCODCOL||')) and '||
                                    ' (FOL.BDREFFN = '||:WREFAUX||') and '||
                                    ' (VER.BDCLAVER like ''0.191%'') and '||
                                    ' (REF.BDFGTSVER = 3) '||
                              ' union all '||
                              ' select FOL.BDVALVFT '||
                              ' from VRHF_EMP_TVERBATOMADOR FOL '||
                              ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                              ' left outer join VRH_BASE_TVERBAS_REF REF on REF.BDCODVER = VER.BDCODVER and '||
                              '        REF.BDREFVER = (select max(BDREFVER) '||
                                                    ' from VRH_BASE_TVERBAS_REF '||
                                                    ' where BDCODVER = VER.BDCODVER and '||
                                                          ' BDREFVER <= '||:WREFAUX||') '||
                              ' where (FOL.BDCODEMP = '||:BDCODEMP||') and '||
                                     '(FOL.BDCODCOL in ('||:BDCODCOL||')) and '||
                                     '(FOL.BDREFVFT = '||:WREFAUX||') and '||
                                     '(VER.BDCLAVER like ''0.191%'') and '||
                                     '(REF.BDFGTSVER = 3) '||
                               ' union all '||
                               ' select FOL.BDVALVFN '||
                               ' from VRHF_EMP_TVERBAINT FOL '||
                               ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                               ' left outer join VRH_BASE_TVERBAS_REF REF on REF.BDCODVER = VER.BDCODVER and '||
                                     ' REF.BDREFVER = (select max(BDREFVER) '||
                                                     ' from VRH_BASE_TVERBAS_REF '||
                                                     ' where BDCODVER = VER.BDCODVER and '||
                                                           ' BDREFVER <= '||:WREFAUX||') '||
                               ' where (FOL.BDCODEMP = '||:BDCODEMP||') and '||
                                      '(FOL.BDCODCOL in ('||:BDCODCOL||')) and '||
                                      '(FOL.BDREFFN = '||:WREFAUX||') and '||
                                      '(VER.BDCLAVER like ''0.191%'') and '||
                                      '(REF.BDFGTSVER = 3) '||
                               ' union all '||
                               ' select FOL.BDVALVFT '||
                               ' from VRHF_EMP_TVERBATOMINT FOL '||
                               ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                               ' left outer join VRH_BASE_TVERBAS_REF REF on REF.BDCODVER = VER.BDCODVER and '||
                                     ' REF.BDREFVER = (select max(BDREFVER) '||
                                                     ' from VRH_BASE_TVERBAS_REF '||
                                                     ' where BDCODVER = VER.BDCODVER and '||
                                                           ' BDREFVER <= '||:WREFAUX||') '||
                               ' where (FOL.BDCODEMP = '||:BDCODEMP||') and '||
                                     ' (FOL.BDCODCOL in ('||:BDCODCOL||')) and '||
                                     ' (FOL.BDREFTOMADOR = '||:WREFAUX||') and '||
                                     ' (VER.BDCLAVER like ''0.191%'') and '||
                                     ' (REF.BDFGTSVER = 3)';
                        for execute statement WSQL2 into :WVALVERBA do
                          begin
                            if ((WVALVERBA > 0) and (WVALVERBA = BDBASEFGTSA13)) then
                              begin
                                BDBASEFGTSA13 = 0;
                                BDFGTSA13 = 0;
                              end
                          end
                   end
               end

          end
     
        BDVALORINDCOMP = 0;
        IF (BDPERCINDCOMP > 0) THEN
          BEGIN
            BDVALORINDCOMP = TRUNC((BDBFGTS * (BDPERCINDCOMP / 100)), 2) +
                             TRUNC((BDBFGTSFC * (BDPERCINDCOMP / 100)), 2) +
                             TRUNC((BDBASEFGTSA13 * (BDPERCINDCOMP / 100)), 2) +
                             TRUNC((BDBASEFGTS13 * (BDPERCINDCOMP / 100)), 2) +
                             TRUNC((BDBASEFGTSC13 * (BDPERCINDCOMP / 100)), 2);
          END
    
        wtotalfgts = wtotalfgts + bdfgts + bdfgts13 + bdfgtsa13 + bdfgtsfc;
        bdsaldoantfgts = 0;
        bdsomafgts = bdfgts + bdfgts13 + bdfgtsa13 + bdfgtsfc;
    
        IF ((wvalormes1 IS NULL) AND (wvalormes2 IS NULL)) THEN
           wvalormes1 = wtotalfgts;
        ELSE
        IF ((wvalormes1 IS NOT NULL) AND (wvalormes2 IS NULL)) THEN
           wvalormes2 = wtotalfgts;
        ELSE
        IF ((wvalormes1 IS NOT NULL) AND (wvalormes2 IS NOT NULL)) THEN
          BEGIN
            bdsaldoantfgts = wvalormes1;
            wvalormes1 = wvalormes2;
            wvalormes2 = wtotalfgts;
          END
    
        IF (TRUNC((bdsaldoantfgts * CAST(bdindicejam AS NUMERIC(15, 6))), 2) >= 0) THEN
           BEGIN
             bdvalorjam = TRUNC(((bdsaldoantfgts + windjamant) * CAST(bdindicejam AS NUMERIC(15, 6))), 2);
             
             IF (bdvalorjam = 0) THEN --Sol.154642 LuizCovre 08/11/21, se o resultado da operação acima(TRUNC), for abaixo de 0,00 o resultado da zero
                BEGIN
                    bdvalorjam = TRUNC(bdindicejam, 3);
                END
             
             windjamant = bdvalorjam;
    
             IF (wvalormes2 IS NOT NULL) THEN
                wvalormes2 = wvalormes2 + windjamant;
           END
        ELSE
           BEGIN
             bdvalorjam = 0;
             windjamant = 0;
           END
    
    
        bdsaldofgts = wtotalfgts + bdvalorjam;
    
        wtotalfgts = wtotalfgts + bdvalorjam;

        SUSPEND;
         end
      END

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

create or alter procedure VRHF_SP_FICHAFGTS2_UNION_ALL (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFFIM integer,
    PRCC varchar(15000) = null,
    PRCALCFERA smallint = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODIND integer,
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBFGTSFC numeric(18,6),
    BDFGTSFC numeric(18,6),
    BDBASEFGTSA13 numeric(18,6),
    BDFGTSA13 numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDBASEFGTSC13 numeric(18,6),
    BDFGTSC13 numeric(18,6),
    BDINDICEJAM numeric(18,6),
    BDSALDOANTFGTS numeric(18,6),
    BDVALORJAM numeric(18,6),
    BDSALDOFGTS numeric(18,6),
    BDSOMAFGTS numeric(18,6),
    BDPERCINDCOMP numeric(18,6),
    BDVALORINDCOMP numeric(18,6),
    BDTIPO integer)
as
declare variable WSQLAUX varchar(3000);
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WANO integer;
declare variable WMES integer;
declare variable WDATA date;
declare variable WTOTALFGTS numeric(15,6);
declare variable WCONTAJAM integer;
declare variable WVALORMES1 numeric(15,6);
declare variable WVALORMES2 numeric(15,6);
declare variable WINDJAMANT numeric(15,6);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WCODIND integer;
declare variable WTEMEMP integer;
declare variable WEMPATU integer;
declare variable WREFATU integer;
declare variable WEMPATU2 integer;
declare variable WREFATU2 integer;
declare variable WCALCFERA13 varchar(5);
declare variable WSQL2 varchar(32700);
declare variable WREFAUX integer;
declare variable WDTGOZO date;
declare variable WVALVERBA numeric(15,6);
declare variable WJOINCOL varchar(300);
BEGIN

  /*
    195894 Isabella 05/04/2024
        procedure criada para uso no relatorio configuravel
        apresenta FGTS pela competencia das folhas normais
        diferente da ficha financeira do fgts do gerador que é pela competencia do pagamento
  */

  IF (prreffim IS NULL) THEN
     BEGIN
       FOR SELECT CURRENT_DATE FROM rdb$database INTO :wdata DO
       wano = EXTRACT(YEAR FROM :wdata);
       wmes = EXTRACT(MONTH FROM :wdata);
       prreffim = CAST((wano||LPAD(wmes, 2, '0')) as INTEGER);
     END

  EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);

  IF ((PRCODEMP IS NOT NULL) AND (prcodemp <> '')) THEN
       prcodemp = UPPER(prcodemp);

  /*André Cursino - 13/10/2022 - Solicitação 168872 - Comentado o trecho abaixo:
  IF (substring(prcodemp from 1 for 4) = 'TAB.') THEN --SOL.154124 LuizCovre -> Quando no filtro vem TAB. gera erro de Unknown column(tem mais de um apelido de tabela sendo utilizado em vários lugares),
    prcodemp = substring(prcodemp from 5 for 10000);  --mas só assim, outras utilizações dessa SP, vem outros tipos de filtro corretamente
                                                      --caso futuramente ou em algum outro processo der erro etc, basta remover ou comentar esse IF, mas terá de achar outra solução para o problema dessa Solicitção.*/
  prCodEmp = replace(prCodEmp, 'TAB', 'TEMP'); /*André Cursino - 13/10/2022 - Solicitação 168872 - o tab vem do gerador de relatórios*/

  wsql = 'select TEMP.BDCODEMP, '||
                'TEMP.BDCODCOL, '||
                'TEMP.BDREF, '||
                'SUM(TEMP.BDBFGTSFN), '||
                'SUM(TEMP.BDFGTSFN), '||
                'SUM(TEMP.BDBFGTSFC), '||
                'SUM(TEMP.BDFGTSFC), '||
                'SUM(TEMP.BDBASEFGTSA13), '||
                'SUM(TEMP.BDFGTSA13), '||
                'SUM(TEMP.BDBASEFGTS13), '||
                'SUM(TEMP.BDFGTS13), '||
                'SUM(TEMP.BDBASEFGTSC13), '||
                'SUM(TEMP.BDFGTSC13), '||
                'case when COALESCE(TEMP.BDTIPO,0) = 9 then 9 else 0 end BDTIPO ';    --15882 - Bruno L. R. - 27/10/2016

  if (COALESCE(prCC, '') <> '') then
     begin
       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'Y.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'Y.BDCODCOL');
         end

       wsql = wsql||'from ( '||
                       'SELECT '||
                         'Y.BDCODEMP, '||
                         'Y.BDCODCOL, '||
                         'Y.BDREFFN BDREF, '||
                         'cast(null as integer) BDCODCENTRO, '||
                         'cast(null as integer) BDCODTPCC, '||
                         'Y.BDBFGTSFN + Y.BDBFGTS13FN + COALESCE(Y.bdbfgtsfefn,0) BDBFGTSFN, '||
                         'Y.BDFGTSFN + Y.BDFGTS13FN + COALESCE(Y.bdfgtsfefn,0) BDFGTSFN, '||
                         '0.0 BDBFGTSFC, '||
                         '0.0 BDFGTSFC, '||
                         '0.0 BDBASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '0 BDTIPO '||
                       'FROM VRHF_EMP_TFOLHANORMAL Y '||
                       WJOINCOL||
                       ' where y.bdreffn = '||prreffim;


       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'Y.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'Y.BDCODCOL');
          end



       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'Y.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'Y.BDCODCOL');
         end

       wsql = wsql||   ' UNION ALL '||
                       'SELECT '||
                         'Y.BDCODEMP, '||
                         'Y.BDCODCOL, '||
                         'Y.BDREFFN, '||
                         'cast(null as integer), '||
                         'cast(null as integer), '||
                         'Y.BDBFGTSFN + COALESCE(Y.bdbfgtsfefn,0), '||
                         'Y.BDFGTSFN + COALESCE(Y.bdfgtsfefn,0), '||
                         '0.0 BDBFGTSFC, '||
                         '0.0 BDFGTSFC, '||
                         'Y.BDBFGTS13FN, '||
                         'Y.BDFGTS13FN, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '0 BDTIPO '||
                       'FROM VRHF_EMP_TFOLHAINT Y '||
                       WJOINCOL||
                       ' where y.bdreffn = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'Y.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'Y.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql||   ' UNION ALL '||
                       'SELECT '||
                         'X.bdcodemp, '||
                         'X.bdcodcol, '||
                         'X.bdreftomador, '||
                         'pfn.bdcodcentro, '||
                         'pfn.bdcodtpcc, '||
                         'X.bdbfgtsft + X.bdbfgts13ft + COALESCE(X.bdbfgtsFEft,0), '||
                         'X.bdfgtsft + X.bdfgts13ft + COALESCE(x.bdfgtsFEft,0), '||
                         '0.0 BDBFGTSFC, '||
                         '0.0 BDFGTSFC, '||
                         '0.0 BDBASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '0 BDTIPO '||
                       'FROM vrhf_emp_tfolhatomador x '||
                       'join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = x.bdcodemp and pfn.bdcodcol = x.bdcodcol and pfn.bdordem = x.bdordem) '||
                       WJOINCOL||
                       ' where x.bdreftomador = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'X.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'X.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end

       wsql = wsql||   ' UNION ALL '||
                       'SELECT '||
                         'X.bdcodemp, '||
                         'X.bdcodcol, '||
                         'X.bdreftomador, '||
                         'pfn.bdcodcentro, '||
                         'pfn.bdcodtpcc, '||
                         'X.bdbfgtsft + COALESCE(X.bdbfgtsFEft,0), '||
                         'X.bdfgtsft + COALESCE(x.bdfgtsFEft,0), '||
                         '0.0 BDBFGTSFC, '||
                         '0.0 BDFGTSFC, '||
                         'X.bdbfgts13ft, '||
                         'X.bdfgts13ft, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '0 BDTIPO '||
                       'FROM vrhf_emp_tfolhatomint x '||
                       'join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = x.bdcodemp and pfn.bdcodcol = x.bdcodcol and pfn.bdordem = x.bdordem) '||
                       WJOINCOL||
                       ' where x.bdreftomador = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'X.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'X.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'C.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'C.BDCODCOL');
         end
       wsql = wsql||   ' UNION ALL '||
                       'SELECT '||
                         'C.BDCODEMP, '||
                         'C.BDCODCOL, '||
                         'C.BDREFFN, '||
                         'cast(null as integer), '||
                         'cast(null as integer), '||
                         '0.0 BDBFGTSXX, '||
                         '0.0 BDFGTSXX, '||
                         'C.BDBFGTSFC + C.BDBFGTS13FC + COALESCE(C.BDBFGTSFEFC,0), '||
                         'C.BDFGTSFC + C.BDFGTS13FC + COALESCE(C.BDFGTSFEFC,0), '||
                         '0.0 BDBASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '6 BDTIPO '||
                       'FROM VRHF_EMP_TFOLHACOMP C '||
                       WJOINCOL||
                       ' where C.BDREFFN = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'C.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'C.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql||   ' UNION ALL '||
                       'SELECT '||
                         'X.bdcodemp, '||
                         'X.bdcodcol, '||
                         'X.bdreffn, '||
                         'pfn.bdcodcentro, '||
                         'pfn.bdcodtpcc, '||
                         '0.0 BDBFGTSXX, '||
                         '0.0 BDFGTSXX, '||
                         'X.bdbfgtsfc + X.bdbfgts13fc + COALESCE(BDBFGTSFEFC,0), '||
                         'X.bdfgtsfC + X.bdfgts13fC + COALESCE(BDFGTSFEFC,0), '||
                         '0.0 BDBASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '6 BDTIPO '||
                       'FROM vrhf_emp_tfoltomcomp x '||
                       'join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = x.bdcodemp and pfn.bdcodcol = x.bdcodcol and pfn.bdordem = x.bdordem) '||
                       WJOINCOL||
                       ' where x.bdreffn = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'X.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'X.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'C.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'C.BDCODCOL');
         end
       wsql = wsql||   ' UNION ALL '||
                       'SELECT '||
                         'C.BDCODEMP, '||
                         'C.BDCODCOL, '||
                         'C.BDREFfn, '||
                         'cast(null as integer), '||
                         'cast(null as integer), '||
                         '0.0 BDBFGTSXX, '||
                         '0.0 BDFGTSXX, '||
                         'COALESCE(C.BDBFGTSFC, 0) + COALESCE(C.BDBFGTS13FC, 0) + COALESCE(C.BDBFGTSFEFC,0), '||
                         'COALESCE(C.BDFGTSFC, 0) + COALESCE(C.BDFGTS13FC, 0) + COALESCE(C.BDFGTSFEFC,0), '||
                         '0.0 BDBASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '6 BDTIPO '||
                       'FROM VRHF_EMP_TFOLHACOMPINT C '||
                       WJOINCOL||
                       ' where C.BDREFN = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'C.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'C.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql||   ' UNION ALL '||
                       'SELECT '||
                         'X.bdcodemp, '||
                         'X.bdcodcol, '||
                         'X.bdrefcomp, '||
                         'pfn.bdcodcentro, '||
                         'pfn.bdcodtpcc, '||
                         '0.0 BDBFGTSXX, '||
                         '0.0 BDFGTSXX, '||
                         'X.bdbfgtsfc + X.bdbfgts13fc + COALESCE(BDBFGTSFEFC,0), '||
                         'X.bdfgtsfC + X.bdfgts13fC + COALESCE(BDFGTSFEFC,0), '||
                         '0.0 BDBASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '6 BDTIPO '||
                       'FROM VRHF_EMP_TFOLTOMCOMPINT X '||
                       'join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = x.bdcodemp and pfn.bdcodcol = x.bdcodcol and pfn.bdordem = x.bdordem) '||
                       WJOINCOL||
                       ' where X.BDREFTOMADOR = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'X.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'X.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'A13.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'A13.BDCODCOL');
         end
       wsql = wsql||   ' UNION ALL '||
                       'SELECT '||
                         'A13.BDCODEMP, '||
                         'A13.BDCODCOL, '||
                         'A13.BDREFA13, '||
                         'pfn.BDCODCENTRO, '||
                         'pfn.BDCODTPCC, '||
                         '0.0 BDBFGTSFN, '||
                         '0.0 BDFGTSFN, '||
                         '0.0 BDBFGTSFC, '||
                         '0.0 BDFGTSFC, '||
                         '0.0 BDBASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         'A13.BDBASEFGTSA13, '||
                         'A13.BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '2 BDTIPO '||
                       'FROM VRHF_EMP_TA13SAL A13 '||
                       'left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = a13.bdcodemp and pfn.bdcodcol = a13.bdcodcol and pfn.bdordem = a13.bdordem) '||
                       WJOINCOL||
                       ' where A13.BDREFA13 = '||prreffim;
                       if (prcalcfera is not null) then
                          wsql = wSql ||' AND a13.bdcalcfera13 <> ''TRUE'''; --30535 Valmor h Junior - Adicionado filtro bdcalcfera13, para verificar se o o adiantamento de 13 foi calculado junto as ferias.

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'A13.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'A13.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'S13.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'S13.BDCODCOL');
         end
       wsql = wsql||   ' UNION ALL '||
                       'SELECT '||
                         'S13.BDCODEMP, '||
                         'S13.BDCODCOL, '||
                         'S13.BDREF13, '||
                         'pfn.BDCODCENTRO, '||
                         'pfn.BDCODTPCC, '||
                         '0.0 BDBFGTSFN, '||
                         '0.0 BDFGTSFN, '||
                         '0.0 BDBFGTSFC, '||
                         '0.0 BDFGTSFC, '||
                         'S13.BDBASEFGTS13, '||
                         'S13.BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '3 BDTIPO '||
                       'FROM VRHF_EMP_T13SAL S13 '||
                       'left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = s13.bdcodemp and pfn.bdcodcol = s13.bdcodcol and pfn.bdordem = s13.bdordem) '||
                       WJOINCOL||
                       ' where S13.BDREF13 = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'S13.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'S13.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'C13.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'C13.BDCODCOL');
         end
       wsql = wsql||   ' UNION ALL '||
                       'SELECT '||
                         'C13.BDCODEMP, '||
                         'C13.BDCODCOL, '||
                         'C13.BDREF13, '||
                         'pfn.BDCODCENTRO, '||
                         'pfn.BDCODTPCC, '||
                         '0.0 BDBFGTSFN, '||
                         '0.0 BDFGTSFN, '||
                         '0.0 BDBFGTSFC, '||
                         '0.0 BDFGTSFC, '||
                         '0.0 BDBASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         'C13.BDBASEFGTSC13, '||
                         'C13.BDFGTSC13, '||
                         '4 BDTIPO '||
                       'FROM VRHF_EMP_TC13SAL C13 '||
                       'left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = c13.bdcodemp and pfn.bdcodcol = c13.bdcodcol and pfn.bdordem = c13.bdordem) '||
                       WJOINCOL||
                       ' where C13.BDREF13 = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'C13.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'C13.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'FA.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'FA.BDCODCOL');
         end
       wsql = wsql||   ' UNION ALL '||
                       'SELECT '||
                         'FA.BDCODEMP, '||
                         'FA.BDCODCOL, '||
                         'CAST((SUBSTRING(CAST(FA.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(FA.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) BDREFFA, '||
                         'pfn.BDCODCENTRO, '||
                         'pfn.BDCODTPCC, '||
                         'FA.BDBFGTSFA + FA.BDBFGTS13FA + COALESCE(FA.bdbfgtsfefa,0), '||
                         'FA.BDFGTSFA + FA.BDFGTS13FA + COALESCE(FA.bdfgtsfefa,0), '||
                         '0.0 BDBFGTSFC, '||
                         '0.0 BDFGTSFC, '||
                         '0.0 BDBFGTS13FAASEFGTS13, '||
                         '0.0 BDFGTS13, '||
                         '0.0 BDBASEFGTSA13, '||
                         '0.0 BDFGTSA13, '||
                         '0.0 BDBASEFGTSC13, '||
                         '0.0 BDFGTSC13, '||
                         '5 BDTIPO '||
                       'FROM VRHF_EMP_TFOLHAAVULSA FA '||
                       'left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = fa.bdcodemp and pfn.bdcodcol = fa.bdcodcol and pfn.bdordem = fa.bdordem) '||
                       WJOINCOL||
                       ' where FA.BDREF = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'FA.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'FA.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql||   ' UNION ALL '||
                       'SELECT '||
                         'X.BDCODEMP, '||
                         'X.BDCODCOL, '||
                         'X.BDREF_FFGTS, '||
                         'cast(null as integer), cast(null as integer), '||
                         'case when X.BDTIPO_FFGTS not in (3, 4, 5, 7) then X.BDBFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS not in (3, 4, 5, 7) then X.BDFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS = 7 then X.BDBFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS = 7 then X.BDFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS = 4 then X.BDBFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS = 4 then X.BDFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS = 3 then X.BDBFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS = 3 then X.BDFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS = 5 then X.BDBFGTS_FFGTS else 0.00 end, '||
                         'case when X.BDTIPO_FFGTS = 5 then X.BDFGTS_FFGTS else 0.00 end, '||
                         '9 BDTIPO '||
                       'FROM VRHF_EMP_TFICHAFGTS X '||
                       WJOINCOL||
                       ' WHERE X.BDREF_FFGTS = '||prreffim||' AND '||
                             '((X.BDTIPO_FFGTS = 1 AND  '||-- Folha normal
                              'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhanormal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREF_FFGTS) AND '||
                              'NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfolhatomador Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFTOMADOR = X.BDREF_FFGTS) AND '||
                              'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhaint Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREF_FFGTS) AND '||
                              'NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfolhatomint Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFTOMADOR = X.BDREF_FFGTS)) '||
                             'OR (X.BDTIPO_FFGTS = 3 AND  '||-- Adiantamento de 13 salario
                                 'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_ta13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFA13 = X.BDREF_FFGTS)) '||
                             'OR (X.BDTIPO_FFGTS = 4 AND  '||-- 13 salario
                                 'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_t13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREF13 = X.BDREF_FFGTS)) '||
                             'OR (X.BDTIPO_FFGTS = 5 AND  '||-- Complemento de 13 salario
                                 'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tc13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREF13 = X.BDREF_FFGTS)) '||
                             'OR (X.BDTIPO_FFGTS = 7 AND  '||-- Folha complementar
                                 'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhacomp Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREF_FFGTS) AND '||
                                 'NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfoltomcomp Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFTOMADOR = X.BDREF_FFGTS) AND '||
                                 'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhacompint Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREF_FFGTS) AND '||
                                 'NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfoltomcompint Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFTOMADOR = X.BDREF_FFGTS))) ';

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'X.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'X.BDCODCOL');
          end

       wsql = wsql||') TEMP ';
     end
  else
     begin

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'Y.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'Y.BDCODCOL');
         end
       wsql = wsql||'from (select '||
                       'Y.BDCODEMP, '||
                       'Y.BDCODCOL, '||
                       'Y.BDREFFN BDREF, '||
                       'Y.BDBFGTSFN + Y.BDBFGTS13FN + COALESCE(Y.bdbfgtsfefn,0) BDBFGTSFN, '||
                       'Y.BDFGTSFN + Y.BDFGTS13FN + COALESCE(Y.bdfgtsfefn,0) BDFGTSFN, '||
                       '0.0 BDBFGTSFC, '||
                       '0.0 BDFGTSFC, '||
                       '0.0 BDBASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '0 BDTIPO '||
                     'FROM VRHF_EMP_TFOLHANORMAL Y '||
                     WJOINCOL||
                     ' where Y.bdreffn = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'Y.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'Y.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'Y.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'Y.BDCODCOL');
         end
       wsql = wsql|| ' UNION ALL '||
                     'SELECT '||
                       'Y.BDCODEMP, '||
                       'Y.BDCODCOL, '||
                       'Y.BDREFFN, '||
                       'Y.BDBFGTSFN + COALESCE(Y.bdbfgtsfefn,0), '||
                       'Y.BDFGTSFN + COALESCE(Y.bdfgtsfefn,0), '||
                       '0.0 BDBFGTSFC, '||
                       '0.0 BDFGTSFC, '||
                       'Y.BDBFGTS13FN, '||
                       'Y.BDFGTS13FN, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '0 BDTIPO '||
                     'FROM VRHF_EMP_TFOLHAINT Y '||
                     replace(WJOINCOL, 'TEMP.BDCODCOL', 'Y.BDCODCOL')||
                     ' where y.bdreffn = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'Y.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'Y.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql|| ' UNION ALL '||
                     'SELECT '||
                       'X.bdcodemp, '||
                       'X.bdcodcol, '||
                       'X.bdreftomador, '||
                       'X.bdbfgtsft + X.bdbfgts13ft + COALESCE(X.bdbfgtsFEft,0), '||
                       'X.bdfgtsft + X.bdfgts13ft + COALESCE(x.bdfgtsFEft,0), '||
                       '0.0 BDBFGTSFC, '||
                       '0.0 BDFGTSFC, '||
                       '0.0 BDBASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '0 BDTIPO '||
                     'FROM vrhf_emp_tfolhatomador x '||
                     WJOINCOL||
                     ' where x.bdreftomador = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'x.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'x.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql|| ' UNION ALL '||
                     'SELECT '||
                       'X.bdcodemp, '||
                       'X.bdcodcol, '||
                       'X.bdreftomador, '||
                       'X.bdbfgtsft + COALESCE(X.bdbfgtsFEft,0), '||
                       'X.bdfgtsft + COALESCE(x.bdfgtsFEft,0), '||
                       '0.0 BDBFGTSFC, '||
                       '0.0 BDFGTSFC, '||
                       'X.bdbfgts13ft, '||
                       'X.bdfgts13ft, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '0 BDTIPO '||
                     'FROM vrhf_emp_tfolhatomint x '||
                     WJOINCOL||
                     ' where x.bdreftomador = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'x.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'x.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'C.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'C.BDCODCOL');
         end
       wsql = wsql|| ' UNION ALL '||
                     'SELECT '||
                       'C.BDCODEMP, '||
                       'C.BDCODCOL, '||
                       'C.BDREFFN, '||
                       '0.0 BDBFGTSXX, '||
                       '0.0 BDFGTSXX, '||
                       'C.BDBFGTSFC + C.BDBFGTS13FC + COALESCE(C.BDBFGTSFEFC,0), '||
                       'C.BDFGTSFC + C.BDFGTS13FC + COALESCE(C.BDFGTSFEFC,0), '||
                       '0.0 BDBASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '6 BDTIPO '||
                     'FROM VRHF_EMP_TFOLHACOMP C '||
                     WJOINCOL||
                     ' where C.BDREFFN = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'C.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'C.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql|| ' UNION ALL '||
                     'SELECT '||
                       'X.bdcodemp, '||
                       'X.bdcodcol, '||
                       'X.bdrefTOMADOR, '||
                       '0.0 BDBFGTSXX, '||
                       '0.0 BDFGTSXX, '||
                       'X.bdbfgtsfc + X.bdbfgts13fc + COALESCE(BDBFGTSFEFC,0), '||
                       'X.bdfgtsfC + X.bdfgts13fC + COALESCE(BDFGTSFEFC,0), '||
                       '0.0 BDBASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '6 BDTIPO '||
                     'FROM vrhf_emp_tfoltomcomp x '||
                     WJOINCOL||
                     ' where x.bdrefTOMADOR = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'x.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'x.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'C.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'C.BDCODCOL');
         end
       wsql = wsql|| ' UNION ALL '||
                     'SELECT '||
                       'C.BDCODEMP, '||
                       'C.BDCODCOL, '||
                       'C.BDREFFN, '||
                       '0.0 BDBFGTSXX, '||
                       '0.0 BDFGTSXX, '||
                       'C.BDBFGTSFC + C.BDBFGTS13FC + COALESCE(C.BDBFGTSFEFC,0), '||
                       'C.BDFGTSFC + C.BDFGTS13FC + COALESCE(C.BDFGTSFEFC,0), '||
                       '0.0 BDBASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '6 BDTIPO '||
                     'FROM VRHF_EMP_TFOLHACOMPINT C '||
                     WJOINCOL||
                     ' where C.BDREFFN = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'C.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'C.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql|| ' UNION ALL '||
                     'SELECT '||
                       'X.bdcodemp, '||
                       'X.bdcodcol, '||
                       'X.bdrefTOMADOR, '||
                       '0.0 BDBFGTSXX, '||
                       '0.0 BDFGTSXX, '||
                       'X.bdbfgtsfc + X.bdbfgts13fc + COALESCE(BDBFGTSFEFC,0), '||
                       'X.bdfgtsfC + X.bdfgts13fC + COALESCE(BDFGTSFEFC,0), '||
                       '0.0 BDBASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '6 BDTIPO '||
                     'FROM VRHF_EMP_TFOLTOMCOMPINT X '||
                     WJOINCOL||
                     ' where x.bdrefTOMADOR = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'x.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'x.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'A.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'A.BDCODCOL');
         end
       wsql = wsql|| ' UNION ALL '||
                     'SELECT '||
                       'A.BDCODEMP, '||
                       'A.BDCODCOL, '||
                       'A.BDREFA13, '||
                       '0.0 BDBFGTSFN, '||
                       '0.0 BDFGTSFN, '||
                       '0.0 BDBFGTSFC, '||
                       '0.0 BDFGTSFC, '||
                       '0.0 BDBASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       'A.BDBASEFGTSA13, '||
                       'A.BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '2 BDTIPO '||
                     'FROM VRHF_EMP_TA13SAL A '||
                     WJOINCOL||
                     ' where A.BDREFA13 = '||prreffim;
                      if (prcalcfera is not null) then
                          wsql = wSql ||' AND A.bdcalcfera13 <> ''TRUE'''; --30535 Valmor h Junior - Adicionado filtro bdcalcfera13, para verificar se o o adiantamento de 13 foi calculado junto as ferias.

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'A.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'A.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'D.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'D.BDCODCOL');
         end
       wsql = wsql|| ' UNION ALL '||
                     'SELECT '||
                       'D.BDCODEMP, '||
                       'D.BDCODCOL, '||
                       'D.BDREF13, '||
                       '0.0 BDBFGTSFN, '||
                       '0.0 BDFGTSFN, '||
                       '0.0 BDBFGTSFC, '||
                       '0.0 BDFGTSFC, '||
                       'D.BDBASEFGTS13, '||
                       'D.BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '3 BDTIPO '||
                     'FROM VRHF_EMP_T13SAL D '||
                     WJOINCOL||
                     ' where D.BDREF13 = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'D.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'D.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'C.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'C.BDCODCOL');
         end
       wsql = wsql|| ' UNION ALL '||
                     'SELECT '||
                       'C.BDCODEMP, '||
                       'C.BDCODCOL, '||
                       'C.BDREF13, '||
                       '0.0 BDBFGTSFN, '||
                       '0.0 BDFGTSFN, '||
                       '0.0 BDBFGTSFC, '||
                       '0.0 BDFGTSFC, '||
                       '0.0 BDBASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       'C.BDBASEFGTSC13, '||
                       'C.BDFGTSC13, '||
                       '4 BDTIPO '||
                     'FROM VRHF_EMP_TC13SAL C '||
                     WJOINCOL||
                     ' where C.BDREF13 = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'C.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'C.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'A.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'A.BDCODCOL');
         end
       wsql = wsql|| ' UNION ALL '||
                     'SELECT '||
                       'A.BDCODEMP, '||
                       'A.BDCODCOL, '||
                       'A.BDREF, '||
                       'A.BDBFGTSFA + A.BDBFGTS13FA + COALESCE(A.bdbfgtsfefa,0), '||
                       'A.BDFGTSFA + A.BDFGTS13FA + COALESCE(A.bdfgtsfefa,0), '||
                       '0.0 BDBFGTSFC, '||
                       '0.0 BDFGTSFC, '||
                       '0.0 BDBFGTS13FAASEFGTS13, '||
                       '0.0 BDFGTS13, '||
                       '0.0 BDBASEFGTSA13, '||
                       '0.0 BDFGTSA13, '||
                       '0.0 BDBASEFGTSC13, '||
                       '0.0 BDFGTSC13, '||
                       '5 BDTIPO '||
                     'FROM VRHF_EMP_TFOLHAAVULSA A '||
                     WJOINCOL||
                     ' where A.BDREF = '||prreffim;

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'A.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'A.BDCODCOL');
          end

       WJOINCOL = '';
       if (position('TEMP_FILTRO_COLCON_REL', prcodcol) > 0) then
         begin
          wjoincol = replace(upper(PRCODCOL), 'TEMP.BDCODEMP', 'X.BDCODEMP');
          wjoincol = replace(WJOINCOL, 'TEMP.BDCODCOL', 'X.BDCODCOL');
         end
       wsql = wsql|| ' UNION ALL '||
                     'SELECT '||
                       'X.BDCODEMP, '||
                       'X.BDCODCOL, '||
                       'X.BDREF_FFGTS, '||
                       'case when X.BDTIPO_FFGTS not in (3, 4, 5, 7) then X.BDBFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS not in (3, 4, 5, 7) then X.BDFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS = 7 then X.BDBFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS = 7 then X.BDFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS = 4 then X.BDBFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS = 4 then X.BDFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS = 3 then X.BDBFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS = 3 then X.BDFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS = 5 then X.BDBFGTS_FFGTS else 0.00 end, '||
                       'case when X.BDTIPO_FFGTS = 5 then X.BDFGTS_FFGTS else 0.00 end, '||
                       '9 BDTIPO '||
                     'FROM VRHF_EMP_TFICHAFGTS X '||
                     WJOINCOL||
                     ' WHERE X.BDREF_FFGTS = '||prreffim||
                            ' and ((X.BDTIPO_FFGTS = 1 AND  '||-- Folha normal
                            'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhanormal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREF_FFGTS) AND '||
                            'NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfolhatomador Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFTOMADOR = X.BDREF_FFGTS) AND '||
                            'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhaint Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREF_FFGTS) AND '||
                            'NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfolhatomint Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFTOMADOR = X.BDREF_FFGTS)) '||
                           'OR (X.BDTIPO_FFGTS = 3 AND  '||-- Adiantamento de 13 salario
                               'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_ta13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFA13 = X.BDREF_FFGTS)) '||
                           'OR (X.BDTIPO_FFGTS = 4 AND   '||-- 13 salario
                               'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_t13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREF13 = X.BDREF_FFGTS)) '||
                           'OR (X.BDTIPO_FFGTS = 5 AND   '||-- Complemento de 13 salario
                               'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tc13sal Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREF13 = X.BDREF_FFGTS)) '||
                           'OR (X.BDTIPO_FFGTS = 7 AND  '||-- Folha complementar
                               'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhacomp Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREF_FFGTS) AND '||
                               'NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfoltomcomp Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFTOMADOR = X.BDREF_FFGTS) AND '||
                               'NOT EXISTS (SELECT Y.BDCODEMP, Y.BDCODCOL FROM vrhf_emp_tfolhacompint Y WHERE Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDREFFN = X.BDREF_FFGTS) AND '||
                               'NOT EXISTS (SELECT Z.BDCODEMP, Z.BDCODCOL FROM vrhf_emp_tfoltomcompint Z WHERE Z.BDCODEMP = X.BDCODEMP AND Z.BDCODCOL = X.BDCODCOL AND Z.BDREFTOMADOR = X.BDREF_FFGTS))) ';

       if ((coalesce(prcodemp, '') <> '') and (WJOINCOL = '')) then
          begin
            wsql = wsql||' and '||replace(prcodemp, 'TEMP.BDCODEMP', 'X.BDCODEMP');

            if (coalesce(prcodcol, '') <> '') then
               wsql = wsql||' and '||replace(prcodcol, 'TEMP.BDCODCOL', 'X.BDCODCOL');
          end

       wsql = wsql||') TEMP ';
     end

  wwhere = '';

  if (COALESCE(prCC, '') <> '') then
     begin
       prcc = UPPER(prcc);
       wwhere = wwhere||' where '||replace(prcc, 'BDCODTPCC', 'TEMP.BDCODTPCC')||' ';
     end

  -- Group by
  wwhere = wwhere||
           ' group by TEMP.BDCODEMP, TEMP.BDCODCOL, TEMP.BDREF, BDTIPO ';

  wsql = wsql||wwhere;
  wsql = wsql||' order by TEMP.BDCODEMP, TEMP.BDCODCOL, TEMP.BDREF, BDTIPO ';

  windjamant = 0;
  wcodemp = 0;
  wcodcol = 0;

  wtememp  = 0;
  wempatu  = 0;
  wrefatu  = 999999;
  wrefatu2 = 999999;
  wempatu2 = 0;

  FOR EXECUTE STATEMENT wsql
    INTO
      :BDCODEMP,
      :BDCODCOL,
      :BDREF,
      :BDBFGTS,
      :BDFGTS,
      :BDBFGTSFC,
      :BDFGTSFC,
      :BDBASEFGTSA13,
      :BDFGTSA13,
      :BDBASEFGTS13,
      :BDFGTS13,
      :BDBASEFGTSC13,
      :BDFGTSC13,
      :BDTIPO
    DO
      BEGIN
        if (wempatu <> bdcodemp) then
           begin
             -- Filtra permissões por empresas
             wtememp = null;
             execute statement 'select first 1 BDCODEMP from VW_EMPRESAS_REF_ATUAL where BDCODEMP = '||:BDCODEMP into :wtememp;
             wtememp = coalesce(wtememp, 0);
             wempatu = bdcodemp;
           end

        if (wtememp > 0) then
           begin
             if ((wempatu2 <> BDCODEMP) or (BDREF < wrefatu) or (BDREF < wrefatu2)) then
                begin
                  if ((wempatu2 <> BDCODEMP) or (BDREF < wrefatu)) then
                     begin
                       wsqlAux = 'select first 1 BDCODIND, BDREFEMP from VRHF_BASE_TEMPVINC where BDCODEMP = '||bdcodemp||' and BDREFEMP <= '||bdref||' order by BDREFEMP DESC ';
        wcodind = NULL;
                       EXECUTE STATEMENT wsqlaux INTO :wcodind, :wrefatu;
        BDCODIND = wcodind;
                     end

                  if ((wempatu2 <> BDCODEMP) or (BDREF < wrefatu)) then
                     begin
                       wsqlaux = 'select first 1 coalesce(bdindcomp, 0) bdindcomp, BDREFEMP from VRHF_BASE_TEMPGPS x where x.bdcodemp = '||wcodemp||' and x.bdrefemp <= '||:bdref||' order by bdcodemp, bdrefemp desc';
                       EXECUTE STATEMENT wsqlaux INTO :BDPERCINDCOMP, :wrefatu2;
                     end

                  wempatu2 = BDCODEMP;
                end
     
        IF (wcodemp <> :bdcodemp OR (wcodcol <> :bdcodcol)) THEN
           BEGIN
             wtotalfgts = 0;
             wcontajam = 0;
             wvalormes1 = NULL;
             wvalormes2 = NULL;
      
             wcodemp = :bdcodemp;
             wcodcol = :bdcodcol;
           END
    
     
        wcontajam = wcontajam + 1;
    
        bdindicejam = 0;
    
      --IF (wcontajam > 2) THEN Sol.154642 LuizCovre 08/11/21
        IF (wcontajam > 0) THEN
        BEGIN
          IF ((bdcodind IS NOT NULL) AND (:bdcodind > 0) AND (:bdref > 0)) THEN
          BEGIN
            wsqlaux = 'select x.bdvalind from TINDVAL x where x.bdcodind = '||:bdcodind||' and x.bdrefind = '||:bdref;
            EXECUTE STATEMENT wsqlaux INTO :bdindicejam;
          END
          ELSE
          BEGIN
            bdindicejam = 0;
          END
        END

        IF (BDTIPO = 0) then                  -- 167754 JoãoVictor 10/01/23
          begin
            if (BDBASEFGTSA13 > 0) then
              begin
                select A13.BDCALCFERA13
                from VRHF_EMP_TA13SAL A13
                WHERE A13.BDCODEMP = :BDCODEMP and A13.BDCODCOL = :BDCODCOL and A13.BDREFA13 = :BDREF
                  into :WCALCFERA13;

                 select max(BDINIPERGOZOFE) from SP_VRHF_GETFERIAS(:BDCODEMP, :BDCODCOL, :BDREF) where BDCALCA13FE = 'TRUE' into :WDTGOZO;
                 WREFAUX = extract (year from WDTGOZO) || RIGHT('0'||trim(EXTRACT(MONTH from WDTGOZO)), 2);

                 if ((:WCALCFERA13 = 'TRUE') and (WREFAUX is not null)) then
                   begin
                     WSQL2 =  '  select FOL.BDVALVFN '||
                              '  from VRHF_EMP_TVERBAFN FOL '||
                              '  join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                              '  left outer join VRH_BASE_TVERBAS_REF REF on REF.BDCODVER = VER.BDCODVER and '||
                                                 ' REF.BDREFVER = (select max(BDREFVER) '||
                                                               '  from VRH_BASE_TVERBAS_REF '||
                                                               ' where BDCODVER = VER.BDCODVER and '||
                                                               ' BDREFVER <= '||:WREFAUX||') '||
                              ' where (FOL.BDCODEMP = '||:BDCODEMP||') and '||
                                    ' (FOL.BDCODCOL in ('||:BDCODCOL||')) and '||
                                    ' (FOL.BDREFFN = '||:WREFAUX||') and '||
                                    ' (VER.BDCLAVER like ''0.191%'') and '||
                                    ' (REF.BDFGTSVER = 3) '||
                              ' union all '||
                              ' select FOL.BDVALVFT '||
                              ' from VRHF_EMP_TVERBATOMADOR FOL '||
                              ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                              ' left outer join VRH_BASE_TVERBAS_REF REF on REF.BDCODVER = VER.BDCODVER and '||
                              '        REF.BDREFVER = (select max(BDREFVER) '||
                                                    ' from VRH_BASE_TVERBAS_REF '||
                                                    ' where BDCODVER = VER.BDCODVER and '||
                                                          ' BDREFVER <= '||:WREFAUX||') '||
                              ' where (FOL.BDCODEMP = '||:BDCODEMP||') and '||
                                     '(FOL.BDCODCOL in ('||:BDCODCOL||')) and '||
                                     '(FOL.BDREFVFT = '||:WREFAUX||') and '||
                                     '(VER.BDCLAVER like ''0.191%'') and '||
                                     '(REF.BDFGTSVER = 3) '||
                               ' union all '||
                               ' select FOL.BDVALVFN '||
                               ' from VRHF_EMP_TVERBAINT FOL '||
                               ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                               ' left outer join VRH_BASE_TVERBAS_REF REF on REF.BDCODVER = VER.BDCODVER and '||
                                     ' REF.BDREFVER = (select max(BDREFVER) '||
                                                     ' from VRH_BASE_TVERBAS_REF '||
                                                     ' where BDCODVER = VER.BDCODVER and '||
                                                           ' BDREFVER <= '||:WREFAUX||') '||
                               ' where (FOL.BDCODEMP = '||:BDCODEMP||') and '||
                                      '(FOL.BDCODCOL in ('||:BDCODCOL||')) and '||
                                      '(FOL.BDREFFN = '||:WREFAUX||') and '||
                                      '(VER.BDCLAVER like ''0.191%'') and '||
                                      '(REF.BDFGTSVER = 3) '||
                               ' union all '||
                               ' select FOL.BDVALVFT '||
                               ' from VRHF_EMP_TVERBATOMINT FOL '||
                               ' join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                               ' left outer join VRH_BASE_TVERBAS_REF REF on REF.BDCODVER = VER.BDCODVER and '||
                                     ' REF.BDREFVER = (select max(BDREFVER) '||
                                                     ' from VRH_BASE_TVERBAS_REF '||
                                                     ' where BDCODVER = VER.BDCODVER and '||
                                                           ' BDREFVER <= '||:WREFAUX||') '||
                               ' where (FOL.BDCODEMP = '||:BDCODEMP||') and '||
                                     ' (FOL.BDCODCOL in ('||:BDCODCOL||')) and '||
                                     ' (FOL.BDREFTOMADOR = '||:WREFAUX||') and '||
                                     ' (VER.BDCLAVER like ''0.191%'') and '||
                                     ' (REF.BDFGTSVER = 3)';
                        for execute statement WSQL2 into :WVALVERBA do
                          begin
                            if ((WVALVERBA > 0) and (WVALVERBA = BDBASEFGTSA13)) then
                              begin
                                BDBASEFGTSA13 = 0;
                                BDFGTSA13 = 0;
                              end
                          end
                   end
               end

          end
     
        BDVALORINDCOMP = 0;
        IF (BDPERCINDCOMP > 0) THEN
          BEGIN
            BDVALORINDCOMP = TRUNC((BDBFGTS * (BDPERCINDCOMP / 100)), 2) +
                             TRUNC((BDBFGTSFC * (BDPERCINDCOMP / 100)), 2) +
                             TRUNC((BDBASEFGTSA13 * (BDPERCINDCOMP / 100)), 2) +
                             TRUNC((BDBASEFGTS13 * (BDPERCINDCOMP / 100)), 2) +
                             TRUNC((BDBASEFGTSC13 * (BDPERCINDCOMP / 100)), 2);
          END
    
        wtotalfgts = wtotalfgts + bdfgts + bdfgts13 + bdfgtsa13 + bdfgtsfc;
        bdsaldoantfgts = 0;
        bdsomafgts = bdfgts + bdfgts13 + bdfgtsa13 + bdfgtsfc;
    
        IF ((wvalormes1 IS NULL) AND (wvalormes2 IS NULL)) THEN
           wvalormes1 = wtotalfgts;
        ELSE
        IF ((wvalormes1 IS NOT NULL) AND (wvalormes2 IS NULL)) THEN
           wvalormes2 = wtotalfgts;
        ELSE
        IF ((wvalormes1 IS NOT NULL) AND (wvalormes2 IS NOT NULL)) THEN
          BEGIN
            bdsaldoantfgts = wvalormes1;
            wvalormes1 = wvalormes2;
            wvalormes2 = wtotalfgts;
          END
    
        IF (TRUNC((bdsaldoantfgts * CAST(bdindicejam AS NUMERIC(15, 6))), 2) >= 0) THEN
           BEGIN
             bdvalorjam = TRUNC(((bdsaldoantfgts + windjamant) * CAST(bdindicejam AS NUMERIC(15, 6))), 2);
             
             IF (bdvalorjam = 0) THEN --Sol.154642 LuizCovre 08/11/21, se o resultado da operação acima(TRUNC), for abaixo de 0,00 o resultado da zero
                BEGIN
                    bdvalorjam = TRUNC(bdindicejam, 3);
                END
             
             windjamant = bdvalorjam;
    
             IF (wvalormes2 IS NOT NULL) THEN
                wvalormes2 = wvalormes2 + windjamant;
           END
        ELSE
           BEGIN
             bdvalorjam = 0;
             windjamant = 0;
           END
    
    
        bdsaldofgts = wtotalfgts + bdvalorjam;
    
        wtotalfgts = wtotalfgts + bdvalorjam;

        SUSPEND;
         end
      END

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

/* Restore proc. body: VRHF_SP_FICHAINSS */
ALTER PROCEDURE VRHF_SP_FICHAINSS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF INTEGER,
BDBINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBASEINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBASEINSSC13 NUMERIC(15,6),
BDINSSC13 NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WDATA DATE;
BEGIN

  IF (prreffim IS NULL) THEN
     BEGIN
       FOR SELECT CURRENT_DATE FROM rdb$database INTO :wdata DO
       wano = EXTRACT(YEAR FROM :wdata);
       wmes = EXTRACT(MONTH FROM :wdata);
       EXECUTE PROCEDURE sp_seta_competencia(wano||wmes, NULL, NULL);
     END
  ELSE
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);


  wsql = 'select X.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'X.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'X.BDREF, '||
                'SUM(X.BDBINSSFN), '||
                'SUM(X.BDINSSFN), '||
                'SUM(X.BDBASEINSS13), '||
                'SUM(X.BDINSS13), '||
                'SUM(X.BDBASEINSSC13), '||
                'SUM(X.BDINSSC13) ';

  wsql = wsql||'from VW_UNION_INSS X '||

             'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
             'on (EMP.BDCODEMP = X.BDCODEMP) '||

             'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
             'on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL) ';

  wwhere = '';

  IF (PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||'('||PRCODEMP||') ';
     END 

  IF (PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'('||PRCODCOL||') ';
     END

  IF (PRREFINI IS NOT NULL AND PRREFFIM IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'(X.BDREF between '||PRREFINI||' and '||PRREFFIM||') ';
     END

  IF (wwhere <> '') THEN
     wwhere = 'where '||wwhere;


  -- Group by
  wwhere = wwhere||
           ' group by X.BDCODEMP, '||
                     'EMP.BDNOMEMP, '||
                     'X.BDCODCOL, '||
                     'COL.BDNOMCOL, '||
                     'X.BDREF ';

  wsql = wsql||wwhere;

    FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :bdnomemp,
        :BDCODCOL,
        :bdnomcol,
        :BDREF,
        :BDBINSS,
        :BDINSS,
        :BDBASEINSS13,
        :BDINSS13,
        :BDBASEINSSC13,
        :BDINSSC13
      DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);


END
^

/* Restore proc. body: VRHF_SP_FICHAIR */
ALTER PROCEDURE VRHF_SP_FICHAIR(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRTIPOCALC INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF VARCHAR(10),
BDTIPOCALC INTEGER,
BDBRUTO NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDVALIR NUMERIC(15,6),
BDVALINSS NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WDATA DATE;
BEGIN

  IF (prreffim IS NULL) THEN
     BEGIN
       FOR SELECT CURRENT_DATE FROM rdb$database INTO :wdata DO
       wano = EXTRACT(YEAR FROM :wdata);
       wmes = EXTRACT(MONTH FROM :wdata);
       EXECUTE PROCEDURE sp_seta_competencia(wano||wmes, NULL, NULL);
     END
  ELSE
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);


  IF ((PRCODEMP IS NOT NULL) AND (prcodemp <> '')) THEN
     BEGIN
       prcodemp = UPPER(prcodemp);
       IF (POSITION('TAB.BDCODEMP',prcodemp) > 0) THEN
          BEGIN
            SELECT bdresult FROM strtran(:prcodemp,'TAB.BDCODEMP','EMP.BDCODEMP') INTO prcodemp;
          END
     END

  wsql = 'select X.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'X.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'X.BDREF, '||
                'X.BDTIPOCALC, '||
                'SUM(X.BDBRUTO), '||
                'SUM(X.BDDEP), '||
                'SUM(X.BDVALIR), '||
                'SUM(X.BDVALINSS) ';


  wsql = wsql||'from VW_UNION_IR X '||

             'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
             'on (EMP.BDCODEMP = X.BDCODEMP) '||

             'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
             'on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL) ';

  wwhere = '';

  IF ((PRCODEMP IS NOT NULL) AND (prcodemp <> '')) THEN
     BEGIN
       wwhere = wwhere||'('||PRCODEMP||') ';
     END 

  IF ((PRCODCOL IS NOT NULL) AND (prcodcol <> '')) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'('||PRCODCOL||') ';
     END

  IF (PRREFINI IS NOT NULL AND PRREFFIM IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'(X.BDREF between '||PRREFINI||' and '||PRREFFIM||') ';
     END

  IF (prtipocalc IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'(X.BDTIPOCALC = '||prtipocalc||') ';
     END


  IF (wwhere <> '') THEN
     wwhere = 'where '||wwhere;


  -- Group by
  wwhere = wwhere||
           ' group by X.BDCODEMP, '||
                     'EMP.BDNOMEMP, '||
                     'X.BDCODCOL, '||
                     'COL.BDNOMCOL, '||
                     'X.BDREF, '||
                     'X.BDTIPOCALC ';

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
     INTO
        :bdcodemp,
        :bdnomemp,
        :bdcodcol,
        :bdnomcol,
        :bdref,
        :bdtipocalc,
        :bdbruto,
        :bddep,
        :bdvalir,
        :bdvalinss
      DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);


END
^

/* Restore proc. body: VRHF_SP_FICHAIR_ANUAL */
CREATE OR ALTER procedure VRHF_SP_FICHAIR_ANUAL (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRANOBASE integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(18),
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL varchar(14),
    BDDATAADMCOL date,
    BDDATARESCISAO date,
    BDREF varchar(10),
    BDRENDTRIB numeric(15,6),
    BDDEP numeric(15,6),
    BDIRRF numeric(15,6),
    BDINSS numeric(15,6),
    BDALUGUEIS numeric(15,6),
    BDPRIVPRIVADA numeric(15,6),
    BDDESPMEDICAS numeric(15,6),
    BDPENSAOALIM numeric(15,6),
    BDPENSAOJUDICIAL numeric(15,6),
    BDAJUDACUSTO numeric(15,6),
    BDLUCROPJ numeric(15,6),
    BDAVISOPREV numeric(15,6),
    BDRENDTRIB13 numeric(15,6),
    BDDEP13 numeric(15,6),
    BDIRRF13 numeric(15,6),
    BDINSS13 numeric(15,6),
    BDPENSAOALIM13 numeric(15,6),
    BDDATA date,
    BDGRUPO integer)
as
declare variable WSQL varchar(32700);
declare variable WSQLFUNC varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WANO integer;
declare variable WMES integer;
declare variable I integer;
declare variable WREFAUX integer;
declare variable WDATAAUX date;
declare variable WQBG integer;
declare variable WDATASAIDA date;
BEGIN

 wAno = pranobase;
 wMes = '12';

 EXECUTE PROCEDURE sp_seta_competencia(wano||wmes, NULL, NULL);

 wsqlfunc = ' select T.BDCODEMP, ' ||
             ' EMPRESAS.BDNOMEMP, ' ||
             'EMPRESAS.BDCNPJEMP,' ||
             'T.BDCODCOL,' ||
             'vw_col.bdnomcol,' ||
             'vw_col.BDCPFCOL,' ||
             'vw_col.BDDATAADMCOL,' ||
             'TRESCISAO.BDDATARESCISAO' ||
             ' from VW_COLABORADORES_REF_ATUAL  t' ;

  wsqlfunc = wsqlfunc||' left outer join SP_CONSULTAEMPRESAS(null, null, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;

  wsqlfunc = wsqlfunc|| 'left outer join vw_colaboradores vw_col on (vw_col.bdcodemp = t.bdcodemp and vw_col.bdcodcol = t.bdcodcol) ';

  wsqlfunc = wsqlfunc|| 'left outer join VRH_EMP_TRESCISAO TRESCISAO on (TRESCISAO.bdcodemp = t.bdcodemp and TRESCISAO.bdcodcol = t.bdcodcol) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsqlfunc = wsqlfunc||wwhere;

  -- FAZ UM FOR EM TODOS OS FUNCIONARIOS
  FOR EXECUTE STATEMENT wsqlfunc
    INTO :BDCODEMP, :bdnomemp, :bdcnpjemp, :bdcodcol , :bdnomcol, :bdcpfcol, :bddataadmcol, :bddatarescisao DO
    BEGIN

      i = 0;
      wrefaux = wano||'01';

      WHILE (i < 12) DO
        BEGIN
          i = i + 1;

          wsql = 'select X.BDREF, '||
                 'SUM(X.BDBRUTO), '||
                 'SUM(X.BDDEP), '||
                 'SUM(X.BDVAlIR), '||
                 'SUM(X.BDVALINSS) ';
            
                
          wsql = wsql||'from VW_UNION_IR X '||
                       'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
                       'on (EMP.BDCODEMP = X.BDCODEMP) '||
        
                       'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
                       'on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL) ';

          wwhere = '';

          wwhere = wwhere||'(X.BDREF = '||wrefaux||')';

          wwhere = wwhere||' and (X.BDTIPOCALC = '||'1'||') ';

          wwhere = wwhere||' and x.bdcodemp = '||:bdcodemp;

          wwhere = wwhere||' and x.bdcodcol = '||:bdcodcol;


          IF (wwhere <> '') THEN
             wwhere = 'where '||wwhere;

           -- Group by
          wwhere = wwhere||
                         ' group by X.BDCODEMP, '||
                         'EMP.BDNOMEMP, '||
                         'X.BDCODCOL, '||
                         'COL.BDNOMCOL, '||
                         'X.BDREF, '||
                         'X.BDTIPOCALC ';

          wsql = wsql||wwhere;

          wqbg = 0;

          FOR EXECUTE STATEMENT wsql
            INTO
              :bdref,
              :bdrendtrib,
              :bddep,
              :bdirrf,
              :bdinss
            DO
          BEGIN
            wqbg = wqbg + 1;
          END

          IF (wqbg = 0) THEN
            BEGIN
              bdref = wrefaux;
              bdrendtrib = 0;
              bddep = 0;
              bdirrf = 0;
              bdinss = 0;
            END

            SELECT bdvalv FROM VRHF_SP_VERBAS_FN_FC('X.BDCODEMP = '|| :bdcodemp , 'X.BDCODCOL='|| :bdcodcol , :bdref , :bdref , '(BDCLAVER like ''0.030.0.1%'')')
            INTO bdpensaoalim;

            SELECT bdvalv FROM VRHF_SP_VERBAS_FN_FC('X.BDCODEMP = '|| :bdcodemp , 'X.BDCODCOL='|| :bdcodcol , :bdref , :bdref , '(BDCLAVER like ''0.030.0.0%'')')
            INTO bdpensaojudicial;

            SELECT bdvalv FROM VRHF_SP_VERBAS_FN_FC('X.BDCODEMP = '|| :bdcodemp , 'X.BDCODCOL='|| :bdcodcol , :bdref , :bdref , '(BDCLAVER like ''0.030.1.0%'') or (BDCLAVER like ''3.010.0.0%'')')
            INTO bddespmedicas;

            SELECT bdvalv FROM VRHF_SP_VERBAS_FN_FC('X.BDCODEMP = '|| :bdcodemp , 'X.BDCODCOL='|| :bdcodcol , :bdref , :bdref , '(BDCLAVER like ''0.040.0%'')')
            INTO bdajudacusto;

            SELECT bdvalv FROM VRHF_SP_VERBAS_FN_FC('X.BDCODEMP = '|| :bdcodemp , 'X.BDCODCOL='|| :bdcodcol , :bdref , :bdref , '(BDCLAVER like ''7.001.2.1%'')')
            INTO bdavisoprev;

            IF (bdalugueis IS NULL) THEN
               bdalugueis = 0;

            IF (bdprivprivada IS NULL) THEN
               bdprivprivada = 0;

            IF (bddespmedicas IS NULL) THEN
               bddespmedicas = 0;

            IF (bdpensaoalim IS NULL) THEN
               bdpensaoalim = 0;

            IF (bdpensaojudicial IS NULL) THEN
               bdpensaojudicial = 0;

            IF (bdajudacusto IS NULL) THEN
               bdajudacusto = 0;

            IF (bdlucropj IS NULL) THEN
               bdlucropj = 0;

            IF (bdavisoprev IS NULL) THEN
               bdavisoprev = 0;

            IF (bdpensaoalim13 IS NULL) THEN
               bdpensaoalim13 = 0;


            IF (i = 1) THEN
              BEGIN
                /* inicio calculo 13 salario */

                wsql = 'select SUM(X.BDBRUTO), '||
                       'SUM(X.BDDEP), '||
                       'SUM(X.BDVAlIR), '||
                       'SUM(X.BDVALINSS) ';
            
                
                wsql = wsql||'from VW_UNION_IR X '||
                         'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
                         'on (EMP.BDCODEMP = X.BDCODEMP) '||
        
                         'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
                         'on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL) ';

                wwhere = '';

                /* verbas de 13 salario de todo ano... */

                wwhere = wwhere||'(X.BDREF between '||wano||'01'||' and '||wano||'12'||') ';

                /* tipo de calculo 4 = Decimo terceiro salario */
                wwhere = wwhere||' and (X.BDTIPOCALC = '||'4'||') ';

                wwhere = wwhere||' and x.bdcodemp = '||:bdcodemp;

                wwhere = wwhere||' and x.bdcodcol = '||:bdcodcol;


                IF (wwhere <> '') THEN
                   wwhere = 'where '||wwhere;

                -- Group by
                wwhere = wwhere||
                         ' group by X.BDCODEMP, '||
                         'EMP.BDNOMEMP, '||
                         'X.BDCODCOL, '||
                         'COL.BDNOMCOL, '||
                         'X.BDREF, '||
                         'X.BDTIPOCALC ';

                wsql = wsql||wwhere;

                wqbg = 0;

                FOR EXECUTE STATEMENT wsql
                INTO
                  :bdrendtrib13,
                  :bddep13,
                  :bdirrf13,
                  :bdinss13
                DO
                BEGIN
                  wqbg = wqbg + 1;
                END

                IF (wqbg = 0) THEN
                  BEGIN
                    bdrendtrib13 = 0;
                    bddep13 = 0;
                    bdirrf13 = 0;
                    bdinss13 = 0;
                  END

                SELECT bdvalv FROM VRHF_SP_VERBAS_FN_FC('X.BDCODEMP = '|| :bdcodemp , 'X.BDCODCOL='|| :bdcodcol , :bdref , :bdref , '(BDCLAVER like ''5.001.0.1%'')')
                INTO bdpensaoalim13;

                IF (bdpensaoalim13 IS NULL) THEN
                   bdpensaoalim13 = 0;

              END

            wdatasaida = CAST(SUBSTRING(CAST(wrefaux AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wrefaux AS VARCHAR(6)) FROM 1 FOR 4) AS DATE);
            bddata = wdatasaida;
            bdgrupo = 1;

            SUSPEND;
            bdgrupo = 2;
            SUSPEND;

            wdataaux = CAST(SUBSTRING(CAST(wrefaux AS VARCHAR(6)) FROM 5 FOR 2)||'-01-'||SUBSTRING(CAST(wrefaux AS VARCHAR(6)) FROM 1 FOR 4) AS DATE);

            wdataaux = addmonth(wdataaux, 1);

            wrefaux = SUBSTRING(CAST(wdataaux AS VARCHAR(40)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataaux AS VARCHAR(40)) FROM 6 FOR 2);

            bdalugueis = 0;
            bdprivprivada = 0;
            bddespmedicas = 0;
            bdpensaoalim = 0;
            bdpensaojudicial = 0;
            bdajudacusto = 0;
            bdlucropj = 0;
            bdavisoprev = 0;

        END /* laco dos 12 meses */

        /* zera os campos de 13 salario na troca de funcionario */
        bdrendtrib13 = 0;
        bddep13 = 0;
        bdirrf13 = 0;
        bdinss13 = 0;



    END /* FIM LACO DE FUNCIONARIO..... */


  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);


END
^

/* Restore proc. body: VRHF_SP_FICHARAIS */
ALTER PROCEDURE VRHF_SP_FICHARAIS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF INTEGER,
BDBRAIS NUMERIC(15,6),
BDB13 NUMERIC(15,6),
BDBA13 NUMERIC(15,6),
BDBC13 NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WDATA DATE;
BEGIN

  IF (prreffim IS NULL) THEN
     BEGIN
       FOR SELECT CURRENT_DATE FROM rdb$database INTO :wdata DO
       wano = EXTRACT(YEAR FROM :wdata);
       wmes = EXTRACT(MONTH FROM :wdata);
       EXECUTE PROCEDURE sp_seta_competencia(wano||wmes, NULL, NULL);
     END
  ELSE
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);


  wsql = 'select X.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'X.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'X.BDREF, '||
                'SUM(X.BDBRAISFN), '||
                'SUM(X.BDBRAIS13), '||
                'SUM(X.BDBRAISA13), '||
                'SUM(X.BDBRAISC13) ';

  wsql = wsql||'from VW_UNION_RAIS X '||

             'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
             'on (EMP.BDCODEMP = X.BDCODEMP) '||

             'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
             'on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL) ';

  wwhere = '';

  IF (PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||'('||PRCODEMP||') ';
     END 

  IF (PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'('||PRCODCOL||') ';
     END

  IF (PRREFINI IS NOT NULL AND PRREFFIM IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'(X.BDREF between '||PRREFINI||' and '||PRREFFIM||') ';
     END

  IF (wwhere <> '') THEN
     wwhere = 'where '||wwhere;


  -- Group by
  wwhere = wwhere||
           ' group by X.BDCODEMP, '||
                     'EMP.BDNOMEMP, '||
                     'X.BDCODCOL, '||
                     'COL.BDNOMCOL, '||
                     'X.BDREF ';

  wsql = wsql||wwhere;

    FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :bdnomemp,
        :BDCODCOL,
        :bdnomcol,
        :BDREF,
        :BDBRAIS,
        :bdb13,
        :bdba13,
        :bdbc13
      DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);


END
^

/* Restore proc. body: VRHF_SP_FICHARAIS_NOVO */
create or alter procedure VRHF_SP_FICHARAIS_NOVO (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDREF integer,
    BDBRAIS numeric(15,6),
    BDB13 numeric(15,6),
    BDBA13 numeric(15,6),
    BDBC13 numeric(15,6))
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WANO integer;
declare variable WMES integer;
declare variable WDATA date;
declare variable WEMPATU integer;
declare variable WCOLATU integer;
BEGIN

  IF (prreffim IS NULL) THEN
     BEGIN
       FOR SELECT CURRENT_DATE FROM rdb$database INTO :wdata DO
       wano = EXTRACT(YEAR FROM :wdata);
       wmes = EXTRACT(MONTH FROM :wdata);
       EXECUTE PROCEDURE sp_seta_competencia(wano||wmes, NULL, NULL);
     END
  ELSE
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);


  wsql = 'select x.BDCODEMP, x.BDCODCOL, x.BDREF,'||
         ' case when x.ORIGEM = 0 then x.BDBRAISFN else x.x1 end BDBRAISFN,'||
         ' case when x.ORIGEM = 0 then x.BDBRAIS13 else x.x2 end BDBRAIS13,'||
         ' case when x.ORIGEM = 0 then x.BDBRAISA13 else x.x3 end BDBRAISA13,'||
         ' case when x.ORIGEM = 0 then x.BDBRAISC13 else x.x4 end BDBRAISC13'||
         ' from ('||
         '        select BDCODEMP, BDCODCOL, BDREF,'||
         '               sum(BDBRAISFN) BDBRAISFN, sum(BDBRAIS13) BDBRAIS13, sum(BDBRAISA13) BDBRAISA13, sum(BDBRAISC13) BDBRAISC13, sum(x1) x1, sum(x2) x2, sum(x3) x3, sum(x4) x4,'||
         '               min(BDORIGEM) ORIGEM'||
         '               from ('||
         '        SELECT BDCODEMP, BDCODCOL, BDREF, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0 x1,0 x2,0 x3,0 x4, BDTIPO, 0 BDORIGEM FROM VW_RAIS_FOL_NORMAL'||
         '        union all'||
         '        SELECT BDCODEMP, BDCODCOL, BDREF, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0,0,0,0,BDTIPO, 0 BDORIGEM  FROM VW_RAIS_FOL_COMPLEMENTAR'||
         '        union all'||
         '        select BDCODEMP, BDCODCOL, BDREF, sum(BDBRAISFN), sum(BDBRAIS13), sum(BDBRAISA13), sum(BDBRAISC13), sum(X1) X1, sum(X2) X2, sum(X3) X3, sum(X4) X4, 0, min(BDORIGEM)'||
         '        from (select BDCODEMP, BDCODCOL, BDREF, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0 X1, 0 X2, 0 X3, 0 X4, 0 BDORIGEM'||
         '              from VW_RAIS_A13'||
         '              union all'||
         '              select BDCODEMP, BDCODCOL, BDREF, 0, 0, 0, 0, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 1 BDORIGEM'||
         '              from VW_FICHA_RAIS_AD13)'||
         '        group by BDCODEMP, BDCODCOL, BDREF'||
         '        union all'||
         '        SELECT BDCODEMP, BDCODCOL, BDREF, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0,0,0,0,BDTIPO, 0 BDORIGEM  FROM VW_RAIS_13S'||
         '        union all'||
         '        SELECT BDCODEMP, BDCODCOL, BDREF, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0,0,0,0,BDTIPO, 0 BDORIGEM  FROM VW_RAIS_C13'||
         '        union all'||
         '        SELECT BDCODEMP, BDCODCOL, BDREF, BDBRAISFN, BDBRAIS13, BDBRAISA13, BDBRAISC13, 0,0,0,0,BDTIPO, 0 BDORIGEM  FROM VW_RAIS_FOL_AVULSA'||
         '        union all'||
         '        SELECT FF.BDCODEMP, FF.BDCODCOL, FF.BDREF, 0,0,0,0,FF.BDBRAISFN, FF.BDBRAIS13, FF.BDBRAISA13, FF.BDBRAISC13, ff.BDTIPO, 1 BDORIGEM from vw_ficha_rais2 FF'||
         '        )'||
         '        group by BDCODEMP, BDCODCOL, BDREF'||
         '      ) x ';

  wsql = wsql||' left outer join VW_VRH_EMP_TCOLCON_CAD COL on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL) ';

  wwhere = '';

  IF (PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||'('||PRCODEMP||') ';
     END 

  IF (PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'('||PRCODCOL||') ';
     END

  IF (PRREFINI IS NOT NULL AND PRREFFIM IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'(X.BDREF between '||PRREFINI||' and '||PRREFFIM||') ';
     END

  IF (wwhere <> '') THEN
     wwhere = 'where '||wwhere;

  -- Group by
--  wwhere = wwhere||
--           ' group by X.BDCODEMP, '||
--                     'EMP.BDNOMEMP, '||
--                     'X.BDCODCOL, '||
--                     'COL.BDNOMCOL, '||
--                     'X.BDREF ';

  wsql = wsql||wwhere;
  wsql = wsql||' order by x.BDCODEMP, x.BDCODCOL';
  wempatu = 0;
  wcolatu = 0;

    FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :BDCODCOL,
        :BDREF,
        :BDBRAIS,
        :bdb13,
        :bdba13,
        :bdbc13
      DO
      begin
        if ((wempatu <> BDCODEMP) or (wcolatu <> BDCODCOL)) then
           begin
             wwhere = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFCOL <= '||prreffim||' order by BDREFCOL DESC';
             execute statement wwhere into :BDNOMCOL;

             if (wempatu <> BDCODEMP) then
                begin
                  wwhere = 'select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = '||BDCODEMP||' and BDREFEMP <= '||prreffim||' order by BDREFEMP DESC';
                  execute statement wwhere into :BDNOMEMP;
                end

              wempatu = BDCODEMP;
              wcolatu = BDCODCOL;
           end

  SUSPEND;
      end

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);

END^

/* Restore proc. body: VRHF_SP_FN_FC_13_C13_VERBAS */
ALTER PROCEDURE VRHF_SP_FN_FC_13_C13_VERBAS(PREMPRESA VARCHAR(15000),
PRCOLABORADOR VARCHAR(30000),
PRREFERENCIA INTEGER,
PRTIPOPARCELA SMALLINT)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF INTEGER,
BDSUMVALV NUMERIC(18,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(15000);
DECLARE VARIABLE WORDERBY VARCHAR(10000);
DECLARE VARIABLE WGROUPBY VARCHAR(10000);
BEGIN
  wsql = 'select ';
  wsql = wsql || 'tverbas_union.bdcodemp, ';
  wsql = wsql || 'tverbas_union.bdcodcol, ';
  wsql = wsql || 'COLCAD.bdNOMCOL, ';
  wsql = wsql || 'tverbas_union.bdref, ';
  wsql = wsql || 'sum(tverbas_union.bdvalv) ';
  wsql = wsql || 'from vw_vrhf_fn_fc_13_c13_verbas tverbas_union ';
  wsql = wsql || 'inner join vrh_base_tverbas tverbas on (tverbas.bdcodver = tverbas_union.bdcodver) ';
  wsql = wsql || 'inner join VW_VERBAS_REF_ATUAL tverbasref on (tverbasref.bdcodver = tverbas.bdcodver) and (tverbasref.bdinssver <> 0) ';
  wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.bdcodemp = tverbas_union.bdcodemp and COLCAD.bdcodcol =  tverbas_union.bdcodcol) ';

  wwhere = '';

  IF (prempresa <> '') THEN
     wwhere = wwhere||prempresa||' ';
  IF (prcolaborador <> '') THEN
      BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
        wwhere = wwhere||prcolaborador||' ';
     END

  IF (prreferencia IS NOT NULL) THEN
     BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
        wwhere = wwhere||'tverbas_union.bdref <= '||prreferencia||' ';
     END

  IF (prtipoparcela = 0) THEN
     wwhere = wwhere||'and (substring(tverbas.bdclaver from 1 for 7) = '||'''0.001.0'''||' '||
                      ' or substring(tverbas.bdclaver from 1 for 7) = '||'''0.001.1'''||' '||
                      ' or substring(tverbas.bdclaver from 1 for 7) = '||'''0.001.2'''||') ';
  ELSE
  IF (prtipoparcela = 1) THEN
     wwhere = wwhere||'and substring(tverbas.bdclaver from 1 for 5) = '||'''0.002'''||' ';
  ELSE
  IF (prtipoparcela = 2) THEN
     wwhere = wwhere||'and substring(tverbas.bdclaver from 1 for 7) = '||'''0.001.3'''||' ';
  ELSE
  IF (prtipoparcela = 3) THEN
     wwhere = wwhere||'and substring(tverbas.bdclaver from 1 for 5) = '||'''0.006'''||' ';
  ELSE
  IF (prtipoparcela = 4) THEN
     wwhere = wwhere||'and (substring(tverbas.bdclaver from 1 for 5) = '||'''0.100'''||' '||
                      ' or substring(tverbas.bdclaver from 1 for 5) = '||'''0.120'''||' '||
                      ' or substring(tverbas.bdclaver from 1 for 5) = '||'''0.140'''||' '||
                      ' or substring(tverbas.bdclaver from 1 for 5) = '||'''0.160'''||' '||
                      ' or substring(tverbas.bdclaver from 1 for 5) = '||'''0.180'''||' '||
                      ' or substring(tverbas.bdclaver from 1 for 5) = '||'''0.190'''||' '||
                      ' or substring(tverbas.bdclaver from 1 for 5) = '||'''0.191'''||') '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''0.110'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''0.130'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''0.150'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''0.170'''||' '||
                      'and tverbasref.bdtipocodver = 0';
  ELSE
  IF (prtipoparcela = 5) THEN
     wwhere = wwhere||'and (substring(tverbas.bdclaver from 1 for 5) = '||'''0.110'''||' '||
                      ' or substring(tverbas.bdclaver from 1 for 5) = '||'''0.130'''||' '||
                      ' or substring(tverbas.bdclaver from 1 for 5) = '||'''0.150'''||' '||
                      ' or substring(tverbas.bdclaver from 1 for 5) = '||'''0.170'''||') ';
  ELSE
  IF (prtipoparcela = 6) THEN
     wwhere = wwhere||'and (substring(tverbas.bdclaver from 1 for 1) = '||'''5'''||' '||
                       'or substring(tverbas.bdclaver from 1 for 5) = '||'''7.050'''||' '||
                       'or substring(tverbas.bdclaver from 1 for 5) = '||'''7.060'''||' '||
                       'or substring(tverbas.bdclaver from 1 for 5) = '||'''7.061'''||' '||
                       'or substring(tverbas.bdclaver from 1 for 5) = '||'''7.071'''||' '||
                       'or substring(tverbas.bdclaver from 1 for 5) = '||'''7.080'''||' '||
                       'or substring(tverbas.bdclaver from 1 for 5) = '||'''7.081'''||' '||
                       'or substring(tverbas.bdclaver from 1 for 5) = '||'''7.090'''||' '||
                       'or substring(tverbas.bdclaver from 1 for 5) = '||'''7.091'''||') '||
                       'and tverbasref.bdtipocodver = 0';

  ELSE
  IF (prtipoparcela = 7) THEN
     wwhere = wwhere||'and substring(tverbas.bdclaver from 1 for 7) <> '||'''0.001.0'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 7) <> '||'''0.001.1'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 7) <> '||'''0.001.2'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''0.002'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 7) <> '||'''0.001.3'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''0.006'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''0.100'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''0.110'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''0.120'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''0.130'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''0.140'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''0.150'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''0.160'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''0.170'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''0.180'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''0.190'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''0.191'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 1) <> '||'''9'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 1) <> '||'''5'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''7.050'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''7.060'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''7.061'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''7.071'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''7.080'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''7.081'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''7.090'''||' '||
                      'and substring(tverbas.bdclaver from 1 for 5) <> '||'''7.091'''||' '||
                      'and tverbasref.bdtipocodver = 0';
  ELSE
  IF (prtipoparcela = 8) THEN
     wwhere = wwhere||'and substring(tverbas.bdclaver from 1 for 5) = '||'''0.007'''||' '||
                      'and tverbasref.bdtipocodver = 1';
  ELSE
  IF (prtipoparcela = 9) THEN
     wwhere = wwhere|| 'and (substring(tverbas.bdclaver from 1 for 5) <> '||'''0.007'''||' and '||
                       'substring(tverbas.bdclaver from 1 for 1) <> '||'''9'''||') and (tverbasref.bdtipocodver = 1) ';

  IF (wwhere <> '') THEN
      wwhere = ' where '||wwhere;

  wGroupby = 'group by tverbas_union.bdcodemp, tverbas_union.bdcodcol, COLCAD.bdnomcol, tverbas_union.bdref ';
  wOrderBy = 'order by tverbas_union.bdcodemp, tverbas_union.bdcodcol, tverbas_union.bdref ';
  wsql = wsql||wwhere||wgroupby||worderby;

  FOR EXECUTE STATEMENT wsql
     INTO
          :bdcodemp,
          :bdcodcol,
          :bdnomcol,
          :bdref,
          :bdsumvalv DO
   SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_GPS */
create or alter procedure VRHF_SP_GPS (
    PRCODIMP integer,
    PRCODEMP varchar(22000),
    PRCODCOL varchar(32000),
    PRCODAUT varchar(10000),
    PRTIPOCOL integer,
    PRANOMES integer,
    PRANOMESPAG integer,
    PRTIPOEMISSAO integer,
    PRAPENASGPS integer,
    PRTIPOGPS integer,
    PRPUXAFILIAIS integer)
returns (
    BDTIPOREG integer,
    BDCODEMP integer,
    BDREFFN integer,
    BDREFPAG integer,
    BDCODTPCC integer,
    BDCODCENTRO integer,
    BDTOTSEG numeric(15,6),
    BDTOTBASE numeric(15,6),
    BDSEGFUN numeric(15,6),
    BDBASEFUN numeric(15,6),
    BDPERCFUN numeric(15,6),
    BDVALFUNEMP numeric(15,6),
    BDSEGPRO numeric(15,6),
    BDBASEPRO numeric(15,6),
    BDPERCPRO numeric(15,6),
    BDVALPROEMP numeric(15,6),
    BDSEGAUT numeric(15,6),
    BDBASEAUT numeric(15,6),
    BDPERCAUT numeric(15,6),
    BDVALAUTEMP numeric(15,6),
    BDSALFAM numeric(15,6),
    BDSALMATERNIDADE numeric(15,6),
    BDBASERATAPO numeric(15,6),
    BDVALORRATAPO numeric(15,6),
    BDBASEFPAS numeric(15,6),
    BDPERCFPAS numeric(15,6),
    BDVALORFPAS numeric(15,6),
    BDPERCRAT numeric(15,6),
    BDVALORRAT numeric(15,6),
    BDVALORBRUTO numeric(15,6),
    BDVALORLIQUIDO numeric(15,6),
    BDNFCOOP numeric(15,6),
    BDCHAVE integer,
    BDVALCOMPENSADO numeric(15,6),
    BDVALACOMPENSAR numeric(15,6),
    BDVALORACUMULADO numeric(15,6),
    BDVALORACUMULADOUSADO numeric(15,6),
    BDVALORACUTERCEIROS numeric(15,6),
    BDVALORACUTERCEIROSUSADO numeric(15,6),
    BDCODEMPANT integer,
    BDCHAVEDARFANT integer,
    BDCODIMPANT integer,
    BDCODPERIODOANT integer,
    BDORDEMANT integer,
    BDREFERENCIAANT integer,
    BDQUOTAANT integer,
    BDDESCACUMDET varchar(3000),
    BDDESCACUM varchar(3000),
    BDVALORCAMPO6 numeric(15,6),
    BDVALNOTAS numeric(15,6),
    BDDESCNOTAS numeric(15,6),
    BDTOTDESCCOMP numeric(15,6),
    BDTOTVALORACUMULADO numeric(15,6),
    BDTOTVALORACUMULADOTERC numeric(15,6),
    BDINICOMP integer,
    BDFIMCOMP integer,
    BDTOTCOMPENSACAO numeric(15,6),
    BDDESCSALFAM numeric(15,6),
    BDDESCDEDGPS numeric(15,6),
    BDVALOUTENTIDADE numeric(15,6),
    BDSIMPLESGPS integer,
    BDCODENQFED integer,
    BDDESCENQFED varchar(10),
    BDCODCOL integer,
    BDCODTER integer,
    BDVALFUNEMPFN numeric(15,6),
    BDVALFUNEMPFC numeric(15,6),
    BDVALFUNEMPFERFN numeric(15,6),
    BDVALFUNEMPFERFC numeric(15,6),
    BDVALFUNEMP13FN numeric(15,6),
    BDVALFUNEMP13FC numeric(15,6),
    BDVALFUNEMP13 numeric(15,6),
    BDVALFUNEMPC13 numeric(15,6),
    BDVALPROEMPFN numeric(15,6),
    BDVALPROEMPFC numeric(15,6),
    BDVALPROEMPFERFN numeric(15,6),
    BDVALPROEMPFERFC numeric(15,6),
    BDVALPROEMP13FN numeric(15,6),
    BDVALPROEMP13FC numeric(15,6),
    BDVALPROEMP13 numeric(15,6),
    BDVALPROEMPC13 numeric(15,6),
    BDVALAUTEMPFN numeric(15,6),
    BDVALAUTEMPFC numeric(15,6),
    BDVALAUTEMPFERFN numeric(15,6),
    BDVALAUTEMPFERFC numeric(15,6),
    BDVALAUTEMP13FN numeric(15,6),
    BDVALAUTEMP13FC numeric(15,6),
    BDVALAUTEMP13 numeric(15,6),
    BDVALAUTEMPC13 numeric(15,6),
    BDVALFPASEMPFN numeric(15,6),
    BDVALFPASEMPFC numeric(15,6),
    BDVALFPASEMPFERFN numeric(15,6),
    BDVALFPASEMPFERFC numeric(15,6),
    BDVALFPASEMP13FN numeric(15,6),
    BDVALFPASEMP13FC numeric(15,6),
    BDVALFPASEMP13 numeric(15,6),
    BDVALFPASEMPC13 numeric(15,6),
    BDVALRATEMPFN numeric(15,6),
    BDVALRATEMPFC numeric(15,6),
    BDVALRATEMPFERFN numeric(15,6),
    BDVALRATEMPFERFC numeric(15,6),
    BDVALRATEMP13FN numeric(15,6),
    BDVALRATEMP13FC numeric(15,6),
    BDVALRATEMP13 numeric(15,6),
    BDVALRATEMPC13 numeric(15,6),
    BDVALRATAPOEMPFN numeric(15,6),
    BDVALRATAPOEMPFC numeric(15,6),
    BDVALRATAPOEMPFERFN numeric(15,6),
    BDVALRATAPOEMPFERFC numeric(15,6),
    BDVALRATAPOEMP13FN numeric(15,6),
    BDVALRATAPOEMP13FC numeric(15,6),
    BDVALRATAPOEMP13 numeric(15,6),
    BDVALRATAPOEMPC13 numeric(15,6),
    BDCHAVEDARF integer)
as
declare variable WSQLTIPOFOLHA varchar(1000);
declare variable WBDBASEFUNFN numeric(15,6);
declare variable WBDBASEFUNFC numeric(15,6);
declare variable WBDBASEFUNFERFN numeric(15,6);
declare variable WBDBASEFUNFERFC numeric(15,6);
declare variable WBDBASEFUN13RFN numeric(15,6);
declare variable WBDBASEFUN13RFC numeric(15,6);
declare variable WBDBASEFUN13 numeric(15,6);
declare variable WBDBASEFUNC13 numeric(15,6);
declare variable WBDBASEPROFN numeric(15,6);
declare variable WBDBASEPROFC numeric(15,6);
declare variable WBDBASEPROFERFN numeric(15,6);
declare variable WBDBASEPROFERFC numeric(15,6);
declare variable WBDBASEPRO13RFN numeric(15,6);
declare variable WBDBASEPRO13RFC numeric(15,6);
declare variable WBDBASEPRO13 numeric(15,6);
declare variable WBDBASEPROC13 numeric(15,6);
declare variable WBDBASEAUTFN numeric(15,6);
declare variable WBDBASEAUTFC numeric(15,6);
declare variable WBDBASEAUTFERFN numeric(15,6);
declare variable WBDBASEAUTFERFC numeric(15,6);
declare variable WBDBASEAUT13RFN numeric(15,6);
declare variable WBDBASEAUT13RFC numeric(15,6);
declare variable WBDBASEAUT13 numeric(15,6);
declare variable WBDBASEAUTC13 numeric(15,6);
declare variable WBDBASEFPASFN numeric(15,6);
declare variable WBDBASEFPASFC numeric(15,6);
declare variable WBDBASEFPASFERFN numeric(15,6);
declare variable WBDBASEFPASFERFC numeric(15,6);
declare variable WBDBASEFPAS13RFN numeric(15,6);
declare variable WBDBASEFPAS13RFC numeric(15,6);
declare variable WBDBASEFPAS13 numeric(15,6);
declare variable WBDBASEFPASC13 numeric(15,6);
declare variable WBDBASERATAPOFN numeric(15,6);
declare variable WBDBASERATAPOFC numeric(15,6);
declare variable WBDBASERATAPOFERFN numeric(15,6);
declare variable WBDBASERATAPOFERFC numeric(15,6);
declare variable WBDBASERATAPO13RFN numeric(15,6);
declare variable WBDBASERATAPO13RFC numeric(15,6);
declare variable WBDBASERATAPO13 numeric(15,6);
declare variable WBDBASERATAPOC13 numeric(15,6);
declare variable WCODTER integer;
declare variable WCODCOL integer;
declare variable WORDEM integer;
declare variable WSQLAUX varchar(10000);
declare variable WSQL varchar(32000);
declare variable WAUX numeric(15,6);
declare variable WSALVAVALORCOMPENSADO numeric(15,6);
declare variable WVALACOMPGPS numeric(15,6);
declare variable WVALCOMPENSADO numeric(15,6);
declare variable WPERC numeric(15,6);
declare variable WVALBASECOMP numeric(15,6);
declare variable WVALPODECOMP numeric(15,6);
declare variable WVALACU numeric(15,6);
declare variable WTOTACU numeric(15,6);
declare variable WVALACUTER numeric(15,6);
declare variable WTOTACUTER numeric(15,6);
declare variable WREFUTIMAL integer;
declare variable WCODPERIODO integer;
declare variable WQUOTA integer;
declare variable WAUXDESC numeric(15,2);
declare variable WAUXDESC2 varchar(30);
declare variable WPOS integer;
declare variable WSQLAUX2 varchar(3000);
declare variable WAUXTOTACU numeric(15,6);
declare variable WAUXTOTACUTER numeric(15,6);
declare variable WINICOMP integer;
declare variable WFIMCOMP integer;
declare variable WTIPOCONTAB integer;
declare variable WSUMVALFUNEMP numeric(15,6);
declare variable WSUMBASEFUNEMP numeric(15,6);
declare variable WSUMVALPROEMP numeric(15,6);
declare variable WSUMBASEPROEMP numeric(15,6);
declare variable WSUMVALAUTEMP numeric(15,6);
declare variable WSUMBASEAUTEMP numeric(15,6);
declare variable WSUMBASEFPAS numeric(15,6);
declare variable WSUMVALFPAS numeric(15,6);
declare variable WSUMBASERAT numeric(15,6);
declare variable WSUMVALRAT numeric(15,6);
BEGIN
  /* prtipogps
     0 = normal
     1 = folha complementar
     2 = 13 sal
     3 = comp. 13 sal
     4 = prévia de rescisão
  */
  /* prtipoemissao
     0 = por cc
     1 = agrupado
     3 = por tomador (utilizado na SEFIP)
  */
  /* prapenasgps
     0 = apenas gps
     1 = historicos compensacoes/nf/gps
  */
  /* PRPUXAFILIAIS
     0 = Nao
     1 = Sim
  */
  /*
    BDTIPOREG
    0 = GPS
    1 = nf
    2 = gps comp
    3 = compensacao
    4 = historico comp
    5 = historico nf
    6 = historico gps
    7 = registro acumulados
    8 = contabilizacao
  */

  IF (prtipogps IS NULL) THEN
     prtipogps = 0;

  IF (prcodimp IS NULL) THEN
     prcodimp = 0;

  IF (prcodemp IS NULL) THEN
     prcodemp = 'null';
  ELSE
     BEGIN
       prcodemp = ''''||prcodemp||'''';
     END

  IF (prcodcol IS NULL) THEN
     prcodcol = 'null';
  ELSE
     prcodcol = ''''||prcodcol||'''';

  IF (prcodaut IS NULL) THEN
     prcodaut = 'null';
  ELSE
     prcodaut = ''''||prcodaut||'''';

  IF (prtipocol IS NULL) THEN
     prtipocol = 0;

  IF (pranomes IS NULL) THEN
     pranomes = 0;

  IF ((prtipoemissao IS NULL) OR (prtipoemissao = 1)) THEN
     prtipoemissao = 1;
  ELSE IF (prtipoemissao <> 3) THEN
     prtipoemissao = 4;

  IF (prpuxafiliais IS NULL) THEN
     prpuxafiliais = 0;

  IF (prapenasgps IS NULL) THEN
     pranomespag = 1;

  IF (pranomespag IS NULL) THEN
     pranomespag = pranomes;

  EXECUTE PROCEDURE sp_seta_competencia(pranomes,NULL,NULL);

  wsql = 'SELECT bdcodemp, bdtipo, bdreffn, bdrefpag, bdcodcentro, bdcodtpcc, bdtotSeg, bdtotBase, bdSEGFUN, bdBaseFun, bdPercFun, bdSegPro, bdBasePro, bdPercPro, bdSegAut, bdBaseAut,'||
         'bdPercAut, bdbaseratapo, bdvalorratapo, bdsalfam, bdsalmaternidade, bdbasefpas, bdpercfpas, bdpercrat, BDVALOUTENTIDADE, bddescenqfed, bdsimplesgps, bdcodenqfed,'||
         'bdcodcol, bdcodter, '||
         'bdbasefunfn, bdbasefunfc, bdbasefunferfn, bdbasefunferfc, bdbasefun13rfn, bdbasefun13rfc, bdbasefun13, bdbasefunc13,'||
         'bdbaseprofn, bdbaseprofc, bdbaseproferfn, bdbaseproferfc, bdbasepro13rfn, bdbasepro13rfc, bdbasepro13, bdbaseproc13,'||
         'bdbaseautfn, bdbaseautfc, bdbaseautferfn, bdbaseautferfc, bdbaseaut13rfn, bdbaseaut13rfc, bdbaseaut13, bdbaseautc13,'||
         'bdbasefpasfn, bdbasefpasfc, bdbasefpasferfn, bdbasefpasferfc, bdbasefpas13rfn, bdbasefpas13rfc, bdbasefpas13, bdbasefpasc13,'||
         'bdbaseratapofn, bdbaseratapofc, bdbaseratapoferfn, bdbaseratapoferfc, bdbaseratapo13rfn, bdbaseratapo13rfc, bdbaseratapo13, bdbaseratapoc13';
  wsql = wsql||' FROM VRHF_SP_DADOS_CALC_GPS('||prcodemp||','||prcodcol||','||prcodaut||','||prtipocol||','||pranomes||','||pranomespag||',0,'||prtipogps||','||prpuxafiliais||','||prapenasgps||')';

  wsumvalfunemp = 0;
  wsumbasefunemp = 0;
  wsumvalproemp = 0;
  wsumbaseproemp = 0;
  wsumvalAUTemp = 0;
  wsumbaseAUTemp = 0;
  WSUMVALAUTEMP = 0;
  WSUMBASEAUTEMP = 0;
  wsumbasefpas = 0;
  wsumvalfpas = 0;
  wsumbaserat = 0;
  wsumvalrat = 0;

  FOR EXECUTE STATEMENT wsql INTO
      : bdcodemp,
      : WTIPOCONTAB,
      : bdreffn,
      : bdrefpag,
      : bdcodcentro,
      : bdcodtpcc,

      /*totais*/
      : bdtotSeg,
      : bdtotBase,

      /*colaboradores*/
      : bdSEGFUN,
      : bdBaseFun,
      : bdPercFun,

       /*prolaboristas*/
      : bdSegPro,
      : bdBasePro,
      : bdPercPro,

      /*autonomos*/
      : bdSegAut,
      : bdBaseAut,
      : bdPercAut,

      /* rat aposentadoria*/
      : bdbaseratapo,
      : bdvalorratapo,

      : bdsalfam,
      : bdsalmaternidade,

      /* base fpas*/
      : bdbasefpas,
      : bdpercfpas,

      /* rat */
      : bdpercrat,

      : BDVALOUTENTIDADE,

      : bddescenqfed,
      : bdsimplesgps,
      : bdcodenqfed,

      : wcodcol,
      : wcodter,

      : wbdbasefunfn,
      : wbdbasefunfc,
      : wbdbasefunferfn,
      : wbdbasefunferfc,
      : wbdbasefun13rfn,
      : wbdbasefun13rfc,
      : wbdbasefun13,
      : wbdbasefunc13,

      : wbdbaseprofn,
      : wbdbaseprofc,
      : wbdbaseproferfn,
      : wbdbaseproferfc,
      : wbdbasepro13rfn,
      : wbdbasepro13rfc,
      : wbdbasepro13,
      : wbdbaseproc13,

      : wbdbaseautfn,
      : wbdbaseautfc,
      : wbdbaseautferfn,
      : wbdbaseautferfc,
      : wbdbaseaut13rfn,
      : wbdbaseaut13rfc,
      : wbdbaseaut13,
      : wbdbaseautc13,

      : wbdbasefpasfn,
      : wbdbasefpasfc,
      : wbdbasefpasferfn,
      : wbdbasefpasferfc,
      : wbdbasefpas13rfn,
      : wbdbasefpas13rfc,
      : wbdbasefpas13,
      : wbdbasefpasc13,

      : wbdbaseratapofn,
      : wbdbaseratapofc,
      : wbdbaseratapoferfn,
      : wbdbaseratapoferfc,
      : wbdbaseratapo13rfn,
      : wbdbaseratapo13rfc,
      : wbdbaseratapo13,
      : wbdbaseratapoc13
      DO
  BEGIN
    bdcodcol = NULL;
    bdcodter = NULL;

    bdinicomp = NULL;
    bdfimcomp = NULL;
    bdtotcompensacao = NULL;
    bdtotvaloracumulado = 0;
    bdtotvaloracumuladoTerc = 0;
    bdvaloracumulado = 0;
    bdvaloracuterceiros = 0;
    bddescsalfam = 0;
    bddescdedgps = 0;
    bddescnotas = 0;
    bdtotdesccomp = 0;

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
    /* colaboradores */
    IF ((bdbaseFun = 0) OR (bdpercFun = 0)) THEN
       waux = 0;
    ELSE
       BEGIN
         waux = (bdbaseFun * (bdpercFun / 100));
         waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
        END
    bdvalfunemp = waux;

    IF (wtipocontab IN (2)) THEN
       BEGIN
         wsumvalfunemp = wsumvalfunemp + bdvalfunemp;
         wsumbasefunemp = wsumbasefunemp + bdbaseFun;
       END

    IF (wtipocontab IN (2)) THEN
       BEGIN
         IF ((wsumbasefunemp = 0) OR (bdpercFun = 0)) THEN
            waux = 0;
         ELSE
            BEGIN
              waux = (wsumbasefunemp * (bdpercFun / 100));
              waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
             END

         IF (waux <> wsumvalfunemp) THEN
            BEGIN
              bdvalfunemp = bdvalfunemp + (waux - wsumvalfunemp);
--              wsumvalfunemp = bdvalfunemp;
              wsumvalfunemp = wsumvalfunemp + (waux - wsumvalfunemp);
            END
       END

    wsqltipofolha = 'select bdvalor01,bdvalor02,bdvalor03,bdvalor04,bdvalor05,bdvalor06,bdvalor07,bdvalor08 from sp_proporc_valores('||bdbasefun||','||bdvalfunemp||','||
                     wbdbasefunfn||','||wbdbasefunfc||','||wbdbasefunferfn||','||wbdbasefunferfc||','||wbdbasefun13rfn||','||wbdbasefun13rfc||','||wbdbasefun13||','||wbdbasefunc13||')';

    EXECUTE STATEMENT wsqltipofolha INTO
          :bdvalfunempfn, :bdvalfunempfc, :bdvalfunempferfn, :bdvalfunempferfc, :bdvalfunemp13fn, :bdvalfunemp13fc, :bdvalfunemp13, :bdvalfunempc13;

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
    /* prolaboristas */
    IF ((bdbasepro = 0) OR (bdpercpro = 0))  THEN
       waux = 0;
    ELSE
       BEGIN
         waux = (bdbasepro * (bdpercpro / 100));
         waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
       END
    bdvalproemp = waux;
    IF (wtipocontab IN (2)) THEN
       BEGIN
         wsumvalproemp = wsumvalproemp + bdvalproemp;
         wsumbaseproemp = wsumbaseproemp + bdbasepro;
       END

    IF (wtipocontab IN (2)) THEN
       BEGIN
         IF ((wsumbaseproemp = 0) OR (bdpercPRO = 0)) THEN
            waux = 0;
         ELSE
            BEGIN
              waux = (wsumbaseproemp * (bdpercPRO / 100));
              waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
             END

         IF (waux <> wsumvalproemp) THEN
            BEGIN
              bdvalproemp = bdvalproemp + (waux - wsumvalproemp);
              wsumvalproemp = bdvalproemp;
            END
       END

    wsqltipofolha = 'select bdvalor01,bdvalor02,bdvalor03,bdvalor04,bdvalor05,bdvalor06,bdvalor07,bdvalor08 from sp_proporc_valores('||bdbasepro||','||bdvalproemp||','||
                     wbdbaseprofn||','||wbdbaseprofc||','||wbdbaseproferfn||','||wbdbaseproferfc||','||wbdbasepro13rfn||','||wbdbasepro13rfc||','||wbdbasepro13||','||wbdbaseproc13||')';

    EXECUTE STATEMENT wsqltipofolha INTO
          :bdvalproempfn, :bdvalproempfc, :bdvalproempferfn, :bdvalproempferfc, :bdvalproemp13fn, :bdvalproemp13fc, :bdvalproemp13, :bdvalproempc13;

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
    /* autonomos */
    IF ((bdbaseaut = 0) OR (bdpercaut = 0))  THEN
       waux = 0;
    ELSE
       BEGIN
         waux = (bdpercaut / 100);
         waux =  CAST(bdbaseaut AS NUMERIC(15,2)) * waux;
         waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
       END
    bdvalautemp = waux;
    IF (wtipocontab IN (2)) THEN
       BEGIN
         wsumvalautemp = wsumvalautemp + bdvalautemp;
         wsumbaseautemp = wsumbaseautemp + bdbaseaut;
       END

    IF (wtipocontab IN (2)) THEN
       BEGIN
         IF ((wsumbaseautemp = 0) OR (bdpercaut = 0)) THEN
            waux = 0;
         ELSE
            BEGIN
              waux = (wsumbaseautemp * (bdpercaut / 100));
              waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
             END

         IF (waux <> wsumvalautemp) THEN
            BEGIN
              bdvalautemp = bdvalautemp + (waux - wsumvalautemp);
              wsumvalautemp = bdvalautemp;
            END
       END

    wsqltipofolha = 'select bdvalor01,bdvalor02,bdvalor03,bdvalor04,bdvalor05,bdvalor06,bdvalor07,bdvalor08 from sp_proporc_valores('||bdbaseaut||','||bdvalautemp||','||
                     wbdbaseautfn||','||wbdbaseautfc||','||wbdbaseautferfn||','||wbdbaseautferfc||','||wbdbaseaut13rfn||','||wbdbaseaut13rfc||','||wbdbaseaut13||','||wbdbaseautc13||')';

    EXECUTE STATEMENT wsqltipofolha INTO
          :bdvalautempfn, :bdvalautempfc, :bdvalautempferfn, :bdvalautempferfc, :bdvalautemp13fn, :bdvalautemp13fc, :bdvalautemp13, :bdvalautempc13;

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
    /* valor fpas (terceiros) */
    IF (bdsimplesgps IN (1,2,5)) THEN
       bdpercfpas = 0;

    IF ((bdbasefpas = 0) OR (bdpercfpas = 0)) THEN
       waux = 0;
    ELSE
       BEGIN
         waux = (bdbasefpas * (bdpercfpas / 100));
         waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
       END
    bdvalorfpas = waux;
    IF (wtipocontab IN (2)) THEN
       BEGIN
         wsumbasefpas = wsumbasefpas + bdbasefpas;
         wsumvalfpas = wsumvalfpas + bdvalorfpas;
       END

    IF (wtipocontab IN (2)) THEN
       BEGIN
         IF ((wsumbasefpas = 0) OR (bdpercfpas = 0)) THEN
            waux = 0;
         ELSE
            BEGIN
              waux = (wsumbasefpas * (bdpercfpas / 100));
              waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
             END

         IF (waux <> wsumvalfpas) THEN
            BEGIN
              bdvalorfpas = bdvalorfpas + (waux - wsumvalfpas);
              wsumvalfpas = bdvalorfpas;
            END
       END

    wsqltipofolha = 'select bdvalor01,bdvalor02,bdvalor03,bdvalor04,bdvalor05,bdvalor06,bdvalor07,bdvalor08 from sp_proporc_valores('||bdbasefpas||','||bdvalorfpas||','||
                     wbdbasefpasfn||','||wbdbasefpasfc||','||wbdbasefpasferfn||','||wbdbasefpasferfc||','||wbdbasefpas13rfn||','||wbdbasefpas13rfc||','||wbdbasefpas13||','||wbdbasefpasc13||')';

    EXECUTE STATEMENT wsqltipofolha INTO
          :bdvalfpasempfn, :bdvalfpasempfc, :bdvalfpasempferfn, :bdvalfpasempferfc, :bdvalfpasemp13fn, :bdvalfpasemp13fc, :bdvalfpasemp13, :bdvalfpasempc13;

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
    /* valor rat*/
    IF (bdsimplesgps IN (1,2,5)) THEN
       bdpercrat = 0;

    IF ((bdbasefpas = 0) OR (bdpercrat = 0)) THEN
       waux = 0;
    ELSE
       BEGIN
         waux = (bdbasefpas * (bdpercrat / 100));
         waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
       END
    bdvalorrat = waux;
    IF (wtipocontab IN (2)) THEN
       BEGIN
         wsumbaserat = wsumbaserat + bdbasefpas;
         wsumvalrat = wsumvalrat + bdvalorrat;
       END

    IF (wtipocontab IN (2)) THEN
       BEGIN
         IF ((wsumbaserat = 0) OR (bdpercrat = 0)) THEN
            waux = 0;
         ELSE
            BEGIN
              waux = (wsumbaserat * (bdpercrat / 100));
              waux =  CAST(waux - 0.005 AS NUMERIC(15,2)); /* cortar */
             END

         IF (waux <> wsumvalrat) THEN
            BEGIN
              bdvalorrat = bdvalorrat + (waux - wsumvalrat);
              wsumvalrat = bdvalorrat;
            END
       END

    wsqltipofolha = 'select bdvalor01,bdvalor02,bdvalor03,bdvalor04,bdvalor05,bdvalor06,bdvalor07,bdvalor08 from sp_proporc_valores('||bdbasefpas||','||bdvalorrat||','||
                     wbdbasefpasfn||','||wbdbasefpasfc||','||wbdbasefpasferfn||','||wbdbasefpasferfc||','||wbdbasefpas13rfn||','||wbdbasefpas13rfc||','||wbdbasefpas13||','||wbdbasefpasc13||')';

    EXECUTE STATEMENT wsqltipofolha INTO
          :bdvalratempfn, :bdvalratempfc, :bdvalratempferfn, :bdvalratempferfc, :bdvalratemp13fn, :bdvalratemp13fc, :bdvalratemp13, :bdvalratempc13;

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- rat aposentadoria

    wsqltipofolha = 'select bdvalor01,bdvalor02,bdvalor03,bdvalor04,bdvalor05,bdvalor06,bdvalor07,bdvalor08 from sp_proporc_valores('||bdbaseratapo||','||bdvalorratapo||','||
                     wbdbaseratapofn||','||wbdbaseratapofc||','||wbdbaseratapoferfn||','||wbdbaseratapoferfc||','||wbdbaseratapo13rfn||','||wbdbaseratapo13rfc||','||wbdbaseratapo13||','||wbdbaseratapoc13||')';

    EXECUTE STATEMENT wsqltipofolha INTO
          :bdvalratapoempfn, :bdvalratapoempfc, :bdvalratapoempferfn, :bdvalratapoempferfc, :bdvalratapoemp13fn, :bdvalratapoemp13fc, :bdvalratapoemp13, :bdvalratapoempc13;

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------

    /*valor bruto sem terceiros*/
    bdvalorbruto = bdtotseg + -- seguradors
                 bdvalautemp + -- autonomos emp
                 bdvalproemp + -- prolabore emp
                 bdvalfunemp + -- colaboradores emp
                 bdvalorratapo + -- rat aposentadoria
                 bdvalorrat; -- rat emp

    IF (wtipocontab = 1) THEN
       BEGIN
         wsumvalfunemp = 0;
         wsumbasefunemp = 0;
         wsumvalproemp = 0;
         wsumbaseproemp = 0;
         WSUMVALAUTEMP = 0;
         WSUMBASEAUTEMP = 0;
         wsumbasefpas = 0;
         wsumvalfpas = 0;
         wsumbaserat = 0;
         wsumvalrat = 0;
         /* soma valor acumulado */
         /*busca a ultima gps emitida para buscar acumulados*/
             /*verifica se existe registro atual para pegar a ordem*/
         wtotacu = 0;
         wtotacuter = 0;
         wsqlaux = 'select first 1 x.bdordem from tdarfpadrao x '||
                   'where x.bdreferencia = '||pranomes||
                   ' and x.bdcodemp = '||bdcodemp||
                   ' and x.bdcodimp = '||prcodimp||
                   ' and x.bdrefpag = '||pranomespag||
                   ' and x.BDTIPOIMPOSTO = ';

         IF (prtipogps = 4) THEN
            wsqlaux = wsqlaux||'0';
         ELSE
            wsqlaux = wsqlaux||prtipogps;

         IF (prtipoemissao <> 0) THEN
            BEGIN
             IF (bdcodtpcc IS NULL) THEN
                BEGIN
                  wsqlaux = wsqlaux||
                            ' and x.BDCODTPCC is null';
                END
             ELSE
                BEGIN
                  wsqlaux = wsqlaux||
                            ' and x.BDCODTPCC = '||bdcodtpcc;
                END
           END

         wordem = NULL;
         EXECUTE STATEMENT wsqlaux INTO wordem;
         wsqlaux = 'select first 1 '||
                      'x.bdreferencia,'||
                      'x.bdordem,'||
                      'x.BDCODPERIODO,'||
                      'x.BDQUOTA from tdarfpadrao x ';
         IF (wordem IS NULL) THEN
            BEGIN
             wsqlaux = wsqlaux||
                       ' where '||
                       ' x.bdcodemp = '||bdcodemp||
                       ' and x.bdcodimp = '||prcodimp||
                       ' and x.bdrefpag <= '||pranomespag||
                       ' and x.BDTIPOIMPOSTO = ';

             IF (prtipogps = 4) THEN
                wsqlaux = wsqlaux||'0';
             ELSE
                wsqlaux = wsqlaux||prtipogps;
            END
         ELSE
            BEGIN
              wsqlaux = wsqlaux||
                        ' where '||
                        ' x.bdcodemp = '||bdcodemp||
                        ' and x.bdcodimp = '||prcodimp||
                        ' and ((x.bdrefpag < '||pranomespag||') or (x.bdrefpag = '||pranomespag||' and x.bdordem < '||wordem||'))'||
                        ' and x.BDTIPOIMPOSTO = ';

              IF (prtipogps = 4) THEN
                 wsqlaux = wsqlaux||'0';
              ELSE
                 wsqlaux = wsqlaux||prtipogps;
            END

         IF (prtipoemissao <> 0) THEN
            BEGIN
             IF (bdcodtpcc IS NULL) THEN
                BEGIN
                  wsqlaux = wsqlaux||
                            ' and x.BDCODTPCC is null';
                END
             ELSE
                BEGIN
                  wsqlaux = wsqlaux||
                            ' and x.BDCODTPCC = '||bdcodtpcc;
                END
            END
     
         wsqlaux = wsqlaux||' order by x.bdrefpag desc, x.bdordem desc';

         wrefutimal = NULL;
         EXECUTE STATEMENT wsqlaux INTO wrefutimal,wordem,wcodperiodo,wquota;
         IF (wtotacu IS NULL) THEN
            wtotacu = 0;

         IF (wtotacuter IS NULL) THEN
            wtotacuter = 0;

         IF ((wrefutimal IS NOT NULL) AND (wrefutimal > 0)) THEN
            BEGIN
              wsqlaux = 'select y.bdvalcampo6,y.bdvalcampo9 from VRHF_SP_HIST_ACUMU_GPS('||''''||'x.bdcodemp = '||bdcodemp||' and x.bdcodimp = '||prcodimp||' and x.bdreferencia = '||wrefutimal||
                        ' and x.bdordem = '||wordem||' and x.BDCODPERIODO = '||wcodperiodo||' and x.BDQUOTA = '||wquota||''''||') y';
     
              FOR EXECUTE STATEMENT wsqlaux INTO
                : wvalacu,
                : wvalacuter
              DO
                BEGIN
                  IF (wvalacu IS NOT NULL) THEN
                     wtotacu = wtotacu + wvalacu;
     
                  IF (wvalacuter IS NOT NULL) THEN
                     wtotacuter = wtotacuter + wvalacuter;
                END
            END
         bdvalorbruto = bdvalorbruto + wtotacu;

         /* fim soma acumulado */
         /* somavalor nota fiscal cooperativa */
         wsqlaux = 'select bdvalliqnf from VRHF_SP_TNFCOOP('||''''||'colcon.bdcodemp = '||bdcodemp||''''||','||bdreffn||',null,'||prtipoemissao||','||prpuxafiliais||')';
         wsqlaux = wsqlaux||' where '||prtipogps||' <> 1'; -- Notas fiscais Coop nao devem ser utilizadas para folha complementar e compl 13 sal e 13 sal
         wsqlaux = wsqlaux||' and '||prtipogps||' <> 2'; -- Notas fiscais Coop nao devem ser utilizadas para folha complementar e compl 13 sal e 13 sal
         wsqlaux = wsqlaux||' and '||prtipogps||' <> 3'; -- Notas fiscais Coop nao devem ser utilizadas para folha complementar e compl 13 sal e 13 sal
         IF (prtipoemissao = 4) THEN
            BEGIN
              IF (bdcodtpcc IS NULL) THEN
                 wsqlaux = wsqlaux||' and bdcodtpcc is null';
              ELSE
                 wsqlaux = wsqlaux||' and bdcodtpcc = '||bdcodtpcc;
            END
         waux = 0;
         EXECUTE STATEMENT wsqlaux INTO waux;
         bdnfcoop = 0;
         IF (waux IS NOT NULL) THEN
            bdnfcoop = waux;
         bdvalorbruto = bdvalorbruto + bdnfcoop;
         wvalbasecomp = bdvalorbruto;
     
         bdvalacompensar = 0;
         bdvalorliquido = bdvalorbruto;

         /* desconta nota fiscais */
         IF (prtipogps = 2) THEN
            wsqlaux = 'select nf.bdchave, nf.bdvaldescnf from vrhf_emp_tnotasfiscais nf'||
                  ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(nf.bdcodtpcc,nf.bdcodcentro,'||pranomes||') toma on'||
                  ' (toma.bdcodcencus = nf.bdcodtpcc and toma.bdcodcentro = nf.bdcodcentro)'||
                  ' where nf.bdcodemp = '||bdcodemp||
                  ' and nf.bdrefnf = '||CAST(SUBSTRING(CAST(pranomes-1 AS VARCHAR(6)) FROM 1 FOR 4)||'13' AS INTEGER);
         ELSE
            wsqlaux = 'select nf.bdchave, nf.bdvaldescnf from vrhf_emp_tnotasfiscais nf'||
                  ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(nf.bdcodtpcc,nf.bdcodcentro,'||pranomes||') toma on'||
                  ' (toma.bdcodcencus = nf.bdcodtpcc and toma.bdcodcentro = nf.bdcodcentro)'||
                  ' where nf.bdcodemp = '||bdcodemp||
                  ' and nf.bdrefnf = '||pranomes;

         wsqlaux = wsqlaux||' and '||prtipogps||' <> 1'|| -- Notas fiscais nao devem ser utilizadas para folha complementar e compl 13 sal
                  ' and '||prtipogps||' <> 3';            -- Notas fiscais nao devem ser utilizadas para folha complementar e compl 13 sal
         IF (prtipoemissao = 4) THEN
            BEGIN
              IF (bdcodtpcc IS NULL) THEN
                 wsqlaux = wsqlaux||' and toma.bdcodtpcc is null';
              ELSE
                 wsqlaux = wsqlaux||' and toma.bdcodtpcc = '||bdcodtpcc;
            END

         wvalcompensado = 0;
         wvalacompgps = 0;
     
         waux = 0;
         bdValNotas = 0;
         bddescnotas = 0;
         FOR EXECUTE STATEMENT wsqlaux INTO
           : bdchave,
           : waux
         DO
            BEGIN
              bdValNotas = bdValNotas + waux;
              IF (bdvalorliquido > waux) THEN
                 BEGIN
                   bdvalorliquido = bdvalorliquido - (waux);
                   bdvalcompensado = waux;
                   bddescnotas = bddescnotas + waux;
                   bdvalacompensar = 0;
                 END
              ELSE
                 BEGIN
                   bdvalcompensado = bdvalorliquido;
                   bddescnotas = bddescnotas + bdvalorliquido;
                   bdvalacompensar = ((waux) - bdvalorliquido);
                   bdvalorliquido = 0;
                 END
              bdtiporeg = 1;
     
              wvalacompgps = wvalacompgps + bdvalacompensar;
              wvalcompensado = wvalcompensado + bdvalcompensado;
              IF (prapenasgps = 1) THEN
                 SUSPEND;
            END

         bdchave = NULL;
         /* desconta maternidade e salario familia*/
         IF (bdsalmaternidade + bdsalfam > 0) THEN
            BEGIN
              IF (bdvalorliquido > bdsalmaternidade) THEN
                 BEGIN
                   bdvalorliquido = bdvalorliquido - (bdsalmaternidade);
                   bdvalacompensar = 0;
                   bdvalcompensado = (bdsalmaternidade);
                   bddescdedgps = bdsalmaternidade;
                 END
              ELSE
                 BEGIN
                   bdvalacompensar = ((bdsalmaternidade + bdsalfam) - bdvalorliquido);
                   bdvalcompensado = bdvalorliquido;
                   bddescdedgps = bdvalorliquido;
                   bdvalorliquido = 0;
                 END
     
              IF (bdvalorliquido > bdsalfam) THEN
                 BEGIN
                   bdvalorliquido = bdvalorliquido - (bdsalfam);
                   bdvalacompensar = 0;
                   bdvalcompensado = bdvalcompensado + bdsalfam;
                   bddescsalfam = bdsalfam;
                 END
              ELSE
                 BEGIN
                   bdvalacompensar = ((bdsalmaternidade + bdsalfam) - bdvalorliquido);
                   bdvalcompensado = bdvalcompensado + bdvalorliquido;
                   bddescsalfam = bdvalorliquido;
                   bdvalorliquido = 0;
                 END
     
              bdtiporeg = 2;
              wvalacompgps = wvalacompgps + bdvalacompensar;
              wvalcompensado = wvalcompensado + bdvalcompensado;
     
              IF (prapenasgps = 1) THEN
                 SUSPEND;
            END
         /* Compensacao */
         wsqlaux = 'select * from vrhf_sp_tcompensacaogps('||prcodimp||','||
                                                          bdcodemp||','||
                                                          prtipogps||','||
                                                          prtipoemissao||',';
     
         IF (bdcodtpcc IS NULL) THEN
            wsqlaux = wsqlaux||'null,0)';
         ELSE
            wsqlaux = wsqlaux||bdcodtpcc||',0)';
     
         waux = 0;
         bdinicomp = NULL;
         bdfimcomp = NULL;
         bdtotcompensacao = 0;
         bdtotdesccomp = 0;
         FOR EXECUTE STATEMENT wsqlaux INTO
           : bdtiporeg,
           : bdchave,
           : waux,
           : wperc,
           : winicomp,
           : wfimcomp
         DO
            BEGIN
              bdtotcompensacao = bdtotcompensacao + waux;
              IF ((bdfimcomp IS NULL) OR (wfimcomp > bdfimcomp)) THEN
                 bdfimcomp = wfimcomp;
     
              IF ((bdinicomp IS NULL) OR (winicomp < bdinicomp)) THEN
                 bdinicomp = winicomp;
     
              IF ((wperc = 0) OR (wperc IS NULL) OR (wperc = 100)) THEN
                 BEGIN
                   wvalpodecomp = wvalbasecomp;
                 END
              ELSE
                 BEGIN
                   wvalpodecomp = wvalbasecomp;
                 END
     
              IF (wvalpodecomp > waux) THEN
                 BEGIN
                   IF (bdvalorliquido > waux) THEN
                      BEGIN
                        bdvalorliquido = bdvalorliquido - (waux);
                        bdvalacompensar = 0;
                        bdvalcompensado = (waux);
                        bdtotdesccomp = bdtotdesccomp + waux;
                      END
                   ELSE
                      BEGIN
                        bdvalacompensar = ((waux) - bdvalorliquido);
                        bdvalcompensado = bdvalorliquido;
                        bdtotdesccomp = bdtotdesccomp + bdvalorliquido;
                        bdvalorliquido = 0;
                      END
                 END
              ELSE
                 BEGIN
                   IF (bdvalorliquido > wvalpodecomp) THEN
                      BEGIN
                        bdvalorliquido = bdvalorliquido - wvalpodecomp;
                        bdvalacompensar = waux - wvalpodecomp;
                        bdvalcompensado = wvalpodecomp;
                        bdtotdesccomp = bdtotdesccomp + wvalpodecomp;
                      END
                   ELSE
                      BEGIN
                        bdvalacompensar = waux - bdvalorliquido;
                        bdvalcompensado = bdvalorliquido;
                        bdtotdesccomp = bdtotdesccomp + bdvalorliquido;
                        bdvalorliquido = 0;
                      END
                 END
     
              wvalacompgps = wvalacompgps + bdvalacompensar;
              wvalcompensado = wvalcompensado + bdvalcompensado;
              IF (prapenasgps = 1) THEN
                 SUSPEND;
            END

         /*valor bruto com terceiros*/
         bdvalorbruto = bdvalorbruto + -- valorbruto
                      wtotacuter + -- valor terceiro acumulado
                      bdvalorfpas; -- valor fpas terceiro

         bdvalorcampo6 = bdvalorliquido;
         /* valor liquido com terceiros */
         bdvalorliquido = bdvalorliquido +
                          wtotacuter + -- valor terceiro acumulado
                          bdvalorfpas; -- valor fpas terceiro
     
         /*registro acumulados */
         bdtiporeg = 7;
         wsalvavalorcompensado = wvalcompensado;
         bddescacumdet = '';
         bddescacum = '';
         wauxtotacu = 0;
         wauxtotacuter = 0;
         IF ((wrefutimal IS NOT NULL) AND (wrefutimal > 0)) THEN
            BEGIN
              wsqlaux = 'select bdcodemp,bdcodimp,bdchavedarf, bdcodperiodo, bdordem, bdreferencia, bdquota, y.bdvalcampo6,y.bdvalcampo9 from VRHF_SP_HIST_ACUMU_GPS('||''''||'x.bdcodemp = '||bdcodemp||' and x.bdcodimp = '||prcodimp||' and x.bdreferencia = '||wrefutimal||
                        ' and x.bdordem = '||wordem||' and x.BDCODPERIODO = '||wcodperiodo||' and x.BDQUOTA = '||wquota||''''||') y'||
                        ' where y.bdvalcampo6 > 0 and y.bdvalcampo9 > 0 '||
                        ' order by bdreferencia,bdordem ';
     
              FOR EXECUTE STATEMENT wsqlaux INTO
                : bdcodempant,
                : bdcodimpant,
                : bdchavedarfant,
                : bdcodperiodoant,
                : bdordemant,
                : bdreferenciaant,
                : bdquotaant,
                : bdvaloracumulado,
                : bdvaloracuterceiros
              DO
                BEGIN
                  IF (bdvaloracumulado IS NULL) THEN
                     bdvaloracumulado = 0;
     
                  IF (bdvaloracuterceiros IS NULL) THEN
                     bdvaloracuterceiros = 0;
     
                  bdtotvaloracumulado = bdvaloracumulado;
                  bdtotvaloracumuladoTerc = bdvaloracuterceiros;
                  wauxtotacu = wauxtotacu + bdtotvaloracumulado;
                  wauxtotacuter = wauxtotacuter + bdtotvaloracumuladoTerc;
     
                  bdvaloracumuladousado = bdvaloracumulado;
                  bdvaloracuterceirosusado = bdvaloracuterceiros;
     
                  IF ((bdvaloracumuladousado > 0) OR (bdvaloracuterceirosusado > 0)) THEN
                     BEGIN
                       IF (bdvaloracumuladousado+bdvaloracuterceirosusado > 0) THEN
                          BEGIN
                            IF (bddescacum <> '') THEN
                               bddescacum = bddescacum||'; ';
                            wauxdesc = CAST(bdvaloracumuladousado+bdvaloracuterceirosusado - 0.005 AS NUMERIC(15,2)); /* cortar */
                            wauxdesc2 = wauxdesc;
     
                            wsqlaux2 = 'select POS from pos('||''''||'.'||''''||','||''''||wauxdesc2||''''||')';
                            EXECUTE STATEMENT wsqlaux2 INTO wpos;
                            wauxdesc2 = SUBSTRING(wauxdesc2 FROM 1 FOR wpos - 1)||','||SUBSTRING(wauxdesc2 FROM wpos + 1);
     
                            bddescacum = bddescacum||''||SUBSTRING(CAST(bdreferenciaant AS VARCHAR(6)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(bdreferenciaant AS VARCHAR(6)) FROM 1 FOR 4);
                            bddescacum = bddescacum||' R$ '||(wauxdesc2);
                          END
     
                       IF ((bdvaloracumuladousado > 0) OR (bdvaloracuterceirosusado > 0)) THEN
                          BEGIN
                            IF (bddescacumdet <> '') THEN
                               bddescacumdet = bddescacumdet||'; ';
         
                            bddescacumdet = bddescacumdet||''||SUBSTRING(CAST(bdreferenciaant AS VARCHAR(6)) FROM 5 FOR 2)||'/'||SUBSTRING(CAST(bdreferenciaant AS VARCHAR(6)) FROM 1 FOR 4);
                            IF (bdvaloracumuladousado > 0) THEN
                               BEGIN
                                 wauxdesc = CAST(bdvaloracumuladousado - 0.005 AS NUMERIC(15,2)); /* cortar */
                                 wauxdesc2 = wauxdesc;
     
                                 wsqlaux2 = 'select POS from pos('||''''||'.'||''''||','||''''||wauxdesc2||''''||')';
                                 EXECUTE STATEMENT wsqlaux2 INTO wpos;
                                 wauxdesc2 = SUBSTRING(wauxdesc2 FROM 1 FOR wpos - 1)||','||SUBSTRING(wauxdesc2 FROM wpos + 1);
     
                                 bddescacumdet = bddescacumdet||' R$ '||wauxdesc2;
     
                                 IF (bdvaloracuterceirosusado > 0) THEN
                                    bddescacumdet = bddescacumdet||' +';
                               END
     
                            IF (bdvaloracuterceirosusado > 0) THEN
                               BEGIN
                                 wauxdesc = CAST(bdvaloracuterceirosusado - 0.005 AS NUMERIC(15,2)); /* cortar */
                                 wauxdesc2 = wauxdesc;
     
                                 wsqlaux2 = 'select POS from pos('||''''||'.'||''''||','||''''||wauxdesc2||''''||')';
                                 EXECUTE STATEMENT wsqlaux2 INTO wpos;
                                 wauxdesc2 = SUBSTRING(wauxdesc2 FROM 1 FOR wpos - 1)||','||SUBSTRING(wauxdesc2 FROM wpos + 1);
                                 bddescacumdet = bddescacumdet||' R$ '||wauxdesc2||'(terc)';
                               END
                          END
                     END
     
                  IF (bdvaloracumulado <= wsalvavalorcompensado) THEN
                     BEGIN
                       wsalvavalorcompensado = wsalvavalorcompensado - bdvaloracumulado;
                       bdvaloracumulado = 0;
                     END
                  ELSE
                     BEGIN
                       bdvaloracumulado = bdvaloracumulado - wsalvavalorcompensado;
                       wsalvavalorcompensado = 0;
                     END
     
                  IF (prapenasgps = 1) THEN
                     SUSPEND;
                END
            END

         bdvaloracumuladousado = NULL;
         bdvaloracuterceirosusado = NULL;
         bdcodempant = NULL;
         bdcodimpant = NULL;
         bdcodperiodoant = NULL;
         bdordemant = NULL;
         bdreferenciaant = NULL;
         bdquotaant = NULL;
         bdchave = NULL;
     
         bdtotvaloracumulado = wauxtotacu;
         bdtotvaloracumuladoTerc = wauxtotacuter;
         bdvalacompensar = wvalacompgps;
         bdvalcompensado = wvalcompensado;
         bdvaloracumulado = wtotacu;
         bdvaloracuterceiros = wtotacuter;
     
         IF (bddescacumdet <> '') THEN
            BEGIN
              bddescacumdet = 'INSS Acum.: '||bddescacumdet||'.';
              bddescacum = 'INSS Acum.: '||bddescacum||'.';
            END
         bdtiporeg = 0;
       END
    ELSE
       BEGIN
         IF (wtipocontab = 2) THEN
            BEGIN
              bdtiporeg = 9;
              bdcodcol = wcodcol;
              bdcodter = wcodter;
            END
         ELSE
            bdtiporeg = 8;
       END

    IF ((prapenasgps = 1) OR (bdtiporeg = 0)) THEN
       SUSPEND;
    bddescacumdet = '';
    bddescacum = '';
  END
END^

/* Restore proc. body: VRHF_SP_GPS_CONTRATANTE */
ALTER PROCEDURE VRHF_SP_GPS_CONTRATANTE(PREMP INTEGER,
PRREF INTEGER,
PRTERC INTEGER,
PRTPCC INTEGER,
PRNRNF VARCHAR(15))
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(5000);
BEGIN

  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wSql = 'select sum(BDVALNF)';
  wSql = wSql || 'from vrhf_emp_tnfcont ';

  wSql = wSql || 'where bdcodemp = '||:premp;
  wSql = wSql || ' and BDREFNF = '||:prref;

  IF (:prnrnf <> '') THEN
    wsql = wsql || ' AND BDNOTAFISCAL = '||:prnrnf;

  IF (:prterc <> 0) THEN
    wsql = wsql || ' AND BDCODTER = '||:prterc;

  IF (:prtpcc <> 0) THEN
    wsql = wsql || ' AND BDCODTPCC = '||:prtpcc;

  FOR EXECUTE STATEMENT wsql
      INTO
        :BDVALOR
     DO
       BEGIN
         SUSPEND;
       END


  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);

END
^

/* Restore proc. body: VRHF_SP_GPS_FUNRURAL */
CREATE OR ALTER procedure VRHF_SP_GPS_FUNRURAL (
    PREMP integer,
    PRREF integer,
    PRNRNF varchar(15),
    PRTIPOEMISSAO integer,
    PRCODIMP integer)
returns (
    BDCODEMP integer,
    BDVALOR numeric(18,6),
    BDVALTERC numeric(18,6),
    BDVALORACU numeric(18,6),
    BDVALACUTERC numeric(18,6),
    BDDESCNOTAS varchar(5000),
    BDBASECALC numeric(18,6),
    BDVALRAT numeric(18,6))
as
declare variable WSQL varchar(5000);
declare variable WNF varchar(20);
declare variable WVALNF numeric(18,6);
declare variable WLISTANOTAS varchar(20000);
declare variable WBDTIPONF integer;
declare variable WPERCINSS numeric(18,6);
declare variable WPERCSENAR numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WPERCRAT2 numeric(18,6);
declare variable WTIPONFATU integer;
declare variable WVAUX numeric(18,6);
declare variable WTEMNFVENDAS smallint;
declare variable WVALNF2 numeric(18,6);
declare variable WPERCINSS2 numeric(18,6);
declare variable WPERCSENAR2 numeric(18,6);
declare variable WNF2 varchar(20);
declare variable WCNPJEMP DM_CNPJ_CPF;
declare variable WCGCTER DM_CNPJ_CPF;
declare variable WCPFPROD DM_CNPJ_CPF;
declare variable WPRODPF DM_BOOLEAN;
declare variable WCODAQUIRUR integer;
declare variable WENTIDADEPAA DM_BOOLEAN;
declare variable WVAINOTA smallint;
declare variable WCODTRIBRUR smallint;
BEGIN
  bdcodemp = premp;

  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wSql = 'select nf.BDVALNF, nf.BDPERCFPASNF, nf.BDPERCTERC, nf.BDPERCRAT, coalesce(nf.BDTIPONF, 0), nf.bdnotafiscal, '||
                'EMPCAD.BDCNPJEMP, TERC.BDCGCTER, TERC.BDCPFPROD, TERC.BDPRODPF, nf.BDCODAQUIRUR, EMPREF.BDENTIDADEPAA,Coalesce(EMPgps.BDCODTRIBRUR,TERC.BDCODTRIBRUR) ';
  wSql = wSql||'from VRHF_EMP_TNFPRODRURAL nf ';
  wsql = wsql||'left outer join TEMPRESAS EMPCAD on (EMPCAD.BDCODEMP = nf.BDCODEMP) ';
  wsql = wsql||'left outer join VW_TTERCEIRO TERC on (TERC.BDCODTER = nf.BDCODTER) ';
  wsql = wsql||'left outer join VW_TEMPRESAS_REF EMPREF on (EMPREF.BDCODEMP = nf.BDCODEMP) ';
  wsql = wsql||'left outer join (Select bdcodemp,max(bdrefemp)bdrefemp from VRHF_BASE_TEMPGPS group by bdcodemp) EMPGPSMAX on (EMPGPSMAX.BDCODEMP = nf.BDCODEMP) ';
  wsql = wsql||'left outer join VRHF_BASE_TEMPGPS EMPGPS on (EMPGPS.BDCODEMP = nf.BDCODEMP and EMPGPS.bdrefemp=EMPGPSMAX.bdrefemp) ';

  IF (prcodimp IS NOT NULL) THEN
     BEGIN
       wSql = wSql || 'join sp_emppresa_imp('||prcodimp||','||prref||',null) emp on (nf.bdcodemp = emp.bdcodemp) ';
       wSql = wSql || 'where emp.bdempimp = '||:premp;
     END
  ELSE
     BEGIN
       wSql = wSql || 'where nf.bdcodemp = '||:premp;
     END

  wSql = wSql || ' and nf.BDREFNF = '||:prref;

  IF (:prnrnf <> '') THEN
    wsql = wsql || ' AND nf.BDNOTAFISCAL = '''||:prnrnf||'''';

  IF (:prtipoemissao = 1) THEN
     wsql = wsql || ' AND coalesce(nf.BDTIPONF, 0) = 0';
  ELSE
     IF (:prtipoemissao = 2) THEN
        wsql = wsql || ' AND coalesce(nf.BDTIPONF, 0) = 1';


  wsql = wsql||' order by nf.BDTIPONF, nf.bdnotafiscal';

  wtiponfatu   = -1;
  bdvalor      = 0;
  bdvalterc    = 0;
  bdvalrat     = 0;
  bddescnotas  = '';
  bdbasecalc   = 0;
  wtemnfvendas = 0;

  FOR EXECUTE STATEMENT wsql
      INTO
        :wvalnf, :wpercinss, :wpercsenar, :wpercrat, :WBDTIPONF, :wnf,
        :wcnpjemp, :wcgcter, :wcpfprod, :wprodpf, :wcodaquirur, :wentidadepaa, :WCODTRIBRUR
     DO
       BEGIN
         wvainota = 0;
         if (coalesce(wbdtiponf, 0) = 1) then
            wvainota = 1;
         else
            begin
              /* Verifica se a empresa é CPF ou CAEPF */
              if ((strlen(:wcnpjemp) <= 14) or (substring(:wcnpjemp from 4 for 1) = '.')) then
                 wvainota = 1;
              /* Verifica empresa CNPJ */
              else
                 begin
                   /* Produtor rural CPF or CAEPF */
                   if ((strlen(:wcgcter) <= 14) or (substring(:wcgcter from 4 for 1) = '.')) then
                      wvainota = 1;
                   else
                   /* Produtor rural com CNPJ */
                   if (strlen(:wcgcter) >= 18 and substring(:wcgcter from 4 for 1) <> '.') then
                      begin
                        if (upper(coalesce(wprodpf, 'FALSE')) = 'TRUE' and strlen(trim(wcpfprod)) = 14) then
                           wvainota = 1;
                        else
                        if ((coalesce(wcodaquirur, 0) in (3, 6)) or (coalesce(wcodaquirur, 0) = 0 and upper(coalesce(wentidadepaa, 'FALSE')) = 'TRUE')) then
                           wvainota = 1;
                        else
                        if (coalesce(wcodaquirur, 0) = 0 and upper(coalesce(wentidadepaa, 'FALSE')) = 'FALSE') then
                           wvainota = 1;
                      end
                 end
            end

         if (wvainota = 1) then
            begin
              if (wtiponfatu = -1) then
                 wtiponfatu = wbdtiponf;
     
              if (wtiponfatu <> wbdtiponf) then
                 begin
                   if (coalesce(prtipoemissao, 0) in (0, 2) and wtiponfatu = 1) then
                      begin
                        wtemnfvendas = 1;
     
                        for select NF.BDVALNF, NF.BDINSS, NF.BDSENAR, NF.BDGILRAT, NF.BDNOTAFISCAL
                            from VRH_EMP_TCOMERCNFPRODRURAL NF
                            where BDCODEMP = :premp and BDREFNF = :prref
                        into :wvalnf2, :wpercinss2, :wpercsenar2, :wpercrat2, :wnf2
                        do
                          begin  

                            if (coalesce(WCODTRIBRUR,0)<>2) then
                               begin
                                 wvaux = wvalnf2 * wpercinss2 / 100;
                                 wvaux = coalesce(wvaux, 0);
                                 if (wvaux > 0) then
                                    wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
          
                                 BDVALOR = BDVALOR + wvaux;
          
     
                                 wvaux = wvalnf2 * wpercrat2 / 100;
                                 wvaux = coalesce(wvaux, 0);
                                 if (wvaux > 0) then
                                   wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
                                 BDVALRAT = BDVALRAT + wvaux;
                               end

                            wvaux = wvalnf2 * wpercsenar2 / 100;
                            wvaux = coalesce(wvaux, 0);
                            if (wvaux > 0) then
                               wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
     
                            BDVALTERC = BDVALTERC + wvaux;

                            BDBASECALC = BDBASECALC + wvalnf2;
     
                            if (BDDESCNOTAS <> '') then
                               BDDESCNOTAS = substring(BDDESCNOTAS||', ' from 1 for 5000);
     
                            BDDESCNOTAS = substring(BDDESCNOTAS||Trim(wnf2) from 1 for 5000);
                          end
                      end
     
                   /* busca valor acumulado */
                   SELECT SUM(x.bdvalacu),SUM(x.bdvalacuter) FROM VRHF_SP_ACU_GPS_FUNRURAL(:prcodimp,'bdcodemp = '||:premp,:prref, :wlistanotas) x
                   INTO bdvaloracu, bdvalacuterc;
     
                   if (coalesce(prcodimp, 0) <> 0) then
                      BDVALOR = BDVALOR + BDVALRAT;
     
                   suspend;
     
                   bdvalor     = 0;
                   bdvalterc   = 0;
                   bdvalrat    = 0;
                   bddescnotas = '';
                   bdbasecalc  = 0;
                   wlistanotas = '';
                   wtiponfatu  = wbdtiponf;
                 end
     
              wvaux = wvalnf * wpercinss / 100;
              wvaux = coalesce(wvaux, 0);
              if (wvaux > 0) then
                 wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
     
              bdvalor = bdvalor + wvaux;
     
              wvaux = wvalnf * wpercrat / 100;
              wvaux = coalesce(wvaux, 0);
              if (wvaux > 0) then
                 wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
     
              bdvalrat = bdvalrat + wvaux;
     
              wvaux = wvalnf * wpercsenar / 100;
              wvaux = coalesce(wvaux, 0);
              if (wvaux > 0) then
                 wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
     
              bdvalterc  = bdvalterc + wvaux;
              bdbasecalc = bdbasecalc + wvalnf;
     
              if (bddescnotas <> '') then
                 bddescnotas = substring(bddescnotas||', ' from 1 for 5000);
              bddescnotas = substring(bddescnotas||Trim(wnf) from 1 for 5000);
     
              if (wlistanotas <> '') then
                 wlistanotas = wlistanotas||' and ';
     
              wlistanotas = wlistanotas||'bdnotafiscal <> '''||wnf||'''';
            end
       END

  if (wtiponfatu <> -1) then
     begin
       if (coalesce(prtipoemissao, 0) in (0, 2) and wtiponfatu = 1) then
          begin
            wtemnfvendas = 1;

            for select NF.BDVALNF, NF.BDINSS, NF.BDSENAR, NF.BDGILRAT, NF.BDNOTAFISCAL
                from VRH_EMP_TCOMERCNFPRODRURAL nf
                where BDCODEMP = :premp and BDREFNF = :prref
            into :wvalnf2, :wpercinss2, :wpercsenar2, :wpercrat2, :wnf2
            do
              begin
                wvaux = wvalnf2 * wpercinss2 / 100;
                wvaux = coalesce(wvaux, 0);
                if (wvaux > 0) then
                   wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));

                BDVALOR = BDVALOR + wvaux;

                wvaux = wvalnf2 * wpercsenar2 / 100;
                wvaux = coalesce(wvaux, 0);
                if (wvaux > 0) then
                   wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));

                BDVALTERC = BDVALTERC + wvaux;

                wvaux = wvalnf2 * wpercrat2 / 100;
                wvaux = coalesce(wvaux, 0);
                if (wvaux > 0) then
                  wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
                BDVALRAT = BDVALRAT + wvaux;

                BDBASECALC = BDBASECALC + wvalnf2;

                if (BDDESCNOTAS <> '') then
                   BDDESCNOTAS = substring(BDDESCNOTAS||', ' from 1 for 5000);

                BDDESCNOTAS = substring(BDDESCNOTAS||Trim(wnf2) from 1 for 5000);
              end
          end

       /* busca valor acumulado */
       SELECT SUM(x.bdvalacu),SUM(x.bdvalacuter) FROM VRHF_SP_ACU_GPS_FUNRURAL(:prcodimp,'bdcodemp = '||:premp,:prref, :wlistanotas) x
       INTO bdvaloracu, bdvalacuterc;

       if (coalesce(prcodimp, 0) <> 0) then
          BDVALOR = BDVALOR + BDVALRAT;

       suspend;
     end


  if (coalesce(prtipoemissao, 0) in (0, 2) and wtemnfvendas = 0) then
     begin
       BDDESCNOTAS = '';
       for select NF.BDVALNF, NF.BDINSS, NF.BDSENAR, NF.BDGILRAT, NF.BDNOTAFISCAL, EMPGPS.BDCODTRIBRUR
           from VRH_EMP_TCOMERCNFPRODRURAL nf
           left outer join (Select bdcodemp,max(bdrefemp)bdrefemp from VRHF_BASE_TEMPGPS group by bdcodemp) EMPGPSMAX on (EMPGPSMAX.BDCODEMP = nf.BDCODEMP)
           left outer join VRHF_BASE_TEMPGPS EMPGPS on (EMPGPS.bdcodemp = EMPGPSMAX.BDCODEMP and EMPGPS.bdrefemp=EMPGPSMAX.bdrefemp)

           where nf.BDCODEMP = :premp and BDREFNF = :prref
       into :wvalnf2, :wpercinss2, :wpercsenar2, :wpercrat2, :wnf2, :wcodtribrur
       do
         begin
           wtemnfvendas = 1;
           if (Coalesce(wcodtribrur,0)<>2) then
              begin
                wvaux = wvalnf2 * wpercinss2 / 100;
                wvaux = coalesce(wvaux, 0);
                if (wvaux > 0) then
                   wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
     
                BDVALOR = BDVALOR + wvaux;
     
                wvaux = wvalnf2 * wpercrat2 / 100;
                wvaux = coalesce(wvaux, 0);
                if (wvaux > 0) then
                  wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
                BDVALRAT = BDVALRAT + wvaux;
     
                BDBASECALC = BDBASECALC + wvalnf2;
              end
           wvaux = wvalnf2 * wpercsenar2 / 100;
           wvaux = coalesce(wvaux, 0);
           if (wvaux > 0) then
              wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));

           BDVALTERC  = BDVALTERC + wvaux;

           if (BDDESCNOTAS <> '') then
              BDDESCNOTAS = substring(BDDESCNOTAS||', ' from 1 for 5000);

           BDDESCNOTAS = substring(BDDESCNOTAS||Trim(wnf2) from 1 for 5000);
         end

       if (wtemnfvendas = 1) then
          suspend;
     end

  EXECUTE PROCEDURE sp_seta_competencia(:prref, NULL, NULL);

END^

/* Restore proc. body: VRHF_SP_GPS_FUNRURAL_RESUMO */
create or alter procedure VRHF_SP_GPS_FUNRURAL_RESUMO (
    PREMP varchar(500),
    PRREF integer,
    PRNRNF varchar(15),
    PRTIPOEMISSAO integer,
    PRCODIMP integer)
returns (
    BDCODEMP integer,
    BDVALOR numeric(18,6),
    BDVALTERC numeric(18,6),
    BDVALORACU numeric(18,6),
    BDVALACUTERC numeric(18,6),
    BDDESCNOTAS varchar(10000),
    BDBASECALC numeric(18,6),
    BDVALRAT numeric(18,6))
as
declare variable WSQL2 varchar(5000);
declare variable WSQL varchar(5000);
declare variable WNF varchar(20);
declare variable WVALNF numeric(18,6);
declare variable WBDTIPONF integer;
declare variable WPERCINSS numeric(18,6);
declare variable WPERCSENAR numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WPERCRAT2 numeric(18,6);
declare variable WTIPONFATU integer;
declare variable WVAUX numeric(18,6);
declare variable WTEMNFVENDAS smallint;
declare variable WVALNF2 numeric(18,6);
declare variable WPERCINSS2 numeric(18,6);
declare variable WPERCSENAR2 numeric(18,6);
declare variable WNF2 varchar(20);
declare variable WCNPJEMP DM_CNPJ_CPF;
declare variable WCGCTER DM_CNPJ_CPF;
declare variable WCPFPROD DM_CNPJ_CPF;
declare variable WPRODPF DM_BOOLEAN;
declare variable WCODAQUIRUR integer;
declare variable WENTIDADEPAA DM_BOOLEAN;
declare variable WVAINOTA smallint;
declare variable WREFINIESOCIAL integer;
declare variable WGRUPOESOCIAL integer;
declare variable WVALORACU numeric(9,2);
declare variable WVALACUTERC numeric(9,2);
BEGIN
--  bdcodemp = premp;

  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wSql = 'select nf.BDCODEMP, nf.BDVALNF, nf.BDPERCFPASNF, nf.BDPERCTERC, nf.BDPERCRAT, coalesce(nf.BDTIPONF, 0), nf.bdnotafiscal, '||
                'EMPCAD.BDCNPJEMP, TERC.BDCGCTER, TERC.BDCPFPROD, TERC.BDPRODPF, nf.BDCODAQUIRUR, EMPREF.BDENTIDADEPAA ';
  wSql = wSql||'from VRHF_EMP_TNFPRODRURAL nf ';
  wsql = wsql||'left outer join TEMPRESAS EMPCAD on (EMPCAD.BDCODEMP = nf.BDCODEMP) ';
  wsql = wsql||'left outer join VW_TTERCEIRO TERC on (TERC.BDCODTER = nf.BDCODTER) ';
  wsql = wsql||'left outer join VW_TEMPRESAS_REF EMPREF on (EMPREF.BDCODEMP = nf.BDCODEMP) ';

  IF (prcodimp IS NOT NULL) THEN
     BEGIN
       wSql = wSql || 'join sp_emppresa_imp('||prcodimp||','||prref||',null) emp on (nf.bdcodemp = emp.bdcodemp) ';
--       wSql = wSql || 'where emp.bdempimp = '||:premp;
       wSql = wSql || 'where emp.'||:premp;
     END
  ELSE
     BEGIN
       wSql = wSql || 'where nf.'||:premp;
     END

  wSql = wSql || ' and nf.BDREFNF = '||:prref;

  IF (:prnrnf <> '') THEN
    wsql = wsql || ' AND nf.BDNOTAFISCAL = '''||:prnrnf||'''';

  IF (:prtipoemissao = 1) THEN
     wsql = wsql || ' AND coalesce(nf.BDTIPONF, 0) = 0';
  ELSE
     IF (:prtipoemissao = 2) THEN
        wsql = wsql || ' AND coalesce(nf.BDTIPONF, 0) = 1';


  wsql = wsql||' order by nf.BDTIPONF, nf.bdnotafiscal';

  wtiponfatu   = -1;
  bdvalor      = 0;
  bdvalterc    = 0;
  bdvalrat     = 0;
  bddescnotas  = '';
  bdbasecalc   = 0;
  wtemnfvendas = 0;
--  wlistanotas  = '';
  bdvaloracu   = 0;
  bdvalacuterc = 0;

  FOR EXECUTE STATEMENT wsql
      INTO
        :bdcodemp, :wvalnf, :wpercinss, :wpercsenar, :wpercrat, :WBDTIPONF, :wnf,
        :wcnpjemp, :wcgcter, :wcpfprod, :wprodpf, :wcodaquirur, :wentidadepaa
     DO
       BEGIN
         wvainota = 0;
         if (coalesce(wbdtiponf, 0) = 1) then
            wvainota = 1;
         else
            begin
              /* Verifica se a empresa é CPF ou CAEPF */
              if ((strlen(:wcnpjemp) <= 14) or (substring(:wcnpjemp from 4 for 1) = '.')) then
                 wvainota = 1;
              /* Verifica empresa CNPJ */
              else
                 begin
                   /* Produtor rural CPF or CAEPF */
                   if ((strlen(:wcgcter) <= 14) or (substring(:wcgcter from 4 for 1) = '.')) then
                      wvainota = 1;
                   else
                   /* Produtor rural com CNPJ */
                   if (strlen(:wcgcter) >= 18 and substring(:wcgcter from 4 for 1) <> '.') then
                      begin
                        if (upper(coalesce(wprodpf, 'FALSE')) = 'TRUE' and strlen(trim(wcpfprod)) = 14) then
                           wvainota = 1;
                        else
                        if ((coalesce(wcodaquirur, 0) in (3, 6)) or (coalesce(wcodaquirur, 0) = 0 and upper(coalesce(wentidadepaa, 'FALSE')) = 'TRUE')) then
                           wvainota = 1;
                        else
                        if (coalesce(wcodaquirur, 0) = 0 and upper(coalesce(wentidadepaa, 'FALSE')) = 'FALSE') then
                           begin
                             wrefiniesocial = 0;
                             wgrupoesocial  = null;
                             select first 1 BDGRUPO from VRH_ESOCIAL_TFASEAMENTO where BDCODEMP = :BDCODEMP into :wgrupoesocial;
                             wgrupoesocial  = coalesce(wgrupoesocial, 0);
                             if (wgrupoesocial = 1) then
                                wrefiniesocial = 201808;
                             else
                             if (wgrupoesocial = 2) then
                                wrefiniesocial = 201904;
                             else
                             if (wgrupoesocial = 3) then
                                wrefiniesocial = 201910;

                             if ((prref < wrefiniesocial) or (wgrupoesocial = 0)) then
                                wvainota = 1;
                           end
                      end
                 end
            end

         if (wvainota = 1) then
            begin
              if (wtiponfatu = -1) then
                 wtiponfatu = wbdtiponf;
     
              if (wtiponfatu <> wbdtiponf) then
                 begin
                   if (coalesce(prtipoemissao, 0) in (0, 2) and wtiponfatu = 1) then
                      begin
                        wtemnfvendas = 1;
--                        for select NF.BDVALNF, NF.BDINSS, NF.BDSENAR, NF.BDGILRAT, NF.BDNOTAFISCAL
--                            from VRH_EMP_TCOMERCNFPRODRURAL NF
--                            where BDCODEMP = :premp and BDREFNF = :prref
--                        into :wvalnf2, :wpercinss2, :wpercsenar2, wpercrat2, :wnf2
                        wsql2 = 'select NF.BDVALNF, NF.BDINSS, NF.BDSENAR, NF.BDGILRAT, NF.BDNOTAFISCAL '||
                                'from VRH_EMP_TCOMERCNFPRODRURAL NF '||
                                'where '||:premp||' and BDREFNF = '||:prref||' and (BDREFNF<=202305 or nf.BDTPCOMERC in (1,3,5))';
                        for execute statement wsql2 into :wvalnf2, :wpercinss2, :wpercsenar2, wpercrat2, :wnf2
                        do
                          begin
                            wvaux = wvalnf2 * wpercinss2 / 100;
                            wvaux = coalesce(wvaux, 0);
                            if (wvaux > 0) then
                               wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
     
                            BDVALOR = BDVALOR + wvaux;
     
                            wpercsenar2 = coalesce(wpercsenar2, 0);
                            wvaux = wvalnf2 * wpercsenar2 / 100;
                            wvaux = coalesce(wvaux, 0);
                            if (wvaux > 0) then
                               wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
     
                            BDVALTERC = BDVALTERC + wvaux;
                            BDBASECALC = BDBASECALC + wvalnf2;
     
                            if (BDDESCNOTAS <> '') then
                               BDDESCNOTAS = BDDESCNOTAS||', ';
     
                            BDDESCNOTAS = substring(BDDESCNOTAS||Trim(wnf2) from 1 for 7000);
                          end
                      end
     
                   /* busca valor acumulado */
--                   SELECT SUM(x.bdvalacu),SUM(x.bdvalacuter) FROM VRHF_SP_ACU_GPS_FUNRURAL(:prcodimp,'bdcodemp = '||:premp,:prref, :wlistanotas) x
                   SELECT SUM(x.bdvalacu),SUM(x.bdvalacuter) FROM VRHF_SP_ACU_GPS_FUNRURAL(:prcodimp, :premp, :prref, :wnf) x
                   INTO :wvaloracu, :wvalacuterc;
     
                   bdvaloracu   = coalesce(bdvaloracu + :wvaloracu, 0);
                   bdvalacuterc = coalesce(bdvalacuterc + :wvalacuterc, 0);
     
                   if (coalesce(prcodimp, 0) <> 0) then
                      BDVALOR = BDVALOR + BDVALRAT;
     
                   suspend;
     
                   bdvalor     = 0;
                   bdvalterc   = 0;
                   bdvalrat    = 0;
                   bddescnotas = '';
                   bdbasecalc  = 0;
--                   wlistanotas = '';
                   wtiponfatu  = wbdtiponf;
                   wvaloracu   = 0;
                   wvalacuterc = 0;
                 end
     
              wvaux = wvalnf * wpercinss / 100;
              wvaux = coalesce(wvaux, 0);
              if (wvaux > 0) then
                 wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
     
              bdvalor = bdvalor + wvaux;
     
              wvaux = wvalnf * wpercrat / 100;
              wvaux = coalesce(wvaux, 0);
              if (wvaux > 0) then
                 wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
     
              bdvalrat = bdvalrat + wvaux;
     

              wpercsenar = coalesce(wpercsenar, 0);
              wvaux = wvalnf * wpercsenar / 100;
              wvaux = coalesce(wvaux, 0);
              if (wvaux > 0) then
                 wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
     
              bdvalterc  = bdvalterc + wvaux;

              wvaux = wvalnf2 * wpercrat2 / 100;
              wvaux = coalesce(wvaux, 0);
              if (wvaux > 0) then
                wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
              BDVALRAT = BDVALRAT + wvaux;

              bdbasecalc = bdbasecalc + wvalnf;
     
              if (bddescnotas <> '') then
                 bddescnotas = bddescnotas||', ';
              bddescnotas = substring(bddescnotas||Trim(wnf) from 1 for 7000);
     
--              if (wlistanotas <> '') then /* 191150 LuizCovre 13/11/2023 essa lista montada dessa maneira estava estourando o limite da String */
--                 wlistanotas = wlistanotas||' and ';

--              wlistanotas = wlistanotas||'bdnotafiscal <> '''||wnf||'''';

--              if (wlistanotas = '') then
--                 wlistanotas = 'bdnotafiscal not in ('||wnf;
--              else
--                 wlistanotas = wlistanotas||','||wnf;

            end
       END

  --wlistanotas = wlistanotas||')';

  if (wtiponfatu = -1) then
     wtiponfatu = 1;

  if (wtiponfatu <> -1) then
     begin
       if (coalesce(prtipoemissao, 0) in (0, 2) and wtiponfatu = 1) then
          begin
            wtemnfvendas = 1;
--            for select NF.BDVALNF, NF.BDINSS, NF.BDSENAR, NF.BDGILRAT, NF.BDNOTAFISCAL
--                from VRH_EMP_TCOMERCNFPRODRURAL NF
--                where BDCODEMP = :premp and BDREFNF = :prref
            wsql2 = '';
            wsql2 = 'select NF.BDCODEMP, NF.BDVALNF, NF.BDINSS, NF.BDSENAR, NF.BDGILRAT, NF.BDNOTAFISCAL '||
                    'from VRH_EMP_TCOMERCNFPRODRURAL NF '||
                    'where '||:premp||' and BDREFNF = '||:prref||'  and (BDREFNF<=202305 or nf.BDTPCOMERC in (1,3,5))';
            for execute statement wsql2
            into :bdcodemp, :wvalnf2, :wpercinss2, :wpercsenar2, wpercrat2, :wnf2
            do
              begin
                wvaux = wvalnf2 * wpercinss2 / 100;
                wvaux = coalesce(wvaux, 0);
                if (wvaux > 0) then
                   wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));

                BDVALOR = BDVALOR + wvaux;

                wpercsenar2 = coalesce(wpercsenar2, 0);
                wvaux = wvalnf2 * wpercsenar2 / 100;
                wvaux = coalesce(wvaux, 0);
                if (wvaux > 0) then
                   wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
                BDVALTERC = BDVALTERC + wvaux;

                wvaux = wvalnf2 * wpercrat2 / 100;
                wvaux = coalesce(wvaux, 0);
                if (wvaux > 0) then
                  wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
                BDVALRAT = BDVALRAT + wvaux;

                BDBASECALC = BDBASECALC + wvalnf2;

                if (BDDESCNOTAS <> '') then
                   BDDESCNOTAS = BDDESCNOTAS||', ';

                BDDESCNOTAS = substring(BDDESCNOTAS||Trim(wnf2) from 1 for 7000);
              end
          end

       /* busca valor acumulado */
--       SELECT SUM(x.bdvalacu),SUM(x.bdvalacuter) FROM VRHF_SP_ACU_GPS_FUNRURAL(:prcodimp,'bdcodemp = '||:premp,:prref, :wlistanotas) x
--       INTO bdvaloracu, bdvalacuterc;

       if (coalesce(prcodimp, 0) <> 0) then
          BDVALOR = BDVALOR + BDVALRAT;

       suspend;
     end


  if (coalesce(prtipoemissao, 0) in (0, 2) and wtemnfvendas = 0) then
     begin
       BDDESCNOTAS = '';
--       for select NF.BDVALNF, NF.BDINSS, NF.BDSENAR, NF.BDGILRAT, NF.BDNOTAFISCAL
--           from VRH_EMP_TCOMERCNFPRODRURAL NF
--           where BDCODEMP = :premp and BDREFNF = :prref
       wsql2 = '';
       wsql2 = 'select NF.BDVALNF, NF.BDINSS, NF.BDSENAR, NF.BDGILRAT, NF.BDNOTAFISCAL '||
               'from VRH_EMP_TCOMERCNFPRODRURAL NF '||
               'where '||:premp||' and BDREFNF = '||:prref||' and (BDREFNF<=202305 or nf.BDTPCOMERC in (1,3,5))  ';
       for execute statement wsql2
       into :wvalnf2, :wpercinss2, :wpercsenar2, :wpercrat2, :wnf2
       do
         begin
           wtemnfvendas = 1;
           wvaux = wvalnf2 * wpercinss2 / 100;
           wvaux = coalesce(wvaux, 0);
           if (wvaux > 0) then
              wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));

           BDVALOR = BDVALOR + wvaux;

           wpercsenar2 = coalesce(wpercsenar2, 0);
           wvaux = wvalnf2 * wpercsenar2 / 100;
           wvaux = coalesce(wvaux, 0);
           if (wvaux > 0) then
              wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));

           BDVALTERC  = BDVALTERC + wvaux;

           wvaux = wvalnf2 * wpercrat2 / 100;
           wvaux = coalesce(wvaux, 0);
           if (wvaux > 0) then
             wvaux = CAST(wvaux - 0.005 AS NUMERIC(18,2));
           BDVALRAT = BDVALRAT + wvaux;

           BDBASECALC = BDBASECALC + wvalnf2;

           if (BDDESCNOTAS <> '') then
              BDDESCNOTAS = BDDESCNOTAS||', ';

           BDDESCNOTAS = substring(BDDESCNOTAS||Trim(wnf2) from 1 for 7000);
         end

       if (wtemnfvendas = 1) then
          suspend;
     end

  EXECUTE PROCEDURE sp_seta_competencia(:prref, NULL, NULL);

END^


/* Restore proc. body: SP_VRHF_FUNRURAL */
CREATE OR ALTER procedure SP_VRHF_FUNRURAL (
    PREMP varchar(25000),
    PRREFINI integer,
    PRREFFIM integer,
    PRFILIAIS smallint = 0,
    PRTIPONF integer = 0)
returns (
    BDCODEMP integer,
    BDTIPONF integer,
    BDREFNF integer,
    BDCODTER integer,
    BDCODAQUIRUR integer,
    BDDATAEMISSAONF date,
    BDCHAVENF integer,
    BDNRONF varchar(20),
    BDSERIENF varchar(5),
    BDVALNF numeric(18,6),
    BDPERCINSS numeric(18,6),
    BDPERCRAT numeric(18,6),
    BDPERCSENAR numeric(18,6),
    BDCNPJPRODRUR DM_CNPJ_CPF,
    BDDESCPRODRUR varchar(100),
    BDINSS numeric(18,6),
    BDRAT numeric(18,6),
    BDSENAR numeric(18,6),
    BDDESCAQUIRUR varchar(500),
    BDTOTALNF numeric(18,6))
as
declare variable WSQL varchar(32700);
declare variable WREFATU integer;
declare variable WTERCATU integer;
declare variable WVAINOTA smallint;
declare variable WCNPJEMP DM_CNPJ_CPF;
declare variable WCGCTER DM_CNPJ_CPF;
declare variable WPRODPF DM_BOOLEAN;
declare variable WCPFPROD DM_CNPJ_CPF;
declare variable WENTIDADEPAA DM_BOOLEAN;
begin
  if (coalesce(prtiponf, 0) in (0, 1, 3, 4)) then
     begin
       if (coalesce(prfiliais, 0) = 1) then
          wsql = 'select coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP), ';
       else
          wsql = 'select NF.BDCODEMP, ';

       wsql = wsql||'NF.BDREFNF, NF.BDCODAQUIRUR, NF.BDCODTER, NF.BDEMISSAONF, NF.BDCHAVE, NF.BDNOTAFISCAL, NF.BDSERIENF, NF.BDVALNF, NF.BDPERCFPASNF, NF.BDPERCTERC, '||
                     'NF.BDPERCRAT, AR.BDDESCAQUIRUR, EMP.BDCNPJEMP, T.BDCGCTER '||
              'from VRHF_EMP_TNFPRODRURAL NF ';

       wsql = wsql||'join TEMPRESAS EMP on (EMP.BDCODEMP = NF.BDCODEMP) ';
       wsql = wsql||'left outer join TTERCEIRO T on (T.BDCODTER = NF.BDCODTER) ';
       wsql = wsql||'left outer join VRH_ESOCIAL_TFASEAMENTO FASE on (FASE.BDCODEMP = NF.BDCODEMP) ';

       wsql = wsql||
              'left outer join TAQUISICAO_RURAL AR on (AR.BDCODAQUIRUR = NF.BDCODAQUIRUR) '||
              'where NF.BDREFNF between '||prrefini||' and '||prreffim||' and coalesce(NF.BDTIPONF, 0) = 0';
     
       -- 138592 - Raphael Teodoro - 11/05/2021 - Tipo NF "4" é o retorno do S-5011, que não traz NF "2 - Sobre a folha de pagamento"
       if (coalesce(prtiponf, 0) = 4) then
          wsql = wsql||' and ((select first 1 R.BDCODTRIBRUR'||
                             ' from TTERCEIRO_REF R'||
                             ' where (R.BDCODTER = T.BDCODTER)'||
                             ' order by BDCODTER desc, BDREFEMP desc) is distinct from 2) ';

       if (coalesce(premp, '') <> '') then
          begin
            wsql = wsql||' and ';
            if (coalesce(prfiliais, 0) = 1) then
               wsql = wsql||'(('||replace(upper(premp), 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(upper(premp), 'BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';
            else
               wsql = wsql||replace(upper(premp), 'BDCODEMP', 'NF.BDCODEMP');
          end
     
       wsql = wsql||' order by NF.BDREFNF, NF.BDCODTER ';
     
       wrefatu       = 0;
       wtercatu      = 0;
       BDDESCPRODRUR = null;
       BDCNPJPRODRUR = null;
       BDTIPONF      = 0;
     
       for execute statement wsql into :BDCODEMP, :BDREFNF, :BDCODAQUIRUR, :BDCODTER, :BDDATAEMISSAONF, :BDCHAVENF, :BDNRONF, :BDSERIENF, :BDVALNF, :BDPERCINSS,
                                       :BDPERCSENAR, :BDPERCRAT, :BDDESCAQUIRUR, :wcnpjemp, :wcgcter
       do
         begin
           wvainota = 0;
           if (coalesce(prtiponf, 0) in (3, 4)) then
              begin
                /* Verifica se a empresa é CPF ou CAEPF */
                if ((strlen(:wcnpjemp) <= 14) or (substring(:wcnpjemp from 4 for 1) = '.')) then
                   wvainota = 1;
                /* Verifica empresa CNPJ */
                else
                   begin
                     /* Produtor rural CPF or CAEPF */
                     if ((strlen(:wcgcter) <= 14) or (substring(:wcgcter from 4 for 1) = '.')) then
                        wvainota = 1;
                     else
                     /* Produtor rural com CNPJ */
                     if (strlen(:wcgcter) >= 18 and substring(:wcgcter from 4 for 1) <> '.') then
                        begin
                          select first 1 BDPRODPF, BDCPFPROD from TTERCEIRO_REF where BDCODTER = :BDCODTER and BDREFEMP <= :BDREFNF order by BDREFEMP DESC into :wprodpf, :wcpfprod;
                          select first 1 BDENTIDADEPAA from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :BDREFNF order by BDREFEMP DESC into :wentidadepaa;
                          if (upper(coalesce(wprodpf, 'FALSE')) = 'TRUE' and strlen(trim(wcpfprod)) = 14) then
                             wvainota = 1;
                          else
                          if ((coalesce(BDCODAQUIRUR, 0) in (3, 6)) or (coalesce(BDCODAQUIRUR, 0) = 0 and upper(coalesce(wentidadepaa, 'FALSE')) = 'TRUE')) then
                             wvainota = 1;
                        end
                   end
              end
           else
              wvainota = 1;

           if (wvainota = 1) then
              begin
                BDPERCSENAR = coalesce(BDPERCSENAR, 0);
                BDINSS = BDVALNF * BDPERCINSS / 100;
                BDINSS = coalesce(BDINSS, 0);
                if (BDINSS > 0) then
                   BDINSS = CAST(BDINSS - 0.005 AS NUMERIC(18,2));
          
                BDRAT = BDVALNF * BDPERCRAT / 100;
                BDRAT = coalesce(BDRAT, 0);
                if (BDRAT > 0) then
                   BDRAT = CAST(BDRAT - 0.005 AS NUMERIC(18,2));
          
                BDSENAR = BDVALNF * BDPERCSENAR / 100;
                BDSENAR = coalesce(BDSENAR, 0);

                if (BDSENAR > 0) then
                   BDSENAR = CAST(BDSENAR - 0.005 AS NUMERIC(18,2));
          
                BDTOTALNF = BDINSS + BDRAT + BDSENAR;
          
                if ((wrefatu <> BDREFNF) or (wtercatu <> BDCODTER)) then
                   begin
                     select first 1 BDNOMETER, BDCPFPROD from TTERCEIRO_REF where BDCODTER = :BDCODTER and BDREFEMP <= :BDREFNF order by BDREFEMP DESC into :BDDESCPRODRUR, :BDCNPJPRODRUR;
          
                     if (strlen(trim(coalesce(BDCNPJPRODRUR, ''))) < 14) then
                        select BDCGCTER from TTERCEIRO where BDCODTER = :BDCODTER into :BDCNPJPRODRUR;
          
                     wrefatu  = BDREFNF;
                     wtercatu = BDCODTER;
                   end
          
                suspend;
              end
         end
     end

  if (coalesce(prtiponf, 0) in (0, 2)) then
     begin
       if (coalesce(prfiliais, 0) = 1) then
          wsql = 'select coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP), ';
       else
          wsql = 'select NF.BDCODEMP, ';

       wsql = wsql||'NF.BDREFNF, NF.BDCODAQUIRUR, NF.BDCODTER, NF.BDEMISSAONF, NF.BDCHAVE, NF.BDNOTAFISCAL, NF.BDSERIENF, NF.BDVALNF, NF.BDPERCFPASNF, NF.BDPERCTERC, '||
                     'NF.BDPERCRAT, AR.BDDESCAQUIRUR '||
              'from VRHF_EMP_TNFPRODRURAL NF ';

       if (coalesce(prfiliais, 0) = 1) then
          wsql = wsql||'join TEMPRESAS EMP on (EMP.BDCODEMP = NF.BDCODEMP) ';

       wsql = wsql||
              'left outer join TAQUISICAO_RURAL AR on (AR.BDCODAQUIRUR = NF.BDCODAQUIRUR) '||
              'where NF.BDREFNF between '||prrefini||' and '||prreffim||' and coalesce(NF.BDTIPONF, 0) = 1';
     
       if (coalesce(premp, '') <> '') then
          begin
            wsql = wsql||' and ';
            if (coalesce(prfiliais, 0) = 1) then
               wsql = wsql||'(('||replace(upper(premp), 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(upper(premp), 'BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';
            else
               wsql = wsql||replace(upper(premp), 'BDCODEMP', 'NF.BDCODEMP');
          end
     
       wsql = wsql||' order by NF.BDREFNF, NF.BDCODTER ';
     
       wrefatu       = 0;
       wtercatu      = 0;
       BDDESCPRODRUR = null;
       BDCNPJPRODRUR = null;
       BDTIPONF      = 1;
     
       for execute statement wsql into :BDCODEMP, :BDREFNF, :BDCODAQUIRUR, :BDCODTER, :BDDATAEMISSAONF, :BDCHAVENF, :BDNRONF, :BDSERIENF, :BDVALNF, :BDPERCINSS,
                                       :BDPERCSENAR, :BDPERCRAT, :BDDESCAQUIRUR
       do
         begin
           BDPERCSENAR = coalesce(BDPERCSENAR, 0);
           BDINSS = BDVALNF * BDPERCINSS / 100;
           BDINSS = coalesce(BDINSS, 0);
           if (BDINSS > 0) then
              BDINSS = CAST(BDINSS - 0.005 AS NUMERIC(18,2));
     
           BDRAT = BDVALNF * BDPERCRAT / 100;
           BDRAT = coalesce(BDRAT, 0);
           if (BDRAT > 0) then
              BDRAT = CAST(BDRAT - 0.005 AS NUMERIC(18,2));
     
           BDSENAR = BDVALNF * BDPERCSENAR / 100;
           BDSENAR = coalesce(BDSENAR, 0);
           if (BDSENAR > 0) then
              BDSENAR = CAST(BDSENAR - 0.005 AS NUMERIC(18,2));
     
           BDTOTALNF = BDINSS + BDRAT + BDSENAR;
     
           if ((wrefatu <> BDREFNF) or (wtercatu <> BDCODTER)) then
              begin
                select first 1 BDNOMETER, BDCPFPROD from TTERCEIRO_REF where BDCODTER = :BDCODTER and BDREFEMP <= :BDREFNF order by BDREFEMP DESC into :BDDESCPRODRUR, :BDCNPJPRODRUR;
     
                if (strlen(trim(coalesce(BDCNPJPRODRUR, ''))) <= 14) then
                   select BDCGCTER from TTERCEIRO where BDCODTER = :BDCODTER into :BDCNPJPRODRUR;
     
                wrefatu  = BDREFNF;
                wtercatu = BDCODTER;
              end
     
           suspend;
         end

       if (coalesce(prfiliais, 0) = 1) then
          wsql = 'select coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP), ';
       else
          wsql = 'select NF.BDCODEMP, ';

       wsql = wsql||'NF.BDREFNF, NF.BDEMISSAONF, NF.BDCHAVE, NF.BDNOTAFISCAL, NF.BDSERIENF, NF.BDVALNF, NF.BDPERCFPASNF, NF.BDPERCTERC, NF.BDCNPJADQ, NF.BDTPCOMERC '||
              'from VRH_EMP_TCOMERCNFPRODRURAL NF ';

       if (coalesce(prfiliais, 0) = 1) then
          wsql = wsql||'join TEMPRESAS EMP on (EMP.BDCODEMP = NF.BDCODEMP) ';

       wsql = wsql||
              'where NF.BDREFNF between '||prrefini||' and '||prreffim;
     
       if (coalesce(premp, '') <> '') then
          begin
            wsql = wsql||' and ';
            if (coalesce(prfiliais, 0) = 1) then
               wsql = wsql||'(('||replace(upper(premp), 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(upper(premp), 'BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';
            else
               wsql = wsql||replace(upper(premp), 'BDCODEMP', 'NF.BDCODEMP');
          end
     
       wsql = wsql||' order by NF.BDREFNF';
     
       wrefatu       = 0;
       wtercatu      = 0;
       BDDESCPRODRUR = null;
       BDTIPONF      = 1;
       BDPERCRAT     = 0;
       BDRAT         = 0;
       BDCODTER      = null;
     
       for execute statement wsql into :BDCODEMP, :BDREFNF, :BDDATAEMISSAONF, :BDCHAVENF, :BDNRONF, :BDSERIENF, :BDVALNF, :BDPERCINSS,
                                       :BDPERCSENAR, :BDCNPJPRODRUR, :BDCODAQUIRUR
       do
         begin
           BDPERCSENAR = coalesce(BDPERCSENAR, 0);
           BDINSS = BDVALNF * BDPERCINSS / 100;
           BDINSS = coalesce(BDINSS, 0);
           if (BDINSS > 0) then
              BDINSS = CAST(BDINSS - 0.005 AS NUMERIC(18,2));
     
           BDSENAR = BDVALNF * BDPERCSENAR / 100;
           BDSENAR = coalesce(BDSENAR, 0);
           if (BDSENAR > 0) then
              BDSENAR = CAST(BDSENAR - 0.005 AS NUMERIC(18,2));
     
           BDTOTALNF = BDINSS + BDRAT + BDSENAR;
     
           if (coalesce(BDCODAQUIRUR, 0) = 1) then
              begin
                BDCODAQUIRUR  = 3;
                BDDESCAQUIRUR = 'Prod. Rural PF/Seg. Especial - Vendas a PJ (exceto Entidade inscrita no PAA) ou a Intermediário PF';
              end
           else
           if (coalesce(BDCODAQUIRUR, 0) = 2) then
              begin
                BDCODAQUIRUR  = 8;
                BDDESCAQUIRUR = 'Pessoa Física/Segurado Especial para Entidade inscrita no PAA';
              end
           else
           if (coalesce(BDCODAQUIRUR, 0) = 3) then
              begin
                BDCODAQUIRUR  = 9;
                BDDESCAQUIRUR = 'Mercado Externo';
              end
           else
              begin
                BDCODAQUIRUR  = 2;
                BDDESCAQUIRUR = 'Diretamente no varejo a consumidor final ou a outro Prod. Rural PF/Seg. Especial ou por PF não produtor rural';
              end

           suspend;
         end
     end
end^


/* Restore proc. body: VRHF_SP_GRCSCOLABORADOR */
ALTER PROCEDURE VRHF_SP_GRCSCOLABORADOR(PREMPRESA VARCHAR(9999),
PRCOLABORADOR VARCHAR(9999),
PRSINDICATO INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODSIND INTEGER,
BDCODCNAE INTEGER,
BDSIGLAUF VARCHAR(2),
BDNOMCID VARCHAR(40),
BDSIGLAUFSIND VARCHAR(2),
BDNOMCIDSIND VARCHAR(40),
BDCNPJSIND VARCHAR(18),
BDCEPSIND VARCHAR(9),
BDBAISIND DM_BDBAIRRO,
BDCOMPLSIND DM_BDCOMPENDERECO COLLATE WIN_PTBR,
BDNUMSIND DM_NUMEND,
BDENTSIND VARCHAR(40),
BDDESCSIND VARCHAR(60),
BDLOGRSIND DM_LOGRADOURO,
BDENDSIND DM_BDENDERECO,
BDAGENCIA VARCHAR(5),
BDCEDENTE VARCHAR(20),
BDCNPJ VARCHAR(20),
BDBAI DM_BDBAIRRO,
BDCEP VARCHAR(9),
BDCOMPL DM_BDCOMPENDERECO COLLATE WIN_PTBR,
BDNUM DM_NUMEND,
BDLOGR DM_LOGRADOURO,
BDEND VARCHAR(80),
BDNOM DM_BDNOMEMP,
BDCAPSOC NUMERIC(15,6))
 AS
DECLARE VARIABLE WGROUPBY VARCHAR(1000);
DECLARE VARIABLE WORDERBY VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(10000);
BEGIN
  IF (prreferencia IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, prultimodia);

  wSql = 'select '||
                 'TSINDTRAB.bdcodsintrab,'|| /*01*/
                 'TSINDTRAB.bddescsintrab,'|| /*02*/
                 'TSINDTRAB.BDCALCCODBARTRAB,'||--                 'TSINDTRAB.bdentsintrab,'|| /*03*/
                 'TSINDTRAB.BDLOGRSINTRAB,'||
                 'TSINDTRAB.bdendsintrab,'|| /*04*/
                 'TSINDTRAB.bdnrosintrab, '; /*05*/
  wSql = wSql || 'TSINDTRAB.bdcomplsintrab,'|| /*06*/
                  'TSINDTRAB.bdbaisintrab,'|| /*07*/
                  'TSINDTRAB.bdcepsintrab,'|| /*08*/
                  'TSINDTRAB.bdcnpjsintrab, '; /*09*/
  wSql = wSql || 'TCIDSIND.bdnomcid,'|| /*10*/
                 'TUFSIND.bdsiglauf, '; /*11*/
  wSql = wSql || 'TEMPREF.bdcodcnae,'|| /*12*/
                 'TCIDCOL.bdNOMCID,'|| /*13*/
                 'TUFCOL.bdsiglauf, '; /*14*/
  wsql = wsql || 'TBANCO.bdcodagban,'|| /*15    -   12821 - Camila - 18/11/2015 */
                 'TSINDTRAB.bdcodcedentetrab, '|| /*16*/
                 'TEMP.BDCNPJEMP, '; /*17*/

  wsql = wsql || 'tufcol.bdsiglauf, '||  /*18*/
                 'tcidcol.bdnomcid, '||   /*19*/
                 'TEMPREF.BDBAIEMP, '|| /*20*/
                 'TEMPREF.BDCEPEMP, '|| /*21*/
                 'TEMPREF.BDCOMPLEMP, '|| /*22*/
                 'TEMPREF.BDNUMEMP, '|| /*23*/
                 'TEMPREF.BDLOGREMP, '||
                 'TEMPREF.BDENDEMP, '|| /*24*/
                 'TEMPREF.BDNOMEMP, '; /*25*/

  wsql = wsql || 'TEMPGRCS.BDCAPSOCEMP ';  /*26*/

  wsql = wSql || ' from tempresas_ref TEMPREF ';

  wSql = wsql || ' left outer join tempresas TEMP on (TEMP.bdcodemp = TEMPREF.bdcodemp)';
  wSql = wsql || ' left outer join vrh_emp_tcolcon TCOLCON on (TCOLCON.bdcodemp = TCOLCON.bdcodemp)';
  wSql = wSql || ' left outer join VRH_EMP_TCOLCON_DOC TCOLCONDOC on (TCOLCONDOC.bdcodemp = TCOLCON.bdcodemp and'||
                 '                                                     TCOLCONDOC.bdcodcol = TCOLCON.bdcodcol) ';
  wSql = wSql || ' left outer join vw_vrh_emp_tcol_vinc TCOLVINC on (TCOLVINC.bdcodemp = TCOLCON.bdcodemp and'||
                 '                                                TCOLVINC.bdcodcol = TCOLCON.bdcodcol) ';
  wSql = wSql || ' left outer join vw_vrhf_base_tempgrcs TEMPGRCS on (TEMPGRCS.bdCODEMP = TEMPREF.bdcodemp) ';
  wsql = wSql || ' left outer join vrh_base_tsindtrab TSINDTRAB on (TSINDTRAB.bdcodsintrab = TCOLVINC.bdcodsintrab) ';
  -- 12821 - Camila - 18/11/2015: adicionado join com a tabela TBANCOS_AG
  wsql = wsql || ' left outer join tbancos_ag TBANCO on (TBANCO.bdcodban = TSINDTRAB.bdcodban and TBANCO.bdcodag = TSINDTRAB.bdcodag) ';
  wSql = wSql || ' left outer join tcidade tcidcol on (tCIDCOL.bdcodcid = TEMPREF.bdcodcid) ';
  wSql = wSql || ' left outer join tcidade tcidsind on (tCIDSIND.bdcodcid = TSINDTRAB.bdcodcid) ';
  wSql = wSql || ' left outer join tuf tufcol on (tufcol.bdcoduf = tcidcol.bdcoduf) ';
  wSql = wSql || ' left outer join tuf tufsind on (tufsind.bdcoduf = tcidsind.bdcoduf) ';
  wSql = wSql || ' left outer join vw_vrh_emp_tcolcon_vinc tcolcon_vinc on (tcolcon_vinc.bdcodemp = TCOLCON.bdcodemp and '||
                 ' tcolcon_vinc.bdcodcol = TCOLCON.bdcodcol) ';
  wwhere = '';

  IF (prempresa <> '') THEN
     wwhere = wwhere||prempresa||' ';

  IF (prcolaborador <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador||' ';
     END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';

  wwhere = wwhere||' TSINDTRAB.bdcodsintrab is not null ';

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';
    
  wwhere = wwhere||'TEMPREF.BDREFEMP in'||
          '('||
          ' select MAX(Y.BDREFEMP)'||
          ' from TEMPRESAS_REF Y'||
          ' where Y.BDCODEMP = TEMPREF.bdcodemp and'||
          '       CAST(Y.BDREFEMP as VARCHAR(6)) <='||
          '          (select TRIM(rdb$get_context('''||'USER_SESSION'||''', '''||'W_ANOMES'||'''))'||
          '           from rdb$database'||
          '          )'||
          ' group by Y.BDCODEMP'||
          ')'||' ';


  IF (prsindicato > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere||'TCOLVINC.bdCODSINTRAB = '||prsindicato||' ';
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wgroupby = '';

  worderby = '';
  wgroupby =     'group by TSINDTRAB.bdcodsintrab,'|| /*01*/
                 'TSINDTRAB.bddescsintrab,'|| /*02*/
                 'TSINDTRAB.BDCALCCODBARTRAB,'||--                 'TSINDTRAB.bdentsintrab,'|| /*03*/
                 'TSINDTRAB.BDLOGRSINTRAB,'||
                 'TSINDTRAB.bdendsintrab,'|| /*04*/
                 'TSINDTRAB.bdnrosintrab, '; /*05*/
  wgroupby = wgroupby || 'TSINDTRAB.bdcomplsintrab,'|| /*06*/
                  'TSINDTRAB.bdbaisintrab,'|| /*07*/
                  'TSINDTRAB.bdcepsintrab,'|| /*08*/
                  'TSINDTRAB.bdcnpjsintrab, '; /*09*/
  wgroupby = wgroupby || 'TCIDSIND.bdnomcid,'|| /*10*/
                 'TUFSIND.bdsiglauf, '; /*11*/
  wgroupby = wgroupby || 'TEMPREF.bdcodcnae,'|| /*12*/
                 'TCIDCOL.bdNOMCID,'|| /*13*/
                 'TUFCOL.bdsiglauf, '; /*14*/
  wgroupby = wgroupby || 'TBANCO.bdcodagban,'|| /*15     -   12821 - Camila - 18/11/2015 */
                 'TSINDTRAB.bdcodcedentetrab, '|| /*16*/
                 'TEMP.BDCNPJEMP, '; /*17*/

  wgroupby = wgroupby || 'tufcol.bdsiglauf, '||  /*18*/
                 'tcidcol.bdnomcid, '||   /*19*/
                 'TEMPREF.BDBAIEMP, '|| /*20*/
                 'TEMPREF.BDCEPEMP, '|| /*21*/
                 'TEMPREF.BDCOMPLEMP, '|| /*22*/
                 'TEMPREF.BDNUMEMP, '|| /*23*/
                 'TEMPREF.BDLOGREMP, '||
                 'TEMPREF.BDENDEMP, '|| /*24*/
                 'TEMPREF.BDNOMEMP, '; /*25*/

  wgroupby = wgroupby || 'TEMPGRCS.BDCAPSOCEMP ';  /*26*/

  wsql = wsql||wwhere||wgroupby||worderby;

  FOR EXECUTE STATEMENT wsql
      INTO :bdcodsind, /*01*/
           :bddescsind, /*02*/
           :bdentsind, /*03*/
           :bdlogrsind,
           :bdendsind, /*04*/
           :bdnumsind, /*05*/
           :bdcomplsind, /*06*/
           :bdbaisind, /*07*/
           :bdcepsind, /*08*/
           :bdcnpjsind, /*09*/
           :bdnomcidsind, /*10*/
           :bdsiglaufsind, /*11*/
           :bdcodcnae, /*12*/
           :bdnomcid, /*13*/
           :bdsiglauf, /*14*/
           :bdagencia, /*15*/
           :bdcedente, /*16*/
           :bdCNPJ, /*17*/
           :bdsiglauf, /*18*/
           :bdnomcid, /*19*/
           :bdbai, /*20*/
           :bdcep, /*21*/
           :bdcompl, /*22*/
           :bdnum, /*23*/
           :bdlogr,
           :bdend, /*24*/
           :bdnom, /*25*/
           :bdcapsoc /*26*/ DO
      BEGIN
        SUSPEND;
      END
END
^

/* Restore proc. body: VRHF_SP_GRCSEMPRESA */
ALTER PROCEDURE VRHF_SP_GRCSEMPRESA(PRSINDICATO INTEGER,
PRREFEMP INTEGER,
PRCODEMP VARCHAR(10000),
PRULTIMODIA DATE)
 RETURNS(BDCODCNAE INTEGER,
BDVALORDOC NUMERIC(15,2),
BDSIGLAUF VARCHAR(2),
BDNOMCID VARCHAR(40),
BDBAI DM_BDBAIRRO,
BDCEP VARCHAR(9),
BDCOMPL DM_BDCOMPENDERECO,
BDNUM DM_NUMEND,
BDEND DM_BDENDERECO,
BDCNPJ VARCHAR(18),
BDNOM DM_BDNOMEMP,
BDSIGLAUFSIND VARCHAR(2),
BDNOMCIDSIND VARCHAR(40),
BDCNPJSIND VARCHAR(18),
BDCEPSIND VARCHAR(9),
BDBAISIND DM_BDBAIRRO,
BDCOMPLSIND DM_BDCOMPENDERECO,
BDNUMSIND DM_NUMEND,
BDENTSIND VARCHAR(20),
BDDESCSIND VARCHAR(60),
BDENDSIND DM_BDENDERECO,
BDCAPSOC NUMERIC(15,2),
BDTIPOEMP CHAR,
BDTIPOCOL CHAR,
BDAGENCIA VARCHAR(5),
BDCEDENTE VARCHAR(20),
BDSALBASE NUMERIC(15,2),
BDTOTCOLAPU INTEGER,
BDTOTCOLEMP INTEGER,
BDTOTREMU NUMERIC(15,2),
BDLOGRSIND DM_LOGRADOURO,
BDLOGR DM_LOGRADOURO)
 AS
DECLARE VARIABLE WORDERBY VARCHAR(10000);
DECLARE VARIABLE WWHERE VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(30000);
BEGIN
  bdtotcolapu = 0;
  bdtotcolemp = 0;
  bdtotremu = 0;

  IF (prrefemp IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prrefemp, NULL, prultimodia);

  wSql = 'select TSINDPAT.bddescsinpat, TSINDPAT.BDCALCCODBARRASINPAT, TSINDPAT.bdendsinpat, TSINDPAT.bdnumsinpat, ';
  wSql =  wSql || 'TSINDPAT.bdcomplsinpat, TSINDPAT.bdbaisinpat, TSINDPAT.bdcepsinpat, TSINDPAT.bdcnpjsinpat, ';
  wSql =  wSql || 'TCIDSIND.bdnomcid, TUFSIND.bdsiglauf, TEMPREF.bdNOMEMP, TEMP.bdCNPJEMP, ';
  wSql =  wSql || 'TEMPREF.bdENDEMP, TEMPREF.bdnumemp, TEMPREF.bdcomplemp, TEMPREF.bdcepemp, TEMPREF.bdbaiemp, ';
  wSql =  wSql || 'TEMPREF.bdcodcnae, TCIDEMP.bdNOMCID, TUFEMP.bdSIGLAUF, TEMPGRCS.BDCAPSOCEMP, ';
  wSql =  wSql || '(TEMPGRCS.BDCAPSOCEMP * (TCONTRSINDFAIX.bdaliqsind / 100)) + TCONTRSINDFAIX.bdparcadicsind bdVALORDOC ';
  wsql = wsql || ', '''||'X'||''' as bdtipoemp, ';
  wSql = wSql || 'TBANCO.bdcodagban, TSINDPAT.bdcodcedentesinpat, ';  -- 12821 - Camila - 18/11/2015
  wSql = wSql || 'tempref.BDLOGREMP, TSINDPAT.BDLOGRESINPAT ';

  wSql = wSql || 'from tempresas_ref TEMPREF ';
  wSql = wSql || 'left outer join TEMPRESAS TEMP on (TEMP.bdcodemp = TEMPREF.bdcodemp) ';
  wSql = wSql || 'left outer join vw_vrhf_base_tempgrcs TEMPGRCS on (TEMPGRCS.bdCODEMP = TEMPREF.bdcodemp) ';
  wSql = wSql || 'left outer join vrhf_base_tsindpatronal TSINDPAT on (TSINDPAT.bdcodsinpat = TEMPGRCS.bdcodsinpat) ';
  -- 12821 - Camila - 18/11/2015
  wsql = wSql || 'left outer join tbancos_ag TBANCO on (TBANCO.bdcodban = TSINDPAT.bdcodban and TBANCO.bdcodag = TSINDPAT.bdcodag) ';
  wSql = wSql || 'left outer join vrhf_tabelas_tcontrsindfaix TCONTRSINDFAIX on ';
  wSql = wSql || '(TCONTRSINDFAIX.bdrefcontrsind = TEMPREF.bdREFEMP and TCONTRSINDFAIX.bdcodcontrsind = TSINDPAT.bdcodcontrsind and ';
  wSql = wSql || 'TCONTRSINDFAIX.bdclainisind <= TEMPGRCS.bdcapsocemp and TCONTRSINDFAIX.bdclafimsind >= TEMPGRCS.BDCAPSOCEMP) ';
  wSql = wSql || 'left outer join tcidade tcidemp on (tCIDEMP.bdcodcid = TEMPREF.bdcodcid) ';
  wSql = wSql || 'left outer join tcidade tcidsind on (tCIDSIND.bdcodcid = TSINDPAT.bdcodcid) ';
  wSql = wSql || 'left outer join tuf tufemp on (tufemp.bdcoduf = tcidemp.bdcoduf) ';
  wSql = wSql || 'left outer join tuf tufsind on (tufsind.bdcoduf = tcidsind.bdcoduf) ';

  wwhere = '';

  IF (prcodemp <> '') THEN
     wwhere = wwhere||prcodemp||' ';

  IF (prSindicato > 0) THEN
     BEGIN
         IF (wwhere <> '') THEN
            wwhere = wwhere||' and ';
         wWhere = wWhere||'TEMPGRCS.bdcodsinpat = '||prsindicato||' ';
     END

  IF (wwhere <> '') THEN
      wwhere = wwhere||' and ';

  wwhere = wwhere||'TEMPREF.BDREFEMP in
          (
           select MAX(Y.BDREFEMP)
           from TEMPRESAS_REF Y
           where Y.BDCODEMP = TEMPREF.bdcodemp and
                 CAST(Y.BDREFEMP as VARCHAR(6)) <=
                     (select TRIM(rdb$get_context('''||'USER_SESSION'||''', '''||'W_ANOMES'||'''))
                      from rdb$database
                     )
            group by Y.BDCODEMP
           )'||' ';

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wOrderBy = '';

  wsql = wsql||wwhere||worderby;

  FOR EXECUTE STATEMENT wsql
      INTO :bddescsind,
           :bdentsind,
           :bdendsind,
           :bdnumsind,
           :bdcomplsind,
           :bdbaisind,
           :bdcepsind,
           :bdcnpjsind,
           :bdnomcidsind,
           :bdsiglaufsind,
           :bdnom,
           :bdcnpj,
           :bdend,
           :bdnum,
           :bdcompl,
           :bdcep,
           :bdbai,
           :bdcodcnae,
           :bdnomcid,
           :bdsiglauf,
           :bdcapsoc,
           :bdvalordoc,
           :bdtipoemp,
           :bdagencia,
           :bdcedente,
           :bdlogr,
           :BDLOGRSIND DO
      BEGIN
        SUSPEND;
      END
END
^

/* Restore proc. body: VRHF_SP_HIST_ACUMU_GPS */
create or alter procedure VRHF_SP_HIST_ACUMU_GPS (
    PRWHERECHAVE varchar(3000))
returns (
    BDCODEMP integer,
    BDCHAVEDARF integer,
    BDCODIMP integer,
    BDCODPERIODO integer,
    BDORDEM integer,
    BDREFERENCIA integer,
    BDQUOTA integer,
    BDVALCAMPO6 numeric(15,6),
    BDVALCAMPO9 numeric(15,6),
    BDCHAVEDARFANT integer)
as
declare variable WSQLAUX varchar(3000);
BEGIN
  /* Procedure Text */
/*  prwherechave = 'x.bdcodemp = 3 and '||
                 'x.bdcodimp = 9053 and '||
                 'x.bdreferencia = 201004 and '||
                 'x.bdordem = 2 and '||
                 'x.BDCODPERIODO = 7 and '||
                 'x.BDQUOTA = 0 ';*/

  wsqlaux = ' select x.bdcodemp ,'||
            'x.bdcodimp ,'||
            'x.BDCHAVEDARF ,'||
            'x.bdcodperiodo ,'||
            'x.bdordem ,'||
            'x.bdreferencia ,'||
            'x.bdquota ,'||
            'coalesce(k.BDVALORACU,0) ,'||
            'coalesce(k.BDVALORACUOUTENT,0) '||
            ' from tdarfpadrao x'||
            ' join timposto imp on (x.bdcodimp = imp.bdcodimp and (coalesce(x.bdvalor,0)+coalesce(x.bdvlroutentidade,0) < imp.bdlimiteisencao)) '||
            ' left outer join (select a.bdcodemp,a.bdchavedarf,sum(a.BDVALORACU) BDVALORACU, sum(a.BDVALORACUOUTENT) BDVALORACUOUTENT'||
            '                  from TRELACAO_ACUMULADO a'||
            '                  join tdarfpadrao x on (x.bdchavedarf = a.bdchavedarf and x.bdcodemp = a.bdcodemp)'||
            '                  where '||prwherechave||
            '                  group by a.bdcodemp,a.bdchavedarf) k on (k.bdcodemp = x.bdcodemp and k.bdchavedarf = x.bdchavedarf)'||
            ' where ';

  wsqlaux = wsqlaux||prwherechave;
  BDCHAVEDARFANT = null;

  FOR EXECUTE STATEMENT wsqlaux INTO
    :bdcodemp ,
    :bdcodimp ,
    :BDCHAVEDARF,
    :bdcodperiodo ,
    :bdordem ,
    :bdreferencia ,
    :bdquota ,
    :bdvalcampo6 ,
    :bdvalcampo9
  DO
    BEGIN
      SUSPEND;
    END

  wsqlaux = ' select x.bdcodemp ,'||
            'x.bdcodimp ,'||
            'a.BDCHAVEDARF ,'||
            'x.bdcodperiodo ,'||
            'x.bdordem ,'||
            'a.bdreferencia ,'||
            'x.bdquota ,'||
            'coalesce(y.bdvaloracu,0) ,'||
            'coalesce(y.bdvaloracuoutent,0), '||
            'y.bdchavedarfant '||
            ' from TRELACAO_ACUMULADO y'||
            ' join TDARFPADRAO x on (x.bdcodemp = y.bdcodemp and x.bdchavedarf = y.BDCHAVEDARF) '||
            ' join TDARFPADRAO a on (A.bdcodemp = y.bdcodemp and A.bdchavedarf = y.bdchavedarfant) '||
            ' join timposto imp on (x.bdcodimp = imp.bdcodimp and (coalesce(x.bdvalor,0)+coalesce(x.bdvlroutentidade,0) < imp.bdlimiteisencao)) '||
            ' where ';

  wsqlaux = wsqlaux||prwherechave;

  FOR EXECUTE STATEMENT wsqlaux INTO
    :bdcodemp ,
    :bdcodimp ,
    :bdchavedarf,
    :bdcodperiodo ,
    :bdordem ,
    :bdreferencia ,
    :bdquota ,
    :bdvalcampo6 ,
    :bdvalcampo9,
    :bdchavedarfant
  DO
    BEGIN
      SUSPEND;
    END
END^

create or alter procedure VRHF_SP_HIST_ACUMU_GPS2 (
    PRWHERECHAVE varchar(3000))
returns (
    BDCODEMP integer,
    BDCHAVEDARF integer,
    BDCODIMP integer,
    BDCODPERIODO integer,
    BDORDEM integer,
    BDREFERENCIA integer,
    BDQUOTA integer,
    BDVALCAMPO6 numeric(15,6),
    BDVALCAMPO9 numeric(15,6),
    BDCHAVEDARFANT integer)
as
declare variable WSQLAUX varchar(3000);
declare variable WLIM numeric(18,6);
declare variable WSQLANT varchar(3000);
declare variable WN1 numeric(18,2);
declare variable WN2 numeric(18,2);
declare variable WCOMPENSACAO numeric(18,2);
BEGIN
  wsqlaux = ' select ' ||
                    'x.bdcodemp ,'||
                    'x.bdcodimp ,'||
                    'x.BDCHAVEDARF ,'||
                    'x.bdcodperiodo ,'||
                    'x.bdordem ,'||
                    'x.bdreferencia ,'||
                    'x.bdquota ,'||
                    'coalesce(X.bdvalor, 0) ,'||
                    'coalesce(X.bdvlroutentidade, 0), '||
                    'IMP.BDLIMITEISENCAO, '||
                    'X.BDCOMPENSACAO '||
            ' from tdarfpadrao x'||
            ' join timposto imp on (x.bdcodimp = imp.bdcodimp) '||
            ' where ';

  wsqlaux = wsqlaux||prwherechave;
  wsqlaux = wsqlaux||' order by X.BDREFPAG DESC, X.BDREFERENCIA DESC, X.BDORDEM DESC ';

  BDCHAVEDARFANT = null;

  FOR EXECUTE STATEMENT wsqlaux INTO
    :bdcodemp ,
    :bdcodimp ,
    :BDCHAVEDARF,
    :bdcodperiodo ,
    :bdordem ,
    :bdreferencia ,
    :bdquota ,
    :bdvalcampo6 ,
    :bdvalcampo9,
    :wlim,
    :wcompensacao
  DO
    BEGIN
      if (bdvalcampo6 + bdvalcampo9 = 0 and wcompensacao >= 0) then
        begin
          bdvalcampo6 = bdvalcampo6;
          bdvalcampo9 = bdvalcampo9;

         BREAK;
         exit;
        end

      if (bdvalcampo6 + bdvalcampo9 < wlim ) then
         begin
           wn1 = null;
           wn2 = null;
           wsqlant = 'select coalesce(X.bdvalor, 0), coalesce(X.bdvlroutentidade, 0) from TRELACAO_ACUMULADO Y '||
                     'join TDARFPADRAO X on (X.BDCODEMP = Y.BDCODEMP and X.BDCHAVEDARF = Y.BDCHAVEDARFANT) '||
                     'where Y.BDCODEMP = '||BDCODEMP||' and Y.BDCHAVEDARF = '||BDCHAVEDARF;

           for execute statement wsqlant into :wn1, :wn2 do
             begin
               if (bdvalcampo6 > 0) then
                 bdvalcampo6 = bdvalcampo6 - wn1;
               if (bdvalcampo9 > 0) then
                 bdvalcampo9 = bdvalcampo9 - wn2;
             end

           if (wn1 is null and wn2 is null) then
              begin
                wsqlant = 'select first 1 coalesce(X.bdvalor, 0), coalesce(X.bdvlroutentidade, 0) from TDARFPADRAO X '||
                          'where X.BDCODEMP = '||BDCODEMP||' and X.BDCHAVEDARF < '||BDCHAVEDARF||' and X.BDCODIMP = '||BDCODIMP||' order by X.BDCHAVEDARF DESC, X.BDREFERENCIA DESC ';
       
                for execute statement wsqlant into :wn1, :wn2 do
                  begin
                    if (wn1 + wn2 < wlim ) then
                       begin
                         if (bdvalcampo6 > 0) then
                           bdvalcampo6 = bdvalcampo6 - wn1;
                         if (bdvalcampo9 > 0) then
                           bdvalcampo9 = bdvalcampo9 - wn2;
                       end
                  end
              end

           SUSPEND;
         end
      else
         BREAK;
    END
END
^

/* Restore proc. body: VRHF_SP_INS_VERBASEMP */
CREATE OR ALTER PROCEDURE VRHF_SP_INS_VERBASEMP(PREMP INTEGER)
 AS
BEGIN
/*
  insert into vrhf_emp_tverbaemp(
              BDCODEMP, BDCODVERMEN, BDCODVERDIA, BDCODVERHOR, BDCODVERHORESP, BDCODVERPRO,
              BDCODVERPROFG, BDCODVEREST, BDCODVERAPO, BDCODVERTRAAUT, BDCODVERDOMFG, BDCODVERDOMSFG,
              BDCODVERAUT, BDCODVERCOM, BDCODVERSEM, BDCODVERSEMPRO, BDCODVERSEMAUT, BDCODVERPLR,
              BDCODVERINS, BDCODVERPER, BDCODVERNOT, BDCODVERDSRHE, BDCODVERDSRSAL, BDCODVERDSRRV,
              BDCODVERVT, BDCODVERVR)
              values
              (:premp, 5, 6, 7, 45, 35, null, 20, 10, 9401, 25, 26, 30, 311, 96, 97, 98, 991, 101,
              116, 131, 543, 541, 542, 201, 202);
  suspend;
*/
END
^

/* Restore proc. body: VRHF_SP_OUTRASINF_CALC */
ALTER PROCEDURE VRHF_SP_OUTRASINF_CALC(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDDESCMEN VARCHAR(15),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDNOMAG VARCHAR(40),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDSEXOCOL INTEGER,
BDEMAILCOL VARCHAR(200),
BDDATANASCCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDDEFFISICOCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE,
BDALVARACOL VARCHAR(5),
BDNOMCOL VARCHAR(70))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WCODUSU INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prRef, NULL, NULL);

  FOR SELECT BDCODUSU FROM sp_get_usuario
  INTO
    wcodusu
  DO

  wsql = 'select CC_REF.BDCODEMP, '||
                'CC_REF.BDCODCOL, '||
                'CC_REF.BDCODCLA, '||
                'CLASSE.BDDESCCLA, ' ||
                'CC_REF.BDGRUPOCLA, '||
                'CC_REF.BDCODMEN, '||
                'MENSAG.BDDESCMEN, '||
                'CC_REF.BDCODSINTRAB, '||
                'SINTRAB.BDDESCSINTRAB, '||
                'CC_REF.BDCODBAN, '||
                'BANCO.BDNOMBAN, '||
                'CC_REF.BDCODAG, '||
                'AGEN.BDNOMAG, '||
                'CC_REF.BDCTADEPCOL, '||
                'CC_REF.BDDIGCTADEPCOL, '||
                'CC_REF.BDTIPOCTACOL, '||
                'CC_REF.BDMODOPAGTOCOL, '||
                'CC_REF.BDCARTAOSALCOL, '||
                'CC_REF.BDFORMAPAGTOCOL, '||
                'CC_REF.BDNRODEPIRCOL, '||
                'CC_REF.BDBASEIRRFADCOL, '||
                'CC_REF.BDVALORPREVPRIVNCOL, '||
                'CC_REF.BDVALORPREVPRIV13COL, '||
                'CC_REF.BDDATAOPCAOFGTSCOL, '||
                'CC_REF.BDCTAFGTSCOL, '||
                'CC_REF.BDCATEGORIACOL, '||
                'CC_REF.BDPERCFGTSCOL, '||
                'CC_REF.BDOCORRENCIACOL, '||
                'CC_REF.BDPERCRATCOL, '||
                'CC_REF.BDPERCDESCFPASCOL, '||
                'CC_REF.BDBASEINSSNCOL, '||
                'CC_REF.BDVALORINSSNCOL, '||
                'CC_REF.BDBASEIRRFNCOL, '||
                'CC_REF.BDVALORIRRFNCOL, '||
                'CC_REF.BDBASEINSS13COL, '||
                'CC_REF.BDVALORINSS13COL, '||
                'CC_REF.BDBASEIRRF13COL, '||
                'CC_REF.BDVALORIRRF13COL, '||
                'CC_REF.BDTIPOCOL, '||
                'CC_REF.BDHORASMENSAISCOL, '||
                'CC_REF.BDHORASSEMANAISCOL, '||
                'CC_REF.BDHORASDIARIASCOL, '||
                'CC_REF.BDPERCINSALUBCOL, '||
                'CC_REF.BDINCIDINSALUBCOL, '||
                'CC_REF.BDPERCPERCULCOL, '||
                'CC_REF.BDINCIDPERICULCOL, '||
                'CC_REF.BDPERCNOTURNOCOL, '||
                'CC_REF.BDINCIDNOTURNOCOL, '||
                'CC_REF.BDNRODEPSALFAMCOL, '||
                'CC_REF.BDIGNORAFALTASFERCOL, '||
                'CC_REF.BDCALCADIANTACOL, '||
                'CC_REF.BDNAOARREDONDARCOL, '||
                'CC_REF.BDIMPETIQUETACOL, '||
                'CC_REF.BDCALCDSRRVCOL, '||
                'CC_REF.BDCALCDSRHECOL, '||
                'CC_REF.BDCALCDSRSALCOL, '||
                'CC_REF.BDCALCVALTRANSCOL, '||
                'CC_REF.BDCALCVALREFCOL, '||
                'CC_REF.BDCODGPS, '||
                'CC_REF.BDDESCINSSDOIRCOL, '||
                'COL.BDSEXOCOL, '||
                'COL.BDEMAILCOL, '||
                'COL.BDDATANASCCOL, '||
                'CC_REF.BDGRAUINSTCOL, '||
                'CC_REF.BDESTCIVCOL, '||
                'COL.BDDATAADMCOL, '||
                'COL.BDDATAADICCOL, '||
                'COL.BDCPFCOL, '||
                'COL.BDPISCOL, '||
                'COL.BDRESERVISTACOL, '||
                'COL.BDCTPSCOL, '||
                'COL.BDSERIECTPSCOL, '||
                'COL.BDDSERIECTPSCOL, '||
                'COL.BDCNHCOL, '||
                'COL.BDVENCCNHCOL, '||
                'COL.BDDEFFISICOCOL, '||
                'COL.BDDATAFIMPRAZO1COL, '||
                'COL.BDDATAFIMPRAZO2COL, '||
                'COL.BDALVARACOL, '||
                'COL.BDNOMCOL '||
         'from VW_COLABORADORES_REF_ATUAL CC_REF '||
         'left outer join VW_COLABORADORES COL '||
           'on (COL.BDCODEMP = CC_REF.BDCODEMP and COL.BDCODCOL = CC_REF.BDCODCOL) '||
         'left outer join VRH_BASE_TCLASSE CLASSE '||
           'on (CLASSE.BDCODCLA = CC_REF.BDCODCLA) '||
         'left outer join VRH_BASE_TMENSAGENS MENSAG '||
           'on (MENSAG.BDCODMEN = CC_REF.BDCODMEN) '||
         'left outer join VRH_BASE_TSINDTRAB SINTRAB '||
           'on (SINTRAB.BDCODSINTRAB = CC_REF.BDCODSINTRAB) '||
         'left outer join TBANCOS BANCO '||
           'on (BANCO.BDCODBAN = CC_REF.BDCODBAN) '||
         'left outer join TBANCOS_AG AGEN '||
           'on (AGEN.BDCODBAN = CC_REF.BDCODBAN and AGEN.BDCODAG = CC_REF.BDCODAG) ';

  wwhere = '';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     wwhere = PRCODEMP;

  IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||PRCODCOL;
     END

  /* filtra as empresas por usuario */
  IF (wcodusu IS NOT NULL AND wcodusu <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'((exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||') and '||
                          'exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||' and Y.BDCODEMP = CC_REF.BDCODEMP)) '||
                         'or '||
                         '(not exists (select Y.BDCODUSU '||
                                      'from TEMPRESA_USUARIO Y '||
                                      'where Y.BDCODUSU = '||wcodusu||'))'||
                         ') ';
     END




  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
    INTO
      :BDCODEMP,
      :BDCODCOL,
      :BDCODCLA,
      :BDDESCCLA,
      :BDGRUPOCLA,
      :BDCODMEN,
      :BDDESCMEN,
      :BDCODSINTRAB,
      :BDDESCSINTRAB,
      :BDCODBAN,
      :BDNOMBAN,
      :BDCODAG,
      :BDNOMAG,
      :BDCTADEPCOL,
      :BDDIGCTADEPCOL,
      :BDTIPOCTACOL,
      :BDMODOPAGTOCOL,
      :BDCARTAOSALCOL,
      :BDFORMAPAGTOCOL,
      :BDNRODEPIRCOL,
      :BDBASEIRRFADCOL,
      :BDVALORPREVPRIVNCOL,
      :BDVALORPREVPRIV13COL,
      :BDDATAOPCAOFGTSCOL,
      :BDCTAFGTSCOL,
      :BDCATEGORIACOL,
      :BDPERCFGTSCOL,
      :BDOCORRENCIACOL,
      :BDPERCRATCOL,
      :BDPERCDESCFPASCOL,
      :BDBASEINSSNCOL,
      :BDVALORINSSNCOL,
      :BDBASEIRRFNCOL,
      :BDVALORIRRFNCOL,
      :BDBASEINSS13COL,
      :BDVALORINSS13COL,
      :BDBASEIRRF13COL,
      :BDVALORIRRF13COL,
      :BDTIPOCOL,
      :BDHORASMENSAISCOL,
      :BDHORASSEMANAISCOL,
      :BDHORASDIARIASCOL,
      :BDPERCINSALUBCOL,
      :BDINCIDINSALUBCOL,
      :BDPERCPERCULCOL,
      :BDINCIDPERICULCOL,
      :BDPERCNOTURNOCOL,
      :BDINCIDNOTURNOCOL,
      :BDNRODEPSALFAMCOL,
      :BDIGNORAFALTASFERCOL,
      :BDCALCADIANTACOL,
      :BDNAOARREDONDARCOL,
      :BDIMPETIQUETACOL,
      :BDCALCDSRRVCOL,
      :BDCALCDSRHECOL,
      :BDCALCDSRSALCOL,
      :BDCALCVALTRANSCOL,
      :BDCALCVALREFCOL,
      :BDCODGPS,
      :BDDESCINSSDOIRCOL,
      :BDSEXOCOL,
      :BDEMAILCOL,
      :BDDATANASCCOL,
      :BDGRAUINSTCOL,
      :BDESTCIVCOL,
      :BDDATAADMCOL,
      :BDDATAADICCOL,
      :BDCPFCOL,
      :BDPISCOL,
      :BDRESERVISTACOL,
      :BDCTPSCOL,
      :BDSERIECTPSCOL,
      :BDDSERIECTPSCOL,
      :BDCNHCOL,
      :BDVENCCNHCOL,
      :BDDEFFISICOCOL,
      :BDDATAFIMPRAZO1COL,
      :BDDATAFIMPRAZO2COL,
      :BDALVARACOL,
      :BDNOMCOL
    DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: VRHF_SP_OUTRASINF_CALC_ATIVOS */
ALTER PROCEDURE VRHF_SP_OUTRASINF_CALC_ATIVOS(PRCODEMP VARCHAR(15000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDDESCMEN VARCHAR(15),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDNOMAG VARCHAR(40),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,6),
BDVALORPREVPRIVNCOL NUMERIC(15,6),
BDVALORPREVPRIV13COL NUMERIC(15,6),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,6),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,6),
BDPERCDESCFPASCOL NUMERIC(15,6),
BDBASEINSSNCOL NUMERIC(15,6),
BDVALORINSSNCOL NUMERIC(15,6),
BDBASEIRRFNCOL NUMERIC(15,6),
BDVALORIRRFNCOL NUMERIC(15,6),
BDBASEINSS13COL NUMERIC(15,6),
BDVALORINSS13COL NUMERIC(15,6),
BDBASEIRRF13COL NUMERIC(15,6),
BDVALORIRRF13COL NUMERIC(15,6),
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,6),
BDHORASSEMANAISCOL NUMERIC(15,6),
BDHORASDIARIASCOL NUMERIC(15,6),
BDPERCINSALUBCOL NUMERIC(15,6),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,6),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,6),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDSEXOCOL INTEGER,
BDEMAILCOL VARCHAR(200),
BDDATANASCCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDDEFFISICOCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE,
BDALVARACOL VARCHAR(5),
BDNOMCOL VARCHAR(70))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WCODUSU INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prRef, NULL, NULL);

  FOR SELECT BDCODUSU FROM sp_get_usuario
  INTO
    wcodusu
  DO

  wsql = 'select CC_REF.BDCODEMP, '||
                'CC_REF.BDCODCOL, '||
                'CC_REF.BDCODCLA, '||
                'CC_REF.BDDESCCLA, ' ||
                'CC_REF.BDGRUPOCLA, '||
                'CC_REF.BDCODMEN, '||
                'MENSAG.BDDESCMEN, '||
                'CC_REF.BDCODSINTRAB, '||
                'SINTRAB.BDDESCSINTRAB, '||
                'CC_REF.BDCODBAN, '||
                'BANCO.BDNOMBAN, '||
                'CC_REF.BDCODAG, '||
                'AGEN.BDNOMAG, '||
                'CC_REF.BDCTADEPCOL, '||
                'CC_REF.BDDIGCTADEPCOL, '||
                'CC_REF.BDTIPOCTACOL, '||
                'CC_REF.BDMODOPAGTOCOL, '||
                'CC_REF.BDCARTAOSALCOL, '||
                'CC_REF.BDFORMAPAGTOCOL, '||
                'CC_REF.BDNRODEPIRCOL, '||
                'CC_REF.BDBASEIRRFADCOL, '||
                'CC_REF.BDVALORPREVPRIVNCOL, '||
                'CC_REF.BDVALORPREVPRIV13COL, '||
                'CC_REF.BDDATAOPCAOFGTSCOL, '||
                'CC_REF.BDCTAFGTSCOL, '||
                'CC_REF.BDCATEGORIACOL, '||
                'CC_REF.BDPERCFGTSCOL, '||
                'CC_REF.BDOCORRENCIACOL, '||
                'CC_REF.BDPERCRATCOL, '||
                'CC_REF.BDPERCDESCFPASCOL, '||
                'CC_REF.BDBASEINSSNCOL, '||
                'CC_REF.BDVALORINSSNCOL, '||
                'CC_REF.BDBASEIRRFNCOL, '||
                'CC_REF.BDVALORIRRFNCOL, '||
                'CC_REF.BDBASEINSS13COL, '||
                'CC_REF.BDVALORINSS13COL, '||
                'CC_REF.BDBASEIRRF13COL, '||
                'CC_REF.BDVALORIRRF13COL, '||
                'CC_REF.BDTIPOCOL, '||
                'CC_REF.BDHORASMENSAISCOL, '||
                'CC_REF.BDHORASSEMANAISCOL, '||
                'CC_REF.BDHORASDIARIASCOL, '||
                'CC_REF.BDPERCINSALUBCOL, '||
                'CC_REF.BDINCIDINSALUBCOL, '||
                'CC_REF.BDPERCPERCULCOL, '||
                'CC_REF.BDINCIDPERICULCOL, '||
                'CC_REF.BDPERCNOTURNOCOL, '||
                'CC_REF.BDINCIDNOTURNOCOL, '||
                'CC_REF.BDNRODEPSALFAMCOL, '||
                'CC_REF.BDIGNORAFALTASFERCOL, '||
                'CC_REF.BDCALCADIANTACOL, '||
                'CC_REF.BDNAOARREDONDARCOL, '||
                'CC_REF.BDIMPETIQUETACOL, '||
                'CC_REF.BDCALCDSRRVCOL, '||
                'CC_REF.BDCALCDSRHECOL, '||
                'CC_REF.BDCALCDSRSALCOL, '||
                'CC_REF.BDCALCVALTRANSCOL, '||
                'CC_REF.BDCALCVALREFCOL, '||
                'CC_REF.BDCODGPS, '||
                'CC_REF.BDDESCINSSDOIRCOL, '||
                'COL.BDSEXOCOL, '||
                'COL.BDEMAILCOL, '||
                'COL.BDDATANASCCOL, '||
                'CC_REF.BDGRAUINSTCOL, '||
                'CC_REF.BDESTCIVCOL, '||
                'COL.BDDATAADMCOL, '||
                'COL.BDDATAADICCOL, '||
                'COL.BDCPFCOL, '||
                'COL.BDPISCOL, '||
                'COL.BDRESERVISTACOL, '||
                'COL.BDCTPSCOL, '||
                'COL.BDSERIECTPSCOL, '||
                'COL.BDDSERIECTPSCOL, '||
                'COL.BDCNHCOL, '||
                'COL.BDVENCCNHCOL, '||
                'COL.BDDEFFISICOCOL, '||
                'COL.BDDATAFIMPRAZO1COL, '||
                'COL.BDDATAFIMPRAZO2COL, '||
                'COL.BDALVARACOL, '||
                'COL.BDNOMCOL '||
         'from VW_COLABORADORES_REF_ATUAL CC_REF '||
         'left outer join VW_COLABORADORES COL '||
           'on (COL.BDCODEMP = CC_REF.BDCODEMP and COL.BDCODCOL = CC_REF.BDCODCOL) '||
         'left outer join VRH_BASE_TCLASSE CLASSE '||
           'on (CLASSE.BDCODCLA = CC_REF.BDCODCLA) '||
         'left outer join VRH_BASE_TMENSAGENS MENSAG '||
           'on (MENSAG.BDCODMEN = CC_REF.BDCODMEN) '||
         'left outer join VRH_BASE_TSINDTRAB SINTRAB '||
           'on (SINTRAB.BDCODSINTRAB = CC_REF.BDCODSINTRAB) '||
         'left outer join TBANCOS BANCO '||
           'on (BANCO.BDCODBAN = CC_REF.BDCODBAN) '||
         'left outer join TBANCOS_AG AGEN '||
           'on (AGEN.BDCODBAN = CC_REF.BDCODBAN and AGEN.BDCODAG = CC_REF.BDCODAG) ';

  wwhere = '';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     wwhere = PRCODEMP;

  IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||PRCODCOL;
     END

  /* filtra as empresas por usuario */
  IF (wcodusu IS NOT NULL AND wcodusu <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'((exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||') and '||
                          'exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||' and Y.BDCODEMP = CC_REF.BDCODEMP)) '||
                         'or '||
                         '(not exists (select Y.BDCODUSU '||
                                      'from TEMPRESA_USUARIO Y '||
                                      'where Y.BDCODUSU = '||wcodusu||'))'||
                         ') ';
     END

  IF (wwhere <> '') THEN
     wwhere = wwhere||' and ';

  wwhere = wwhere||' not exists(select W.BDCODCOL from VRH_EMP_TRESCISAO W where W.BDREFRESCISAO < '||prref||' and W.BDCODEMP = CC_REF.BDCODEMP and W.BDCODCOL = CC_REF.BDCODCOL) ';

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
    INTO
      :BDCODEMP,
      :BDCODCOL,
      :BDCODCLA,
      :BDDESCCLA,
      :BDGRUPOCLA,
      :BDCODMEN,
      :BDDESCMEN,
      :BDCODSINTRAB,
      :BDDESCSINTRAB,
      :BDCODBAN,
      :BDNOMBAN,
      :BDCODAG,
      :BDNOMAG,
      :BDCTADEPCOL,
      :BDDIGCTADEPCOL,
      :BDTIPOCTACOL,
      :BDMODOPAGTOCOL,
      :BDCARTAOSALCOL,
      :BDFORMAPAGTOCOL,
      :BDNRODEPIRCOL,
      :BDBASEIRRFADCOL,
      :BDVALORPREVPRIVNCOL,
      :BDVALORPREVPRIV13COL,
      :BDDATAOPCAOFGTSCOL,
      :BDCTAFGTSCOL,
      :BDCATEGORIACOL,
      :BDPERCFGTSCOL,
      :BDOCORRENCIACOL,
      :BDPERCRATCOL,
      :BDPERCDESCFPASCOL,
      :BDBASEINSSNCOL,
      :BDVALORINSSNCOL,
      :BDBASEIRRFNCOL,
      :BDVALORIRRFNCOL,
      :BDBASEINSS13COL,
      :BDVALORINSS13COL,
      :BDBASEIRRF13COL,
      :BDVALORIRRF13COL,
      :BDTIPOCOL,
      :BDHORASMENSAISCOL,
      :BDHORASSEMANAISCOL,
      :BDHORASDIARIASCOL,
      :BDPERCINSALUBCOL,
      :BDINCIDINSALUBCOL,
      :BDPERCPERCULCOL,
      :BDINCIDPERICULCOL,
      :BDPERCNOTURNOCOL,
      :BDINCIDNOTURNOCOL,
      :BDNRODEPSALFAMCOL,
      :BDIGNORAFALTASFERCOL,
      :BDCALCADIANTACOL,
      :BDNAOARREDONDARCOL,
      :BDIMPETIQUETACOL,
      :BDCALCDSRRVCOL,
      :BDCALCDSRHECOL,
      :BDCALCDSRSALCOL,
      :BDCALCVALTRANSCOL,
      :BDCALCVALREFCOL,
      :BDCODGPS,
      :BDDESCINSSDOIRCOL,
      :BDSEXOCOL,
      :BDEMAILCOL,
      :BDDATANASCCOL,
      :BDGRAUINSTCOL,
      :BDESTCIVCOL,
      :BDDATAADMCOL,
      :BDDATAADICCOL,
      :BDCPFCOL,
      :BDPISCOL,
      :BDRESERVISTACOL,
      :BDCTPSCOL,
      :BDSERIECTPSCOL,
      :BDDSERIECTPSCOL,
      :BDCNHCOL,
      :BDVENCCNHCOL,
      :BDDEFFISICOCOL,
      :BDDATAFIMPRAZO1COL,
      :BDDATAFIMPRAZO2COL,
      :BDALVARACOL,
      :BDNOMCOL
    DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: VRHF_SP_OUTRASINF_CALC_AUT */
ALTER PROCEDURE VRHF_SP_OUTRASINF_CALC_AUT(PRCODCOL VARCHAR(32700),
PRREF INTEGER,
PREMPRESA INTEGER = 0)
 RETURNS(BDCODCOL INTEGER,
BDCODCLA INTEGER,
BDDESCCLA VARCHAR(40),
BDGRUPOCLA INTEGER,
BDCODMEN INTEGER,
BDDESCMEN VARCHAR(15),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDNOMAG VARCHAR(40),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDMODOPAGTOCOL INTEGER,
BDCARTAOSALCOL VARCHAR(7),
BDFORMAPAGTOCOL INTEGER,
BDNRODEPIRCOL INTEGER,
BDBASEIRRFADCOL NUMERIC(15,2),
BDVALORPREVPRIVNCOL NUMERIC(15,2),
BDVALORPREVPRIV13COL NUMERIC(15,2),
BDDATAOPCAOFGTSCOL DATE,
BDCTAFGTSCOL VARCHAR(11),
BDCATEGORIACOL INTEGER,
BDPERCFGTSCOL NUMERIC(15,2),
BDOCORRENCIACOL INTEGER,
BDPERCRATCOL NUMERIC(15,2),
BDPERCDESCFPASCOL NUMERIC(15,2),
BDTIPOCOL INTEGER,
BDHORASMENSAISCOL NUMERIC(15,2),
BDHORASSEMANAISCOL NUMERIC(15,2),
BDHORASDIARIASCOL NUMERIC(15,2),
BDPERCINSALUBCOL NUMERIC(15,2),
BDINCIDINSALUBCOL INTEGER,
BDPERCPERCULCOL NUMERIC(15,2),
BDINCIDPERICULCOL INTEGER,
BDPERCNOTURNOCOL NUMERIC(15,2),
BDINCIDNOTURNOCOL INTEGER,
BDNRODEPSALFAMCOL INTEGER,
BDIGNORAFALTASFERCOL VARCHAR(5),
BDCALCADIANTACOL VARCHAR(5),
BDNAOARREDONDARCOL VARCHAR(5),
BDIMPETIQUETACOL VARCHAR(5),
BDCALCDSRRVCOL VARCHAR(5),
BDCALCDSRHECOL VARCHAR(5),
BDCALCDSRSALCOL VARCHAR(5),
BDCALCVALTRANSCOL VARCHAR(5),
BDCALCVALREFCOL VARCHAR(5),
BDCODGPS INTEGER,
BDDESCINSSDOIRCOL VARCHAR(5),
BDSEXOCOL INTEGER,
BDEMAILCOL VARCHAR(200),
BDDATANASCCOL DATE,
BDGRAUINSTCOL INTEGER,
BDESTCIVCOL INTEGER,
BDDATAADMCOL DATE,
BDDATAADICCOL DATE,
BDCPFCOL VARCHAR(18),
BDPISCOL VARCHAR(14),
BDRESERVISTACOL VARCHAR(16),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDCNHCOL VARCHAR(11),
BDVENCCNHCOL DATE,
BDDEFFISICOCOL INTEGER,
BDDATAFIMPRAZO1COL DATE,
BDDATAFIMPRAZO2COL DATE,
BDALVARACOL VARCHAR(5),
BDNOMCOL DM_BDNOMTER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WCODUSU INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prRef, NULL, NULL);

  FOR SELECT BDCODUSU FROM sp_get_usuario
  INTO
    wcodusu
  DO

/*00*/  wsql = 'select SERVICO.BDCODTER BDCODCOL, ';
/*01*/  wsql = wsql||'VINC.BDCODCLA, ';
/*02*/  wsql = wsql||'CLASSE.BDDESCCLA, ';
/*03*/  wsql = wsql||'CLASSE.BDGRUPOCLA, ';
/*04*/  wsql = wsql||'0 BDCODMEN,';
/*05*/  wsql = wsql||''''' BDDESCMEN, ';
/*06*/  wsql = wsql||'0 BDCODSINTRAB,';
/*07*/  wsql = wsql||''''' BDDESCSINTRAB, ';
/*08*/  wsql = wsql||'BAN.BDCODBAN, ';
/*09*/  wsql = wsql||'BANCO.BDNOMBAN, ';
/*10*/  wsql = wsql||'BAN.BDCODAG, ';
/*11*/  wsql = wsql||'AGEN.BDNOMAG, ';
/*12*/  wsql = wsql||'BAN.BDCTADEPTER BDCTADEPCOL, ';
/*13*/  wsql = wsql||'BAN.BDDIGCTADEPTER BDDIGCTADEPCOL, ';
/*14*/  wsql = wsql||'BAN.BDTIPOCTATER BDTIPOCTACOL, ';
/*15*/  wsql = wsql||'BAN.BDMODOPAGTOTER BDMODOPAGTOCOL, ';
/*16*/  wsql = wsql||'BAN.BDCARTAOSALTER BDCARTAOSALCOL, ';
/*17*/  wsql = wsql||'0 BDFORMAPAGTOCOL,';
/*18*/  wsql = wsql||'TERCREF.BDNRODEPIRTER BDNRODEPIRCOL, ';
/*19*/  wsql = wsql||'0 BDBASEIRRFADCOL,';
/*20*/  wsql = wsql||'0 BDVALORPREVPRIVNCOL,';
/*21*/  wsql = wsql||'0 BDVALORPREVPRIV13COL,';
/*22*/  wsql = wsql||'TER.BDDATACADTER BDDATAOPCAOFGTSCOL,';
/*23*/  wsql = wsql||'null BDCTAFGTSCOL, ';
/*24*/  wsql = wsql||'FGTS.BDCATEGORIATER BDCATEGORIACOL, ';
/*25*/  wsql = wsql||'0 BDPERCFGTSCOL, ';
/*26*/  wsql = wsql||'FGTS.BDOCORRENCIATER BDOCORRENCIACOL, ';
/*27*/  wsql = wsql||'FGTS.BDPERCRATTER BDPERCRATCOL, ';
/*28*/  wsql = wsql||'0 BDPERCDESCFPASCOL, ';
--/*29*/  wsql = wsql||'CC_REF.BDBASEINSSNCOL, ';
--/*30*/  wsql = wsql||'CC_REF.BDVALORINSSNCOL, ';
--/*31*/  wsql = wsql||'CC_REF.BDBASEIRRFNCOL, ';
--/*32*/  wsql = wsql||'CC_REF.BDVALORIRRFNCOL, ';
--/*33*/  wsql = wsql||'CC_REF.BDBASEINSS13COL, ';
--/*34*/  wsql = wsql||'CC_REF.BDVALORINSS13COL, ';
--/*35*/  wsql = wsql||'CC_REF.BDBASEIRRF13COL, ';
--/*36*/  wsql = wsql||'CC_REF.BDVALORIRRF13COL, ';
/*37*/  wsql = wsql||'0 BDTIPOCOL, ';
/*38*/  wsql = wsql||'0 BDHORASMENSAISCOL, ';
/*39*/  wsql = wsql||'0 BDHORASSEMANAISCOL, ';
/*40*/  wsql = wsql||'0 BDHORASDIARIASCOL, ';
/*41*/  wsql = wsql||'0 BDPERCINSALUBCOL, ';
/*42*/  wsql = wsql||'0 BDINCIDINSALUBCOL, ';
/*43*/  wsql = wsql||'0 BDPERCPERCULCOL, ';
/*44*/  wsql = wsql||'0 BDINCIDPERICULCOL, ';
/*45*/  wsql = wsql||'0 BDPERCNOTURNOCOL, ';
/*46*/  wsql = wsql||'0 BDINCIDNOTURNOCOL, ';
/*47*/  wsql = wsql||'0 BDNRODEPSALFAMCOL, ';
/*48*/  wsql = wsql||''''' BDIGNORAFALTASFERCOL, ';
/*49*/  wsql = wsql||''''' BDCALCADIANTACOL, ';
/*50*/  wsql = wsql||''''' BDNAOARREDONDARCOL, ';
/*51*/  wsql = wsql||''''' BDIMPETIQUETACOL, ';
/*52*/  wsql = wsql||''''' BDCALCDSRRVCOL, ';
/*53*/  wsql = wsql||''''' BDCALCDSRHECOL, ';
/*54*/  wsql = wsql||''''' BDCALCDSRSALCOL, ';
/*55*/  wsql = wsql||''''' BDCALCVALTRANSCOL, ';
/*56*/  wsql = wsql||''''' BDCALCVALREFCOL, ';
/*57*/  wsql = wsql||'0 BDCODGPS, ';
/*58*/  wsql = wsql||''''' BDDESCINSSDOIRCOL, ';
/*59*/  wsql = wsql||'FIS_REF.BDSEXOTER BDSEXOCOL, ';
/*60*/  wsql = wsql||'TER.BDEMAILTER BDEMAILCOL, ';
/*61*/  wsql = wsql||'TERCRH.BDDATANASCTER BDDATANASCCOL, ';
/*62*/  wsql = wsql||'TERCREF.BDGRAUINSTTER BDGRAUINSTCOL, ';
/*63*/  wsql = wsql||'TERCREF.BDESTCIVTER BDESTCIVCOL, ';
/*64*/  wsql = wsql||'TER.BDDATACADTER BDDATAADMCOL, ';
/*65*/  wsql = wsql||'TER.BDDATACADTER BDDATAADICCOL, ';
/*66*/  wsql = wsql||'case when char_length(TERCRH.BDCPFMEITER) = 14 then TERCRH.BDCPFMEITER else TER.BDCGCTER end BDCPFCOL, ';
/*67*/  wsql = wsql||'DOCREF.BDPISTER BDPISCOL, ';
/*68*/  wsql = wsql||'DOC.BDRESERVISTATER BDRESERVISTACOL, ';
/*69*/  wsql = wsql||'DOCREF.BDCTPSTER BDCTPSCOL, ';
/*70*/  wsql = wsql||'DOCREF.BDSERIECTPSTER BDSERIECTPSCOL, ';
/*71*/  wsql = wsql||'DOCREF.BDDSERIECTPSTER BDDSERIECTPSCOL, ';
/*72*/  wsql = wsql||'DOCREF.BDCNHTER BDCNHCOL, ';
/*73*/  wsql = wsql||'DOCREF.BDVENCCNHTER BDVENCCNHCOL, ';
/*74*/  wsql = wsql||'0 BDDEFFISICOCOL, ';
/*75*/  wsql = wsql||'null BDDATAFIMPRAZO1COL, ';
/*76*/  wsql = wsql||'null BDDATAFIMPRAZO2COL, ';
/*77*/  wsql = wsql||'''FALSE'' BDALVARACOL, ';
/*78*/  wsql = wsql||'TER.BDNOMETER BDNOMCOL ';
        wsql = wsql||'from ('||
                            'select * from VRH_BASE_TSERVTERC '||
                            'where BDREFPAGSERV >= '||prref;

        IF (prempresa > 0) THEN
           wsql = wsql||' and BDCODEMP = '||prempresa;

        wsql = wsql||') SERVICO ';

        wsql = wsql||'join TTERCEIRO_REF TER on TER.BDCODTER = SERVICO.BDCODTER and TER.BDREFEMP = (select first 1 BDREFEMP from TTERCEIRO_REF where BDCODTER = TER.BDCODTER and BDREFEMP <= '||prref||' order by BDCODTER desc, BDREFEMP desc) ';
        wsql = wsql||'left outer join TTERCEIRO_RH TERCRH on TERCRH.BDCODTER = SERVICO.BDCODTER ';
        wsql = wsql||'left outer join VRH_BASE_TTERC_DOC DOC on DOC.BDCODTER = SERVICO.BDCODTER ';
        wsql = wsql||'left outer join VRH_BASE_TTERC_VINC VINC on VINC.BDCODTER = SERVICO.BDCODTER and VINC.BDREFTERC = (select max(BDREFTERC) from VRH_BASE_TTERC_VINC where BDCODTER = VINC.BDCODTER and BDREFTERC <= '||prref||') ';
        wsql = wsql||'left outer join VRHF_BASE_TTERC_BANCO BAN on BAN.BDCODTER = SERVICO.BDCODTER and BAN.BDREFTERC = (select max(BDREFTERC) from VRHF_BASE_TTERC_BANCO where BDCODTER = BAN.BDCODTER and BDREFTERC <= '||prref||') ';
        wsql = wsql||'left outer join VRH_BASE_TTERC_REF TERCREF on TERCREF.BDCODTER = SERVICO.BDCODTER and TERCREF.BDREFTERC = (select max(BDREFTERC) from VRH_BASE_TTERC_REF where BDCODTER = TERCREF.BDCODTER and BDREFTERC <= '||prref||') ';
        wsql = wsql||'left outer join VRHF_BASE_TTERC_FGTSGPS FGTS on FGTS.BDCODTER = SERVICO.BDCODTER and FGTS.BDREFTERC = (select max(BDREFTERC) from VRHF_BASE_TTERC_FGTSGPS where BDCODTER = FGTS.BDCODTER and BDREFTERC <= '||prref||') ';
        wsql = wsql||'left outer join VRH_BASE_TTERC_FISREF FIS_REF on FIS_REF.BDCODTER = SERVICO.BDCODTER and FIS_REF.BDREFTERC = (select max(BDREFTERC) from VRH_BASE_TTERC_FISREF where BDCODTER = FIS_REF.BDCODTER and BDREFTERC <= '||prref||') ';
        wsql = wsql||'left outer join VRH_BASE_TTERC_DOCREF DOCREF on DOCREF.BDCODTER = SERVICO.BDCODTER and DOCREF.BDREFTERC = (select max(BDREFTERC) from VRH_BASE_TTERC_DOCREF where BDCODTER = DOCREF.BDCODTER and BDREFTERC <= '||prref||') ';
        wsql = wsql||'left outer join VRH_BASE_TCLASSE CLASSE on (CLASSE.BDCODCLA = VINC.BDCODCLA) ';
        wsql = wsql||'left outer join TBANCOS BANCO on (BANCO.BDCODBAN = BAN.BDCODBAN) ';
        wsql = wsql||'left outer join TBANCOS_AG AGEN on (AGEN.BDCODBAN = BAN.BDCODBAN and AGEN.BDCODAG = BAN.BDCODAG) ';

  wwhere = '';

/*  if (PRCODEMP is not null and PRCODEMP <> '') then
     wwhere = PRCODEMP;*/

  IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||PRCODCOL;
     END

  /* filtra as empresas por usuario */
  IF (wcodusu IS NOT NULL AND wcodusu <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'((exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||') and '||
                          'exists (select Y.BDCODUSU '||
                                  'from TEMPRESA_USUARIO Y '||
                                  'where Y.BDCODUSU = '||wcodusu||')) '||
                         'or '||
                         '(not exists (select Y.BDCODUSU '||
                                      'from TEMPRESA_USUARIO Y '||
                                      'where Y.BDCODUSU = '||wcodusu||'))'||
                         ') ';
     END




  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
    INTO
/*      :BDCODEMP,*/
      :BDCODCOL,
      :BDCODCLA,
      :BDDESCCLA,
      :BDGRUPOCLA,
      :BDCODMEN,
      :BDDESCMEN,
      :BDCODSINTRAB,
      :BDDESCSINTRAB,
      :BDCODBAN,
      :BDNOMBAN,
      :BDCODAG,
      :BDNOMAG,
      :BDCTADEPCOL,
      :BDDIGCTADEPCOL,
      :BDTIPOCTACOL,
      :BDMODOPAGTOCOL,
      :BDCARTAOSALCOL,
      :BDFORMAPAGTOCOL,
      :BDNRODEPIRCOL,
      :BDBASEIRRFADCOL,
      :BDVALORPREVPRIVNCOL,
      :BDVALORPREVPRIV13COL,
      :BDDATAOPCAOFGTSCOL,
      :BDCTAFGTSCOL,
      :BDCATEGORIACOL,
      :BDPERCFGTSCOL,
      :BDOCORRENCIACOL,
      :BDPERCRATCOL,
      :BDPERCDESCFPASCOL,
--      :BDBASEINSSNCOL,
--      :BDVALORINSSNCOL,
--      :BDBASEIRRFNCOL,
--      :BDVALORIRRFNCOL,
--      :BDBASEINSS13COL,
--      :BDVALORINSS13COL,
--      :BDBASEIRRF13COL,
--      :BDVALORIRRF13COL,
      :BDTIPOCOL,
      :BDHORASMENSAISCOL,
      :BDHORASSEMANAISCOL,
      :BDHORASDIARIASCOL,
      :BDPERCINSALUBCOL,
      :BDINCIDINSALUBCOL,
      :BDPERCPERCULCOL,
      :BDINCIDPERICULCOL,
      :BDPERCNOTURNOCOL,
      :BDINCIDNOTURNOCOL,
      :BDNRODEPSALFAMCOL,
      :BDIGNORAFALTASFERCOL,
      :BDCALCADIANTACOL,
      :BDNAOARREDONDARCOL,
      :BDIMPETIQUETACOL,
      :BDCALCDSRRVCOL,
      :BDCALCDSRHECOL,
      :BDCALCDSRSALCOL,
      :BDCALCVALTRANSCOL,
      :BDCALCVALREFCOL,
      :BDCODGPS,
      :BDDESCINSSDOIRCOL,
      :BDSEXOCOL,
      :BDEMAILCOL,
      :BDDATANASCCOL,
      :BDGRAUINSTCOL,
      :BDESTCIVCOL,
      :BDDATAADMCOL,
      :BDDATAADICCOL,
      :BDCPFCOL,
      :BDPISCOL,
      :BDRESERVISTACOL,
      :BDCTPSCOL,
      :BDSERIECTPSCOL,
      :BDDSERIECTPSCOL,
      :BDCNHCOL,
      :BDVENCCNHCOL,
      :BDDEFFISICOCOL,
      :BDDATAFIMPRAZO1COL,
      :BDDATAFIMPRAZO2COL,
      :BDALVARACOL,
      :BDNOMCOL
    DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: VRHF_SP_QUADROHORARIOS */
ALTER PROCEDURE VRHF_SP_QUADROHORARIOS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRDIASEMANA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCIDADE VARCHAR(40),
BDUF VARCHAR(2),
BDBAIEMP DM_BDBAIRRO,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCEPEMP VARCHAR(9),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDPISCOL VARCHAR(14),
BDCODQH INTEGER,
BDDESQH DM_BDDESCQH,
BDDIA INTEGER,
BDHORAENT TIME,
BDHORASAI TIME)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WANO VARCHAR(4);
DECLARE VARIABLE WULTDIA VARCHAR(10);
DECLARE VARIABLE WMES VARCHAR(2);
DECLARE VARIABLE WDIA VARCHAR(2);
BEGIN


  EXECUTE PROCEDURE sp_seta_competencia(pranomes, NULL, prultimodia);

  wmes = CAST(SUBSTRING(CAST(:pranomes AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:pranomes AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wultdia = wmes||'/'||wdia||'/'||wano;


  wsql = 'select vw_vincdia.bdcodemp, empresas.bdnomemp , empresas.bdcnpjemp, empresas.BDNOMCID, empresas.bdsiglauf , empresas.bdbaiemp, empresas.bdlogremp,
          empresas.bdendemp, empresas.bdnumemp, empresas.bdcepemp, vw_vincdia.bdcodcol,col.bdnomcol, col.bdctpscol, col.bdseriectpscol, col.bdpiscol, vw_vincdia.bdcodqh, tqh.bddescqh,
          tqh_dias.bddiasemqh,  tqh_horas.bdqhhsent, tqh_horas.bdqhhssai
          from vw_tcolcon_vincdia vw_vincdia
          left outer join SP_CONSULTAEMPRESAS(' || pranomes || ', null, null) empresas on (empresas.bdcodemp = vw_vincdia.bdcodemp )
          left outer join vrh_sp_colcon(null,null,null,null,null, ' || pranomes || ' , '''||wultdia||''' , 1,1,1,1,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0) col  on (vw_vincdia.BDCODEMP = col.BDCODEMP and vw_vincdia.BDCODCOL = col.BDCODCOL)
          inner join vrh_base_tqh_dias tqh_dias on (tqh_dias.bdcodqh = vw_vincdia.bdcodqh)
          inner join vrh_base_tqh_horas tqh_horas on (tqh_horas.bdcodqhh = tqh_dias.bdcodqhh)
          inner join VRH_BASE_TQH tqh on (tqh.bdcodqh = vw_vincdia.bdcodqh)';

  wwhere = '(vw_vincdia.bdcodemp = ' || prcodemp || ')';


  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere || ' and (vw_vincdia.bdcodcol = ' || prcodcol || ')' ;
     END

  IF (prdiasemana IS NOT  NULL) THEN
     wwhere = wwhere|| ' and (tqh_dias.bddiasemqh = ' || prdiasemana || ')';

  IF (wwhere <> '') THEN
     wwhere = 'where '||wwhere;

  -- oder by
  wwhere = wwhere|| ' order by vw_vincdia.bdcodemp, vw_vincdia.bdcodcol, tqh_dias.bddiasemqh, tqh_horas.bdqhhsent  ';

  wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :bdnomemp,
        :bdcnpjemp,
        :bdcidade,
        :bduf,
        :bdbaiemp,
        :bdlogremp,
        :bdendemp,
        :bdnumemp,
        :bdcepemp,
        :BDCODCOL,
        :bdnomcol,
        :bdctpscol,
        :bdseriectpscol,
        :bdpiscol,
        :bdcodqh,
        :bddesqh,
        :bddia,
        :bdhoraent,
        :bdhorasai
      DO

    SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);


END
^

/* Restore proc. body: VRH_SP_SOMA_FERIAS_RECIBO */
create or alter procedure VRH_SP_SOMA_FERIAS_RECIBO (
    PREMPRESA varchar(15000),
    PRCOLABORADOR varchar(30000),
    PRDATAGOZOINI date = null,
    PRDATAGOZOFIM date = null,
    PRDATAPAGINI date = null,
    PRDATAPAGFIM date = null,
    PRCODFE integer = null)
returns (
    BDCODEMP integer not null,
    BDCODCOL integer not null,
    BDINIPERAQUISFE date not null,
    BDCODFE integer not null,
    BDINIPERGOZOFE date,
    BDFIMPERAQUISFE date,
    BDFIMPERGOZOFE date,
    BDDATAPAGFE date,
    BDQTDGOZOFE numeric(18,6),
    BDQTDABONOFE numeric(18,6),
    BDSALDOINIFE numeric(15,6),
    BDSALDOFIMFE numeric(15,6),
    BDBASEIRFE numeric(15,6),
    BDALIQIRFE numeric(15,6),
    BDVALORIRFE numeric(15,6),
    BDBASEINSSFE numeric(15,6),
    BDALIQINSSFE numeric(15,6),
    BDVALORINSSFE numeric(15,6),
    BDDEPFE numeric(15,6),
    BDSALBASEFE numeric(15,6),
    BDSALBASEHEFE numeric(15,6),
    BDDATABAIXAFE date,
    BDCOLETIVASFE varchar(5),
    BDREFPAGABOFE integer,
    BDBASEFGTSFE numeric(15,6),
    BDVALORFGTSFE numeric(15,6),
    BDVALORFGTSCSFE numeric(15,6),
    BDMAIORREMFE numeric(15,6),
    BDBSALFAMFE numeric(15,6),
    BDSALFAMFE numeric(15,6),
    BDCOMPETENCIAFE varchar(7),
    BDFALTASFE numeric(15,6),
    BDFERIADOSFE integer,
    BDBASEIROUTFE numeric(15,6),
    BDVALORIROUTFE numeric(15,6),
    BDDEPIROUTFE numeric(15,6),
    BDESTPROVFE numeric(15,6),
    BDBASEPISFE numeric(15,6),
    BDBRATAPOFE numeric(15,6),
    BDCREDITOFE numeric(15,6),
    BDDEBITOFE numeric(15,6),
    BDLIQUIDO numeric(18,6),
    BDREFINIFE integer,
    BDREFFIMFE integer,
    BDCALCA13FE varchar(5),
    BDTIPOA13FE integer,
    BDPERCA13FE numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDDATAPROCFE date,
    BDHORAPROCFE time,
    BDORDEM integer,
    BDDATAAVISO date,
    BDSALDOFINALSINDFE numeric(18,6),
    BDDIASLICFE numeric(18,6),
    BDTEMPOSERVFE integer,
    BDVALSALMINVIGENTE numeric(18,6),
    BDENVIOUESOCIAL varchar(5),
    BDENVIOUPGTOESOCIAL varchar(5),
    BDIDDEMONSTRATIVO varchar(30),
    BDFOLHAAUTOMATICA DM_BOOLEAN,
    BDRECIBOESOCIAL varchar(30),
    BDCODEVT integer,
    BDCODEVTFIM integer,
    BDREFPAGFE integer,
    BDLIQUIDOA13 numeric(18,6),
    BDINIGOZORECIBOFE date,
    BDFIMGOZORECIBOFE date,
    BDQTDGOZORECIBOFE numeric(18,6),
    BDREFFERIAS integer)
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(30000);
BEGIN
  wwhere = ' where not BDISTRANSFERENCIA ';

  IF (prempresa <> '') THEN
     BEGIN
       wwhere = wwhere||' and ('||prempresa||')';

       IF (prcolaborador <> '') THEN
          wwhere = wwhere||' and ('||prcolaborador||')';
     END

  IF (prdatagozoini IS NOT NULL) THEN
     wwhere = wwhere||' and ((COALESCE(BDINIGOZORECIBOFE,BDINIPERGOZOFE) <= '''||COALESCE(prdatagozofim,prdatagozoini)||''') and'||
                              ' (COALESCE(BDFIMGOZORECIBOFE,BDFIMPERGOZOFE) >= '''||prdatagozoini||''')) ';

  IF (prdatapagini IS NOT NULL) THEN
     BEGIN
       IF ((prdatapagfim IS NOT NULL) AND (prdatapagini <> prdatapagfim)) THEN
          wwhere = wwhere||' and (BDDATAPAGFE between '''||prdatapagini||''' and '''||prdatapagfim||''')';
       ELSE
          wwhere = wwhere||' and (BDDATAPAGFE >= '''||prdatapagini||''')';
     END

  IF (COALESCE(prcodfe,0) = 0) THEN
     prcodfe = NULL;

  IF (prcodfe IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||' and ((BDINIGOZORECIBOFE is NULL) or'||
                              ' (EXISTS(select T1.BDCODFE'||
                                      ' from VRH_EMP_TFERIAS T1'||
                                      ' where (T1.BDCODEMP = FER.BDCODEMP)'||
                                        ' and (T1.BDCODCOL = FER.BDCODCOL)'||
                                        ' and (T1.BDINIPERAQUISFE = FER.BDINIPERAQUISFE)'||
                                        ' and (T1.BDINIGOZORECIBOFE = FER.BDINIGOZORECIBOFE)'||
                                        ' and (T1.BDCODFE = '||CAST(prcodfe AS VARCHAR(10))||' or T1.BDDATAPAGFE = (SELECT BDDATAPAGFE '||
                                                                                                                   'FROM VRH_EMP_TFERIAS '||
                                                                                                                   'WHERE BDCODFE = '||CAST(prcodfe AS VARCHAR(10))||' '||
                                                                                                                   'AND BDCODEMP = FER.BDCODEMP '||
                                                                                                                   'AND BDCODCOL = FER.BDCODCOL '||
                                                                                                                   'AND BDINIPERAQUISFE = FER.BDINIPERAQUISFE) )'||
                               ')))';
     END

  wsql = 'select BDCODEMP, BDCODCOL, BDINIPERAQUISFE, min(BDINIGOZORECIBOFE),'||
               ' MIN(BDCODFE), MIN(BDINIPERGOZOFE), MIN(BDFIMPERAQUISFE), MIN(BDFIMPERGOZOFE), MIN(BDDATAPAGFE),'||
               ' SUM(BDQTDGOZOFE), MIN(BDQTDABONOFE), MIN(BDSALDOINIFE), MIN(BDSALDOFIMFE), SUM(BDBASEIRFE),'||
               ' MIN(BDALIQIRFE), SUM(BDVALORIRFE), SUM(BDBASEINSSFE), MIN(BDALIQINSSFE), SUM(BDVALORINSSFE),'||
               ' MIN(BDDEPFE), MIN(BDSALBASEFE), MIN(BDSALBASEHEFE), MIN(BDDATABAIXAFE), MIN(BDCOLETIVASFE),'||
               ' MIN(BDREFPAGABOFE), SUM(BDBASEFGTSFE), SUM(BDVALORFGTSFE), SUM(BDVALORFGTSCSFE), MIN(BDMAIORREMFE),'||
               ' SUM(BDBSALFAMFE), SUM(BDSALFAMFE), MIN(BDCOMPETENCIAFE), SUM(BDFALTASFE), SUM(BDFERIADOSFE),'||
               ' SUM(BDBASEIROUTFE), SUM(BDVALORIROUTFE), MIN(BDDEPIROUTFE), MIN(BDESTPROVFE), SUM(BDBASEPISFE),'||
               ' SUM(BDBRATAPOFE), SUM(BDCREDITOFE), SUM(BDDEBITOFE), SUM(BDLIQUIDO), MIN(BDREFINIFE),'||
               ' MIN(BDREFFIMFE), MIN(BDCALCA13FE), MIN(BDTIPOA13FE), MIN(BDPERCA13FE), SUM(BDBFGTS13),'||
               ' MIN(BDFGTS13), MIN(BDDATAPROCFE), MIN(BDHORAPROCFE), MIN(BDORDEM), MIN(BDDATAAVISO),'||
               ' SUM(BDSALDOFINALSINDFE), SUM(BDDIASLICFE), MIN(BDTEMPOSERVFE), MIN(BDVALSALMINVIGENTE), MIN(BDENVIOUESOCIAL),'||
               ' MIN(BDENVIOUPGTOESOCIAL), MIN(BDIDDEMONSTRATIVO), MIN(BDFOLHAAUTOMATICA), MIN(BDRECIBOESOCIAL), MIN(BDCODEVT),'||
               ' MIN(BDCODEVTFIM), MIN(BDREFPAGFE), SUM(BDLIQUIDOA13), MIN(BDFIMGOZORECIBOFE), MIN(BDQTDGOZORECIBOFE)'||
        ' from VRH_EMP_TFERIAS FER'||
          wwhere||
        ' group by BDCODEMP, BDCODCOL, BDINIPERAQUISFE, BDDATAPAGFE';
  FOR EXECUTE STATEMENT wsql
  INTO :BDCODEMP, :BDCODCOL, :BDINIPERAQUISFE, :BDINIGOZORECIBOFE,
       :BDCODFE, :BDINIPERGOZOFE, :BDFIMPERAQUISFE, :BDFIMPERGOZOFE, :BDDATAPAGFE,
       :BDQTDGOZOFE, :BDQTDABONOFE, :BDSALDOINIFE, :BDSALDOFIMFE, :BDBASEIRFE,
       :BDALIQIRFE, :BDVALORIRFE, :BDBASEINSSFE, :BDALIQINSSFE, :BDVALORINSSFE,
       :BDDEPFE, :BDSALBASEFE, :BDSALBASEHEFE, :BDDATABAIXAFE, :BDCOLETIVASFE,
       :BDREFPAGABOFE, :BDBASEFGTSFE, :BDVALORFGTSFE, :BDVALORFGTSCSFE, :BDMAIORREMFE,
       :BDBSALFAMFE, :BDSALFAMFE, :BDCOMPETENCIAFE, :BDFALTASFE, :BDFERIADOSFE,
       :BDBASEIROUTFE, :BDVALORIROUTFE, :BDDEPIROUTFE, :BDESTPROVFE, :BDBASEPISFE,
       :BDBRATAPOFE, :BDCREDITOFE, :BDDEBITOFE, :BDLIQUIDO, :BDREFINIFE,
       :BDREFFIMFE, :BDCALCA13FE, :BDTIPOA13FE, :BDPERCA13FE, :BDBFGTS13,
       :BDFGTS13, :BDDATAPROCFE, :BDHORAPROCFE, :BDORDEM, :BDDATAAVISO,
       :BDSALDOFINALSINDFE, :BDDIASLICFE, :BDTEMPOSERVFE, :BDVALSALMINVIGENTE, :BDENVIOUESOCIAL,
       :BDENVIOUPGTOESOCIAL, :BDIDDEMONSTRATIVO, :BDFOLHAAUTOMATICA, :BDRECIBOESOCIAL, :BDCODEVT,
       :BDCODEVTFIM, :BDREFPAGFE, :BDLIQUIDOA13, :BDFIMGOZORECIBOFE, :BDQTDGOZORECIBOFE DO
    BEGIN
      BDREFFERIAS = coalesce(BDREFPAGFE, BDREFINIFE, BDREFPAGABOFE);
      SUSPEND;
    END
END^

create or alter procedure VRH_SP_SOMA_VERBA_FERIAS_RECIBO (
    PREMPRESA varchar(15000),
    PRCOLABORADOR varchar(30000),
    PRDATAGOZOINI date = null,
    PRDATAGOZOFIM date = null,
    PRCODVER integer = 0,
    PRDATAPAGINI date = null,
    PRDATAPAGFIM date = null,
    PRCODFE integer = null,
    PRCONTABILIZACAO varchar(5) = 'FALSE')
returns (
    BDCODEMP integer not null,
    BDCODCOL integer not null,
    BDINIPERAQUISFE date not null,
    BDINIGOZORECIBOFE date,
    BDCODFE integer not null,
    BDCODVER integer not null,
    BDREFVFE numeric(15,6),
    BDVALVFE numeric(15,6),
    BDIGNREFVFE varchar(5),
    BDIGNVALVFE varchar(5),
    BDREFAUXVFE numeric(15,6),
    BDORVERBAFE integer,
    BDVALIFE numeric(18,6),
    BDIGNREFAVFE varchar(5),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000))
as
declare variable WTIPOREFVER integer;
declare variable WMINREFVFE numeric(18,6);
declare variable WCLAVER varchar(20);
declare variable WMINREFAUXVFE numeric(18,6);
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(30000);
declare variable WAND varchar(7);
declare variable WFILTROCODVER varchar(50);
declare variable WMAIORIGUAL varchar(2);
begin
  wand = ' where ';
  wwhere = '';

   IF (prempresa <> '') THEN
      BEGIN
        wwhere = wwhere||wand||'('||prempresa||') ';
        wand = ' and ';

        IF (prcolaborador <> '') THEN
           BEGIN
             wwhere = wwhere||wand||'('||prcolaborador||') ';
             wand = ' and ';
           END
        if (PRCODFE <> 0) then
           begin
             wwhere = wwhere ||wand||' (BDCODFE in ('||PRCODFE||') or FER.BDDATAPAGFE in (select BDDATAPAGFE '||
                                                                                        'from VRH_EMP_TFERIAS '||
                                                                                        'where BDCODFE in ('||PRCODFE||') and '||
                                                                                              'BDCODEMP = FER.BDCODEMP and '||
                                                                                              'BDCODCOL = FER.BDCODCOL))';
    wand = ' and ';
           end
      END

   IF (prdatagozoini is NOT NULL) THEN
      BEGIN
        wwhere = wwhere||wand||'((COALESCE(BDINIGOZORECIBOFE,BDINIPERGOZOFE) <= '''||COALESCE(prdatagozofim,prdatagozoini)||''') and'||
                               ' (COALESCE(BDFIMGOZORECIBOFE,BDFIMPERGOZOFE) >= '''||prdatagozoini||''')) ';
        wand = ' and ';
      END

  if (PRCONTABILIZACAO = 'TRUE') then
    WMAIORIGUAL = '>=';
  else
    WMAIORIGUAL = '=';

  IF (prdatapagini is NOT NULL) THEN
     BEGIN
       IF ((prdatapagfim is NOT NULL) and (prdatapagini <> prdatapagfim)) THEN
          wwhere = wwhere||wand||'(BDDATAPAGFE between '''||prdatapagini||''' and '''||prdatapagfim||''')';
       ELSE
          wwhere = wwhere||wand||'(BDDATAPAGFE '||WMAIORIGUAL||' '''||prdatapagini||''')';

       wand = ' and ';
     END

  IF (COALESCE(prcodfe,0) = 0) THEN
     prcodfe = NULL;

  IF (prcodfe IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||wand||'((FER.BDINIGOZORECIBOFE is NULL) or'||
                              ' (EXISTS(select T1.BDCODFE'||
                                      ' from VRH_EMP_TFERIAS T1'||
                                      ' where (T1.BDCODEMP = FER.BDCODEMP)'||
                                        ' and (T1.BDCODCOL = FER.BDCODCOL)'||
                                        ' and (T1.BDINIPERAQUISFE = FER.BDINIPERAQUISFE)'||
                                        ' and (T1.BDINIGOZORECIBOFE = FER.BDINIGOZORECIBOFE)'||
                                        ' and (T1.BDCODFE = '||CAST(prcodfe AS VARCHAR(10))||' OR T1.BDDATAPAGFE in (SELECT BDDATAPAGFE '||
                                                                                            'FROM VRH_EMP_TFERIAS '||
                                                                                            'WHERE BDCODFE= '||CAST(prcodfe AS VARCHAR(10))||' '||
                                                                                            'AND BDCODEMP = FER.BDCODEMP '||
                                                                                            'AND BDCODCOL = FER.BDCODCOL )) )'||
                               '))';
       wand = ' and ';
     END

  if (COALESCE(prcodver,0) > 0) then
     wfiltrocodver = ' and (VF.BDCODVER = '||CAST(prcodver as VARCHAR(10))||')';
  else
     wfiltrocodver = '';


  wsql = 'select FER.BDCODEMP, FER.BDCODCOL, FER.BDINIPERAQUISFE, min(FER.BDINIGOZORECIBOFE), VF.BDCODVER,'||
               ' (select first 1 VER.BDTIPOREFVER'||
                ' from VRH_BASE_TVERBAS_REF VER'||
                ' where (VER.BDCODVER = VF.BDCODVER)'||
                ' order by VER.BDCODVER desc, VER.BDREFVER desc) BDTIPOREFVER, MIN(VF.BDREFVFE), MIN(V.BDCLAVER), MIN(VF.BDREFAUXVFE),'||
               ' MIN(VF.BDCODFE), SUM(VF.BDREFVFE), SUM(VF.BDVALVFE), MIN(VF.BDIGNREFVFE), MIN(VF.BDIGNVALVFE),'||
               ' SUM(VF.BDREFAUXVFE), MIN(VF.BDORVERBAFE), SUM(VF.BDVALIFE), MIN(VF.BDIGNREFAVFE), MIN(VF.BDCOMPESP),'||
               ' MIN(VF.BDFORMREFAUX), MIN(VF.BDFORMREF), MIN(VF.BDFORMVAL)'||
        ' from (select * from VRH_EMP_TFERIAS FER'||wwhere||') FER'||
        ' inner join VRHF_EMP_TVERBAFE VF on (VF.BDCODEMP = FER.BDCODEMP)'||
                                       ' and (VF.BDCODCOL = FER.BDCODCOL)'||
                                       ' and (VF.BDINIPERAQUISFE = FER.BDINIPERAQUISFE)'||
                                       ' and (VF.BDCODFE = FER.BDCODFE)'||
                                             wfiltrocodver||
        ' left outer join VRH_BASE_TVERBAS V on (V.BDCODVER = VF.BDCODVER)'||
        ' group by FER.BDCODEMP, FER.BDCODCOL, FER.BDINIPERAQUISFE, FER.BDDATAPAGFE, VF.BDCODVER';
  FOR EXECUTE STATEMENT wsql
  INTO :BDCODEMP, :BDCODCOL, :BDINIPERAQUISFE, :BDINIGOZORECIBOFE, :BDCODVER,
       :wtiporefver, :wminrefvfe, :wclaver, :wminrefauxvfe,
       :BDCODFE, :BDREFVFE, :BDVALVFE, :BDIGNREFVFE, :BDIGNVALVFE,
       :BDREFAUXVFE, :BDORVERBAFE, :BDVALIFE, :BDIGNREFAVFE, :BDCOMPESP,
       :BDFORMREFAUX, :BDFORMREF, :BDFORMVAL DO
    BEGIN
      -- Nao somar referencia em verba percentual
      if (wtiporefver = 4) then
         BDREFVFE = wminrefvfe;

      -- Nao somar referencia auxiliar em 1/3
      if (SUBSTRING(wclaver FROM 1 FOR 5) in ('3.002', '3.004', '3.006', '3.008')) then
         BDREFAUXVFE = wminrefauxvfe;

      SUSPEND;
    END
end^

/* Restore proc. body: VRHF_SP_RECIBO_FERIAS */
create or alter procedure VRHF_SP_RECIBO_FERIAS (
    PREMPRESA varchar(15000),
    PRCOLABORADOR varchar(30000),
    PRORDEMIMP integer,
    PRCLASSE integer,
    PRFUNCAO integer,
    PRCENTROCUSTO integer,
    PRSINDICATO integer,
    PRDATAGOZOINI date,
    PRDATAGOZOFIM date,
    PRPERIODOAQUISITIVO date,
    PRCODIGOFERIAS integer,
    PRTIPOCODVER integer,
    PRREFERENCIA integer,
    PRULTIMODIA date,
    PRCOLETIVAS integer,
    PRAVISO integer = 0,
    PRIDADE21 integer = 2100,
    PRNOVORECIBO smallint = 0)
returns (
    BDTIPOESCALA integer,
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDBAIEMP DM_BDBAIRRO,
    BDNOMCIDEMP varchar(40),
    BDSIGLAUFEMP varchar(2),
    BDCNPJEMP varchar(18),
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCHAVE integer,
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDSIGLAUFCTPS varchar(2),
    BDDESCTFUC varchar(40),
    BDDATAADMCOL date,
    BDINIPERAQUISFE date,
    BDFIMPERAQUISFE date,
    BDCODFE integer,
    BDINIPERGOZOFE date,
    BDFIMPERGOZOFE date,
    BDFALTASFE numeric(15,6),
    BDSALBASEFE numeric(15,6),
    BDSALBASEHEFE numeric(15,6),
    BDQTDABONOFE numeric(18,6),
    BDDATAPAGFE date,
    BDCODVER integer,
    BDTIPOCODVER integer,
    BDORDEMVER integer,
    BDDESCVER varchar(80),
    BDDESCREDVER varchar(20),
    BDREFVFE numeric(15,6),
    BDVALVFE numeric(15,6),
    BDTIPOREFVER integer,
    BDREFPAGABOFE integer,
    BDINISWS date,
    BDFIMSWS date,
    BDVALLIQUIDO numeric(15,6),
    BDCALCA13FE varchar(5),
    BDSALINI numeric(15,6),
    BDDIASLICFE numeric(18,6),
    BDDATAAVISO date,
    BDCLASSVER varchar(20),
    BDREFAUXVER numeric(15,6),
    BDCOLETIVAS varchar(5),
    BDDEPIR integer,
    BDDIASFERFE numeric(18,6),
    BDLOGOEMP blob sub_type 0 segment size 32720,
    BDREFHOREMP DM_BOOLEAN,
    BDCPFCOL varchar(14),
    BDDATARELABONO date,
    BDORDEM integer,
    BDFERIADOSFE integer,
    BDREFERENCIA integer,
    BDDTAINICIALFOLGA date,
    BDCODQH integer,
    BDCODPQUA integer)
as
declare variable WORDERBY varchar(10000);
declare variable WWHERE varchar(15000);
declare variable WWHEREAVISO varchar(15000);
declare variable WSQL varchar(30000);
declare variable WMES integer;
declare variable WANO integer;
declare variable WDIA integer;
declare variable WDATAAUX varchar(10);
declare variable WCHAVE integer;
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WSQLAVISO varchar(30000);
declare variable WSQLFERIAS varchar(30000);
declare variable WREFDADOSEMP integer;
declare variable WSQLDADOSEMP varchar(500);
declare variable WWHEREDADOSEMP varchar(500);
declare variable WCODEMPATU integer;
declare variable WCODCOLATU integer;
declare variable WINIPERAQUISATU date;
declare variable WCODFEATU integer;
declare variable WBDCODEMP integer;
declare variable WBDCODCOL integer;
declare variable WBDINIPERAQUISFE date;
declare variable WBDCODFE integer;
declare variable WBDCODVER integer;
declare variable WBDORDEMVER integer;
declare variable WCVER integer;
declare variable WCVER2 integer;
declare variable WEMPFERI integer;
declare variable WQTDPARC integer;
declare variable WPARCELA integer;
declare variable WTAM integer;
declare variable WCODSINTRAB integer;
declare variable WDATAFERFIM date;
declare variable WDATAFER date;
declare variable WMESDIAFES varchar(4);
declare variable WTIPOFES integer;
declare variable WCODAUX2 integer;
declare variable WAND varchar(7);
declare variable WVIEWEMP varchar(30000);
declare variable WVIEWCOL varchar(30000);
BEGIN
   wrefdadosemp = 0;

   IF (prreferencia IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, PRULTIMODIA);

   wsql = 'select ';

   IF (prtipocodver IS NULL) THEN
      wsql = wsql || 'distinct ';

   wsql = wsql || 'adm.bdsalinicol, vw_col_ref_atual.bdcodemp, temp.bdnomemp, temp.bdlogremp, temp.bdendemp, temp.bdnumemp, temp.bdcomplemp, temp.bdbaiemp, tcidemp.bdnomcid, ';
   wsql = wsql || 'tufemp.bdsiglauf, emp.bdcnpjemp, vw_col_ref_atual.bdcodcol, vw_col_ref_atual.bddataadmcol, tfuc.bddesctfuc, tferias.bdiniperaquisfe, tferias.bdfimperaquisfe, ';
   wsql = wsql || 'tferias.bdcodfe, tferias.bdinipergozofe, tferias.bdfimpergozofe, tferias.bdfaltasfe, tferias.bdsalbasefe, tferias.bdsalbasehefe, tferias.bddatapagfe, ';
   wsql = wsql || 'tferias.bdqtdabonofe, tferias.bdliquido, tferias.bdcalca13fe, tdepcol.depir, tferias.bdcoletivasfe ';

   IF (prtipocodver IS NOT NULL) THEN
      BEGIN
         wsql = wsql || ', tferias.bdcodver, tverbas.BDCLAVER, tverbas.bddescver, tverbas.bddescredver, tverbasref.bdtipocodver, tverbas.bdordemver, ';
         wsql = wsql || 'tferias.bdrefvfe, tferias.bdvalvfe, tferias.BDREFAUXVFE, tverbasref.bdtiporefver ';
      END

   wsql = wsql || ', tferias.BDREFPAGABOFE, (select sum(coalesce(ref.bddiaslicfe,0)) bddiaslicfe from vrh_emp_tferiasref ref '||
                  '   where tferias.bdcodemp = ref.bdcodemp and tferias.bdcodcol = ref.bdcodcol and tferias.bdiniperaquisfe = ref.bdiniperaquisfe and tferias.bdcodfe = ref.bdcodfe) bddiaslicfe '||
                  ', (select sum(coalesce(ref.bddiasferfe,0)) bddiasferfe from vrh_emp_tferiasref ref where tferias.bdcodemp = ref.bdcodemp and tferias.bdcodcol = ref.bdcodcol and tferias.bdiniperaquisfe = '||
                  '   ref.bdiniperaquisfe and tferias.bdcodfe = ref.bdcodfe) bddiasferfe, tferias.bddataaviso, img.bdlogoemp, colcondoc.BDCPFCOL, tferias.BDORDEM, lvinc.BDCODSINTRAB, CVD.bdtipoescala '||
                  ', CVD.BDDTAINICIALFOLGA, CVD.BDCODQH, CVD.BDCODPQUA ';

   --wsqlferias = 'select vw_col_ref_atual.* from vw_vrhf_ferias vw_col_ref_atual '; -- 81269 - Raphael Teodoro - 26/10/2022

   -- 81269 - Raphael Teodoro - 26/10/2022 - Ferias interrompidas
   WVIEWEMP = '';
   if (coalesce(PREMPRESA, '') <> '') then
     WVIEWEMP = replace(:prempresa,'vw_col_ref_atual.','');

   WVIEWCOL = '';
   if (coalesce(PRCOLABORADOR, '') <> '') then
     WVIEWCOL = replace(:prcolaborador,'vw_col_ref_atual.','');

   wsqlferias = 'select vw_col_ref_atual.*'||
               ' from (select SPFER.bdcodemp, SPFER.bdcodcol, SPFER.bdcodfe, SPFER.bdiniperaquisfe, SPFER.bdfimperaquisfe, SPFER.bdrefpagabofe, SPFER.bddataaviso, SPFER.bdordem,'||
                         ' COALESCE(SPFER.bdinigozorecibofe, SPFER.bdinipergozofe) as bdinipergozofe, COALESCE(SPFER.bdfimgozorecibofe, SPFER.bdfimpergozofe) as bdfimpergozofe,'||
                         ' SPFER.bdfaltasfe, SPFER.bdsalbasefe, SPFER.bdsalbasehefe, SPFER.bddatapagfe, SPFER.bdqtdabonofe, SPFER.bdliquido, SPFER.bdcalca13fe, SPFER.bdcoletivasfe,'||
                         ' SPVFER.BDCODVER, SPVFER.BDREFVFE, SPVFER.BDREFAUXVFE, SPVFER.BDVALVFE'||
                     ' from VRH_SP_SOMA_FERIAS_RECIBO('''                 ||WVIEWEMP||''', '''||WVIEWCOL||''', '||COALESCE(''''||:prdatagozoini||'''','NULL')||', '||COALESCE(''''||:prdatagozofim||'''','NULL')||   ', NULL, NULL, '||CAST(COALESCE(prcodigoferias,0) as VARCHAR(2))||') SPFER'||
                     ' left outer join VRH_SP_SOMA_VERBA_FERIAS_RECIBO('''||WVIEWEMP||''', '''||WVIEWCOL||''', '||COALESCE(''''||:prdatagozoini||'''','NULL')||', '||COALESCE(''''||:prdatagozofim||'''','NULL')||', 0, NULL, NULL, '||CAST(COALESCE(prcodigoferias,0) as VARCHAR(2))||') SPVFER'||
                                  ' on (SPVFER.BDCODEMP = SPFER.BDCODEMP) and (SPVFER.BDCODCOL = SPFER.BDCODCOL) and (SPVFER.BDINIPERAQUISFE = SPFER.BDINIPERAQUISFE) and (SPVFER.BDCODFE = SPFER.BDCODFE)'||
                      ') vw_col_ref_atual ';

   wsqlAviso = 'select av.bdcodemp, emp.bdnomemp, emp.bdlogremp, emp.bdendemp, emp.bdnumemp, emp.bdcomplemp, emp.bdbaiemp, cidemp.bdnomcid bdnomcidemp, ufemp.bdsiglauf bdsiglaufemp, '||
               ' temp.bdcnpjemp, av.bdcodcol, CASE WHEN (FIS.BDNMSOCIAL <> '''' and PAR.bdusanomesocial = ''TRUE'') THEN FIS.BDNMSOCIAL ELSE colcad.BDNOMCOL END BDNOMCOL, 1 bdchave, docref.bdctpscol, docref.bdseriectpscol, docref.bddseriectpscol, '||
               ' ufdoc.bdsiglauf bdsiglaufctps, tfuc.bddesctfuc bddesctfuc, col.bddataadmcol,  vw_col_ref_atual.bdperaqui bdiniperaquisfe, vw_col_ref_atual.bdfimperaqui bdfimperaquisfe, vw_col_ref_atual.bdcodfe bdcodfe, '||
               ' vw_col_ref_atual.bdinigozo bdinipergozofe, vw_col_ref_atual.bdfimgozo bdfimpergozofe, 0 bdfaltasfe, null bdsalbasehefe, '||
               ' vw_col_ref_atual.bdqtdabono bdqtdabonofe, null bddatapagfe, null bdcodver, null BDCLAVER, null bdtipocodver, null bdordemver, null bddescver, null bddescredver, null bdrefvfe, '||
               ' null bdvalvfe, null BDREFAUXVFE, null bdtiporefver, vw_col_ref_atual.bdrefabono bdrefpagabofe, null bdinisws, null bdfimsws, null bdvalliquido, null bdcalca13fe, '||
               ' null bdcoletivasfe, part.bdsalinicol bdsalini, null bddiaslicfe, null bddiasferfe, vw_col_ref_atual.bddataaviso, tdepcol.depir, diacol.bdtipoescala, COL.BDCPFCOL '||
               ' from vrh_emp_tdet_avisoferias vw_col_ref_atual join vrh_emp_tavisoferias av on (vw_col_ref_atual.bdcodemp = av.bdcodemp and av.bdcodcol = vw_col_ref_atual.bdcodcol and av.bddataaviso = vw_col_ref_atual.bddataaviso) '||
               ' left outer join vw_tempresas_ref_join emp on (av.bdcodemp = emp.bdcodemp) left outer join tempresas temp on (temp.bdcodemp = av.bdcodemp) '||
               ' left outer join vrh_emp_tcolcon col on (av.bdcodemp = col.bdcodemp and av.bdcodcol = col.bdcodcol) left outer join vw_vrh_emp_tcolcon_cad colcad on (colcad.bdcodemp = col.bdcodemp and colcad.bdcodcol = col.bdcodcol) '||
               ' left outer join vw_vrh_emp_tcolcon_docref docref on (docref.bdcodemp = col.bdcodemp and docref.bdcodcol = col.bdcodcol) left outer join vrh_emp_tcolcon_partida part on (av.bdcodemp = part.bdcodemp and av.bdcodcol = part.bdcodcol) '||
               ' left outer join VRH_EMP_TCOL_DOC doc on (av.bdcodemp = doc.bdcodemp and av.bdcodcol = doc.bdcodcol) left outer join tuf ufdoc on (ufdoc.bdcoduf = docref.bdcoduf) '||
               ' left outer join VW_TCOLCON_VINCDIA diacol on (diacol.BDCODEMP = av.BDCODEMP and diacol.BDCODCOL = av.BDCODCOL) left outer join vrh_funcoes_tfuc tfuc on (tfuc.bdCODPLAFUC = diacol.bdcodplafuc and tfuc.bdcodtfuc = diacol.bdcodtfuc) '||
               ' left outer join tcidade cidemp on (emp.bdcodcid = cidemp.bdcodcid) left outer join tuf ufemp on (ufemp.bdcoduf = cidemp.bdcoduf) '||
               ' left outer join VRH_EMP_TCOLCON_DOC colcondoc on (colcondoc.BDCODEMP = vw_col_ref_atual.BDCODEMP and colcondoc.BDCODCOL = vw_col_ref_atual.BDCODCOL) '||
               ' left outer join VRH_EMP_TCOLCON_FIS FIS ON (FIS.BDCODEMP = colcad.BDCODEMP AND FIS.BDCODCOL = colcad.BDCODCOL AND FIS.bdrefcol=colcad.bdrefcol)'||
               ' left outer join VRHF_BASE_TEMPPAR PAR ON (emp.BDCODEMP = PAR.BDCODEMP AND emp.bdrefemp=PAR.bdrefemp)'||
               ' left outer join( select BDCODEMP, BDCODCOL, count(*) DEPIR from VW_VRH_EMP_TDEP_REF DEPIR '||
                                ' where ((coalesce(DEPIR.BDREFIRDPN,0) = 0) or (coalesce(DEPIR.BDREFIRDPN,0) >= '''||:PRREFERENCIA||''')) and upper(coalesce(DEPIR.BDDEPIRDPN, ''FALSE'')) = ''TRUE'' and '||
                                '  ((DEPIR.BDPARENESCODPN not in (3, 8)) and (((select coalesce(BDAAAAMM, '''||:PRREFERENCIA||''') from AAAAMM(DEPIR.BDDATAENTREDPN)) <= '''||:PRREFERENCIA||''') and '||
                                '    ((select coalesce(BDAAAAMM, '''||:PRREFERENCIA||''') from AAAAMM(DEPIR.BDDATANASCDPN)) <= '''||:PRREFERENCIA||''' )) and ((DEPIR.BDDATABAUXADPN is null) '||
                                '     or (SUBSTRING(CAST(DEPIR.BDDATABAUXADPN AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(DEPIR.BDDATABAUXADPN AS VARCHAR(10)) FROM 6 FOR 2) >= '''||:PRREFERENCIA||''')) and '||
                                '   (((upper(DEPIR.BDINVALIDODPN) = ''TRUE'') or (DEPIR.BDREFIRDPN >= '||:PRREFERENCIA||')) or (((DEPIR.BDPARENESCODPN in (0, 4, 5, 6)) and '||
                                '       ('||:PRREFERENCIA||' - cast((select coalesce(BDAAAAMM, '''||:PRREFERENCIA||''') from AAAAMM(DEPIR.BDDATANASCDPN)) as integer) < '||:PRIDADE21||')    ) or '||
                                '     (DEPIR.BDPARENESCODPN in (1, 2))))) group by DEPIR.BDCODEMP, DEPIR.BDCODCOL) TDEPCOL on (TDEPCOL.BDCODEMP = AV.BDCODEMP and TDEPCOL.BDCODCOL = AV.BDCODCOL)';
   wwhere = '';
   WWHEREAVISO = '';
   wand = ' where ';

   IF (prempresa <> '') THEN
      BEGIN
        wwhere      = wwhere     ||wand||prempresa||' ';
        wwhereaviso = wwhereaviso||wand||prempresa||' ';
        wand = ' and ';

   IF (prcolaborador <> '') THEN
      BEGIN
             wwhere      = wwhere     ||wand||prcolaborador||' ';
             wwhereaviso = wwhereaviso||wand||prcolaborador||' ';
             wand = ' and ';
            END
     END

   IF (PRCOLETIVAS <> 1) THEN
     BEGIN
        IF ((prdatagozoini IS NOT NULL) AND (prdatagozofim IS NOT NULL)) THEN
          BEGIN
            wwhere      = wwhere     ||wand;
            wwhereaviso = wwhereaviso||wand;
            wand = ' and ';

            wwhere = wwhere||'(((vw_col_ref_atual.bdinipergozofe >= '''||prdatagozoini||''''||') and (vw_col_ref_atual.bdinipergozofe <= '''||prdatagozofim||''''||')) or ';
            wwhere = wwhere||' ((vw_col_ref_atual.bdfimpergozofe >= '''||prdatagozoini||''''||') and (vw_col_ref_atual.bdfimpergozofe <= '''||prdatagozofim||''''||')))';

            wwhereaviso = wwhereaviso||'(((vw_col_ref_atual.bdinigozo >= '''||prdatagozoini||''''||') and (vw_col_ref_atual.bdinigozo <= '''||prdatagozofim||''''||')) or ';
            wwhereaviso = wwhereaviso||' ((vw_col_ref_atual.bdfimgozo >= '''||prdatagozoini||''''||') and (vw_col_ref_atual.bdfimgozo <= '''||prdatagozofim||''''||')))';
               END
           ELSE
             BEGIN
               IF (prperiodoaquisitivo IS NOT NULL) THEN
                 BEGIN
                 wwhere      = wwhere     ||wand||'vw_col_ref_atual.bdiniperaquisfe = '''||prperiodoaquisitivo||''''||' ';
                 wwhereaviso = wwhereaviso||wand||'vw_col_ref_atual.bdperaqui = '''||prperiodoaquisitivo||''''||' ';
                 wand = ' and ';
                      END
                 END

           IF (prcodigoferias IS NOT NULL AND prcodigoferias > 0) THEN
              BEGIN
            wwhere      = wwhere     ||wand||'vw_col_ref_atual.bdcodfe = '||prcodigoferias||' ';
            wwhereaviso = wwhereaviso||wand||'vw_col_ref_atual.bdcodfe = '||prcodigoferias||' ';
            wand = ' and ';
                    END
              END

   wwhereaviso = wwhereaviso||wand||' not exists (select * from vrh_emp_tferias fer where fer.bdcodemp = vw_col_ref_atual.bdcodemp and fer.bdcodcol = vw_col_ref_atual.bdcodcol '||
                             ' and fer.bdiniperaquisfe = vw_col_ref_atual.bdperaqui and fer.bdcodfe = vw_col_ref_atual.bdcodfe) ';
   wsqlferias = wsqlferias||wwhere;
   wsqlaviso  = wsqlaviso ||wwhereaviso;

   wsql = wsql || ' from ('||wsqlferias||') tferias ';
   wsql = wsql || 'join VRH_EMP_TCOLCON vw_col_ref_atual on (vw_col_ref_atual.BDCODEMP = tferias.BDCODEMP and vw_col_ref_atual.BDCODCOL = tferias.BDCODCOL) ';
   wsql = wsql || 'left outer join ('||
                     'select vw_col_ref_atual.BDCODEMP, vw_col_ref_atual.BDCODCOL, max(vw_col_ref_atual.BDDATACOL) BDDATACOL '||
                     'from VRH_EMP_TCOL_VINCDIA vw_col_ref_atual '||
                     'where SUBSTRING(CAST(vw_col_ref_atual.BDDATACOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(vw_col_ref_atual.BDDATACOL AS VARCHAR(10)) FROM 6 FOR 2) <= '||prreferencia||'';

                     if (coalesce(prempresa, '') <> '') then
      begin
                        wsql = wsql||' and '||prempresa;
                     if (coalesce(prcolaborador, '') <> '') then
                        wsql = wsql||' and '||prcolaborador;
      end
   wsql = wsql||' group by vw_col_ref_atual.BDCODEMP, vw_col_ref_atual.BDCODCOL';
   wsql = wsql||') COL_DIAVINC on (COL_DIAVINC.BDCODEMP = vw_col_ref_atual.BDCODEMP and COL_DIAVINC.BDCODCOL = vw_col_ref_atual.BDCODCOL) ';
   wsql = wsql||'left outer join VRH_EMP_TCOL_VINCDIA CVD on (CVD.BDCODEMP = TFERIAS.BDCODEMP and CVD.BDCODCOL = TFERIAS.BDCODCOL and CVD.BDDATACOL = COL_DIAVINC.BDDATACOL) ';
   wsql = wsql||'left outer join VW_TEMPRESAS_REF TEMP on (TEMP.BDCODEMP = TFERIAS.BDCODEMP) ';
   wsql = wsql||'left outer join TEMPRESAS EMP on (EMP.BDCODEMP = TFERIAS.BDCODEMP) ';
   wsql = wsql||'left outer join vw_vrh_emp_tcol_adm adm on (adm.bdcodemp = vw_col_ref_atual.bdcodemp and vw_col_ref_atual.bdcodcol = adm.bdcodcol) ';
   wsql = wsql||'left outer join VRH_EMP_TCOL_DOC COL_DOC on (COL_DOC.bdcodemp = vw_col_ref_atual.bdcodemp and vw_col_ref_atual.bdcodcol = COL_DOC.bdcodcol) ';
   wsql = wsql||'left outer join TCIDADE TCIDEMP on (TCIDEMP.BDCODCID = TEMP.BDCODCID) ';
   wsql = wsql||'left outer join TUF TUFEMP on (TUFEMP.BDCODUF = TCIDEMP.BDCODUF) ';
   wsql = wsql||'left outer join vrh_funcoes_tfuc tfuc on (tfuc.bdCODPLAFUC = CVD.bdcodplafuc and tfuc.bdcodtfuc = CVD.bdcodtfuc) ';
   wSQL = wSQL||'left outer join( select BDCODEMP, BDCODCOL, count(*) DEPIR from VW_VRH_EMP_TDEP_REF DEPIR '||
                  ' where ((coalesce(DEPIR.BDREFIRDPN,0) = 0) or (coalesce(DEPIR.BDREFIRDPN,0) >= '''||:PRREFERENCIA||''')) and upper(coalesce(DEPIR.BDDEPIRDPN, ''FALSE'')) = ''TRUE'' and '||
                  '  ((DEPIR.BDPARENESCODPN not in (3, 8)) and (((select coalesce(BDAAAAMM, '''||:PRREFERENCIA||''') from AAAAMM(DEPIR.BDDATAENTREDPN)) <= '''||:PRREFERENCIA||''') and '||
                  '    ((select coalesce(BDAAAAMM, '''||:PRREFERENCIA||''') from AAAAMM(DEPIR.BDDATANASCDPN)) <= '''||:PRREFERENCIA||''')) and ((DEPIR.BDDATABAUXADPN is null) or '||
                  '    (SUBSTRING(CAST(DEPIR.BDDATABAUXADPN AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(DEPIR.BDDATABAUXADPN AS VARCHAR(10)) FROM 6 FOR 2) >= '''||:PRREFERENCIA||''')) and '||
                  '   (((upper(DEPIR.BDINVALIDODPN) = ''TRUE'') or (DEPIR.BDREFIRDPN >= '||:PRREFERENCIA||')) or (((DEPIR.BDPARENESCODPN in (0, 4, 5, 6)) and '||
                  '       ('||:PRREFERENCIA||' - cast((select coalesce(BDAAAAMM, '''||:PRREFERENCIA||''') from AAAAMM(DEPIR.BDDATANASCDPN)) as integer) < '||:PRIDADE21||')    ) or '||
                  '     (DEPIR.BDPARENESCODPN in (1, 2))))) group by DEPIR.BDCODEMP, DEPIR.BDCODCOL) TDEPCOL on (TDEPCOL.BDCODEMP = TFERIAS.BDCODEMP and TDEPCOL.BDCODCOL = TFERIAS.BDCODCOL)';

   IF (PRCOLETIVAS = 1) THEN
        wsql = wsql || ' left outer join vrh_emp_tferias_coletivas col on (tferias.bdcodemp = col.bdcodemp and tferias.bdcodcol = col.bdcodcol and tferias.bdiniperaquisfe = col.bdiniperaquisfe and tferias.bdcodfe = col.bdcodfe) ';

   IF (prtipocodver IS NOT NULL) THEN
      wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = tferias.bdcodver) left outer join vw_verbas_ref_atual tverbasref on (tverbasref.bdcodver = tverbas.bdcodver) ';

   wsql = wsql || ' left outer join TEMPRESAS_IMG img on (tferias.bdcodemp = img.bdcodemp) left outer join VW_VRH_EMP_TCOL_VINC lvinc on (tferias.bdcodemp = lvinc.bdcodemp and tferias.bdcodcol = lvinc.bdcodcol) ';

   if (prcentrocusto>0) then
      wsql = wsql || ' left outer join VRHF_EMP_TPREPFN PF on (PF.BDCODEMP = tferias.BDCODEMP and PF.BDCODCOL = tferias.BDCODCOL and PF.BDORDEM = tferias.BDORDEM)';

   if (coalesce(prclasse, 0) > 0)  then
      wsql = wsql || ' left outer join VW_VRH_EMP_TCOLCON_VINC nvinc on (tferias.bdcodemp = nvinc.bdcodemp and tferias.bdcodcol = nvinc.bdcodcol) ';

   wsql = wsql || ' left outer join VRH_EMP_TCOLCON_DOC colcondoc on (tferias.bdcodemp = colcondoc.bdcodemp and tferias.bdcodcol = colcondoc.bdcodcol) ';

   wwhere = '';
   wand = ' where ';

   IF (PRCOLETIVAS = 1) THEN
     BEGIN
       prcodigoferias = 0;
        wwhere = wwhere||wand||'col.bdinifer = '''||prdatagozoini||''''||' ';
        wand = ' and ';
     END

    IF (prcentrocusto > 0) THEN      --139716 Adicionado filtro para centro de custo Valmor H. Junior
      BEGIN
         wwhere = wwhere||wand||' PF.bdcodtpcc = '||prcentrocusto||' ';
        wand = ' and ';
      END

   IF (prtipocodver IS NOT NULL) THEN
      BEGIN
        wwhere = wwhere||wand||'tverbasref.bdtipocodver = '||prtipocodver||' ';
        wand = ' and ';
      END

   IF (prfuncao > 0) THEN
      BEGIN
        wwhere = wwhere||wand||'tfuc.bdCODTFUC = '||prfuncao||' ';
        wand = ' and ';
      END

   IF (prSindicato > 0) THEN
      BEGIN
        wwhere = wwhere||wand||'lvinc.bdCODSINTRAB = '||prsindicato||' '; -- 17564 | Marcelo B. M. | 02/06/2017
        wand = ' and ';
      END

   IF (prclasse > 0) THEN
      BEGIN
        wwhere = wwhere||wand||'nvinc.bdCODCLA = '||prClasse||' '; -- 17564 | Marcelo B. M. | 02/06/2017
        wand = ' and ';
      END
      
   worderby = ' order by vw_col_ref_atual.BDCODEMP, vw_col_ref_atual.BDCODCOL, tferias.BDCODVER ';

   wsql = wsql||wwhere||worderby;
   wchave = 1;
   wempatu = 0;
   wcolatu = 0;

   wsqldadosemp = 'select first 1 e2.BDNOMEMP, e2.BDLOGREMP, e2.BDENDEMP, e2.BDNUMEMP, e2.BDCOMPLEMP, e2.BDBAIEMP, c.BDNOMCID, u.BDSIGLAUF, e1.BDCNPJEMP from tempresas e1 ' ||
                  'join tempresas_ref e2 on (e2.BDCODEMP = e1.BDCODEMP) left outer join tcidade c on (c.BDCODCID = e2.BDCODCID) left outer join tuf u on (c.BDCODUF = u.BDCODUF) ';

   wcodempatu = NULL;
   wcodcolatu = NULL;
   winiperaquisatu = NULL;
   wcodfeatu = NULL;
   wcver = 0;

   IF (prtipocodver IS NOT NULL) THEN
      BEGIN
         FOR EXECUTE STATEMENT wsql
            INTO
            :bdsalini,:bdcodemp,:bdnomemp,:bdlogremp,:bdendemp,:bdnumemp,:bdcomplemp,:bdbaiemp,:bdnomcidemp,:bdsiglaufemp,:bdcnpjemp,:bdcodcol,:bddataadmcol,:bddesctfuc,:bdiniperaquisfe,:bdfimperaquisfe,
            :bdcodfe,:bdinipergozofe,:bdfimpergozofe,:bdfaltasfe,:bdsalbasefe,:bdsalbasehefe,:bddatapagfe,:bdqtdabonofe,:bdvalliquido,:bdcalca13fe,:bddepir,:bdcoletivas,
            :bdcodver, :bdclassver, :bddescver, :bddescredver, :bdtipocodver, :bdordemver, :bdrefvfe, :bdvalvfe, :bdrefauxver, :bdtiporefver,
            :bdrefpagabofe,:bddiaslicfe,:bddiasferfe,:bddataaviso,:bdlogoemp,:bdcpfcol,:bdordem,:wcodsintrab,:BDTIPOESCALA,:BDDTAINICIALFOLGA,:BDCODQH,:BDCODPQUA  DO
            BEGIN
              wbdcodemp = BDCODEMP;
              wbdcodcol = BDCODCOL;
              wbdiniperaquisfe = BDINIPERAQUISFE;
              wbdcodfe = BDCODFE;
              wbdcodver = BDCODVER;
              wbdordemver = BDORDEMVER;
              bdferiadosfe = 0;

              if (bdinipergozofe is not null and bdfimpergozofe is not null) then
                 begin
                   BDREFERENCIA = CAST((SUBSTRING(CAST(bdinipergozofe as VARCHAR(10)) from 1 for 4)||SUBSTRING(CAST(bdinipergozofe as VARCHAR(10)) from 6 for 2)) AS INTEGER);

                   wdatafer = bdinipergozofe;
                   wdataferfim = wdatafer + bddiasferfe;

                   while (wdatafer <= wdataferfim) do
                     begin
                       wmesdiafes = SUBSTRING(CAST(:wdatafer AS VARCHAR(10)) FROM 6 FOR 2)||SUBSTRING(CAST(:wdatafer AS VARCHAR(10)) FROM 9 FOR 2);
                       wtipofes = null;
                       wcodaux2 = null;
                       if (coalesce(wcodsintrab, 0) > 0) then
                          begin
                            wwheredadosemp = 'select BDCODSINTRAB, BDTIPFER from VRHF_BASE_TFERISIND where BDCODSINTRAB = '||wcodsintrab||' and BDMESDIAFES = '''||wmesdiafes||'''';
                            execute statement wwheredadosemp into :wcodaux2, :wtipofes;
                          end

                       if (coalesce(wcodaux2, 0) = 0) then
                          begin
                            wwheredadosemp = 'select BDCODEMP, BDTIPFER from VRHF_BASE_TFERIEMP where BDCODEMP = '||BDCODEMP||' and BDMESDIAFES = '''||wmesdiafes||'''';
                            execute statement wwheredadosemp into :wcodaux2, :wtipofes;
                          end

                       if (coalesce(wcodaux2, 0) > 0) then
                          begin
                            wtipofes = coalesce(wtipofes, 0);
                            if ((wtipofes = 0) or (wtipofes = 1 and UPPER(COALESCE(BDCOLETIVAS, 'FALSE')) = 'TRUE') or (wtipofes = 2 and UPPER(COALESCE(BDCOLETIVAS, 'FALSE')) = 'FALSE')) then
                               begin
                                 bdferiadosfe = bdferiadosfe + 1;
                                 wdataferfim = wdataferfim + 1;
                               end
                          end

                       wdatafer = wdatafer + 1;
                     end
                 end
              else
                 BDREFERENCIA = BDREFPAGABOFE;

              if (SUBSTRING(:BDCLASSVER FROM 1 FOR 7) = '3.001.3') then
                 begin
                   wwheredadosemp = 'select first 1 PARCI.BDPARCELAPI, PARC.BDQTDMESESPAR '||
                                  'from VRH_EMP_TPARCELAMENTOS_ITENS PARCI join VRH_EMP_TPARCELAMENTOS PARC on (PARC.BDCODEMP = PARCI.BDCODEMP and PARC.BDCODCOL = PARCI.BDCODCOL and PARC.BDCODPARC = PARCI.BDCODPARC) '||
                                    'where PARCI.BDCODEMP = '||BDCODEMP||' and PARCI.BDCODCOL = '||BDCODCOL;
                   if (bdinipergozofe is not null) then
                      wwheredadosemp = wwheredadosemp||' and PARCI.BDREFPI = '||SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2);
                   else
                      wwheredadosemp = wwheredadosemp||' and PARCI.BDREFPI = '||BDREFPAGABOFE;
     
                   wqtdparc = null;
                   wparcela = null;
                   execute statement wwheredadosemp into :wparcela, :wqtdparc;
     
                   if (coalesce(:wparcela, 0) > 0 and coalesce(:wqtdparc, 0) > 0) then
                      begin
                        if (strlen(:bddescver||' '||:wparcela||'/'||:wqtdparc) > 40) then
                           begin
                             wtam = strlen(' '||:wparcela||'/'||:wqtdparc);
                             bddescver = SUBSTRING(bddescver FROM 1 FOR (40 - :wtam))||' '||wparcela||'/'||wqtdparc;
                           end
                        else
                           bddescver = bddescver||' '||wparcela||'/'||wqtdparc;
     
                        if (strlen(:bddescredver||' '||:wparcela||'/'||:wqtdparc) > 20) then
                           begin
                             wtam = strlen(' '||:wparcela||'/'||:wqtdparc);
                             bddescredver = SUBSTRING(bddescredver FROM 1 FOR (20 - :wtam))||' '||wparcela||'/'||wqtdparc;
                           end
                        else
                           bddescver = bddescver||' '||wparcela||'/'||wqtdparc;
                      end
                 end

              IF (wcodempatu IS NULL) THEN
                wcodempatu = BDCODEMP;
              IF (wcodcolatu IS NULL) THEN
                wcodcolatu = BDCODCOL;
              IF (winiperaquisatu IS NULL) THEN
                winiperaquisatu = BDINIPERAQUISFE;
              IF (wcodfeatu IS NULL) THEN
                wcodfeatu = BDCODFE;

              bddatarelabono = bdfimperaquisfe - 15;

            while (EXTRACT(WEEKDAY FROM :bddatarelabono) in (0,6)) do   /* Domingo e s??bado */
                bddatarelabono = bddatarelabono - 1;

            wwheredadosemp = 'select first 1 BDCODFERI from TFERIADOSNOVO '||
                               'where ((coalesce(BDTIPOFERI, 0) = 0 and CAST(coalesce(BDMESDIAFERI, 0) AS INTEGER) > 0) or (coalesce(BDTIPOFERI, 0) = 1 and BDDATAFERI is not null)) and '||
                                  '(coalesce(BDDATAFERI, CAST((SUBSTRING(BDMESDIAFERI FROM 3 FOR 2)||''/''||SUBSTRING(BDMESDIAFERI FROM 1 FOR 2)||''/''||'||SUBSTRING(:prreferencia FROM 1 FOR 4)||') AS DATE)) = '''||bddatarelabono||''') ';
              wempferi = null;
              execute statement wwheredadosemp into :wempferi;
              while (coalesce(wempferi, 0) <> 0) do
                begin
                  bddatarelabono = bddatarelabono - 1;
                wwheredadosemp = 'select first 1 BDCODFERI from TFERIADOSNOVO '||
                                   'where ((coalesce(BDTIPOFERI, 0) = 0 and CAST(coalesce(BDMESDIAFERI, 0) AS INTEGER) > 0) or (coalesce(BDTIPOFERI, 0) = 1 and BDDATAFERI is not null)) and '||
                                     '(coalesce(BDDATAFERI, CAST((SUBSTRING(BDMESDIAFERI FROM 3 FOR 2)||''/''||SUBSTRING(BDMESDIAFERI FROM 1 FOR 2)||''/''||'||SUBSTRING(:prreferencia FROM 1 FOR 4)||') AS DATE)) = '''||bddatarelabono||''') ';
                  wempferi = null;
                  execute statement wwheredadosemp into :wempferi;
                end

              bddatarelabono = bdfimperaquisfe - 15;

            while (EXTRACT(WEEKDAY FROM :bddatarelabono) in (0,6)) do   /* Domingo e s????bado */
                bddatarelabono = bddatarelabono - 1;

            wwheredadosemp = 'select first 1 BDCODFERI from TFERIADOSNOVO '||
                               'where ((coalesce(BDTIPOFERI, 0) = 0 and CAST(coalesce(BDMESDIAFERI, 0) AS INTEGER) > 0) or (coalesce(BDTIPOFERI, 0) = 1 and BDDATAFERI is not null)) and '||
                                  '(coalesce(BDDATAFERI, CAST((SUBSTRING(BDMESDIAFERI FROM 3 FOR 2)||''/''||SUBSTRING(BDMESDIAFERI FROM 1 FOR 2)||''/''||'||SUBSTRING(:prreferencia FROM 1 FOR 4)||') AS DATE)) = '''||bddatarelabono||''') ';
              wempferi = null;
              execute statement wwheredadosemp into :wempferi;
              while (coalesce(wempferi, 0) <> 0) do
                begin
                  bddatarelabono = bddatarelabono - 1;
                wwheredadosemp = 'select first 1 BDCODFERI from TFERIADOSNOVO '||
                                   'where ((coalesce(BDTIPOFERI, 0) = 0 and CAST(coalesce(BDMESDIAFERI, 0) AS INTEGER) > 0) or (coalesce(BDTIPOFERI, 0) = 1 and BDDATAFERI is not null)) and '||
                                      'coalesce(BDDATAFERI, CAST((SUBSTRING(BDMESDIAFERI FROM 3 FOR 2)||''/''||SUBSTRING(BDMESDIAFERI FROM 1 FOR 2)||''/''||'||SUBSTRING(:prreferencia FROM 1 FOR 4)||') AS DATE)) = '''||bddatarelabono||''' ';
                  wempferi = null;
                  execute statement wwheredadosemp into :wempferi;
                end

              IF (bdinipergozofe IS NULL) THEN
                 BEGIN
                   wmes = CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5) AS INTEGER);
                   wano = CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
                   wrefdadosemp = CAST((CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4) AS VARCHAR(4)) || CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5) AS VARCHAR(2))) AS INTEGER); /*10208 - Ramon*/

                   SELECT ultdia FROM ultimo_dia_mes(:wmes,:wano) INTO wdia;
                   wdataaux = SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4);
                   bdinisws = CAST(wdataaux AS DATE);
                   wdataaux = SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/'||wdia||'/'||SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4);
                   bdfimsws = CAST(wdataaux AS DATE);
                 END
              ELSE
                 BEGIN
                   wrefdadosemp = CAST((SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER); /*10208 - Ramon*/
                   bdinisws = bdinipergozofe;
                   bdfimsws = bdfimpergozofe;
                 END

              if (wempatu = 0) then
                 begin
                   select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = :BDCODEMP and BDREFEMP <= :prreferencia order by BDREFEMP DESC into :BDREFHOREMP;
                 end

              IF (wempatu = 0 and wcolatu = 0) THEN
                 begin
                    select first 1 CASE WHEN (FIS.BDNMSOCIAL <> '' and PAR.bdusanomesocial = 'TRUE') THEN FIS.BDNMSOCIAL ELSE cad.BDNOMCOL END BDNOMCOL from VRH_EMP_TCOLCON_CAD cad
                    left outer join VRH_EMP_TCOLCON_FIS FIS ON (FIS.BDCODEMP = cad.BDCODEMP AND FIS.BDCODCOL = cad.BDCODCOL AND FIS.bdrefcol=cad.bdrefcol)
                    left outer join(select a.bdcodemp,max(a.bdrefemp)bdrefemp from VRHF_BASE_TEMPPAR a group by a.bdcodemp) pmax on  (pmax.BDCODEMP = cad.BDCODEMP)
                    left outer join VRHF_BASE_TEMPPAR PAR  on (par.bdcodemp=pmax.bdcodemp and par.bdrefemp=pmax.bdrefemp)
                   where cad.BDCODEMP = :BDCODEMP and cad.BDCODCOL = :BDCODCOL order by fis.bdrefcol  DESC into :BDNOMCOL;

                   if (BDNOMCOL is null) then
                   select first 1 docref.bdctpscol, docref.bdseriectpscol, docref.bddseriectpscol, tuf_doc.bdsiglauf
                   from VRH_EMP_TCOLCON_DOCREF docref
                   left outer join TUF tuf_doc on (tuf_doc.bdcoduf = docref.bdcoduf)
                   where docref.BDCODEMP = :BDCODEMP and docref.BDCODCOL = :BDCODCOL and docref.BDREFCOL <= :prreferencia
                   order by docref.BDREFCOL DESC
                   into :BDCTPSCOL, :BDSERIECTPSCOL, :BDDSERIECTPSCOL, :BDSIGLAUFCTPS;
                 end

              IF (wempatu = 0) THEN
                 wempatu = bdcodemp;

              IF (wcolatu = 0) THEN
                 wcolatu = bdcodcol;

              IF ((wempatu <> bdcodemp) OR (wcolatu <> bdcodcol)) THEN
                 BEGIN
                    select first 1 CASE WHEN (FIS.BDNMSOCIAL <> '' and PAR.bdusanomesocial = 'TRUE') THEN FIS.BDNMSOCIAL ELSE cad.BDNOMCOL END BDNOMCOL from VRH_EMP_TCOLCON_CAD cad
                    left outer join VRH_EMP_TCOLCON_FIS FIS ON (FIS.BDCODEMP = cad.BDCODEMP AND FIS.BDCODCOL = cad.BDCODCOL AND FIS.bdrefcol=cad.bdrefcol)
                    left outer join(select a.bdcodemp,max(a.bdrefemp)bdrefemp from VRHF_BASE_TEMPPAR a group by a.bdcodemp) pmax on  (pmax.BDCODEMP = cad.BDCODEMP)
                    left outer join VRHF_BASE_TEMPPAR PAR  on (par.bdcodemp=pmax.bdcodemp and par.bdrefemp=pmax.bdrefemp)
                   where cad.BDCODEMP = :BDCODEMP and cad.BDCODCOL = :BDCODCOL  order by fis.bdrefcol  DESC into :BDNOMCOL;

                   if (BDNOMCOL is null) then
                    select first 1 CASE WHEN (FIS.BDNMSOCIAL <> '' and PAR.bdusanomesocial = 'TRUE') THEN FIS.BDNMSOCIAL ELSE cad.BDNOMCOL END BDNOMCOL from VRH_EMP_TCOLCON_CAD cad
                    left outer join VRH_EMP_TCOLCON_FIS FIS ON (FIS.BDCODEMP = cad.BDCODEMP AND FIS.BDCODCOL = cad.BDCODCOL AND FIS.bdrefcol=cad.bdrefcol)
                    left outer join(select a.bdcodemp,max(a.bdrefemp)bdrefemp from VRHF_BASE_TEMPPAR a group by a.bdcodemp) pmax on  (pmax.BDCODEMP = cad.BDCODEMP)
                    left outer join VRHF_BASE_TEMPPAR PAR  on (par.bdcodemp=pmax.bdcodemp and par.bdrefemp=pmax.bdrefemp)
                   where cad.BDCODEMP = :BDCODEMP and cad.BDCODCOL = :BDCODCOL  order by fis.bdrefcol  DESC into :BDNOMCOL;

                   select first 1 docref.bdctpscol, docref.bdseriectpscol, docref.bddseriectpscol, tuf_doc.bdsiglauf
                   from VRH_EMP_TCOLCON_DOCREF docref
                   left outer join TUF tuf_doc on (tuf_doc.bdcoduf = docref.bdcoduf)
                   where docref.BDCODEMP = :BDCODEMP and docref.BDCODCOL = :BDCODCOL and docref.BDREFCOL <= :prreferencia
                   order by docref.BDREFCOL DESC
                   into :BDCTPSCOL, :BDSERIECTPSCOL, :BDDSERIECTPSCOL, :BDSIGLAUFCTPS;

                   if (wempatu <> BDCODEMP) then
                        select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = :BDCODEMP and BDREFEMP <= :prreferencia order by BDREFEMP DESC into :BDREFHOREMP;

                   wchave = 1;
                   wempatu = bdcodemp;
                   wcolatu = bdcodcol;
                 END

              bdchave = wchave;
              wchave = wchave + 1;

              wwheredadosemp = ' where e1.BDCODEMP = '||bdcodemp||' and e2.BDREFEMP = (select first 1 bdrefemp from tempresas_ref where bdcodemp = '||bdcodemp||' and bdrefemp <= '||wrefdadosemp||' order by bdrefemp desc)';
              IF (wrefdadosemp > 0) THEN
                BEGIN
                  EXECUTE STATEMENT wsqldadosemp || wwheredadosemp
                  INTO
                    :bdnomemp, :bdlogremp, :bdendemp, :bdnumemp, :bdcomplemp, :bdbaiemp, :bdnomcidemp, :bdsiglaufemp, :bdcnpjemp;
                END

              IF (prnovorecibo = 1) THEN
                BEGIN
                  IF ((BDCODEMP <> wcodempatu) OR (BDCODCOL <> wcodcolatu) OR (BDINIPERAQUISFE <> winiperaquisatu) OR (BDCODFE <> wcodfeatu)) THEN
                    BEGIN
                      wcver2 = 0;
                      IF (prtipocodver = 0) THEN
                        BEGIN
                          SELECT COUNT(*)
                          FROM VRHF_EMP_TVERBAFE X
                          JOIN VW_TVERBAS_REF Y ON (Y.BDCODVER = X.BDCODVER)
                          WHERE X.BDCODEMP = :wcodempatu AND X.BDCODCOL = :wcodcolatu AND X.BDINIPERAQUISFE = :winiperaquisatu AND X.BDCODFE = :wcodfeatu AND Y.BDTIPOCODVER IN (1,3)
                          INTO :wcver2;
                        END
                      ELSE
                        BEGIN
                          SELECT COUNT(*)
                          FROM VRHF_EMP_TVERBAFE X
                          JOIN VW_TVERBAS_REF Y ON (Y.BDCODVER = X.BDCODVER)
                          WHERE X.BDCODEMP = :wcodempatu AND X.BDCODCOL = :wcodcolatu AND X.BDINIPERAQUISFE = :winiperaquisatu AND X.BDCODFE = :wcodfeatu AND Y.BDTIPOCODVER NOT IN (1,3)
                          INTO :wcver2;
                        END
    
                      WHILE (wcver < wcver2) DO
                        BEGIN
                          BDCODEMP = wcodempatu;
                          BDCODCOL = wcodcolatu;
                          BDINIPERAQUISFE = winiperaquisatu;
                          BDCODFE = wcodfeatu;
                          BDCODVER = 0;
                          BDORDEMVER = 9999999;
                          SUSPEND;
                          wcver = wcver + 1;
                        END
    
                      BDCODEMP = wbdcodemp;
                      BDCODCOL = wbdcodcol;
                      BDINIPERAQUISFE = wbdiniperaquisfe;
                      BDCODFE = wbdcodfe;
                      BDCODVER = wbdcodver;
                      BDORDEMVER = wbdordemver;
                      wcver = 0;
                      wcodempatu = BDCODEMP;
                      wcodcolatu = BDCODCOL;
                      winiperaquisatu = BDINIPERAQUISFE;
                      wcodfeatu = BDCODFE;
                    END

                  wcver = wcver + 1;
                END
              SUSPEND;
            END

         IF (prnovorecibo = 1) THEN
           BEGIN
             IF ((wcodempatu <> 0) AND (wcodcolatu <> 0) AND (winiperaquisatu IS NOT NULL) AND (wcodfeatu <> 0)) THEN
               BEGIN
                 wcver2 = 0;
                 IF (prtipocodver = 0) THEN
                   BEGIN
                     SELECT COUNT(*)FROM VRHF_EMP_TVERBAFE X JOIN VW_TVERBAS_REF Y ON (Y.BDCODVER = X.BDCODVER)
                     WHERE X.BDCODEMP = :wcodempatu AND X.BDCODCOL = :wcodcolatu AND X.BDINIPERAQUISFE = :winiperaquisatu AND X.BDCODFE = :wcodfeatu AND Y.BDTIPOCODVER IN (1,3)
                     INTO :wcver2;
                   END
                 ELSE
                   BEGIN
                     SELECT COUNT(*) FROM VRHF_EMP_TVERBAFE X JOIN VW_TVERBAS_REF Y ON (Y.BDCODVER = X.BDCODVER)
                     WHERE X.BDCODEMP = :wcodempatu AND X.BDCODCOL = :wcodcolatu AND X.BDINIPERAQUISFE = :winiperaquisatu AND X.BDCODFE = :wcodfeatu AND Y.BDTIPOCODVER NOT IN (1,3)
                     INTO :wcver2;
                   END

                 WHILE (wcver < wcver2) DO
                   BEGIN
                     BDCODEMP = wcodempatu;
                     BDCODCOL = wcodcolatu;
                     BDINIPERAQUISFE = winiperaquisatu;
                     BDCODFE = wcodfeatu;
                     BDCODVER = 0;
                     BDORDEMVER = 9999999;
                     SUSPEND;
                     wcver = wcver + 1;
                   END
               END
           END

        /* Inclui registros de aviso */
        IF (praviso = 1) THEN
           BEGIN
             FOR EXECUTE STATEMENT wSqlAviso INTO
               :bdcodemp, :bdnomemp, :bdlogremp, :bdendemp, :bdnumemp, :bdcomplemp, :bdbaiemp, :bdnomcidemp, :bdsiglaufemp, :bdcnpjemp, :bdcodcol, :bdnomcol, :bdchave, :bdctpscol, :bdseriectpscol, :bddseriectpscol,
               :bdsiglaufctps, :bddesctfuc, :bddataadmcol,  :bdiniperaquisfe, :bdfimperaquisfe, :bdcodfe, :bdinipergozofe, :bdfimpergozofe, :bdfaltasfe, :bdsalbasehefe,
               :bdqtdabonofe, :bddatapagfe, :bdcodver, :bdclassver, :bdtipocodver, :bdordemver, :bddescver, :bddescredver, :bdrefvfe, :bdvalvfe, :bdrefauxver, :bdtiporefver, :bdrefpagabofe, :bdinisws, :bdfimsws, :bdvalliquido, :bdcalca13fe, :bdcoletivas, :bdsalini, :bddiaslicfe, :bddiasferfe, 
               :bddataaviso, :bddepir, :BDTIPOESCALA, :bdcpfcol
              DO
               BEGIN
                 IF (bdinipergozofe IS NULL) THEN
                    BEGIN
                      BDREFERENCIA = BDREFPAGABOFE;
                      wmes = CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5) AS INTEGER);
                      wano = CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
                      wrefdadosemp = CAST((CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4) AS VARCHAR(4)) || CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5) AS VARCHAR(2))) AS INTEGER); /*10208 - Ramon*/
   
                      SELECT ultdia FROM ultimo_dia_mes(:wmes,:wano) INTO wdia;
                      wdataaux = SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4);
                      bdinisws = CAST(wdataaux AS DATE);
                      wdataaux = SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/'||wdia||'/'||SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4);
                      bdfimsws = CAST(wdataaux AS DATE);

                      SELECT FIRST 1 BDSALBASECOL
                      FROM VRH_EMP_TCOLCON_CALCDIA
                      WHERE BDCODEMP = :BDCODEMP AND
                            BDCODCOL = :BDCODCOL AND
                            BDDATACOL <= SUBSTRING(CAST(:bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(:bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4)
                      ORDER BY BDDATACOL DESC
                      INTO :BDSALBASEFE;
                    END
                 ELSE
                    BEGIN
                      BDREFERENCIA = CAST((SUBSTRING(CAST(bdinipergozofe as VARCHAR(10)) from 1 for 4)||SUBSTRING(CAST(bdinipergozofe as VARCHAR(10)) from 6 for 2)) AS INTEGER);
                      wrefdadosemp = CAST((SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER); /*10208 - Ramon*/
                      bdinisws = bdinipergozofe;
                      bdfimsws = bdfimpergozofe;

                      SELECT FIRST 1 BDSALBASECOL
                      FROM VRH_EMP_TCOLCON_CALCDIA
                      WHERE BDCODEMP = :BDCODEMP AND
                            BDCODCOL = :BDCODCOL AND
                            BDDATACOL <= :BDINIPERGOZOFE
                      ORDER BY BDDATACOL DESC
                      INTO :BDSALBASEFE;
                    END

                 wwheredadosemp = ' where e1.BDCODEMP = '||bdcodemp||' and e2.BDREFEMP = (select first 1 bdrefemp from tempresas_ref where bdcodemp = '||bdcodemp||' and bdrefemp <= '||wrefdadosemp||' order by bdrefemp desc)';
                 IF (wrefdadosemp > 0) THEN
                   BEGIN
                     EXECUTE STATEMENT wsqldadosemp || wwheredadosemp
                     INTO
                       :bdnomemp, :bdlogremp, :bdendemp, :bdnumemp, :bdcomplemp, :bdbaiemp, :bdnomcidemp, :bdsiglaufemp, :bdcnpjemp;
                   END

                 SUSPEND;
               END
           END
      END
   ELSE
      BEGIN
         FOR EXECUTE STATEMENT wsql
            INTO
            :bdsalini, :bdcodemp, :bdnomemp, :bdlogremp, :bdendemp, :bdnumemp, :bdcomplemp, :bdbaiemp, :bdnomcidemp, :bdsiglaufemp, :bdcnpjemp, :bdcodcol, :bddataadmcol, :bddesctfuc, :bdiniperaquisfe, :bdfimperaquisfe,
            :bdcodfe, :bdinipergozofe, :bdfimpergozofe, :bdfaltasfe, :bdsalbasefe, :bdsalbasehefe, :bddatapagfe, :bdqtdabonofe, :bdvalliquido, :bdcalca13fe, :bddepir, :bdcoletivas,
            :BDREFPAGABOFE,:bddiaslicfe,:bddiasferfe,:bddataaviso,:bdlogoemp,:bdcpfcol,:bdordem,:wcodsintrab,:BDTIPOESCALA,:BDDTAINICIALFOLGA,:BDCODQH,:BDCODPQUA DO
            BEGIN
              bdferiadosfe = 0;

              if (bdinipergozofe is not null and bdfimpergozofe is not null) then
                 begin
                   BDREFERENCIA = CAST((SUBSTRING(CAST(bdinipergozofe as VARCHAR(10)) from 1 for 4)||SUBSTRING(CAST(bdinipergozofe as VARCHAR(10)) from 6 for 2)) AS INTEGER);
                   wdatafer = bdinipergozofe;
                   wdataferfim = wdatafer + bddiasferfe;

                   while (wdatafer <= wdataferfim) do
                     begin
                       wmesdiafes = SUBSTRING(CAST(:wdatafer AS VARCHAR(10)) FROM 6 FOR 2)||SUBSTRING(CAST(:wdatafer AS VARCHAR(10)) FROM 9 FOR 2);
                       wtipofes = null;
                       wcodaux2 = null;
                       if (coalesce(wcodsintrab, 0) > 0) then
                          begin
                            wwheredadosemp = 'select BDCODSINTRAB, BDTIPFER from VRHF_BASE_TFERISIND where BDCODSINTRAB = '||wcodsintrab||' and BDMESDIAFES = '''||wmesdiafes||'''';
                            execute statement wwheredadosemp into :wcodaux2, :wtipofes;
                          end

                       if (coalesce(wcodaux2, 0) = 0) then
                          begin
                            wwheredadosemp = 'select BDCODEMP, BDTIPFER from VRHF_BASE_TFERIEMP where BDCODEMP = '||BDCODEMP||' and BDMESDIAFES = '''||wmesdiafes||'''';
                            execute statement wwheredadosemp into :wcodaux2, :wtipofes;
                          end

                       if (coalesce(wcodaux2, 0) > 0) then
                          begin
                            wtipofes = coalesce(wtipofes, 0);
                            if ((wtipofes = 0) or (wtipofes = 1 and UPPER(COALESCE(BDCOLETIVAS, 'FALSE')) = 'TRUE') or (wtipofes = 2 and UPPER(COALESCE(BDCOLETIVAS, 'FALSE')) = 'FALSE')) then
                               begin
                                 bdferiadosfe = bdferiadosfe + 1;
                                 wdataferfim = wdataferfim + 1;
                               end
                          end

                       wdatafer = wdatafer + 1;
                     end
                 end
              else
                 BDREFERENCIA = BDREFPAGABOFE;

              -- Parcelamentos
              if (SUBSTRING(:BDCLASSVER FROM 1 FOR 7) = '3.001.3') then
                 begin
                 wwheredadosemp = 'select first 1 PARCI.BDPARCELAPI, PARC.BDQTDMESESPAR from VRH_EMP_TPARCELAMENTOS_ITENS PARCI '||
                                    'join VRH_EMP_TPARCELAMENTOS PARC on (PARC.BDCODEMP = PARCI.BDCODEMP and PARC.BDCODCOL = PARCI.BDCODCOL and PARC.BDCODPARC = PARCI.BDCODPARC) '||
                                    'where PARCI.BDCODEMP = '||BDCODEMP||' and PARCI.BDCODCOL = '||BDCODCOL;
     
                   if (bdinipergozofe is not null) then
                      wwheredadosemp = wwheredadosemp||' and PARCI.BDREFPI = '||SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2);
                   else
                      wwheredadosemp = wwheredadosemp||' and PARCI.BDREFPI = '||BDREFPAGABOFE;
     
                   wqtdparc = null;
                   wparcela = null;
                   execute statement wwheredadosemp into :wparcela, :wqtdparc;
     
                   if (coalesce(:wparcela, 0) > 0 and coalesce(:wqtdparc, 0) > 0) then
                      begin
                        if (strlen(:bddescver||' '||:wparcela||'/'||:wqtdparc) > 40) then
                           begin
                             wtam = strlen(' '||:wparcela||'/'||:wqtdparc);
                             bddescver = SUBSTRING(bddescver FROM 1 FOR (40 - :wtam))||' '||wparcela||'/'||wqtdparc;
                           end
                        else
                           bddescver = bddescver||' '||wparcela||'/'||wqtdparc;
     
                        if (strlen(:bddescredver||' '||:wparcela||'/'||:wqtdparc) > 20) then
                           begin
                             wtam = strlen(' '||:wparcela||'/'||:wqtdparc);
                             bddescredver = SUBSTRING(bddescredver FROM 1 FOR (20 - :wtam))||' '||wparcela||'/'||wqtdparc;
                           end
                        else
                           bddescver = bddescver||' '||wparcela||'/'||wqtdparc;
                      end
                 end

              bddatarelabono = bdfimperaquisfe - 15;

            while (EXTRACT(WEEKDAY FROM :bddatarelabono) in (0,6)) do   /* Domingo e s??bado */
                bddatarelabono = bddatarelabono - 1;

            wwheredadosemp = 'select first 1 BDCODFERI from TFERIADOSNOVO '||
                               'where  ((coalesce(BDTIPOFERI, 0) = 0 and coalesce(BDMESDIAFERI, 0) > 0) or (coalesce(BDTIPOFERI, 0) = 1 and BDDATAFERI is not null)) and '||
                                  '(coalesce(BDDATAFERI, CAST((SUBSTRING(BDMESDIAFERI FROM 3 FOR 2)||''/''||SUBSTRING(BDMESDIAFERI FROM 1 FOR 2)||''/''||'||SUBSTRING(:prreferencia FROM 1 FOR 4)||') AS DATE)) = '''||bddatarelabono||''') ';
              wempferi = null;
              execute statement wwheredadosemp into :wempferi;
              while (coalesce(wempferi, 0) <> 0) do
                begin
                  bddatarelabono = bddatarelabono - 1;
                wwheredadosemp = 'select first 1 BDCODFERI from TFERIADOSNOVO '||
                                   'where ((coalesce(BDTIPOFERI, 0) = 0 and coalesce(BDMESDIAFERI, 0) > 0) or (coalesce(BDTIPOFERI, 0) = 1 and BDDATAFERI is not null)) and '||
                                      '(coalesce(BDDATAFERI, CAST((SUBSTRING(BDMESDIAFERI FROM 3 FOR 2)||''/''||SUBSTRING(BDMESDIAFERI FROM 1 FOR 2)||''/''||'||SUBSTRING(:prreferencia FROM 1 FOR 4)||') AS DATE)) = '''||bddatarelabono||''') ';
                  wempferi = null;
                  execute statement wwheredadosemp into :wempferi;
                end

              IF (bdinipergozofe IS NULL) THEN
                 BEGIN
                   wmes = CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5) AS INTEGER);
                   wano = CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
                   wrefdadosemp = CAST((CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4) AS VARCHAR(4)) || CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5) AS VARCHAR(2))) AS INTEGER); /*10208 - Ramon*/

                   SELECT ultdia FROM ultimo_dia_mes(:wmes,:wano) INTO wdia;
                   wdataaux = SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4);
                   bdinisws = CAST(wdataaux AS DATE);
                   wdataaux = SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/'||wdia||'/'||SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4);
                   bdfimsws = CAST(wdataaux AS DATE);
                 END
              ELSE
                 BEGIN
                   wrefdadosemp = CAST((SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER); /*10208 - Ramon*/
                   bdinisws = bdinipergozofe;
                   bdfimsws = bdfimpergozofe;
                 END

              if (wempatu = 0) then
                 select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = :BDCODEMP and BDREFEMP <= :prreferencia order by BDREFEMP DESC into :BDREFHOREMP;

              IF (wempatu  = 0 and wcolatu  = 0) THEN
                 begin
                    select first 1 CASE WHEN (FIS.BDNMSOCIAL <> '' and PAR.bdusanomesocial = 'TRUE') THEN FIS.BDNMSOCIAL ELSE cad.BDNOMCOL END Nome_Colaborador from VRH_EMP_TCOLCON_CAD cad
                    left outer join VRH_EMP_TCOLCON_FIS FIS ON (FIS.BDCODEMP = cad.BDCODEMP AND FIS.BDCODCOL = cad.BDCODCOL AND FIS.bdrefcol=cad.bdrefcol)
                    left outer join(select a.bdcodemp,max(a.bdrefemp)bdrefemp from VRHF_BASE_TEMPPAR a group by a.bdcodemp) pmax on  (pmax.BDCODEMP = cad.BDCODEMP)
                    left outer join VRHF_BASE_TEMPPAR PAR  on (par.bdcodemp=pmax.bdcodemp and par.bdrefemp=pmax.bdrefemp)
                   where cad.BDCODEMP = :BDCODEMP and cad.BDCODCOL = :BDCODCOL  order by fis.bdrefcol  DESC into :BDNOMCOL;

                   if (BDNOMCOL is null) then
                    select first 1 CASE WHEN (FIS.BDNMSOCIAL <> '' and PAR.bdusanomesocial = 'TRUE') THEN FIS.BDNMSOCIAL ELSE cad.BDNOMCOL END Nome_Colaborador from VRH_EMP_TCOLCON_CAD cad
                    left outer join VRH_EMP_TCOLCON_FIS FIS ON (FIS.BDCODEMP = cad.BDCODEMP AND FIS.BDCODCOL = cad.BDCODCOL AND FIS.bdrefcol=cad.bdrefcol)
                    left outer join(select a.bdcodemp,max(a.bdrefemp)bdrefemp from VRHF_BASE_TEMPPAR a group by a.bdcodemp) pmax on  (pmax.BDCODEMP = cad.BDCODEMP)
                    left outer join VRHF_BASE_TEMPPAR PAR  on (par.bdcodemp=pmax.bdcodemp and par.bdrefemp=pmax.bdrefemp)
                   where cad.BDCODEMP = :BDCODEMP and cad.BDCODCOL = :BDCODCOL order by fis.bdrefcol  DESC into :BDNOMCOL;

                   select first 1 docref.bdctpscol, docref.bdseriectpscol, docref.bddseriectpscol, tuf_doc.bdsiglauf
                   from VRH_EMP_TCOLCON_DOCREF docref
                   left outer join TUF tuf_doc on (tuf_doc.bdcoduf = docref.bdcoduf)
                   where docref.BDCODEMP = :BDCODEMP and docref.BDCODCOL = :BDCODCOL and docref.BDREFCOL <= :prreferencia
                   order by docref.bdrefcol DESC
                   into :BDCTPSCOL, :BDSERIECTPSCOL, :BDDSERIECTPSCOL, :BDSIGLAUFCTPS;
                 end

              IF (wempatu = 0) THEN
                 wempatu = bdcodemp;

              IF (wcolatu = 0) THEN
                 wcolatu = bdcodcol;

              IF ((wempatu <> bdcodemp) OR (wcolatu <> bdcodcol)) THEN
                 BEGIN
                   select first 1 CASE WHEN (FIS.BDNMSOCIAL <> '' and PAR.bdusanomesocial = 'TRUE') THEN FIS.BDNMSOCIAL ELSE cad.BDNOMCOL END Nome_Colaborador from VRH_EMP_TCOLCON_CAD cad
                   left outer join VRH_EMP_TCOLCON_FIS FIS ON (FIS.BDCODEMP = cad.BDCODEMP AND FIS.BDCODCOL = cad.BDCODCOL AND FIS.bdrefcol=cad.bdrefcol)
                   left outer join(select a.bdcodemp,max(a.bdrefemp)bdrefemp from VRHF_BASE_TEMPPAR a group by a.bdcodemp) pmax on  (pmax.BDCODEMP = cad.BDCODEMP)
                   left outer join VRHF_BASE_TEMPPAR PAR  on (par.bdcodemp=pmax.bdcodemp and par.bdrefemp=pmax.bdrefemp)
                   where cad.BDCODEMP = :BDCODEMP and cad.BDCODCOL = :BDCODCOL  order by fis.bdrefcol  DESC into :BDNOMCOL;

                   if (BDNOMCOL is null) then
                      select first 1 CASE WHEN (FIS.BDNMSOCIAL <> '' and PAR.bdusanomesocial = 'TRUE') THEN FIS.BDNMSOCIAL ELSE cad.BDNOMCOL END Nome_Colaborador from VRH_EMP_TCOLCON_CAD cad
                      left outer join VRH_EMP_TCOLCON_FIS FIS ON (FIS.BDCODEMP = cad.BDCODEMP AND FIS.BDCODCOL = cad.BDCODCOL AND FIS.bdrefcol=cad.bdrefcol)
                      left outer join(select a.bdcodemp,max(a.bdrefemp)bdrefemp from VRHF_BASE_TEMPPAR a group by a.bdcodemp) pmax on  (pmax.BDCODEMP = cad.BDCODEMP)
                      left outer join VRHF_BASE_TEMPPAR PAR  on (par.bdcodemp=pmax.bdcodemp and par.bdrefemp=pmax.bdrefemp)
                      where cad.BDCODEMP = :BDCODEMP and cad.BDCODCOL = :BDCODCOL order by fis.bdrefcol DESC into :BDNOMCOL;

                   select first 1 docref.bdctpscol, docref.bdseriectpscol, docref.bddseriectpscol, tuf_doc.bdsiglauf
                   from VRH_EMP_TCOLCON_DOCREF docref
                   left outer join TUF tuf_doc on (tuf_doc.bdcoduf = docref.bdcoduf)
                   where docref.BDCODEMP = :BDCODEMP and docref.BDCODCOL = :BDCODCOL and docref.BDREFCOL <= :prreferencia
                   order by docref.BDREFCOL DESC
                   into :BDCTPSCOL, :BDSERIECTPSCOL, :BDDSERIECTPSCOL, :BDSIGLAUFCTPS;

                   if (wempatu <> BDCODEMP) then
                        select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = :BDCODEMP and BDREFEMP <= :prreferencia order by BDREFEMP DESC into :BDREFHOREMP;

                   wchave = 1;
                   wempatu = bdcodemp;
                   wcolatu = bdcodcol;
                 END

              bdchave = wchave;
              wchave = wchave + 1;

              wwheredadosemp = ' where e1.BDCODEMP = '||bdcodemp||' and e2.BDREFEMP = (select first 1 bdrefemp from tempresas_ref where bdcodemp = '||bdcodemp||' and bdrefemp <= '||wrefdadosemp||' order by bdrefemp desc)';
              IF (wrefdadosemp > 0) THEN
                BEGIN
                  EXECUTE STATEMENT wsqldadosemp || wwheredadosemp
                INTO :bdnomemp, :bdlogremp, :bdendemp, :bdnumemp, :bdcomplemp, :bdbaiemp, :bdnomcidemp, :bdsiglaufemp, :bdcnpjemp;
                END

              SUSPEND;
            END

        IF (praviso = 1) THEN
           BEGIN
             FOR EXECUTE STATEMENT wSqlAviso INTO
               :bdcodemp, :bdnomemp, :bdlogremp, :bdendemp, :bdnumemp, :bdcomplemp, :bdbaiemp, :bdnomcidemp, :bdsiglaufemp, :bdcnpjemp, :bdcodcol, :BDNOMCOL, :bdchave, :bdctpscol, :bdseriectpscol, :bddseriectpscol,
               :bdsiglaufctps, :bddesctfuc, :bddataadmcol,  :bdiniperaquisfe, :bdfimperaquisfe, :bdcodfe, :bdinipergozofe, :bdfimpergozofe, :bdfaltasfe, :bdsalbasehefe, :bdqtdabonofe, :bddatapagfe, :bdcodver, 
               :bdclassver, :bdtipocodver, :bdordemver, :bddescver, :bddescredver, :bdrefvfe, :bdvalvfe, :bdrefauxver, :bdtiporefver, :bdrefpagabofe, :bdinisws, :bdfimsws, :bdvalliquido, :bdcalca13fe, 
               :bdcoletivas, :bdsalini, :bddiaslicfe, :bddiasferfe, :bddataaviso, :bddepir, :BDTIPOESCALA, :bdcpfcol
              DO
               BEGIN
                 IF (bdinipergozofe IS NULL) THEN
                    BEGIN
                      BDREFERENCIA = BDREFPAGABOFE;
                      wmes = CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5) AS INTEGER);
                      wano = CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
                      wrefdadosemp = CAST((CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4) AS VARCHAR(4)) || CAST(SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5) AS VARCHAR(2))) AS INTEGER); /*10208 - Ramon*/
   
                      SELECT ultdia FROM ultimo_dia_mes(:wmes,:wano) INTO wdia;
                      wdataaux = SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4);
                      bdinisws = CAST(wdataaux AS DATE);
                      wdataaux = SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/'||wdia||'/'||SUBSTRING(CAST(bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4);
                      bdfimsws = CAST(wdataaux AS DATE);

                      SELECT FIRST 1 BDSALBASECOL
                      FROM VRH_EMP_TCOLCON_CALCDIA
                      WHERE BDCODEMP = :BDCODEMP AND BDCODCOL = :BDCODCOL AND BDDATACOL <= SUBSTRING(CAST(:bdrefpagabofe AS VARCHAR(6)) FROM 5)||'/01/'||SUBSTRING(CAST(:bdrefpagabofe AS VARCHAR(6)) FROM 1 FOR 4) ORDER BY BDDATACOL DESC
                      INTO :BDSALBASEFE;
                    END
                 ELSE
                    BEGIN
                      BDREFERENCIA = CAST((SUBSTRING(CAST(bdinipergozofe as VARCHAR(10)) from 1 for 4)||SUBSTRING(CAST(bdinipergozofe as VARCHAR(10)) from 6 for 2)) AS INTEGER);
                      wrefdadosemp = CAST((SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER); /*10208 - Ramon*/
                      bdinisws = bdinipergozofe;
                      bdfimsws = bdfimpergozofe;

                      SELECT FIRST 1 BDSALBASECOL
                      FROM VRH_EMP_TCOLCON_CALCDIA
                      WHERE BDCODEMP = :BDCODEMP AND
                            BDCODCOL = :BDCODCOL AND
                            BDDATACOL <= :BDINIPERGOZOFE
                      ORDER BY BDDATACOL DESC
                      INTO :BDSALBASEFE;
                    END

                   wwheredadosemp = ' where e1.BDCODEMP = '||bdcodemp||' and e2.BDREFEMP = (select first 1 bdrefemp from tempresas_ref where bdcodemp = '||bdcodemp||' and bdrefemp <= '||wrefdadosemp||' order by bdrefemp desc)';
                   IF (wrefdadosemp > 0) THEN
                     BEGIN
                       EXECUTE STATEMENT wsqldadosemp || wwheredadosemp
                       INTO
                         :bdnomemp, :bdlogremp, :bdendemp, :bdnumemp, :bdcomplemp, :bdbaiemp, :bdnomcidemp, :bdsiglaufemp, :bdcnpjemp;
                     END

                 SUSPEND;
               END
           END
      END
END^

/* Restore proc. body: VRHF_SP_REL_DECLARA_RENDIMENTOS */
ALTER PROCEDURE VRHF_SP_REL_DECLARA_RENDIMENTOS(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDTOTALRENDIMENTOS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDVAL13 NUMERIC(15,6),
BDVALPENALI NUMERIC(15,6),
BDVALIND NUMERIC(15,6),
BDVALDIR NUMERIC(15,6),
BDVALDME NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WULTDIA VARCHAR(10);
DECLARE VARIABLE WDIA INTEGER;
DECLARE VARIABLE WANOMES INTEGER;
BEGIN
  wmes = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wanomes = CAST((SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 5 FOR 2)||SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 1 FOR 4)) AS INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wultdia = wmes||'/'||wdia||'/'||wano;

  EXECUTE PROCEDURE sp_seta_competencia(wanomes, NULL, NULL);


  wsql = '  SELECT T.BDCODEMP, empresas.bdnomemp, empresas.bdcnpjemp, T.BDCODCOL, col.bdnomcol, col.bdcpfcol,
           sum(coalesce(T.bdbirrffn, 0.00) +  coalesce(T.BDINSSFN, 0.00) + coalesce(T.bdirrffn, 0.00) + coalesce(T.bddepfn, 0.00) +
               coalesce(FOLC.bdbirrffc, 0.00) +  coalesce(FOLC.bdinssfc, 0.00) + coalesce(FOLC.bdirrffc, 0.00) + coalesce(FOLC.bddepfc , 0.00) +
           coalesce(FERN.BDBASEIRFE + FERN.BDVALORINSSFE + FERN.BDDEPFE, 0.00)) BDTOTALRENDIMENTOS,

           SUM(coalesce(T.bdinssfn, 0.00) +  coalesce(FOLC.bdinssfc, 0.00)) AS BDINSS,
           SUM(coalesce(T.bdirrffn, 0.00) +  coalesce(FOLC.bdirrffc, 0.00)) AS BDIRRF,
           SUM(coalesce(T13.bdval13, 0.00) + coalesce(TC13.bdvalc13,  0.00)) AS BDVAL13,
           SUM(coalesce(TPEN.BDVALPEN, 0.00)) AS BDVALPEN_ALI,
           SUM(coalesce(INDR.BDVALIND, 0.00)) AS BDVAL_IND,
           SUM(coalesce(AJCUSTOS.BDVALDIR, 0.00)) AS BDVAL_DIR,
           SUM(coalesce(DESPM.BDVALDME, 0.00)) AS BDVAL_DMED '||

         ' from VRHF_EMP_TFOLHANORMAL T ' ||
         ' left outer join VRHF_EMP_TFOLHACOMP FOLC on (FOLC.BDCODEMP = T.BDCODEMP and FOLC.BDCODCOL = T.BDCODCOL and FOLC.BDREFFN = T.BDREFFN ) ' ||
         ' left outer join VRH_EMP_TFERIAS FERN on (FERN.BDCODEMP = T.BDCODEMP and FERN.BDCODCOL = T.BDCODCOL and t.bdreffn = CAST((substring((CAST(FERN.bddatapagfe AS VARCHAR(10))) from 1 for 4) || substring((CAST(FERN.bddatapagfe AS VARCHAR(10))) from 6 for 2)) AS INTEGER) )
           left outer join vrhf_emp_t13sal T13 on (T13.BDCODEMP = T.BDCODEMP and T13.BDCODCOL = T.BDCODCOL and T13.bdref13 = T.BDREFFN )
           left outer join vrhf_emp_tc13sal TC13 on (TC13.BDCODEMP = T.BDCODEMP and TC13.BDCODCOL = T.BDCODCOL and TC13.bdrefc13 = T.BDREFFN )
           left outer join VW_VALOR_MES_PENSAO_ALIMENTICIA TPEN on (TPEN.BDCODEMP = T.BDCODEMP and TPEN.BDCODCOL = T.BDCODCOL and TPEN.BDREFPEN = T.BDREFFN)
           left outer join VW_VALOR_MES_INDENIZACAO INDR on (INDR.BDCODEMP = T.BDCODEMP and INDR.BDCODCOL = T.BDCODCOL and INDR.BDREFIND = T.BDREFFN)
           left outer join VW_VALOR_MES_DIARIAS_ACUSTOS AJCUSTOS on (AJCUSTOS.BDCODEMP = T.BDCODEMP and AJCUSTOS.BDCODCOL = T.BDCODCOL and AJCUSTOS.BDREFDIR = T.BDREFFN)
           left outer join VW_VALOR_MES_DESPESAS_MEDICAS DESPM on (DESPM.BDCODEMP = T.BDCODEMP and DESPM.BDCODCOL = T.BDCODCOL and DESPM.BDREFDME = T.BDREFFN)
           left outer join vrh_sp_colcon(null,null,null,null,null, ' || prreffim || ' , '''||wultdia||''' , 1,1,1,1,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0) col  on (T.BDCODEMP = col.BDCODEMP and T.BDCODCOL = col.BDCODCOL)
           left outer join SP_CONSULTAEMPRESAS(null, null, null) empresas on (empresas.bdcodemp = t.bdcodemp )' ;

   wwhere = '';

  IF (:prrefini IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and T.BDREFFN >= '''||:prrefini||''' ';
       ELSE
          wwhere = wwhere||' where T.BDREFFN >= '''||:prrefini||''' ';
    END

  IF (:prreffim IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and T.BDREFFN <= '''||:prreffim||''' ';
       ELSE
          wwhere = wwhere||' where T.BDREFFN <= '''||:prreffim||''' ';
    END

  IF (:PRCODEMP IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       ELSE
          wwhere = ' where ';

       wwhere = wwhere||:PRCODEMP;
     END

  IF (:PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||:PRCODCOL;
     END

  IF (prfuncao > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'col.bdcodtfuc = '||prfuncao||' ';  -- funcionario
     END

  IF (prsindicato > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere||'col.bdCODSINTRAB = '||prsindicato||' ';  -- TCOLVINC.
     END

  IF (prclasse > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'col.bdCODCLA = '||prclasse||' '; -- tcolcon_vinc
     END



 wsql = wsql||wwhere || ' GROUP BY T.BDCODEMP, empresas.bdnomemp, empresas.bdcnpjemp, T.BDCODCOL, col.bdnomcol, col.bdcpfcol ORDER BY T.BDCODEMP, T.BDCODCOL ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdnomemp,
    :bdcnpjemp,
    :BDCODCOL,
    :bdnomcol,
    :bdcpfcol,
    :BDTOTALRENDIMENTOS,
    :bdinss,
    :bdirrf,
    :bdval13,
    :BDVALPENALI,
    :BDVALIND,
    :BDVALDIR,
    :BDVALDME
  DO
  IF (bdtotalrendimentos > 0) THEN
     SUSPEND;
END
^

/* Restore proc. body: SP_VRHF_DECLARACAO_DOMESTICO */
create or alter procedure SP_VRHF_DECLARACAO_DOMESTICO (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRANOBASE integer,
    PRTOMADOR integer,
    PRCODSIND integer,
    PRCLASSE integer,
    PRFUNCAO integer,
    PRORDEM varchar(50),
    PRDATAEMISSAO varchar(10),
    PRSITUACAO integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDDATAADM date,
    BDDATARESCISAO date,
    BDPIS varchar(14),
    BDCPF varchar(14),
    BDCOMPETENCIA integer,
    BDSALMIN numeric(15,6),
    BDBINSSN numeric(15,6),
    BDBINSSFE numeric(15,6),
    BDBINSS13 numeric(15,6),
    BDREMUNERACAO numeric(18,6),
    BDINSSPATRONAL numeric(15,6),
    BDDIFERENCAINSS numeric(15,6),
    BDTOTALCONTRPATRONAL numeric(15,6),
    BDPARCELANAODEDUTIVEL numeric(15,6),
    BDINF varchar(20),
    BDORDEM varchar(50),
    BDDATAEMISSAO varchar(10),
    BDANOBASE integer)
as
declare variable WULTDIA varchar(10);
declare variable WPRIDIA varchar(10);
declare variable WDIA varchar(10);
declare variable WMES varchar(10);
declare variable WORDEM varchar(50);
declare variable WPRIDIAEMISSAO varchar(10);
declare variable WULTDIAEMISSAO varchar(10);
declare variable WWHERE varchar(30000);
declare variable WSQLALIQ varchar(500);
declare variable WSQL varchar(30000);
declare variable WALIQINSS numeric(18,6);
declare variable WBASE numeric(18,6);
BEGIN
  wpridia = '01/01/'||pranobase;
  wultdia = '12/31/'||pranobase;

  wmes = SUBSTRING(:prdataemissao FROM 4 FOR 2);
  SELECT ultdia FROM ultimo_dia_mes(:wmes, :pranobase) INTO :wdia;
  wpridiaemissao = wmes||'/01/'||pranobase;
  wultdiaemissao = wmes||'/'||wdia||'/'||pranobase;

  wwhere = '';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
     BEGIN
       wwhere = ' where ' || prcodemp;

       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          wwhere = wwhere || ' and ' || prcodcol;
     END
  ELSE
     BEGIN
       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          wwhere = ' where ' || prcodcol;
     END

  IF (prtomador > 0) THEN
     wordem = ', ORDEM ';
  ELSE
     wordem = ', null ';

  wsql = 'select distinct BDCODEMPRESA, BDCODCOLABORADOR, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, RESC.BDDATARESCISAO, DOCREF.BDPISCOL, COL.BDCPFCOL, REF, ' ||
         'max(SALMIN.BDSALMIN) SALMIN, COALESCE(INSS, 0), COALESCE(INSSFE, 0), COALESCE(INSS13, 0), INF ' || wordem;

  IF (prtomador > 0) THEN
     wordem = ', NULL AS ORDEM ';
  ELSE
     wordem = '';

  wsql = wsql || 'from (select FN.BDCODEMP as BDCODEMPRESA, FN.BDCODCOL as BDCODCOLABORADOR, FN.BDREFFN as REF, ' ||
         'FN.BDBINSSFN as INSS, FN.BDBINSSFEFOLFN as INSSFE, FN.BDBINSS13FN as INSS13, '''' as INF ' || wordem || ' from VRHF_EMP_TFOLHANORMAL FN ' || wwhere;

  wsql = wsql || ' union all select FC.BDCODEMP as BDCODEMPRESA, FC.BDCODCOL as BDCODCOLABORADOR, FC.BDREFCOMP as REF, ' ||
            'FC.BDBINSSFC as INSS, FC.BDBINSSFEFOLFC as INSSFE, FC.BDBINSS13FC as INSS13, ''Fol. Compl.'' as INF' || wordem || ' from VRHF_EMP_TFOLHACOMP FC ' || wwhere;

  wsql = wsql || ' union all select F13SAL.BDCODEMP as BDCODEMPRESA, F13SAL.BDCODCOL as BDCODCOLABORADOR, F13SAL.BDREF13 as REF, ' ||
            'F13SAL.BDBASEINSS13 as INSS, 0 as INSSFE, 0 as INSS13, ''13º Sal.'' as INF' || wordem || ' from VRHF_EMP_T13SAL F13SAL ' || wwhere;

  IF (prtomador > 0) THEN
     wordem = ', FT.BDORDEM AS ORDEM ';

  wsql = wsql || ' union all select FT.BDCODEMP as BDCODEMPRESA, FT.BDCODCOL as BDCODCOLABORADOR, FT.BDREFTOMADOR as REF, ' ||
            'SUM(FT.BDBINSSFT) as INSS, SUM(FT.BDBINSSFEFOLFT) as INSSFE, SUM(FT.BDBINSS13FT) as INSS13, '''' as INF' || wordem || ' from VRHF_EMP_TFOLHATOMADOR FT ' || wwhere ||
            ' group by REF, BDCODEMPRESA, BDCODCOLABORADOR, INF';

  IF (prtomador > 0) THEN
     BEGIN
       wsql = wsql || ', FT.BDORDEM ';
       wordem = ', FTC.BDORDEM AS ORDEM ';
     END

  wsql = wsql || ' union all select FTC.BDCODEMP as BDCODEMPRESA, FTC.BDCODCOL as BDCODCOLABORADOR, FTC.bdreftomador as REF, ' ||
            'FTC.BDBINSSFC as INSS, FTC.BDBINSSFEFOLFC as INSSFE, FTC.BDBINSS13FC as INSS13, ''Fol. Compl'' as INF' || wordem || ' from VRHF_EMP_TFOLTOMCOMP FTC ' || wwhere;

  IF (prtomador > 0) THEN
     wordem = ', FER.BDORDEM AS ORDEM';

  wsql = wsql || ' union all select FER.BDCODEMP as BDCODEMPRESA, FER.BDCODCOL as BDCODCOLABORADOR, FER.BDREFINIFE as REF, ' ||
            'FER.BDBASEINSSFE as INSS, 0 as INSSFE, 0 as INSS13, ''Férias'' as INF' || wordem || ' from VRH_EMP_TFERIAS FER ' || wwhere || ') ';

  wsql = wsql || 'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = BDCODEMPRESA and COL.BDCODCOL = BDCODCOLABORADOR) ' ||
         'left outer join VRH_EMP_TCOLCON_DOC DOC on (DOC.BDCODEMP = COL.BDCODEMP and DOC.BDCODCOL = COL.BDCODCOL) ' ||
         'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = BDCODEMPRESA and RESC.BDCODCOL = BDCODCOLABORADOR) ' ||
         'left outer join VRHF_TABELAS_TSALMIN SALMIN on (SALMIN.BDREFSM <= REF) ' ||
         'left outer join VRH_EMP_TCOLCON_VINC VINC on (VINC.BDCODEMP = BDCODEMPRESA and VINC.BDCODCOL = BDCODCOLABORADOR) ' ||
         'left outer join VRH_BASE_TCLASSE CLAS on (VINC.BDCODCLA = CLAS.BDCODCLA) ' ||
         'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = BDCODEMPRESA and COLCAD.BDCODCOL = BDCODCOLABORADOR) ' ||
         'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = BDCODEMPRESA and DOCREF.BDCODCOL = BDCODCOLABORADOR) ';

  -- Filtros
  IF (prtomador > 0) THEN
     BEGIN
       wsql = wsql || 'left outer join VRHF_EMP_TPREPFN PREP on (prep.bdcodemp = bdcodempresa and prep.bdcodcol = bdcodcolaborador and prep.bdordem = ordem) ';
     END

  IF (prcodsind > 0) THEN
     wsql = wsql || 'left outer join VRH_EMP_TCOL_VINC VINC2 on (vinc2.bdcodemp = bdcodempresa and vinc2.bdcodcol = bdcodcolaborador) ';

  IF (prfuncao > 0) THEN
     wsql = wsql || 'left outer join VRH_EMP_TCOL_VINCDIA coldia on (coldia.bdcodemp = bdcodempresa and coldia.bdcodcol = bdcodcolaborador) ';

  IF (prsituacao = 0) THEN
     wSql = wSql || ' join SP_SOMENTE_ATIVOS(''' || wpridia || ''', ''' || wultdia || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ';

  IF (prsituacao = 2) THEN
     wSql = wSql || ' join SP_SOMENTE_DEMITIDOS(''' || wultdia || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 3) THEN
     wSql = wSql || ' join SP_SOMENTE_ADMITIDOS_MES(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 4) THEN
     wSql = wSql || ' join SP_SOMENTE_DEMITIDOS_MES(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 5) THEN
     wSql = wSql || ' join SP_ATIVOS_SEM_DEMITIDOS_MES(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 6) THEN
     wSql = wSql || ' join SP_ATI_SEM_DEM_COM_TRANSF(''' || wpridia || ''',''' || wultdia || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 7) THEN
     wSql = wSql || ' join SP_ATI_SEM_AFAST_MES_INT(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  IF (prsituacao = 8) THEN
     wSql = wSql || ' join SP_AFASTADOS_MES_INTEIRO(''' || wpridiaemissao || ''',''' || wultdiaemissao || ''') Y on (y.bdcodemp = bdcodempresa and y.bdcodcol = bdcodcolaborador) ' ;

  -- Where e filtros
  wwhere = ' where clas.bdgrupocla = 7 and SUBSTRING(CAST(REF AS VARCHAR(6)) FROM 1 FOR 4) = ' || pranobase;

  IF (prtomador > 0) THEN
     BEGIN
       wwhere = wwhere || ' and prep.bdcodtpcc = '||prtomador;
       wordem = ', ORDEM ';
     END
  ELSE
     wordem = '';

  IF (prcodsind > 0) THEN
     wwhere = wwhere||' and vinc2.bdcodsintrab = '||prcodsind;

  IF (prclasse > 0) THEN
     wwhere = wwhere||' and vinc.bdcodcla = '||prclasse;

  IF (prfuncao > 0) THEN
     wwhere = wwhere||' and coldia.bdcodtfuc = '||prfuncao;

  wsql = wsql || wwhere || ' group by BDCODEMPRESA, BDCODCOLABORADOR, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, RESC.BDDATARESCISAO, DOCREF.BDPISCOL, COL.BDCPFCOL, REF, ' ||
         'INSS, INSSFE, INSS13, INF ' || wordem;

  IF (prordem IS NOT NULL AND prordem <> '') THEN
     BEGIN
       IF (PRORDEM = 'BDCODCOL') THEN
          wsql = wsql || 'ORDER BY BDCODEMPRESA, BDCODCOLABORADOR, REF, INF ';
       ELSE
          wsql = wsql || 'ORDER BY BDCODEMPRESA, COLCAD.BDNOMCOL, REF, INF ';
     END
  ELSE
     wsql = wsql || 'ORDER BY BDCODEMPRESA, REF, INF ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :bdcodcol,
    :bdnomcol,
    :bddataadm,
    :bddatarescisao,
    :bdpis,
    :bdcpf,
    :bdcompetencia,
    :bdsalmin,
    :bdbinssn,
    :bdbinssfe,
    :bdbinss13,
    :bdinf,
    :bdordem
  DO
    BEGIN
      bdremuneracao = bdbinssn + bdbinssfe + bdbinss13;
      bddataemissao = prdataemissao;
      bdanobase = pranobase;
      bdtotalcontrpatronal  = bdremuneracao * 12 / 100;

      IF ((bdremuneracao - bdsalmin) > 0) THEN
         bdparcelanaodedutivel = (bdremuneracao - bdsalmin) * 12 / 100;
      ELSE
         bdparcelanaodedutivel = 0;

      wbase = 0;
      IF (bdbinssn IS NOT NULL AND bdbinssn > 0) THEN
         BEGIN
           wbase = bdbinssn;
           wsqlaliq = 'select fol.bdaliqinssfn from vrhf_emp_tfolhanormal fol where fol.bdcodemp = '
                || bdcodemp || ' and fol.bdcodcol = ' || bdcodcol || ' and fol.bdreffn = ' || bdcompetencia;
         END
      ELSE
      IF (bdbinssfe IS NOT NULL AND bdbinssfe > 0) THEN
         BEGIN
           wbase = bdbinssfe;
           wsqlaliq = 'select fol.bdaliqinssfefolfn from vrhf_emp_tfolhanormal fol where fol.bdcodemp = '
           || bdcodemp || ' and fol.bdcodcol = ' || bdcodcol || ' and fol.bdreffn = ' || bdcompetencia;
         END
      ELSE
      IF (bdbinss13 IS NOT NULL AND bdbinss13 > 0) THEN
        BEGIN
          wbase = bdbinss13;
          wsqlaliq = 'select fol.bdaliqinss13fn vrhf_emp_tfolhanormal fol where fol.bdcodemp = '
          || bdcodemp || ' and fol.bdcodcol = ' || bdcodcol || ' and fol.bdreffn = ' || bdcompetencia;
        END
      ELSE
      -- Não tem cálculo nenhum
        wsqlaliq = '';

      IF (wsqlaliq IS NOT NULL AND wsqlaliq <> '') THEN
        BEGIN
          FOR EXECUTE STATEMENT wsqlaliq
          INTO
            :waliqinss
          DO
            BEGIN
              bdinsspatronal = wbase * waliqinss / 100;
            
              IF (bdremuneracao < bdsalmin) THEN
                 bddiferencainss = 0;
              ELSE
                 bddiferencainss = (bdremuneracao - bdsalmin) * waliqinss / 100;
            END
        END
      ELSE
        BEGIN
          bdinsspatronal = 0;
          bddiferencainss = 0;
        END

      SUSPEND;
    END
END
^

/* Restore proc. body: VRHF_SP_REL_LIQUIDO_FOLHA */
ALTER PROCEDURE VRHF_SP_REL_LIQUIDO_FOLHA(PRCODEMP VARCHAR(25000),
PRCODCOL VARCHAR(32700),
PRANOMES INTEGER,
PRULTDIAMES DATE,
PRTABELA VARCHAR(300),
PRDATANULL INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDCODBAN INTEGER,
BDNOMBAN VARCHAR(60),
BDCODAG INTEGER,
BDCODAGBAN VARCHAR(5),
BDCODAGBANDV VARCHAR(2),
BDCTADEPCOL VARCHAR(15),
BDDIGCTADEPCOL VARCHAR(2),
BDTIPOCTACOL INTEGER,
BDDATAADMCOL DATE,
BDDESCTFUC VARCHAR(40),
BDREF INTEGER,
SALBASE NUMERIC(15,6),
PROVE NUMERIC(15,6),
DESCO NUMERIC(15,6),
LIQ NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(PRANOMES, NULL, PRULTDIAMES);

  wsql = 'select t.bdcodemp, '||
                'emp.bdnomemp, '||
                't.BDCODCOL, '||
                'col.bdnomcol, '||
                'col.bdcpfcol, '||
                'col.bdcodban, '||
                'CadBan.bdnomban, '||
                'col.bdcodag, '||
                'ban.bdcodagban, '||
                'ban.bdcodagbandv, '||
                'col.BDCTADEPCOL, '||
                'col.BDDIGCTADEPCOL, '||
                'col.BDTIPOCTACOL, '||
                'col.bddataadmcol, '||
                'colfunc.BDDESCTFUC, '||
                't.BDREF, '||
                't.BDSALBASE SALBASE , '||
                'SUM(t.BDPROVENTO) PROVE, '||
                'SUM(t.BDDESCONTO) DESCO, '||
                'SUM(t.BDPROVENTO) - SUM(t.BDDESCONTO) LIQ ';

  wsql = wsql||'from '||prtabela||'(';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||''''||prcodemp||''', ';
  ELSE
     wsql = wsql||'null, ';

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wsql = wsql||''''||prcodcol||''', ';
  ELSE
     wsql = wsql||'null, ';

  wsql = wsql||pranomes;

  IF (prdatanull IS NOT NULL) THEN
     wsql = wsql||', null) T ';
  ELSE
     wsql = wsql||') T ';

  wsql = wsql||'join VW_COLABORADORES_REF_ATUAL col '||
                 'on (T.BDCODEMP = col.BDCODEMP and T.BDCODCOL = col.BDCODCOL) ';
  wsql = wsql||'left outer join VW_VRH_EMP_TCOL_VINCDIA coldia '||
                 'on (T.BDCODEMP = coldia.BDCODEMP and T.BDCODCOL = coldia.BDCODCOL) ';
  wsql = wsql||'left outer join TBANCOS_AG BAN '||
                 'on (col.bdcodban = ban.bdcodban and  col.bdcodag = ban.bdcodag) ';
  wsql = wsql||'left outer join tBancos CadBan '||
                 'on (col.bdcodban = Cadban.bdcodban) ';
  wsql = wsql||'left outer join VW_TEMPRESAS_REF emp '||
                 'on (t.bdcodemp = emp.bdcodemp ) ';
  wsql = wsql||'left outer join VRH_FUNCOES_TFUC colfunc '||
                 'on (coldia.BDCODPLAFUC = colfunc.BDCODPLAFUC and coldia.BDCODTFUC = colfunc.BDCODTFUC) ';

  wsql = wsql||'group by t.BDCODEMP, emp.bdnomemp, T.BDCODCOL, col.bdnomcol, col.bddataadmcol, t.BDSALBASE, col.BDCODCOL, col.bdcodban, CadBan.bdnomban, col.bdcodag, '||
                        'col.BDCTADEPCOL, col.BDDIGCTADEPCOL, col.BDTIPOCTACOL, col.bdcpfcol, colfunc.BDDESCTFUC, t.bdref, ban.bdcodagban, ban.bdcodagbandv ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDNOMEMP,
    :BDCODCOL,
    :BDNOMCOL,
    :BDCPFCOL,
    :BDCODBAN,
    :BDNOMBAN,
    :BDCODAG,
    :BDCODAGBAN,
    :BDCODAGBANDV,
    :BDCTADEPCOL,
    :BDDIGCTADEPCOL,
    :BDTIPOCTACOL,
    :BDDATAADMCOL,
    :BDDESCTFUC,
    :BDREF,
    :SALBASE,
    :PROVE,
    :DESCO,
    :LIQ
  DO
  SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_REL_PREVIA_RESC */
CREATE OR ALTER PROCEDURE VRHF_SP_REL_PREVIA_RESC (
    PREMPRESA VARCHAR(10000),
    PRCOLABORADOR VARCHAR(32700),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRFUNCAO INTEGER,
    PRSINDICATO INTEGER,
    PRCLASSE INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP VARCHAR(18),
    BDCODCOL INTEGER,
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL VARCHAR(14),
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDBAIEMP DM_BDBAIRRO,
    BDNOMCID VARCHAR(40),
    BDSIGLAUFEMP VARCHAR(2),
    BDCEPEMP VARCHAR(9),
    BDCODCNAE INTEGER,
    BDPISCOL VARCHAR(14),
    BDLOGRCOL VARCHAR(15),
    BDENDCOL VARCHAR(60),
    BDNUMCOL DM_NUMEND,
    BDBAICOL VARCHAR(50),
    BDCEPCOL VARCHAR(9),
    BDNOMCIDCOL VARCHAR(40),
    BDSIGLAUFCOL VARCHAR(2),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDATANASCCOL DATE,
    BDNOMMAECOL VARCHAR(70),
    BDDATAADMCOL DATE,
    BDCATEGORIACOL INTEGER,
    BDDATAAVPREVIO DATE,
    BDCHAVEINDENTIFICACAO VARCHAR(49),
    BDDESCPRES VARCHAR(110),
    BDCODSAQUE INTEGER,
    BDDATARESCISAO DATE,
    BDDATAPAGRESCISAO DATE,
    BDCAMPO29 NUMERIC(15,2),
    BDCAMPO30 NUMERIC(15,2),
    BDCAMPO30REF INTEGER,
    BDCAMPO31 NUMERIC(15,2),
    BDCAMPO31REF INTEGER,
    BDCAMPO32 NUMERIC(15,2),
    BDCAMPO32REF INTEGER,
    BDCAMPO33 NUMERIC(15,2),
    BDCAMPO33REF INTEGER,
    BDCAMPO34 NUMERIC(15,2),
    BDCAMPO34REF INTEGER,
    BDCAMPO35 NUMERIC(15,2),
    BDCAMPO35REF INTEGER,
    BDCAMPO36 NUMERIC(15,2),
    BDCAMPO36REF INTEGER,
    BDCAMPO37 NUMERIC(15,2),
    BDCAMPO38 NUMERIC(15,2),
    BDCAMPO39 NUMERIC(15,2),
    BDCAMPO40 NUMERIC(15,2),
    BDCAMPO40REF INTEGER,
    BDCAMPO41 NUMERIC(15,2),
    BDCAMPO42 NUMERIC(15,2),
    BDCAMPO43 NUMERIC(15,2),
    BDCAMPO44 NUMERIC(15,2),
    BDCAMPO45 NUMERIC(15,2),
    BDCAMPO46BRUTO NUMERIC(15,2),
    BDCAMPO47 NUMERIC(15,2),
    BDCAMPO48 NUMERIC(15,2),
    BDCAMPO49 NUMERIC(15,2),
    BDCAMPO50 NUMERIC(15,2),
    BDCAMPO51 NUMERIC(15,2),
    BDCAMPO52 NUMERIC(15,2),
    BDCAMPO53 NUMERIC(15,2),
    BDCAMPO54TOTDED NUMERIC(15,2),
    BDCAMPO55LIQREC NUMERIC(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WULTDIA VARCHAR(10);
DECLARE VARIABLE WDIA INTEGER;
DECLARE VARIABLE WANOMES INTEGER;
DECLARE VARIABLE WDATAINICIAL VARCHAR(10);
DECLARE VARIABLE WDATAFINAL VARCHAR(10);
DECLARE VARIABLE WTOTALBRUTO NUMERIC(15,2);
DECLARE VARIABLE WTOTALDEDUCOES NUMERIC(15,2);
DECLARE VARIABLE WDATARESC INTEGER;
BEGIN

  wmes = CAST(SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wanomes = CAST((SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 5 FOR 2)||SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 1 FOR 4)) AS INTEGER);
  wdatainicial = wmes||'/'||'01'||'/'||wano;

  wmes = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wanomes = CAST((SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 5 FOR 2)||SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 1 FOR 4)) AS INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wultdia = wmes||'/'||wdia||'/'||wano;
  wdatafinal = wmes||'/'||wdia||'/'||wano;

  EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);

  wsql =   ' SELECT RESC.bdcodemp, EMPR.bdnomemp , emp.bdcnpjemp, RESC.bdcodcol, colcad.bdnomcol,  colcon_doc.bdcpfcol,
            empr.bdlogremp, empr.bdendemp , empr.bdnumemp, empr.bdbaiemp, cidemp.bdnomcid, ufemp.bdsiglauf, empr.bdcepemp, empr.bdcodcnae,
            docref.bdpiscol, colcad.bdlogrcol, colcad.bdendcol, colcad.bdnumcol, colcad.bdbaicol, colcad.bdcepcol,
            spcidadecol.bdnomcid, spufcol.bdsiglauf , docref.bdctpscol, docref.bdseriectpscol,
            colcon.bddatanasccol, col_parent.bdnommaecol, colcon.bddataadmcol, colcon_fgts.bdcategoriacol, RESC.bddataavprevioprev, RESC.bdchaveindentificacaoprev,
            preresc.bddescpres, preresc.bdcodsaque, resc.bddatarescisaoprev, resc.bddatapagrescisaoprev

           from vrh_emp_trescisao_previa RESC
           join tempresas emp on (emp.bdcodemp = RESC.bdcodemp)
           join VW_TEMPRESAS_REF empr on (empr.bdcodemp = RESC.bdcodemp )
           join VRH_BASE_TPREPRESC PRERESC on (preresc.bdcodpres = resc.bdcodpres)
           join vrh_emp_tcolcon colcon on (colcon.bdcodemp = resc.bdcodemp and colcon.bdcodcol = resc.bdcodcol)
           left outer join vw_vrh_emp_tcolcon_cad colcad on (colcad.bdcodemp = resc.bdcodemp and colcad.bdcodcol = resc.bdcodcol)
           join vrh_emp_tcolcon_doc colcon_doc on (colcon_doc.bdcodemp = resc.bdcodemp and colcon_doc.bdcodcol = resc.bdcodcol)
           left outer join vrh_emp_tcol_doc col_doc on (col_doc.bdcodemp = resc.bdcodemp and col_doc.bdcodcol = resc.bdcodcol)
           left outer join vrh_emp_tcol_parent col_parent on (col_parent.bdcodemp = resc.bdcodemp and col_parent.bdcodcol = resc.bdcodcol)
           left outer join vw_vrhf_emp_tcolcon_fgtsgps colcon_fgts on (colcon_fgts.bdcodemp = resc.bdcodemp and colcon_fgts.bdcodcol = resc.bdcodcol)
           left outer join tcidade spcidadecol on (spcidadecol.bdcodcid = colcad.bdcodcid)
           left outer join tuf spufcol on (spufcol.bdcoduf = spcidadecol.bdcoduf)
           left outer join tcidade cidemp on (cidemp.bdcodcid = empr.bdcodcid)
           left outer join tuf ufemp on (ufemp.bdcoduf = cidemp.bdcoduf)  
           left outer join vw_colaboradores_ref_atual refatu on (refatu.bdcodemp = RESC.bdcodemp and refatu.bdcodcol = RESC.BDCODCOL)
           left outer join vw_tcolcon_vincdia vincdia on (vincdia.bdcodemp = RESC.bdcodemp and vincdia.bdcodcol = RESC.bdcodcol)
           join vw_vrh_emp_tcolcon_docref docref on (docref.bdcodemp = resc.bdcodemp and docref.bdcodcol = resc.bdcodcol)';          --Sol:16861 Marcelo B. M. 23/01/2017

  wwhere = '';

  IF (:prrefini IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and RESC.bddatarescisaoprev >= '''||:wdatainicial||''' ';
       ELSE
          wwhere = wwhere||' where RESC.bddatarescisaoprev >= '''||:wdatainicial||''' ';
    END

  IF (:prreffim IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and RESC.bddatarescisaoprev <= '''||:wdatafinal||''' ';
       ELSE
          wwhere = wwhere||' where RESC.bddatarescisaoprev <= '''||:wdatafinal||''' ';
    END


  IF (prempresa <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prempresa||' ';
     END


  IF (prcolaborador <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador||' ';
     END

  IF (prfuncao > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'vincdia.bdcodtfuc = '||prfuncao||' ';  -- funcionario Sol:16861 Marcelo B. M. 23/01/2017
     END

  IF (prsindicato > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere||'refatu.bdCODSINTRAB = '||prsindicato||' ';  -- TCOLVINC. Sol:16861 Marcelo B. M. 23/01/2017
     END

  IF (prclasse > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'refatu.bdCODCLA = '||prclasse||' '; -- tcolcon_vinc Sol:16861 Marcelo B. M. 23/01/2017
     END



 wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdnomemp,
    :bdcnpjemp,
    :BDCODCOL,
    :bdnomcol,
    :bdcpfcol,
    :bdlogremp,
    :bdendemp,
    :bdnumemp,
    :bdbaiemp,
    :bdnomcid,
    :bdsiglaufemp,
    :bdcepemp,
    :bdcodcnae,
    :bdpiscol,
    :bdlogrcol,
    :bdendcol,
    :bdnumcol,
    :bdbaicol,
    :bdcepcol,
    :bdnomcidcol,
    :bdsiglaufcol,
    :bdctpscol,
    :bdseriectpscol,
    :bddatanasccol,
    :bdnommaecol,
    :bddataadmcol,
    :bdcategoriacol,
    :bddataavprevio,
    :bdchaveindentificacao,
    :bddescpres,
    :bdcodsaque, 
    :bddatarescisao,
    :bddatapagrescisao
    DO

    BEGIN

      wdataresc = CAST((SUBSTRING((CAST(:bddatarescisao AS VARCHAR(10))) FROM 1 FOR 4) || SUBSTRING((CAST(:bddatarescisao AS VARCHAR(10))) FROM 6 FOR 2)) AS INTEGER);

      wTotalBruto = 0;
      wTotalDeducoes = 0;

      bdcampo29 = 0;    bdcampo30 = 0;      bdcampo30ref = 0;  bdcampo31 = 0;     bdcampo31ref = 0;
      bdcampo32 = 0;    bdcampo32ref = 0;   bdcampo33 = 0;     bdcampo33ref = 0;  bdcampo34 = 0;
      bdcampo34ref = 0; bdcampo35 = 0;      bdcampo35ref = 0;  bdcampo36 = 0;     bdcampo36ref = 0;  bdcampo37 = 0;
      bdcampo38 = 0;    bdcampo39 = 0;      bdcampo40 = 0;     bdcampo41 = 0;     bdcampo42 = 0;     bdcampo43 = 0;
      bdcampo44 = 0;    bdcampo45 = 0;      bdcampo46bruto = 0;bdcampo47 = 0;     bdcampo48 = 0;     bdcampo49 = 0;
      bdcampo50 = 0;    bdcampo51 = 0;      bdcampo52 = 0;     bdcampo53 = 0;     bdcampo54totded = 0;

      -- CAMPO 29
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.001.2.1%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)

         INTO
         :bdcampo29;

      IF (:bdcampo29 IS NULL) THEN
         bdcampo29 = 0;

      wTotalBruto = wTotalBruto + bdcampo29;

      -- campo 30
      SELECT SUM(BDVALVFNPR),SUM(BDREFVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.001.0.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo30,
      :bdcampo30ref;

      IF (:bdcampo30 IS NULL) THEN
        BEGIN
          bdcampo30 = 0;
          bdcampo30ref = 0;
        END

      wTotalBruto = wTotalBruto + bdcampo30;

      -- campo 31

      SELECT SUM(BDVALVFNPR),SUM(BDREFVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.050.0.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo31,
      :bdcampo31ref;

      IF (:bdcampo31 IS NULL) THEN
        BEGIN
          bdcampo31 = 0;
          bdcampo31ref = 0;
        END

      wTotalBruto = wTotalBruto + bdcampo31;

      -- campo 32
      SELECT SUM(BDVALVFNPR),SUM(BDREFVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.060.0.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo32,
      :bdcampo32ref;

      IF (:bdcampo32 IS NULL) THEN
        BEGIN
          bdcampo32 = 0;
          bdcampo32ref = 0;
        END

      wTotalBruto = wTotalBruto + bdcampo32;

      -- campo 33
      SELECT SUM(BDVALVFNPR),SUM(BDREFVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.030.0.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo33,
      :bdcampo33ref;

      IF (:bdcampo33 IS NULL) THEN
        BEGIN
          bdcampo33 = 0;
          bdcampo33ref = 0;
        END

      wTotalBruto = wTotalBruto + bdcampo33;

      -- campo 34
      SELECT SUM(BDVALVFNPR),SUM(BDREFVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.010.0.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo34,
      :bdcampo34ref;

      IF (:bdcampo34 IS NULL) THEN
        BEGIN
         bdcampo34 = 0;
         bdcampo34ref = 0;
        END

      wTotalBruto = wTotalBruto + bdcampo34;

      -- campo 35
      SELECT SUM(BDVALVFNPR),SUM(BDREFVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.012.0.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo35,
      :bdcampo35ref;

      IF (:bdcampo35 IS NULL) THEN
        BEGIN
         bdcampo35 = 0;
         bdcampo35ref = 0;
        END

      wTotalBruto = wTotalBruto + bdcampo35;

      -- campo 36
      SELECT SUM(BDVALVFNPR),SUM(BDREFVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '9.050.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo36,
      :bdcampo36ref;

      IF (:bdcampo36 IS NULL) THEN
        BEGIN
         bdcampo36 = 0;
         bdcampo36ref = 0;
        END

      wTotalBruto = wTotalBruto + bdcampo36;

     -- CAMPO 37
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '0.002.0.2%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo37;

      IF (:bdcampo37 IS NULL) THEN
         bdcampo37 = 0;                             

      wTotalBruto = wTotalBruto + bdcampo37;

      -- CAMPO 38
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '0.001.3.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo38;

      IF (:bdcampo38 IS NULL) THEN
         bdcampo38 = 0;

      wTotalBruto = wTotalBruto + bdcampo38;

      -- campo 39
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '0.003.0.0%')
            JOIN VW_VERBAS_REF_ATUAL VER ON (VER.BDCODVER = x.bdcodver)
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER AND ver.bdtipocodver = 0)
      INTO
      :bdcampo39;

      IF (:bdcampo39 IS NULL) THEN
         bdcampo39 = 0;

      wTotalBruto = wTotalBruto + bdcampo39;

     -- campo 40
      SELECT SUM(BDVALVFNPR),SUM(BDREFVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '0.006%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo40,
      :bdcampo40ref;

      IF (:bdcampo40 IS NULL) THEN
        BEGIN
          bdcampo40 = 0;
          bdcampo40ref = 0;
        END

      wTotalBruto = wTotalBruto + bdcampo40;

      -- campo 41
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '0.002.0.0%')
            JOIN VW_VERBAS_REF_ATUAL VER ON (VER.BDCODVER = x.bdcodver)
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER AND ver.bdtipocodver = 0)
      INTO

      :bdcampo41;

      IF (:bdcampo41 IS NULL) THEN
         bdcampo41 = 0;

      wTotalBruto = wTotalBruto + bdcampo41;

      -- campo 42
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.001.1.2%')
            JOIN VW_VERBAS_REF_ATUAL VER ON (VER.BDCODVER = x.bdcodver)
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER AND ver.bdtipocodver = 0)
      INTO

      :bdcampo42;

      IF (:bdcampo42 IS NULL) THEN
         bdcampo42 = 0;

      wTotalBruto = wTotalBruto + bdcampo42;

      -- campo 43
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.032.0.0%')
            JOIN VW_VERBAS_REF_ATUAL VER ON (VER.BDCODVER = x.bdcodver)
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER AND ver.bdtipocodver = 0)
      INTO
      :bdcampo43;

      IF (:bdcampo43 IS NULL) THEN
         bdcampo43 = 0;

      wTotalBruto = wTotalBruto + bdcampo43;

      -- campo 44
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.032.1%')
            JOIN VW_VERBAS_REF_ATUAL VER ON (VER.BDCODVER = x.bdcodver)
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER AND ver.bdtipocodver = 0)
      INTO
      :bdcampo44;

      IF (:bdcampo44 IS NULL) THEN
         bdcampo44 = 0;

      wTotalBruto = wTotalBruto + bdcampo44;

      bdcampo46bruto = wTotalBruto; -- Total bruto Campo 46


   -- campo 47
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '9.010.0.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo47;

      IF (:bdcampo47 IS NULL) THEN
         bdcampo47 = 0;

      wTotalDeducoes = wTotalDeducoes + bdcampo47;

   -- campo 48
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '9.010.0.7%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo48;

      IF (:bdcampo48 IS NULL) THEN
         bdcampo48 = 0;

      wTotalDeducoes = wTotalDeducoes + bdcampo48;

   -- campo 49
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '7.061%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo49;

      IF (:bdcampo49 IS NULL) THEN
         bdcampo49 = 0;

      wTotalDeducoes = wTotalDeducoes + bdcampo49;

   -- campo 50
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '9.010.1.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo50;

      IF (:bdcampo50 IS NULL) THEN
         bdcampo50 = 0;

      wTotalDeducoes = wTotalDeducoes + bdcampo50;

   -- campo 51
      SELECT SUM(BDVALVFNPR) FROM VRHF_EMP_TVERBAFN_PREV_RESC x
            JOIN vrh_base_tverbas y ON (y.BDCLAVER LIKE '9.001.1.0%')
            WHERE (x.bdcodemp = :bdcodemp AND x.bdcodcol = :bdcodcol AND y.BDCODVER = x.BDCODVER)
      INTO
      :bdcampo51;

      IF (:bdcampo51 IS NULL) THEN
         bdcampo51 = 0;

      wTotalDeducoes = wTotalDeducoes + bdcampo51;


      bdcampo54totded = wtotaldeducoes;
      bdcampo55liqrec = bdcampo46bruto - bdcampo54totded; -- Total liquido campo 55


       SUSPEND;

     END
END
^

/* Restore proc. body: VRHF_SP_REL_PREVIA_RESC2 */
ALTER PROCEDURE VRHF_SP_REL_PREVIA_RESC2(PREMPRESA VARCHAR(10000),
PRCOLABORADOR VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRFUNCAO INTEGER,
PRSINDICATO INTEGER,
PRCLASSE INTEGER,
PRTIPOFILTRO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCPFCOL VARCHAR(14),
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDBAIEMP DM_BDBAIRRO,
BDNOMCID VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCEPEMP VARCHAR(9),
BDCODCNAE INTEGER,
BDPISCOL VARCHAR(14),
BDLOGRCOL VARCHAR(15),
BDENDCOL VARCHAR(60),
BDNUMCOL DM_NUMEND,
BDBAICOL VARCHAR(50),
BDCEPCOL VARCHAR(9),
BDNOMCIDCOL VARCHAR(40),
BDSIGLAUFCOL VARCHAR(2),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDATANASCCOL DATE,
BDNOMMAECOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCATEGORIACOL INTEGER,
BDDATAAVPREVIO DATE,
BDCHAVEINDENTIFICACAO VARCHAR(49),
BDDESCPRES VARCHAR(110),
BDCODSAQUE INTEGER,
BDDATARESCISAO DATE,
BDDATAPAGRESCISAO DATE,
BDREF INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(70),
BDDESCREDVER VARCHAR(35),
BDREFV NUMERIC(15,6),
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDORDEMVER INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WULTDIA VARCHAR(10);
DECLARE VARIABLE WDIA INTEGER;
DECLARE VARIABLE WANOMES INTEGER;
DECLARE VARIABLE WDATAINICIAL VARCHAR(10);
DECLARE VARIABLE WDATAFINAL VARCHAR(10);
DECLARE VARIABLE WDATARESC INTEGER;
BEGIN

  wmes = CAST(SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wanomes = CAST((SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 5 FOR 2)||SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 1 FOR 4)) AS INTEGER);
  wdatainicial = wmes||'/'||'01'||'/'||wano;

  wmes = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wanomes = CAST((SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 5 FOR 2)||SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 1 FOR 4)) AS INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wultdia = wmes||'/'||wdia||'/'||wano;
  wdatafinal = wmes||'/'||wdia||'/'||wano;

  EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);

  wsql =   'select RESC.bdcodemp, EMPRESAS.bdnomemp , empresas.bdcnpjemp, RESC.bdcodcol, spcolcon.bdnomcol,  spcolcon.bdcpfcol,
            empresas.bdlogremp, empresas.bdendemp , empresas.bdnumemp, empresas.bdbaiemp, empresas.bdnomcid, empresas.bdsiglauf, empresas.bdcepemp, empresas.bdcodcnae,
            spcolcon.bdpiscol, spcolcon.bdlogrcol, spcolcon.bdendcol, spcolcon.bdnumcol, spcolcon.bdbaicol, spcolcon.bdcepcol,
            spcidadecol.bdnomcid, spcidadecol.bdsiglauf , spcolcon.bdctpscol, spcolcon.bdseriectpscol,
            spcolcon.bddatanasccol, spcolcon.bdnommaecol, spcolcon.bddataadmcol, spcolcon.bdcategoriacol, RESC.bddataavprevioprev, RESC.bdchaveindentificacaoprev,
            preresc.bddescpres, preresc.bdcodsaque, resc.bddatarescisaoprev, resc.bddatapagrescisaoprev,
            fn.bdref, fn.bdcodver, fn.bddescver, fn.bddescredver, fn.bdrefv, fn.bdprovento, fn.bddesconto, tverbas.bdordemver

           from vrh_emp_trescisao_previa RESC
           join VRH_BASE_TPREPRESC PRERESC on (preresc.bdcodpres = resc.bdcodpres)
           join vrh_sp_colcon(null,null,null,null,null, ' || prreffim || ' , '''||wultdia||''' , 1,1,1,1,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0) spcolcon  on
              (RESC.BDCODEMP = spcolcon.BDCODEMP and RESC.BDCODCOL = spcolcon.BDCODCOL)
           left outer join SP_CONSULTACIDADE(null) spcidadecol on (spcidadecol.bdcodcid = spcolcon.bdcodcid)
           left outer join SP_CONSULTAEMPRESAS(null, null, null) empresas on (empresas.bdcodemp = RESC.bdcodemp )
           left outer join vrhf_sp_cons_calc_previa_resc(null,null,'||  'CAST((substring((CAST(resc.bddatarescisaoprev AS VARCHAR(10))) from 1 for 4) || substring((CAST(resc.bddatarescisaoprev AS VARCHAR(10))) from 6 for 2)) AS INTEGER)' ||') FN on (fn.bdcodemp = resc.bdcodemp and fn.bdcodcol = resc.bdcodcol)
           join vrh_base_tverbas tverbas on (fn.bdcodver = tverbas.bdcodver)' ;

  wwhere = '';

  IF (:prrefini IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and RESC.bddatarescisaoprev >= '''||:wdatainicial||''' ';
       ELSE
          wwhere = wwhere||' where RESC.bddatarescisaoprev >= '''||:wdatainicial||''' ';
    END

  IF (:prreffim IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and RESC.bddatarescisaoprev <= '''||:wdatafinal||''' ';
       ELSE
          wwhere = wwhere||' where RESC.bddatarescisaoprev <= '''||:wdatafinal||''' ';
    END


  IF (prempresa <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prempresa||' ';
     END


  IF (prcolaborador <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador||' ';
     END

  IF (prfuncao > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'spcolcon.bdcodtfuc = '||prfuncao||' ';  -- funcionario
     END

  IF (prsindicato > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere||'spcolcon.bdCODSINTRAB = '||prsindicato||' ';  -- TCOLVINC.
     END

  IF (prclasse > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'spcolcon.bdCODCLA = '||prclasse||' '; -- tcolcon_vinc
     END

  IF (prtipofiltro = 1) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'fn.bdprovento > 0 ';
     END

  IF (prtipofiltro = 2) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'fn.bddesconto > 0 ';
     END

 wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdnomemp,
    :bdcnpjemp,
    :BDCODCOL,
    :bdnomcol,
    :bdcpfcol,
    :bdlogremp,
    :bdendemp,
    :bdnumemp,
    :bdbaiemp,
    :bdnomcid,
    :bdsiglaufemp,
    :bdcepemp,
    :bdcodcnae,
    :bdpiscol,
    :bdlogrcol,
    :bdendcol,
    :bdnumcol,
    :bdbaicol,
    :bdcepcol,
    :bdnomcidcol,
    :bdsiglaufcol,
    :bdctpscol,
    :bdseriectpscol,
    :bddatanasccol,
    :bdnommaecol,
    :bddataadmcol,
    :bdcategoriacol,
    :bddataavprevio,
    :bdchaveindentificacao,
    :bddescpres,
    :bdcodsaque, 
    :bddatarescisao,
    :bddatapagrescisao,
    :bdref,
    :bdcodver,
    :bddescver,
    :bddescredver,
    :bdrefv,
    :bdprovento,
    :bddesconto,
    :bdordemver
    DO

   SUSPEND;



END
^

/* Restore proc. body: VRHF_SP_REL_RECIBO_RESCISAO */
create or alter procedure VRHF_SP_REL_RECIBO_RESCISAO (
    PREMPRESA varchar(10000),
    PRCOLABORADOR varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRFUNCAO integer,
    PRSINDICATO integer,
    PRCLASSE integer,
    PRTIPOFOLHA integer,
    PRDATAINI integer,
    PRDATAFIM integer)
returns (
    BDMAIORREMUNERACAOANT numeric(18,6),
    BDCODTIPOCONTRATO integer,
    BDDESCTIPOCONTRATO varchar(150),
    BDCODSINTRAB integer,
    BDCODCEDENTETRAB varchar(20),
    BDCNPJSINTRAB varchar(18),
    BDDESCSINTRAB varchar(60),
    BDPERTRCTRESC numeric(15,6),
    BDPERFGTSRESC numeric(15,6),
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(18),
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL varchar(14),
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDBAIEMP DM_BDBAIRRO,
    BDNOMCID varchar(40),
    BDSIGLAUFEMP varchar(2),
    BDCEPEMP varchar(9),
    BDCODCNAE integer,
    BDPISCOL varchar(14),
    BDLOGRCOL varchar(15),
    BDENDCOL varchar(60),
    BDNUMCOL DM_NUMEND,
    BDBAICOL varchar(50),
    BDCEPCOL varchar(9),
    BDNOMCIDCOL varchar(40),
    BDSIGLAUFCOL varchar(2),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL DM_DIGSERIECTPS,
    BDDATANASCCOL date,
    BDNOMMAECOL varchar(70),
    BDDATAADMCOL date,
    BDCATEGORIACOL integer,
    BDDATAAVPREVIO date,
    BDCHAVEINDENTIFICACAO varchar(49),
    BDDESCPRES varchar(110),
    BDCODSAQUE integer,
    BDDATARESCISAO date,
    BDDATAPAGRESCISAO date,
    BDVINCEMPCOL integer,
    BDSIGLAUFCTPS varchar(2),
    BDSIGLAHNET varchar(3),
    BDDESCHNET varchar(200),
    BDDESCCATEGORIA varchar(300),
    BDSALBASE numeric(18,6),
    BDDATAOPCAOFGTS date,
    BDTIPOCOL integer,
    BDCNPJTOM varchar(18),
    BDREFRESCISAO integer,
    BDECONSIGNADO DM_BOOLEAN,
    BDREFRESCISAOPOST integer)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WMES integer;
declare variable WANO integer;
declare variable WDIA integer;
declare variable WDATAINICIAL varchar(10);
declare variable WDATAFINAL varchar(10);
declare variable WFIMPRAZO1 date;
declare variable WFIMPRAZO2 date;
declare variable WFP1 date;
declare variable WFP2 date;
declare variable WTIPOADM smallint;
declare variable WECONSIG integer;
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
BEGIN

  wmes = CAST(SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
--  wanomes = cast((substring(cast(:prrefini as varchar(6)) from 5 for 2)||substring(cast(:prrefini as varchar(6)) from 1 for 4)) as INTEGER);
  wdatainicial = wmes||'/'||'01'||'/'||wano;

  wmes = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
--  wanomes = cast((substring(cast(:prreffim as varchar(6)) from 5 for 2)||substring(cast(:prreffim as varchar(6)) from 1 for 4)) as INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

--  wultdia = wmes||'/'||wdia||'/'||wano;
  wdatafinal = wmes||'/'||wdia||'/'||wano;

  EXECUTE PROCEDURE sp_seta_competencia(:prreffim, NULL, NULL);

  wsql =   ' SELECT                                                              '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' RESC.BDCODEMP,                                                      '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' EMPRESAS.BDNOMEMP,                                                  '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' EMP.BDCNPJEMP,                                                      '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' RESC.BDCODCOL,                                                      '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' COLCAD.BDNOMCOL,                                                    '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' DOC.BDCPFCOL,                                                       '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' EMPRESAS.BDLOGREMP,                                                 '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' EMPRESAS.BDENDEMP,                                                  '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' EMPRESAS.BDNUMEMP,                                                  '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' EMPRESAS.BDBAIEMP,                                                  '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' CIDEMP.BDNOMCID,                                                    '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' UFEMP.BDSIGLAUF,                                                    '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' EMPRESAS.BDCEPEMP,                                                  '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' EMPRESAS.BDCODCNAE,                                                 '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' DOCREF.BDPISCOL,                                                    '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' COLCAD.BDLOGRCOL,                                                   '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' COLCAD.BDENDCOL,                                                    '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' COLCAD.BDNUMCOL,                                                    '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' COLCAD.BDBAICOL,                                                    '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' COLCAD.BDCEPCOL,                                                    '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' CIDCOL.BDNOMCID,                                                    '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' UFCOL.BDSIGLAUF,                                                    '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' case when coalesce(DOCREF.BDCTPSCOL, '''') = '''' and coalesce(DOCREF.BDSERIECTPSCOL, '''') = '''' then substring(replace(replace(doc.bdcpfcol, ''.'', ''''), ''-'', '''') from 1 for 7) else docref.bdctpscol end bdctpscol,'|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' case when coalesce(DOCREF.BDCTPSCOL, '''') = '''' and coalesce(DOCREF.BDSERIECTPSCOL, '''') = '''' then substring(replace(replace(doc.bdcpfcol, ''.'', ''''), ''-'', '''') from 8 for 4) else docref.bdseriectpscol end bdseriectpscol,'|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' DOCREF.BDDSERIECTPSCOL,                                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' COLCON.BDDATANASCCOL,                                               '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' PARCOL.BDNOMMAECOL,                                                 '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' coalesce (COL_ADM.BDNOVADATAADMRT, COLCON.BDDATAADMCOL) as BDDATAADMCOL, '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' FGTSCOL.BDCATEGORIACOL,                                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' CASE                                                                '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDDATAAVPREVIO IS NULL THEN RESC.BDDATAAVPREVIO       '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' ELSE                                                                '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     RESC.BDDATANOTIF                                                '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' END BDDT,                                                           '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' RESC.BDCHAVEINDENTIFICACAO,                                         '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' PRERESC.BDDESCPRES,                                                 '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' PRERESC.BDCODSAQUE,                                                 '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           --' RESC.BDDATARESCISAO,                                                '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' COALESCE(RESC.bdnovadatarescisao, RESC.BDDATARESCISAO) AS bddatarescisao, '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' RESC.BDDATAPAGRESCISAO,                                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' TCON_VINC.BDCODSINTRAB,                                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' SIND.BDCALCCODBARTRAB,                                              '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' SIND.BDCNPJSINTRAB,                                                 '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' SIND.BDDESCSINTRAB,                                                 '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' RESC.BDPERTRCTRESC,                                                 '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' RESC.BDPERFGTSRESC,                                                 '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' RESC.BDCODTIPOCONTRATO,                                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' TIPCON.BDDESCRICAO,                                                 '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' MREM.BDMAIORREMUNERACAO,                                            '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' CASE                                                                '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 1  THEN 15                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 2  THEN 20                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 3  THEN 25                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 4  THEN 30                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 5  THEN 31                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 6  THEN 35                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 7  THEN 40                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 8  THEN 50                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 9  THEN 55                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 10 THEN 60                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 11 THEN 65                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 12 THEN 70                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 13 THEN 75                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 14 THEN 80                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 15 THEN 90                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 16 THEN 95                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 17 THEN 96                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     WHEN RESC.BDVINCEMPCOL = 18 THEN 97                             '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' ELSE                                                                '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     10                                                              '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' END BDVINCEMPCOL,                                                   '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' case when coalesce(DOCREF.BDCTPSCOL, '''') = '''' and coalesce(DOCREF.BDSERIECTPSCOL, '''') = '''' then case when CIDEMP.BDCODUF between 1 and 27 then UFEMP.BDSIGLAUF when CIDEMPM.BDCODUF between 1 and 27 then UFMAT.BDSIGLAUF else '''' end else ufctps.bdsiglauf end bdsiglauf, '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||

           'CASE WHEN COALESCE(PRERESC.BDCODHNET,0) = 0 THEN MFGTS.BDCODSEFMFG ELSE HNET.BDSIGLAHNET END,'||

           ' CASE                                                                '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '     when PRERESC.BDCODPRES in (75,76) then PRERESC.BDDESCPRES       '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' else                                                                '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '      HNET.BDDESCHNET                                                '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' END BDDESCHNET,                                                     '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' CATEG.BDDESCCATEGORIA,                                              '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' FN.BDSALBASE,                                                       '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' RESC.BDDATAOPCAOFGTS,                                               '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' COLCALC.BDTIPOCOL,                                                  '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' COL_ADM.BDDATAFIMPRAZO1COL,                                         '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' COL_ADM.BDDATAFIMPRAZO2COL,                                         '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' TOM.BDCNPJTOM,                                                      '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           ' RESC.BDREFRESCISAO                                                  '|| ASCII_CHAR(13) || ASCII_CHAR(10) ||
           '  FROM (SELECT RESC.* FROM VWRH_TRESCISAO_ADM_COL RESC               '||ASCII_CHAR(13)  || ASCII_CHAR(10);

  wwhere = '';
  IF (prempresa <> '') THEN
     BEGIN
       wwhere = wwhere||prempresa||' ';
     END


  IF (prcolaborador <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador||' ';
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere||
         ' order by RESC.BDCODEMP, RESC.BDCODCOL, RESC.BDDATARESCISAO '||
         ') RESC ';

    IF (prtipofolha IS NOT NULL AND prtipofolha = 1) THEN
       BEGIN
         wsql = wsql||'join ('||
                  'select RESC.BDCODEMP,RESC.BDCODCOL,RESC.BDREFFN,RESC.BDREFFC,RESC.BDREFCOMP,RESC.BDCODCENTRO,RESC.BDCODTPCC,RESC.BDDATABAIXA,RESC.BDBFGTS,RESC.BDFGTS,'||
                     'RESC.BDFGTSCS,RESC.BDBFGTS13,RESC.BDFGTS13,RESC.BDFGTS13CS,RESC.BDMAIORREM,'||
                     'RESC.BDBINSS,RESC.BDALIQINSS,RESC.BDINSS,RESC.BDBIRRF,RESC.BDALIQIRRF,RESC.BDIRRF,RESC.BDBINSS13,RESC.BDALIQINSS13,RESC.BDINSS13,RESC.BDBIRRF13,'||
                     'RESC.BDALIQIRRF13,RESC.BDIRRF13,RESC.BDBSALFAM,RESC.BDSALFAM,RESC.BDBRAIS,'||
                     'RESC.BDSALBASE,RESC.BDDEP,RESC.BDBINSSFEFOL,RESC.BDINSSFEFOL,RESC.BDALIQINSSFEFOL,RESC.BDCREDITO,RESC.BDDEBITO,RESC.BDBFGTSFEFOL,RESC.BDFGTSFEFOL,'||
                     'RESC.BDLIQUIDO,RESC.BDDATAPAGFC '||
                  'from VWRH_UNION_FC_FCT_MES_BASES RESC ';

         wwhere = '';
         if (prempresa <> '') then
            begin
              wwhere = wwhere||prempresa;

              if (prcolaborador <> '') then
                 wwhere = wwhere||' and '||prcolaborador;
            end

         if (prdataini is not null and prdataini <> 0 and prdatafim is not null and prdatafim <> 0) then
            wwhere = wwhere||' and resc.bdreffc >= '||prdataini||' and resc.bdreffc <= '||prdatafim;

         if (wwhere <> '') then
            wwhere = ' where '||wwhere;

         wsql = wsql||wwhere;


         wsql = wsql||' union all '||
                  'select RESC.BDCODEMP,RESC.BDCODCOL,RESC.BDREFFN,RESC.BDREFFC,RESC.BDREFCOMP,RESC.BDCODCENTRO,RESC.BDCODTPCC,RESC.BDDATABAIXA,RESC.BDBFGTS,RESC.BDFGTS,'||
                     'RESC.BDFGTSCS,RESC.BDBFGTS13,RESC.BDFGTS13,RESC.BDFGTS13CS,RESC.BDMAIORREM,'||
                     'RESC.BDBINSS,RESC.BDALIQINSS,RESC.BDINSS,RESC.BDBIRRF,RESC.BDALIQIRRF,RESC.BDIRRF,RESC.BDBINSS13,RESC.BDALIQINSS13,RESC.BDINSS13,RESC.BDBIRRF13,'||
                     'RESC.BDALIQIRRF13,RESC.BDIRRF13,RESC.BDBSALFAM,RESC.BDSALFAM,RESC.BDBRAIS,'||
                     'RESC.BDSALBASE,RESC.BDDEP,RESC.BDBINSSFEFOL,RESC.BDINSSFEFOL,RESC.BDALIQINSSFEFOL,RESC.BDCREDITO,RESC.BDDEBITO,RESC.BDBFGTSFEFOL,RESC.BDFGTSFEFOL,'||
                     'RESC.BDLIQUIDO,RESC.BDDATAPAGFC '||
                  'from VWRH_UNION_FCI_FCIT_MES_BASES RESC ';

         wwhere = '';
         if (prempresa <> '') then
            begin
              wwhere = wwhere||prempresa;

              if (prcolaborador <> '') then
                 wwhere = wwhere||' and '||prcolaborador;
            end

         if (prdataini is not null and prdataini <> 0 and prdatafim is not null and prdatafim <> 0) then
            wwhere = wwhere||' and resc.bdreffc >= '||prdataini||' and resc.bdreffc <= '||prdatafim;

         if (wwhere <> '') then
            wwhere = ' where '||wwhere;

         wsql = wsql||wwhere;

         wsql = wsql||') fn on (fn.bdcodemp = resc.bdcodemp and fn.bdcodcol = resc.bdcodcol) ';
       END
    ELSE
    IF ((prtipofolha IS NULL) OR (prtipofolha = 0)) THEN
       BEGIN
         wsql = wsql||'join ('||
            'select resc.BDCODEMP, resc.BDCODCOL, resc.BDREFFN, resc.BDSALBASE from VWRH_UNION_FN_FT_MES_BASES resc '||ASCII_CHAR(13) || ASCII_CHAR(10);

         wwhere = '';
         IF (prempresa <> '') THEN
            wwhere = wwhere||prempresa||' ';

         IF (prcolaborador <> '') THEN
            BEGIN
              IF (wwhere <> '') THEN
                 wwhere = wwhere||' and ';
              wwhere = wwhere||prcolaborador||' ';
            END
       
         IF (wwhere <> '') THEN
            wwhere = ' where '||wwhere;
       
         wsql = wsql||wwhere;

         wsql = wsql||
                ' union                                                                      '||ASCII_CHAR(13) || ASCII_CHAR(10)||
                ' select                                                                     '||ASCII_CHAR(13) || ASCII_CHAR(10)||
                ' resc.BDCODEMP,                                                             '||ASCII_CHAR(13) || ASCII_CHAR(10)||
                ' resc.BDCODCOL,                                                             '||ASCII_CHAR(13) || ASCII_CHAR(10)||
                ' resc.BDREFFN,                                                              '||ASCII_CHAR(13) || ASCII_CHAR(10)||
                ' resc.BDSALBASE                                                             '||ASCII_CHAR(13) || ASCII_CHAR(10)||
                ' from vwrh_union_fi_fti_mes_bases resc                                      '||ASCII_CHAR(13) || ASCII_CHAR(10)||
                ' join VRH_EMP_TINTERMITENTE CONV on (CONV.BDCODEMP     = resc.BDCODEMP and  '||ASCII_CHAR(13) || ASCII_CHAR(10)||
                '                                     CONV.BDCODCOL     = resc.BDCODCOL and  '||ASCII_CHAR(13) || ASCII_CHAR(10)||
                '                                     CONV.BDCODCONTTI  = resc.BDCODCONTTI ) '||ASCII_CHAR(13) || ASCII_CHAR(10);

         wwhere = ' where upper(coalesce(CONV.BDCONVRESCTI, ''FALSE'')) = ''TRUE'' '||ASCII_CHAR(13) || ASCII_CHAR(10);
         IF (prempresa <> '') THEN
            wwhere = wwhere||' and '||prempresa||' ';

         IF (prcolaborador <> '') THEN
            BEGIN
              wwhere = wwhere||' and '||prcolaborador||' ';
            END
       
         wsql = wsql||wwhere;

         wsql = wsql||') fn on (fn.bdcodemp = resc.bdcodemp and fn.bdcodcol = resc.bdcodcol and fn.bdreffn = resc.bdrefrescisao) '||ASCII_CHAR(13) || ASCII_CHAR(10);
       END

    wsql = wsql||
           --' LEFT OUTER JOIN VRH_BASE_TPREPRESC PRERESC ON (PRERESC.BDCODPRES = RESC.BDCODPRES)                                            '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           ' LEFT OUTER JOIN VRH_BASE_TPREPRESC PRERESC ON (PRERESC.BDCODPRES = COALESCE(RESC.BDNOVOCODPRES, RESC.BDCODPRES))              '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           ' JOIN VW_TEMPRESAS_REF EMPRESAS ON (EMPRESAS.BDCODEMP = RESC.BDCODEMP )                                                        '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           ' JOIN TEMPRESAS EMP ON (EMP.BDCODEMP = RESC.BDCODEMP)                                                                          '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           ' JOIN VRH_EMP_TCOLCON COLCON ON (COLCON.BDCODEMP = RESC.BDCODEMP AND                                                           '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                 COLCON.BDCODCOL = RESC.BDCODCOL    )                                                          '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           ' LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON (COLCAD.BDCODEMP = RESC.BDCODEMP AND                                         '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                                   COLCAD.BDCODCOL = RESC.BDCODCOL)                                            '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           ' LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF DOCREF ON (DOCREF.BDCODEMP = RESC.BDCODEMP AND                                      '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                                       DOCREF.BDCODCOL = RESC.BDCODCOL)                                        '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           ' LEFT OUTER JOIN VRH_BASE_THOMOLOGANET HNET ON (HNET.BDCODHNET = PRERESC.BDCODHNET)                                            '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           ' LEFT OUTER JOIN VWRH_MAIORREMUNERACAO_DEMITIDOS MREM ON (RESC.BDCODEMP = MREM.BDCODEMP AND                                    '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                                          RESC.BDCODCOL = MREM.BDCODCOL AND                                    '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                                           (                                                                   '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                                            (                                                                  '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                                             SELECT                                                            '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                                             (                                                                 '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                                              SELECT                                                           '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                                              AAA.BDAAAAMM                                                     '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                                              FROM AAAAMM(BDNOVADATA) AAA                                      '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                                             )                                                                 '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                                             FROM DIMINUI_MESES(RESC.BDDATARESCISAO,1)                         '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                                            )                                                                  '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                                           ) = MREM.BDREFFN                           )                        '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           ' LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC DOC ON (DOC.BDCODEMP = RESC.BDCODEMP AND                                                  '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                              DOC.BDCODCOL = RESC.BDCODCOL)                                                    '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           ' LEFT OUTER JOIN VRH_EMP_TCOL_DOC DOCCOL ON (DOCCOL.BDCODEMP = RESC.BDCODEMP AND                                               '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                              DOCCOL.BDCODCOL = RESC.BDCODCOL)                                                 '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           ' LEFT OUTER JOIN VW_VRHF_EMP_TCOLCON_FGTSGPS FGTSCOL ON (FGTSCOL.BDCODEMP = RESC.BDCODEMP AND                                  '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           '                                                         FGTSCOL.BDCODCOL = RESC.BDCODCOL    )                                 '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           ' LEFT OUTER JOIN VRH_BASE_TCATEGORIA CATEG ON (CATEG.BDCODCATEGORIA = FGTSCOL.BDCATEGORIACOL)                                  '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           ' LEFT OUTER JOIN VRH_EMP_TCOL_PARENT PARCOL ON (PARCOL.BDCODEMP = RESC.BDCODEMP AND PARCOL.BDCODCOL = RESC.BDCODCOL)           '||ASCII_CHAR(13) || ASCII_CHAR(10)||
           ' LEFT OUTER JOIN VW_VRHF_EMP_TCOL_CALC COLCALC ON (COLCALC.BDCODEMP = RESC.BDCODEMP AND COLCALC.BDCODCOL = RESC.BDCODCOL)      ';

  IF (prclasse > 0) THEN
     wsql = wsql||
            'left outer join VW_vrh_emp_tcolcon_vinc tcolcon_vinc on (tcolcon_vinc.bdcodemp = resc.bdcodemp and  '||ASCII_CHAR(13) || ASCII_CHAR(10)||
            '                                                         tcolcon_vinc.bdcodcol = resc.bdcodcol    ) ';
             
  wsql = wsql||
         'left outer join VW_VRH_EMP_TCOL_VINC tcon_vinc on (tcon_vinc.bdcodemp = resc.bdcodemp and  '||ASCII_CHAR(13) || ASCII_CHAR(10)||
         '                                                   tcon_vinc.bdcodcol = resc.bdcodcol    ) ';

  IF (prfuncao > 0) THEN
     wsql = wsql||
            ' left outer join VW_TCOLCON_VINCDIA vincdia on (vincdia.bdcodemp = resc.bdcodemp and  '||ASCII_CHAR(13) || ASCII_CHAR(10)||
            '                                                vincdia.bdcodcol = resc.bdcodcol    ) ';

  wsql = wsql||
         ' left outer join vrh_base_tsindtrab sind on (sind.bdcodsintrab = tcon_vinc.bdcodsintrab)             '||ASCII_CHAR(13) || ASCII_CHAR(10)||
         ' left outer join vrh_tipo_contrato_exp tipcon on (tipcon.bdcodtipocontrato = resc.bdcodtipocontrato) '||ASCII_CHAR(13) || ASCII_CHAR(10)||
         ' left outer join tcidade cidemp on (empresas.bdcodcid = cidemp.bdcodcid)                             '||ASCII_CHAR(13) || ASCII_CHAR(10)||
         ' left outer join tcidade cidcol on (cidcol.bdcodcid = colcad.bdcodcid)                               '||ASCII_CHAR(13) || ASCII_CHAR(10)||
         ' left outer join tuf ufemp on (ufemp.bdcoduf = cidemp.bdcoduf)                                       '||ASCII_CHAR(13) || ASCII_CHAR(10)||
         ' left outer join tuf ufcol on (ufcol.bdcoduf = cidcol.bdcoduf)                                       '||ASCII_CHAR(13) || ASCII_CHAR(10)||
         ' left outer join tuf ufctps on (ufctps.bdcoduf = docref.bdcoduf)                                     '||ASCII_CHAR(13) || ASCII_CHAR(10)||
         ' left outer join VW_VRH_EMP_TCOL_ADM COL_ADM on (COL_ADM.BDCODEMP = resc.bdcodemp and COL_ADM.BDCODCOL = resc.bdcodcol) '||ASCII_CHAR(13) || ASCII_CHAR(10)||
         ' left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = resc.bdcodemp and pfn.bdcodcol = resc.bdcodcol and
                                                    bdordem = (select max(bdordem) from vrhf_emp_tprepfn
                                                               where bdcodemp = pfn.bdcodemp and bdcodcol = pfn.bdcodcol))'||ASCII_CHAR(13) || ASCII_CHAR(10)||
         ' left outer join vrh_base_tcustom tom on (tom.bdcodcentro = pfn.bdcodcentro and tom.bdcodtpcc = pfn.bdcodtpcc) '||ASCII_CHAR(13) || ASCII_CHAR(10)||
         ' left outer join TEMPRESAS EMPM on (EMPM.BDCODEMP = EMP.BDCODMATRIZ) '||ASCII_CHAR(13) || ASCII_CHAR(10)||
         ' left outer join TEMPRESAS_REF EMPRM on (EMPRM.BDCODEMP = EMPM.BDCODEMP and EMPRM.BDREFEMP = (select first 1 BDREFEMP
                                                                                                              from TEMPRESAS_REF
                                                                                                              where BDCODEMP = EMPRM.BDCODEMP and
                                                                                                                    BDREFEMP <= ' || :prreffim || '
                                                                                                              order by BDCODEMP desc, BDREFEMP desc)) '||ASCII_CHAR(13) || ASCII_CHAR(10)||
         ' left outer join TCIDADE CIDEMPM on (CIDEMPM.BDCODCID = EMPRM.BDCODCID) '||ASCII_CHAR(13) || ASCII_CHAR(10)||
         ' left outer join TUF UFMAT on (UFMAT.BDCODUF = CIDEMPM.BDCODUF) '||
         ' left outer join VRH_BASE_TMOTFGTS MFGTS on (MFGTS.BDCODMFG = PRERESC.BDCODMFG) ';

  wwhere = '';

  IF (:prrefini IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||
                   ' and RESC.BDDATARESCISAO >= '''||:wdatainicial||''' ';
       ELSE
          wwhere = wwhere||
                   ' where RESC.BDDATARESCISAO >= '''||:wdatainicial||''' ';
    END

  IF (:prreffim IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||
                   ' and RESC.BDDATARESCISAO <= '''||:wdatafinal||''' ';
       ELSE
          wwhere = wwhere||
                   ' where RESC.BDDATARESCISAO <= '''||:wdatafinal||''' ';
    END


  IF (prempresa <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prempresa||' ';
     END


  IF (prcolaborador <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador||' ';
     END

  IF (prfuncao > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'vincdia.bdcodtfuc = '||prfuncao||' ';  -- funcionario
     END

  IF (prsindicato > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere||'tcon_vinc.bdCODSINTRAB = '||prsindicato||' ';  -- TCOLVINC.
     END

  IF (prclasse > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'tcolcon_vinc.bdCODCLA = '||prclasse||' '; -- tcolcon_vinc
     END

  wsql = wsql||wwhere;

  wempatu = 0;
  wcolatu = 0;
  wrefatu = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdnomemp,
    :bdcnpjemp,
    :BDCODCOL,
    :bdnomcol,
    :bdcpfcol,
    :bdlogremp,
    :bdendemp,
    :bdnumemp,
    :bdbaiemp,
    :bdnomcid,
    :bdsiglaufemp,
    :bdcepemp,
    :bdcodcnae,
    :bdpiscol,
    :bdlogrcol,
    :bdendcol,
    :bdnumcol,
    :bdbaicol,
    :bdcepcol,
    :bdnomcidcol,
    :bdsiglaufcol,
    :bdctpscol,
    :bdseriectpscol,
    :BDDSERIECTPSCOL,
    :bddatanasccol,
    :bdnommaecol,
    :bddataadmcol,
    :bdcategoriacol,
    :bddataavprevio,
    :bdchaveindentificacao,
    :bddescpres,
    :bdcodsaque, 
    :bddatarescisao,
    :bddatapagrescisao,
    :bdcodsintrab,
    :bdcodcedentetrab,
    :bdcnpjsintrab,
    :bddescsintrab,
    :bdpertrctresc,
    :bdperfgtsresc,
    :BDCODTIPOCONTRATO,
    :BDDESCTIPOCONTRATO,
    :bdmaiorremuneracaoant,
    :bdvincempcol,
    :bdsiglaufctps,
    :bdsiglahnet,
    :bddeschnet,
    :bddesccategoria,
    :bdsalbase,
    :bddataopcaofgts,
    :bdtipocol,
    :wfimprazo1,
    :wfimprazo2,
    :bdcnpjtom,
    :bdrefrescisao
    DO
    BEGIN
      if ((wempatu <> BDCODEMP) or (wcolatu <> BDCODCOL) or (wrefatu <> BDREFRESCISAO)) then
         begin
           BDECONSIGNADO = 'FALSE';
           weconsig = null;
    
           select first 1 P.BDCODPARC
           from VRH_EMP_TPARCELAMENTOS P
           join VRH_EMP_TPARCELAMENTOS_ITENS PI on (PI.BDCODEMP = P.BDCODEMP and PI.BDCODCOL = P.BDCODCOL and PI.BDCODPARC = P.BDCODPARC)
           where P.BDCODEMP = :BDCODEMP and P.BDCODCOL = :BDCODCOL and PI.BDREFPI = :BDREFRESCISAO and P.BDECONSIGNADO
           into :weconsig;
    
           if (coalesce(weconsig, 0) > 0) then
              BDECONSIGNADO = 'TRUE';


           wempatu = BDCODEMP;
           wcolatu = BDCODCOL;
           wrefatu = BDREFRESCISAO;
         end

      if (coalesce(bdcodtipocontrato, 0) > 1) then
         begin
           wfp1     = null;
           wfp2     = null;
           wtipoadm = 0;
     
           select BDDATAFIMPRAZO1COL, BDDATAFIMPRAZO2COL
           from SP_PRAZO_EXPERIENCIA_SITUACAO('BDCODEMP = '||:bdcodemp, 'BDCODCOL = '||:bdcodcol, null, null)
           into :wfp1, wfp2;
     
           if (wfp1 is not null and wfp2 is not null) then
              begin
                wfimprazo1 = wfp1;
                wfimprazo2 = wfp2;
              end
     
           if (wfimprazo1 is not null) then
              begin
                if (bddatarescisao > wfimprazo1) then
                   wtipoadm = 1;
              end

           if (wfimprazo2 is not null) then
              begin
                if (bddatarescisao > wfimprazo2) then
                   wtipoadm = 1;
                else
                   wtipoadm = 0;
              end

           -- Mudou o tipo de contrato
           if (wtipoadm = 1) then
              begin
                bdcodtipocontrato = 1;
                select first 1 BDDESCRICAO from VRH_TIPO_CONTRATO_EXP where BDCODTIPOCONTRATO = 1 into :BDDESCTIPOCONTRATO;
              end
         end

      -- competência posterior a rescisão
      select first 1 BDREFERENCIA from INC_REFERENCIA(:BDREFRESCISAO, 1) into :BDREFRESCISAOPOST;
      SUSPEND;
    END
END^

/* Restore proc. body: VRHF_SP_REL_RECIBO_RESCISAO2 */
create or alter procedure VRHF_SP_REL_RECIBO_RESCISAO2 (
    PREMPRESA varchar(10000),
    PRCOLABORADOR varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRFUNCAO integer,
    PRSINDICATO integer,
    PRCLASSE integer,
    PRTIPOFILTRO integer,
    PRTIPOFOLHA integer,
    PRDTPGTO integer,
    PRDTPGTOFIM integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(18),
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL varchar(14),
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDBAIEMP DM_BDBAIRRO,
    BDNOMCID varchar(40),
    BDSIGLAUFEMP varchar(2),
    BDCEPEMP varchar(9),
    BDCODCNAE integer,
    BDPISCOL varchar(14),
    BDLOGRCOL varchar(15),
    BDENDCOL varchar(60),
    BDNUMCOL DM_NUMEND,
    BDBAICOL varchar(50),
    BDCEPCOL varchar(9),
    BDNOMCIDCOL varchar(40),
    BDSIGLAUFCOL varchar(2),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL DM_DIGSERIECTPS,
    BDDATANASCCOL date,
    BDNOMMAECOL varchar(70),
    BDDATAADMCOL date,
    BDCATEGORIACOL integer,
    BDDATAAVPREVIO date,
    BDCHAVEINDENTIFICACAO varchar(49),
    BDREFRESCISAO integer,
    BDDESCPRES varchar(110),
    BDCODSAQUE integer,
    BDDATARESCISAO date,
    BDDATAPAGRESCISAO date,
    BDREF integer,
    BDCODVER integer,
    BDDESCVER varchar(70),
    BDDESCREDVER varchar(35),
    BDREFV numeric(18,6),
    BDREFAUXV numeric(18,6),
    BDHEVER numeric(18,6),
    BDPROVENTO numeric(18,6),
    BDDESCONTO numeric(18,6),
    BDORDEMVER integer,
    BDCLAVER varchar(20),
    BDPERCINSALUBCOL numeric(18,6),
    BDPERCPERICULCOL numeric(18,6),
    BDPERCNOTURNOCOL numeric(18,6),
    BDHORASDIARIASCOL numeric(18,6),
    BDSIGLAUFCTPS varchar(2),
    BDTIPOREFVER integer,
    BDREFHOREMP varchar(5),
    BDCLAVERAUX varchar(20),
    BDDESCVERAUX varchar(70),
    BDPROVENTOOUTROS numeric(18,6),
    BDDESCONTOOUTROS numeric(18,6),
    BDTIPOCOL integer,
    BDCNPJTOM varchar(18))
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WMES integer;
declare variable WANO integer;
declare variable WDIA integer;
declare variable WDATAINICIAL varchar(10);
declare variable WDATAFINAL varchar(10);
BEGIN

  wmes = CAST(SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prrefini AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
--  wanomes = cast((substring(cast(:prrefini as varchar(6)) from 5 for 2)||substring(cast(:prrefini as varchar(6)) from 1 for 4)) as INTEGER);
  wdatainicial = wmes||'/'||'01'||'/'||wano;

  wmes = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
  wano = CAST(SUBSTRING(CAST(:prreffim AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
--  wanomes = cast((substring(cast(:prreffim as varchar(6)) from 5 for 2)||substring(cast(:prreffim as varchar(6)) from 1 for 4)) as INTEGER);

  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wdatafinal = wmes||'/'||wdia||'/'||wano;

  EXECUTE PROCEDURE sp_seta_competencia(:prreffim, NULL, NULL);

  wsql = 'select RESC.bdcodemp,'||
                 'EMPRESAS.bdnomemp ,'||
                 'emp.bdcnpjemp,'||
                 'RESC.bdcodcol,'||
                 'colcad.bdnomcol,'||
                 'doc.bdcpfcol,'||
                 'empresas.bdlogremp,'||
                 'empresas.bdendemp ,'||
                 'empresas.bdnumemp,'||
                 'empresas.bdbaiemp,'||
                 'cidemp.bdnomcid,'||
                 'ufemp.bdsiglauf,'||
                 'empresas.bdcepemp,'||
                 'empresas.bdcodcnae,'||
                 'docref.bdpiscol,'||
                 'colcad.bdlogrcol,'||
                 'colcad.bdendcol,'||
                 'colcad.bdnumcol,'||
                 'colcad.bdbaicol,'||
                 'colcad.bdcepcol,'||
                 'cidcol.bdnomcid,'||
                 'ufcol.bdsiglauf ,'||
                 'case when coalesce(DOCREF.BDCTPSCOL, '''') = '''' and coalesce(DOCREF.BDSERIECTPSCOL, '''') = '''' then substring(replace(replace(doc.bdcpfcol, ''.'', ''''), ''-'', '''') from 1 for 7) else docref.bdctpscol end bdctpscol,'||
                 'case when coalesce(DOCREF.BDCTPSCOL, '''') = '''' and coalesce(DOCREF.BDSERIECTPSCOL, '''') = '''' then substring(replace(replace(doc.bdcpfcol, ''.'', ''''), ''-'', '''') from 8 for 4) else docref.bdseriectpscol end bdseriectpscol,'||
                 'docref.bddseriectpscol,'||
                 'colcon.bddatanasccol,'||
                 'parcol.bdnommaecol,'||
                 'coalesce(COL_ADM.BDNOVADATAADMRT, COLCON.BDDATAADMCOL) as BDDATAADMCOL,'||
                 'fgtscol.bdcategoriacol,'||
                 'case when RESC.bddataavprevio is null then RESC.bddataavprevio else RESC.BDDATANOTIF end bdDT, '|| --RESC.bddataavprevio,
                 'RESC.bdchaveindentificacao,'||
                 'resc.bdrefrescisao,'||
                 'preresc.bddescpres,'||
                 'preresc.bdcodsaque,'||
                 --'resc.bddatarescisao,'||
                 'coalesce(resc.bdnovadatarescisao, resc.bddatarescisao) as bddatarescisao, '||
                 'resc.bddatapagrescisao,'||
                 'fn.bdreffn,'||
                 'fn.bdcodver,'||
                 'tverbas.bddescver,'||
                 'tverbas.bddescredver,'||
                 'case when substring(tverbas.bdclaver from 1 for 7) = ''9.010.0'' then fn.bdrefvfn_max else fn.bdrefvfn_sum end,'||
                 'case when substring(tverbas.bdclaver from 1 for 7) = ''9.010.0'' then fn.bdrefauxvfn_sum else case when verref.BDDEDFORMREFAUXVER = ''TRUE'' then fn.bdrefauxvfn_sum else fn.bdrefauxvfn_max end end,'||
                 'verref.bdhever,'||
                 'case when coalesce(verref.bdtipocodver, 0) = 0 then fn.bdvalvfn '||
                      'when coalesce(verref.bdtipocodver, 0) <> 0 then 0 '||
                 'end bdprovento, '||
                 'case when coalesce(verref.bdtipocodver, 0) = 1 then fn.bdvalvfn '||
                      'when coalesce(verref.bdtipocodver, 0) <> 1 then 0 '||
                 'end bddesconto, '||
                 'tverbas.bdordemver, '||
                 'tverbas.bdclaver, '||
                 'tcol_calc.bdpercinsalubcol, '||
                 'tcol_calc.bdpercperculcol, '||
                 'case when (sind.BDPERCNOTST is not null) and (sind.BDPERCNOTST <> 0) then sind.BDPERCNOTST else tcol_calc.bdpercnoturnocol end BDPERCNOT, '||
                 'tcol_calc.bdhorasdiariascol, '||
                 'case when coalesce(DOCREF.BDCTPSCOL, '''') = '''' and coalesce(DOCREF.BDSERIECTPSCOL, '''') = '''' then case when CIDEMP.BDCODUF between 1 and 27 then UFEMP.BDSIGLAUF when CIDEMPM.BDCODUF between 1 and 27 then UFMAT.BDSIGLAUF else '''' end else ufctps.bdsiglauf end bdsiglauf, '||
                 'verref.bdtiporefver, '||
                 'empref.bdrefhoremp, '||
                 'class.bdclaver bdclaveraux, '||
                 'class.bddescver bddescveraux, '||
                 'case when coalesce(verref.bdtipocodver, 0) = 2 then fn.bdvalvfn '||
                      'when coalesce(verref.bdtipocodver, 0) <> 2 then 0 '||
                 'end bdproventooutros, '||
                 'case when coalesce(verref.bdtipocodver, 0) = 3 then fn.bdvalvfn '||
                      'when coalesce(verref.bdtipocodver, 0) <> 3 then 0 '||
                 'end bddescontooutros, '||
                 'colcalc.bdtipocol, '||
                 'tom.bdcnpjtom '||
          'from ( select RESC.* from vrh_emp_trescisao RESC';

  wwhere = '';
  IF (prempresa <> '') THEN
     BEGIN
       wwhere = wwhere||prempresa||' ';
     END

  IF (prcolaborador <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador||' ';
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsql = wsql||wwhere;
  wsql = wsql||
          ') RESC ';

 IF ((prtipofolha IS NULL) OR (prtipofolha = 0)) THEN
    begin
      wsql = wsql||' join (select resc.bdcodemp,resc.bdcodcol,resc.bdreffn,resc.bdcodver,resc.bdrefvfn_max,resc.bdrefvfn_sum,resc.bdrefauxvfn_sum,resc.bdrefauxvfn_max,resc.bdvalvfn '||
                          'from vwrh_union_fn_ft_mes resc ';

      wwhere = '';
      IF (prempresa <> '') THEN
         BEGIN
           wwhere = wwhere||prempresa||' ';
         END
    
      IF (prcolaborador <> '') THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||prcolaborador||' ';
         END
    
      IF (prrefini IS NOT NULL AND prreffim IS NOT NULL) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'resc.bdreffn >= '||prrefini||' and resc.bdreffn <= '||prreffim||' ';
         END

      IF (wwhere <> '') THEN
         wwhere = ' where '||wwhere;

      wsql = wsql||wwhere;

      wsql = wsql||' union all select resc.bdcodemp,resc.bdcodcol,resc.bdreffn,resc.bdcodver,resc.bdrefvfn_max,resc.bdrefvfn_sum,resc.bdrefauxvfn_sum,resc.bdrefauxvfn_max,resc.bdvalvfn '||
                          'from vwrh_union_fi_fti_mes resc '||
                   ' join VRH_EMP_TINTERMITENTE CONV on (CONV.BDCODEMP = resc.BDCODEMP and CONV.BDCODCOL = resc.BDCODCOL and CONV.BDCODCONTTI = resc.BDCODCONTTI) ';

      wwhere = ' where upper(coalesce(CONV.BDCONVRESCTI, ''FALSE'')) = ''TRUE'' ';
      IF (prempresa <> '') THEN
         BEGIN
           wwhere = wwhere||' and '||prempresa||' ';
         END
    
      IF (prcolaborador <> '') THEN
         BEGIN
           wwhere = wwhere||' and '||prcolaborador||' ';
         END
    
      IF (prrefini IS NOT NULL AND prreffim IS NOT NULL) THEN
         BEGIN
           wwhere = wwhere||' and resc.bdreffn >= '||prrefini||' and resc.bdreffn <= '||prreffim||' ';
         END

      wsql = wsql||wwhere;

      wsql = wsql||') fn on (fn.bdcodemp = resc.bdcodemp and fn.bdcodcol = resc.bdcodcol and fn.bdreffn = resc.bdrefrescisao)';
    end
 ELSE
    BEGIN
      wsql = wsql||' join ('||
         'select resc.BDCODEMP,resc.BDCODCOL,resc.BDREFFN,resc.BDDTCOMP,resc.BDCODVER,resc.BDREFVFN_SUM,resc.BDREFAUXVFN_SUM,resc.BDREFVFN_MAX,resc.BDREFAUXVFN_MAX,'||
            'resc.BDVALVFN,resc.BDIGNREFVFN,resc.BDIGNVALVFN '||
         'from VWRH_UNION_FC_FCT_CALC resc ';

      wwhere = '';
      if (prempresa <> '') then
         begin
           wwhere = wwhere||prempresa;

           if (prcolaborador <> '') then
              wwhere = wwhere||' and '||prcolaborador;
         end

      if (prrefini is not null and prreffim is not null) then
         wwhere = wwhere||' and resc.bdreffn >= '||prrefini||' and resc.bdreffn <= '||prreffim||' ';

      if (wwhere <> '') then
         wwhere = ' where '||wwhere;

      wsql = wsql||wwhere;

      wsql = wsql||' union all '||
         'select resc.BDCODEMP,resc.BDCODCOL,resc.BDREFFN,resc.BDDTCOMP,resc.BDCODVER,resc.BDREFVFN_SUM,resc.BDREFAUXVFN_SUM,resc.BDREFVFN_MAX,resc.BDREFAUXVFN_MAX,'||
            'resc.BDVALVFN,resc.BDIGNREFVFN,resc.BDIGNVALVFN '||
         'from vwrh_union_fci_fcit_calc resc ';

      wwhere = '';
      if (prempresa <> '') then
         begin
           wwhere = wwhere||prempresa;

           if (prcolaborador <> '') then
              wwhere = wwhere||' and '||prcolaborador;
         end

      if (prrefini is not null and prreffim is not null) then
         wwhere = wwhere||' and resc.bdreffn >= '||prrefini||' and resc.bdreffn <= '||prreffim||' ';

      if (wwhere <> '') then
         wwhere = ' where '||wwhere;

      wsql = wsql||wwhere;
      wsql = wsql||') fn on (fn.bdcodemp = resc.bdcodemp and fn.bdcodcol = resc.bdcodcol) ';
    END

  wsql = wsql||
          'join vrh_emp_tcolcon colcon on (colcon.bdcodemp = resc.bdcodemp and colcon.bdcodcol = resc.bdcodcol) '||
          'left outer join VRH_EMP_TCOL_ADM COL_ADM on (COL_ADM.BDCODEMP = COLCON.BDCODEMP and COL_ADM.BDCODCOL = COLCON.BDCODCOL) '||
          'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = RESC.BDCODEMP and COLCAD.BDCODCOL = RESC.BDCODCOL) '||
          'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = RESC.BDCODEMP and DOCREF.BDCODCOL = RESC.BDCODCOL) '||
          'join VW_TEMPRESAS_REF empresas on (empresas.bdcodemp = RESC.bdcodemp ) '||
          'join tempresas emp on (emp.bdcodemp = resc.bdcodemp) '||
          --'join VRH_BASE_TPREPRESC PRERESC on (preresc.bdcodpres = resc.bdcodpres) '||
          'join VRH_BASE_TPREPRESC PRERESC on (preresc.bdcodpres = COALESCE(RESC.BDNOVOCODPRES, resc.bdcodpres)) '||
          'left outer join VW_VRHF_BASE_TEMPCALC empref on (empref.bdcodemp = resc.bdcodemp) '||
          'left outer join vrh_emp_tcolcon_doc doc on (doc.bdcodemp = resc.bdcodemp and doc.bdcodcol = resc.bdcodcol) '||
          'left outer join VRH_EMP_TCOL_DOC doccol on (doccol.bdcodemp = resc.bdcodemp and doccol.bdcodcol = resc.bdcodcol) '||
          'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS fgtscol on (fgtscol.bdcodemp = resc.bdcodemp and fgtscol.bdcodcol = resc.bdcodcol) '||
          'left outer join vrh_emp_tcol_parent parcol on (parcol.bdcodemp = resc.bdcodemp and parcol.bdcodcol = resc.bdcodcol) '||
          'left outer join VW_VRH_EMP_TCOL_VINC tcon_vinc on (tcon_vinc.bdcodemp = resc.bdcodemp and tcon_vinc.bdcodcol = resc.bdcodcol) '||
          'left outer join VW_vrh_emp_tcolcon_vinc tcolcon_vinc on (tcolcon_vinc.bdcodemp = resc.bdcodemp and tcolcon_vinc.bdcodcol = resc.bdcodcol) '||
          'left outer join vw_vrhf_emp_tcol_calc colcalc on (colcalc.BDCODEMP = RESC.BDCODEMP and colcalc.BDCODCOL = RESC.BDCODCOL) ' ;

  IF (prfuncao > 0) THEN
     wsql = wsql||
                'left outer join VW_TCOLCON_VINCDIA vincdia on (vincdia.bdcodemp = resc.bdcodemp and vincdia.bdcodcol = resc.bdcodcol) ';

  wsql = wsql||
             'left outer join VW_VRHF_EMP_TCOL_CALC tcol_calc on (tcol_calc.bdcodemp = resc.bdcodemp and tcol_calc.bdcodcol = resc.bdcodcol) '||
             'left outer join VW_VRH_BASE_TSINDTREF sind on (sind.BDCODSINTRAB = tcon_vinc.BDCODSINTRAB) ';

  wsql = wsql||' join vrh_base_tverbas tverbas on (fn.bdcodver = tverbas.bdcodver) '||
               '  left outer join vw_verbas_ref_atual verref on (verref.bdcodver = tverbas.bdcodver) '||
               '  left outer join tcidade cidemp on (empresas.bdcodcid = cidemp.bdcodcid) '||
               '  left outer join tcidade cidcol on (cidcol.bdcodcid = colcad.bdcodcid) '||
               '  left outer join tuf ufemp on (ufemp.bdcoduf = cidemp.bdcoduf) '||
               '  left outer join tuf ufcol on (ufcol.bdcoduf = cidcol.bdcoduf) '||
               '  left outer join tuf ufctps on (ufctps.bdcoduf = docref.bdcoduf) '||
               '  left outer join vrh_base_tverbas class on (class.bdclaver = substring(tverbas.bdclaver from 1 for 5)) '||
               '  left outer join vrhf_emp_tprepfn pfn on (pfn.bdcodemp = resc.bdcodemp and pfn.bdcodcol = resc.bdcodcol and '||
                                                          'bdordem = (select max(bdordem) from vrhf_emp_tprepfn '||
                                                                     'where bdcodemp = pfn.bdcodemp and bdcodcol = pfn.bdcodcol)) '||
               '  left outer join vrh_base_tcustom tom on (tom.bdcodcentro = pfn.bdcodcentro and tom.bdcodtpcc = pfn.bdcodtpcc) '||
               '  left outer join TEMPRESAS EMPM on (EMPM.BDCODEMP = EMP.BDCODMATRIZ) '||
               '  left outer join TEMPRESAS_REF EMPRM on (EMPRM.BDCODEMP = EMPM.BDCODEMP and EMPRM.BDREFEMP = (select first 1 BDREFEMP '||
                                                                                                              'from TEMPRESAS_REF '||
                                                                                                              'where BDCODEMP = EMPRM.BDCODEMP and '||
                                                                                                                    'BDREFEMP <= ' || :prreffim || ' '||
                                                                                                              'order by BDCODEMP desc, BDREFEMP desc)) '||
                 'left outer join TCIDADE CIDEMPM on (CIDEMPM.BDCODCID = EMPRM.BDCODCID) '||
                 'left outer join TUF UFMAT on (UFMAT.BDCODUF = CIDEMPM.BDCODUF) ';

  wwhere = '';

  IF (:prrefini IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and RESC.BDDATARESCISAO >= '''||:wdatainicial||''' ';
       ELSE
          wwhere = wwhere||' where RESC.BDDATARESCISAO >= '''||:wdatainicial||''' ';
    END

  IF (:prreffim IS NOT NULL) THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and RESC.BDDATARESCISAO <= '''||:wdatafinal||''' ';
       ELSE
          wwhere = wwhere||' where RESC.BDDATARESCISAO <= '''||:wdatafinal||''' ';
    END


  IF (prempresa <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prempresa||' ';
     END


  IF (prcolaborador <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador||' ';
     END

  IF (prfuncao > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'vincdia.bdcodtfuc = '||prfuncao||' ';  -- funcionario
     END

  IF (prsindicato > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere||'tcon_vinc.bdCODSINTRAB = '||prsindicato||' ';  -- TCOLVINC.
     END

  IF (prclasse > 0) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||'tcolcon_vinc.bdCODCLA = '||prclasse||' '; -- tcolcon_vinc
     END

  IF (prtipofiltro = 1) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||' coalesce(verref.bdtipocodver, 0) in (0,2) ';
     END

  IF (prtipofiltro = 2) THEN
     BEGIN
        IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
        wwhere = wwhere||' coalesce(verref.bdtipocodver, 0) in (1,3) ';
     END

 IF ((NOT ((prtipofolha IS NULL) OR (prtipofolha = 0))) AND (prdtpgto IS NOT NULL)) THEN
    BEGIN
        IF (wwhere <> '') THEN
           wwhere = wwhere||' and ';
        ELSE
           wwhere = wwhere||' where ';
        wwhere = wwhere||' fn.bddtcomp >= '||PRDTPGTO||' and fn.bddtcomp <= '||PRDTPGTOFIM;
    END

 wsql = wsql||wwhere;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdnomemp,
    :bdcnpjemp,
    :BDCODCOL,
    :bdnomcol,
    :bdcpfcol,
    :bdlogremp,
    :bdendemp,
    :bdnumemp,
    :bdbaiemp,
    :bdnomcid,
    :bdsiglaufemp,
    :bdcepemp,
    :bdcodcnae,
    :bdpiscol,
    :bdlogrcol,
    :bdendcol,
    :bdnumcol,
    :bdbaicol,
    :bdcepcol,
    :bdnomcidcol,
    :bdsiglaufcol,
    :bdctpscol,
    :bdseriectpscol,
    :BDDSERIECTPSCOL,
    :bddatanasccol,
    :bdnommaecol,
    :bddataadmcol,
    :bdcategoriacol,
    :bddataavprevio,
    :bdchaveindentificacao,
    :bdrefrescisao,
    :bddescpres,
    :bdcodsaque, 
    :bddatarescisao,
    :bddatapagrescisao,
    :bdref,
    :bdcodver,
    :bddescver,
    :bddescredver,
    :bdrefv,
    :bdrefauxv,
    :bdhever,
    :bdprovento,
    :bddesconto,
    :bdordemver,
    :bdclaver,
    :bdpercinsalubcol,
    :bdpercpericulcol,
    :bdpercnoturnocol,
    :bdhorasdiariascol,
    :bdsiglaufctps,
    :bdtiporefver,
    :bdrefhoremp,
    :bdclaveraux,
    :bddescveraux,
    :bdproventooutros,
    :bddescontooutros,
    :bdtipocol,
    :bdcnpjtom
    DO

   SUSPEND;
END^

/* Restore proc. body: VRHF_SP_RETORNAEMPRESA_GPS */
ALTER PROCEDURE VRHF_SP_RETORNAEMPRESA_GPS(PREMP INTEGER,
PRREF INTEGER)
 RETURNS(BDSIMPLESGPS INTEGER)
 AS
BEGIN
  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

/*  select BDSIMPLESGPS from VW_VRHF_BASE_TEMPGPSx where bdcodemp = :premp
  into
    :BDSIMPLESGPS;*/

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: VRHF_SP_SALARIOS_CONTRIB */
ALTER PROCEDURE VRHF_SP_SALARIOS_CONTRIB(PREMPRESA VARCHAR(15000),
PRCOLABORADOR VARCHAR(30000),
PRORDEMIMP INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRCENTROCUSTO INTEGER,
PRSINDICATO INTEGER,
PRBANCO INTEGER,
PRAGENCIA INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDLOGREMP DM_LOGRADOURO,
BDENDEMP DM_BDENDERECO,
BDNUMEMP DM_NUMEND,
BDCOMPLEMP DM_BDCOMPENDERECO,
BDBAIEMP DM_BDBAIRRO,
BDNOMCIDEMP VARCHAR(40),
BDSIGLAUFEMP VARCHAR(2),
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL VARCHAR(70),
BDDATAADMCOL DATE,
BDCPFCOL VARCHAR(14),
BDPISCOL VARCHAR(14),
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDSIGLAUFCTPS VARCHAR(2),
BDDATARESCISAO DATE,
BDDATAINSS DATE,
BDREFINSS INTEGER,
BDBASEINSS NUMERIC(15,6),
BDVALORINSS NUMERIC(15,2),
BDCODEMPAUX INTEGER,
BDCODCOLAUX INTEGER,
BDDATAINSSAUX DATE,
BDVALORINSSAUX NUMERIC(15,6),
BDBASEINSSAUX NUMERIC(15,6),
BDREFINSSAUX INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WSQLAUX VARCHAR(30000);
DECLARE VARIABLE WWHERE VARCHAR(15000);
DECLARE VARIABLE WWHEREAUX VARCHAR(15000);
DECLARE VARIABLE WORDERBY VARCHAR(10000);
BEGIN
   IF (prreferencia IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, PRULTIMODIA);


   wWhere = '';

   IF (prEmpresa <> '') THEN
      wWhere = wWhere || prEmpresa || ' ';

   IF (prColaborador <> '') THEN
     BEGIN
       IF (wWhere <> '') THEN
         wWhere = wWhere || ' and ';
       wWhere = wWhere || prColaborador || ' ';
     END

   wOrderBy = '';
   IF (prOrdemImp IS NOT NULL) THEN
     BEGIN
       wOrderBy = 'order by ';
        
       IF (prOrdemImp = 0) THEN
         wOrderBy = wOrderBy || 'BDCODEMP, BDCODCOL, BDREFINSS ';
       ELSE IF (prOrdemImp = 1) THEN
         wOrderBy = wOrderBy || 'BDCODEMP, BDNOMCOL, BDREFINSS ';
     END

   wSqlAux = '';
   wWhereAux = '';
   IF (prFuncao > 0) THEN
     BEGIN
       IF (wWhereAux <> '') THEN
         wWhereAux = wWhereAux || ' and ';

       wWhereAux = wWhereAux || 'TFUC.BDCODTFUC = ' || prFuncao || ' ';

       wSqlAux = wSqlAux || 'left outer join VW_TCOLCON_VINCDIA COL_DIA on (COL_DIA.BDCODEMP = FOL.BDCODEMP and COL_DIA.BDCODCOL = FOL.BDCODCOL) ';
       wSqlAux = wSqlAux || 'left outer join VRH_FUNCOES_TFUC TFUC on (TFUC.BDCODPLAFUC = COL_DIA.BDCODPLAFUC and TFUC.BDCODTFUC = COL_DIA.BDCODTFUC) ';
     END

   IF (prSindicato > 0) THEN
     BEGIN
       IF (wWhereAux <> '') THEN
         wWhereAux = wWhereAux || ' and ';

       wWhereAux = wWhereAux || 'COL_VINC.BDCODSINTRAB = ' || prSindicato || ' ';

       wSqlAux = wSqlAux || 'left outer join VW_VRH_EMP_TCOL_VINC COL_VINC on (COL_VINC.BDCODEMP = FOL.BDCODEMP and COL_VINC.BDCODCOL = FOL.BDCODCOL) ';
     END

   IF (prClasse > 0) THEN
     BEGIN
       IF (wWhereAux <> '') THEN
         wWhereAux = wWhereAux || ' and ';

       wWhereAux = wWhereAux || 'COLCON_VINC.BDCODCLA = ' || prClasse || ' ';

       wSqlAux = wSqlAux || 'left outer join VW_VRH_EMP_TCOLCON_VINC COLCON_VINC on (COLCON_VINC.BDCODEMP = FOL.BDCODEMP and COLCON_VINC.BDCODCOL = FOL.BDCODCOL) ';
     END

   IF (prBanco > 0) THEN
     BEGIN
       IF (wWhereAux <> '') THEN
         wWhereAux = wWhereAux || ' and ';

       wWhereAux = wWhereAux || 'COLCON_BANCO.BDCODBAN = ' || prBanco || ' ';

       wSqlAux = wSqlAux || 'left outer join VW_VRHF_EMP_TCOLCON_BANCO COLCON_BANCO on (COLCON_BANCO.BDCODEMP = FOL.BDCODEMP and COLCON_BANCO.BDCODCOL = FOL.BDCODCOL) ';
     END

   IF (prAgencia > 0) THEN
     BEGIN
       IF (wWhereAux <> '') THEN
         wWhereAux = wWhereAux || ' and ';

       wWhereAux = wWhereAux || 'COLCON_BANCO.BDCODAG = ' || prAgencia || ' ';

       IF (NOT (prBanco > 0)) THEN
         wSqlAux = wSqlAux || 'left outer join VW_VRHF_EMP_TCOLCON_BANCO COLCON_BANCO on (COLCON_BANCO.BDCODEMP = FOL.BDCODEMP and COLCON_BANCO.BDCODCOL = FOL.BDCODCOL) ';
     END

   wsql = 'select ';
   --wsql = wsql || 'BDCODEMP, ';
   wsql = wsql || 'CALC.BDCODEMP, ';
   wsql = wsql || 'BDNOMEMP, ';
   wsql = wsql || 'BDLOGREMP, ';
   wsql = wsql || 'BDENDEMP, ';
   wsql = wsql || 'BDNUMEMP, ';
   wsql = wsql || 'BDCOMPLEMP, ';
   wsql = wsql || 'BDBAIEMP, ';
   wsql = wsql || 'BDNOMCID, ';
   --wsql = wsql || 'BDSIGLAUFEMP, ';
   wsql = wsql || 'TUF_EMP.BDSIGLAUF as BDSIGLAUFEMP, ';
   --wsql = wsql || 'BDCNPJEMP, ';
   wsql = wsql || 'TEMPA.BDCNPJEMP, ';
   --wsql = wsql || 'BDCODCOL, ';
   wsql = wsql || 'COL.BDCODCOL, ';
   wsql = wsql || 'BDNOMCOL, ';
   wsql = wsql || 'BDDATAADMCOL, ';
   --wsql = wsql || 'BDCPFCOL, ';
   wsql = wsql || 'COL_DOC.BDCPFCOL, ';
   wsql = wsql || 'BDPISCOL, ';
   wsql = wsql || 'BDCTPSCOL, ';
   wsql = wsql || 'BDSERIECTPSCOL, ';
   wsql = wsql || 'BDDSERIECTPSCOL, ';
   --wsql = wsql || 'BDSIGLAUFDOC, ';
   wsql = wsql || 'TUF_DOC.BDSIGLAUF as BDSIGLAUFDOC, ';
   wsql = wsql || 'BDDATARESCISAO, ';
   wsql = wsql || 'NULL BDDATAINSS, ';
   wsql = wsql || 'BDREFINSS, ';
   wsql = wsql || 'SUM(coalesce(BDBASEINSS, 0)) BDBASEINSS, ';
   wsql = wsql || 'SUM(coalesce(BDVALORINSS, 0)) BDVALORINSS ';

   wsql = wsql || 'from ( ';

   /*wsql = wsql || 'select FOL.BDCODEMP, EMP_REF.BDNOMEMP, EMP_REF.BDLOGREMP, EMP_REF.BDENDEMP, EMP_REF.BDNUMEMP, EMP_REF.BDCOMPLEMP, EMP_REF.BDBAIEMP, ';
   wsql = wsql || '       CID.BDNOMCID, TUF_EMP.BDSIGLAUF BDSIGLAUFEMP, TEMP.BDCNPJEMP, ';
   wsql = wsql || '       FOL.BDCODCOL, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, COL_DOC.BDCPFCOL, DOCREF.BDPISCOL, ';
   wsql = wsql || '       DOCREF.BDCTPSCOL, DOCREF.BDSERIECTPSCOL, DOCREF.BDDSERIECTPSCOL, TUF_DOC.BDSIGLAUF BDSIGLAUFDOC, RESC.BDDATARESCISAO, ';
   wsql = wsql || '       coalesce(FOL.BDREFFN, 0) as BDREFINSS, ';
   wsql = wsql || '       coalesce(FOL.BDBINSSFN, 0) + coalesce(FOL.BDBINSSFEFOLFN, 0) + coalesce(FOL.BDBINSS13FN, 0) as BDBASEINSS, ';
   wsql = wsql || '       coalesce(FOL.BDINSSFN, 0) + coalesce(FOL.BDINSSFEFOLFN, 0) + coalesce(FOL.BDINSS13FN, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_TFOLHANORMAL FOL ';
   wsql = wsql || 'left outer join TEMPRESAS TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join VW_TEMPRESAS_REF EMP_REF on (EMP_REF.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join TCIDADE CID on (CID.BDCODCID = EMP_REF.BDCODCID) ';
   wsql = wsql || 'left outer join TUF TUF_EMP on (TUF_EMP.BDCODUF = CID.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON_DOC COL_DOC on (COL_DOC.BDCODEMP = COL.BDCODEMP and COL_DOC.BDCODCOL = COL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FOL.BDCODEMP and DOCREF.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join TUF TUF_DOC on (TUF_DOC.BDCODUF = DOCREF.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';*/

   wsql = wsql || 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, coalesce(FOL.BDREFFN, 0) as BDREFINSS, ';
   wsql = wsql || 'coalesce(FOL.BDBINSSFN, 0) + coalesce(FOL.BDBINSSFEFOLFN, 0) + coalesce(FOL.BDBINSS13FN, 0) as BDBASEINSS, ';
   wsql = wsql || 'coalesce(FOL.BDINSSFN, 0) + coalesce(FOL.BDINSSFEFOLFN, 0) + coalesce(FOL.BDINSS13FN, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_TFOLHANORMAL FOL ';

   IF (wSqlAux <> '') THEN
     wsql = wsql || wSqlAux;

   IF (wWhere <> '') THEN
     wsql = wsql || 'where ' || wWhere || ' and (FOL.BDREFFN <= ' || prReferencia || ') ';
   ELSE
     wsql = wsql || 'where (FOL.BDREFFN <= ' || prReferencia || ') ';

   IF (wWhereAux <> '') THEN
     wsql = wsql || ' and ' || wWhereAux || ' ';

   wsql = wsql || 'union all ';

   /*wsql = wsql || 'select FOL.BDCODEMP, EMP_REF.BDNOMEMP, EMP_REF.BDLOGREMP, EMP_REF.BDENDEMP, EMP_REF.BDNUMEMP, EMP_REF.BDCOMPLEMP, EMP_REF.BDBAIEMP, ';
   wsql = wsql || '       CID.BDNOMCID, TUF_EMP.BDSIGLAUF BDSIGLAUFEMP, TEMP.BDCNPJEMP, ';
   wsql = wsql || '       FOL.BDCODCOL, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, COL_DOC.BDCPFCOL, DOCREF.BDPISCOL, ';
   wsql = wsql || '       DOCREF.BDCTPSCOL, DOCREF.BDSERIECTPSCOL, DOCREF.BDDSERIECTPSCOL, TUF_DOC.BDSIGLAUF BDSIGLAUFDOC, RESC.BDDATARESCISAO, ';
   wsql = wsql || '       coalesce(FOL.BDREFTOMADOR, 0) as BDREFINSS, ';
   wsql = wsql || '       coalesce(FOL.BDBINSSFT, 0) + coalesce(FOL.BDBINSSFEFOLFT, 0) + coalesce(FOL.BDBINSS13FT, 0) as BDBASEINSS, ';
   wsql = wsql || '       coalesce(FOL.BDINSSFT, 0) + coalesce(FOL.BDINSSFEFOLFT, 0) + coalesce(FOL.BDINSS13FT, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_TFOLHATOMADOR FOL ';
   wsql = wsql || 'left outer join TEMPRESAS TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join VW_TEMPRESAS_REF EMP_REF on (EMP_REF.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join TCIDADE CID on (CID.BDCODCID = EMP_REF.BDCODCID) ';
   wsql = wsql || 'left outer join TUF TUF_EMP on (TUF_EMP.BDCODUF = CID.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON_DOC COL_DOC on (COL_DOC.BDCODEMP = COL.BDCODEMP and COL_DOC.BDCODCOL = COL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FOL.BDCODEMP and DOCREF.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join TUF TUF_DOC on (TUF_DOC.BDCODUF = DOCREF.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';*/

   wsql = wsql || 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, coalesce(FOL.BDREFTOMADOR, 0) as BDREFINSS, ';
   wsql = wsql || 'coalesce(FOL.BDBINSSFT, 0) + coalesce(FOL.BDBINSSFEFOLFT, 0) + coalesce(FOL.BDBINSS13FT, 0) as BDBASEINSS, ';
   wsql = wsql || 'coalesce(FOL.BDINSSFT, 0) + coalesce(FOL.BDINSSFEFOLFT, 0) + coalesce(FOL.BDINSS13FT, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_TFOLHATOMADOR FOL ';

   IF (wSqlAux <> '') THEN
     wsql = wsql || wSqlAux;

   IF (wWhere <> '') THEN
     wsql = wsql || 'where ' || wWhere || ' and (FOL.BDREFTOMADOR <= ' || prReferencia || ') ';
   ELSE
     wsql = wsql || 'where (FOL.BDREFTOMADOR <= ' || prReferencia || ') ';

   IF (wWhereAux <> '') THEN
     wsql = wsql || ' and ' || wWhereAux || ' ';

   wsql = wsql || 'union all ';

   /*wsql = wsql || 'select FOL.BDCODEMP, EMP_REF.BDNOMEMP, EMP_REF.BDLOGREMP, EMP_REF.BDENDEMP, EMP_REF.BDNUMEMP, EMP_REF.BDCOMPLEMP, EMP_REF.BDBAIEMP, ';
   wsql = wsql || '       CID.BDNOMCID, TUF_EMP.BDSIGLAUF BDSIGLAUFEMP, TEMP.BDCNPJEMP, ';
   wsql = wsql || '       FOL.BDCODCOL, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, COL_DOC.BDCPFCOL, DOCREF.BDPISCOL, ';
   wsql = wsql || '       DOCREF.BDCTPSCOL, DOCREF.BDSERIECTPSCOL, DOCREF.BDDSERIECTPSCOL, TUF_DOC.BDSIGLAUF BDSIGLAUFDOC, RESC.BDDATARESCISAO, ';
   wsql = wsql || '       coalesce(substring(FOL.BDREFFC from 1 for 6), 0) as BDREFINSS, ';
   wsql = wsql || '       coalesce(FOL.BDBINSSFC, 0) as BDBASEINSS, ';
   wsql = wsql || '       coalesce(FOL.BDINSSFC, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_TFOLHACOMP FOL ';
   wsql = wsql || 'left outer join TEMPRESAS TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join VW_TEMPRESAS_REF EMP_REF on (EMP_REF.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join TCIDADE CID on (CID.BDCODCID = EMP_REF.BDCODCID) ';
   wsql = wsql || 'left outer join TUF TUF_EMP on (TUF_EMP.BDCODUF = CID.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON_DOC COL_DOC on (COL_DOC.BDCODEMP = COL.BDCODEMP and COL_DOC.BDCODCOL = COL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FOL.BDCODEMP and DOCREF.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join TUF TUF_DOC on (TUF_DOC.BDCODUF = DOCREF.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';*/

   wsql = wsql || 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFC, coalesce(substring(FOL.BDREFFC from 1 for 6), 0) as BDREFINSS, ';
   wsql = wsql || 'coalesce(FOL.BDBINSSFC, 0) as BDBASEINSS, coalesce(FOL.BDINSSFC, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_TFOLHACOMP FOL ';

   IF (wSqlAux <> '') THEN
     wsql = wsql || wSqlAux;

   IF (wWhere <> '') THEN
     wsql = wsql || 'where ' || wWhere || ' and (FOL.BDREFFN <= ' || prReferencia || ') ';
   ELSE
     wsql = wsql || 'where (FOL.BDREFFN <= ' || prReferencia || ') ';

   IF (wWhereAux <> '') THEN
     wsql = wsql || ' and ' || wWhereAux || ' ';

   wsql = wsql || 'union all ';

   /*wsql = wsql || 'select FOL.BDCODEMP, EMP_REF.BDNOMEMP, EMP_REF.BDLOGREMP, EMP_REF.BDENDEMP, EMP_REF.BDNUMEMP, EMP_REF.BDCOMPLEMP, EMP_REF.BDBAIEMP, ';
   wsql = wsql || '       CID.BDNOMCID, TUF_EMP.BDSIGLAUF BDSIGLAUFEMP, TEMP.BDCNPJEMP, ';
   wsql = wsql || '       FOL.BDCODCOL, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, COL_DOC.BDCPFCOL, DOCREF.BDPISCOL, ';
   wsql = wsql || '       DOCREF.BDCTPSCOL, DOCREF.BDSERIECTPSCOL, DOCREF.BDDSERIECTPSCOL, TUF_DOC.BDSIGLAUF BDSIGLAUFDOC, RESC.BDDATARESCISAO, ';
   wsql = wsql || '       coalesce(substring(FOL.BDREFTOMADOR from 1 for 6), 0) as BDREFINSS, ';
   wsql = wsql || '       coalesce(FOL.BDBINSSFC, 0) as BDBASEINSS, ';
   wsql = wsql || '       coalesce(FOL.BDINSSFC, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_TFOLTOMCOMP FOL ';
   wsql = wsql || 'left outer join TEMPRESAS TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join VW_TEMPRESAS_REF EMP_REF on (EMP_REF.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join TCIDADE CID on (CID.BDCODCID = EMP_REF.BDCODCID) ';
   wsql = wsql || 'left outer join TUF TUF_EMP on (TUF_EMP.BDCODUF = CID.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON_DOC COL_DOC on (COL_DOC.BDCODEMP = COL.BDCODEMP and COL_DOC.BDCODCOL = COL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FOL.BDCODEMP and DOCREF.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join TUF TUF_DOC on (TUF_DOC.BDCODUF = DOCREF.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';*/

   wsql = wsql || 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, ';
   wsql = wsql || 'coalesce(substring(FOL.BDREFTOMADOR from 1 for 6), 0) as BDREFINSS, ';
   wsql = wsql || 'coalesce(FOL.BDBINSSFC, 0) as BDBASEINSS, coalesce(FOL.BDINSSFC, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_TFOLTOMCOMP FOL ';

   IF (wSqlAux <> '') THEN
     wsql = wsql || wSqlAux;

   IF (wWhere <> '') THEN
     wsql = wsql || 'where ' || wWhere || ' and (FOL.BDREFTOMADOR <= ' || prReferencia || ') ';
   ELSE
     wsql = wsql || 'where (FOL.BDREFTOMADOR <= ' || prReferencia || ') ';

   IF (wWhereAux <> '') THEN
     wsql = wsql || ' and ' || wWhereAux || ' ';

   wsql = wsql || 'union all ';

   /*wsql = wsql || 'select FOL.BDCODEMP, EMP_REF.BDNOMEMP, EMP_REF.BDLOGREMP, EMP_REF.BDENDEMP, EMP_REF.BDNUMEMP, EMP_REF.BDCOMPLEMP, EMP_REF.BDBAIEMP, ';
   wsql = wsql || '       CID.BDNOMCID, TUF_EMP.BDSIGLAUF BDSIGLAUFEMP, TEMP.BDCNPJEMP, ';
   wsql = wsql || '       FOL.BDCODCOL, COLCAD.BDNOMCOL, COL.BDDATAADMCOL, COL_DOC.BDCPFCOL, DOCREF.BDPISCOL, ';
   wsql = wsql || '       DOCREF.BDCTPSCOL, DOCREF.BDSERIECTPSCOL, DOCREF.BDDSERIECTPSCOL, TUF_DOC.BDSIGLAUF BDSIGLAUFDOC, RESC.BDDATARESCISAO, ';
   wsql = wsql || '       coalesce(substring(FOL.BDREF13 from 1 for 4) || 13, 0) as BDREFINSS, ';
   wsql = wsql || '       coalesce(FOL.BDBASEINSS13, 0) as BDBASEINSS, ';
   wsql = wsql || '       coalesce(FOL.BDVALORINSS13, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_T13SAL FOL ';
   wsql = wsql || 'left outer join VRHF_EMP_TC13SAL CFOL on (CFOL.BDCODEMP = FOL.BDCODEMP and CFOL.BDCODCOL = FOL.BDCODCOL and CFOL.BDREFC13 <= ' || prReferencia || ') ';
   wsql = wsql || 'left outer join TEMPRESAS TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join VW_TEMPRESAS_REF EMP_REF on (EMP_REF.BDCODEMP = FOL.BDCODEMP) ';
   wsql = wsql || 'left outer join TCIDADE CID on (CID.BDCODCID = EMP_REF.BDCODCID) ';
   wsql = wsql || 'left outer join TUF TUF_EMP on (TUF_EMP.BDCODUF = CID.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = FOL.BDCODEMP and COL.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = FOL.BDCODEMP and COLCAD.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = FOL.BDCODEMP and DOCREF.BDCODCOL = FOL.BDCODCOL) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON_DOC COL_DOC on (COL_DOC.BDCODEMP = COL.BDCODEMP and COL_DOC.BDCODCOL = COL.BDCODCOL) ';
   wsql = wsql || 'left outer join TUF TUF_DOC on (TUF_DOC.BDCODUF = DOCREF.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';*/

   wsql = wsql || 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13, ';
   wsql = wsql || 'coalesce(substring(FOL.BDREF13 from 1 for 4) || 13, 0) as BDREFINSS, ';
   wsql = wsql || 'coalesce(FOL.BDBASEINSS13, 0) as BDBASEINSS, coalesce(FOL.BDVALORINSS13, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_T13SAL FOL ';
   wsql = wsql || 'left outer join VRHF_EMP_TC13SAL CFOL on (CFOL.BDCODEMP = FOL.BDCODEMP and ';
   wsql = wsql || 'CFOL.BDCODCOL = FOL.BDCODCOL and ';
   wsql = wsql || 'CFOL.BDREFC13 <= 202008) ';

   IF (wSqlAux <> '') THEN
     wsql = wsql || wSqlAux;

   IF (wWhere <> '') THEN
      wsql = wsql || 'where ' || wWhere || ' and (FOL.BDREF13 <= ' || prReferencia || ') ';
   ELSE
      wsql = wsql || 'where (FOL.BDREF13 <= ' || prReferencia || ') ';

   IF (wWhereAux <> '') THEN
     wsql = wsql || ' and ' || wWhereAux || ' ';

   wsql = wsql || 'union all ';

   wsql = wsql || 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, ';
   wsql = wsql || 'coalesce(substring(FOL.BDREFTOMADOR from 1 for 6), 0) as BDREFINSS, ';
   wsql = wsql || 'coalesce(FOL.BDBASEINSSNMVNOVO, 0) as BDBASEINSS, coalesce(FOL.BDINSSFT, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_TFOLHATOMINT FOL ';

   IF (wSqlAux <> '') THEN
     wsql = wsql || wSqlAux;

   IF (wWhere <> '') THEN
      wsql = wsql || 'where ' || wWhere || ' and (FOL.BDREFTOMADOR <= ' || prReferencia || ') ';
   ELSE
      wsql = wsql || 'where (FOL.BDREFTOMADOR <= ' || prReferencia || ') ';

   IF (wWhereAux <> '') THEN
     wsql = wsql || ' and ' || wWhereAux || ' ';

   wsql = wsql || 'union all ';

   wsql = wsql || 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFC, ';
   wsql = wsql || 'coalesce(substring(FOL.BDREFTOMADOR from 1 for 6), 0) as BDREFINSS, ';
   wsql = wsql || 'coalesce(FOL.BDBASEINSSNMVNOVO, 0) as BDBASEINSS, coalesce(FOL.BDINSSFC, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_TFOLTOMCOMPINT FOL ';

   IF (wSqlAux <> '') THEN
     wsql = wsql || wSqlAux;

   IF (wWhere <> '') THEN
      wsql = wsql || 'where ' || wWhere || ' and (FOL.BDREFTOMADOR <= ' || prReferencia || ') ';
   ELSE
      wsql = wsql || 'where (FOL.BDREFTOMADOR <= ' || prReferencia || ') ';

   IF (wWhereAux <> '') THEN
     wsql = wsql || ' and ' || wWhereAux || ' ';

   wsql = wsql || 'union all ';

   wsql = wsql || 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, coalesce(substring(FOL.BDREFFN from 1 for 6), 0) as BDREFINSS, ';
   wsql = wsql || 'coalesce(FOL.BDBASEINSSNMVNOVO, 0) as BDBASEINSS, coalesce(FOL.BDINSSFN, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_TFOLHAINT FOL ';

   IF (wSqlAux <> '') THEN
     wsql = wsql || wSqlAux;

   IF (wWhere <> '') THEN
      wsql = wsql || 'where ' || wWhere || ' and (FOL.BDREFFN <= ' || prReferencia || ') ';
   ELSE
      wsql = wsql || 'where (FOL.BDREFFN <= ' || prReferencia || ') ';

   IF (wWhereAux <> '') THEN
     wsql = wsql || ' and ' || wWhereAux || ' ';

   wsql = wsql || 'union all ';

   wsql = wsql || 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, coalesce(substring(FOL.BDREFFN from 1 for 6), 0) as BDREFINSS, ';
   wsql = wsql || 'coalesce(FOL.BDBASEINSSNMVNOVO, 0) as BDBASEINSS, coalesce(FOL.BDINSSFC, 0) as BDVALORINSS ';
   wsql = wsql || 'from VRHF_EMP_TFOLHACOMPINT FOL ';

   IF (wSqlAux <> '') THEN
     wsql = wsql || wSqlAux;

   IF (wWhere <> '') THEN
      wsql = wsql || 'where ' || wWhere || ' and (FOL.BDREFFN <= ' || prReferencia || ') ';
   ELSE
      wsql = wsql || 'where (FOL.BDREFFN <= ' || prReferencia || ') ';

   IF (wWhereAux <> '') THEN
     wsql = wsql || ' and ' || wWhereAux || ' ';

   wsql = wsql || ') CALC ';

   wsql = wsql || 'left outer join TEMPRESAS TEMPA on (TEMPA.BDCODEMP = CALC.BDCODEMP) ';
   wsql = wsql || 'left outer join VW_TEMPRESAS_REF EMP_REF on (EMP_REF.BDCODEMP = CALC.BDCODEMP) ';
   wsql = wsql || 'left outer join TCIDADE CID on (CID.BDCODCID = EMP_REF.BDCODCID) ';
   wsql = wsql || 'left outer join TUF TUF_EMP on (TUF_EMP.BDCODUF = CID.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = CALC.BDCODEMP and COL.BDCODCOL = CALC.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = CALC.BDCODEMP and COLCAD.BDCODCOL = CALC.BDCODCOL) ';
   wsql = wsql || 'left outer join VRH_EMP_TCOLCON_DOC COL_DOC on (COL_DOC.BDCODEMP = COL.BDCODEMP and COL_DOC.BDCODCOL = COL.BDCODCOL) ';
   wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = CALC.BDCODEMP and DOCREF.BDCODCOL = CALC.BDCODCOL) ';
   wsql = wsql || 'left outer join TUF TUF_DOC on (TUF_DOC.BDCODUF = DOCREF.BDCODUF) ';
   wsql = wsql || 'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

   wsql = wsql || 'group by BDCODEMP, BDNOMEMP, BDLOGREMP, BDENDEMP, BDNUMEMP, BDCOMPLEMP, BDBAIEMP, BDNOMCID, BDSIGLAUFEMP, BDCNPJEMP, BDCODCOL, BDNOMCOL, BDDATAADMCOL, BDCPFCOL, BDPISCOL, ';
   wsql = wsql || '         BDCTPSCOL, BDSERIECTPSCOL, BDDSERIECTPSCOL, BDSIGLAUFDOC, BDDATARESCISAO, BDDATAINSS, BDREFINSS ';
   wsql = wsql || wOrderBy;


   FOR EXECUTE STATEMENT wsql
     INTO
          :bdcodemp,
          :bdnomemp,
          :bdlogremp,
          :bdendemp,
          :bdnumemp,
          :bdcomplemp,
          :bdbaiemp,
          :bdnomcidemp,
          :bdsiglaufemp,
          :bdcnpjemp,
          :bdcodcol,
          :bdnomcol,
          :bddataadmcol,
          :bdcpfcol,
          :bdpiscol,
          :bdctpscol,
          :bdseriectpscol,
          :bddseriectpscol,
          :bdsiglaufctps,
          :bddatarescisao,
          :bddatainss,
          :bdrefinss,
          :bdbaseinss,
          :bdvalorinss DO
   SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_TCALC_AUTONOMO */
create or alter procedure VRHF_SP_TCALC_AUTONOMO (
    PRCODEMP varchar(32700),
    PRCODTER varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer)
returns (
    BDGRUPOCLA integer,
    BDCODTER integer,
    BDCODEMP integer,
    BDCODSERV integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDANOMES integer,
    BDBASEIR numeric(15,6),
    BDFAIXAIR numeric(15,6),
    BDVALORIR numeric(15,6),
    BDBASEINSS numeric(15,6),
    BDFAIXAINSS numeric(15,6),
    BDVALORINSS numeric(15,6),
    BDBASERATAPO numeric(15,6),
    BDVALORRATAPO numeric(15,6),
    BDVALORDEP numeric(15,6),
    BDVALOUTENTIDADES numeric(15,6),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDOCORRENCIACOL integer,
    BDCATEGORIACOL integer,
    BDBASEINSSNMVNOVO numeric(15,6))
as
declare variable WTERCMEI varchar(5);
declare variable WCATESOCIAL integer;
declare variable WSQL varchar(32000);
declare variable WWHERET varchar(32000);
declare variable WCODEMPAUT integer;
BEGIN
  /* pragrupatomador
     0 = Nao agrupa
     1 = Agrupa por referencia
     2 = Agrupo por referencia e centro/Tomador
     3 = Agrupa por referencia e Tomador (se nao for tomador verifica pela classificacao e nao encontrando considera empresa)
     4 = Agrupa por referencia e Tipo Tomador (so vai criar mais registros pra empresa se for tomador 155)
  */


  -- A implementação a seguir foi feita por causa de performance.
  -- Só vai retornar alguma coisa de autônomos se passar no filtro inicial
  IF (prrefini IS NOT NULL) THEN
    BEGIN
      wcodempaut = NULL;
      wsql = 'select first 1 colcon.BDCODEMP from VRHF_BASE_CALC_TERC colcon where ';

      IF (prreffim IS NOT NULL) THEN
        wsql = wsql||'colcon.bdrefinssserv >= '||prrefini||' and colcon.bdrefinssserv <= '||prreffim;
      ELSE
        wsql = wsql||'colcon.bdrefinssserv = '||prrefini||' ';
    
      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;
    
      IF (prcodter IS NOT NULL AND prcodter <> '') THEN
        wsql = wsql||' and '||prcodter;
    END
  ELSE
    wcodempaut = 1;

  EXECUTE STATEMENT wsql INTO :wcodempaut;

  wsql = '';

  IF (wcodempaut IS NOT NULL AND wcodempaut <> 0) THEN
    BEGIN
      wwheret = '';
    
      IF (prcodemp IS NOT NULL) THEN
         BEGIN
           IF (wwheret <> '') THEN
              BEGIN
                wwheret = wwheret||' and ';
              END
           ELSE
              BEGIN
                wwheret = wwheret||' where ';
              END
    
           wwheret = wwhereT||prcodemp;
         END
    
      IF (prcodter IS NOT NULL) THEN
         BEGIN
    --       if (upper(substring(prcodter from 1 for 15)) = 'COLCON.BDCODCOL') then
    --          prcodter = 'colcon.bdcodter'||substring(prcodter from 16);
    
           IF (wwheret <> '') THEN
              BEGIN
                wwheret = wwheret||' and ';
              END
           ELSE
              BEGIN
                wwheret = wwheret||' where ';
              END
    
           wwheret = wwhereT||prcodter;
         END
    
      IF ((prrefini IS NOT NULL) AND (prreffim IS NOT NULL)) THEN
         BEGIN
           IF (wwheret <> '') THEN
              BEGIN
                wwheret = wwheret||' and ';
              END
           ELSE
              BEGIN
                wwheret = wwheret||' where ';
              END
    
           wwheret = wwhereT||'cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) >= '||prrefini||' and '||'cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) <= '||prreffim;
         END
      ELSE
         BEGIN
           IF (prrefini IS NOT NULL) THEN
              BEGIN
                IF (wwheret <> '') THEN
                   BEGIN
                     wwheret = wwheret||' and ';
                   END
                ELSE
                   BEGIN
                     wwheret = wwheret||' where ';
                   END
    
                wwheret = wwhereT||'cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) = '||prrefini;
              END
           ELSE
              BEGIN
                IF (prreffim IS NOT NULL) THEN
                   BEGIN
                     IF (wwheret <> '') THEN
                        BEGIN
                          wwheret = wwheret||' and ';
                        END
                     ELSE
                        BEGIN
                          wwheret = wwheret||' where ';
                        END
    
                     wwheret = wwhereT||'cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) = '||prreffim;
                   END
              END
         END
    
      /* Procedure Text VRHF_SP_TIPO_TOMADOR_GPS*/
      IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 4)) THEN
         BEGIN
              wsql = 'select grupo.bdgrupocla, COLCON.BDCODEMP, COLCON.bdcodter, cast(null as integer),'||
                     '       max(cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer)) bdanomes,'||
                     '       sum(COLCON.bdbaseinss), max(COLCON.bdfaixainss), sum(COLCON.bdvalorinss),'||
                     '       sum(COLCON.bdbaseir), max(COLCON.bdfaixair), sum(COLCON.bdvalorir),'||
                     '       sum(COLCON.bdbaseratapo), sum(COLCON.bdvalorratapo), sum(COLCON.bdvalordep), sum(colcon.BDVALOUTENTIDADES), pf.bdCodCentro, toma.bdCODTPCC,'||
                     '       sum(colcon.bdcreditoserv), sum(colcon.bddebitoserv), max(coalesce(fgts.bdocorrenciater,0)) BDOCORRENCIACOL,'||
                     '       max(coalesce(fgts.bdcategoriater,0)) BDCATEGORIACOL,  sum(colcon.BDBASEINSSNMVNOVO) BDBASEINSSNMVNOVO '||
                     ' from vrhf_base_calc_terc COLCON'||
                     ' left outer join vrh_base_tservterc pf on'||
                     '                 (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodter = pf.bdcodter and colcon.bdcodserv = pf.bdcodserv)'||
                     ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro,'||prrefini||') toma on'||
                     '                (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro)'||
                     ' left outer join tempresas temp on (temp.bdcodemp = colcon.bdcodemp)'||
                     ' left outer join VRHF_BASE_TTERC_FGTSGPS FGTS on (FGTS.BDCODTER = COLCON.BDCODTER and '||
                                                                       'FGTS.BDREFTERC = (select first 1 BDREFTERC from VRHF_BASE_TTERC_FGTSGPS where BDCODTER = FGTS.BDCODTER and BDREFTERC <= cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) order by BDCODTER, BDREFTERC desc)) '||
                     ' left outer join VRH_BASE_TTERC_VINC COLCON_VINC on (COLCON_VINC.BDCODTER = COLCON.BDCODTER and '||
                                                                          'COLCON_VINC.BDREFTERC = (select first 1 BDREFTERC from VRH_BASE_TTERC_VINC where BDCODTER = COLCON_VINC.BDCODTER and BDREFTERC <= cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) order by BDCODTER, BDREFTERC desc)) '||
                     ' left outer join VRH_BASE_TCLASSE GRUPO on GRUPO.BDCODCLA = COLCON_VINC.BDCODCLA '||
                     wwheret||
                     'group by ter.bdgrupocla, colcon.bdcodemp, colcon.bdcodter, cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer), pf.bdCodCentro, toma.bdCODTPCC';
         END
      ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 3)) THEN
         BEGIN
              wsql = 'select grupo.bdgrupocla, COLCON.BDCODEMP, COLCON.bdcodter, cast(null as integer),'||
                     '       max(cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer)) bdanomes,'||
                     '       sum(COLCON.bdbaseinss), max(COLCON.bdfaixainss), sum(COLCON.bdvalorinss),'||
                     '       sum(COLCON.bdbaseir), max(COLCON.bdfaixair), sum(COLCON.bdvalorir),'||
                     '       sum(COLCON.bdbaseratapo), sum(COLCON.bdvalorratapo), sum(COLCON.bdvalordep), sum(colcon.BDVALOUTENTIDADES), pf.bdCodCentro, toma.bdCODTPCC,'||
                     '       sum(colcon.bdcreditoserv), sum(colcon.bddebitoserv), max(coalesce(fgts.bdocorrenciater,0)) BDOCORRENCIACOL,'||
                     '       max(coalesce(fgts.bdcategoriater,0)) BDCATEGORIACOL, sum(colcon.BDBASEINSSNMVNOVO) BDBASEINSSNMVNOVO '||
                     ' from vrhf_base_calc_terc COLCON'||
                     ' left outer join vrh_base_tservterc pf on'||
                     '                 (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodter = pf.bdcodter and colcon.bdcodserv = pf.bdcodserv)'||
                     ' left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on'||
                     '                (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro)'||
                     ' left outer join VRHF_BASE_TTERC_FGTSGPS FGTS on (FGTS.BDCODTER = COLCON.BDCODTER and '||
                                                                       'FGTS.BDREFTERC = (select first 1 BDREFTERC from VRHF_BASE_TTERC_FGTSGPS where BDCODTER = FGTS.BDCODTER and BDREFTERC <= cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) order by BDCODTER, BDREFTERC desc)) '||
                     ' left outer join VRH_BASE_TTERC_VINC COLCON_VINC on (COLCON_VINC.BDCODTER = COLCON.BDCODTER and '||
                                                                          'COLCON_VINC.BDREFTERC = (select first 1 BDREFTERC from VRH_BASE_TTERC_VINC where BDCODTER = COLCON_VINC.BDCODTER and BDREFTERC <= cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) order by BDCODTER, BDREFTERC desc)) '||
                     ' left outer join VRH_BASE_TCLASSE GRUPO on GRUPO.BDCODCLA = COLCON_VINC.BDCODCLA '||
                     wwheret||
                     'group by ter.bdgrupocla, colcon.bdcodemp, colcon.bdcodter, cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer), pf.bdCodCentro, toma.bdCODTPCC';
         END
      ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 2)) THEN
         BEGIN
              wsql = 'select grupo.bdgrupocla, COLCON.BDCODEMP, COLCON.bdcodter, cast(null as integer),'||
                     '       max(cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer)) bdanomes,'||
                     '       sum(COLCON.bdbaseinss), max(COLCON.bdfaixainss), sum(COLCON.bdvalorinss),'||
                     '       sum(COLCON.bdbaseir), max(COLCON.bdfaixair), sum(COLCON.bdvalorir),'||
                     '       sum(COLCON.bdbaseratapo), sum(COLCON.bdvalorratapo), sum(COLCON.bdvalordep), sum(colcon.BDVALOUTENTIDADES), pf.bdCodCentro, pf.bdCODTPCC,'||
                     '       sum(colcon.bdcreditoserv), sum(colcon.bddebitoserv), max(coalesce(fgts.bdocorrenciater,0)) BDOCORRENCIACOL, '||
                     '       max(coalesce(fgts.bdcategoriater,0)) BDCATEGORIACOL, sum(colcon.BDBASEINSSNMVNOVO) BDBASEINSSNMVNOVO '||
                     ' from vrhf_base_calc_terc COLCON'||
                     ' left outer join vrh_base_tservterc pf on'||
                     '                 (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodter = pf.bdcodter and colcon.bdcodserv = pf.bdcodserv)'||
    --                 ' left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on'||
    --                 '                (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro)'||
                     ' left outer join tempresas temp on (temp.bdcodemp = colcon.bdcodemp)'||
                     ' left outer join VRHF_BASE_TTERC_FGTSGPS FGTS on (FGTS.BDCODTER = COLCON.BDCODTER and '||
                                                                       'FGTS.BDREFTERC = (select first 1 BDREFTERC from VRHF_BASE_TTERC_FGTSGPS where BDCODTER = FGTS.BDCODTER and BDREFTERC <= cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) order by BDCODTER, BDREFTERC desc)) '||
                     ' left outer join VRH_BASE_TTERC_VINC COLCON_VINC on (COLCON_VINC.BDCODTER = COLCON.BDCODTER and '||
                                                                          'COLCON_VINC.BDREFTERC = (select first 1 BDREFTERC from VRH_BASE_TTERC_VINC where BDCODTER = COLCON_VINC.BDCODTER and BDREFTERC <= cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) order by BDCODTER, BDREFTERC desc)) '||
                     ' left outer join VRH_BASE_TCLASSE GRUPO on GRUPO.BDCODCLA = COLCON_VINC.BDCODCLA '||
                     wwheret||
                     'group by ter.bdgrupocla, colcon.bdcodemp, colcon.bdcodter, cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer), pf.bdCodCentro, pf.bdCODTPCC';
         END
      ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 1)) THEN
         BEGIN
              wsql = 'select grupo.bdgrupocla, COLCON.BDCODEMP, COLCON.bdcodter, cast(null as integer), '||
                     '       max(cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer)) bdanomes,'||
                     '       sum(COLCON.bdbaseinss), max(COLCON.bdfaixainss), sum(COLCON.bdvalorinss),'||
                     '       sum(COLCON.bdbaseir), max(COLCON.bdfaixair), sum(COLCON.bdvalorir),'||
                     '       sum(COLCON.bdbaseratapo), sum(COLCON.bdvalorratapo), sum(COLCON.bdvalordep), sum(colcon.BDVALOUTENTIDADES), cast(null as integer), cast(null as integer),'||
                     '       sum(colcon.bdcreditoserv), sum(colcon.bddebitoserv), max(coalesce(fgts.bdocorrenciater,0)) BDOCORRENCIACOL, '||
                     '       max(coalesce(fgts.bdcategoriater,0)) BDCATEGORIACOL, sum(colcon.BDBASEINSSNMVNOVO) BDBASEINSSNMVNOVO '||
                     ' from vrhf_base_calc_terc COLCON'||
                     ' left outer join vrh_base_tservterc pf on'||
                     '                 (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodter = pf.bdcodter and colcon.bdcodserv = pf.bdcodserv)'||
    --                 ' left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on'||
    --                 '                (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro)'||
                     ' left outer join tempresas temp on (temp.bdcodemp = colcon.bdcodemp)'||
                     ' left outer join VRHF_BASE_TTERC_FGTSGPS FGTS on (FGTS.BDCODTER = COLCON.BDCODTER and '||
                                                                       'FGTS.BDREFTERC = (select first 1 BDREFTERC from VRHF_BASE_TTERC_FGTSGPS where BDCODTER = FGTS.BDCODTER and BDREFTERC <= cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) order by BDCODTER, BDREFTERC desc)) '||
                     ' left outer join VRH_BASE_TTERC_VINC COLCON_VINC on (COLCON_VINC.BDCODTER = COLCON.BDCODTER and '||
                                                                          'COLCON_VINC.BDREFTERC = (select first 1 BDREFTERC from VRH_BASE_TTERC_VINC where BDCODTER = COLCON_VINC.BDCODTER and BDREFTERC <= cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) order by BDCODTER, BDREFTERC desc)) '||
                     ' left outer join VRH_BASE_TCLASSE GRUPO on GRUPO.BDCODCLA = COLCON_VINC.BDCODCLA '||
                     wwheret||
                     ' group by ter.bdgrupocla, colcon.bdcodemp, colcon.bdcodter, cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer)';
         END
      ELSE
         BEGIN
              wsql = 'select grupo.bdgrupocla, COLCON.BDCODEMP, COLCON.bdcodter, colcon.bdcodserv, '||
    --                 '       201005 bdanomes,'||
                     '       cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) bdanomes,'||
                     '       COLCON.bdbaseinss, COLCON.bdfaixainss, COLCON.bdvalorinss,'||
                     '       COLCON.bdbaseir, COLCON.bdfaixair, COLCON.bdvalorir,'||
                     '       COLCON.bdbaseratapo, COLCON.bdvalorratapo, COLCON.bdvalordep, colcon.BDVALOUTENTIDADES, pf.bdCodCentro, pf.bdCODTPCC,'||
                     '       colcon.bdcreditoserv, colcon.bddebitoserv, coalesce(fgts.bdocorrenciater,0) BDOCORRENCIACOL, '||
                     '       coalesce(fgts.bdcategoriater,0) BDCATEGORIACOL, colcon.BDBASEINSSNMVNOVO '||
                     ' from vrhf_base_calc_terc COLCON'||
                     ' left outer join vrh_base_tservterc pf on'||
                     '                 (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodter = pf.bdcodter and colcon.bdcodserv = pf.bdcodserv)'||
                     ' left outer join tempresas temp on (temp.bdcodemp = colcon.bdcodemp)'||
                     ' left outer join VRHF_BASE_TTERC_FGTSGPS FGTS on (FGTS.BDCODTER = COLCON.BDCODTER and '||
                                                                       'FGTS.BDREFTERC = (select first 1 BDREFTERC from VRHF_BASE_TTERC_FGTSGPS where BDCODTER = FGTS.BDCODTER and BDREFTERC <= cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) order by BDCODTER, BDREFTERC desc)) '||
                     ' left outer join VRH_BASE_TTERC_VINC COLCON_VINC on (COLCON_VINC.BDCODTER = COLCON.BDCODTER and '||
                                                                          'COLCON_VINC.BDREFTERC = (select first 1 BDREFTERC from VRH_BASE_TTERC_VINC where BDCODTER = COLCON_VINC.BDCODTER and BDREFTERC <= cast((select x.bdaaaamm from aaaamm(pf.bddataserv) x) as integer) order by BDCODTER, BDREFTERC desc)) '||
                     ' left outer join VRH_BASE_TCLASSE GRUPO on GRUPO.BDCODCLA = COLCON_VINC.BDCODCLA '||
                     wwheret;
         END
    
      FOR EXECUTE STATEMENT wsql INTO
        : bdgrupocla,
        : bdcodemp,
        : bdcodter,
        : bdcodserv,
        : bdanomes,
        : bdbaseinss,
        : bdfaixainss,
        : bdvalorinss,
        : bdbaseir,
        : bdfaixair,
        : bdvalorir,
        : bdvalorratapo,
        : bdbaseratapo,
        : bdvalordep,
        : bdvaloutentidades,
        : bdcodcentro,
        : bdcodtpcc,
        : bdcredito,
        : bddebito,
        : bdocorrenciacol,
        : bdcategoriacol,
        : bdbaseinssnmvnovo
        DO
      BEGIN
        wcatesocial = 0;
        wtercmei = 'FALSE';

        select first 1 FGTS.BDCATEGORIAESOCIAL, case when char_length(RH.BDCPFMEITER) = 14 then 'TRUE'  else 'FALSE' end TERCMEI
        from VRHF_BASE_TTERC_FGTSGPS FGTS
        left outer join TTERCEIRO_RH RH on RH.BDCODTER = FGTS.BDCODTER
        where FGTS.BDCODTER = :BDCODTER and FGTS.BDREFTERC <= :prrefini
        order by BDREFTERC DESC into :wcatesocial, :wtercmei;

        if ((wcatesocial = 741) or (wtercmei = 'TRUE')) then
          BEGIN
            if (BDBASEINSS = 0)  then
              BEGIN
                select sum(FN.BDVALOR) from VRHF_BASE_ITEMS_CALCTERC FN
                join VW_TVERBAS_REF V on (V.BDCODVER = FN.BDCODVER)
                where FN.BDCODEMP = :BDCODEMP and FN.BDCODTER = :BDCODTER and FN.BDCODSERV = :bdcodserv and ((coalesce(V.BDBASEGPSVER, 'FALSE') = 'TRUE'))
                into :BDBASEINSS;

                BDBASEINSS = coalesce(BDBASEINSS, 0);
              END
          END
        SUSPEND;
      END
  END
END^

/* Restore proc. body: VRHF_SP_TCOMPENSACAOGPS */
create or alter procedure VRHF_SP_TCOMPENSACAOGPS (
    PRCODIMP integer,
    PRCODEMP integer,
    PRTIPOGPS integer,
    PRTIPOEMISSAO integer,
    PRCODTPCC integer,
    PRRETORNACOMPENSACAO integer,
    PRANOMES integer,
    PRCHAVEDARF integer)
returns (
    BDTIPOREG integer,
    BDCHAVE integer,
    BDVALOR numeric(15,6),
    BDPERC numeric(15,6),
    BDMESINI integer,
    BDMESFIM integer,
    BDVALORREAJUSTE numeric(15,6),
    BDVALORSEMREAJUSTE numeric(15,6))
as
declare variable WCHAVEDARF integer;
declare variable WAUXTOMADOR varchar(32000);
declare variable WAUXTOMADOR2 varchar(3200);
declare variable WWHEREHISTTROCA varchar(3200);
declare variable WWHEREHIST varchar(3200);
declare variable WSQLAUX varchar(32000);
declare variable WANOMESAUX integer;
declare variable WPERCREAJUSTE numeric(15,6);
declare variable WFOLHANORAL integer;
declare variable WTIPOIMPOSTO integer;
declare variable WMESDEC varchar(2);
declare variable WANODEC varchar(4);
BEGIN
   /* prretornacompensacao
     0 = todos
     1 = Nao retornar a compensacao
   */

    WANOMESAUX = pranomes;

    IF (prretornacompensacao IS NULL) THEN
       prretornacompensacao = 0;

    IF (prtipoemissao = 3) THEN
       BEGIN
         wauxtomador = ' left outer join vrhf_sp_tomador(comp.bdcodtpcc,comp.bdcodcentro) toma on';
         wauxtomador2 = ' left outer join vrhf_sp_tomador(darf.bdcodtpcc,darf.bdcodcentro) toma on';
       END
    ELSE
       BEGIN
         wauxtomador = ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(comp.bdcodtpcc,comp.bdcodcentro,'||pranomes||') toma on';
         wauxtomador2 = ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(darf.bdcodtpcc,darf.bdcodcentro,'||pranomes||') toma on';
       END

    /*Verifica se foi emitida a GPS 13 se não foi buscar da Folha normal*/
    wfolhanoral = 0;
    IF ((SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 5) = '12') AND (prtipogps = 0)) THEN
       BEGIN
         SELECT FIRST 1 bdcodemp FROM tdarfpadrao darf
         WHERE darf.bdcodemp = :prcodemp
         AND darf.bdcodimp = :prcodimp
         AND darf.bdreferencia = :pranomes
         AND darf.bdtipoimposto = 2 INTO wfolhanoral;

         IF (wfolhanoral = 0) THEN
            wfolhanoral = 1;
       END

    wwherehist = '';
    WWHEREHISTTROCA = '';
    IF (SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 5) > '12') THEN
       BEGIN
         wwherehist = ' and 0 = 1';
       END
    ELSE IF (SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 5) = '01') THEN
       BEGIN
         wwherehist = ' and ((darf.bdreferencia = '||SUBSTRING(CAST(pranomes-2 AS VARCHAR(6)) FROM 1 FOR 4)||'12';
         wwherehist = wwherehist||' and darf.bdtipoimposto = 0) ';
         wwherehist = wwherehist||' or darf.bdreferencia = '||SUBSTRING(CAST(pranomes-1 AS VARCHAR(6)) FROM 1 FOR 4)||'14';
         wwherehist = wwherehist||')';
         WWHEREHISTTROCA = ' or (comp.bdchavedarf is null and comp.bdreferencia = '||pranomes||')';
       END
    ELSE
       BEGIN
         WWHEREHISTTROCA = ' or (comp.bdchavedarf is null and comp.bdreferencia = '||pranomes||')';
         IF (SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 5) = '12' AND ((prtipogps = 2) OR (wfolhanoral = 1)) )  THEN
            BEGIN
              wwherehist = wwherehist||' and ( darf.bdreferencia = '||(pranomes-1);
              IF (wfolhanoral = 0) THEN
                 BEGIN
                   wwherehist = wwherehist||' or ( darf.bdreferencia = '||SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 1 FOR 4)||'13)';
                   wanomesaux = CAST(SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 1 FOR 4)||'13' AS INTEGER);
                 END
            END
         ELSE
         IF (SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 5) = '12' AND prtipogps = 0)  THEN
            BEGIN
              wwherehist = wwherehist||' and ((darf.bdreferencia = '||(pranomes)||') and  (darf.bdtipoimposto <> 0)';
            END
         ELSE
            BEGIN
              wwherehist = wwherehist||' and ( darf.bdreferencia = '||(pranomes-1);

              IF (SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 5) = '12') THEN
                 BEGIN
                   wwherehist = wwherehist||' or ( darf.bdreferencia = '||SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 1 FOR 4)||'13)';
                 END
            END

         wwherehist = wwherehist||')';
       END

   /* Verifica a ultima gps emitida na competencia para não carrega valores restantes de varias guias */
  wchavedarf = prchavedarf;

    /* desconta compensacao */
    /* 3 = Compensacao*/
   wsqlaux = 'select 3, comp.bdchave,comp.bdvaldesccgps - (select coalesce(sum(r.bdvalor),0) from vrh_emp_rcomp r where r.bdchave = comp.bdchave and r.bdcodemp = comp.bdcodemp),comp.bdpercgps,comp.bdrefinicgps,bdreffimcgps,0 bdtipoimposto from vrhf_emp_tcompgps comp'||
             wauxtomador||
             --' left outer join VRHF_SP_TIPO_TOMADOR_GPS(comp.bdcodtpcc,comp.bdcodcentro) toma on'||
             ' (toma.bdcodcencus = comp.bdcodtpcc and toma.bdcodcentro = comp.bdcodcentro)'||
             ' where comp.bdcodemp = '||prcodemp||
             ' and ((comp.bdrefcgps = '||WANOMESAUX||')';

    IF ((prtipogps = 2) AND (SUBSTRING(CAST(pranomes AS VARCHAR(6)) FROM 5) <> '12')) THEN
      BEGIN
        wsqlaux = wsqlaux||' or (comp.bdrefcgps = '||CAST(SUBSTRING(CAST(WANOMESAUX AS VARCHAR(6)) FROM 1 FOR 4)||'13' AS INTEGER)||')';
      END

    wsqlaux = wsqlaux||') and '||prtipogps||' <> 3'; -- Compensacao nao devem ser utilizadas para folha complementar e compl 13 sal e 13 sal
    IF (prtipoemissao IN (3,4)) THEN
       BEGIN
         IF (prcodtpcc IS NULL) THEN
            wsqlaux = wsqlaux||' and toma.bdcodtpcc is null';
         ELSE
            wsqlaux = wsqlaux||' and toma.bdcodtpcc = '||prcodtpcc;
       END

    IF (COALESCE(wchavedarf,0) > 0) THEN
       BEGIN
         wsqlaux = wsqlaux||' and not exists(select * from vrhf_emp_thistcomp x where x.bdcodemp = comp.bdcodemp and x.bdchave = comp.bdchave and x.bdchavedarf <= '||wchavedarf||')';
         wsqlaux = wsqlaux||' union all ';
         /* 4 = historico comp*/
         wsqlaux = wsqlaux||' select 4, comp.bdchave,comp.bdvalacompensar - (select coalesce(sum(r.bdvalor),0) from vrh_emp_hrcomp r where r.bdchavedarfhistcomp = comp.bdchavedarfhistcomp and r.bdcodemp = comp.bdcodemp)'||
                            ' ,compx.bdpercgps,darf.BDREFERENCIA,darf.BDREFERENCIA, COALESCE(darf.BDTIPOIMPOSTO,0) from vrhf_emp_thistcomp comp'||
                            ' left outer join tdarfpadrao darf on (darf.bdcodemp = comp.bdcodemp and darf.bdchavedarf = comp.bdchavedarf) '||
                            ' left outer join vrhf_emp_tcompgps compx on (compx.bdcodemp = comp.bdcodempcompgps and compx.bdchave = comp.bdchave)'||
                            ' where comp.bdcodemp = '||prcodemp||
                            ' and ((darf.bdcodimp = '||prcodimp||
                            ' and darf.bdchavedarf = '||wchavedarf;
         wsqlaux = wsqlaux||')'||WWHEREHISTTROCA||')';
         wsqlaux = wsqlaux||' union all ';
         /* 5 = historico nf */
         wsqlaux = wsqlaux||' select 5, comp.bdchave,comp.bdvalacompensar - (select coalesce(sum(r.bdvalor),0) from vrh_emp_hrnf r where r.bdcodemp = comp.bdcodemp and r.bdchavedarfhistnf = comp.bdchavedarfhistnf)'||
                            ' ,100,darf.BDREFERENCIA,darf.BDREFERENCIA, COALESCE(darf.BDTIPOIMPOSTO,0) from vrhf_emp_thistnf comp'||
                            ' left outer join tdarfpadrao darf on (darf.bdcodemp = comp.bdcodemp and darf.bdchavedarf = comp.bdchavedarf)'||
                            ' where comp.bdcodemp = '||prcodemp||
                            ' and ((darf.bdcodimp = '||prcodimp||
                            ' and darf.bdchavedarf = '||wchavedarf;
         wsqlaux = wsqlaux||')'||WWHEREHISTTROCA||')';
         wsqlaux = wsqlaux||' union all ';
         /* 6 = historico gps */
         wsqlaux = wsqlaux||' select 6, 0, comp.bdvalacompensar - (select coalesce(sum(r.bdvalor),0) from vrh_emp_hrded r where r.bdchavedarfhistgps = comp.bdchavedarfhistgps and r.bdcodemp = comp.bdcodemp) '||
                            ',100,darf.BDREFERENCIA,darf.BDREFERENCIA, COALESCE(darf.BDTIPOIMPOSTO,0) from vrhf_emp_thistoricogps comp'||
                            ' left outer join tdarfpadrao darf on (darf.bdcodemp = comp.bdcodemp and darf.bdchavedarf = comp.bdchavedarf)'||
                            ' where comp.bdcodemp = '||prcodemp||
                            ' and ((darf.bdcodimp = '||prcodimp||
                            ' and darf.bdchavedarf = '||wchavedarf;
         wsqlaux = wsqlaux||')'||WWHEREHISTTROCA||')';
       END
    wpercreajuste = -1;

    /* 3 = Compensacao*/
    /* 4 = historico comp*/
    /* 5 = historico nf */
    /* 6 = historico gps */
    FOR EXECUTE STATEMENT wsqlaux INTO
      : bdtiporeg,
      : bdchave,
      : bdvalor,
      : bdperc,
      : bdmesini,
      : bdmesfim,
      : wtipoimposto
    DO
      BEGIN
        IF (bdvalor IS NULL) THEN
           bdvalor = 0;

        IF (bdperc IS NULL) THEN
           bdperc = 0;

        IF (bdvalor > 0) THEN
           BEGIN
             bdvalorsemreajuste = bdvalor;
             bdvalorreajuste = 0;
             IF ((pranomes > bdmesini) AND (bdtiporeg <> 3)) THEN
                BEGIN
                  IF (wpercreajuste = -1) THEN
                     BEGIN
                        SELECT COALESCE(ind.bdvalind,0) bdvalind FROM vw_vrhf_base_tempvinc vinc
                             LEFT OUTER JOIN tindval ind ON (vinc.bdcodindgps = ind.bdcodind)
                               WHERE vinc.bdcodemp = :prcodemp AND ind.bdrefind = :bdmesini INTO wpercreajuste;

                        IF ((wpercreajuste IS NULL) OR (wpercreajuste < 0)) THEN
                           wpercreajuste = 0;
                     END

                  bdvalorreajuste = 0;
                  IF (wpercreajuste > 0) THEN
                     BEGIN
                       bdvalorreajuste = (bdvalorsemreajuste * wpercreajuste) / 100;
                       bdvalorreajuste = CAST(bdvalorreajuste AS NUMERIC(15,2));
                     END
                END
             ELSE
             IF ((pranomes = bdmesini) AND (bdtiporeg <> 3) AND (wtipoimposto = 2)) THEN
                BEGIN
                  IF (wpercreajuste = -1) THEN
                     BEGIN
                        IF (CAST(SUBSTRING(:BDMESINI FROM 5 FOR 2) AS INTEGER) = 1) THEN
                          BEGIN
                            wanodec = CAST((CAST(SUBSTRING(:BDMESINI FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4));
                            wmesdec = '12';
                          END
                        ELSE
                          BEGIN
                            wanodec = SUBSTRING(:BDMESINI FROM 1 FOR 4);
                            wmesdec = TRIM(CAST((CAST(SUBSTRING(:BDMESINI FROM 5 FOR 2) AS INTEGER) - 1) AS VARCHAR(2)));
                            WHILE (strlen(:wmesdec) < 2) DO
                              wmesdec = '0'||wmesdec;
                          END


                        SELECT COALESCE(ind.bdvalind,0) bdvalind FROM vw_vrhf_base_tempvinc vinc
                             LEFT OUTER JOIN tindval ind ON (vinc.bdcodindgps = ind.bdcodind)
                               WHERE vinc.bdcodemp = :prcodemp AND ind.bdrefind = :wanodec||:wmesdec INTO wpercreajuste;

                        IF ((wpercreajuste IS NULL) OR (wpercreajuste < 0)) THEN
                           wpercreajuste = 0;
                     END

                  bdvalorreajuste = 0;
                  IF (wpercreajuste > 0) THEN
                     BEGIN
                       bdvalorreajuste = (bdvalorsemreajuste * wpercreajuste) / 100;
                       bdvalorreajuste = CAST(bdvalorreajuste AS NUMERIC(15,2));
                     END
                END

             bdvalor = bdvalorsemreajuste + bdvalorreajuste;

             IF ((prretornacompensacao = 0) OR (bdtiporeg <> 3)) THEN
                SUSPEND;
           END
      END
END^

/* Restore proc. body: SP_VRHF_MEDIAS */
create or alter procedure SP_VRHF_MEDIAS (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREF integer,
    BDTIPO integer,
    BDCC integer,
    BDVREF numeric(18,6),
    BDVREFAUX numeric(18,6),
    BDVVAL numeric(18,6))
as
declare variable WCODEMP_TABELATEMP smallint;
declare variable WSQL varchar(32700);
BEGIN
  WCODEMP_TABELATEMP = 0;
  if (position('tmp_empresas_select',prcodemp)>0) then
     wcodemp_tabelatemp = 1;


  -- HORAS EXTRAS
  -- FOLHA NORMAL
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFFN, '||
           '0 BDTIPOCALC, '||
           '0 BDCCFN, '||
           'PL.BDREFVFN, '||
           'PL.BDREFAUXVFN, '||
           'PL.BDVALVFN '||
         'FROM '||
         'VRHF_EMP_TVERBAFN PL ';

  if (wcodemp_tabelatemp = 1) then
     wSQL = wSQL||' inner join tmp_empresas_select E ON E.BDCODEMP = PL.BDCODEMP ';

  wsql = wsql||' where PL.BDREFFN >= '||prrefini||' and PL.BDREFFN <= '||prreffim;

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') AND (WCODEMP_TABELATEMP = 0)) THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_OUT VER where VER.BDCODVER = PL.BDCODVER) ';


  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;

  -- FOLHA INTERMITENTE
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFFN, '||
           '0 BDTIPOCALC, '||
           '0 BDCCFN, '||
           'PL.BDREFVFN, '||
           'PL.BDREFAUXVFN, '||
           'PL.BDVALVFN '||
         'FROM '||
         'VRHF_EMP_TVERBAINT PL ';

  if (wcodemp_tabelatemp = 1) then
     wSQL = wSQL||' inner join tmp_empresas_select E ON E.BDCODEMP = PL.BDCODEMP ';

  wsql = wsql||' where PL.BDREFFN >= '||prrefini||' and PL.BDREFFN <= '||prreffim;

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') AND (WCODEMP_TABELATEMP = 0)) THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_OUT VER where VER.BDCODVER = PL.BDCODVER) ';


  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;


  -- Em caso de transferência
  wsql = 'SELECT '||
           'TR.BDCODEMPDEST, TR.BDCODCOLDEST, PL.BDCODVER, PL.BDREFFN, 9999 BDTIPOCALC, 0 BDCCFN, PL.BDREFVFN, PL.BDREFAUXVFN, PL.BDVALVFN '||
         'FROM '||
         'VRHF_EMP_TVERBAFN PL '||
         'JOIN VRH_EMP_TTRANSCOL TR on (TR.BDCODEMPORIG = PL.BDCODEMP and TR.BDCODCOLORIG = PL.BDCODCOL) ';

  if (wcodemp_tabelatemp = 1) then
     wSQL = wSQL||' inner join tmp_empresas_select E ON E.BDCODEMP = TR.BDCODEMPDEST ';

  wsql = wsql||' where TR.BDREFTRF = PL.BDREFFN ';
  wsql = wsql||'and SUBSTRING(CAST(TR.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 7) = SUBSTRING(CAST(TR.BDDATATRF -1 AS VARCHAR(10)) FROM 1 FOR 7) ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') AND (WCODEMP_TABELATEMP = 0)) THEN
     wsql = wsql||' and '||REPLACE(UPPER(prcodemp), 'PL.BDCODEMP', 'TR.BDCODEMPDEST');

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'PL.BDCODCOL', 'TR.BDCODCOLDEST');

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_OUT VER where VER.BDCODVER = PL.BDCODVER) ';


  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    BEGIN
      IF (bdref >= prrefini AND bdref <= prreffim) THEN
        SUSPEND;
    END


  -- Em caso de transferência - Folha Intermitente
  wsql = 'SELECT '||
           'TR.BDCODEMPDEST, TR.BDCODCOLDEST, PL.BDCODVER, PL.BDREFFN, 9999 BDTIPOCALC, 0 BDCCFN, PL.BDREFVFN, PL.BDREFAUXVFN, PL.BDVALVFN '||
         'FROM '||
         'VRHF_EMP_TVERBAINT PL '||
         'JOIN VRH_EMP_TTRANSCOL TR on (TR.BDCODEMPORIG = PL.BDCODEMP and TR.BDCODCOLORIG = PL.BDCODCOL) ';

  if (wcodemp_tabelatemp = 1) then
     wSQL = wSQL||' inner join tmp_empresas_select E ON E.BDCODEMP = TR.BDCODEMPDEST ';

  wsql = wsql||' where TR.BDREFTRF = PL.BDREFFN ';
  wsql = wsql||'and SUBSTRING(CAST(TR.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 7) = SUBSTRING(CAST(TR.BDDATATRF -1 AS VARCHAR(10)) FROM 1 FOR 7) ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') AND (WCODEMP_TABELATEMP = 0)) THEN
     wsql = wsql||' and '||REPLACE(UPPER(prcodemp), 'PL.BDCODEMP', 'TR.BDCODEMPDEST');

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'PL.BDCODCOL', 'TR.BDCODCOLDEST');

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_OUT VER where VER.BDCODVER = PL.BDCODVER) ';


  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    BEGIN
      IF (bdref >= prrefini AND bdref <= prreffim) THEN
        SUSPEND;
    END


  -- FOLHA POR TOMADOR
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFTOMADOR, '||
           '100 BDTIPOCALC, '||
           'PL.BDORDEM, '||
           'PL.BDREFVFT, '||
           'PL.BDREFAUXVFT, '||
           'PL.BDVALVFT '||
         'FROM '||
         'VRHF_EMP_TVERBATOMADOR PL ';

  if (wcodemp_tabelatemp = 1) then
     wSQL = wSQL||' inner join tmp_empresas_select E ON E.BDCODEMP = PL.BDCODEMP ';

  wsql = wsql||' where PL.BDREFTOMADOR >= '||prrefini||' and PL.BDREFTOMADOR <= '||prreffim;

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') AND (WCODEMP_TABELATEMP = 0)) THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_OUT VER where VER.BDCODVER = PL.BDCODVER) ';

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;


  -- FOLHA INTERMITENTE POR TOMADOR
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFTOMADOR, '||
           '100 BDTIPOCALC, '||
           'PL.BDORDEM, '||
           'PL.BDREFVFT, '||
           'PL.BDREFAUXVFT, '||
           'PL.BDVALVFT '||
         'FROM '||
         'VRHF_EMP_TVERBATOMINT PL ';

  if (wcodemp_tabelatemp = 1) then
     wSQL = wSQL||' inner join tmp_empresas_select E ON E.BDCODEMP = PL.BDCODEMP ';

  wsql = wsql||' where PL.BDREFTOMADOR >= '||prrefini||' and PL.BDREFTOMADOR <= '||prreffim;

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') AND (WCODEMP_TABELATEMP = 0)) THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_OUT VER where VER.BDCODVER = PL.BDCODVER) ';

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;


  -- Em caso de transferência
  wsql = 'SELECT '||
           'TR.BDCODEMPDEST, TR.BDCODCOLDEST, PL.BDCODVER, PL.BDREFTOMADOR, 9999 BDTIPOCALC, PL.BDORDEM, PL.BDREFVFT, PL.BDREFAUXVFT, PL.BDVALVFT '||
         'FROM '||
         'VRHF_EMP_TVERBATOMADOR PL '||
         'JOIN VRH_EMP_TTRANSCOL TR on (TR.BDCODEMPORIG = PL.BDCODEMP and TR.BDCODCOLORIG = PL.BDCODCOL) ';

  if (wcodemp_tabelatemp = 1) then
     wSQL = wSQL||' inner join tmp_empresas_select E ON E.BDCODEMP = TR.BDCODEMPDEST ';

  wsql = wsql||' where TR.BDREFTRF = PL.BDREFTOMADOR ';
  wsql = wsql||'and SUBSTRING(CAST(TR.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 7) = SUBSTRING(CAST(TR.BDDATATRF -1 AS VARCHAR(10)) FROM 1 FOR 7) ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') AND (WCODEMP_TABELATEMP = 0)) THEN
     wsql = wsql||' and '||REPLACE(UPPER(prcodemp), 'PL.BDCODEMP', 'TR.BDCODEMPDEST');

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'PL.BDCODCOL', 'TR.BDCODCOLDEST');

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_OUT VER where VER.BDCODVER = PL.BDCODVER) ';


  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    BEGIN
      IF (bdref >= prrefini AND bdref <= prreffim) THEN
        SUSPEND;
    END

  -- Em caso de transferência - Folha Intermitente por Tomador
  wsql = 'SELECT '||
           'TR.BDCODEMPDEST, TR.BDCODCOLDEST, PL.BDCODVER, PL.BDREFTOMADOR, 9999 BDTIPOCALC, PL.BDORDEM, PL.BDREFVFT, PL.BDREFAUXVFT, PL.BDVALVFT '||
         'FROM '||
         'VRHF_EMP_TVERBATOMINT PL '||
         'JOIN VRH_EMP_TTRANSCOL TR on (TR.BDCODEMPORIG = PL.BDCODEMP and TR.BDCODCOLORIG = PL.BDCODCOL) ';

  if (wcodemp_tabelatemp = 1) then
     wSQL = wSQL||' inner join tmp_empresas_select E ON E.BDCODEMP = TR.BDCODEMPDEST ';

  wsql = wsql||' where TR.BDREFTRF = PL.BDREFTOMADOR ';
  wsql = wsql||'and SUBSTRING(CAST(TR.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 7) = SUBSTRING(CAST(TR.BDDATATRF -1 AS VARCHAR(10)) FROM 1 FOR 7) ';

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') AND (WCODEMP_TABELATEMP = 0)) THEN
     wsql = wsql||' and '||REPLACE(UPPER(prcodemp), 'PL.BDCODEMP', 'TR.BDCODEMPDEST');

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||REPLACE(UPPER(prcodcol), 'PL.BDCODCOL', 'TR.BDCODCOLDEST');

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_OUT VER where VER.BDCODVER = PL.BDCODVER) ';


  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    BEGIN
      IF (bdref >= prrefini AND bdref <= prreffim) THEN
        SUSPEND;
    END


  -- FOLHA COMPLEMENTAR
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFFN, '||
           '1 BDTIPOCALC, '||
           '0 BDCCFC, '||
           'PL.BDREFVFC, '||
           'PL.BDREFAUXVFC, '||
           'PL.BDVALVFC '||
         'FROM '||
         'VRHF_EMP_TVERBAFC PL ';

  if (wcodemp_tabelatemp = 1) then
     wSQL = wSQL||' inner join tmp_empresas_select E ON E.BDCODEMP = PL.BDCODEMP ';

  wsql = wsql||' where PL.BDREFFN >= '||prrefini||' and PL.BDREFFN <= '||prreffim;

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') AND (WCODEMP_TABELATEMP = 0)) THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_OUT VER where VER.BDCODVER = PL.BDCODVER) ';

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;

  -- FOLHA COMPLEMENTAR POR TOMADOR
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFTOMADOR, '||
           '101 BDTIPOCALC, '||
           'PL.BDORDEM, '||
           'PL.BDREFVFC, '||
           'PL.BDREFAUXVFC, '||
           'PL.BDVALVFC '||
         'FROM '||
         'VRHF_EMP_TVERBAFCTOMADOR PL ';

  if (wcodemp_tabelatemp = 1) then
     wSQL = wSQL||' inner join tmp_empresas_select E ON E.BDCODEMP = PL.BDCODEMP ';

  wsql = wsql||' where PL.BDREFTOMADOR >= '||prrefini||' and PL.BDREFTOMADOR <= '||prreffim;

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') AND (WCODEMP_TABELATEMP = 0)) THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_OUT VER where VER.BDCODVER = PL.BDCODVER) ';

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;

  -- FOLHA AVULSA
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'CAST((SUBSTRING(CAST(PL.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(PL.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER), '||
           '200 BDTIPOCALC, '||
           '0 BDCCFHE, '||
           'PL.BDREFVFA, '||
           'PL.BDREFAUXVFA, '||
           'PL.BDVALVFA '||
         'FROM '||
           'VRHF_EMP_TVERBAFA PL ';

  if (wcodemp_tabelatemp = 1) then
     wSQL = wSQL||' inner join tmp_empresas_select E ON E.BDCODEMP = PL.BDCODEMP ';

  wsql = wsql||' where CAST((SUBSTRING(CAST(PL.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(PL.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= '||prrefini||' and CAST((SUBSTRING(CAST(PL.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(PL.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= '||prreffim;

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') AND (WCODEMP_TABELATEMP = 0)) THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  wsql = wsql||
         ' and exists '||
         '(select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HE VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_RV VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_HN VER where VER.BDCODVER = PL.BDCODVER '||
              'union all '||
              'select VER.BDCODVER '||
              'from VW_VRH_BASE_TVERBAS_FICHA_OUT VER where VER.BDCODVER = PL.BDCODVER) ';

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;

  -- VALORES LANÇADOS NA FICHA FINANCEIRA HE
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFFHE, '||
           '9999 BDTIPOCALC, '||
           '0 BDCCFHE, '||
           'PL.BDVREFFHE, '||
           '0.000000 BDREFAUXFHE, '||
           'PL.BDVVALFHE '||
         'FROM '||
         'VRHF_EMP_TFICHAHE PL ';

  if (wcodemp_tabelatemp = 1) then
     wSQL = wSQL||' inner join tmp_empresas_select E ON E.BDCODEMP = PL.BDCODEMP ';

    WSQL = WSQL ||     ' WHERE '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHANORMAL Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFFN = PL.BDREFFHE) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMADOR Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFTOMADOR = PL.BDREFFHE) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMP Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFFN = PL.BDREFFHE) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMP Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFTOMADOR = PL.BDREFFHE) '||
           'AND '||
           'PL.BDREFFHE >= '||prrefini||' AND PL.BDREFFHE <= '||prreffim;

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') AND (WCODEMP_TABELATEMP = 0)) THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;

  -- VALORES LANÇADOS NA FICHA FINANCEIRA RV
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFFRV, '||
           '9999 BDTIPOCALC, '||
           '0 BDCCFRV, '||
           'PL.BDVREFFRV, '||
           '0.000000 BDREFAUXFRV, '||
           'PL.BDVVALFRV '||
         'FROM '||
         'VRHF_EMP_TFICHARV PL ';

   if (wcodemp_tabelatemp = 1) then
     wSQL = wSQL||' inner join tmp_empresas_select E ON E.BDCODEMP = PL.BDCODEMP ';

     WSQL = WSQL ||    ' WHERE '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHANORMAL Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFFN = PL.BDREFFRV) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMADOR Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFTOMADOR = PL.BDREFFRV) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMP Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFFN = PL.BDREFFRV) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMP Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFTOMADOR = PL.BDREFFRV) '||
           'AND '||
           'PL.BDREFFRV >= '||prrefini||' AND PL.BDREFFRV <= '||prreffim;

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') AND (WCODEMP_TABELATEMP = 0)) THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;


  -- VALORES LANÇADOS NA FICHA FINANCEIRA HN
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFFHN, '||
           '9999 BDTIPOCALC, '||
           '0 BDCCFHN, '||
           'PL.BDVREFFHN, '||
           '0.000000 BDREFAUXFHN, '||
           'PL.BDVVALFHN '||
         'FROM '||
         'VRHF_EMP_TFICHAHN PL ';
  if (wcodemp_tabelatemp = 1) then
     wSQL = wSQL||' inner join tmp_empresas_select E ON E.BDCODEMP = PL.BDCODEMP ';

   WSQL = WSQL ||      ' WHERE '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHANORMAL Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFFN = PL.BDREFFHN) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMADOR Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFTOMADOR = PL.BDREFFHN) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMP Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFFN = PL.BDREFFHN) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMP Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFTOMADOR = PL.BDREFFHN) '||
           'AND '||
           'PL.BDREFFHN >= '||prrefini||' AND PL.BDREFFHN <= '||prreffim;

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') AND (WCODEMP_TABELATEMP = 0)) THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;


  -- VALORES LANÇADOS NA FICHA FINANCEIRA OUTRAS
  wsql = 'SELECT '||
           'PL.BDCODEMP, '||
           'PL.BDCODCOL, '||
           'PL.BDCODVER, '||
           'PL.BDREFFOT, '||
           '9999 BDTIPOCALC, '||
           '0 BDCCFOT, '||
           'PL.BDVREFFOT, '||
           '0.000000 BDREFAUXFOT, '||
           'PL.BDVVALFOT '||
         'FROM '||
         'VRHF_EMP_TFICHAOUTRAS PL ';
  if (wcodemp_tabelatemp = 1) then
     wSQL = wSQL||' inner join tmp_empresas_select E ON E.BDCODEMP = PL.BDCODEMP ';

  WSQL = WSQL ||    ' WHERE '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHANORMAL Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFFN = PL.BDREFFOT) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHATOMADOR Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFTOMADOR = PL.BDREFFOT) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLHACOMP Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFFN = PL.BDREFFOT) '||
           'AND '||
           'NOT EXISTS (SELECT Y.BDCODEMP FROM VRHF_EMP_TFOLTOMCOMP Y WHERE Y.BDCODEMP = PL.BDCODEMP AND Y.BDCODCOL = PL.BDCODCOL AND Y.BDREFTOMADOR = PL.BDREFFOT) '||
           'AND '||
           'PL.BDREFFOT >= '||prrefini||' AND PL.BDREFFOT <= '||prreffim;

  IF ((prcodemp IS NOT NULL AND prcodemp <> '') AND (WCODEMP_TABELATEMP = 0)) THEN
    wsql = wsql||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
    wsql = wsql||' and '||prcodcol;

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodcol, :bdcodver, :bdref, :bdtipo, :bdcc, :bdvref, :bdvrefaux, :bdvval DO
    SUSPEND;

END^

/* Restore proc. body: SP_VRHF_HISTORICO_FAP */
CREATE OR ALTER PROCEDURE SP_VRHF_HISTORICO_FAP (
    PREMP VARCHAR(32700))
RETURNS (
    BDCODEMP INTEGER,
    BDREFEMP INTEGER,
    BDFAPANTERIOR NUMERIC(18,6),
    BDFAPATUAL NUMERIC(18,6))
AS
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WREFEMP INTEGER;
DECLARE VARIABLE WFAP NUMERIC(18,6);
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WFAPATU NUMERIC(18,6);
BEGIN
  wwhere = '';
  IF (premp IS NOT NULL AND premp <> '') THEN
    wwhere = wwhere||' where '||premp;

  wwhere = wwhere||' order by BDCODEMP,BDREFEMP ';

  wempatu = 0;
  wfapatu = -99;

  FOR EXECUTE STATEMENT 'select BDCODEMP, BDREFEMP, BDFAP from vrhf_base_tempgps '||wwhere INTO :wcodemp, :wrefemp, :wfap DO
    BEGIN
      IF ((wempatu <> wcodemp) OR (wfapatu <> wfap)) THEN
        BEGIN
          IF (wempatu = 0) THEN
            BEGIN
              BDCODEMP = wcodemp;
              BDREFEMP = wrefemp;
              BDFAPANTERIOR = 0;
              BDFAPATUAL = wfap;
              SUSPEND;
              wempatu = wcodemp;
              wfapatu = wfap;
            END
          ELSE
            BEGIN
              IF (wempatu <> wcodemp) THEN
                wfapatu = 0;

              BDCODEMP = wcodemp;
              BDREFEMP = wrefemp;
              BDFAPANTERIOR = wfapatu;
              BDFAPATUAL = wfap;
              SUSPEND;
              wempatu = wcodemp;
              wfapatu = wfap;
            END
        END
    END

  IF ((wempatu <> 0 AND wempatu <> wcodemp) OR (wfapatu <> -99 AND wfapatu <> wfap)) THEN
    BEGIN
      BDCODEMP = wcodemp;
      BDREFEMP = wrefemp;
      BDFAPANTERIOR = wfapatu;
      BDFAPATUAL = wfap;
    END
END
^

/* Restore proc. body: VRHF_SP_TFOLHA_NORMAL */
create or alter procedure VRHF_SP_TFOLHA_NORMAL (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(2788) = null)
returns (
    BDGRUPOCLA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDREFFN integer,
    BDDATABAIXAFN date,
    BDBFGTSFN numeric(15,6),
    BDFGTSFN numeric(15,6),
    BDFGTSCSFN numeric(15,6),
    BDBFGTS13FN numeric(15,6),
    BDFGTS13FN numeric(15,6),
    BDFGTS13CSFN numeric(15,6),
    BDMAIORREMFN numeric(15,6),
    BDBINSSFN numeric(15,6),
    BDALIQINSSFN numeric(15,6),
    BDINSSFN numeric(15,6),
    BDBIRRFFN numeric(15,6),
    BDALIQIRRFFN numeric(15,6),
    BDIRRFFN numeric(15,6),
    BDBINSS13FN numeric(15,6),
    BDALIQINSS13FN numeric(15,6),
    BDINSS13FN numeric(15,6),
    BDBIRRF13FN numeric(15,6),
    BDALIQIRRF13FN numeric(15,6),
    BDIRRF13FN numeric(15,6),
    BDBSALFAMFN numeric(15,6),
    BDSALFAMFN numeric(15,6),
    BDBRAISFN numeric(15,6),
    BDSALBASEFN numeric(15,6),
    BDDEPFN numeric(15,6),
    BDBASEPISFN numeric(15,6),
    BDBASEPISFEFN numeric(15,6),
    BDBASEPIS13FN numeric(15,6),
    BDBSALMATEMPFN numeric(15,6),
    BDSALMATEMPFN numeric(15,6),
    BDBRATAPOFN numeric(15,6),
    BDBRATAPOFEFN numeric(15,6),
    BDBRATAPO13FN numeric(15,6),
    BDBINSSFEFOLFN numeric(15,6),
    BDINSSFEFOLFN numeric(15,6),
    BDALIQINSSFEFOLFN numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDCREDITOFN numeric(15,6),
    BDDEBITOFN numeric(15,6),
    BDBFGTSFEFN numeric(15,6),
    BDFGTSFEFN numeric(15,6),
    BDBMATEMPFNFN numeric(15,6),
    BDBMATEMP13FN numeric(15,6),
    BDVMATEMPFNFN numeric(15,6),
    BDVMATEMP13FN numeric(15,6),
    BDLIQUIDOFN numeric(18,6),
    BDDATAPGTO date,
    BDBINSSAPFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDCODCONTTI integer,
    BDBASEFGTSMESESOCIAL numeric(18,6),
    BDBASEFGTS13ESOCIAL numeric(18,6),
    BDVALORFGTSMESESOCIAL numeric(18,6),
    BDVALORFGTS13ESOCIAL numeric(18,6),
    BDVALORFGTSINDESOCIAL numeric(18,6),
    BDBASEFGTSINDESOCIAL numeric(18,6))
as
declare variable WSQL varchar(32700);
declare variable WWHEREN varchar(32700);
declare variable WWHERET varchar(32700);
declare variable WBFGTSA13 numeric(18,6);
declare variable WFGTSA13 numeric(18,6);
BEGIN
  /* pragrupatomador
     0 = Nao agrupa
     1 = Agrupa por referencia
     2 = Agrupo por referencia e centro/Tomador
     3 = Agrupa por referencia e Tomador (se nao for tomador verifica pela classificacao e nao encontrando considera empresa)
     4 = Agrupa por referencia e Tipo Tomador (so vai criar mais registros pra empresa se for tomador 155)
  */

  /* Procedure Text */
  wsql = 'select f.bdgrupocla, colcon.BDCODEMP, colcon.BDCODCOL, colcon.BDREFFN, colcon.BDDATABAIXAFN, colcon.BDBFGTSFN,'||
         'colcon.BDFGTSFN, colcon.BDFGTSCSFN, colcon.BDBFGTS13FN, colcon.BDFGTS13FN, colcon.BDFGTS13CSFN, colcon.BDMAIORREMFN,'||
         'colcon.BDBINSSFN, '||
         'colcon.BDALIQINSSFN, colcon.BDINSSFN, colcon.BDBIRRFFN, colcon.BDALIQIRRFFN, colcon.BDIRRFFN,'||
--         'case when ((coalesce(colcon.bdbaseinss13mvnovo, 0) <> 0) and (coalesce(colcon.BDBINSSMV13FN, 0) <> 0)) then colcon.BDBASEINSS13MVNOVO else colcon.BDBINSS13FN end, '||  /* 139499 Jarde 26/08/2020 */
         'COLCON.BDBINSS13FT, '||                                                                                                                             /* 139499 Jarde 26/08/2020 */
         'colcon.BDALIQINSS13FN, colcon.BDINSS13FN, colcon.BDBIRRF13FN, colcon.BDALIQIRRF13FN,'||
         'colcon.BDIRRF13FN, colcon.BDBSALFAMFN, colcon.BDSALFAMFN, colcon.BDBRAISFN, colcon.BDSALBASEFN, colcon.BDDEPFN,'||
         'colcon.BDBASEPISFN, colcon.BDBASEPISFEFN, colcon.BDBASEPIS13FN, colcon.BDBSALMATEMPFN, colcon.BDSALMATEMPFN, colcon.BDBRATAPOFN, colcon.BDBRATAPOFEFN, colcon.BDBRATAPO13FN,'||
         'colcon.BDBINSSFEFOLFN,'||
         'colcon.BDINSSFEFOLFN, colcon.BDALIQINSSFEFOLFN, colcon.bdcreditofn, COLCON.bddebitofn,'||
         'colcon.bdBFGTSFEFN, COLCON.BDFGTSFEFN'||
         ',COLCON.BDBSALMATEMPFNFN,COLCON.BDBSALMATEMP13FN,COLCON.BDVSALMATEMPFNFN,COLCON.BDVSALMATEMP13FN, COLCON.BDLIQUIDO, COLCON.BDDATAPGTOFN, '||
         'COLCON.BDBINSSAPFN, COLCON.BDINSSAPFN, COLCON.BDBINSS13APFN, COLCON.BDINSS13APFN, COLCON.BDCODCONTTI, '||
         'COLCON.BDBASEFGTSMESESOCIAL, COLCON.BDVALORFGTSMESESOCIAL, COLCON.BDBASEFGTS13ESOCIAL, COLCON.BDVALORFGTS13ESOCIAL, COLCON.BDBASEFGTSINDESOCIAL, COLCON.BDVALORFGTSINDESOCIAL '||

         'from (select colcon.BDCODEMP, colcon.BDCODCOL, colcon.BDREFFN, colcon.BDDATABAIXAFN, colcon.BDBFGTSFN,'||
         'colcon.BDFGTSFN, colcon.BDFGTSCSFN, colcon.BDBFGTS13FN, colcon.BDFGTS13FN, colcon.BDFGTS13CSFN, colcon.BDMAIORREMFN,'||
--         'case when coalesce(colcon.bdbaseinssnmvnovo, 0) <> 0 then colcon.BDBASEINSSNMVNOVO else colcon.BDBINSSFN end BDBINSSFN, '||
         'colcon.BDBINSSFN,'||
         'colcon.BDALIQINSSFN, colcon.BDINSSFN, colcon.BDBIRRFFN, colcon.BDALIQIRRFFN, colcon.BDIRRFFN,'||
--         'case when ((coalesce(colcon.bdbaseinss13mvnovo, 0) <> 0) and (coalesce(colcon.BDBINSSMV13FN, 0) <> 0)) then colcon.BDBASEINSS13MVNOVO else colcon.BDBINSS13FN end, '||  /* 139499 Jarde 26/08/2020 */
--         'COLCON.BDBASEINSS13MVNOVO AS BDBINSS13FT, '||                                                                                                                             /* 139499 Jarde 26/08/2020 */     /* 163256 Leonardo 06/06/2022 */
         'colcon.BDBINSS13FN AS BDBINSS13FT, '||                                                                                                                                    /* 163256 Leonardo 06/06/2022 */    
         'colcon.BDALIQINSS13FN, colcon.BDINSS13FN, colcon.BDBIRRF13FN, colcon.BDALIQIRRF13FN,'||
         'colcon.BDIRRF13FN, colcon.BDBSALFAMFN, colcon.BDSALFAMFN, colcon.BDBRAISFN, colcon.BDSALBASEFN, colcon.BDDEPFN,'||
         'colcon.BDBASEPISFN, colcon.BDBASEPISFEFN, colcon.BDBASEPIS13FN, colcon.BDBSALMATEMPFN, colcon.BDSALMATEMPFN, colcon.BDBRATAPOFN, colcon.BDBRATAPOFEFN, colcon.BDBRATAPO13FN,'||
         'colcon.BDBINSSFEFOLFN,'||
         'colcon.BDINSSFEFOLFN, colcon.BDALIQINSSFEFOLFN, colcon.bdcreditofn, COLCON.bddebitofn,'||
         'colcon.bdBFGTSFEFN, COLCON.BDFGTSFEFN'||
         ',COLCON.BDBSALMATEMPFNFN,COLCON.BDBSALMATEMP13FN,COLCON.BDVSALMATEMPFNFN,COLCON.BDVSALMATEMP13FN, COLCON.BDLIQUIDO, COLCON.BDDATAPGTOFN, '||
         'COLCON.BDBINSSAPFN, COLCON.BDINSSAPFN, COLCON.BDBINSS13APFN, COLCON.BDINSS13APFN, cast(null as INTEGER) BDCODCONTTI, '||
         'COLCON.BDBASEFGTSMESESOCIAL, COLCON.BDVALORFGTSMESESOCIAL, COLCON.BDBASEFGTS13ESOCIAL, COLCON.BDVALORFGTS13ESOCIAL, COLCON.BDBASEFGTSINDESOCIAL, COLCON.BDVALORFGTSINDESOCIAL '||
         'from vrhf_emp_tfolhanormal COLCON '||
         'join tempresas emp on (emp.bdcodemp = COLCON.BDCODEMP) ';

  if (position(upper('tmp_empresas_select'), upper(prcodemp)) > 0) then
    wsql = wsql ||' '||prcodemp;

  if (coalesce(prpuxafiliais, 0) = 1 and coalesce(prcodemp, '') <> '' and (position(upper('tmp_empresas_select'), upper(prcodemp)) <= 0)) then
     begin
       prcodemp = UPPER(prcodemp);

       if (coalesce(prfiliais, '') <> '') then
          begin
            wwheren = replace(prcodemp,'COLCON.BDCODEMP','EMP.BDCODMATRIZ');
            prcodemp = '('||prcodemp||' or (('||wwheren||') and (emp.bdcodemp in ('||prfiliais||'))))';
          end
       else
          prcodemp = replace(prcodemp,'COLCON.BDCODEMP','coalesce(emp.bdcodmatriz,emp.bdcodemp)');
     end

  wwheren = ' where COALESCE(COLCON.BDTAGFN,0) = 0 ';
  wwheret = ' where COALESCE(COLCON.BDTAGFT,0) = 0 ';

  if ((coalesce(prcodemp, '') <> '') and (position(upper('tmp_empresas_select'), upper(prcodemp)) <= 0)) then
     begin
       wwheren = wwheren||' and '||prcodemp;
       wwheret = wwheret||' and '||prcodemp;
     end

  if (coalesce(prcodcol, '') <> '') then
     begin
       wwheren = wwheren||' and '||prcodcol;
       wwheret = wwheret||' and '||prcodcol;
     end

  if (coalesce(prrefini, 0) <> 0 and coalesce(prreffim, 0) <> 0) then
     begin
       wwheren = wwheren||'and COLCON.BDREFFN >= '||prrefini||' and '||'COLCON.BDREFFN <= '||prreffim;
       wwheret = wwhereT||'and COLCON.BDREFTOMADOR >= '||prrefini||' and '||'COLCON.BDREFTOMADOR <= '||prreffim;
     end
  else
     begin
       if (coalesce(prrefini, 0) <> 0) then
          begin
            wwheren = wwheren||' and COLCON.BDREFFN = '||prrefini;
            wwheret = wwhereT||' and COLCON.BDREFTOMADOR = '||prrefini;
          end
       else
          begin
            if (coalesce(prreffim, 0) <> 0) then
               begin
                 wwheren = wwheren||' and COLCON.BDREFFN = '||prreffim;
                 wwheret = wwhereT||' and COLCON.BDREFTOMADOR = '||prreffim;
               end
          end
     end

  if (prrefini is null) then
     prrefini = 299912;

  wsql = wsql||wwheren;


  wsql = wsql||' union all '||
         'select colcon.BDCODEMP, colcon.BDCODCOL, colcon.BDREFFN, colcon.BDDATABAIXAFN, colcon.BDBFGTSFN,'||
         'colcon.BDFGTSFN, colcon.BDFGTSCSFN, colcon.BDBFGTS13FN, colcon.BDFGTS13FN, colcon.BDFGTS13CSFN, colcon.BDMAIORREMFN,'||
         'colcon.BDBINSSFN, colcon.BDALIQINSSFN, colcon.BDINSSFN, colcon.BDBIRRFFN, colcon.BDALIQIRRFFN, colcon.BDIRRFFN,'||
         'colcon.BDBINSS13FN, colcon.BDALIQINSS13FN, colcon.BDINSS13FN, colcon.BDBIRRF13FN, colcon.BDALIQIRRF13FN,'||
         'colcon.BDIRRF13FN, colcon.BDBSALFAMFN, colcon.BDSALFAMFN, colcon.BDBRAISFN, colcon.BDSALBASEFN, colcon.BDDEPFN,'||
         'colcon.BDBASEPISFN, colcon.BDBASEPISFEFN, colcon.BDBASEPIS13FN, colcon.BDBSALMATEMPFN, colcon.BDSALMATEMPFN, colcon.BDBRATAPOFN, colcon.BDBRATAPOFEFN, colcon.BDBRATAPO13FN,'||
         'colcon.BDBINSSFEFOLFN,'||
         'colcon.BDINSSFEFOLFN, colcon.BDALIQINSSFEFOLFN, colcon.bdcreditofn, COLCON.bddebitofn,'||
         'colcon.bdBFGTSFEFN, COLCON.BDFGTSFEFN'||
         ',COLCON.BDBSALMATEMPFNFN,COLCON.BDBSALMATEMP13FN,COLCON.BDVSALMATEMPFNFN,COLCON.BDVSALMATEMP13FN, COLCON.BDLIQUIDO, COLCON.BDDATAPGTOFN, '||
         'COLCON.BDBINSSAPFN, COLCON.BDINSSAPFN, COLCON.BDBINSS13APFN, COLCON.BDINSS13APFN, COLCON.BDCODCONTTI, '||
         'COLCON.BDBASEFGTSMESESOCIAL, COLCON.BDVALORFGTSMESESOCIAL, COLCON.BDBASEFGTS13ESOCIAL, COLCON.BDVALORFGTS13ESOCIAL, COLCON.BDBASEFGTSINDESOCIAL, COLCON.BDVALORFGTSINDESOCIAL '||
         'from vrhf_emp_tfolhaint COLCON '||
         'join tempresas emp on (emp.bdcodemp = COLCON.BDCODEMP) ';

  wsql = wsql||wwheren;

  wsql = wsql||') COLCON '||
         'left outer join (select BDCODEMP, BDCODCOL, max(BDREFCOL) BDREFCOL from VRH_EMP_TCOLCON_VINC where BDREFCOL <= '||prrefini||' group by BDCODEMP, BDCODCOL) x2 on (x2.bdcodemp = COLCON.BDCODEMP and x2.bdcodcol = COLCON.BDCODCOL) '||
         'left outer join VRH_EMP_TCOLCON_VINC x on (x.bdcodemp = COLCON.BDCODEMP and x.bdcodcol = COLCON.BDCODCOL and x.bdrefcol = x2.bdrefcol) '||
         'left outer join VRH_BASE_TCLASSE f on (f.bdcodcla = x.bdcodcla) ';

  IF (coalesce(prcodtpcc, '') = '') THEN
     BEGIN
       FOR EXECUTE STATEMENT wsql
       INTO
         :bdGrupocla,
         :bdcodemp,
         :bdcodcol,
         :bdreffn,
         :bddatabaixafn,
         :bdbfgtsfn,
         :bdfgtsfn,
         :bdfgtscsfn,
         :bdbfgts13fn,
         :bdfgts13fn,
         :bdfgts13csfn,
         :bdmaiorremfn,
         :bdbinssfn,
         :bdaliqinssfn,
         :bdinssfn,
         :bdbirrffn,
         :bdaliqirrffn,
         :bdirrffn,
         :bdbinss13fn,
         :bdaliqinss13fn,
         :bdinss13fn,
         :bdbirrf13fn,
         :bdaliqirrf13fn,
         :bdirrf13fn,
         :bdbsalfamfn,
         :bdsalfamfn,
         :bdbraisfn,
         :bdsalbasefn,
         :bddepfn,
         :bdbasepisfn,
         :bdbasepisFEfn,
         :bdbasepis13fn,
         :bdbsalmatempfn,
         :bdsalmatempfn,
         :bdbratapofn,
         :bdbratapoFEfn,
         :bdbratapo13fn,
         :bdbinssfefolfn,
         :bdinssfefolfn,
         :bdaliqinssfefolfn,
         :bdcreditofn,
         :bddebitofn,
         :bdBFGTSFEFN,
         :BDFGTSFEFN,
         :BDBMATEMPFNFN,
         :BDBMATEMP13FN,
         :BDVMATEMPFNFN,
         :BDVMATEMP13FN,
         :BDLIQUIDOFN,
         :BDDATAPGTO,
         :BDBINSSAPFN,
         :BDINSSAPFN,
         :BDBINSS13APFN,
         :BDINSS13APFN,
         :BDCODCONTTI,
         :BDBASEFGTSMESESOCIAL,
         :BDVALORFGTSMESESOCIAL,
         :BDBASEFGTS13ESOCIAL,
         :BDVALORFGTS13ESOCIAL,
         :BDBASEFGTSINDESOCIAL,
         :BDVALORFGTSINDESOCIAL
       DO
         BEGIN
           bdcalctomador = 'False';

           if (bdcodcontti is null) then
              bdcodcontti = 0;

           SUSPEND;
         END
    END

  BDBMATEMPFNFN = 0;
  BDBMATEMP13FN = 0;
  BDVMATEMPFNFN = 0;
  BDVMATEMP13FN = 0;

  --Retorno dos valores caculados de FGTS pelo eSocial
  BDBASEFGTSMESESOCIAL  = 0;
  BDBASEFGTS13ESOCIAL   = 0;
  BDVALORFGTSMESESOCIAL = 0;
  BDVALORFGTS13ESOCIAL  = 0;
  BDVALORFGTSINDESOCIAL = 0;
  BDBASEFGTSINDESOCIAL  = 0;

  IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 4)) THEN
     BEGIN
       wsql = 'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFT), '||
                'sum(COLCON.BDFGTSFT), sum(COLCON.BDFGTSCSFT), sum(COLCON.BDBFGTS13FT), sum(COLCON.BDFGTS13FT), '||
                'sum(COLCON.BDFGTS13CSFT),sum(COLCON.BDMAIORREMFT), sum(COLCON.BDBINSSFT), max(COLCON.BDALIQINSSFT), '||
                'sum(COLCON.BDINSSFT), sum(COLCON.BDBIRRFFT), max(COLCON.BDALIQIRRFFT), sum(COLCON.BDIRRFFT), '||
                'sum(COLCON.BDBINSS13FT), max(COLCON.BDALIQINSS13FT), sum(COLCON.BDINSS13FT), '||
                'sum(COLCON.BDBIRRF13FT), max(COLCON.BDALIQIRRF13FT), sum(COLCON.BDIRRF13FT), sum(COLCON.BDBSALFAMFT), '||
                'sum(COLCON.BDSALFAMFT), sum(COLCON.BDBRAISFT), max(COLCON.BDSALBASEFT), '||
                'sum(COLCON.BDDEPFT), sum(COLCON.BDBASEPISFT), sum(COLCON.BDBASEPISFEFT), sum(COLCON.BDBASEPIS13FT), sum(COLCON.BDBSALMATEMPFT), '||
                'sum(COLCON.BDSALMATEMPFT), sum(COLCON.BDBRATAPOFT), sum(COLCON.BDBRATAPOFEFT), sum(COLCON.BDBRATAPO13FT), '||
                'sum(COLCON.BDBINSSFEFOLFT), sum(COLCON.BDINSSFEFOLFT), max(COLCON.BDALIQINSSFEFOLFT), '||
                'COLCON.bdCodCentrotoma BDCODCENTRO, COLCON.bdCODTPCCTOMA BDCODTPCC, '||
                'sum(colcon.bdCreditoFT), sum(colcon.bdDebitoFT), '||
                'sum(colcon.bdBFGTSFEFT), sum(COLCON.BDFGTSFEFT), '||
                'sum(colcon.BDBSALMATEMPFNFT),sum(colcon.BDBSALMATEMP13FT),sum(colcon.BDVSALMATEMPFNFT),sum(colcon.BDVSALMATEMP13FT), sum(COLCON.BDLIQUIDO), MAX(COLCON.BDDATAPGTOFT), '||
                'sum(COLCON.BDBINSSAPFT), sum(COLCON.BDINSSAPFT), sum(COLCON.BDBINSS13APFT), sum(COLCON.BDINSS13APFT) ';

       wsql = wsql||',sum(COLCON.BDBASEFGTSMESESOCIAL) BDBASEFGTSMESESOCIAL, sum(COLCON.BDBASEFGTS13ESOCIAL) BDBASEFGTS13ESOCIAL, sum(COLCON.BDVALORFGTSMESESOCIAL) BDVALORFGTSMESESOCIAL, sum(COLCON.BDVALORFGTS13ESOCIAL) BDVALORFGTS13ESOCIAL, sum(COLCON.BDVALORFGTSINDESOCIAL) BDVALORFGTSINDESOCIAL, sum(COLCON.BDBASEFGTSINDESOCIAL) BDBASEFGTSINDESOCIAL ';

       wsql = wsql||'from ( '||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, cast(null as INTEGER) BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, '||
--                'case when coalesce(COLCON.BDBASEINSSNMVNOVO, 0) <> 0 then COLCON.BDBASEINSSNMVNOVO else COLCON.BDBINSSFT end BDBINSSFT, '||
                'COLCON.BDBINSSFT BDBINSSFT, '||
                'COLCON.BDALIQINSSFT,COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
--                'case when ((coalesce(colcon.bdbaseinss13mvnovo, 0) <> 0) and (coalesce(colcon.BDBINSSMV13FT, 0) <> 0)) then COLCON.BDBASEINSS13MVNOVO else COLCON.BDBINSS13FT end BDBINSS13FT, '||  /* 139499 Jarde 26/08/2020 */
--                'COLCON.BDBASEINSS13MVNOVO AS BDBINSS13FT, '||                                                                                                                                         /* 139499 Jarde 26/08/2020 */  /* 163256 Leonardo 06/06/2022 */
                'COLCON.BDBINSS13FT AS BDBINSS13FT, '||                                                                                                                                                /* 163256 Leonardo 06/06/2022 */
                'COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(toma.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTROTOMA, toma.bdCODTPCC bdcodtpcctoma, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, '||
                'pf.bdCodCentro bdcodcentro, pf.bdCODTPCC bdcodtpcc, COLCON.BDLIQUIDO, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT ';

       wsql = WSQL ||', COLCON.BDBASEFGTSMESESOCIAL, COLCON.BDBASEFGTS13ESOCIAL, COLCON.BDVALORFGTSMESESOCIAL, COLCON.BDVALORFGTS13ESOCIAL, COLCON.BDVALORFGTSINDESOCIAL, COLCON.BDBASEFGTSINDESOCIAL ';

       wsql = WSQL ||'from vrhf_emp_tfolhatomador COLCON '||
              'join tempresas emp on (colcon.bdcodemp = emp.bdcodemp)'||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro,'||prrefini||') toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              wwheret;

       wsql = wsql||' union all '||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, '||
                'COLCON.BDBINSSFT, '||
                'COLCON.BDALIQINSSFT,COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'COLCON.BDBINSS13FT, '||
                'COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(toma.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTROTOMA, toma.bdCODTPCC bdcodtpcctoma, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, '||
                'pf.bdCodCentro bdcodcentro, pf.bdCODTPCC bdcodtpcc, COLCON.BDLIQUIDO, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT ';

       wsql = WSQL ||', COLCON.BDBASEFGTSMESESOCIAL, COLCON.BDBASEFGTS13ESOCIAL, COLCON.BDVALORFGTSMESESOCIAL, COLCON.BDVALORFGTS13ESOCIAL, COLCON.BDVALORFGTSINDESOCIAL, COLCON.BDBASEFGTSINDESOCIAL ';

       wsql = WSQL ||'from vrhf_emp_tfolhatomint COLCON '||
              'join tempresas emp on (colcon.bdcodemp = emp.bdcodemp)'||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro,'||prrefini||') toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              wwheret;

       wsql = wsql||') COLCON '||
              'left outer join (select BDCODEMP, BDCODCOL, max(BDREFCOL) BDREFCOL from VRH_EMP_TCOLCON_VINC where BDREFCOL <= '||prrefini||' group by BDCODEMP, BDCODCOL) X2 on (X2.BDCODEMP = colcon.bdcodemp and X2.bdcodcol = colcon.bdcodcol) '||
              'left outer join VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = colcon.bdcodemp and X.bdcodcol = colcon.bdcodcol and X.BDREFCOL = X2.BDREFCOL) '||
              'left outer join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by f.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,COLCON.BDCODCONTTI,colcon.BDREFTOMADOR,COLCON.bdCodCentroTOMA, COLCON.bdCODTPCCTOMA';
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 3)) THEN
     BEGIN
       wsql = 'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFT), '||
                'sum(COLCON.BDFGTSFT), sum(COLCON.BDFGTSCSFT), sum(COLCON.BDBFGTS13FT), sum(COLCON.BDFGTS13FT), '||
                'sum(COLCON.BDFGTS13CSFT),sum(COLCON.BDMAIORREMFT), sum(COLCON.BDBINSSFT), max(COLCON.BDALIQINSSFT), '||
                'sum(COLCON.BDINSSFT), sum(COLCON.BDBIRRFFT), max(COLCON.BDALIQIRRFFT), sum(COLCON.BDIRRFFT), '||
                'sum(COLCON.BDBINSS13FT), max(COLCON.BDALIQINSS13FT), sum(COLCON.BDINSS13FT), '||
                'sum(COLCON.BDBIRRF13FT), max(COLCON.BDALIQIRRF13FT), sum(COLCON.BDIRRF13FT), sum(COLCON.BDBSALFAMFT), '||
                'sum(COLCON.BDSALFAMFT), sum(COLCON.BDBRAISFT), max(COLCON.BDSALBASEFT), '||
                'sum(COLCON.BDDEPFT), sum(COLCON.BDBASEPISFT), sum(COLCON.BDBASEPISFEFT), sum(COLCON.BDBASEPIS13FT), sum(COLCON.BDBSALMATEMPFT), '||
                'sum(COLCON.BDSALMATEMPFT), sum(COLCON.BDBRATAPOFT), sum(COLCON.BDBRATAPOFEFT), sum(COLCON.BDBRATAPO13FT), '||
                'sum(COLCON.BDBINSSFEFOLFT), sum(COLCON.BDINSSFEFOLFT), max(COLCON.BDALIQINSSFEFOLFT), '||
                'COLCON.BDCODCENTROTOMA bdCodCentro, COLCON.bdCODTPCCTOMA BDCODTPCC, '||
                'sum(colcon.bdCreditoFT), sum(colcon.bdDebitoFT), '||
                'sum(colcon.bdBFGTSFEFT), sum(COLCON.BDFGTSFEFT), '||
                'sum(colcon.BDBSALMATEMPFNFT),sum(colcon.BDBSALMATEMP13FT),sum(colcon.BDVSALMATEMPFNFT),sum(colcon.BDVSALMATEMP13FT), sum(COLCON.Bdliquido), MAX(COLCON.BDDATAPGTOFT), '||
                'sum(COLCON.BDBINSSAPFT), sum(COLCON.BDINSSAPFT), sum(COLCON.BDBINSS13APFT), sum(COLCON.BDINSS13APFT) ';

       wsql = wsql||',sum(COLCON.BDBASEFGTSMESESOCIAL) BDBASEFGTSMESESOCIAL, sum(COLCON.BDBASEFGTS13ESOCIAL) BDBASEFGTS13ESOCIAL, sum(COLCON.BDVALORFGTSMESESOCIAL) BDVALORFGTSMESESOCIAL, sum(COLCON.BDVALORFGTS13ESOCIAL) BDVALORFGTS13ESOCIAL, sum(COLCON.BDVALORFGTSINDESOCIAL) BDVALORFGTSINDESOCIAL, sum(COLCON.BDBASEFGTSINDESOCIAL) BDBASEFGTSINDESOCIAL ';

       wsql = wsql||'from ( '||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, cast(null as INTEGER) BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, '||
--                'case when coalesce(COLCON.bdbaseinssnmvnovo, 0) <> 0 then COLCON.bdbaseinssnmvnovo else COLCON.BDBINSSFT end BDBINSSFT, '||
                'COLCON.BDBINSSFT BDBINSSFT, '||
                'COLCON.BDALIQINSSFT, COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
--                'case when ((coalesce(colcon.bdbaseinss13mvnovo, 0) <> 0) and (coalesce(colcon.BDBINSSMV13FT, 0) <> 0)) then COLCON.bdbaseinss13mvnovo else COLCON.BDBINSS13FT end BDBINSS13FT, '||  /* 139499 Jarde 26/08/2020 */
--                'COLCON.BDBASEINSS13MVNOVO AS BDBINSS13FT, '||                                                                                                                                         /* 139499 Jarde 26/08/2020 */ /* 163256 Leonardo 06/06/2022 */
                'COLCON.BDBINSS13FT AS BDBINSS13FT, '||                                                                                                                                                /* 163256 Leonardo 06/06/2022 */
                'COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(toma.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTROTOMA, toma.bdCODTPCC bdCODTPCCtoma, '||
                'case when COALESCE(pf.BDCODTPCC, 0) = 0 then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC BDCODTPCC, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT ';

       wsql = WSQL ||', COLCON.BDBASEFGTSMESESOCIAL, COLCON.BDBASEFGTS13ESOCIAL, COLCON.BDVALORFGTSMESESOCIAL, COLCON.BDVALORFGTS13ESOCIAL, COLCON.BDVALORFGTSINDESOCIAL, COLCON.BDBASEFGTSINDESOCIAL ';

       wsql = WSQL ||'from vrhf_emp_tfolhatomador COLCON '||
              'join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              wwheret;

       wsql = wsql||' union all '||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, '||
                'COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(toma.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTROTOMA, toma.bdCODTPCC bdCODTPCCtoma, '||
                'case when COALESCE(pf.BDCODTPCC, 0) = 0 then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC BDCODTPCC, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT ';

       wsql = WSQL ||', COLCON.BDBASEFGTSMESESOCIAL, COLCON.BDBASEFGTS13ESOCIAL, COLCON.BDVALORFGTSMESESOCIAL, COLCON.BDVALORFGTS13ESOCIAL, COLCON.BDVALORFGTSINDESOCIAL, COLCON.BDBASEFGTSINDESOCIAL ';

       wsql = WSQL ||'from vrhf_emp_tfolhatomint COLCON '||
              'join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              wwheret;

       wsql = wsql||') COLCON '||
              'left outer join (select BDCODEMP, BDCODCOL, max(BDREFCOL) BDREFCOL from VRH_EMP_TCOLCON_VINC where BDREFCOL <= '||prrefini||' group by BDCODEMP, BDCODCOL) X2 on (X2.BDCODEMP = colcon.bdcodemp and X2.bdcodcol = colcon.bdcodcol) '||
              'left outer join VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = colcon.bdcodemp and X.bdcodcol = colcon.bdcodcol and X.BDREFCOL = X2.BDREFCOL) '||
              'left outer join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by f.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,COLCON.BDCODCONTTI,colcon.BDREFTOMADOR,COLCON.bdCodCentrotoma,COLCON.bdCODTPCCtoma ';
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 2)) THEN
     BEGIN
       wsql = 'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL,COLCON.BDCODCONTTI,COLCON.BDREFTOMADOR, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFT), '||
                'sum(COLCON.BDFGTSFT), sum(COLCON.BDFGTSCSFT), sum(COLCON.BDBFGTS13FT), sum(COLCON.BDFGTS13FT), '||
                'sum(COLCON.BDFGTS13CSFT),sum(COLCON.BDMAIORREMFT), sum(COLCON.BDBINSSFT), max(COLCON.BDALIQINSSFT), '||
                'sum(COLCON.BDINSSFT), sum(COLCON.BDBIRRFFT), max(COLCON.BDALIQIRRFFT), sum(COLCON.BDIRRFFT), '||
                'sum(COLCON.BDBINSS13FT), max(COLCON.BDALIQINSS13FT), sum(COLCON.BDINSS13FT), '||
                'sum(COLCON.BDBIRRF13FT), max(COLCON.BDALIQIRRF13FT), sum(COLCON.BDIRRF13FT), sum(COLCON.BDBSALFAMFT), '||
                'sum(COLCON.BDSALFAMFT), sum(COLCON.BDBRAISFT), max(COLCON.BDSALBASEFT), '||
                'sum(COLCON.BDDEPFT), sum(COLCON.BDBASEPISFT), sum(COLCON.BDBASEPISFEFT), sum(COLCON.BDBASEPIS13FT), sum(COLCON.BDBSALMATEMPFT), '||
                'sum(COLCON.BDSALMATEMPFT), sum(COLCON.BDBRATAPOFT),sum(COLCON.BDBRATAPOFEFT), sum(COLCON.BDBRATAPO13FT), '||
                'sum(COLCON.BDBINSSFEFOLFT), sum(COLCON.BDINSSFEFOLFT), max(COLCON.BDALIQINSSFEFOLFT), '||
                'COLCON.bdCodCentro, COLCON.bdCODTPCC, '||
                'sum(colcon.bdCreditoFT), sum(colcon.bdDebitoFT), '||
                'sum(colcon.bdBFGTSFEFT), sum(COLCON.BDFGTSFEFT), '||
                'sum(colcon.BDBSALMATEMPFNFT),sum(colcon.BDBSALMATEMP13FT),sum(colcon.BDVSALMATEMPFNFT),sum(colcon.BDVSALMATEMP13FT), sum(COLCON.bdliquido), MAX(COLCON.BDDATAPGTOFT), '||
                'sum(COLCON.BDBINSSAPFT), sum(COLCON.BDINSSAPFT), sum(COLCON.BDBINSS13APFT), sum(COLCON.BDINSS13APFT) ';

       wsql = wsql||',sum(COLCON.BDBASEFGTSMESESOCIAL) BDBASEFGTSMESESOCIAL, sum(COLCON.BDBASEFGTS13ESOCIAL) BDBASEFGTS13ESOCIAL, sum(COLCON.BDVALORFGTSMESESOCIAL) BDVALORFGTSMESESOCIAL, sum(COLCON.BDVALORFGTS13ESOCIAL) BDVALORFGTS13ESOCIAL, sum(COLCON.BDVALORFGTSINDESOCIAL) BDVALORFGTSINDESOCIAL, sum(COLCON.BDBASEFGTSINDESOCIAL) BDBASEFGTSINDESOCIAL ';

       wsql = wsql||'from ( '||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, cast(null as INTEGER) BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, '||
--                'case when coalesce(colcon.bdbaseinssnmvnovo, 0) <> 0 then colcon.bdbaseinssnmvnovo else COLCON.BDBINSSFT end BDBINSSFT, '||
                'COLCON.BDBINSSFT BDBINSSFT, '||
                'COLCON.BDALIQINSSFT, COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
--                'case when ((coalesce(colcon.bdbaseinss13mvnovo, 0) <> 0) and (coalesce(colcon.BDBINSSMV13FT, 0) <> 0)) then colcon.bdbaseinss13mvnovo else COLCON.BDBINSS13FT end BDBINSS13FT, '||  /* 139499 Jarde 26/08/2020 */
--                'COLCON.BDBASEINSS13MVNOVO AS BDBINSS13FT, '||                                                                                                                                         /* 139499 Jarde 26/08/2020 */  /* 163256 Leonardo 06/06/2022 */
                'COLCON.BDBINSS13FT AS BDBINSS13FT, '||                                                                                                                                                /* 163256 Leonardo 06/06/2022 */
                'COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT,COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(pf.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTRO, pf.bdCODTPCC, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT ';

       wsql = WSQL ||', COLCON.BDBASEFGTSMESESOCIAL, COLCON.BDBASEFGTS13ESOCIAL, COLCON.BDVALORFGTSMESESOCIAL, COLCON.BDVALORFGTS13ESOCIAL, COLCON.BDVALORFGTSINDESOCIAL, COLCON.BDBASEFGTSINDESOCIAL ';

       wsql = WSQL ||'from vrhf_emp_tfolhatomador COLCON '||
              'join tempresas emp on (emp.BDCODEMP = COLCON.BDCODEMP) '||
              'join vrhf_emp_tprepfn pf on (pf.BDCODEMP = COLCON.BDCODEMP and pf.BDCODCOL = COLCON.BDCODCOL and pf.BDORDEM = COLCON.BDORDEM) '||
              wwheret;

       wsql = wsql||' union all '||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, '||
                'COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT,COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(pf.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTRO, pf.bdCODTPCC, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT ';

       wsql = WSQL ||', COLCON.BDBASEFGTSMESESOCIAL, COLCON.BDBASEFGTS13ESOCIAL, COLCON.BDVALORFGTSMESESOCIAL, COLCON.BDVALORFGTS13ESOCIAL, COLCON.BDVALORFGTSINDESOCIAL, COLCON.BDBASEFGTSINDESOCIAL ';

       wsql = WSQL ||'from vrhf_emp_tfolhatomint COLCON '||
              'join tempresas emp on (emp.bdcodemp = COLCON.BDCODEMP) '||
              'join vrhf_emp_tprepfn pf on (pf.bdcodemp = COLCON.BDCODEMP and pf.bdcodcol = COLCON.BDCODCOL and pf.bdordem = COLCON.BDORDEM) '||
              wwheret;

       wsql = wsql||') COLCON '||
              'left outer join (select BDCODEMP, BDCODCOL, max(BDREFCOL) BDREFCOL from VRH_EMP_TCOLCON_VINC where BDREFCOL <= '||prrefini||' group by BDCODEMP, BDCODCOL) X2 on (X2.BDCODEMP = colcon.bdcodemp and X2.bdcodcol = colcon.bdcodcol) '||
              'left outer join VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = colcon.bdcodemp and X.bdcodcol = colcon.bdcodcol and X.BDREFCOL = X2.BDREFCOL) '||
              'left outer join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||'group by f.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,COLCON.BDCODCONTTI,colcon.BDREFTOMADOR,COLCON.bdCodCentro, COLCON.bdCODTPCC ';
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 1)) THEN
     BEGIN
       wsql = 'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL,COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFT),'||
                'sum(COLCON.BDFGTSFT), sum(COLCON.BDFGTSCSFT), sum(COLCON.BDBFGTS13FT), sum(COLCON.BDFGTS13FT),'||
                'sum(COLCON.BDFGTS13CSFT),sum(COLCON.BDMAIORREMFT), sum(COLCON.BDBINSSFT), max(COLCON.BDALIQINSSFT),'||
                'sum(COLCON.BDINSSFT), sum(COLCON.BDBIRRFFT), max(COLCON.BDALIQIRRFFT), sum(COLCON.BDIRRFFT),'||
                'sum(COLCON.BDBINSS13FT), max(COLCON.BDALIQINSS13FT), sum(COLCON.BDINSS13FT),'||
                'sum(COLCON.BDBIRRF13FT), max(COLCON.BDALIQIRRF13FT), sum(COLCON.BDIRRF13FT), sum(COLCON.BDBSALFAMFT),'||
                'sum(COLCON.BDSALFAMFT), sum(COLCON.BDBRAISFT), max(COLCON.BDSALBASEFT),'||
                'sum(COLCON.BDDEPFT), sum(COLCON.BDBASEPISFT), sum(COLCON.BDBASEPISFEFT), sum(COLCON.BDBASEPIS13FT), sum(COLCON.BDBSALMATEMPFT),'||
                'sum(COLCON.BDSALMATEMPFT), sum(COLCON.BDBRATAPOFT), sum(COLCON.BDBRATAPOFEFT), sum(COLCON.BDBRATAPO13FT),'||
                'sum(COLCON.BDBINSSFEFOLFT), sum(COLCON.BDINSSFEFOLFT), max(COLCON.BDALIQINSSFEFOLFT),'||
                'cast(null as integer), cast(null as integer),'||
                'sum(colcon.bdCreditoFT), sum(colcon.bdDebitoFT),'||
                'sum(colcon.bdBFGTSFEFT), sum(COLCON.BDFGTSFEFT),'||
                'sum(colcon.BDBSALMATEMPFNFT),sum(colcon.BDBSALMATEMP13FT),sum(colcon.BDVSALMATEMPFNFT),sum(colcon.BDVSALMATEMP13FT),sum(COLCON.bdliquido), MAX(COLCON.BDDATAPGTOFT), '||
                'sum(COLCON.BDBINSSAPFT), sum(COLCON.BDINSSAPFT), sum(COLCON.BDBINSS13APFT), sum(COLCON.BDINSS13APFT) ';

       wsql = wsql||',sum(COLCON.BDBASEFGTSMESESOCIAL) BDBASEFGTSMESESOCIAL, sum(COLCON.BDBASEFGTS13ESOCIAL) BDBASEFGTS13ESOCIAL, sum(COLCON.BDVALORFGTSMESESOCIAL) BDVALORFGTSMESESOCIAL, sum(COLCON.BDVALORFGTS13ESOCIAL) BDVALORFGTS13ESOCIAL, sum(COLCON.BDVALORFGTSINDESOCIAL) BDVALORFGTSINDESOCIAL, sum(COLCON.BDBASEFGTSINDESOCIAL) BDBASEFGTSINDESOCIAL ';

       wsql = wsql||'from ('||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, cast(null as INTEGER) BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, '||
                'COLCON.BDBINSSFT BDBINSSFT, '||
--                'case when coalesce(colcon.bdbaseinssnmvnovo, 0) <> 0 then colcon.bdbaseinssnmvnovo else COLCON.BDBINSSFT end BDBINSSFT, '||
                'COLCON.BDALIQINSSFT, COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
--                'case when ((coalesce(colcon.bdbaseinss13mvnovo, 0) <> 0) and (coalesce(colcon.BDBINSSMV13FT, 0) <> 0)) then colcon.bdbaseinss13mvnovo else COLCON.BDBINSS13FT end BDBINSS13FT, '||  /* 139499 Jarde 26/08/2020 */
--                'COLCON.BDBASEINSS13MVNOVO AS BDBINSS13FT, '||                                                                                                                                         /* 139499 Jarde 26/08/2020 */  /* 163256 Leonardo 06/06/2022 */
                'COLCON.BDBINSS13FT AS BDBINSS13FT, '||                                                                                                                                                /* 163256 Leonardo 06/06/2022 */
                'COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, '||
                'case when COALESCE(pf.BDCODTPCC, 0) = 0 then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT ';

       wsql = WSQL ||', COLCON.BDBASEFGTSMESESOCIAL, COLCON.BDBASEFGTS13ESOCIAL, COLCON.BDVALORFGTSMESESOCIAL, COLCON.BDVALORFGTS13ESOCIAL, COLCON.BDVALORFGTSINDESOCIAL, COLCON.BDBASEFGTSINDESOCIAL ';

       wsql = WSQL ||'from vrhf_emp_tfolhatomador COLCON '||
              'join tempresas emp on (emp.BDCODEMP = COLCON.BDCODEMP) '||
              'join vrhf_emp_tprepfn pf on (pf.bdcodemp = COLCON.BDCODEMP and pf.bdcodcol = COLCON.BDCODCOL and PF.BDORDEM = COLCON.BDORDEM) '||
              'left outer join VW_VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = COLCON.BDCODEMP and X.BDCODCOL = COLCON.BDCODCOL) '||
              'left outer join VRH_BASE_TCLASSE f on (f.bdcodcla = X.BDCODCLA) '||
              wwheret;

       wsql = wsql||' union all '||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, '||
                'COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, '||
                'case when COALESCE(pf.BDCODTPCC, 0) = 0 then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT ';

       wsql = WSQL ||', COLCON.BDBASEFGTSMESESOCIAL, COLCON.BDBASEFGTS13ESOCIAL, COLCON.BDVALORFGTSMESESOCIAL, COLCON.BDVALORFGTS13ESOCIAL, COLCON.BDVALORFGTSINDESOCIAL, COLCON.BDBASEFGTSINDESOCIAL ';

       wsql = WSQL ||'from vrhf_emp_tfolhatomint COLCON '||
              'join tempresas emp on (emp.bdcodemp = COLCON.BDCODEMP) '||
              'join vrhf_emp_tprepfn pf on (pf.bdcodemp = COLCON.BDCODEMP and pf.bdcodcol = COLCON.BDCODCOL and pf.bdordem = COLCON.BDORDEM) '||
              'left outer join VW_VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = COLCON.BDCODEMP and X.BDCODCOL = COLCON.BDCODCOL) '||
              'left outer join VRH_BASE_TCLASSE f on (f.bdcodcla = X.BDCODCLA) '||
              wwheret;

       wsql = wsql||') COLCON '||
              'left outer join (select BDCODEMP, BDCODCOL, max(BDREFCOL) BDREFCOL from VRH_EMP_TCOLCON_VINC where BDREFCOL <= '||prrefini||' group by BDCODEMP, BDCODCOL) X2 on (X2.BDCODEMP = colcon.bdcodemp and X2.bdcodcol = colcon.bdcodcol) '||
              'left outer join VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = colcon.bdcodemp and X.bdcodcol = colcon.bdcodcol and X.BDREFCOL = X2.BDREFCOL) '||
              'left outer join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by f.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,COLCON.BDCODCONTTI,colcon.BDREFTOMADOR';
     END
  ELSE
     BEGIN
       wsql = 'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI,COLCON.BDREFTOMADOR, COLCON.BDORDEM, COLCON.BDDATABAIXAFT, COLCON.BDBFGTSFT, COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, '||
                'COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, COLCON.BDFGTS13CSFT, '||
                'COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, COLCON.BDBINSS13FT, '||
                'COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, COLCON.BDDEPFT, '||
                'COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, COLCON.bdCodCentro, COLCON.bdCODTPCC, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT ';

       wsql = wsql||',COLCON.BDBASEFGTSMESESOCIAL, COLCON.BDBASEFGTS13ESOCIAL, COLCON.BDVALORFGTSMESESOCIAL, COLCON.BDVALORFGTS13ESOCIAL, COLCON.BDVALORFGTSINDESOCIAL, COLCON.BDBASEFGTSINDESOCIAL ';

       wsql = wsql||'from (select '||
                 'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, cast(null as INTEGER) BDCODCONTTI,COLCON.BDORDEM, COLCON.BDDATABAIXAFT, COLCON.BDBFGTSFT, COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, COLCON.BDFGTS13CSFT,'||
                 'COLCON.BDMAIORREMFT, '||
                 'COLCON.BDBINSSFT BDBINSSFT, '||
--                 'case when coalesce(colcon.bdbaseinssnmvnovo, 0) <> 0 then colcon.bdbaseinssnmvnovo else COLCON.BDBINSSFT end BDBINSSFT, '|| Almir Não deve usar o valor cm MV 
                 'COLCON.BDALIQINSSFT, COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
--                 'case when ((coalesce(colcon.bdbaseinss13mvnovo, 0) <> 0) and (coalesce(colcon.BDBINSSMV13FT, 0) <> 0)) then colcon.bdbaseinss13mvnovo else COLCON.BDBINSS13FT end BDBINSS13FT, '||   /* 139499 Jarde 26/08/2020 */
--                 'COLCON.BDBASEINSS13MVNOVO AS BDBINSS13FT, '||                                                                                                                                          /* 139499 Jarde 26/08/2020 */    /* 163256 Leonardo 06/06/2022 */    
                 'COLCON.BDBINSS13FT AS BDBINSS13FT, '||                                                                                                                                          /* 163256 Leonardo 06/06/2022 */
                 'COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT,'||
                 'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, COLCON.BDDEPFT, '||
                 'COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT,'||
                 'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT,'||
                 'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, pf.bdCodCentro, pf.bdCODTPCC,'||
                 'colcon.bdCreditoFT, colcon.bdDebitoFT,'||
                 'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                 'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                 'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT ';

       wsql = WSQL ||', COLCON.BDBASEFGTSMESESOCIAL, COLCON.BDBASEFGTS13ESOCIAL, COLCON.BDVALORFGTSMESESOCIAL, COLCON.BDVALORFGTS13ESOCIAL, COLCON.BDVALORFGTSINDESOCIAL, COLCON.BDBASEFGTSINDESOCIAL ';

       wsql = WSQL ||'from vrhf_emp_tfolhatomador COLCON '||
                 'join tempresas emp on (emp.bdcodemp = COLCON.BDCODEMP) '||
                 'join vrhf_emp_tprepfn pf on (pf.bdcodemp = COLCON.BDCODEMP and pf.bdcodcol = COLCON.BDCODCOL and pf.bdordem = COLCON.BDORDEM) '||
                 wwheret;

          wsql = wsql||'union all select '||
                 'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDCODCONTTI,COLCON.BDORDEM, COLCON.BDDATABAIXAFT, COLCON.BDBFGTSFT, COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, COLCON.BDFGTS13CSFT,'||
                 'COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT,'||
                 'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, COLCON.BDDEPFT, '||
                 'COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT,'||
                 'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT,'||
                 'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, pf.bdCodCentro, pf.bdCODTPCC,'||
                 'colcon.bdCreditoFT, colcon.bdDebitoFT,'||
                 'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                 'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                 'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT ';

      wsql = WSQL ||', COLCON.BDBASEFGTSMESESOCIAL, COLCON.BDBASEFGTS13ESOCIAL, COLCON.BDVALORFGTSMESESOCIAL, COLCON.BDVALORFGTS13ESOCIAL, COLCON.BDVALORFGTSINDESOCIAL, COLCON.BDBASEFGTSINDESOCIAL ';

      wsql = WSQL ||'from vrhf_emp_tfolhatomint COLCON '||
                 'join tempresas emp on (emp.bdcodemp = COLCON.BDCODEMP) '||
                 'join vrhf_emp_tprepfn pf on (pf.bdcodemp = COLCON.BDCODEMP and pf.bdcodcol = COLCON.BDCODCOL and pf.bdordem = COLCON.BDORDEM) '||
                 wwheret;

       wsql = wsql||') COLCON '||
              'left outer join (select BDCODEMP, BDCODCOL, max(BDREFCOL) BDREFCOL from VRH_EMP_TCOLCON_VINC where BDREFCOL <= '||prrefini||' group by BDCODEMP, BDCODCOL) X2 on (X2.BDCODEMP = colcon.bdcodemp and X2.bdcodcol = colcon.bdcodcol) '||
              'left outer join VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = colcon.bdcodemp and X.bdcodcol = colcon.bdcodcol and X.BDREFCOL = X2.BDREFCOL) '||
              'left outer join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;
     END

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdgrupocla,
    :bdcodemp, --BDCODEMP,
    :bdcodcol, -- BDCODCOL,
    :bdcodcontti, 
    :bdreffn, -- BDREFTOMADOR,
    :bdordem, -- BDORDEM,
    :bddatabaixafn, -- BDDATABAIXAFT,
    :bdbfgtsfn, -- BDBFGTSFT,
    :bdfgtsfn, -- BDFGTSFT,
    :bdfgtscsfn, -- BDFGTSCSFT,
    :bdbfgts13fn, --- BDBFGTS13FT,
    :bdfgts13fn, -- BDFGTS13FT,
    :bdfgts13csfn, -- BDFGTS13CSFT,'||
    :bdmaiorremfn, -- 'BDMAIORREMFT,
    :bdbinssfn, -- BDBINSSFT,
    :bdaliqinssfn, -- BDALIQINSSFT,
    :bdinssfn, -- BDINSSFT,
    :bdbirrffn, -- BDBIRRFFT,
    :bdaliqirrffn, -- BDALIQIRRFFT,
    :bdirrffn, -- BDIRRFFT,
    :bdbinss13fn, -- BDBINSS13FT,
    :bdaliqinss13fn, -- BDALIQINSS13FT,
    :bdinss13fn, -- BDINSS13FT,'||
    :bdbirrf13fn, -- 'BDBIRRF13FT,
    :bdaliqirrf13fn, -- BDALIQIRRF13FT,
    :bdirrf13fn, -- BDIRRF13FT,
    :bdbsalfamfn, -- BDBSALFAMFT,
    :bdsalfamfn, --BDSALFAMFT,
    :bdbraisfn, -- BDBRAISFT,
    :bdsalbasefn, -- BDSALBASEFT,
    :bddepfn, -- BDDEPFT,
    :bdbasepisfn, -- BDBASEPISFT,
    :bdbasepisFEfn, -- BDBASEPISFEFT,
    :bdbasepis13fn, -- BDBASEPIS13FT,
    :bdbsalmatempfn, -- BDBSALMATEMPFT,'||
    :bdsalmatempfn, -- 'BDSALMATEMPFT,
    :bdbratapofn, -- BDBRATAPOFT,
    :bdbratapoFEfn, -- BDBRATAPOFEFT,
    :bdbratapo13fn, -- BDBRATAPO13FT,
    :bdbinssfefolfn, -- BDBINSSFEFOLFT,
    :bdinssfefolfn, -- BDALIQINSSFEFOLFT'||
    :bdaliqinssfefolfn, -- BDINSSFEFOLFT,
    :bdCodCentro, -- bdCodCentro
    :bdCODTPCC, -- BDCODTPCC
    :bdcreditofn,
    :bddebitofn,
    :bdBFGTSFEFN,
    :BDFGTSFEFN,
    :BDBMATEMPFNFN,
    :BDBMATEMP13FN,
    :BDVMATEMPFNFN,
    :BDVMATEMP13FN,
    :BDLIQUIDOFN,
    :BDDATAPGTO,
    :BDBINSSAPFN,
    :BDINSSAPFN,
    :BDBINSS13APFN,
    :BDINSS13APFN,
    :BDBASEFGTSMESESOCIAL,
    :BDBASEFGTS13ESOCIAL,
    :BDVALORFGTSMESESOCIAL,
    :BDVALORFGTS13ESOCIAL,
    :BDVALORFGTSINDESOCIAL,
    :BDBASEFGTSINDESOCIAL

  DO
    BEGIN
      bdcalctomador = 'True';
      if (bdcodcontti is null) then
         bdcodcontti = 0;

      SUSPEND;
    END
END^

/* Restore proc. body: VRHF_SP_TFOLHA_INT */
create or alter procedure VRHF_SP_TFOLHA_INT (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(772) = null)
returns (
    BDGRUPOCLA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODCONTTI integer,
    BDORDEM integer,
    BDREFFN integer,
    BDDATABAIXAFN date,
    BDBFGTSFN numeric(15,6),
    BDFGTSFN numeric(15,6),
    BDFGTSCSFN numeric(15,6),
    BDBFGTS13FN numeric(15,6),
    BDFGTS13FN numeric(15,6),
    BDFGTS13CSFN numeric(15,6),
    BDMAIORREMFN numeric(15,6),
    BDBINSSFN numeric(15,6),
    BDALIQINSSFN numeric(15,6),
    BDINSSFN numeric(15,6),
    BDBIRRFFN numeric(15,6),
    BDALIQIRRFFN numeric(15,6),
    BDIRRFFN numeric(15,6),
    BDBINSS13FN numeric(15,6),
    BDALIQINSS13FN numeric(15,6),
    BDINSS13FN numeric(15,6),
    BDBIRRF13FN numeric(15,6),
    BDALIQIRRF13FN numeric(15,6),
    BDIRRF13FN numeric(15,6),
    BDBSALFAMFN numeric(15,6),
    BDSALFAMFN numeric(15,6),
    BDBRAISFN numeric(15,6),
    BDSALBASEFN numeric(15,6),
    BDDEPFN numeric(15,6),
    BDBASEPISFN numeric(15,6),
    BDBASEPISFEFN numeric(15,6),
    BDBASEPIS13FN numeric(15,6),
    BDBSALMATEMPFN numeric(15,6),
    BDSALMATEMPFN numeric(15,6),
    BDBRATAPOFN numeric(15,6),
    BDBRATAPOFEFN numeric(15,6),
    BDBRATAPO13FN numeric(15,6),
    BDBINSSFEFOLFN numeric(15,6),
    BDINSSFEFOLFN numeric(15,6),
    BDALIQINSSFEFOLFN numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDCREDITOFN numeric(15,6),
    BDDEBITOFN numeric(15,6),
    BDBFGTSFEFN numeric(15,6),
    BDFGTSFEFN numeric(15,6),
    BDBMATEMPFNFN numeric(15,6),
    BDBMATEMP13FN numeric(15,6),
    BDVMATEMPFNFN numeric(15,6),
    BDVMATEMP13FN numeric(15,6),
    BDLIQUIDOFN numeric(18,6),
    BDDATAPGTO date,
    BDBINSSAPFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSS13APFN numeric(18,6))
as
declare variable WSQL varchar(32700);
declare variable WWHEREN varchar(32700);
declare variable WWHERET varchar(32700);
     BEGIN
  /* pragrupatomador
     0 = Nao agrupa
     1 = Agrupa por referencia
     2 = Agrupo por referencia e centro/Tomador
     3 = Agrupa por referencia e Tomador (se nao for tomador verifica pela classificacao e nao encontrando considera empresa)
     4 = Agrupa por referencia e Tipo Tomador (so vai criar mais registros pra empresa se for tomador 155)
  */

  /* Procedure Text */
  wsql = 'select f.bdgrupocla, colcon.BDCODEMP, colcon.BDCODCOL, cast(null as INTEGER) BDCODCONTTI, colcon.BDREFFN, colcon.BDDATABAIXAFN, colcon.BDBFGTSFN,'||
         'colcon.BDFGTSFN, colcon.BDFGTSCSFN, colcon.BDBFGTS13FN, colcon.BDFGTS13FN, colcon.BDFGTS13CSFN, colcon.BDMAIORREMFN,'||
         'case when coalesce(colcon.bdbaseinssnmvnovo, 0) <> 0 then colcon.BDBASEINSSNMVNOVO else colcon.BDBINSSFN end, '||
         'colcon.BDALIQINSSFN, colcon.BDINSSFN, colcon.BDBIRRFFN, colcon.BDALIQIRRFFN, colcon.BDIRRFFN,'||
         'case when coalesce(colcon.bdbaseinss13mvnovo, 0) <> 0 then colcon.BDBASEINSS13MVNOVO else colcon.BDBINSS13FN end, '||
         'colcon.BDALIQINSS13FN, colcon.BDINSS13FN, colcon.BDBIRRF13FN, colcon.BDALIQIRRF13FN,'||
         'colcon.BDIRRF13FN, colcon.BDBSALFAMFN, colcon.BDSALFAMFN, colcon.BDBRAISFN, colcon.BDSALBASEFN, colcon.BDDEPFN,'||
         'colcon.BDBASEPISFN, colcon.BDBASEPISFEFN, colcon.BDBASEPIS13FN, colcon.BDBSALMATEMPFN, colcon.BDSALMATEMPFN, colcon.BDBRATAPOFN, colcon.BDBRATAPOFEFN, colcon.BDBRATAPO13FN,'||
         'colcon.BDBINSSFEFOLFN,'||
         'colcon.BDINSSFEFOLFN, colcon.BDALIQINSSFEFOLFN, colcon.bdcreditofn, COLCON.bddebitofn,'||
         'colcon.bdBFGTSFEFN, COLCON.BDFGTSFEFN'||
         ',COLCON.BDBSALMATEMPFNFN,COLCON.BDBSALMATEMP13FN,COLCON.BDVSALMATEMPFNFN,COLCON.BDVSALMATEMP13FN, COLCON.BDLIQUIDO, COLCON.BDDATAPGTOFN, '||
         'COLCON.BDBINSSAPFN, COLCON.BDINSSAPFN, COLCON.BDBINSS13APFN, COLCON.BDINSS13APFN '||
         'from VRHF_EMP_TFOLHANORMAL COLCON '||
         'join tempresas emp on (emp.bdcodemp = COLCON.BDCODEMP) '||
         'left outer join VW_VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = COLCON.BDCODEMP and X.BDCODCOL = COLCON.BDCODCOL) '||
         'left outer join VRH_BASE_TCLASSE f on (f.bdcodcla = X.BDCODCLA) ';


  if (coalesce(prpuxafiliais, 0) = 1 and coalesce(prcodemp, '') <> '') then
     begin
       prcodemp = UPPER(prcodemp);

       if (coalesce(prfiliais, '') <> '') then
          begin
            wwheren = replace(prcodemp,'COLCON.BDCODEMP','EMP.BDCODMATRIZ');
            prcodemp = '('||prcodemp||' or (('||wwheren||') and (emp.bdcodemp in ('||prfiliais||'))))';
          end
       else
          prcodemp = replace(prcodemp,'COLCON.BDCODEMP','coalesce(emp.bdcodmatriz,emp.bdcodemp)');
     end

  wwheren = ' where COALESCE(COLCON.BDTAGFN,0) = 0 ';
  wwheret = ' where COALESCE(COLCON.BDTAGFT,0) = 0 ';

  if (coalesce(prcodemp, '') <> '') then
     begin
       wwheren = wwheren||' and '||prcodemp;
       wwheret = wwheret||' and '||prcodemp;
     end

  if (coalesce(prcodcol, '') <> '') then
     begin
       wwheren = wwheren||' and '||prcodcol;
       wwheret = wwheret||' and '||prcodcol;
     end

  if (coalesce(prrefini, 0) <> 0 and coalesce(prreffim, 0) <> 0) then
     begin
       wwheren = wwheren||'and COLCON.BDREFFN >= '||prrefini||' and '||'COLCON.BDREFFN <= '||prreffim;
       wwheret = wwhereT||'and COLCON.BDREFTOMADOR >= '||prrefini||' and '||'COLCON.BDREFTOMADOR <= '||prreffim;
     end
  else
     begin
       if (coalesce(prrefini, 0) <> 0) then
          begin
            wwheren = wwheren||' and COLCON.BDREFFN = '||prrefini;
            wwheret = wwhereT||' and COLCON.BDREFTOMADOR = '||prrefini;
          end
       else
          begin
            if (coalesce(prreffim, 0) <> 0) then
               begin
                 wwheren = wwheren||' and COLCON.BDREFFN = '||prreffim;
                 wwheret = wwhereT||' and COLCON.BDREFTOMADOR = '||prreffim;
               end
          end
     end

  wsql = wsql||wwheren;


  wsql = wsql||' union all '||
         'select f.bdgrupocla, colcon.BDCODEMP, colcon.BDCODCOL, colcon.BDCODCONTTI, colcon.BDREFFN, colcon.BDDATABAIXAFN, colcon.BDBFGTSFN,'||
         'colcon.BDFGTSFN, colcon.BDFGTSCSFN, colcon.BDBFGTS13FN, colcon.BDFGTS13FN, colcon.BDFGTS13CSFN, colcon.BDMAIORREMFN,'||
         'colcon.BDBINSSFN, colcon.BDALIQINSSFN, colcon.BDINSSFN, colcon.BDBIRRFFN, colcon.BDALIQIRRFFN, colcon.BDIRRFFN,'||
         'colcon.BDBINSS13FN, colcon.BDALIQINSS13FN, colcon.BDINSS13FN, colcon.BDBIRRF13FN, colcon.BDALIQIRRF13FN,'||
         'colcon.BDIRRF13FN, colcon.BDBSALFAMFN, colcon.BDSALFAMFN, colcon.BDBRAISFN, colcon.BDSALBASEFN, colcon.BDDEPFN,'||
         'colcon.BDBASEPISFN, colcon.BDBASEPISFEFN, colcon.BDBASEPIS13FN, colcon.BDBSALMATEMPFN, colcon.BDSALMATEMPFN, colcon.BDBRATAPOFN, colcon.BDBRATAPOFEFN, colcon.BDBRATAPO13FN,'||
         'colcon.BDBINSSFEFOLFN,'||
         'colcon.BDINSSFEFOLFN, colcon.BDALIQINSSFEFOLFN, colcon.bdcreditofn, COLCON.bddebitofn,'||
         'colcon.bdBFGTSFEFN, COLCON.BDFGTSFEFN'||
         ',COLCON.BDBSALMATEMPFNFN,COLCON.BDBSALMATEMP13FN,COLCON.BDVSALMATEMPFNFN,COLCON.BDVSALMATEMP13FN, COLCON.BDLIQUIDO, COLCON.BDDATAPGTOFN, '||
         'COLCON.BDBINSSAPFN, COLCON.BDINSSAPFN, COLCON.BDBINSS13APFN, COLCON.BDINSS13APFN '||
         'from vrhf_emp_tfolhaint COLCON '||
         'join tempresas emp on (emp.bdcodemp = COLCON.BDCODEMP) '||
         'left outer join VW_VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = COLCON.BDCODEMP and X.BDCODCOL = COLCON.BDCODCOL) '||
         'left outer join VRH_BASE_TCLASSE f on (f.bdcodcla = X.BDCODCLA) ';


  wsql = wsql||wwheren;

  IF (coalesce(prcodtpcc, '') = '') THEN
     BEGIN
       FOR EXECUTE STATEMENT wsql
       INTO
         :bdGrupocla,
         :bdcodemp,
         :bdcodcol,
         :bdcodcontti,
         :bdreffn,
         :bddatabaixafn,
         :bdbfgtsfn,
         :bdfgtsfn,
         :bdfgtscsfn,
         :bdbfgts13fn,
         :bdfgts13fn,
         :bdfgts13csfn,
         :bdmaiorremfn,
         :bdbinssfn,
         :bdaliqinssfn,
         :bdinssfn,
         :bdbirrffn,
         :bdaliqirrffn,
         :bdirrffn,
         :bdbinss13fn,
         :bdaliqinss13fn,
         :bdinss13fn,
         :bdbirrf13fn,
         :bdaliqirrf13fn,
         :bdirrf13fn,
         :bdbsalfamfn,
         :bdsalfamfn,
         :bdbraisfn,
         :bdsalbasefn,
         :bddepfn,
         :bdbasepisfn,
         :bdbasepisFEfn,
         :bdbasepis13fn,
         :bdbsalmatempfn,
         :bdsalmatempfn,
         :bdbratapofn,
         :bdbratapoFEfn,
         :bdbratapo13fn,
         :bdbinssfefolfn,
         :bdinssfefolfn,
         :bdaliqinssfefolfn,
         :bdcreditofn,
         :bddebitofn,
         :bdBFGTSFEFN,
         :BDFGTSFEFN,
         :BDBMATEMPFNFN,
         :BDBMATEMP13FN,
         :BDVMATEMPFNFN,
         :BDVMATEMP13FN,
         :BDLIQUIDOFN,
         :BDDATAPGTO,
         :BDBINSSAPFN,
         :BDINSSAPFN,
         :BDBINSS13APFN,
         :BDINSS13APFN
       DO
         BEGIN
           bdcalctomador = 'False';

           if (bdcodcontti is null) then
              bdcodcontti = 0;
           SUSPEND;
         END
    END

  BDBMATEMPFNFN = 0;
  BDBMATEMP13FN = 0;
  BDVMATEMPFNFN = 0;
  BDVMATEMP13FN = 0;
  IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 4)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFT), '||
                'sum(COLCON.BDFGTSFT), sum(COLCON.BDFGTSCSFT), sum(COLCON.BDBFGTS13FT), sum(COLCON.BDFGTS13FT), '||
                'sum(COLCON.BDFGTS13CSFT),sum(COLCON.BDMAIORREMFT), sum(COLCON.BDBINSSFT), max(COLCON.BDALIQINSSFT), '||
                'sum(COLCON.BDINSSFT), sum(COLCON.BDBIRRFFT), max(COLCON.BDALIQIRRFFT), sum(COLCON.BDIRRFFT), '||
                'sum(COLCON.BDBINSS13FT), max(COLCON.BDALIQINSS13FT), sum(COLCON.BDINSS13FT), '||
                'sum(COLCON.BDBIRRF13FT), max(COLCON.BDALIQIRRF13FT), sum(COLCON.BDIRRF13FT), sum(COLCON.BDBSALFAMFT), '||
                'sum(COLCON.BDSALFAMFT), sum(COLCON.BDBRAISFT), max(COLCON.BDSALBASEFT), '||
                'sum(COLCON.BDDEPFT), sum(COLCON.BDBASEPISFT), sum(COLCON.BDBASEPISFEFT), sum(COLCON.BDBASEPIS13FT), sum(COLCON.BDBSALMATEMPFT), '||
                'sum(COLCON.BDSALMATEMPFT), sum(COLCON.BDBRATAPOFT), sum(COLCON.BDBRATAPOFEFT), sum(COLCON.BDBRATAPO13FT), '||
                'sum(COLCON.BDBINSSFEFOLFT), sum(COLCON.BDINSSFEFOLFT), max(COLCON.BDALIQINSSFEFOLFT), '||
                'COLCON.bdCodCentrotoma BDCODCENTRO, COLCON.bdCODTPCCTOMA BDCODTPCC, '||
                'sum(colcon.bdCreditoFT), sum(colcon.bdDebitoFT), '||
                'sum(colcon.bdBFGTSFEFT), sum(COLCON.BDFGTSFEFT), '||
                'sum(colcon.BDBSALMATEMPFNFT),sum(colcon.BDBSALMATEMP13FT),sum(colcon.BDVSALMATEMPFNFT),sum(colcon.BDVSALMATEMP13FT), sum(COLCON.BDLIQUIDO), MAX(COLCON.BDDATAPGTOFT), '||
                'sum(COLCON.BDBINSSAPFT), sum(COLCON.BDINSSAPFT), sum(COLCON.BDBINSS13APFT), sum(COLCON.BDINSS13APFT) '||
              'from (';

       wsql = wsql||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, cast(null as INTEGER) BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, '||
                'case when coalesce(COLCON.BDBASEINSSNMVNOVO, 0) <> 0 then COLCON.BDBASEINSSNMVNOVO else COLCON.BDBINSSFT end BDBINSSFT, '||
                'COLCON.BDALIQINSSFT,COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'case when coalesce(COLCON.BDBASEINSS13MVNOVO, 0) <> 0 then COLCON.BDBASEINSS13MVNOVO else COLCON.BDBINSS13FT end BDBINSS13FT, '||
                'COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(toma.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTROTOMA, toma.bdCODTPCC bdcodtpcctoma, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, '||
                'pf.bdCodCentro bdcodcentro, pf.bdCODTPCC bdcodtpcc, COLCON.BDLIQUIDO, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from vrhf_emp_tfolhatomador COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp)'||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro,'||prrefini||') toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              'left outer join VW_VRH_EMP_TCOLCON_VINC X on (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
              'left outer join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) '||
              wwheret;

       wsql = wsql||' union all '||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, '||
                'COLCON.BDBINSSFT, '||
                'COLCON.BDALIQINSSFT,COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'COLCON.BDBINSS13FT, '||
                'COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(toma.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTROTOMA, toma.bdCODTPCC bdcodtpcctoma, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, '||
                'pf.bdCodCentro bdcodcentro, pf.bdCODTPCC bdcodtpcc, COLCON.BDLIQUIDO, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from vrhf_emp_tfolhatomint COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp)'||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro,'||prrefini||') toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              'left outer join VW_VRH_EMP_TCOLCON_VINC X on (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
              'left outer join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) '||
              wwheret;

       wsql = wsql||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by COLCON.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,COLCON.BDCODCONTTI,colcon.BDREFTOMADOR,COLCON.bdCodCentroTOMA, COLCON.bdCODTPCCTOMA';
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 3)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFT), '||
                'sum(COLCON.BDFGTSFT), sum(COLCON.BDFGTSCSFT), sum(COLCON.BDBFGTS13FT), sum(COLCON.BDFGTS13FT), '||
                'sum(COLCON.BDFGTS13CSFT),sum(COLCON.BDMAIORREMFT), sum(COLCON.BDBINSSFT), max(COLCON.BDALIQINSSFT), '||
                'sum(COLCON.BDINSSFT), sum(COLCON.BDBIRRFFT), max(COLCON.BDALIQIRRFFT), sum(COLCON.BDIRRFFT), '||
                'sum(COLCON.BDBINSS13FT), max(COLCON.BDALIQINSS13FT), sum(COLCON.BDINSS13FT), '||
                'sum(COLCON.BDBIRRF13FT), max(COLCON.BDALIQIRRF13FT), sum(COLCON.BDIRRF13FT), sum(COLCON.BDBSALFAMFT), '||
                'sum(COLCON.BDSALFAMFT), sum(COLCON.BDBRAISFT), max(COLCON.BDSALBASEFT), '||
                'sum(COLCON.BDDEPFT), sum(COLCON.BDBASEPISFT), sum(COLCON.BDBASEPISFEFT), sum(COLCON.BDBASEPIS13FT), sum(COLCON.BDBSALMATEMPFT), '||
                'sum(COLCON.BDSALMATEMPFT), sum(COLCON.BDBRATAPOFT), sum(COLCON.BDBRATAPOFEFT), sum(COLCON.BDBRATAPO13FT), '||
                'sum(COLCON.BDBINSSFEFOLFT), sum(COLCON.BDINSSFEFOLFT), max(COLCON.BDALIQINSSFEFOLFT), '||
                'COLCON.BDCODCENTROTOMA bdCodCentro, COLCON.bdCODTPCCTOMA BDCODTPCC, '||
                'sum(colcon.bdCreditoFT), sum(colcon.bdDebitoFT), '||
                'sum(colcon.bdBFGTSFEFT), sum(COLCON.BDFGTSFEFT), '||
                'sum(colcon.BDBSALMATEMPFNFT),sum(colcon.BDBSALMATEMP13FT),sum(colcon.BDVSALMATEMPFNFT),sum(colcon.BDVSALMATEMP13FT), sum(COLCON.Bdliquido), MAX(COLCON.BDDATAPGTOFT), '||
                'sum(COLCON.BDBINSSAPFT), sum(COLCON.BDINSSAPFT), sum(COLCON.BDBINSS13APFT), sum(COLCON.BDINSS13APFT) '||
              'from ( ';

       wsql = wsql||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, cast(null as INTEGER) BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, '||
                'case when coalesce(COLCON.bdbaseinssnmvnovo, 0) <> 0 then COLCON.bdbaseinssnmvnovo else COLCON.BDBINSSFT end BDBINSSFT, '||
                'COLCON.BDALIQINSSFT, COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'case when coalesce(COLCON.bdbaseinss13mvnovo, 0) <> 0 then COLCON.bdbaseinss13mvnovo else COLCON.BDBINSS13FT end BDBINSS13FT, '||
                'COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(toma.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTROTOMA, toma.bdCODTPCC bdCODTPCCtoma, '||
                'case when COALESCE(pf.BDCODTPCC, 0) = 0 then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC BDCODTPCC, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from vrhf_emp_tfolhatomador COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              'left outer join VW_VRH_EMP_TCOLCON_VINC X on (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
              'left outer join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) '||
              wwheret;

       wsql = wsql||' union all '||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, '||
                'COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(toma.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTROTOMA, toma.bdCODTPCC bdCODTPCCtoma, '||
                'case when COALESCE(pf.BDCODTPCC, 0) = 0 then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC BDCODTPCC, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from vrhf_emp_tfolhatomint COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              'left outer join VW_VRH_EMP_TCOLCON_VINC X on (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
              'left outer join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) '||
              wwheret;

       wsql = wsql||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by COLCON.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,COLCON.BDCODCONTTI,colcon.BDREFTOMADOR,COLCON.bdCodCentrotoma,COLCON.bdCODTPCCtoma ';
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 2)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL,COLCON.BDCODCONTTI,COLCON.BDREFTOMADOR, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFT), '||
                'sum(COLCON.BDFGTSFT), sum(COLCON.BDFGTSCSFT), sum(COLCON.BDBFGTS13FT), sum(COLCON.BDFGTS13FT), '||
                'sum(COLCON.BDFGTS13CSFT),sum(COLCON.BDMAIORREMFT), sum(COLCON.BDBINSSFT), max(COLCON.BDALIQINSSFT), '||
                'sum(COLCON.BDINSSFT), sum(COLCON.BDBIRRFFT), max(COLCON.BDALIQIRRFFT), sum(COLCON.BDIRRFFT), '||
                'sum(COLCON.BDBINSS13FT), max(COLCON.BDALIQINSS13FT), sum(COLCON.BDINSS13FT), '||
                'sum(COLCON.BDBIRRF13FT), max(COLCON.BDALIQIRRF13FT), sum(COLCON.BDIRRF13FT), sum(COLCON.BDBSALFAMFT), '||
                'sum(COLCON.BDSALFAMFT), sum(COLCON.BDBRAISFT), max(COLCON.BDSALBASEFT), '||
                'sum(COLCON.BDDEPFT), sum(COLCON.BDBASEPISFT), sum(COLCON.BDBASEPISFEFT), sum(COLCON.BDBASEPIS13FT), sum(COLCON.BDBSALMATEMPFT), '||
                'sum(COLCON.BDSALMATEMPFT), sum(COLCON.BDBRATAPOFT),sum(COLCON.BDBRATAPOFEFT), sum(COLCON.BDBRATAPO13FT), '||
                'sum(COLCON.BDBINSSFEFOLFT), sum(COLCON.BDINSSFEFOLFT), max(COLCON.BDALIQINSSFEFOLFT), '||
                'COLCON.bdCodCentro, COLCON.bdCODTPCC, '||
                'sum(colcon.bdCreditoFT), sum(colcon.bdDebitoFT), '||
                'sum(colcon.bdBFGTSFEFT), sum(COLCON.BDFGTSFEFT), '||
                'sum(colcon.BDBSALMATEMPFNFT),sum(colcon.BDBSALMATEMP13FT),sum(colcon.BDVSALMATEMPFNFT),sum(colcon.BDVSALMATEMP13FT), sum(COLCON.bdliquido), MAX(COLCON.BDDATAPGTOFT), '||
                'sum(COLCON.BDBINSSAPFT), sum(COLCON.BDINSSAPFT), sum(COLCON.BDBINSS13APFT), sum(COLCON.BDINSS13APFT) '||
              'from ( ';

       wsql = wsql||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, cast(null as INTEGER) BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, '||
                'case when coalesce(colcon.bdbaseinssnmvnovo, 0) <> 0 then colcon.bdbaseinssnmvnovo else COLCON.BDBINSSFT end BDBINSSFT, '||
                'COLCON.BDALIQINSSFT, COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'case when coalesce(colcon.bdbaseinss13mvnovo, 0) <> 0 then colcon.bdbaseinss13mvnovo else COLCON.BDBINSS13FT end BDBINSS13FT, '||
                'COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT,COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(pf.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTRO, pf.bdCODTPCC, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from vrhf_emp_tfolhatomador COLCON '||
              'join tempresas emp on (emp.BDCODEMP = COLCON.BDCODEMP) '||
              'join vrhf_emp_tprepfn pf on (pf.BDCODEMP = COLCON.BDCODEMP and pf.BDCODCOL = COLCON.BDCODCOL and pf.BDORDEM = COLCON.BDORDEM) '||
              'left outer join VW_VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = COLCON.BDCODEMP and X.BDCODCOL = COLCON.BDCODCOL) '||
              'left outer join VRH_BASE_TCLASSE f on (f.bdcodcla = X.BDCODCLA) '||
              wwheret;

       wsql = wsql||' union all '||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, '||
                'COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT,COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'case when COALESCE(pf.bdCODTPCC, 0) = 0 then null else pf.bdCodCentro end BDCODCENTRO, pf.bdCODTPCC, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from vrhf_emp_tfolhatomint COLCON '||
              'join tempresas emp on (emp.bdcodemp = COLCON.BDCODEMP) '||
              'join vrhf_emp_tprepfn pf on (pf.bdcodemp = COLCON.BDCODEMP and pf.bdcodcol = COLCON.BDCODCOL and pf.bdordem = COLCON.BDORDEM) '||
              'left outer join VW_VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = COLCON.BDCODEMP and X.BDCODCOL = COLCON.BDCODCOL) '||
              'left outer join VRH_BASE_TCLASSE f on (f.bdcodcla = X.BDCODCLA) '||
              wwheret;

       wsql = wsql||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||'group by COLCON.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,COLCON.BDCODCONTTI,colcon.BDREFTOMADOR,COLCON.bdCodCentro, COLCON.bdCODTPCC ';
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 1)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL,COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFT),'||
                'sum(COLCON.BDFGTSFT), sum(COLCON.BDFGTSCSFT), sum(COLCON.BDBFGTS13FT), sum(COLCON.BDFGTS13FT),'||
                'sum(COLCON.BDFGTS13CSFT),sum(COLCON.BDMAIORREMFT), sum(COLCON.BDBINSSFT), max(COLCON.BDALIQINSSFT),'||
                'sum(COLCON.BDINSSFT), sum(COLCON.BDBIRRFFT), max(COLCON.BDALIQIRRFFT), sum(COLCON.BDIRRFFT),'||
                'sum(COLCON.BDBINSS13FT), max(COLCON.BDALIQINSS13FT), sum(COLCON.BDINSS13FT),'||
                'sum(COLCON.BDBIRRF13FT), max(COLCON.BDALIQIRRF13FT), sum(COLCON.BDIRRF13FT), sum(COLCON.BDBSALFAMFT),'||
                'sum(COLCON.BDSALFAMFT), sum(COLCON.BDBRAISFT), max(COLCON.BDSALBASEFT),'||
                'sum(COLCON.BDDEPFT), sum(COLCON.BDBASEPISFT), sum(COLCON.BDBASEPISFEFT), sum(COLCON.BDBASEPIS13FT), sum(COLCON.BDBSALMATEMPFT),'||
                'sum(COLCON.BDSALMATEMPFT), sum(COLCON.BDBRATAPOFT), sum(COLCON.BDBRATAPOFEFT), sum(COLCON.BDBRATAPO13FT),'||
                'sum(COLCON.BDBINSSFEFOLFT), sum(COLCON.BDINSSFEFOLFT), max(COLCON.BDALIQINSSFEFOLFT),'||
                'cast(null as integer), cast(null as integer),'||
                'sum(colcon.bdCreditoFT), sum(colcon.bdDebitoFT),'||
                'sum(colcon.bdBFGTSFEFT), sum(COLCON.BDFGTSFEFT),'||
                'sum(colcon.BDBSALMATEMPFNFT),sum(colcon.BDBSALMATEMP13FT),sum(colcon.BDVSALMATEMPFNFT),sum(colcon.BDVSALMATEMP13FT),sum(COLCON.bdliquido), MAX(COLCON.BDDATAPGTOFT), '||
                'sum(COLCON.BDBINSSAPFT), sum(COLCON.BDINSSAPFT), sum(COLCON.BDBINSS13APFT), sum(COLCON.BDINSS13APFT) '||
              'from (';

       wsql = wsql||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, cast(null as INTEGER) BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, '||
                'case when coalesce(colcon.bdbaseinssnmvnovo, 0) <> 0 then colcon.bdbaseinssnmvnovo else COLCON.BDBINSSFT end BDBINSSFT, '||
                'COLCON.BDALIQINSSFT, COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'case when coalesce(colcon.bdbaseinss13mvnovo, 0) <> 0 then colcon.bdbaseinss13mvnovo else COLCON.BDBINSS13FT end BDBINSS13FT, '||
                'COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, '||
                'case when COALESCE(pf.BDCODTPCC, 0) = 0 then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from vrhf_emp_tfolhatomador COLCON '||
              'join tempresas emp on (emp.BDCODEMP = COLCON.BDCODEMP) '||
              'join vrhf_emp_tprepfn pf on (pf.bdcodemp = COLCON.BDCODEMP and pf.bdcodcol = COLCON.BDCODCOL) '||
              'left outer join VW_VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = COLCON.BDCODEMP and X.BDCODCOL = COLCON.BDCODCOL) '||
              'left outer join VRH_BASE_TCLASSE f on (f.bdcodcla = X.BDCODCLA) '||
              wwheret;

       wsql = wsql||' union all '||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDCODCONTTI, COLCON.BDBFGTSFT, '||
                'COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, '||
                'COLCON.BDFGTS13CSFT,COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, '||
                'COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                'COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, '||
                'COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, '||
                'COLCON.BDDEPFT, COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, '||
                'case when COALESCE(pf.BDCODTPCC, 0) = 0 then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from vrhf_emp_tfolhatomint COLCON '||
              'join tempresas emp on (emp.bdcodemp = COLCON.BDCODEMP) '||
              'join vrhf_emp_tprepfn pf on (pf.bdcodemp = COLCON.BDCODEMP and pf.bdcodcol = COLCON.BDCODCOL and pf.bdordem = COLCON.BDORDEM) '||
              'left outer join VW_VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = COLCON.BDCODEMP and X.BDCODCOL = COLCON.BDCODCOL) '||
              'left outer join VRH_BASE_TCLASSE f on (f.bdcodcla = X.BDCODCLA) '||
              wwheret;

       wsql = wsql||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by COLCON.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,COLCON.BDCODCONTTI,colcon.BDREFTOMADOR';
     END
  ELSE
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI,COLCON.BDREFTOMADOR, COLCON.BDORDEM, COLCON.BDDATABAIXAFT, COLCON.BDBFGTSFT, COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, '||
                'COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, COLCON.BDFGTS13CSFT, '||
                'COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, COLCON.BDBINSS13FT, '||
                'COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT, '||
                'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, COLCON.BDDEPFT, '||
                'COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT, '||
                'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT, '||
                'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, COLCON.bdCodCentro, COLCON.bdCODTPCC, '||
                'colcon.bdCreditoFT, colcon.bdDebitoFT, '||
                'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
              'from ( ';

          wsql = wsql||'select '||
                 'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, cast(null as INTEGER) BDCODCONTTI,COLCON.BDORDEM, COLCON.BDDATABAIXAFT, COLCON.BDBFGTSFT, COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, COLCON.BDFGTS13CSFT,'||
                 'COLCON.BDMAIORREMFT, '||
                 'case when coalesce(colcon.bdbaseinssnmvnovo, 0) <> 0 then colcon.bdbaseinssnmvnovo else COLCON.BDBINSSFT end BDBINSSFT, '||
                 'COLCON.BDALIQINSSFT, COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, '||
                 'case when coalesce(colcon.bdbaseinss13mvnovo, 0) <> 0 then colcon.bdbaseinss13mvnovo else COLCON.BDBINSS13FT end BDBINSS13FT, '||
                 'COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT,'||
                 'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, COLCON.BDDEPFT, '||
                 'COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT,'||
                 'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT,'||
                 'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, pf.bdCodCentro, pf.bdCODTPCC,'||
                 'colcon.bdCreditoFT, colcon.bdDebitoFT,'||
                 'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                 'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                 'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
                 'from vrhf_emp_tfolhatomador COLCON '||
                 'join tempresas emp on (emp.bdcodemp = COLCON.BDCODEMP) '||
                 'join vrhf_emp_tprepfn pf on (pf.bdcodemp = COLCON.BDCODEMP and pf.bdcodcol = COLCON.BDCODCOL and pf.bdordem = COLCON.BDORDEM) '||
                 'left outer join VW_VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = COLCON.BDCODEMP and X.BDCODCOL = COLCON.BDCODCOL) '||
                 'left outer join VRH_BASE_TCLASSE f on (f.bdcodcla = X.BDCODCLA) '||
                 wwheret;

          wsql = wsql||'union all select '||
                 'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDCODCONTTI,COLCON.BDORDEM, COLCON.BDDATABAIXAFT, COLCON.BDBFGTSFT, COLCON.BDFGTSFT, COLCON.BDFGTSCSFT, COLCON.BDBFGTS13FT, COLCON.BDFGTS13FT, COLCON.BDFGTS13CSFT,'||
                 'COLCON.BDMAIORREMFT, COLCON.BDBINSSFT, COLCON.BDALIQINSSFT, COLCON.BDINSSFT, COLCON.BDBIRRFFT, COLCON.BDALIQIRRFFT, COLCON.BDIRRFFT, COLCON.BDBINSS13FT, COLCON.BDALIQINSS13FT, COLCON.BDINSS13FT,'||
                 'COLCON.BDBIRRF13FT, COLCON.BDALIQIRRF13FT, COLCON.BDIRRF13FT, COLCON.BDBSALFAMFT, COLCON.BDSALFAMFT, COLCON.BDBRAISFT, COLCON.BDSALBASEFT, COLCON.BDDEPFT, '||
                 'COLCON.BDBASEPISFT, COLCON.BDBASEPISFEFT, COLCON.BDBASEPIS13FT, COLCON.BDBSALMATEMPFT,'||
                 'COLCON.BDSALMATEMPFT, COLCON.BDBRATAPOFT, COLCON.BDBRATAPOFEFT, COLCON.BDBRATAPO13FT,'||
                 'COLCON.BDBINSSFEFOLFT, COLCON.BDINSSFEFOLFT, COLCON.BDALIQINSSFEFOLFT, pf.bdCodCentro, pf.bdCODTPCC,'||
                 'colcon.bdCreditoFT, colcon.bdDebitoFT,'||
                 'colcon.bdBFGTSFEFT, COLCON.BDFGTSFEFT, '||
                 'colcon.BDBSALMATEMPFNFT,colcon.BDBSALMATEMP13FT,colcon.BDVSALMATEMPFNFT,colcon.BDVSALMATEMP13FT, COLCON.bdliquido, COLCON.BDDATAPGTOFT, '||
                 'COLCON.BDBINSSAPFT, COLCON.BDINSSAPFT, COLCON.BDBINSS13APFT, COLCON.BDINSS13APFT '||
                 'from vrhf_emp_tfolhatomint COLCON '||
                 'join tempresas emp on (emp.bdcodemp = COLCON.BDCODEMP) '||
                 'join vrhf_emp_tprepfn pf on (pf.bdcodemp = COLCON.BDCODEMP and pf.bdcodcol = COLCON.BDCODCOL and pf.bdordem = COLCON.BDORDEM) '||
                 'left outer join VW_VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = COLCON.BDCODEMP and X.BDCODCOL = COLCON.BDCODCOL) '||
                 'left outer join VRH_BASE_TCLASSE f on (f.bdcodcla = X.BDCODCLA) '||
                 wwheret;

       wsql = wsql||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;
     END

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdgrupocla,
    :bdcodemp, --BDCODEMP,
    :bdcodcol, -- BDCODCOL,
    :bdcodcontti, --BDCODCONTTI,
    :bdreffn, -- BDREFTOMADOR,
    :bdordem, -- BDORDEM,
    :bddatabaixafn, -- BDDATABAIXAFT,
    :bdbfgtsfn, -- BDBFGTSFT,
    :bdfgtsfn, -- BDFGTSFT,
    :bdfgtscsfn, -- BDFGTSCSFT,
    :bdbfgts13fn, --- BDBFGTS13FT,
    :bdfgts13fn, -- BDFGTS13FT,
    :bdfgts13csfn, -- BDFGTS13CSFT,'||
    :bdmaiorremfn, -- 'BDMAIORREMFT,
    :bdbinssfn, -- BDBINSSFT,
    :bdaliqinssfn, -- BDALIQINSSFT,
    :bdinssfn, -- BDINSSFT,
    :bdbirrffn, -- BDBIRRFFT,
    :bdaliqirrffn, -- BDALIQIRRFFT,
    :bdirrffn, -- BDIRRFFT,
    :bdbinss13fn, -- BDBINSS13FT,
    :bdaliqinss13fn, -- BDALIQINSS13FT,
    :bdinss13fn, -- BDINSS13FT,'||
    :bdbirrf13fn, -- 'BDBIRRF13FT,
    :bdaliqirrf13fn, -- BDALIQIRRF13FT,
    :bdirrf13fn, -- BDIRRF13FT,
    :bdbsalfamfn, -- BDBSALFAMFT,
    :bdsalfamfn, --BDSALFAMFT,
    :bdbraisfn, -- BDBRAISFT,
    :bdsalbasefn, -- BDSALBASEFT,
    :bddepfn, -- BDDEPFT,
    :bdbasepisfn, -- BDBASEPISFT,
    :bdbasepisFEfn, -- BDBASEPISFEFT,
    :bdbasepis13fn, -- BDBASEPIS13FT,
    :bdbsalmatempfn, -- BDBSALMATEMPFT,'||
    :bdsalmatempfn, -- 'BDSALMATEMPFT,
    :bdbratapofn, -- BDBRATAPOFT,
    :bdbratapoFEfn, -- BDBRATAPOFEFT,
    :bdbratapo13fn, -- BDBRATAPO13FT,
    :bdbinssfefolfn, -- BDBINSSFEFOLFT,
    :bdinssfefolfn, -- BDALIQINSSFEFOLFT'||
    :bdaliqinssfefolfn, -- BDINSSFEFOLFT,
    :bdCodCentro, -- bdCodCentro
    :bdCODTPCC, -- BDCODTPCC
    :bdcreditofn,
    :bddebitofn,
    :bdBFGTSFEFN,
    :BDFGTSFEFN,
    :BDBMATEMPFNFN,
    :BDBMATEMP13FN,
    :BDVMATEMPFNFN,
    :BDVMATEMP13FN,
    :BDLIQUIDOFN,
    :BDDATAPGTO,
    :BDBINSSAPFN,
    :BDINSSAPFN,
    :BDBINSS13APFN,
    :BDINSS13APFN
  DO
    BEGIN
      bdcalctomador = 'True';
      if (bdcodcontti is null) then
         bdcodcontti = 0;
      SUSPEND;
    END
END^

/* Restore proc. body: SP_VRHF_AGRUPAR_QH */
create or alter procedure SP_VRHF_AGRUPAR_QH
returns (
    BDCODQHH integer,
    BDDESCRICAO varchar(300))
as
declare variable WSQL varchar(300);
declare variable WSQL2 varchar(300);
declare variable WDESCRICAO varchar(300);
declare variable WCODQHH integer;
declare variable WCODQHHS integer;
declare variable WQHHSSAI varchar(50);
declare variable WQHHSENT varchar(50);
declare variable WCODQHHSMAX integer;
declare variable WULTIMOCODQHH integer;
declare variable WHORASTRABALHOFLEXIVEL varchar(50);
declare variable WHORAINTERVALOFLEXIVEL varchar(50);
BEGIN
  WSQL = 'SELECT HORAS.BDCODQHH, HORAS.BDCODQHHS, HORAS.BDQHHSENT, HORAS.BDQHHSSAI, HORAS.BDINTERVALO, HORAS.BDHORAFLEX FROM vrh_base_tqh_horas HORAS ';
  WSQL = WSQL || 'GROUP BY HORAS.BDCODQHH, HORAS.BDCODQHHS, HORAS.BDQHHSENT, HORAS.BDQHHSSAI, HORAS.BDINTERVALO, HORAS.BDHORAFLEX  ';
  WSQL = WSQL || 'ORDER BY HORAS.BDCODQHH, HORAS.BDCODQHHS ';

  wultimocodqhh = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    :wcodqhh, 
    :wcodqhhs,
    :wqhhsent,
    :wqhhssai,
    :WHORAINTERVALOFLEXIVEL,
    :WHORASTRABALHOFLEXIVEL
  DO
    BEGIN
      IF ((WHORAINTERVALOFLEXIVEL IS NOT NULL) AND (WHORASTRABALHOFLEXIVEL IS NOT NULL)) THEN
         BEGIN
           wdescricao = SUBSTRING(WHORAINTERVALOFLEXIVEL FROM 1 FOR 8) || ' ' || SUBSTRING(WHORASTRABALHOFLEXIVEL FROM 1 FOR 8) || ' ';
         END
      ELSE
      IF ((wcodqhh IS NULL) OR (wcodqhh <> wultimocodqhh))  THEN
         BEGIN
           wdescricao = SUBSTRING(wqhhsent FROM 1 FOR 8) || ' ' || SUBSTRING(wqhhssai FROM 1 FOR 8) || ' ';
           wultimocodqhh = wcodqhh;
         END
      ELSE
         BEGIN
           wdescricao = wdescricao || SUBSTRING(wqhhsent FROM 1 FOR 8) || ' ' || SUBSTRING(wqhhssai FROM 1 FOR 8) || ' ';
           wultimocodqhh = wcodqhh;
         END

      SELECT MAX(bdcodqhhs) FROM vrh_base_tqh_horas WHERE bdcodqhh = :wcodqhh INTO :wcodqhhsmax;

      IF (wcodqhhs = wcodqhhsmax) THEN
         BEGIN
           bdcodqhh = wcodqhh;
           bddescricao = wdescricao;

           SUSPEND;
         END
    END
END^

/* Restore proc. body: VRHF_SP_TFOLHA_NORMAL_PREV_RESC */
create or alter procedure VRHF_SP_TFOLHA_NORMAL_PREV_RESC (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(772) = null)
returns (
    BDGRUPOCLA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDREFFN integer,
    BDDATABAIXAFN date,
    BDBFGTSFN numeric(15,6),
    BDFGTSFN numeric(15,6),
    BDFGTSCSFN numeric(15,6),
    BDBFGTS13FN numeric(15,6),
    BDFGTS13FN numeric(15,6),
    BDFGTS13CSFN numeric(15,6),
    BDMAIORREMFN numeric(15,6),
    BDBINSSFN numeric(15,6),
    BDALIQINSSFN numeric(15,6),
    BDINSSFN numeric(15,6),
    BDBIRRFFN numeric(15,6),
    BDALIQIRRFFN numeric(15,6),
    BDIRRFFN numeric(15,6),
    BDBINSS13FN numeric(15,6),
    BDALIQINSS13FN numeric(15,6),
    BDINSS13FN numeric(15,6),
    BDBIRRF13FN numeric(15,6),
    BDALIQIRRF13FN numeric(15,6),
    BDIRRF13FN numeric(15,6),
    BDBSALFAMFN numeric(15,6),
    BDSALFAMFN numeric(15,6),
    BDBRAISFN numeric(15,6),
    BDSALBASEFN numeric(15,6),
    BDDEPFN numeric(15,6),
    BDBASEPISFN numeric(15,6),
    BDBASEPISFEFN numeric(15,6),
    BDBASEPIS13FN numeric(15,6),
    BDBSALMATEMPFN numeric(15,6),
    BDSALMATEMPFN numeric(15,6),
    BDBRATAPOFN numeric(15,6),
    BDBRATAPOFEFN numeric(15,6),
    BDBRATAPO13FN numeric(15,6),
    BDBINSSFEFOLFN numeric(15,6),
    BDINSSFEFOLFN numeric(15,6),
    BDALIQINSSFEFOLFN numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDCREDITOFN numeric(15,6),
    BDDEBITOFN numeric(15,6),
    BDBFGTSFEFN numeric(15,6),
    BDFGTSFEFN numeric(15,6),
    BDBMATEMPFNFN numeric(15,6),
    BDBMATEMP13FN numeric(15,6),
    BDVMATEMPFNFN numeric(15,6),
    BDVMATEMP13FN numeric(15,6),
    BDLIQUIDOFN numeric(18,6),
    BDDATAPGTO date,
    BDBINSSAPFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSS13APFN numeric(18,6))
as
declare variable WSQL varchar(32700);
declare variable WWHEREN varchar(32700);
declare variable WWHERET varchar(32700);
BEGIN
  /* pragrupatomador
     0 = Nao agrupa
     1 = Agrupa por referencia
     2 = Agrupo por referencia e centro/Tomador
     3 = Agrupa por referencia e Tomador (se nao for tomador verifica pela classificacao e nao encontrando considera empresa)
     4 = Agrupa por referencia e Tipo Tomador (so vai criar mais registros pra empresa se for tomador 155)
  */

  /* Procedure Text */
  wsql = 'select f.bdgrupocla, colcon.BDCODEMP, colcon.BDCODCOL, prevresc.bdrefrescisaoprev, colcon.BDDATABAIXAFNPR, colcon.BDBFGTSFNPR,'||
         'colcon.BDFGTSFNPR, colcon.BDFGTSCSFNPR, colcon.BDBFGTS13FNPR, colcon.BDFGTS13FNPR, colcon.BDFGTS13CSFNPR, colcon.BDMAIORREMFNPR,'||
         'case when coalesce(colcon.bdbaseinssnmvnovo, 0) <> 0 then colcon.bdbaseinssnmvnovo else colcon.BDBINSSFNPR end BDBINSSFNPR, '||
         'colcon.BDALIQINSSFNPR, colcon.BDINSSFNPR, colcon.BDBIRRFFNPR, colcon.BDALIQIRRFFNPR, colcon.BDIRRFFNPR,'||
         'case when coalesce(colcon.bdbaseinss13mvnovo, 0) <> 0 then colcon.bdbaseinss13mvnovo else colcon.BDBINSS13FNPR end BDBINSS13FNPR, '||
         'colcon.BDALIQINSS13FNPR, colcon.BDINSS13FNPR, colcon.BDBIRRF13FNPR, colcon.BDALIQIRRF13FNPR,'||
         'colcon.BDIRRF13FNPR, colcon.BDBSALFAMFNPR, colcon.BDSALFAMFNPR, colcon.BDBRAISFNPR, colcon.BDSALBASEFNPR, colcon.BDDEPFNPR,'||
         'colcon.BDBASEPISFNPR, 0 BDBASEPISFEFN, 0 BDBASEPIS13FN, colcon.BDBSALMATEMPFNPR, colcon.BDSALMATEMPFNPR, colcon.BDBRATAPOFNPR, 0 BDBRATAPOFEFN, 0 BDBRATAPO13FN,'||
         'colcon.BDBINSSFEFOLFNPR,'||
         'colcon.BDINSSFEFOLFNPR, colcon.BDALIQINSSFEFOLFNPR, 0 bdcreditofn, 0 bddebitofn,'||
         'colcon.bdBFGTSFEFN, COLCON.BDFGTSFEFN'||
         ',COLCON.BDBSALMATEMPFNPR,0 BDBSALMATEMP13FN,COLCON.BDSALMATEMPFNPR, 0 BDVSALMATEMP13FN, 0 BDLIQUIDO, CAST(null as DATE) BDDATAPGTOFN, '||
         'COLCON.BDBINSSAPFNPR, COLCON.BDINSSAPFNPR, COLCON.BDBINSS13APFNPR, COLCON.BDINSS13APFNPR '||
         'from vrhf_emp_tfolhanormal_prev_resc COLCON '||
         'join vrh_emp_trescisao_previa prevresc on (prevresc.bdcodemp = COLCON.BDCODEMP and prevresc.bdcodcol = COLCON.BDCODCOL) '||
         'join tempresas emp on (emp.bdcodemp = COLCON.BDCODEMP) '||
         'left outer join VW_VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = COLCON.BDCODEMP and X.BDCODCOL = COLCON.BDCODCOL) '||
         'left outer join VRH_BASE_TCLASSE f on (f.bdcodcla = X.BDCODCLA) ';


  if (coalesce(prpuxafiliais, 0) = 1 and coalesce(prcodemp, '') <> '') then
     begin
       prcodemp = UPPER(prcodemp);

       if (coalesce(prfiliais, '') <> '') then
          begin
            wwheren = replace(prcodemp,'COLCON.BDCODEMP','EMP.BDCODMATRIZ');
            prcodemp = '('||prcodemp||' or (('||wwheren||') and (emp.bdcodemp in ('||prfiliais||'))))';
          end
       else
          prcodemp = replace(prcodemp,'COLCON.BDCODEMP','coalesce(emp.bdcodmatriz,emp.bdcodemp)');
     end

  wwheren = '';
  wwheret = '';

  if (coalesce(prcodemp, '') <> '') then
     begin
       wwheren = wwheren||prcodemp;
       wwheret = wwheret||prcodemp;

       if (coalesce(prcodcol, '') <> '') then
          begin
            wwheren = wwheren||' and '||prcodcol;
            wwheret = wwheret||' and '||prcodcol;
          end
     end

  if (coalesce(prrefini, 0) <> 0 and coalesce(prreffim, 0) <> 0) then
     begin
       if (wwheren <> '') then
          wwheren = wwheren||' and ';

       if (wwheret <> '') then
          wwheret = wwheret||' and ';

       wwheren = wwheren||'prevresc.BDREFRESCISAOPREV >= '||prrefini||' and '||'prevresc.BDREFRESCISAOPREV <= '||prreffim;
       wwheret = wwheret||'prevresc.BDREFRESCISAOPREV >= '||prrefini||' and '||'prevresc.BDREFRESCISAOPREV <= '||prreffim;
     end
  else
     begin
       if (coalesce(prrefini, 0) <> 0) then
          begin
            if (wwheren <> '') then
               wwheren = wwheren||' and ';
     
            if (wwheret <> '') then
               wwheret = wwheret||' and ';

            wwheren = wwheren||'prevresc.BDREFRESCISAOPREV= '||prrefini;
            wwheret = wwhereT||'prevresc.BDREFRESCISAOPREV = '||prrefini;
          end
       else
          begin
            if (coalesce(prreffim, 0) <> 0) then
               begin
                 if (wwheren <> '') then
                    wwheren = wwheren||' and ';
          
                 if (wwheret <> '') then
                    wwheret = wwheret||' and ';

                 wwheren = wwheren||'prevresc.BDREFRESCISAOPREV = '||prreffim;
                 wwheret = wwhereT||'prevresc.BDREFRESCISAOPREV = '||prreffim;
               end
          end
     end

  if (wwheren <> '') then
     wwheren = ' where '||wwheren;

  if (wwheret <> '') then
     wwheret = ' where '||wwheret;


  if (coalesce(prcodtpcc, '') = '') then
     begin
       for execute statement wsql||wwheren
       into
         :bdGrupocla,
         :bdcodemp,
         :bdcodcol,
         :bdreffn,
         :bddatabaixafn,
         :bdbfgtsfn,
         :bdfgtsfn,
         :bdfgtscsfn,
         :bdbfgts13fn,
         :bdfgts13fn,
         :bdfgts13csfn,
         :bdmaiorremfn,
         :bdbinssfn,
         :bdaliqinssfn,
         :bdinssfn,
         :bdbirrffn,
         :bdaliqirrffn,
         :bdirrffn,
         :bdbinss13fn,
         :bdaliqinss13fn,
         :bdinss13fn,
         :bdbirrf13fn,
         :bdaliqirrf13fn,
         :bdirrf13fn,
         :bdbsalfamfn,
         :bdsalfamfn,
         :bdbraisfn,
         :bdsalbasefn,
         :bddepfn,
         :bdbasepisfn,
         :bdbasepisFEfn,
         :bdbasepis13fn,
         :bdbsalmatempfn,
         :bdsalmatempfn,
         :bdbratapofn,
         :bdbratapoFEfn,
         :bdbratapo13fn,
         :bdbinssfefolfn,
         :bdinssfefolfn,
         :bdaliqinssfefolfn,
         :bdcreditofn,
         :bddebitofn,
         :bdBFGTSFEFN,
         :BDFGTSFEFN,
         :BDBMATEMPFNFN,
         :BDBMATEMP13FN,
         :BDVMATEMPFNFN,
         :BDVMATEMP13FN,
         :BDLIQUIDOFN,
         :BDDATAPGTO,
         :BDBINSSAPFN,
         :BDINSSAPFN,
         :BDBINSS13APFN,
         :BDINSS13APFN
       DO
         BEGIN
           bdcalctomador = 'False';
           SUSPEND;
         END
    END

  BDBMATEMPFNFN = 0;
  BDBMATEMP13FN = 0;
  BDVMATEMPFNFN = 0;
  BDVMATEMP13FN = 0;
  IF (coalesce(pragrupatomador, 0) = 4) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFRESCISAOPREV, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFTPR), '||
                'sum(COLCON.BDFGTSFTPR), sum(COLCON.BDFGTSCSFTPR), sum(COLCON.BDBFGTS13FTPR), sum(COLCON.BDFGTS13FTPR), '||
                'sum(COLCON.BDFGTS13CSFTPR),sum(COLCON.BDMAIORREMFTPR), sum(COLCON.BDBINSSFTPR), max(COLCON.BDALIQINSSFTPR), '||
                'sum(COLCON.BDINSSFTPR), sum(COLCON.BDBIRRFFTPR), max(COLCON.BDALIQIRRFFTPR), sum(COLCON.BDIRRFFTPR), '||
                'sum(COLCON.BDBINSS13FTPR), max(COLCON.BDALIQINSS13FTPR), sum(COLCON.BDINSS13FTPR), '||
                'sum(COLCON.BDBIRRF13FTPR), max(COLCON.BDALIQIRRF13FTPR), sum(COLCON.BDIRRF13FTPR), sum(COLCON.BDBSALFAMFTPR), '||
                'sum(COLCON.BDSALFAMFTPR), sum(COLCON.BDBRAISFTPR), max(COLCON.BDSALBASEFTPR), '||
                'sum(COLCON.BDDEPFTPR), sum(COLCON.BDBASEPISFTPR), sum(COLCON.BDBASEPISFEFTPR), sum(COLCON.BDBASEPIS13FTPR), sum(COLCON.BDBSALMATEMPFTPR), '||
                'sum(COLCON.BDSALMATEMPFTPR), sum(COLCON.BDBRATAPOFTPR), sum(COLCON.BDBRATAPOFEFTPR), sum(COLCON.BDBRATAPO13FTPR), '||
                'sum(COLCON.BDBINSSFEFOLFTPR), sum(COLCON.BDINSSFEFOLFTPR), max(COLCON.BDALIQINSSFEFOLFTPR), '||
                'COLCON.bdCodCentrotoma BDCODCENTRO, COLCON.bdCODTPCCTOMA BDCODTPCC, '||
                'sum(colcon.bdCreditoFTPR), sum(colcon.bdDebitoFTPR), '||
                'sum(colcon.bdBFGTSFEFTPR), sum(COLCON.BDFGTSFEFTPR), '||
                'sum(colcon.BDBSALMATEMPFNFTPR),sum(colcon.BDBSALMATEMP13FTPR),sum(colcon.BDVSALMATEMPFNFTPR),sum(colcon.BDVSALMATEMP13FTPR), sum(COLCON.BDLIQUIDOFTPR), MAX(COLCON.BDDATAPGTOFTPR), '||
                'sum(COLCON.BDBINSSAPFTPR), sum(COLCON.BDINSSAPFTPR), sum(COLCON.BDBINSS13APFTPR), sum(COLCON.BDINSS13APFTPR) '||
              'from (';

       wsql = wsql||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, prevresc.BDREFRESCISAOPREV, COLCON.BDBFGTSFTPR, '||
                'COLCON.BDFGTSFTPR, COLCON.BDFGTSCSFTPR, COLCON.BDBFGTS13FTPR, COLCON.BDFGTS13FTPR, '||
                'COLCON.BDFGTS13CSFTPR,COLCON.BDMAIORREMFTPR, '||
                'case when coalesce(colcon.bdbaseinssnmvnovo, 0) <> 0 then colcon.bdbaseinssnmvnovo else COLCON.BDBINSSFTPR end BDBINSSFTPR, '||
                'COLCON.BDALIQINSSFTPR, COLCON.BDINSSFTPR, COLCON.BDBIRRFFTPR, COLCON.BDALIQIRRFFTPR, COLCON.BDIRRFFTPR, '||
                'case when coalesce(colcon.bdbaseinss13mvnovo, 0) <> 0 then colcon.bdbaseinss13mvnovo else COLCON.BDBINSS13FTPR end BDBINSS13FTPR, '||
                'COLCON.BDALIQINSS13FTPR, COLCON.BDINSS13FTPR, '||
                'COLCON.BDBIRRF13FTPR, COLCON.BDALIQIRRF13FTPR, COLCON.BDIRRF13FTPR, COLCON.BDBSALFAMFTPR, '||
                'COLCON.BDSALFAMFTPR, COLCON.BDBRAISFTPR, COLCON.BDSALBASEFTPR, '||
                'COLCON.BDDEPFTPR, COLCON.BDBASEPISFTPR, COLCON.BDBASEPISFEFTPR, COLCON.BDBASEPIS13FTPR, COLCON.BDBSALMATEMPFTPR, '||
                'COLCON.BDSALMATEMPFTPR, COLCON.BDBRATAPOFTPR, COLCON.BDBRATAPOFEFTPR, COLCON.BDBRATAPO13FTPR, '||
                'COLCON.BDBINSSFEFOLFTPR, COLCON.BDINSSFEFOLFTPR, COLCON.BDALIQINSSFEFOLFTPR, '||
                'pf.bdCodCentro bdcodcentrotoma, toma.bdCODTPCC bdcodtpcctoma, '||
                'colcon.bdCreditoFTPR, colcon.bdDebitoFTPR, '||
                'colcon.bdBFGTSFEFTPR, COLCON.BDFGTSFEFTPR, '||
                '0 BDBSALMATEMPFNFTPR,0 BDBSALMATEMP13FTPR,0 BDVSALMATEMPFNFTPR, 0 BDVSALMATEMP13FTPR, '||
                'pf.bdCodCentro bdcodcentro, pf.bdCODTPCC bdcodtpcc, COLCON.BDLIQUIDOFTPR, CAST(null as DATE) BDDATAPGTOFTPR, '||
                'COLCON.BDBINSSAPFTPR, COLCON.BDINSSAPFTPR, COLCON.BDBINSS13APFTPR, COLCON.BDINSS13APFTPR '||
              'from vrhf_emp_tfoltom_prev_resc COLCON '||
              ' join vrh_emp_trescisao_previa prevresc on (prevresc.bdcodemp = colcon.bdcodemp and prevresc.bdcodcol = colcon.bdcodcol) '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp)'||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro,'||prrefini||') toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              'left outer join VW_VRH_EMP_TCOLCON_VINC X on (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
              'left outer join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) '||
              wwheret||') COLCON ';

       if (coalesce(prcodtpcc, '') <> '') then
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by COLCON.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,colcon.BDREFRESCISAOPREV,COLCON.bdCodCentroTOMA, COLCON.bdCODTPCCTOMA';
     end
  else if (coalesce(pragrupatomador, 0) = 3) then
     begin
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFRESCISAOPREV, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFTPR), '||
                'sum(COLCON.BDFGTSFTPR), sum(COLCON.BDFGTSCSFTPR), sum(COLCON.BDBFGTS13FTPR), sum(COLCON.BDFGTS13FTPR), '||
                'sum(COLCON.BDFGTS13CSFTPR),sum(COLCON.BDMAIORREMFTPR), sum(COLCON.BDBINSSFTPR), max(COLCON.BDALIQINSSFTPR), '||
                'sum(COLCON.BDINSSFTPR), sum(COLCON.BDBIRRFFTPR), max(COLCON.BDALIQIRRFFTPR), sum(COLCON.BDIRRFFTPR), '||
                'sum(COLCON.BDBINSS13FTPR), max(COLCON.BDALIQINSS13FTPR), sum(COLCON.BDINSS13FTPR), '||
                'sum(COLCON.BDBIRRF13FTPR), max(COLCON.BDALIQIRRF13FTPR), sum(COLCON.BDIRRF13FTPR), sum(COLCON.BDBSALFAMFTPR), '||
                'sum(COLCON.BDSALFAMFTPR), sum(COLCON.BDBRAISFTPR), max(COLCON.BDSALBASEFTPR), '||
                'sum(COLCON.BDDEPFTPR), sum(COLCON.BDBASEPISFTPR), sum(COLCON.BDBASEPISFEFTPR), sum(COLCON.BDBASEPIS13FTPR), sum(COLCON.BDBSALMATEMPFTPR), '||
                'sum(COLCON.BDSALMATEMPFTPR), sum(COLCON.BDBRATAPOFTPR), sum(COLCON.BDBRATAPOFEFTPR), sum(COLCON.BDBRATAPO13FTPR), '||
                'sum(COLCON.BDBINSSFEFOLFTPR), sum(COLCON.BDINSSFEFOLFTPR), max(COLCON.BDALIQINSSFEFOLFTPR), '||
                'COLCON.BDCODCENTROTOMA bdCodCentro, COLCON.bdCODTPCCTOMA BDCODTPCC, '||
                'sum(colcon.bdCreditoFTPR), sum(colcon.bdDebitoFTPR), '||
                'sum(colcon.bdBFGTSFEFTPR), sum(COLCON.BDFGTSFEFTPR), '||
                'sum(colcon.BDBSALMATEMPFNFTPR),sum(colcon.BDBSALMATEMP13FTPR),sum(colcon.BDVSALMATEMPFNFTPR),sum(colcon.BDVSALMATEMP13FTPR), sum(COLCON.BdliquidoFTPR), MAX(COLCON.BDDATAPGTOFTPR), '||
                'sum(COLCON.BDBINSSAPFTPR), sum(COLCON.BDINSSAPFTPR), sum(COLCON.BDBINSS13APFTPR), sum(COLCON.BDINSS13APFTPR) '||
              'from ( ';

       wsql = wsql||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, prevresc.BDREFRESCISAOPREV, COLCON.BDBFGTSFTPR, '||
                'COLCON.BDFGTSFTPR, COLCON.BDFGTSCSFTPR, COLCON.BDBFGTS13FTPR, COLCON.BDFGTS13FTPR, '||
                'COLCON.BDFGTS13CSFTPR,COLCON.BDMAIORREMFTPR, '||
                'case when coalesce(colcon.bdbaseinssnmvnovo, 0) <> 0 then colcon.bdbaseinssnmvnovo else COLCON.BDBINSSFTPR end BDBINSSFTPR, '||
                'COLCON.BDALIQINSSFTPR, COLCON.BDINSSFTPR, COLCON.BDBIRRFFTPR, COLCON.BDALIQIRRFFTPR, COLCON.BDIRRFFTPR, '||
                'case when coalesce(colcon.bdbaseinss13mvnovo, 0) <> 0 then colcon.bdbaseinss13mvnovo else COLCON.BDBINSS13FTPR end BDBINSS13FTPR, '||
                'COLCON.BDALIQINSS13FTPR, COLCON.BDINSS13FTPR, '||
                'COLCON.BDBIRRF13FTPR, COLCON.BDALIQIRRF13FTPR, COLCON.BDIRRF13FTPR, COLCON.BDBSALFAMFTPR, '||
                'COLCON.BDSALFAMFTPR, COLCON.BDBRAISFTPR, COLCON.BDSALBASEFTPR, '||
                'COLCON.BDDEPFTPR, COLCON.BDBASEPISFTPR, COLCON.BDBASEPISFEFTPR, COLCON.BDBASEPIS13FTPR, COLCON.BDBSALMATEMPFTPR, '||
                'COLCON.BDSALMATEMPFTPR, COLCON.BDBRATAPOFTPR, COLCON.BDBRATAPOFEFTPR, COLCON.BDBRATAPO13FTPR, '||
                'COLCON.BDBINSSFEFOLFTPR, COLCON.BDINSSFEFOLFTPR, COLCON.BDALIQINSSFEFOLFTPR, '||
                'pf.bdCodCentro bdCodCentrotoma, toma.bdCODTPCC bdCODTPCCtoma, pf.BDCODCENTRO BDCODCENTRO, pf.BDCODTPCC BDCODTPCC, '||
                'colcon.bdCreditoFTPR, colcon.bdDebitoFTPR, '||
                'colcon.bdBFGTSFEFTPR, COLCON.BDFGTSFEFTPR, '||
                '0 BDBSALMATEMPFNFTPR,0 BDBSALMATEMP13FTPR,0 BDVSALMATEMPFNFTPR,0 BDVSALMATEMP13FTPR, COLCON.bdliquidoFTPR, CAST(null as DATE) BDDATAPGTOFTPR, '||
                'COLCON.BDBINSSAPFTPR, COLCON.BDINSSAPFTPR, COLCON.BDBINSS13APFTPR, COLCON.BDINSS13APFTPR '||
              'from vrhf_emp_tfoltom_prev_resc COLCON '||
              ' join vrh_emp_trescisao_previa prevresc on (prevresc.bdcodemp = colcon.bdcodemp and prevresc.bdcodcol = colcon.bdcodcol) '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              'left outer join VW_VRH_EMP_TCOLCON_VINC X on (colcon.bdcodemp = X.bdcodemp and colcon.bdcodcol = X.bdcodcol) '||
              'left outer join VRH_BASE_TCLASSE f on (X.bdcodcla = f.bdcodcla) '||
              wwheret||') COLCON ';

       if (coalesce(prcodtpcc, '') <> '') then
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by COLCON.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,colcon.BDREFRESCISAOPREV,COLCON.bdCodCentrotoma,COLCON.bdCODTPCCtoma ';
     end
  else if (coalesce(pragrupatomador, 0) = 2) then
     begin
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFRESCISAOPREV, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFTPR), '||
                'sum(COLCON.BDFGTSFTPR), sum(COLCON.BDFGTSCSFTPR), sum(COLCON.BDBFGTS13FTPR), sum(COLCON.BDFGTS13FTPR), '||
                'sum(COLCON.BDFGTS13CSFTPR),sum(COLCON.BDMAIORREMFTPR), sum(COLCON.BDBINSSFTPR), max(COLCON.BDALIQINSSFTPR), '||
                'sum(COLCON.BDINSSFTPR), sum(COLCON.BDBIRRFFTPR), max(COLCON.BDALIQIRRFFTPR), sum(COLCON.BDIRRFFTPR), '||
                'sum(COLCON.BDBINSS13FTPR), max(COLCON.BDALIQINSS13FTPR), sum(COLCON.BDINSS13FTPR), '||
                'sum(COLCON.BDBIRRF13FTPR), max(COLCON.BDALIQIRRF13FTPR), sum(COLCON.BDIRRF13FTPR), sum(COLCON.BDBSALFAMFTPR), '||
                'sum(COLCON.BDSALFAMFTPR), sum(COLCON.BDBRAISFTPR), max(COLCON.BDSALBASEFTPR), '||
                'sum(COLCON.BDDEPFTPR), sum(COLCON.BDBASEPISFTPR), sum(COLCON.BDBASEPISFEFTPR), sum(COLCON.BDBASEPIS13FTPR), sum(COLCON.BDBSALMATEMPFTPR), '||
                'sum(COLCON.BDSALMATEMPFTPR), sum(COLCON.BDBRATAPOFTPR),sum(COLCON.BDBRATAPOFEFTPR), sum(COLCON.BDBRATAPO13FTPR), '||
                'sum(COLCON.BDBINSSFEFOLFTPR), sum(COLCON.BDINSSFEFOLFTPR), max(COLCON.BDALIQINSSFEFOLFTPR), '||
                'COLCON.bdCodCentro, COLCON.bdCODTPCC, '||
                'sum(colcon.bdCreditoFTPR), sum(colcon.bdDebitoFTPR), '||
                'sum(colcon.bdBFGTSFEFTPR), sum(COLCON.BDFGTSFEFTPR), '||
                'sum(colcon.BDBSALMATEMPFNFTPR),sum(colcon.BDBSALMATEMP13FTPR),sum(colcon.BDVSALMATEMPFNFTPR),sum(colcon.BDVSALMATEMP13FTPR), sum(COLCON.bdliquidoFTPR), MAX(COLCON.BDDATAPGTOFTPR), '||
                'sum(COLCON.BDBINSSAPFTPR), sum(COLCON.BDINSSAPFTPR), sum(COLCON.BDBINSS13APFTPR), sum(COLCON.BDINSS13APFTPR) '||
              'from ( ';

       wsql = wsql||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, prevresc.BDREFRESCISAOPREV, COLCON.BDBFGTSFTPR, '||
                'COLCON.BDFGTSFTPR, COLCON.BDFGTSCSFTPR, COLCON.BDBFGTS13FTPR, COLCON.BDFGTS13FTPR, '||
                'COLCON.BDFGTS13CSFTPR,COLCON.BDMAIORREMFTPR, '||
                'case when coalesce(colcon.bdbaseinssnmvnovo, 0) <> 0 then colcon.bdbaseinssnmvnovo else COLCON.BDBINSSFTPR end BDBINSSFTPR, '||
                'COLCON.BDALIQINSSFTPR, COLCON.BDINSSFTPR, COLCON.BDBIRRFFTPR, COLCON.BDALIQIRRFFTPR, COLCON.BDIRRFFTPR, '||
                'case when coalesce(colcon.bdbaseinss13mvnovo, 0) <> 0 then colcon.bdbaseinss13mvnovo else COLCON.BDBINSS13FTPR end BDBINSS13FTPR, '||
                'COLCON.BDALIQINSS13FTPR, COLCON.BDINSS13FTPR, '||
                'COLCON.BDBIRRF13FTPR, COLCON.BDALIQIRRF13FTPR, COLCON.BDIRRF13FTPR, COLCON.BDBSALFAMFTPR, '||
                'COLCON.BDSALFAMFTPR, COLCON.BDBRAISFTPR, COLCON.BDSALBASEFTPR, '||
                'COLCON.BDDEPFTPR, COLCON.BDBASEPISFTPR, COLCON.BDBASEPISFEFTPR, COLCON.BDBASEPIS13FTPR, COLCON.BDBSALMATEMPFTPR, '||
                'COLCON.BDSALMATEMPFTPR, COLCON.BDBRATAPOFTPR,COLCON.BDBRATAPOFEFTPR, COLCON.BDBRATAPO13FTPR, '||
                'COLCON.BDBINSSFEFOLFTPR, COLCON.BDINSSFEFOLFTPR, COLCON.BDALIQINSSFEFOLFTPR, '||
                'pf.bdCodCentro, pf.bdCODTPCC, '||
                'colcon.bdCreditoFTPR, colcon.bdDebitoFTPR, '||
                'colcon.bdBFGTSFEFTPR, COLCON.BDFGTSFEFTPR, '||
                '0 BDBSALMATEMPFNFTPR,0 BDBSALMATEMP13FTPR,0 BDVSALMATEMPFNFTPR,0 BDVSALMATEMP13FTPR, COLCON.bdliquidoFTPR, CAST(null as DATE) BDDATAPGTOFTPR, '||
                'COLCON.BDBINSSAPFTPR, COLCON.BDINSSAPFTPR, COLCON.BDBINSS13APFTPR, COLCON.BDINSS13APFTPR '||
              'from vrhf_emp_tfoltom_prev_resc COLCON '||
              'join vrh_emp_trescisao_previa prevresc on (prevresc.bdcodemp = COLCON.BDCODEMP and prevresc.bdcodcol = COLCON.BDCODCOL) '||
              'join tempresas emp on (emp.bdcodemp = COLCON.BDCODEMP) '||
              'join vrhf_emp_tprepfn pf on (pf.bdcodemp = COLCON.BDCODEMP and pf.BDCODCOL = COLCON.BDCODCOL and pf.bdordem = COLCON.BDORDEM) '||
              'left outer join VW_VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = COLCON.BDCODEMP and X.BDCODCOL = COLCON.BDCODCOL) '||
              'left outer join VRH_BASE_TCLASSE f on (f.bdcodcla = X.BDCODCLA) '||
              wwheret||')  COLCON ';

       if (coalesce(prcodtpcc, '') <> '') then
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||'group by COLCON.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,colcon.BDREFRESCISAOPREV,COLCON.bdCodCentro, COLCON.bdCODTPCC ';
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 1)) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFRESCISAOPREV, cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFTPR),'||
                'sum(COLCON.BDFGTSFTPR), sum(COLCON.BDFGTSCSFTPR), sum(COLCON.BDBFGTS13FTPR), sum(COLCON.BDFGTS13FTPR),'||
                'sum(COLCON.BDFGTS13CSFTPR),sum(COLCON.BDMAIORREMFTPR), sum(COLCON.BDBINSSFTPR), max(COLCON.BDALIQINSSFTPR),'||
                'sum(COLCON.BDINSSFTPR), sum(COLCON.BDBIRRFFTPR), max(COLCON.BDALIQIRRFFTPR), sum(COLCON.BDIRRFFTPR),'||
                'sum(COLCON.BDBINSS13FTPR), max(COLCON.BDALIQINSS13FTPR), sum(COLCON.BDINSS13FTPR),'||
                'sum(COLCON.BDBIRRF13FTPR), max(COLCON.BDALIQIRRF13FTPR), sum(COLCON.BDIRRF13FTPR), sum(COLCON.BDBSALFAMFTPR),'||
                'sum(COLCON.BDSALFAMFTPR), sum(COLCON.BDBRAISFTPR), max(COLCON.BDSALBASEFTPR),'||
                'sum(COLCON.BDDEPFTPR), sum(COLCON.BDBASEPISFTPR), sum(COLCON.BDBASEPISFEFTPR), sum(COLCON.BDBASEPIS13FTPR), sum(COLCON.BDBSALMATEMPFTPR),'||
                'sum(COLCON.BDSALMATEMPFTPR), sum(COLCON.BDBRATAPOFTPR), sum(COLCON.BDBRATAPOFEFTPR), sum(COLCON.BDBRATAPO13FTPR),'||
                'sum(COLCON.BDBINSSFEFOLFTPR), sum(COLCON.BDINSSFEFOLFTPR), max(COLCON.BDALIQINSSFEFOLFTPR),'||
                'cast(null as integer), cast(null as integer),'||
                'sum(colcon.bdCreditoFTPR), sum(colcon.bdDebitoFTPR),'||
                'sum(colcon.bdBFGTSFEFTPR), sum(COLCON.BDFGTSFEFTPR),'||
                'sum(colcon.BDBSALMATEMPFNFTPR),sum(colcon.BDBSALMATEMP13FTPR),sum(colcon.BDVSALMATEMPFNFTPR),sum(colcon.BDVSALMATEMP13FTPR),sum(COLCON.bdliquidoFTPR), MAX(COLCON.BDDATAPGTOFTPR), '||
                'sum(COLCON.BDBINSSAPFTPR), sum(COLCON.BDINSSAPFTPR), sum(COLCON.BDBINSS13APFTPR), sum(COLCON.BDINSS13APFTPR) '||
              'from (';

       wsql = wsql||
              'select '||
                'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, prevresc.BDREFRESCISAOPREV, COLCON.BDBFGTSFTPR, '||
                'COLCON.BDFGTSFTPR, COLCON.BDFGTSCSFTPR, COLCON.BDBFGTS13FTPR, COLCON.BDFGTS13FTPR, '||
                'COLCON.BDFGTS13CSFTPR,COLCON.BDMAIORREMFTPR, '||
                'case when coalesce(colcon.bdbaseinssnmvnovo, 0) <> 0 then colcon.bdbaseinssnmvnovo else COLCON.BDBINSSFTPR end BDBINSSFTPR, '||
                'COLCON.BDALIQINSSFTPR, COLCON.BDINSSFTPR, COLCON.BDBIRRFFTPR, COLCON.BDALIQIRRFFTPR, COLCON.BDIRRFFTPR, '||
                'case when coalesce(colcon.bdbaseinss13mvnovo, 0) <> 0 then colcon.bdbaseinss13mvnovo else COLCON.BDBINSS13FTPR end BDBINSS13FTPR, '||
                'COLCON.BDALIQINSS13FTPR, COLCON.BDINSS13FTPR, '||
                'COLCON.BDBIRRF13FTPR, COLCON.BDALIQIRRF13FTPR, COLCON.BDIRRF13FTPR, COLCON.BDBSALFAMFTPR, '||
                'COLCON.BDSALFAMFTPR, COLCON.BDBRAISFTPR, COLCON.BDSALBASEFTPR, '||
                'COLCON.BDDEPFTPR, COLCON.BDBASEPISFTPR, COLCON.BDBASEPISFEFTPR, COLCON.BDBASEPIS13FTPR, COLCON.BDBSALMATEMPFTPR, '||
                'COLCON.BDSALMATEMPFTPR, COLCON.BDBRATAPOFTPR, COLCON.BDBRATAPOFEFTPR, COLCON.BDBRATAPO13FTPR, '||
                'COLCON.BDBINSSFEFOLFTPR, COLCON.BDINSSFEFOLFTPR, COLCON.BDALIQINSSFEFOLFTPR, '||
                'colcon.bdCreditoFTPR, colcon.bdDebitoFTPR, '||
                'colcon.bdBFGTSFEFTPR, COLCON.BDFGTSFEFTPR, '||
                '0 BDBSALMATEMPFNFTPR,0 BDBSALMATEMP13FTPR,0 BDVSALMATEMPFNFTPR, 0 BDVSALMATEMP13FTPR, '||
                'pf.BDCODCENTRO, pf.BDCODTPCC, COLCON.bdliquidoFTPR, CAST(null as DATE) BDDATAPGTOFTPR, '||
                'COLCON.BDBINSSAPFTPR, COLCON.BDINSSAPFTPR, COLCON.BDBINSS13APFTPR, COLCON.BDINSS13APFTPR '||
              'from vrhf_emp_tfoltom_prev_resc COLCON '||
              'join vrh_emp_trescisao_previa prevresc on (prevresc.bdcodemp = COLCON.BDCODEMP and prevresc.BDCODCOL = COLCON.BDCODCOL) '||
              'join tempresas emp on (emp.bdcodemp = COLCON.BDCODEMP) '||
              'join vrhf_emp_tprepfn pf on (pf.bdcodemp = COLCON.BDCODEMP and pf.bdcodcol = COLCON.BDCODCOL and pf.bdordem = COLCON.BDORDEM) '||
              'left outer join VW_VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = COLCON.BDCODEMP and X.BDCODCOL = COLCON.BDCODCOL) '||
              'left outer join VRH_BASE_TCLASSE f on (f.bdcodcla = X.BDCODCLA) '||
              wwheret||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by COLCON.bdgrupocla,colcon.bdcodemp,colcon.bdcodcol,colcon.BDREFRESCISAOPREV ';
     END
  ELSE
     BEGIN
       wsql = 'select '||
                'COLCON.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFRESCISAOPREV, COLCON.BDORDEM, COLCON.BDDATABAIXAFTPR, COLCON.BDBFGTSFTPR, COLCON.BDFGTSFTPR, COLCON.BDFGTSCSFTPR, '||
                'COLCON.BDBFGTS13FTPR, COLCON.BDFGTS13FTPR, COLCON.BDFGTS13CSFTPR, '||
                'COLCON.BDMAIORREMFTPR, COLCON.BDBINSSFTPR, COLCON.BDALIQINSSFTPR, COLCON.BDINSSFTPR, COLCON.BDBIRRFFTPR, COLCON.BDALIQIRRFFTPR, COLCON.BDIRRFFTPR, COLCON.BDBINSS13FTPR, '||
                'COLCON.BDALIQINSS13FTPR, COLCON.BDINSS13FTPR, '||
                'COLCON.BDBIRRF13FTPR, COLCON.BDALIQIRRF13FTPR, COLCON.BDIRRF13FTPR, COLCON.BDBSALFAMFTPR, COLCON.BDSALFAMFTPR, COLCON.BDBRAISFTPR, COLCON.BDSALBASEFTPR, COLCON.BDDEPFTPR, '||
                'COLCON.BDBASEPISFTPR, COLCON.BDBASEPISFEFTPR, COLCON.BDBASEPIS13FTPR, COLCON.BDBSALMATEMPFTPR, '||
                'COLCON.BDSALMATEMPFTPR, COLCON.BDBRATAPOFTPR, COLCON.BDBRATAPOFEFTPR, COLCON.BDBRATAPO13FTPR, '||
                'COLCON.BDBINSSFEFOLFTPR, COLCON.BDINSSFEFOLFTPR, COLCON.BDALIQINSSFEFOLFTPR, COLCON.bdCodCentro, COLCON.bdCODTPCC, '||
                'colcon.bdCreditoFTPR, colcon.bdDebitoFTPR, '||
                'colcon.bdBFGTSFEFTPR, COLCON.BDFGTSFEFTPR, '||
                'colcon.BDBSALMATEMPFNFTPR,colcon.BDBSALMATEMP13FTPR,colcon.BDVSALMATEMPFNFTPR,colcon.BDVSALMATEMP13FTPR, COLCON.bdliquidoFTPR, COLCON.BDDATAPGTOFTPR, '||
                'COLCON.BDBINSSAPFTPR, COLCON.BDINSSAPFTPR, COLCON.BDBINSS13APFTPR, COLCON.BDINSS13APFTPR '||
              'from ( ';

          wsql = wsql||'select '||
                 'f.bdgrupocla, COLCON.BDCODEMP, COLCON.BDCODCOL, prevresc.BDREFRESCISAOPREV, COLCON.BDORDEM, COLCON.BDDATABAIXAFTPR, COLCON.BDBFGTSFTPR, COLCON.BDFGTSFTPR, COLCON.BDFGTSCSFTPR, COLCON.BDBFGTS13FTPR, COLCON.BDFGTS13FTPR, COLCON.BDFGTS13CSFTPR,'||
                 'COLCON.BDMAIORREMFTPR, '||
                 'case when coalesce(colcon.bdbaseinssnmvnovo, 0) <> 0 then colcon.bdbaseinssnmvnovo else COLCON.BDBINSSFTPR end BDBINSSFTPR, '||
                 'COLCON.BDALIQINSSFTPR, COLCON.BDINSSFTPR, COLCON.BDBIRRFFTPR, COLCON.BDALIQIRRFFTPR, COLCON.BDIRRFFTPR, '||
                 'case when coalesce(colcon.bdbaseinss13mvnovo, 0) <> 0 then colcon.bdbaseinss13mvnovo else COLCON.BDBINSS13FTPR end BDBINSS13FTPR, '||
                 'COLCON.BDALIQINSS13FTPR, COLCON.BDINSS13FTPR,'||
                 'COLCON.BDBIRRF13FTPR, COLCON.BDALIQIRRF13FTPR, COLCON.BDIRRF13FTPR, COLCON.BDBSALFAMFTPR, COLCON.BDSALFAMFTPR, COLCON.BDBRAISFTPR, COLCON.BDSALBASEFTPR, COLCON.BDDEPFTPR, '||
                 'COLCON.BDBASEPISFTPR, COLCON.BDBASEPISFEFTPR, COLCON.BDBASEPIS13FTPR, COLCON.BDBSALMATEMPFTPR,'||
                 'COLCON.BDSALMATEMPFTPR, COLCON.BDBRATAPOFTPR, COLCON.BDBRATAPOFEFTPR, COLCON.BDBRATAPO13FTPR,'||
                 'COLCON.BDBINSSFEFOLFTPR, COLCON.BDINSSFEFOLFTPR, COLCON.BDALIQINSSFEFOLFTPR, pf.bdCodCentro, pf.bdCODTPCC,'||
                 'colcon.bdCreditoFTPR, colcon.bdDebitoFTPR,'||
                 'colcon.bdBFGTSFEFTPR, COLCON.BDFGTSFEFTPR, '||
                 '0 BDBSALMATEMPFNFTPR,0 BDBSALMATEMP13FTPR,0 BDVSALMATEMPFNFTPR,0 BDVSALMATEMP13FTPR, COLCON.bdliquidoFTPR, CAST(null as DATE) BDDATAPGTOFTPR, '||
                 'COLCON.BDBINSSAPFTPR, COLCON.BDINSSAPFTPR, COLCON.BDBINSS13APFTPR, COLCON.BDINSS13APFTPR '||
                 'from vrhf_emp_tfoltom_prev_resc COLCON '||
                 'join vrh_emp_trescisao_previa prevresc on (prevresc.bdcodemp = COLCON.BDCODEMP and prevresc.bdcodcol = COLCON.BDCODCOL) '||
                 'join tempresas emp on (emp.bdcodemp = COLCON.BDCODEMP) '||
                 'join vrhf_emp_tprepfn pf on (pf.bdcodemp = COLCON.BDCODEMP and pf.bdcodcol = COLCON.BDCODCOL and pf.bdordem = COLCON.BDORDEM) '||
                 'left outer join VW_VRH_EMP_TCOLCON_VINC X on (X.BDCODEMP = COLCON.BDCODEMP and X.BDCODCOL = COLCON.BDCODCOL) '||
                 'left outer join VRH_BASE_TCLASSE f on (f.bdcodcla = X.BDCODCLA) '||
                 wwheret||') COLCON ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;
     END

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdgrupocla,
    :bdcodemp, --BDCODEMP,
    :bdcodcol, -- BDCODCOL,
    :bdreffn, -- BDREFTOMADOR,
    :bdordem, -- BDORDEM,
    :bddatabaixafn, -- BDDATABAIXAFT,
    :bdbfgtsfn, -- BDBFGTSFT,
    :bdfgtsfn, -- BDFGTSFT,
    :bdfgtscsfn, -- BDFGTSCSFT,
    :bdbfgts13fn, --- BDBFGTS13FT,
    :bdfgts13fn, -- BDFGTS13FT,
    :bdfgts13csfn, -- BDFGTS13CSFT,'||
    :bdmaiorremfn, -- 'BDMAIORREMFT,
    :bdbinssfn, -- BDBINSSFT,
    :bdaliqinssfn, -- BDALIQINSSFT,
    :bdinssfn, -- BDINSSFT,
    :bdbirrffn, -- BDBIRRFFT,
    :bdaliqirrffn, -- BDALIQIRRFFT,
    :bdirrffn, -- BDIRRFFT,
    :bdbinss13fn, -- BDBINSS13FT,
    :bdaliqinss13fn, -- BDALIQINSS13FT,
    :bdinss13fn, -- BDINSS13FT,'||
    :bdbirrf13fn, -- 'BDBIRRF13FT,
    :bdaliqirrf13fn, -- BDALIQIRRF13FT,
    :bdirrf13fn, -- BDIRRF13FT,
    :bdbsalfamfn, -- BDBSALFAMFT,
    :bdsalfamfn, --BDSALFAMFT,
    :bdbraisfn, -- BDBRAISFT,
    :bdsalbasefn, -- BDSALBASEFT,
    :bddepfn, -- BDDEPFT,
    :bdbasepisfn, -- BDBASEPISFT,
    :bdbasepisFEfn, -- BDBASEPISFEFT,
    :bdbasepis13fn, -- BDBASEPIS13FT,
    :bdbsalmatempfn, -- BDBSALMATEMPFT,'||
    :bdsalmatempfn, -- 'BDSALMATEMPFT,
    :bdbratapofn, -- BDBRATAPOFT,
    :bdbratapoFEfn, -- BDBRATAPOFEFT,
    :bdbratapo13fn, -- BDBRATAPO13FT,
    :bdbinssfefolfn, -- BDBINSSFEFOLFT,
    :bdinssfefolfn, -- BDALIQINSSFEFOLFT'||
    :bdaliqinssfefolfn, -- BDINSSFEFOLFT,
    :bdCodCentro, -- bdCodCentro
    :bdCODTPCC, -- BDCODTPCC
    :bdcreditofn,
    :bddebitofn,
    :bdBFGTSFEFN,
    :BDFGTSFEFN,
    :BDBMATEMPFNFN,
    :BDBMATEMP13FN,
    :BDVMATEMPFNFN,
    :BDVMATEMP13FN,
    :BDLIQUIDOFN,
    :BDDATAPGTO,
    :BDBINSSAPFN,
    :BDINSSAPFN,
    :BDBINSS13APFN,
    :BDINSS13APFN
  DO
    BEGIN
      bdcalctomador = 'True';
      SUSPEND;
    END
END^

/* Restore proc. body: VRHF_SP_TFOLHACOMP */
create or alter procedure VRHF_SP_TFOLHACOMP (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(28000),
    PRREFINICOMP integer,
    PRREFFIMCOMP integer,
    PRREFINIPAG integer,
    PRREFFIMPAG integer,
    PRAGRUPATOMADOR integer,
    PRTIPOFC integer = 0,
    PRSEPARCALC integer = 0,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(772) = null,
    PRINSSPATRONAL smallint = 0,
    PRCOMPLEESOCIAL integer = 0,
    PRTIPOREL integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDREFFN integer,
    BDREFFC integer,
    BDREFCOMP integer,
    BDDATAPAGFC date,
    BDDATABAIXAFC date,
    BDBFGTSFC numeric(15,6),
    BDFGTSFC numeric(15,6),
    BDFGTSCSFC numeric(15,6),
    BDBFGTS13FC numeric(15,6),
    BDFGTS13FC numeric(15,6),
    BDFGTS13CSFC numeric(15,6),
    BDMAIORREMFC numeric(15,6),
    BDBINSSFC numeric(15,6),
    BDALIQINSSFC numeric(15,6),
    BDINSSFC numeric(15,6),
    BDBIRRFFC numeric(15,6),
    BDALIQIRRFFC numeric(15,6),
    BDIRRFFC numeric(15,6),
    BDBINSS13FC numeric(15,6),
    BDALIQINSS13FC numeric(15,6),
    BDINSS13FC numeric(15,6),
    BDBIRRF13FC numeric(15,6),
    BDALIQIRRF13FC numeric(15,6),
    BDIRRF13FC numeric(15,6),
    BDBSALFAMFC numeric(15,6),
    BDSALFAMFC numeric(15,6),
    BDBRAISFC numeric(15,6),
    BDSALBASEFC numeric(15,6),
    BDDEPFC numeric(15,6),
    BDBASEPISFC numeric(15,6),
    BDBASEPISFEFC numeric(15,6),
    BDBASEPIS13FC numeric(15,6),
    BDBSALMATEMPFC numeric(15,6),
    BDSALMATEMPFC numeric(15,6),
    BDBRATAPOFC numeric(15,6),
    BDBRATAPOFEFC numeric(15,6),
    BDBRATAPO13FC numeric(15,6),
    BDBINSSFEFOLFC numeric(15,6),
    BDINSSFEFOLFC numeric(15,6),
    BDALIQINSSFEFOLFC numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDBFGTSFEFC numeric(15,6),
    BDFGTSFEFC numeric(15,6),
    BDCODTIPOFC integer,
    BDBINSSMVFC numeric(18,6),
    BDBINSSMV13FC numeric(18,6),
    BDINSSMVFC numeric(18,6),
    BDINSSMV13FC numeric(18,6),
    BDBINSSAPFC numeric(18,6),
    BDBINSS13APFC numeric(18,6),
    BDINSSAPFC numeric(18,6),
    BDINSS13APFC numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDINSSFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDLIQUIDOFC numeric(18,6),
    BDDATAGRRF date,
    BDCODCONTTI integer,
    BDREFVINCFN integer,
    BDSALFAM13GPS numeric(18,6),
    BDSALFAMFNGPS numeric(18,6),
    BDDTACCONV date,
    BDTIPOEVT integer,
    BDIDDEMONSTRATIVO varchar(100),
    BDDTPGTOBRICONV date,
    BDCODACCONV integer,
    BDBFGTSMESANT numeric(18,2),
    BDFGTSMESANT numeric(18,2),
    BDBFGTSMESPOST numeric(18,2),
    BDFGTSMESPOST numeric(18,2),
    BDBFGTSMES numeric(18,2),
    BDFGTSMES numeric(18,2),
    BDFGTSMES13 numeric(18,2),
    BDSALDO numeric(18,2),
    BDFGTS40 numeric(18,2),
    BDFGTS10 numeric(18,2),
    BDTOTALGRRF numeric(18,2),
    BDTEMGRRF integer,
    BDFGTSIND numeric(18,2),
    BDPERCMULTA10 numeric(18,2),
    BDPERCMULTA40 numeric(18,2),
    BDBFGTSMESSEFIP numeric(18,2),
    BDFGTSMESSEFIP numeric(18,2),
    BDTOTAL numeric(18,2),
    BDFGTS13 numeric(18,2),
    BDSALDOTOTAL numeric(18,2))
as
declare variable WDATAPAG varchar(50);
declare variable WORDEMDATAPAG varchar(50);
declare variable WSQL varchar(32700);
declare variable WWHEREN varchar(32700);
declare variable WSQLCC varchar(32700);
declare variable WVALVFC numeric(18,6);
declare variable WTIPOCODVER integer;
declare variable WINSSVER integer;
declare variable WBASEGPSVER DM_BOOLEAN;
declare variable WCODVER integer;
declare variable WCLAVER varchar(20);
declare variable WSQLVERBAS varchar(5000);
declare variable WTEMBENEFICIO integer;
declare variable WFILTROADC varchar(100);
declare variable WDATARESCISAO date;
declare variable WCALCFGTSMESANT boolean;
declare variable WDATAPAGGRFC date;
declare variable WSQLAUXDAT varchar(32700);
declare variable WAAAAMM varchar(10);
declare variable WDATAAUX date;
BEGIN
  /* pragrupatomador
     0 = Nao agrupa
     1 = Agrupa por referencia
     2 = Agrupo por referencia e centro/Tomador
     3 = Agrupa por referencia e Tomador (se nao for tomador verifica pela classificacao e nao encontrando considera empresa)
     4 = Agrupa por referencia e Tipo Tomador (so vai criar mais registros pra empresa se for tomador 155)
     5 = Agrupa por calculo
     6 = Agrupar por data do pagamento
  */

  prpuxafiliais   = coalesce(prpuxafiliais, 0); pragrupatomador = coalesce(pragrupatomador, 0); prseparcalc     = coalesce(prseparcalc, 0);

  WFILTROADC = ' ADC.BDDTPGTOBRICONV ';
  if (PRTIPOREL = 1) then WFILTROADC = ' COLCON.BDDATAPAGFC '; -- Utilizado no relatório liquido da folha, onde deve olhar pra data do pagamento informado na tela do calculo (BDDATAPAGFC) e não da apuração de impostos do ADC(BDDTPGTOBRICONV).

  IF (prpuxafiliais = 1) THEN
    begin
      if (coalesce(prcodemp, '') <> '') then
        begin
          prcodemp = upper(prcodemp);
     
          if ((prfiliais is not null) and (prfiliais <> '')) then
            begin
              wwheren = replace(prcodemp,'COLCON.BDCODEMP','EMP.BDCODMATRIZ');
              prcodemp = '('||prcodemp||' or (('||wwheren||') and (emp.bdcodemp in ('||prfiliais||'))))';
            end
          else prcodemp = replace(prcodemp,'COLCON.BDCODEMP','coalesce(emp.bdcodmatriz,emp.bdcodemp)');
        end
    end

  wsql = 'select COLCON.bdcodemp, COLCON.BDCODEMP,COLCON.BDCODCOL,COLCON.BDREFFN, COLCON.BDREFCOMP,COLCON.BDDATAPAGFC,COLCON.BDDATABAIXAFC,COLCON.BDBFGTSFC,'||
  ' COLCON.BDFGTSFC,COLCON.BDFGTSCSFC,COLCON.BDBFGTS13FC,COLCON.BDFGTS13FC,COLCON.BDFGTS13CSFC,COLCON.BDMAIORREMFC,COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, COLCON.BDINSSFC,COLCON.BDBIRRFFC,COLCON.BDALIQIRRFFC,COLCON.BDIRRFFC,COLCON.BDBINSS13FC,COLCON.BDALIQINSS13FC,'||
  ' COLCON.BDINSS13FC,COLCON.BDBIRRF13FC,COLCON.BDALIQIRRF13FC,COLCON.BDIRRF13FC,COLCON.BDBSALFAMFC, COLCON.BDSALFAMFC,COLCON.BDBRAISFC,COLCON.BDSALBASEFC,COLCON.BDDEPFC,COLCON.BDBASEPISFC,COLCON.BDBASEPISFEFC,'||
  ' COLCON.BDBASEPIS13FC,COLCON.BDBSALMATEMPFC,COLCON.BDSALMATEMPFC,COLCON.BDBRATAPOFC,COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC,COLCON.BDBINSSFEFOLFC,COLCON.BDINSSFEFOLFC,COLCON.BDALIQINSSFEFOLFC,COLCON.BDCREDITOFC,COLCON.BDDEBITOFC,'||
  ' COLCON.bdbfgtsfefc,COLCON.bdfgtsfefc,COLCON.BDREFFC,COLCON.BDCODTIPOFC, COLCON.BDBINSSMVFC,COLCON.BDBINSSMV13FC,COLCON.BDINSSMVFC,COLCON.BDINSSMV13FC,COLCON.BDBINSSAPFC,COLCON.BDBINSS13APFC, '||
  ' COLCON.BDINSSAPFC,COLCON.BDINSS13APFC,FOLN.BDBINSSFN,FOLN.BDINSSFN,FOLN.BDBINSS13FN,FOLN.BDINSS13FN,FOLN.BDBINSSAPFN, FOLN.BDBINSS13APFN,FOLN.BDINSSAPFN,FOLN.BDINSS13APFN,COLCON.BDLIQUIDO,COLCON.BDDATAGRRFFC,cast(null as INTEGER) BDCODCONTTI, '||
  ' COLCON.BDREFVINCFN, ADC.BDDTACCONV,COLCON.BDTIPOEVT,COLCON.BDIDDEMONSTRATIVO, ADC.BDDTPGTOBRICONV, ADC.BDCODACCONV, RESC.BDDATAPAGRESCISAO, RESC.BDCALCFGTSMESANT, RESC.BDDATAPAGGRFC '||
  ' from VRHF_EMP_TFOLHACOMP COLCON'||
  ' join TEMPRESAS emp on (colcon.bdcodemp = emp.bdcodemp) '||
  ' join VRHF_EMP_TFOLHANORMAL FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFFN = COLCON.BDREFFN) '||
  ' left outer join vrh_emp_trescisao resc on (COLCON.BDCODEMP = resc.BDCODEMP and COLCON.BDCODCOL = resc.BDCODCOL) ' ||
  ' left outer join VRH_EMP_TACCONV ADC on (ADC.bdcodemp = COLCON.bdcodemp) and (adc.bdcodacconv = COLCON.bdcodacconv)';
                                                                                                                                                                 
  wwheren = '';
  IF (coalesce(prcodemp, '') <> '') THEN
     begin
       if (wwheren <> '') then wwheren = wwheren||' and ';
       else wwheren = wwheren||' where ';

       wwheren = wwheren||prcodemp;
     end

  if (coalesce(prcodcol, '') <> '') then
     begin
       if (wwheren <> '') then wwheren = wwheren||' and ';
       else wwheren = wwheren||' where ';

       wwheren = wwheren||prcodcol;
     end

  if (((prrefinicomp is not null) and (prreffimcomp is not null)) and ((prrefinicomp <> 0) and (prreffimcomp <> 0))) then
     begin
       if (wwheren <> '') then wwheren = wwheren||' and ';
       else wwheren = wwheren||' where ';

       wwheren = wwheren||'COLCON.BDREFFN >= '||prrefinicomp||' and '||'COLCON.BDREFFN <= '||prreffimcomp;
     end
  else
     begin
       if ((prrefinicomp is not null) and (prrefinicomp <> 0)) then
          begin
            if (wwheren <> '') then wwheren = wwheren||' and ';
            else wwheren = wwheren||' where ';

            wwheren = wwheren||'COLCON.BDREFFN = '||prrefinicomp;
          end
       else
          begin
            if ((prreffimcomp is not null) and (prreffimcomp <> 0)) then
               begin
                 if (wwheren <> '') then wwheren = wwheren||' and ';
                 else wwheren = wwheren||' where ';

                 wwheren = wwheren||'COLCON.BDREFFN = '||prreffimcomp;
               end
          end
     end

  if ((prrefinipag is not null) and (prrefinipag <> 0) and (prreffimpag is not null) and (prreffimpag <> 0)) then
     begin
       if (wwheren <> '') then wwheren = wwheren||' and ';
       else wwheren = wwheren||' where ';

       if (PRCOMPLEESOCIAL = 1) then
         begin
           wwheren = wwheren||'((COLCON.BDCODTIPOFC <> 3 AND COLCON.BDREFFN = '||prrefinipag||') OR ';
           wwheren = wwheren||' (COLCON.BDCODACCONV IS NOT NULL AND COLCON.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM('||WFILTROADC||')) >= ' ||prrefinipag||' and (SELECT * FROM AAAAMM('||WFILTROADC||')) <= '||prreffimpag||'))';
         END
       ELSE
         BEGIN
           wwheren = wwheren||'((COLCON.BDCODTIPOFC <> 3 AND COLCON.BDREFCOMP >= '||prrefinipag||' and COLCON.BDREFCOMP <= '||prreffimpag||') OR ';
           wwheren = wwheren||' (COLCON.BDCODACCONV IS NOT NULL AND COLCON.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM('||WFILTROADC||')) >= ' ||prrefinipag||' and (SELECT * FROM AAAAMM('||WFILTROADC||')) <= '||prreffimpag||'))';

         END
     end
  else
     begin
       if (prrefinipag is not null and prrefinipag <> 0) then
          begin
            if (wwheren <> '') then wwheren = wwheren||' and ';
            else wwheren = wwheren||' where ';

            wwheren = wwheren||'((COLCON.BDCODTIPOFC <> 3 AND COLCON.BDREFCOMP = '||prrefinipag||') OR';
            wwheren = wwheren||' (COLCON.BDCODACCONV IS NOT NULL AND COLCON.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM('||WFILTROADC||')) = ' ||prrefinipag||'))';
          end
       else
          begin
            if (prreffimpag is not null and prreffimpag <> 0) then
               begin
                 if (wwheren <> '') then wwheren = wwheren||' and ';
                 else wwheren = wwheren||' where ';

                 wwheren = wwheren||'((COLCON.BDCODTIPOFC <> 3 AND COLCON.BDREFCOMP = '||prreffimpag||') OR';
                 wwheren = wwheren||' (COLCON.BDCODACCONV IS NOT NULL AND COLCON.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM('||WFILTROADC||')) = ' ||prreffimpag||'))';
               end
          end
     end

  if (prtipofc > 0) then
     begin
       if (wwheren <> '') then wwheren = wwheren||' and ';
       else wwheren = wwheren||' where ';

       wwheren = wwheren||'coalesce(COLCON.BDCODTIPOFC,1) = '||prtipofc;
     end

  wsql = wsql||wwheren;
  if (pragrupatomador = 6) then
     begin
       wsql = 'select  COLCON.BDCODEMP, COLCON.BDCODEMP, COLCON.BDCODCOL,  max(COLCON.BDREFFN), max(COLCON.BDREFCOMP), COLCON.BDDATAPAGFC, max(COLCON.BDDATABAIXAFC),  sum(COLCON.BDBFGTSFC), sum(COLCON.BDFGTSFC),'||
       'sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), sum(COLCON.BDINSSFC),'||
       'sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC),'||
       'sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC),'||
       'sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC), sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC),'||
       'max(COLCON.BDALIQINSSFEFOLFC), sum(COLCON.BDCREDITOFC), sum(COLCON.BDDEBITOFC), sum(COLCON.BDBFGTSFEFC), sum(COLCON.BDFGTSFEFC), max(COLCON.BDREFFC),'||
       'max(COLCON.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), sum(COLCON.BDBINSSAPFC), sum(COLCON.BDBINSS13APFC), sum(COLCON.BDINSSAPFC),'||
       'sum(COLCON.BDINSS13APFC), sum(FOLN.BDBINSSFN), sum(FOLN.BDINSSFN), sum(FOLN.BDBINSS13FN), sum( FOLN.BDINSS13FN), sum(FOLN.BDBINSSAPFN), sum(FOLN.BDBINSS13APFN), sum(FOLN.BDINSSAPFN),'||
       'sum(FOLN.BDINSS13APFN), sum(COLCON.BDLIQUIDO), max(COLCON.BDDATAGRRFFC), cast(null as integer) BDCODCONTTI, max(COLCON.BDREFVINCFN), ADC.BDDTACCONV, max(COLCON.BDTIPOEVT),max(COLCON.BDIDDEMONSTRATIVO), '||
       'MAX(ADC.BDDTPGTOBRICONV), MAX(COLCON.BDCODACCONV), RESC.BDDATAPAGRESCISAO, RESC.BDCALCFGTSMESANT, RESC.BDDATAPAGGRFC '||
       'from VRHF_EMP_TFOLHACOMP COLCON'||
       ' join TEMPRESAS EMP on (COLCON.BDCODEMP = EMP.BDCODEMP)'||
       ' join VRHF_EMP_TFOLHANORMAL FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFFN = COLCON.BDREFFN) '||
       ' left outer join vrh_emp_trescisao resc on (COLCON.BDCODEMP = resc.BDCODEMP and COLCON.BDCODCOL = resc.BDCODCOL) ' ||
       ' left outer join VRH_EMP_TACCONV ADC on (ADC.bdcodemp = COLCON.bdcodemp) and (adc.bdcodacconv = COLCON.bdcodacconv)';
       wsql = wsql||wwheren;
       wsql = wsql||' group by COLCON.BDCODEMP, COLCON.BDCODCOL,BDCODCONTTI, BDDATAPAGFC, ADC.BDDTACCONV,  RESC.BDDATAPAGRESCISAO, RESC.BDCALCFGTSMESANT, RESC.BDDATAPAGGRFC ';
     END
     
  wsql = wsql||' union all ';
  wsql = wsql|| ' select COLCON.bdcodemp, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFFN, COLCON.BDREFCOMP,'||
  ' COLCON.BDDATAPAGFC, COLCON.BDDATABAIXAFC, COLCON.BDBFGTSFC, COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, COLCON.BDFGTS13CSFC,'||
  ' COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, COLCON.BDBINSS13FC,'||
  ' COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC,'||
  ' COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, COLCON.BDSALFAMFC, COLCON.BDBRAISFC, COLCON.BDSALBASEFC, COLCON.BDDEPFC, COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC,'||
  ' COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC, COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC,'||
  ' COLCON.BDALIQINSSFEFOLFC, COLCON.BDCREDITOFC, COLCON.BDDEBITOFC, COLCON.bdbfgtsfefc, COLCON.bdfgtsfefc, COLCON.BDREFFC, COLCON.BDCODTIPOFC, COLCON.BDBINSSMVFC,'||
  ' COLCON.BDBINSSMV13FC,  COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC,  COLCON.BDBINSSAPFC, '||
  ' COLCON.BDBINSS13APFC,  COLCON.BDINSSAPFC,  COLCON.BDINSS13APFC,  FOLN.BDBINSSFN, FOLN.BDINSSFN,  FOLN.BDBINSS13FN,  FOLN.BDINSS13FN,  FOLN.BDBINSSAPFN, '||
  ' FOLN.BDBINSS13APFN,  FOLN.BDINSSAPFN,  FOLN.BDINSS13APFN,  COLCON.BDLIQUIDO, COLCON.BDDATAGRRFFC,  COLCON.BDCODCONTTI,  null as BDREFVINCFN, '||
  ' ADC.BDDTACCONV, COLCON.BDTIPOEVT, COLCON.BDIDDEMONSTRATIVO, ADC.BDDTPGTOBRICONV, COLCON.BDCODACCONV, '||
  ' RESC.BDDATAPAGRESCISAO, RESC.BDCALCFGTSMESANT, RESC.BDDATAPAGGRFC '||
  ' from VRHF_EMP_TFOLHACOMPINT COLCON'||
  ' join TEMPRESAS emp on (colcon.bdcodemp = emp.bdcodemp) '||
  ' join VRHF_EMP_TFOLHAINT FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFFN = COLCON.BDREFFN and FOLN.BDCODCONTTI = COLCON.BDCODCONTTI) '||
  ' left outer join vrh_emp_trescisao resc on (COLCON.BDCODEMP = resc.BDCODEMP and COLCON.BDCODCOL = resc.BDCODCOL) '||
  ' left outer join VRH_EMP_TACCONV ADC on (ADC.bdcodemp = COLCON.bdcodemp) and (adc.bdcodacconv = COLCON.bdcodacconv)';

  wsql = wsql||wwheren;
  prinsspatronal = coalesce(prinsspatronal, 0);

  if ((prcodtpcc is null) or (prcodtpcc = '')) then
     begin
       bdcalctomador = 'FALSE';

       for execute statement wsql
       into
         :bdcodemp, :BDCODEMP, :BDCODCOL, :BDREFFN, :BDREFCOMP, :BDDATAPAGFC, :BDDATABAIXAFC, :BDBFGTSFC, :BDFGTSFC, :BDFGTSCSFC, :BDBFGTS13FC,
         :BDFGTS13FC, :BDFGTS13CSFC, :BDMAIORREMFC, :BDBINSSFC, :BDALIQINSSFC, :BDINSSFC, :BDBIRRFFC, :BDALIQIRRFFC, :BDIRRFFC, :BDBINSS13FC,
         :BDALIQINSS13FC, :BDINSS13FC, :BDBIRRF13FC, :BDALIQIRRF13FC, :BDIRRF13FC, :BDBSALFAMFC, :BDSALFAMFC, :BDBRAISFC, :BDSALBASEFC,
         :BDDEPFC, :BDBASEPISFC, :BDBASEPISFEFC, :BDBASEPIS13FC, :BDBSALMATEMPFC, :BDSALMATEMPFC, :BDBRATAPOFC, :BDBRATAPOFEFC, :BDBRATAPO13FC, :BDBINSSFEFOLFC,
         :BDINSSFEFOLFC, :BDALIQINSSFEFOLFC, :bdcredito, :bddebito, :bdbfgtsfefc, :bdfgtsfefc, :BDREFFC, :BDCODTIPOFC, :BDBINSSMVFC, :BDBINSSMV13FC, :BDINSSMVFC,
         :BDINSSMV13FC, :BDBINSSAPFC, :BDBINSS13APFC, :BDINSSAPFC, :BDINSS13APFC, :BDBINSSFN, :BDINSSFN, :BDBINSS13FN, :BDINSS13FN, :BDBINSSAPFN, :BDBINSS13APFN,
         :BDINSSAPFN, :BDINSS13APFN, :BDLIQUIDOFC, :BDDATAGRRF, :BDCODCONTTI, :BDREFVINCFN, :bddtacconv, :bdtipoevt, :bdiddemonstrativo, :BDDTPGTOBRICONV,
         :bdcodacconv, :wdatarescisao, :wcalcfgtsmesant, :wdatapaggrfc
       do
         begin
           BDSALFAMFNGPS = 0; BDSALFAM13GPS = 0;
           if (prinsspatronal = 1) then
              begin
                if (BDREFFN >= 201508) then BDBINSSFC = 0; BDBINSS13FC = 0; BDBINSSFEFOLFC = 0;
              end

           wtembeneficio = 0;
           if (coalesce(:BDCODCONTTI, 0) > 0) then
              begin
                for select FC.BDCODVER, FC.BDVALVFC
                    from VRHF_EMP_TVERBAFCINT FC
                    where FC.BDCODEMP = :BDCODEMP and FC.BDCODCOL = :BDCODCOL and FC.BDREFFN = :BDREFFN and FC.BDREFFC = :BDREFFC and FC.BDCODCONTTI = :BDCODCONTTI
                into :wcodver, :wvalvfc
                do
                  begin
                    select first 1 VR.BDTIPOCODVER, VR.BDINSSVER, VR.BDBASEGPSVER, V.BDCLAVER
                    from VRH_BASE_TVERBAS_REF VR
                    join VRH_BASE_TVERBAS V on (V.BDCODVER = VR.BDCODVER)
                    where VR.BDCODVER = :wcodver and VR.BDREFVER <= :BDREFFN order by VR.BDREFVER DESC
                    into :wtipocodver, :winssver, :wbasegpsver, :wclaver;
           
                    winssver    = coalesce(winssver, 0); wtipocodver = coalesce(wtipocodver, 0); wbasegpsver = upper(coalesce(wbasegpsver, 'FALSE'));
      
                    if (substring(:wclaver from 1 for 7) in ('8.015.3','8.015.4','8.035.3','8.035.4')) then
                       wtembeneficio = 1;

                    if (wbasegpsver = 'TRUE') then
                       begin
                         if (prinsspatronal = 1 and :BDREFFN >= 201508) then
                            begin
                              if (winssver = 3) then
                                 begin
                                   if (wtipocodver = 0) then BDBINSS13FC = BDBINSS13FC + :wvalvfc;
                                   else if (wtipocodver = 1) then BDBINSS13FC = BDBINSS13FC - :wvalvfc;
                                 end
                              else
                              if (winssver > 0) then
                                 begin
                                   if (wtipocodver = 0) then BDBINSSFC = BDBINSSFC + :wvalvfc;
                                   else if (wtipocodver = 1) then BDBINSSFC = BDBINSSFC - :wvalvfc;
                                 end
                            end
                       end
                    else
                       begin
                         if ((substring(:wclaver from 1 for 5) = '8.005') or  (substring(:wclaver from 1 for 5) = '7.070') or (substring(:wclaver from 1 for 5) = '0.610')) then
                            begin
                              if (winssver = 3) then
                                 begin
                                   if (wtipocodver = 0) then BDSALFAM13GPS = BDSALFAM13GPS + :wvalvfc;
                                   else if (wtipocodver = 1) then BDSALFAM13GPS = BDSALFAM13GPS - :wvalvfc;
                                 end
                              else
                              if (winssver > 0) then
                                 begin
                                   if (wtipocodver = 0) then BDSALFAMFNGPS = BDSALFAMFNGPS + :wvalvfc;
                                   else if (wtipocodver = 1) then BDSALFAMFNGPS = BDSALFAMFNGPS - :wvalvfc;
                                 end
                            end
                       end
                  end
              end
           else
              begin
                for select FC.BDCODVER, FC.BDVALVFC
                    from VRHF_EMP_TVERBAFC FC
                    where FC.BDCODEMP = :BDCODEMP and FC.BDCODCOL = :BDCODCOL and FC.BDREFFN = :BDREFFN and FC.BDREFFC = :BDREFFC
                into :wcodver, :wvalvfc
                do
                  begin
                    select first 1 VR.BDTIPOCODVER, VR.BDINSSVER, VR.BDBASEGPSVER, V.BDCLAVER
                    from VRH_BASE_TVERBAS_REF VR
                    join VRH_BASE_TVERBAS V on (V.BDCODVER = VR.BDCODVER)
                    where VR.BDCODVER = :wcodver and VR.BDREFVER <= :BDREFFN order by VR.BDREFVER DESC
                    into :wtipocodver, :winssver, :wbasegpsver, :wclaver;
      
                    winssver = coalesce(winssver, 0); wtipocodver = coalesce(wtipocodver, 0); wbasegpsver = upper(coalesce(wbasegpsver, 'FALSE'));
      
                    if (substring(:wclaver from 1 for 7) in ('8.015.3','8.015.4','8.035.3','8.035.4')) then wtembeneficio = 1;

                    if (wbasegpsver = 'TRUE') then
                       begin
                         if (prinsspatronal = 1 and :BDREFFN >= 201508) then
                            begin
                              if (winssver = 3) then
                                 begin
                                   if (wtipocodver = 0) then BDBINSS13FC = BDBINSS13FC + :wvalvfc;
                                   else if (wtipocodver = 1) then BDBINSS13FC = BDBINSS13FC - :wvalvfc;
                                 end
                              else
                              if (winssver > 0) then
                                 begin
                                   if (wtipocodver = 0) then BDBINSSFC = BDBINSSFC + :wvalvfc;
                                   else if (wtipocodver = 1) then BDBINSSFC = BDBINSSFC - :wvalvfc;
                                 end
                            end
                       end
                    else
                       begin
                         if ((substring(:wclaver from 1 for 5) = '8.005') or  (substring(:wclaver from 1 for 5) = '7.070') or (substring(:wclaver from 1 for 5) = '0.610')) then
                            begin
                              if (winssver = 3) then
                                 begin
                                   if (wtipocodver = 0) then BDSALFAM13GPS = BDSALFAM13GPS + :wvalvfc;
                                   else if (wtipocodver = 1) then BDSALFAM13GPS = BDSALFAM13GPS - :wvalvfc;
                                 end
                              else
                              if (winssver > 0) then
                                 begin
                                   if (wtipocodver = 0) then BDSALFAMFNGPS = BDSALFAMFNGPS + :wvalvfc;
                                   else if (wtipocodver = 1) then BDSALFAMFNGPS = BDSALFAMFNGPS - :wvalvfc;
                                 end
                            end
                       end
                  end
              end

           if (prinsspatronal = 1) then
              begin
                if (BDREFFN >= 201508) then
                   begin
                     if ((BDBINSSFC < 0) and (wtembeneficio <> 1)) then BDBINSSFC = 0;
                     if (BDBINSS13FC < 0) then BDBINSS13FC = 0;
                   end
              end

           SUSPEND;
         end
     end

  WDATAPAG = 'COLCON.BDDATAPAGFC'; wordemdatapag = '';

  if (prseparcalc = 0) then
     begin
       if (pragrupatomador >= 1 and pragrupatomador <= 6) then
         begin
           WDATAPAG = 'max(colcon.BDDATAPAGFC)'; wordemdatapag = '';
         end
       else WDATAPAG = 'colcon.BDDATAPAGFC';

       wordemdatapag = '';
     end
  else WDATAPAG = 'colcon.BDDATAPAGFC'; wordemdatapag = ', colcon.BDDATAPAGFC';

  wsqlcc = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, cast(null as INTEGER) BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
  'COLCON.BDBFGTSFC, COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, '||
  'COLCON.BDFGTS13CSFC,COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, '||
  'COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, '||
  'COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
  'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, '||
  'COLCON.BDSALFAMFC, COLCON.BDBRAISFC,COLCON.BDSALBASEFC, '||
  'COLCON.BDDEPFC, COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, '||
  'COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC, COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, '||
  'COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, '||
  'colcon.bdcreditofc, colcon.bddebitofc, colcon.bddatapagfc, colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc, '||
  'colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
  'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc, FOLN.bdbinssft, FOLN.bdinssft, FOLN.bdbinss13ft, FOLN.bdinss13ft, '||
  'foln.bdbinssapft, foln.bdbinss13apft, foln.bdinssapft, foln.bdinss13apft, COLCON.BDLIQUIDO, '||
  'case when pf.BDCODTPCC is null then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC, COLCON.BDDATAGRRFFC, COLCON.BDORDEM, COLCON.BDDATABAIXAFC, '||
  'COLCON.BDREFVINCFN, ADC.bddtacconv, COLCON.BDTIPOEVT,COLCON.BDIDDEMONSTRATIVO, ADC.BDDTPGTOBRICONV, COLCON.BDCODACCONV, ' ||
  'RESC.BDDATAPAGRESCISAO, RESC.BDCALCFGTSMESANT, RESC.BDDATAPAGGRFC ';

  if (pragrupatomador in (3, 4)) then wsqlcc = wsqlcc||', case when toma.bdCODTPCC is null then null else pf.bdCodCentro end bdCodCentrotoma, toma.bdCODTPCC bdCODTPCCtoma ';

  wsqlcc = wsqlcc || 'from VRHF_EMP_TFOLTOMCOMP COLCON join TEMPRESAS emp on (colcon.bdcodemp = emp.bdcodemp) '||
  'join VRHF_EMP_TFOLHATOMADOR FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLN.BDORDEM = COLCON.BDORDEM) '||
  'join VRHF_EMP_TPREPFN pf on (pf.BDCODEMP = COLCON.BDCODEMP and pf.BDCODCOL = COLCON.BDCODCOL and pf.BDORDEM = COLCON.BDORDEM) '||
  'left outer join vrh_emp_trescisao resc on (COLCON.BDCODEMP = resc.BDCODEMP and COLCON.BDCODCOL = resc.BDCODCOL) '||
  'left outer join VRH_EMP_TACCONV ADC on (ADC.bdcodemp = COLCON.bdcodemp) and (adc.bdcodacconv = COLCON.bdcodacconv) ';

  if (pragrupatomador = 4) then wsqlcc = wsqlcc||'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro,'||prrefinicomp||') toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) ';
  else if (pragrupatomador = 3) then wsqlcc = wsqlcc||'left outer join VRHF_SP_TOMADOR(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) ';

  wsqlcc = wsqlcc|| replace(upper(wwheren), 'COLCON.BDREFFN', 'COLCON.BDREFTOMADOR');
  wsqlcc = wsqlcc||' union all '||
  'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
  'COLCON.BDBFGTSFC, COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, '||
  'COLCON.BDFGTS13CSFC,COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, '||
  'COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, '||
  'COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
  'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, '||
  'COLCON.BDSALFAMFC, COLCON.BDBRAISFC, COLCON.BDSALBASEFC, '||
  'COLCON.BDDEPFC, COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, '||
  'COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC,COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, '||
  'COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, '||
  'colcon.bdcreditofc, colcon.bddebitofc, colcon.bddatapagfc, colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc, '||
  'colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
  'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc, '||
  'FOLN.bdbinssft, FOLN.bdinssft, FOLN.bdbinss13ft, FOLN.bdinss13ft, '||
  'foln.bdbinssapft, foln.bdbinss13apft, foln.bdinssapft, foln.bdinss13apft, COLCON.BDLIQUIDO, '||
  'case when pf.BDCODTPCC is null then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC, COLCON.BDDATAGRRFFC, COLCON.BDORDEM, COLCON.BDDATABAIXAFC, '||
  'null as BDREFVINCFN, ADC.bddtacconv, COLCON.BDTIPOEVT,COLCON.BDIDDEMONSTRATIVO, ADC.BDDTPGTOBRICONV, COLCON.BDCODACCONV, ' ||
  ' RESC.BDDATAPAGRESCISAO, RESC.BDCALCFGTSMESANT, RESC.BDDATAPAGGRFC ';

  if (pragrupatomador in (3, 4)) then wsqlcc = wsqlcc||', case when toma.bdCODTPCC is null then null else pf.bdCodCentro end bdCodCentrotoma, toma.bdCODTPCC bdCODTPCCtoma ';
  wsqlcc = wsqlcc|| 'from VRHF_EMP_TFOLTOMCOMPINT COLCON join TEMPRESAS emp on (colcon.bdcodemp = emp.bdcodemp) '||
  'join VRHF_EMP_TFOLHATOMINT FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLN.BDORDEM = COLCON.BDORDEM and FOLN.BDCODCONTTI = COLCON.BDCODCONTTI) '||
  'join VRHF_EMP_TPREPFN pf on (pf.BDCODEMP = COLCON.BDCODEMP and pf.BDCODCOL = COLCON.BDCODCOL and pf.BDORDEM = COLCON.BDORDEM) '||
  'left outer join vrh_emp_trescisao resc on (COLCON.BDCODEMP = resc.BDCODEMP and COLCON.BDCODCOL = resc.BDCODCOL) '||
  'left outer join VRH_EMP_TACCONV ADC on (ADC.bdcodemp = COLCON.bdcodemp) and (adc.bdcodacconv = COLCON.bdcodacconv) ';

  if (pragrupatomador = 4) then
     wsqlcc = wsqlcc||'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro,'||prrefinicomp||') toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) ';
  else if (pragrupatomador = 3) then
     wsqlcc = wsqlcc||'left outer join VRHF_SP_TOMADOR(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) ';

  wsqlcc = wsqlcc|| replace(upper(wwheren), 'COLCON.BDREFFN', 'COLCON.BDREFTOMADOR');
  if (pragrupatomador = 5) then
     begin
       wsql = 'select '||
       'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
       WDATAPAG||', cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
       'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), '||
       'sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
       'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), '||
       'sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
       'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), '||
       'sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
       'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), '||
       'sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC), sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
       'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
       'cast(null as integer), cast(null as integer), sum(colcon.bdcreditofc), sum(colcon.bddebitofc), sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc), '||
       'colcon.BDREFFC, max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
       'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc), '||
       'sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
       'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13apft), '||
       'sum(COLCON.bdliquido), max(COLCON.bddatagrrffc), max(COLCON.bdrefvincfn), colcon.bddtacconv, max(COLCON.BDTIPOEVT),max(COLCON.BDIDDEMONSTRATIVO), MAX(COLCON.BDDTPGTOBRICONV), MAX(COLCON.BDCODACCONV), '||
       'COLCON.BDDATAPAGRESCISAO, COLCON.BDCALCFGTSMESANT, COLCON.BDDATAPAGGRFC '||
       'from (';
              
       wsql = wsql||wsqlcc||') COLCON ';
       if (coalesce(prcodtpcc, '') <> '') then wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.bdcodemp,colcon.bdcodcol,colcon.BDCODCONTTI,colcon.BDREFTOMADOR, colcon.BDREFFC, COLCON.BDREFCOMP, colcon.bddtacconv, COLCON.BDDATAPAGRESCISAO, COLCON.BDCALCFGTSMESANT, COLCON.BDDATAPAGGRFC'||wordemdatapag;
     end
  else if (pragrupatomador = 4) then
     begin
       wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
       WDATAPAG||', CAST(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
       'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), '||
       'sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
       'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), '||
       'sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
       'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), '||
       'sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
       'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), '||
       'sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC),sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
       'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
       'case when COLCON.bdCODTPCCtoma is null then null else COLCON.bdCodCentrotoma end bdCodCentro, COLCON.bdCODTPCCtoma bdCODTPCC, '||
       'sum(colcon.bdcreditofc), sum(colcon.bddebitofc), sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc), '||
       'max(colcon.BDREFFC), max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
       'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc), '||
       'sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
       'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13ft), '||
       'sum(COLCON.bdliquido), max(COLCON.BDDATAGRRFFC), max(COLCON.bdrefvincfn), colcon.bddtacconv, max(COLCON.BDTIPOEVT),max(COLCON.BDIDDEMONSTRATIVO), max(COLCON.BDDTPGTOBRICONV), MAX(COLCON.BDCODACCONV), '||
       'COLCON.BDDATAPAGRESCISAO, COLCON.BDCALCFGTSMESANT, COLCON.BDDATAPAGGRFC '||
       'from (';
              
       wsql = wsql||wsqlcc||') COLCON ';
       if (coalesce(prcodtpcc, '') <> '') then wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.bdcodemp,colcon.bdcodcol,colcon.BDCODCONTTI,colcon.BDREFTOMADOR,COLCON.BDREFCOMP, COLCON.bdCodCentrotoma, COLCON.bdCODTPCCtoma, colcon.bddtacconv, COLCON.BDDATAPAGRESCISAO, COLCON.BDCALCFGTSMESANT, COLCON.BDDATAPAGGRFC '||wordemdatapag;
     end
  else if (pragrupatomador = 3) then
     begin
       wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
       WDATAPAG||', cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
       'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), '||
       'sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
       'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), '||
       'sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
       'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), '||
       'sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
       'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), '||
       'sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC),sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
       'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
       'case when COLCON.bdCODTPCCtoma is null then null else COLCON.bdCodCentrotoma end bdCodCentro, COLCON.bdCODTPCCtoma bdCODTPCC, '||
       'sum(colcon.bdcreditofc), sum(colcon.bddebitofc), sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc), '||
       'max(colcon.BDREFFC), max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
       'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc), '||
       'sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
       'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13apft), '||
       'sum(COLCON.bdliquido), max(COLCON.BDDATAGRRFFC), max(COLCON.bdrefvincfn), colcon.bddtacconv, max(COLCON.BDTIPOEVT),max(COLCON.BDIDDEMONSTRATIVO), max(COLCON.BDDTPGTOBRICONV), MAX(COLCON.BDCODACCONV), '||
       'COLCON.BDDATAPAGRESCISAO, COLCON.BDCALCFGTSMESANT, COLCON.BDDATAPAGGRFC '||
       'from (';
 
       wsql = wsql||wsqlcc||') COLCON ';
       if (coalesce(prcodtpcc, '') <> '') then wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.bdcodemp,colcon.bdcodcol,colcon.BDCODCONTTI,colcon.BDREFTOMADOR, COLCON.BDREFCOMP, COLCON.bdCodCentrotoma, COLCON.bdCODTPCCtoma, colcon.bddtacconv, COLCON.BDDATAPAGRESCISAO, COLCON.BDCALCFGTSMESANT, COLCON.BDDATAPAGGRFC '||wordemdatapag;
     end
  else if (pragrupatomador = 2) then
     begin
       wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
       WDATAPAG||',cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
       'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), '||
       'sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
       'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), '||
       'sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
       'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), '||
       'sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
       'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), '||
       'sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC),sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
       'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
       'case when COLCON.bdCODTPCC is null then null else COLCON.bdCodCentro end bdCodCentro, COLCON.bdCODTPCC, '||
       'sum(colcon.bdcreditofc), sum(colcon.bddebitofc), sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc), '||
       'max(colcon.BDREFFC), max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
       'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc), '||
       'sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
       'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13apft), '||
       'sum(COLCON.bdliquido), max(COLCON.bddatagrrffc), max(COLCON.bdrefvincfn), colcon.bddtacconv, max(COLCON.BDTIPOEVT),max(COLCON.BDIDDEMONSTRATIVO), max(COLCON.BDDTPGTOBRICONV), MAX(COLCON.BDCODACCONV), '||
       'COLCON.BDDATAPAGRESCISAO, COLCON.BDCALCFGTSMESANT, COLCON.BDDATAPAGGRFC '||
       'from (';

       wsql = wsql||wsqlcc||') COLCON ';
       if (coalesce(prcodtpcc, '') <> '') then wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.bdcodemp,colcon.bdcodcol,colcon.BDCODCONTTI,colcon.BDREFTOMADOR,COLCON.BDREFCOMP, COLCON.bdCodCentro, COLCON.bdCODTPCC, colcon.bddtacconv, COLCON.BDDATAPAGRESCISAO, COLCON.BDCALCFGTSMESANT, COLCON.BDDATAPAGGRFC '||wordemdatapag;
     end
  else if (pragrupatomador = 1) then
     begin
       wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
       WDATAPAG||',cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
       'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), '||
       'sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
       'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), '||
       'sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
       'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), '||
       'sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
       'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), '||
       'sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC), sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
       'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
       'cast(null as integer), cast(null as integer), sum(colcon.bdcreditofc), sum(colcon.bddebitofc), sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc), '||
       'max(colcon.BDREFFC), max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
       'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc), '||
       'sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
       'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13apft), '||
       'sum(COLCON.bdliquido), max(COLCON.BDDATAGRRFFC), max(COLCON.BDREFVINCFN), colcon.bddtacconv, max(COLCON.BDTIPOEVT),max(COLCON.BDIDDEMONSTRATIVO), max(COLCON.BDDTPGTOBRICONV), MAX(COLCON.BDCODACCONV), '||
       'COLCON.BDDATAPAGRESCISAO, COLCON.BDCALCFGTSMESANT, COLCON.BDDATAPAGGRFC '||
       'from (';

       wsql = wsql||wsqlcc||') COLCON ';
       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.bdcodemp,colcon.bdcodcol,colcon.bdcodcontti,colcon.bdreftomador, colcon.bdrefcomp, colcon.bddtacconv, COLCON.BDDATAPAGRESCISAO, COLCON.BDCALCFGTSMESANT, COLCON.BDDATAPAGGRFC '||wordemdatapag;
     end
      else if (pragrupatomador = 6) then
     begin
       wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, max(COLCON.BDREFTOMADOR), max(COLCON.BDREFCOMP), '||
       WDATAPAG||',cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
       'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), '||
       'sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
       'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), '||
       'sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
       'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), '||
       'sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
       'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), '||
       'sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC), sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
       'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
       'cast(null as integer), cast(null as integer), sum(colcon.bdcreditofc), sum(colcon.bddebitofc), sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc), '||
       'max(colcon.BDREFFC), max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
       'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc), '||
       'sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
       'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13apft), '||
       'sum(COLCON.bdliquido), max(COLCON.BDDATAGRRFFC), max(COLCON.BDREFVINCFN), COLCON.bddtacconv, max(COLCON.BDTIPOEVT),max(COLCON.BDIDDEMONSTRATIVO), max(COLCON.BDDTPGTOBRICONV), MAX(COLCON.BDCODACCONV), '||
       'COLCON.BDDATAPAGRESCISAO, COLCON.BDCALCFGTSMESANT, COLCON.BDDATAPAGGRFC '||
       'from (';

       wsql = wsql||wsqlcc||') COLCON ';
       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.bdcodemp,colcon.bdcodcol,colcon.BDCODCONTTI,BDDATAPAGFC,bddtacconv, COLCON.BDDATAPAGRESCISAO, COLCON.BDCALCFGTSMESANT, COLCON.BDDATAPAGGRFC '||wordemdatapag;
     END
  ELSE
     BEGIN
       wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
       WDATAPAG||', COLCON.BDORDEM, COLCON.BDDATABAIXAFC, COLCON.BDBFGTSFC, COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, COLCON.BDFGTS13CSFC, '||
       'COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
       'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, COLCON.BDSALFAMFC, COLCON.BDBRAISFC, COLCON.BDSALBASEFC, COLCON.BDDEPFC, '||
       'COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC, COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, '||
       'COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, case when COLCON.bdCODTPCC is null then null else COLCON.bdCodCentro end bdCodCentro, COLCON.bdCODTPCC, '||
       'colcon.bdcreditofc, colcon.bddebitofc, colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc, colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
       'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc, COLCON.bdbinssft, COLCON.bdinssft, COLCON.bdbinss13ft, COLCON.bdinss13ft, '||
       'colcon.bdbinssapft, colcon.bdbinss13apft, colcon.bdinssapft, colcon.bdinss13apft, '||
       'COLCON.bdliquido, COLCON.BDDATAGRRFFC, COLCON.BDREFVINCFN, colcon.bddtacconv, COLCON.BDTIPOEVT,COLCON.BDIDDEMONSTRATIVO, COLCON.BDDTPGTOBRICONV, COLCON.BDCODACCONV, '||
       'COLCON.BDDATAPAGRESCISAO, COLCON.BDCALCFGTSMESANT, COLCON.BDDATAPAGGRFC '||
       'from (';

       wsql = wsql||wsqlcc||') COLCON ';
       if (coalesce(prcodtpcc, '') <> '') then wsql = wsql||' where '||prcodtpcc;
     END

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp, :bdcodcol, :bdcodcontti, :bdreffn, :BDREFCOMP, :BDDATAPAGFC, :bdordem, :bddatabaixafC,
    :bdbfgtsfC, :bdfgtsfc, :bdfgtscsfc, :bdbfgts13fc, :bdfgts13fc, :bdfgts13csfc, :bdmaiorremfc, :bdbinssfc,
    :bdaliqinssfc, :bdinssfc, :bdbirrffc, :bdaliqirrffc, :bdirrffc, :bdbinss13fc, :bdaliqinss13fc, :bdinss13fc,
    :bdbirrf13fc, :bdaliqirrf13fc, :bdirrf13fc, :bdbsalfamfc, :bdsalfamfc, :bdbraisfc, :bdsalbasefc, :bddepfc,
    :bdbasepisfc, :bdbasepisFEfc, :bdbasepis13fc, :bdbsalmatempfc, :bdsalmatempfc, :bdbratapofc, :bdbratapoFEfc, :bdbratapo13fc,
    :bdbinssfefolfc, :bdinssfefolfc, :bdaliqinssfefolfc, :bdCodCentro, :bdCODTPCC, :bdcredito, :bddebito, :bdBFGTSFEfc,
    :bdFGTSFEfc, :BDREFFC, :BDCODTIPOFC, :BDBINSSMVFC, :BDBINSSMV13FC, :BDINSSMVFC, :BDINSSMV13FC, :BDBINSSAPFC,
    :BDBINSS13APFC, :BDINSSAPFC, :BDINSS13APFC, :BDBINSSFN, :BDINSSFN, :BDBINSS13FN, :BDINSS13FN, :BDBINSSAPFN,
    :BDBINSS13APFN, :BDINSSAPFN, :BDINSS13APFN, :BDLIQUIDOFC, :BDDATAGRRF, :BDREFVINCFN, :bddtacconv, :bdtipoevt,
    :bdiddemonstrativo, :BDDTPGTOBRICONV, :bdcodacconv, :wdatarescisao, :wcalcfgtsmesant, :wdatapaggrfc
  DO
    BEGIN
      bdcalctomador = 'True'; BDSALFAMFNGPS = 0; BDSALFAM13GPS = 0; wtembeneficio = 0;

      if (coalesce(:BDCODCONTTI, 0) > 0) then
         begin
           if (bdordem is null) then
              wsqlverbas = 'select FC.BDCODVER, FC.BDVALVFC from VRHF_EMP_TVERBAFCTOMINT FC '||'where FC.BDCODEMP = '||:BDCODEMP||' and FC.BDCODCOL = '||:BDCODCOL||' and FC.BDREFTOMADOR = '||:BDREFFN||
              ' and FC.BDREFFC = '||:BDREFFC||' and FC.BDCODCONTTI = '||:BDCODCONTTI||' and FC.BDORDEM is null ';
           else
              wsqlverbas = 'select FC.BDCODVER, FC.BDVALVFC from VRHF_EMP_TVERBAFCTOMINT FC '||
              'where FC.BDCODEMP = '||:BDCODEMP||' and FC.BDCODCOL = '||:BDCODCOL||' and FC.BDREFTOMADOR = '||:BDREFFN||' and FC.BDREFFC = '||:BDREFFC||' and FC.BDCODCONTTI = '||:BDCODCONTTI||' and FC.BDORDEM = '||:BDORDEM;

           for execute statement wsqlverbas
           into :wcodver, :wvalvfc
           do
             begin
               select first 1 VR.BDTIPOCODVER, VR.BDINSSVER, VR.BDBASEGPSVER, V.BDCLAVER
               from VRH_BASE_TVERBAS_REF VR
               join VRH_BASE_TVERBAS V on (V.BDCODVER = VR.BDCODVER)
               where VR.BDCODVER = :wcodver and VR.BDREFVER <= :BDREFFN order by VR.BDREFVER DESC
               into :wtipocodver, :winssver, :wbasegpsver, :wclaver;
        
               winssver    = coalesce(winssver, 0); wtipocodver = coalesce(wtipocodver, 0); wbasegpsver = upper(coalesce(wbasegpsver, 'FALSE'));
               if (substring(:wclaver from 1 for 7) in ('8.015.3','8.015.4','8.035.3','8.035.4')) then wtembeneficio = 1;

               if (wbasegpsver = 'TRUE') then
                  begin
                    if (prinsspatronal = 1 and :BDREFFN >= 201508) then
                       begin
                         if (winssver = 3) then
                            begin
                              if (wtipocodver = 0) then BDBINSS13FC = BDBINSS13FC + :wvalvfc;
                              else if (wtipocodver = 1) then BDBINSS13FC = BDBINSS13FC - :wvalvfc;
                            end
                         else
                         if (winssver > 0) then
                            begin
                              if (wtipocodver = 0) then BDBINSSFC = BDBINSSFC + :wvalvfc;
                              else if (wtipocodver = 1) then BDBINSSFC = BDBINSSFC - :wvalvfc;
                            end
                       end
                  end
               else
                  begin
                    if ((substring(:wclaver from 1 for 5) = '8.005') or  (substring(:wclaver from 1 for 5) = '7.070') or (substring(:wclaver from 1 for 5) = '0.610')) then
                       begin
                         if (winssver = 3) then
                            begin
                              if (wtipocodver = 0) then BDSALFAM13GPS = BDSALFAM13GPS + :wvalvfc;
                              else if (wtipocodver = 1) then BDSALFAM13GPS = BDSALFAM13GPS - :wvalvfc;
                            end
                         else
                         if (winssver > 0) then
                            begin
                              if (wtipocodver = 0) then BDSALFAMFNGPS = BDSALFAMFNGPS + :wvalvfc;
                              else if (wtipocodver = 1) then BDSALFAMFNGPS = BDSALFAMFNGPS - :wvalvfc;
                            end
                       end
                  end
             end
         end
      else
         begin
           if (bdordem is null) then
              wsqlverbas = 'select FC.BDCODVER, FC.BDVALVFC from VRHF_EMP_TVERBAFCTOMADOR FC '||
              'where FC.BDCODEMP = '||:BDCODEMP||' and FC.BDCODCOL = '||:BDCODCOL||' and FC.BDREFTOMADOR = '||:BDREFFN||' and FC.BDREFFC = '||:BDREFFC||' and FC.BDORDEM is null ';
           else
              wsqlverbas = 'select FC.BDCODVER, FC.BDVALVFC from VRHF_EMP_TVERBAFCTOMADOR FC '||
              'where FC.BDCODEMP = '||:BDCODEMP||' and FC.BDCODCOL = '||:BDCODCOL||' and FC.BDREFTOMADOR = '||:BDREFFN|| ' and FC.BDREFFC = '||:BDREFFC||' and FC.BDORDEM = '||:BDORDEM;

           for execute statement wsqlverbas
           into :wcodver, :wvalvfc
           do
             begin
               select first 1 VR.BDTIPOCODVER, VR.BDINSSVER, VR.BDBASEGPSVER, V.BDCLAVER
               from VRH_BASE_TVERBAS_REF VR
               join VRH_BASE_TVERBAS V on (V.BDCODVER = VR.BDCODVER)
               where VR.BDCODVER = :wcodver and VR.BDREFVER <= :BDREFFN order by VR.BDREFVER DESC
               into :wtipocodver, :winssver, :wbasegpsver, :wclaver;
      
               winssver = coalesce(winssver, 0); wtipocodver = coalesce(wtipocodver, 0); wbasegpsver = upper(coalesce(wbasegpsver, 'FALSE'));
               if (substring(:wclaver from 1 for 7) in ('8.015.3','8.015.4','8.035.3','8.035.4')) then wtembeneficio = 1;

               if (wbasegpsver = 'TRUE') then
                  begin
                    if (prinsspatronal = 1 and :BDREFFN >= 201508) then
                       begin
                         if (winssver = 3) then
                            begin
                              if (wtipocodver = 0) then BDBINSS13FC = BDBINSS13FC + :wvalvfc;
                              else if (wtipocodver = 1) then BDBINSS13FC = BDBINSS13FC - :wvalvfc;
                            end
                         else
                         if (winssver > 0) then
                            begin
                              if (wtipocodver = 0) then BDBINSSFC = BDBINSSFC + :wvalvfc;
                              else if (wtipocodver = 1) then BDBINSSFC = BDBINSSFC - :wvalvfc;
                            end
                       end
                  end
               else
                  begin
                    if ((substring(:wclaver from 1 for 5) = '8.005') or  (substring(:wclaver from 1 for 5) = '7.070') or (substring(:wclaver from 1 for 5) = '0.610')) then
                       begin
                         if (winssver = 3) then
                            begin
                              if (wtipocodver = 0) then BDSALFAM13GPS = BDSALFAM13GPS + :wvalvfc;
                              else if (wtipocodver = 1) then BDSALFAM13GPS = BDSALFAM13GPS - :wvalvfc;
                            end
                         else
                         if (winssver > 0) then
                            begin
                              if (wtipocodver = 0) then BDSALFAMFNGPS = BDSALFAMFNGPS + :wvalvfc;
                              else if (wtipocodver = 1) then BDSALFAMFNGPS = BDSALFAMFNGPS - :wvalvfc;
                            end
                       end
                  end
             end
         end

      if (prinsspatronal = 1) then
         begin
           if (BDREFFN >= 201508) then
              begin
                if ((BDBINSSFC < 0) and (wtembeneficio <> 1)) then BDBINSSFC = 0;
                if (BDBINSS13FC < 0) then BDBINSS13FC = 0;
              end
         end

      WDATAAUX = NULL;
      if (BDDATAGRRF is not null) then WDATAAUX = BDDATAGRRF; else WDATAAUX = BDDATAPAGFC;

      if (WDATAAUX is not null) then
        begin
          WSQLAUXDAT = ' SELECT X.BDBFGTSMESANT, X.BDFGTSMESANT, X.BDBFGTSMES, X.BDFGTSMES, X.BDFGTSIND, X.BDBFGTSMESSEFIP, X.BDFGTSMESSEFIP, ' ||
          ' X.BDSALDO, X.BDFGTS40, X.BDFGTS10, X.BDTOTAL, ' ||
          ' CASE WHEN X.BDTOTAL > 0 THEN 1 ' ||
          ' WHEN X.BDTOTAL <= 0 THEN 0 END BDTEMGRRF, X.BDPERCMULTA40, X.BDPERCMULTA10, X.BDFGTS13, X.BDSALDOTOTAL ' ||
          ' FROM VRHF_EMP_VAL_GRRF_FC(' || BDCODEMP || ',' || BDCODCOL || ',' || BDREFFN || ',''' || WDATAAUX || ''','|| BDCODTIPOFC ||') X ';
            execute statement WSQLAUXDAT
          into :BDBFGTSMESANT, :BDFGTSMESANT, :BDBFGTSMES, :BDFGTSMES, :BDFGTSIND, :BDBFGTSMESSEFIP, :BDFGTSMESSEFIP, :BDSALDO, :BDFGTS40, :BDFGTS10, :BDTOTAL, :BDTEMGRRF, :BDPERCMULTA40, :BDPERCMULTA10, :BDFGTS13, :BDSALDOTOTAL;
    
          if (BDTOTAL <> 0) then BDTEMGRRF = 1;
        end

      if (WDATARESCISAO is not null) then
        begin
          if ((BDDATAGRRF <= WDATARESCISAO) AND (WCALCFGTSMESANT = 'TRUE')) then
            begin
                WDATAAUX = NULL;
                BDBFGTSMESANT = 0; BDFGTSMESANT = 0; BDBFGTSMESPOST = 0; BDFGTSMESPOST = 0; BDBFGTSMES = 0; BDFGTSMES = 0;
                BDFGTSMES13 = 0; BDSALDO = 0; BDFGTS40 = 0; BDFGTS10 = 0; BDTOTALGRRF = 0; BDTEMGRRF = 0; BDFGTSIND = 0;
                BDPERCMULTA10 = 0; BDPERCMULTA40 = 0; BDBFGTSMESSEFIP = 0; BDFGTSMESSEFIP = 0; BDTOTAL = 0; BDFGTS13 = 0; BDSALDOTOTAL = 0;

                WSQLAUXDAT = 'select bdaaaamm from aaaamm(cast(' || '''' || cast(WDATARESCISAO as varchar(10)) || '''' || ' as date))'; execute statement WSQLAUXDAT into WAAAAMM;
            
                if (WAAAAMM <> BDREFCOMP) then
                  begin
                    WDATARESCISAO = null;
                    /* Verifica se a rescisão é no mês seguinte e se tem o parâmetro de FGTS mês anterior, para não buscar o FGTS do mês */
                    if (substring(WAAAAMM from 5 for 2) = '01') then WAAAAMM = cast((cast((substring(WAAAAMM from 1 for 4)) as integer) - 1) as varchar(4)) || '12';
                    else
                      begin
                        if (cast((substring(WAAAAMM from 5 for 2)) as integer) <= 10) then WAAAAMM = substring(WAAAAMM from 1 for 4) || '0' || cast((cast((substring(WAAAAMM from 5 for 2)) as integer) - 1) as varchar(1));
                        else WAAAAMM = substring(WAAAAMM from 1 for 4) || cast((cast((substring(WAAAAMM from 5 for 2)) as integer) - 1) as varchar(2));
                    end
            
                    if (WAAAAMM = BDREFCOMP) then
                    begin
                      BDBFGTSMESPOST = COALESCE(BDBFGTSFC, 0) + COALESCE(BDBFGTS13FC, 0) + COALESCE(BDBFGTSFEFC, 0);
                      BDFGTSMESPOST = COALESCE(BDFGTSFC, 0) + COALESCE(BDFGTS13FC, 0) + COALESCE(BDFGTSFEFC, 0);
                      BDBFGTSFC = 0; BDBFGTS13FC = 0;BDBFGTSFEFC = 0; BDFGTSFC = 0; BDFGTS13FC = 0; BDFGTSFEFC = 0;
                    end
                  end

                  if (WDATARESCISAO is not null) then
                    begin
                      if (BDDATAGRRF is not null) then WDATAAUX = BDDATAGRRF; else WDATAAUX = BDDATAPAGFC;

                      WSQLAUXDAT = ' SELECT X.BDBFGTSMESANT, X.BDFGTSMESANT, X.BDBFGTSMES, X.BDFGTSMES, X.BDFGTSIND, X.BDBFGTSMESSEFIP, X.BDFGTSMESSEFIP, ' ||
                      ' X.BDSALDO, X.BDFGTS40, X.BDFGTS10, X.BDTOTAL, ' ||
                      ' CASE WHEN X.BDTOTAL > 0 THEN 1 ' ||
                      ' WHEN X.BDTOTAL <= 0 THEN 0 END BDTEMGRRF, X.BDPERCMULTA40, X.BDPERCMULTA10, X.BDFGTS13, X.BDSALDOTOTAL ' ||
                      ' FROM VRHF_EMP_VAL_GRRF_FC(' || BDCODEMP || ',' || BDCODCOL || ',' || BDREFFN || ',''' || WDATAAUX || ''','|| BDCODTIPOFC ||') X ';
                        execute statement WSQLAUXDAT
                      into :BDBFGTSMESANT, :BDFGTSMESANT, :BDBFGTSMES, :BDFGTSMES, :BDFGTSIND, :BDBFGTSMESSEFIP, :BDFGTSMESSEFIP, :BDSALDO, :BDFGTS40, :BDFGTS10, :BDTOTAL, :BDTEMGRRF, :BDPERCMULTA40, :BDPERCMULTA10, :BDFGTS13, :BDSALDOTOTAL;

                      if (BDTOTAL <> 0) then BDTEMGRRF = 1;
                    end
            end
        end

      SUSPEND;
    END
END^



/* Restore proc. body: VRHF_SP_TFOLHACOMP_INT */
create or alter procedure VRHF_SP_TFOLHACOMP_INT (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(28000),
    PRREFINICOMP integer,
    PRREFFIMCOMP integer,
    PRREFINIPAG integer,
    PRREFFIMPAG integer,
    PRAGRUPATOMADOR integer,
    PRTIPOFC integer = 0,
    PRSEPARCALC integer = 0,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(772) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODCONTTI integer,
    BDORDEM integer,
    BDREFFN integer,
    BDREFFC integer,
    BDREFCOMP integer,
    BDDATAPAGFC date,
    BDDATABAIXAFC date,
    BDBFGTSFC numeric(15,6),
    BDFGTSFC numeric(15,6),
    BDFGTSCSFC numeric(15,6),
    BDBFGTS13FC numeric(15,6),
    BDFGTS13FC numeric(15,6),
    BDFGTS13CSFC numeric(15,6),
    BDMAIORREMFC numeric(15,6),
    BDBINSSFC numeric(15,6),
    BDALIQINSSFC numeric(15,6),
    BDINSSFC numeric(15,6),
    BDBIRRFFC numeric(15,6),
    BDALIQIRRFFC numeric(15,6),
    BDIRRFFC numeric(15,6),
    BDBINSS13FC numeric(15,6),
    BDALIQINSS13FC numeric(15,6),
    BDINSS13FC numeric(15,6),
    BDBIRRF13FC numeric(15,6),
    BDALIQIRRF13FC numeric(15,6),
    BDIRRF13FC numeric(15,6),
    BDBSALFAMFC numeric(15,6),
    BDSALFAMFC numeric(15,6),
    BDBRAISFC numeric(15,6),
    BDSALBASEFC numeric(15,6),
    BDDEPFC numeric(15,6),
    BDBASEPISFC numeric(15,6),
    BDBASEPISFEFC numeric(15,6),
    BDBASEPIS13FC numeric(15,6),
    BDBSALMATEMPFC numeric(15,6),
    BDSALMATEMPFC numeric(15,6),
    BDBRATAPOFC numeric(15,6),
    BDBRATAPOFEFC numeric(15,6),
    BDBRATAPO13FC numeric(15,6),
    BDBINSSFEFOLFC numeric(15,6),
    BDINSSFEFOLFC numeric(15,6),
    BDALIQINSSFEFOLFC numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDBFGTSFEFC numeric(15,6),
    BDFGTSFEFC numeric(15,6),
    BDCODTIPOFC integer,
    BDBINSSMVFC numeric(18,6),
    BDBINSSMV13FC numeric(18,6),
    BDINSSMVFC numeric(18,6),
    BDINSSMV13FC numeric(18,6),
    BDBINSSAPFC numeric(18,6),
    BDBINSS13APFC numeric(18,6),
    BDINSSAPFC numeric(18,6),
    BDINSS13APFC numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDINSSFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDLIQUIDOFC numeric(18,6),
    BDDATAGRRF date)
as
declare variable WDATAPAG varchar(50);
declare variable WORDEMDATAPAG varchar(50);
declare variable WSQL varchar(32700);
declare variable WWHEREN varchar(32700);
declare variable WSQLCC varchar(32700);
BEGIN
  /* pragrupatomador
     0 = Nao agrupa
     1 = Agrupa por referencia
     2 = Agrupo por referencia e centro/Tomador
     3 = Agrupa por referencia e Tomador (se nao for tomador verifica pela classificacao e nao encontrando considera empresa)
     4 = Agrupa por referencia e Tipo Tomador (so vai criar mais registros pra empresa se for tomador 155)
     5 = Agrupa por calculo
  */

  if (prpuxafiliais = 1) then
     begin
       if (coalesce(prcodemp, '') <> '') then
          begin
            prcodemp = UPPER(prcodemp);
     
            if (coalesce(prfiliais, '') <> '') then
               begin
                 wwheren = replace(prcodemp, 'COLCON.BDCODEMP', 'EMP.BDCODMATRIZ');
                 prcodemp = '('||prcodemp||' or (('||wwheren||') and (emp.bdcodemp in ('||prfiliais||'))))';
               end
            else
              prcodemp = replace(prcodemp, 'COLCON.BDCODEMP', 'coalesce(emp.bdcodmatriz,emp.bdcodemp)');
          end
     end

  /* Procedure Text */
  wsql = 'select COLCON.bdcodemp,COLCON.BDCODEMP,COLCON.BDCODCOL,cast(null as INTEGER) BDCODCONTTI,COLCON.BDREFFN,COLCON.BDREFCOMP,COLCON.BDDATAPAGFC,COLCON.BDDATABAIXAFC,'||
           ' COLCON.BDBFGTSFC,COLCON.BDFGTSFC,COLCON.BDFGTSCSFC,COLCON.BDBFGTS13FC,COLCON.BDFGTS13FC,COLCON.BDFGTS13CSFC,COLCON.BDMAIORREMFC,COLCON.BDBINSSFC,COLCON.BDALIQINSSFC,'||
           ' COLCON.BDINSSFC,COLCON.BDBIRRFFC,COLCON.BDALIQIRRFFC,COLCON.BDIRRFFC,COLCON.BDBINSS13FC,COLCON.BDALIQINSS13FC,COLCON.BDINSS13FC,COLCON.BDBIRRF13FC,COLCON.BDALIQIRRF13FC,'||
           ' COLCON.BDIRRF13FC,COLCON.BDBSALFAMFC,COLCON.BDSALFAMFC,COLCON.BDBRAISFC,COLCON.BDSALBASEFC,COLCON.BDDEPFC,COLCON.BDBASEPISFC,COLCON.BDBASEPISFEFC,COLCON.BDBASEPIS13FC,'||
           ' COLCON.BDBSALMATEMPFC,COLCON.BDSALMATEMPFC,COLCON.BDBRATAPOFC,COLCON.BDBRATAPOFEFC,COLCON.BDBRATAPO13FC,COLCON.BDBINSSFEFOLFC,COLCON.BDINSSFEFOLFC,COLCON.BDALIQINSSFEFOLFC,'||
           ' COLCON.BDCREDITOFC,COLCON.BDDEBITOFC,COLCON.bdbfgtsfefc,COLCON.bdfgtsfefc,COLCON.BDREFFC,COLCON.BDCODTIPOFC,COLCON.BDBINSSMVFC,COLCON.BDBINSSMV13FC,COLCON.BDINSSMVFC,'||
           ' COLCON.BDINSSMV13FC,COLCON.BDBINSSAPFC,COLCON.BDBINSS13APFC,COLCON.BDINSSAPFC,COLCON.BDINSS13APFC,FOLN.BDBINSSFN,FOLN.BDINSSFN,FOLN.BDBINSS13FN,FOLN.BDINSS13FN, '||
           ' FOLN.BDBINSSAPFN,FOLN.BDBINSS13APFN,FOLN.BDINSSAPFN, '||
           ' FOLN.BDINSS13APFN, '||
           ' ((select coalesce(sum(BDVALVFC), 0) BDLIQUIDO ' ||
           '   from VRHF_EMP_TVERBAFC FCV ' ||
           '   join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) ' ||
           '   where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and FCV.BDREFFN = COLCON.BDREFFN and FCV.BDREFFC = COLCON.BDREFFC) - ' ||
           '  (select coalesce(sum(BDVALVFC), 0) BDLIQUIDO ' ||
           '   from VRHF_EMP_TVERBAFC FCV ' ||
           '   join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) ' ||
           '   where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and FCV.BDREFFN = COLCON.BDREFFN and FCV.BDREFFC = COLCON.BDREFFC)) BDLIQUIDO, '||
           ' COLCON.BDDATAGRRFFC '||
           ' from vrhf_emp_tfolhacomp COLCON'||
           ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
           ' join VRHF_EMP_TFOLHANORMAL FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFFN = COLCON.BDREFFN) ';

  wwheren = '';

  prtipofc = coalesce(prtipofc, 0);
  pragrupatomador = coalesce(pragrupatomador, 0);

  if (coalesce(prcodemp, '') <> '') then
     begin
       if (wwheren <> '') then
          wwheren = wwheren||' and ';
       else
          wwheren = wwheren||' where ';

       wwheren = wwheren||prcodemp;

       if (coalesce(prcodcol, '') <> '') then
          begin
            if (wwheren <> '') then
               wwheren = wwheren||' and ';
            else
               wwheren = wwheren||' where ';

            wwheren = wwheren||prcodcol;
          end
     end


  if (coalesce(prrefinicomp, 0) <> 0 and coalesce(prreffimcomp, 0) <> 0) then
     begin
       if (wwheren <> '') then
          wwheren = wwheren||' and ';
       else
          wwheren = wwheren||' where ';

       wwheren = wwheren||'COLCON.BDREFFN >= '||prrefinicomp||' and '||'COLCON.BDREFFN <= '||prreffimcomp;
     end
  else
     begin
       if (coalesce(prrefinicomp, 0) <> 0) then
          begin
            if (wwheren <> '') then
               wwheren = wwheren||' and ';
            else
               wwheren = wwheren||' where ';

            wwheren = wwheren||'COLCON.BDREFFN = '||prrefinicomp;
          end
       else
          begin
            if (coalesce(prreffimcomp, 0) <> 0) then
               begin
                 if (wwheren <> '') then
                    wwheren = wwheren||' and ';
                 else
                    wwheren = wwheren||' where ';

                 wwheren = wwheren||'COLCON.BDREFFN = '||prreffimcomp;
               end
          end
     end

  if (coalesce(prrefinipag, 0) <> 0 and coalesce(prreffimpag, 0) <> 0) then
     begin
       if (wwheren <> '') then
          wwheren = wwheren||' and ';
       else
          wwheren = wwheren||' where ';

       wwheren = wwheren||'COLCON.BDREFCOMP >= '||prrefinipag||' and '||'COLCON.BDREFCOMP <= '||prreffimpag;
     end
  else
     begin
       if (coalesce(prrefinipag, 0) <> 0) then
          begin
            if (wwheren <> '') then
               wwheren = wwheren||' and ';
            else
               wwheren = wwheren||' where ';

            wwheren = wwheren||'COLCON.BDREFCOMP = '||prrefinipag;
          end
       else
          begin
            if (coalesce(prreffimpag, 0) <> 0) then
               begin
                 if (wwheren <> '') then
                    wwheren = wwheren||' and ';
                 else
                    wwheren = wwheren||' where ';

                 wwheren = wwheren||'COLCON.BDREFCOMP = '||prreffimpag;
               end
          end
     end

  if (prtipofc > 0) then
     begin
       if (wwheren <> '') then
          wwheren = wwheren||' and ';
       else
          wwheren = wwheren||' where ';

       wwheren = wwheren||'coalesce(COLCON.BDCODTIPOFC,1) = '||prtipofc;
     end

  wsql = wsql||wwheren;


  wsql = wsql||' union all ';

  wsql = wsql||
         'select COLCON.bdcodemp,COLCON.BDCODEMP,COLCON.BDCODCOL,COLCON.BDCODCONTTI,COLCON.BDREFFN,COLCON.BDREFCOMP,COLCON.BDDATAPAGFC,COLCON.BDDATABAIXAFC,COLCON.BDBFGTSFC,'||
           ' COLCON.BDFGTSFC,COLCON.BDFGTSCSFC,COLCON.BDBFGTS13FC,COLCON.BDFGTS13FC,COLCON.BDFGTS13CSFC,COLCON.BDMAIORREMFC,COLCON.BDBINSSFC,COLCON.BDALIQINSSFC,COLCON.BDINSSFC,'||
           ' COLCON.BDBIRRFFC,COLCON.BDALIQIRRFFC,COLCON.BDIRRFFC,COLCON.BDBINSS13FC,COLCON.BDALIQINSS13FC,COLCON.BDINSS13FC,COLCON.BDBIRRF13FC,COLCON.BDALIQIRRF13FC,COLCON.BDIRRF13FC,'||
           ' COLCON.BDBSALFAMFC,COLCON.BDSALFAMFC,COLCON.BDBRAISFC,COLCON.BDSALBASEFC,COLCON.BDDEPFC,COLCON.BDBASEPISFC,COLCON.BDBASEPISFEFC,COLCON.BDBASEPIS13FC,COLCON.BDBSALMATEMPFC,'||
           ' COLCON.BDSALMATEMPFC,COLCON.BDBRATAPOFC,COLCON.BDBRATAPOFEFC,COLCON.BDBRATAPO13FC,COLCON.BDBINSSFEFOLFC,COLCON.BDINSSFEFOLFC,COLCON.BDALIQINSSFEFOLFC,COLCON.BDCREDITOFC,'||
           ' COLCON.BDDEBITOFC,COLCON.bdbfgtsfefc,COLCON.bdfgtsfefc,COLCON.BDREFFC,COLCON.BDCODTIPOFC,COLCON.BDBINSSMVFC,COLCON.BDBINSSMV13FC,COLCON.BDINSSMVFC,COLCON.BDINSSMV13FC, '||
           ' COLCON.BDBINSSAPFC,COLCON.BDBINSS13APFC,COLCON.BDINSSAPFC,COLCON.BDINSS13APFC,FOLN.BDBINSSFN,FOLN.BDINSSFN,FOLN.BDBINSS13FN,FOLN.BDINSS13FN,FOLN.BDBINSSAPFN, '||
           ' FOLN.BDBINSS13APFN,FOLN.BDINSSAPFN,FOLN.BDINSS13APFN, '||
           ' ((select coalesce(sum(BDVALVFC), 0) BDLIQUIDO ' ||
           '   from VRHF_EMP_TVERBAFCINT FCV ' ||
           '   join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) ' ||
           '   where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and FCV.BDREFFN = COLCON.BDREFFN and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDCODCONTTI = COLCON.BDCODCONTTI) - ' ||
           '  (select coalesce(sum(BDVALVFC), 0) BDLIQUIDO ' ||
           '   from VRHF_EMP_TVERBAFCINT FCV ' ||
           '   join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) ' ||
           '   where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and FCV.BDREFFN = COLCON.BDREFFN and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDCODCONTTI = COLCON.BDCODCONTTI)) BDLIQUIDO, '||
           ' COLCON.BDDATAGRRFFC '||
           ' from VRHF_EMP_TFOLHACOMPINT COLCON'||
           ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
           ' join VRHF_EMP_TFOLHAINT FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFFN = COLCON.BDREFFN and FOLN.BDCODCONTTI = COLCON.BDCODCONTTI) ';

  wsql = wsql||wwheren;

  if (coalesce(prcodtpcc, '') = '') then
     begin
       bdcalctomador = 'FALSE';
     
       for execute statement wsql
       into
         :bdcodemp, :BDCODEMP, :BDCODCOL, :BDCODCONTTI, :BDREFFN, :BDREFCOMP, :BDDATAPAGFC, :BDDATABAIXAFC, :BDBFGTSFC, :BDFGTSFC, :BDFGTSCSFC, :BDBFGTS13FC, :BDFGTS13FC, :BDFGTS13CSFC,
         :BDMAIORREMFC, :BDBINSSFC, :BDALIQINSSFC, :BDINSSFC, :BDBIRRFFC, :BDALIQIRRFFC, :BDIRRFFC, :BDBINSS13FC, :BDALIQINSS13FC, :BDINSS13FC, :BDBIRRF13FC, :BDALIQIRRF13FC, :BDIRRF13FC,
         :BDBSALFAMFC, :BDSALFAMFC, :BDBRAISFC, :BDSALBASEFC, :BDDEPFC, :BDBASEPISFC, :BDBASEPISFEFC, :BDBASEPIS13FC, :BDBSALMATEMPFC, :BDSALMATEMPFC, :BDBRATAPOFC, :BDBRATAPOFEFC,
         :BDBRATAPO13FC, :BDBINSSFEFOLFC, :BDINSSFEFOLFC, :BDALIQINSSFEFOLFC, :bdcredito, :bddebito, :bdbfgtsfefc, :bdfgtsfefc, :BDREFFC, :BDCODTIPOFC, :BDBINSSMVFC, :BDBINSSMV13FC,
         :BDINSSMVFC, :BDINSSMV13FC, :BDBINSSAPFC, :BDBINSS13APFC, :BDINSSAPFC, :BDINSS13APFC, :BDBINSSFN, :BDINSSFN, :BDBINSS13FN, :BDINSS13FN, :BDBINSSAPFN, :BDBINSS13APFN,
         :BDINSSAPFN, :BDINSS13APFN, :BDLIQUIDOFC, :BDDATAGRRF
       do
         suspend;
     end

  WDATAPAG = 'colcon.BDDATAPAGFC';
  wordemdatapag = '';

  prseparcalc = coalesce(prseparcalc, 0);
  if (prseparcalc = 0) then
     begin
       if (pragrupatomador in (1, 2, 3, 4, 5)) then
          begin
            WDATAPAG = 'max(colcon.BDDATAPAGFC)';
            wordemdatapag = '';
          end
       else
          begin
            WDATAPAG = 'colcon.BDDATAPAGFC';
            wordemdatapag = '';
          end
     end
  else
     begin
       WDATAPAG = 'colcon.BDDATAPAGFC';
       wordemdatapag = ', colcon.BDDATAPAGFC';
     end

  wsqlcc = 'select '||
             'COLCON.BDCODEMP, '||
             'COLCON.BDCODCOL, '||
             'CAST(NULL AS INTEGER) BDCODCONTTI, '||
             'COLCON.BDREFTOMADOR, '||
             'COLCON.BDREFCOMP, '||
             'COLCON.BDBFGTSFC, '||
             'COLCON.BDFGTSFC, '||
             'COLCON.BDFGTSCSFC, '||
             'COLCON.BDBFGTS13FC, '||
             'COLCON.BDFGTS13FC, '||
             'COLCON.BDFGTS13CSFC, '||
             'COLCON.BDMAIORREMFC, '||
             'COLCON.BDBINSSFC, '||
             'COLCON.BDALIQINSSFC, '||
             'COLCON.BDINSSFC, '||
             'COLCON.BDBIRRFFC, '||
             'COLCON.BDALIQIRRFFC, '||
             'COLCON.BDIRRFFC, '||
             'COLCON.BDBINSS13FC, '||
             'COLCON.BDALIQINSS13FC, '||
             'COLCON.BDINSS13FC, '||
             'COLCON.BDBIRRF13FC, '||
             'COLCON.BDALIQIRRF13FC, '||
             'COLCON.BDIRRF13FC, '||
             'COLCON.BDBSALFAMFC, '||
             'COLCON.BDSALFAMFC, '||
             'COLCON.BDBRAISFC, '||
             'COLCON.BDSALBASEFC, '||
             'COLCON.BDDEPFC, '||
             'COLCON.BDBASEPISFC, '||
             'COLCON.BDBASEPISFEFC, '||
             'COLCON.BDBASEPIS13FC, '||
             'COLCON.BDBSALMATEMPFC, '||
             'COLCON.BDSALMATEMPFC, '||
             'COLCON.BDBRATAPOFC, '||
             'COLCON.BDBRATAPOFEFC, '||
             'COLCON.BDBRATAPO13FC, '||
             'COLCON.BDBINSSFEFOLFC, '||
             'COLCON.BDINSSFEFOLFC, '||
             'COLCON.BDALIQINSSFEFOLFC, '||
             'COLCON.BDCREDITOFC, '||
             'COLCON.BDDEBITOFC, '||
             'COLCON.BDDATAPAGFC, '||
             'COLCON.BDBFGTSFEFC, '||
             'COLCON.BDFGTSFEFC, '||
             'COLCON.BDREFFC, '||
             'COLCON.BDCODTIPOFC, '||
             'COLCON.BDBINSSMVFC, '||
             'COLCON.BDBINSSMV13FC, '||
             'COLCON.BDINSSMVFC, '||
             'COLCON.BDINSSMV13FC, '||
             'COLCON.BDBINSSAPFC, '||
             'COLCON.BDBINSS13APFC, '||
             'COLCON.BDINSSAPFC, '||
             'COLCON.BDINSS13APFC, '||
             'FOLN.BDBINSSFT, '||
             'FOLN.BDINSSFT, '||
             'FOLN.BDBINSS13FT, '||
             'FOLN.BDINSS13FT, '||
             'FOLN.BDBINSSAPFT, '||
             'FOLN.BDBINSS13APFT, '||
             'FOLN.BDINSSAPFT, '||
             'FOLN.BDINSS13APFT, '||
             '((select coalesce(sum(BDVALVFC),0) BDLIQUIDO '||
               'from VRHF_EMP_TVERBAFCTOMADOR FCV '||
               'join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
               'where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM) - '||
              '(select coalesce(sum(BDVALVFC),0) BDLIQUIDO '||
               'from VRHF_EMP_TVERBAFCTOMADOR FCV '||
               'join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
               'where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM '||
               ')) BDLIQUIDO, '||
             'COLCON.BDDATAGRRFFC, '||
             'case when PF.BDCODTPCC is null then null else PF.BDCODCENTRO end BDCODCENTRO, '||
             'PF.BDCODTPCC ';

  if (pragrupatomador in (3, 4)) then
     wsqlcc = wsqlcc||', case when TOMA.BDCODTPCC is null then null else PF.BDCODCENTRO end BDCODCENTROTOMA, '||
                      'TOMA.BDCODTPCC BDCODTPCCTOMA ';
  else
  if (pragrupatomador not in (1, 2, 3, 4, 5)) then
     wsqlcc = wsqlcc||', COLCON.BDORDEM, COLCON.BDDATABAIXAFC ';

  wsqlcc = wsqlcc||
           'from VRHF_EMP_TFOLTOMCOMP COLCON '||
           'join TEMPRESAS EMP on (COLCON.BDCODEMP = EMP.BDCODEMP) '||
           'join VRHF_EMP_TFOLHATOMADOR FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLN.BDORDEM = COLCON.BDORDEM) '||
           'join VRHF_EMP_TPREPFN PF on (PF.BDCODEMP = COLCON.BDCODEMP and PF.BDCODCOL = COLCON.BDCODCOL and PF.BDORDEM = COLCON.BDORDEM) ';

  if (pragrupatomador = 4) then
     wsqlcc = wsqlcc||'left outer join VRHF_SP_TIPO_TOMADOR_GPS(PF.BDCODTPCC,PF.BDCODCENTRO,'||prrefinicomp||') TOMA on (TOMA.BDCODCENCUS = PF.BDCODTPCC and TOMA.BDCODCENTRO = PF.BDCODCENTRO) ';
  else
  if (pragrupatomador = 3) then
     wsqlcc = wsqlcc||'left outer join VRHF_SP_TOMADOR(PF.BDCODTPCC,PF.BDCODCENTRO) TOMA on (TOMA.BDCODCENCUS = PF.BDCODTPCC and TOMA.BDCODCENTRO = PF.BDCODCENTRO) ';

  wsqlcc = wsqlcc||
           replace(upper(wwheren), 'COLCON.BDREFFN', 'COLCON.BDREFTOMADOR')||' '||
           'union all '||
           'select '||
             'COLCON.BDCODEMP, '||
             'COLCON.BDCODCOL, '||
             'COLCON.BDCODCONTTI, '||
             'COLCON.BDREFTOMADOR, '||
             'COLCON.BDREFCOMP, '||
             'COLCON.BDBFGTSFC, '||
             'COLCON.BDFGTSFC, '||
             'COLCON.BDFGTSCSFC, '||
             'COLCON.BDBFGTS13FC, '||
             'COLCON.BDFGTS13FC, '||
             'COLCON.BDFGTS13CSFC, '||
             'COLCON.BDMAIORREMFC, '||
             'COLCON.BDBINSSFC, '||
             'COLCON.BDALIQINSSFC, '||
             'COLCON.BDINSSFC, '||
             'COLCON.BDBIRRFFC, '||
             'COLCON.BDALIQIRRFFC, '||
             'COLCON.BDIRRFFC, '||
             'COLCON.BDBINSS13FC, '||
             'COLCON.BDALIQINSS13FC, '||
             'COLCON.BDINSS13FC, '||
             'COLCON.BDBIRRF13FC, '||
             'COLCON.BDALIQIRRF13FC, '||
             'COLCON.BDIRRF13FC, '||
             'COLCON.BDBSALFAMFC, '||
             'COLCON.BDSALFAMFC, '||
             'COLCON.BDBRAISFC, '||
             'COLCON.BDSALBASEFC, '||
             'COLCON.BDDEPFC, '||
             'COLCON.BDBASEPISFC, '||
             'COLCON.BDBASEPISFEFC, '||
             'COLCON.BDBASEPIS13FC, '||
             'COLCON.BDBSALMATEMPFC, '||
             'COLCON.BDSALMATEMPFC, '||
             'COLCON.BDBRATAPOFC, '||
             'COLCON.BDBRATAPOFEFC, '||
             'COLCON.BDBRATAPO13FC, '||
             'COLCON.BDBINSSFEFOLFC, '||
             'COLCON.BDINSSFEFOLFC, '||
             'COLCON.BDALIQINSSFEFOLFC, '||
             'COLCON.BDCREDITOFC, '||
             'COLCON.BDDEBITOFC, '||
             'COLCON.BDDATAPAGFC, '||
             'COLCON.BDBFGTSFEFC, '||
             'COLCON.BDFGTSFEFC, '||
             'COLCON.BDREFFC, '||
             'COLCON.BDCODTIPOFC, '||
             'COLCON.BDBINSSMVFC, '||
             'COLCON.BDBINSSMV13FC, '||
             'COLCON.BDINSSMVFC, '||
             'COLCON.BDINSSMV13FC, '||
             'COLCON.BDBINSSAPFC, '||
             'COLCON.BDBINSS13APFC, '||
             'COLCON.BDINSSAPFC, '||
             'COLCON.BDINSS13APFC, '||
             'FOLN.BDBINSSFT, '||
             'FOLN.BDINSSFT, '||
             'FOLN.BDBINSS13FT, '||
             'FOLN.BDINSS13FT, '||
             'FOLN.BDBINSSAPFT, '||
             'FOLN.BDBINSS13APFT, '||
             'FOLN.BDINSSAPFT, '||
             'FOLN.BDINSS13APFT, '||
             '((select coalesce(sum(BDVALVFC),0) BDLIQUIDO '||
               'from VRHF_EMP_TVERBAFCTOMINT FCV '||
               'join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
               'where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM and FCV.BDCODCONTTI = COLCON.BDCODCONTTI) - '||
              '(select coalesce(sum(BDVALVFC),0) BDLIQUIDO '||
               'from VRHF_EMP_TVERBAFCTOMINT FCV '||
               'join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
               'where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM and FCV.BDCODCONTTI = COLCON.BDCODCONTTI '||
               ')) BDLIQUIDO, '||
             'COLCON.BDDATAGRRFFC, '||
             'case when PF.BDCODTPCC is null then null else PF.BDCODCENTRO end BDCODCENTRO, '||
             'PF.BDCODTPCC ';

  if (pragrupatomador in (3, 4)) then
     wsqlcc = wsqlcc||', case when TOMA.BDCODTPCC is null then null else PF.BDCODCENTRO end BDCODCENTROTOMA, '||
                      'TOMA.BDCODTPCC BDCODTPCCTOMA ';
  else
  if (pragrupatomador not in (1, 2, 3, 4, 5)) then
     wsqlcc = wsqlcc||', COLCON.BDORDEM, COLCON.BDDATABAIXAFC ';

  wsqlcc = wsqlcc||
           'from VRHF_EMP_TFOLTOMCOMPINT COLCON '||
           'join TEMPRESAS EMP on (COLCON.BDCODEMP = EMP.BDCODEMP) '||
           'join VRHF_EMP_TFOLHATOMINT FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLN.BDORDEM = COLCON.BDORDEM and FOLN.BDCODCONTTI = COLCON.BDCODCONTTI) '||
           'join VRHF_EMP_TPREPFN PF on (PF.BDCODEMP = COLCON.BDCODEMP and PF.BDCODCOL = COLCON.BDCODCOL and PF.BDORDEM = COLCON.BDORDEM) ';

  if (pragrupatomador = 4) then
     wsqlcc = wsqlcc||'left outer join VRHF_SP_TIPO_TOMADOR_GPS(PF.BDCODTPCC,PF.BDCODCENTRO,'||prrefinicomp||') TOMA on (TOMA.BDCODCENCUS = PF.BDCODTPCC and TOMA.BDCODCENTRO = PF.BDCODCENTRO) ';
  else
  if (pragrupatomador = 3) then
     wsqlcc = wsqlcc||'left outer join VRHF_SP_TOMADOR(PF.BDCODTPCC,PF.BDCODCENTRO) TOMA on (TOMA.BDCODCENCUS = PF.BDCODTPCC and TOMA.BDCODCENTRO = PF.BDCODCENTRO) ';

  wsqlcc = wsqlcc||
           replace(upper(wwheren), 'COLCON.BDREFFN', 'COLCON.BDREFTOMADOR')||' ';
           
  if (pragrupatomador = 5) then
     begin
       wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                WDATAPAG||',cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC),sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), '||
                'sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC),sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), '||
                'sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC),sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), '||
                'sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC),sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), '||
                'sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC), sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC),sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
                'cast(null as integer), cast(null as integer),sum(colcon.bdcreditofc), sum(colcon.bddebitofc), '||
                'sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc),colcon.BDREFFC, max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
                'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc),sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
                'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13apft),sum(COLCON.bdliquido), max(COLCON.bddatagrrffc) '||
              'from (';
              
       wsql = wsql||wsqlcc||') COLCON ';

       if (coalesce(prcodtpcc, '') <> '') then
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.BDCODEMP,colcon.BDCODCOL,colcon.BDCODCONTTI,colcon.BDREFTOMADOR, colcon.BDREFFC, COLCON.BDREFCOMP'||wordemdatapag;
     end
  else if (pragrupatomador = 4) then
     begin
       wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP,'||WDATAPAG||',CAST(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
                'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC),sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
                'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC),sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
                'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC),sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
                'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC),sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC),sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
                'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC),case when COLCON.bdCODTPCCtoma is null then null else COLCON.bdCodCentrotoma end bdCodCentro, COLCON.bdCODTPCCtoma bdCODTPCC, '||
                'sum(colcon.bdcreditofc), sum(colcon.bddebitofc),sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc),max(colcon.BDREFFC), max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
                'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc),sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
                'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13ft),sum(COLCON.bdliquido), max(COLCON.BDDATAGRRFFC) '||
              'from (';
              
       wsql = wsql||wsqlcc||') COLCON ';

       if (coalesce(prcodtpcc, '') <> '') then
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.BDCODEMP,colcon.BDCODCOL,colcon.BDCODCONTTI,colcon.BDREFTOMADOR,COLCON.BDREFCOMP, COLCON.bdCodCentrotoma, COLCON.bdCODTPCCtoma '||wordemdatapag;
     end
  else if (pragrupatomador = 3) then
     begin
       wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||WDATAPAG||', cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
                'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC),sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
                'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC),sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
                'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC),sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
                'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC),sum(COLCON.BDSALMATEMPFC), '||
                'sum(COLCON.BDBRATAPOFC),sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC),sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
                'case when COLCON.bdCODTPCCtoma is null then null else COLCON.bdCodCentrotoma end bdCodCentro, COLCON.bdCODTPCCtoma bdCODTPCC,sum(colcon.bdcreditofc), sum(colcon.bddebitofc), '||
                'sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc),max(colcon.BDREFFC), max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
                'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc),sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
                'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13apft),sum(COLCON.bdliquido), max(COLCON.BDDATAGRRFFC) '||
              'from (';
 
       wsql = wsql||wsqlcc||') COLCON ';
            
       if (coalesce(prcodtpcc, '') <> '') then
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.BDCODEMP,colcon.BDCODCOL,colcon.BDCODCONTTI,colcon.BDREFTOMADOR, COLCON.BDREFCOMP, COLCON.bdCodCentrotoma, COLCON.bdCODTPCCtoma'||wordemdatapag;
     end
  else if (pragrupatomador = 2) then
     begin
       wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||WDATAPAG||',cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
                'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC),sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
                'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC),sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
                'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC),sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
                'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC),sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC),sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
                'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC),case when COLCON.bdCODTPCC is null then null else COLCON.bdCodCentro end bdCodCentro, COLCON.bdCODTPCC, '||
                'sum(colcon.bdcreditofc), sum(colcon.bddebitofc),sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc),max(colcon.BDREFFC), max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
                'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc),sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
                'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13apft),sum(COLCON.bdliquido), max(COLCON.bddatagrrffc) '||
              'from (';

       wsql = wsql||wsqlcc||') COLCON ';

       if (coalesce(prcodtpcc, '') <> '') then
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.BDCODEMP,colcon.BDCODCOL,colcon.BDCODCONTTI,colcon.BDREFTOMADOR, COLCON.BDREFCOMP, COLCON.bdCodCentro, COLCON.bdCODTPCC '||wordemdatapag;
     end
  else if (pragrupatomador = 1) then
     begin
       wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||WDATAPAG||',cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
                'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC),sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
                'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC),sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
                'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC),sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
                'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC),sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC), sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
                'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC),cast(null as integer), cast(null as integer),sum(colcon.bdcreditofc), sum(colcon.bddebitofc), '||
                'sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc),max(colcon.BDREFFC), max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
                'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc),sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
                'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13apft),sum(COLCON.bdliquido), max(COLCON.BDDATAGRRFFC) '||
              'from (';

       wsql = wsql||wsqlcc||') COLCON ';


       if (coalesce(prcodtpcc, '') <> '') then
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.BDCODEMP,colcon.BDCODCOL,colcon.BDCODCONTTI,colcon.BDREFTOMADOR, COLCON.BDREFCOMP'||wordemdatapag;
     end
  else
     begin
       wsql = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||WDATAPAG||',COLCON.BDORDEM, COLCON.BDDATABAIXAFC, COLCON.BDBFGTSFC, COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, COLCON.BDFGTS13CSFC, '||
                'COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
                'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, COLCON.BDSALFAMFC, COLCON.BDBRAISFC, COLCON.BDSALBASEFC, COLCON.BDDEPFC,COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, '||
                'COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC, COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC,COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, case when COLCON.bdCODTPCC is null then null else COLCON.bdCodCentro end bdCodCentro, COLCON.bdCODTPCC, '||
                'colcon.bdcreditofc, colcon.bddebitofc,colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc,colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
                'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc,COLCON.bdbinssft, COLCON.bdinssft, COLCON.bdbinss13ft, COLCON.bdinss13ft, '||
                'colcon.bdbinssapft, colcon.bdbinss13apft, colcon.bdinssapft, colcon.bdinss13apft,COLCON.bdliquido, COLCON.BDDATAGRRFFC '||
              'from (';

       wsql = wsql||wsqlcc||') COLCON ';

       if (coalesce(prcodtpcc, '') <> '') then
          wsql = wsql||' where '||prcodtpcc;

     end

  for execute statement wsql
  into
    :bdcodemp,
    :bdcodcol,
    :bdcodcontti,
    :bdreffn,
    :BDREFCOMP,
    :BDDATAPAGFC,
    :bdordem,
    :bddatabaixafC,
    :bdbfgtsfC,
    :bdfgtsfc,
    :bdfgtscsfc,
    :bdbfgts13fc,
    :bdfgts13fc,
    :bdfgts13csfc,
    :bdmaiorremfc,
    :bdbinssfc,
    :bdaliqinssfc,
    :bdinssfc,
    :bdbirrffc,
    :bdaliqirrffc,
    :bdirrffc,
    :bdbinss13fc,
    :bdaliqinss13fc,
    :bdinss13fc,
    :bdbirrf13fc,
    :bdaliqirrf13fc,
    :bdirrf13fc,
    :bdbsalfamfc,
    :bdsalfamfc,
    :bdbraisfc,
    :bdsalbasefc,
    :bddepfc,
    :bdbasepisfc,
    :bdbasepisFEfc,
    :bdbasepis13fc,
    :bdbsalmatempfc,
    :bdsalmatempfc,
    :bdbratapofc,
    :bdbratapoFEfc,
    :bdbratapo13fc,
    :bdbinssfefolfc,
    :bdinssfefolfc,
    :bdaliqinssfefolfc,
    :bdCodCentro,
    :bdCODTPCC,
    :bdcredito,
    :bddebito,
    :bdBFGTSFEfc,
    :bdFGTSFEfc,
    :BDREFFC,
    :BDCODTIPOFC,
    :BDBINSSMVFC,
    :BDBINSSMV13FC,
    :BDINSSMVFC,
    :BDINSSMV13FC,
    :BDBINSSAPFC,
    :BDBINSS13APFC,
    :BDINSSAPFC,
    :BDINSS13APFC,
    :BDBINSSFN,
    :BDINSSFN,
    :BDBINSS13FN,
    :BDINSS13FN,
    :BDBINSSAPFN,
    :BDBINSS13APFN,
    :BDINSSAPFN,
    :BDINSS13APFN,
    :BDLIQUIDOFC,
    :BDDATAGRRF
  do
    begin
      bdcalctomador = 'true';
      SUSPEND;
    end
end^


--Everton - Alteração da SP_GR_SCI_EMPRESAS para receber a lista de empresas e filtrar por ela.
--          Havia casos onde ela era chamada pela view VWGR_SCI_EMPRESAS e era feito where na view
--          tornando o processo extremamente lento.
create or alter procedure SP_GR_SCI_EMPRESAS (
    PRTODOSSOCIOS integer = 0,
    PRLISTAEMPRESAS varchar(10000) = null,
    PRVERIFICACEI smallint = 0,
    PRTBTEMP smallint = 0)
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDCNPJEMP varchar(18),
    BDDATAINIATIVEMP date,
    BDORGAOEMP varchar(8),
    BDDATAREGEMP date,
    BDDATACONSTEMP date,
    BDDESCCARTEMP varchar(40),
    BDDATAFIMATIVEMP date,
    BDREFEMP integer,
    BDCODPLAPADRAO integer,
    BDCODHIST integer,
    BDCODCENTROS integer,
    BDCODPLATRIB integer,
    BDCODCID integer,
    BDCODCONT integer,
    BDCODNATJUR integer,
    BDCODCNAE integer,
    BDNOMEMP varchar(100),
    BDAPEEMP varchar(20),
    BDENDEMP varchar(60),
    BDNUMEMP DM_NUMEND,
    BDBAIEMP varchar(50),
    BDCEPEMP varchar(9),
    BDDDDEMP integer,
    BDFONEEMP varchar(15),
    BDFAXEMP varchar(15),
    BDEMAILEMP varchar(200),
    BDCOMPLEMP varchar(60),
    BDLOGREMP varchar(15),
    BDIEEMP varchar(20),
    BDIMEMP varchar(20),
    BDSITEMP varchar(5),
    BDCODPLANOONLINE integer,
    BDLOGOEMP blob sub_type 0 segment size 80,
    BDNOMESC varchar(100),
    BDINIATIVESC date,
    BDFIMATIVESC date,
    BDLOGOESC blob sub_type 0 segment size 80,
    BDLOGRESC varchar(15),
    BDENDESC varchar(60),
    BDNUMESC DM_NUMEND,
    BDBAIESC varchar(50),
    BDCEPESC varchar(9),
    BDCNPJESC varchar(18),
    BDDDDESC integer,
    BDFONEESC varchar(15),
    BDRAMALESC varchar(6),
    BDEMAILESC varchar(200),
    BDCONTTERCESC varchar(5),
    BDCOMPLESC varchar(60),
    BDFAXESC varchar(15),
    BDCODCIDESC integer,
    BDCRCESC varchar(15),
    BDAPEPLA varchar(20),
    BDNOMPLA varchar(80),
    BDNOMCID varchar(40),
    BDANIVCID varchar(4),
    BDSIGLAUF varchar(2),
    BDDESCUF varchar(40),
    BDNOMECONT varchar(40),
    BDCPFCONT varchar(14),
    BDCRCCONT varchar(15),
    BDENDCONT varchar(60),
    BDLOGRCONT varchar(15),
    BDNUMEROCONT DM_NUMEND,
    BDCOMPLCONT varchar(60),
    BDCEPCONT varchar(9),
    BDBAIRROCONT varchar(50),
    BDDDDCONT integer,
    BDFONECONT varchar(15),
    BDFAXCONT varchar(15),
    BDEMAILCONT varchar(200),
    BDCMCCONT varchar(14),
    BDESCOLARIDADECONT integer,
    BDTIPOCONTABILISTA integer,
    BDCODOCUPA integer,
    BDCODQUACONT integer,
    BDCODQUA varchar(100),
    BDREGJUN varchar(30),
    BDCODCIDSOC integer,
    BDNOMSOC varchar(80),
    BDENDSOC varchar(60),
    BDNUMSOC DM_NUMEND,
    BDCOMPLSOC varchar(60),
    BDBAISOC varchar(60),
    BDCEPSOC varchar(9),
    BDCGCCEISOC varchar(18),
    BDDDSOC integer,
    BDTELRESSOC varchar(15),
    BDTELCELSOC varchar(15),
    BDEMAILSOC varchar(200),
    BDLOGRSOC varchar(15),
    BDQUALIRESPLEGALSOC integer,
    BDEXTERIORSOC varchar(5),
    BDDATAENTSOC date,
    BDDATASAISOC date,
    BDCODPAISSOC integer,
    BDQUALIFICACAOSOC varchar(100),
    BDDESCQUALISOC varchar(100),
    BDRESPONSAVELSOC varchar(5),
    BDCPFRESPLEGALSOC varchar(14),
    BDPARAMREL integer,
    BDEXPQUALISOC integer,
    BDQUALISOCDIPJ varchar(100),
    BDDESCQUALISOCREP varchar(100),
    BDDESCQUALISOCSPED varchar(100),
    BDPERSONALIZACAO varchar(113),
    BDQTDCOTASOC numeric(15,2),
    BDVALCOTASOC numeric(15,2),
    BDPERCCOTASOC numeric(15,2),
    BDCODCONTEF integer,
    BDNOMECONTEF varchar(40),
    BDCPFCONTEF varchar(14),
    BDCRCCONTEF varchar(15),
    BDENDCONTEF varchar(60),
    BDLOGRCONTEF varchar(15),
    BDNUMEROCONTEF DM_NUMEND,
    BDCOMPLCONTEF varchar(60),
    BDCEPCONTEF varchar(9),
    BDBAIRROCONTEF varchar(50),
    BDDDDCONTEF integer,
    BDFONECONTEF varchar(15),
    BDFAXCONTEF varchar(15),
    BDEMAILCONTEF varchar(200),
    BDCMCCONTEF varchar(14),
    BDESCOLARIDADECONTEF integer,
    BDTIPOCONTABILISTAEF integer,
    BDCODOCUPAEF integer,
    BDCODCONTRH integer,
    BDNOMECONTRH varchar(40),
    BDCPFCONTRH varchar(14),
    BDCRCCONTRH varchar(15),
    BDENDCONTRH varchar(60),
    BDLOGRCONTRH varchar(15),
    BDNUMEROCONTRH DM_NUMEND,
    BDCOMPLCONTRH varchar(60),
    BDCEPCONTRH varchar(9),
    BDBAIRROCONTRH varchar(50),
    BDDDDCONTRH integer,
    BDFONECONTRH varchar(15),
    BDFAXCONTRH varchar(15),
    BDEMAILCONTRH varchar(200),
    BDCMCCONTRH varchar(14),
    BDESCOLARIDADECONTRH integer,
    BDTIPOCONTABILISTARH integer,
    BDCODOCUPARH integer,
    BDLIVRO varchar(15),
    BDFOLHA varchar(15),
    BDNOMECARTORIO varchar(100),
    BDRGSOC varchar(13),
    BDORGEMISOC varchar(20),
    BDSIGLAUFRG varchar(2),
    BDDESCUFRG varchar(40),
    BDESTCIVILSOC char(22),
    BDCODCBO integer,
    BDDESCCBO varchar(150),
    BDCODACESSOSN varchar(12),
    BDSECAOCNAE varchar(1),
    BDTIPOCNAE integer,
    BDCLASSIFICACAOCNAE varchar(20),
    BDDESCCNAE varchar(200),
    BDDESCCNAEADICIONAIS varchar(10000),
    BDNOMCIDESC varchar(40),
    BDSIGLAUFESC varchar(2),
    BDCODESC integer,
    BDCODSOC integer,
    BDCODFPAS integer,
    BDASSINATURACONTEF blob sub_type 0 segment size 80,
    BDASSINATURASOC blob sub_type 0 segment size 80,
    BDREGIMETRIBUTACAO varchar(100),
    BDTIPOAPURACAO varchar(40),
    BDCODZONA integer,
    BDNOMEZONA varchar(40),
    BDDESCNAT varchar(100),
    BDCEIEMP DM_CNPJ_CPF,
    BDCODIBGE integer,
    BDFORMATRIBUTACAO varchar(50),
    BDDESCATIVIDADE varchar(100),
    BDDESCANEXOS varchar(100),
    BDDESCANEXOS_2018 varchar(100),
    BDSOCREPRESENTANTE varchar(80),
    BDCODCLATRI integer,
    BDDATANASCSOC date,
    BDDESCENQFED varchar(6),
    BDTAREFASWEB varchar(5))
as
declare variable WSQL varchar(32000) collate WIN_PTBR;
declare variable WSQLEMPRESAS varchar(32000) collate WIN_PTBR;
declare variable WANEXOIII_2018 varchar(5);
declare variable WANEXOIV_2018 varchar(5);
declare variable WANEXOV_2018 varchar(5);
declare variable WANEXOIII varchar(5);
declare variable WANEXOIV varchar(5);
declare variable WANEXOV varchar(5);
declare variable WCOMERCIO varchar(5);
declare variable WINDUSTRIA varchar(5);
declare variable WSERVICO varchar(5);
begin
  --Ao alterar, se necessário atualizar as views GR_SCI_EMPRESAS
  IF (PRTODOSSOCIOS IS NULL) THEN
     PRTODOSSOCIOS = 0;

  prtbtemp = coalesce(prtbtemp, 0);

  if (PRLISTAEMPRESAS IS NULL) then
     WSQLEMPRESAS = 'FROM tempresas temp ';
  ELSE
     begin
       --Condições para serem colocadas na cláusula "Where"
       if (((Position(upper('IS NULL'), upper(PRLISTAEMPRESAS)) > 0) or (Position('=', PRLISTAEMPRESAS) > 0)) or (Position(upper('BETWEEN'), upper(PRLISTAEMPRESAS)) > 0) 
          or (Position(upper('BDCODEMP IN'), upper(PRLISTAEMPRESAS))>0) or (Position(upper('BDCODEMP NOT IN'), upper(PRLISTAEMPRESAS)) > 0) ) then
          WSQLEMPRESAS = 'FROM (SELECT * FROM tempresas WHERE '||PRLISTAEMPRESAS||') temp ';
       ELSE
       --LISTA DE EMPRESAS NO FORMATO "IN (COD1,..,CODN)" ou "NOT IN (COD1,..,CODN)"
       if (position(upper('IN'),upper(PRLISTAEMPRESAS)) > 0) then
          WSQLEMPRESAS = 'FROM (SELECT * FROM tempresas WHERE BDCODEMP '||PRLISTAEMPRESAS||') temp ';
       else
          --LISTA DE EMPRESAS NO FORMATO "COD1,..,CODN"
          WSQLEMPRESAS = 'FROM (SELECT * FROM tempresas WHERE BDCODEMP IN ('||PRLISTAEMPRESAS||')) temp ';
    end


  WSQL = 'SELECT temp.BDCODEMP, temp.BDCODMATRIZ, temp.BDCNPJEMP, temp.BDDATAINIATIVEMP, '||
       'tref.BDORGAOEMP, tref.BDDATAREGEMP, temp.BDDATACONSTEMP, tref.BDDESCCARTEMP, '||--alt:14844 - incluido temp.BDDATACONSTEMP. Ana - 05/08/2016
       'temp.BDDATAFIMATIVEMP, temp.BDTAREFASWEB, '||

       'tref.BDREFEMP, tref.BDCODPLAPADRAO, tref.BDCODHIST, tref.BDCODCENTROS, tref.bdcodplatrib, '||
       'tref.BDCODCID, '||
       'tref.BDCODCONT, tref.BDCODNATJUR, tref.BDCODCNAE, tref.BDNOMEMP, '||
       'tref.BDAPEEMP, tref.BDENDEMP, tref.BDNUMEMP, tref.BDBAIEMP, tref.BDCEPEMP, '||
       'tref.BDDDDEMP, tref.BDFONEEMP, tref.BDFAXEMP, tref.BDEMAILEMP, tref.BDCOMPLEMP, '||
       'tref.BDLOGREMP, tref.BDIEEMP, tref.BDIMEMP, tref.BDSITEMP, TREF.BDCODPLANOONLINE, timg.BDLOGOEMP, '||

       --Carlos Machado - 30/04/2019 - #alt:99811 - Criacao de campos para enquadramento federal e tipo de apuracao federal
       'CASE WHEN (ENQFED.BDCODENQFED in (1, 2) and (''TRUE'' in (UPPER(ATVEMP.BDCOMERCIO),UPPER(ATVEMP.BDINDUSTRIA), UPPER(ATVEMP.BDSERVICO)))) THEN ''Simples Nacional'''||
       '     WHEN (ENQFED.BDCODENQFED = 1) then ''Micro empreendedor'''||
       '     WHEN (ENQFED.BDCODENQFED = 2) then ''Empresa de pequeno porte'''||
       '     WHEN (ENQFED.BDCODENQFED = 3) then '||
                ' CASE WHEN (ENQFED.BDFORMATRIBUTACAO = 1) THEN ''Lucro presumido'''||
                '      WHEN (ENQFED.BDFORMATRIBUTACAO = 2) THEN ''Lucro real'''||
                '      WHEN (ENQFED.BDFORMATRIBUTACAO = 3) THEN ''Imune do IRPJ'''||
                '      WHEN (ENQFED.BDFORMATRIBUTACAO = 4) THEN ''Isento do IRPJ'''||
                '      ELSE ''Nenhum'' end'||
       '     WHEN (ENQFED.BDCODENQFED = 4) then ''Micro empreendedor individual'''||
       '     ELSE CADENQ.bddescenqfed END AS BDREGIMETRIBUTACAO, '||
       'case '||
         ' when (ENQFED.BDFORMATRIBUTACAO = 1) then ''Lucro presumido'''||
         ' when (ENQFED.BDFORMATRIBUTACAO = 2) then ''Lucro real'''||
         ' when (ENQFED.BDFORMATRIBUTACAO = 3) then ''Imune do IRPJ'''||
         ' when (ENQFED.BDFORMATRIBUTACAO = 4) then ''Isento do IRPJ'''||
         ' else ''Nenhum'''||
       'end as BDFORMATRIBUTACAO, '||
       'CASE WHEN (GER.BDTIPOAPURACAO = 1) THEN ''Regime de caixa'' '||
       'ELSE ''Regime de competência'' END AS BDTIPOAPURACAO, '||

       'tesc.BDNOMESC, tesc.BDINIATIVESC, tesc.BDFIMATIVESC, tesc.BDLOGOESC, tesc.BDLOGRESC, '||
       'tesc.BDENDESC, tesc.BDNUMESC, tesc.BDBAIESC, tesc.BDCEPESC, tesc.BDCNPJESC, '||
       'tesc.BDDDDESC, tesc.BDFONEESC, tesc.BDRAMALESC, tesc.BDEMAILESC, tesc.BDCONTTERCESC, '||
       'tesc.BDCOMPLESC, tesc.BDFAXESC, tesc.BDCODCID "BDCODCIDESC", tesc.BDCRCESC, '||

       'tpla.BDAPELIDO "BDAPEPLA", tpla.bdnome "BDNOMPLA", '||

       'tcid.bdnomcid, tcid.bdanivcid, '||

       'tuf.bdsiglauf, tuf.bddescuf, '||

       'tcon.bdnomecont, tcon.bdcpfcont, tcon.bdcrccont, tcon.bdendcont, '||
       'tcon.bdlogrcont, tcon.bdnumerocont, tcon.bdcomplcont, tcon.bdcepcont, '||
       'tcon.bdbairrocont, tcon.bddddcont, tcon.bdfonecont, tcon.bdfaxcont, '||
       'tcon.bdemailcont, tcon.bdcmccont, tcon.bdescolaridadecont, tcon.bdtipocontabilista, '||
       'tcon.bdcodocupa, tqcont.bdEXPQUALISOC, tqcont.bddescqualisoc, '||

       'vsuc_base_temp.bdregjun, '||

       'tsoc.BDCODCID "BDCODCIDSOC", tsoc_ref.BDNOMSOC, tsoc.BDDATANASCSOC, tsoc.BDENDSOC, tsoc.BDNUMSOC, '||
       'tsoc.BDCOMPLSOC, tsoc.BDBAISOC, tsoc.BDCEPSOC, tsoc.BDCGCCEISOC, tsoc_ref.bddddsoc AS BDDDSOC, '||
       'tsoc_ref.BDTELRESSOC, tsoc_ref.BDTELCELSOC, tsoc_ref.BDEMAILSOC, '||
       'tsoc.BDLOGRSOC, tsoc.BDQUALIRESPLEGALSOC, tsoc.BDEXTERIORSOC,tsoc.BDDATAENTSOC, '||
       'tsoc.BDDATASAISOC, tsoc.BDCODPAIS "BDCODPAISSOC", tsoc_ref.BDSOCREPRESENTANTE, tqua.bddescqualisoc, tqua.bddescqualisoc, '||
       'tsoc_ref.BDRESPONSAVELSOC, tsoc.BDCPFRESPLEGALSOC, '||
       '0, tqua.BDEXPQUALISOC, '||
       'tqdipj.bddescqualisoc, tqrep.bddescqualisoc, tqsped.bddescqualisoc, '||
       'CASE WHEN (tesc.bdprintesc = 1) THEN tesc.bdnomesc '||
       '     WHEN (tesc.bdprintesc = 2) THEN tesc.bdnomesc||'||''''||' - '||''''||'||(SELECT FIRST 1 BDPERSONALIZACAO FROM TPERSONALIZACAO) '||
       '     ELSE '||
       '     (SELECT FIRST 1 BDPERSONALIZACAO FROM TPERSONALIZACAO) END AS "bdpersonalizacao", '||
       'tcot.bdqtdcota, tcot.bdvalcota, tcot.bdperccota, '||

       'tconef.bdcodcont, tconef.bdnomecont, tconef.bdcpfcont, tconef.bdcrccont, tconef.bdendcont, '||
       'tconef.bdlogrcont, tconef.bdnumerocont, tconef.bdcomplcont, tconef.bdcepcont, '||
       'tconef.bdbairrocont, tconef.bddddcont, tconef.bdfonecont, tconef.bdfaxcont, '||
       'tconef.bdemailcont, tconef.bdcmccont, tconef.bdescolaridadecont, tconef.bdtipocontabilista,'||
       'tconef.bdcodocupa, '||

       'tconrh.bdcodcont, tconrh.bdnomecont, tconrh.bdcpfcont, tconrh.bdcrccont, tconrh.bdendcont, '||
       'tconRH.bdlogrcont, tconRH.bdnumerocont, tconRH.bdcomplcont, tconrh.bdcepcont, '||
       'tconRH.bdbairrocont, tconRH.bddddcont, tconRH.bdfonecont, tconRH.bdfaxcont, '||
       'tconRH.bdemailcont, tconRH.bdcmccont, tconRH.bdescolaridadecont, tconRH.bdtipocontabilista, '||
       'tconRH.bdcodocupa, tref.bdlivro, tref.bdfolha, tref.bdnomecartorio, tsoc.BDRGSOC, tsoc.BDORGEMISOC, '||
       'tUFSoc.bdsiglauf "BDSIGLAUFRG", tUFSoc.bddescuf "BDDESCUFRG", '||
       'CASE WHEN (tsoc.bdestcivilsoc = 0) THEN '||''''||'Solteiro'||''''||' '||
       '     WHEN (tsoc.bdestcivilsoc = 1) THEN '||''''||'Casado'||''''||' '||
       '     WHEN (tsoc.bdestcivilsoc = 2) THEN '||''''||'Divorciado'||''''||' '||
       '     WHEN (tsoc.bdestcivilsoc = 3) THEN '||''''||'Viúvo'||''''||' '||
       '     WHEN (tsoc.bdestcivilsoc = 4) THEN '||''''||'Separado judicialmente'||''''||' '||
       '     WHEN (tsoc.bdestcivilsoc = 5) THEN '||''''||'União estável'||''''||' '||
       '     WHEN (tsoc.bdestcivilsoc = 6) THEN '||''''||'Outros'||''''||' '||
       '     ELSE '||
       '     '||''''||'Não informado'||''''||' END AS "BDESTCIVILSOC", '||
       'tsoc.bdcodcbo, tCBO.bddesccbo, parfed.bdcodacessosn, '||
       'cnae.bdsecao, cnae.bdtipocnae, cnae.bdclassificacao, cnae.bddesccnae, '||
       'CAST(TRIM(COALESCE(cnae.bddesccnae, '||''''||''||''''||')||CASE WHEN (cnae.bddesccnae <> '||''''||''||''''||' AND cnaeadc.BDDESCCNAEAdicionais <> '||''''||''||''''||') THEN '||''''||'; '||''''||' ELSE '||''''||''||''''||' END||COALESCE(cnaeadc.BDDESCCNAEAdicionais, '||''''||''||''''||')) AS VARCHAR(10000)), '||
       'tcidesc.bdnomcid, ufesc.bdsiglauf, tesc.bdcodesc, tsoc.bdcodsoc, fpas.bdcodfpas, tconef.bdassinatura, tsoc.bdassinatura, tref.bdcodzona, z.bdnomezona, NATJUR.BDDESCNAT, TEMP.BDCEIEMP,tcid.bdcodibge, '||
       'ATVEMP.BDCOMERCIO, ATVEMP.BDINDUSTRIA, ATVEMP.BDSERVICO, ANX.BDANEXOIII, ANX.BDANEXOIV, ANX.BDANEXOV, ANX.BDANEXOIII_2018, ANX.BDANEXOIV_2018, ANX.BDANEXOV_2018, EMPESOC.BDCODCLATRI, CADENQ.bddescenqfed '||
WSQLEMPRESAS;

  if (prtbtemp > 0) then
     wsql = wsql||' join TMP_EMPRESAS_SELECT FILEMP on (FILEMP.BDCODEMP = TEMP.BDCODEMP) ';

  wsql = wsql||

'JOIN vw_tempresas_ref tref ON (tref.bdcodemp = temp.bdcodemp) '||
'LEFT OUTER JOIN VEF_BASE_TEMPCADATV ATVEMP ON (ATVEMP.bdcodemp = TEMP.BDCODEMP and atvemp.bdrefemp = tref.bdrefemp) '||
'LEFT OUTER JOIN TENQFED ENQFED ON (ENQFED.bdcodemp = TEMP.BDCODEMP AND ENQFED.bdrefemp = TREF.bdrefemp) '||
'LEFT OUTER JOIN TCADENQFED CADENQ ON (CADENQ.bdcodenqfed = ENQFED.bdcodenqfed)'||
'LEFT OUTER JOIN VEF_BASE_TEMPPARGER GER ON (GER.bdcodemp = TEMP.BDCODEMP AND GER.bdrefemp = TREF.bdrefemp) '||
'LEFT OUTER JOIN tempresas_img timg ON (timg.bdcodemp = temp.bdcodemp) '||
'LEFT OUTER JOIN tplano_padrao tpla ON (tpla.bdcodplapadrao = tref.bdcodplapadrao) '||
'LEFT OUTER JOIN tcidade tcid ON (tcid.bdcodcid = tref.bdcodcid) '||
'LEFT OUTER JOIN tuf ON (tuf.bdcoduf = tcid.bdcoduf) '||
'LEFT OUTER JOIN tcontador_padrao tcon ON (tcon.bdcodcont = tref.bdcodcont) '||
'LEFT OUTER JOIN tcontador_padrao tconef ON (tconef.bdcodcont = tref.bdcodcontef) '||
'LEFT OUTER JOIN tcontador_padrao tconrh ON (tconrh.bdcodcont = tref.bdcodcontrh) '||
'LEFT OUTER JOIN vsuc_base_temp ON (vsuc_base_temp.bdcodemp = temp.bdcodemp) '||
'LEFT OUTER JOIN tescritorio tesc ON (tesc.bdcodesc = tcon.bdcodesc) '||
'LEFT OUTER JOIN empresas_tsoc tsoc ON (tsoc.bdcodemp = temp.bdcodemp ';

--Celso Bahr - 03/09/2025 - #alt:231322 - Validação para quando prtodossocios = 0
  if (prtodossocios > 0) then
     wsql = wsql||'                                       AND ('||:PRTODOSSOCIOS||' <> 0 or tsoc.bdcodsoc = (SELECT FIRST 1 empresas_tsoc.bdcodsoc FROM VW_EMPRESAS_TSOC_REF EMPRESAS_TSOC ';
  else
     wsql = wsql||'                                       AND (tsoc.bdcodsoc = (SELECT FIRST 1 empresas_tsoc.bdcodsoc FROM VW_EMPRESAS_TSOC_REF EMPRESAS_TSOC ';


  wsql = wsql||
--'                                       AND ('||:PRTODOSSOCIOS||' <> 0 or tsoc.bdcodsoc = (SELECT FIRST 1 empresas_tsoc.bdcodsoc FROM VW_EMPRESAS_TSOC_REF EMPRESAS_TSOC '||

'                                                            WHERE empresas_tsoc.bdcodemp = temp.bdcodemp '||
'                                                            AND empresas_tsoc.bddataentsoc <= CURRENT_DATE '||
'                                                            AND (empresas_tsoc.bddatasaisoc >= CURRENT_DATE OR (empresas_tsoc.bddatasaisoc IS NULL))'||
'                                                            AND empresas_tsoc.bdresponsavelsoc = '||''''||'TRUE'||''''||' '||
'                                                            ORDER BY empresas_tsoc.bddataentsoc DESC))) '||
'LEFT OUTER JOIN vw_empresas_tsoc_ref_max_min socref ON (socref.bdcodemp = tsoc.bdcodemp AND socref.bdcodsoc = tsoc.bdcodsoc) '||
'LEFT OUTER JOIN empresas_tsoc_ref tsoc_ref ON (tsoc_ref.bdcodemp = socref.bdcodemp AND tsoc_ref.bdcodsoc = socref.bdcodsoc AND tsoc_ref.bdrefsoc = socref.bdrefsoc) '||


'LEFT OUTER JOIN tqualificacaosoc tqua ON (tqua.bdqualificacaosoc = tsoc.bdqualificacaosoc) '||
'LEFT OUTER JOIN empresas_tsoccotas tcot ON (tcot.bdcodemp = tsoc.bdcodemp AND tcot.bdcodsoc = tsoc.bdcodsoc '||
'                                            AND tcot.bdrefcota = (SELECT FIRST 1 empresas_tsoccotas.bdrefcota FROM empresas_tsoccotas '||
'                                                                  WHERE empresas_tsoccotas.bdcodemp = tsoc.bdcodemp '||
'                                                                  AND empresas_tsoccotas.bdcodsoc = tsoc.bdcodsoc '||
'                                                                  AND empresas_tsoccotas.bdrefcota <= (SELECT TRIM(rdb$get_context('||''''||'USER_SESSION'||''''||', '||''''||'W_ANOMES'||''''||')) FROM rdb$database) '||
'                                                                  ORDER BY empresas_tsoccotas.bdrefcota DESC)) '||
'LEFT OUTER JOIN tuf tUFSoc ON (tUFSoc.bdcoduf = tsoc.bdcodufrg) '||
'LEFT OUTER JOIN tqualificacaosoc tqdipj ON (tqdipj.bdqualificacaosoc = tsoc.bdqualilegaldipjsoc) '||
'LEFT OUTER JOIN tqualificacaosoc tqrep ON (tqrep.bdqualificacaosoc = tsoc.bdqualiresplegalsoc) '||
'LEFT OUTER JOIN tqualificacaosoc tqsped ON (tqsped.bdqualificacaosoc = tsoc.bdqualispedsoc) '||
'LEFT OUTER JOIN tqualificacaosoc tqcont ON (tqcont.bdqualificacaosoc = tcon.bdqualificacaosoc) '||
'LEFT OUTER JOIN VRH_BASE_TCBO tCBO ON (tCBO.bdcodcbo = tsoc.bdcodcbo) '||
--'LEFT OUTER JOIN VW_VEF_BASE_TEMPPARFED parfed ON (parfed.bdcodemp = temp.bdcodemp AND parfed.bdrefemp = tref.bdrefemp) '|| Alt.: #224878 - Nao deve mais olhar a referencia, a view agora ja busca referencia correta...
'LEFT OUTER JOIN VW_VEF_BASE_TEMPPARFED parfed ON (parfed.bdcodemp = temp.bdcodemp) '||
'LEFT OUTER JOIN TCNAE cnae ON (cnae.bdcodcnae = tref.bdcodcnae) '||

/*LEFT OUTER JOIN (SELECT LIST(cnaeadd.BDDESCCNAE, '; ') AS BDDESCCNAEAdicionais, cnaeadicionais.bdcodemp FROM VRH_BASE_EMP_CNAEADIC cnaeadicionais
                 LEFT OUTER JOIN TCNAE cnaeadd ON (cnaeadd.BDCODCNAE = cnaeadicionais.BDCODCNAE)
                 GROUP BY cnaeadicionais.bdcodemp) AS cnaeadc ON (cnaeadc.bdcodemp = tref.BDCODEMP)*/
--Alt:20280 - Everton - Aqui as descrições dos CNAEs adicionais precisam ser filtradas por referência, do contrário traz todas as descrições de CNAEs de todas as referências cadastradas para a empresa
'LEFT OUTER JOIN(SELECT LIST(CNAEADD.BDDESCCNAE, '||''''||'; '||''''||') AS BDDESCCNAEADICIONAIS, CNAEADICIONAIS.BDCODEMP, CNAEADICIONAIS.BDREFEMP '||
'                FROM VRH_BASE_EMP_CNAEADIC CNAEADICIONAIS '||
'                LEFT OUTER JOIN TCNAE CNAEADD ON (CNAEADD.BDCODCNAE = CNAEADICIONAIS.BDCODCNAE) '||
'                GROUP BY CNAEADICIONAIS.BDCODEMP, CNAEADICIONAIS.BDREFEMP) AS CNAEADC ON (CNAEADC.BDCODEMP = TREF.BDCODEMP) AND (CNAEADC.BDREFEMP = TREF.BDREFEMP) '||

'LEFT OUTER JOIN tcidade tcidesc ON (tcidesc.bdcodcid = tesc.bdcodcid) '||
'LEFT OUTER JOIN tuf ufesc ON (ufesc.bdcoduf = tcidesc.bdcoduf) '||
'LEFT OUTER JOIN VRHF_BASE_TEMPGPS gps ON (gps.bdcodemp = temp.bdcodemp) AND (gps.bdrefemp = tref.bdrefemp) '||
'LEFT OUTER JOIN VRH_BASE_TFPAS_TERCEIROS fpas ON (fpas.bdcodfpasterc = gps.bdcodfpasterc) '||
'LEFT OUTER JOIN TZONA z ON (z.bdcodzona = tref.bdcodzona) '||
'LEFT OUTER JOIN TNATJUR NATJUR ON (NATJUR.BDCODNATJUR = TREF.BDCODNATJUR) '||
'LEFT OUTER JOIN VEF_BASE_TEMPITEMSATV ANX on (TREF.BDCODEMP = ANX.BDCODEMP and TREF.BDREFEMP = ANX.BDREFEMP) ' ||
'LEFT OUTER JOIN VW_VRHF_BASE_TEMPESOCIAL EMPESOC on (EMPESOC.BDCODEMP = TREF.BDCODEMP) ';

  FOR EXECUTE STATEMENT WSQL
INTO :BDCODEMP, :BDCODMATRIZ, :BDCNPJEMP, :BDDATAINIATIVEMP, :BDORGAOEMP, :BDDATAREGEMP, :BDDATACONSTEMP,
     :BDDESCCARTEMP, :BDDATAFIMATIVEMP, :BDTAREFASWEB, :BDREFEMP, :BDCODPLAPADRAO, :BDCODHIST, :BDCODCENTROS, :BDCODPLATRIB, :BDCODCID,
     :BDCODCONT, :BDCODNATJUR, :BDCODCNAE, :BDNOMEMP, :BDAPEEMP, :BDENDEMP, :BDNUMEMP, :BDBAIEMP, :BDCEPEMP, :BDDDDEMP,
     :BDFONEEMP, :BDFAXEMP, :BDEMAILEMP, :BDCOMPLEMP, :BDLOGREMP, :BDIEEMP, :BDIMEMP, :BDSITEMP, :BDCODPLANOONLINE,
     :BDLOGOEMP, :BDREGIMETRIBUTACAO, :BDFORMATRIBUTACAO, :BDTIPOAPURACAO, :BDNOMESC, :BDINIATIVESC, :BDFIMATIVESC, :BDLOGOESC, :BDLOGRESC, :BDENDESC, :BDNUMESC, :BDBAIESC,
     :BDCEPESC, :BDCNPJESC, :BDDDDESC, :BDFONEESC, :BDRAMALESC, :BDEMAILESC, :BDCONTTERCESC, :BDCOMPLESC, :BDFAXESC,
     :BDCODCIDESC, :BDCRCESC, :BDAPEPLA, :BDNOMPLA, :BDNOMCID, :BDANIVCID, :BDSIGLAUF, :BDDESCUF, :BDNOMECONT,
     :BDCPFCONT, :BDCRCCONT, :BDENDCONT, :BDLOGRCONT, :BDNUMEROCONT, :BDCOMPLCONT, :BDCEPCONT, :BDBAIRROCONT,
     :BDDDDCONT, :BDFONECONT, :BDFAXCONT, :BDEMAILCONT, :BDCMCCONT, :BDESCOLARIDADECONT, :BDTIPOCONTABILISTA,
     :BDCODOCUPA, :BDCODQUACONT, :BDCODQUA, :BDREGJUN, :BDCODCIDSOC, :BDNOMSOC, :BDDATANASCSOC, :BDENDSOC, :BDNUMSOC, :BDCOMPLSOC,
     :BDBAISOC, :BDCEPSOC, :BDCGCCEISOC, :BDDDSOC, :BDTELRESSOC, :BDTELCELSOC, :BDEMAILSOC, :BDLOGRSOC,
     :BDQUALIRESPLEGALSOC, :BDEXTERIORSOC, :BDDATAENTSOC, :BDDATASAISOC, :BDCODPAISSOC, :BDSOCREPRESENTANTE, :BDQUALIFICACAOSOC,
     :BDDESCQUALISOC, :BDRESPONSAVELSOC, :BDCPFRESPLEGALSOC, :BDPARAMREL, :BDEXPQUALISOC, :BDQUALISOCDIPJ,
     :BDDESCQUALISOCREP, :BDDESCQUALISOCSPED, :BDPERSONALIZACAO, :BDQTDCOTASOC, :BDVALCOTASOC, :BDPERCCOTASOC,
     :BDCODCONTEF, :BDNOMECONTEF, :BDCPFCONTEF, :BDCRCCONTEF, :BDENDCONTEF, :BDLOGRCONTEF, :BDNUMEROCONTEF,
     :BDCOMPLCONTEF, :BDCEPCONTEF, :BDBAIRROCONTEF, :BDDDDCONTEF, :BDFONECONTEF, :BDFAXCONTEF, :BDEMAILCONTEF,
     :BDCMCCONTEF, :BDESCOLARIDADECONTEF, :BDTIPOCONTABILISTAEF, :BDCODOCUPAEF, :BDCODCONTRH, :BDNOMECONTRH,
     :BDCPFCONTRH, :BDCRCCONTRH, :BDENDCONTRH, :BDLOGRCONTRH, :BDNUMEROCONTRH, :BDCOMPLCONTRH, :BDCEPCONTRH,
     :BDBAIRROCONTRH, :BDDDDCONTRH, :BDFONECONTRH, :BDFAXCONTRH, :BDEMAILCONTRH, :BDCMCCONTRH, :BDESCOLARIDADECONTRH,
     :BDTIPOCONTABILISTARH, :BDCODOCUPARH, :BDLIVRO, :BDFOLHA, :BDNOMECARTORIO, :BDRGSOC, :BDORGEMISOC, :BDSIGLAUFRG,
     :BDDESCUFRG, :BDESTCIVILSOC, :BDCODCBO, :BDDESCCBO, :BDCODACESSOSN, :BDSECAOCNAE, :BDTIPOCNAE,
     :BDCLASSIFICACAOCNAE, :BDDESCCNAE, :BDDESCCNAEADICIONAIS, :BDNOMCIDESC, :BDSIGLAUFESC, :BDCODESC, :BDCODSOC,
     :BDCODFPAS, :BDASSINATURACONTEF, :BDASSINATURASOC, :BDCODZONA, :BDNOMEZONA, :BDDESCNAT, :BDCEIEMP, :BDCODIBGE,
     :WCOMERCIO, :WINDUSTRIA, :WSERVICO, :WANEXOIII, :WANEXOIV, :WANEXOV, :WANEXOIII_2018, :WANEXOIV_2018, :WANEXOV_2018,
     :BDCODCLATRI, :BDDESCENQFED

     DO
     BEGIN

       if (BDRESPONSAVELSOC = 'TRUE') then
         BDRESPONSAVELSOC = 'Sim';
       else 
         BDRESPONSAVELSOC = 'Não';

       if (coalesce(prverificacei, 0) = 1) then
          begin
            if ((CHAR_LENGTH(BDCEIEMP) = 15) and (CHAR_LENGTH(BDCODNATJUR) = 4) and ((POSITION('4' IN SUBSTRING(BDCODNATJUR FROM 1 FOR 1)) > 0)) or (BDCODNATJUR = '3034')) then
               BDCNPJEMP = BDCEIEMP;
          end
        --Leonardo Pereira - 14/04/2021 - #147699 - retornando novos campos concatenados
        ---Atividades
        BDDESCATIVIDADE = '';
        if (WCOMERCIO = 'TRUE') then
           begin
              BDDESCATIVIDADE = 'Comércio';
              if ((WINDUSTRIA = 'TRUE') and (WSERVICO <> 'TRUE')) then
                  BDDESCATIVIDADE = BDDESCATIVIDADE||' e ';
              else if (WINDUSTRIA = 'TRUE') then
                 BDDESCATIVIDADE = BDDESCATIVIDADE||', ';
           end
        if (WINDUSTRIA = 'TRUE') then
           BDDESCATIVIDADE = :BDDESCATIVIDADE||'Indústria';

        if (WSERVICO = 'TRUE') then
           begin
             if (BDDESCATIVIDADE <> '') then
                BDDESCATIVIDADE = :BDDESCATIVIDADE||' e ';
             BDDESCATIVIDADE = :BDDESCATIVIDADE||'Serviço';
           end
        ---Anexos
        BDDESCANEXOS = '';
        if (WANEXOIII = 'TRUE') then
           begin
             BDDESCANEXOS = 'Anexo III';

             if ((WANEXOIV = 'TRUE') and (WANEXOV <> 'TRUE')) then
                BDDESCANEXOS = BDDESCANEXOS||' e ';
              else if (WANEXOIV = 'TRUE') then
                      BDDESCANEXOS =  BDDESCANEXOS||', ';
           end
        if (WANEXOIV = 'TRUE') then
           BDDESCANEXOS = BDDESCANEXOS||'Anexo IV';

        if (WANEXOV = 'TRUE') then
           begin
             if (BDDESCANEXOS <> '') then
                BDDESCANEXOS = BDDESCANEXOS||' e ';
             BDDESCANEXOS = BDDESCANEXOS||'Anexo V';
           end
        --anexos 2018
        BDDESCANEXOS_2018 = '';
        if (WANEXOIII_2018 = 'TRUE') then
           begin
             BDDESCANEXOS_2018 = 'Anexo III';

             if ((WANEXOIV_2018 = 'TRUE') and (WANEXOV_2018 <> 'TRUE')) then
                BDDESCANEXOS_2018 = BDDESCANEXOS_2018||' e ';
              else if (WANEXOV_2018 = 'TRUE') then
                      BDDESCANEXOS_2018 =  BDDESCANEXOS_2018||', ';
           end
        if (WANEXOIV_2018 = 'TRUE') then
           BDDESCANEXOS_2018 = BDDESCANEXOS_2018||'Anexo IV';

        if (WANEXOV_2018 = 'TRUE') then
           begin
             if (BDDESCANEXOS_2018 <> '') then
                BDDESCANEXOS_2018 = BDDESCANEXOS_2018||' e ';
             BDDESCANEXOS_2018 = BDDESCANEXOS_2018||'Anexo V';
           end
       SUSPEND;
     END
end^

CREATE OR ALTER PROCEDURE FK_MANUAL_INSERT (
    TABELA_DEST VARCHAR(64) NOT NULL,
    TABELA_ATUAL VARCHAR(64) NOT NULL,
    OLD1 INTEGER,
    OLD2 INTEGER,
    NEW1 INTEGER,
    NEW2 INTEGER,
    PRUSA2 SMALLINT NOT NULL)
AS
DECLARE VARIABLE WTABELA_DEST INTEGER;
DECLARE VARIABLE WTABELA_ATU INTEGER;
begin
  if (PRUSA2 = 0) then
  begin       
    old2 = null;
    new2 = null;
  end

  IF ((OLD1 IS DISTINCT FROM NEW1 OR OLD2 IS DISTINCT FROM NEW2)) THEN
  BEGIN
    select first 1 d.bdchave from tdesc_table_banco d where d.bdtable = :tabela_atual into :wtabela_atu;
    select first 1 d.bdchave from tdesc_table_banco d where d.bdtable = :tabela_dest into :wtabela_dest;

    if (wtabela_atu is null and wtabela_dest is null) then
      EXCEPTION SALDO 'Programador, adicione uma chave na sua tabela '||tabela_atual||' e '||tabela_dest||' na tdesc_table_banco, faça na trunk, não tem problema';
    if (wtabela_atu is null) then
      EXCEPTION SALDO 'Programador, adicione uma chave na tabela '||tabela_atual||' na tdesc_table_banco, faça na trunk, não tem problema';
    if (wtabela_dest is null) then
      EXCEPTION SALDO 'Programador, adicione uma chave na tabela '||tabela_dest||' na tdesc_table_banco, faça na trunk, não tem problema';

    IF (OLD1 IS NOT NULL AND (OLD2 IS NOT NULL OR PRUSA2 = 0)) THEN
      INSERT INTO TFK_MANUAL (BDTABELA, BDCODIGO1, BDCODIGO2, BDTABELAFK, BDCOUNT) VALUES (:wtabela_dest, :OLD1, :OLD2, :wtabela_atu, -1);

    IF (new1 IS NOT NULL AND (new2 IS NOT NULL OR PRUSA2 = 0)) THEN
      INSERT INTO TFK_MANUAL (BDTABELA, BDCODIGO1, BDCODIGO2, BDTABELAFK, BDCOUNT) VALUES (:wtabela_dest, :new1, :new2, :wtabela_atu, 1);
  END
end^

CREATE OR ALTER PROCEDURE FK_MANUAL_DELETE (
    TABELA VARCHAR(64),
    OLD1 INTEGER,
    OLD2 INTEGER)
AS
DECLARE VARIABLE WTABELA_ATU INTEGER;
DECLARE VARIABLE WTABELA_FK VARCHAR(64);
begin
  select first 1 d.bdchave from tdesc_table_banco d where d.bdtable = :tabela into :wtabela_atu;

  SELECT D.BDTABLE
  FROM (SELECT FIRST 1 MAN.BDTABELAFK
        FROM TFK_MANUAL MAN
        WHERE (MAN.BDTABELA = :wtabela_atu AND
              MAN.BDCODIGO1 IS NOT DISTINCT FROM :old1 AND
              MAN.BDCODIGO2 IS NOT DISTINCT FROM :old2)
        GROUP BY MAN.BDTABELAFK
        HAVING SUM(BDCOUNT) > 0) MAN
  LEFT OUTER JOIN TDESC_TABLE_BANCO D ON (D.BDCHAVE = MAN.BDTABELAFK)
  INTO :wtabela_fk;

  IF (wtabela_fk IS NOT NULL) THEN
    EXCEPTION EX_DELETE wtabela_fk;
end^

/* Restore proc. body: VRHF_SP_TIPO_TOMADOR_GPS */
create or alter procedure VRHF_SP_TIPO_TOMADOR_GPS (
    PRCENCUS integer,
    PRPLANOCUS integer,
    PRREF integer,
    PR13 smallint = 0)
returns (
    BDCODCENCUS integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCTALON varchar(40),
    BDTIPCTA smallint,
    BDNOMCTA varchar(40),
    BDAPECTA varchar(20),
    BDFILTROGER varchar(20),
    BDCLANOM varchar(80),
    BDTIPO integer,
    BDCNPJTOM varchar(18),
    BDTIPOTOM integer,
    BDTIPOFERTOM integer,
    BDSOMSALFERTOM varchar(5),
    BDTIPO13TOM integer,
    BDSOMSAL13TOM varchar(5),
    BDNOMETOM varchar(70),
    BDAPELIDO varchar(20),
    BDNOME varchar(40))
as
declare variable WTIPOTOM integer;
declare variable WCLASSIFICACAO varchar(80);
declare variable WSQL varchar(1000);
declare variable WTIPO integer;
declare variable WSQLRETORNO varchar(1000);
declare variable WSQLDADOSPERC varchar(1000);
declare variable WDP integer;
declare variable WCLASS varchar(80);
declare variable WPONTO integer;
BEGIN
  /*
    bdtipo = 1 Tomador
   */
  IF (prplanocus IS NULL) THEN
     prplanocus = 0;

  IF (prcencus IS NULL) THEN
     prcencus = 0;

  bdcodcencus = prcencus;

  select TPCC.BDCTALON,TPCC.BDTIPO,TOM.bdtipotom FROM centros_tpcc TPCC
  LEFT OUTER JOIN vrh_base_tcustom TOM ON (TOM.BDCODCENTRO = TPCC.BDCODCENTRO AND TOM.BDCODTPCC = TPCC.BDCODTPCC)
  where TPCC.bdcodcentro = :prplanocus and
        TPCC.bdcodtpcc = :prcencus
  INTO wclassificacao,wtipo, wtipotom;

  select TOM.BDNOMETOM, TOM.BDCODCENTRO from vrh_base_tcustom TOM
  where TOM.bdcodcentro = :prplanocus and TOM.bdcodtpcc = :prcencus
  into BDNOMETOM, BDCODCENTRO;

  IF (pr13 = 0) THEN
    BEGIN
      select first 1 COALESCE(BDDADPERTOM,0) from VRH_BASE_TCUSTOM_GPS
      where BDCODCENTRO = :prplanocus and BDCODTPCC = :prcencus and BDREFCUSTO <= :prref
      order by bdrefcusto desc
      INTO :wdp;
    END
  ELSE
    wdp = 0;

  IF ((wdp IS NULL) OR (wtipo <> 1)) THEN
    wdp = 0;

  IF ((wdp = 0) and ((wtipo <> 1) OR ((wtipotom = 0) OR (wtipotom IS NULL))) AND (prcencus <> 0)) THEN
--  IF ((wdp = 0) AND ((wtipo <> 1) OR (wtipotom <> 0) OR (wtipotom IS NULL)) AND (prcencus <> 0)) THEN
     BEGIN
       prcencus = NULL;
       wclass = REVERSE(:wclassificacao);
       wponto = POSITION('.' IN :wclass);
       IF (wponto > 0) THEN
         BEGIN
           wclass = SUBSTRING(:wclass FROM wponto + 1 FOR char_length(:wclass));
           wclass = REVERSE(:wclass);

           SELECT FIRST 1 tpcc.bdctalon, tpcc.BDTIPO, tpcc.bdcodtpcc
              FROM centros_tpcc tpcc
              LEFT OUTER JOIN vrh_base_tcustom TOM ON (TOM.BDCODCENTRO = TPCC.BDCODCENTRO AND TOM.BDCODTPCC = TPCC.BDCODTPCC)
              LEFT OUTER JOIN (select BDCODCENTRO, BDCODTPCC, max(BDREFCUSTO) BDREFCUSTO from VRH_BASE_TCUSTOM_GPS where BDCODCENTRO = :prplanocus and BDREFCUSTO <= :prref group by BDCODCENTRO, BDCODTPCC) gps2 ON (gps2.bdcodcentro = tom.bdcodcentro AND gps2.bdcodtpcc = tom.bdcodtpcc)
              LEFT OUTER JOIN VRH_BASE_TCUSTOM_GPS gps ON (gps.bdcodcentro = tom.bdcodcentro AND gps.bdcodtpcc = tom.bdcodtpcc and gps.bdrefcusto = gps2.bdrefcusto)
              WHERE tpcc.bdctalon = :wclass
                    AND tpcc.bdcodcentro = :prplanocus AND tpcc.bdtipo = 1 AND ((tom.bdtipotom IN (0, 2)) OR (TRIM(UPPER(gps.bdanexovi)) = 'TRUE') OR (gps.bddadpertom IN (1,4,6)))   /* Projeto */
              ORDER BY tpcc.BDCTALON DESC
              INTO :wclassificacao,:wtipo,:prcencus;
         END

       IF (prcencus IS NULL) THEN
          prcencus = 0;

     END

  select TPCC.BDCODCENTRO, TPCC.BDCODTPCC, TPCC.BDCTALON, TPCC.BDTIPCTA, TPCC.BDNOMCTA, TPCC.BDAPECTA, TPCC.BDFILTROGER,
         TPCC.BDCLANOM, TPCC.BDTIPO, TOM.BDCNPJTOM, TOM.BDTIPOTOM, TOM.BDTIPOFERTOM, TOM.BDSOMSALFERTOM, TOM.BDTIPO13TOM, TOM.BDSOMSAL13TOM,
         TOM.BDNOMETOM, PCC.BDAPELIDO, PCC.BDNOME from centros_tpcc TPCC
  left outer join vrh_base_tcustom TOM on (TOM.BDCODCENTRO = TPCC.BDCODCENTRO and
                                           TOM.BDCODTPCC = TPCC.BDCODTPCC)
  left outer join tcentros PCC on (PCC.BDCODCENTRO = TPCC.BDCODCENTRO)
  where TPCC.bdcodcentro = :prplanocus and
        TPCC.bdcodtpcc = :prcencus
  INTO
    :bdcodcentro ,
    :bdcodtpcc ,
    :bdctalon ,
    :bdtipcta ,
    :bdnomcta ,
    :bdapecta ,
    :bdfiltroger ,
    :bdclanom ,
    :bdtipo ,
    :bdcnpjtom ,
    :bdtipotom ,
    :bdtipofertom ,
    :bdsomsalfertom ,
    :bdtipo13tom ,
    :bdsomsal13tom ,
    :bdnometom ,
    :bdapelido ,
    :bdnome;

  SUSPEND;
END^

/* Restore proc. body: VRHF_SP_TNFCOOP */
create or alter procedure VRHF_SP_TNFCOOP (
    PRCODEMP varchar(32000),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer,
    PRPUXAFILIAIS integer,
    PRCODIMP integer = 0)
returns (
    BDCODEMP integer,
    BDCHAVE integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDREFNF integer,
    BDNOTAFISCAL varchar(15),
    BDDATAEMINF date,
    BDVALLIQNF numeric(15,6),
    BDVALNF numeric(15,6))
as
declare variable WCAMPOEMP varchar(150);
declare variable WWHERET varchar(32000);
declare variable WSQL varchar(32000);
declare variable WJOINFILIAL varchar(32000);
BEGIN
  /* pragrupatomador
     0 = Nao agrupa
     1 = Agrupa por referencia
     2 = Agrupo por referencia e centro/Tomador
     3 = Agrupa por referencia e Tomador (se nao for tomador verifica pela classificacao e nao encontrando considera empresa)
     4 = Agrupa por referencia e Tipo Tomador (so vai criar mais registros pra empresa se for tomador 155)
  */
  wwheret = '';

  IF (prpuxafiliais IS NULL) THEN
     prpuxafiliais = 0;

  wjoinfilial = '';
  IF (prpuxafiliais = 0) THEN
     wcampoemp = 'COLCON.BDCODEMP xbdcodemp';
  ELSE
     BEGIN
       wcampoemp = 'case when temp.bdcodmatriz is not null then temp.bdcodmatriz else temp.bdcodemp end xbdcodemp';

       IF (prcodimp <> 0) THEN
          BEGIN
            wcampoemp = 'impemp.bdempimp xbdcodemp';

            wjoinfilial = ' join (select colcon.bdcodemp, case when ei.bdcodimp is null then colcon.bdcodmatriz else colcon.bdcodemp end bdempimp '||
                          ' from tempresas colcon left outer join vw_tempresaimpostoref ei on (ei.bdcodemp = colcon.bdcodemp and ei.bdcodimp = '||prcodimp||') ';

            IF (prcodemp IS NOT NULL) THEN
               wjoinfilial = wjoinfilial||' where '||prcodemp;

            wjoinfilial = wjoinfilial||' group by colcon.bdcodemp, bdempimp ) impemp on (impemp.bdcodemp = colcon.bdcodemp) ';
          END
     END


  IF (prcodemp IS NOT NULL) THEN
     BEGIN
       IF (wwheret <> '') THEN
          BEGIN
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheret = wwheret||' where ';
          END

       wwheret = wwhereT||prcodemp;
     END

  IF ((prrefini IS NOT NULL) AND (prreffim IS NOT NULL)) THEN
     BEGIN
       IF (wwheret <> '') THEN
          BEGIN
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheret = wwheret||' where ';
          END

       wwheret = wwhereT||'COLCON.BDREFNF >= '||prrefini||' and '||'COLCON.BDREFNF <= '||prreffim;
     END
  ELSE
     BEGIN
       IF (prrefini IS NOT NULL) THEN
          BEGIN
            IF (wwheret <> '') THEN
               BEGIN
                 wwheret = wwheret||' and ';
               END
            ELSE
               BEGIN
                 wwheret = wwheret||' where ';
               END

            wwheret = wwhereT||'COLCON.BDREFNF = '||prrefini;
          END
       ELSE
          BEGIN
            IF (prreffim IS NOT NULL) THEN
               BEGIN
                 IF (wwheret <> '') THEN
                    BEGIN
                      wwheret = wwheret||' and ';
                    END
                 ELSE
                    BEGIN
                      wwheret = wwheret||' where ';
                    END

                 wwheret = wwhereT||'COLCON.BDREFNF = '||prreffim;
               END
          END
     END

  IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 4)) THEN
     BEGIN
          wsql = 'select '||
                 wcampoemp||', '||
                 ' cast(null as integer), '||
                 ' COLCON.BDCODCENTRO,'||
                 ' toma.bdCODTPCC,' ||
                 ' COLCON.BDREFNF,'||
                 ' cast(null as integer),'||
                 ' cast(null as date),'||
                 ' sum(COLCON.BDVALLIQNF),'||
                 ' sum(COLCON.BDVALNF) '||
                 ' from vrhf_emp_tnfcoop COLCON'||
                 wjoinfilial||
                 ' left outer join VRHF_SP_TIPO_TOMADOR_GPS(COLCON.bdcodtpcc,COLCON.bdcodcentro,'||prrefini||') toma on (toma.bdcodcencus = COLCON.bdcodtpcc and toma.bdcodcentro = COLCON.bdcodcentro)'||
                 ' left outer join tempresas temp on (COLCON.bdcodemp = temp.bdcodemp)'||
                 wwheret||
                 ' group by xbdcodemp,colcon.BDREFNF,COLCON.bdCodCentro, toma.bdCODTPCC';
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 3)) THEN
     BEGIN
          wsql = 'select '||
                 wcampoemp||', '||
                 ' cast(null as integer), '||
                 ' COLCON.BDCODCENTRO,'||
                 ' toma.bdCODTPCC,' ||
                 ' COLCON.BDREFNF,'||
                 ' cast(null as integer),'||
                 ' cast(null as date),'||
                 ' sum(COLCON.BDVALLIQNF),'||
                 ' sum(COLCON.BDVALNF) '||
                 ' from vrhf_emp_tnfcoop COLCON'||
                 wjoinfilial||
                 ' left outer join vrhf_sp_tomador(COLCON.bdcodtpcc,COLCON.bdcodcentro) toma on (toma.bdcodcencus = COLCON.bdcodtpcc and toma.bdcodcentro = COLCON.bdcodcentro)'||
                 ' left outer join tempresas temp on (COLCON.bdcodemp = temp.bdcodemp)'||
                 wwheret||
                 ' group by xbdcodemp,colcon.BDREFNF,COLCON.bdCodCentro, toma.bdCODTPCC';
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 2)) THEN
     BEGIN
          wsql = 'select '||
                 wcampoemp||', '||
                 ' cast(null as integer), '||
                 ' COLCON.BDCODCENTRO,'||
                 ' COLCON.bdCODTPCC,' ||
                 ' COLCON.BDREFNF,'||
                 ' cast(null as integer),'||
                 ' cast(null as date),'||
                 ' sum(COLCON.BDVALLIQNF),'||
                 ' sum(COLCON.BDVALNF) '||
                 ' from vrhf_emp_tnfcoop COLCON'||
                 wjoinfilial||
                 ' left outer join tempresas temp on (COLCON.bdcodemp = temp.bdcodemp)'||
                 wwheret||
                 ' group by xbdcodemp,colcon.BDREFNF,COLCON.bdCodCentro, COLCON.bdCODTPCC';
     END
  ELSE IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador = 1)) THEN
     BEGIN
          wsql = 'select '||
                 wcampoemp||', '||
                 ' cast(null as integer), '||
                 ' cast(null as integer),'||
                 ' cast(null as integer),' ||
                 ' COLCON.BDREFNF,'||
                 ' cast(null as integer),'||
                 ' cast(null as date),'||
                 ' sum(COLCON.BDVALLIQNF),'||
                 ' sum(COLCON.BDVALNF) '||
                 ' from vrhf_emp_tnfcoop COLCON'||
                 wjoinfilial||
                 ' left outer join tempresas temp on (COLCON.bdcodemp = temp.bdcodemp)'||
                 wwheret||
                 ' group by xbdcodemp,colcon.BDREFNF';
     END
  ELSE
     BEGIN
          wsql = 'select '||
                 wcampoemp||', '||
                 ' COLCON.BDCHAVE,'||
                 ' COLCON.BDCODCENTRO,'||
                 ' COLCON.bdCODTPCC,' ||
                 ' COLCON.BDREFNF,'||
                 ' COLCON.BDNOTAFISCAL,'||
                 ' COLCON.BDDATAEMINF,'||
                 ' COLCON.BDVALLIQNF,'||
                 ' COLCON.BDVALNF '||
                 ' from vrhf_emp_tnfcoop COLCON'||
                 wjoinfilial||
                 ' left outer join tempresas temp on (COLCON.bdcodemp = temp.bdcodemp)'||
                 wwheret;
     END

  FOR EXECUTE STATEMENT wsql INTO
    : bdcodemp ,
    : bdchave ,
    : bdcodcentro ,
    : bdcodtpcc ,
    : bdrefnf ,
    : bdnotafiscal ,
    : bddataeminf ,
    : bdvalliqnf,
    : bdvalnf
  DO
    BEGIN
      SUSPEND;
    END
END^

/* Restore proc. body: VRHF_SP_TODAS_GPS */
ALTER PROCEDURE VRHF_SP_TODAS_GPS(PRCODEMP VARCHAR(32000),
PRCODCOL VARCHAR(22000),
PRCODAUT VARCHAR(10000),
PRTIPOCOL INTEGER,
PRANOMES INTEGER,
PRANOMESPAG INTEGER,
PRAPENASGPS INTEGER,
PRTIPOGPS INTEGER,
PRPUXAFILIAIS INTEGER)
 RETURNS(BDTIPOREG INTEGER,
BDCODEMP INTEGER,
BDREFFN INTEGER,
BDREFPAG INTEGER,
BDCODTPCC INTEGER,
BDTOTSEG NUMERIC(15,6),
BDTOTBASE NUMERIC(15,6),
BDSEGFUN NUMERIC(15,6),
BDBASEFUN NUMERIC(15,6),
BDPERCFUN NUMERIC(15,6),
BDVALFUNEMP NUMERIC(15,6),
BDSEGPRO NUMERIC(15,6),
BDBASEPRO NUMERIC(15,6),
BDPERCPRO NUMERIC(15,6),
BDVALPROEMP NUMERIC(15,6),
BDSEGAUT NUMERIC(15,6),
BDBASEAUT NUMERIC(15,6),
BDPERCAUT NUMERIC(15,6),
BDVALAUTEMP NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDSALMATERNIDADE NUMERIC(15,6),
BDBASERATAPO NUMERIC(15,6),
BDVALORRATAPO NUMERIC(15,6),
BDBASEFPAS NUMERIC(15,6),
BDPERCFPAS NUMERIC(15,6),
BDVALORFPAS NUMERIC(15,6),
BDPERCRAT NUMERIC(15,6),
BDVALORRAT NUMERIC(15,6),
BDVALORBRUTO NUMERIC(15,6),
BDVALORLIQUIDO NUMERIC(15,6),
BDNFCOOP NUMERIC(15,6),
BDCHAVE INTEGER,
BDVALCOMPENSADO NUMERIC(15,6),
BDVALACOMPENSAR NUMERIC(15,6),
BDVALORACUMULADO NUMERIC(15,6),
BDVALORACUMULADOUSADO NUMERIC(15,6),
BDVALORACUMUTERCEIRO NUMERIC(15,6),
BDVALORACUTERCEIROSUSADO NUMERIC(15,6),
BDCODEMPANT INTEGER,
BDCODIMPANT INTEGER,
BDCODPERIODOANT INTEGER,
BDORDEMANT INTEGER,
BDREFERENCIAANT INTEGER,
BDQUOTAANT INTEGER,
BDDESCACUMDET VARCHAR(3000),
BDDESCACU VARCHAR(3000),
BDVALORCAMPO6 NUMERIC(15,6),
BDVALORNOTAS NUMERIC(15,6),
BDTOTVALORACUMULADO NUMERIC(15,6),
BDTOTVALORACUMULADOTERC NUMERIC(15,6),
BDINICOMP INTEGER,
BDFIMCOMP INTEGER,
BDTOTCOMPENSACAO NUMERIC(15,6),
BDDESCNOTAS NUMERIC(15,6),
BDTOTDESCCOMP NUMERIC(15,6),
BDDESCSALFAM NUMERIC(15,6),
BDDESCDEDGPS NUMERIC(15,6),
BDVALOUTENTIDADES NUMERIC(15,6),
BDSIMPLESGPS INTEGER,
BDCODENQFED INTEGER,
BDDESCENQFED VARCHAR(10),
BDCHAVEDARF INTEGER)
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODIMP INTEGER;
DECLARE VARIABLE WWHEREEMP VARCHAR(30000);
DECLARE VARIABLE WCODIMPANT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WSQLGPS VARCHAR(30000);
DECLARE VARIABLE WPARAMETROS VARCHAR(30000);
BEGIN
  /* PRTIPOCOL
     0 = Todos
     1 = Colaboradores
     2 = Autonomos
   */

  /* Procedure Text */
  IF (prcodemp IS NULL) THEN
     prcodemp = 'null';
  ELSE
     prcodemp = ''''||prcodemp||'''';

  IF (pranomes IS NULL) THEN
     pranomes = 0;

  wsql = 'select bdCODIMP,BDCODEMP from sp_tempresaimposto_ref('||prcodemp||','||pranomes||',0)'||
         ' where BDDOCARRECADACAO = 12'||
         ' order by bdCODIMP,BDCODEMP';
--  select * from vrhf_sp_calc_gps(9053,'colcon.bdcodemp = 3',null,201005,201005,0,0,0)

  wparametros = '';
  IF (prcodcol IS NULL) THEN
     wparametros = 'null,';
  ELSE
     wparametros = ''''||prcodcol||''''||',';

  IF (prcodaut IS NULL) THEN
     wparametros = wparametros||'null,';
  ELSE
     wparametros = wparametros||''''||prcodaut||''''||',';

  IF (prtipocol IS NULL) THEN
     wparametros = wparametros||'null,';
  ELSE
     wparametros = wparametros||prtipocol||',';

  IF (pranomes IS NULL) THEN
     wparametros = wparametros||'null,';
  ELSE
     BEGIN
       wparametros = wparametros||pranomes||',';
       EXECUTE PROCEDURE sp_seta_competencia(pranomes,NULL,NULL);
     END

  IF (pranomespag IS NULL) THEN
     wparametros = wparametros||'null,';
  ELSE
     BEGIN
       wparametros = wparametros||pranomespag||',';
       EXECUTE PROCEDURE sp_seta_competencia(pranomespag,NULL,NULL);
     END

  IF (prapenasgps IS NULL) THEN
     wparametros = wparametros||'null,';
  ELSE
     wparametros = wparametros||prapenasgps||',';

  IF (prtipogps IS NULL) THEN
     wparametros = wparametros||'null,';
  ELSE
     wparametros = wparametros||prtipogps||',';

  IF (prpuxafiliais IS NULL) THEN
     wparametros = wparametros||'null)';
  ELSE
     wparametros = wparametros||prpuxafiliais||')';

  wcodimpant = -1;
  wwhereemp = '';
  FOR EXECUTE STATEMENT wsql INTO wcodimp,wcodemp DO
  BEGIN
--    suspend;
     IF ((wcodimpant = -1) OR (wcodimp = wcodimpant)) THEN
        BEGIN
          wcodimpant = wcodimp;
          IF (wwhereemp <> '') THEN
             wwhereemp = wwhereemp||',';

          wwhereemp = wwhereemp||wcodemp;
        END
     ELSE
        BEGIN
          wsqlgps = 'select '||
                    ' bdtiporeg, bdcodemp, bdreffn, bdrefpag, bdcodtpcc, bdtotseg, bdtotbase, bdsegfun, bdbasefun,'||
                    ' bdpercfun, bdvalfunemp, bdsegpro, bdbasepro, bdpercpro, bdvalproemp, bdsegaut, bdbaseaut, bdpercaut,'||
                    ' bdvalautemp, bdsalfam, bdsalmaternidade, bdbaseratapo, bdvalorratapo, bdbasefpas, bdpercfpas, bdvalorfpas,'||
                    ' bdpercrat, bdvalorrat, bdvalorbruto, bdvalorliquido, bdnfcoop, bdchave, bdvalcompensado, bdvalacompensar,'||
                    ' bdvaloracumulado, bdvaloracumuladousado, bdvaloracumuterceiro, bdvaloracuterceirosusado, bdcodempant,'||
                    ' bdcodimpant, bdcodperiodoant, bdordemant, bdreferenciaant, bdquotaant, bddescacumdet, bddescacu,'||
                    ' bdvalorcampo6, bdvalornotas, bdtotvaloracumulado, bdtotvaloracumuladoterc, bdinicomp, bdfimcomp, bdtotcompensacao, '||
                    ' BDDESCNOTAS, BDTOTDESCCOMP, bddescsalfam, bddescdedgps, BDVALOUTENTIDADES, bdsimplesgps, bdcodenqfed,'||
                    ' bddescenqfed, BDCHAVEDARF '||
                    ' from vrhf_sp_calc_gps('||wcodimpant||','||''''||'colcon.bdcodemp in ('||wwhereemp||')'||''''||','||wparametros;



          FOR EXECUTE STATEMENT wsqlgps INTO
              :bdtiporeg, :bdcodemp, :bdreffn, :bdrefpag, :bdcodtpcc, :bdtotseg, :bdtotbase, :bdsegfun, :bdbasefun,
              :bdpercfun, :bdvalfunemp, :bdsegpro, :bdbasepro, :bdpercpro, :bdvalproemp, :bdsegaut, :bdbaseaut, :bdpercaut,
              :bdvalautemp, :bdsalfam, :bdsalmaternidade, :bdbaseratapo, :bdvalorratapo, :bdbasefpas, :bdpercfpas, :bdvalorfpas,
              :bdpercrat, :bdvalorrat, :bdvalorbruto, :bdvalorliquido, :bdnfcoop, :bdchave, :bdvalcompensado, :bdvalacompensar,
              :bdvaloracumulado, :bdvaloracumuladousado, :bdvaloracumuterceiro, :bdvaloracuterceirosusado, :bdcodempant,
              :bdcodimpant, :bdcodperiodoant, :bdordemant, :bdreferenciaant, :bdquotaant, :bddescacumdet, :bddescacu,
              :bdvalorcampo6, :bdvalornotas, :bdtotvaloracumulado, :bdtotvaloracumuladoterc, :bdinicomp, :bdfimcomp,
              :bdtotcompensacao, :bddescnotas,: bdtotdesccomp, :bddescsalfam, :bddescdedgps, :BDVALOUTENTIDADES, :bdsimplesgps, :bdcodenqfed,
              :bddescenqfed, :BDCHAVEDARF  DO
              SUSPEND;

          wcodimpant = wcodimp;
          wwhereemp = ''||wcodemp;
        END
  END

  IF (wcodimpant <> -1) THEN
     BEGIN
          wsqlgps = 'select '||
                    ' bdtiporeg, bdcodemp, bdreffn, bdrefpag, bdcodtpcc, bdtotseg, bdtotbase, bdsegfun, bdbasefun,'||
                    ' bdpercfun, bdvalfunemp, bdsegpro, bdbasepro, bdpercpro, bdvalproemp, bdsegaut, bdbaseaut, bdpercaut,'||
                    ' bdvalautemp, bdsalfam, bdsalmaternidade, bdbaseratapo, bdvalorratapo, bdbasefpas, bdpercfpas, bdvalorfpas,'||
                    ' bdpercrat, bdvalorrat, bdvalorbruto, bdvalorliquido, bdnfcoop, bdchave, bdvalcompensado, bdvalacompensar,'||
                    ' bdvaloracumulado, bdvaloracumuladousado, bdvaloracumuterceiro, bdvaloracuterceirosusado, bdcodempant,'||
                    ' bdcodimpant, bdcodperiodoant, bdordemant, bdreferenciaant, bdquotaant, bddescacumdet, bddescacu,'||
                    ' bdvalorcampo6, bdvalornotas, bdtotvaloracumulado, bdtotvaloracumuladoterc, bdinicomp, bdfimcomp, bdtotcompensacao, '||
                    ' BDDESCNOTAS,BDTOTDESCCOMP, bddescsalfam, bddescdedgps, BDVALOUTENTIDADES, bdsimplesgps, bdcodenqfed,'||
                    ' bddescenqfed, BDCHAVEDARF '||
                    ' from vrhf_sp_calc_gps('||wcodimpant||','||''''||'colcon.bdcodemp in ('||wwhereemp||')'||''''||','||wparametros;


          FOR EXECUTE STATEMENT wsqlgps INTO
              :bdtiporeg, :bdcodemp, :bdreffn, :bdrefpag, :bdcodtpcc, :bdtotseg, :bdtotbase, :bdsegfun, :bdbasefun,
              :bdpercfun, :bdvalfunemp, :bdsegpro, :bdbasepro, :bdpercpro, :bdvalproemp, :bdsegaut, :bdbaseaut, :bdpercaut,
              :bdvalautemp, :bdsalfam, :bdsalmaternidade, :bdbaseratapo, :bdvalorratapo, :bdbasefpas, :bdpercfpas, :bdvalorfpas,
              :bdpercrat, :bdvalorrat, :bdvalorbruto, :bdvalorliquido, :bdnfcoop, :bdchave, :bdvalcompensado, :bdvalacompensar,
              :bdvaloracumulado, :bdvaloracumuladousado, :bdvaloracumuterceiro, :bdvaloracuterceirosusado, :bdcodempant,
              :bdcodimpant, :bdcodperiodoant, :bdordemant, :bdreferenciaant, :bdquotaant, :bddescacumdet, :bddescacu,
              :bdvalorcampo6, :bdvalornotas, :bdtotvaloracumulado, :bdtotvaloracumuladoterc, :bdinicomp, :bdfimcomp,
              :bdtotcompensacao,:BDDESCNOTAS,:BDTOTDESCCOMP, :bddescsalfam, :bddescdedgps, :BDVALOUTENTIDADES, :bdsimplesgps, :bdcodenqfed,
              :bddescenqfed, :BDCHAVEDARF DO
              SUSPEND;
     END
END
^

/* Restore proc. body: VRHF_SP_TOMADOR */
ALTER PROCEDURE VRHF_SP_TOMADOR(PRCENCUS INTEGER,
PRPLANOCUS INTEGER)
 RETURNS(BDCODCENCUS INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCTALON VARCHAR(40),
BDTIPCTA SMALLINT,
BDNOMCTA VARCHAR(40),
BDAPECTA VARCHAR(20),
BDFILTROGER VARCHAR(20),
BDCLANOM VARCHAR(80),
BDTIPO INTEGER,
BDCNPJTOM VARCHAR(18),
BDTIPOTOM INTEGER,
BDTIPOFERTOM INTEGER,
BDSOMSALFERTOM VARCHAR(5),
BDTIPO13TOM INTEGER,
BDSOMSAL13TOM VARCHAR(5),
BDNOMETOM VARCHAR(70),
BDAPELIDO VARCHAR(20),
BDNOME VARCHAR(40),
BDTIPODOCTOM INTEGER,
BDCODLOT integer,
BDCODLOTACAO varchar(30),
BDCODESTAB varchar(30))
 AS
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(80);
declare variable WCLASSAUX varchar(80);
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WTIPO INTEGER;
DECLARE VARIABLE WSQLRETORNO VARCHAR(1000);
DECLARE VARIABLE WPOS INTEGER;
BEGIN
  /*
    bdtipo = 1 Tomador
   */
  IF (prplanocus IS NULL) THEN
     prplanocus = 0;

  IF (prcencus IS NULL) THEN
     prcencus = 0;
  bdcodcencus = prcencus;
  select cla.BDCTALON,cla.BDTIPO from centros_tpcc cla where cla.bdcodcentro = :prplanocus and cla.bdcodtpcc = :prcencus INTO wclassificacao,wtipo;

  --Ajustado pra fazer um laço destrinchando a classificação, caso ache um tomador na classificação pai, utiliza esse, caso chegue na título e não achar nenhum tomador, irá utilizar a empresa msm.
  if (wtipo <> 1) then
    begin
     wclassaux = wclassificacao;
     prcencus = null;

    while (wclassaux is not null) do
    begin
       wtipo = null;

       select first 1 cla.bdcodtpcc, cla.bdtipo
       from centros_tpcc cla
       where cla.bdcodcentro = :prplanocus
       and cla.bdctalon = :wclassaux
       into :prcencus, :wtipo;
    
       if (wtipo = 1) then
          leave;

       prcencus = null;
    
       wpos = position('.', reverse(wclassaux));
    
       if (wpos = 0) then
         wclassaux = null;
       else
         wclassaux = substring(wclassaux from 1 for char_length(wclassaux) - wpos);
    end

     if (prcencus is null) then
        prcencus = 0;
   end

  select TPCC.BDCODCENTRO, TPCC.BDCODTPCC, TPCC.BDCTALON, TPCC.BDTIPCTA, TPCC.BDNOMCTA, TPCC.BDAPECTA, TPCC.BDFILTROGER,
         TPCC.BDCLANOM, TPCC.BDTIPO, TOM.BDCNPJTOM, TOM.BDTIPOTOM, TOM.BDTIPOFERTOM, TOM.BDSOMSALFERTOM, TOM.BDTIPO13TOM, TOM.BDSOMSAL13TOM,
         TOM.BDNOMETOM, PCC.BDAPELIDO, PCC.BDNOME, case when STRLEN(TRIM(TOM.BDCNPJTOM)) >= 18 then 0 else 1 end BDTIPODOCTOM,
         TOM.BDCODLOT, TOM.BDCODLOTACAO, TOM.BDCODESTAB from centros_tpcc TPCC
         left outer join vrh_base_tcustom TOM on (TOM.BDCODCENTRO = TPCC.BDCODCENTRO and TOM.BDCODTPCC = TPCC.BDCODTPCC)
         left outer join tcentros PCC on (PCC.BDCODCENTRO = TPCC.BDCODCENTRO)
         where TPCC.bdcodcentro = :prplanocus and TPCC.bdcodtpcc = :prcencus
  INTO
    :bdcodcentro ,
    :bdcodtpcc ,
    :bdctalon ,
    :bdtipcta ,
    :bdnomcta ,
    :bdapecta ,
    :bdfiltroger ,
    :bdclanom ,
    :bdtipo ,
    :bdcnpjtom ,
    :bdtipotom ,
    :bdtipofertom ,
    :bdsomsalfertom ,
    :bdtipo13tom ,
    :bdsomsal13tom ,
    :bdnometom ,
    :bdapelido ,
    :bdnome,
    :bdtipodoctom,
    :BDCODLOT,
    :BDCODLOTACAO,
    :BDCODESTAB;
  SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_TOTAL_COL_ATIVOS */
ALTER PROCEDURE VRHF_SP_TOTAL_COL_ATIVOS(PRCODEMP INTEGER,
PRREF INTEGER,
PRDATAADMISSAO DATE)
 RETURNS(TTATIVOS INTEGER)
 AS
DECLARE VARIABLE wsql VARCHAR(15000);
BEGIN


  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

    wSql = 'select ';
--    if (:PRCODEMP is not null) then
      wSql = wSql || 'count(COL.BDCODEMP) TTATIVOS';
--    else
--      wSql = wSql || 'col.bdcodemp, count(COL.BDCODEMP) ';

    wSql = wSql || ' from vw_colaboradores COL ';
    wSql = wSql || ' left outer join VW_EMPRESAS_REF_ATUAL EMP on (COL.bdcodemp = EMP.bdcodemp) ';
--    if (:PRCODEMP is not null) then
--      begin
        wSql = wSql ||'where col.bdcodemp = '||:PRCODEMP;
--        wSql = wSql ||' and  ( col.bddataadmcol <= '||:prdataini||')';
--      end
--    else
      wSql = wSql ||' and  ( col.bddataadmcol <= '''||:prdataadmissao||''')';


    wSql = wSql || ' AND (  not exists ( select REC.BDCODEMP, REC.BDCODCOL from vrh_emp_trescisao REC where REC.BDCODEMP = COL.BDCODEMP and ';
    wSql = wSql || ' REC.BDCODCOL = COL.BDCODCOL and ';
    wSql = wSql || ' CAST((SUBSTRING(CAST(REC.BDDATARESCISAO as VARCHAR(10)) from 1 for 4)||SUBSTRING(CAST(REC.BDDATARESCISAO as VARCHAR(10)) from 6 for 2)) As INTEGER) <= '||prref||')) ';
    wSql = wSql || ' AND (not exists ( select TRA.bdcodemporig, TRA.bdcodcolorig from vrh_emp_ttranscol TRA';
    wSql = wSql || ' where TRA.bdcodemporig = COL.BDCODEMP and TRA.bdcodcolorig = COL.BDCODCOL))';

--    if (:PRCODEMP is null) then
--       wSql = wSql || ' group by col.bdcodemp';


  FOR EXECUTE STATEMENT wsql
      INTO
        :TTATIVOS
     DO
       BEGIN
         SUSPEND;
       END


  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: VRHF_SP_TOTPRO_TOTDESC */
ALTER PROCEDURE VRHF_SP_TOTPRO_TOTDESC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPADOR INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODTPCC INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDLIQUIDO NUMERIC(15,6))
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  wsql = 'select FN.bdcodemp,  FN.BDCODTPCC ,  BDCODCOL, BDREFFN, SUM(BDPROVENTO) PROVE, SUM(BDDESCONTO) DESCO, SUM(BDPROVENTO) - SUM(BDDESCONTO) LIQ '||
         'from VRHF_SP_CALC_FOLHANORMAL(';

  IF (prCODEMP IS NULL) THEN
     wsql = wsql||'null, ';
  ELSE
     wsql = wsql||''''||prCODEMP||''''||',';


  IF (prcodcol IS NULL) THEN
     wsql = wsql||'null, ';
  ELSE
     wsql = wsql||''''||PRCODCOL||''''||',';


  wsql = wsql||prrefini||',';
  wsql = wsql||prreffim||',';


  wsql = wsql||pragrupador||'null) FN '||' group by FN.BDCODEMP, FN.BDCODTPCC, bdcodcol,  bdrefFN ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdcodtpcc,
    :BDCODCOL,
    :BDREF,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDLIQUIDO
  DO

  SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_TOTPRO_TOTDESC_ADSAL */
ALTER PROCEDURE VRHF_SP_TOTPRO_TOTDESC_ADSAL(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREF INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREF INTEGER,
BDPROVENTO NUMERIC(15,6),
BDDESCONTO NUMERIC(15,6),
BDLIQUIDO NUMERIC(15,6))
 AS
DECLARE VARIABLE wsql VARCHAR(32700);
BEGIN
  wsql = 'select bdcodemp,  BDCODCOL, BDREF, SUM(BDPROVENTO) PROVE, SUM(BDDESCONTO) DESCO, SUM(BDPROVENTO) - SUM(BDDESCONTO) LIQ '||
         'from VRHF_SP_CONS_CALC_ADSALARIO(';

  IF (prCODEMP IS NULL) THEN
     wsql = wsql||'null, ';
  ELSE
     wsql = wsql||''''||prCODEMP||''''||',';


  IF (prcodcol IS NULL) THEN
     wsql = wsql||'null, ';
  ELSE
     wsql = wsql||''''||PRCODCOL||''''||',';


  wsql = wsql||PRREF||', NULL)'||'group by BDCODEMP, bdcodcol,  bdref ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREF,
    :BDPROVENTO,
    :BDDESCONTO,
    :BDLIQUIDO
  DO

  SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_TPREPFB_CC */
ALTER PROCEDURE VRHF_SP_TPREPFB_CC RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDDATAENTRADA DATE,
BDHORAENTRADA TIME,
BDTIPO INTEGER,
BDQTDTEMPO NUMERIC(15,6),
BDCTALON VARCHAR(40),
BDTIPCTA SMALLINT,
BDNOMCTA VARCHAR(100),
BDAPECTA VARCHAR(20),
BDFILTROGER VARCHAR(20),
BDCLANOM VARCHAR(140))
 AS
DECLARE VARIABLE wref INTEGER;
DECLARE VARIABLE wsqlemp VARCHAR(32700);
DECLARE VARIABLE wsql VARCHAR(32700);
BEGIN
  /* Procedure Text */
  wsql = '';
  wsql = wsql||'select';
  wsql = wsql||' pfn.bdcodemp,';
  wsql = wsql||' pfn.bdcodcol,';
  wsql = wsql||' pfn.bdordem,';
  wsql = wsql||' pfn.bdcodcentro,';
  wsql = wsql||' pfn.bdcodtpcc,';
  wsql = wsql||' pfn.bddataentrada,';
  wsql = wsql||' pfn.bdhoraentrada,';
  wsql = wsql||' pfn.bdtipo,';
  wsql = wsql||' pfn.bdqtdtempo,';
  wsql = wsql||' cc.BDCTALON,';
  wsql = wsql||' cc.BDTIPCTA,';
  wsql = wsql||' cc.BDNOMCTA,';
  wsql = wsql||' cc.BDAPECTA,';
  wsql = wsql||' cc.BDFILTROGER,';
  wsql = wsql||' cc.BDCLANOM';
  wsql = wsql||' from vrhf_EMP_tprepfn pfn ';
  wsql = wsql||' left outer join centros_tpcc cc on (cc.bdcodcentro = pfn.bdcodcentro and cc.bdcodtpcc = pfn.bdcodtpcc) ';

  FOR EXECUTE STATEMENT wsql INTO
    :bdcodemp,
    :bdcodcol,
    :bdordem,
    :bdcodcentro,
    :bdcodtpcc,
    :bddataentrada,
    :bdhoraentrada,
    :bdtipo,
    :bdqtdtempo,
    :BDCTALON,
    :BDTIPCTA,
    :BDNOMCTA,
    :BDAPECTA,
    :BDFILTROGER,
    :BDCLANOM
  DO
  BEGIN
    IF (:bdcodtpcc IS NULL) THEN
       BEGIN
          FOR SELECT bdaaaamm FROM aaaamm(:bddataentrada) INTO wref DO
            BEGIN
            END

          EXECUTE PROCEDURE sp_seta_competencia(wref, NULL, NULL);
          wsqlEmp = 'select emp.bdnomemp from SP_TEMPRESAS_REF('||wRef||') emp'||
                    ' where emp.bdcodemp = '||:bdcodemp;
          FOR EXECUTE STATEMENT wsqlEmp INTO :BDNOMCTA DO
            BEGIN
            END
          EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
       END

    SUSPEND;
  END

END
^

/* Restore proc. body: VRHF_SP_TPREPFN_CC_REF */
create or alter procedure VRHF_SP_TPREPFN_CC_REF (
    PRREF integer,
    PREMPRESA varchar(32700),
    PRCOLABORADOR varchar(32700),
    PRTEMPO integer,
    PRDATAINI date,
    PRDATAFIM date,
    PRFERIAS smallint = 0,
    PRCALCULO DM_BOOLEAN = 'TRUE',
    PRPREVRESC integer = 0,
    PRPARAMETROEMP13 DM_BOOLEAN = 'FALSE')
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDDATAENTRADA date,
    BDHORAENTRADA time,
    BDTIPO integer,
    BDQTDTEMPO numeric(15,6),
    BDCTALON varchar(40),
    BDTIPCTA smallint,
    BDNOMCTA varchar(100),
    BDAPECTA varchar(20),
    BDFILTROGER varchar(20),
    BDCLANOM varchar(140),
    BDTEMPO integer,
    BDTEMPOFN integer,
    BDPERCFN numeric(15,6),
    BDLANCHORAS numeric(15,2),
    BDTOTHORAS numeric(15,2),
    BDTOTDSR numeric(15,2),
    BDLANCDSR numeric(15,2))
as
declare variable WDATARESC date;
declare variable WSQLEMP varchar(32700);
declare variable WSQL varchar(32700);
declare variable WULTDIA date;
declare variable WEMPRESA integer;
declare variable WFUNCIONARIO integer;
declare variable WHORASAIDACC time;
declare variable WULTDIAMES date;
declare variable WPRIDIAMES date;
declare variable WDATAENTAUX date;
declare variable WHORAENTAUX time;
declare variable WMES integer;
declare variable WANO integer;
declare variable WDIA integer;
declare variable WULTDIASET varchar(10);
declare variable WPRIMDIASET varchar(10);
declare variable WPROPTOM integer;
declare variable WPROPFER integer;
declare variable WESTADEFERIAS integer;
BEGIN
  /* Procedure Text */
  wano = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wmes = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 5 FOR 6) AS INTEGER);
  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  wultdiaset = wmes||'/'||wdia||'/'||wano;
  wPrimDiaset = wmes||'/01/'||wano;

  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, CAST(wPrimDiaset AS DATE), CAST(wultdiaset AS DATE));

  IF (prempresa IS NOT NULL) THEN
     prempresa = ''''||prempresa||'''';

  IF (prcolaborador IS NOT NULL) THEN
     prcolaborador = ''''||prcolaborador||'''';

  IF (prempresa IS NULL) THEN
     prempresa = 'null';

  IF (prcolaborador IS NULL) THEN
     prcolaborador = 'null';

  wsql = '';
  wsql = wsql||'select';
  wsql = wsql||' pfn.bdcodemp,';
  wsql = wsql||' pfn.bdcodcol,';
  wsql = wsql||' pfn.bdordem,';
  wsql = wsql||' pfn.bdcodcentro,';
  wsql = wsql||' pfn.bdcodtpcc,';
  wsql = wsql||' pfn.bddataentrada,';
  wsql = wsql||' pfn.bdhoraentrada,';
  wsql = wsql||' pfn.bdtipo,';
  wsql = wsql||' pfn.bdqtdtempo,';
  wsql = wsql||' pfn.bdpercfn,';
  wsql = wsql||' pfn.bdlanchoras,';
  wsql = wsql||' pfn.bdtothoras,';
  wsql = wsql||' pfn.bdtotdsr,';
  wsql = wsql||' pfn.bdlancdsr,';
  wsql = wsql||' cc.BDCTALON,';
  wsql = wsql||' cc.BDTIPCTA,';
  wsql = wsql||' cc.BDNOMCTA,';
  wsql = wsql||' cc.BDAPECTA,';
  wsql = wsql||' cc.BDFILTROGER,';
  wsql = wsql||' cc.BDCLANOM';

  IF (prdatafim IS NOT NULL) THEN
     IF ((prref IS NOT NULL) AND (CAST(wultdiaset AS DATE) < prdatafim)) THEN
        wsql = wsql||' from vrhf_sp_tprepfn_ref('||prref||','||prempresa||','||prcolaborador||',cast('||''''||CAST(:prdataini AS VARCHAR(10))||''''||' as date),cast('||''''||wultdiaset||''''||' as date), ''FALSE'', ' ||  :PRPARAMETROEMP13 || ') pfn';
     ELSE
        wsql = wsql||' from vrhf_sp_tprepfn_ref('||prref||','||prempresa||','||prcolaborador||',cast('||''''||CAST(:prdataini AS VARCHAR(10))||''''||' as date),cast('||''''||CAST(:prdatafim AS VARCHAR(10))||''''||' as date), ''FALSE'', ' ||  :PRPARAMETROEMP13 ||') pfn';
  ELSE
     wsql = wsql||' from vrhf_sp_tprepfn_ref('||prref||','||prempresa||','||prcolaborador||',null,null, ''FALSE'', ' || :PRPARAMETROEMP13 || ') pfn';
  wsql = wsql||' left outer join centros_tpcc cc on (cc.bdcodcentro = pfn.bdcodcentro and cc.bdcodtpcc = pfn.bdcodtpcc)';
  wsql = wsql||' order by pfn.bdcodemp,pfn.bdcodcol,pfn.bddataentrada,pfn.bdhoraentrada';

  wempresa = 0;
  wfuncionario = 0;
  wproptom = 0;
--  SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES'))) AS DATE) FROM rdb$database INTO wdataaux;

  FOR EXECUTE STATEMENT wsql INTO
    :bdcodemp,
    :bdcodcol,
    :bdordem,
    :bdcodcentro,
    :bdcodtpcc,
    :bddataentrada,
    :bdhoraentrada,
    :bdtipo,
    :bdqtdtempo,
    :bdpercfn,
    :bdlanchoras,
    :bdtothoras,
    :bdtotdsr,
    :bdlancdsr,
    :BDCTALON,
    :BDTIPCTA,
    :BDNOMCTA,
    :BDAPECTA,
    :BDFILTROGER,
    :BDCLANOM
  DO
  BEGIN
    bdTempo = 0;

    IF (BDNOMCTA IS NOT NULL) THEN
    begin
        BDNOMCTA = REPLACE(BDNOMCTA, ASCII_CHAR(13), '');
        BDNOMCTA = REPLACE(BDNOMCTA, ASCII_CHAR(10), '');
    end

    IF ((wempresa <> bdcodemp) OR (wfuncionario <> bdcodcol))THEN
       BEGIN
          wempresa = bdcodemp;
          wfuncionario = bdcodcol;
          SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES'))) AS DATE) FROM rdb$database INTO wultdiames;
          SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES'))) AS DATE) FROM rdb$database INTO wultdia;
--          SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES'))) AS DATE) FROM rdb$database INTO wdataatu;
          SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES'))) AS DATE) FROM rdb$database INTO wpridiames;

          wdataresc = NULL;
          if (PRPREVRESC = 1) then
            WSQLemp = 'select first 1 colcon.BDDATARESCISAOPREV from VRH_EMP_TRESCISAO_PREVIA colcon where colcon.BDCODEMP = '||:bdcodemp||' and colcon.BDCODCOL = '||:bdcodcol||' and colcon.BDREFRESCISAOPREV = '||:prref;
          else
          wsqlemp = 'select first 1 colcon.bddatarescisao from vrh_emp_trescisao colcon where colcon.bdcodemp = '||:bdcodemp||' and colcon.bdcodcol = '||:bdcodcol||' and colcon.bdrefrescisao = '||:prref;

          EXECUTE STATEMENT wsqlemp INTO :wdataresc;

          IF (prferias = 1) THEN
             wproptom = 0;
          ELSE
             SELECT BDPROPTOMEMP, BDPROPFEREMP FROM VW_VRHF_BASE_TEMPPROP WHERE BDCODEMP = :bdcodemp INTO :wproptom, :wpropfer;
          -- 30 dias
          IF (wproptom = 1) THEN
             BEGIN
               westadeferias = NULL;
               SELECT FIRST 1 BDCODEMP FROM vrh_emp_tferias WHERE BDCODEMP = :bdcodemp AND bdcodcol = :bdcodcol AND ((BDREFINIFE = :prref) OR (BDREFFIMFE = :prref)) INTO :westadeferias;
               IF (westadeferias IS NOT NULL AND westadeferias = :BDCODEMP AND wpropfer = 0) THEN
                 BEGIN
                   IF (CAST((SUBSTRING(CAST(:wultdia AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) IN (1,3,5,7,8,10,12)) THEN
                      BEGIN
                        wultdia = CAST((SUBSTRING(CAST(:wultdia AS VARCHAR(10)) FROM 1 FOR 8)||'30') AS DATE);
                        wultdiames = CAST((SUBSTRING(CAST(:wultdiames AS VARCHAR(10)) FROM 1 FOR 8)||'30') AS DATE);
                      END
                 END
               ELSE
               IF (CAST((SUBSTRING(CAST(:wultdia AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) IN (1,3,5,7,8,10,12)) THEN
                  BEGIN
                    wultdia = CAST((SUBSTRING(CAST(:wultdia AS VARCHAR(10)) FROM 1 FOR 8)||'30') AS DATE);
                    wultdiames = CAST((SUBSTRING(CAST(:wultdiames AS VARCHAR(10)) FROM 1 FOR 8)||'30') AS DATE);
             END
       END
       END

    IF (:bdcodtpcc IS NULL) THEN
       BEGIN
          wsqlEmp = 'select first 1 emp_ref.bdnomemp from tempresas emp '||
                    'inner join tempresas_ref emp_ref on (emp_ref.bdcodemp = emp.bdcodemp and  '||
                    '                                     emp_ref.bdrefemp = coalesce((select max(D2.bdrefemp) '||
                    '                                                                  from tempresas_ref D2 '||
                    '                                                                  where D2.BDCODEMP = emp.BDCODEMP and '||
                    '                                                                        D2.bdrefemp <= (select cast(rdb$get_context(''USER_SESSION'', ''W_ANOMES'') as integer) '||
                    '                                                                                  from RDB$DATABASE)), '||
                    '                                                                 (select min(D1.bdrefemp) '||
                    '                                                                  from tempresas_ref D1 '||
                    '                                                                  where D1.BDCODEMP = emp.BDCODEMP))) '||
                    'where emp.bdcodemp = '||:bdcodemp;

          EXECUTE STATEMENT wsqlEmp INTO :BDNOMCTA;
       END

     IF (prtempo >= 1) THEN
        BEGIN
          wultdia = NULL;
          SELECT FIRST 1 bddataentrada,bdhoraentrada data FROM vrhf_emp_tprepfn pf
             WHERE (pf.bddataentrada+pf.bdhoraentrada > (:bddataentrada+:bdhoraentrada)) AND
                   (pf.bdcodemp = :bdcodemp) AND (pf.bdcodcol = : bdcodcol)
                   ORDER BY bddataentrada+bdhoraentrada INTO :wultdia,:WHORASAIDACC;

          IF ((wultdia IS NULL) OR (wultdia > wultdiames) ) THEN
             BEGIN
               SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES'))) AS DATE) FROM rdb$database INTO wultdia;

               IF (wproptom = 1) THEN
                  BEGIN
                    IF (westadeferias IS NOT NULL AND westadeferias = :BDCODEMP AND wpropfer = 0) THEN
                      BEGIN
                        IF (CAST((SUBSTRING(CAST(:wultdia AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) IN (1,3,5,7,8,10,12)) THEN
                           BEGIN
                             wultdia = CAST((SUBSTRING(CAST(:wultdia AS VARCHAR(10)) FROM 1 FOR 8)||'30') AS DATE);
                           END
                      END
                    ELSE
                    IF (CAST((SUBSTRING(CAST(:wultdia AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) IN (1,3,5,7,8,10,12)) THEN
                       BEGIN
                         wultdia = CAST((SUBSTRING(CAST(:wultdia AS VARCHAR(10)) FROM 1 FOR 8)||'30') AS DATE);
                  END
                  END

               --if (prtempo < 2) then
               --   select PRDIASEGUINTE from dia_seguinte(:wultdia) into wultdia;
               whorasaidacc = CAST('23:59' AS TIME);
             END

           IF ((wdataresc IS NOT NULL) AND (wultdia > wdataresc)) THEN
             BEGIN
               wultdia = wdataresc;

               --if (prtempo < 2) then
               --   select PRDIASEGUINTE from dia_seguinte(:wultdia) into wultdia;
               whorasaidacc = CAST('23:59' AS TIME);
             END

          wdataentaux = :bddataentrada;
          whoraentaux = :bdhoraentrada;

          IF (prtempo >= 1) THEN
             BEGIN
               IF (:wdataentaux < wpridiames) THEN
                  wdataentaux = wpridiames;

               IF (prdataini > :wdataentaux) THEN
                  wdataentaux = prdataini;

               IF ((prdatafim IS NOT NULL) AND (wultdia > prdatafim)) THEN
                  BEGIN
                    wultdia = prdatafim;
                    -- Não pode ir para o dia seguinte quando é informado a data final
--                    select PRDIASEGUINTE from dia_seguinte(:wultdia) into wultdia;
                    whorasaidacc = CAST('23:59' AS TIME);
                  END

               WHILE (wdataentaux <= wultdia) DO
                 BEGIN
                   IF ((wdataentaux = :bddataentrada) AND (wdataentaux = wultdia)) THEN
                      BEGIN
                        bdtempo = bdtempo + CAST((whorasaidacc - whoraentaux) AS INTEGER);
                        IF (whorasaidacc = '23:59') THEN
                           bdtempo = bdtempo + 60;
                      END
                   ELSE IF (wdataentaux = :bddataentrada) THEN
                      BEGIN
                        bdtempo = bdtempo + CAST((CAST('23:59' AS TIME) - whoraentaux) AS INTEGER) + 60;
                      END
                   ELSE IF (wdataentaux = wultdia) THEN
                      BEGIN
                        bdtempo = bdtempo + CAST((whorasaidacc - CAST('00:00' AS TIME)) AS INTEGER);
                        IF (whorasaidacc = '23:59') THEN
                           bdtempo = bdtempo + 60;
                      END
                   ELSE
                      BEGIN
                        bdtempo = bdtempo + CAST((CAST('23:59' AS TIME) - CAST('00:00' AS TIME)) AS INTEGER) + 60;
                      END

                   SELECT PRDIASEGUINTE FROM dia_seguinte(:wdataentaux) INTO wdataentaux;
                 END

               bdtempo = bdtempo / 60;
               bdtempofn = bdtempo;
               /*if (:bddataentrada < wpridiames) then
                  begin
                    select bdtempo from VRHF_SP_TTEMPOTRAB(:bdcodemp,:bdcodcol,:wpridiames,cast('00:00' as time),:wultdia,:whorasaidacc) into :bdtempofn;
                  end
               else
                  begin
                    select bdtempo from VRHF_SP_TTEMPOTRAB(:bdcodemp,:bdcodcol,:bddataentrada,:bdhoraentrada,:wultdia,:whorasaidacc) into :bdtempofn;
                  end*/
             END
          ELSE IF (:bddataentrada < wpridiames) THEN
             BEGIN
               SELECT bdtempo FROM VRHF_SP_TTEMPOTRAB(:bdcodemp,:bdcodcol,:wpridiames,CAST('00:00' AS TIME),:wultdia,:whorasaidacc) INTO :bdtempo;
               bdtempofn = bdtempo;
             END
          ELSE
             BEGIN
               SELECT bdtempo FROM VRHF_SP_TTEMPOTRAB(:bdcodemp,:bdcodcol,:bddataentrada,:bdhoraentrada,:wultdia,:whorasaidacc) INTO :bdtempo;
               bdtempofn = bdtempo;
             END
        END

    IF ((BDDATAENTRADA > wultdia) and (SUBSTRING(CAST(:BDDATAENTRADA AS VARCHAR(10)) FROM 6 FOR 2) <> SUBSTRING(CAST(:wultdia AS VARCHAR(10)) FROM 6 FOR 2)))  THEN
       BEGIN
         IF (PRCALCULO <> 'TRUE') THEN
    SUSPEND;
  END
    ELSE
       SUSPEND;
  END

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

/* Restore proc. body: VRHF_SP_TPREPFN_REF */
create or alter procedure VRHF_SP_TPREPFN_REF (
    PRREFERENCIA integer,
    PREMPRESA varchar(32700),
    PRCOLABORADOR varchar(32700),
    PRDATAINI date,
    PRDATAFIM date,
    PRRETORNADEMITIDOS varchar(5) = 'FALSE'   /*164967 - André Cursino - 30/09/2022*/ ,
    PRPARAMETROEMP13 DM_BOOLEAN = 'FALSE')
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDDATAENTRADA date,
    BDHORAENTRADA time,
    BDTIPO integer,
    BDQTDTEMPO numeric(15,6),
    BDPERCFN numeric(15,6),
    BDLANCHORAS numeric(15,2),
    BDTOTHORAS numeric(15,2),
    BDTOTDSR numeric(15,2),
    BDLANCDSR numeric(15,2),
    BDRATEIO13SAL integer)
as
declare variable WWHERECOL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WANOS varchar(4);
declare variable WAUX varchar(32700);
declare variable WSQLANT varchar(32700);
declare variable WSQLCOL varchar(32700);
declare variable WCOLATU integer;
declare variable WEMPATU integer;
declare variable WMESS varchar(2);
declare variable WMES smallint;
declare variable WULTDIA integer;
declare variable WULTDIAS varchar(2);
declare variable WANO integer;
declare variable WDATAINI varchar(10);
declare variable WANOMES varchar(6);
declare variable WDATAFIM varchar(10);
declare variable WSQL varchar(32700);
declare variable WDIASEMANA integer;
declare variable WANTERIOR smallint;
declare variable WHORAINI time;
declare variable WSQLHORA varchar(3200);
declare variable WRATEIO13SAL integer;
BEGIN
  IF (prdatafim IS NOT NULL) THEN
     SELECT bdaaaamm FROM aaaamm(:prdatafim) INTO wanomes;
  ELSE
     wanomes = CAST(prreferencia AS VARCHAR(6));

  wmess = SUBSTRING(wanomes FROM 5 FOR 2);
  wanos = SUBSTRING(wanomes FROM 1 FOR 4);

  wmes = CAST(wmess AS SMALLINT);
  wano = CAST(wanos AS INTEGER);

  wwhere = '';

  IF ((prempresa IS NOT NULL) AND (prempresa <> '')) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prempresa;
     END

  IF ((prcolaborador IS NOT NULL) AND (prcolaborador <> '')) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcolaborador;
     END

  IF (prdatafim IS NOT NULL) THEN
     BEGIN
       wultdias = EXTRACT(DAY FROM prdatafim);
     END
  ELSE
     BEGIN
       SELECT ultdia FROM ultimo_dia_mes(:wmes,:wano) INTO wultdia;
       wultdias = CAST(wultdia AS VARCHAR(2));
     END

  wwhere = ' '||wwhere;

  IF (prdatafim IS NOT NULL) THEN
     BEGIN
       wdataini = wmess||'/01/'||wanos;
       IF (CAST(wDataIni AS DATE) < :prdataini) THEN
          wdataini = CAST(:prdataini AS VARCHAR(10));
     END
  ELSE
     BEGIN
       wdataini = wmess||'/01/'||wanos;
     END
  wDataFim = wmess||'/'||wultdias||'/'||wanos;
  /* Procedure Text */



  WSQL = 'select prepcalc.BDCODEMP, BDCODCOL, BDORDEM, BDCODCENTRO, BDCODTPCC, BDDATAENTRADA, BDHORAENTRADA, BDTIPO, ';


  if (PRPARAMETROEMP13 = 'TRUE') then
    WSQL = WSQL || 'BDQTDTEMPO + BDRATEIO13SAL + 100000, ';
  else
    WSQL = WSQL || 'BDQTDTEMPO , ';

  WSQL = WSQL || 'BDPERCFN, ' || 'BDLANCHORAS, BDTOTHORAS, BDTOTDSR, BDLANCDSR ';

  if (PRPARAMETROEMP13 = 'TRUE') then
    WSQL = WSQL || ' , e.BDRATEIO13SAL ';
  else
    WSQL = WSQL || ' , 0 BDRATEIO13SAL ';
    
  WSQL = WSQL || 'from vrhf_emp_tprepfn prepcalc ';

  if (PRPARAMETROEMP13 = 'TRUE') then
  begin
    WSQL = WSQL || ' left outer join VRHF_BASE_TEMPGPS e on e.BDCODEMP = prepcalc.BDCODEMP  ' ||
                   ' and e.BDREFEMP = (select FIRST 1 x.BDREFEMP from VRHF_BASE_TEMPGPS x ' ||
                   '                   where x.BDCODEMP = prepcalc.BDCODEMP  ' ||
                   '                   and x.BDREFEMP <= ' || PRREFERENCIA ||
                   '                   order by x.BDREFEMP DESC) ';
  end

  WSQL = WSQL || ' where prepcalc.bddataentrada >= ' || '''' || WDATAINI || '''' || ' and (prepcalc.bddataentrada <= ' || '''' || WDATAFIM || '''' || ')';


  WSQLANT = 'select first 1 prepcalc.BDCODEMP, BDCODCOL, BDORDEM, BDCODCENTRO, BDCODTPCC, BDDATAENTRADA, BDHORAENTRADA, BDTIPO, BDQTDTEMPO, BDPERCFN, '||
                           'BDLANCHORAS, BDTOTHORAS, BDTOTDSR, BDLANCDSR ';

  if (PRPARAMETROEMP13 = 'TRUE') then
    WSQLANT = WSQLANT || ' , e.BDRATEIO13SAL ';
  else
    WSQLANT = WSQLANT || ' , 0 BDRATEIO13SAL ';
    
  WSQLANT = WSQLANT || 'from vrhf_emp_tprepfn prepcalc ';

  if (PRPARAMETROEMP13 = 'TRUE') then
  begin
    WSQLANT = WSQLANT || ' left outer join VRHF_BASE_TEMPGPS e on e.BDCODEMP = prepcalc.BDCODEMP  ' ||
                         ' and e.BDREFEMP = (select FIRST 1 x.BDREFEMP from VRHF_BASE_TEMPGPS x ' ||
                         '                   where x.BDCODEMP = prepcalc.BDCODEMP  ' ||
                         '                   and x.BDREFEMP <= ' || PRREFERENCIA ||
                         '                   order by x.BDREFEMP DESC) ';
  end

  WSQLANT = WSQLANT || ' where prepcalc.bddataentrada < ' || '''' || WDATAINI || '''';

  if (PRPARAMETROEMP13 = 'TRUE') then
    WSQLANT = WSQLANT || ' and COALESCE(e.BDRATEIO13SAL,0) <> 2 ';/*opção 2 = não ratear */

  WWHERECOL = '';
  IF (prempresa IS NOT NULL) THEN
     WWHERECOL = ' and '||prempresa;
  IF (prcolaborador IS NOT NULL) THEN
     WWHERECOL = WWHERECOL||' and '||prcolaborador;

  IF (prempresa IS NOT NULL) THEN
     prempresa = ''''||prempresa||'''';

  IF (prcolaborador IS NOT NULL) THEN
     prcolaborador = ''''||prcolaborador||'''';

  IF (prempresa IS NULL) THEN
     prempresa = 'null';

  IF (prcolaborador IS NULL) THEN
     prcolaborador = 'null';

--  wsqlcol = 'select bdcodemp, bdcodcol from vrh_sp_colcon('||prempresa||','
--                                                           ||prcolaborador||','
--                                                           ||'null'||','||'null'||','||'null'||','||prreferencia
--                                                           ||','||''''||wdatafim||''''
--                                                           ||',1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0)';


  wsqlcol = 'select colcon.bdcodemp,colcon.bdcodcol from vrh_emp_tcolcon colcon'||
            ' left outer join vrh_emp_trescisao res on (colcon.bdcodemp = res.bdcodemp and colcon.bdcodcol = res.bdcodcol)'||
            ' where colcon.bddataadmcol <= '||''''||wdatafim||''''||WWHERECOL; /*||*/
   
  if (Upper(prRetornaDemitidos) = 'FALSE') then /*164967 - André Cursino - 30/09/2022*/
    wsqlcol = wsqlcol || ' and ((res.BDDATARESCISAO is null) or (res.bdrefrescisao >= '||wanomes||'))';

  wsqlcol = wsqlcol || ' and exists (select * from vrhf_emp_tprepfn a where colcon.bdcodemp = a.bdcodemp and colcon.bdcodcol = a.bdcodcol)';

  wdiasemana = EXTRACT(WEEKDAY FROM CAST(wdataini AS DATE));

  FOR EXECUTE STATEMENT wsqlcol INTO :wempatu,:wcolatu DO
    BEGIN
      wsqlhora = 'select first 1 tqh.bdqhhsent from VRH_EMP_TCOL_VINCDIA cd'||
                 ' left outer join vrh_base_tqh_horario qhh on (CD.bdcodqh = qhh.bdcodqhh)'||
                 ' left outer join vrh_base_tqh_dias qh on (cd.bdcodqh = qh.bdcodqh and cd.bdcodpqua = qh.bdcodpqua and qhh.bdcodqhh = qh.bddiasemqh)'||
                 ' left outer join vrh_base_tqh_horas tqh on (qh.bdcodqhh = tqh.bdcodqhh and tqh.bdcodqhhs = qh.bddiasemqh)'||
                 ' where cd.bdcodemp = '||wempatu||' and cd.bdcodcol = '||wcolatu||
                 ' and cd.bddatacol <= cast('||''''||wDataini||''''||'as date) and tqh.bdcodqhhs ='||wdiasemana||
                 ' order by cd.bddatacol desc';

      EXECUTE STATEMENT wsqlhora INTO :whoraini;

      IF (whoraini IS NULL) THEN
         whoraini = CAST('00:00' AS TIME);

      wwhere = ' and prepcalc.bdcodemp = '||wempatu||' and prepcalc.bdcodcol = '||wcolatu;


    if (PRPARAMETROEMP13 = 'FALSE') then
      waux = wsql||wwhere||' order by prepcalc.bddataentrada, prepcalc.bdhoraentrada';
    else
    begin
      WAUX = WSQL || WWHERE || ' and COALESCE(e.BDRATEIO13SAL,0) = 0 ' || /*opção 0 = rateio do mes */

      ' union all ' ||

      WSQL || WWHERE || ' and COALESCE(e.BDRATEIO13SAL,0) = 1 ' || /*opção 1 = ultima alocacao */
                        ' and prepcalc.BDORDEM = (select FIRST 1 x.BDORDEM from vrhf_emp_tprepfn x ' ||
                        '                   where x.BDCODEMP = prepcalc.BDCODEMP and x.BDCODCOL = prepcalc.BDCODCOL ' ||
                        '                   and (x.bddataentrada >= ' || '''' || WDATAINI || ''')' ||
                        '                   and (x.bddataentrada <= ' || '''' || WDATAFIM || ''')' ||
                        '                   order by x.BDORDEM DESC) ' ;

    end

      wanterior = 0;

      FOR EXECUTE STATEMENT waux
      INTO
        :bdcodemp,
        :bdcodcol,
        :bdordem,
        :bdcodcentro,
        :bdcodtpcc,
        :bddataentrada,
        :bdhoraentrada,
        :bdtipo,
        :bdqtdtempo,
        :bdpercfn,
        :bdlanchoras,
        :bdtothoras,
        :bdtotdsr,
        :bdlancdsr,
        :bdrateio13sal
      DO
        BEGIN
          IF (((bddataentrada = CAST(wdataini AS DATE)) AND (bdhoraentrada <= whoraini))
               or (BDRATEIO13SAL = 1)) then /* apenas ultimo tomador */ 
             BEGIN
               wanterior = 1;
             END
          SUSPEND;
        END

      IF (wanterior = 0) THEN
         BEGIN
           waux = WSQLANT||wwhere||' order by prepcalc.bddataentrada desc, prepcalc.bdhoraentrada desc';
           FOR EXECUTE STATEMENT waux
           INTO
             :bdcodemp,
             :bdcodcol,
             :bdordem,
             :bdcodcentro,
             :bdcodtpcc,
             :bddataentrada,
             :bdhoraentrada,
             :bdtipo,
             :bdqtdtempo,
             :bdpercfn,
             :bdlanchoras,
             :bdtothoras,
             :bdtotdsr,
             :bdlancdsr,
             :bdrateio13sal
           DO
           SUSPEND;
         END
    END

END^

/* Restore proc. body: VRHF_SP_TTEMPOTRAB */
ALTER PROCEDURE VRHF_SP_TTEMPOTRAB(PRCODEMP INTEGER,
PRCODFUN INTEGER,
PRDATAENT DATE,
PRHORAENT TIME,
PRDATASAI DATE,
PRHORASAI TIME)
 RETURNS(BDTEMPO INTEGER)
 AS
DECLARE VARIABLE wdataatu DATE;
DECLARE VARIABLE wdiasemana INTEGER;
DECLARE VARIABLE wsqlhorario VARCHAR(32700);
DECLARE VARIABLE whorario INTEGER;
DECLARE VARIABLE whoraent TIME;
DECLARE VARIABLE whorasai TIME;
BEGIN
  bdtempo = 0;
  /* Procedure Text */
    wdataatu = prdataent;
    WHILE (wdataatu <= prdatasai) DO
    BEGIN
      wdiasemana = EXTRACT(WEEKDAY FROM wdataatu);
    
        wsqlhorario = 'select first 1 qh.bdcodqh from VRH_EMP_TCOL_VINCDIA cd'||
                        ' left outer join vrh_base_tqh_dias qh on (cd.bdcodqh = qh.bdcodqh)'||
                        ' left outer join vrh_base_tqh_horario qhh on (qh.bdcodqh = qhh.bdcodqhh)'||
                        ' where cd.bdcodemp = '||:prcodemp||' and cd.bdcodcol = '||:prcodfun||' and'||
                        ' qh.bddiasemqh = '||wdiasemana||' and'||
                        ' cd.bddatacol = (select first 1 cd.bddatacol from VRH_EMP_TCOL_VINCDIA cd'||
                        '                    left outer join vrh_base_tqh_dias qh on (cd.bdcodqh = qh.bdcodqh)'||
                        '                    left outer join vrh_base_tqh_horario qhh on (qh.bdcodqh = qhh.bdcodqhh)'||
                        '                    where cd.bdcodemp = '||:prcodemp||' and cd.bdcodcol = '||:prcodfun||
                        '                    and cd.bddatacol <= cast('||''''||CAST(wdataatu AS VARCHAR(10))||''''||' as date)'||
                        '                    order by cd.bddatacol desc)'||
                        ' order by cd.bddatacol desc';

    
        FOR EXECUTE STATEMENT wsqlhorario INTO :WHORARIO DO
          BEGIN
              wsqlhorario = 'select tqh.bdqhhsent,tqh.bdqhhssai from vrh_base_tqh_horas tqh'||
                            ' where tqh.bdcodqhh = '||:whorario;
    
              FOR EXECUTE STATEMENT wsqlhorario INTO :whoraent,:whorasai DO
                BEGIN
                  IF ((wdataatu = prdatasai) AND (whoraent > prhorasai)) THEN
                     BREAK;
    
                  IF (wdataatu = prdataent) THEN
                     BEGIN
                       IF (whoraent < :prhoraent) THEN
                          BEGIN
                            whoraent = :prhoraent;
                          END
                     END
    
                  IF (wdataatu = prdatasai) THEN
                     BEGIN
                       IF (whorasai > prhorasai) THEN
                          BEGIN
                            whorasai = prhorasai;
                          END
                     END
    
                   IF ((whoraent > :prhoraent) OR ((whoraent < :prhoraent) AND (whorasai > :prhoraent)) OR
                      (((whoraent < :prhoraent) AND (whorasai < :prhoraent)) AND (whorasai < whoraent))) THEN
                      BEGIN
                        IF  (whorasai < whoraent) THEN
                           BEGIN
                              bdtempo = bdtempo + CAST((CAST('23:59' AS TIME) - whoraent)/60 AS INTEGER) + 1;
                              bdtempo = bdtempo + CAST(CAST(whorasai - CAST('00:00' AS TIME) AS INTEGER)/60 AS INTEGER);
                           END
                        ELSE
                           BEGIN
                              bdtempo = bdtempo + CAST((whorasai - whoraent)/60 AS INTEGER);
                           END
                      END
                END
          END
    
      IF (wdataatu = prdatasai) THEN
         BREAK;
    
      SELECT PRDIASEGUINTE FROM dia_seguinte(:wdataatu) INTO wdataatu;
    END
  SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_TVERBAFC */
create or alter procedure VRHF_SP_TVERBAFC (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(25000),
    PRREFINICOMP integer,
    PRREFFIMCOMP integer,
    PRREFINIPAG integer,
    PRREFFIMPAG integer,
    PRAGRUPATOMADOR integer,
    PRSEPARARCALC integer = 0,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(772) = null,
    PRCOMPLEESOCIAL integer = 0)
returns (
    BDCODVER integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFCOMP integer,
    BDREFVFC numeric(15,6),
    BDREFAUXVFC numeric(15,6),
    BDVALVFC numeric(15,6),
    BDIGNREFVFC varchar(5),
    BDIGNREFAVFC varchar(5),
    BDIGNVALVFC varchar(5),
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDREFFC integer,
    BDCODCONTTI integer)
as
declare variable WDATAPAG varchar(50);
declare variable WGROUPBYDATAPAG varchar(50);
declare variable WSQL varchar(32700);
declare variable WWHEREN varchar(32700);
declare variable WWHERET varchar(32700);
declare variable WAUX1 numeric(15,6);
declare variable WAUX2 numeric(15,6);
declare variable WAUXTIPO integer;
BEGIN
  /* pragrupatomador
     0 = Nao agrupa
     1 = Agrupa por referencia
     2 = Agrupo por referencia e centro/Tomador
     3 = Agrupa por referencia e Tomador (se nao for tomador verifica pela classificacao e nao encontrando considera empresa)
     4 = Agrupa por referencia e Tipo Tomador (so vai criar mais registros pra empresa se for tomador 155)
  */

  prpuxafiliais   = coalesce(prpuxafiliais, 0);
  pragrupatomador = coalesce(pragrupatomador, 0);
  prsepararcalc   = coalesce(prsepararcalc, 0);

  wsql = 'select COLCON.bdcodver, COLCON.bdcodemp, COLCON.bdcodcol, COLCON.bdreffn, COLCON.BDREFCOMP, COLCON.bdrefvfc,'||
         'COLCON.bdrefauxvfc, COLCON.bdvalvfc, COLCON.bdignrefvfc, COLCON.bdignrefavfc, COLCON.bdignvalvfc, COLCON.BDREFFC, cast(null as INTEGER) BDCODCONTTI '||
         ' from vrhf_emp_tverbafc COLCON '||
         ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
         ' join VRHF_EMP_TFOLHACOMP FOLCOMP ON (COLCON.BDCODEMP = FOLCOMP.BDCODEMP AND COLCON.BDCODCOL = FOLCOMP.BDCODCOL AND COLCON.BDREFFN = FOLCOMP.BDREFFN AND COLCON.BDREFFC = FOLCOMP.BDREFFC) '||  /* 158041 Leonardo Schwab 05/06/2023 */
         ' left outer join VRH_EMP_TACCONV ACCONV ON (FOLCOMP.BDCODEMP = ACCONV.BDCODEMP AND FOLCOMP.BDCODACCONV = ACCONV.BDCODACCONV)';                                                                  /* 158041 Leonardo Schwab 05/06/2023 */

  if (prpuxafiliais = 1) then
     begin
       if (coalesce(prcodemp, '') <> '') then
          begin
            prcodemp = upper(prcodemp);
     
            if (coalesce(prfiliais, '') <> '') then
               begin
                 wwheren = replace(prcodemp,'COLCON.BDCODEMP','EMP.BDCODMATRIZ');
                 prcodemp = '('||prcodemp||' or (('||wwheren||') and (emp.bdcodemp in ('||prfiliais||'))))';
               end
            else
               prcodemp = replace(prcodemp,'COLCON.BDCODEMP','coalesce(emp.bdcodmatriz,emp.bdcodemp)');
          end
     end

  wwheren = '';
  wwheret = '';

  IF (prcodemp IS NOT NULL) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||' where ';
          END

       wwheren = wwheren||prcodemp;
       wwheret = wwhereT||prcodemp;
     END

  IF (prcodcol IS NOT NULL) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||' where ';
          END

       wwheren = wwheren||prcodcol;
       wwheret = wwhereT||prcodcol;
     END

  IF ((prrefinicomp IS NOT NULL) AND (prreffimcomp IS NOT NULL)) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||' where ';
          END

       wwheren = wwheren||'COLCON.BDREFFN >= '||prrefinicomp||' and '||'COLCON.BDREFFN <= '||prreffimcomp;
       wwheret = wwhereT||'COLCON.BDREFTOMADOR >= '||prrefinicomp||' and '||'COLCON.BDREFTOMADOR <= '||prreffimcomp;
     END
  ELSE
     BEGIN
       IF (prrefinicomp IS NOT NULL) THEN
          BEGIN
            IF (wwheren <> '') THEN
               BEGIN
                 wwheren = wwheren||' and ';
                 wwheret = wwheret||' and ';
               END
            ELSE
               BEGIN
                 wwheren = wwheren||' where ';
                 wwheret = wwheret||' where ';
               END

            wwheren = wwheren||'COLCON.BDREFFN = '||prrefinicomp;
            wwheret = wwhereT||'COLCON.BDREFTOMADOR = '||prrefinicomp;
          END
       ELSE
          BEGIN
            IF (prreffimcomp IS NOT NULL) THEN
               BEGIN
                 IF (wwheren <> '') THEN
                    BEGIN
                      wwheren = wwheren||' and ';
                      wwheret = wwheret||' and ';
                    END
                 ELSE
                    BEGIN
                      wwheren = wwheren||' where ';
                      wwheret = wwheret||' where ';
                    END

                 wwheren = wwheren||'COLCON.BDREFFN = '||prreffimcomp;
                 wwheret = wwhereT||'COLCON.BDREFTOMADOR = '||prreffimcomp;
               END
          END
     END

  IF ((prrefinipag IS NOT NULL) AND (prreffimpag IS NOT NULL)) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||' where ';
          END

/*       wwheren = wwheren||'COLCON.BDREFCOMP >= '||prrefinipag||' and '||'COLCON.BDREFCOMP <= '||prreffimpag;
       wwheret = wwhereT||'COLCON.BDREFCOMP >= '||prrefinipag||' and '||'COLCON.BDREFTOMADOR <= '||prreffimpag;
*/
       if (PRCOMPLEESOCIAL = 1) then
          BEGIN
           wwheren = wwheren||'((FOLCOMP.BDCODTIPOFC <> 3 AND COLCON.BDREFFN = '||prrefinipag||') or ';
           wwheren = wwheren||' (FOLCOMP.BDCODACCONV IS NOT NULL AND FOLCOMP.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) >= ' ||prrefinipag||' and (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) <= '||prreffimpag||'))';

           wwheret = wwhereT||'((FOLCOMP.BDCODTIPOFC <> 3 AND COLCON.BDREFTOMADOR = '||prrefinipag||') or ';
           wwheret = wwhereT||' (FOLCOMP.BDCODACCONV IS NOT NULL AND FOLCOMP.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) >= ' ||prrefinipag||' and (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) <= '||prreffimpag||'))';
     END
       else
         BEGIN
           wwheren = wwheren||'((FOLCOMP.BDCODTIPOFC <> 3 AND COLCON.BDREFCOMP >= '||prrefinipag||' and '||'COLCON.BDREFCOMP <= '||prreffimpag||') or ';
           wwheren = wwheren||' (FOLCOMP.BDCODACCONV IS NOT NULL AND FOLCOMP.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) >= ' ||prrefinipag||' and (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) <= '||prreffimpag||'))';

           wwheret = wwhereT||'((FOLCOMP.BDCODTIPOFC <> 3 AND COLCON.BDREFCOMP >= '||prrefinipag||' and '||'COLCON.BDREFCOMP <= '||prreffimpag||') or ';
           wwheret = wwhereT||' (FOLCOMP.BDCODACCONV IS NOT NULL AND FOLCOMP.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) >= ' ||prrefinipag||' and (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) <= '||prreffimpag||'))';
         END
     END
  ELSE
     BEGIN
       IF (prrefinipag IS NOT NULL) THEN
          BEGIN
            IF (wwheren <> '') THEN
               BEGIN
                 wwheren = wwheren||' and ';
                 wwheret = wwheret||' and ';
               END
            ELSE
               BEGIN
                 wwheren = wwheren||' where ';
                 wwheret = wwheret||' where ';
               END

/*            wwheren = wwheren||'COLCON.BDREFCOMP = '||prrefinipag;
            wwheret = wwhereT||'COLCON.BDREFCOMP = '||prrefinipag;
*/
            wwheren = wwheren||'((FOLCOMP.BDCODTIPOFC <> 3 AND COLCON.BDREFCOMP = '||prrefinipag||') or ';
            wwheren = wwheren||' (FOLCOMP.BDCODACCONV IS NOT NULL AND FOLCOMP.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefinipag||'))';

            wwheret = wwhereT||'((FOLCOMP.BDCODTIPOFC <> 3 AND COLCON.BDREFCOMP = '||prrefinipag||') or ';
            wwheret = wwheret||' (FOLCOMP.BDCODACCONV IS NOT NULL AND FOLCOMP.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prrefinipag||'))';
          END
       ELSE
          BEGIN
            IF (prreffimpag IS NOT NULL) THEN
               BEGIN
                 IF (wwheren <> '') THEN
                    BEGIN
                      wwheren = wwheren||' and ';
                      wwheret = wwheret||' and ';
                    END
                 ELSE
                    BEGIN
                      wwheren = wwheren||' where ';
                      wwheret = wwheret||' where ';
                    END

/*                 wwheren = wwheren||'COLCON.BDREFCOMP = '||prreffimpag;
                 wwheret = wwhereT||'COLCON.BDREFCOMP = '||prreffimpag;
*/
                 wwheren = wwheren||'((FOLCOMP.BDCODTIPOFC <> 3 AND COLCON.BDREFCOMP = '||prreffimpag||') or ';
                 wwheren = wwheren||' (FOLCOMP.BDCODACCONV IS NOT NULL AND FOLCOMP.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prreffimpag||'))';

                 wwheret = wwhereT||'((FOLCOMP.BDCODTIPOFC <> 3 AND COLCON.BDREFCOMP = '||prreffimpag||') or ';
                 wwheret = wwhereT||' (FOLCOMP.BDCODACCONV IS NOT NULL AND FOLCOMP.BDCODTIPOFC = 3 AND (SELECT * FROM AAAAMM(ACCONV.BDDTPGTOBRICONV)) = ' ||prreffimpag||'))';
               END
          END
     END

  wsql = wsql||wwheren;

  wsql = wsql||' union all ';


  wsql = wsql||
         'select COLCON.bdcodver, COLCON.bdcodemp, COLCON.bdcodcol, COLCON.bdreffn, COLCON.BDREFCOMP, COLCON.bdrefvfc,'||
         'COLCON.bdrefauxvfc, COLCON.bdvalvfc, COLCON.bdignrefvfc, COLCON.bdignrefavfc, COLCON.bdignvalvfc, COLCON.BDREFFC, COLCON.BDCODCONTTI '||
         ' from VRHF_EMP_TVERBAFCINT COLCON '||
         ' join TEMPRESAS emp on (colcon.bdcodemp = emp.bdcodemp) '||
         ' join VRHF_EMP_TFOLHACOMPINT FOLCOMP ON (COLCON.BDCODEMP = FOLCOMP.BDCODEMP AND COLCON.BDCODCOL = FOLCOMP.BDCODCOL AND COLCON.BDREFFN = FOLCOMP.BDREFFN AND COLCON.BDREFFC = FOLCOMP.BDREFFC AND COLCON.BDCODCONTTI = FOLCOMP.BDCODCONTTI) '||  /* 158041 Leonardo Schwab 05/06/2023 */
         ' left outer join VRH_EMP_TACCONV ACCONV ON (FOLCOMP.BDCODEMP = ACCONV.BDCODEMP AND FOLCOMP.BDCODACCONV = ACCONV.BDCODACCONV)';                                                                  /* 158041 Leonardo Schwab 05/06/2023 */

  wsql = wsql||wwheren;

  IF (coalesce(prcodtpcc, '') = '') THEN
     BEGIN
       FOR EXECUTE STATEMENT wsql
       INTO
         :bdcodver,
         :bdcodemp,
         :bdcodcol,
         :bdreffn,
         :BDREFCOMP,
         :bdrefvfc,
         :bdrefauxvfc,
         :bdvalvfC,
         :bdignrefvfc,
         :bdignrefavfc,
         :bdignvalvfc,
         :BDREFFC,
         :BDCODCONTTI
       DO
         BEGIN
           bdcalctomador = 'FALSE';
           SUSPEND;
         END
     END

  IF (prreffimpag IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prreffimpag, NULL, NULL);
  ELSE IF (prrefinipag IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prrefinipag, NULL, NULL);


   if (prsepararcalc = 0)  then
      begin
        if (pragrupatomador >= 1 and pragrupatomador <= 5) then
           begin
             wdatapag = 'max(colcon.BDREFFC)';
             wgroupbydatapag = '';
           end
        else
           begin
             wdatapag = 'colcon.BDREFFC';
             wgroupbydatapag = '';
           end
      end
   else
      begin
        wdatapag = 'colcon.BDREFFC';
        wgroupbydatapag = ',colcon.BDREFFC';
      end

  IF (pragrupatomador = 4) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, cast(null as integer), '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, sum(COLCON.BDREFVFC), max(COLCON.BDREFAUXVFC), '||
                'max(COLCON.BDREFVFC), sum(COLCON.BDREFAUXVFC), max(colcon.bdtiporefver), '||
                'sum(COLCON.BDVALVFC), max(COLCON.BDIGNREFVFC), max(COLCON.BDIGNREFAVFC), max(COLCON.BDIGNVALVFC), '||
                'colcon.bdCodCentrotoma bdcodcentro , colcon.bdCODTPCCtoma bdcodtpcc, '||
                wdatapag||
              ' from ( ';

       wsql = wsql||
              'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, '||
                'tv.bdtiporefver, COLCON.BDREFFC, '||
                'COLCON.BDVALVFC, COLCON.BDIGNREFVFC, COLCON.BDIGNREFAVFC, COLCON.BDIGNVALVFC, '||
                'toma.bdCodCentro bdCodCentrotoma, toma.bdCODTPCC bdCODTPCCtoma, pf.BDCODCENTRO, pf.BDCODTPCC, cast(null as INTEGER) BDCODCONTTI '||
              'from VRHF_EMP_TVERBAFCTOMADOR COLCON '||
              'join TEMPRESAS emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'left outer join VRHF_EMP_TPREPFN pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join VW_VERBAS_REF_ATUAL tv on (colcon.bdcodver = tv.bdcodver) '||
              'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro,'||prrefinicomp||') toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              'join VRHF_EMP_TFOLTOMCOMP FOLCOMP ON (COLCON.BDCODEMP = FOLCOMP.BDCODEMP AND COLCON.BDCODCOL = FOLCOMP.BDCODCOL AND COLCON.BDREFTOMADOR = FOLCOMP.BDREFTOMADOR AND COLCON.BDREFFC = FOLCOMP.BDREFFC AND COLCON.BDORDEM = FOLCOMP.BDORDEM) '||  /* 158041 Leonardo Schwab 05/06/2023 */
              'left outer join VRH_EMP_TACCONV ACCONV ON (FOLCOMP.BDCODEMP = ACCONV.BDCODEMP AND FOLCOMP.BDCODACCONV = ACCONV.BDCODACCONV)'||                                                                  /* 158041 Leonardo Schwab 05/06/2023 */
              wwheret;

       wsql = wsql||' union all '||
              'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, '||
                'tv.bdtiporefver, COLCON.BDREFFC, '||
                'COLCON.BDVALVFC, COLCON.BDIGNREFVFC, COLCON.BDIGNREFAVFC, COLCON.BDIGNVALVFC, '||
                'toma.bdCodCentro bdCodCentrotoma, toma.bdCODTPCC bdCODTPCCtoma, pf.BDCODCENTRO, pf.BDCODTPCC, COLCON.BDCODCONTTI '||
              'from VRHF_EMP_TVERBAFCTOMINT COLCON '||
              'join TEMPRESAS emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'left outer join VRHF_EMP_TPREPFN pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join VW_VERBAS_REF_ATUAL tv on (colcon.bdcodver = tv.bdcodver) '||
              'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro,'||prrefinicomp||') toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              'join VRHF_EMP_TFOLTOMCOMPINT FOLCOMP ON (COLCON.BDCODEMP = FOLCOMP.BDCODEMP AND COLCON.BDCODCOL = FOLCOMP.BDCODCOL AND COLCON.BDREFTOMADOR = FOLCOMP.BDREFTOMADOR AND COLCON.BDREFFC = FOLCOMP.BDREFFC AND COLCON.BDORDEM = FOLCOMP.BDORDEM AND COLCON.bdcodcontti  = FOLCOMP.bdcodcontti) '||  /* 158041 Leonardo Schwab 05/06/2023 */
              'left outer join VRH_EMP_TACCONV ACCONV ON (FOLCOMP.BDCODEMP = ACCONV.BDCODEMP AND FOLCOMP.BDCODACCONV = ACCONV.BDCODACCONV)'||                                                                  /* 158041 Leonardo Schwab 05/06/2023 */
              wwheret;

       wsql = wsql||') COLCON ';

       if (coalesce(prcodtpcc, '') <> '') then
          begin
            wsql = wsql||' where '||prcodtpcc|| ' ' ;
          end

       wsql = wsql||' group by COLCON.BDCODVER,colcon.bdcodemp,colcon.bdcodcol,colcon.BDCODCONTTI,colcon.BDREFTOMADOR,COLCON.BDREFCOMP, COLCON.bdCodCentrotoma, colcon.bdCODTPCCtoma'||wgroupbydatapag;
     end
  else if (pragrupatomador = 3) then
     begin
       wsql = 'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, cast(null as integer), '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, sum(COLCON.BDREFVFC), max(COLCON.BDREFAUXVFC), '||
                'max(COLCON.BDREFVFC), sum(COLCON.BDREFAUXVFC), max(COLCON.bdtiporefver), '||
                'sum(COLCON.BDVALVFC), max(COLCON.BDIGNREFVFC), max(COLCON.BDIGNREFAVFC), max(COLCON.BDIGNVALVFC), '||
                'COLCON.bdCodCentro, COLCON.bdCODTPCC,'||
                wdatapag||' from (';

       wsql = wsql||
              'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, '||
                'tv.bdtiporefver, COLCON.BDREFFC, '||
                'COLCON.BDVALVFC, COLCON.BDIGNREFVFC, COLCON.BDIGNREFAVFC, COLCON.BDIGNVALVFC, '||
                'pf.bdCodCentro, toma.bdCODTPCC, cast(null as INTEGER) BDCODCONTTI '||
              'from vrhf_emp_tverbafctomador COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'left outer join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join VW_VERBAS_REF_ATUAL tv on (colcon.bdcodver = tv.bdcodver) '||
              'left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              'join VRHF_EMP_TFOLTOMCOMP FOLCOMP ON (COLCON.BDCODEMP = FOLCOMP.BDCODEMP AND COLCON.BDCODCOL = FOLCOMP.BDCODCOL AND COLCON.BDREFTOMADOR = FOLCOMP.BDREFTOMADOR AND COLCON.BDREFFC = FOLCOMP.BDREFFC AND COLCON.BDORDEM = FOLCOMP.BDORDEM) '||  /* 158041 Leonardo Schwab 05/06/2023 */
              'left outer join VRH_EMP_TACCONV ACCONV ON (FOLCOMP.BDCODEMP = ACCONV.BDCODEMP AND FOLCOMP.BDCODACCONV = ACCONV.BDCODACCONV)'||                                                                  /* 158041 Leonardo Schwab 05/06/2023 */
              wwheret;

       wsql = wsql||' union all '||
              'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, '||
                'tv.bdtiporefver, COLCON.BDREFFC, '||
                'COLCON.BDVALVFC, COLCON.BDIGNREFVFC, COLCON.BDIGNREFAVFC, COLCON.BDIGNVALVFC, '||
                'pf.bdCodCentro, toma.bdCODTPCC, COLCON.BDCODCONTTI '||
              'from VRHF_EMP_TVERBAFCTOMINT COLCON '||
              'join TEMPRESAS emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'left outer join VRHF_EMP_TPREPFN pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join VW_VERBAS_REF_ATUAL tv on (colcon.bdcodver = tv.bdcodver) '||
              'left outer join VRHF_SP_TOMADOR(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              'join VRHF_EMP_TFOLTOMCOMPINT FOLCOMP ON (COLCON.BDCODEMP = FOLCOMP.BDCODEMP AND COLCON.BDCODCOL = FOLCOMP.BDCODCOL AND COLCON.BDREFTOMADOR = FOLCOMP.BDREFTOMADOR AND COLCON.BDREFFC = FOLCOMP.BDREFFC AND COLCON.BDORDEM = FOLCOMP.BDORDEM AND COLCON.bdcodcontti  = FOLCOMP.bdcodcontti) '||  /* 158041 Leonardo Schwab 05/06/2023 */
              'left outer join VRH_EMP_TACCONV ACCONV ON (FOLCOMP.BDCODEMP = ACCONV.BDCODEMP AND FOLCOMP.BDCODACCONV = ACCONV.BDCODACCONV)'||                                                                  /* 158041 Leonardo Schwab 05/06/2023 */
              wwheret;

       wsql = wsql||') COLCON ';

       if (coalesce(prcodtpcc, '') <> '') then
          begin
            wsql = wsql||' where '||prcodtpcc|| ' ' ;
          end

       wsql = wsql||' group by COLCON.BDCODVER, colcon.bdcodemp,colcon.bdcodcol,colcon.BDCODCONTTI,colcon.BDREFTOMADOR, COLCON.BDREFCOMP, COLCON.bdCodCentro, COLCON.bdCODTPCC'||wgroupbydatapag;
     end
  else if (pragrupatomador = 2) then
     begin
       wsql = 'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, cast(null as integer), '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, sum(COLCON.BDREFVFC), max(COLCON.BDREFAUXVFC), '||
                'max(COLCON.BDREFVFC), sum(COLCON.BDREFAUXVFC), max(COLCON.bdtiporefver), '||
                'sum(COLCON.BDVALVFC), max(COLCON.BDIGNREFVFC), max(COLCON.BDIGNREFAVFC), max(COLCON.BDIGNVALVFC), '||
                'COLCON.bdCodCentro, COLCON.bdCODTPCC, '||
                wdatapag||
                ' from (';

       wsql = wsql||
              'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFFC, '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, '||
                'tv.bdtiporefver, '||
                'COLCON.BDVALVFC, COLCON.BDIGNREFVFC, COLCON.BDIGNREFAVFC, COLCON.BDIGNVALVFC, '||
                'pf.bdCodCentro, pf.bdCODTPCC, cast(null as INTEGER) BDCODCONTTI '||
              'from VRHF_EMP_TVERBAFCTOMADOR COLCON '||
              'join VRHF_EMP_TPREPFN pf on (pf.bdcodemp = colcon.bdcodemp and pf.bdcodcol = colcon.bdcodcol and pf.bdordem = colcon.bdordem) '||
              'join tempresas emp on (emp.bdcodemp = colcon.bdcodemp) '||
              'left outer join VW_VERBAS_REF_ATUAL tv on (tv.bdcodver = colcon.bdcodver) '||
              'join VRHF_EMP_TFOLTOMCOMP FOLCOMP ON (COLCON.BDCODEMP = FOLCOMP.BDCODEMP AND COLCON.BDCODCOL = FOLCOMP.BDCODCOL AND COLCON.BDREFTOMADOR = FOLCOMP.BDREFTOMADOR AND COLCON.BDREFFC = FOLCOMP.BDREFFC AND COLCON.BDORDEM = FOLCOMP.BDORDEM) '||  /* 158041 Leonardo Schwab 05/06/2023 */
              'left outer join VRH_EMP_TACCONV ACCONV ON (FOLCOMP.BDCODEMP = ACCONV.BDCODEMP AND FOLCOMP.BDCODACCONV = ACCONV.BDCODACCONV)'||                                                                  /* 158041 Leonardo Schwab 05/06/2023 */
              wwheret;

       wsql = wsql||' union all '||
              'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFFC, '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, '||
                'tv.bdtiporefver, '||
                'COLCON.BDVALVFC, COLCON.BDIGNREFVFC, COLCON.BDIGNREFAVFC, COLCON.BDIGNVALVFC, '||
                'pf.bdCodCentro, pf.bdCODTPCC, COLCON.BDCODCONTTI '||
              'from VRHF_EMP_TVERBAFCTOMINT COLCON '||
              'join VRHF_EMP_TPREPFN pf on (pf.bdcodemp = colcon.bdcodemp and pf.bdcodcol = colcon.bdcodcol and pf.bdordem = colcon.bdordem) '||
              'join tempresas emp on (emp.bdcodemp = colcon.bdcodemp) '||
              'left outer join VW_VERBAS_REF_ATUAL tv on (tv.bdcodver = colcon.bdcodver) '||
              'join VRHF_EMP_TFOLTOMCOMPINT FOLCOMP ON (COLCON.BDCODEMP = FOLCOMP.BDCODEMP AND COLCON.BDCODCOL = FOLCOMP.BDCODCOL AND COLCON.BDREFTOMADOR = FOLCOMP.BDREFTOMADOR AND COLCON.BDREFFC = FOLCOMP.BDREFFC AND COLCON.BDORDEM = FOLCOMP.BDORDEM AND COLCON.bdcodcontti  = FOLCOMP.bdcodcontti) '||  /* 158041 Leonardo Schwab 05/06/2023 */
              'left outer join VRH_EMP_TACCONV ACCONV ON (FOLCOMP.BDCODEMP = ACCONV.BDCODEMP AND FOLCOMP.BDCODACCONV = ACCONV.BDCODACCONV)'||                                                                  /* 158041 Leonardo Schwab 05/06/2023 */
              wwheret;

        wsql = wsql||') COLCON ';

        if (coalesce(prcodtpcc, '') <> '') then
          begin
            wsql = wsql||' where '||prcodtpcc|| ' ' ;
          end

        wsql = wsql||' group by COLCON.BDCODVER,colcon.bdcodemp,colcon.bdcodcol,colcon.BDCODCONTTI,colcon.BDREFTOMADOR,colcon.BDREFCOMP,COLCON.bdCodCentro, COLCON.bdCODTPCC'||wgroupbydatapag;
     end
  else if (pragrupatomador = 1) then
     begin
       wsql = 'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, cast(null as integer), '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, sum(COLCON.BDREFVFC), max(COLCON.BDREFAUXVFC), '||
                'max(COLCON.BDREFVFC), sum(COLCON.BDREFAUXVFC), max(COLCON.bdtiporefver), '||
                'sum(COLCON.BDVALVFC), max(COLCON.BDIGNREFVFC), max(COLCON.BDIGNREFAVFC), max(COLCON.BDIGNVALVFC), '||
                'cast(null as integer), cast(null as integer), '||
              wdatapag||
              ' from (';

       wsql = wsql||
              'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, COLCON.BDREFFC, '||
                'COLCON.BDREFVFC, COLCON.BDREFAUXVFC, tv.bdtiporefver, '||
                'COLCON.BDVALVFC, COLCON.BDIGNREFVFC, COLCON.BDIGNREFAVFC, COLCON.BDIGNVALVFC, '||
                'pf.BDCODCENTRO, pf.BDCODTPCC, cast(null as INTEGER) BDCODCONTTI '||
              'from VRHF_EMP_TVERBAFCTOMADOR COLCON '||
              'join TEMPRESAS emp on (emp.bdcodemp = colcon.bdcodemp) '||
              'join VRHF_EMP_TPREPFN pf on (pf.BDCODEMP = COLCON.BDCODEMP and pf.BDCODCOL = COLCON.BDCODCOL and pf.BDORDEM = COLCON.BDORDEM) '||
              'left outer join VW_VERBAS_REF_ATUAL tv on (tv.bdcodver = colcon.bdcodver) '||
              'join VRHF_EMP_TFOLTOMCOMP FOLCOMP ON (COLCON.BDCODEMP = FOLCOMP.BDCODEMP AND COLCON.BDCODCOL = FOLCOMP.BDCODCOL AND COLCON.BDREFTOMADOR = FOLCOMP.BDREFTOMADOR AND COLCON.BDREFFC = FOLCOMP.BDREFFC AND COLCON.BDORDEM = FOLCOMP.BDORDEM) '||  /* 158041 Leonardo Schwab 05/06/2023 */
              'left outer join VRH_EMP_TACCONV ACCONV ON (FOLCOMP.BDCODEMP = ACCONV.BDCODEMP AND FOLCOMP.BDCODACCONV = ACCONV.BDCODACCONV)'||                                                                  /* 158041 Leonardo Schwab 05/06/2023 */
              wwheret;

       wsql = wsql||' union all '||
              'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, COLCON.BDREFFC, '||
                'COLCON.BDREFVFC, COLCON.BDREFAUXVFC, tv.bdtiporefver, '||
                'COLCON.BDVALVFC, COLCON.BDIGNREFVFC, COLCON.BDIGNREFAVFC, COLCON.BDIGNVALVFC, '||
                'pf.BDCODCENTRO, pf.BDCODTPCC, COLCON.BDCODCONTTI '||
              'from VRHF_EMP_TVERBAFCTOMINT COLCON '||
              'join TEMPRESAS emp on (emp.bdcodemp = colcon.bdcodemp) '||
              'join VRHF_EMP_TPREPFN pf on (pf.BDCODEMP = COLCON.BDCODEMP and pf.BDCODCOL = COLCON.BDCODCOL and pf.BDORDEM = COLCON.BDORDEM) '||
              'left outer join VW_VERBAS_REF_ATUAL tv on (tv.bdcodver = colcon.bdcodver) '||
              'join VRHF_EMP_TFOLTOMCOMPINT FOLCOMP ON (COLCON.BDCODEMP = FOLCOMP.BDCODEMP AND COLCON.BDCODCOL = FOLCOMP.BDCODCOL AND COLCON.BDREFTOMADOR = FOLCOMP.BDREFTOMADOR AND COLCON.BDREFFC = FOLCOMP.BDREFFC AND COLCON.BDORDEM = FOLCOMP.BDORDEM AND COLCON.bdcodcontti  = FOLCOMP.bdcodcontti) '||  /* 158041 Leonardo Schwab 05/06/2023 */
              'left outer join VRH_EMP_TACCONV ACCONV ON (FOLCOMP.BDCODEMP = ACCONV.BDCODEMP AND FOLCOMP.BDCODACCONV = ACCONV.BDCODACCONV)'||                                                                  /* 158041 Leonardo Schwab 05/06/2023 */
              wwheret;

       wsql = wsql||') COLCON ';

        if (coalesce(prcodtpcc, '') <> '') then
          begin
            wsql = wsql||' where '||prcodtpcc|| ' ' ;
          end

        wsql = wsql||' group by COLCON.BDCODVER,colcon.bdcodemp,colcon.bdcodcol,colcon.BDCODCONTTI,colcon.BDREFTOMADOR,colcon.BDREFCOMP'||wgroupbydatapag;
     end
  else
     begin
       wsql = 'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, colcon.bdOrdem, '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, COLCON.bdtiporefver, COLCON.BDVALVFC, '||
                'COLCON.BDIGNREFVFC, COLCON.BDIGNREFAVFC, COLCON.BDIGNVALVFC, '||
                'COLCON.bdCodCentro, COLCON.bdCODTPCC, '||
                wdatapag||
              ' from (';

       wsql = wsql||
              'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, colcon.bdOrdem, '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, tv.bdtiporefver, COLCON.BDVALVFC, '||
                'COLCON.BDIGNREFVFC, COLCON.BDIGNREFAVFC, COLCON.BDIGNVALVFC, COLCON.BDREFFC, '||
                'pf.bdCodCentro, pf.bdCODTPCC, cast(null as INTEGER) BDCODCONTTI '||
              'from VRHF_EMP_TVERBAFCTOMADOR COLCON '||
              'join TEMPRESAS emp on (emp.bdcodemp = colcon.bdcodemp) '||
              'join VRHF_EMP_TPREPFN pf on (pf.bdcodemp = colcon.bdcodemp and pf.bdcodcol = colcon.bdcodcol and pf.bdordem = colcon.bdordem) '||
              'left outer join VW_VERBAS_REF_ATUAL tv on (tv.bdcodver = colcon.bdcodver) '||
              'join VRHF_EMP_TFOLTOMCOMP FOLCOMP ON (COLCON.BDCODEMP = FOLCOMP.BDCODEMP AND COLCON.BDCODCOL = FOLCOMP.BDCODCOL AND COLCON.BDREFTOMADOR = FOLCOMP.BDREFTOMADOR AND COLCON.BDREFFC = FOLCOMP.BDREFFC AND COLCON.BDORDEM = FOLCOMP.BDORDEM) '||  /* 158041 Leonardo Schwab 05/06/2023 */
              'left outer join VRH_EMP_TACCONV ACCONV ON (FOLCOMP.BDCODEMP = ACCONV.BDCODEMP AND FOLCOMP.BDCODACCONV = ACCONV.BDCODACCONV)'||                                                                  /* 158041 Leonardo Schwab 05/06/2023 */
              wwheret;

       wsql = wsql||' union all '||
              'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, colcon.bdOrdem, '||
                'COLCON.BDREFTOMADOR, colcon.BDREFCOMP, COLCON.BDREFVFC, COLCON.BDREFAUXVFC, tv.bdtiporefver, COLCON.BDVALVFC, '||
                'COLCON.BDIGNREFVFC, COLCON.BDIGNREFAVFC, COLCON.BDIGNVALVFC, COLCON.BDREFFC, '||
                'pf.bdCodCentro, pf.bdCODTPCC, COLCON.BDCODCONTTI '||
              'from VRHF_EMP_TVERBAFCTOMINT COLCON '||
              'join TEMPRESAS emp on (emp.bdcodemp = colcon.bdcodemp) '||
              'join VRHF_EMP_TPREPFN pf on (pf.bdcodemp = colcon.bdcodemp and pf.bdcodcol = colcon.bdcodcol and pf.bdordem = colcon.bdordem) '||
              'left outer join VW_VERBAS_REF_ATUAL tv on (tv.bdcodver = colcon.bdcodver) '||
              'join VRHF_EMP_TFOLTOMCOMPINT FOLCOMP ON (COLCON.BDCODEMP = FOLCOMP.BDCODEMP AND COLCON.BDCODCOL = FOLCOMP.BDCODCOL AND COLCON.BDREFTOMADOR = FOLCOMP.BDREFTOMADOR AND COLCON.BDREFFC = FOLCOMP.BDREFFC AND COLCON.BDORDEM = FOLCOMP.BDORDEM AND COLCON.bdcodcontti  = FOLCOMP.bdcodcontti) '||  /* 158041 Leonardo Schwab 05/06/2023 */
              'left outer join VRH_EMP_TACCONV ACCONV ON (FOLCOMP.BDCODEMP = ACCONV.BDCODEMP AND FOLCOMP.BDCODACCONV = ACCONV.BDCODACCONV)'||                                                                  /* 158041 Leonardo Schwab 05/06/2023 */
              wwheret;

       wsql = wsql||') COLCON ';

        if (coalesce(prcodtpcc, '') <> '') then
          begin
            wsql = wsql||' where '||prcodtpcc|| ' ' ;
          end
     end

  if (wsql <> '') then
     begin
       bdcalctomador = 'TRUE';
       for execute statement wsql
       into
         :bdcodver,
         :bdcodemp,
         :bdcodcol,
         :bdcodcontti,
         :bdOrdem,
         :bdreffn,
         :BDREFCOMP,
         :bdrefvfc,
         :bdrefauxvfc,
         :waux1,
         :waux2,
         :wauxtipo,
         :bdvalvfc,
         :bdignrefvfc,
         :bdignrefavfc,
         :bdignvalvfc,
         :bdcodcentro,
         :bdcodtpcc,
         :BDREFFC
       do
         begin
           if (wauxtipo = 4) then
              begin
                BDREFVFC = waux1;
                bdrefauxvfc = waux2;
              END
           SUSPEND;
         end
     end

end^

/* Restore proc. body: SP_VRHF_AGRUPA_VERBAS_FT */
create or alter procedure SP_VRHF_AGRUPA_VERBAS_FT (
    PRAGRUPADOR integer,
    PRREF integer,
    PRFILTRO varchar(32700) = null,
    PRFILTROCC varchar(20000) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFTOMADOR integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCODVER integer,
    BDREFVFT_SUM numeric(15,6),
    BDREFVFT_MAX numeric(15,6),
    BDREFAUXVFT numeric(15,6),
    BDVALVFT numeric(15,6),
    BDIGNREFVFT DM_BOOLEAN,
    BDIGNREFAVFT DM_BOOLEAN,
    BDIGNVALVFT DM_BOOLEAN,
    BDTIPOREFVER integer,
    BDCODCONTTI integer)
as
declare variable WSQL varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREFTOMADOR integer;
declare variable WORDEM integer;
declare variable WCODCENTRO integer;
declare variable WCODTPCC integer;
declare variable WCODVER integer;
declare variable WREFVFT numeric(15,6);
declare variable WREFAUXVFT numeric(15,6);
declare variable WVALVFT numeric(15,6);
declare variable WIGNREFFT DM_BOOLEAN;
declare variable WIGNREFAFT DM_BOOLEAN;
declare variable WIGNVALFT DM_BOOLEAN;
declare variable WHOREMP DM_BOOLEAN;
declare variable WTIPOREFVER integer;
declare variable WVERATU integer;
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WCENTROATU integer;
declare variable WTPCCATU integer;
declare variable WREFVTFANT_MAX numeric(15,6);
declare variable WREFVTFANT_SUM numeric(15,6);
declare variable WREFAUXVFTANT numeric(15,6);
declare variable WVALVFTANT numeric(15,6);
declare variable WIGNREFFTANT DM_BOOLEAN;
declare variable WIGNREFAFTANT DM_BOOLEAN;
declare variable WIGNVALFTANT DM_BOOLEAN;
declare variable WFRACAO numeric(15,6);
declare variable WCODCONTTI integer;
declare variable WCONTTIATU integer;
BEGIN
  IF (pragrupador IS NOT NULL AND pragrupador IN (2,3,4)) THEN
     BEGIN
       wordem = NULL;
       wsql = 'select BDCODVER, BDCODEMP, BDCODCOL, BDREFTOMADOR, BDREFVFT, BDREFAUXVFT, BDVALVFT, BDIGNREFVFT, BDIGNREFAVFT, BDIGNVALVFT, BDCODCENTRO, BDCODTPCC, BDCODCONTTI '||
              ' from (select '||
              'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, '||
              'COLCON.BDREFTOMADOR, COLCON.BDREFVFT, COLCON.BDREFAUXVFT,'||
              'COLCON.BDVALVFT, COLCON.BDIGNREFVFT, COLCON.BDIGNREFAVFT, COLCON.BDIGNVALVFT,';

       IF (pragrupador = 2) THEN
          wsql = wsql||'case when COALESCE(pf.bdCODTPCC,0) = 0 then 0 else COALESCE(pf.bdCodCentro,0) end BDCODCENTRO, COALESCE(pf.bdCODTPCC,0) BDCODTPCC, ';
       ELSE
          wsql = wsql||'case when COALESCE(toma.bdCODTPCC,0) = 0 then 0 else COALESCE(toma.bdCodCentro,0) end BDCODCENTRO, COALESCE(toma.bdCODTPCC,0) BDCODTPCC, ';

       wsql = wsql||
              '0 BDCODCONTTI '||
              'from vrhf_emp_tverbatomador COLCON '||
              'join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) ';

       IF (pragrupador = 3) THEN
          wsql = wsql||'left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) ';
       ELSE
       IF (pragrupador = 4) THEN
          wsql = wsql||'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro,'||prref||') toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) ';

       IF (prfiltro IS NOT NULL AND prfiltro <> '') THEN
          wsql = wsql||prfiltro;

       wsql = wsql||' union all select '||
              'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, '||
              'COLCON.BDREFTOMADOR, COLCON.BDREFVFT, COLCON.BDREFAUXVFT,'||
              'COLCON.BDVALVFT, COLCON.BDIGNREFVFT, COLCON.BDIGNREFAVFT, COLCON.BDIGNVALVFT,';

       IF (pragrupador = 2) THEN
          wsql = wsql||'case when COALESCE(pf.bdCODTPCC,0) = 0 then 0 else COALESCE(pf.bdCodCentro,0) end BDCODCENTRO, COALESCE(pf.bdCODTPCC,0) BDCODTPCC, ';
       ELSE
          wsql = wsql||'case when COALESCE(toma.bdCODTPCC,0) = 0 then 0 else COALESCE(toma.bdCodCentro,0) end BDCODCENTRO, COALESCE(toma.bdCODTPCC,0) BDCODTPCC, ';

       wsql = wsql||
              'COLCON.BDCODCONTTI '||
              'from vrhf_emp_tverbatomint COLCON '||
              'join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) ';

       IF (pragrupador = 3) THEN
          wsql = wsql||'left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) ';
       ELSE
       IF (pragrupador = 4) THEN
          wsql = wsql||'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro,'||prref||') toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) ';

       IF (prfiltro IS NOT NULL AND prfiltro <> '') THEN
          wsql = wsql||prfiltro;


       wsql = wsql||') COLCON ';
       IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
          wsql = wsql||' where '||prfiltrocc;

       wsql = wsql||' order by BDCODEMP,BDCODCOL,BDREFTOMADOR,BDCODCONTTI,BDCODCENTRO,BDCODTPCC,BDCODVER ';

       wveratu        = 0;
       wempatu        = 0;
       wcolatu        = 0;
       wrefatu        = 0;
       wcentroatu     = -1;
       wtpccatu       = -1;
       wrefvtfant_sum = 0;
       wrefvtfant_max = 0;
       wrefauxvftant  = 0;
       wvalvftant     = 0;
       wignrefaftant  = '';
       wignrefftant   = '';
       wignvalftant   = '';
       wconttiatu     = -1;
       whoremp        = 'FALSE';

       FOR EXECUTE STATEMENT wsql INTO :wcodver,:wcodemp,:wcodcol,:wreftomador,:wrefvft,:wrefauxvft,:wvalvft,:wignrefft,:wignrefaft,:wignvalft,:wcodcentro,:wcodtpcc,:wcodcontti DO
         BEGIN
           if ((wempatu <> wcodemp) or (wrefatu <> wreftomador)) then
              begin
                select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = :wcodemp and BDREFEMP <= :wreftomador order by BDREFEMP DESC into :whoremp;
                whoremp = upper(coalesce(whoremp, 'FALSE'));
              end

           IF (wveratu = 0) THEN
              wveratu = wcodver;
           IF (wempatu = 0) THEN
              wempatu = wcodemp;
           IF (wcolatu = 0) THEN
              wcolatu = wcodcol;
           IF (wrefatu = 0) THEN
              wrefatu = wreftomador;
           IF (wcentroatu = -1) THEN
              wcentroatu = wcodcentro;
           IF (wtpccatu = -1) THEN
              wtpccatu = wcodtpcc;
           IF (wconttiatu = -1) THEN
              wconttiatu = wcodcontti;

           IF ((wveratu <> wcodver) OR (wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wrefatu <> wreftomador) OR (wcentroatu <> wcodcentro) OR (wtpccatu <> wcodtpcc) OR (wconttiatu <> wcodcontti)) THEN
              BEGIN
                BDCODVER     = wveratu;
                BDCODEMP     = wempatu;
                BDCODCOL     = wcolatu;
                BDREFTOMADOR = wrefatu;

                if (wconttiatu = 0) then
                   BDCODCONTTI = NULL;
                else
                   BDCODCONTTI = wconttiatu;

                IF (wcentroatu = 0) THEN
                   BDCODCENTRO = NULL;
                ELSE
                   BDCODCENTRO  = wcentroatu;

                IF (wtpccatu = 0) THEN
                   BDCODTPCC = NULL;
                ELSE
                   BDCODTPCC    = wtpccatu;

                BDORDEM      = wordem;
                BDREFVFT_SUM = wrefvtfant_sum;
                BDREFVFT_MAX = wrefvtfant_max;
                BDREFAUXVFT  = wrefauxvftant;
                BDVALVFT     = wvalvftant;
                BDIGNREFAVFT = wignrefaftant;
                BDIGNREFVFT  = wignrefftant;
                BDIGNVALVFT  = wignvalftant;
                BDTIPOREFVER = wtiporefver;
                SUSPEND;
                wveratu        = wcodver;
                wempatu        = wcodemp;
                wcolatu        = wcodcol;
                wrefatu        = wreftomador;
                wcentroatu     = wcodcentro;
                wtpccatu       = wcodtpcc;
                wconttiatu     = wcodcontti;
                wrefvtfant_sum = 0;
                wrefvtfant_max = 0;
                wrefauxvftant  = 0;
                wvalvftant     = 0;
                wignrefaftant  = '';
                wignrefftant   = '';
                wignvalftant   = '';
              END

           wignrefaftant = wignrefaft;
           wignrefftant  = wignrefft;
           wignvalftant  = wignvalft;

           wvalvftant    = wvalvftant + wvalvft;
           wrefauxvftant = wrefauxvftant + wrefauxvft;

           IF (wrefvtfant_max < wrefvft) THEN
              wrefvtfant_max = wrefvft;

           select first 1 BDTIPOREFVER from VRH_BASE_TVERBAS_REF where BDCODVER = :wveratu and BDREFVER <= :wrefatu order by BDREFVER desc into :wtiporefver;
           -- Converte horas e tipo de referência da verba é Horas
           IF (UPPER(whoremp) = 'TRUE' AND wtiporefver = 1 AND wrefvft > 0) THEN
              BEGIN
                -- Converte a referencia atual de Horas para Valor
                wfracao      = wrefvft - CAST((wrefvft - 0.5) AS INTEGER);
                IF (wrefvft > 0) THEN
                   BEGIN
                     wrefvft = wrefvft - wfracao;
                     wfracao = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                     wrefvft = wrefvft + wfracao;
                   END
     
                -- Converte a soma atual de Horas para Valor
                wfracao  = wrefvtfant_sum - CAST((wrefvtfant_sum - 0.5) AS INTEGER);
                IF (wrefvtfant_sum > 0) THEN
                   BEGIN
                     wrefvtfant_sum = wrefvtfant_sum - wfracao;
                     wfracao        = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                     wrefvtfant_sum = wrefvtfant_sum + wfracao;
                   END
     
                -- Soma os VALORES
                wrefvtfant_sum = wrefvtfant_sum +  wrefvft;
     
                -- Converte o resultado novamente em Horas
                wfracao  = wrefvtfant_sum - CAST((wrefvtfant_sum - 0.5) AS INTEGER);
                IF (wrefvtfant_sum > 0) THEN
                   BEGIN
                     wrefvtfant_sum = wrefvtfant_sum - wfracao;
                     wfracao        = CAST((wfracao / 100 * 60) AS NUMERIC(15,2));
                     wrefvtfant_sum = wrefvtfant_sum + wfracao;
                   END
              END
           ELSE
              wrefvtfant_sum = wrefvtfant_sum + wrefvft;

         END

       IF ((wveratu <> 0) AND (wempatu <> 0) AND (wcolatu <> 0) AND (wrefatu <> 0) AND (wcentroatu <> -1) AND (wtpccatu <> -1) AND (wconttiatu <> -1)) THEN
          BEGIN
            BDCODVER     = wveratu;
            BDCODEMP     = wempatu;
            BDCODCOL     = wcolatu;
            BDREFTOMADOR = wrefatu;

            if (wconttiatu = 0) then
               BDCODCONTTI  = NULL;
            else
               BDCODCONTTI  = wconttiatu;

            IF (wcentroatu = 0) THEN
               BDCODCENTRO = NULL;
            ELSE
               BDCODCENTRO  = wcentroatu;

            IF (wtpccatu = 0) THEN
               BDCODTPCC = NULL;
            ELSE
               BDCODTPCC    = wtpccatu;

            BDORDEM      = NULL;
            BDREFVFT_SUM = wrefvtfant_sum;
            BDREFVFT_MAX = wrefvtfant_max;
            BDREFAUXVFT  = wrefauxvftant;
            BDVALVFT     = wvalvftant;
            BDIGNREFAVFT = wignrefaftant;
            BDIGNREFVFT  = wignrefftant;
            BDIGNVALVFT  = wignvalftant;
            BDTIPOREFVER = wtiporefver;
            SUSPEND;
          END
     END
  ELSE
  IF (pragrupador IS NOT NULL AND pragrupador = 1) THEN
     BEGIN
       wordem = NULL;
       wsql = 'select * from (select '||
              'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, '||
              'COLCON.BDREFTOMADOR, COLCON.BDREFVFT, COLCON.BDREFAUXVFT,'||
              'COLCON.BDVALVFT, COLCON.BDIGNREFVFT, COLCON.BDIGNREFAVFT, COLCON.BDIGNVALVFT,';

       wsql = wsql||
              '0 BDCODCONTTI ';

       IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
          wsql = wsql||',COALESCE(pf.bdCodCentro,0) BDCODCENTRO, COALESCE(pf.bdCODTPCC,0) BDCODTPCC ';
       ELSE
          wsql = wsql||',cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';

       wsql = wsql||
              'from vrhf_emp_tverbatomador COLCON '||
              'join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) ';

       IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
          wsql = wsql||'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) ';

       IF (prfiltro IS NOT NULL AND prfiltro <> '') THEN
          wsql = wsql||prfiltro;


       wsql = wsql||' union all select '||
              'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, '||
              'COLCON.BDREFTOMADOR, COLCON.BDREFVFT, COLCON.BDREFAUXVFT,'||
              'COLCON.BDVALVFT, COLCON.BDIGNREFVFT, COLCON.BDIGNREFAVFT, COLCON.BDIGNVALVFT,';

       wsql = wsql||
              'COLCON.BDCODCONTTI ';

       IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
          wsql = wsql||',COALESCE(pf.bdCodCentro,0) BDCODCENTRO, COALESCE(pf.bdCODTPCC,0) BDCODTPCC ';
       ELSE
          wsql = wsql||',cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';

       wsql = wsql||
              'from vrhf_emp_tverbatomint COLCON '||
              'join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) ';

       IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
          wsql = wsql||'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) ';

       IF (prfiltro IS NOT NULL AND prfiltro <> '') THEN
          wsql = wsql||prfiltro;

       wsql = wsql||') COLCON ';
       IF (prfiltrocc IS NOT NULL AND prfiltrocc <> '') THEN
          wsql = wsql||' where '||prfiltrocc;

       wsql = wsql||' order by BDCODEMP,BDCODCOL,BDREFTOMADOR,BDCODCONTTI,BDCODVER ';

       wveratu        = 0;
       wempatu        = 0;
       wcolatu        = 0;
       wrefatu        = 0;
       wrefvtfant_sum = 0;
       wrefvtfant_max = 0;
       wrefauxvftant  = 0;
       wvalvftant     = 0;
       wignrefaftant  = '';
       wignrefftant   = '';
       wignvalftant   = '';
       wconttiatu     = -1;
       whoremp        = 'FALSE';

       FOR EXECUTE STATEMENT wsql INTO :wcodver,:wcodemp,:wcodcol,:wreftomador,:wrefvft,:wrefauxvft,:wvalvft,:wignrefft,:wignrefaft,:wignvalft,:wcodcontti, :wcodcentro, :wcodtpcc DO
         BEGIN
           if ((wempatu <> wcodemp) or (wrefatu <> wreftomador)) then
              begin
                select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = :wcodemp and BDREFEMP <= :wreftomador order by BDREFEMP DESC into :whoremp;
                whoremp = upper(coalesce(whoremp, 'FALSE'));
              end

           IF (wveratu = 0) THEN
              wveratu = wcodver;
           IF (wempatu = 0) THEN
              wempatu = wcodemp;
           IF (wcolatu = 0) THEN
              wcolatu = wcodcol;
           IF (wrefatu = 0) THEN
              wrefatu = wreftomador;
           if (wconttiatu = -1) then
              wconttiatu = wcodcontti;

           IF ((wveratu <> wcodver) OR (wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wrefatu <> wreftomador) OR (wconttiatu <> wcodcontti)) THEN
              BEGIN
                BDCODVER     = wveratu;
                BDCODEMP     = wempatu;
                BDCODCOL     = wcolatu;
                BDREFTOMADOR = wrefatu;

                if (wconttiatu = 0) then
                   BDCODCONTTI = null;
                else
                   BDCODCONTTI = wconttiatu;

                BDCODCENTRO  = NULL;
                BDCODTPCC    = NULL;
                BDORDEM      = wordem;
                BDREFVFT_SUM = wrefvtfant_sum;
                BDREFVFT_MAX = wrefvtfant_max;
                BDREFAUXVFT  = wrefauxvftant;
                BDVALVFT     = wvalvftant;
                BDIGNREFAVFT = wignrefaftant;
                BDIGNREFVFT  = wignrefftant;
                BDIGNVALVFT  = wignvalftant;
                BDTIPOREFVER = wtiporefver;
                SUSPEND;
                wveratu        = wcodver;
                wempatu        = wcodemp;
                wcolatu        = wcodcol;
                wrefatu        = wreftomador;
                wconttiatu     = wcodcontti;
                wrefvtfant_sum = 0;
                wrefvtfant_max = 0;
                wrefauxvftant  = 0;
                wvalvftant     = 0;
                wignrefaftant  = '';
                wignrefftant   = '';
                wignvalftant   = '';
              END

           wignrefaftant = wignrefaft;
           wignrefftant  = wignrefft;
           wignvalftant  = wignvalft;

           wvalvftant    = wvalvftant + wvalvft;
           wrefauxvftant = wrefauxvftant + wrefauxvft;

           IF (wrefvtfant_max < wrefvft) THEN
              wrefvtfant_max = wrefvft;

           select first 1 BDTIPOREFVER from VRH_BASE_TVERBAS_REF where BDCODVER = :wveratu and BDREFVER <= :wrefatu order by BDREFVER desc into :wtiporefver;
           -- Converte horas e tipo de referência da verba é Horas
           IF (UPPER(whoremp) = 'TRUE' AND wtiporefver = 1 AND wrefvft > 0) THEN
              BEGIN
                -- Converte a referencia atual de Horas para Valor
                wfracao      = wrefvft - CAST((wrefvft - 0.5) AS INTEGER);
                IF (wrefvft > 0) THEN
                   BEGIN
                     wrefvft = wrefvft - wfracao;
                     wfracao = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                     wrefvft = wrefvft + wfracao;
                   END
     
                -- Converte a soma atual de Horas para Valor
                wfracao  = wrefvtfant_sum - CAST((wrefvtfant_sum - 0.5) AS INTEGER);
                IF (wrefvtfant_sum > 0) THEN
                   BEGIN
                     wrefvtfant_sum = wrefvtfant_sum - wfracao;
                     wfracao        = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                     wrefvtfant_sum = wrefvtfant_sum + wfracao;
                   END
     
                -- Soma os VALORES
                wrefvtfant_sum = wrefvtfant_sum +  wrefvft;
     
                -- Converte o resultado novamente em Horas
                wfracao  = wrefvtfant_sum - CAST((wrefvtfant_sum - 0.5) AS INTEGER);
                IF (wrefvtfant_sum > 0) THEN
                   BEGIN
                     wrefvtfant_sum = wrefvtfant_sum - wfracao;
                     wfracao        = CAST((wfracao / 100 * 60) AS NUMERIC(15,2));
                     wrefvtfant_sum = wrefvtfant_sum + wfracao;
                   END
              END
           ELSE
              wrefvtfant_sum = wrefvtfant_sum + wrefvft;

         END

       IF ((wveratu <> 0) AND (wempatu <> 0) AND (wcolatu <> 0) AND (wrefatu <> 0) AND (wconttiatu <> -1)) THEN
          BEGIN
            BDCODVER     = wveratu;
            BDCODEMP     = wempatu;
            BDCODCOL     = wcolatu;
            BDREFTOMADOR = wrefatu;

            if (wconttiatu = 0) then
               BDCODCONTTI = null;
            else
               BDCODCONTTI = wconttiatu;

            BDCODCENTRO  = NULL;
            BDCODTPCC    = NULL;
            BDORDEM      = wordem;
            BDREFVFT_SUM = wrefvtfant_sum;
            BDREFVFT_MAX = wrefvtfant_max;
            BDREFAUXVFT  = wrefauxvftant;
            BDVALVFT     = wvalvftant;
            BDIGNREFAVFT = wignrefaftant;
            BDIGNREFVFT  = wignrefftant;
            BDIGNVALVFT  = wignvalftant;
            BDTIPOREFVER = wtiporefver;
            SUSPEND;
          END
     END
END^


/* Restore proc. body: VRHF_SP_TVERBAFN */
create or alter procedure VRHF_SP_TVERBAFN (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(2788) = null)
returns (
    BDCODVER integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFVFN numeric(15,6),
    BDREFAUXVFN numeric(15,6),
    BDVALVFN numeric(15,6),
    BDIGNREFVFN varchar(5),
    BDIGNREFAVFN varchar(5),
    BDIGNVALVFN varchar(5),
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDCODCONTTI integer)
as
declare variable WSQL varchar(32700);
declare variable WWHEREN varchar(32700);
declare variable WWHERET varchar(32700);
declare variable WMAXREF numeric(15,6);
declare variable WSUMREF numeric(15,6);
declare variable WTIPOREF integer;
BEGIN
  /* pragrupatomador
     0 = Nao agrupa
     1 = Agrupa por referencia
     2 = Agrupo por referencia e Tomador/centro custo
     3 = Agrupo por referencia e Tomador
     4 = Agrupa por referencia e Tipo Tomador (so vai criar mais registros pra empresa se for tomador 155)
  */

  /* Procedure Text */
  wsql = 'select COLCON.bdcodver, COLCON.bdcodemp, COLCON.bdcodcol, COLCON.bdreffn, COLCON.bdrefvfn,'||
         'COLCON.bdrefauxvfn, COLCON.bdvalvfn, COLCON.bdignrefvfn, COLCON.bdignrefavfn, COLCON.bdignvalvfn, cast(null as INTEGER) BDCODCONTTI '||
         ' from vrhf_emp_tverbafn COLCON';

  if (position(upper('tmp_empresas_select'), upper(prcodemp)) > 0) then
    wsql = wsql ||' '||prcodemp;

  IF (prpuxafiliais = 1) THEN
     BEGIN
       wsql = wsql||' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) ';

       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '') and (position(upper('tmp_empresas_select'), upper(prcodemp)) <= 0)) THEN
          BEGIN
            prcodemp = UPPER(prcodemp);
     
            IF ((prfiliais IS NOT NULL) AND (prfiliais <> '')) THEN
               BEGIN
                 SELECT bdresult FROM strtran(:prcodemp,'COLCON.BDCODEMP','EMP.BDCODMATRIZ') INTO wwheren;
                 prcodemp = '('||prcodemp||' or (('||wwheren||') and (emp.bdcodemp in ('||prfiliais||'))))';
               END
            ELSE
               BEGIN
                 SELECT bdresult FROM strtran(:prcodemp,'COLCON.BDCODEMP','coalesce(emp.bdcodmatriz,emp.bdcodemp)') INTO prcodemp;
               END
          END
     END

  wwheren = '';
  wwheret = '';

  IF ((prcodemp IS NOT NULL) and (position(upper('tmp_empresas_select'), upper(prcodemp)) <= 0)) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||' where ';
          END

       wwheren = wwheren||prcodemp;
       wwheret = wwhereT||prcodemp;
     END

  IF (prcodcol IS NOT NULL) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||' where ';
          END

       wwheren = wwheren||prcodcol;
       wwheret = wwhereT||prcodcol;
     END

  IF ((prrefini IS NOT NULL) AND (prreffim IS NOT NULL)) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||' where ';
          END

       wwheren = wwheren||'BDREFFN >= '||prrefini||' and '||'BDREFFN <= '||prreffim;
       wwheret = wwhereT||'BDREFTOMADOR >= '||prrefini||' and '||'BDREFTOMADOR <= '||prreffim;
     END
  ELSE
     BEGIN
       IF (prrefini IS NOT NULL) THEN
          BEGIN
            IF (wwheren <> '') THEN
               BEGIN
                 wwheren = wwheren||' and ';
                 wwheret = wwheret||' and ';
               END
            ELSE
               BEGIN
                 wwheren = wwheren||' where ';
                 wwheret = wwheret||' where ';
               END

            wwheren = wwheren||'BDREFFN = '||prrefini;
            wwheret = wwhereT||'BDREFTOMADOR = '||prrefini;
          END
       ELSE
          BEGIN
            IF (prreffim IS NOT NULL) THEN
               BEGIN
                 IF (wwheren <> '') THEN
                    BEGIN
                      wwheren = wwheren||' and ';
                      wwheret = wwheret||' and ';
                    END
                 ELSE
                    BEGIN
                      wwheren = wwheren||' where ';
                      wwheret = wwheret||' where ';
                    END

                 wwheren = wwheren||'BDREFFN = '||prreffim;
                 wwheret = wwhereT||'BDREFTOMADOR = '||prreffim;
               END
          END
     END

  wsql = wsql||wwheren;


  wsql = wsql||' union all ';


  wsql = wsql||'select COLCON.bdcodver, COLCON.bdcodemp, COLCON.bdcodcol, COLCON.bdreffn, COLCON.bdrefvfn,'||
         'COLCON.bdrefauxvfn, COLCON.bdvalvfn, COLCON.bdignrefvfn, COLCON.bdignrefavfn, COLCON.bdignvalvfn, COLCON.BDCODCONTTI '||
         ' from vrhf_emp_tverbaint COLCON';

  IF (prpuxafiliais = 1) THEN
     wsql = wsql||' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) ';     

  wsql = wsql||wwheren;

  IF ((prcodtpcc IS NULL) OR (prcodtpcc = '')) THEN
     BEGIN
       FOR EXECUTE STATEMENT wsql
       INTO
         :bdcodver,
         :bdcodemp,
         :bdcodcol,
         :bdreffn,
         :bdrefvfn,
         :bdrefauxvfn,
         :bdvalvfn,
         :bdignrefvfn,
         :bdignrefavfn,
         :bdignvalvfn,
         :bdcodcontti
       DO
         BEGIN
           bdcalctomador = 'FALSE';

           if (bdcodcontti is null) then
              bdcodcontti = 0;
           SUSPEND;
         END
    END

  IF (prreffim IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);
  ELSE IF (prrefini IS NOT NULL) THEN
     EXECUTE PROCEDURE sp_seta_competencia(prrefini, NULL, NULL);


  IF ((pragrupatomador IS NOT NULL) AND (pragrupatomador IN (1,2,3,4))) THEN
     BEGIN
       wwheret = replace(wwheret, 'BDREFTOMADOR', 'COLCON.BDREFTOMADOR');

       wsql = 'select BDCODVER,BDCODEMP,BDCODCOL,BDORDEM,BDREFTOMADOR,BDREFVFT_SUM,BDREFVFT_MAX,BDREFAUXVFT,BDVALVFT,BDIGNREFVFT,BDIGNREFAVFT,'||
              'BDIGNVALVFT,BDCODCENTRO,BDCODTPCC,BDTIPOREFVER,BDCODCONTTI from SP_VRHF_AGRUPA_VERBAS_FT('||pragrupatomador||','||prrefini||','''||wwheret||''',';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||''''||prcodtpcc||''') ';
       ELSE
          wsql = wsql||'null) ';

     END
  ELSE
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, colcon.bdOrdem, '||
                'COLCON.BDREFTOMADOR, COLCON.BDREFVFT,COLCON.BDREFVFT, COLCON.BDREFAUXVFT, COLCON.BDVALVFT, '||
                'COLCON.BDIGNREFVFT, COLCON.BDIGNREFAVFT, COLCON.BDIGNVALVFT, '||
                'COLCON.bdCodCentro, COLCON.bdCODTPCC, VERREF.BDTIPOREFVER, cast(null as INTEGER) BDCODCONTTI '||
              'from ( ';

       wsql = wsql||'select '||
              'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, colcon.bdOrdem,'||
              'COLCON.BDREFTOMADOR, COLCON.BDREFVFT, COLCON.BDREFAUXVFT, COLCON.BDVALVFT,'||
              'COLCON.BDIGNREFVFT, COLCON.BDIGNREFAVFT, COLCON.BDIGNVALVFT, '||
              'pf.bdCodCentro, pf.bdCODTPCC '||
              ' from vrhf_emp_tverbatomador COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              ' join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              wwheret||') COLCON ';
       wsql = wsql||
              'left outer join (select BDCODVER, max(BDREFVER) BDREFVER from VRH_BASE_TVERBAS_REF where BDREFVER <= '||prrefini||' group by BDCODVER) VERREF2 on (VERREF2.BDCODVER = COLCON.BDCODVER) '||
              'left outer join VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = COLCON.BDCODVER and VERREF.BDREFVER = VERREF2.BDREFVER) ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;


       wsql = wsql||' union all select '||
                'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, colcon.bdOrdem, '||
                'COLCON.BDREFTOMADOR, COLCON.BDREFVFT,COLCON.BDREFVFT, COLCON.BDREFAUXVFT, COLCON.BDVALVFT, '||
                'COLCON.BDIGNREFVFT, COLCON.BDIGNREFAVFT, COLCON.BDIGNVALVFT, '||
                'COLCON.bdCodCentro, COLCON.bdCODTPCC, VERREF.BDTIPOREFVER, COLCON.BDCODCONTTI '||
              'from ( ';

       wsql = wsql||'select '||
              'COLCON.BDCODVER, COLCON.BDCODEMP, COLCON.BDCODCOL, colcon.bdOrdem,'||
              'COLCON.BDREFTOMADOR, COLCON.BDREFVFT, COLCON.BDREFAUXVFT, COLCON.BDVALVFT,'||
              'COLCON.BDIGNREFVFT, COLCON.BDIGNREFAVFT, COLCON.BDIGNVALVFT, '||
              'pf.bdCodCentro, pf.bdCODTPCC, COLCON.BDCODCONTTI '||
              ' from vrhf_emp_tverbatomint COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              ' join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              wwheret||') COLCON ';
       wsql = wsql||
              'left outer join (select BDCODVER, max(BDREFVER) BDREFVER from VRH_BASE_TVERBAS_REF where BDREFVER <= '||prrefini||' group by BDCODVER) VERREF2 on (VERREF2.BDCODVER = COLCON.BDCODVER) '||
              'left outer join VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = COLCON.BDCODVER and VERREF.BDREFVER = VERREF2.BDREFVER) ';

       IF (prcodtpcc IS NOT NULL AND prcodtpcc <> '') THEN
          wsql = wsql||' where '||prcodtpcc;
     END

  IF (wsql <> '') THEN
     BEGIN
       FOR EXECUTE STATEMENT wsql
       INTO
         :bdcodver,
         :bdcodemp,
         :bdcodcol,
         :bdOrdem,
         :bdreffn,
         :wsumref,
         :wmaxref,
         :bdrefauxvfn,
         :bdvalvfn,
         :bdignrefvfn,
         :bdignrefavfn,
         :bdignvalvfn,
         :bdcodcentro,
         :bdcodtpcc,
         :wtiporef,
         :bdcodcontti
       DO
         BEGIN
           bdcalctomador = 'TRUE';

           IF (wtiporef = 4) THEN
              bdrefvfn = wmaxref;
           ELSE
              bdrefvfn = wsumref;

           if (bdcodcontti is null) then
              bdcodcontti = 0;

           SUSPEND;
         END
     END
END^

/* Restore proc. body: VRHF_SP_TVERBAFN_PREV_RESC */
ALTER PROCEDURE VRHF_SP_TVERBAFN_PREV_RESC(PRCODEMP VARCHAR(32700),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRAGRUPATOMADOR INTEGER)
 RETURNS(BDCODVER INTEGER,
BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDREFFNPR INTEGER,
BDREFVFNPR NUMERIC(15,6),
BDREFAUXVFNPR NUMERIC(15,6),
BDVALVFNPR NUMERIC(15,6),
BDIGNREFVFNPR VARCHAR(5),
BDIGNVALVFNPR VARCHAR(5),
BDORDEM INTEGER,
BDCODCENTRO INTEGER,
BDCODTPCC INTEGER,
BDCALCTOMADOR VARCHAR(5))
 AS
DECLARE VARIABLE wsql VARCHAR(32700);
DECLARE VARIABLE wwheren VARCHAR(32700);
DECLARE VARIABLE wwheret VARCHAR(32700);
DECLARE VARIABLE wsql2 VARCHAR(32700);
BEGIN
  /* pragrupatomador
     0 = Nao agrupa
     1 = Agrupa por referencia
     2 = Agrupo por referencia e Tomador
  */

  /* Procedure Text */
  wsql = 'select bdcodver, bdcodemp, bdcodcol, bdreffnpr, bdrefvfnpr,'||
         'bdrefauxvfnpr, bdvalvfnpr, bdignrefvfnpr, bdignvalvfnpr'||
         ' from vrhf_emp_tverbafn_prev_resc COLCON';

  wwheren = '';
  wwheret = '';

  IF (prcodemp IS NOT NULL) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||' where ';
          END

       wwheren = wwheren||prcodemp;
       wwheret = wwhereT||prcodemp;
     END

  IF (prcodcol IS NOT NULL) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||' where ';
          END

       wwheren = wwheren||prcodcol;
       wwheret = wwhereT||prcodcol;
     END

  IF ((prrefini IS NOT NULL) AND (prreffim IS NOT NULL)) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||' where ';
          END

       wwheren = wwheren||'BDREFfnpr >= '||prrefini||' and '||'BDREFfnpr <= '||prreffim;
       wwheret = wwhereT||'BDREFTOMADOR >= '||prrefini||' and '||'BDREFTOMADOR <= '||prreffim;
     END
  ELSE
     BEGIN
       IF (prrefini IS NOT NULL) THEN
          BEGIN
            IF (wwheren <> '') THEN
               BEGIN
                 wwheren = wwheren||' and ';
                 wwheret = wwheret||' and ';
               END
            ELSE
               BEGIN
                 wwheren = wwheren||' where ';
                 wwheret = wwheret||' where ';
               END

            wwheren = wwheren||'BDREFfnpr = '||prrefini;
            wwheret = wwhereT||'BDREFTOMADOR = '||prrefini;
          END
       ELSE
          BEGIN
            IF (prreffim IS NOT NULL) THEN
               BEGIN
                 IF (wwheren <> '') THEN
                    BEGIN
                      wwheren = wwheren||' and ';
                      wwheret = wwheret||' and ';
                    END
                 ELSE
                    BEGIN
                      wwheren = wwheren||' where ';
                      wwheret = wwheret||' where ';
                    END

                 wwheren = wwheren||'BDREFfnpr = '||prreffim;
                 wwheret = wwhereT||'BDREFTOMADOR = '||prreffim;
               END
          END
     END


  FOR EXECUTE STATEMENT wsql||wwheren
  INTO
    :bdcodver,
    :bdcodemp,
    :bdcodcol,
    :bdreffnpr,
    :bdrefvfnpr,
    :bdrefauxvfnpr,
    :bdvalvfnpr,
    :bdignrefvfnpr,
    :bdignvalvfnpr
  DO
    BEGIN
      bdcalctomador = 'FALSE';
      SUSPEND;
    END

END
^

/* Restore proc. body: VRHF_SP_UNION_VERBAS_SIM_NAO */
ALTER PROCEDURE VRHF_SP_UNION_VERBAS_SIM_NAO(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRCODSINTRAB VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRLOCAL VARCHAR(100),
PRSIMNAO VARCHAR(100))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODSIND INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(40),
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF BLOB,
BDFORMVAL BLOB,
BDDESCCOND BLOB,
BDLOCAL VARCHAR(10),
BDSIMNAO INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(15000);
DECLARE VARIABLE WSQLFUNC VARCHAR(15000);
DECLARE VARIABLE WDATAINI VARCHAR(8);
DECLARE VARIABLE WDATAFIM VARCHAR(8);
DECLARE VARIABLE WDTAUX VARCHAR(10);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(NULL, prdataini, prdatafim);

  wdtaux = CAST(prdataini AS VARCHAR(10));
  wdataini = SUBSTRING(wdtaux FROM 1 FOR 4)||SUBSTRING(wdtaux FROM 6 FOR 2)||SUBSTRING(wdtaux FROM 9 FOR 2);

  wdtaux = CAST(prdatafim AS VARCHAR(10));
  wdatafim = SUBSTRING(wdtaux FROM 1 FOR 4)||SUBSTRING(wdtaux FROM 6 FOR 2)||SUBSTRING(wdtaux FROM 9 FOR 2);


  wsql = 'select t.BDCODEMP, '||
                'empresas.BDNOMEMP, '||
                'empresas.bdcnpjemp, '||
                't.BDCODCOL, '||
                'vw_col.bdnomcol,'||
                'COL_DIAVINC.BDCODPLAFUC,'||
                'COL_DIAVINC.BDCODTFUC,'||
                't.BDCODSINTRAB, '||
                't.BDCODVER, '||
                'tverbas.BDDESCVER,'||
                't.BDANOINI, '||
                't.BDMESINI, '||
                't.BDDIAINI, '||
                't.BDANOFIM, '||
                't.BDMESFIM, '||
                't.BDDIAFIM, '||
                't.BDFORMULAREF, '||
                't.BDFORMULAVAL, '||
                't.BDDESCCOND, '||
                't.BDLOCAL, '||
                't.BDSIMNAO ';

  wsql = wsql||'from vw_union_verbas_sim_nao t ';

  wsql = wsql||' left outer join SP_CONSULTAEMPRESAS(null, null, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;

  wsql = wsql|| 'left outer join vw_colaboradores vw_col on (vw_col.bdcodemp = t.bdcodemp and vw_col.bdcodcol = t.bdcodcol) ';

  wsql = wsql || 'left outer join VW_TCOLCON_VINCDIA COL_DIAVINC on (COL_DIAVINC.BDCODEMP = t.BDCODEMP and
                                                                     COL_DIAVINC.BDCODCOL = t.BDCODCOL) ';

  wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = t.bdcodver) ';


  wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                      '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                      '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     wsql = wsql||' and '||PRCODEMP;

  IF (prcodsintrab IS NOT NULL AND prcodsintrab <> '') THEN
     wsql = wsql||' and '||prcodsintrab;

  IF (prlocal IS NOT NULL AND prlocal <> '') THEN
     wsql = wsql||' and '||prlocal;

  IF (prsimnao IS NOT NULL AND prsimnao <> '') THEN
     wsql = wsql||' and '||prsimnao;

  IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
     wsql = wsql||' and '||PRCODCOL;

  wSql = wSQl ||' and bdlocal = ''FUNC''';


  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :bdnomemp,
    :bdcnpjemp,
    :bdcodcol,
    :bdnomcol,
    :BDCODPLAFUC,
    :BDCODTFUC,
    :bdcodsind,
    :BDCODVER,
    :BDDESCVER,
    :BDANOINI,
    :BDMESINI,
    :BDDIAINI,
    :BDANOFIM,
    :BDMESFIM,
    :BDDIAFIM,
    :BDFORMREF,
    :BDFORMVAL,
    :BDDESCCOND,
    :bdlocal,
    :BDSIMNAO
  DO
  SUSPEND;

-- exit;

  /* inicio verbas sim nao empresa... */

  wsql = 'select t.BDCODEMP, '||
                'empresas.BDNOMEMP, '||
                'empresas.bdcnpjemp, '||
                't.BDCODCOL, '||
                'vw_col.bdnomcol,'||
                'COL_DIAVINC.BDCODPLAFUC,'||
                'COL_DIAVINC.BDCODTFUC,'||
                't.BDCODSINTRAB, '||
                't.BDCODVER, '||
                'tverbas.BDDESCVER,'||
                't.BDANOINI, '||
                't.BDMESINI, '||
                't.BDDIAINI, '||
                't.BDANOFIM, '||
                't.BDMESFIM, '||
                't.BDDIAFIM, '||
                't.BDFORMULAREF, '||
                't.BDFORMULAVAL, '||
                't.BDDESCCOND, '||
                't.BDLOCAL, '||
                't.BDSIMNAO ';

  wsql = wsql||'from vw_union_verbas_sim_nao t ';

  wsql = wsql||' left outer join SP_CONSULTAEMPRESAS(null, null, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;

  wsql = wsql|| 'left outer join vw_colaboradores vw_col on (vw_col.bdcodemp = t.bdcodemp and vw_col.bdcodcol = t.bdcodcol) ';

  wsql = wsql || 'left outer join VW_TCOLCON_VINCDIA COL_DIAVINC on (COL_DIAVINC.BDCODEMP = t.BDCODEMP and
                                                                     COL_DIAVINC.BDCODCOL = t.BDCODCOL) ';

  wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = t.bdcodver) ';

  wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                      '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                      '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     wsql = wsql||' and '||PRCODEMP;

  IF (prcodsintrab IS NOT NULL AND prcodsintrab <> '') THEN
     wsql = wsql||' and '||prcodsintrab;

  IF (prlocal IS NOT NULL AND prlocal <> '') THEN
     wsql = wsql||' and '||prlocal;

  IF (prsimnao IS NOT NULL AND prsimnao <> '') THEN
     wsql = wsql||' and '||prsimnao;

  wSql = wSQl ||' and bdlocal = ''EMP''';


  FOR EXECUTE STATEMENT wsql
  INTO :BDCODEMP, :bdnomemp, :bdcnpjemp, :bdcodcol, :bdnomcol, :BDCODPLAFUC, :BDCODTFUC, :bdcodsind, :BDCODVER, :BDDESCVER, :BDANOINI,
    :BDMESINI, :BDDIAINI, :BDANOFIM, :BDMESFIM, :BDDIAFIM, :BDFORMREF, :BDFORMVAL, :BDDESCCOND, :bdlocal, :BDSIMNAO
  DO
  BEGIN

    wsqlfunc = ' select BDCODEMP, BDCODCOL from VW_COLABORADORES_REF_ATUAL  t' ;

    wsqlfunc = wsqlfunc ||' WHERE t.BDCODEMP = '|| :bdcodemp ;

  IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
     wsqlfunc = wsqlfunc||' and '||PRCODCOL;

    -- FAZ UM FOR EM TODOS OS FUNCIONARIOS REFERENTE A EMPRESA ATUAL PARA LANCAR AS VERBAS POR EMPRESA
    FOR EXECUTE STATEMENT wsqlfunc
      INTO :BDCODEMP, :bdcodcol  DO
      BEGIN

       SUSPEND;
      END
  END

  /* FINAL verbas sim nao empresa... */

  EXIT;

 /* inicio verbas sim nao sindicato... */

  wsql = 'select t.BDCODEMP, '||
                't.BDCODCOL, '||
                't.BDCODSINTRAB, '||
                't.BDCODVER, '||
                'tverbas.BDDESCVER,'||
                't.BDANOINI, '||
                't.BDMESINI, '||
                't.BDDIAINI, '||
                't.BDANOFIM, '||
                't.BDMESFIM, '||
                't.BDDIAFIM, '||
                't.BDFORMULAREF, '||
                't.BDFORMULAVAL, '||
                't.BDDESCCOND, '||
                't.BDLOCAL, '||
                't.BDSIMNAO ';
  wsql = wsql||'from vw_union_verbas_sim_nao t ';

  wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = t.bdcodver) ';


  wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                      '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                      '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

  IF (prcodsintrab IS NOT NULL AND prcodsintrab <> '') THEN
     wsql = wsql||' and '||prcodsintrab;

  IF (prlocal IS NOT NULL AND prlocal <> '') THEN
     wsql = wsql||' and '||prlocal;

  IF (prsimnao IS NOT NULL AND prsimnao <> '') THEN
     wsql = wsql||' and '||prsimnao;

  wSql = wSQl ||' and bdlocal = ''SIND''';


  FOR EXECUTE STATEMENT wsql
  INTO :BDCODEMP, :bdcodcol, :bdcodsind, :BDCODVER, :bddescver, :BDANOINI, :BDMESINI, :BDDIAINI, :BDANOFIM, :BDMESFIM, :BDDIAFIM, :BDFORMREF, :BDFORMVAL,:BDDESCCOND, :bdlocal, :BDSIMNAO  DO
  BEGIN

    wsqlfunc = ' select BDCODEMP, BDCODCOL from VW_COLABORADORES_REF_ATUAL  t' ;

    wsqlfunc = wsqlfunc ||' WHERE t.bdcodsintrab = '|| :bdcodsind ;

    IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
       wsqlfunc = wsqlfunc||' and '||PRCODEMP;

    IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
       wsqlfunc = wsqlfunc||' and '||PRCODCOL;

    -- FAZ UM FOR EM TODOS OS FUNCIONARIOS REFERENTE O SINDICATO ATUAL PARA LANCAR AS VERBAS POR SINDICATO
    FOR EXECUTE STATEMENT wsqlfunc
      INTO :BDCODEMP, :bdcodcol  DO
      BEGIN

       SUSPEND;
      END
  END

  /* FINAL verbas sim nao sindicato... */

--  exit;


 /* inicio verbas sim nao FUNCOES... */

  wsql = 'select t.BDCODEMP, '||
                't.BDCODCOL, '||
                't.BDCODSINTRAB, '||
                't.BDCODVER, '||
                'tverbas.BDDESCVER,'||
                't.BDANOINI, '||
                't.BDMESINI, '||
                't.BDDIAINI, '||
                't.BDANOFIM, '||
                't.BDMESFIM, '||
                't.BDDIAFIM, '||
                't.BDFORMULAREF, '||
                't.BDFORMULAVAL, '||
                't.BDDESCCOND, '||
                't.BDLOCAL, '||
                't.BDSIMNAO ';
  wsql = wsql||'from vw_union_verbas_sim_nao t ';

  wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = t.bdcodver) ';

  wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                      '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                      '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

  IF (prcodsintrab IS NOT NULL AND prcodsintrab <> '') THEN
     wsql = wsql||' and '||prcodsintrab;

  IF (prlocal IS NOT NULL AND prlocal <> '') THEN
     wsql = wsql||' and '||prlocal;

  IF (prsimnao IS NOT NULL AND prsimnao <> '') THEN
     wsql = wsql||' and '||prsimnao;

  wSql = wSQl ||' and bdlocal = ''FUNCAO''';


  FOR EXECUTE STATEMENT wsql
  INTO :BDCODEMP, :bdcodcol, :bdcodsind, :BDCODVER, :bddescver, :BDANOINI, :BDMESINI, :BDDIAINI, :BDANOFIM, :BDMESFIM, :BDDIAFIM, :BDFORMREF, :BDFORMVAL,:BDDESCCOND, :bdlocal, :BDSIMNAO  DO
  BEGIN

    wsqlfunc = ' select BDCODEMP, BDCODCOL from VW_COLABORADORES_REF_ATUAL  t' ;

    wsqlfunc = wsqlfunc ||' WHERE t.bdcodsintrab = '|| :bdcodsind ;

    IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
       wsqlfunc = wsqlfunc||' and '||PRCODCOL;

    -- FAZ UM FOR EM TODOS OS FUNCIONARIOS REFERENTE a funcao ATUAL PARA LANCAR AS VERBAS POR funcao
    FOR EXECUTE STATEMENT wsqlfunc
      INTO :BDCODEMP, :bdcodcol  DO
      BEGIN

       SUSPEND;
      END
  END

  /* FINAL verbas sim nao FUNCOES... */




  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: VRHF_SP_UNION_VERBAS_SIM_NAO_2 */
ALTER PROCEDURE VRHF_SP_UNION_VERBAS_SIM_NAO_2(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRCODSINTRAB VARCHAR(10000),
PRDATAINI DATE,
PRDATAFIM DATE,
PRLOCAL VARCHAR(100),
PRSIMNAO VARCHAR(100))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(18),
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDCODPLAFUC INTEGER,
BDCODTFUC INTEGER,
BDCODSIND INTEGER,
BDCODVER INTEGER,
BDDESCVER VARCHAR(40),
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000),
BDDESCCOND BLOB,
BDLOCAL VARCHAR(10),
BDSIMNAO INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(15000);
DECLARE VARIABLE WSQLFUNC VARCHAR(15000);
DECLARE VARIABLE WDATAINI VARCHAR(8);
DECLARE VARIABLE WDATAFIM VARCHAR(8);
DECLARE VARIABLE WDTAUX VARCHAR(10);
DECLARE VARIABLE WWHERE VARCHAR(15000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(NULL, prdataini, prdatafim);

  wdtaux = CAST(prdataini AS VARCHAR(10));
  wdataini = SUBSTRING(wdtaux FROM 1 FOR 4)||SUBSTRING(wdtaux FROM 6 FOR 2)||SUBSTRING(wdtaux FROM 9 FOR 2);

  wdtaux = CAST(prdatafim AS VARCHAR(10));
  wdatafim = SUBSTRING(wdtaux FROM 1 FOR 4)||SUBSTRING(wdtaux FROM 6 FOR 2)||SUBSTRING(wdtaux FROM 9 FOR 2);

  wsqlfunc = ' select T.BDCODEMP, ' ||
             ' EMPRESAS.BDNOMEMP, ' ||
             'EMPRESAS.BDCNPJEMP,' ||
             'T.BDCODCOL,' ||
             'vw_col.bdnomcol,' ||
             'COL_DIAVINC.BDCODPLAFUC,' ||
             'COL_DIAVINC.BDCODTFUC,' ||
             't.BDCODSINTRAB' ||
             ' from VW_COLABORADORES_REF_ATUAL  t' ;

  wsqlfunc = wsqlfunc||' left outer join SP_CONSULTAEMPRESAS(null, null, null) empresas on (empresas.bdcodemp = t.bdcodemp ) ' ;

  wsqlfunc = wsqlfunc|| 'left outer join vw_colaboradores vw_col on (vw_col.bdcodemp = t.bdcodemp and vw_col.bdcodcol = t.bdcodcol) ';

  wsqlfunc = wsqlfunc || 'left outer join VW_TCOLCON_VINCDIA COL_DIAVINC on (COL_DIAVINC.BDCODEMP = t.BDCODEMP and
                                                                     COL_DIAVINC.BDCODCOL = t.BDCODCOL) ';

  wwhere = '';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  wsqlfunc = wsqlfunc||wwhere;

  -- FAZ UM FOR EM TODOS OS FUNCIONARIOS
  FOR EXECUTE STATEMENT wsqlfunc
    INTO :BDCODEMP, :bdnomemp, :bdcnpjemp, :bdcodcol , :bdnomcol, :BDCODPLAFUC, :bdcodtfuc, :bdcodsind DO
    BEGIN

      wwhere = '';

      wsql = 'select t.BDCODVER, '||
             'tverbas.BDDESCVER,'||
             't.BDANOINI, '||
             't.BDMESINI, '||
             't.BDDIAINI, '||
             't.BDANOFIM, '||
             't.BDMESFIM, '||
             't.BDDIAFIM, '||
             't.BDFORMULAREF, '||
             't.BDFORMULAVAL, '||
             't.BDDESCCOND, '||
             't.BDLOCAL, '||
             't.BDSIMNAO ';

      wsql = wsql||'from vw_union_verbas_sim_nao t ';

      wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = t.bdcodver) ';


      wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                    '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                    '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

      wsql = wsql||' and t.bdcodemp = '||:bdcodemp;

      IF (prcodsintrab IS NOT NULL AND prcodsintrab <> '') THEN
         wsql = wsql||' and '||prcodsintrab;

      IF (prlocal IS NOT NULL AND prlocal <> '') THEN
         wsql = wsql||' and '||prlocal;

      IF (prsimnao IS NOT NULL AND prsimnao <> '') THEN
         wsql = wsql||' and '||prsimnao;

      wsql = wsql||' and t.bdcodcol = '||:bdcodcol;

      wSql = wSQl ||' and bdlocal = ''FUNC''';

      /* laco de verbas sim nao por funcionario */

      FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODVER,
        :BDDESCVER,
        :BDANOINI,
        :BDMESINI,
        :BDDIAINI,
        :BDANOFIM,
        :BDMESFIM,
        :BDDIAFIM,
        :BDFORMREF,
        :BDFORMVAL,
        :BDDESCCOND,
        :bdlocal,
        :BDSIMNAO
      DO
      SUSPEND;

    /* final laco verbas sim nao funcionario */

    /* inicio verbas sim nao empresa */

      wwhere = '';

      wsql = 'select t.BDCODVER, '||
             'tverbas.BDDESCVER,'||
             't.BDANOINI, '||
             't.BDMESINI, '||
             't.BDDIAINI, '||
             't.BDANOFIM, '||
             't.BDMESFIM, '||
             't.BDDIAFIM, '||
             't.BDFORMULAREF, '||
             't.BDFORMULAVAL, '||
             't.BDDESCCOND, '||
             't.BDLOCAL, '||
             't.BDSIMNAO ';

      wsql = wsql||'from vw_union_verbas_sim_nao t ';

      wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = t.bdcodver) ';


      wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                    '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                    '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

      wsql = wsql||' and t.bdcodemp = '||:bdcodemp;

      IF (prcodsintrab IS NOT NULL AND prcodsintrab <> '') THEN
         wsql = wsql||' and '||prcodsintrab;

      IF (prlocal IS NOT NULL AND prlocal <> '') THEN
         wsql = wsql||' and '||prlocal;

      IF (prsimnao IS NOT NULL AND prsimnao <> '') THEN
         wsql = wsql||' and '||prsimnao;

      wSql = wSQl ||' and bdlocal = ''EMP''';

      /* laco de verbas sim nao por EMPRESA */

      FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODVER,
        :BDDESCVER,
        :BDANOINI,
        :BDMESINI,
        :BDDIAINI,
        :BDANOFIM,
        :BDMESFIM,
        :BDDIAFIM,
        :BDFORMREF,
        :BDFORMVAL,
        :BDDESCCOND,
        :bdlocal,
        :BDSIMNAO
      DO
      SUSPEND;

      /* fim verbas sim nao por empresa */

    /* inicio verbas sim nao sindicato */

      wwhere = '';

      wsql = 'select t.BDCODVER, '||
             'tverbas.BDDESCVER,'||
             't.BDANOINI, '||
             't.BDMESINI, '||
             't.BDDIAINI, '||
             't.BDANOFIM, '||
             't.BDMESFIM, '||
             't.BDDIAFIM, '||
             't.BDFORMULAREF, '||
             't.BDFORMULAVAL, '||
             't.BDDESCCOND, '||
             't.BDLOCAL, '||
             't.BDSIMNAO ';

      wsql = wsql||'from vw_union_verbas_sim_nao t ';

      wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = t.bdcodver) ';


      wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                    '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                    '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

      IF (prcodsintrab IS NOT NULL AND prcodsintrab <> '') THEN
         wsql = wsql||' and '||prcodsintrab;

      IF (prlocal IS NOT NULL AND prlocal <> '') THEN
         wsql = wsql||' and '||prlocal;

      IF (prsimnao IS NOT NULL AND prsimnao <> '') THEN
         wsql = wsql||' and '||prsimnao;

      wSql = wSQl ||' and bdlocal = ''SIND''';

      IF (:bdcodsind IS NOT NULL) THEN
         wsql = wsql ||' and t.bdcodsintrab = '|| :bdcodsind;
      ELSE
         wsql = wsql ||' and t.bdcodsintrab = '|| 999999;

      /* laco de verbas sim nao por SINDICATO */

      FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODVER,
        :BDDESCVER,
        :BDANOINI,
        :BDMESINI,
        :BDDIAINI,
        :BDANOFIM,
        :BDMESFIM,
        :BDDIAFIM,
        :BDFORMREF,
        :BDFORMVAL,
        :BDDESCCOND,
        :bdlocal,
        :BDSIMNAO
      DO
      SUSPEND;

      /* fim verbas sim nao por SINDICATO */

      /* inicio verbas sim nao funcao */

      wwhere = '';

      wsql = 'select t.BDCODVER, '||
             'tverbas.BDDESCVER,'||
             't.BDANOINI, '||
             't.BDMESINI, '||
             't.BDDIAINI, '||
             't.BDANOFIM, '||
             't.BDMESFIM, '||
             't.BDDIAFIM, '||
             't.BDFORMULAREF, '||
             't.BDFORMULAVAL, '||
             't.BDDESCCOND, '||
             't.BDLOCAL, '||
             't.BDSIMNAO ';

      wsql = wsql||'from vw_union_verbas_sim_nao t ';

      wsql = wsql || 'left outer join vrh_base_tverbas tverbas on (tverbas.bdcodver = t.bdcodver) ';


      wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                    '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                    '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

      IF (prcodsintrab IS NOT NULL AND prcodsintrab <> '') THEN
         wsql = wsql||' and '||prcodsintrab;

      IF (prlocal IS NOT NULL AND prlocal <> '') THEN
         wsql = wsql||' and '||prlocal;

      IF (prsimnao IS NOT NULL AND prsimnao <> '') THEN
         wsql = wsql||' and '||prsimnao;

      wSql = wSQl ||' and bdlocal = ''FUNCAO''';

      IF (:bdcodplafuc IS NOT NULL) THEN
         wsql = wsql ||' and T.BDCODPLAFUC = '|| :bdcodplafuc;
      ELSE
         wsql = wsql ||' and T.BDCODPLAFUC = '|| 999999;

      IF (:bdcodtfuc IS NOT NULL) THEN
         wsql = wsql ||' and T.BDCODFUNCAO = '|| :bdcodtfuc;
      ELSE
         wsql = wsql ||' and T.BDCODFUNCAO= '|| 999999;

      /* laco de verbas sim nao por funcao */

      FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODVER,
        :BDDESCVER,
        :BDANOINI,
        :BDMESINI,
        :BDDIAINI,
        :BDANOFIM,
        :BDMESFIM,
        :BDDIAFIM,
        :BDFORMREF,
        :BDFORMVAL,
        :BDDESCCOND,
        :bdlocal,
        :BDSIMNAO
      DO
      SUSPEND;

      /* fim verbas sim nao por funcao */

    END /* fim laco do funcinario */

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: VRHF_SP_UNIONCALCDETALHE */
ALTER PROCEDURE VRHF_SP_UNIONCALCDETALHE RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDREFFN INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDREFCOMP INTEGER,
BDDATABAIXA DATE,
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDETALHE VARCHAR(1000),
BDBINSSFEFOL NUMERIC(15,6),
BDINSSFEFOL NUMERIC(15,6),
BDALIQINSSFEFOL NUMERIC(15,6),
BDTIPODET INTEGER,
BDORDEMDETALHE INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  /* HistOrico da folha complementar */
  wsql = 'select ';
  wsql = wsql||'FN.BDCODEMP, '||
               'FN.BDCODCOL, '||
               'FN.BDCODVER, '||
               'FN.BDREFFN, '||
               'FN.BDREFVHFC, '||
               'FN.BDREFAUXVHFC, '||
               'FN.BDVALVHFC, '||
               'FN.BDIGNREFVHFC, '||
               'FN.BDIGNVALVHFC, '||
               'FN.BDREFCOMP, '||
               'CAST(NULL AS DATE) BDDATABAIXAFN, '||
               '0.0 BDBFGTSFN, '||
               '0.0 BDFGTSFN, '||
               '0.0 BDFGTSCSFN, '||
               '0.0 BDBFGTS13FN, '||
               '0.0 BDFGTS13FN, '||
               '0.0 BDFGTS13CSFN, '||
               '0.0 BDMAIORREMFN, '||
               '0.0 BDBINSSFN, '||
               '0.0 BDALIQINSSFN, '||
               '0.0 BDINSSFN, '||
               '0.0 BDBIRRFFN, '||
               '0.0 BDALIQIRRFFN, '||
               '0.0 BDIRRFFN, '||
               '0.0 BDBINSS13FN, '||
               '0.0 BDALIQINSS13FN, '||
               '0.0 BDINSS13FN, '||
               '0.0 BDBIRRF13FN, '||
               '0.0 BDALIQIRRF13FN, '||
               '0.0 BDIRRF13FN, '||
               '0.0 BDBSALFAMFN, '||
               '0.0 BDSALFAMFN, '||
               '0.0 BDBRAISFN, '||
               '0.0 BDSALBASEFN, '||
               '0.0 BDDEPFN, '||
               'FN.BDDETALHEHFC, '||
               '0.0 BDAPE01, '||
               '0.0 BDAPE02, '||
               '0.0 BDAPE03, '||
               '0 BDTIPO, '||
               'FN.BDORDEMDETALHE ';
  wsql = wsql||'from vrhf_emp_thist_folhacomp FN ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFV,
    :BDREFAUXV,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDREFCOMP,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDDETALHE,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDTIPODET,
    :BDORDEMDETALHE
  DO
  SUSPEND;

  /* HistOrico de fErias */
  wsql = 'select ';
  wsql = wsql||'RFE.BDCODEMP, '||
               'RFE.BDCODCOL, '||
               'RFE.BDCODVERFN, '||
               'RFE.BDREFFE, '||
               'RFE.BDREFVRFE, '||
               'RFE.BDREFAUXVRFE, '||
               'RFE.BDVALVRFE, '||
               'RFE.BDIGNREFVRFE, '||
               'RFE.BDIGNVALVRFE, '||
               '0 BDREFCOMP, '||
               'CAST(NULL AS DATE) BDAPE01, '||
               '0.0 BDAPE02, '||
               '0.0 BDAPE03, '||
               '0.0 BDAPE04, '||
               '0.0 BDAPE05, '||
               '0.0 BDAPE06, '||
               '0.0 BDAPE07, '||
               '0.0 BDAPE08, '||
               '0.0 BDAPE09, '||
               '0.0 BDAPE10, '||
               '0.0 BDAPE11, '||
               '0.0 BDAPE12, '||
               '0.0 BDAPE13, '||
               '0.0 BDAPE14, '||
               '0.0 BDAPE15, '||
               '0.0 BDAPE16, '||
               '0.0 BDAPE17, '||
               '0.0 BDAPE18, '||
               '0.0 BDAPE19, '||
               '0.0 BDAPE20, '||
               '0.0 BDAPE21, '||
               '0.0 BDAPE22, '||
               '0.0 BDAPE23, '||
               '0.0 BDAPE24, '||
               '0.0 BDAPE25, '||
               'RFE.BDDETALHERFE, '||
               '0.0 BDAPE26, '||
               '0.0 BDAPE27, '||
               '0.0 BDAPE28, '||
               '1 BDCODFE, '||
               'RFE.BDORDEMDETALHE ';

  wsql = wsql||'from vrhf_emp_tverbarfe RFE ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFV,
    :BDREFAUXV,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDREFCOMP,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDDETALHE,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDTIPODET,
    :BDORDEMDETALHE
  DO
  SUSPEND;

  /* HistOrico de tomadores */
  wsql = 'select RFE.BDCODEMP, '||
                'RFE.BDCODCOL, '||
                'RFE.BDCODVER, '||
                'RFE.BDREFTOMADOR, '||
                'RFE.BDREFVFT, '||
                'RFE.BDREFAUXVFT, '||
                'RFE.BDVALVFT, '||
                'RFE.BDIGNREFVFT,'||
                'RFE.BDIGNVALVFT, '||
                '0 BDREFCOMP, '||
                'CAST(NULL AS DATE) BDAPE01, '||
                '0.0 BDAPE02,'||
                '0.0 BDAPE03,'||
                '0.0 BDAPE04,'||
                '0.0 BDAPE05,'||
                '0.0 BDAPE06,'||
                '0.0 BDAPE07,'||
                '0.0 BDAPE08,'||
                '0.0 BDAPE09,'||
                '0.0 BDAPE10,'||
                '0.0 BDAPE11,'||
                '0.0 BDAPE12,'||
                '0.0 BDAPE13,'||
                '0.0 BDAPE14,'||
                '0.0 BDAPE15,'||
                '0.0 BDAPE16,'||
                '0.0 BDAPE17,'||
                '0.0 BDAPE18,'||
                '0.0 BDAPE19,'||
                '0.0 BDAPE20,'||
                '0.0 BDAPE21,'||
                '0.0 BDAPE22,'||
                '0.0 BDAPE23,'||
                '0.0 BDAPE24,'||
                '0.0 BDAPE25,'||
                'RFE.BDDETALHEVFT,'||
                '0.0 BDAPE26,'||
                '0.0 BDAPE27,'||
                '0.0 BDAPE28,'||
                'RFE.BDITEMVFT, '||
                '0 BDORDEMDETALHE ';

  wsql = wsql||'from VRHF_EMP_TVERBATOMADOR RFE ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFV,
    :BDREFAUXV,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDREFCOMP,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDDETALHE,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDTIPODET,
    :BDORDEMDETALHE
  DO
  SUSPEND;

  /* HistOrico de fErias rescisAo */
  wsql = 'select ';
  wsql = wsql||'FN.BDCODEMP, '||
               'FN.BDCODCOL, '||
               'FN.BDCODVER, '||
               'FN.BDREFFN, '||
               'FN.BDREFVFND, '||
               'FN.BDREFAUXVFND, '||
               'FN.BDVALVFND, '||
               'FN.BDIGNREFVFND, '||
               'FN.BDIGNVALVFND, '||
               '0 BDREFCOMP, '||
               'CAST(NULL AS DATE) BDDATABAIXAFN, '||
               '0.0 BDBFGTSFN, '||
               '0.0 BDFGTSFN, '||
               '0.0 BDFGTSCSFN, '||
               '0.0 BDBFGTS13FN, '||
               '0.0 BDFGTS13FN, '||
               '0.0 BDFGTS13CSFN, '||
               '0.0 BDMAIORREMFN, '||
               '0.0 BDBINSSFN, '||
               '0.0 BDALIQINSSFN, '||
               '0.0 BDINSSFN, '||
               '0.0 BDBIRRFFN, '||
               '0.0 BDALIQIRRFFN, '||
               '0.0 BDIRRFFN, '||
               '0.0 BDBINSS13FN, '||
               '0.0 BDALIQINSS13FN, '||
               '0.0 BDINSS13FN, '||
               '0.0 BDBIRRF13FN, '||
               '0.0 BDALIQIRRF13FN, '||
               '0.0 BDIRRF13FN, '||
               '0.0 BDBSALFAMFN, '||
               '0.0 BDSALFAMFN, '||
               '0.0 BDBRAISFN, '||
               '0.0 BDSALBASEFN, '||
               '0.0 BDDEPFN, '||
               'FN.BDDETALHEFND, '||
               '0.0 BDAPE01, '||
               '0.0 BDAPE02, '||
               '0.0 BDAPE03, '||
               '4 BDTIPO, '||
               'FN.BDORDEMDETALHE ';

  wsql = wsql||'from VRHF_EMP_TVERBAFN_DET FN ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDREFFN,
    :BDREFV,
    :BDREFAUXV,
    :BDVALV,
    :BDIGNREFV,
    :BDIGNVALV,
    :BDREFCOMP,
    :BDDATABAIXA,
    :BDBFGTS,
    :BDFGTS,
    :BDFGTSCS,
    :BDBFGTS13,
    :BDFGTS13,
    :BDFGTS13CS,
    :BDMAIORREM,
    :BDBINSS,
    :BDALIQINSS,
    :BDINSS,
    :BDBIRRF,
    :BDALIQIRRF,
    :BDIRRF,
    :BDBINSS13,
    :BDALIQINSS13,
    :BDINSS13,
    :BDBIRRF13,
    :BDALIQIRRF13,
    :BDIRRF13,
    :BDBSALFAM,
    :BDSALFAM,
    :BDBRAIS,
    :BDSALBASE,
    :BDDEP,
    :BDDETALHE,
    :BDBINSSFEFOL,
    :BDINSSFEFOL,
    :BDALIQINSSFEFOL,
    :BDTIPODET,
    :BDORDEMDETALHE
  DO
  SUSPEND;
END
^

/* Restore proc. body: VRHF_SP_VALORES_CONTRIB_SINDICA */
CREATE OR ALTER PROCEDURE VRHF_SP_VALORES_CONTRIB_SINDICA (
    PRTIPOFOLHA INTEGER,
    PREMPRESA VARCHAR(30000),
    PRCODCOL VARCHAR(30000),
    PRREFERENCIA INTEGER,
    PRSIND INTEGER)
RETURNS (
    BDTIPOFOLHA INTEGER,
    BDREF INTEGER,
    BDSIND INTEGER,
    BDCODEMP INTEGER,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDGRUPOCLA VARCHAR(100),
    BDVALOR NUMERIC(15,6),
    BDCODCOL INTEGER,
    BDSALBASE NUMERIC(15,6),
    BDQTD INTEGER,
    BDCODVER INTEGER,
    BDNOMSIND VARCHAR(60),
    BDCNPJSIND VARCHAR(18))
AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WEMP VARCHAR(30000);
DECLARE VARIABLE WCOL VARCHAR(30000);
DECLARE VARIABLE WSQLAUX VARCHAR(200);
DECLARE VARIABLE WQTD INTEGER;
BEGIN
  /*
    tipo folha
    0 = todos
    1 = fn
    2 = fc
    3 = a13
    4 = 13
    5 = c13
  */

  wsql = 'delete from VRHF_COL_CALC_GRCS';
  EXECUTE STATEMENT wsql;

  /* Procedure Text */
  IF ((prempresa IS NOT NULL) AND (prempresa <> '')) THEN
     wemp = ''''||prempresa||'''';
  ELSE
     wemp = 'null';

  IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
     wcol = ''''||prcodcol||'''';
  ELSE
     wcol = 'null';

  wsql = '';
  IF (prtipofolha IN (0,1)) THEN
     BEGIN
       wsql = 'select 1, fn.BDCODVER, fn.bdreffn bdref, fn.bdcodemp, fn.bdcodcentro, fn.bdcodtpcc , coalesce(colcon.bdcodsintrabcla, colcon.bdcodsintrab) bdsind,'||
              'substring(verba.bdclaver from 1 for 9) grupocla, fn.bdvalvfn bdvalor, fn.bdcodcol'||
              ' from vrhf_sp_tverbafn('||wemp||', '||wcol||','||prreferencia||', null, 0) fn , vw_vrh_emp_tcol_vinc colcon, vrh_base_tverbas verba'||
              ' where (fn.bdcodemp = colcon.bdcodemp and fn.bdcodcol = colcon.bdcodcol) and'||
              '    (verba.bdcodver = fn.bdcodver) and ((verba.bdclaver starting with '||''''||'0.004'||''') or (verba.bdclaver starting with '||''''||'0.710'||''')) ';

       IF ((prsind IS NOT NULL) AND (prsind > 0)) THEN
          wsql = wsql||' and coalesce(colcon.bdcodsintrabcla, colcon.bdcodsintrab) = '||prsind;
       IF (prtipofolha IN (0)) THEN
         wsql = wsql||' union';
      END

  IF (prtipofolha IN (0,2)) THEN
     BEGIN
       wsql = wsql||' select 2, fc.BDCODVER, fc.BDREFCOMP bdref, fc.bdcodemp, fc.bdcodcentro, fc.bdcodtpcc, coalesce(colcon.bdcodsintrabcla, colcon.bdcodsintrab) bdsind,'||
                    ' substring(verba.bdclaver from 1 for 9) grupocla, fc.bdvalvfc bdvalor, fc.bdcodcol'||
                    ' from vrhf_sp_tverbafc('||wemp||', '||wcol||', null, null,'||prreferencia||', null,0) fc , vw_vrh_emp_tcol_vinc colcon, vrh_base_tverbas verba'||
                    ' where (fc.bdcodemp = colcon.bdcodemp and fc.bdcodcol = colcon.bdcodcol) and'||
                    ' (verba.bdcodver = fc.bdcodver) and ((verba.bdclaver starting with '||''''||'0.004'||''') or (verba.bdclaver starting with '||''''||'0.710'||''')) ';
       IF ((prsind IS NOT NULL) AND (prsind > 0)) THEN
          wsql = wsql||' and coalesce(colcon.bdcodsintrabcla, colcon.bdcodsintrab) = '||prsind;
       IF (prtipofolha IN (0)) THEN
         wsql = wsql||' union';
     END

  IF (prtipofolha IN (0,3)) THEN
     BEGIN
       wsql = wsql||' select 3, a13.BDCODVER, a13.bdrefa13 bdref, a13.bdcodemp, null bdcodcentro, null bdcodtpcc, coalesce(colcon.bdcodsintrabcla, colcon.bdcodsintrab) bdsind,'||
                    ' substring(verba.bdclaver from 1 for 9) grupocla, a13.bdvalva13 bdvalor, a13.bdcodcol'||
                    ' from vrhf_emp_tverbaa13 a13, vw_vrh_emp_tcol_vinc colcon, vrh_base_tverbas verba'||
                    ' where (a13.bdcodemp = colcon.bdcodemp and a13.bdcodcol = colcon.bdcodcol) and'||
                    ' (verba.bdcodver = a13.bdcodver) and verba.bdclaver starting with '||''''||'4.047'||''''||' and a13.bdrefa13 = '||prreferencia;
       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          wsql = wsql||' and '||prcodcol;
       IF ((prempresa IS NOT NULL) AND (prempresa <> '')) THEN
          wsql = wsql||' and '||prempresa;
       IF ((prsind IS NOT NULL) AND (prsind > 0)) THEN
          wsql = wsql||' and coalesce(colcon.bdcodsintrabcla, colcon.bdcodsintrab) = '||prsind;
       IF (prtipofolha IN (0)) THEN
         wsql = wsql||' union';
     END

  IF (prtipofolha IN (0,4)) THEN
     BEGIN
       wsql = wsql||' select 4, d3.BDCODVER, d3.bdref13 bdref, d3.bdcodemp, null bdcodcentro, null bdcodtpcc, coalesce(colcon.bdcodsintrabcla, colcon.bdcodsintrab) bdsind,'||
                    ' substring(verba.bdclaver from 1 for 9) grupocla, d3.bdvalv13 bdvalor, d3.bdcodcol'||
                    ' from vrhf_emp_tverba13 d3, vw_vrh_emp_tcol_vinc colcon, vrh_base_tverbas verba'||
                    ' where (d3.bdcodemp = colcon.bdcodemp and d3.bdcodcol = colcon.bdcodcol) and'||
                    ' (verba.bdcodver = d3.bdcodver) and verba.bdclaver starting with '||''''||'5.070'||''''||' and d3.bdref13 = '||prreferencia;
       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          wsql = wsql||' and '||prcodcol;
       IF ((prempresa IS NOT NULL) AND (prempresa <> '')) THEN
          wsql = wsql||' and '||prempresa;
       IF ((prsind IS NOT NULL) AND (prsind > 0)) THEN
          wsql = wsql||' and coalesce(colcon.bdcodsintrabcla, colcon.bdcodsintrab) = '||prsind;
       IF (prtipofolha IN (0)) THEN
         wsql = wsql||' union';
     END

  IF (prtipofolha IN (0,5)) THEN
     BEGIN
       wsql = wsql||' select 5, c13.BDCODVER, c13.bdrefc13 bdref, c13.bdcodemp, null bdcodcentro, null bdcodtpcc, coalesce(colcon.bdcodsintrabcla, colcon.bdcodsintrab) bdsind,'||
                    ' substring(verba.bdclaver from 1 for 9) grupocla, c13.bdvalvc13 bdvalor, c13.bdcodcol'||
                    ' from vrhf_emp_tverbac13 c13, vw_vrh_emp_tcol_vinc colcon, vrh_base_tverbas verba'||
                    ' where (c13.bdcodemp = colcon.bdcodemp and c13.bdcodcol = colcon.bdcodcol) and'||
                    ' (verba.bdcodver = c13.bdcodver) and verba.bdclaver starting with '||''''||'6.070'||''''||' and c13.bdrefc13 = '||prreferencia;
       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          wsql = wsql||' and '||prcodcol;
       IF ((prempresa IS NOT NULL) AND (prempresa <> '')) THEN
          wsql = wsql||' and '||prempresa;
       IF ((prsind IS NOT NULL) AND (prsind > 0)) THEN
          wsql = wsql||' and coalesce(colcon.bdcodsintrabcla, colcon.bdcodsintrab) = '||prsind;
     END

  FOR EXECUTE STATEMENT wsql INTO
    :bdtipofolha,
    :BDCODVER,
    :bdref,
    :bdcodemp,
    :bdcodcentro,
    :bdcodtpcc,
    :bdsind,
    :bdgrupocla,
    :bdvalor,
    :bdcodcol DO
  BEGIN
    wsqlaux = 'select count(bdcodemp) from VRHF_COL_CALC_GRCS where bdcodemp = '||bdcodemp||
                                                              ' and bdcodcol = '||bdcodcol||
                                                              ' and BDGRUPOCLA = '||''''||bdgrupocla||'''';

    EXECUTE STATEMENT wsqlaux INTO :wqtd;

    SELECT bddescsintrab, bdcnpjsintrab FROM VRH_BASE_TSINDTRAB WHERE bdcodsintrab = :bdsind INTO :bdnomsind, :bdcnpjsind;

    bdsalbase = 0;
    bdqtd = 0;
    IF (wqtd <= 0) THEN
       BEGIN
         wsqlaux = 'insert into VRHF_COL_CALC_GRCS(bdcodemp, bdcodcol,BDGRUPOCLA) values('||bdcodemp||','||bdcodcol||','||''''||bdgrupocla||''''||')';
         EXECUTE STATEMENT wsqlaux;

         wsqlaux = 'select BDSALBASECOL from VW_VRH_EMP_TCOLCON_CALCDIA where bdcodemp = '||bdcodemp||' and bdcodcol = '||bdcodcol;

         EXECUTE STATEMENT wsqlaux INTO :bdsalbase;
         bdqtd = 1;
       END

    SUSPEND;
  END
END
^

/* Restore proc. body: VRHF_SP_VERBAS_FN_FC */
ALTER PROCEDURE VRHF_SP_VERBAS_FN_FC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRREFINI INTEGER,
PRREFFIM INTEGER,
PRCLASSVERBAS VARCHAR(20000))
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDREF INTEGER,
BDCODVER INTEGER,
BDREFV NUMERIC(15,6),
BDREFAUXV NUMERIC(15,6),
BDVALV NUMERIC(15,6),
BDBFGTS NUMERIC(15,6),
BDFGTS NUMERIC(15,6),
BDFGTSCS NUMERIC(15,6),
BDBFGTS13 NUMERIC(15,6),
BDFGTS13 NUMERIC(15,6),
BDFGTS13CS NUMERIC(15,6),
BDMAIORREM NUMERIC(15,6),
BDBINSS NUMERIC(15,6),
BDALIQINSS NUMERIC(15,6),
BDINSS NUMERIC(15,6),
BDBIRRF NUMERIC(15,6),
BDALIQIRRF NUMERIC(15,6),
BDIRRF NUMERIC(15,6),
BDBINSS13 NUMERIC(15,6),
BDALIQINSS13 NUMERIC(15,6),
BDINSS13 NUMERIC(15,6),
BDBIRRF13 NUMERIC(15,6),
BDALIQIRRF13 NUMERIC(15,6),
BDIRRF13 NUMERIC(15,6),
BDBSALFAM NUMERIC(15,6),
BDSALFAM NUMERIC(15,6),
BDBRAIS NUMERIC(15,6),
BDSALBASE NUMERIC(15,6),
BDDEP NUMERIC(15,6),
BDDESCVER VARCHAR(40),
BDDESCREDVER VARCHAR(20),
BDCLAVER VARCHAR(20),
BDIGNREFAV VARCHAR(5),
BDIGNREFV VARCHAR(5),
BDIGNVALV VARCHAR(5),
BDTIPO INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WDATA DATE;
BEGIN
  IF (prreffim IS NULL) THEN
     BEGIN
       FOR SELECT CURRENT_DATE FROM rdb$database INTO :wdata DO
       wano = EXTRACT(YEAR FROM :wdata);
       wmes = EXTRACT(MONTH FROM :wdata);
       EXECUTE PROCEDURE sp_seta_competencia(wano||wmes, NULL, NULL);
     END
  ELSE
     EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);

  wsql = 'select X.BDCODEMP, '||
                'EMP.BDNOMEMP, '||
                'X.BDCODCOL, '||
                'COL.BDNOMCOL, '||
                'X.BDREF, '||
                'Y.BDCODVER, '||
                'SUM(X.BDREFV), '||
                'SUM(X.BDREFAUXV), '||
                'SUM(X.BDVALV), '||
                'MAX(X.BDBFGTS), '||
                'MAX(X.BDFGTS), '||
                'MAX(X.BDFGTSCS), '||
                'MAX(X.BDBFGTS13), '||
                'MAX(X.BDFGTS13), '||
                'MAX(X.BDFGTS13CS), '||
                'MAX(X.BDMAIORREM), '||
                'MAX(X.BDBINSS), '||
                'MAX(X.BDALIQINSS), '||
                'MAX(X.BDINSS), '||
                'MAX(X.BDBIRRF), '||
                'MAX(X.BDALIQIRRF), '||
                'MAX(X.BDIRRF), '||
                'MAX(X.BDBINSS13), '||
                'MAX(X.BDALIQINSS13), '||
                'MAX(X.BDINSS13), '||
                'MAX(X.BDBIRRF13), '||
                'MAX(X.BDALIQIRRF13), '||
                'MAX(X.BDIRRF13), '||
                'MAX(X.BDBSALFAM), '||
                'MAX(X.BDSALFAM), '||
                'MAX(X.BDBRAIS), '||
                'MAX(X.BDSALBASE), '||
                'MAX(X.BDDEP), '||
                'Y.BDDESCVER, '||
                'y.bddescredver, '||
                'Y.BDCLAVER, '||
                'X.BDIGNREFAV, '||
                'X.BDIGNREFV, '||
                'X.BDIGNVALV, '||
                'X.BDTIPO ';

  wsql = wsql||'from SP_VRHF_VERBAS_FN_FC X '||
               'left outer join VRH_BASE_TVERBAS Y '||
                 'on (X.BDCODVER = Y.BDCODVER) ' ||

             'left outer join VW_EMPRESAS_REF_ATUAL EMP '||
             'on (EMP.BDCODEMP = X.BDCODEMP) '||

             'left outer join VW_VRH_EMP_TCOLCON_CAD COL '||
             'on (COL.BDCODEMP = X.BDCODEMP and COL.BDCODCOL = X.BDCODCOL) ';


  wwhere = '';

  IF (PRCODEMP IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||'('||PRCODEMP||') ';
     END 

  IF (PRCODCOL IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'('||PRCODCOL||') ';
     END

  IF (PRREFINI IS NOT NULL AND PRREFFIM IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'(X.BDREF between '||PRREFINI||' and '||PRREFFIM||') ';
     END

  IF (PRCLASSVERBAS IS NOT NULL) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||'('||PRCLASSVERBAS||') ';
     END 

  IF (wwhere <> '') THEN
     wwhere = 'where '||wwhere;

  wsql = wsql||wwhere;

  wsql = wsql||'group by X.BDCODEMP, '||
                        'EMP.BDNOMEMP, '||
                        'X.BDCODCOL, '||
                        'COL.BDNOMCOL, '||
                        'X.BDREF, '||
                        'Y.BDCODVER, '||
                        'Y.BDDESCVER, '||
                        'Y.BDDESCREDVER, '||
                        'Y.BDCLAVER, ' ||
                        'X.BDIGNREFV, '||
                        'X.BDIGNVALV, '||
                        'X.BDTIPO ';

    FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :bdnomemp,
        :BDCODCOL,
        :bdnomcol,
        :BDREF,
        :BDCODVER,
        :BDREFV,
        :BDREFAUXV,
        :BDVALV,
        :BDBFGTS,
        :BDFGTS,
        :BDFGTSCS,
        :BDBFGTS13,
        :BDFGTS13,
        :BDFGTS13CS,
        :BDMAIORREM,
        :BDBINSS,
        :BDALIQINSS,
        :BDINSS,
        :BDBIRRF,
        :BDALIQIRRF,
        :BDIRRF,
        :BDBINSS13,
        :BDALIQINSS13,
        :BDINSS13,
        :BDBIRRF13,
        :BDALIQIRRF13,
        :BDIRRF13,
        :BDBSALFAM,
        :BDSALFAM,
        :BDBRAIS,
        :BDSALBASE,
        :BDDEP,
        :bddescver,
        :BDDESCREDVER,
        :BDCLAVER,
        :BDIGNREFAV,
        :BDIGNREFV,
        :BDIGNVALV,
        :BDTIPO
      DO

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: SP_VRH_VERBAS */
CREATE OR ALTER PROCEDURE SP_VRH_VERBAS (
    PRANOMES INTEGER,
    PRNIVELCLASSIFICACAO SMALLINT = 0)
RETURNS (
    BDCODVER INTEGER NOT NULL,
    BDREFVER INTEGER NOT NULL,
    BDTIPOCODVER INTEGER,
    BDINSSVER INTEGER,
    BDFGTSVER INTEGER,
    BDIRVER INTEGER,
    BDTIPOREFVER INTEGER,
    BDBASESFVER INTEGER,
    BDPISVER VARCHAR(5),
    BDBASEHEVER VARCHAR(5),
    BDBASEMAIORVER VARCHAR(5),
    BDRAISVER VARCHAR(5),
    BDBASEGPSVER VARCHAR(5),
    BDMENORESVER VARCHAR(5),
    BDPROPVER VARCHAR(5),
    BDBASEVTVER VARCHAR(5),
    BDREEMBGPSVER VARCHAR(5),
    BDHEVER NUMERIC(15,6),
    BDGRAVAFICHAHNVER VARCHAR(5),
    BDCCPRINCIPALVER VARCHAR(5),
    BDFORMREFVER VARCHAR(5000),
    BDFORMVALVER VARCHAR(5000),
    BDBASEDSRHEVER VARCHAR(5),
    BDBASEDSRRVVER VARCHAR(5),
    BDFORMREFAUXVER VARCHAR(5000),
    BDDEDFORMREFAUXVER VARCHAR(5),
    BDDEDFORMREFVER VARCHAR(5),
    BDDEDFORMVALVER VARCHAR(5),
    BDRENDISENTOIRVER VARCHAR(5),
    BDFORMINTVER VARCHAR(5000),
    BDSIMPLESNACIONAL VARCHAR(5),
    BDBASE13HN VARCHAR(5),
    BDBASEFERHN VARCHAR(5),
    BDBASEAVHN VARCHAR(5),
    BDPAGAESTOUROVER VARCHAR(5),
    BDGARANTIAMINVER VARCHAR(5),
    BDINDRESC VARCHAR(5),
    BDNAOCONVHORASVER DM_BOOLEAN,
    BDAPEVER VARCHAR(20) NOT NULL,
    BDDESCVER VARCHAR(40),
    BDDESCREDVER VARCHAR(20),
    BDCLAVER VARCHAR(20),
    BDREADONLY VARCHAR(5),
    BDORDEMVER INTEGER,
    BDINATIVAVER VARCHAR(5),
    BDSITVER INTEGER,
    BDBASESALRAIS VARCHAR(5),
    BDSITMATVER VARCHAR(5),
    BDSITDOEVER VARCHAR(5),
    BDSITACITRABVER VARCHAR(5),
    BDSITMILITARVER VARCHAR(5),
    BDSITMATEMPVER VARCHAR(5),
    BDSITACITRAB15VER VARCHAR(5),
    BDSITDOETRABVER VARCHAR(5),
    BDSITLICVENCVER VARCHAR(5),
    BDSITDOE15VER VARCHAR(5),
    BDSITSINDICALVER VARCHAR(5),
    BDSITAPOINVVER VARCHAR(5),
    BDSITOUTRASVER VARCHAR(5),
    BDTIPOVER INTEGER,
    BDORDEMTIPOCODVER INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(5000);
BEGIN
  wsql = 'select '||
           'VERREF.BDCODVER,'||
           'VERREF.BDREFVER,'||
           'VERREF.BDTIPOCODVER,'||
           'VERREF.BDINSSVER,'||
           'VERREF.BDFGTSVER,'||
           'VERREF.BDIRVER,'||
           'VERREF.BDTIPOREFVER,'||
           'VERREF.BDBASESFVER,'||
           'VERREF.BDPISVER,'||
           'VERREF.BDBASEHEVER,'||
           'VERREF.BDBASEMAIORVER,'||
           'VERREF.BDRAISVER,'||
           'VERREF.BDBASEGPSVER,'||
           'VERREF.BDMENORESVER,'||
           'VERREF.BDPROPVER,'||
           'VERREF.BDBASEVTVER,'||
           'VERREF.BDREEMBGPSVER,'||
           'VERREF.BDHEVER,'||
           'VERREF.BDGRAVAFICHAHNVER,'||
           'VERREF.BDCCPRINCIPALVER,'||
           'VERREF.BDFORMREFVER,'||
           'VERREF.BDFORMVALVER,'||
           'VERREF.BDBASEDSRHEVER,'||
           'VERREF.BDBASEDSRRVVER,'||
           'VERREF.BDFORMREFAUXVER,'||
           'VERREF.BDDEDFORMREFAUXVER,'||
           'VERREF.BDDEDFORMREFVER,'||
           'VERREF.BDDEDFORMVALVER,'||
           'VERREF.BDRENDISENTOIRVER,'||
           'VERREF.BDFORMINTVER,'||
           'VERREF.BDSIMPLESNACIONAL,'||
           'VERREF.BDBASE13HN,'||
           'VERREF.BDBASEFERHN,'||
           'VERREF.BDBASEAVHN,'||
           'VERREF.BDPAGAESTOUROVER,'||
           'VERREF.BDGARANTIAMINVER,'||
           'VERREF.BDINDRESC,'||
           'VERREF.BDNAOCONVHORASVER,'||
           'VER.BDAPEVER,'||
           'VER.BDDESCVER,'||
           'VER.BDDESCREDVER,'||
           'VER.BDCLAVER,'||
           'VER.BDREADONLY,'||
           'VER.BDORDEMVER,'||
           'VER.BDINATIVAVER,'||
           'VER.BDSITVER,'||
           'VER.BDBASESALRAIS,'||
           'VER.BDSITMATVER,'||
           'VER.BDSITDOEVER,'||
           'VER.BDSITACITRABVER,'||
           'VER.BDSITMILITARVER,'||
           'VER.BDSITMATEMPVER,'||
           'VER.BDSITACITRAB15VER,'||
           'VER.BDSITDOETRABVER,'||
           'VER.BDSITLICVENCVER,'||
           'VER.BDSITDOE15VER,'||
           'VER.BDSITSINDICALVER,'||
           'VER.BDSITAPOINVVER,'||
           'VER.BDSITOUTRASVER,'||
           'VER.BDTIPOVER,'||
           'case when VERREF.BDTIPOCODVER = 1 then 2 when VERREF.BDTIPOCODVER = 2 then 1 else COALESCE(VERREF.BDTIPOCODVER, 0) END BDORDEMTIPOCODVER '||
         'from VRH_BASE_TVERBAS_REF VERREF '||
         'join(select BDCODVER, max(BDREFVER) BDREFVER '||
              'from VRH_BASE_TVERBAS_REF '||
              'where BDREFVER <= '||:pranomes||' '||
              'group by BDCODVER) REF on (REF.BDCODVER = VERREF.BDCODVER and REF.BDREFVER = VERREF.BDREFVER) '||
         'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = VERREF.BDCODVER)';

  --  Somente analíticas
  IF (prnivelclassificacao = 1) THEN
    wsql = wsql||' where STRLEN(VER.BDCLAVER) > 9';
  ELSE
  -- Somente título
  IF (prnivelclassificacao = 2) THEN
    wsql = wsql||' where STRLEN(VER.BDCLAVER) <= 9';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODVER,
    :BDREFVER,
    :BDTIPOCODVER,
    :BDINSSVER,
    :BDFGTSVER,
    :BDIRVER,
    :BDTIPOREFVER,
    :BDBASESFVER,
    :BDPISVER,
    :BDBASEHEVER,
    :BDBASEMAIORVER,
    :BDRAISVER,
    :BDBASEGPSVER,
    :BDMENORESVER,
    :BDPROPVER,
    :BDBASEVTVER,
    :BDREEMBGPSVER,
    :BDHEVER,
    :BDGRAVAFICHAHNVER,
    :BDCCPRINCIPALVER,
    :BDFORMREFVER,
    :BDFORMVALVER,
    :BDBASEDSRHEVER,
    :BDBASEDSRRVVER,
    :BDFORMREFAUXVER,
    :BDDEDFORMREFAUXVER,
    :BDDEDFORMREFVER,
    :BDDEDFORMVALVER,
    :BDRENDISENTOIRVER,
    :BDFORMINTVER,
    :BDSIMPLESNACIONAL,
    :BDBASE13HN,
    :BDBASEFERHN,
    :BDBASEAVHN,
    :BDPAGAESTOUROVER,
    :BDGARANTIAMINVER,
    :BDINDRESC,
    :BDNAOCONVHORASVER,
    :BDAPEVER,
    :BDDESCVER,
    :BDDESCREDVER,
    :BDCLAVER,
    :BDREADONLY,
    :BDORDEMVER,
    :BDINATIVAVER,
    :BDSITVER,
    :BDBASESALRAIS,
    :BDSITMATVER,
    :BDSITDOEVER,
    :BDSITACITRABVER,
    :BDSITMILITARVER,
    :BDSITMATEMPVER,
    :BDSITACITRAB15VER,
    :BDSITDOETRABVER,
    :BDSITLICVENCVER,
    :BDSITDOE15VER,
    :BDSITSINDICALVER,
    :BDSITAPOINVVER,
    :BDSITOUTRASVER,
    :BDTIPOVER,
    :BDORDEMTIPOCODVER
  DO
    SUSPEND;
END^

/* Restore proc. body: VRHF_SP_VERBAS_FOL_NORMAL_AUT */
create or alter procedure VRHF_SP_VERBAS_FOL_NORMAL_AUT (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32000),
    PRCODAUT varchar(10000),
    PRTIPOCOL integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer,
    PRFILTRO varchar(2000),
    PRCODTPCC varchar(10000),
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(2788) = null /* COLLATE WIN1252 - default */ ,
    PRFUCDET smallint = 0,
    PRBASECALC smallint = 1)
returns (
    BDCODPLAFUC integer,
    BDCODSINTRAB integer,
    BDCODCLA integer,
    BDDESCENQFED varchar(10),
    BDTEMGRRF integer,
    BDBSALFAM numeric(18,6),
    BDDATARESCISAO date,
    BDDESCRICAOMOTRES varchar(300),
    BDTIPOMOV integer,
    BDTIPO_COL integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMEMP DM_BDNOMEMP,
    BDAPEEMP DM_BDAPEMP,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP varchar(9),
    BDCNPJEMP varchar(18),
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDNOMCOL DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDPERCRATCOL numeric(18,6),
    BDDESCTFUC varchar(150),
    BDCPFCOL varchar(18),
    BDPISCOL varchar(14),
    BDCODENQFED integer,
    BDSIMPLESGPS integer,
    BDCTPSCOL DM_BDCTPS,
    BDCODCBO integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDREFFN integer,
    BDCODSERV integer,
    BDCODVER integer,
    BDDESCVER varchar(80),
    BDREFV numeric(18,6),
    BDPROVENTO numeric(18,6),
    BDDESCONTO numeric(18,6),
    BDSALBASE numeric(18,6),
    BDBINSS numeric(18,6),
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBIRRF numeric(18,6),
    BDBRAIS numeric(18,6),
    BDDESCREDVER varchar(80),
    BDIRRF numeric(18,6),
    BDGRUPOCLA integer,
    BDBINSS13 numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDBIRRF13 numeric(18,6),
    BDVFGTS13 numeric(18,6),
    BDBINSSFEFOL numeric(18,6),
    BDVINSSFEFOL numeric(18,6),
    BDBFGTSFEFOL numeric(18,6),
    BDVFGTSFEFOL numeric(18,6),
    BDDESCCC varchar(80),
    BDPISVER varchar(5),
    BDCLAVER varchar(20),
    BDBFGTSMESANT numeric(18,6),
    BDFGTSMESANT numeric(18,6),
    BDBFGTSMES numeric(18,6),
    BDFGTSMES numeric(18,6),
    BDSALDO numeric(18,6),
    BDFGTS40 numeric(18,6),
    BDFGTS10 numeric(18,6),
    BDTOTALGRRF numeric(18,6),
    BDORDEMVER integer,
    BDORDEMTIPOCODVER integer,
    BDTIPOCODVER integer,
    BDCODTFUC integer,
    BDTIPOREFVER integer,
    BDREFHOREMP varchar(5),
    BDVALMVINSSTER numeric(15,6),
    BDREFAUXV numeric(15,6),
    BDDATAPGTO date,
    BDCCATVCONCOM DM_BOOLEAN,
    BDBFGTSMESPOST numeric(18,6),
    BDFGTSMESPOST numeric(18,6),
    BDINSSFN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDMVINSSTER numeric(18,6),
    BDHORASMENSAISCOL numeric(18,6),
    BDFGTSIND numeric(18,6),
    BDDATAGRRF date,
    BDBASEINSSMV numeric(18,6),
    BDBASEIRRFMV numeric(18,6),
    BDVALORINSSMV numeric(18,6),
    BDVALORIRRFMV numeric(18,6),
    BDPERCMULTA40 numeric(15,2),
    BDPERCMULTA10 numeric(15,2),
    BDCODCONTTI integer,
    BDCATEGORIAESOCIAL integer,
    BDCODSERVB DM_BOOLEAN,
    BDSALFAM13GPS numeric(18,6),
    BDSALFAMFNGPS numeric(18,6),
    BDCONTRCOL integer,
    BDFGTSMES13 numeric(18,6),
    BDBASEPISFN numeric(18,6),
    BDBASEPISFEFN numeric(18,6),
    BDBASEPIS13FN numeric(18,6),
    BDCREDTRAB numeric(18,6),
    BDCREDTRABFERIAS numeric(18,6),
    BDCREDTRABCONTAB numeric(18,6),
    BDCREDTRABGUIAMENSAL boolean,
    BDGRRFPRES integer)
as
declare variable WVALSALFAM numeric(18,6);
declare variable WCODAUT varchar(10000);
declare variable WSQLAUXDAT varchar(5000);
declare variable WAAAAMM varchar(6);
declare variable WULDIAMES varchar(15);
declare variable WULTDIADATA varchar(10);
declare variable WSQL varchar(32700);
declare variable WREFAUX varchar(10);
declare variable WCODEMP varchar(32000);
declare variable WCODCOL varchar(32000);
declare variable WREFINI varchar(10);
declare variable WREFFIM varchar(10);
declare variable WCODTPCC varchar(10000);
declare variable WCALCFGTSMESANT DM_BOOLEAN;
declare variable WTEMAUT integer;
declare variable WV1 numeric(18,6);
declare variable WV2 numeric(18,6);
declare variable WDESCDETFUC varchar(150);
declare variable WHORASRED numeric(15,2);
declare variable WCODSERVMAX integer;
declare variable WREFPAGTO integer;
declare variable WCODVER integer;
declare variable WINSSVER integer;
declare variable WTIPOCODVER integer;
declare variable WBASEGPSVER DM_BOOLEAN;
declare variable WTERANT integer;
declare variable WEMPANT integer;
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WCODCID integer;
declare variable WUSANMSOCIAL DM_BOOLEAN;
declare variable WVERSAOCALC integer;
declare variable WEMPCRED integer;
declare variable WCOLCRED integer;
declare variable WREFCRED integer;
declare variable WCODCENTROCRED integer;
declare variable WCODTPCCCRED integer;
declare variable WCODCONTTICRED integer;
declare variable WBDBFGTSMESANT numeric(18,2);
declare variable WBDFGTSMESANT numeric(18,2);
declare variable WSQLMESANTFC varchar(10000);
begin
  /* prTIPOCOL
     0 = Todos
     1 = Colaboradores
     2 = Autonomos
  */

  WSQLMESANTFC = '';

  BDVALMVINSSTER = 0;
  WTERANT = 0;
  WEMPANT = 0;

  if (PRREFFIM is not null) then
    execute procedure SP_SETA_COMPETENCIA(PRREFFIM, null, null);
  else
  if (PRREFINI is not null) then
    execute procedure SP_SETA_COMPETENCIA(PRREFINI, null, null);

  if (PRCODEMP is null) then
    WCODEMP = 'null';
  else
    WCODEMP = '''' || PRCODEMP || '''';

  if (PRCODCOL is null) then
    WCODCOL = 'null';
  else
    WCODCOL = '''' || PRCODCOL || '''';

  if (PRCODAUT is null) then
    WCODAUT = 'null';
  else
    WCODAUT = '''' || PRCODAUT || '''';

  if (PRCODTPCC is null) then
    WCODTPCC = 'null';
  else
    WCODTPCC = '''' || PRCODTPCC || '''';

  if (PRTIPOCOL is null) then
    PRTIPOCOL = 0;

  if (PRREFINI is null) then
    WREFINI = ' null ';
  else
    WREFINI = '' || PRREFINI;

  if (PRREFFIM is null) then
    WREFFIM = ' null ';
  else
    WREFFIM = '' || PRREFFIM;

  if (PRREFFIM is not null) then
  begin
    WREFAUX = WREFFIM;
  end
  else
  if (PRREFINI is not null) then
  begin
    WREFAUX = WREFINI;
  end
  else
  begin
    WREFAUX = 'null';
  end

  WULTDIADATA = null;

  WSQL = '';
  if (WREFAUX <> 'null') then
    WSQL = 'select cast(ultdia as varchar(2)) from ULTIMO_DIA_MES(' || substring(WREFAUX from 5 for 2) || ',' || substring(WREFAUX from 1 for 4) || ')';

  if (WSQL <> '') then
  begin
    execute statement WSQL
        into WULDIAMES;
    WULTDIADATA = substring(WREFAUX from 1 for 4)||'-'||substring(WREFAUX from 5 for 2)||'-'||trim(WULDIAMES);

    WULDIAMES = substring(WREFAUX from 5 for 2) || '/' || WULDIAMES || '/' || substring(WREFAUX from 1 for 4);
    WULDIAMES = '''' || WULDIAMES || '''';

  end

  if ((PRFILIAIS is not null) or (PRFILIAIS <> '')) then
    PRFILIAIS = '''' || PRFILIAIS || '''';
  else
    PRFILIAIS = 'null';

  WSQL = 'select ' || /*01*/ '0 Tipo_Col, ' || /*02*/ 'T.BDCODEMP Codigo_Empresa,' || /*03*/ 'T.BDCODCOL Codigo_Colaborador,' ||/*09*/ 'tEMP.BDCNPJEMP Cnpj_Empresa,' || /*14*/ 'COL.BDDATAADMCOL Admissao_Colaborador, ' ||  --/*16*/       'colfunc.BDDESCTFUC Funcao_Colaborador,'||
  /*17*/ 'doccol.BDCPFCOL Cpf_Colaborador ,' ||  --/*22*/       'COLFUNC.bdcodcbo CBO_Col,'||
  /*23*/ 't.BDCODCENTRO Codigo_Plano_CC ,' || /*24*/ 't.BDCODTPCC Codigo_CC ,' || /*25*/ 't.bdrefFN Referencia,' || /*26*/ 'T.BDCODVER Codigo_Verba,' || /*27*/ 'T.BDDESCVER Descricao_Verba,' || /*28*/ 'T.BDREFV Referencia_Verba,' || /*29*/ 'T.BDPROVENTO Proventos_Folha ,' || /*30*/ 'T.BDDESCONTO Descontos_Folha,' || /*31*/ 'T.BDSALBASE,' || /*32*/ 'T.BDBINSS,' || /*33*/ 'T.BDBFGTS,' || /*34*/ 't.BDFGTS,' || /*35*/ 't.BDBIRRF,' || /*36*/ 't.BDBRAIS,' || /*37*/ 't.BDDESCREDVER,' || /*38*/ 't.bdirrf,' || --/*39*/       'gcla.bdgrupocla,'||
  /*40*/ 't.bdbINSS13,' || /*41*/ 't.bdbFGTS13,' || /*42*/ 't.bdbIRRF13,' || /*43*/ 'cc.bdnomcta,' || /*44*/ 't.BDPISVER,' || /*45*/ 't.BDCLAVER,' || /*46*/ 't.bdfgts13,' || /*47*/ 't.BDBINSSFEFOL,' || /*48*/ 't.BDINSSFEFOL,' || /*49*/ 't.BDBFGTSFEFOL,' || /*50*/ 't.BDFGTSFEFOL,' || /*51*/ 'resc.bddatarescisao,' || /*52*/ 'pres.bddescpres,' || /*53*/ 'pres.bdtipomov,' || /*54*/ 't.bdbSalFam,' || --/*56*/       'vic.bdcodcla,'||
  /*59*/ 't.BDORDEMVER,' || /*60*/ 't.BDORDEMTIPOCODVER,' || /*61*/ 't.BDTIPOCODVER,' || --/*62*/       'null BDCODTFUC, '||
  /*63*/ 'T.bdtiporefver, ' || /*64*/ 'T.bdrefhoremp, ' || /*65*/ 'resc.BDCALCFGTSMESANT, ' || /*66*/ 'T.BDREFAUXV, ' || /*67*/ 'T.BDDATAPGTO, ' || 'T.BDINSS, ' || 'T.BDINSS13, ' || 'T.BDBINSSAPFN, ' || 'T.BDINSSAPFN, ' || 'T.BDBINSS13APFN, ' || 'T.BDINSS13APFN, ' || 'RESC.BDDATAPAGGRFC, ' || 'T.BDCODCONTTI ' ||
         ', col.bdcontrcol '||
         ', T.bdbasepisfn, T.bdbasepisfefn, T.bdbasepis13fn, resc.BDCREDTRABGUIAMENSAL, pres.BDGRRFPRES '||
         ' from VRHF_SP_CALC_FOLHANORMAL (' || WCODEMP || ',' || WCODCOL || ', ' || WREFINI || ', ' || WREFFIM || ', ' || PRAGRUPATOMADOR || ',' || WCODTPCC || ',' || PRPUXAFILIAIS || ',' || PRFILIAIS || ') T';

  WSQL = WSQL || ' join tempresas temp on (temp.bdcodemp = t.bdcodemp)';
  WSQL = WSQL || ' join vrh_emp_tcolcon col on (T.BDCODEMP = col.BDCODEMP and T.BDCODCOL = col.BDCODCOL) ';

--  WSQL = WSQL || ' left outer join (select BDCODEMP, BDCODCOL, max(BDREFCOL) BDREFCOL from VRH_EMP_TCOLCON_DOCREF where BDREFCOL <= '||prrefini||' group by BDCODEMP, BDCODCOL) DOCREF2 on (DOCREF2.BDCODEMP = T.BDCODEMP and DOCREF2.BDCODCOL = T.BDCODCOL) ';
--  WSQL = WSQL || ' left outer join VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = T.BDCODEMP and DOCREF.BDCODCOL = T.BDCODCOL and DOCREF.BDREFCOL = DOCREF2.BDREFCOL) ';

  WSQL = WSQL || ' left outer join vrh_emp_tcolcon_doc doccol on (T.BDCODEMP = doccol.BDCODEMP and T.BDCODCOL = doccol.BDCODCOL) ';
  WSQL = WSQL || ' left outer join vrh_emp_tcol_doc doc on (T.BDCODEMP = doc.BDCODEMP and T.BDCODCOL = doc.BDCODCOL) ';
--  WSQL = WSQL || ' left outer join ('||
--                     'select BDCODEMP, BDCODCOL, max(BDREFCOL) BDREFCOL from VRHF_EMP_TCOLCON_FGTSGPS where BDREFCOL <= '||prrefini||' group by BDCODEMP, BDCODCOL) gpscol2 on (gpscol2.BDCODEMP = T.BDCODEMP and gpscol2.BDCODCOL = T.BDCODCOL) ';
--  WSQL = WSQL || ' left outer join VRHF_EMP_TCOLCON_FGTSGPS gpscol on (gpscol.BDCODEMP = T.BDCODEMP and gpscol.BDCODCOL = T.BDCODCOL and gpscol.BDREFCOL = gpscol2.BDREFCOL) ';

  WSQL = WSQL || ' left outer join vrh_emp_trescisao resc on (T.BDCODEMP = resc.BDCODEMP and T.BDCODCOL = resc.BDCODCOL) ';
  WSQL = WSQL || ' left outer join vrh_base_tprepresc pres on (resc.bdcodpres = pres.bdcodpres) ';
--  WSQL = WSQL || ' left outer join (select BDCODEMP, bdcodcol,  max(BDREFCOL) BDREFCOL from VRH_EMP_TCOL_VINC where BDREFCOL <= '||prrefini||' group by BDCODEMP, BDCODCOL) vinc2 on (vinc2.BDCODEMP = T.BDCODEMP and vinc2.BDCODCOL = T.BDCODCOL) ';
--  WSQL = WSQL || ' left outer join VRH_EMP_TCOL_VINC vinc on (vinc.BDCODEMP = T.BDCODEMP and vinc.BDCODCOL = T.BDCODCOL and vinc.BDREFCOL = vinc2.BDREFCOL) ';
  WSQL = WSQL || ' left outer join centros_tpcc cc on (cc.bdcodcentro = t.bdcodcentro and cc.bdcodtpcc = t.bdcodtpcc)';

  if (PRFILTRO is not null and
      PRFILTRO <> '') then
  begin
    WSQL = WSQL || :PRFILTRO;
  end

  WSQL = WSQL||' order by T.BDCODEMP, T.BDREFFN, T.BDCODCOL ';

  BDVALMVINSSTER = 0;
  BDMVINSSTER    = 0;
  wempatu = 0;
  wcolatu = 0;
  wrefatu = 0;
  wusanmsocial = 'FALSE';
  wempcred = 0;
  wcolcred = 0;
  wrefcred = 0;
  wcodcentrocred = 0;
  wcodtpcccred = 0;
  wcodcontticred = 0;

  if (PRTIPOCOL <> 2) then
    for execute statement WSQL
            into /*01*/ :BDTIPO_COL,
            /*02*/ :BDCODEMP,
            /*03*/ :BDCODCOL,
--            /*04*/ :BDNOMEMP,
--            /*05*/ :BDENDEMP,
--            /*06*/ :BDNUMEMP,
--            /*07*/ :BDBAIEMP,
--            /*08*/ :BDCEPEMP,
            /*09*/ :BDCNPJEMP,
--            /*10*/ :BDNOMCID,
--            /*11*/ :BDSIGLAUF,
--            /*12*/ :BDCOMPLEMP,
--            /*13*/ :BDNOMCOL,
            /*14*/ :BDDATAADMCOL,
--            /*15*/ :BDPERCRATCOL,
            --/*16*/ : bddesctfuc ,
            /*17*/ :BDCPFCOL,
--            /*18*/ :BDPISCOL,
--            /*19*/ :BDCODENQFED,
--            /*20*/ :BDSIMPLESGPS,
--            /*21*/ :BDCTPSCOL,
            --/*22*/ : bdcodcbo ,
            /*23*/ :BDCODCENTRO,
            /*24*/ :BDCODTPCC,
            /*25*/ :BDREFFN,
            /*26*/ :BDCODVER,
            /*27*/ :BDDESCVER,
            /*28*/ :BDREFV,
            /*29*/ :BDPROVENTO,
            /*30*/ :BDDESCONTO,
            /*31*/ :BDSALBASE,
            /*32*/ :BDBINSS,
            /*33*/ :BDBFGTS,
            /*34*/ :BDFGTS,
            /*35*/ :BDBIRRF,
            /*36*/ :BDBRAIS,
            /*37*/ :BDDESCREDVER,
            /*38*/ :BDIRRF,
            --/*39*/ : bdgrupocla,
            /*40*/ :BDBINSS13,
            /*41*/ :BDBFGTS13,
            /*42*/ :BDBIRRF13,
            /*43*/ :BDDESCCC,
            /*44*/ :BDPISVER,
            /*45*/ :BDCLAVER,
            /*46*/ :BDVFGTS13,
            /*47*/ :BDBINSSFEFOL,
            /*48*/ :BDVINSSFEFOL,
            /*49*/ :BDBFGTSFEFOL,
            /*50*/ :BDVFGTSFEFOL,
            /*51*/ :BDDATARESCISAO,
            /*52*/ :BDDESCRICAOMOTRES,
            /*53*/ :BDTIPOMOV,
            /*54*/ :BDBSALFAM,
--            /*55*/ :BDDESCENQFED,
            --/*56*/ : bdcodcla,
--            /*57*/ :BDCODSINTRAB,
            --/*58*/ : bdcodplafuc,
            /*59*/ :BDORDEMVER,
            /*60*/ :BDORDEMTIPOCODVER,
            /*61*/ :BDTIPOCODVER,
            --/*62*/ : bdcodtfuc,
            /*63*/ :BDTIPOREFVER,
            /*64*/ :BDREFHOREMP,
            /*65*/ :WCALCFGTSMESANT,
            /*66*/ :BDREFAUXV,
            /*66*/ :BDDATAPGTO,
--            :BDCCATVCONCOM,
            :BDINSSFN, :BDINSS13FN, :BDBINSSAPFN, :BDINSSAPFN, :BDBINSS13APFN,
            :BDINSS13APFN, :BDDATAGRRF, :BDCODCONTTI,
--            :BDCATEGORIAESOCIAL,
            :BDCONTRCOL,
            :BDBASEPISFN,
            :BDBASEPISFEFN,
            :BDBASEPIS13FN,
            :BDCREDTRABGUIAMENSAL,
            :BDGRRFPRES
    do
    begin
      BDCODSERVB = 'TRUE';

      if ((wempatu <> BDCODEMP) or (wrefatu <> BDREFFN)) then
         begin
           wempatu = BDCODEMP;
           wrefatu = BDREFFN;
           wcolatu = 0;
           BDNOMEMP = null;
           BDAPEEMP = null;
           BDENDEMP = null;
           BDNUMEMP = null;
           BDCEPEMP = null;
           BDBAIEMP = null;
           BDCOMPLEMP = null;
           wcodcid = null;
           BDNOMCID = null;
           BDSIGLAUF = null;
           BDCODENQFED = null;
           BDDESCENQFED = null;
           BDSIMPLESGPS = null;
           BDCCATVCONCOM = null;
           wusanmsocial = null;

           select first 1 BDNOMEMP, BDAPEEMP, BDENDEMP, BDNUMEMP, BDCEPEMP, BDBAIEMP, BDCOMPLEMP, BDCODCID from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :BDREFFN order by BDREFEMP desc
           into :BDNOMEMP, :BDAPEEMP, :BDENDEMP, :BDNUMEMP, :BDCEPEMP, :BDBAIEMP, :BDCOMPLEMP, :wcodcid;

           if (coalesce(wcodcid, 0) > 0) then
              select first 1 CID.BDNOMCID, UF.BDSIGLAUF from TCIDADE CID join TUF UF on (UF.BDCODUF = CID.BDCODUF) where CID.BDCODCID = :wcodcid into :BDNOMCID, :BDSIGLAUF;

           select first 1 E.BDCODENQFED, CE.BDDESCENQFED from TENQFED E join TCADENQFED CE on (CE.BDCODENQFED = E.BDCODENQFED) where E.BDCODEMP = :BDCODEMP and E.BDREFEMP <= :BDREFFN order by E.BDREFEMP desc into :BDCODENQFED, :BDDESCENQFED;
           select first 1 BDSIMPLESGPS, BDCCATVCONCOM from VRHF_BASE_TEMPGPS where BDCODEMP = :BDCODEMP and BDREFEMP <= :BDREFFN order by BDREFEMP desc into :BDSIMPLESGPS, :BDCCATVCONCOM;
           select first 1 BDUSANOMESOCIAL from VRHF_BASE_TEMPPAR where BDCODEMP = :BDCODEMP and BDREFEMP <= :BDREFFN order by BDREFEMP desc into :wusanmsocial;
           wusanmsocial = upper(coalesce(wusanmsocial, 'FALSE'));
         end

      if (wcolatu <> BDCODCOL) then
         begin
           wcolatu = BDCODCOL;
           BDCODPLAFUC = null;
           BDCODTFUC = null;
           BDDESCTFUC = null;
           BDCODCBO = null;
           wdescdetfuc = null;
           BDCODCLA = null;
           BDGRUPOCLA = null;
           BDHORASMENSAISCOL = null;
           whorasred = null;
           BDNOMCOL = null;
           BDPISCOL = null;
           BDCTPSCOL = null;
           BDPERCRATCOL = null;
           BDCATEGORIAESOCIAL = null;
           BDCODSINTRAB = null;

           SELECT first 1 X.BDCODPLAFUC, X.BDCODTFUC, Z.BDDESCTFUC, Z.BDCODCBO, SUBSTRING(Z.BDDESCFUNCDET FROM 1 FOR 150) from vrh_emp_tcol_vincdia X left outer join VRH_FUNCOES_TFUC Z on (Z.BDCODPLAFUC = X.BDCODPLAFUC and Z.BDCODTFUC = X.BDCODTFUC) where X.BDCODEMP = :BDCODEMP and X.BDCODCOL = :BDCODCOL and X.BDREFCOL <= :BDREFFN order by X.BDDATACOL desc
          into :BDCODPLAFUC, :BDCODTFUC, :BDDESCTFUC, :BDCODCBO, :WDESCDETFUC;

           if (coalesce(PRFUCDET, 0) = 1) then
             begin
        if (trim(coalesce(WDESCDETFUC, '')) <> '') then
          BDDESCTFUC = WDESCDETFUC;
             end

           select first 1 X.BDCODCLA, Z.BDGRUPOCLA from vrh_emp_tcolcon_vinc X left outer join VRH_BASE_TCLASSE Z on (Z.BDCODCLA = X.BDCODCLA) where X.BDCODEMP = :BDCODEMP and X.BDCODCOL = :BDCODCOL and X.BDREFCOL <= :BDREFFN order by X.BDREFCOL DESC
           into :BDCODCLA, :BDGRUPOCLA;

           select first 1 X.BDHORASMENSAISCOL from VRHF_EMP_TCOL_CALC X where X.BDCODEMP = :BDCODEMP and X.BDCODCOL = :BDCODCOL and X.BDREFCOL <= :BDREFFN order by X.BDREFCOL DESC
           into :BDHORASMENSAISCOL;

           WHORASRED = 0;
           select first 1 X.BDMESREDSAL FROM VRH_EMP_TREDUCAOCOL X where X.BDCODEMP = :BDCODEMP and X.BDCODCOL = :BDCODCOL and
             X.BDREFINIREDSAL <= :BDREFFN and X.BDREFFIMREDSAL >= :BDREFFN and X.BDDATAFIMREDSAL >= cast(trim(:wultdiadata) as date)
           order by X.BDDATAFIMREDSAL DESC
          into :WHORASRED;
     
           if (coalesce(whorasred, 0) > 0) then
        BDHORASMENSAISCOL =  WHORASRED;

           if (wusanmsocial = 'TRUE') then
              select first 1 BDNMSOCIAL from VRH_EMP_TCOLCON_FIS where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :BDREFFN order by BDREFCOL desc into :BDNOMCOL;

           if (trim(coalesce(BDNOMCOL, '')) = '') then
              select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :BDREFFN order by BDREFCOL desc into :BDNOMCOL;

           select first 1 BDPISCOL, BDCTPSCOL from VRH_EMP_TCOLCON_DOCREF where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :BDREFFN order by BDREFCOL desc into :BDPISCOL, :BDCTPSCOL;
           select first 1 BDPERCRATCOL, BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :BDREFFN order by BDREFCOL desc into :BDPERCRATCOL, :BDCATEGORIAESOCIAL;
           select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :BDREFFN order by BDREFCOL desc into :BDCODSINTRAB;
         end

      if ((BDCODEMP <> WEMPCRED) or (BDCODCOL <> WCOLCRED) or (BDREFFN <> WREFCRED) or (BDCODCENTRO <> WCODCENTROCRED) or (BDCODTPCC <> WCODTPCCCRED) or (BDCODCONTTI <> WCODCONTTICRED)) then
         begin
           wempcred = BDCODEMP;
           wcolcred = BDCODCOL;
           wrefcred = BDREFFN;
           wcodcentrocred = BDCODCENTRO;
           wcodtpcccred = BDCODTPCC;
           wcodcontticred = BDCODCONTTI;

           BDCREDTRAB       = 0;
           BDCREDTRABCONTAB = 0;
           BDCREDTRABFERIAS = 0;

           if ((BDCODCONTTI is null) OR (BDCODCONTTI = 0)) then
              begin
                SELECT
                   SUM(A.BDVALOR) AS BDCREDTRAB,
                   SUM(CASE WHEN VR.BDCLAVER STARTING WITH '0.100.4.1' THEN A.BDVALOR ELSE null END) AS BDCREDTRABFERIAS,
                   SUM(CASE WHEN VR.BDCLAVER NOT STARTING WITH '0.100.4.1' THEN A.BDVALOR ELSE null END) AS BDCREDTRABCONTAB
                FROM (
                   SELECT TOM.BDCODEMP, TOM.BDCODCOL, TOM.BDREFTOMADOR BDREF,TOM.BDCODVER, TOM.BDVALVFT BDVALOR
                     FROM VRHF_EMP_TVERBATOMADOR TOM
                   UNION ALL
                   SELECT FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFN BDREF, FN.BDCODVER, FN.BDVALVFN BDVALOR
                     FROM VRHF_EMP_TVERBAFN FN
                   ) A
                LEFT OUTER JOIN VRH_BASE_TVERBAS VR ON VR.BDCODVER = A.BDCODVER
                WHERE A.BDCODEMP = :BDCODEMP AND A.BDCODCOL = :BDCODCOL
                AND A.BDREF = :BDREFFN
                AND ((VR.BDCLAVER STARTING WITH '0.070.1.1') or (VR.BDCLAVER STARTING WITH '0.100.4.1') or (VR.BDCLAVER STARTING WITH '0.009.1.1') or (VR.BDCLAVER STARTING WITH '0.009.1.2'))
                into :BDCREDTRAB, :BDCREDTRABFERIAS, :BDCREDTRABCONTAB;
              end
         end

      BDCODSERV = BDREFFN;
      BDBFGTSMESANT = 0;
      BDFGTSMESANT = 0;
      BDBFGTSMES = 0;
      BDFGTSMES = 0;
      BDFGTSMES13 = 0;
      BDSALDO = 0;
      BDFGTS40 = 0;
      BDFGTS10 = 0;
      BDTOTALGRRF = 0;
      BDTEMGRRF = 0;
      BDBFGTSMESPOST = 0;
      BDFGTSMESPOST = 0;
      BDFGTSIND = 0;
      BDPERCMULTA10 = 0;
      BDPERCMULTA40 = 0;

      if (BDDATARESCISAO is not null) then
      begin
        WSQLAUXDAT = 'select bdaaaamm from aaaamm(cast(' || '''' || cast(BDDATARESCISAO as varchar(10)) || '''' || ' as date))';

        execute statement WSQLAUXDAT
            into WAAAAMM;

        if (WAAAAMM <> BDREFFN) then
        begin
          BDDATARESCISAO = null;
          BDDESCRICAOMOTRES = '';

               /* Verifica se a rescisão é no mês seguinte e se tem o parâmetro de FGTS mês anterior, para não buscar o FGTS do mês */
          if (substring(WAAAAMM from 5 for 2) = '01') then
            WAAAAMM = cast((cast((substring(WAAAAMM from 1 for 4)) as integer) - 1) as varchar(4)) || '12';
          else
          begin
            if (cast((substring(WAAAAMM from 5 for 2)) as integer) <= 10) then
              WAAAAMM = substring(WAAAAMM from 1 for 4) || '0' || cast((cast((substring(WAAAAMM from 5 for 2)) as integer) - 1) as varchar(1));
            else
              WAAAAMM = substring(WAAAAMM from 1 for 4) || cast((cast((substring(WAAAAMM from 5 for 2)) as integer) - 1) as varchar(2));
          end

          if (WAAAAMM = BDREFFN and
              upper(WCALCFGTSMESANT) = 'TRUE') then
          begin
            BDBFGTSMESPOST = COALESCE(BDBFGTS, 0) + COALESCE(BDBFGTS13, 0) + COALESCE(BDBFGTSFEFOL, 0);
            BDFGTSMESPOST = COALESCE(BDFGTS, 0) + COALESCE(BDVFGTS13, 0) + COALESCE(BDVFGTSFEFOL, 0);

            BDBFGTS = 0;
            BDBFGTS13 = 0;
            BDBFGTSFEFOL = 0;
            BDFGTS = 0;
            BDVFGTS13 = 0;
            BDVFGTSFEFOL = 0;
          end
        end

        if (BDDATARESCISAO is not null) then
        begin
          WSQLAUXDAT = 'select x.bdbfgtsmesant,x.bdfgtsmesant, x.bdbfgtsmes, x.bdfgtsmes, x.bdsaldo, x.bdfgts40, x.bdfgts10, x.bdtotal, x.bdfgtsind, x.bdpercmulta40, x.bdpercmulta10, x.BDFGTS13 from VRHF_EMP_VAL_GRRF(' || BDCODEMP || ',' || BDCODCOL || ',' || BDREFFN || ',' || BDREFFN || ',0) x';
          execute statement WSQLAUXDAT
              into :BDBFGTSMESANT, :BDFGTSMESANT, :BDBFGTSMES, :BDFGTSMES, :BDSALDO, :BDFGTS40, :BDFGTS10, :BDTOTALGRRF,
              :BDFGTSIND, :BDPERCMULTA40, :BDPERCMULTA10, :BDFGTSMES13;

          WBDBFGTSMESANT = 0;
          WBDFGTSMESANT = 0;

          /*Vai trazer nessa consulta o FGTS já do mes anterior das complementares, de todos os tipos sem filtrar por data, apenas pela referencia da complementar*/
          WSQLMESANTFC = 'select x.bdbfgtsmes, x.bdfgtsmes from VRHF_EMP_VAL_GRRF_FC(' || BDCODEMP || ',' || BDCODCOL || ',' || BDREFFN || ',null, null, ''FALSE'', ''FALSE'') x';
          execute statement WSQLMESANTFC
            into :WBDBFGTSMESANT, :WBDFGTSMESANT;


          BDBFGTSMESANT = BDBFGTSMESANT + COALESCE(WBDBFGTSMESANT, 0);
          BDFGTSMESANT = BDFGTSMESANT + COALESCE(WBDFGTSMESANT, 0);

          if (BDTOTALGRRF <> 0) then
            BDTEMGRRF = 1;
      end
    end

      BDSALFAMFNGPS = 0;
      BDSALFAM13GPS = 0;
      WVALSALFAM = 0;
     
      for select FN.BDVALVFN, FN.BDCODVER
          from (select BDVALVFN, BDCODVER
                from VRHF_EMP_TVERBAFN
                where BDCODEMP = :BDCODEMP and
                      BDCODCOL = :BDCODCOL and
                      BDREFFN = :BDREFFN
                union all
                select BDVALVFN, BDCODVER
                from VRHF_EMP_TVERBAINT
                where BDCODEMP = :BDCODEMP and
                      BDCODCOL = :BDCODCOL and
                      BDREFFN = :BDREFFN
                union all
                select BDVALVFT, BDCODVER
                from VRHF_EMP_TVERBATOMADOR
                where BDCODEMP = :BDCODEMP and
                      BDCODCOL = :BDCODCOL and
                      BDREFTOMADOR = :BDREFFN
                union all
                select BDVALVFT, BDCODVER
                from VRHF_EMP_TVERBATOMINT
                where BDCODEMP = :BDCODEMP and
                      BDCODCOL = :BDCODCOL and
                      BDREFTOMADOR = :BDREFFN) FN
          join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER)
          where (VER.BDCLAVER starting with '8.005') or (VER.BDCLAVER starting with '7.070')
       into :wvalsalfam, :wcodver
       do
         begin
           winssver = null;
           wtipocodver = null;
           wbasegpsver = null;
           select first 1 BDINSSVER, BDTIPOCODVER, BDBASEGPSVER from VRH_BASE_TVERBAS_REF where BDCODVER = :wcodver and BDREFVER <= :BDREFFN order by BDREFVER DESC into :winssver, :wtipocodver, :wbasegpsver;
           winssver = coalesce(winssver, 0);
           wtipocodver = coalesce(wtipocodver, 0);
           wbasegpsver = upper(coalesce(wbasegpsver, 'FALSE'));

           if (wbasegpsver = 'FALSE') then
              begin
                if (wtipocodver = 1) then
                   wvalsalfam = wvalsalfam * -1;

                if (winssver = 1) then
                   BDSALFAMFNGPS = :BDSALFAMFNGPS + wvalsalfam;
     
                if (winssver = 3) then
                   BDSALFAM13GPS = :BDSALFAM13GPS + wvalsalfam;
              end
         end

      suspend;
    end

 -- A PARTIR DAQUI RETORNA OS DADOS DOS AUTÔNOMOS (PARTICIPANTES)

  BDCODSINTRAB = null;
  BDCODPLAFUC = null;
  BDHORASMENSAISCOL = 220;
  BDFGTSIND = 0;
  BDDATAGRRF = null;
  BDCODCONTTI = 0;
  BDCONTRCOL = null;
  wempatu = 0;
  wcolatu = 0;
  wrefatu = 0;

  if (PRCODEMP is null) then
    WCODEMP = 'null';
  else
  begin
    select BDRESULT
    from STRTRAN(upper(:PRCODEMP), 'COLCON.', 'FN.')
    into :WCODEMP;
    WCODEMP = '''' || WCODEMP || '''';
  end
--    wcodemp = ''''||'fn.'||substring(prcodemp from 8)||'''';

  if (PRCODAUT is null) then
    WCODAUT = 'null';
  else
  begin
    select BDRESULT
    from STRTRAN(upper(:PRCODAUT), 'COLCON.', 'FN.')
    into :WCODAUT;
    WCODAUT = '''' || WCODAUT || '''';
  end
--    wcodaut = ''''||'fn.'||substring(prcodaut from 8)||'''';

  if ((PRCODTPCC is null) or (PRCODTPCC = '')) then
    WCODTPCC = 'null';
  else
  begin
    select BDRESULT
    from STRTRAN(upper(:PRCODTPCC), 'COLCON.', 'SERV.')
    into :WCODTPCC;
    WCODTPCC = '''' || WCODTPCC || '''';
  end

  WSQL = ' select ' || /*01*/ ' 1,' || /*02*/ ' T.BDCODEMP Codigo_Empresa,' || /*03*/ ' T.BDCODCOL Codigo_Colaborador,' || --/*09*/    ' EMP.BDCNPJEMP Cnpj_Empresa,'||
--/*10*/    ' EMP.BDNOMCID Cidade_Empresa,'||
--/*11*/    ' EMP.BDSIGLAUF UF_Empresa,'||
  /*09*/ ' tEMP.BDCNPJEMP Cnpj_Empresa,' || --/*13*/    ' col.BDNOMCOL Nome_Colaborador,'||
  /*14*/ ' s.BDDATASERV Admissao_Colaborador,' || --/*15*/    ' COL.bdpercratcol Rat_Apo_Col ,'||
--/*16*/    ' CBO.BDDESCCBOTSIN Funcao_Colaborador,'||
--/*17*/    ' COL.BDCPFCOL Cpf_Colaborador ,'||
--/*18*/    ' COL.BDPISCOL Pis_Colaborador ,'||
--/*22*/    ' COL.bdcodcbo CBO_Col,'||
  /*23*/ ' s.BDCODCENTRO Codigo_Plano_CC ,' || /*24*/ ' s.BDCODTPCC Codigo_CC        ,' || /*25*/ ' t.bdreffn, ' || /*26*/ 'T.BDCODVER Codigo_Verba,' || /*27*/ 'T.BDDESCVER Descricao_Verba,' || /*28*/ 'T.BDREFV Referencia_Verba,' || /*29*/ 'case when (t.BDTIPOCODVER in (0, 2)) then t.BDVALV else 0 end Proventos_Folha ,' || /*30*/ 'case when (t.BDTIPOCODVER in (0, 2)) then 0 else t.BDVALV end Descontos_Folha,' || /*31*/ 's.BDVALORSERV,';
  if (PRBASECALC = 1) then
    WSQL = WSQL || /*32*/ 'coalesce(t.BDBINSSCALC,t.BDBINSS),';
  else
    WSQL = WSQL || /*32*/ 't.BDBINSS,';

  WSQL = WSQL || /*33*/ 'coalesce(t.bdbircalc,t.BDBIRRF),' || /*34*/ 't.BDBRAIS,' || /*35*/ 't.BDDESCREDVER,' || /*36*/ 't.bdirrf,' || --/*37*/    'col.BDGRUPOCLA,'||
  /*38*/ 'cc.bdnomcta,' || /*39*/ 't.BDPISVER,' || /*40*/ 't.bdclaver,' || --/*42*/    'col.bdcodcla, '||
  /*43*/ 't.bdordemver, ' || /*44*/ 't.bdordemtipocodver, ' || /*45*/ 't.bdtipocodver, ' || /*46*/ 't.bdtiporefver, ' || /*47*/ 't.bdrefhoremp, ' || 'cs.BDBINSSCALC - cs.BDBASEINSS, ' || 'cs.BDDATAPAGSERV, ' || 'cs.BDVALORINSS, ' || '0 BDINSS13FN, ' || '0 BDBINSSAPFN, ' || '0 BDINSSAPFN, ' || '0 BDBINSS13APFN, ' || '0 BDINSS13APFN ' ||
         ', cs.BDVERSAOCALC '||

  ' from vrhf_sp_calc_autonomo (' || WCODEMP || ',' || WCODAUT || ',' || WREFAUX || ', null,' || PRPUXAFILIAIS || ',' || PRFILIAIS || ',' || WCODTPCC || ') T';
  WSQL = WSQL || ' left outer join vrh_base_tservterc s on (t.bdreffn = s.bdcodserv and t.bdcodemp = s.bdcodemp and t.bdcodcol = s.bdcodter)';
  WSQL = WSQL || ' left outer join vrhf_base_calc_terc cs on (t.bdreffn = cs.bdcodserv and t.bdcodemp = cs.bdcodemp and t.bdcodcol = cs.bdcodter)';
  WSQL = WSQL || ' join tempresas temp on (temp.bdcodemp = t.bdcodemp)';
--  WSQL = WSQL || ' join (select BDCODEMP, max(BDREFEMP) BDREFEMP from TEMPRESAS_REF where BDREFEMP <= '||prrefini||' group by BDCODEMP) emp2 on (emp2.bdcodemp = t.bdcodemp)';
--  WSQL = WSQL || ' join TEMPRESAS_REF emp on (emp.bdcodemp = t.bdcodemp and emp.bdrefemp = emp2.BDREFEMP)';

--  WSQL = WSQL || ' left outer join tcidade cidemp on (cidemp.bdcodcid = emp.bdcodcid)';
--  WSQL = WSQL || ' left outer join tuf ufemp on (cidemp.bdcoduf = ufemp.bdcoduf)';

--  WSQL = WSQL || ' left outer join (select BDCODEMP, max(BDREFEMP) BDREFEMP from TENQFED where BDREFEMP <= '||prrefini||' group by BDCODEMP) TENQ2 on (TENQ2.bdcodemp = t.bdcodemp)';
--  WSQL = WSQL || ' left outer join TENQFED TENQ on (TENQ.bdcodemp = t.bdcodemp and TENQ.BDREFEMP = TENQ2.BDREFEMP) ';
--  WSQL = WSQL || ' left outer join TCADENQFED DESCFED on (TENQ.BDCODENQFED = DESCFED.BDCODENQFED)';
--  WSQL = WSQL || ' left outer join (select BDCODEMP, max(BDREFEMP) BDREFEMP from VRHF_BASE_TEMPGPS where BDREFEMP <= '||prrefini||' group by BDCODEMP) gps2 on (gps2.bdcodemp = t.bdcodemp)';
--  WSQL = WSQL || ' left outer join VRHF_BASE_TEMPGPS gps on (gps.bdcodemp = t.bdcodemp and gps.BDREFEMP = gps2.BDREFEMP) ';
  WSQL = WSQL || ' left outer join centros_tpcc cc on (cc.bdcodcentro = s.bdcodcentro and cc.bdcodtpcc = s.bdcodtpcc)';

  wsql = wsql||' order by T.BDCODEMP, T.BDREFFN, T.BDCODCOL ';

  WTEMAUT = 0;

  WSQLAUXDAT = 'select first 1 COLCON.BDCODTER from VRHF_BASE_CALC_TERC COLCON ';
  WSQLAUXDAT = WSQLAUXDAT || ' join vrh_base_tservterc X on (X.BDCODEMP = COLCON.BDCODEMP and X.BDCODTER = COLCON.BDCODTER and X.BDCODSERV = COLCON.BDCODSERV) ';

  if (position(upper('tmp_empresas_select'), upper(prcodemp)) > 0) then
    WSQLAUXDAT = WSQLAUXDAT ||' '||prcodemp;

  WSQLAUXDAT = WSQLAUXDAT || ' where X.BDREFSERV between ' || PRREFINI || ' and ' || PRREFFIM;

  if (PRCODEMP is not null and
      PRCODEMP <> '' and (position(upper('tmp_empresas_select'), upper(prcodemp)) <= 0)) then
    WSQLAUXDAT = WSQLAUXDAT || ' and ' || PRCODEMP;
  if (PRCODAUT is not null and
      PRCODAUT <> '') then
    WSQLAUXDAT = WSQLAUXDAT || ' and ' || PRCODAUT;

  execute statement WSQLAUXDAT
      into :WTEMAUT;

  if (PRTIPOCOL <> 1 and
      WTEMAUT <> 0 and
      WTEMAUT is not null) then
-- if (prcodaut is null) then
  begin
      BDREFAUXV = 0;
      BDBINSSFEFOL = 0;
      BDVINSSFEFOL = 0;
      BDBFGTSFEFOL = 0;
      BDVFGTSFEFOL = 0;

    BDBINSS13 = 0;
    BDBFGTS13 = 0;
    BDBIRRF13 = 0;
      BDBFGTS = 0;
      BDFGTS = 0;
      BDVFGTS13 = 0;
    BDREFFN = cast(WREFAUX as integer);
    BDDATARESCISAO = null;
    BDDESCRICAOMOTRES = '';
    BDBSALFAM = 0;
    BDBFGTSMESANT = 0;
    BDFGTSMESANT = 0;
    BDBFGTSMES = 0;
    BDFGTSMES = 0;
    BDFGTSMES13 = 0;
    BDSALDO = 0;
    BDFGTS40 = 0;
    BDFGTS10 = 0;
    BDTOTALGRRF = 0;
      BDTEMGRRF = 0;
      BDCODTFUC = 0;
      BDTIPOMOV = 0;
      BDPERCMULTA40 = 0;
      BDPERCMULTA10 = 0;
      BDCATEGORIAESOCIAL = null;
    BDBFGTSMESPOST = 0;
    BDFGTSMESPOST = 0;
    BDBASEPISFN = 0;
    BDBASEPISFEFN = 0;
    BDBASEPIS13FN = 0;
    for execute statement WSQL
            into /*01*/ :BDTIPO_COL,
            /*02*/ :BDCODEMP,
            /*03*/ :BDCODCOL,
--            /*04*/ :BDNOMEMP,
--            /*05*/ :BDENDEMP,
--            /*06*/ :BDNUMEMP,
--            /*07*/ :BDBAIEMP,
--            /*08*/ :BDCEPEMP,
            /*09*/ :BDCNPJEMP,
--            /*10*/ :BDNOMCID,
--            /*11*/ :BDSIGLAUF,
--            /*12*/ :BDCOMPLEMP,
            --      /*13*/ : bdnomcol ,
            /*14*/ :BDDATAADMCOL,
            --      /*15*/ : bdpercratcol ,
            --      /*16*/ : bddesctfuc ,
            --      /*17*/ : bdcpfcol ,
            --      /*18*/ : bdpiscol ,
--            /*19*/ :BDCODENQFED,
--            /*20*/ :BDSIMPLESGPS,
            --      /*21*/ : bdctpscol ,
            --      /*22*/ : bdcodcbo ,
            /*23*/ :BDCODCENTRO,
            /*24*/ :BDCODTPCC,
            /*25*/ :BDCODSERV,
            /*26*/ :BDCODVER,
            /*27*/ :BDDESCVER,
            /*28*/ :BDREFV,
            /*29*/ :BDPROVENTO,
            /*30*/ :BDDESCONTO,
            /*31*/ :BDSALBASE,
            /*32*/ :BDBINSS,
            /*33*/ :BDBIRRF,
            /*34*/ :BDBRAIS,
            /*35*/ :BDDESCREDVER,
            /*36*/ :BDIRRF,
            --      /*37*/ : BDGRUPOCLA,
            /*38*/ :BDDESCCC,
            /*39*/ :BDPISVER,
            /*40*/ :BDCLAVER,
--            /*41*/ :BDDESCENQFED,
            --      /*42*/ : bdcodcla,
            /*43*/ :BDORDEMVER,
            /*44*/ :BDORDEMTIPOCODVER,
            /*45*/ :BDTIPOCODVER,
            /*46*/ :BDTIPOREFVER,
            /*47*/ :BDREFHOREMP,
             :BDVALMVINSSTER, :BDDATAPGTO,
--            :BDCCATVCONCOM,
            :BDINSSFN, :BDINSS13FN, :BDBINSSAPFN,
            :BDINSSAPFN, :BDBINSS13APFN, :BDINSS13APFN,
            :WVERSAOCALC
    do
    begin
      if ((wempatu <> BDCODEMP) or (wrefatu <> BDREFFN)) then
         begin
           wempatu = BDCODEMP;
           wrefatu = BDREFFN;
           wcolatu = 0;
           BDNOMEMP = null;
           BDAPEEMP = null;
           BDENDEMP = null;
           BDNUMEMP = null;
           BDCEPEMP = null;
           BDBAIEMP = null;
           BDCOMPLEMP = null;
           wcodcid = null;
           BDNOMCID = null;
           BDSIGLAUF = null;
           BDCODENQFED = null;
           BDDESCENQFED = null;
           BDSIMPLESGPS = null;
           BDCCATVCONCOM = null;

           select first 1 BDNOMEMP, BDAPEEMP, BDENDEMP, BDNUMEMP, BDCEPEMP, BDBAIEMP, BDCOMPLEMP, BDCODCID from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :BDREFFN order by BDREFEMP desc
           into :BDNOMEMP, :BDAPEEMP, :BDENDEMP, :BDNUMEMP, :BDCEPEMP, :BDBAIEMP, :BDCOMPLEMP, :wcodcid;

           if (coalesce(wcodcid, 0) > 0) then
              select first 1 CID.BDNOMCID, UF.BDSIGLAUF from TCIDADE CID join TUF UF on (UF.BDCODUF = CID.BDCODUF) where CID.BDCODCID = :wcodcid into :BDNOMCID, :BDSIGLAUF;

           select first 1 E.BDCODENQFED, CE.BDDESCENQFED from TENQFED E join TCADENQFED CE on (CE.BDCODENQFED = E.BDCODENQFED) where E.BDCODEMP = :BDCODEMP and E.BDREFEMP <= :BDREFFN order by E.BDREFEMP desc into :BDCODENQFED, :BDDESCENQFED;
           select first 1 BDSIMPLESGPS, BDCCATVCONCOM from VRHF_BASE_TEMPGPS where BDCODEMP = :BDCODEMP and BDREFEMP <= :BDREFFN order by BDREFEMP desc into :BDSIMPLESGPS, :BDCCATVCONCOM;
         end


    if ((WTERANT <> BDCODCOL) or (WEMPANT <> BDCODEMP))  then
      begin
          WTERANT = BDCODCOL;
          WEMPANT = BDCODEMP;

          wsqlauxdat = 'select COL.BDNOMCOL,COL.BDPERCRATCOL,COL.BDCPFCOL,COL.BDPISCOL,COL.BDCTPSCOL,COL.BDCODCBO,COL.BDGRUPOCLA,COL.BDCODCLA,COL.BDDESCCBOTSIN, COL.BDCATEGORIAESOCIAL '||
                       'from '||
                       '(select TREF.BDNOMETER BDNOMCOL, FGTS.BDPERCRATTER BDPERCRATCOL, case when (char_length(RH.BDCPFMEITER) = 14) then RH.BDCPFMEITER else TER.BDCGCTER end BDCPFCOL, DOC.BDPISTER BDPISCOL, case when DOC.BDCTPSTER = '''' then 0 else DOC.BDCTPSTER end BDCTPSCOL, VINC.BDCODCBO, CLA.BDGRUPOCLA, VINC.BDCODCLA, CBO.BDDESCCBOTSIN, FGTS.BDCATEGORIAESOCIAL '||
                       '  from TTERCEIRO TER '||
                       '  left outer join TTERCEIRO_RH RH on (RH.BDCODTER = TER.BDCODTER) '||
                       '  left outer join TTERCEIRO_REF TREF on (TREF.BDCODTER = TER.BDCODTER and TREF.BDREFEMP = (select max(R.BDREFEMP) from TTERCEIRO_REF R where R.BDCODTER = TER.BDCODTER and R.bdrefemp <= '||prreffim||'))'||
                       '  left outer join VRHF_BASE_TTERC_FGTSGPS FGTS on (FGTS.BDCODTER = TREF.BDCODTER and FGTS.BDREFTERC = TREF.BDREFEMP)'||
                       '  left outer join VRH_BASE_TTERC_DOCREF DOC on (DOC.BDCODTER = TREF.BDCODTER and DOC.BDREFTERC = (select max(R.BDREFTERC) from VRH_BASE_TTERC_DOCREF R where R.BDCODTER = TER.BDCODTER and R.BDREFTERC <='||prreffim||'))'||
                       '  left outer join VRH_BASE_TTERC_VINC VINC on (VINC.BDCODTER = TER.BDCODTER and VINC.BDREFTERC = DOC.BDREFTERC)'||
                       '  left outer join VRH_BASE_CBO_TSIN CBO on (VINC.BDCODCBO = CBO.BDCODCBO and VINC.BDCODCBOTSIN = CBO.BDCODCBOTSIN)'||
                       '  left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)'||
                       '  where TER.BDCODTER = '||BDCODCOL||' )COL';
    
      execute statement WSQLAUXDAT
          into :BDNOMCOL, :BDPERCRATCOL, :BDCPFCOL, :BDPISCOL, :BDCTPSCOL, :BDCODCBO, :BDGRUPOCLA, :BDCODCLA,
                   :BDDESCTFUC, :BDCATEGORIAESOCIAL;
      end

      BDMVINSSTER = 0;
      select sum(BDVALORINSS)
      from VRHF_BASE_CALC_TERC
      where BDCODEMP = :BDCODEMP and
            BDCODTER = :BDCODCOL and
            BDCODSERV < :BDCODSERV and
            BDREFINSSSERV >= :PRREFINI and
            BDREFINSSSERV <= :PRREFFIM
      into :BDMVINSSTER;
      BDMVINSSTER = coalesce(BDMVINSSTER, 0);

      -- { 17413 Marcelo B. M. 25/05/2017 Início }
      BDBASEINSSMV = 0;
      BDVALORINSSMV = 0;
      --          SELECT SUM(BDBASEINSS), SUM(BDVALORINSS) FROM VRHF_BASE_CALC_TERC WHERE BDCODEMP = :bdcodemp AND BDCODTER = :BDCODCOL AND BDCODSERV < :bdcodserv AND
      --             BDREFINSSSERV >= :prrefini AND BDREFINSSSERV <= :prreffim INTO :bdbaseinssmv, :bdvalorinssmv;
      --          bdbaseinssmv = COALESCE(bdbaseinssmv, 0);
      --          bdvalorinssmv = COALESCE(bdvalorinssmv, 0);

      select sum(BDBASEINSSNTER), sum(BDVALORINSSNTER)
      from VRHF_BASE_TTERC_MVINC
      where BDCODEMP = :BDCODEMP and
            BDCODTER = :BDCODCOL and
            BDREFTERC <= :PRREFINI and
            ((coalesce(BDREFTERCFIM, 0) = 0) or (coalesce(BDREFTERCFIM, 0) >= :PRREFINI))
      into :WV1, :WV2;

      BDBASEINSSMV = BDBASEINSSMV + coalesce(WV1, 0);
      BDVALORINSSMV = BDVALORINSSMV + coalesce(WV2, 0);

      BDBASEIRRFMV = 0;
      BDVALORIRRFMV = 0;
      if (coalesce(WVERSAOCALC,0) = 0) then
         begin
      WREFPAGTO = cast((substring(cast(:BDDATAPGTO as varchar(10)) from 1 for 4) || substring(cast(:BDDATAPGTO as varchar(10)) from 6 for 2)) as integer);
      select sum(BDBASEIR), sum(BDVALORIR)
      from VRHF_BASE_CALC_TERC
      where BDCODEMP = :BDCODEMP and
            BDCODTER = :BDCODCOL and
            BDCODSERV < :BDCODSERV and
            BDREFIRSERV >= :WREFPAGTO and
            BDREFIRSERV <= :WREFPAGTO
      into :BDBASEIRRFMV, :BDVALORIRRFMV;
      BDBASEIRRFMV = coalesce(BDBASEIRRFMV, 0);
      BDVALORIRRFMV = coalesce(BDVALORIRRFMV, 0);
         end

      WV1 = null;
      WV2 = null;
      select sum(BDBASEIRRFNTER), sum(BDVALORIRRFNTER)
      from VRHF_BASE_TTERC_MVINC
      where BDCODEMP = :BDCODEMP and
            BDCODTER = :BDCODCOL and
            BDREFTERC <= :PRREFINI and
            ((coalesce(BDREFTERCFIM, 0) = 0) or (coalesce(BDREFTERCFIM, 0) >= :PRREFINI))
      into :WV1, :WV2;

      BDBASEIRRFMV = BDBASEIRRFMV + coalesce(WV1, 0);
      BDVALORIRRFMV = BDVALORIRRFMV + coalesce(WV2, 0);

          -- { 17413 Marcelo B. M. 25/05/2017 Fim }

      WCODSERVMAX = null;
          select max(BDCODSERV)
          from VRH_BASE_TSERVTERC
          where BDCODTER = :BDCODCOL and
                BDCODEMP = :BDCODEMP and
            BDREFSERV between :PRREFFIM and :PRREFFIM
      into :WCODSERVMAX;

      if (WCODSERVMAX <> BDCODSERV) then
             BDCODSERVB = 'FALSE';
          else
             BDCODSERVB = 'TRUE';

      BDSALFAM13GPS = 0;
      BDSALFAMFNGPS = 0;

      suspend;
    end
  end

  execute procedure SP_SETA_COMPETENCIA(:PRREFINI, null, null);
end^

/* Restore proc. body: VRHF_SP_VERBAS_FOLHA */
ALTER PROCEDURE VRHF_SP_VERBAS_FOLHA(PREMPRESA VARCHAR(30000),
PRCOLABORADOR VARCHAR(30000),
PRORDEMIMPRESSAO INTEGER,
PRTIPOFOLHA INTEGER,
PRREFINI INTEGER,
PRREFFIN INTEGER,
PRAGRUPARSINDICATO INTEGER,
PRCLASSE INTEGER,
PRFUNCAO INTEGER,
PRCENTROCUSTO INTEGER,
PRSINDICATO INTEGER,
PRREFERENCIA INTEGER,
PRULTIMODIA DATE)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODCOL INTEGER,
BDNOMCOL DM_BDNOMCOL,
BDDESCTFUC VARCHAR(40),
BDDATAADMCOL DATE,
BDCTPSCOL DM_BDCTPS,
BDSERIECTPSCOL DM_SERIECTPS,
BDDSERIECTPSCOL VARCHAR(1),
BDPISCOL VARCHAR(14),
BDSALBASECOL NUMERIC(15,6),
BDCODSINTRAB INTEGER,
BDDESCSINTRAB VARCHAR(60),
BDLOGRSINTRAB VARCHAR(15),
BDENDSINTRAB VARCHAR(40),
BDBAISINTRAB VARCHAR(20),
BDNROSINTRAB DM_NUMEND,
BDCOMPLSINTRAB VARCHAR(20),
BDNOMCIDSINTRAB VARCHAR(40),
BDSIGLAUFSINTRAB VARCHAR(2),
BDCODVER INTEGER,
BDREFVER INTEGER,
BDDESCVER VARCHAR(40),
BDREFV NUMERIC(15,6),
BDVALV NUMERIC(15,6))
 AS
DECLARE VARIABLE WFIELDVERREF VARCHAR(30);
DECLARE VARIABLE WORDERBY VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WWHERE VARCHAR(10000);
BEGIN
      IF (prreferencia IS NOT NULL) THEN
         EXECUTE PROCEDURE sp_seta_competencia(prreferencia, NULL, prultimodia);
    
      wsql = 'select ';
      wsql = wsql || 'temp.bdcodemp, ';
      wsql = wsql || 'temp.bdnomemp,  ';
      wsql = wsql || 'vw_col_ref_atual.bdcodcol, ';
      wsql = wsql || 'vw_col.bdnomcol, ';
      wsql = wsql || 'tfuc.bddesctfuc, ';
      wsql = wsql || 'vw_col.bddataadmcol, ';
      wsql = wsql || 'vw_col.bdctpscol, ';
      wsql = wsql || 'vw_col.bdseriectpscol, ';
      wsql = wsql || 'vw_col.bddseriectpscol, ';
      wsql = wsql || 'vw_col.bdpiscol, ';
      wsql = wsql || 'col_calcdia.bdsalbasecol, ';
      wsql = wsql || 'tsintrab.bdcodsintrab, ';
      wsql = wsql || 'tsintrab.bddescsintrab, ';
      wsql = wsql || 'tsintrab.bdlogrsintrab, ';
      wsql = wsql || 'tsintrab.bdendsintrab, ';
      wsql = wsql || 'tsintrab.bdbaisintrab, ';
      wsql = wsql || 'tsintrab.bdnrosintrab, ';
      wsql = wsql || 'tsintrab.bdcomplsintrab, ';
      wsql = wsql || 'tcidsintrab.bdnomcid, ';
      wsql = wsql || 'tufsintrab.bdsiglauf, ';
      wsql = wsql || 'tverbas.bddescver, ';


      --folha normal
      IF (prtipofolha = 0) THEN
         BEGIN
           wsql = wsql || 'tfolhanormal.bdcodver, ';
           wsql = wsql || 'tfolhanormal.bdref, ';
           wsql = wsql || 'tfolhanormal.bdrefv, ';
           wsql = wsql || 'tfolhanormal.bdvalv ';
         END
      ELSE
      --adiantamento salário
      IF (prtipofolha = 1) THEN
         BEGIN
           wsql = wsql || 'tfolhaad.bdcodver, ';
           wsql = wsql || 'tfolhaad.bdrefad, ';
           wsql = wsql || 'tfolhaad.bdrefv, ';
           wsql = wsql || 'tfolhaad.bdvalv ';
         END
      ELSE
      --adiantamento 13 sal
      IF (prtipofolha = 2) THEN
         BEGIN
           wsql = wsql || 'ta13sal.bdcodver, ';
           wsql = wsql || 'ta13sal.bdrefa13, ';
           wsql = wsql || 'ta13sal.bdrefva13, ';
           wsql = wsql || 'ta13sal.bdvala13 ';
         END
      --13 salario
      IF (prtipofolha = 3) THEN
         BEGIN
           wsql = wsql || 't13sal.bdcodver, ';
           wsql = wsql || 't13sal.bdref, ';
           wsql = wsql || 't13sal.bdrefv, ';
           wsql = wsql || 't13sal.bdvalv ';
         END
      ELSE
      --complemento 13 sal
      IF (prtipofolha = 4) THEN
         BEGIN
           wsql = wsql || 'tc13sal.bdcodver, ';
           wsql = wsql || 'tc13sal.bdrefc13, ';
           wsql = wsql || 'tc13sal.bdrefvc13, ';
           wsql = wsql || 'tc13sal.bdvalvc13 ';
         END
      ELSE
      --Ferias
      /*if (prtipofolha = 5) then
         begin
         end
      else
      --PLR
      if (prtipofolha = 6) then
         begin
         end
      else*/
      --Folha complementar
      IF (prtipofolha = 7) THEN
         BEGIN
           wsql = wsql || 'tfolhacomp.bdcodver, ';
           wsql = wsql || 'tfolhacomp.bdref, ';
           wsql = wsql || 'tfolhacomp.bdrefv, ';
           wsql = wsql || 'tfolhacomp.bdvalv ';
         END
    
      wsql = wsql || 'from VW_COLABORADORES_REF_ATUAL vw_col_ref_atual ';
      wsql = wSql || 'left outer join SP_CONSULTAEMPRESAS('||prReferencia||', 0,  NULL) temp on (temp.bdCodemp =  vw_col_ref_atual.bdcodemp) ';
      wsql = wsql || 'left outer join vw_colaboradores vw_col on (vw_col.bdcodemp = vw_col_ref_atual.bdcodemp and
                                                                  vw_col.bdcodcol = vw_col_ref_atual.bdcodcol) ';
      wsql = wsql || 'left outer join VW_TCOLCON_VINCDIA COL_DIAVINC on (COL_DIAVINC.BDCODEMP = vw_col_ref_atual.BDCODEMP and
                                                                       COL_DIAVINC.BDCODCOL = vw_col_ref_atual.BDCODCOL) ';

      wsql = wsql || 'left outer join vrh_funcoes_tfuc tfuc on (tfuc.bdCODPLAFUC = COL_DIAVINC.bdcodplafuc and tfuc.bdcodtfuc = COL_DIAVINC.bdcodtfuc) ';
    
      wsql = wsql || 'left outer join vw_tcolcon_calcdia col_calcdia on (col_calcdia.BDCODEMP = vw_col_ref_atual.BDCODEMP and
                                                                       col_calcdia.BDCODCOL = vw_col_ref_atual.BDCODCOL) ';
      wsql = wsql || 'left outer join vrh_base_tsindtrab tsintrab on (tsintrab.bdcodsintrab =  vw_col_ref_atual.bdcodsintrab) ';
      wsql = wsql || 'left outer join tcidade tcidsintrab on (tcidsintrab.bdcodcid = tsintrab.bdcodcid) ';
      wsql = wsql || 'left outer join tuf tufsintrab on (tufsintrab.bdcoduf = tcidsintrab.bdcoduf) ';

      --folha normal
      IF (prtipofolha = 0) THEN
         BEGIN
           wsql = wsql || 'left outer join SP_vrhf_folhanormal tfolhanormal on (tfolhanormal.bdcodemp = vw_col_ref_atual.bdcodemp and tfolhanormal.bdcodcol = vw_col_ref_atual.bdcodcol) ';
           wsql = wsql || 'left outer join VRH_BASE_TVERBAS  tverbas on (tverbas.bdcodver = tfolhanormal.bdcodver) ';
         END
      ELSE
      --adiantamento salário
      IF (prtipofolha = 1) THEN
         BEGIN
           wsql = wsql || 'left outer join vw_vrhf_adiantamento_sal on (tfolhaad.bdcodemp = vw_col_ref_atual.bdcodemp and tfolhaad.bdcodcol = vw_col_ref_atual.bdcodcol) ';
           wsql = wsql || 'left outer join VRH_BASE_TVERBAS  tverbas on (tverbas.bdcodver = tfolhaad.bdcodver) ';
         END
      ELSE
      --adiantamento 13 sal
      IF (prtipofolha = 2) THEN
         BEGIN
           wsql = wsql || 'left outer join vw_vrhf_a13sal ta13sal on (ta13sal.bdcodemp = vw_col_ref_atual.bdcodemp and ta13sal.bdcodcol = vw_col_ref_atual.bdcodcol) ';
           wsql = wsql || 'left outer join VRH_BASE_TVERBAS  tverbas on (tverbas.bdcodver = ta13sal.bdcodver) ';
         END
      --13 salario
      IF (prtipofolha = 3) THEN
         BEGIN
           wsql = wsql || 'left outer join vw_vrhf_13sal t13sal on (t13sal.bdcodemp = vw_col_ref_atual.bdcodemp and t13sal.bdcodcol = vw_col_ref_atual.bdcodcol) ';
           wsql = wsql || 'left outer join VRH_BASE_TVERBAS  tverbas on (tverbas.bdcodver = t13sal.bdcodver) ';
         END
      ELSE
      --complemento 13 sal
      IF (prtipofolha = 4) THEN
         BEGIN
           wsql = wsql || 'left outer join vw_vrhf_c13sal tc13sal on (tc13sal.bdcodemp = vw_col_ref_atual.bdcodemp and tc13sal.bdcodcol = vw_col_ref_atual.bdcodcol) ';
           wsql = wsql || 'left outer join VRH_BASE_TVERBAS  tverbas on (tverbas.bdcodver = tc13sal.bdcodver) ';
         END
      ELSE
      --Ferias
      /*if (prtipofolha = 5) then
         begin
         end
      else
      --PLR
      if (prtipofolha = 6) then
         begin
         end*/
      --Folha complementar
      IF (prtipofolha = 7) THEN
         BEGIN
           wsql = wsql || 'left outer join SP_VRHF_FOLHACOMPLEMENTAR tfolhacomp on (tfolhacomp.bdcodemp = vw_col_ref_atual.bdcodemp and tfolhacomp.bdcodcol = vw_col_ref_atual.bdcodcol) ';
           wsql = wsql || 'left outer join VRH_BASE_TVERBAS tverbas on (tverbas.bdcodver = tfolhacomp.bdcodver) ';
         END

       wwhere = '';

      IF (prempresa <> '') THEN
         wwhere = wwhere||prempresa||' ';
    
      IF (prcolaborador <> '') THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||prcolaborador||' ';
         END

      IF (prfuncao > 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'tfuc.bdCODTFUC = '||prfuncao||' ';
         END
    
      IF (prSindicato > 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'vw_col_ref_atual.bdCODSINTRAB = '||prsindicato||' ';
         END
    
      IF (prclasse > 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'vw_col_ref_atual.bdCODCLA = '||prClasse||' ';
         END

      --folha normal
      IF (prtipofolha = 0) THEN
         BEGIN
            wfieldverref = 'tfolhanormal.bdREF';
            IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';

            wwhere = wwhere||'tfolhanormal.bdREF >= '||prrefini||' and '||'tfolhanormal.bdREF <= '||prreffin||' ';
         END
      ELSE
      --adiantamento salário
      IF (prtipofolha = 1) THEN
         BEGIN
            wfieldverref = 'tfolhaad.BDREFA13';
            IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';

            wwhere = wwhere||'tfolhaad.BDREFA13 >= '||prrefini||' and '||'tfolhaad.BDREFAD <= '||prreffin||' ';
         END
      ELSE
      --adiantamento 13 sal
      IF (prtipofolha = 2) THEN
         BEGIN
            wfieldverref = 'ta13sal.BDREFA13';
            IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';

            wwhere = wwhere||'ta13sal.BDREFA13 >= '||prrefini||' and '||'ta13sal.BDREFA13 <= '||prreffin||' ';
         END
      --13 salario
      IF (prtipofolha = 3) THEN
         BEGIN
            wfieldverref = 't13sal.BDREF';
            IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';

            wwhere = wwhere||'t13sal.BDREF >= '||prrefini||' and '||'t13sal.BDREF <= '||prreffin||' ';
         END
      ELSE
      --complemento 13 sal
      IF (prtipofolha = 4) THEN
         BEGIN
           wfieldverref = 'tc13sal.BDREFC13';
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';

           wwhere = wwhere||'tc13sal.BDREFC13 >= '||prrefini||' and '||'tc13sal.BDREFC13 <= '||prreffin||' ';
          END
      ELSE
      /*--Ferias
      if (prtipofolha = 5) then
         begin
         end
      else
      --PLR
      if (prtipofolha = 6) then
         begin
         end*/
      --Folha complementar
      IF (prtipofolha = 7) THEN
         BEGIN
           wfieldverref = 'tfolhacomp.BDREF';
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';

            wwhere = wwhere||'tfolhacomp.BDREF >= '||prrefini||' and '||'tfolhacomp.BDREF <= '||prreffin||' ';
         END
      IF (wwhere <> '') THEN
         wwhere = ' where '||wwhere;


      worderby = '';
      IF (prordemimpressao IS NOT NULL) THEN
         BEGIN
            worderby = 'order by ';
            IF (prordemimpressao = 0) THEN
               BEGIN
                 IF (pragruparsindicato = 1) THEN
                    worderby = wOrderBy||'temp.bdcodemp,'||wfieldverref||',tsintrab.bdcodsintrab,'||'tverbas.bdcodver,vw_col_ref_atual.bdcodcol ';
                 ELSE
                    worderby = wOrderBy||'temp.bdcodemp,'||wfieldverref||','||'tverbas.bdcodver,vw_col_ref_atual.bdcodcol ';
               END
            ELSE
               BEGIN
                 IF (pragruparsindicato = 1) THEN
                    worderby = wOrderBy||'temp.bdcodemp,'||wfieldverref||',tsintrab.bdcodsintrab,'||'tverbas.bdcodver,vw_col.bdnomcol ';
                 ELSE
                    worderby = wOrderBy||'temp.bdcodemp,'||wfieldverref||','||'tverbas.bdcodver,vw_col.bdnomcol ';
               END
         END
      wsql = wsql||wwhere||worderby;

      FOR EXECUTE STATEMENT wsql
      INTO
         :bdcodemp,
         :bdnomemp,
         :bdcodcol,
         :bdnomcol,
         :bddesctfuc,
         :bddataadmcol,
         :bdctpscol,
         :bdseriectpscol,
         :bddseriectpscol,
         :bdpiscol,
         :bdsalbasecol,
         :bdcodsintrab,
         :bddescsintrab,
         :bdlogrsintrab,
         :bdendsintrab,
         :bdbaisintrab,
         :bdnrosintrab,
         :bdcomplsintrab,
         :bdnomcidsintrab,
         :bdsiglaufsintrab,
         :bddescver,
         :bdcodver,
         :bdrefver,
         :bdrefv,
         :bdvalv DO
       BEGIN
         SUSPEND;
       END
END
^

/* Restore proc. body: VRHF_SP_VERBAS_PREV_RESC */
create or alter procedure VRHF_SP_VERBAS_PREV_RESC (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPATOMADOR integer,
    PRCODCC varchar(10000) = '' /* COLLATE WIN1252 - default */ )
returns (
    BDCODPLAFUC integer,
    BDCODSINTRAB integer,
    BDCODCLA integer,
    BDDESCENQFED varchar(10),
    BDTEMGRRF integer,
    BDBSALFAM numeric(18,6),
    BDDATARESCISAO date,
    BDDESCRICAOMOTRES varchar(300),
    BDTIPOMOV integer,
    BDTIPO_COL integer,
    BDCODMATRIZ integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMEMP DM_BDNOMEMP,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDBAIEMP DM_BDBAIRRO,
    BDCEPEMP varchar(9),
    BDCNPJEMP varchar(18),
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
    BDCOMPLEMP DM_BDCOMPENDERECO,
    BDNOMCOL DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDPERCRATCOL numeric(18,6),
    BDDESCTFUC varchar(80),
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDCODENQFED integer,
    BDSIMPLESGPS integer,
    BDCTPSCOL DM_BDCTPS,
    BDCODCBO integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDREFFN integer,
    BDCODSERV integer,
    BDCODVER integer,
    BDDESCVER varchar(80),
    BDREFV numeric(18,6),
    BDPROVENTO numeric(18,6),
    BDDESCONTO numeric(18,6),
    BDSALBASE numeric(18,6),
    BDBINSS numeric(18,6),
    BDBFGTS numeric(18,6),
    BDFGTS numeric(18,6),
    BDBIRRF numeric(18,6),
    BDBRAIS numeric(18,6),
    BDDESCREDVER varchar(80),
    BDIRRF numeric(18,6),
    BDGRUPOCLA integer,
    BDBINSS13 numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDBIRRF13 numeric(18,6),
    BDVFGTS13 numeric(18,6),
    BDBINSSFEFOL numeric(18,6),
    BDVINSSFEFOL numeric(18,6),
    BDBFGTSFEFOL numeric(18,6),
    BDVFGTSFEFOL numeric(18,6),
    BDDESCCC varchar(80),
    BDPISVER varchar(5),
    BDCLAVER varchar(20),
    BDBFGTSMESANT numeric(18,6),
    BDFGTSMESANT numeric(18,6),
    BDBFGTSMES numeric(18,6),
    BDFGTSMES numeric(18,6),
    BDSALDO numeric(18,6),
    BDFGTS40 numeric(18,6),
    BDFGTS10 numeric(18,6),
    BDTOTALGRRF numeric(18,6),
    BDORDEMVER integer,
    BDORDEMTIPOCODVER integer,
    BDTIPOCODVER integer,
    BDTIPOREFVER integer,
    BDREFHOREMP varchar(5),
    BDDATAPGTO date,
    BDBFGTSMESPOST numeric(18,6),
    BDFGTSMESPOST numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSSFNPR numeric(18,6),
    BDINSS13FNPR numeric(18,6),
    BDCCATVCONCOM DM_BOOLEAN,
    BDREFAUXV numeric(18,6),
    BDFGTSIND numeric(18,6),
    BDDATAGRRF date,
    BDPERCMULTA40 numeric(15,2),
    BDPERCMULTA10 numeric(15,2),
    BDFGTSMES13 numeric(18,6),
    BDCREDTRAB numeric(18,6),
    BDCREDTRABFERIAS numeric(18,6),
    BDCREDTRABCONTAB numeric(18,6),
    BDCREDTRABGUIAMENSAL boolean,
    BDGRRFPRES integer)
as
declare variable WSQLAUXDAT varchar(300);
declare variable WAAAAMM varchar(6);
declare variable WULDIAMES varchar(15);
declare variable WSQL varchar(32700);
declare variable WREFAUX varchar(10);
declare variable WCODEMP varchar(3000);
declare variable WCODCOL varchar(3000);
declare variable WREFINI varchar(10);
declare variable WREFFIM varchar(10);
declare variable WREF integer;
declare variable WCALCFGTSMESANT DM_BOOLEAN;
declare variable WEMPCRED integer;
declare variable WCOLCRED integer;
declare variable WREFCRED integer;
declare variable WCODCENTROCRED integer;
declare variable WCODTPCCCRED integer;
BEGIN
    IF (prreffim IS NOT NULL) THEN
        BEGIN
            EXECUTE PROCEDURE sp_seta_competencia(prreffim, NULL, NULL);
            wRef = prreffim;
        END
    ELSE 
        BEGIN
            IF (prrefini IS NOT NULL) THEN
                BEGIN
                    EXECUTE PROCEDURE sp_seta_competencia(prrefini, NULL, NULL);
                    wRef = prrefini;
                END
            ELSE
                BEGIN
                    wRef = 201112;
                END
        END

    IF (prcodemp IS NULL) THEN
        wcodemp = 'null';
    ELSE
        wcodemp = ''''||prcodemp||'''';

    IF (prcodcol IS NULL) THEN
        wcodcol = 'null';
    ELSE
        wcodcol = ''''||prcodcol||'''';

    IF (prrefini IS NULL) THEN
        wrefini = ' null ';
    ELSE
        wrefini = ''||prrefini;

    IF (prreffim IS NULL) THEN
        wreffim = ' null ';
    ELSE
        wreffim = ''||prreffim;

    IF (prreffim IS NOT NULL) THEN
        BEGIN
        wrefaux = wreffim;
        END
    ELSE 
        BEGIN
            IF (prrefini IS NOT NULL) THEN
                BEGIN
                    wrefaux = wrefini;
                END
            ELSE
                BEGIN
                    wrefaux = 'null';
                END
        END

    wsql = '';
    IF (wrefaux <> 'null') THEN
        wsql = 'select cast(ultdia as varchar(2)) from ULTIMO_DIA_MES('||SUBSTRING(wrefaux FROM 5 FOR 2)||','||SUBSTRING(wrefaux FROM 1 FOR 4)||')';

    IF (wsql <> '') THEN
        BEGIN
            EXECUTE STATEMENT wsql INTO wuldiames;
            wuldiames = SUBSTRING(wrefaux FROM 5 FOR 2)||'/'||wuldiames||'/'||SUBSTRING(wrefaux FROM 1 FOR 4);
            wuldiames = ''''||wuldiames||'''';
        END


    if (((PRCODCC is not null) and (PRCODCC <> '')) or (PRAGRUPATOMADOR <> 1))  then
      begin
        if (PRAGRUPATOMADOR = 3) then
          WSQL = 'select TIPO_COL, CODIGO_EMPRESA, CODIGO_COLABORADOR, BDCODMATRIZ, NOME_EMPRESA, ENDERECO_EMPRESA, NUMERO_EMPRESA, '||
                 ' BAIRRO_EMPRESA, CEP_EMPRESA, CNPJ_EMPRESA, CIDADE_EMPRESA, UF_EMPRESA, COMPL_EMPRESA, ADMISSAO_COLABORADOR, '||
                 ' RAT_APO_COL, FUNCAO_COLABORADOR, CPF_COLABORADOR, PIS_COLABORADOR, BDCODENQFED, CTPS_COL, CBO_COL, '||
                 ' CODIGO_PLANO_CC, CODIGO_CC, REFERENCIA, CODIGO_VERBA, DESCRICAO_VERBA, SUM(REFERENCIA_VERBA)REFERENCIA_VERBA, SUM(PROVENTOS_FOLHA)PROVENTOS_FOLHA, '||
                 ' SUM(DESCONTOS_FOLHA)DESCONTOS_FOLHA, BDSALBASE, SUM(BDBINSS)BDBINSS,SUM(BDBFGTS)BDBFGTS,SUM(BDFGTS) BDFGTS,SUM(BDBIRRF) BDBIRRF, SUM(BDBRAIS) BDBRAIS, BDDESCREDVER,SUM(BDIRRF) BDIRRF, BDGRUPOCLA, '||
                 ' SUM(BDBINSS13)BDBINSS13, SUM(BDBFGTS13)BDBFGTS13, SUM(BDBIRRF13)BDBIRRF13, BDNOMCTA, BDPISVER, BDCLAVER, SUM(BDFGTS13)BDFGTS13, SUM(BDBINSSFEFOL)BDBINSSFEFOL, SUM(BDINSSFEFOL)BDINSSFEFOL, SUM(BDBFGTSFEFOL)BDBFGTSFEFOL, '||
                 ' SUM(BDFGTSFEFOL)BDFGTSFEFOL, BDDATARESCISAOPREV, BDDESCPRES, BDTIPOMOV, SUM(BDBSALFAM)BDBSALFAM, BDDESCENQFED, BDCODCLA, BDCODSINTRAB, '||
                 ' BDCODPLAFUC, BDORDEMVER, BDORDEMTIPOCODVER, BDTIPOCODVER, BDTIPOREFVER, BDREFHOREMP, BDCALCFGTSMESANT, '||
                 ' BDDATAPAGRESCISAOPREV, SUM(BDBINSSAPFNPR)BDBINSSAPFNPR, SUM(BDINSSAPFNPR)BDINSSAPFNPR, SUM(BDBINSS13APFNPR)BDBINSS13APFNPR, SUM(BDINSS13APFNPR)BDINSS13APFNPR, SUM(BDINSS)BDINSS, SUM(BDINSS13)BDINSS13, '||
                 ' SUM(BDREFAUXVFN_MAX)BDREFAUXVFN_MAX, BDDATAPAGGRFCPREV, MAX(BDCREDTRABGUIAMENSAL) BDCREDTRABGUIAMENSAL, MAX(BDGRRFPRES) BDGRRFPRES '||
                 ' from ( ';
        else
          WSQL = 'select TIPO_COL, CODIGO_EMPRESA, CODIGO_COLABORADOR, BDCODMATRIZ, NOME_EMPRESA, ENDERECO_EMPRESA, NUMERO_EMPRESA, BAIRRO_EMPRESA, CEP_EMPRESA, CNPJ_EMPRESA, CIDADE_EMPRESA, '||
                 ' UF_EMPRESA, COMPL_EMPRESA, ADMISSAO_COLABORADOR, RAT_APO_COL, FUNCAO_COLABORADOR, CPF_COLABORADOR, PIS_COLABORADOR, BDCODENQFED, CTPS_COL, CBO_COL, CODIGO_PLANO_CC, CODIGO_CC, REFERENCIA, CODIGO_VERBA, '||
                 ' DESCRICAO_VERBA, REFERENCIA_VERBA, PROVENTOS_FOLHA, DESCONTOS_FOLHA, BDSALBASE, BDBINSS, BDBFGTS, BDFGTS, BDBIRRF, BDBRAIS, BDDESCREDVER, '||
                 ' BDIRRF, BDGRUPOCLA, BDBINSS13, BDBFGTS13, BDBIRRF13, BDNOMCTA, BDPISVER, BDCLAVER, BDFGTS13, BDBINSSFEFOL, BDINSSFEFOL, BDBFGTSFEFOL, BDFGTSFEFOL, '||
                 ' BDDATARESCISAOPREV, BDDESCPRES, BDTIPOMOV, BDBSALFAM, BDDESCENQFED, BDCODCLA, BDCODSINTRAB, BDCODPLAFUC, BDORDEMVER, BDORDEMTIPOCODVER, '||
                 ' BDTIPOCODVER, BDTIPOREFVER, BDREFHOREMP, BDCALCFGTSMESANT, BDDATAPAGRESCISAOPREV, BDBINSSAPFNPR, BDINSSAPFNPR, BDBINSS13APFNPR, BDINSS13APFNPR, '||
                 ' BDINSS, BDINSS13,BDREFAUXVFN_MAX, BDDATAPAGGRFCPREV, BDCREDTRABGUIAMENSAL, BDGRRFPRES '||
                 ' from ( ';


        WSQL = WSQL || 'select '||
               '0 Tipo_Col, res.BDCODEMP Codigo_Empresa,res.BDCODCOL Codigo_Colaborador,TEMP.BDCODMATRIZ, EMP.BDNOMEMP Nome_Empresa,EMP.BDENDEMP Endereco_Empresa,'||
               'EMP.BDNUMEMP Numero_Empresa,EMP.BDBAIEMP Bairro_Empresa,EMP.BDCEPEMP Cep_Empresa,tEMP.BDCNPJEMP Cnpj_Empresa,cid.BDNOMCID Cidade_Empresa,uf.BDSIGLAUF UF_Empresa,'||
               'EMP.BDCOMPLEMP Compl_Empresa ,COL.BDDATAADMCOL Admissao_Colaborador, colconfgts.bdpercratcol Rat_Apo_Col ,colfunc.BDDESCTFUC Funcao_Colaborador,'||
               'colcondoc.BDCPFCOL Cpf_Colaborador ,DOCREF.BDPISCOL Pis_Colaborador ,tenq.bdcodenqfed,DOCREF.bdctpscol CTPS_Col,COLFUNC.bdcodcbo CBO_Col,'||
               'colcon.BDCODCENTRO Codigo_Plano_CC ,colcon.BDCODTPCC Codigo_CC ,'||wref||' Referencia,COLCON.BDCODVER Codigo_Verba,ver.BDDESCVER Descricao_Verba,colcon.BDREFVFN_MAX Referencia_Verba,'||
               'case when (RVA.BDTIPOCODVER in (0, 2)) then COLCON.BDVALVFN else 0 end Proventos_Folha, case when (RVA.BDTIPOCODVER in (0, 2)) then 0 else COLCON.BDVALVFN end Descontos_Folha,'||
               'foln.BDSALBASE,foln.BDBINSS,foln.BDBFGTS,foln.BDFGTS,foln.BDBIRRF,foln.BDBRAIS,ver.BDDESCREDVER,foln.BDIRRF,classe.bdgrupocla,foln.BDBINSS13,foln.BDBFGTS13,foln.BDBIRRF13,'||
               'cc.bdnomcta,rva.bdpisver,ver.BDCLAVER,foln.BDFGTS13,foln.BDBINSSFEFOL,foln.BDINSSFEFOL,foln.BDBFGTSFEFOL,foln.BDFGTSFEFOL,res.bddatarescisaoprev,pres.bddescpres,'||
               'pres.bdtipomov,foln.BDBSALFAM,DESCFED.BDDESCENQFED,colconvinc.bdcodcla,colvinc.BDCODSINTRAB,colvincdia.bdcodplafuc,VER.bdordemver,RVA.BDORDEMTIPOCODVER,'||
               'RVA.BDTIPOCODVER,RVA.BDTIPOREFVER,empref.bdrefhoremp,res.BDCALCFGTSMESANTPREV BDCALCFGTSMESANT, res.BDDATAPAGRESCISAOPREV, '||
               'FOLN.BDBINSSAPFNPR, FOLN.BDINSSAPFNPR, FOLN.BDBINSS13APFNPR, FOLN.BDINSS13APFNPR, FOLN.BDINSS, FOLN.BDINSS13, colcon.BDREFAUXVFN_MAX, '||
               'res.BDDATAPAGGRFCPREV, res.BDCREDTRABGUIAMENSAL, pres.BDGRRFPRES ';
    
        WSQL = WSQL||'from ('||
                     'select colcon.* from vrh_emp_trescisao_previa colcon where COLCON.BDREFRESCISAOPREV = '||wref;
    
        IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
            wsql = wsql||' and '||prcodemp;
    
        IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
            wsql = wsql||' and '||prcodcol;
    
        WSQL = WSQL||') res '||
               'left outer join SP_VRH_CC_DATA(RES.bdcodemp,RES.bdcodcol,cast(' || wuldiames ||' as date)) cccol ' ||
               '                               on (cccol.bdcodemp = RES.bdcodemp and cccol.bdcodcol = RES.bdcodcol)'||
               'left outer join VRH_EMP_TCOLCON col on (col.bdcodemp = res.bdcodemp and col.bdcodcol = res.bdcodcol) '||
               'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = RES.BDCODEMP and COLCAD.BDCODCOL = RES.BDCODCOL) '||
               'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = RES.BDCODEMP and DOCREF.BDCODCOL = RES.BDCODCOL) '||
               'left outer join vw_vrhf_emp_tcolcon_fgtsgps colconfgts on (colconfgts.bdcodemp = res.bdcodemp and colconfgts.bdcodcol = res.bdcodcol) '||
               'left outer join vw_vrh_emp_tcolcon_vinc colconvinc on (colconvinc.bdcodemp = res.bdcodemp and colconvinc.bdcodcol = res.bdcodcol) '||
               'left outer join vw_vrh_emp_tcol_vinc colvinc on (colvinc.bdcodemp = res.bdcodemp and colvinc.bdcodcol = res.bdcodcol) '||
               'left outer join vw_vrh_emp_tcol_vincdia colvincdia on (colvincdia.bdcodemp = res.bdcodemp and colvincdia.bdcodcol = res.bdcodcol) '||
               'left outer join vrh_emp_tcolcon_doc colcondoc on (colcondoc.bdcodemp = res.bdcodemp and colcondoc.bdcodcol = res.bdcodcol) '||
               'left outer join vrh_emp_tcol_doc coldoc on (coldoc.bdcodemp = res.bdcodemp and coldoc.bdcodcol = res.bdcodcol) '||
               'left outer join(select COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDORDEM, VERBA.BDCODVER, VERBA.BDREFVFTPR BDREFVFN_MAX, '||
                              '        VERBA.BDREFAUXVFTPR BDREFAUXVFN_MAX, VERBA.BDVALVFTPR BDVALVFN, P.BDCODCENTRO, ';
                              if (PRAGRUPATOMADOR = 3) then
                                WSQL = WSQL||' case when C.BDTIPCTA = 1 then null else P.BDCODTPCC end BDCODTPCC ';
                              else
                                WSQL = WSQL||' P.BDCODTPCC BDCODTPCC ';

                              WSQL = WSQL||
                              ' from VRHF_EMP_TFOLTOM_PREV_RESC COLCON '||
                              ' left outer join VRHF_EMP_TVERBAFT_PREV_RESC VERBA on VERBA.BDCODEMP = COLCON.BDCODEMP and '||
                                                                                   ' VERBA.BDCODCOL = COLCON.BDCODCOL and '||
                                                                                   ' VERBA.BDORDEM = COLCON.BDORDEM '||
                              ' left outer join VRHF_EMP_TPREPFN P on P.BDCODEMP = COLCON.BDCODEMP and '||
                                                                      ' P.BDCODCOL = COLCON.BDCODCOL and '||
                                                                      ' P.BDORDEM = COLCON.BDORDEM '||
                              '  left outer join CENTROS_TPCC C on C.BDCODCENTRO = P.BDCODCENTRO and C.BDCODTPCC = P.BDCODTPCC ';

                                  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
                                      wsql = wsql||' where '||prcodemp;
    
                                  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
                                      wsql = wsql||' and '||prcodcol;

        WSQL = WSQL ||' group by COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDORDEM, VERBA.BDCODVER, VERBA.BDREFVFTPR, VERBA.BDREFAUXVFTPR, VERBA.BDVALVFTPR, P.BDCODCENTRO, BDCODTPCC '||
                      ' union all '||
                      ' select COLCON.BDCODEMP, COLCON.BDCODCOL, 0 BDORDEM, VERBA.BDCODVER, VERBA.BDREFVFNPR BDREFVFN_MAX, '||
                               ' VERBA.BDREFAUXVFNPR BDREFAUXVFN_MAX, VERBA.BDVALVFNPR BDVALVFN, null BDCODCENTRO, null BDCODTPCC '||
                      ' from VRHF_EMP_TFOLHANORMAL_PREV_RESC COLCON '||
                      ' left outer join VRHF_EMP_TVERBAFN_PREV_RESC VERBA on VERBA.BDCODEMP = COLCON.BDCODEMP and '||
                                                                           ' VERBA.BDCODCOL = COLCON.BDCODCOL ';
                          IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
                              wsql = wsql||' where '||prcodemp;

                          IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
                              wsql = wsql||' and '||prcodcol;
          WSQL = WSQL||' group by COLCON.BDCODEMP, COLCON.BDCODCOL, VERBA.BDCODVER, VERBA.BDREFVFNPR, VERBA.BDREFAUXVFNPR, VERBA.BDVALVFNPR) COLCON on (COLCON.BDCODEMP = RES.BDCODEMP and COLCON.BDCODCOL = RES.BDCODCOL) '||
                       'left outer join (select COLCON.BDCODEMP, COLCON.BDCODCOL, Y.BDCODCENTRO, Y.BDCODTPCC, sum(COLCON.BDBFGTSFTPR) BDBFGTS, '||
                                           'sum(COLCON.BDFGTSFTPR) BDFGTS, sum(COLCON.BDFGTSCSFTPR) BDFGTSCSFTPR, sum(COLCON.BDBFGTS13FTPR) BDBFGTS13, '||
                                           'sum(COLCON.BDFGTS13FTPR) BDFGTS13, sum(COLCON.BDFGTS13CSFTPR) BDFGTS13CS, max(COLCON.BDMAIORREMFTPR) BDMAIORREM, '||
                                           'sum(COLCON.BDBINSSFTPR) BDBINSS, max(COLCON.BDALIQINSSFTPR) BDALIQINSS, sum(COLCON.BDINSSFTPR) BDINSS, '||
                                           'sum(COLCON.BDBIRRFFTPR) BDBIRRF, max(COLCON.BDALIQIRRFFTPR) BDALIQIRRF, sum(COLCON.BDIRRFFTPR) BDIRRF, '||
                                           'sum(COLCON.BDBINSS13FTPR) BDBINSS13, max(COLCON.BDALIQINSS13FTPR) BDALIQINSS13, '||
                                           'sum(COLCON.BDINSS13FTPR) BDINSS13, sum(COLCON.BDBIRRF13FTPR) BDBIRRF13, '||
                                           'max(COLCON.BDALIQIRRF13FTPR) BDALIQIRRF13, sum(COLCON.BDIRRF13FTPR) BDIRRF13, '||
                                           'sum(COLCON.BDBSALFAMFTPR) BDBSALFAM, sum(COLCON.BDSALFAMFTPR) BDSALFAM, sum(COLCON.BDBRAISFTPR) BDBRAIS, '||
                                           'max(COLCON.BDSALBASEFTPR) BDSALBASE, sum(COLCON.BDDEPFTPR) BDDEP, sum(COLCON.BDBINSSFEFOLFTPR) BDBINSSFEFOL, '||
                                           'sum(COLCON.BDINSSFEFOLFTPR) BDINSSFEFOL, max(COLCON.BDALIQINSSFEFOLFTPR) BDALIQINSSFEFOL, '||
                                           'sum(COLCON.BDCREDITOFTPR) BDCREDITO, sum(COLCON.BDDEBITOFTPR) BDDEBITO, sum(COLCON.BDBFGTSFEFTPR) BDBFGTSFEFOL, '||
                                           'sum(COLCON.BDFGTSFEFTPR) BDFGTSFEFOL, sum(COLCON.BDBIRRFFEFTPR) BDBIRRFFE, sum(COLCON.BDIRRFFEFTPR) BDIRRFFE, '||
                                           'sum(COLCON.BDBINSSAPFTPR) BDBINSSAPFNPR, sum(COLCON.BDINSSAPFTPR) BDINSSAPFNPR, '||
                                           'sum(COLCON.BDBINSS13APFTPR) BDBINSS13APFNPR, sum(COLCON.BDINSS13APFTPR) BDINSS13APFNPR '||
                                        ' from VRHF_EMP_TFOLTOM_PREV_RESC COLCON '||
                                        ' left outer join VRHF_EMP_TPREPFN Y on Y.BDCODEMP = COLCON.BDCODEMP and '||
                                                                              ' Y.BDCODCOL = COLCON.BDCODCOL and  '||
                                                                              ' Y.BDORDEM  = COLCON.BDORDEM ';

               IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
                   wsql = wsql||' where '||prcodemp;

               IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
                   wsql = wsql||' and '||prcodcol;

               WSQL = WSQL||' group by COLCON.BDCODEMP, COLCON.BDCODCOL, Y.BDCODCENTRO, Y.BDCODTPCC ';
               WSQL = WSQL||' union all ';
               WSQL = WSQL||'select COLCON.BDCODEMP, COLCON.BDCODCOL, cast(null as integer), cast(null as integer), COLCON.BDBFGTSFNPR, '||
                                  ' COLCON.BDFGTSFNPR, COLCON.BDFGTSCSFNPR, COLCON.BDBFGTS13FNPR, COLCON.BDFGTS13FNPR, COLCON.BDFGTS13CSFNPR, '||
                                  ' COLCON.BDMAIORREMFNPR, COLCON.BDBINSSFNPR, COLCON.BDALIQINSSFNPR, COLCON.BDINSSFNPR, COLCON.BDBIRRFFNPR, '||
                                  ' COLCON.BDALIQIRRFFNPR, COLCON.BDIRRFFNPR, COLCON.BDBINSS13FNPR, COLCON.BDALIQINSS13FNPR, '||
                                  ' COLCON.BDINSS13FNPR, COLCON.BDBIRRF13FNPR, COLCON.BDALIQIRRF13FNPR, COLCON.BDIRRF13FNPR, '||
                                  ' COLCON.BDBSALFAMFNPR, COLCON.BDSALFAMFNPR, COLCON.BDBRAISFNPR, COLCON.BDSALBASEFNPR, COLCON.BDDEPFNPR, '||
                                  ' COLCON.BDBINSSFEFOLFNPR, COLCON.BDINSSFEFOLFNPR, COLCON.BDALIQINSSFEFOLFNPR, '||
                                  ' cast(0 as numeric(18,6)), cast(0 as numeric(18,6)), COLCON.BDBFGTSFEFN, COLCON.BDFGTSFEFN, '||
                                  ' COLCON.BDBIRRFFEFNPR, COLCON.BDIRRFFEFNPR, COLCON.BDBINSSAPFNPR, COLCON.BDINSSAPFNPR, '||
                                  ' COLCON.BDBINSS13APFNPR, COLCON.BDINSS13APFNPR '||
                            'from VRHF_EMP_TFOLHANORMAL_PREV_RESC COLCON ';

                IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
                    wsql = wsql||' where '||prcodemp;

                IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
                    wsql = wsql||' and '||prcodcol;

               WSQL = WSQL||') FOLN on (FOLN.BDCODEMP = RES.BDCODEMP and FOLN.BDCODCOL = RES.BDCODCOL and coalesce(FOLN.BDCODTPCC, 0) = coalesce(COLCON.BDCODTPCC, 0))'||
               'left outer join vrh_base_tclasse classe on (classe.bdcodcla = colconvinc.bdcodcla) '||
               'left outer join CENTROS_TPCC cc on (cc.bdcodcentro = colcon.BDCODCENTRO and cc.bdcodtpcc = colcon.bdcodtpcc) '||
               'left outer join VW_VERBAS_REF_ATUAL RVA on (RVA.BDCODVER = colcon.BDCODVER) '||
               'left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = colcon.BDCODVER) '||
               'left outer join VW_TEMPRESAS_REF emp on (emp.bdcodemp = res.bdcodemp) '||
               'left outer join tempresas temp on (temp.bdcodemp = res.bdcodemp) '||
               'left outer join VW_VRHF_BASE_TEMPCALC empref on (empref.bdcodemp = res.bdcodemp) '||
               'left outer join VRH_FUNCOES_TFUC colfunc on  (colvincdia.BDCODPLAFUC = colfunc.BDCODPLAFUC and colvincdia.BDCODTFUC = colfunc.BDCODTFUC) '||
               'left outer join vw_tenqfed TENQ on (TENQ.bdcodemp = res.bdcodemp) '||
               'left outer join vrh_base_tprepresc pres on (pres.bdcodpres = res.bdcodpres) '||
               'left outer join TCADENQFED DESCFED on (TENQ.BDCODENQFED = DESCFED.BDCODENQFED) '||
               'left outer join tcidade cid on (emp.bdcodcid = cid.bdcodcid) '||
               'left outer join tuf uf on (uf.bdcoduf = cid.bdcoduf) '||
               'order by res.BDCODEMP,res.BDCODCOL ';

               WSQL = WSQL || ')';

               if (PRCODCC <> '') then
                 WSQL = WSQL || ' where '||:PRCODCC;

               if (PRAGRUPATOMADOR = 3) then
                 WSQL = WSQL || ' group by TIPO_COL, CODIGO_EMPRESA, CODIGO_COLABORADOR, BDCODMATRIZ, NOME_EMPRESA, ENDERECO_EMPRESA, NUMERO_EMPRESA, BAIRRO_EMPRESA, CEP_EMPRESA, CNPJ_EMPRESA, CIDADE_EMPRESA, UF_EMPRESA, COMPL_EMPRESA, ADMISSAO_COLABORADOR, RAT_APO_COL, FUNCAO_COLABORADOR, CPF_COLABORADOR, PIS_COLABORADOR, BDCODENQFED, CTPS_COL, CBO_COL, CODIGO_PLANO_CC, CODIGO_CC, REFERENCIA, CODIGO_VERBA, DESCRICAO_VERBA, BDSALBASE, BDDESCREDVER, BDGRUPOCLA, BDNOMCTA, BDPISVER, BDCLAVER, BDDATARESCISAOPREV, BDDESCPRES, BDTIPOMOV, BDDESCENQFED, BDCODCLA, BDCODSINTRAB, BDCODPLAFUC, BDORDEMVER, BDORDEMTIPOCODVER, BDTIPOCODVER, BDTIPOREFVER, BDREFHOREMP, BDCALCFGTSMESANT, BDDATAPAGRESCISAOPREV, BDDATAPAGGRFCPREV  ';

       end
     else
       begin
    wsql = 'select '||
           '0 Tipo_Col, res.BDCODEMP Codigo_Empresa,res.BDCODCOL Codigo_Colaborador,TEMP.BDCODMATRIZ, EMP.BDNOMEMP Nome_Empresa,EMP.BDENDEMP Endereco_Empresa,'||
           'EMP.BDNUMEMP Numero_Empresa,EMP.BDBAIEMP Bairro_Empresa,EMP.BDCEPEMP Cep_Empresa,tEMP.BDCNPJEMP Cnpj_Empresa,cid.BDNOMCID Cidade_Empresa,uf.BDSIGLAUF UF_Empresa,'||
           'EMP.BDCOMPLEMP Compl_Empresa ,COL.BDDATAADMCOL Admissao_Colaborador, colconfgts.bdpercratcol Rat_Apo_Col ,colfunc.BDDESCTFUC Funcao_Colaborador,'||
           'colcondoc.BDCPFCOL Cpf_Colaborador ,DOCREF.BDPISCOL Pis_Colaborador ,tenq.bdcodenqfed,DOCREF.bdctpscol CTPS_Col,COLFUNC.bdcodcbo CBO_Col,'||
               'cccol.BDCODCENTRO Codigo_Plano_CC ,cccol.BDCODTPCC Codigo_CC ,'||wref||' Referencia,COLCON.BDCODVER Codigo_Verba,ver.BDDESCVER Descricao_Verba,colcon.BDREFVFN_SUM Referencia_Verba,'||
           'case when (RVA.BDTIPOCODVER in (0, 2)) then COLCON.BDVALVFN else 0 end Proventos_Folha, case when (RVA.BDTIPOCODVER in (0, 2)) then 0 else COLCON.BDVALVFN end Descontos_Folha,'||
           'foln.BDSALBASE,foln.BDBINSS,foln.BDBFGTS,foln.BDFGTS,foln.BDBIRRF,foln.BDBRAIS,ver.BDDESCREDVER,foln.BDIRRF,classe.bdgrupocla,foln.BDBINSS13,foln.BDBFGTS13,foln.BDBIRRF13,'||
           'cc.bdnomcta,rva.bdpisver,ver.BDCLAVER,foln.BDFGTS13,foln.BDBINSSFEFOL,foln.BDINSSFEFOL,foln.BDBFGTSFEFOL,foln.BDFGTSFEFOL,res.bddatarescisaoprev,pres.bddescpres,'||
           'pres.bdtipomov,foln.BDBSALFAM,DESCFED.BDDESCENQFED,colconvinc.bdcodcla,colvinc.BDCODSINTRAB,colvincdia.bdcodplafuc,VER.bdordemver,RVA.BDORDEMTIPOCODVER,'||
           'RVA.BDTIPOCODVER,RVA.BDTIPOREFVER,empref.bdrefhoremp,res.BDCALCFGTSMESANTPREV BDCALCFGTSMESANT, res.BDDATAPAGRESCISAOPREV, '||
           'FOLN.BDBINSSAPFNPR, FOLN.BDINSSAPFNPR, FOLN.BDBINSS13APFNPR, FOLN.BDINSS13APFNPR, FOLN.BDINSS, FOLN.BDINSS13, colcon.BDREFAUXVFN_MAX, '||
           'res.BDDATAPAGGRFCPREV, res.BDCREDTRABGUIAMENSAL, pres.BDGRRFPRES ';
    
    wsql = wsql||
           'from ('||
           'select colcon.* from vrh_emp_trescisao_previa colcon where COLCON.BDREFRESCISAOPREV = '||wref;
    
    IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;
    
    IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;
    
    wsql = wsql||
           ') res '||
           'left outer join SP_VRH_CC_DATA(RES.bdcodemp,RES.bdcodcol,cast(' || wuldiames ||' as date)) cccol ' ||
           '                               on (cccol.bdcodemp = RES.bdcodemp and cccol.bdcodcol = RES.bdcodcol)'||
           'left outer join VRH_EMP_TCOLCON col on (col.bdcodemp = res.bdcodemp and col.bdcodcol = res.bdcodcol) '||
           'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = RES.BDCODEMP and COLCAD.BDCODCOL = RES.BDCODCOL) '||
           'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = RES.BDCODEMP and DOCREF.BDCODCOL = RES.BDCODCOL) '||
           'left outer join vw_vrhf_emp_tcolcon_fgtsgps colconfgts on (colconfgts.bdcodemp = res.bdcodemp and colconfgts.bdcodcol = res.bdcodcol) '||
           'left outer join vw_vrh_emp_tcolcon_vinc colconvinc on (colconvinc.bdcodemp = res.bdcodemp and colconvinc.bdcodcol = res.bdcodcol) '||
           'left outer join vw_vrh_emp_tcol_vinc colvinc on (colvinc.bdcodemp = res.bdcodemp and colvinc.bdcodcol = res.bdcodcol) '||
           'left outer join vw_vrh_emp_tcol_vincdia colvincdia on (colvincdia.bdcodemp = res.bdcodemp and colvincdia.bdcodcol = res.bdcodcol) '||
           'left outer join vrh_emp_tcolcon_doc colcondoc on (colcondoc.bdcodemp = res.bdcodemp and colcondoc.bdcodcol = res.bdcodcol) '||
           'left outer join vrh_emp_tcol_doc coldoc on (coldoc.bdcodemp = res.bdcodemp and coldoc.bdcodcol = res.bdcodcol) '||
           'left outer join VWRH_UNION_FNPR_FTPR_MES colcon on (colcon.bdcodemp = res.bdcodemp and colcon.bdcodcol = res.bdcodcol) '||
           'left outer join VWRH_UNION_FNPR_FTPR_MES_BASES FOLN on (FOLN.BDCODEMP = res.BDCODEMP and FOLN.BDCODCOL = res.BDCODCOL) '||
           'left outer join vrh_base_tclasse classe on (classe.bdcodcla = colconvinc.bdcodcla) '||
           'left outer join CENTROS_TPCC cc on (cc.bdcodcentro = cccol.BDCODCENTRO and cc.bdcodtpcc = cccol.bdcodtpcc) '||
           'left outer join VW_VERBAS_REF_ATUAL RVA on (RVA.BDCODVER = colcon.BDCODVER) '||
           'left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = colcon.BDCODVER) '||
           'left outer join VW_TEMPRESAS_REF emp on (emp.bdcodemp = res.bdcodemp) '||
           'left outer join tempresas temp on (temp.bdcodemp = res.bdcodemp) '||
           'left outer join VW_VRHF_BASE_TEMPCALC empref on (empref.bdcodemp = res.bdcodemp) '||
           'left outer join VRH_FUNCOES_TFUC colfunc on  (colvincdia.BDCODPLAFUC = colfunc.BDCODPLAFUC and colvincdia.BDCODTFUC = colfunc.BDCODTFUC) '||
           'left outer join vw_tenqfed TENQ on (TENQ.bdcodemp = res.bdcodemp) '||
           'left outer join vrh_base_tprepresc pres on (pres.bdcodpres = res.bdcodpres) '||
           'left outer join TCADENQFED DESCFED on (TENQ.BDCODENQFED = DESCFED.BDCODENQFED) '||
           'left outer join tcidade cid on (emp.bdcodcid = cid.bdcodcid) '||
           'left outer join tuf uf on (uf.bdcoduf = cid.bdcoduf) '||
           'order by res.BDCODEMP,res.BDCODCOL ';
         end
    wcodemp = 0;
    wcodcol = 0;
    WEMPCRED = 0;
    WCOLCRED = 0;
    WREFCRED = 0;
    WCODCENTROCRED = 0;
    WCODTPCCCRED = 0;

    FOR EXECUTE STATEMENT wsql INTO
        /*01*/ : bdtipo_col ,
        /*02*/ : bdcodemp ,
        /*03*/ : bdcodcol ,
               : bdcodmatriz,
        /*04*/ : bdnomemp ,
        /*05*/ : bdendemp ,
        /*06*/ : bdnumemp ,
        /*07*/ : bdbaiemp ,
        /*08*/ : bdcepemp ,
        /*09*/ : bdcnpjemp ,
        /*10*/ : bdnomcid ,
        /*11*/ : bdsiglauf ,
        /*12*/ : bdcomplemp ,
        --/*13*/ : bdnomcol ,
        /*14*/ : bddataadmcol ,
        /*15*/ : bdpercratcol ,
        /*16*/ : bddesctfuc ,
        /*17*/ : bdcpfcol ,

               : bdpiscol ,

        /*18*/ : bdcodenqfed ,
        --/*19*/ : bdsimplesgps ,
        /*20*/ : bdctpscol ,
        /*21*/ : bdcodcbo ,
        /*22*/ : bdcodcentro ,
        /*23*/ : bdcodtpcc ,
        /*24*/ : bdreffn,
        /*25*/ : BDCODVER,
        /*26*/ : BDDESCVER,
        /*27*/ : BDREFV,
        /*28*/ : BDPROVENTO,
        /*29*/ : BDDESCONTO,
        /*30*/ : BDSALBASE,
        /*31*/ : BDBINSS,
        /*32*/ : BDBFGTS,
        /*33*/ : BDFGTS,
        /*34*/ : BDBIRRF,
        /*35*/ : BDBRAIS,
        /*36*/ : bddescredver,
        /*37*/ : bdirrf,
        /*38*/ : bdgrupocla,
        /*39*/ : bdbINSS13,
        /*40*/ : bdbFGTS13,
        /*41*/ : bdbIRRF13,
        /*42*/ : BDDESCCC,
        /*43*/ : bdpisver,
        /*44*/ : bdclaver,
        /*45*/ : BDVFGTS13,
               : BDBINSSFEFOL,
               : BDVINSSFEFOL,
               : BDBFGTSFEFOL,
               : BDVFGTSFEFOL,
        /*46*/ : bddatarescisao,
        /*47*/ : bddescricaomotres,
               : bdtipomov,
        /*48*/ : bdbsalfam,
        /*49*/ : BDDESCENQFED,
        /*50*/ : bdcodcla,
        /*51*/ : BDCODSINTRAB,
        /*52*/ : bdcodplafuc,
               : bdordemver,
               : bdordemtipocodver,
               : bdtipocodver,
               : bdtiporefver,
               : bdrefhoremp,
               : wcalcfgtsmesant,
               : bddatapgto,
               : bdbinssapfn,
               : bdinssapfn,
               : bdbinss13apfn,
               : bdinss13apfn,
               : bdinssfnpr,
               : bdinss13fnpr,
        --       : bdccatvconcom,
               : bdrefauxv,
               : bddatagrrf,
               : BDCREDTRABGUIAMENSAL,
               : BDGRRFPRES
    DO
        BEGIN
            bdcodserv = bdreffn;
            bdbfgtsmesant = 0;
            bdfgtsmesant = 0;
            bdbfgtsmes = 0;
            bdfgtsmes = 0;
            BDFGTSMES13 = 0;
            bdsaldo = 0;
            bdfgts40 = 0;
            bdfgts10 = 0;
            bdtotalgrrf = 0;
            bdtemgrrf = 0;
            bdbfgtsmespost = 0;
            bdfgtsmespost = 0;
            bdfgtsind = 0;
            bdpercmulta10 = 0;
            bdpercmulta40 = 0;

            if ((wcodemp <> BDCODEMP) or (wcodcol <> BDCODCOL)) then
                begin
                    wsqlauxdat = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFCOL <= '||BDREFFN||' order by BDREFCOL DESC ';
                    execute statement wsqlauxdat into :BDNOMCOL;
     
                    if (wcodemp <> BDCODEMP) then
                        begin
                            wsqlauxdat = 'select first 1 BDSIMPLESGPS, BDCCATVCONCOM from VRHF_BASE_TEMPGPS where BDCODEMP = '||BDCODEMP||' and  BDREFEMP <= '||BDREFFN||' order by BDREFEMP DESC ';
                            execute statement wsqlauxdat into :BDSIMPLESGPS, :BDCCATVCONCOM;
                        end

                    wcodemp = BDCODEMP;
                    wcodcol = BDCODCOL;

                    IF (bddatarescisao IS NOT NULL) THEN
                        BEGIN
                            wsqlauxdat = 'select bdaaaamm from aaaamm(cast('||''''||CAST(bddatarescisao AS VARCHAR(10))||''''||' as date))';
     
                            EXECUTE STATEMENT wsqlauxdat INTO waaaamm;
     
                            IF (waaaamm <> bdreffn) THEN
                                BEGIN
                                    bddatarescisao = NULL;
                                    bddescricaomotres = '';
     
                                    /* Verifica se a rescisão é no mês seguinte e se tem o parâmetro de FGTS mês anterior, para não buscar o FGTS do mês */
                                    IF (SUBSTRING(waaaamm FROM 5 FOR 2) = '01') THEN
                                        waaaamm = CAST((CAST((SUBSTRING(waaaamm FROM 1 FOR 4)) AS INTEGER) - 1) AS VARCHAR(4))||'12';
                                    ELSE
                                        BEGIN
                                            IF (CAST((SUBSTRING(waaaamm FROM 5 FOR 2)) AS INTEGER) <= 10) THEN
                                                waaaamm = SUBSTRING(waaaamm FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(waaaamm FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1));
                                            ELSE
                                                waaaamm = SUBSTRING(waaaamm FROM 1 FOR 4)||CAST((CAST((SUBSTRING(waaaamm FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1));
                                        END
     
                                    IF (waaaamm = bdreffn AND UPPER(wcalcfgtsmesant) = 'TRUE') THEN
                                        BEGIN
                                            bdbfgtsmespost = bdbfgts;
                                            bdfgtsmespost = bdfgts;
                             
                                            bdbfgts = 0;
                                            bdbfgts13 = 0;
                                            bdbfgtsfefol = 0;
                                            bdfgts = 0;
                                            bdvfgts13 = 0;
                                            bdvfgtsfefol = 0;
                                        END
                                END
     
     
                        END
                end

            IF (bddatarescisao IS NOT NULL) THEN
                BEGIN
                    wsqlauxdat = 'select x.bdbfgtsmesant,x.bdfgtsmesant, x.bdbfgtsmes, x.bdfgtsmes, x.bdsaldo, x.bdfgts40, x.bdfgts10, x.bdtotal, x.bdfgtsind, x.bdpercmulta40, x.bdpercmulta10, x.bdfgts13 from VRHF_EMP_VAL_GRRF('||bdcodemp||','||bdcodcol||','||bdreffn||','||bdreffn||',2) x';
                    EXECUTE STATEMENT wsqlauxdat INTO
                    : bdbfgtsmesant,
                    : bdfgtsmesant,
                    : bdbfgtsmes,
                    : bdfgtsmes,
                    : bdsaldo,
                    : bdfgts40,
                    : bdfgts10,
                    : bdtotalgrrf,
                    : bdfgtsind,
                    : bdpercmulta40,
                    : bdpercmulta10,
                    : bdfgtsmes13;
            
                    IF (bdtotalgrrf <> 0) THEN
                        BDTEMGRRF = 1;
                END

            if ((BDCODEMP <> WEMPCRED) or (BDCODCOL <> WCOLCRED) or (BDREFFN <> WREFCRED) or (BDCODCENTRO <> WCODCENTROCRED) or (BDCODTPCC <> WCODTPCCCRED)) then
             begin
               wempcred = BDCODEMP;
               wcolcred = BDCODCOL;
               wrefcred = BDREFFN;
               wcodcentrocred = BDCODCENTRO;
               wcodtpcccred = BDCODTPCC;
    
               BDCREDTRAB       = 0;
               BDCREDTRABCONTAB = 0;
               BDCREDTRABFERIAS = 0;
    

                SELECT
                   SUM(A.BDVALOR) AS BDCREDTRAB,
                   SUM(CASE WHEN VR.BDCLAVER STARTING WITH '0.100.4.1' THEN A.BDVALOR ELSE null END) AS BDCREDTRABFERIAS,
                   SUM(CASE WHEN VR.BDCLAVER NOT STARTING WITH '0.100.4.1' THEN A.BDVALOR ELSE null END) AS BDCREDTRABCONTAB
                FROM (
                    SELECT TOM.BDCODEMP, TOM.BDCODCOL, TOM.BDREFVFTPR BDREF, TOM.BDCODVER, TOM.BDVALVFTPR BDVALOR
                    FROM VRHF_EMP_TVERBAFT_PREV_RESC TOM
                    UNION ALL
                    SELECT FN.BDCODEMP, FN.BDCODCOL, FN.BDREFVFNPR BDREF, FN.BDCODVER, FN.BDVALVFNPR BDVALOR
                    FROM
                    VRHF_EMP_TVERBAFN_PREV_RESC FN
                    ) A
                LEFT OUTER JOIN VRH_BASE_TVERBAS VR ON VR.BDCODVER = A.BDCODVER
                WHERE A.BDCODEMP = :BDCODEMP AND A.BDCODCOL = :BDCODCOL
                AND ((VR.BDCLAVER STARTING WITH '0.070.1.1') or (VR.BDCLAVER STARTING WITH '0.100.4.1') or (VR.BDCLAVER STARTING WITH '0.009.1.1') or (VR.BDCLAVER STARTING WITH '0.009.1.2'))
                into :BDCREDTRAB, :BDCREDTRABFERIAS, :BDCREDTRABCONTAB;

             end

        SUSPEND;
      END
END^

/* Restore proc. body: VRHF_SP_VERBAS_SIM_COL_CALC */
ALTER PROCEDURE VRHF_SP_VERBAS_SIM_COL_CALC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODEMP INTEGER,
BDCODCOL INTEGER,
BDCODVER INTEGER,
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
DECLARE VARIABLE wsql VARCHAR(15000);
DECLARE VARIABLE wdataini VARCHAR(8);
DECLARE VARIABLE wdatafim VARCHAR(8);
DECLARE VARIABLE wdtaux VARCHAR(10);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(NULL, prdataini, prdatafim);

  wdtaux = CAST(prdataini AS VARCHAR(10));
  wdataini = SUBSTRING(wdtaux FROM 1 FOR 4)||SUBSTRING(wdtaux FROM 6 FOR 2)||SUBSTRING(wdtaux FROM 9 FOR 2);

  wdtaux = CAST(prdatafim AS VARCHAR(10));
  wdatafim = SUBSTRING(wdtaux FROM 1 FOR 4)||SUBSTRING(wdtaux FROM 6 FOR 2)||SUBSTRING(wdtaux FROM 9 FOR 2);


  wsql = 'select BDCODEMP, '||
                'BDCODCOL, '||
                'BDCODVER, '||
                'BDANOINI, '||
                'BDMESINI, '||
                'BDDIAINI, '||
                'BDANOFIM, '||
                'BDMESFIM, '||
                'BDDIAFIM, '||
                'BDFORMULAREF, '||
                'BDFORMULAVAL ';
  wsql = wsql||'from VW_VERBAS_SIM_COL_ATUAL ';
  wsql = wsql|| 'where ((BDDATAINI >= '||wdataini||' and BDDATAINI <= '||wdatafim||') or '||
                      '(BDDATAFIM >= '||wdataini||' and BDDATAFIM <= '||wdatafim||') or '||
                      '(BDDATAINI <= '||wdataini||' and BDDATAFIM >= '||wdatafim||')) ';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     wsql = wsql||' and '||PRCODEMP;

  IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
     wsql = wsql||' and '||PRCODCOL;

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDCODVER,
    :BDANOINI,
    :BDMESINI,
    :BDDIAINI,
    :BDANOFIM,
    :BDMESFIM,
    :BDDIAFIM,
    :BDFORMREF,
    :BDFORMVAL
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: VRHF_SP_VERBAS_SIM_PRES_CALC */
ALTER PROCEDURE VRHF_SP_VERBAS_SIM_PRES_CALC(PRCODEMP VARCHAR(10000),
PRCODCOL VARCHAR(32700),
PRDATAINI DATE,
PRDATAFIM DATE)
 RETURNS(BDCODPRES INTEGER,
BDCODVER INTEGER,
BDANOINI INTEGER,
BDMESINI INTEGER,
BDDIAINI INTEGER,
BDANOFIM INTEGER,
BDMESFIM INTEGER,
BDDIAFIM INTEGER,
BDFORMREF VARCHAR(5000),
BDFORMVAL VARCHAR(5000))
 AS
DECLARE VARIABLE WSQL VARCHAR(15000);
DECLARE VARIABLE WDATAINI VARCHAR(8);
DECLARE VARIABLE WDATAFIM VARCHAR(8);
DECLARE VARIABLE WDTAUX VARCHAR(10);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(NULL, prdataini, prdatafim);

  wdtaux = CAST(prdataini AS VARCHAR(10));
  wdataini = SUBSTRING(wdtaux FROM 1 FOR 4)||SUBSTRING(wdtaux FROM 6 FOR 2)||SUBSTRING(wdtaux FROM 9 FOR 2);

  wdtaux = CAST(prdatafim AS VARCHAR(10));
  wdatafim = SUBSTRING(wdtaux FROM 1 FOR 4)||SUBSTRING(wdtaux FROM 6 FOR 2)||SUBSTRING(wdtaux FROM 9 FOR 2);


  wsql = 'select VS.BDCODPRES, '||
                'VS.BDCODVER, '||
                'VS.BDANOINI, '||
                'VS.BDMESINI, '||
                'VS.BDDIAINI, '||
                'VS.BDANOFIM, '||
                'VS.BDMESFIM, '||
                'VS.BDDIAFIM, '||
                'VS.BDFORMULAREF, '||
                'VS.BDFORMULAVAL ';
  wsql = wsql||'from VW_VERBAS_SIM_PRESC_ATUAL VS ';
  wsql = wsql|| 'where ((VS.BDDATAINI >= '||wdataini||' and VS.BDDATAINI <= '||wdatafim||') or '||
                      '(VS.BDDATAFIM >= '||wdataini||' and VS.BDDATAFIM <= '||wdatafim||') or '||
                      '(VS.BDDATAINI <= '||wdataini||' and VS.BDDATAFIM >= '||wdatafim||')) ';

  wsql = wsql||' and (exists (select RESC.BDCODPRES from VRH_EMP_TRESCISAO RESC where VS.BDCODPRES = RESC.BDCODPRES and RESC.BDDATARESCISAO >= '''||prdataini||
             ''' and RESC.BDDATARESCISAO <= '''||prdatafim||'''';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     wsql = wsql||' and '||PRCODEMP;

  IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
     wsql = wsql||' and '||PRCODCOL;

  wsql = wsql||')) ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODPRES,
    :BDCODVER,
    :BDANOINI,
    :BDMESINI,
    :BDDIAINI,
    :BDANOFIM,
    :BDMESFIM,
    :BDDIAFIM,
    :BDFORMREF,
    :BDFORMVAL
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: VRHF_SPF_BC_PROLAB_COLAB */
ALTER PROCEDURE VRHF_SPF_BC_PROLAB_COLAB(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER,
PRTIPOCADASTRO INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE camposum VARCHAR(50);
DECLARE VARIABLE tabela VARCHAR(100);
DECLARE VARIABLE strtpfolha VARCHAR(100);
DECLARE VARIABLE wsql VARCHAR(5000);
BEGIN
  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  IF (:prtipofolha = 0) THEN
      BEGIN
        camposum   = 'BDBINSSFN';
        strtpfolha   = 'FN';
        tabela       = 'VRHF_EMP_TFOLHANORMAL FOLHA ';

      END
   ELSE
     IF (:prtipofolha = 1) THEN
        BEGIN
          camposum   = 'BDBINSSFC';
          strtpfolha   = 'FC';
          tabela       = 'VRHF_EMP_Tfolhacomp FOLHA ';
        END
     ELSE
       IF (:prtipofolha = 2) THEN
         BEGIN
            camposum = 'BDBASEINSS13';
            strtpfolha   = '13';
            tabela   = 'VRHF_EMP_T13SAL FOLHA ';
         END
       ELSE
         BEGIN
            camposum   = 'BDBASEINSSC13';
            strtpfolha   = 'c13';
            tabela       = 'VRHF_EMP_TC13SAL FOLHA ';
         END


  WSql = 'select sum(FOLHA.'||camposum||')';
  wsql = wsql || ' FROM '||:tabela;

  wsql = wsql || ' left outer join vw_colaboradores_ref_atual con on (FOLHA.bdcodemp = CON.bdcodemp and ';
  wsql = wsql ||                                                     ' FOLHA.bdcodcol = CON.bdcodcol)';
  wsql = wsql || ' where CON.bdcontrcol = '||:PRTIPOCADASTRO;--SEGURADOS COLABORADORES - SEGURADOS PROLABORISTAS
  wsql = wsql || ' AND FOLHA.bdcodemp = '||:premp;
  wsql = wsql || ' AND FOLHA.bdref'||strtpfolha||' = '||:prref;

  IF (:prfiltrocol <> NULL) THEN
    wsql = wsql || ' and '||:prfiltrocol;

  FOR EXECUTE STATEMENT wsql
     INTO
        :BDVALOR
     DO
       BEGIN
         SUSPEND;
       END

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: VRHF_SPF_BC_PROLABORISTAS */
ALTER PROCEDURE VRHF_SPF_BC_PROLABORISTAS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE ALIQ NUMERIC(15,4);
DECLARE VARIABLE SQL VARCHAR(500);
BEGIN

  SQL = 'SELECT * FROM VRHF_SPF_BC_PROLAB_COLAB(';
  SQL = SQL || premp ||',';
  IF (:prfiltrocol = '') THEN
    SQL = SQL ||'null,';
  ELSE
    SQL = SQL || prfiltrocol ||',';

  SQL = SQL || prref ||',';
  SQL = SQL || prtipofolha ||',1)';

  FOR EXECUTE STATEMENT SQL
     INTO
        :BDVALOR
     DO
       BEGIN
          SELECT BDEMPEMP FROM vrh_sp_empresas(NULL, :prref) WHERE bdcodemp = :premp
          INTO
            :aliq;

         BDVALOR = ((BDVALOR *ALIQ)/100 );
         SUSPEND;
       END

END
^

/* Restore proc. body: VRHF_SPF_BC_RAT */
ALTER PROCEDURE VRHF_SPF_BC_RAT(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE ALIQFAP NUMERIC(15,4);
DECLARE VARIABLE ALIQ NUMERIC(15,4);
DECLARE VARIABLE ALIQCNAE NUMERIC(15,4);
DECLARE VARIABLE SQL VARCHAR(5000);
BEGIN

  SQL = 'SELECT * FROM VRHF_SPF_BC_PROLAB_COLAB(';
  SQL = SQL || premp ||',';
  IF (:prfiltrocol = '') THEN
    SQL = SQL ||'null,';
  ELSE
    SQL = SQL || prfiltrocol ||',';

  SQL = SQL || prref ||',';
  SQL = SQL || prtipofolha ||',0)';

  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  FOR EXECUTE STATEMENT SQL
     INTO
        :BDVALOR
     DO
       BEGIN
         SELECT cn.bdtaxacnae FROM sp_consultaempresas(:prref,:premp,null) emp
         LEFT OUTER JOIN vw_tcnae_ref cn ON (emp.bdcodcnae = cn.bdcodcnae)
         WHERE bdcodemp = :premp
         INTO
           :aliqcnae;

         IF ((aliqcnae IS NULL) OR (aliqcnae = 0)) THEN
           BEGIN
             SELECT cn.bdtaxacnae FROM sp_consultaempresas(:prref,:premp,null) emp
             LEFT OUTER JOIN vw_tcnae_ref cn ON (emp.bdcodcnae = cn.bdcodcnae)
             WHERE bdcodemp = :premp
             INTO
               :aliqcnae;
           END

         SELECT bdfap FROM vrh_sp_empresas(NULL,:prREF)
         WHERE bdcodemp = :premp
         INTO
           :ALIQFAP;

         aliq = (aliqcnae * aliqfap);

         BDVALOR = ((BDVALOR *ALIQ)/100 );

         SUSPEND;
       END
END
^

/* Restore proc. body: VRHF_SPF_BC_SEGURADOS */
ALTER PROCEDURE VRHF_SPF_BC_SEGURADOS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE aliq NUMERIC(15,4);
DECLARE VARIABLE sql VARCHAR(5000);
BEGIN

  SQL = 'SELECT * FROM VRHF_SPF_BC_PROLAB_COLAB(';
  SQL = SQL || premp ||',';
  IF (:prfiltrocol = '') THEN
    SQL = SQL ||'null,';
  ELSE
    SQL = SQL || prfiltrocol ||',';

  SQL = SQL || prref ||',';
  SQL = SQL || prtipofolha ||',0)';

  FOR EXECUTE STATEMENT SQL
     INTO
        :BDVALOR
     DO
       BEGIN
          SELECT emp.BDFUNEMP FROM vrh_sp_empresas(NULL, :prref) emp WHERE bdcodemp = :premp
          INTO
            :aliq;
--    :BDEMPEMP,
--    :BDAUTEMP,
--    :BDFUNEMP,
         BDVALOR = ((BDVALOR *ALIQ)/100 );

         SUSPEND;
       END

END
^

/* Restore proc. body: VRHF_SPF_BC_TERCEIROS */
ALTER PROCEDURE VRHF_SPF_BC_TERCEIROS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE aliq NUMERIC(15,4);
DECLARE VARIABLE sql VARCHAR(5000);
BEGIN

  SQL = 'SELECT * FROM VRHF_SPF_BC_PROLAB_COLAB(';
  SQL = SQL || premp ||',';
  IF (:prfiltrocol = '') THEN
    SQL = SQL ||'null,';
  ELSE
    SQL = SQL || prfiltrocol ||',';

  SQL = SQL || prref ||',';
  SQL = SQL || prtipofolha ||',0)';

  FOR EXECUTE STATEMENT SQL
     INTO
        :BDVALOR
     DO
       BEGIN
         SELECT EMP.bdperterc FROM vrh_sp_empresas(NULL,:prref) emp
         WHERE EMP.bdcodemp = :premp
         INTO
           :aliq;

         BDVALOR = ((BDVALOR *ALIQ)/100 );

         SUSPEND;
       END

END
^

/* Restore proc. body: VRHF_SPF_PROLAB_COLAB */
ALTER PROCEDURE VRHF_SPF_PROLAB_COLAB(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER,
PRTIPOCADASTRO INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE camposum VARCHAR(50);
DECLARE VARIABLE tabela VARCHAR(100);
DECLARE VARIABLE strtpfolha VARCHAR(100);
DECLARE VARIABLE wsql VARCHAR(5000);
BEGIN
  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  IF (:prtipofolha = 0) THEN
      BEGIN
        camposum   = 'BDINSSFN';
        strtpfolha   = 'FN';
        tabela       = 'VRHF_EMP_TFOLHANORMAL FOLHA ';

      END
   ELSE
     IF (:prtipofolha = 1) THEN
        BEGIN
          camposum   = 'BDINSSFC';
          strtpfolha   = 'FC';
          tabela       = 'VRHF_EMP_Tfolhacomp FOLHA ';
        END
     ELSE
       IF (:prtipofolha = 2) THEN
         BEGIN
            camposum = 'BDVALORINSS13';
            strtpfolha   = '13';
            tabela   = 'VRHF_EMP_T13SAL FOLHA ';
         END
       ELSE
         BEGIN
            camposum   = 'BDVALORINSSC13';
            strtpfolha   = 'c13';
            tabela       = 'VRHF_EMP_TC13SAL FOLHA ';
         END


  WSql = 'select sum(FOLHA.'||camposum||')';
  wsql = wsql || ' FROM '||:tabela;

  wsql = wsql || ' left outer join vw_colaboradores_ref_atual con on (FOLHA.bdcodemp = CON.bdcodemp and ';
  wsql = wsql ||                                                     ' FOLHA.bdcodcol = CON.bdcodcol)';
  wsql = wsql || ' where CON.bdcontrcol = '||:PRTIPOCADASTRO;--SEGURADOS COLABORADORES - SEGURADOS PROLABORISTAS
  wsql = wsql || ' AND FOLHA.bdcodemp = '||:premp;
  wsql = wsql || ' AND FOLHA.bdref'||strtpfolha||' = '||:prref;

  IF (:prfiltrocol IS NOT NULL) THEN
    wsql = wsql || ' and '||:prfiltrocol;

  FOR EXECUTE STATEMENT wsql
     INTO
        :BDVALOR
     DO
       BEGIN
         SUSPEND;
       END

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: VRHF_SPF_PROLABORISTAS */
ALTER PROCEDURE VRHF_SPF_PROLABORISTAS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE sql VARCHAR(500);
BEGIN

  SQL = 'SELECT * FROM VRHF_SPF_PROLAB_COLAB(';
  SQL = SQL || premp ||',';
  IF (:prfiltrocol = '') THEN
    SQL = SQL ||'null,';
  ELSE
    SQL = SQL || prfiltrocol ||',';

  SQL = SQL || prref ||',';
  SQL = SQL || prtipofolha ||',1)';

  FOR EXECUTE STATEMENT SQL
     INTO
        :BDVALOR
     DO
       BEGIN
         SUSPEND;
       END

END
^

/* Restore proc. body: VRHF_SPF_RATAPO */
ALTER PROCEDURE VRHF_SPF_RATAPO(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE TABELA VARCHAR(100);
DECLARE VARIABLE STRTPFOLHA VARCHAR(50);
DECLARE VARIABLE CAMPOSUM VARCHAR(50);
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WVALCALC NUMERIC(15,6);
DECLARE VARIABLE PERC NUMERIC(15,4);
DECLARE VARIABLE WSQL VARCHAR(5000);
BEGIN

  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  IF (:prtipofolha = 0) THEN
      BEGIN
        camposum   = 'BDBRATAPOFN + FOLHA.BDBRATAPOFEFN + FOLHA.BDBRATAPO13FN';
        strtpfolha   = 'FN';
        tabela       = 'VRHF_EMP_TFOLHANORMAL FOLHA ';

      END
   ELSE
     IF (:prtipofolha = 1) THEN
        BEGIN
          camposum   = 'BDBRATAPOFC + FOLHA.BDBRATAPOFEFC + FOLHA.BDBRATAPO13FC';
          strtpfolha   = 'FC';
          tabela       = 'VRHF_EMP_Tfolhacomp FOLHA ';
        END
     ELSE
       IF (:prtipofolha = 2) THEN
         BEGIN
            camposum = 'BDBRATAPO13';
            strtpfolha   = '13';
            tabela   = 'VRHF_EMP_T13SAL FOLHA ';
         END
       ELSE
         BEGIN
            camposum   = 'BDBRATAPOC13';
            strtpfolha   = 'c13';
            tabela       = 'VRHF_EMP_TC13SAL FOLHA ';
         END


  WSql = 'select FOLHA.BDCODCOL, sum(FOLHA.'||camposum||') BDVALOR';
  wsql = wsql || ' FROM '||:tabela;

  wsql = wsql || ' left outer join vw_colaboradores_ref_atual con on (FOLHA.bdcodemp = CON.bdcodemp and ';
  wsql = wsql ||                                                     ' FOLHA.bdcodcol = CON.bdcodcol)';
  wsql = wsql || ' where CON.bdcontrcol = 0';--SEGURADOS COLABORADORES .... APOSENTADORIA
  wsql = wsql || ' AND FOLHA.bdcodemp = '||:premp;
  wsql = wsql || ' AND FOLHA.bdref'||strtpfolha||' = '||:prref;

  IF ((:prfiltrocol IS NOT NULL) AND (:prfiltrocol <> ''))  THEN
    wsql = wsql || ' and '||:prfiltrocol;

  wsql = wsql || ' group by folha.bdcodcol ';

  wvalcalc = 0;

  FOR EXECUTE STATEMENT wsql
     INTO
        : wcodcol,
        : BDVALOR
     DO
       BEGIN

/*         select col.bdPERCRATCOL from VW_COLABORADORES_REF_ATUAL col
         where col.bdcodcol = :wcodcol and col.bdcodemp = :premp
         into
           :perc;
        if (:bdvalor is not null) then
          wvalcalc = wvalcalc + ((:bdvalor * :perc) /100);   */
       END


  BDVALOR = wvalcalc;

  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);

END
^

/* Restore proc. body: VRHF_SPF_SALFAM */
ALTER PROCEDURE VRHF_SPF_SALFAM(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE tabelaclasse VARCHAR(100);
DECLARE VARIABLE tabela VARCHAR(100);
DECLARE VARIABLE strtpfolha VARCHAR(10);
DECLARE VARIABLE wsql VARCHAR(5000);
BEGIN
  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  IF (:prtipofolha = 0) THEN
      BEGIN
        STRTPFOLHA   = 'FN';
        tabela       = 'VRHF_EMP_TFOLHANORMAL FOLHA ';
        tabelaclasse = 'vrhf_emp_tverbafn VFOLHA ';
      END
   ELSE
     IF (:prtipofolha = 1) THEN
        BEGIN
          STRTPFOLHA = 'FC';
          tabela       = 'VRHF_EMP_Tfolhacomp FOLHA ';
          tabelaclasse = 'vrhf_emp_tverbafc VFOLHA ';

        END
     ELSE
       IF (:prtipofolha = 2) THEN
         BEGIN
            STRTPFOLHA   = '13';
            tabela       = 'VRHF_EMP_T13SAL FOLHA ';
            tabelaclasse = 'vrhf_emp_tverba13 VFOLHA ';
         END
       ELSE
         BEGIN
            STRTPFOLHA   = 'c13';
            tabela       = 'VRHF_EMP_TC13SAL FOLHA ';
            tabelaclasse = 'vrhf_emp_tverbaC13 VFOLHA ';
         END


  WSql = 'select sum(FOLHA.BDSALFAM'||strtpfolha||')';
  wsql = wsql || ' FROM '||:tabela;
  wsql = wsql || ' left outer join '||:tabelaclasse||' on (FOLHA.bdcodemp = VFOLHA.bdcodemp and ';
  wsql = wsql ||                                          'FOLHA.bdcodcol = VFOLHA.bdcodcol and ';
  wsql = wsql ||                                          'FOLHA.bdref'||strtpfolha||'  = VFOLHA.bdref'||strtpfolha||')';

  wsql = wsql || ' left outer join vrh_base_tverbas ver on (VFOLHA.bdcodver = ver.bdcodver) ';
  wsql = wsql || 'where substring(ver.bdclaver from 1 for 5) = ''9.050''';
  wsql = wsql || ' and FOLHA.bdcodemp = '||:premp;
  wsql = wsql || ' AND FOLHA.bdref'||strtpfolha||' = '||:prref;

  IF (:prfiltrocol <> '') THEN
    wsql = wsql || ' and '||:prfiltrocol;

  FOR EXECUTE STATEMENT wsql
      INTO
        :BDVALOR
     DO
       BEGIN
         SUSPEND;
       END


  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: VRHF_SPF_SALMATERNIDADE */
ALTER PROCEDURE VRHF_SPF_SALMATERNIDADE(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE tabelaclasse VARCHAR(100);
DECLARE VARIABLE tabela VARCHAR(100);
DECLARE VARIABLE strtpfolha VARCHAR(10);
DECLARE VARIABLE verba VARCHAR(10);
DECLARE VARIABLE wsql VARCHAR(5000);
BEGIN
  IF (prref IS NOT NULL) THEN
    EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  IF (:prtipofolha = 0) THEN
      BEGIN
        STRTPFOLHA   = 'FN';
        tabela       = 'VRHF_EMP_TFOLHANORMAL FOLHA ';
        tabelaclasse = 'vrhf_emp_tverbafn VFOLHA ';
        verba        = '8.005';
      END
   ELSE
     IF (:prtipofolha = 1) THEN
        BEGIN
          STRTPFOLHA = 'FC';
          tabela       = 'VRHF_EMP_Tfolhacomp FOLHA ';
          tabelaclasse = 'vrhf_emp_tverbafc VFOLHA ';
          verba        = '8.005';
        END
     ELSE
       IF (:prtipofolha = 2) THEN
         BEGIN
            STRTPFOLHA   = '13';
            tabela       = 'VRHF_EMP_T13SAL FOLHA ';
            tabelaclasse = 'vrhf_emp_tverba13 VFOLHA ';
            verba        = '5.010';
         END
       ELSE
         BEGIN
            STRTPFOLHA   = 'c13';
            tabela       = 'VRHF_EMP_TC13SAL FOLHA ';
            tabelaclasse = 'vrhf_emp_tverbaC13 VFOLHA ';
            verba        = '6.010';
         END


  WSql = 'select sum(FOLHA.BDSALMATEMP'||strtpfolha||')';
  wsql = wsql || ' FROM '||:tabela;
  wsql = wsql || ' left outer join '||:tabelaclasse||' on (FOLHA.bdcodemp = VFOLHA.bdcodemp and ';
  wsql = wsql ||                                          'FOLHA.bdcodcol = VFOLHA.bdcodcol and ';
  wsql = wsql ||                                          'FOLHA.bdref'||strtpfolha||'  = VFOLHA.bdref'||strtpfolha||')';

  wsql = wsql || ' left outer join vrh_base_tverbas ver on (VFOLHA.bdcodver = ver.bdcodver) ';
  wsql = wsql || 'where substring(ver.bdclaver from 1 for 5) = '||verba;
  wsql = wsql || ' and FOLHA.bdcodemp = '||:premp;
  wsql = wsql || ' AND FOLHA.bdref'||strtpfolha||' = '||:prref;

  IF (:prfiltrocol <> '') THEN
    wsql = wsql || ' and '||:prfiltrocol;

  FOR EXECUTE STATEMENT wsql
      INTO
        :BDVALOR
     DO
       BEGIN
         SUSPEND;
       END


  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END
^

/* Restore proc. body: VRHF_SPF_SEGURADOS */
ALTER PROCEDURE VRHF_SPF_SEGURADOS(PREMP INTEGER,
PRFILTROCOL VARCHAR(15000),
PRREF INTEGER,
PRTIPOFOLHA INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE sql VARCHAR(5000);
BEGIN

  SQL = 'SELECT * FROM VRHF_SPF_PROLAB_COLAB(';
  SQL = SQL || premp ||',';
  IF (:prfiltrocol = '') THEN
    SQL = SQL ||'null,';
  ELSE
    SQL = SQL || prfiltrocol ||',';

  SQL = SQL || prref ||',';
  SQL = SQL || prtipofolha ||',0)';

  FOR EXECUTE STATEMENT SQL
     INTO
        :BDVALOR
     DO
       BEGIN
         SUSPEND;
       END

END
^

/* Restore proc. body: VRHF_SPF_VALNOTAFISCAL */
ALTER PROCEDURE VRHF_SPF_VALNOTAFISCAL(PREMP INTEGER,
PRREF INTEGER)
 RETURNS(BDVALOR NUMERIC(15,6))
 AS
DECLARE VARIABLE sql VARCHAR(500);
BEGIN

  SQL = 'select sum(NF.bdvaldescnf) BDVALOR';
  SQL = SQL || ' FROM vrhf_emp_tnotasfiscais NF ';
  SQL = SQL || ' WHERE NF.bdcodemp = '|| prEMP ;
  SQL = SQL || ' and NF.bdrefnf = '|| prREF ;

  FOR EXECUTE STATEMENT SQL
     INTO
        :BDVALOR
     DO
       BEGIN
         SUSPEND;
       END

END
^

/* Restore proc. body: VSUC_COPIA_CENTROS_PLANO */
ALTER PROCEDURE VSUC_COPIA_CENTROS_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
DECLARE VARIABLE wclanom VARCHAR(80);
DECLARE VARIABLE wfiltroger VARCHAR(20);
DECLARE VARIABLE wapecta VARCHAR(20);
DECLARE VARIABLE wnomcta VARCHAR(40);
DECLARE VARIABLE wtipcta SMALLINT;
DECLARE VARIABLE wctalon VARCHAR(40);
DECLARE VARIABLE wcnpjtom VARCHAR(18);
DECLARE VARIABLE wtipotom INTEGER;
DECLARE VARIABLE wtipofertom INTEGER;
DECLARE VARIABLE wsomsalfertom VARCHAR(5);
DECLARE VARIABLE wtipo13tom INTEGER;
DECLARE VARIABLE wsomsal13tom VARCHAR(5);
DECLARE VARIABLE wnometom VARCHAR(70);
DECLARE VARIABLE wcodtpcc INTEGER;
DECLARE VARIABLE wcodcid INTEGER;
DECLARE VARIABLE wlogrtom VARCHAR(15);
DECLARE VARIABLE wendtom VARCHAR(60);
DECLARE VARIABLE wbaitom VARCHAR(50);
DECLARE VARIABLE wceptom VARCHAR(9);
DECLARE VARIABLE wfonetom VARCHAR(15);
DECLARE VARIABLE wcompltom VARCHAR(60);
DECLARE VARIABLE wcodenqfed INTEGER;
DECLARE VARIABLE wcodcnae INTEGER;
DECLARE VARIABLE wcodfpasterc INTEGER;
DECLARE VARIABLE wemptom NUMERIC(15,6);
DECLARE VARIABLE wauttom NUMERIC(15,6);
DECLARE VARIABLE wcoltom NUMERIC(15,6);
DECLARE VARIABLE wtaxsertom NUMERIC(15,6);
DECLARE VARIABLE wdadcadtom INTEGER;
DECLARE VARIABLE wdadpertom INTEGER;
DECLARE VARIABLE wsimplesgpstom INTEGER;
DECLARE VARIABLE wfaptom NUMERIC(15,6);
DECLARE VARIABLE wcodlot INTEGER;
DECLARE VARIABLE wcnpjcont VARCHAR(18);
DECLARE VARIABLE wcnpjprop VARCHAR(18);
DECLARE VARIABLE wcodter INTEGER;
DECLARE VARIABLE wcodrecterc INTEGER;
DECLARE VARIABLE wanexo3 DM_BOOLEAN;
DECLARE VARIABLE wanexo4 DM_BOOLEAN;
DECLARE VARIABLE wanexo5 DM_BOOLEAN;
DECLARE VARIABLE wanexo6 DM_BOOLEAN;
DECLARE VARIABLE wcomercio DM_BOOLEAN;
DECLARE VARIABLE windustria DM_BOOLEAN;
DECLARE VARIABLE wservico DM_BOOLEAN;
DECLARE VARIABLE wdesonobra DM_BOOLEAN;
DECLARE VARIABLE wrat NUMERIC(18,6);
BEGIN
  DELETE FROM centros_tpcc WHERE bdCODCENTRO = :codigonovo;

  FOR SELECT bdCODTPCC,bdCTALON,bdTIPCTA,bdNOMCTA,bdAPECTA,bdFILTROGER,bdCLANOM, BDTIPO FROM centros_tpcc
             WHERE bdCODCENTRO = :codigocopiar INTO
             :wcodtpcc,:wctalon,:wtipcta,:wnomcta,:wapecta,:wfiltroger,:wclanom, :wtipotom DO
     BEGIN
        INSERT INTO centros_tpcc (bdCODCENTRO,bdCODTPCC,bdCTALON,bdTIPCTA,bdNOMCTA,bdAPECTA,bdFILTROGER,bdCLANOM, BDTIPO) VALUES
                                  (:codigonovo,:wcodtpcc,:wctalon,:wtipcta,:wnomcta,:wapecta,:wfiltroger,:wclanom,:wtipotom);
     END


  FOR SELECT bdCODTPCC,bdCNPJTOM,bdTIPOTOM,bdTIPOFERTOM,bdSOMSALFERTOM,bdTIPO13TOM,bdSOMSAL13TOM,bdNOMETOM,BDCODLOT,BDCNPJCONT,BDCNPJPROP,BDCODTER FROM VRH_BASE_TCUSTOM
             WHERE bdCODCENTRO = :codigocopiar INTO
             :wcodtpcc,:wcnpjtom,:wtipotom,:wtipofertom,:wsomsalfertom,:wtipo13tom,:wsomsal13tom,:wnometom,:wcodlot,:wcnpjcont,:wcnpjprop,:wcodter  DO
     BEGIN
        INSERT INTO VRH_BASE_TCUSTOM (bdCODCENTRO,bdCODTPCC,bdCNPJTOM,bdTIPOTOM,bdTIPOFERTOM,bdSOMSALFERTOM,bdTIPO13TOM,bdSOMSAL13TOM,bdNOMETOM,BDCODLOT,BDCNPJCONT,BDCNPJPROP,BDCODTER) VALUES
                                  (:codigonovo,:wcodtpcc,:wcnpjtom,:wtipotom,:wtipofertom,:wsomsalfertom,:wtipo13tom,:wsomsal13tom,:wnometom,:wcodlot,:wcnpjcont,:wcnpjprop,:wcodter);
     END

  FOR SELECT bdCODTPCC,bdREFCUSTO,bdCODSEFIPCUSTO FROM VRH_BASE_TCUSTOM_REF
             WHERE bdCODCENTRO = :codigocopiar INTO
             :wcodtpcc,:wtipotom,:wtipofertom  DO
     BEGIN
        INSERT INTO VRH_BASE_TCUSTOM_REF (bdCODCENTRO,bdCODTPCC,bdREFCUSTO,bdCODSEFIPCUSTO) VALUES
                                  (:codigonovo,:wcodtpcc,:wtipotom,:wtipofertom);
     END

  FOR SELECT bdCODTPCC,bdREFCUSTO,bdCODCID,bdLOGRTOM,bdENDTOM,bdNUMCTOM,bdBAITOM,bdCEPTOM,bdDDDTOM,bdFONETOM,bdCOMPLTOM FROM VRH_BASE_TCUSTOM_END
             WHERE bdCODCENTRO = :codigocopiar INTO
             :wcodtpcc,:wtipotom,:wcodcid,:wlogrtom,:wendtom,:wtipo13tom,:wbaitom,:wceptom,:wtipofertom,:wfonetom,:wcompltom  DO
     BEGIN
        INSERT INTO VRH_BASE_TCUSTOM_END (bdCODCENTRO,bdCODTPCC,bdREFCUSTO,bdCODCID,bdLOGRTOM,bdENDTOM,bdNUMCTOM,bdBAITOM,bdCEPTOM,bdDDDTOM,bdFONETOM,bdCOMPLTOM) VALUES
                                  (:codigonovo,:wcodtpcc,:wtipotom,:wcodcid,:wlogrtom,:wendtom,:wtipo13tom,:wbaitom,:wceptom,:wtipofertom,:wfonetom,:wcompltom);
     END

  FOR SELECT bdCODTPCC,bdREFCUSTO,bdCODREC,bdCODRECTRANSP,bdCODMEN,bdCODENQFED,bdCODCNAE,bdCODFPASTERC,bdEMPTOM,bdAUTTOM,bdCOLTOM,bdTAXSERTOM,
      bdDADCADTOM,bdDADPERTOM,BDFAPTOM,BDSIMPLESGPSTOM,BDCODRECTERC,BDANEXOIII,BDANEXOIV,BDANEXOV,
      BDCOMERCIO,BDINDUSTRIA,BDSERVICO,BDDESONOBRA,BDRAT FROM VRH_BASE_TCUSTOM_GPS
             WHERE bdCODCENTRO = :codigocopiar INTO
             :wcodtpcc,:wtipotom,:wcodcid,:wtipo13tom,:wtipofertom,:wcodenqfed,:wcodcnae,:wcodfpasterc,:wemptom,:wauttom,:wcoltom,:wtaxsertom,
             :wdadcadtom,:wdadpertom,:wfaptom,:wsimplesgpstom,:wcodrecterc,:wanexo3,:wanexo4,:wanexo5,
             :wcomercio,:windustria,:wservico,:wdesonobra,:wrat DO
     BEGIN
        INSERT INTO VRH_BASE_TCUSTOM_GPS (bdCODCENTRO,bdCODTPCC,bdREFCUSTO,bdCODREC,bdCODRECTRANSP,bdCODMEN,bdCODENQFED,bdCODCNAE,bdCODFPASTERC,bdEMPTOM,bdAUTTOM,bdCOLTOM,bdTAXSERTOM,
               bdDADCADTOM,bdDADPERTOM,BDFAPTOM,BDSIMPLESGPSTOM,BDCODRECTERC,BDANEXOIII,BDANEXOIV,BDANEXOV,
               BDCOMERCIO,BDINDUSTRIA,BDSERVICO,BDDESONOBRA,BDRAT) VALUES
                                  (:codigonovo,:wcodtpcc,:wtipotom,:wcodcid,:wtipo13tom,:wtipofertom,:wcodenqfed,:wcodcnae,:wcodfpasterc,:wemptom,:wauttom,:wcoltom,:wtaxsertom,
                                  :wdadcadtom,:wdadpertom,:wfaptom,:wsimplesgpstom,:wcodrecterc,:wanexo3,:wanexo4,:wanexo5,
                                  :wcomercio,:windustria,:wservico,:wdesonobra,:wrat);
     END
END
^

/* Restore proc. body: VSUC_COPIA_CONTAS_PLANO */
CREATE OR ALTER PROCEDURE VSUC_COPIA_CONTAS_PLANO (
    APELIDO_NOVO_PLANO VARCHAR(20),
    CODIGONOVO INTEGER,
    CODIGOCOPIAR INTEGER)
AS
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WAPECTA VARCHAR(20);
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WRELCTA INTEGER;
DECLARE VARIABLE WINVERTESINAL VARCHAR(5);
DECLARE VARIABLE WFILTROGER VARCHAR(20);
DECLARE VARIABLE WCLANOM VARCHAR(140);
DECLARE VARIABLE WFORMULA VARCHAR(200);
DECLARE VARIABLE WCONDICAO VARCHAR(100);
DECLARE VARIABLE WCONCILIAAUTOMATICA VARCHAR(5);
DECLARE VARIABLE WGRUPOCTA INTEGER;
DECLARE VARIABLE WCTACOMP VARCHAR(5);
DECLARE VARIABLE WDATACADCTA DATE;
DECLARE VARIABLE WDATAINATIVACTA DATE;
DECLARE VARIABLE WCTARATEIO VARCHAR(5);
DECLARE VARIABLE WCTAOBRIG VARCHAR(5);
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WPERTENCECONTA INTEGER;
DECLARE VARIABLE WNIVEL SMALLINT;
DECLARE VARIABLE WCONTAMEP VARCHAR(5);
DECLARE VARIABLE WCTAEMPREENDIMENTOSIMOB VARCHAR(5);
DECLARE VARIABLE WCTAUNIDADEIMOB VARCHAR(5);
DECLARE VARIABLE WCTACAIXAPR VARCHAR(5);
DECLARE VARIABLE WCTABANCOPR VARCHAR(5);
DECLARE VARIABLE WCTATRANSPR VARCHAR(5);
BEGIN
  DELETE FROM PLANOS_TPLA WHERE BDCODPLAPADRAO = :CodigoNovo;

  IF ((CodigoNovo IS NULL) OR (CodigoNovo = 0)) THEN
    SELECT BDCODPLAPADRAO FROM TPLANO_PADRAO WHERE BDAPELIDO = :Apelido_Novo_Plano INTO CodigoNovo;

  FOR SELECT BDCODTPLA, BDCTALON, BDNOMCTA, BDAPECTA, BDTIPCTA, BDRELCTA, BDINVERTESINAL, BDFILTROGER,
             BDCLANOM, BDFORMULA, BDCONDICAO, BDCONCILIAAUTOMATICA, BDGRUPOCTA, BDCTACOMP, BDDATACADCTA,
             BDDATAINATIVACTA, BDCTARATEIO, BDCTAOBRIG, BDPARTICIPANTE, BDPERTENCECONTA, BDNIVEL, BDCONTAMEP,
             BDCTAEMPREENDIMENTOSIMOB, BDCTAUNIDADEIMOB, BDCTACAIXAPR, BDCTABANCOPR, BDCTATRANSPR
  FROM PLANOS_TPLA
  WHERE BDCODPLAPADRAO = :CodigoCopiar INTO
        :wcodtpla, :wctalon, :wnomcta, :wapecta, :wtipcta, :wrelcta, :winvertesinal, :wfiltroger,
        :wclanom, :wformula, :wcondicao, :wconciliaautomatica, :wgrupocta, :wctacomp, :wdatacadcta,
        :wdatainativacta, :wctarateio, :wctaobrig, :wparticipante, :wpertenceconta, :wnivel, :wcontamep,
        :WCTAEMPREENDIMENTOSIMOB, :WCTAUNIDADEIMOB, :WCTACAIXAPR, :WCTABANCOPR, :WCTATRANSPR DO
    INSERT INTO PLANOS_TPLA (BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDNOMCTA, BDAPECTA, BDTIPCTA, BDRELCTA, BDINVERTESINAL, BDFILTROGER,
                             BDCLANOM, BDFORMULA, BDCONDICAO, BDCONCILIAAUTOMATICA, BDGRUPOCTA, BDCTACOMP, BDDATACADCTA,
                             BDDATAINATIVACTA, BDCTARATEIO, BDCTAOBRIG, BDPARTICIPANTE, BDPERTENCECONTA, BDNIVEL, BDCONTAMEP,
                             BDCTAEMPREENDIMENTOSIMOB, BDCTAUNIDADEIMOB, BDCTACAIXAPR, BDCTABANCOPR, BDCTATRANSPR)
                     VALUES (:codigonovo, :wcodtpla, :wctalon, :wnomcta, :wapecta, :wtipcta, :wrelcta, :winvertesinal, :wfiltroger,
                             :wclanom, :wformula, :wcondicao, :wconciliaautomatica, :wgrupocta, :wctacomp, :wdatacadcta,
                             :wdatainativacta, :wctarateio, :wctaobrig, :wparticipante, :wpertenceconta, :wnivel, :wcontamep,
                             :WCTAEMPREENDIMENTOSIMOB, :WCTAUNIDADEIMOB, :WCTACAIXAPR, :WCTABANCOPR, :WCTATRANSPR);
END
^

/* Restore proc. body: VSUC_COPIA_CONTAS_PLANO_FCONT */
ALTER PROCEDURE VSUC_COPIA_CONTAS_PLANO_FCONT(APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
DECLARE VARIABLE wcodpla_sped INTEGER;
DECLARE VARIABLE wcodtpla INTEGER;
DECLARE VARIABLE wcodtpla_sped INTEGER;
DECLARE VARIABLE wcodgrupoconta_sped INTEGER;
DECLARE VARIABLE wano INTEGER;
BEGIN
  DELETE FROM PLANOS_TPLA_FCONT WHERE PLANOS_TPLA_FCONT.bdcodplapadrao = :codigonovo;


  IF ((codigonovo IS NULL) OR (codigonovo = 0)) THEN
     BEGIN
        SELECT tplano_padrao_FCONT.bdcodplapadrao_fcont FROM tplano_padrao_FCONT WHERE tplano_padrao_FCONT.bdapelido = :apelido_novo_plano INTO codigonovo;
     END

  FOR SELECT planos_tpla_FCONT.bdcodpla_fcont, planos_tpla_FCONT.bdcodtpla, planos_tpla_FCONT.bdcodtpla_fcont, planos_tpla_FCONT.bdcodgrupoconta_fcont, planos_tpla_FCONT.bdano
             FROM planos_tpla_FCONT
             WHERE planos_tpla_FCONT.bdcodplapadrao = :codigocopiar
             INTO :wcodpla_sped, wcodtpla, :wcodtpla_sped, :wcodgrupoconta_sped, :wano DO
     BEGIN
        INSERT INTO planos_tpla_FCONT (bdcodplapadrao, bdcodpla_fcont, bdcodtpla, bdcodtpla_fcont, bdcodgrupoconta_fcont, bdano) VALUES
                                     (:codigonovo   ,:wcodpla_sped, :wcodtpla,  :wcodtpla_sped, :wcodgrupoconta_sped, :wano);
     END
END
^

/* Restore proc. body: VSUC_COPIA_CONTAS_PLANO_SPED */
ALTER PROCEDURE VSUC_COPIA_CONTAS_PLANO_SPED(APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
DECLARE VARIABLE WCODPLA_SPED INTEGER;
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WCODTPLA_SPED INTEGER;
DECLARE VARIABLE WCODGRUPOCONTA_SPED INTEGER;
DECLARE VARIABLE WANO INTEGER;
BEGIN
  DELETE FROM PLANOS_TPLA_SPED WHERE BDCODPLAPADRAO = :codigonovo;


  IF ((codigonovo IS NULL) OR (codigonovo = 0)) THEN
     BEGIN
        SELECT BDCODPLAPADRAO_SPED FROM tplano_padrao_sped WHERE BDAPELIDO = :apelido_novo_plano INTO codigonovo;
     END

  FOR SELECT BDCODPLA_SPED   , BDCODTPLA,  BDCODTPLA_SPED, BDCODGRUPOCONTA_SPED, BDANO FROM planos_tpla_sped  WHERE bdCODPLAPADRAO = : codigocopiar INTO
             :wcodpla_sped   , wcodtpla,  :wcodtpla_sped, :wcodgrupoconta_sped, :wano DO
     BEGIN
        INSERT INTO planos_tpla_sped (bdCODPLAPADRAO, BDCODPLA_SPED, BDCODTPLA, BDCODTPLA_SPED, BDCODGRUPOCONTA_SPED, BDANO) VALUES
                                     (:codigonovo   ,:wcodpla_sped, :wcodtpla,  :wcodtpla_sped, :wcodgrupoconta_sped, :wano);
     END
END
^

/* Restore proc. body: VSUC_COPIA_FORMULAS_PLANO */
CREATE OR ALTER PROCEDURE VSUC_COPIA_FORMULAS_PLANO (
    APELIDO_NOVO_PLANO VARCHAR(20),
    CODIGONOVO INTEGER,
    CODIGOCOPIAR INTEGER,
    DMPLCPC26 BIGINT = 0,
    PRRELATORIO INTEGER = 0,
    PRVINCULOTPLA INTEGER = 0)
AS
DECLARE VARIABLE WCODFOR INTEGER;
DECLARE VARIABLE WAPEFOR VARCHAR(20);
DECLARE VARIABLE WCLAFOR VARCHAR(40);
DECLARE VARIABLE WNOMFOR VARCHAR(100);
DECLARE VARIABLE WTIPFOR INTEGER;
DECLARE VARIABLE WSUBLFOR VARCHAR(5);
DECLARE VARIABLE WLINSEMVALFOR VARCHAR(5);
DECLARE VARIABLE WNEGFOR VARCHAR(5);
DECLARE VARIABLE WDESCFOR BLOB SUB_TYPE 1 SEGMENT SIZE 512;
DECLARE VARIABLE WCONDICAO VARCHAR(512);
DECLARE VARIABLE WGRUPOFOR INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WAPURAFOR DM_BOOLEAN;
DECLARE VARIABLE WDLPAECD integer;
BEGIN
  if (PRRELATORIO = 9) then
  begin
    DELETE FROM VSUC_BASE_FORMULA_TMENSAL WHERE bdCODPFOR = :codigonovo;

    IF ((codigonovo IS NULL) OR (codigonovo = 0)) THEN
      SELECT bdcodpfor FROM vsuc_base_tformula WHERE BDAPEPFOR = :apelido_novo_plano INTO codigonovo;

    if (EXISTS(select FIRST 1 BDCODPFOR FROM VSUC_BASE_FORMULA_TMENSAL WHERE bdcodpfor = :codigocopiar)) then
      insert into VSUC_BASE_FORMULA_TMENSAL (BDCODPFOR, BDQUADRO, BDCODFOR, BDNOMFOR, BDAPEFOR, BDCLAFOR, BDTIPFOR, BDGRUPOFOR, BDDESCFOR, BDCONDICAO, BDNEGFOR, BDSUBLFOR, BDLINSEMVALFOR,BDCODPLAPADRAO,BDCODTPLA)
      select :codigonovo AS bdcodpfor, BDQUADRO, BDCODFOR, BDNOMFOR, BDAPEFOR, BDCLAFOR, BDTIPFOR, BDGRUPOFOR, BDDESCFOR, BDCONDICAO, BDNEGFOR, BDSUBLFOR, BDLINSEMVALFOR,IIF(:prvinculotpla = 0, null, BDCODPLAPADRAO),IIF(:prvinculotpla = 0, null, BDCODTPLA) from VSUC_BASE_FORMULA_TMENSAL  WHERE bdcodpfor = :codigocopiar;
    ELSE
       insert into VSUC_BASE_FORMULA_TMENSAL
                           (BDCODPFOR, BDQUADRO, BDCODFOR, BDNOMFOR, BDAPEFOR, BDCLAFOR, BDTIPFOR, BDGRUPOFOR, BDDESCFOR, BDCONDICAO, BDNEGFOR, BDSUBLFOR, BDLINSEMVALFOR,BDCODPLAPADRAO,BDCODTPLA)
      select :codigonovo AS bdcodpfor,0 AS BDQUADRO,BDCODFOR,BDNOMFOR,BDAPEFOR,BDCLAFOR, BDTIPFOR, BDGRUPOFOR, BDDESCFOR, BDCONDICAO, BDNEGFOR, BDSUBLFOR, BDLINSEMVALFOR,IIF(:prvinculotpla = 0, null, BDCODPLAPADRAO),IIF(:prvinculotpla = 0, null, BDCODTPLA) from vsuc_base_tformula_tpfo  WHERE bdcodpfor = :codigocopiar;
  end
  else
  IF (dmplcpc26 = 0) THEN
  BEGIN
    DELETE FROM vsuc_base_tformula_tpfo WHERE bdCODPFOR = :codigonovo;
    IF ((codigonovo IS NULL) OR (codigonovo = 0)) THEN
       SELECT bdcodpfor FROM vsuc_base_tformula WHERE BDAPEPFOR = :apelido_novo_plano INTO codigonovo;

    FOR SELECT bdCODFOR,bdAPEFOR,bdCLAFOR,bdNOMFOR,bdTIPFOR,bdSUBLFOR,bdLINSEMVALFOR,bdNEGFOR,bdDESCFOR,BDCONDICAO,BDGRUPOFOR,BDCODPLAPADRAO,BDCODTPLA,BDAPURAFOR, BDDLPAECD
        FROM vsuc_base_tformula_tpfo
        WHERE bdCODPFOR = :codigocopiar
        INTO :wCODFOR,:wAPEFOR,:wCLAFOR,:wNOMFOR,:wTIPFOR,:wSUBLFOR,:wLINSEMVALFOR,:wNEGFOR,:wDESCFOR, :wCONDICAO, :wGRUPOFOR,:WCODPLAPADRAO,:WCODTPLA,:WAPURAFOR, :wdlpaecd DO
    BEGIN
      if (prvinculotpla = 0) then
        BEGIN
          wcodplapadrao = NULL;
          wcodtpla = NULL;
        END

      INSERT INTO vsuc_base_tformula_tpfo (bdCODPFOR,bdCODFOR,bdAPEFOR,bdCLAFOR,bdNOMFOR,bdTIPFOR,bdSUBLFOR,bdLINSEMVALFOR,bdNEGFOR,bdDESCFOR,BDCONDICAO,BDGRUPOFOR,BDCODPLAPADRAO,BDCODTPLA,BDAPURAFOR,BDDLPAECD)
      VALUES (:codigonovo,:wCODFOR,:wAPEFOR,:wCLAFOR,:wNOMFOR,:wTIPFOR, :wSUBLFOR,:wLINSEMVALFOR,:wNEGFOR,:wDESCFOR,:wCONDICAO,:wGRUPOFOR, :WCODPLAPADRAO, :WCODTPLA,:WAPURAFOR,:wdlpaecd);
    END
  END
  ELSE
  BEGIN
    DELETE FROM vsuc_base_formula_tlincol WHERE bdCODPFOR = :codigonovo;
    DELETE FROM vsuc_base_formula_tcolunas WHERE bdCODPFOR = :codigonovo;
    DELETE FROM vsuc_base_formula_tlinhas WHERE bdCODPFOR = :codigonovo;

    IF ((codigonovo IS NULL) OR (codigonovo = 0)) THEN
       SELECT bdcodpfor FROM vsuc_base_tformula WHERE BDAPEPFOR = :apelido_novo_plano INTO codigonovo;

    INSERT INTO vsuc_base_formula_tlinhas (bdcodpfor, bdcodlinha, bddescricao) SELECT :codigonovo AS bdcodpfor, lin.bdcodlinha, lin.bddescricao FROM vsuc_base_formula_tlinhas lin WHERE bdcodpfor = :codigocopiar;
    INSERT INTO vsuc_base_formula_tcolunas (bdcodpfor, bdcodcoluna, bdcodplapadrao, bdcodtpla, bdtipodesc, bddescricao) SELECT :codigonovo AS bdcodpfor, col.bdcodcoluna, col.bdcodplapadrao, col.bdcodtpla, col.bdtipodesc, col.bddescricao FROM vsuc_base_formula_tcolunas col WHERE bdcodpfor = :codigocopiar;
    INSERT INTO vsuc_base_formula_tlincol (bdcodpfor, bdcodcoluna, bdcodlinha, bddescfor) SELECT :codigonovo AS bdcodpfor, lc.bdcodcoluna, lc.bdcodlinha, lc.bddescfor FROM vsuc_base_formula_tlincol lc WHERE bdcodpfor = :codigocopiar;
  END
END^

--#alt:13583 - Criado procedimento para copia dos lançamentos da planilha. Ana - 01/03/2017
CREATE OR ALTER PROCEDURE VSUC_COPIA_PLANILHA_TLAN (
    CODIGONOVO INTEGER,
    CODIGOCOPIAR INTEGER)
AS
DECLARE VARIABLE WCHAVE INTEGER NOT NULL;
DECLARE VARIABLE WCODPLAPADRAO INTEGER NOT NULL;
DECLARE VARIABLE WDEBITO INTEGER;
DECLARE VARIABLE WCREDITO INTEGER;
DECLARE VARIABLE WCODHIST INTEGER NOT NULL;
DECLARE VARIABLE WCODTPHI INTEGER;
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WCOMPL VARCHAR(200) COLLATE WIN_PTBR;
DECLARE VARIABLE WLOTE VARCHAR(10) COLLATE WIN_PTBR;
DECLARE VARIABLE WDCTO VARCHAR(15);
DECLARE VARIABLE WCODTERCEIROD INTEGER;
DECLARE VARIABLE WCODTERCEIROC INTEGER;
DECLARE VARIABLE WFORMULA VARCHAR(200);
DECLARE VARIABLE WCONTABILIZACAO INTEGER;
DECLARE VARIABLE WTIPOFCONT INTEGER;
DECLARE VARIABLE WDLPA VARCHAR(5);
DECLARE VARIABLE WDMPL VARCHAR(5);
DECLARE VARIABLE WDOAR VARCHAR(5);
DECLARE VARIABLE WDFC VARCHAR(5);
DECLARE VARIABLE WDVA VARCHAR(5);
DECLARE VARIABLE WBE VARCHAR(5);
DECLARE VARIABLE WLALUR VARCHAR(5);
DECLARE VARIABLE WDESCRICAO VARCHAR(30000);
BEGIN
  IF ((CodigoNovo IS NULL) OR (CodigoNovo = 0)) THEN
    SELECT COALESCE((MAX(BDCODPLANILHA)+1),1) FROM VSUC_PLANILHAS_TLAN INTO CodigoNovo;

  FOR SELECT BDCHAVE, BDCODPLAPADRAO, BDDEBITO, BDCREDITO, BDCODHIST, BDCODTPHI, BDDATA, BDVALOR, BDCOMPL, BDLOTE,
             BDDCTO, BDCODTERCEIROD, BDCODTERCEIROC, BDFORMULA, BDCONTABILIZACAO, BDTIPOFCONT, BDDLPA, BDDMPL, BDDOAR,
             BDDFC, BDDVA, BDBE, BDLALUR, BDDESCRICAO
      FROM VSUC_PLANILHAS_TLAN
      WHERE BDCODPLANILHA = :CODIGOCOPIAR
      INTO :WCHAVE, :WCODPLAPADRAO, :WDEBITO, :WCREDITO, :WCODHIST, :WCODTPHI, :WDATA, :WVALOR, :WCOMPL, :WLOTE, :WDCTO,
           :WCODTERCEIROD, :WCODTERCEIROC, :WFORMULA, :WCONTABILIZACAO, :WTIPOFCONT, :WDLPA, :WDMPL, :WDOAR, :WDFC,
           :WDVA, :WBE, :WLALUR, :WDESCRICAO
  DO
    INSERT INTO VSUC_PLANILHAS_TLAN (BDCODPLANILHA, BDCHAVE, BDCODPLAPADRAO, BDDEBITO, BDCREDITO, BDCODHIST, BDCODTPHI,
                                     BDDATA, BDVALOR, BDCOMPL, BDLOTE, BDDCTO, BDCODTERCEIROD, BDCODTERCEIROC,
                                     BDFORMULA, BDCONTABILIZACAO, BDTIPOFCONT, BDDLPA, BDDMPL, BDDOAR, BDDFC, BDDVA,
                                     BDBE, BDLALUR, BDDESCRICAO)
    VALUES (:CodigoNovo, :WCHAVE, :WCODPLAPADRAO, :WDEBITO, :WCREDITO, :WCODHIST, :WCODTPHI, :WDATA, :WVALOR, :WCOMPL,
            :WLOTE, :WDCTO, :WCODTERCEIROD, :WCODTERCEIROC, :WFORMULA, :WCONTABILIZACAO, :WTIPOFCONT, :WDLPA, :WDMPL,
            :WDOAR, :WDFC, :WDVA, :WBE, :WLALUR, :WDESCRICAO);
END
^


/* Restore proc. body: VSUC_COPIA_HISTORICOS_PLANO */
ALTER PROCEDURE VSUC_COPIA_HISTORICOS_PLANO(APELIDO_NOVO_PLANO VARCHAR(20),
CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
DECLARE VARIABLE wpula VARCHAR(5);
DECLARE VARIABLE wapelido VARCHAR(20);
DECLARE VARIABLE wnome VARCHAR(100);
BEGIN
  DELETE FROM HIST_TPHI WHERE bdCODHIST = :codigonovo;

  IF ((codigonovo IS NULL) OR (codigonovo = 0))  THEN
     BEGIN
        SELECT bdcodhist FROM thist WHERE BDAPELIDO = :apelido_novo_plano INTO codigonovo;
     END

  FOR SELECT bdNOME,bdAPELIDO,bdPULACOMPL FROM HIST_TPHI
      WHERE bdCODHIST = :codigocopiar
      ORDER BY bdcodhist
      INTO :wnome, :wapelido, :wpula DO
     BEGIN
        INSERT INTO HIST_TPHI (bdCODHIST,bdNOME,bdAPELIDO,bdPULACOMPL) VALUES
                    (:codigonovo,:wnome,:wapelido,:wpula);
     END



END
^

/* Restore proc. body: VSUC_COPIA_HORARIO_PLANO */
ALTER PROCEDURE VSUC_COPIA_HORARIO_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
DECLARE VARIABLE WCODQH INTEGER;
DECLARE VARIABLE WDESCQH VARCHAR(999);
DECLARE VARIABLE WCODQHH INTEGER;
DECLARE VARIABLE WDIASEMQH INTEGER;
BEGIN
  IF ((codigonovo IS NULL) OR (codigonovo = 0)) THEN
     SELECT MAX(BDCODPQUA) FROM VRH_BASE_TPLANO_QUADRO INTO :codigonovo;

  DELETE FROM VRH_BASE_TQH WHERE BDCODPQUA = :codigonovo;

  FOR SELECT BDCODQH,BDDESCQH FROM VRH_BASE_TQH WHERE BDCODPQUA = :codigocopiar INTO :wcodqh, :wdescqh DO
    BEGIN
      INSERT INTO VRH_BASE_TQH (BDCODPQUA,BDCODQH,BDDESCQH) VALUES (:codigonovo,:wcodqh,:wdescqh);
    END

  FOR SELECT BDCODQH,BDCODQHH,BDDIASEMQH FROM VRH_BASE_TQH_DIAS WHERE BDCODPQUA = :codigocopiar INTO :wcodqh, :wcodqhh, :wdiasemqh DO
    BEGIN
      INSERT INTO VRH_BASE_TQH_DIAS (BDCODPQUA,BDCODQH,BDCODQHH,BDDIASEMQH) VALUES (:codigonovo,:wcodqh,:wcodqhh,:wdiasemqh);
    END


END
^

/* Restore proc. body: VSUC_COPIA_MOEDAS_PLANO */
ALTER PROCEDURE VSUC_COPIA_MOEDAS_PLANO(CODIGONOVO INTEGER,
CODIGOCOPIAR INTEGER)
 AS
DECLARE VARIABLE wvalor NUMERIC(15,6);
DECLARE VARIABLE wdata DATE;
BEGIN
  DELETE FROM moedas_tmoe WHERE bdCODMOEDAS = :codigonovo;

  IF ((codigonovo IS NULL) OR (codigonovo =0)) THEN
     BEGIN
        SELECT MAX(bdCODMOEDAS) FROM tmoedas INTO codigonovo;
     END

  FOR SELECT bdDATA,bdVALOR FROM moedas_tmoe WHERE bdCODMOEDAS = :codigocopiar
      INTO :wdata,:wvalor DO
     BEGIN
        INSERT INTO moedas_tmoe (bdCODMOEDAS,bdDATA,bdVALOR) VALUES
                                (:codigonovo,:wdata,:wvalor);
     END




END
^

/* Restore proc. body: VSUC_GETDEMONSTRATIVO */
create or alter procedure VSUC_GETDEMONSTRATIVO (
    PRCODEMP varchar(2048),
    PRIGNORAZERAMENTO integer,
    PRDETALHAFILIAL integer,
    PRSALDOANTERIOR integer,
    PRCONTABILIZACAO integer,
    PRDATAINI date,
    PRDATAFIN date,
    PREXPORTACAOECF integer,
    PRINDICE integer,
    PRCC varchar(8192),
    PRDETALHAR_CC integer,
    PRLANCNOTCC integer,
    PRDETALHAR_TERC integer,
    PRNIVELCC integer,
    PRDATEINIZER date = null,
    PRDATEFINZER date = null,
    PREMPRESAGRPECO integer = 0,
    PRGRPECO integer = 0,
    PRELIMINACOESK300K315 integer = 0)
returns (
    BDCODEMP integer,
    BDCODPLAPADRAO integer,
    BDCODTPLA integer,
    BDCTALON varchar(40),
    BDNOMCTA varchar(100),
    BDAPECTA varchar(20),
    BDTIPCTA integer,
    BDGRUPOCTA integer,
    BDRELCTA integer,
    BDSALANT numeric(15,2),
    BDSALDEB numeric(15,2),
    BDSALCRE numeric(15,2),
    BDMOVPER numeric(15,2),
    BDSALATU numeric(15,2),
    BDSALANT1 numeric(15,2),
    BDSALDEB1 numeric(15,2),
    BDSALCRE1 numeric(15,2),
    BDMOVPER1 numeric(15,2),
    BDSALATU1 numeric(15,2),
    BDSALANT2 numeric(15,2),
    BDSALDEB2 numeric(15,2),
    BDSALCRE2 numeric(15,2),
    BDMOVPER2 numeric(15,2),
    BDSALATU2 numeric(15,2),
    BDCODTPCC integer,
    BDNOMTPCC varchar(2048),
    BDCODTER integer)
as
declare variable WSQL varchar(30000);
declare variable WCODMATRIZ integer;
declare variable WDATAINI_ANT_ANT date;
declare variable WDATAFIN_ANT_ANT date;
declare variable WDATAINI_ANT date;
declare variable WDATAFIN_ANT date;
declare variable WDATAINI date;
declare variable WDATAFIN date;
declare variable WCOUNT integer;
declare variable WEMPRESAS varchar(20000);
declare variable WSTR varchar(10000);
declare variable WSQLDEB varchar(5000);
declare variable WSQLCRE varchar(5000);
declare variable WCTALON varchar(40);
declare variable WCODTPLA integer;
declare variable WDEB_ANT_ZER numeric(15,2);
declare variable WCRE_ANT_ZER numeric(15,2);
declare variable WDEB_ANT numeric(15,2);
declare variable WCRE_ANT numeric(15,2);
declare variable WDEB_2_ZER numeric(15,2);
declare variable WCRE_2_ZER numeric(15,2);
declare variable WDEB_2 numeric(15,2);
declare variable WCRE_2 numeric(15,2);
declare variable WDEB_2_ATU numeric(15,2);
declare variable WCRE_2_ATU numeric(15,2);
declare variable WDEB_1_ZER numeric(15,2);
declare variable WCRE_1_ZER numeric(15,2);
declare variable WDEB_1 numeric(15,2);
declare variable WCRE_1 numeric(15,2);
declare variable WDEB_1_ATU numeric(15,2);
declare variable WCRE_1_ATU numeric(15,2);
declare variable WDEB_ZER numeric(15,2);
declare variable WCRE_ZER numeric(15,2);
declare variable WDEB numeric(15,2);
declare variable WCRE numeric(15,2);
declare variable WDEB_ATU numeric(15,2);
declare variable WCRE_ATU numeric(15,2);
declare variable WZERAMENTO_ANT smallint;
declare variable WZERAMENTO_ANT_ANT smallint;
declare variable WCODPLAPADRAOREF smallint;
declare variable WCAMPOSCC varchar(100);
declare variable WANOECF smallint;
declare variable WSQLAUX varchar(30000);
declare variable WCENTROCUSTO integer;
declare variable WDEB_INI_ZER numeric(15,2);
declare variable WCRE_INI_ZER numeric(15,2);
BEGIN
--alt 85094 - 20/06/2018 - Carlos Machado - Adicionado tratamento de centro de custo.
  WCAMPOSCC = ' BDCODTPCC, BDCODCENTRO ';
  -- codigo da matriz
  wsql = 'select first 1 distinct bdcodmatriz from tempresas ';
  wsql = wsql||'where bdcodmatriz is not null ';
  wsql = wsql||'and bdcodemp in ('||prcodemp||')';
  EXECUTE STATEMENT wsql INTO :wcodmatriz;

  IF ((wcodmatriz IS NULL) OR (wcodmatriz = 0)) THEN
     BEGIN
       EXECUTE STATEMENT 'select first 1 bdcodemp from tempresas where bdcodemp in ('||prcodemp||')' INTO wcodmatriz;
     END

  -- filtro das empresas
  wempresas = 'and (';
  wstr = prcodemp||',';
  WHILE (wstr <> '') DO
    BEGIN
      wcount = POSITION(',', wstr);
      wempresas = wempresas||'(((TLAN.BDCODEMP = '||wcodmatriz||')';
      IF (wcodmatriz <> SUBSTRING(wstr FROM 1 FOR wcount-1)) THEN
         wempresas = wempresas||' or (TLAN.BDCODEMP = '||SUBSTRING(wstr FROM 1 FOR wcount-1)||'))) or ';
      ELSE
         wempresas = wempresas||')) or ';
      wstr = SUBSTRING(wstr FROM wcount+1 FOR CHAR_LENGTH(wstr));
    END
  wempresas = SUBSTRING(wempresas FROM 1 FOR CHAR_LENGTH(wempresas)-CHAR_LENGTH(' or '))||')';


  --exception ex_date;
  -- plano padrao
  --alt:11615 - 30/06/2015 - Carrega o codigo do plano referencial da empresa. Pedro
  wsql = 'select first 1 bdcodplapadrao, BDCODPLAPADRAOREF from VW_TEMPRESAS_REF where bdcodemp = '||wcodmatriz;
  EXECUTE STATEMENT wsql INTO :bdcodplapadrao, :wCodPlaPadraoRef;


  --Ruan Eliabe - 21/11/2023 - #167193 - Será preciso pegar o plano de CC uma vez
  wsql = 'select bdcodcentros from vw_empresas_ref_atual where bdcodemp = '||wcodmatriz;
  EXECUTE STATEMENT wsql INTO :WCENTROCUSTO;
  --#Alt.:12232 - 13/06/2015 - Carrega o ano da preparaso mais proximo com data informada
  wanoecf = 0;
  IF (prexportacaoecf = 1) THEN
    BEGIN
      wsql = 'select first 1 bdANO from PLANOS_TPLA_ECF ';
      wsql = wsql||'where (bdANO <= substring('''||prdataini||''' from 1 for 4)) and ';
      wsql = wsql||'(bdCODPLAPADRAOREF = '||wcodplapadraoref||') and ';
      wsql = wsql||'(bdCODPLAPADRAO = '||bdcodplapadrao||') order by bdANO desc';
      EXECUTE STATEMENT wsql INTO :wanoecf;
    END

  -- datas dos zeramentos
  wsql = 'select * from (select first 1 distinct bddatainizer, bddatafimzer from vsuc_empresas_tencexe ';
  wsql = wsql||'where bddatafimzer < '''||prdataini||''' ';
  wsql = wsql||'and bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'order by bddatafimzer desc)';
  EXECUTE STATEMENT wsql INTO :wdataini, wdatafin;


  if (wdataini is not null) then
    begin
      wsql = wsql||' union all ';
      wsql = wsql||'select * from (select first 1 distinct bddatainizer, bddatafimzer from vsuc_empresas_tencexe ';
      wsql = wsql||'where bddatafimzer < '''||prdataini||''' ';
      wsql = wsql||'and bdcodemp in ('||prcodemp||') ';
      wsql = wsql||'and bddatafimzer < '''||wdataini||''' ';
      wsql = wsql||'order by bddatafimzer desc)';
    end
  wcount = 1;
  wzeramento_ant = 0;
  wzeramento_ant_ant = 0;
  FOR EXECUTE STATEMENT wsql INTO :wdataini, wdatafin DO
     BEGIN
       IF (wcount = 1) THEN
          BEGIN
            --alt:13744 - 17/05/2016 - Se tiver selecionado o ano inteiro, estiver selecionando apenas um ano e tiver marcado
            --para mostrar o Saldo Anterior, entao o periodo anterior sera o ano anterior inteiro, independente do zeramento. Pedro
            IF ((prSaldoAnterior = 1) AND (EXTRACT(YEAR FROM prdataini) = EXTRACT(YEAR FROM prdatafin)) AND
                (EXTRACT(DAY FROM prdataini) = 1) AND (EXTRACT(MONTH FROM prdataini) = 1) AND
                (EXTRACT(DAY FROM prdatafin) = 31) AND (EXTRACT(MONTH FROM prdatafin) = 12)) THEN
              BEGIN
                wdataini_ant = addyear(prdataini, -1);
                wdatafin_ant = addyear(prdatafin, -1);
              END
            --alt:13744 - 13/05/2016 - Caso haja algum periodo entre o inicio do periodo e o ultimo zeramento,
            --pega esse periodo como periodo anterior, senao, utiliza o periodo do zeramento como periodo anterior. Pedro
            ELSE IF ((wdatafin +1) = prdataini) THEN
              BEGIN
                wdataini_ant = wdataini;
                wdatafin_ant = wdatafin;
              END
            ELSE
              BEGIN
                wdataini_ant = (wdatafin +1);
                wdatafin_ant = (prdataini -1);
              END
          END
       ELSE
         --alt:13744 - 17/05/2016 - Se tiver selecionado o ano inteiro, estiver selecionando apenas um ano e tiver marcado
         --para mostrar o Saldo Anterior, entao o periodo anterior sera o ano anterior inteiro, independente do zeramento. Pedro
         IF ((prSaldoAnterior = 1) AND (EXTRACT(YEAR FROM prdataini) = EXTRACT(YEAR FROM prdatafin)) AND
             (EXTRACT(DAY FROM prdataini) = 1) AND (EXTRACT(MONTH FROM prdataini) = 1) AND
             (EXTRACT(DAY FROM prdatafin) = 31) AND (EXTRACT(MONTH FROM prdatafin) = 12)) THEN
           BEGIN
             wdataini_ant_ant = addyear(prdataini, -2);
             wdatafin_ant_ant = addyear(prdatafin, -2);
           END
         ELSE --alt:14760 - 14/06/2016 - Correcao na estrutura. Pedro
           BEGIN
             wdataini_ant_ant = wdataini;
             wdatafin_ant_ant = wdatafin;
           END
       wcount = wcount + 1;
     END
  -- caso nao ha algumas das datas anteriores, pegar a data de inicio das atividades
  IF ((wdataini_ant IS NULL) OR (wdatafin_ant IS NULL) OR (wdataini_ant_ant IS NULL) OR (wdatafin_ant_ant IS NULL)) THEN
     BEGIN
       wsql = 'select min(bddatainiativemp) from tempresas ';
       wsql = wsql||'where bddatainiativemp is not null ';
       wsql = wsql||'and bdcodemp in ('||prcodemp||') ';
       EXECUTE STATEMENT wsql INTO :wdataini;
     END
  -- data do periodo anterior
  IF ((wdataini_ant IS NULL) OR (wdatafin_ant IS NULL)) THEN
     BEGIN
       wdataini_ant = wdataini;
       wdatafin_ant = prdataini -1;
     END
  -- data do periodo anterior ao anterior
  IF ((wdataini_ant_ant IS NULL) OR (wdatafin_ant_ant IS NULL)) THEN
     BEGIN
       wdatafin_ant_ant = wdataini_ant-1;
       IF (wdataini < wdatafin_ant_ant) THEN
          wdataini_ant_ant = wdataini;
       ELSE
          wdataini_ant_ant = wdatafin_ant_ant-1;
     END     
  ELSE
  if (wdatafin_ant_ant < wdataini_ant) then
    wdatafin_ant_ant = wdataini_ant-1;

  if ((PRDATEINIZER is not null) and (PRDATEFINZER is not null)) then
     begin
       wdataini_ant = PRDATEINIZER;
       wdatafin_ant = PRDATEFINZER;
       wdataini_ant_ant = PRDATEINIZER-1;
       wdatafin_ant_ant = PRDATEINIZER-1;
     end

  -- data atual
  wdataini = prdataini;
  wdatafin = prdatafin;

  -- limpar tabela temporaria
  EXECUTE STATEMENT 'delete from VSUC_EMPRESAS_DEMONSTRATIVO';

  -- calculo dos debitos e creditos nos periodos selecionados
  wsqldeb = '';
  -- saldo anterior a todos os periodos
  wsqldeb = wsqldeb||'sum(case when (bddata < '''||wdataini_ant_ant||''') then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebitoantzer, ';
  wsqldeb = wsqldeb||'sum(case when (bddata < '''||wdataini_ant_ant||''' and bdtipolan <> 10) then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebitoant, ';
  -- periodo anterior ao anterior
  wsqldeb = wsqldeb||'sum(case when (bddata between '''||wdataini_ant_ant||''' and '''||wdatafin_ant_ant||''') then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebito2zer, ';
  wsqldeb = wsqldeb||'sum(case when ((bddata between '''||wdataini_ant_ant||''' and '''||wdatafin_ant_ant||''') and (bdtipolan <> 10)) then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebito2, ';
  wsqldeb = wsqldeb||'sum(case when ((bddata < '''||wdataini_ant_ant||''') or ((bddata between '''||wdataini_ant_ant||''' and '''||wdatafin_ant_ant||''') and (bdtipolan <> 10))) then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebito2atu, ';
  -- periodo anterior
  wsqldeb = wsqldeb||'sum(case when (bddata between '''||wdataini_ant||''' and '''||wdatafin_ant||''') then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebito1zer, ';
  wsqldeb = wsqldeb||'sum(case when ((bddata between '''||wdataini_ant||''' and '''||wdatafin_ant||''') and (bdtipolan <> 10)) then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebito1, ';
  wsqldeb = wsqldeb||'sum(case when ((bddata < '''||wdataini_ant||''') or ((bddata between '''||wdataini_ant||''' and '''||wdatafin_ant||''') and (bdtipolan <> 10))) then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebito1atu, ';
  -- periodo atual
  wsqldeb = wsqldeb||'sum(case when (bddata between '''||wdataini||''' and '''||wdatafin||''') then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebitozer, ';

  wsqldeb = wsqldeb||'sum(case when ((bddata between '''||wdataini||''' and '''||wdatafin||''') and (bdtipolan <> 10)) then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebito, ';


  wsqldeb = wsqldeb||'sum(case when ((bddata < '''||wdataini||''') or ((bddata between '''||wdataini||''' and '''||wdatafin||''') and (bdtipolan <> 10))) then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebitoatu, ';
  --exception ex_date;

    if ((PRDATEINIZER is not null) and (PRDATEFINZER is not null)) then
    wsqldeb = wsqldeb||'sum(case when ((bddata between '''||wdataini||''' and '''||wdatafin||''') and (bdtipolan <> 10)) or (bddata between '''||(PRDATEFINZER+1)||''' and '''||(wdataini-1)||''') then coalesce(TLAN.bdvalor, 0) else 0 end) as bddebitoIniZer ';
  else
    wsqldeb = wsqldeb||'0 as bddebitoIniZer ';

  --alt:6178 - 11/11/2015 - Adicionada validacao, se tiver informado um codigo de indice, entao substituira onde possui o campo "BDVALOR" pelo proprio campo mais o valor do indice na data do lancamento. Pedro
  IF (prIndice > 0) THEN
    wsqldeb = REPLACE(wsqldeb, 'TLAN.bdvalor', 'TLAN.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prIndice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),'||
                                                             '(select first 1 BDVALIND from TINDVAL where BDCODIND = '||prIndice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))');

  wsqlcre = '';
  -- saldo anterior a todos os periodos
  wsqlcre = wsqlcre||'       0 as bdcreditoantzer, ';
  wsqlcre = wsqlcre||'       0 as bdcreditoant, ';
  -- periodo anterior ao anterior
  wsqlcre = wsqlcre||'       0 as bdcredito2zer, ';
  wsqlcre = wsqlcre||'       0 as bdcredito2, ';
  wsqlcre = wsqlcre||'       0 as bdcredito2atu, ';
  -- periodo anterior
  wsqlcre = wsqlcre||'       0 as bdcredito1zer, ';
  wsqlcre = wsqlcre||'       0 as bdcredito1, ';
  wsqlcre = wsqlcre||'       0 as bdcredito1atu, ';
  -- periodo atual
  wsqlcre = wsqlcre||'       0 as bdcreditozer, ';
  wsqlcre = wsqlcre||'       0 as bdcredito, ';
  wsqlcre = wsqlcre||'       0 as bdcreditoatu, ';  
  wsqlcre = wsqlcre||'       0 as bdcreditoIniZer ';


  -- povoando tabela temporaria
  wsql = 'insert into VSUC_EMPRESAS_DEMONSTRATIVO (';
  wsql = wsql||'bdcodemp, bdcodtpla, BDCODTERCEIRO, ';
  wsql = wsql||wcamposcc||', ';
  wsql = wsql||'bddebitoantzer, bdcreditoantzer, ';
  wsql = wsql||'bddebitoant,    bdcreditoant, ';
  wsql = wsql||'bddebito2zer,   bdcredito2zer, ';
  wsql = wsql||'bddebito2,      bdcredito2, ';
  wsql = wsql||'bddebito2atu,   bdcredito2atu, ';
  wsql = wsql||'bddebito1zer,   bdcredito1zer, ';
  wsql = wsql||'bddebito1,      bdcredito1, ';
  wsql = wsql||'bddebito1atu,   bdcredito1atu, ';
  wsql = wsql||'bddebitozer,    bdcreditozer, ';
  wsql = wsql||'bddebito,       bdcredito, ';
  wsql = wsql||'bddebitoatu,    bdcreditoatu, ';
  wsql = wsql||'bddebitoIniZer, bdcreditoIniZer) ';

  if (prnivelcc > 0) then
    begin
      wsql = wsql||'select SAL.BDCODEMP, SAL.BDCODTPLA, SAL.TERCEIRO, coalesce(PAI.BDCODTPCC,0) AS BDCODTPCC, coalesce(PAI.BDCODCENTRO,0) AS BDCODCENTRO, sal.BDDEBITOANTZER, sal.BDCREDITOANTZER, SAL.BDDEBITOANT, SAL.BDCREDITOANT, SAL.BDDEBITO2ZER,SAL.BDCREDITO2ZER,SAL.BDDEBITO2, SAL.BDCREDITO2, SAL.BDDEBITO2ATU,';
      wsql = wsql||'SAL.BDCREDITO2ATU, SAL.BDDEBITO1ZER,SAL.BDCREDITO1ZER, SAL.BDDEBITO1, SAL.BDCREDITO1,SAL.BDDEBITO1ATU, SAL.BDCREDITO1ATU,SAL.BDDEBITOZER,';
      wsql = wsql||'SAL.BDCREDITOZER, SAL.BDDEBITO, SAL.BDCREDITO,SAL.BDDEBITOATU, SAL.BDCREDITOATU, SAL.bddebitoIniZer , SAL.bdcreditoIniZer from (';
  wsql = wsql||'select bdcodemp, bdcodtpla, ';
    end
  else
    wsql = wsql||'select bdcodemp, bdcodtpla, ';
  if (prdetalhar_terc = 1) then
    wsql = wsql||'COALESCE(BDCODTERCEIRO,0), ';
  ELSE
    wsql = wsql||'0 AS TERCEIRO, ';

  IF ((PRDETALHAR_CC != 1)) THEN
     wsql = wsql||'0, 0, ';
  ELSE
     wsql = wsql||' COALESCE(BDCODTPCC,0) AS BDCODTPCC, COALESCE(BDCODCENTRO,0) AS bdcodcentro, ';
  wsql = wsql||'       sum(bddebitoantzer) as bddebitoantzer, ';
  wsql = wsql||'       sum(bdcreditoantzer) as bdcreditoantzer, ';
  wsql = wsql||'       sum(bddebitoant) as bddebitoant, ';
  wsql = wsql||'       sum(bdcreditoant) as bdcreditoant, ';
  wsql = wsql||'       sum(bddebito2zer) as bddebito2zer, ';
  wsql = wsql||'       sum(bdcredito2zer) as bdcredito2zer, ';
  wsql = wsql||'       sum(bddebito2) as bddebito2, ';
  wsql = wsql||'       sum(bdcredito2) as bdcredito2, ';
  wsql = wsql||'       sum(bddebito2atu) as bddebito2atu, ';
  wsql = wsql||'       sum(bdcredito2atu) as bdcredito2atu, ';
  wsql = wsql||'       sum(bddebito1zer) as bddebito1zer, ';
  wsql = wsql||'       sum(bdcredito1zer) as bdcredito1zer, ';
  wsql = wsql||'       sum(bddebito1) as bddebito1, ';
  wsql = wsql||'       sum(bdcredito1) as bdcredito1, ';
  wsql = wsql||'       sum(bddebito1atu) as bddebito1atu, ';
  wsql = wsql||'       sum(bdcredito1atu) as bdcredito1atu, ';
  wsql = wsql||'       sum(bddebitozer) as bddebitozer, ';
  wsql = wsql||'       sum(bdcreditozer) as bdcreditozer, ';
  wsql = wsql||'       sum(bddebito) as bddebito, ';
  wsql = wsql||'       sum(bdcredito) as bdcredito, ';
  wsql = wsql||'       sum(bddebitoatu) as bddebitoatu, ';
  wsql = wsql||'       sum(bdcreditoatu) as bdcreditoatu, ';
  wsql = wsql||'       sum(bddebitoIniZer) as bddebitoIniZer, ';
  wsql = wsql||'       sum(bdcreditoIniZer) as bdcreditoIniZer ';
  wsql = wsql||'from (';
  IF (prdetalhar_cc = 1) THEN
     wsql = wsql||'select '||wcamposcc||', TLAN.bdcodemp, bddebito as bdcodtpla, ';
  ELSE
     wsql = wsql||'select TLAN.bdcodemp, bddebito as bdcodtpla, ';
  if (prdetalhar_terc = 1) then
    wsql = wsql||'BDCODTERCEIROD as BDCODTERCEIRO, ';
  wsql = wsql||wsqldeb||','||wsqlcre;
  --#alt:148865 - Machado - 13/04/2020 - Relatório DRE - Lentidão na emissão
  wsql = wsql||'from (select TLAN.BDCODEMP, BDDATA, BDDEBITO, BDTIPOLAN ';
  if (prdetalhar_terc = 1) then
    wsql = wsql||', BDCODTERCEIROD ';
  IF (prdetalhar_cc = 1) THEN
    wsql = wsql||', '||wcamposcc||', SUM(iif(BDCODTPCC is null, tlan.bdvalor,tlcc.bdvalor)) AS BDVALOR ';
  ELSE
    wsql = wsql||', SUM(TLAN.BDVALOR) AS BDVALOR ';
  wsql = wsql||'from vsuc_empresas_tlan tlan ';
  IF (prdetalhar_cc = 1) THEN
    BEGIN
      if ((prlancnotcc = 1) or (prdetalhar_cc = 0)) then
         wsql = wsql||'LEFT OUTER';
      ELSE
         wsql = wsql||'INNER';
      wsql = wsql||' join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and BDDEBCRE = 0)';
    END
  wsql = wsql||'where (bddata <= '''||wdatafin||''') ';
  wsql = wsql||'and (bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  wsql = wsql||'and (bddebito is not null) ';
  wsql = wsql||'#empresas#';
  --#alt:148865 - Machado - 13/04/2020 - Relatório DRE - Lentidão na emissão
  wsql = wsql||'GROUP BY BDCODEMP, BDDATA, bddebito, BDTIPOLAN';
  IF (prdetalhar_cc = 1) THEN
    wsql = wsql||', '||wcamposcc;
  if (prdetalhar_terc = 1) then
    wsql = wsql||', BDCODTERCEIROD ';

  if (:PRELIMINACOESK300K315 = 1) then
  begin
    WSQL = WSQL || ' union all';
    WSQL = WSQL || ' select K300.BDCODEMPGRPECO, K310.BDDATAREF, K300.BDCODTPLA, 1 as BDTIPOLAN,';
    if (prdetalhar_terc = 1) then
      WSQL = WSQL || ' K300.BDCODTERCEIRO,';
    WSQL = WSQL || ' ELIK310.BDVLRELIMK315 as BDVALOR';
    WSQL = WSQL || '        from VSUC_EMP_TLAN_SPED_K315 K315';
    WSQL = WSQL || '        left join VSUC_EMP_TLAN_SPED_K300 K300 on (K300.BDCODK300 = K315.BDCODK300 and';
    WSQL = WSQL || '              K300.BDCODEMPGRPECO = K315.BDCODEMPGRPECO and';
    WSQL = WSQL || '              K300.BDCODGRPECO = K315.BDCODGRPECO)';
    WSQL = WSQL || '        inner join VSUC_EMP_TLAN_SPED_K310 K310 on (K310.BDCODK300 = K315.BDCODK300 and';
    WSQL = WSQL || '              K310.BDCODEMPGRPECO = K315.BDCODEMPGRPECO and';
    WSQL = WSQL || '              K310.BDCODGRPECO = K315.BDCODGRPECO and';
    WSQL = WSQL || '              K310.BDCODK310 = K315.BDCODK310)';
    WSQL = WSQL || '        left join VSUC_EMP_TLAN_SPED_K315 ELIK310 on (K310.BDCODK300 = ELIK310.BDCODK300 and';
    WSQL = WSQL || '              K310.BDCODEMPGRPECO = ELIK310.BDCODEMPGRPECO and';
    WSQL = WSQL || '              K310.BDCODGRPECO = ELIK310.BDCODGRPECO and';
    WSQL = WSQL || '              K310.BDCODK310 = ELIK310.BDCODK310)';
    WSQL = WSQL || '        where K300.BDCODEMPGRPECO = '||prempresagrpeco||' and';
    WSQL = WSQL || '              K300.BDCODGRPECO = '||prgrpeco||' and';
    WSQL = WSQL || '              K300.BDTIPCONT = 0 and';
    WSQL = WSQL || '              K315.BDCODTPLA is not null and';
    WSQL = WSQL || '              ELIK310.BDSITELIMK315 = 0 and';
    WSQL = WSQL || '              K310.BDDATAREF <= '''||wdatafin||'''';
    WSQL = WSQL || '        group by K300.BDCODEMPGRPECO, K310.BDDATAREF, BDCODTPLA,';
    if (prdetalhar_terc = 1) then
      WSQL = WSQL || 'BDCODTERCEIRO,';
    WSQL = WSQL || 'BDVALOR';
  end

  wsql = wsql||') tlan ';
  wsql = wsql||'Group By TLAN.BDCODEMP, bdcodtpla ';
  IF (prdetalhar_cc = 1) THEN
    wsql = wsql||', '||wcamposcc||' '; 
  if (prdetalhar_terc = 1) then
    wsql = wsql||', BDCODTERCEIROD ';
  wsql = wsql||'union ';
  IF (prdetalhar_cc = 1) THEN
     wsql = wsql||'select '||wcamposcc||', TLAN.bdcodemp, bdcredito as bdcodtpla, ';
  ELSE
     wsql = wsql||'select TLAN.bdcodemp, bdcredito as bdcodtpla, ';
  if (prdetalhar_terc = 1) then
    wsql = wsql||'BDCODTERCEIROC as BDCODTERCEIRO, ';
  wsql = wsql||wsqlcre||','||wsqldeb;
  --#alt:148865 - Machado - 13/04/2020 - Relatório DRE - Lentidão na emissão
  wsql = wsql||'from (select TLAN.BDCODEMP, BDDATA, BDCREDITO, BDTIPOLAN ';
  if (prdetalhar_terc = 1) then
    wsql = wsql||', BDCODTERCEIROC ';
  IF (prdetalhar_cc = 1) THEN
    wsql = wsql||', BDCODCENTRO, BDCODTPCC, SUM(iif(BDCODTPCC is null, tlan.bdvalor,tlcc.bdvalor)) AS BDVALOR ';
  ELSE
    wsql = wsql||', SUM(TLAN.BDVALOR) AS BDVALOR ';

  wsql = wsql||'from vsuc_empresas_tlan tlan ';
  IF (prdetalhar_cc = 1) THEN
    BEGIN
      if ((prlancnotcc = 1) or (prdetalhar_cc = 0)) then
         wsql = wsql||'LEFT OUTER';
      ELSE
         wsql = wsql||'INNER';
      wsql = wsql||' join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and BDDEBCRE = 1) ';
    END
  wsql = wsql||'where (bddata <= '''||wdatafin||''') ';
  wsql = wsql||'and (bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  wsql = wsql||'and (BDCREDITO is not null) ';
  wsql = wsql||'#empresas#';
  --#alt:148865 - Machado - 13/04/2020 - Relatório DRE - Lentidão na emissão
  wsql = wsql||'GROUP BY BDCODEMP, BDDATA, BDCREDITO, BDTIPOLAN';
  if (prdetalhar_terc = 1) then
    wsql = wsql||', BDCODTERCEIROC ';
  IF (prdetalhar_cc = 1) THEN
    wsql = wsql||', BDCODCENTRO, BDCODTPCC ';

  if (:PRELIMINACOESK300K315 = 1) then
  begin
    WSQL = WSQL || ' union all';
    WSQL = WSQL || ' select K300.BDCODEMPGRPECO, K310.BDDATAREF, K300.BDCODTPLA, 1 as BDTIPOLAN,';
    if (prdetalhar_terc = 1) then
      WSQL = WSQL || ' K300.BDCODTERCEIRO,';
    WSQL = WSQL || ' ELIK310.BDVLRELIMK315 as BDVALOR';
    WSQL = WSQL || '        from VSUC_EMP_TLAN_SPED_K315 K315';
    WSQL = WSQL || '        left join VSUC_EMP_TLAN_SPED_K300 K300 on (K300.BDCODK300 = K315.BDCODK300 and';
    WSQL = WSQL || '              K300.BDCODEMPGRPECO = K315.BDCODEMPGRPECO and';
    WSQL = WSQL || '              K300.BDCODGRPECO = K315.BDCODGRPECO)';
    WSQL = WSQL || '        inner join VSUC_EMP_TLAN_SPED_K310 K310 on (K310.BDCODK300 = K315.BDCODK300 and';
    WSQL = WSQL || '              K310.BDCODEMPGRPECO = K315.BDCODEMPGRPECO and';
    WSQL = WSQL || '              K310.BDCODGRPECO = K315.BDCODGRPECO and';
    WSQL = WSQL || '              K310.BDCODK310 = K315.BDCODK310)';
    WSQL = WSQL || '        left join VSUC_EMP_TLAN_SPED_K315 ELIK310 on (K310.BDCODK300 = ELIK310.BDCODK300 and';
    WSQL = WSQL || '              K310.BDCODEMPGRPECO = ELIK310.BDCODEMPGRPECO and';
    WSQL = WSQL || '              K310.BDCODGRPECO = ELIK310.BDCODGRPECO and';
    WSQL = WSQL || '              K310.BDCODK310 = ELIK310.BDCODK310)';
    WSQL = WSQL || '        where K300.BDCODEMPGRPECO = '||prempresagrpeco||' and';
    WSQL = WSQL || '              K300.BDCODGRPECO = '||prgrpeco||' and';
    WSQL = WSQL || '              K300.BDTIPCONT = 0 and';
    WSQL = WSQL || '              K315.BDCODTPLA is not null and';
    WSQL = WSQL || '              ELIK310.BDSITELIMK315 = 1 and';
    WSQL = WSQL || '              K310.BDDATAREF <= '''||wdatafin||'''';
    WSQL = WSQL || '        group by K300.BDCODEMPGRPECO, K310.BDDATAREF, BDCODTPLA,';
    if (prdetalhar_terc = 1) then
      WSQL = WSQL || 'BDCODTERCEIRO,';
    WSQL = WSQL || 'BDVALOR';
  end

  wsql = wsql||') tlan ';
  wsql = wsql||'Group By bdcodemp, BDCODTPLA ';
  IF (prdetalhar_cc = 1) THEN
    wsql = wsql||', '||wcamposcc||' ';
  if (prdetalhar_terc = 1) then
    wsql = wsql||', BDCODTERCEIROC ';
  wsql = wsql||') as tlan ';
  IF (PRDETALHAR_CC = 1) THEN
    BEGIN
      IF (NOT ((prcc IS NULL) OR (prcc = ''))) THEN
        BEGIN
          wsql = wsql||' where bdcodtpcc in ('||prcc||') ';
          if (prlancnotcc = 1) THEN
             wsql = wsql||' or bdcodtpcc is null ';
        END
      ELSE IF(prlancnotcc = 0) THEN
         wsql = wsql||' where bdcodtpcc is not null ';
      wsql = wsql||' group by bdcodemp, bdcodtpla, bdcodtpcc, BDCODCENTRO ';
    END
  ELSE
     wsql = wsql||'group by bdcodemp, bdcodtpla ';
  if (prdetalhar_terc = 1) then
    wsql = wsql||', BDCODTERCEIRO ';
  wsql = wsql||'order by bdcodemp, bdcodtpla ';
  if (prnivelcc > 0) then
    begin
      wsql = wsql||' ) SAL ';
      WSQL = WSQL||' LEFT OUTER JOIN centros_tpcc TPCC ON (TPCC.bdcodcentro = '||wcentrocusto||' and tpcc.BDCODTPCC = SAL.BDCODTPCC) ';
      WSQL = WSQL||' LEFT OUTER JOIN centros_tpcc PAI  ON (PAI.bdcodcentro = '||wcentrocusto||' and PAI.bdctalon = (select BDCLASSIFICACAO FROM sp_get_classificacao_nivel(tpcc.bdctalon, '||prnivelcc||'))) ';
    end


  EXECUTE STATEMENT replace(wsql, '#empresas#', wempresas);

  -- inserir contas titulos e totalizando-as
  FOR SELECT bdcodtpla, bdctalon FROM planos_tpla
      WHERE bdcodplapadrao = :bdcodplapadrao
      AND bdtipcta IN (0, 2) --alt:14249 - 06/05/2016 - nao estava totalizando as contas consolidadoras. Pedro
      INTO :wcodtpla, :wctalon DO
      BEGIN
        wsql = 'insert into VSUC_EMPRESAS_DEMONSTRATIVO (bdcodemp, bdcodtpla, ';   
        wsql = wsql||        wcamposcc||', ';
        wsql = wsql||'       bddebitoantzer, bdcreditoantzer, ';
        wsql = wsql||'       bddebitoant,    bdcreditoant, ';
        wsql = wsql||'       bddebito2zer,   bdcredito2zer, ';
        wsql = wsql||'       bddebito2,      bdcredito2, ';
        wsql = wsql||'       bddebito2atu,   bdcredito2atu, ';
        wsql = wsql||'       bddebito1zer,   bdcredito1zer, ';
        wsql = wsql||'       bddebito1,      bdcredito1, ';
        wsql = wsql||'       bddebito1atu,   bdcredito1atu, ';
        wsql = wsql||'       bddebitozer,    bdcreditozer, ';
        wsql = wsql||'       bddebito,       bdcredito, ';
        wsql = wsql||'       bddebitoatu,    bdcreditoatu, ';
        wsql = wsql||'       bddebitoIniZer, bdcreditoIniZer) ';
        wsql = wsql||'select temp.bdcodemp, '||wcodtpla||' as bdcodtpla, ';  
        wsql = wsql||'       COALESCE(BDCODTPCC,0), COALESCE(BDCODCENTRO,0), ';
        wsql = wsql||'       sum(bddebitoantzer) as bddebitoantzer, ';
        wsql = wsql||'       sum(bdcreditoantzer) as bdcreditoantzer, ';
        wsql = wsql||'       sum(bddebitoant) as bddebitoant, ';
        wsql = wsql||'       sum(bdcreditoant) as bdcreditoant, ';
        wsql = wsql||'       sum(bddebito2zer) as bddebito2zer, ';
        wsql = wsql||'       sum(bdcredito2zer) as bdcredito2zer, ';
        wsql = wsql||'       sum(bddebito2) as bddebito2, ';
        wsql = wsql||'       sum(bdcredito2) as bdcredito2, ';
        wsql = wsql||'       sum(bddebito2atu) as bddebito2atu, ';
        wsql = wsql||'       sum(bdcredito2atu) as bdcredito2atu, ';
        wsql = wsql||'       sum(bddebito1zer) as bddebito1zer, ';
        wsql = wsql||'       sum(bdcredito1zer) as bdcredito1zer, ';
        wsql = wsql||'       sum(bddebito1) as bddebito1, ';
        wsql = wsql||'       sum(bdcredito1) as bdcredito1, ';
        wsql = wsql||'       sum(bddebito1atu) as bddebito1atu, ';
        wsql = wsql||'       sum(bdcredito1atu) as bdcredito1atu, ';
        wsql = wsql||'       sum(bddebitozer) as bddebitozer, ';
        wsql = wsql||'       sum(bdcreditozer) as bdcreditozer, ';
        wsql = wsql||'       sum(bddebito) as bddebito, ';
        wsql = wsql||'       sum(bdcredito) as bdcredito, ';
        wsql = wsql||'       sum(bddebitoatu) as bddebitoatu, ';
        wsql = wsql||'       sum(bdcreditoatu) as bdcreditoatu, ';
        wsql = wsql||'       sum(bddebitoIniZer) as bddebitoIniZer, ';
        wsql = wsql||'       sum(bdcreditoIniZer) as bdcreditoIniZer ';
        wsql = wsql||'from vsuc_empresas_demonstrativo temp ';
        wsql = wsql||'inner join planos_tpla tpla on (tpla.bdcodplapadrao = '||bdcodplapadrao||' and tpla.bdcodtpla = temp.bdcodtpla) ';
        wsql = wsql||'where substring(tpla.bdctalon from 1 for '||CHAR_LENGTH(wctalon)||') = '''||wctalon||''' ';
        wsql = wsql||'and tpla.bdtipcta = 1 ';
        --wsql = wsql||wempresas;
        wsql = wsql||' group by bdcodemp, '||wcamposcc;
        EXECUTE STATEMENT wsql;
      END

  -- retorno do resultado do demonstrativo
  wsql = 'select ';
  IF (prdetalhafilial = 1) THEN
    wsql = wsql||'demo.BDCODEMP';
  ELSE
    wsql = wsql||wcodmatriz||' as BDCODEMP';
  wsql = wsql||', tpla.BDCODTPLA, tpla.bdctalon, '||IIF(prdetalhar_terc = 1, 'coalesce(ter.BDNOMETER, tpla.bdnomcta)', 'tpla.bdnomcta');
  wsql = wsql||', tpla.bdapecta, tpla.bdtipcta, tpla.bdgrupocta, tpla.bdrelcta, ';
  if (prdetalhar_terc = 1) then
    wsql = wsql||'ter.BDCODTER, ';
  ELSE
    wsql = wsql||' NULL AS BDCODTER, ';
  --alt:11615 - 30/06/2015 - Carrega o grupo referencial se for uma exportacao do Sped ECF. Pedro
  IF (prExportacaoECF = 1) THEN
   wsql = wsql||' coalesce(ecf.BDCODGRUPOCTA, 0) as BDCODGRUPOCTA,';
  ELSE
   wsql = wsql||'0 as BDCODGRUPOCTA,';
  --alt:11615 - Fim
  wsql = wsql||'             sum(BDDEBITOANTZER), sum(BDCREDITOANTZER), sum(BDDEBITOANT), sum(BDCREDITOANT), ';
  wsql = wsql||'             sum(BDDEBITO2ZER),   sum(BDCREDITO2ZER),   sum(BDDEBITO2),   sum(BDCREDITO2),   sum(BDDEBITO2ATU),   sum(BDCREDITO2ATU), ';
  wsql = wsql||'             sum(BDDEBITO1ZER),   sum(BDCREDITO1ZER),   sum(BDDEBITO1),   sum(BDCREDITO1),   sum(BDDEBITO1ATU),   sum(BDCREDITO1ATU), ';
  wsql = wsql||'             sum(BDDEBITOZER),    sum(BDCREDITOZER),    sum(BDDEBITO),    sum(BDCREDITO),    sum(BDDEBITOATU),    sum(BDCREDITOATU), sum(bddebitoIniZer), sum(bdcreditoIniZer), demo.bdcodtpcc, cc.BDNOMCTA as BDNOMTPCC ';

  wsql = wsql||'from vsuc_empresas_demonstrativo demo ';
  wsql = wsql||'inner join planos_tpla tpla on (tpla.bdcodplapadrao = '||bdcodplapadrao||' and tpla.bdcodtpla = demo.bdcodtpla) ';
  if (PRDETALHAR_TERC = 1) then
    BEGIN
      wsql = wsql||'LEFT OUTER JOIN (SELECT 1 AS BDMOSTRATER FROM rdb$database UNION ALL SELECT 0 AS BDMOSTRATER FROM rdb$database) TERAUX ON (DEMO.BDCODTERCEIRO = IIF(TPLA.BDPARTICIPANTE = 1, DEMO.BDCODTERCEIRO, NULL)) ';
      wsql = wsql||'left outer join VW_TTERCEIRO ter on (ter.BDCODTER = IIF(TPLA.BDPARTICIPANTE = 1 AND TERAUX.BDMOSTRATER = 1, demo.BDCODTERCEIRO, 0))';
    END
  --alt:11615 - 30/06/2015 - Carrega o grupo referencial se for uma exportacao do Sped ECF. Pedro
  IF (prExportacaoECF = 1) THEN
    wSQL = wSQL||'left outer join PLANOS_TPLA_ECF ecf on (ecf.BDCODPLAPADRAO = tpla.BDCODPLAPADRAO and ecf.BDCODTPLA = tpla.BDCODTPLA and ecf.BDCODPLAPADRAOREF = '||wCodPlaPadraoRef||' and ecf.BDANO = '||wanoecf||')';
  --alt:11615 - Fim

  wsql = wsql||'left outer join CENTROS_TPCC cc on (cc.BDCODCENTRO = demo.BDCODCENTRO and cc.bdcodtpcc = demo.bdcodtpcc) ';

  wsql = wsql||'group by ';
  IF (prdetalhafilial = 1) THEN
    wsql = wsql||'demo.bdcodemp, ';
  wsql = wsql||'tpla.BDCODTPLA, tpla.bdctalon, tpla.bdnomcta, tpla.bdapecta, tpla.bdtipcta, tpla.bdgrupocta, tpla.bdrelcta, BDCODGRUPOCTA, bdcodtpcc, BDNOMTPCC ';

  if (prdetalhar_terc = 1) then
    wsql = wsql||', ter.bdcodter, ter.bdnometer ';

  wsql = wsql||'order by ';
  IF (prdetalhafilial = 1) THEN
    wsql = wsql||'demo.bdcodemp, ';
  wsql = wsql||'tpla.bdctalon ';

  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdcodtpla, : bdctalon, :bdnomcta, :bdapecta, :bdtipcta, :bdgrupocta, :bdrelcta, :bdcodter, :wCodPlaPadraoRef,
           :wdeb_ant_zer, :wcre_ant_zer,
           :wdeb_ant,     :wcre_ant,
           :wdeb_2_zer,   :wcre_2_zer,
           :wdeb_2,       :wcre_2,
           :wdeb_2_atu,   :wcre_2_atu,
           :wdeb_1_zer,   :wcre_1_zer,
           :wdeb_1,       :wcre_1,
           :wdeb_1_atu,   :wcre_1_atu,
           :wdeb_zer,     :wcre_zer,
           :wdeb,         :wcre,
           :wdeb_atu,     :wcre_atu,  
           :wdeb_ini_zer, :wcre_ini_zer,
           :bdcodtpcc,    :bdnomtpcc DO
      BEGIN
        if (bdcodter IS NOT NULL) then
          BEGIN
             bdctalon = REVERSE(bdctalon);
             bdctalon = SUBSTRING(bdctalon FROM POSITION('.', bdctalon) FOR strlen(bdctalon));
             bdctalon = REVERSE(bdctalon);
             bdctalon = bdctalon||LPAD(bdcodter, 9, '0');
          END

        IF (bdgrupocta IN (1,2,3)) THEN
           BEGIN
             /*******************************************************************************************************************************
             Contas do Passivo, Patrimonio Liquido e Receitas sao da natureza Credora, portando, devem ser calculadas com "Credito - Debito".
             *******************************************************************************************************************************/

             --alt:14249 - 29/04/2016 - nao deve ignorar o zeramento para as contas do Ativo, Passivo e PL, pois eles compoem o saldo destes grupos. Pedro
             --alt:11615 - 30/06/2015 - Verifica o grupo da conta preparada no Sped ECF, o grupo 04 devera ignorar o zeramento. Pedro
             IF (((prignorazeramento = 1) OR (wCodPlaPadraoRef = 4)) AND NOT (bdgrupocta IN (0,1,2))) THEN
                BEGIN
                  bdsalant2 = wcre_ant_zer - wdeb_ant_zer;
                  bdsaldeb2 = wdeb_2;
                  bdsalcre2 = wcre_2;
                  bdmovper2 = wcre_2 - wdeb_2;
                  bdsalatu2 = bdsalant2 + bdmovper2;

                  bdsalant1 = bdsalant2 + (wcre_2_zer - wdeb_2_zer);
                  bdsaldeb1 = wdeb_1;
                  bdsalcre1 = wcre_1;
                  bdmovper1 = wcre_1 - wdeb_1;
                  bdsalatu1 = bdsalant1 + bdmovper1;

                  bdsalant = bdsalant1 + (wcre_1_zer - wdeb_1_zer);

                  bdsaldeb = wdeb;
                  bdsalcre = wcre;

                  bdmovper = wcre - wdeb;
                  bdsalatu = bdsalant + bdmovper;
                  if ((PRDATEINIZER is not null) and (PRDATEFINZER is not null)) then
                    begin
                      bdsalatu = bdsalant + (wcre_ini_zer - wdeb_ini_zer);
                    end
                END
             ELSE
                BEGIN
                  bdsalant2 = wcre_ant_zer - wdeb_ant_zer;
                  bdsaldeb2 = wdeb_2_zer;
                  bdsalcre2 = wcre_2_zer;
                  bdmovper2 = wcre_2_zer - wdeb_2_zer;
                  bdsalatu2 = bdsalant2 + bdmovper2;

                  bdsalant1 = bdsalatu2;
                  bdsaldeb1 = wdeb_1_zer;
                  bdsalcre1 = wcre_1_zer;
                  bdmovper1 = wcre_1_zer - wdeb_1_zer;
                  bdsalatu1 = bdsalant1 + bdmovper1;

                  bdsalant = bdsalatu1;
                  bdsaldeb = wdeb_zer;
                  bdsalcre = wcre_zer;
                  bdmovper = wcre_zer - wdeb_zer;
                  bdsalatu = bdsalant + bdmovper;
                END
           END
        ELSE
           BEGIN
             /*******************************************************************************************************************************
             Contas do Ativo, Depesas e Outros sao da natureza Devedora, portando, devem ser calculadas com "Debito - Credito".
             *******************************************************************************************************************************/

             --alt:14249 - 29/04/2016 - Nao deve ignorar o zeramento para as contas do Ativo, Passivo e PL, pois eles compoem o saldo destes grupos. Pedro
             --alt:11615 - 30/06/2015 - Verifica o grupo da conta preparada no Sped ECF, o grupo 04 devera ignorar o zeramento. Pedro
             IF (((prignorazeramento = 1) OR (wCodPlaPadraoRef = 4)) AND NOT (bdgrupocta IN (0,1,2))) THEN
                BEGIN
                  bdsalant2 = wdeb_ant_zer - wcre_ant_zer;
                  bdsaldeb2 = wdeb_2;
                  bdsalcre2 = wcre_2;
                  bdmovper2 = wdeb_2 - wcre_2;
                  bdsalatu2 = bdsalant2 + bdmovper2;

                  bdsalant1 = bdsalant2 + (wdeb_2_zer - wcre_2_zer);
                  bdsaldeb1 = wdeb_1;
                  bdsalcre1 = wcre_1;
                  bdmovper1 = wdeb_1 - wcre_1;
                  bdsalatu1 = bdsalant1 + bdmovper1;

                  bdsalant = bdsalant1 + (wdeb_1_zer - wcre_1_zer);
                  bdsaldeb = wdeb;
                  bdsalcre = wcre;

                  bdmovper = wdeb - wcre;
                  bdsalatu = bdsalant + bdmovper;

                  if ((PRDATEINIZER is not null) and (PRDATEFINZER is not null)) then
                    begin
                      bdsalatu = bdsalant + (wdeb_ini_zer - wcre_ini_zer);
                    end
                END
             ELSE
                BEGIN
                  bdsalant2 = wdeb_ant_zer - wcre_ant_zer;
                  bdsaldeb2 = wdeb_2_zer;
                  bdsalcre2 = wcre_2_zer;
                  bdmovper2 = wdeb_2_zer - wcre_2_zer;
                  bdsalatu2 = bdsalant2 + bdmovper2;

                  bdsalant1 = bdsalatu2;
                  bdsaldeb1 = wdeb_1_zer;
                  bdsalcre1 = wcre_1_zer;
                  bdmovper1 = wdeb_1_zer - wcre_1_zer;
                  bdsalatu1 = bdsalant1 + bdmovper1;

                  bdsalant = bdsalatu1;
                  bdsaldeb = wdeb_zer;
                  bdsalcre = wcre_zer;
                  bdmovper = wdeb_zer - wcre_zer;
                  bdsalatu = bdsalant + bdmovper;
                END
           END

        SUSPEND;
      END
END
^

/* Restore proc. body: VSUC_LANCAMENTOS_AGRUPADOS */
create or alter procedure VSUC_LANCAMENTOS_AGRUPADOS (
    PRCODEMP varchar(1024),
    PRTIPOLAN varchar(100),
    PRCHAVEONLINE varchar(120),
    PRDATA date,
    PRCONTABILIZACAO integer,
    PRDEBITO integer,
    PRCREDITO integer,
    PRCOMPL smallint = null,
    PRCODTPCC varchar(8192) = null)
returns (
    BDCODEMP integer,
    BDCHAVE integer,
    BDCODPLAPADRAO integer,
    BDCODHIST integer,
    BDLOTE varchar(10),
    BDDATA date,
    BDDEBITO integer,
    BDCONCD varchar(5),
    BDCREDITO integer,
    BDCONCC varchar(5),
    BDVALOR numeric(15,2),
    BDDATALAN date,
    BDHORALAN time,
    BDDATALANALT date,
    BDHORALANALT time,
    BDCODUSU integer,
    BDCODUSUALTERACAO integer,
    BDCODTPHI integer,
    BDNOMEHIST varchar(100),
    BDCOMPL varchar(200),
    BDDCTO varchar(15),
    BDCODTERCEIROD integer,
    BDCODTERCEIROC integer,
    BDTIPLAN varchar(100),
    BDTRANSFERIDO integer,
    BDGRUPO integer,
    BDTOTLAN integer,
    BDAGRUPADOR integer,
    BDTIPOLAN integer,
    BDCHAVEONLINE varchar(120),
    BDCODTPCC integer,
    BDTRANSACAO integer,
    BDTRANFECHADA varchar(5),
    BDCONCILIACAOPENDENTE integer,
    BDOBSERVACAODEB type of column VSUC_EMPRESAS_TOBS.BDOBSERVACAO,
    BDOBSERVACAOCRE type of column VSUC_EMPRESAS_TOBS.BDOBSERVACAO)
as
declare variable WSQL varchar(10240);
declare variable WSQLAUX varchar(10240);
declare variable WCOUNT integer;
declare variable WDATA date;
declare variable WDATAANT date;
declare variable WDEBITO integer;
declare variable WDEBANT integer;
declare variable WCREDITO integer;
declare variable WCREANT integer;
declare variable WCHAVEONLINE varchar(120);
declare variable WCHAVEONLINEANT varchar(120);
declare variable WVALOR numeric(15,2);
declare variable WTOTAL numeric(15,2);
declare variable WCHAVE integer;
declare variable WCHAVEANT integer;
declare variable WGRUPO integer;
declare variable WGRUPOANT integer;
declare variable WTOTLAN integer;
declare variable WTOTLANANT integer;
declare variable WAGRUPADOR integer;
declare variable WAGRUPADORANT integer;
declare variable WTIPLAN varchar(100);
declare variable WTIPLANANT varchar(100);
declare variable WCOMPL1 varchar(200);
declare variable WCOMPL2 varchar(200);
declare variable WCODPLAPADRAOANT integer;
declare variable WTIPOLANANT integer;
declare variable WCODHISTANT integer;
declare variable WCODEMP integer;
declare variable WCODEMPANT integer;
declare variable WCODTPCC integer;
declare variable WCODTPCCANT integer;
BEGIN
  wchaveonlineant = '';
  wdataant = NULL;
  wdebant = 0;
  wcreant = 0;
  wtotal = 0;
  wcount = 0;
  --#alt:123476 - 29/07/2019 - Carlos Machado - Estava deixando a empresa anterior ocasionalmente.
  wcodempant = 0;
  wcodplapadraoant = 0;
  wtipolanant = 0;
  wcodhistant = 0;
  wtiplanant = 0;

  wsql = 'select lan.bdcodemp, lan.bdcodplapadrao, lan.bdtipolan, lan.bdcodhist, lan.bddata, lan.bddebito, lan.bdcredito, lan.bdchaveonline, tip.bddescricao bdTIPLAN, ';
  wsql = wsql||'min(lan.bdchave), count(lan.bdchave), case when count(lan.bdchave) > 1 then 1 else 0 end as bdagrupador, '; --alt:11759 - 01/02/2016 - Só deve aparecer o botão para agrupar nos lançamentos agrupados, antes mostrava em todos da Folha. Pedro
  IF (prcodtpcc IS NULL OR (prcodtpcc = '')) THEN
     BEGIN
       wsql = wsql||'sum(lan.bdvalor), null as bdcodtpcc ';
       wsql = wsql||'from VSUC_EMPRESAS_TLAN lan ';
     END
  ELSE
     BEGIN
       wsql = wsql||'sum(tlcc.BDVALOR), tlcc.bdcodtpcc from vsuc_empresas_tlcc tlcc ';
       wsql = wsql||'inner join vsuc_empresas_tlan lan on (lan.bdcodemp = tlcc.bdcodemp and lan.bdchave = tlcc.bdchave) ';
     END
  --left join HIST_TPHI hist on ((hist.bdcodhist = lan.bdcodhist) and (hist.bdcodtphi = lan.bdcodtphi))
  wsql = wsql||'left outer join tipos_lancamentos_padrao tip on (tip.bdcodtipo = lan.bdtipolan) ';
  wsql = wsql||'left outer join vsuc_empresas_translan trans on ((trans.bdcodemp = lan.bdcodemp and trans.bdchave = lan.bdchave) or (trans.bdcodemprec = lan.bdcodemp and trans.bdchaverec = lan.bdchave)) ';
  wsql = wsql||'WHERE lan.BDCODEMP in ('||prcodemp||') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (lan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  wsql = wsql||'and ((lan.bdtipolan in ('||prtipolan||')) and (lan.bdchaveonline is not null)) ';
  IF (prcodtpcc IS NOT NULL AND (prcodtpcc <> '')) THEN
     wsql = wsql||' and tlcc.bdcodtpcc in ('||prcodtpcc||')';

  wsql = wsql||'group by lan.bdcodemp, lan.bdcodplapadrao, lan.bdtipolan, lan.bdcodhist, lan.bddata, lan.bddebito, lan.bdcredito, lan.bdchaveonline, tip.bddescricao ';
  IF (prcodtpcc IS NOT NULL AND (prcodtpcc <> '')) THEN
    wsql = wsql||', tlcc.bdcodtpcc ';
  wsql = wsql||'order by lan.bdchaveonline, lan.bddata ';
  FOR EXECUTE STATEMENT wsql INTO :WCODEMP, :bdcodplapadrao, :bdtipolan, :bdcodhist, :wdata, :wdebito, :wcredito, :wchaveonline, :bdtiplan, :wgrupo, :wtotlan, :wagrupador, :wvalor, :wcodtpcc DO
      BEGIN
-- alt:#6537 - gilberto - 29/08/2013
--        if ((wchaveonlineant <> wchaveonline) or (wdataant <> wdata)) then
--        if ((wchaveonlineant <> wchaveonline) or (wdataant <> wdata) or (coalesce(wdebant, 0) <> coalesce(wdebito, 0)) or (coalesce(wcreant, 0) <> coalesce(wcredito, 0))) then
           BEGIN
             bdchave = wchaveant;
             bddata = wdataant;
             bdgrupo = wgrupoant;
             bdtotlan = wtotlanant;
             bdagrupador = wagrupadorant;
             bdchaveonline = wchaveonlineant;
             bdcodtpcc = wcodtpccant;
             BDCODEMP = WCODEMPANT;
             IF (wcount >= 2) THEN
                BEGIN
                  IF (wtotal < 0) THEN
                     BEGIN
                       bddebito = wdebant;
                       bdcredito = wcreant;
                       bdvalor = wtotal * -1;
                     END
                  ELSE
                     BEGIN
                       bddebito = wcreant;
                       bdcredito = wdebant;
                       bdvalor = wtotal;
                     END
                END
             ELSE
                BEGIN
                  bddebito = wdebant;
                  bdcredito = wcreant;
                  bdvalor = wtotal;
                END

             IF (wchaveant IS NOT NULL) THEN
               SUSPEND;
             wtotal = 0;
             wdebant = wdebito;
             wcreant = wcredito;
             wdataant = wdata;
             wcount = 0;
             wtotlanant = 0;

-- alt:#6537 - gilberto - 29/08/2013
--             if (wchaveonlineant = prchaveonline and wdataant = prdata) then
--             if ((wchaveonlineant = prchaveonline) and (wdataant = prdata) and (coalesce(wdebito, 0) = coalesce(prdebito, 0)) and (coalesce(wcredito, 0) = coalesce(prcredito, 0))) then
             IF ((wchaveonline = prchaveonline) AND (wdata = prdata) AND (COALESCE(wdebito, 0) = COALESCE(prdebito, 0)) AND (COALESCE(wcredito, 0) = COALESCE(prcredito, 0))) THEN
--             if ((wchaveonline = prchaveonline) and (wdata = prdata)) then
                BEGIN
                  wsqlaux = 'select lan.bdCHAVE,  lan.bdCODEMP, lan.bdcodplapadrao, lan.bdcodhist, lan.BDLOTE, ';
                  wsqlaux = wsqlaux||'lan.BDDATA, lan.BDDEBITO, lan.BDTIPOLAN,  lan.bdCONCD, lan.BDCREDITO, ';
                  wsqlaux = wsqlaux||'lan.bdCONCC, lan.bddatalan, lan.bdhoralan, lan.bddatalanalt, ';
                  wsqlaux = wsqlaux||'lan.bdhoralanalt, lan.bdcodusu, lan.bdcodusualteracao, lan.BDCODTPHI, ';
                  wsqlaux = wsqlaux||'hist.bdNOME,lan.BDCOMPL,  lan.BDDCTO ,lan.bdcodterceirod, lan.bdcodterceiroc, ';
                  wsqlaux = wsqlaux||'tip.bddescricao bdTIPLAN, ';
                  wsqlaux = wsqlaux||'case when (lan.bdcodemp = trans.bdcodemp) then trans.bdcodemprec when (lan.bdcodemp = trans.bdcodemprec) then trans.bdcodemp end bdtransferido , ';
                  wsqlaux = wsqlaux||'null as bdtotlan, 0 as bdagrupador, lan.bdchaveonline, lan.bdtransacao, lan.bdtranfechada, ';
                  --alt:17776 - 09/03/2017 - Adicionadas colunas do status de conciliação e observação, acrescentadas para a central de conciliações. Pedro
                  wsqlaux = wsqlaux||'lan.bdconciliacaopendente, tObsDeb.BDOBSERVACAO as BDOBSERVACAODEB, tobsCre.BDOBSERVACAO as BDOBSERVACAOCRE, ';
                  IF (prcodtpcc IS NULL OR (prcodtpcc = '')) THEN
                     BEGIN
                       wsqlaux = wsqlaux||'lan.bdvalor, null as bdcodtpcc ';
                       wsqlaux = wsqlaux||'from VSUC_EMPRESAS_TLAN lan ';
                     END
                  ELSE
                     BEGIN
                       wsqlaux = wsqlaux||'tlcc.BDVALOR, tlcc.bdcodtpcc from vsuc_empresas_tlcc tlcc ';
                       wsqlaux = wsqlaux||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave and tlcc.bdcodtpcc in ('||prcodtpcc||')) ';
                     END
                  wsqlaux = wsqlaux||'left join HIST_TPHI hist on ((hist.bdcodhist = lan.bdcodhist) and (hist.bdcodtphi = lan.bdcodtphi)) ';
                  wsqlaux = wsqlaux||'left outer join tipos_lancamentos_padrao tip on (tip.bdcodtipo = lan.bdtipolan) ';
                  wsqlaux = wsqlaux||'left outer join vsuc_empresas_translan trans on ((trans.bdcodemp = lan.bdcodemp and trans.bdchave = lan.bdchave) or (trans.bdcodemprec = lan.bdcodemp and trans.bdchaverec = lan.bdchave)) ';
                  --alt:17776 - 09/03/2017 - Adicionadas colunas do status de conciliação e observação, acrescentadas para a central de conciliações. Pedro
                  wsqlaux = wsqlaux||'left join VSUC_EMPRESAS_TOBS tObsDeb on (tObsDeb.BDCODEMP = lan.BDCODEMP and tObsDeb.BDCHAVE = lan.BDCHAVE and tObsDeb.BDDEBCRE = 0) ';
                  wsqlaux = wsqlaux||'left join VSUC_EMPRESAS_TOBS tObsCre on (tObsCre.BDCODEMP = lan.BDCODEMP and tObsCre.BDCHAVE = lan.BDCHAVE and tObsCre.BDDEBCRE = 1) ';
                  wsqlaux = wsqlaux||'WHERE lan.BDCODEMP in ('||prcodemp||') ';
                  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
                  IF (prcontabilizacao <> 99) THEN
                    wsqlaux = wsqlaux||'and (lan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
                  wsqlaux = wsqlaux||'and ((lan.bdtipolan in ('||prtipolan||')) and (lan.bdchaveonline is not null)) ';
                  wsqlaux = wsqlaux||'and lan.bddata = cast('''||prdata||''' as date) ' ;
                  wsqlaux = wsqlaux||'and lan.bdchaveonline = '''||prchaveonline||''' ';
-- alt:#6537 - gilberto - 29/08/2013
                  wsqlaux = wsqlaux||' and ((coalesce(lan.bddebito, 0) = '||COALESCE(wdebito, 0)||') and (coalesce(lan.bdcredito, 0) = '||COALESCE(wcredito, 0)||')) ';

                  wsqlaux = wsqlaux||'order by lan.bdchaveonline, lan.bddata ';
                  FOR EXECUTE STATEMENT wsqlaux
                      INTO :bdchave, :bdcodemp, :bdcodplapadrao, :bdcodhist, :bdlote, :bddata, :bddebito, :bdtipolan, :bdconcd, :bdcredito, :bdconcc,
                           :bddatalan, :bdhoralan, :bddatalanalt, :bdhoralanalt, :bdcodusu, :bdcodusualteracao, :bdcodtphi, :bdnomehist, :bdcompl, :bddcto,
                           :bdcodterceirod, :bdcodterceiroc, :bdtiplan, :bdtransferido, :bdtotlan, :bdagrupador, :bdchaveonline, :bdtransacao, :bdtranfechada,
                           :bdconciliacaopendente, :bdobservacaodeb, :bdobservacaocre, :bdvalor, :bdcodtpcc DO
                      BEGIN
                        BDGRUPO = :wGrupo; --alt:11759 - 04/02/2016 - Preciso que o grupo seja o mesmo que o do lançamento agrupado, para poder ordenar corretamente, já que nem sempre é agrupada a ChaveOnline inteira. Pedro
                        SUSPEND;
                      END
                END
           END

        IF ((wdebant = wcredito) AND (wcreant = wdebito) AND (wdataant = wdata)) THEN
           BEGIN
             wtotal = wtotal - wvalor;
             wcount = wcount + 1;
           END
        ELSE
           BEGIN
             wtotal = wtotal + wvalor;
             wcount = wcount + 1;
           END
        wtotlanant = wtotlanant + wtotlan;


        wchaveant = wgrupo;
        wdataant = wdata;
        wdebant = wdebito;  
        wcreant = wcredito;
        wchaveonlineant = wchaveonline;
        wgrupoant = wgrupo;
        wcodtpccant = wcodtpcc;
        wagrupadorant = wagrupador;
        wcodempant = wcodemp;
        wcodplapadraoant = bdcodplapadrao;
        wtipolanant = bdtipolan;
        wcodhistant = bdcodhist;
        wtiplanant = bdtiplan;
        wcodtpcc = bdcodtpcc;

        BDCODEMP = NULL;
        BDCHAVE = NULL;
        BDCODPLAPADRAO = NULL;
        BDCODHIST = NULL;
        BDLOTE = NULL;
        BDDATA = NULL;
        BDDEBITO = NULL;
        BDCONCD = NULL;
        BDCREDITO = NULL;
        BDCONCC = NULL;
        BDVALOR = NULL;
        BDDATALAN = NULL;
        BDHORALAN = NULL;
        BDDATALANALT = NULL;
        BDHORALANALT = NULL;
        BDCODUSU = NULL;
        BDCODUSUALTERACAO = NULL;
        BDCODTPHI = NULL;
        BDNOMEHIST = NULL;
        BDCOMPL = NULL;
        BDDCTO = NULL;
        BDCODTERCEIROD = NULL;
        BDCODTERCEIROC = NULL;
        BDTIPLAN = NULL;
        BDTRANSFERIDO = NULL;
        BDGRUPO = NULL;
        BDTOTLAN = NULL;
        BDAGRUPADOR = NULL;
        BDTIPOLAN = NULL;
        BDCHAVEONLINE = NULL;
        BDCODTPCC = NULL;
        BDTRANSACAO = NULL;
        BDTRANFECHADA = NULL;
        BDCONCILIACAOPENDENTE = NULL;
        BDOBSERVACAODEB = NULL;
        BDOBSERVACAOCRE = NULL;
      END

  IF (wchaveant IS NOT NULL) THEN
     BEGIN
       bdchave = wchaveant;
       bddata = wdataant;
       bdgrupo = wgrupoant;
       bdtotlan = wtotlanant;
       bdagrupador = wagrupadorant;
       bdchaveonline = wchaveonlineant;
       bdcodemp = wcodempant;
       bdcodplapadrao = wcodplapadraoant;
       bdtipolan = wtipolanant;
       bdcodhist = wcodhistant;
       bdtiplan = wtiplanant;

       IF (wcount >= 2) THEN
          BEGIN
            IF (wtotal < 0) THEN
               BEGIN
                 bddebito = wdebant;
                 bdcredito = wcreant;
                 bdvalor = wtotal * -1;
               END
            ELSE
               BEGIN
                 bddebito = wcreant;
                 bdcredito = wdebant;
                 bdvalor = wtotal;
               END
          END
       ELSE
          BEGIN
            bddebito = wdebant;
            bdcredito = wcreant;
            bdvalor = wtotal;
          END

       IF (wchaveant IS NOT NULL) THEN
          BEGIN
            SUSPEND;
-- alt:#6537 - gilberto - 29/08/2013
--            if (wchaveonlineant = prchaveonline and wdataant = prdata) then
            IF ((wchaveonlineant <> wchaveonline) OR (wdataant <> wdata) OR (COALESCE(wdebant, 0) <> COALESCE(wdebito, 0)) OR (COALESCE(wcreant, 0) <> COALESCE(wcredito, 0))) THEN
               BEGIN
                 wsqlaux = 'select lan.bdCHAVE,  lan.bdCODEMP, lan.bdcodplapadrao, lan.bdcodhist, lan.BDLOTE, ';
                 wsqlaux = wsqlaux||'lan.BDDATA, lan.BDDEBITO, lan.BDTIPOLAN,  lan.bdCONCD, lan.BDCREDITO, ';
                 wsqlaux = wsqlaux||'lan.bdCONCC, lan.bddatalan, lan.bdhoralan, lan.bddatalanalt, ';
                 wsqlaux = wsqlaux||'lan.bdhoralanalt, lan.bdcodusu, lan.bdcodusualteracao, lan.BDCODTPHI, ';
                 wsqlaux = wsqlaux||'hist.bdNOME,lan.BDCOMPL,  lan.BDDCTO ,lan.bdcodterceirod, lan.bdcodterceiroc, ';
                 wsqlaux = wsqlaux||'tip.bddescricao bdTIPLAN, ';
                 wsqlaux = wsqlaux||'case when (lan.bdcodemp = trans.bdcodemp) then trans.bdcodemprec when (lan.bdcodemp = trans.bdcodemprec) then trans.bdcodemp end bdtransferido , ';
                 wsqlaux = wsqlaux||'null as bdtotlan, 0 as bdagrupador, lan.bdchaveonline, lan.bdtransacao, lan.bdtranfechada, ';
                 --alt:17776 - 09/03/2017 - Adicionadas colunas do status de conciliação e observação, acrescentadas para a central de conciliações. Pedro
                 wsqlaux = wsqlaux||'lan.bdconciliacaopendente, tObsDeb.BDOBSERVACAO as BDOBSERVACAODEB, tobsCre.BDOBSERVACAO as BDOBSERVACAOCRE, ';
                 IF (prcodtpcc IS NULL OR (prcodtpcc = '')) THEN
                    BEGIN
                      wsqlaux = wsqlaux||'lan.bdvalor, null as bdcodtpcc ';
                      wsqlaux = wsqlaux||'from VSUC_EMPRESAS_TLAN lan ';
                    END
                 ELSE
                    BEGIN
                      wsqlaux = wsqlaux||'tlcc.BDVALOR, tlcc.bdcodtpcc from vsuc_empresas_tlcc tlcc ';
                      wsqlaux = wsqlaux||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave and tlcc.bdcodtpcc in ('||prcodtpcc||')) ';
                    END
                 wsqlaux = wsqlaux||'left join HIST_TPHI hist on ((hist.bdcodhist = lan.bdcodhist) and (hist.bdcodtphi = lan.bdcodtphi)) ';
                 wsqlaux = wsqlaux||'left outer join tipos_lancamentos_padrao tip on (tip.bdcodtipo = lan.bdtipolan) ';
                 wsqlaux = wsqlaux||'left outer join vsuc_empresas_translan trans on ((trans.bdcodemp = lan.bdcodemp and trans.bdchave = lan.bdchave) or (trans.bdcodemprec = lan.bdcodemp and trans.bdchaverec = lan.bdchave)) ';
                 --alt:17776 - 09/03/2017 - Adicionadas colunas do status de conciliação e observação, acrescentadas para a central de conciliações. Pedro
                 wsqlaux = wsqlaux||'left join VSUC_EMPRESAS_TOBS tObsDeb on (tObsDeb.BDCODEMP = tlan.BDCODEMP and tObsDeb.BDCHAVE = tlan.BDCHAVE and tObsDeb.BDDEBCRE = 0) ';
                 wsqlaux = wsqlaux||'left join VSUC_EMPRESAS_TOBS tObsCre on (tObsCre.BDCODEMP = tlan.BDCODEMP and tObsCre.BDCHAVE = tlan.BDCHAVE and tObsCre.BDDEBCRE = 1) ';
                 wsqlaux = wsqlaux||'WHERE lan.BDCODEMP in ('||prcodemp||') ';
                 --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
                 IF (prcontabilizacao <> 99) THEN
                   wsqlaux = wsqlaux||'and (lan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
                 wsqlaux = wsqlaux||'and ((lan.bdtipolan in ('||prtipolan||')) and (lan.bdchaveonline is not null)) ';
                 wsqlaux = wsqlaux||'and lan.bddata = cast('''||prdata||''' as date) ' ;
                 wsqlaux = wsqlaux||'and lan.bdchaveonline = '''||prchaveonline||''' ';
                 wsqlaux = wsqlaux||'order by lan.bdchaveonline, lan.bddata ';
                 FOR EXECUTE STATEMENT wsqlaux
                     INTO :bdchave, :bdcodemp, :bdcodplapadrao, :bdcodhist, :bdlote, :bddata, :bddebito, :bdtipolan, :bdconcd, :bdcredito, :bdconcc,
                          :bddatalan, :bdhoralan, :bddatalanalt, :bdhoralanalt, :bdcodusu, :bdcodusualteracao, :bdcodtphi, :bdnomehist, :bdcompl, :bddcto,
                          :bdcodterceirod, :bdcodterceiroc, :bdtiplan, :bdtransferido, :bdtotlan, :bdagrupador, :bdchaveonline, :bdtransacao, :bdtranfechada,
                          :bdconciliacaopendente, :bdobservacaodeb, :bdobservacaocre, :bdvalor, :wcodtpcc DO
                     BEGIN
                        BDGRUPO = :wGrupo; --alt:11759 - 04/02/2016 - Preciso que o grupo seja o mesmo que o do lançamento agrupado, para poder ordenar corretamente, já que nem sempre é agrupada a ChaveOnline inteira. Pedro
                        SUSPEND;
                      END
               END
          END
     END
END
^

/* Restore proc. body: VSUC_NRO_NOTA_COMPL */
ALTER PROCEDURE VSUC_NRO_NOTA_COMPL(PRCOMPL VARCHAR(200),
PRZEROESQ SMALLINT)
 RETURNS(NRONF VARCHAR(50))
 AS
DECLARE VARIABLE WCHAR CHAR(1);
DECLARE VARIABLE WCONTA INTEGER;
DECLARE VARIABLE WPOS INTEGER;
BEGIN
  -- retorna os numeros dos documentos de acordo com o parametro de ignorar zeros a esquerda
  wconta = 1;
  --#alt:6773. Carlos Mello(30/09/2013)
  /*nronf = '';
  while (wconta <= strlen(prcompl)) do
    begin
      wchar = substring(prcompl from wconta for 1);
      select pos from pos(:wchar,'0123456789') into :wpos;
      if (wpos <> 0) then
         nronf = nronf||wchar;
      wconta = wconta + 1;
    end*/
  nronf = prcompl; -- Está vindo o Número do documento

  IF ((przeroesq IS NULL) OR (przeroesq = 0)) THEN
     BEGIN
       WHILE (SUBSTRING(nronf FROM 1 FOR 1) = '0') DO
         BEGIN
           nronf = SUBSTRING(nronf FROM 2 FOR strlen(nronf)-1);
         END
     END

  SUSPEND;
END
^

/* Restore proc. body: VSUC_SP_ALTERA_LANCAMENTOS */
ALTER PROCEDURE VSUC_SP_ALTERA_LANCAMENTOS AS
BEGIN
  /* Procedure Text */

END
^

create or alter procedure VSUC_SP_RESTAURA_LANC_LIXEIRA (
    PRCODEMP integer,
    PRCHAVE integer,
    PRTRANSACAO integer,
    PRMANTERCHAVE integer,
    PRNOVACHAVE integer,
    PRNOVATRANSACAO integer,
    PRIGNORAR_N_PRA_N integer = 0,
    PRUPDATE_LANCAMENTO integer = 0)
as
declare variable WUSUARIO integer;
declare variable WTABLE varchar(100) collate WIN_PTBR;
declare variable WFIELDS varchar(2000) collate WIN_PTBR;
declare variable WSQL varchar(5000) collate WIN_PTBR;
declare variable WTABLE_ORIGINAL varchar(100);
declare variable WCODEMPAUX integer;
declare variable WCHAVEAUX integer;
declare variable WNOVACHAVE integer;
declare variable WNOVATRANSACAO integer;
declare variable WNOVACHAVEAUX integer;
BEGIN
  IF (PRMANTERCHAVE = 1) THEN
    WNOVACHAVE = PRCHAVE;
  ELSE
    WNOVACHAVE = PRNOVACHAVE;

  WNOVATRANSACAO = PRTRANSACAO;

  FOR SELECT TRIM(RDB$RELATION_NAME),
             (SELECT LIST(TRIM(F.RDB$FIELD_NAME), ', ') FROM RDB$RELATION_FIELDS F
              JOIN RDB$RELATIONS R ON F.RDB$RELATION_NAME = R.RDB$RELATION_NAME AND R.RDB$VIEW_BLR IS NULL AND (R.RDB$SYSTEM_FLAG IS NULL OR R.RDB$SYSTEM_FLAG = 0)
              WHERE F.RDB$RELATION_NAME = REPLACE(RELA.RDB$RELATION_NAME, '_LX', '') AND
                    TRIM(F.RDB$FIELD_NAME) NOT IN ('BDEXCLUINDO', 'BDRECLIXEIRA', 'BDTRANSACAO', 'BDCHAVE','BDCHAVEVINC')) FROM RDB$RELATIONS RELA
      WHERE RDB$VIEW_BLR IS NULL AND
            (RDB$SYSTEM_FLAG IS NULL OR RDB$SYSTEM_FLAG = 0) AND
            (RDB$RELATION_NAME STARTS WITH 'VSUC_LX_EMPRESAS_T')
      ORDER BY CHAR_LENGTH(TRIM(RDB$RELATION_NAME)), RDB$RELATION_NAME INTO :WTABLE, :WFIELDS
  DO
  BEGIN
    WCODEMPAUX = NULL;
    WTABLE_ORIGINAL = REPLACE(WTABLE, '_LX', '');
    WSQL = 'INSERT INTO ' || WTABLE_ORIGINAL || ' (' || WFIELDS || ' #CAMPO#) SELECT ' || WFIELDS || ' #VALOR# from ' || WTABLE;
    WSQL = WSQL || ' where bdcodemp = ' || PRCODEMP || ' and bdchave = ' || PRCHAVE;
    IF (WTABLE_ORIGINAL = 'VSUC_EMPRESAS_TLAN') THEN
    BEGIN
      WSQL = REPLACE(WSQL, '#CAMPO#', ', BDRECLIXEIRA, BDTRANSACAO, BDCHAVE');
      WSQL = REPLACE(WSQL, '#VALOR#', ', ''TRUE'', ' || COALESCE(WNOVATRANSACAO, 'null') || ', ' || WNOVACHAVE);
    END
    ELSE IF (WTABLE = 'VSUC_LX_EMPRESAS_TRANSLAN') THEN
    BEGIN
      WSQL = NULL;
    END
    ELSE IF (WTABLE = 'VSUC_LX_EMPRESAS_TLANCARA') THEN
    BEGIN
      WSQL = NULL;
      IF (PRIGNORAR_N_PRA_N = 0) THEN
      BEGIN
        SELECT FIRST 1
                       CASE
                         WHEN (BDCODEMPORIGEM <> :PRCODEMP) THEN BDCODEMPORIGEM
                         WHEN (BDCODEMPDESTINO <> :PRCODEMP) THEN BDCODEMPDESTINO
                       END BDCODEMP,
                       CASE
                         WHEN (BDCODEMPORIGEM <> :PRCODEMP) THEN BDCHAVELANORIGEM
                         WHEN (BDCODEMPDESTINO <> :PRCODEMP) THEN BDCHAVELANDESTINO
                       END BDCHAVE FROM VSUC_LX_EMPRESAS_TLANCARA
        WHERE (BDCODEMPORIGEM = :PRCODEMP AND
              BDCHAVELANORIGEM = :PRCHAVE) OR (BDCODEMPDESTINO = :PRCODEMP AND
              BDCHAVELANDESTINO = :PRCHAVE) INTO :WCODEMPAUX, :WCHAVEAUX;
        IF (WCODEMPAUX IS NOT NULL) THEN
        BEGIN
          WNOVACHAVEAUX = WCHAVEAUX;
          DELETE FROM VSUC_LX_EMPRESAS_TLANCARA
          WHERE (BDCODEMPORIGEM = :PRCODEMP AND
                BDCHAVELANORIGEM = :PRCHAVE) OR (BDCODEMPDESTINO = :PRCODEMP AND
                BDCHAVELANDESTINO = :PRCHAVE);

          EXECUTE PROCEDURE VSUC_SP_RESTAURA_LANC_LIXEIRA(:WCODEMPAUX, :WCHAVEAUX, :PRTRANSACAO,
              :PRMANTERCHAVE, :WNOVACHAVEAUX, :WNOVATRANSACAO, 1, 1);

          INSERT INTO VSUC_EMPRESAS_TLANCARA (BDCODEMPORIGEM, BDCHAVELANORIGEM, BDCODEMPDESTINO,
                                              BDCHAVELANDESTINO)
          VALUES (:PRCODEMP, :WNOVACHAVE, :WCODEMPAUX, :WNOVACHAVEAUX);
        END
      END
    END

    WSQL = REPLACE(WSQL, '#CAMPO#', ', BDCHAVE');
    WSQL = REPLACE(WSQL, '#VALOR#', ', ' || WNOVACHAVE);
    IF (WSQL IS NOT NULL) THEN
      EXECUTE STATEMENT WSQL;
  END

  UPDATE VSUC_LX_EMPRESAS_TLAN TLAN
  SET TLAN.BDEXCLUINDO = 1
  WHERE TLAN.BDCODEMP = :PRCODEMP AND
        TLAN.BDCHAVE = :PRCHAVE;
END
^

CREATE OR ALTER PROCEDURE VSUC_SP_MOVE_LANC_LIXEIRA (
PRCODEMP            INTEGER,
PRCHAVE             INTEGER,
PRIGNORAR_N_PRA_N   INTEGER = 0,
PRUPDATE_LANCAMENTO INTEGER = 0)
AS
DECLARE VARIABLE WUSUARIO          INTEGER;
DECLARE VARIABLE WTABLE            VARCHAR(100) COLLATE WIN_PTBR;
DECLARE VARIABLE WFIELDS           VARCHAR(2000) COLLATE WIN_PTBR;
DECLARE VARIABLE WSQL              VARCHAR(5000) COLLATE WIN_PTBR;
DECLARE VARIABLE WTABLE_ORIGINAL   VARCHAR(100);
DECLARE VARIABLE WCODEMPAUX        INTEGER;
DECLARE VARIABLE WCHAVEAUX         INTEGER;
DECLARE VARIABLE WCHAVEEXCLUSAOAUX BIGINT;
BEGIN
  SELECT BDCODUSU FROM SP_GET_USUARIO INTO :WUSUARIO;
  if (WUSUARIO IS NULL) then
    WUSUARIO = 1;

  DELETE FROM VSUC_LX_EMPRESAS_TLAN WHERE BDCODEMP = :PRCODEMP AND BDCHAVE = :PRCHAVE;

  FOR SELECT TRIM(RDB$RELATION_NAME),
             (SELECT LIST(TRIM(F.RDB$FIELD_NAME), ', ') FROM RDB$RELATION_FIELDS F
              JOIN RDB$RELATIONS R ON F.RDB$RELATION_NAME = R.RDB$RELATION_NAME AND R.RDB$VIEW_BLR IS NULL AND (R.RDB$SYSTEM_FLAG IS NULL OR R.RDB$SYSTEM_FLAG = 0)
              WHERE F.RDB$RELATION_NAME = REPLACE(RELA.RDB$RELATION_NAME, '_LX', '') AND TRIM(F.RDB$FIELD_NAME) NOT IN ('BDEXCLUINDO', 'BDRECLIXEIRA')) FROM RDB$RELATIONS RELA
      WHERE RDB$VIEW_BLR IS NULL AND
            (RDB$SYSTEM_FLAG IS NULL OR RDB$SYSTEM_FLAG = 0) AND
            (RDB$RELATION_NAME STARTS WITH 'VSUC_LX_EMPRESAS_T')
      ORDER BY CHAR_LENGTH(TRIM(RDB$RELATION_NAME)), RDB$RELATION_NAME INTO :WTABLE, :WFIELDS
  DO
  BEGIN
    WCODEMPAUX = NULL;
    WTABLE_ORIGINAL = REPLACE(WTABLE, '_LX', '');
    WSQL = 'INSERT INTO ' || WTABLE || ' (' || WFIELDS || ' #CAMPO#) SELECT ' || WFIELDS || ' #VALOR# from ' || WTABLE_ORIGINAL;
    WSQL = WSQL || ' where bdcodemp = ' || PRCODEMP || ' and bdchave = ' || PRCHAVE;
    IF (WTABLE_ORIGINAL = 'VSUC_EMPRESAS_TLAN') THEN
    BEGIN
      WSQL = REPLACE(WSQL, '#CAMPO#', ', BDCODUSUEXCLUSAO');
      WSQL = REPLACE(WSQL, '#VALOR#', ', '||WUSUARIO);
    END
    ELSE IF (WTABLE = 'VSUC_LX_EMPRESAS_TRANSLAN') THEN
    BEGIN
      WSQL = NULL;
    END
    ELSE IF (WTABLE = 'VSUC_LX_EMPRESAS_TLANCARA') THEN
    BEGIN
      WSQL = NULL;
      IF (PRIGNORAR_N_PRA_N = 0) THEN
      BEGIN
        SELECT FIRST 1 BDCODEMPDESTINO, BDCHAVELANDESTINO FROM VSUC_EMPRESAS_TLANCARA
        WHERE BDCODEMPORIGEM = :PRCODEMP AND
              BDCHAVELANORIGEM = :PRCHAVE INTO :WCODEMPAUX, :WCHAVEAUX;
        IF (WCODEMPAUX IS NOT NULL) THEN
        BEGIN
          EXECUTE PROCEDURE VSUC_SP_MOVE_LANC_LIXEIRA(:WCODEMPAUX, :WCHAVEAUX, 1, 1);

          INSERT INTO VSUC_LX_EMPRESAS_TLANCARA (BDCODEMPORIGEM, BDCHAVELANORIGEM, BDCODEMPDESTINO,
                                                 BDCHAVELANDESTINO)
          VALUES (:PRCODEMP, :PRCHAVE, :WCODEMPAUX, :WCHAVEAUX);
        END
      END
    END

      WSQL = REPLACE(WSQL, '#CAMPO#', '');
      WSQL = REPLACE(WSQL, '#VALOR#', '');
    IF (WSQL IS NOT NULL) THEN
      EXECUTE STATEMENT WSQL;
  END

  IF (PRUPDATE_LANCAMENTO = 1) THEN
  BEGIN
    UPDATE VSUC_EMPRESAS_TLAN TLAN
    SET TLAN.BDEXCLUINDO = 1
    WHERE TLAN.BDCODEMP = :PRCODEMP AND
          TLAN.BDCHAVE = :PRCHAVE;
  END
END
^

CREATE OR ALTER PROCEDURE VSUC_SP_RESTAURA_LANCS_LIXEIRA (
    PRSESSAO INTEGER,
    PRLANCDUPLICADOS INTEGER,
    PRMANTERCHAVE INTEGER,
    PRCODEMP INTEGER,
    PRULTCHAVE INTEGER,
    PRULTTRANSACAO INTEGER)
AS
DECLARE VARIABLE WSQL          VARCHAR(5000);
DECLARE VARIABLE WSQLAUX       VARCHAR(5000);
DECLARE VARIABLE WEMPRESAS     VARCHAR(5000);
DECLARE VARIABLE WCODEMP       INTEGER;
DECLARE VARIABLE WCHAVE        INTEGER;
DECLARE VARIABLE WTRANSACAO    INTEGER;
DECLARE VARIABLE WEXCLUINDO    INTEGER;
DECLARE VARIABLE WULTCHAVE     INTEGER;
DECLARE VARIABLE WULTTRANSACAO INTEGER;
BEGIN
  WULTCHAVE = PRULTCHAVE;

  IF (PRMANTERCHAVE = 0 AND
      PRULTTRANSACAO > 0) THEN
  BEGIN
    SELECT FIRST 1 COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) FROM TEMPRESAS EMP
    WHERE BDCODEMP = :PRCODEMP INTO :WCODEMP;

    SELECT FIRST 1 TRIM(LIST(EMP.BDCODEMP, ',')) FROM TEMPRESAS EMP
    WHERE EMP.BDCODEMP = :WCODEMP OR EMP.BDCODMATRIZ = :WCODEMP INTO :WEMPRESAS;

    WSQL = 'SELECT DISTINCT BDTRANSACAO FROM VSUC_LX_EMPRESAS_TLAN lx inner join TMP_VSUC_LX_EMPRESAS_TLAN_TEMP lxtemp on lxtemp.bdcodemp = lx.bdcodemp AND LXTEMP.BDCHAVE = LX.BDCHAVE and LXTEMP.BDSESSAO = ' || :prsessao;
    FOR EXECUTE STATEMENT WSQL
            INTO :WTRANSACAO
    DO
    BEGIN
      IF (WTRANSACAO IS NOT NULL) THEN
      BEGIN
        WSQLAUX = 'UPDATE VSUC_LX_EMPRESAS_TLAN SET BDTRANSACAO = ' || :PRULTTRANSACAO || ' WHERE BDTRANSACAO = ' || WTRANSACAO || ' and BDCODEMP IN (' || WEMPRESAS || ')';
        EXECUTE STATEMENT WSQLAUX;

        PRULTTRANSACAO = PRULTTRANSACAO - 1;
      END
    END
  END

  WSQL = 'SELECT LX.BDCODEMP, LX.BDCHAVE, LX.BDTRANSACAO, LX.BDEXCLUINDO FROM VSUC_LX_EMPRESAS_TLAN LX INNER JOIN TMP_VSUC_LX_EMPRESAS_TLAN_TEMP LXTEMP ON LX.BDCODEMP = LXTEMP.BDCODEMP AND LX.BDCHAVE = LXTEMP.BDCHAVE and LXTEMP.BDSESSAO = ' || :prsessao;
  WSQL = WSQL || ' where LX.BDEXCLUINDO IS NULL ';
  IF (PRCODEMP > 0) THEN
    WSQL = WSQL || ' AND LX.BDCODEMP = ' || :PRCODEMP;

  FOR EXECUTE STATEMENT WSQL
          INTO :WCODEMP, :WCHAVE, :WTRANSACAO, :WEXCLUINDO
  DO
  BEGIN
    EXECUTE PROCEDURE VSUC_SP_RESTAURA_LANC_LIXEIRA(:WCODEMP, :WCHAVE, :WTRANSACAO, :PRMANTERCHAVE,
        :WULTCHAVE, 0);
    WULTCHAVE = WULTCHAVE - 1;
    IF (WTRANSACAO IS NOT NULL) THEN
      WULTTRANSACAO = WULTTRANSACAO - 1;
  END

  DELETE FROM VSUC_LX_EMPRESAS_TLAN
  WHERE BDEXCLUINDO = 1;
END

^

/* Restore proc. body: VSUC_SP_BALANCETE_MENSAL */
CREATE OR ALTER PROCEDURE VSUC_SP_BALANCETE_MENSAL (
    PRCODEMP VARCHAR(2048),
    PRDATINI DATE,
    PRDATFIN DATE,
    PRIGNORA_ZERAMENTO INTEGER,
    PRCTAINI INTEGER,
    PRCTAFIN INTEGER,
    PRINDICE INTEGER,
    PRCODTPCC VARCHAR(8192),
    PRREFEMP INTEGER,
    PRLANSEMCC INTEGER,
    PRNAOMOSTRACONTACOMP INTEGER,
    PRCONSOLIDADA INTEGER,
    PRDETALHARCTAPARTICIPANTE INTEGER,
    PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
    PRCONCATENACODPARTICIPANTE INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRNIVELCC INTEGER = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP VARCHAR(18),
    BDCODMATRIZ INTEGER,
    BDCODEMPFILIAL INTEGER,
    BDCODPLAPADRAO INTEGER,
    BDCODCTA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDTIPCTA SMALLINT,
    BDCODTPCC INTEGER,
    BDNOMTPCC VARCHAR(40),
    BDSALDO_ANTERIOR NUMERIC(15,2),
    BDSALDO_ANT_DEB NUMERIC(15,2),
    BDSALDO_ANT_CRE NUMERIC(15,2),
    BDSALDO_DEB NUMERIC(15,2),
    BDSALDO_CRE NUMERIC(15,2),
    BDSALDO_ATUAL NUMERIC(15,2),
    BDGRPCTA SMALLINT,
    BDTPCCLON VARCHAR(20),
    BDMOVIMENTO NUMERIC(15,2),
    BDFORMULA VARCHAR(200),
    BDRELCTA INTEGER,
    BDCLANOM VARCHAR(140),
    BDDATINI DATE,
    BDDATFIN DATE,
    BDAPECTA VARCHAR(20))
AS
DECLARE VARIABLE WDATINI DATE;
DECLARE VARIABLE WDATFIN DATE;
BEGIN
  wdatini = prdatini;
  wdatfin = addmonth(wdatini, 1)-1;
  WHILE (wdatfin <= prdatfin) DO
    BEGIN
      bddatini = wdatini;
      bddatfin = wdatfin;
      FOR SELECT BDCODEMP, BDNOMEMP, BDCNPJEMP, BDCODMATRIZ, BDCODEMPFILIAL, BDCODPLAPADRAO,
                 BDCODCTA, BDCTALON, BDNOMCTA, BDTIPCTA, BDCODTPCC, BDNOMTPCC,
                 BDSALDO_ANTERIOR, BDSALDO_ANT_DEB, BDSALDO_ANT_CRE, BDSALDO_DEB,
                 BDSALDO_CRE, BDSALDO_ATUAL, BDGRPCTA, BDTPCCLON, BDMOVIMENTO,
                 BDFORMULA, BDRELCTA, BDCLANOM, BDAPECTA
          FROM vsuc_sp_retorna_balancete(:prcodemp, :wdatini, :wdatfin, :prignora_zeramento, :prctaini, :prctafin,:prindice,:prcodtpcc,:prrefemp, :prlansemcc, 0, :prnaomostracontacomp,
                                         :prconsolidada, :prdetalharctaparticipante, :PRAGRUPARPARTICIPANTEPORCNPJ, :prconcatenacodparticipante, :prniveisconta,0,:prcontabilizacao,:prmatrizfilialconsolidado,
                                         0, 0, 0, 0, 0, 0, 0, :prnivelcc)
          INTO :BDCODEMP, :BDNOMEMP, :BDCNPJEMP, :BDCODMATRIZ, :BDCODEMPFILIAL, :BDCODPLAPADRAO,
               :BDCODCTA, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDCODTPCC, :BDNOMTPCC,
               :BDSALDO_ANTERIOR, :BDSALDO_ANT_DEB, :BDSALDO_ANT_CRE, :BDSALDO_DEB,
               :BDSALDO_CRE, :BDSALDO_ATUAL, :BDGRPCTA, :BDTPCCLON, :BDMOVIMENTO,
               :BDFORMULA, :BDRELCTA, :BDCLANOM, :BDAPECTA DO
          SUSPEND;

      wdatini = addmonth(wdatini, 1);
      wdatfin = addmonth(wdatini, 1)-1;
    END
END^

CREATE OR ALTER PROCEDURE VSUC_SP_CENTRAL_CONCILIACAO (
    PRSQL VARCHAR(32000),
    PRPLANO_CONTA INTEGER,
    PRCONTA INTEGER,
    PRPARTICIPANTE INTEGER,
    PRSALDO_ANTERIOR NUMERIC(18,2),
    PRCONCILIACAO VARCHAR(100))
RETURNS (
    BDCODEMP INTEGER,
    BDCHAVE INTEGER,
    BDDATA DATE,
    BDDCTO VARCHAR(15),
    BDDEBITO INTEGER,
    BDCODTERCEIROD INTEGER,
    BDCREDITO INTEGER,
    BDCODTERCEIROC INTEGER,
    BDCODTPHI INTEGER,
    BDCOMPL VARCHAR(200),
    BDTIPOLAN INTEGER,
    BDTRANSACAO INTEGER,
    BDVALOR NUMERIC(18,2),
    BDSALDO NUMERIC(18,2),
    BDGRUPOCTA INTEGER,
    BDVALORDEB NUMERIC(18,2),
    BDVALORCRE NUMERIC(18,2),
    BDCONCILIADO INTEGER,
    BDDEBCRE INTEGER,
    BDCONCILIADOBASE INTEGER,
    BDBLOQUEADO VARCHAR(5),
    BDTIPOCONC INTEGER,
    BDDCTOZEROESQ varchar(15),
    BDNRODOCCOMPL Varchar(255))
AS
DECLARE VARIABLE WCONCILIADO_DEB INTEGER;
DECLARE VARIABLE WCONCILIADO_CRE INTEGER;
DECLARE VARIABLE WCONCILIADO_BASE_CRE INTEGER;
DECLARE VARIABLE WCONCILIADO_BASE_DEB INTEGER;
DECLARE VARIABLE WSAVE_DEBCRE INTEGER;
DECLARE VARIABLE WSALDO_RELATIVO NUMERIC(18,2);
begin
  if (PRSALDO_ANTERIOR is null) then
    PRSALDO_ANTERIOR = 0;
  PRCONCILIACAO = TRIM(COALESCE(PRCONCILIACAO, ''));

  SELECT BDGRUPOCTA FROM PLANOS_TPLA WHERE BDCODPLAPADRAO = :PRPLANO_CONTA AND BDCODTPLA = :PRCONTA INTO :BDGRUPOCTA;

  FOR EXECUTE STATEMENT PRSQL
  INTO :BDCODEMP, :BDCHAVE, :BDDATA, :BDDCTO, :BDDEBITO, :BDCODTERCEIROD, :BDCREDITO,
  :BDCODTERCEIROC, :BDCODTPHI, :BDCOMPL, :BDTIPOLAN, :BDTRANSACAO, :BDVALOR, :BDSALDO,
  :WCONCILIADO_DEB, :WCONCILIADO_CRE, :BDDEBCRE, :WCONCILIADO_BASE_DEB, :WCONCILIADO_BASE_CRE, 
  :BDBLOQUEADO, :bdtipoconc, :BDDCTOZEROESQ, :BDNRODOCCOMPL DO
    BEGIN
      BDVALOR = COALESCE(bdvalor, 0);
      WSAVE_DEBCRE = BDDEBCRE;

      if (WSAVE_DEBCRE = 2) then
        BEGIN
          BDDEBCRE = 0;
          BDCONCILIADO = :WCONCILIADO_DEB;
          BDCONCILIADOBASE = :WCONCILIADO_BASE_DEB;
        END
                              
      BDVALORCRE = 0;
      BDVALORDEB = 0;
      if (BDDEBCRE = 0) then
        begin
          BDVALORDEB = bdvalor;
          BDCONCILIADO = :WCONCILIADO_DEB;
          BDCONCILIADOBASE = :WCONCILIADO_BASE_DEB;
        end
      else
      if (BDDEBCRE = 1) then
        begin
          BDVALORCRE = bdvalor;
          BDCONCILIADO = :WCONCILIADO_CRE;
          BDCONCILIADOBASE = :WCONCILIADO_BASE_CRE;
        end

      if (BDGRUPOCTA in (1,2,3)) then
        WSALDO_RELATIVO = bdvalor * iif(BDDEBCRE = 1, 1, -1);
      else
        WSALDO_RELATIVO = bdvalor * iif(BDDEBCRE = 1, -1, 1);

      PRSALDO_ANTERIOR = PRSALDO_ANTERIOR + WSALDO_RELATIVO;
      
      BDSALDO = PRSALDO_ANTERIOR;
      if (WSAVE_DEBCRE <> 2 or PRCONCILIACAO = '' or POSITION(BDCONCILIADOBASE, PRCONCILIACAO) > 0) then
        suspend;

      if (WSAVE_DEBCRE = 2) then
        BEGIN
          BDDEBCRE = 1;
          BDCONCILIADO = :WCONCILIADO_CRE;
          BDCONCILIADOBASE = :WCONCILIADO_BASE_CRE;

          BDVALORCRE = 0;
          BDVALORDEB = 0;
          if (BDDEBCRE = 0) then
            begin
              BDVALORDEB = bdvalor;
              BDCONCILIADO = :WCONCILIADO_DEB;
              BDCONCILIADOBASE = :WCONCILIADO_BASE_DEB;
            end
          else
          if (BDDEBCRE = 1) then
            begin
              BDVALORCRE = bdvalor;
              BDCONCILIADO = :WCONCILIADO_CRE;
              BDCONCILIADOBASE = :WCONCILIADO_BASE_CRE;
            end
    
          if (BDGRUPOCTA in (1,2,3)) then
            WSALDO_RELATIVO = bdvalor * iif(BDDEBCRE = 1, 1, -1);
          else
            WSALDO_RELATIVO = bdvalor * iif(BDDEBCRE = 1, -1, 1);
    
          PRSALDO_ANTERIOR = PRSALDO_ANTERIOR + WSALDO_RELATIVO;
          
          BDSALDO = PRSALDO_ANTERIOR;
          if (WSAVE_DEBCRE <> 2 or PRCONCILIACAO = '' or POSITION(BDCONCILIADOBASE, PRCONCILIACAO) > 0) then
            suspend;
        END
    END
end
^
/* Restore proc. body: VRH_SP_RATEIO_INTERMITENTE */
create or alter procedure VRH_SP_RATEIO_INTERMITENTE (
    PRREF integer,
    PREMPRESA varchar(32700),
    PRCOLABORADOR varchar(32700))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODCONTTI integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDDATAENTRADA date,
    BDHORAENTRADA time,
    BDTIPO integer,
    BDQTDTEMPO numeric(15,6),
    BDCTALON varchar(40),
    BDTIPCTA smallint,
    BDNOMCTA varchar(100),
    BDAPECTA varchar(20),
    BDFILTROGER varchar(20),
    BDCLANOM varchar(140),
    BDTEMPO integer,
    BDTEMPOFN integer,
    BDPERCFN numeric(15,6),
    BDLANCHORAS numeric(15,2),
    BDTOTHORAS numeric(15,2),
    BDTOTDSR numeric(15,2),
    BDLANCDSR numeric(15,2))
as
declare variable WSQLAUX varchar(32700);
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WULTDIA integer;
declare variable WANO integer;
declare variable WMES smallint;
declare variable WDIA integer;
declare variable WDATAINI varchar(10);
declare variable WDATAFIM varchar(10);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WCODCONTTI integer;
begin
  /* Procedure Text */
 wwhere='';
 wsqlaux='';

 if ((prempresa<>'') and (prempresa is not null)) then
     wwhere = wwhere ||' where ' || prempresa;

 if ((prcolaborador<>'') and (prcolaborador is not null)) then
     begin
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';
       else
          wwhere = wwhere||' where ';

        wwhere = wwhere  || prcolaborador;
      end

  wmes= SUBSTRING(cast(prref as varchar(6)) FROM 5 FOR 2);
  wano= SUBSTRING(cast(prref as varchar(6)) FROM 1 FOR 4);

 select ultdia from ultimo_dia_mes(:wmes,:wano) into :wultdia;
  wdatafim=wmes||'/'||wultdia||'/'||wano;
  wdataini=wmes||'/'||'1'||'/'||wano;
  if (wwhere<>'') then
     wwhere = wwhere|| ' and bddatainiservti>='||''''||wdataini||''''|| ' and ' ||' bddatafimservti <=' ||''''||wdatafim||'''';
  else
     wwhere = ' where bddatainiservti>='||''''||wdataini||''''|| ' and ' ||' bddatafimservti <=' ||''''||wdatafim||'''';

  wsql= 'Select bdcodemp,bdcodcol,bdcodcontti,cast(bddatainiservti as varchar(10)),cast(bddatafimservti as varchar(10)) from vrh_emp_tintermitente colcon';

  wsql=wsql||' '|| wwhere;
   FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodcol,:wcodcontti,wdataini,wdatafim DO
       begin

       bdcodemp=wcodemp;
       bdcodcol=wcodcol;
       bdcodcontti=wcodcontti;

       wdataini= substring(wdataini from 6 for 2 )||'/'||substring(wdataini from 9 for 2 )||'/'||substring(wdataini from 1 for 4 );
       wdatafim= substring(wdatafim from 6 for 2 )||'/'||substring(wdatafim from 9 for 2 )||'/'||substring(wdatafim from 1 for 4 );

        wsqlaux= 'Select BDORDEM,BDCODCENTRO,BDCODTPCC,BDDATAENTRADA,bdhoraentrada,BDTIPO,bdqtdtempo,bdctalon,bdtipcta,bdnomcta,bdapecta,bdfiltroger,bdclanom,bdtempo,bdtempofn,bdpercfn,bdlanchoras,bdtothoras,bdtotdsr,bdlancdsr from VRHF_SP_TPREPFN_CC_REF('||cast(prref as varchar(6))||','||'''colcon.bdcodemp='||wcodemp||''','||'''colcon.bdcodcol='||wcodcol||''',1,'||''''||wdataini ||''','||''''||wdatafim||''''||')';
        FOR EXECUTE STATEMENT wsqlaux INTO
                        :BDORDEM,:BDCODCENTRO,:BDCODTPCC,:bddataentrada,:bdhoraentrada,:bdtipo,:bdqtdtempo,:bdctalon,:bdtipcta,:bdnomcta,:bdapecta,:bdfiltroger,:bdclanom,:bdtempo,:bdtempofn,:bdpercfn,:bdlanchoras,:bdtothoras,:bdtotdsr,:bdlancdsr DO
           begin

           suspend;
           end

       end


end^



/* Restore proc. body: VSUC_SP_BALANCO_PATRIMONIAL */
create or alter procedure VSUC_SP_BALANCO_PATRIMONIAL (
    PRCODEMP varchar(2048),
    PRDATINI date,
    PRDATFIN date,
    PRIGNZER integer,
    PRCTALONINI varchar(40),
    PRCTALONFIN varchar(40),
    PRCTALONPAS varchar(40),
    PRINDICE integer,
    PRLISTACC varchar(8192),
    PRNAOMOSTRACONTACOMP integer,
    PRREFEMP integer,
    PRCONSOLIDADA integer,
    PRDETALHARCTAPARTICIPANTE integer,
    PRCONCATENACODPARTICIPANTE integer,
    PRNIVEISCONTA varchar(50),
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRSEMCC integer,
    PRAGRUPARPARTICIPANTEPORCNPJ integer = 0,
    PRDETALHAREMPREENDIMENTO integer = 0,
    PRDETALHARUNIDIMOB integer = 0,
    PRMOSTRARPROP integer = 0,
    PRAGRUPARPARTICIPANTEPORCPF integer = 0,
    PRCTAINI integer = 0,
    PRCTAFIN integer = 0,
    PRPLANOGRPECO integer = 0,
    PREMPRESAGRPECO integer = 0,
    PRGRPECO integer = 0,
    PRELIMINACOESK300K315 integer = 0)
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(20),
    BDCODPLAPADRAO integer,
    BDCODCTA integer,
    BDCTALON varchar(40),
    BDNOMCTA varchar(300),
    BDTIPCTA integer,
    BDSEQCTA varchar(40),
    BDCODCENTROS integer,
    BDCODTPCC integer,
    BDNOMTPCC varchar(80),
    BDSALANT numeric(15,2),
    BDSAL_ANT_DEB numeric(15,2),
    BDSAL_ANT_CRE numeric(15,2),
    BDSALMOV numeric(15,2),
    BDSALDO_DEB numeric(15,2),
    BDSALDO_CRE numeric(15,2),
    BDSALATU numeric(15,2),
    BDFORMULA varchar(1024),
    BDCODEMPFILIAL integer,
    BDGRPCTA integer,
    BDAPECTA varchar(20),
    BDPERTENCECONTA integer,
    BDCLANOM varchar(315))
as
declare variable WCODEMP integer;
declare variable WCODPLAPADRAO integer;
declare variable WCODCENTROS integer;
declare variable WCODCTAINI integer;
declare variable WCODCTAFIN integer;
declare variable WSQLEMP varchar(4096);
declare variable WSQL varchar(1024);
declare variable WCTALONATIVO varchar(40);
declare variable WCTALONPATLIQ varchar(40);
declare variable WDATAHORA varchar(30);
declare variable WFIND smallint;
declare variable WPARTICIPANTE integer;
declare variable WPOS integer;
declare variable WCODPARTICIPANTE integer;
declare variable WRELCONTA integer;
declare variable WCCPART DM_LISTA;
declare variable WCODEMPREENDIMENTO integer;
declare variable WCODUNIDIMOB integer;
declare variable WDESCEMPREENDIMENTO varchar(500);
declare variable WDESCUNIDIMOB varchar(500);
declare variable WCADINCORP integer;
declare variable WRAIZCTASEMEMPREENDIMENTO varchar(40);
declare variable WRAIZCTASEMEMPREENDIMENTOANT varchar(40);
declare variable WNOMCTA varchar(100);
declare variable WCTALONANT varchar(40);
BEGIN
  -- sql referente as empresas selecionadas
  wsqlemp = 'select bdcodemp, bdcodmatriz, bdcodplapadrao,  bdcodcentros from vw_empresas_ref_atual where bdcodemp in ('||prcodemp||') order by bdcodmatriz,  bdcodemp';
  -- laco das empresas selecionadas
  wdatahora = localtimestamp;

  FOR EXECUTE STATEMENT wsqlemp
      INTO :wcodemp, :bdcodmatriz, :wcodplapadrao, :wcodcentros DO
      BEGIN

        -- retorna a primeira conta do ativo
        SELECT FIRST 1 planos_tpla.bdcodtpla, planos_tpla.bdctalon FROM planos_tpla
        WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
        AND planos_tpla.bdctalon = :prctalonini
        ORDER BY planos_tpla.bdctalon ASC INTO :wcodctaini, :wctalonativo;

        -- retorna a primeira conta do passivo a descoberto
        SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
        WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
        AND planos_tpla.bdctalon = :prctalonpas
        ORDER BY planos_tpla.bdctalon ASC INTO :wctalonpatliq;

        -- retorna a ultima conta do resto do plano
        wsql = 'select first 1 planos_tpla.bdcodtpla from planos_tpla ';
        wsql = wsql||'where planos_tpla.bdcodplapadrao = '||wcodplapadrao;
        wsql = wsql||' and substring(planos_tpla.bdctalon from 1 for '||strlen(prctalonfin)||') = '''||prctalonfin||'''';
        wsql = wsql||'order by planos_tpla.bdctalon desc';
        EXECUTE STATEMENT wsql INTO :wcodctafin;

        if (PRGRPECO > 0) then
          begin
            :wcodctaini = :prctaini;
            :wcodctafin = :prctafin;
          end

        -- sql responsavel pela limpeza da tabela cache de saldos
--        delete from VSUC_EMPRESAS_TBALANCETE;
        DELETE FROM VSUC_EMPRESAS_TBALANCETE_3 WHERE bdcodemp <> 0;

        IF ((prlistacc IS NULL) OR (TRIM(prlistacc) = '')) THEN
           BEGIN
             FOR SELECT tsal.codemp, tsal.codplapadrao, tsal.conta, tsal.classificacao, tsal.nomeconta, tsal.tipconta,
                        tsal.saldo_anterior, tsal.saldo_ant_deb, tsal.saldo_ant_cre, tsal.saldo_atual, tsal.saldo_deb, tsal.saldo_cre,
                        tref.bdnomemp, temp.bdcnpjemp, tsal.formula, tsal.clanom, tsal.participante, tsal.GRUPOCONTA, tsal.apecta, tsal.pertenceconta, tsal.relconta
                 FROM VSUC_SP_RETORNA_SALDO_CONTAS_X(:wcodemp, :wcodctaini, :wcodctafin, :prdatini, :prdatfin, :prindice, :prignzer, :bdcodtpcc, :wcodplapadrao,0,
                                                     :prnaomostracontacomp,:prconsolidada, :prniveisconta,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado,0,
                                                     0, 0, :PRPLANOGRPECO, :PREMPRESAGRPECO, :PRGRPECO,0,'', :PRELIMINACOESK300K315) tsal
                 LEFT OUTER JOIN tempresas temp ON (temp.bdcodemp = tsal.codemp)
                 LEFT OUTER JOIN tempresas_ref tref ON (tref.bdcodemp = temp.bdcodemp)
                 WHERE tref.bdrefemp = (SELECT FIRST 1 tempresas_ref.bdrefemp FROM tempresas_ref
                                        WHERE tempresas_ref.bdcodemp = temp.bdcodemp
                                        AND tempresas_ref.bdrefemp <= :prrefemp
                                        ORDER BY tempresas_ref.bdrefemp DESC)
                 INTO :bdcodemp, :bdcodplapadrao, :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta,
                      :bdsalant, :bdsal_ant_deb, :bdsal_ant_cre, :bdsalatu, :bdsaldo_deb, :bdsaldo_cre,
                      :bdnomemp, :bdcnpjemp, :bdformula, :bdclanom, :wparticipante, :bdgrpcta, :bdapecta, :BDPERTENCECONTA, :wrelconta DO
             BEGIN

               --alt:11586 - Precisa retornar zero pra quando vai imprimir sem CC e as linhas de espaço entre títulos. Como Null estava dando problema na ordenação. Pedro
               bdcodtpcc = 0;

               bdcodempfilial = bdcodemp;

               SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
               IF (wpos <> 0) THEN
                  BEGIN
                    IF (bdcodmatriz IS NULL) THEN
                       bdcodmatriz = bdcodemp;

                    bdcodemp = bdcodmatriz;
                  END
               bdsalmov = bdsalatu - bdsalant;

               IF (SUBSTRING(bdctalon FROM 1 FOR strlen(wctalonativo)) = wctalonativo) THEN
                  bdseqcta = 'ATIVO';
               ELSE
                 IF (SUBSTRING(bdctalon FROM 1 FOR strlen(wctalonpatliq)) = wctalonpatliq) THEN
                   bdseqcta = 'PASSIVO A DESCOBERTO';
                 ELSE
                 --Verifica o grupo da conta para saber se deve exibir ou excluir. (o que tem o "DEL" é deletado pelo Delphi). Pedro
                 IF ((wrelconta = 0) OR (wrelconta IS NULL)) THEN
                    bdseqcta = 'X';
                 ELSE
                    bdseqcta = 'DEL';

               -- Detalhado por participante
               IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdtipcta = 1)) THEN
                 BEGIN
                   --#alt:17868. Adicionado parâmetro para agrupar por CNPJ. Ana - 12/05/2017
                   FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdsaldo_atual, tsalctapar.bdsaldo_anterior, tsalctapar.bdcodparticipante
                       FROM vsuc_sp_retorna_saldos_ctaparty(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,:prignzer,0,0,:prcodemp,
                                                            :prcontabilizacao,:pragruparparticipanteporcnpj,'', 0, :pragruparparticipanteporcpf, 0, 0,
                                                            :PRREFEMP,'','',:PREMPRESAGRPECO, :PRGRPECO, :PRELIMINACOESK300K315) tsalctapar
                       -- Fim
                       INTO :bdnomcta, :bdctalon, :bdsalatu, :bdsalant, :wcodparticipante DO
                       BEGIN
                         bdclanom = SUBSTRING(bdctalon FROM 1 FOR strlen(bdctalon)-10)||' '||bdnomcta;
                         IF (prconcatenacodparticipante = 1) THEN
                           BEGIN
                             wpos     = CHARACTER_LENGTH(:wcodparticipante);
                                        -- 100 -> máximo de caracteres para nome da conta
                                        -- 003 -> qtd de caracteres " - ";
                             wpos     = ((100 - wpos) - 3);
                             bdnomcta = wcodparticipante||' - '||SUBSTRING(bdnomcta FROM 1 FOR wpos);
                           END

                         bdsalmov = bdsalatu - bdsalant;
                         SUSPEND;
                       END
                 END
               ELSE
                 BEGIN
                   wcadincorp = 0;
                   --Detalhado por incorporadora
                   IF ((prdetalharempreendimento = 1) OR (prdetalharunidimob = 1)) THEN
                     BEGIN
                       wnomcta = bdnomcta;
                       IF (wctalonant IS NULL) THEN
                         wctalonant = bdctalon;

                       --Carlos Machado - #alt:123617 - 19/08/2019
                       if (BDTIPCTA = 0) then
                        BEGIN
                           wcadincorp = 1;
                           IF ((NOT prconsolidada IS NULL AND prconsolidada <> 0) or (bdtipcta = 2)) THEN
                             SUSPEND;
                           ELSE
                             BEGIN
                               SELECT bdresult FROM vsuc_sp_consolidada(:bdcodplapadrao, :bdctalon) INTO :wfind;
                               IF ((wfind IS NULL) OR (wfind = 0)) THEN
                                 SUSPEND;
                               ELSE
                                 wcadincorp = 0;
                             END    
                        END

                       FOR SELECT tsalctaincorp.bdclassificacao, tsalctaincorp.bdsaldo_deb, tsalctaincorp.bdsaldo_ant_deb, tsalctaincorp.bdsaldo_cre, tsalctaincorp.bdsaldo_ant_cre,
                              tsalctaincorp.bdsaldo_atual, tsalctaincorp.bdsaldo_anterior, tsalctaincorp.bdmovimento, tsalctaincorp.bdcodempreendimento, tsalctaincorp.bdcodunidimob,
                              tsalctaincorp.bddescempreendimento, tsalctaincorp.bddescunidimob, tsalctaincorp.BDRAIZCTASEMEMPREENDIMENTO
                           FROM VSUC_SP_RETORNA_SALDOS_INCORP_2(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,:PRIGNZER,
                                                                0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :wctalonant, :bdtipcta, :wraizctasemempreendimentoant,
                                                                :prdetalharempreendimento, :prdetalharunidimob, :prmostrarprop) tsalctaincorp
                           INTO :bdctalon, :bdsaldo_deb, :bdsal_ant_deb, :bdsaldo_cre, :bdsal_ant_cre, :bdsalatu, :bdsalant, :BDSALMOV,
                                :wcodempreendimento, :wcodunidimob,:wdescempreendimento, :wdescunidimob, :WRAIZCTASEMEMPREENDIMENTO DO
                           BEGIN
--                            IF ((bdtipcta = 0) AND (wdescempreendimento IS NOT NULL)) THEN
--                              bdnomcta = bdnomcta||' ('||wdescempreendimento||')';

--                            IF (wcodunidimob IS NOT NULL) THEN
--                              bdnomcta = bdnomcta||' ('||wdescunidimob||')';

                              IF ((bdtipcta = 0) AND (wdescempreendimento IS NOT NULL)) THEN
                                bdnomcta = SUBSTRING(COALESCE(bdnomcta, '') || ' (' || COALESCE(wdescempreendimento, '')
                                                     FROM 1 FOR 299) || ')';

                              IF (wcodunidimob IS NOT NULL) THEN
                                bdnomcta = SUBSTRING(COALESCE(bdnomcta, '') || ' (' || COALESCE(wdescunidimob, '')
                                                     FROM 1 FOR 299) || ')';

                             IF (wraizctasemempreendimento IS NOT NULL) THEN
                               wraizctasemempreendimentoant = wraizctasemempreendimento;

                             SUSPEND;

                             wcadincorp = 1;
                             bdnomcta = wnomcta;
                           END
                     END
                   if (WCADINCORP = 0) then
                    BEGIN
                       IF ((NOT prconsolidada IS NULL AND prconsolidada <> 0) or (bdtipcta = 2)) THEN
                         SUSPEND;
                       ELSE
                         BEGIN
                           SELECT bdresult FROM vsuc_sp_consolidada(:bdcodplapadrao, :bdctalon) INTO :wfind;
                           IF ((wfind IS NULL) OR (wfind = 0)) THEN
                             SUSPEND;
                         END    
                    END
                   IF (bdtipcta = 0) THEN
                     wctalonant = bdctalon;
                END
             END
           END
        ELSE
           BEGIN
             WCCPART = '<'; --Machado - 04/01/2019 - Alterado para detalhar CC com participante - #91350
             FOR SELECT tsal.bdcodemp, tsal.bdcodplapadrao, tsal.bdconta, tsal.bdclassificacao, tsal.bdnomeconta, tsal.bdtipconta,
                        tsal.bdsaldo_anterior, tsal.bdsaldo_ant_deb, tsal.bdsaldo_ant_cre, tsal.bdsaldo_atual, tsal.bdsaldo_deb, tsal.bdsaldo_cre,
                        tref.bdnomemp, temp.bdcnpjemp, tsal.bdformula, tsal.bdclanom, tsal.bdparticipante, tsal.bdGRUPOCONTA, tsal.bdapecta, tsal.bdpertenceconta, tsal.bdrelconta,
                        COALESCE(tsal.bdcodtpcc, 0), tsal.bdnomtpcc, tref.bdcodcentros
                 FROM vsuc_sp_retorna_saldo_contas_xz(:wcodemp, :wcodctaini, :wcodctafin, :prdatini, :prdatfin, :prindice, :prignzer, :prlistacc, :wcodplapadrao,:prsemcc,
                                                      0, :prnaomostracontacomp,:prconsolidada, :prniveisconta,:prcontabilizacao,:prmatrizfilialconsolidado,0,0,0,0,'','',
                                                      :PRELIMINACOESK300K315) tsal
                 LEFT OUTER JOIN tempresas temp ON (temp.bdcodemp = tsal.bdcodemp)
                 LEFT OUTER JOIN tempresas_ref tref ON (tref.bdcodemp = temp.bdcodemp)
                 WHERE tref.bdrefemp = (SELECT FIRST 1 tempresas_ref.bdrefemp FROM tempresas_ref
                                        WHERE tempresas_ref.bdcodemp = temp.bdcodemp
                                        AND tempresas_ref.bdrefemp <= :prrefemp
                                        ORDER BY tempresas_ref.bdrefemp DESC)
                 INTO :bdcodemp, :bdcodplapadrao, :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta,
                      :bdsalant, :bdsal_ant_deb, :bdsal_ant_cre, :bdsalatu, :bdsaldo_deb, :bdsaldo_cre,
                      :bdnomemp, :bdcnpjemp, :bdformula, :bdclanom, :wparticipante, :bdgrpcta, :bdapecta, :BDPERTENCECONTA, :wrelconta, :bdcodtpcc, :bdnomtpcc, :bdcodcentros DO
             BEGIN

               bdcodempfilial = bdcodemp;
               SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
               IF (wpos <> 0) THEN
                  BEGIN
                    IF (bdcodmatriz IS NULL) THEN
                       bdcodmatriz = bdcodemp;

                    bdcodemp = bdcodmatriz;
                  END
               bdsalmov = bdsalatu - bdsalant;

               IF (SUBSTRING(bdctalon FROM 1 FOR strlen(wctalonativo)) = wctalonativo) THEN
                  bdseqcta = 'ATIVO';
               ELSE
                 IF (SUBSTRING(bdctalon FROM 1 FOR strlen(wctalonpatliq)) = wctalonpatliq) THEN
                   bdseqcta = 'PASSIVO A DESCOBERTO';
                 ELSE
                 --Verifica o grupo da conta para saber se deve exibir ou excluir. (o que tem o "DEL" é deletado pelo Delphi)
                 IF ((wrelconta = 0) OR (wrelconta IS NULL)) THEN
                    bdseqcta = 'X';
                 ELSE
                    bdseqcta = 'DEL';

               -- Detalhado por participante
               IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdtipcta = 1)) THEN
                 BEGIN
                   IF (POSITION('<'||BDCODCTA||'>', WCCPART) <= 0) THEN
                     BEGIN
                       WCCPART = WCCPART||bdcodcta||'><';
                       --#alt:17868. Adicionado parâmetro para agrupar por CNPJ. Ana - 12/05/2017
                       FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdsaldo_atual, tsalctapar.bdsaldo_anterior, tsalctapar.bdcodparticipante, BDCENTROCUSTO
                           FROM vsuc_sp_retorna_saldos_ctaparty(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,
                                                                :prignzer,0,0,:prcodemp,:prcontabilizacao,:pragruparparticipanteporcnpj, 
                                                                :PRLISTACC, :PRSEMCC, 0, 0, 0, :PRREFEMP, '', '', :PREMPRESAGRPECO, :PRGRPECO, :PRELIMINACOESK300K315) tsalctapar
                           -- Fim
                           INTO :bdnomcta, :bdctalon, :bdsalatu, :bdsalant, :wcodparticipante, :BDCODTPCC DO
                           BEGIN
                           bdclanom = SUBSTRING(bdctalon FROM 1 FOR strlen(bdctalon)-10)||' '||bdnomcta;
                             IF (prconcatenacodparticipante = 1) THEN
                               BEGIN
                                 wpos     = CHARACTER_LENGTH(:wcodparticipante);
                                            -- 100 -> máximo de caracteres para nome da conta
                                            -- 003 -> qtd de caracteres " - ";
                                 wpos     = ((100 - wpos) - 3);
                                 bdnomcta = wcodparticipante||' - '||SUBSTRING(bdnomcta FROM 1 FOR wpos);
                               END
    
                             bdsalmov = bdsalatu - bdsalant;
                             SUSPEND;
                           END
                     END
                 END
               ELSE
                 BEGIN        
                   wcadincorp = 0;
                   --Detalhado por incorporadora
                   if (((prdetalharempreendimento = 1) or (prdetalharunidimob = 1)) and ((PRSEMCC = 1) or (bdcodtpcc > 0) )) then
                     BEGIN
                       wnomcta = bdnomcta;
                       IF (wctalonant IS NULL) THEN
                         wctalonant = bdctalon;

                       --Carlos Machado - #alt:123617 - 19/08/2019
                       if (BDTIPCTA = 0) then
                        BEGIN
                           wcadincorp = 1;
                           IF ((NOT prconsolidada IS NULL AND prconsolidada <> 0) or (bdtipcta = 2)) THEN
                             SUSPEND;
                           ELSE
                             BEGIN
                               SELECT bdresult FROM vsuc_sp_consolidada(:bdcodplapadrao, :bdctalon) INTO :wfind;
                               IF ((wfind IS NULL) OR (wfind = 0)) THEN
                                 SUSPEND;
                               ELSE
                                 wcadincorp = 0;
                             END    
                        END

                       FOR SELECT tsalctaincorp.bdclassificacao, tsalctaincorp.bdsaldo_deb, tsalctaincorp.bdsaldo_ant_deb, tsalctaincorp.bdsaldo_cre, tsalctaincorp.bdsaldo_ant_cre,
                              tsalctaincorp.bdsaldo_atual, tsalctaincorp.bdsaldo_anterior, tsalctaincorp.bdmovimento, tsalctaincorp.bdcodempreendimento, tsalctaincorp.bdcodunidimob,
                              tsalctaincorp.bddescempreendimento, tsalctaincorp.bddescunidimob, tsalctaincorp.BDRAIZCTASEMEMPREENDIMENTO
                           FROM VSUC_SP_RETORNA_SALDOS_INCORP_2(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,:PRIGNZER,
                                                                0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :wctalonant, :bdtipcta, :wraizctasemempreendimentoant,
                                                                :prdetalharempreendimento, :prdetalharunidimob, :prmostrarprop, :bdcodtpcc, :PRSEMCC) tsalctaincorp
                           INTO :bdctalon, :bdsaldo_deb, :bdsal_ant_deb, :bdsaldo_cre, :bdsal_ant_cre, :bdsalatu, :bdsalant, :BDSALMOV,
                                :wcodempreendimento, :wcodunidimob,:wdescempreendimento, :wdescunidimob, :WRAIZCTASEMEMPREENDIMENTO DO
                           BEGIN
--                            IF ((bdtipcta = 0) AND (wdescempreendimento IS NOT NULL)) THEN
--                              bdnomcta = bdnomcta||' ('||wdescempreendimento||')';

--                            IF (wcodunidimob IS NOT NULL) THEN
--                              bdnomcta = bdnomcta||' ('||wdescunidimob||')';

                              IF ((bdtipcta = 0) AND (wdescempreendimento IS NOT NULL)) THEN
                                bdnomcta = SUBSTRING(COALESCE(bdnomcta, '') || ' (' || COALESCE(wdescempreendimento, '')
                                                     FROM 1 FOR 299) || ')';

                              IF (wcodunidimob IS NOT NULL) THEN
                                bdnomcta = SUBSTRING(COALESCE(bdnomcta, '') || ' (' || COALESCE(wdescunidimob, '')
                                                     FROM 1 FOR 299) || ')';

                             IF (wraizctasemempreendimento IS NOT NULL) THEN
                               wraizctasemempreendimentoant = wraizctasemempreendimento;
                             SELECT BDRPOS FROM RPOS('.', :BDCTALON) INTO :WPOS;
                             IF (BDTIPCTA = 1) THEN
                               bdclanom = SUBSTRING(BDCTALON FROM 1 FOR WPOS - 1)||' '||bdnomcta;
                             ELSE
                               bdclanom = BDCTALON;

                             SUSPEND;

                             wcadincorp = 1;
                             bdnomcta = wnomcta;
                           END
                     END
                   if (WCADINCORP = 0) then
                    BEGIN
                       IF ((NOT prconsolidada IS NULL AND prconsolidada <> 0) or (bdtipcta = 2)) THEN
                         SUSPEND;
                       ELSE
                         BEGIN
                           SELECT bdresult FROM vsuc_sp_consolidada(:bdcodplapadrao, :bdctalon) INTO :wfind;
                           IF ((wfind IS NULL) OR (wfind = 0)) THEN
                             SUSPEND;
                         END
                    END
                   
                   IF (bdtipcta = 0) THEN
                     wctalonant = bdctalon;
                 END
             END
           END
      END
END
^

/* Restore proc. body: VSUC_SP_CONCILIACAO_AUTOMATICA */
ALTER PROCEDURE VSUC_SP_CONCILIACAO_AUTOMATICA(PRCODEMP INTEGER,
PRCODCTA INTEGER,
PRCODCLIFOR INTEGER,
PRCODPLAPADRAO INTEGER,
PRDOCTO VARCHAR(15),
PRCONTABILIZACAO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCHAVE INTEGER,
BDCODPLAPADRAO INTEGER,
BDDEBITO INTEGER,
BDCODTERCEIROD INTEGER,
BDCONCD VARCHAR(5),
BDCREDITO INTEGER,
BDCODTERCEIROC INTEGER,
BDCONCC VARCHAR(5),
BDVALOR NUMERIC(15,2),
BDLOTE VARCHAR(10),
BDCOMPL VARCHAR(200),
BDDCTO VARCHAR(15))
 AS
DECLARE VARIABLE WSQL VARCHAR(2000);
DECLARE VARIABLE WSQLAUX VARCHAR(2000);
DECLARE VARIABLE WVALORD NUMERIC(15,2);
DECLARE VARIABLE WVALORC NUMERIC(15,2);
DECLARE VARIABLE WCONCC VARCHAR(5);
DECLARE VARIABLE WCONCD VARCHAR(5);
BEGIN
  bdcodemp       = prcodemp;
  bdcodplapadrao = prcodplapadrao;
  wvalord = 0;
  wvalorc = 0;

  --alt:17706 - 03/05/2017 - Criado tratamento no documento para desconsiderar números/caracteres depois dos símbolos "/", "\" ou "-". Pedro
  prDOCTO = UPPER(SUBSTRING(prDOCTO FROM 1 FOR
                            CASE WHEN (prDOCTO CONTAINING '/') THEN POSITION('/', prDOCTO) -1
                                 WHEN (prDOCTO CONTAINING '\') THEN POSITION('\', prDOCTO) -1
                                 WHEN (prDOCTO CONTAINING '-') THEN POSITION('-', prDOCTO) -1
                            ELSE CHAR_LENGTH(prDOCTO) END));

  -- Soma os valores a débitos
  wsql = '';
  /*Carlos Mello(09/05/2013) - Solicitação.: 5660.
  Foi utilizado o -0.005 para funcionar corretamente o arredondamento, pois não quero que arredonde pra cima e nem pra baixo.
  Ex.: 1.999 ficaria 2.00 -> Mas na realidade quero 1.99, ou seja, 1.999 - 0.005 = 1.994 com o arredondamento fica 1.99
       1.994 ficaria 1.99 -> No arredondademto vai ficar 1.994 - 0.005 = 1.989 com arredondamento fica 1.99*/
  --wsql = wsql||'select Round(SUM(tlan.bdvalor),2) ';
  wsql = wsql||'select cast(SUM(tlan.bdvalor) - 0.005 as numeric(15,2)) ';
  wsql = wsql||'from vsuc_empresas_tlan tlan ';
  wsql = wsql||'where ';
  wsql = wsql||'(tlan.bdcodemp in ('||:prcodemp||')) and ';
  wsql = wsql||'(tlan.bdcodplapadrao = '||:prcodplapadrao||') and ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'(tlan.bdcontabilizacao in (0,'||:prcontabilizacao||')) and ';
  wsql = wsql||'(bddebito = '||:prcodcta||') and ';
  wsql = wsql||'((tlan.bdconcd is null) or (UPPER(tlan.bdconcd) = '''||'FALSE'||''')) and ';
  --alt:17706 - 03/05/2017 - Criado tratamento no documento para desconsiderar números/caracteres depois dos símbolos "/", "\" ou "-". Pedro
  --wsql = wsql||'(UPPER(tlan.bddcto) = UPPER('''||:prdocto||''')) and ';
  wsql = wsql||'(Upper(Substring(bddcto from 1 for';
  wsql = wsql||' case when (bddcto containing '''||'/'||''') then position('''||'/'||''', bddcto) -1';
  wsql = wsql||'      when (bddcto containing '''||'\'||''') then position('''||'\'||''', bddcto) -1';
  wsql = wsql||'      when (bddcto containing '''||'-'||''') then position('''||'-'||''', bddcto) -1';
  wsql = wsql||' else char_length(bddcto) end)) = '''||:prDocto||''') and ';
  IF ((prcodclifor = 0) OR (prcodclifor IS NULL)) THEN
    wsql = wsql||'((tlan.bdcodterceirod = 0) or (tlan.bdcodterceirod is null))';
  ELSE
    wsql = wsql||'(tlan.bdcodterceirod = '||:prcodclifor||')';
  EXECUTE STATEMENT wsql INTO :wvalord;

  -- Soma os valores a créditos
  wsql = '';
  --Carlos Mello(09/05/2013) - Solicitação.: 5660.
  --wsql = wsql||'select Round(SUM(tlan.bdvalor),2) ';
  wsql = wsql||'select cast(SUM(tlan.bdvalor) - 0.005 as numeric(15,2)) ';
  wsql = wsql||'from vsuc_empresas_tlan tlan ';
  wsql = wsql||'where ';
  wsql = wsql||'(tlan.bdcodemp in ('||:prcodemp||')) and ';
  wsql = wsql||'(tlan.bdcodplapadrao = '||:prcodplapadrao||') and ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'(tlan.bdcontabilizacao in (0,'||:prcontabilizacao||')) and ';
  wsql = wsql||'(bdcredito = '||:prcodcta||') and ';
  wsql = wsql||'((tlan.bdconcc is null) or (UPPER(tlan.bdconcc) = '''||'FALSE'||''')) and ';
  --alt:17706 - 03/05/2017 - Criado tratamento no documento para desconsiderar números/caracteres depois dos símbolos "/", "\" ou "-". Pedro
  --wsql = wsql||'(UPPER(tlan.bddcto) = UPPER('''||:prdocto||''')) and ';
  wsql = wsql||'(Upper(Substring(bddcto from 1 for';
  wsql = wsql||' case when (bddcto containing '''||'/'||''') then position('''||'/'||''', bddcto) -1';
  wsql = wsql||'      when (bddcto containing '''||'\'||''') then position('''||'\'||''', bddcto) -1';
  wsql = wsql||'      when (bddcto containing '''||'-'||''') then position('''||'-'||''', bddcto) -1';
  wsql = wsql||' else char_length(bddcto) end)) = '''||:prDocto||''') and ';
  IF ((prcodclifor = 0) OR (prcodclifor IS NULL) ) THEN
    wsql = wsql||'((tlan.bdcodterceiroc = 0) or (tlan.bdcodterceiroc is null))';
  ELSE
    wsql = wsql||'(tlan.bdcodterceiroc = '||:prcodclifor||')';
  EXECUTE STATEMENT wsql INTO :wvalorc;

  /*
  /alt:14942 - 25/01/2017 - Sempre que alterar uma regra de conciliação, alterar também no uConciliacaoClientesFornecedores > SetConciliacaoCliFor e
  /    SetConciliacaoEmMemoria, uConsultaLancamento, uConsultaRazaoVideo e as procedures VSUC_SP_CONCILIACAO e VSUC_SP_CONCILIACAO_AUTOMATICA. Pedro
  */

  -- Verifica se os valores a debito e a credito são iguais para gerar a conciliação
  IF (((wvalord > 0) OR (wvalorc > 0)) AND
      ((wvalord - wvalorc) = 0)) THEN
    BEGIN
      wsql = '';
      wsql = wsql||'select tlan.bdchave, tlan.bddebito, tlan.bdcodterceirod, Upper(tlan.bdconcd) bdconcd, ';
      --Carlos Mello(09/05/2013) - Solicitação.: 5660.
      --wsql = wsql||'tlan.bdcredito, tlan.bdcodterceiroc, Upper(tlan.bdconcc) bdconcc, Round(tlan.bdvalor,2), ';
      wsql = wsql||'tlan.bdcredito, tlan.bdcodterceiroc, Upper(tlan.bdconcc) bdconcc,  cast(tlan.bdvalor - 0.005 as numeric(15,2)), ';
      wsql = wsql||'tlan.bdlote, tlan.bdcompl, tlan.bddcto ';
      wsql = wsql||'from vsuc_empresas_tlan tlan ';
      wsql = wsql||'where ';
      wsql = wsql||'(tlan.bdcodemp in ('||:prcodemp||')) and ';
      wsql = wsql||'(tlan.bdcodplapadrao = '||:prcodplapadrao||') and ';
      --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
      IF (prcontabilizacao <> 99) THEN
        wsql = wsql||'(tlan.bdcontabilizacao in (0,'||:prcontabilizacao||')) and ';
      wsql = wsql||'((tlan.bddebito = '||:prcodcta||') or (tlan.bdcredito = '||:prcodcta||')) and ';
      wsql = wsql||'(((tlan.bdconcd is null) or (UPPER(tlan.bdconcd) = '''||'FALSE'||''')) or ';
      wsql = wsql||' ((tlan.bdconcc is null) or (UPPER(tlan.bdconcc) = '''||'FALSE'||'''))) and ';
      --alt:17706 - 03/05/2017 - Criado tratamento no documento para desconsiderar números/caracteres depois dos símbolos "/", "\" ou "-". Pedro
      --wsql = wsql||'(UPPER(tlan.bddcto) = UPPER('''||:prdocto||''')) and ';
      wsql = wsql||'(Upper(Substring(bddcto from 1 for';
      wsql = wsql||' case when (bddcto containing '''||'/'||''') then position('''||'/'||''', bddcto) -1';
      wsql = wsql||'      when (bddcto containing '''||'\'||''') then position('''||'\'||''', bddcto) -1';
      wsql = wsql||'      when (bddcto containing '''||'-'||''') then position('''||'-'||''', bddcto) -1';
      wsql = wsql||' else char_length(bddcto) end)) = '''||:prDocto||''') and ';
      --#alt:16587 - Adicionado controle para o participante, estava conciliando quando o documento era igual mas os participantes diferentes. Ana - 16/12/2016
      IF ((prcodclifor = 0) OR (prcodclifor IS NULL)) THEN
        wsql = wsql||'(((tlan.bdcodterceirod = 0) or (tlan.bdcodterceirod is null)) or ((tlan.bdcodterceiroc = 0) or (tlan.bdcodterceiroc is null)))';
      ELSE
        wsql = wsql||'((tlan.bdcodterceirod = '||:prcodclifor||') or (tlan.bdcodterceiroc = '||:prcodclifor||'))';
      wsql = wsql||'order by tlan.bdvalor';

      /*
      /alt:14942 - 25/01/2017 - Sempre que alterar uma regra de conciliação, alterar também no uConciliacaoClientesFornecedores > SetConciliacaoCliFor e
      /    SetConciliacaoEmMemoria, uConsultaLancamento, uConsultaRazaoVideo e as procedures VSUC_SP_CONCILIACAO e VSUC_SP_CONCILIACAO_AUTOMATICA. Pedro
      */

      -- Altera e retorna os lançamentos conciliados
      FOR EXECUTE STATEMENT wsql
          INTO :bdchave,:bddebito,:bdcodterceirod,:bdconcd,:bdcredito,:bdcodterceiroc,:bdconcc,
               :bdvalor,:bdlote,:bdcompl,:bddcto DO
          BEGIN
            IF ((bddebito = prcodcta) AND
                ((bdconcd IS NULL) OR (bdconcd = 'FALSE')) AND
                (((prcodclifor = 0) OR (prcodclifor IS NULL)) OR (prcodclifor = bdcodterceirod))) THEN -- concilia lançamentos a debito
              BEGIN
                wsqlaux = 'update vsuc_empresas_tlan tlan set tlan.bdconcd = '''||'True'||''', ';
                --#alt:13456 - Adicionada atribuição ao indice do tipo de conciliação. Ana - 28/10/2016
                --alt:14942 - 27/01/2016 - Alterado para já definir aqui o código do tipo de conciliação, assim, não precisa percorrer novamente a tabela como estava na rotina abaixo. Pedro
                wsqlaux = wsqlaux||'bdtipoconc = case when Upper(BDCONCC) = '''||'TRUE'||''' then 6 else 4 end ';
                wsqlaux = wsqlaux||'where (bdcodemp = '||:prcodemp||')';
                wsqlaux = wsqlaux||'  and (bdcodplapadrao = '||:prcodplapadrao||')';
                --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
                IF (prcontabilizacao <> 99) THEN
                  wsqlaux = wsqlaux||' and (tlan.bdcontabilizacao in (0,'||:prcontabilizacao||'))';
                wsqlaux = wsqlaux||' and (tlan.bdchave = '||:bdchave||')';
                EXECUTE STATEMENT wsqlaux;
                bdconcd = 'True';
                SUSPEND;
              END
            ELSE
              IF ((bdcredito = prcodcta) AND
                  ((bdconcc IS NULL) OR (bdconcc = 'FALSE')) AND
                  (((prcodclifor = 0) OR (prcodclifor IS NULL)) OR (prcodclifor = bdcodterceiroc))) THEN -- concilia lançamentos a credito
                BEGIN
                  wsqlaux = 'update vsuc_empresas_tlan set bdconcc = '''||'TRUE'||''', ';
                  --#alt:13456 - Adicionada atribuição ao indice do tipo de conciliação. Ana - 28/10/2016
                  --alt:14942 - 27/01/2016 - Alterado para já definir aqui o código do tipo de conciliação, assim, não precisa percorrer novamente a tabela como estava na rotina abaixo. Pedro
                  wsqlaux = wsqlaux||'bdtipoconc = case when Upper(BDCONCD) = '''||'TRUE'||''' then 6 else 5 end ';
                  wsqlaux = wsqlaux||'where (bdcodemp = '||:prcodemp||')';
                  wsqlaux = wsqlaux||'  and (bdcodplapadrao = '||:prcodplapadrao||')';
                  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
                  IF (prcontabilizacao <> 99) THEN
                    wsqlaux = wsqlaux||' and (bdcontabilizacao in (0,'||:prcontabilizacao||'))';
                  wsqlaux = wsqlaux||' and (bdchave = '||:bdchave||')';
                  EXECUTE STATEMENT wsqlaux;
                  bdconcc = 'True';
                  SUSPEND;
                END

             /*
             /alt:14942 - 25/01/2017 - Sempre que alterar uma regra de conciliação, alterar também no uConciliacaoClientesFornecedores > SetConciliacaoCliFor e
             /    SetConciliacaoEmMemoria, uConsultaLancamento, uConsultaRazaoVideo e as procedures VSUC_SP_CONCILIACAO e VSUC_SP_CONCILIACAO_AUTOMATICA. Pedro
             */

             /*alt:14942 - 27/01/2017 - Rotina desnecessária, retirada para melhoria de performance. Pedro
             --#alt:13456 - Adicionada verificação se os dois valores foram conciliados, tanto debito quanto crédito
             FOR SELECT bdconcc, bdconcd FROM vsuc_empresas_tlan
                 WHERE (bdcodemp = :prcodemp)
                 AND   (bdchave = :bdchave)
                 INTO :wConcc, :wConcd DO
                   BEGIN
                     IF ((SUBSTRING(upper(wConcc) from 1 for 1)= 'T') AND (SUBSTRING(upper(wConcd) from 1 for 1) = 'T')) THEN
                        UPDATE vsuc_empresas_tlan SET bdtipoconc = 6 WHERE (bdchave = :bdchave) AND (bdcodemp = :prcodemp);
                     SUSPEND;
                   END
             --#alt:13456. fim*/
          END
    END
END
^

/* Restore proc. body: VSUC_SP_CONSOLIDADA */
ALTER PROCEDURE VSUC_SP_CONSOLIDADA(PRCODPLAPADRAO INTEGER,
PRCTALON VARCHAR(40))
 RETURNS(BDRESULT SMALLINT)
 AS
DECLARE VARIABLE wctalon VARCHAR(40);
BEGIN
  bdresult = NULL;
  FOR SELECT bdctalon FROM planos_tpla
      WHERE bdcodplapadrao = :prcodplapadrao
      AND bdtipcta = 2 INTO :wctalon DO
      IF (SUBSTRING(prctalon FROM 1 FOR strlen(wctalon)) = wctalon) THEN
         BEGIN
           bdresult = 1;
           BREAK;
         END
  SUSPEND;
END
^

/* Restore proc. body: VSUC_SP_COPIA_CONTAS_FORMULAS */
ALTER PROCEDURE VSUC_SP_COPIA_CONTAS_FORMULAS(PRCODPFOR INTEGER,
PRCODPLAPADRAO INTEGER,
PRCLASS VARCHAR(30000))
 AS
DECLARE VARIABLE wctalon VARCHAR(40);
DECLARE VARIABLE wnomcta VARCHAR(40);
DECLARE VARIABLE wapecta VARCHAR(20);
DECLARE VARIABLE wtipcta SMALLINT;
DECLARE VARIABLE wsql VARCHAR(30000);
BEGIN

  wsql = 'select tpla.bdctalon, tpla.bdnomcta, tpla.bdapecta,  tpla.bdtipcta from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||prcodplapadrao||' and ('||prclass||')';

--  exception ex_date wsql;
--  wsql = wsql||'where bdCODPLAPADRAO = '||prcodplapadrao||' and ('||prclass||')';

--  execute statement wsql;
  FOR EXECUTE STATEMENT wsql
  INTO :wctalon,:wnomcta,:wapecta,:wtipcta DO
     BEGIN
        wnomcta = SUBSTRING(wnomcta FROM 1 FOR 65);
        INSERT INTO vsuc_base_tformula_tpfo (bdCODPFOR,bdCODFOR,bdCLAFOR,bdNOMFOR,bdAPEFOR,bdTIPFOR) VALUES
                                            (:prcodpfor,NULL,:wctalon,:wnomcta,:wapecta,:wtipcta);
     END

END
^

/* Restore proc. body: VSUC_SP_COPY_PREPARACAO_FOR_ECF_Y520 */
create or alter procedure VSUC_SP_COPY_PREPARACAO_FOR_ECF_Y520 (
    PRCODPLAPADRAOFORM integer,
    PRCODPLAPADRAO integer,
    PRCODPAIS integer,
    PRDE_ANO integer,
    PRPARA_ANO integer,
    PROPCAO integer,
    PRTIPOY520 integer,
    PRFORMAY520 integer)
as
declare variable WTIPOFOR integer;
declare variable WSQL varchar(10000);
declare variable WCODTFORREF integer;
declare variable WFORMULA varchar(20000);
BEGIN

   if (:PROPCAO = 0) then
      begin
        wSQL = 'delete from PLANOS_TFOR_ECF_Y520 where BDCODPLAFORPADRAOREF = '||:PRCODPLAPADRAOFORM||' and BDCODPLAPADRAO = '||:prCODPLAPADRAO||' and BDCODPAIS = '||:prCODPAIS||' and BDANO = '||:PRPARA_ANO;

        execute statement wsql;
      end

   wSQL = 'select BDCODTFORREF, BDDESCFOR, BDTIPOFOR from PLANOS_TFOR_ECF_Y520 F1 where ';
   wSQL = wSQL||'BDCODPLAFORPADRAOREF = '||:prcodplapadraoform||' and BDCODPLAPADRAO = '||:prCODPLAPADRAO||' and BDCODPAIS = '||:prCODPAIS||' and BDANO = '||:PRDE_ANO;
   if (propcao = 1) then
      begin
        wSQL = wSQL||' and not exists(select *';
        wSQL = wSQL||'  from PLANOS_TFOR_ECF_Y520 F2 where ';
        wSQL = wSQL||'  F2.BDCODPLAFORPADRAOREF = F1.BDCODPLAFORPADRAOREF and F2.BDCODPLAPADRAO = F1.BDCODPLAPADRAO and F2.BDCODTFORREF = F1.BDCODTFORREF and F2.BDCODPAIS = F1.BDCODPAIS and F2.BDTIPOY520 = F1.BDTIPOY520 and F2.BDFORMAY520 = F1.BDFORMAY520 and F2.BDANO =  '||:PRPARA_ANO||')';
      end

   FOR EXECUTE STATEMENT wSQL INTO :wCODTFORREF, :WFORMULA, :WTIPOFOR DO
     BEGIN
       update or insert into PLANOS_TFOR_ECF_Y520 (BDCODPLAFORPADRAOREF, BDCODTFORREF, BDCODPLAPADRAO, BDCODPAIS, BDANO, BDDESCFOR, BDTIPOFOR, BDTIPOY520, BDFORMAY520)
       values (:prcodplapadraoform,:wCODTFORREF,:prcodplapadrao,:prcodpais,:prpara_ano,:wformula,:wtipofor,:prtipoy520,:prformay520) matching(BDCODPLAFORPADRAOREF, BDCODTFORREF, BDCODPLAPADRAO, BDCODPAIS, BDANO, BDTIPOY520, BDFORMAY520);

    END

END
^

/* Restore proc. body: VSUC_SP_EXPORTA_SPED_I300 */
CREATE OR ALTER PROCEDURE VSUC_SP_EXPORTA_SPED_I300 (
    PRCODEMP VARCHAR(2048),
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRIGNORA_ZERAMENTO INTEGER,
    PRCODTPCC VARCHAR(8192),
    PRREFEMP INTEGER,
    PRLANSEMCC INTEGER,
    PRCONTABILIZACAO INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP VARCHAR(18),
    BDCODMATRIZ INTEGER,
    BDCODPLAPADRAO INTEGER,
    BDDATA DATE,
    BDCODCTA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDDEBITO NUMERIC(15,2),
    BDCREDITO NUMERIC(15,2),
    BDCODTPCC INTEGER,
    BDNOMTPCC VARCHAR(40),
    BDCODCENTROS INTEGER,
    BDCTALONCC VARCHAR(40))
AS
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WCONTA INTEGER;
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WCTALONANT VARCHAR(40);
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WDATAINI VARCHAR(10);
DECLARE VARIABLE WDATAFIM VARCHAR(10);
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WSQLINNER VARCHAR(10480);
DECLARE VARIABLE WNOMTER VARCHAR(100);
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WPARTICIPANTES VARCHAR(1048);
DECLARE VARIABLE WCTALONCC VARCHAR(40);
BEGIN
  --#152313 - 24/06/2021 - Carlos Machado - Alterado para detalhar por participante
  EXECUTE PROCEDURE sp_seta_competencia(prrefemp, NULL, NULL);
  -- retorna as empresas selecionadas
  wsql = 'select distinct(temp.bdcodemp), tref.bdnomemp, temp.bdcnpjemp, tref.bdcodplapadrao, temp.bdcodmatriz, TREF.BDCODCENTROS ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc';
  -- executa o sql das empresas
  FOR EXECUTE STATEMENT wsql
     INTO :bdcodemp, :bdnomemp, :bdcnpjemp, :bdcodplapadrao, :bdcodmatriz, :BDCODCENTROS DO
     BEGIN
       -- verifica se existe centro de custo selecionado
       IF ((prcodtpcc = '') OR (prcodtpcc IS NULL)) THEN
         BEGIN
           wparticipantes = '';
           wsql = 'Select tlan.bddata,tlan.bddebito,tpla.bdnomcta,tpla.bdctalon,tlan.bdvalor,tpla.BDPARTICIPANTE ';
           wsql = wsql||'from (Select bddata,bddebito,Sum(bdvalor) as bdvalor from VSUC_EMPRESAS_TLAN ';
           wsql = wsql||'      where ';
           --  1 -> Fiscal | 2 -> Societário | 99 -> Todos
           IF (prcontabilizacao <> 99) THEN
             wsql = wsql||'    (bdcontabilizacao in (0,'||prcontabilizacao||')) and ';
           wsql = wsql||'      (bddebito is not null) and ';
           wsql = wsql||'      (bddata between '''||prdataini||''' and '''||prdatafim||''') and ';
           wsql = wsql||'      (bdcodemp in ('||bdcodemp||'))';
           wsql = wsql||'      group by bdcodemp,bddata,bddebito) tlan ';
           wsql = wsql||'left outer join planos_tpla tpla on ((tpla.bdcodplapadrao = '||bdcodplapadrao||') and (tpla.bdcodtpla = tlan.bddebito)) ';

           FOR EXECUTE STATEMENT wsql  INTO wdata, wconta, wnomcta, wctalon , wvalor, wparticipante  DO
             BEGIN
               bdcodcta = wconta;   
               bdcredito = 0;
               if (wparticipante = 1) then
                begin
                   if (POSITION('<'||wconta||'>', wparticipantes) <= 0) then
                     begin
                       wparticipantes = wparticipantes||'<'||wconta||'>';
    
                       wsqlinner = 'Select tlan.bddata,tlan.BDCODTERCEIROD,tlan.bdvalor, tter.BDNOME ';
                       wsqlinner = wsqlinner||'from (Select bdcodemp,bddata,bdcredito,BDCODTERCEIROD, sum(bdvalor) as BDVALOR from VSUC_EMPRESAS_TLAN ';
                       wsqlinner = wsqlinner||'      where ';
                       --  1 -> Fiscal | 2 -> Societário | 99 -> Todos
                       IF (prcontabilizacao <> 99) THEN
                         wsqlinner = wsqlinner||'    (bdcontabilizacao in (0,'||prcontabilizacao||')) and ';
                       wsqlinner = wsqlinner||'      (bddebito = '||wconta||') and ';
                       wsqlinner = wsqlinner||'      (bddata between '''||prdataini||''' and '''||prdatafim||''') and ';
                       wsqlinner = wsqlinner||'      (bdcodemp in ('||bdcodemp||'))';
                       wsqlinner = wsqlinner||'      group by bdcodemp,bddata,bdcredito,BDCODTERCEIROD) tlan ';
                       wsqlinner = wsqlinner||'left outer join VW_TTERCEIRO_SIMPLES tter on ((tter.bdcodter = tlan.BDCODTERCEIROD)) ';
    
                       FOR EXECUTE STATEMENT wsqlinner  INTO wdata,wcodter, wvalor, wnomter DO
                         BEGIN
                          bddata = wdata;
                          bdctalon = wctalon;
                          bdnomcta = wnomter;
                          bddebito = wvalor;
    
                          if (wcodter > 0) then
                            begin
                              bdctalon = REVERSE(bdctalon);
                              bdctalon = SUBSTRING(bdctalon FROM POSITION('.', bdctalon) FOR strlen(bdctalon));
                              bdctalon = REVERSE(bdctalon);
                              wpos     =  CHARACTER_LENGTH(:bdctalon)-1;
                              bdctalon = bdctalon||LPAD(wcodter, 9, '0');
                            end
    
                          SUSPEND;
                         END
                     end
                end
               else
                begin
                  bddata = wdata;
                  bdctalon = wctalon;
                  bdnomcta = wnomcta;
                  bddebito = wvalor;

                  SUSPEND;
                end
             END
           wparticipantes = '';
           wsql = 'Select tlan.bddata,tlan.bdcredito,tpla.bdnomcta,tpla.bdctalon,bdvalor, tpla.BDPARTICIPANTE ';
           wsql = wsql||'from (Select bddata,bdcredito,Sum(bdvalor) as bdvalor from VSUC_EMPRESAS_TLAN ';
           wsql = wsql||'      where ';
           --  1 -> Fiscal | 2 -> Societário | 99 -> Todos
           IF (prcontabilizacao <> 99) THEN
             wsql = wsql||'    (bdcontabilizacao in (0,'||prcontabilizacao||')) and ';
           wsql = wsql||'      (bdcredito is not null) and ';
           wsql = wsql||'      (bddata between '''||prdataini||''' and '''||prdatafim||''') and ';
           wsql = wsql||'      (bdcodemp in ('||bdcodemp||'))';
           wsql = wsql||'      group by bdcodemp,bddata,bdcredito) tlan ';
           wsql = wsql||'left outer join planos_tpla tpla on ((tpla.bdcodplapadrao = '||bdcodplapadrao||') and (tpla.bdcodtpla = tlan.bdcredito)) ';
           FOR EXECUTE STATEMENT wsql  INTO wdata, wconta, wnomcta, wctalon , wvalor, wparticipante  DO
             BEGIN
             bdcodcta = wconta;
             bddebito = 0;
             if (wparticipante = 1) then
                begin
                  if (POSITION('<'||wconta||'>', wparticipantes) <= 0) then
                    begin
                       wparticipantes = wparticipantes||'<'||wconta||'>';
                       wsqlinner = 'Select tlan.bddata,tlan.BDCODTERCEIROC,tlan.bdvalor, tter.BDNOME ';
                       wsqlinner = wsqlinner||'from (Select bdcodemp,bddata,bdcredito,BDCODTERCEIROC, sum(bdvalor) as BDVALOR from VSUC_EMPRESAS_TLAN ';
                       wsqlinner = wsqlinner||'      where ';
                       --  1 -> Fiscal | 2 -> Societário | 99 -> Todos
                       IF (prcontabilizacao <> 99) THEN
                         wsqlinner = wsqlinner||'    (bdcontabilizacao in (0,'||prcontabilizacao||')) and ';
                       wsqlinner = wsqlinner||'      (bdcredito = '||wconta||') and ';
                       wsqlinner = wsqlinner||'      (bddata between '''||prdataini||''' and '''||prdatafim||''') and ';
                       wsqlinner = wsqlinner||'      (bdcodemp in ('||bdcodemp||'))';
                       wsqlinner = wsqlinner||'      group by bdcodemp,bddata,bdcredito,BDCODTERCEIROC) tlan ';
                       wsqlinner = wsqlinner||'left outer join VW_TTERCEIRO_SIMPLES tter on ((tter.bdcodter = tlan.BDCODTERCEIROC)) ';
    
                       FOR EXECUTE STATEMENT wsqlinner  INTO wdata, wcodter, wvalor, wnomter DO
                         BEGIN
                          bddata = wdata;
                          bdctalon = wctalon;
                          bdnomcta = wnomter;
                          bdcredito = wvalor;
    
                          if (wcodter > 0) then
                            begin
                              bdctalon = REVERSE(bdctalon);
                              bdctalon = SUBSTRING(bdctalon FROM POSITION('.', bdctalon) FOR strlen(bdctalon));
                              bdctalon = REVERSE(bdctalon);
                              wpos     =  CHARACTER_LENGTH(:bdctalon)-1;
                              bdctalon = bdctalon||LPAD(wcodter, 9, '0');
                            end
    
                          SUSPEND;
                         END
                    end
                end
               else
                begin
                   bddata = wdata;
                   bdctalon = wctalon;
                   bdnomcta = wnomcta;
                   bdcredito = wvalor;
                   SUSPEND;
                end
             END
         END
       ELSE
         BEGIN
           --#alt:165247 - Machado - 28/06/2022 - Alterado para levar a classificacao do CC
           wparticipantes = '';
           wsql = 'Select tlan.bddata,tlan.bddebito,tpla.bdnomcta,tpla.bdctalon,tlan.bdcodtpcc,tlan.bdvalor,tpla.BDPARTICIPANTE, tpcc.BDCTALON as BDCTALONCC ';
           wsql = wsql||'from (Select tlan.bddata,tlan.bddebito,tlcc.bdcodtpcc,sum(case when (tlcc.bdcodtpcc > 0) then tlcc.bdvalor else tlan.bdvalor end) as bdVALOR, tlcc.bdcodcentro ';
           wsql = wsql||'      from (Select bdcodemp,bdchave,bddata,bddebito,bdvalor from VSUC_EMPRESAS_TLAN ';
           wsql = wsql||'            where ';
           --  1 -> Fiscal | 2 -> Societário | 99 -> Todos
           IF (prcontabilizacao <> 99) THEN
             wsql = wsql||'          (bdCONTABILIZACAO in (0,'||prcontabilizacao||')) and ';
           wsql = wsql||'            (bddebito is not null) and ';
           wsql = wsql||'            (bddata between '''||prdataini||''' and '''||prdatafim||''') and ';
           wsql = wsql||'            (bdcodemp in ('||bdcodemp||'))) tlan ';
           wsql = wsql||'      left outer join VSUC_EMPRESAS_TLCC tlcc on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave and tlcc.bddebcre = 0)';
           wsql = wsql||'      group by tlan.bddata,tlan.bddebito,tlcc.bdcodcentro,tlcc.bdcodtpcc) tlan ';
           wsql = wsql||'left outer join planos_tpla tpla on ((tpla.bdcodplapadrao = '||bdcodplapadrao||') and (tpla.bdcodtpla = tlan.bddebito)) ';
           wsql = wsql||'left outer join CENTROS_TPCC tpcc on ((tpcc.bdcodcentro = tlan.bdcodcentro) and (tpcc.bdcodtpcc = tlan.bdcodtpcc)) ';
           FOR EXECUTE STATEMENT wsql  INTO wdata,wconta,wnomcta,wctalon,wcodtpcc,wvalor,wparticipante,wctaloncc  DO
             BEGIN
               bdcodcta  = wconta;
               bdcredito = 0;
               if (wparticipante = 1) then
                begin  
                  if (POSITION('<'||wconta||'>', wparticipantes) <= 0) then
                    begin
                       wparticipantes = wparticipantes||'<'||wconta||'>';
                       wsqlinner = 'Select tlan.bddata,tlan.BDCODTERCEIROD,tlan.bdvalor, tter.BDNOME,tlan.bdcodtpcc, tpcc.BDCTALON as BDCTALONCC ';
                       wsqlinner = wsqlinner||'from (Select TLAN.bdcodemp,TLAN.bddata,TLAN.bddebito,TLAN.BDCODTERCEIROD, ';
                       wsqlinner = wsqlinner||'tlcc.bdcodtpcc,sum(case when (tlcc.bdcodtpcc > 0) then tlcc.bdvalor else tlan.bdvalor end) as bdVALOR, tlcc.bdcodcentro';
                       wsqlinner = wsqlinner||'       from VSUC_EMPRESAS_TLAN TLAN ';
                       wsqlinner = wsqlinner||'       left outer join VSUC_EMPRESAS_TLCC tlcc on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave and tlcc.bddebcre = 1) where';
                       --  1 -> Fiscal | 2 -> Societário | 99 -> Todos
                       IF (prcontabilizacao <> 99) THEN
                         wsqlinner = wsqlinner||'    (TLAN.bdcontabilizacao in (0,'||prcontabilizacao||')) and ';
                       wsqlinner = wsqlinner||'      (TLAN.bddebito = '||wconta||') and ';
                       wsqlinner = wsqlinner||'      (TLAN.bddata between '''||prdataini||''' and '''||prdatafim||''') and ';
                       wsqlinner = wsqlinner||'      (TLAN.bdcodemp in ('||bdcodemp||'))';
                       wsqlinner = wsqlinner||'      group by TLAN.bdcodemp,TLAN.bddata,TLAN.bddebito,TLAN.BDCODTERCEIROD,tlcc.bdcodtpcc, tlcc.bdcodcentro) tlan ';
                       wsqlinner = wsqlinner||'left outer join VW_TTERCEIRO_SIMPLES tter on ((tter.bdcodter = tlan.BDCODTERCEIROD)) ';
                       wsqlinner = wsqlinner||'left outer join CENTROS_TPCC tpcc on ((tpcc.bdcodcentro = tlan.bdcodcentro) and (tpcc.bdcodtpcc = tlan.bdcodtpcc)) ';
    
                       FOR EXECUTE STATEMENT wsqlinner  INTO wdata, wcodter, wvalor, wnomter, wcodtpcc,wctaloncc DO
                         BEGIN
                          bddata = wdata;
                          bdctalon = wctalon;
                          bdnomcta = wnomter;
                          bddebito = wvalor;
                          bdcodtpcc = wcodtpcc;
                          bdctaloncc = wctaloncc;
    
                          if (wcodter > 0) then
                            begin
                              bdctalon = REVERSE(bdctalon);
                              bdctalon = SUBSTRING(bdctalon FROM POSITION('.', bdctalon) FOR strlen(bdctalon));
                              bdctalon = REVERSE(bdctalon);
                              wpos     =  CHARACTER_LENGTH(:bdctalon)-1;
                              bdctalon = bdctalon||LPAD(wcodter, 9, '0');
                            end
    
                          SUSPEND;
                         END
                    end
                end
               else
                begin
                   bddata    = wdata;
                   bdctalon  = wctalon;
                   bdnomcta  = wnomcta;
                   bdcodtpcc = wcodtpcc;
                   bdctaloncc = wctaloncc;
                   bddebito  = wvalor;
                   SUSPEND;
                 end
             END

           wparticipantes = '';
           wsql = 'Select tlan.bddata,tlan.bdcredito,tpla.bdnomcta,tpla.bdctalon,tlan.bdcodtpcc,tlan.bdvalor,tpla.BDPARTICIPANTE, tpcc.BDCTALON as BDCTALONCC ';
           wsql = wsql||'from (Select tlan.bddata,tlan.bdcredito,tlcc.bdcodtpcc,sum(case when (tlcc.bdcodtpcc > 0) then tlcc.bdvalor else tlan.bdvalor end) as bdVALOR, tlcc.bdcodcentro ';
           wsql = wsql||'      from (Select bdcodemp,bdchave,bddata,bdcredito,bdvalor from VSUC_EMPRESAS_TLAN TLAN ';
           wsql = wsql||'            where ';
           --  1 -> Fiscal | 2 -> Societário | 99 -> Todos
           IF (prcontabilizacao <> 99) THEN
             wsql = wsql||'          (bdCONTABILIZACAO in (0,'||prcontabilizacao||')) and ';
           wsql = wsql||'            (bdcredito is not null) and ';
           wsql = wsql||'            (bddata between '''||prdataini||''' and '''||prdatafim||''') and ';
           wsql = wsql||'            (bdcodemp in ('||bdcodemp||'))) tlan ';
           wsql = wsql||'      left outer join VSUC_EMPRESAS_TLCC tlcc on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave and tlcc.bddebcre = 1)';
           wsql = wsql||'group by tlan.bddata,tlan.bdcredito,tlcc.bdcodtpcc,tlcc.bdcodcentro) tlan ';
           wsql = wsql||'left outer join planos_tpla tpla on ((tpla.bdcodplapadrao = '||bdcodplapadrao||') and (tpla.bdcodtpla = tlan.bdcredito)) ';   
           wsql = wsql||'left outer join CENTROS_TPCC tpcc on ((tpcc.bdcodcentro = tlan.bdcodcentro) and (tpcc.bdcodtpcc = tlan.bdcodtpcc)) ';

           FOR EXECUTE STATEMENT wsql  INTO wdata,wconta,wnomcta,wctalon,wcodtpcc,wvalor,wparticipante, wctaloncc  DO
             BEGIN
               bdcodcta  = wconta;
               bddebito  = 0;
               if (wparticipante = 1) then
                begin
                  if (POSITION('<'||wconta||'>', wparticipantes) <= 0) then
                    begin
                       wparticipantes = wparticipantes||'<'||wconta||'>';
                       wsqlinner = 'Select tlan.bddata,tlan.BDCODTERCEIROC,tlan.bdvalor, tter.BDNOME,tlan.bdcodtpcc, tpcc.BDCTALON as BDCTALONCC ';
                       wsqlinner = wsqlinner||'from (Select TLAN.bdcodemp,TLAN.bddata,TLAN.bdcredito,TLAN.BDCODTERCEIROC, ';
                       wsqlinner = wsqlinner||'tlcc.bdcodtpcc,sum(case when (tlcc.bdcodtpcc > 0) then tlcc.bdvalor else tlan.bdvalor end) as bdVALOR,tlcc.bdcodcentro';
                       wsqlinner = wsqlinner||'       from VSUC_EMPRESAS_TLAN TLAN ';
                       wsqlinner = wsqlinner||'       left outer join VSUC_EMPRESAS_TLCC tlcc on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave and tlcc.bddebcre = 1) where';
                       --  1 -> Fiscal | 2 -> Societário | 99 -> Todos
                       IF (prcontabilizacao <> 99) THEN
                         wsqlinner = wsqlinner||'    (TLAN.bdcontabilizacao in (0,'||prcontabilizacao||')) and ';
                       wsqlinner = wsqlinner||'      (TLAN.bdcredito = '||wconta||') and ';
                       wsqlinner = wsqlinner||'      (TLAN.bddata between '''||prdataini||''' and '''||prdatafim||''') and ';
                       wsqlinner = wsqlinner||'      (TLAN.bdcodemp in ('||bdcodemp||'))';
                       wsqlinner = wsqlinner||'      group by TLAN.bdcodemp,TLAN.bddata,TLAN.bdcredito,TLAN.BDCODTERCEIROC,tlcc.bdcodtpcc,tlcc.bdcodcentro) tlan ';
                       wsqlinner = wsqlinner||'left outer join VW_TTERCEIRO_SIMPLES tter on ((tter.bdcodter = tlan.BDCODTERCEIROC)) ';          
                       wsqlinner = wsqlinner||'left outer join CENTROS_TPCC tpcc on ((tpcc.bdcodcentro = tlan.bdcodcentro) and (tpcc.bdcodtpcc = tlan.bdcodtpcc)) ';
    
                       FOR EXECUTE STATEMENT wsqlinner  INTO wdata, wcodter, wvalor, wnomter, wcodtpcc, wctaloncc DO
                         BEGIN
                          bddata = wdata;
                          bdctalon = wctalon;
                          bdnomcta = wnomter;
                          bdcredito = wvalor;
                          bdcodtpcc = wcodtpcc;
                          bdctaloncc = wctaloncc;
    
                          if (wcodter > 0) then
                            begin
                              bdctalon = REVERSE(bdctalon);
                              bdctalon = SUBSTRING(bdctalon FROM POSITION('.', bdctalon) FOR strlen(bdctalon));
                              bdctalon = REVERSE(bdctalon);
                              wpos     =  CHARACTER_LENGTH(:bdctalon)-1;
                              bdctalon = bdctalon||LPAD(wcodter, 9, '0');
                            end
    
                          SUSPEND;
                         END
                    end
                end
               else
                begin
                   bddata    = wdata;
                   bdcodcta  = wconta;
                   bdctalon  = wctalon;
                   bdnomcta  = wnomcta;
                   bdcodtpcc = wcodtpcc;   
                   bdctaloncc = wctaloncc;

                   bdcredito = wvalor;
                   SUSPEND;
                 end
             END
         END
     END
END
^

/* Restore proc. body: VSUC_SP_IMPORTAFORMULA */
CREATE OR ALTER PROCEDURE VSUC_SP_IMPORTAFORMULA (
    PRCODPLAPADRAO INTEGER,
    PRCODFOR INTEGER,
    PRNIVELINI INTEGER,
    PRNIVELFIM INTEGER,
    PRCTALONINI VARCHAR(40),
    PRCTALONFIM VARCHAR(40),
    PRQUADRO INTEGER = 0)
AS
DECLARE VARIABLE WCONTADOR INTEGER;
DECLARE VARIABLE WNIVEL INTEGER;
DECLARE VARIABLE WAPEFOR VARCHAR(20);
DECLARE VARIABLE WNOMFOR VARCHAR(100);
DECLARE VARIABLE WTIPFOR INTEGER;
DECLARE VARIABLE WCLAFOR VARCHAR(40);
DECLARE VARIABLE WCODPFOR VARCHAR(10);
DECLARE VARIABLE WCTALONFIM VARCHAR(40);
DECLARE VARIABLE WTIPOPROXCTA INTEGER;
DECLARE VARIABLE WCADAUTOMATICO VARCHAR(5);
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WGRUPOCTA INTEGER;
DECLARE VARIABLE WGRUPOFOR INTEGER;
DECLARE VARIABLE WTIPOFOR INTEGER;
BEGIN

  DELETE FROM vsuc_base_tformula_tpfo TFORMULAS WHERE TFORMULAS.bdcodpfor = :prcodfor; 
  DELETE FROM vsuc_base_formula_tmensal TFORMULAS WHERE TFORMULAS.bdcodpfor = :prcodfor and tformulas.bdquadro = :prquadro;

  SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND SUBSTRING(planos_tpla.bdctalon FROM 1 FOR CHARACTER_LENGTH(:prctalonfim)) = :prctalonfim
  ORDER BY planos_tpla.bdctalon DESC
  INTO :wctalonfim;

  SELECT TFor.bdcadautomatico, tfor.bdtipfor FROM VSUC_BASE_TFORMULA TFor WHERE TFor.bdcodpfor = :PRCODFOR INTO :WCADAUTOMATICO, :WTIPOFOR;

  FOR SELECT planos_tpla.bdcodtpla, planos_tpla.bdcodtpla, planos_tpla.bdctalon,
             planos_tpla.bdtipcta, planos_tpla.bdnomcta, planos_tpla.bdapecta, planos_tpla.bdgrupocta
      FROM planos_tpla
      WHERE (planos_tpla.bdcodplapadrao = :prcodplapadrao)
      AND (planos_tpla.bdctalon BETWEEN :prctalonini AND :wctalonfim)
      ORDER BY planos_tpla.bdctalon ASC
      INTO :WCODPFOR, :WCODTPLA, :WCLAFOR, :WTIPFOR, :WNOMFOR, :WAPEFOR, :WGRUPOCTA DO
      BEGIN

          wNivel = 0;
          wcontador = 0;

          IF (WGRUPOCTA IN (0,4,5)) THEN
            wGRUPOFOR = 0;
          ELSE
            wGRUPOFOR = 1;

          --#148746 - 19/03/2021 - Celso Bahr - Ajuste para contas consolidadas
          IF (wtipfor IN (0,2)) THEN
            wtipfor = 0;
          ELSE
            wtipfor = 1;

          WHILE (wcontador < strlen(wClafor)) DO
            BEGIN
             IF (SUBSTRING(wClafor FROM wcontador +1 FOR 1) = '.') THEN
                wNivel = wNivel + 1;

             wContador = wContador +1;
            END


          IF ((wNivel >= prnivelini) AND (wNivel <= prnivelfim)) THEN
             BEGIN
               IF ((wnivel = prnivelfim) or (wtipfor = 1)) THEN
                 BEGIN
                   if (WTIPOFOR = 9) then
                     INSERT INTO vsuc_base_formula_tmensal (BDCODPFOR, BDQUADRO, BDCLAFOR, BDTIPFOR, BDNOMFOR, BDAPEFOR, BDDESCFOR, BDGRUPOFOR)
                                                     VALUES(:prcodfor, :prquadro, :wclafor, '1', :wnomfor, :wapefor, 'Conta('||:wcodpfor||')', :wgrupofor);
                   else
                   INSERT INTO vsuc_base_tformula_tpfo (BDCODPFOR, BDCLAFOR, BDTIPFOR, BDNOMFOR, BDAPEFOR, BDDESCFOR, BDGRUPOFOR)
                                                VALUES(:prcodfor, :wclafor, '1', :wnomfor, :wapefor, 'Conta('||:wcodpfor||')', :wgrupofor);

                 END
               ELSE
                 BEGIN
                    /* Verifica se o plano de formulas que receberá as contas possi cadastro automático */  
                    /* Verifica se a conta é título de ultimo nível, ou seja, conta título acima de uma analítica */
                    IF (:WCADAUTOMATICO = 'TRUE' and (SELECT FIRST 1 TPla.bdtipcta FROM Planos_TPla TPla WHERE TPla.bdctalon LIKE :WCLAFOR||'.%' ORDER BY TPla.bdctalon) = 1) THEN
                          BEGIN
                        if (WTIPOFOR = 9) then
                         INSERT INTO vsuc_base_formula_tmensal (BDCODPFOR, BDQUADRO, BDCLAFOR, BDTIPFOR, BDNOMFOR, BDAPEFOR, BDDESCFOR, BDCODPLAPADRAO, BDCODTPLA, BDGRUPOFOR)
                                                       VALUES(:prcodfor, :prquadro, :wclafor, :wtipfor, :wnomfor, :wapefor, '', :prcodplapadrao, :wcodtpla, :wgrupofor);
                        else
                             INSERT INTO vsuc_base_tformula_tpfo (BDCODPFOR, BDCLAFOR, BDTIPFOR, BDNOMFOR, BDAPEFOR, BDDESCFOR, BDCODPLAPADRAO, BDCODTPLA, BDGRUPOFOR)
                                                   VALUES(:prcodfor, :wclafor, :wtipfor, :wnomfor, :wapefor, '', :prcodplapadrao, :wcodtpla, :wgrupofor);
                          END
                          ELSE
                          BEGIN
                        if (WTIPOFOR = 9) then
                          INSERT INTO vsuc_base_formula_tmensal (BDCODPFOR, BDQUADRO, BDCLAFOR, BDTIPFOR, BDNOMFOR, BDAPEFOR, BDDESCFOR, BDGRUPOFOR)
                                                      VALUES(:prcodfor, :prquadro, :wclafor, :wtipfor, :wnomfor, :wapefor, '', :wgrupofor);
                        else
                            INSERT INTO vsuc_base_tformula_tpfo (BDCODPFOR, BDCLAFOR, BDTIPFOR, BDNOMFOR, BDAPEFOR, BDDESCFOR, BDGRUPOFOR)
                                                     VALUES(:prcodfor, :wclafor, :wtipfor, :wnomfor, :wapefor, '', :wgrupofor);
                          END
                        END
                        END
                     END
END
^

/* Restore proc. body: VSUC_SP_INSERT_ENCEX */
ALTER PROCEDURE VSUC_SP_INSERT_ENCEX(PRCODEMP INTEGER,
PRCODPLANOS INTEGER,
PRCODTPLA INTEGER,
PRCODHIST INTEGER,
PRCODTPHI INTEGER,
PRCODUSU INTEGER,
PRDATAINIZER DATE,
PRDATAFIMZER DATE,
PRDATALANCZER DATE,
PRDATAZER DATE,
PRHORAZER TIMESTAMP)
 RETURNS(PRCHAVEZER INTEGER)
 AS
BEGIN
  INSERT INTO VSUC_EMPRESAS_TENCEXE
  (BDCODEMP,BDCHAVEZER,BDCODPLANOS,BDCODTPLA,BDCODHIST,BDCODTPHI,BDCODUSU,BDDATAINIZER,BDDATAFIMZER,BDDATALANCZER,BDDATAZER,BDHORAZER)
  VALUES
  (:prcodemp,0,:prcodplanos,:prcodtpla,:prcodhist,:prcodtphi,:prcodusu,:prdatainizer,:prdatafimzer,:prdatalanczer,:prdatazer,:prhorazer);

  SELECT MAX(bdCHAVEZER) FROM  VSUC_EMPRESAS_TENCEXE WHERE bdCODEMP = :prcodemp INTO :prchavezer;
  SUSPEND;
END
^

/* Restore proc. body: VSUC_SP_INSERT_LANC */
ALTER PROCEDURE VSUC_SP_INSERT_LANC(PRCHAVE INTEGER,
PRCODEMP INTEGER,
PRCODPLAPADRAO INTEGER,
PRDEBITO INTEGER,
PRCREDITO INTEGER,
PRCODHIST INTEGER,
PRCODTPHI INTEGER,
PRUSUARIO INTEGER,
PRLOTE VARCHAR(10),
PRDATA DATE,
PRVALOR NUMERIC(15,2),
PRCOMPL VARCHAR(100),
PRDATALAN DATE,
PRHORALAN TIME,
PRTIPOLAN SMALLINT,
PRDCTO VARCHAR(5),
PRCONCD VARCHAR(5),
PRCONCC VARCHAR(5),
PRCHAVEZER INTEGER,
PRREFEMP INTEGER)
 AS
BEGIN

  /* a chave é gravada automaticamente no before insert*/
  INSERT INTO vsuc_empresas_tlan
  (BDCHAVE, BDCODEMP, BDCODPLAPADRAO, BDDEBITO, BDCREDITO, BDCODHIST,
   BDCODTPHI, bdcodusu, BDLOTE, BDDATA, BDVALOR, BDCOMPL, BDDATALAN,
   BDHORALAN, BDTIPOLAN, BDDCTO, BDCONCD, BDCONCC, BDCHAVEZER)
  VALUES
  (:prchave, :prcodemp, :prcodplapadrao, :prdebito, :prcredito, :prcodhist,
   :prcodtphi, :prusuario, :prlote, :prdata, :prvalor, :prcompl, :prdatalan,
   :prhoralan, :prtipolan, :prdcto, :prconcd, :prconcc, :prchavezer);



END
^

/* Restore proc. body: VSUC_SP_LISTA_CTA_RAZAO_VIDEO */
ALTER PROCEDURE VSUC_SP_LISTA_CTA_RAZAO_VIDEO(PRCODEMP VARCHAR(2048),
PRCODPLAPADRAO INTEGER,
PRDATINI DATE,
PRDATFIM DATE,
PRCTALONINI VARCHAR(40),
PRCTALONFIM VARCHAR(40),
PRTIPORAZAO INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODTPLA INTEGER,
BDNOMCTA VARCHAR(100),
BDCTALON VARCHAR(40),
BDCODPARTICIPANTE INTEGER)
 AS
DECLARE VARIABLE wsql VARCHAR(3000);
DECLARE VARIABLE wsql2 VARCHAR(3000);
DECLARE VARIABLE wsqlemp VARCHAR(3000);
DECLARE VARIABLE wcodplapadrao INTEGER;
DECLARE VARIABLE wsaldo_deb NUMERIC(15,2);
DECLARE VARIABLE wsaldo_cre NUMERIC(15,2);
DECLARE VARIABLE wnomcta VARCHAR(100);
DECLARE VARIABLE wpos INTEGER;
DECLARE VARIABLE wdatini VARCHAR(10);
DECLARE VARIABLE wdatfin VARCHAR(10);
DECLARE VARIABLE wsomavlr NUMERIC(15,2);
DECLARE VARIABLE wcodemp INTEGER;
DECLARE VARIABLE wparticipante INTEGER;
DECLARE VARIABLE wcodempaux INTEGER;
DECLARE VARIABLE wfilial INTEGER;
DECLARE VARIABLE wtipolancfilial INTEGER;
DECLARE VARIABLE wcodcta INTEGER;
DECLARE VARIABLE wtipocta INTEGER;
DECLARE VARIABLE wpermite INTEGER;
DECLARE VARIABLE wsomavlraux NUMERIC(15,2);
DECLARE VARIABLE wempprinc INTEGER;
BEGIN
  -- Foi aleterado a rotina para melhorar o desempenho
  /*wsql = 'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao ';
  wsql = wsql||'from planos_tpla tpla ';
  wsql = wsql||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodplapadrao = tpla.bdcodplapadrao) ';
  wsql = wsql||'where ';
  wsql = wsql||'tlan.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'and ((tpla.bdcodtpla = tlan.bddebito) or (tpla.bdcodtpla = tlan.bdcredito)) ';
  wsql = wsql||'and (tlan.bddata between '''||prdatini||''' and '''||prdatfim||''') ';
  wsql = wsql||'and tpla.bdcodtpla in (select tcta.bdcodtpla from planos_tpla tcta ';
  wsql = wsql||'                       where (tcta.bdcodplapadrao = tlan.bdcodplapadrao) and ';
  wsql = wsql||'                       (tcta.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''') ';
  if (prTipoRazao = 1) then
    begin
      wsql = wsql||' and ((((bdconcd = ''TRUE'') and (not bddebito is null)) and (tpla.bdcodtpla = tlan.bddebito)) ';
      wsql = wsql||' or (((BDCONCC = ''TRUE'') and (not bdcredito is null))) and (tpla.bdcodtpla = tlan.bdcredito)) ';
    end
  else
    if (prTipoRazao = 2) then
      begin
        wsql = wsql||' and ((((bdconcd is null) and (not bddebito is null)) and (tpla.bdcodtpla = tlan.bddebito)) ';
        wsql = wsql||' or (((BDCONCC is null) and (not bdcredito is null))) and (tpla.bdcodtpla = tlan.bdcredito)) ';
      end
  wsql = wsql||'                       order by tcta.bdctalon)';*/
  wdatini = SUBSTRING(CAST(PRDATINI AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(PRDATINI AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(PRDATINI AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatfim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatfim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatfim AS VARCHAR(10)) FROM 1 FOR 4);

  IF (prctalonini = prctalonfim) THEN
    BEGIN
      wsql = '';
      wsql = 'select tpla.bdcodtpla, tpla.bdnomcta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao from planos_tpla tpla ';
      --#alt:5619 - gilberto - 13/08/2013 ______________________________________________________________________________________________________
      SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wcodcta;
      IF ((wcodcta IS NOT NULL) AND (wcodcta > 0)) THEN
         wsql = wsql||' inner join vsuc_select_contas tsel on (tsel.bdcodplapadrao = tpla.bdcodplapadrao and tsel.bdcodtpla = tpla.bdcodtpla) ';
      ---------------------------------------------------------------------------------------------------------------------------------#alt:5619
      wsql = wsql||' where (tpla.bdcodplapadrao = '||prcodplapadrao||') and (tpla.bdctalon between '''||prctalonini||''' and  '''||prctalonfim||''' )';
      FOR EXECUTE STATEMENT wsql INTO :bdcodtpla,:bdnomcta,:bdctalon,:wparticipante,:wcodplapadrao DO
      BEGIN
        -- retorna as empresas selecionadas
        wsqlemp = 'select temp.bdcodemp from tempresas temp ';
        wsqlemp = wsqlemp||'where temp.bdcodemp in ('||prcodemp||') ';
        wsqlemp = wsqlemp||'order by temp.bdcodemp';
        -- executa o sql das empresas
        FOR EXECUTE STATEMENT wsqlemp INTO :wcodemp DO
        BEGIN
          wsomavlr = 0;
          wsql2    = '';
          --#alt:5837
          /*wsql2    = 'Select Sum(bdvalor) from vsuc_empresas_tlan where ';
          wsql2    = wsql2||' (bdcodemp = '||wcodemp||') and (bdcodplapadrao = '||prcodplapadrao||') and ';
          wsql2    = wsql2||' (bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
          wsql2    = wsql2||' ((bddebito = '||bdcodtpla||') or (bdcredito = '||bdcodtpla||'))';
          if (prTipoRazao = 1) then
            begin
              wsql2 = wsql2||' and ((((Upper(bdconcd) = ''TRUE'') and (not bddebito is null)) and (bddebito = '||bdcodtpla||')) ';
              wsql2 = wsql2||' or   (((Upper(bdconcc)  = ''TRUE'') and (not bdcredito is null)) and (bdcredito = '||bdcodtpla||'))) ';
            end
          else
            if (prTipoRazao = 2) then
              begin
                wsql2 = wsql2||' and (((((Upper(bdconcd) = ''FALSE'') or (bdconcd is null)) and (not bddebito is null)) and (bddebito = '||bdcodtpla||')) ';
                wsql2 = wsql2||' or   ((((Upper(bdconcc) = ''FALSE'') or (bdconcc is null)) and (not bdcredito is null)) and (bdcredito = '||bdcodtpla||'))) ';
              end */
          --Débito
          wsql2    = 'Select bdcodemp,bddebito, 1 as bdtipcta, Sum(bdvalor) from vsuc_empresas_tlan where ';
          wsql2    = wsql2||' (bdcodemp = '||wcodemp||') and (bdcodplapadrao = '||prcodplapadrao||') and ';
          wsql2    = wsql2||' (bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
          wsql2    = wsql2||' (bddebito = '||bdcodtpla||') ';
          --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
          IF (prcontabilizacao <> 99) THEN
            wsql2    = wsql2||' and (bdcontabilizacao in (0,'||prcontabilizacao||'))';
          IF (prTipoRazao = 1) THEN
            wsql2 = wsql2||' and (Upper(bdconcd) = ''TRUE'') ';
          ELSE
          IF (prTipoRazao = 2) THEN
            wsql2 = wsql2||' and ((Upper(bdconcd) = ''FALSE'') or (bdconcd is null)) ';
          wsql2 = wsql2||'Group By bdcodemp,bddebito ';

          wsql2 = wsql2||'union all ';
          --Crédito
          wsql2    = wsql2||'Select bdcodemp,bdcredito, 2 as bdtipcta, Sum(bdvalor) from vsuc_empresas_tlan where ';
          wsql2    = wsql2||' (bdcodemp = '||wcodemp||') and (bdcodplapadrao = '||prcodplapadrao||') and ';
          wsql2    = wsql2||' (bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
          wsql2    = wsql2||' (bdcredito = '||bdcodtpla||') ';
          --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
          IF (prcontabilizacao <> 99) THEN
            wsql2    = wsql2||' and (bdcontabilizacao in (0,'||prcontabilizacao||'))';
          IF (prTipoRazao = 1) THEN
            wsql2 = wsql2||' and (Upper(bdconcc) = ''TRUE'') ';
          ELSE
          IF (prTipoRazao = 2) THEN
            wsql2 = wsql2||' and ((Upper(bdconcc) = ''FALSE'') or (bdconcd is null)) ';
          wsql2 = wsql2||'Group By bdcodemp,bdcredito ';
          --#alt:5837
          --execute statement wsql2 into :wsomavlr;
          FOR EXECUTE STATEMENT wsql2 INTO :wcodempaux,:wcodcta,:wtipocta,:wsomavlraux DO
            BEGIN
            --  SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(:wtipocta,:wcodemp,:wcodempaux,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
            --  IF (wpermite = 1) THEN
                wsomavlr = wsomavlr + wsomavlraux;
            END

          IF (wsomavlr > 0) THEN
            BEGIN
              -- Detalhado por participante
              IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1)) THEN--#alt:6309
                BEGIN
                  FOR SELECT tctapar.bdnome, tctapar.bdclassificacao, tctapar.bdcodparticipante, tctapar.bdsaldo_deb, tctapar.bdsaldo_cre
                  --from vsuc_sp_retorna_saldos_cta_part(:wcodemp,:wcodplapadrao,:prdatini,:prdatfim,:bdcodtpla,0,0,0,0, -- alt:#6647 - gilberto - 12/09/2013
                  FROM vsuc_sp_retorna_saldos_ctaparty(:wcodemp,:wcodplapadrao,:prdatini,:prdatfim,:bdcodtpla,0,0,0,0,
                                                       :prcodemp,:prcontabilizacao) tctapar
                  INTO :wnomcta, :bdctalon, :bdcodparticipante,:wsaldo_deb,:wsaldo_cre  DO
                    BEGIN
                      IF ((wsaldo_deb <> 0) OR (wsaldo_cre <> 0))  THEN
                        BEGIN
                          IF (prconcatenacodparticipante = 1) THEN
                            BEGIN
                              wpos     = CHARACTER_LENGTH(:bdcodparticipante);
                                         -- 100 -> máximo de caracteres para nome da conta
                                         -- 003 -> qtd de caracteres " - ";
                              wpos     = ((100 - wpos) - 3);
                              bdnomcta = bdcodparticipante||' - '||SUBSTRING(wnomcta FROM 1 FOR wpos);
                            END
                          SUSPEND;
                        END
                    END
                END
--              else
                SUSPEND;
            END
        END
      END
    END
  ELSE
    BEGIN
      wcodempaux = 0;
      wcodcta    = 0;

      wsql = '';
      --#alt:5837
      /*wsql = wsql||'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'tlan.bdcodemp ';
      wsql = wsql||'from planos_tpla tpla, vsuc_empresas_tlan tlan ';
      wsql = wsql||'where ';
      wsql = wsql||'(tpla.bdcodplapadrao = tlan.bdcodplapadrao) and ';
      wsql = wsql||'(tlan.bdcodemp in ('||prcodemp||')) and ';
      wsql = wsql||'((tpla.bdcodtpla = tlan.bddebito) or (tpla.bdcodtpla = tlan.bdcredito)) and ';
      wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
      wsql = wsql||'(tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')';*/
/*
      wsql = wsql||'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'tlan.bdcodemp, 1 as bdtipolanc ';
      wsql = wsql||'from planos_tpla tpla, vsuc_empresas_tlan tlan ';
      wsql = wsql||'where ';
      wsql = wsql||'(tpla.bdcodplapadrao = tlan.bdcodplapadrao) and ';
      wsql = wsql||'(tlan.bdcodemp in ('||prcodemp||')) and ';
      wsql = wsql||'(tpla.bdcodtpla = tlan.bddebito) and ';
      wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
      wsql = wsql||'(tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')';
*/
      wsql = 'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'       tlan.bdcodemp, 1 as bdtipolanc ';
      wsql = wsql||'from vsuc_empresas_tlan tlan ';
      wsql = wsql||'inner join planos_tpla tpla on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and (tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')) ';
      --#alt:5619 - gilberto - 13/08/2013 _____________________________________________________________________________________________________
      SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wcodcta;
      IF ((wcodcta IS NOT NULL) AND (wcodcta <> 0)) THEN
         wsql = wsql||'inner join vsuc_select_contas tsel on (tsel.bdcodplapadrao = tpla.bdcodplapadrao and tsel.bdcodtpla = tpla.bdcodtpla) ';
      --------------------------------------------------------------------------------------------------------------------------------#alt:5619
      wsql = wsql||'where (tlan.bdcodemp in ('||prcodemp||')) ';
      wsql = wsql||'and (tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';
      --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
      IF (prcontabilizacao <> 99) THEN
         wsql = wsql||' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||'))';
      wsql = wsql||' union all ';
/*
      wsql = wsql||'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'tlan.bdcodemp, 2 as bdtipolanc ';
      wsql = wsql||'from planos_tpla tpla, vsuc_empresas_tlan tlan ';
      wsql = wsql||'where ';
      wsql = wsql||'(tpla.bdcodplapadrao = tlan.bdcodplapadrao) and ';
      wsql = wsql||'(tlan.bdcodemp in ('||prcodemp||')) and ';
      wsql = wsql||'(tpla.bdcodtpla = tlan.bdcredito) and ';
      wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') and ';
      wsql = wsql||'(tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')';
*/
      wsql = 'select distinct tpla.bdcodtpla as bdconta, tpla.bdnomcta as bdnome_conta, tpla.bdctalon, tpla.bdparticipante, tpla.bdcodplapadrao, ';
      wsql = wsql||'       tlan.bdcodemp, 1 as bdtipolanc ';
      wsql = wsql||'from vsuc_empresas_tlan tlan ';
      wsql = wsql||'inner join planos_tpla tpla on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and (tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''')) ';
      --#alt:5619 - gilberto - 13/08/2013 _____________________________________________________________________________________________________
      SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wcodcta;
      IF ((wcodcta IS NOT NULL) AND (wcodcta <> 0)) THEN
         wsql = wsql||'inner join vsuc_select_contas tsel on (tsel.bdcodplapadrao = tpla.bdcodplapadrao and tsel.bdcodtpla = tpla.bdcodtpla) ';
      --------------------------------------------------------------------------------------------------------------------------------#alt:5619
      wsql = wsql||'where (tlan.bdcodemp in ('||prcodemp||')) ';
      wsql = wsql||'and (tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';
      --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
      IF (prcontabilizacao <> 99) THEN
        wsql = wsql||' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||'))';

      --Retorna a empresa principal
      SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
      IF (wpos = 0) THEN
        wempprinc = prcodemp;
      ELSE
        wempprinc = SUBSTRING(prcodemp FROM 1 FOR (wpos - 1));

      FOR EXECUTE STATEMENT wsql
      INTO :bdcodtpla,:bdnomcta,:bdctalon,:wparticipante,:wcodplapadrao,:wcodemp,:wtipocta DO
      BEGIN
        IF ((wcodemp <> wcodempaux) OR (bdcodtpla <> wcodcta)) THEN
          BEGIN
            -- Detalhado por participante
            IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1)) THEN
              BEGIN
                FOR SELECT tctapar.bdnome, tctapar.bdclassificacao, tctapar.bdcodparticipante, tctapar.bdsaldo_deb, tctapar.bdsaldo_cre
                    --from vsuc_sp_retorna_saldos_cta_part(:wcodemp,:wcodplapadrao,:prdatini,:prdatfim,:bdcodtpla, -- alt:#6647 - gilberto - 12/09/2013
                    FROM vsuc_sp_retorna_saldos_ctaparty(:wcodemp,:wcodplapadrao,:prdatini,:prdatfim,:bdcodtpla,0,
                                                         0,0,0,:prcodemp,:prcontabilizacao) tctapar
                INTO :wnomcta, :bdctalon, :bdcodparticipante,:wsaldo_deb,:wsaldo_cre  DO
                BEGIN
                  IF ((wsaldo_deb <> 0) OR (wsaldo_cre <> 0))  THEN
                    BEGIN
                      IF (prconcatenacodparticipante = 1) THEN
                        BEGIN
                          wpos     = CHARACTER_LENGTH(:bdcodparticipante);
                                     -- 100 -> máximo de caracteres para nome da conta
                                     -- 003 -> qtd de caracteres " - ";
                          wpos     = ((100 - wpos) - 3);
                          bdnomcta = bdcodparticipante||' - '||SUBSTRING(wnomcta FROM 1 FOR wpos);
                        END
                      SUSPEND;
                      wcodempaux = wcodemp;
                      wcodcta    = bdcodtpla;
                    END
                END
              END
            ELSE
              BEGIN
              --  SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(:wtipocta,:wempprinc,:wcodemp,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
              --  IF (wpermite = 1) THEN
                  SUSPEND;
                wcodempaux = wcodemp;
                wcodcta    = bdcodtpla;
              END
          END
      END
    END
END
^

--#alt:96787 - Carlos Machado - 12/03/2019
create or alter procedure VSUC_SP_MONTA_CONCILIACAO (
    PRCONCILIADOS varchar(40),
    PRCONC varchar(40),
    PRCONCPENDENTE varchar(40),
    PRDEBCRED varchar(40))
returns (
    BDSQLCONCILIADO varchar(1000))
as
declare variable WCONCILIADOS varchar(40);
declare variable WPOS integer;
declare variable WCONCILIADO varchar(5);
declare variable WPENDENTES integer;
begin
  wconciliados = prconciliados;
  WPENDENTES = 0;
  BDSQLCONCILIADO = '';
  WHILE (wconciliados <> '') DO
   BEGIN
     wpos = POSITION(',', wconciliados);
     if (wpos > 0) then
      WCONCILIADO = SUBSTRING(wconciliados FROM 1 FOR wpos - 1);
     else
      begin
        WCONCILIADO = wconciliados;
        wpos = strlen(wconciliados);
      end

     if (WCONCILIADO IN ('1','2') or ((WCONCILIADO = '3') AND (PRCONCPENDENTE <> ''))) then
      begin
       if (BDSQLCONCILIADO = '') then
         BDSQLCONCILIADO = ' (';
       else
         BDSQLCONCILIADO = BDSQLCONCILIADO||' or ';
       IF (WCONCILIADO = '1') THEN
          BDSQLCONCILIADO = BDSQLCONCILIADO||'(Upper('||PRCONC||') = '||'''TRUE'''||')';
       ELSE
       IF (WCONCILIADO = '2') THEN
          BDSQLCONCILIADO = BDSQLCONCILIADO||'((Upper('||PRCONC||') = '||'''FALSE'''||') or ('||PRCONC||' is null) or (Upper('||PRCONC||') = '||''''''||') )';
       ELSE
       IF (WCONCILIADO = '3') THEN
         BEGIN
          BDSQLCONCILIADO = BDSQLCONCILIADO||'(('||PRCONCPENDENTE||' = 3) or (('||PRCONCPENDENTE||' = 1) and ('||PRDEBCRED||' = 0)) or (('||prconcpendente||' = 2) and ('||PRDEBCRED||' = 1)))';
          WPENDENTES = 1;
         END
      end
     wconciliados = SUBSTRING(wconciliados FROM wpos+1 FOR strlen(wconciliados));
   END
   if (BDSQLCONCILIADO <> '') then
     BEGIN
       if (WPENDENTES <> 1 AND PRCONCPENDENTE <> '') then
         BDSQLCONCILIADO = '('||BDSQLCONCILIADO||' AND (('||PRCONCPENDENTE||' IS NULL) or ('||PRCONCPENDENTE||' = 0)))';
       BDSQLCONCILIADO = BDSQLCONCILIADO||')';
     END
  suspend;
end
^

/* Restore proc. body: VSUC_SP_LISTA_CTA_RAZAO_VIDEO_X */
CREATE OR ALTER PROCEDURE VSUC_SP_LISTA_CTA_RAZAO_VIDEO_X (
    PRCODEMP VARCHAR(2048),
    PRCODPLAPADRAO INTEGER,
    PRDATINI DATE,
    PRDATFIM DATE,
    PRCTALONINI VARCHAR(40),
    PRCTALONFIM VARCHAR(40),
    PRTIPORAZAO VARCHAR(20),
    PRPARTINI INTEGER,
    PRPARTFIM INTEGER,
    PRDETALHARCTAPARTICIPANTE INTEGER,
    PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRDETALHARCC INTEGER,
    PRLCC VARCHAR(8192),
    PRLANCAMENTOSEMCC INTEGER,
    PRDETALHAREMPREENDIMENTO INTEGER = 0,
    PRDETALHARUNIDIMOB INTEGER = 0,
    PRMOSTRARPROPUNIDADE INTEGER = 0,
    PRAGRUPARPARTICIPANTEPORCPF INTEGER = 0,
    PRORDEM INTEGER = 0,
    PRTIPOLAN varchar(3200) = '')
RETURNS (
    BDCODTPLA INTEGER,
    BDNOMCTA VARCHAR(300),
    BDCTALON VARCHAR(40),
    BDCODPARTICIPANTE INTEGER,
    BDCNPJPART VARCHAR(20),
    BDEMPREENDIMENTO INTEGER,
    BDUNIDIMOB INTEGER,
    BDCODEMP INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(8192);
declare variable WCODEMP integer;
declare variable WCTALON varchar(40);
declare variable WNOMETER varchar(100);
declare variable WCODTPLA integer;
declare variable WCODTER integer;
declare variable WMULTICTA integer;
declare variable WCNPJPARTANT varchar(20);
declare variable WEMPREE integer;
declare variable WUNID integer;
declare variable WEMPREEANT integer;
declare variable WUNIDANT integer;
declare variable WNAODETALHAEMP integer;
declare variable WNAODETALHAUNID integer;
declare variable WCLASS varchar(40);
declare variable WNOMEINCORP varchar(100);
declare variable WCODEMPANT integer;
declare variable WSQLTIPORAZAO varchar(1000);
declare variable WSQLPART varchar(1000);

BEGIN

  SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wmulticta;

  wsql = '';
  wsql = wsql||'select tlan.bdcodemp, tlan.bdcodtpla, ';
  wsql = wsql||'       tpla.bdnomcta, tpla.bdctalon, ';
  --#alt:145558 - Machado - 11/06/2021 - Agrupar participante por CPF.
  IF (1 in (pragruparparticipanteporcnpj, pragruparparticipanteporcpf)) THEN
    begin
      wSQL = wSQL||' tlan.BDCODTER, TER.bdnometer, case';
      if (pragruparparticipanteporcnpj = 1) then
        wSQL = wSQL||' when ter.bdcodpais = 30 and CHAR_LENGTH(terAux.BDCGCTER) = 18 THEN substring(terAux.BDCGCTER from 1 for 10)';
      if (pragruparparticipanteporcpf = 1) then
        wSQL = wSQL||' when ter.bdcodpais = 30 and CHAR_LENGTH(terAux.BDCGCTER) = 14 THEN terAux.BDCGCTER';
      wSQL = wSQL||' else ter.bdcodter end as BDCNPJPART ';
    end
  ELSE 
  IF (prdetalharctaparticipante = 1) THEN
     wsql = wsql||'tlan.BDCODTER, TER.bdnometer, substring(ter.BDCGCTER from 1 for 10) as BDCNPJPART ';
  ELSE
     wsql = wsql||'null as BDCODTER, null as BDNOMETER, null as BDCNPJPART ';

  --#alt:93770. Ana - 16/01/2019
  IF ((prdetalharempreendimento = 1) OR (prdetalharunidimob = 1)) THEN
    wsql = wsql||', BDCODEMPREENDIMENTO ';
  ELSE
    wsql = wsql||', null as BDCODEMPREENDIMENTO ';

  IF (prdetalharunidimob = 1) THEN
   wsql = wsql||', BDCODIGOUNIIMOB ';
  ELSE
    wsql = wsql||', null as BDCODIGOUNIIMOB ';

  wsql = wsql||'from (select * from( ';
  /************************************************** Débito **************************************************/
  wsql = wsql||'Select tlan.bdcodemp, tlan.bdcodplapadrao, tlan.bddebito as bdcodtpla, ';
  IF (prdetalharctaparticipante = 1) THEN
     wsql = wsql||'       bdcodterceirod as bdcodter ';
  ELSE
     wsql = wsql||'       null as bdcodter ';

  wsql = wsql||', TINCORP.bdcodempreendimento, TINCORP.bdcodigouniimob '; --#alt:93770. Ana - 15/01/2019
  wsql = wsql||'from vsuc_empresas_tlan tlan ';
  wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORP on (TINCORP.bdcodemp = TLAN.BDCODEMP and TINCORP.bdchave = TLAN.BDCHAVE and TINCORP.bddebcre = 0) '; --#alt:93770. Ana - 15/01/2019

  IF ((PRDETALHARCC = 1) AND (TRIM(prlcc) <> '')) THEN
    BEGIN
      IF (prlancamentosemcc = 0) THEN
        wsql = wsql||'inner join VSUC_EMPRESAS_TLCC tlcc on (tlcc.BDCODEMP = tlan.BDCODEMP and tlcc.BDCHAVE = tlan.BDCHAVE and tlcc.BDDEBCRE = 0 and tlcc.bdcodtpcc in ('||prlcc||')) ';
      ELSE
        wsql = wsql||'left join VSUC_EMPRESAS_TLCC tlcc on (tlcc.BDCODEMP = tlan.BDCODEMP and tlcc.BDCHAVE = tlan.BDCHAVE and tlcc.BDDEBCRE = 0 and tlcc.bdcodtpcc in ('||prlcc||')) ';
    END

  IF (wmulticta > 0) THEN
     wsql = wsql||'inner join vsuc_select_contas tsel on (tsel.bdcodplapadrao = tlan.bdcodplapadrao and tsel.bdcodtpla = tlan.bddebito) ';
  wsql = wsql||'where (tlan.bdcodplapadrao = '||prcodplapadrao||') ';
  wsql = wsql||'and (tlan.bddebito > 0) ';
  IF (prcontabilizacao <> 99) THEN
     wsql = wsql||'   and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';

  select bdsqlconciliado from vsuc_sp_monta_conciliacao(:prTipoRazao, 'tlan.bdconcd', 'tlan.BDCONCILIACAOPENDENTE', '0') into :wsqltiporazao;
  if (wsqltiporazao <> '') then
  wsql = wsql||' and '||wsqltiporazao;

  wsql = wsql||'and (tlan.bddata between '''||prdatini||''' and '''||prdatfim||''') ';
  wsql = wsql||'and ((tlan.bdcodemp IN ('||prcodemp||')) ';
  wsql = wsql||') ';
  
  if (PRTIPOLAN <> '') then --#212425
     wsql = wsql || ' and (tlan.bdtipolan in ('||PRTIPOLAN||')) ';  

  wsql = wsql||'union ';
  /************************************************** Crédito **************************************************/
  wsql = wsql||'Select tlan.bdcodemp, tlan.bdcodplapadrao, tlan.bdcredito as bdcodtpla, ';
  IF (prdetalharctaparticipante = 1) THEN
     wsql = wsql||'       bdcodterceiroc as bdcodter ';
  ELSE
     wsql = wsql||'       null as bdcodter ';

  wsql = wsql||'       ,TINCORP.bdcodempreendimento, TINCORP.bdcodigouniimob '; --#alt:93770. Ana - 15/01/2019
  wsql = wsql||'from vsuc_empresas_tlan tlan ';
  wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORP on (TINCORP.bdcodemp = TLAN.BDCODEMP and TINCORP.bdchave = TLAN.BDCHAVE and TINCORP.bddebcre = 1) '; --#alt:93770. Ana - 15/01/2019

  IF ((PRDETALHARCC = 1) AND (TRIM(prlcc) <> '')) THEN
    BEGIN
      IF (prlancamentosemcc = 0) THEN
        wsql = wsql||'inner join VSUC_EMPRESAS_TLCC tlcc on (tlcc.BDCODEMP = tlan.BDCODEMP and tlcc.BDCHAVE = tlan.BDCHAVE and tlcc.BDDEBCRE = 1 and tlcc.bdcodtpcc in ('||prlcc||')) ';
      ELSE
        wsql = wsql||'left join VSUC_EMPRESAS_TLCC tlcc on (tlcc.BDCODEMP = tlan.BDCODEMP and tlcc.BDCHAVE = tlan.BDCHAVE and tlcc.BDDEBCRE = 1 and tlcc.bdcodtpcc in ('||prlcc||')) ';
    END

  IF (wmulticta > 0) THEN
     wsql = wsql||'inner join vsuc_select_contas tsel on (tsel.bdcodplapadrao = tlan.bdcodplapadrao and tsel.bdcodtpla = tlan.bdcredito) ';
  wsql = wsql||'where (tlan.bdcodplapadrao = '||prcodplapadrao||') ';
  wsql = wsql||'and (tlan.bdcredito IS NOT NULL) ';
  IF (prcontabilizacao <> 99) THEN
     wsql = wsql||'   and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';

  select bdsqlconciliado from vsuc_sp_monta_conciliacao(:prTipoRazao, 'tlan.bdconcc', 'tlan.BDCONCILIACAOPENDENTE', '1') into :wsqltiporazao;
  if (wsqltiporazao <> '') then
  wsql = wsql||' and '||wsqltiporazao;
  
  if (PRTIPOLAN <> '') then --#212425
     wsql = wsql || ' and (tlan.bdtipolan in ('||PRTIPOLAN||')) ';  

  wsql = wsql||'and (tlan.bddata between '''||prdatini||''' and '''||prdatfim||''') ';
  wsql = wsql||'and ((tlan.bdcodemp IN ('||prcodemp||')) ';
  wsql = wsql||')) A ';
  wsql = wsql||'group by a.BDCODEMP, a.BDCODPLAPADRAO, a.BDCODTPLA, a.BDCODTER, a.BDCODEMPREENDIMENTO, a.BDCODIGOUNIIMOB ';
  wsql = wsql||') tlan ';
  wsql = wsql||'inner join planos_tpla tpla on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcodtpla) ';
  IF (wmulticta > 0) THEN
     wsql = wsql||') ';
  ELSE
     wsql = wsql||' and (tpla.bdctalon between '''||prctalonini||''' and '''||prctalonfim||''' )) ';
  IF (1 in (prAgruparParticipantePorCNPJ, pragruparparticipanteporcpf)) THEN
    BEGIN
      wSQL = wSQL||'left join TTERCEIRO terAux on (terAux.BDCODTER = tlan.BDCODTER) ';
      wSQL = wSQL||'left join VW_TTERCEIRO ter on (ter.BDCODTER = terAux.BDCODTER) ';
      if (prAgruparParticipantePorCNPJ <> 1) then
      wSQL = wSQL||'where terAux.BDCODTER between '||:prPartIni||' and '||prPartFim||' ';
    END
  ELSE 
  IF (prDetalharCtaParticipante = 1) THEN
    BEGIN
      --#89622 - Carlos Machado - 11/09/2018 - Alterado para não fazer agrupamento de participantes do exterior
      wSQL = wSQL||'left join VW_TTERCEIRO ter on (ter.BDCODTER = tlan.BDCODTER) ';
      wsql = wsql||'left join TTERCEIRO terc on (terc.BDCODTER = ter.BDCODTER) ';
      wSQL = wSQL||'where ter.BDCODTER between '||:prPartIni||' and '||prPartFim||' ';
    END
  IF (PRAGRUPARPARTICIPANTEPORCNPJ = 0 and pragruparparticipanteporcpf = 0) THEN
    wsql = wsql||'order by tlan.bdcodtpla, tlan.bdcodter ';
  ELSE
    wsql = wsql||'order by bdcodtpla, bdcnpjpart, ter.bdcodter ';

  wcnpjpartant = '';
  FOR EXECUTE STATEMENT wsql
      INTO :wcodemp, :bdcodtpla, :bdnomcta, :bdctalon, :bdcodparticipante, :wnometer, :BDCNPJPART, :wempree, :wunid DO
      BEGIN
         IF ((COALESCE(wcodtpla, 0) <> COALESCE(bdcodtpla, 0)) OR (COALESCE(wcodter, 0) <> COALESCE(bdcodparticipante, 0)) OR (wempreeant <> wempree) OR (wunid <> wunidant) or (wcodemp <> wcodempant and wempreeant = wempree)) THEN
            BEGIN
              IF ((prdetalharctaparticipante = 1) AND (bdcodparticipante > 0) and (PRAGRUPARPARTICIPANTEPORCNPJ = 1)) THEN
                 BEGIN
                   bdcodparticipante = null;
                   wsqlpart = 'select first 1 ter.bdcodter from TTERCEIRO ter ';
                   wsqlpart = wsqlpart||'where ((CHAR_LENGTH(TRIM(ter.BDCGCTER)) = 18 and ';
                   wsqlpart = wsqlpart||''''||:BDCNPJPART||'''  = substring(ter.BDCGCTER from 1 for 10)) and ';
                   wsqlpart = wsqlpart||'(ter.bdcodter between '||:prPartIni||' and '||prPartFim||')) ';
                   EXECUTE STATEMENT wsqlpart into :bdcodparticipante;
                 end

              if (not((prdetalharctaparticipante = 1)  and (PRAGRUPARPARTICIPANTEPORCNPJ = 1) and (bdcodparticipante IS NULL))) then
                begin

              bdnomcta = REPLACE(bdnomcta, '-', '');
    
              IF ((prdetalharctaparticipante = 1) AND (bdcodparticipante IS NOT NULL)) THEN
                 BEGIN
                   if (PRAGRUPARPARTICIPANTEPORCNPJ = 1) then
                     begin
                       wsqlpart = 'select first 1 ter.bdcodter, teraux.bdnometer from TTERCEIRO ter ';
                           wsqlpart = wsqlpart||'left join TTERCEIRO_ref teraux on (TER.BDCODTER = TERAUX.BDCODTER) ';
                       wsqlpart = wsqlpart||'where (CHAR_LENGTH(TRIM(ter.BDCGCTER)) = 18 and substring('''||:BDCNPJPART||''' from 1 for 10) = substring(ter.BDCGCTER from 1 for 10)) ';
                           wsqlpart = wsqlpart||'order by ter.bdcgcter, teraux.bdrefemp desc';
                       EXECUTE STATEMENT wsqlpart into :bdcodparticipante, wnometer;
                     end
                   wctalon = REVERSE(bdctalon);
                   wctalon = SUBSTRING(wctalon FROM POSITION('.', wctalon) FOR CHARACTER_LENGTH(wctalon));
                   bdctalon = REVERSE(wctalon)||LPAD(bdcodparticipante, 8, '0');
           -- #154789 - Marcela -  Consulta Razão em vídeo - Ordenar participante por ordem alfabética - 02/08/2022
                   if (PRORDEM = 1) then
                     bdnomcta = SUBSTRING(wnometer||SUBSTRING(' ('||bdcodparticipante||') ' FROM 1 FOR (100 - CHARACTER_LENGTH(wnometer))) FROM 1 FOR 100);
                   else
                   bdnomcta = SUBSTRING(bdcodparticipante||SUBSTRING(' - '||wnometer FROM 1 FOR (100 - CHARACTER_LENGTH(bdcodparticipante))) FROM 1 FOR 100);
                 END
    
              --#alt:93770. Ana - 15/01/2019
              IF (((PRDETALHAREMPREENDIMENTO = 1) OR (PRDETALHARUNIDIMOB = 1)) AND
                 (((wempree IS NOT NULL) AND (wempree > 0)) OR ((wunid IS NOT NULL) AND (wunid > 0)))) THEN
                BEGIN
                  BDCODEMP         = wcodemp;
                  bdempreendimento = wempree;
                  bdunidimob       = wunid;
    
                  WNAODETALHAEMP = 0;
                  IF (PRDETALHAREMPREENDIMENTO = 0) THEN
                    WNAODETALHAEMP = 1;
             
                  WNAODETALHAUNID = 0;
                  IF (PRDETALHARUNIDIMOB = 0) THEN
                    WNAODETALHAUNID = 1;
            
                  SELECT FIRST 1 BDCLASSIFICACAO FROM VSUC_RETORNA_CLA_INCORP(:bdcodtpla, :PRCODPLAPADRAO, :wempree, :wunid, :wnaodetalhaemp, :wnaodetalhaunid, :wcodemp) INTO :WCLASS;
    
                  IF (WCLASS IS NOT NULL) THEN
                    BEGIN
                      bdctalon = WCLASS;
            
                      IF ((wunid IS NOT NULL) AND (wunid > 0) AND (PRDETALHARUNIDIMOB = 1)) THEN
                        BEGIN
                          if (PRMOSTRARPROPUNIDADE <> 0) then
                            SELECT cad.BDDESCRICAO||COALESCE(' - '||TER.bdcodter||'-'||TER.bdnometer, ' - Não informado') FROM VEF_BASE_TCADUNIDIMOBILIARIA cad
                            left join vw_tterceiro ter on (ter.bdcodter = COALESCE((SELECT FIRST 1 F200.BDCODTER FROM VEF_EMP_TMOVOPIMOBILIARIA_F200 F200
                            WHERE F200.BDCODEMP = cad.bdcodemp
                            and F200.BDCODEMPREENDIMENTO = cad.BDCODEMPREENDIMENTO
                            and F200.BDCODIGOUNIIMOB = cad.BDCODIGOUNIIMOB order by F200.BDCHAVE DESC), cad.bdcodter))
                            WHERE cad.BDCODEMP = :wcodemp AND cad.BDCODEMPREENDIMENTO = :wempree AND cad.BDCODIGOUNIIMOB = :wunid INTO :WNOMEINCORP;
                          else
                            SELECT cad.BDDESCRICAO FROM VEF_BASE_TCADUNIDIMOBILIARIA cad
                            WHERE cad.BDCODEMP = :wcodemp AND cad.BDCODEMPREENDIMENTO = :wempree AND cad.BDCODIGOUNIIMOB = :wunid INTO :WNOMEINCORP;
    
                          bdnomcta = wcodemp||' - '||wempree||' - '||wunid||' - '||bdnomcta;
                        END
                      ELSE
                      IF ((wempree IS NOT NULL) AND (wempree > 0) AND (PRDETALHAREMPREENDIMENTO = 1)) THEN
                        BEGIN
                          SELECT SUBSTRING(BDNOMEEMPRE FROM 1 FOR 100) FROM VEF_EMP_TCADEMPREENDIMENTO
                          WHERE BDCODEMP = :wcodemp AND BDCODEMPREENDIMENTO = :wempree INTO :WNOMEINCORP;
    
                          bdnomcta = wcodemp||' - '||wempree||' - '||bdnomcta;
                        END
            
                      IF (WNOMEINCORP IS NOT NULL) THEN
                        bdnomcta = bdnomcta ||' ('||wnomeincorp||')';
                    END
                END
              --#alt:93770. fim
    
              IF ((PRAGRUPARPARTICIPANTEPORCNPJ = 0 and pragruparparticipanteporcpf = 0) OR (BDCNPJPART <> wcnpjpartant)) THEN
                SUSPEND;
    
              wcnpjpartant = BDCNPJPART;
                end
            END
        wcodtpla = bdcodtpla;
        wcodter = bdcodparticipante;

        wempreeant = wempree;
        wcodempant = wcodemp;
        wunidant   = wunid;
      END
END
^

/* Restore proc. body: VSUC_SP_LISTA_TLAN_CONC_CLIFOR */
ALTER PROCEDURE VSUC_SP_LISTA_TLAN_CONC_CLIFOR(PREMPRESA INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRCLIFOR SMALLINT,
PRLANCONC SMALLINT,
PRZEROESQ SMALLINT,
PRCODPLAPADRAO INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(CONCILIACAOOK SMALLINT)
 AS
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WCLASSIFICACAOINI VARCHAR(50);
DECLARE VARIABLE WCLASSIFICACAOFIM VARCHAR(50);
DECLARE VARIABLE WDEBITO INTEGER;
DECLARE VARIABLE WCREDITO INTEGER;
DECLARE VARIABLE WCONTA INTEGER;
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WSOMALANCS NUMERIC(15,2);
DECLARE VARIABLE WNRONF VARCHAR(200);
DECLARE VARIABLE WCONCILIOU VARCHAR(7);
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WDEBCRE VARCHAR(9);
DECLARE VARIABLE WCAMPOCONC VARCHAR(7);
DECLARE VARIABLE WCAMPOLANCPRINC VARCHAR(7);
DECLARE VARIABLE WVALDEB NUMERIC(15,2);
DECLARE VARIABLE WVALCRE NUMERIC(15,2);
DECLARE VARIABLE WVLRDEBAUX NUMERIC(15,2);
DECLARE VARIABLE WVLRCREAUX INTEGER;
DECLARE VARIABLE WCONTA_PARTICIPANTE INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
BEGIN
  conciliacaook = 0;

  -- pega a classificação inicial da conta
  SELECT bdctalon FROM planos_tpla WHERE (bdcodplapadrao = :prcodplapadrao) AND (bdcodtpla = :prcontainicial) INTO :wclassificacaoini;

  -- pega a classificação final da conta
  SELECT bdctalon FROM planos_tpla WHERE (bdcodplapadrao = :prcodplapadrao) AND (bdcodtpla = :prcontafinal) INTO :wclassificacaofim;

  -- limpa as conciliações anteriores
  IF (prlanconc = 1) THEN
     BEGIN
       FOR SELECT tlan.bdchave FROM vsuc_empresas_tlan tlan, planos_tpla tpla
           WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
           AND   (tlan.bdcodplapadrao = :prcodplapadrao)
           AND   (tlan.bdcodplapadrao = tpla.bdcodplapadrao)
           AND   ((tlan.bddebito = tpla.bdcodtpla) OR (tlan.bdcredito = tpla.bdcodtpla))
           AND   (tpla.bdctalon BETWEEN :wclassificacaoini AND :wclassificacaofim)
           --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
           AND   (tlan.bdcontabilizacao IN (0,:prcontabilizacao))
           AND   (bdcodemp = :prempresa) INTO :wchave DO
       BEGIN
         UPDATE vsuc_empresas_tlan SET bdconcd = NULL, bdconcc = NULL WHERE (bdchave = :wchave) AND (bdcodemp = :prempresa);
         conciliacaook = conciliacaook + 1;
       END
     
       IF (conciliacaook > 0) THEN
          conciliacaook = 1;
--       suspend;
     END

  -- retorna as contas selecionadas
  FOR SELECT tpla.bdcodtpla, tpla.BDPARTICIPANTE FROM planos_tpla tpla
      WHERE tpla.bdcodplapadrao = :prcodplapadrao
      AND tpla.bdctalon BETWEEN :wclassificacaoini AND :wclassificacaofim
      ORDER BY tpla.bdctalon
      INTO :wconta, :WCONTA_PARTICIPANTE DO
      BEGIN
        -- retorna os numeros dos documentos de acordo com o parametro de ignorar zeros a esquerda
        FOR SELECT DISTINCT (SELECT nronf FROM VSUC_NRO_NOTA_COMPL(tlan.bddcto, :przeroesq)) FROM vsuc_empresas_tlan tlan
            WHERE tlan.bdcodemp = :prempresa
            AND tlan.bdcodplapadrao = :prcodplapadrao
            AND ((tlan.bddebito = :wconta) OR (tlan.bdcredito = :wconta))
            AND ((tlan.bddcto IS NOT NULL) AND (tlan.bddcto <> ''))
            --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
            AND (tlan.bdcontabilizacao IN (0,:prcontabilizacao))
            ORDER BY tlan.bddcto
            INTO :wnronf DO
            BEGIN

              /*for select bdcodter from tterceiro where (BDCODTER in (select distinct BDCODTERCEIROD from vsuc_empresas_tlan
                                                                       where (bddata between :prdatainicial and :prdatafinal)
                                                                             and   ((bdconcd is null) or (upper(bdconcd) = 'FALSE'))
                                                                             and   ((bdconcc is null) or (upper(bdconcc) = 'FALSE'))
                                                                             and   (bdcodplapadrao = :prcodplapadrao)
                                                                             and   ((bddebito = :wconta) or (bdcredito = :wconta))
                                                                             --#alt:6500 - gilberto - 23/08/2013
                                                                             --and   (bdcodemp = :prempresa)
                                                                             and ((bdcodemp = :prempresa) or (bdcodemp in (select distinct bdfilial from vsuc_empresas_tlan where bdcodemp = :prempresa and bddata between :prdatainicial and :prdatafinal)))
                                                                             --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
                                                                             and (bdcontabilizacao in (0,:prcontabilizacao))
                                                                             --#alt:6773. Carlos Mello(30/09/2013)
                                                                             --and   (bddcto like '%'||:wnronf)
                                                                             and   (Trim(Upper(bddcto)) = Trim(Upper(:wnronf))) and
                                                                             (BDCODTERCEIROD is not null or BDCODTERCEIROC is not null) ))
                                                     or
                                                     (BDCODTER in (select distinct BDCODTERCEIROC from vsuc_empresas_tlan
                                                                       where (bddata between :prdatainicial and :prdatafinal)
                                                                             and   ((bdconcd is null) or (upper(bdconcd) = 'FALSE'))
                                                                             and   ((bdconcc is null) or (upper(bdconcc) = 'FALSE'))
                                                                             and   (bdcodplapadrao = :prcodplapadrao)
                                                                             and   ((bddebito = :wconta) or (bdcredito = :wconta))
                                                                             --#alt:6500 - gilberto - 23/08/2013
                                                                             --and   (bdcodemp = :prempresa)
                                                                             and ((bdcodemp = :prempresa) or (bdcodemp in (select distinct bdfilial from vsuc_empresas_tlan where bdcodemp = :prempresa and bddata between :prdatainicial and :prdatafinal)))
                                                                             --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
                                                                             and (bdcontabilizacao in (0,:prcontabilizacao))
                                                                             --#alt:6773. Carlos Mello(30/09/2013)
                                                                             --and   (bddcto like '%'||:wnronf)
                                                                             and   (Trim(Upper(bddcto)) = Trim(Upper(:wnronf))) and
                                                                             (BDCODTERCEIROD is not null or BDCODTERCEIROC is not null) ))
              order by bdcodter into :WCODTER do
                  begin*/

                      -- soma os lançamentos a debito e a credito

                      -- Não é uma conta de Participante. Bruno Borges - 11/11/2013
                      IF (WCONTA_PARTICIPANTE = 0) THEN
                         BEGIN
                           SELECT SUM(COALESCE((CASE WHEN (bddebito = :wconta) THEN bdvalor END), 0)) "bdvaldeb",
                                  SUM(COALESCE((CASE WHEN (bdcredito = :wconta) THEN bdvalor END), 0)) "bdvalcre"
                               FROM vsuc_empresas_tlan
                               WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
                               AND   ((bdconcd IS NULL) OR (UPPER(bdconcd) = 'FALSE'))
                               AND   ((bdconcc IS NULL) OR (UPPER(bdconcc) = 'FALSE'))
                               AND   (bdcodplapadrao = :prcodplapadrao)
                               AND   ((bddebito = :wconta) OR (bdcredito = :wconta))
                               --#alt:6500 - gilberto - 23/08/2013
                               --and   (bdcodemp = :prempresa)
                               AND ((bdcodemp = :prempresa) OR (bdcodemp IN (SELECT DISTINCT bdfilial FROM vsuc_empresas_tlan WHERE bdcodemp = :prempresa AND bddata BETWEEN :prdatainicial AND :prdatafinal)))
                               --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
                               AND (bdcontabilizacao IN (0,:prcontabilizacao))
                               --#alt:6773. Carlos Mello(30/09/2013)
                               --and   (bddcto like '%'||:wnronf)
                               AND   (TRIM(UPPER(bddcto)) = TRIM(UPPER(:wnronf)))
                               INTO :wvaldeb, :wvalcre;

                               -- verifica se os valores a debito e a credito são iguais para gerar a conciliação
                               IF (((wvaldeb - wvalcre) = 0) AND (wvaldeb > 0) AND (wvalcre > 0)) THEN
                                  BEGIN
                                    -- concilia lançamentos a debito
                                    UPDATE vsuc_empresas_tlan SET bdconcd = 'TRUE'
                                    WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
                                    AND   ((bdconcd IS NULL) OR (UPPER(bdconcd) = 'FALSE'))
                                    AND   ((bdconcc IS NULL) OR (UPPER(bdconcc) = 'FALSE'))
                                    AND   (bdcodplapadrao = :prcodplapadrao)
                                    AND   (bddebito = :wconta)
                                    --#alt:6500 - gilberto - 23/08/2013
                                    --and   (bdcodemp = :prempresa)
                                    AND ((bdcodemp = :prempresa) OR (bdcodemp IN (SELECT DISTINCT bdfilial FROM vsuc_empresas_tlan WHERE bdcodemp = :prempresa AND bddata BETWEEN :prdatainicial AND :prdatafinal)))
                                    --#alt:4750  0 -> Ambos | 1 -> Fiscal | 2 -> Societário | 99 -> Todos
                                    AND   (bdcontabilizacao IN (0,:prcontabilizacao))
                                    --#alt:6773. Carlos Mello(30/09/2013)
                                    --and   (bddcto like '%'||:wnronf);
                                    AND   (TRIM(UPPER(bddcto)) = TRIM(UPPER(:wnronf)));
                 
                                    -- concilia lançamentos a credito
                                    UPDATE vsuc_empresas_tlan SET bdconcc = 'TRUE'
                                    WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
                                    AND   ((bdconcd IS NULL) OR (UPPER(bdconcd) = 'FALSE'))
                                    AND   ((bdconcc IS NULL) OR (UPPER(bdconcc) = 'FALSE'))
                                    AND   (bdcodplapadrao = :prcodplapadrao)
                                    AND   (bdcredito = :wconta)
                                    --#alt:6500 - gilberto - 23/08/2013
                                    --and   (bdcodemp = :prempresa)
                                    AND ((bdcodemp = :prempresa) OR (bdcodemp IN (SELECT DISTINCT bdfilial FROM vsuc_empresas_tlan WHERE bdcodemp = :prempresa AND bddata BETWEEN :prdatainicial AND :prdatafinal)))
                                    --#alt:4750  0 -> Ambos | 1 -> Fiscal | 2 -> Societário | 99 -> Todos
                                    AND   (bdcontabilizacao IN (0,:prcontabilizacao))
                                    --#alt:6773. Carlos Mello(30/09/2013)
                                    --and   (bddcto like '%'||:wnronf);
                                    AND   (TRIM(UPPER(bddcto)) = TRIM(UPPER(:wnronf)));
                 
                                    -- informa que houve conciliação
                                    conciliacaook = 1;
                                  END      



                         END
                      ELSE
                         BEGIN

                            FOR SELECT DISTINCT bdcodter FROM tterceiro WHERE (BDCODTER IN (SELECT /*distinct*/ BDCODTERCEIROD FROM vsuc_empresas_tlan
                                                                                            WHERE ((bdconcd IS NULL) OR (UPPER(bdconcd) = 'FALSE'))
                                                                                                  AND   (bdcodplapadrao = :prcodplapadrao)
                                                                                                  AND   ((bddebito = :wconta))
                                                                                                  --#alt:6500 - gilberto - 23/08/2013
                                                                                                  --and   (bdcodemp = :prempresa)
       
                                                                                                  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
                                                                                                  AND (bdcontabilizacao IN (0,:prcontabilizacao))
                                                                                                  --#alt:6773. Carlos Mello(30/09/2013)
                                                                                                  --and   (bddcto like '%'||:wnronf)
                                                                                                  AND   (TRIM(UPPER(bddcto)) = TRIM(UPPER(:wnronf))) AND
                                                                                                  (BDCODTERCEIROD IS NOT NULL) AND
                                                                                                  (bddata BETWEEN :prdatainicial AND :prdatafinal) AND
                                                                                                  ((bdcodemp IN (SELECT DISTINCT bdfilial FROM vsuc_empresas_tlan WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal) AND (bdcodemp = :prempresa) )) OR (bdcodemp = :prempresa))
                                                                                           )
                                                                              )
                                                                   OR
                                                                   (BDCODTER IN (SELECT /*distinct*/ BDCODTERCEIROC FROM vsuc_empresas_tlan
                                                                                     WHERE ((bdconcc IS NULL) OR (UPPER(bdconcc) = 'FALSE'))
                                                                                           AND   (bdcodplapadrao = :prcodplapadrao)
                                                                                           AND   ((bdcredito = :wconta))
                                                                                           --#alt:6500 - gilberto - 23/08/2013
                                                                                           --and   (bdcodemp = :prempresa)

                                                                                           --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
                                                                                           AND (bdcontabilizacao IN (0,:prcontabilizacao))
                                                                                           --#alt:6773. Carlos Mello(30/09/2013)
                                                                                           --and   (bddcto like '%'||:wnronf)
                                                                                           AND   (TRIM(UPPER(bddcto)) = TRIM(UPPER(:wnronf))) AND
                                                                                           (BDCODTERCEIROC IS NOT NULL) AND
                                                                                           (bddata BETWEEN :prdatainicial AND :prdatafinal) AND
                                                                                           ((bdcodemp IN (SELECT DISTINCT bdfilial FROM vsuc_empresas_tlan WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal) AND (bdcodemp = :prempresa) )) OR (bdcodemp = :prempresa))
                                                                                )
                                                                   )
                            ORDER BY bdcodter INTO :WCODTER DO     
                                BEGIN

                                   SELECT SUM(COALESCE((CASE WHEN (bddebito = :wconta) THEN bdvalor END), 0)) "bdvaldeb",
                                          SUM(COALESCE((CASE WHEN (bdcredito = :wconta) THEN bdvalor END), 0)) "bdvalcre"
                                       FROM vsuc_empresas_tlan
                                       WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
                                       AND   ((bdconcd IS NULL) OR (UPPER(bdconcd) = 'FALSE'))
                                       AND   ((bdconcc IS NULL) OR (UPPER(bdconcc) = 'FALSE'))
                                       AND   (bdcodplapadrao = :prcodplapadrao)
                                       AND   ((bddebito = :wconta) OR (bdcredito = :wconta))
                                       --#alt:6500 - gilberto - 23/08/2013
                                       --and   (bdcodemp = :prempresa)
                                       AND ((bdcodemp = :prempresa) OR (bdcodemp IN (SELECT DISTINCT bdfilial FROM vsuc_empresas_tlan WHERE bdcodemp = :prempresa AND bddata BETWEEN :prdatainicial AND :prdatafinal)))
                                       --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
                                       AND (bdcontabilizacao IN (0,:prcontabilizacao))
                                       --#alt:6773. Carlos Mello(30/09/2013)
                                       --and   (bddcto like '%'||:wnronf)
                                       AND   (TRIM(UPPER(bddcto)) = TRIM(UPPER(:wnronf)))
        
                                       /*********************************************************/
             
                                       AND (BDCODTERCEIROD = :WCODTER OR BDCODTERCEIROC = :WCODTER)
        
                                       /*******************************************************/
             
                                       INTO :wvaldeb, :wvalcre;
        
        
                                       -- verifica se os valores a debito e a credito são iguais para gerar a conciliação
                                       IF (((wvaldeb - wvalcre) = 0) AND (wvaldeb > 0) AND (wvalcre > 0)) THEN
                                          BEGIN
                                            -- concilia lançamentos a debito
                                            UPDATE vsuc_empresas_tlan SET bdconcd = 'TRUE'
                                            WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
                                            AND   ((bdconcd IS NULL) OR (UPPER(bdconcd) = 'FALSE'))
                                            AND   ((bdconcc IS NULL) OR (UPPER(bdconcc) = 'FALSE'))
                                            AND   (bdcodplapadrao = :prcodplapadrao)
                                            AND   (bddebito = :wconta)
                                            --#alt:6500 - gilberto - 23/08/2013
                                            --and   (bdcodemp = :prempresa)
                                            AND ((bdcodemp = :prempresa) OR (bdcodemp IN (SELECT DISTINCT bdfilial FROM vsuc_empresas_tlan WHERE bdcodemp = :prempresa AND bddata BETWEEN :prdatainicial AND :prdatafinal)))
                                            --#alt:4750  0 -> Ambos | 1 -> Fiscal | 2 -> Societário | 99 -> Todos
                                            AND   (bdcontabilizacao IN (0,:prcontabilizacao))
                                            --#alt:6773. Carlos Mello(30/09/2013)
                                            --and   (bddcto like '%'||:wnronf);
                                            AND   (TRIM(UPPER(bddcto)) = TRIM(UPPER(:wnronf)))

                                            AND (BDCODTERCEIROD = :WCODTER);
                         


                                            -- concilia lançamentos a credito
                                            UPDATE vsuc_empresas_tlan SET bdconcc = 'TRUE'
                                            WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
                                            AND   ((bdconcd IS NULL) OR (UPPER(bdconcd) = 'FALSE'))
                                            AND   ((bdconcc IS NULL) OR (UPPER(bdconcc) = 'FALSE'))
                                            AND   (bdcodplapadrao = :prcodplapadrao)
                                            AND   (bdcredito = :wconta)
                                            --#alt:6500 - gilberto - 23/08/2013
                                            --and   (bdcodemp = :prempresa)
                                            AND ((bdcodemp = :prempresa) OR (bdcodemp IN (SELECT DISTINCT bdfilial FROM vsuc_empresas_tlan WHERE bdcodemp = :prempresa AND bddata BETWEEN :prdatainicial AND :prdatafinal)))
                                            --#alt:4750  0 -> Ambos | 1 -> Fiscal | 2 -> Societário | 99 -> Todos
                                            AND   (bdcontabilizacao IN (0,:prcontabilizacao))
                                            --#alt:6773. Carlos Mello(30/09/2013)
                                            --and   (bddcto like '%'||:wnronf);
                                            AND   (TRIM(UPPER(bddcto)) = TRIM(UPPER(:wnronf)))

                                            AND (BDCODTERCEIROC = :WCODTER);

                         
                                            -- informa que houve conciliação
                                            conciliacaook = 1;
                                          END      
                                END
                         END



                      /*
                      -- verifica se os valores a debito e a credito são iguais para gerar a conciliação
                      if (((wvaldeb - wvalcre) = 0) and (wvaldeb > 0) and (wvalcre > 0)) then
                         begin
                           -- concilia lançamentos a debito
                           update vsuc_empresas_tlan set bdconcd = 'TRUE'
                           where (bddata between :prdatainicial and :prdatafinal)
                           and   ((bdconcd is null) or (upper(bdconcd) = 'FALSE'))
                           and   ((bdconcc is null) or (upper(bdconcc) = 'FALSE'))
                           and   (bdcodplapadrao = :prcodplapadrao)
                           and   (bddebito = :wconta)
                           --#alt:6500 - gilberto - 23/08/2013
                           --and   (bdcodemp = :prempresa)
                           and ((bdcodemp = :prempresa) or (bdcodemp in (select distinct bdfilial from vsuc_empresas_tlan where bdcodemp = :prempresa and bddata between :prdatainicial and :prdatafinal)))
                           --#alt:4750  0 -> Ambos | 1 -> Fiscal | 2 -> Societário | 99 -> Todos
                           and   (bdcontabilizacao in (0,:prcontabilizacao))
                           --#alt:6773. Carlos Mello(30/09/2013)
                           --and   (bddcto like '%'||:wnronf);
                           and   (Trim(Upper(bddcto)) = Trim(Upper(:wnronf)));
        
                           -- concilia lançamentos a credito
                           update vsuc_empresas_tlan set bdconcc = 'TRUE'
                           where (bddata between :prdatainicial and :prdatafinal)
                           and   ((bdconcd is null) or (upper(bdconcd) = 'FALSE'))
                           and   ((bdconcc is null) or (upper(bdconcc) = 'FALSE'))
                           and   (bdcodplapadrao = :prcodplapadrao)
                           and   (bdcredito = :wconta)
                           --#alt:6500 - gilberto - 23/08/2013
                           --and   (bdcodemp = :prempresa)
                           and ((bdcodemp = :prempresa) or (bdcodemp in (select distinct bdfilial from vsuc_empresas_tlan where bdcodemp = :prempresa and bddata between :prdatainicial and :prdatafinal)))
                           --#alt:4750  0 -> Ambos | 1 -> Fiscal | 2 -> Societário | 99 -> Todos
                           and   (bdcontabilizacao in (0,:prcontabilizacao))
                           --#alt:6773. Carlos Mello(30/09/2013)
                           --and   (bddcto like '%'||:wnronf);
                           and   (Trim(Upper(bddcto)) = Trim(Upper(:wnronf)));
        
                           -- informa que houve conciliação
                           conciliacaook = 1;
                         end      
                        */
                  --end
            END
      END
  SUSPEND;

/*
  conciliacaook = 0;

  -- pega a classificação inicial da conta
  select bdctalon from planos_tpla where (bdcodplapadrao = :prcodplapadrao) and (bdcodtpla = :prcontainicial) into :wclassificacaoini;

  -- pega a classificação final da conta
  select bdctalon from planos_tpla where (bdcodplapadrao = :prcodplapadrao) and (bdcodtpla = :prcontafinal) into :wclassificacaofim;

  -- limpa as conciliações anteriores
  if (prlanconc = 1) then
     begin
       for select tlan.bdchave from vsuc_empresas_tlan tlan, planos_tpla tpla
           where (bddata Between :prdatainicial and :prdatafinal)
           and   (tlan.bdcodplapadrao = :prcodplapadrao)
           and   (tlan.bdcodplapadrao = tpla.bdcodplapadrao)
           and   ((tlan.bddebito = tpla.bdcodtpla) or (tlan.bdcredito = tpla.bdcodtpla))
           and   (tpla.bdctalon between :wclassificacaoini and :wclassificacaofim)
           --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
           and   (tlan.bdcontabilizacao in (0,:prcontabilizacao))
           and   (bdcodemp = :prempresa) into :wchave do
       begin
         update vsuc_empresas_tlan set bdconcd = null, bdconcc = null where (bdchave = :wchave) and (bdcodemp = :prempresa);
         conciliacaook = conciliacaook + 1;
       end
     
       if (conciliacaook > 0) then
          conciliacaook = 1;
--       suspend;
     end

  -- retorna as contas selecionadas
  for select tpla.bdcodtpla from planos_tpla tpla
      where tpla.bdcodplapadrao = :prcodplapadrao
      and tpla.bdctalon between :wclassificacaoini and :wclassificacaofim
      order by tpla.bdctalon
      into :wconta do
      begin
        -- retorna os numeros dos documentos de acordo com o parametro de ignorar zeros a esquerda
        for select distinct (select nronf from VSUC_NRO_NOTA_COMPL(tlan.bddcto, :przeroesq)) from vsuc_empresas_tlan tlan
            where tlan.bdcodemp = :prempresa
            and tlan.bdcodplapadrao = :prcodplapadrao
            and ((tlan.bddebito = :wconta) or (tlan.bdcredito = :wconta))
            and ((tlan.bddcto is not null) and (tlan.bddcto <> ''))
            --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
            and (tlan.bdcontabilizacao in (0,:prcontabilizacao))
            order by tlan.bddcto
            into :wnronf do
            begin
              -- soma os lançamentos a debito e a credito
              select sum(coalesce((case when (bddebito = :wconta) then bdvalor end), 0)) "bdvaldeb",
                     sum(coalesce((case when (bdcredito = :wconta) then bdvalor end), 0)) "bdvalcre"
                  from vsuc_empresas_tlan
                  where (bddata between :prdatainicial and :prdatafinal)
                  and   ((bdconcd is null) or (upper(bdconcd) = 'FALSE'))
                  and   ((bdconcc is null) or (upper(bdconcc) = 'FALSE'))
                  and   (bdcodplapadrao = :prcodplapadrao)
                  and   ((bddebito = :wconta) or (bdcredito = :wconta))
                  --#alt:6500 - gilberto - 23/08/2013
                  --and   (bdcodemp = :prempresa)
                  and ((bdcodemp = :prempresa) or (bdcodemp in (select distinct bdfilial from vsuc_empresas_tlan where bdcodemp = :prempresa and bddata between :prdatainicial and :prdatafinal)))
                  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
                  and (bdcontabilizacao in (0,:prcontabilizacao))
                  --#alt:6773. Carlos Mello(30/09/2013)
                  --and   (bddcto like '%'||:wnronf)
                  and   (Trim(Upper(bddcto)) = Trim(Upper(:wnronf)))
                  into :wvaldeb, :wvalcre;
              -- verifica se os valores a debito e a credito são iguais para gerar a conciliação
              if (((wvaldeb - wvalcre) = 0) and (wvaldeb > 0) and (wvalcre > 0)) then
                 begin
                   -- concilia lançamentos a debito
                   update vsuc_empresas_tlan set bdconcd = 'TRUE'
                   where (bddata between :prdatainicial and :prdatafinal)
                   and   ((bdconcd is null) or (upper(bdconcd) = 'FALSE'))
                   and   ((bdconcc is null) or (upper(bdconcc) = 'FALSE'))
                   and   (bdcodplapadrao = :prcodplapadrao)
                   and   (bddebito = :wconta)
                   --#alt:6500 - gilberto - 23/08/2013
                   --and   (bdcodemp = :prempresa)
                   and ((bdcodemp = :prempresa) or (bdcodemp in (select distinct bdfilial from vsuc_empresas_tlan where bdcodemp = :prempresa and bddata between :prdatainicial and :prdatafinal)))
                   --#alt:4750  0 -> Ambos | 1 -> Fiscal | 2 -> Societário | 99 -> Todos
                   and   (bdcontabilizacao in (0,:prcontabilizacao))
                   --#alt:6773. Carlos Mello(30/09/2013)
                   --and   (bddcto like '%'||:wnronf);
                   and   (Trim(Upper(bddcto)) = Trim(Upper(:wnronf)));

                   -- concilia lançamentos a credito
                   update vsuc_empresas_tlan set bdconcc = 'TRUE'
                   where (bddata between :prdatainicial and :prdatafinal)
                   and   ((bdconcd is null) or (upper(bdconcd) = 'FALSE'))
                   and   ((bdconcc is null) or (upper(bdconcc) = 'FALSE'))
                   and   (bdcodplapadrao = :prcodplapadrao)
                   and   (bdcredito = :wconta)
                   --#alt:6500 - gilberto - 23/08/2013
                   --and   (bdcodemp = :prempresa)
                   and ((bdcodemp = :prempresa) or (bdcodemp in (select distinct bdfilial from vsuc_empresas_tlan where bdcodemp = :prempresa and bddata between :prdatainicial and :prdatafinal)))
                   --#alt:4750  0 -> Ambos | 1 -> Fiscal | 2 -> Societário | 99 -> Todos
                   and   (bdcontabilizacao in (0,:prcontabilizacao))
                   --#alt:6773. Carlos Mello(30/09/2013)
                   --and   (bddcto like '%'||:wnronf);
                   and   (Trim(Upper(bddcto)) = Trim(Upper(:wnronf)));

                   -- informa que houve conciliação
                   conciliacaook = 1;
                 end
            end
      end
  suspend;
 */
END
^

/* Restore proc. body: VSUC_SP_MOVIMENTO_MENSAL */
ALTER PROCEDURE VSUC_SP_MOVIMENTO_MENSAL(
    PRCODEMP VARCHAR(1024),
    PRCONTA INTEGER,
    PRCC VARCHAR(8192),
    PRANOINICIAL INTEGER,
    PRANOFINAL INTEGER,
    PRREFEMP INTEGER,
    PRPARTICIPANTE INTEGER,
    PRIGNORAZERAMENTO INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER) 
RETURNS (
    BDDEB01 NUMERIC(15,2),
    BDDEB02 NUMERIC(15,2),
    BDDEB03 NUMERIC(15,2),
    BDDEB04 NUMERIC(15,2),
    BDDEB05 NUMERIC(15,2),
    BDDEB06 NUMERIC(15,2),
    BDDEB07 NUMERIC(15,2),
    BDDEB08 NUMERIC(15,2),
    BDDEB09 NUMERIC(15,2),
    BDDEB10 NUMERIC(15,2),
    BDDEB11 NUMERIC(15,2),
    BDDEB12 NUMERIC(15,2),
    BDCRE01 NUMERIC(15,2),
    BDCRE02 NUMERIC(15,2),
    BDCRE03 NUMERIC(15,2),
    BDCRE04 NUMERIC(15,2),
    BDCRE05 NUMERIC(15,2),
    BDCRE06 NUMERIC(15,2),
    BDCRE07 NUMERIC(15,2),
    BDCRE08 NUMERIC(15,2),
    BDCRE09 NUMERIC(15,2),
    BDCRE10 NUMERIC(15,2),
    BDCRE11 NUMERIC(15,2),
    BDCRE12 NUMERIC(15,2),
    BDMOV01 NUMERIC(15,2),
    BDMOV02 NUMERIC(15,2),
    BDMOV03 NUMERIC(15,2),
    BDMOV04 NUMERIC(15,2),
    BDMOV05 NUMERIC(15,2),
    BDMOV06 NUMERIC(15,2),
    BDMOV07 NUMERIC(15,2),
    BDMOV08 NUMERIC(15,2),
    BDMOV09 NUMERIC(15,2),
    BDMOV10 NUMERIC(15,2),
    BDMOV11 NUMERIC(15,2),
    BDMOV12 NUMERIC(15,2),
    BDSAL01 NUMERIC(15,2),
    BDSAL02 NUMERIC(15,2),
    BDSAL03 NUMERIC(15,2),
    BDSAL04 NUMERIC(15,2),
    BDSAL05 NUMERIC(15,2),
    BDSAL06 NUMERIC(15,2),
    BDSAL07 NUMERIC(15,2),
    BDSAL08 NUMERIC(15,2),
    BDSAL09 NUMERIC(15,2),
    BDSAL10 NUMERIC(15,2),
    BDSAL11 NUMERIC(15,2),
    BDSAL12 NUMERIC(15,2),
    BDSALTOTDEB NUMERIC(15,2),
    BDSALTOTCRE NUMERIC(15,2),
    BDSALTOTMOV NUMERIC(15,2),
    BDSALTOTATU NUMERIC(15,2),
    BDANO INTEGER,
    BDGRPCTA INTEGER,
    BDDEBANT NUMERIC(15,2),
    BDCREANT NUMERIC(15,2),
    BDMOVANT NUMERIC(15,2),
    BDSALANT NUMERIC(15,2)) 
AS
DECLARE VARIABLE WSQL VARCHAR(1024);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WBDSALTOTDEB NUMERIC(15,2);
DECLARE VARIABLE WBDSALTOTCRE NUMERIC(15,2);
DECLARE VARIABLE WBDSALTOTMOV NUMERIC(15,2);
DECLARE VARIABLE WBDSALTOTATU NUMERIC(15,2);
DECLARE VARIABLE WBDDEBANT NUMERIC(15,2);
DECLARE VARIABLE WBDCREANT NUMERIC(15,2);
DECLARE VARIABLE WBDSALANT NUMERIC(15,2);
DECLARE VARIABLE WBDDEB01 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB02 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB03 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB04 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB05 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB06 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB07 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB08 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB09 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB10 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB11 NUMERIC(15,2);
DECLARE VARIABLE WBDDEB12 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE01 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE02 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE03 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE04 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE05 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE06 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE07 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE08 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE09 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE10 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE11 NUMERIC(15,2);
DECLARE VARIABLE WBDCRE12 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV01 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV02 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV03 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV04 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV05 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV06 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV07 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV08 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV09 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV10 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV11 NUMERIC(15,2);
DECLARE VARIABLE WBDMOV12 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL01 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL02 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL03 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL04 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL05 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL06 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL07 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL08 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL09 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL10 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL11 NUMERIC(15,2);
DECLARE VARIABLE WBDSAL12 NUMERIC(15,2);
BEGIN
  wcount = 0;
  WHILE (wcount <= pranofinal - pranoinicial) DO
    BEGIN
      BDANO = :pranoinicial + :wcount;
      --Precisa zerar o valores para não interferir nos valores dos próximos anos
      bdsaltotdeb = 0;
      bdsaltotcre = 0;
      bdsaltotmov = 0;
      bdsaltotatu = 0;
      bddebant    = 0;
      bdcreant    = 0;
      bdmovant    = 0;
      bdsalant    = 0;

      bddeb01 = 0;
      bddeb02 = 0;
      bddeb03 = 0;
      bddeb04 = 0;
      bddeb05 = 0;
      bddeb06 = 0;
      bddeb07 = 0;
      bddeb08 = 0;
      bddeb09 = 0;
      bddeb10 = 0;
      bddeb11 = 0;
      bddeb12 = 0;

      bdcre01 = 0;
      bdcre02 = 0;
      bdcre03 = 0;
      bdcre04 = 0;
      bdcre05 = 0;
      bdcre06 = 0;
      bdcre07 = 0;
      bdcre08 = 0;
      bdcre09 = 0;
      bdcre10 = 0;
      bdcre11 = 0;
      bdcre12 = 0;

      --alt:9515 - Adicionado campo do movimento. Pedro
      bdmov01 = 0;
      bdmov02 = 0;
      bdmov03 = 0;
      bdmov04 = 0;
      bdmov05 = 0;
      bdmov06 = 0;
      bdmov07 = 0;
      bdmov08 = 0;
      bdmov09 = 0;
      bdmov10 = 0;
      bdmov11 = 0;
      bdmov12 = 0;

      bdsal01 = 0;
      bdsal02 = 0;
      bdsal03 = 0;
      bdsal04 = 0;
      bdsal05 = 0;
      bdsal06 = 0;
      bdsal07 = 0;
      bdsal08 = 0;
      bdsal09 = 0;
      bdsal10 = 0;
      bdsal11 = 0;
      bdsal12 = 0;

      wsql = 'select bdcodemp from tempresas where bdcodemp in ('||prcodemp||')';
      FOR EXECUTE STATEMENT wsql INTO :wcodemp DO
          BEGIN
            SELECT bdano, bdgrpcta, bdsaltotdeb, bdsaltotcre, bdsaltotmov, bdsaltotatu, bddebant, bdcreant, bdsalant,
                   bddeb01, bddeb02, bddeb03, bddeb04, bddeb05, bddeb06, bddeb07, bddeb08, bddeb09, bddeb10, bddeb11, bddeb12,
                   bdcre01, bdcre02, bdcre03, bdcre04, bdcre05, bdcre06, bdcre07, bdcre08, bdcre09, bdcre10, bdcre11, bdcre12,
                   bdmov01, bdmov02, bdmov03, bdmov04, bdmov05, bdmov06, bdmov07, bdmov08, bdmov09, bdmov10, bdmov11, bdmov12,
                   bdsal01, bdsal02, bdsal03, bdsal04, bdsal05, bdsal06, bdsal07, bdsal08, bdsal09, bdsal10, bdsal11, bdsal12
            FROM vsuc_sp_retorna_mov_mensal(:wcodemp, :prconta, :prcc, :bdano, :bdano, :prrefemp, :prparticipante, :prignorazeramento,:prcontabilizacao,:prmatrizfilialconsolidado)
            INTO :bdano, :bdgrpcta, :wbdsaltotdeb, :wbdsaltotcre, :wbdsaltotmov, :wbdsaltotatu, :wbddebant, :wbdcreant, :wbdsalant,
                 :wbddeb01, :wbddeb02, :wbddeb03, :wbddeb04, :wbddeb05, :wbddeb06, :wbddeb07, :wbddeb08, :wbddeb09, :wbddeb10, :wbddeb11, :wbddeb12,
                 :wbdcre01, :wbdcre02, :wbdcre03, :wbdcre04, :wbdcre05, :wbdcre06, :wbdcre07, :wbdcre08, :wbdcre09, :wbdcre10, :wbdcre11, :wbdcre12,
                 :wbdmov01, :wbdmov02, :wbdmov03, :wbdmov04, :wbdmov05, :wbdmov06, :wbdmov07, :wbdmov08, :wbdmov09, :wbdmov10, :wbdmov11, :wbdmov12,
                 :wbdsal01, :wbdsal02, :wbdsal03, :wbdsal04, :wbdsal05, :wbdsal06, :wbdsal07, :wbdsal08, :wbdsal09, :wbdsal10, :wbdsal11, :wbdsal12;

            bdsaltotdeb = COALESCE(bdsaltotdeb, 0) + COALESCE(wbdsaltotdeb, 0);
            bdsaltotcre = COALESCE(bdsaltotcre, 0) + COALESCE(wbdsaltotcre, 0);
            bdsaltotatu = COALESCE(bdsaltotatu, 0) + COALESCE(wbdsaltotatu, 0);
            bdsaltotmov = COALESCE(bdsaltotmov, 0) + COALESCE(wbdsaltotmov, 0);
            bddebant    = COALESCE(bddebant, 0) + COALESCE(wbddebant, 0);
            bdcreant    = COALESCE(bdcreant, 0) + COALESCE(wbdcreant, 0);
            bdsalant    = COALESCE(bdsalant, 0) + COALESCE(wbdsalant, 0);

            bddeb01 = COALESCE(bddeb01, 0) + COALESCE(wbddeb01, 0);
            bddeb02 = COALESCE(bddeb02, 0) + COALESCE(wbddeb02, 0);
            bddeb03 = COALESCE(bddeb03, 0) + COALESCE(wbddeb03, 0);
            bddeb04 = COALESCE(bddeb04, 0) + COALESCE(wbddeb04, 0);
            bddeb05 = COALESCE(bddeb05, 0) + COALESCE(wbddeb05, 0);
            bddeb06 = COALESCE(bddeb06, 0) + COALESCE(wbddeb06, 0);
            bddeb07 = COALESCE(bddeb07, 0) + COALESCE(wbddeb07, 0);
            bddeb08 = COALESCE(bddeb08, 0) + COALESCE(wbddeb08, 0);
            bddeb09 = COALESCE(bddeb09, 0) + COALESCE(wbddeb09, 0);
            bddeb10 = COALESCE(bddeb10, 0) + COALESCE(wbddeb10, 0);
            bddeb11 = COALESCE(bddeb11, 0) + COALESCE(wbddeb11, 0);
            bddeb12 = COALESCE(bddeb12, 0) + COALESCE(wbddeb12, 0);

            bdcre01 = COALESCE(bdcre01, 0) + COALESCE(wbdcre01, 0);
            bdcre02 = COALESCE(bdcre02, 0) + COALESCE(wbdcre02, 0);
            bdcre03 = COALESCE(bdcre03, 0) + COALESCE(wbdcre03, 0);
            bdcre04 = COALESCE(bdcre04, 0) + COALESCE(wbdcre04, 0);
            bdcre05 = COALESCE(bdcre05, 0) + COALESCE(wbdcre05, 0);
            bdcre06 = COALESCE(bdcre06, 0) + COALESCE(wbdcre06, 0);
            bdcre07 = COALESCE(bdcre07, 0) + COALESCE(wbdcre07, 0);
            bdcre08 = COALESCE(bdcre08, 0) + COALESCE(wbdcre08, 0);
            bdcre09 = COALESCE(bdcre09, 0) + COALESCE(wbdcre09, 0);
            bdcre10 = COALESCE(bdcre10, 0) + COALESCE(wbdcre10, 0);
            bdcre11 = COALESCE(bdcre11, 0) + COALESCE(wbdcre11, 0);
            bdcre12 = COALESCE(bdcre12, 0) + COALESCE(wbdcre12, 0);

            --alt:9515 - Adicionados campos do movimento. Pedro
            bdmov01 = COALESCE(bdmov01, 0) + COALESCE(wbdmov01, 0);
            bdmov02 = COALESCE(bdmov02, 0) + COALESCE(wbdmov02, 0);
            bdmov03 = COALESCE(bdmov03, 0) + COALESCE(wbdmov03, 0);
            bdmov04 = COALESCE(bdmov04, 0) + COALESCE(wbdmov04, 0);
            bdmov05 = COALESCE(bdmov05, 0) + COALESCE(wbdmov05, 0);
            bdmov06 = COALESCE(bdmov06, 0) + COALESCE(wbdmov06, 0);
            bdmov07 = COALESCE(bdmov07, 0) + COALESCE(wbdmov07, 0);
            bdmov08 = COALESCE(bdmov08, 0) + COALESCE(wbdmov08, 0);
            bdmov09 = COALESCE(bdmov09, 0) + COALESCE(wbdmov09, 0);
            bdmov10 = COALESCE(bdmov10, 0) + COALESCE(wbdmov10, 0);
            bdmov11 = COALESCE(bdmov11, 0) + COALESCE(wbdmov11, 0);
            bdmov12 = COALESCE(bdmov12, 0) + COALESCE(wbdmov12, 0);

            bdsal01 = COALESCE(bdsal01, 0) + COALESCE(wbdsal01, 0);
            bdsal02 = COALESCE(bdsal02, 0) + COALESCE(wbdsal02, 0);
            bdsal03 = COALESCE(bdsal03, 0) + COALESCE(wbdsal03, 0);
            bdsal04 = COALESCE(bdsal04, 0) + COALESCE(wbdsal04, 0);
            bdsal05 = COALESCE(bdsal05, 0) + COALESCE(wbdsal05, 0);
            bdsal06 = COALESCE(bdsal06, 0) + COALESCE(wbdsal06, 0);
            bdsal07 = COALESCE(bdsal07, 0) + COALESCE(wbdsal07, 0);
            bdsal08 = COALESCE(bdsal08, 0) + COALESCE(wbdsal08, 0);
            bdsal09 = COALESCE(bdsal09, 0) + COALESCE(wbdsal09, 0);
            bdsal10 = COALESCE(bdsal10, 0) + COALESCE(wbdsal10, 0);
            bdsal11 = COALESCE(bdsal11, 0) + COALESCE(wbdsal11, 0);
            bdsal12 = COALESCE(bdsal12, 0) + COALESCE(wbdsal12, 0);
          END

      wcount = wcount + 1;
      SUSPEND;
    END
END
^

/* Restore proc. body: VSUC_SP_NOMENCLATURA_CTA_PARTIC */
CREATE OR ALTER PROCEDURE VSUC_SP_NOMENCLATURA_CTA_PARTIC (
    PRCODTERCEIRO INTEGER,
    PRCLASSIFICACAO VARCHAR(40),
    PRCONCATENA INTEGER,
    PRREFEMP INTEGER)
RETURNS (
    BDNOME VARCHAR(100),
    BDCLASSIFICACAO VARCHAR(100))
AS
DECLARE VARIABLE WNOME VARCHAR(100);
DECLARE VARIABLE WSQL VARCHAR(2000);
DECLARE VARIABLE WPOS INTEGER;
BEGIN

  BDCLASSIFICACAO = REVERSE(PRCLASSIFICACAO);
  BDCLASSIFICACAO = SUBSTRING(BDCLASSIFICACAO FROM POSITION('.', BDCLASSIFICACAO) FOR STRLEN(BDCLASSIFICACAO));
  BDCLASSIFICACAO = REVERSE(BDCLASSIFICACAO);
  BDCLASSIFICACAO = BDCLASSIFICACAO || LPAD(PRCODTERCEIRO, 9, '0');

  SELECT FIRST 1 BDNOMETER
  FROM TTERCEIRO_REF X
  WHERE BDCODTER = :PRCODTERCEIRO AND
        BDREFEMP <= COALESCE((SELECT FIRST 1 RF2.BDREFEMP
                              FROM TTERCEIRO_REF RF2
                              WHERE RF2.BDCODTER = X.BDCODTER AND
                                    RF2.BDREFEMP <= :PRREFEMP
                              ORDER BY RF2.BDCODTER DESC, RF2.BDREFEMP DESC), (SELECT FIRST 1 RF2.BDREFEMP
                                                                               FROM TTERCEIRO_REF RF2
                                                                               WHERE RF2.BDCODTER = X.BDCODTER
                                                                               ORDER BY RF2.BDCODTER, RF2.BDREFEMP))
  ORDER BY BDREFEMP DESC
  INTO :WNOME;

  IF (PRCONCATENA = 1) THEN
    BEGIN
    WPOS = CHARACTER_LENGTH(:PRCODTERCEIRO);
    -- 100 -> máximo de caracteres para nome da conta
              -- 03 -> qtd de caracteres " - ";
    WPOS = ((100 - WPOS) - 3);
    WNOME = PRCODTERCEIRO || ' - ' || SUBSTRING(WNOME FROM 1 FOR WPOS);
    END

  BDNOME = SUBSTRING(WNOME FROM 1 FOR 100);
  SUSPEND;
END
^

/* Restore proc. body: VSUC_SP_PERMITECALCSALDOLANCMF */
ALTER PROCEDURE VSUC_SP_PERMITECALCSALDOLANCMF(PRCAMPO INTEGER,
PRCODEMPMASTER INTEGER,
PRCODEMP INTEGER,
PRFILIAL INTEGER,
PRTIPOLANCFILIAL INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PREMPRESAS VARCHAR(2048))
 RETURNS(BDPERMITE SMALLINT)
 AS
DECLARE VARIABLE wpos_matriz INTEGER;
DECLARE VARIABLE wpos_filial INTEGER;
DECLARE VARIABLE wpos_pernamatriz INTEGER;
BEGIN
  --Carlos Mello - #alt:5837. Foi feito uma alteração onde é permitodo lançar nas filias mesmo estando na matriz, mas
  --para calcular o saldo precisa seguir algumas regras. Ex: Se estou na matriz, filial, filtros ou qual perna do lançamento deve calcular
  --OBS.: Caso tenha alguma alterção nessa regra, favor verficar a rotina "getPermiteCalcSaldoLancMatrizFilial" no fonte uLancamentoDBMGR

  -- BDPERMITE, PRCONSOLIDADO  -> 0 - False | 1 - True
  -- PRCAMPO, PRTIPOLANCFILIAL -> 1 - Débito | 2 - Crédito
  -- PRCONSOLIDADO -> Pelo que observei algumas stored procedure calculam separadamente as empresas e depois somam a matriz com filial, por isso foi criado o parâmetro
  bdpermite = 0;
  IF (prfilial IS NULL) THEN
    prfilial = 0;

  --Estou na matriz e tem uma perna do lançamento na filial, mas só quero os lançamentos da matriz(a perna da matriz) e que a matriz esteja no filtro
  --select Pos from pos(','||:prcodempmaster||',', ','||:prempresas||',') into :wpos_pernamatriz;
  --alt:#6535 - gilberto - 05/09/2013
  wpos_pernamatriz = POSITION(prcodempmaster, prcodemp);

  --Estou na matriz mas também quero os lançamentos da filial conforme o filtro(Lançamentos que foram feito na filial -> BDCODEMP = Filial)
  --select Pos from pos(','||:prcodemp||',', ','||:prempresas||',') into :wpos_matriz;
  --alt:#6535 - gilberto - 05/09/2013
  wpos_matriz = POSITION(prcodemp,  prempresas);

  --Estou na matriz mas também quero a perna que está na filial conforme o filtro
  --select Pos from pos(','||:prfilial||',', ','||:prempresas||',') into :wpos_filial;
  --alt:#6535 - gilberto - 05/09/2013
  wpos_filial = POSITION(prfilial,  prempresas);


  IF (((prcodempmaster = prcodemp) AND (prfilial = 0)) OR
      --Estou na filial mas o lançamento foi feito na matriz para a filial(uma perna)
      ((prcodempmaster = prfilial) AND (prcampo = prtipolancfilial)) OR
      --Estou na matriz e tem uma perna do lançamento na filial, mas só quero os lançamentos da matriz(a perna da matriz) e que a matriz esteja no filtro
      ((prcodempmaster = prcodemp) AND (prfilial <> 0) AND (prcampo <> prtipolancfilial) AND (wpos_pernamatriz > 0)) OR
      --Estou na matriz mas também quero os lançamentos da filial conforme o filtro(Lançamentos que foram feito na filial -> BDCODEMP = Filial)
      ((prmatrizfilialconsolidado = 1) AND (prcodempmaster <> prcodemp) AND (prfilial = 0) AND (wpos_matriz > 0)) OR
      --Estou na matriz mas também quero a perna que está na filial conforme o filtro
      ((prmatrizfilialconsolidado = 1) AND (prcodempmaster = prcodemp) AND (prfilial <> 0) AND (prcampo = prtipolancfilial) AND (wpos_filial > 0))) THEN
    bdpermite = 1;
  SUSPEND;
END
^

/* Restore proc. body: VSUC_SP_RETORNA_BALANCETE */
create or alter procedure VSUC_SP_RETORNA_BALANCETE (
    PRCODEMP varchar(2048),
    PRDATINI date,
    PRDATFIN date,
    PRIGNORA_ZERAMENTO integer,
    PRCTAINI integer,
    PRCTAFIN integer,
    PRINDICE integer,
    PRCODTPCC varchar(32000),
    PRREFEMP integer,
    PRLANSEMCC integer,
    PRORDEM integer,
    PRNAOMOSTRACONTACOMP integer,
    PRCONSOLIDADA integer,
    PRDETALHARCTAPARTICIPANTE integer,
    PRAGRUPARPARTICIPANTEPORCNPJ integer,
    PRCONCATENACODPARTICIPANTE integer,
    PRNIVEISCONTA varchar(50),
    PRTODASASCONTAS integer,
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRDRE integer = 0,
    PRTODOPLANOCONTAS integer = 0,
    PRDETALHAREMPREENDIMENTO integer = 0,
    PRDETALHARUNIDIMOB integer = 0,
    PRMOSTRARPROP integer = 0,
    PRDADOSIMPRIMIR integer = 0,
    PRAGRUPARPARTICIPANTEPORCPF integer = 0,
    PRNIVELCC integer = 0,
    PRSOMENTEMOVIMENTO integer = 0,
    PREMPREENDIMENTO varchar(32000) = '' /* COLLATE WIN1252 - default */ ,
    PRPLANOGRPECO integer = 0,
    PREMPRESAGRPECO integer = 0,
    PRGRPECO integer = 0,
    PRTODOSPART varchar(2048) = '' /* COLLATE WIN1252 - default */ ,
    PRDETALHARCCEMPREEND integer = 0,
    PRIGNZERPERANT integer = 0,
    PRTIPOLAN varchar(3200) = '' /* COLLATE WIN1252 - default */ ,
    PRELIMINACOESK300K315 integer = 0)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(18),
    BDCODMATRIZ integer,
    BDCODEMPFILIAL integer,
    BDCODPLAPADRAO integer,
    BDCODCTA integer,
    BDCTALON varchar(60),
    BDNOMCTA varchar(300),
    BDTIPCTA smallint,
    BDCODTPCC integer,
    BDNOMTPCC varchar(40),
    BDSALDO_ANTERIOR numeric(15,2),
    BDSALDO_ANT_DEB numeric(15,2),
    BDSALDO_ANT_CRE numeric(15,2),
    BDSALDO_DEB numeric(15,2),
    BDSALDO_CRE numeric(15,2),
    BDSALDO_ATUAL numeric(15,2),
    BDGRPCTA smallint,
    BDTPCCLON varchar(20),
    BDMOVIMENTO numeric(15,2),
    BDFORMULA varchar(200),
    BDRELCTA integer,
    BDCLANOM varchar(340),
    BDCODTER integer,
    BDAPECTA varchar(20),
    BDSALDO_ANTERIOR_DRE numeric(15,2),
    BDSALDO_ANT_DEB_DRE numeric(15,2),
    BDSALDO_ANT_CRE_DRE numeric(15,2),
    BDRAIZCNPJPARTICIPANTE varchar(10),
    BDRAIZCLASSIFICACAOCTA varchar(40),
    BDCODUNIDIMOB integer,
    BDCODEMPREENDIMENTO integer,
    BDAPEEMP DM_BDAPEMP,
    BDVALORCOMPFILIAIS numeric(15,2),
    BDSALDO_SEM_CONCILIACAO numeric(15,2),
    BDSALDO_ATUAL_REAL numeric(15,2),
    BDFILTROCC varchar(200),
    BDCODNE integer,
    BDCPFCNPJTER varchar(18),
    BDCTACOMP varchar(5),
    BDDATAULTLANC date,
    BDCODTARBANCARIA integer,
    BDVALORUNIT numeric(15,2),
    BDVALORPERCENT numeric(15,2))
as
declare variable WCTALON varchar(40);
declare variable WSALDO_ANT_DEB numeric(15,2);
declare variable WSALDO_DEB numeric(15,2);
declare variable WSALDO_CRE numeric(15,2);
declare variable WSALDO_ANT_CRE numeric(15,2);
declare variable WSALDO_ATUAL numeric(15,2);
declare variable WSALDO_ANTERIOR numeric(15,2);
declare variable WCONTA integer;
declare variable WCONTA_ANT_AUX integer;
declare variable WNOMCTA varchar(100);
declare variable WTIPCTA smallint;
declare variable WCLANOM varchar(140);
declare variable WCTALONANT varchar(40);
declare variable WCTALON_ANT_AUX varchar(40);
declare variable WSQL varchar(10480);
declare variable WGRPCTA smallint;
declare variable WFORMULA varchar(200);
declare variable WDATAHORA varchar(30);
declare variable WPARTICIPANTE integer;
declare variable WPOS integer;
declare variable WCODPARTICIPANTE integer;
declare variable WSALDO_ANTERIOR_DRE numeric(15,2);
declare variable WSALDO_ANT_DEB_DRE numeric(15,2);
declare variable WSALDO_ANT_CRE_DRE numeric(15,2);
declare variable WCODTPCC integer;
declare variable WCODTPCCANT integer;
declare variable WNOMTPCC varchar(40);
declare variable WTPCCLON varchar(20);
declare variable WCODEMPREENDIMENTO integer;
declare variable WCODUNIDIMOB integer;
declare variable WDESCEMPREENDIMENTO varchar(500);
declare variable WDESCUNIDIMOB varchar(500);
declare variable WCADINCORP integer;
declare variable WRAIZCTASEMEMPREENDIMENTO varchar(40);
declare variable WRAIZCTASEMEMPREENDIMENTOANT varchar(40);
declare variable WRAIZ_CTA_SEM_EMPR_AUX_ANT varchar(40);
declare variable WPARTCCFEITOS DM_MAXVARCHAR;
declare variable WPARTICIPANTEANT integer;
declare variable WSIT_PARTICIPANTE integer;
declare variable WFILTROCC varchar(200);
declare variable WFILTROCCANT varchar(200);
declare variable WANO integer;
declare variable WCCANT integer;
declare variable WEMPREENDCCFEITOS DM_MAXVARCHAR;
declare variable WCCS2 varchar(10000);
declare variable WCCS varchar(10000);
BEGIN
-- select * from VSUC_SP_RETORNA_BALANCETE('13,14', '01/01/2015', '12/31/2015', 0, 19, 35, '', 201204, 0, 0,1, 1, 0,'1,2,3,4') order by bdcodtpcc, bdctalon
  DELETE FROM vsuc_empresas_tbalancete_3 WHERE bdcodemp <> 0;
  -- retorna as empresas selecionadas
  wsql = 'select case when (temp.bdcodmatriz is null) then temp.bdcodemp ';
  wpos = POSITION(',', :prcodemp);
  IF (wpos <> 0) THEN
     wsql = wsql||'            when (temp.bdcodmatriz is not null) then temp.bdcodmatriz ';
  ELSE
     BEGIN
       wsql = wsql||'          when ((temp.bdcodmatriz is not null) and (temp.bdcodemp not in ('||prcodemp||'))) then temp.bdcodmatriz ';
       wsql = wsql||'          when (temp.bdcodemp in ('||prcodemp||')) then temp.bdcodemp ';
     END
  wsql = wsql||'       end bdcodemp, ';
  wsql = wsql||'       temp.bdcodemp bdcodempfilial, ';
  wsql = wsql||'       tref.bdnomemp, tref.BDAPEEMP, temp.bdcnpjemp, tref.bdcodplapadrao, temp.bdcodmatriz ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';
  -- executa o sql das empresas

  wdatahora = localtimestamp;
  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdcodempfilial, :bdnomemp, :BDAPEEMP, :bdcnpjemp, :bdcodplapadrao, :bdcodmatriz DO
      BEGIN
        IF (TRIM(BDAPEEMP) = '') THEN
          BDAPEEMP = bdnomemp;

        bdcodter = 0;
        wcadincorp = 0;
        -- delete from vsuc_empresas_tbalancete where bdcodemp <> 0;
        -- verifica se existe centro de custo selecionado
        IF (prcodtpcc = '') THEN
           BEGIN
             bdcodtpcc = 0;
             bdnomtpcc = '';
             bdtpcclon = '';


             --#alt:11436 - Adiconado controle para o parametro de imprimir o plano de contas completo PRTODOPLANOCONTAS. Ana - 15/12/2016
             -- retorna todas as contas do plano de contas sem o centro de custo
             FOR SELECT tsalcta.conta, tsalcta.classificacao, tsalcta.nomeconta, tsalcta.tipconta, tsalcta.GRUPOCONTA,
                        tsalcta.saldo_ant_deb, tsalcta.saldo_ant_cre, tsalcta.saldo_deb,
                        tsalcta.saldo_cre, tsalcta.saldo_atual,
                        tsalcta.saldo_anterior, tsalcta.formula, tsalcta.relconta, tsalcta.clanom, tsalcta.participante, tsalcta.apecta,
                        tsalcta.saldo_ant_deb_dre, tsalcta.saldo_ant_cre_dre, tsalcta.saldo_anterior_dre, tsalcta.SALDO_SEM_CONCILIACAO, tsalcta.SALDO_ATUAL_REAL, tsalcta.DATAULTLANCAMENTO
                 FROM vsuc_sp_retorna_saldo_contas_x(:bdcodempfilial, :prctaini, :prctafin, :prdatini, :prdatfin, :prindice, :prignora_zeramento, 0, :bdcodplapadrao,:prlansemcc,
                                                     :prnaomostracontacomp,:prconsolidada,:prniveisconta,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado,:prdre, :prtodoplanocontas,
                                                     :prsomentemovimento, :prplanogrpeco, :prempresagrpeco, :prgrpeco, :prIgnZerPerAnt, :prtipolan, :PRELIMINACOESK300K315) tsalcta
                 INTO :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta, :bdgrpcta,
                      :bdsaldo_ant_deb, :bdsaldo_ant_cre, :bdsaldo_deb, :bdsaldo_cre, :bdsaldo_atual,
                      :bdsaldo_anterior, :bdformula, :bdrelcta, :bdclanom, :wparticipante, :bdapecta,
                      :bdsaldo_ant_deb_dre, :bdsaldo_ant_cre_dre, :bdsaldo_anterior_dre, :BDSALDO_SEM_CONCILIACAO, :BDSALDO_ATUAL_REAL, :bddataultlanc DO
                BEGIN
                  WSIT_PARTICIPANTE = -1; --Conta n??o participante
                   
                  /*#136662 - Djonathan*/
                  SELECT
                  CASE
                    WHEN TPLA.BDCTACOMP IS NULL THEN 'FALSE'
                    ELSE TPLA.BDCTACOMP
                  END AS BDCTACOMP
                  FROM PLANOS_TPLA TPLA
                    WHERE TPLA.BDCODPLAPADRAO = :BDCODPLAPADRAO
                    AND TPLA.BDCODTPLA = :BDCODCTA
                    INTO BDCTACOMP;

                  /*#195630 - Exportar DESIF. Marcela*/
                  :BDCODTARBANCARIA = null;
                  :BDVALORUNIT = null;
                  :BDVALORPERCENT = null;
                  select first 1 tar.BDCODDESIF, des.bdvalorunit, des.bdvalorpercent
                  from VSUC_EMPRESAS_TLAN LAN
                  inner join VSUC_EMPRESAS_TLDESIF DES on (DES.BDCHAVE = LAN.BDCHAVE and
                        DES.BDCODEMP = LAN.BDCODEMP)
                  inner join EMPRESAS_TTARBANC_DESIF TAR on DES.BDCODTARBAN = TAR.BDCODDESIF
                  where BDDATA between :PRDATINI and :PRDATFIN and
                        (LAN.BDDEBITO = :bdcodcta or LAN.BDCREDITO = :bdcodcta)
                  INTO :BDCODTARBANCARIA, :BDVALORUNIT, :BDVALORPERCENT;
                   
                  -- Detalhado por participante
                  IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdtipcta = 1)) THEN
                    BEGIN
                      WSIT_PARTICIPANTE = 0; --Conta participante sem participantes
                      --delete from vsuc_empresas_tbalancete_2 tbalan where tbalan.bdcodemp = :bdcodempfilial and tbalan.bddatahora = :wdatahora and tbalan.bdcodtpla = :bdcodcta;
                      --delete from vsuc_empresas_tbalancete_3 tbalan where tbalan.bdcodemp = :bdcodempfilial and tbalan.bdcodtpla = :bdcodcta;

                      wano = CAST(EXTRACT(YEAR FROM prdatini) AS INTEGER);

                      SELECT first 1 ne.bdcodnota FROM VSUC_EMPRESAS_TNOT_EXPLICATIVAS NE
                      WHERE ne.bdcodplapadrao = :bdcodplapadrao
                      AND ne.bdcodtpla = :bdcodcta
                      AND ne.bdreferencia = :wano
                      AND ne.bdcodemp = :bdcodemp
                      INTO :bdcodne;

                      if (:bdcodne is null) then --#198215 - Djonathan
                        begin
                          SELECT first 1 ne.bdcodnota FROM VSUC_EMPRESAS_TNOT_EXPLICATIVAS NE
                          WHERE ne.bdcodplapadrao = :bdcodplapadrao
                          AND ne.bdcodtpla = :bdcodcta
                          AND ne.bdreferencia = :wano
                          AND ne.bdcodemp is null
                          INTO :bdcodne;
                        end

                      FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdsaldo_deb, tsalctapar.bdsaldo_ant_deb,
                                 tsalctapar.bdsaldo_cre, tsalctapar.bdsaldo_ant_cre, tsalctapar.bdsaldo_atual, tsalctapar.bdsaldo_anterior, tsalctapar.bdmovimento,
                                 tsalctapar.bdcodparticipante, tsalctapar.bdraizcnpjparticipante, tsalctapar.bdraizclassificacaocta, tsalctapar.BDVALOR_NAO_CONCILIADO,
                                 tsalctapar.bdcgcter, tsalctapar.bddataultlancamento
                           --from vsuc_sp_retorna_saldos_cta_part(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,
                           --from vsuc_sp_retorna_saldos_ctaparty(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,
                           --                                     :prignora_zeramento,0,0,:prcodemp,:prcontabilizacao) tsalctapar
                           --alt:9167 - Adicionado par??metro para agrupar participantes por CNPJ. Pedro
                           FROM vsuc_sp_retorna_saldos_ctaparty(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,:prignora_zeramento,
                                                                0,0,:prcodemp,:prcontabilizacao,:pragruparparticipanteporcnpj, '', 0,
                                                                :PRAGRUPARPARTICIPANTEPORCPF, 0, :prsomentemovimento, :prrefemp, :PRTODOSPART,
                                                                :prtipolan, :prempresagrpeco, :prgrpeco, :PRELIMINACOESK300K315) tsalctapar
                           INTO :bdnomcta, :bdctalon, :bdsaldo_deb, :bdsaldo_ant_deb, :bdsaldo_cre, :bdsaldo_ant_cre, :bdsaldo_atual, :bdsaldo_anterior, :bdmovimento,
                                :wcodparticipante, :bdraizcnpjparticipante, :bdraizclassificacaocta, :BDSALDO_SEM_CONCILIACAO, :bdcpfcnpjter, :bddataultlanc DO
                        BEGIN
                          bdcodter = :wcodparticipante;
                          bdclanom = SUBSTRING(bdctalon FROM 1 FOR strlen(bdctalon)-10)||' '||bdnomcta;
                          if (PRSOMENTEMOVIMENTO <> 0) then
                            bdsaldo_atual_real = bdmovimento;
                          else
                            bdsaldo_atual_real = bdsaldo_atual;

                          --#alt:125296. Tive que criar um campo expec??fico para tratar o valor do relat??rio, com a op????o de dados a imprimir(que escolhe saldo atual ou movimento).
                          --Com empresas que possuem muitas filiais, estava estourando o filtro de contas com movimento. Ana - 07/01/2020
                          IF (PRDADOSIMPRIMIR = 2) THEN
                            BEGIN
                              IF (BDGRPCTA < 2) THEN
                                BDVALORCOMPFILIAIS = bdsaldo_atual;
                              ELSE
                                BDVALORCOMPFILIAIS = bdmovimento;
                            END
                          ELSE
                            IF (PRDADOSIMPRIMIR = 0) THEN
                              BDVALORCOMPFILIAIS = bdmovimento;
                            ELSE
                              BDVALORCOMPFILIAIS = bdsaldo_atual;
                            WSIT_PARTICIPANTE = 1; --Conta participante com participantes
                            SUSPEND;
                        END

                    END

                  IF (WSIT_PARTICIPANTE = -1 OR (PRTODASASCONTAS = 1 AND WSIT_PARTICIPANTE = 0)) THEN
                    BEGIN
                      bdcodunidimob = NULL;
                      bdcodempreendimento = NULL;
                      bdcodne = null;

                      bdcodter = 0;
                      bdmovimento = bdsaldo_atual - bdsaldo_anterior;
                      --#Alt:19049
                      bdraizcnpjparticipante = '';
                      --#alt:20415. Ana - 22/09/2017
                      bdraizclassificacaocta = '';

                      --Detalhado por incorporadora
                      IF ((prdetalharempreendimento = 1) OR (prdetalharunidimob = 1)) THEN
                        BEGIN
                          wcadincorp = 0;
                          wnomcta = bdnomcta;
                          IF (wctalonant IS NULL) THEN
                            wctalonant = bdctalon;

                          --Carlos Machado - #alt:123617 - 19/08/2019
                          IF ((BDTIPCTA = 0) AND
                             ((COALESCE(bdsaldo_ant_cre, 0) <> 0)  OR (COALESCE(bdsaldo_ant_deb, 0) <> 0) OR
                              (COALESCE(bdsaldo_cre, 0) <> 0)      OR (COALESCE(bdsaldo_deb, 0) <> 0) OR
                              (COALESCE(bdsaldo_anterior, 0) <> 0) OR (COALESCE(bdsaldo_atual, 0) <> 0) OR
                              (PRSOMENTEMOVIMENTO = 1 AND COALESCE(BDSALDO_ATUAL_REAL, 0) <> 0) OR
                              --As consolidadas tamb??m podem ter anal??ticas com f??rmulas #88604 - Carlos Machado -30/08/2018
                              (PRTODASASCONTAS = 1) OR (BDTIPCTA = 0) OR (BDTIPCTA = 2) OR (bdformula <> '') OR (prtodoplanocontas = 1))) THEN
                            BEGIN
                              --#alt:125296. Tive que criar um campo expec??fico para tratar o valor do relat??rio, com a op????o de dados a imprimir(que escolhe saldo atual ou movimento).
                              --Com empresas que possuem muitas filiais, estava estourando o filtro de contas com movimento. Ana - 07/01/2020
                              IF (PRDADOSIMPRIMIR = 2) THEN
                                BEGIN
                                  IF (BDGRPCTA < 2) THEN
                                    BDVALORCOMPFILIAIS = bdsaldo_atual;
                                  ELSE
                                    BDVALORCOMPFILIAIS = bdmovimento;
                                END
                              ELSE
                                IF (PRDADOSIMPRIMIR = 0) THEN
                                  BDVALORCOMPFILIAIS = bdmovimento;
                                ELSE
                                  BDVALORCOMPFILIAIS = bdsaldo_atual;

                              SUSPEND;
                              wcadincorp = 1;
                            END

                          FOR SELECT tsalctaincorp.bdclassificacao, tsalctaincorp.bdsaldo_deb, tsalctaincorp.bdsaldo_ant_deb, tsalctaincorp.bdsaldo_cre, tsalctaincorp.bdsaldo_ant_cre,
                                     tsalctaincorp.bdsaldo_atual, tsalctaincorp.bdsaldo_anterior, tsalctaincorp.bdmovimento, tsalctaincorp.bdcodempreendimento, tsalctaincorp.bdcodunidimob,
                                     tsalctaincorp.bddescempreendimento, tsalctaincorp.bddescunidimob, tsalctaincorp.bdraizclassificacaocta, tsalctaincorp.BDRAIZCTASEMEMPREENDIMENTO,
                                     tsalctaincorp.bddataultlancamento, tsalctaincorp.bdcodtpcc
                              FROM VSUC_SP_RETORNA_SALDOS_INCORP_2(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,:prignora_zeramento,
                                                                    0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :wctalonant, :bdtipcta, :wraizctasemempreendimentoant,
                                                                    :prdetalharempreendimento, :prdetalharunidimob, :prmostrarprop, 0, 0, 0, 0, :prempreendimento, :PRDETALHARCCEMPREEND, :prtipolan) tsalctaincorp
                               INTO :bdctalon, :bdsaldo_deb, :bdsaldo_ant_deb, :bdsaldo_cre, :bdsaldo_ant_cre, :bdsaldo_atual, :bdsaldo_anterior, :bdmovimento,
                                    :wcodempreendimento, :wcodunidimob,:wdescempreendimento, :wdescunidimob, :bdraizclassificacaocta, :WRAIZCTASEMEMPREENDIMENTO,
                                    :bddataultlanc, :bdcodtpcc DO
                            BEGIN
                              if (PRSOMENTEMOVIMENTO <> 0) then
                                bdsaldo_atual_real = bdmovimento;
                              else
                                bdsaldo_atual_real = bdsaldo_atual;
--                            IF ((bdtipcta = 0) AND (wdescempreendimento IS NOT NULL)) THEN
--                              bdnomcta = bdnomcta||' ('||wdescempreendimento||')';

--                            IF (wcodunidimob IS NOT NULL) THEN
--                              bdnomcta = bdnomcta||' ('||wdescunidimob||')';

                              IF ((bdtipcta = 0) AND (wdescempreendimento IS NOT NULL)) THEN
                                bdnomcta = SUBSTRING(COALESCE(bdnomcta, '') || ' (' || COALESCE(wdescempreendimento, '')
                                                     FROM 1 FOR 299) || ')';

                              IF (wcodunidimob IS NOT NULL) THEN
                                bdnomcta = SUBSTRING(COALESCE(bdnomcta, '') || ' (' || COALESCE(wdescunidimob, '')
                                                     FROM 1 FOR 299) || ')';
                                --#alt:123617 - Carlos Machado - 30/07/2019
                              SELECT BDRPOS FROM RPOS('.', :BDCTALON) INTO :WPOS;
                              IF (BDTIPCTA = 1) THEN
                                bdclanom = SUBSTRING(BDCTALON FROM 1 FOR WPOS - 1)||' '||bdnomcta;
                              ELSE
                                bdclanom = BDCTALON;

                              IF (wraizctasemempreendimento IS NOT NULL) THEN
                                wraizctasemempreendimentoant = wraizctasemempreendimento;

                              bdcodunidimob = wcodunidimob;
                              bdcodempreendimento = wcodempreendimento;

                              --#alt:125296. Tive que criar um campo expec??fico para tratar o valor do relat??rio, com a op????o de dados a imprimir(que escolhe saldo atual ou movimento).
                              --Com empresas que possuem muitas filiais, estava estourando o filtro de contas com movimento. Ana - 07/01/2020
                              IF (PRDADOSIMPRIMIR = 2) THEN
                                BEGIN
                                  IF (BDGRPCTA < 2) THEN
                                    BDVALORCOMPFILIAIS = bdsaldo_atual;
                                  ELSE
                                    BDVALORCOMPFILIAIS = bdmovimento;
                                END
                              ELSE
                                IF (PRDADOSIMPRIMIR = 0) THEN
                                  BDVALORCOMPFILIAIS = bdmovimento;
                                ELSE
                                  BDVALORCOMPFILIAIS = bdsaldo_atual;

                               SUSPEND;

                               wcadincorp = 1;
                               bdnomcta = wnomcta;
                            END
                        END

                      bdcodter = 0;
                      bdmovimento = bdsaldo_atual - bdsaldo_anterior;
                      --#Alt:19049
                      bdraizcnpjparticipante = '';
                      --#alt:20415. Ana - 22/09/2017
                      bdraizclassificacaocta = '';

                      wano = CAST(EXTRACT(YEAR FROM prdatini) AS INTEGER);

                      SELECT first 1 coalesce(ne.bdcodnota, null) FROM VSUC_EMPRESAS_TNOT_EXPLICATIVAS NE
                      WHERE ne.bdcodplapadrao = :bdcodplapadrao
                      AND ne.bdcodtpla = :bdcodcta
                      AND ne.bdreferencia = :wano
                      AND ne.bdcodemp = :bdcodemp
                      INTO :bdcodne;

                      if (:bdcodne is null) then --#198215 - Djonathan
                        begin
                          SELECT first 1 ne.bdcodnota FROM VSUC_EMPRESAS_TNOT_EXPLICATIVAS NE
                          WHERE ne.bdcodplapadrao = :bdcodplapadrao
                          AND ne.bdcodtpla = :bdcodcta
                          AND ne.bdreferencia = :wano
                          AND ne.bdcodemp is null
                          INTO :bdcodne;
                        end

                      IF ((wcadincorp = 0) AND
                         ((COALESCE(bdsaldo_ant_cre, 0) <> 0)  OR (COALESCE(bdsaldo_ant_deb, 0) <> 0) OR
                          (COALESCE(bdsaldo_cre, 0) <> 0)      OR (COALESCE(bdsaldo_deb, 0) <> 0) OR
                          (COALESCE(bdsaldo_anterior, 0) <> 0) OR (COALESCE(bdsaldo_atual, 0) <> 0) OR
                          (PRSOMENTEMOVIMENTO = 1 AND COALESCE(BDSALDO_ATUAL_REAL, 0) <> 0) OR
                          --As consolidadas tamb??m podem ter anal??ticas com f??rmulas #88604 - Carlos Machado -30/08/2018
                          (PRTODASASCONTAS = 1) OR (BDTIPCTA = 0) OR (BDTIPCTA = 2) OR (bdformula <> '') OR (prtodoplanocontas = 1))) THEN
                        BEGIN
                          --#alt:125296. Tive que criar um campo expec??fico para tratar o valor do relat??rio, com a op????o de dados a imprimir(que escolhe saldo atual ou movimento).
                          --Com empresas que possuem muitas filiais, estava estourando o filtro de contas com movimento. Ana - 07/01/2020
                          IF (PRDADOSIMPRIMIR = 2) THEN
                            BEGIN
                              IF (BDGRPCTA < 2) THEN
                                BDVALORCOMPFILIAIS = bdsaldo_atual;
                              ELSE
                                BDVALORCOMPFILIAIS = bdmovimento;
                            END
                          ELSE
                            IF (PRDADOSIMPRIMIR = 0) THEN
                              BDVALORCOMPFILIAIS = bdmovimento;
                            ELSE
                              BDVALORCOMPFILIAIS = bdsaldo_atual;

                          SUSPEND;
                        END

                    END

                  IF (bdtipcta = 0) THEN
                    wctalonant = bdctalon;
                END
           END
         ELSE
           BEGIN
             -- retorna a conta longa da conta inicial
             SELECT tpla.bdctalon FROM planos_tpla tpla
             WHERE tpla.bdcodplapadrao = :bdcodplapadrao
             AND tpla.bdcodtpla = :prctaini
             INTO :wctalonant;
             -- inicializa as variaveis
             bdsaldo_ant_cre = 0;
             bdsaldo_ant_deb = 0;
             bdsaldo_cre = 0;
             bdsaldo_deb = 0;
             bdsaldo_anterior = 0;
             bdsaldo_atual = 0;
             WPARTICIPANTEANT  = 0;
             WPARTCCFEITOS     = '<'; --Machado - 04/01/2019 - Alterado para detalhar CC com participante - #91350
             WEMPREENDCCFEITOS = '<';
             wCONTA_ANT_AUX   = prCTAINI;   --#Alt:123277.
             wCTALON_ANT_AUX  = wCTALONANT; --#Alt:123277.
             --#alt:17388 - Removi o campo bdformula do retorno, pois estava duplicado e atribuia direto pro return deixando o retorno com valor incorreto. Ana - 23/01/2018
             FOR SELECT bdconta, bdclassificacao, bdnomeconta, bdtipconta, bdgrupoconta, bdsaldo_ant_deb, bdsaldo_ant_cre,
                        bdsaldo_deb, bdsaldo_cre, bdsaldo_atual, bdsaldo_anterior, bdformula, bdrelconta, bdclanom,
                        /*bdformula,*/ bdapecta, bdsaldo_ant_deb_dre, bdsaldo_ant_cre_dre, bdsaldo_anterior_dre, bdcodtpcc,
                        bdnomtpcc, bdtpcclon, bdparticipante, bdsaldo_atual_real, bdfiltrocc, bddataultlanc
                 FROM vsuc_sp_retorna_saldo_contas_xz(:bdcodempfilial, :prctaini, :prctafin, :prdatini, :prdatfin, :prindice, :prignora_zeramento, :prcodtpcc,
                                                      :bdcodplapadrao, :prlansemcc, :prordem,:prnaomostracontacomp, :prconsolidada, :prniveisconta, :prcontabilizacao, 
                                                      :prmatrizfilialconsolidado, :prdre, :prnivelcc, :prsomentemovimento, :prdetalharccempreend, :PREMPREENDIMENTO,
                                                      :prtipolan, :PRELIMINACOESK300K315) tsalcta
                 INTO :wconta, :wctalon, :wnomcta, :wtipcta, :wgrpcta, :wsaldo_ant_deb, :wsaldo_ant_cre, :wsaldo_deb,
                      :wsaldo_cre, :wsaldo_atual, :wsaldo_anterior, :wformula, :bdrelcta, :wclanom, /*:bdformula,*/ :bdapecta,
                      :wsaldo_ant_deb_dre, :wsaldo_ant_cre_dre, :wsaldo_anterior_dre, :wcodtpcc, :wnomtpcc, :wtpcclon,
                      :wparticipante, :bdsaldo_atual_real, :wfiltrocc, :bddataultlanc DO
               BEGIN
                      
                 /*#136662 - Djonathan*/
                 SELECT
                 CASE
                   WHEN TPLA.BDCTACOMP IS NULL THEN 'FALSE'
                   ELSE TPLA.BDCTACOMP
                 END AS BDCTACOMP
                 FROM PLANOS_TPLA TPLA
                     WHERE TPLA.BDCODPLAPADRAO = :BDCODPLAPADRAO
                     AND TPLA.BDCODTPLA = :BDCODCTA
                     INTO BDCTACOMP;
                         
                 bdcodter = 0;
                 --alt:9381 - Quando for nullo troca para zero, sen??o n??o consegue totalizar
                 --corretamente por centro de custo onde for sem centro de custos. Pedro
                 IF (wcodtpcc IS NULL) THEN
                   wcodtpcc = 0;
                 IF (WPARTICIPANTE IS NULL) THEN
                   WPARTICIPANTE = 0;
                 --#Alt:19049
                 bdraizcnpjparticipante = '';
                 --#alt:20416. Ana - 22/09/2017
                 bdraizclassificacaocta = '';
                 wcadincorp = 0;

                 --#Alt:17388 - Adicionada condição para imprimir as contas com formulas - Fernando Jr. 19/01/2018
                 --#alt:11436 - Adicionada condição do novo parametro para imprimir todas as contas quando estiver setado. Ana - 15/12/2016
                 IF ((COALESCE(bdsaldo_ant_cre, 0) <> 0)  OR (COALESCE(bdsaldo_ant_deb, 0) <> 0) OR
                     (COALESCE(bdsaldo_cre, 0) <> 0)      OR (COALESCE(bdsaldo_deb, 0) <> 0) OR
                     (COALESCE(bdsaldo_anterior, 0) <> 0) OR (COALESCE(bdsaldo_atual, 0) <> 0) OR
                     (PRSOMENTEMOVIMENTO = 1 AND COALESCE(BDSALDO_ATUAL_REAL, 0) <> 0) OR
                     (BDTIPCTA = 0) OR (bdformula <> '') OR  (prtodoplanocontas = 1)) THEN
                   BEGIN
                   --#alt:121984. Ana - 04/07/2019
                   /*IF ((((wctalonant <> wctalon) OR (COALESCE(wcodtpccant, 0) <> COALESCE(wcodtpcc, 0))) and not (PRDETALHARCTAPARTICIPANTE = 1 AND WPARTICIPANTEANT = 1 AND BDTIPCTA = 1)) and
                          ((prdetalharempreendimento = 0) or (prdetalharunidimob = 0))) THEN
                          SUSPEND;*/

                     bdcodcta  = wconta;
                     bdctalon  = wctalon;
                     bdnomcta  = wnomcta;
                     bdtipcta  = wtipcta;
                     bdclanom  = wclanom;
                     bdgrpcta  = wgrpcta;
                     bdformula = wformula;
                     bdcodtpcc = wcodtpcc;
                     bdnomtpcc = wnomtpcc;
                     bdtpcclon = wtpcclon;
                     bdfiltrocc = wfiltrocc;
   
                     bdsaldo_ant_cre = wsaldo_ant_cre;
                     bdsaldo_ant_deb = wsaldo_ant_deb;
                     bdsaldo_cre = wsaldo_cre;
                     bdsaldo_deb = wsaldo_deb;
                     bdsaldo_anterior = wsaldo_anterior;
                     bdsaldo_atual = wsaldo_atual;
                     
                     --alt:9179 - N??o estava imprimindo o BDMOVIMENTO para os centros de custos. Pedro
                     bdmovimento = bdsaldo_atual - bdsaldo_anterior;
                     
                     bdsaldo_ant_cre_dre = wsaldo_ant_cre_dre;
                     bdsaldo_ant_deb_dre = wsaldo_ant_deb_dre;
                     bdsaldo_anterior_dre = wsaldo_anterior_dre;
                   END
                 ELSE
                   BEGIN
                     bdcodcta  = wconta;
                     bdctalon  = wctalon;
                     bdnomcta  = wnomcta;
                     bdtipcta  = wtipcta;
                     bdclanom  = wclanom;
                     bdgrpcta  = wgrpcta;
                     bdformula = wformula;
                     bdcodtpcc = wcodtpcc;
                     bdnomtpcc = wnomtpcc;
                     bdtpcclon = wtpcclon;
                     bdfiltrocc = wfiltrocc;
                     
                     bdsaldo_ant_cre = bdsaldo_ant_cre + wsaldo_ant_cre;
                     bdsaldo_ant_deb = bdsaldo_ant_deb + wsaldo_ant_deb;
                     bdsaldo_cre = bdsaldo_cre + wsaldo_cre;
                     bdsaldo_deb = bdsaldo_deb + wsaldo_deb;
                     bdsaldo_anterior = bdsaldo_anterior + wsaldo_anterior;
                     bdsaldo_atual = bdsaldo_atual + wsaldo_atual;

                     --alt:9179 - N??o estava imprimindo o BDMOVIMENTO para os centros de custos. Pedro
                     bdmovimento = bdsaldo_atual - bdsaldo_anterior;
                     
                     bdsaldo_ant_cre_dre = bdsaldo_ant_cre_dre + wsaldo_ant_cre_dre;
                     bdsaldo_ant_deb_dre = bdsaldo_ant_deb_dre + wsaldo_ant_deb_dre;
                     bdsaldo_anterior_dre = bdsaldo_anterior_dre + wsaldo_anterior_dre;
                   END
                 --wctalonant = wctalon;

                 BDCODTPCC = wcodtpcc;
                 wfiltroccant = wfiltrocc;

                 IF (PRDETALHARCTAPARTICIPANTE = 1  AND BDTIPCTA = 1 AND WPARTICIPANTE = 1) THEN
                   BEGIN
                     IF (POSITION('<'||BDCODCTA||'>', WPARTCCFEITOS) <= 0) THEN
                       BEGIN
                         WPARTCCFEITOS = WPARTCCFEITOS||bdcodcta||'><';
                         FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdsaldo_deb, tsalctapar.bdsaldo_ant_deb,
                                    tsalctapar.bdsaldo_cre, tsalctapar.bdsaldo_ant_cre, tsalctapar.bdsaldo_atual, tsalctapar.bdsaldo_anterior, tsalctapar.bdmovimento,
                                    tsalctapar.bdcodparticipante, tsalctapar.bdraizcnpjparticipante, tsalctapar.bdraizclassificacaocta, tsalctapar.BDCENTROCUSTO, tsalctapar.BDNOMTPCC, tsalctapar.BDTPCCLON,
                                    tsalctapar.bdcgcter, tsalctapar.bddataultlancamento
                               FROM vsuc_sp_retorna_saldos_ctaparty(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,:prignora_zeramento,
                                                                    0,0,:prcodemp,:prcontabilizacao,:pragruparparticipanteporcnpj, :PRCODTPCC, :PRLANSEMCC,
                                                                    :PRAGRUPARPARTICIPANTEPORCPF, :prnivelcc, :prsomentemovimento, :prrefemp, '', :prtipolan,
                                                                    :prempresagrpeco, :prgrpeco, :PRELIMINACOESK300K315) tsalctapar
                               INTO :bdnomcta, :bdctalon, :bdsaldo_deb, :bdsaldo_ant_deb, :bdsaldo_cre, :bdsaldo_ant_cre, :bdsaldo_atual, :bdsaldo_anterior, :bdmovimento,
                                    :wcodparticipante, :bdraizcnpjparticipante, :bdraizclassificacaocta, :BDCODTPCC, :BDNOMTPCC, :BDTPCCLON, :bdcpfcnpjter, :bddataultlanc DO
                           BEGIN
                             bdcodter = :wcodparticipante;
                             bdclanom = SUBSTRING(bdctalon FROM 1 FOR strlen(bdctalon)-10)||' '||bdnomcta;
                             if (PRSOMENTEMOVIMENTO <> 0) then
                               bdsaldo_atual_real = bdmovimento;
                             else
                               bdsaldo_atual_real = bdsaldo_atual;
                             --#alt:125296. Tive que criar um campo expec??fico para tratar o valor do relat??rio, com a op????o de dados a imprimir(que escolhe saldo atual ou movimento).
                             --Com empresas que possuem muitas filiais, estava estourando o filtro de contas com movimento. Ana - 07/01/2020
                             IF (PRDADOSIMPRIMIR = 2) THEN
                               BEGIN
                                 IF (BDGRPCTA < 2) THEN
                                   BDVALORCOMPFILIAIS = bdsaldo_atual;
                                 ELSE
                                   BDVALORCOMPFILIAIS = bdmovimento;
                                 END
                               ELSE
                                 IF (PRDADOSIMPRIMIR = 0) THEN
                                   BDVALORCOMPFILIAIS = bdmovimento;
                                 ELSE
                                   BDVALORCOMPFILIAIS = bdsaldo_atual;
    
                               SUSPEND;
                           END
                       END
                   END
                 ELSE
                   BEGIN
                     bdcodunidimob = NULL;
                     bdcodempreendimento = NULL;

                     --Detalhado por incorporadora
                     IF (((prdetalharempreendimento = 1) OR (prdetalharunidimob = 1)) AND ((PRLANSEMCC = 1) OR (bdcodtpcc > 0) OR ((bdtipcta = 0) AND (prordem = 1)))) THEN
                       BEGIN
                         --#Alt:123277. Quando tiver mais de um CC ele repete a conta cont??bil, por isso precisamos voltar para o que era, caso contr??rio ele se perde. - Carlos Mello (18/07/2019)
                         IF ((BDTIPCTA = 0) AND (wCONTA_ANT_AUX = BDCODCTA) AND (wCTALONANT <> wCTALON_ANT_AUX)) THEN
                           wCTALONANT = wCTALON_ANT_AUX;
                         IF ((wCONTA_ANT_AUX = BDCODCTA) AND (COALESCE(wRAIZCTASEMEMPREENDIMENTOANT,'') <> COALESCE(WRAIZ_CTA_SEM_EMPR_AUX_ANT,''))) THEN
                           WRAIZCTASEMEMPREENDIMENTOANT = WRAIZ_CTA_SEM_EMPR_AUX_ANT;
                  
                         wnomcta = bdnomcta;
                         IF (wctalonant IS NULL) THEN
                           wctalonant = bdctalon;

                         --Carlos Machado - #alt:123617 - 19/08/2019
                         IF ((BDTIPCTA = 0) AND
                             ((COALESCE(bdsaldo_ant_cre, 0) <> 0)  OR (COALESCE(bdsaldo_ant_deb, 0) <> 0) OR
                             (COALESCE(bdsaldo_cre, 0) <> 0)      OR (COALESCE(bdsaldo_deb, 0) <> 0) OR
                             (COALESCE(bdsaldo_anterior, 0) <> 0) OR (COALESCE(bdsaldo_atual, 0) <> 0) OR
                             (PRSOMENTEMOVIMENTO = 1 AND COALESCE(BDSALDO_ATUAL_REAL, 0) <> 0) OR
                             --As consolidadas tamb??m podem ter anal??ticas com f??rmulas #88604 - Carlos Machado -30/08/2018
                             (PRTODASASCONTAS = 1) OR (BDTIPCTA = 0) OR (BDTIPCTA = 2) OR (bdformula <> '') OR (prtodoplanocontas = 1))) THEN
                           BEGIN
                             wcadincorp = 1;

                             --#alt:125296. Tive que criar um campo expec??fico para tratar o valor do relat??rio, com a op????o de dados a imprimir(que escolhe saldo atual ou movimento).
                             --Com empresas que possuem muitas filiais, estava estourando o filtro de contas com movimento. Ana - 07/01/2020
                             IF (PRDADOSIMPRIMIR = 2) THEN
                               BEGIN
                                 IF (BDGRPCTA < 2) THEN
                                   BDVALORCOMPFILIAIS = bdsaldo_atual;
                                 ELSE
                                   BDVALORCOMPFILIAIS = bdmovimento;
                               END
                             ELSE
                             IF (PRDADOSIMPRIMIR = 0) THEN
                               BDVALORCOMPFILIAIS = bdmovimento;
                             ELSE
                               BDVALORCOMPFILIAIS = bdsaldo_atual;

                             SUSPEND;
                           END

                         if (prdetalharccempreend = 1) then
                           begin
                             if ((wCCANT > 0) AND (wCCANT <> BDCODTPCC)) then
                               WEMPREENDCCFEITOS = '<';
    
                             WCCS2 = 'select cast(list(distinct CC.BDCODTPCC) as varchar(10000)) BDCODTPCC';
                             WCCS2 = WCCS2 ||'  from VEF_EMP_TCADEMPREENDIMENTO EMP';
                             WCCS2 = WCCS2 ||'  left join CENTROS_TPCC CC on (EMP.BDCODCENTRO = CC.BDCODCENTRO and';
                             WCCS2 = WCCS2 ||'                                EMP.BDCODTPCC = CC.BDCODTPCC)';
                             WCCS2 = WCCS2 ||'     where BDCODEMP = '||:bdcodempfilial||' and';
                             WCCS2 = WCCS2 ||'           BDCODEMPREENDIMENTO in ('||:prempreendimento||')';
                        
                             execute statement WCCS2 into :wccs;
                           end

                         IF ((POSITION('<'||BDCODCTA||'>', WEMPREENDCCFEITOS) <= 0) or (prdetalharccempreend = 0))  THEN
                           BEGIN
                             if (prdetalharccempreend = 1) then
                               WEMPREENDCCFEITOS = WEMPREENDCCFEITOS||bdcodcta||'><';

                             FOR SELECT tsalctaincorp.bdclassificacao, tsalctaincorp.bdsaldo_deb, tsalctaincorp.bdsaldo_ant_deb, tsalctaincorp.bdsaldo_cre, tsalctaincorp.bdsaldo_ant_cre,
                                        tsalctaincorp.bdsaldo_atual, tsalctaincorp.bdsaldo_anterior, tsalctaincorp.bdmovimento, tsalctaincorp.bdcodempreendimento, tsalctaincorp.bdcodunidimob,
                                        tsalctaincorp.bddescempreendimento, tsalctaincorp.bddescunidimob, tsalctaincorp.bdraizclassificacaocta, tsalctaincorp.BDRAIZCTASEMEMPREENDIMENTO,
                                        tsalctaincorp.bddataultlancamento, tsalctaincorp.bdcodtpcc
                                   FROM VSUC_SP_RETORNA_SALDOS_INCORP_2(:bdcodempfilial,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,:prignora_zeramento,
                                                                        0,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado, :wctalonant, :bdtipcta, :wraizctasemempreendimentoant,
                                                                        :prdetalharempreendimento, :prdetalharunidimob, :prmostrarprop, :bdcodtpcc, :PRLANSEMCC, 1, :prnivelcc, :prempreendimento,
                                                                        :PRDETALHARCCEMPREEND, :prtipolan) tsalctaincorp
                                   INTO :bdctalon, :bdsaldo_deb, :bdsaldo_ant_deb, :bdsaldo_cre, :bdsaldo_ant_cre, :bdsaldo_atual, :bdsaldo_anterior, :bdmovimento,
                                        :wcodempreendimento, :wcodunidimob,:wdescempreendimento, :wdescunidimob, :bdraizclassificacaocta, :WRAIZCTASEMEMPREENDIMENTO,
                                        :bddataultlanc, :bdcodtpcc DO
                               BEGIN
                                 if (prdetalharccempreend = 1) then
                                   begin
                                     if (BDCODTPCC is null) then
                                       BDCODTPCC = wcodtpcc;
    
                                     if (wCCANT <> BDCODTPCC) then
                                       begin
                                         select CC.BDNOMCTA, CC.BDCTALON
                                         from VEF_EMP_TCADEMPREENDIMENTO EMP
                                         left join CENTROS_TPCC CC on (EMP.BDCODCENTRO = CC.BDCODCENTRO and
                                                                       EMP.BDCODTPCC = CC.BDCODTPCC)
                                         where BDCODEMP = :bdcodempfilial and
                                               BDCODEMPREENDIMENTO = :wcodempreendimento
                                         INTO :bdnomtpcc, :bdtpcclon;
                                       end
                                   end
                                 else
                                   bdcodtpcc = wcodtpcc;

--                            IF ((bdtipcta = 0) AND (wdescempreendimento IS NOT NULL)) THEN
--                              bdnomcta = bdnomcta||' ('||wdescempreendimento||')';

--                            IF (wcodunidimob IS NOT NULL) THEN
--                              bdnomcta = bdnomcta||' ('||wdescunidimob||')';

                              IF ((bdtipcta = 0) AND (wdescempreendimento IS NOT NULL)) THEN
                                bdnomcta = SUBSTRING(COALESCE(bdnomcta, '') || ' (' || COALESCE(wdescempreendimento, '')
                                                     FROM 1 FOR 299) || ')';

                              IF (wcodunidimob IS NOT NULL) THEN
                                bdnomcta = SUBSTRING(COALESCE(bdnomcta, '') || ' (' || COALESCE(wdescunidimob, '')
                                                     FROM 1 FOR 299) || ')';

                                 --#alt:123617 - Carlos Machado - 30/07/2019
                                 SELECT BDRPOS FROM RPOS('.', :BDCTALON) INTO :WPOS;
                                 IF (BDTIPCTA = 1) THEN
                                   bdclanom = SUBSTRING(BDCTALON FROM 1 FOR WPOS - 1)||' '||bdnomcta;
                                 ELSE
                                   bdclanom = BDCTALON;
    
                                 if (PRSOMENTEMOVIMENTO <> 0) then
                                   bdsaldo_atual_real = bdmovimento;
                                 else
                                   bdsaldo_atual_real = bdsaldo_atual;

                                 --#Alt:123277. Quando tiver mais de um CC ele repete a conta cont??bil, por isso precisamos voltar para o que era, caso contr??rio ele se perde. - Carlos Mello (18/07/2019)
                                 WRAIZ_CTA_SEM_EMPR_AUX_ANT = wRAIZCTASEMEMPREENDIMENTOANT;
                        
                                 IF (wraizctasemempreendimento IS NOT NULL) THEN
                                   wraizctasemempreendimentoant = wraizctasemempreendimento;
    
                                 bdcodunidimob = wcodunidimob;
                                 bdcodempreendimento = wcodempreendimento;

                                 --#alt:125296. Tive que criar um campo expec??fico para tratar o valor do relat??rio, com a op????o de dados a imprimir(que escolhe saldo atual ou movimento).
                                 --Com empresas que possuem muitas filiais, estava estourando o filtro de contas com movimento. Ana - 07/01/2020
                                 IF (PRDADOSIMPRIMIR = 2) THEN
                                   BEGIN
                                     IF (BDGRPCTA < 2) THEN
                                       BDVALORCOMPFILIAIS = bdsaldo_atual;
                                     ELSE
                                       BDVALORCOMPFILIAIS = bdmovimento;
                                   END
                                 ELSE
                                   IF (PRDADOSIMPRIMIR = 0) THEN
                                     BDVALORCOMPFILIAIS = bdmovimento;
                                   ELSE
                                     BDVALORCOMPFILIAIS = bdsaldo_atual;

                                   SUSPEND;
                                 wcadincorp = 1;
                                 bdnomcta = wnomcta;
                                 if (prdetalharccempreend = 1) then
                                   wCCANT = BDCODTPCC;
                               END
                           END
                       END
                         bdcodter = 0;
                         bdmovimento = bdsaldo_atual - bdsaldo_anterior;
                         bdraizcnpjparticipante = '';
                         bdraizclassificacaocta = '';
                         
                         IF ((wcadincorp = 0) AND
                             ((COALESCE(bdsaldo_ant_cre, 0) <> 0)  OR (COALESCE(bdsaldo_ant_deb, 0) <> 0) OR
                             (COALESCE(bdsaldo_cre, 0) <> 0)      OR (COALESCE(bdsaldo_deb, 0) <> 0) OR
                             (COALESCE(bdsaldo_anterior, 0) <> 0) OR (COALESCE(bdsaldo_atual, 0) <> 0) OR
                             (PRSOMENTEMOVIMENTO = 1 AND COALESCE(BDSALDO_ATUAL_REAL, 0) <> 0) OR
                             --As consolidadas tamb??m podem ter anal??ticas com f??rmulas #88604 - Carlos Machado -30/08/2018
                             (PRTODASASCONTAS = 1) OR (BDTIPCTA = 0) OR (BDTIPCTA = 2) OR (bdformula <> '') OR (prtodoplanocontas = 1))
                             ) THEN
                           BEGIN
                             --#alt:125296. Tive que criar um campo expec??fico para tratar o valor do relat??rio, com a op????o de dados a imprimir(que escolhe saldo atual ou movimento).
                             --Com empresas que possuem muitas filiais, estava estourando o filtro de contas com movimento. Ana - 07/01/2020
                             IF (PRDADOSIMPRIMIR = 2) THEN
                               BEGIN
                                 IF (BDGRPCTA < 2) THEN
                                   BDVALORCOMPFILIAIS = bdsaldo_atual;
                                 ELSE
                                   BDVALORCOMPFILIAIS = bdmovimento;
                               END
                             ELSE
                             IF (PRDADOSIMPRIMIR = 0) THEN
                               BDVALORCOMPFILIAIS = bdmovimento;
                             ELSE
                               BDVALORCOMPFILIAIS = bdsaldo_atual;
                             wcadincorp = 1;
    
                             SUSPEND;
                           END

                        if (prdetalharccempreend = 1) then
                          wCCANT = BDCODTPCC;
                   END

                     WPARTICIPANTEANT = WPARTICIPANTE;
                     --#Alt:123277. Quando tiver mais de um CC ele repete a conta cont??bil, por isso precisamos voltar para o que era, caso contr??rio ele se perde. - Carlos Mello (18/07/2019)
                     wCONTA_ANT_AUX   = BDCODCTA;
                     wCTALON_ANT_AUX  = wCTALONANT;
                     
                     IF (BDTIPCTA = 0) THEN
                       wCTALONANT = BDCTALON;
                     
                     --#alt:125296. Tive que criar um campo expec??fico para tratar o valor do relat??rio, com a op????o de dados a imprimir(que escolhe saldo atual ou movimento).
                     --Com empresas que possuem muitas filiais, estava estourando o filtro de contas com movimento. Ana - 07/01/2020
                     IF (PRDADOSIMPRIMIR = 2) THEN
                       BEGIN
                         IF (BDGRPCTA < 2) THEN
                           BDVALORCOMPFILIAIS = bdsaldo_atual;
                         ELSE
                           BDVALORCOMPFILIAIS = bdmovimento;
                       END
                     ELSE
                       IF (PRDADOSIMPRIMIR = 0) THEN
                         BDVALORCOMPFILIAIS = bdmovimento;
                       ELSE
                         BDVALORCOMPFILIAIS = bdsaldo_atual;
               END
                 --#Alt:17388 - Adicionada condicao para imprimir as contas com formulas - Fernando Jr. 19/01/2018
                 --#alt:11436 - Adicionada condi????o do novo parametro para imprimir todas as contas quando estiver setado. Ana - 15/12/2016
                 --alt:9386 - Adicionado esse suspend porque se ele soma centros de custos iguais, o ??ltimo n??o ?? impresso. Pedro
                 IF (((COALESCE(bdsaldo_ant_cre, 0) <> 0) OR
                      (COALESCE(bdsaldo_ant_deb, 0) <> 0) OR
                      (COALESCE(bdsaldo_cre, 0) <> 0)     OR
                      (COALESCE(bdsaldo_deb, 0) <> 0)     OR
                     --As consolidadas tamb??m podem ter anal??ticas com f??rmulas #88604 - Carlos Machado -30/08/2018
                      (COALESCE(bdsaldo_anterior, 0) <> 0) OR
                      (COALESCE(bdsaldo_atual, 0) <> 0)    OR
                      (PRSOMENTEMOVIMENTO = 1 AND COALESCE(BDSALDO_ATUAL_REAL, 0) <> 0) OR
                      (BDTIPCTA = 0) OR
                      (BDTIPCTA = 2) OR
                      (bdformula <> '') OR
                      (prtodoplanocontas = 1)) AND
                     NOT (PRDETALHARCTAPARTICIPANTE = 1  AND BDTIPCTA = 1 AND WPARTICIPANTEANT = 1) AND
                     NOT (wcadincorp = 1) AND (prdetalharccempreend = 0)
                     )
                      THEN
                       SUSPEND;
                 --alt:9386 - Fim
    
                 bdsaldo_atual_real = 0; 

             bdsaldo_atual_real = 0; 

           END

--        delete from vsuc_empresas_tbalancete_2 where bdcodemp <> 0 and bddatahora = :wdatahora;
        DELETE FROM vsuc_empresas_tbalancete_3 WHERE bdcodemp <> 0;

      END
END
^

--Carlos Machado - #alt:123617 - 19/08/2019
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDOS_INCORP_2 (
    PRCODEMP INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRDTINICIAL DATE,
    PRDTFINAL DATE,
    PRCONTA INTEGER,
    PRINDICE INTEGER,
    PRIGNORAZERAMENTO INTEGER,
    PRCONCILIADOS INTEGER,
    PREMPRESAS VARCHAR(2048),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRCTALONANT VARCHAR(40),
    PRCTATITULO INTEGER,
    PRRAIZCTASEMEMPREENDIMENTOANT VARCHAR(40),
    PRDETALHAREMPREENDIMENTO INTEGER,
    PRDETALHARUNIDIMOB INTEGER,
    PRMOSTRARPROP INTEGER,
    PRCC INTEGER = 0,
    PRLANCSEMCC INTEGER = 0,
    PRDETALHARCC INTEGER = 0,
    PRNIVELCC INTEGER = 0,
    PREMPREENDIMENTO varchar(32000) = '' /* COLLATE WIN1252 - default */ ,
    PRDETALHARCCEMPREEND integer = 0,
    PRTIPOLAN varchar(3200) = '')
returns (
    BDCLASSIFICACAO varchar(80),
    BDSALDO_DEB numeric(15,2),
    BDSALDO_ANT_DEB numeric(15,2),
    BDSALDO_CRE numeric(15,2),
    BDSALDO_ANT_CRE numeric(15,2),
    BDMOVIMENTO numeric(15,2),
    BDSALDO_ATUAL numeric(15,2),
    BDSALDO_ANTERIOR numeric(15,2),
    BDRAIZCLASSIFICACAOCTA varchar(40),
    BDCODEMPREENDIMENTO integer,
    BDCODUNIDIMOB integer,
    BDDESCEMPREENDIMENTO varchar(500),
    BDDESCUNIDIMOB varchar(500),
    BDRAIZCTASEMEMPREENDIMENTO varchar(40),
    BDDATAULTLANCAMENTO date,
    BDCODTPCC integer)
as
declare variable WGRUPOCTA integer;
declare variable WSQL varchar(10000);
declare variable WSQLSUMSALDO varchar(10000);
declare variable WSQLWHERELAND varchar(10000);
declare variable WSQLWHERELANC varchar(10000);
declare variable WSQLWHERELAN_AUX varchar(1000);
declare variable WSQL_EMP varchar(5000);
declare variable WCODEMP integer;
declare variable WPOS integer;
declare variable WCLASSIFICACAO varchar(40);
declare variable WCODTPLA integer;
declare variable WSALDO_DEB numeric(15,6);
declare variable WSALDO_ANT_DEB numeric(15,6);
declare variable WSALDO_CRE numeric(15,6);
declare variable WSALDO_ANT_CRE numeric(15,6);
declare variable WDEBCRE integer;
declare variable WCODEMPREENDIMENTO integer;
declare variable WCODUNIDIMOB integer;
declare variable WDESCEMPREENDIMENTO varchar(500);
declare variable WDESCUNIDIMOB varchar(500);
declare variable WCOUNTNIVELCTA integer;
declare variable WUSAEMPREENDIMENTO varchar(5);
declare variable WUSAUNIDIMOB varchar(5);
declare variable WTABELAVLR varchar(5);
declare variable WIMPINCORP integer;
declare variable WCCS varchar(10000);
declare variable WZERAMENTOSIGNORAR varchar(250);
declare variable WSQL_DETALHARCCEMPREEND varchar(250);
declare variable WCCS2 varchar(10000);
declare variable WEMPREENDIMENTO varchar(1024);
BEGIN
  wCOUNTNIVELCTA    = 0;
  WIMPINCORP        = 0; --#Alt:123277. Variável para controlar se passou pelos cálculos de incorporadoras

  --#Alt:123277. Alterado SQL para ser feito uma única vez
  SELECT BDCTALON, BDGRUPOCTA, BDCTAEMPREENDIMENTOSIMOB, BDCTAUNIDADEIMOB FROM PLANOS_TPLA
  WHERE BDCODPLAPADRAO = :PRCODPLAPADRAO AND
        BDCODTPLA      = :PRCONTA
  INTO :wCLASSIFICACAO, :wGRUPOCTA, :wUSAEMPREENDIMENTO, :wUSAUNIDIMOB;
    
  IF (((wusaempreendimento IS NULL) OR (wusaempreendimento = '') OR (UPPER(wusaempreendimento) = 'FALSE')) AND
      ((wusaunidimob IS NULL) OR (wusaunidimob = '') OR (UPPER(wusaunidimob) = 'FALSE'))) THEN
      EXIT;

  IF ((prconta = 0) OR (prconta IS NULL)) THEN
    EXIT;

  wzeramentosignorar = '';
  if (prignorazeramento = 2) then
    SELECT LIST(E.bdchavezer, ',') FROM tmp_vsuc_empresas_tencexe E WHERE E.bdcodemp = :PRCODEMP INTO :wzeramentosignorar;

  if (wzeramentosignorar <> '') then
    wsql_emp = 'tlan.bdtipolan <> 10 or tlan.bdchavezer not in ('||wzeramentosignorar||')';
  else
    wsql_emp = 'tlan.bdtipolan <> 10';
  wzeramentosignorar = wsql_emp;

  wsql_emp = ' and (';
   IF (POSITION(',', prempresas) > 0) THEN
     wsql_emp = wsql_emp||'tlan.bdcodemp = '||prcodemp;
   ELSE
     wsql_emp = wsql_emp||'tlan.bdcodemp = '||prcodemp;
   wsql_emp = wsql_emp||') ';

  if ((PRCC > 0) or (prdetalharccempreend = 1))  then
    wtabelavlr = 'TLCC.';
  else
    wtabelavlr = 'TLAN.';

  --#alt:153018 - 04/08/2021 - Machado - - Impressão dos CENTRO de CUSTO
  if (PRCC > 0 and prnivelcc > 0)  then
    select cast(list(tpcc.bdcodtpcc, ',') as varchar(10000)) from vw_empresas_ref_atual EMP
    inner join centros_tpcc tpcc on (tpcc.bdcodcentro = emp.bdcodcentros)
    where EMP.bdcodemp = :prcodemp into :wccs;
  else
  if (prdetalharccempreend = 1) then
    begin

      WCCS2 = 'select cast(list(distinct BDCODEMPREENDIMENTO) as varchar(10000)) BDCODTPCC';
      WCCS2 = WCCS2 ||'  from VEF_EMP_TCADEMPREENDIMENTO EMP';
      WCCS2 = WCCS2 ||'     where BDCODEMP = '||:prcodemp||' and';
      WCCS2 = WCCS2 ||'           BDCODTPCC in ('||:prcc||') and BDCODEMPREENDIMENTO in ('||:prempreendimento||')';

      execute statement WCCS2 into :wempreendimento;

      if (wempreendimento is null) then
        :wempreendimento = :prempreendimento;

      WCCS2 = 'select cast(list(distinct CC.BDCODTPCC) as varchar(10000)) BDCODTPCC';
      WCCS2 = WCCS2 ||'  from VEF_EMP_TCADEMPREENDIMENTO EMP';
      WCCS2 = WCCS2 ||'  left join CENTROS_TPCC CC on (EMP.BDCODCENTRO = CC.BDCODCENTRO and';
      WCCS2 = WCCS2 ||'                                EMP.BDCODTPCC = CC.BDCODTPCC)';
      WCCS2 = WCCS2 ||'     where BDCODEMP = '||:prcodemp||' and';
      WCCS2 = WCCS2 ||'           BDCODEMPREENDIMENTO in ('||:wempreendimento||')';

      execute statement WCCS2 into :wccs;

      if (wccs is null) then
        :wccs = :prcc;

    end
  else
    wccs = prcc;

  wsql_detalharccempreend = '';
  if (prdetalharccempreend = 1) then
    wsql_detalharccempreend = ' and (/*(TLCC.BDCODTPCC in ('||wccs||')) or */(TINCORP.bdcodempreendimento in ('||:wempreendimento||')))';

  --SQL padrão para somar o saldo
  wsqlsumsaldo = '';
  IF (prindice = 0) THEN
    BEGIN
      if (prdetalharccempreend = 1) then
        begin
          wsqlsumsaldo = wsqlsumsaldo||'sum(case when (tlan.bddata < '''||prdtinicial||''') then coalesce(TLCC.bdvalor, TLAN.bdvalor) else 0 end) as bdsalant, ';
          IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
            wsqlsumsaldo = wsqlsumsaldo||'sum(case when (((tlan.bddata >= '''||prdtinicial||''') and ('||wzeramentosignorar||')) or (tlan.bddata < '''||prdtinicial||''')) then coalesce(TLCC.bdvalor, TLAN.bdvalor) else 0 end) as bdsalatu, ';
          ELSE
            wsqlsumsaldo = wsqlsumsaldo||'sum(coalesce(TLCC.bdvalor, COALESCE(TLAN.bdvalor,0))) as bdsalatu, ';
        end
      else
        begin
          wsqlsumsaldo = wsqlsumsaldo||'sum(case when (tlan.bddata < '''||prdtinicial||''') then '||wtabelavlr||'bdvalor else 0 end) as bdsalant, ';
          IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
            wsqlsumsaldo = wsqlsumsaldo||'sum(case when (((tlan.bddata >= '''||prdtinicial||''') and ('||wzeramentosignorar||')) or (tlan.bddata < '''||prdtinicial||''')) then '||wtabelavlr||'bdvalor else 0 end) as bdsalatu, ';
          ELSE
            wsqlsumsaldo = wsqlsumsaldo||'sum(coalesce('||wtabelavlr||'bdvalor, 0)) as bdsalatu, ';
        end

    END
  ELSE
    BEGIN
      if (prdetalharccempreend = 1) then
        begin
          wsqlsumsaldo = wsqlsumsaldo||'sum(case when (tlan.bddata < '''||prdtinicial||''') then coalesce(TLCC.bdvalor, TLAN.bdvalor) / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsqlsumsaldo = wsqlsumsaldo||'                                                                                 (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalant, ';
          IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
            BEGIN
              wsqlsumsaldo = wsqlsumsaldo||'sum(case when (((tlan.bddata >= '''||prdtinicial||''') and ('||wzeramentosignorar||')) or (tlan.bddata < '''||prdtinicial||''')) then ';
              wsqlsumsaldo = wsqlsumsaldo||'coalesce(TLCC.bdvalor, TLAN.bdvalor) / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
              wsqlsumsaldo = wsqlsumsaldo||'                        (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalatu, ';
            END
          ELSE
            BEGIN
              wsqlsumsaldo = wsqlsumsaldo||'sum(coalesce(TLCC.bdvalor, TLAN.bdvalor) / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
              wsqlsumsaldo = wsqlsumsaldo||'                            (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))) as bdsalatu, ';-- com zeramento
            END
        end
      else
        begin
          wsqlsumsaldo = wsqlsumsaldo||'sum(case when (tlan.bddata < '''||prdtinicial||''') then '||wtabelavlr||'bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsqlsumsaldo = wsqlsumsaldo||'                                                                                 (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalant, ';
          IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
            BEGIN
              wsqlsumsaldo = wsqlsumsaldo||'sum(case when (((tlan.bddata >= '''||prdtinicial||''') and ('||wzeramentosignorar||')) or (tlan.bddata < '''||prdtinicial||''')) then ';
              wsqlsumsaldo = wsqlsumsaldo||wtabelavlr||'bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
              wsqlsumsaldo = wsqlsumsaldo||'                        (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalatu, ';
            END
          ELSE
            BEGIN
              wsqlsumsaldo = wsqlsumsaldo||'sum('||wtabelavlr||'bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
              wsqlsumsaldo = wsqlsumsaldo||'                            (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))) as bdsalatu, ';-- com zeramento
            END
        end

    END

  --SQL de tratamento dos lançamentos a débito
  wsqlwhereland = '';
  wsqlwhereland = wsqlwhereland || 'and (tlan.bdcodplapadrao = '||:prcodplapadrao||') ';
  wsqlwhereland = wsqlwhereland || 'and (tlan.bddata <= '''||:prdtfinal||''') ';
  IF (prcontabilizacao <> 99) THEN
    wsqlwhereland = wsqlwhereland||'and (tlan.bdcontabilizacao in (0,'||:prcontabilizacao||'))';
  IF (prconciliados = 1) THEN
    wsqlwhereland = wsqlwhereland||'and (upper(tlan.bdconcd) = '''||'TRUE'||''') ';
  ELSE
  IF (prconciliados = 2) THEN
    wsqlwhereland = wsqlwhereland||'and ((tlan.bdconcd is null) or (upper(tlan.bdconcd) = '''||'FALSE'||''')) ';
 
  IF (PRTIPOLAN <> '') THEN --#212425
    wsqlwhereland = wsqlwhereland || ' and (tlan.bdtipolan in ('||PRTIPOLAN||'))'; 

  --SQL de tratamento dos lançamentos a crédito
  wsqlwherelanc = '';
  wsqlwherelanc = wsqlwherelanc || 'and (tlan.bdcodplapadrao = '||:prcodplapadrao||') ';
  wsqlwherelanc = wsqlwherelanc || 'and (tlan.bddata <= '''||:prdtfinal||''') ';
  IF (prcontabilizacao <> 99) THEN
    wsqlwherelanc = wsqlwherelanc||'and (tlan.bdcontabilizacao in (0,'||:prcontabilizacao||'))';
  IF (prconciliados = 1) THEN
    wsqlwherelanc = wsqlwherelanc||' and (upper(tlan.bdconcc) = '''||'TRUE'||''') ';
  ELSE
  IF (prconciliados = 2) THEN
    wsqlwherelanc = wsqlwherelanc||' and ((tlan.bdconcc is null) or (upper(tlan.bdconcc) = '''||'FALSE'||''')) ';
 
  IF (PRTIPOLAN <> '') THEN --#212425
    wsqlwherelanc = wsqlwherelanc || ' and (tlan.bdtipolan in ('||PRTIPOLAN||'))'; 

  --#Alt:123277. Implementado o controle para a opção "Lançamentos sem centros de custos". - Carlos Mello (18/07/2019)
  wSQLWHERELAN_AUX = '(('||SUBSTRING(wSQLWHERELAND FROM 4 FOR STRLEN(wSQLWHERELAND))||') or ('||SUBSTRING(wSQLWHERELANC FROM 4 FOR STRLEN(wSQLWHERELANC))||')) '; -- O SUBSTRING foi utilizado para remover a expressão "and"
  if (((PRCC is null) or (PRCC = 0)) and (PRLANCSEMCC > 0)) then
     begin
       wSQLWHERELAND = WSQLWHERELAND||'and ((TLCC.BDCODTPCC in ('||wccs||')) or (TLCC.BDCODTPCC is null)) ';
       WSQLWHERELANC = WSQLWHERELANC||'and ((TLCC.BDCODTPCC in ('||wccs||')) or (TLCC.BDCODTPCC is null)) ';
     end

  --Busca os totais das contas títulos
  wsql = '';
  wsql = wsql || 'select TLAN.BDCODEMPREENDIMENTO, TCADEMPR.BDNOMEEMPRE, ';
  wsql = wsql || '       sum(case when (bddebcre = 0) then bdsalant else 0 end) as bddebant, ';
  wsql = wsql || '       sum(case when (bddebcre = 0) then bdsalatu else 0 end) as bddebatu, ';
  wsql = wsql || '       sum(case when (bddebcre = 1) then bdsalant else 0 end) as bdcreant, ';
  wsql = wsql || '       sum(case when (bddebcre = 1) then bdsalatu else 0 end) as bdcreatu, ';
  wsql = wsql || '       MAX(BDDATA) AS BDDATA ';
  if (prdetalharccempreend = 1) then
    wsql = wsql||'    , TCADEMPR.BDCODTPCC ';
  else
    wsql = wsql||',0 as BDCODTPCC ';
  wsql = wsql || 'from ( ';
                        --*****DÉBITO****
  wsql = wsql || '      select TLAN.BDCODEMP, 0 as BDDEBCRE, case when TINCORP.BDCODEMPREENDIMENTO is null then 0 else TINCORP.BDCODEMPREENDIMENTO end as BDCODEMPREENDIMENTO, ';
  wsql = wsql ||        wsqlsumsaldo;
  wsql = wsql || '      max(BDDATA) as BDDATA ';
  if (prdetalharccempreend = 1) then
    wsql = wsql||'    , TLCC.BDCODTPCC ';
  else
    wsql = wsql||',null as BDCODTPCC';
  wsql = wsql || '      from PLANOS_TPLA TCTA ';
  wsql = wsql || '      inner join VSUC_EMPRESAS_TLAN TLAN on (TLAN.BDCODPLAPADRAO = TCTA.BDCODPLAPADRAO and TLAN.BDDEBITO = TCTA.BDCODTPLA) ';
  wsql = wsql || '      left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 0) ';
--  wsql = wsql || '      left join VEF_EMP_TCADEMPREENDIMENTO TCADEMPR on (TLAN.BDCODEMP = TCADEMPR.BDCODEMP and TINCORP.BDCODEMPREENDIMENTO = TCADEMPR.BDCODEMPREENDIMENTO) ';
  if ((PRCC > 0) or ((PRCC = 0) and (prdetalharccempreend = 1))) then
    begin
      if (prdetalharccempreend = 1) then
        begin
          wsql = wsql || '      left join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 0 ';

          if (PRLANCSEMCC <> 0) then
            wsql = wsql||'and ((TLCC.BDCODTPCC in ('||wccs||')) or (TLCC.BDCODTPCC is null))';

          wsql = wsql || ')';
        end
      else
        begin
          wsql = wsql || '      inner join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 0 and ';

          if (PRLANCSEMCC <> 0) then
            wsql = wsql||' ((TLCC.BDCODTPCC in ('||wccs||')) or (TLCC.BDCODTPCC is null))';
          else
            wsql = wsql||' (TLCC.BDCODTPCC in ('||wccs||'))';

          wsql = wsql || ')';
        end

    end
  else --#Alt:123277. Implementado o controle para a opção "Lançamentos sem centros de custos". - Carlos Mello (18/07/2019)
  if (PRLANCSEMCC > 0) then
     wSQL = wSQL||'      left outer join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 0)';

  wsql = wsql || '      where BDCTALON like('''||:wclassificacao||'%'') ';
  wsql = wsql ||        wsqlwhereland;
  wsql = wsql ||        wsql_emp;
  wsql = wsql ||        wsql_detalharccempreend;
  wsql = wsql || '      group by TLAN.BDCODEMP, BDDEBCRE, TINCORP.BDCODEMPREENDIMENTO';
  if (prdetalharccempreend = 1) then
    wsql = wsql||', TLCC.BDCODTPCC ';
  else
    wsql = wsql||', BDCODTPCC ';
  wsql = wsql || '      union ';
                        --*****CRÉDITO****
  wsql = wsql || '      select TLAN.BDCODEMP, 1 as BDDEBCRE, case when TINCORP.BDCODEMPREENDIMENTO is null then 0 else TINCORP.BDCODEMPREENDIMENTO end as BDCODEMPREENDIMENTO, ';
  wsql = wsql ||        wsqlsumsaldo;
  wsql = wsql || '      max(BDDATA) as BDDATA ';
  if (prdetalharccempreend = 1) then
    wsql = wsql||'    , TLCC.BDCODTPCC ';
  else
    wsql = wsql||',0 as BDCODTPCC';
  wsql = wsql || '      from PLANOS_TPLA TCTA ';
  wsql = wsql || '      inner join VSUC_EMPRESAS_TLAN TLAN on (TLAN.BDCODPLAPADRAO = TCTA.BDCODPLAPADRAO and TLAN.BDCREDITO = TCTA.BDCODTPLA) ';
  wsql = wsql || '      left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 1) ';
--  wsql = wsql || '      left join VEF_EMP_TCADEMPREENDIMENTO TCADEMPR on (TLAN.BDCODEMP = TCADEMPR.BDCODEMP and TINCORP.BDCODEMPREENDIMENTO = TCADEMPR.BDCODEMPREENDIMENTO) ';
  if ((PRCC > 0) or ((PRCC = 0) and (prdetalharccempreend = 1))) then
    begin
      if (prdetalharccempreend = 1) then
        begin
          wsql = wsql || '      left join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 1 ';

          if (PRLANCSEMCC <> 0) then
            wsql = wsql||'and ((TLCC.BDCODTPCC in ('||wccs||')) or (TLCC.BDCODTPCC is null))';

          wsql = wsql || ')';
        end
      else
        begin
          wsql = wsql || '      inner join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 1 and ';

          if (PRLANCSEMCC <> 0) then
            wsql = wsql||' ((TLCC.BDCODTPCC in ('||wccs||')) or (TLCC.BDCODTPCC is null))';
          else
            wsql = wsql||' (TLCC.BDCODTPCC in ('||wccs||'))';
    
          wsql = wsql || ')';
        end

    end
  else --#Alt:123277. Implementado o controle para a opção "Lançamentos sem centros de custos". - Carlos Mello (18/07/2019)
  if (PRLANCSEMCC > 0) then
     wSQL = wSQL||'      left outer join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 1)';

  wsql = wsql || '      where BDCTALON like('''||:wclassificacao||'%'') ';
  wsql = wsql ||        wsqlwherelanc;
  wsql = wsql ||        wsql_emp;
  wsql = wsql ||        wsql_detalharccempreend;
  wsql = wsql || '      group by TLAN.BDCODEMP, BDDEBCRE, TINCORP.BDCODEMPREENDIMENTO ';
  if (prdetalharccempreend = 1) then
    wsql = wsql||', TLCC.BDCODTPCC ';
  else
    wsql = wsql||', BDCODTPCC ';
  wsql = wsql || ') TLAN ';
  wsql = wsql || 'left join VEF_EMP_TCADEMPREENDIMENTO TCADEMPR on (TLAN.BDCODEMP = TCADEMPR.BDCODEMP and TLAN.BDCODEMPREENDIMENTO = TCADEMPR.BDCODEMPREENDIMENTO) ';
--  if (prempreendimento > '0') then
--    wsql = wsql || 'WHERE TLAN.BDCODEMPREENDIMENTO IN ('||:prempreendimento||')';
  wsql = wsql || 'group by TLAN.BDCODEMPREENDIMENTO, TCADEMPR.BDNOMEEMPRE ';
  if (prdetalharccempreend = 1) then
     wsql = wsql||', BDCODTPCC ';

  FOR EXECUTE STATEMENT wsql
  INTO :wcodempreendimento, :wdescempreendimento, :wsaldo_ant_deb, :wsaldo_deb, :wsaldo_ant_cre, :wsaldo_cre, :bddataultlancamento, :bdcodtpcc DO
  BEGIN

    IF ((prdetalharempreendimento = 1) AND (prctatitulo = 0)) THEN
      BEGIN
        IF (wgrupocta IN (1,2,3)) THEN
          bdsaldo_anterior = (wsaldo_ant_cre - wsaldo_ant_deb);
        ELSE
          bdsaldo_anterior = (wsaldo_ant_deb - wsaldo_ant_cre);
     
        IF (wgrupocta IN (1,2,3)) THEN
          bdsaldo_atual = (wsaldo_cre - wsaldo_deb);
        ELSE
          bdsaldo_atual = (wsaldo_deb - wsaldo_cre);

                                   bdsaldo_ant_cre = wsaldo_ant_cre;
                                   bdsaldo_ant_deb = wsaldo_ant_deb;
        bdsaldo_cre = wsaldo_cre - wsaldo_ant_cre;
        bdsaldo_deb = wsaldo_deb - wsaldo_ant_deb;
        bdmovimento = bdsaldo_atual - bdsaldo_anterior;

        bdclassificacao = wclassificacao||'.'||PRCODEMP||iif(9 - CHAR_LENGTH(wcodempreendimento||PRCODEMP) >  0,LPAD('', 9 - CHAR_LENGTH(wcodempreendimento||PRCODEMP), '0'), '')||wcodempreendimento;
        BDRAIZCTASEMEMPREENDIMENTO = WCLASSIFICACAO;
        bdcodempreendimento = wcodempreendimento;
        if (PRDETALHARCCEMPREEND = 0) then
          bddescempreendimento= wdescempreendimento;

        IF ((wdescempreendimento IS NULL) and (PRDETALHARCCEMPREEND = 0)) THEN
          bddescempreendimento = 'Sem empreendimento imobiliário';

        if ((PRDETALHARCCEMPREEND = 0) or
            ((PRDETALHARCCEMPREEND = 1) and (:wempreendimento = :wcodempreendimento) and (:wccs = :bdcodtpcc))) then
          SUSPEND;
        wIMPINCORP = 1; --#Alt:123277.   
      END
    ELSE
      BEGIN
        wsql = '';
        wsql = 'select TLAN.BDCODEMP, TLAN.BDCODTPLA, TLAN.BDDEBCRE, ';
        wsql = wsql||' TLAN.BDCODEMPREENDIMENTO, TCADEMPR.BDNOMEEMPRE, TLAN.BDCODIGOUNIIMOB, ';
        if (prmostrarprop <> 0) then
          wsql = wsql||'SUBSTRING(TCADUNID.BDDESCRICAO FROM 1 for 83)||COALESCE('' - ''||TER.bdcodter||''-''||TER.bdnometer, '' - Não informado'') ';
        else
          wsql = wsql||'TCADUNID.BDDESCRICAO';
        wsql = wsql||',       sum(case when (bddebcre = 0) then bdsalant else 0 end) as bddebant, ';
        wsql = wsql||'       sum(case when (bddebcre = 0) then bdsalatu else 0 end) as bddebatu, ';
        wsql = wsql||'       sum(case when (bddebcre = 1) then bdsalant else 0 end) as bdcreant, ';
        wsql = wsql||'       sum(case when (bddebcre = 1) then bdsalatu else 0 end) as bdcreatu, ';
        wsql = wsql||'       max(BDDATA) as BDDATAULTLANC ';
        if (prdetalharccempreend = 1) then
          wsql = wsql||'    , TCADEMPR.BDCODTPCC ';
        else
          wsql = wsql||',0 as BDCODTPCC ';
        wsql = wsql||' from ( ';
        --*******DÉBITO******
        wsql = wsql||'select TLAN.BDCODEMP, TLAN.BDCODPLAPADRAO, TLAN.BDDATA, TLAN.BDTIPOLAN, ';
       wsql = wsql||'       TLAN.BDDEBITO as BDCODTPLA, TLAN.BDCODTERCEIROD as BDCODTER, 0 as BDDEBCRE, TINCORPD.BDCODEMPREENDIMENTO,';
        IF ((prdetalharunidimob = 0) AND (wusaunidimob IS NOT NULL)) THEN
          wsql = wsql||'       null as BDCODIGOUNIIMOB, ';
        ELSE
          wsql = wsql||'       TINCORPD.BDCODIGOUNIIMOB, ';
        wsql = wsql||wsqlsumsaldo;
        wsql = wsql||'      max(BDDATA) as BDDATAULTLANC ';
        IF (prdetalharccempreend = 1) then
          wsql = wsql||'      , TLCC.BDCODTPCC ';
        else
          wsql = wsql||', null as BDCODTPCC ';
        wsql = wsql||'from VSUC_EMPRESAS_TLAN TLAN ';
        wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORPD on (TLAN.BDCODEMP = TINCORPD.BDCODEMP and TLAN.BDCHAVE = TINCORPD.BDCHAVE and TINCORPD.BDDEBCRE = 0) ';

        if ((PRCC > 0) or ((PRCC = 0) and (prdetalharccempreend = 1))) then
          begin
            if (prdetalharccempreend = 1) then
              begin
                wsql = wsql || 'left join VEF_EMP_TCADEMPREENDIMENTO TCADEMPR on (TINCORPD.BDCODEMP = TCADEMPR.BDCODEMP and TINCORPD.BDCODEMPREENDIMENTO = TCADEMPR.BDCODEMPREENDIMENTO)';
                wsql = wsql || 'left join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 0)';
              END
            else
              wsql = wsql || 'inner join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 0 and TLCC.BDCODTPCC in ('||wccs||')) ';
          end
        else --#Alt:123277. Implementado o controle para a opção "Lançamentos sem centros de custos". - Carlos Mello (18/07/2019)
        if (PRLANCSEMCC > 0) then
           wSQL = wSQL||'left outer join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 0) ';
        wsql = wsql||'where (tlan.bddebito = '||prconta||') ';
        wsql = wsql||wsqlwhereland;

        if (prdetalharccempreend = 1) then
          wsql = wsql|| ' and (/*(TLCC.BDCODTPCC in ('||wccs||')) or*/ (TINCORPD.bdcodempreendimento in ('||:wempreendimento||')))';
        else
        IF ((wcodempreendimento = 0) OR (wcodempreendimento IS NULL)) THEN
          wsql = wsql||'and (TINCORPD.BDCODEMPREENDIMENTO is null) ';
--        ELSE
--        IF (prdetalharccempreend = 1) then
--          wsql = wsql||'and ((TINCORPD.BDCODEMPREENDIMENTO ='||:wcodempreendimento||') or (TLCC.BDCODTPCC = TCADEMPR.BDCODTPCC AND TINCORPD.BDCODEMPREENDIMENTO IS NULL)) ';
        ELSE
          wsql = wsql||'and (TINCORPD.BDCODEMPREENDIMENTO ='||:wcodempreendimento||') ';
        wsql = wsql||wsql_emp;
        wsql = wsql||'group by TLAN.BDCODEMP, TLAN.BDCODPLAPADRAO, TLAN.BDDATA, TLAN.BDDEBITO, TLAN.BDCODTERCEIROD, TLAN.BDTIPOLAN, TINCORPD.BDCODEMPREENDIMENTO, TINCORPD.BDCODIGOUNIIMOB ';
        if (prdetalharccempreend = 1) then
          wsql = wsql||', TLCC.BDCODTPCC ';
        else
          wsql = wsql||', BDCODTPCC ';
        wsql = wsql||'union all ';
        --******CRÉDITO******
        wsql = wsql||'select TLAN.BDCODEMP, TLAN.BDCODPLAPADRAO, TLAN.BDDATA, TLAN.BDTIPOLAN, ';
        wsql = wsql||'       TLAN.BDCREDITO as BDCODTPLA, TLAN.BDCODTERCEIROC as BDCODTER, 1 as BDDEBCRE, TINCORPC.BDCODEMPREENDIMENTO,';
        IF ((prdetalharunidimob = 0) AND (wusaunidimob IS NOT NULL)) THEN
          wsql = wsql||'     null as BDCODIGOUNIIMOB, ';
        ELSE
          wsql = wsql||'     TINCORPC.BDCODIGOUNIIMOB, ';
        wsql = wsql||wsqlsumsaldo;
        wsql = wsql||'      max(BDDATA) as BDDATAULTLANC ';
        if (prdetalharccempreend = 1) then
          wsql = wsql||', TLCC.BDCODTPCC ';
        else
          wsql = wsql||',0 as BDCODTPCC ';
        wsql = wsql||'from vsuc_empresas_tlan tlan ';
        wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORPC on (TLAN.BDCODEMP = TINCORPC.BDCODEMP and TLAN.BDCHAVE = TINCORPC.BDCHAVE and TINCORPC.BDDEBCRE = 1) ';
        if ((PRCC > 0) or ((PRCC = 0) and (prdetalharccempreend = 1))) then
          begin
            if (prdetalharccempreend = 1) then
              begin
                wsql = wsql || 'left join VEF_EMP_TCADEMPREENDIMENTO TCADEMPR on (TINCORPC.BDCODEMP = TCADEMPR.BDCODEMP and TINCORPC.BDCODEMPREENDIMENTO = TCADEMPR.BDCODEMPREENDIMENTO)';
                wsql = wsql || 'left join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 1)';
              end
            else
              wsql = wsql || 'inner join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 1 and TLCC.BDCODTPCC in ('||wccs||')) ';
          end
        else--#Alt:123277. Implementado o controle para a opção "Lançamentos sem centros de custos". - Carlos Mello (18/07/2019)
        if (PRLANCSEMCC > 0) then
           wSQL = wSQL||'left outer join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 1) ';
        wsql = wsql||'where (tlan.bdcredito = '||prconta||') ';
        wsql = wsql||wsqlwherelanc;

        if (prdetalharccempreend = 1) then
          wsql = wsql||' and (/*(TLCC.BDCODTPCC in ('||wccs||')) or */(TINCORPC.bdcodempreendimento in ('||:wempreendimento||')))';
        else
        IF ((wcodempreendimento = 0) OR (wcodempreendimento IS NULL)) THEN
          wsql = wsql||'and (TINCORPC.BDCODEMPREENDIMENTO is null) ';
--        ELSE
--        IF (prdetalharccempreend = 1) then
--          wsql = wsql||'and ((TINCORPC.BDCODEMPREENDIMENTO ='||:wcodempreendimento||') or (TLCC.BDCODTPCC = TCADEMPR.BDCODTPCC and TINCORPC.BDCODEMPREENDIMENTO is null)) ';
        ELSE
          wsql = wsql||'and (TINCORPC.BDCODEMPREENDIMENTO ='||:wcodempreendimento||') ';
        wsql = wsql||wsql_emp;

        wsql = wsql||'group by TLAN.BDCODEMP, TLAN.BDCODPLAPADRAO, TLAN.BDDATA, TLAN.BDCREDITO, TLAN.BDCODTERCEIROC, TLAN.BDTIPOLAN, TINCORPC.BDCODEMPREENDIMENTO, TINCORPC.BDCODIGOUNIIMOB';
        if (prdetalharccempreend = 1) then
          wsql = wsql||', TLCC.BDCODTPCC ';
        else
          wsql = wsql||', BDCODTPCC ';
        wsql = wsql||') tlan ';
        wsql = wsql||'left join VEF_EMP_TCADEMPREENDIMENTO TCADEMPR on (TLAN.BDCODEMP = TCADEMPR.BDCODEMP and TLAN.BDCODEMPREENDIMENTO = TCADEMPR.BDCODEMPREENDIMENTO) ';
        wsql = wsql||'left join VEF_BASE_TCADUNIDIMOBILIARIA TCADUNID on (TLAN.BDCODEMP = TCADUNID.BDCODEMP and TLAN.BDCODEMPREENDIMENTO = TCADUNID.BDCODEMPREENDIMENTO and TLAN.BDCODIGOUNIIMOB = TCADUNID.BDCODIGOUNIIMOB) ';
        if (prmostrarprop <> 0) then
          BEGIN
            wsql = wsql||' left join vw_tterceiro ter on (ter.bdcodter = COALESCE((SELECT FIRST 1 F200.BDCODTER FROM VEF_EMP_TMOVOPIMOBILIARIA_F200 F200';
            wsql = wsql||' WHERE F200.BDCODEMP = tcadunid.bdcodemp';
            wsql = wsql||'   and F200.BDCODEMPREENDIMENTO = tcadunid.BDCODEMPREENDIMENTO';
            wsql = wsql||'   and F200.BDCODIGOUNIIMOB = tcadunid.BDCODIGOUNIIMOB order by F200.BDCHAVE DESC), tcadunid.bdcodter))';
          END
        wsql = wsql||'group by TLAN.BDCODEMP, TLAN.BDCODTPLA, TLAN.BDDEBCRE, TLAN.BDCODEMPREENDIMENTO, TLAN.BDCODIGOUNIIMOB, TCADEMPR.BDNOMEEMPRE, TCADUNID.BDDESCRICAO, TCADEMPR.BDCODTPCC ';
        if (prmostrarprop <> 0) then
         wsql = wsql||', ter.BDNOMETER, TER.bdcodter';


        FOR EXECUTE STATEMENT wsql
        INTO :wcodemp, :wcodtpla, :wdebcre, :wcodempreendimento, :wdescempreendimento, :wcodunidimob, :wdescunidimob,
             :wsaldo_ant_deb, :wsaldo_deb, :wsaldo_ant_cre, :wsaldo_cre, :bddataultlancamento, :bdcodtpcc DO

        BEGIN
          IF (((wcodempreendimento IS NULL) OR (wcodempreendimento = 0)) and (PRDETALHARCCEMPREEND = 0)) THEN
            BEGIN
              wcodempreendimento   = 0;
              bddescempreendimento = 'Sem empreendimento imobiliário';
            END

          bdclassificacao = wclassificacao;
          bdraizclassificacaocta = wclassificacao;
          bdcodempreendimento = wcodempreendimento;
          bdcodunidimob = wcodunidimob;
          if (PRDETALHARCCEMPREEND = 0) then
            bddescempreendimento = wdescempreendimento;
          bddescunidimob = wdescunidimob;

          IF ((prraizctasemempreendimentoant IS NOT NULL) AND (prraizctasemempreendimentoant <> '')) THEN
            BEGIN
              bdclassificacao = prraizctasemempreendimentoant||'.'||PRCODEMP||iif(9 - CHAR_LENGTH(wcodempreendimento||prcodemp) >  0,LPAD('', 9 - CHAR_LENGTH(wcodempreendimento||prcodemp), '0'), '')||wcodempreendimento;
              wpos = strlen(bdclassificacao)+ 1;
              prctalonant = bdclassificacao||SUBSTRING(prctalonant FROM wpos FOR strlen(prctalonant));
            END
                  
          wpos = 1;
          WHILE (POSITION('.', bdclassificacao) > 0) DO
            BEGIN
              wpos = wpos + POSITION('.', bdclassificacao);
              bdclassificacao = SUBSTRING(wclassificacao FROM wpos FOR strlen(wclassificacao));
            END

          IF  ((prdetalharunidimob = 1) AND (UPPER(wusaunidimob) = 'TRUE')) THEN
            BEGIN
              IF (wcodunidimob IS NULL) THEN
                wcodunidimob = 0;
              bdclassificacao = prctalonant||'.'||bdclassificacao||LPAD(wcodunidimob, 5, '0');
            END
          ELSE
            bdclassificacao = prctalonant||'.'||bdclassificacao;
    
          IF (wgrupocta IN (1,2,3)) THEN
            bdsaldo_anterior = (wsaldo_ant_cre - wsaldo_ant_deb);
          ELSE
            bdsaldo_anterior = (wsaldo_ant_deb - wsaldo_ant_cre);
         
          IF (wgrupocta IN (1,2,3)) THEN
            bdsaldo_atual = (wsaldo_cre - wsaldo_deb);
          ELSE
            bdsaldo_atual = (wsaldo_deb - wsaldo_cre);
    
          bdsaldo_ant_cre = wsaldo_ant_cre;
          bdsaldo_ant_deb = wsaldo_ant_deb;
          bdsaldo_cre = wsaldo_cre - wsaldo_ant_cre;
          bdsaldo_deb = wsaldo_deb - wsaldo_ant_deb;
          bdmovimento = bdsaldo_atual - bdsaldo_anterior;

          if ((PRDETALHARCCEMPREEND = 0) or
              ((PRDETALHARCCEMPREEND = 1) and (:wempreendimento = :wcodempreendimento) and (:wccs = :bdcodtpcc))) then
            SUSPEND;
          wIMPINCORP = 1; --#Alt:123277.
        END
      END
  END

  --#Alt:123277. Se não retornou conteúdo e sendo uma conta título com a opção "Detalhar por centro de custo" selecionada a rotina deve retornar esse registro do mesmo jeito para os devidos controles e tratamentos.
  --Caso realmente não precise por não ter valor o sistema vai limpar as contas zeradas
  if ((wIMPINCORP = 0) and (prCTATITULO = 0) and (prDETALHARCC = 1) and (prDETALHAREMPREENDIMENTO = 1) and (Upper(wUSAEMPREENDIMENTO) = 'TRUE')) then
     begin
       --Deve retornar todos os empreendimentos utilizados conforme o filtro para montar corretamente as classificações
       wSQL = 'Select distinct TLAN.BDCODEMP, TINCORP.BDCODEMPREENDIMENTO, TCADEMPR.BDNOMEEMPRE ';
       wSQL = wSQL||'from ( ';
       wSQL = wSQL||'       Select distinct TLAN.BDCODEMP, TLAN.BDCHAVE ';
       wSQL = wSQL||'       from ( ';
       wSQL = wSQL||'              Select TCTA.BDCODPLAPADRAO, TCTA.BDCODTPLA from PLANOS_TPLA TCTA ';
       wSQL = wSQL||'              where ';
       wSQL = wSQL||'              (TCTA.BDCODPLAPADRAO = '||:prCODPLAPADRAO||') and ';
       wSQL = wSQL||'              (TCTA.BDCTALON like('''||:wCLASSIFICACAO||'%'')) and ';
       wSQL = wSQL||'              (TCTA.BDTIPCTA = 1) ';
       wSQL = wSQL||'            ) TCTA ';
       wSQL = wSQL||'       inner join VSUC_EMPRESAS_TLAN TLAN on (TLAN.BDCODPLAPADRAO = TCTA.BDCODPLAPADRAO and ((TLAN.BDDEBITO = TCTA.BDCODTPLA) or (TLAN.BDCREDITO = TCTA.BDCODTPLA))) ';
       wSQL = wSQL||'       where ';
       wSQL = wSQL||'       '||wSQLWHERELAN_AUX||' ';
       wSQL = wSQL||'       '||wSQL_EMP||' ';
       wSQL = wSQL||'     ) TLAN ';
       wSQL = wSQL||'inner join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE) ';
       wSQL = wSQL||'left join VEF_EMP_TCADEMPREENDIMENTO TCADEMPR on (TCADEMPR.BDCODEMP = TLAN.BDCODEMP and TCADEMPR.BDCODEMPREENDIMENTO = TINCORP.BDCODEMPREENDIMENTO) ';

       For execute statement wsql
        into :wCODEMP, :wCODEMPREENDIMENTO, :wDESCEMPREENDIMENTO do
        begin
          bdclassificacao = wclassificacao||'.'||PRCODEMP||iif(9 - CHAR_LENGTH(wcodempreendimento||PRCODEMP) >  0,LPAD('', 9 - CHAR_LENGTH(wcodempreendimento||PRCODEMP), '0'), '')||wcodempreendimento;
          BDRAIZCTASEMEMPREENDIMENTO = WCLASSIFICACAO;
          bdcodempreendimento = wcodempreendimento;
          if (PRDETALHARCCEMPREEND = 0) then
            bddescempreendimento= wdescempreendimento;
          SUSPEND;
        end
     end
END
^

--#alt:23030. Ana - 15/03/2018
create or alter procedure VSUC_SP_RETORNA_SALDOS_CTAINCOR (
    PRCODEMP integer,
    PRCODPLAPADRAO integer,
    PRDTINICIAL date,
    PRDTFINAL date,
    PRCONTA integer,
    PRINDICE integer,
    PRIGNORAZERAMENTO integer,
    PRCONCILIADOS integer,
    PREMPRESAS varchar(2048),
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRCTALONANT varchar(40),
    PRCTATITULO integer,
    PRRAIZCTASEMEMPREENDIMENTOANT varchar(40),
    PRDETALHAREMPREENDIMENTO integer,
    PRDETALHARUNIDIMOB integer,
    PRMOSTRARPROP integer,
    PRCC integer = 0,
    PRLANCSEMCC integer = 0,
    PRDETALHARCC integer = 0)
returns (
    BDCLASSIFICACAO varchar(40),
    BDSALDO_DEB numeric(15,2),
    BDSALDO_ANT_DEB numeric(15,2),
    BDSALDO_CRE numeric(15,2),
    BDSALDO_ANT_CRE numeric(15,2),
    BDMOVIMENTO numeric(15,2),
    BDSALDO_ATUAL numeric(15,2),
    BDSALDO_ANTERIOR numeric(15,2),
    BDRAIZCLASSIFICACAOCTA varchar(40),
    BDCODEMPREENDIMENTO integer,
    BDCODUNIDIMOB integer,
    BDDESCEMPREENDIMENTO varchar(500),
    BDDESCUNIDIMOB varchar(500),
    BDRAIZCTASEMEMPREENDIMENTO varchar(40))
as
declare variable WGRUPOCTA integer;
declare variable WSQL varchar(10000);
declare variable WSQLSUMSALDO varchar(10000);
declare variable WSQLWHERELAND varchar(10000);
declare variable WSQLWHERELANC varchar(10000);
declare variable WSQLWHERELAN_AUX varchar(1000);
declare variable WSQL_EMP varchar(5000);
declare variable WPERMITE integer;
declare variable WCODEMP integer;
declare variable WFILIAL integer;
declare variable WTIPOLANCFILIAL integer;
declare variable WPOS_PERNAMATRIZ integer;
declare variable WPOS_MATRIZ integer;
declare variable WPOS_FILIAL integer;
declare variable WPOS integer;
declare variable WPOSANT integer;
declare variable WCLASSIFICACAO varchar(40);
declare variable WEMPRESAS varchar(2048);
declare variable WCODTPLA integer;
declare variable WOR varchar(4);
declare variable WSALDO_DEB numeric(15,6);
declare variable WSALDO_ANT_DEB numeric(15,6);
declare variable WSALDO_CRE numeric(15,6);
declare variable WSALDO_ANT_CRE numeric(15,6);
declare variable WDEBCRE integer;
declare variable WCODEMPREENDIMENTO integer;
declare variable WCODUNIDIMOB integer;
declare variable WDESCEMPREENDIMENTO varchar(500);
declare variable WDESCUNIDIMOB varchar(500);
declare variable WCLASSIFICACAOAUX varchar(40);
declare variable WCOUNTNIVELCTA integer;
declare variable WCOUNTNIVELCTAAUX integer;
declare variable WUSAEMPREENDIMENTO varchar(5);
declare variable WUSAUNIDIMOB varchar(5);
declare variable WTABELAVLR varchar(5);
declare variable WIMPINCORP integer;
declare variable WSTR_AUX varchar(40);
BEGIN
  wCOUNTNIVELCTA    = 0;
  wCOUNTNIVELCTAAUX = 0;
  WIMPINCORP        = 0; --#Alt:123277. Variável para controlar se passou pelos cálculos de incorporadoras

  --#Alt:123277. Alterado SQL para ser feito uma única vez
  SELECT BDCTALON, BDGRUPOCTA, BDCTAEMPREENDIMENTOSIMOB, BDCTAUNIDADEIMOB FROM PLANOS_TPLA
  WHERE BDCODPLAPADRAO = :PRCODPLAPADRAO AND
        BDCODTPLA = :PRCONTA
  INTO :wCLASSIFICACAO, :wGRUPOCTA, :wUSAEMPREENDIMENTO, :wUSAUNIDIMOB;
    
  IF (((wusaempreendimento IS NULL) OR (wusaempreendimento = '') OR (UPPER(wusaempreendimento) = 'FALSE') ) AND
      ((wusaunidimob IS NULL) OR (wusaunidimob = '') OR (UPPER(wusaunidimob) = 'FALSE'))) THEN
      EXIT;

  IF ((prconta = 0) OR (prconta IS NULL)) THEN
    EXIT;  

  wempresas = '';
  SELECT COALESCE(bdCODMATRIZ,0) FROM tempresas WHERE bdCODEMP = :prCodEmp INTO :wCodEmp;
  IF (wCodEmp > 0) THEN
     BEGIN
       FOR SELECT bdcodemp FROM tempresas
           WHERE (bdcodmatriz = COALESCE((SELECT FIRST 1 bdcodmatriz FROM tempresas WHERE bdcodemp = :prcodemp), :prcodemp)) OR
                 (bdcodemp = COALESCE((SELECT FIRST 1 bdcodmatriz FROM tempresas WHERE bdcodemp = :prcodemp), :prcodemp))
       INTO :wCodEmp DO
         BEGIN
           wempresas = wempresas || wCodEmp || ',';
         END
     END

  wsql_emp = ' and (';
   IF (POSITION(',', prempresas) > 0) THEN
      wsql_emp = wsql_emp||' (tlan.bdcodemp = '||prcodemp||')';
   ELSE
    wsql_emp = wsql_emp||'(tlan.bdcodemp = '||prcodemp||')';
   wsql_emp = wsql_emp||') ';

  if (PRCC > 0) then
    wtabelavlr = 'TLCC.';
  else
    wtabelavlr = 'TLAN.';

  --SQL padrão para somar o saldo
  wsqlsumsaldo = '';
  IF (prindice = 0) THEN
    BEGIN
      wsqlsumsaldo = wsqlsumsaldo||'sum(case when (tlan.bddata < '''||prdtinicial||''') then '||wtabelavlr||'bdvalor else 0 end) as bdsalant, ';
      IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
        wsqlsumsaldo = wsqlsumsaldo||'sum(case when (((tlan.bddata >= '''||prdtinicial||''') and (tlan.bdtipolan <> 10)) or (tlan.bddata < '''||prdtinicial||''')) then '||wtabelavlr||'bdvalor else 0 end) as bdsalatu ';
      ELSE
        wsqlsumsaldo = wsqlsumsaldo||'sum(coalesce('||wtabelavlr||'bdvalor, 0)) as bdsalatu ';
    END
  ELSE
    BEGIN
      wsqlsumsaldo = wsqlsumsaldo||'sum(case when (tlan.bddata < '''||prdtinicial||''') then '||wtabelavlr||'bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
      wsqlsumsaldo = wsqlsumsaldo||'                                                                                 (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalant, ';
      IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
        BEGIN
          wsqlsumsaldo = wsqlsumsaldo||'sum(case when (((tlan.bddata >= '''||prdtinicial||''') and (tlan.bdtipolan <> 10)) or (tlan.bddata < '''||prdtinicial||''')) then ';
          wsqlsumsaldo = wsqlsumsaldo||wtabelavlr||'bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsqlsumsaldo = wsqlsumsaldo||'                        (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalatu ';
        END
      ELSE
        BEGIN
          wsqlsumsaldo = wsqlsumsaldo||'sum('||wtabelavlr||'bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsqlsumsaldo = wsqlsumsaldo||'                            (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))) as bdsalatu ';-- com zeramento
        END
    END

  --SQL de tratamento dos lançamentos a débito
  wsqlwhereland = '';
  wsqlwhereland = wsqlwhereland || 'and (tlan.bdcodplapadrao+0 = '||:prcodplapadrao||') ';
  wsqlwhereland = wsqlwhereland || 'and (tlan.bddata <= '''||:prdtfinal||''') ';
  IF (prcontabilizacao <> 99) THEN
    wsqlwhereland = wsqlwhereland||'and (tlan.bdcontabilizacao in (0,'||:prcontabilizacao||'))';
  IF (prconciliados = 1) THEN
    wsqlwhereland = wsqlwhereland||'and (upper(tlan.bdconcd) = '''||'TRUE'||''') ';
  ELSE
  IF (prconciliados = 2) THEN
    wsqlwhereland = wsqlwhereland||'and ((tlan.bdconcd is null) or (upper(tlan.bdconcd) = '''||'FALSE'||''')) ';

  --SQL de tratamento dos lançamentos a crédito
  wsqlwherelanc = '';
  wsqlwherelanc = wsqlwherelanc || 'and (tlan.bdcodplapadrao+0 = '||:prcodplapadrao||') ';
  wsqlwherelanc = wsqlwherelanc || 'and (tlan.bddata <= '''||:prdtfinal||''') ';
  IF (prcontabilizacao <> 99) THEN
    wsqlwherelanc = wsqlwherelanc||'and (tlan.bdcontabilizacao in (0,'||:prcontabilizacao||'))';
  IF (prconciliados = 1) THEN
    wsqlwherelanc = wsqlwherelanc||' and (upper(tlan.bdconcc) = '''||'TRUE'||''') ';
  ELSE
  IF (prconciliados = 2) THEN
    wsqlwherelanc = wsqlwherelanc||' and ((tlan.bdconcc is null) or (upper(tlan.bdconcc) = '''||'FALSE'||''')) ';

  --#Alt:123277. Implementado o controle para a opção "Lançamentos sem centros de custos". - Carlos Mello (18/07/2019)
  wSQLWHERELAN_AUX = '(('||SUBSTRING(wSQLWHERELAND FROM 4 FOR STRLEN(wSQLWHERELAND))||') or ('||SUBSTRING(wSQLWHERELANC FROM 4 FOR STRLEN(wSQLWHERELANC))||')) '; -- O SUBSTRING foi utilizado para remover a expressão "and"
  if (((PRCC is null) or (PRCC = 0)) and (PRLANCSEMCC > 0)) then
     begin
       wSQLWHERELAND = WSQLWHERELAND||'and ((TLCC.BDCODTPCC in ('||PRCC||')) or (TLCC.BDCODTPCC is null)) ';
       WSQLWHERELANC = WSQLWHERELANC||'and ((TLCC.BDCODTPCC in ('||PRCC||')) or (TLCC.BDCODTPCC is null)) ';
     end

  --Busca os totais das contas títulos
  wsql = '';
  wsql = wsql || 'select TLAN.BDCODEMPREENDIMENTO, TCADEMPR.BDNOMEEMPRE, ';
  wsql = wsql || '       sum(case when (bddebcre = 0) then bdsalant else 0 end) as bddebant, ';
  wsql = wsql || '       sum(case when (bddebcre = 0) then bdsalatu else 0 end) as bddebatu, ';
  wsql = wsql || '       sum(case when (bddebcre = 1) then bdsalant else 0 end) as bdcreant, ';
  wsql = wsql || '       sum(case when (bddebcre = 1) then bdsalatu else 0 end) as bdcreatu ';
  wsql = wsql || 'from ( ';
                        --*****DÉBITO****
  wsql = wsql || '      select TLAN.BDCODEMP, 0 as BDDEBCRE, case when TINCORP.BDCODEMPREENDIMENTO is null then 0 else TINCORP.BDCODEMPREENDIMENTO end as BDCODEMPREENDIMENTO, ';
  wsql = wsql ||        wsqlsumsaldo;
  wsql = wsql || '      from PLANOS_TPLA TCTA ';
  wsql = wsql || '      inner join VSUC_EMPRESAS_TLAN TLAN on (TLAN.BDCODPLAPADRAO = TCTA.BDCODPLAPADRAO and TLAN.BDDEBITO = TCTA.BDCODTPLA) ';
  wsql = wsql || '      left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 0) ';
  wsql = wsql || '      left join VEF_EMP_TCADEMPREENDIMENTO TCADEMPR on (TLAN.BDCODEMP = TCADEMPR.BDCODEMP and TINCORP.BDCODEMPREENDIMENTO = TCADEMPR.BDCODEMPREENDIMENTO) ';
  if (PRCC > 0) then
    begin
      wsql = wsql || '      inner join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 0 and ';
      if (PRLANCSEMCC <> 0) then
        wsql = wsql||' ((TLCC.BDCODTPCC in ('||PRCC||')) or (TLCC.BDCODTPCC is null))';
      else
        wsql = wsql||' (TLCC.BDCODTPCC in ('||PRCC||'))';
      wsql = wsql || ')';
    end
  else --#Alt:123277. Implementado o controle para a opção "Lançamentos sem centros de custos". - Carlos Mello (18/07/2019)
  if (PRLANCSEMCC > 0) then
     wSQL = wSQL||'      left outer join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 0)';

  wsql = wsql || '      where BDCTALON like('''||:wclassificacao||'%'') ';
  wsql = wsql ||        wsqlwhereland;
  wsql = wsql ||        wsql_emp;
  wsql = wsql || '      group by TLAN.BDCODEMP, BDDEBCRE, TINCORP.BDCODEMPREENDIMENTO ';
  wsql = wsql || '      union ';
                        --*****CRÉDITO****
  wsql = wsql || '      select TLAN.BDCODEMP, 1 as BDDEBCRE, case when TINCORP.BDCODEMPREENDIMENTO is null then 0 else TINCORP.BDCODEMPREENDIMENTO end as BDCODEMPREENDIMENTO, ';
  wsql = wsql ||        wsqlsumsaldo;
  wsql = wsql || '      from PLANOS_TPLA TCTA ';
  wsql = wsql || '      inner join VSUC_EMPRESAS_TLAN TLAN on (TLAN.BDCODPLAPADRAO = TCTA.BDCODPLAPADRAO and TLAN.BDCREDITO = TCTA.BDCODTPLA) ';
  wsql = wsql || '      left join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE and TINCORP.BDDEBCRE = 1) ';
  wsql = wsql || '      left join VEF_EMP_TCADEMPREENDIMENTO TCADEMPR on (TLAN.BDCODEMP = TCADEMPR.BDCODEMP and TINCORP.BDCODEMPREENDIMENTO = TCADEMPR.BDCODEMPREENDIMENTO) ';
  if (PRCC > 0) then
    begin
      wsql = wsql || '      inner join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 1 and ';
      if (PRLANCSEMCC <> 0) then
        wsql = wsql||' ((TLCC.BDCODTPCC in ('||PRCC||')) or (TLCC.BDCODTPCC is null))';
      else
        wsql = wsql||' (TLCC.BDCODTPCC in ('||PRCC||'))';
      wsql = wsql || ')';
    end
  else --#Alt:123277. Implementado o controle para a opção "Lançamentos sem centros de custos". - Carlos Mello (18/07/2019)
  if (PRLANCSEMCC > 0) then
     wSQL = wSQL||'      left outer join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 1)';

  wsql = wsql || '      where BDCTALON like('''||:wclassificacao||'%'') ';
  wsql = wsql ||        wsqlwherelanc;
  wsql = wsql ||        wsql_emp;
  wsql = wsql || '      group by TLAN.BDCODEMP, BDDEBCRE, TINCORP.BDCODEMPREENDIMENTO ';
  wsql = wsql || ') TLAN ';
  wsql = wsql || 'left join VEF_EMP_TCADEMPREENDIMENTO TCADEMPR on (TLAN.BDCODEMP = TCADEMPR.BDCODEMP and TLAN.BDCODEMPREENDIMENTO = TCADEMPR.BDCODEMPREENDIMENTO) ';
  wsql = wsql || 'group by TLAN.BDCODEMPREENDIMENTO, TCADEMPR.BDNOMEEMPRE ';


  FOR EXECUTE STATEMENT wsql
  INTO :wcodempreendimento, :wdescempreendimento, :wsaldo_ant_deb, :wsaldo_deb, :wsaldo_ant_cre, :wsaldo_cre DO
  BEGIN

    IF ((prdetalharempreendimento = 1) AND (prctatitulo = 0)) THEN
      BEGIN
        IF (wgrupocta IN (1,2,3)) THEN
          bdsaldo_anterior = (wsaldo_ant_cre - wsaldo_ant_deb);
        ELSE
          bdsaldo_anterior = (wsaldo_ant_deb - wsaldo_ant_cre);
     
        IF (wgrupocta IN (1,2,3)) THEN
          bdsaldo_atual = (wsaldo_cre - wsaldo_deb);
        ELSE
          bdsaldo_atual = (wsaldo_deb - wsaldo_cre);

                                   bdsaldo_ant_cre = wsaldo_ant_cre;
                                   bdsaldo_ant_deb = wsaldo_ant_deb;
        bdsaldo_cre = wsaldo_cre - wsaldo_ant_cre;
        bdsaldo_deb = wsaldo_deb - wsaldo_ant_deb;
        bdmovimento = bdsaldo_atual - bdsaldo_anterior;

        wcodtpla = 0;
        SELECT TCTA.bdcodtpla FROM PLANOS_TPLA TCTA
        WHERE BDCTALON LIKE(:prctalonant) AND
              BDCODPLAPADRAO + 0 = :prcodplapadrao
        INTO  :wcodtpla;

        wpos = 1;
        wposant = 0;
        bdclassificacao = wclassificacao;
        WHILE (POSITION('.', bdclassificacao) > 0) DO
          BEGIN
            wpos = wpos + POSITION('.', bdclassificacao);
            bdclassificacao = SUBSTRING(wclassificacao FROM wpos FOR strlen(wclassificacao));
            wposant = wpos;
            wcountnivelcta = wcountnivelcta + 1;
          END

        IF (wcodtpla <> 0) THEN
          BEGIN
            bdclassificacao = SUBSTRING(wclassificacao FROM 1 FOR wposant-1)||PRCODEMP||iif(9 - CHAR_LENGTH(wcodempreendimento||PRCODEMP) >  0,LPAD('', 9 - CHAR_LENGTH(wcodempreendimento||PRCODEMP), '0'), '')||wcodempreendimento;
            bdraizctasemempreendimento = SUBSTRING(wclassificacao FROM 1 FOR wposant-2);
          END
        ELSE
          BEGIN
            IF (prraizctasemempreendimentoant IS NOT NULL) THEN
              BEGIN
                wclassificacaoaux = prraizctasemempreendimentoant||'.'||PRCODEMP||iif(9 - CHAR_LENGTH(wcodempreendimento||PRCODEMP) >  0,LPAD('', 9 - CHAR_LENGTH(wcodempreendimento||PRCODEMP), '0'), '')||wcodempreendimento;
                wpos = strlen(wclassificacaoaux)+ 1;
                prctalonant = wclassificacaoaux||SUBSTRING(prctalonant FROM wpos FOR strlen(prctalonant));
                wclassificacaoaux = prctalonant;

                wpos = 1;
                wposant = 0;
                WHILE (POSITION('.', wclassificacaoaux) > 0) DO
                  BEGIN
                    wpos = wpos + POSITION('.', wclassificacaoaux);
                    wclassificacaoaux = SUBSTRING(prctalonant FROM wpos FOR strlen(prctalonant));
                    wposant = wpos;
                    wcountnivelctaaux = wcountnivelctaaux + 1;
                  END

                IF (wcountnivelctaaux >= wcountnivelcta) THEN
                  prctalonant = SUBSTRING(prctalonant FROM 1 FOR wposant-2);
              END
            bdclassificacao = prctalonant||'.'||bdclassificacao;
          END

        bdcodempreendimento = wcodempreendimento;
        bddescempreendimento= wdescempreendimento;

        IF (wdescempreendimento IS NULL) THEN
          bddescempreendimento = 'Sem empreendimento imobiliário';

        SUSPEND;
        wIMPINCORP = 1; --#Alt:123277.   
      END
    ELSE
      BEGIN
        wsql = '';
        wsql = 'select TLAN.BDCODEMP, TLAN.BDCODTPLA, TLAN.BDDEBCRE, ';
        wsql = wsql||' TLAN.BDCODEMPREENDIMENTO, TCADEMPR.BDNOMEEMPRE, TLAN.BDCODIGOUNIIMOB, ';
        if (prmostrarprop <> 0) then
          wsql = wsql||'SUBSTRING(TCADUNID.BDDESCRICAO FROM 1 for 83)||COALESCE('' - ''||TER.bdcodter||''-''||TER.bdnometer, '' - Não informado'') ';
        else
          wsql = wsql||'TCADUNID.BDDESCRICAO';
        wsql = wsql||',       sum(case when (bddebcre = 0) then bdsalant else 0 end) as bddebant, ';
        wsql = wsql||'       sum(case when (bddebcre = 0) then bdsalatu else 0 end) as bddebatu, ';
        wsql = wsql||'       sum(case when (bddebcre = 1) then bdsalant else 0 end) as bdcreant, ';
        wsql = wsql||'       sum(case when (bddebcre = 1) then bdsalatu else 0 end) as bdcreatu ';
        wsql = wsql||' from ( ';
        --*******DÉBITO******
        wsql = wsql||'select TLAN.BDCODEMP, TLAN.BDCODPLAPADRAO, TLAN.BDDATA, TLAN.BDTIPOLAN, ';
       wsql = wsql||'       TLAN.BDDEBITO as BDCODTPLA, TLAN.BDCODTERCEIROD as BDCODTER, 0 as BDDEBCRE, TINCORPD.BDCODEMPREENDIMENTO,';
        IF ((prdetalharunidimob = 0) AND (wusaunidimob IS NOT NULL)) THEN
          wsql = wsql||'       null as BDCODIGOUNIIMOB, ';
        ELSE
          wsql = wsql||'       TINCORPD.BDCODIGOUNIIMOB, ';
        wsql = wsql||wsqlsumsaldo;
        wsql = wsql||'from VSUC_EMPRESAS_TLAN TLAN ';
        wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORPD on (TLAN.BDCODEMP = TINCORPD.BDCODEMP and TLAN.BDCHAVE = TINCORPD.BDCHAVE and TINCORPD.BDDEBCRE = 0) ';
        if (PRCC > 0) then
          wsql = wsql || 'inner join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 0 and TLCC.BDCODTPCC in ('||PRCC||')) ';
        else --#Alt:123277. Implementado o controle para a opção "Lançamentos sem centros de custos". - Carlos Mello (18/07/2019)
        if (PRLANCSEMCC > 0) then
           wSQL = wSQL||'left outer join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 0) ';
        wsql = wsql||'where (tlan.bddebito = '||prconta||') ';
        wsql = wsql||wsqlwhereland;
        IF ((wcodempreendimento = 0) OR (wcodempreendimento IS NULL)) THEN
          wsql = wsql||'and (TINCORPD.BDCODEMPREENDIMENTO is null) ';
        ELSE
          wsql = wsql||'and (TINCORPD.BDCODEMPREENDIMENTO ='||:wcodempreendimento||') ';
        wsql = wsql||wsql_emp;
        wsql = wsql||'group by TLAN.BDCODEMP, TLAN.BDCODPLAPADRAO, TLAN.BDDATA, TLAN.BDDEBITO, TLAN.BDCODTERCEIROD, TLAN.BDTIPOLAN, TINCORPD.BDCODEMPREENDIMENTO, TINCORPD.BDCODIGOUNIIMOB ';
        wsql = wsql||'union all ';
        --******CRÉDITO******
        wsql = wsql||'select TLAN.BDCODEMP, TLAN.BDCODPLAPADRAO, TLAN.BDDATA, TLAN.BDTIPOLAN, ';
        wsql = wsql||'       TLAN.BDCREDITO as BDCODTPLA, TLAN.BDCODTERCEIROC as BDCODTER, 1 as BDDEBCRE, TINCORPC.BDCODEMPREENDIMENTO,';
        IF ((prdetalharunidimob = 0) AND (wusaunidimob IS NOT NULL)) THEN
          wsql = wsql||'     null as BDCODIGOUNIIMOB, ';
        ELSE
          wsql = wsql||'     TINCORPC.BDCODIGOUNIIMOB, ';
        wsql = wsql||wsqlsumsaldo;
        wsql = wsql||'from vsuc_empresas_tlan tlan ';
        wsql = wsql||'left join VSUC_EMPRESAS_TLINCORP TINCORPC on (TLAN.BDCODEMP = TINCORPC.BDCODEMP and TLAN.BDCHAVE = TINCORPC.BDCHAVE and TINCORPC.BDDEBCRE = 1) ';
        if (PRCC > 0) then
          wsql = wsql || 'inner join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 1 and TLCC.BDCODTPCC in ('||PRCC||')) ';
        else--#Alt:123277. Implementado o controle para a opção "Lançamentos sem centros de custos". - Carlos Mello (18/07/2019)
        if (PRLANCSEMCC > 0) then
           wSQL = wSQL||'left outer join VSUC_EMPRESAS_TLCC TLCC on (TLCC.BDCODEMP = TLAN.BDCODEMP and TLCC.BDCHAVE = TLAN.BDCHAVE and TLCC.BDDEBCRE = 1) ';
        wsql = wsql||'where (tlan.bdcredito = '||prconta||') ';
        wsql = wsql||wsqlwherelanc;
        IF ((wcodempreendimento = 0) OR (wcodempreendimento IS NULL)) THEN
          wsql = wsql||'and (TINCORPC.BDCODEMPREENDIMENTO is null) ';
        ELSE
          wsql = wsql||'and (TINCORPC.BDCODEMPREENDIMENTO ='||:wcodempreendimento||') ';
        wsql = wsql||wsql_emp;
        wsql = wsql||'group by TLAN.BDCODEMP, TLAN.BDCODPLAPADRAO, TLAN.BDDATA, TLAN.BDCREDITO, TLAN.BDCODTERCEIROC, TLAN.BDTIPOLAN, TINCORPC.BDCODEMPREENDIMENTO, TINCORPC.BDCODIGOUNIIMOB ';
        wsql = wsql||') tlan ';
        wsql = wsql||'left join VEF_EMP_TCADEMPREENDIMENTO TCADEMPR on (TLAN.BDCODEMP = TCADEMPR.BDCODEMP and TLAN.BDCODEMPREENDIMENTO = TCADEMPR.BDCODEMPREENDIMENTO) ';
        wsql = wsql||'left join VEF_BASE_TCADUNIDIMOBILIARIA TCADUNID on (TLAN.BDCODEMP = TCADUNID.BDCODEMP and TLAN.BDCODEMPREENDIMENTO = TCADUNID.BDCODEMPREENDIMENTO and TLAN.BDCODIGOUNIIMOB = TCADUNID.BDCODIGOUNIIMOB) ';
        if (prmostrarprop <> 0) then
          BEGIN
            wsql = wsql||' left join vw_tterceiro ter on (ter.bdcodter = COALESCE((SELECT FIRST 1 F200.BDCODTER FROM VEF_EMP_TMOVOPIMOBILIARIA_F200 F200';
            wsql = wsql||' WHERE F200.BDCODEMP = tcadunid.bdcodemp';
            wsql = wsql||'   and F200.BDCODEMPREENDIMENTO = tcadunid.BDCODEMPREENDIMENTO';
            wsql = wsql||'   and F200.BDCODIGOUNIIMOB = tcadunid.BDCODIGOUNIIMOB order by F200.BDCHAVE DESC), tcadunid.bdcodter))';
          END
        wsql = wsql||'group by TLAN.BDCODEMP, TLAN.BDCODTPLA, TLAN.BDDEBCRE, TLAN.BDCODEMPREENDIMENTO, TLAN.BDCODIGOUNIIMOB, TCADEMPR.BDNOMEEMPRE, TCADUNID.BDDESCRICAO ';
        if (prmostrarprop <> 0) then
         wsql = wsql||', ter.BDNOMETER, TER.bdcodter';

        
        FOR EXECUTE STATEMENT wsql
        INTO :wcodemp, :wcodtpla, :wdebcre, :wcodempreendimento, :wdescempreendimento, :wcodunidimob, :wdescunidimob,
             :wsaldo_ant_deb, :wsaldo_deb, :wsaldo_ant_cre, :wsaldo_cre DO
        BEGIN
             wpermite = 1;
          IF (wpermite = 1) THEN
            BEGIN  
              IF ((wcodempreendimento IS NULL) OR (wcodempreendimento = 0) ) THEN
                BEGIN
                  wcodempreendimento   = 0;
                  bddescempreendimento = 'Sem empreendimento imobiliário';
                END

              bdclassificacao = wclassificacao;
              bdraizclassificacaocta = wclassificacao;
              bdcodempreendimento = wcodempreendimento;
              bdcodunidimob = wcodunidimob;
              bddescempreendimento = wdescempreendimento;
              bddescunidimob = wdescunidimob;

              IF ((prraizctasemempreendimentoant IS NOT NULL) AND (prraizctasemempreendimentoant <> '')) THEN
                BEGIN
                  bdclassificacao = prraizctasemempreendimentoant||'.'||PRCODEMP||iif(9 - CHAR_LENGTH(wcodempreendimento||prcodemp) >  0,LPAD('', 9 - CHAR_LENGTH(wcodempreendimento||prcodemp), '0'), '')||wcodempreendimento;
                  wpos = strlen(bdclassificacao)+ 1;
                  prctalonant = bdclassificacao||SUBSTRING(prctalonant FROM wpos FOR strlen(prctalonant));
                END

              wpos = 1;
              wposant = 0;
              WHILE (POSITION('.', bdclassificacao) > 0) DO
                BEGIN
                  wpos = wpos + POSITION('.', bdclassificacao);
                  bdclassificacao = SUBSTRING(wclassificacao FROM wpos FOR strlen(wclassificacao));
                  wposant = wpos;
                END

              IF  ((prdetalharunidimob = 1) AND (UPPER(wusaunidimob) = 'TRUE')) THEN
                BEGIN
                  IF (wcodunidimob IS NULL) THEN
                    wcodunidimob = 0;
                  bdclassificacao = prctalonant||'.'||LPAD(wcodunidimob, 9, '0');
                END
              ELSE
                bdclassificacao = prctalonant||'.'||bdclassificacao;
        
              IF (wgrupocta IN (1,2,3)) THEN
                bdsaldo_anterior = (wsaldo_ant_cre - wsaldo_ant_deb);
              ELSE
                bdsaldo_anterior = (wsaldo_ant_deb - wsaldo_ant_cre);
             
              IF (wgrupocta IN (1,2,3)) THEN
                bdsaldo_atual = (wsaldo_cre - wsaldo_deb);
              ELSE
                bdsaldo_atual = (wsaldo_deb - wsaldo_cre);
        
                              bdsaldo_ant_cre = wsaldo_ant_cre;
                              bdsaldo_ant_deb = wsaldo_ant_deb;
              bdsaldo_cre = wsaldo_cre - wsaldo_ant_cre;
              bdsaldo_deb = wsaldo_deb - wsaldo_ant_deb;
              bdmovimento = bdsaldo_atual - bdsaldo_anterior;

              SUSPEND;
              wIMPINCORP = 1; --#Alt:123277.
            END
        END
      END
  END

  --#Alt:123277. Se não retornou conteúdo e sendo uma conta título com a opção "Detalhar por centro de custo" selecionada a rotina deve retornar esse registro do mesmo jeito para os devidos controles e tratamentos.
  --Caso realmente não precise por não ter valor o sistema vai limpar as contas zeradas
  if ((wIMPINCORP = 0) and (prCTATITULO = 0) and (prDETALHARCC = 1) and (prDETALHAREMPREENDIMENTO = 1) and (Upper(wUSAEMPREENDIMENTO) = 'TRUE')) then
     begin
       wCODTPLA = 0;
       Select TCTA.BDCODTPLA from PLANOS_TPLA TCTA
       where BDCTALON like(:prCTALONANT) and
             BDCODPLAPADRAO + 0 = :prCODPLAPADRAO
       into  :wCODTPLA;

       wPos     = 1;
       wPosAnt  = 0;
       wSTR_AUX = wCLASSIFICACAO;
       while  (POSITION('.', wSTR_AUX) > 0) do
         begin
           wPos            = wPos + POSITION('.', wSTR_AUX);
           wSTR_AUX = SUBSTRING(wCLASSIFICACAO FROM wPos FOR STRLEN(wCLASSIFICACAO));
           wPosAnt         = wPos;
           wCountNivelCta = wCountNivelCta + 1;
         end

       --Deve retornar todos os empreendimentos utilizados conforme o filtro para montar corretamente as classificações
       wSQL = 'Select distinct TLAN.BDCODEMP, TINCORP.BDCODEMPREENDIMENTO, TCADEMPR.BDNOMEEMPRE ';
       wSQL = wSQL||'from ( ';
       wSQL = wSQL||'       Select distinct TLAN.BDCODEMP, TLAN.BDCHAVE ';
       wSQL = wSQL||'       from ( ';
       wSQL = wSQL||'              Select TCTA.BDCODPLAPADRAO, TCTA.BDCODTPLA from PLANOS_TPLA TCTA ';
       wSQL = wSQL||'              where ';
       wSQL = wSQL||'              (TCTA.BDCODPLAPADRAO = '||:prCODPLAPADRAO||') and ';
       wSQL = wSQL||'              (TCTA.BDCTALON like('''||:wCLASSIFICACAO||'%'')) and ';
       wSQL = wSQL||'              (TCTA.BDTIPCTA = 1) ';
       wSQL = wSQL||'            ) TCTA ';
       wSQL = wSQL||'       inner join VSUC_EMPRESAS_TLAN TLAN on (TLAN.BDCODPLAPADRAO = TCTA.BDCODPLAPADRAO and ((TLAN.BDDEBITO = TCTA.BDCODTPLA) or (TLAN.BDCREDITO = TCTA.BDCODTPLA))) ';
       wSQL = wSQL||'       where ';
       wSQL = wSQL||'       '||wSQLWHERELAN_AUX||' ';
       wSQL = wSQL||'       '||wSQL_EMP||' ';
       wSQL = wSQL||'     ) TLAN ';
       wSQL = wSQL||'inner join VSUC_EMPRESAS_TLINCORP TINCORP on (TLAN.BDCODEMP = TINCORP.BDCODEMP and TLAN.BDCHAVE = TINCORP.BDCHAVE) ';
       wSQL = wSQL||'left join VEF_EMP_TCADEMPREENDIMENTO TCADEMPR on (TCADEMPR.BDCODEMP = TLAN.BDCODEMP and TCADEMPR.BDCODEMPREENDIMENTO = TINCORP.BDCODEMPREENDIMENTO) ';

       For execute statement wsql
        into :wCODEMP, :wCODEMPREENDIMENTO, :wDESCEMPREENDIMENTO do
        begin
          bdCLASSIFICACAO = wSTR_AUX;

          if ((wCODEMPREENDIMENTO IS NULL) OR (wCODEMPREENDIMENTO = 0) ) then
             begin
               wCODEMPREENDIMENTO   = 0;
               bdDESCEMPREENDIMENTO = 'Sem empreendimento imobiliário';
             end
    
          if (wCODTPLA <> 0) then
             begin
               bdCLASSIFICACAO            = SUBSTRING(wCLASSIFICACAO FROM 1 FOR wPosAnt-1)||prCODEMP||iif(9 - CHAR_LENGTH(wCODEMPREENDIMENTO||prCODEMP) >  0,LPAD('', 9 - CHAR_LENGTH(wCODEMPREENDIMENTO||prCODEMP), '0'), '')||wCODEMPREENDIMENTO;
               bdRAIZCTASEMEMPREENDIMENTO = SUBSTRING(wCLASSIFICACAO FROM 1 FOR wPosAnt-2);
             end
          else
             begin
               if (prRAIZCTASEMEMPREENDIMENTOANT IS NOT NULL) then
                  begin
                    wCLASSIFICACAOAUX = prRAIZCTASEMEMPREENDIMENTOANT||'.'||prCODEMP||iif(9 - CHAR_LENGTH(wCODEMPREENDIMENTO||prCODEMP) >  0,LPAD('', 9 - CHAR_LENGTH(wCODEMPREENDIMENTO||prCODEMP), '0'), '')||wCODEMPREENDIMENTO;
                    wPos              = STRLEN(wCLASSIFICACAOAUX)+ 1;
                    prCTALONANT       = wCLASSIFICACAOAUX||SUBSTRING(prCTALONANT FROM wPos FOR STRLEN(prCTALONANT));
                    wCLASSIFICACAOAUX = prCTALONANT;

                    wPos              = 1;
                    wPosAnt           = 0;
                    wCountNivelCtaAux = 0;
                    while (POSITION('.', wCLASSIFICACAOAUX) > 0) do
                      begin
                        wPos              = wPos + POSITION('.', wCLASSIFICACAOAUX);
                        wCLASSIFICACAOAUX = SUBSTRING(prCTALONANT FROM wPos FOR STRLEN(prCTALONANT));
                        wPosAnt           = wPos;
                        wCountNivelCtaAux = wCountNivelCtaAux + 1;
                      end

                    If (wCountNivelCtaAux >= wCountNivelCta) then
                       prCTALONANT = SUBSTRING(prCTALONANT FROM 1 FOR wPosAnt-2);
                  end
    
               bdCLASSIFICACAO = prCTALONANT||'.'||bdCLASSIFICACAO;
             end
    
           SUSPEND;
        end
     end
END
^

/*Esta rotina retorna a classificação da conta passada por parâmetro conforme o código do empreendimento e da unidade imobiliária, verificando
o nível da conta título que ela descende*/
create or alter procedure VSUC_RETORNA_CLA_INCORP (
    PRCODCTA integer,
    PRCODPLAPADRAO integer,
    PRCODEMPREENDIMENTO integer,
    PRUNIDIMOB integer,
    PRNAODETALHAREMPREENDIMENTO integer = 0,
    PRNAODETALHARUNIDIMOB integer = 0,
    PREMPRESA integer = 0)
returns (
    BDCLASSIFICACAO varchar(40))
as
declare variable WUSAEMPREENDIMENTO varchar(5);
declare variable WUSAUNIDIMOB varchar(5);
declare variable WCLASSIFICACAO varchar(40);
declare variable WCLASSIFICACAOORG varchar(40);
declare variable WCLASSIFICACAOAUX varchar(40);
declare variable WPOS integer;
declare variable WPOSCTA integer;
declare variable WTIPCTA integer;
declare variable WUNIIMOB varchar(12);
BEGIN
  SELECT BDCTAEMPREENDIMENTOSIMOB, BDCTAUNIDADEIMOB, BDCTALON, BDTIPCTA FROM PLANOS_TPLA
  WHERE BDCODPLAPADRAO = :prcodplapadrao AND
        BDCODTPLA = :prcodcta
  INTO :wusaempreendimento, :wusaunidimob, :wclassificacaoorg, :WTIPCTA;

  IF (((wusaempreendimento IS NULL) OR (wusaempreendimento = '') OR (UPPER(wusaempreendimento) = 'FALSE') ) AND
      ((wusaunidimob IS NULL) OR (wusaunidimob = '') OR (UPPER(wusaunidimob) = 'FALSE'))) THEN
      EXIT;

  wclassificacaoaux = WCLASSIFICACAOORG;
  WHILE (POSITION('.', wclassificacaoaux) > 0) DO
    BEGIN
      wpos = POSITION('.', wclassificacaoaux);
      wclassificacaoaux = SUBSTRING(wclassificacaoaux FROM wpos + 1 FOR strlen(wclassificacaoaux));
  END
  bdclassificacao = wclassificacaoorg;
  if (WTIPCTA = 1) then
    bdclassificacao = SUBSTRING(bdclassificacao from 1 FOR CHAR_LENGTH(bdclassificacao) - CHAR_LENGTH(wclassificacaoaux) - 1);

  IF ((UPPER(wusaempreendimento) = 'TRUE') AND (PRNAODETALHAREMPREENDIMENTO = 0)) THEN
    begin
      bdclassificacao = bdclassificacao||'.'||prempresa||iif(9 - CHAR_LENGTH(prcodempreendimento||prempresa) >  0,LPAD('', 9 - CHAR_LENGTH(prcodempreendimento||prempresa), '0'), '')||prcodempreendimento;
    end

  bdclassificacao = bdclassificacao||'.'||wclassificacaoaux;

  IF ((UPPER(wusaunidimob) = 'TRUE') AND (PRNAODETALHARUNIDIMOB = 0)) THEN
    BEGIN
      --#alt:120032 - Carlos Machado - Erro validacao ECD Conta consolidada e empreendimento - Deve adicionar os 0000000 atras sempre
      if ((prunidimob > 0) AND (prunidimob IS NOT NULL)) then
        WUNIIMOB = prunidimob;
      else
        WUNIIMOB = '';
      bdclassificacao = bdclassificacao||LPAD(WUNIIMOB, 5, '0');
    END
  SUSPEND;
END
^
--#alt:23030. fim

create or alter procedure VSUC_COPIA_PLANO_TROCA (
    CODIGONOVO integer,
    CODIGOCOPIAR integer)
as
declare variable WNOVOCODIGO integer;
BEGIN
  DELETE FROM VSUC_PLANOTROCA_TINTACOES WHERE BDCODPLATROCAINT = :codigonovo;

  IF (:codigonovo IS NULL OR (:codigonovo = 0)) THEN
     SELECT COALESCE(MAX(BDCODPLATROCAINT), 1) FROM VSUC_PLANOTROCA_TINTEGRACOES INTO :wnovocodigo;
  ELSE
     wnovocodigo = :codigonovo;
  insert into VSUC_PLANOTROCA_TINTACOES (BDCODPLATROCAINT, BDCHAVE, BDCTAUNICA, BDCCUNICO, BDDEBITOFIL, BDCREDITOFIL,
                                         BDCCDEBFIL, BDCCCREFIL, BDHISTFIL, BDAPLICAFILTROHIST, BDACAODEBITO,
                                         BDACAOCREDITO, BDACAOCCDEB, BDACAOCCCRE, BDACAOHIST, BDACAOTERDEB, BDACAOTERCRE,
                                         BDCODPLAPADRAO, BDDEBITOACAO, BDCODTERCEIROD, BDCREDITOACAO, BDCODTERCEIROC,
                                         BDCODHIST, BDCODTPHIACAO, BDCODCENTRO, BDCCDEBACAO, BDCCCREACAO, BDCODEMP,
                                         BDACAOEMPREED, BDACAOUNIIMOBD, BDACAOEMPREEC, BDACAOUNIIMOBC, BDCODEMPREEACAOD,
                                         BDCODUNIIMOBACAOD, BDCODEMPREEACAOC, BDCODUNIIMOBACAOC)
  select :wnovocodigo, BDCHAVE, BDCTAUNICA, BDCCUNICO, BDDEBITOFIL, BDCREDITOFIL, BDCCDEBFIL, BDCCCREFIL, BDHISTFIL,
         BDAPLICAFILTROHIST, BDACAODEBITO, BDACAOCREDITO, BDACAOCCDEB, BDACAOCCCRE, BDACAOHIST, BDACAOTERDEB,
         BDACAOTERCRE, BDCODPLAPADRAO, BDDEBITOACAO, BDCODTERCEIROD, BDCREDITOACAO, BDCODTERCEIROC, BDCODHIST,
         BDCODTPHIACAO, BDCODCENTRO, BDCCDEBACAO, BDCCCREACAO, BDCODEMP, BDACAOEMPREED, BDACAOUNIIMOBD, BDACAOEMPREEC,
         BDACAOUNIIMOBC, BDCODEMPREEACAOD, BDCODUNIIMOBACAOD, BDCODEMPREEACAOC, BDCODUNIIMOBACAOC
  from VSUC_PLANOTROCA_TINTACOES where BDCODPLATROCAINT = :CODIGOCOPIAR;
END^

--#alt:18801. Alterei a estrutura da procedure. Ana - 18/05/2017
--#alt:18661 - Fiz alterações aqui para não ter que executar a consulta em lugares diferentes e para corrigir o erro de duplicidade do participante. Ana - 10/05/2017
--#alt:15089 - Procedimento para retornar a preparação das contas do registro I157 da exportação do Sped ECD. Ana - 15/03/2017
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_CONTAS_I157 (
    PRCODPLAPADRAO INTEGER,
    PRCODPLAPADRAOI157 INTEGER,
    PRMODELO INTEGER = 0)
RETURNS (
    BDCODTPLAI157 INTEGER,
    BDCTALONI157 VARCHAR(40),
    BDNOMCTAI157 VARCHAR(100),
    BDTIPCTA INTEGER,
    BDCODTPLA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDCODTER INTEGER,
    BDNOMETER VARCHAR(100),
    BDCODEMPREENDIMENTO INTEGER,
    BDCODIGOUNIIMOB INTEGER,
    BDFILIAL INTEGER,
    BDDEBCRE_ORIGINAL VARCHAR(1),
    BDVALOR_ORIGINAL NUMERIC(15,2),
    BDCTALON_FISICO VARCHAR(100),
    BDPARTICIPANTE INTEGER,
    BDCODGRUPOCTA INTEGER) /*#136662 - DJONATHAN*/
as
declare variable WSQL DM_MAXVARCHAR;
BEGIN
  IF (prmodelo = 0) THEN
    BEGIN
      wSQL =        ' select CTAI157.BDCODTPLAI157, CTAI157.BDCTALON as BDCTALONI157, CTAI157.BDNOMCTA as BDNOMCTAI157, CTAI157.BDTIPCTA,';
      wSQL = wSQL|| '        CTA.BDCODTPLA, CTA.BDCTALON as BDCTALON, CTA.BDNOMCTA, CTAVINC.BDCODTER, ';
      wSQL = wSQL|| '        (select first 1 BDNOMETER ';
      wSQL = wSQL|| '        from TTERCEIRO_REF PART ';
      wSQL = wSQL|| '        where PART.BDCODTER = CTAVINC.BDCODTER ';
      wSQL = wSQL|| '        order by BDREFEMP desc) as BDNOMETER, null as BDCODEMPREENDIMENTO, null as BDCODIGOUNIIMOB, null as BDFILIAL, ';
      wSQL = wSQL|| '        CTAI157.BDVALOR_ORIGINAL, CTAI157.BDDEBCRE_ORIGINAL, CTAI157.BDCTALON_FISICO, CTA.BDPARTICIPANTE, CTAI157.BDCODGRUPOCTA';
      wSQL = wSQL|| ' from PLANOS_TPLA_ECD_I157 CTAI157 ';
      wSQL = wSQL|| ' left join PLANOS_TPLA_I157 CTAVINC on (CTAI157.BDCODPLAPADRAO = CTAVINC.BDCODPLAPADRAOECD and';
      wSQL = wSQL|| '                                        CTAI157.BDCODTPLAI157 = CTAVINC.BDCODTPLAI157 and ';
      wSQL = wSQL|| '                                        CTAI157.BDCODPLAPADRAOI157 = CTAVINC.BDCODPLAPADRAOI157)';
      wSQL = wSQL|| ' left join PLANOS_TPLA CTA on (CTAVINC.BDCODPLAPADRAO = CTA.BDCODPLAPADRAO and CTAVINC.BDCODTPLA = CTA.BDCODTPLA) ';
      --wSQL = wSQL|| ' left join TTERCEIRO_REF PART on (CTAVINC.BDCODTER = PART.BDCODTER) ';  --#alt:18661. Ana - 10/05/2017
      wSQL = wSQL|| ' where CTAI157.BDCODPLAPADRAO = ' || PRCODPLAPADRAO;
      IF (PRCODPLAPADRAOI157 > 0) THEN
        wSQL = wSQL|| ' and CTAI157.BDCODPLAPADRAOI157 = ' || PRCODPLAPADRAOI157;
    END
  ELSE
    BEGIN
      wSQL =        ' select CTAI157.BDCODTPLAI157, CTAI157.BDCTALON as BDCTALONI157, CTAI157.BDNOMCTA as BDNOMCTAI157, CTAI157.BDTIPCTA,';
      wSQL = wSQL|| '        CTA.BDCODTPLA, CTA.BDCTALON as BDCTALON, CTA.BDNOMCTA, CTAVINC.BDCODTER, ';
      wSQL = wSQL|| '        (select first 1 BDNOMETER ';
      wSQL = wSQL|| '        from TTERCEIRO_REF PART ';
      wSQL = wSQL|| '        where PART.BDCODTER = CTAVINC.BDCODTER ';
      wSQL = wSQL|| '        order by BDREFEMP desc) as BDNOMETER, CTAVINC.BDCODEMPREENDIMENTO, CTAVINC.BDCODIGOUNIIMOB, CTAVINC.BDFILIAL, ';
      wSQL = wSQL|| '        CTAI157.BDVALOR_ORIGINAL, CTAI157.BDDEBCRE_ORIGINAL, CTAI157.BDCTALON AS BDCTALON_FISICO, CTA.BDPARTICIPANTE, CTAI157.BDCODGRUPOCTA';
      wSQL = wSQL|| ' from EMPRESAS_CONTAS_ECD_I157 CTAI157 ';
      wSQL = wSQL|| ' left join EMPRESAS_INCORP_I157 CTAVINC on (CTAI157.BDCODEMP = CTAVINC.BDCODEMP and ';
      wSQL = wSQL|| '                                        CTAI157.BDCODTPLAI157 = CTAVINC.BDCODTPLAI157 and ';
      wSQL = wSQL|| '                                        CTAI157.BDCODPLAPADRAOI157 = CTAVINC.BDCODPLAPADRAOI157) ';
      wSQL = wSQL|| ' left join PLANOS_TPLA CTA on (CTAVINC.BDCODPLAPADRAO = CTA.BDCODPLAPADRAO and CTAVINC.BDCODTPLA = CTA.BDCODTPLA) ';
      wSQL = wSQL|| ' where CTAI157.BDCODEMP = ' || PRCODPLAPADRAO;
      IF (PRCODPLAPADRAOI157 > 0) THEN
        wSQL = wSQL|| ' and CTAI157.BDCODPLAPADRAOI157 = ' || PRCODPLAPADRAOI157;
    END

  FOR EXECUTE STATEMENT wSQL INTO :BDCODTPLAI157, :BDCTALONI157, :BDNOMCTAI157, :BDTIPCTA, :BDCODTPLA, :BDCTALON, :BDNOMCTA, :BDCODTER, :BDNOMETER, :BDCODEMPREENDIMENTO,
                                  :BDCODIGOUNIIMOB, :BDFILIAL, :BDVALOR_ORIGINAL, :BDDEBCRE_ORIGINAL, :BDCTALON_FISICO, :BDPARTICIPANTE, :BDCODGRUPOCTA  DO
  BEGIN
    SUSPEND;
  END
END
^

create or alter procedure SP_REMOVE_CLASS_ZERADAS (
    PRCLASSIFICACAO varchar(40),
    PRRETIRAZEROSFINAL DM_BOOLEAN = 'FALSE')
returns (
    BDCLASSIFICACAO varchar(40))
as
declare variable WCLASSIFICAO varchar(40);
declare variable WCLASSIFICAO_AUX varchar(40);
declare variable WPOS integer;
declare variable WPOS_ULTIMA integer;
begin
  wclassificao = prclassificacao||'.';
  PRRETIRAZEROSFINAL = UPPER(PRRETIRAZEROSFINAL);

  wpos = 1; --Guarda a posição atual de procura
  wpos_ultima = 1; --Guarda a posição de inicio da remocao
  if (PRRETIRAZEROSFINAL = 'FALSE') then
    begin
      WHILE (wpos <= char_length(wclassificao)) DO
        begin
          if (substring(wclassificao from wpos for 1) = '.') then --Remove a parte zerada
            begin
              wclassificao_aux = '';
              if (wpos_ultima > 1) then
                wclassificao_aux = wclassificao_aux || substring(wclassificao from 1 for wpos_ultima);
              if (wpos < char_length(wclassificao)) then
                wclassificao_aux = wclassificao_aux || substring(wclassificao from wpos + 1);
              wpos = wpos - (char_length(wclassificao) - char_length(wclassificao_aux)) + 1; --Subtrai os caracteres da posicao atual e vai pro próximo char
              wclassificao = wclassificao_aux;
            end
          else
          if (substring(wclassificao from wpos for 1) <> '0') then --Caso encontre um numero deve procurar na proxima parte
            begin
              wpos = position('.', wclassificao, wpos)+1;
              wpos_ultima = wpos-1;
              if (wpos = 0) then break;
            end
          else  --Caso encontre um zero continua
            begin
              wpos = wpos + 1;
            end
        end
      if (substring(wclassificao from char_length(wclassificao)) = '.') then
        wclassificao = substring(wclassificao from 1 for char_length(wclassificao) - 1);
    end
  else
    /* #171955 - Relatórios com plano de contas secundário - COSIF - somatório incorreto do grupo 3
    Tratamento criado para o plano secundário pois estava se perdendo nas somas por conta da classificação. */
    WHILE ((substring(wclassificao from char_length(wclassificao)) = '.') or (substring(wclassificao from char_length(wclassificao)) = '0'))  do
      wclassificao = substring(wclassificao from 1 for char_length(wclassificao) - 1);
  bdclassificacao = wclassificao;
  SUSPEND;
end
^

CREATE OR ALTER PROCEDURE VSUC_COPIA_PLANO_SECUNDARIO (
    PRAPELIDONOVO VARCHAR(20),
    PRCODIGONOVO INTEGER,
    PRCODIGOCOPIAR INTEGER)
AS
BEGIN
  DELETE FROM PLANOS_TPLA_SECUNDARIO WHERE BDCODPLAPADRAO_SEC = :PRCODIGONOVO;

  IF ((PRCODIGONOVO IS NULL) OR (PRCODIGONOVO = 0)) THEN
    SELECT BDCODPLAPADRAO_SEC FROM TPLANO_SECUNDARIO WHERE BDAPELIDO = :PRAPELIDONOVO INTO PRCODIGONOVO;


  INSERT INTO PLANOS_TPLA_SECUNDARIO (BDCODPLAPADRAO_SEC, BDCODTPLA, BDCTALON, BDNOMCTA, BDAPECTA, BDTIPCTA, BDGRUPOCTA)
  SELECT :PRCODIGONOVO AS BDCODPLAPADRAO_SEC, BDCODTPLA, BDCTALON, BDNOMCTA, BDAPECTA, BDTIPCTA, BDGRUPOCTA
  FROM PLANOS_TPLA_SECUNDARIO WHERE BDCODPLAPADRAO_SEC = :PRCODIGOCOPIAR;

  INSERT INTO VSUC_PREPARACAO_TPLA_SECUNDARIO (BDCODPLAPADRAO, BDCODEMP, BDCODPLAPADRAO_SEC, BDCODTPLA, BDCODTPLA_SEC)
  SELECT BDCODPLAPADRAO, BDCODEMP, :PRCODIGONOVO AS BDCODPLAPADRAO_SEC, BDCODTPLA, BDCODTPLA_SEC
  FROM VSUC_PREPARACAO_TPLA_SECUNDARIO WHERE BDCODPLAPADRAO_SEC = :PRCODIGOCOPIAR;
END^

/* Restore proc. body: VSUC_SP_RETORNA_BALANCETE_COMPA */
ALTER PROCEDURE VSUC_SP_RETORNA_BALANCETE_COMPA(PRCODEMP VARCHAR(2048),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRTIPCOMP INTEGER,
PRQTDCOMP INTEGER,
PRCODTPCC VARCHAR(8192),
PRIGNZER SMALLINT,
PRREFEMP INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDCODMATRIZ INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCENTROS INTEGER,
BDCODTPLA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDSALANT NUMERIC(15,2),
BDSALATU_01 NUMERIC(15,2),
BDSALMOV_01 NUMERIC(15,2),
BDSALATU_02 NUMERIC(15,2),
BDSALMOV_02 NUMERIC(15,2),
BDSALATU_03 NUMERIC(15,2),
BDSALMOV_03 NUMERIC(15,2),
BDSALATU_04 NUMERIC(15,2),
BDSALMOV_04 NUMERIC(15,2),
BDSALATU_05 NUMERIC(15,2),
BDSALMOV_05 NUMERIC(15,2),
BDSALATU_06 NUMERIC(15,2),
BDSALMOV_06 NUMERIC(15,2),
BDSALATU_07 NUMERIC(15,2),
BDSALMOV_07 NUMERIC(15,2),
BDSALATU_08 NUMERIC(15,2),
BDSALMOV_08 NUMERIC(15,2),
BDSALATU_09 NUMERIC(15,2),
BDSALMOV_09 NUMERIC(15,2),
BDSALATU_10 NUMERIC(15,2),
BDSALMOV_10 NUMERIC(15,2),
BDSALATU_11 NUMERIC(15,2),
BDSALMOV_11 NUMERIC(15,2),
BDSALATU_12 NUMERIC(15,2),
BDSALMOV_12 NUMERIC(15,2))
 AS
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WDATA_INICIAL DATE;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WCTALONINI VARCHAR(40);
DECLARE VARIABLE WCTALONFIN VARCHAR(40);
DECLARE VARIABLE WSQL VARCHAR(10240);
BEGIN
  wsql = 'select temp.bdcodemp, temp.bdcnpjemp, temp.bdcodmatriz, ';
  wsql = wsql||'tref.bdnomemp, tref.bdcodplapadrao, tref.bdcodcentros ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join tempresas_ref tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'and tref.bdrefemp = (select first 1 tempresas_ref.bdrefemp from tempresas_ref ';
  wsql = wsql||                     'where tempresas_ref.bdrefemp <= '||prrefemp;
  wsql = wsql||                     ' and tempresas_ref.bdcodemp = '||prcodemp;
  wsql = wsql||                     ' order by tempresas_ref.bdrefemp desc) ';
  wsql = wsql||'order by temp.bdcodmatriz, temp.bdcodemp';

  FOR EXECUTE STATEMENT wsql 
      INTO :bdcodemp, :bdcnpjemp, :bdcodmatriz, :bdnomemp, :bdcodplapadrao, :bdcodcentros DO
      BEGIN
        DELETE FROM vsuc_empresas_tbalancete;
        -- verificação dos centro de custos selecionados
        IF (prcodtpcc <> '') THEN
           BEGIN
             wsql = 'select tpcc.bdcodtpcc, tpcc.bdnomcta from centros_tpcc tpcc ';
             wsql = wsql||'where tpcc.bdcodcentro = '||bdcodcentros;
             wsql = wsql||' and tpcc.bdcodtpcc in ('||prcodtpcc||') ';
             wsql = wsql||'order by tpcc.bdctalon';
           END
        ELSE
        -- o retorno desse sql deve ser "0" para que o laço passe pelo menos uma vez pelo cálculo de saldos,
        -- isso deve acontecer quando não há centro de custo selecionado
           BEGIN
             wsql = 'select first 1 distinct(case when (tpcc.bdcodtpcc <> 0) then 0 end) "bdcodtpcc", tpcc.bdnomcta ';
             wsql = wsql||'from centros_tpcc tpcc ';
             wsql = wsql||'where tpcc.bdcodcentro = '||bdcodcentros;
           END

        FOR EXECUTE STATEMENT wsql
            INTO :bdcodtpcc, :bdnomtpcc DO
            BEGIN
              IF (bdcodtpcc = 0) THEN
                 bdnomtpcc = '';

              FOR SELECT tpla.bdcodtpla, tpla.bdctalon, tpla.bdnomcta, tpla.bdtipcta
                  FROM planos_tpla tpla
                  WHERE tpla.bdcodplapadrao = :bdcodplapadrao
                  ORDER BY tpla.bdctalon
                  INTO :bdcodtpla, :bdctalon, :bdnomcta, :bdtipcta DO
                  BEGIN
                    wcount = 1;
                    WHILE (wcount < (prqtdcomp + 1)) DO
                      BEGIN
                        -- mensal
                        IF (prtipcomp = 0) THEN
                           BEGIN
                             wdata_inicial = addmonth(prdatini, wcount);
                             wdata_final   = addmonth(prdatini, wcount+1)-1;
                           END
                        ELSE
                        -- anual
                           BEGIN
                             wdata_inicial = addyear(prdatini, wcount);
                             wdata_final   = addyear(prdatini, wcount+1)-1;
                           END
              
                        IF (wdata_final <= prdatfin) THEN
                           BEGIN
                             -- janeiro
                             IF (wcount = 1) THEN
                                BEGIN
                                  SELECT tsal.SALDO_ANTERIOR, tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalant, bdsalatu_01;
                                END
                             ELSE
                             -- fevereiro
                             IF (wcount = 2) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_02;
                                END
                             ELSE
                             -- março
                             IF (wcount = 3) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_03;
                                END
                             ELSE
                             -- abril
                             IF (wcount = 4) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_04;
                                END
                             ELSE
                             -- maio
                             IF (wcount = 5) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_05;
                                END
                             ELSE
                             -- junho
                             IF (wcount = 6) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_06;
                                END
                             ELSE
                             -- julho
                             IF (wcount = 7) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_07;
                                END
                             ELSE
                             -- agosto
                             IF (wcount = 8) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_08;
                                END
                             ELSE
                             -- setembro
                             IF (wcount = 9) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_09;
                                END
                             ELSE
                             -- outubro
                             IF (wcount = 10) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_10;
                                END
                             ELSE
                             -- novembro
                             IF (wcount = 11) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_11;
                                END
                             ELSE
                             -- dezembro
                             IF (wcount = 12) THEN
                                BEGIN
                                  SELECT tsal.Saldo_Atual
                                  FROM sp_retorna_saldo_emp(:bdcodemp, :bdcodtpla, :wdata_inicial, :wdata_final, :prignzer, :bdcodtpcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsal
                                  INTO :bdsalatu_12;
                                END
      
                             SUSPEND;
                             wcount = wcount +1;
                           END
                      END
                  END
            END
      END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_BALANCO_PATRIMO */
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_BALANCO_PATRIMO (
    PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCTALONINI VARCHAR(40),
PRCTALONFIN VARCHAR(40),
PRCTALONPAS VARCHAR(40),
PRINDICE INTEGER,
PRLISTACC VARCHAR(8192),
PRNAOMOSTRACONTACOMP INTEGER,
PRCTASEMMOV INTEGER,
PRREFEMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRAGRUPARPARTICIPANTEPORCNPJ INTEGER = 0,
    PRAGRUPARPARTICIPANTEPORCPF INTEGER = 0)
RETURNS (
    BDCODEMP INTEGER,
BDCODMATRIZ INTEGER,
BDCODEMPFILIAL INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDSEQCTA VARCHAR(40),
BDCODCENTROS INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(80),
BDSALANT NUMERIC(15,2),
BDSALMOV NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDANAVER NUMERIC(15,2),
BDFORMULA VARCHAR(1024),
BDGRPCTA INTEGER,
BDAPECTA VARCHAR(20))
 AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODCENTROS INTEGER;
DECLARE VARIABLE WCODCTAINI INTEGER;
DECLARE VARIABLE WCODCTAFIN INTEGER;
DECLARE VARIABLE WSQLEMP VARCHAR(4096);
DECLARE VARIABLE WLENGTH INTEGER;
DECLARE VARIABLE WVALTIT NUMERIC(15,2);
DECLARE VARIABLE WSQLTCC VARCHAR(8192);
DECLARE VARIABLE WSEQCTA VARCHAR(100);
DECLARE VARIABLE WDATAHORA VARCHAR(30);
DECLARE VARIABLE WFIND SMALLINT;
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCODPARTICIPANTE INTEGER;
BEGIN
  wsqlemp = 'select case when (temp.bdcodmatriz is null) then temp.bdcodemp ';
  SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
  IF (wpos <> 0) THEN
     wsqlemp = wsqlemp||'            when (temp.bdcodmatriz is not null) then temp.bdcodmatriz ';
  ELSE
     BEGIN
       wsqlemp = wsqlemp||'          when ((temp.bdcodmatriz is not null) and (temp.bdcodemp not in ('||prcodemp||'))) then temp.bdcodmatriz ';
       wsqlemp = wsqlemp||'          when (temp.bdcodemp in ('||prcodemp||')) then temp.bdcodemp ';
     END
  wsqlemp = wsqlemp||'       end bdcodemp, ';
  wsqlemp = wsqlemp||'       temp.bdcodemp bdcodempfilial, ';
  wsqlemp = wsqlemp||'       tref.bdnomemp, temp.bdcnpjemp, tref.bdcodplapadrao, temp.bdcodmatriz ';
  wsqlemp = wsqlemp||'from tempresas temp ';
  wsqlemp = wsqlemp||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsqlemp = wsqlemp||'where temp.bdcodemp in ('||prcodemp||') ';
  wsqlemp = wsqlemp||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';

  wdatahora = localtimestamp;

  FOR EXECUTE STATEMENT wsqlemp
--      into :wcodemp, :bdcodmatriz, :wcodplapadrao, :wcodcentros do
      INTO :bdcodemp, :bdcodempfilial, :bdnomemp, :bdcnpjemp, :bdcodplapadrao, :bdcodmatriz DO
      BEGIN
        IF (bdcodmatriz IS NULL) THEN
           bdcodmatriz = 0;
        -- retorna a primeira conta referente a classificacao
        SELECT FIRST 1 planos_tpla.bdcodtpla FROM planos_tpla
        WHERE planos_tpla.bdcodplapadrao = :bdcodplapadrao
        AND planos_tpla.bdctalon = :prctalonini
        ORDER BY planos_tpla.bdctalon ASC INTO :wcodctaini;
        -- retorna a ultima conta referente a classificacao
        SELECT FIRST 1 planos_tpla.bdcodtpla FROM planos_tpla
        WHERE planos_tpla.bdcodplapadrao = :bdcodplapadrao
        AND planos_tpla.bdctalon = :prctalonfin
        ORDER BY planos_tpla.bdctalon ASC INTO :wcodctafin;
        -- sql responsavel pela limpeza da tabela cache de saldos
        --delete from VSUC_EMPRESAS_TBALANCETE_2; Fabiano: 23/05/2012 Não pode apagar tudo porque tem outros usuários que estão comitando dados. Só posso apagar o que é meu.
--        delete from vsuc_empresas_tbalancete_2 where bdcodemp <> 0 and bddatahora = :wdatahora;
        DELETE FROM vsuc_empresas_tbalancete_3 WHERE bdcodemp <> 0;
        -- verificacao dos centro de custos selecionados
        IF ((TRIM(prlistacc) <> '') AND (wcodcentros IS NOT NULL)) THEN
           BEGIN
             wsqltcc = 'select tpcc.bdcodtpcc, tpcc.bdnomcta from centros_tpcc tpcc ';
             wsqltcc = wsqltcc||'where tpcc.bdcodcentro = '||wcodcentros;
             wsqltcc = wsqltcc||' and tpcc.bdcodtpcc in ('||prlistacc||')';
           END
        ELSE
        -- o retorno desse sql deve ser 0 para que o laco passe pelo menos uma vez pelo calculo de saldos,
        -- isso deve acontecer quando nao ha centro de custo selecionado
           BEGIN
             wsqltcc = 'select case when (temp.bdcodemp <> 0) then 0 end, tref.bdnomemp ';
             wsqltcc = wsqltcc||'from tempresas temp ';
             wsqltcc = wsqltcc||'inner join tempresas_ref tref on (tref.bdcodemp = temp.bdcodemp) ';
             --Pegava sempre a mesma empresa
             --wsqltcc = wsqltcc||'where temp.bdcodemp = '||bdcodemp;
             wsqltcc = wsqltcc||'where temp.bdcodemp = '||bdcodempfilial;
             wsqltcc = wsqltcc||' and tref.bdrefemp = (select first 1 tempresas_ref.bdrefemp from tempresas_ref ';
             wsqltcc = wsqltcc||                      'where tempresas_ref.bdcodemp = temp.bdcodemp ';
             wsqltcc = wsqltcc||                      'and tempresas_ref.bdrefemp <= '||prrefemp;
             wsqltcc = wsqltcc||                      ' order by tempresas_ref.bdrefemp desc) ';
           END
        -- laco dos centro de custos
        IF (NOT ((bdcodplapadrao IS NULL) AND (wcodcentros IS NULL))) THEN
        FOR EXECUTE STATEMENT wsqltcc
            INTO :bdcodtpcc, :bdnomtpcc DO
            BEGIN
              -- caso nao ha centro de custo selecionado, o nome do mesmo deve ser em branco
              IF (bdcodtpcc = 0) THEN
                 BEGIN
                   bdnomtpcc = '';
                   bdcodcentros = 0;
                 END
              ELSE
                 bdcodcentros = wcodcentros;
              -- laco do calculo dos saldos do plano de contas
              FOR SELECT tsal.codemp, tsal.codplapadrao, tsal.conta, tsal.classificacao,
                         tsal.nomeconta, tsal.tipconta, tsal.saldo_anterior, tsal.saldo_atual,
                         tref.bdnomemp, temp.bdcnpjemp, tsal.formula, tsal.grupoconta, tsal.participante, tsal.apecta
                  FROM vsuc_sp_retorna_saldo_contas_x(:bdcodempfilial, :wcodctaini, :wcodctafin, :prdatini, :prindice, :prdatfin, :prignzer, :bdcodtpcc, :bdcodplapadrao,
                                                      0,:prnaomostracontacomp,:prconsolidada, :prniveisconta,:prcodemp,:prcontabilizacao,:prmatrizfilialconsolidado,0) tsal
                  LEFT OUTER JOIN tempresas temp ON (temp.bdcodemp = tsal.codemp)
                  LEFT OUTER JOIN tempresas_ref tref ON (tref.bdcodemp = temp.bdcodemp)
                  WHERE tref.bdrefemp = (SELECT FIRST 1 tempresas_ref.bdrefemp FROM tempresas_ref
                                         WHERE tempresas_ref.bdcodemp = temp.bdcodemp
                                         AND tempresas_ref.bdrefemp <= :prrefemp
                                         ORDER BY tempresas_ref.bdrefemp DESC)
                  INTO :bdcodemp, :bdcodplapadrao, :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta,
                       :bdsalant, :bdsalatu, :bdnomemp, :bdcnpjemp, :bdformula, :BDGRPCTA,  :wparticipante, :bdapecta DO
              BEGIN
                -- Detalhado por participante
                IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdtipcta = 1)) THEN
                  BEGIN
                    --#alt:17868. Adicionado parâmetro para agrupar por CNPJ. Ana - 12/05/2017
                    FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdsaldo_atual, tsalctapar.bdsaldo_anterior, tsalctapar.bdcodparticipante
                        --from vsuc_sp_retorna_saldos_cta_part(:bdcodemp,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,-- alt:#6647 - gilberto - 12/09/2013
                        FROM vsuc_sp_retorna_saldos_ctaparty(:bdcodemp,:bdcodplapadrao,:prdatini,:prdatfin,:bdcodcta,:prindice,
                                                             :prignzer,0,0,:prcodemp,:prcontabilizacao,:pragruparparticipanteporcnpj,
                                                             '', 0, :pragruparparticipanteporcpf, 0, 0, :prrefemp) tsalctapar
                        INTO :bdnomcta, :bdctalon, :bdsalatu, :bdsalant, :wcodparticipante DO
                        BEGIN
                          IF (prconcatenacodparticipante = 1) THEN
                            BEGIN
                              wpos     = CHARACTER_LENGTH(:wcodparticipante);
                                         -- 100 -> máximo de caracteres para nome da conta
                                         -- 03 -> qtd de caracteres " - ";
                              wpos     = ((100 - wpos) - 3);
                              bdnomcta = wcodparticipante||' - '||SUBSTRING(bdnomcta FROM 1 FOR wpos);
                            END

                          -- se a conta for "patrimonio liquido"
                          IF (bdctalon = prctalonpas) THEN
                            BEGIN
                              wseqcta = bdnomcta;
                              IF (bdsalatu IS NULL) THEN
                                wvaltit = 0;
                              ELSE
                                wvaltit = bdsalatu;
                            END
                          bdsalmov = bdsalatu - bdsalant;
                          bdseqcta = wseqcta;
                          -- cálculo do percentual da analise vertical
                          IF (wvaltit = 0) THEN
                            bdanaver = 0;
                          ELSE
                            bdanaver = (bdsalatu * 100) / wvaltit;

                          SUSPEND;
                        END
                  END
                ELSE
                  BEGIN
                    -- sql para verificar se a conta atual é uma titulo geral
                    SELECT FIRST 1 tpos.pos FROM pos('.', :bdctalon) tpos INTO :wlength;
                    IF (wlength IS NULL) THEN
                      wlength = 0;
                    -- se a conta for uma "titulo geral" ou "patrimonio liquido"
                    IF ((wlength = 0) OR (bdctalon = prctalonpas)) THEN
                      BEGIN
                        wseqcta = bdnomcta;
                        IF (bdsalatu IS NULL) THEN
                          wvaltit = 0;
                        ELSE
                          wvaltit = bdsalatu;
                      END
                    bdsalmov = bdsalatu - bdsalant;
                    bdseqcta = wseqcta;
                    -- caculo do percentual da analise vertical
                    IF (wvaltit = 0) THEN
                      bdanaver = 0;
                    ELSE
                      bdanaver = (bdsalatu * 100) / wvaltit;

                --alt:7847 - Alguém, talvez o Gilberto havia comentado esta parte que só dá o suspend se a conta tiver movimento ou for para imprimir contas sem movimento.
                --Estou descomentando essa parte e comentando a que foi adicionada para imprimir sempre as contas consolidadas, pois pelo que vimos, atualmente não faz sentido. Pedro
                IF ((prctasemmov = 0) AND ((bdsalatu <> 0) OR (bdsalmov <> 0)) OR (prctasemmov = 1)) THEN
                   SUSPEND;
--                     gilberto
/*                    if ((not prconsolidada is null) and (prconsolidada <> 0)) then
                      suspend;
                    else
                      begin
                        select bdresult from vsuc_sp_consolidada(:bdcodplapadrao, :bdctalon) into :wfind;
                        if ((wfind is null) or (wfind = 0)) then
                          suspend;
                        else
                          if (bdtipcta = 2) then
                            suspend;
                      end*/
                  END
              END
            END
      END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_CADASTRO_BEM */
CREATE OR ALTER PROCEDURE vsuc_sp_retorna_cadastro_bem (
    prcodemp INTEGER,
    prdatini DATE,
    prdatfin DATE,
    prctaini INTEGER,
    prctafin INTEGER,
    prcodplapadrao INTEGER,
    prcontabilizacao INTEGER,
    prmostrardepreciados INTEGER)
RETURNS (
    bdcodemp INTEGER,
    bdcodbem INTEGER,
    bddatataxadepreciacao DATE,
    bdmesesdepreciados INTEGER,
    bddepreciacaoperiodo NUMERIC(15,2),
    bddepreciacaoacumuladaatual NUMERIC(15,2),
    bdvalorresidualcontabil NUMERIC(15,2),
    bdvalorresidualcontabilmoeda NUMERIC(15,2))
AS
DECLARE VARIABLE wctaini VARCHAR(40);
DECLARE VARIABLE wctafin VARCHAR(40);
BEGIN
  /* conta inicial */
  SELECT FIRST 1 tpla.bdctalon FROM planos_tpla tpla
  WHERE tpla.bdcodplapadrao = :prcodplapadrao
  AND tpla.bdcodtpla = :prctaini
  INTO :wctaini;
  /* conta final */
  SELECT FIRST 1 tpla.bdctalon FROM planos_tpla tpla
  WHERE tpla.bdcodplapadrao = :prcodplapadrao
  AND tpla.bdcodtpla = :prctafin
  INTO :wctafin;

  /* filtro */
  FOR SELECT tbem.bdcodemp, tbem.bdcodbem FROM empresas_tbem tbem
      LEFT OUTER JOIN planos_tpla tpla ON (tpla.bdcodplapadrao = tbem.bdcodplapadrao AND tpla.bdcodtpla = tbem.bdcodtpla)
      WHERE tbem.bdcodemp = :prcodemp
      --alt:13685 - 08/04/2016 - Implementação para mostrar bens totalmente depreciados. Pedro
      AND (((:PRMOSTRARDEPRECIADOS = 0) AND (tbem.bddatoriaquibem BETWEEN :prdatini AND :prdatfin)) OR ((:prmostrardepreciados = 1) AND (tbem.bddatoriaquibem <= :prdatfin)))
      AND tpla.bdctalon BETWEEN :wctaini AND :wctafin
      INTO :bdcodemp, :bdcodbem DO
      BEGIN
        SELECT tcalc.prdatataxadepreciacao,
               tcalc.prmesesdepreciados,
               tcalc.prdepreciacaoperiodo, tcalc.prdepreciacaoacumuladaatual,
               tcalc.prvalorresidualcontabil, tcalc.prvalorresidualcontabilmoeda
        FROM sp_cons_calc_dep(:bdcodemp, :bdcodbem, extract(MONTH FROM :prdatini)||'/01/'||extract(YEAR FROM :prdatini), :prdatfin,0,:prcontabilizacao) tcalc
        WHERE (tcalc.PRMESESDEPRECIAR = 0) OR (:prmostrardepreciados = 0) --alt:13685 - 08/04/2016 - Implementação para mostrar bens totalmente depreciados. Pedro
        INTO :bddatataxadepreciacao, :bdmesesdepreciados, :bddepreciacaoperiodo,
             :bddepreciacaoacumuladaatual, :bdvalorresidualcontabil, :bdvalorresidualcontabilmoeda;
        SUSPEND;
      END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_CLASSGROUP */
ALTER PROCEDURE VSUC_SP_RETORNA_CLASSGROUP(PRCODPLANOPADRAO INTEGER,
PRCAMPOPESQUISA VARCHAR(20),
PRCONTEUDO VARCHAR(40),
PRPESQUISAINICIO INTEGER)
 RETURNS(PRCLASSIFICACAO VARCHAR(40))
 AS
DECLARE VARIABLE wcount INTEGER;
DECLARE VARIABLE wclassaux VARCHAR(40);
DECLARE VARIABLE wclass VARCHAR(40);
DECLARE VARIABLE wsql VARCHAR(1024);
BEGIN
  wsql = 'Select TPLA.BDCTALON ';
  wsql = wsql||'from PLANOS_TPLA TPLA ';
  wsql = wsql||'where TPLA.bdcodplapadrao = '||prcodplanopadrao;
  IF (prpesquisainicio = 0) THEN
     wsql = wsql||'and UPPER('||prcampopesquisa||') LIKE UPPER('||''''||prconteudo||'%'||''''||')';
  ELSE
     wsql = wsql||'and UPPER('||prcampopesquisa||') LIKE UPPER('||''''||'%'||prconteudo||'%'||''''||')';

  IF (prconteudo <> '') THEN
     BEGIN
       FOR EXECUTE STATEMENT wsql INTO :wclass DO
         BEGIN
           wclassaux = wclass;
           wclass = wclass||'.';
           WHILE (strlen(wclass) > 0) DO
             BEGIN
               IF (SUBSTRING(wclass FROM strlen(wclass) FOR 1) = '.') THEN
                  BEGIN
                    prclassificacao = SUBSTRING(wclass FROM 1 FOR strlen(wclass)-1);
                    SUSPEND;
                  END

               wclass = SUBSTRING(wclass FROM 1 FOR strlen(wclass)-1);
             END

           wcount = strlen(wclassaux);
           FOR SELECT tpla.bdctalon FROM planos_tpla tpla
               WHERE tpla.bdcodplapadrao = :prcodplanopadrao
               AND SUBSTRING(tpla.bdctalon FROM 1 FOR :wcount) = :wclassaux
               AND tpla.bdctalon <> :wclassaux
               ORDER BY tpla.bdctalon
               INTO :prclassificacao DO
               SUSPEND;

         END
     END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_COMPARATIVO */
ALTER PROCEDURE VSUC_SP_RETORNA_COMPARATIVO(PREMPRESAS VARCHAR(1024),
PRCTAINI INTEGER,
PRCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRINDICE INTEGER,
PRTIPCOMP INTEGER,
PRCC VARCHAR(8192),
PRTIPOSALDO INTEGER,
PRREFEMP INTEGER,
PRIGNZER INTEGER,
PRLANSEMCC INTEGER,
PRAGRUPAEMPRESAFILIAIS INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRNIVEISCONTA VARCHAR(50),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCODMATRIZ INTEGER,
BDCNPJEMP VARCHAR(18),
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(50),
BDNOMCTA VARCHAR(100),
BDTIPCTA INTEGER,
BDGRPCTA INTEGER,
BDCODTPCC INTEGER,
BDNOMTPCC VARCHAR(40),
BDQTDCOMP INTEGER,
BDSALDO01 NUMERIC(15,2),
BDMOVIMENTO01 NUMERIC(15,2),
BDSALDO02 NUMERIC(15,2),
BDMOVIMENTO02 NUMERIC(15,2),
BDSALDO03 NUMERIC(15,2),
BDMOVIMENTO03 NUMERIC(15,2),
BDSALDO04 NUMERIC(15,2),
BDMOVIMENTO04 NUMERIC(15,2),
BDSALDO05 NUMERIC(15,2),
BDMOVIMENTO05 NUMERIC(15,2),
BDSALDO06 NUMERIC(15,2),
BDMOVIMENTO06 NUMERIC(15,2),
BDSALDO07 NUMERIC(15,2),
BDMOVIMENTO07 NUMERIC(15,2),
BDSALDO08 NUMERIC(15,2),
BDMOVIMENTO08 NUMERIC(15,2),
BDSALDO09 NUMERIC(15,2),
BDMOVIMENTO09 NUMERIC(15,2),
BDSALDO10 NUMERIC(15,2),
BDMOVIMENTO10 NUMERIC(15,2),
BDSALDO11 NUMERIC(15,2),
BDMOVIMENTO11 NUMERIC(15,2),
BDSALDO12 NUMERIC(15,2),
BDMOVIMENTO12 NUMERIC(15,2),
BDFORMULA VARCHAR(1024))
 AS
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WTOTAL INTEGER;
DECLARE VARIABLE WFIND INTEGER;
DECLARE VARIABLE WCLASSINI VARCHAR(50);
DECLARE VARIABLE WCLASSFIN VARCHAR(50);
DECLARE VARIABLE WDATA_INICIAL DATE;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WSQLUPDATE VARCHAR(10240);
DECLARE VARIABLE WSQLTPCC VARCHAR(10240);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMEMP VARCHAR(100);
DECLARE VARIABLE WCNPJEMP VARCHAR(18);
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODCTA INTEGER;
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WGRPCTA INTEGER;
DECLARE VARIABLE WCODCENTROS INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WNOMTPCC VARCHAR(40);
DECLARE VARIABLE WSALATU NUMERIC(15,2);
DECLARE VARIABLE WMOVIMENTO NUMERIC(15,2);
DECLARE VARIABLE WSALDORELATORIO NUMERIC(15,2);
DECLARE VARIABLE WFORMULA VARCHAR(10240);
DECLARE VARIABLE WSQLCONTAS VARCHAR(10240);
DECLARE VARIABLE WSQLMESES VARCHAR(10240);
DECLARE VARIABLE WDATAHORA VARCHAR(30);
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WNIVELCONTA INTEGER;
DECLARE VARIABLE WIMPANALITICA INTEGER;
DECLARE VARIABLE WINDICE INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCODPARTICIPANTE INTEGER;
BEGIN
  wdatahora = localtimestamp;
  --delete from vsuc_empresas_comparativo;

  wsql = 'select first 1 bdcodplapadrao from vw_empresas_ref_atual  ';
  wsql = wsql||'where bdcodemp in ('||prempresas||') ';
  EXECUTE STATEMENT wsql INTO :wcodplapadrao;

  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
  AND planos_tpla.bdcodtpla = :prctaini
  INTO :wclassini;

  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
  AND planos_tpla.bdcodtpla = :prctafin
  INTO :wclassfin;

  SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :wcodplapadrao
  AND SUBSTRING(planos_tpla.bdctalon FROM 1 FOR CHARACTER_LENGTH(:wclassfin)) = :wclassfin
  ORDER BY planos_tpla.bdctalon DESC
  INTO :wclassfin;

  -- Se encontrar no prNiveisConta o "1" significa que deve imprimir contas analíticas
  SELECT BDRPOS FROM RPOS(',1,',','||:prniveisconta||',') INTO :wimpanalitica;

  wsql = 'select bdcodemp, bdnomemp, bdcodmatriz, bdcnpjemp, bdcodplapadrao ';
  wsql = wsql||'from vw_empresas_ref_atual ';
  wsql = wsql||'where bdcodemp in ('||prempresas||') ';

  wcount    = 0;
  FOR EXECUTE STATEMENT wsql
      INTO :wcodemp, :wnomemp, :wcodmatriz, :wcnpjemp, :wcodplapadrao DO
      BEGIN
        -- giovanni... insere somente as contas com lancamentos

        wsqlcontas = '';
        wsqlcontas = wsqlcontas||' select distinct CONTAS.bdcodtpla,CONTAS.bdctalon,CONTAS.bdtipcta, CONTAS.bdgrupocta, CONTAS.bdnomcta, CONTAS.bdformula, ';
        --alt:7211 - Alterado de wcodemp para prempresas para passar a empresa matriz e suas filiais, caso sejam informadas. Pedro
        --wsqlcontas = wsqlcontas||' CONTAS.bdparticipante  from VSUC_SP_RETORNA_CONTAS_USADAS('||wcodemp||', '||wcodplapadrao||','''||prdatini||''','''||prdatfin||''','''||wclassini||''','''||wclassfin||''',0,0,0,3,0) CONTAS ';
        wsqlcontas = wsqlcontas||' CONTAS.bdparticipante  from VSUC_SP_RETORNA_CONTAS_USADAS('''||prempresas||''', '||wcodplapadrao||','''||prdatini||''','''||prdatfin||''','''||wclassini||''','''||wclassfin||''',0,0,0,3,0) CONTAS ';
        wsqlcontas = wsqlcontas||' order by BDCTALON';


        FOR EXECUTE STATEMENT wsqlcontas
            INTO :wcodcta, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wformula, :wparticipante DO
          BEGIN
            -- Filtro pelo nível da conta
            SELECT contar_char FROM contar_char(:wctalon,'.') INTO :wnivelconta;
            wnivelconta = wnivelconta + 1;
            SELECT BDRPOS FROM RPOS(','||CAST(:wnivelconta AS VARCHAR(100))||',',','||:prniveisconta||',') INTO :windice;
            IF ((prniveisconta = '9999') OR           -- Não tem filtro
                (wnivelconta = 1) OR                  -- O primeiro nível sempre imprime
                ((windice > 0) AND (:wtipcta = 0)) OR -- O nível da conta foi selecionado no filtro e é título
                ((windice > 0) AND (wimpanalitica > 0) AND (:wtipcta = 1))) THEN -- É do nível selecionado, analítica e foi selecionado para imprimir as contas analíticas
              BEGIN
                -- Tratamento para detalhar participante
                IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (wtipcta = 1)) THEN
                  BEGIN
                    FOR SELECT tsalctapar.bdnome, tsalctapar.bdclassificacao, tsalctapar.bdcodparticipante
                        --from vsuc_sp_retorna_saldos_cta_part(:wcodemp,:wcodplapadrao,:prdatini,:prdatfin,:wcodcta,:prignzer,0,1,0, -- alt:#6647 - gilberto - 12/09/2013
                        FROM vsuc_sp_retorna_saldos_ctaparty(:wcodemp,:wcodplapadrao,:prdatini,:prdatfin,:wcodcta,:prindice,:prignzer,0,0,
                                                             :prempresas,:prcontabilizacao, 0, '', 0, 0, 0, 0, 
                :prrefemp) tsalctapar
                        INTO :wnomcta, :wctalon, :wcodparticipante DO
                        BEGIN
                          IF (prconcatenacodparticipante = 1) THEN
                            BEGIN
                              wpos     = CHARACTER_LENGTH(:wcodparticipante);
                                         -- 100 -> máximo de caracteres para nome da conta
                                         -- 03 -> qtd de caracteres " - ";
                              wpos     = ((100 - wpos) - 3);
                              wnomcta = wcodparticipante||' - '||SUBSTRING(wnomcta FROM 1 FOR wpos);
                            END

                          INSERT INTO vsuc_empresas_comparativo (bddatahora, bdcodemp, bdnomemp, bdcodmatriz, bdcnpjemp, bdcodplapadrao, bdcodcta,
                                                                 bdctalon, bdtipcta, bdgrpcta, bdnomcta, bdformula)
                          VALUES(:wdatahora, :wcodemp, :wnomemp, :wcodmatriz, :wcnpjemp, :wcodplapadrao, :wcodcta, :wctalon, :wtipcta, :wgrpcta ,:wnomcta, :wformula);
                        END
                  END
                ELSE
                  BEGIN
                    INSERT INTO vsuc_empresas_comparativo (bddatahora, bdcodemp, bdnomemp, bdcodmatriz, bdcnpjemp,
                                                           bdcodplapadrao, bdcodcta, bdctalon, bdtipcta, bdgrpcta, bdnomcta, bdformula)
                    VALUES (:wdatahora, :wcodemp, :wnomemp, :wcodmatriz, :wcnpjemp, :wcodplapadrao, :wcodcta, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wformula);
                  END
              END
          END
      END

  -- mensal ____________________________________________________________________
  IF (prtipcomp = 0) THEN
     BEGIN
       wtotal = 0;
       wdata_inicial = prdatini;
       WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatfin FROM 1 FOR 4)||SUBSTRING(prdatfin FROM 6 FOR 2) AS INTEGER)) DO
         BEGIN
           wtotal = wtotal + 1;
           wdata_inicial = addmonth(prdatini, wtotal);
         END
     END
  ELSE
  -- anual _____________________________________________________________________
     BEGIN
       wtotal = CAST(SUBSTRING(prdatfin FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdatini FROM 1 FOR 4) AS INTEGER);
       IF (wtotal = 0) THEN
          wtotal = 1;
       ELSE
          wTotal = wTotal +1;
     END

  wcount = 0;
  WHILE (wcount < wtotal) DO
    BEGIN
      -- mensal ________________________________________________________
      IF (prtipcomp = 0) THEN
         BEGIN
           wdata_inicial = addmonth(prdatini, wcount);
           wdata_final   = addmonth(prdatini, wcount+1)-1;
         END
      ELSE
      -- anual _________________________________________________________
         BEGIN
           wdata_inicial = addyear(prdatini, wcount);
           wdata_final   = addyear(prdatini, wcount+1)-1;
         END

      IF (wdata_final <= prdatfin) THEN
         BEGIN
           wsqlmeses = '';
           wsqlmeses = wsqlmeses|| ' select bdcodemp, bdnomemp, bdcnpjemp, bdcodmatriz, bdcodplapadrao, bdcodcta, bdctalon, bdnomcta, bdtipcta, bdgrpcta, bdcodtpcc, bdnomtpcc, ';
           wsqlmeses = wsqlmeses|| ' bdsaldo_atual, bdmovimento ';
           wsqlmeses = wsqlmeses|| ' from vsuc_sp_retorna_balancete(''' || :prempresas || ''', ''' || :wdata_inicial || ''', ''';
           wsqlmeses = wsqlmeses|| :wdata_final || ''', ' || :prignzer || ', ' || :prctaini || ', ' || :prctafin || ', '||:prindice||', ''' ||  :prcc || ''' , ' || :prrefemp || ', ';
           wsqlmeses = wsqlmeses|| :prlansemcc || ', 0, 0, 0,'|| :prdetalharctaparticipante || ',0, '''|| :prniveisconta ||''',0,'||:prcontabilizacao||','||:prmatrizfilialconsolidado||')';

/*
           if (prtiposaldo = 2) then
              wsqlmeses = wsqlmeses|| ' where bdsaldo_atual <> 0';
           else
              wsqlmeses = wsqlmeses|| ' where bdmovimento <> 0';*/
           ----
           FOR EXECUTE STATEMENT wsqlmeses
               INTO :wcodemp, :wnomemp, :wcnpjemp, :wcodmatriz, :wcodplapadrao,
                    :wcodcta, :wctalon, :wnomcta, :wtipcta, :wgrpcta, :wcodtpcc, :wnomtpcc,
                    :wsalatu, :wmovimento DO
           BEGIN
             --alt:7333 - Retirado o filtro, pois agora deve trazer tano o saldo quanto o movimento. Pedro
             /*if (prtiposaldo = 2) then
                wSaldoRelatorio = wsalatu;
             else
                wSaldoRelatorio = wmovimento;*/

             --alt:7333 - Adicionados campos do movimento. Pedro
             wsqlupdate = 'update vsuc_empresas_comparativo set ';
             IF (wcount = 0) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO01 = coalesce(BDSALDO01, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO01 = coalesce(BDMOVIMENTO01, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 1) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO02 = coalesce(BDSALDO02, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO02 = coalesce(BDMOVIMENTO02, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 2) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO03 = coalesce(BDSALDO03, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO03 = coalesce(BDMOVIMENTO03, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 3) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO04 = coalesce(BDSALDO04, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO04 = coalesce(BDMOVIMENTO04, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 4) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO05 = coalesce(BDSALDO05, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO05 = coalesce(BDMOVIMENTO05, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 5) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO06 = coalesce(BDSALDO06, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO06 = coalesce(BDMOVIMENTO06, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 6) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO07 = coalesce(BDSALDO07, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO07 = coalesce(BDMOVIMENTO07, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 7) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO08 = coalesce(BDSALDO08, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO08 = coalesce(BDMOVIMENTO08, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 8) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO09 = coalesce(BDSALDO09, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO09 = coalesce(BDMOVIMENTO09, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 9) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO10 = coalesce(BDSALDO10, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO10 = coalesce(BDMOVIMENTO10, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 10) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO11 = coalesce(BDSALDO11, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO11 = coalesce(BDMOVIMENTO11, 0) + '||COALESCE(wMovimento, 0);
                END
             ELSE
             IF (wcount = 11) THEN
                BEGIN
                  wSqlUpdate = wSqlUpdate||' BDSALDO12 = coalesce(BDSALDO12, 0) + '||COALESCE(wSalAtu, 0)||',';
                  wSqlUpdate = wSqlUpdate||' BDMOVIMENTO12 = coalesce(BDMOVIMENTO12, 0) + '||COALESCE(wMovimento, 0);
                END
             wSqlUpdate = wSqlUpdate||' where bdcodemp = '||wcodemp;
             wSqlUpdate = wSqlUpdate||' and bddatahora = '''||wdatahora||'''';
             wSqlUpdate = wSqlUpdate||' and bdcodcta = '||wcodcta;
             wSqlUpdate = wSqlUpdate||' and bdctalon = '''||wctalon||'''';
             IF (TRIM(prcc) <> '') THEN
                wSqlUpdate = wSqlUpdate||' and bdcodtpcc = '||wcodtpcc;

             EXECUTE STATEMENT wSqlUpdate;
           END
         END
      wcount = wcount + 1;
    END

  -- implementado para que se possa agrupar todas as filiais somando os saldos
  IF (PRAGRUPAEMPRESAFILIAIS = 1) THEN
     BEGIN
       wsql = 'select first 1 bdcodemp, bdcodmatriz, bdcnpjemp, bdnomemp, bdcodplapadrao ';
       wsql = wsql||'from vw_empresas_ref_atual ';
       wsql = wsql||'where bdcodemp in ('||prempresas||') ';
       EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodmatriz, :bdcnpjemp, :bdnomemp, :bdcodplapadrao;

       --alt:7333 - Adicionados campos do movimento. Pedro
       FOR SELECT DISTINCT  tcomp.BDCODCTA, tcomp.BDCTALON, tcomp.BDNOMCTA, tcomp.BDTIPCTA, tcomp.BDGRPCTA, COALESCE(tcomp.BDCODTPCC, 0), tcomp.BDNOMTPCC, tcomp.bdformula,
                  SUM(COALESCE(tcomp.BDSALDO01, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO01, 0)), SUM(COALESCE(tcomp.BDSALDO02, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO02, 0)),
                  SUM(COALESCE(tcomp.BDSALDO03, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO03, 0)), SUM(COALESCE(tcomp.BDSALDO04, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO04, 0)),
                  SUM(COALESCE(tcomp.BDSALDO05, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO05, 0)), SUM(COALESCE(tcomp.BDSALDO06, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO06, 0)),
                  SUM(COALESCE(tcomp.BDSALDO07, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO07, 0)), SUM(COALESCE(tcomp.BDSALDO08, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO08, 0)),
                  SUM(COALESCE(tcomp.BDSALDO09, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO09, 0)), SUM(COALESCE(tcomp.BDSALDO10, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO10, 0)),
                  SUM(COALESCE(tcomp.BDSALDO11, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO11, 0)), SUM(COALESCE(tcomp.BDSALDO12, 0)), SUM(COALESCE(tcomp.BDMOVIMENTO12, 0))
           FROM vsuc_empresas_comparativo tcomp
           WHERE  (bddatahora = :wdatahora)
           GROUP BY tcomp.BDCODCTA, tcomp.BDCTALON, tcomp.BDNOMCTA, tcomp.BDTIPCTA, tcomp.BDGRPCTA, tcomp.BDCODTPCC, tcomp.BDNOMTPCC, tcomp.bdformula
           ORDER BY tcomp.bdctalon, tcomp.bdcodtpcc
           --alt:7333 - Adicionados campos do movimento. Pedro
           INTO :BDCODCTA, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC, :bdformula,
                :BDSALDO01, :BDMOVIMENTO01, :BDSALDO02, :BDMOVIMENTO02,
                :BDSALDO03, :BDMOVIMENTO03, :BDSALDO04, :BDMOVIMENTO04,
                :BDSALDO05, :BDMOVIMENTO05, :BDSALDO06, :BDMOVIMENTO06,
                :BDSALDO07, :BDMOVIMENTO07, :BDSALDO08, :BDMOVIMENTO08,
                :BDSALDO09, :BDMOVIMENTO09, :BDSALDO10, :BDMOVIMENTO10,
                :BDSALDO11, :BDMOVIMENTO11, :BDSALDO12, :BDMOVIMENTO12 DO
           BEGIN
             BDQTDCOMP = wtotal;
             --alt:7333 - Adicionados campos do movimento. Pedro
             IF ((BDSALDO01 <> 0 OR BDSALDO02 <> 0 OR BDSALDO03 <> 0 OR BDSALDO04 <> 0 OR
                  BDSALDO05 <> 0 OR BDSALDO06 <> 0 OR BDSALDO07 <> 0 OR BDSALDO08 <> 0 OR
                  BDSALDO09 <> 0 OR BDSALDO10 <> 0 OR BDSALDO11 <> 0 OR BDSALDO12 <> 0) OR
                 (BDMOVIMENTO01 <> 0 OR BDMOVIMENTO02 <> 0 OR BDMOVIMENTO03 <> 0 OR BDMOVIMENTO04 <> 0 OR
                  BDMOVIMENTO05 <> 0 OR BDMOVIMENTO06 <> 0 OR BDMOVIMENTO07 <> 0 OR BDMOVIMENTO08 <> 0 OR
                  BDMOVIMENTO09 <> 0 OR BDMOVIMENTO10 <> 0 OR BDMOVIMENTO11 <> 0 OR BDMOVIMENTO12 <> 0) OR
                 (BDTIPCTA = 0) OR (BDFORMULA <> '')) THEN
                 SUSPEND;
           END
     END
  ELSE
  --alt:7333 - Adicionados campos do movimento. Pedro
  FOR SELECT tcomp.BDCODEMP, tcomp.BDCODMATRIZ, tcomp.BDNOMEMP, tcomp.BDCNPJEMP,
             tcomp.bdcodplapadrao, tcomp.BDCODCTA, tcomp.BDCTALON, tcomp.BDNOMCTA,
             tcomp.BDTIPCTA, tcomp.BDGRPCTA, COALESCE(tcomp.BDCODTPCC, 0), tcomp.BDNOMTPCC,
             tcomp.BDSALDO01, tcomp.BDMOVIMENTO01, tcomp.BDSALDO02, tcomp.BDMOVIMENTO02,
             tcomp.BDSALDO03, tcomp.BDMOVIMENTO03, tcomp.BDSALDO04, tcomp.BDMOVIMENTO04,
             tcomp.BDSALDO05, tcomp.BDMOVIMENTO05, tcomp.BDSALDO06, tcomp.BDMOVIMENTO06,
             tcomp.BDSALDO07, tcomp.BDMOVIMENTO07, tcomp.BDSALDO08, tcomp.BDMOVIMENTO08,
             tcomp.BDSALDO09, tcomp.BDMOVIMENTO09, tcomp.BDSALDO10, tcomp.BDMOVIMENTO10,
             tcomp.BDSALDO11, tcomp.BDMOVIMENTO11, tcomp.BDSALDO12, tcomp.BDMOVIMENTO12, tcomp.bdformula
      FROM vsuc_empresas_comparativo tcomp
      WHERE  (bddatahora = :wdatahora)
      --alt:7333 - Adicionados campos do movimento. Pedro
      ORDER BY tcomp.bdcodemp, tcomp.bdcodmatriz, tcomp.bdctalon, tcomp.bdcodtpcc
      INTO :BDCODEMP, :bdcodmatriz, :BDNOMEMP, :BDCNPJEMP, :bdcodplapadrao,
           :BDCODCTA, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC,
           :BDSALDO01, :BDMOVIMENTO01, :BDSALDO02, :BDMOVIMENTO02,
           :BDSALDO03, :BDMOVIMENTO03, :BDSALDO04, :BDMOVIMENTO04,
           :BDSALDO05, :BDMOVIMENTO05, :BDSALDO06, :BDMOVIMENTO06,
           :BDSALDO07, :BDMOVIMENTO07, :BDSALDO08, :BDMOVIMENTO08,
           :BDSALDO09, :BDMOVIMENTO09, :BDSALDO10, :BDMOVIMENTO10,
           :BDSALDO11, :BDMOVIMENTO11, :BDSALDO12, :BDMOVIMENTO12, :bdformula DO
      BEGIN
        BDQTDCOMP = wtotal;
        SUSPEND;
      END

  --Não utiliza mais o "vsuc_empresas_tbalancete", mas sim o "vsuc_empresas_tbalancete_2"
  --delete from vsuc_empresas_tbalancete;
  DELETE FROM vsuc_empresas_comparativo WHERE bdcodemp <> 0 AND bddatahora = :wdatahora;
END
^

--#alt:20462. Criada nova SP para melhorar o desempenho. A antiga permanecerá para caso houver lentidões ou erros futuros. Ana - 11/05/2018
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_COMPARATIVO_Y (
    PRCODEMP VARCHAR(2048),
    PRCTAINI INTEGER,
    PRCTAFIN INTEGER,
    PRDATAINI DATE,
    PRDATAFIN DATE,
    PRINDICE INTEGER,
    PRCTASEMMOV INTEGER,
    PRTIPCOMP INTEGER,
    PRCODTPCC VARCHAR(32000),
    PRTIPOSALDO INTEGER,
    PRREFEMP INTEGER,
    PRIGNZER INTEGER,
    PRLANSEMCC INTEGER,
    PRAGRUPAEMPRESAFILIAIS INTEGER,
    PRDETALHARCTAPARTICIPANTE INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRCTACONSOLIDADA INTEGER,
    PRAGRUPARPORCNPJ INTEGER = 0,
    PRAGRUPARPORCPF INTEGER = 0,
    PRTODASCTAS integer = 0)
returns (
    BDCODEMP integer,
    BDCODEMPFILIAL integer,
    BDNOMEMP varchar(100),
    BDCODMATRIZ integer,
    BDCNPJEMP varchar(18),
    BDCODPLAPADRAO integer,
    BDCODCTA integer,
    BDCTALON varchar(50),
    BDNOMCTA varchar(100),
    BDCLANOM varchar(150),
    BDTIPCTA integer,
    BDGRPCTA integer,
    BDCODTPCC integer,
    BDNOMTPCC varchar(40),
    BDQTDCOMP integer,
    BDFORMULA varchar(1024),
    BDSALDO01 numeric(15,2),
    BDMOVIMENTO01 numeric(15,2),
    BDSALDOREAL01 numeric(15,2),
    BDSALDO02 numeric(15,2),
    BDMOVIMENTO02 numeric(15,2),
    BDSALDOREAL02 numeric(15,2),
    BDSALDO03 numeric(15,2),
    BDMOVIMENTO03 numeric(15,2),
    BDSALDOREAL03 numeric(15,2),
    BDSALDO04 numeric(15,2),
    BDMOVIMENTO04 numeric(15,2),
    BDSALDOREAL04 numeric(15,2),
    BDSALDO05 numeric(15,2),
    BDMOVIMENTO05 numeric(15,2),
    BDSALDOREAL05 numeric(15,2),
    BDSALDO06 numeric(15,2),
    BDMOVIMENTO06 numeric(15,2),
    BDSALDOREAL06 numeric(15,2),
    BDSALDO07 numeric(15,2),
    BDMOVIMENTO07 numeric(15,2),
    BDSALDOREAL07 numeric(15,2),
    BDSALDO08 numeric(15,2),
    BDMOVIMENTO08 numeric(15,2),
    BDSALDOREAL08 numeric(15,2),
    BDSALDO09 numeric(15,2),
    BDMOVIMENTO09 numeric(15,2),
    BDSALDOREAL09 numeric(15,2),
    BDSALDO10 numeric(15,2),
    BDMOVIMENTO10 numeric(15,2),
    BDSALDOREAL10 numeric(15,2),
    BDSALDO11 numeric(15,2),
    BDMOVIMENTO11 numeric(15,2),
    BDSALDOREAL11 numeric(15,2),
    BDSALDO12 numeric(15,2),
    BDMOVIMENTO12 numeric(15,2),
    BDSALDOREAL12 numeric(15,2),
    BDMEDIASALDO numeric(15,2),
    BDTOTALSALDO numeric(15,2),
    BDMEDIAMOVIMENTO numeric(15,2),
    BDTOTALMOVIMENTO numeric(15,2))
as
declare variable WSQL varchar(24000);
declare variable WCOUNT integer;
declare variable WCOUNTSQL integer;
declare variable WNUMEROSALDO varchar(3);
declare variable WTOTAL integer;
declare variable WDATA_INICIAL date;
declare variable WDATA_FINAL date;
declare variable WCODEMP integer;
declare variable WNOMEMP varchar(100);
declare variable WCNPJEMP varchar(18);
declare variable WPOS integer;
declare variable WDATINI_TRIM date;
BEGIN
  -- Caso seja para agrupar as empresas eu busco o c??digo, nome e CNPJ separadamente
  IF (pragrupaempresafiliais = 1) THEN
    BEGIN
      wpos = POSITION(',', :prcodemp);
      IF (wpos <> 0) THEN
        wcodemp = COALESCE(CAST(SUBSTRING(prcodemp FROM 1 FOR (wpos -1)) AS INTEGER),0);
      ELSE
        wcodemp = COALESCE(CAST(:prcodemp AS INTEGER),0);

      SELECT emp.bdcodemp,emp.bdcnpjemp,ref.bdnomemp  FROM tempresas emp
      INNER JOIN vw_empresas_ref_atual ref ON (ref.bdcodemp = emp.bdcodemp)
      WHERE (emp.bdcodemp = :wcodemp) INTO :wcodemp, :wcnpjemp, :wnomemp;
    END

  -- mensal ____________________________________________________________________
  IF (prtipcomp = 0) THEN
     BEGIN
       wtotal = 0;
       wdata_inicial = prdataini;
       WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatafin FROM 1 FOR 4)||SUBSTRING(prdatafin FROM 6 FOR 2) AS INTEGER)) DO
         BEGIN
           wtotal = wtotal + 1;
           wdata_inicial = addmonth(prdataini, wtotal);
         END
     END
  ELSE
  -- trimestral ________________________________________________________________ Carlos Machado - 09/11/2018 - #alt:69974
  IF (prtipcomp = 1) THEN
    BEGIN
      --Calcula trimestres (mes - 1)/3 + 1 = (1..3, 4..6, 7..9, 10..12) - 1 divint 3 + 1
      wcount = (CAST(SUBSTRING(prdataini FROM 6 FOR 2) AS INTEGER) - 1) / 3 + 1;
      wtotal = (CAST(SUBSTRING(prdatafin FROM 6 FOR 2) AS INTEGER) - 1) / 3 + 1;

      --Calcula quantidade de trimestres baseado no mes
      wtotal = wtotal - wcount + 1;
      --Calcula quantidade de trimestres baseado no ano (4 por ano)
      wtotal = wtotal + (CAST(SUBSTRING(prdatafin FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdataini FROM 1 FOR 4) AS INTEGER)) * 4;
      WDATINI_TRIM = PRDATAINI;

      wcount = (CAST(SUBSTRING(prdataini FROM 6 FOR 2) AS INTEGER) - 1);
     --Diz qual a data inicial do trimestre
      WDATINI_TRIM = ADDMONTH(WDATINI_TRIM, - MOD(wcount, 3));
    END
  ELSE
  -- anual _____________________________________________________________________
     BEGIN
       wtotal = CAST(SUBSTRING(prdatafin FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdataini FROM 1 FOR 4) AS INTEGER);
       IF (wtotal = 0) THEN
          wtotal = 1;
       ELSE
          wTotal = wTotal +1;
     END

  wcount = 0;
  WHILE (wcount < wtotal) DO
    BEGIN
      -- mensal ________________________________________________________
      IF (prtipcomp = 0) THEN
        BEGIN
          wdata_inicial = addmonth(prdataini, wcount);
          wdata_final   = addmonth(prdataini, wcount + 1) - 1;
        END
      ELSE
      -- trimestral ____________________________________________________ Carlos Machado - 09/11/2018 - #alt:69974
      IF (prtipcomp = 1) THEN     
        BEGIN
          wdata_inicial = addmonth(WDATINI_TRIM, wcount * 3);
          if (PRDATAINI > WDATA_INICIAL) then
            WDATA_INICIAL = PRDATAINI;
          wdata_final   = addmonth(WDATINI_TRIM, wcount * 3 + 3) - 1;
          if (PRDATAFIN < WDATA_FINAL) then
            WDATA_FINAL = PRDATAFIN;
        END
      ELSE
      -- anual _________________________________________________________
        BEGIN
          wdata_inicial = addyear(prdataini, wcount);
          wdata_final   = addyear(prdataini, wcount + 1) - 1;
        END


      IF (pragrupaempresafiliais = 1) THEN
        wsql = 'Select null as BDCODEMP, BDCODPLAPADRAO, BDCODCTA, null as BDCODMATRIZ, null as BDNOMEMP, null as BDCNPJEMP, BDCTALON, BDNOMCTA, BDCLANOM, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,null as BDCODEMPFILIAL ';
      ELSE
        wsql = 'Select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDCLANOM, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL ';

      wCountSQL = 1;
      --sempre deve executar 12 vezes por causa dos campos
      WHILE (wCountSQL <= 12) DO
        BEGIN
          IF (wCountSQL <= 9) THEN
            wNumeroSaldo = '0'||wCountSQL;
          ELSE
            wNumeroSaldo = wCountSQL;

          IF (wCountSQL = (wcount + 1)) THEN
            wsql = wsql||' ,bdsaldo_atual as BDSALDO'||wNumeroSaldo||', bdmovimento as BDMOVIMENTO'||wNumeroSaldo||', BDSALDO_ATUAL_REAL as BDSALDOREAL'||wNumeroSaldo||' ';
          ELSE
            wsql = wsql||' ,null as BDSALDO'||wNumeroSaldo||', null as BDMOVIMENTO'||wNumeroSaldo||', null as BDSALDOREAL'||wNumeroSaldo||' ';

          wCountSQL = wCountSQL + 1;
        END

      wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
      wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', '||pragruparporcnpj||'';
      wsql = wsql||', 0, '''||prniveisconta||''', '||prCtaSemMov||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||',0, '||prtodasctas||',0,0,0,0,'||pragruparporcpf||',0,'||(iif(wcount = 0, '0', '1'))||')';
           
      IF ((prCtaSemMov = 0) and (prtodasctas = 0)) THEN
        BEGIN
          IF (prTipoSaldo = 0) THEN
            wsql = wSQL||' where (coalesce(BDMOVIMENTO, 0) <> 0) ';
          ELSE
          IF (prTipoSaldo = 1) THEN
            wsql = wSQL||' where (coalesce(BDSALDO_ATUAL, 0) <> 0) or (coalesce(BDSALDO_ATUAL_REAL, 0) <> 0) ';
          ELSE
          IF (prTipoSaldo = 2) THEN
            wsql = wSQL||' where (((coalesce(BDSALDO_ATUAL, 0) <> 0) or (coalesce(BDSALDO_ATUAL_REAL, 0) <> 0)) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1))';

          wsql = wSQL||' or (bdsaldo_deb <> 0 or bdsaldo_cre <> 0 or ((BDSALDO_ANT_DEB <> 0 or BDSALDO_ANT_cre <> 0) and (BDSALDO_ANT_DEB <> BDSALDO_ANT_cre)))';
          wsql = wSQL||' or (BDFORMULA <> '''||''||''')';
        END



      wcount = wcount + 1;

      FOR EXECUTE STATEMENT wsql INTO
        :BDCODEMP, :BDCODPLAPADRAO, :BDCODCTA, :BDCODMATRIZ, :BDNOMEMP, :BDCNPJEMP, :BDCTALON, :BDNOMCTA, :BDCLANOM, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC, :BDFORMULA, :BDCODEMPFILIAL,
        :BDSALDO01, :BDMOVIMENTO01, :BDSALDOREAL01, :BDSALDO02, :BDMOVIMENTO02, :BDSALDOREAL02, :BDSALDO03, :BDMOVIMENTO03, :BDSALDOREAL03,
        :BDSALDO04, :BDMOVIMENTO04, :BDSALDOREAL04, :BDSALDO05, :BDMOVIMENTO05, :BDSALDOREAL05, :BDSALDO06, :BDMOVIMENTO06, :BDSALDOREAL06,
        :BDSALDO07, :BDMOVIMENTO07, :BDSALDOREAL07, :BDSALDO08, :BDMOVIMENTO08, :BDSALDOREAL08, :BDSALDO09, :BDMOVIMENTO09, :BDSALDOREAL09,
        :BDSALDO10, :BDMOVIMENTO10, :BDSALDOREAL10, :BDSALDO11, :BDMOVIMENTO11, :BDSALDOREAL11, :BDSALDO12, :BDMOVIMENTO12, :BDSALDOREAL12 DO
      BEGIN
        IF (pragrupaempresafiliais = 1) THEN
          BEGIN
            bdcodemp       = wcodemp;
            bdcnpjemp      = wcnpjemp;
            bdnomemp       = wnomemp;
            bdcodempfilial = bdcodemp;
          END
    
        BDQTDCOMP = wtotal;
    
        SUSPEND;
      END
    END
END
^
--#alt:20462.

/* Restore proc. body: VSUC_SP_RETORNA_COMPARATIVO_X */
create or alter procedure VSUC_SP_RETORNA_COMPARATIVO_X (
    PRCODEMP varchar(2048),
    PRCTAINI integer,
    PRCTAFIN integer,
    PRDATAINI date,
    PRDATAFIN date,
    PRINDICE integer,
    PRCTASEMMOV integer,
    PRIMPRIMIRCOLUNASEXTRAS integer,
    PRTIPCOMP integer,
    PRCODTPCC varchar(32000),
    PRTIPOSALDO integer,
    PRREFEMP integer,
    PRIGNZER integer,
    PRLANSEMCC integer,
    PRAGRUPAEMPRESAFILIAIS integer,
    PRDETALHARCTAPARTICIPANTE integer,
    PRCONCATENACODPARTICIPANTE integer,
    PRNIVEISCONTA varchar(50),
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRCTACONSOLIDADA integer,
    PRFORMACALC integer = 0,
    PRAGRUPARPORCNPJ integer = 0,
    PRAGRUPARPORCPF integer = 0,
    PRTODASCTAS integer = 0)
returns (
    BDCODEMP integer,
    BDCODEMPFILIAL integer,
    BDNOMEMP varchar(100),
    BDCODMATRIZ integer,
    BDCNPJEMP varchar(18),
    BDCODPLAPADRAO integer,
    BDCODCTA integer,
    BDCTALON varchar(50),
    BDNOMCTA varchar(100),
    BDCLANOM varchar(150),
    BDTIPCTA integer,
    BDGRPCTA integer,
    BDCODTPCC integer,
    BDNOMTPCC varchar(40),
    BDQTDCOMP integer,
    BDFORMULA varchar(1024),
    BDSALDO01 numeric(15,2),
    BDMOVIMENTO01 numeric(15,2),
    BDSALDOREAL01 numeric(15,2),
    BDSALDO02 numeric(15,2),
    BDMOVIMENTO02 numeric(15,2),
    BDSALDOREAL02 numeric(15,2),
    BDSALDO03 numeric(15,2),
    BDMOVIMENTO03 numeric(15,2),
    BDSALDOREAL03 numeric(15,2),
    BDSALDO04 numeric(15,2),
    BDMOVIMENTO04 numeric(15,2),
    BDSALDOREAL04 numeric(15,2),
    BDSALDO05 numeric(15,2),
    BDMOVIMENTO05 numeric(15,2),
    BDSALDOREAL05 numeric(15,2),
    BDSALDO06 numeric(15,2),
    BDMOVIMENTO06 numeric(15,2),
    BDSALDOREAL06 numeric(15,2),
    BDSALDO07 numeric(15,2),
    BDMOVIMENTO07 numeric(15,2),
    BDSALDOREAL07 numeric(15,2),
    BDSALDO08 numeric(15,2),
    BDMOVIMENTO08 numeric(15,2),
    BDSALDOREAL08 numeric(15,2),
    BDSALDO09 numeric(15,2),
    BDMOVIMENTO09 numeric(15,2),
    BDSALDOREAL09 numeric(15,2),
    BDSALDO10 numeric(15,2),
    BDMOVIMENTO10 numeric(15,2),
    BDSALDOREAL10 numeric(15,2),
    BDSALDO11 numeric(15,2),
    BDMOVIMENTO11 numeric(15,2),
    BDSALDOREAL11 numeric(15,2),
    BDSALDO12 numeric(15,2),
    BDMOVIMENTO12 numeric(15,2),
    BDSALDOREAL12 numeric(15,2),
    BDMEDIASALDO numeric(15,2),
    BDTOTALSALDO numeric(15,2),
    BDMEDIAMOVIMENTO numeric(15,2),
    BDTOTALMOVIMENTO numeric(15,2))
as
declare variable WSQL varchar(24000);
declare variable WCOUNT integer;
declare variable WTOTAL integer;
declare variable WDATA_INICIAL date;
declare variable WDATA_FINAL date;
declare variable WCODEMP integer;
declare variable WNOMEMP varchar(100);
declare variable WCNPJEMP varchar(18);
declare variable WPOS integer;
BEGIN
  --#alt:20462. Criada nova SP para melhorar o desempenho. A antiga permanecer?? para caso houver lentid??es ou erros futuros. Ana - 08/05/2018
  --#alt:69974 - Carlos Machado - 09/11/2018 - Alterado apenas na nova rotina: Tratamento para comparativo trimestral
  IF (PRFORMACALC = 1) THEN
   BEGIN
     FOR SELECT BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA, BDCODEMPFILIAL,
                BDSALDO01, BDMOVIMENTO01, BDSALDOREAL01, BDSALDO02, BDMOVIMENTO02, BDSALDOREAL02, BDSALDO03, BDMOVIMENTO03, BDSALDOREAL03,
                BDSALDO04, BDMOVIMENTO04, BDSALDOREAL04, BDSALDO05, BDMOVIMENTO05, BDSALDOREAL05, BDSALDO06, BDMOVIMENTO06, BDSALDOREAL06,
                BDSALDO07, BDMOVIMENTO07, BDSALDOREAL07, BDSALDO08, BDMOVIMENTO08, BDSALDOREAL08, BDSALDO09, BDMOVIMENTO09, BDSALDOREAL09,
                BDSALDO10, BDMOVIMENTO10, BDSALDOREAL10, BDSALDO11, BDMOVIMENTO11, BDSALDOREAL11, BDSALDO12, BDMOVIMENTO12, BDSALDOREAL12,
                BDQTDCOMP, BDCLANOM
         FROM VSUC_SP_RETORNA_COMPARATIVO_Y(:prcodemp, :prctaini, :prctafin, :prdataini, :prdatafin, :prindice, :prctasemmov, :prtipcomp, :prcodtpcc, :prtiposaldo, :prrefemp, :prignzer,
                                            :prlansemcc, :pragrupaempresafiliais, :prdetalharctaparticipante, :prniveisconta, :prcontabilizacao, :prmatrizfilialconsolidado,
                                            :prctaconsolidada, :pragruparporcnpj, :pragruparporcpf, :prtodasctas)

      INTO
      :BDCODEMP, :BDCODPLAPADRAO, :BDCODCTA, :BDCODMATRIZ, :BDNOMEMP, :BDCNPJEMP, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC, :BDFORMULA, :BDCODEMPFILIAL,
      :BDSALDO01, :BDMOVIMENTO01, :BDSALDOREAL01, :BDSALDO02, :BDMOVIMENTO02, :BDSALDOREAL02, :BDSALDO03, :BDMOVIMENTO03, :BDSALDOREAL03,
      :BDSALDO04, :BDMOVIMENTO04, :BDSALDOREAL04, :BDSALDO05, :BDMOVIMENTO05, :BDSALDOREAL05, :BDSALDO06, :BDMOVIMENTO06, :BDSALDOREAL06,
      :BDSALDO07, :BDMOVIMENTO07, :BDSALDOREAL07, :BDSALDO08, :BDMOVIMENTO08, :BDSALDOREAL08, :BDSALDO09, :BDMOVIMENTO09, :BDSALDOREAL09,
      :BDSALDO10, :BDMOVIMENTO10, :BDSALDOREAL10, :BDSALDO11, :BDMOVIMENTO11, :BDSALDOREAL11, :BDSALDO12, :BDMOVIMENTO12, :BDSALDOREAL12,
      :BDQTDCOMP, :BDCLANOM DO
        SUSPEND;

   END
  ELSE
  BEGIN
      -- Caso seja para agrupar as empresas eu busco o c??digo, nome e CNPJ separadamente
      IF (pragrupaempresafiliais = 1) THEN
        BEGIN
          wpos = POSITION(',', :prcodemp);
          IF (wpos <> 0) THEN
            wcodemp = COALESCE(CAST(SUBSTRING(prcodemp FROM 1 FOR (wpos -1)) AS INTEGER),0);
          ELSE
            wcodemp = COALESCE(CAST(:prcodemp AS INTEGER),0);
    
          SELECT emp.bdcodemp,emp.bdcnpjemp,ref.bdnomemp  FROM tempresas emp
          INNER JOIN vw_empresas_ref_atual ref ON (ref.bdcodemp = emp.bdcodemp)
          WHERE (emp.bdcodemp = :wcodemp) INTO :wcodemp, :wcnpjemp, :wnomemp;
        END
    
      -- mensal ____________________________________________________________________
      IF (prtipcomp = 0) THEN
         BEGIN
           wtotal = 0;
           wdata_inicial = prdataini;
           WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatafin FROM 1 FOR 4)||SUBSTRING(prdatafin FROM 6 FOR 2) AS INTEGER)) DO
             BEGIN
               wtotal = wtotal + 1;
               wdata_inicial = addmonth(prdataini, wtotal);
             END
         END
      ELSE
      -- anual _____________________________________________________________________
         BEGIN
           wtotal = CAST(SUBSTRING(prdatafin FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdataini FROM 1 FOR 4) AS INTEGER);
           IF (wtotal = 0) THEN
              wtotal = 1;
           ELSE
              wTotal = wTotal +1;
         END
    
      wcount = 0;
      WHILE (wcount < wtotal) DO
        BEGIN
          -- mensal ________________________________________________________
          IF (prtipcomp = 0) THEN
             BEGIN
               wdata_inicial = addmonth(prdataini, wcount);
               wdata_final   = addmonth(prdataini, wcount + 1) - 1;
             END
          ELSE
          -- anual _________________________________________________________
             BEGIN
               wdata_inicial = addyear(prdataini, wcount);
               wdata_final   = addyear(prdataini, wcount + 1) - 1;
             END
    
          IF (wsql IS NULL) THEN
             BEGIN
               IF (pragrupaempresafiliais = 1) THEN
                 wsql = 'Select null as BDCODEMP, BDCODPLAPADRAO, BDCODCTA, null as BDCODMATRIZ, null as BDNOMEMP, null as BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,null as BDCODEMPFILIAL,';
               ELSE
                 wsql = 'Select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
    
               wsql = wsql||' sum(coalesce(BDSALDO01, 0)) as BDSALDO01, sum(coalesce(BDMOVIMENTO01, 0)) as BDMOVIMENTO01, sum(coalesce(BDSALDO02, 0)) as BDSALDO02, sum(coalesce(BDMOVIMENTO02, 0)) as BDMOVIMENTO02,';
               wsql = wsql||' sum(coalesce(BDSALDO03, 0)) as BDSALDO03, sum(coalesce(BDMOVIMENTO03, 0)) as BDMOVIMENTO03, sum(coalesce(BDSALDO04, 0)) as BDSALDO04, sum(coalesce(BDMOVIMENTO04, 0)) as BDMOVIMENTO04,';
               wsql = wsql||' sum(coalesce(BDSALDO05, 0)) as BDSALDO05, sum(coalesce(BDMOVIMENTO05, 0)) as BDMOVIMENTO05, sum(coalesce(BDSALDO06, 0)) as BDSALDO06, sum(coalesce(BDMOVIMENTO06, 0)) as BDMOVIMENTO06,';
               wsql = wsql||' sum(coalesce(BDSALDO07, 0)) as BDSALDO07, sum(coalesce(BDMOVIMENTO07, 0)) as BDMOVIMENTO07, sum(coalesce(BDSALDO08, 0)) as BDSALDO08, sum(coalesce(BDMOVIMENTO08, 0)) as BDMOVIMENTO08,';
               wsql = wsql||' sum(coalesce(BDSALDO09, 0)) as BDSALDO09, sum(coalesce(BDMOVIMENTO09, 0)) as BDMOVIMENTO09, sum(coalesce(BDSALDO10, 0)) as BDSALDO10, sum(coalesce(BDMOVIMENTO10, 0)) as BDMOVIMENTO10,';
               wsql = wsql||' sum(coalesce(BDSALDO11, 0)) as BDSALDO11, sum(coalesce(BDMOVIMENTO11, 0)) as BDMOVIMENTO11, sum(coalesce(BDSALDO12, 0)) as BDSALDO12, sum(coalesce(BDMOVIMENTO12, 0)) as BDMOVIMENTO12';
               wsql = wsql||' from (';
             END
          ELSE
             wsql = wsql||' union all ';
    
          IF (wcount = 0) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' bdsaldo_atual as BDSALDO01, bdmovimento as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||prCtaSemMov||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||',0, '||prtodasctas||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
          ELSE
          IF (wcount = 1) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, bdsaldo_atual as BDSALDO02, bdmovimento as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||prCtaSemMov||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||',0, '||prtodasctas||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE  
           IF (wcount = 2) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' bdsaldo_atual as BDSALDO03, bdmovimento as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||prCtaSemMov||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||',0, '||prtodasctas||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 3) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, bdsaldo_atual as BDSALDO04, bdmovimento as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||prCtaSemMov||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||',0, '||prtodasctas||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 4) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' bdsaldo_atual as BDSALDO05, bdmovimento as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||prCtaSemMov||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||',0, '||prtodasctas||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 5) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, bdsaldo_atual as BDSALDO06, bdmovimento as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||prCtaSemMov||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||',0, '||prtodasctas||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 6) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' bdsaldo_atual as BDSALDO07, bdmovimento as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||prCtaSemMov||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||',0, '||prtodasctas||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 7) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, bdsaldo_atual as BDSALDO08, bdmovimento as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||prCtaSemMov||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||',0, '||prtodasctas||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 8) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' bdsaldo_atual as BDSALDO09, bdmovimento as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||prCtaSemMov||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||',0, '||prtodasctas||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 9) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, bdsaldo_atual as BDSALDO10, bdmovimento as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||prCtaSemMov||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||',0, '||prtodasctas||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 10) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' bdsaldo_atual as BDSALDO11, bdmovimento as BDMOVIMENTO11, null as BDSALDO12, null as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||prCtaSemMov||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||',0, '||prtodasctas||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
           ELSE
           IF (wcount = 11) THEN
             BEGIN
               wsql = wsql||' select BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA,BDCODEMPFILIAL,';
               wsql = wsql||' null as BDSALDO01, null as BDMOVIMENTO01, null as BDSALDO02, null as BDMOVIMENTO02,';
               wsql = wsql||' null as BDSALDO03, null as BDMOVIMENTO03, null as BDSALDO04, null as BDMOVIMENTO04,';
               wsql = wsql||' null as BDSALDO05, null as BDMOVIMENTO05, null as BDSALDO06, null as BDMOVIMENTO06,';
               wsql = wsql||' null as BDSALDO07, null as BDMOVIMENTO07, null as BDSALDO08, null as BDMOVIMENTO08,';
               wsql = wsql||' null as BDSALDO09, null as BDMOVIMENTO09, null as BDSALDO10, null as BDMOVIMENTO10,';
               wsql = wsql||' null as BDSALDO11, null as BDMOVIMENTO11, bdsaldo_atual as BDSALDO12, bdmovimento as BDMOVIMENTO12';
               wsql = wsql||' from vsuc_sp_retorna_balancete('''||prcodemp||''', '''||wdata_inicial||''', '''||wdata_final||''', '||prignzer||', ';
               wsql = wsql||prctaini||', '||prctafin||', '||:prindice||', '''||prcodtpcc||''', '||prrefemp||', '||prlansemcc||', 0, 0,'||prctaconsolidada||', '||prdetalharctaparticipante||', 0';
               wsql = wsql||', 0, '''||prniveisconta||''', '||prCtaSemMov||', '||prcontabilizacao||', '||prmatrizfilialconsolidado||',0, '||prtodasctas||')';
               
               IF (prCtaSemMov = 0) THEN
                  BEGIN
                    IF (prTipoSaldo = 0) THEN
                       wsql = wSQL||' where coalesce(BDMOVIMENTO, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 1) THEN
                       wsql = wSQL||' where coalesce(BDSALDO_ATUAL, 0) <> 0 or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                    ELSE
                    IF (prTipoSaldo = 2) THEN
                       wsql = wSQL||' where ((coalesce(BDSALDO_ATUAL, 0) <> 0) and (BDGRPCTA < 2)) or ((coalesce(BDMOVIMENTO, 0) <> 0) and (BDGRPCTA > 1)) or (BDTIPCTA = 0) or (BDFORMULA <> '''||''||''')';
                  END
             END
    
          wcount = wcount + 1;
        END
    
      wsql = wsql||' ) group by BDCODEMP, BDCODPLAPADRAO, BDCODCTA, BDNOMEMP, BDCODMATRIZ, BDCNPJEMP, BDCTALON, BDNOMCTA, BDTIPCTA, BDGRPCTA, BDCODTPCC, BDNOMTPCC, BDFORMULA, BDCODEMPFILIAL';
    
      FOR EXECUTE STATEMENT wsql INTO
          :BDCODEMP, :BDCODPLAPADRAO, :BDCODCTA, :BDCODMATRIZ, :BDNOMEMP, :BDCNPJEMP, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDGRPCTA, :BDCODTPCC, :BDNOMTPCC, :BDFORMULA, :BDCODEMPFILIAL,
          :BDSALDO01, :BDMOVIMENTO01, :BDSALDO02, :BDMOVIMENTO02, :BDSALDO03, :BDMOVIMENTO03, :BDSALDO04, :BDMOVIMENTO04,
          :BDSALDO05, :BDMOVIMENTO05, :BDSALDO06, :BDMOVIMENTO06, :BDSALDO07, :BDMOVIMENTO07, :BDSALDO08, :BDMOVIMENTO08,
          :BDSALDO09, :BDMOVIMENTO09, :BDSALDO10, :BDMOVIMENTO10, :BDSALDO11, :BDMOVIMENTO11, :BDSALDO12, :BDMOVIMENTO12 DO
        BEGIN
          IF (pragrupaempresafiliais = 1) THEN
            BEGIN
              bdcodemp       = wcodemp;
              bdcnpjemp      = wcnpjemp;
              bdnomemp       = wnomemp;
              bdcodempfilial = bdcodemp;
            END
    
          BDQTDCOMP = wtotal;
    
          IF ((PRFORMACALC = 0) AND (PRIMPRIMIRCOLUNASEXTRAS = 1)) THEN
             BEGIN
               BDTOTALSALDO = (COALESCE(BDSALDO01, 0) + COALESCE(BDSALDO02, 0) + COALESCE(BDSALDO03, 0) + COALESCE(BDSALDO04, 0) + COALESCE(BDSALDO05, 0) + COALESCE(BDSALDO06, 0) +
                               COALESCE(BDSALDO07, 0) + COALESCE(BDSALDO08, 0) + COALESCE(BDSALDO09, 0) + COALESCE(BDSALDO10, 0) + COALESCE(BDSALDO11, 0) + COALESCE(BDSALDO12, 0));
               BDMEDIASALDO = BDTOTALSALDO / wtotal;
    
               BDTOTALMOVIMENTO = (COALESCE(BDMOVIMENTO01, 0) + COALESCE(BDMOVIMENTO02, 0) + COALESCE(BDMOVIMENTO03, 0) + COALESCE(BDMOVIMENTO04, 0) +
                                   COALESCE(BDMOVIMENTO05, 0) + COALESCE(BDMOVIMENTO06, 0) + COALESCE(BDMOVIMENTO07, 0) + COALESCE(BDMOVIMENTO08, 0) +
                                   COALESCE(BDMOVIMENTO09, 0) + COALESCE(BDMOVIMENTO10, 0) + COALESCE(BDMOVIMENTO11, 0) + COALESCE(BDMOVIMENTO12, 0));
               BDMEDIAMOVIMENTO = BDTOTALMOVIMENTO / wtotal;
             END
    
          SUSPEND;
        END
  END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_CONTAS_USADAS */
ALTER PROCEDURE VSUC_SP_RETORNA_CONTAS_USADAS(PREMPRESAS VARCHAR(1024),
PRCODPLAPADRAO INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRTITULOS INTEGER,
PRORCAMENTO INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRTIPOCONCILIACAO INTEGER,
PRTODASASCONTAS INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODTPLA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDAPECTA VARCHAR(20),
BDTIPCTA SMALLINT,
BDRELCTA INTEGER,
BDINVERTESINAL VARCHAR(5),
BDFILTROGER VARCHAR(20),
BDCLANOM VARCHAR(140),
BDFORMULA VARCHAR(200),
BDCONDICAO VARCHAR(100),
BDCONCILIAAUTOMATICA VARCHAR(5),
BDGRUPOCTA INTEGER,
BDPARTICIPANTE INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WANOINI INTEGER;
DECLARE VARIABLE WANOFIM INTEGER;
BEGIN
 /* Criado giovanni */

  --bdcodemp = prempresas;  alt:7211 - Alterado de wcodemp para prempresas para passar a empresa matriz e suas filiais, caso sejam informadas. Pedro
  wsql = 'select first 1 case when (bdcodmatriz is not null) then bdcodmatriz else bdcodemp end ';
  wsql = wsql||' from tempresas where bdcodemp in ('||prempresas||')';
  EXECUTE STATEMENT wsql INTO :bdcodemp;

  /* adiciona contas a debito */
  wanoini = EXTRACT(YEAR FROM prdataini);
  wanofim = EXTRACT(YEAR FROM prdatafim);

  IF ((prtodasascontas IS NOT NULL) AND (prtodasascontas <> 0)) THEN
    BEGIN
      wsql = '';
      wSql = ' select tpla.BDCODTPLA, tpla.BDCODPLAPADRAO, tpla.bdctalon, tpla.bdnomcta,  tpla.bdapecta, tpla.BDTIPCTA, tpla.BDRELCTA,  tpla.BDINVERTESINAL, tpla.BDFILTROGER, ';
      wsql = wsql||' tpla.BDCLANOM,  tpla.BDFORMULA,  tpla.BDCONDICAO,  tpla.BDCONCILIAAUTOMATICA, tpla.BDGRUPOCTA, tpla.bdparticipante ';
      wsql = wsql||' from planos_tpla tpla ';
      wsql = wsql||' where tpla.BDCODPLAPADRAO = ' || prcodplapadrao ;

      FOR EXECUTE STATEMENT wsql INTO :bdcodtpla, :bdcodplapadrao, :bdctalon, :bdnomcta, :bdapecta, :bdtipcta, :bdrelcta, :bdinvertesinal, :bdfiltroger,
                            :bdclanom, :bdformula, :bdcondicao, :bdconciliaautomatica, :bdgrupocta, :bdparticipante DO
        BEGIN
          SUSPEND;
        END

      EXIT;
    END

  IF (prorcamento <> 1) THEN
     BEGIN
       wsql = 'select tlan.BDDEBITO , ';
       wsql = wsql||' tpla.BDCODPLAPADRAO, tpla.bdctalon, tpla.bdnomcta, ';
       wsql = wsql||' tpla.bdapecta, tpla.BDTIPCTA, tpla.BDRELCTA, ';
       wsql = wsql||' tpla.BDINVERTESINAL, tpla.BDFILTROGER, tpla.BDCLANOM, ';
       wsql = wsql||' tpla.BDFORMULA,  tpla.BDCONDICAO, ';
       wsql = wsql||' tpla.BDCONCILIAAUTOMATICA, tpla.BDGRUPOCTA, tpla.bdparticipante ';
       wsql = wsql||'from (select x.BDDEBITO, x.bdcodplapadrao, x.bdcodemp';
       wsql = wsql||'      from vsuc_empresas_tlan x ';

       --alt:7211 - Alterado de "bdcodemp = prempresas" para bdcodemp in (prempresas) para selecionar a empresa matriz e suas filiais, caso sejam informadas. Pedro
       --wsql = wsql||'      where x.bddebito is not null and x.bdcodemp = '||prempresas||' and x.bdcodplapadrao = '||prcodplapadrao;
       wsql = wsql||'      where x.bddebito is not null and x.bdcodemp in ('||prempresas||') and x.bdcodplapadrao = '||prcodplapadrao;
       IF (PRDATAINI IS NOT NULL) THEN
          wsql = wsql||'   and (x.bddata between '''||prdataini||''' and '''||prdatafim||''') ';
       -- Filtro do lançamento conciliado
       /* 0 - Normal | 1 - Conciliados | 2 - Não conciliados | 3 - Todos */
       IF (prtipoconciliacao = 1) THEN
         wsql = wsql||'    and (Upper(bdconcd) = ''TRUE'') ';
       ELSE
         IF (prtipoconciliacao = 2) THEN
           wsql = wsql||'  and ((Upper(bdconcd) = ''FALSE'') or (bdconcd is null)) ';
       -- Fim filtro do lançamento conciliado
       wsql = wsql||'      group by x.BDDEBITO, x.bdcodplapadrao, x.bdcodemp) tlan ';

       wsql = wsql||'inner join planos_tpla tpla on (tpla.bdcodplapadrao = tlan.bdcodplapadrao and tpla.bdcodtpla = tlan.bddebito) ';

       IF (prclassificacao_inicial IS NOT NULL) THEN
          wsql = wsql||'where (tpla.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''') ';
       IF (prnaomostracontacomp = 1) THEN
          wsql = wsql||' and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = ' || '''FALSE''' || ')) ';

       FOR EXECUTE STATEMENT wsql INTO  :bdcodtpla, :bdcodplapadrao, :bdctalon, :bdnomcta, :bdapecta, :bdtipcta, :bdrelcta, :bdinvertesinal, :bdfiltroger,
                                   :bdclanom, :bdformula, :bdcondicao, :bdconciliaautomatica, :bdgrupocta, :bdparticipante DO
          BEGIN
            SUSPEND;
          END
     
       /* adiciona contas a credito */

       wsql = 'select tlan.BDCREDITO , ';
       wsql = wsql||' tpla.BDCODPLAPADRAO, tpla.bdctalon, tpla.bdnomcta, ';
       wsql = wsql||' tpla.bdapecta, tpla.BDTIPCTA, tpla.BDRELCTA, ';
       wsql = wsql||' tpla.BDINVERTESINAL, tpla.BDFILTROGER, tpla.BDCLANOM, ';
       wsql = wsql||' tpla.BDFORMULA,  tpla.BDCONDICAO, ';
       wsql = wsql||' tpla.BDCONCILIAAUTOMATICA, tpla.BDGRUPOCTA, tpla.bdparticipante ';
       wsql = wsql||'from (select x.BDCREDITO, x.bdcodplapadrao, x.bdcodemp ';
       wsql = wsql||'      from vsuc_empresas_tlan x ';

       --alt:7211 - Alterado de "bdcodemp = prempresas" para bdcodemp in (prempresas) para selecionar a empresa matriz e suas filiais, caso sejam informadas. Pedro
       --wsql = wsql||'      where x.bdCREDITO is not null and x.bdcodemp = '||prempresas||' and x.bdcodplapadrao = '||prcodplapadrao;
       wsql = wsql||'      where x.bdCREDITO is not null and x.bdcodemp in ('||prempresas||') and x.bdcodplapadrao = '||prcodplapadrao;
       IF (PRDATAINI IS NOT NULL) THEN
          wsql = wsql||'   and (x.bddata between '''||prdataini||''' and '''||prdatafim||''') ';
       -- Filtro do lançamento conciliado
       /* 0 - Normal | 1 - Conciliados | 2 - Não conciliados | 3 - Todos */
       IF (prtipoconciliacao = 1) THEN
         wsql = wsql||'    and (Upper(bdconcc) = ''TRUE'') ';
       ELSE
         IF (prtipoconciliacao = 2) THEN
           wsql = wsql||'  and ((Upper(bdconcc) = ''FALSE'') or (bdconcc is null)) ';
       -- Fim filtro do lançamento conciliado
       wsql = wsql||'      group by x.BDCREDITO, x.bdcodplapadrao, x.bdcodemp) tlan ';

       wsql = wsql||'inner join planos_tpla tpla on (tpla.bdcodplapadrao = tlan.bdcodplapadrao and tpla.bdcodtpla = tlan.bdcredito) ';

       IF (prclassificacao_inicial IS NOT NULL) THEN
          wsql = wsql||'where (tpla.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''') ';

     
       FOR EXECUTE STATEMENT wsql INTO :bdcodtpla, :bdcodplapadrao, :bdctalon, :bdnomcta, :bdapecta, :bdtipcta, :bdrelcta, :bdinvertesinal, :bdfiltroger,
                                   :bdclanom, :bdformula, :bdcondicao, :bdconciliaautomatica, :bdgrupocta, :bdparticipante DO
          BEGIN
            SUSPEND;
          END
     END
 
   IF (prorcamento = 1) THEN
      BEGIN
        wSql = ' select distinct tlan.BDCODTPLA , ';
        wsql = wsql||'tpla.BDCODPLAPADRAO, tpla.bdctalon, tpla.bdnomcta, tpla.bdapecta, tpla.BDTIPCTA, tpla.BDRELCTA,  tpla.BDINVERTESINAL, tpla.BDFILTROGER, tpla.BDCLANOM, tpla.BDFORMULA,  tpla.BDCONDICAO, ';
        wsql = wsql||'tpla.BDCONCILIAAUTOMATICA, tpla.BDGRUPOCTA, tpla.bdparticipante ';
        wsql = wsql||'from VSUC_EMPRESAS_TORC tlan ';
        wsql = wsql||'inner join planos_tpla tpla on tpla.bdcodplapadrao = tlan.bdcodplapadrao and tpla.bdcodtpla = tlan.BDCODTPLA';

        --alt:7211 - Alterado de "bdcodemp = prempresas" para bdcodemp in (prempresas) para selecionar a empresa matriz e suas filiais, caso sejam informadas. Pedro
        --wsql = wsql||' where tlan.bdcodemp = ' || prEmpresas || ' AND  tlan.BDCODTPLA IS NOT NULL ';
        wsql = wsql||' where tlan.bdcodemp in ('||prempresas||') AND  tlan.BDCODTPLA IS NOT NULL ';
        wsql = wsql||' and tpla.BDCODPLAPADRAO = ' || prcodplapadrao ;
        IF (PRDATAINI IS NOT NULL) THEN
           wsql = wsql || ' and (tlan.bdano between '||wanoini||' and '||wanofim||') ';
        IF (prclassificacao_inicial IS NOT NULL) THEN
           wsql = wsql||' and (tpla.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''') ';
  
        FOR EXECUTE STATEMENT wsql INTO :bdcodtpla, :bdcodplapadrao, :bdctalon, :bdnomcta, :bdapecta, :bdtipcta, :bdrelcta, :bdinvertesinal, :bdfiltroger,
                                :bdclanom, :bdformula, :bdcondicao, :bdconciliaautomatica, :bdgrupocta, :bdparticipante DO
          BEGIN
            SUSPEND;
          END
      END
 
   /* adiciona contas titulo */
   IF (prtitulos = 0) THEN
      BEGIN
        wSql = ' select tpla.BDCODTPLA , ';
        wsql = wsql||'tpla.bdctalon, tpla.bdnomcta, tpla.bdapecta, tpla.BDTIPCTA, tpla.BDRELCTA, tpla.BDINVERTESINAL, tpla.BDFILTROGER, tpla.BDCLANOM, tpla.BDFORMULA,  tpla.BDCONDICAO, ';
        wsql = wsql||'tpla.BDCONCILIAAUTOMATICA, tpla.BDGRUPOCTA, tpla.bdparticipante ';
        wsql = wsql||'from planos_tpla tpla ';
--        wsql = wsql||' where tpla.BDCODPLAPADRAO = ' || prcodplapadrao || ' AND tpla.BDTIPCTA in (0,2) ';-- gilberto - 17/05/2011 - incluido as contas consolidadas
--        wsql = wsql||' where tpla.BDCODPLAPADRAO = ' || prcodplapadrao || ' AND ((tpla.BDTIPCTA in (0,2)) or ((tpla.BDTIPCTA = 1) AND (TPLA.bdformula IS NOT NULL))) ';--
        wsql = wsql||' where tpla.BDCODPLAPADRAO = '||prcodplapadrao||' AND ((tpla.BDTIPCTA in (0,2)) or ((tpla.BDTIPCTA = 1) AND (TPLA.bdformula <> ''''))) ';-- GIOVANNI - 27/04/2012 - incluido as com formulas
        IF (prnaomostracontacomp = 1) THEN
            wsql = wsql||' and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = ' || '''FALSE''' || ')) ';

        IF ((prclassificacao_inicial IS NOT NULL) AND (prclassificacao_final IS NOT NULL)) THEN
           wsql = wsql||' and (tpla.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''') ';


        FOR EXECUTE STATEMENT wsql INTO :bdcodtpla, :bdctalon, :bdnomcta, :bdapecta, :bdtipcta, :bdrelcta, :bdinvertesinal, :bdfiltroger,
                                :bdclanom, :bdformula, :bdcondicao, :bdconciliaautomatica, :bdgrupocta, :bdparticipante DO
          BEGIN
            SUSPEND;
          END
      END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_CONTR_PATRIMON */
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_CONTR_PATRIMON (
    PRCODEMP VARCHAR(2048),
    PRCTAINI INTEGER,
    PRCTAFIN INTEGER,
    PRDATINI DATE,
    PRDATFIN DATE,
    PRMODELO INTEGER,
    PRTIPO INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRREFEMP INTEGER,
    PRMOSTRADEPRECIADOS INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRDETALHARTAXADEP INTEGER = 0,
    PRCODTPCC varchar(8192) = '',
    prRelBaiPar INTEGER = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDCODMATRIZ INTEGER,
    BDCODEMPFILIAL INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCODBEM INTEGER,
    BDNOMBEM VARCHAR(200),
    BDCODTPLA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMTPLA VARCHAR(100),
    BDCODFOR INTEGER,
    BDNOMFOR VARCHAR(100),
    BDCODCC INTEGER,
    BDCTALONCC VARCHAR(20),
    BDNOMCC VARCHAR(40),
    BDVALORCORRIGIDOANTERIOR NUMERIC(15,2),
    BDCORRECAOPERIODO NUMERIC(15,2),
    BDVALORCORRIGIDOATUAL NUMERIC(15,2),
    BDDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2),
    BDDEPRECIACAOPERIODO NUMERIC(15,2),
    BDDEPRECIACAOPERIODOMOEDA NUMERIC(15,6),
    BDDEPRECIACAOACUMULADAATUAL NUMERIC(15,2),
    BDDEPRECIACAOACUMULADAATUALMOE NUMERIC(15,6),
    BDCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2),
    BDVALORRESIDUALCONTABIL NUMERIC(15,2),
    BDVALORRESIDUALCONTABILMOEDA NUMERIC(15,6),
    BDTOTALMESESDEPRECIACAO INTEGER,
    BDMESESDEPRECIADOS INTEGER,
    BDMESESDEPRECIAR INTEGER,
    BDTAXADEPRECIACAOANUAL NUMERIC(6,6),
    BDDATATAXADEPRECIACAO DATE,
    BDREFERENCIA VARCHAR(7),
    BDNATBEM VARCHAR(20),
    BDESPECIE VARCHAR(20),
    BDDATAAQUISICAO DATE,
    BDVALORMOEDA NUMERIC(15,6),
    BDVALORAQUISICAOMOEDA NUMERIC(15,6),
    BDVALORCORRIGIDOANTERIORMOEDA NUMERIC(15,6),
    BDVALORAQUISICAOORIGINAL NUMERIC(15,2),
    BDVALORBAIXA NUMERIC(15,2),
    BDSOMARDEPRECIACAO INTEGER,
    BDCODORIGBEM INTEGER,
    BDTIPOBEM INTEGER,
    BDCLACOD VARCHAR(21),
    BDULTIMOAGREGADO INTEGER,
    BDVALORRESIDUAL NUMERIC(15,6),
    BDCODBAI INTEGER,
    BDBAIXAADICIONAL INTEGER,
    BDDATAINICALC DATE,
    BDVALVENBAI NUMERIC(15,6),
    BDCODMOT INTEGER,
    BDDESCMOT VARCHAR(50),
    BDSALDOQTD INTEGER,
    BDQTDBAIXA INTEGER,
    BDOBSBAIXA VARCHAR(200),
    BDQUANTIDADEBEM INTEGER,
    BDNRCHAPA VARCHAR(20),
    BDVALAQUIBEMORIGINAL NUMERIC(15,2),
    BDCGCTER varchar(18))
AS
DECLARE VARIABLE WCTALONINI VARCHAR(40);
DECLARE VARIABLE WCTALONFIN VARCHAR(40);
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODBEM INTEGER;
DECLARE VARIABLE WNOMBEM VARCHAR(200);
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WNOMTPLA VARCHAR(100);
DECLARE VARIABLE WCODFOR INTEGER;
DECLARE VARIABLE WNOMFOR VARCHAR(100);
DECLARE VARIABLE WCODCC INTEGER;
DECLARE VARIABLE WCCLON VARCHAR(20);
DECLARE VARIABLE WNOMCC VARCHAR(40);
DECLARE VARIABLE WDATE DATE;
DECLARE VARIABLE WDATAUX VARCHAR(7);
DECLARE VARIABLE WVALORAQUISICAO NUMERIC(15,2);
DECLARE VARIABLE WCORRECAOPERIODO NUMERIC(15,2);
DECLARE VARIABLE WVALORCORRIGIDOATUAL NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOACUMULADAANTERIOR NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOPERIODO NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOPERIODOMOEDA NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUAL NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOACUMULADAATUALMOED NUMERIC(15,2);
DECLARE VARIABLE WCORRECAOMONETARIADEPRECIACAO NUMERIC(15,2);
DECLARE VARIABLE WVALORRESIDUALCONTABIL NUMERIC(15,2);
DECLARE VARIABLE WVALORRESIDUALCONTABILMOEDA NUMERIC(15,2);
DECLARE VARIABLE WTOTALMESESDEPRECIACAO INTEGER;
DECLARE VARIABLE WMESESDEPRECIADOS INTEGER;
DECLARE VARIABLE WMESESDEPRECIAR INTEGER;
DECLARE VARIABLE WTAXADEPRECIACAOANUAL NUMERIC(6,6);
DECLARE VARIABLE WDATATAXADEPRECIACAO DATE;
DECLARE VARIABLE WDATINI DATE;
DECLARE VARIABLE WDATFIN DATE;
DECLARE VARIABLE WVALORBAIXA NUMERIC(15,2);
DECLARE VARIABLE WDEPRECIACAOBAIXAMOEDA NUMERIC(15,2);
DECLARE VARIABLE WSQL VARCHAR(1024);
DECLARE VARIABLE WNATBEM INTEGER;
DECLARE VARIABLE WESPECIE VARCHAR(20);
DECLARE VARIABLE WDATAAQUISICAO DATE;
DECLARE VARIABLE WDATABAIXA DATE;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WCODAUX INTEGER;
DECLARE VARIABLE WTAXAANT NUMERIC(6,6);
DECLARE VARIABLE WVALORBAIXA2 NUMERIC(15,2);
DECLARE VARIABLE WDATABAIXA2 DATE;
begin
  WCODAUX = 0;

  select first 1 TPLA.BDCTALON
  from PLANOS_TPLA TPLA
  where TPLA.BDCODPLAPADRAO = :PRCODPLAPADRAO and
        ((TPLA.BDCODTPLA = :PRCTAINI) or (:PRCTAINI is null))
  order by BDCTALON asc
  into :WCTALONINI;

  select first 1 TPLA.BDCTALON
  from PLANOS_TPLA TPLA
  where TPLA.BDCODPLAPADRAO = :PRCODPLAPADRAO and
        ((TPLA.BDCODTPLA = :PRCTAFIN) or (:PRCTAFIN is null))
  order by BDCTALON desc
  into :WCTALONFIN;

  -- retorna as empresas selecionadas
  WSQL = 'select case when (bdcodmatriz is null) then bdcodemp ';
  select POS
  from POS(',', :PRCODEMP)
  into :WPOS;
  if (WPOS = 0) then
    select POS
    from POS('=', :PRCODEMP)
    into :WPOS;
  if (WPOS <> 0) then
    WSQL = WSQL || '            when (bdcodmatriz is not null) then bdcodmatriz ';
  else
  begin
    WSQL = WSQL || '          when ((bdcodmatriz is not null) and (bdcodemp not in (' || PRCODEMP || '))) then bdcodmatriz ';
    WSQL = WSQL || '          when (bdcodemp in (' || PRCODEMP || ')) then bdcodemp ';
  end
  WSQL = WSQL || '       end bdcodemp, ';
  WSQL = WSQL || '       bdcodemp bdcodempfilial, ';
  WSQL = WSQL || '       bdcodmatriz, bdnomemp ';
  --  wsql = wsql||'from tempresas temp ';
  WSQL = WSQL || 'from vw_empresas_ref_atual ';
  --  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  select POS
  from POS('=', :PRCODEMP)
  into :WPOS;
  if (WPOS <> 0) then
    WSQL = WSQL || 'where ' || PRCODEMP;
  else
    WSQL = WSQL || 'where bdcodemp in (' || PRCODEMP || ') ';
  WSQL = WSQL || ' order by bdcodmatriz asc, bdcodemp asc ';
  -- executa o sql das empresas
  for execute statement WSQL
          into :BDCODEMP, :BDCODEMPFILIAL, :BDCODMATRIZ, :BDNOMEMP
  do
  begin

    if (PRMODELO in (0, 1, 3)) then
    begin
      /*
       wsql = 'select temp.bdcodemp, tbem.bdcodbem, tbem.bdnombem, tpla.bdcodtpla, ';
       wsql = wsql||' tpla.bdctalon,  tpla.bdnomcta, tfor.bdcodter, tfor.bdnometer, ';
       wsql = wsql||' tbem.bddatoriaquibem, tcc.bdcodtpcc, tcc.bdctalon, tcc.bdnomcta, ';
       wsql = wsql||' tbem.bdnatbem, tbem.BDDATORIAQUIBEM, tbem.bdidbem ';
       wsql = wsql||'from empresas_tbem tbem ';
       wsql = wsql||'inner join tempresas temp on (temp.bdcodemp = tbem.bdcodemp) ';
       wsql = wsql||'left outer join planos_tpla tpla on (tpla.bdcodplapadrao = tbem.bdcodplapadrao and tpla.bdcodtpla = tbem.bdcodtpla) ';
       wsql = wsql||'left outer join tterceiro_ref tfor on (tfor.bdcodter = tbem.bdcodter and tfor.bdrefemp = (select first 1 tfr.bdrefemp from tterceiro_ref tfr ';
       wsql = wsql||                                                                                          'where tfr.bdcodter = tfor.bdcodter ';
       wsql = wsql||                                                                                          'and tfr.bdrefemp <= '||prrefemp;
       wsql = wsql||                                                                                         ' order by tfr.bdrefemp desc)) ';
       wsql = wsql||'left outer join centros_tpcc tcc on (tcc.bdcodcentro = tbem.bdcodcentro and tcc.bdcodtpcc = tbem.bdcodtpcc) ';
       wsql = wsql||'where tbem.bdcodemp = '||prcodemp;
       wsql = wsql||'and tbem.bdcodplapadrao = '||prcodplapadrao;
       if (prtipo <> 0) then
          wsql = wsql||' and tbem.BDDATORIAQUIBEM between '''||prdatini||''' and '''||prdatfin||''' ';
       wsql = wsql||' and (tpla.bdctalon between '''||wctalonini||''' and '''||wctalonfin||''') ';
       wsql = wsql||'order by tpla.bdcodtpla';

       for execute statement wsql*/

      --#alt:17098 - Adicionado os campos bdcodorigbem, bdtipobem e bdultimoagregado para os parâmetros de saída. Ana - 09/05/2017
      --#alt:15304 - Adicionado novo campo no select BDVALAQUIBEM. Ana - 26/08/2016
      --#alt:154385- Machado - 06/09/2021 - indexado BDULTIMOAGREGADO, estava lento
      for select TEMP.BDCODEMP, TBEM.BDCODBEM, TBEM.BDNOMBEM, TPLA.BDCODTPLA, TPLA.BDCTALON, TPLA.BDNOMCTA,
                 TFOR.BDCODTER, TFOR.BDNOMETER, TBEM.BDDATORIAQUIBEM, TCC.BDCODTPCC, TCC.BDCTALON, TCC.BDNOMCTA,
                 TBEM.BDNATBEM, TBEM.BDDATORIAQUIBEM, TBEM.BDIDPATRBEM, TBEM.BDVALAQUIBEM, TBEM.BDCODORIGBEM,
                 TBEM.BDTIPOBEM,
                 (select max(BEM2.BDCODBEM)
                  from EMPRESAS_TBEM BEM2
                  where BEM2.bdcodemp = TBEM.bdcodemp AND BEM2.BDCODORIGBEM = coalesce(TBEM.BDCODORIGBEM, 0)) as BDULTIMOAGREGADO, TBEM.BDQUANTIDADEBEM, TBEM.BDNRCHAPA, TBEM.BDVALAQUIBEMORIGINAL, TFOR.BDCGCTER
          from EMPRESAS_TBEM TBEM
          inner join TEMPRESAS TEMP on (TEMP.BDCODEMP = TBEM.BDCODEMP)
          left outer join PLANOS_TPLA TPLA on (TPLA.BDCODPLAPADRAO = TBEM.BDCODPLAPADRAO and TPLA.BDCODTPLA = TBEM.BDCODTPLA)
          left outer join TTERCEIRO_REF TFOR on (TFOR.BDCODTER = TBEM.BDCODTER and TFOR.BDREFEMP = (select first 1 TFR.BDREFEMP
                                                                                                    from TTERCEIRO_REF TFR
                                                                                                    where TFR.BDCODTER = TFOR.BDCODTER and
                                                                                                          TFR.BDREFEMP <= :PRREFEMP
                                                                                                    order by TFR.BDREFEMP desc))
          left outer join CENTROS_TPCC TCC on (TCC.BDCODCENTRO = TBEM.BDCODCENTRO and TCC.BDCODTPCC = TBEM.BDCODTPCC)
          where TBEM.BDCODEMP = :BDCODEMPFILIAL and
                TBEM.BDCODPLAPADRAO = :PRCODPLAPADRAO and
                (TPLA.BDCTALON between :WCTALONINI and :WCTALONFIN)
          order by TPLA.BDCODTPLA
          into :WCODEMP, :WCODBEM, :WNOMBEM, :WCODTPLA, :WCTALON, :WNOMTPLA, :WCODFOR, :WNOMFOR, :WDATA, :WCODCC,
               :WCCLON, :WNOMCC, :WNATBEM, :WDATAAQUISICAO, :WESPECIE, :WVALORAQUISICAO, :BDCODORIGBEM, :BDTIPOBEM,
               :BDULTIMOAGREGADO, :BDQUANTIDADEBEM, :BDNRCHAPA, :BDVALAQUIBEMORIGINAL, :BDCGCTER
      do
      begin
        BDBAIXAADICIONAL = 0;
        if ((PRCODTPCC IS NOT NULL) and
            (PRCODTPCC <> '')) then
          begin
            select POS
            from POS(','||:WCODCC||',', ','||:PRCODTPCC||',')
            into :WPOS;
            if ((not (:WPOS > 0)) or (:WCODCC is null)) then
              continue;
          end
        
        if ((((WDATAAQUISICAO >= PRDATINI) and
            (WDATAAQUISICAO <= PRDATFIN)) and
            (not PRTIPO in (0,3))) or ((WDATAAQUISICAO <= PRDATFIN) and
            ((PRTIPO in (0,3)) or (PRTIPO in (2, 4))))) then
        begin
          if (prmodelo in (0,1) and prtipo in (2, 4)) then
            begin
              WSQL = 'select BDCODBAI, BDVALBAI, BDDATBAI, BDVALVENBAI, BAI.BDCODMOT, MOT.BDDESCRICAO,BDOBSBAI, coalesce(BDQTDBAI,0) '||
                          ' from EMPRESAS_TBAI BAI'||
                          ' left outer join EMPRESAS_TMOTIVOBAI MOT on (MOT.BDCODMOT = BAI.BDCODMOT) '||
                          ' where BDCODEMP = '||WCODEMP||' and'||
                          '      BDCODBEM = '||WCODBEM||' and'||
                          '      BDCONTABILIZACAO = '||PRCONTABILIZACAO||' and'||
                          '      BDDATBAI between '''||PRDATINI||''' and '''||PRDATFIN||''''||
                          ' ORDER BY BDDATBAI DESC';
            end
           else
           if (prtipo = 4) then
            begin
              WSQL = 'select null as BDCODBAI, sum(BDVALBAI) as BDVALBAI, cast('''||PRDATFIN||''' AS date) as BDDATBAI, sum(BDVALVENBAI) as BDVALVENBAI, null,  null, null, sum(BDQTDBAI) '||
                          ' from EMPRESAS_TBAI'||
                          ' where BDCODEMP = '||WCODEMP||' and'||
                          '      BDCODBEM = '||WCODBEM||' and'||
                          '      BDCONTABILIZACAO = '||PRCONTABILIZACAO||' and'||
                          '      BDDATBAI between '''||PRDATINI||''' and '''||PRDATFIN||'''';
            end
          else
            begin
              wSQL = 'select first 1 cast(null AS INTEGER) as BDCODBAI, cast(null AS INTEGER) as BDVALBAI, cast('''||PRDATFIN||''' AS date) as BDDATBAI, NULL AS BDVALVENBAI, NULL, NULL,NULL, NULL  from EMPRESAS_TBEM';
            end
          FOR EXECUTE STATEMENT wSQL into :BDCODBAI, :WVALORBAIXA2, :WDATABAIXA2, :BDVALVENBAI, :BDCODMOT ,:BDDESCMOT, :BDOBSBAIXA, :BDQTDBAIXA DO
            BEGIN
              for select PRVALORCORRIGIDOANTERIOR, PRVALORCORRIGIDOANTERIORMOEDA, PRCORRECAOPERIODO, PRVALORCORRIGIDOATUAL,
                         PRDEPRECIACAOACUMULADAANTERIOR, PRDEPRECIACAOPERIODO, PRDEPRECIACAOPERIODOMOEDA,
                         PRDEPRECIACAOACUMULADAATUAL, PRDEPRECIACAOACUMULADAATUALMOED, PRCORRECAOMONETARIADEPRECIACAO,
                         PRVALORRESIDUALCONTABIL, PRVALORRESIDUALCONTABILMOEDA, PRTOTALMESESDEPRECIACAO, PRMESESDEPRECIADOS,
                         PRMESESDEPRECIAR, PRTAXADEPRECIACAOANUAL, PRDATATAXADEPRECIACAO, PRVALORBAIXA, PRDATABAIXA,
                         PRDEPRECIACAOBAIXAMOEDA, PRVALORMOEDA, PRVALORAQUISICAOMOEDA, PRVALORAQUISICAOORIGINAL,
                         PRSOMARDEPRECIACAO, BDVALORRESIDUAL, PRTAXADEPRECIACAOANUAL_ANT, PRDATAINICALC
                  FROM SP_CONS_CALC_DEP(:WCODEMP, :WCODBEM, :PRDATINI, :WDATABAIXA2, :PRTIPO, :PRCONTABILIZACAO, :PRDETALHARTAXADEP, :prRelBaiPar)
                  into :BDVALORCORRIGIDOANTERIOR, :BDVALORCORRIGIDOANTERIORMOEDA, :BDCORRECAOPERIODO,
                       :BDVALORCORRIGIDOATUAL, :BDDEPRECIACAOACUMULADAANTERIOR, :BDDEPRECIACAOPERIODO,
                       :BDDEPRECIACAOPERIODOMOEDA, :BDDEPRECIACAOACUMULADAATUAL, :BDDEPRECIACAOACUMULADAATUALMOE,
                       :BDCORRECAOMONETARIADEPRECIACAO, :BDVALORRESIDUALCONTABIL, :BDVALORRESIDUALCONTABILMOEDA,
                       :BDTOTALMESESDEPRECIACAO, :BDMESESDEPRECIADOS, :BDMESESDEPRECIAR, :BDTAXADEPRECIACAOANUAL,
                       :BDDATATAXADEPRECIACAO, :WVALORBAIXA, :WDATABAIXA, :WDEPRECIACAOBAIXAMOEDA, BDVALORMOEDA,
                       BDVALORAQUISICAOMOEDA, BDVALORAQUISICAOORIGINAL, BDSOMARDEPRECIACAO, :BDVALORRESIDUAL, :WTAXAANT, :BDDATAINICALC
              do
              begin

                select sum(BDQTDBAI) from EMPRESAS_TBAI B where
                          B.BDCODEMP = :WCODEMP and
                          B.BDCODBEM = :WCODBEM and
                          B.BDDATBAI <= :WDATABAIXA2 into :BDSALDOQTD;
                BDSALDOQTD = :BDQUANTIDADEBEM - coalesce(:bdsaldoqtd,0);

                if ((prmodelo <> 0 and not prtipo in (2, 4)) or (prtipo <> 4)) then
                   select sum(coalesce(BDQTDBAI,0)) from EMPRESAS_TBAI B where B.BDCODEMP = :WCODEMP and B.BDCODBEM = :WCODBEM and B.BDDATBAI <= :WDATABAIXA2 into :BDQTDBAIXA;

               if (wvalorbaixa2 is not null) then
                 wvalorbaixa = wvalorbaixa2;

                BDCODEMP = WCODEMP;
                BDCODBEM = WCODBEM;
                BDNOMBEM = WNOMBEM;
                BDCODTPLA = WCODTPLA;
                BDCTALON = WCTALON;
                --#alt:163939 - Carlos Machado - 24/05/2022
                if (BDCODORIGBEM > 0) then
                  BDCLACOD = lpad(cast(BDCODORIGBEM as varchar(10)), 10) || '.' || lpad(cast(BDCODBEM as varchar(10)), 10);
                  else
                  BDCLACOD = lpad(cast(BDCODBEM as varchar(10)), 10);
                BDNOMTPLA = WNOMTPLA;
                BDCODFOR = WCODFOR;
                BDNOMFOR = WNOMFOR;
                BDCODCC = WCODCC;
                BDCTALONCC = WCCLON;
                BDNOMCC = WNOMCC;
                BDVALORBAIXA = WVALORBAIXA;
    
                if (BDCODCC is null) then
                  BDCODCC = 0;
    
                if (WNATBEM = 0) then
                  BDNATBEM = 'Bem original';
                else
                if (WNATBEM = 1) then
                  BDNATBEM = 'Aquisição parcial';
                else
                if (WNATBEM = 2) then
                  BDNATBEM = 'Reavaliação';
                else
                if (WNATBEM = 3) then
                  BDNATBEM = 'Transferência';
                BDESPECIE = WESPECIE;
                BDDATAAQUISICAO = WDATAAQUISICAO;
                BDESPECIE = WESPECIE;
    
                --                        if ((prtipo = 2) and ((wvalorbaixa is not null) and (wvalorbaixa > 0))) then
                --                           begin
                --                             bdvalorcorrigidoanterior = wvalorbaixa;
                --                             bdvalorcorrigidoatual = wdepreciacaobaixamoeda;
                --                           end
    
                --                        suspend;
    
                if (BDTAXADEPRECIACAOANUAL = 0 and
                    WTAXAANT > 0) then
                  BDTAXADEPRECIACAOANUAL = WTAXAANT;
    
                if (BDDEPRECIACAOPERIODO > 0) then
                begin
    
                  if (PRTIPO in (2, 4)) then
                  begin
                    if ((WVALORBAIXA is not null) and
                        (WVALORBAIXA > 0)) then
                    begin
                      if ((WDATABAIXA >= PRDATINI) and
                          (WDATABAIXA <= PRDATFIN)) then
                      begin
                        BDVALORCORRIGIDOANTERIOR = WVALORBAIXA;
                        BDVALORCORRIGIDOATUAL = WVALORBAIXA;
                        BDDATAAQUISICAO = WDATABAIXA2;
    
                        --#alt:85169. Esta sendo impresso o campo BDVALORAQUISICAOORIGINAL quando o tipo e o 2, nao sei quando foi alterado o campo no relatorio. Ana - 20/06/2018
                        BDVALORAQUISICAOORIGINAL = WVALORBAIXA;
                        BDVALORCORRIGIDOANTERIORMOEDA = (WVALORBAIXA * BDVALORMOEDA);
                        if (BDCODMATRIZ > 0) then
                          BDCODEMP = BDCODMATRIZ;
                        suspend;
                      end
                    end
                  end
                  else
                  begin
                    if (BDTOTALMESESDEPRECIACAO > 0) then
                    begin
                      if (BDCODMATRIZ > 0) then
                        BDCODEMP = BDCODMATRIZ;
    
                      suspend;
                    end
                  end
                end
                else
                begin
                  -- somente quando no relatorio esta para sair bens que nao tiveram depreciacao
                  if ((BDMESESDEPRECIADOS = 0) or (PRMOSTRADEPRECIADOS = 1)) then
                  begin
                    if (BDCODMATRIZ > 0) then
                      BDCODEMP = BDCODMATRIZ;
    
                    -- #alt:15304 - Quando o bem não tem depreciação cadastrada não temos como saber se é do fiscal ou societário. Nesse caso o bem deve aparecer para os dois modelos de contabilização. Ana - 26/08/2016
                    if ((BDVALORAQUISICAOORIGINAL = 0) and
                        (BDVALORRESIDUALCONTABIL = 0)) then
                    begin
                      BDVALORAQUISICAOORIGINAL = WVALORAQUISICAO;
                      BDVALORRESIDUALCONTABIL = WVALORAQUISICAO;
                    end
    
                    --#alt:17098 - Quando era o relatório de relação de baixas estava mostrando os bens mesmo sem baixas.  Ana - 09/05/2017
                    if (((PRTIPO in (2, 4)) and
                        ((WVALORBAIXA is not null) and
                        (WVALORBAIXA > 0)) and
                        ((WDATABAIXA >= PRDATINI) and
                        (WDATABAIXA <= PRDATFIN)))) then
                        suspend;
                    else
                    if (PRTIPO not in (2, 4)) then
                      suspend;
                  end
                end
              end    
                BDBAIXAADICIONAL = 1;
            END
        end
      end
    end
    else
    begin
      /*
       wsql = 'select temp.bdcodemp, tbem.bdcodbem, tbem.bdnombem, tpla.bdcodtpla, ';
       wsql = wsql||' tpla.bdctalon,  tpla.bdnomcta, tfor.bdcodter, tfor.bdnometer, ';
       wsql = wsql||' tbem.bddatoriaquibem, tcc.bdcodtpcc, tcc.bdctalon, tcc.bdnomcta, ';
       wsql = wsql||' tbem.bdnatbem, tbem.bdidbem ';
       wsql = wsql||'from empresas_tbem tbem ';
       wsql = wsql||'inner join tempresas temp on (temp.bdcodemp = tbem.bdcodemp) ';
       wsql = wsql||'left outer join planos_tpla tpla on (tpla.bdcodplapadrao = tbem.bdcodplapadrao and tpla.bdcodtpla = tbem.bdcodtpla) ';
       wsql = wsql||'left outer join tterceiro_ref tfor on (tfor.bdcodter = tbem.bdcodter and tfor.bdrefemp = (select first 1 tfr.bdrefemp from tterceiro_ref tfr ';
       wsql = wsql||                                                                                          'where tfr.bdcodter = tfor.bdcodter ';
       wsql = wsql||                                                                                          'and tfr.bdrefemp <= '||prrefemp;
       wsql = wsql||                                                                                         ' order by tfr.bdrefemp desc)) ';
       wsql = wsql||'left outer join centros_tpcc tcc on (tcc.bdcodcentro = tbem.bdcodcentro and tcc.bdcodtpcc = tbem.bdcodtpcc) ';
       wsql = wsql||'where tbem.bdcodemp = '||prcodemp||' ';
       wsql = wsql||'and tbem.bdcodplapadrao = '||prcodplapadrao;
--               and substring(cast(tbem.bddataquibem as varchar(10)) from 1 for 7) = :wdataux
       if (prtipo <> 0) then
          wsql = wsql||' and tbem.BDDATORIAQUIBEM between '''||prdatini||''' and '''||prdatfin||''' ';
       wsql = wsql||' and (tpla.bdctalon between '''||wctalonini||''' and '''||wctalonfin||''') ';
       wsql = wsql||'order by tpla.bdcodtpla';
       for execute statement wsql*/

      --#alt:17098 - Adicionado os campos bdcodorigbem, bdtipobem e bdultimoagregado para os parâmetros de saída. Ana - 09/05/2017
      --#alt:15304 - Adicionado novo campo no select BDVALAQUIBEM. Ana - 26/08/2016
      --#alt:154385- Machado - 06/09/2021 - indexado BDULTIMOAGREGADO, estava lento
      for select TEMP.BDCODEMP, TBEM.BDCODBEM, TBEM.BDNOMBEM, TPLA.BDCODTPLA, TPLA.BDCTALON, TPLA.BDNOMCTA,
                 TFOR.BDCODTER, TFOR.BDNOMETER, TBEM.BDDATORIAQUIBEM, TCC.BDCODTPCC, TCC.BDCTALON, TCC.BDNOMCTA,
                 TBEM.BDNATBEM, TBEM.BDIDPATRBEM, TBEM.BDDATORIAQUIBEM, TBEM.BDVALAQUIBEM, TBEM.BDCODORIGBEM,
                 TBEM.BDTIPOBEM,
                 (select max(BEM2.BDCODBEM)
                  from EMPRESAS_TBEM BEM2
                  where BEM2.bdcodemp = TBEM.bdcodemp AND BEM2.BDCODORIGBEM = coalesce(TBEM.BDCODORIGBEM, 0)) as BDULTIMOAGREGADO, TBEM.BDNRCHAPA, TBEM.BDVALAQUIBEMORIGINAL, TFOR.BDCGCTER
          from EMPRESAS_TBEM TBEM
          inner join TEMPRESAS TEMP on (TEMP.BDCODEMP = TBEM.BDCODEMP)
          left outer join PLANOS_TPLA TPLA on (TPLA.BDCODPLAPADRAO = TBEM.BDCODPLAPADRAO and TPLA.BDCODTPLA = TBEM.BDCODTPLA)
          left outer join TTERCEIRO_REF TFOR on (TFOR.BDCODTER = TBEM.BDCODTER and TFOR.BDREFEMP = (select first 1 TFR.BDREFEMP
                                                                                                    from TTERCEIRO_REF TFR
                                                                                                    where TFR.BDCODTER = TFOR.BDCODTER and
                                                                                                          TFR.BDREFEMP <= :PRREFEMP
                                                                                                    order by TFR.BDREFEMP desc))
          left outer join CENTROS_TPCC TCC on (TCC.BDCODCENTRO = TBEM.BDCODCENTRO and TCC.BDCODTPCC = TBEM.BDCODTPCC)
          where TBEM.BDCODEMP = :BDCODEMPFILIAL and
                TBEM.BDCODPLAPADRAO = :PRCODPLAPADRAO and
                (TPLA.BDCTALON between :WCTALONINI and :WCTALONFIN)
          order by TPLA.BDCODTPLA
          into :WCODEMP, :WCODBEM, :WNOMBEM, :WCODTPLA, :WCTALON, :WNOMTPLA, :WCODFOR, :WNOMFOR, :WDATA, :WCODCC,
               :WCCLON, :WNOMCC, :WNATBEM, :WESPECIE, :WDATAAQUISICAO, :WVALORAQUISICAO, :BDCODORIGBEM, :BDTIPOBEM,
               :BDULTIMOAGREGADO, :BDNRCHAPA, :BDVALAQUIBEMORIGINAL, :BDCGCTER
      do
      begin
        --             if ((((wdataaquisicao >= prdatini) and (wdataaquisicao <= prdatfin)) and (prtipo <> 0)) or ((prtipo = 0) or (prTipo = 2))) then
        if ((PRCODTPCC IS NOT NULL) and
            (PRCODTPCC <> '')) then
          begin
            select POS
            from POS(','||:WCODCC||',', ','||:PRCODTPCC||',')
            into :WPOS;
            if ((not (:WPOS > 0)) or (:WCODCC is null)) then
              continue;
          end
          
        if ((((WDATAAQUISICAO >= PRDATINI) and
            (WDATAAQUISICAO <= PRDATFIN)) and
            (not PRTIPO in (0,3))) or ((WDATAAQUISICAO <= PRDATFIN) and
            ((PRTIPO in (0,3)) or (PRTIPO in (2, 4))))) then
        begin
          WDATE = PRDATINI;
          WDATAUX = substring(cast(WDATE as varchar(10)) from 1 for 7);

          while (WDATE < PRDATFIN) do
          begin
            WDATINI = cast(WDATAUX || '-01' as date);
            WDATFIN = ADDMONTH(WDATINI, 1) - 1;

            BDVALORCORRIGIDOANTERIOR = 0;
            BDVALORCORRIGIDOANTERIORMOEDA = 0;
            BDCORRECAOPERIODO = 0;
            BDVALORCORRIGIDOATUAL = 0;
            BDDEPRECIACAOACUMULADAANTERIOR = 0;
            BDDEPRECIACAOPERIODO = 0;
            BDDEPRECIACAOPERIODOMOEDA = 0;
            BDDEPRECIACAOACUMULADAATUAL = 0;
            BDDEPRECIACAOACUMULADAATUALMOE = 0;
            BDCORRECAOMONETARIADEPRECIACAO = 0;
            BDVALORRESIDUALCONTABIL = 0;
            BDVALORRESIDUALCONTABILMOEDA = 0;
            BDTOTALMESESDEPRECIACAO = 0;
            BDMESESDEPRECIADOS = 0;
            BDMESESDEPRECIAR = 0;
            BDTAXADEPRECIACAOANUAL = 0;
            --#ALT:17098 - Adicionei o valor da baixa, pois ele verificava este valor mas não retornava da procedure. Ana - 19/05/2017
            select PRVALORCORRIGIDOANTERIOR, PRVALORCORRIGIDOANTERIORMOEDA, PRCORRECAOPERIODO, PRVALORCORRIGIDOATUAL,
                   PRDEPRECIACAOACUMULADAANTERIOR, PRDEPRECIACAOPERIODO, PRDEPRECIACAOPERIODOMOEDA,
                   PRDEPRECIACAOACUMULADAATUAL, PRDEPRECIACAOACUMULADAATUALMOED, PRCORRECAOMONETARIADEPRECIACAO,
                   PRVALORRESIDUALCONTABIL, PRVALORRESIDUALCONTABILMOEDA, PRTOTALMESESDEPRECIACAO, PRMESESDEPRECIADOS,
                   PRMESESDEPRECIAR, PRTAXADEPRECIACAOANUAL, PRDATATAXADEPRECIACAO, PRVALORMOEDA, PRVALORAQUISICAOMOEDA,
                   PRVALORAQUISICAOORIGINAL, PRSOMARDEPRECIACAO, PRVALORBAIXA, PRTAXADEPRECIACAOANUAL_ANT, PRDATAINICALC
            from SP_CONS_CALC_DEP(:WCODEMP, :WCODBEM, :WDATINI, :WDATFIN, :PRTIPO, :PRCONTABILIZACAO, :PRDETALHARTAXADEP, :prRelBaiPar)
            into :BDVALORCORRIGIDOANTERIOR, :BDVALORCORRIGIDOANTERIORMOEDA, :BDCORRECAOPERIODO, :BDVALORCORRIGIDOATUAL,
                 :BDDEPRECIACAOACUMULADAANTERIOR, :BDDEPRECIACAOPERIODO, :BDDEPRECIACAOPERIODOMOEDA,
                 :BDDEPRECIACAOACUMULADAATUAL, :BDDEPRECIACAOACUMULADAATUALMOE, :BDCORRECAOMONETARIADEPRECIACAO,
                 :BDVALORRESIDUALCONTABIL, :BDVALORRESIDUALCONTABILMOEDA, :BDTOTALMESESDEPRECIACAO, :BDMESESDEPRECIADOS,
                 :BDMESESDEPRECIAR, :BDTAXADEPRECIACAOANUAL, :BDDATATAXADEPRECIACAO, :BDVALORMOEDA,
                 BDVALORAQUISICAOMOEDA, BDVALORAQUISICAOORIGINAL, BDSOMARDEPRECIACAO, WVALORBAIXA, :WTAXAANT, :BDDATAINICALC;

            BDCODEMP = WCODEMP;
            BDCODBEM = WCODBEM;
            BDNOMBEM = WNOMBEM;
            BDCODTPLA = WCODTPLA;
            BDCTALON = WCTALON;
            --#alt:163939 - Carlos Machado - 24/05/2022
            if (BDCODORIGBEM > 0) then
              BDCLACOD = lpad(cast(BDCODORIGBEM as varchar(10)), 10) || '.' || lpad(cast(BDCODBEM as varchar(10)), 10);
              else
              BDCLACOD = lpad(cast(BDCODBEM as varchar(10)), 10);
            BDNOMTPLA = WNOMTPLA;
            BDCODFOR = WCODFOR;
            BDNOMFOR = WNOMFOR;
            BDCODCC = WCODCC;
            BDCTALONCC = WCCLON;
            BDNOMCC = WNOMCC;
            BDREFERENCIA = WDATAUX;

            if (BDCODCC is null) then
              BDCODCC = 0;

            if (WNATBEM = 0) then
              BDNATBEM = 'Bem original';
            else
            if (WNATBEM = 1) then
              BDNATBEM = 'Aquisição parcial';
            else
            if (WNATBEM = 2) then
              BDNATBEM = 'Reavaliação';
            else
            if (WNATBEM = 3) then
              BDNATBEM = 'Transferência';
            BDESPECIE = WESPECIE;
            BDDATAAQUISICAO = WDATA;
            BDESPECIE = WESPECIE;

            --                      if ((prtipo = 2) and ((wvalorbaixa is not null) and (wvalorbaixa > 0))) then
            --                         begin
            --                           bdvalorcorrigidoanterior = wvalorbaixa;
            --                           bdvalorcorrigidoatual = wdepreciacaobaixamoeda;
            --                         end
            --                      else

            if (BDTAXADEPRECIACAOANUAL = 0 and
                WTAXAANT > 0) then
              BDTAXADEPRECIACAOANUAL = WTAXAANT;

            if (BDDEPRECIACAOPERIODO > 0) then
            begin

              if ((BDVALORCORRIGIDOANTERIOR is not null) or (BDVALORCORRIGIDOATUAL is not null) or (BDDEPRECIACAOACUMULADAATUAL is not null) or (BDDEPRECIACAOPERIODO is not null)) then
              begin
                if (PRTIPO in (2, 4)) then
                begin
                  if ((WVALORBAIXA is not null) and
                      (WVALORBAIXA > 0)) then
                  begin
                    if (BDCODMATRIZ > 0) then
                      BDCODEMP = BDCODMATRIZ;

                    suspend;
                  end
                end
                else
                begin
                  if (BDCODMATRIZ > 0) then
                    BDCODEMP = BDCODMATRIZ;

                  suspend;
                end
              end
            end
            else -- somente quando no relatorio esta para sair bens que nao tiveram depreciacao
            if ((BDMESESDEPRECIADOS = 0) or (PRMOSTRADEPRECIADOS = 1)) then
            begin
              if (BDCODMATRIZ > 0) then
                BDCODEMP = BDCODMATRIZ;

              -- #alt:15304 - Quando o bem não tem depreciação cadastrada não temos como saber se é do fiscal ou societário. Nesse caso o bem deve aparecer para os dois modelos de contabilização. Ana - 26/08/2016
              if ((BDVALORAQUISICAOORIGINAL = 0) and
                  (BDVALORRESIDUALCONTABIL = 0)) then
              begin
                BDVALORAQUISICAOORIGINAL = WVALORAQUISICAO;
                BDVALORRESIDUALCONTABIL = WVALORAQUISICAO;
              end

              --#alt:19813 - Nesta opção não traz a data da baixa então não precisa ser verificado o período. Ana - 24/08/2017
              --#alt:17098 - Quando era o relatório de relação de baixas estava mostrando os bens mesmo sem baixas.  Ana - 09/05/2017
              if (((PRTIPO = 2) and
                  ((WVALORBAIXA is not null) and
                  (WVALORBAIXA > 0)) /*AND ((WDATABAIXA >= PRDATINI) AND (WDATABAIXA <= PRDATFIN))*/ ) or (PRTIPO <> 2)) then
                suspend;
            end

            WDATE = ADDMONTH(WDATE, 1);
            WDATAUX = substring(cast(WDATE as varchar(10)) from 1 for 7);
          end
        end
      end
    end
  end
end
^

/* Restore proc. body: VSUC_SP_RETORNA_CRITICA_LANC */
ALTER PROCEDURE VSUC_SP_RETORNA_CRITICA_LANC(PRCODEMP VARCHAR(2048),
PRDATINI DATE,
PRDATFIN DATE,
PRCHAVEINI INTEGER,
PRCHAVEFIM INTEGER,
PRLOTEINI VARCHAR(10),
PRLOTEFIM VARCHAR(10),
PRTRANSINI INTEGER,
PRTRANSFIM INTEGER,
PRCOLUNAS INTEGER,
PRLCC VARCHAR(8192),
PRTOTDIA INTEGER,
PRTOTMES INTEGER,
PRTOTANO INTEGER,
PRTOTLOTE INTEGER,
PRDATAS VARCHAR(1024),
PRLANCSEMTRANS INTEGER,
PRREFEMP INTEGER,
PRCODTIPOLANC INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRSTATUSTRANSACAO INTEGER = 0)
 RETURNS(PRCHAVE INTEGER,
PRDATA DATE,
PRCODIGO_CREDITO INTEGER,
PRVALOR_CREDITO NUMERIC(15,2),
PRCODIGO_DEBITO INTEGER,
PRVALOR_DEBITO NUMERIC(15,2),
PRCOMPLEMENTO VARCHAR(200),
PRHISTORICO VARCHAR(200),
PREMPRESA INTEGER,
PRNOMEEMPRESA DM_BDNOMEMP,
PRCODTPCC INTEGER,
PRCNPJEMP VARCHAR(18),
PRLOTE VARCHAR(10),
PRDCTO VARCHAR(15),
PRCODMATRIZ INTEGER,
PRDEBCRE INTEGER,
PRVALOR NUMERIC(15,2),
PRVALORRAT NUMERIC(15,2),
PRQUEBRADIA DATE,
PRQUEBRAMES VARCHAR(7),
PRQUEBRARANO VARCHAR(4),
PRQUEBRALOTE VARCHAR(10),
PRSEQUENCIA INTEGER,
PRNOMECC VARCHAR(40),
PRCODEMPFILIAL INTEGER,
PRCONTAB INTEGER,
PRDESCTIPOLANC VARCHAR(100),
BDTRANSACAO INTEGER)
 AS
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WSQL VARCHAR(3096);
DECLARE VARIABLE WCHAVECC INTEGER;
DECLARE VARIABLE WCOMCC INTEGER;
DECLARE VARIABLE WVALORCCDEB NUMERIC(15,2);
DECLARE VARIABLE WVALORCCCRE NUMERIC(15,2);
DECLARE VARIABLE WVALORCCGERAL NUMERIC(15,2);
DECLARE VARIABLE WGUARDAVALORRAT NUMERIC(15,2);
DECLARE VARIABLE WGUARDAPRVALOR NUMERIC(15,2);
DECLARE VARIABLE WGUARDACHAVE INTEGER;
DECLARE VARIABLE WGUARDAEMPRESARAT INTEGER;
DECLARE VARIABLE WGUARDAEMPANT INTEGER;
DECLARE VARIABLE WGUARDACONTADEBCC INTEGER;
DECLARE VARIABLE WGUARDACONTACRECC INTEGER;
DECLARE VARIABLE WGUARDADEBCRE INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPERMITED INTEGER;
DECLARE VARIABLE WPERMITEC INTEGER;
DECLARE VARIABLE WEMPPRINC INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WTRANSACAO INTEGER;
BEGIN
  wdatini = SUBSTRING(CAST(prdatini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatfin AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatfin AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatfin AS VARCHAR(10)) FROM 1 FOR 4);

  --alt: 6183 - Adicionado filtro por tipo de lançamento. Pedro
  SELECT BDDESCRICAO FROM TIPOS_LANCAMENTOS_PADRAO WHERE BDCODTIPO = :prCodTipoLanc INTO :prDescTipoLanc;

  --Retorna a empresa principal
  SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
  IF (wpos = 0) THEN
    wempprinc = prcodemp;
  ELSE
    wempprinc = SUBSTRING(prcodemp FROM 1 FOR (wpos - 1));

  wsql = 'select tlan.BDCHAVE, tlan.BDDATA, tlan.BDCREDITO, tlan.BDDEBITO, tlan.BDCOMPL, thist.bdnome, tlan.bdlote, tlan.bddcto, tlan.bdvalor, temp.bdcodmatriz , ';
  wsql = wsql||' tlan.bdcodemp, temp.bdnomemp, temp.bdcnpjemp, tlan.bdcontabilizacao, tlan.BDTRANSACAO ';

  IF (prlcc = '') THEN
     wsql = wsql||' , null bdx, null bdy, null bdz, null bdc  from vsuc_empresas_tlan tlan ';
  ELSE
     BEGIN
       wsql = wsql||' , tlcc.BDVALOR, tlcc.bdcodtpcc, tlcc.bddebcre , tpcc.bdnomcta';
       wsql = wsql||' from vsuc_empresas_tlan tlan ';
       wsql = wsql||' left outer join vsuc_empresas_tlcc tlcc on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
       wsql = wsql||' left outer join CENTROS_TPCC tpcc on (tlcc.bdcodcentro = tpcc.bdcodcentro and tlcc.bdcodtpcc = tpcc.bdcodtpcc) ';
     END

  wsql = wsql||' inner join vw_empresas_ref_atual temp on (temp.bdcodemp = tlan.bdcodemp) ';
  wsql = wsql||' left outer join hist_tphi thist on (thist.bdcodhist = tlan.bdcodhist and thist.bdcodtphi = tlan.bdcodtphi) ';
  wsql = wsql||' where ';

  --alt:6183 - Adicionado o filtro por tipo de lançamento. Pedro
  IF ((NOT prCodTipoLanc IS NULL) AND (prDescTipoLanc <> '')) THEN
     wSQL = wSQL||' BDTIPOLAN = '||prCodTipoLanc||' and ';

  --#alt:5837.
  --wsql = wsql||'(tlan.bdcodemp in ('||trim(prcodemp)||')) and ';
  wsql = wsql||'(tlan.bdcodemp in ('||TRIM(prcodemp)||')) and ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'(tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) and ';

  IF ((prloteini <> '') AND (prlotefim <> '')) THEN
     wsql = wsql||'(tlan.bdlote between '''||prloteini||''' and '''||prlotefim||''') and ';
  ELSE
  IF (prloteini <> '') THEN
     wsql = wsql||'(tlan.bdlote = '''||prloteini||''') and ';
  ELSE
  IF (prlotefim <> '') THEN
     wsql = wsql||'(tlan.bdlote = '''||prlotefim||''') and ';

  IF ((TRIM(prchaveini) IS NOT NULL) AND (TRIM(prchavefim) IS NOT NULL)) THEN
     wsql = wsql||'(tlan.bdchave between '||prchaveini||' and '||prchavefim||') and ';
  ELSE
  IF (TRIM(prchaveini) IS NOT  NULL) THEN
     wsql = wsql||'(tlan.bdchave >= '||prchaveini||') and ';
  ELSE
  IF (prchavefim IS NOT NULL) THEN
     wsql = wsql||'(tlan.bdchave <= '||prchavefim||') and ';

  --alt:8070 - Filtro pela transação inicial e final e imprimir lançamentos sem transação. Pedro
  IF ((TRIM(prtransini) IS NOT NULL) AND (TRIM(prtransfim) IS NOT NULL)) THEN
     BEGIN
       wsql = wsql||'((tlan.bdtransacao between '||prtransini||' and '||prtransfim||') ';

       IF (prlancsemtrans = 0) THEN
          wsql = wsql||') and ';
       ELSE
          wsql = wsql||' or (tlan.bdtransacao is null)) and ';
     END
  ELSE
  IF (TRIM(prtransini) IS NOT  NULL) THEN
     BEGIN
       wsql = wsql||'((tlan.bdtransacao >= '||prtransini||') ';

       IF (prlancsemtrans = 0) THEN
          wsql = wsql||') and ';
       ELSE
          wsql = wsql||' or (tlan.bdtransacao is null)) and ';
     END
  ELSE
  IF (prtransfim IS NOT NULL) THEN
     BEGIN
       wsql = wsql||'((tlan.bdtransacao <= '||prtransfim||') ';

       IF (prlancsemtrans = 0) THEN
          wsql = wsql||') and ';
       ELSE
          wsql = wsql||' or (tlan.bdtransacao is null)) and ';
     END
  ELSE
  IF (prlancsemtrans = 0) THEN
     wsql = wsql||'(tlan.bdtransacao is not null) and';
  --alt:8070 - Fim

  IF (prdatas IS NULL) THEN
     wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';
  ELSE
     -- Somente datas com diferencas...
     wsql = wsql||'(tlan.bddata in ('||TRIM(prdatas)||')) ';

  --#alt:16410 - Adicionado filtro por status da transação. Ana - 05/05/2017
  IF (prstatustransacao = 1) THEN
    wsql = wsql||'and (upper(BDTRANFECHADA) = ''FALSE'') ';
  ELSE IF (prstatustransacao = 2) THEN
    wsql = wsql||'and (upper(BDTRANFECHADA) = ''TRUE'')';
  --#alt:16410. fim

  wsql = wsql||'order by tlan.bddata, tlan.bdchave, temp.bdcodemp';

  wvalorccdeb = 0;
  wvalorcccre = 0;
  /* laco dos lancamentos diario _____________________________________________*/
  FOR EXECUTE STATEMENT wsql
      INTO :prchave, :prdata,
           :prcodigo_credito, :prcodigo_debito, :prcomplemento, :prhistorico, :prlote, :prdcto,
           :wvalor , :prcodmatriz, :prempresa, :prnomeempresa, :prcnpjemp, :prcontab, :BDTRANSACAO,
           :prvalorrat, :prcodtpcc, :prdebcre, :prnomecc DO
      BEGIN
        prcodempfilial = prempresa;
        IF (prcodmatriz IS NULL) THEN
           prcodmatriz = prempresa;
        prempresa = prcodmatriz;

        --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:wempprinc,:prcodempfilial,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermited;
        --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:wempprinc,:prcodempfilial,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermitec;

        /* se trocou de chave verifica se tem que lancar valor sem centro de custo */
        IF ((wcomcc = 1) AND (:prchave <> wchavecc)) THEN
          BEGIN
            wguardaprvalor = wValor;
            wguardavalorrat = prvalorrat;
            wguardachave = prchave;
            wguardaempant = prempresa;
            wguardadebcre = prdebcre;


            IF ((wvalorccdeb = 0) AND (wguardacontadebcc > 0)) THEN
              BEGIN
                prnomecc = 'Sem centro de custo';
                prvalor = wvalorccgeral;
                wvalorccdeb = 0;
                wcomcc = 0;
                prvalorrat = wvalorccgeral;
                prvalor_debito = wvalorccgeral;
                prvalor_credito = NULL;
                prsequencia = 1;
                prcodtpcc = NULL;
                prdebcre = NULL;

                prempresa = wguardaempresarat;
                prchave   = wchavecc;
                SUSPEND;
              END

            IF ((wvalorcccre = 0) AND (wguardacontacrecc > 0)) THEN
              BEGIN
                prnomecc = 'Sem centro de custo';
                prvalor = wvalorccgeral;
                wvalorcccre = 0;
                wcomcc = 0;
                prvalorrat = wvalorccgeral;
                prvalor_debito = NULL;
                prvalor_credito = wvalorccgeral;
                prsequencia = 1;
                prcodtpcc = NULL;
                prdebcre = NULL;

                prempresa = wguardaempresarat;
                prchave   = wchavecc;
                SUSPEND;
              END

            wvalorccdeb = 0;
            wvalorcccre = 0;

            prempresa = wguardaempant;
            prvalor = wguardaprvalor;
            prvalorrat = wguardavalorrat;
            prchave = wguardachave;
            prdebcre = wguardadebcre;
          END

        IF ((prcodigo_debito > 0)) THEN
           prvalor_debito = :wvalor;
        ELSE
          BEGIN
            prvalor_debito  = NULL;
            prcodigo_debito = NULL;
          END

        IF ((prcodigo_credito > 0)) THEN
           prvalor_credito = :wvalor;
        ELSE
          BEGIN
            prvalor_credito  = NULL;
            prcodigo_credito = NULL;
          END

        --#alt:5837.
        --if (prcolunas = 1) then
        --  prvalor_credito = :wvalor;

        prvalor = :wvalor;

        IF (prtotdia = 1) THEN
           prquebradia = :prdata;
        IF (prtotmes = 1) THEN
           prquebrames = SUBSTRING(CAST(:prdata AS VARCHAR(10)) FROM 6 FOR 2)||'/'||SUBSTRING(CAST(:prdata AS VARCHAR(10)) FROM 1 FOR 4);
        IF (prtotano = 1) THEN
           prquebrarano = SUBSTRING(CAST(:prdata AS VARCHAR(10)) FROM 1 FOR 4);

        IF (prtotlote = 1) THEN
          BEGIN
            IF (:prlote <> '' ) THEN
               prquebralote = :prlote;
            ELSE
               prquebralote = '  ';
          END

        IF (:prvalorrat > 0) THEN
          BEGIN
            /* faz um lacamento somente com seus dados gerais, sem valores.... */
            IF ((wvalorccdeb = 0) AND (wvalorcccre = 0)) THEN
              BEGIN
                wguardacontadebcc = prcodigo_debito;
                wguardacontacrecc = prcodigo_credito;
                wguardaempresarat = :prempresa;
                wvalorccgeral = :prvalor;
                wcomcc        = 1;
                wchavecc      = :prchave;
                wguardavalorrat = :prvalorrat;
                prvalor = NULL;
                prvalor_debito = NULL;
                prvalor_credito = NULL;
                prvalorrat = NULL;
                prsequencia = NULL;
                SUSPEND;
                prvalorrat = wguardavalorrat;
              END

            prvalor = wvalorccgeral;
            prsequencia = 2;

            IF ((prdebcre = 0)) THEN
               BEGIN
                 wvalorccdeb = wvalorccdeb + :prvalorrat;
                 prvalor = NULL;
                 prvalor_debito = :prvalorrat;
                 prvalor_credito = NULL;
               END
            ELSE
--            IF (wpermitec = 1) THEN
--               BEGIN
                 wvalorcccre = wvalorcccre + :prvalorrat;
                 prvalor_debito = NULL;
                 prvalor_credito = :prvalorrat;
                 prvalor = NULL;
--               END
               END
        ELSE
           BEGIN
             /* nao precisa controlar cc */
             wcomcc    = 0;
           END
        SUSPEND;
      END

  /* se chegou no fim e o ultimo lancamento era de cc */
  IF (wcomcc = 1)  THEN
    BEGIN
      IF ((wvalorccdeb = 0) AND (wguardacontadebcc > 0))  THEN
        BEGIN
          prnomecc = 'Sem centro de custo';
          prvalor = wvalorccgeral;
          wvalorccdeb = 0;
          wcomcc = 0;
          prvalorrat = wvalorccgeral;
          prvalor_debito = wvalorccgeral;
          prvalor_credito = NULL;
          prsequencia = 1;
          prcodtpcc = NULL;
          prdebcre = NULL;

          prempresa = wguardaempresarat;
          prchave   = wchavecc;
          SUSPEND;
        END

      IF ((wvalorcccre = 0) AND (wguardacontacrecc > 0))  THEN
        BEGIN
          prnomecc = 'Sem centro de custo';
          prvalor = wvalorccgeral;
          wvalorcccre = 0;
          wcomcc = 0;
          prvalorrat = wvalorccgeral;
          prvalor_debito = NULL;
          prvalor_credito = wvalorccgeral;
          prsequencia = 1;
          prcodtpcc = NULL;
          prdebcre = NULL;

          prempresa = wguardaempresarat;
          prchave   = wchavecc;
          SUSPEND;
        END

      prsequencia = NULL;
      wvalorccdeb = 0;
      wvalorcccre = 0;
    END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_DIARIO */
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_DIARIO (
    PRCODEMP INTEGER,
    PRDATINI DATE,
    PRDATFIN DATE,
    PRMODELO INTEGER,
    PRFILIAIS VARCHAR(1024),
    PRLCC VARCHAR(8192),
    PRDETALHARCTAPARTICIPANTE INTEGER,
    PRREFEMP INTEGER,
    PRAGRUPAR VARCHAR(1024),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRDETALHARFILIAL INTEGER)
RETURNS (
    PRCHAVE INTEGER,
    PRDATA DATE,
    PRCODIGO_CREDITO INTEGER,
    PRCLASSI_CREDITO VARCHAR(40),
    PRVALOR_CREDITO NUMERIC(15,2),
    PRCODIGO_DEBITO INTEGER,
    PRCLASSI_DEBITO VARCHAR(40),
    PRVALOR_DEBITO NUMERIC(15,2),
    PRCOMPLEMENTO VARCHAR(200),
    PRHISTORICO VARCHAR(400),
    PREMPRESA INTEGER,
    PRNOMEEMPRESA DM_BDNOMEMP,
    PRCODTPCC INTEGER,
    PRCNPJEMP VARCHAR(18),
    PRLOTE VARCHAR(10),
    PRDCTO VARCHAR(15),
    PRCODMATRIZ INTEGER,
    PRDETALHE VARCHAR(250),
    PREMPRESAFILIAL INTEGER,
    PRCHAVEONLINE VARCHAR(120),
    PRTRANSACAO INTEGER,
    PRCLASSI_CC VARCHAR(40),
    PRNOMCTA VARCHAR(100))
AS
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WCTALONC VARCHAR(40);
DECLARE VARIABLE WNOMCTAC VARCHAR(100);
DECLARE VARIABLE WPARTICIPANTEC INTEGER;
DECLARE VARIABLE WCODTERCEIROC INTEGER;
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WSQL VARCHAR(8192);
DECLARE VARIABLE WCTALOND VARCHAR(40);
DECLARE VARIABLE WNOMCTAD VARCHAR(100);
DECLARE VARIABLE WPARTICIPANTED INTEGER;
DECLARE VARIABLE WCODTERCEIROD INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WTIPLAN INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WEMPRESAS VARCHAR(2000);
DECLARE VARIABLE WCODIGOAUX INTEGER;
DECLARE VARIABLE WCLASSIAUX VARCHAR(40);
DECLARE VARIABLE WVLRAUX NUMERIC(15,2);
DECLARE VARIABLE WIMPPERNA INTEGER;
DECLARE VARIABLE WDEBCRECC INTEGER;
DECLARE VARIABLE WREFANT INTEGER;
BEGIN
  WREFANT = rdb$get_context('USER_SESSION', 'W_ANOMES');
  EXECUTE PROCEDURE sp_seta_competencia(prrefemp, NULL, NULL);

  wdatini = SUBSTRING(CAST(prdatini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatfin AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatfin AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatfin AS VARCHAR(10)) FROM 1 FOR 4);

  wsql = '';
  wsql = wsql||'select tlan.BDCHAVE, tlan.BDDATA, ';
  wsql = wsql||'tlan.BDCREDITO, tlan.bdcodterceiroc, tplac.bdctalon, tplac.bdnomcta, tplac.bdparticipante, ';
  wsql = wsql||'tlan.BDDEBITO, tlan.bdcodterceirod, tplad.bdctalon, tplad.bdnomcta, tplad.bdparticipante, ';
  wsql = wsql||'tlan.BDCOMPL, thist.bdnome, tlan.bdcodemp, temp.bdnomemp, ';
  wsql = wsql||'temp.bdcnpjemp, tlan.bdlote, tlan.bddcto, temp.bdcodmatriz, tlan.bdtipolan, tlan.bdchaveonline, ';
  wsql = wsql||' tlan.bdtransacao, ';
  IF (prlcc = '') THEN
     wsql = wsql||'tlan.BDVALOR, null, NULL AS PRCLASSI_CC, null as bddebcre from vsuc_empresas_tlan tlan ';
  ELSE
     BEGIN
       wsql = wsql||'tlcc.BDVALOR, tlcc.bdcodtpcc, tpcc.BDCTALON, tlcc.bddebcre from vsuc_empresas_tlcc tlcc ';
       wsql = wsql||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
       wsql = wsql||'left outer join CENTROS_TPCC tpcc on (tpcc.BDCODCENTRO = tlcc.BDCODCENTRO and tpcc.BDCODTPCC = tlcc.BDCODTPCC) ';
     END
  wsql = wsql||'left outer join hist_tphi thist on (thist.bdcodhist = tlan.bdcodhist and thist.bdcodtphi = tlan.bdcodtphi) ';
  wsql = wsql||'left outer join planos_tpla tplac on (tplac.bdcodplapadrao = tlan.bdcodplapadrao and tplac.bdcodtpla = tlan.bdcredito) ';
  wsql = wsql||'left outer join planos_tpla tplad on (tplad.bdcodplapadrao = tlan.bdcodplapadrao and tplad.bdcodtpla = tlan.bddebito) ';
  wsql = wsql||'join vw_empresas_ref_atual temp on (temp.bdcodemp = tlan.bdcodemp) ';
  wsql = wsql||'where ';
  IF (prfiliais <> '') THEN
     wsql = wsql||'(tlan.bdcodemp in ('||TRIM(prfiliais)||')) and ';
  ELSE
     wsql = wsql||'(tlan.bdcodemp = '||prcodemp||') and ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'(tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) and ';
  IF (prlcc <> '') THEN
     wsql = wsql||'(tlcc.bdcodtpcc in ('||TRIM(prlcc)||')) and ';
  wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';
  IF (pragrupar = '') THEN
     wsql = wsql||'order by tlan.bddata, temp.bdcodemp';
  ELSE
     BEGIN
       wsql = wsql||'and tlan.bdtipolan not in ('||pragrupar||') ';
       wsql = wsql||'union all ';
       wsql = wsql||'select tlan.BDCHAVE, ';
       wsql = wsql||'       tlan.bddata, ';
       wsql = wsql||'       tlan.BDCREDITO, tlan.bdcodterceiroc, tplac.bdctalon, ';
       wsql = wsql||'       tplac.bdnomcta, tplac.bdparticipante, tlan.BDDEBITO, tlan.bdcodterceirod, tplad.bdctalon, ';
       wsql = wsql||'       tplad.bdnomcta, tplad.bdparticipante, tlan.BDCOMPL, tlan.bdnomehist, tlan.bdcodemp, ';
       wsql = wsql||'       tref.bdnomemp, temp.bdcnpjemp, tlan.bdlote, tlan.bddcto, temp.bdcodmatriz, ';
       wsql = wsql||'       tlan.bdtipolan, tlan.bdchaveonline, ';
       wsql = wsql||'       tlan.bdtransacao, tlan.BDVALOR, tlan.bdcodtpcc, null, null from tempresas temp ';
       wsql = wsql||'inner join vsuc_lancamentos_agrupados(';
       IF (prfiliais <> '') THEN
          wsql = wsql||''''||prfiliais||''''; --alt:11820 - 01/06/2015 - Adicionadas aspas para poder passar uma string com várias filiais. Pedro
       ELSE
          wsql = wsql||prcodemp;
       wsql = wsql||', '''||pragrupar||''', null, null,'||prcontabilizacao||', null, null, 1, ';
       IF (prlcc IS NULL OR prlcc = '') THEN
          wsql = wsql||' null) ';
       ELSE
          wsql = wsql||''''||TRIM(prlcc)||''') ';
       wsql = wsql||' tlan on (tlan.bdcodemp = temp.bdcodemp) ';
       wsql = wsql||'left outer join planos_tpla tplac on (tplac.bdcodplapadrao = tlan.bdcodplapadrao and tplac.bdcodtpla = tlan.bdcredito) ';
       wsql = wsql||'left outer join planos_tpla tplad on (tplad.bdcodplapadrao = tlan.bdcodplapadrao and tplad.bdcodtpla = tlan.bddebito) ';
       wsql = wsql||'left outer join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) where ';
       IF (prfiliais <> '') THEN
          wsql = wsql||'(tlan.bdcodemp in ('||TRIM(prfiliais)||')) and ';
       ELSE
          wsql = wsql||'(tlan.bdcodemp = '||prcodemp||') and ';
       -- A rotina vsuc_lancamentos_agrupados não tem o campo bdcontabilizacao e a contabilização é tratado lá dentro
       --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
       --if (prcontabilizacao <> 99) then
       --  wsql = wsql||'(tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) and ';
       wsql = wsql||'(tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';

     END

  /* laco dos lancamentos diario _____________________________________________*/
  prempresa = prcodemp;
  wempresas = prcodemp;
  IF (prfiliais <> '') THEN
    wempresas = prfiliais;

  FOR EXECUTE STATEMENT wsql
      INTO :prchave, :prdata,
           :prcodigo_credito, :wcodterceiroc, :wctalonc, :wnomctac, :wparticipantec,
           :prcodigo_debito, :wcodterceirod, :wctalond, :wnomctad, :wparticipanted,
           :prcomplemento, :prhistorico, :prempresafilial,
           :prnomeempresa, :prcnpjemp, :prlote, :prdcto, :prcodmatriz, :wtiplan, :prchaveonline,
           :prtransacao, :wvalor, :prcodtpcc, :PRCLASSI_CC, :wdebcrecc DO
      BEGIN
        -- Crédito
        prclassi_credito = wctalonc;
        IF ((wparticipantec = 1) AND (prdetalharctaparticipante = 1) AND (wcodterceiroc > 0)) THEN
          SELECT bdclassificacao, bdnome FROM vsuc_sp_nomenclatura_cta_partic(:wcodterceiroc,:wctalonc,0,:prrefemp) INTO :prclassi_credito,:wnomctac;
        -- Débito
        prclassi_debito  = wctalond;
        IF ((wparticipanted = 1) AND (prdetalharctaparticipante = 1) AND (wcodterceirod > 0)) THEN
          SELECT bdclassificacao, bdnome FROM vsuc_sp_nomenclatura_cta_partic(:wcodterceirod,:wctalond,0,:prrefemp) INTO :prclassi_debito,:wnomctad;

        IF (prlcc = '') THEN
           prcodtpcc = 0;

        /* diario modelo detalhado ___________________________________________*/
        IF (prmodelo = 1) THEN
           BEGIN
             --prhistorico = prcomplemento;
             /* lancamento a credito _________________________________________*/
             IF (((NOT prcodigo_credito IS NULL) OR (prcodigo_credito <> 0)) AND (coalesce(wdebcrecc, 1) = 1))  THEN
                BEGIN
                  --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodemp,:prempresafilial,:prmatrizfilialconsolidado,:wempresas) INTO :wpermite;
                  --IF (wpermite = 1) THEN
                  --  BEGIN
                      prvalor_credito = wvalor;
                      prvalor_debito  = NULL;
                      prdetalhe       = prcodigo_credito||' - '||prclassi_credito||' - '||wnomctac;
                      PRNOMCTA        = wnomctac;
                      SUSPEND;-- gilberto - 13/11/2012
                  --  END
                    END

              /* lancamento a debito _________________________________________*/
             IF (((NOT prcodigo_debito IS NULL) OR (prcodigo_debito <> 0)) AND (coalesce(wdebcrecc, 0) = 0))  THEN
                BEGIN
                  --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:prempresafilial,:prmatrizfilialconsolidado,:wempresas) INTO :wpermite;
                  --IF (wpermite = 1) THEN
                  --  BEGIN
                      prvalor_credito = NULL;
                      prvalor_debito  = wvalor;
                      prdetalhe       = prcodigo_debito||' - '||prclassi_debito||' - '||wnomctad;
                      PRNOMCTA = wnomctad;
                      SUSPEND;
                  --  END
                    END
                END
        ELSE
           /* diario modelo simplificado _____________________________________*/
           BEGIN
             wcodigoaux = 0;
             wclassiaux = '';
             wvlraux    = 0;
             wimpperna  = 0;

             prvalor_credito = wvalor;
             --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodemp,:prempresafilial,:prmatrizfilialconsolidado,:wempresas) INTO :wpermite;
             IF (prcodigo_credito IS NULL)  THEN
               BEGIN
                 prcodigo_credito = NULL;
                 prclassi_credito = '';
                 prvalor_credito  = NULL;
               END

             --alt:14634 - 27/05/2016 - Se o lançamento é um "lançar a" crédito, deve alterar a filial do lançamento, pois para o débito deve enxergar como um lançamento comum na matriz. Pedro
             prvalor_debito  = wvalor;
--             SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:prempresafilial,:prmatrizfilialconsolidado,:wempresas) INTO :wpermite;
             IF (prcodigo_debito IS NULL) THEN
               BEGIN
                 prcodigo_debito = NULL;
                 prclassi_debito = '';
                 prvalor_debito  = NULL;
               END

               SUSPEND;
           END
      END
   EXECUTE PROCEDURE SP_SETA_COMPETENCIA(wrefant);
END
^

/* Restore proc. body: VSUC_SP_RETORNA_MOV_DIARIO */
CREATE OR ALTER procedure VSUC_SP_RETORNA_MOV_DIARIO (
    PRCODEMP varchar(1024),
    PRCONTA integer,
    PRDATAINI date,
    PRDATAFIM date,
    PRREFEMP integer,
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRPARTICIPANTE integer)
returns (
    data date,
    DEB numeric(15,2),
    CRE numeric(15,2),
    SAL numeric(15,2),
    DEBANT numeric(15,2),
    CREANT numeric(15,2),
    SALANT numeric(15,2))
as
declare variable WSALAUX numeric(15,2);
declare variable WCODPLAPADRAO integer;
declare variable WGRUPOCONTA integer;
declare variable WSALDODEB numeric(15,2);
declare variable WSALDOCRE numeric(15,2);
declare variable WSQL varchar(10240);
declare variable WTAMANHO integer;
declare variable WCLASSIFICACAO varchar(50);
declare variable WLSTCTA varchar(8192);
declare variable WCODCTA integer;
declare variable WDATINI varchar(10);
declare variable WDATFIN varchar(10);
declare variable WCODEMP integer;
declare variable WDEBANT numeric(15,2);
declare variable WCREANT numeric(15,2);
declare variable WSALANT numeric(15,2);
declare variable WPOS integer;
declare variable WEMPPRINC integer;
declare variable WFILIAL integer;
declare variable WTIPOLANCFILIAL integer;
declare variable WTIPOLAN integer;
declare variable WVLR numeric(15,2);
declare variable WPERMITE integer;
declare variable WDATAAUX date;
declare variable WDATAANT date;
declare variable WPRIMEIROREG integer;
declare variable WPOS_PERNAMATRIZ integer;
declare variable WPOS_MATRIZ integer;
declare variable WPOS_FILIAL integer;
declare variable WCAMPO integer;
BEGIN
  wsaldocre      = 0;
  wsaldodeb      = 0;
  wtamanho       = 0;
  wclassificacao = '';

  -- retorna informações referente a conta selecionada _________________________
  wsql = 'select first 1 bdctalon, bdgrupocta, bdcodplapadrao ';
  wsql = wsql||'from PLANOS_TPLA  ';
  wsql = wsql||'where bdCODPLAPADRAO = (select first 1 tref.bdcodplapadrao ';
  wsql = wsql||'                        from tempresas_ref tref ';
  wsql = wsql||'                        where tref.bdcodemp in ('||prcodemp||')';
  wsql = wsql||'                        and tref.bdrefemp <= '||prrefemp;
  wsql = wsql||'                        order by tref.bdrefemp desc) ';
  wsql = wsql||'and (bdCODTPLA = '||prconta||') ';
  EXECUTE STATEMENT wsql
  INTO :wClassificacao, :wgrupoconta, :wcodplapadrao;
  -- retorna a quantidade de caracteres da conta longa selecionada _____________
  wtamanho = strlen(wclassificacao);
  -- retorno dos códigos das contas selecionadas _______________________________
  wsql = 'select tpla.bdcodtpla from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
  wsql = wsql||' and substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''' ';
  wsql = wsql||'and ((TPLA.BDTIPCTA = 1) or (TPLA.BDTIPCTA is null)) ';
  wsql = wsql||'order by tpla.bdctalon';

  wlstcta = '';
  FOR EXECUTE STATEMENT wsql INTO :wcodcta DO
     BEGIN
       wlstcta = wlstcta||TRIM(CAST(wcodcta AS VARCHAR(10)))||',';
     END
  wlstcta = SUBSTRING(wlstcta FROM 1 FOR strlen(wlstcta)-1);
  -- formatação das datas para serem usadas no sql _____________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);
  -- sql para ser executado no laço ____________________________________________
  --#alt:5837.
  /*wsql = 'SELECT SUM(CASE ';
  wsql = wsql||'             WHEN (tlan.bdcredito in ('||wlstcta||')) THEN ';
  wsql = wsql||'               TLAN.BDVALOR ';
  wsql = wsql||'             ELSE ';
  wsql = wsql||'               0 ';
  wsql = wsql||'           end) AS "SALDEB", ';
  wsql = wsql||'       sum(case ';
  wsql = wsql||'             when (tlan.bddebito in ('||wlstcta||')) then ';
  wsql = wsql||'               TLAN.BDVALOR ';
  wsql = wsql||'             else ';
  wsql = wsql||'               0 ';
  wsql = wsql||'           end) AS "SALCRE", ';
  wsql = wsql||'       tlan.bddata "DATA" ';
  wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';
  wsql = wsql||'where (tlan.bdcodemp in ('||prcodemp||')) ';
  wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  wsql = wsql||'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';
  wsql = wsql||'and (TLAN.BDDATA between '''||wdatini||''' and '''||wdatfin||''') ';
  wsql = wsql||'and ((tlan.bdcredito in ('||wlstcta||')) or (tlan.bddebito in ('||wlstcta||'))) ';
  wsql = wsql||'Group By tlan.bddata ';
  wsql = wsql||'Order by tlan.bddata Asc '; */
  --Retorna a empresa principal
  SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
  IF (wpos = 0) THEN
    wempprinc = prcodemp;
  ELSE
    wempprinc = SUBSTRING(prcodemp FROM 1 FOR (wpos - 1));

  wsql = 'Select * from (';
  wsql = wsql||'SELECT tlan.bdcodemp,1 as bdtipolanc,tlan.bddata "DATA",';
  wsql = wsql||'SUM(CASE WHEN (tlan.bddebito in ('||wlstcta||')) THEN TLAN.BDVALOR ELSE 0 end) AS "SALDEB" ';
  wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';
  wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||wcodplapadrao||') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  wsql = wsql||'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';
  wsql = wsql||'and (tlan.bddebito in ('||wlstcta||')) ';
  wsql = wsql||'and (TLAN.BDDATA between '''||wdatini||''' and '''||wdatfin||''') ';
  wsql = wsql||'and (tlan.bdcodemp in ('||prcodemp||')) ';
  if (PRPARTICIPANTE <> 0) then
     wsql = wsql||'and (tlan.bdcodterceirod in ('||PRPARTICIPANTE||')) ';
  wsql = wsql||'Group By tlan.bdcodemp,bdtipolanc,tlan.bddata';
  wsql = wsql||' union all ';
  wsql = wsql||'SELECT tlan.bdcodemp,2 as bdtipolanc,tlan.bddata "DATA",';
  wsql = wsql||'SUM(CASE WHEN (tlan.bdcredito in ('||wlstcta||')) THEN TLAN.BDVALOR ELSE 0 end) AS "SALCRE" ';
  wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';
  wsql = wsql||'where (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  wsql = wsql||'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';
  wsql = wsql||'and (tlan.bdcredito in ('||wlstcta||')) ';
  wsql = wsql||'and (TLAN.BDDATA between '''||wdatini||''' and '''||wdatfin||''') ';
  wsql = wsql||'and (tlan.bdcodemp in ('||prcodemp||')) ';
  if (PRPARTICIPANTE <> 0) then
     wsql = wsql||'and (tlan.bdcodterceiroc in ('||PRPARTICIPANTE||')) ';
  wsql = wsql||'Group By tlan.bdcodemp,bdtipolanc,tlan.bddata';
  wsql = wsql||') Order by data Asc';

  sal = 0;
  -- verifica se a data atual é a data inicial, para calcular os saldos anteriores
  FOR EXECUTE STATEMENT
    'SELECT bdcodemp FROM tempresas WHERE bdcodemp IN (' || prcodemp || ')'
    INTO :wcodemp DO
    BEGIN
      IF (PRPARTICIPANTE <> 0) THEN
      BEGIN
        SELECT
        SUM(BDSALDO_DEB), SUM(BDSALDO_CRE), SUM(BDSALDO_ATUAL), SUM(BDSALDO_ANT_DEB), SUM(BDSALDO_ANT_CRE), SUM(BDSALDO_ANTERIOR)
        FROM vsuc_sp_retorna_saldos_ctaparty(
              :wcodemp, :wcodplapadrao, :PRDATAINI, :PRDATAINI,
              :prconta, 0, 0, :prparticipante, 0, :prcodemp,
              :prcontabilizacao, 1, '', 0, 0, 0, 0, :prrefemp)
        INTO :wsaldodeb, :wsaldocre, :wsalaux, :wdebant, :wcreant, :wsalant;
      END
      ELSE
      BEGIN
        SELECT
            SALDO_DEB, SALDO_CRE, Saldo_Atual,
            Saldo_Ant_Deb, Saldo_Ant_Cre, Saldo_Anterior
        FROM sp_retorna_saldo_emp_x(
            :wcodemp, :prconta, :PRDATAINI, :PRDATAINI,
            0, 0, NULL, NULL, :prrefemp, 0, :prcontabilizacao,
            :prmatrizfilialconsolidado, :PRPARTICIPANTE, :prparticipante)
        INTO :wsaldodeb, :wsaldocre, :wsalaux, :wdebant, :wcreant, :wsalant;
      END
    
      deb     = COALESCE(deb, 0)     + COALESCE(wsaldodeb, 0);
      cre     = COALESCE(cre, 0)     + COALESCE(wsaldocre, 0);
      sal     = COALESCE(sal, 0)     + COALESCE(wsalant, 0);
      debant  = COALESCE(debant, 0)  + COALESCE(wdebant, 0);
      creant  = COALESCE(creant, 0)  + COALESCE(wcreant, 0);
      salant  = COALESCE(salant, 0)  + COALESCE(wsalant, 0);
    END
  --#alt:5837.
  wdataant     = NULL;
  wprimeiroreg = 1;
  deb = 0;
  cre = 0;
  --for execute statement wsql into :wsaldocre, :wsaldodeb, :data do
  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wtipolan,:wdataaux,:wvlr  DO
    BEGIN
      IF ((wdataant <> wdataaux) AND (wprimeiroreg = 0)) THEN
        BEGIN
          SUSPEND;
          deb = 0;
          cre = 0;
        END
      data = wdataaux;

--      select bdpermite from vsuc_sp_permitecalcsaldolancmf(:wtipolan,:wempprinc,:wcodemp,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
        --alt:#6524 - implementado rotina "POS" aqui, por questão de desempenho, precisa apenas uma vez para as duas verificações
        -- IF (NOT ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0))) THEN
           -- BEGIN
             -- wpos_pernamatriz = POSITION(prcodemp, wcodemp);
             -- wpos_matriz = POSITION(wcodemp,  prcodemp);
             -- wpos_filial = POSITION(wfilial,  prcodemp);
          -- END
        wpermite = 0;
        --alt:#6524 - implementado rotina "VSUC_SP_PERMITECALCSALDOLANCMF" diretamente aqui, por questão de desempenho
        --select bdpermite from vsuc_sp_permitecalcsaldolancmf(1,:wempprinc,:prempresa,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
        -- IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
           wpermite = 1;
        -- ELSE
           -- BEGIN
             -- --#Alt:14975 (30/06/2016) - Foi setado a variável wtipolan para a wcampo e alterado de prcodemp para wempprinc no controle do "Lançar a". Com as
             -- --variáveis anteriores ocorria erro e não iria fazer o controle corretamente.
             -- --wcampo = wtipolancfilial;
             -- wcampo = wtipolan;
             -- IF (((wempprinc = wcodemp) AND (wfilial = 0)) OR
                 -- --Estou na filial mas o lançamento foi feito na matriz para a filial(uma perna)
                 -- ((wempprinc = wfilial) AND (wcampo = wtipolancfilial)) OR
                 -- --Estou na matriz e tem uma perna do lançamento na filial, mas só quero os lançamentos da matriz(a perna da matriz) e que a matriz esteja no filtro
                 -- ((wempprinc = wcodemp) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
                 -- --Estou na matriz mas também quero os lançamentos da filial conforme o filtro(Lançamentos que foram feito na filial -> BDCODEMP = Filial)
                 -- ((prmatrizfilialconsolidado = 1) AND (wempprinc <> wcodemp) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
                 -- --Estou na matriz mas também quero a perna que está na filial conforme o filtro
                 -- ((prmatrizfilialconsolidado = 1) AND (wempprinc = wcodemp) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
                -- wpermite = 1;
           -- END

      IF (wpermite = 1) THEN
        BEGIN
          IF (wvlr IS NULL) THEN
            wvlr = 0;
          wsaldodeb = wvlr;
          wsaldocre = 0;
          IF (wtipolan = 2) THEN--Crédito
            BEGIN
              wsaldodeb = 0;
              wsaldocre = wvlr;
            END
          -- aplicação da regra contabilista _____________________________________
          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
            wsalaux = sal + (wsaldodeb - wsaldocre);
          ELSE
          IF ((wgrupoconta = 1) OR (wgrupoconta = 2) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
            wsalaux = sal + (wsaldocre - wsaldodeb);
          --wsalaux = sal + (wsaldodeb - wsaldocre);

          deb = deb + wsaldodeb;
          cre = cre + wsaldocre;

          sal = wsalaux;
          --#alt:5837.
          --suspend;
        END
      wdataant     = data;
      wprimeiroreg = 0;
    END
  IF (wdataant IS NOT NULL) THEN
    SUSPEND;
END
^

/* Restore proc. body: VSUC_SP_RETORNA_MOV_MENSAL */
create or alter procedure VSUC_SP_RETORNA_MOV_MENSAL (
    PRCODEMP integer,
    PRCONTA integer,
    PRCC varchar(8192),
    PRANOINICIAL integer,
    PRANOFINAL integer,
    PRREFEMP integer,
    PRPARTICIPANTE integer,
    PRIGNORAZERAMENTO integer,
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer)
returns (
    BDDEB01 numeric(15,2),
    BDDEB02 numeric(15,2),
    BDDEB03 numeric(15,2),
    BDDEB04 numeric(15,2),
    BDDEB05 numeric(15,2),
    BDDEB06 numeric(15,2),
    BDDEB07 numeric(15,2),
    BDDEB08 numeric(15,2),
    BDDEB09 numeric(15,2),
    BDDEB10 numeric(15,2),
    BDDEB11 numeric(15,2),
    BDDEB12 numeric(15,2),
    BDCRE01 numeric(15,2),
    BDCRE02 numeric(15,2),
    BDCRE03 numeric(15,2),
    BDCRE04 numeric(15,2),
    BDCRE05 numeric(15,2),
    BDCRE06 numeric(15,2),
    BDCRE07 numeric(15,2),
    BDCRE08 numeric(15,2),
    BDCRE09 numeric(15,2),
    BDCRE10 numeric(15,2),
    BDCRE11 numeric(15,2),
    BDCRE12 numeric(15,2),
    BDMOV01 numeric(15,2),
    BDMOV02 numeric(15,2),
    BDMOV03 numeric(15,2),
    BDMOV04 numeric(15,2),
    BDMOV05 numeric(15,2),
    BDMOV06 numeric(15,2),
    BDMOV07 numeric(15,2),
    BDMOV08 numeric(15,2),
    BDMOV09 numeric(15,2),
    BDMOV10 numeric(15,2),
    BDMOV11 numeric(15,2),
    BDMOV12 numeric(15,2),
    BDSAL01 numeric(15,2),
    BDSAL02 numeric(15,2),
    BDSAL03 numeric(15,2),
    BDSAL04 numeric(15,2),
    BDSAL05 numeric(15,2),
    BDSAL06 numeric(15,2),
    BDSAL07 numeric(15,2),
    BDSAL08 numeric(15,2),
    BDSAL09 numeric(15,2),
    BDSAL10 numeric(15,2),
    BDSAL11 numeric(15,2),
    BDSAL12 numeric(15,2),
    BDSALTOTDEB numeric(15,2),
    BDSALTOTCRE numeric(15,2),
    BDSALTOTMOV numeric(15,2),
    BDSALTOTATU numeric(15,2),
    BDANO integer,
    BDDEBANT numeric(15,2),
    BDCREANT numeric(15,2),
    BDMOVANT numeric(15,2),
    BDSALANT numeric(15,2),
    BDGRPCTA integer)
as
declare variable WDATAINI varchar(10);
declare variable WDATAFIM varchar(10);
declare variable WCOUNT integer;
declare variable WANOINICIAL varchar(4);
declare variable WGRUPOCONTA integer;
declare variable WCODPLAPADRAO integer;
declare variable WCOUNT1 integer;
declare variable WTAM integer;
declare variable WCTALON varchar(40);
declare variable WSQL varchar(10240);
declare variable WDEB numeric(15,2);
declare variable WCRE numeric(15,2);
declare variable WREF varchar(6);
declare variable WSALATU numeric(15,2);
declare variable WLSTCTA varchar(8192);
declare variable WCODCTA integer;
declare variable WCODEMP integer;
declare variable WFILIAL integer;
declare variable WTIPOLANCFILIAL integer;
declare variable WTIPOLAN integer;
declare variable WVLR numeric(15,2);
declare variable WPERMITE integer;
declare variable WPOS_PERNAMATRIZ integer;
declare variable WPOS_MATRIZ integer;
declare variable WPOS_FILIAL integer;
declare variable WCAMPO integer;
BEGIN
  bdsaltotdeb = 0;
  bdsaltotcre = 0;
  bdsaltotmov = 0;
  bdsaltotatu = 0;
  wgrupoconta = 0;
  wcodplapadrao = 0;


  SELECT bdgrupocta, strlen(bdctalon), bdctalon, bdcodplapadrao
  FROM PLANOS_TPLA
  WHERE bdCODPLAPADRAO = (SELECT FIRST 1 tref.bdcodplapadrao
                          FROM tempresas_ref tref
                          WHERE tref.bdcodemp = :prcodemp
                          AND tref.bdrefemp <= :prrefemp
                          ORDER BY tref.bdrefemp DESC)
  AND (bdCODTPLA = :prconta)
  INTO :wgrupoconta, :wtam, :wctalon, wcodplapadrao;

  wcount = 0;
  WHILE (wcount <= pranofinal - pranoinicial) DO
    BEGIN
      BDANO = :pranoinicial + :wcount;

      SELECT CAST(:pranoinicial+:wcount AS VARCHAR(4)) AS C_ANO_INI FROM RDB$DataBase INTO :wAnoinicial;

      wdataini = '01/'||'01/'||:wanoinicial;
      wdatafim = '01/'||'31/'||:wanoinicial;

      --alt:9801 - Alterado para fazer o select mesmo que não tenha movimento no ano informado, pois a pedido da solicitação, deve trazer pelo menos o saldo anterior neste caso. Pedro

      /* Feito select para saber se existe lançamento no ano atual.
         Se tiver, continua a rotina calculando os saldos mes a mes..
         Caso contrário, zera variáveis e passa para próximo ano.*/
      /*select count(bdChave) from vsuc_empresas_tlan
      where (bdCodEmp = :prcodemp)
-- #alt:6470 - gilberto - 16/08/2013 ___________________________________________
--      and (bdData >= '01/01/'||:wanoinicial)
--      and (bdData <= '12/31/'||:wanoinicial) into :wcount1;
      and substring(bddata from 1 for 4) = :wanoinicial into :wcount1;*/
---------------------------------------------------------------------- #alt:6470
      /*if (wcount1 = 0) then
         begin
            wcount = wcount + 1;

            bddeb01 = 0;
            bddeb02 = 0;
            bddeb03 = 0;
            bddeb04 = 0;
            bddeb05 = 0;
            bddeb06 = 0;
            bddeb07 = 0;
            bddeb08 = 0;
            bddeb09 = 0;
            bddeb10 = 0;
            bddeb11 = 0;
            bddeb12 = 0;

            bdcre01 = 0;
            bdcre02 = 0;
            bdcre03 = 0;
            bdcre04 = 0;
            bdcre05 = 0;
            bdcre06 = 0;
            bdcre07 = 0;
            bdcre08 = 0;
            bdcre09 = 0;
            bdcre10 = 0;
            bdcre11 = 0;
            bdcre12 = 0;

            --alt:9515 - Adicionados campos do movimento. Pedro
            bdmov01 = 0;
            bdmov02 = 0;
            bdmov03 = 0;
            bdmov04 = 0;
            bdmov05 = 0;
            bdmov06 = 0;
            bdmov07 = 0;
            bdmov08 = 0;
            bdmov09 = 0;
            bdmov10 = 0;
            bdmov11 = 0;
            bdmov12 = 0;

            bdsal01 = 0;
            bdsal02 = 0;
            bdsal03 = 0;
            bdsal04 = 0;
            bdsal05 = 0;
            bdsal06 = 0;
            bdsal07 = 0;
            bdsal08 = 0;
            bdsal09 = 0;
            bdsal10 = 0;
            bdsal11 = 0;
            bdsal12 = 0;

            suspend;
         end
      else
         begin*/
      --alt:9801 - Fim
              -- Mês 01
              IF ((prparticipante = 0) OR (prparticipante IS NULL)) THEN
                BEGIN
                  SELECT SALDO_DEB, SALDO_CRE, MOVIMENTO, Saldo_Atual, Saldo_Ant_Deb, Saldo_Ant_Cre, Saldo_Anterior
                  FROM sp_retorna_saldo_emp_x(:prcodemp, :prconta, :wdataini, :wdatafim, 0, :prignorazeramento, :prcc, NULL, :prrefemp,0,:prcontabilizacao,:prmatrizfilialconsolidado)
                  INTO :bddeb01, :bdcre01, :bdmov01, bdsal01, bddebant, bdcreant, bdsalant;
                END
              ELSE
                BEGIN
                  SELECT SUM(BDSALDO_DEB), SUM(BDSALDO_CRE), SUM(BDMOVIMENTO), SUM(BDSALDO_ATUAL), SUM(BDSALDO_ANT_DEB), SUM(BDSALDO_ANT_CRE), SUM(BDSALDO_ANTERIOR)
                  --from VSUC_SP_RETORNA_SALDOS_CTA_PART(:prcodemp,:wcodplapadrao, :wdataini, :wdatafim, :prconta, :prignorazeramento, -- alt:#6647 - gilberto - 12/09/2013
                  FROM vsuc_sp_retorna_saldos_ctaparty(:prcodemp,:wcodplapadrao, :wdataini, :wdatafim, :prconta, 0, :prignorazeramento,
                                                       :prparticipante, 0,:prcodemp,:prcontabilizacao, 
                                                        1, '', 0, 0, 0, 0, :prrefemp) --alt:13972 - 20/06/2016 - Precisa agrupar por CNPJ, senão virão 2 registros quando há "lançar a". Pedro
                  INTO :bddeb01, :bdcre01, :bdmov01, bdsal01, bddebant, bdcreant, bdsalant;
                END

              wsalatu = COALESCE(bdsalant, 0);
/*
              bddeb01 = 0;
              bddeb02 = 0;
              bddeb03 = 0;
              bddeb04 = 0;
              bddeb05 = 0;
              bddeb06 = 0;
              bddeb07 = 0;
              bddeb08 = 0;
              bddeb09 = 0;
              bddeb10 = 0;
              bddeb11 = 0;
              bddeb12 = 0;
    
              bdcre01 = 0;
              bdcre02 = 0;
              bdcre03 = 0;
              bdcre04 = 0;
              bdcre05 = 0;
              bdcre06 = 0;
              bdcre07 = 0;
              bdcre08 = 0;
              bdcre09 = 0;
              bdcre10 = 0;
              bdcre11 = 0;
              bdcre12 = 0;
*/
              --alt:9515 - Retirado, pois não será mais utilizada essa lista de contas.
              --Além de tornar o processo muito lento ela excede facilmente o limite de caracteres do wSQL.
              --Com ela, essa rotina demorava 10 segundos na RN, agora leva apenas 1 segundo. Pedro
              /*wsql = '';
              wsql = wsql||'select tpla.bdcodtpla from planos_tpla tpla ';
              wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
              wsql = wsql||' and substring(tpla.BDCTALON FROM 1 FOR '||wtam||') = '''||wctalon||''' ';
              wsql = wsql||'order by tpla.bdctalon';

              wlstcta = '';
              for execute statement wsql into :wcodcta do
                 begin
                   wlstcta = wlstcta||trim(cast(wcodcta as varchar(10)))||',';
                 end
              wlstcta = substring(wlstcta from 1 for strlen(wlstcta)-1);*/
              --alt:9515 - Fim

              wsql = 'Select * from (';
              --#alt:5837
              /*wsql = wsql||'SELECT ';
              if ((prparticipante = 0) or (prparticipante is null)) then
                begin
                  wsql = wsql||'   SUM(CASE WHEN (tlan.bdcredito in ('||wlstcta||')) THEN TLAN.BDVALOR ELSE 0 end) AS SALCRE, ';
                  wsql = wsql||'   SUM(case when (tlan.bddebito in ('||wlstcta||')) then TLAN.BDVALOR else 0 end) AS SALDEB, ';
                end
              else
                begin
                  wsql = wsql||'   SUM(CASE WHEN ((tlan.bdcredito in ('||wlstcta||')) and (tlan.BDCODTERCEIROC = '|| :prparticipante ||')) THEN TLAN.BDVALOR ELSE 0 end) AS SALCRE, ';
                  wsql = wsql||'   SUM(case when ((tlan.bddebito in ('||wlstcta||')) and (tlan.BDCODTERCEIROD = '|| :prparticipante ||')) then TLAN.BDVALOR else 0 end) AS SALDEB, ';
                end
              wsql = wsql||'       (substring(bddata from 1 for 4)||substring(bddata from 6 for 2)) as Referencia ';
              wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';
              wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
              wsql = wsql||'and (tlan.bdcodplapadrao = '||wcodplapadrao||') ';
              if (prignorazeramento <> 1) then
                 wsql = wsql||'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';
              wsql = wsql||'and (substring(cast(TLAN.BDDATA as varchar(10)) from 1 for 4) = '''||wanoinicial||''') ';
              wsql = wsql||'and ((tlan.bdcredito in ('||wlstcta||')) or (tlan.bddebito in ('||wlstcta||'))) ';
              wsql = wsql||'Group By Referencia ';
              wsql = wsql||'Order by Referencia Asc ';*/

              --Débito
              wsql = wsql||'SELECT tlan.bdcodemp, 1 as bdtipolan,(substring(bddata from 1 for 4)||substring(bddata from 6 for 2)) as Referencia, ';

              --alt:9515 - Comentado porque não vai mais utilizar a lista de contas e a checagem por este método não é adequada. Mais detalhes acima. Pedro
              /*if ((prparticipante = 0) or (prparticipante is null)) then
                wsql = wsql||'SUM(case when (tlan.bddebito in ('||wlstcta||')) then TLAN.BDVALOR else 0 end) AS SALDEB ';
              else
                wsql = wsql||'SUM(case when ((tlan.bddebito in ('||wlstcta||')) and (tlan.BDCODTERCEIROD = '|| :prparticipante ||')) then TLAN.BDVALOR else 0 end) AS SALDEB ';*/

              --#Alt:14968 (01/07/2016) - Incluído a condição para buscar o valor da TLCC quando tem centro de custo informado. Carlos Mello
              IF ((prCC IS NOT NULL) AND (prCC <> '')) THEN
                wsql = wsql||'sum(TLCC.BDVALOR) AS SALDEB ';
              ELSE
                wsql = wsql||'sum(TLAN.BDVALOR) AS SALDEB ';
              --alt:9515 - Fim

              wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';

              --alt:13972 - 19/05/2016 - Adicionado filtro por centro de custo. Pedro
              IF ((prCC IS NOT NULL) AND (prCC <> '')) THEN
                wSQL = wSQL||'inner join VSUC_EMPRESAS_TLCC tlcc on (tlcc.BDCODEMP = tlan.BDCODEMP and tlcc.BDCHAVE = tlan.BDCHAVE and tlcc.BDDEBCRE = 0 and tlcc.BDCODTPCC in ('||prCC||')) ';

              --alt:9515 - Adicionado inner join das contas para poder filtrar pela classificação. Pedro
              wsql = wsql||'inner join PLANOS_TPLA TPLA on (TPLA.BDCODTPLA = TLAN.BDDEBITO and TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO) ';
              wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||wcodplapadrao||') ';

              IF (prignorazeramento <> 1) THEN
                 wsql = wsql||'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';

              --alt:9515 - Retirada a validação da lista de contas e adicionada pela classificação
              --e a do terceiro que também era feito na parte do select. Mais detalhes acima. Pedro
              --wsql = wsql||'and (tlan.bddebito in ('||wlstcta||')) ';
              wsql = wsql||'and (substring(TPLA.BDCTALON from 1 for '||wtam||') = '''||wctalon||''') ';

              IF ((prparticipante <> 0) AND (prparticipante IS NOT NULL)) THEN
                wsql = wsql||'and (tlan.BDCODTERCEIROD = '|| :prparticipante ||') ';
              --alt:9515 - Fim

              --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
              IF (prcontabilizacao <> 99) THEN
                wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
              wsql = wsql||'and (substring(cast(TLAN.BDDATA as varchar(10)) from 1 for 4) = '''||wanoinicial||''') ';

              --alt:9515 - Alterado para pegar corretamente os lançamentos com a regra de "lançar a". Pedro
              --wsql = wsql||'and (tlan.bdcodemp = '||prcodemp||') ';
              wsql = wsql||'and (tlan.bdcodemp = '||prcodemp||') ';

              wsql = wsql||'Group By tlan.BDCODEMP, BDTIPOLAN, REFERENCIA ';
              wsql = wsql||' union all ';

              --Crédito
              wsql = wsql||'SELECT tlan.bdcodemp, 2 as bdtipolan,(substring(bddata from 1 for 4)||substring(bddata from 6 for 2)) as Referencia, ';

              --alt:9515 - Comentado porque não vai mais utilizar a lista de contas e a checagem por este método não é adequada. Mais detalhes acima. Pedro
              /*if ((prparticipante = 0) or (prparticipante is null)) then
                wsql = wsql||'SUM(case when (tlan.bdcredito in ('||wlstcta||')) then TLAN.BDVALOR else 0 end) AS SALCRE ';
              else
                wsql = wsql||'SUM(case when ((tlan.bdcredito in ('||wlstcta||')) and (tlan.BDCODTERCEIROC = '|| :prparticipante ||')) then TLAN.BDVALOR else 0 end) AS SALCRE ';*/

              --#Alt:14968 (01/07/2016) - Incluído a condição para buscar o valor da TLCC quando tem centro de custo informado. Carlos Mello
              IF ((prCC IS NOT NULL) AND (prCC <> '')) THEN
                wsql = wsql||'sum(TLCC.BDVALOR) AS SALCRE ';
              ELSE
                wsql = wsql||'sum(TLAN.BDVALOR) AS SALCRE ';
              --alt:9515 - Fim

              wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';

              --alt:13972 - 19/05/2016 - Adicionado filtro por centro de custo. Pedro
              IF ((prCC IS NOT NULL) AND (prCC <> '')) THEN
                wSQL = wSQL||'inner join VSUC_EMPRESAS_TLCC tlcc on (tlcc.BDCODEMP = tlan.BDCODEMP and tlcc.BDCHAVE = tlan.BDCHAVE and tlcc.BDDEBCRE = 1 and tlcc.BDCODTPCC in ('||prCC||')) ';

              --alt:9515 - Adicionado inner join das contas para poder filtrar pela classificação. Pedro
              wsql = wsql||'inner join PLANOS_TPLA TPLA on (TPLA.BDCODTPLA = TLAN.BDCREDITO and TPLA.BDCODPLAPADRAO = TLAN.BDCODPLAPADRAO) ';
              wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||wcodplapadrao||') ';
              IF (prignorazeramento <> 1) THEN
                 wsql = wsql||'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL)) ';

              --alt:9515 - Retirada a validação da lista de contas e adicionada pela classificação
              --e a do terceiro que também era feito na parte do select. Mais detalhes acima. Pedro
              --wsql = wsql||'and (tlan.bdcredito in ('||wlstcta||')) ';
              wsql = wsql||'and (substring(TPLA.BDCTALON from 1 for '||wtam||') = '''||wctalon||''') ';

              IF ((prparticipante <> 0) AND (prparticipante IS NOT NULL)) THEN
                wsql = wsql||'and (tlan.BDCODTERCEIROC = '|| :prparticipante ||') ';
              --alt:9515 - Fim

              --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
              IF (prcontabilizacao <> 99) THEN
                wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
              wsql = wsql||'and (substring(cast(TLAN.BDDATA as varchar(10)) from 1 for 4) = '''||wanoinicial||''') ';

              --alt:9515 - Alterado para pegar corretamente os lançamentos com a regra de "lançar a". Pedro
              --wsql = wsql||'and ((tlan.bdcodemp = '||prcodemp||') or (tlan.bdfilial = '||prcodemp||')) ';
              wsql = wsql||'and (tlan.bdcodemp = '||prcodemp||') ';

              wsql = wsql||'Group By tlan.BDCODEMP, BDTIPOLAN, REFERENCIA ';
              wsql = wsql||') Order by Referencia Asc ';

              FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wtipolan,:wref,:wvlr DO
                BEGIN
--                  select bdpermite from vsuc_sp_permitecalcsaldolancmf(:wtipolan,:prcodemp,      :wcodemp,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
                  --alt:#6524 - implementado rotina "POS" aqui, por questão de desempenho, precisa apenas uma vez para as duas verificações
                  -- IF (NOT ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0))) THEN
                     -- BEGIN
                       -- wpos_pernamatriz = POSITION(prcodemp, wcodemp);
                       -- wpos_matriz = POSITION(wcodemp,  prcodemp);
                       -- wpos_filial = POSITION(wfilial,  prcodemp);
                    -- END
                  wpermite = 0;
                  --alt:#6524 - implementado rotina "VSUC_SP_PERMITECALCSALDOLANCMF" diretamente aqui, por questão de desempenho
                  --select bdpermite from vsuc_sp_permitecalcsaldolancmf(1,:wempprinc,:prempresa,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
                  -- IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
                     wpermite = 1;
                  -- ELSE
                     -- BEGIN
                       -- --alt:9515 - Alterado porque aqui deve passar o tipo da conta, e não do lançamento na filial, ainda mais que ele vai comparar o wcampo com o wtipolancfilial.
                       -- --Como o wcampo recebe do wtipolancfilial e o wcampo é comparado com o wtipolancfilial, abaixo estaria como fazer "wtipolancfilial = wtipolancfilial"
                       -- --e "wtipolancfilial <> wtipolancfilial". Como essas validações não funcionavam corretamente, não retornava os valores corretos. Pedro
                       -- --wcampo = wtipolancfilial;
                       -- wcampo = wtipolan;
                       -- IF (((prcodemp = wcodemp) AND (wfilial = 0)) OR
                           -- --Estou na filial mas o lançamento foi feito na matriz para a filial(uma perna)
                           -- ((prcodemp = wfilial) AND (wcampo = wtipolancfilial)) OR
                           -- --Estou na matriz e tem uma perna do lançamento na filial, mas só quero os lançamentos da matriz(a perna da matriz) e que a matriz esteja no filtro
                           -- ((prcodemp = wcodemp) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
                           -- --Estou na matriz mas também quero os lançamentos da filial conforme o filtro(Lançamentos que foram feito na filial -> BDCODEMP = Filial)
                           -- ((prmatrizfilialconsolidado = 1) AND (prcodemp <> wcodemp) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
                           -- --Estou na matriz mas também quero a perna que está na filial conforme o filtro
                           -- ((prmatrizfilialconsolidado = 1) AND (prcodemp = wcodemp) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
                          -- wpermite = 1;
                     -- END

                  IF (wpermite = 1) THEN
                    BEGIN
                      /*if (wdeb is null) then
                         wdeb = 0;
                      if (wcre is null) then
                       wcre = 0;*/
                      IF (wvlr IS NULL) THEN
                        wvlr = 0;
                      wdeb = wvlr;
                      wcre = 0;
                      IF (wtipolan = 2) THEN--Crédito
                        BEGIN
                          wdeb = 0;
                          wcre = wvlr;
                        END

                      IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                        wsalatu = COALESCE(wsalatu, 0) + (COALESCE(wdeb, 0) - COALESCE(wcre, 0));
                      ELSE
                      IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                        wsalatu = COALESCE(wsalatu, 0) + (COALESCE(wcre, 0) - COALESCE(wdeb, 0));
-- #alt:6470 - gilberto - 20/08/2013
/*                      if (substring(wref from 5 for 2) = '01') then
                        begin
                          bddeb01 = coalesce(bddeb01, 0) + wdeb;
                          bdcre01 = coalesce(bdcre01, 0) + wcre;
                          bdsal01 = coalesce(bdsal01, 0) + wsalatu;

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          if ((wgrupoconta = 0) or (wgrupoconta = 4) or (wgrupoconta = 5))  then -- ATIVO e DESPESAS
                            bdmov01 = coalesce(bdmov01, 0.00) + (coalesce(wdeb, 0.00) - coalesce(wcre, 0.00));
                          else
                          if ((wgrupoconta = 1) or (wgrupoconta = 3)) then -- PASSIVO e RECEITAS
                            bdmov01 = coalesce(bdmov01, 0.00) + (coalesce(wcre, 0.00) - coalesce(wdeb, 0.00));
                        end
                      else */
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '02') THEN
                        BEGIN
                          bddeb02 = COALESCE(bddeb02, 0) + COALESCE(wdeb, 0);
                          bdcre02 = COALESCE(bdcre02, 0) + COALESCE(wcre, 0);
                          bdsal02 = COALESCE(bdsal02, 0) + COALESCE(wsalatu, 0);

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov02 = COALESCE(bdmov02, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov02 = COALESCE(bdmov02, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '03') THEN
                        BEGIN
                          bddeb03 = COALESCE(bddeb03, 0) + COALESCE(wdeb, 0);
                          bdcre03 = COALESCE(bdcre03, 0) + COALESCE(wcre, 0);
                          bdsal03 = COALESCE(bdsal03, 0) + COALESCE(wsalatu, 0);   

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov03 = COALESCE(bdmov03, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov03 = COALESCE(bdmov03, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '04') THEN
                        BEGIN
                          bddeb04 = COALESCE(bddeb04, 0) + COALESCE(wdeb, 0);
                          bdcre04 = COALESCE(bdcre04, 0) + COALESCE(wcre, 0);
                          bdsal04 = COALESCE(bdsal04, 0) + COALESCE(wsalatu, 0);   

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov04 = COALESCE(bdmov04, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov04 = COALESCE(bdmov04, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '05') THEN
                        BEGIN
                          bddeb05 = COALESCE(bddeb05, 0) + COALESCE(wdeb, 0);
                          bdcre05 = COALESCE(bdcre05, 0) + COALESCE(wcre, 0);
                          bdsal05 = COALESCE(bdsal05, 0) + COALESCE(wsalatu, 0);   

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov05 = COALESCE(bdmov05, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov05 = COALESCE(bdmov05, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '06') THEN
                        BEGIN
                          bddeb06 = COALESCE(bddeb06, 0) + COALESCE(wdeb, 0);
                          bdcre06 = COALESCE(bdcre06, 0) + COALESCE(wcre, 0);
                          bdsal06 = COALESCE(bdsal06, 0) + COALESCE(wsalatu, 0);  

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov06 = COALESCE(bdmov06, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov06 = COALESCE(bdmov06, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '07') THEN
                        BEGIN
                          bddeb07 = COALESCE(bddeb07, 0) + COALESCE(wdeb, 0);
                          bdcre07 = COALESCE(bdcre07, 0) + COALESCE(wcre, 0);
                          bdsal07 = COALESCE(bdsal07, 0) + COALESCE(wsalatu, 0);    

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov07 = COALESCE(bdmov07, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov07 = COALESCE(bdmov07, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '08') THEN
                        BEGIN
                          bddeb08 = COALESCE(bddeb08, 0) + COALESCE(wdeb, 0);
                          bdcre08 = COALESCE(bdcre08, 0) + COALESCE(wcre, 0);
                          bdsal08 = COALESCE(bdsal08, 0) + COALESCE(wsalatu, 0);    

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov08 = COALESCE(bdmov08, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov08 = COALESCE(bdmov08, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '09') THEN
                        BEGIN
                          bddeb09 = COALESCE(bddeb09, 0) + COALESCE(wdeb, 0);
                          bdcre09 = COALESCE(bdcre09, 0) + COALESCE(wcre, 0);
                          bdsal09 = COALESCE(bdsal09, 0) + COALESCE(wsalatu, 0); 

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov09 = COALESCE(bdmov09, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov09 = COALESCE(bdmov09, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '10') THEN
                        BEGIN
                          bddeb10 = COALESCE(bddeb10, 0) + COALESCE(wdeb, 0);
                          bdcre10 = COALESCE(bdcre10, 0) + COALESCE(wcre, 0);
                          bdsal10 = COALESCE(bdsal10, 0) + COALESCE(wsalatu, 0);   

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov10 = COALESCE(bdmov10, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov10 = COALESCE(bdmov10, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '11') THEN
                        BEGIN
                          bddeb11 = COALESCE(bddeb11, 0) + COALESCE(wdeb, 0);
                          bdcre11 = COALESCE(bdcre11, 0) + COALESCE(wcre, 0);
                          bdsal11 = COALESCE(bdsal11, 0) + COALESCE(wsalatu, 0); 

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov11 = COALESCE(bdmov11, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov11 = COALESCE(bdmov11, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                      ELSE
                      IF (SUBSTRING(wref FROM 5 FOR 2) = '12') THEN
                        BEGIN
                          bddeb12 = COALESCE(bddeb12, 0) + COALESCE(wdeb, 0);
                          bdcre12 = COALESCE(bdcre12, 0) + COALESCE(wcre, 0);
                          bdsal12 = COALESCE(bdsal12, 0) + COALESCE(wsalatu, 0);  

                          --alt:9515 - Adicionados campos do movimento. Pedro
                          IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                            bdmov12 = COALESCE(bdmov12, 0.00) + (COALESCE(wdeb, 0.00) - COALESCE(wcre, 0.00));
                          ELSE
                          IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                            bdmov12 = COALESCE(bdmov12, 0.00) + (COALESCE(wcre, 0.00) - COALESCE(wdeb, 0.00));
                        END
                    END
                END

              IF (bdsal02 IS NULL) THEN
                 bdsal02 = COALESCE(bdsal01, 0);
              IF (bdsal03 IS NULL) THEN
                 bdsal03 = COALESCE(bdsal02, 0);
              IF (bdsal04 IS NULL) THEN
                 bdsal04 = COALESCE(bdsal03, 0);
              IF (bdsal05 IS NULL) THEN
                 bdsal05 = COALESCE(bdsal04, 0);
              IF (bdsal06 IS NULL) THEN
                 bdsal06 = COALESCE(bdsal05, 0);
              IF (bdsal07 IS NULL) THEN
                 bdsal07 = COALESCE(bdsal06, 0);
              IF (bdsal08 IS NULL) THEN
                 bdsal08 = COALESCE(bdsal07, 0);
              IF (bdsal09 IS NULL) THEN
                 bdsal09 = COALESCE(bdsal08, 0);
              IF (bdsal10 IS NULL) THEN
                 bdsal10 = COALESCE(bdsal09, 0);
              IF (bdsal11 IS NULL) THEN
                 bdsal11 = COALESCE(bdsal10, 0);
              IF (bdsal12 IS NULL) THEN
                 bdsal12 = COALESCE(bdsal11, 0);

              -- gilberto - 21/08/2013 - #alt:6470 -----------------------------
              -- inserido coalesce pois alguns valores eram nulos prejudicando os meses seguintes
              IF ((wgrupoconta = 0) OR (wgrupoconta = 4) OR (wgrupoconta = 5))  THEN -- ATIVO e DESPESAS
                 BEGIN
--                   wsalatu = wsalatu + (wdeb - wcre);
                   bdsal02 = COALESCE(bdsal01, 0) + COALESCE(bddeb02, 0) - COALESCE(bdcre02, 0);
                   bdsal03 = COALESCE(bdsal02, 0) + COALESCE(bddeb03, 0) - COALESCE(bdcre03, 0);
                   bdsal04 = COALESCE(bdsal03, 0) + COALESCE(bddeb04, 0) - COALESCE(bdcre04, 0);
                   bdsal05 = COALESCE(bdsal04, 0) + COALESCE(bddeb05, 0) - COALESCE(bdcre05, 0);
                   bdsal06 = COALESCE(bdsal05, 0) + COALESCE(bddeb06, 0) - COALESCE(bdcre06, 0);
                   bdsal07 = COALESCE(bdsal06, 0) + COALESCE(bddeb07, 0) - COALESCE(bdcre07, 0);
                   bdsal08 = COALESCE(bdsal07, 0) + COALESCE(bddeb08, 0) - COALESCE(bdcre08, 0);
                   bdsal09 = COALESCE(bdsal08, 0) + COALESCE(bddeb09, 0) - COALESCE(bdcre09, 0);
                   bdsal10 = COALESCE(bdsal09, 0) + COALESCE(bddeb10, 0) - COALESCE(bdcre10, 0);
                   bdsal11 = COALESCE(bdsal10, 0) + COALESCE(bddeb11, 0) - COALESCE(bdcre11, 0);
                   bdsal12 = COALESCE(bdsal11, 0) + COALESCE(bddeb12, 0) - COALESCE(bdcre12, 0);
                 END
              ELSE
              IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
                 BEGIN
--                   wsalatu = wsalatu + (wcre - wdeb);
                   bdsal02 = COALESCE(bdsal01, 0) + COALESCE(bdcre02, 0) - COALESCE(bddeb02, 0);
                   bdsal03 = COALESCE(bdsal02, 0) + COALESCE(bdcre03, 0) - COALESCE(bddeb03, 0);
                   bdsal04 = COALESCE(bdsal03, 0) + COALESCE(bdcre04, 0) - COALESCE(bddeb04, 0);
                   bdsal05 = COALESCE(bdsal04, 0) + COALESCE(bdcre05, 0) - COALESCE(bddeb05, 0);
                   bdsal06 = COALESCE(bdsal05, 0) + COALESCE(bdcre06, 0) - COALESCE(bddeb06, 0);
                   bdsal07 = COALESCE(bdsal06, 0) + COALESCE(bdcre07, 0) - COALESCE(bddeb07, 0);
                   bdsal08 = COALESCE(bdsal07, 0) + COALESCE(bdcre08, 0) - COALESCE(bddeb08, 0);
                   bdsal09 = COALESCE(bdsal08, 0) + COALESCE(bdcre09, 0) - COALESCE(bddeb09, 0);
                   bdsal10 = COALESCE(bdsal09, 0) + COALESCE(bdcre10, 0) - COALESCE(bddeb10, 0);
                   bdsal11 = COALESCE(bdsal10, 0) + COALESCE(bdcre11, 0) - COALESCE(bddeb11, 0);
                   bdsal12 = COALESCE(bdsal11, 0) + COALESCE(bdcre12, 0) - COALESCE(bddeb12, 0);
                 END

              bdsaltotdeb = COALESCE(bdsaltotdeb, 0) +
                            COALESCE(bddeb01, 0) +
                            COALESCE(bddeb02, 0) +
                            COALESCE(bddeb03, 0) +
                            COALESCE(bddeb04, 0) +
                            COALESCE(bddeb05, 0) +
                            COALESCE(bddeb06, 0) +
                            COALESCE(bddeb07, 0) +
                            COALESCE(bddeb08, 0) +
                            COALESCE(bddeb09, 0) +
                            COALESCE(bddeb10, 0) +
                            COALESCE(bddeb11, 0) +
                            COALESCE(bddeb12, 0);
        
              bdsaltotcre = COALESCE(bdsaltotcre, 0) +
                            COALESCE(bdcre01, 0) +
                            COALESCE(bdcre02, 0) +
                            COALESCE(bdcre03, 0) +
                            COALESCE(bdcre04, 0) +
                            COALESCE(bdcre05, 0) +
                            COALESCE(bdcre06, 0) +
                            COALESCE(bdcre07, 0) +
                            COALESCE(bdcre08, 0) +
                            COALESCE(bdcre09, 0) +
                            COALESCE(bdcre10, 0) +
                            COALESCE(bdcre11, 0) +
                            COALESCE(bdcre12, 0);
              -------------------------------------------------------- #alt:6470
        
              --alt:9515 - Adicionados campos do movimento. Pedro
              bdsaltotmov = COALESCE(bdsaltotmov, 0) +
                            COALESCE(bdmov01, 0) +
                            COALESCE(bdmov02, 0) +
                            COALESCE(bdmov03, 0) +
                            COALESCE(bdmov04, 0) +
                            COALESCE(bdmov05, 0) +
                            COALESCE(bdmov06, 0) +
                            COALESCE(bdmov07, 0) +
                            COALESCE(bdmov08, 0) +
                            COALESCE(bdmov09, 0) +
                            COALESCE(bdmov10, 0) +
                            COALESCE(bdmov11, 0) +
                            COALESCE(bdmov12, 0);

              bdsaltotatu = bdsal12;
              BDGRPCTA = wgrupoconta;
        
              wcount = wcount +1;
              SUSPEND;
         --end
    END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_PLANOS_TPLA */
ALTER PROCEDURE VSUC_SP_RETORNA_PLANOS_TPLA(PRCODPLANOPADRAO INTEGER,
PRCAMPOPESQUISA VARCHAR(20),
PRCONTEUDO VARCHAR(20),
PRPESQUISAINICIO INTEGER)
 RETURNS(BDCODTPLA INTEGER,
BDCTALON VARCHAR(40),
BDTIPCTA INTEGER,
BDNOMCTA VARCHAR(100),
BDAPECTA VARCHAR(20),
BDRELCTA INTEGER,
BDFILTROGER VARCHAR(20),
BDFORMULA VARCHAR(200),
BDCONDICAO VARCHAR(200))
 AS
DECLARE VARIABLE winto VARCHAR(20);
DECLARE VARIABLE wclass VARCHAR(40);
DECLARE "crClass" CURSOR FOR (SELECT DISTINCT(prclassificacao) 
    FROM vsuc_sp_retorna_classgroup(:prcodplanopadrao, :prcampopesquisa, :prconteudo, :prpesquisainicio));
BEGIN
/* 00:01 */

  OPEN "crClass";

  DELETE FROM tconsulta_classificacao;

  WHILE (1 = 1) DO
    BEGIN
      FETCH "crClass" INTO :wclass;
      IF (ROW_COUNT = 0) THEN
         LEAVE;

      INSERT INTO tconsulta_classificacao (bdclass) VALUES (:wclass);
    END

  CLOSE "crClass";

  FOR SELECT tpla.BDCODTPLA, tpla.BDCTALON, tpla.BDTIPCTA, tpla.BDNOMCTA, tpla.BDAPECTA,
             tpla.BDRELCTA, tpla.BDFILTROGER, tpla.BDFORMULA, tpla.BDCONDICAO
      FROM PLANOS_TPLA tpla
      WHERE tpla.bdcodplapadrao = :prcodplanopadrao
      ORDER BY tpla.bdCTALON
      INTO :bdcodtpla, :bdctalon, :bdtipcta, :bdnomcta, :bdapecta, :bdrelcta, :bdfiltroger, :bdformula, :bdcondicao DO
      BEGIN
        FOR SELECT bdclass FROM tconsulta_classificacao INTO :wclass DO
            IF (wclass = bdctalon) THEN
               SUSPEND;
      END

  DELETE FROM tconsulta_classificacao;
END
^

/* Restore proc. body: VSUC_SP_RETORNA_RAZAO_CONTAS */
ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_CONTAS(PRCODEMP VARCHAR(1024),
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRLCC VARCHAR(8192),
PRORDEMPRESA INTEGER,
PRREFEMP INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARFILIAL INTEGER)
 RETURNS(PRHISTORICO VARCHAR(100),
PRDATA DATE,
PRCHAVE INTEGER,
PRCONTA INTEGER,
PRCONTRA INTEGER,
PRCREDITO NUMERIC(15,2),
PRDEBITO NUMERIC(15,2),
PRCONCILIADO VARCHAR(5),
PREMPRESA INTEGER,
PRNOMEEMPRESA DM_BDNOMEMP,
PRCC INTEGER,
PRNOME_CONTA VARCHAR(100),
PRCLASS_CONTA VARCHAR(40),
PRCLASS_CONTRA VARCHAR(40),
PRNOME_CONTA_CONTRA VARCHAR(100),
PRLOTE VARCHAR(10),
PRDCTO VARCHAR(15),
PRCOMPL VARCHAR(200),
PRCNPJEMP VARCHAR(18),
PRCODMATRIZ INTEGER,
PRGRPCTA INTEGER,
PRCODHIST INTEGER,
PRCODPLAPADRAO INTEGER,
PRCODTPHI INTEGER,
PRPARTICIPANTECONTA INTEGER,
PRPARTICIPANTECONTRA INTEGER,
PRCODTERCEIROCONTA INTEGER,
PRCODTERCEIROCONTRA INTEGER,
PRCODEMPFILIAL INTEGER,
PRTIPOLAN INTEGER,
PRCHAVEONLINE VARCHAR(120))
 AS
DECLARE VARIABLE wcredito INTEGER;
DECLARE VARIABLE wdebito INTEGER;
DECLARE VARIABLE wvalor NUMERIC(15,2);
DECLARE VARIABLE wctalonc VARCHAR(40);
DECLARE VARIABLE wctalonaxuc VARCHAR(40);
DECLARE VARIABLE wnomctac VARCHAR(100);
DECLARE VARIABLE wtipctac INTEGER;
DECLARE VARIABLE wcodterceiroc INTEGER;
DECLARE VARIABLE wparticipantec INTEGER;
DECLARE VARIABLE wconcd VARCHAR(5);
DECLARE VARIABLE wconcc VARCHAR(5);
DECLARE VARIABLE wdatini VARCHAR(10);
DECLARE VARIABLE wdatfin VARCHAR(10);
DECLARE VARIABLE wsql VARCHAR(11244);
DECLARE VARIABLE wctalond VARCHAR(40);
DECLARE VARIABLE wctalonaxud VARCHAR(40);
DECLARE VARIABLE wnomctad VARCHAR(100);
DECLARE VARIABLE wtipctad INTEGER;
DECLARE VARIABLE wcodterceirod INTEGER;
DECLARE VARIABLE wparticipanted INTEGER;
DECLARE VARIABLE wgrpctac INTEGER;
DECLARE VARIABLE wgrpctad INTEGER;
DECLARE VARIABLE wdebcre INTEGER;
DECLARE VARIABLE wcodempresalan INTEGER;
DECLARE VARIABLE wpos INTEGER;
DECLARE VARIABLE wfilial INTEGER;
DECLARE VARIABLE wtipolancfilial INTEGER;
DECLARE VARIABLE wpermite INTEGER;
DECLARE VARIABLE wempprinc INTEGER;
DECLARE VARIABLE wselectcta INTEGER;
DECLARE VARIABLE wsubstr VARCHAR(1024);
DECLARE VARIABLE wstr VARCHAR(1024);
DECLARE VARIABLE wpos_pernamatriz INTEGER;
DECLARE VARIABLE wcount INTEGER;
DECLARE VARIABLE wpos_matriz INTEGER;
DECLARE VARIABLE wpos_filial INTEGER;
DECLARE VARIABLE wcampo INTEGER;
BEGIN
  wsql = 'select first 1 case when (temp.bdcodmatriz is null) then temp.bdcodemp ';
  wpos = POSITION(',', :prcodemp);
  IF (wpos <> 0) THEN
     wsql = wsql||'            when (temp.bdcodmatriz is not null) then temp.bdcodmatriz ';
  ELSE
     BEGIN
       wsql = wsql||'          when ((temp.bdcodmatriz is not null) and (temp.bdcodemp not in ('||prcodemp||'))) then temp.bdcodmatriz ';
       wsql = wsql||'          when (temp.bdcodemp in ('||prcodemp||')) then temp.bdcodemp ';
     END
  wsql = wsql||'       end bdcodemp ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'where temp.bdcodemp in ('||prcodemp||')';
  EXECUTE STATEMENT wsql INTO :prempresa;

  wdatini   = SUBSTRING(CAST(prdata_inicial AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
              SUBSTRING(CAST(prdata_inicial AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
              SUBSTRING(CAST(prdata_inicial AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin   = SUBSTRING(CAST(prdata_final AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
              SUBSTRING(CAST(prdata_final AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
              SUBSTRING(CAST(prdata_final AS VARCHAR(10)) FROM 1 FOR 4);

  --Retorna a empresa principal
  wpos = POSITION(',', :prcodemp);
  IF (wpos = 0) THEN
     wempprinc = prcodemp;
  ELSE
     wempprinc = SUBSTRING(prcodemp FROM 1 FOR (wpos - 1));

  -- Débito
  wsql = 'select tlan.bdchave, tlan.bddata, tlan.bdcodemp, ';
  wsql = wsql||'tlan.bdcredito, tlan.bdcodterceiroc, tlan.bdconcc, tplac.bdctalon, tplac.bdnomcta, tplac.bdgrupocta, tplac.bdtipcta, tplac.bdparticipante, ';
  wsql = wsql||'tlan.bddebito, tlan.bdcodterceirod, tlan.bdconcd, tplad.bdctalon, tplad.bdnomcta, tplad.bdgrupocta, tplad.bdtipcta, tplad.bdparticipante, ';
  wsql = wsql||'this.bdnome, tlan.bdlote, tlan.bdcompl, tlan.bddcto, this.bdcodhist, tlan.bdcodtphi, tlan.bdcodplapadrao, ';
  wsql = wsql||'temp.bdcnpjemp, temp.bdcodmatriz, temp.bdnomemp, tlan.bdtipolan, tlan.bdchaveonline, ';

  IF (prlcc = '') THEN
     wsql = wsql||'tlan.bdvalor, tlan.bdchave, tlan.bdchave from vsuc_empresas_tlan tlan ';
  ELSE
     BEGIN
       wsql = wsql||'tlcc.bdvalor, tlcc.bdcodtpcc, tlcc.bddebcre from vsuc_empresas_tlcc tlcc ';
       wsql = wsql||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
     END
  wsql = wsql||'left outer join planos_tpla tplad on (tplad.bdcodplapadrao = tlan.bdcodplapadrao and tplad.bdcodtpla = tlan.bddebito) ';
  wsql = wsql||'left outer join planos_tpla tplac on (tplac.bdcodplapadrao = tlan.bdcodplapadrao and tplac.bdcodtpla = tlan.bdcredito) ';
  wsql = wsql||'left outer join hist_tphi this on (this.bdcodhist = tlan.bdcodhist and this.bdcodtphi = tlan.bdcodtphi) ';
  wsql = wsql||'inner join vw_empresas_ref_atual temp on (temp.bdcodemp = tlan.bdcodemp) ';
  wsql = wsql||'where ';
  --#alt:5619 - gilberto - 13/08/2013 __________________________________________________
  SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wselectcta;
  IF ((wselectcta IS NOT NULL) AND (wselectcta > 0)) THEN
     wsql = wsql||'(tlan.bddebito in (select bdcodtpla from vsuc_select_contas tsel)) ';
  -----------------------------------------------------------------------------#alt:5619
  ELSE
     wsql = wsql||'(tplad.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (prlcc <> '') THEN
     wsql = wsql||'and (tlcc.bdcodtpcc in ('||TRIM(prlcc)||')) ';
  wsql = wsql||'and (tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';
  IF ((prpartini IS NOT NULL) AND (prpartfin IS NOT NULL)) THEN
     wsql = wsql||'and (tlan.bdcodterceirod between '||prpartini||' and '||prpartfin||') ';
  --#alt:5837.
  --wsql = wsql||'and tlan.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'and (tlan.bdcodemp in ('||prcodemp||')) ';

  FOR EXECUTE STATEMENT wsql
  INTO :prchave, :prdata, :prempresa,
       :wcredito, :wcodterceiroc, :wconcc, :wctalonc, :wnomctac, :wgrpctac, :wtipctac, :wparticipantec,
       :wdebito, :wcodterceirod, :wconcd, :wctalond, :wnomctad, :wgrpctad, :wtipctad, :wparticipanted,
       :prhistorico, :prlote, :prcompl, :prdcto, :prcodhist, :prcodtphi, :prcodplapadrao,
       :prcnpjemp, :prcodmatriz, :prnomeempresa, :prtipolan, :prchaveonline,
       :wvalor, :prcc, :wdebcre DO
  BEGIN
    prcodempfilial = prempresa;

    wpos = POSITION(',', :prcodemp);
    IF (wpos <> 0) THEN
       BEGIN
         prcodempfilial = prempresa;
         IF (prcodmatriz IS NULL) THEN
            prcodmatriz = prempresa;
         prempresa = prcodmatriz;
       END

    --Foi criado essas variáveis auxiliares pois quando esta por detalhar participante
    --ele precisa verificar a classificação pela conta original
    wctalonaxuc = wctalonc;
    wctalonaxud = wctalond;

    IF (prlcc = '') THEN
       prcc = 0;
    -- Débito
--    if ((prdetalharctaparticipante = 1) and (wparticipanted = 1) and (wtipctad = 1)) then
--      select bdclassificacao, bdnome from vsuc_sp_nomenclatura_cta_partic(:wcodterceirod,:wctalond,:prconcatenacodparticipante) into :wctalond,:wnomctad;


    --alt:#6524 - implementado rotina "POS" aqui, por questão de desempenho, precisa apenas uma vez para as duas verificações
--    select bdpermite from vsuc_sp_permitecalcsaldolancmf(1,:wempprinc,:prempresa,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
    -- IF (NOT ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0))) THEN
       -- BEGIN
       -- --alt:#6535 - gilberto - 05/09/2013
         -- wpos_pernamatriz = POSITION(wempprinc, prcodemp);
         -- wpos_matriz = POSITION(prempresa, prcodemp);
         -- wpos_filial = POSITION(wfilial, prcodemp);
      -- END
    wcampo = 1;

    -- IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
       wpermite = 1;
    -- ELSE
    -- IF (((wempprinc = prempresa) AND (wfilial = 0)) OR
        -- --Estou na filial mas o lançamento foi feito na matriz para a filial(uma perna)
        -- ((wempprinc = wfilial) AND (wcampo = wtipolancfilial)) OR
        -- --Estou na matriz e tem uma perna do lançamento na filial, mas só quero os lançamentos da matriz(a perna da matriz) e que a matriz esteja no filtro
        -- ((wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
        -- --Estou na matriz mas também quero os lançamentos da filial conforme o filtro(Lançamentos que foram feito na filial -> BDCODEMP = Filial)
        -- ((prmatrizfilialconsolidado = 1) AND (wempprinc <> prempresa) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
        -- --Estou na matriz mas também quero a perna que está na filial conforme o filtro
        -- ((prmatrizfilialconsolidado = 1) AND (wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
       -- wpermite = 1;
    -- ELSE
       -- wpermite = 0;
    -------------------------------------------------------------------alt:#6524
    IF (wpermite = 1) THEN
      BEGIN
        --#alt:5837.
        -- IF ((wfilial > 0) AND (wtipolancfilial = 1)) THEN
          -- prcodempfilial = wfilial;
        --Verifica se precisa limpar a conta contra
        --alt:#6524-------------------------------------------------------------
        --select bdpermite from vsuc_sp_permitecalcsaldolancmf(2,:wempprinc,:prempresa,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
        wcampo = 2;
    
        -- IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
           wpermite = 1;
        -- ELSE
        -- IF (((wempprinc = prempresa) AND (wfilial = 0)) OR
            -- --Estou na filial mas o lançamento foi feito na matriz para a filial(uma perna)
            -- ((wempprinc = wfilial) AND (wcampo = wtipolancfilial)) OR
            -- --Estou na matriz e tem uma perna do lançamento na filial, mas só quero os lançamentos da matriz(a perna da matriz) e que a matriz esteja no filtro
            -- ((wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
            -- --Estou na matriz mas também quero os lançamentos da filial conforme o filtro(Lançamentos que foram feito na filial -> BDCODEMP = Filial)
            -- ((prmatrizfilialconsolidado = 1) AND (wempprinc <> prempresa) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
            -- --Estou na matriz mas também quero a perna que está na filial conforme o filtro
            -- ((prmatrizfilialconsolidado = 1) AND (wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
           -- wpermite = 1;
        -- ELSE
           -- wpermite = 0;
        ---------------------------------------------------------------alt:#6524
        IF (prclassificacao_inicial = prclassificacao_final) THEN
          BEGIN
            IF (((prlcc = '') AND (NOT wdebito IS NULL)) OR
                ((prlcc <> '') AND (wdebcre = 0))) THEN
              BEGIN
                IF (wctalonaxud BETWEEN prclassificacao_inicial AND prclassificacao_final) THEN
                  BEGIN
                    prdebito     = wvalor;
                    prcredito    = NULL;
                    prconta      = wdebito;
                    prcontra     = wcredito;
                    prconciliado = wconcd;
                    prgrpcta     = wgrpctad;

                    prnome_conta         = wnomctad;
                    prclass_conta        = wctalond;
                    prparticipanteconta  = wparticipanted;
                    prcodterceiroconta   = wcodterceirod;
                    prclass_contra       = wctalonc;
                    prnome_conta_contra  = wnomctac;
                    prparticipantecontra = wparticipantec;
                    prcodterceirocontra  = wcodterceiroc;
                    --#alt:5837.
                    IF ((wpermite = 0) OR ((prdetalharfilial = 1) AND (wfilial > 0))) THEN
                      BEGIN
                        prcontra             = NULL;
                        prclass_contra       = '';
                        prnome_conta_contra  = '';
                        prparticipantecontra = NULL;
                        prcodterceirocontra  = NULL;
                      END
                    SUSPEND;
                  END
              END
          END
        ELSE
          BEGIN
            IF (((prlcc = '') AND (NOT wdebito IS NULL)) OR
                ((prlcc <> '') AND (wdebcre = 0))) THEN
              BEGIN
                IF (wctalonaxud BETWEEN prclassificacao_inicial AND prclassificacao_final) THEN
                  BEGIN
                    prdebito     = wvalor;
                    prcredito    = NULL;
                    prconta      = wdebito;
                    prcontra     = wcredito;
                    prconciliado = wconcd;
                    prgrpcta     = wgrpctad;

                    prnome_conta         = wnomctad;
                    prclass_conta        = wctalond;
                    prparticipanteconta  = wparticipanted;
                    prcodterceiroconta   = wcodterceirod;
                    prclass_contra       = wctalonc;
                    prnome_conta_contra  = wnomctac;
                    prparticipantecontra = wparticipantec;
                    prcodterceirocontra  = wcodterceiroc;
                    --#alt:5837.
                    IF ((wpermite = 0) OR ((prdetalharfilial = 1) AND (wfilial > 0))) THEN
                      BEGIN
                        prcontra             = NULL;
                        prclass_contra       = '';
                        prnome_conta_contra  = '';
                        prparticipantecontra = NULL;
                        prcodterceirocontra  = NULL;
                      END
                    SUSPEND;
                  END
              END
          END
      END
  END
  -- Crédito
  wsql = 'select tlan.bdchave, tlan.bddata, tlan.bdcodemp, ';
  wsql = wsql||'tlan.bdcredito, tlan.bdcodterceiroc, tlan.bdconcc, tplac.bdctalon, tplac.bdnomcta, tplac.bdgrupocta, tplac.bdtipcta, tplac.bdparticipante, ';
  wsql = wsql||'tlan.bddebito, tlan.bdcodterceirod, tlan.bdconcd, tplad.bdctalon, tplad.bdnomcta, tplad.bdgrupocta, tplad.bdtipcta, tplad.bdparticipante, ';
  wsql = wsql||'this.bdnome, tlan.bdlote, tlan.bdcompl, tlan.bddcto, this.bdcodhist, tlan.bdcodtphi, tlan.bdcodplapadrao, ';
  wsql = wsql||'temp.bdcnpjemp, temp.bdcodmatriz, temp.bdnomemp, tlan.bdtipolan, tlan.bdchaveonline, ';
  IF (prlcc = '') THEN
     wsql = wsql||'tlan.bdvalor, tlan.bdchave, tlan.bdchave from vsuc_empresas_tlan tlan ';
  ELSE
     BEGIN
       wsql = wsql||'tlcc.bdvalor, tlcc.bdcodtpcc, tlcc.bddebcre from vsuc_empresas_tlcc tlcc ';
       wsql = wsql||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
     END
  wsql = wsql||'left outer join planos_tpla tplac on (tplac.bdcodplapadrao = tlan.bdcodplapadrao and tplac.bdcodtpla = tlan.bdcredito) ';
  wsql = wsql||'left outer join planos_tpla tplad on (tplad.bdcodplapadrao = tlan.bdcodplapadrao and tplad.bdcodtpla = tlan.bddebito) ';
  wsql = wsql||'left outer join hist_tphi this on (this.bdcodhist = tlan.bdcodhist and this.bdcodtphi = tlan.bdcodtphi) ';
  wsql = wsql||'inner join vw_empresas_ref_atual temp on (temp.bdcodemp = tlan.bdcodemp) ';
  wsql = wsql||'where ';
  --#alt:5619 - gilberto - 13/08/2013 ______________________________________________
  SELECT FIRST 1 bdcodtpla FROM vsuc_select_contas INTO :wselectcta;
  IF ((wselectcta IS NOT NULL) AND (wselectcta > 0)) THEN
     wsql = wsql||'(tlan.bdcredito in (select bdcodtpla from vsuc_select_contas)) ';
  -------------------------------------------------------------------------#alt:5619
  ELSE
     wsql = wsql||'(tplac.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (prlcc <> '') THEN
     wsql = wsql||'and (tlcc.bdcodtpcc in ('||TRIM(prlcc)||')) ';
  wsql = wsql||'and (tlan.bddata between '''||wdatini||''' and '''||wdatfin||''') ';
  IF ((prpartini IS NOT NULL) AND (prpartfin IS NOT NULL)) THEN
     wsql = wsql||'and (tlan.bdcodterceiroc between '||prpartini||' and '||prpartfin||') ';
  --#alt:5837.
  --wsql = wsql||'and tlan.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'and (tlan.bdcodemp in ('||prcodemp||')) ';


  FOR EXECUTE STATEMENT wsql
  INTO :prchave, :prdata, :prempresa,
       :wcredito, :wcodterceiroc, :wconcc, :wctalonc, :wnomctac, :wgrpctac, :wtipctac, :wparticipantec,
       :wdebito, :wcodterceirod, :wconcd, :wctalond, :wnomctad, :wgrpctad, :wtipctad, :wparticipanted,
       :prhistorico, :prlote, :prcompl, :prdcto, :prcodhist, :prcodtphi, :prcodplapadrao,
       :prcnpjemp, :prcodmatriz, :prnomeempresa, :prtipolan, :prchaveonline,
       :wvalor, :prcc, :wdebcre DO
  BEGIN
    prcodempfilial = prempresa;

    wpos = POSITION(',', :prcodemp);
    IF (wpos <> 0) THEN
       BEGIN
--         prcodempfilial = prempresa;
         IF (prcodmatriz IS NULL) THEN
            prcodmatriz = prempresa;
         prempresa = prcodmatriz;
       END

    --Foi criado essas variáveis auxiliares pois quando esta por detalhar participante
    --ele precisa verificar a classificação pela conta original
    wctalonaxuc = wctalonc;
    wctalonaxud = wctalond;

    IF (prlcc = '') THEN
       prcc = 0;
    -- Crédito
--    if ((prdetalharctaparticipante = 1) and (wparticipantec = 1) and (wtipctac = 1)) then
--       select bdclassificacao, bdnome from vsuc_sp_nomenclatura_cta_partic(:wcodterceiroc,:wctalonc,:prconcatenacodparticipante) into :wctalonc,:wnomctac;


    --alt:#6524 - implementado rotina "POS" aqui, por questão de desempenho, precisa apenas uma vez para as duas verificações
    --select bdpermite from vsuc_sp_permitecalcsaldolancmf(2,:wempprinc,:prempresa,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
    -- IF (NOT ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0))) THEN
       -- BEGIN
       -- --alt:#6535 - gilberto - 05/09/2013
         -- wpos_pernamatriz = POSITION(wempprinc, prcodemp);
         -- wpos_matriz = POSITION(prempresa, prcodemp);
         -- wpos_filial = POSITION(wfilial, prcodemp);
      -- END
    wcampo = 2;

    -- IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
       wpermite = 1;
    -- ELSE
    -- IF (((wempprinc = prempresa) AND (wfilial = 0)) OR
        -- --Estou na filial mas o lançamento foi feito na matriz para a filial(uma perna)
        -- ((wempprinc = wfilial) AND (wcampo = wtipolancfilial)) OR
        -- --Estou na matriz e tem uma perna do lançamento na filial, mas só quero os lançamentos da matriz(a perna da matriz) e que a matriz esteja no filtro
        -- ((wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
        -- --Estou na matriz mas também quero os lançamentos da filial conforme o filtro(Lançamentos que foram feito na filial -> BDCODEMP = Filial)
        -- ((prmatrizfilialconsolidado = 1) AND (wempprinc <> prempresa) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
        -- --Estou na matriz mas também quero a perna que está na filial conforme o filtro
        -- ((prmatrizfilialconsolidado = 1) AND (wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
       -- wpermite = 1;
    -- ELSE
       -- wpermite = 0;
    -------------------------------------------------------------------alt:#6524
    IF (wpermite = 1) THEN
      BEGIN
        --#alt:5837.
        -- IF ((wfilial > 0) AND (wtipolancfilial = 2)) THEN
          -- prcodempfilial = wfilial;
        --Verifica se precisa limpar a conta contra
        --alt:#6524-------------------------------------------------------------
        --select bdpermite from vsuc_sp_permitecalcsaldolancmf(1,:wempprinc,:prempresa,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
        wcampo = 2;
    
        -- IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
           wpermite = 1;
        -- ELSE
        -- IF (((wempprinc = prempresa) AND (wfilial = 0)) OR
            -- --Estou na filial mas o lançamento foi feito na matriz para a filial(uma perna)
            -- ((wempprinc = wfilial) AND (wcampo = wtipolancfilial)) OR
            -- --Estou na matriz e tem uma perna do lançamento na filial, mas só quero os lançamentos da matriz(a perna da matriz) e que a matriz esteja no filtro
            -- ((wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
            -- --Estou na matriz mas também quero os lançamentos da filial conforme o filtro(Lançamentos que foram feito na filial -> BDCODEMP = Filial)
            -- ((prmatrizfilialconsolidado = 1) AND (wempprinc <> prempresa) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
            -- --Estou na matriz mas também quero a perna que está na filial conforme o filtro
            -- ((prmatrizfilialconsolidado = 1) AND (wempprinc = prempresa) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
           -- wpermite = 1;
        -- ELSE
           -- wpermite = 0;
        ---------------------------------------------------------------alt:#6524
        IF (prclassificacao_inicial = prclassificacao_final) THEN
          BEGIN
            IF (((prlcc = '') AND (NOT wcredito IS NULL)) OR
                ((prlcc <> '') AND (wdebcre = 1))) THEN
              BEGIN
                IF (wctalonaxuc BETWEEN prclassificacao_inicial AND prclassificacao_final) THEN
                  BEGIN
                    prdebito     = NULL;
                    prcredito    = wvalor;
                    prconta      = wcredito;
                    prcontra     = wdebito;
                    prconciliado = wconcc;
                    prgrpcta     = wgrpctac;

                    prnome_conta         = wnomctac;
                    prclass_conta        = wctalonc;
                    prparticipanteconta  = wparticipantec;
                    prcodterceiroconta   = wcodterceiroc;
                    prclass_contra       = wctalond;
                    prnome_conta_contra  = wnomctad;
                    prparticipantecontra = wparticipanted;
                    prcodterceirocontra  = wcodterceirod;
                    --#alt:5837.
                    IF ((wpermite = 0) OR ((prdetalharfilial = 1) AND (wfilial > 0))) THEN
                      BEGIN
                        prcontra             = NULL;
                        prclass_contra       = '';
                        prnome_conta_contra  = '';
                        prparticipantecontra = NULL;
                        prcodterceirocontra  = NULL;
                      END
                    SUSPEND;
                  END
              END
          END
        ELSE
          BEGIN
            IF (((prlcc = '') AND (NOT wcredito IS NULL)) OR
                ((prlcc <> '') AND (wdebcre = 1))) THEN
              BEGIN
                IF (wctalonaxuc BETWEEN prclassificacao_inicial AND prclassificacao_final) THEN
                  BEGIN
                    prdebito     = NULL;
                    prcredito    = wvalor;
                    prconta      = wcredito;
                    prcontra     = wdebito;
                    prconciliado = wconcc;
                    prgrpcta     = wgrpctac;

                    prnome_conta         = wnomctac;
                    prclass_conta        = wctalonc;
                    prparticipanteconta  = wparticipantec;
                    prcodterceiroconta   = wcodterceiroc;
                    prclass_contra       = wctalond;
                    prnome_conta_contra  = wnomctad;
                    prparticipantecontra = wparticipanted;
                    prcodterceirocontra  = wcodterceirod;
                    --#alt:5837.
                    IF ((wpermite = 0) OR ((prdetalharfilial = 1) AND (wfilial > 0))) THEN
                      BEGIN
                        prcontra             = NULL;
                        prclass_contra       = '';
                        prnome_conta_contra  = '';
                        prparticipantecontra = NULL;
                        prcodterceirocontra  = NULL;
                      END
                    SUSPEND;
                  END
              END
          END
      END
  END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_RAZAO_CONTAS_X */
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_CONTAS_X (
    PRCODEMP VARCHAR(1024),
    PRREFEMP INTEGER,
    PRCLASSIFICACAO_INICIAL VARCHAR(40),
    PRCLASSIFICACAO_FINAL VARCHAR(40),
    PRDATA_INICIAL DATE,
    PRDATA_FINAL DATE,
    PRINDICE INTEGER,
    PRDETALHARCC INTEGER,
    PRLCC DM_MAXVARCHAR,
    PRLANCAMENTOSEMCC INTEGER,
    PRDETALHARCTAPARTICIPANTE INTEGER,
    PRAGRUPARPARTICIPANTEPORCNPJ INTEGER,
    PRCONCATENACODPARTICIPANTE INTEGER,
    PRPARTINI INTEGER,
    PRPARTFIN INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRCONTASSEMMOVIMENTO INTEGER,
    PRIGNORAZERAMENTO INTEGER = 0,
    PRDETALHAREMPREENDIMENTO INTEGER = 0,
    PRDETALHARUNIDIMOB INTEGER = 0,
    PRPRMOSTRARPROPUNIDADE INTEGER = 0,
    PRPRODRURAL DM_BOOLEAN = 'FALSE' /* COLLATE WIN1252 - default */ ,
    PRIMOVEIS VARCHAR(1024) = '' /* COLLATE WIN1252 - default */ ,
    PRLISTAPART VARCHAR(10000) = '' /* COLLATE WIN1252 - default */ ,
    PRAGRUPARPARTICIPANTEPORCPF INTEGER = 0,
    PRPLANO_SECUNDARIO INTEGER = 0,
    PRFILTRAREMPREENDIMENTO VARCHAR(1024) = '' /* COLLATE WIN1252 - default */ ,
    PRFILTRARUNIDIMOBILIARIA VARCHAR(1024) = '' /* COLLATE WIN1252 - default */ ,
    PRNAOMOSTRARLANCSEMDADOSRU DM_BOOLEAN = 'FALSE' /* COLLATE WIN1252 - default */ ,
    PRFILTIPOLAN varchar(3200) = '')
RETURNS (
    PRHISTORICO VARCHAR(100),
    PRDATA DATE,
    PRCHAVE INTEGER,
    PRCONTA INTEGER,
    PRCONTRA INTEGER,
    PRCREDITO NUMERIC(18,2),
    PRDEBITO NUMERIC(18,2),
    PRCONCILIADO VARCHAR(5),
    PREMPRESA INTEGER,
    PRNOMEEMPRESA DM_BDNOMEMP,
    PRCC INTEGER,
    PRNOME_CONTA VARCHAR(300),
    PRNOME_CONTA_ORIGINAL VARCHAR(300),
    PRCLASS_CONTA VARCHAR(40),
    PRCLASS_CONTRA VARCHAR(40),
    PRNOME_CONTA_CONTRA VARCHAR(300),
    PRLOTE VARCHAR(10),
    PRDCTO VARCHAR(15),
    PRCOMPL VARCHAR(200),
    PRCNPJEMP VARCHAR(18),
    PRCODMATRIZ INTEGER,
    PRGRPCTA INTEGER,
    PRCODHIST INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRCODTPHI INTEGER,
    PRPARTICIPANTECONTA INTEGER,
    PRPARTICIPANTECONTRA INTEGER,
    PRCODTERCEIROCONTA INTEGER,
    PRCODTERCEIROCONTRA INTEGER,
    PRCGC_CONTA VARCHAR(18),
    PRCODEMPFILIAL INTEGER,
    PRTIPOLANCFILIAL INTEGER,
    PRTIPOLAN INTEGER,
    PRCHAVEONLINE VARCHAR(120),
    PRCODCENTRO INTEGER,
    PRTRANSACAO INTEGER,
    PRTRANFECHADA DM_BOOLEAN,
    PRCONCILIACAOPENDENTE INTEGER,
    PRCLANOM VARCHAR(355),
    PRDEBCRE INTEGER,
    PREMPREENDIMENTO INTEGER,
    PRUNIDIMOB INTEGER,
    PRNATUREZALAN INTEGER,
    PRCTALCDPR VARCHAR(6),
    PRPART_PR VARCHAR(18),
    PRCODPART_PR INTEGER,
    PRTIPLANPR VARCHAR(6),
    PRCODIMOVRUR INTEGER,
    PRTIPDOCPR INTEGER,
    PRSALRELCONCILIACOES varchar(5))
AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WEMPPRINC INTEGER;
DECLARE VARIABLE WSELECTCTA INTEGER;
DECLARE VARIABLE WPOS_PERNAMATRIZ INTEGER;
DECLARE VARIABLE WPOS_MATRIZ INTEGER;
DECLARE VARIABLE WPOS_FILIAL INTEGER;
DECLARE VARIABLE WCAMPO INTEGER;
DECLARE VARIABLE WTIPCTACONTA INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WNOMETER VARCHAR(100);
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WNAODETALHAEMP INTEGER;
DECLARE VARIABLE WNAODETALHAUNID INTEGER;
DECLARE VARIABLE WCLASS VARCHAR(40);
DECLARE VARIABLE WNOMEINCORP VARCHAR(400);
DECLARE VARIABLE WWHERE VARCHAR(1000);
DECLARE VARIABLE WTIPO_SEC INTEGER;
declare variable WANOCOSIF INTEGER;
BEGIN
  WSQL = 'select first 1 case when (temp.bdcodmatriz is null) then temp.bdcodemp ';
  WPOS = POSITION(',', :PRCODEMP);
  IF (WPOS <> 0) THEN
    WSQL = WSQL || '            when (temp.bdcodmatriz is not null) then temp.bdcodmatriz ';
  ELSE
     BEGIN
    WSQL = WSQL || '          when ((temp.bdcodmatriz is not null) and (temp.bdcodemp not in (' || PRCODEMP || '))) then temp.bdcodmatriz ';
    WSQL = WSQL || '          when (temp.bdcodemp in (' || PRCODEMP || ')) then temp.bdcodemp ';
     END
  WSQL = WSQL || '       end bdcodemp ';
  WSQL = WSQL || 'from tempresas temp ';
  WSQL = WSQL || 'where temp.bdcodemp in (' || PRCODEMP || ')';
  --alt:15745 - 14/09/2016 - Corrigida variável onde deve ser gravado o código da empresa matriz. Estava com erro no "lançar a" validar com a empresa incorreta. Pedro
  --EXECUTE STATEMENT wsql INTO :prempresa;
  EXECUTE STATEMENT WSQL
      INTO :PRCODMATRIZ;

  --Retorna a empresa principal
  IF (WPOS = 0) THEN
    WEMPPRINC = PRCODEMP;
  ELSE
    WEMPPRINC = SUBSTRING(PRCODEMP FROM 1 FOR (WPOS - 1));

  SELECT FIRST 1 BDCODTPLA
  FROM VSUC_SELECT_CONTAS
  INTO :WSELECTCTA;

  WSQL = '';
  WSQL = WSQL || 'select tx.bdchave, tx.bddata, ';
  --#Alt:21066 - Alterado por causa da lentidão (Carlos Mello)
  --wsql = wsql||'       tx.bdcodemp, emp.bdnomemp, emp.bdcnpjemp, ';
  WSQL = WSQL || '       TX.bdcodemp, empref.bdnomemp, emp.bdcnpjemp, ';
  WSQL = WSQL || '       tpla.bdcodplapadrao, ';
  WSQL = WSQL || '       tx.bdlote, tx.bdcompl, tx.bddcto, ';
  WSQL = WSQL || ' ';
  WSQL = WSQL || '       tx.bdtipolan, tx.bdchaveonline, ';
  WSQL = WSQL || '       tx.bdcodhist, tx.bdcodtphi, this.bdnome,  ';
  IF (PRPLANO_SECUNDARIO > 0) THEN
  BEGIN
    WTIPO_SEC = 0;
    SELECT BDTIPO
    FROM TPLANO_SECUNDARIO
    WHERE BDCODPLAPADRAO_SEC = :PRPLANO_SECUNDARIO
    INTO :WTIPO_SEC;

    WSQL = WSQL || '       TSEC.BDCODTPLA as BDCONTA, TERC.bdcodter as bdcodter_conta, tx.bdconc as bdconc_conta, tx.bdconciliacaopendente, ';
    WSQL = WSQL || '       TSEC.bdctalon';
    IF (WTIPO_SEC = 1) THEN
      WSQL = WSQL || '||''-''||tsec.BDCODCOSIF';
    WSQL = WSQL || '       as ctalon_conta, TSEC.bdnomcta as bdnomcta_conta, TSEC.bdnomcta as bdnomcta_conta_original, TSEC.bdgrupocta as bdgrupocta_conta, TSEC.bdtipcta as bdtipcta_conta, null as bdclanom, 0 as bdparticipante, ';
    WSQL = WSQL || '       TSEC_CTR.bdcodtpla as BDCONTRA, tx.bdcodterceiroc as bdcodter_contra, TSEC_CTR.bdctalon as bdctalon_contra, TSEC_CTR.bdnomcta as bdnomcta_contra, 0 as bdparticipante_contra, ';
  END
  ELSE
  BEGIN
    WSQL = WSQL || '       tpla.bdcodtpla as BDCONTA, TERC.bdcodter as bdcodter_conta, tx.bdconc as bdconc_conta, tx.bdconciliacaopendente, ';
    WSQL = WSQL || '       tpla.bdctalon as ctalon_conta, tpla.bdnomcta as bdnomcta_conta, tpla.bdnomcta as bdnomcta_conta_original, tpla.bdgrupocta as bdgrupocta_conta, tpla.bdtipcta as bdtipcta_conta, ';
    WSQL = WSQL || '       tpla.bdclanom,';
    IF ((WSELECTCTA IS NOT NULL) AND
        (WSELECTCTA > 0)) THEN
      WSQL = WSQL || 'case when lista.BDTIPOSELECAO = 1 then tpla.bdparticipante else 0 end as bdparticipante, ';
    ELSE
      WSQL = WSQL || 'tpla.bdparticipante, ';

    WSQL = WSQL || '       tplaCtr.bdcodtpla as BDCONTRA, tx.bdcodterceiroc as bdcodter_contra, tplaCtr.bdctalon as bdctalon_contra, tplaCtr.bdnomcta as bdnomcta_contra, tplaCtr.bdparticipante as bdparticipante_contra, ';
  END
  WSQL = WSQL || '       tx.bddebito, tx.bdcredito, tx.debcre, ';
  WSQL = WSQL || '       tx.bdcodcentro, tx.bdcodtpcc, tx.bdtransacao, tx.BDTRANFECHADA, TERC.BDCGCTER, null as BDNOMETER ';
  WSQL = WSQL || ' , TX.bdcodempreendimento, TX.bdcodigouniimob, '; --#alt:93770. Ana - 15/01/2019

  WSQL = WSQL || ' case when TX.DEBCRE = 0 then (case ';
  WSQL = WSQL || ' when BDTIPOPE = 0 and TLPR.BDTIPMOV = 0 then ' || '''000''';
  WSQL = WSQL || ' when BDTIPOPE = 0 and TLPR.BDTIPMOV = 1 then iif(CTA.BDCODLCDPR > 0, CTA.BDCODLCDPR, null) ';
  WSQL = WSQL || ' when BDTIPOPE = 0 and TLPR.BDTIPMOV = 2 then ' || '''999''';
  WSQL = WSQL || ' when BDTIPOPE = 1 and TLPR.BDTRANSTIPMOV = 0 then ' || '''000''';
  WSQL = WSQL || ' when BDTIPOPE = 1 and TLPR.BDTRANSTIPMOV = 1 then iif(TRN.BDCODLCDPR > 0, TRN.BDCODLCDPR, null) ';
  WSQL = WSQL || ' when BDTIPOPE = 1 and TLPR.BDTRANSTIPMOV = 2 then ' || '''999''' || ' end)';
  WSQL = WSQL || ' when TX.DEBCRE = 1 then (case ';
  WSQL = WSQL || ' when BDTIPOPE = 1 and TLPR.BDTIPMOV = 0 then ' || '''000''';
  WSQL = WSQL || ' when BDTIPOPE = 1 and TLPR.BDTIPMOV = 1 then iif(CTA.BDCODLCDPR > 0, CTA.BDCODLCDPR, null) ';
  WSQL = WSQL || ' when BDTIPOPE = 1 and TLPR.BDTIPMOV = 2 then ' || '''999''';
  WSQL = WSQL || ' when BDTIPOPE = 0 and TLPR.BDTRANSTIPMOV = 0 then ' || '''000''';
  WSQL = WSQL || ' when BDTIPOPE = 0 and TLPR.BDTRANSTIPMOV = 1 then iif(TRN.BDCODLCDPR > 0, TRN.BDCODLCDPR, null) ';
  WSQL = WSQL || ' when BDTIPOPE = 0 and TLPR.BDTRANSTIPMOV = 2 then ' || '''999''' || ' end)';
  WSQL = WSQL || '  else null end as BDCTALCDPR, ';

  WSQL = WSQL || ' case ';
  WSQL = WSQL || ' when coalesce(TLPR.BDTIPOPARTICIPANTE,0) = 0 then PART.BDCGCTER ';
  WSQL = WSQL || ' when coalesce(TLPR.BDTIPOPARTICIPANTE,0) = 1 then EMP.BDCNPJEMP ';
  WSQL = WSQL || ' when coalesce(TLPR.BDTIPOPARTICIPANTE,0) = 2 then TLPR.BDCPFMANUAL ';
  WSQL = WSQL || ' else null end as BDPART_RURAL,';
  WSQL = WSQL || ' case when TX.DEBCRE = 0 and coalesce(BDTIPOPE,0) = 0 and coalesce(TLPR.BDTIPOPARTICIPANTE,0) = 0 then PART.BDCODTER ';
  WSQL = WSQL || ' when TX.DEBCRE = 1 and coalesce(BDTIPOPE,0) = 1 and coalesce(TLPR.BDTIPOPARTICIPANTE,0) = 0 then PART.BDCODTER ';
  WSQL = WSQL || ' else null end as BDCODPART_RURAL, TLPR.BDTIPLAN, TLPR.BDCODIMOVRUR, TLPR.bdtipdoc as BDTIPDOCPR, ';
  WSQL = WSQL || ' tpla.bdsalrelconciliacoes ';

  -- Carlos Machado #alt:127357 - Movido filtro para cima, deve filtrar as contas antes de fazer o select
  WSQL = WSQL || 'from (select * from planos_tpla tpla ';
  SELECT FIRST 1 BDCODPLAPADRAO
  FROM TEMPRESAS_REF
  WHERE BDCODEMP = :PRCODMATRIZ AND
        BDREFEMP <= :PRREFEMP
  ORDER BY BDCODEMP DESC, BDREFEMP DESC
  INTO :WCODPLAPADRAO;
  
  IF (WCODPLAPADRAO IS NULL) THEN
    BEGIN
        SELECT FIRST 1 BDCODPLAPADRAO
        FROM TEMPRESAS_REF
        WHERE BDCODEMP = :PRCODMATRIZ
        ORDER BY BDREFEMP asc
        INTO :WCODPLAPADRAO;
    END
 
  -- seleção de contas ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  IF ((WSELECTCTA IS NOT NULL) AND
      (WSELECTCTA > 0)) THEN
    WSQL = WSQL || 'where (tpla.BDCODPLAPADRAO = ' || WCODPLAPADRAO || ' and tpla.BDCODTPLA in (select bdcodtpla from vsuc_select_contas tsel)) ';
  ELSE
    BEGIN
    IF (PRPLANO_SECUNDARIO > 0) THEN
      WSQL = WSQL || 'where (tpla.BDCODPLAPADRAO = ' || WCODPLAPADRAO || ' and tpla.BDTIPCTA = 1) ';
    ELSE
      WSQL = WSQL || 'where (tpla.BDCODPLAPADRAO = ' || WCODPLAPADRAO || ' and tpla.BDCTALON between ''' || PRCLASSIFICACAO_INICIAL || ''' and ''' || PRCLASSIFICACAO_FINAL || ''' and tpla.BDTIPCTA = 1) ';
    END
  WSQL = WSQL || ') tpla left outer join (';
  -- debito -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  WSQL = WSQL || 'select tlan.bdchave, tlan.bddata, tlan.bdcodemp, tlan.bdcodplapadrao, ';
  WSQL = WSQL || '       tlan.bdlote, tlan.bdcompl, tlan.bddcto, ';
  WSQL = WSQL || '  ';
  WSQL = WSQL || '       tlan.bdtipolan, tlan.bdchaveonline, ';
  WSQL = WSQL || '       tlan.bdcodhist, tlan.bdcodtphi, ';
  WSQL = WSQL || '       tlan.bddebito as bdconta, tlan.bdcodterceirod as bdcodter, tlan.bdconcd as bdconc, tlan.bdconciliacaopendente, ';
  WSQL = WSQL || '       tlan.bdcredito as bdcontra, tlan.bdcodterceiroc, tlan.bdtransacao, tlan.BDTRANFECHADA, ';
  WSQL = WSQL || '       TINCORP.bdcodempreendimento, TINCORP.bdcodigouniimob, '; --#alt:93770. Ana - 15/01/2019

  --alt:1186 - Colocado aqui em cima e adicionada validação do novo parâmetro, pois precisa o novo parâmetro antes do LancamentoSemCC. Pedro
  IF ((PRLCC = '') OR (PRDETALHARCC = 0)) THEN
     BEGIN
    --alt:6178 - 09/11/2015 - Verifica se foi informado um índice, caso positivo, divide o valor do lançamento pelo valor do índice na data. Função dos relatórios em outra moeda. Pedro
    IF (COALESCE(PRPRODRURAL, 'FALSE') = 'TRUE') THEN
    BEGIN
      WSQL = WSQL || ' case when TLDPR.BDTIPOPE = 1 and coalesce(TLDPR.bdtransferencia, ' || '''FALSE''' || ') = ' || '''FALSE''' || '  then 0 ';
      WSQL = WSQL || ' else TLAN.BDVALOR end as BDDEBITO, ';
      WSQL = WSQL || ' case when TLDPR.BDTIPOPE = 1 and coalesce(TLDPR.bdtransferencia, ' || '''FALSE''' || ') = ' || '''FALSE''' || ' then TLAN.BDVALOR ';
      WSQL = WSQL || ' else 0 end as BDCREDITO, case ';
      WSQL = WSQL || ' when TLDPR.BDTIPOPE = 1 and coalesce(TLDPR.bdtransferencia, ' || '''FALSE''' || ') = ' || '''FALSE''' || ' then 1 ';
      WSQL = WSQL || ' else 0 end as DEBCRE, ';
    END
       ELSE
         BEGIN
      IF (PRINDICE = 0) THEN
        WSQL = WSQL || 'tlan.bdvalor as bddebito,';
      ELSE
      BEGIN
        WSQL = WSQL || 'tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
        WSQL = WSQL || '                        (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) as bddebito,';
         END
       --alt:6178 - Fim

      WSQL = WSQL || '       null as bdcredito, 0 as debcre, ';
     END
    WSQL = WSQL || '       null as bdcodcentro, null as bdcodtpcc ';
    WSQL = WSQL || 'from vsuc_empresas_tlan tlan ';
  END
  ELSE

  --alt:1186 - Fim
  --alt:7794 - Adicionada a opção de mostrar lançamentos sem centro de custo. Pedro
  IF (PRLANCAMENTOSEMCC <> 0) THEN
     BEGIN
    --alt:6178 - 09/11/2015 - Verifica se foi informado um índice, caso positivo, divide o valor do lançamento pelo valor do índice na data. Função dos relatórios em outra moeda. Pedro
    IF (PRINDICE = 0) THEN
      WSQL = WSQL || 'case when TLCC.BDVALOR is null then TLAN.BDVALOR else TLCC.BDVALOR end as BDDEBITO, ';
       ELSE
         BEGIN
      WSQL = WSQL || 'case when TLCC.BDVALOR is null then TLAN.BDVALOR else TLCC.BDVALOR end';
      WSQL = WSQL || '          / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
      WSQL = WSQL || '                     (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) as bddebito,';
         END
       --alt:6178 - Fim

    WSQL = WSQL || '       null as bdcredito, 0 as debcre, TLCC.BDCODCENTRO, TLCC.BDCODTPCC ';
    WSQL = WSQL || 'from vsuc_empresas_tlan tlan ';
       --alt:9149 - Adicionado "TLCC.BDDEBCRE = 0" porque se tiver centro de custo no crédito e não tiver no débito, não retorna o sem cento de custo do débito. Pedro
    WSQL = WSQL || 'left outer join VSUC_EMPRESAS_TLCC TLCC on (TLAN.BDCODEMP = TLCC.BDCODEMP and TLAN.BDCHAVE = TLCC.BDCHAVE and TLCC.BDDEBCRE = 0) ';
     END
  ELSE
  --alt:7794 - Fim
  -- centro de custo a debito --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
     BEGIN
    --alt:6178 - 09/11/2015 - Verifica se foi informado um índice, caso positivo, divide o valor do lançamento pelo valor do índice na data. Função dos relatórios em outra moeda. Pedro
    IF (PRINDICE = 0) THEN
      WSQL = WSQL || 'tlcc.bdvalor as bddebito,';
       ELSE
         BEGIN
      WSQL = WSQL || 'tlcc.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
      WSQL = WSQL || '                        (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) as bddebito,';
         END
       --alt:6178 - Fim
    WSQL = WSQL || '       null as bdcredito, 0 as debcre, ';
    WSQL = WSQL || '       tlcc.bdcodcentro, tlcc.bdcodtpcc ';
    WSQL = WSQL || 'from vsuc_empresas_tlcc tlcc ';
    WSQL = WSQL || 'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
     END

  WSQL = WSQL || 'left join VSUC_EMPRESAS_TLINCORP TINCORP on (TINCORP.bdcodemp = TLAN.BDCODEMP and TINCORP.bdchave = TLAN.BDCHAVE and TINCORP.bddebcre = 0) '; --#alt:93770. Ana - 15/01/2019
  WSQL = WSQL || 'left outer join VSUC_EMPRESAS_TLPR TLDPR on (TLAN.BDCHAVE = TLDPR.BDCHAVE and TLAN.BDCODEMP = TLDPR.BDCODEMP) ';
  WSQL = WSQL || 'where (tlan.bddata between ''' || PRDATA_INICIAL || ''' and ''' || PRDATA_FINAL || ''') ';

  -- contabilização ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  IF (PRCONTABILIZACAO <> 99) THEN
    WSQL = WSQL || 'and (tlan.bdcontabilizacao in (0,' || PRCONTABILIZACAO || ')) ';
 
  if (PRFILTIPOLAN <> '') then --#212425
    WSQL = WSQL || ' and (tlan.bdtipolan in ('|| PRFILTIPOLAN ||')) '; 

  -- filtro de centro de custo a debito ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  IF (PRLCC <> '') THEN
     BEGIN
       --alt:1186 - Adicionada essa validação para aqui tratar quando não for para detalhar por centro de custo mas deve validar os
    --centros de custos selecionados ou sem centro de custos, caso que ocorre no Razão em Vídeo. Pedro
    IF (PRDETALHARCC = 0) THEN
         BEGIN
      WSQL = WSQL || 'and (exists (select first 1 * from VSUC_EMPRESAS_TLCC tlcc where tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave ';
      WSQL = WSQL || 'and tlcc.bdcodtpcc in (' || TRIM(PRLCC) || ') and tlcc.bddebcre = 0) ';
      IF (PRLANCAMENTOSEMCC <> 0) THEN
        WSQL = WSQL || 'or not exists (select first 1 * from VSUC_EMPRESAS_TLCC tlcc where tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave and tlcc.bddebcre = 0)) ';
           ELSE
        WSQL = WSQL || ')';
         END

       --alt:1186 - Fim
       ELSE
    IF (PRLANCAMENTOSEMCC <> 0) THEN
      WSQL = WSQL || 'and ((tlcc.bdcodtpcc in (' || TRIM(PRLCC) || ') and tlcc.bddebcre = 0) or (TLCC.BDCODTPCC is null)) ';
       ELSE
      WSQL = WSQL || 'and (tlcc.bdcodtpcc in (' || TRIM(PRLCC) || ') and tlcc.bddebcre = 0) ';
     END

  -- filtro de participante a debito -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  --#alt:91311. Quando o CNPJ é o mesmo para os participantes e selecionava apenas um, não estava agrupando. Ana - 11/10/2018
  --#alt:82544 - Carlos Machado - 17/09/2018
  IF ((COALESCE(PRLISTAPART, '') <> '') AND
      (PRAGRUPARPARTICIPANTEPORCNPJ = 0) AND
      (PRAGRUPARPARTICIPANTEPORCPF = 0)) THEN
    WSQL = WSQL || 'and ((tlan.bdcodterceirod in (' || PRLISTAPART || ')) or (coalesce(tlan.bdcodterceirod,0) = 0)) ';
  ELSE
  IF ((PRPARTINI IS NOT NULL) AND
      (PRPARTFIN IS NOT NULL) AND
      (PRAGRUPARPARTICIPANTEPORCNPJ = 0) AND
      (PRAGRUPARPARTICIPANTEPORCPF = 0)) THEN
    WSQL = WSQL || 'and ((tlan.bdcodterceirod between ' || PRPARTINI || ' and ' || PRPARTFIN || ') or (coalesce(tlan.bdcodterceirod,0) = 0)) ';

  -- ignora zeramento ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  IF (PRIGNORAZERAMENTO <> 0) THEN
    WSQL = WSQL || 'and (tlan.bdtipolan <> 10) ';
  WSQL = WSQL || 'and (tlan.bdcodemp in (' || PRCODEMP || ')) ';

  WSQL = WSQL || 'union ';
  -- credito -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  WSQL = WSQL || 'select tlan.bdchave, tlan.bddata, tlan.bdcodemp, tlan.bdcodplapadrao, ';
  WSQL = WSQL || '       tlan.bdlote, tlan.bdcompl, tlan.bddcto, ';
  WSQL = WSQL || '  ';
  WSQL = WSQL || '       tlan.bdtipolan, tlan.bdchaveonline, ';
  WSQL = WSQL || '       tlan.bdcodhist, tlan.bdcodtphi, ';
  WSQL = WSQL || '       tlan.bdcredito as bdconta, tlan.bdcodterceiroc as bdcodter, tlan.bdconcc as bdconc, tlan.bdconciliacaopendente, ';
  WSQL = WSQL || '       tlan.bddebito as bdcontra, tlan.bdcodterceirod, tlan.bdtransacao, tlan.BDTRANFECHADA, ';
  WSQL = WSQL || '       TINCORP.bdcodempreendimento, TINCORP.bdcodigouniimob, '; --#alt:93770. Ana - 15/01/2019

  --alt:1186 - Colocado aqui em cima e adicionada validação do novo parâmetro, pois precisa o novo parâmetro antes do LancamentoSemCC. Pedro
  IF ((PRLCC = '') OR (PRDETALHARCC = 0)) THEN
     BEGIN
    IF (COALESCE(PRPRODRURAL, 'FALSE') = 'TRUE') THEN
    BEGIN
      WSQL = WSQL || ' case when TLDPR.BDTIPOPE = 0 and coalesce(TLDPR.bdtransferencia, ' || '''FALSE''' || ') = ' || '''FALSE''' || ' then TLAN.BDVALOR ';
      WSQL = WSQL || ' else 0 end as BDDEBITO, case when TLDPR.BDTIPOPE = 0 and coalesce(TLDPR.bdtransferencia, ' || '''FALSE''' || ') = ' || '''FALSE''' || ' then 0 ';
      WSQL = WSQL || ' else TLAN.BDVALOR end as BDCREDITO, ';
      WSQL = WSQL || ' case when TLDPR.BDTIPOPE = 0 and coalesce(TLDPR.bdtransferencia, ' || '''FALSE''' || ') = ' || '''FALSE''' || ' then 0 ';
      WSQL = WSQL || 'else 1 end as DEBCRE, ';
    END
    ELSE
    BEGIN
      WSQL = WSQL || 'null as bddebito, ';
      --alt:6178 - 09/11/2015 - Verifica se foi informado um índice, caso positivo, divide o valor do lançamento pelo valor do índice na data. Função dos relatórios em outra moeda. Pedro
      IF (PRINDICE = 0) THEN
        WSQL = WSQL || 'tlan.bdvalor as bdcredito,';
       ELSE
         BEGIN
        WSQL = WSQL || 'tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
        WSQL = WSQL || '                        (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) as bdcredito,';
         END
       --alt:6178 - Fim
      WSQL = WSQL || '       1 as debcre,';
     END
    WSQL = WSQL || ' null as bdcodcentro, null as bdcodtpcc ';
    WSQL = WSQL || 'from vsuc_empresas_tlan tlan ';
  END
  ELSE

  --alt:1186 - Fim

  IF (PRLANCAMENTOSEMCC <> 0) THEN
     BEGIN
    WSQL = WSQL || 'null as bddebito, ';
    --alt:6178 - 09/11/2015 - Verifica se foi informado um índice, caso positivo, divide o valor do lançamento pelo valor do índice na data. Função dos relatórios em outra moeda. Pedro
    IF (PRINDICE = 0) THEN
      WSQL = WSQL || 'case when TLCC.BDVALOR is null then TLAN.BDVALOR else TLCC.BDVALOR end as bdcredito, ';
       ELSE
         BEGIN
      WSQL = WSQL || 'case when TLCC.BDVALOR is null then TLAN.BDVALOR else TLCC.BDVALOR end';
      WSQL = WSQL || '          / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
      WSQL = WSQL || '                     (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) as bdcredito,';
         END
       --alt:6178 - Fim

    WSQL = WSQL || '       1 as debcre, TLCC.BDCODCENTRO, TLCC.BDCODTPCC ';
    WSQL = WSQL || 'from vsuc_empresas_tlan tlan ';
    WSQL = WSQL || 'left outer join VSUC_EMPRESAS_TLCC TLCC on (TLAN.BDCODEMP = TLCC.BDCODEMP and TLAN.BDCHAVE = TLCC.BDCHAVE and TLCC.BDDEBCRE = 1) ';
     END
  ELSE
  -- centro de custo a credito -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
     BEGIN
    WSQL = WSQL || 'null as bddebito, ';
    --alt:6178 - 09/11/2015 - Verifica se foi informado um índice, caso positivo, divide o valor do lançamento pelo valor do índice na data. Função dos relatórios em outra moeda. Pedro
    IF (PRINDICE = 0) THEN
      WSQL = WSQL || 'tlcc.bdvalor as bdcredito,';
       ELSE
         BEGIN
      WSQL = WSQL || 'tlcc.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
      WSQL = WSQL || '                        (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) as bdcredito,';
         END
       --alt:6178 - Fim
    WSQL = WSQL || '       1 as debcre, tlcc.bdcodcentro, tlcc.bdcodtpcc ';
    WSQL = WSQL || 'from vsuc_empresas_tlcc tlcc ';
    WSQL = WSQL || 'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
     END

  WSQL = WSQL || 'left join VSUC_EMPRESAS_TLINCORP TINCORP on (TINCORP.bdcodemp = TLAN.BDCODEMP and TINCORP.bdchave = TLAN.BDCHAVE and TINCORP.bddebcre = 1) '; --#alt:93770. Ana - 15/01/2019
  WSQL = WSQL || 'left outer join VSUC_EMPRESAS_TLPR TLDPR on (TLAN.BDCHAVE = TLDPR.BDCHAVE and TLAN.BDCODEMP = TLDPR.BDCODEMP) ';
  WSQL = WSQL || 'where (tlan.bddata between ''' || PRDATA_INICIAL || ''' and ''' || PRDATA_FINAL || ''') ';

  -- contabilização ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  IF (PRCONTABILIZACAO <> 99) THEN
    WSQL = WSQL || 'and (tlan.bdcontabilizacao in (0,' || PRCONTABILIZACAO || ')) ';
 
  if (PRFILTIPOLAN <> '') then --#212425
    WSQL = WSQL || ' and (tlan.bdtipolan in ('|| PRFILTIPOLAN ||')) '; 
  -- filtro de centro de custo a credito ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  IF (PRLCC <> '') THEN
     BEGIN
       --alt:1186 - Adicionada essa validação para aqui tratar quando não for para detalhar por centro de custo mas deve validar os
    --centros de custos selecionados ou sem centro de custos, caso que ocorre no Razão em Vídeo. Pedro
    IF (PRDETALHARCC = 0) THEN
         BEGIN
      WSQL = WSQL || 'and (exists (select first 1 * from VSUC_EMPRESAS_TLCC tlcc where tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave ';
      WSQL = WSQL || 'and tlcc.bdcodtpcc in (' || TRIM(PRLCC) || ') and tlcc.bddebcre = 1) ';
      IF (PRLANCAMENTOSEMCC <> 0) THEN
        WSQL = WSQL || 'or not exists (select first 1 * from VSUC_EMPRESAS_TLCC tlcc where tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave and tlcc.bddebcre = 1)) ';
           ELSE
        WSQL = WSQL || ')';
         END

       --alt:1186 - Fim
       ELSE
    IF (PRLANCAMENTOSEMCC <> 0) THEN
      WSQL = WSQL || 'and ((tlcc.bdcodtpcc in (' || TRIM(PRLCC) || ') and tlcc.bddebcre = 1) or (TLCC.BDCODTPCC is null)) ';
       ELSE
      WSQL = WSQL || 'and (tlcc.bdcodtpcc in (' || TRIM(PRLCC) || ') and tlcc.bddebcre = 1) ';
     END

  -- filtro de participante a credito -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  --#alt:91311. Quando o CNPJ é o mesmo para os participantes e selecionava apenas um, não estava agrupando. Ana - 11/10/2018
  --#alt:82544 - Carlos Machado - 17/09/2018
  IF ((COALESCE(PRLISTAPART, '') <> '') AND
      (PRAGRUPARPARTICIPANTEPORCNPJ = 0) AND
      (PRAGRUPARPARTICIPANTEPORCPF = 0)) THEN
    WSQL = WSQL || 'and ((tlan.bdcodterceiroc in (' || PRLISTAPART || ')) or (coalesce(tlan.bdcodterceiroc,0) = 0)) ';
  ELSE
  IF ((PRPARTINI IS NOT NULL) AND
      (PRPARTFIN IS NOT NULL) AND
      (PRAGRUPARPARTICIPANTEPORCNPJ = 0) AND
      (PRAGRUPARPARTICIPANTEPORCPF = 0)) THEN
  --IF ((prpartini IS NOT NULL) AND (prpartfin IS NOT NULL)) THEN
    WSQL = WSQL || 'and ((tlan.bdcodterceiroc between ' || PRPARTINI || ' and ' || PRPARTFIN || ') or (coalesce(tlan.bdcodterceiroc,0) = 0)) ';

  -- ignora zeramento ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  IF (PRIGNORAZERAMENTO <> 0) THEN
    WSQL = WSQL || 'and (tlan.bdtipolan <> 10) ';
  WSQL = WSQL || 'and (tlan.bdcodemp in (' || PRCODEMP || ')) ';

  WSQL = WSQL || ') tx on (tpla.bdcodplapadrao = tx.bdcodplapadrao and tpla.bdcodtpla = tx.bdconta';

  WSQL = WSQL || ') ';
  WSQL = WSQL || 'left outer join hist_tphi this on (this.bdcodhist = tx.bdcodhist and this.bdcodtphi = tx.bdcodtphi) ';
  WSQL = WSQL || 'left outer join planos_tpla tplaCtr on (tplaCtr.bdcodplapadrao = tx.bdcodplapadrao and tplaCtr.bdcodtpla = tx.bdcontra';
  WSQL = WSQL || ') ';

  --#Alt:21066 - Alterado por causa da lentidão (Carlos Mello - 29/11/2017)
  --wsql = wsql||'left join vw_empresas_ref_atual emp on (emp.bdcodemp = tx.bdcodemp) ';
  WSQL = WSQL || 'left join TEMPRESAS EMP on (EMP.BDCODEMP = TX.BDCODEMP) ';
  WSQL = WSQL || 'left join ( Select bdCODEMP, bdNOMEMP from TEMPRESAS_REF REF ';
  WSQL = WSQL || '            where ';
  WSQL = WSQL || '           (REF.bdCODEMP in (' || PRCODEMP || ')) and ';
  WSQL = WSQL || '           (REF.bdREFEMP = (SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x ';
  WSQL = WSQL || '                            WHERE x.bdcodemp in (' || PRCODEMP || ') AND ';
  WSQL = WSQL || '                            X.BDREFEMP <= (SELECT TRIM(rdb$get_context(' || '''USER_SESSION''' || ',' || '''W_ANOMES''' || ')) FROM rdb$database) ';
  WSQL = WSQL || '                            ORDER BY x.bdcodemp DESC, x.bdrefemp DESC)) ';
  WSQL = WSQL || '          ) EMPREF on (EMPREF.BDCODEMP = TX.BDCODEMP) ';
  --#Alt:21066 - Fim
  WSQL = WSQL || 'left join TTERCEIRO terc on (terc.bdcodter = tx.bdcodter) '; --alt:13329 - 10/02/2016 - Ordenar participante pelo CGC e utilizado no caso de agrupar pelo CNPJ. Pedro

  --alt:9167 - Caso seja para agrupar participante por CNPJ, foi adicionada essa cláusula where para fazer isso. Pedro
  --#alt:145558 - Machado - 11/06/2021 - Agrupar participante por CPF.
  IF ((COALESCE(PRLISTAPART, '') <> '') AND
      (1 IN (PRAGRUPARPARTICIPANTEPORCNPJ, PRAGRUPARPARTICIPANTEPORCPF))) THEN
  BEGIN
    IF (POSITION(',' IN PRLISTAPART) = 0) THEN
    BEGIN
      WSQL = WSQL || 'join TTERCEIRO terAux on (terAux.BDCODTER in (' || PRLISTAPART || ') and ((terc.BDCODTER = terAux.BDCODTER)';
      IF (PRAGRUPARPARTICIPANTEPORCNPJ = 1) THEN
        WSQL = WSQL || ' or (CHAR_LENGTH(TRIM(terAux.BDCGCTER)) = 18 and substring(terc.BDCGCTER from 1 for 10) = substring(terAux.BDCGCTER from 1 for 10))';
      IF (PRAGRUPARPARTICIPANTEPORCPF = 1) THEN
        WSQL = WSQL || ' or (CHAR_LENGTH(TRIM(terAux.BDCGCTER)) = 14 and terc.BDCGCTER = terAux.BDCGCTER)';
      WSQL = WSQL || ')) ';
    END
    ELSE
      WSQL = WSQL || 'join TTERCEIRO terAux on (terc.BDCODTER = terAux.BDCODTER and terAux.BDCODTER in (' || PRLISTAPART || ')) ';
  END
  ELSE
  IF ((PRPARTINI IS NOT NULL) AND
      (PRPARTFIN IS NOT NULL) AND
      (1 IN (PRAGRUPARPARTICIPANTEPORCNPJ, PRAGRUPARPARTICIPANTEPORCPF))) THEN
  BEGIN
    --#alt:91311. Quando o CNPJ é o mesmo para os participantes e selecionava apenas um, não estava agrupando. Por isso é necessário o join. Ana - 11/10/2018
    --#alt:82544 - Carlos Machado - 17/09/2018 - Não vi sentido em fazer aqui, além de deixar tudo mais complexo, em alguns casos não funcionava
    --alt:16679 - 30/05/2017 - Caso o participante inicial seja o mesmo que o final, não pode fazer esse filtro do código do participante, implementado na alteração #16045, senão não trás . Pedro
    --#alt:145558 - Machado - 11/06/2021 - Agrupar participante por CPF.
    IF (PRPARTINI = PRPARTFIN) THEN
    BEGIN
      WSQL = WSQL || 'join TTERCEIRO terAux on (terAux.BDCODTER between ' || PRPARTINI || ' and ' || PRPARTFIN || ' and ((terc.BDCODTER = terAux.BDCODTER)';
      IF (PRAGRUPARPARTICIPANTEPORCNPJ = 1) THEN
        WSQL = WSQL || ' or (CHAR_LENGTH(TRIM(terAux.BDCGCTER)) = 18 and substring(terc.BDCGCTER from 1 for 10) = substring(terAux.BDCGCTER from 1 for 10))';
      IF (PRAGRUPARPARTICIPANTEPORCPF = 1) THEN
        WSQL = WSQL || ' or (CHAR_LENGTH(TRIM(terAux.BDCGCTER)) = 14 and terc.BDCGCTER = terAux.BDCGCTER)';
      WSQL = WSQL || '))';
    END
    ELSE
      WSQL = WSQL || 'join TTERCEIRO terAux on (terc.BDCODTER = terAux.BDCODTER and terAux.BDCODTER between ' || PRPARTINI || ' and ' || PRPARTFIN || ' and substring(terc.BDCGCTER from 1 for 10) = substring(terAux.BDCGCTER from 1 for 10)) ';

  END
  --alt:9167 - Fim

  -- detalhar contas específicas de participantes ------------------------------------------------------------------------------------------------------------------------------------------------------------------
  WSQL = WSQL || 'left join VSUC_SELECT_CONTAS lista on (tpla.BDCODPLAPADRAO = lista.BDCODPLAPADRAO and tpla.BDCODTPLA = lista.BDCODTPLA) ';
  -- Carlos Machado #alt:127357 - Movido filtro para cima, deve filtrar as contas antes de fazer o select
  --  -- seleção de contas ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  --  IF ((wselectcta IS NOT NULL) AND (wselectcta > 0)) THEN
  --     wsql = wsql||'where (tpla.BDCODTPLA in (select bdcodtpla from vsuc_select_contas tsel)) ';
  --  ELSE
  --   BEGIN
  --      SELECT FIRST 1 BDCODPLAPADRAO FROM TEMPRESAS_REF WHERE BDCODEMP = :prCodMatriz AND BDREFEMP <= :prRefEmp ORDER BY BDCODEMP DESC, BDREFEMP DESC INTO :wCodPlaPadrao;
  --      wsql = wsql||'where (tpla.BDCODPLAPADRAO = '||wCodPlaPadrao||' and tpla.BDCTALON between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''' and tpla.BDTIPCTA = 1) ';
  --    END
  -- Carlos Machado #alt:127357 - Linha causava lentidão, no razão saldos ele já faz ordenação
  --  wsql = wsql||'order by bdcodemp, bddata, bdconta, TERC.BDCGCTER ';
  WSQL = WSQL || 'left outer join VSUC_EMPRESAS_TLPR TLPR on (TX.BDCHAVE = TLPR.BDCHAVE and TX.BDCODEMP = TLPR.BDCODEMP) ';
  WSQL = WSQL || 'left outer join TEMPRESAS_CTACORRENTE CTA on (CTA.BDCODEMP = TLPR.BDCODEMP and CTA.BDCHAVE = TLPR.BDCTACOR) ';
  WSQL = WSQL || 'left outer join TEMPRESAS_CTACORRENTE TRN on (TRN.BDCODEMP = TLPR.BDCODEMP and TRN.BDCHAVE = TLPR.BDTRANSCTACOR) ';
  WSQL = WSQL || 'left outer join TTERCEIRO PART on (PART.BDCODTER = TLPR.BDCODTER) ';

  IF (PRPLANO_SECUNDARIO > 0) THEN
  BEGIN
      WSQL = WSQL || ' left outer join VSUC_PREPARACAO_TPLA_SECUNDARIO PREP_SEC on (PREP_SEC.bdcodemp = ' || PRCODMATRIZ;
      WSQL = WSQL || ' AND PREP_SEC.bdcodplapadrao_sec = ' || PRPLANO_SECUNDARIO || ' AND PREP_SEC.bdcodplapadrao = ' || WCODPLAPADRAO || ' AND PREP_SEC.bdcodtpla = tpla.BDCODTPLA ';
      if ((prplano_secundario = 1) and (substring(prdata_final from 1 for 4) > 2021)) then
        begin
          if (substring(prdata_final from 1 for 4) < 2025) then
            WANOCOSIF = 2024;
          else
          if (substring(prdata_final from 1 for 4) >= 2025) then
            WANOCOSIF = substring(prdata_final from 1 for 4);

          WSQL = WSQL ||' and PREP_SEC.BDANOPLACOSIF = '|| WANOCOSIF;
        end

      WSQL = WSQL ||')';
      WSQL = WSQL || ' left join PLANOS_TPLA_SECUNDARIO TSEC ON (TSEC.BDCODPLAPADRAO_SEC = PREP_SEC.BDCODPLAPADRAO_SEC AND TSEC.BDCODTPLA = PREP_SEC.BDCODTPLA_SEC ';
      if ((prplano_secundario = 1) and (substring(prdata_final from 1 for 4) > 2021)) then
        begin
          if (substring(prdata_final from 1 for 4) < 2025) then
            WSQL = WSQL || ' and ((2024 between TSEC.BDANOINIVALCOSIF and TSEC.BDANOFIMVALCOSIF) or (2024 = TSEC.BDANOINIVALCOSIF))';
          else
          if (substring(prdata_final from 1 for 4) >= 2025) then
            WSQL = WSQL || ' and ((TSEC.BDANOINIVALCOSIF = 2025 and TSEC.BDANOFIMVALCOSIF is null) or ('|| substring(prdata_final from 1 for 4) ||' = TSEC.BDANOINIVALCOSIF))';
          
        end

      WSQL = WSQL ||')';

      WSQL = WSQL || ' left join VSUC_PREPARACAO_TPLA_SECUNDARIO PREP_SEC_CTR on (PREP_SEC_CTR.bdcodemp = ' || PRCODMATRIZ;
      WSQL = WSQL || ' AND PREP_SEC_CTR.bdcodplapadrao_sec = ' || PRPLANO_SECUNDARIO || ' AND PREP_SEC_CTR.bdcodplapadrao = ' || WCODPLAPADRAO || ' AND PREP_SEC_CTR.bdcodtpla = tplaCtr.BDCODTPLA ';
      if ((prplano_secundario = 1) and (substring(prdata_final from 1 for 4) > 2021)) then
        begin
          if (substring(prdata_final from 1 for 4) < 2025) then
            WANOCOSIF = 2024;
          else
          if (substring(prdata_final from 1 for 4) >= 2025) then
            WANOCOSIF = substring(prdata_final from 1 for 4);

          WSQL = WSQL ||' and PREP_SEC_CTR.BDANOPLACOSIF = '|| WANOCOSIF;
        end

      WSQL = WSQL ||')';
      WSQL = WSQL || ' left join PLANOS_TPLA_SECUNDARIO TSEC_CTR ON (TSEC_CTR.BDCODPLAPADRAO_SEC = PREP_SEC_CTR.BDCODPLAPADRAO_SEC AND TSEC_CTR.BDCODTPLA = PREP_SEC_CTR.BDCODTPLA_SEC ';
      if ((prplano_secundario = 1) and (substring(prdata_final from 1 for 4) > 2021)) then
        begin
          if (substring(prdata_final from 1 for 4) < 2025) then
            WSQL = WSQL || ' and ((2024 between TSEC_CTR.BDANOINIVALCOSIF and TSEC_CTR.BDANOFIMVALCOSIF) or (2024 = TSEC_CTR.BDANOINIVALCOSIF))';
          else
          if (substring(prdata_final from 1 for 4) >= 2025) then
            WSQL = WSQL || ' and ((TSEC_CTR.BDANOINIVALCOSIF = 2025 and TSEC_CTR.BDANOFIMVALCOSIF is null) or ('||substring(prdata_final from 1 for 4)||' = TSEC_CTR.BDANOINIVALCOSIF))';

        end

      WSQL = WSQL ||')';
  END

  WWHERE = '';
  IF (COALESCE(PRPRODRURAL, 'FALSE') = 'TRUE') THEN
  BEGIN
    IF (PRIMOVEIS <> '' AND
        PRIMOVEIS IS NOT NULL) THEN
      WWHERE = WWHERE || 'TLPR.BDCODIMOVRUR in (' || PRIMOVEIS || ')';
    ELSE
      WWHERE = WWHERE || '(tpla.BDCTACAIXAPR collate win_ptbr = ''TRUE'' or tpla.BDCTABANCOPR collate win_ptbr = ''TRUE'' or tpla.BDCTATRANSPR collate win_ptbr = ''TRUE'')';
    --#193364 - Razão produtor rural - opção de não mostrar lançamentos sem dados de produtor rural. Marcela - 16/01/2024
    IF (COALESCE(PRNAOMOSTRARLANCSEMDADOSRU, 'FALSE') = 'TRUE') then
      WWHERE = WWHERE || 'AND (TX.BDCHAVE = TLPR.BDCHAVE)';
  END
  ELSE
  IF (PRIMOVEIS <> '' AND
      PRIMOVEIS IS NOT NULL) THEN
    WWHERE = WWHERE || 'TLPR.BDCODIMOVRUR in (' || PRIMOVEIS || ')';

  IF (PRPLANO_SECUNDARIO > 0) THEN
  BEGIN
    IF (WWHERE <> '') THEN
      WWHERE = WWHERE || ' and ';
    WWHERE = WWHERE || '(TSEC.BDCTALON between ''' || PRCLASSIFICACAO_INICIAL || ''' and ''' || PRCLASSIFICACAO_FINAL || ''')';
  END

  IF (prfiltrarempreendimento <> '' AND prfiltrarempreendimento IS NOT NULL) THEN
    begin
      if (WWHERE <> '') then
        WWHERE = WWHERE || ' and ';
      WWHERE = WWHERE || '(TX.BDCODEMPREENDIMENTO in (' || prfiltrarempreendimento || ') or ((tpla.bdctaempreendimentosimob = '||'''FALSE'''||') or (TPLA.BDCTAEMPREENDIMENTOSIMOB is null)))';
      if (prfiltrarunidimobiliaria <> '' and prfiltrarunidimobiliaria is not null) then
        WWHERE = WWHERE || 'and (TX.BDCODIGOUNIIMOB in (' || prfiltrarunidimobiliaria || ') or ((tpla.bdctaunidadeimob = '||'''FALSE'''||') or (TPLA.BDCTAUNIDADEIMOB is null)))';
    end

  IF (WWHERE <> '') THEN
    WSQL = WSQL || ' WHERE ' || WWHERE;

  FOR EXECUTE STATEMENT WSQL
          INTO :PRCHAVE, :PRDATA, :PREMPRESA, :PRNOMEEMPRESA, :PRCNPJEMP, :PRCODPLAPADRAO, :PRLOTE, :PRCOMPL, :PRDCTO, :PRTIPOLAN, :PRCHAVEONLINE, :PRCODHIST, :PRCODTPHI, :PRHISTORICO, :PRCONTA, :PRCODTERCEIROCONTA, :PRCONCILIADO,
          :PRCONCILIACAOPENDENTE, :PRCLASS_CONTA, :PRNOME_CONTA, :PRNOME_CONTA_ORIGINAL, :PRGRPCTA, :WTIPCTACONTA, :PRCLANOM, :PRPARTICIPANTECONTA, :PRCONTRA, :PRCODTERCEIROCONTRA, :PRCLASS_CONTRA, :PRNOME_CONTA_CONTRA,
          :PRPARTICIPANTECONTRA, :PRDEBITO, :PRCREDITO, :PRDEBCRE, :PRCODCENTRO, :PRCC, :PRTRANSACAO, :PRTRANFECHADA, :PRCGC_CONTA, :WNOMETER, :PREMPREENDIMENTO, :PRUNIDIMOB, :PRCTALCDPR, :PRPART_PR, :PRCODPART_PR, :PRTIPLANPR,
          :PRCODIMOVRUR, :PRTIPDOCPR, :prsalrelconciliacoes
  DO
  BEGIN
    IF (PRCLANOM IS NULL) THEN
    BEGIN
      PRCLANOM = PRCLASS_CONTA;
        --se nao for conta titulo
      SELECT BDRPOS
      FROM RPOS('.', :PRCLANOM)
      INTO WPOS;
      IF (WPOS > 0) THEN
            BEGIN
        PRCLANOM = SUBSTRING(PRCLANOM FROM 1 FOR WPOS - 1);
        SELECT BDRETORNO
        FROM PREENCHE_DIREITA(:PRCLANOM, 40, ' ')
        INTO PRCLANOM;
        PRCLANOM = PRCLANOM || PRNOME_CONTA;
            END
    END

    --alt:13329 - 10/02/2016 - Foi trazido para cá o select que buscava o nome do participante, que agora também trás o código dele, mas apenas do "matriz" no caso de estar agrupando pelo CNPJ. Pedro
    IF ((PRPARTICIPANTECONTA = 1) AND
        (PRDETALHARCTAPARTICIPANTE = 1) AND
        (PRCODTERCEIROCONTA IS NOT NULL)) THEN
      BEGIN
      IF ((PRDETALHARCTAPARTICIPANTE = 1) AND
          (PRAGRUPARPARTICIPANTEPORCNPJ = 1) AND
          CHAR_LENGTH(TRIM(PRCGC_CONTA)) = 18) THEN
          --#89622 - Carlos Machado - 11/09/2018 - Alterado para não fazer agrupamento de participantes do exterior
        SELECT FIRST 1 BDCODTER, BDNOMETER
        FROM VW_TTERCEIRO
        WHERE (SUBSTRING(BDCGCTER FROM 1 FOR 10) = SUBSTRING(:PRCGC_CONTA FROM 1 FOR 10) AND
              BDCODPAIS = 30) OR (BDCODPAIS <> 30 AND
              BDCODTER = :PRCODTERCEIROCONTA)
        ORDER BY BDCGCTER
        INTO :WCODTER, :WNOMETER;
        ELSE
      IF ((PRDETALHARCTAPARTICIPANTE = 1) AND
          (PRAGRUPARPARTICIPANTEPORCPF = 1) AND
          CHAR_LENGTH(TRIM(PRCGC_CONTA)) = 14) THEN
        SELECT FIRST 1 BDCODTER, BDNOMETER
        FROM VW_TTERCEIRO
        WHERE (BDCGCTER = :PRCGC_CONTA AND
              BDCODPAIS = 30) OR (BDCODPAIS <> 30 AND
              BDCODTER = :PRCODTERCEIROCONTA)
        ORDER BY BDCGCTER
        INTO :WCODTER, :WNOMETER;
        ELSE
        SELECT FIRST 1 BDCODTER, BDNOMETER
        FROM TTERCEIRO_REF X
        WHERE BDCODTER = :PRCODTERCEIROCONTA
              --#149080 - 11/07/2022 Razão/Diário/Balancete - Verificar data de emissão pra nome de contas de participante. Marcela
              AND
              BDREFEMP <= COALESCE((SELECT FIRST 1 RF2.BDREFEMP
                                    FROM TTERCEIRO_REF RF2
                                    WHERE RF2.BDCODTER = X.BDCODTER AND
                                          RF2.BDREFEMP <= :PRREFEMP
                                    ORDER BY RF2.BDCODTER DESC, RF2.BDREFEMP DESC), (SELECT FIRST 1 RF2.BDREFEMP
                                                                                     FROM TTERCEIRO_REF RF2
                                                                                     WHERE RF2.BDCODTER = X.BDCODTER
                                                                                     ORDER BY RF2.BDCODTER, RF2.BDREFEMP))
        ORDER BY BDCODTER DESC, BDREFEMP DESC
        INTO :WCODTER, :WNOMETER;
      END

    IF (PREMPRESA IS NULL) THEN
      PREMPRESA = PRCODMATRIZ;
    --alt:13329 - Fim
    PRCODEMPFILIAL = PREMPRESA;

    --#ALT:59041. Ana - 21/11/2019
    IF (PRGRPCTA IN (1, 2, 3)) THEN
      BEGIN
      IF ((COALESCE(PRCREDITO, 0) <> 0) AND
          (COALESCE(PRDEBITO, 0) = 0)) THEN
        PRNATUREZALAN = 0;
        ELSE
      IF ((COALESCE(PRCREDITO, 0) = 0) AND
          (COALESCE(PRDEBITO, 0) <> 0)) THEN
        PRNATUREZALAN = 1;
      END
    ELSE
      BEGIN
      IF ((COALESCE(PRCREDITO, 0) = 0) AND
          (COALESCE(PRDEBITO, 0) <> 0)) THEN
        PRNATUREZALAN = 0;
        ELSE
      IF ((COALESCE(PRCREDITO, 0) <> 0) AND
          (COALESCE(PRDEBITO, 0) = 0)) THEN
        PRNATUREZALAN = 1;
      END

    IF ((PRDETALHARCTAPARTICIPANTE = 1) AND
        (PRPARTICIPANTECONTA = 1) AND
        (WTIPCTACONTA = 1) AND
        (PRCODTERCEIROCONTA IS NOT NULL)) THEN
       BEGIN
         --select bdclassificacao, bdnome from vsuc_sp_nomenclatura_cta_partic(:wcodterceirod,:wctalond,:prconcatenacodparticipante) into :wctalond,:wnomctad;
      PRCLASS_CONTA = REVERSE(PRCLASS_CONTA);
      PRCLASS_CONTA = SUBSTRING(PRCLASS_CONTA FROM POSITION('.', PRCLASS_CONTA) FOR STRLEN(PRCLASS_CONTA));
      PRCLASS_CONTA = REVERSE(PRCLASS_CONTA);
      --#alt:92930. A ordenação alfabética estava incorreta. Ana - 19/11/2018
      WPOS = CHARACTER_LENGTH(:PRCLASS_CONTA) - 1;
      PRCLANOM = SUBSTRING(PRCLASS_CONTA FROM 1 FOR WPOS) || ' ' || UPPER(WNOMETER);
      PRCLASS_CONTA = PRCLASS_CONTA || LPAD(WCODTER, 9, '0'); --alt:14526 - 27/06/2016 - Alterado de 8 para 9 casas para ficar igual ao Balancete e Cadastro de Participantes. Pedro

      IF (PRCONCATENACODPARTICIPANTE = 1) THEN
           BEGIN
        WPOS = CHARACTER_LENGTH(:WCODTER);
        WPOS = ((100 - WPOS) - 3);
        WNOMETER = WCODTER || ' - ' || SUBSTRING(WNOMETER FROM 1 FOR WPOS);
           END
      PRNOME_CONTA = SUBSTRING(WNOMETER FROM 1 FOR 100);
       END

    --#alt:70754. Ana - 28/09/2018
    IF ((PRDETALHARCTAPARTICIPANTE = 1) AND
        (prparticipantecontra = 1) AND
        (WTIPCTACONTA = 1) AND
        (prcodterceirocontra IS NOT NULL)) THEN
       BEGIN
      SELECT FIRST 1 BDCODTER, BDNOMETER
      FROM TTERCEIRO_REF X
      WHERE BDCODTER = :PRCODTERCEIROCONTRA
            --#149080 - 11/07/2022 Razão/Diário/Balancete - Verificar data de emissão pra nome de contas de participante. Marcela
            AND
            BDREFEMP <= COALESCE((SELECT FIRST 1 RF2.BDREFEMP
                                    FROM TTERCEIRO_REF RF2
                                    WHERE RF2.BDCODTER = X.BDCODTER AND
                                          RF2.BDREFEMP <= :PRREFEMP
                                    ORDER BY RF2.BDCODTER DESC, RF2.BDREFEMP DESC),
                                  (SELECT FIRST 1 RF2.BDREFEMP
                                     FROM TTERCEIRO_REF RF2
                                     WHERE RF2.BDCODTER = X.BDCODTER
                                     ORDER BY RF2.BDCODTER, RF2.BDREFEMP))
      ORDER BY BDCODTER DESC, BDREFEMP DESC
      INTO :WCODTER, :WNOMETER;

      PRCLASS_CONTRA = REVERSE(PRCLASS_CONTRA);
      PRCLASS_CONTRA = SUBSTRING(PRCLASS_CONTRA FROM POSITION('.', PRCLASS_CONTRA) FOR STRLEN(PRCLASS_CONTRA));
      PRCLASS_CONTRA = REVERSE(PRCLASS_CONTRA);
      PRCLASS_CONTRA = PRCLASS_CONTRA || LPAD(WCODTER, 9, '0');

      IF (PRCONCATENACODPARTICIPANTE = 1) THEN
           BEGIN
        WPOS = CHARACTER_LENGTH(:WCODTER);
        WPOS = ((100 - WPOS) - 3);
        WNOMETER = WCODTER || ' - ' || SUBSTRING(WNOMETER FROM 1 FOR WPOS);
           END
      PRNOME_CONTA_CONTRA = SUBSTRING(WNOMETER FROM 1 FOR 100);
       END

    --#alt:93770. Ana - 15/01/2019
    IF (((PRDETALHAREMPREENDIMENTO = 1) OR (PRDETALHARUNIDIMOB = 1)) AND
        (((PREMPREENDIMENTO IS NOT NULL) AND
        (PREMPREENDIMENTO > 0)) OR ((PRUNIDIMOB IS NOT NULL) AND
        (PRUNIDIMOB > 0)))) THEN
      BEGIN
        WNAODETALHAEMP = 0;
        IF (PRDETALHAREMPREENDIMENTO = 0) THEN
          WNAODETALHAEMP = 1;

        WNAODETALHAUNID = 0;
        IF (PRDETALHARUNIDIMOB = 0) THEN
          WNAODETALHAUNID = 1;

      WCLASS = NULL;
      SELECT FIRST 1 BDCLASSIFICACAO
      FROM VSUC_RETORNA_CLA_INCORP(:PRCONTA, :PRCODPLAPADRAO, :PREMPREENDIMENTO, :PRUNIDIMOB, :WNAODETALHAEMP, :WNAODETALHAUNID, :PREMPRESA)
      INTO :WCLASS;

        IF (WCLASS IS NOT NULL) THEN
          BEGIN
        PRCLASS_CONTA = WCLASS;

            WNOMEINCORP = '';
        IF ((PREMPREENDIMENTO IS NOT NULL) AND
            (PREMPREENDIMENTO > 0) AND
            (PRDETALHAREMPREENDIMENTO = 1)) THEN
              BEGIN
          SELECT SUBSTRING(BDNOMEEMPRE FROM 1 FOR 300)
          FROM VEF_EMP_TCADEMPREENDIMENTO
          WHERE BDCODEMP = :PREMPRESA AND
                BDCODEMPREENDIMENTO = :PREMPREENDIMENTO
          INTO :WNOMEINCORP;
              END
        IF ((PRUNIDIMOB IS NOT NULL) AND
            (PRUNIDIMOB > 0) AND
            (PRDETALHARUNIDIMOB = 1)) THEN
              BEGIN
          IF (WNOMEINCORP <> '') THEN
            WNOMEINCORP = WNOMEINCORP || ' - ';

          IF (PRPRMOSTRARPROPUNIDADE <> 0) THEN
            SELECT :WNOMEINCORP || SUBSTRING(CAD.BDDESCRICAO FROM 1 FOR 83) || COALESCE(' - ' || TER.BDCODTER || ' - ' || TER.BDNOMETER, ' - Não informado')
            FROM VEF_BASE_TCADUNIDIMOBILIARIA CAD
            LEFT JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = COALESCE((SELECT FIRST 1 F200.BDCODTER
                                                                    FROM VEF_EMP_TMOVOPIMOBILIARIA_F200 F200
                                                                    WHERE F200.BDCODEMP = CAD.BDCODEMP AND
                                                                          F200.BDCODEMPREENDIMENTO = CAD.BDCODEMPREENDIMENTO AND
                                                                          F200.BDCODIGOUNIIMOB = CAD.BDCODIGOUNIIMOB
                                                                    ORDER BY F200.BDCHAVE DESC), CAD.BDCODTER))
            WHERE CAD.BDCODEMP = :PREMPRESA AND
                  CAD.BDCODEMPREENDIMENTO = :PREMPREENDIMENTO AND
                  CAD.BDCODIGOUNIIMOB = :PRUNIDIMOB
            INTO :WNOMEINCORP;
          ELSE
            SELECT :WNOMEINCORP || SUBSTRING(CAD.BDDESCRICAO FROM 1 FOR 200)
            FROM VEF_BASE_TCADUNIDIMOBILIARIA CAD
            WHERE CAD.BDCODEMP = :PREMPRESA AND
                  CAD.BDCODEMPREENDIMENTO = :PREMPREENDIMENTO AND
                  CAD.BDCODIGOUNIIMOB = :PRUNIDIMOB
            INTO :WNOMEINCORP;
              END

            IF (WNOMEINCORP IS NOT NULL) THEN
              BEGIN
          WNOMEINCORP = SUBSTRING(WNOMEINCORP FROM 1 FOR 197 - CHAR_LENGTH(PRNOME_CONTA));
          PRNOME_CONTA = PRNOME_CONTA || ' (' || WNOMEINCORP || ')';
          PRCLANOM = PRCLASS_CONTA || ' ' || UPPER(WNOMEINCORP);
              END
          END
      END

    --alt:#6524 - implementado rotina "POS" aqui, por questão de desempenho, precisa apenas uma vez para as duas verificações
    --select bdpermite from vsuc_sp_permitecalcsaldolancmf(1,:wempprinc,:prempresa,:prmatrizfilialconsolidado,:prcodemp) into :wpermite;
    WCAMPO = PRDEBCRE + 1;

    WPERMITE = 1;
    -------------------------------------------------------------------alt:#6524
    --alt:13893 - 29/08/2016 - Também deve retornar o registro caso esteja marcado para trazer as contas sem movimento. Pedro
    --#alt:91184- 11/10/2018 - Carlos Machado - O tratamento de contas sem movimento agora é feito após a execução
    --IF ((wpermite = 1 AND (PRCHAVE IS NOT NULL)) OR ((prContasSemMovimento = 1) AND (PRCHAVE IS NULL))) THEN
    IF (PRCHAVE IS NOT NULL) THEN
       SUSPEND;
  END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_RAZAO_SALDO */
ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_SALDO(PRCODEMP VARCHAR(1024),
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRINDICE INTEGER,
PRLCC VARCHAR(8192),
PRORDEMPRESA INTEGER,
PRREFEMP INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
BDCONCILIADOS INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRAGRUPAR VARCHAR(1024),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARFILIAL INTEGER)
 RETURNS(BDHISTORICO VARCHAR(400),
BDDATA DATE,
BDCHAVE INTEGER,
BDCONTA INTEGER,
BDCONTRA INTEGER,
BDCREDITO NUMERIC(15,2),
BDDEBITO NUMERIC(15,2),
BDSALDO NUMERIC(15,2),
BDCONCILIADO VARCHAR(5),
BDEMPRESA INTEGER,
BDNOMEEMPRESA VARCHAR(100),
BDCODCENTRO INTEGER,
BDCC INTEGER,
BDNOME_CONTA VARCHAR(100),
BDCLASS_CONTA VARCHAR(40),
BDCOD_TERCEIRO_CONTA INTEGER,
BDCLASS_CONTRA VARCHAR(40),
BDNOME_CONTA_CONTRA VARCHAR(100),
BDCOD_TERCEIRO_CONTRA INTEGER,
BDVALOR NUMERIC(15,2),
BDORDSALDO INTEGER,
BDLOTE VARCHAR(10),
BDDCTO VARCHAR(15),
BDCOMPL VARCHAR(200),
BDCNPJEMP VARCHAR(18),
BDSALDOANTERIOR NUMERIC(15,2),
BDVALORSEMSINAL NUMERIC(15,2),
BDGRUPOCONTA INTEGER,
BDCODHIST INTEGER,
BDCODPLAPADRAO INTEGER,
BDREF VARCHAR(8),
BDCODTPHI INTEGER,
BDEMPRESAFILIAL INTEGER,
BDVLRCONCILIADO NUMERIC(15,2),
BDVLRACONCILIAR NUMERIC(15,2),
BDCHAVEONLINE VARCHAR(120))
 AS
DECLARE VARIABLE wconta INTEGER;
DECLARE VARIABLE wsaldo NUMERIC(15,2);
DECLARE VARIABLE wclass VARCHAR(40);
DECLARE VARIABLE wvalor NUMERIC(15,2);
DECLARE VARIABLE wordem INTEGER;
DECLARE VARIABLE wclassini VARCHAR(40);
DECLARE VARIABLE wclassfin VARCHAR(40);
DECLARE VARIABLE wtam INTEGER;
DECLARE VARIABLE wcredito NUMERIC(15,2);
DECLARE VARIABLE wdebito NUMERIC(15,2);
DECLARE VARIABLE wgrupocta INTEGER;
DECLARE VARIABLE wsqlsaldo VARCHAR(1024);
DECLARE VARIABLE wsql VARCHAR(10240);
DECLARE VARIABLE wparticipante INTEGER;
DECLARE VARIABLE wclass_ant VARCHAR(40);
DECLARE VARIABLE wpos INTEGER;
DECLARE VARIABLE wsqlemp VARCHAR(10240);
DECLARE VARIABLE wcodempefilial INTEGER;
DECLARE VARIABLE wcodmatriz INTEGER;
BEGIN
  EXECUTE STATEMENT 'delete from vsuc_empresas_trazao_saldo where bdcodemp is not null';

  wsql = 'insert into VSUC_EMPRESAS_TRAZAO_SALDO (BDCODEMP,BDCODPLAPADRAO,BDCODTPLA,BDCTALON,BDTIPCTA,BDGRPCTA,BDNOMCTA,BDCODCENTRO,BDCODTPCC,BDPARTICIPANTE,BDSALDO) ';
  wsql = wsql||'select tlan.bdcodemp, tlan.bdcodplapadrao, tlan.bdconta, ';
  wsql = wsql||'tpla.BDCTALON, tpla.BDTIPCTA, tpla.bdgrupocta, tpla.BDNOMCTA, tlan.bdcodcentro, tlan.bdcodtpcc, null as bdcodter, ';
  wsql = wsql||'((select SALDO_ANTERIOR from sp_retorna_saldo_emp(tlan.bdcodemp, tpla.bdcodtpla, '''||prdata_inicial||''', '''||prdata_final||''', 0, tlan.bdcodtpcc, null, '||prrefemp||', '||bdconciliados||','||prcontabilizacao||','||prmatrizfilialconsolidado||',tlan.bdparticipante))) ';
  wsql = wsql||'from (select distinct bdcodemp, bdcodplapadrao, bdconta, bdcodcentro, bdcodtpcc, bdparticipante ';--gilberto - 12/08/2013 - #alt:6159
  wsql = wsql||'from (select distinct tlan.bdcodemp, bdcodplapadrao, bddebito as bdconta, ';
  IF (TRIM(prlcc) = '') THEN
     wsql = wsql||' null as bdcodcentro, null as bdcodtpcc, tlan.bdcodterceirod as bdparticipante from vsuc_empresas_tlan tlan ';
  ELSE
     BEGIN
       wsql = wsql||'tlcc.bdcodcentro, tlcc.bdcodtpcc, tlan.bdcodterceirod as bdparticipante from vsuc_empresas_tlan tlan ';
       wsql = wsql||' left outer join vsuc_empresas_tlcc tlcc on (tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave and tlcc.bddebcre = 0 and tlcc.bdcodtpcc in ('||prlcc||')) ';
     END
  --Carlos Mello(05/02/2013) - Solicitação.: 5022. Não estava calculando o Saldo Anterior corretamente.
  --wsql = wsql||'     where tlan.bdcodemp in ('||prcodemp||') and bddata between '''||prdata_inicial||''' and '''||prdata_final||''' and bddebito is not null ';
-- GILBERTO - 23/04/2013 - 5504 - NÃO CALCULAVA SALDO ANTERIOR DA FILIAL SE A MESMA NÃO TIVER MOVIMENTO NO PERÍODO
--  wsql = wsql||'     where tlan.bdcodemp in ('||prcodemp||') and bddata between '''||substring(prdata_inicial from 1 for 4)||'-01-01'||''' and '''||substring(prdata_final from 1 for 4)||'-12-31'||''' and bddebito is not null ';
  --#alt:5837
  --wsql = wsql||'     where tlan.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'     where (tlan.bdcodemp in ('||prcodemp||')) ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'   and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
--  WSQL = WSQL||'     AND bddata <= '''||substring(prdata_final from 1 for 4)||'-12-31'||''' and bddebito is not null ';-- gilberto - 26/07/2013 - 6159
  WSQL = WSQL||'     AND bddata < '''||prdata_inicial||''' and bddebito is not null '; -- gilberto - 26/07/2013 - 6159
  -- gilberto - 28/05/2013 - incluido para considerar participante no calculo de saldo anterior
  IF ((prpartini IS NOT NULL) AND (prpartini <> 0)) THEN
     wsql = wsql||' and (tlan.bdcodterceirod >= '||prpartini||')';
  IF ((prpartfin IS NOT NULL) AND (prpartfin <> 0)) THEN
     wsql = wsql||' and (tlan.bdcodterceirod <= '||prpartfin||')';
  -- __________________________________________________________________________________________
  wsql = wsql||'      union all ';
  wsql = wsql||'      select distinct tlan.bdcodemp, bdcodplapadrao, bdcredito as bdconta, ';
  IF (TRIM(prlcc) = '') THEN
     wsql = wsql||' null as bdcodcentro, null as bdcodtpcc, tlan.bdcodterceiroc as bdparticipante from vsuc_empresas_tlan tlan ';
  ELSE
     BEGIN
       wsql = wsql||'tlcc.bdcodcentro, tlcc.bdcodtpcc, tlan.bdcodterceirod as bdparticipante from vsuc_empresas_tlan tlan ';
       wsql = wsql||' left outer join vsuc_empresas_tlcc tlcc on (tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave and tlcc.bddebcre = 1 and tlcc.bdcodtpcc in ('||prlcc||')) ';
     END
  --Solicitação.: 5022.
  --wsql = wsql||'     where tlan.bdcodemp in ('||prcodemp||') and bddata between '''||prdata_inicial||''' and '''||prdata_final||''' and bdcredito is not null) tlan ';
-- GILBERTO - 23/04/2013 - 5504 - NÃO CALCULAVA SALDO ANTERIOR DA FILIAL SE A MESMA NÃO TIVER MOVIMENTO NO PERÍODO
--  wsql = wsql||'     where tlan.bdcodemp in ('||prcodemp||') and bddata between '''||substring(prdata_inicial from 1 for 4)||'-01-01'||''' and '''||substring(prdata_final from 1 for 4)||'-12-31'||''' and bdcredito is not null) tlan ';
  --#alt:5837
  --wsql = wsql||'     where tlan.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'     where (tlan.bdcodemp in ('||prcodemp||')) ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'   and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
--  WSQL = WSQL||'     and bddata <= '''||substring(prdata_final from 1 for 4)||'-12-31'||''' and bdcredito is not null';-- gilberto - 26/07/2013 - 6159
  WSQL = WSQL||'     and bddata < '''||prdata_inicial||''' and bdcredito is not null';-- gilberto - 26/07/2013 - 6159
  -- gilberto - 28/05/2013 - incluido para considerar participante no calculo de saldo anterior
  IF ((prpartini IS NOT NULL) AND (prpartini <> 0)) THEN
     wsql = wsql||' and (tlan.bdcodterceiroc >= '||prpartini||')';
  IF ((prpartfin IS NOT NULL) AND (prpartfin <> 0)) THEN
     wsql = wsql||' and (tlan.bdcodterceiroc <= '||prpartfin||')';
  -- __________________________________________________________________________________________
  wsql = wsql||')';--gilberto - 12/08/2013 - #alt:6159
  wsql = wsql||') tlan ';
  wsql = wsql||' inner join planos_tpla tpla on (tpla.bdcodplapadrao = tlan.bdcodplapadrao and tpla.bdcodtpla = tlan.bdconta and tpla.bdtipcta = 1) ';
  wsql = wsql||'where tpla.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''' ';
  EXECUTE STATEMENT wsql;

--  if (prdetalharctaparticipante = 1) then
     BEGIN
       wsql = 'insert into VSUC_EMPRESAS_TRAZAO_SALDO (BDCODEMP,BDCODPLAPADRAO,BDCODTPLA,BDCTALON,BDTIPCTA,BDGRPCTA,BDNOMCTA,BDCODCENTRO,BDCODTPCC,BDPARTICIPANTE,BDSALDO) ';
       wsql = wsql||'select tlan.bdcodemp, tlan.bdcodplapadrao, tlan.bdconta, ';
       wsql = wsql||'tpla.BDCTALON, tpla.BDTIPCTA, tpla.bdgrupocta, tpla.BDNOMCTA, null as bdcodcentro, null as bdcodtpcc, tlan.bdcodter, ';
--       wsql = wsql||'(select bdsaldo_anterior from vsuc_sp_retorna_saldos_cta_part(tlan.bdcodemp, tlan.bdcodplapadrao, '''||prdata_inicial||''', '''||prdata_final||''', tlan.bdconta, '; -- alt:#6647 - gilberto - 12/09/2013
       wsql = wsql||'(select bdsaldo_anterior from vsuc_sp_retorna_saldos_ctaparty(tlan.bdcodemp, tlan.bdcodplapadrao, '''||prdata_inicial||''', '''||prdata_final||''', tlan.bdconta,'||:prindice||', ';
       wsql = wsql||'                                                              0, tlan.bdcodter, '||bdconciliados||','''||:prcodemp||''','||:prcontabilizacao||', 0,'''''', 0, 0, 0, 0, '||:PRREFEMP||')) ';
       wsql = wsql||'from (select distinct bdcodemp, bdcodplapadrao, bdconta, bdcodter ';-- #alt:6430 - gilberto - 20/08/2013
       wsql = wsql||'from (select distinct bdcodemp, bdcodplapadrao, bddebito as bdconta, bdcodterceirod as bdcodter ';
       wsql = wsql||'      from vsuc_empresas_tlan ';
       --#alt:5837
       --wsql = wsql||'      where bdcodemp in ('||prcodemp||') and ';
       wsql = wsql||'      where (bdcodemp in ('||prcodemp||')) and ';
       --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
       IF (prcontabilizacao <> 99) THEN
         wsql = wsql||'   (bdcontabilizacao in (0,'||prcontabilizacao||')) and ';
       wsql = wsql||'      bddata between '''||SUBSTRING(prdata_inicial FROM 1 FOR 4)||'-01-01'||''' and '''||SUBSTRING(prdata_final FROM 1 FOR 4)||'-12-31'||''' and bddebito is not null and bdcodterceirod is not null ';
       wsql = wsql||'      union all ';
       wsql = wsql||'      select distinct bdcodemp, bdcodplapadrao, bdcredito as bdconta, bdcodterceiroc as bdcodter ';
       wsql = wsql||'      from vsuc_empresas_tlan ';
       --#alt:5837
       --wsql = wsql||'      where bdcodemp in ('||prcodemp||') and ';
       wsql = wsql||'      where (bdcodemp in ('||prcodemp||')) and ';
       --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
       IF (prcontabilizacao <> 99) THEN
         wsql = wsql||'    (bdcontabilizacao in (0,'||prcontabilizacao||')) and ';
       wsql = wsql||'      bddata between '''||SUBSTRING(prdata_inicial FROM 1 FOR 4)||'-01-01'||''' and '''||SUBSTRING(prdata_final FROM 1 FOR 4)||'-12-31'||''' and bdcredito is not null and bdcodterceiroc is not null)) tlan ';
       wsql = wsql||'inner join planos_tpla tpla on (tpla.bdcodplapadrao = tlan.bdcodplapadrao and tpla.bdcodtpla = tlan.bdconta and tpla.bdtipcta = 1) ';
       wsql = wsql||'where tpla.bdctalon between '''||prclassificacao_inicial||''' and '''||prclassificacao_final||''' ';
       EXECUTE STATEMENT wsql;
     END

  -- BDCONCILIADOS = 0 TODOS 1 CONCILIADOS 2 NAO CONCILIADOS

  wconta     = 0;
  wsaldo     = 0;
  wordem     = 0;
  bdvlraconciliar = 0;
  bdvlrconciliado = 0;
  wclass_ant = '';

  wsql = '';
  IF (pragrupar <> '') THEN
     wsql = wsql||'select * from (';

  wsql = wsql||'select TRazao.prhistorico, TRazao.prdata, TRazao.prchave, TRazao.prconta, ';
  wsql = wsql||'TRazao.prcontra, TRazao.prcredito, TRazao.prdebito, ';
  wsql = wsql||'TRazao.prconciliado, TRazao.prempresa, ';
  wsql = wsql||'TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta, TRazao.prclass_conta, ';
  wsql = wsql||'TRazao.prclass_contra, TRazao.prnome_conta_contra, TRAZAO.prlote, TRAZAO.prdcto, TRAZAO.prcompl, TRAZAO.prcnpjemp, ';
  wsql = wsql||'TRAZAO.PRGRPCTA, TRAZAO.PRCODHIST, TRAZAO.PRCODTPHI, TRAZAO.PRCODPLAPADRAO , ';
  wsql = wsql||'(substring((CAST(TRazao.prdata AS VARCHAR(10))) from 6 for 2) || ''/'' || substring((CAST(TRazao.prdata AS VARCHAR(10))) from 1 for 4)) as "BDREF", ';
  wsql = wsql||'TRAZAO.prparticipanteconta, tRAZAO.prcodterceiroconta, tRAZAO.prcodterceirocontra, trazao.PRCODEMPFILIAL, trazao.prcodmatriz, trazao.PRCHAVEONLINE ';

  wsql = wsql||'from vsuc_sp_retorna_razao_contas('''||TRIM(prcodemp)||''','''||TRIM(prclassificacao_inicial)||''','''||TRIM(prclassificacao_final)||''','''||prdata_inicial||''','''||prdata_final||''',''';
--  wsql = wsql||                                   trim(prlcc)||''','||trim(prordempresa)||','||prrefemp||','||prdetalharctacliente||','||prdetalharctafornecedor||','||PRCONCATENACODCLIFOR||',null,null) TRazao ';
  wsql = wsql||                                   TRIM(prlcc)||''',';
  wsql = wsql||TRIM(prordempresa)||',';
  wsql = wsql||prrefemp||',';
  wsql = wsql||prdetalharctaparticipante||',';
  wsql = wsql||PRCONCATENACODPARTICIPANTE||',';
  IF (prpartini IS NOT NULL) THEN
     wsql = wsql||prpartini||',';
  ELSE
     wsql = wsql||'null,';
  IF (prpartfin IS NOT NULL) THEN
     wsql = wsql||prpartfin||',';
  ELSE
     wsql = wsql||'null,';
  wsql = wsql||prcontabilizacao||','||prmatrizfilialconsolidado||','||prdetalharfilial||') TRazao ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' where (Upper(TRazao.prconciliado) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' where ((Upper(TRazao.prconciliado) = '||'''FALSE'''||') or (TRazao.prconciliado is null))';

  -- agrupa lançamentos ________________________________________________________
  IF (pragrupar <> '') THEN
     BEGIN
       IF (bdconciliados IN (1,2)) THEN
          wsql = wsql||' and trazao.PRTIPOLAN not in ('||pragrupar||') ';
       ELSE
          wsql = wsql||' where trazao.PRTIPOLAN not in ('||pragrupar||') ';

       wsql = wsql||'union all ';
       wsql = wsql||'select null as prhistorico, TRazao.prdata, min(TRazao.prchave), TRazao.prconta, ';
       wsql = wsql||'TRazao.prcontra, sum(TRazao.prcredito), sum(TRazao.prdebito), ';
       wsql = wsql||'null as prconciliado, TRazao.prempresa, ';
       wsql = wsql||'TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta, TRazao.prclass_conta, ';
       wsql = wsql||'TRazao.prclass_contra, TRazao.prnome_conta_contra, null as prlote, null as prdcto, null as prcompl, TRAZAO.prcnpjemp, ';
       wsql = wsql||'TRAZAO.PRGRPCTA, TRAZAO.PRCODHIST, TRAZAO.PRCODTPHI, TRAZAO.PRCODPLAPADRAO , ';
       wsql = wsql||'(substring((CAST(TRazao.prdata AS VARCHAR(10))) from 6 for 2) || ''/'' || substring((CAST(TRazao.prdata AS VARCHAR(10))) from 1 for 4)) as "BDREF", ';
       wsql = wsql||'null as prparticipanteconta, null as prcodterceiroconta, null as prcodterceirocontra, trazao.PRCODEMPFILIAL, trazao.prcodmatriz, trazao.PRCHAVEONLINE ';
     
       wsql = wsql||'from vsuc_sp_retorna_razao_contas('''||TRIM(prcodemp)||''','''||TRIM(prclassificacao_inicial)||''','''||TRIM(prclassificacao_final)||''','''||prdata_inicial||''','''||prdata_final||''',''';
       wsql = wsql||                                   TRIM(prlcc)||''',';
       wsql = wsql||TRIM(prordempresa)||',';
       wsql = wsql||prrefemp||',';
       wsql = wsql||prdetalharctaparticipante||',';
       wsql = wsql||PRCONCATENACODPARTICIPANTE||',';
       IF (prpartini IS NOT NULL) THEN
          wsql = wsql||prpartini||',';
       ELSE
          wsql = wsql||'null,';
       IF (prpartfin IS NOT NULL) THEN
          wsql = wsql||prpartfin||',';
       ELSE
          wsql = wsql||'null,';
       wsql = wsql||prcontabilizacao||','||prmatrizfilialconsolidado||','||prdetalharfilial||') TRazao ';
     
       IF (bdconciliados = 1) THEN
          wsql = wsql|| ' where (Upper(TRazao.prconciliado) = '||'''TRUE'''||')';
       ELSE
       IF (bdconciliados = 2) THEN
          wsql = wsql|| ' where ((Upper(TRazao.prconciliado) = '||'''FALSE'''||') or (TRazao.prconciliado is null))';
       IF (bdconciliados IN (1,2)) THEN
          wsql = wsql||' and trazao.PRTIPOLAN in ('||pragrupar||') ';
       ELSE
          wsql = wsql||' where trazao.PRTIPOLAN in ('||pragrupar||') ';

       wsql = wsql||'group by TRazao.prdata, trazao.PRCHAVEONLINE, TRazao.prconta, ';
       wsql = wsql||'TRazao.prcontra, ';
       wsql = wsql||'TRazao.prempresa, ';
       wsql = wsql||'TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta, TRazao.prclass_conta, ';
       wsql = wsql||'TRazao.prclass_contra, TRazao.prnome_conta_contra, TRAZAO.prcnpjemp, ';
       wsql = wsql||'TRAZAO.PRGRPCTA, TRAZAO.PRCODHIST, TRAZAO.PRCODTPHI, TRAZAO.PRCODPLAPADRAO, ';
       wsql = wsql||'trazao.PRCODEMPFILIAL, trazao.prcodmatriz) TRAZAO ';
     END

  IF (prordempresa = 1) THEN
     BEGIN
       IF (prdetalharctaparticipante = 0) THEN
--          wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prconta, TRazao.prdata, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
          wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prclass_conta, TRazao.prdata, TRazao.prchave';
       ELSE
          wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.PRCODTERCEIROCONTA, TRazao.prdata, TRazao.prchave';
     END
  ELSE
  IF (prordempresa = 2) THEN
     BEGIN
       IF (prdetalharctaparticipante = 0) THEN
          wsql = wsql||'order by TRazao.prnome_conta, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prchave';
       ELSE
          wsql = wsql||'order by TRazao.PRCODTERCEIROCONTA, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prchave';
     END
  ELSE
  IF (prordempresa = 3) THEN
     BEGIN
       IF (prdetalharctaparticipante = 0) THEN
--          wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prdata, TRazao.prconta, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
          wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prdata, TRazao.prclass_conta, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
       ELSE
          wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prdata, TRazao.PRCODTERCEIROCONTA, TRazao.prchave';
     END
  ELSE
     BEGIN
       IF (prdetalharctaparticipante = 0) THEN
--          wsql = wsql||'order by TRazao.prconta, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
          wsql = wsql||'order by TRazao.prclass_conta, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
       ELSE
          wsql = wsql||'order by TRazao.PRCODTERCEIROCONTA, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prchave';
     END
/*
  for select TRazao.prhistorico, TRazao.prdata, TRazao.prchave, TRazao.prconta,
             TRazao.prcontra, TRazao.prentrada, TRazao.prsaida, TRazao.prconciliado, TRazao.prempresa,
             TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta, TRazao.prclass_conta,
             TRazao.prclass_contra, TRAZAO.prlote, TRAZAO.prdcto, TRAZAO.prcompl, TRAZAO.prcnpjemp
      from vsuc_sp_retorna_razao_contas(:prcodigo_empresa, :wclassini, :wclassfin,
                                        :prdata_inicial, :prdata_final, :prfiliais, :prlcc) TRazao
      order by TRazao.prconta, TRazao.prdata
*/
  FOR EXECUTE STATEMENT wsql
      INTO :bdhistorico, :bddata, :bdchave, :bdconta, :bdcontra, :bdcredito, :bddebito, /*:prcomplemento,*/
           /*:prcontra_longa, */:bdconciliado, :bdempresa, :bdnomeempresa, :bdcc, :bdnome_conta,
           :bdclass_conta, :bdclass_contra, :bdnome_conta_contra, :bdlote, :bddcto, :bdcompl, :bdcnpjemp, :bdgrupoconta, :bdcodhist,
           :bdcodtphi, :bdcodplapadrao, :bdref, :wparticipante, :bdcod_terceiro_conta, :bdcod_terceiro_contra, :BDEMPRESAFILIAL, :wcodmatriz, :bdchaveonline DO
      BEGIN
        bdsaldoanterior = 0;

        SELECT tpla.bdctalon, tpla.bdgrupocta FROM planos_tpla TPla
        WHERE tpla.bdcodplapadrao = :bdcodplapadrao
        AND tpla.bdcodtpla = :bdconta
        INTO :wclass, :wgrupocta;

        --Incluido a verificação (wconta <> bdcontra), sem isso entrava nesta rotina sempre. Bruno Borges
/* gilberto - 22/05/2013 - 5772
        if (((wconta <> bdconta) and ((wconta <> bdcontra) or (bdcontra is null and wconta is not null))) or
            (((prdetalharctaparticipante = 1) and (wparticipante = 1)) and
             (bdclass_conta <> wclass_ant)))then*/
        IF ((((wconta <> bdconta) AND ((wconta <> bdcontra) OR (bdcontra IS NULL AND wconta IS NOT NULL))) OR (bdclass_conta <> wclass_ant)) OR
            ((bdclass_conta <> wclass_ant) AND ((prdetalharctaparticipante = 1) AND (wparticipante = 1)))) THEN
           BEGIN
             bdvlraconciliar = 0;
             bdvlrconciliado = 0;

             /* INICIO Giovanni, precisa fazer um laco das empresas para trazer o saldo anterior correto */

             -- retorna as empresas selecionadas
             wsqlemp = 'select temp.bdcodemp bdempresasefilial ';
             wsqlemp = wsqlemp||'from tempresas temp ';
             wsqlemp = wsqlemp||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
             wsqlemp = wsqlemp||'where temp.bdcodemp in ('||prcodemp||') ';
             wsqlemp = wsqlemp||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';
             -- executa o sql das empresas

             FOR EXECUTE STATEMENT wsqlemp
                 INTO :wcodempefilial DO
             BEGIN
               wsaldo = 0;
/*               -- Detalhado por participante
               if ((prdetalharctaparticipante = 1) and (wparticipante = 1)) then
                 select bdsaldo_anterior from vsuc_sp_retorna_saldos_cta_part(:wcodempefilial,:bdcodplapadrao,:prdata_inicial,:prdata_final,:bdconta,
                                                                              0,:bdcod_terceiro_conta,0,:bdconciliados)
                 into :wsaldo;
               else
                 select SALDO_ANTERIOR from sp_retorna_saldo_emp(:wcodempefilial, :bdconta,
                 :prdata_inicial, :prdata_final, 0, :bdcc, null, :prrefemp,:bdconciliados)
                 into :wsaldo;
*/
               wsqlsaldo = 'select sum(coalesce(bdsaldo,0)) from vsuc_empresas_trazao_saldo ';
               wsqlsaldo = wsqlsaldo||'where bdcodemp = '||wcodempefilial;
               wsqlsaldo = wsqlsaldo||' and bdcodtpla = '||bdconta;
               IF (((prdetalharctaparticipante IS NULL) OR (prdetalharctaparticipante = 0)) OR ((bdcod_terceiro_conta IS NULL) OR (bdcod_terceiro_conta = 0))) THEN
                  BEGIN
                    wsqlsaldo = wsqlsaldo||' and bdparticipante is null ';
                    IF ((bdcc IS NOT NULL) AND (bdcc <> 0)) THEN
                       BEGIN
                         wsqlsaldo = wsqlsaldo||' and bdcodtpcc = '||bdcc;
                       END
                  END
               ELSE
                  BEGIN
                    wsqlsaldo = wsqlsaldo||' and bdparticipante = '||bdcod_terceiro_conta;
                    IF ((bdcc IS NOT NULL) AND (bdcc <> 0)) THEN
                       BEGIN
                         wsqlsaldo = wsqlsaldo||' and bdcodtpcc = '||bdcc;
                       END
                  END
               EXECUTE STATEMENT wsqlsaldo INTO :wsaldo;

               bdsaldoanterior = bdsaldoanterior + COALESCE(wsaldo,0);
               wsaldo = bdsaldoanterior;
             END


             SELECT FIRST 1 bdcodcentro FROM vsuc_empresas_trazao_saldo WHERE bdcodcentro > 0 INTO :bdcodcentro;


             /* FIM Giovanni, precisa fazer um laco das empresas para trazer o saldo anterior correto */

             SELECT tpla.bdctalon, tpla.bdgrupocta FROM planos_tpla TPla
             WHERE tpla.bdcodplapadrao = :bdcodplapadrao
             AND tpla.bdcodtpla = :bdconta
             INTO :wclass, :wgrupocta;

             wordem = 0;

             IF (wgrupocta IN (1,2,3)) THEN
                BEGIN
                  wsaldo = (wsaldo + COALESCE(bdcredito, 0) - COALESCE(bddebito, 0));
                  wvalor = COALESCE(bdcredito, 0) - COALESCE(bddebito, 0);
                END
             ELSE
                BEGIN
                  wsaldo = (wsaldo + COALESCE(bddebito, 0) - COALESCE(bdcredito, 0));
                  wvalor = COALESCE(bddebito, 0) - COALESCE(bdcredito, 0);
                END
           END
        ELSE
           BEGIN
             bdsaldoanterior = wsaldo;

             IF (wgrupocta IN (1,2,3)) THEN
                BEGIN
                  wsaldo = (wsaldo + COALESCE(bdcredito, 0) - COALESCE(bddebito, 0));
                  wvalor = COALESCE(bdcredito, 0) - COALESCE(bddebito, 0);
                END
             ELSE
                BEGIN
                  wsaldo = (wsaldo + COALESCE(bddebito, 0) - COALESCE(bdcredito, 0));
                  wvalor = COALESCE(bddebito, 0) - COALESCE(bdcredito, 0);
                END
           END
        wordem = wordem + 1;
        bdordsaldo = wordem;
        bdsaldo = wsaldo;
        IF (wvalor < 0) THEN
           bdvalorsemsinal = wvalor * -1;
        ELSE
           bdvalorsemsinal = wvalor;
        bdvalor     = wvalor;
        wconta      = bdconta;

        -- giovanni comentei a linha abaixo, se precisar me chamar para discutir...
        -- ja que o bdcompl ja tem o completo do historico completo, pra que dois campos iguais ????
        -- bdhistorico = bdcompl;

       IF (bdhistorico IS NOT NULL) THEN
         BEGIN
           SELECT pos FROM pos('*', :bdhistorico) INTO :wpos;
             IF (wpos > 0) THEN
                bdhistorico = bdcompl;
             ELSE
               bdhistorico = bdhistorico || ' ' || bdcompl;
         END
       ELSE
         bdhistorico = bdcompl;

       IF ((UPPER(bdconciliado) <> 'TRUE') OR (bdconciliado IS NULL)) THEN
          bdvlraconciliar = bdvlraconciliar + wvalor;
       ELSE
          bdvlrconciliado = bdvlrconciliado + wvalor;

        wclass_ant  = bdclass_conta;

        SUSPEND;
      END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_SALDO_CREDOR */
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CREDOR (
PRCODEMP         VARCHAR(1024),
PRDATINI         DATE,
PRDATFIN         DATE,
PRINDICE         INTEGER,
PRCONTABILIZACAO INTEGER,
PRCODPLAPADRAO   INTEGER,
PRCONTA          INTEGER,
PRREFEMP         INTEGER)
RETURNS (
BDCODEMP         INTEGER,
BDNOMEMP         DM_BDNOMEMP,
BDCONTA          INTEGER,
BDDATA           DATE,
BDCTALON         DM_CLASSCONTAS,
BDNOMCTA         VARCHAR(100),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDSALDO_DEB      NUMERIC(15,2),
BDSALDO_CRE      NUMERIC(15,2),
BDMOVIMENTO      NUMERIC(15,2),
BDSALDO_ATUAL    NUMERIC(15,2),
BDGRUPOCTA       INTEGER)
AS
DECLARE VARIABLE WSQL        VARCHAR(2048);
DECLARE VARIABLE WEMPRESAANT INTEGER;
BEGIN
  BDCONTA = PRCONTA;
  WEMPRESAANT = -1;

  SELECT COALESCE(TPLA.BDGRUPOCTA, 0), TPLA.BDNOMCTA, TPLA.BDCTALON FROM PLANOS_TPLA TPLA
  WHERE TPLA.BDCODPLAPADRAO = :PRCODPLAPADRAO AND
        TPLA.BDCODTPLA = :PRCONTA INTO :BDGRUPOCTA, :BDNOMCTA, :BDCTALON;

  WSQL = 'SELECT BDCODEMP, BDDATA,';

  WSQL = WSQL || ' sum(case when bddebito = ' || :PRCONTA || ' then bdvalor else 0 end) ';
  IF (PRINDICE > 0) THEN
  BEGIN
    WSQL = WSQL || '      / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
    WSQL = WSQL || '                 (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) ';
  END

  WSQL = WSQL || ' as BDVALORDEBITO,';

  WSQL = WSQL || ' sum(case when bdCREDITO = ' || :PRCONTA || ' then bdvalor else 0 end) ';
  IF (PRINDICE > 0) THEN
  BEGIN
    WSQL = WSQL || '      / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
    WSQL = WSQL || '                 (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) ';
  END

  WSQL = WSQL || ' as BDVALORCREDITO';

  WSQL = WSQL || ' FROM VSUC_EMPRESAS_TLAN TLAN';
  WSQL = WSQL || ' WHERE (BDCODEMP IN (' || :PRCODEMP || ')) AND';
  WSQL = WSQL || '       (BDCONTABILIZACAO IN (0, ' || :PRCONTABILIZACAO || ')) AND';
  WSQL = WSQL || '       (' || :PRCONTA || ' IN (BDCREDITO, BDDEBITO)) AND';
  WSQL = WSQL || '       (BDDATA BETWEEN ''' || PRDATINI || ''' AND ''' || :PRDATFIN || ''')';
  WSQL = WSQL || '  GROUP BY BDCODEMP, BDDATA ORDER BY BDCODEMP, BDDATA';

  FOR EXECUTE STATEMENT WSQL
          INTO :BDCODEMP, :BDDATA, :BDSALDO_DEB, :BDSALDO_CRE
  DO
  BEGIN
    IF (WEMPRESAANT <> BDCODEMP) THEN
    BEGIN
      SELECT TSALDO.SALDO_ANTERIOR FROM SP_RETORNA_SALDO_EMP_X(:BDCODEMP, :BDCONTA, :BDDATA, :BDDATA, :PRINDICE, 0, NULL, NULL, :PRREFEMP, 0, :PRCONTABILIZACAO, 0) TSALDO INTO :BDSALDO_ATUAL;

      BDNOMEMP = NULL;
      SELECT TEM.BDNOMEMP FROM TEMPRESAS_REF TEM
      WHERE (TEM.BDCODEMP = :BDCODEMP AND
            TEM.BDREFEMP = (SELECT FIRST 1 TREF.BDREFEMP FROM TEMPRESAS_REF TREF
                            WHERE TREF.BDCODEMP = :BDCODEMP AND
                                  TREF.BDREFEMP <= :PRREFEMP
                            ORDER BY TREF.BDREFEMP DESC)) INTO :BDNOMEMP;

      WEMPRESAANT = BDCODEMP;
    END

    BDSALDO_DEB = COALESCE(BDSALDO_DEB, 0);
    BDSALDO_CRE = COALESCE(BDSALDO_CRE, 0);
    BDSALDO_ATUAL = COALESCE(BDSALDO_ATUAL, 0);

    IF (BDGRUPOCTA IN (1, 2, 3)) THEN
      BDMOVIMENTO = BDSALDO_CRE - BDSALDO_DEB;
    ELSE
      BDMOVIMENTO = BDSALDO_DEB - BDSALDO_CRE;

    BDSALDO_ANTERIOR = BDSALDO_ATUAL;
    BDSALDO_ATUAL = BDSALDO_ANTERIOR + BDMOVIMENTO;

    IF (BDSALDO_ATUAL < 0) THEN
    BEGIN
      SUSPEND;
    END
  END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_RAZAO_SALDO_X */
create or alter procedure VSUC_SP_RETORNA_RAZAO_SALDO_X (
    PRCODEMP varchar(1024),
    PRCLASSIFICACAO_INICIAL varchar(40),
    PRCLASSIFICACAO_FINAL varchar(40),
    PRDATA_INICIAL date,
    PRDATA_FINAL date,
    PRINDICE integer,
    PRDETALHARCC integer,
    PRLCC DM_MAXVARCHAR,
    PRLANCAMENTOSEMCC integer,
    PRORDEMPRESA integer,
    PRREFEMP integer,
    PRDETALHARCTAPARTICIPANTE integer,
    PRAGRUPARPARTICIPANTEPORCNPJ integer,
    PRCONCATENACODPARTICIPANTE integer,
    BDCONCILIADOS varchar(20),
    PRPARTINI integer,
    PRPARTFIN integer,
    PRAGRUPAR varchar(1024),
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRDCDOISLANCAMENTOS integer,
    PRCONTASSEMMOVIMENTO integer,
    PRIGNORAZERAMENTO integer = 0,
    PRIGNORASALDOANTERIOR integer = 0,
    PRDETALHARFILIAL integer = 0,
    PRORDENACAO integer = 0,
    PRDETALHAREMPREENDIMENTO integer = 0,
    PRDETALHARUNIDIMOB integer = 0,
    PRMOSTRARPROPUNIDADE integer = 0,
    PRSOLANSEMEMPREE integer = 0,
    PRORDENANATUREZA integer = 0,
    PRPRODRURAL DM_BOOLEAN = 'FALSE' /* COLLATE WIN1252 - default */ ,
    PRIMOVEIS varchar(1024) = '' /* COLLATE WIN1252 - default */ ,
    PRLISTAPART varchar(10000) = '' /* COLLATE WIN1252 - default */ ,
    PRAGRUPARPARTICIPANTEPORCPF integer = 0,
    PRMOSTRARCC integer = 0,
    PRPLANO_SECUNDARIO integer = 0,
    PREMPREENDIMENTO varchar(1024) = '' /* COLLATE WIN1252 - default */ ,
    PRUNIDIMOBILIARIA varchar(1024) = '' /* COLLATE WIN1252 - default */ ,
    PRNAOMOSTRARLANCSEMDADOSRU DM_BOOLEAN = 'FALSE' /* COLLATE WIN1252 - default */ ,
    PRFILTIPOLAN varchar(3200) = '' /* COLLATE WIN1252 - default */ )
returns (
    BDHISTORICO varchar(100),
    BDDATA date,
    BDCHAVE integer,
    BDCONTA integer,
    BDCONTRA integer,
    BDCREDITO numeric(15,2),
    BDDEBITO numeric(15,2),
    BDSALDO numeric(15,2),
    BDCONCILIADO varchar(5),
    BDEMPRESA integer,
    BDNOMEEMPRESA varchar(100),
    BDCODCENTRO integer,
    BDCC integer,
    BDNOME_CONTA varchar(300),
    BDNOME_CONTA_ORIGINAL varchar(300),
    BDCLASS_CONTA varchar(40),
    BDCOD_TERCEIRO_CONTA integer,
    BDCGC_CONTA varchar(18),
    BDCLASS_CONTRA varchar(40),
    BDNOME_CONTA_CONTRA varchar(300),
    BDCOD_TERCEIRO_CONTRA integer,
    BDVALOR numeric(15,2),
    BDORDSALDO integer,
    BDLOTE varchar(10),
    BDDCTO varchar(15),
    BDCOMPL varchar(200),
    BDCNPJEMP varchar(18),
    BDSALDOANTERIOR numeric(15,2),
    BDVALORSEMSINAL numeric(15,2),
    BDGRUPOCONTA integer,
    BDCODHIST integer,
    BDCODPLAPADRAO integer,
    BDREF varchar(8),
    BDCODTPHI integer,
    BDEMPRESAFILIAL integer,
    BDTIPOLANCFILIAL integer,
    BDVLRCONCILIADO numeric(15,2),
    BDVLRACONCILIAR numeric(15,2),
    BDCHAVEONLINE varchar(120),
    BDTRANSACAO integer,
    BDTRANFECHADA DM_BOOLEAN,
    BDTIPOLAN integer,
    BDSEQCTA varchar(7),
    BDCLANOM varchar(355),
    BDCONCILIACAOPENDENTE integer,
    BDCC_CONTRA integer,
    BDEMPREENDIMENTO integer,
    BDUNIDIMOB integer,
    BDNATUREZALAN integer,
    BDCTALCDPR varchar(6),
    BDPART_PR varchar(18),
    BDCODPART_PR integer,
    BDTIPLANPR varchar(6),
    BDCODIMOVRUR integer,
    BDTIPDOCPR integer,
    BDSALRELCONCILIACOES DM_BOOLEAN)
as
declare variable WCONTA integer;
declare variable WSALDO numeric(15,2);
declare variable WVALOR numeric(15,2);
declare variable WORDEM integer;
declare variable WTAM integer;
declare variable WSQL varchar(10240);
declare variable WPARTICIPANTE integer;
declare variable WPOS integer;
declare variable WSQLEMP varchar(10240);
declare variable WCODEMPEFILIAL integer;
declare variable WCODMATRIZ integer;
declare variable WCODTER integer;
declare variable WCC_ATU integer;
declare variable WSALDOAUX numeric(15,2);
declare variable WAGRUPAPART integer;
declare variable WFILIAL integer;
declare variable WCLASSIFICACAO varchar(100);
declare variable WCGCTERANT varchar(20);
declare variable WEMPREENDIMENTO integer;
declare variable WUNIDADEIMOB integer;
declare variable WSQLCONCILIADO varchar(1000);
declare variable WCODEMPDC integer;
declare variable WCHAVEDC integer;
declare variable WSQLCONTAS varchar(1000);
declare variable WCONTA_SALDO integer;
declare variable WSALRELCONTABILIZACAO boolean;
declare variable WREGRACC integer;
declare variable WREGRALANCAMENTOSEMCC integer;
BEGIN
  /* BDCONCILIADOS:
      0: Conciliados
      1: Não conciliados
      2: Pendentes
      3: Todos
  */

  wconta     = 0;
  wsaldo     = 0;
  wordem     = 0;
  bdvlraconciliar = 0;
  bdvlrconciliado = 0;
  wAgrupaPart = 1;
  WEMPREENDIMENTO = 0;
  WUNIDADEIMOB    = 0;
  wRegraCC = 0;
  wRegraLancamentoSemCC = 0;
  wsql = '';

  IF (pragrupar <> '') THEN
     wsql = wsql||'select * from (';

  wsql = wsql||'select TRazao.prhistorico, TRazao.prdata, TRazao.prchave, TRazao.prconta, ';
  wsql = wsql||'TRazao.prcontra, TRazao.prcredito, TRazao.prdebito, ';
  wsql = wsql||'TRazao.prconciliado, TRazao.prconciliacaopendente, TRazao.prempresa, ';
  wsql = wsql||'TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta, TRazao.prnome_conta_original, TRazao.prclass_conta, TRazao.prcgc_conta, ';
  wsql = wsql||'TRazao.prclass_contra, TRazao.prnome_conta_contra, TRazao.prlote, TRazao.prdcto, TRazao.prcompl, TRazao.prcnpjemp, ';
  wsql = wsql||'TRazao.PRGRPCTA, TRazao.PRCODHIST, TRazao.PRCODTPHI, TRazao.PRCODPLAPADRAO , ';
  wsql = wsql||'extract(month from TRazao.prdata)||''/''||extract(year from TRazao.prdata) as BDREF, '; --alt:14942 - 26/01/2017 - Simplificada a extração da data para facilitar a compreensão. Pedro
  wsql = wsql||'TRazao.prparticipanteconta, TRazao.prcodterceiroconta, TRazao.prcodterceirocontra, TRazao.PRCODEMPFILIAL, TRazao.PRCHAVEONLINE, TRazao.PRCODCENTRO, ';
  --#alt:85616 - Carlos Machado - Adicionada opção de ordenação alfabetica. 18/07/2018
  wsql = wsql||'TRazao.prtransacao, TRazao.prtranfechada, TRazao.prtipolan, TRazao.prcodmatriz, TRazao.prclanom as BDCLANOM, ';
  --#alt:93770. Implementado detalhar por empreendimento e unidade imobiliária. Ana - 15/01/2019
  wsql = wsql||'TRazao.PREMPREENDIMENTO, TRazao.PRUNIDIMOB, ';
  --#ALT:59041. Ana - 22/11/2019
  wsql = wsql||'TRAZAO.PRNATUREZALAN, TRazao.PRCTALCDPR, TRazao.PRPART_PR, TRazao.PRCODPART_PR , TRazao.PRTIPLANPR, TRazao.PRCODIMOVRUR, TRazao.PRTIPDOCPR, ';
  wsql = wsql||'TRAZAO.PRSALRELCONCILIACOES ';

  wsql = wsql||'from vsuc_sp_retorna_razao_contas_x('''||TRIM(prcodemp)||''','||:prRefEmp||','''||TRIM(prclassificacao_inicial)||''','''||TRIM(prclassificacao_final)||''','''||prdata_inicial||''','''||prdata_final||''',';
  wsql = wsql||prIndice||', '||(PRDETALHARCC+PRMOSTRARCC)||','''||TRIM(prlcc)||''','||prlancamentosemcc||',';
  wsql = wsql||prdetalharctaparticipante||',';
  wsql = wsql||PRAGRUPARPARTICIPANTEPORCNPJ||',';
  wsql = wsql||PRCONCATENACODPARTICIPANTE||',';
  IF (coalesce(prlistapart,'') <> '') then
     wsql = wsql||'null,null,';
  else
    begin
  IF (prpartini IS NOT NULL) THEN
     wsql = wsql||prpartini||',';
  ELSE
     wsql = wsql||'null,';
  IF (prpartfin IS NOT NULL) THEN
     wsql = wsql||prpartfin||',';
  ELSE
     wsql = wsql||'null,';
    end
  wsql = wsql||prcontabilizacao||','||prmatrizfilialconsolidado||','||prContasSemMovimento||','||prignorazeramento||',';
  --#alt:93770. Implementado detalhar por empreendimento e unidade imobiliária. Ana - 15/01/2019
  wsql = wsql||PRDETALHAREMPREENDIMENTO||','||PRDETALHARUNIDIMOB||', '||prmostrarpropunidade;
  wsql = wsql||','''||PRPRODRURAL||''','''||PRIMOVEIS||''','''||prlistapart||''','||pragruparparticipanteporcpf;
  wsql = wsql||','||PRPLANO_SECUNDARIO;
  --#alt:93770. fim

  --#164065 - Razão e livro caixa - Implementado filtro de empreendimento e unidade imobiliária. Marcela - 22/08/2022
  wsql = wsql||','''||prempreendimento||''', '''||prunidimobiliaria;
  --#164065. fim
  --#193364 - Razão produtor rural - opção de não mostrar lançamentos sem dados de produtor rural. Marcela - 16/01/2024
  wsql = wsql||''','''||PRNAOMOSTRARLANCSEMDADOSRU||''' ';
  --#212425
  wsql = wsql||','''||PRFILTIPOLAN||''') TRazao ';
  SELECT BDSQLCONCILIADO FROM VSUC_SP_MONTA_CONCILIACAO(:bdconciliados, 'TRazao.prconciliado', 'TRazao.prconciliacaopendente', 'TRazao.prdebcre')  INTO :wsqlconciliado;
  if (wsqlconciliado <> '') then
  wsql = wsql||' where '||wsqlconciliado;
  -- agrupa lançamentos ________________________________________________________
  IF (pragrupar <> '') THEN
     BEGIN
       IF (WSQLCONCILIADO <> '') THEN
          wsql = wsql||' and TRazao.PRTIPOLAN not in ('||pragrupar||') ';
       ELSE
          wsql = wsql||' where TRazao.PRTIPOLAN not in ('||pragrupar||') ';
       wsql = wsql||' or TRAZAO.PRTIPOLAN is null ';

  if (prempreendimento <> '' and prempreendimento is not null) then
    BEGIN
      if (pragrupar <> '' AND wsqlconciliado <> '') then
        wsql = wsql||' where TRazao.PREMPREENDIMENTO in ('||prempreendimento||') ';
      else
        wsql = wsql||' and TRazao.PREMPREENDIMENTO in ('||prempreendimento||') ';
      if (prunidimobiliaria <> '' and prunidimobiliaria is not null) then
        wsql = wsql||' and TRazao.prunidimob in ('||prunidimobiliaria||') ';
    end
       --#alt:149942 - Machado - 07/05/2021 - Alterado visualização de razão com lançamentos agrupados MAX(prhistorico)
       wsql = wsql||'union all ';
       wsql = wsql||'select MAX(prhistorico) as prhistorico, TRazao.prdata, min(TRazao.prchave), TRazao.prconta, ';
       wsql = wsql||'TRazao.prcontra, sum(TRazao.prcredito), sum(TRazao.prdebito), ';
       wsql = wsql||'null as prconciliado, null as prconciliacaopendente, TRazao.prempresa, ';
       wsql = wsql||'TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta,TRazao.prnome_conta_original, TRazao.prclass_conta, TRazao.prcgc_conta, ';
       wsql = wsql||'TRazao.prclass_contra, TRazao.prnome_conta_contra, null as prlote, null as prdcto, MAX(prcompl) as prcompl, TRazao.prcnpjemp, ';
       wsql = wsql||'TRazao.PRGRPCTA, TRazao.PRCODHIST, TRazao.PRCODTPHI, TRazao.PRCODPLAPADRAO , ';
       wsql = wsql||'extract(month from TRazao.prdata)||''/''||extract(year from TRazao.prdata) as BDREF, '; --alt:14942 - 26/01/2017 - Simplificada a extração da data para facilitar a compreensão. Pedro
       wsql = wsql||'null as prparticipanteconta, null as prcodterceiroconta, null as prcodterceirocontra, TRazao.PRCODEMPFILIAL, TRazao.PRCHAVEONLINE, TRazao.PRCODCENTRO, ';
       wsql = wsql||'null as prtransacao, null as prtranfechada, TRazao.prtipolan, TRazao.prcodmatriz, TRazao.prclanom as BDCLANOM, ';
       --#alt:93770. Implementado detalhar por empreendimento e unidade imobiliária. Ana - 15/01/2019
       wsql = wsql||'NULL AS PREMPREENDIMENTO, NULL AS PRUNIDIMOB, ';
       --#ALT:59041. Ana - 22/11/2019
       wsql = wsql||'NULL AS PRNATUREZALAN, TRazao.PRCTALCDPR, TRazao.PRPART_PR, TRazao.PRCODPART_PR, TRazao.PRTIPLANPR, TRazao.PRCODIMOVRUR, TRazao.PRTIPDOCPR, ';
       wsql = wsql||'TRazao.PRSALRELCONCILIACOES ';

       wsql = wsql||'from vsuc_sp_retorna_razao_contas_x('''||TRIM(prcodemp)||''','||:prRefEmp||','''||TRIM(prclassificacao_inicial)||''','''||TRIM(prclassificacao_final)||''','''||prdata_inicial||''','''||prdata_final||''',';

       wsql = wsql||prIndice||', '||(PRDETALHARCC+prmostrarcc)||','''||TRIM(prlcc)||''','||prlancamentosemcc||',';
       wsql = wsql||prdetalharctaparticipante||',';
       wsql = wsql||PRAGRUPARPARTICIPANTEPORCNPJ||',';
       wsql = wsql||PRCONCATENACODPARTICIPANTE||',';
       IF (coalesce(prlistapart,'') <> '') then
          wsql = wsql||'null,null,';
       ELSE
          begin
       IF (prpartini IS NOT NULL) THEN
          wsql = wsql||prpartini||',';
       ELSE
          wsql = wsql||'null,';
       IF (prpartfin IS NOT NULL) THEN
          wsql = wsql||prpartfin||',';
       ELSE
          wsql = wsql||'null,';
          end
       wsql = wsql||prcontabilizacao||','||prmatrizfilialconsolidado||','||prContasSemMovimento||','||prignorazeramento||',';

       --#alt:93770. Implementado detalhar por empreendimento e unidade imobiliária. Ana - 15/01/2019
       wsql = wsql||PRDETALHAREMPREENDIMENTO||','||PRDETALHARUNIDIMOB||', '||prmostrarpropunidade;

       wsql = wsql||','''||PRPRODRURAL||''','''||PRIMOVEIS||''','''||prlistapart||''','||PRAGRUPARPARTICIPANTEPORCPF;
       wsql = wsql||','||PRPLANO_SECUNDARIO;
       --#alt:93770. fim

       --#164065 - Razão e livro caixa - Implementado filtro de empreendimento e unidade imobiliária. Marcela - 22/08/2022
       wsql = wsql||','''||prempreendimento||''', '''||prunidimobiliaria;
        --#164065. fim
    --#193364 - Razão produtor rural - opção de não mostrar lançamentos sem dados de produtor rural. Marcela - 16/01/2024
       wsql = wsql||''','''||PRNAOMOSTRARLANCSEMDADOSRU||''' ';
       --#212425
       wsql = wsql||','''||PRFILTIPOLAN||''') TRazao ';
       ----wsql = wsql||WSQLCONCILIADO;
       ----Leonardo Pereira - 19/11/2020 - Erro no relatório de conciliação #144698
       IF (WSQLCONCILIADO <> '') THEN
          begin
            wsql = wsql||' where '||WSQLCONCILIADO;
          wsql = wsql||' and TRazao.PRTIPOLAN in ('||pragrupar||') ';
          end
       ELSE
          wsql = wsql||' where TRazao.PRTIPOLAN in ('||pragrupar||') ';

       if (prempreendimento <> '' and prempreendimento is not null) then
         BEGIN
           wsql = wsql||' and TRazao.PREMPREENDIMENTO in ('||prempreendimento||') ';
           if (prunidimobiliaria <> '' and prunidimobiliaria is not null) then
             wsql = wsql||' and TRazao.prunidimob in ('||prunidimobiliaria||') ';
         end

       wsql = wsql||'group by TRazao.prdata, TRazao.prconta, ';
       wsql = wsql||'TRazao.prcontra, ';
       wsql = wsql||'TRazao.prempresa, TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta,TRazao.prnome_conta_original, ';
       wsql = wsql||'TRazao.prclass_conta, TRazao.prcgc_conta, TRazao.prclass_contra, TRazao.prnome_conta_contra, BDCLANOM, ';
       wsql = wsql||'TRazao.prcnpjemp, ';
       wsql = wsql||'TRazao.PRGRPCTA, TRazao.PRCODHIST, TRazao.PRCODTPHI, TRazao.PRCODPLAPADRAO , ';
       wsql = wsql||'TRazao.PRCODEMPFILIAL, TRazao.prcodmatriz, TRazao.PRCHAVEONLINE, TRazao.PRCODCENTRO, TRazao.prtipolan, ';
       wsql = wsql||'TRazao.PRCTALCDPR, TRazao.PRPART_PR, TRazao.PRCODPART_PR, TRazao.PRTIPLANPR, TRazao.PRCODIMOVRUR, TRazao.PRTIPDOCPR, TRAZAO.PRSALRELCONCILIACOES ) TRazao ';
     END

  IF (prordenacao = 0) THEN
    wclassificacao = 'TRazao.prclass_conta';
  ELSE
    wclassificacao = 'BDCLANOM';

  if (PRORDENANATUREZA = 1) then
    wclassificacao = wclassificacao || ',TRazao.prdata, TRAZAO.PRNATUREZALAN';

  IF (prordempresa = 1) THEN
     BEGIN
       wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, '
                  ||iif(PRDETALHARCC = 1, 'TRazao.prcc, ', '')||wclassificacao||', TRazao.prdata, TRazao.prchave' ||iif(prmostrarcc = 1, ', TRazao.prcc', '');
     END
  ELSE
  IF (prordempresa = 2) THEN
     BEGIN
       wsql = wsql||'order by TRazao.prnome_conta, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, '||wclassificacao||', TRazao.prchave';
     END
  ELSE
  IF (prordempresa = 3) THEN
     BEGIN
       wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prdata, '||wclassificacao||', TRazao.prchave';
     END
  ELSE
  IF (prordempresa = 4) THEN
    BEGIN
      --EXPORTACAO SOMENTE DATA ECF - CARLOS MACHADO - 20/07/2018
      wsql = wsql||'order by TRazao.prdata, TRazao.prclass_conta, TRazao.prchave';
    END
  ELSE
  if (prordempresa = 5) then
     BEGIN
      --Adicionando rotina pra gerar o relatório na ordem de CÓDIGO DA CONTA / DATA / CENTRO DE CUSTO
      wsql = wsql||'order by TRazao.prclass_conta,TRazao.prdata, TRazao.prchave';
    END
  ELSE
     BEGIN
       wsql = wsql||'order by '||iif(PRDETALHARCC = 1, 'TRazao.prcc, ', '')||wclassificacao||', TRazao.prdata, TRazao.prchave, TRazao.prcodmatriz, TRazao.prempresa, TRazao.PRCODEMPFILIAL, TRazao.prchave';
     END

  FOR EXECUTE STATEMENT wsql
      INTO :bdhistorico, :bddata, :bdchave, :bdconta, :bdcontra, :bdcredito, :bddebito,
           :bdconciliado, :bdconciliacaopendente, :bdempresa, :bdnomeempresa, :bdcc, :bdnome_conta,:bdnome_conta_original,
           :bdclass_conta, :bdcgc_conta, :bdclass_contra, :bdnome_conta_contra, :bdlote, :bddcto, :bdcompl, :bdcnpjemp, :bdgrupoconta, :bdcodhist,
           :bdcodtphi, :bdcodplapadrao, :bdref, :wparticipante, :bdcod_terceiro_conta, :bdcod_terceiro_contra, :BDEMPRESAFILIAL, :bdchaveonline, :bdcodcentro,
           :bdtransacao, :bdtranfechada, :bdtipolan,  :wcodmatriz, :bdclanom, :bdempreendimento, :bdunidimob, :bdnaturezalan, :BDCTALCDPR, :BDPART_PR,
           :BDCODPART_PR, :BDTIPLANPR, :BDCODIMOVRUR, :BDTIPDOCPR, :bdsalrelconciliacoes DO
      BEGIN
        bdsaldoanterior = 0;
        BDSEQCTA = NULL;
        BDCC_CONTRA = NULL;

        IF ( (COALESCE(wconta, 0) <> COALESCE(bdconta, 0)) OR
             (COALESCE(wcc_atu, 0) <> COALESCE(bdcc, 0) AND (:prdetalharcc <> 0)) OR
             (PRDETALHAREMPREENDIMENTO = 1 and COALESCE(WEMPREENDIMENTO, 0) <> COALESCE(bdempreendimento, 0)) OR
             (PRDETALHAREMPREENDIMENTO = 1 and (bdempresafilial <> wFilial) and COALESCE(WEMPREENDIMENTO, 0) <> 0) OR
             (PRDETALHARUNIDIMOB = 1 and (COALESCE(WEMPREENDIMENTO, 0) <> COALESCE(bdempreendimento, 0) or COALESCE(WUNIDADEIMOB, 0) <> COALESCE(bdunidimob, 0))) OR
             ((prDetalharCtaParticipante = 1) AND (wParticipante = 1) AND
             --#alt:145558 - Machado - 11/06/2021 - Agrupar participante por CPF.
             --Sem agrupar
             ((((prAgruparParticipantePorCNPJ = 0 or CHAR_LENGTH((TRIM(bdcgc_conta))) <> 18) and
                (PRAGRUPARPARTICIPANTEPORCPF = 0 or CHAR_LENGTH((TRIM(bdcgc_conta))) <> 14) AND (bdcod_terceiro_conta <> wcodter)))
             --Agrupar CNPJ
               or ((prAgruparParticipantePorCNPJ = 1 AND CHAR_LENGTH((TRIM(bdcgc_conta))) = 18) and (SUBSTRING(bdcgc_conta FROM 1 FOR 10) <> SUBSTRING(wCGCTerAnt FROM 1 FOR 10)))
             --Agrupar CPF
               or ((pragruparparticipanteporcpf  = 1 AND CHAR_LENGTH((TRIM(bdcgc_conta))) = 14) and (bdcgc_conta <> wCGCTerAnt))
             ))
             OR ((prDetalharFilial = 1) AND (bdempresafilial <> wFilial)) ) THEN
           BEGIN
             bdvlraconciliar = 0;
             bdvlrconciliado = 0;

             wFilial = bdempresafilial;
             wsaldo = 0;
             IF (PRIGNORASALDOANTERIOR = 0) THEN
               BEGIN
                 IF ((prDetalharCtaParticipante = 1) AND (wparticipante = 1) AND (1 in (pragruparparticipanteporcnpj, pragruparparticipanteporcpf))) THEN
                   BEGIN
                     wsqlemp = 'select emp.bdcodemp as bdempresasefilial, ter.bdcodter ';
--                     wsqlemp = wsqlemp||'from TEMPRESAS emp ';
--                     wsqlemp = wsqlemp||'cross join TTERCEIRO ter ';
--                     wsqlemp = wsqlemp||'where emp.bdcodemp in ('||:prCODEMP||')';
--                     --#89622 - Carlos Machado - 11/09/2018 - Alterado para não fazer agrupamento de participantes do exterior
--                     wsqlemp = wsqlemp||'  and exists (select BDCODTER from VW_TTERCEIRO terAux where terAux.BDCODTER = '||COALESCE(:bdCOD_TERCEIRO_CONTA, 0);
--                     wsqlemp = wsqlemp||'  and ((substring(ter.BDCGCTER from 1 for 10) = substring(terAux.BDCGCTER from 1 for 10) AND terAux.bdcodpais = 30) or (terAux.bdcodpais <> 30 and TER.bdcodter = '||COALESCE(:bdCOD_TERCEIRO_CONTA, 0)||')))';
                       --#91311 - Carlos Machado - 16/10/2018 - Estava causando lentidao
                       wsqlemp = wsqlemp||' from TEMPRESAS EMP';
                       wsqlemp = wsqlemp||' inner join VW_TTERCEIRO TERAUX on (TERAUX.BDCODTER = '||COALESCE(:bdCOD_TERCEIRO_CONTA, 0)||')';
                       --#alt:153860 - 16/08/2021 - Machado - Relatório Razão e Livro Caixa
                       if (char_length(bdcgc_conta) = 14 and pragruparparticipanteporcpf = 1) then
                         wsqlemp = wsqlemp||' inner join TTERCEIRO TER on ((TER.BDCGCTER = TERAUX.BDCGCTER and ((teraux.bdcodpais = 30 and CHAR_LENGTH(teraux.bdcgcter) = 14) or TERAUX.BDCODTER = TER.BDCODTER)))';
                       else
                       if (char_length(bdcgc_conta) = 18 and pragruparparticipanteporcnpj = 1) then
                         wsqlemp = wsqlemp||' inner join TTERCEIRO TER on ((substring(TER.BDCGCTER from 1 for 10) = substring(TERAUX.BDCGCTER from 1 for 10) and ((teraux.bdcodpais = 30 and CHAR_LENGTH(teraux.bdcgcter) = 18) or TERAUX.BDCODTER = TER.BDCODTER)))';
                       else
                         wsqlemp = wsqlemp||' inner join TTERCEIRO TER on (TERAUX.BDCODTER = TER.BDCODTER)';
                       wsqlemp = wsqlemp||' where EMP.BDCODEMP in ('||:prCODEMP||')';
                       wsqlemp = wsqlemp||' order by EMP.BDCODMATRIZ asc, EMP.BDCODEMP asc, TER.BDCODTER asc  ';
                     wAgrupaPart = 0;
                   END
                 ELSE
                   BEGIN
                     wsqlemp = 'select emp.bdcodemp as bdempresasefilial, '||COALESCE(:bdCOD_TERCEIRO_CONTA, 0)||' as bdcodter ';
                     wsqlemp = wsqlemp||'from TEMPRESAS emp ';
                     wsqlemp = wsqlemp||'where emp.bdcodemp in ('||:prCODEMP||')';
                     wsqlemp = wsqlemp||'order by emp.BDCODMATRIZ asc, emp.BDCODEMP asc ';
                   END
                 FOR EXECUTE STATEMENT wsqlemp INTO :wCODEMPEFILIAL, :wCODTER DO
                 BEGIN
                   wsaldo    = 0;
                   wsaldoaux = 0;

                   if (prplano_secundario > 0) then
                      begin
                        wsqlcontas = 'SELECT PREP.BDCODTPLA, TPLA.BDSALRELCONCILIACOES FROM VSUC_PREPARACAO_TPLA_SECUNDARIO PREP ';
                        wsqlcontas = wsqlcontas||' INNER JOIN PLANOS_TPLA TPLA ON (TPLA.bdcodplapadrao = PREP.bdcodplapadrao AND TPLA.bdcodtpla = PREP.bdcodtpla AND TPLA.bdtipcta = 1)';
                        wsqlcontas = wsqlcontas||'WHERE PREP.bdcodemp = '||wcodmatriz||' and PREP.BDCODPLAPADRAO = '||bdcodplapadrao||' and PREP.BDCODPLAPADRAO_SEC = '||prplano_secundario||' and PREP.bdcodtpla_sec = '||bdconta;
                        if (prplano_secundario = 1) then
                          wsqlcontas = wsqlcontas||' and PREP.BDANOPLACOSIF = '|| substring(prdata_final from 1 for 4);
                      end
                   else
                      begin
                        wsqlcontas = 'SELECT BDCODTPLA, BDSALRELCONCILIACOES FROM PLANOS_TPLA WHERE BDCODPLAPADRAO = '||bdcodplapadrao||' and BDCODTPLA = '||bdconta;
                      end

                   FOR EXECUTE STATEMENT wsqlcontas into :WCONTA_SALDO, :wsalrelcontabilizacao DO
                   BEGIN
                   bdsalrelconciliacoes = :wsalrelcontabilizacao;
                   -- Detalhado por participante

                   IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1) AND (bdcod_terceiro_conta IS NOT NULL)) THEN
                      BEGIN
                        if (:prmostrarcc = 1) then
                          BEGIN
                            wRegraCC = NULL;
                            wRegraLancamentoSemCC = 0;
                          END
                        else
                          BEGIN
                            wRegraCC = iif(:bdcc is null and :PRLANCAMENTOSEMCC = 1, 1, :BDCC);
                            wRegraLancamentoSemCC = iif(:bdcc is null and :PRLANCAMENTOSEMCC = 1, 1, 0);
                          END


                          FOR SELECT bdsaldo_anterior FROM vsuc_sp_retorna_saldos_ctaparty(:wcodempefilial,:bdcodplapadrao,:prdata_inicial,:prdata_inicial,:WCONTA_SALDO,:prindice,
                                                                                         0,:wCodTer,:bdconciliados,:prcodemp,:prcontabilizacao,
                                                                                         :PRAGRUPARPARTICIPANTEPORCNPJ, :wregracc , :wRegraLancamentoSemCC,
                                                                                         :pragruparparticipanteporcpf, 0, 0, :prrefemp, '', :PRFILTIPOLAN)
                        INTO :wsaldoaux DO
                          BEGIN
                            wsaldo = wsaldo + COALESCE(wsaldoaux,0);
                          END
                      END
                   ELSE
                      BEGIN
                       if (:prmostrarcc = 1) then
                         BEGIN
                           wRegraCC = NULL;
                         END
                       else
                         BEGIN
                           wRegraCC = iif(:bdcc is NULL and :PRLANCAMENTOSEMCC = 1, 0, :bdcc);
                         END

                        --#alt:87155. Adicionei o código da empresa matriz para controle de busca do plano de contas da empresa. Ana - 20/07/2018
                        IF ((prdetalharctaparticipante = 0) AND (((PRPARTINI > 0) AND (PRPARTFIN > 0)) or (coalesce(prlistapart,'') <> '') ))  THEN
                             SELECT SALDO_ANTERIOR+:wsaldo FROM sp_retorna_saldo_emp_x(:wcodempefilial, :WCONTA_SALDO, :prdata_inicial, :prdata_inicial, :prIndice, 0, :wRegraCC, NULL,
                                                                             :prrefemp,0,:prcontabilizacao ,:prmatrizfilialconsolidado, :PRPARTINI, :PRPARTFIN,iif(:PRDETALHAREMPREENDIMENTO = 1,:BDEMPREENDIMENTO, 0),iif(:PRDETALHARUNIDIMOB = 1,:BDUNIDIMOB, 0),0, :wcodmatriz,0,:prlistapart, :PRFILTIPOLAN)
                           INTO :wsaldo;
                        ELSE
                             SELECT SALDO_ANTERIOR+:wsaldo FROM sp_retorna_saldo_emp_x(:wcodempefilial, :WCONTA_SALDO, :prdata_inicial, :prdata_inicial, :prIndice, 0, :wRegraCC, NULL,
                                                                             :prrefemp,0,:prcontabilizacao ,:prmatrizfilialconsolidado,0,0,iif(:PRDETALHAREMPREENDIMENTO = 1,:BDEMPREENDIMENTO, 0),iif(:PRDETALHARUNIDIMOB = 1,:BDUNIDIMOB, 0),0, :wcodmatriz,0,:prlistapart, :PRFILTIPOLAN)
                           INTO :wsaldo;
                      END
                   END

                   --quando agruparParticipantePorCNPJ, então deve somar apenas na filial corrente. Se somar todas as filiais o saldo não bate. Ana - 22/09/2016
                   IF (prAgruparParticipanteporCNPJ = 0 and pragruparparticipanteporcpf = 0) THEN
                       IF  --quando detalharfilial e não detalharparticipante, então soma a matriz
                           (((prDetalharFilial = 1) AND (wFilial = wcodempefilial)) OR
                           --Se detalhar empreendimento soma apenas na empresa
                             (wFilial = wcodempefilial AND PRDETALHAREMPREENDIMENTO = 1 AND BDEMPREENDIMENTO > 0)) THEN
                           BEGIN
                             bdsaldoanterior = COALESCE(wsaldo,0);
                             wsaldo = bdsaldoanterior;
                             BREAK;
                           END
                       ELSE
                          BEGIN
                             bdsaldoanterior = bdsaldoanterior + COALESCE(wsaldo,0);
                             wsaldo = bdsaldoanterior;
                          END
                   ELSE
                       -- se detalhar por filial então soma tudo
                       -- se não soma apenas quando for da filial corrente
                       IF ((prdetalharfilial = 0) OR (wFilial = wcodempefilial) OR (wFilial IS NULL)) THEN
                          BEGIN
                             bdsaldoanterior = bdsaldoanterior + COALESCE(wsaldo,0);
                             wsaldo = bdsaldoanterior;
                          END
                        ELSE
                        --#alt:126643 - 05/11/2019 - Carlos Machado - Saldo errado quando agrupa CNPJ e detalha filial
                             wsaldo = bdsaldoanterior;
                 END
               END

             wordem = 0;

             IF (bdgrupoconta IN (1,2,3)) THEN
                BEGIN
                  wsaldo = (wsaldo + COALESCE(bdcredito, 0) - COALESCE(bddebito, 0));
                  wvalor = COALESCE(bdcredito, 0) - COALESCE(bddebito, 0);
                END
             ELSE
                BEGIN
                  wsaldo = (wsaldo + COALESCE(bddebito, 0) - COALESCE(bdcredito, 0));
                  wvalor = COALESCE(bddebito, 0) - COALESCE(bdcredito, 0);
                END
           END
        ELSE
           BEGIN
             bdsaldoanterior = wsaldo;

             IF (bdgrupoconta IN (1,2,3)) THEN
                BEGIN
                  wsaldo = (wsaldo + COALESCE(bdcredito, 0) - COALESCE(bddebito, 0));
                  wvalor = COALESCE(bdcredito, 0) - COALESCE(bddebito, 0);
                END
             ELSE
                BEGIN
                  wsaldo = (wsaldo + COALESCE(bddebito, 0) - COALESCE(bdcredito, 0));
                  wvalor = COALESCE(bddebito, 0) - COALESCE(bdcredito, 0);
                END
           END
        wordem = wordem + 1;
        bdordsaldo = wordem;
        bdsaldo = wsaldo;
        IF (wvalor < 0) THEN
           bdvalorsemsinal = wvalor * -1;
        ELSE
           bdvalorsemsinal = wvalor;
        bdvalor     = wvalor;

       IF ((UPPER(bdconciliado) <> 'TRUE') OR (bdconciliado IS NULL)) THEN
          bdvlraconciliar = bdvlraconciliar + wvalor;
       ELSE
          bdvlrconciliado = bdvlrconciliado + wvalor;

        wconta = bdconta;
        wcodter = bdcod_terceiro_conta;
        wCGCTerAnt = bdcgc_conta;
        WEMPREENDIMENTO = BDEMPREENDIMENTO;
        WUNIDADEIMOB = BDUNIDIMOB;

        --alt:7823 - Copia o centro de que será gravado para a variável do centro de custo, que faz verificação de qual centro de custo é o atual. Pedro
        wcc_atu = bdcc;

        --#alt:91184- 11/10/2018 - Carlos Machado - O tratamento de contas sem movimento agora é feito após a execução
        --IF ((PRCONTASSEMMOVIMENTO = 0) OR (BDCHAVE IS NOT NULL) OR (BDSALDOANTERIOR <> 0)) THEN
        IF ((BDCHAVE IS NOT NULL) and ((prsolansemempree = 0) or
           ((prsolansemempree = 1) and ((WEMPREENDIMENTO = 0) or (WEMPREENDIMENTO is null)) and ((WUNIDADEIMOB = 0) or (WUNIDADEIMOB is null))))) THEN
          BEGIN
          --#alt:133629 - Machado - 24/03/2020 - Alterada rotina para que possa gerar infinitamente o razão
          --#alt:140112 - Machado - 07/08/2020 - Relatório Razão e Livro Caixa - Lentidão
          if (prdcdoislancamentos = 1 and bdcontra IS NULL and UPPER(bdtranfechada) = 'TRUE') then
            begin
            wsql = 'select count (BDTRANSACAO), MAX(bdcodemp), max(bdchave) from (select first 2 BDTRANSACAO, bdcodemp, bdchave from VSUC_EMPRESAS_TLAN where BDCODEMP in ('||:bdempresa||') and BDTRANFECHADA = '''||'TRUE'||''' and '||
                   'BDTRANSACAO = '||COALESCE(:bdtransacao, 0)||' and '||
                   '((bdcodemp <> '||bdempresa||' or bdchave <> '||bdchave||')))';
            EXECUTE STATEMENT wsql INTO :wtam, :wcodempdc, :wchavedc;
            if (wtam = 0) then
              begin
                wsql = 'select count (BDTRANSACAO), MAX(bdcodemp), max(bdchave) from (select first 2 BDTRANSACAO, bdcodemp, bdchave from VSUC_EMPRESAS_TLAN where BDCODEMP in ('||:prcodemp||') and BDTRANFECHADA = '''||'TRUE'||''' and '||
                       'BDTRANSACAO = '||COALESCE(:bdtransacao, 0)||' and '||
                       '((bdcodemp <> '||bdempresa||' or bdchave <> '||bdchave||')))';
                EXECUTE STATEMENT wsql INTO :wtam, :wcodempdc, :wchavedc;
              end
            IF (wtam = 1) THEN
                begin
                  wsql = 'SELECT FIRST 1 case when TLAN.BDDEBITO = TPLA.BDCODTPLA then TLAN.BDDEBITO else TLAN.BDCREDITO end as BDCONTA, '||
                         'TPLA.BDNOMCTA, TPLA.BDCTALON, CC.BDCODTPCC '||
                         'FROM VSUC_EMPRESAS_TLAN TLAN '||
                         'LEFT OUTER JOIN PLANOS_TPLA TPLA on (tpla.BDCODPLAPADRAO = tlan.BDCODPLAPADRAO and (tpla.BDCODTPLA = tlan.BDDEBITO or tpla.BDCODTPLA = tlan.BDCREDITO)) '||
                         'LEFT OUTER JOIN VSUC_EMPRESAS_TLCC CC ON (CC.BDCODEMP = TLAN.BDCODEMP AND CC.BDCHAVE = TLAN.BDCHAVE AND CC.BDDEBCRE = '||IIF(BDDEBITO IS NULL, 0, 1)||' AND (CC.BDPERCENTUAL IS NULL OR CC.BDPERCENTUAL = 0 OR CC.BDPERCENTUAL = 100))'||
                         'WHERE TLAN.BDCODEMP = '||wcodempdc||' and TLAN.bdchave = '||wchavedc;
                  EXECUTE STATEMENT wsql INTO :BDCONTRA, :BDNOME_CONTA_CONTRA, :BDCLASS_CONTRA, :BDCC_CONTRA;
                end
            end
                      SUSPEND;
                  END

--        IF (prdcdoislancamentos = 1) THEN
--          BEGIN
--            wsql = 'select count (BDTRANSACAO) from VSUC_EMPRESAS_TLAN where BDCODEMP in ('||:prcodemp||') and BDTRANFECHADA = '''||'TRUE'||''' and '||
--                   'BDTRANSACAO = '||COALESCE(:bdtransacao, 0)||' and (BDDEBITO is null or BDCREDITO is null) and '||
--                   '(coalesce(BDDEBITO, 0) <> coalesce('||:bdconta||', 0) and coalesce(BDCREDITO, 0) <> coalesce('||:bdconta||', 0))';
--            EXECUTE STATEMENT wsql INTO :wtam;
--            IF (wtam = 1) THEN
--              BEGIN
--                wsql = 'SELECT TLAN.bdcodemp, TLAN.BDCHAVE, TLAN.BDDATA, TLAN.BDCODPLAPADRAO, TLAN.BDTRANFECHADA, TLAN.BDTRANSACAO, '||
--                       '/*Conta*/ case when TLAN.BDDEBITO = TPLA.BDCODTPLA then TLAN.BDDEBITO else TLAN.BDCREDITO end as BDCONTA, '||
--                       '/*Valor débito*/ case when TLAN.BDDEBITO = TPLA.BDCODTPLA then TLAN.BDVALOR end as BDDEBITO, '||
--                       '/*Valor crédito*/ case when (TLAN.BDDEBITO is null and TLAN.BDCREDITO is not null) then TLAN.BDVALOR end as BDCREDITO '||
--                       'FROM VSUC_EMPRESAS_TLAN TLAN '||
--                       'LEFT OUTER JOIN PLANOS_TPLA TPLA on (tpla.BDCODPLAPADRAO = tlan.BDCODPLAPADRAO and (tpla.BDCODTPLA = tlan.BDDEBITO or tpla.BDCODTPLA = tlan.BDCREDITO)) '||
--                       'WHERE BDCODEMP in ('||:prcodemp||') and BDTRANFECHADA = '''||'TRUE'||''' and BDTRANSACAO = '||:bdtransacao||' and (BDDEBITO is null or BDCREDITO is null) and '||
--                       '      (coalesce(BDDEBITO, 0) <> coalesce('||:bdconta||', 0) and coalesce(BDCREDITO, 0) <> coalesce('||:bdconta||', 0))';
--                EXECUTE STATEMENT wsql INTO :bdempresafilial, :bdchave, :bddata, :bdcodplapadrao, :bdtranfechada, :bdtransacao, :bdconta, :bddebito, :bdcredito;
--                  BEGIN
--                    --#ALT:70754. Para o novo modelo do razão preciso destas informações da contrapartida. Ana
--                    SELECT FIRST 1 BDCTALON, BDNOMCTA FROM PLANOS_TPLA WHERE BDCODTPLA = :bdconta AND BDCODPLAPADRAO = :bdcodplapadrao INTO :BDCLASS_CONTA, :BDNOME_CONTA;
--
--                    BDSEQCTA = 'DEL'; --alt:10873 - 17/03/2015 - Se for 'DEL' é lançamento utilizado para verificar contrapartida, deve excluir depois de usar. Pedro
--
--                    IF ((prsolansemempree = 0) or
--                       ((prsolansemempree = 1) and ((WEMPREENDIMENTO = 0) or (WEMPREENDIMENTO is null)) and ((WUNIDADEIMOB = 0) or (WUNIDADEIMOB is null)))) THEN
--                      SUSPEND;
--                  END
--              END
--          END
              END
END^

/* Restore proc. body: VSUC_SP_RETORNA_RAZAO_SALDO2 */
ALTER PROCEDURE VSUC_SP_RETORNA_RAZAO_SALDO2(PRCODEMP VARCHAR(1024),
PRCLASSIFICACAO_INICIAL VARCHAR(40),
PRCLASSIFICACAO_FINAL VARCHAR(40),
PRDATA_INICIAL DATE,
PRDATA_FINAL DATE,
PRINDICE INTEGER,
PRLCC VARCHAR(8192),
PRORDEMPRESA INTEGER,
PRREFEMP INTEGER,
PRDETALHARCTAPARTICIPANTE INTEGER,
PRCONCATENACODPARTICIPANTE INTEGER,
BDCONCILIADOS INTEGER,
PRPARTINI INTEGER,
PRPARTFIN INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRDETALHARFILIAL INTEGER)
 RETURNS(BDHISTORICO VARCHAR(400),
BDDATA DATE,
BDCHAVE INTEGER,
BDCONTA INTEGER,
BDCONTRA INTEGER,
BDCREDITO NUMERIC(15,2),
BDDEBITO NUMERIC(15,2),
BDSALDO NUMERIC(15,2),
BDCONCILIADO VARCHAR(5),
BDEMPRESA INTEGER,
BDNOMEEMPRESA VARCHAR(80),
BDCC INTEGER,
BDNOME_CONTA VARCHAR(100),
BDCLASS_CONTA VARCHAR(30),
BDCOD_TERCEIRO_CONTA INTEGER,
BDCLASS_CONTRA VARCHAR(20),
BDNOME_CONTA_CONTRA VARCHAR(100),
BDCOD_TERCEIRO_CONTRA INTEGER,
BDVALOR NUMERIC(15,2),
BDORDSALDO INTEGER,
BDLOTE VARCHAR(10),
BDDCTO VARCHAR(15),
BDCOMPL VARCHAR(200),
BDCNPJEMP VARCHAR(18),
BDSALDOANTERIOR NUMERIC(15,2),
BDVALORSEMSINAL NUMERIC(15,2),
BDGRUPOCONTA INTEGER,
BDCODHIST INTEGER,
BDCODPLAPADRAO INTEGER,
BDREF VARCHAR(8),
BDCODTPHI INTEGER,
BDEMPRESAFILIAL INTEGER)
 AS
DECLARE VARIABLE wconta INTEGER;
DECLARE VARIABLE wsaldo NUMERIC(15,2);
DECLARE VARIABLE wclass VARCHAR(20);
DECLARE VARIABLE wvalor NUMERIC(15,2);
DECLARE VARIABLE wordem INTEGER;
DECLARE VARIABLE wclassini VARCHAR(30);
DECLARE VARIABLE wclassfin VARCHAR(30);
DECLARE VARIABLE wtam INTEGER;
DECLARE VARIABLE wcredito NUMERIC(15,2);
DECLARE VARIABLE wdebito NUMERIC(15,2);
DECLARE VARIABLE wgrupocta INTEGER;
DECLARE VARIABLE wsql VARCHAR(10240);
DECLARE VARIABLE wparticipante INTEGER;
DECLARE VARIABLE wclass_ant VARCHAR(30);
DECLARE VARIABLE wpos INTEGER;
DECLARE VARIABLE wsqlemp VARCHAR(10240);
DECLARE VARIABLE wcodempefilial INTEGER;
BEGIN
  -- BDCONCILIADOS = 0 TODOS 1 CONCILIADOS 2 NAO CONCILIADOS

  wconta     = 0;
  wsaldo     = 0;
  wordem     = 0;
  wclass_ant = '';

  wsql = 'select TRazao.prhistorico, TRazao.prdata, TRazao.prchave, TRazao.prconta, ';
  wsql = wsql||'TRazao.prcontra, TRazao.prcredito, TRazao.prdebito, ';
  wsql = wsql||'TRazao.prconciliado, TRazao.prempresa, ';
  wsql = wsql||'TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta, TRazao.prclass_conta, ';
  wsql = wsql||'TRazao.prclass_contra, TRazao.prnome_conta_contra, TRAZAO.prlote, TRAZAO.prdcto, TRAZAO.prcompl, TRAZAO.prcnpjemp, ';
  wsql = wsql||'TRAZAO.PRGRPCTA, TRAZAO.PRCODHIST, TRAZAO.PRCODTPHI, TRAZAO.PRCODPLAPADRAO , ';
  wsql = wsql||'(substring((CAST(TRazao.prdata AS VARCHAR(10))) from 6 for 2) || ''/'' || substring((CAST(TRazao.prdata AS VARCHAR(10))) from 1 for 4)), ';
  wsql = wsql||'TRAZAO.prparticipanteconta, tRAZAO.prcodterceiroconta, tRAZAO.prcodterceirocontra, trazao.PRCODEMPFILIAL ';

  wsql = wsql||'from vsuc_sp_retorna_razao_contas('''||TRIM(prcodemp)||''','''||TRIM(prclassificacao_inicial)||''','''||TRIM(prclassificacao_final)||''','''||prdata_inicial||''','''||prdata_final||''',''';
--  wsql = wsql||                                   trim(prlcc)||''','||trim(prordempresa)||','||prrefemp||','||prdetalharctacliente||','||prdetalharctafornecedor||','||PRCONCATENACODCLIFOR||',null,null) TRazao ';
  wsql = wsql||                                   TRIM(prlcc)||''',';
  wsql = wsql||TRIM(prordempresa)||',';
  wsql = wsql||prrefemp||',';
  wsql = wsql||prdetalharctaparticipante||',';
  wsql = wsql||PRCONCATENACODPARTICIPANTE||',';
  IF (prpartini IS NOT NULL) THEN
     wsql = wsql||prpartini||',';
  ELSE
     wsql = wsql||'null,';
  IF (prpartfin IS NOT NULL) THEN
     wsql = wsql||prpartfin||',';
  ELSE
     wsql = wsql||'null,';
  wsql = wsql||prcontabilizacao||','||prmatrizfilialconsolidado||','||prdetalharfilial||') TRazao ';

  IF (bdconciliados = 1) THEN
     wsql = wsql|| ' where (Upper(TRazao.prconciliado) = '||'''TRUE'''||')';
  ELSE
  IF (bdconciliados = 2) THEN
     wsql = wsql|| ' where ((Upper(TRazao.prconciliado) = '||'''FALSE'''||') or (TRazao.prconciliado is null))';

  IF (prordempresa = 1) THEN
--     wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prconta, TRazao.prdata, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
     wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prclass_conta, TRazao.prdata, TRazao.prchave';
  ELSE
  IF (prordempresa = 2) THEN
     wsql = wsql||'order by TRazao.prnome_conta, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prchave';
  ELSE
  IF (prordempresa = 3) THEN
--     wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prdata, TRazao.prconta, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
     wsql = wsql||'order by TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prdata, TRazao.prclass_conta, TRazao.prchave';
  ELSE
--     wsql = wsql||'order by TRazao.prconta, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prchave'; -- gilberto - 26/07/2013 - 6208
     wsql = wsql||'order by TRazao.prclass_conta, TRazao.prdata, TRazao.prcodmatriz, TRazao.prempresa, trazao.PRCODEMPFILIAL, TRazao.prchave';
/*
  for select TRazao.prhistorico, TRazao.prdata, TRazao.prchave, TRazao.prconta,
             TRazao.prcontra, TRazao.prentrada, TRazao.prsaida, TRazao.prconciliado, TRazao.prempresa,
             TRazao.prnomeempresa, TRazao.prcc, TRazao.prnome_conta, TRazao.prclass_conta,
             TRazao.prclass_contra, TRAZAO.prlote, TRAZAO.prdcto, TRAZAO.prcompl, TRAZAO.prcnpjemp
      from vsuc_sp_retorna_razao_contas(:prcodigo_empresa, :wclassini, :wclassfin,
                                        :prdata_inicial, :prdata_final, :prfiliais, :prlcc) TRazao
      order by TRazao.prconta, TRazao.prdata
*/
  FOR EXECUTE STATEMENT wsql
      INTO :bdhistorico, :bddata, :bdchave, :bdconta, :bdcontra, :bdcredito, :bddebito, /*:prcomplemento,*/
           /*:prcontra_longa, */:bdconciliado, :bdempresa, :bdnomeempresa, :bdcc, :bdnome_conta,
           :bdclass_conta, :bdclass_contra, :bdnome_conta_contra, :bdlote, :bddcto, :bdcompl, :bdcnpjemp, :bdgrupoconta, :bdcodhist,
           :bdcodtphi, :bdcodplapadrao, :bdref, :wparticipante, :bdcod_terceiro_conta, :bdcod_terceiro_contra, :BDEMPRESAFILIAL DO
      BEGIN
        bdsaldoanterior = 0;
        --Incluido a verificação (wconta <> bdcontra), sem isso entrava nesta rotina sempre. Bruno Borges
        IF (((wconta <> bdconta) AND (wconta <> bdcontra)) OR
            (((prdetalharctaparticipante = 1) AND (wparticipante = 1)) AND
             (bdclass_conta <> wclass_ant)))THEN
           BEGIN

             /* INICIO Giovanni, precisa fazer um laco das empresas para trazer o saldo anterior correto */

             -- retorna as empresas selecionadas
             wsqlemp = 'select temp.bdcodemp bdempresasefilial ';
             wsqlemp = wsqlemp||'from tempresas temp ';
             wsqlemp = wsqlemp||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
             wsqlemp = wsqlemp||'where temp.bdcodemp in ('||prcodemp||') ';
             wsqlemp = wsqlemp||'order by temp.bdcodmatriz asc, temp.bdcodemp asc ';
             -- executa o sql das empresas

             FOR EXECUTE STATEMENT wsqlemp
                 INTO :wcodempefilial DO
             BEGIN
               -- Detalhado por participante
               IF ((prdetalharctaparticipante = 1) AND (wparticipante = 1)) THEN
--                 select bdsaldo_anterior from vsuc_sp_retorna_saldos_cta_part(:wcodempefilial,:bdcodplapadrao,:prdata_inicial,:prdata_final,:bdconta, -- alt:#6647 - gilberto - 12/09/2013
                 SELECT bdsaldo_anterior FROM vsuc_sp_retorna_saldos_ctaparty(:wcodempefilial,:bdcodplapadrao,:prdata_inicial,:prdata_final,:bdconta,:prindice,
                                                                              0,:bdcod_terceiro_conta,:BDCONCILIADOS,:prcodemp,:prcontabilizacao,
                                                                              0, '', 0, 0, 0, 0, :prrefemp)
                 INTO :wsaldo;
               ELSE
                 SELECT /*(saldo_ant_deb - saldo_ant_cre) */     SALDO_ANTERIOR FROM sp_retorna_saldo_emp(:wcodempefilial, :bdconta,
                 :prdata_inicial, :prdata_final, 0, :bdcc, NULL, :prrefemp,:bdconciliados,:prcontabilizacao,:prmatrizfilialconsolidado)
                 INTO :wsaldo;

                 bdsaldoanterior = bdsaldoanterior + wsaldo;
             END


             /* FIM Giovanni, precisa fazer um laco das empresas para trazer o saldo anterior correto */

             SELECT tpla.bdctalon, tpla.bdgrupocta FROM planos_tpla TPla
             WHERE tpla.bdcodplapadrao = :bdcodplapadrao
             AND tpla.bdcodtpla = :bdconta
             INTO :wclass, :wgrupocta;

             wordem = 0;

             /* Saldo ________________________________________________________*/
             -- Credito --------------------------------------------------------
             wcredito = bdcredito;
             IF ((wcredito IS NULL) OR (wcredito = 0)) THEN
                wcredito = 0;
             ELSE
             -- Ativo
             IF (wgrupocta = 0) THEN
                wcredito = wcredito * -1;
             ELSE
             -- Passivo
             IF (wgrupocta = 1) THEN
                wcredito = wcredito;
             ELSE
             -- Receitas
             IF (wgrupocta = 3) THEN
                wcredito = wcredito;
             ELSE
             -- Despesas
             IF (wgrupocta = 4) THEN
                wcredito = wcredito * -1;
             ELSE
             -- Outros
             IF (wgrupocta = 5) THEN
                wcredito = wcredito * -1;
           
             -- Debito ---------------------------------------------------------
             wdebito = bddebito;
             IF ((wdebito IS NULL) OR (wdebito = 0)) THEN
                wdebito = 0;
             ELSE
             -- Ativo
             IF (wgrupocta = 0) THEN
                wdebito = wdebito;
             ELSE
             -- Passivo
             IF (wgrupocta = 1) THEN
                wdebito = wdebito * -1;
             ELSE
             -- Receitas
             IF (wgrupocta = 3) THEN
                wdebito = wdebito * -1;
             ELSE
             -- Despesas
             IF (wgrupocta = 4) THEN
                wdebito = wdebito;
             ELSE
             -- Outros
             IF (wgrupocta = 5) THEN
                wdebito = wdebito;
             -------------------------------------------------------------------

             wsaldo = wsaldo + wdebito + wcredito;
             wvalor = wdebito + wcredito;
             /*_______________________________________________________________*/
           END
        ELSE
           BEGIN
             bdsaldoanterior = wsaldo;

             /* Saldo ________________________________________________________*/
             -- Credito --------------------------------------------------------
             wcredito = bdcredito;
             IF ((wcredito IS NULL) OR (wcredito = 0)) THEN
                wcredito = 0;
             ELSE
             -- Ativo
             IF (wgrupocta = 0) THEN
                wcredito = wcredito * -1;
             ELSE
             -- Passivo
             IF (wgrupocta = 1) THEN
                wcredito = wcredito;
             ELSE
             -- Receitas
             IF (wgrupocta = 3) THEN
                wcredito = wcredito;
             ELSE
             -- Despesas
             IF (wgrupocta = 4) THEN
                wcredito = wcredito * -1;
             ELSE
             -- Outros
             IF (wgrupocta = 5) THEN
                wcredito = wcredito * -1;
           
             -- Debito ---------------------------------------------------------
             wdebito = bddebito;
             IF ((wdebito IS NULL) OR (wdebito = 0)) THEN
                wdebito = 0;
             ELSE
             -- Ativo
             IF (wgrupocta = 0) THEN
                wdebito = wdebito;
             ELSE
             -- Passivo
             IF (wgrupocta = 1) THEN
                wdebito = wdebito * -1;
             ELSE
             -- Receitas
             IF (wgrupocta = 3) THEN
                wdebito = wdebito * -1;
             ELSE
             -- Despesas
             IF (wgrupocta = 4) THEN
                wdebito = wdebito;
             ELSE
             -- Outros
             IF (wgrupocta = 5) THEN
                wdebito = wdebito;
             -------------------------------------------------------------------

             wsaldo = wsaldo + wdebito + wcredito;
             wvalor = wdebito + wcredito;
             /*_______________________________________________________________*/
           END
        wordem = wordem + 1;
        bdordsaldo = wordem;
        bdsaldo = wsaldo;
        IF (wvalor < 0) THEN
           bdvalorsemsinal = wvalor * -1;
        ELSE
           bdvalorsemsinal = wvalor;
        bdvalor     = wvalor;
        wconta      = bdconta;

        -- giovanni comentei a linha abaixo, se precisar me chamar para discutir...
        -- ja que o bdcompl ja tem o completo do historico completo, pra que dois campos iguais ????
        -- bdhistorico = bdcompl;

       IF (bdhistorico IS NOT NULL) THEN
         BEGIN
           SELECT pos FROM pos('*', :bdhistorico) INTO :wpos;
             IF (wpos > 0) THEN
                bdhistorico = bdcompl;
             ELSE
               bdhistorico = bdhistorico || ' ' || bdcompl;
         END
       ELSE
         bdhistorico = bdcompl;


        wclass_ant  = bdclass_conta;

        SUSPEND;
      END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_REL_ORCA */
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_REL_ORCA (
    PRCODEMP VARCHAR(2048),
    PRDATINI DATE,
    PRDATFIN DATE,
    PRIGNORA_ZERAMENTO INTEGER,
    PRCTAINI INTEGER,
    PRCTAFIN INTEGER,
    PRINDICE INTEGER,
    PRCODTPCC VARCHAR(8192),
    PRREFEMP INTEGER,
    PRLANSEMCC INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP VARCHAR(18),
    BDCODMATRIZ INTEGER,
    BDCODPLAPADRAO INTEGER,
    BDCODCTA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDTIPCTA SMALLINT,
    BDCODTPCC INTEGER,
    BDNOMTPCC VARCHAR(40),
    BDSALDOREALIZADO NUMERIC(15,2),
    BDGRPCTA SMALLINT,
    BDTPCCLON VARCHAR(20),
    BDFORMULA VARCHAR(200),
    BDRELCTA INTEGER,
    BDNEGFOR VARCHAR(5),
    BDSUBLFOR VARCHAR(5),
    BDLINSEMVALFOR VARCHAR(5))
AS
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WSALDOREALIZADO NUMERIC(15,2);
DECLARE VARIABLE WCONTA INTEGER;
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WGRPCTA SMALLINT;
DECLARE VARIABLE WFORMULA VARCHAR(200);
BEGIN
  BDNEGFOR = 'FALSE';
  BDSUBLFOR = 'FALSE';
  BDLINSEMVALFOR = 'FALSE';

  -- retorna as empresas selecionadas
  wsql = 'select distinct(temp.bdcodemp), tref.bdnomemp, temp.bdcnpjemp, tref.bdcodplapadrao, temp.bdcodmatriz ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc';
  -- executa o sql das empresas
  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdnomemp, :bdcnpjemp, :bdcodplapadrao, :bdcodmatriz DO
      BEGIN
        DELETE FROM VSUC_EMPRESAS_REL_TORCAMENTO_2 WHERE 1=1;
        -- verifica se existe centro de custo selecionado
        IF (prcodtpcc = '') THEN
           BEGIN
             bdcodtpcc = 0;
             bdnomtpcc = '';
             bdtpcclon = '';
             -- retorna todas as contas do plano de contas sem o centro de custo
             FOR SELECT tsalcta.conta, tsalcta.classificacao, tsalcta.nomeconta, tsalcta.tipconta, tsalcta.GRUPOCONTA,
                        tsalcta.bdrealizado,  tsalcta.formula, tsalcta.relconta
                 FROM vsuc_sp_retorna_saldo_orca(:bdcodemp, :prctaini, :prctafin, :prdatini, :prdatfin, :prIndice, :prignora_zeramento, 0, :bdcodplapadrao,
                                                 :prniveisconta,0,:prcontabilizacao,:prmatrizfilialconsolidado) tsalcta
                 INTO :bdcodcta, :bdctalon, :bdnomcta, :bdtipcta, :bdgrpcta,
                      :bdsaldorealizado,  :bdformula, :bdrelcta DO
                 BEGIN
                       BEGIN
                         --bdmovimento = bdsaldo_atual - bdsaldo_anterior;
                         SUSPEND;
                       END
                 END
           END
        ELSE
           BEGIN
             -- inicializa as variaveis
             bdsaldorealizado = 0;
             -- sql por centro de custo selecionado
             wsql = 'select tpcc.bdcodtpcc, tpcc.bdnomcta, tpcc.bdctalon from centros_tpcc tpcc ';
             wsql = wsql||'where tpcc.bdcodcentro = (select first 1 temp.bdcodcentros from tempresas_ref temp ';
             wsql = wsql||                          'where temp.bdcodemp in ('||bdcodemp||')';
             wsql = wsql||                         ' and temp.bdrefemp <= '||prrefemp;
             wsql = wsql||                         ' order by temp.bdrefemp desc) ';
             wsql = wsql||'and tpcc.bdcodtpcc in ('||prcodtpcc||')';
             -- execucao do sql por centro de custo para trazer os lancamnetos sem o centro de custo
             IF (prlansemcc = 1) THEN
                BEGIN
                     FOR SELECT conta, classificacao, nomeconta, tipconta, GRUPOCONTA, bdrealizado,
                              formula, relconta
                       FROM vsuc_sp_retorna_saldo_orca(:bdcodemp, :prctaini, :prctafin, :prdatini, :prdatfin, :prIndice, :prignora_zeramento, '-1',
                                                       :bdcodplapadrao,:prniveisconta,0,:prcontabilizacao,:prmatrizfilialconsolidado,
                                                       1)
                       INTO :wconta, :wctalon, :wnomcta, :wtipcta, :wgrpcta,
                            :wsaldorealizado, :wformula, :bdrelcta DO
                      BEGIN
                                   bdcodcta = wconta;
                                   bdctalon = wctalon;
                                   bdnomcta = wnomcta;
                                   bdtipcta = wtipcta;
                                   bdgrpcta = wgrpcta;
                          bdformula = wformula;    
                          bdsaldorealizado = :wsaldorealizado;
                          
                          bdcodtpcc = NULL;
                          bdnomtpcc = 'Sem Centro de Custo';
                          bdtpcclon = NULL;
                          SUSPEND;
                                 END
                                 END

             -- execucao do sql por centro de custo
             FOR EXECUTE STATEMENT wsql
                 INTO :bdcodtpcc, :bdnomtpcc, :bdtpcclon DO
                 BEGIN
                   -- laco que retorna as contas por centro de custo selecionado
                   FOR SELECT conta, classificacao, nomeconta, tipconta, GRUPOCONTA, bdrealizado,
                              formula, relconta
                       FROM vsuc_sp_retorna_saldo_orca(:bdcodemp, :prctaini, :prctafin, :prdatini, :prdatfin, :prIndice, :prignora_zeramento, :bdcodtpcc,
                                                       :bdcodplapadrao,:prniveisconta,0,:prcontabilizacao,:prmatrizfilialconsolidado)
                       INTO :wconta, :wctalon, :wnomcta, :wtipcta, :wgrpcta,
                            :wsaldorealizado, :wformula, :bdrelcta DO
                       BEGIN
                              bdcodcta = wconta;
                              bdctalon = wctalon;
                              bdnomcta = wnomcta;
                              bdtipcta = wtipcta;
                              bdgrpcta = wgrpcta;
                              bdformula = wformula;
                              bdsaldorealizado = :wsaldorealizado;

                         SUSPEND;
                            END
                            END
                       END
                 END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_RELESTATIST_GRA */
ALTER PROCEDURE VSUC_SP_RETORNA_RELESTATIST_GRA(PRCODEMP VARCHAR(10000),
PRCODUSU INTEGER,
PRTIPCOMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDTIPO VARCHAR(20),
BDMES VARCHAR(8),
BDMESVALOR INTEGER,
BDCOLOR VARCHAR(10))
 AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WSQLLANC VARCHAR(10480);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WQTDLINHA INTEGER;
DECLARE VARIABLE WQTDDEB INTEGER;
DECLARE VARIABLE WQTDCRE INTEGER;
DECLARE VARIABLE WQTGER INTEGER;
DECLARE VARIABLE WTOTAL INTEGER;
DECLARE VARIABLE WDATA_INICIAL DATE;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WTOTALLINHA1 INTEGER;
DECLARE VARIABLE WTOTALLINHA2 INTEGER;
DECLARE VARIABLE WTOTALLINHA3 INTEGER;
DECLARE VARIABLE WTOTALLINHA4 INTEGER;
DECLARE VARIABLE WCODEPMANT INTEGER;
DECLARE VARIABLE WNOMEMPANT VARCHAR(100);
DECLARE VARIABLE WCNPJANT VARCHAR(20);
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WCODEMPAUX INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WQTDDAUX INTEGER;
DECLARE VARIABLE WQTDCAUX INTEGER;
DECLARE VARIABLE WQTDLINHAAUX INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- mensal ____________________________________________________________________
  IF (prtipcomp = 0) THEN
     BEGIN
       wtotal = 0;
       wdata_inicial = prdataini;
       WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatafim FROM 1 FOR 4)||SUBSTRING(prdatafim FROM 6 FOR 2) AS INTEGER)) DO
         BEGIN
           wtotal = wtotal + 1;
           wdata_inicial = addmonth(prdataini, wtotal);
         END
     END
  ELSE
  -- anual _____________________________________________________________________
     BEGIN
       wtotal = (CAST(SUBSTRING(prdatafim FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdataini FROM 1 FOR 4) AS INTEGER)) +1;
       IF (wtotal = 0) THEN
          wtotal = 1;
     END

  wsql = 'select distinct(temp.bdcodemp), tref.bdnomemp, temp.bdcnpjemp ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  IF (prcodemp IS NOT NULL) THEN
     wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';

  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc';
  -- executa o sql das empresas
  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdnomemp, :bdcnpjemp  DO
      BEGIN
        wtotallinha1 = 0;
        wtotallinha2 = 0;
        wtotallinha3 = 0;
        wtotallinha4 = 0;
        BDCOLOR = 0;

        wcount = 1;
        WHILE (wcount-1 < wtotal) DO
          BEGIN
            -- mensal ________________________________________________________
            IF (prtipcomp = 0) THEN
              BEGIN
                wdata_inicial = addmonth(prdataini, wcount-1);
                wdata_final   = addmonth(prdataini, wcount)-1;
              END
            ELSE
           -- anual _________________________________________________________
              BEGIN
                wdata_inicial = addyear(prdataini, wcount-1);
                wdata_final   = addyear(prdataini, wcount)-1;
              END

            --#alt:5837.
            /*wSqllanc =  'select count (bdchave) totlanclinha , count(bddebito) linhadeb, count(bdcredito) linhacre from vsuc_empresas_tlan LAN ' ||
                        ' where bdcodemp = ' || :bdcodemp;
            if (prcodusu > 0) then
            wSqllanc =  'select count (bdchave) totlanclinha , count(bddebito) linhadeb, count(bdcredito) linhacre from vsuc_empresas_tlan LAN ' ||
                        ' where bdcodemp = ' || :bdcodemp || ' and bdcodusu = ' || prcodusu;*/
            wSqllanc = 'Select bdcodemp,COUNT(bdchave) totlanclinha,COUNT(bddebito) linhadeb,COUNT(bdcredito) linhacre from vsuc_empresas_tlan LAN ';
            IF (prcodusu > 0) THEN
              wSqllanc = wSqllanc||' where (bdcodemp = '||:bdcodemp||') and bdcodusu = ' || prcodusu;
            ELSE
              wSqllanc = wSqllanc||' where (bdcodemp = '||:bdcodemp||')';
            --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
            IF (prcontabilizacao <> 99) THEN
              wSqllanc = wSqllanc||' and (bdcontabilizacao in (0,'||prcontabilizacao||'))';

            IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
               wsqllanc = wsqllanc ||' and (BDDATA between '''||wdata_inicial||''' and '''||wdata_final||''') ';

            IF ((prwhere IS NOT NULL) AND (prwhere <> '')) THEN
               wsqllanc = wsqllanc || ' and  ' || prwhere;
            wsqllanc = wsqllanc||' Group by bdcodemp';
            --#alt:5837.
            /*for execute statement wsqllanc into :wqtdlinha, :WQTDDEB, :WQTDCRE   do
               begin
                 wqtger = WQTDDEB + WQTDCRE;
               end*/
            wqtddeb   = 0;
            wqtdcre   = 0;
            wqtdlinha = 0;
            FOR EXECUTE STATEMENT wsqllanc INTO :wcodempaux,:wqtdlinhaaux,:wqtddaux,:wqtdcaux DO
              BEGIN
                --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:bdcodemp,:wcodempaux,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
                --IF (wpermite = 1) THEN
                  wqtddeb = wqtddeb + wqtddaux;

                --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:bdcodemp,:wcodempaux,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
                --IF (wpermite = 1) THEN
                  wqtdcre = wqtdcre + wqtdcaux;

                wqtdlinha = wqtdlinha + wqtdlinhaaux;
              END
            wqtger = wqtddeb + wqtdcre;

            IF (WQTDDEB IS NULL) THEN
              WQTDDEB = 0;
            IF (WQTDCRE IS NULL) THEN
              WQTDCRE = 0;
            IF (wqtger IS NULL) THEN
              wqtger = 0;

            bdmes = '';
            bdmesvalor = 0;

            IF (wcount = 1) THEN
               BDCOLOR = 'clRed';
            ELSE
            IF (wcount = 2) THEN
               BDCOLOR = 'clBlue';
            ELSE
            IF (wcount = 3) THEN
               BDCOLOR = 'clMaroon';
            ELSE
            IF (wcount = 4) THEN
               BDCOLOR = 'clYellow';
            ELSE
            IF (wcount = 5) THEN
               BDCOLOR = 'clNavy';
            ELSE
            IF (wcount = 6) THEN
               BDCOLOR = 'clLime';
            ELSE
            IF (wcount = 7) THEN
               BDCOLOR = 'clBlack';
            ELSE
            IF (wcount = 8) THEN
               BDCOLOR = 'clFuchsia';
            ELSE
            IF (wcount = 9) THEN
               BDCOLOR = 'clAqua';
            ELSE
            IF (wcount = 10) THEN
               BDCOLOR = 'clSkyBlue';
            ELSE
            IF (wcount = 11) THEN
               BDCOLOR = 'cl3DLight';
            ELSE
            IF (wcount = 12) THEN
               BDCOLOR = 'clOlive';

            wcount = wcount + 1;
            bdmesvalor =wqtdlinha;
            IF (prtipcomp <= 0) THEN
               bdmes = SUBSTRING(CAST(wdata_inicial AS VARCHAR(10)) FROM 6 FOR 2)||'/'|| SUBSTRING(CAST(wdata_inicial AS VARCHAR(10)) FROM 1 FOR 4);
            ELSE
               bdmes = SUBSTRING(CAST(wdata_inicial AS VARCHAR(10)) FROM 1 FOR 4);

            SUSPEND;
          END
      END
END
^

/* Restore proc. body: VSUC_SP_RETORNA_RELESTATISTGRA */
ALTER PROCEDURE VSUC_SP_RETORNA_RELESTATISTGRA(PRCODEMP VARCHAR(2048),
PRTIPCOMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDTIPO VARCHAR(20),
BDMES01 INTEGER,
BDMES02 INTEGER,
BDMES03 INTEGER,
BDMES04 INTEGER,
BDMES05 INTEGER,
BDMES06 INTEGER,
BDMES07 INTEGER,
BDMES08 INTEGER,
BDMES09 INTEGER,
BDMES10 INTEGER,
BDMES11 INTEGER,
BDMES12 INTEGER,
BDTOTAL INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WSQLLANC VARCHAR(10480);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WQTDLINHA INTEGER;
DECLARE VARIABLE WQTDDEB INTEGER;
DECLARE VARIABLE WQTDCRE INTEGER;
DECLARE VARIABLE WQTGER INTEGER;
DECLARE VARIABLE WTOTAL INTEGER;
DECLARE VARIABLE WDATA_INICIAL DATE;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WTOTALLINHA1 INTEGER;
DECLARE VARIABLE WTOTALLINHA2 INTEGER;
DECLARE VARIABLE WTOTALLINHA3 INTEGER;
DECLARE VARIABLE WTOTALLINHA4 INTEGER;
DECLARE VARIABLE WCODEPMANT INTEGER;
DECLARE VARIABLE WNOMEMPANT VARCHAR(100);
DECLARE VARIABLE WCNPJANT VARCHAR(20);
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WCODEMPAUX INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WQTDDAUX INTEGER;
DECLARE VARIABLE WQTDCAUX INTEGER;
DECLARE VARIABLE WQTDLINHAAUX INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- mensal ____________________________________________________________________
  IF (prtipcomp = 0) THEN
     BEGIN
       wtotal = 0;
       wdata_inicial = prdataini;
       WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatafim FROM 1 FOR 4)||SUBSTRING(prdatafim FROM 6 FOR 2) AS INTEGER)) DO
         BEGIN
           wtotal = wtotal + 1;
           wdata_inicial = addmonth(prdataini, wtotal);
         END
     END
  ELSE
  -- anual _____________________________________________________________________
     BEGIN
       wtotal = (CAST(SUBSTRING(prdatafim FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdataini FROM 1 FOR 4) AS INTEGER)) +1;
       IF (wtotal = 0) THEN
          wtotal = 1;
     END

  wsql = 'select distinct(temp.bdcodemp), tref.bdnomemp, temp.bdcnpjemp ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  IF (prcodemp IS NOT NULL) THEN
     wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';

  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc';
  -- executa o sql das empresas
  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdnomemp, :bdcnpjemp  DO
      BEGIN
        bdtotal = 0;
        wtotallinha1 = 0;
        wtotallinha2 = 0;
        wtotallinha3 = 0;
        wtotallinha4 = 0;

        wcount = 1;
        WHILE (wcount-1 < wtotal) DO
          BEGIN
            -- mensal ________________________________________________________
            IF (prtipcomp = 0) THEN
              BEGIN
                wdata_inicial = addmonth(prdataini, wcount-1);
                wdata_final   = addmonth(prdataini, wcount)-1;
              END
            ELSE
           -- anual _________________________________________________________
              BEGIN
                wdata_inicial = addyear(prdataini, wcount-1);
                wdata_final   = addyear(prdataini, wcount)-1;
              END
            --#alt:5837.
            /*wSqllanc =  'select count (bdchave) totlanclinha , count(bddebito) linhadeb, count(bdcredito) linhacre from vsuc_empresas_tlan LAN ' ||
                        ' where bdcodemp = ' || :bdcodemp;*/
            wSqllanc = 'Select bdcodemp,COUNT(bdchave) totlanclinha,COUNT(bddebito) linhadeb,COUNT(bdcredito) linhacre from vsuc_empresas_tlan LAN ' ||
                       'where (bdcodemp = '||:bdcodemp||')';
            --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
            IF (prcontabilizacao <> 99) THEN
              wSqllanc = wSqllanc||' and (bdcontabilizacao in (0,'||prcontabilizacao||'))';

            IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
               wsqllanc = wsqllanc ||' and (BDDATA between '''||wdata_inicial||''' and '''||wdata_final||''') ';

            IF ((prwhere IS NOT NULL) AND (prwhere <> '')) THEN
               wsqllanc = wsqllanc || ' and  ' || prwhere;
            wsqllanc = wsqllanc||' Group by bdcodemp';
            --#alt:5837.
            /*for execute statement wsqllanc into :wqtdlinha, :WQTDDEB, :WQTDCRE   do
               begin
                 wqtger = WQTDDEB + WQTDCRE;
               end*/
            wqtddeb   = 0;
            wqtdcre   = 0;
            wqtdlinha = 0;
            FOR EXECUTE STATEMENT wsqllanc INTO :wcodempaux,:wqtdlinhaaux,:wqtddaux,:wqtdcaux DO
              BEGIN
               -- SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:bdcodemp,:wcodempaux,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
               -- IF (wpermite = 1) THEN
                  wqtddeb = wqtddeb + wqtddaux;

               -- SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:bdcodemp,:wcodempaux,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
               -- IF (wpermite = 1) THEN
                  wqtdcre = wqtdcre + wqtdcaux;

                wqtdlinha = wqtdlinha + wqtdlinhaaux;
              END
            wqtger = wqtddeb + wqtdcre;

            IF (WQTDDEB IS NULL) THEN
               WQTDDEB = 0;
            IF (WQTDCRE IS NULL) THEN
               WQTDCRE = 0;
            IF (wqtger IS NULL) THEN
               wqtger = 0;

            bdmes01 = 0;
            bdmes02 = 0;
            bdmes03 = 0;
            bdmes04 = 0;
            bdmes05 = 0;
            bdmes06 = 0;
            bdmes07 = 0;
            bdmes08 = 0;
            bdmes09 = 0;
            bdmes10 = 0;
            bdmes11 = 0;
            bdmes12 = 0;

            IF (wcount = 1) THEN
              BEGIN
                bdtipo = 1;
                bdmes01 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes01 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes01 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes01 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes01 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes01 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes01 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;
                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes01 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */
              END
            ELSE
            IF (wcount = 2) THEN
              BEGIN
                bdtipo = 1;
                bdmes02 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes02 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes02 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes02 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes02 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes02 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes02 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes02 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 3) THEN
              BEGIN
                bdtipo = 1;
                bdmes03 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes03 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes03 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes03 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes03 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes03 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes03 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes03 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 4) THEN
              BEGIN
                bdtipo = 1;
                bdmes04 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes04 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes04 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes04 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes04 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes04 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes04 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes04 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 5) THEN
              BEGIN
                bdtipo = 1;
                bdmes05 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes05 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes05 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes05 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes05 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes05 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes05 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes05 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 6) THEN
              BEGIN
                bdtipo = 1;
                bdmes06 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes06 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes06 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes06 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes06 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes06 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes06 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes06 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 7) THEN
              BEGIN
                bdtipo = 1;
                bdmes07 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes07 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes07 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes07 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes07 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes07 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes07 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes07 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 8) THEN
              BEGIN
                bdtipo = 1;
                bdmes08 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes08 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes08 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes08 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes08 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes08 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes08 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes08 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 9) THEN
              BEGIN
                bdtipo = 1;
                bdmes09 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes09 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes09 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes09 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes09 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes09 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes09 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes09 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 10) THEN
              BEGIN
                bdtipo = 1;
                bdmes10 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes10 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes10 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes10 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes10 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes10 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes10 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes10 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 11) THEN
              BEGIN
                bdtipo = 1;
                bdmes11 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes11 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes11 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes11 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes11 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes11 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes11 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes11 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END
            ELSE
            IF (wcount = 12) THEN
              BEGIN
                bdtipo = 1;
                bdmes12 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes12 = wqtdlinha;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 2;
                bdmes12 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes12 = wqtddeb;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 3;
                bdmes12 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes12 = wqtdcre;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

                bdtipo = 4;
                bdmes12 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;
                SUSPEND;

                /* inicio total geral */
                wcodepmant = bdcodemp;
                wnomempant = bdnomemp;
                wcnpjant = bdcnpjemp;

                bdcodemp = 1000000000;
                bdnomemp = 'TOTAL GERAL';
                bdcnpjemp = '';
                bdmes12 = wqtger;

                SUSPEND;

                bdcodemp = wcodepmant;
                bdnomemp = wnomempant;
                bdcnpjemp = wcnpjant;

                /* final todal geral */

              END

            wcount = wcount + 1;
          END
      END

END
^

/* Restore proc. body: VSUC_SP_RETORNA_RELESTATISTICA */
ALTER PROCEDURE VSUC_SP_RETORNA_RELESTATISTICA(PRCODEMP VARCHAR(10000),
PRCODUSU INTEGER,
PRTIPCOMP INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDTIPO VARCHAR(20),
BDMES01 INTEGER,
BDMES02 INTEGER,
BDMES03 INTEGER,
BDMES04 INTEGER,
BDMES05 INTEGER,
BDMES06 INTEGER,
BDMES07 INTEGER,
BDMES08 INTEGER,
BDMES09 INTEGER,
BDMES10 INTEGER,
BDMES11 INTEGER,
BDMES12 INTEGER,
BDTOTAL INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WSQLLANC VARCHAR(10480);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WQTDLINHA INTEGER;
DECLARE VARIABLE WQTDDEB INTEGER;
DECLARE VARIABLE WQTDCRE INTEGER;
DECLARE VARIABLE WQTGER INTEGER;
DECLARE VARIABLE WTOTAL INTEGER;
DECLARE VARIABLE WDATA_INICIAL DATE;
DECLARE VARIABLE WDATA_FINAL DATE;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WTOTALLINHA1 INTEGER;
DECLARE VARIABLE WTOTALLINHA2 INTEGER;
DECLARE VARIABLE WTOTALLINHA3 INTEGER;
DECLARE VARIABLE WTOTALLINHA4 INTEGER;
DECLARE VARIABLE WCODEPMANT INTEGER;
DECLARE VARIABLE WNOMEMPANT VARCHAR(100);
DECLARE VARIABLE WCNPJANT VARCHAR(20);
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WCODEMPAUX INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WQTDDAUX INTEGER;
DECLARE VARIABLE WQTDCAUX INTEGER;
DECLARE VARIABLE WQTDLINHAAUX INTEGER;
BEGIN

  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- mensal ____________________________________________________________________
  IF (prtipcomp = 0) THEN
     BEGIN
       wtotal = 0;
       wdata_inicial = prdataini;
       WHILE (CAST(SUBSTRING(wdata_inicial FROM 1 FOR 4)||SUBSTRING(wdata_inicial FROM 6 FOR 2) AS INTEGER) <= CAST(SUBSTRING(prdatafim FROM 1 FOR 4)||SUBSTRING(prdatafim FROM 6 FOR 2) AS INTEGER)) DO
         BEGIN
           wtotal = wtotal + 1;
           wdata_inicial = addmonth(prdataini, wtotal);
         END
     END
  ELSE
  -- anual _____________________________________________________________________
     BEGIN
       wtotal = (CAST(SUBSTRING(prdatafim FROM 1 FOR 4) AS INTEGER) - CAST(SUBSTRING(prdataini FROM 1 FOR 4) AS INTEGER)) +1;
       IF (wtotal = 0) THEN
          wtotal = 1;
     END

  wsql = 'select distinct(temp.bdcodemp), tref.bdnomemp, temp.bdcnpjemp ';
  wsql = wsql||'from tempresas temp ';
  wsql = wsql||'inner join vw_empresas_ref_atual tref on (tref.bdcodemp = temp.bdcodemp) ';
  IF (prcodemp IS NOT NULL) THEN
     wsql = wsql||'where temp.bdcodemp in ('||prcodemp||') ';

  wsql = wsql||'order by temp.bdcodmatriz asc, temp.bdcodemp asc';

  -- executa o sql das empresas
  FOR EXECUTE STATEMENT wsql
      INTO :bdcodemp, :bdnomemp, :bdcnpjemp  DO
      BEGIN
        bdtotal = 0;
        wtotallinha1 = 0;
        wtotallinha2 = 0;
        wtotallinha3 = 0;
        wtotallinha4 = 0;

        wcount = 1;
        WHILE (wcount-1 < wtotal) DO
          BEGIN
            -- mensal ________________________________________________________
            IF (prtipcomp = 0) THEN
              BEGIN
                wdata_inicial = addmonth(prdataini, wcount-1);
                wdata_final   = addmonth(prdataini, wcount)-1;
              END
            ELSE
           -- anual _________________________________________________________
              BEGIN
                wdata_inicial = addyear(prdataini, wcount-1);
                wdata_final   = addyear(prdataini, wcount)-1;
              END
            --#alt:5837.
            /*wSqllanc = 'select count (bdchave) totlanclinha , count(bddebito) linhadeb, count(bdcredito) linhacre from vsuc_empresas_tlan LAN ';
            if (prcodusu > 0) then
              wSqllanc = wSqllanc||' where bdcodemp = ' || :bdcodemp || ' and bdcodusu = ' || prcodusu;
            else
              wSqllanc = wSqllanc||' where bdcodemp = ' || :bdcodemp;*/
            wSqllanc = 'select bdcodemp, COUNT(bdchave) totlanclinha , COUNT(bddebito) linhadeb, COUNT(bdcredito) linhacre from vsuc_empresas_tlan LAN ';
            IF (prcodusu > 0) THEN
              wSqllanc = wSqllanc||' where (bdcodemp = '||:bdcodemp||') and bdcodusu = '|| prcodusu;
            ELSE
              wSqllanc = wSqllanc||' where (bdcodemp = '||:bdcodemp||')';
            --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
            IF (prcontabilizacao <> 99) THEN
              wSqllanc = wSqllanc||' and (bdcontabilizacao in (0,'||prcontabilizacao||'))';

            IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
               wsqllanc = wsqllanc ||' and (BDDATA between '''||wdata_inicial||''' and '''||wdata_final||''') ';

            IF ((prwhere IS NOT NULL) AND (prwhere <> '')) THEN
               wsqllanc = wsqllanc || ' and  ' || prwhere;
            wsqllanc = wsqllanc||' Group by bdcodemp';
            --#alt:5837.
            /*for execute statement wsqllanc into :wqtdlinha, :WQTDDEB, :WQTDCRE   do
              begin
                wqtger = WQTDDEB + WQTDCRE;
              end*/
            wqtddeb   = 0;
            wqtdcre   = 0;
            wqtdlinha = 0;
            FOR EXECUTE STATEMENT wsqllanc INTO :wcodempaux,:wqtdlinhaaux,:wqtddaux,:wqtdcaux DO
              BEGIN
                --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:bdcodemp,:wcodempaux,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
                --IF (wpermite = 1) THEN
                  wqtddeb = wqtddeb + wqtddaux;

                --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:bdcodemp,:wcodempaux,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
                --IF (wpermite = 1) THEN
                  wqtdcre = wqtdcre + wqtdcaux;

                wqtdlinha = wqtdlinha + wqtdlinhaaux;
              END
            wqtger = wqtddeb + wqtdcre;

            IF (WQTDDEB IS NULL) THEN
               WQTDDEB = 0;
            IF (WQTDCRE IS NULL) THEN
               WQTDCRE = 0;
            IF (wqtger IS NULL) THEN
               wqtger = 0;

            bdmes01 = 0;
            bdmes02 = 0;
            bdmes03 = 0;
            bdmes04 = 0;
            bdmes05 = 0;
            bdmes06 = 0;
            bdmes07 = 0;
            bdmes08 = 0;
            bdmes09 = 0;
            bdmes10 = 0;
            bdmes11 = 0;
            bdmes12 = 0;

            IF (wcount = 1) THEN
              BEGIN
                bdtipo = 1;
                bdmes01 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;




                bdtipo = 2;
                bdmes01 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                bdtipo = 3;
                bdmes01 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;
                SUSPEND;

                bdtipo = 4;
                bdmes01 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;
              END
            ELSE
            IF (wcount = 2) THEN
              BEGIN
                bdtipo = 1;
                bdmes02 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                bdtipo = 2;
                bdmes02 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                bdtipo = 3;
                bdmes02 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;
                SUSPEND;

                bdtipo = 4;
                bdmes02 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;
              END
            ELSE
            IF (wcount = 3) THEN
              BEGIN
                bdtipo = 1;
                bdmes03 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                bdtipo = 2;
                bdmes03 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                bdtipo = 3;
                bdmes03 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                bdtipo = 4;
                bdmes03 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

              END
            ELSE
            IF (wcount = 4) THEN
              BEGIN
                bdtipo = 1;
                bdmes04 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                bdtipo = 2;
                bdmes04 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                bdtipo = 3;
                bdmes04 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;


                bdtipo = 4;
                bdmes04 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

              END
            ELSE
            IF (wcount = 5) THEN
              BEGIN
                bdtipo = 1;
                bdmes05 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                bdtipo = 2;
                bdmes05 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                bdtipo = 3;
                bdmes05 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;


                bdtipo = 4;
                bdmes05 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;


              END
            ELSE
            IF (wcount = 6) THEN
              BEGIN
                bdtipo = 1;
                bdmes06 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                bdtipo = 2;
                bdmes06 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                bdtipo = 3;
                bdmes06 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                bdtipo = 4;
                bdmes06 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

              END
            ELSE
            IF (wcount = 7) THEN
              BEGIN
                bdtipo = 1;
                bdmes07 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                bdtipo = 2;
                bdmes07 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                bdtipo = 3;
                bdmes07 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;
                SUSPEND;



                bdtipo = 4;
                bdmes07 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;



              END
            ELSE
            IF (wcount = 8) THEN
              BEGIN
                bdtipo = 1;
                bdmes08 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;



                bdtipo = 2;
                bdmes08 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;



                bdtipo = 3;
                bdmes08 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;



                bdtipo = 4;
                bdmes08 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

              END
            ELSE
            IF (wcount = 9) THEN
              BEGIN
                bdtipo = 1;
                bdmes09 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;



                bdtipo = 2;
                bdmes09 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;


                bdtipo = 3;
                bdmes09 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;


                bdtipo = 4;
                bdmes09 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;


              END
            ELSE
            IF (wcount = 10) THEN
              BEGIN
                bdtipo = 1;
                bdmes10 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;



                bdtipo = 2;
                bdmes10 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;


                bdtipo = 3;
                bdmes10 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;



                bdtipo = 4;
                bdmes10 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;


              END
            ELSE
            IF (wcount = 11) THEN
              BEGIN
                bdtipo = 1;
                bdmes11 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                bdtipo = 2;
                bdmes11 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                bdtipo = 3;
                bdmes11 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;

                SUSPEND;

                bdtipo = 4;
                bdmes11 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;

                SUSPEND;

              END
            ELSE
            IF (wcount = 12) THEN
              BEGIN
                bdtipo = 1;
                bdmes12 = wqtdlinha;
                wTotalLinha1 = wTotalLinha1 + wqtdlinha;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha1;
                SUSPEND;

                bdtipo = 2;
                bdmes12 = WQTDDEB;
                wTotalLinha2 = wTotalLinha2 + WQTDDEB;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha2;
                SUSPEND;

                bdtipo = 3;
                bdmes12 = WQTDCRE;
                wTotalLinha3 = wTotalLinha3 + wqtdcre;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha3;
                SUSPEND;

                bdtipo = 4;
                bdmes12 = wqtger;
                wTotalLinha4 = wTotalLinha4 + wqtger;
                IF (wcount = wTotal) THEN
                   bdtotal = wtotallinha4;
                SUSPEND;

              END

            wcount = wcount + 1;
          END
      END

END
^

/* Restore proc. body: VSUC_SP_RETORNA_SALDO */
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO (
    PRCODEMP VARCHAR(1024),
    PRCONTA INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRIGNORAZERAMENTO SMALLINT,
    PRCC INTEGER,
    PRRELCTA INTEGER,
    PRREFEMP INTEGER,
    PRFORM VARCHAR(10),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER)
RETURNS (
    MOVIMENTO_ANT_CRE NUMERIC(15,2),
    SALDO_ANT_DEB NUMERIC(15,2),
    SALDO_ANT_CRE NUMERIC(15,2),
    SALDO_DEB NUMERIC(15,2),
    SALDO_CRE NUMERIC(15,2),
    SALDO_ATUAL NUMERIC(15,2),
    SALDO_ANTERIOR NUMERIC(15,2),
    MOVIMENTO_ANT_DEB NUMERIC(15,2),
    SALDO_MOVIMENTO NUMERIC(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WTEMCC SMALLINT = 0;
DECLARE VARIABLE WTAMANHO INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(50);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WGRUPOCTA INTEGER;
DECLARE VARIABLE WDEBITO NUMERIC(15,2);
DECLARE VARIABLE WCREDITO NUMERIC(15,2);
DECLARE VARIABLE WLEVEL INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WVLR NUMERIC(15,2);
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WREFATUAL INTEGER;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WNOVADATA DATE;
BEGIN
  SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database INTO :wrefatual;
  EXECUTE PROCEDURE sp_seta_competencia(:prrefemp);

  --alt:10666 - Adicionado select para retornar a empresa matriz (selecionando v??rias) ou ela mesma caso
  wsql = 'select first 1 coalesce(BDCODMATRIZ, BDCODEMP) from TEMPRESAS where BDCODEMP in ('||:prcodemp||')';
  EXECUTE STATEMENT wsql INTO :WCODMATRIZ;

  -- pega a classificacao da conta passada por parametro (prconta) _____________
  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta, planos_tpla.bdcodplapadrao
  FROM PLANOS_TPLA
  WHERE planos_tpla.bdcodtpla = :prconta
  AND planos_tpla.bdcodplapadrao = (SELECT FIRST 1 tref.bdcodplapadrao
                                    FROM vw_empresas_ref_atual tref
                                    --WHERE tref.bdcodemp = :prcodemp)
                                    --alt:10666 - Alterado para pegar o c??digo do select e n??o do par??metro, que agora pode ser uma lista de empresas. Pedro
                                    WHERE tref.bdcodemp = :wcodmatriz)
--                                    from tempresas_ref tref
--                                    where tref.bdcodemp = :prcodemp
--                                    and tref.bdrefemp <= :prrefemp
--                                    order by tref.bdrefemp desc)
  INTO :wclassificacao, :wgrupocta, :wcodplapadrao;

  EXECUTE PROCEDURE sp_seta_competencia(:wrefatual);

  wtamanho = strlen(wclassificacao);

  -- retorna o nivel da conta para calcular ou nao as contas descendentes ______
  wsql = '';
  wsql = wsql||'select count(tpla.bdcodtpla) from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||wcodplapadrao;
  wsql = wsql||'and substring(tpla.bdctalon from 1 for '||wtamanho||') = '''||wclassificacao||''' ';
  EXECUTE STATEMENT wsql INTO :wlevel;

  -- configura datas para serem usadas no sql __________________________________
  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  -- SALDO A DEBITO ____________________________________________________________
  SALDO_DEB = 0;
  --#alt:5837.
  /*-- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
            join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT E FEITO PARA QUANDO NAO TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN '; */
  wsql = 'Select tlan.bdcodemp,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT E FEITO PARA QUANDO NAO TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END

--  if (Trim(prform) <> '') then
--     wsql = wsql||'inner join vsuc_empresas_tlanform tform on (tform.bdcodemp = tlan.bdcodemp and tform.bdchave = tlan.bdchave) ';
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||wcodplapadrao||') ';  --alt:7040 - Colocado o BDCODEMP para o final e o "+0", para melhoria de performance. Pedro
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ??rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
     wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lancamento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

--  if (Trim(prform) <> '') then
--     wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''' or tlan.'||prform||' <> '''||'0'||''')';

  IF (TRIM(prform) <> '') THEN
     wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''')';

  --wsql = wsql||'and ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';  --alt:7040 - Colocado o BDCODEMP para o final e o "+0", para melhoria de performance. Pedro
  wsql = wsql||'and (tlan.bdcodemp in ('||prcodemp||')) ';  --alt:10666 - Trocado para "in" para aceitar multiplas empresas. Pedro
  wsql = wsql||' group by tlan.bdcodemp';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_DEB do
    if (SALDO_DEB is null) then
      SALDO_DEB=0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      --alt:10666 - Trocado do par??metro de empresa para o c??digo da matriz, pois agora o par??metro pode ser uma lista de empresas. Pedro
      --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:WCODMATRIZ,:wcodemp,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      --IF (wpermite = 1) THEN
        SALDO_DEB = SALDO_DEB + wvlr;
    END

  -- SALDO A CREDITO ___________________________________________________________
  SALDO_CRE = 0;
  --#alt:5837.
  /*-- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT E FEITO PARA QUANDO NAO TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT E FEITO PARA QUANDO NAO TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END

--  if (Trim(prform) <> '') then
--     wsql = wsql||'inner join vsuc_empresas_tlanform tform on (tform.bdcodemp = tlan.bdcodemp and tform.bdchave = tlan.bdchave) ';
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||wcodplapadrao||') ';  --alt:7040 - Colocado o BDCODEMP para o final e o "+0", para melhoria de performance. Pedro
  wsql = wsql||'and (TLAN.BDDATA BETWEEN '''||wdatini||''' AND '''||wdatfin||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ??rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lancamento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

--  if (Trim(prform) <> '') then
--     wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''' or tlan.'||prform||' <> '''||'0'||''')';
  IF (TRIM(prform) <> '') THEN
    wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''')';

  --wsql = wsql||'and ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';  --alt:7040 - Colocado o BDCODEMP para o final e o "+0", para melhoria de performance. Pedro
  wsql = wsql||'and (tlan.bdcodemp in ('||prcodemp||')) ';  --alt:10666 - Trocado para "in" para aceitar multiplas empresas. Pedro
  wsql = wsql||' group by tlan.bdcodemp';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_CRE do
    if (SALDO_CRE is null) then
      SALDO_CRE=0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      --alt:10666 - Trocado do par??metro de empresa para o c??digo da matriz, pois agora o par??metro pode ser uma lista de empresas. Pedro
      --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:WCODMATRIZ,:wcodemp,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      --IF (wpermite = 1) THEN
        SALDO_CRE = SALDO_CRE + wvlr;
    END

  -- SALDO ANTERIOR A DEBITO _________________________________________________
  SALDO_ANT_DEB = 0;
  --#alt:5837.
  /*-- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT E FEITO PARA QUANDO NAO TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN '; */
  wsql = 'Select tlan.bdcodemp,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT E FEITO PARA QUANDO NAO TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END

--  if (Trim(prform) <> '') then
--     wsql = wsql||'inner join vsuc_empresas_tlanform tform on (tform.bdcodemp = tlan.bdcodemp and tform.bdchave = tlan.bdchave) ';
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||wcodplapadrao||') ';  --alt:7040 - Colocado o BDCODEMP para o final e o "+0", para melhoria de performance. Pedro
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ??rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bddebito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lancamento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

--  if (Trim(prform) <> '') then
--     wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''' or tlan.'||prform||' <> '''||'0'||''')';
  IF (TRIM(prform) <> '') THEN
     wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''')';

  --wsql = wsql||'and ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';  --alt:7040 - Colocado o BDCODEMP para o final e o "+0", para melhoria de performance. Pedro
  wsql = wsql||'and (tlan.bdcodemp in ('||prcodemp||')) ';  --alt:10666 - Trocado para "in" para aceitar multiplas empresas. Pedro
  wsql = wsql||' group by tlan.bdcodemp';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_ANT_DEB do
    if (SALDO_ANT_DEB is null) then
      SALDO_ANT_DEB=0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      --alt:10666 - Trocado do par??metro de empresa para o c??digo da matriz, pois agora o par??metro pode ser uma lista de empresas. Pedro
      --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:WCODMATRIZ,:wcodemp,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      --IF (wpermite = 1) THEN
        SALDO_ANT_DEB = SALDO_ANT_DEB + wvlr;
    END

  -- SALDO ANTERIOR A CREDITO __________________________________________________
  SALDO_ANT_CRE = 0;
  --#alt:5837.
  /*-- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
  if ((prcc <> 0) and (not (prcc is null))) then
     wsql = 'SELECT SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC
             join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  else
     -- ESTE SELECT E FEITO PARA QUANDO NAO TENHA CENTRO DE CUSTOS
     wsql = 'SELECT coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';*/
  wsql = 'Select tlan.bdcodemp,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
     wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE -- ESTE SELECT E FEITO PARA QUANDO NAO TENHA CENTRO DE CUSTOS
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bdcredito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END


  --alt:10666 - Teste da solicita????o.

--  if (Trim(prform) <> '') then
--     wsql = wsql||'inner join vsuc_empresas_tlanform tform on (tform.bdcodemp = tlan.bdcodemp and tform.bdchave = tlan.bdchave) ';
  --#alt:5837.
  --wsql = wsql||'where (tlan.bdcodemp = '||prcodemp||') ';
  wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||wcodplapadrao||') ';  --alt:7040 - Colocado o BDCODEMP para o final e o "+0", para melhoria de performance. Pedro
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societ??rio | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and (tlan.bdcredito = '||prconta||') ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lancamento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';

--  if (Trim(prform) <> '') then
--     wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''' or tlan.'||prform||' <> '''||'0'||''')';
  IF (TRIM(prform) <> '') THEN
     wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''')';

  --wsql = wsql||'and ((tlan.bdcodemp = '||prcodemp||') or (bdfilial = '||prcodemp||')) ';  --alt:7040 - Colocado o BDCODEMP para o final e o "+0", para melhoria de performance. Pedro
  wsql = wsql||' and (tlan.bdcodemp in ('||prcodemp||')) '; --alt:10666 - Trocado para "in" para aceitar multiplas empresas. Pedro
  wsql = wsql||' group by tlan.bdcodemp';
  --#alt:5837.
  /*for execute statement wSQL into :SALDO_ANT_CRE do
    if (SALDO_ANT_CRE is null) then
      SALDO_ANT_CRE=0;*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
      --alt:10666 - Trocado do par??metro de empresa para o c??digo da matriz, pois agora o par??metro pode ser uma lista de empresas. Pedro
      --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:WCODMATRIZ,:wcodemp,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
      --IF (wpermite = 1) THEN
        SALDO_ANT_CRE = SALDO_ANT_CRE + wvlr;
    END

  -- MOVIMENTO ANTERIOR A CREDITO
  MOVIMENTO_ANT_CRE = 0;
  wsql = 'Select tlan.bdcodemp,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.BDCREDITO) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END

  wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  wano = CAST(SUBSTRING(CAST(wdatini AS VARCHAR(10)) FROM 7 FOR 9) AS INTEGER);
  wano = wano - 1;
  wnovadata = CAST('01'||'-01-'||wano AS DATE);
  wsql = wsql||'and (TLAN.BDDATA >= '''||wnovadata||''') ';

  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and ((tlan.bdcredito = '||prconta||')) ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lancamento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';


  IF (TRIM(prform) <> '') THEN
     wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''')';


  wsql = wsql||'and (tlan.bdcodemp in ('||prcodemp||')) ';
  wsql = wsql||' group by tlan.bdcodemp';

  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
        MOVIMENTO_ANT_CRE = MOVIMENTO_ANT_CRE + wvlr;
    END

  -- MOVIMENTO ANTERIOR A DEBITO
  MOVIMENTO_ANT_DEB = 0;
  wsql = 'Select tlan.bdcodemp,';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN -- ESTE SELECT E FEITO PARA QUANDO TENHA CENTRO DE CUSTOS
    wsql = wsql||'SUM(TLCC.BDVALOR) AS SOMA FROM VSUC_EMPRESAS_TLCC TLCC join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
  ELSE
    wsql = wsql||'coalesce(sum(tlan.bdvalor),0) AS SOMA FROM VSUC_EMPRESAS_TLAN TLAN ';

  IF (wlevel > 1) THEN
    BEGIN
      wsql = wsql||'left outer join planos_tpla TPLA on ((tpla.bdcodplapadrao = tlan.bdcodplapadrao) and (tpla.bdcodtpla = tlan.bddebito) and ((tpla.bdtipcta = 1) or (tpla.bdtipcta is null))';
      IF (prrelcta IS NOT NULL) THEN
        wsql = wsql||' and (tpla.bdrelcta = '||prrelcta||')) ';
      ELSE
        wsql = wsql||') ';
    END

  wsql = wsql||'where (tlan.bdcodplapadrao+0 = '||wcodplapadrao||') ';
  wsql = wsql||'and (TLAN.BDDATA < '''||wdatini||''') ';
  wano = CAST(SUBSTRING(CAST(wdatini AS VARCHAR(10)) FROM 7 FOR 9) AS INTEGER);
  wano = wano - 1;
  wnovadata = CAST('01'||'-01-'||wano AS DATE);
  wsql = wsql||'and (TLAN.BDDATA >= '''||wnovadata||''') ';

  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF (wlevel = 1) THEN
    wsql = wsql||'and ((tlan.bddebito = '||prconta||')) ';
  ELSE
    wsql = wsql||'and (substring(tpla.BDCTALON FROM 1 FOR '||wtamanho||') = '''||wclassificacao||''') ';

  IF (prignorazeramento = 1) THEN
    wsql = wsql || 'AND ((TLAN.BDTIPOLAN <> 10) or (TLAN.BDTIPOLAN IS NULL))'; -- bdTIPOLAN = 10 > Lancamento de Zeramento

  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';


  IF (TRIM(prform) <> '') THEN
     wsql = wsql||'and (tlan.'||prform||' = '''||'TRUE'||''')';


  wsql = wsql||'and (tlan.bdcodemp in ('||prcodemp||')) ';
  wsql = wsql||' group by tlan.bdcodemp';

  FOR EXECUTE STATEMENT wSQL INTO :wcodemp,:wvlr DO
    BEGIN
      IF (wvlr IS NULL) THEN
        wvlr = 0;
        MOVIMENTO_ANT_DEB = MOVIMENTO_ANT_DEB + wvlr;
    END

  -- SALDO ANTERIOR ____________________________________________________________
  IF ((wgrupocta = 0) OR (wgrupocta = 4))  THEN -- ATIVO e DESPESAS
     SALDO_ANTERIOR = (SALDO_ANT_DEB-SALDO_ANT_CRE);
  ELSE
     IF ((wgrupocta = 1) OR (wgrupocta = 3) OR (wgrupocta = 5)) THEN -- PASSIVO e RECEITAS
        SALDO_ANTERIOR = (SALDO_ANT_CRE-SALDO_ANT_DEB);

  --SALDO_ATUAL = (SALDO_DEB-SALDO_CRE);
  IF ((wgrupocta = 0) OR (wgrupocta = 4))  THEN -- ATIVO e DESPESAS
    BEGIN
      saldo_atual = saldo_anterior + SALDO_DEB - SALDO_CRE;
      saldo_movimento = SALDO_DEB - SALDO_CRE;
    END
  ELSE
    BEGIN
       IF ((wgrupocta = 1) OR (wgrupocta = 3) OR (wgrupocta = 5)) THEN -- PASSIVO e RECEITAS
         BEGIN
           saldo_atual = saldo_anterior - SALDO_DEB + SALDO_CRE;
           saldo_movimento = SALDO_CRE - SALDO_DEB;
         END
    END

  SUSPEND;
END
^

/* Restore proc. body: VSUC_SP_RETORNA_SALDO_CONS_ORCA */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONS_ORCA(PRCODEMP INTEGER,
PRCONTA INTEGER,
PRCODTPCC INTEGER,
PRANO INTEGER,
PRREFEMP INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDSAL01 NUMERIC(15,2),
BDSAL02 NUMERIC(15,2),
BDSAL03 NUMERIC(15,2),
BDSAL04 NUMERIC(15,2),
BDSAL05 NUMERIC(15,2),
BDSAL06 NUMERIC(15,2),
BDSAL07 NUMERIC(15,2),
BDSAL08 NUMERIC(15,2),
BDSAL09 NUMERIC(15,2),
BDSAL10 NUMERIC(15,2),
BDSAL11 NUMERIC(15,2),
BDSAL12 NUMERIC(15,2))
 AS
DECLARE VARIABLE WDATAINI VARCHAR(10);
DECLARE VARIABLE WDATAFIM VARCHAR(10);
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WGRUPOCONTA INTEGER;
DECLARE VARIABLE WDATAREF VARCHAR(10);
DECLARE VARIABLE WDEB01 NUMERIC(15,2);
DECLARE VARIABLE WDEB02 NUMERIC(15,2);
DECLARE VARIABLE WDEB03 NUMERIC(15,2);
DECLARE VARIABLE WDEB04 NUMERIC(15,2);
DECLARE VARIABLE WDEB05 NUMERIC(15,2);
DECLARE VARIABLE WDEB06 NUMERIC(15,2);
DECLARE VARIABLE WDEB07 NUMERIC(15,2);
DECLARE VARIABLE WDEB08 NUMERIC(15,2);
DECLARE VARIABLE WDEB09 NUMERIC(15,2);
DECLARE VARIABLE WDEB10 NUMERIC(15,2);
DECLARE VARIABLE WDEB11 NUMERIC(15,2);
DECLARE VARIABLE WDEB12 NUMERIC(15,2);
DECLARE VARIABLE WCRE01 NUMERIC(15,2);
DECLARE VARIABLE WCRE02 NUMERIC(15,2);
DECLARE VARIABLE WCRE03 NUMERIC(15,2);
DECLARE VARIABLE WCRE04 NUMERIC(15,2);
DECLARE VARIABLE WCRE05 NUMERIC(15,2);
DECLARE VARIABLE WCRE06 NUMERIC(15,2);
DECLARE VARIABLE WCRE07 NUMERIC(15,2);
DECLARE VARIABLE WCRE08 NUMERIC(15,2);
DECLARE VARIABLE WCRE09 NUMERIC(15,2);
DECLARE VARIABLE WCRE10 NUMERIC(15,2);
DECLARE VARIABLE WCRE11 NUMERIC(15,2);
DECLARE VARIABLE WCRE12 NUMERIC(15,2);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
BEGIN
 wdataini = '01/'||'01/'||:prano;
 wdatafim = '12/'||'31/'||:prano;

 wgrupoconta = 0;

 SELECT bdgrupocta
 FROM PLANOS_TPLA
 WHERE bdCODPLAPADRAO = (SELECT FIRST 1 tref.bdcodplapadrao
                          FROM tempresas_ref tref
                          WHERE tref.bdcodemp = :prcodemp
                          AND tref.bdrefemp <= :prrefemp
                          ORDER BY tref.bdrefemp DESC)
 AND (bdCODTPLA = :prconta)
 INTO :wgrupoconta;

 bdsal01 = 0;
 bdsal02 = 0;
 bdsal03 = 0;
 bdsal04 = 0;
 bdsal05 = 0;
 bdsal06 = 0;
 bdsal07 = 0;
 bdsal08 = 0;
 bdsal09 = 0;
 bdsal10 = 0;
 bdsal11 = 0;
 bdsal12 = 0;
 wdeb01  = 0;
 wdeb02  = 0;
 wdeb03  = 0;
 wdeb04  = 0;
 wdeb05  = 0;
 wdeb06  = 0;
 wdeb07  = 0;
 wdeb08  = 0;
 wdeb09  = 0;
 wdeb10  = 0;
 wdeb11  = 0;
 wdeb12  = 0;
 wcre01  = 0;
 wcre02  = 0;
 wcre03  = 0;
 wcre04  = 0;
 wcre05  = 0;
 wcre06  = 0;
 wcre07  = 0;
 wcre08  = 0;
 wcre09  = 0;
 wcre10  = 0;
 wcre11  = 0;
 wcre12  = 0;

 /* saldo debito no periodo */
 IF ((prcodtpcc = 0) OR (prcodtpcc IS NULL)) THEN
   BEGIN
     wsql = '';
     --#alt:5837.
     --wsql = wsql || ' select substring(cast(BDDATA as varchar(10)) from 6 for 2) || substring(cast(BDDATA as varchar(10)) from 1 for 4) BDREF,' ;
     wsql = wsql || ' select bdcodemp,substring(cast(BDDATA as varchar(10)) from 6 for 2) || substring(cast(BDDATA as varchar(10)) from 1 for 4) BDREF,' ;
     wsql = wsql || ' SUM(bdvalor) BDVALDEB ';
     wsql = wsql || ' from vsuc_empresas_tlan LAN ';
     --wsql = wsql || ' where bdcodemp = ' || :prcodemp || 'AND (BDDEBITO = ' || :prconta || ' ) ';
     wsql = wsql || ' where ((bdcodemp = ' || :prcodemp || ')) AND (BDDEBITO = ' || :prconta || ' ) ';
     wsql = wsql || ' AND (BDDATA between ''' ||  wdataini || ''' and ''' ||  wdatafim || '''' || ')';
     --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
     IF (prcontabilizacao <> 99) THEN
       wsql = wsql || ' and (bdcontabilizacao in (0,'||prcontabilizacao||')) ';
     wsql = wsql || ' GROUP BY bdcodemp,bdref' ;
   END
 ELSE
   BEGIN
     wsql = '';
     --#alt:5837.
     --wsql = wsql || ' select substring(cast(BDDATA as varchar(10)) from 6 for 2) || substring(cast(BDDATA as varchar(10)) from 1 for 4) BDREF,' ;
     wsql = wsql || 'select TLAN.bdcodemp,substring(cast(BDDATA as varchar(10)) from 6 for 2) || substring(cast(BDDATA as varchar(10)) from 1 for 4) BDREF,' ;
     wsql = wsql || ' SUM(TLCC.BDVALOR) BDVALDEB ';
     wsql = wsql || ' from VSUC_EMPRESAS_TLCC tlcc ';
     wsql = wsql || ' join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
     --wsql = wsql || ' where tlan.bdcodemp = ' || :prcodemp || 'AND (tlan.BDDEBITO = ' || :prconta || ' ) ';
     wsql = wsql || ' where (tlan.bdcodemp = ' || :prcodemp || ') AND (tlan.BDDEBITO = ' || :prconta || ' ) ';
     wsql = wsql || ' and tlcc.BDCODTPCC = ' || :prcodtpcc || 'AND (tlcc.bddebcre = 0) ';
     wsql = wsql || ' AND (BDDATA between ''' ||  wdataini || ''' and ''' ||  wdatafim || '''' || ')';
     --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
     IF (prcontabilizacao <> 99) THEN
       wsql = wsql || ' and (bdcontabilizacao in (0,'||prcontabilizacao||')) ';
     wsql = wsql || ' GROUP BY TLAN.bdcodemp,bdref';
   END

 FOR EXECUTE STATEMENT wsql  INTO :wcodemp,:wdataref,:wvalor  DO
  BEGIN
    --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:wcodemp,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
    --IF (wpermite = 1) THEN
      --BEGIN
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '01') THEN
          wdeb01 = wdeb01 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '02') THEN
          wdeb02 = wdeb02 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '03') THEN
          wdeb03 = wdeb03 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '04') THEN
          wdeb04 = wdeb04 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '05') THEN
          wdeb05 = wdeb05 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '06') THEN
          wdeb06 = wdeb06 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '07') THEN
          wdeb07 = wdeb07 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '08') THEN
          wdeb08 = wdeb08 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '09') THEN
          wdeb09 = wdeb09 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '10') THEN
          wdeb10 = wdeb10 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '11') THEN
          wdeb11 = wdeb11 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '12') THEN
          wdeb12 = wdeb12 + wvalor;
      --END
      END

 /* saldo crédito no periodo */
 IF ((prcodtpcc = 0) OR (prcodtpcc IS NULL)) THEN
   BEGIN
     wsql = '';
     --#alt:5837.
     --wsql = wsql || ' select substring(cast(BDDATA as varchar(10)) from 6 for 2) || substring(cast(BDDATA as varchar(10)) from 1 for 4) BDREF,' ;
     wsql = wsql || 'Select bdcodemp,substring(cast(BDDATA as varchar(10)) from 6 for 2) || substring(cast(BDDATA as varchar(10)) from 1 for 4) BDREF,' ;
     wsql = wsql || ' SUM(bdvalor) BDVALCRE ';
     wsql = wsql || ' from vsuc_empresas_tlan LAN ';
     --wsql = wsql || ' where bdcodemp = ' || :prcodemp || 'AND (BDCREDITO = ' || :prconta || ' ) ';
     wsql = wsql || ' where (bdcodemp = ' || :prcodemp || ') AND (BDCREDITO = ' || :prconta || ' ) ';
     wsql = wsql || ' AND (BDDATA between ''' ||  wdataini || ''' and ''' ||  wdatafim || '''' || ')';
     --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
     IF (prcontabilizacao <> 99) THEN
       wsql = wsql || ' and (bdcontabilizacao in (0,'||prcontabilizacao||')) ';
     wsql = wsql || ' GROUP BY bdcodemp,bdref' ;
   END
 ELSE
   BEGIN
     wsql = '';
     --#alt:5837.
     --wsql = wsql || ' select substring(cast(BDDATA as varchar(10)) from 6 for 2) || substring(cast(BDDATA as varchar(10)) from 1 for 4) BDREF,' ;
     wsql = wsql || ' select TLAN.bdcodemp,substring(cast(BDDATA as varchar(10)) from 6 for 2) || substring(cast(BDDATA as varchar(10)) from 1 for 4) BDREF,' ;
     wsql = wsql || ' SUM(TLCC.BDVALOR) BDVALCRE ';
     wsql = wsql || ' from VSUC_EMPRESAS_TLCC tlcc ';
     wsql = wsql || ' join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
     --wsql = wsql || ' where tlan.bdcodemp = ' || :prcodemp || 'AND (tlan.BDCREDITO = ' || :prconta || ' ) ';
     wsql = wsql || ' where (tlan.bdcodemp = ' || :prcodemp || ') AND (tlan.BDCREDITO = ' || :prconta || ' ) ';
     wsql = wsql || ' and tlcc.BDCODTPCC = ' || :prcodtpcc || 'AND (tlcc.bddebcre = 1) ';
     wsql = wsql || ' AND (BDDATA between ''' ||  wdataini || ''' and ''' ||  wdatafim || '''' || ')';
     --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
     IF (prcontabilizacao <> 99) THEN
       wsql = wsql || ' and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
     wsql = wsql || ' GROUP BY TLAN.bdcodemp,bdref' ;
   END

 FOR EXECUTE STATEMENT wsql  INTO :wcodemp,:wdataref,:wvalor  DO
  BEGIN
    --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodemp,:wcodemp,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
    --IF (wpermite = 1) THEN
      --BEGIN
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '01') THEN
          wcre01 = wcre01 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '02') THEN
          wcre02 = wcre02 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '03') THEN
          wcre03 = wcre03 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '04') THEN
          wcre04 = wcre04 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '05') THEN
          wcre05 = wcre05 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '06') THEN
          wcre06 = wcre06 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '07') THEN
          wcre07 = wcre07 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '08') THEN
          wcre08 = wcre08 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '09') THEN
          wcre09 = wcre09 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '10') THEN
          wcre10 = wcre10 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '11') THEN
          wcre11 = wcre11 + wvalor;
        ELSE
        IF (SUBSTRING(wdataref FROM 1 FOR 2) = '12') THEN
          wcre12 = wcre12 + wvalor;
      --END
      END

  IF ((wgrupoconta = 0) OR (wgrupoconta = 4))  THEN -- ATIVO e DESPESAS
    BEGIN
      bdsal01 = wdeb01 - wcre01;
      bdsal02 = wdeb02 - wcre02;
      bdsal03 = wdeb03 - wcre03;
      bdsal04 = wdeb04 - wcre04;
      bdsal05 = wdeb05 - wcre05;
      bdsal06 = wdeb06 - wcre06;
      bdsal07 = wdeb07 - wcre07;
      bdsal08 = wdeb08 - wcre08;
      bdsal09 = wdeb09 - wcre09;
      bdsal10 = wdeb10 - wcre10;
      bdsal11 = wdeb11 - wcre11;
      bdsal12 = wdeb12 - wcre12;
    END
  ELSE
    IF ((wgrupoconta = 1) OR (wgrupoconta = 3)) THEN -- PASSIVO e RECEITAS
      BEGIN
        bdsal01 = wcre01 - wdeb01;
        bdsal02 = wcre02 - wdeb02;
        bdsal03 = wcre03 - wdeb03;
        bdsal04 = wcre04 - wdeb04;
        bdsal05 = wcre05 - wdeb05;
        bdsal06 = wcre06 - wdeb06;
        bdsal07 = wcre07 - wdeb07;
        bdsal08 = wcre08 - wdeb08;
        bdsal09 = wcre09 - wdeb09;
        bdsal10 = wcre10 - wdeb10;
        bdsal11 = wcre11 - wdeb11;
        bdsal12 = wcre12 - wdeb12;
      END

  SUSPEND;
END
^

/* Restore proc. body: VSUC_SP_RETORNA_SALDO_CONTAS */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS(PRCODIGOEMP INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRIGNORAZERAMENTO INTEGER,
PRCC INTEGER,
PRCODPLAPADRAO INTEGER,
PRLANCSEMCC INTEGER,
PRNAOMOSTRACONTACOMP INTEGER,
PRCONSOLIDADA INTEGER,
PRDATAHORA VARCHAR(30),
PRNIVEISCONTA VARCHAR(50),
PRTODASASCONTAS INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(CODEMP INTEGER,
CODPLAPADRAO INTEGER,
CONTA INTEGER,
CLASSIFICACAO VARCHAR(40),
NOMECONTA VARCHAR(100),
GRUPOCONTA SMALLINT,
RELCONTA INTEGER,
CLANOM VARCHAR(140),
TIPCONTA SMALLINT,
SALDO_ANT_DEB NUMERIC(15,2),
SALDO_ANT_CRE NUMERIC(15,2),
SALDO_DEB NUMERIC(15,2),
SALDO_CRE NUMERIC(15,2),
SALDO_ATUAL NUMERIC(15,2),
SALDO_ANTERIOR NUMERIC(15,2),
FORMULA VARCHAR(200),
PARTICIPANTE INTEGER)
 AS
DECLARE VARIABLE WGRPCTA INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(40);
DECLARE VARIABLE WCODIGOPLANO INTEGER;
DECLARE VARIABLE WRELCTA INTEGER;
DECLARE VARIABLE WCLANOM VARCHAR(140);
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WSALDO_DEBITO NUMERIC(15,2);
DECLARE VARIABLE WSALDO_CREDITO NUMERIC(15,2);
DECLARE VARIABLE WANTERIOR_DEBITO NUMERIC(15,2);
DECLARE VARIABLE WANTERIOR_CREDITO NUMERIC(15,2);
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WCLASSINI VARCHAR(40);
DECLARE VARIABLE WCLASSFIN VARCHAR(40);
DECLARE VARIABLE WFORMULA VARCHAR(10240);
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WNIVELCONTA INTEGER;
DECLARE VARIABLE WIMPANALITICA INTEGER;
DECLARE VARIABLE WINDICE INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WSQL_AUX VARCHAR(32000);
BEGIN
  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prcontainicial
  INTO :wclassini;

  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prcontafinal
  INTO :wclassfin;

  SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND SUBSTRING(planos_tpla.bdctalon FROM 1 FOR CHARACTER_LENGTH(:wclassfin)) = :wclassfin
  ORDER BY planos_tpla.bdctalon DESC
  INTO :wclassfin;

  -- Se encontrar no prNiveisConta o "1" significa que deve imprimir contas analíticas
  SELECT BDRPOS FROM RPOS(',1,',','||:prniveisconta||',') INTO :wimpanalitica;

  -- retorna o plano de contas para a tabela temporaria
  wsql = '';
  wsql = wsql|| ' select distinct CONTAS.bdcodplapadrao, CONTAS.bdcodtpla,CONTAS.bdctalon,CONTAS.bdtipcta,CONTAS.bdnomcta, ';
  wsql = wsql|| ' CONTAS.bdgrupocta, CONTAS.bdrelcta, CONTAS.BDCLANOM, CONTAS.bdformula, CONTAS.bdparticipante  from VSUC_SP_RETORNA_CONTAS_USADAS(' || prcodigoemp || ', ' || prcodplapadrao ||   ',null,null,null,null,0,0,' || prnaomostracontacomp || ',3,'  || prtodasascontas ||') CONTAS';
  wsql = wsql|| ' where (contas.bdcodplapadrao = ' || :prcodplapadrao || ') and (contas.bdctalon between ''' || :wclassini || ''' and  ''' || :wclassfin || ''')';
  wsql = wsql||' order by BDCTALON';

  FOR EXECUTE STATEMENT wsql
      INTO :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta, :wnomcta, :wgrpcta, :wrelcta, :wclanom,  :wformula, :wparticipante DO
      BEGIN
        INSERT INTO vsuc_empresas_tbalancete_2 (bddatahora, bdcodemp, bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdgrpcta, bdnomcta,
                                                bdvalor_debito, bdvalor_credito, bdanterior_debito, bdanterior_credito, bdrelcta, bdclanom, bdformula, bdparticipante)
        VALUES(:prdatahora, :prcodigoemp, :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta, :wgrpcta, :wnomcta, 0.00, 0.00, 0.00, 0.00, :wrelcta, :wclanom, :wformula, :wparticipante);
      END

  -- lancamnetos sem centro de custo

  -- Valor a debito
  wsql = '';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     BEGIN
        -- centro de custo
        --#alt:5837.
        --wsql = wsql||'SELECT tlan.bddebito, SUM(TLCC.BDVALOR) AS valor_debito ';
        wsql = wsql||'SELECT tlan.bdcodemp,tlan.bddebito, SUM(TLCC.BDVALOR) AS valor_debito ';
        wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC ';
        wsql = wsql||'join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
     END
  ELSE
     BEGIN
       -- lancamentos
       --#alt:5837.
       --wsql = wsql || 'select tlan.bddebito, coalesce(sum(tlan.bdvalor),0) as valor_debito ';
       wsql = wsql || 'select tlan.bdcodemp,tlan.bddebito, coalesce(sum(tlan.bdvalor),0) as valor_debito ';
       wsql = wsql || 'from vsuc_empresas_tlan tlan ';
     END
  wsql = wsql || 'where (tlan.bdcodplapadrao = '||prcodplapadrao||') ';
  -- gilberto - 15/03/2012 - para lancamentos sem centro de custo deve calcular tudo
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql||'and (TLCC.BDDEBCRE = 0) ';
  -- Giovanni - somente lancamentos sem cc
  IF (prlancsemcc = 1) THEN
     BEGIN
--     wsql = wsql || 'and not tlan.bdchave in (select bdchave from vsuc_empresas_tlcc where bdcodemp = tlan.bdcodemp) ';
       wsql = wsql||'and not tlan.bdchave in ( ';
       wsql = wsql||'                         select bdchave ';
       wsql = wsql||'                         from (select bdcodemp, bdchave, count(bdchave) total ';
       wsql = wsql||'                               from (select distinct bdcodemp, bdchave, bddebcre ';
       wsql = wsql||'                                     from vsuc_empresas_tlcc ';
       wsql = wsql||'                                     where bdcodemp = tlan.bdcodemp) ';
       wsql = wsql||'                               group by bdcodemp, bdchave) ';
       wsql = wsql||'                         where total = 2) ';
     END
  IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
     wsql = wsql || 'and (tlan.bdtipolan <> 10) ';
  wsql = wsql || 'and (tlan.bddata between '''||prdataini||''' and '''||prdatafim||''') ';
  --#alt:5837.
  --wsql = wsql || 'and (tlan.bdcodemp = '||prcodigoemp||') ';
  wsql = wsql || 'and (tlan.bdcodemp = '||prcodigoemp||') ';
  wsql = wsql || 'and (tlan.bddebito is not null) ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql || 'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';
  wsql = wsql || 'Group By tlan.bdcodemp,tlan.bddebito ';

  -- pega a classificaaoo e o saldo total das contas analiticas ______________--
  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodtpla,:wsaldo_debito DO
    BEGIN
      --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodigoemp,:wcodemp,:prmatrizfilialconsolidado,:prcodigoemp) INTO :wpermite;
      --IF (wpermite = 1) THEN
        --BEGIN
          --#alt:5837.
          /*-- faz um update no debito, pq ja foi gravado o lancamento antes zerado
          update vsuc_empresas_tbalancete_2 set bdValor_debito = :wsaldo_debito
          where bdcodemp = :prcodigoemp
          and   bdcodplapadrao = :prcodplapadrao
          and   bdcodtpla = :wcodtpla
          and   bdvalor_debito = 0
          and   bddatahora = :prdatahora; */
          wsql_aux = 'update vsuc_empresas_tbalancete_2 set ';
          wsql_aux = wsql_aux||'bdValor_debito = (coalesce((select bdValor_debito from vsuc_empresas_tbalancete_2';
          wsql_aux = wsql_aux||'                             where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||prcodplapadrao;
          wsql_aux = wsql_aux||'                             and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||'''),0)';
          wsql_aux = wsql_aux||'                  + '||wsaldo_debito||') ';
          wsql_aux = wsql_aux||'where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||prcodplapadrao;
          wsql_aux = wsql_aux||' and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||'''';
          EXECUTE STATEMENT wsql_aux;
        --END
        END

--  exception ex_date;

  -- valor a credito
  wsql = '';
 IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     BEGIN
       -- centro de custo
       --#alt:5837.
       --wsql = wsql||'SELECT tlan.bdcredito, SUM(TLCC.BDVALOR) AS valor_credito ';
       wsql = wsql||'SELECT tlan.bdcodemp,tlan.bdcredito, SUM(TLCC.BDVALOR) AS valor_credito ';
       wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC ';
       wsql = wsql||'join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
     END
  ELSE
     BEGIN
       -- lancamentos
       --#alt:5837.
       --wsql = wsql || 'select tlan.bdcredito, coalesce(sum(tlan.bdvalor),0) as valor_credito ';
       wsql = wsql || 'select tlan.bdcodemp,tlan.bdcredito, coalesce(sum(tlan.bdvalor),0) as valor_credito ';
       wsql = wsql || 'from vsuc_empresas_tlan tlan ';
     END
  wsql = wsql || 'where (tlan.bdcodplapadrao = '||prcodplapadrao||') ';
  -- gilberto - 15/03/2012 - para lancamentos sem centro de custo deve calcular tudo
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql||'and (TLCC.BDDEBCRE = 1) ';
  -- Giovanni - somente lancamentos sem cc
  IF (prlancsemcc = 1) THEN
     BEGIN
--     wsql = wsql || 'and not tlan.bdchave in (select bdchave from vsuc_empresas_tlcc where bdcodemp = tlan.bdcodemp) ';
       wsql = wsql||'and not tlan.bdchave in ( ';
       wsql = wsql||'                         select bdchave ';
       wsql = wsql||'                         from (select bdcodemp, bdchave, count(bdchave) total ';
       wsql = wsql||'                               from (select distinct bdcodemp, bdchave, bddebcre ';
       wsql = wsql||'                                     from vsuc_empresas_tlcc ';
       wsql = wsql||'                                     where bdcodemp = tlan.bdcodemp) ';
       wsql = wsql||'                               group by bdcodemp, bdchave) ';
       wsql = wsql||'                         where total = 2) ';
     END
  IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
     wsql = wsql || 'and (tlan.bdtipolan <> 10) ';
  wsql = wsql || 'and (tlan.bddata between '''||prdataini||''' and '''||prdatafim||''') ';
  --#alt:5837.
  --wsql = wsql || 'and (tlan.bdcodemp = '||prcodigoemp||') ';
  wsql = wsql || 'and (tlan.bdcodemp = '||prcodigoemp||') ';
  wsql = wsql || 'and (tlan.bdcredito is not null) ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql || 'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';
  wsql = wsql || 'Group By tlan.bdcodemp,tlan.bdcredito ';

  -- pega a classificaaoo e o saldo total das analiticas _______________________
  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodtpla, :wsaldo_credito DO
    BEGIN
      --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodigoemp,:wcodemp,:prmatrizfilialconsolidado,:prcodigoemp) INTO :wpermite;
      --IF (wpermite = 1) THEN
        --BEGIN
          -- faz update no credito, pq ja foi gravado o lancamento antes zerado __
          --#alt:5837.
          /*update vsuc_empresas_tbalancete_2 set bdValor_Credito = :wsaldo_credito
          where bdcodemp = :prcodigoemp
          and   bdcodplapadrao = :prcodplapadrao
          and   bdcodtpla = :wcodtpla
          and   bdvalor_credito = 0
          and   bddatahora = :prdatahora;*/
          wsql_aux = 'update vsuc_empresas_tbalancete_2 set ';
          wsql_aux = wsql_aux||'bdValor_Credito = (coalesce((select bdValor_Credito from vsuc_empresas_tbalancete_2';
          wsql_aux = wsql_aux||'                             where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||prcodplapadrao;
          wsql_aux = wsql_aux||'                             and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||'''),0)';
          wsql_aux = wsql_aux||'                  + '||wsaldo_credito||') ';
          wsql_aux = wsql_aux||'where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||prcodplapadrao;
          wsql_aux = wsql_aux||' and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||'''';
          EXECUTE STATEMENT wsql_aux;
        --END
        END

  -- valor a debito anterior
  wsql = '';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     BEGIN
        --#alt:5837.
        --wsql = wsql||'SELECT tlan.bddebito, SUM(TLCC.BDVALOR) AS valor_debito ';
        wsql = wsql||'SELECT tlan.bdcodemp,tlan.bddebito, SUM(TLCC.BDVALOR) AS valor_debito ';
        wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC ';
        wsql = wsql||'join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
     END
  ELSE
     BEGIN
       --#alt:5837.
       --wsql = wsql || 'select tlan.bddebito, coalesce(sum(tlan.bdvalor),0) as valor_debito_anterior ';
       wsql = wsql || 'select tlan.bdcodemp,tlan.bddebito, coalesce(sum(tlan.bdvalor),0) as valor_debito_anterior ';
       wsql = wsql || 'from vsuc_empresas_tlan tlan ';
     END
  wsql = wsql || 'where (tlan.bdcodplapadrao = '||prcodplapadrao||') ';
  -- gilberto - 14/03/2012 - calcular apenas os lancamentos CC referente ao calculo atual
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql||'and (TLCC.BDDEBCRE = 1) ';
  -- Giovanni - somente lancamentos sem cc
  IF (prlancsemcc = 1) THEN
     BEGIN
--     wsql = wsql || 'and not tlan.bdchave in (select bdchave from vsuc_empresas_tlcc where bdcodemp = tlan.bdcodemp) ';
       wsql = wsql||'and not tlan.bdchave in ( ';
       wsql = wsql||'                         select bdchave ';
       wsql = wsql||'                         from (select bdcodemp, bdchave, count(bdchave) total ';
       wsql = wsql||'                               from (select distinct bdcodemp, bdchave, bddebcre ';
       wsql = wsql||'                                     from vsuc_empresas_tlcc ';
       wsql = wsql||'                                     where bdcodemp = tlan.bdcodemp) ';
       wsql = wsql||'                               group by bdcodemp, bdchave) ';
       wsql = wsql||'                         where total = 2) ';
     END
  -- Carlos Mello(22/06/2011) - Solicitação.: 1028. Segundo análise do Celso para saldo anterior não deve ignorar o zeramento
  --para saldo anterior sempre deve ignorar o zeramento
  --if ((prignorazeramento is not null) and (prignorazeramento <> 0)) then
  --   wsql = wsql || 'and (tlan.bdtipolan <> 10) ';
  wsql = wsql || 'and (tlan.bddata < '''||prdataini||''') ';
  --#alt:5837.
  --wsql = wsql || 'and (tlan.bdcodemp = '||prcodigoemp||') ';
  wsql = wsql || 'and (tlan.bdcodemp = '||prcodigoemp||') ';
  wsql = wsql || 'and (tlan.bddebito is not null) ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql || 'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';
  wsql = wsql || 'Group By tlan.bdcodemp,tlan.bddebito ';

  -- pega a classificacao e o saldo total das contas analiticas ________________
  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodtpla, :wsaldo_debito DO
    BEGIN
      --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodigoemp,:wcodemp,:prmatrizfilialconsolidado,:prcodigoemp) INTO :wpermite;
      --IF (wpermite = 1) THEN
        --BEGIN
          -- faz um update no debito, pq ja foi gravado o lancamento antes zerado
          --#alt:5837.
          /*update vsuc_empresas_tbalancete_2 set bdAnterior_debito = :wsaldo_debito
          where bdcodemp = :prcodigoemp
          and   bdcodplapadrao = :prcodplapadrao
          and   bdcodtpla = :wcodtpla
          and   bdAnterior_debito = 0
          and bddatahora = :prdatahora; */
          wsql_aux = 'update vsuc_empresas_tbalancete_2 set ';
          wsql_aux = wsql_aux||'bdAnterior_debito = (coalesce((select bdAnterior_debito from vsuc_empresas_tbalancete_2';
          wsql_aux = wsql_aux||'                               where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||prcodplapadrao;
          wsql_aux = wsql_aux||'                               and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||'''),0)';
          wsql_aux = wsql_aux||'                  + '||wsaldo_debito||') ';
          wsql_aux = wsql_aux||'where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||prcodplapadrao;
          wsql_aux = wsql_aux||' and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||'''';
          EXECUTE STATEMENT wsql_aux;
        --END
        END

  -- valor a credito anterior
  wsql = '';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     BEGIN
       -- centro de custo
       --#alt:5837.
       --wsql = wsql||'SELECT tlan.bdcredito, SUM(TLCC.BDVALOR) AS valor_debito ';
       wsql = wsql||'SELECT tlan.bdcodemp,tlan.bdcredito, SUM(TLCC.BDVALOR) AS valor_debito ';
       wsql = wsql||'FROM VSUC_EMPRESAS_TLCC TLCC ';
       wsql = wsql||'join VSUC_EMPRESAS_TLAN TLAN on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
     END
  ELSE
     BEGIN
       -- lancamentos
       --#alt:5837.
       --wsql = wsql || 'select tlan.bdcredito, coalesce(sum(tlan.bdvalor),0) as valor_credito_anterior ';
       wsql = wsql || 'select tlan.bdcodemp,tlan.bdcredito, coalesce(sum(tlan.bdvalor),0) as valor_credito_anterior ';
       wsql = wsql || 'from vsuc_empresas_tlan tlan ';
     END
  wsql = wsql || 'where (tlan.bdcodplapadrao = '||prcodplapadrao||') ';
  -- gilberto - 14/03/2012 - calcular apenas os lancamentos CC referente ao calculo atual
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql||'and (TLCC.BDDEBCRE = 1) ';
  -- Giovanni - somente lancamentos sem cc
  IF (prlancsemcc = 1) THEN
     BEGIN
--     wsql = wsql || 'and not tlan.bdchave in (select bdchave from vsuc_empresas_tlcc where bdcodemp = tlan.bdcodemp) ';
       wsql = wsql||'and not tlan.bdchave in ( ';
       wsql = wsql||'                         select bdchave ';
       wsql = wsql||'                         from (select bdcodemp, bdchave, count(bdchave) total ';
       wsql = wsql||'                               from (select distinct bdcodemp, bdchave, bddebcre ';
       wsql = wsql||'                                     from vsuc_empresas_tlcc ';
       wsql = wsql||'                                     where bdcodemp = tlan.bdcodemp) ';
       wsql = wsql||'                               group by bdcodemp, bdchave) ';
       wsql = wsql||'                         where total = 2) ';
     END
--   Carlos Mello(22/06/2011) - Solicitação.: 1028. Segundo análise do Celso para saldo anterior não deve ignorar o zeramento
  --para saldo anterior sempre deve ignorar o zeramento
--  if ((prignorazeramento is not null) and (prignorazeramento <> 0)) then
--     wsql = wsql || 'and (tlan.bdtipolan <> 10) ';
  wsql = wsql || 'and (tlan.bddata < '''||prdataini||''') ';
  --#alt:5837.
  --wsql = wsql || 'and (tlan.bdcodemp = '||prcodigoemp||') ';
  wsql = wsql || 'and (tlan.bdcodemp = '||prcodigoemp||') ';
  wsql = wsql || 'and (tlan.bdcredito is not null) ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql || 'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
     wsql = wsql || 'AND (TLCC.bdcodtpcc = '||prcc||') ';
  wsql = wsql || 'Group By tlan.bdcodemp,tlan.bdcredito';

  -- pega a classificaaoo e o saldo total das analiticas _______________________
  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wcodtpla, :wsaldo_credito DO
    BEGIN
      --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodigoemp,:wcodemp,:prmatrizfilialconsolidado,:prcodigoemp) INTO :wpermite;
      --IF (wpermite = 1) THEN
        --BEGIN
          -- faz update no credito, pq ja foi gravado o lancamento antes zerado __
          --#alt:5837.
          /*update vsuc_empresas_tbalancete_2 set bdAnterior_Credito = :wsaldo_credito
          where bdcodemp = :prcodigoemp
          and   bdcodplapadrao = :prcodplapadrao
          and   bdcodtpla = :wcodtpla
          and   bdAnterior_credito = 0
          and   bddatahora = :prdatahora; */
          wsql_aux = 'update vsuc_empresas_tbalancete_2 set ';
          wsql_aux = wsql_aux||'bdAnterior_Credito = (coalesce((select bdAnterior_Credito from vsuc_empresas_tbalancete_2';
          wsql_aux = wsql_aux||'                                where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||prcodplapadrao;
          wsql_aux = wsql_aux||'                                and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||'''),0)';
          wsql_aux = wsql_aux||'                  + '||wsaldo_credito||') ';
          wsql_aux = wsql_aux||'where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||prcodplapadrao;
          wsql_aux = wsql_aux||' and bdcodtpla = '||wcodtpla||' and bddatahora = '''||prdatahora||'''';
          EXECUTE STATEMENT wsql_aux;
        --END
        END

  FOR SELECT tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, tbal.bdtipcta
      FROM vsuc_empresas_tbalancete_2 tbal
      WHERE tbal.bdtipcta IN (0,2)-- gilberto - 17/05/2011 - totalizando as contas consolidadas
      AND tbal.bdcodemp = :prcodigoemp
      AND tbal.bddatahora = :prdatahora
      INTO :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta DO
      BEGIN
        -- fas um select para totalizar as contas titulos ______________________
        SELECT SUM(tbal.bdvalor_debito) AS valor_debito, SUM(tbal.bdvalor_credito) AS valor_credito,
               SUM(tbal.bdanterior_debito) AS anterior_debito, SUM(tbal.bdanterior_credito) AS anterior_credito
        FROM vsuc_empresas_tbalancete_2 tbal
--        where substring(bdctalon from 1 for strlen(:wclassificacao)) = :wclassificacao
        WHERE bdctalon LIKE :wclassificacao||'%'
        AND tbal.bdcodemp = :prcodigoemp
        AND tbal.bddatahora = :prdatahora
        GROUP BY SUBSTRING(bdctalon FROM 1 FOR strlen(:wclassificacao))
        INTO :wsaldo_debito, :wsaldo_credito, :wanterior_debito, :wanterior_credito;

        -- da um update na tabela de balancete para gravar os totais ___________
        UPDATE vsuc_empresas_tbalancete_2 SET bdvalor_debito = :wsaldo_debito,
                                            bdvalor_credito = :wsaldo_credito,
                                            bdanterior_debito = :wanterior_debito,
                                            bdanterior_credito = :wanterior_credito
        WHERE bdcodemp = :prcodigoemp
        AND   bdcodplapadrao = :wcodigoplano
        AND   bdcodtpla = :wcodtpla
        AND   bddatahora = :prdatahora
        AND   bdctalon = :wclassificacao;
      END

  -- gilberto - 07/10/2011 - retira as contas analiticas que pertencem a uma conta consolidadas
  IF ((prconsolidada IS NULL) OR (prconsolidada = 0)) THEN
     BEGIN
       FOR SELECT bdctalon FROM planos_tpla WHERE bdcodplapadrao = :prcodplapadrao AND bdtipcta = 2 INTO :wctalon DO
           BEGIN
             wsql = 'delete from vsuc_empresas_tbalancete_2 ';
             wsql = wsql||'where bdcodplapadrao = '||prcodplapadrao;
--             wsql = wsql||' and substring(bdctalon from 1 for strlen('''||wctalon||''')) = '''||wctalon||''' ';
             wsql = wsql||' and bdctalon like '''||wctalon||'%'||''' ';
             wsql = wsql||'and bdctalon <> '''||wctalon||''' ';
             wsql = wsql||'and bddatahora = '''||prdatahora||''' ';
             EXECUTE STATEMENT wsql;
           END
     END

  -- faz o select na tabela de balancete e monta os retornos para a impressao
  FOR SELECT bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdgrpcta, bdnomcta,
             bdvalor_debito, bdvalor_credito, bdanterior_debito, bdanterior_credito, bdformula, bdrelcta, bdclanom, bdparticipante
      FROM vsuc_empresas_tbalancete_2 tbal
      WHERE bddatahora = :prdatahora
      ORDER BY bdctalon ASC
      INTO :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta, :wgrpcta, :wnomcta,
       :wsaldo_debito, :wsaldo_credito, :wanterior_debito, :wanterior_credito, :formula, :relconta , :clanom, :wparticipante DO
      BEGIN
        codemp = :prcodigoemp;
        codplapadrao = :wcodigoplano;
        conta  = :wcodtpla;
        classificacao = :wclassificacao;
        nomeconta = :wnomcta;
        tipconta = :wtipcta;
        grupoconta = :wgrpcta;
        participante = :wparticipante;
        saldo_ant_deb = :wanterior_debito;
        saldo_ant_cre = :wanterior_credito;
        saldo_deb = :wsaldo_debito;
        saldo_cre = :wsaldo_credito;

        IF (wgrpcta IN (1,2,3)) THEN
           saldo_anterior = (wanterior_credito - wanterior_debito);
        ELSE
           saldo_anterior = (wanterior_debito - wanterior_credito);

        IF (wgrpcta IN (1,2,3)) THEN
           saldo_atual = (saldo_anterior + :wsaldo_credito - :wsaldo_debito);
        ELSE
           saldo_atual = (saldo_anterior + :wsaldo_debito - :wsaldo_credito);

        -- Filtro pelo nível da conta
        SELECT contar_char FROM contar_char(:wclassificacao,'.') INTO :wnivelconta;
        wnivelconta = wnivelconta + 1;
        SELECT BDRPOS FROM RPOS(','||CAST(:wnivelconta AS VARCHAR(100))||',',','||:prniveisconta||',') INTO :windice;
        IF ((prniveisconta = '9999') OR           -- Não tem filtro
            (wnivelconta = 1) OR                  -- O primeiro nível sempre imprime
            ((windice > 0) AND (:wtipcta = 0)) OR -- O nível da conta foi selecionado no filtro e é título
           -- ((windice > 0) and (wimpanalitica > 0) and (:wtipcta = 1))) then -- É do nível selecionado, analítica e foi selecionado para imprimir as contas analíticas
            -- alteracao abaixo pq nao esta imprimindo as contas consolidas , so imprimia as contas analiticas no balancete
            (((windice > 0) AND (wimpanalitica > 0) AND ((:wtipcta = 1) OR (:wtipcta = 2))))) THEN -- É do nível selecionado, analítica e foi selecionado para imprimir as contas analíticas

          SUSPEND;
      END

  DELETE FROM vsuc_empresas_tbalancete_2 WHERE bddatahora = :prdatahora;
END
^

/* Restore proc. body: VSUC_SP_RETORNA_SALDO_CONTAS_CC */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS_CC(PRCODEMP INTEGER,
PRCODCTAINI INTEGER,
PRCODCTAFIN INTEGER,
PRDATINI DATE,
PRDATFIN DATE,
PRIGNZER INTEGER,
PRCODTPCC INTEGER,
PRCODPLAPADRAO INTEGER,
PRNAOMOSTRACONTACOMP INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODPLAPADRAO INTEGER,
BDCODCTA INTEGER,
BDCTALON VARCHAR(40),
BDNOMCTA VARCHAR(100),
BDGRPCTA SMALLINT,
BDRELCTA INTEGER,
BDTIPCTA SMALLINT,
BDSALANTDEB NUMERIC(15,2),
BDSALANTCRE NUMERIC(15,2),
BDSALDEB NUMERIC(15,2),
BDSALCRE NUMERIC(15,2),
BDSALATU NUMERIC(15,2),
BDSALANT NUMERIC(15,2),
BDFORMULA VARCHAR(200))
 AS
DECLARE VARIABLE WCTALONINI VARCHAR(40);
DECLARE VARIABLE WCTALONFIN VARCHAR(40);
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WTIPCTA INTEGER;
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WGRPCTA INTEGER;
DECLARE VARIABLE WRELCTA INTEGER;
DECLARE VARIABLE WCODTPLACRE INTEGER;
DECLARE VARIABLE WCODTPLADEB INTEGER;
DECLARE VARIABLE WCTALONCRE VARCHAR(40);
DECLARE VARIABLE WCTALONDEB VARCHAR(40);
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WDEBCRE INTEGER;
DECLARE VARIABLE WVALDEB NUMERIC(15,2);
DECLARE VARIABLE WVALCRE NUMERIC(15,2);
DECLARE VARIABLE WVALDEBANT NUMERIC(15,2);
DECLARE VARIABLE WVALCREANT NUMERIC(15,2);
DECLARE VARIABLE WFORMULA VARCHAR(200);
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WDATAHORA VARCHAR(30);
BEGIN
  -- Não foi feito a modificação Matriz/Filial da solicitação 5837, porque a rotina não
  --está funcinado e ela não é utilizada.
  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prcodctaini
  INTO :wctalonini;

  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prcodctafin
  INTO :wctalonfin;

  SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND SUBSTRING(planos_tpla.bdctalon FROM 1 FOR CHARACTER_LENGTH(:wctalonfin)) = :wctalonfin
  ORDER BY planos_tpla.bdctalon DESC
  INTO :wctalonfin;


-- giovanni... insere somente as contas com lancamentos

  wdatahora = localtimestamp;

  wsql = '';
  wsql = wsql|| ' select distinct CONTAS.bdcodplapadrao, CONTAS.bdcodtpla,CONTAS.bdctalon,CONTAS.bdtipcta,CONTAS.bdnomcta, ';
  wsql = wsql|| ' CONTAS.bdgrupocta, CONTAS.bdrelcta,CONTAS.bdformula  from VSUC_SP_RETORNA_CONTAS_USADAS(' || prcodemp || ', ' || prcodplapadrao ||   ',null,null,null,null,0,0,' || prnaomostracontacomp || ',3,null) CONTAS'; --',3,null,null,0' || ') CONTAS'; alt:9173 - Comentado para tirar os parâmetros extras que tinha aqui, estavam causando erro no SQL. Pedro
  wsql = wsql|| ' where (contas.bdcodplapadrao = ' || :prcodplapadrao || ') and (contas.bdctalon between ''' || :wctalonini || ''' and  ''' || :wctalonfin || ''' ) order by BDCTALON';


  FOR EXECUTE STATEMENT wsql
      INTO :wcodplapadrao, :wcodtpla, :wctalon, :wtipcta, :wnomcta, :wgrpcta, :wrelcta, :wformula DO
      BEGIN
        INSERT INTO vsuc_empresas_tbalancete_2 (bddatahora, bdcodemp, bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdgrpcta, bdnomcta,
                                              bdvalor_debito, bdvalor_credito, bdanterior_debito, bdanterior_credito, bdrelcta, bdformula)
        VALUES(:wdatahora, :prcodemp, :wcodplapadrao, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, 0.00, 0.00, 0.00, 0.00, :wrelcta, :wformula);
      END


  -- retorna salto anterior
  FOR SELECT tbalcre.bdcodtpla "bdcodtplacre", tbalcre.bdctalon "bdctaloncre",
             tbaldeb.bdcodtpla "bdcodtpladeb", tbaldeb.bdctalon "bdctalondeb",
             TLAN.BDVALOR, tlcc.bddebcre--, tlcc.bdcodtpcc
      FROM VSUC_EMPRESAS_TLCC TLCC
      JOIN VSUC_EMPRESAS_TLAN TLAN ON ((TLCC.BDCHAVE = TLAN.BDCHAVE) AND (TLCC.BDCODEMP = TLAN.BDCODEMP))
      LEFT OUTER JOIN vsuc_empresas_tbalancete_2 tbalcre ON (tbalcre.bdcodplapadrao = tlan.bdcodplapadrao AND
                                                           tbalcre.bdcodtpla = tlan.bdcredito AND
                                                           tbalcre.bdcodplapadrao = :prcodplapadrao AND
                                                           tbalcre.bdtipcta = 1)
      LEFT OUTER JOIN vsuc_empresas_tbalancete_2 tbaldeb ON (tbaldeb.bdcodplapadrao = tlan.bdcodplapadrao AND
                                                           tbaldeb.bdcodtpla = tlan.bddebito AND
                                                           tbaldeb.bdcodplapadrao = :prcodplapadrao AND
                                                           tbaldeb.bdtipcta = 1)
      WHERE (tlan.bdtipolan <> 0)
      AND (tlan.bddata < :prdatini)
      AND (tlan.bdcodemp = :prcodemp)
      AND (TLCC.bdcodtpcc = :prcodtpcc)
      ORDER BY tbalcre.bdctalon, tbaldeb.bdctalon DESC
      INTO :wcodtplacre, :wctaloncre,
           :wcodtpladeb, :wctalondeb,
           :wvalor, :wdebcre DO
      BEGIN
        bdcodemp = prcodemp;
        bdcodplapadrao = prcodplapadrao;

        IF (wdebcre = 0) THEN
           BEGIN
             --alt:9173 - Adicionado o SUM  e o Coalesce porque estava ocorrendo erro por vir mais de um lançamento na mesma conta quando usa Centro de Custos. Pedro
             SELECT SUM(COALESCE(tbal.bdvalor_debito, 0)), SUM(COALESCE(tbal.bdvalor_credito, 0)),
                    SUM(COALESCE(tbal.bdanterior_debito, 0)), SUM(COALESCE(tbal.bdanterior_credito, 0))
             FROM vsuc_empresas_tbalancete_2 tbal
             WHERE tbal.bdcodemp = :prcodemp
             AND tbal.bdcodplapadrao = :prcodplapadrao
             AND tbal.bdcodtpla = :wcodtplacre
             INTO :wvaldeb, :wvalcre, :wvaldebant, :wvalcreant;

             UPDATE vsuc_empresas_tbalancete_2 tbal SET
             tbal.bdvalor_debito = (:wvalcre + :wvalor)
             WHERE tbal.bdcodemp = :prcodemp
             AND tbal.bdcodplapadrao = :prcodplapadrao
             AND tbal.bdcodtpla = :wcodtplacre;
           END
        ELSE
           BEGIN
             --alt:9173 - Adicionado o SUM  e o Coalesce porque estava ocorrendo erro por vir mais de um lançamento na mesma conta quando usa Centro de Custos. Pedro
             SELECT SUM(COALESCE(tbal.bdvalor_debito, 0)), SUM(COALESCE(tbal.bdvalor_credito, 0)),
                    SUM(COALESCE(tbal.bdanterior_debito, 0)), SUM(COALESCE(tbal.bdanterior_credito, 0))
             FROM vsuc_empresas_tbalancete_2 tbal
             WHERE tbal.bdcodemp = :prcodemp
             AND tbal.bdcodplapadrao = :prcodplapadrao
             AND tbal.bdcodtpla = :wcodtpladeb
             INTO :wvaldeb, :wvalcre, :wvaldebant, :wvalcreant;

             UPDATE vsuc_empresas_tbalancete_2 tbal SET
             tbal.bdvalor_debito = (:wvaldeb + :wvalor)
             WHERE tbal.bdcodemp = :prcodemp
             AND tbal.bdcodplapadrao = :prcodplapadrao
             AND tbal.bdcodtpla = :wcodtpladeb;
           END
      END

  -- retorna salto atual
  FOR SELECT tbalcre.bdcodtpla "bdcodtplacre", tbalcre.bdctalon "bdctaloncre",
             tbaldeb.bdcodtpla "bdcodtpladeb", tbaldeb.bdctalon "bdctalondeb",
             TLAN.BDVALOR, tlcc.bddebcre--, tlcc.bdcodtpcc
      FROM VSUC_EMPRESAS_TLCC TLCC
      JOIN VSUC_EMPRESAS_TLAN TLAN ON ((TLCC.BDCHAVE = TLAN.BDCHAVE) AND (TLCC.BDCODEMP = TLAN.BDCODEMP))
      LEFT OUTER JOIN vsuc_empresas_tbalancete_2 tbalcre ON (tbalcre.bdcodplapadrao = tlan.bdcodplapadrao AND
                                                           tbalcre.bdcodtpla = tlan.bdcredito AND
                                                           tbalcre.bdcodplapadrao = :prcodplapadrao AND
                                                           tbalcre.bdtipcta = 1)
      LEFT OUTER JOIN vsuc_empresas_tbalancete_2 tbaldeb ON (tbaldeb.bdcodplapadrao = tlan.bdcodplapadrao AND
                                                           tbaldeb.bdcodtpla = tlan.bddebito AND
                                                           tbaldeb.bdcodplapadrao = :prcodplapadrao AND
                                                           tbaldeb.bdtipcta = 1)
      WHERE (tlan.bdtipolan <> 0)
      AND (tlan.bddata BETWEEN :prdatini AND :prdatfin)
      AND (tlan.bdcodemp = :prcodemp)
      AND (TLCC.bdcodtpcc = :prcodtpcc)
      ORDER BY tbalcre.bdctalon, tbaldeb.bdctalon DESC
      INTO :wcodtplacre, :wctaloncre,
           :wcodtpladeb, :wctalondeb,
           :wvalor, :wdebcre DO
      BEGIN
        bdcodemp = prcodemp;
        bdcodplapadrao = prcodplapadrao;

        IF (wdebcre = 0) THEN
           BEGIN
             SELECT tbal.bdvalor_debito, tbal.bdvalor_credito,
                    tbal.bdanterior_debito, tbal.bdanterior_credito
             FROM vsuc_empresas_tbalancete_2 tbal
             WHERE tbal.bdcodemp = :prcodemp
             AND tbal.bdcodplapadrao = :prcodplapadrao
             AND tbal.bdcodtpla = :wcodtplacre
             INTO :wvaldeb, :wvalcre, :wvaldebant, :wvalcreant;

             UPDATE vsuc_empresas_tbalancete_2 tbal SET
             tbal.bdvalor_debito = (:wvalcre + :wvalor)
             WHERE tbal.bdcodemp = :prcodemp
             AND tbal.bdcodplapadrao = :prcodplapadrao
             AND tbal.bdcodtpla = :wcodtplacre;
           END
        ELSE
           BEGIN
             SELECT tbal.bdvalor_debito, tbal.bdvalor_credito,
                    tbal.bdanterior_debito, tbal.bdanterior_credito
             FROM vsuc_empresas_tbalancete_2 tbal
             WHERE tbal.bdcodemp = :prcodemp
             AND tbal.bdcodplapadrao = :prcodplapadrao
             AND tbal.bdcodtpla = :wcodtpladeb
             INTO :wvaldeb, :wvalcre, :wvaldebant, :wvalcreant;

             UPDATE vsuc_empresas_tbalancete_2 tbal SET
             tbal.bdvalor_debito = (:wvaldeb + :wvalor)
             WHERE tbal.bdcodemp = :prcodemp
             AND tbal.bdcodplapadrao = :prcodplapadrao
             AND tbal.bdcodtpla = :wcodtpladeb;
           END
      END

  FOR SELECT tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, tbal.bdtipcta
      FROM vsuc_empresas_tbalancete_2 tbal
      WHERE tbal.bdtipcta = 0
      INTO :wcodplapadrao, :wcodtpla, :wctalon, :wtipcta DO
      BEGIN
        -- fas um select para totalizar as contas titulos ______________________
        SELECT SUM(tbal.bdvalor_debito) AS valor_debito, SUM(tbal.bdvalor_credito) AS valor_credito,
               SUM(tbal.bdanterior_debito) AS anterior_debito, SUM(tbal.bdanterior_credito) AS anterior_credito
        FROM vsuc_empresas_tbalancete_2 tbal
        WHERE SUBSTRING(bdctalon FROM 1 FOR strlen(:wctalon)) = :wctalon
        GROUP BY SUBSTRING(bdctalon FROM 1 FOR strlen(:wctalon))
        INTO :wvaldeb, :wvalcre, :wvaldebant, :wvalcreant;

        -- da um update na tabela de balancete para gravar os totais ___________
        UPDATE vsuc_empresas_tbalancete_2 SET bdvalor_debito = :wvaldeb,
                                            bdvalor_credito = :wvalcre,
                                            bdanterior_debito = :wvaldebant,
                                            bdanterior_credito = :wvalcreant
        WHERE bdcodemp = :prcodemp
        AND   bdcodplapadrao = :wcodplapadrao
        AND   bdcodtpla = :wcodtpla
        AND   bdctalon = :wctalon;
      END

  -- parametros de saida
  FOR SELECT bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdgrpcta, bdnomcta,
             bdvalor_debito, bdvalor_credito, bdanterior_debito, bdanterior_credito, bdformula
      FROM vsuc_empresas_tbalancete_2 tbal
      ORDER BY bdctalon ASC
      INTO :wcodplapadrao, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta,
           :wvaldeb, :wvalcre, :wvaldebant, :wvalcreant, :wformula DO
      BEGIN
        bdcodemp = :prcodemp;
        bdcodplapadrao = :wcodplapadrao;
        bdcodcta  = :wcodtpla;
        bdctalon = :wctalon;
        bdnomcta = :wnomcta;
        bdtipcta = :wtipcta;
        bdgrpcta = :wgrpcta;
        bdsalantdeb = :wvaldebant;
        bdsalantcre = :wvalcreant;
        bdsaldeb = :wvaldeb;
        bdsalcre = :wvalcre;
        bdformula = :wformula;

        IF (wgrpcta IN (1,2,3)) THEN
           bdsalant = (wvalcreant - wvaldebant);
        ELSE
           bdsalant = (wvaldebant - wvalcreant);

        IF (wgrpcta IN (1,2,3)) THEN
           bdsalatu = (bdsalant + :wvalcre - :wvaldeb);
        ELSE
           bdsalatu = (bdsalant + :wvaldeb - :wvalcre);



        SUSPEND;
      END

  DELETE FROM vsuc_empresas_tbalancete_2 WHERE bddatahora = :wdatahora ;
END
^

/* Restore proc. body: VSUC_SP_RETORNA_SALDO_CONTAS_X */
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_CONTAS_X (
    PRCODIGOEMP INTEGER,
    PRCONTAINICIAL INTEGER,
    PRCONTAFINAL INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRINDICE INTEGER,
    PRIGNORAZERAMENTO INTEGER,
    PRCC INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRLANCSEMCC INTEGER,
    PRNAOMOSTRACONTACOMP INTEGER,
    PRCONSOLIDADA INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PREMPRESAS VARCHAR(2048),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRDRE INTEGER = 0,
    PRTODOPLANOCONTAS INTEGER = 0,
    PRSOMENTEMOVIMENTO INTEGER = 0,
    PRPLANOGRPECO integer = 0,
    PREMPRESAGRPECO integer = 0,
    PRGRPECO integer = 0,
    PRIGNZERPERANT integer = 0,
    PRTIPOLAN varchar(3200) = '',
    PRELIMINACOESK300K315 integer = 0)
returns (
    CODEMP integer,
    CODPLAPADRAO integer,
    CONTA integer,
    CLASSIFICACAO varchar(40),
    NOMECONTA varchar(100),
    GRUPOCONTA smallint,
    RELCONTA integer,
    CLANOM varchar(140),
    TIPCONTA smallint,
    SALDO_ANT_DEB numeric(15,2),
    SALDO_ANT_CRE numeric(15,2),
    SALDO_DEB numeric(15,2),
    SALDO_CRE numeric(15,2),
    SALDO_ATUAL numeric(15,2),
    SALDO_ANTERIOR numeric(15,2),
    FORMULA varchar(200),
    PARTICIPANTE integer,
    APECTA varchar(20),
    PERTENCECONTA integer,
    SALDO_ANT_DEB_DRE numeric(15,2),
    SALDO_ANT_CRE_DRE numeric(15,2),
    SALDO_ANTERIOR_DRE numeric(15,2),
    SALDO_SEM_CONCILIACAO numeric(15,2),
    SALDO_ATUAL_REAL numeric(15,2),
    DATAULTLANCAMENTO date)
as
declare variable WGRPCTA integer;
declare variable WCLASSIFICACAO varchar(40);
declare variable WCODIGOPLANO integer;
declare variable WTIPCTA smallint;
declare variable WCODTPLA integer;
declare variable WNOMCTA varchar(100);
declare variable WSALDO_DEBITO numeric(15,2);
declare variable WSALDO_CREDITO numeric(15,2);
declare variable WANTERIOR_DEBITO numeric(15,2);
declare variable WANTERIOR_CREDITO numeric(15,2);
declare variable WSQL varchar(32000);
declare variable WCLASSINI varchar(40);
declare variable WCLASSFIN varchar(40);
declare variable WPARTICIPANTE integer;
declare variable WNIVELCONTA integer;
declare variable WIMPANALITICA integer;
declare variable WINDICE integer;
declare variable WAPECTA varchar(20);
declare variable WPERTENCECONTA integer;
declare variable WDTULTZERAMENTO date;
declare variable WSQL_AUX varchar(32000);
declare variable WANTERIOR_DEBITO_DRE numeric(15,2);
declare variable WANTERIOR_CREDITO_DRE numeric(15,2);
declare variable WCONT integer;
declare variable WSELECTCONTAS integer;
declare variable WSQLSALDOS varchar(32000);
declare variable WSALDO_NAO_CONCILIADO numeric(15,2);
declare variable WTIPOCONTANIVEL smallint;
declare variable WCLASSIFICACAO_REVERSE DM_CLASSCONTAS;
declare variable WPOSITION_PONTO integer;
declare variable WBALANCETES_RODANDO integer;
declare variable WBALANCETES_RODANDO_LIMITE integer;
declare variable WULTIMOCONSOLIDADA varchar(40);
declare variable WVALOR_DEBITO_REAL numeric(15,2);
declare variable WVALOR_CREDITO_REAL numeric(15,2);
declare variable WZERAMENTOSIGNORAR varchar(200);
declare variable WVALOR_DEBITO_ANT_ZER numeric(15,2);
declare variable WVALOR_CREDITO_ANT_ZER numeric(15,2);
BEGIN
  --#alt:155149 - Machado - 14/09/2021 - 1.21.9.99 - Melhoria de performance, inserts e updates estavam causando lentidão na MG.
  select coalesce(bdVALORINT, 0) from TPARAMETRO where bdParam = 'BALANCETES_RODANDO_LIMITE' into :wBALANCETES_RODANDO_LIMITE;
  if (wBALANCETES_RODANDO_LIMITE > 0) then
   begin
    while (1=1) do
     begin
      select coalesce(bdVALORINT, 0) from TPARAMETRO where bdParam = 'BALANCETES_RODANDO_LIMITE' into :wBALANCETES_RODANDO_LIMITE;
      select bdVALORINT from TPARAMETRO where bdParam = 'BALANCETES_RODANDO' into :wBALANCETES_RODANDO;
      if (wBALANCETES_RODANDO <= (wBALANCETES_RODANDO_LIMITE - 1)) then
      break;
     end
    IN AUTONOMOUS TRANSACTION DO UPDATE TPARAMETRO set bdVALORINT = bdVALORINT + 1 where bdPARAM='BALANCETES_RODANDO';
   end

  if ((prcodplapadrao <> PRPLANOGRPECO) and (PRPLANOGRPECO <> 0)) then
    BEGIN
      SELECT planos_tpla.bdctalon FROM planos_tpla
      WHERE planos_tpla.bdcodplapadrao = :PRPLANOGRPECO
      AND planos_tpla.bdcodtpla = :prcontainicial
      ORDER BY planos_tpla.bdctalon
      INTO :wclassini;
    
      -- retorno da classifica??o final ____________________________________________
      SELECT planos_tpla.bdctalon FROM planos_tpla
      WHERE planos_tpla.bdcodplapadrao = :PRPLANOGRPECO
      AND planos_tpla.bdcodtpla = :prcontafinal
      ORDER BY planos_tpla.bdctalon
      INTO :wclassfin;
      SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
      WHERE planos_tpla.bdcodplapadrao = :PRPLANOGRPECO
      AND planos_tpla.bdctalon LIKE :wclassfin||'%'
      ORDER BY planos_tpla.bdcodplapadrao DESC, planos_tpla.bdctalon DESC
      INTO :wclassfin;
    END
  ELSE
    BEGIN
  -- retorno da classificação inicial __________________________________________
  
      SELECT planos_tpla.bdctalon FROM planos_tpla
      WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
      AND planos_tpla.bdcodtpla = :prcontainicial
      ORDER BY planos_tpla.bdctalon
      INTO :wclassini;
    
      -- retorno da classificação final ____________________________________________
      SELECT planos_tpla.bdctalon FROM planos_tpla
      WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
      AND planos_tpla.bdcodtpla = :prcontafinal
      ORDER BY planos_tpla.bdctalon
      INTO :wclassfin;
      SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
      WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
      AND planos_tpla.bdctalon LIKE :wclassfin||'%'
      ORDER BY planos_tpla.bdcodplapadrao DESC, planos_tpla.bdctalon DESC
      INTO :wclassfin;
    END
  -- carrega se tem alguma conta específica selecionada ________________________
  SELECT FIRST 1 BDCODTPLA FROM VSUC_SELECT_CONTAS INTO :wSelectContas;

  IF ((prDRE <> 0) AND (prDRE IS NOT NULL)) THEN
    BEGIN
      -- Retorna o último zeramento
      SELECT FIRST 1 BDDATAINIZER FROM VSUC_EMPRESAS_TENCEXE WHERE BDCODEMP = :prCodigoEmp AND BDDATAFIMZER < :prDataIni ORDER BY BDCODEMP DESC, BDDATAFIMZER DESC INTO :wDtUltZeramento;
      IF (wDtUltZeramento IS NULL) THEN
        SELECT FIRST 1 BDDATA FROM VSUC_EMPRESAS_TLAN WHERE BDCODEMP = :prCodigoEmp ORDER BY BDCODEMP, BDDATA INTO :wDtUltZeramento;
      IF (wDtUltZeramento IS NULL) THEN
        wDtUltZeramento = :prDataIni;

      -- Limpa tabela temporária de contas com zeramento
      DELETE FROM VSUC_EMP_TCTAZERADAS WHERE bdcodemp IS NOT NULL;

      -- Povoa tabela temporária de contas com zeramento
      wsql = 'Insert into VSUC_EMP_TCTAZERADAS ';
      wsql = wsql||'Select bdcodemp,bdcodcta from (Select tlan.bdcodemp, tlan.bdcredito bdcodcta';
      wsql = wsql||'                               from VSUC_EMPRESAS_TLAN tlan';
      wsql = wsql||'                               where';
      wsql = wsql||'                               (tlan.bddata <= '''||prDataIni||''') and';
      wsql = wsql||'                               (tlan.bdcodemp = '||prCodigoEmp||') and';
      wsql = wsql||'                               (tlan.bdcredito is not null) and';
      wsql = wsql||'                               (tlan.bdtipolan = 10)';
      wsql = wsql||'                               Group By bdcodemp, bdcodcta';
      wsql = wsql||'                               union all';
      wsql = wsql||'                               Select tlan.bdcodemp, tlan.bddebito bdcodcta';
      wsql = wsql||'                               from VSUC_EMPRESAS_TLAN tlan';
      wsql = wsql||'                               where';
      wsql = wsql||'                               (tlan.bddata <= '''||prDataIni||''') and';
      wsql = wsql||'                               (tlan.bdcodemp = '||prCodigoEmp||') and';
      wsql = wsql||'                               (tlan.bddebito is not null) and';
      wsql = wsql||'                               (tlan.bdtipolan = 10)';
      wsql = wsql||'                               Group By bdcodemp, bdcodcta) ';
      wsql = wsql||'Group by bdcodemp,bdcodcta';
      EXECUTE STATEMENT wsql;
    END

  wzeramentosignorar = '';
  if (prignorazeramento = 2) then
    SELECT LIST(E.bdchavezer, ',') FROM tmp_vsuc_empresas_tencexe E WHERE E.bdcodemp = :prcodigoemp INTO :wzeramentosignorar;

  -- limpa tabela temporaria de saldos _________________________________________
  DELETE FROM vsuc_emp_tsaldos WHERE bdcodemp IS NOT NULL;
  -- povoa tabela temporária de saldos _________________________________________

  wsqlsaldos = '';

  IF ((prlancsemcc = 1) AND ((prcc IS NULL) OR (prcc = 0))) THEN
    BEGIN
      wsql_aux = 'where (tlan.bddata <= '''||prdatafim||''') ';
      if (PRSOMENTEMOVIMENTO = 1) then
        wsql_aux = wsql_aux||' AND (tlan.bddata >= '''||prdataini||''') ';
      --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
      IF (prcontabilizacao <> 99) THEN
        wsql_aux = wsql_aux||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
      wsql_aux = wsql_aux||'and (tlan.bdcodemp = '||prcodigoemp||') ';
      IF (PRTIPOLAN <> '') THEN --#212425
        wsqlsaldos = wsqlsaldos || ' and (tlan.bdtipolan in ('||PRTIPOLAN||'))';   

      --Débito
      wsqlsaldos = wsqlsaldos||'select tlan.bdcodemp,tlan.bddata,tlan.bdcredito as bdcredito,tlan.bddebito,tlan.bdtipolan, ';
      wsqlsaldos = wsqlsaldos||'sum(coalesce(tlan.bdvalor, 0)) as bdvalor, NULL AS BDVALCONC, NULL AS BDVALCOND ,null as bdcodtpcc ,null as bddebcre ';
      if (wzeramentosignorar <> '') then
        wsqlsaldos = wsqlsaldos||', tlan.bdchavezer ';
      wsqlsaldos = wsqlsaldos||'from ';
      wsqlsaldos = wsqlsaldos||'     (select tlan.bdcodemp,tlan.bdchave,tlan.bddata,null as bdcredito,tlan.bddebito,tlan.bdtipolan, ';
      --alt:6178 - 09/11/2015 - Verifica se foi informado um índice, caso positivo, divide o valor do lançamento pelo valor do índice na data. Função dos relatórios em outra moeda. Pedro
      IF (prindice = 0) THEN
        wsqlsaldos = wsqlsaldos||'tlan.bdvalor ';
      ELSE
        BEGIN
          wsqlsaldos = wsqlsaldos||'tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsqlsaldos = wsqlsaldos||'                        (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) ';
        END
      if (wzeramentosignorar <> '') then
        wsqlsaldos = wsqlsaldos||', tlan.bdchavezer ';
      --alt:6178 - Fim
      wsqlsaldos = wsqlsaldos||'     from vsuc_empresas_tlan tlan ';
      wsqlsaldos = wsqlsaldos||      wsql_aux||') tlan ';
      wsqlsaldos = wsqlsaldos||'Group By tlan.bdcodemp,tlan.bdcredito,tlan.bddebito,tlan.bddata,tlan.bdtipolan ';
      if (wzeramentosignorar <> '') then
        wsqlsaldos = wsqlsaldos||', tlan.bdchavezer ';
      wsqlsaldos = wsqlsaldos||'union ';
      --Crédito
      wsqlsaldos = wsqlsaldos||'select tlan.bdcodemp,tlan.bddata,tlan.bdcredito,tlan.bddebito,tlan.bdtipolan, ';
      wsqlsaldos = wsqlsaldos||'sum(coalesce(tlan.bdvalor, 0)), NULL AS BDVALCONC, NULL AS BDVALCOND,null,null ';
      if (wzeramentosignorar <> '') then
        wsqlsaldos = wsqlsaldos||', tlan.bdchavezer ';
      wsqlsaldos = wsqlsaldos||'from ';
      wsqlsaldos = wsqlsaldos||'     (select tlan.bdcodemp,tlan.bdchave,tlan.bddata,tlan.bdcredito,null as bddebito,tlan.bdtipolan, ';
      --alt:6178 - 09/11/2015 - Verifica se foi informado um índice, caso positivo, divide o valor do lançamento pelo valor do índice na data. Função dos relatórios em outra moeda. Pedro
      IF (prindice = 0) THEN
        wsqlsaldos = wsqlsaldos||'tlan.bdvalor ';
      ELSE
        BEGIN
          wsqlsaldos = wsqlsaldos||'tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsqlsaldos = wsqlsaldos||'                        (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) ';
        END
      --alt:6178 - Fim
      if (wzeramentosignorar <> '') then
        wsqlsaldos = wsqlsaldos||', tlan.bdchavezer ';
      wsqlsaldos = wsqlsaldos||'     from vsuc_empresas_tlan tlan ';
      wsqlsaldos = wsqlsaldos||      wsql_aux||') tlan ';
      wsqlsaldos = wsqlsaldos||'Group By tlan.bdcodemp,tlan.bdcredito,tlan.bddebito,tlan.bddata,tlan.bdtipolan ';
      if (wzeramentosignorar <> '') then
        wsqlsaldos = wsqlsaldos||', tlan.bdchavezer ';
    END
  ELSE
    BEGIN
      wsqlsaldos = wsqlsaldos||'select tlan.bdcodemp,tlan.bddata,tlan.bdcredito,tlan.bddebito,tlan.bdtipolan, ';
      --alt:6178 - 09/11/2015 - Verifica se foi informado um índice, caso positivo, divide o valor do lançamento pelo valor do índice na data. Função dos relatórios em outra moeda. Pedro
      IF ((prcc IS NULL) OR (prcc = 0)) THEN
        BEGIN
          IF (prindice = 0) THEN
            BEGIN
            wsqlsaldos = wsqlsaldos||'sum(coalesce(tlan.bdvalor, 0)) as bdvalor , ';
              --#alt:131626 - Machado - valores sem conciliação
              wsqlsaldos = wsqlsaldos||'sum(case when (COALESCE(UPPER(TLAN.BDCONCC), ''FALSE'') <> ''TRUE'' or coalesce(TLAN.BDCONCILIACAOPENDENTE, 0) IN (2,3)) THEN TLAN.BDVALOR ELSE 0 end) as BDVALCONC,';
              wsqlsaldos = wsqlsaldos||'sum(case when (COALESCE(UPPER(TLAN.BDCONCD), ''FALSE'') <> ''TRUE'' or coalesce(TLAN.BDCONCILIACAOPENDENTE, 0) IN (1,3)) THEN TLAN.BDVALOR ELSE 0 end) as BDVALCOND,';
            END
          ELSE
            BEGIN
              wsqlsaldos = wsqlsaldos||'sum(tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
              wsqlsaldos = wsqlsaldos||'                            (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))) as bdvalor, ';
              --#alt:131626 - Machado - valores sem conciliação
              wsqlsaldos = wsqlsaldos||'NULL AS BDVALCONC, NULL AS BDVALCOND, ';
            END
        END
      ELSE
        BEGIN
          IF (prindice = 0) THEN
            BEGIN
            wsqlsaldos = wsqlsaldos||'sum(case when (tlcc.bdcodtpcc is null) then coalesce(tlan.bdvalor, 0) else coalesce(tlcc.bdvalor, 0) end) as bdvalor, ';
             --#alt:131626 - Machado - valores sem conciliação
             wsqlsaldos = wsqlsaldos||'NULL AS BDVALCONC, NULL AS BDVALCOND, ';
            END
          ELSE
            BEGIN
              wsqlsaldos = wsqlsaldos||'sum(case when (tlcc.bdcodtpcc is null) then coalesce(tlan.bdvalor, 0) else coalesce(tlcc.bdvalor, 0) end';
              wsqlsaldos = wsqlsaldos||'      / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
              wsqlsaldos = wsqlsaldos||'                 (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))) as bdvalor, ';
              --#alt:131626 - Machado - valores sem conciliação
              wsqlsaldos = wsqlsaldos||'NULL AS BDVALCONC, NULL AS BDVALCOND, ';
            END
        END
      --alt:6178 - Fim
      IF ((prcc IS NULL) OR (prcc = 0)) THEN
         wsqlsaldos = wsqlsaldos||'null as bdcodtpcc ,null as bddebcre ';
      ELSE
         wsqlsaldos = wsqlsaldos||'tlcc.bdcodtpcc, tlcc.bddebcre ';
      if (wzeramentosignorar <> '') then
        wsqlsaldos = wsqlsaldos||', tlan.bdchavezer ';

      wsqlsaldos = wsqlsaldos||'from vsuc_empresas_tlan tlan ';
      IF (NOT ((prcc IS NULL) OR (prcc = 0))) THEN
         BEGIN
           wsqlsaldos = wsqlsaldos||'left outer join vsuc_empresas_tlcc tlcc on (tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave ';
           IF ((prcc IS NOT NULL) AND (prcc <> 0)) THEN
              wsqlsaldos = wsqlsaldos||'and tlcc.bdcodtpcc = '||prcc;
           wsqlsaldos = wsqlsaldos||') ';
         END

      wsqlsaldos = wsqlsaldos||'where (tlan.bddata <= '''||prdatafim||''') ';
      if (PRSOMENTEMOVIMENTO = 1) then
        wsqlsaldos = wsqlsaldos||' AND (tlan.bddata >= '''||prdataini||''') ';

      --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
      IF (prcontabilizacao <> 99) THEN
        wsqlsaldos = wsqlsaldos||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
      wsqlsaldos = wsqlsaldos||'and (tlan.bdcodemp = '||prcodigoemp||') ';
      IF (PRTIPOLAN <> '') THEN --#212425
        wsqlsaldos = wsqlsaldos || ' and (tlan.bdtipolan in ('||PRTIPOLAN||'))';   
      wsqlsaldos = wsqlsaldos||'Group By tlan.bdcodemp,tlan.bdcredito,tlan.bddebito,tlan.bddata,tlan.bdtipolan ';
      IF (NOT ((prcc IS NULL) OR (prcc = 0))) THEN
         wsqlsaldos = wsqlsaldos||', tlcc.bdcodtpcc, tlcc.bddebcre ';
      if (wzeramentosignorar <> '') then
        wsqlsaldos = wsqlsaldos||', tlan.bdchavezer ';

      if (:PRELIMINACOESK300K315 = 1) then
        begin
          wsqlsaldos = wsqlsaldos||' union all';
          wsqlsaldos = wsqlsaldos||' select K300.BDCODEMPGRPECO, K310.BDDATAREF,';
          wsqlsaldos = wsqlsaldos||'        iif(ELIK310.BDSITELIMK315 = 0, null, K300.BDCODTPLA) BDCREDITO,';
          wsqlsaldos = wsqlsaldos||'        iif(ELIK310.BDSITELIMK315 = 1, null, K300.BDCODTPLA) BDDEBITO, 1 as BDTIPOLAN,';
          wsqlsaldos = wsqlsaldos||'        ELIK310.BDVLRELIMK315 as BDVALOR, null as BDVALCONC, null as BDVALCOND, null as BDCODTPCC,';
          wsqlsaldos = wsqlsaldos||'        null as BDDEBCRE';
          if (wzeramentosignorar <> '') then
            wsqlsaldos = wsqlsaldos||', null as bdchavezer ';
          wsqlsaldos = wsqlsaldos||' from VSUC_EMP_TLAN_SPED_K315 K315';
          wsqlsaldos = wsqlsaldos||' left join VSUC_EMP_TLAN_SPED_K300 K300 on (K300.BDCODK300 = K315.BDCODK300 and';
          wsqlsaldos = wsqlsaldos||'       K300.BDCODEMPGRPECO = K315.BDCODEMPGRPECO and';
          wsqlsaldos = wsqlsaldos||'       K300.BDCODGRPECO = K315.BDCODGRPECO)';
          wsqlsaldos = wsqlsaldos||' inner join VSUC_EMP_TLAN_SPED_K310 K310 on (K310.BDCODK300 = K315.BDCODK300 and';
          wsqlsaldos = wsqlsaldos||'       K310.BDCODEMPGRPECO = K315.BDCODEMPGRPECO and';
          wsqlsaldos = wsqlsaldos||'       K310.BDCODGRPECO = K315.BDCODGRPECO and';
          wsqlsaldos = wsqlsaldos||'       K310.BDCODK310 = K315.BDCODK310)';
          wsqlsaldos = wsqlsaldos||' left join VSUC_EMP_TLAN_SPED_K315 ELIK310 on (K310.BDCODK300 = ELIK310.BDCODK300 and';
          wsqlsaldos = wsqlsaldos||'       K310.BDCODEMPGRPECO = ELIK310.BDCODEMPGRPECO and';
          wsqlsaldos = wsqlsaldos||'       K310.BDCODGRPECO = ELIK310.BDCODGRPECO and';
          wsqlsaldos = wsqlsaldos||'       K310.BDCODK310 = ELIK310.BDCODK310)';
          wsqlsaldos = wsqlsaldos||' where K300.BDCODEMPGRPECO = '||PREMPRESAGRPECO||' and';
          wsqlsaldos = wsqlsaldos||'       K300.BDCODGRPECO = '||PRGRPECO||' and';
          wsqlsaldos = wsqlsaldos||'       K300.BDTIPCONT = 0 and';
          wsqlsaldos = wsqlsaldos||'       K315.BDCODTPLA is not null and';
          wsqlsaldos = wsqlsaldos||'       K310.BDDATAREF <= '''||prdatafim||'''';
          wsqlsaldos = wsqlsaldos||' group by K300.BDCODEMPGRPECO, BDCREDITO, BDDEBITO, K310.BDDATAREF, BDVALOR';
        end
    END

--  EXECUTE STATEMENT wsql;
  wsqlsaldos = '('||wsqlsaldos||')';

  -- retorna saldos da tabela temporária de saldos _____________________________
  wsql = '';
  wsql = wsql||'INSERT INTO VSUC_EMPRESAS_TBALANCETE_3 (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDANTERIOR_DEBITO_DRE, BDANTERIOR_DEBITO, BDVALOR_DEBITO_ANT_ZER, ';
  wsql = wsql||'BDVALOR_DEBITO, BDANTERIOR_CREDITO_DRE, BDANTERIOR_CREDITO, BDVALOR_CREDITO_ANT_ZER, ';
  wsql = wsql||'BDVALOR_CREDITO, BDVALOR_DEBITO_REAL, BDVALOR_CREDITO_REAL, BDSALDO_SEM_CONC, BDDATAULTLANC, BDCTALON, BDTIPCTA, BDGRPCTA,';
  wsql = wsql||'BDNOMCTA, BDRELCTA, BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA, bdpertenceconta) ';
  IF ((prcodplapadrao <> PRPLANOGRPECO) and (PRPLANOGRPECO <> 0)) THEN
    begin
      wsql = wsql||'SELECT '||PREMPRESAGRPECO||' as BDCODEMP, tplaprep.BDCODPLAPADRAO, tplaprep.BDCODTPLA, TBAL.BDANTERIOR_DEBITO_DRE, TBAL.BDANTERIOR_DEBITO, tbal.BDVALOR_DEBITO_ANT_ZER, TBAL.BDVALOR_DEBITO, TBAL.BDANTERIOR_CREDITO_DRE,';
      wsql = wsql||' TBAL.BDANTERIOR_CREDITO,tbal.BDVALOR_CREDITO_ANT_ZER, TBAL.BDVALOR_CREDITO, TBAL.BDVALOR_DEBITO_REAL, TBAL.BDVALOR_CREDITO_REAL, TBAL.BDSALDO_SEM_CONC, TBAL.BDDATA, tplaprep.BDCTALON, tplaprep.BDTIPCTA, tplaprep.BDGRUPOCTA, ';
      wsql = wsql||'tplaprep.BDNOMCTA, tplaprep.BDRELCTA, tplaprep.BDFORMULA, tplaprep.BDCLANOM, tplaprep.BDPARTICIPANTE, tplaprep.BDAPECTA, tplaprep.bdpertenceconta FROM (';
     end
  else
    begin
      wsql = wsql||'SELECT TBAL.*, tpla.BDCTALON, tpla.BDTIPCTA, tpla.BDGRUPOCTA, ';
      wsql = wsql||'tpla.BDNOMCTA, tpla.BDRELCTA, tpla.BDFORMULA, tpla.BDCLANOM, tpla.BDPARTICIPANTE, tpla.BDAPECTA, tpla.bdpertenceconta FROM (';
    end
  wsql = wsql||'SELECT BDCODEMP, '||PRCODPLAPADRAO||' as BDCODPLAPADRAO, BDCONTA, ';
  wsql = wsql||'SUM(IIF(BDTIPOSALDO = 1, BDVALOR_ANT_DRE, 0)) AS BDANTERIOR_DEBITO_DRE, ';
  wsql = wsql||'SUM(IIF(BDTIPOSALDO = 1, BDVALOR_ANT, 0)) AS BDANTERIOR_DEBITO, ';
  wsql = wsql||'SUM(IIF(BDTIPOSALDO = 1, BDVALOR_ANT_ZER, 0)) AS BDVALOR_DEBITO_ANT_ZER, ';
  wsql = wsql||'SUM(IIF(BDTIPOSALDO = 1, BDVALOR_ATU, 0)) AS BDVALOR_DEBITO, ';
  wsql = wsql||'SUM(IIF(BDTIPOSALDO = 0, BDVALOR_ANT_DRE, 0)) AS BDANTERIOR_CREDITO_DRE, ';
  wsql = wsql||'SUM(IIF(BDTIPOSALDO = 0, BDVALOR_ANT, 0)) AS BDANTERIOR_CREDITO, ';        
  wsql = wsql||'SUM(IIF(BDTIPOSALDO = 0, BDVALOR_ANT_ZER, 0)) AS BDVALOR_CREDITO_ANT_ZER, ';
  wsql = wsql||'SUM(IIF(BDTIPOSALDO = 0, BDVALOR_ATU, 0)) AS BDVALOR_CREDITO, ';    
  wsql = wsql||'SUM(IIF(BDTIPOSALDO = 1, bdvalor_atu_real, 0)) AS BDVALOR_DEBITO_REAL, ';
  wsql = wsql||'SUM(IIF(BDTIPOSALDO = 0, bdvalor_atu_real, 0)) AS BDVALOR_CREDITO_REAL, ';
  wsql = wsql||'SUM(IIF(BDTIPOSALDO = 1, BDVALCONC, -BDVALCONC)) AS BDSALDO_SEM_CONC, ';
  wsql = wsql||'MAX(BDDATA) as BDDATA FROM ( ';

  wsql = wsql||'select bdcodemp,IIF(BDTIPOSALDO = 1, BDDEBITO, bdcredito) as bdconta, BDTIPOSALDO, ';

  IF (prDRE = 1) THEN-- se for DRE o calculo do saldo anterior deve considerar zeramento para demonstrar
     wsql = wsql||'       sum(case when ((bddata >= '''||wDtUltZeramento||''' and bddata < '''||prdataini||''') and (bdtipolan <> 10)) then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant_dre, ';
  ELSE
     wsql = wsql||'       0 as bdvalor_ant_dre, ';

  IF ((wzeramentosignorar <> '') and (PRIGNZERPERANT = 0)) THEN
    wsql = wsql||'      sum(case when (bddata < '''||prdataini||''' and (bdtipolan <> 10 or bdchavezer not in ('||wzeramentosignorar||'))) then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';
  ELSE
  wsql = wsql||'      sum(case when (bddata < '''||prdataini||''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';

  IF ((wzeramentosignorar <> '') and (PRIGNZERPERANT = 1)) THEN
    wsql = wsql||'      sum(case when (bddata < '''||prdataini||''' and (bdtipolan <> 10 or bdchavezer not in ('||wzeramentosignorar||'))) then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant_zer, ';
  ELSE
  wsql = wsql||'      sum(case when (bddata < '''||prdataini||''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant_zer, ';

  IF ((wzeramentosignorar <> '') and (PRIGNZERPERANT = 0)) THEN
    wsql = wsql||'       sum(case when (bddata >= '''||prdataini||''' and (bdtipolan <> 10 or bdchavezer not in ('||wzeramentosignorar||'))) then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu, ';
  ELSE
  IF ((prignorazeramento = 1)  or (PRIGNZERPERANT = 1)) THEN
     wsql = wsql||'       sum(case when (bddata >= '''||prdataini||''' and bdtipolan <> 10) then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu, ';
  ELSE
     wsql = wsql||'       sum(case when (bddata >= '''||prdataini||''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu, ';

  wsql = wsql||'       sum(case when (bddata >= '''||prdataini||''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu_real, ';

  --#alt:131626 - Machado - valores sem conciliação
  IF ((wzeramentosignorar <> '') and (PRIGNZERPERANT = 0)) THEN
    wsql = wsql||'       sum(case when ((bdtipolan <> 10 or bdchavezer not in ('||wzeramentosignorar||'))) then coalesce(IIF(BDTIPOSALDO = 1, BDVALCOND, BDVALCONC), 0) else 0 end) as BDVALCONC, ';
  ELSE
  IF ((prignorazeramento = 1) or (PRIGNZERPERANT = 1)) THEN
     wsql = wsql||'       sum(case when ((bddata >= '''||prdataini||''' and bdtipolan <> 10) or (bddata < '''||prdataini||''')) then coalesce(IIF(BDTIPOSALDO = 1, BDVALCOND, BDVALCONC), 0) else 0 end) as BDVALCONC, ';
  ELSE
     wsql = wsql||'       sum(coalesce(IIF(BDTIPOSALDO = 1, BDVALCOND, BDVALCONC), 0)) as BDVALCONC, ';

  wsql = wsql||'MAX(BDDATA) as BDDATA ';
  wsql = wsql||'from '||wsqlsaldos||' tlan ';

  wsql = wsql||'LEFT OUTER JOIN (SELECT 1 AS BDTIPOSALDO FROM rdb$database UNION ALL SELECT 0 AS BDTIPOSALDO FROM rdb$database) TLANAUX ON (1=1) ';
  wsql = wsql||'GROUP BY BDCODEMP, BDCONTA, BDTIPOSALDO) ';
  wsql = wsql||'where bdconta is not null ';
  wsql = wsql||'GROUP BY BDCODEMP, BDCONTA) TBAL ';
  wsql = wsql||' left outer join planos_tpla tpla on ('||PRCODPLAPADRAO||' = tpla.bdcodplapadrao and TBAL.BDCONTA = tpla.bdcodtpla) ';
  --alt:10233 - Implementada a validação das contas de compensação aqui, para poder diferenciar se a conta que está sendo calculada é de débito ou crédito. Pedro
  IF ((prcodplapadrao <> PRPLANOGRPECO) and (PRPLANOGRPECO <> 0)) THEN
    begin
      wsql = wsql||'left outer join VSUC_PREPARACAO_GRUPOECONOMICO prep on ((TPLA.bdcodplapadrao = prep.bdcodplapadrao) and (TPLA.bdcodtpla = prep.bdcodtpla) and (prep.bdcodemp = '||prempresagrpeco||') and (prep.bdcodgrpeco = '||prgrpeco||')) ';
      wsql = wsql||'left outer join PLANOS_TPLA TPLAprep on (TPLAprep.bdcodplapadrao = prep.bdcodplapadraoprep) and (TPLAprep.bdcodtpla = prep.bdcodtplaprep) ';
    end

  if (((prcodplapadrao <> PRPLANOGRPECO) and (PRPLANOGRPECO <> 0)) and (prnaomostracontacomp = 1))then
    wsql = wsql||'where (tplaprep.BDCODTPLA is not null) and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = '''||'FALSE'||''')) ';
  else
  if ((prcodplapadrao <> PRPLANOGRPECO) and (PRPLANOGRPECO <> 0)) then
    wsql = wsql||'where (tplaprep.BDCODTPLA is not null)';
  else
  if (prnaomostracontacomp = 1) then
    wsql = wsql||'where ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = '''||'FALSE'||''')) ';

  -- insere os saldos na tabela temporária do balancete ________________________
  DELETE FROM vsuc_empresas_tbalancete_3;
  EXECUTE STATEMENT wsql;

  -- faz o select na tabela temporária de balancete e monta os retornos para a impressao
  wSQL = 'SELECT  TPLA.bdcodplapadrao, TPLA.bdcodtpla, TPLA.bdctalon, TPLA.bdtipcta, TPLA.bdgrupocta, TPLA.bdnomcta,';
  wSQL = wSQL||'  COALESCE(bdvalor_debito, 0), COALESCE(bdvalor_credito, 0), ';
  wSQL = wSQL||'  COALESCE(bdanterior_debito, 0), COALESCE(bdanterior_credito, 0),';
  wSQL = wSQL||'  COALESCE(bdanterior_debito_dre, 0), COALESCE(bdanterior_credito_dre, 0),';
  wSQL = wSQL||'  COALESCE(BDVALOR_DEBITO_REAL, 0), COALESCE(BDVALOR_CREDITO_REAL, 0),';    
  wSQL = wSQL||'  COALESCE(BDVALOR_DEBITO_ANT_ZER, 0), COALESCE(BDVALOR_CREDITO_ANT_ZER, 0),';
  wSQL = wSQL||'  TPLA.bdformula, TPLA.bdrelcta, TPLA.bdclanom,';
  --alt:7866 - 27/10/2015 - Caso tenha a opção de detalhar por participantes específicos, precisa verificar aqui se o em questão
  --está marcado ou não para retornar como conta participante, para depois a VSUC_SP_RETORNA_BALANCETE detalhar ou não. Pedro
  IF ((wSelectContas IS NOT NULL) AND (wSelectContas > 0)) THEN
    wSQL = wSQL||' case when lista.BDCODTPLA is null then 0 else TPLA.BDPARTICIPANTE end as BDPARTICIPANTE,';
  ELSE
    wSQL = wSQL||' TPLA.bdparticipante,';
  wSQL = wSQL||' TPLA.bdapecta, TPLA.bdpertenceconta, COALESCE(BDSALDO_SEM_CONC, 0),';
  wSQL = wSQL||' TBAL.BDDATAULTLANC';

  wSQL = wSQL||' FROM PLANOS_TPLA TPLA';

  IF ((prcodplapadrao <> PRPLANOGRPECO) and (PRPLANOGRPECO <> 0)) THEN
    wSQL = wSQL||' LEFT JOIN vsuc_empresas_tbalancete_3 tbal ON (TBAL.bdcodemp = '||prempresagrpeco||' and TPLA.bdcodplapadrao = TBAL.bdcodplapadrao AND TPLA.bdcodtpla = tbal.bdcodtpla)';
  else
    wSQL = wSQL||' LEFT JOIN vsuc_empresas_tbalancete_3 tbal ON (TBAL.bdcodemp = '||prcodigoemp||' and TPLA.bdcodplapadrao = TBAL.bdcodplapadrao AND TPLA.bdcodtpla = tbal.bdcodtpla)';

  IF ((wSelectContas IS NOT NULL) AND (wSelectContas > 0)) THEN
    wSQL = wSQL||' left join VSUC_SELECT_CONTAS lista on (tbal.BDCODPLAPADRAO = lista.BDCODPLAPADRAO and tbal.BDCODTPLA = lista.BDCODTPLA)';
  --alt:7866 - Fim
  
  IF ((prcodplapadrao <> PRPLANOGRPECO) and (PRPLANOGRPECO <> 0)) THEN
    wSQL = wSQL||' WHERE TPLA.bdcodplapadrao = '||prplanogrpeco;
  else
    wSQL = wSQL||' WHERE TPLA.bdcodplapadrao = '||prcodplapadrao;

    wSQL = wSQL||' AND TPLA.bdctalon BETWEEN '''||:wclassini||''' AND '''||:wclassfin||'''';


  if (PRLANCSEMCC = 0 AND PRTODOPLANOCONTAS = 0) then
    wSQL = wSQL||' AND (TPLA.bdtipcta <> 1 OR TBAL.bdcodemp IS NOT NULL or coalesce(TPLA.bdformula, '''') <> '''')';

  wSQL = wSQL||' ORDER BY TPLA.bdcodplapadrao, TPLA.bdctalon ';

  WULTIMOCONSOLIDADA = 'A';
  FOR EXECUTE STATEMENT wSQL INTO :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta, :wgrpcta, :wnomcta,
       :wsaldo_debito, :wsaldo_credito, :wanterior_debito, :wanterior_credito, :wanterior_debito_dre, :wanterior_credito_dre,
       :wvalor_debito_real, :wvalor_credito_real, :wVALOR_debito_ANT_ZER, :wVALOR_CREDITO_ANT_ZER,
       :formula, :relconta , :clanom, :wparticipante, :wapecta, :wpertenceconta, :WSALDO_NAO_CONCILIADO, :dataultlancamento DO
      BEGIN
        if (wtipcta = 2 AND NOT wclassificacao STARTING WITH wultimoconsolidada) then wultimoconsolidada = wclassificacao||'.';

        IF (NOT (((prconsolidada IS NULL) OR (prconsolidada = 0)) AND (wclassificacao starting with wultimoconsolidada))) then
          BEGIN
            codemp = :prcodigoemp;
            codplapadrao = :wcodigoplano;
            conta  = :wcodtpla;
            classificacao = :wclassificacao;
            nomeconta = :wnomcta;
            tipconta = :wtipcta;
            grupoconta = :wgrpcta;
            participante = :wparticipante;
    
            if ((wtipcta <> 1) and (prcodplapadrao <> PRPLANOGRPECO) and (PRPLANOGRPECO <> 0))then
              begin
                  SELECT coalesce(SUM(bdvalor_debito), 0), coalesce(SUM(bdvalor_credito), 0), coalesce(SUM(bdanterior_debito), 0), coalesce(SUM(bdanterior_credito), 0),
                  coalesce(SUM(bdanterior_debito_dre), 0), coalesce(SUM(bdanterior_credito_dre), 0),
                  COALESCE(SUM(BDVALOR_DEBITO_REAL), 0), COALESCE(SUM(BDVALOR_CREDITO_REAL), 0),
                  COALESCE(SUM(BDVALOR_debito_ANT_ZER), 0), COALESCE(SUM(BDVALOR_credito_ANT_ZER), 0),
                  coalesce(SUM(BDSALDO_SEM_CONC), 0), MAX(BDDATAULTLANC)
                  FROM vsuc_empresas_tbalancete_3 tbal
                  WHERE tbal.bdcodemp = :PREMPRESAGRPECO AND TBAL.bdcodplapadrao = :PRPLANOGRPECO AND TBAL.bdctalon STARTING WITH :wclassificacao||'.'
                  INTO :wsaldo_debito, :wsaldo_credito, :wanterior_debito, :wanterior_credito, :wanterior_debito_dre, :wanterior_credito_dre, :wvalor_debito_real,
                       :wvalor_credito_real, :wVALOR_debito_ANT_ZER, :wVALOR_credito_ANT_ZER, :WSALDO_NAO_CONCILIADO, :dataultlancamento;
              end
            else
            if (wtipcta <> 1) then
              begin
                  SELECT coalesce(SUM(bdvalor_debito), 0), coalesce(SUM(bdvalor_credito), 0), coalesce(SUM(bdanterior_debito), 0), coalesce(SUM(bdanterior_credito), 0),
                  coalesce(SUM(bdanterior_debito_dre), 0), coalesce(SUM(bdanterior_credito_dre), 0),
                  COALESCE(SUM(BDVALOR_DEBITO_REAL), 0), COALESCE(SUM(BDVALOR_CREDITO_REAL), 0), 
                  COALESCE(SUM(BDVALOR_debito_ANT_ZER), 0), COALESCE(SUM(BDVALOR_credito_ANT_ZER), 0),
                  coalesce(SUM(BDSALDO_SEM_CONC), 0), MAX(BDDATAULTLANC)
                  FROM vsuc_empresas_tbalancete_3 tbal
                  WHERE tbal.bdcodemp = :prcodigoemp AND TBAL.bdcodplapadrao = :wcodigoplano AND TBAL.bdctalon STARTING WITH :wclassificacao||'.'
                  INTO :wsaldo_debito, :wsaldo_credito, :wanterior_debito, :wanterior_credito, :wanterior_debito_dre, :wanterior_credito_dre, :wvalor_debito_real,
                       :wvalor_credito_real, :wVALOR_debito_ANT_ZER, :wVALOR_credito_ANT_ZER, :WSALDO_NAO_CONCILIADO, :dataultlancamento;
              end
    
            saldo_ant_deb = wanterior_debito;
            saldo_ant_cre = :wanterior_credito;
            saldo_ant_deb_dre = :wanterior_debito_dre;
            saldo_ant_cre_dre = :wanterior_credito_dre;
            saldo_deb = :wsaldo_debito;
            SALDO_SEM_CONCILIACAO = :WSALDO_NAO_CONCILIADO;
            saldo_cre = :wsaldo_credito;
            apecta = :wapecta;
            pertenceconta = :wpertenceconta;
    
            IF (wgrpcta IN (1,2,3)) THEN
               BEGIN
                 saldo_anterior = (wanterior_credito - wanterior_debito);
                 saldo_anterior_dre = (wanterior_credito_dre - wanterior_debito_dre);
                 saldo_atual = (saldo_anterior + :wsaldo_credito - :wsaldo_debito);
                 SALDO_SEM_CONCILIACAO = -SALDO_SEM_CONCILIACAO;
                 SALDO_ATUAL_REAL = (saldo_anterior + :wvalor_credito_real - :wvalor_debito_real);
                 if (PRIGNZERPERANT = 1) then
                   saldo_anterior = (wVALOR_credito_ANT_ZER - wVALOR_debito_ANT_ZER);
               END
            ELSE
               BEGIN
                 saldo_anterior = (wanterior_debito - wanterior_credito);
                 saldo_anterior_dre = (wanterior_debito_dre - wanterior_credito_dre);
                 saldo_atual = (saldo_anterior + :wsaldo_debito - :wsaldo_credito);
                 SALDO_ATUAL_REAL = (saldo_anterior + :wvalor_debito_real - :wvalor_credito_real);
                 if (PRIGNZERPERANT = 1) then
                   saldo_anterior = (wVALOR_debito_ANT_ZER - wVALOR_credito_ANT_ZER);
               END

            if ((codplapadrao <> PRPLANOGRPECO) and (PRPLANOGRPECO <> 0))then
               begin
                 codemp = prcodigoemp;
                 codplapadrao = prcodplapadrao;
               end
    
            -- Filtro pelo nível da conta __________________________________________
            wnivelconta = 1;
            wCont = 1;
            WHILE (wcont <= CHAR_LENGTH(wclassificacao)) DO
              BEGIN
                IF (SUBSTRING(wclassificacao FROM wcont FOR 1) = '.') THEN
                   wnivelconta = wnivelconta + 1;
                wcont = wcont + 1;
              END
            --#alt:141589 - 31/08/2020 - Machado - Quando detalhar consolidada e remover as analíticas deve emitir as contas consolidadoras
            WTIPOCONTANIVEL = wtipcta;
            if (WTIPOCONTANIVEL = 2) then
              BEGIN
                if (prconsolidada = 1) then
                  WTIPOCONTANIVEL = 0;
                ELSE
                  WTIPOCONTANIVEL = 1;
              END
    
            windice = POSITION(','||CAST(:wnivelconta AS VARCHAR(100))||',',','||:prniveisconta||',');
            -- Se encontrar no prNiveisConta o "1" significa que deve imprimir contas analíticas
            wimpanalitica = POSITION(',1,',','||:prniveisconta||',');
    
            --#alt:141889 - 14/09/2020 - Machado - Conta analítica/título/consolidadora mesmo nivel na emissão dos Relatórios e na Exportação da ECD
            if (wimpanalitica <= 0 AND prniveisconta <> '9999' AND WTIPOCONTANIVEL = 1) then
              begin
                WCLASSIFICACAO_REVERSE = REVERSE(CLASSIFICACAO);
                WPOSITION_PONTO = POSITION('.' IN WCLASSIFICACAO_REVERSE);
                if (WPOSITION_PONTO <= 0) then
                  WPOSITION_PONTO = 1;
    
                WCLASSIFICACAO_REVERSE = REVERSE(SUBSTRING(WCLASSIFICACAO_REVERSE FROM WPOSITION_PONTO));
                WPOSITION_PONTO = null;
                select first 1 1 from PLANOS_TPLA WHERE BDCODPLAPADRAO = :codplapadrao AND BDCTALON STARTING WITH :wclassificacao_reverse AND BDTIPCTA IN (0,iif(:prconsolidada = 1, 2, 0)) INTO :wposition_ponto;
                if (wposition_ponto = 1) then
                  WTIPOCONTANIVEL = 0;
              end
    
            IF ((prniveisconta = '9999') OR           -- Não tem filtro
                (wnivelconta = 1) OR                  -- O primeiro nível sempre imprime
                ((windice > 0) AND (:WTIPOCONTANIVEL = 0)) OR -- O nível da conta foi selecionado no filtro e é título
                --Ele remove as consolidadas tambem, caso contrario pode dar problemas com o ECD/J100 e as contas bancarias
                (((windice > 0) AND (wimpanalitica > 0) AND (:WTIPOCONTANIVEL = 1)))) THEN -- É do nível selecionado, analítica e foi selecionado para imprimir as contas analíticas
               SUSPEND;
           END
      END

  -- limpa tabela temporária do balancete ______________________________________
  --delete from vsuc_empresas_tbalancete_3 where bdcodemp is not null;
  if (wBALANCETES_RODANDO_LIMITE > 0) then
    IN AUTONOMOUS TRANSACTION DO update TPARAMETRO set bdVALORINT = bdVALORINT - 1 where bdPARAM='BALANCETES_RODANDO';

  WHEN ANY DO
  BEGIN
    if (wBALANCETES_RODANDO_LIMITE > 0) then
      IN AUTONOMOUS TRANSACTION DO update TPARAMETRO set bdVALORINT = bdVALORINT - 1 where bdPARAM='BALANCETES_RODANDO';
    EXCEPTION;
  END
  --#alt:155149 - Fim;
END
^

/* Restore proc. body: VSUC_SP_RETORNA_SALDO_CONTAS_XZ */
create or alter procedure VSUC_SP_RETORNA_SALDO_CONTAS_XZ (
    PRCODIGOEMP integer,
    PRCONTAINICIAL integer,
    PRCONTAFINAL integer,
    PRDATAINI date,
    PRDATAFIM date,
    PRINDICE integer,
    PRIGNORAZERAMENTO integer,
    PRCC varchar(32000),
    PRCODPLAPADRAO integer,
    PRLANCSEMCC integer,
    PRORDEM integer,
    PRNAOMOSTRACONTACOMP integer,
    PRCONSOLIDADA integer,
    PRNIVEISCONTA varchar(50),
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLIDADO integer,
    PRDRE integer = 0,
    PRNIVELCC integer = 0,
    PRSOMENTEMOVIMENTO integer = 0,
    PRDETALHARCCEMPREEND integer = 0,
    PRCODEMPREENDIMENTO varchar(32000) = '' /* COLLATE WIN1252 - default */ ,
    PRTIPOLAN varchar(3200) = '',
    PRELIMINACOESK300K315 integer = 0)
returns (
    BDCODEMP integer,
    BDCODPLAPADRAO integer,
    BDCONTA integer,
    BDCLASSIFICACAO varchar(40),
    BDNOMECONTA varchar(100),
    BDGRUPOCONTA smallint,
    BDRELCONTA integer,
    BDCLANOM varchar(140),
    BDTIPCONTA smallint,
    BDSALDO_ANT_DEB numeric(15,2),
    BDSALDO_ANT_CRE numeric(15,2),
    BDSALDO_DEB numeric(15,2),
    BDSALDO_CRE numeric(15,2),
    BDSALDO_ATUAL numeric(15,2),
    BDSALDO_ANTERIOR numeric(15,2),
    BDFORMULA varchar(200),
    BDPARTICIPANTE integer,
    BDAPECTA varchar(20),
    BDPERTENCECONTA integer,
    BDSALDO_ANT_DEB_DRE numeric(15,2),
    BDSALDO_ANT_CRE_DRE numeric(15,2),
    BDSALDO_ANTERIOR_DRE numeric(15,2),
    BDCODTPCC integer,
    BDNOMTPCC varchar(40),
    BDTPCCLON varchar(20),
    BDSALDO_ATUAL_REAL numeric(15,2),
    BDFILTROCC varchar(200),
    BDDATAULTLANC date)
as
declare variable WGRPCTA integer;
declare variable WCLASSIFICACAO varchar(40);
declare variable WCODIGOPLANO integer;
declare variable WRELCTA integer;
declare variable WCLANOM varchar(140);
declare variable WTIPCTA smallint;
declare variable WCODTPLA integer;
declare variable WNOMCTA varchar(100);
declare variable WSALDO_DEBITO numeric(15,2);
declare variable WSALDO_CREDITO numeric(15,2);
declare variable WANTERIOR_DEBITO numeric(15,2);
declare variable WANTERIOR_CREDITO numeric(15,2);
declare variable WSQL varchar(32000);
declare variable WCLASSINI varchar(40);
declare variable WCLASSFIN varchar(40);
declare variable WFORMULA varchar(10240);
declare variable WCTALON varchar(40);
declare variable WPARTICIPANTE integer;
declare variable WNIVELCONTA integer;
declare variable WIMPANALITICA integer;
declare variable WINDICE integer;
declare variable WAPECTA varchar(20);
declare variable WPERTENCECONTA integer;
declare variable WDTULTZERAMENTO date;
declare variable WSQL_AUX varchar(32000);
declare variable WANTERIOR_DEBITO_DRE numeric(15,2);
declare variable WANTERIOR_CREDITO_DRE numeric(15,2);
declare variable WCONT integer;
declare variable WCODTPCC integer;
declare variable WNOMTPCC varchar(40);
declare variable WTPCCLON varchar(20);
declare variable WSELECTCONTAS integer;
declare variable WCENTROCUSTO integer;
declare variable WTIPOCONTANIVEL smallint;
declare variable WCLASSIFICACAO_REVERSE DM_CLASSCONTAS;
declare variable WPOSITION_PONTO integer;
declare variable WVALOR_CREDITO_REAL numeric(15,2);
declare variable WVALOR_DEBITO_REAL numeric(15,2);
declare variable WZERAMENTOSIGNORAR varchar(200);
declare variable WFILTROCC varchar(200);
declare variable WEMPREENDIMENTO integer;
declare variable WEMPREENATU integer;
declare variable WCCATU integer;
declare variable WJOINDEB varchar(300);
declare variable WJOINCRE varchar(300);
declare variable WWHERE varchar(500);
begin

  -- retorno da classificação inicial __________________________________________
  select PLANOS_TPLA.BDCTALON
  from PLANOS_TPLA
  where PLANOS_TPLA.BDCODPLAPADRAO = :PRCODPLAPADRAO and
        PLANOS_TPLA.BDCODTPLA = :PRCONTAINICIAL
  order by PLANOS_TPLA.BDCTALON
  into :WCLASSINI;

  -- retorno da classificação final ____________________________________________
  select PLANOS_TPLA.BDCTALON
  from PLANOS_TPLA
  where PLANOS_TPLA.BDCODPLAPADRAO = :PRCODPLAPADRAO and
        PLANOS_TPLA.BDCODTPLA = :PRCONTAFINAL
  order by PLANOS_TPLA.BDCTALON
  into :WCLASSFIN;
  select first 1 PLANOS_TPLA.BDCTALON
  from PLANOS_TPLA
  where PLANOS_TPLA.BDCODPLAPADRAO = :PRCODPLAPADRAO and
        substring(PLANOS_TPLA.BDCTALON from 1 for character_length(:WCLASSFIN)) = :WCLASSFIN
  order by PLANOS_TPLA.BDCTALON desc
  into :WCLASSFIN;

  --alt:7866 - 27/10/2015 - Pedro
  -- carrega se tem alguma conta específica selecionada ________________________
  select first 1 BDCODTPLA
  from VSUC_SELECT_CONTAS
  into :WSELECTCONTAS;

  --Insere o nome e a classificação do centro de custo
  --Machado - 04/01/2019 - #91350 - Só preciso pegar o plano de CC uma vez
  select BDCODCENTROS
  from VW_EMPRESAS_REF_ATUAL
  where BDCODEMP = :PRCODIGOEMP
  into :WCENTROCUSTO;

  if ((PRDRE <> 0) and
      (PRDRE is not null)) then
  begin
    -- Retorna o último zeramento
    select first 1 BDDATAINIZER
    from VSUC_EMPRESAS_TENCEXE
    where BDCODEMP = :PRCODIGOEMP and
          BDDATAFIMZER < :PRDATAINI
    order by BDDATAFIMZER desc
    into :WDTULTZERAMENTO;
    if (WDTULTZERAMENTO is null) then
      select first 1 BDDATA
      from VSUC_EMPRESAS_TLAN
      where BDCODEMP = :PRCODIGOEMP
      order by BDDATA
      into :WDTULTZERAMENTO;
    if (WDTULTZERAMENTO is null) then
      WDTULTZERAMENTO = :PRDATAINI;

    -- Limpa tabela temporária de contas com zeramento
    delete from VSUC_EMP_TCTAZERADAS
    where BDCODEMP is not null;
    -- Povoa tabela temporária de contas com zeramento
    WSQL = 'Insert into VSUC_EMP_TCTAZERADAS ';
    WSQL = WSQL || 'Select bdcodemp,bdcodcta from (Select tlan.bdcodemp, tlan.bdcredito bdcodcta';
    WSQL = WSQL || '                               from VSUC_EMPRESAS_TLAN tlan';
    WSQL = WSQL || '                               where';
    WSQL = WSQL || '                               (tlan.bddata <= ''' || PRDATAINI || ''') and';
    WSQL = WSQL || '                               (tlan.bdcodemp = ' || PRCODIGOEMP || ') and';
    WSQL = WSQL || '                               (tlan.bdcredito is not null) and';
    WSQL = WSQL || '                               (tlan.bdtipolan = 10)';
    WSQL = WSQL || '                               Group By bdcodemp, bdcodcta';
    WSQL = WSQL || '                               union all';
    WSQL = WSQL || '                               Select tlan.bdcodemp, tlan.bddebito bdcodcta';
    WSQL = WSQL || '                               from VSUC_EMPRESAS_TLAN tlan';
    WSQL = WSQL || '                               where';
    WSQL = WSQL || '                               (tlan.bddata <= ''' || PRDATAINI || ''') and';
    WSQL = WSQL || '                               (tlan.bdcodemp = ' || PRCODIGOEMP || ') and';
    WSQL = WSQL || '                               (tlan.bddebito is not null) and';
    WSQL = WSQL || '                               (tlan.bdtipolan = 10)';
    WSQL = WSQL || '                               Group By bdcodemp, bdcodcta) ';
    WSQL = WSQL || 'Group by bdcodemp,bdcodcta';
    execute statement WSQL;
  end

  WZERAMENTOSIGNORAR = '';
  if (PRIGNORAZERAMENTO = 2) then
    select list(E.BDCHAVEZER, ',')
    from TMP_VSUC_EMPRESAS_TENCEXE E
    where E.BDCODEMP = :PRCODIGOEMP
    into :WZERAMENTOSIGNORAR;

  if (prdetalharccempreend = 1) then
    begin
      if (position(',',PRCODEMPREENDIMENTO) > 0) then
        begin
          wempreendimento = substring(PRCODEMPREENDIMENTO from 1 for position(',',PRCODEMPREENDIMENTO)-1);
          PRCODEMPREENDIMENTO = substring(PRCODEMPREENDIMENTO from position(',',PRCODEMPREENDIMENTO)+1 for character_length(PRCODEMPREENDIMENTO));
        end
      else
        wempreendimento = PRCODEMPREENDIMENTO;
    end
  else
    PRCODEMPREENDIMENTO = 0;

  WHILE (PRCODEMPREENDIMENTO <> '') DO
    begin
      -- limpa tabela temporaria de saldos _________________________________________
      delete from VSUC_EMP_TSALDOS
      where BDCODEMP is not null;
      -- povoa tabela temporária de saldos _________________________________________

      if (prdetalharccempreend = 1) then
        begin
          SELECT first 1 cc.BDCODTPCC, EMP.bdcodempreendimento
          from VEF_EMP_TCADEMPREENDIMENTO EMP
            left join CENTROS_TPCC CC on (EMP.BDCODCENTRO = CC.BDCODCENTRO and
                  EMP.BDCODTPCC = CC.BDCODTPCC)
            where (emp.BDCODEMP = :PRCODIGOEMP and
                   emp.BDCODEMPREENDIMENTO = :wempreendimento)
          INTO :WCCATU, :WEMPREENATU;

          if (:WCCATU is null) then
            :WCCATU = 0;
          if (:WEMPREENATU is null) then
            :WEMPREENATU = 0;
          else
            :wempreenatu = wempreendimento;
       end

      WSQL = '';
      if ((PRLANCSEMCC = 1) and
          ((PRCC is not null) and
          (PRCC <> ''))) then
      begin
        WSQL_AUX = 'where (tlan.bddata <= ''' || PRDATAFIM || ''') ';
        if (PRSOMENTEMOVIMENTO = 1) then
          WSQL_AUX = WSQL_AUX || ' AND (tlan.bddata >= ''' || PRDATAINI || ''') ';
        --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
        if (PRCONTABILIZACAO <> 99) then
          WSQL_AUX = WSQL_AUX || 'and (tlan.bdcontabilizacao in (0,' || PRCONTABILIZACAO || ')) ';
        IF (PRTIPOLAN <> '') THEN --#212425
          WSQL_AUX = WSQL_AUX || ' and (tlan.bdtipolan in ('||PRTIPOLAN||'))';
        WSQL_AUX = WSQL_AUX || 'and (tlan.bdcodemp = ' || PRCODIGOEMP || ') ';
    
        --Débito
        WSQL = WSQL || 'select tlan.bdcodemp,tlan.bddata,tlan.bdcredito as BDCREDITO,tlan.bddebito,tlan.bdtipolan, ';
        WSQL = WSQL || 'sum(coalesce(tlan.bdvalor, 0)) as BDVALOR, null as BDCODTPCC, null as BDDEBCRE ';
        if (WZERAMENTOSIGNORAR <> '') then
          WSQL = WSQL || ', tlan.bdchavezer';
    
        WSQL = WSQL || ', MAX(BDDATA) as bddataultlanc ';
        WSQL = WSQL || 'from ';
        WSQL = WSQL || '     (select tlan.bdcodemp,tlan.bdchave,tlan.bddata,null as bdcredito,tlan.bddebito,tlan.bdtipolan, ';
        --alt:6178 - 09/11/2015 - Verifica se foi informado um índice, caso positivo, divide o valor do lançamento pelo valor do índice na data. Função dos relatórios em outra moeda. Pedro
        if (PRINDICE = 0) then
          WSQL = WSQL || 'tlan.bdvalor ';
        else
        begin
          WSQL = WSQL || 'tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          WSQL = WSQL || '                        (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) as bdvalor ';
        end
        if (WZERAMENTOSIGNORAR <> '') then
          WSQL = WSQL || ', tlan.bdchavezer';
        --alt:6178 - Fim
    
        WSQL = WSQL || '     from vsuc_empresas_tlan tlan ';
    
        WSQL = WSQL || WSQL_AUX;
    
        WSQL = WSQL || ') tlan ';
        WSQL = WSQL || 'left outer join vsuc_empresas_tlcc tlcc on (tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave and tlcc.bddebcre = 0) ';
        WSQL = WSQL || 'where (tlcc.bddebcre is null) ';
        WSQL = WSQL || 'Group By tlan.bdcodemp,tlan.bdcredito,tlan.bddebito,tlan.bddata,tlan.bdtipolan ';
        if (WZERAMENTOSIGNORAR <> '') then
          WSQL = WSQL || ', tlan.bdchavezer ';
        WSQL = WSQL || 'union ';
        --Crédito
        WSQL = WSQL || 'select tlan.bdcodemp,tlan.bddata,tlan.bdcredito,tlan.bddebito,tlan.bdtipolan, ';
        WSQL = WSQL || 'sum(coalesce(tlan.bdvalor, 0)) as BDVALOR, null as BDCODTPCC, null as BDDEBCRE ';
        if (WZERAMENTOSIGNORAR <> '') then
          WSQL = WSQL || ', tlan.bdchavezer';
    
        WSQL = WSQL || ', MAX(BDDATA) as bddataultlanc ';
        WSQL = WSQL || 'from ';
        WSQL = WSQL || '     (select tlan.bdcodemp,tlan.bdchave,tlan.bddata,tlan.bdcredito,null as bddebito,tlan.bdtipolan, ';
        --alt:6178 - 09/11/2015 - Verifica se foi informado um índice, caso positivo, divide o valor do lançamento pelo valor do índice na data. Função dos relatórios em outra moeda. Pedro
        if (PRINDICE = 0) then
          WSQL = WSQL || 'tlan.bdvalor ';
        else
        begin
          WSQL = WSQL || 'tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          WSQL = WSQL || '                        (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) as bdvalor ';
        end
        if (WZERAMENTOSIGNORAR <> '') then
          WSQL = WSQL || ', tlan.bdchavezer ';
        --alt:6178 - Fim
    
        WSQL = WSQL || '     from vsuc_empresas_tlan tlan ';
    
        WSQL = WSQL || WSQL_AUX;
    
        WSQL = WSQL || ') tlan ';
        WSQL = WSQL || 'left outer join vsuc_empresas_tlcc tlcc on (tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave and tlcc.bddebcre = 1) ';
        WSQL = WSQL || 'where (tlcc.bddebcre is null) ';
        WSQL = WSQL || 'Group By tlan.bdcodemp,tlan.bdcredito,tlan.bddebito,tlan.bddata,tlan.bdtipolan ';
        if (WZERAMENTOSIGNORAR <> '') then
          WSQL = WSQL || ', tlan.bdchavezer ';
    
        WSQL = WSQL || ' union all ';
      end
    
      if ((PRCC is not null) and
          (PRCC <> '')) then
      begin
        WSQL = WSQL || 'select tlan.bdcodemp,tlan.bddata,tlan.bdcredito,tlan.bddebito,tlan.bdtipolan, ';
        if ((PRCC is null) or (PRCC = '')) then
        begin
          --alt:6178 - 09/11/2015 - Verifica se foi informado um índice, caso positivo, divide o valor do lançamento pelo valor do índice na data. Função dos relatórios em outra moeda. Pedro
          if (PRINDICE = 0) then
            WSQL = WSQL || 'sum(coalesce(tlan.bdvalor, 0)) as BDVALOR, ';
          else
          begin
            WSQL = WSQL || 'sum(tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
            WSQL = WSQL || '                            (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))) as bdvalor, ';
          end
          --alt:6178 - Fim
        end
        else
        begin
          --alt:6178 - 09/11/2015 - Verifica se foi informado um índice, caso positivo, divide o valor do lançamento pelo valor do índice na data. Função dos relatórios em outra moeda. Pedro
          if (PRINDICE = 0) then
            begin
              if (prdetalharccempreend = 0) then
                WSQL = WSQL || 'sum(coalesce(tlcc.bdvalor, 0)) as bdvalor, ';
              else
                WSQL = WSQL || 'sum(coalesce(TLCC.BDVALOR, coalesce(tlan.bdvalor,0))) as bdvalor, ';
            end
          else
            begin
              WSQL = WSQL || 'sum(case when (tlcc.bdcodtpcc is null) then coalesce(tlan.bdvalor, 0) else coalesce(tlcc.bdvalor, 0) end';
              WSQL = WSQL || '      / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
              WSQL = WSQL || '                 (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))) as bdvalor, ';
            end
          --alt:6178 - Fim
        end
        if ((PRCC is null) or (PRCC = '')) then
          WSQL = WSQL || 'null, null ';
        else
          begin
            if (prdetalharccempreend = 0) then
              WSQL = WSQL || 'tlcc.bdcodtpcc, tlcc.bddebcre ';
            else
              WSQL = WSQL || :wccatu ||' AS BDCODTPCC, coalesce(TLCC.BDDEBCRE,tinc.bddebcre) as bddebcre ';
          end
        if (WZERAMENTOSIGNORAR <> '') then
          WSQL = WSQL || ', tlan.bdchavezer ';
    
        WSQL = WSQL || ', max(bddata) as bddataultlanc';
        if (prdetalharccempreend = 1) then
          WSQL = WSQL || ', TINC.BDCODEMPREENDIMENTO ';
        WSQL = WSQL || ' from vsuc_empresas_tlan tlan ';

        WJOINDEB = '';
        WJOINCRE = '';
        if (not((PRCC is null) or (PRCC = ''))) then
          begin
            if (prdetalharccempreend = 0) then
              begin
                WSQL = WSQL || 'inner join vsuc_empresas_tlcc tlcc on (tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave ';
            
                if ((PRCC is not null) and (PRCC <> '') and (char_length(PRCC) < 6000)) then
                  WSQL = WSQL || 'and tlcc.bdcodtpcc in (' || PRCC || ')';
            
                WSQL = WSQL || ') ';
              end
            else
              begin
                WJOINDEB = 'left join vsuc_empresas_tlcc tlcc on (tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave and TLCC.BDDEBCRE = 0) ';
                WJOINCRE = 'left join vsuc_empresas_tlcc tlcc on (tlcc.bdcodemp = tlan.bdcodemp and tlcc.bdchave = tlan.bdchave and TLCC.BDDEBCRE = 1) ';
              end
          end
    
        if (prdetalharccempreend = 1) then
          begin
            WJOINDEB = WJOINDEB || 'left join vsuc_empresas_tlincorp tinc on (tlan.BDCODEMP = tinc.BDCODEMP and tlan.BDCHAVE = tinc.BDCHAVE and TINC.BDDEBCRE = 0) ';
            WJOINCRE = WJOINCRE || 'left join vsuc_empresas_tlincorp tinc on (tlan.BDCODEMP = tinc.BDCODEMP and tlan.BDCHAVE = tinc.BDCHAVE and TINC.BDDEBCRE = 1) ';
          end
    
        WWHERE = 'where (tlan.bddata <= ''' || PRDATAFIM || ''') ';
        if (PRSOMENTEMOVIMENTO = 1) then
          WWHERE = WWHERE || ' AND (tlan.bddata >= ''' || PRDATAINI || ''') ';
        --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
        if (PRCONTABILIZACAO <> 99) then
          WWHERE = WWHERE || 'and (tlan.bdcontabilizacao in (0,' || PRCONTABILIZACAO || ')) ';
        IF (PRTIPOLAN <> '') THEN -- #212425
          WWHERE = WWHERE || ' and (tlan.bdtipolan in ('||PRTIPOLAN||'))';
    
        WWHERE = WWHERE || 'and (tlan.bdcodemp = ' || PRCODIGOEMP || ') ';
    
        if (prdetalharccempreend = 1) then
           WWHERE = WWHERE || 'and (tlcc.bdcodtpcc = ' || :wccatu || ' or (tinc.bdcodempreendimento = '||:wempreenatu||'))';
        WWHERE = WWHERE || 'Group By tlan.bdcodemp,tlan.bdcredito,tlan.bddebito,tlan.bddata,tlan.bdtipolan ';
    
        if (not((PRCC is null) or (PRCC = ''))) then
          if (prdetalharccempreend = 0) then
            WWHERE = WWHERE || ', tlcc.bdcodtpcc, TLCC.bddebcre ';
          else
            WWHERE = WWHERE || ', TLCC.bdcodtpcc, bddebcre, tinc.bdcodempreendimento';
    
        if (WZERAMENTOSIGNORAR <> '') then
          WWHERE = WWHERE || ', tlan.bdchavezer ';

        if (:PRELIMINACOESK300K315 = 1) then
        begin
          WWHERE = WWHERE||' union all';
          WWHERE = WWHERE||'        select K300.BDCODEMPGRPECO, K310.BDDATAREF,';
          WWHERE = WWHERE||'               iif(ELIK310.BDSITELIMK315 = 0, null, K300.BDCODTPLA) BDCREDITO,';
          WWHERE = WWHERE||'               iif(ELIK310.BDSITELIMK315 = 1, null, K300.BDCODTPLA) BDDEBITO, null as BDTIPOLAN,';
          WWHERE = WWHERE||'               ELIK310.BDVLRELIMK315 as BDVALOR, null as BDVALCONC, null as BDVALCOND, null as BDCODTPCC,';
          WWHERE = WWHERE||'               null as BDDEBCRE';
          if (WZERAMENTOSIGNORAR <> '') then
            WWHERE = WWHERE||',null as bdchavezer';
          WWHERE = WWHERE||'        from VSUC_EMP_TLAN_SPED_K315 K315';
          WWHERE = WWHERE||'        left join VSUC_EMP_TLAN_SPED_K300 K300 on (K300.BDCODK300 = K315.BDCODK300 and';
          WWHERE = WWHERE||'              K300.BDCODEMPGRPECO = K315.BDCODEMPGRPECO and';
          WWHERE = WWHERE||'              K300.BDCODGRPECO = K315.BDCODGRPECO)';
          WWHERE = WWHERE||'        inner join VSUC_EMP_TLAN_SPED_K310 K310 on (K310.BDCODK300 = K315.BDCODK300 and';
          WWHERE = WWHERE||'              K310.BDCODEMPGRPECO = K315.BDCODEMPGRPECO and';
          WWHERE = WWHERE||'              K310.BDCODGRPECO = K315.BDCODGRPECO and';
          WWHERE = WWHERE||'              K310.BDCODK310 = K315.BDCODK310)';
          WWHERE = WWHERE||'        left join VSUC_EMP_TLAN_SPED_K315 ELIK310 on (K310.BDCODK300 = ELIK310.BDCODK300 and';
          WWHERE = WWHERE||'              K310.BDCODEMPGRPECO = ELIK310.BDCODEMPGRPECO and';
          WWHERE = WWHERE||'              K310.BDCODGRPECO = ELIK310.BDCODGRPECO and';
          WWHERE = WWHERE||'              K310.BDCODK310 = ELIK310.BDCODK310)';
          WWHERE = WWHERE||'        where K300.BDCODEMPGRPECO = 4801 and';
          WWHERE = WWHERE||'              K300.BDCODGRPECO = 1 and';
          WWHERE = WWHERE||'              K300.BDTIPCONT = 0 and';
          WWHERE = WWHERE||'              K315.BDCODTPLA is not null';
          WWHERE = WWHERE||'        group by K300.BDCODEMPGRPECO, BDCREDITO, BDDEBITO, K310.BDDATAREF, BDVALOR';
        end

        WWHERE = WWHERE || ')';
      end
    
      -- Gilberto - 06/04/2015 - ALT:#9178 - inserido condição para verificar se a situação ocorre
      if (((PRLANCSEMCC = 1) and
          ((PRCC is not null) and
          (PRCC <> ''))) or ((PRCC is not null) and
          (PRCC <> ''))) then
        --Sol. 129419 - 17/12/2019 - Machado - Estava ficando lento depois de muitas execuções (Removido uso da tabela temporária)
        WSQL_AUX = '(' || WSQL;
      else
        WSQL_AUX = 'vsuc_emp_tsaldos';

      -- retorna saldos da tabela temporária de saldos _____________________________
      WSQL = '';
      WSQL = WSQL || 'select bdcodemp,bddebito, 1 as bdtipcta, coalesce(bdcodtpcc, null) as bdcodtpcc, ';
    
      if (PRDRE = 1) then -- se for DRE o calculo do saldo anterior deve considerar zeramento para demonstrar
        WSQL = WSQL || '       sum(case when ((bddata >= ''' || WDTULTZERAMENTO || ''' and bddata < ''' || PRDATAINI || ''') and (bdtipolan <> 10)) then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant_dre, ';
      else
        WSQL = WSQL || '       0 as bdvalor_ant_dre, ';
    
      WSQL = WSQL || '      sum(case when (bddata < ''' || PRDATAINI || ''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';
    
      if (WZERAMENTOSIGNORAR <> '') then
        WSQL = WSQL || '       sum(case when (bddata >= ''' || PRDATAINI || ''' and (bdtipolan <> 10 or bdchavezer not in (' || WZERAMENTOSIGNORAR || '))) then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu, ';
      else
      if (PRIGNORAZERAMENTO = 1) then
        WSQL = WSQL || '       sum(case when (bddata >= ''' || PRDATAINI || ''' and bdtipolan <> 10) then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu, ';
      else
        WSQL = WSQL || '       sum(case when (bddata >= ''' || PRDATAINI || ''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu, ';
    
      WSQL = WSQL || '       sum(case when (bddata >= ''' || PRDATAINI || ''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu_real, ';
      WSQL = WSQL || '       max(bddataultlanc) as bddataultlanc ';
    
      WSQL = WSQL || 'from ' || WSQL_AUX || WJOINDEB || WWHERE ||' tlan ';
    
      --alt:10233 - Implementada a validação das contas de compensação aqui, para poder diferenciar se a conta que está sendo calculada é de débito ou crédito. Pedro
      if (PRNAOMOSTRACONTACOMP = 1) then --alt:11108 - 08/04/2015 - Pedro
        WSQL = WSQL || 'left outer join PLANOS_TPLA tpla on (' || PRCODPLAPADRAO || ' = tpla.BDCODPLAPADRAO and tlan.BDDEBITO = tpla.BDCODTPLA) ';
    
      WSQL = WSQL || 'where (bddata <= ''' || PRDATAFIM || ''') ';
    
      --alt:10233 - Implementada a validação das contas de compensação aqui, para poder diferenciar se a conta que está sendo calculada é de débito ou crédito. Pedro
      if (PRNAOMOSTRACONTACOMP = 1) then --alt:11108 - 08/04/2015 - Pedro
        WSQL = WSQL || 'and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = ''' || 'FALSE' || ''')) ';
    
      if ((PRCC <> '') and
          (not(PRCC is null))) then
      begin
        WSQL = WSQL || 'and (BDDEBCRE = 0) ';
        if (char_length(PRCC) < 6000) then
         if (prdetalharccempreend = 0) then
           WSQL = WSQL || 'and (bdcodtpcc in (' || PRCC || ')) ';
         else
           WSQL = WSQL || 'and ((bdcodtpcc = ' || :WCCATU || ') or (tlan.bdcodempreendimento = '||:wempreenatu||'))';
    
        if (PRLANCSEMCC = 1) then
          WSQL = WSQL || 'or (bdcodtpcc is null) ';
        else
        if (prdetalharccempreend = 0) then
          WSQL = WSQL || 'and (bdcodtpcc is not null) ';
    
      end
      else
      if (PRLANCSEMCC = 1) then
        WSQL = WSQL || 'and (bdcodtpcc is null) '; -- somente sem centro de custo
    
      WSQL = WSQL || 'and (bdcodemp = ' || PRCODIGOEMP || ') ';
    
      WSQL = WSQL || 'Group By bdcodemp,bddebito, bdcodtpcc ';
      WSQL = WSQL || 'union all ';
      WSQL = WSQL || 'select bdcodemp,bdcredito, 0 as bdtipcta, coalesce(bdcodtpcc, null) as bdcodtpcc, ';
    
      if (PRDRE = 1) then -- se for DRE o calculo do saldo anterior deve considerar zeramento para demonstrar
        WSQL = WSQL || '       sum(case when ((bddata >= ''' || WDTULTZERAMENTO || ''' and bddata < ''' || PRDATAINI || ''') and (bdtipolan <> 10)) then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant_dre, ';
      else
        WSQL = WSQL || '       0 as bdvalor_ant_dre, ';
    
      WSQL = WSQL || '       sum(case when (bddata < ''' || PRDATAINI || ''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_ant, ';
    
      if (WZERAMENTOSIGNORAR <> '') then
        WSQL = WSQL || '       sum(case when (bddata >= ''' || PRDATAINI || ''' and (bdtipolan <> 10 or bdchavezer not in (' || WZERAMENTOSIGNORAR || '))) then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu, ';
      else
      if (PRIGNORAZERAMENTO = 1) then
        WSQL = WSQL || '       sum(case when (bddata >= ''' || PRDATAINI || ''' and bdtipolan <> 10) then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu, ';
      else
        WSQL = WSQL || '       sum(case when (bddata >= ''' || PRDATAINI || ''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu, ';
    
      WSQL = WSQL || '       sum(case when (bddata >= ''' || PRDATAINI || ''') then coalesce(bdvalor, 0) else 0 end) as bdvalor_atu_real, ';
      WSQL = WSQL || '       max(bddataultlanc) as bddataultlanc ';
    
      WSQL = WSQL || 'from ' || WSQL_AUX || WJOINCRE || WWHERE || ' tlan ';
    
      --alt:10233 - Implementada a validação das contas de compensação aqui, para poder diferenciar se a conta que está sendo calculada é de débito ou crédito. Pedro
      if (PRNAOMOSTRACONTACOMP = 1) then --alt:11108 - 08/04/2015 - Pedro
        WSQL = WSQL || 'left outer join PLANOS_TPLA tpla on (' || PRCODPLAPADRAO || ' = tpla.BDCODPLAPADRAO and tlan.BDCREDITO = tpla.BDCODTPLA) ';
    
      WSQL = WSQL || 'where (bddata <= ''' || PRDATAFIM || ''') ';
    
      --alt:10233 - Implementada a validação das contas de compensação aqui, para poder diferenciar se a conta que está sendo calculada é de débito ou crédito. Pedro
      if (PRNAOMOSTRACONTACOMP = 1) then --alt:11108 - 08/04/2015 - Pedro
        WSQL = WSQL || 'and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = ''' || 'FALSE' || ''')) ';
    
      if ((PRCC <> '') and
          (not(PRCC is null))) then
      begin
        WSQL = WSQL || 'and (BDDEBCRE = 1) ';
        if (char_length(PRCC) < 6000) then
         if (prdetalharccempreend = 0) then
           WSQL = WSQL || 'and (bdcodtpcc in (' || PRCC || ')) ';
         else
           WSQL = WSQL || 'and ((bdcodtpcc = ' || :WCCATU || ') or (tlan.bdcodempreendimento = '|| :wempreenatu ||'))';
    
        if (PRLANCSEMCC = 1) then
          WSQL = WSQL || 'or (bdcodtpcc is null) ';
        else
        if (prdetalharccempreend = 0) then
          WSQL = WSQL || 'and (bdcodtpcc is not null) ';
      end
      else
      if (PRLANCSEMCC = 1) then
        WSQL = WSQL || 'and (bdcodtpcc is null) '; -- somente sem centro de custo
    
      WSQL = WSQL || 'and (bdcodemp = ' || PRCODIGOEMP || ') ';
      WSQL = WSQL || 'Group By bdcodemp,bdcredito, bdcodtpcc ';
    
      --#alt:153018 - 04/08/2021 - Machado - Impressão dos CENTRO de CUSTO
      if (PRNIVELCC > 0) then
      begin
        WSQL_AUX = WSQL;
        WSQL = 'SELECT SAL.BDCODEMP, SAL.BDDEBITO, SAL.BDTIPCTA, PAI.BDCODTPCC, SAL.BDVALOR_ANT_DRE, SAL.BDVALOR_ANT, SAL.BDVALOR_ATU, SAL.bdvalor_atu_real, sal.BDDATAULTLANC';
        WSQL = WSQL || ' FROM (' || WSQL_AUX || ') SAL';
        WSQL = WSQL || ' LEFT OUTER JOIN centros_tpcc TPCC ON (TPCC.bdcodcentro = ' || WCENTROCUSTO || ' and tpcc.BDCODTPCC = SAL.BDCODTPCC) ';
        WSQL = WSQL || ' LEFT OUTER JOIN centros_tpcc PAI  ON (PAI.bdcodcentro = ' || WCENTROCUSTO || ' and PAI.bdctalon = (select BDCLASSIFICACAO FROM sp_get_classificacao_nivel(tpcc.bdctalon, ' || PRNIVELCC || '))) ';
      end
    
      WSQL_AUX = WSQL;
      WSQL = 'INSERT INTO VSUC_EMPRESAS_TBALANCETE_3 (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDGRPCTA, BDNOMCTA,'
          || ' BDANTERIOR_DEBITO_DRE, BDANTERIOR_DEBITO, BDVALOR_DEBITO, BDANTERIOR_CREDITO_DRE, BDANTERIOR_CREDITO, BDVALOR_CREDITO,'
          || ' BDVALOR_DEBITO_REAL, BDVALOR_CREDITO_REAL, BDCODTPCC,'
          || ' BDRELCTA, BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA, BDPERTENCECONTA, bddataultlanc)'
          || ' SELECT TBAL.BDCODEMP, TBAL.BDCODPLAPADRAO, TBAL.BDDEBITO, TPLA.BDCTALON, TPLA.BDTIPCTA, TPLA.BDGRUPOCTA, TPLA.BDNOMCTA,'
          || ' TBAL.BDANTERIOR_DEBITO_DRE, TBAL.BDANTERIOR_DEBITO, TBAL.BDVALOR_DEBITO, TBAL.BDANTERIOR_CREDITO_DRE,'
          || ' TBAL.BDANTERIOR_CREDITO, TBAL.BDVALOR_CREDITO, TBAL.BDVALOR_DEBITO_REAL, TBAL.BDVALOR_CREDITO_REAL, '
          || ' TBAL.BDCODTPCC, TPLA.BDRELCTA, TPLA.BDFORMULA, TPLA.BDCLANOM,'
          || ' TPLA.BDPARTICIPANTE, TPLA.BDAPECTA, TPLA.BDPERTENCECONTA, tbal.bddataultlanc'
          || ' FROM (SELECT BDCODEMP, ' || PRCODPLAPADRAO || ' AS BDCODPLAPADRAO, BDDEBITO, BDCODTPCC,'
          || ' SUM(IIF(BDTIPCTA = 1, BDVALOR_ANT_DRE, 0)) AS BDANTERIOR_DEBITO_DRE,'
          || ' SUM(IIF(BDTIPCTA = 1, BDVALOR_ANT, 0)) AS BDANTERIOR_DEBITO,'
          || ' SUM(IIF(BDTIPCTA = 1, BDVALOR_ATU, 0)) AS BDVALOR_DEBITO,'
          || ' SUM(IIF(BDTIPCTA = 0, BDVALOR_ANT_DRE, 0)) AS BDANTERIOR_CREDITO_DRE,'
          || ' SUM(IIF(BDTIPCTA = 0, BDVALOR_ANT, 0)) AS BDANTERIOR_CREDITO,'
          || ' SUM(IIF(BDTIPCTA = 0, BDVALOR_ATU, 0)) AS BDVALOR_CREDITO,'
          || ' SUM(IIF(BDTIPCTA = 1, bdvalor_atu_real, 0)) AS BDVALOR_DEBITO_REAL, '
          || ' SUM(IIF(BDTIPCTA = 0, bdvalor_atu_real, 0)) AS BDVALOR_CREDITO_REAL, '
          || ' max(bddataultlanc) as bddataultlanc '
          || ' FROM (' || WSQL_AUX || ') GROUP BY BDCODEMP, BDDEBITO, BDCODTPCC) TBAL'
          || ' LEFT OUTER JOIN PLANOS_TPLA TPLA ON (TBAL.BDCODPLAPADRAO = TPLA.BDCODPLAPADRAO AND TBAL.BDDEBITO = TPLA.BDCODTPLA)'
          || ' WHERE TBAL.BDDEBITO IS NOT NULL';
    
      -- insere os saldos na tabela temporária do balancete ________________________
      delete from VSUC_EMPRESAS_TBALANCETE_3;
      execute statement WSQL;
    
      if ((PRCC <> '') and
          (not(PRCC is null)) and
          (char_length(PRCC) >= 6000)) then
      begin
        for select distinct BDCODTPCC
            from VSUC_EMPRESAS_TBALANCETE_3
            where (BDCODTPCC is not null)
            into :WCODTPCC
        do
        begin
          if (position(',' || trim(cast(WCODTPCC as varchar(10))) || ',' in ',' || PRCC || ',') <= 0) then
          begin
            WSQL = 'delete from VSUC_EMPRESAS_TBALANCETE_3 where bdcodtpcc = ' || WCODTPCC;
            execute statement WSQL;
          end
        end
      end
    
      if (PRORDEM = 1) then
      --Machado - 11/03/2019 - Replicada alteração do outro modelo para esse.
      --INÍCIO DO CÁLCULO DO MODELO CONTAS/CENTRO DE CUSTO
      begin
        WSQL = '';
    
        WSQL = WSQL || ' select tpla.BDCODPLAPADRAO, tpla.BDCODTPLA, tpla.BDCTALON, tpla.BDTIPCTA, tpla.BDGRUPOCTA, tpla.BDNOMCTA, tpla.BDRELCTA, ';
        WSQL = WSQL || ' tpla.BDFORMULA, tpla.BDCLANOM, tpla.BDPARTICIPANTE, tpla.bdapecta, tpla.bdpertenceconta, null as bdcodtpcc ';
        WSQL = WSQL || 'from planos_tpla tpla ';
        WSQL = WSQL || 'where tpla.BDCODPLAPADRAO = ' || PRCODPLAPADRAO;
        WSQL = WSQL || ' AND ((tpla.BDTIPCTA in (0,2))) ';
    
        if (PRNAOMOSTRACONTACOMP = 1) then
          WSQL = WSQL || 'and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = ''' || 'FALSE' || ''')) ';
    
        for execute statement WSQL
                into :WCODIGOPLANO, :WCODTPLA, :WCTALON, :WTIPCTA, :WGRPCTA, :WNOMCTA, :WRELCTA, :WFORMULA, :WCLANOM,
                :WPARTICIPANTE, :WAPECTA, :WPERTENCECONTA, :WCODTPCC
        do
        begin
          if (WTIPCTA <> 1) then
          begin
            for select sum(coalesce(TBAL.BDVALOR_DEBITO, 0)) as VALOR_DEBITO,
                       sum(coalesce(TBAL.BDVALOR_CREDITO, 0)) as VALOR_CREDITO,
                       sum(coalesce(TBAL.BDANTERIOR_DEBITO, 0)) as ANTERIOR_DEBITO,
                       sum(coalesce(TBAL.BDANTERIOR_CREDITO, 0)) as ANTERIOR_CREDITO,
                       sum(coalesce(TBAL.BDANTERIOR_DEBITO_DRE, 0)) as ANTERIOR_DEBITO_DRE,
                       sum(coalesce(TBAL.BDANTERIOR_CREDITO_DRE, 0)) as ANTERIOR_CREDITO_DRE,
                       sum(coalesce(TBAL.BDVALOR_DEBITO_REAL, 0)) as BDVALOR_DEBITO_REAL,
                       sum(coalesce(TBAL.BDVALOR_CREDITO_REAL, 0)) as BDVALOR_CREDITO_REAL,
                       max(TBAL.BDDATAULTLANC) as BDDATAULTLANC
                from VSUC_EMPRESAS_TBALANCETE_3 TBAL
                where TBAL.BDCTALON starting with :WCTALON and
                      TBAL.BDCODEMP = :PRCODIGOEMP and
                      TBAL.BDCODPLAPADRAO = :WCODIGOPLANO and
                      TBAL.BDTIPCTA = 1
                into :WSALDO_DEBITO, :WSALDO_CREDITO, :WANTERIOR_DEBITO, :WANTERIOR_CREDITO, :WANTERIOR_DEBITO_DRE,
                     :WANTERIOR_CREDITO_DRE, :WVALOR_DEBITO_REAL, :WVALOR_CREDITO_REAL, :BDDATAULTLANC
            do
            begin
    
              insert into VSUC_EMPRESAS_TBALANCETE_3 (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDGRPCTA,
                                                      BDNOMCTA, BDRELCTA, BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA,
                                                      BDPERTENCECONTA, BDCODTPCC, BDVALOR_DEBITO, BDVALOR_CREDITO,
                                                      BDANTERIOR_DEBITO, BDANTERIOR_CREDITO, BDANTERIOR_DEBITO_DRE,
                                                      BDANTERIOR_CREDITO_DRE, BDVALOR_DEBITO_REAL, BDVALOR_CREDITO_REAL,
                                                      BDDATAULTLANC)
              values (:PRCODIGOEMP, :WCODIGOPLANO, :WCODTPLA, :WCTALON, :WTIPCTA, :WGRPCTA, :WNOMCTA, :WRELCTA, :WFORMULA,
                      :WCLANOM, :WPARTICIPANTE, :WAPECTA, :WPERTENCECONTA, null, :WSALDO_DEBITO, :WSALDO_CREDITO,
                      :WANTERIOR_DEBITO, :WANTERIOR_CREDITO, :WANTERIOR_DEBITO_DRE, :WANTERIOR_CREDITO_DRE,
                      :WVALOR_DEBITO_REAL, :WVALOR_CREDITO_REAL, :BDDATAULTLANC);
            end
          end
          else
          begin
            --Machado - 04/01/2019 - #91350
            insert into VSUC_EMPRESAS_TBALANCETE_3 (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDGRPCTA,
                                                    BDNOMCTA, BDRELCTA, BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA,
                                                    BDPERTENCECONTA, BDCODTPCC, BDDATAULTLANC)
            values (:PRCODIGOEMP, :WCODIGOPLANO, :WCODTPLA, :WCTALON, :WTIPCTA, :WGRPCTA, :WNOMCTA, :WRELCTA, :WFORMULA,
                    :WCLANOM, :WPARTICIPANTE, :WAPECTA, :WPERTENCECONTA, :WCODTPCC, :BDDATAULTLANC);
            --MATCHING (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCODTPCC);
          end
        end
    
        --Inicio 17388 - Retorna as contas com formulas - Fernando Jr. 18/01/2018
        WSQL_AUX = ' select BDCODTPCC ';
        WSQL_AUX = WSQL_AUX || ' from VSUC_EMPRESAS_TBALANCETE_3 ';
        WSQL_AUX = WSQL_AUX || ' group by BDCODTPCC';
        --Sol. 129419 - 17/12/2019 - Machado - Estava ficando lento depois de muitas execuções
        WFORMULA = null;
        select list(TPLA.BDCODTPLA, ',')
        from PLANOS_TPLA TPLA
        where BDCODPLAPADRAO = :PRCODPLAPADRAO and
              (BDFORMULA <> '' or (TPLA.BDTIPCTA in (0, 2) and
              exists(select A.BDCODTPLA
                     from PLANOS_TPLA A
                     where A.BDCODPLAPADRAO = :PRCODPLAPADRAO and
                           A.BDCTALON starting with TPLA.BDCTALON and
                           A.BDFORMULA <> '')))
        into :WFORMULA;
        if (coalesce(WFORMULA, '') <> '') then
        begin
          WSQL = 'INSERT INTO VSUC_EMPRESAS_TBALANCETE_3(BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDGRPCTA,';
          WSQL = WSQL || ' BDNOMCTA, BDRELCTA, BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA,bdpertenceconta, BDCODTPCC) ';
          WSQL = WSQL || ' select ' || PRCODIGOEMP || ', tpla.BDCODPLAPADRAO, tpla.BDCODTPLA, tpla.BDCTALON, tpla.BDTIPCTA, tpla.BDGRUPOCTA, ';
          WSQL = WSQL || ' tpla.BDNOMCTA, tpla.BDRELCTA, tpla.BDFORMULA, tpla.BDCLANOM, tpla.BDPARTICIPANTE, tpla.bdapecta, tpla.bdpertenceconta, null ';
          WSQL = WSQL || ' from planos_tpla tpla where (tpla.BDCODPLAPADRAO = ' || PRCODPLAPADRAO || ' AND (TPLA.BDCODTPLA IN (' || WFORMULA || '))) ';
          execute statement WSQL;
        end
      end
    
      --FIM DO CÁLCULO DO MODELO CONTAS/CENTRO DE CUSTO
      else
      --INÍCIO DO CÁLCULO DO MODELO CENTRO DE CUSTO/CONTAS
      begin
        WSQL = '';
        --       -- insere e atualiza a tabela temporária do balancete com as informações do plano de contas
        --       wsql = 'select tpla.BDCODPLAPADRAO, tpla.BDCODTPLA, tpla.BDCTALON, tpla.BDTIPCTA, tpla.BDGRUPOCTA, tpla.BDNOMCTA, tpla.BDRELCTA, ';
        --       wsql = wsql||'tpla.BDFORMULA, tpla.BDCLANOM, tpla.BDPARTICIPANTE, tpla.BDAPECTA, tpla.bdpertenceconta, tlan.bdcodtpcc ';
        --       wsql = wsql||'from planos_tpla tpla ';
        --       --alt:9179 - Trocado para inner join para melhoria de desempenho, pois não faz sentido trazer aqui lançamentos sem centro de custo. Pedro
        --       --wsql = wsql||'left outer join VSUC_EMPRESAS_TBALANCETE_3 tlan on (tlan.bdcodplapadrao = tpla.bdcodplapadrao and tlan.bdcodtpla = tpla.bdcodtpla) ';
        --       wsql = wsql||'inner join VSUC_EMPRESAS_TBALANCETE_3 tlan on (tlan.bdcodplapadrao = tpla.bdcodplapadrao and tlan.bdcodtpla = tpla.bdcodtpla) ';
        --       wsql = wsql||'where tpla.bdcodplapadrao = '||prcodplapadrao;
        --
        --
        --       wsql = wsql||' union all ';
        WSQL = WSQL || ' select tpla.BDCODPLAPADRAO, tpla.BDCODTPLA, tpla.BDCTALON, tpla.BDTIPCTA, tpla.BDGRUPOCTA, tpla.BDNOMCTA, tpla.BDRELCTA, ';
        WSQL = WSQL || ' tpla.BDFORMULA, tpla.BDCLANOM, tpla.BDPARTICIPANTE, tpla.bdapecta, tpla.bdpertenceconta, null as bdcodtpcc ';
        WSQL = WSQL || ' from planos_tpla tpla ';
        WSQL = WSQL || ' where tpla.BDCODPLAPADRAO = ' || PRCODPLAPADRAO;
        WSQL = WSQL || ' AND ((tpla.BDTIPCTA in (0,2))) ';
    
        if (PRNAOMOSTRACONTACOMP = 1) then
          WSQL = WSQL || ' and ((tpla.BDCTACOMP is null) or (tpla.BDCTACOMP = ''' || 'FALSE' || '''))';
    
        for execute statement WSQL
                into :WCODIGOPLANO, :WCODTPLA, :WCTALON, :WTIPCTA, :WGRPCTA, :WNOMCTA, :WRELCTA, :WFORMULA, :WCLANOM,
                :WPARTICIPANTE, :WAPECTA, :WPERTENCECONTA, :WCODTPCC
        do
        begin
          if (WTIPCTA <> 1) then
          begin
            for select sum(coalesce(TBAL.BDVALOR_DEBITO, 0)) as VALOR_DEBITO,
                       sum(coalesce(TBAL.BDVALOR_CREDITO, 0)) as VALOR_CREDITO,
                       sum(coalesce(TBAL.BDANTERIOR_DEBITO, 0)) as ANTERIOR_DEBITO,
                       sum(coalesce(TBAL.BDANTERIOR_CREDITO, 0)) as ANTERIOR_CREDITO,
                       sum(coalesce(TBAL.BDANTERIOR_DEBITO_DRE, 0)) as ANTERIOR_DEBITO_DRE,
                       sum(coalesce(TBAL.BDANTERIOR_CREDITO_DRE, 0)) as ANTERIOR_CREDITO_DRE,
                       sum(coalesce(TBAL.BDVALOR_DEBITO_REAL, 0)) as BDVALOR_DEBITO_REAL,
                       sum(coalesce(TBAL.BDVALOR_CREDITO_REAL, 0)) as BDVALOR_CREDITO_REAL, TBAL.BDCODTPCC,
                       max(TBAL.BDDATAULTLANC) as BDDATAULTLANC
                from VSUC_EMPRESAS_TBALANCETE_3 TBAL
                where TBAL.BDCTALON starting with :WCTALON and
                      TBAL.BDCODEMP = :PRCODIGOEMP and
                      TBAL.BDCODPLAPADRAO = :WCODIGOPLANO and
                      TBAL.BDTIPCTA = 1
                group by TBAL.BDCODTPCC
                into :WSALDO_DEBITO, :WSALDO_CREDITO, :WANTERIOR_DEBITO, :WANTERIOR_CREDITO, :WANTERIOR_DEBITO_DRE,
                     :WANTERIOR_CREDITO_DRE, :WVALOR_DEBITO_REAL, :WVALOR_CREDITO_REAL, :WCODTPCC, :BDDATAULTLANC
            do
            begin
              --alt:9179 - Trocado para insert pois nunca estará dando update, já que aqui trata apenas contas título e até aqui não tem nenhuma conta título armazenada.
              --Assim a procedure ficou 1/7 mais rápida por não ter que verificar se a conta já existe na tabela. Pedro
              /*update or insert into VSUC_EMPRESAS_TBALANCETE_3
                        (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDGRPCTA, BDNOMCTA, BDRELCTA,
                         BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA, BDPERTENCECONTA, BDCODTPCC,
                         BDVALOR_DEBITO, BDVALOR_CREDITO, BDANTERIOR_DEBITO,
                         BDANTERIOR_CREDITO, BDANTERIOR_DEBITO_DRE, BDANTERIOR_CREDITO_DRE) values
                        (:prcodigoemp, :wcodigoplano, :wcodtpla, :wctalon, :wtipcta, :wgrpcta, :wnomcta, :wrelcta,
                         :wformula, :wclanom, :wparticipante, :wapecta, :wpertenceconta, :wcodtpcc,
                         :WSALDO_DEBITO, :WSALDO_CREDITO, :WANTERIOR_DEBITO,
                         :WANTERIOR_CREDITO, :WANTERIOR_DEBITO_DRE, :WANTERIOR_CREDITO_DRE)
                        matching (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCODTPCC);*/
    
              insert into VSUC_EMPRESAS_TBALANCETE_3 (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDGRPCTA,
                                                      BDNOMCTA, BDRELCTA, BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA,
                                                      BDPERTENCECONTA, BDCODTPCC, BDVALOR_DEBITO, BDVALOR_CREDITO,
                                                      BDANTERIOR_DEBITO, BDANTERIOR_CREDITO, BDANTERIOR_DEBITO_DRE,
                                                      BDANTERIOR_CREDITO_DRE, BDVALOR_DEBITO_REAL, BDVALOR_CREDITO_REAL,
                                                      BDDATAULTLANC)
              values (:PRCODIGOEMP, :WCODIGOPLANO, :WCODTPLA, :WCTALON, :WTIPCTA, :WGRPCTA, :WNOMCTA, :WRELCTA, :WFORMULA,
                      :WCLANOM, :WPARTICIPANTE, :WAPECTA, :WPERTENCECONTA, :WCODTPCC, :WSALDO_DEBITO, :WSALDO_CREDITO,
                      :WANTERIOR_DEBITO, :WANTERIOR_CREDITO, :WANTERIOR_DEBITO_DRE, :WANTERIOR_CREDITO_DRE,
                      :WVALOR_DEBITO_REAL, :WVALOR_CREDITO_REAL, :BDDATAULTLANC);
            end
          end
          else
          begin
            --Machado - 04/01/2019 - #91350
            insert into VSUC_EMPRESAS_TBALANCETE_3 (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDGRPCTA,
                                                    BDNOMCTA, BDRELCTA, BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA,
                                                    BDPERTENCECONTA, BDCODTPCC, BDDATAULTLANC)
            values (:PRCODIGOEMP, :WCODIGOPLANO, :WCODTPLA, :WCTALON, :WTIPCTA, :WGRPCTA, :WNOMCTA, :WRELCTA, :WFORMULA,
                    :WCLANOM, :WPARTICIPANTE, :WAPECTA, :WPERTENCECONTA, :WCODTPCC, :BDDATAULTLANC);
            --MATCHING (BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCODTPCC);
          end
        end
    
        --Inicio 17388 - Retorna as contas com formulas - Fernando Jr. 18/01/2018
        WSQL_AUX = ' select BDCODTPCC ';
        WSQL_AUX = WSQL_AUX || ' from VSUC_EMPRESAS_TBALANCETE_3 ';
        WSQL_AUX = WSQL_AUX || ' group by BDCODTPCC';
        --Sol. 129419 - 17/12/2019 - Machado - Estava ficando lento depois de muitas execuções
        WFORMULA = null;
        select list(TPLA.BDCODTPLA, ',')
        from PLANOS_TPLA TPLA
        where BDCODPLAPADRAO = :PRCODPLAPADRAO and
              (BDFORMULA <> '' or (TPLA.BDTIPCTA in (0, 2) and
              exists(select A.BDCODTPLA
                     from PLANOS_TPLA A
                     where A.BDCODPLAPADRAO = :PRCODPLAPADRAO and
                           A.BDCTALON starting with TPLA.BDCTALON and
                           A.BDFORMULA <> '')))
        into :WFORMULA;
        if (coalesce(WFORMULA, '') <> '') then
        begin
          WSQL = 'INSERT INTO VSUC_EMPRESAS_TBALANCETE_3(BDCODEMP, BDCODPLAPADRAO, BDCODTPLA, BDCTALON, BDTIPCTA, BDGRPCTA,';
          WSQL = WSQL || ' BDNOMCTA, BDRELCTA, BDFORMULA, BDCLANOM, BDPARTICIPANTE, BDAPECTA,bdpertenceconta, BDCODTPCC) ';
          WSQL = WSQL || ' select ' || PRCODIGOEMP || ', tpla.BDCODPLAPADRAO, tpla.BDCODTPLA, tpla.BDCTALON, tpla.BDTIPCTA, tpla.BDGRUPOCTA, ';
          WSQL = WSQL || ' tpla.BDNOMCTA, tpla.BDRELCTA, tpla.BDFORMULA, tpla.BDCLANOM, tpla.BDPARTICIPANTE, tpla.bdapecta, tpla.bdpertenceconta, tlan.BDCODTPCC ';
          WSQL = WSQL || ' from (' || WSQL_AUX || ') tlan';
          WSQL = WSQL || ' INNER join planos_tpla tpla ON (tpla.BDCODPLAPADRAO = ' || PRCODPLAPADRAO || ' AND (TPLA.BDCODTPLA IN (' || WFORMULA || '))) ';
          execute statement WSQL;
        end
        --Fim 17388
      end
    
      -- retira as contas analiticas que pertencem a uma conta consolidadas ________
      if ((PRCONSOLIDADA is null) or (PRCONSOLIDADA = 0)) then
      begin
        for select BDCTALON
            from PLANOS_TPLA
            where BDCODPLAPADRAO = :PRCODPLAPADRAO and
                  BDTIPCTA = 2
            into :WCTALON
        do
        begin
          WSQL = 'delete from VSUC_EMPRESAS_TBALANCETE_3 ';
          WSQL = WSQL || 'where bdcodplapadrao = ' || PRCODPLAPADRAO;
          WSQL = WSQL || ' and bdctalon like ''' || WCTALON || '.%' || ''' ';
          WSQL = WSQL || ' and bdcodemp = ' || PRCODIGOEMP || ' ';
          execute statement WSQL;
        end
      end
    
      -- faz o select na tabela temporária de balancete e monta os retornos para a impressao
      --Sol. 129419 - 17/12/2019 - Machado - Estava ficando lento depois de muitas execuções (Unificado centro de custo no select)
      WSQL = 'SELECT  tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, tbal.bdtipcta, tbal.bdgrpcta, tbal.bdnomcta,';
      WSQL = WSQL || '  COALESCE(tbal.bdvalor_debito, 0), COALESCE(tbal.bdvalor_credito, 0),';
      WSQL = WSQL || '  COALESCE(tbal.bdanterior_debito, 0), COALESCE(tbal.bdanterior_credito, 0),';
      WSQL = WSQL || '  COALESCE(tbal.bdanterior_debito_dre, 0), COALESCE(tbal.bdanterior_credito_dre, 0),';
      WSQL = WSQL || '  COALESCE(tbal.bdvalor_debito_real, 0), COALESCE(tbal.bdvalor_credito_real, 0),';
      WSQL = WSQL || '  tbal.bdformula, tbal.bdrelcta, tbal.bdclanom,';
      --alt:7866 - 27/10/2015 - Caso tenha a opção de detalhar por participantes específicos, precisa verificar aqui se o em questão
      --está marcado ou não para retornar como conta participante, para depois a VSUC_SP_RETORNA_BALANCETE detalhar ou não. Pedro
      if ((WSELECTCONTAS is not null) and
          (WSELECTCONTAS > 0)) then
        WSQL = WSQL || ' case when lista.BDCODTPLA is null then 0 else tbal.BDPARTICIPANTE end as BDPARTICIPANTE,';
      else
        WSQL = WSQL || ' tbal.bdparticipante,';
      --alt:7866 - Fim
      WSQL = WSQL || ' tbal.bdapecta, tbal.bdpertenceconta, tpcc.bdcodtpcc, tpcc.bdnomcta, tpcc.bdctalon, tpcc.bdfiltroger, tbal.BDDATAULTLANC';
      WSQL = WSQL || ' FROM vsuc_empresas_tbalancete_3 tbal';
      WSQL = WSQL || ' left outer join centros_tpcc tpcc on (tpcc.BDCODCENTRO = ' || coalesce(WCENTROCUSTO, 0) || ' and tpcc.bdcodtpcc = tbal.bdcodtpcc)';
      --alt:7866 - 27/10/2015 - Faz a verificação para saber qual o tipo de filtro que será aplicado aqui, para o caso de selecionar contas específicas. Pedro
      if ((WSELECTCONTAS is not null) and
          (WSELECTCONTAS > 0)) then
        WSQL = WSQL || ' left join VSUC_SELECT_CONTAS lista on (tbal.BDCODPLAPADRAO = lista.BDCODPLAPADRAO and tbal.BDCODTPLA = lista.BDCODTPLA)';
      --alt:7866 - Fim
      WSQL = WSQL || ' where tbal.bdcodemp = ' || PRCODIGOEMP || ' AND tbal.bdcodplapadrao = ' || PRCODPLAPADRAO || ' and  tbal.bdctalon BETWEEN ''' || WCLASSINI || ''' AND ''' || :WCLASSFIN || '''';
      WSQL = WSQL || ' ORDER BY tbal.bdcodemp, tbal.bdcodplapadrao, tbal.bdctalon';

      for execute statement WSQL
              into :WCODIGOPLANO, :WCODTPLA, :WCLASSIFICACAO, :WTIPCTA, :WGRPCTA, :WNOMCTA, :WSALDO_DEBITO, :WSALDO_CREDITO,
              :WANTERIOR_DEBITO, :WANTERIOR_CREDITO, :WANTERIOR_DEBITO_DRE, :WANTERIOR_CREDITO_DRE, :WVALOR_DEBITO_REAL,
              :WVALOR_CREDITO_REAL, :BDFORMULA, :BDRELCONTA, :BDCLANOM, :WPARTICIPANTE, :WAPECTA, :WPERTENCECONTA,
              :WCODTPCC, :WNOMTPCC, :WTPCCLON, :WFILTROCC, :BDDATAULTLANC
      do
      begin
        BDCODEMP = :PRCODIGOEMP;
        BDCODPLAPADRAO = :WCODIGOPLANO;
        BDCONTA = :WCODTPLA;
        BDCLASSIFICACAO = :WCLASSIFICACAO;
        BDNOMECONTA = :WNOMCTA;
        BDTIPCONTA = :WTIPCTA;
        BDGRUPOCONTA = :WGRPCTA;
        BDPARTICIPANTE = :WPARTICIPANTE;
        BDSALDO_ANT_DEB = :WANTERIOR_DEBITO;
        BDSALDO_ANT_CRE = :WANTERIOR_CREDITO;
        BDSALDO_ANT_DEB_DRE = :WANTERIOR_DEBITO_DRE;
        BDSALDO_ANT_CRE_DRE = :WANTERIOR_CREDITO_DRE;
        BDSALDO_DEB = :WSALDO_DEBITO;
        BDSALDO_CRE = :WSALDO_CREDITO;
        BDAPECTA = :WAPECTA;
        BDPERTENCECONTA = :WPERTENCECONTA;
    
    
        BDCODTPCC = WCODTPCC;
        BDNOMTPCC = WNOMTPCC;
        BDTPCCLON = WTPCCLON;
        BDFILTROCC = WFILTROCC;
    
        if (WGRPCTA in (1, 2, 3)) then
        begin
          BDSALDO_ANTERIOR = (WANTERIOR_CREDITO - WANTERIOR_DEBITO);
          BDSALDO_ANTERIOR_DRE = (WANTERIOR_CREDITO_DRE - WANTERIOR_DEBITO_DRE);
          BDSALDO_ATUAL = (BDSALDO_ANTERIOR + :WSALDO_CREDITO - :WSALDO_DEBITO);
          BDSALDO_ATUAL_REAL = (BDSALDO_ANTERIOR + :WVALOR_CREDITO_REAL - :WVALOR_DEBITO_REAL);
        end
        else
        begin
          BDSALDO_ANTERIOR = (WANTERIOR_DEBITO - WANTERIOR_CREDITO);
          BDSALDO_ANTERIOR_DRE = (WANTERIOR_DEBITO_DRE - WANTERIOR_CREDITO_DRE);
          BDSALDO_ATUAL = (BDSALDO_ANTERIOR + :WSALDO_DEBITO - :WSALDO_CREDITO);
          BDSALDO_ATUAL_REAL = (BDSALDO_ANTERIOR + :WVALOR_DEBITO_REAL - :WVALOR_CREDITO_REAL);
        end
    
        WNIVELCONTA = 1;
        WCONT = 1;
        while (WCONT <= char_length(WCLASSIFICACAO)) do
        begin
          if (substring(WCLASSIFICACAO from WCONT for 1) = '.') then
            WNIVELCONTA = WNIVELCONTA + 1;
          WCONT = WCONT + 1;
        end
        --#alt:141589 - 31/08/2020 - Machado - Quando detalhar consolidada e remover as analíticas deve emitir as contas consolidadoras
        WTIPOCONTANIVEL = WTIPCTA;
        if (WTIPOCONTANIVEL = 2) then
        begin
          if (PRCONSOLIDADA = 1) then
            WTIPOCONTANIVEL = 0;
          else
            WTIPOCONTANIVEL = 1;
        end
    
        WINDICE = position(',' || cast(:WNIVELCONTA as varchar(100)) || ',', ',' || :PRNIVEISCONTA || ',');
        WIMPANALITICA = position(',1,', ',' || :PRNIVEISCONTA || ',');
    
        --#alt:141889 - 14/09/2020 - Machado - Conta analítica/título/consolidadora mesmo nivel na emissão dos Relatórios e na Exportação da ECD
        if (WIMPANALITICA <= 0 and
            PRNIVEISCONTA <> '9999' and
            WTIPOCONTANIVEL = 1) then
        begin
          WCLASSIFICACAO_REVERSE = reverse(BDCLASSIFICACAO);
          WPOSITION_PONTO = position('.' in WCLASSIFICACAO_REVERSE);
          if (WPOSITION_PONTO <= 0) then
            WPOSITION_PONTO = 1;
    
          WCLASSIFICACAO_REVERSE = reverse(substring(WCLASSIFICACAO_REVERSE from WPOSITION_PONTO));
          WPOSITION_PONTO = null;
          select first 1 1
          from PLANOS_TPLA
          where BDCODPLAPADRAO = :BDCODPLAPADRAO and
                BDCTALON starting with :WCLASSIFICACAO_REVERSE and
                BDTIPCTA in (0, iif(:PRCONSOLIDADA = 1, 2, 0))
          into :WPOSITION_PONTO;
          if (WPOSITION_PONTO = 1) then
            WTIPOCONTANIVEL = 0;
        end

        if ((PRNIVEISCONTA = '9999') or -- Não tem filtro
            (WNIVELCONTA = 1) or -- O primeiro nível sempre imprime
            ((WINDICE > 0) and
            (:WTIPOCONTANIVEL = 0)) or -- O nível da conta foi selecionado no filtro e é título
            --Ele remove as consolidadas tambem, caso contrario pode dar problemas com o ECD/J100 e as contas bancarias
            (((WINDICE > 0) and
            (WIMPANALITICA > 0) and
            (:WTIPOCONTANIVEL = 1)))) then -- É do nível selecionado, analítica e foi selecionado para imprimir as contas analíticas
          suspend;
      end

      if (prdetalharccempreend = 1) then
        begin
          if (position(',',PRCODEMPREENDIMENTO) > 0) then
            BEGIN
              wempreendimento = substring(PRCODEMPREENDIMENTO from 1 for position(',',PRCODEMPREENDIMENTO)-1);
              PRCODEMPREENDIMENTO = substring(PRCODEMPREENDIMENTO from position(',',PRCODEMPREENDIMENTO)+1 for character_length(PRCODEMPREENDIMENTO));
            END
          else
            begin
              wempreendimento = PRCODEMPREENDIMENTO;
              if (wempreenatu = PRCODEMPREENDIMENTO) then
                PRCODEMPREENDIMENTO = '';
            end
        end
      else
        PRCODEMPREENDIMENTO = '';

      -- limpa tabela temporária do balancete ______________________________________
      delete from VSUC_EMPRESAS_TBALANCETE_3
      where BDCODEMP is not null;
  END
end
^

/* Restore proc. body: VSUC_SP_RETORNA_SALDO_LANC */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_LANC(PRCODEMP INTEGER,
PRREFEMP INTEGER,
PRCONTA_DEB INTEGER,
PRCONTA_CRED INTEGER,
PRDATA DATE,
PRPARTICIPANTED INTEGER,
PRPARTICIPANTEC INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFIIALCONSOLIDADO INTEGER)
 RETURNS(ANT_AO_DIA_D NUMERIC(15,2),
DEB_DO_DIA_D NUMERIC(15,2),
CRED_DO_DIA_D NUMERIC(15,2),
ATUAL_DO_DIA_D NUMERIC(15,2),
ANT_AO_DIA_C NUMERIC(15,2),
DEB_DO_DIA_C NUMERIC(15,2),
CRED_DO_DIA_C NUMERIC(15,2),
ATUAL_DO_DIA_C NUMERIC(15,2),
ANT_AO_MES_C NUMERIC(15,2),
ATUAL_DO_MES_C NUMERIC(15,2),
ANT_AO_MES_D NUMERIC(15,2),
DEB_DO_MES_D NUMERIC(15,2),
CRED_DO_MES_D NUMERIC(15,2),
MOV_DO_MES_D NUMERIC(15,2),
ATUAL_DO_MES_D NUMERIC(15,2),
ANT_DO_MES_C NUMERIC(15,2),
DEB_DO_MES_C NUMERIC(15,2),
CRED_DO_MES_C NUMERIC(15,2),
MOV_DO_MES_C NUMERIC(15,2),
ATUTAL_DO_MES_C NUMERIC(15,2))
 AS
DECLARE VARIABLE WMES_S_ANT VARCHAR(2);
DECLARE VARIABLE WMES_S VARCHAR(2);
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WANO VARCHAR(4);
DECLARE VARIABLE WSQL VARCHAR(1024);
DECLARE VARIABLE WBDDEB VARCHAR(7);
DECLARE VARIABLE WBDCRE VARCHAR(7);
BEGIN
 /* Procedure Text */

  ANT_AO_DIA_D = 0;
  DEB_DO_DIA_D = 0;
  CRED_DO_DIA_D = 0;
  ATUAL_DO_DIA_D = 0;
  ANT_AO_DIA_C = 0;
  DEB_DO_DIA_C = 0;
  CRED_DO_DIA_C = 0;
  ATUAL_DO_DIA_C = 0;
  ANT_AO_MES_C = 0;
  ATUAL_DO_MES_C = 0;
  ANT_AO_MES_D = 0;
  DEB_DO_MES_D = 0;
  CRED_DO_MES_D = 0;
  MOV_DO_MES_D = 0;
  ATUAL_DO_MES_D = 0;
  ANT_DO_MES_C = 0;
  DEB_DO_MES_C = 0;
  CRED_DO_MES_C = 0;
  MOV_DO_MES_C = 0;
  ATUTAL_DO_MES_C = 0;

  wMes = CAST(SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);
  wAno = CAST(SUBSTRING(CAST(prdata AS VARCHAR(10)) FROM 1 FOR 4) AS INTEGER);

  SELECT str FROM strZero(EXTRACT(MONTH FROM :prdata), 2) INTO :wmes_s;

  wbddeb = 'BDDEB' || wmes_s;
  wbdcre = 'BDCRE' || wmes_s;

  /* Débito */

  -- Retorna saldo da conta débito
  SELECT SALDO_ANTERIOR, SALDO_DEB, SALDO_CRE, SALDO_ATUAL FROM
    vsuc_sp_retorna_saldo(:prcodemp, :prconta_deb, :prdata, :prdata, 0, 0, 0, :prrefemp, '',:prcontabilizacao,:prmatrizfiialconsolidado)
    INTO :ant_ao_dia_d, :deb_do_dia_d, :cred_do_dia_d, :atual_do_dia_d;

  IF (wMes = 1) THEN
    BEGIN
      wsql = 'select BDSALANT, ' || wbddeb || ', ' || wbdcre || ', ' || wbddeb || '-' || wbdcre || ', BDSAL' || wmes_s;
      wsql = wsql||' from VSUC_SP_MOVIMENTO_MENSAL(' || :prcodemp || ',' || :prconta_deb || ',' || wano || ',' || wano || ',' || :prrefemp || ',';
      wsql = wsql|| :prparticipanted || ',0,' || :prcontabilizacao || ',' || :prmatrizfiialconsolidado || ')';
    END
  ELSE
    BEGIN
      SELECT str FROM strZero(EXTRACT(MONTH FROM :prdata) -1, 2) INTO :wmes_s_ant;

      wsql = 'select BDSAL' || wmes_s_ant || ',' || wbddeb || ', ' || wbdcre || ', ' || wbddeb || '-' || wbdcre || ', BDSAL' || wmes_s;
      wsql = wsql||' from VSUC_SP_MOVIMENTO_MENSAL(' || :prcodemp || ',' || :prconta_deb || ',' || wano || ',' || wano || ',' || :prrefemp || ',';
      wsql = wsql|| :prparticipanted || ',0,' || :prcontabilizacao || ',' || :prmatrizfiialconsolidado || ')';
    END

  EXECUTE STATEMENT wsql INTO :ant_ao_mes_d, :deb_do_mes_d, :cred_do_mes_d, :mov_do_mes_d, :atual_do_mes_d;

  SUSPEND;

  /* Fim */

  /* Crédito */

  ANT_AO_DIA_D = 0;
  DEB_DO_DIA_D = 0;
  CRED_DO_DIA_D = 0;
  ATUAL_DO_DIA_D = 0;
  ANT_AO_DIA_C = 0;
  DEB_DO_DIA_C = 0;
  CRED_DO_DIA_C = 0;
  ATUAL_DO_DIA_C = 0;
  ANT_AO_MES_C = 0;
  ATUAL_DO_MES_C = 0;
  ANT_AO_MES_D = 0;
  DEB_DO_MES_D = 0;
  CRED_DO_MES_D = 0;
  MOV_DO_MES_D = 0;
  ATUAL_DO_MES_D = 0;
  ANT_DO_MES_C = 0;
  DEB_DO_MES_C = 0;
  CRED_DO_MES_C = 0;
  MOV_DO_MES_C = 0;
  ATUTAL_DO_MES_C = 0;

  -- Retorna saldo da conta crédito
  SELECT SALDO_ANTERIOR, SALDO_DEB, SALDO_CRE, SALDO_ATUAL FROM
    vsuc_sp_retorna_saldo(:prcodemp, :prconta_cred, :prdata, :prdata, 0, 0, 0, :prrefemp, '',:prcontabilizacao,:prmatrizfiialconsolidado)
    INTO :ant_ao_dia_c, :deb_do_dia_c, :cred_do_dia_c, :atual_do_dia_c;

  IF (wMes = 1) THEN
    BEGIN
      wsql = 'select BDSALANT, ' || wbddeb || ', ' || wbdcre || ', ' || wbddeb || '-' || wbdcre || ', BDSAL' || wmes_s;
      wsql = wsql||' from VSUC_SP_MOVIMENTO_MENSAL(' || :prcodemp || ',' || :prconta_cred || ',' || wano || ',' || wano || ',' || :prrefemp || ',';
      wsql = wsql|| :prparticipantec || ',0,' || :prcontabilizacao || ',' || :prmatrizfiialconsolidado || ')';
    END
  ELSE
    BEGIN
      SELECT str FROM strZero(EXTRACT(MONTH FROM :prdata) -1, 2) INTO :wmes_s_ant;

      wsql = 'select BDSAL' || wmes_s_ant || ',' || wbddeb || ', ' || wbdcre || ', ' || wbddeb || '-' || wbdcre || ', BDSAL' || wmes_s;
      wsql = wsql||' from VSUC_SP_MOVIMENTO_MENSAL(' || :prcodemp || ',' || :prconta_cred || ',' || wano || ',' || wano || ',' || :prrefemp || ',';
      wsql = wsql|| :prparticipantec || ',0,' || :prcontabilizacao || ',' || :prmatrizfiialconsolidado || ')';
    END

  EXECUTE STATEMENT wsql INTO :ant_ao_mes_c, :deb_do_mes_c, :cred_do_mes_c, :mov_do_mes_c, :atual_do_mes_c;

  SUSPEND;
  /* Fim */
END
^

/* Restore proc. body: VSUC_SP_RETORNA_SALDO_ORCA */
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_SALDO_ORCA (
    PRCODIGOEMP INTEGER,
    PRCONTAINICIAL INTEGER,
    PRCONTAFINAL INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE,
    PRINDICE INTEGER,
    PRIGNORAZERAMENTO INTEGER,
    PRCC INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PRTODASASCONTAS INTEGER,
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRLANCSEMCC INTEGER = 0)
RETURNS (
    CODEMP INTEGER,
    CODPLAPADRAO INTEGER,
    CONTA INTEGER,
    CLASSIFICACAO VARCHAR(40),
    NOMECONTA VARCHAR(100),
    GRUPOCONTA SMALLINT,
    RELCONTA INTEGER,
    TIPCONTA SMALLINT,
    BDORCADO INTEGER,
    BDREALIZADO NUMERIC(15,2),
    FORMULA VARCHAR(200))
AS
DECLARE VARIABLE WGRPCTA INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(40);
DECLARE VARIABLE WCODIGOPLANO INTEGER;
DECLARE VARIABLE WRELCTA INTEGER;
DECLARE VARIABLE WTIPCTA SMALLINT;
DECLARE VARIABLE WCODTPLA INTEGER;
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WMOVIMENTO NUMERIC(15,2);
DECLARE VARIABLE WSQL VARCHAR(32000);
DECLARE VARIABLE WCLASSINI VARCHAR(40);
DECLARE VARIABLE WCLASSFIN VARCHAR(40);
DECLARE VARIABLE WFORMULA VARCHAR(10240);
DECLARE VARIABLE WSALDO_DEBITO NUMERIC(15,2);
DECLARE VARIABLE WSALDO_CREDITO NUMERIC(15,2);
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE SALDO_DEBSAIDA NUMERIC(15,2);
DECLARE VARIABLE SALDO_CRESAIDA NUMERIC(15,2);
DECLARE VARIABLE WNIVELCONTA INTEGER;
DECLARE VARIABLE WIMPANALITICA INTEGER;
DECLARE VARIABLE WINDICE INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WSQL_AUX VARCHAR(32000);
BEGIN
  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prcontainicial
  INTO :wclassini;

  SELECT planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prcontafinal
  INTO :wclassfin;

  SELECT FIRST 1 planos_tpla.bdctalon FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND SUBSTRING(planos_tpla.bdctalon FROM 1 FOR CHARACTER_LENGTH(:wclassfin)) = :wclassfin
  ORDER BY planos_tpla.bdctalon DESC
  INTO :wclassfin;

  -- Se encontrar no prNiveisConta o "1" significa que deve imprimir contas analíticas
  SELECT BDRPOS FROM RPOS(',1,',','||:prniveisconta||',') INTO :wimpanalitica;

/* giovanni... insere somente as contas com lancamentos */
  wsql = '';
  wsql = wsql|| ' select distinct CONTAS.bdcodplapadrao, CONTAS.bdcodtpla,CONTAS.bdctalon,CONTAS.bdtipcta,CONTAS.bdnomcta, ';
  wsql = wsql|| ' CONTAS.bdgrupocta, CONTAS.bdrelcta,CONTAS.bdformula  from VSUC_SP_RETORNA_CONTAS_USADAS(' || prcodigoemp || ', ' || prcodplapadrao ||   ',null,null,null,null,0,1,0,3,' || prtodasascontas  ||  ') CONTAS';
  wsql = wsql|| ' where (contas.bdcodplapadrao = ' || :prcodplapadrao || ') and (contas.bdctalon between ''' || :wclassini || ''' and  ''' || :wclassfin || ''' ) order by BDCTALON';

  FOR EXECUTE STATEMENT wsql
      INTO :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta, :wnomcta, :wgrpcta, :wrelcta, :wformula DO
      BEGIN
        INSERT INTO VSUC_EMPRESAS_REL_TORCAMENTO_2 (bdcodemp, bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdgrpcta, bdnomcta,
                                                 BDORCADO, BDDEBITO, bdrelcta, bdformula)
        VALUES(:prcodigoemp, :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta, :wgrpcta, :wnomcta, 0.00, 0.00, :wrelcta, :wformula);
      END

 -- BUSCA VALORES A DEBITO INICIO -----------------------------------------------------------------------------------------------------------------
  wsql = '';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    BEGIN
      -- centro de custo
      --#alt:5837.
      --wsql = wsql||'SELECT tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, SUM(TLCC.BDVALOR) AS valor_debito ';
      wsql = wsql||'SELECT tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, ';

      --alt:6178 - 09/11/2015 - Verifica se foi informado um índice, caso positivo, divide o valor do lançamento pelo valor do índice na data. Função dos relatórios em outra moeda. Pedro
      IF (prindice = 0) THEN
        wsql = wsql||'sum(coalesce(tlcc.bdvalor, tlan.bdvalor)) as valor_debito ';
      ELSE
        BEGIN
          wsql = wsql||'sum(coalesce(tlcc.bdvalor, tlan.bdvalor) / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                            (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))) as valor_debito ';
        END
      --alt:6178 - Fim
      if (PRLANCSEMCC = 0) then
        begin
          wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';
          wsql = wsql||'join VSUC_EMPRESAS_TLCC TLCC on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
        end
      else
        begin
          wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';
          wsql = wsql||'left outer join VSUC_EMPRESAS_TLCC TLCC on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP) and (tlcc.bddebcre = 0)) ';
        end
    END
  ELSE
    BEGIN
      -- lancamentos
      --#alt:5837.
      --wsql = wsql || 'select tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, ';
      wsql = wsql || 'select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, ';

      --alt:6178 - 09/11/2015 - Verifica se foi informado um índice, caso positivo, divide o valor do lançamento pelo valor do índice na data. Função dos relatórios em outra moeda. Pedro
      IF (prindice = 0) THEN
        wsql = wsql||'coalesce(sum(tlan.bdvalor),0) as valor_debito ';
      ELSE
        BEGIN
          wsql = wsql||'coalesce(sum(tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                                     (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))),0) as valor_debito ';
        END
      --alt:6178 - Fim

      wsql = wsql || 'from vsuc_empresas_tlan tlan ';
     END
  wsql = wsql || 'left outer join VSUC_EMPRESAS_REL_TORCAMENTO_2 tbal on ((tlan.bdcodplapadrao = tbal.bdcodplapadrao) and (tlan.bddebito = tbal.bdcodtpla)) ';
  wsql = wsql || 'where (tbal.bdcodplapadrao = '||prcodplapadrao||') ';
  IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
     wsql = wsql || 'and (tlan.bdtipolan <> 10) ';
  wsql = wsql || 'and (tbal.bdtipcta = 1) ';
  wsql = wsql || 'and (tlan.bddata between '''||prdataini||''' and '''||prdatafim||''') ';
  --#alt:5837.
  --wsql = wsql || 'and (tlan.bdcodemp = '||prcodigoemp||') ';
  wsql = wsql||'and ((tlan.bdcodemp = '||prcodigoemp||')) ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    begin
      wsql = wsql || 'AND ((TLCC.bdcodtpcc = '||prcc||') ';
      if (prlancsemcc = 1) then
        wsql = wsql || 'OR (TLCC.bdcodtpcc IS NULL)';
      wsql = wsql || ')';
    end
  wsql = wsql || 'Group By tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon ';
  wsql = wsql || 'Order By tbal.bdctalon Desc ';

  -- pega a classificacao e o saldo total das contas analiticas ______________--
  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wfilial,:wtipolancfilial,:wcodigoplano, :wcodtpla, :wclassificacao, :wsaldo_debito DO
    BEGIN
      --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:prcodigoemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodigoemp) INTO :wpermite;
      IF (1=1) THEN
        BEGIN
          -- faz um update no debito, pq ja foi gravado o lancamento antes zerado
          --#alt:5837.
          /*update vsuc_empresas_rel_torcamento set BDDEBITO = :wsaldo_debito
          where bdcodemp = :prcodigoemp
          and   bdcodplapadrao = :wcodigoplano
          and   bdcodtpla = :wcodtpla
          and   bdctalon = :wclassificacao
          and   bddatahora = :prdatahora
          and   ((BDDEBITO = 0) or (bddebito is null)); */
          wsql_aux = 'update vsuc_empresas_rel_torcamento_2 set ';
          wsql_aux = wsql_aux||'BDDEBITO = (coalesce(BDDEBITO,0) + '||wsaldo_debito||') ';
          wsql_aux = wsql_aux||'where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||wcodigoplano;
          wsql_aux = wsql_aux||' and bdcodtpla = '||wcodtpla||' and bdctalon = '''||wclassificacao||'''';
          EXECUTE STATEMENT wsql_aux;
        END
    END
  -- BUSCA VALORES A DEBITO FIM -----------------------------------------------------------------------------------------------------------------

 -- BUSCA VALORES A CREDITO INICIO -----------------------------------------------------------------------------------------------------------------
  wsql = '';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    BEGIN
      -- centro de custo
      --#alt:5837.
      --wsql = wsql||'SELECT tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, ';
      wsql = wsql||'SELECT tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, ';

      --alt:6178 - 09/11/2015 - Verifica se foi informado um índice, caso positivo, divide o valor do lançamento pelo valor do índice na data. Função dos relatórios em outra moeda. Pedro
      IF (prindice = 0) THEN
        wsql = wsql||'sum(coalesce(tlcc.bdvalor, tlan.bdvalor)) as valor_credito ';
      ELSE
        BEGIN
          wsql = wsql||'coalesce(sum(coalesce(tlcc.bdvalor, tlan.bdvalor) / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                                     (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))),0) as valor_credito ';
        END
       --alt:6178 - Fim

      if (PRLANCSEMCC = 0) then
        begin
          wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';
          wsql = wsql||'join VSUC_EMPRESAS_TLCC TLCC on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP)) ';
        end
      else
        begin
          wsql = wsql||'FROM VSUC_EMPRESAS_TLAN TLAN ';
          wsql = wsql||'left outer join VSUC_EMPRESAS_TLCC TLCC on ((TLCC.BDCHAVE = TLAN.BDCHAVE) and (TLCC.BDCODEMP = TLAN.BDCODEMP) and (tlcc.bddebcre = 1)) ';
        end
    END
  ELSE
    BEGIN
      -- lancamentos
      --#alt:5837.
      --wsql = wsql || 'select tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, ';
      wsql = wsql || 'select tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, ';

      --alt:6178 - 09/11/2015 - Verifica se foi informado um índice, caso positivo, divide o valor do lançamento pelo valor do índice na data. Função dos relatórios em outra moeda. Pedro
      IF (prindice = 0) THEN
        wsql = wsql||'coalesce(sum(tlan.bdvalor),0) as valor_credito ';
      ELSE
        BEGIN
          wsql = wsql||'coalesce(sum(tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          wsql = wsql||'                                     (select first 1 BDVALIND from TINDVAL where BDCODIND = '||prindice||' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))),0) as valor_credito ';
        END
      --alt:6178 - Fim

      wsql = wsql || 'from vsuc_empresas_tlan tlan ';
    END
  wsql = wsql || 'left outer join VSUC_EMPRESAS_REL_TORCAMENTO_2 tbal on ((tlan.bdcodplapadrao = tbal.bdcodplapadrao) and (tlan.bdcredito = tbal.bdcodtpla)) ';
  wsql = wsql || 'where (tbal.bdcodplapadrao = '||prcodplapadrao||') ';
  IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
     wsql = wsql || 'and (tlan.bdtipolan <> 10) ';
  wsql = wsql || 'and (tbal.bdtipcta = 1) ';
  wsql = wsql || 'and (tlan.bddata between '''||prdataini||''' and '''||prdatafim||''') ';
  --#alt:5837.
  --wsql = wsql || 'and (tlan.bdcodemp = '||prcodigoemp||') ';
  wsql = wsql||'and (tlan.bdcodemp = '||prcodigoemp||') ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  IF ((prcc <> 0) AND (NOT (prcc IS NULL))) THEN
    begin
      wsql = wsql || 'AND ((TLCC.bdcodtpcc = '||prcc||') ';
      if (prlancsemcc = 1) then
        wsql = wsql || 'OR (TLCC.bdcodtpcc IS NULL)';
      wsql = wsql || ')';
    end
  wsql = wsql || 'Group By tlan.bdcodemp,tlan.bdfilial,tlan.bdtipolancfilial,tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon ';
  wsql = wsql || 'Order By tbal.bdctalon Desc ';

  -- pega a classificacao e o saldo total das analiticas _______________________
  FOR EXECUTE STATEMENT wsql INTO :wcodemp,:wfilial,:wtipolancfilial,:wcodigoplano,:wcodtpla,:wclassificacao,:wsaldo_credito DO
    BEGIN
      --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:prcodigoemp,:wcodemp,:wfilial,:wtipolancfilial,:prmatrizfilialconsolidado,:prcodigoemp) INTO :wpermite;
      IF (1 = 1) THEN
        BEGIN
          -- faz update no credito, pq ja foi gravado o lancamento antes zerado __
          --#alt:5837.
          /*update vsuc_empresas_rel_torcamento set BDCREDITO = :wsaldo_credito
          where bdcodemp = :prcodigoemp
          and   bdcodplapadrao = :wcodigoplano
          and   bdcodtpla = :wcodtpla
          and   bdctalon = :wclassificacao
          and   bddatahora = :prdatahora
          and   ((BDCREDITO = 0) or (bdcredito is null)); */
          wsql_aux = 'update vsuc_empresas_rel_torcamento_2 set ';
          wsql_aux = wsql_aux||'BDCREDITO = (coalesce(BDCREDITO,0) + '||wsaldo_credito||') ';
          wsql_aux = wsql_aux||'where bdcodemp = '||prcodigoemp||' and bdcodplapadrao = '||wcodigoplano;
          wsql_aux = wsql_aux||' and bdcodtpla = '||wcodtpla||' and bdctalon = '''||wclassificacao||'''';
          EXECUTE STATEMENT wsql_aux;
        END
    END
  -- BUSCA VALORES A CREDITO FIM -----------------------------------------------------------------------------------------------------------------

  -- BUSCA VALORES ORCADOS INICIO ---------------------------------------------------------------------------------------------------------------

  -- BUSCA VALORES ORCADOS FIM ---------------------------------------------------------------------------------------------------------------

  FOR SELECT tbal.bdcodplapadrao, tbal.bdcodtpla, tbal.bdctalon, tbal.bdtipcta
      FROM vsuc_empresas_rel_torcamento_2 tbal
      WHERE tbal.bdtipcta = 0
      INTO :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta DO
      BEGIN
        -- fas um select para totalizar as contas titulos ______________________
        SELECT coalesce(SUM(tbal.BDdebito), 0) AS valor_debito, coalesce(SUM(tbal.BDcredito), 0) AS valor_credito
        FROM vsuc_empresas_rel_torcamento_2 tbal
        WHERE bdctalon starting with :wclassificacao||'.'
        INTO :wsaldo_debito, :wsaldo_credito;

        -- da um update na tabela de balancete para gravar os totais ___________
        UPDATE vsuc_empresas_rel_torcamento_2 SET BDDEBITO = :wsaldo_debito,
                                            BDCREDITO = :wsaldo_credito
        WHERE bdcodemp = :prcodigoemp
        AND   bdcodplapadrao = :wcodigoplano
        AND   bdcodtpla = :wcodtpla
        AND   bdctalon = :wclassificacao;
      END

  -- faz o select na tabela de balancete e monta os retornos para a impressao
  FOR SELECT bdcodplapadrao, bdcodtpla, bdctalon, bdtipcta, bdgrpcta, bdnomcta,
             BDDEBITO, BDCREDITO, bdformula, bdrelcta
      FROM vsuc_empresas_rel_torcamento_2 tbal
      ORDER BY bdctalon ASC
      INTO :wcodigoplano, :wcodtpla, :wclassificacao, :wtipcta, :wgrpcta, :wnomcta,
       :wsaldo_debito, :wsaldo_credito, :formula, :relconta DO
      BEGIN
        codemp = :prcodigoemp;
        codplapadrao = :wcodigoplano;
        conta  = :wcodtpla;
        classificacao = :wclassificacao;
        nomeconta = :wnomcta;
        tipconta = :wtipcta;
        grupoconta = :wgrpcta;

        saldo_debsaida = :wsaldo_debito;
        saldo_cresaida = :wsaldo_credito;

        IF (saldo_debsaida IS NULL) THEN
           saldo_debsaida = 0;

        IF (saldo_cresaida IS NULL) THEN
           saldo_cresaida = 0;

        IF (wgrpcta IN (1,2,3)) THEN
           BDREALIZADO = (saldo_cresaida - saldo_debsaida);
        ELSE
           BDREALIZADO = (saldo_debsaida - saldo_cresaida);

        -- Filtro pelo nível da conta
        SELECT contar_char FROM contar_char(:wclassificacao,'.') INTO :wnivelconta;
        wnivelconta = wnivelconta + 1;
        SELECT BDRPOS FROM RPOS(','||CAST(:wnivelconta AS VARCHAR(100))||',',','||:prniveisconta||',') INTO :windice;
        IF ((prniveisconta = '9999') OR           -- Não tem filtro
            (wnivelconta = 1) OR                  -- O primeiro nível sempre imprime
            ((windice > 0) AND (:wtipcta = 0)) OR -- O nível da conta foi selecionado no filtro e é título
            ((windice > 0) AND (wimpanalitica > 0) AND (:wtipcta = 1))) THEN -- É do nível selecionado, analítica e foi selecionado para imprimir as contas analíticas
          SUSPEND;
      END

  DELETE FROM vsuc_empresas_rel_torcamento_2 WHERE 1=1;
END
^

/* Restore proc. body: VSUC_SP_RETORNA_SALDOS_CTA_PART */
ALTER PROCEDURE VSUC_SP_RETORNA_SALDOS_CTA_PART(PRCODEMP INTEGER,
PRCODPLAPADRAO INTEGER,
PRDTINICIAL DATE,
PRDTFINAL DATE,
PRCONTA INTEGER,
PRIGNORAZERAMENTO INTEGER,
PRCODTERCEIRO INTEGER,
PRRETORNAAPENASCONTAS INTEGER,
PRCONCILIADOS INTEGER,
PREMPRESAS VARCHAR(2048),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDNOME VARCHAR(100),
BDCLASSIFICACAO VARCHAR(40),
BDSALDO_DEB NUMERIC(15,2),
BDSALDO_ANT_DEB NUMERIC(15,2),
BDSALDO_CRE NUMERIC(15,2),
BDSALDO_ANT_CRE NUMERIC(15,2),
BDSALDO_ATUAL NUMERIC(15,2),
BDSALDO_ANTERIOR NUMERIC(15,2),
BDCODPARTICIPANTE INTEGER)
 AS
DECLARE VARIABLE wgrupocta INTEGER;
DECLARE VARIABLE wcodterceiro INTEGER;
DECLARE VARIABLE wnomterceiro VARCHAR(100);
DECLARE VARIABLE wdebito INTEGER;
DECLARE VARIABLE wcredito INTEGER;
DECLARE VARIABLE wsql VARCHAR(3000);
DECLARE VARIABLE wsql_aux VARCHAR(3000);
DECLARE VARIABLE wdtinicial VARCHAR(10);
DECLARE VARIABLE wdtfinal VARCHAR(10);
DECLARE VARIABLE wpermite INTEGER;
DECLARE VARIABLE wcodemp INTEGER;
DECLARE VARIABLE wfilial INTEGER;
DECLARE VARIABLE wtipolancfilial INTEGER;
DECLARE VARIABLE wsaldo_deb NUMERIC(15,2);
DECLARE VARIABLE wsaldo_cre NUMERIC(15,2);
DECLARE VARIABLE wsaldo_ant_deb NUMERIC(15,2);
DECLARE VARIABLE wsaldo_ant_cre NUMERIC(15,2);
DECLARE VARIABLE wpos_pernamatriz INTEGER;
DECLARE VARIABLE wpos_matriz INTEGER;
DECLARE VARIABLE wpos_filial INTEGER;
DECLARE VARIABLE wcampo INTEGER;
DECLARE VARIABLE wexist_debito INTEGER;
DECLARE VARIABLE wexist_credito INTEGER;
DECLARE VARIABLE wpos INTEGER;
DECLARE VARIABLE wposant INTEGER;
BEGIN
/*
conciliados
0 = normal
1 = conciliados
2 = não conciliados
3 = todos
*/
  bdnome           = '';
  bdsaldo_deb      = 0;
  bdsaldo_ant_deb  = 0;
  bdsaldo_cre      = 0;
  bdsaldo_ant_cre  = 0;
  bdsaldo_anterior = 0;
  bdsaldo_atual    = 0;

  IF ((prconta = 0) OR (prconta IS NULL)) THEN
    EXIT;

  SELECT planos_tpla.bdctalon, planos_tpla.bdgrupocta FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdcodtpla = :prconta
  INTO :bdclassificacao, :wgrupocta;

  wdtinicial = prdtinicial;
  wdtfinal   = prdtfinal;


  wsql = 'select tlan.bdcodter, terc.bdnometer, sum(bddebito), sum(bdcredito) from (';
  wsql = wsql||'select distinct tlan.bdcodterceirod as bdcodter,';--alt:#6535 - gilberto - 05/09/2013
  wsql = wsql||'1 as bddebito, 0 as bdcredito ';
  wsql = wsql||'from ';
  wsql = wsql||'( ';
  wsql = wsql||'  select distinct x.bdcodterceirod ';
  wsql = wsql||'  from vsuc_empresas_tlan x ';
  wsql = wsql||'  where x.bdcodterceirod is not null ';
  wsql = wsql||'  and (x.bdcodemp in ('||prcodemp||'))';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'  and (x.bdcontabilizacao in (0,'||prcontabilizacao||'))';
  wsql = wsql||'  and (x.bddebito = '||prconta||') ';--alt:#6535 - gilberto - 05/09/2013

  IF (prcodterceiro > 0) THEN
    wsql = wsql||'    and x.bdcodterceirod = ' || prcodterceiro;

  wsql = wsql||') tlan ';
  wsql = wsql||'union ';
  wsql = wsql||'select distinct tlan.bdcodterceiroc as bdcodter, ';--alt:#6535 - gilberto - 05/09/2013
  wsql = wsql||'0 as bddebito, 1 as bdcredito ';
  wsql = wsql||'from ';
  wsql = wsql||'( ';
  wsql = wsql||'  select distinct x.bdcodterceiroc ';
  wsql = wsql||'  from vsuc_empresas_tlan x ';
  wsql = wsql||'  where x.bdcodterceiroc is not null ';
  wsql = wsql||'  and (x.bdcodemp in ('||prcodemp||'))';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'  and (x.bdcontabilizacao in (0,'||prcontabilizacao||'))';
  wsql = wsql||'  and (x.bdcredito = '||prconta||') ';--alt:#6535 - gilberto - 05/09/2013

  IF (prcodterceiro > 0) THEN
    wsql = wsql||'    and x.bdcodterceiroc = ' || prcodterceiro;

  wsql = wsql||') tlan ';
  wsql = wsql||') tlan ';

  wsql = wsql||'inner join (select RF.bdcodter, RF.bdnometer ';
  wsql = wsql||'            from tterceiro_ref RF ';
  wsql = wsql||'            where RF.bdREFEMP = (select max(RF2.bdREFEMP) ';
  wsql = wsql||'                                 from TTERCEIRO_REF RF2 ';
  wsql = wsql||'                                 where RF.bdCODTER = RF2.bdCODTER)) terc on (terc.bdcodter = tlan.bdcodter) ';

  wsql = wsql||' group by bdcodter, bdnometer';

  FOR EXECUTE STATEMENT wsql
  INTO :wcodterceiro,:wnomterceiro, :WEXIST_DEBITO, :WEXIST_CREDITO DO
  BEGIN
    wsaldo_deb       = 0;
    wsaldo_cre       = 0;
    wsaldo_ant_deb   = 0;
    wsaldo_ant_cre   = 0;
    bdsaldo_deb      = 0;
    bdsaldo_ant_deb  = 0;
    bdsaldo_cre      = 0;
    bdsaldo_ant_cre  = 0;
    bdsaldo_anterior = 0;
    bdsaldo_atual    = 0;
    wsql_aux         = '';

    -- Pode ser que queira apenas montar as contas de participantes sem precisar dos saldos
    IF ((prretornaapenascontas = 0) OR (prretornaapenascontas IS NULL)) THEN
      BEGIN
        -- débito
        IF (wexist_debito = 1) THEN
           BEGIN
             wsql_aux = 'select tlan.bdcodemp, tlan.bddebito, ';
             wsql_aux = wsql_aux||'sum(case when (tlan.bddata < '''||prdtinicial||''') then tlan.bdvalor else 0 end) as bddebito_anterior, ';
             IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
                wsql_aux = wsql_aux||'sum(case when (((tlan.bddata > '''||prdtinicial||''') and (tlan.bdtipolan <> 10)) or (tlan.bddata < '''||prdtinicial||''')) then tlan.bdvalor else 0 end) as bddebito_atual ';
             ELSE
                wsql_aux = wsql_aux||'sum(coalesce(tlan.bdvalor, 0)) as bddebito_atual_com_zeramento ';
             wsql_aux = wsql_aux||'from vsuc_empresas_tlan tlan ';
--             wsql_aux = wsql_aux||'where (tlan.bdcodplapadrao = '||prcodplapadrao||') ';
             wsql_aux = wsql_aux||'where (tlan.bddata <= '''||prdtfinal||''') ';
             wsql_aux = wsql_aux||'and (bdcodplapadrao+0 = '||prcodplapadrao||') ';
             wsql_aux = wsql_aux||'and (tlan.bdcodemp in ('||prcodemp||')) ';
             IF (prcontabilizacao <> 99) THEN
                wsql_aux = wsql_aux||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
             wsql_aux = wsql_aux||'and (tlan.bddebito = '||prconta||') ';
             wsql_aux = wsql_aux||'and (tlan.bdcodterceirod = '||wcodterceiro||') ';
             IF (prconciliados = 1) THEN
                wsql_aux = wsql_aux||' and (upper(bdconcd) = '''||'TRUE'||''') ';
             ELSE
             IF (prconciliados = 2) THEN
                wsql_aux = wsql_aux||' and ((tlan.bdconcd is null) or (upper(tlan.bdconcd) = '''||'FALSE'||''')) ';
             wsql_aux = wsql_aux||'group by tlan.bdcodemp, tlan.bddebito ';
     
             FOR EXECUTE STATEMENT wsql_aux INTO :wcodemp, :wdebito, :wsaldo_ant_deb, :wsaldo_deb DO
               BEGIN
                 -- IF (NOT ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0))) THEN
                    -- BEGIN
                      -- wpos_pernamatriz = POSITION(wcodemp, prempresas);
                      -- wpos_matriz = POSITION(prcodemp, prempresas);
                      -- wpos_filial = POSITION(wfilial, prempresas);
                    -- END
                  wcampo = 1;
              
                  -- IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
                     wpermite = 1;
                  -- ELSE
                  -- IF (((wcodemp = prcodemp) AND (wfilial = 0)) OR
                      -- --Estou na filial mas o lançamento foi feito na matriz para a filial(uma perna)
                      -- ((wcodemp = wfilial) AND (wcampo = wtipolancfilial)) OR
                      -- --Estou na matriz e tem uma perna do lançamento na filial, mas só quero os lançamentos da matriz(a perna da matriz) e que a matriz esteja no filtro
                      -- ((wcodemp = prcodemp) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
                      -- --Estou na matriz mas também quero os lançamentos da filial conforme o filtro(Lançamentos que foram feito na filial -> BDCODEMP = Filial)
                      -- ((prmatrizfilialconsolidado = 1) AND (wcodemp <> prcodemp) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
                      -- --Estou na matriz mas também quero a perna que está na filial conforme o filtro
                      -- ((prmatrizfilialconsolidado = 1) AND (wcodemp = prcodemp) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
                     -- wpermite = 1;
                  -- ELSE
                     -- wpermite = 0;
     
     --            --select bdpermite from vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:wcodemp,:prmatrizfilialconsolidado,:prempresas) into :wpermite;
                 --IF (wpermite = 1) THEN
                    --BEGIN
                      bdsaldo_deb = bdsaldo_deb + wsaldo_deb;
                      bdsaldo_ant_deb = bdsaldo_ant_deb + wsaldo_ant_deb;
                    --END
                    END
               END

        -- crédito'
        IF (wexist_credito = 1) THEN
           BEGIN
             wsql_aux = 'select tlan.bdcodemp, tlan.bdcredito, ';
             wsql_aux = wsql_aux||'sum(case when (tlan.bddata < '''||prdtinicial||''') then tlan.bdvalor else 0 end) as bdcredito_anterior, ';
             IF ((prignorazeramento IS NOT NULL) AND (prignorazeramento <> 0)) THEN
                wsql_aux = wsql_aux||'sum(case when (((tlan.bddata > '''||prdtinicial||''') and (tlan.bdtipolan <> 10)) or (tlan.bddata < '''||prdtinicial||''')) then tlan.bdvalor else 0 end) as bdcredito_atual ';
             ELSE
                wsql_aux = wsql_aux||'sum(coalesce(tlan.bdvalor, 0)) as bdcredito_atual_com_zeramento ';
             wsql_aux = wsql_aux||'from vsuc_empresas_tlan tlan ';
--             wsql_aux = wsql_aux||'where (tlan.bdcodplapadrao = '||prcodplapadrao||') ';
             wsql_aux = wsql_aux||'where (tlan.bddata <= '''||prdtfinal||''') ';
             wsql_aux = wsql_aux||'and (bdcodplapadrao+0 = '||prcodplapadrao||') ';
             wsql_aux = wsql_aux||'and (tlan.bdcodemp in ('||prcodemp||')) ';
             IF (prcontabilizacao <> 99) THEN
                wsql_aux = wsql_aux||'and (tlan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
             wsql_aux = wsql_aux||'and (tlan.bdcredito = '||prconta||') ';
             wsql_aux = wsql_aux||'and (tlan.bdcodterceiroc = '||wcodterceiro||') ';
             IF (prconciliados = 1) THEN
                wsql_aux = wsql_aux||' and (upper(bdconcc) = '''||'TRUE'||''') ';
             ELSE
             IF (prconciliados = 2) THEN
                wsql_aux = wsql_aux||' and ((tlan.bdconcc is null) or (upper(tlan.bdconcc) = '''||'FALSE'||''')) ';
             wsql_aux = wsql_aux||'group by tlan.bdcodemp, tlan.bdcredito ';
     
             FOR EXECUTE STATEMENT wsql_aux INTO :wcodemp, :wcredito, :wsaldo_ant_cre, :wsaldo_cre DO
               BEGIN
                 -- IF (NOT ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0))) THEN
                    -- BEGIN
                      -- wpos_pernamatriz = POSITION(wcodemp, prempresas);
                      -- wpos_matriz = POSITION(prcodemp, prempresas);
                      -- wpos_filial = POSITION(wfilial, prempresas);
                    -- END
                  wcampo = 2;
              
                  -- IF ((wtipolancfilial = 0) AND (COALESCE(wfilial, 0) = 0)) THEN
                     wpermite = 1;
                  -- ELSE
                  -- IF (((wcodemp = prcodemp) AND (wfilial = 0)) OR
                      -- --Estou na filial mas o lançamento foi feito na matriz para a filial(uma perna)
                      -- ((wcodemp = wfilial) AND (wcampo = wtipolancfilial)) OR
                      -- --Estou na matriz e tem uma perna do lançamento na filial, mas só quero os lançamentos da matriz(a perna da matriz) e que a matriz esteja no filtro
                      -- ((wcodemp = prcodemp) AND (wfilial <> 0) AND (wcampo <> wtipolancfilial) AND (wpos_pernamatriz > 0)) OR
                      -- --Estou na matriz mas também quero os lançamentos da filial conforme o filtro(Lançamentos que foram feito na filial -> BDCODEMP = Filial)
                      -- ((prmatrizfilialconsolidado = 1) AND (wcodemp <> prcodemp) AND (wfilial = 0) AND (wpos_matriz > 0)) OR
                      -- --Estou na matriz mas também quero a perna que está na filial conforme o filtro
                      -- ((prmatrizfilialconsolidado = 1) AND (wcodemp = prcodemp) AND (wfilial <> 0) AND (wcampo = wtipolancfilial) AND (wpos_filial > 0))) THEN
                     -- wpermite = 1;
                  -- ELSE
                     -- wpermite = 0;
                  -------------------------------------------------------------------alt:#6524
     
     --        --    select bdpermite from vsuc_sp_permitecalcsaldolancmf(1,:prcodemp,:wcodemp,:prmatrizfilialconsolidado,:prempresas) into :wpermite;
                 --IF (wpermite = 1) THEN
                    --BEGIN
                      bdsaldo_cre = bdsaldo_cre + wsaldo_cre;
                      bdsaldo_ant_cre = bdsaldo_ant_cre + wsaldo_ant_cre;
                    --END
                    END
               END

      bdcodparticipante = wcodterceiro;
      bdnome            = SUBSTRING(wnomterceiro FROM 1 FOR 100);

      wpos = 0;
      wposant = 0;
      WHILE (wpos > 0) DO
        BEGIN
          wpos = POSITION('.', bdclassificacao, wpos);
          wposant = wpos;
        END
      bdclassificacao = SUBSTRING(bdclassificacao FROM 1 FOR wposant)||LPAD(wcodterceiro, 8, '0');


      IF (wgrupocta IN (1,2,3)) THEN
         bdsaldo_anterior = (bdsaldo_ant_cre - bdsaldo_ant_deb);
      ELSE
         bdsaldo_anterior = (bdsaldo_ant_deb - bdsaldo_ant_cre);
  
      IF (wgrupocta IN (1,2,3)) THEN
         bdsaldo_atual = (bdsaldo_cre - bdsaldo_deb);
      ELSE
         bdsaldo_atual = (bdsaldo_deb - bdsaldo_cre);
  
      bdsaldo_cre = bdsaldo_cre - bdsaldo_ant_cre;
      bdsaldo_deb = bdsaldo_deb - bdsaldo_ant_deb;
      SUSPEND;
    END
  END
END
^

/* Restore proc. body: SP_GET_CLASSIFICACAO_NIVEL */
CREATE OR ALTER PROCEDURE SP_GET_CLASSIFICACAO_NIVEL (
    PRCLASSIFICACAO VARCHAR(100),
    PRNIVEL INTEGER)
RETURNS (
    BDCLASSIFICACAO VARCHAR(100))
AS
DECLARE VARIABLE WCOUNT INTEGER;
BEGIN
  /* Procedure Text */
  WCOUNT = 0;
  IF (CHAR_LENGTH(PRCLASSIFICACAO) - CHAR_LENGTH(REPLACE(PRCLASSIFICACAO, '.', '')) <= PRNIVEL - 1) THEN
    BDCLASSIFICACAO = PRCLASSIFICACAO;
  ELSE
  BEGIN
    WCOUNT = 0;
    BDCLASSIFICACAO = '';
    WHILE (WCOUNT < PRNIVEL) DO
    BEGIN
      IF (BDCLASSIFICACAO <> '') THEN
        BDCLASSIFICACAO = BDCLASSIFICACAO || '.';
      BDCLASSIFICACAO = BDCLASSIFICACAO || SUBSTRING(PRCLASSIFICACAO FROM 1 FOR POSITION('.', PRCLASSIFICACAO) - 1);
      PRCLASSIFICACAO = SUBSTRING(PRCLASSIFICACAO FROM POSITION('.', PRCLASSIFICACAO) + 1);
      WCOUNT = WCOUNT + 1;
    END
  END
  SUSPEND;
END
^

/* Restore proc. body: VSUC_SP_RETORNA_SALDOS_CTAPARTY */
create or alter procedure VSUC_SP_RETORNA_SALDOS_CTAPARTY (
    PRCODEMP integer,
    PRCODPLAPADRAO integer,
    PRDTINICIAL date,
    PRDTFINAL date,
    PRCONTA integer,
    PRINDICE integer,
    PRIGNORAZERAMENTO integer,
    PRCODTERCEIRO integer,
    PRCONCILIADOS varchar(20),
    PREMPRESAS varchar(2048),
    PRCONTABILIZACAO integer,
    PRAGRUPARPARTICIPANTEPORCNPJ integer = 0,
    PRCC DM_MAXVARCHAR = '',
    PRLANCSEMCC integer = 0,
    PRAGRUPARPARTICIPANTEPORCPF integer = 0,
    PRNIVELCC integer = 0,
    PRSOMENTEMOVIMENTO integer = 0,
    PRREFEMP integer = 0,
    PRTODOSPART varchar(2048) = '',
    PRTIPOLAN varchar(3200) = '',
    PREMPRESAGRPECO integer = 0,
    PRGRPECO integer = 0,
    PRELIMINACOESK300K315 integer = 0)
returns (
    BDNOME varchar(100),
    BDCLASSIFICACAO varchar(40),
    BDSALDO_DEB numeric(15,2),
    BDSALDO_ANT_DEB numeric(15,2),
    BDSALDO_CRE numeric(15,2),
    BDSALDO_ANT_CRE numeric(15,2),
    BDMOVIMENTO numeric(15,2),
    BDSALDO_ATUAL numeric(15,2),
    BDSALDO_ANTERIOR numeric(15,2),
    BDCODPARTICIPANTE integer,
    BDRAIZCNPJPARTICIPANTE varchar(10),
    BDRAIZCLASSIFICACAOCTA varchar(40),
    BDCENTROCUSTO integer,
    BDNOMTPCC varchar(40),
    BDTPCCLON varchar(20),
    BDVALOR_NAO_CONCILIADO numeric(15,2),
    BDCGCTER varchar(18),
    BDDATAULTLANCAMENTO date)
as
declare variable WGRUPOCTA integer;
declare variable WSQL varchar(32765);
declare variable WSQL_EMP varchar(5000);
declare variable WPERMITE integer;
declare variable WCODEMP integer;
declare variable WCLASSIFICACAO varchar(40);
declare variable WEMPRESAS varchar(2048);
declare variable WCODTPLA integer;
declare variable WCODPARTICIPANTE integer;
declare variable WCNPJPART varchar(18);
declare variable WCNPJANTPART varchar(10);
declare variable WSALDO_DEB numeric(15,6);
declare variable WSALDO_ANT_DEB numeric(15,6);
declare variable WSALDO_CRE numeric(15,6);
declare variable WSALDO_ANT_CRE numeric(15,6);
declare variable WNOME varchar(100);
declare variable WCODPAIS integer;
declare variable WCODPAISANT integer;
declare variable WCODCID integer;
declare variable WDEBCRE integer;
declare variable WPARTEXTERIORANT integer;
declare variable WVALORFIELD varchar(100);
declare variable WCCANT integer;
declare variable WCCATU integer;
declare variable WNOMTPCC varchar(40);
declare variable WTPCCLON varchar(20);
declare variable WSQLCONCILIACAO varchar(1000);
declare variable WVALOR_N_CONC numeric(15,2);
declare variable WCNPJORIGINAL varchar(18);
declare variable WCNPJORIGINAL_ANT varchar(18);
declare variable WTERAUX integer;
declare variable WZERAMENTOSIGNORAR varchar(250);
declare variable WREFANT integer;
declare variable WDATAULTLANCAMENTO date;
BEGIN
  WREFANT = rdb$get_context('USER_SESSION', 'W_ANOMES');
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prrefemp);
  WPARTEXTERIORANT = 0;
  IF (PRCC IS NULL) THEN
    PRCC = '';
  /* Conciliados
    0 = normal
    1 = conciliados
    2 = n??o conciliados
    3 = todos */
  --Machado - 04/01/2019 - #91350
  IF (PRCC = '') THEN
    WVALORFIELD = 'TLAN.BDVALOR';
  ELSE
    WVALORFIELD = 'IIF(TLCC.BDDEBCRE IS NULL, TLAN.BDVALOR, TLCC.BDVALOR)';

  IF ((PRCONTA = 0) OR (PRCONTA IS NULL)) THEN
    EXIT;

  SELECT PLANOS_TPLA.BDCTALON, PLANOS_TPLA.BDGRUPOCTA
  FROM PLANOS_TPLA
  WHERE PLANOS_TPLA.BDCODPLAPADRAO = :PRCODPLAPADRAO AND
        PLANOS_TPLA.BDCODTPLA = :PRCONTA
  INTO :WCLASSIFICACAO, :WGRUPOCTA;

  -- #Alt:15233 (In??cio) - Precisamos carregar todos os lançamentos da matriz e filiais e depois controlar se deve imprimir ou
  -- não os dados. Isso é necessário porque o usuário pode selecionar só as filiais, mas tem casos que o lançamento foi feito na
  -- na matriz e apenas uma perna está na filial. Por isso preciso carregar os lançamentos.
  WEMPRESAS = '';
  SELECT COALESCE(BDCODMATRIZ, 0)
  FROM TEMPRESAS
  WHERE BDCODEMP = :PRCODEMP
  INTO :WCODEMP;
  IF (WCODEMP > 0) THEN
    BEGIN
      FOR SELECT BDCODEMP
         FROM TEMPRESAS
         WHERE (BDCODMATRIZ = COALESCE((SELECT FIRST 1 BDCODMATRIZ
                                        FROM TEMPRESAS
                                        WHERE BDCODEMP = :PRCODEMP), :PRCODEMP)) OR (BDCODEMP = COALESCE((SELECT FIRST 1 BDCODMATRIZ
                                                                                                          FROM TEMPRESAS
                                                                                                          WHERE BDCODEMP = :PRCODEMP), :PRCODEMP))
        INTO :WCODEMP
      DO
        BEGIN
          WEMPRESAS = WEMPRESAS || WCODEMP || ',';
        END
    END

  WZERAMENTOSIGNORAR = '';
  IF (PRIGNORAZERAMENTO = 2) THEN
    SELECT LIST(E.BDCHAVEZER, ',')
    FROM TMP_VSUC_EMPRESAS_TENCEXE E
    WHERE E.BDCODEMP = :PRCODEMP
    INTO :WZERAMENTOSIGNORAR;

  IF (WZERAMENTOSIGNORAR <> '') THEN
    WSQL_EMP = 'tlan.bdtipolan <> 10 or tlan.bdchavezer not in (' || WZERAMENTOSIGNORAR || ')';
  ELSE
    WSQL_EMP = 'tlan.bdtipolan <> 10';
  WZERAMENTOSIGNORAR = WSQL_EMP;

  IF (WEMPRESAS = '') THEN
    WEMPRESAS = PREMPRESAS || ',';

  WSQL_EMP = ' and (';

  IF (POSITION(',', PREMPRESAS) > 0) THEN
    WSQL_EMP = WSQL_EMP || ' (tlan.bdcodemp = ' || PRCODEMP || ')';
  ELSE
    WSQL_EMP = WSQL_EMP || '(tlan.bdcodemp = ' || PRCODEMP || ')';
  WSQL_EMP = WSQL_EMP || ') ';
  -- #Alt:15233 (Fim)

  --alt:9167 - Alterado select para trazer a parte inicial do CNPJ e retirado o BDNOMETER, pois ele sempre retorna null aqui, ele ?? setado no final, na hora de commitar. Pedro
  WSQL = 'select bdcodemp, tlan.bdcodtpla, tlan.bdcodter, bdcgcter, bddebcre, '; --alt:14679 - Adicionado campo BDDEBCRE. Pedro
  IF (PRCC != '') THEN
    WSQL = WSQL || 'TPCC.BDCODTPCC, TPCC.BDNOMCTA, TPCC.BDCTALON AS BDTPCCLON,';
  ELSE
    WSQL = WSQL || 'null as BDCODTPCC, null as BDNOMCTA, NULL AS BDTPCCLON, ';

  WSQL = WSQL || '       sum(case when (bddebcre = 0) then BDVALCONC else -BDVALCONC end) as BDVALCONC,';
  WSQL = WSQL || '       sum(case when (bddebcre = 0) then bdsalant else 0 end) as bddebant,';
  WSQL = WSQL || '       sum(case when (bddebcre = 0) then bdsalatu else 0 end) as bddebatu,';
  WSQL = WSQL || '       sum(case when (bddebcre = 1) then bdsalant else 0 end) as bdcreant,';
  WSQL = WSQL || '       sum(case when (bddebcre = 1) then bdsalatu else 0 end) as bdcreatu,';
  WSQL = WSQL || '       max(bddata)';
  WSQL = WSQL || ' from (';

  if (:PRELIMINACOESK300K315 = 1) then
   WSQL = WSQL || 'select * from(';

  --****************************************************************************  D??bito  **************************************************************************************************
  WSQL = WSQL || 'select tlan.bdcodemp, tlan.bdcodplapadrao, tlan.bddata, tlan.bdtipolan, ';
  WSQL = WSQL || '       tlan.bddebito as bdcodtpla, tlan.bdcodterceirod as bdcodter, ';
  WSQL = WSQL || '       0 as bddebcre, ';
  IF (PRCC != '') THEN
    WSQL = WSQL || '     tlcc.BDCODTPCC, tlcc.BDCODCENTRO,  ';

  --alt:6178 - 09/11/2015 - Verifica se foi informado um ??ndice, caso positivo, divide o valor do lan??amento pelo valor do ??ndice na data. Fun????o dos relat??rios em outra moeda. Pedro
  IF (PRINDICE = 0) THEN
    BEGIN
      WSQL = WSQL || 'sum(case when (tlan.bddata < ''' || PRDTINICIAL || ''') then ' || WVALORFIELD || ' else 0 end) as bdsalant, ';
      IF ((PRIGNORAZERAMENTO IS NOT NULL) AND
          (PRIGNORAZERAMENTO <> 0)) THEN
        BEGIN
          --#alt:131626 - Machado - valores sem concilia????o
          WSQL = WSQL || 'sum(case when ((COALESCE(UPPER(TLAN.BDCONCD), ''FALSE'') <> ''TRUE'' or coalesce(TLAN.BDCONCILIACAOPENDENTE, 0) IN (1,3)) and (((tlan.bddata >= ''' || PRDTINICIAL || ''') and (' || WZERAMENTOSIGNORAR || ')) or (tlan.bddata < ''' || PRDTINICIAL || '''))) THEN TLAN.BDVALOR ELSE 0 end) as BDVALCONC,';
          WSQL = WSQL || 'sum(case when (((tlan.bddata >= ''' || PRDTINICIAL || ''') and (' || WZERAMENTOSIGNORAR || ')) or (tlan.bddata < ''' || PRDTINICIAL || ''')) then ' || WVALORFIELD || ' else 0 end) as bdsalatu ';
        END
      ELSE
        BEGIN
          --#alt:131626 - Machado - valores sem concilia????o
          WSQL = WSQL || 'sum(case when (COALESCE(UPPER(TLAN.BDCONCD), ''FALSE'') <> ''TRUE'' or coalesce(TLAN.BDCONCILIACAOPENDENTE, 0) IN (1,3)) THEN TLAN.BDVALOR ELSE 0 end) as BDVALCONC,';
          WSQL = WSQL || 'sum(coalesce(' || WVALORFIELD || ', 0)) as bdsalatu '; -- com zeramento
        END
      WSQL = WSQL || '';
    END
  ELSE
    BEGIN
      WSQL = WSQL || 'sum(case when (tlan.bddata < ''' || PRDTINICIAL || ''') then ' || WVALORFIELD || ' / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
      WSQL = WSQL || '                                                                                 (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalant, ';
      WSQL = WSQL || '0 as BDVALCONC';
      IF ((PRIGNORAZERAMENTO IS NOT NULL) AND
          (PRIGNORAZERAMENTO <> 0)) THEN
        BEGIN
          WSQL = WSQL || ',sum(case when (((tlan.bddata >= ''' || PRDTINICIAL || ''') and (' || WZERAMENTOSIGNORAR || ')) or (tlan.bddata < ''' || PRDTINICIAL || ''')) then ';
          WSQL = WSQL || WVALORFIELD || ' / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          WSQL = WSQL || '                        (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalatu ';
        END
      ELSE
        BEGIN
          WSQL = WSQL || ',sum(' || WVALORFIELD || ' / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          WSQL = WSQL || '                            (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))) as bdsalatu '; -- com zeramento
        END
    END
  --alt:6178 - 09/11/2015 - Fim

  WSQL = WSQL || 'from vsuc_empresas_tlan tlan ';
  IF (PRCC != '') THEN
    WSQL = WSQL || ' left outer join vsuc_empresas_tlcc tlcc on (tlcc.BDCODEMP = tlan.BDCODEMP and tlcc.BDCHAVE = tlan.bdchave and tlcc.BDDEBCRE = 0)';
  WSQL = WSQL || 'where (tlan.bdcodplapadrao+0 = ' || PRCODPLAPADRAO || ') ';
  WSQL = WSQL || 'and (tlan.bddata <= ''' || PRDTFINAL || ''') ';
  IF (PRSOMENTEMOVIMENTO = 1) THEN
    WSQL = WSQL || 'and (tlan.bddata >= ''' || PRDTINICIAL || ''') ';
  WSQL = WSQL || 'and (tlan.bddebito = ' || PRCONTA || ') ';
  IF ((PRCODTERCEIRO IS NOT NULL) AND
      (PRCODTERCEIRO <> 0)) THEN
    WSQL = WSQL || 'and (tlan.bdcodterceirod = ' || PRCODTERCEIRO || ') ';
  ELSE
    WSQL = WSQL || 'and (tlan.bdcodterceirod is not null) ';
  IF (PRCONTABILIZACAO <> 99) THEN
    WSQL = WSQL || 'and (tlan.bdcontabilizacao in (0,' || PRCONTABILIZACAO || '))';

  IF (PRTIPOLAN <> '') THEN --#212425
    WSQL = WSQL || ' and (tlan.bdtipolan in ('||PRTIPOLAN||'))';

  SELECT BDSQLCONCILIADO
  FROM VSUC_SP_MONTA_CONCILIACAO(:PRCONCILIADOS, 'tlan.bdconcd', '', '')
  INTO :WSQLCONCILIACAO;
  IF (WSQLCONCILIACAO <> '') THEN
    WSQL = WSQL || ' and ' || WSQLCONCILIACAO;
  WSQL = WSQL || WSQL_EMP;

  WSQL = WSQL || 'group by tlan.bdcodemp, tlan.bdcodplapadrao, tlan.bddata, tlan.bddebito, tlan.bdcodterceirod, tlan.bdtipolan ';
  IF (PRCC != '') THEN
    WSQL = WSQL || ', tlcc.BDCODTPCC, tlcc.BDCODCENTRO ';

  if (:PRELIMINACOESK300K315 = 1) then
  begin
    WSQL = WSQL || ' union all';
    WSQL = WSQL || '   select K300.BDCODEMPGRPECO, '||PRCODPLAPADRAO||' as BDCODPLAPADRAO, K310.BDDATAREF, null as BDTIPOLAN, K300.BDCODTPLA,';
    WSQL = WSQL || '          K300.BDCODTERCEIRO BDCODTER, 0 as BDDEBITO,';
    WSQL = WSQL || '          case';
    WSQL = WSQL || '             when (K310.BDDATAREF < ''' || PRDTINICIAL || ''') then ELIK310.BDVLRELIMK315';
    WSQL = WSQL || '              else 0';
    WSQL = WSQL || '           end as BDSALANT,';
    WSQL = WSQL || '           null as BDVALCONC, ELIK310.BDVLRELIMK315 as BDSALATU';
    WSQL = WSQL || '    from VSUC_EMP_TLAN_SPED_K315 K315';
    WSQL = WSQL || '    left join VSUC_EMP_TLAN_SPED_K300 K300 on (K300.BDCODK300 = K315.BDCODK300 and';
    WSQL = WSQL || '          K300.BDCODEMPGRPECO = K315.BDCODEMPGRPECO and';
    WSQL = WSQL || '          K300.BDCODGRPECO = K315.BDCODGRPECO)';
    WSQL = WSQL || '    inner join VSUC_EMP_TLAN_SPED_K310 K310 on (K310.BDCODK300 = K315.BDCODK300 and';
    WSQL = WSQL || '          K310.BDCODEMPGRPECO = K315.BDCODEMPGRPECO and';
    WSQL = WSQL || '          K310.BDCODGRPECO = K315.BDCODGRPECO and';
    WSQL = WSQL || '          K310.BDCODK310 = K315.BDCODK310)';
    WSQL = WSQL || '    left join VSUC_EMP_TLAN_SPED_K315 ELIK310 on (K310.BDCODK300 = ELIK310.BDCODK300 and';
    WSQL = WSQL || '          K310.BDCODEMPGRPECO = ELIK310.BDCODEMPGRPECO and';
    WSQL = WSQL || '          K310.BDCODGRPECO = ELIK310.BDCODGRPECO and';
    WSQL = WSQL || '          K310.BDCODK310 = ELIK310.BDCODK310)';
    WSQL = WSQL || '    where K300.BDCODEMPGRPECO = '||PREMPRESAGRPECO||' and';
    WSQL = WSQL || '          K300.BDCODGRPECO = '||PRGRPECO||' and';
    WSQL = WSQL || '          K300.BDTIPCONT = 0 and';
	WSQL = WSQL || '          K310.BDCODEMPK310 in ('||PREMPRESAS||') and';
    WSQL = WSQL || '          K315.BDCODTPLA is not null and';
    WSQL = WSQL || '          ELIK310.BDSITELIMK315 = 0 and';
    WSQL = WSQL || '          K300.BDCODTPLA = '|| PRCONTA;
    WSQL = WSQL || '    group by K300.BDCODEMPGRPECO, BDCODTPLA, BDCODTER, BDDEBITO, K310.BDDATAREF,BDSALANT, BDSALATU)';
  end
  WSQL = WSQL || ' union ';

  if (:PRELIMINACOESK300K315 = 1) then
   WSQL = WSQL || ' select * from(';

  --****************************************************************************  Cr??dito  *************************************************************************************************
  WSQL = WSQL || 'select tlan.bdcodemp, tlan.bdcodplapadrao, tlan.bddata, tlan.bdtipolan, ';
  WSQL = WSQL || '       tlan.bdcredito as bdcodtpla, tlan.bdcodterceiroc as bdcodter, ';
  WSQL = WSQL || '       1 as bddebcre, ';
  IF (PRCC != '') THEN
    WSQL = WSQL || '     tlcc.BDCODTPCC, tlcc.BDCODCENTRO, ';

  --alt:6178 - 09/11/2015 - Verifica se foi informado um ??ndice, caso positivo, divide o valor do lan??amento pelo valor do ??ndice na data. Fun????o dos relat??rios em outra moeda. Pedro
  IF (PRINDICE = 0) THEN
    BEGIN
      WSQL = WSQL || 'sum(case when (tlan.bddata < ''' || PRDTINICIAL || ''') then ' || WVALORFIELD || ' else 0 end) as bdsalant, ';
      IF ((PRIGNORAZERAMENTO IS NOT NULL) AND
          (PRIGNORAZERAMENTO <> 0)) THEN
        BEGIN
          --#alt:131626 - Machado - valores sem concilia????o
          WSQL = WSQL || 'sum(case when ((COALESCE(UPPER(TLAN.BDCONCC), ''FALSE'') <> ''TRUE'' or coalesce(TLAN.BDCONCILIACAOPENDENTE, 0) IN (2,3)) and (((tlan.bddata >= ''' || PRDTINICIAL || ''') and (' || WZERAMENTOSIGNORAR || ')) or (tlan.bddata < ''' || PRDTINICIAL || '''))) THEN TLAN.BDVALOR ELSE 0 end) as BDVALCONC,';
          WSQL = WSQL || 'sum(case when (((tlan.bddata >= ''' || PRDTINICIAL || ''') and (' || WZERAMENTOSIGNORAR || ')) or (tlan.bddata < ''' || PRDTINICIAL || ''')) then ' || WVALORFIELD || ' else 0 end) as bdsalatu ';
        END
      ELSE
        BEGIN
          --#alt:131626 - Machado - valores sem concilia????o
          WSQL = WSQL || 'sum(case when (COALESCE(UPPER(TLAN.BDCONCC), ''FALSE'') <> ''TRUE'' or coalesce(TLAN.BDCONCILIACAOPENDENTE, 0) IN (2,3)) THEN TLAN.BDVALOR ELSE 0 end) as BDVALCONC,';
          WSQL = WSQL || 'sum(coalesce(' || WVALORFIELD || ', 0)) as bdsalatu '; -- com zeramento
        END
      WSQL = WSQL || '';
    END
  ELSE
    BEGIN
      WSQL = WSQL || 'sum(case when (tlan.bddata < ''' || PRDTINICIAL || ''') then tlan.bdvalor / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
      WSQL = WSQL || '                                                                                 (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalant, ';
      WSQL = WSQL || ' null as BDVALCONC,';
      IF ((PRIGNORAZERAMENTO IS NOT NULL) AND
          (PRIGNORAZERAMENTO <> 0)) THEN
        BEGIN
          WSQL = WSQL || 'sum(case when (((tlan.bddata >= ''' || PRDTINICIAL || ''') and (' || WZERAMENTOSIGNORAR || ')) or (tlan.bddata < ''' || PRDTINICIAL || ''')) then ';
          WSQL = WSQL || '' || WVALORFIELD || ' / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          WSQL = WSQL || '                        (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc)) else 0 end) as bdsalatu ';
        END
      ELSE
        BEGIN
          WSQL = WSQL || 'sum(' || WVALORFIELD || ' / coalesce((select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND <= tlan.BDDATA order by BDCODIND desc, BDDATAIND desc),';
          WSQL = WSQL || '                            (select first 1 BDVALIND from TINDVAL where BDCODIND = ' || PRINDICE || ' and BDDATAIND > tlan.BDDATA order by BDCODIND asc, BDDATAIND asc))) as bdsalatu '; -- com zeramento
        END
    END
  --alt:6178 - Fim

  WSQL = WSQL || 'from vsuc_empresas_tlan tlan ';
  IF (PRCC != '') THEN
    WSQL = WSQL || ' left outer join vsuc_empresas_tlcc tlcc on (tlcc.BDCODEMP = tlan.BDCODEMP and tlcc.BDCHAVE = tlan.bdchave and tlcc.BDDEBCRE = 1)';

  WSQL = WSQL || 'where (tlan.bdcodplapadrao+0 = ' || PRCODPLAPADRAO || ') ';
  WSQL = WSQL || 'and (tlan.bddata <= ''' || PRDTFINAL || ''') ';
  IF (PRSOMENTEMOVIMENTO = 1) THEN
    WSQL = WSQL || 'and (tlan.bddata >= ''' || PRDTINICIAL || ''') ';
  WSQL = WSQL || 'and (tlan.bdcredito = ' || PRCONTA || ') ';
  IF ((PRCODTERCEIRO IS NOT NULL) AND
      (PRCODTERCEIRO <> 0)) THEN
    WSQL = WSQL || 'and (tlan.bdcodterceiroc = ' || PRCODTERCEIRO || ') ';
  ELSE
    WSQL = WSQL || 'and (tlan.bdcodterceiroc is not null) ';
  IF (PRCONTABILIZACAO <> 99) THEN
    WSQL = WSQL || 'and (tlan.bdcontabilizacao in (0,' || PRCONTABILIZACAO || '))';

  IF (PRTIPOLAN <> '') THEN --#212425
    WSQL = WSQL || ' and (tlan.bdtipolan in ('||PRTIPOLAN||'))';

  SELECT BDSQLCONCILIADO
  FROM VSUC_SP_MONTA_CONCILIACAO(:PRCONCILIADOS, 'tlan.bdconcc', '', '')
  INTO :WSQLCONCILIACAO;
  IF (WSQLCONCILIACAO <> '') THEN
    WSQL = WSQL || ' and ' || WSQLCONCILIACAO;
  WSQL = WSQL || WSQL_EMP;
  WSQL = WSQL || 'group by tlan.bdcodemp, tlan.bdcodplapadrao, tlan.bddata, tlan.bdcredito, tlan.bdcodterceiroc, tlan.bdtipolan ';
  IF (PRCC != '') THEN
    WSQL = WSQL || ', tlcc.BDCODTPCC, tlcc.BDCODCENTRO ';

  if (:PRELIMINACOESK300K315 = 1) then
  begin
    WSQL = WSQL || ' union all';
    WSQL = WSQL || '   select K300.BDCODEMPGRPECO, '||PRCODPLAPADRAO||' as BDCODPLAPADRAO, K310.BDDATAREF, null as BDTIPOLAN, K300.BDCODTPLA,';
    WSQL = WSQL || '          K300.BDCODTERCEIRO BDCODTER, 1 as BDDEBITO,';
    WSQL = WSQL || '          case';
    WSQL = WSQL || '             when (K310.BDDATAREF < ''' || PRDTINICIAL || ''') then ELIK310.BDVLRELIMK315';
    WSQL = WSQL || '              else 0';
    WSQL = WSQL || '           end as BDSALANT,';
    WSQL = WSQL || '           null as BDVALCONC, ELIK310.BDVLRELIMK315 as BDSALATU';
    WSQL = WSQL || '    from VSUC_EMP_TLAN_SPED_K315 K315';
    WSQL = WSQL || '    left join VSUC_EMP_TLAN_SPED_K300 K300 on (K300.BDCODK300 = K315.BDCODK300 and';
    WSQL = WSQL || '          K300.BDCODEMPGRPECO = K315.BDCODEMPGRPECO and';
    WSQL = WSQL || '          K300.BDCODGRPECO = K315.BDCODGRPECO)';
    WSQL = WSQL || '    inner join VSUC_EMP_TLAN_SPED_K310 K310 on (K310.BDCODK300 = K315.BDCODK300 and';
    WSQL = WSQL || '          K310.BDCODEMPGRPECO = K315.BDCODEMPGRPECO and';
    WSQL = WSQL || '          K310.BDCODGRPECO = K315.BDCODGRPECO and';
    WSQL = WSQL || '          K310.BDCODK310 = K315.BDCODK310)';
    WSQL = WSQL || '    left join VSUC_EMP_TLAN_SPED_K315 ELIK310 on (K310.BDCODK300 = ELIK310.BDCODK300 and';
    WSQL = WSQL || '          K310.BDCODEMPGRPECO = ELIK310.BDCODEMPGRPECO and';
    WSQL = WSQL || '          K310.BDCODGRPECO = ELIK310.BDCODGRPECO and';
    WSQL = WSQL || '          K310.BDCODK310 = ELIK310.BDCODK310)';
    WSQL = WSQL || '    where K300.BDCODEMPGRPECO = '||PREMPRESAGRPECO||' and';
    WSQL = WSQL || '          K300.BDCODGRPECO = '||PRGRPECO||' and';
    WSQL = WSQL || '          K300.BDTIPCONT = 0 and';
	WSQL = WSQL || '          K310.BDCODEMPK310 in ('||PREMPRESAS||') and';
    WSQL = WSQL || '          K315.BDCODTPLA is not null and';
    WSQL = WSQL || '          ELIK310.BDSITELIMK315 = 1 and';
    WSQL = WSQL || '          K300.BDCODTPLA = '|| PRCONTA;
    WSQL = WSQL || '    group by K300.BDCODEMPGRPECO, BDCODTPLA, BDCODTER, BDDEBITO, K310.BDDATAREF,BDSALANT, BDSALATU)';
  end
  ------------------------------------------------------------------------------
  WSQL = WSQL || ') tlan ';
  --alt:9167 - Adicionado join com a tabela de Terceiros para pegar o CNPJ do participante. Pedro
  WSQL = WSQL || 'inner join TTERCEIRO terc on (terc.bdcodter = tlan.bdcodter) ';
  IF (PRCC != '') THEN
    BEGIN
      --#alt:153018 - 04/08/2021 - Machado - Impress??o dos CENTRO de CUSTO
      IF (PRNIVELCC > 0) THEN
        BEGIN
          WSQL = WSQL || ' LEFT OUTER JOIN centros_tpcc FILHO ON (FILHO.BDCODCENTRO = TLAN.BDCODCENTRO and FILHO.BDCODTPCC = TLAN.BDCODTPCC) ';
          WSQL = WSQL || ' LEFT OUTER JOIN centros_tpcc TPCC  ON (TPCC.bdcodcentro = FILHO.BDCODCENTRO and TPCC.bdctalon = (select BDCLASSIFICACAO FROM sp_get_classificacao_nivel(FILHO.bdctalon, ' || PRNIVELCC || '))) ';
        END
      ELSE
        BEGIN
          WSQL = WSQL || 'left outer join CENTROS_TPCC TPCC on (TPCC.BDCODCENTRO = TLAN.BDCODCENTRO and TPCC.BDCODTPCC = TLAN.BDCODTPCC) ';
        END
    END
  --alt:9167 - Adicionado CNPJ do participante no group by. Pedro
  WSQL = WSQL || 'group by bdcodemp, bdcodtpla, bdcodter, bdcgcter, bddebcre, BDCODTPCC, BDNOMCTA, BDTPCCLON '; --alt:14679 - Adicionado campo BDDEBCRE. Pedro

  --alt:9167 - Alterado order, deve primeiro ordenar pelo CNPJ para trazer juntas as mesmas empresas. Pedro
  WSQL = WSQL || 'order by BDCODTPCC, bdcgcter desc, bdcodter desc ';

  FOR EXECUTE STATEMENT WSQL
          INTO :WCODEMP, :WCODTPLA, :WCODPARTICIPANTE, :WCNPJPART, :WDEBCRE, :WCCATU, :WNOMTPCC, :WTPCCLON,
               :WVALOR_N_CONC, :WSALDO_ANT_DEB, :WSALDO_DEB, :WSALDO_ANT_CRE, :WSALDO_CRE, :wdataultlancamento
  DO
  --alt:14679 - Adicionado campo BDDEBCRE. Pedro
  BEGIN
    IF ((prcc = '') or
       (prcc IS NULL) or
       (((prcc <> '') AND (NOT (prcc IS NULL))) and (PRLANCSEMCC <> 0) and ((WCCATU is null) or (WCCATU <= 0))) or
       (((prcc <> '') AND (NOT (prcc IS NULL))) and ((WCCATU is not null) and (WCCATU > 0)) and (position(','||trim(cast(WCCATU as varchar(10)))||',' IN ','||prcc||',') > 0))) THEN
      begin
        WCNPJORIGINAL = WCNPJPART;
         --alt:13329 - 10/02/2016 - Retorna o CNPJ completo porque o mesmo campo ?? utilizado na ordena????o, e aqui corta para poder agrupar. Pedro
        WCNPJPART = SUBSTRING(WCNPJPART FROM 1 FOR 10);
        BDRAIZCNPJPARTICIPANTE = '';
        IF (WCCATU IS NULL) THEN
          WCCATU = 0;
         --alt:12008 - Creio que n??o precisa buscar novamente o CNPJ j?? que ?? do mesmo participante, pode apenas copiar o do atual. Pedro
         --alt:9167 - Se for para agrupar os participantes por CNPJ e o CNPJ anterior estiver nullo (somente na primeira vez que passa aqui) ele pega o CNPJ pr??prio participante. Pedro
        IF ((PRAGRUPARPARTICIPANTEPORCNPJ = 0) AND
            (PRAGRUPARPARTICIPANTEPORCPF = 0) AND
            (WCNPJANTPART IS NULL)) THEN
          BEGIN
            WCNPJANTPART = WCNPJPART;
            WCNPJORIGINAL_ANT = WCNPJORIGINAL;
          END

        WPERMITE = 1;

        --alt:9167 - Alterado m??todo como retorna os valores. Deve variar para o caso de n??o estar agrupando pelo cnpj, ou se est??, quando o cnpj for igual ou diferente ao anterior. Pedro
        IF (WPERMITE = 1) THEN
          BEGIN
            --alt:12008 - 15/12/2015 - Aproveito para carregar junto o nome e o c??digo do pa??s do participante, para n??o precisar executar duas vezes.
            -- Uso a ordena????o bdcodter e bdrefemp porque este ??ndice ?? mais r??pido. Pedro
            SELECT FIRST 1 BDNOMETER, COALESCE(BDCODPAIS, 0), COALESCE(BDCODCID, 0)
            FROM TTERCEIRO_REF X
            WHERE BDCODTER = :WCODPARTICIPANTE
                    --#149080 - 11/07/2022 Raz??o/Di??rio/Balancete - Verificar data de emiss??o pra nome de contas de participante. Marcela
                  AND
                  BDREFEMP <= COALESCE((SELECT FIRST 1 RF2.BDREFEMP
                                        FROM TTERCEIRO_REF RF2
                                        WHERE RF2.BDCODTER = X.BDCODTER AND
                  RF2.BDREFEMP <= :prrefemp
                                        ORDER BY RF2.BDCODTER DESC, RF2.BDREFEMP DESC), (SELECT FIRST 1 RF2.BDREFEMP
                                                                                         FROM TTERCEIRO_REF RF2
                                                                                         WHERE RF2.BDCODTER = X.BDCODTER
                                                                                         ORDER BY RF2.BDCODTER, RF2.BDREFEMP))
        
              ORDER BY BDCODTER DESC, BDREFEMP DESC
              INTO :WNOME, :WCODPAIS, :WCODCID;
            --#Alt:14856. N??o estava imprimindo os participantes que n??o tinha o pa??s informado.
            IF ((PRAGRUPARPARTICIPANTEPORCNPJ = 1 OR PRAGRUPARPARTICIPANTEPORCPF = 1) AND
                (WCODPAIS = 0) AND
                (WCODCID > 0)) THEN
              SELECT BDCODPAIS
              FROM TCIDADE
              WHERE BDCODCID = :WCODCID
              INTO :WCODPAIS;
        
              WTERAUX = WCODPARTICIPANTE;
                 --Machado - 04/01/2019 - #91350 - Alterado para usar sempre o participante com menor c??digo.
              IF (PRAGRUPARPARTICIPANTEPORCNPJ = 1 AND
                WCODPAIS = 30 AND
                (CHAR_LENGTH(WCNPJORIGINAL) = 18)) THEN
                BEGIN
                  SELECT FIRST 1 BDCODTER
                  FROM TTERCEIRO
                  WHERE BDCGCTER STARTING WITH :WCNPJPART
                  ORDER BY BDCGCTER
                  INTO :WTERAUX;
                  IF (WTERAUX <> WCODPARTICIPANTE) THEN
                    SELECT FIRST 1 BDNOMETER, COALESCE(BDCODPAIS, 0), COALESCE(BDCODCID, 0), BDCODTER
                    FROM TTERCEIRO_REF
                    WHERE BDCODTER = (:WTERAUX) AND
                          BDREFEMP <= :prrefemp
                    ORDER BY BDCODTER DESC, BDREFEMP DESC
                    INTO :WNOME, :WCODPAIS, :WCODCID, :WCODPARTICIPANTE;
                END
        
              IF (PRAGRUPARPARTICIPANTEPORCPF = 1 AND
                 WCODPAIS = 30 AND
                 CHAR_LENGTH(WCNPJORIGINAL) = 14) THEN
                BEGIN
                  select first 1 T.BDCODTER
                  from TTERCEIRO T
                  join TTERCEIRO_REF TR on TR.BDCODTER = T.BDCODTER
                  where T.BDCGCTER = :WCNPJORIGINAL and
                        TR.BDCODPAIS = 30 and
                        TR.BDREFEMP <= :prrefemp
                  order by T.BDCGCTER
                  INTO :WTERAUX;
                  
                  IF (WTERAUX <> WCODPARTICIPANTE) THEN
                    SELECT FIRST 1 BDNOMETER, COALESCE(BDCODPAIS, 0), COALESCE(BDCODCID, 0), BDCODTER
                    FROM TTERCEIRO_REF
                    WHERE BDCODTER = (:WTERAUX) AND
                          BDREFEMP <= :prrefemp
                    ORDER BY BDCODTER DESC, BDREFEMP DESC
                    INTO :WNOME, :WCODPAIS, :WCODCID, :WCODPARTICIPANTE;
                END
        
                 --#Alt:14856. N??o estava imprimindo os participantes que n??o tinha o pa??s informado.
              IF ((PRAGRUPARPARTICIPANTEPORCNPJ = 1 OR PRAGRUPARPARTICIPANTEPORCPF = 1) AND
                  (WCODPAIS = 0) AND
                  (WCODCID > 0)) THEN
                SELECT BDCODPAIS
                FROM TCIDADE
                WHERE BDCODCID = :WCODCID
                INTO :WCODPAIS;
        
                 --Quando n??o est?? agrupando por CNPJ.
                 --Quando ?? participante do exterior, que ent??o n??o deve agrupar.
                 --#alt:145558 - Machado - 11/06/2021 - Agrupar participante por CPF.
              IF ((WCODPAIS <> 30) OR NOT((PRAGRUPARPARTICIPANTEPORCNPJ = 1) AND
                  (CHAR_LENGTH(WCNPJORIGINAL) = 18) OR (PRAGRUPARPARTICIPANTEPORCPF = 1) AND
                  (CHAR_LENGTH(WCNPJORIGINAL) = 14))) THEN
                BEGIN
                  --#alt:20416. Quando mandava agrupar por cnpj mas havia algum participante do exterior inserido, n??o estava mostrando o participante agrupado anterior.
                  --            E devo verificar tamb??m se o participante anterior n??o era do exterior. Ana - 19/10/2017
                  IF ((WCODPAISANT = 30) AND
                      (WPARTEXTERIORANT = 0) AND
                      ((PRAGRUPARPARTICIPANTEPORCNPJ = 1) AND
                      (CHAR_LENGTH(WCNPJORIGINAL_ANT) = 18) OR (PRAGRUPARPARTICIPANTEPORCPF = 1) AND
                      (CHAR_LENGTH(WCNPJORIGINAL_ANT) = 14))) THEN
                    BEGIN
                      IF ((PRAGRUPARPARTICIPANTEPORCNPJ = 1) AND
                          (BDRAIZCNPJPARTICIPANTE = '')) THEN
                        BDRAIZCNPJPARTICIPANTE = SUBSTRING(WCNPJANTPART FROM 1 FOR 10);
                      SUSPEND;
                    END
            
                  BDCODPARTICIPANTE = WCODPARTICIPANTE;
                  BDCGCTER = wcnpjoriginal;
                  BDCLASSIFICACAO = WCLASSIFICACAO;
                  --#alt:20416 - Precisa retornar a classifica????o original da conta. Ana - 22/09/2017
                  BDRAIZCLASSIFICACAOCTA = WCLASSIFICACAO;
                  BDNOME = WNOME;
                  BDCENTROCUSTO          = WCCATU;
                  BDNOMTPCC              = WNOMTPCC;
                  BDTPCCLON              = WTPCCLON;
                  --#Alt:19049 - Preciso retornar a ra??z do CNPJ caso seja para agrupar participante pelo CNPJ
                  IF (CHAR_LENGTH(WCNPJORIGINAL) <> 18) THEN
                    BDRAIZCNPJPARTICIPANTE = '';
                  ELSE
                    IF (PRAGRUPARPARTICIPANTEPORCNPJ = 1) THEN
                      BDRAIZCNPJPARTICIPANTE = SUBSTRING(WCNPJPART FROM 1 FOR 10);
                  --#Alt:24324 - Melhorado a forma de montar a classifica????o do participante.
                  BDCLASSIFICACAO = REVERSE(BDCLASSIFICACAO);
                  BDCLASSIFICACAO = SUBSTRING(BDCLASSIFICACAO FROM POSITION('.', BDCLASSIFICACAO) FOR STRLEN(BDCLASSIFICACAO));
                  BDCLASSIFICACAO = REVERSE(BDCLASSIFICACAO);
                  BDCLASSIFICACAO = BDCLASSIFICACAO || LPAD(WCODPARTICIPANTE, 9, '0');
            
                  IF (WGRUPOCTA IN (1, 2, 3)) THEN
                    BDSALDO_ANTERIOR = (WSALDO_ANT_CRE - WSALDO_ANT_DEB);
                  ELSE
                    BDSALDO_ANTERIOR = (WSALDO_ANT_DEB - WSALDO_ANT_CRE);
            
                  IF (WGRUPOCTA IN (1, 2, 3)) THEN
                    BDSALDO_ATUAL = (WSALDO_CRE - WSALDO_DEB);
                  ELSE
                    BDSALDO_ATUAL = (WSALDO_DEB - WSALDO_CRE);
            
                  IF (WGRUPOCTA IN (1, 2, 3)) THEN
                    BDVALOR_NAO_CONCILIADO = -WVALOR_N_CONC;
                  ELSE
                    BDVALOR_NAO_CONCILIADO = WVALOR_N_CONC;

                  BDSALDO_ANT_CRE = WSALDO_ANT_CRE;
                  BDSALDO_ANT_DEB = WSALDO_ANT_DEB;
                  BDSALDO_CRE = WSALDO_CRE - WSALDO_ANT_CRE;
                  BDSALDO_DEB = WSALDO_DEB - WSALDO_ANT_DEB;
                  BDMOVIMENTO = BDSALDO_ATUAL - BDSALDO_ANTERIOR; --alt:9515 - Adicionado campo do movimento. Pedro
                  --#alt:20416 - Tenho que verificar se o participante anterior era do exterior tamb??m, para o caso de ter mais de um participante do exterior e duplica-los. Ana - 19/10/2017
                  WPARTEXTERIORANT = 1;
                  BDDATAULTLANCAMENTO = :WDATAULTLANCAMENTO;
                  SUSPEND;
                END
              ELSE
              --Quando o CNPJ atual ?? diferente do anterior (outra empresa, ent??o deve comitar o anterior e substituir os valores pelos novos.
              IF (WCNPJANTPART <> WCNPJPART OR WCCANT <> WCCATU) THEN
                BEGIN
                  --#alt:145558 - Machado - 11/06/2021 - Agrupar participante por CPF.
                  IF ((WCODPAISANT = 30) AND
                     ((PRAGRUPARPARTICIPANTEPORCNPJ = 1) AND
                      (CHAR_LENGTH(WCNPJORIGINAL_ANT) = 18) OR (PRAGRUPARPARTICIPANTEPORCPF = 1) AND
                      (CHAR_LENGTH(WCNPJORIGINAL_ANT) = 14))) THEN --alt:12008 - 15/12/2015 - Se trocou o CNPJ e ?? participante nacional, ent??o deve retornar o valor, n??o agrupar. Pedro
                    BEGIN
                          --#Alt:19990 - Preciso retornar a ra??z do CNPJ caso seja para agrupar participante pelo CNPJ (19049)
                      IF ((PRAGRUPARPARTICIPANTEPORCNPJ = 1) AND
                          (BDRAIZCNPJPARTICIPANTE = '')) THEN
                        BDRAIZCNPJPARTICIPANTE = SUBSTRING(WCNPJANTPART FROM 1 FOR 10);
                      SUSPEND;
                    END
        
                  --#Alt:19990 - Preciso retornar a ra??z do CNPJ caso seja para agrupar participante pelo CNPJ
                  IF (CHAR_LENGTH(WCNPJORIGINAL) <> 18) THEN
                    BDRAIZCNPJPARTICIPANTE = '';
                  ELSE
                    IF (PRAGRUPARPARTICIPANTEPORCNPJ = 1) THEN
                      BDRAIZCNPJPARTICIPANTE = SUBSTRING(WCNPJPART FROM 1 FOR 10);
            
                  BDCODPARTICIPANTE = WCODPARTICIPANTE;
                  BDCGCTER = wcnpjoriginal;
                  BDCLASSIFICACAO = WCLASSIFICACAO;
                  BDCENTROCUSTO = WCCATU;
                  BDNOMTPCC     = WNOMTPCC;
                  BDTPCCLON     = WTPCCLON;
                  --#alt:20416 - Precisa retornar a classifica????o original da conta. Ana - 22/09/2017
                  BDRAIZCLASSIFICACAOCTA = WCLASSIFICACAO;
                  BDNOME = WNOME;
                  --#Alt:24324 - Melhorado a forma de montar a classifica????o do participante.
                  BDCLASSIFICACAO = REVERSE(BDCLASSIFICACAO);
                  BDCLASSIFICACAO = SUBSTRING(BDCLASSIFICACAO FROM POSITION('.', BDCLASSIFICACAO) FOR STRLEN(BDCLASSIFICACAO));
                  BDCLASSIFICACAO = REVERSE(BDCLASSIFICACAO);
                  BDCLASSIFICACAO = BDCLASSIFICACAO || LPAD(WCODPARTICIPANTE, 9, '0');
            
                  IF (WGRUPOCTA IN (1, 2, 3)) THEN
                    BDSALDO_ANTERIOR = (WSALDO_ANT_CRE - WSALDO_ANT_DEB);
                  ELSE
                    BDSALDO_ANTERIOR = (WSALDO_ANT_DEB - WSALDO_ANT_CRE);
            
                  IF (WGRUPOCTA IN (1, 2, 3)) THEN
                    BDSALDO_ATUAL = (WSALDO_CRE - WSALDO_DEB);
                  ELSE
                    BDSALDO_ATUAL = (WSALDO_DEB - WSALDO_CRE);
            
                  IF (WGRUPOCTA IN (1, 2, 3)) THEN
                    BDVALOR_NAO_CONCILIADO = -WVALOR_N_CONC;
                  ELSE
                    BDVALOR_NAO_CONCILIADO = WVALOR_N_CONC;
            
                  BDSALDO_ANT_CRE = WSALDO_ANT_CRE;
                  BDSALDO_ANT_DEB = WSALDO_ANT_DEB;
                  BDSALDO_CRE = WSALDO_CRE - WSALDO_ANT_CRE;
                  BDSALDO_DEB = WSALDO_DEB - WSALDO_ANT_DEB;
                  BDMOVIMENTO = BDSALDO_ATUAL - BDSALDO_ANTERIOR; --alt:9515 - Adicionado campo do movimento. Pedro
                  --#alt:20416 - Tenho que verificar se o participante anterior era do exterior tamb??m, para o caso de ter mais de um participante do exterior e duplica-los. Ana - 19/10/2017
                  WPARTEXTERIORANT = 0;
                  BDDATAULTLANCAMENTO = :WDATAULTLANCAMENTO;

                END
            --O CNPJ atual ?? igual ao anterior (mesma empresa, ent??o deve agrupar).
        ELSE
          BEGIN
             BDCODPARTICIPANTE = WCODPARTICIPANTE;
             BDCGCTER = wcnpjoriginal;
             BDCLASSIFICACAO = WCLASSIFICACAO;
             BDCENTROCUSTO = WCCATU;
             BDNOMTPCC     = WNOMTPCC;
             BDTPCCLON     = WTPCCLON;
             --#alt:20416 - Precisa retornar a classifica????o original da conta. Ana - 22/09/2017
             BDRAIZCLASSIFICACAOCTA = WCLASSIFICACAO;
             BDNOME = WNOME;
             --#Alt:19049 - Preciso retornar a ra??z do CNPJ caso seja para agrupar participante pelo CNPJ
             IF (PRAGRUPARPARTICIPANTEPORCNPJ = 1) THEN
               BDRAIZCNPJPARTICIPANTE = SUBSTRING(WCNPJPART FROM 1 FOR 10);
             --#Alt:24324 - Melhorado a forma de montar a classifica????o do participante.
             BDCLASSIFICACAO = REVERSE(BDCLASSIFICACAO);
             BDCLASSIFICACAO = SUBSTRING(BDCLASSIFICACAO FROM POSITION('.', BDCLASSIFICACAO) FOR STRLEN(BDCLASSIFICACAO));
             BDCLASSIFICACAO = REVERSE(BDCLASSIFICACAO);
             BDCLASSIFICACAO = BDCLASSIFICACAO || LPAD(WCODPARTICIPANTE, 9, '0');
             IF (WGRUPOCTA IN (1, 2, 3)) THEN
               BEGIN
                 BDSALDO_ANTERIOR = COALESCE(BDSALDO_ANTERIOR, 0) + (WSALDO_ANT_CRE - WSALDO_ANT_DEB);
                 BDSALDO_ATUAL = COALESCE(BDSALDO_ATUAL, 0) + (WSALDO_CRE - WSALDO_DEB);
                 BDVALOR_NAO_CONCILIADO = COALESCE(BDVALOR_NAO_CONCILIADO, 0) - WVALOR_N_CONC;
               END
             ELSE
               BEGIN
                 BDSALDO_ANTERIOR = COALESCE(BDSALDO_ANTERIOR, 0) + (WSALDO_ANT_DEB - WSALDO_ANT_CRE);
                 BDSALDO_ATUAL = COALESCE(BDSALDO_ATUAL, 0) + (WSALDO_DEB - WSALDO_CRE);
                 BDVALOR_NAO_CONCILIADO = COALESCE(BDVALOR_NAO_CONCILIADO, 0) + WVALOR_N_CONC;
               END
             BDSALDO_ANT_CRE = COALESCE(BDSALDO_ANT_CRE, 0) + WSALDO_ANT_CRE;
             BDSALDO_ANT_DEB = COALESCE(BDSALDO_ANT_DEB, 0) + WSALDO_ANT_DEB;
             BDSALDO_CRE = COALESCE(BDSALDO_CRE, 0) + (WSALDO_CRE - WSALDO_ANT_CRE);
             BDSALDO_DEB = COALESCE(BDSALDO_DEB, 0) + (WSALDO_DEB - WSALDO_ANT_DEB);
             BDMOVIMENTO = BDSALDO_ATUAL - BDSALDO_ANTERIOR; --alt:9515 - Adicionado campo do movimento. Pedro
                 --#alt:20416 - Tenho que verificar se o participante anterior era do exterior tamb??m, para o caso de ter mais de um participante do exterior e duplica-los. Ana - 19/10/2017
             WPARTEXTERIORANT = 0;
           END
         WCODPAISANT = WCODPAIS;
         WCNPJANTPART = WCNPJPART;
         WCNPJORIGINAL_ANT = WCNPJORIGINAL;
         WCCANT       = WCCATU;
      END
    END
  END

  --alt:9167 - Garante que, se ainda tiver algum valor, deve commitar o ??ltimo lan??amento, sem isso o ??ltimo nunca seria commitado. Pedro
  IF ((((PRAGRUPARPARTICIPANTEPORCNPJ = 1) AND
      (WCODPAISANT = 30) AND
      (CHAR_LENGTH(WCNPJORIGINAL_ANT) = 18)) OR ((PRAGRUPARPARTICIPANTEPORCPF = 1) AND
      (WCODPAISANT = 30) AND
      (CHAR_LENGTH(WCNPJORIGINAL_ANT) = 14))) AND --alt:12008 - 11/01/2015 - S?? deve retornar o ??ltimo participante caso ele seja nacional. Pedro
      ((COALESCE(BDSALDO_ANT_CRE, 0) <> 0) OR (COALESCE(BDSALDO_ANT_DEB, 0) <> 0) OR (COALESCE(BDSALDO_CRE, 0) <> 0) OR (COALESCE(BDSALDO_DEB, 0) <> 0))) THEN
    SUSPEND;

  if (PRTODOSPART <> '') then
    begin
      WSQL = 'select ' || PRCODEMP || ' as BDCODEMP, ' || PRCODPLAPADRAO || ' as BDCODTPLA, TERC.BDCODTER, TERC.BDCGCTER, 0 as BDDEBCRE, null as BDCODTPCC, null as BDNOMCTA, ';
      WSQL = WSQL || ' null as BDTPCCLON, 0 as BDVALCONC , 0 as BDDEBANT, 0 as BDDEBATU , 0 as BDCREANT, 0 as BDCREATU ';
      WSQL = WSQL || ' FROM TTERCEIRO TERC where (terc.bdcodter in (' || PRTODOSPART || ')) ';
      WSQL = WSQL || ' group by BDCODEMP, BDCODTPLA, BDCODTER, BDCGCTER, BDDEBCRE, BDCODTPCC, BDNOMCTA, BDTPCCLON';
    
      for execute statement WSQL
           into :WCODEMP, :WCODTPLA, :WCODPARTICIPANTE, :WCNPJPART, :WDEBCRE, :WCCATU, :WNOMTPCC, :WTPCCLON,
                :WVALOR_N_CONC, :WSALDO_ANT_DEB, :WSALDO_DEB, :WSALDO_ANT_CRE, :WSALDO_CRE, :wdataultlancamento
      do
        begin
          if (WPERMITE = 1) then
            begin
              --alt:12008 - 15/12/2015 - Aproveito para carregar junto o nome e o c??digo do pa??s do participante, para n??o precisar executar duas vezes.
              -- Uso a ordena????o bdcodter e bdrefemp porque este ??ndice ?? mais r??pido. Pedro
              select first 1 BDNOMETER, coalesce(BDCODPAIS, 0), coalesce(BDCODCID, 0)
              from TTERCEIRO_REF X
              where BDCODTER = :WCODPARTICIPANTE
                  --#149080 - 11/07/2022 Raz??o/Di??rio/Balancete - Verificar data de emiss??o pra nome de contas de participante. Marcela
                    and
                    BDREFEMP <= coalesce((select first 1 RF2.BDREFEMP
                                          from TTERCEIRO_REF RF2
                                          where RF2.BDCODTER = X.BDCODTER and
                                                RF2.BDREFEMP <= :PRREFEMP
                                          order by RF2.BDCODTER desc, RF2.BDREFEMP desc), (select first 1 RF2.BDREFEMP
                                                                                           from TTERCEIRO_REF RF2
                                                                                           where RF2.BDCODTER = X.BDCODTER
                                                                                           order by RF2.BDCODTER, RF2.BDREFEMP))
    
              order by BDCODTER desc, BDREFEMP desc
              into :WNOME, :WCODPAIS, :WCODCID;
    
              --#Alt:14856. N??o estava imprimindo os participantes que n??o tinha o pa??s informado.
              if ((PRAGRUPARPARTICIPANTEPORCNPJ = 1 or PRAGRUPARPARTICIPANTEPORCPF = 1) and
                  (WCODPAIS = 0) and
                  (WCODCID > 0)) then
                select BDCODPAIS
                from TCIDADE
                where BDCODCID = :WCODCID
                into :WCODPAIS;
    
              WTERAUX = WCODPARTICIPANTE;
              --Machado - 04/01/2019 - #91350 - Alterado para usar sempre o participante com menor c??digo.
              if (PRAGRUPARPARTICIPANTEPORCNPJ = 1 and
                 WCODPAIS = 30 and
                 (char_length(WCNPJORIGINAL) = 18)) then
                begin
                  select first 1 BDCODTER
                  from TTERCEIRO
                  where BDCGCTER starting with :WCNPJPART
                  order by BDCGCTER
                  into :WTERAUX;
                  if (WTERAUX <> WCODPARTICIPANTE) then
                    select first 1 BDNOMETER, coalesce(BDCODPAIS, 0), coalesce(BDCODCID, 0), BDCODTER
                    from TTERCEIRO_REF
                    where BDCODTER = (:WTERAUX) and
                          BDREFEMP <= :PRREFEMP
                    order by BDCODTER desc, BDREFEMP desc
                    into :WNOME, :WCODPAIS, :WCODCID, :WCODPARTICIPANTE;
                end
    
              if (PRAGRUPARPARTICIPANTEPORCPF = 1 and
                  WCODPAIS = 30 and
                  char_length(WCNPJORIGINAL) = 14) then
                begin
                  select first 1 BDCODTER
                  from TTERCEIRO
                  where BDCGCTER = :WCNPJORIGINAL
                  order by BDCGCTER
                  into :WTERAUX;
                  if (WTERAUX <> WCODPARTICIPANTE) then
                    select first 1 BDNOMETER, coalesce(BDCODPAIS, 0), coalesce(BDCODCID, 0), BDCODTER
                    from TTERCEIRO_REF
                    where BDCODTER = (:WTERAUX) and
                          BDREFEMP <= :PRREFEMP
                    order by BDCODTER desc, BDREFEMP desc
                    into :WNOME, :WCODPAIS, :WCODCID, :WCODPARTICIPANTE;
                end
    
              --#Alt:14856. N??o estava imprimindo os participantes que n??o tinha o pa??s informado.
              if ((PRAGRUPARPARTICIPANTEPORCNPJ = 1 or PRAGRUPARPARTICIPANTEPORCPF = 1) and
                  (WCODPAIS = 0) and
                  (WCODCID > 0)) then
                select BDCODPAIS
                from TCIDADE
                where BDCODCID = :WCODCID
                into :WCODPAIS;
    
              --Quando n??o est?? agrupando por CNPJ.
              --Quando ?? participante do exterior, que ent??o n??o deve agrupar.
              --#alt:145558 - Machado - 11/06/2021 - Agrupar participante por CPF.
              if ((WCODPAIS <> 30) or not((PRAGRUPARPARTICIPANTEPORCNPJ = 1) and
                  (char_length(WCNPJORIGINAL) = 18) or (PRAGRUPARPARTICIPANTEPORCPF = 1) and
                  (char_length(WCNPJORIGINAL) = 14))) then
                begin
                  --#alt:20416. Quando mandava agrupar por cnpj mas havia algum participante do exterior inserido, n??o estava mostrando o participante agrupado anterior.
                  --            E devo verificar tamb??m se o participante anterior n??o era do exterior. Ana - 19/10/2017
                  if ((WCODPAISANT = 30) and
                      (WPARTEXTERIORANT = 0) and
                      ((PRAGRUPARPARTICIPANTEPORCNPJ = 1) and
                      (char_length(WCNPJORIGINAL_ANT) = 18) or (PRAGRUPARPARTICIPANTEPORCPF = 1) and
                      (char_length(WCNPJORIGINAL_ANT) = 14))) then
                    begin
                      if ((PRAGRUPARPARTICIPANTEPORCNPJ = 1) and
                          (BDRAIZCNPJPARTICIPANTE = '')) then
                        BDRAIZCNPJPARTICIPANTE = substring(WCNPJANTPART from 1 for 10);
                      suspend;
                    end
        
                  BDCODPARTICIPANTE = WCODPARTICIPANTE;
                  BDCGCTER = wcnpjoriginal;
                  BDCLASSIFICACAO = WCLASSIFICACAO;
                  --#alt:20416 - Precisa retornar a classifica????o original da conta. Ana - 22/09/2017
                  BDRAIZCLASSIFICACAOCTA = WCLASSIFICACAO;
                  BDNOME = WNOME;
                  BDCENTROCUSTO = WCCATU;
                  BDNOMTPCC = WNOMTPCC;
                  BDTPCCLON = WTPCCLON;
                  --#Alt:19049 - Preciso retornar a ra??z do CNPJ caso seja para agrupar participante pelo CNPJ
                  if (char_length(WCNPJORIGINAL) <> 18) then
                    BDRAIZCNPJPARTICIPANTE = '';
                  else
                  if (PRAGRUPARPARTICIPANTEPORCNPJ = 1) then
                    BDRAIZCNPJPARTICIPANTE = substring(WCNPJPART from 1 for 10);
                  --#Alt:24324 - Melhorado a forma de montar a classifica????o do participante.
                  BDCLASSIFICACAO = reverse(BDCLASSIFICACAO);
                  BDCLASSIFICACAO = substring(BDCLASSIFICACAO from position('.', BDCLASSIFICACAO) for STRLEN(BDCLASSIFICACAO));
                  BDCLASSIFICACAO = reverse(BDCLASSIFICACAO);
                  BDCLASSIFICACAO = BDCLASSIFICACAO || lpad(WCODPARTICIPANTE, 9, '0');
        
                  if (WGRUPOCTA in (1, 2, 3)) then
                    BDSALDO_ANTERIOR = (WSALDO_ANT_CRE - WSALDO_ANT_DEB);
                  else
                    BDSALDO_ANTERIOR = (WSALDO_ANT_DEB - WSALDO_ANT_CRE);
        
                  if (WGRUPOCTA in (1, 2, 3)) then
                    BDSALDO_ATUAL = (WSALDO_CRE - WSALDO_DEB);
                  else
                    BDSALDO_ATUAL = (WSALDO_DEB - WSALDO_CRE);
        
                  if (WGRUPOCTA in (1, 2, 3)) then
                    BDVALOR_NAO_CONCILIADO = -WVALOR_N_CONC;
                  else
                    BDVALOR_NAO_CONCILIADO = WVALOR_N_CONC;
        
                  BDSALDO_ANT_CRE = WSALDO_ANT_CRE;
                  BDSALDO_ANT_DEB = WSALDO_ANT_DEB;
                  BDSALDO_CRE = WSALDO_CRE - WSALDO_ANT_CRE;
                  BDSALDO_DEB = WSALDO_DEB - WSALDO_ANT_DEB;
                  BDMOVIMENTO = BDSALDO_ATUAL - BDSALDO_ANTERIOR; --alt:9515 - Adicionado campo do movimento. Pedro
                  --#alt:20416 - Tenho que verificar se o participante anterior era do exterior tamb??m, para o caso de ter mais de um participante do exterior e duplica-los. Ana - 19/10/2017
                  WPARTEXTERIORANT = 1;
        
                  suspend;
                end
              else
              --Quando o CNPJ atual ?? diferente do anterior (outra empresa, ent??o deve comitar o anterior e substituir os valores pelos novos.
              if (WCNPJANTPART <> WCNPJPART or WCCANT <> WCCATU) then
                begin
                  --#alt:145558 - Machado - 11/06/2021 - Agrupar participante por CPF.
                  if ((WCODPAISANT = 30) and
                      ((PRAGRUPARPARTICIPANTEPORCNPJ = 1) and
                       (char_length(WCNPJORIGINAL_ANT) = 18) or (PRAGRUPARPARTICIPANTEPORCPF = 1) and
                       (char_length(WCNPJORIGINAL_ANT) = 14))) then --alt:12008 - 15/12/2015 - Se trocou o CNPJ e ?? participante nacional, ent??o deve retornar o valor, n??o agrupar. Pedro
                    begin
                      --#Alt:19990 - Preciso retornar a ra??z do CNPJ caso seja para agrupar participante pelo CNPJ (19049)
                      if ((PRAGRUPARPARTICIPANTEPORCNPJ = 1) and
                          (BDRAIZCNPJPARTICIPANTE = '')) then
                        BDRAIZCNPJPARTICIPANTE = substring(WCNPJANTPART from 1 for 10);
                      suspend;
                    end
            
                  --#Alt:19990 - Preciso retornar a ra??z do CNPJ caso seja para agrupar participante pelo CNPJ
                  if (char_length(WCNPJORIGINAL) <> 18) then
                    BDRAIZCNPJPARTICIPANTE = '';
                  else
                  if (PRAGRUPARPARTICIPANTEPORCNPJ = 1) then
                    BDRAIZCNPJPARTICIPANTE = substring(WCNPJPART from 1 for 10);
                  
                  BDCODPARTICIPANTE = WCODPARTICIPANTE;
                  BDCGCTER = wcnpjoriginal;
                  BDCLASSIFICACAO = WCLASSIFICACAO;
                  BDCENTROCUSTO = WCCATU;
                  BDNOMTPCC = WNOMTPCC;
                  BDTPCCLON = WTPCCLON;
                  --#alt:20416 - Precisa retornar a classifica????o original da conta. Ana - 22/09/2017
                  BDRAIZCLASSIFICACAOCTA = WCLASSIFICACAO;
                  BDNOME = WNOME;
                  --#Alt:24324 - Melhorado a forma de montar a classifica????o do participante.
                  BDCLASSIFICACAO = reverse(BDCLASSIFICACAO);
                  BDCLASSIFICACAO = substring(BDCLASSIFICACAO from position('.', BDCLASSIFICACAO) for STRLEN(BDCLASSIFICACAO));
                  BDCLASSIFICACAO = reverse(BDCLASSIFICACAO);
                  BDCLASSIFICACAO = BDCLASSIFICACAO || lpad(WCODPARTICIPANTE, 9, '0');
            
                  if (WGRUPOCTA in (1, 2, 3)) then
                    BDSALDO_ANTERIOR = (WSALDO_ANT_CRE - WSALDO_ANT_DEB);
                  else
                    BDSALDO_ANTERIOR = (WSALDO_ANT_DEB - WSALDO_ANT_CRE);
            
                  if (WGRUPOCTA in (1, 2, 3)) then
                    BDSALDO_ATUAL = (WSALDO_CRE - WSALDO_DEB);
                  else
                    BDSALDO_ATUAL = (WSALDO_DEB - WSALDO_CRE);
            
                  if (WGRUPOCTA in (1, 2, 3)) then
                    BDVALOR_NAO_CONCILIADO = -WVALOR_N_CONC;
                  else
                    BDVALOR_NAO_CONCILIADO = WVALOR_N_CONC;
            
                  BDSALDO_ANT_CRE = WSALDO_ANT_CRE;
                  BDSALDO_ANT_DEB = WSALDO_ANT_DEB;
                  BDSALDO_CRE = WSALDO_CRE - WSALDO_ANT_CRE;
                  BDSALDO_DEB = WSALDO_DEB - WSALDO_ANT_DEB;
                  BDMOVIMENTO = BDSALDO_ATUAL - BDSALDO_ANTERIOR; --alt:9515 - Adicionado campo do movimento. Pedro
                  --#alt:20416 - Tenho que verificar se o participante anterior era do exterior tamb??m, para o caso de ter mais de um participante do exterior e duplica-los. Ana - 19/10/2017
                  WPARTEXTERIORANT = 0;
                  BDDATAULTLANCAMENTO = :WDATAULTLANCAMENTO;
                end
              --O CNPJ atual ?? igual ao anterior (mesma empresa, ent??o deve agrupar).
              else
                begin
                  BDCODPARTICIPANTE = WCODPARTICIPANTE;
                  BDCGCTER = wcnpjoriginal;
                  BDCLASSIFICACAO = WCLASSIFICACAO;
                  BDCENTROCUSTO = WCCATU;
                  BDNOMTPCC = WNOMTPCC;
                  BDTPCCLON = WTPCCLON;
                  --#alt:20416 - Precisa retornar a classifica????o original da conta. Ana - 22/09/2017
                  BDRAIZCLASSIFICACAOCTA = WCLASSIFICACAO;
                  BDNOME = WNOME;
                  --#Alt:19049 - Preciso retornar a ra??z do CNPJ caso seja para agrupar participante pelo CNPJ
                  if (PRAGRUPARPARTICIPANTEPORCNPJ = 1) then
                    BDRAIZCNPJPARTICIPANTE = substring(WCNPJPART from 1 for 10);
                  --#Alt:24324 - Melhorado a forma de montar a classifica????o do participante.
                  BDCLASSIFICACAO = reverse(BDCLASSIFICACAO);
                  BDCLASSIFICACAO = substring(BDCLASSIFICACAO from position('.', BDCLASSIFICACAO) for STRLEN(BDCLASSIFICACAO));
                  BDCLASSIFICACAO = reverse(BDCLASSIFICACAO);
                  BDCLASSIFICACAO = BDCLASSIFICACAO || lpad(WCODPARTICIPANTE, 9, '0');
        
                  if (WGRUPOCTA in (1, 2, 3)) then
                    begin
                      BDSALDO_ANTERIOR = coalesce(BDSALDO_ANTERIOR, 0) + (WSALDO_ANT_CRE - WSALDO_ANT_DEB);
                      BDSALDO_ATUAL = coalesce(BDSALDO_ATUAL, 0) + (WSALDO_CRE - WSALDO_DEB);
                      BDVALOR_NAO_CONCILIADO = coalesce(BDVALOR_NAO_CONCILIADO, 0) - WVALOR_N_CONC;
                    end
                  else
                    begin
                      BDSALDO_ANTERIOR = coalesce(BDSALDO_ANTERIOR, 0) + (WSALDO_ANT_DEB - WSALDO_ANT_CRE);
                      BDSALDO_ATUAL = coalesce(BDSALDO_ATUAL, 0) + (WSALDO_DEB - WSALDO_CRE);
                      BDVALOR_NAO_CONCILIADO = coalesce(BDVALOR_NAO_CONCILIADO, 0) + WVALOR_N_CONC;
                    end
        
                  BDSALDO_ANT_CRE = coalesce(BDSALDO_ANT_CRE, 0) + WSALDO_ANT_CRE;
                  BDSALDO_ANT_DEB = coalesce(BDSALDO_ANT_DEB, 0) + WSALDO_ANT_DEB;
                  BDSALDO_CRE = coalesce(BDSALDO_CRE, 0) + (WSALDO_CRE - WSALDO_ANT_CRE);
                  BDSALDO_DEB = coalesce(BDSALDO_DEB, 0) + (WSALDO_DEB - WSALDO_ANT_DEB);
                  BDMOVIMENTO = BDSALDO_ATUAL - BDSALDO_ANTERIOR; --alt:9515 - Adicionado campo do movimento. Pedro
                  --#alt:20416 - Tenho que verificar se o participante anterior era do exterior tamb??m, para o caso de ter mais de um participante do exterior e duplica-los. Ana - 19/10/2017
                  WPARTEXTERIORANT = 0;
                  BDDATAULTLANCAMENTO = :WDATAULTLANCAMENTO;
                end
            end
        end
    end

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(wrefant);
END
^

/* Restore proc. body: VSUC_SP_RETORNA_TOTAIS_LANC */
ALTER PROCEDURE VSUC_SP_RETORNA_TOTAIS_LANC(PRCODEMP VARCHAR(2048),
PRDATAINI DATE,
PRDATAFIM DATE,
PRWHERE VARCHAR(2048),
PRREF INTEGER,
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER,
PRSTATUSTRANSACAO INTEGER = 0,
PRLANCSEMTRANS INTEGER = 1,
PRDATAS VARCHAR(1024) = '')
 RETURNS(BDCODEMP INTEGER,
BDNOMEMP DM_BDNOMEMP,
BDCNPJEMP VARCHAR(20),
BDQTDLINHA INTEGER,
BDVALLINHA NUMERIC(15,2),
BDQTDDEB INTEGER,
BDVALDEB NUMERIC(15,2),
BDQTDCRE INTEGER,
BDVALCRE NUMERIC(15,2),
BDQTDGERAL INTEGER,
BDVALGERAL NUMERIC(15,2),
BDDIF NUMERIC(15,2),
BDCODEMPFILIAL INTEGER)
 AS
DECLARE VARIABLE WSQL VARCHAR(10480);
DECLARE VARIABLE WSQLLANC VARCHAR(10480);
DECLARE VARIABLE WDATINI VARCHAR(10);
DECLARE VARIABLE WDATFIN VARCHAR(10);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WTIPOLANCFILIAL INTEGER;
DECLARE VARIABLE WVLR NUMERIC(15,2);
DECLARE VARIABLE WQTD INTEGER;
DECLARE VARIABLE WPERMITE INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WEMPPRINC INTEGER;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prref, NULL, NULL);

  wdatini = SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdataini AS VARCHAR(10)) FROM 1 FOR 4);
  wdatfin = SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 6 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 9 FOR 2)||'/'||
            SUBSTRING(CAST(prdatafim AS VARCHAR(10)) FROM 1 FOR 4);

  --Retorna a empresa principal
  SELECT Pos FROM pos(',', :prcodemp) INTO :wpos;
  IF (wpos = 0) THEN
    wempprinc = prcodemp;
  ELSE
    wempprinc = SUBSTRING(prcodemp FROM 1 FOR (wpos - 1));

  wsql = 'select temp.bdcodmatriz, temp.bdcodemp, temp.bdnomemp, temp.bdcnpjemp, ';
  --#alt:5837.
  /*wsql = wsql||'       count(lan.bdchave) totlanclinha , count(lan.bddebito) linhadeb, ';
  wsql = wsql||'       count(lan.bdcredito) linhacre , sum(lan.bdvalor) totalvalor, ';
  wsql = wsql||'       count(lan.bddebito) + count(lan.bdcredito) bdqtdgeral '; */
  wsql = wsql||'       count(lan.bdchave) totlanclinha , sum(lan.bdvalor) totalvalor ';
  wsql = wsql||'       from vsuc_empresas_tlan LAN ';
  wsql = wsql||'inner join vw_empresas_ref_atual temp on (temp.bdcodemp = lan.bdcodemp) ';
  --#alt:5837.
  --wsql = wsql||'where lan.bdcodemp in ('||prcodemp||') ';
  wsql = wsql||'where (lan.bdcodemp in ('||prcodemp||')) ';
  --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (lan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  --#alt:16410 - Adicionei o controle pelo filtro das datas com diferença, sem ela estava levando os valores errados com esta opção. Ana - 05/05/2017
  IF ((prdatas IS NOT NULL) AND (prdatas <> '')) THEN
    wsql = wsql||'and (lan.BDDATA in ('||TRIM(prdatas)||')) ';
  ELSE
  IF (prdataini IS NOT NULL AND prdatafim IS NOT NULL) THEN
     wsql = wsql||' and (lan.BDDATA between '''||wdatini||''' and '''||wdatfin||''') ';

  --#alt:16410 - Adicionado filtro por status da transação e a opção de mostrar os lançamentos sem transação que não tinha e deixava os valores inválidos. Ana - 05/05/2017
  IF (prstatustransacao = 1) THEN
    wsql = wsql||'and (upper(LAN.BDTRANFECHADA) = ''FALSE'') ';
  ELSE IF (prstatustransacao = 2) THEN
    wsql = wsql||'and (upper(LAN.BDTRANFECHADA) = ''TRUE'') ';

  IF (prlancsemtrans = 0) THEN
       wsql = wsql||'and (lan.bdtransacao is not null) ';
  --#alt:16410. fim

  IF ((prwhere IS NOT NULL) AND (prwhere <> '')) THEN
     wsql = wsql||' and  '||prwhere;
  wsql = wsql||'group by temp.bdcodmatriz, temp.bdcodemp, temp.bdnomemp, temp.bdcnpjemp ';
  wsql = wsql||'order by temp.bdcodmatriz, temp.bdcodemp ';
  -- executa o sql das empresas
  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodempfilial, :bdnomemp, :bdcnpjemp, :BDQTDLINHA, /*:BDQTDDEB, :BDQTDCRE, */:bdvallinha/*, :bdqtdgeral*/ DO
      BEGIN
        bdvaldeb   = 0;
        bdvalcre   = 0;
        bdqtddeb   = 0;
        bdqtdcre   = 0;
        bdqtdgeral = 0;

        IF (bdcodemp IS NULL) THEN
           bdcodemp = bdcodempfilial;

        IF (bdqtdlinha IS NULL) THEN
           bdqtdlinha = 0;
        IF (bdvallinha IS NULL) THEN
           bdvallinha = 0;
        --#alt:5837.
        SELECT Pos FROM pos(','||:bdcodempfilial||',', ','||:prcodemp||',') INTO :wpos;
        IF (wpos > 0) THEN
          BEGIN
            -- Débito ______________________________________________________________
            --#alt:5837.
            /*wSqllanc = 'select sum(bdvalor) from vsuc_empresas_tlan LAN where bdcodemp = '||bdcodempfilial||' and bddebito is not null ';
            if ((prdataini is not null) and (prdatafim is not null)) then
              wsqllanc = wsqllanc||' and (BDDATA between '''||wdatini||''' and '''||wdatfin||''') ';
            if ((prwhere is not null) and (prwhere <> '')) then
              wsqllanc = wsqllanc||' and  '||prwhere;
            execute statement wsqllanc into :bdvaldeb;*/
            wSqllanc = 'Select bdcodemp,sum(bdvalor),count(bdchave) from vsuc_empresas_tlan LAN ';
            wsqllanc = wsqllanc||'where (bdcodemp = '||bdcodempfilial||') and bddebito is not null ';
            --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
            IF (prcontabilizacao <> 99) THEN
              wsqllanc = wsqllanc||'and (bdcontabilizacao in (0,'||prcontabilizacao||')) ';
            --#alt:16410 - Adicionei o controle pelo filtro das datas com diferença, sem ela estava levando os valores errados com esta opção. Ana - 05/05/2017
            IF ((prdatas IS NOT NULL) AND (prdatas <> ''))THEN
              wsqllanc = wsqllanc||'and (lan.BDDATA in ('||TRIM(prdatas)||')) ';
            ELSE
            IF ((prdataini IS NOT NULL) AND (prdatafim IS NOT NULL)) THEN
              wsqllanc = wsqllanc||' and (BDDATA between '''||wdatini||''' and '''||wdatfin||''') ';
            --#alt:16410 - Adicionado filtro por status da transação e a opção de mostrar os lançamentos sem transação que não tinha e deixava os valores inválidos. Ana - 05/05/2017
            IF (prstatustransacao = 1) THEN
              wsqllanc = wsqllanc||'and (upper(LAN.BDTRANFECHADA) = ''FALSE'') ';
            ELSE IF (prstatustransacao = 2) THEN
              wsqllanc = wsqllanc||'and (upper(LAN.BDTRANFECHADA) = ''TRUE'')';

            IF (prlancsemtrans = 0) THEN
              wsqllanc = wsqllanc||'and (lan.bdtransacao is not null) ';
            --#alt:16410. fim
            IF ((prwhere IS NOT NULL) AND (prwhere <> '')) THEN
              wsqllanc = wsqllanc||' and  '||prwhere;
            wsqllanc = wsqllanc||' Group by bdcodemp';
            FOR EXECUTE STATEMENT wsqllanc INTO :wcodemp, :wvlr,:wqtd DO
              BEGIN
                IF (wvlr IS NULL) THEN
                  wvlr = 0;
                IF (wqtd IS NULL) THEN
                  wqtd = 0;
                --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(1,:bdcodempfilial,:wcodemp,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
                --IF (wpermite = 1) THEN
                  --BEGIN
                    bdvaldeb = bdvaldeb + wvlr;
                    bdqtddeb = bdqtddeb + wqtd;
                  --END
                  END

            IF (bdqtddeb IS NULL) THEN
              bdqtddeb = 0;
            IF (bdvaldeb IS NULL) THEN
              bdvaldeb = 0;

            -- Crédito _____________________________________________________________
            --#alt:5837.
            /*wSqllanc = 'select sum(bdvalor) from vsuc_empresas_tlan LAN where bdcodemp = '||bdcodempfilial||' and bdcredito is not null ';
            if (prdataini is not null and prdatafim is not null) then
              wsqllanc = wsqllanc||' and (BDDATA between '''||wdatini||''' and '''||wdatfin||''') ';
            if ((prwhere is not null) and (prwhere <> '')) then
              wsqllanc = wsqllanc||' and  '||prwhere;
            execute statement wsqllanc into :bdvalcre;*/
            wSqllanc = 'Select bdcodemp,sum(bdvalor),count(bdchave) from vsuc_empresas_tlan LAN ';
            wsqllanc = wsqllanc||'where (bdcodemp = '||bdcodempfilial||') and bdcredito is not null ';
            --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
            IF (prcontabilizacao <> 99) THEN
              wsqllanc = wsqllanc||'and (bdcontabilizacao in (0,'||prcontabilizacao||')) ';
            --#alt:16410 - Adicionei o controle pelo filtro das datas com diferença, sem ela estava levando os valores errados com esta opção. Ana - 05/05/2017
            IF ((prdatas IS NOT NULL) AND (prdatas <> ''))THEN
              wsqllanc = wsqllanc||'and (lan.BDDATA in ('||TRIM(prdatas)||')) ';
            ELSE
            IF ((prdataini IS NOT NULL) AND (prdatafim IS NOT NULL)) THEN
              wsqllanc = wsqllanc||' and (BDDATA between '''||wdatini||''' and '''||wdatfin||''') ';
            --#alt:16410 - Adicionado filtro por status da transação e a opção de mostrar os lançamentos sem transação que não tinha e deixava os valores inválidos. Ana - 05/05/2017
            IF (prstatustransacao = 1) THEN
              wsqllanc = wsqllanc||'and (upper(LAN.BDTRANFECHADA) = ''FALSE'') ';
            ELSE IF (prstatustransacao = 2) THEN
              wsqllanc = wsqllanc||'and (upper(LAN.BDTRANFECHADA) = ''TRUE'')';

            IF (prlancsemtrans = 0) THEN
              wsqllanc = wsqllanc||'and (lan.bdtransacao is not null) ';
            --#alt:16410. fim
            IF ((prwhere IS NOT NULL) AND (prwhere <> '')) THEN
              wsqllanc = wsqllanc||' and  '||prwhere;
            wsqllanc = wsqllanc||' Group by bdcodemp';
            FOR EXECUTE STATEMENT wsqllanc INTO :wcodemp, :wvlr,:wqtd DO
              BEGIN
                IF (wvlr IS NULL) THEN
                  wvlr = 0;
                IF (wqtd IS NULL) THEN
                  wqtd = 0;
                --SELECT bdpermite FROM vsuc_sp_permitecalcsaldolancmf(2,:bdcodempfilial,:wcodemp,:prmatrizfilialconsolidado,:prcodemp) INTO :wpermite;
                --IF (wpermite = 1) THEN
                  --BEGIN
                    bdvalcre = bdvalcre + wvlr;
                    bdqtdcre = bdqtdcre + wqtd;
                  --END
                  END

            IF (bdqtdcre IS NULL) THEN
              bdqtdcre = 0;
            IF (bdvalcre IS NULL) THEN
              bdvalcre = 0;

            -- totais ______________________________________________________________
            bdvalgeral = bdvaldeb + bdvalcre;
            bdqtdgeral = bdqtddeb + bdqtdcre;
            bddif = bdvalcre - bdvaldeb;
          END

        IF (bdqtdgeral IS NULL) THEN
           bdqtdgeral = 0;
        IF (bdvalgeral IS NULL) THEN
           bdvalgeral = 0;
        IF (bddif IS NULL) THEN
           bddif = 0;

        SUSPEND;
      END
END
^

/* Restore proc. body: VSUC_SP_TENC_EXERCICIO */
ALTER PROCEDURE VSUC_SP_TENC_EXERCICIO(PRCODEMP INTEGER,
PRCONTA VARCHAR(1024),
PRCTACONTRAPARTIDA INTEGER,
PRDATAINI DATE,
PRDATAFIM DATE,
PRDATALANC DATE,
PRLOTE VARCHAR(10),
PRCOMPLEMENTO VARCHAR(100),
PRCODTPHI INTEGER,
PRUSUARIO INTEGER,
PRCHAVEZERA INTEGER,
PRCODPLAPADRAO INTEGER,
PRCODHIST INTEGER,
PRREFEMP INTEGER,
PRLANCCONTRAPART INTEGER)
 RETURNS(PRCHAVEZERAMENTO INTEGER,
PRZEROUCONTAS INTEGER)
 AS
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(50);
DECLARE VARIABLE WCTADEB INTEGER;
DECLARE VARIABLE WCTACRE INTEGER;
DECLARE VARIABLE WVALLAN NUMERIC(15,2);
DECLARE VARIABLE WSQL VARCHAR(1024);
DECLARE VARIABLE WVALDEB NUMERIC(15,2);
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WVALCRE NUMERIC(15,2);
DECLARE VARIABLE WQUERY VARCHAR(1024);
BEGIN
  wvalcre = 0;
  wvaldeb = 0;
  wvallan = 0;
  wctalon = '';

  wsql = 'select tpla.bdctalon from planos_tpla tpla ';
  wsql = wsql||'where tpla.bdcodplapadrao = '||prcodplapadrao;
  wsql = wsql||' and tpla.bdcodtpla in ('||prconta||') ';
  wsql = wsql||'order by tpla.bdctalon';

  prchavezeramento = prchavezera;

  FOR EXECUTE STATEMENT wsql
      INTO :wclassificacao DO
      BEGIN
        IF ((prchavezeramento = 0) OR (prchavezeramento IS NULL))  THEN
           SELECT PRCHAVEZER FROM vsuc_sp_insert_encex(:prcodemp,:prcodplapadrao,:prctacontrapartida,:prcodhist,:prcodtphi,:prusuario,:prdataini,:prdatafim,:prdatalanc,CURRENT_DATE,CURRENT_TIME) INTO :prchavezeramento;
        -- Crédito
        wquery = 'select distinct(TLAN.bdcredito), sum(TLAN.bdvalor), Tpla.bdctalon ';
        wquery = wquery||'from VSUC_EMPRESAS_TLAN TLAN ';
        wquery = wquery||'join PLANOS_TPLA TPLA on (TPLA.bdcodplapadrao = TLAN.bdcodplapadrao and TPLA.bdcodtpla = TLAN.bdcredito and TPLA.bdtipcta = 1) ';
        wquery = wquery||'where (TLAN.bddata between '''||prdataini||''' and '''||prdatafim||''') ';
        wquery = wquery||'and (coalesce(TLAN.bdtipolan,1) <> 10) ';
        wquery = wquery||'and (TLAN.bdcodplapadrao = '||prcodplapadrao||') ';
        wquery = wquery||'and (TLAN.bdcodemp = '||prcodemp||') ';
        wquery = wquery||'and (substring(TPLA.bdctalon from 1 for '||strlen(wclassificacao)||') = '''||wclassificacao||''') ';
        wquery = wquery||'group by tlan.bdcredito,Tpla.bdctalon ';
        wquery = wquery||'order by Tpla.bdctalon ';

        FOR EXECUTE STATEMENT wquery
            INTO :wctacre, :wvallan, :wctalon DO
            BEGIN
              przeroucontas = 1;
              wvalcre = wvalcre + wvallan;
              IF (wvallan <> 0) THEN -- Não precisa efetuar o zeramento quando o valor for 0(zero)
                BEGIN
                  IF (prlanccontrapart <> 0) THEN
                     EXECUTE PROCEDURE vsuc_sp_insert_lanc(NULL, :prcodemp, :prcodplapadrao, :wctacre, :prctacontrapartida, :prcodhist, :prcodtphi, :prusuario, :prlote, :prdatalanc, :wvallan, :prcomplemento, :prdatalanc, NULL, 10, NULL, NULL, NULL,:prchavezeramento, :prrefemp);
                  ELSE
                    BEGIN
                      EXECUTE PROCEDURE vsuc_sp_insert_lanc(NULL, :prcodemp, :prcodplapadrao, :wctacre, NULL, :prcodhist, :prcodtphi, :prusuario, :prlote, :prdatalanc, :wvallan, :prcomplemento, :prdatalanc, NULL, 10, NULL, NULL, NULL,:prchavezeramento, :prrefemp);
--                    execute procedure vsuc_sp_insert_lanc(null, :prcodemp, :prcodplapadrao, null, :prctacontrapartida, :prcodhist, :prcodtphi, :prusuario, :prlote, :prdatalanc, :wvallan, :prcomplemento, :prdatalanc, null, 10, null, null, null,:prchavezeramento, :prrefemp);
                    END
                END
            END
        -- Débito
        wquery = 'select distinct(TLAN.bddebito), sum(TLAN.bdvalor), Tpla.bdctalon ';
        wquery = wquery||'from VSUC_EMPRESAS_TLAN TLAN ';
        wquery = wquery||'join PLANOS_TPLA TPLA on (TPLA.bdcodplapadrao = TLAN.bdcodplapadrao and TPLA.bdcodtpla = TLAN.bddebito and TPLA.bdtipcta = 1) ';
        wquery = wquery||'where (TLAN.bddata between '''||prdataini||''' and '''||prdatafim||''') ';
        wquery = wquery||'and (coalesce(TLAN.bdtipolan,1) <> 10) ';
        wquery = wquery||'and (TLAN.bdcodplapadrao = '||prcodplapadrao||') ';
        wquery = wquery||'and (TLAN.bdcodemp = '||prcodemp||') ';
        wquery = wquery||'and (substring(TPLA.bdctalon from 1 for '||strlen(wclassificacao)||') = '''||wclassificacao||''') ';
        wquery = wquery||'group by tlan.bddebito,Tpla.bdctalon ';
        wquery = wquery||'order by Tpla.bdctalon ';

        FOR EXECUTE STATEMENT wquery
            INTO :wctadeb, :wvallan, :wctalon DO
            BEGIN
              przeroucontas = 1;
              wvaldeb = wvaldeb + wvallan;
              IF (wvallan <> 0) THEN -- Não precisa efetuar o zeramento quando o valor for 0(zero)
                BEGIN
                  IF (prlanccontrapart <> 0) THEN
                     EXECUTE PROCEDURE vsuc_sp_insert_lanc(NULL, :prcodemp, :prcodplapadrao, :prctacontrapartida, :wctadeb, :prcodhist, :prcodtphi, :prusuario, :prlote, :prdatalanc, :wvallan, :prcomplemento, :prdatalanc, NULL, 10, NULL, NULL, NULL, :prchavezeramento, :prrefemp);
                   ELSE
                     BEGIN
--                      execute procedure vsuc_sp_insert_lanc(null, :prcodemp, :prcodplapadrao, :prctacontrapartida, null, :prcodhist, :prcodtphi, :prusuario, :prlote, :prdatalanc, :wvallan, :prcomplemento, :prdatalanc, null, 10, null, null, null, :prchavezeramento, :prrefemp);
                        EXECUTE PROCEDURE vsuc_sp_insert_lanc(NULL, :prcodemp, :prcodplapadrao, NULL, :wctadeb, :prcodhist, :prcodtphi, :prusuario, :prlote, :prdatalanc, :wvallan, :prcomplemento, :prdatalanc, NULL, 10, NULL, NULL, NULL, :prchavezeramento, :prrefemp);
                     END
                END
            END
      END
  /* Carlos Mello(16/06/2011) - Não precisa gerar um zeramento quando o valor for 0(zero) */
  IF (wvaldeb > 0) THEN
     EXECUTE PROCEDURE vsuc_sp_insert_lanc(NULL, :prcodemp, :prcodplapadrao, :prctacontrapartida, NULL, :prcodhist, :prcodtphi, :prusuario, :prlote, :prdatalanc, :wvaldeb, :prcomplemento, :prdatalanc, NULL, 10, NULL, NULL, NULL, :prchavezeramento, :prrefemp);

  IF (wvalcre > 0) THEN
     EXECUTE PROCEDURE vsuc_sp_insert_lanc(NULL, :prcodemp, :prcodplapadrao, NULL, :prctacontrapartida, :prcodhist, :prcodtphi, :prusuario, :prlote, :prdatalanc, :wvalcre, :prcomplemento, :prdatalanc, NULL, 10, NULL, NULL, NULL,:prchavezeramento, :prrefemp);

  --Exclui o registro na VSUC_EMPRESAS_TENCEXE caso não tenha feito nenhum lançamento de zeramento
  IF ((przeroucontas = 0) OR (przeroucontas IS NULL)) THEN
    EXECUTE STATEMENT 'Delete from VSUC_EMPRESAS_TENCEXE  where (BDCHAVEZER = '||prchavezeramento||')';

  SUSPEND;
END
^

/* Restore proc. body: VSUC_SP_UPDATE_TLAN_CONC_BANC */
ALTER PROCEDURE VSUC_SP_UPDATE_TLAN_CONC_BANC(PREMPRESA INTEGER,
PRDEBCRE INTEGER,
PRCONTA INTEGER,
PRDATAINICIAL DATE,
PRDATAFINAL DATE,
PRCOMPL VARCHAR(200),
PRVALOR FLOAT,
PRCODPLAPADRAO INTEGER,
PRDCTO VARCHAR(15),
PRCONTABILIZACAO INTEGER,
PRMATRIZFILIALCONSOLIDADO INTEGER)
 RETURNS(BDCODEMP INTEGER,
BDCODPLAPADRAO INTEGER,
BDCHAVE INTEGER)
 AS
DECLARE VARIABLE WVALOR FLOAT;
DECLARE VARIABLE WCOMPL VARCHAR(200);
DECLARE VARIABLE WCONCC VARCHAR(5);
DECLARE VARIABLE WCONCD VARCHAR(5);
BEGIN
  bdcodemp = prempresa;
  bdcodplapadrao = prcodplapadrao;

  --alt:17706 - 03/05/2017 - Criado tratamento no documento para desconsiderar números/caracteres depois dos símbolos "/", "\" ou "-". Pedro
  prDCTO = UPPER(SUBSTRING(prDCTO FROM 1 FOR
                           CASE WHEN (prDCTO CONTAINING '/') THEN POSITION('/', prDCTO) -1
                                WHEN (prDCTO CONTAINING '\') THEN POSITION('\', prDCTO) -1
                                WHEN (prDCTO CONTAINING '-') THEN POSITION('-', prDCTO) -1
                           ELSE CHAR_LENGTH(prDCTO) END));

  -- verifica se é débito crédito ou os dois
  --if (prdebcre = 0) then
  IF (prdebcre IN (0,2)) THEN
    BEGIN
      FOR SELECT bdchave,bdcompl,bdvalor FROM vsuc_empresas_tlan
      --alt:17706 - 03/05/2017 - Criado tratamento no documento para desconsiderar números/caracteres depois dos símbolos "/", "\" ou "-". Pedro
      --WHERE (((UPPER(bdcompl) LIKE :prcompl) AND (UPPER(bddcto) = UPPER(:prdcto))) /*OR((UPPER(bdcompl) LIKE :prcompl) OR (UPPER(bddcto) = UPPER(:prdcto)))*/)  --#alt:13456 - comentado pois estava alterando todos os lançamentos com o mesmo complemento. Ana - 28/10/2016
      WHERE (UPPER(bdcompl) LIKE :prcompl)
      AND   (UPPER(SUBSTRING(bddcto FROM 1 FOR
                             CASE WHEN (bddcto CONTAINING '/') THEN POSITION('/', bddcto) -1
                                  WHEN (bddcto CONTAINING '\') THEN POSITION('\', bddcto) -1
                                  WHEN (bddcto CONTAINING '-') THEN POSITION('-', bddcto) -1
                             ELSE CHAR_LENGTH(bddcto) END)) = :prDCTO)
      --alt:17706 - Fim
      AND   (bdvalor = :prvalor)
      AND   (bddata BETWEEN :prdatainicial AND :prdatafinal)
      AND   (bddebito = :prconta)
      AND   (bdcodplapadrao = :prcodplapadrao)
      AND   (bdcodemp = :prempresa)
      --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
      AND   (bdcontabilizacao IN (0,:prcontabilizacao))
      INTO :bdchave,:wcompl,:wvalor DO
        BEGIN
          --#alt:13456 - Atribuido valor ao campo do tipo de conciliação. Ana - 27/10/2016
          UPDATE vsuc_empresas_tlan SET bdconcd = 'TRUE'/*, bdtipoconc = 1*/ WHERE (bdchave = :bdchave) AND (bdcodemp = :prempresa) AND (UPPER(COALESCE(bdconcd,'')) <> 'TRUE');
          SUSPEND;
        END
    END
  --else
  --if (prdebcre = 1) then
  IF (prdebcre IN (1,2)) THEN
    BEGIN
      FOR SELECT bdchave, bdcompl, bdvalor FROM vsuc_empresas_tlan
      --alt:17706 - 03/05/2017 - Criado tratamento no documento para desconsiderar números/caracteres depois dos símbolos "/", "\" ou "-". Pedro
      --WHERE (((UPPER(bdcompl) LIKE :prcompl) AND (UPPER(bddcto) = UPPER(:prdcto))) /*OR ((UPPER(bdcompl) LIKE :prcompl) OR (UPPER(bddcto) = UPPER(:prdcto)))*/) --#alt:13456 - comentado pois estava alterando todos os lançamentos com o mesmo complemento. Ana - 28/10/2016
      WHERE (UPPER(bdcompl) LIKE :prcompl)
      AND   (UPPER(SUBSTRING(bddcto FROM 1 FOR
                             CASE WHEN (bddcto CONTAINING '/') THEN POSITION('/', bddcto) -1
                                  WHEN (bddcto CONTAINING '\') THEN POSITION('\', bddcto) -1
                                  WHEN (bddcto CONTAINING '-') THEN POSITION('-', bddcto) -1
                             ELSE CHAR_LENGTH(bddcto) END)) = :prDCTO)
      --alt:17706 - Fim
      AND   (bdvalor = :prvalor)
      AND   (bddata BETWEEN :prdatainicial AND :prdatafinal)
      AND   (bdcredito = :prconta)
      AND   (bdcodplapadrao = :prcodplapadrao)
      AND   (bdcodemp = :prempresa)
      --#alt:4750  1 -> Fiscal | 2 -> Societário | 99 -> Todos
      AND   (bdcontabilizacao IN (0,:prcontabilizacao))
      INTO :bdchave, :wcompl, :wvalor DO
        BEGIN
          --#alt:13456 - Atribuido valor ao campo do tipo de conciliação. Ana - 27/10/2016  
          UPDATE vsuc_empresas_tlan SET bdconcc = 'TRUE'/*, bdtipoconc = 2*/ WHERE (bdchave = :bdchave) AND (bdcodemp = :prempresa) AND (UPPER(COALESCE(bdconcc,'')) <> 'TRUE');
          SUSPEND;
        END
    END
  /*else
    begin
      for select bdchave, bdcompl, bdvalor from vsuc_empresas_tlan
      where (((Upper(bdcompl) like :prcompl) and (upper(bddcto) = upper(:prdcto))) or ((Upper(bdcompl) like :prcompl) or (upper(bddcto) = upper(:prdcto))))
      and   (bdvalor = :prvalor)
      and   (bddata Between :prdatainicial and :prdatafinal)
      and   (bddebito = :prconta)
      and   (bdcodplapadrao = :prcodplapadrao)
      and   (bdcodemp = :prempresa)
      into :bdchave, :wcompl, :wvalor do
        begin
          update vsuc_empresas_tlan set bdconcd = 'TRUE' where (bdchave = :bdchave) and (bdcodemp = :prempresa) and (Upper(COALESCE(bdconcd,'')) <> 'TRUE');
          suspend;
        end

      for select bdchave, bdcompl, bdvalor from vsuc_empresas_tlan
      where (((Upper(bdcompl) like :prcompl) and (upper(bddcto) = upper(:prdcto))) or ((Upper(bdcompl) like :prcompl) or (upper(bddcto) = upper(:prdcto))))
      and   (bdvalor = :prvalor)
      and   (bddata Between :prdatainicial and :prdatafinal)
      and   (bdcredito = :prconta)
      and   (bdcodplapadrao = :prcodplapadrao)
      and   (bdcodemp = :prempresa)
      into :bdchave, :wcompl, :wvalor do
        begin
          update vsuc_empresas_tlan set bdconcc = 'TRUE' where (bdchave = :bdchave) and (bdcodemp = :prempresa) and (Upper(COALESCE(bdconcc,'')) <> 'TRUE');
          suspend;
        end
    end
    SUSPEND;*/

  --#alt:13456 - Adicionada verificação se os dois valores foram conciliados, tanto debito quanto crédito
  FOR SELECT bdconcc, bdconcd FROM vsuc_empresas_tlan
      WHERE (bdcodemp = :prempresa)
      AND   (bdchave = :bdchave)
      INTO :wConcc, :wConcd DO
        BEGIN
          IF ((wConcc = 'TRUE') AND (wConcd = 'TRUE')) THEN
             UPDATE vsuc_empresas_tlan SET bdtipoconc = 3 WHERE (bdchave = :bdchave) AND (bdcodemp = :prempresa);
          SUSPEND;
        END
  --#alt:13456. fim
END
^

/* Restore proc. body: VSUC_SP_UPDATE_TLAN_CONC_CLIFOR */
ALTER PROCEDURE VSUC_SP_UPDATE_TLAN_CONC_CLIFOR(PREMPRESA INTEGER,
PRCONTAINICIAL INTEGER,
PRCONTAFINAL INTEGER,
PRDATAINICIAL VARCHAR(10),
PRDATAFINAL VARCHAR(10),
PRCLIFOR SMALLINT,
PRCODPLAPADRAO INTEGER)
 RETURNS(CONCILIACAOOK SMALLINT)
 AS
DECLARE VARIABLE wchave INTEGER;
DECLARE VARIABLE wclassificacaoini VARCHAR(50);
DECLARE VARIABLE wclassificacaofim VARCHAR(50);
BEGIN
  conciliacaook = 0;

  /* pega a classificação inicial da conta */
  SELECT bdctalon FROM planos_tpla WHERE (bdcodplapadrao = :prcodplapadrao) AND (bdcodtpla = :prcontainicial) INTO :wclassificacaoini;

  /* pega a classificação final da conta */
  SELECT bdctalon FROM planos_tpla WHERE (bdcodplapadrao = :prcodplapadrao) AND (bdcodtpla = :prcontafinal) INTO :wclassificacaofim;

  /* conciliação cliente dédito e crédito */
  /*if (prclifor = 0) then
    begin*/

  /*for select bdchave from vsuc_empresas_tlan
      where (bddata Between :prdatainicial and :prdatafinal)
      and   (bddebito Between :wclassificacaoini and :wclassificacaofim)
      and   (bdcodplapadrao = :wcodpla)
      and   (bdcodemp = :prempresa) into :wchave do*/

  FOR SELECT bdchave FROM vsuc_empresas_tlan tlan, planos_tpla tpla
      WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
      AND   (tlan.bdcodplapadrao = :prcodplapadrao)
      AND   (tlan.bdcodplapadrao = tpla.bdcodplapadrao)
      AND   (tlan.bddebito = tpla.bdcodtpla)
      AND   (tpla.bdctalon BETWEEN :wclassificacaoini AND :wclassificacaofim)
      AND   (bdcodemp = :prempresa) INTO :wchave DO
      BEGIN
        UPDATE vsuc_empresas_tlan SET bdconcd = 'TRUE' WHERE (bdchave = :wchave) AND (bdcodemp = :prempresa);
        conciliacaook = 1;
      END

  /*for select bdchave from vsuc_empresas_tlan
      where (bddata Between :prdatainicial and :prdatafinal)
      and   (bdcredito Between :wclassificacaoini and :wclassificacaofim)
      and   (bdcodplapadrao = :wcodpla)
      and   (bdcodemp = :prempresa) into :wchave do*/

  FOR SELECT bdchave FROM vsuc_empresas_tlan tlan, planos_tpla tpla
      WHERE (bddata BETWEEN :prdatainicial AND :prdatafinal)
      AND   (tlan.bdcodplapadrao = :prcodplapadrao)
      AND   (tlan.bdcodplapadrao = tpla.bdcodplapadrao)
      AND   (tlan.bdcredito = tpla.bdcodtpla)
      AND   (tpla.bdctalon BETWEEN :wclassificacaoini AND :wclassificacaofim)
      AND   (bdcodemp = :prempresa) INTO :wchave DO
      BEGIN
        UPDATE vsuc_empresas_tlan SET bdconcc = 'TRUE' WHERE (bdchave = :wchave) AND (bdcodemp = :prempresa);
        conciliacaook = 1;
      END
    /*end
  else
    begin

    end*/
  SUSPEND;
END
^

/* Restore proc. body: SP_VRH_EMP_GERENCIAL_PORIDADE */
CREATE OR ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORIDADE (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRDATAATUAL DATE,
    PRAGRUPADOR SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMECC DM_BDNOMEMP,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDIDADE01 INTEGER,
    BDIDADE02 INTEGER,
    BDIDADE03 INTEGER,
    BDIDADE04 INTEGER,
    BDIDADE05 INTEGER,
    BDIDADE06 INTEGER,
    BDIDADE07 INTEGER,
    BDIDADE08 INTEGER,
    BDIDADE09 INTEGER,
    BDIDADE10 INTEGER,
    BDIDADE11 INTEGER,
    BDTOTAL INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMECC DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WDATANASC DATE;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WNOMECCATU DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WID01 INTEGER;
DECLARE VARIABLE WID02 INTEGER;
DECLARE VARIABLE WID03 INTEGER;
DECLARE VARIABLE WID04 INTEGER;
DECLARE VARIABLE WID05 INTEGER;
DECLARE VARIABLE WID06 INTEGER;
DECLARE VARIABLE WID07 INTEGER;
DECLARE VARIABLE WID08 INTEGER;
DECLARE VARIABLE WID09 INTEGER;
DECLARE VARIABLE WID10 INTEGER;
DECLARE VARIABLE WID11 INTEGER;
DECLARE VARIABLE WID INTEGER;
DECLARE VARIABLE WDTRESC DATE;
BEGIN
  /*
    Essa procedure retorna os colaboradores ATIVOS (a partir e/ou até a data prDataAtual), separados por idade
    prAgrupador: 0 = Agrupado na empresa; 1 = Separado por centro de custos
  */


  IF (pragrupador = 1) THEN   -- Separa por centro de custos
    BEGIN
      wsql = 'select COL.BDCODEMP, '||
               'case when (CUSTO.BDDEESCCUS is not null and CUSTO.BDDEESCCUS <> '''') then CUSTO.BDDEESCCUS ' ||
                    'when (TPCC.BDNOMCTA is not null and TPCC.BDNOMCTA <> '''') then TPCC.BDNOMCTA '||
                    'else EMP.BDNOMEMP end, '||
               'DEP.BDCODCENTRO, DEP.BDCODTPCC, COL.BDDATANASCCOL, RESC.BDDATARESCISAO '||
             'from VRH_EMP_TCOLCON COL '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRHF_EMP_TPREPFN DEP on (DEP.BDCODEMP = COL.BDCODEMP and DEP.BDCODCOL = COL.BDCODCOL) '||
             'left outer join '||
               '( '||
                 'select CC.BDCODEMP, CC.BDCODCOL, MAX(CC.BDDATAENTRADA) BDDATAENTRADA '||
                 'from VRHF_EMP_TPREPFN CC '||
                 'where CC.BDDATAENTRADA <= '''||prdataatual||''' '||
                 'group by CC.BDCODEMP, CC.BDCODCOL '||
               ') FILTRO on (FILTRO.BDCODEMP = DEP.BDCODEMP and FILTRO.BDCODCOL = DEP.BDCODCOL and FILTRO.BDDATAENTRADA = DEP.BDDATAENTRADA) '||
             'left outer join VRH_CUSTOS_TCUSTOS CUSTO on (CUSTO.BDCODCENTRO = DEP.BDCODCENTRO and CUSTO.BDCODTPCC = DEP.BDCODTPCC) ' ||
             'left outer join CENTROS_TPCC TPCC on (TPCC.BDCODCENTRO = DEP.BDCODCENTRO and TPCC.BDCODTPCC = DEP.BDCODTPCC) ' ||
             'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

      wsql = wsql||
             'where COL.BDDATAADMCOL <= '''||prdataatual||''' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataatual||''')) ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP, DEP.BDCODCENTRO, DEP.BDCODTPCC ';
    END
  ELSE
    BEGIN
      wsql = 'select COL.BDCODEMP, EMP.BDNOMEMP, null BDCODCENTRO, null BDCODTPCC, COL.BDDATANASCCOL, RESC.BDDATARESCISAO '||
             'from VRH_EMP_TCOLCON COL '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

      wsql = wsql||
             'where COL.BDDATAADMCOL <= '''||prdataatual||''' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataatual||''')) ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP ';
    END

  wempatu = -1;
  wcodcentroatu = -1;
  wcodtpccatu = -1;
  wid01 = 0;
  wid02 = 0;
  wid03 = 0;
  wid04 = 0;
  wid05 = 0;
  wid06 = 0;
  wid07 = 0;
  wid08 = 0;
  wid09 = 0;
  wid10 = 0;
  wid11 = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wnomecc, :wcodcentro, :wcodtpcc, :wdatanasc, :wdtresc DO
    BEGIN
      IF (wempatu = -1) THEN
        wempatu = wcodemp;

      IF (wcodcentroatu = -1) THEN
        wcodcentroatu = wcodcentro;

      IF (wcodtpccatu = -1) THEN
        wcodtpccatu = wcodtpcc;

      IF ((wempatu <> wcodemp) OR (COALESCE(wcodcentroatu, -1) <> COALESCE(wcodcentro,-1)) OR (COALESCE(wcodtpccatu,-1) <> COALESCE(wcodtpcc,-1))) THEN
        BEGIN
          bdcodemp = wempatu;
          bdnomecc = wnomeccatu;
          bdcodcentro = wcodcentroatu;
          bdcodtpcc   = wcodtpccatu;

          bdidade01 = wid01;
          bdidade02 = wid02;
          bdidade03 = wid03;
          bdidade04 = wid04;
          bdidade05 = wid05;
          bdidade06 = wid06;
          bdidade07 = wid07;
          bdidade08 = wid08;
          bdidade09 = wid09;
          bdidade10 = wid10;
          bdidade11 = wid11;
          bdtotal   = wid01 + wid02 + wid03 + wid04 + wid05 + wid06 + wid07 + wid08 + wid09 + wid10 + wid11;
          SUSPEND;

          wempatu = wcodemp;
          wcodcentroatu = wcodcentro;
          wcodtpccatu   = wcodtpcc;
          wid01 = 0;
          wid02 = 0;
          wid03 = 0;
          wid04 = 0;
          wid05 = 0;
          wid06 = 0;
          wid07 = 0;
          wid08 = 0;
          wid09 = 0;
          wid10 = 0;
          wid11 = 0;
        END

      IF (wdatanasc IS NOT NULL) THEN
        BEGIN
          IF (wdtresc IS NOT NULL AND prdataatual > wdtresc) THEN
            wid = ROUND((wdtresc - wdatanasc) / 365.24);
          ELSE
            wid = ROUND((prdataatual - wdatanasc) / 365.24);

          IF (wid >= 14) THEN
            BEGIN
              IF (wid <= 18) THEN
                wid01 = wid01 + 1;
              ELSE
              IF (wid <= 23) THEN
                wid02 = wid02 + 1;
              ELSE
              IF (wid <= 28) THEN
                wid03 = wid03 + 1;
              ELSE
              IF (wid <= 33) THEN
                wid04 = wid04 + 1;
              ELSE
              IF (wid <= 38) THEN
                wid05 = wid05 + 1;
              ELSE
              IF (wid <= 43) THEN
                wid06 = wid06 + 1;
              ELSE
              IF (wid <= 48) THEN
                wid07 = wid07 + 1;
              ELSE
              IF (wid <= 53) THEN
                wid08 = wid08 + 1;
              ELSE
              IF (wid <= 58) THEN
                wid09 = wid09 + 1;
              ELSE
              IF (wid <= 63) THEN
                wid10 = wid10 + 1;
              ELSE
                wid11 = wid11 + 1;
            END
        END

      wnomeccatu = wnomecc;
    END


  IF (wempatu <> -1) THEN
    BEGIN
      bdcodemp    = wempatu;
      bdnomecc = wnomeccatu;
      bdcodcentro = wcodcentroatu;
      bdcodtpcc   = wcodtpccatu;

      bdidade01 = wid01;
      bdidade02 = wid02;
      bdidade03 = wid03;
      bdidade04 = wid04;
      bdidade05 = wid05;
      bdidade06 = wid06;
      bdidade07 = wid07;
      bdidade08 = wid08;
      bdidade09 = wid09;
      bdidade10 = wid10;
      bdidade11 = wid11;
      bdtotal   = wid01 + wid02 + wid03 + wid04 + wid05 + wid06 + wid07 + wid08 + wid09 + wid10 + wid11;
      SUSPEND;
    END
END
^

/* Restore proc. body: SP_VRH_EMP_GERENCIAL_PORTEMPO */
CREATE OR ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORTEMPO (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRDATAATUAL DATE,
    PRAGRUPADOR SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMECC DM_BDNOMEMP,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDTEMPO01 INTEGER,
    BDTEMPO02 INTEGER,
    BDTEMPO03 INTEGER,
    BDTEMPO04 INTEGER,
    BDTEMPO05 INTEGER,
    BDTEMPO06 INTEGER,
    BDTEMPO07 INTEGER,
    BDTEMPO08 INTEGER,
    BDTEMPO09 INTEGER,
    BDTEMPO10 INTEGER,
    BDTEMPO11 INTEGER,
    BDTOTAL INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMECC DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WDATAADM DATE;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WNOMECCATU DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WTP01 INTEGER;
DECLARE VARIABLE WTP02 INTEGER;
DECLARE VARIABLE WTP03 INTEGER;
DECLARE VARIABLE WTP04 INTEGER;
DECLARE VARIABLE WTP05 INTEGER;
DECLARE VARIABLE WTP06 INTEGER;
DECLARE VARIABLE WTP07 INTEGER;
DECLARE VARIABLE WTP08 INTEGER;
DECLARE VARIABLE WTP09 INTEGER;
DECLARE VARIABLE WTP10 INTEGER;
DECLARE VARIABLE WTP11 INTEGER;
DECLARE VARIABLE WTP INTEGER;
DECLARE VARIABLE WDTRESC DATE;
BEGIN
  /*
    Essa procedure retorna os colaboradores ATIVOS (a partir e/ou até a data prDataAtual), separados por tempo de serviço
    prAgrupador: 0 = Agrupado na empresa; 1 = Separado por centro de custos
  */


  IF (pragrupador = 1) THEN   -- Separa por centro de custos
    BEGIN
      wsql = 'select COL.BDCODEMP, '||
               'case when (CUSTO.BDDEESCCUS is not null and CUSTO.BDDEESCCUS <> '''') then CUSTO.BDDEESCCUS ' ||
                    'when (TPCC.BDNOMCTA is not null and TPCC.BDNOMCTA <> '''') then TPCC.BDNOMCTA '||
                    'else EMP.BDNOMEMP end, '||
               'DEP.BDCODCENTRO, DEP.BDCODTPCC, COL.BDDATAADMCOL, RESC.BDDATARESCISAO '||
             'from VRH_EMP_TCOLCON COL '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRHF_EMP_TPREPFN DEP on (DEP.BDCODEMP = COL.BDCODEMP and DEP.BDCODCOL = COL.BDCODCOL) '||
             'left outer join '||
               '( '||
                 'select CC.BDCODEMP, CC.BDCODCOL, MAX(CC.BDDATAENTRADA) BDDATAENTRADA '||
                 'from VRHF_EMP_TPREPFN CC '||
                 'where CC.BDDATAENTRADA <= '''||prdataatual||''' '||
                 'group by CC.BDCODEMP, CC.BDCODCOL '||
               ') FILTRO on (FILTRO.BDCODEMP = DEP.BDCODEMP and FILTRO.BDCODCOL = DEP.BDCODCOL and FILTRO.BDDATAENTRADA = DEP.BDDATAENTRADA) '||
             'left outer join VRH_CUSTOS_TCUSTOS CUSTO on (CUSTO.BDCODCENTRO = DEP.BDCODCENTRO and CUSTO.BDCODTPCC = DEP.BDCODTPCC) ' ||
             'left outer join CENTROS_TPCC TPCC on (TPCC.BDCODCENTRO = DEP.BDCODCENTRO and TPCC.BDCODTPCC = DEP.BDCODTPCC) ' ||
             'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

      wsql = wsql||
             'where COL.BDDATAADMCOL <= '''||prdataatual||''' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataatual||''')) ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP, DEP.BDCODCENTRO, DEP.BDCODTPCC ';
    END
  ELSE
    BEGIN
      wsql = 'select COL.BDCODEMP, EMP.BDNOMEMP, null BDCODCENTRO, null BDCODTPCC, COL.BDDATAADMCOL, RESC.BDDATARESCISAO '||
             'from VRH_EMP_TCOLCON COL '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

      wsql = wsql||
             'where COL.BDDATAADMCOL <= '''||prdataatual||''' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataatual||''')) ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP ';
    END

  wempatu = -1;
  wcodcentroatu = -1;
  wcodtpccatu = -1;
  wtp01 = 0;
  wtp02 = 0;
  wtp03 = 0;
  wtp04 = 0;
  wtp05 = 0;
  wtp06 = 0;
  wtp07 = 0;
  wtp08 = 0;
  wtp09 = 0;
  wtp10 = 0;
  wtp11 = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wnomecc, :wcodcentro, :wcodtpcc, :wdataadm, :wdtresc DO
    BEGIN
      IF (wempatu = -1) THEN
        wempatu = wcodemp;

      IF (wcodcentroatu = -1) THEN
        wcodcentroatu = wcodcentro;

      IF (wcodtpccatu = -1) THEN
        wcodtpccatu = wcodtpcc;

      IF ((wempatu <> wcodemp) OR (COALESCE(wcodcentroatu, -1) <> COALESCE(wcodcentro,-1)) OR (COALESCE(wcodtpccatu,-1) <> COALESCE(wcodtpcc,-1))) THEN
        BEGIN
          bdcodemp = wempatu;
          bdnomecc = wnomeccatu;
          bdcodcentro = wcodcentroatu;
          bdcodtpcc   = wcodtpccatu;

          bdTEMPO01 = wtp01;
          bdTEMPO02 = wtp02;
          bdTEMPO03 = wtp03;
          bdTEMPO04 = wtp04;
          bdTEMPO05 = wtp05;
          bdTEMPO06 = wtp06;
          bdTEMPO07 = wtp07;
          bdTEMPO08 = wtp08;
          bdTEMPO09 = wtp09;
          bdTEMPO10 = wtp10;
          bdTEMPO11 = wtp11;
          bdtotal   = wtp01 + wtp02 + wtp03 + wtp04 + wtp05 + wtp06 + wtp07 + wtp08 + wtp09 + wtp10 + wtp11;
          SUSPEND;

          wempatu = wcodemp;
          wcodcentroatu = wcodcentro;
          wcodtpccatu   = wcodtpcc;
          wtp01 = 0;
          wtp02 = 0;
          wtp03 = 0;
          wtp04 = 0;
          wtp05 = 0;
          wtp06 = 0;
          wtp07 = 0;
          wtp08 = 0;
          wtp09 = 0;
          wtp10 = 0;
          wtp11 = 0;
        END

      IF (wdataadm IS NOT NULL) THEN
        BEGIN
          IF (wdtresc IS NOT NULL AND prdataatual > wdtresc) THEN
            wtp = ROUND((wdtresc - wdataadm) / 365.24);
          ELSE
            wtp = ROUND((prdataatual - wdataadm) / 365.24);

          IF (wtp <= 2) THEN
            wtp01 = wtp01 + 1;
          ELSE
          IF (wtp <= 5) THEN
            wtp02 = wtp02 + 1;
          ELSE
          IF (wtp <= 8) THEN
            wtp03 = wtp03 + 1;
          ELSE
          IF (wtp <= 11) THEN
            wtp04 = wtp04 + 1;
          ELSE
          IF (wtp <= 14) THEN
            wtp05 = wtp05 + 1;
          ELSE
          IF (wtp <= 17) THEN
            wtp06 = wtp06 + 1;
          ELSE
          IF (wtp <= 20) THEN
            wtp07 = wtp07 + 1;
          ELSE
          IF (wtp <= 23) THEN
            wtp08 = wtp08 + 1;
          ELSE
          IF (wtp <= 26) THEN
            wtp09 = wtp09 + 1;
          ELSE
          IF (wtp <= 29) THEN
            wtp10 = wtp10 + 1;
          ELSE
            wtp11 = wtp11 + 1;
        END

      wnomeccatu = wnomecc;
    END


  IF (wempatu <> -1) THEN
    BEGIN
      bdcodemp    = wempatu;
      bdnomecc = wnomeccatu;
      bdcodcentro = wcodcentroatu;
      bdcodtpcc   = wcodtpccatu;

      bdTEMPO01 = wtp01;
      bdTEMPO02 = wtp02;
      bdTEMPO03 = wtp03;
      bdTEMPO04 = wtp04;
      bdTEMPO05 = wtp05;
      bdTEMPO06 = wtp06;
      bdTEMPO07 = wtp07;
      bdTEMPO08 = wtp08;
      bdTEMPO09 = wtp09;
      bdTEMPO10 = wtp10;
      bdTEMPO11 = wtp11;
      bdtotal   = wtp01 + wtp02 + wtp03 + wtp04 + wtp05 + wtp06 + wtp07 + wtp08 + wtp09 + wtp10 + wtp11;
      SUSPEND;
    END
END
^

/* Restore proc. body: SP_VRH_EMP_GERENCIAL_PORFUNCAO */
CREATE OR ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORFUNCAO (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRDATAATUAL DATE,
    PRAGRUPADOR SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMECC DM_BDNOMEMP,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDTEMPO01 INTEGER,
    BDTEMPO02 INTEGER,
    BDTEMPO03 INTEGER,
    BDTEMPO04 INTEGER,
    BDTEMPO05 INTEGER,
    BDTEMPO06 INTEGER,
    BDTEMPO07 INTEGER,
    BDTEMPO08 INTEGER,
    BDTEMPO09 INTEGER,
    BDTEMPO10 INTEGER,
    BDTEMPO11 INTEGER,
    BDTOTAL INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WSQL2 VARCHAR(1000);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WCODCOL INTEGER;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WNOMECC DM_BDNOMEMP;
DECLARE VARIABLE WNOMECCATU DM_BDNOMEMP;
DECLARE VARIABLE WDTCOL DATE;
DECLARE VARIABLE WDTCOLANTES DATE;
DECLARE VARIABLE WCODPLAFUC INTEGER;
DECLARE VARIABLE WCODTFUC INTEGER;
DECLARE VARIABLE WDTADM DATE;
DECLARE VARIABLE WDTRESC DATE;
DECLARE VARIABLE WTP INTEGER;
DECLARE VARIABLE WTP01 INTEGER;
DECLARE VARIABLE WTP02 INTEGER;
DECLARE VARIABLE WTP03 INTEGER;
DECLARE VARIABLE WTP04 INTEGER;
DECLARE VARIABLE WTP05 INTEGER;
DECLARE VARIABLE WTP06 INTEGER;
DECLARE VARIABLE WTP07 INTEGER;
DECLARE VARIABLE WTP08 INTEGER;
DECLARE VARIABLE WTP09 INTEGER;
DECLARE VARIABLE WTP10 INTEGER;
DECLARE VARIABLE WTP11 INTEGER;
BEGIN
  /*
    Essa procedure retorna os colaboradores ATIVOS (a partir e/ou até a data prDataAtual), separados por função/cargo
    prAgrupador: 0 = Agrupado na empresa; 1 = Separado por centro de custos

    Para essa procedure funcionar corretamente deve ser executado o SetaCompentencia do ObjectDAO com a competência atual.
  */

  IF (pragrupador = 1) THEN   -- Separa por centro de custos
    BEGIN
      wsql = 'select COL.BDCODEMP, '||
               'case when (CUSTO.BDDEESCCUS is not null and CUSTO.BDDEESCCUS <> '''') then CUSTO.BDDEESCCUS ' ||
                    'when (TPCC.BDNOMCTA is not null and TPCC.BDNOMCTA <> '''') then TPCC.BDNOMCTA '||
                    'else EMP.BDNOMEMP end, COL.BDCODCOL, '||
               'DEP.BDCODCENTRO, DEP.BDCODTPCC, COL.BDDATACOL, COL.BDCODPLAFUC, COL.BDCODTFUC, COL2.BDDATAADMCOL, RESC.BDDATARESCISAO '||
             'from VW_VRH_EMP_TCOL_VINCDIA COL '||
             'join VRH_EMP_TCOLCON COL2 on (COL2.BDCODEMP = COL.BDCODEMP and COL2.BDCODCOL = COL.BDCODCOL) '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRHF_EMP_TPREPFN DEP on (DEP.BDCODEMP = COL.BDCODEMP and DEP.BDCODCOL = COL.BDCODCOL) '||
             'left outer join '||
                '( '||
                  'select CC.BDCODEMP, CC.BDCODCOL, MAX(CC.BDDATAENTRADA) BDDATAENTRADA '||
                  'from VRHF_EMP_TPREPFN CC '||
                  'where CC.BDDATAENTRADA <= '''||prdataatual||''' '||
                  'group by CC.BDCODEMP, CC.BDCODCOL '||
                ') FILTRO on (FILTRO.BDCODEMP = DEP.BDCODEMP and FILTRO.BDCODCOL = DEP.BDCODCOL and FILTRO.BDDATAENTRADA = DEP.BDDATAENTRADA) '||
             'left outer join VRH_CUSTOS_TCUSTOS CUSTO on (CUSTO.BDCODCENTRO = DEP.BDCODCENTRO and CUSTO.BDCODTPCC = DEP.BDCODTPCC) '||
             'left outer join CENTROS_TPCC TPCC on (TPCC.BDCODCENTRO = DEP.BDCODCENTRO and TPCC.BDCODTPCC = DEP.BDCODTPCC) '||
             'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) '||
             'where COL2.BDDATAADMCOL <= '''||prdataatual||''' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataatual||''')) ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP, DEP.BDCODCENTRO, DEP.BDCODTPCC ';
    END
  ELSE
    BEGIN
      wsql = 'select COL.BDCODEMP, EMP.BDNOMEMP, COL.BDCODCOL, null BDCODCENTRO, null BDCODTPCC, COL.BDDATACOL, COL.BDCODPLAFUC, COL.BDCODTFUC, COL2.BDDATAADMCOL, RESC.BDDATARESCISAO '||
             'from VW_VRH_EMP_TCOL_VINCDIA COL '||
             'join VRH_EMP_TCOLCON COL2 on (COL2.BDCODEMP = COL.BDCODEMP and COL2.BDCODCOL = COL.BDCODCOL) '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

      wsql = wsql||
             'where COL2.BDDATAADMCOL <= '''||prdataatual||''' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataatual||''')) ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP ';
    END

  wempatu = -1;
  wcentroatu = -1;
  wcodtpccatu = -1;

  wtp01 = 0;
  wtp02 = 0;
  wtp03 = 0;
  wtp04 = 0;
  wtp05 = 0;
  wtp06 = 0;
  wtp07 = 0;
  wtp08 = 0;
  wtp09 = 0;
  wtp10 = 0;
  wtp11 = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wnomecc, :wcodcol, :wcodcentro, :wcodtpcc, :wdtcol, :wcodplafuc, :wcodtfuc, :wdtadm, :wdtresc DO
    BEGIN
      IF (wempatu = -1) THEN
        wempatu = wcodemp;

      IF (wcentroatu = -1) THEN
        wcentroatu = wcodcentro;

      IF (wcodtpccatu = -1) THEN
        wcodtpccatu = wcodtpcc;

      IF ((wempatu <> wcodemp) OR (COALESCE(wcentroatu,-1) <> COALESCE(wcodcentro,-1)) OR (COALESCE(wcodtpccatu,-1) <> COALESCE(wcodtpcc,-1))) THEN
        BEGIN
          BDCODEMP = wempatu;
          bdcodcentro = wcentroatu;
          bdcodtpcc = wcodtpccatu;
          bdnomecc = wnomeccatu;
          bdtempo01 = wtp01;
          bdtempo02 = wtp02;
          bdtempo03 = wtp03;
          bdtempo04 = wtp04;
          bdtempo05 = wtp05;
          bdtempo06 = wtp06;
          bdtempo07 = wtp07;
          bdtempo08 = wtp08;
          bdtempo09 = wtp09;
          bdtempo10 = wtp10;
          bdtempo11 = wtp11;
          bdtotal   = wtp01 + wtp02 + wtp03 + wtp04 + wtp05 + wtp06 + wtp07 + wtp08 + wtp09 + wtp10 + wtp11;
          SUSPEND;

          wtp01 = 0;
          wtp02 = 0;
          wtp03 = 0;
          wtp04 = 0;
          wtp05 = 0;
          wtp06 = 0;
          wtp07 = 0;
          wtp08 = 0;
          wtp09 = 0;
          wtp10 = 0;
          wtp11 = 0;

          wempatu = wcodemp;
          wcentroatu = wcodcentro;
          wcodtpccatu = wcodtpcc;
        END

      -- Verifica a última alteração de cargo
      wsql2 =
            'select MAX(COLV.BDDATACOL) BDDATACOL '||
            'from vrh_emp_tcol_vincdia COLV '||
            'where COLV.BDCODEMP = '||wcodemp||' and COLV.BDCODCOL = '||wcodcol||' and COLV.BDDATACOL < '''||wdtcol||''' and ((COALESCE(COLV.BDCODTFUC,0) <> '||COALESCE(wcodtfuc,0)||') or (COALESCE(COLV.BDCODPLAFUC,0) <> '||COALESCE(wcodplafuc,0)||')) ';

      wdtcolantes = NULL;
      EXECUTE STATEMENT wsql2 INTO :wdtcolantes;

      IF ((wdtcolantes IS NULL) OR (wdtcolantes < wdtadm)) THEN
        wdtcolantes = wdtadm;

      IF (wdtresc IS NOT NULL AND prdataatual > wdtresc) THEN
        wtp = ROUND((wdtresc - wdtcolantes) / 365.24);
      ELSE
        wtp = ROUND((prdataatual - wdtcolantes) / 365.24);

      IF (wtp <= 2) THEN
        wtp01 = wtp01 + 1;
      ELSE
      IF (wtp <= 5) THEN
        wtp02 = wtp02 + 1;
      ELSE
      IF (wtp <= 8) THEN
        wtp03 = wtp03 + 1;
      ELSE
      IF (wtp <= 11) THEN
        wtp04 = wtp04 + 1;
      ELSE
      IF (wtp <= 14) THEN
        wtp05 = wtp05 + 1;
      ELSE
      IF (wtp <= 17) THEN
        wtp06 = wtp06 + 1;
      ELSE
      IF (wtp <= 20) THEN
        wtp07 = wtp07 + 1;
      ELSE
      IF (wtp <= 23) THEN
        wtp08 = wtp08 + 1;
      ELSE
      IF (wtp <= 26) THEN
        wtp09 = wtp09 + 1;
      ELSE
      IF (wtp <= 29) THEN
        wtp10 = wtp10 + 1;
      ELSE
        wtp11 = wtp11 + 1;

      wnomeccatu = wnomecc;
    END

  IF (wempatu <> -1) THEN
    BEGIN
      BDCODEMP = wempatu;
      bdcodcentro = wcentroatu;
      bdcodtpcc = wcodtpccatu;
      bdnomecc = wnomeccatu;
      bdtempo01 = wtp01;
      bdtempo02 = wtp02;
      bdtempo03 = wtp03;
      bdtempo04 = wtp04;
      bdtempo05 = wtp05;
      bdtempo06 = wtp06;
      bdtempo07 = wtp07;
      bdtempo08 = wtp08;
      bdtempo09 = wtp09;
      bdtempo10 = wtp10;
      bdtempo11 = wtp11;
      bdtotal   = wtp01 + wtp02 + wtp03 + wtp04 + wtp05 + wtp06 + wtp07 + wtp08 + wtp09 + wtp10 + wtp11;
      SUSPEND;
    END
END
^

/* Restore proc. body: SP_VRH_EMP_GERENCIAL_PORINST */
CREATE OR ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORINST (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRDATAATUAL DATE,
    PRGRAUINST SMALLINT = 0,
    PRAGRUPADOR SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMECC DM_BDNOMEMP,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDINST01 INTEGER,
    BDINST02 INTEGER,
    BDINST03 INTEGER,
    BDINST04 INTEGER,
    BDINST05 INTEGER,
    BDINST06 INTEGER,
    BDINST07 INTEGER,
    BDINST08 INTEGER,
    BDINST09 INTEGER,
    BDINST10 INTEGER,
    BDINST11 INTEGER,
    BDINST12 INTEGER,
    BDINST13 INTEGER,
    BDTOTAL INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMECC DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WNOMECCATU DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WGRAU INTEGER;
DECLARE VARIABLE WINST01 INTEGER;
DECLARE VARIABLE WINST02 INTEGER;
DECLARE VARIABLE WINST03 INTEGER;
DECLARE VARIABLE WINST04 INTEGER;
DECLARE VARIABLE WINST05 INTEGER;
DECLARE VARIABLE WINST06 INTEGER;
DECLARE VARIABLE WINST07 INTEGER;
DECLARE VARIABLE WINST08 INTEGER;
DECLARE VARIABLE WINST09 INTEGER;
DECLARE VARIABLE WINST10 INTEGER;
DECLARE VARIABLE WINST11 INTEGER;
DECLARE VARIABLE WINST12 INTEGER;
DECLARE VARIABLE WINST13 INTEGER;
BEGIN
  /*
    Essa procedure retorna os colaboradores ATIVOS (a partir e/ou até a data prDataAtual), separados por grau de instruçao
    prGrauInst: 0 = Todos; 1 = 1º Grau; 2 = 2º Grau; 3 = 3º Grau
    prAgrupador: 0 = Agrupado na empresa; 1 = Separado por centro de custos
  */


  IF (pragrupador = 1) THEN   -- Separa por centro de custos
    BEGIN
      wsql = 'select COL.BDCODEMP, '||
               'case when (CUSTO.BDDEESCCUS is not null and CUSTO.BDDEESCCUS <> '''') then CUSTO.BDDEESCCUS ' ||
                    'when (TPCC.BDNOMCTA is not null and TPCC.BDNOMCTA <> '''') then TPCC.BDNOMCTA '||
                    'else EMP.BDNOMEMP end, '||
               'DEP.BDCODCENTRO, DEP.BDCODTPCC, COALESCE(COL.BDGRAUINSTCOL,0) '||
             'from VRH_EMP_TCOLCON COL '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRHF_EMP_TPREPFN DEP on (DEP.BDCODEMP = COL.BDCODEMP and DEP.BDCODCOL = COL.BDCODCOL) '||
             'left outer join '||
               '( '||
                 'select CC.BDCODEMP, CC.BDCODCOL, MAX(CC.BDDATAENTRADA) BDDATAENTRADA '||
                 'from VRHF_EMP_TPREPFN CC '||
                 'where CC.BDDATAENTRADA <= '''||prdataatual||''' '||
                 'group by CC.BDCODEMP, CC.BDCODCOL '||
               ') FILTRO on (FILTRO.BDCODEMP = DEP.BDCODEMP and FILTRO.BDCODCOL = DEP.BDCODCOL and FILTRO.BDDATAENTRADA = DEP.BDDATAENTRADA) '||
             'left outer join VRH_CUSTOS_TCUSTOS CUSTO on (CUSTO.BDCODCENTRO = DEP.BDCODCENTRO and CUSTO.BDCODTPCC = DEP.BDCODTPCC) ' ||
             'left outer join CENTROS_TPCC TPCC on (TPCC.BDCODCENTRO = DEP.BDCODCENTRO and TPCC.BDCODTPCC = DEP.BDCODTPCC) ' ||
             'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

      wsql = wsql||
             'where COL.BDDATAADMCOL <= '''||prdataatual||''' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataatual||''')) ';

      IF (prgrauinst = 1) THEN  -- Filtro somente colaboradores com o primeiro grau
        wsql = wsql||
               ' and COALESCE(COL.BDGRAUINSTCOL,0) in (0,1,2,3,4) ';
      ELSE
      IF (prgrauinst = 2) THEN  -- Filtro somente colaboradores com o segundo grau
        wsql = wsql||
               ' and COALESCE(COL.BDGRAUINSTCOL,0) in (5,6) ';
      ELSE
      IF (prgrauinst = 3) THEN  -- Filtro somente colaboradores com o terceiro grau
        wsql = wsql||
               ' and COALESCE(COL.BDGRAUINSTCOL,0) in (7,8,9,10,11,12) ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP, DEP.BDCODCENTRO, DEP.BDCODTPCC ';
    END
  ELSE
    BEGIN
      wsql = 'select COL.BDCODEMP, EMP.BDNOMEMP, null BDCODCENTRO, null BDCODTPCC, COL.BDGRAUINSTCOL '||
             'from VRH_EMP_TCOLCON COL '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';

      wsql = wsql||
             'where COL.BDDATAADMCOL <= '''||prdataatual||''' and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||prdataatual||''')) ';

      IF (prgrauinst = 1) THEN  -- Filtro somente colaboradores com o primeiro grau
        wsql = wsql||
               ' and COALESCE(COL.BDGRAUINSTCOL,0) in (0,1,2,3,4) ';
      ELSE
      IF (prgrauinst = 2) THEN  -- Filtro somente colaboradores com o segundo grau
        wsql = wsql||
               ' and COALESCE(COL.BDGRAUINSTCOL,0) in (5,6) ';
      ELSE
      IF (prgrauinst = 3) THEN  -- Filtro somente colaboradores com o terceiro grau
        wsql = wsql||
               ' and COALESCE(COL.BDGRAUINSTCOL,0) in (7,8,9,10,11,12) ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP ';
    END

  wempatu = -1;
  wcodcentroatu = -1;
  wcodtpccatu = -1;
  wINST01 = 0;
  wINST02 = 0;
  wINST03 = 0;
  wINST04 = 0;
  wINST05 = 0;
  wINST06 = 0;
  wINST07 = 0;
  wINST08 = 0;
  wINST09 = 0;
  wINST10 = 0;
  wINST11 = 0;
  wINST12 = 0;
  wINST13 = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wnomecc, :wcodcentro, :wcodtpcc, :wgrau DO
    BEGIN
      IF (wempatu = -1) THEN
        wempatu = wcodemp;

      IF (wcodcentroatu = -1) THEN
        wcodcentroatu = wcodcentro;

      IF (wcodtpccatu = -1) THEN
        wcodtpccatu = wcodtpcc;

      IF ((wempatu <> wcodemp) OR (COALESCE(wcodcentroatu, -1) <> COALESCE(wcodcentro,-1)) OR (COALESCE(wcodtpccatu,-1) <> COALESCE(wcodtpcc,-1))) THEN
        BEGIN
          bdcodemp = wempatu;
          bdnomecc = wnomeccatu;
          bdcodcentro = wcodcentroatu;
          bdcodtpcc   = wcodtpccatu;

          BDINST01 = wINST01;
          BDINST02 = wINST02;
          BDINST03 = wINST03;
          BDINST04 = wINST04;
          BDINST05 = wINST05;
          BDINST06 = wINST06;
          BDINST07 = wINST07;
          BDINST08 = wINST08;
          BDINST09 = wINST09;
          BDINST10 = wINST10;
          BDINST11 = wINST11;
          BDINST12 = wINST12;
          BDINST13 = wINST13;
          bdtotal   = wINST01 + wINST02 + wINST03 + wINST04 + wINST05 + wINST06 + wINST07 + wINST08 + wINST09 + wINST10 + wINST11 + wINST12 + wINST13;
          SUSPEND;

          wempatu = wcodemp;
          wcodcentroatu = wcodcentro;
          wcodtpccatu   = wcodtpcc;
          wINST01 = 0;
          wINST02 = 0;
          wINST03 = 0;
          wINST04 = 0;
          wINST05 = 0;
          wINST06 = 0;
          wINST07 = 0;
          wINST08 = 0;
          wINST09 = 0;
          wINST10 = 0;
          wINST11 = 0;
          wINST12 = 0;
          wINST13 = 0;
        END

      IF (wGRAU = 1) THEN
        wINST02 = wINST02 + 1;
      ELSE
      IF (wGRAU = 2) THEN
        wINST03 = wINST03 + 1;
      ELSE
      IF (wGRAU = 3) THEN
        wINST04 = wINST04 + 1;
      ELSE
      IF (wGRAU = 4) THEN
        wINST05 = wINST05 + 1;
      ELSE
      IF (wGRAU = 5) THEN
        wINST06 = wINST06 + 1;
      ELSE
      IF (wGRAU = 6) THEN
        wINST07 = wINST07 + 1;
      ELSE
      IF (wGRAU = 7) THEN
        wINST08 = wINST08 + 1;
      ELSE
      IF (wGRAU = 8) THEN
        wINST09 = wINST09 + 1;
      ELSE
      IF (wGRAU = 9) THEN
        wINST10 = wINST10 + 1;
      ELSE
      IF (wGRAU = 10) THEN
        wINST11 = wINST11 + 1;
      ELSE
      IF (wGRAU = 11) THEN
        wINST12 = wINST12 + 1;
      ELSE
      IF (wGRAU = 12) THEN
        wINST13 = wINST13 + 1;
      ELSE
        wINST01 = wINST01 + 1;

      wnomeccatu = wnomecc;
    END


  IF (wempatu <> -1) THEN
    BEGIN
      bdcodemp    = wempatu;
      bdnomecc = wnomeccatu;
      bdcodcentro = wcodcentroatu;
      bdcodtpcc   = wcodtpccatu;

      BDINST01 = wINST01;
      BDINST02 = wINST02;
      BDINST03 = wINST03;
      BDINST04 = wINST04;
      BDINST05 = wINST05;
      BDINST06 = wINST06;
      BDINST07 = wINST07;
      BDINST08 = wINST08;
      BDINST09 = wINST09;
      BDINST10 = wINST10;
      BDINST11 = wINST11;
      BDINST12 = wINST12;
      BDINST13 = wINST13;
      bdtotal   = wINST01 + wINST02 + wINST03 + wINST04 + wINST05 + wINST06 + wINST07 + wINST08 + wINST09 + wINST10 + wINST11 + wINST12 + wINST13;
      SUSPEND;
    END
END
^

/* Restore proc. body: SP_VRH_EMP_GERENCIAL_PORRESC */
CREATE OR ALTER PROCEDURE SP_VRH_EMP_GERENCIAL_PORRESC (
    PRCODEMP VARCHAR(20000),
    PRCODCOL VARCHAR(32700),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRAGRUPADOR SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDNOMECC DM_BDNOMEMP,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDREFRESCISAO INTEGER,
    BDINIEMP INTEGER,
    BDINICOL INTEGER,
    BDTOTALSAIDAS INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WNOMECC DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WNOMECCATU DM_BDNOMEMP;
DECLARE VARIABLE WCODCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WREFRESC INTEGER;
DECLARE VARIABLE WREFRESCANT INTEGER;
DECLARE VARIABLE WINIC INTEGER;
DECLARE VARIABLE WINIEMP INTEGER;
DECLARE VARIABLE WINICOL INTEGER;
BEGIN
  /*
    Essa procedure retorna os colaboradores DEMITIDO dentro do período prrefini e prreffim
    prAgrupador: 0 = Agrupado na empresa; 1 = Separado por centro de custos
  */


  IF (pragrupador = 1) THEN   -- Separa por centro de custos
    BEGIN
      wsql = 'select COL.BDCODEMP, '||
               'case when (CUSTO.BDDEESCCUS is not null and CUSTO.BDDEESCCUS <> '''') then CUSTO.BDDEESCCUS ' ||
                    'when (TPCC.BDNOMCTA is not null and TPCC.BDNOMCTA <> '''') then TPCC.BDNOMCTA '||
                    'else EMP.BDNOMEMP end, '||
               'DEP.BDCODCENTRO, DEP.BDCODTPCC, COL.BDREFRESCISAO, COALESCE(PRES.BDINIPRES,0) '||
             'from VRH_EMP_TRESCISAO COL '||
             'join VRH_BASE_TPREPRESC PRES on (PRES.BDCODPRES = COL.BDCODPRES) '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) '||
             'left outer join VRHF_EMP_TPREPFN DEP on (DEP.BDCODEMP = COL.BDCODEMP and DEP.BDCODCOL = COL.BDCODCOL) '||
             'left outer join '||
               '( '||
                 'select CC.BDCODEMP, CC.BDCODCOL, MAX(CC.BDDATAENTRADA) BDDATAENTRADA '||
                 'from VRHF_EMP_TPREPFN CC '||
                 'group by CC.BDCODEMP, CC.BDCODCOL '||
               ') FILTRO on (FILTRO.BDCODEMP = DEP.BDCODEMP and FILTRO.BDCODCOL = DEP.BDCODCOL and FILTRO.BDDATAENTRADA = DEP.BDDATAENTRADA) '||
             'left outer join VRH_CUSTOS_TCUSTOS CUSTO on (CUSTO.BDCODCENTRO = DEP.BDCODCENTRO and CUSTO.BDCODTPCC = DEP.BDCODTPCC) ' ||
             'left outer join CENTROS_TPCC TPCC on (TPCC.BDCODCENTRO = DEP.BDCODCENTRO and TPCC.BDCODTPCC = DEP.BDCODTPCC) ';

      wsql = wsql||
             'where COL.BDREFRESCISAO >= '||prrefini||' and COL.BDREFRESCISAO <= '||prreffim||' ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP, COL.BDREFRESCISAO, DEP.BDCODCENTRO, DEP.BDCODTPCC ';
    END
  ELSE
    BEGIN
      wsql = 'select COL.BDCODEMP, EMP.BDNOMEMP, null BDCODCENTRO, null BDCODTPCC, COL.BDREFRESCISAO, COALESCE(PRES.BDINIPRES,0) '||
             'from VRH_EMP_TRESCISAO COL '||
             'join VRH_BASE_TPREPRESC PRES on (PRES.BDCODPRES = COL.BDCODPRES) '||
             'join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = COL.BDCODEMP) ';

      wsql = wsql||
             'where COL.BDREFRESCISAO >= '||prrefini||' and COL.BDREFRESCISAO <= '||prreffim||' ';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wsql = wsql||' and '||prcodemp;

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
        wsql = wsql||' and '||prcodcol;

      wsql = wsql||' order by COL.BDCODEMP, COL.BDREFRESCISAO ';
    END

  wempatu = -1;
  wcodcentroatu = -1;
  wcodtpccatu = -1;
  wrefrescant = -1;
  winiemp = 0;
  winicol = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wnomecc, :wcodcentro, :wcodtpcc, :wrefresc, :winic DO
    BEGIN
      IF (wempatu = -1) THEN
        wempatu = wcodemp;

      IF (wcodcentroatu = -1) THEN
        wcodcentroatu = wcodcentro;

      IF (wcodtpccatu = -1) THEN
        wcodtpccatu = wcodtpcc;

      IF (wrefrescant = -1) THEN
        wrefrescant = wrefresc;

      IF ((wempatu <> wcodemp) OR (wrefrescant <> wrefresc) OR (COALESCE(wcodcentroatu, -1) <> COALESCE(wcodcentro,-1)) OR (COALESCE(wcodtpccatu,-1) <> COALESCE(wcodtpcc,-1))) THEN
        BEGIN
          bdcodemp = wempatu;
          bdnomecc = wnomeccatu;
          bdcodcentro = wcodcentroatu;
          bdcodtpcc   = wcodtpccatu;
          bdrefrescisao = wrefrescant;

          bdinicol = winicol;
          bdiniemp = winiemp;
          bdtotalsaidas = winicol + winiemp;
          SUSPEND;

          wempatu = wcodemp;
          wcodcentroatu = wcodcentro;
          wcodtpccatu   = wcodtpcc;
          wrefrescant = wrefresc;
          winicol = 0;
          winiemp = 0;
        END

      IF (winic = 0) THEN
        winicol = winicol + 1;
      ELSE
        winiemp = winiemp + 1;

      wnomeccatu = wnomecc;
    END


  IF (wempatu <> -1) THEN
    BEGIN
      bdcodemp    = wempatu;
      bdnomecc = wnomeccatu;
      bdcodcentro = wcodcentroatu;
      bdcodtpcc   = wcodtpccatu;
      bdrefrescisao = wrefrescant;
      bdinicol = winicol;
      bdiniemp = winiemp;
      bdtotalsaidas = winicol + winiemp;
      SUSPEND;
    END
END
^

-- Sol. 18932 - Marcelo B. M. - Alt:20/07/2017
/* Restore proc. body: SP_VRHF_DADOS_INSS_FN_PREV_RESC */
CREATE OR ALTER procedure SP_VRHF_DADOS_INSS_FN_PREV_RESC (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS varchar(15000) = null)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDCODCENTROS integer,
    BDCODTPCC integer,
    BDINSSFNPR numeric(18,6),
    BDINSSFEFOLFNPR numeric(18,6),
    BDINSS13FNPR numeric(18,6),
    BDBINSSFNPR numeric(18,6),
    BDBINSSFEFOLFNPR numeric(18,6),
    BDBINSS13FNPR numeric(18,6),
    BDBRATAPOFNPR numeric(18,6),
    BDBRATAPOFEFNPR numeric(18,6),
    BDBRATAPO13FNPR numeric(18,6),
    BDSALFAMFNPR numeric(18,6),
    BDSALMATEMPFNPR numeric(18,6),
    BDBINSS13INDFNPR numeric(18,6),
    BDBINSSAPFNPR numeric(18,6),
    BDBINSS13APFNPR numeric(18,6),
    BDINSSAPFNPR numeric(18,6),
    BDINSS13APFNPR numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDPERCRATCOL numeric(18,6),
    BDPERCDESCFPASCOL numeric(18,6),
    BDBASERAT numeric(18,6))
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(30000);
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WCLAVER varchar(20);
declare variable WTIPOCODVER integer;
declare variable WINSSVER integer;
declare variable WBASEGPSVER varchar(5);
declare variable WREEMBGPSVER varchar(5);
declare variable WVALOR numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WINSSFE numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WBASEINSS numeric(18,6);
declare variable WBASEINSSFE numeric(18,6);
declare variable WBASEINSS13 numeric(18,6);
declare variable WSALFAM numeric(18,6);
declare variable WSALMATEMP numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WBINSSAP numeric(18,6);
declare variable WBINSS13AP numeric(18,6);
declare variable WINSSAP numeric(18,6);
declare variable WINSS13AP numeric(18,6);
declare variable WAINSSAP numeric(18,6);
declare variable WAINSS13AP numeric(18,6);
declare variable WEMPAP integer;
declare variable WSOMAAP numeric(18,6);
declare variable WTABINSS integer;
declare variable WSQLINSS varchar(1500);
declare variable WALIQINSS numeric(18,6);
declare variable WFAIXAINSS numeric(18,6);
declare variable WCODSIND integer;
declare variable WLIMSIND integer;
declare variable WLIMEMP integer;
declare variable WCONTRCOL integer;
declare variable WREEMB numeric(18,6);
declare variable WREFRESC integer;
declare variable WBMULTVINC numeric(18,6);
declare variable WVMULTVINC numeric(18,6);
declare variable WVINDEVIDO numeric(18,6);
declare variable WVINDEVIDOSF numeric(18,6);
declare variable WBAVPREV numeric(18,6);
declare variable WTEMVALOR smallint;
declare variable WPERCDESCFPAS numeric(18,6);
declare variable WSINDATU integer;
declare variable WBASEINSSCONTR numeric(18,6);
declare variable WBASEINSSCONTRATU numeric(18,6);
declare variable WCLATRIB integer;
declare variable WCOOP integer;
declare variable WCATESOC integer;
declare variable WSALMIN numeric(15,2);
declare variable WCATEGORIAESOC integer;
BEGIN
  wsql = 'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFNPR, FNPR.BDINSSAPFNPR, FNPR.BDINSS13APFNPR, VERREF.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, '||
                'VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, FNPR.BDBINSSFNPR from (';

  IF (prfiliais IS NOT NULL AND prfiliais <> '') THEN
     BEGIN
       wsql = wsql||'select BDCODEMP from TEMPRESAS where ((';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||prcodemp||') or (';

       wsql = wsql||prfiliais||'))) FILIAIS ';
       wsql = wsql||'join VRHF_EMP_TVERBAFN_PREV_RESC FN on (FN.BDCODEMP = FILIAIS.BDCODEMP';

       IF (prref IS NOT NULL AND prref <> 0) THEN
         wsql = wsql||' and RESC.BDREFRESCISAOPREV = '||prref;

      wsql = wsql||') ';
     END
  ELSE
    BEGIN
      wsql = wsql||'select PREV.* from VRHF_EMP_TVERBAFN_PREV_RESC PREV ';
      wsql = wsql||'join VRH_EMP_TRESCISAO_PREVIA RESC on RESC.BDCODEMP = PREV.BDCODEMP and RESC.BDCODCOL = PREV.BDCODCOL ';
      wwhere  = '';

      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         BEGIN
           wwhere = wwhere||replace(UPPER(prcodemp), 'BDCODEMP', 'PREV.BDCODEMP');
    
           IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
              BEGIN
                IF (wwhere <> '') THEN
                   wwhere = wwhere||' and ';
         
                wwhere = wwhere||replace(UPPER(prcodcol), 'BDCODCOL', 'PREV.BDCODCOL');
              END
         END
    
      IF (prref IS NOT NULL AND prref <> 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'RESC.BDREFRESCISAOPREV = '||prref||' ';
         END
    
    
      IF (wwhere <> '') THEN
         wwhere = ' where '||wwhere;
    
      wsql = wsql||wwhere;
    
      wsql = wsql||') FN ';
    END

  wsql = wsql||'join VRHF_EMP_TFOLHANORMAL_PREV_RESC FNPR on (FNPR.BDCODEMP = FN.BDCODEMP and FNPR.BDCODCOL = FN.BDCODCOL) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||'left outer join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';
  ELSE
     wsql = wsql||'join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';

  wsql = wsql||'order by FN.BDCODEMP,FN.BDCODCOL ';

  wempatu     = 0;
  wcolatu     = 0;
  wsalfam     = 0;
  winss       = 0;
  winssfe     = 0;
  winss13     = 0;
  wbaseinss   = 0;
  wbaseinssfe = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wbinssap    = 0;
  wbinss13ap  = 0;
  wainssap    = 0;
  wainss13ap  = 0;
  wempap      = 0;
  wsomaap     = 0;
  wreemb      = 0;
  wvindevido  = 0;
  wvindevidosf = 0;
  wbavprev     = 0;
  wtemvalor = 0;
  wsindatu = 0;
  wcodsind = -1;
  wclatrib = null;
  wcoop    = null;
  wcatesoc = null;

  EXECUTE PROCEDURE sp_seta_competencia(prref);

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wvalor, :winssap, :winss13ap, :wclaver, :wtipocodver, :winssver, :wbasegpsver, :wreembgpsver, :wbaseinsscontr DO
  BEGIN
    IF (wempatu = 0) THEN
      BEGIN
        wempatu = wcodemp;
        wlimemp = NULL;
        SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
        IF (wlimemp IS NULL) THEN
           wlimemp = 0;    -- não possui liminar

        select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
        into :wclatrib, :wcoop;
        wclatrib = coalesce(wclatrib, 0);
        wcoop    = coalesce(wcoop, 0);
      END

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    /*
      Retorna bases de INSS
    */
    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol)) THEN
       BEGIN
         --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a versão com a alteração abaixo corretamente.
         SELECT BDCODSINTRAB FROM VW_VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
         IF (wsindatu <> wcodsind) THEN
           BEGIN
             wlimsind = NULL;
             wsindatu = wcodsind;
             IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
                SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wsindatu INTO :wlimsind;
             IF (wlimsind IS NULL) THEN
                wlimsind = 0;             -- não possui liminar
           END

         IF (wempatu <> wcodemp) THEN
           BEGIN
             wlimemp = NULL;
             SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
             IF (wlimemp IS NULL) THEN
                wlimemp = 0;    -- não possui liminar

             wclatrib = null;
             wcoop    = null;
             select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
             into :wclatrib, :wcoop;
             wclatrib = coalesce(wclatrib, 0);
             wcoop    = coalesce(wcoop, 0);
           END

         BDGPSSEFIP       = 0;
         BDCODEMP         = wempatu;
         BDCODCOL         = wcolatu;
         BDREFFN          = prref;
         BDCODCENTROS     = NULL;
         BDCODTPCC        = NULL;
         BDINSSFNPR       = winss;
         BDINSSFEFOLFNPR  = winssfe;
         BDINSS13FNPR     = winss13;
         BDBAVPREV        = 0;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSSFNPR = wbinssap;
         ELSE
            BDBINSSFNPR = wbaseinss;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13FNPR = wbaseinss13 - wbinss13ap;
         ELSE
            BDBINSS13FNPR = wbaseinss13;

         BDBINSSFEFOLFNPR = wbaseinssfe;
         BDBINSSAPFNPR    = wbinssap;
         BDBINSS13APFNPR  = wbinss13ap;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13INDFNPR = 0;
         ELSE
            BDBINSS13INDFNPR = wbinss13ap;

         IF (BDBINSSFEFOLFNPR > 0 AND BDINSSFNPR < 0) THEN
            BDINSSFEFOLFNPR = bdinssfefolfnpr + bdinssfnpr;

         IF (BDBINSSFNPR < 0 AND BDBINSSFEFOLFNPR > 0) THEN
            BDBINSSFEFOLFNPR = BDBINSSFEFOLFNPR + BDBINSSFNPR;

         wpercrat = 0;
         wpercdescfpas = 0;
         wcontrcol = NULL;
         wcatesoc = null;
         SELECT BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL, BDCATEGORIAESOCIAL
         FROM VW_VRHF_EMP_TCOLCON_FGTSGPS
         WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu
         INTO :wpercrat, :wpercdescfpas, :wcontrcol, :wcatesoc;

         IF (wcontrcol IS NULL) THEN
            wcontrcol = 0;

         IF (wcontrcol = 1) THEN
            bdbinssfnpr = wbaseinsscontratu;

         IF (bdbinssfnpr < 0) THEN
            bdbinssfnpr = 0;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BEGIN
              BDBRATAPOFNPR   = BDBINSSFNPR;     --+ BDBINSSFEFOLFN;
              BDBRATAPOFEFNPR = BDBINSSFEFOLFNPR;
              BDBRATAPO13FNPR = BDBINSS13FNPR;
            END
         ELSE
            BEGIN
              BDBRATAPOFNPR   = 0;
              BDBRATAPOFEFNPR = 0;
              BDBRATAPO13FNPR = 0;
            END

         BDSALFAMFNPR        = wsalfam;
         BDSALMATEMPFNPR     = wsalmatemp;
         BDINSSAPFNPR        = wainssap;
         BDINSS13APFNPR      = wainss13ap;
         BDVALREEMBOLSO      = wreemb;
         BDVALINDEVIDO       = wvindevido;
         BDVALINDEVIDOSF     = wvindevidosf;
         BDPERCRATCOL        = wpercrat;
         BDPERCDESCFPASCOL   = wpercdescfpas;

         if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and coalesce(wcatesoc, 0) in (731, 734)) then
            begin
              BDBINSS13APFNPR  = 0;
              BDBINSS13FNPR    = 0;
              BDBINSS13INDFNPR = 0;
              BDBINSSAPFNPR    = 0;
              BDBINSSFEFOLFNPR = 0;
              BDBINSSFNPR      = 0;
            end

         BDBASERAT = BDBINSSFNPR + BDBINSS13FNPR;

         select first 1 BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS
         where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :PRREF
         order by BDREFCOL DESC into :WCATEGORIAESOC;

         if (WCATEGORIAESOC IN (107, 108)) then
            begin
              BDBINSSFNPR = BDBINSSFNPR + BDBINSS13FNPR;
              BDBINSS13FNPR = 0;

              select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREF order by bdrefsm DESC INTO :WSALMIN;
              if (BDBINSSFNPR > WSALMIN * 1.5) then
                 begin
                   BDBINSSFNPR = BDBINSSFNPR - WSALMIN * 1.5;
                 end
              else
                 begin
                   BDBINSSFNPR = 0;
                 end
            end

         SUSPEND;

         IF (prref >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
            BEGIN
              BDGPSSEFIP     = 1;
              BDCODEMP       = wempatu;
              BDCODCOL       = wcolatu;
              BDREFFN        = prref;
              BDCODCENTROS   = NULL;
              BDCODTPCC      = NULL;
              BDBAVPREV      = wbavprev;

              wrefresc = NULL;
              SELECT BDREFRESCISAO FROM VRH_EMP_TRESCISAO WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu AND BDREFRESCISAO = :prref INTO :wrefresc;

              IF (wcontrcol = 0 AND wrefresc = prref) THEN
                 BEGIN
                   IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
                      BEGIN
                        BDINSSFNPR  = wainssap;
                        BDBINSSFNPR = wbinssap;
                      END
                   ELSE
                      BEGIN
                        IF ((wbinssap <> 0) OR (wtemvalor = 1)) THEN
                           BEGIN
                             IF (wbinssap < 0) THEN
                               wbinssap = 0;

                             BDBINSSFNPR = wbinssap;
                             wbinssap = wbinssap + wbaseinssfe;
                             wbmultvinc = 0;
                             wvmultvinc = 0;
                             SELECT BDBASEINSSNCOL, BDVALORINSSNCOL FROM VW_VRHF_EMP_TCOLCON_MVINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wbmultvinc, :wvmultvinc;
                             BDBINSSFNPR = BDBINSSFNPR + wbmultvinc;

                             SELECT COALESCE(BDCODINSS, 0) FROM VW_VRHF_BASE_TEMPVINC WHERE BDCODEMP = :wempatu INTO :wtabinss;
                             IF (wtabinss = 0) THEN
                                wtabinss = 1;
     
                             waliqinss = 0;
                             wsqlinss = 'select first 1 COALESCE(X.BDALIQINSS, 0) '||
                                        'from VRHF_TABELAS_TINSSFAIXAS X '||
                                        'join ('||
                                          'select BDCODINSS, MAX(BDREFINSS) BDREFINSS from VRHF_TABELAS_TINSSFAIXAS '||
                                          'where BDREFINSS <= '||prref||' and BDCODINSS = '||wtabinss||' '||
                                          'group by BDCODINSS '||
                                        ') Y on (Y.BDCODINSS = X.BDCODINSS and Y.BDREFINSS = X.BDREFINSS) '||
                                        'where X.BDFAIXAINSS >= '||wbinssap||' order by X.BDFAIXAINSS ';
     
                             EXECUTE STATEMENT wsqlinss INTO :waliqinss;
     
                             IF ((waliqinss = 0) OR (waliqinss IS NULL)) THEN
                                BEGIN
                                  wsqlinss = 'select MAX(X.BDFAIXAINSS), MAX(X.BDALIQINSS) '||
                                             'from VRHF_TABELAS_TINSSFAIXAS X '||
                                             'join ('||
                                               'select BDCODINSS, MAX(BDREFINSS) BDREFINSS from VRHF_TABELAS_TINSSFAIXAS '||
                                               'where BDREFINSS <= '||prref||' and BDCODINSS = '||wtabinss||' '||
                                               'group by BDCODINSS '||
                                             ') Y on (Y.BDCODINSS = X.BDCODINSS and Y.BDREFINSS = X.BDREFINSS) '||
                                             'group by X.BDCODINSS, X.BDREFINSS ';
     
                                  wfaixainss = 0;
                                  waliqinss  = 0;
                                  EXECUTE STATEMENT wsqlinss INTO :wfaixainss, :waliqinss;
     
                                  IF (wfaixainss IS NULL) THEN
                                     wfaixainss = 0;
     
                                  IF (waliqinss IS NULL) THEN
                                     waliqinss = 0;
     
                                  BDINSSFNPR = wfaixainss * waliqinss / 100;
                                END
                             ELSE
                                BDINSSFNPR = wbinssap * waliqinss / 100;
     
                             BDBINSSFNPR = BDBINSSFNPR - wbmultvinc;
                             BDINSSFNPR = CAST(BDINSSFNPR - 0.005 AS NUMERIC(15,2)); /* cortar */
                             BDINSSFNPR = BDINSSFNPR - winssfe - wvmultvinc;
                           END
                        ELSE
                           BEGIN
                             BDINSSFNPR = winss;
                             BDBINSSFNPR = wbaseinss;
                           END
                      END
                 END
              ELSE
                 BEGIN
                   BDINSSFNPR = winss;
                   BDBINSSFNPR = wbaseinss;
                 END

              BDINSSFEFOLFNPR     = winssfe;
              BDINSS13FNPR        = wainss13ap;
              BDBINSSFEFOLFNPR    = wbaseinssfe;
              BDBINSSAPFNPR       = wbinssap;
              BDBINSS13FNPR       = wbaseinss13;
              BDBINSS13APFNPR     = wbinss13ap;
              BDBINSS13INDFNPR    = wbinss13ap;
              BDPERCRATCOL        = wpercrat;
              BDPERCDESCFPASCOL   = wpercdescfpas;

              IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
                 BEGIN
                   BDBRATAPOFNPR   = BDBINSSFNPR;   -- + BDBINSSFEFOLFN;
                   BDBRATAPOFEFNPR = BDBINSSFEFOLFNPR;
                   BDBRATAPO13FNPR = BDBINSS13FNPR;
                 END
              ELSE
                 BEGIN
                   BDBRATAPOFNPR   = 0;
                   BDBRATAPOFEFNPR = 0;
                   BDBRATAPO13FNPR = 0;
                 END
     
              BDSALFAMFNPR     = wsalfam;
              BDSALMATEMPFNPR  = wsalmatemp;
              BDINSSAPFNPR     = wainssap;
              BDINSS13APFNPR   = wainss13ap;
              BDVALREEMBOLSO   = wreemb;
              BDVALINDEVIDO    = wvindevido;
              BDVALINDEVIDOSF  = wvindevidosf;

              IF (BDBINSSFEFOLFNPR > 0 AND BDINSSFNPR < 0) THEN
                 BDINSSFEFOLFNPR = bdinssfefolfnpr + bdinssfnpr;
              IF (BDBINSSFNPR < 0 AND BDBINSSFEFOLFNPR > 0) THEN
                 BDBINSSFEFOLFNPR = BDBINSSFEFOLFNPR + BDBINSSFNPR;

              if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and coalesce(wcatesoc, 0) in (731, 734)) then
                 begin
                   BDBINSS13APFNPR  = 0;
                   BDBINSS13FNPR    = 0;
                   BDBINSS13INDFNPR = 0;
                   BDBINSSAPFNPR    = 0;
                   BDBINSSFEFOLFNPR = 0;
                   BDBINSSFNPR      = 0;
                 end

              BDBASERAT = BDBINSSFNPR + BDBINSS13FNPR;

              select first 1 BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS
              where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :PRREF
              order by BDREFCOL DESC into :WCATEGORIAESOC;

              if (WCATEGORIAESOC IN (107, 108)) then
                 begin
                   BDBINSSFNPR = BDBINSSFNPR + BDBINSS13FNPR;
                   BDBINSS13FNPR = 0;

                   select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREF order by bdrefsm DESC INTO :WSALMIN;
                   if (BDBINSSFNPR > WSALMIN * 1.5) then
                      begin
                        BDBINSSFNPR = BDBINSSFNPR - WSALMIN * 1.5;
                      end
                   else
                      begin
                        BDBINSSFNPR = 0;
                      end
                 end

              SUSPEND;
            END

         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wsalfam     = 0;
         winss       = 0;
         winssfe     = 0;
         winss13     = 0;
         wbaseinss   = 0;
         wbaseinssfe = 0;
         wbaseinss13 = 0;
         wsalmatemp  = 0;
         wbinssap    = 0;
         wbinss13ap  = 0;
         wainssap    = 0;
         wainss13ap  = 0;
         wreemb      = 0;
         wvindevido  = 0;
         wvindevidosf = 0;
         wbavprev     = 0;
         wtemvalor = 0;
       END

    wainssap   = winssap;
    wainss13ap = winss13ap;
    wbaseinsscontratu = wbaseinsscontr;

    IF (prref >= 200903 AND prgpssefip = 1 AND wempap <> wcodemp) THEN
       BEGIN
         wsomaap = 0;

         SELECT SUM(BDSOMA) FROM (
           SELECT X.bdvalvfnpr BDSOMA FROM vrhf_emp_tverbafn_prev_resc X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp
           UNION ALL
           SELECT X.bdvalvftpr BDSOMA FROM vrhf_emp_tverbaft_prev_resc X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp
         )
         INTO :wsomaap;
         wempap = wcodemp;
       END

    -- INSS folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.0') THEN
       winss = winss + wvalor;

    -- INSS férias demonstradas na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.2') THEN
       winssfe = winssfe + wvalor;

    -- INSS 13o. rescisão descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;

    -- Base de INSS folha normal
    IF ((winssver = 1)) THEN
       BEGIN
         IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
            BEGIN
              IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
       END
    ELSE
    IF ((winssver = 0)) THEN  --não incide
       BEGIN
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
         ELSE
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                 wbaseinss13 = wbaseinss13 + wvalor;
              ELSE
              IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                 wbaseinss13 = wbaseinss13 - wvalor;
            END
       END

    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 2) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END
    ELSE
    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 1 AND SUBSTRING(wclaver FROM 1 FOR 5) >= '0.100' AND SUBSTRING(wclaver FROM 1 FOR 5) < '0.200') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END

    -- Base de INSS 13o. salário descontado na rescisão
    IF ((winssver = 3)) THEN
       BEGIN
         IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
         IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       END

    -- Valor de salário família
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '9.050' AND wtipocodver = 0) THEN
       wsalfam = wsalfam + wvalor;

    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.2') THEN  --  Valores indevidos da GPS
       wvindevido = wvindevido + wvalor;

    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.0') THEN  --  Valores SF indevidos da GPS
       wvindevidosf = wvindevidosf + wvalor;

    -- Base de salário maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005') OR
         (SUBSTRING(wclaver FROM 1 FOR 7) = '7.061.2') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.710'))) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END

    -- Base INSS sem o aviso prévio indenizado
    IF (SUBSTRING(wclaver FROM 1 FOR 7) <> '7.001.3') THEN
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
              ELSE
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinss13ap = wbinss13ap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinss13ap = wbinss13ap - wvalor;

                   wtemvalor = 1;
                 END
            END
       END
    ELSE
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 7, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
       END

    -- INSS sobre o aviso prévio indenizado do 13º salário
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '7.060') THEN
       BEGIN
         IF (winssver = 3) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbinss13ap = wbinss13ap + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbinss13ap = wbinss13ap - wvalor;
            END
       END

  END


  IF ((wempatu <> 0) AND (wcolatu <> 0)) THEN
     BEGIN
       wcodsind = NULL;
       wlimemp = NULL;
       wlimsind = NULL;
       SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
       IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
          BEGIN
            SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
          END
 
       IF (wlimsind IS NULL) THEN
          wlimsind = 0;             -- não possui liminar
 
       IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
          SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
 
       IF (wlimemp IS NULL) THEN
          wlimemp = 0;    -- não possui liminar

       wclatrib = null;
       wcoop    = null;
       select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
       into :wclatrib, :wcoop;
       wclatrib = coalesce(wclatrib, 0);
       wcoop    = coalesce(wcoop, 0);

       BDGPSSEFIP       = 0;
       BDCODEMP         = wempatu;
       BDCODCOL         = wcolatu;
       BDREFFN          = prref;
       BDCODCENTROS     = NULL;
       BDCODTPCC        = NULL;
       BDINSSFNPR       = winss;
       BDINSSFEFOLFNPR  = winssfe;
       BDINSS13FNPR     = winss13;
       BDBINSSFEFOLFNPR = wbaseinssfe;
       BDBINSSAPFNPR    = wbinssap;
       BDBINSS13APFNPR  = wbinss13ap;
       BDINSSAPFNPR     = wainssap;
       BDINSS13APFNPR   = wainss13ap;
       BDBAVPREV        = 0;

       IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
          BDBINSSFNPR = wbinssap;
       ELSE
          BDBINSSFNPR = wbaseinss;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13FNPR = wbaseinss13 - wbinss13ap;
       ELSE
          BDBINSS13FNPR = wbaseinss13;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13INDFNPR = 0;
       ELSE
          BDBINSS13INDFNPR = wbinss13ap;

       IF (BDBINSSFEFOLFNPR > 0 AND BDINSSFNPR < 0) THEN
          BDINSSFEFOLFNPR = bdinssfefolfnpr + bdinssfnpr;
       IF (BDBINSSFNPR < 0 AND BDBINSSFEFOLFNPR > 0) THEN
          BDBINSSFEFOLFNPR = BDBINSSFEFOLFNPR + BDBINSSFNPR;

       wpercrat = 0;
       wpercdescfpas = 0;
       wcontrcol = NULL;
       wcatesoc = null;
       SELECT first 1 BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL, BDCATEGORIAESOCIAL
       FROM VRHF_EMP_TCOLCON_FGTSGPS
       WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prref
       order by BDREFCOL DESC
       INTO :wpercrat, :wpercdescfpas, :wcontrcol, wcatesoc;

       IF (wcontrcol IS NULL) THEN
          wcontrcol = 0;
 
       IF (wcontrcol = 1) THEN
          bdbinssfnpr = wbaseinsscontratu;

       IF (bdbinssfnpr < 0) THEN
          bdbinssfnpr = 0;

       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BEGIN
            BDBRATAPOFNPR   = wbaseinss;   -- + wbaseinssfe;
            BDBRATAPOFEFNPR = wbaseinssfe;
            BDBRATAPO13FNPR = wbaseinss13;
          END
       ELSE
          BEGIN
            BDBRATAPOFNPR   = 0;
            BDBRATAPOFEFNPR = 0;
            BDBRATAPO13FNPR = 0;
          END

       BDSALFAMFNPR        = wsalfam;
       BDSALMATEMPFNPR     = wsalmatemp;
       BDVALREEMBOLSO      = wreemb;
       BDVALINDEVIDO       = wvindevido;
       BDPERCRATCOL        = wpercrat;
       BDPERCDESCFPASCOL   = wpercdescfpas;

       if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and coalesce(wcatesoc, 0) in (731, 734)) then
          begin
            BDBINSS13APFNPR  = 0;
            BDBINSS13FNPR    = 0;
            BDBINSS13INDFNPR = 0;
            BDBINSSAPFNPR    = 0;
            BDBINSSFEFOLFNPR = 0;
            BDBINSSFNPR      = 0;
          end

       BDBASERAT = BDBINSSFNPR + BDBINSS13FNPR;

       select first 1 BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS
       where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :PRREF
       order by BDREFCOL DESC into :WCATEGORIAESOC;

       if (WCATEGORIAESOC IN (107, 108)) then
          begin
            BDBINSSFNPR = BDBINSSFNPR + BDBINSS13FNPR;
            BDBINSS13FNPR = 0;

            select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREF order by bdrefsm DESC INTO :WSALMIN;
            if (BDBINSSFNPR > WSALMIN * 1.5) then
               begin
                 BDBINSSFNPR = BDBINSSFNPR - WSALMIN * 1.5;
               end
            else
               begin
                 BDBINSSFNPR = 0;
               end
          end

       SUSPEND;

       IF (prRef >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
          BEGIN
            BDGPSSEFIP     = 1;
            BDCODEMP       = wempatu;
            BDCODCOL       = wcolatu;
            BDREFFN        = prref;
            BDCODCENTROS   = NULL;
            BDCODTPCC      = NULL;
            BDBAVPREV      = wbavprev;

            wrefresc = NULL;
            SELECT BDREFRESCISAO FROM VRH_EMP_TRESCISAO WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu AND BDREFRESCISAO = :prref INTO :wrefresc;
            IF (wcontrcol = 0 AND wrefresc = prref) THEN
               BEGIN
                 IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
                    BEGIN
                      BDINSSFNPR  = wainssap;
                      BDBINSSFNPR = wbinssap;
                    END
                 ELSE
                    BEGIN
                      IF ((wbinssap <> 0) OR (wtemvalor = 1)) THEN
                         BEGIN
                           IF (wbinssap < 0) THEN
                             wbinssap = 0;

                           BDBINSSFNPR = wbinssap;
                           wbinssap = wbinssap + wbaseinssfe;
     
                           wbmultvinc = 0;
                           wvmultvinc = 0;
                           SELECT BDBASEINSSNCOL, BDVALORINSSNCOL FROM VW_VRHF_EMP_TCOLCON_MVINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wbmultvinc, :wvmultvinc;
                           BDBINSSFNPR = BDBINSSFNPR + wbmultvinc;

                           SELECT COALESCE(BDCODINSS, 0) FROM VW_VRHF_BASE_TEMPVINC WHERE BDCODEMP = :wempatu INTO :wtabinss;
                           IF (wtabinss = 0) THEN
                              wtabinss = 1;
     
                           waliqinss = 0;
                           wsqlinss = 'select first 1 COALESCE(X.BDALIQINSS, 0) '||
                                      'from VRHF_TABELAS_TINSSFAIXAS X '||
                                      'join ('||
                                        'select BDCODINSS, MAX(BDREFINSS) BDREFINSS from VRHF_TABELAS_TINSSFAIXAS '||
                                        'where BDREFINSS <= '||prref||' and BDCODINSS = '||wtabinss||' '||
                                        'group by BDCODINSS '||
                                      ') Y on (Y.BDCODINSS = X.BDCODINSS and Y.BDREFINSS = X.BDREFINSS) '||
                                      'where X.BDFAIXAINSS >= '||wbinssap||' order by X.BDFAIXAINSS ';
     
                           EXECUTE STATEMENT wsqlinss INTO :waliqinss;
     
                           IF ((waliqinss = 0) OR (waliqinss IS NULL)) THEN
                              BEGIN
                                wsqlinss = 'select MAX(X.BDFAIXAINSS), MAX(X.BDALIQINSS) '||
                                           'from VRHF_TABELAS_TINSSFAIXAS X '||
                                           'join ('||
                                             'select BDCODINSS, MAX(BDREFINSS) BDREFINSS from VRHF_TABELAS_TINSSFAIXAS '||
                                             'where BDREFINSS <= '||prref||' and BDCODINSS = '||wtabinss||' '||
                                             'group by BDCODINSS '||
                                           ') Y on (Y.BDCODINSS = X.BDCODINSS and Y.BDREFINSS = X.BDREFINSS) '||
                                           'group by X.BDCODINSS, X.BDREFINSS ';
     
                                wfaixainss = 0;
                                waliqinss  = 0;
                                EXECUTE STATEMENT wsqlinss INTO :wfaixainss, :waliqinss;
     
                                IF (wfaixainss IS NULL) THEN
                                   wfaixainss = 0;
     
                                IF (waliqinss IS NULL) THEN
                                   waliqinss = 0;
     
                                BDINSSFNPR = wfaixainss * waliqinss / 100;
                              END
                           ELSE
                              BDINSSFNPR = wbinssap * waliqinss / 100;
     
                           BDBINSSFNPR = BDBINSSFNPR - wbmultvinc;
                           BDINSSFNPR = CAST(BDINSSFNPR - 0.005 AS NUMERIC(15,2)); /* cortar */
                           BDINSSFNPR = BDINSSFNPR - winssfe - wvmultvinc;
     
                         END
                      ELSE
                         BEGIN
                           BDINSSFNPR = winss;
                           BDBINSSFNPR = wbaseinss;
                         END
                    END
               END
            ELSE
               BEGIN
                 BDINSSFNPR = winss;
                 BDBINSSFNPR = wbaseinss;
               END

            BDINSSFEFOLFNPR     = winssfe;
            BDINSS13FNPR        = wainss13ap;
            BDBINSSFEFOLFNPR    = wbaseinssfe;
            BDBINSS13FNPR       = wbaseinss13;
            BDBINSSAPFNPR       = wbinssap;
            BDBINSS13APFNPR     = wbinss13ap;
            BDBINSS13INDFNPR    = wbinss13ap;
            BDINSSAPFNPR        = wainssap;
            BDINSS13APFNPR      = wainss13ap;
            BDPERCRATCOL        = wpercrat;
            BDPERCDESCFPASCOL   = wpercdescfpas;
     
            IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
               BEGIN
                 BDBRATAPOFNPR   = BDBINSSFNPR;    -- + BDBINSSFEFOLFN;
                 BDBRATAPOFEFNPR = BDBINSSFEFOLFNPR;
                 BDBRATAPO13FNPR = BDBINSS13FNPR;
               END
            ELSE
               BEGIN
                 BDBRATAPOFNPR   = 0;
                 BDBRATAPOFEFNPR = 0;
                 BDBRATAPO13FNPR = 0;
               END
     
            BDSALFAMFNPR     = wsalfam;
            BDSALMATEMPFNPR  = wsalmatemp;

            BDVALREEMBOLSO = wreemb;
            BDVALINDEVIDO  = wvindevido;
            IF (BDBINSSFEFOLFNPR > 0 AND BDINSSFNPR < 0) THEN
               BDINSSFEFOLFNPR = bdinssfefolfnpr + bdinssfnpr;
            IF (BDBINSSFNPR < 0 AND BDBINSSFEFOLFNPR > 0) THEN
               BDBINSSFEFOLFNPR = BDBINSSFEFOLFNPR + BDBINSSFNPR;

            if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and coalesce(wcatesoc, 0) in (731, 734)) then
               begin
                 BDBINSS13APFNPR  = 0;
                 BDBINSS13FNPR    = 0;
                 BDBINSS13INDFNPR = 0;
                 BDBINSSAPFNPR    = 0;
                 BDBINSSFEFOLFNPR = 0;
                 BDBINSSFNPR      = 0;
               end

            BDBASERAT = BDBINSSFNPR + BDBINSS13FNPR;

            select first 1 BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS
            where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :PRREF
            order by BDREFCOL DESC into :WCATEGORIAESOC;

            if (WCATEGORIAESOC IN (107, 108)) then
               begin
                 BDBINSSFNPR = BDBINSSFNPR + BDBINSS13FNPR;
                 BDBINSS13FNPR = 0;

                 select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREF order by bdrefsm DESC INTO :WSALMIN;
                 if (BDBINSSFNPR > WSALMIN * 1.5) then
                    begin
                      BDBINSSFNPR = BDBINSSFNPR - WSALMIN * 1.5;
                    end
                 else
                    begin
                      BDBINSSFNPR = 0;
                    end
               end

            SUSPEND;
          END
     END
END^

/* Restore proc. body: SP_VRHF_DADOS_INSS_FT_PREV_RESC */
create or alter procedure SP_VRHF_DADOS_INSS_FT_PREV_RESC (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRGPSSEFIP smallint = 0,
    PRFILIAIS varchar(15000) = null)
returns (
    BDGPSSEFIP integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDINSSFTPR numeric(18,6),
    BDINSSFEFOLFTPR numeric(18,6),
    BDINSS13FTPR numeric(18,6),
    BDBINSSFTPR numeric(18,6),
    BDBINSSFEFOLFTPR numeric(18,6),
    BDBINSS13FTPR numeric(18,6),
    BDBRATAPOFTPR numeric(18,6),
    BDBRATAPOFEFTPR numeric(18,6),
    BDBRATAPO13FTPR numeric(18,6),
    BDSALFAMFTPR numeric(18,6),
    BDSALMATEMPFTPR numeric(18,6),
    BDBINSSAPFTPR numeric(18,6),
    BDBINSS13INDFTPR numeric(18,6),
    BDBINSS13APFTPR numeric(18,6),
    BDINSSAPFTPR numeric(18,6),
    BDINSS13APFTPR numeric(18,6),
    BDVALREEMBOLSO numeric(18,6),
    BDVALINDEVIDO numeric(18,6),
    BDVALINDEVIDOSF numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDPERCRATCOL numeric(18,6),
    BDPERCDESCFPASCOL numeric(18,6),
    BDBASERAT numeric(18,2))
as
declare variable WCCNULL integer;
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(32000);
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WCENTROS integer;
declare variable WCENTROSATU integer;
declare variable WCC integer;
declare variable WCCATU integer;
declare variable WCLAVER varchar(20);
declare variable WTIPOCODVER integer;
declare variable WINSSVER integer;
declare variable WBASEGPSVER varchar(5);
declare variable WREEMBGPSVER varchar(5);
declare variable WVALOR numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WINSSFE numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WBASEINSS numeric(18,6);
declare variable WBASEINSSFE numeric(18,6);
declare variable WBASEINSS13 numeric(18,6);
declare variable WSALFAM numeric(18,6);
declare variable WSALMATEMP numeric(18,6);
declare variable WPERCRAT numeric(18,6);
declare variable WBINSSAP numeric(18,6);
declare variable WBINSS13AP numeric(18,6);
declare variable WINSSAP numeric(18,6);
declare variable WINSS13AP numeric(18,6);
declare variable WAINSSAP numeric(18,6);
declare variable WAINSS13AP numeric(18,6);
declare variable WEMPAP integer;
declare variable WSOMAAP numeric(18,6);
declare variable WCODSIND integer;
declare variable WLIMSIND integer;
declare variable WLIMEMP integer;
declare variable WREEMB numeric(18,6);
declare variable WVINDEVIDO numeric(18,6);
declare variable WVINDEVIDOSF numeric(18,6);
declare variable WBAVPREV numeric(18,6);
declare variable WTEMVALOR smallint;
declare variable WPERCDEDFPAS numeric(18,6);
declare variable WSINDATU integer;
declare variable WORDEM integer;
declare variable WORDEMATU integer;
declare variable WCONTRCOL integer;
declare variable WBASEINSSCONTR numeric(18,6);
declare variable WBASEINSSCONTRATU numeric(18,6);
declare variable WCLATRIB integer;
declare variable WCOOP integer;
declare variable WCATESOC integer;
declare variable WSALMIN numeric(15,2);
declare variable WCATEGORIAESOC integer;
BEGIN
  wsql = 'select FN.BDCODEMP, FN.BDCODCOL, FN.BDVALVFTPR, FTPR.BDINSSAPFTPR, FTPR.BDINSS13APFTPR, VERREF.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDINSSVER, '||
                'VERREF.BDBASEGPSVER, VERREF.BDREEMBGPSVER, PREP.BDORDEM, PREP.BDCODCENTRO, PREP.BDCODTPCC, FTPR.BDBINSSFTPR from (';

  IF (prfiliais IS NOT NULL AND prfiliais <> '') THEN
     BEGIN
       wsql = wsql||'select BDCODEMP from TEMPRESAS where ((';

       IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
         wsql = wsql||prcodemp||') or (';

       wsql = wsql||prfiliais||'))) FILIAIS ';
       wsql = wsql||'join VRHF_EMP_TVERBAFT_PREV_RESC FN on (FN.BDCODEMP = FILIAIS.BDCODEMP';

      IF (prref IS NOT NULL AND prref <> 0) THEN
         wsql = wsql||' and RESC.BDREFRESCISAOPREV  = '||prref;

      wsql = wsql||') ';
     END
  ELSE
    BEGIN
      wsql = wsql||'select PREV.* from VRHF_EMP_TVERBAFT_PREV_RESC PREV ';
      wsql = wsql||'join VRH_EMP_TRESCISAO_PREVIA RESC on RESC.BDCODEMP = PREV.BDCODEMP and RESC.BDCODCOL = PREV.BDCODCOL ';
      wwhere  = '';
    
      IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
        wwhere = wwhere||replace(upper(prcodemp), 'BDCODEMP', 'PREV.BDCODEMP');

      IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';

           wwhere = wwhere||replace(upper(prcodcol), 'BDCODCOL', 'PREV.BDCODCOL');
         END
    
      IF (prref IS NOT NULL AND prref <> 0) THEN
         BEGIN
           IF (wwhere <> '') THEN
              wwhere = wwhere||' and ';
    
           wwhere = wwhere||'RESC.BDREFRESCISAOPREV = '||prref||' ';
         END
    
    
      IF (wwhere <> '') THEN
         wwhere = ' where '||wwhere;
    
      wsql = wsql||wwhere;
    
      wsql = wsql||') FN ';
    END

  wsql = wsql||'join VRHF_EMP_TPREPFN prep on (FN.bdcodemp = prep.bdcodemp and FN.bdcodcol = prep.bdcodcol and FN.bdordem = prep.bdordem) ';
  wsql = wsql||'join VRHF_EMP_TFOLTOM_PREV_RESC FTPR on (FTPR.BDCODEMP = FN.BDCODEMP and FTPR.BDCODCOL = FN.BDCODCOL and FTPR.BDORDEM = FN.BDORDEM) ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wsql = wsql||'left outer join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';
  ELSE
     wsql = wsql||'join VW_VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) ';
  wsql = wsql||'order by FN.BDCODEMP,FN.BDCODCOL,PREP.BDCODCENTRO,PREP.BDCODTPCC ';

  wempatu     = 0;
  wcolatu     = 0;
  wordematu   = 0;
  wcentrosatu = 0;
  wccatu      = 0;
  wsalfam     = 0;
  winss       = 0;
  winssfe     = 0;
  winss13     = 0;
  wbaseinss   = 0;
  wbaseinssfe = 0;
  wbaseinss13 = 0;
  wsalmatemp  = 0;
  wbinssap    = 0;
  wbinss13ap  = 0;
  wainssap    = 0;
  wainss13ap  = 0;
  wempap      = 0;
  wsomaap     = 0;
  wreemb      = 0;
  wvindevido  = 0;
  wvindevidosf = 0;
  wbavprev     = 0;
  wtemvalor = 0;
  wsindatu = 0;
  wcodsind = -1;
  wbaseinsscontratu = 0;
  wclatrib = null;
  wcoop    = null;
  wcatesoc = null;

  EXECUTE PROCEDURE sp_seta_competencia(prref);

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wcodcol, :wvalor, :winssap, :winss13ap, :wclaver, :wtipocodver, :winssver, :wbasegpsver, :wreembgpsver,
                                  :wordem, :wcentros, :wcc, :wbaseinsscontr DO
  BEGIN
    IF (wempatu = 0) THEN
      BEGIN
        wempatu = wcodemp;
        wlimemp = NULL;
        SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
        IF (wlimemp IS NULL) THEN
           wlimemp = 0;    -- não possui liminar

        select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
        into :wclatrib, :wcoop;
        wclatrib = coalesce(wclatrib, 0);
        wcoop    = coalesce(wcoop, 0);
      END

    IF (wcolatu = 0) THEN
       wcolatu = wcodcol;

    IF (wcentrosatu = 0) THEN
       wcentrosatu = wcentros;

    IF (wccatu = 0) THEN
       wccatu = wcc;

    IF (wordematu = 0) THEN
       wordematu = wordem;

    wCCNull = 0;
    IF ((wccatu IS NULL) AND (wcc IS NOT NULL)) THEN
       wccnull = 1;
    IF ((wccatu IS NOT NULL) AND (wcc IS NULL)) THEN
       wccnull = 1;

    /*
      Retorna bases de INSS
    */
    IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wcentrosatu <> wcentros) OR (wccatu <> wcc) OR (wCCNull = 1)) THEN
       BEGIN
         --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a versão com a alteração abaixo corretamente.
         wcodsind = NULL;

         SELECT BDCODSINTRAB FROM VW_VRH_EMP_TCOL_VINC WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
         IF (wsindatu <> wcodsind) THEN
           BEGIN
             wlimsind = NULL;
             wsindatu = wcodsind;
             IF (wsindatu IS NOT NULL AND wsindatu <> 0) THEN
               SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wsindatu INTO :wlimsind;
             IF (wlimsind IS NULL) THEN
                wlimsind = 0;             -- não possui liminar
           END

         IF (wempatu <> wcodemp) THEN
           BEGIN
             wlimemp = NULL;
             SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;
             IF (wlimemp IS NULL) THEN
                wlimemp = 0;    -- não possui liminar

             wclatrib = null;
             wcoop    = null;
             select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
             into :wclatrib, :wcoop;
             wclatrib = coalesce(wclatrib, 0);
             wcoop    = coalesce(wcoop, 0);
           END

         BDGPSSEFIP       = 0;
         BDCODEMP         = wempatu;
         BDCODCOL         = wcolatu;
         BDREFFN          = prref;
         BDORDEM          = wordematu;
         BDCODCENTRO      = wcentrosatu;
         BDCODTPCC        = wccatu;
         BDINSSFTPR       = winss;
         BDINSSFEFOLFTPR  = winssfe;
         BDINSS13FTPR     = winss13;
         BDBINSSFEFOLFTPR = wbaseinssfe;
         BDBINSSAPFTPR    = wbinssap;
         BDBINSS13INDFTPR = wbinss13ap;
         BDBINSS13APFTPR  = wbinss13ap;
         BDINSSAPFTPR     = wainssap;
         BDINSS13APFTPR   = wainss13ap;
         BDBAVPREV      = 0;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSS13INDFTPR = 0;
         ELSE
            BDBINSS13INDFTPR = wbinss13ap;

         IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
            BDBINSSFTPR = wbinssap;
         ELSE
            BDBINSSFTPR = wbaseinss;

         IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
            BDBINSS13FTPR = wbaseinss13 - wbinss13ap;
         ELSE
            BDBINSS13FTPR = wbaseinss13;


         IF (BDBINSSFEFOLFTPR > 0 AND BDINSSFTPR < 0) THEN
            BDINSSFEFOLFTPR = bdinssfefolftpr + bdinssftpr;

         IF (BDBINSSFTPR < 0 AND BDBINSSFEFOLFTPR > 0) THEN
            BDBINSSFEFOLFTPR = BDBINSSFEFOLFTPR + BDBINSSFTPR;

         wpercrat = 0;
         wpercdedfpas = 0;
         wcatesoc = null;
         SELECT first 1 BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL, BDCATEGORIAESOCIAL
         FROM VRHF_EMP_TCOLCON_FGTSGPS
         WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prref
         order by BDREFCOL DESC
         INTO :wpercrat, :wpercdedfpas, :wcontrcol, :wcatesoc;

         IF (wcontrcol = 1) THEN
            BDBINSSFTPR = wbaseinsscontratu;

         IF (BDBINSSFTPR < 0) THEN
            BDBINSSFTPR = 0;

         IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
            BEGIN
              BDBRATAPOFTPR   = BDBINSSFTPR;   -- + BDBINSSFEFOLFN;
              BDBRATAPOFEFTPR = BDBINSSFEFOLFTPR;
              BDBRATAPO13FTPR = BDBINSS13FTPR;
            END
         ELSE
            BEGIN
              BDBRATAPOFTPR   = 0;
              BDBRATAPOFEFTPR = 0;
              BDBRATAPO13FTPR = 0;
            END

         BDSALFAMFTPR        = wsalfam;
         BDSALMATEMPFTPR     = wsalmatemp;
         BDVALREEMBOLSO      = wreemb;
         BDVALINDEVIDO       = wvindevido;
         BDVALINDEVIDOSF     = wvindevidosf;
         BDPERCRATCOL        = wpercrat;
         BDPERCDESCFPASCOL   = wpercdedfpas;

         if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and coalesce(wcatesoc, 0) in (731, 734)) then
            begin
              BDBINSS13APFTPR  = 0;
              BDBINSS13FTPR    = 0;
              BDBINSS13INDFTPR = 0;
              BDBINSSAPFTPR    = 0;
              BDBINSSFEFOLFTPR = 0;
              BDBINSSFTPR      = 0;
            end

         BDBASERAT = BDBINSSFTPR + BDBINSS13FTPR;

         select first 1 BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS
         where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :PRREF
         order by BDREFCOL DESC into :WCATEGORIAESOC;

         if (WCATEGORIAESOC IN (107, 108)) then
            begin
              BDBINSSFTPR = BDBINSSFTPR + BDBINSS13FTPR;
              BDBINSS13FTPR = 0;

              select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREF order by bdrefsm DESC INTO :WSALMIN;
              if (BDBINSSFTPR > WSALMIN * 1.5) then
                 begin
                   BDBINSSFTPR = BDBINSSFTPR - WSALMIN * 1.5;
                 end
              else
                 begin
                   BDBINSSFTPR = 0;
                 end
            end

         SUSPEND;

         IF (prref >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
            BEGIN
              BDGPSSEFIP       = 1;
              BDCODEMP         = wempatu;
              BDCODCOL         = wcolatu;
              BDREFFN          = prref;
              BDORDEM          = wordematu;
              BDCODCENTRO      = wcentrosatu;
              BDCODTPCC        = wccatu;
              BDINSSFTPR       = wainssap;
              BDINSSFEFOLFTPR  = winssfe;
              BDINSS13FTPR     = wainss13ap;
              BDBAVPREV        = wbavprev;

              --if (wainssap <> 0) then
              IF ((wbavprev <> 0) OR (wtemvalor = 1)) THEN
                 BEGIN
                   IF (wbaseinssfe + wbinssap < 0) THEN
                      BEGIN
                   IF (wbinssap < 0) THEN
                     wbinssap = 0;
                      END

                   BDINSSFTPR  = wainssap;
                   BDBINSSFTPR = wbinssap;
                 END
              ELSE
                 BEGIN
                   BDINSSFTPR  = winss;
                   BDBINSSFTPR = wbaseinss;
                 END

              BDBINSSFEFOLFTPR    = wbaseinssfe;
              BDBINSS13FTPR       = wbaseinss13;
              BDBINSS13APFTPR     = wbinss13ap;
              BDINSSAPFTPR        = wainssap;
              BDINSS13APFTPR      = wainss13ap;
              BDPERCRATCOL        = wpercrat;
              BDPERCDESCFPASCOL   = wpercdedfpas;

              IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
                 BEGIN
                   BDBRATAPOFTPR   = BDBINSSAPFTPR;   -- + BDBINSSFEFOLFN;
                   BDBRATAPOFEFTPR = BDBINSSFEFOLFTPR;
                   BDBRATAPO13FTPR = BDBINSS13FTPR;
                 END
              ELSE
                 BEGIN
                   BDBRATAPOFTPR   = 0;
                   BDBRATAPOFEFTPR = 0;
                   BDBRATAPO13FTPR = 0;
                 END
     
              BDSALFAMFTPR     = wsalfam;
              BDSALMATEMPFTPR  = wsalmatemp;

              BDVALREEMBOLSO = wreemb;
              BDVALINDEVIDO  = wvindevido;
              BDVALINDEVIDOSF = wvindevidosf;

              IF (BDBINSSFEFOLFTPR > 0 AND BDINSSFTPR < 0) THEN
                 BDINSSFEFOLFTPR = bdinssfefolftpr + bdinssftpr;

              IF (BDBINSSFTPR < 0 AND BDBINSSFEFOLFTPR > 0) THEN
                 BDBINSSFEFOLFTPR = BDBINSSFEFOLFTPR + BDBINSSFTPR;

              if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and coalesce(wcatesoc, 0) in (731, 734)) then
                 begin
                   BDBINSS13APFTPR  = 0;
                   BDBINSS13FTPR    = 0;
                   BDBINSS13INDFTPR = 0;
                   BDBINSSAPFTPR    = 0;
                   BDBINSSFEFOLFTPR = 0;
                   BDBINSSFTPR      = 0;
                 end

              BDBASERAT = BDBINSSFTPR + BDBINSS13FTPR;

              select first 1 BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS
              where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :PRREF
              order by BDREFCOL DESC into :WCATEGORIAESOC;

              if (WCATEGORIAESOC IN (107, 108)) then
                 begin
                   BDBINSSFTPR = BDBINSSFTPR + BDBINSS13FTPR;
                   BDBINSS13FTPR = 0;

                   select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREF order by bdrefsm DESC INTO :WSALMIN;
                   if (BDBINSSFTPR > WSALMIN * 1.5) then
                      begin
                        BDBINSSFTPR = BDBINSSFTPR - WSALMIN * 1.5;
                      end
                   else
                      begin
                        BDBINSSFTPR = 0;
                      end
                 end

              SUSPEND;
            END

         wempatu     = wcodemp;
         wcolatu     = wcodcol;
         wordematu   = wordem;
         wcentrosatu = wcentros;
         wccatu      = wcc;
         wsalfam     = 0;
         winss       = 0;
         winssfe     = 0;
         winss13     = 0;
         wbaseinss   = 0;
         wbaseinssfe = 0;
         wbaseinss13 = 0;
         wsalmatemp  = 0;
         wbinssap    = 0;
         wbinss13ap  = 0;
         wainssap    = 0;
         wainss13ap  = 0;
         wreemb      = 0;
         wvindevido  = 0;
         wvindevidosf = 0;
         wbavprev     = 0;
         wtemvalor = 0;
       END

    wainssap   = winssap;
    wainss13ap = winss13ap;
    wbaseinsscontratu = wbaseinsscontr;

    IF (prref >= 200903 AND prgpssefip = 1 AND wempap <> wcodemp) THEN
       BEGIN
         wsomaap = 0;
         SELECT SUM(BDSOMA) FROM (
           SELECT X.bdvalvfnpr BDSOMA FROM vrhf_emp_tverbafn_prev_resc X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp
           UNION ALL
           SELECT X.bdvalvftpr BDSOMA FROM vrhf_emp_tverbaft_prev_resc X
           JOIN VW_TVERBAS_REF Y ON (Y.bdcodver = X.bdcodver AND Y.bdclaver LIKE '7.001.3%' AND Y.bdinssver <> 0)
           WHERE X.bdcodemp = :wcodemp
         )
         INTO :wsomaap;
         wempap = wcodemp;
       END

    -- INSS folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.0') THEN
       winss = winss + wvalor;

    -- INSS férias demonstradas na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.2') THEN
       winssfe = winssfe + wvalor;

    -- INSS 13o. rescisão descontado na folha normal
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.0.7') THEN
       winss13 = winss13 + wvalor;

    -- Base de INSS folha normal
    IF ((winssver = 1)) THEN
       BEGIN
         IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
            BEGIN
              IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
       END
    ELSE
    IF ((winssver = 0)) THEN  --não incide
       BEGIN
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbaseinss = wbaseinss + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbaseinss = wbaseinss - wvalor;
            END
         ELSE
         IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
            BEGIN
              IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                 wbaseinss13 = wbaseinss13 + wvalor;
              ELSE
              IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                 wbaseinss13 = wbaseinss13 - wvalor;
            END
       END

    -- Base de INSS férias demonstrativo na folha
    IF (winssver = 2) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END
    ELSE
    IF (winssver = 1 AND SUBSTRING(wclaver FROM 1 FOR 5) >= '0.100' AND SUBSTRING(wclaver FROM 1 FOR 5) < '0.200') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- Provento
            wbaseinssfe = wbaseinssfe + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- Desconto
            wbaseinssfe = wbaseinssfe - wvalor;
       END

    -- Base de INSS 13o. salário descontado na rescisão
    IF ((winssver = 3)) THEN
       BEGIN
         IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
            wbaseinss13 = wbaseinss13 + wvalor;
         ELSE
         IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
            wbaseinss13 = wbaseinss13 - wvalor;
       END

    -- Valor de salário família
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '9.050') THEN
       wsalfam = wsalfam + wvalor;

    -- Valor indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.2') THEN
       wvindevido = wvindevido + wvalor;

    -- Valor SF indevido GPS
    IF (SUBSTRING(wclaver FROM 1 FOR 9) = '9.060.0.0') THEN
       wvindevidosf = wvindevidosf + wvalor;

    -- Base de salário maternidade
    IF ((UPPER(wreembgpsver) = 'TRUE') AND
        ((SUBSTRING(wclaver FROM 1 FOR 5) = '4.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '5.010') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '6.010') OR
         (SUBSTRING(wclaver FROM 1 FOR 5) = '7.070') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.071') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '8.005') OR
         (SUBSTRING(wclaver FROM 1 FOR 7) = '7.061.2') OR (SUBSTRING(wclaver FROM 1 FOR 5) = '7.710'))) THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wsalmatemp = wsalmatemp + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wsalmatemp = wsalmatemp - wvalor;
       END
    ELSE
    IF (UPPER(wreembgpsver) = 'TRUE') THEN
       BEGIN
         IF (wtipocodver = 0) THEN  -- provento
            wreemb = wreemb + wvalor;
         ELSE
         IF (wtipocodver = 1) THEN  -- desconto
            wreemb = wreemb - wvalor;
       END

    -- Base de INSS folha normal sem o aviso prévio indenizado
    IF (SUBSTRING(wclaver FROM 1 FOR 7) <> '7.001.3') THEN
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinssap = wbinssap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinssap = wbinssap - wvalor;

                   wtemvalor = 1;
                 END
              ELSE
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) = 7 AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbinss13ap = wbinss13ap + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbinss13ap = wbinss13ap - wvalor;

                   wtemvalor = 1;
                 END
            END
       END
    ELSE
       BEGIN
         IF ((winssver = 1)) THEN
            BEGIN
              IF ((SUBSTRING(wclaver FROM 1 FOR 5) < '0.100') OR (SUBSTRING(wclaver FROM 1 FOR 5) >= '0.200')) THEN
                 BEGIN
                   IF ((wtipocodver = 0) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF ((wtipocodver = 1) AND (UPPER(wbasegpsver) = 'TRUE')) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
         ELSE
         IF ((winssver = 0)) THEN  --não incide
            BEGIN
              IF (CAST(SUBSTRING(wclaver FROM 1 FOR 1) AS INTEGER) IN (0, 7, 8) AND UPPER(wbasegpsver) = 'TRUE')  THEN
                 BEGIN
                   IF (wtipocodver = 0) THEN  -- Provento
                      wbavprev = wbavprev + wvalor;
                   ELSE
                   IF (wtipocodver = 1) THEN  -- Desconto
                      wbavprev = wbavprev - wvalor;
                 END
            END
       END

    -- INSS sobre o aviso prévio indenizado do 13º salário
    IF (SUBSTRING(wclaver FROM 1 FOR 5) = '7.060') THEN
       BEGIN
         IF (winssver = 3) THEN
            BEGIN
              IF (wtipocodver = 0) THEN  -- Provento
                 wbinss13ap = wbinss13ap + wvalor;
              ELSE
              IF (wtipocodver = 1) THEN  -- Desconto
                 wbinss13ap = wbinss13ap - wvalor;
            END
       END

  END


  IF ((wempatu <> 0) AND (wcolatu <> 0) AND ((wccatu <> 0) OR (wccatu IS NULL))) THEN
     BEGIN
       wcodsind = NULL;
       wlimemp = NULL;
       wlimsind = NULL;
       SELECT BDCODSINTRAB FROM vw_vrh_emp_tcol_vinc WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu INTO :wcodsind;
       IF (wcodsind IS NOT NULL AND wcodsind <> 0) THEN
          BEGIN
            SELECT BDLIMINARAVPREVST FROM vw_vrh_base_tsindtref WHERE BDCODSINTRAB = :wcodsind INTO :wlimsind;
          END

       IF (wlimsind IS NULL) THEN
          wlimsind = 0;             -- não possui liminar

       IF (wlimsind = 1) THEN   -- conforme cadastro de empresa
          SELECT BDLIMINARAVPREVEMP FROM vw_vrhf_base_tempcalc WHERE BDCODEMP = :wempatu INTO :wlimemp;

       IF (wlimemp IS NULL) THEN
          wlimemp = 0;    -- não possui liminar

       wclatrib = null;
       wcoop    = null;
       select first 1 BDCODCLATRI, BDESCOOPERATIVA from VRHF_BASE_TEMPESOCIAL where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC
       into :wclatrib, :wcoop;
       wclatrib = coalesce(wclatrib, 0);
       wcoop    = coalesce(wcoop, 0);

       BDGPSSEFIP       = 0;
       BDCODEMP         = wempatu;
       BDCODCOL         = wcolatu;
       BDREFFN          = prref;
       BDORDEM          = wordematu;
       BDCODCENTRO      = wcentrosatu;
       BDCODTPCC        = wccatu;
       BDINSSFTPR       = winss;
       BDINSSFEFOLFTPR  = winssfe;
       BDINSS13FTPR     = winss13;
       BDBINSSFEFOLFTPR = wbaseinssfe;
       BDBINSSAPFTPR    = wbinssap;
       BDBINSS13APFTPR  = wbinss13ap;
       BDINSSAPFTPR     = wainssap;
       BDINSS13APFTPR   = wainss13ap;
       BDBAVPREV        = 0;

       IF ((wlimsind IN (3,4,6,7)) OR (wlimsind = 1 AND wlimemp IN (2,3,5,6))) THEN
          BDBINSSFTPR = wbinssap;
       ELSE
          BDBINSSFTPR = wbaseinss;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13INDFTPR = 0;
       ELSE
          BDBINSS13INDFTPR = wbinss13ap;

       IF ((wlimsind IN (6,7)) OR (wlimsind = 1 AND wlimemp IN (5,6))) THEN
          BDBINSS13FTPR = wbaseinss13 - wbinss13ap;
       ELSE
          BDBINSS13FTPR = wbaseinss13;

       IF (BDBINSSFTPR+BDBINSSFEFOLFTPR < 0) THEN
          BEGIN
            BDBINSSFEFOLFTPR = 0;
            BDBINSSFTPR = 0;
          END

       IF (BDBINSSFEFOLFTPR > 0 AND BDINSSFTPR < 0) THEN
          BDINSSFEFOLFTPR = bdinssfefolftpr + bdinssftpr;

       IF (BDBINSSFTPR < 0 AND BDBINSSFEFOLFTPR > 0) THEN
          BDBINSSFEFOLFTPR = BDBINSSFEFOLFTPR + BDBINSSFTPR;

       wpercrat = 0;
       wpercdedfpas = 0;
       wcatesoc = null;

       SELECT first 1 BDPERCRATCOL, BDPERCDESCFPASCOL, BDCONTRCOL, BDCATEGORIAESOCIAL
       FROM VW_VRHF_EMP_TCOLCON_FGTSGPS
       WHERE BDCODEMP = :wempatu AND BDCODCOL = :wcolatu and BDREFCOL <= :prref
       INTO :wpercrat, :wpercdedfpas, :wcontrcol, :wcatesoc;

       IF (wcontrcol = 1) THEN
          BDBINSSFTPR = wbaseinsscontratu;

       IF (BDBINSSFTPR < 0) THEN
          BDBINSSFTPR = 0;

       IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
          BEGIN
            BDBRATAPOFTPR   = wbaseinss;    -- + wbaseinssfe;
            BDBRATAPOFEFTPR = wbaseinssfe;
            BDBRATAPO13FTPR = wbaseinss13;
          END
       ELSE
          BEGIN
            BDBRATAPOFTPR   = 0;
            BDBRATAPOFEFTPR = 0;
            BDBRATAPO13FTPR = 0;
          END

       BDSALFAMFTPR        = wsalfam;
       BDSALMATEMPFTPR     = wsalmatemp;
       BDVALREEMBOLSO      = wreemb;
       BDVALINDEVIDO       = wvindevido;
       BDVALINDEVIDOSF     = wvindevidosf;
       BDPERCRATCOL        = wpercrat;
       BDPERCDESCFPASCOL   = wpercdedfpas;

       if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and coalesce(wcatesoc, 0) in (731, 734)) then
          begin
            BDBINSS13APFTPR  = 0;
            BDBINSS13FTPR    = 0;
            BDBINSS13INDFTPR = 0;
            BDBINSSAPFTPR    = 0;
            BDBINSSFEFOLFTPR = 0;
            BDBINSSFTPR      = 0;
          end

       BDBASERAT = BDBINSSFTPR + BDBINSS13FTPR;

       select first 1 BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS
       where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :PRREF
       order by BDREFCOL DESC into :WCATEGORIAESOC;

       if (WCATEGORIAESOC IN (107, 108)) then
          begin
            BDBINSSFTPR = BDBINSSFTPR + BDBINSS13FTPR;
            BDBINSS13FTPR = 0;

            select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREF order by bdrefsm DESC INTO :WSALMIN;
            if (BDBINSSFTPR > WSALMIN * 1.5) then
               begin
                 BDBINSSFTPR = BDBINSSFTPR - WSALMIN * 1.5;
               end
            else
               begin
                 BDBINSSFTPR = 0;
               end
          end

       SUSPEND;

    IF (prref >= 200903 AND prgpssefip = 1 AND wsomaap <> 0) THEN
          BEGIN
            BDGPSSEFIP     = 1;
            BDCODEMP       = wempatu;
            BDCODCOL       = wcolatu;
            BDREFFN        = prref;
            BDORDEM        = wordematu;
            BDCODCENTRO    = wcentrosatu;
            BDCODTPCC      = wccatu;
            BDBAVPREV      = wbavprev;

            IF ((wainssap <> 0) OR (wtemvalor = 1)) THEN
               BEGIN
                 IF (wbaseinssfe + wbinssap < 0) THEN
                    BEGIN
                 IF (wbinssap < 0) THEN
                   wbinssap = 0;
                    END

                 BDINSSFTPR  = wainssap;
                 BDBINSSFTPR = wbinssap;
               END
            ELSE
               BEGIN
                 BDINSSFTPR  = winss;
                 BDBINSSFTPR = wbaseinss;
               END

            BDINSSFEFOLFTPR     = winssfe;
            BDINSS13FTPR        = wainss13ap;
            BDBINSSFEFOLFTPR    = wbaseinssfe;
            BDBINSS13FTPR       = wbaseinss13;
            BDBINSSAPFTPR       = wbinssap;
            BDBINSS13INDFTPR    = wbinss13ap;
            BDBINSS13APFTPR     = wbinss13ap;
            BDINSSAPFTPR        = wainssap;
            BDINSS13APFTPR      = wainss13ap;
            BDPERCRATCOL        = wpercrat;
            BDPERCDESCFPASCOL   = wpercdedfpas;
     
            IF (wpercrat <> 0 AND wpercrat IS NOT NULL) THEN
               BEGIN
                 BDBRATAPOFTPR   = BDBINSSFTPR;    -- + BDBINSSFEFOLFN;
                 BDBRATAPOFEFTPR = BDBINSSFEFOLFTPR;
                 BDBRATAPO13FTPR = BDBINSS13FTPR;
               END
            ELSE
               BEGIN
                 BDBRATAPOFTPR   = 0;
                 BDBRATAPOFEFTPR = 0;
                 BDBRATAPO13FTPR = 0;
               END
     
            BDSALFAMFTPR     = wsalfam;
            BDSALMATEMPFTPR  = wsalmatemp;

            BDVALREEMBOLSO = wreemb;
            BDVALINDEVIDO  = wvindevido;
            BDVALINDEVIDOSF = wvindevidosf;

            IF (BDBINSSFEFOLFTPR > 0 AND BDINSSFTPR < 0) THEN
               BDINSSFEFOLFTPR = bdinssfefolftpr + bdinssftpr;
            IF (BDBINSSFTPR < 0 AND BDBINSSFEFOLFTPR > 0) THEN
               BDBINSSFEFOLFTPR = BDBINSSFEFOLFTPR + BDBINSSFTPR;

            if (coalesce(wclatrib, 0) = 99 and coalesce(wcoop, 0) = 1 and coalesce(wcatesoc, 0) in (731, 734)) then
               begin
                 BDBINSS13APFTPR  = 0;
                 BDBINSS13FTPR    = 0;
                 BDBINSS13INDFTPR = 0;
                 BDBINSSAPFTPR    = 0;
                 BDBINSSFEFOLFTPR = 0;
                 BDBINSSFTPR      = 0;
               end

            BDBASERAT = BDBINSSFTPR + BDBINSS13FTPR;

            select first 1 BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS
            where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :PRREF
            order by BDREFCOL DESC into :WCATEGORIAESOC;

            if (WCATEGORIAESOC IN (107, 108)) then
               begin
                 BDBINSSFTPR = BDBINSSFTPR + BDBINSS13FTPR;
                 BDBINSS13FTPR = 0;

                 select first 1 bdSalMin from VRHF_TABELAS_TSALMIN where bdrefsm <= :PRREF order by bdrefsm DESC INTO :WSALMIN;
                 if (BDBINSSFTPR > WSALMIN * 1.5) then
                    begin
                      BDBINSSFTPR = BDBINSSFTPR - WSALMIN * 1.5;
                    end
                 else
                    begin
                      BDBINSSFTPR = 0;
                    end
               end

            SUSPEND;
         END
     END
END^

/* Restore proc. body: SP_PEGA_EVENTO_ORIGINAL */
create or alter procedure SP_PEGA_EVENTO_ORIGINAL (
    PRCHAVE varchar(60),
    PRCODEMP integer)
returns (
    BDCODIGO integer,
    BDSTATUS integer)
as
declare variable WSQL varchar(500);
declare variable BDEVENTOVINC integer;
begin
  BDCODIGO = null;
  BDEVENTOVINC = null;
  BDSTATUS = null;
  WSQL = 'select first 1 BDCODIGO, BDEVENTOVINC, BDSTATUS from VRH_ESOCIAL_TARQUIVO where BDCHAVE = ' || '''' || PRCHAVE || ''' and not (BDSTATUS in (4,5,6,7,8)) and BDCODEMP = ' || PRCODEMP;
  execute statement WSQL
      into :BDCODIGO, :BDEVENTOVINC, :BDSTATUS;
  if (BDEVENTOVINC is not null) then
    begin
      while (BDEVENTOVINC is not null) do
          begin
            WSQL = 'select first 1 BDCODIGO, BDEVENTOVINC, BDSTATUS from VRH_ESOCIAL_TARQUIVO where BDCODIGO =' || BDEVENTOVINC || ' and not (BDSTATUS in (4,5,6,7,8)) and BDCODEMP = ' || PRCODEMP;
            for execute statement WSQL into :BDCODIGO, :BDEVENTOVINC, :BDSTATUS do
              suspend;
            BDEVENTOVINC = null;
          end
       suspend;
    end
   else
    suspend;
end^

/* Restore proc. body: SP_PEGAEVT_VINCULADOS */
create or alter procedure SP_PEGAEVT_VINCULADOS (
    PREMPRESA integer,
    PRCODIGO integer,
    PRSTATUS integer,
    PRCHAVE varchar(60))
returns (
    BDCODEMP integer,
    BDSTATUS integer,
    BDCHAVE varchar(60),
    BDCODIGO integer)
as
declare variable WSQL varchar(3000);
begin
  /* Procedure Text */  
  bdcodigo = prcodigo;
  bdstatus = prstatus;
  bdchave = prchave;
  bdcodemp = prempresa;
  suspend;

  if (coalesce(prempresa, 0) <= 0) then
     prempresa = 0;

  if (coalesce(prcodigo, 0) <= 0) then
     prcodigo = 0;

  wsql = 'select bdcodigo, bdcodemp, bdstatus, bdchave from vrh_esocial_tarquivo where BDEVENTOVINC = ' || prcodigo || ' and BDCODEMP = ' || prempresa;
  for execute statement wsql into :bdcodigo, :bdcodemp, :bdstatus, : bdchave do
    begin
      if (coalesce(bdcodigo, 0) <= 0) then
         bdcodigo = 0;
      if (coalesce(bdstatus, 0) <= 0) then
         bdstatus = 0;
      if (coalesce(bdchave, '') = '') then
         bdchave = '';

      wsql = 'select bdcodigo, bdstatus, bdchave, bdcodemp from sp_pegaevt_vinculados('|| bdcodemp || ',' || bdcodigo || ',' || bdstatus || ',''' || bdchave || ''')';
      for execute statement wsql into :bdcodigo, :bdstatus, : bdchave, :bdcodemp do
        suspend;
    end
end^

/* Restore proc. body: SP_PEGAEVT_VINCULADO_SUCESSO */
CREATE OR ALTER procedure SP_PEGAEVT_VINCULADO_SUCESSO (
    PREMPRESA integer,
    PRCODIGO integer)
returns (
    BDCODEVT integer)
as
declare variable BDEVENTOVINC integer;
declare variable BDSTATUS integer;
declare variable WSQL varchar(250);
declare variable WEVTVINC integer;
begin
  /* Procedure Text */
  BDCODEVT = 0;

  if (coalesce(prempresa, 0) <= 0) then
    prempresa = 0;

  if (coalesce(prcodigo, 0) <= 0) then
    prcodigo = 0;

  wsql = 'select BDEVENTOVINC, BDCODIGO, bdstatus from vrh_esocial_tarquivo where BDCODIGO = ' || prcodigo || ' and BDCODEMP = ' || prempresa;
  execute statement WSQL
    into :BDEVENTOVINC, :BDCODEVT, :BDSTATUS;

  if ((BDCODEVT > 0) and (BDEVENTOVINC > 0) and (BDEVENTOVINC = BDCODEVT)) then
    begin
      BDCODEVT = 0;
      BDEVENTOVINC = 0;
    end
  else
  if (coalesce(BDEVENTOVINC, 0) > 0) then
    begin
      WEVTVINC = BDEVENTOVINC;

      while ((coalesce(WEVTVINC, 0) > 0) and (coalesce(bdstatus, 0) <> 2)) do
        begin
          BDCODEVT = 0;
          BDSTATUS = 0;

          wsql = 'select BDEVENTOVINC, BDCODIGO, bdstatus from vrh_esocial_tarquivo where BDCODIGO = ' || WEVTVINC || ' and BDCODEMP = ' || prempresa;

          WEVTVINC = 0;

          for execute statement WSQL into :BDEVENTOVINC, :BDCODEVT, :BDSTATUS do
            begin
              if ((BDCODEVT > 0) and (BDEVENTOVINC > 0) and (BDEVENTOVINC = BDCODEVT)) then
                begin
                  WEVTVINC = 0;
                  if (bdstatus <> 2) then
                    begin
                      BDCODEVT = 0;
                      BDEVENTOVINC = 0;
                    end
                end
              else
                begin
                  WEVTVINC = BDEVENTOVINC;
                end
            end
        end
    end

  if (BDSTATUS <> 2) then
    BDCODEVT = 0;

  suspend;
end^

-- 125979 - Raphael Teodoro - 21/01/2020
CREATE OR ALTER procedure SP_VRH_PAINEL_UPDATE (
    PRCODEMP integer,
    PRANOMES integer,
    PRSTATUS varchar(1),
    PRFIELDPAINEL varchar(25),
    PRTODOSPERIODICOS type of DM_BOOLEAN = 'FALSE',
    PRTODOSDCTF type of DM_BOOLEAN = 'FALSE')
as
declare variable WWHERE varchar(1000);
declare variable WFIELDS varchar(10000);
declare variable WSQL varchar(10000);
declare variable WEXISTE type of DM_BOOLEAN;
declare variable WISDCTF type of DM_BOOLEAN;
BEGIN
  -- Evitar erro caso a referencia seja preenchida posteriormente
  IF ((pranomes IS NULL) OR (pranomes = 0)) THEN
     EXIT;

  -- 140108 - Raphael Teodoro - 12/08/2020
  IF ((prfieldpainel = 'BDDCTFWEB') OR
      (prfieldpainel = 'BDDCTFMANUAL')) THEN
     BEGIN
       wIsDCTF = 'TRUE';
       wexiste = 'TRUE';
     END
  ELSE
     BEGIN
       wIsDCTF = 'FALSE';
       wexiste = 'FALSE';
       SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRH_ESOCIAL_TARQUIVO WHERE (bdcodemp = :prcodemp) INTO :wexiste;
     END

  IF (wexiste <> 'TRUE') THEN
     EXIT;

  wexiste = 'FALSE';
  SELECT FIRST 1 'TRUE' AS BDEXISTE FROM vrh_emp_painel WHERE (bdcodemp = :prcodemp) AND (bdano = (:pranomes/100)) INTO :wexiste;

  -- Cria registro caso nao exista
  IF (wexiste <> 'TRUE') THEN
     INSERT INTO vrh_emp_painel(bdcodemp, bdano) VALUES (:prcodemp, (:pranomes/100));

  -- Verifica se "exclusao" tornou "sem calculo"
  IF ((prstatus = '2') AND (prfieldpainel <> '')) THEN
     BEGIN
       wexiste = 'FALSE';
       IF (prfieldpainel = 'BDPERFOLHANORMAL') THEN
          BEGIN
            SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRHF_EMP_TFOLHANORMAL WHERE (bdcodemp = :prcodemp) AND (bdreffn = :pranomes) INTO :wexiste;
            IF (wexiste <> 'TRUE') THEN
               SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRHF_EMP_TFOLHATOMADOR WHERE (bdcodemp = :prcodemp) AND (bdreftomador = :pranomes) INTO :wexiste;
          END
       ELSE
       IF (prfieldpainel = 'BDPERFOLHAINTERMITENTE') THEN
          BEGIN
            SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRHF_EMP_TFOLHAINT WHERE (bdcodemp = :prcodemp) AND (bdreffn = :pranomes) INTO :wexiste;
            IF (wexiste <> 'TRUE') THEN
               SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRHF_EMP_TFOLHATOMINT WHERE (bdcodemp = :prcodemp) AND (bdreftomador = :pranomes) INTO :wexiste;
          END
       ELSE
       IF (prfieldpainel = 'BDPERFOLHAAUTONOMO') THEN
          SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRH_BASE_TSERVTERC WHERE (bdcodemp = :prcodemp) AND (bdrefserv = :pranomes) INTO :wexiste;
       ELSE
       IF (prfieldpainel = 'BDPERFOLHAADSALARIO') THEN
          SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRHF_EMP_TADSAL WHERE (bdcodemp = :prcodemp) AND (bdrefad = :pranomes) INTO :wexiste;
       ELSE
       IF (prfieldpainel = 'BDPERFOLHACOMPLEMENTAR') THEN
          BEGIN
            SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRHF_EMP_TFOLHACOMP WHERE (bdcodemp = :prcodemp) AND (bdrefcomp = :pranomes) INTO :wexiste;
            IF (wexiste <> 'TRUE') THEN
               SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRHF_EMP_TFOLTOMCOMP WHERE (bdcodemp = :prcodemp) AND (bdreftomador = :pranomes) INTO :wexiste;

            -- 27813 - Raphael Teodoro - 04/02/2020
            IF (wexiste <> 'TRUE') THEN
               SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRHF_EMP_TFOLHACOMPINT WHERE (bdcodemp = :prcodemp) AND (bdrefcomp = :pranomes) INTO :wexiste;

            -- 27813 - Raphael Teodoro - 04/02/2020
            IF (wexiste <> 'TRUE') THEN
               SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRHF_EMP_TFOLTOMCOMPINT WHERE (bdcodemp = :prcodemp) AND (bdreftomador = :pranomes) INTO :wexiste;
          END
       ELSE
       IF (prfieldpainel = 'BDPERFOLHAFERIAS') THEN
          BEGIN
            SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRH_EMP_TFERIAS WHERE (bdcodemp = :prcodemp) AND (bdrefinife = :pranomes) INTO :wexiste;
            IF (wexiste <> 'TRUE') THEN
               SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRH_EMP_TFERIAS WHERE (bdcodemp = :prcodemp) AND (:pranomes BETWEEN bdrefinife AND bdreffimfe) INTO :wexiste;
          END
       ELSE
       IF (prfieldpainel = 'BDPERFOLHAAVULSA') THEN
          SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRHF_EMP_TFOLHAAVULSA WHERE (bdcodemp = :prcodemp) AND (bdref = :pranomes) INTO :wexiste;
       ELSE
       IF (prfieldpainel = 'BDPERFOLHA13SALARIO') THEN
          SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRHF_EMP_T13SAL WHERE (bdcodemp = :prcodemp) AND (bdref13 = :pranomes) INTO :wexiste;
       ELSE
       IF (prfieldpainel = 'BDPERFOLHAAD13SALARIO') THEN
          SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRHF_EMP_TA13SAL WHERE (bdcodemp = :prcodemp) AND (bdrefa13 = :pranomes) INTO :wexiste;
       ELSE
       IF (prfieldpainel = 'BDPERFOLHACOMP13SALARIO') THEN
          SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRHF_EMP_TC13SAL WHERE (bdcodemp = :prcodemp) AND (bdrefc13 = :pranomes) INTO :wexiste;
       ELSE
       IF (prfieldpainel = 'BDPERNFFUNRURAL') THEN
          SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRHF_EMP_TNFPRODRURAL WHERE (bdcodemp = :prcodemp) AND (bdrefnf = :pranomes) INTO :wexiste;
       ELSE
       -- 140108 - Raphael Teodoro - 06/08/2020
       IF (prfieldpainel = 'BDDCTFWEB') THEN
          SELECT FIRST 1 'TRUE' AS BDEXISTE FROM VRH_EMP_DCTFWEB WHERE (bdcodemp = :prcodemp) AND (bdref = :pranomes) INTO :wexiste;
       ELSE
          wexiste = 'TRUE'; -- Nao modifica

       IF (wexiste <> 'TRUE') THEN
          prstatus = ' '; -- Sem calculo
     END

  wfields = '';

  IF (prfieldpainel <> '') THEN
     BEGIN
       IF (wfields <> '') THEN
          wfields = wfields || ',';

       wfields = wfields || prfieldpainel || ' = SUBSTRING(COALESCE(' || prfieldpainel || ',''             '') FROM 1 FOR ' || CAST(MOD(pranomes,100)-1 AS VARCHAR(2)) || ') ||' || ' ''' || prstatus || ''' ||' || ' SUBSTRING(COALESCE(' || prfieldpainel || ',''             '') FROM ' || CAST(MOD(pranomes,100)+1 AS VARCHAR(2)) || ' FOR 13)';
     END

  IF (prtodosperiodicos = 'TRUE') THEN
     BEGIN
       IF (wfields <> '') THEN
          wfields = wfields || ',';

       wfields = wfields || 'BDPERFOLHANORMAL        = SUBSTRING(COALESCE(BDPERFOLHANORMAL,       ''             '') FROM 1 FOR ' || CAST(MOD(pranomes,100)-1 AS VARCHAR(2)) || ') ||' || ' ''' || prstatus || ''' ||' || ' SUBSTRING(COALESCE(BDPERFOLHANORMAL,       ''             '') FROM ' || CAST(MOD(pranomes,100)+1 AS VARCHAR(2)) || ' FOR 13),' ||
                            'BDPERFOLHAINTERMITENTE  = SUBSTRING(COALESCE(BDPERFOLHAINTERMITENTE, ''             '') FROM 1 FOR ' || CAST(MOD(pranomes,100)-1 AS VARCHAR(2)) || ') ||' || ' ''' || prstatus || ''' ||' || ' SUBSTRING(COALESCE(BDPERFOLHAINTERMITENTE, ''             '') FROM ' || CAST(MOD(pranomes,100)+1 AS VARCHAR(2)) || ' FOR 13),' ||
                            'BDPERFOLHAAUTONOMO      = SUBSTRING(COALESCE(BDPERFOLHAAUTONOMO,     ''             '') FROM 1 FOR ' || CAST(MOD(pranomes,100)-1 AS VARCHAR(2)) || ') ||' || ' ''' || prstatus || ''' ||' || ' SUBSTRING(COALESCE(BDPERFOLHAAUTONOMO,     ''             '') FROM ' || CAST(MOD(pranomes,100)+1 AS VARCHAR(2)) || ' FOR 13),' ||
                            'BDPERFOLHAADSALARIO     = SUBSTRING(COALESCE(BDPERFOLHAADSALARIO,    ''             '') FROM 1 FOR ' || CAST(MOD(pranomes,100)-1 AS VARCHAR(2)) || ') ||' || ' ''' || prstatus || ''' ||' || ' SUBSTRING(COALESCE(BDPERFOLHAADSALARIO,    ''             '') FROM ' || CAST(MOD(pranomes,100)+1 AS VARCHAR(2)) || ' FOR 13),' ||
                            'BDPERFOLHACOMPLEMENTAR  = SUBSTRING(COALESCE(BDPERFOLHACOMPLEMENTAR, ''             '') FROM 1 FOR ' || CAST(MOD(pranomes,100)-1 AS VARCHAR(2)) || ') ||' || ' ''' || prstatus || ''' ||' || ' SUBSTRING(COALESCE(BDPERFOLHACOMPLEMENTAR, ''             '') FROM ' || CAST(MOD(pranomes,100)+1 AS VARCHAR(2)) || ' FOR 13),' ||
                            'BDPERFOLHAFERIAS        = SUBSTRING(COALESCE(BDPERFOLHAFERIAS,       ''             '') FROM 1 FOR ' || CAST(MOD(pranomes,100)-1 AS VARCHAR(2)) || ') ||' || ' ''' || prstatus || ''' ||' || ' SUBSTRING(COALESCE(BDPERFOLHAFERIAS,       ''             '') FROM ' || CAST(MOD(pranomes,100)+1 AS VARCHAR(2)) || ' FOR 13),' ||
                            'BDPERFOLHAAVULSA        = SUBSTRING(COALESCE(BDPERFOLHAAVULSA,       ''             '') FROM 1 FOR ' || CAST(MOD(pranomes,100)-1 AS VARCHAR(2)) || ') ||' || ' ''' || prstatus || ''' ||' || ' SUBSTRING(COALESCE(BDPERFOLHAAVULSA,       ''             '') FROM ' || CAST(MOD(pranomes,100)+1 AS VARCHAR(2)) || ' FOR 13),' ||
                            'BDPERFOLHA13SALARIO     = SUBSTRING(COALESCE(BDPERFOLHA13SALARIO,    ''             '') FROM 1 FOR ' || CAST(MOD(pranomes,100)-1 AS VARCHAR(2)) || ') ||' || ' ''' || prstatus || ''' ||' || ' SUBSTRING(COALESCE(BDPERFOLHA13SALARIO,    ''             '') FROM ' || CAST(MOD(pranomes,100)+1 AS VARCHAR(2)) || ' FOR 13),' ||
                            'BDPERFOLHAAD13SALARIO   = SUBSTRING(COALESCE(BDPERFOLHAAD13SALARIO,  ''             '') FROM 1 FOR ' || CAST(MOD(pranomes,100)-1 AS VARCHAR(2)) || ') ||' || ' ''' || prstatus || ''' ||' || ' SUBSTRING(COALESCE(BDPERFOLHAAD13SALARIO,  ''             '') FROM ' || CAST(MOD(pranomes,100)+1 AS VARCHAR(2)) || ' FOR 13),' ||
                            'BDPERFOLHACOMP13SALARIO = SUBSTRING(COALESCE(BDPERFOLHACOMP13SALARIO,''             '') FROM 1 FOR ' || CAST(MOD(pranomes,100)-1 AS VARCHAR(2)) || ') ||' || ' ''' || prstatus || ''' ||' || ' SUBSTRING(COALESCE(BDPERFOLHACOMP13SALARIO,''             '') FROM ' || CAST(MOD(pranomes,100)+1 AS VARCHAR(2)) || ' FOR 13),' ||
                            'BDPERNFFUNRURAL         = SUBSTRING(COALESCE(BDPERNFFUNRURAL,        ''             '') FROM 1 FOR ' || CAST(MOD(pranomes,100)-1 AS VARCHAR(2)) || ') ||' || ' ''' || prstatus || ''' ||' || ' SUBSTRING(COALESCE(BDPERNFFUNRURAL,        ''             '') FROM ' || CAST(MOD(pranomes,100)+1 AS VARCHAR(2)) || ' FOR 13) ';
     END

  IF (prtodosdctf = 'TRUE') THEN
     BEGIN
       IF (wfields <> '') THEN
          wfields = wfields || ',';

       wfields = wfields || 'BDDCTFWEB = SUBSTRING(COALESCE(BDDCTFWEB,''             '') FROM 1 FOR ' || CAST(MOD(pranomes,100)-1 AS VARCHAR(2)) || ') ||' || ' ''' || prstatus || ''' ||' || ' SUBSTRING(COALESCE(BDDCTFWEB,''             '') FROM ' || CAST(MOD(pranomes,100)+1 AS VARCHAR(2)) || ' FOR 13)';
     END

  wsql = 'UPDATE vrh_emp_painel' ||
                   ' SET ' || wfields ||
                   ' WHERE (BDCODEMP = ' || prcodemp || ')' ||
                     ' AND (BDANO = ' || (pranomes/100) || ')';

  IF ((wIsDCTF <> 'TRUE') AND -- 140108 - Raphael Teodoro - 03/09/2020
      ((prstatus = '1') OR (prstatus = '2'))) THEN  -- Sol. 134802 | Michel Luciano | 10/03/2020 | Está apresentando divergências mesmo com o período fechado.
    BEGIN
      wwhere = ' AND (SUBSTRING(COALESCE(BDPERFOLHANORMAL, ''             '') FROM ' || CAST(MOD(pranomes,100) AS VARCHAR(2)) || ' FOR 1) <> ''3'' )';
      wsql   = wsql || wwhere;
    END

  EXECUTE STATEMENT wsql;
END
^

/* Restore proc. body: SP_GET_HISTORICOCOMPLETO */
CREATE OR ALTER PROCEDURE SP_GET_HISTORICOCOMPLETO (
    HISTORICO VARCHAR(3000),
    COMPLEMENTO VARCHAR(3000),
    COMPLEMENTOCOMPLETO VARCHAR(3000))
RETURNS (WRESULT VARCHAR(3000))
AS 
BEGIN
  /* Procedure Text */
  WRESULT = '';
  IF (COALESCE(COMPLEMENTO, '') <> '') THEN
    WRESULT = WRESULT || COMPLEMENTO;

  IF (COALESCE(COMPLEMENTOCOMPLETO, '') <> '') THEN
    WRESULT = WRESULT || COMPLEMENTOCOMPLETO;

  IF ((COALESCE(HISTORICO, '') <> '') AND (POSITION('*', HISTORICO) <= 0)) THEN
    WRESULT = HISTORICO || ' ' || WRESULT;

  SUSPEND;
END
^

--#172717 - Djonathan
CREATE OR ALTER PROCEDURE SP_GET_CLASSIFICACAO_SEM_ZEROS (
    PRCLASSIFICACAO VARCHAR(40))
RETURNS (
    BDRESULT VARCHAR(20))
AS
DECLARE VARIABLE wTEMP_CLASSIFICACAO VARCHAR(100);
DECLARE VARIABLE I INTEGER;
BEGIN
    FOR SELECT BDCLASSIFICACAO FROM SP_GET_CLASSIFICACAO_NIVEL(:PRCLASSIFICACAO, 1)
        INTO :wTEMP_CLASSIFICACAO
    DO
    BEGIN
        I = 1;

        WHILE ((I <= CHAR_LENGTH(wTEMP_CLASSIFICACAO)) AND (SUBSTRING(wTEMP_CLASSIFICACAO FROM I FOR 1) = '0')) DO
            I = I + 1;

        BDRESULT = SUBSTRING(wTEMP_CLASSIFICACAO FROM I);
        
        IF (BDRESULT IS NULL OR BDRESULT = '') THEN
            BDRESULT = '0';

        SUSPEND;
    END
END^

/* CREATE OR ALTER TRIGGER... */

CREATE OR ALTER trigger tintegracao_arq_cliente_bi0 for tintegracao_arq_cliente
active before insert position 0
AS
begin
  new.bddatahora = localtimestamp;
  new.bdstatusprocesso = 0;
end^

CREATE OR ALTER TRIGGER TEMPRESAS_SEQ_DED_BI0 FOR TEMPRESAS_SEQ_DED
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER TPARCEIRO_BI0 FOR TPARCEIRO
active before insert position 0
AS
begin
  /* Trigger text */
  new.bddata = localtimestamp;
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TDIMEQ12_1926_AD0 FOR TOL_VEF_EMP_TDIMEQ12_1926
ACTIVE AFTER DELETE POSITION 0
AS
begin
  DELETE FROM VEF_EMP_TMOVAJU1926 WHERE BDCODEMP = OLD.BDCODEMP AND BDORDEM1926 = OLD.BDORDEM1926;
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_IMP_SERV_BI0 FOR VRH_BASE_TCONF_IMP_SERV
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;
begin
  if (coalesce(new.bdcodimpserv, 0) = 0) then
     begin
       select coalesce(max(BDCODIMPSERV) + 1, 1) from VRH_BASE_TCONF_IMP_SERV into :vcod;
       new.bdcodimpserv = :vcod;
     end
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERTHEMA_BI0 FOR VEF_EMP_TMOVSERTHEMA
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
END
^

CREATE OR ALTER TRIGGER VRHF_TINFO_DESC_SIMPLES_BIU0 FOR VRHF_TINFO_DESC_SIMPLES
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
  DECLARE VARIABLE wsql VARCHAR(3000);
  DECLARE VARIABLE wvalorultrapassadescsimpli VARCHAR(5);
begin
  /* Trigger text */

  wvalorultrapassadescsimpli = 'FALSE';

  new.bdvalorsimplificadotabela = coalesce(old.bdvalorsimplificadotabela,0);

  if (old.bdprutilizadescsimpli is null) then
    new.bdprutilizadescsimpli = 'FALSE';


  if (old.bdautonomo is null) then
     begin
       IF (new.bdautonomo = 1) THEN
         wsql = 'select first 1 bdutilizadescsimplificado from tterceiro_ref where bdcodter = '|| new.bdcodcolcon ||' and bdrefemp <= '|| new.bdreferencia ||' order by bdrefemp desc ';
       ELSE
         wsql = 'Select first 1 bdutilizadescsimplificado from VRH_EMP_TCOLCON_REF where bdcodemp = '|| new.bdcodemp ||' and bdcodcol = '|| new.bdcodcolcon ||' and bdrefcol <= '|| new.bdreferencia ||' order by bdrefcol desc';
     
       EXECUTE STATEMENT wsql INTO new.bdprutilizadescsimpli;

       wsql = 'Select first 1 coalesce(bddescontosimplificado, 0) from VRHF_TABELAS_TIRDADOS where BDREFIR <= '|| new.bdreferencia ||' and BDTIPOCALCFIR <> 8 order by bdrefir desc';

       EXECUTE STATEMENT wsql INTO new.bdvalorsimplificadotabela;
     end

  IF (upper(new.bdvaloresdeferias) = 'TRUE') THEN    /* Cálculo de férias*/
    BEGIN
        if (coalesce(new.bdrendtributavelferias, 0) > 0) then
          begin
            /*Soma dos valores de pensão, previdência e INSS*/
            new.bdpensaoferias = coalesce(new.bdpensaoferias, 0);
            new.bdprevferias = coalesce(new.bdprevferias, 0);
            new.bdinssferias = coalesce(new.bdinssferias, 0);
            new.bddepferias = coalesce(new.bddepferias, 0);

            /*Caso não atribua nenhum valor para o desconsimplificado mantem o valor anterior e evita ficar null*/
            if ((new.bdvalorsimplificadotabela > 0) and
               (upper(new.bdprutilizadescsimpli) = 'TRUE') and
               ((new.bdpensaoferias + new.bdprevferias + new.bdinssferias + new.bddepferias) < new.bdvalorsimplificadotabela)) then
               new.bdvalordescsimpleferias = coalesce(old.bdvalordescsimpleferias, 0) + coalesce(new.bdvalorsimpliutilizadoferias, 0);
            else
            if ((new.bdvalordescsimpleferias is null) and (old.bdvalordescsimpleferias is null)) then
              new.bdvalordescsimpleferias = 0;
          end
        else
          begin
            new.bdpensaoferias = coalesce(old.bdpensaoferias, 0);
            new.bddepferias = coalesce(old.bddepferias, 0);
            new.bdprevferias = coalesce(old.bdprevferias, 0);
            new.bdinssferias = coalesce(old.bdinssferias, 0);
            new.bdvalorsimpliutilizadoferias = coalesce(old.bdvalorsimpliutilizadoferias, 0);
            new.bdvalordescsimpleferias = coalesce(old.bdvalordescsimpleferias, 0);
          end


        new.bdpensaooutrasfolhas = coalesce(old.bdpensaooutrasfolhas, 0);
        new.bddepoutrasfolhas = coalesce(old.bddepoutrasfolhas, 0);
        new.bdprevoutrasfolhas = coalesce(old.bdprevoutrasfolhas, 0);
        new.bdinssoutrasfolhas = coalesce(old.bdinssoutrasfolhas, 0);
        new.bdvalorsimpliutilizado = coalesce(old.bdvalorsimpliutilizado, 0);
        new.bdvalordescsimpli = coalesce(old.bdvalordescsimpli, 0);
    END
  ELSE
  IF (upper(new.bdvaloresdeferias) = 'FALSE') THEN /* Outros tipos de cálculos */
    BEGIN
        if (coalesce(new.bdrendtributavel, 0) > 0) then
          begin
            /*Soma dos valores de pensão, previdência e INSS*/
            new.bdpensaooutrasfolhas = coalesce(new.bdpensaooutrasfolhas, 0) + coalesce(old.bdpensaooutrasfolhas, 0);
            new.bdprevoutrasfolhas = coalesce(new.bdprevoutrasfolhas, 0) + coalesce(old.bdprevoutrasfolhas, 0);
            new.bdinssoutrasfolhas = coalesce(new.bdinssoutrasfolhas, 0) + coalesce(old.bdinssoutrasfolhas, 0);
    
            if (coalesce(old.bddepoutrasfolhas,0) > coalesce(new.bddepoutrasfolhas,0)) then
               new.bddepoutrasfolhas = coalesce(old.bddepoutrasfolhas, 0);
            else
               new.bddepoutrasfolhas = coalesce(new.bddepoutrasfolhas, 0);
    
            if (((new.bdvalorsimplificadotabela > 0) and
               (upper(new.bdprutilizadescsimpli) = 'TRUE')) and (coalesce(new.bdvalorsimpliutilizado,0) > 0)) then
               begin
                 if ((new.bdpensaooutrasfolhas + new.bdprevoutrasfolhas + new.bdinssoutrasfolhas + new.bddepoutrasfolhas) < new.bdvalorsimplificadotabela) then
                     new.bdvalordescsimpli = new.bdvalorsimpliutilizado;
                 else
                     new.bdvalordescsimpli = 0;
               end
            else
            if ((new.bdpensaooutrasfolhas + new.bdprevoutrasfolhas + new.bdinssoutrasfolhas + new.bddepoutrasfolhas) < new.bdvalorsimplificadotabela)  then
               begin
                  new.bdvalordescsimpli = coalesce(old.bdvalordescsimpli, 0);
               end
            else
               begin
                  new.bdvalordescsimpli = 0;
               end
          end
        else
          begin
            new.bdpensaooutrasfolhas = coalesce(old.bdpensaooutrasfolhas, 0);
            new.bddepoutrasfolhas = coalesce(old.bddepoutrasfolhas, 0);
            new.bdprevoutrasfolhas = coalesce(old.bdprevoutrasfolhas, 0);
            new.bdinssoutrasfolhas = coalesce(old.bdinssoutrasfolhas, 0);
            new.bdvalorsimpliutilizado = coalesce(old.bdvalorsimpliutilizado, 0);
            new.bdvalordescsimpli = coalesce(old.bdvalordescsimpli, 0);
          end

        new.bdpensaoferias = coalesce(old.bdpensaoferias, 0);
        new.bddepferias = coalesce(old.bddepferias, 0);
        new.bdprevferias = coalesce(old.bdprevferias, 0);
        new.bdinssferias = coalesce(old.bdinssferias, 0);
        new.bdvalorsimpliutilizadoferias = coalesce(old.bdvalorsimpliutilizadoferias, 0);
        new.bdvalordescsimpleferias = coalesce(old.bdvalordescsimpleferias, 0);
    END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TEXPDYNAMICS_BI0 FOR VRH_BASE_TEXPDYNAMICS
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF ((NEW.bdcodexp IS NULL) OR (NEW.bdcodexp = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODEXP) + 1, 1) FROM VRH_BASE_TEXPDYNAMICS WHERE BDCODEMP = NEW.bdcodemp INTO :vcod;
       NEW.bdcodexp = :vcod;
     END
END^

CREATE or ALTER trigger vrhf_emp_tfcpensao_dep_bi0 for vrhf_emp_tfcpensao_dep
active before insert position 0
AS
declare variable wcodigopk integer;
begin
  /* Trigger text */
  select max(BDCODIGOPK) BDCODIGOPK from VRHF_EMP_TFCPENSAO_DEP
  where (BDCODEMP = new.BDCODEMP) and
        (BDREFFN = new.BDREFFN) and
        (BDCODCOL = new.BDCODCOL) and
        (BDCODBENEF = new.BDCODBENEF) and
        (BDREFFC = new.BDREFFC) into :wcodigopk;

  if (coalesce(wcodigopk, 0) <> 0) then
      new.BDCODIGOPK = :wcodigopk + 1;
  else
      new.BDCODIGOPK = 1;
end^

CREATE OR ALTER TRIGGER TARQ_STORAGESCI_BI0 FOR TARQ_STORAGESCI
ACTIVE BEFORE INSERT POSITION 0
AS
declare variable wNovaChave Integer;
begin
  select Coalesce(max(bdchave),0)+1 from tarq_storagesci into :wNovaChave;

  new.bdchave = :wNovaChave;
end^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAFC_DET_BI0 FOR VRHF_EMP_TVERBAFC_DET
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
--  IF ((NEW.bditemfcd IS NULL) OR (NEW.bditemfcd = 0)) THEN
--     BEGIN
       SELECT COALESCE(MAX(BDITEMFCD) + 1, 1) FROM VRHF_EMP_TVERBAFC_DET
       WHERE BDCODVER = NEW.bdcodver AND BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol AND BDREFFN = NEW.bdreffn AND
             BDREFFC = NEW.bdreffc INTO :vcod;
       NEW.bditemfcd = :vcod;
--     END
END^

CREATE OR ALTER TRIGGER vef_emp_tplanilhasndeb_bd0 FOR vef_emp_tplanilhasndeb
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  --delete from VEF_EMP_TPLASNDEBDARF where (bdcodfilial = old.bdcodemp) and (bdcodplasn = old.bdcodplasn);
END^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAFCT_DET_BI0 FOR VRHF_EMP_TVERBAFCT_DET
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
--  IF ((NEW.bditemfctd IS NULL) OR (NEW.bditemfctd = 0)) THEN
--     BEGIN
       SELECT COALESCE(MAX(BDITEMFCTD) + 1, 1) FROM VRHF_EMP_TVERBAFCT_DET
       WHERE BDCODVER = NEW.bdcodver AND BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol AND BDREFTOMADOR = NEW.bdreftomador AND BDORDEM = NEW.bdordem AND
             BDREFFC = NEW.bdreffc INTO :vcod;
       NEW.bditemfctd = :vcod;
--     END
     END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAFCTINT_DET_BI0 FOR VRHF_EMP_TVERBAFCTINT_DET
ACTIVE BEFORE INSERT POSITION 0
as
  declare variable vcod integer;
begin
--  if ((new.bditemfctd is null) or (new.bditemfctd = 0)) then
--     BEGIN
       SELECT COALESCE(MAX(BDITEMFCTD) + 1, 1) FROM VRHF_EMP_TVERBAFCTINT_DET
       WHERE BDCODVER = NEW.bdcodver AND BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol AND BDREFTOMADOR = NEW.bdreftomador AND BDORDEM = NEW.bdordem AND
             BDREFFC = NEW.bdreffc AND BDCODCONTTI = NEW.bdcodcontti INTO :vcod;
       new.bditemfctd = :vcod;
--     end
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAFCINT_DET_BI0 FOR VRHF_EMP_TVERBAFCINT_DET
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
--  IF ((NEW.bditemfcd IS NULL) OR (NEW.bditemfcd = 0)) THEN
--     BEGIN
       SELECT COALESCE(MAX(BDITEMFCD) + 1, 1) FROM VRHF_EMP_TVERBAFCINT_DET
       WHERE BDCODVER = NEW.bdcodver AND BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol AND BDREFFN = NEW.bdreffn AND
             BDREFFC = NEW.bdreffc AND BDCODCONTTI = NEW.BDCODCONTTI INTO :vcod;
       NEW.bditemfcd = :vcod;
--     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TTIPOFOLHACOMP_BI0 FOR VRH_BASE_TTIPOFOLHACOMP
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF ((NEW.bdcodtipofc IS NULL) OR (NEW.bdcodtipofc = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(BDCODTIPOFC) + 1, 1) FROM VRH_BASE_TTIPOFOLHACOMP INTO :vcod;
      NEW.bdcodtipofc = :vcod;
    END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_CLASSTRIBUTARIA_BI0 FOR VRH_BASE_CLASSTRIBUTARIA
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF ((NEW.bdcodclatri IS NULL) OR (NEW.bdcodclatri = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(BDCODCLATRI) + 1,1) FROM VRH_BASE_CLASSTRIBUTARIA INTO :vcod;
      NEW.bdcodclatri = :vcod;
    END
END
^

CREATE OR ALTER TRIGGER TLOG_BU0 FOR TLOG
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  --alt:15642 - 13/09/2016 - Registros do tipo "exclusão de lançamentos contábeis" (13) também devem ser agrupados. Pedro
  --alt:15307 - 15/08/2016 - Criada trigger para quando for impressão de relatório em vídeo, somar os tempos em um só registro, para não estufar muito o banco. Pedro
  IF (((NEW.BDTIPOACAO = 5) AND (NEW.BDTIPOIMPRESSAO = 0)) OR (NEW.BDTIPOACAO = 13)) THEN --Impressão de relatório em vídeo
    BEGIN
      NEW.BDDATA = DATEADD(SECOND, NEW.BDHORAFINAL - NEW.BDHORAINICIAL, CAST(OLD.BDDATA||' '||OLD.BDHORAFINAL AS TIMESTAMP)); --Data final, somado dia caso passe das 24 horas
      NEW.BDDATASISTEMA = OLD.BDDATASISTEMA; --Data inicial (mantém a antiga, neste caso)
      NEW.BDHORAFINAL = DATEADD(SECOND, NEW.BDHORAFINAL - NEW.BDHORAINICIAL, OLD.BDHORAFINAL); --Hora final, mantém a antiga somando com a diferença de horas do novo registro
      NEW.BDHORAINICIAL = OLD.BDHORAINICIAL; --Hora inicial (mantém a antiga, neste caso)
      NEW.BDQUANTIDADE = COALESCE(OLD.BDQUANTIDADE, 1) + 1; --Quantidade de registros que estão sendo agrupados aqui.
    END
END
^

CREATE or alter trigger tlog_biu0 for tlog
active before insert or update position 0
AS
begin
  /* Trigger text */
  new.bdacao = zipblob(new.bdacao);
end^


CREATE OR ALTER TRIGGER VTPO_TCONF_BI FOR VTPO_TCONF
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcodigo INTEGER;
BEGIN
  -- Marcos P - 02/10/2025 - #231019
  vcodigo = 0;
  IF ((NEW.bdcodconf IS NULL) OR (NEW.bdcodconf = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodconf)+1),1) FROM vtpo_tconf INTO vcodigo;
       NEW.bdcodconf = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodconf FROM vtpo_tconf WHERE bdcodconf = NEW.bdcodconf INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodconf)+1),1) FROM vtpo_tconf INTO vcodigo;
            NEW.bdcodconf = vcodigo;
         END
    END
END
^

--#alt:58948. Ana - 18/07/2018
CREATE OR ALTER trigger vtpo_motivo_inatividade_bi0 FOR vtpo_motivo_inatividade
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE wCodigo INTEGER;
BEGIN
  SELECT COALESCE((MAX(BDCODMOTIVO) + 1), 1) FROM VTPO_MOTIVO_INATIVIDADE INTO :wCodigo;
  IF ((NEW.BDCODMOTIVO IS NULL) OR (NEW.BDCODMOTIVO = 0) OR (NEW.BDCODMOTIVO < wCodigo)) THEN
    NEW.BDCODMOTIVO = :wCodigo;
END
^

--#alt:162662 Matheus C.S. 05/07/2022
CREATE OR ALTER TRIGGER VSST_EMP_TAUTODECLARACAO_BI0 FOR VSST_EMP_TAUTODECLARACAO
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;
BEGIN
  IF ((NEW.BDCODIGO IS NULL) OR (NEW.BDCODIGO = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(X.BDCODIGO) + 1, 1)
       FROM VSST_EMP_TAUTODECLARACAO X
       WHERE X.BDCODEMP = NEW.BDCODEMP
       INTO :vNovoCod;

       NEW.BDCODIGO = :vNovoCod;
     END
END
^

--#alt:162662 Matheus C.S. 05/07/2022
CREATE OR ALTER TRIGGER VSST_EMP_TAUTO_DOC_BI0 FOR VSST_EMP_TAUTODECLARACAO_DOC
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;
BEGIN
  IF ((NEW.BDCODDOC IS NULL) OR (NEW.BDCODDOC = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(X.BDCODDOC) + 1, 1)
       FROM VSST_EMP_TAUTODECLARACAO_DOC X
       WHERE (X.BDCODEMP = NEW.BDCODEMP) and
             (X.BDCODAUTODECLARACAO = NEW.BDCODAUTODECLARACAO)
       INTO :vNovoCod;

       NEW.BDCODDOC = :vNovoCod;
     END
END
^

CREATE OR ALTER trigger JUSTIFICATIVA_INATIVIDADE_bi0 FOR VTPO_JUSTIFICATIVA_INATIVIDADE
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE wCodigo INTEGER;
BEGIN
  SELECT COALESCE((MAX(BDCODJUSTIFICATIVA) + 1), 1) FROM VTPO_JUSTIFICATIVA_INATIVIDADE WHERE BDCODUSU = NEW.BDCODUSU INTO :wCodigo;
  IF ((NEW.BDCODJUSTIFICATIVA IS NULL) OR (NEW.BDCODJUSTIFICATIVA = 0) OR (NEW.BDCODJUSTIFICATIVA < wCodigo)) THEN
    NEW.BDCODJUSTIFICATIVA = :wCodigo;
END
^
--#alt:58948.fim

CREATE OR ALTER TRIGGER VRH_ESOCIAL_TARQUIVO_AI0 FOR VRH_ESOCIAL_TARQUIVO
ACTIVE AFTER INSERT POSITION 0
AS
  declare variable wdata DATE;
  declare variable wnada integer;
  declare variable wcodemp integer;
  declare variable wcpf varchar(18);
  declare variable wnome varchar(70);
  declare variable WCODUSUARIO INTEGER;
  declare variable WCODCADASTRO INTEGER;
begin

  select first 1 current_date from RDB$DATABASE into :wdata;

  if (new.bddataenviarevt > :wdata) then
     insert into VRH_ESOCIAL_TTOTSTATUS(BDCODEMP, BDCOMPETENCIA, BDSTATUS, BDTOTSTATUS) values(new.bdcodemp, new.bdrefarq, 999, 1);
  else
     begin
        if (new.bdstatus = 2) then
           begin
              if (exists(select first 1 bdcodoco from VRH_ESOCIAL_TOCORRENCIA_EVT OCORRENCIA where (OCORRENCIA.BDCODEMP = new.BDCODEMP) and (OCORRENCIA.BDCODEVT = new.BDCODIGO))) then
                 insert into VRH_ESOCIAL_TTOTSTATUS(BDCODEMP, BDCOMPETENCIA, BDSTATUS, BDTOTSTATUS) values (new.bdcodemp, new.bdrefarq, 50, 1);
              else
                 insert into VRH_ESOCIAL_TTOTSTATUS(BDCODEMP, BDCOMPETENCIA, BDSTATUS, BDTOTSTATUS) values (new.bdcodemp, new.bdrefarq, coalesce(new.bdstatus, 0), 1);
           end
        else
           insert into VRH_ESOCIAL_TTOTSTATUS(BDCODEMP, BDCOMPETENCIA, BDSTATUS, BDTOTSTATUS) values (new.bdcodemp, new.bdrefarq, coalesce(new.bdstatus, 0), 1);
     end

  select next value for eSocialAlt from rdb$database into wnada;

  IF ((NEW.BDSTATUS = 2) AND (NEW.BDCODTIPO = 14)) THEN
     begin
       wcodemp = 0;
       select bdcodmatriz from tempresas EMP where EMP.bdcodemp = NEW.BDCODEMP INTO :wcodemp;

       if (coalesce(wcodemp, 0) = 0) then
          wcodemp = new.bdcodemp;

       if ((COALESCE(NEW.BDCODTER, 0) = 0) AND (COALESCE(NEW.BDCODCOL, 0) > 0)) then
          begin
             select COL.BDCODCOL, COL.BDCPFCOL, CAD.BDNOMCOL from VRH_EMP_TCOLCON COL
             left join VRH_EMP_TCOLCON_CAD CAD ON (COL.BDCODEMP = CAD.BDCODEMP AND COL.BDCODCOL = CAD.BDCODCOL AND CAD.BDREFCOL = (select first 1 bdrefcol from vrh_emp_tcolcon_cad
                                                                                                                                   where bdcodemp = COL.BDCODEMP and
                                                                                                                                         bdcodcol = COL.BDCODCOL and
                                                                                                                                         bdrefcol <= NEW.bdrefarq
                                                                                                                                   order by bdrefcol desc))
             WHERE COL.BDCODEMP = NEW.BDCODEMP and COL.BDCODCOL = NEW.BDCODCOL into :WCODCADASTRO, :wcpf, :wnome;
          end
       else if (COALESCE(NEW.BDCODTER, 0) > 0) then
          begin
            SELECT TRF.BDNOMETER FROM TTERCEIRO_REF TRF
            WHERE TRF.BDCODTER = NEW.BDCODTER AND
                  TRF.BDREFEMP = (SELECT MAX(TRF1.BDREFEMP) FROM TTERCEIRO_REF TRF1 WHERE TRF1.BDCODTER = TRF.BDCODTER AND TRF1.BDREFEMP <= NEW.BDREFARQ)
            INTO :WNOME;

            select first 1 RH.BDCODTER, RH.BDCPFMEITER from TTERCEIRO_RH RH where RH.BDCODTER = NEW.BDCODTER and char_length(RH.BDCPFMEITER) = 14 into :WCODCADASTRO, :WCPF;
        
            WCPF = COALESCE(WCPF, '');

            if (WCPF = '') then
              select first 1 C.BDCODTER, C.BDCGCTER from TTERCEIRO C where C.BDCODTER = NEW.BDCODTER into :WCODCADASTRO, :WCPF;

            WCPF = COALESCE(WCPF, '');
          end

       wcpf = coalesce(wcpf, '');

       if (COALESCE(WCODCADASTRO, 0) > 0) then
          begin
            update or insert into VRH_EMP_TDIFERENCA5002 (BDCODMATRIZ, BDCPFCOL, BDREF, BDTIPCODREC, BDMENSAGEM, BDCODCAMPO, BDNOMECOL, BDCODEMP,BDTIPOMSG)
            values (:wcodemp, :wcpf, NEW.BDREFARQ, 1, 'Não houve emissão do totalizador S-5002 nesta competência, portanto o sistema não consegue apontar diferenças e os dados podem divergir do eSocial.',
                    NULL, :wnome, NEW.BDCODEMP,1)
            matching (BDCODMATRIZ, BDCPFCOL, BDREF, BDTIPCODREC);

            WCODUSUARIO = 0;
            SELECT FIRST 1 BDCODUSU FROM TUSUARIO WHERE BDNOMUSU = 'schip' INTO :WCODUSUARIO;

            UPDATE OR INSERT INTO TAUTOMATIZACOES (BDPROCESSO, BDSTATUS, BDINCLUSAO, BDPREVISAO, BDUSUARIO, BDEMPRESA, BDCPF, BDREF, BDAPENASFORAHORARIOCOMERCIAL)
            VALUES (55,0,CURRENT_TIMESTAMP, CAST(DATEADD(MINUTE, 30, CAST('NOW' AS TIMESTAMP)) AS TIMESTAMP), :WCODUSUARIO, :WCODEMP, '', NEW.BDREFARQ, 'FALSE')
            MATCHING (BDPROCESSO, BDSTATUS, BDEMPRESA, BDREF);
          end
     end
end^

CREATE OR ALTER trigger vrh_esocial_tarquivo_bu0 for vrh_esocial_tarquivo
active before update position 0
AS
declare variable wnada integer;
begin
  select next value for eSocialAlt from rdb$database into wnada;
  if (old.BDCODTIPO = 20 and
      new.BDSTATUS in (5, 6, 7)) then
  begin
    delete from VRH_ESOCIAL_FECHAMENTO
    where BDCODEMP = new.BDCODEMP and
          BDREF = new.BDREFARQ and
          BDDATAREAB is null and
          coalesce(BDINTEGRADO, 'FALSE') = 'FALSE' and    
          coalesce(BDANUAL, 'FALSE') = coalesce(new.BDAPURACAOANUAL, 'FALSE');
  end

  if ((old.BDCODTIPO = 20) and
      (new.BDSTATUS = 2) and
      (new.BDSTATUS <> old.BDSTATUS)) then
  /* fechamento */
  begin
    delete from VRH_ESOCIAL_FECHAMENTO
    where BDCODEMP = new.BDCODEMP and
          BDREF = new.BDREFARQ and
          BDDATAREAB is null and
          coalesce(BDINTEGRADO, 'FALSE') = 'FALSE' and    
          coalesce(BDANUAL, 'FALSE') = coalesce(new.BDAPURACAOANUAL, 'FALSE');
    insert into VRH_ESOCIAL_FECHAMENTO (BDCODEMP, BDREF, BDDATA, BDHORA, BDANUAL, BDSEMMOVIMENTO, BDINTEGRADO)
    values (new.BDCODEMP, new.BDREFARQ, 'NOW', 'NOW', coalesce(new.BDAPURACAOANUAL, 'FALSE'), old.BDSEMMOVIMENTO, 'TRUE');
  end

  if ((old.BDCODTIPO = 19) and
      (new.BDSTATUS = 2) and
      (new.BDSTATUS <> old.BDSTATUS)) then
  begin
    update VRH_ESOCIAL_FECHAMENTO
    set BDDATAREAB = 'NOW',
        BDHORAREAB = 'NOW'
    where BDCODEMP = new.BDCODEMP and
          BDREF = new.BDREFARQ and
          BDDATAREAB is null and
          coalesce(BDANUAL, 'FALSE') = coalesce(new.BDAPURACAOANUAL, 'FALSE');
  end

  if ((old.BDCODTIPO = 44) and
      (new.BDSTATUS = 2) and
      (new.BDSTATUS <> old.BDSTATUS)) then
  begin
    delete from VRH_ESOCIAL_FECHAMENTO
    where BDCODEMP = new.BDCODEMP and
          BDREF = new.BDREFARQ and
          coalesce(BDANUAL, 'FALSE') = coalesce(new.BDAPURACAOANUAL, 'FALSE');
    insert into VRH_ESOCIAL_SOLCONTINGENCIA (BDCODEMP, BDREF, BDDATA, BDHORA, BDUSUARIO)
    values (new.BDCODEMP, new.BDREFARQ, 'NOW', 'NOW', (select BDCODUSU
                                                       from SP_GET_USUARIO));
  end

  if ((old.BDCODTIPO = 1) and
      (new.BDSTATUS = 2) and
      (new.BDSTATUS <> old.BDSTATUS) and
      (old.BDMOTIVO = 'Exclusão')) then
  begin
    if (old.BDREFARQ = (select min(BDREFARQ)
                        from VRH_ESOCIAL_TARQUIVO EVTREF
                        inner join TEMPRESAS E on E.BDCODEMP = EVTREF.BDCODEMP
                        where ((E.BDCODEMP = old.BDCODEMP) or (E.BDCODMATRIZ = old.BDCODEMP)) and
                              EVTREF.BDCODTIPO = 1)) then
    begin
      update TEMPRESAS E
      set E.BDEXPINIESOCIAL = 'FALSE'
      where E.BDCODEMP in (select E2.BDCODEMP
                           from TEMPRESAS E2
                           where (E2.BDCODEMP = old.BDCODEMP) or (E2.BDCODMATRIZ = old.BDCODEMP));

      delete from VRH_ESOCIAL_TARQUIVO A
      where A.BDSTATUS = 0 and
            A.BDCODIGO <> old.BDCODIGO and
            A.BDCODEMP in (select A2.BDCODEMP
                           from TEMPRESAS A2
                           where (A2.BDCODEMP = old.BDCODEMP) or (A2.BDCODMATRIZ = old.BDCODEMP));
    end
  end
  else
  if ((old.BDCODTIPO = 2) and
      (new.BDSTATUS = 2) and
      (new.BDSTATUS <> old.BDSTATUS) and
      (old.BDMOTIVO = 'Exclusão')) then
  begin
    if (old.BDREFARQ = (select min(BDREFARQ)
                        from VRH_ESOCIAL_TARQUIVO EVTREF
                        inner join TEMPRESAS E on E.BDCODEMP = EVTREF.BDCODEMP
                        where (E.BDCODEMP = old.BDCODEMP) and
                              (EVTREF.BDCODTIPO = 2) and
                              ((E.BDMATRIZNAOCADSIS = 'TRUE') or (E.BDCODMATRIZ > 0)))) then
    begin
      update TEMPRESAS E
      set E.BDEXPINIESOCIAL = 'FALSE'
      where E.BDCODEMP in (select E2.BDCODEMP
                           from TEMPRESAS E2
                           where (E2.BDCODEMP = old.BDCODEMP));

      delete from VRH_ESOCIAL_TARQUIVO A
      where A.BDSTATUS = 0 and
            A.BDCODIGO <> old.BDCODIGO and
            A.BDCODEMP = old.BDCODEMP;
    end
  end
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_TARQUIVO_AU0 FOR VRH_ESOCIAL_TARQUIVO
ACTIVE AFTER UPDATE POSITION 0
AS
  declare variable wdata DATE;
  declare variable wnada integer;
  declare variable wCodEvtAnterior integer;
  declare variable wtipocat integer;
  declare variable wrecibocat varchar(30);
  declare variable wchavecat integer;
  declare variable wcodcolcat integer;
  declare variable wcodst integer;
  declare variable wcodemp integer;
  declare variable wcpf varchar(18);
  declare variable wnome varchar(70);
  declare variable WCODUSUARIO integer;
  declare variable WCODCADASTRO INTEGER;
begin
  select next value for eSocialAlt from rdb$database into wnada;
  if ((coalesce(new.bdstatus, 0) <> coalesce(old.bdstatus, 0)) or (new.bdcodemp <> old.bdcodemp) or (new.bddataenviarevt <> old.bddataenviarevt) or (new.bdrefarq <> old.bdrefarq)) then
     begin
       select first 1 current_date from RDB$DATABASE into :wdata;
     
       if (old.bddataenviarevt > :wdata) then
          insert into VRH_ESOCIAL_TTOTSTATUS(BDCODEMP, BDCOMPETENCIA, BDSTATUS, BDTOTSTATUS) values (old.bdcodemp, old.bdrefarq, 999, -1);
       else
          begin
             if (old.bdstatus = 2) then
                begin
                   if (exists(select first 1 bdcodoco from VRH_ESOCIAL_TOCORRENCIA_EVT OCORRENCIA where (OCORRENCIA.BDCODEMP = new.BDCODEMP) and (OCORRENCIA.BDCODEVT = old.BDCODIGO))) then
                      insert into VRH_ESOCIAL_TTOTSTATUS(BDCODEMP, BDCOMPETENCIA, BDSTATUS, BDTOTSTATUS) values (new.bdcodemp, new.bdrefarq, 50, 1);
                   else
                      insert into VRH_ESOCIAL_TTOTSTATUS(BDCODEMP, BDCOMPETENCIA, BDSTATUS, BDTOTSTATUS) values (old.bdcodemp, old.bdrefarq, coalesce(old.bdstatus, 0), -1);
                end
             else
               insert into VRH_ESOCIAL_TTOTSTATUS(BDCODEMP, BDCOMPETENCIA, BDSTATUS, BDTOTSTATUS) values (old.bdcodemp, old.bdrefarq, coalesce(old.bdstatus, 0), -1);
          end

       if (new.bddataenviarevt > :wdata) then
          insert into VRH_ESOCIAL_TTOTSTATUS(BDCODEMP, BDCOMPETENCIA, BDSTATUS, BDTOTSTATUS) values (new.bdcodemp, new.bdrefarq, 999, 1);
       else
          begin
             if (new.bdstatus = 2) then
                begin
                   if (exists(select first 1 bdcodoco from VRH_ESOCIAL_TOCORRENCIA_EVT OCORRENCIA where (OCORRENCIA.BDCODEMP = new.BDCODEMP) and (OCORRENCIA.BDCODEVT = new.BDCODIGO))) then
                      insert into VRH_ESOCIAL_TTOTSTATUS(BDCODEMP, BDCOMPETENCIA, BDSTATUS, BDTOTSTATUS) values (new.bdcodemp, new.bdrefarq, 50, 1);
                   else
                      insert into VRH_ESOCIAL_TTOTSTATUS(BDCODEMP, BDCOMPETENCIA, BDSTATUS, BDTOTSTATUS) values (new.bdcodemp, new.bdrefarq, coalesce(new.bdstatus, 0), 1);
                end
             else
                insert into VRH_ESOCIAL_TTOTSTATUS(BDCODEMP, BDCOMPETENCIA, BDSTATUS, BDTOTSTATUS) values (new.bdcodemp, new.bdrefarq, coalesce(new.bdstatus, 0), 1);
          end
     end

  if (coalesce(new.bdstatus, 0) = 4) then
    begin
        select BDCODEVT from SP_PEGAEVT_VINCULADO_SUCESSO(new.bdcodemp, new.bdcodigo) into :wCodEvtAnterior;
        if (:wCodEvtAnterior > 0) then
            begin
                update VRH_EMP_TSITCOL set BDCODEVTINICIO = :wCodEvtAnterior where BDCODEVTINICIO = new.bdcodigo and bdcodemp = new.bdcodemp;
                update VRH_EMP_TSITCOL set BDCODEVTFIM = :wCodEvtAnterior where BDCODEVTFIM = new.bdcodigo and bdcodemp = new.bdcodemp;
                update VRH_EMP_TFERIAS set BDCODEVT = :wCodEvtAnterior where BDCODEVT = new.bdcodigo and bdcodemp = new.bdcodemp;
            end
    end
 
  if ((new.bdstatus = 2) and (new.bdcodtipo = 23)) then
    begin
        update VRH_EMP_TCOL_ADMPREL set BDRECIBO = new.bdrecibo WHERE BDCODEMP = NEW.BDCODEMP and BDCODCOL = NEW.BDCODCOL;
    end

  if ((new.bdstatus = 2) and (new.bdcodtipo = 54)) then
    begin
        update VRH_EMP_TCOL_EXAME_TOX set BDRECIBO = new.bdrecibo WHERE BDCODEMP = NEW.BDCODEMP and BDCODCOL = NEW.BDCODCOL and BDCODIGO = NEW.BDCHAVETOXIC;
    end

  if ((new.bdstatus = 2) and (new.bdcodtipo = 28)) then
    begin
        update VRH_EMP_TCOL_ASO set BDRECIBO = new.bdrecibo WHERE BDCODEMP = NEW.BDCODEMP and BDCODCOL = NEW.BDCODCOL and BDCODASO = NEW.BDCHAVEASO;
    end    
    
  if ((new.bdstatus = 2) and ((new.bdcodtipo = 27) or ((new.bdcodtipo = 38) and (new.bdeventoexclusao = 27)))) then
    begin
      if (new.bdeventoexclusao = 27) then
        begin
          select BDCODCOL, BDCHAVECAT from VRH_ESOCIAL_TARQUIVO ARQ where ARQ.BDCODEMP = NEW.BDCODEMP and ARQ.BDCODIGO = NEW.bdevtexcluido and ARQ.BDCHAVECAT is not null
          into :wcodcolcat, :wchavecat;

          if (wcodcolcat is null) then
            wcodcolcat = 0;

          if (wchavecat is null) then
            wchavecat = 0;

          if (wchavecat <> 0) then
            begin
              select COALESCE(CAT.BDRECIBOESOC,'') BDRECIBOESOC, CAT.BDTIPOCAT from VRH_EMP_TCAT CAT where CAT.BDCODEMP = NEW.BDCODEMP and CAT.BDCODCOL = :wcodcolcat and CAT.BDCHAVE = :wchavecat
              into :wrecibocat, :wtipocat;

              if (wrecibocat is null) then
                wrecibocat = '';

              if (wtipocat is null) then
                wtipocat = 0;

              if (wtipocat = 1) then
                begin
                  if (wrecibocat <> '') then
                    begin
                      update VRH_EMP_TCAT set BDRECIBORETEXC = :wrecibocat, BDRECIBOESOC = new.BDRECIBO
                      WHERE BDCODEMP = NEW.BDCODEMP and BDCODCOL = :wcodcolcat and BDCHAVE = :wchavecat;
                    end
                  else
                     begin
                       update VRH_EMP_TCAT set BDRECIBOESOC = new.BDRECIBO
                       WHERE BDCODEMP = NEW.BDCODEMP and BDCODCOL = :wcodcolcat and BDCHAVE = :wchavecat;
                     end
                end
              else
                begin
                  if (wrecibocat <> '') then
                    begin
                      update VRH_EMP_TCAT set BDRECIBORETEXC = :wrecibocat, BDRECIBOESOC = :wrecibocat, BDNRCAT = :wrecibocat
                      WHERE BDCODEMP = NEW.BDCODEMP and BDCODCOL = :wcodcolcat and BDCHAVE = :wchavecat;
                    end
                  else
                    begin
                      update VRH_EMP_TCAT set BDRECIBOESOC = :wrecibocat, BDNRCAT = :wrecibocat
                      WHERE BDCODEMP = NEW.BDCODEMP and BDCODCOL = :wcodcolcat and BDCHAVE = :wchavecat;
                    end
                end
            end
        end
      else
        begin
          select COALESCE(CAT.BDRECIBOESOC,'') BDRECIBOESOC, CAT.BDTIPOCAT from VRH_EMP_TCAT CAT where CAT.BDCODEMP = NEW.BDCODEMP and CAT.BDCODCOL = NEW.BDCODCOL and CAT.BDCHAVE = NEW.BDCHAVECAT
          into :wrecibocat, :wtipocat;

          if (wrecibocat is null) then
            wrecibocat = '';

          if (wtipocat is null) then
            wtipocat = 0;

          if (wtipocat = 1) then
            begin
              if (wrecibocat <> '') then
                begin
                 update VRH_EMP_TCAT set BDRECIBORETEXC = :wrecibocat, BDRECIBOESOC = new.BDRECIBO
                 WHERE BDCODEMP = NEW.BDCODEMP and BDCODCOL = NEW.BDCODCOL and BDCHAVE = NEW.BDCHAVECAT;
                end
              else
                begin
                 update VRH_EMP_TCAT set BDRECIBOESOC = new.BDRECIBO
                 WHERE BDCODEMP = NEW.BDCODEMP and BDCODCOL = NEW.BDCODCOL and BDCHAVE = NEW.BDCHAVECAT;
                end
            end
          else
            begin
              if (wrecibocat <> '') then
                begin
                  update VRH_EMP_TCAT set BDRECIBORETEXC = :wrecibocat, BDRECIBOESOC = new.BDRECIBO, BDNRCAT = new.BDRECIBO
                  WHERE BDCODEMP = NEW.BDCODEMP and BDCODCOL = NEW.BDCODCOL and BDCHAVE = NEW.BDCHAVECAT;
                end
             else
               begin
                 update VRH_EMP_TCAT set BDRECIBOESOC = new.BDRECIBO, BDNRCAT = new.BDRECIBO
                 WHERE BDCODEMP = NEW.BDCODEMP and BDCODCOL = NEW.BDCODCOL and BDCHAVE = NEW.BDCHAVECAT;
               end
            end
       end
    end

  if ((new.BDSTATUS = 2) and (new.BDCHAVETREINAMENTO is not null)) then
    begin
        update VRH_EMP_TTREINAMENTO set BDRECIBO = new.BDRECIBO WHERE BDCODEMP = NEW.BDCODEMP and BDCODCOL = NEW.BDCODCOL and BDCODTREINAMENTO = NEW.BDCHAVETREINAMENTO;
    end    

  if ((new.BDSTATUS = 2) and (new.BDCHAVEPPP is not null)) then
    begin
        update VSST_EMP_CONDAMB set BDRECIBO = new.BDRECIBO WHERE BDCODEMP = NEW.BDCODEMP and BDCODCOL = NEW.BDCODCOL and BDCHAVE = NEW.BDCHAVEPPP;
    end    

--  IF ((NEW.BDSTATUS <> OLD.BDSTATUS) AND
--      (NEW.BDSTATUS IN (3,4))) THEN
--     EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdrefarq, '4', '', 'TRUE'); -- 4 - Recusado

  -- #141489 Antony R. (01/02/2023)
  if ((new.bdcodtipo = 19) and (new.bdstatus = 2)) then
  begin
    -- Classificação: 01.01.01.02.01.0002 - Descrição: ESOCIAL - S-1299 - Fechamento dos Eventos Periódicos(Retificação)
    wcodst = (select first 1 (bdcodst) from VCT_EMPRESA_TSOLICITATAREFA tar
              inner join VCT_BASE_OBRIGACAO obr on (obr.bdcodobrser = tar.bdcodobrigacao)
              where (tar.bdcodemp = new.bdcodemp) and (tar.bdrefsol = new.bdrefarq) and (obr.bdclassificacao = '01.01.01.02.01.0001') order by bdcodst asc);
    if (wcodst > 0) then
      begin
        insert into VCT_EMPRESA_TSOLICITATAREFA (bdcodemp, bdcodst, bdcodcol, bdcodimp, bdcodobrigacao, bdcodservico, bdcodtipo,
                                                 bddatasol, bdfaturar, bddatasolicitada, bddataprevisao, bddatafim,
                                                 bdserie, bdrefsol, bdquantidade, bdvalorunitario, bdvalordesconto, bdtipodesconto, bdparcelas,
                                                 bdtiposolicitacao, bdvencimento, bdentrega, bdalerta, bdaguard, bdstatusatual)
        select tar.bdcodemp, null as bdcodst, tar.bdcodcol, tar.bdcodimp, (select obr.bdcodobrser from VCT_BASE_OBRIGACAO obr where obr.bdclassificacao = '01.01.01.02.01.0002'),
               tar.bdcodservico, tar.bdcodtipo, current_date, tar.bdfaturar, current_date, tar.bddataprevisao, null,
               tar.bdserie, tar.bdrefsol, tar.bdquantidade, tar.bdvalorunitario, tar.bdvalordesconto, tar.bdtipodesconto, tar.bdparcelas,
               tar.bdtiposolicitacao, tar.bdvencimento, tar.bdentrega, tar.bdalerta, tar.bdaguard, 6
        from VCT_EMPRESA_TSOLICITATAREFA tar
        where (tar.bdcodemp = new.bdcodemp) and (tar.bdcodst = :wcodst);
      end
  end

 -- #141489 Marcos P. (08/09/2025)
  if ((new.bdcodtipo = 19) and (new.bdstatus = 2)) then
  begin
    -- Classificação: 01.01.01.02.02.0002 - Descrição: ESOCIAL – S-2501 - Reclamatória trabalhista – Tributos (A)
    wcodst = (select first 1 (bdcodst) from VCT_EMPRESA_TSOLICITATAREFA tar
              inner join VCT_BASE_OBRIGACAO obr on (obr.bdcodobrser = tar.bdcodobrigacao)
              where (tar.bdcodemp = new.bdcodemp) and (tar.bdrefsol = new.bdrefarq) and (obr.bdclassificacao = '01.01.01.02.02.0002') order by bdcodst asc);
    if (wcodst > 0) then
      begin
        insert into VCT_EMPRESA_TSOLICITATAREFA (bdcodemp, bdcodst, bdcodcol, bdcodimp, bdcodobrigacao, bdcodservico, bdcodtipo,
                                                 bddatasol, bdfaturar, bddatasolicitada, bddataprevisao, bddatafim,
                                                 bdserie, bdrefsol, bdquantidade, bdvalorunitario, bdvalordesconto, bdtipodesconto, bdparcelas,
                                                 bdtiposolicitacao, bdvencimento, bdentrega, bdalerta, bdaguard, bdstatusatual)
        select tar.bdcodemp, null as bdcodst, tar.bdcodcol, tar.bdcodimp, (select obr.bdcodobrser from VCT_BASE_OBRIGACAO obr where obr.bdclassificacao = '01.01.05.0003'),
               tar.bdcodservico, tar.bdcodtipo, current_date, tar.bdfaturar, current_date, tar.bddataprevisao, null,
               tar.bdserie, tar.bdrefsol, tar.bdquantidade, tar.bdvalorunitario, tar.bdvalordesconto, tar.bdtipodesconto, tar.bdparcelas,
               tar.bdtiposolicitacao, tar.bdvencimento, tar.bdentrega, tar.bdalerta, tar.bdaguard, 6
        from VCT_EMPRESA_TSOLICITATAREFA tar
        where (tar.bdcodemp = new.bdcodemp) and (tar.bdcodst = :wcodst);
      end
  end


  -- Baixa automática das tarefas
  if ((new.bdcodtipo = 20) and (new.bdstatus = 2)) then
  begin
    if ((new.bdapuracaoanual is null) or (upper(new.bdapuracaoanual) = 'FALSE')) then
    begin
      -- Classificação: 01.01.01.02.01.0001 - Descrição: ESOCIAL - S-1299 - Fechamento dos Eventos Periódicos
      wcodst = (select first 1 (bdcodst) from VCT_EMPRESA_TSOLICITATAREFA tar
               inner join VCT_BASE_OBRIGACAO obr on (obr.bdcodobrser = tar.bdcodobrigacao)
               where (tar.bdcodemp = new.bdcodemp) and (tar.bdrefsol = new.bdrefarq) and (obr.bdclassificacao = '01.01.01.02.01.0001') and (tar.bddatafim is null) order by bdcodst asc);
      if (wcodst > 0) then
      begin
        update VCT_EMPRESA_TSOLICITATAREFA x set x.bddatafim = current_date
        where (x.bdcodemp = new.bdcodemp) and (x.bdcodst = :wcodst);
   
--        insert into VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP,BDCODST,BDCODUSURESPONSAVEL,BDDATA,BDHORA,BDSTATUS,BDOBSERVACAO)
--        values (new.bdcodemp,:wcodst,1,current_date,current_time, 4,'Finalizada automaticamente pelo processo de transmissão do esocial.');
        insert into VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP,BDCODST,BDCODUSURESPONSAVEL,BDDATA,BDHORA,BDSTATUS,BDCODBHS)
        values (new.bdcodemp,:wcodst,1,current_date,current_time, 4, 38);
      end
        
      wcodst = 0;
        
      -- Classificação: 01.01.01.02.01.0002 - Descrição: ESOCIAL - S-1299 - Fechamento dos Eventos Periódicos(Retificação)
      wcodst = (select first 1 (bdcodst) from VCT_EMPRESA_TSOLICITATAREFA tar
               inner join VCT_BASE_OBRIGACAO obr on (obr.bdcodobrser = tar.bdcodobrigacao)
               where (tar.bdcodemp = new.bdcodemp) and (tar.bdrefsol = new.bdrefarq) and (obr.bdclassificacao = '01.01.01.02.01.0002') and (tar.bddatafim is null) order by bdcodst asc);
      if (wcodst > 0) then
      begin
        update VCT_EMPRESA_TSOLICITATAREFA x set x.bddatafim = current_date
        where (x.bdcodemp = new.bdcodemp) and (x.bdcodst = :wcodst);

--        insert into VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP,BDCODST,BDCODUSURESPONSAVEL,BDDATA,BDHORA,BDSTATUS,BDOBSERVACAO)
--        values (new.bdcodemp,:wcodst,1,current_date,current_time, 4,'Finalizada automaticamente pelo processo de transmissão do esocial.');
        insert into VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP,BDCODST,BDCODUSURESPONSAVEL,BDDATA,BDHORA,BDSTATUS,BDCODBHS)
        values (new.bdcodemp,:wcodst,1,current_date,current_time, 4, 38);
      end
    end --
    else
    begin
      -- Classificação: 01.01.01.02.01.0003 - Descrição: ESOCIAL - S-1299 - Fechamento dos Eventos Periódicos(Anual 13º salário)
      wcodst = (select first 1 (bdcodst) from VCT_EMPRESA_TSOLICITATAREFA tar
               inner join VCT_BASE_OBRIGACAO obr on (obr.bdcodobrser = tar.bdcodobrigacao)
               where (tar.bdcodemp = new.bdcodemp) and (substring(tar.bdrefsol from 1 for 4) = substring(new.bdrefarq from 1 for 4)) and (obr.bdclassificacao = '01.01.01.02.01.0003') and (tar.bddatafim is null) order by bdcodst asc);
      if (wcodst > 0) then
      begin
        update VCT_EMPRESA_TSOLICITATAREFA x set x.bddatafim = current_date
        where (x.bdcodemp = new.bdcodemp) and (x.bdcodst = :wcodst);

--        insert into VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP,BDCODST,BDCODUSURESPONSAVEL,BDDATA,BDHORA,BDSTATUS,BDOBSERVACAO)
--        values (new.bdcodemp,:wcodst,1,current_date,current_time, 4,'Finalizada automaticamente pelo processo de transmissão do esocial.');
        insert into VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP,BDCODST,BDCODUSURESPONSAVEL,BDDATA,BDHORA,BDSTATUS,BDCODBHS)
        values (new.bdcodemp,:wcodst,1,current_date,current_time, 4, 38);
      end
    end
  end
  
  if (new.bdstatus <> old.bdstatus) then
     begin
       update VRH_ESOCIAL_DEMONS_EVT X set x.bdstatus = new.bdstatus where x.bdcodemp = new.bdcodemp and x.bdcodevt = new.bdcodigo; -- atualiza o status dos eventos

       if ((new.bdstatus = 2) and (new.bdcodtipo in (3, 11, 34, 37, 38))) then --// S-1010, S-1200, S-2299, S-2399, S-3000
          begin
            execute procedure sp_cria_inconf_s1010(new.bdcodemp, new.bdcodcol, new.bdcodigo, new.bdcodtipo, new.bdrefarq, new.bdcodver);
          end
     end

  IF (((NEW.BDSTATUS <> OLD.BDSTATUS) AND (NEW.BDSTATUS = 2)) AND (NEW.BDCODTIPO = 14)) THEN
     begin
       wcodemp = 0;

       select bdcodmatriz from tempresas EMP where EMP.bdcodemp = NEW.BDCODEMP INTO :wcodemp;

       if (coalesce(wcodemp, 0) = 0) then
          wcodemp = new.bdcodemp;

       if ((COALESCE(NEW.BDCODTER, 0) = 0) AND (COALESCE(NEW.BDCODCOL, 0) > 0)) then
          begin
             select COL.BDCODCOL, COL.BDCPFCOL, CAD.BDNOMCOL from VRH_EMP_TCOLCON COL
             left join VRH_EMP_TCOLCON_CAD CAD ON (COL.BDCODEMP = CAD.BDCODEMP AND COL.BDCODCOL = CAD.BDCODCOL AND CAD.BDREFCOL = (select first 1 bdrefcol from vrh_emp_tcolcon_cad
                                                                                                                                   where bdcodemp = COL.BDCODEMP and
                                                                                                                                         bdcodcol = COL.BDCODCOL and
                                                                                                                                         bdrefcol <= NEW.bdrefarq
                                                                                                                                   order by bdrefcol desc))
             WHERE COL.BDCODEMP = new.bdcodemp and COL.BDCODCOL = NEW.BDCODCOL into :wcodcadastro, :wcpf, :wnome;
          end
       else if (COALESCE(NEW.BDCODTER, 0) > 0) then
          begin
            SELECT TRF.BDNOMETER FROM TTERCEIRO_REF TRF
            WHERE TRF.BDCODTER = NEW.BDCODTER AND
                  TRF.BDREFEMP = (SELECT MAX(TRF1.BDREFEMP) FROM TTERCEIRO_REF TRF1 WHERE TRF1.BDCODTER = TRF.BDCODTER AND TRF1.BDREFEMP <= NEW.BDREFARQ)
            INTO :WNOME;

            select first 1 RH.BDCODTER, RH.BDCPFMEITER from TTERCEIRO_RH RH where RH.BDCODTER = NEW.BDCODTER and char_length(RH.BDCPFMEITER) = 14 into :WCODCADASTRO, :WCPF;
        
            WCPF = COALESCE(WCPF, '');

            if (WCPF = '') then
              select first 1 C.BDCODTER, C.BDCGCTER from TTERCEIRO C where C.BDCODTER = NEW.BDCODTER into :WCODCADASTRO, :WCPF;

            WCPF = COALESCE(WCPF, '');
          end

       wcpf = coalesce(wcpf, '');

       if (COALESCE(WCODCADASTRO, 0) > 0) then
          begin
            update or insert into VRH_EMP_TDIFERENCA5002 (BDCODMATRIZ, BDCPFCOL, BDREF, BDTIPCODREC, BDMENSAGEM, BDCODCAMPO, BDNOMECOL, BDCODEMP, BDTIPOMSG)
            values (:wcodemp, :wcpf, NEW.BDREFARQ, 1, 'Não houve emissão do totalizador S-5002 nesta competência, portanto o sistema não consegue apontar diferenças e os dados podem divergir do eSocial.', NULL, :wnome,
                    NEW.BDCODEMP,1)
            matching (BDCODMATRIZ, BDCPFCOL, BDREF, BDTIPCODREC);

            WCODUSUARIO = 0;
            SELECT FIRST 1 BDCODUSU FROM TUSUARIO WHERE BDNOMUSU = 'schip' INTO :WCODUSUARIO;

            UPDATE OR INSERT INTO TAUTOMATIZACOES (BDPROCESSO, BDSTATUS, BDINCLUSAO, BDPREVISAO, BDUSUARIO, BDEMPRESA, BDCPF, BDREF, BDAPENASFORAHORARIOCOMERCIAL)
            VALUES (55,0,CURRENT_TIMESTAMP, CAST(DATEADD(MINUTE, 30, CAST('NOW' AS TIMESTAMP)) AS TIMESTAMP), :WCODUSUARIO, :WCODEMP, '', NEW.BDREFARQ, 'FALSE')
            MATCHING (BDPROCESSO, BDSTATUS, BDEMPRESA, BDREF);

          end
     end

end
^

CREATE OR ALTER trigger vrh_esocial_tarquivo_ad0 for vrh_esocial_tarquivo
active after delete position 0
AS
  declare variable wdata DATE;
  declare variable wnada integer;
begin
  select next value for eSocialAlt from rdb$database into wnada;
  select first 1 current_date from RDB$DATABASE into :wdata;

  if (old.bddataenviarevt > :wdata) then
     insert into VRH_ESOCIAL_TTOTSTATUS(BDCODEMP, BDCOMPETENCIA, BDSTATUS, BDTOTSTATUS) values(old.bdcodemp, old.bdrefarq, 999, -1);
  else
     insert into VRH_ESOCIAL_TTOTSTATUS(BDCODEMP, BDCOMPETENCIA, BDSTATUS, BDTOTSTATUS) values(old.bdcodemp, old.bdrefarq, coalesce(old.bdstatus, 0), -1);
end^

CREATE OR ALTER trigger vrh_esocial_tarquivo_bd0 for vrh_esocial_tarquivo
active before delete position 0
AS
declare variable wnada integer;
begin
  select next value for eSocialAlt from rdb$database into wnada;
   /* S-2230 */
  if (old.bdcodtipo = 29) then
    begin
        update VRH_EMP_TSITCOL set BDCODEVTINICIO = null where BDCODEMP = old.bdcodemp and BDCODEVTINICIO = old.bdcodigo;
        update VRH_EMP_TSITCOL set BDCODEVTFIM = null where BDCODEMP = old.bdcodemp and BDCODEVTFIM = old.bdcodigo;
        update VRH_EMP_TFERIAS set BDCODEVT = null where BDCODEMP = old.bdcodemp and BDCODEVT = old.bdcodigo;
    end
end^

--alt:11587 - 07/07/2015 - Nova trigger para controle da chave da tabela. Pedro
CREATE OR ALTER TRIGGER VSUC_EMPRESAS_TPRE_ECF_Y665_BI0 FOR VSUC_EMPRESAS_TPRE_ECF_Y665
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE wCodigo INTEGER;
BEGIN
  SELECT COALESCE(MAX(BDCHAVE), 0) +1 FROM VSUC_EMPRESAS_TPRE_ECF_Y665 WHERE BDCODEMP = NEW.BDCODEMP INTO :wCodigo;
  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0) OR (NEW.BDCHAVE < wCodigo)) THEN
    NEW.BDCHAVE = :wCodigo;
END
^

--alt:11995 - 11/08/2015 - Criada trigger para deletar os lançamentos criados automaticamente pela integração do contábil para o lalur agora que não há mais a chave de ligação. Pedro
CREATE OR ALTER TRIGGER vlal_imp_contablalur_bd0 FOR vlal_empresas_imp_contablalur
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  IF (OLD.bdtipo = 0) THEN -- Lucro Real (A parte do lucro presumido existe a chave de ligação com o cascade habilitado)
     BEGIN
       DELETE FROM VLAL_EMPRESAS_TLLA WHERE BDCODEMP = OLD.BDCODEMP AND BDTIPLAN = 400 AND
              EXTRACT(YEAR FROM BDDATLLA)||LPAD(EXTRACT(MONTH FROM BDDATLLA), 2, '0') BETWEEN OLD.BDREFINICIAL AND OLD.BDREFFINAL;
     END
END
^

--alt:4936 - 16/11/2015 - Criada trigger para controle da chave da nova tabela. Pedro
CREATE OR ALTER TRIGGER tidiomas_bi0 FOR tidiomas
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE wCodigo INTEGER;
BEGIN
  IF ((NEW.BDCODIDIOMA IS NULL) OR (NEW.BDCODIDIOMA = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(BDCODIDIOMA), 0) +1 FROM TIDIOMAS INTO :wCodigo;
      NEW.BDCODIDIOMA = :wCodigo;
    END
END
^

--#alt:12280 - Criada trigger para controle da chave da nova tabela. Ana - 04/10/2016
CREATE OR ALTER TRIGGER tr_bf_insert_vsuc_tconfig_imp_c FOR vsuc_tconfig_imp_cta
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE wCodigo INTEGER;
BEGIN
  wCodigo = 0;
  IF ((NEW.BDCODIMPCTA IS NULL) OR (NEW.BDCODIMPCTA = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(BDCODIMPCTA)+1), 1)
       FROM VSUC_TCONFIG_IMP_CTA
       INTO wCodigo;

       NEW.BDCODIMPCTA = wCodigo;
     END
END
^

/* Trigger: VLAL_CONF_TRIMESTRAL_BI0 */
CREATE OR ALTER TRIGGER VLAL_CONF_TRIMESTRAL_BI0 FOR VLAL_CONF_TRIMESTRAL
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(conf.BDCHAVE) + 1, 1) FROM VLAL_CONF_TRIMESTRAL conf WHERE conf.BDCODCONTABLALUR = NEW.BDCODCONTABLALUR INTO NEW.BDCHAVE;
     END
END
^

CREATE OR ALTER TRIGGER VLAL_EMPRESAS_PREP_CONT_BI0 FOR VLAL_EMPRESAS_PREP_CONT
ACTIVE BEFORE INSERT POSITION 0
AS
begin
 IF (NEW.BDCHAVE IS NULL OR NEW.BDCHAVE = 0) THEN
   NEW.BDCHAVE = coalesce((select first 1 BDCHAVE from vlal_empresas_prep_cont order by BDCHAVE desc),0)+1;
end^

CREATE OR ALTER TRIGGER VTPO_ATIVIDADE_EXE_BI0 FOR VTPO_ATIVIDADE_EXE
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (NEW.BDTIPOATI = 1) THEN -- 1 Padrão SCI
    BEGIN
       SELECT COALESCE(MAX(BDCODATI) + 1, 1) FROM VTPO_ATIVIDADE_EXE WHERE BDTIPOATI = 1 INTO NEW.BDCODATI; -- 1 - Padrão SCI | 2 - Manual
    END
  ELSE -- 2 Manual
  IF (NEW.BDCODATI IS NULL OR NEW.BDCODATI <= 100) THEN -- Foi deixado do código 1 ao 100 exclusivo para SCI
     BEGIN
       SELECT COALESCE(MAX(BDCODATI) + 1, 1) FROM VTPO_ATIVIDADE_EXE WHERE BDTIPOATI = 2 INTO NEW.BDCODATI; -- 1 - Padrão SCI | 2 - Manual
       --Deixar um leque de 100 registros para uso exclusivo da SCI
       IF (NEW.BDCODATI <= 100) THEN
          NEW.BDCODATI = 101;
     END
END^

/* Trigger: TVALIDACAOSPED_AGENDAMENTOS_BI */
CREATE OR ALTER TRIGGER TVALIDACAOSPED_AGENDAMENTOS_BI FOR TVALIDACAOSPED_AGENDAMENTOS
ACTIVE BEFORE INSERT POSITION 0
as
begin
  if (new.bdid is null or new.bdid = 0) then
  begin
    new.bdid = gen_id(gen_tvalidacaosped_agendamentos_id,1);
    new.bdordem = new.bdid;
  end
end
^

CREATE OR ALTER TRIGGER VTPO_ATIVIDADE_EXE_REGISTRO_BI0 FOR VTPO_ATIVIDADE_EXE_REGISTRO
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vCodigo bigint;
  declare variable vconnectid integer;
BEGIN
--  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
--  begin
--    select coalesce(max(bdchave), 0) + 1 from vtpo_atividade_exe_registro into :vcodigo;
--    new.bdchave = vcodigo;
--  end
-- Gilberto - 10/07/2024 - #204416 - Deve executar pela generator, porque inserções paralelas podem ocasionar deadlook
  vcodigo = 1;
  if (GEN_ID(GEN_VTPO_ATIVIDADE_EXE_REGISTRO,0)=0) then
     select coalesce(max(bdchave),0)+1 from vtpo_atividade_exe_registro into :vcodigo;
  NEW.bdchave = GEN_ID(GEN_VTPO_ATIVIDADE_EXE_REGISTRO, :vcodigo);


  IF (NEW.BDCODATI IS NULL OR NEW.BDCODATI = 0)THEN
     NEW.BDCODATI = 2;

-- Gilberto - 26/09/2025 - #232639 - Com a alteração do cálculo da distorção dos tempos,
--                                   podemos deixar o sistema lançar tempo ocioso sobre tempo automático,
--                                   e evitar que registros automáticos não sejam computados por conta desse erro
--  /* Gilberto - 26/03/2021 - W148169 - Quando inserir registro automático que esteja no mesmo tempo do registro ocioso, não gravar */
--  if (new.bdtiporegistro = 0) then
--  begin
--    vcodigo = null;
--    select first 1 bdchave from vtpo_atividade_exe_registro x
--    where ((x.bdcodusu = new.bdcodusu) and (x.bdtiporegistro = 1) and (x.bdchave <> new.bdchave))
--    and ((x.bddataini >= new.bddataini) and (x.bddatafin <= new.bddatafin))
--    and (((x.bdhoraini >= new.bdhoraini) and (x.bdhorafin <= new.bdhorafin)) or ((x.bdhoraini <= new.bdhoraini) and (x.bdhorafin >= new.bdhorafin)))
--    into :vcodigo;
--    if (coalesce(vcodigo, 0) > 0) then
--       exception EX_TEMPORIZADOR_ATIVIDADES;
--  end

-- Gilberto - 13/01/2025 - #237931
--  select first 1 bdhostid, bdconnectid from vtpo_gethostid into :vcodigo, :vconnectid;
  SELECT first 1 CAST((TRIM(rdb$get_context('USER_SESSION', 'W_HOSTID'))) AS INTEGER),
                 CAST((TRIM(rdb$get_context('USER_SESSION', 'W_CONNECTID'))) AS INTEGER)
  FROM rdb$database into :vcodigo, :vconnectid;
  
  if (new.bdhostid is null) then
     new.bdhostid = :vcodigo;
  if (new.bdconnectid is null) then
     new.bdconnectid = :vconnectid;
END^

CREATE or alter trigger vtpo_base_userhost_bi0 for vtpo_base_userhost
active before insert position 0
AS
  declare variable vid integer;
begin
  if ((new.bdid is null) or (new.bdid = 0)) then
  begin
    select first 1 bdid from vtpo_base_userhost order by bdid desc into :vid;
    new.bdid = coalesce(vid, 0) +1;
  end
end^

create or alter procedure VTPO_GETHOSTID
as
declare variable VHOST varchar(255);
declare variable VUSER varchar(255);
declare variable VRETURNING integer;
declare variable BDHOSTID integer;
declare variable BDCONNECTID integer;
begin
  SELECT first 1  CAST((TRIM(rdb$get_context('USER_SESSION', 'W_HOSTID'))) AS INTEGER),
                  CAST((TRIM(rdb$get_context('USER_SESSION', 'W_CONNECTID'))) AS INTEGER)
  FROM rdb$database into :BDHOSTID, :BDCONNECTID;

  if ((coalesce(BDHOSTID,0)=0)or(coalesce(BDCONNECTID,0)=0)) then
  begin
    SELECT first 1 X.BDCONNECTID, X.BDHOST, X.BDUSER, uh.bdid
    from(SELECT current_connection as BDCONNECTID, MON$TIMESTAMP as BDCONNECTTIME,
                MON$REMOTE_HOST BDHOST, MON$REMOTE_OS_USER BDUSER
         FROM MON$ATTACHMENTS
         where MON$ATTACHMENT_ID=current_connection) X
    left join vtpo_base_userhost uh on(uh.bdhost=x.bdhost and uh.bduser=x.bduser)
    into :BDCONNECTID, :vhost, :vuser, :BDHOSTID;
    if (coalesce(BDHOSTID,0)=0) then
    begin
      insert into vtpo_base_userhost(bdhost,bduser)values(:vhost,:vuser)returning bdid into :vreturning;
      bdhostid = vreturning;
    end
  
    rdb$set_context('USER_SESSION', 'W_HOSTID', :bdhostid);
    rdb$set_context('USER_SESSION', 'W_CONNECTID', :BDCONNECTID);
  end
end^

--#alt:15854 - Criada trigger para controle da chave da nova tabela. Ana - 13/01/2017
CREATE OR ALTER TRIGGER tr_bf_insert_vsuctconfigimpptro FOR vsuc_tconfig_imp_platroca
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE wCodigo INTEGER;
BEGIN
  wCodigo = 0;
  IF ((NEW.BDCODIMPPLATROCA IS NULL) OR (NEW.BDCODIMPPLATROCA = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(BDCODIMPPLATROCA)+1), 1)
       FROM VSUC_TCONFIG_IMP_PLATROCA
       INTO wCodigo;

       NEW.BDCODIMPPLATROCA = wCodigo;
     END
END^

--Sol: 17003 Morgana. 21/03/2017. Gerar chave para o cadastro de observações.
CREATE OR ALTER TRIGGER vfin_esc_tconfigvarobs_bi0 FOR vfin_esc_tconfigvarobs
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF ((NEW.bdchaveconfig = 0) OR (NEW.bdchaveconfig IS NULL)) THEN
     BEGIN
       SELECT COALESCE(MAX(conf.bdchaveconfig)+1,1) FROM VFIN_ESC_TCONFIGVAROBS conf
       WHERE conf.bdcodesc = NEW.bdcodesc INTO NEW.bdchaveconfig;
     END
END
^

CREATE OR ALTER TRIGGER TACESSOSITEGOV_BI0 FOR TACESSOSITEGOV
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF ((NEW.bdcodigo IS NULL) OR (NEW.bdcodigo = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(BDCODIGO) + 1, 1) FROM tacessositegov INTO :vcod;
      NEW.bdcodigo = :vcod;
    END

END
^

CREATE OR ALTER TRIGGER TINDVAL_BIU0 FOR TINDVAL
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
BEGIN
  NEW.BDDATAIND = CAST(LPAD(SUBSTRING(NEW.BDREFIND FROM 5 FOR 2), 2, '01') ||'/'|| REPLACE(CASE WHEN CHAR_LENGTH(NEW.BDREFIND) > 6 THEN OVERLAY(NEW.BDREFIND PLACING '' FROM 1 FOR 6) ELSE '01' END, '00', '01') ||'/'|| OVERLAY(NEW.BDREFIND PLACING '' FROM 5 FOR 4) AS DATE);
END
^

CREATE OR ALTER TRIGGER PLANOS_TPLA_ECF_BIU0 FOR PLANOS_TPLA_ECF
ACTIVE BEFORE INSERT /*OR UPDATE*/ POSITION 0  --#alt:18406 - Estava gerando erro quando executava o delete na alteração. Ana - 24/04/2017
AS
BEGIN
  --alt:11501 - Criada trigger para deletar os registros que ficariam vazios (sem grupo e conta referencial). Pedro
  IF ((NEW.BDCODTPLAREF IS NULL) AND (NEW.BDCODGRUPOCTA IS NULL)) THEN
    DELETE FROM PLANOS_TPLA_ECF WHERE BDCODPLAPADRAOREF = NEW.BDCODPLAPADRAOREF
                                  AND BDCODPLAPADRAO = NEW.BDCODPLAPADRAO
                                  AND BDCODTPLA = NEW.BDCODTPLA
                                  AND BDANO = NEW.BDANO;
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTAB_SN_SERVICO_VI_BI FOR VEF_BASE_TTAB_SN_SERVICO_VI
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vCODCONFSIMPNAC INTEGER;
  DECLARE VARIABLE vNUMFAIXA INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumfaixa IS NULL) OR (NEW.bdnumfaixa = 0)) THEN
    BEGIN
      IF ((NEW.bdcodconfsimpnac IS NULL) OR (NEW.bdcodconfsimpnac = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdcodconfsimpnac)), 1) FROM vef_base_tconf_sn  INTO vcodconfsimpnac;
          NEW.bdcodconfsimpnac = vcodconfsimpnac;
        END

       SELECT COALESCE((MAX(bdnumfaixa)+1), 1) FROM vef_base_ttab_sn_servico_vi
       WHERE bdcodconfsimpnac = NEW.bdcodconfsimpnac INTO vnumfaixa;
       NEW.bdnumfaixa = vnumfaixa;
    END
  ELSE
    BEGIN
       IF ((NEW.bdcodconfsimpnac IS NULL) OR (NEW.bdcodconfsimpnac = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdcodconfsimpnac)), 1) FROM vef_base_tconf_sn  INTO vcodconfsimpnac;
          NEW.bdcodconfsimpnac = vcodconfsimpnac;
        END

       SELECT bdnumfaixa FROM vef_base_ttab_sn_servico_vi
       WHERE (bdnumfaixa = NEW.bdnumfaixa) AND (bdcodconfsimpnac = NEW.bdcodconfsimpnac) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumfaixa)+1), 1) FROM vef_base_ttab_sn_servico_vi WHERE (bdcodconfsimpnac = NEW.bdcodconfsimpnac) INTO vnumfaixa;
           NEW.bdnumfaixa = vnumfaixa;
         END

    END
END
^

CREATE OR ALTER TRIGGER CENTROS_TPCC_BD0 FOR CENTROS_TPCC
ACTIVE BEFORE DELETE POSITION 0 
AS
  DECLARE VARIABLE vlength INTEGER;
BEGIN
  IF (OLD.bdtipcta = 0) THEN
     BEGIN
       vlength = strlen(OLD.bdctalon);

       DELETE FROM centros_tpcc
       WHERE bdcodcentro = OLD.bdcodcentro
       AND SUBSTRING(bdctalon FROM 1 FOR :vlength) = OLD.bdctalon
       AND bdctalon <> OLD.bdctalon;

       IF (EXISTS(SELECT * FROM centros_tpcc
                  WHERE bdcodcentro = OLD.bdcodcentro
                  AND SUBSTRING(bdctalon FROM 1 FOR :vlength) = OLD.bdctalon
                  AND bdctalon <> OLD.bdctalon)) THEN
          EXCEPTION nao_excluir_titulo;

     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSINDTRAB_PERC_BI0 FOR VRH_BASE_TSINDTRAB_PERC
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF ((NEW.bdcodsin_p IS NULL) OR (NEW.bdcodsin_p = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodsin_p) + 1, 1) FROM vrh_base_tsindtrab_perc INTO :vcod;
       NEW.bdcodsin_p = :vcod;
     END

  NEW.bdapesin_p = UPPER(NEW.bdapesin_p);
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSINDTRAB_PERC_BU0 FOR VRH_BASE_TSINDTRAB_PERC
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  NEW.bdapesin_p = UPPER(NEW.bdapesin_p);
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRESCISAO_AD0 FOR VRH_EMP_TRESCISAO
ACTIVE AFTER DELETE POSITION 0
AS
  DECLARE VARIABLE vcodrep INTEGER;
  DECLARE VARIABLE vcodobr INTEGER;
  DECLARE VARIABLE vcodusu INTEGER;
  declare variable vCODST integer;
BEGIN
  vcodusu = 0;
  SELECT BDCODUSU FROM SP_GET_USUARIO INTO :vcodusu;

  IF (vcodusu IS NOT NULL AND vcodusu <> 0) THEN
     BEGIN
       /* Exclui a tarefa de exportação para seguro desemprego */
       vcodrep = 0;
       SELECT BDCODREP FROM TREPOSITORIO WHERE BDCHAVESCI = 17 INTO :vcodrep;
       IF (vcodrep IS NOT NULL AND vcodrep <> 0) THEN
          BEGIN
            vcodobr = 0;
            SELECT FIRST 1 Y.BDCODOBRIGACAO
            FROM ttela_sistema X
            JOIN VCT_CONFIG_TELAOBRSER Y ON (Y.BDCODTELA = X.bdcodtelasis)
            WHERE UPPER(X.bdnometela) = 'TFRRELGERADORRELATORIORH-'||:vcodrep INTO :vcodobr;
            IF (vcodobr IS NOT NULL AND vcodobr <> 0) THEN
               BEGIN
                 DELETE FROM vct_empresa_tsolicitatarefa
                 WHERE bdcodemp = OLD.bdcodemp AND bdcodusu = :vcodusu AND bdcodcol = OLD.bdcodcol AND bdcodobrigacao = :vcodobr AND bdcodtipo = 501 AND
                       bddatasol = OLD.bddatanotif AND bddatasolicitada = OLD.bddatarescisao AND bddataprevisao = OLD.bddatapagrescisao;
               END
          END

       /* Exclui a tarefa de exportação para GRRF */
       vcodobr = 0;
       SELECT FIRST 1 Y.BDCODOBRIGACAO
       FROM ttela_sistema X
       JOIN VCT_CONFIG_TELAOBRSER Y ON (Y.BDCODTELA = X.bdcodtelasis)
       WHERE UPPER(X.bdnometela) = 'TFRPROCESSOEXPORTACAOGRRF' INTO :vcodobr;
       IF (vcodobr IS NOT NULL AND vcodobr <> 0) THEN
          BEGIN
            DELETE FROM vct_empresa_tsolicitatarefa
            WHERE bdcodemp = OLD.bdcodemp AND bdcodusu = :vcodusu AND bdcodcol = OLD.bdcodcol AND bdcodobrigacao = :vcodobr AND bdcodtipo = 501 AND
                  bddatasol = OLD.bddatanotif AND bddatasolicitada = OLD.bddatarescisao AND bddataprevisao = OLD.bddatapaggrfc;
          END

     END

  -- Sol: 138078 Morgana. 19/06/2020. Finalizar tarefas de seguro desemprego e FGTS rescisório.
  -- Gilberto - 25/06/2020 - quando não há ou não encontra a tarefas, o campo BDCODST retorna nulo, ocorrendo erro na exclusão da recisão
  select max(bdcodst) bdcodst from vct_empresa_tsolicitatarefa where bdcodemp = old.bdcodemp and bdcodcolvinc = old.bdcodcol and bdcodobrigacao = 6 and bdrefsol = old.bdrefrescisao into :vcodst;
  if (vcodst is not null) then
  begin
--    INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODSITWEB)
    INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDCODBHS, BDCODSITWEB)
    VALUES (OLD.bdcodemp, (select max(bdcodst) bdcodst from vct_empresa_tsolicitatarefa where bdcodemp = old.bdcodemp
    and bdcodcolvinc = old.bdcodcol and bdcodobrigacao = 6 and bdrefsol = old.bdrefrescisao), null, :vcodusu, CURRENT_DATE, CURRENT_TIME, 4,
--    'Finalizada pelo sistema pela exclusão da rescisão do colaborador.', 2);
    39, 2);
  end

  select max(bdcodst) bdcodst from vct_empresa_tsolicitatarefa where bdcodemp = old.bdcodemp and bdcodcolvinc = old.bdcodcol and bdcodimp = 104 and bdrefsol = old.bdrefrescisao into :vcodst;
  if (vcodst is not null) then
  begin
--    INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODSITWEB)
    INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDCODBHS, BDCODSITWEB)
    VALUES (OLD.bdcodemp, (select max(bdcodst) bdcodst from vct_empresa_tsolicitatarefa where bdcodemp = old.bdcodemp
    and bdcodcolvinc = old.bdcodcol and bdcodimp = 104 and bdrefsol = old.bdrefrescisao), null, :vcodusu, CURRENT_DATE, CURRENT_TIME, 4,
--    'Finalizada pelo sistema pela exclusão da rescisão do colaborador.', 2);
    39, 2);
  end

  -- Exclui convocação, caso seja intermitente e a convocação seja apenas para informar a rescisão
  vcodrep = null;
  select first 1 BDCODCONTTI from VRH_EMP_TINTERMITENTE where BDCODEMP = old.bdcodemp and BDCODCOL = old.bdcodcol and upper(coalesce(BDAPENASRESCISAO, 'FALSE')) = 'TRUE' into :vcodrep;
  if (coalesce(vcodrep, 0) > 0) then
     begin
       delete from VRHF_EMP_TFOLHAINT where BDCODEMP = old.bdcodemp and BDCODCOL = old.bdcodcol and BDCODCONTTI = :vcodrep;
       delete from VRHF_EMP_TFOLHATOMINT where BDCODEMP = old.bdcodemp and BDCODCOL = old.bdcodcol and BDCODCONTTI = :vcodrep;
       delete from VRH_EMP_TINTERMITENTE where BDCODEMP = old.bdcodemp and BDCODCOL = old.bdcodcol and BDCODCONTTI = :vcodrep;
     end
END^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_PARTIDA_AD0 FOR VRH_EMP_TCOLCON_PARTIDA
ACTIVE AFTER DELETE POSITION 0
AS
  DECLARE VARIABLE vcodobr INTEGER;
  DECLARE VARIABLE vdesc VARCHAR(100);
  DECLARE VARIABLE vp1 INTEGER;
  DECLARE VARIABLE vp2 INTEGER;
  DECLARE VARIABLE vcodusu INTEGER;
BEGIN
  IF (UPPER(OLD.BDSEGDESCOL) = 'TRUE') THEN
     BEGIN
       vcodusu = 0;
       SELECT BDCODUSU FROM SP_GET_USUARIO INTO :vcodusu;
       IF (vcodusu IS NOT NULL AND vcodusu <> 0) THEN
          BEGIN
            vcodobr = 0;
            vdesc = '';

            FOR SELECT Y.BDCODOBRIGACAO, UPPER(Z.BDDESCRICAO) BDDESCRICAO
                FROM ttela_sistema X
                JOIN VCT_CONFIG_TELAOBRSER Y ON (Y.BDCODTELA = X.bdcodtelasis)
                JOIN VCT_BASE_OBRIGACAO Z ON (Z.BDCODOBRSER = Y.BDCODOBRIGACAO)
                WHERE UPPER(X.bdnometela) = 'TFREXPORTACAOCAGED' AND UPPER(X.bdcaptiontela) = 'DIÁRIO'
                INTO :vcodobr, :vdesc DO
              BEGIN
                IF (vcodobr <> 0) THEN
                   BEGIN
                     vp1 = 0;
                     vp2 = 0;
                     SELECT POS FROM POS('DIÁRIO', :vdesc) INTO :vp1;
                     SELECT POS FROM POS('DIARIO', :vdesc) INTO :vp2;
                     IF ((vp1 > 0) OR (vp2 > 0)) THEN
                        BEGIN
                          DELETE FROM vct_empresa_tsolicitatarefa
                          WHERE bdcodemp = OLD.bdcodemp AND bdcodusu = :vcodusu AND bdcodcol = OLD.bdcodcol AND bdcodobrigacao = :vcodobr AND bdcodtipo = 501 AND
                                bddatasol = OLD.bddataadmcol AND bddatasolicitada = OLD.bddataadmcol AND bddataprevisao = OLD.bddataadmcol;
                        END
                   END
              END
          END
     END
END^

CREATE OR ALTER TRIGGER EMPRESAS_TDEPRECIACAO_BI0 FOR EMPRESAS_TDEPRECIACAO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  --declare variable vNova_Chave integer;
  DECLARE VARIABLE vCodDep INTEGER;
BEGIN
  vCodigo = 0;
  IF ((NEW.bdcodbem IS NULL) OR (NEW.bdcodbem = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdcodbem)), 1) FROM empresas_tbem WHERE (bdcodemp = NEW.bdcodemp) INTO vCodigo;
       NEW.bdcodbem = vCodigo;
     END

  IF ((NEW.bdcoddep IS NULL) OR (NEW.bdcoddep = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdcoddep)+1), 1) FROM empresas_tdepreciacao
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodbem = NEW.bdcodbem) INTO vcoddep;
       NEW.bdcoddep = vcoddep;
     END
END
^

CREATE OR ALTER trigger empresas_tvalorresidual_bi0 for empresas_tvalorresidual
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODVALRES IS NULL) OR (NEW.BDCODVALRES = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODVALRES)+1), 1) FROM EMPRESAS_TVALORRESIDUAL INTO vNova_Chave;
      NEW.BDCODVALRES = vNova_Chave;
     END
  ELSE
    BEGIN
       SELECT BDCODVALRES FROM EMPRESAS_TVALORRESIDUAL WHERE (BDCODVALRES = NEW.BDCODVALRES) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCODVALRES)+1), 1) FROM EMPRESAS_TVALORRESIDUAL INTO vNova_Chave;
           NEW.BDCODVALRES = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER empresas_tsoc_bu0 FOR empresas_tsoc
ACTIVE BEFORE UPDATE POSITION 0
AS
  DECLARE VARIABLE vCODCOL INTEGER;
  DECLARE VARIABLE vREFCOL INTEGER;
BEGIN
/* Gilberto - 25/10/2017 - 20915 - Esse processo é feito pelo único

   vCODCOL = NULL;
   SELECT FIRST 1 x.bdCODCOL FROM vrh_emp_tcolcon_doc x
   LEFT OUTER JOIN vrh_emp_trescisao r ON (x.bdcodemp = r.bdcodemp AND x.bdcodcol = r.bdcodcol)
   WHERE (x.BDCODEMP = NEW.bdcodemp) AND (x.BDCONTRCOL = 1) AND  -- and (r.bddatarescisao is null) and
         (x.BDCPFCOL = NEW.bdcgcceisoc) INTO :vCODCOL;

   -- Seleciona dados basicos do colaborados e joga nas variáveis
   IF (vCODCOL IS NOT NULL) THEN
     BEGIN
       UPDATE vrh_emp_tcolcon
         SET BDDATANASCCOL = NEW.BDDATANASCSOC,
             BDCODCIDNASC = NEW.BDCODCIDNASC
       WHERE (BDCODEMP    = NEW.bdcodemp) AND
             (BDCONTRCOL  = 1) AND
             (BDCODCOL    = :vCODCOL);

       UPDATE vrh_emp_tcol_hist
         SET BDCODPAIS = NEW.BDCODPAISORIG,
             BDNATURALIZADOCOL = NEW.BDNATURALIZADO,
             BDPORTNAT = NEW.BDPORTNAT,
             BDDATANATURALIZACAO = NEW.BDDATANATURALIZACAO,
             BDDTAPOSENT = new.BDDATACHEBRASIL
       WHERE (BDCODEMP = NEW.BDCODEMP) AND
             (BDCONTRCOL = 1) AND
             (BDCODCOL   = :vCODCOL);
       
       SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database INTO :vREFCOL;
       if (COALESCE(vREFCOL, 0) = 0) then
         vREFCOL = SUBSTRING(NEW.BDDATAENTSOC FROM 1 FOR 4)||SUBSTRING(NEW.BDDATAENTSOC FROM 6 FOR 2);

       UPDATE OR INSERT INTO VRH_EMP_TCOLCON_REF
              (BDCODEMP, BDCODCOL, BDREFCOL, BDCONTRCOL)
       VALUES (NEW.BDCODEMP, :vCODCOL, :vREFCOL, 1)
       MATCHING (BDCODEMP, BDCODCOL, BDREFCOL);

       UPDATE OR INSERT INTO VRH_EMP_TCOLCON_CAD
              (BDCODEMP, BDCODCOL, BDREFCOL, BDCONTRCOL, BDCODCID,
--               BDNOMCOL, Gilberto - 19/10/2017 - 20915
               BDENDCOL, BDNUMCOL, BDCOMPLCOL, BDBAICOL, BDCEPCOL,
               BDLOGRCOL, BDSEXOCOL, BDGRAUINSTCOL, BDDATACHEBRASILCOL,
               BDESTCIVCOL, BDCODPAISRES)
       VALUES (NEW.BDCODEMP, :vCODCOL, :vREFCOL, 1, NEW.BDCODCID,
--               NEW.BDNOMSOC, Gilberto - 19/10/2017 - 20915
               NEW.BDENDSOC, NEW.BDNUMSOC, NEW.BDCOMPLSOC, NEW.BDBAISOC, NEW.BDCEPSOC,
               NEW.BDLOGRSOC, NEW.BDSEXO, NEW.BDGRAUINST, NEW.BDDATACHEBRASIL,
               new.bdestcivilsoc, NEW.bdcodpais)
       MATCHING (BDCODEMP, BDCODCOL, BDREFCOL);

       if (new.bdcodpais is null) then
       begin
         UPDATE OR INSERT INTO VRH_EMP_TCOLCON_CAD
                (BDCODEMP, BDCODCOL, BDREFCOL, BDCONTRCOL, BDCODPAISRES)
         VALUES (NEW.BDCODEMP, :vCODCOL, :vREFCOL, 1, (select first 1 BDCODPAIS from TPAIS where upper(bddescpais)='BRASIL'))
         MATCHING (BDCODEMP, BDCODCOL, BDREFCOL);
       end


       UPDATE OR INSERT INTO VRH_EMP_TCOLCON_DOCREF
              (BDCODEMP, BDCODCOL, BDREFCOL, BDCONTRCOL,
               BDRGCOL, BDORGEMIRGCOL, BDCODUFRG, BDDATAEMIRGCOL, BDPISCOL)
       VALUES (NEW.BDCODEMP, :vCODCOL, :vREFCOL, 1,
               NEW.BDRGSOC, NEW.BDORGEMISOC, NEW.BDCODUFRG, NEW.BDDATAEMIRG, NEW.BDINSCNIT)
       MATCHING (BDCODEMP, BDCODCOL, BDREFCOL);
    END
*/
END
^

CREATE OR ALTER TRIGGER TRESOURCECOUNT_BIU0 FOR TRESOURCECOUNT
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  if (old.bdcount is null) then
     new.bdcount = 1;
  else
     new.bdcount = old.bdcount + 1;
end
^

CREATE OR ALTER TRIGGER empresas_tsoc_ref_aiu0 FOR empresas_tsoc_ref
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
  DECLARE VARIABLE vCODCOL INTEGER;
BEGIN
/* Gilberto - 25/10/2017 - 20915 - Esse processo é feito pelo único

   vCODCOL = NULL;
   SELECT FIRST 1 x.bdCODCOL FROM vrh_emp_tcolcon_doc x
   INNER JOIN empresas_tsoc soc ON (soc.bdcodemp = x.bdcodemp AND soc.bdcodsoc = NEW.bdcodsoc AND soc.bdcgcceisoc = x.BDCPFCOL)
   LEFT OUTER JOIN vrh_emp_trescisao r ON (x.bdcodemp = r.bdcodemp AND x.bdcodcol = r.bdcodcol)
   WHERE (x.BDCODEMP = NEW.bdcodemp)
   AND (x.BDCONTRCOL = 1)
   INTO :vCODCOL;

   IF ((vCODCOL IS NOT NULL) AND (vCODCOL > 0) AND (NEW.bdnomsoc IS NOT NULL)) THEN
   BEGIN
     UPDATE OR INSERT INTO VRH_EMP_TCOLCON_REF
            (BDCODEMP, BDCODCOL, BDREFCOL, BDCONTRCOL)
     VALUES (NEW.BDCODEMP, :vCODCOL, NEW.BDREFSOC, 1)
     MATCHING (BDCODEMP, BDCODCOL, BDREFCOL);

     UPDATE OR INSERT INTO VRH_EMP_TCOLCON_CAD
            (BDCODEMP, BDCODCOL, BDREFCOL, BDCONTRCOL,
             BDNOMCOL, BDDDDCOL, BDFONECOL, BDDDDCELCOL, BDCELCOL, BDEMAILCOL)
     VALUES (NEW.BDCODEMP, :vCODCOL, NEW.BDREFSOC, 1,
             NEW.BDNOMSOC, NEW.BDDDDSOC, NEW.BDTELRESSOC, NEW.BDDDCELSOC, NEW.BDTELCELSOC, NEW.BDEMAILSOC)
     MATCHING (BDCODEMP, BDCODCOL, BDREFCOL);
   END
*/
END^

CREATE OR ALTER TRIGGER empresas_tsoc_ref_bi0 FOR empresas_tsoc_ref
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCODSOC INTEGER;
BEGIN
  IF ((NEW.bdcodsoc IS NULL) OR (NEW.bdcodsoc = 0)) THEN
  BEGIN
    SELECT COALESCE(MAX(bdcodsoc), 0)+1 FROM empresas_tsoc WHERE bdcodemp = NEW.bdcodemp INTO vcodsoc;
    NEW.bdcodsoc = vcodsoc;
  END
END^


CREATE OR ALTER TRIGGER PLANOS_TPLA_BD0 FOR PLANOS_TPLA
ACTIVE BEFORE DELETE POSITION 0 
AS
  DECLARE VARIABLE vlength INTEGER;
BEGIN
  IF (OLD.bdtipcta = 0) THEN
     BEGIN
       vlength = strlen(OLD.bdctalon);

       DELETE FROM planos_tpla
       WHERE bdcodplapadrao = OLD.bdcodplapadrao
       AND SUBSTRING(bdctalon FROM 1 FOR :vlength) = OLD.bdctalon
       AND bdctalon <> OLD.bdctalon;

       IF (EXISTS(SELECT * FROM planos_tpla
                  WHERE bdcodplapadrao = OLD.bdcodplapadrao
                  AND SUBSTRING(bdctalon FROM 1 FOR :vlength) = OLD.bdctalon
                  AND bdctalon <> OLD.bdctalon)) THEN
          EXCEPTION nao_excluir_titulo;

     END

  EXECUTE PROCEDURE FK_MANUAL_DELETE('PLANOS_TPLA', OLD.BDCODPLAPADRAO, OLD.BDCODTPLA);

  IF (EXISTS(SELECT FIRST 1 LAN.BDCODEMP
             FROM VSUC_EMPRESAS_TLAN LAN
             WHERE OLD.bdcodplapadrao = lan.bdcodplapadrao and old.bdcodtpla IN (LAN.bddebito, LAN.bdcredito))) THEN
    EXCEPTION EX_DELETE 'VSUC_EMPRESAS_TLAN';
END
^

CREATE OR ALTER TRIGGER vfin_base_tplanositfin_bi0 FOR vfin_base_tplanositfin
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdcodplasitfin IS NULL) OR (NEW.bdcodplasitfin = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodplasitfin)+1),1) FROM VFIN_BASE_TPLANOSITFIN INTO vCodigo;
      NEW.bdcodplasitfin = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodplasitfin FROM VFIN_BASE_TPLANOSITFIN WHERE bdcodplasitfin = NEW.bdcodplasitfin INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodplasitfin) + 1), 1) FROM VFIN_BASE_TPLANOSITFIN INTO vCodigo;
           NEW.bdcodplasitfin = vCodigo;
         END
    END
END
^

CREATE OR ALTER trigger vfin_base_tplanoconciliado_bi0 for vfin_base_tplanoconciliado
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdcodplaconc IS NULL) OR (NEW.bdcodplaconc = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodplaconc)+1),1) FROM vfin_base_tplanoconciliado INTO vCodigo;
      NEW.bdcodplaconc = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodplaconc FROM vfin_base_tplanoconciliado WHERE bdcodplaconc = NEW.bdcodplaconc INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodplaconc) + 1), 1) FROM vfin_base_tplanoconciliado INTO vCodigo;
           NEW.bdcodplaconc = vCodigo;
         END
    END
END
^

CREATE OR ALTER trigger vfin_base_tgrupoeconomico_bi0 for vfin_base_tgrupoeconomico
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdcodgrupoecon IS NULL) OR (NEW.bdcodgrupoecon = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodgrupoecon)+1),1) FROM vfin_base_tgrupoeconomico INTO vCodigo;
      NEW.bdcodgrupoecon = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodgrupoecon FROM vfin_base_tgrupoeconomico WHERE bdcodgrupoecon = NEW.bdcodgrupoecon INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodgrupoecon) + 1), 1) FROM vfin_base_tgrupoeconomico INTO vCodigo;
           NEW.bdcodgrupoecon = vCodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VFIN_BASE_TVINCPROCESSOCONC_AD0 FOR VFIN_BASE_TVINCPROCESSOCONCI
ACTIVE AFTER DELETE POSITION 0
AS
begin
  -- Sol: #84320 Morgana. 06/06/2018. Deletar a despesa vinculada.
  DELETE FROM VFIN_ESC_TCONTASPAGARDESP WHERE BDCODESC = old.BDCODESC AND BDCHAVECTAPAG = old.BDCHAVECTAPAG AND BDORDEMDESP = old.BDORDEMDESP;
end
^

CREATE OR ALTER TRIGGER VFIN_BASE_TSITCLIENTE_BI0 FOR VFIN_BASE_TSITCLIENTE
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wDataSit date;
  declare variable wChaveSit integer;
begin
  select first (1) bddatasitcli, bdchavesitcli from VFIN_BASE_TSITCLIENTE
  where (bdcodcli = new.bdcodcli) order by bddatasitcli desc, bdchavesitcli desc into :wdatasit, :wchavesit;

  if ( (new.bddatasitcli >= wdatasit) and (new.bdchavesitcli > wchavesit) or (new.bdchavesitcli = 1) ) then
     begin
       update VFIN_BASE_TSITCLIENTE cli set cli.bdsitatual = 'FALSE' where cli.bdcodcli = new.bdcodcli;
       new.bdsitatual = 'TRUE';
     end
  else
      new.bdsitatual = 'FALSE';

end
^

create or alter procedure SP_VFIN_ATUSITEMP (
    PRCODEMP integer)
as
-- /* Julio Cesar - 20/07/2023 - W183361 - Título: Situação financeira do cliente */
-- Removido a variável WCODEMP, pois a consulta é realizada com base no código da empresa se tornando desnecessário
-- declare variable WCODEMP integer;
declare variable WREFEMP integer;
declare variable WSITEMP DM_BOOLEAN;
declare variable WCODCLI integer;
declare variable WCODSITCLI integer;
declare variable WCODCLIEMP integer;
begin
--  /* Gilberto - 13/09/2021 - W154809 - Situação Financeira de clientes */
--  wsql = 'select bdcodemp,bdrefemp,case when(bddatasitcli is null)then bdsitemp else BDSITUACAOFINANCEIRA end as BDSITEMP from(';
--  wsql = wsql||'select emp.bdcodemp,emp.bdrefemp,emp.bdsitemp,';
--  wsql = wsql||'case when(sit.bdcodcli is null)then coalesce(emp.bdsitemp,'||'''FALSE'''||')';-- não há situação financeira definida, deve usar oque foi definido no cadastro de empresas
--  wsql = wsql||'when(sit.bdcodsitcli=3)then'||'''TRUE'''||'else'||'''FALSE''';
--  wsql = wsql||'end as BDSITUACAOFINANCEIRA, sit.bddatasitcli ';
--  wsql = wsql||'from tempresas_ref emp ';
--  wsql = wsql||'left outer join vfin_base_tsitcliente sit on(sit.bdcodcli=emp.bdcodemp ';
--  wsql = wsql||'and sit.bddatasitcli=(select first 1 bddatasitcli from vfin_base_tsitcliente dat ';
--  wsql = wsql||'where(dat.bdcodcli=sit.bdcodcli)';
--  wsql = wsql||'and(substring(BDDATASITCLI from 1 for 4)||substring(BDDATASITCLI from 6 for 2)<=emp.bdrefemp)';
--  wsql = wsql||'order by dat.bddatasitcli desc))';
--  if ((prcodemp is not null) and (prcodemp>0)) then
--     wsql = wsql||'where(emp.bdcodemp='||prcodemp||')';
--  wsql = wsql||'order by emp.bdcodemp,sit.bddatasitcli,emp.bdrefemp desc)';
--
--  for execute statement wsql
--  into :wcodemp, :wrefemp, :wsitemp do
--  begin
--    -- a variável é iniciada aqui e finalizada em TEMPRESAS_REF_AI1, no momento que faz o update para garantir que não afete outros processos
--    rdb$set_context('USER_SESSION', 'VFIN_ATU_SITEMP', CAST('TRUE' AS VARCHAR(5)));
--    update tempresas_ref set bdsitemp = :wsitemp where bdcodemp = :wcodemp and bdrefemp = :wrefemp and ((bdsitemp is null)or(bdsitemp <> :wsitemp));
--  end

  wsitemp = 'FALSE';
-- O código do cliente já está sendo retornado para a variável wcodcliemp
--  for select EMP.bdcodcli, REF.BDREFEMP, REF.BDSITEMP, emp.bdcodcli from TEMPRESAS_REF REF
  for select REF.BDREFEMP, REF.BDSITEMP, emp.bdcodcli from TEMPRESAS_REF REF
      inner join tempresas EMP on (EMP.BDCODEMP = REF.bdcodemp)
      where(EMP.BDCODEMP = :prcodemp)
      and(emp.bdcodcli is not null)
      order by REF.BDCODEMP, REF.BDREFEMP
--  into :wcodemp, :wrefemp, :wsitemp, :wcodcliemp do
  into :wrefemp, :wsitemp, :wcodcliemp do
  begin
    select first 1 SIT.BDCODCLI, SIT.bdcodsitcli from vfin_base_tsitcliente SIT
    where SIT.bdcodcli = :wcodcliemp
    and (substring(SIT.BDDATASITCLI from 1 for 4) || substring(SIT.BDDATASITCLI from 6 for 2) <= :wrefemp)
    order by SIT.BDDATASITCLI desc
    into :wcodcli, :wcodsitcli;
    if (wcodcli is not null) then
    begin
      if ((wcodsitcli is not null) and (wcodsitcli = 3)) then
         wsitemp = 'TRUE';
      else
         wsitemp = 'FALSE';
    end

    rdb$set_context('USER_SESSION', 'VFIN_ATU_SITEMP', CAST('TRUE' AS VARCHAR(5)));
--    update tempresas set bdcontrsitfin = 'TRUE' where bdcodemp = :wcodemp;
--    update tempresas_ref set bdsitemp = :wsitemp where bdcodemp = :wcodemp and bdrefemp = :wrefemp and ((bdsitemp is null)or(bdsitemp <> :wsitemp));
    update tempresas set bdcontrsitfin = 'TRUE' where bdcodemp = :prcodemp;
    update tempresas_ref set bdsitemp = :wsitemp where bdcodemp = :prcodemp and bdrefemp = :wrefemp and ((bdsitemp is null)or(bdsitemp <> :wsitemp));
  end

  -- Gilberto - 16/11/2021 - Atualiza a tag bdsitatual para manter apenas esse no Grid de situação financeira
  if (wcodcliemp is not null) then
  begin
    update vfin_base_tsitcliente SIT set bdsitatual = 'TRUE'
    where sit.bdchavesitcli = (select first 1 CLI.bdchavesitcli from vfin_base_tsitcliente CLI
                               where CLI.bdcodcli = SIT.bdcodcli
                               and cli.bddatasitcli <= current_date
                               order by CLI.bddatasitcli desc, cli.bdchavesitcli desc)
    and sit.bdcodcli = :wcodcliemp
    and ((sit.bdsitatual is null)or(sit.bdsitatual <> 'TRUE'));
    
    update vfin_base_tsitcliente SIT set bdsitatual = 'FALSE'
    where sit.bdchavesitcli <> (select first 1 CLI.bdchavesitcli from vfin_base_tsitcliente CLI
                                where CLI.bdcodcli = SIT.bdcodcli
                                and cli.bddatasitcli <= current_date
                                order by CLI.bddatasitcli desc, cli.bdchavesitcli desc)
    and sit.bdcodcli = :wcodcliemp
    and ((sit.bdsitatual is null)or(sit.bdsitatual <> 'FALSE'));
  end
end^


CREATE OR ALTER TRIGGER VFIN_BASE_TSITCLIENTE_AI0 FOR VFIN_BASE_TSITCLIENTE
ACTIVE AFTER INSERT POSITION 0
AS
  declare variable vRefSituacao varchar(6);
  declare variable vCODEMP integer;
  declare variable vUltCodSitCli integer;
begin
  select bdcodsitcli from VFIN_BASE_TSITCLIENTE where bdcodcli = new.bdcodcli and bdchavesitcli =
  (select first 1 (bdchavesitcli) bdchavesitcli from VFIN_BASE_TSITCLIENTE where bdcodcli = new.bdcodcli and bddatasitcli < new.bddatasitcli order by bdchavesitcli desc) into :vUltCodSitCli;

  if ( (new.bdcodsitcli = 3) or (:vUltCodSitCli = 3)) then
    begin
      if (((select BDCODTIPOCLI from vfin_base_tcliente where bdcodcli = new.bdcodcli) <> 3) and (new.bddatasitcli is not null)) then
        begin
          vRefSituacao = cast(substring(new.bddatasitcli from 1 for 4)||substring(new.bddatasitcli from 6 for 2) as integer);

           if ((cast((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database) as integer)) = 0) then
             begin
               if (vrefsituacao = 0) then
                 execute procedure sp_seta_competencia(cast(substring(current_date from 1 for 4)||substring(current_date from 6 for 2) as integer));
               else
                 execute procedure sp_seta_competencia(vrefsituacao);
             end

          execute statement 'execute procedure sp_vfin_empresacliente_ref('||new.bdcodcli||', '||:vrefsituacao||');';

          select first 1 bdcodemp from tempresas where bdcodcli = new.bdcodcli into :vcodemp;
          if (vcodemp is not null) then
            begin
              rdb$set_context('USER_SESSION', 'VFIN_ATU_SITEMP', CAST('TRUE' AS VARCHAR(5)));
              execute statement 'execute procedure sp_vfin_atusitemp('||vcodemp||')';
            end
        end
    end

  /*if (new.bdcodsitcli = 9) then
    begin
      update TEMPRESAS set bddatasaiemp = new.bddatasitcli where bdcodcli = new.bdcodcli;
      update VFIN_BASE_TCLIENTE set bddatasaicli = new.bddatasitcli where bdcodcli = new.bdcodcli;
    end*/
end^

CREATE OR ALTER TRIGGER VFIN_BASE_TSITCLIENTE_AD0 FOR VFIN_BASE_TSITCLIENTE
ACTIVE AFTER DELETE POSITION 0
AS
  declare variable vRefSituacao varchar(6);
  declare variable vSitEmp varchar(5);
  declare variable vVerAntCli integer;
  declare variable vdata date;
  declare variable vref integer;
  declare variable vchavant integer;
  declare variable vcodemp integer;
begin
    vRefSituacao = cast(substring(old.bddatasitcli from 1 for 4)||substring(old.bddatasitcli from 6 for 2) as integer);
/* Gilberto - 14/05/2021 - está dando erro ao excluir situações financeira na mesma data
    -- Sol: #149671 | Gabriel Bobello | 27/04/2021 | Criando para exclusão de situações financeiras.
    -- Ativa
    if (old.bdcodsitcli = 2) then
        begin
          select bdcodsitcli from vfin_base_tsitcliente where bdcodcli = old.bdcodcli and bddatasitcli = (select max(bddatasitcli) from vfin_base_tsitcliente where bdcodcli = old.bdcodcli) into : vVerAntCli;
          if (vVerAntCli = 3 ) then
            begin
              vSitEmp = 'TRUE';
              update TEMPRESAS_REF set bdsitemp = :vSitEmp where bdcodemp = old.bdcodcli and bdrefemp >= :vRefSituacao;
            end
        end
    else    -- Inativo   
    if (old.bdcodsitcli = 3) then
        begin
          select bdcodsitcli from vfin_base_tsitcliente where bdcodcli = old.bdcodcli and bddatasitcli = (select max(bddatasitcli) from vfin_base_tsitcliente where bdcodcli = old.bdcodcli) into : vVerAntCli;
          if (vVerAntCli <> 3) then
            begin
              vSitEmp = 'FALSE';
              update TEMPRESAS_REF set bdsitemp = :vSitEmp where bdcodemp = old.bdcodcli and bdrefemp >= :vRefSituacao;
            end
        end
*/

  -- seleciona a última situação financeira antes dá que está sendo excluída
/* select first 1 BDCODSITCLI, bddatasitcli, bdchavesitcli from VFIN_BASE_TSITCLIENTE
  where BDCODCLI = old.bdcodcli
  and BDDATASITCLI <= (select max(BDDATASITCLI) from VFIN_BASE_TSITCLIENTE where BDCODCLI = OLD.BDCODCLI)
  and BDCHAVESITCLI < old.bdchavesitcli
  order by BDCHAVESITCLI desc*/

--  -- Antony Rairon (14/06/2021) - Em alguns casos não estava selecionando corretamente a situação anterior
--  select first 1 BDCODSITCLI, bddatasitcli, bdchavesitcli from VFIN_BASE_TSITCLIENTE
--  where BDCODCLI = old.bdcodcli and bdchavesitcli <> old.bdchavesitcli
--  order by bddatasitcli desc, bdchavesitcli desc
--  into :vverantcli, :vdata, :vchavant;
--  vref = cast(substring(vdata from 1 for 4)||substring(vdata from 6 for 2) as integer);
--  -- verifica a situação financeira anterior, não a que está sendo excluída
--  if (vverantcli = 3) then
--     vsitemp = 'TRUE';
--  else
--     vsitemp = 'FALSE';
--  -- altera apenas a situação financeira que está sendo excluída
--  update tempresas_ref set bdsitemp = :vsitemp where bdcodemp = old.bdcodcli and bdrefemp = :vrefsituacao;
--  -- caso a situação financeira anterior seja diferente da atual, deve alterar a anterior também
--  if (vrefsituacao <> vref) then
--     update tempresas_ref set bdsitemp = :vsitemp where bdcodemp = old.bdcodcli and bdrefemp = :vref;
--  -- #127924 - Antony Rairon (01/06/2021) - Foi criado o campo BDSITATUAL na tabela VFIN_BASE_TSITCLIENTE, quando excluir a situação atual, a anterior deve assumir como atual
--  if (old.bdsitatual = 'TRUE') then
--     update VFIN_BASE_TSITCLIENTE set bdsitatual = 'TRUE' where bdcodcli = old.bdcodcli and bdchavesitcli = :vchavant;
  select first 1 bdcodemp from tempresas where bdcodcli = old.bdcodcli into :vcodemp;
  if (vcodemp is not null) then
  begin
-- Gilberto - 07/12/2021 - Não é necessário porque já faz dentro da procedure
--    rdb$set_context('USER_SESSION', 'VFIN_ATU_SITEMP', CAST('TRUE' AS VARCHAR(5)));
    execute statement 'execute procedure sp_vfin_atusitemp('||vcodemp||')';
  end

-- W165009 - Antony R. (22/06/2022) - Ao deletar a situação de saida do escritorio deve limpar a data de saida do cadastro de empresa e cliente
  if (old.bdcodsitcli = 9) then
  begin
    update TEMPRESAS set bddatasaiemp = null where bdcodcli = old.bdcodcli;
    update VFIN_BASE_TCLIENTE set bddatasaicli = null where bdcodcli = old.bdcodcli;
  end

end
^

CREATE OR ALTER TRIGGER vfin_base_tsitclienteobs_bi0 FOR vfin_base_tsitclienteobs
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vOrdem INTEGER;
BEGIN
  vOrdem = 0;
  IF ((NEW.bdordemobs IS NULL) OR (NEW.bdordemobs = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdordemobs)+1, 1) FROM vfin_base_tsitclienteobs
       WHERE bdcodcli = NEW.bdcodcli AND bdchavesitcli = NEW.bdchavesitcli
       INTO vOrdem;
       NEW.bdordemobs = vOrdem;
     END
  ELSE
    BEGIN
      SELECT bdordemobs FROM vfin_base_tsitclienteobs WHERE bdcodcli = NEW.bdcodcli AND bdchavesitcli = NEW.bdchavesitcli and bdordemobs = NEW.bdordemobs INTO vOrdem;

      IF (vordem > 0) THEN
         BEGIN
           SELECT COALESCE(MAX(bdordemobs)+1, 1) FROM vfin_base_tsitclienteobs
           WHERE bdcodcli = NEW.bdcodcli AND bdchavesitcli = NEW.bdchavesitcli
           INTO vOrdem;
           NEW.bdordemobs = vOrdem;
         END
    END
END
^

CREATE OR ALTER trigger vfin_esc_tnfse_servico_bi0 for vfin_esc_tnfse_servico
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordem)+1),1) FROM VFIN_ESC_TNFSE_SERVICO
      where bdcodcli = new.bdcodcli and bdcodesc = new.bdcodesc
      and bdchavefatura = new.bdchavefatura and bdordemser = new.bdordemser
      INTO vcodigo;
      NEW.bdordem = vcodigo;
    END
  ELSE
    BEGIN
      SELECT bdordem FROM VFIN_ESC_TNFSE_SERVICO
      where bdcodcli = new.bdcodcli and bdcodesc = new.bdcodesc
      and bdchavefatura = new.bdchavefatura and bdordemser = new.bdordemser
      and bdordem = NEW.bdordem
      INTO vcodigo;
     
      IF (vcodigo > 0) THEN
        BEGIN
          SELECT COALESCE((MAX(bdordem)+1),1) FROM VFIN_ESC_TNFSE_SERVICO
          where bdcodcli = new.bdcodcli and bdcodesc = new.bdcodesc
          and bdchavefatura = new.bdchavefatura and bdordemser = new.bdordemser
          INTO vcodigo;
          NEW.bdordem = vcodigo;
        END
    END
END
^

CREATE OR ALTER TRIGGER PLANOS_TPLA_BU0 FOR PLANOS_TPLA
ACTIVE BEFORE UPDATE POSITION 0 
AS
  DECLARE VARIABLE  wparte VARCHAR(140);
  DECLARE VARIABLE  wrpos INTEGER;
  DECLARE VARIABLE wNivel INTEGER;
BEGIN
  --Trigger text

  -- gravar bdclanom para ordernar por nome e classificacao  inicio
  wparte = NEW.bdctalon;
  -- se nao for conta titulo
  IF (NEW.bdtipcta = 1) THEN
     BEGIN
       SELECT bdrpos FROM rpos('.',:wparte) INTO wrpos;
       IF (wrpos > 0) THEN
          BEGIN
            wparte = SUBSTRING(wparte FROM 1 FOR wrpos - 1);
            SELECT bdretorno FROM preenche_direita(:wparte,40,' ') INTO wparte;
            wparte = wparte || NEW.bdnomcta;
          END
     END

  NEW.bdclanom = wparte;

  /* gravar bdclanom para ordernar por nome e classificacao  fim*/
  EXECUTE PROCEDURE CONTAR_CHAR(NEW.BDCTALON, '.') RETURNING_VALUES :wNivel;
  NEW.bdnivel = :wNivel;
END
^

CREATE OR ALTER TRIGGER PLANOS_TPLA_FCONT_PADRAO_BI0 FOR PLANOS_TPLA_FCONT_PADRAO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodtpla_FCONT_padrao IS NULL) OR (NEW.bdcodtpla_FCONT_padrao = 0))  THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodtpla_FCONT_padrao)+1), 1) FROM planos_tpla_FCONT_padrao WHERE bdcodplapadrao_FCONT = NEW.bdcodplapadrao_FCONT INTO vNova_Chave;
      NEW.bdcodtpla_FCONT_padrao = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdcodtpla_FCONT_padrao FROM planos_tpla_FCONT_padrao WHERE (bdcodtpla_FCONT_padrao = NEW.bdcodtpla_FCONT_padrao) AND (bdcodplapadrao_FCONT = NEW.bdcodplapadrao_FCONT) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodtpla_FCONT_padrao)+1), 1) FROM planos_tpla_FCONT_padrao WHERE bdcodplapadrao_FCONT = NEW.bdcodplapadrao_FCONT INTO vNova_Chave;
           NEW.bdcodtpla_FCONT_padrao = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER PLANOS_TPLA_SPED_PADRAO_BI0 FOR PLANOS_TPLA_SPED_PADRAO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodtpla_sped_padrao IS NULL) OR (NEW.bdcodtpla_sped_padrao = 0))  THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodtpla_sped_padrao)+1), 1) FROM planos_tpla_sped_padrao WHERE bdcodplapadrao_sped = NEW.bdcodplapadrao_sped INTO vNova_Chave;
      NEW.bdcodtpla_sped_padrao = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdcodtpla_sped_padrao FROM planos_tpla_sped_padrao WHERE (bdcodtpla_sped_padrao = NEW.bdcodtpla_sped_padrao) AND (bdcodplapadrao_sped = NEW.bdcodplapadrao_sped) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodtpla_sped_padrao)+1), 1) FROM planos_tpla_sped_padrao WHERE bdcodplapadrao_sped = NEW.bdcodplapadrao_sped INTO vNova_Chave;
           NEW.bdcodtpla_sped_padrao = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER TASSINATURA_BI0 FOR TASSINATURA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDCODASS IS NULL) OR (NEW.bdcodass = 0)) THEN
    BEGIN
      SELECT bdresult FROM maxsci('BDCODASS', 'BDCODSIS, BDCODASS', 'BDCODSIS = '||NEW.BDCODSIS, 'tassinatura') INTO vCodigo;
      NEW.BDCODASS = vcodigo+1;
    END
  ELSE
    BEGIN
       SELECT BDCODASS FROM tassinatura WHERE (BDCODASS = NEW.BDCODASS) AND (BDCODSIS = NEW.BDCODSIS) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           NEW.BDCODASS = vCodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TBANCOS_BI0 FOR TBANCOS
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (COALESCE(NEW.BDCODBAN, 0) = 0) THEN
     NEW.BDCODBAN = new.BDCODFEBRABAN;
END
^

CREATE OR ALTER TRIGGER TBANCOS_FEBRABAN_BI0 FOR TBANCOS_FEBRABAN
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODFEBRABAN IS NULL) OR (NEW.BDCODFEBRABAN = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODFEBRABAN) + 1, 1)
       FROM TBANCOS_FEBRABAN
       INTO :vNovoCod;

       NEW.BDCODFEBRABAN = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER TBLOQLAN_BI0 FOR TBLOQLAN
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodblq IS NULL) OR (NEW.bdcodblq = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdcodblq)+1),1) FROM tbloqlan INTO vcodigo;
       NEW.bdcodblq = vcodigo;
     END
  ELSE
     BEGIN
       SELECT bdcodblq FROM tbloqlan WHERE bdcodblq = NEW.bdcodblq INTO vcodigo;

       IF (vcodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdcodblq)+1),1) FROM tbloqlan INTO vcodigo;
            NEW.bdcodblq = vcodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER TBLOQLAN_EMPRESA_AI0 FOR TBLOQLAN_EMPRESA
ACTIVE AFTER INSERT POSITION 0 
AS
  DECLARE VARIABLE wSQL VARCHAR(1000);
BEGIN
/*
  wsql = 'insert into tbloqlan_usuario (BDCODGRUPO, BDCODUSU, BDCODEMP, BDCODBLQ, BDCODBLE) ';
  wsql = wsql||'select bdcodgrupo, bdcodusu, '||new.bdcodemp||', '||new.bdcodblq||', '||new.bdcodble;
  wsql = wsql||' from tgrupousuario_usuario ';
  wsql = wsql||'where bdcodgrupo <> 1 ';
  wsql = wsql||'order by bdcodgrupo, bdcodusu ';

--  exception ex_bloqlan wsql;

  execute statement wsql;*/
END
^

CREATE OR ALTER TRIGGER TBLOQLAN_EMPRESA_BD0 FOR TBLOQLAN_EMPRESA
ACTIVE BEFORE DELETE POSITION 0 
AS DECLARE VARIABLE vcodemp INTEGER;
BEGIN
  SELECT FIRST 1 bdcodemp
  FROM vsuc_empresas_bloqencexe
  WHERE bdcodemp = OLD.bdcodemp
  AND bdcodblq = OLD.bdcodblq
  AND bdcodble = OLD.bdcodble
  INTO :vcodemp;
  IF (COALESCE(vcodemp, 0) <> 0) THEN
     EXCEPTION ex_bloqzer;
END
^

CREATE OR ALTER TRIGGER TBLOQLAN_EMPRESA_BI0 FOR TBLOQLAN_EMPRESA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodble IS NULL) OR (NEW.bdcodble = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdcodble)+1),1) FROM tbloqlan_empresa WHERE bdcodblq = NEW.BDCODBLQ INTO vcodigo;
       NEW.bdcodble = vcodigo;
     END
  ELSE
     BEGIN
       SELECT bdcodble FROM tbloqlan_empresa WHERE bdcodblq = NEW.bdcodblq AND bdcodble = NEW.bdcodble INTO vcodigo;

       IF (vcodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdcodble)+1),1) FROM tbloqlan_empresa WHERE bdcodblq = NEW.bdcodblq INTO vcodigo;
            NEW.bdcodble = vcodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER TCADPRO_ATVCONPREV_BI0 FOR TCADPRO_ATVCONPREV
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vcodprod INTEGER;
  DECLARE VARIABLE vordem INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
    BEGIN
       IF ((NEW.bdcodprod IS NULL) OR (NEW.bdcodprod = 0)) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODPROD)), 1) FROM tcadpro INTO vcodprod;
            NEW.bdcodprod = vcodprod;
         END
       SELECT COALESCE((MAX(bdordem)+1), 1) FROM TCADPRO_ATVCONPREV
       WHERE (bdcodprod = NEW.bdcodprod) INTO vordem;
       NEW.bdordem = vordem;
    END
  ELSE
    BEGIN
       IF ((NEW.bdcodprod IS NULL) OR (NEW.bdcodprod = 0)) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODPROD)), 1) FROM tcadpro INTO vcodprod;
            NEW.bdcodprod = vcodprod;
         END

       SELECT bdordem FROM TCADPRO_ATVCONPREV
       WHERE (bdordem = NEW.bdordem) AND (bdcodprod = NEW.bdcodprod) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordem)+1), 1) FROM TCADPRO_ATVCONPREV
           WHERE (bdcodprod = NEW.bdcodprod) AND (bdordem = NEW.bdordem) INTO vordem;
           NEW.bdordem = vordem;
         END

    END
END
^

CREATE OR ALTER TRIGGER VCT_EMPRESA_TSOLICITATAREFA_BU0 FOR VCT_EMPRESA_TSOLICITATAREFA
ACTIVE BEFORE UPDATE POSITION 0
AS
--declare variable vhora time;
declare variable vcodusu integer;
begin
  select first 1 bdcodusu from vw_usuarios_secao into :vcodusu;
  if (:vcodusu is not null) then
     new.bdcodusu = :vcodusu;

  if (new.bddatafim is not null and new.bdvencimento is not null) then
  begin
    if (new.bddatafim = new.bdvencimento) then
    begin
      new.bdstatusfinalizacao = 0;
      new.bddiasfinalizacao  = 0;
    end
    else
    if (new.bddatafim < new.bdvencimento) then
    begin
      new.bdstatusfinalizacao = 1;
      new.bddiasfinalizacao = datediff(day, new.bddatafim, new.bdvencimento);
    end
    else
    begin
      new.bdstatusfinalizacao = 2;
      new.bddiasfinalizacao = datediff(day, new.bdvencimento, new.bddatafim);
    end
  end
  else
  begin
    new.bdstatusfinalizacao = null;
    new.bddiasfinalizacao = null;
  end
-- Gilberto - 31/07/2026 - #248539 - Revertido porque passou a não listar os usuários responsáveis configurados
--  -- Gilberto - 30/06/2026 - #246890 - Quando um usuário altera a tarefa e não estava na lista de usuário, deve passar a fazer parte
--  Insert into vct_empresa_tarefa_usuario (BDCODEMP, BDCODST, BDCODUSU)
--  select new.bdcodemp, new.bdcodst, bdcodusu from tusuario usu
--  where bdcodusu = new.bdcodusu
--  and not exists(select first 1 bdcodusu from vct_empresa_tarefa_usuario x
--                 where x.bdcodemp = new.bdcodemp
--                 and x.bdcodst = new.bdcodst
--                 and x.bdcodusu = usu.bdcodusu);  
end
^

CREATE OR ALTER trigger vct_empresa_tsolicitatarefa_bd0 for vct_empresa_tsolicitatarefa
active before delete position 0
AS DECLARE VARIABLE v_BDDATATAREFA DATE;
BEGIN
 SELECT first 1 bddatatarefa FROM vct_config_datas INTO :v_BDDATATAREFA;

  /* Augusto #185627 Verifica se v_BDDATATAREFA é nulo antes de continuar */
  IF (v_BDDATATAREFA IS NULL) THEN
  BEGIN
  -- Elimina vinculo com o financeiro
  UPDATE VFIN_ESC_TSERVICOFIXO SET bdcodemp = NULL, bdcodst = NULL WHERE bdcodemp = OLD.bdcodemp AND bdcodst = OLD.bdcodst;
  END

  -- Excluindo aqui porque a tabela não tem PK e não funciona o DELETE CASCADE
  delete from vct_empresa_tarefa_usuario where bdcodemp = old.bdcodemp and bdcodst = old.bdcodst;
END
^

CREATE or alter trigger tcadpro_bd0 for tcadpro
active before delete position 0
AS
begin
  if (OLD.bdqtdarquivado > 0) then
    EXCEPTION ex_delete 'TARQUIVAMENTO';
end^

CREATE OR ALTER TRIGGER TCADPRO_BI0 FOR TCADPRO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF (NEW.BDCODTIPO = 1) THEN
    BEGIN
      /* Trigger text */
      vcodigo = 0;
      IF ((NEW.bdcodprod IS NULL) OR (NEW.bdcodprod = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdcodprod)+1),1) FROM tcadpro INTO vcodigo;
          NEW.bdcodprod = vcodigo;
        END
      ELSE
        BEGIN
          SELECT bdcodprod FROM tcadpro WHERE bdcodprod = NEW.bdcodprod INTO vcodigo;
        
          IF (vcodigo > 0) THEN
            BEGIN
              SELECT COALESCE((MAX(bdcodprod)+1),1) FROM tcadpro INTO vcodigo;
              NEW.bdcodprod = vcodigo;
            END
        END
      END
END
^

CREATE OR ALTER TRIGGER TCAMPOSGERADOR_BI0 FOR TCAMPOSGERADOR
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodcampoger IS NULL) OR (NEW.bdcodcampoger = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodcampoger)+1,1) FROM tcamposgerador WHERE bdcodtabger = NEW.bdcodtabger INTO NEW.bdcodcampoger;
     END
END
^

CREATE OR ALTER TRIGGER TCAT_AGENTECAUSADOR_BI0 FOR TCAT_AGENTECAUSADOR
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodagcausa IS NULL) OR (NEW.bdcodagcausa = 0)) THEN
     SELECT COALESCE(MAX(bdcodagcausa),0)+1 FROM tcat_agentecausador INTO NEW.bdcodagcausa;
END
^

CREATE OR ALTER TRIGGER TCAT_PCORPOATINGIDA_BI0 FOR TCAT_PCORPOATINGIDA
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodpcorpo IS NULL) OR (NEW.bdcodpcorpo = 0)) THEN
     SELECT COALESCE(MAX(bdcodpcorpo),0)+1 FROM tcat_pcorpoatingida INTO NEW.bdcodpcorpo;
END
^

CREATE OR ALTER TRIGGER TCAT_SITGERACTRAB_BI0 FOR TCAT_SITGERACTRAB
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodsitger IS NULL) OR (NEW.bdcodsitger = 0)) THEN
     SELECT COALESCE(MAX(bdcodsitger),0)+1 FROM tcat_sitgeractrab INTO NEW.bdcodsitger;
END
^

CREATE OR ALTER TRIGGER TCLASSE_VENCIMENTO_BI0 FOR TCLASSE_VENCIMENTO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vcodrec INTEGER;
  DECLARE VARIABLE vclavenc INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdclavenc IS NULL) OR (NEW.bdclavenc = 0)) THEN
    BEGIN
      IF ((NEW.bdcodrec IS NULL) OR (NEW.bdcodrec = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCODREC)), 1) FROM tcodrec INTO vcodrec;
          NEW.bdcodrec = vcodrec;
        END

       SELECT COALESCE((MAX(bdClavenc)+1), 1) FROM tclasse_vencimento
       WHERE (bdcodrec = NEW.bdcodrec) INTO vclavenc;
       NEW.bdclavenc = vclavenc;
    END
  ELSE
    BEGIN
       IF ((NEW.bdcodrec IS NULL) OR (NEW.bdcodrec = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCODREC)), 1) FROM tcodrec INTO vcodrec;
          NEW.bdcodrec = vcodrec;
        END

       SELECT bdclavenc FROM tclasse_vencimento
       WHERE (bdclavenc = NEW.bdclavenc) AND (bdcodrec = NEW.bdcodrec) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdclavenc)+1), 1) FROM tclasse_vencimento WHERE (bdcodrec = NEW.bdcodrec) INTO vclavenc;
           NEW.bdclavenc = vclavenc;
         END

    END
END
^

CREATE OR ALTER TRIGGER TCNAE_BI0 FOR TCNAE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodNovo INTEGER;

BEGIN
  IF ((NEW.BDCODCNAE IS NULL) OR (NEW.BDCODCNAE = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODCNAE) + 1, 1)
       FROM tcnae
       INTO :vCodNovo;

       NEW.BDCODCNAE = :vCodNovo;
     END
END
^

CREATE OR ALTER TRIGGER TCNAE_REF_BI0 FOR TCNAE_REF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodNovo INTEGER;

BEGIN
  IF ((NEW.BDCODCNAE IS NULL) OR (NEW.BDCODCNAE = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODCNAE), 1)
       FROM tcnae
       INTO :vCodNovo; /*pega o max da tabela principal, o registro que acabou de ser adicionado*/

       NEW.BDCODCNAE = :vCodNovo;
     END
END
^

CREATE OR ALTER TRIGGER TCODIGO_SERVICO_BI0 FOR TCODIGO_SERVICO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;

  IF ((NEW.bdcodser IS NULL) OR (NEW.bdcodser = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodser)+1),1) FROM tcodigo_servico INTO vcodigo;
        NEW.bdcodser = vcodigo;
     END
END
^

CREATE OR ALTER TRIGGER TCOMPLEMENTO_HIST_BI0 FOR TCOMPLEMENTO_HIST
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcodigo INTEGER;
BEGIN
  /* Trigger text */
  IF ((NEW.BDCODCOMPHIST IS NULL) OR (NEW.bdcodcomphist = 0) )THEN
     BEGIN
       SELECT COALESCE(MAX(x.BDCODCOMPHIST),0)+1 FROM tcomplemento_hist x INTO vcodigo;
       NEW.BDCODCOMPHIST = vcodigo;
     END
END
^

CREATE OR ALTER TRIGGER TCOMPLEMENTO_HIST_ESP_BI0 FOR TCOMPLEMENTO_HIST_ESP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vChave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemesp IS NULL) OR (NEW.bdordemesp = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordemesp)+1), 1) FROM TCOMPLEMENTO_HIST_ESP WHERE bdcodcomphist = NEW.bdcodcomphist INTO vChave;
       NEW.bdordemesp = vChave;
     END
  ELSE
     BEGIN
       SELECT bdordemesp FROM TCOMPLEMENTO_HIST_ESP WHERE (bdordemesp = NEW.bdordemesp) AND (bdcodcomphist = NEW.bdcodcomphist) INTO vcodigo;
    
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemesp)+1), 1) FROM TCOMPLEMENTO_HIST_ESP WHERE bdcodcomphist = NEW.bdcodcomphist INTO vChave;
           NEW.bdordemesp = vChave;
         END
     END
END
^

CREATE OR ALTER TRIGGER TCOMPONENTES_ETIQUETA_BI0 FOR TCOMPONENTES_ETIQUETA
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodrep IS NULL) OR (NEW.bdcodrep = 0)) THEN
     BEGIN
       SELECT MAX(bdcodrep) FROM trepositorio INTO NEW.bdcodrep;
     END

  IF ((NEW.bdcodmod IS NULL) OR (NEW.bdcodmod = 0))  THEN
     BEGIN
       SELECT MAX(bdcodmod) FROM tmodelo_etiqueta WHERE bdcodrep = NEW.bdcodrep INTO NEW.bdcodmod;
     END

  IF ((NEW.bdcodcomp IS NULL) OR (NEW.bdcodcomp = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodcomp),0)+1 FROM tcomponentes_etiqueta WHERE bdcodrep = NEW.bdcodrep AND bdcodmod = NEW.bdcodmod INTO NEW.bdcodcomp;
     END
END
^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_AU0 FOR TCONF_CONTAS_ONLINE
ACTIVE AFTER UPDATE POSITION 0 
AS
 DECLARE VARIABLE vCount INTEGER;
  declare variable wnada BIGINT;
BEGIN
  /* Trigger text */

  IF ((NEW.BDCOPYTITULO IS NULL) OR (NEW.BDCOPYTITULO <> 1)) THEN
     BEGIN
--       SELECT COUNT(*) FROM tol_update_conta up
--              WHERE up.bdcodplanoonline = NEW.bdcodplanoonline
--                   AND (up.bdchave = NEW.bdchave OR
--                        up.bdchavetitulo = NEW.bdchave) INTO vCount;
--       IF (vCount > 0) THEN
--          BEGIN
--            EXECUTE PROCEDURE sp_atu_lancamentos_contabil(NEW.bdcodplanoonline,NEW.bdchave,0,
--                                                          NEW.BDCONTADEBPROV,NEW.BDCONTACREDPROV,NEW.BDCODHISTPROV,
--                                                          OLD.BDCONTADEBPROV,OLD.BDCONTACREDPROV,OLD.BDCODHISTPROV,
--                                                          NEW.BDCODPLAPADRAO,NULL);
--          
--            EXECUTE PROCEDURE sp_atu_lancamentos_contabil(NEW.bdcodplanoonline,NEW.bdchave,1,
--                                                          NEW.BDCONTADEBPGTO,NEW.BDCONTACREDPGTO,NEW.BDCODHISTPGTO,
--                                                          OLD.BDCONTADEBPGTO,OLD.BDCONTACREDPGTO,OLD.bdcodhistpgto,
--                                                          NEW.BDCODPLAPADRAO,NULL);
--          END
     
       IF (OLD.bdclassificacao <> NEW.bdclassificacao) THEN
          BEGIN
            UPDATE tol_update_conta up SET up.bdclassifbusca = NEW.bdclassificacao WHERE up.bdclassifbusca = OLD.bdclassificacao AND up.BDCODPLANOONLINE = OLD.BDCODPLANOONLINE;
            UPDATE tol_update_conta up SET up.bdclassiftitulo = NEW.bdclassificacao WHERE up.bdclassiftitulo = OLD.bdclassificacao AND up.BDCODPLANOONLINE = OLD.BDCODPLANOONLINE;
          END
     
     --       fsql = 'update tol_update_conta up set up.bdchavetitulo = up.bdchave'||
     --              ' where up.bdchave = '||new.bdchave||' and up.bdchavetitulo <> up.bdchave and up.bdcodplanoonline = '||new.bdcodplanoonline;
     
     --       execute statement fsql;
   END

  wnada = GEN_ID(GEN_ALT_PLANOONLINE, 1);
END
^


CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_BI0 FOR TCONF_CONTAS_ONLINE
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE v1 INTEGER;
  DECLARE VARIABLE v2 INTEGER;
  DECLARE VARIABLE v3 INTEGER;
  declare variable wnada BIGINT;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDchave)+1),1) FROM TCONF_CONTAS_ONLINE  WHERE BDCODPLANOONLINE = NEW.bdcodplanoonline INTO vcodigo;
       NEW.BDCHAVE = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDCHAVE FROM tconf_contas_online WHERE (BDCODPLANOONLINE = NEW.bdcodplanoonline) AND (BDCHAVE = NEW.BDCHAVE) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCHAVE)+1),1) FROM tconf_contas_online WHERE BDCODPLANOONLINE = NEW.bdcodplanoonline INTO vcodigo;
            NEW.BDCHAVE = vcodigo;
         END
    END

  /*carrega codigo de planos quando inserir regitro novo */
  IF ((NEW.BDCODPLAPADRAO IS NULL) OR (NEW.BDCODTPHI IS NULL) OR (NEW.BDCODCENTRO IS NULL))  THEN
     BEGIN
       SELECT BDCODPLAPADRAO,BDCODHIST,BDCODCENTRO FROM tplano_conf_online WHERE bdcodplanoonline = NEW.BDCODPLANOONLINE INTO v1,v2, v3;

       IF (NEW.BDCODPLAPADRAO IS NULL)  THEN
          NEW.BDCODPLAPADRAO = v1;
       IF (NEW.BDCODTPHI IS NULL) THEN
          NEW.BDCODTPHI = v2;
       IF (NEW.BDCODCENTRO IS NULL) THEN
          NEW.BDCODCENTRO = v3;

     END

  if (trim(new.bdnaocontab) = '') then
     new.bdnaocontab = null;

  wnada = GEN_ID(GEN_ALT_PLANOONLINE, 1);
END
^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_BU0 FOR TCONF_CONTAS_ONLINE
ACTIVE BEFORE UPDATE POSITION 0
AS
DECLARE VARIABLE v1 INTEGER;
DECLARE VARIABLE v2 INTEGER;
DECLARE VARIABLE v3 INTEGER;
BEGIN
  IF ((NEW.BDCODPLAPADRAO IS NULL) OR (NEW.BDCODTPHI IS NULL) OR (NEW.BDCODCENTRO IS NULL))  THEN
     BEGIN
       SELECT BDCODPLAPADRAO,BDCODHIST,BDCODCENTRO FROM tplano_conf_online WHERE bdcodplanoonline = NEW.BDCODPLANOONLINE INTO v1,v2, v3;

       IF (NEW.BDCODPLAPADRAO IS NULL)  THEN
          NEW.BDCODPLAPADRAO = v1;
       IF (NEW.BDCODTPHI IS NULL) THEN
          NEW.BDCODTPHI = v2;
       IF (NEW.BDCODCENTRO IS NULL) THEN
          NEW.BDCODCENTRO = v3;

     END

  if (trim(new.bdnaocontab) = '') then
     new.bdnaocontab = null;
END
^

CREATE OR ALTER TRIGGER TCONF_HISTCONTAS_BI0 FOR TCONF_HISTCONTAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.bdcodconfhistconta IS NULL) OR (NEW.bdcodconfhistconta = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodconfhistconta) + 1, 1)
       FROM TCONF_HISTCONTAS
       INTO :vNovoCod;

       NEW.bdcodconfhistconta = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER TCONFCONSFORM_BI0 FOR TCONFCONSFORM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vCodigo = 0;
  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdordem)+1),1)
        FROM TCONFCONSFORM
        WHERE bdcodqplaconsconf = NEW.bdcodqplaconsconf
        AND bdcodplaconsconf = NEW.bdcodplaconsconf
        AND bdcodsis = NEW.bdcodsis
        INTO vcodigo;
        NEW.bdordem = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdordem
       FROM TCONFCONSFORM
       WHERE bdordem = NEW.bdordem
       AND bdcodqplaconsconf = NEW.bdcodqplaconsconf
       AND bdcodplaconsconf = NEW.bdcodplaconsconf
       AND bdcodsis = NEW.bdcodsis
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdordem)+1),1)
            FROM TCONFCONSFORM
            WHERE bdcodqplaconsconf = NEW.bdcodqplaconsconf
            AND bdcodplaconsconf = NEW.bdcodplaconsconf
            AND bdcodsis = NEW.bdcodsis
            INTO vcodigo;
            NEW.bdordem = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TCONFIG_RELATORIOS_BI0 FOR TCONFIG_RELATORIOS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCod INTEGER;

BEGIN
  IF (NEW.BDCODCONREL IS NULL OR (NEW.BDCODCONREL = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(X.BDCODCONREL) + 1), 1) FROM TCONFIG_RELATORIOS X INTO vCod;
        NEW.BDCODCONREL = vCod;
     END
END
^

CREATE OR ALTER TRIGGER TDETGPSSEFIP_INS FOR TDETGPSSEFIP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE wacu NUMERIC(15,6);
  DECLARE VARIABLE wacuterc NUMERIC(15,6);
  DECLARE VARIABLE wchave INTEGER;
  DECLARE VARIABLE wsql VARCHAR(300);
BEGIN
  wsql = 'select x.bdchave,x.bdacumulado,x.bdacumuladoterc from tdetgpssefip x '||
         ' where x.bdcodemp = '||NEW.bdcodemp;

  IF (NEW.bdcodtpcc IS NULL) THEN
     wsql = wsql||' and x.bdcodtpcc is null';
  ELSE
     wsql = wsql||' and x.bdcodtpcc ='||NEW.bdcodtpcc;

  EXECUTE STATEMENT wsql INTO wchave,wacu,wacuterc;

  IF (wchave IS NOT NULL) THEN
     BEGIN
       wsql = 'delete from tdetgpssefip x where x.bdchave = '||wchave;

       EXECUTE STATEMENT wsql;

       NEW.bdacumulado = NEW.bdacumulado + wacu;
       NEW.bdacumuladoterc = NEW.bdacumuladoterc + wacuterc;
     END

  /* Trigger text */
  IF ((NEW.bdchave IS NULL)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdchave)+1,1) FROM tdetgpssefip INTO NEW.bdchave;
     END
END
^

CREATE OR ALTER TRIGGER TDIFERENCA_IMP_BI0 FOR TDIFERENCA_IMP
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF (NEW.BDCODEMPCOL IS NULL) THEN
     NEW.BDCODEMPCOL = NEW.BDCODEMP;
END
^

CREATE OR ALTER TRIGGER TDOCARRECADACAO_BI0 FOR TDOCARRECADACAO
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF (NEW.bdcoddocarrec IS NULL) THEN
     SELECT COALESCE(MAX(bdcoddocarrec)+1,1) FROM tdocarrecadacao INTO NEW.bdcoddocarrec;
END
^

CREATE OR ALTER TRIGGER TEMISSAOIMPOSTO_BI0 FOR TEMISSAOIMPOSTO
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF (NEW.bdcodclient IS NULL) THEN
     NEW.bdcodclient = 1;
END
^

CREATE OR ALTER TRIGGER TEMP_SPED_FCONT_REF_BI0 FOR TEMP_SPED_FCONT_REF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT bdresult FROM maxsci('bdcodemp', 'bdcodemp', ' (bdstatusemp <> 1) ', 'tempresas') INTO vcodigo;   --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018
        NEW.bdcodemp = vcodigo;
     END
  ELSE
     BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
          BEGIN
            SELECT bdresult FROM maxsci('bdcodemp', 'bdcodemp', ' (bdstatusemp <> 1) ', 'tempresas') INTO vcodigo;--#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018
            NEW.bdcodemp = vcodigo;
          END
     END
END
^



CREATE OR ALTER TRIGGER TEMPRESAS_AU0 FOR TEMPRESAS
ACTIVE AFTER UPDATE POSITION 0 
AS
  DECLARE VARIABLE vEMPREF INTEGER;
  DECLARE VARIABLE vCODIMP INTEGER;
  DECLARE VARIABLE vCLASSIMP VARCHAR(40);
BEGIN
  -- gilberto - 11/03/2014 - ALT#:7290 - finaliza impostos que são calculados apenas pela matriz. Obs.: verificar automatismo da tabela TEMPRESAS_REF
  IF ((COALESCE(OLD.bdcodmatriz, 0) <> COALESCE(NEW.bdcodmatriz, 0)) AND (NEW.bdcodmatriz IS NOT NULL)) THEN
     BEGIN
       SELECT bdempref FROM vw_empresas_ref_atual WHERE bdcodemp = NEW.bdcodemp INTO :vempref;
       IF (SUBSTRING(vempref FROM 5 FOR 2) = '01') THEN
          vempref = vempref - 89;
       ELSE
          vempref = vempref - 1;

       FOR SELECT emp.bdcodimp, timp.bdclassimp FROM tempresaimposto emp
           INNER JOIN timposto timp ON (timp.bdcodimp = emp.bdcodimp)
           WHERE emp.bdcodemp = NEW.bdcodemp
           AND ((SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.01.03')) = '01.01.01.03') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.01.04')) = '01.01.01.04') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.01')) = '01.01.02.01') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.02')) = '01.01.02.02') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.03')) = '01.01.02.03') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.04')) = '01.01.02.04') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.06')) = '01.01.02.06') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.08')) = '01.01.02.08') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.09')) = '01.01.02.09') OR
                (SUBSTRING(timp.bdclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.10')) = '01.01.02.10'))
           INTO :vcodimp, :vclassimp DO
           BEGIN
             UPDATE tempresaimposto SET
             bdreffimimp = :vempref
             WHERE bdcodemp = NEW.bdcodemp
             AND bdcodimp = :vcodimp;
           END
     END
END
^

CREATE OR ALTER TRIGGER TEMPRESAS_BD0 FOR TEMPRESAS
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE EXCLUIREG_INTERMEDIARIOS_ONLINE(OLD.bdcodemp);


  -- Gilberto - 05/09/2019 - Em analise com o módulo Fiscal, concluiu-se que não podemos colocar a exclusão dessas tabela como DELETE CASCADE, então para resolver a exclusão de empresas em massa, foi feito esse procedimento que só se ativa nessa situação.
--  if ((select first 1 upper(BDVALUE) from VW_GET_EXCLUIREMPRESAS) = 'TRUE') then -- Gilberto - 17/09/2019 - deve sempre executar esse script quando excluir empresa
  begin
    update VEF_EMP_TC195SAI set bdcodobs = null where bdcodemp = old.bdcodemp;
    update VEF_REINF_EVT set bdcodretif = null, bdrecibo = null where bdcodemp = old.bdcodemp;
    delete from VEF_EMP_TMOVSAIINFCOM where bdcodemp = old.bdcodemp;
    delete from VEF_BASE_TPLANOACOESTROCA pla where bdcodobsc195 in (select obs.bdcodobs from vef_base_tobservacao obs where obs.bdcodemp = old.bdcodemp);
  end
END
^

CREATE OR ALTER trigger tempresas_bu0 for tempresas
active before update position 0
as
declare variable VCODESC integer;
declare variable VCODPLANOONLINE integer;
declare variable VCODPLAPADRAO integer;
declare variable VCODHIST integer;
declare variable VCODCENTROS integer;
declare variable VCODEMPLANC integer;
declare variable VBDDATAINIESOCIAL date;
declare variable VCODUSU integer;
declare variable vDATAHORA timestamp;
declare variable vIP varchar(15);
begin
  if (new.BDEXCLUIREMP IS NULL) then
  begin
     new.BDEXCLUIR_QDO = NULL;
  end
  
  if (new.BDCODMATRIZ is null) then
  begin
    update TEMPRESAS
    set BDCODESC = new.BDCODESC
    where BDCODMATRIZ = new.BDCODEMP and
          BDCODESC <> new.BDCODESC;
    update TEMPRESAS
    set BDDATAINIESOCIAL = new.BDDATAINIESOCIAL
    where BDCODMATRIZ = new.BDCODEMP and
          BDDATAINIESOCIAL <> new.BDDATAINIESOCIAL;
  end
  else
  if (coalesce(new.BDCODMATRIZ, 0) <> coalesce(old.BDCODMATRIZ, 0)) then
  begin
    select BDCODESC from TEMPRESAS
    where BDCODEMP = new.BDCODMATRIZ
    into :VCODESC;
    new.BDCODESC = VCODESC;
    if ((VCODESC is not null)and(VCODESC<>0)) then
    begin
-- Gilberto - 12/12/2018 - Retirado porque dá erro no cadastro de empresa quando tem "tranzação sped", possívelmente a seção do sistema não é a mesma da trigger
--      EXECUTE PROCEDURE SP_INSERIR_LOG(new.BDCODEMP, NULL, null, NULL, null, NULL, null, null, 'Empresa adicionada ao escritório automáticamente porque a empresa se tornou filial da empresa '||new.bdcodmatriz, 0, 1,
--                                       null, null, 'TEMPRESAS', 'Cadastro de empresas', NULL, 'TEMPRESAS', NULL, 'FALSE', null);
    end

    select BDDATAINIESOCIAL
    from TEMPRESAS
    where BDCODEMP = new.BDCODMATRIZ
    into :VBDDATAINIESOCIAL;
    new.BDDATAINIESOCIAL = VBDDATAINIESOCIAL;

    --#Alt:19940 - Precisamos verificar se não existe movimentação na matriz e filiais antes de fazer a alteração
    select first 1 emp.BDCODEMP
    from TEMPRESAS emp
    join VSUC_EMPRESAS_TLAN lan on lan.bdcodemp = emp.bdcodemp
    where new.BDCODMATRIZ in (emp.bdcodemp, emp.BDCODMATRIZ)
    into :VCODEMPLANC;

    if (VCODEMPLANC is null) then
    begin
      select first 1 BDCODPLANOONLINE, BDCODPLAPADRAO, BDCODHIST, BDCODCENTROS
      from VW_EMPRESAS_REF_ATUAL
      where BDCODEMP = new.BDCODMATRIZ
      into :VCODPLANOONLINE, :VCODPLAPADRAO, :VCODHIST, :VCODCENTROS;

      update TEMPRESAS_REF
      set BDCODPLANOONLINE = :VCODPLANOONLINE,
          BDCODPLAPADRAO = :VCODPLAPADRAO,
          BDCODHIST = :VCODHIST,
          BDCODCENTROS = :VCODCENTROS
      where (BDCODEMP = new.BDCODEMP) and
            ((BDCODPLANOONLINE <> :VCODPLANOONLINE) or (BDCODPLAPADRAO <> :VCODPLAPADRAO) or (BDCODHIST <> :VCODHIST) or (BDCODCENTROS <> :VCODCENTROS));
    end
  end

  -- Tratamento para Sicalc, quando alterava o CNPJ continuava buscando o registro do CNPJ antigo
  if ((COALESCE(OLD.bdcodmatriz, 0) <> COALESCE(NEW.bdcodmatriz, 0)) or (OLD.bdcnpjemp <> NEW.bdcnpjemp) or (OLD.bdmatriznaocadsis <> NEW.bdmatriznaocadsis)) then
    NEW.BDTOKENSICALC = '';

  -- Auditor folha - se trocar de plano, precisa limpar os alertas que já foram buscados do plano anterior
  IF ((COALESCE(OLD.bdcodpavemp, 0) <> COALESCE(NEW.bdcodpavemp, 0))) THEN
     begin
       if (old.bdcodpavemp is not null) then
          begin
            delete from VRH_BASE_ALERTA_VENC where bdcodemp = old.bdcodemp and bdcodpav = old.bdcodpavemp;
          end
     end

  /* Gilberto - 29/03/2022 - criado para tentar rastrear qual processo muda CNPJ e vínculo da empresa */
  if (new.bdcnpjemp <> old.bdcnpjemp) then
     EXECUTE PROCEDURE SP_INSERIR_LOG(new.bdcodemp, NULL, null, NULL, null, NULL, null, null, 'CNPJ da empresa mudou [De:'||old.bdcnpjemp||'] <-> [Para:'||new.bdcnpjemp||']', 0, 1, null, null, (select BDNOMETELA from vw_get_processo), (select BDCAPTIONTELA from vw_get_processo), NULL, 'TEMPRESAS', NULL, 'FALSE', null);
  if (coalesce(new.bdcodcli, 0) <> coalesce(old.bdcodcli, 0)) then
     EXECUTE PROCEDURE SP_INSERIR_LOG(new.bdcodemp, NULL, null, NULL, null, NULL, null, null, 'Vinculo entre empresa e cliente [De:'||old.bdcodcli||'] <-> [Para:'||new.bdcodcli||']', 0, 1, null, null, (select BDNOMETELA from vw_get_processo), (select BDCAPTIONTELA from vw_get_processo), NULL, 'TEMPRESAS', NULL, 'FALSE', null);
end^

CREATE OR ALTER TRIGGER TEMPRESAS_CTACORRENTE_BI0 FOR TEMPRESAS_CTACORRENTE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdchave)+1),1) FROM TEMPRESAS_CTACORRENTE WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;
        NEW.bdchave = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdchave FROM TEMPRESAS_CTACORRENTE WHERE bdchave = NEW.bdchave AND bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1),1) FROM TEMPRESAS_CTACORRENTE WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;
            NEW.bdchave = vcodigo;
         END
    END
  IF (((NEW.BDCODLCDPR IS NULL) OR (NEW.BDCODLCDPR = 0)) AND NEW.bdchave < 999) THEN
    BEGIN
      vcodigo = 0;
      SELECT first 1 bdchave FROM TEMPRESAS_CTACORRENTE WHERE bdcodemp = NEW.bdcodemp AND BDCODLCDPR = NEW.bdchave INTO vcodigo;
      if (vcodigo = 0) then
        NEW.BDCODLCDPR = NEW.bdchave;
    END
END
^

--#alt:22876. Ana - 22/03/2018
CREATE OR ALTER TRIGGER VSUC_EMPRESAS_TCALCPOC_BI0 FOR VSUC_EMPRESAS_TCALCPOC
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE VCODIGO INTEGER;
BEGIN
  VCODIGO = 0;
  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVE) + 1), 1) FROM VSUC_EMPRESAS_TCALCPOC
      WHERE BDCODEMP = NEW.BDCODEMP  INTO VCODIGO;

      NEW.BDCHAVE = VCODIGO;
    END
  ELSE
    BEGIN
      SELECT BDCHAVE FROM VSUC_EMPRESAS_TCALCPOC
      WHERE BDCHAVE = NEW.BDCHAVE AND BDCODEMP = NEW.BDCODEMP INTO VCODIGO;

      IF (VCODIGO > 0) THEN
      BEGIN
        SELECT COALESCE((MAX(BDCHAVE) + 1), 1) FROM VSUC_EMPRESAS_TCALCPOC
        WHERE BDCODEMP = NEW.BDCODEMP INTO VCODIGO;

        NEW.BDCHAVE = VCODIGO;
      END
    END
END
^

--#alt:23031. Ana - 22/03/2018
CREATE OR ALTER TRIGGER VSUC_TTRANSFCUSTOINCOR_BI0 FOR VSUC_EMPRESAS_TTRANSFCUSTOINCOR
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE VCODIGO INTEGER;
BEGIN
  VCODIGO = 0;
  IF ((NEW.bdchavetransfcustoincorp IS NULL) OR (NEW.bdchavetransfcustoincorp = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchavetransfcustoincorp) + 1), 1) FROM vsuc_empresas_ttransfcustoincor
      WHERE BDCODEMP = NEW.BDCODEMP  INTO VCODIGO;

      NEW.bdchavetransfcustoincorp = VCODIGO;
    END
  ELSE
    BEGIN
      SELECT bdchavetransfcustoincorp FROM vsuc_empresas_ttransfcustoincor
      WHERE bdchavetransfcustoincorp = NEW.bdchavetransfcustoincorp AND BDCODEMP = NEW.BDCODEMP INTO VCODIGO;

      IF (VCODIGO > 0) THEN
      BEGIN
        SELECT COALESCE((MAX(bdchavetransfcustoincorp) + 1), 1) FROM vsuc_empresas_ttransfcustoincor
        WHERE BDCODEMP = NEW.BDCODEMP INTO VCODIGO;

        NEW.bdchavetransfcustoincorp = VCODIGO;
      END
    END
END
^

--#alt:23826. Ana - 24/04/2018
CREATE OR ALTER TRIGGER bfi_vsuc_tprocevolucobra FOR vsuc_empresas_tprocevolucobra
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE VCODIGO INTEGER;
BEGIN
  VCODIGO = 0;
  IF ((NEW.BDCHAVEPROCEVOLUCOBRA IS NULL) OR (NEW.BDCHAVEPROCEVOLUCOBRA = 0)) THEN
  BEGIN
    SELECT COALESCE((MAX(BDCHAVEPROCEVOLUCOBRA) + 1), 1) FROM VSUC_EMPRESAS_TPROCEVOLUCOBRA
    WHERE BDCODEMP = NEW.BDCODEMP INTO VCODIGO;

    NEW.BDCHAVEPROCEVOLUCOBRA = VCODIGO;
  END
  ELSE
  BEGIN
    SELECT BDCHAVEPROCEVOLUCOBRA FROM VSUC_EMPRESAS_TPROCEVOLUCOBRA
    WHERE BDCHAVEPROCEVOLUCOBRA = NEW.BDCHAVEPROCEVOLUCOBRA AND BDCODEMP = NEW.BDCODEMP
    INTO VCODIGO;

    IF (VCODIGO > 0) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVEPROCEVOLUCOBRA) + 1), 1) FROM VSUC_EMPRESAS_TPROCEVOLUCOBRA
      WHERE BDCODEMP = NEW.BDCODEMP INTO VCODIGO;

      NEW.BDCHAVEPROCEVOLUCOBRA = VCODIGO;
    END
  END
END
^

CREATE OR ALTER TRIGGER VSUC_EMPRESAS_TPREINCORP_BI0 FOR VSUC_EMPRESAS_TPREINCORP
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE VCODIGO INTEGER;
BEGIN
  VCODIGO = 0;
  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVE) + 1), 1) FROM vsuc_empresas_tpreincorp
      WHERE BDCODEMP = NEW.BDCODEMP  INTO VCODIGO;

      NEW.BDCHAVE = VCODIGO;
    END
  ELSE
    BEGIN
      SELECT BDCHAVE FROM vsuc_empresas_tpreincorp
      WHERE BDCHAVE = NEW.BDCHAVE AND BDCODEMP = NEW.BDCODEMP INTO VCODIGO;

      IF (VCODIGO > 0) THEN
      BEGIN
        SELECT COALESCE((MAX(BDCHAVE) + 1), 1) FROM vsuc_empresas_tpreincorp
        WHERE BDCODEMP = NEW.BDCODEMP INTO VCODIGO;

        NEW.BDCHAVE = VCODIGO;
      END
    END
END
^
--#alt:23031. fim

CREATE OR ALTER TRIGGER TEMPRESAS_HIST_BI0 FOR TEMPRESAS_HIST
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (BDSTATUSEMP <> 1) INTO vcodigo; --#Alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 14/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (BDSTATUSEMP <> 1) INTO vcodigo; --#Alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 14/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TEMPRESAS_IMG_BI0 FOR TEMPRESAS_IMG
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT bdresult FROM maxsci('bdcodemp', 'bdcodemp', ' (bdstatusemp <> 1) ', 'tempresas') INTO vcodigo;  --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018
        NEW.bdcodemp = vcodigo;
     END
  ELSE
     BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
          BEGIN
            SELECT bdresult FROM maxsci('bdcodemp', 'bdcodemp', ' (bdstatusemp <> 1) ', 'tempresas') INTO vcodigo;  --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018
            NEW.bdcodemp = vcodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER TEMPRESAS_ISENCOES_BI0 FOR TEMPRESAS_ISENCOES
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodisencao IS NULL) OR (NEW.bdcodisencao = 0)) THEN
     SELECT COALESCE(MAX(bdcodisencao),0)+1 FROM tempresas_isencoes INTO NEW.bdcodisencao;
END
^

CREATE OR ALTER TRIGGER TEMPRESAS_REF_AD0 FOR TEMPRESAS_REF
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE sp_atualiza_apelido_ie_emp(OLD.bdcodemp,NULL);
END
^



CREATE OR ALTER TRIGGER tempresas_ref_ai0 FOR tempresas_ref
INACTIVE AFTER INSERT POSITION 0
AS
BEGIN
--  EXECUTE PROCEDURE sp_atualiza_apelido_ie_emp(NEW.bdcodemp,NEW.bdrefemp);
END
^

CREATE OR ALTER TRIGGER TEMPRESAS_REF_AI1 FOR TEMPRESAS_REF
ACTIVE AFTER INSERT OR UPDATE POSITION 1
AS
  DECLARE VARIABLE vCount INTEGER;
  DECLARE VARIABLE vrefant INTEGER;
  DECLARE VARIABLE vrefini INTEGER;
  DECLARE VARIABLE vreffin INTEGER;
  DECLARE VARIABLE vrefaux INTEGER;
  DECLARE VARIABLE vcodmatriz INTEGER;
  DECLARE VARIABLE vcodimp INTEGER;
  DECLARE VARIABLE vcodimp1 INTEGER;
  DECLARE VARIABLE vcodimp2 INTEGER;
  DECLARE VARIABLE vclassimp VARCHAR(20);
  DECLARE VARIABLE vcodplatrib INTEGER;
  DECLARE VARIABLE vcodplatribant INTEGER;
  DECLARE VARIABLE vcoddarfativa INTEGER;
  declare variable vVFIN_ATU_SITEMP varchar(5);
BEGIN
  -- Gilberto - 13/09/2021 - W154809 - Situação Financeira de clientes
  -- Apenas para execução de script que atualiza situação de empresa (inativa) por competência
  SELECT TRIM(rdb$get_context('USER_SESSION', 'VFIN_ATU_SITEMP')) FROM rdb$database into :vVFIN_ATU_SITEMP;
  if (upper(coalesce(vVFIN_ATU_SITEMP, 'FALSE')) = 'TRUE') then
  begin
    rdb$set_context('USER_SESSION', 'VFIN_ATU_SITEMP', null);
    exit;
  end

  EXECUTE PROCEDURE sp_atualiza_apelido_ie_emp(NEW.bdcodemp,NEW.bdrefemp);

  /* IMPOSTOS COM MAIS DE UMA REFERENCIA EM ABERTO */
  FOR SELECT bdcodimp, bdrefemp, bdreffimimp FROM tempresaimposto imp
      WHERE bdcodemp = NEW.bdcodemp
      AND (SELECT COUNT(*) FROM tempresaimposto WHERE bdcodemp = imp.bdcodemp AND bdcodimp = imp.bdcodimp AND bdreffimimp IS NULL) > 1
      ORDER BY bdcodemp, bdcodimp, bdrefemp DESC
      INTO :vcodimp, :vrefini, :vreffin DO
      BEGIN
        IF (vcodimp <> vcodimp1) THEN
           vrefant = NULL;
        IF (vrefant IS NOT NULL) THEN
        BEGIN
          IF (SUBSTRING(vrefant FROM 5 FOR 2) = '01') THEN
             vrefant = vrefant - 89;
          ELSE
             vrefant = vrefant - 1;
          UPDATE tempresaimposto SET bdreffimimp = :vrefant WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = :vcodimp AND bdrefemp = :vrefini;
        END
        vcodimp1 = vcodimp;
        vrefant = vrefini;
      END


  SELECT FIRST 1 BDCODPLATRIB FROM tempresas_ref WHERE BDCODEMP = NEW.BDCODEMP AND BDREFEMP < NEW.bdrefemp ORDER BY BDREFEMP DESC INTO :vcodplatribant;
  SELECT FIRST 1 BDCODEMP FROM tdarfpadrao WHERE BDCODEMP = NEW.bdcodemp into :vcoddarfativa;
  /* APENAS SE HOUVER MUDANÇA DE PLANO TRIBUTÁRIO ----------------------------------------------------------------------------------------------------------------------------------------------------- */
  IF ((vcoddarfativa is NULL) AND (vcodplatribant IS NULL)) then
  BEGIN

    /* PLANO TRIBUTÀRIO ANTERIOR */
    IF (OLD.bdcodplatrib IS NULL) THEN
       vcodplatrib = vcodplatribant;
    ELSE
       vcodplatrib = OLD.bdcodplatrib;
    /* REFERENCIA ANTERIOR */
    vrefant = NEW.bdrefemp;
    IF (SUBSTRING(vrefant FROM 5 FOR 2) = '01') THEN
       vrefant = vrefant - 89;
    ELSE
       vrefant = vrefant - 1;
    /* MATRIZ */
    SELECT bdcodmatriz FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO :vcodmatriz;

/* IMPOSTOS ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
    /* LISTA OS IMPOSTOS DOS DOIS PLANOS, ANTERIOR E ATUAL, PARA COMPARAR AS MUDANÇAS E COM ISSO FINALIZA OU INSERE OS IMPOSTOS */
    FOR SELECT DISTINCT --bdcodplatrib1, bdcodplatrib2,
               CASE WHEN (bdcodimp1 IS NULL) THEN bdcodimp2 ELSE bdcodimp1 END bdcodimp,
               bdcodimp1, bdcodimp2, imp.bdclassimp AS bdclassimp2
        FROM (
        SELECT trib1.bdcodplatrib AS bdcodplatrib1, trib1.bdcodimp AS bdcodimp1, trib2.bdcodplatrib AS bdcodplatrib2, trib2.bdcodimp AS bdcodimp2 FROM vct_tributos_plano_tributario trib1
        LEFT JOIN vct_tributos_plano_tributario trib2 ON (trib2.bdcodplatrib = NEW.BDCODPLATRIB AND trib2.bdcodimp IS NOT NULL AND trib1.bdcodimp = trib2.bdcodimp)
        WHERE trib1.bdcodplatrib = :vcodplatrib
        AND trib1.bdcodimp IS NOT NULL
        UNION
        SELECT trib2.bdcodplatrib, trib2.bdcodimp, trib1.bdcodplatrib, trib1.bdcodimp FROM vct_tributos_plano_tributario trib1
        LEFT JOIN vct_tributos_plano_tributario trib2 ON (trib2.bdcodplatrib = :vcodplatrib AND trib2.bdcodimp IS NOT NULL AND trib1.bdcodimp = trib2.bdcodimp)
        WHERE trib1.bdcodplatrib = NEW.BDCODPLATRIB
        AND trib1.bdcodimp IS NOT NULL
        )
        LEFT OUTER JOIN timposto imp ON (imp.bdcodimp = bdcodimp2 AND coalesce(imp.bdperapuracao, 0) <> 11)
        ORDER BY bdcodimp
        INTO :vcodimp, :vcodimp1, :vcodimp2, :vclassimp DO
        BEGIN
          IF (vcodimp2 IS NULL) THEN
          BEGIN
            UPDATE tempresaimposto SET bdreffimimp = :vrefant WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = :vcodimp AND (bdreffimimp IS NULL OR (bdreffimimp = 0));
          END
          ELSE
          /* quando for filial, não importar esses tributos, pois os mesmos são calculados apenas pela matriz */
          IF ((vcodmatriz IS NULL) OR
              ((vcodmatriz IS NOT NULL) AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.01.03')) <> '01.01.01.03') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.01.04')) <> '01.01.01.04') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.01')) <> '01.01.02.01') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.02')) <> '01.01.02.02') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.03')) <> '01.01.02.03') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.04')) <> '01.01.02.04') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.06')) <> '01.01.02.06') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.08')) <> '01.01.02.08') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.09')) <> '01.01.02.09') AND
               (SUBSTRING(vclassimp FROM 1 FOR CHAR_LENGTH('01.01.02.10')) <> '01.01.02.10'))) THEN
          BEGIN
            vcount = NULL;
            SELECT FIRST 1 bdcodimp FROM tempresaimposto WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = :vcodimp AND bdrefemp <= NEW.bdrefemp AND bdreffimimp IS NULL INTO :vcount;
            IF (vcount IS NULL) THEN
               UPDATE OR INSERT INTO tempresaimposto (bdcodemp, bdrefemp, bdcodimp, bdreffimimp) VALUES (NEW.bdcodemp, NEW.bdrefemp, :vcodimp, NULL) MATCHING (bdcodemp, bdrefemp, bdcodimp);

            vrefaux = NULL;
            FOR SELECT bdrefemp FROM tempresaimposto WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = :vcodimp AND bdrefemp > NEW.bdrefemp AND bdreffimimp IS NULL INTO :vrefaux DO
            BEGIN
              IF (vrefaux IS NOT NULL) THEN
              BEGIN
                IF (SUBSTRING(vrefaux FROM 5 FOR 2) = '01') THEN
                   vrefaux = vrefaux - 89;
                ELSE
                   vrefaux = vrefaux - 1;
  
                UPDATE tempresaimposto SET bdreffimimp = :vrefaux WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = :vcodimp AND bdrefemp = NEW.bdrefemp AND bdreffimimp IS NULL;
              END
            END
          END
        END
    /* AJUSTA REFERÊNCIAS QUANDO ALTERA UM ANTERIOR A OUTRA QUE JÁ FOI INSERIDA */
    vcodimp1 = 0;
    FOR SELECT bdcodimp, bdrefemp, bdreffimimp
        FROM tempresaimposto imp
        WHERE bdcodemp = NEW.bdcodemp
        AND (SELECT COUNT(*) FROM tempresaimposto WHERE bdcodemp = imp.bdcodemp AND bdcodimp = imp.bdcodimp) > 1
        ORDER BY bdcodemp, bdcodimp, bdrefemp DESC
        INTO :vcodimp, :vrefini, :vreffin DO
        BEGIN
          IF (vcodimp1 <> vcodimp) THEN
             vrefant = 0;

          IF ((vrefini IS NOT NULL) AND (vrefant <> 0)) THEN
          BEGIN
            IF (NOT ((vreffin >= vrefini) AND (vreffin <= vrefant))) THEN
            BEGIN
              UPDATE tempresaimposto SET bdreffimimp = :vrefant WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = :vcodimp AND bdrefemp = :vrefini;
            END
          END

          vcodimp1 = vcodimp;
          IF (SUBSTRING(vrefini FROM 5 FOR 2) = '01') THEN
             vrefant = vrefini - 89;
          ELSE
             vrefant = vrefini - 1;
        END
  end

  /* CASO REFERENCIA FINAL FOR MENOR QUE INICIAL */
  UPDATE tempresaimposto SET bdreffimimp = bdrefemp WHERE BDCODEMP = NEW.bdcodemp AND bdreffimimp < bdrefemp;
  /* ELIMINA IMPOSTOS INDEFINIDOS */
  DELETE FROM tempresaimposto IMP WHERE BDCODEMP = NEW.bdcodemp AND EXISTS (SELECT * FROM TIMPOSTO WHERE BDCODIMP = IMP.BDCODIMP AND bdperapuracao = 11);
END
^

CREATE OR ALTER TRIGGER TEMPRESAS_REF_BI0 FOR TEMPRESAS_REF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (BDSTATUSEMP <> 1) INTO vcodigo; --#Alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 26/01/2018
        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (BDSTATUSEMP <> 1) INTO vcodigo; --#Alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 26/01/2018
            NEW.bdcodemp = vcodigo;
         END
    END

  --#Alt:19940.
  IF (NEW.bdcodcentros = 0) THEN
     NEW.bdcodcentros = NULL; 
END
^

CREATE OR ALTER TRIGGER tempresas_ref_bu0 FOR tempresas_ref
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  --#Alt:19940.
  IF (NEW.bdcodcentros = 0) THEN
     NEW.bdcodcentros = NULL;
END
^

CREATE OR ALTER TRIGGER TEMPRESAS_REN_ISENCOES_BI0 FOR TEMPRESAS_REN_ISENCOES
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodrenisencao IS NULL) OR (NEW.bdcodrenisencao = 0)) THEN
     SELECT COALESCE(MAX(bdcodrenisencao),0)+1 FROM tempresas_ren_isencoes WHERE bdcodemp = NEW.bdcodemp AND bdcodisencao = NEW.bdcodisencao INTO NEW.bdcodrenisencao;
END
^

CREATE OR ALTER trigger tempresas_scp_bi for tempresas_scp
active before insert position 0
AS
DECLARE VARIABLE wCodEmp INTEGER;
DECLARE VARIABLE wRefEmp INTEGER;
DECLARE VARIABLE wCodSCP INTEGER;
BEGIN
  wCodEmp = 0;
  wRefEmp = 0;
  wCodSCP = 0;
/*
  IF ( (NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0) ) THEN
    BEGIN
      SELECT COALESCE(MAX(bdcodemp), 1) FROM tempresas
      WHERE (BDSTATUSEMP <> 1) INTO wCodEmp; --#Alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 14/02/2018

      NEW.bdcodemp = :wCodEmp;
    END 
  */
  IF ( (NEW.bdrefemp IS NULL) OR (NEW.bdrefemp = 0) ) THEN
    BEGIN
      SELECT CAST(TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) AS INTEGER) FROM rdb$database INTO :wRefEmp;
      NEW.bdrefemp = :wRefEmp;
    END 
/*
  IF ( (NEW.bdcodscp IS NULL) OR (NEW.bdcodscp = 0) ) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodscp) + 1), 1) FROM tempresas_scp WHERE ( bdcodemp = NEW.bdcodemp ) AND ( bdrefemp = NEW.bdrefemp ) INTO :wCodSCP;
      NEW.bdcodscp = :wCodSCP;
    END
  ELSE
    BEGIN
      SELECT bdcodscp FROM tempresas_scp WHERE ( bdcodemp = NEW.bdcodemp ) AND ( bdrefemp = NEW.bdrefemp ) AND ( bdcodscp = NEW.bdcodscp ) INTO :wCodSCP;

      IF ( :wCodSCP > 0 ) THEN
        BEGIN
          SELECT COALESCE((MAX(bdcodscp) + 1), 1) FROM tempresas_scp WHERE ( bdcodemp = NEW.bdcodemp ) AND ( bdrefemp = NEW.bdrefemp ) INTO :wCodSCP;
          NEW.bdcodscp = :wCodSCP;
        END 
    END          */
    END
^

CREATE OR ALTER trigger tenqfed_bio for tenqfed
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vRef INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
--        select coalesce((max(bdcodemp)),1) from tempresas_ref into vcodigo;
        --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 14/02/2018
        /*SELECT FIRST 1 COALESCE(bdcodemp,1), bdrefemp FROM tempresas_ref
        ORDER BY bdcodemp DESC
        INTO vcodigo, vref;*/
        select first 1 coalesce(REF.BDCODEMP, 1), BDREFEMP from TEMPRESAS_REF REF
        inner join TEMPRESAS EMP on (REF.BDCODEMP = EMP.BDCODEMP and EMP.BDSTATUSEMP <> 1)
        order by REF.BDCODEMP desc  
        into vcodigo, vref;

        NEW.bdcodemp = vcodigo;
        NEW.bdrefemp = vref;
     END
  ELSE
    BEGIN
--       select bdcodemp from tempresas_ref where bdcodemp = NEW.bdcodemp into vcodigo;
        SELECT FIRST 1 COALESCE(bdcodemp,1), bdrefemp FROM tempresas_ref
        WHERE bdcodemp = NEW.bdcodemp
        ORDER BY bdcodemp DESC
        INTO vcodigo, vref;

       IF (vcodigo = 0) THEN
         BEGIN
--            select coalesce((max(bdcodemp)),1) from tempresas_ref into vcodigo;
            --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 14/02/2018
            /*SELECT FIRST 1 COALESCE(bdcodemp,1), bdrefemp FROM tempresas_ref
            ORDER BY bdcodemp DESC
            INTO vcodigo, vref;   */
            select first 1 coalesce(REF.BDCODEMP, 1), BDREFEMP from TEMPRESAS_REF REF
            inner join TEMPRESAS EMP on (REF.BDCODEMP = EMP.BDCODEMP and EMP.BDSTATUSEMP <> 1)
            order by REF.BDCODEMP desc
            into vcodigo, vref;

            NEW.bdcodemp = vcodigo;
            NEW.bdrefemp = vref;
         END
    END

  SELECT E.BDCODEMP
  FROM TENQFED E
  WHERE E.BDCODEMP = NEW.BDCODEMP
  AND E.BDREFEMP = NEW.BDREFEMP
  INTO :vCodigo;

  IF (ROW_COUNT > 0) THEN
    EXECUTE PROCEDURE LANCA_EXCEPTION('Inserindo enquadramento duplicado. Empresa:'||NEW.BDCODEMP||', Ref: '||NEW.BDREFEMP , NULL, NULL);
END^

CREATE OR ALTER TRIGGER TEXPORTACAO_IMPOSTOS_BI0 FOR TEXPORTACAO_IMPOSTOS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  IF ((NEW.BDCHAVEEXP IS NULL) OR (NEW.BDCHAVEEXP = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCHAVEEXP)+1,1) FROM texportacao_impostos INTO NEW.bdchaveexp;
     END
  ELSE
     BEGIN
       SELECT BDCHAVEEXP FROM texportacao_impostos WHERE BDCHAVEEXP = NEW.bdchaveexp INTO vcodigo;

       IF (vcodigo <> 0) THEN
          BEGIN
            SELECT COALESCE(MAX(BDCHAVEEXP)+1,1) FROM texportacao_impostos INTO NEW.bdchaveexp;
          END
     END
END
^

CREATE OR ALTER TRIGGER TFATCONV_BI0 FOR TFATCONV
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vcodprod INTEGER;
  DECLARE VARIABLE vcodfatcon INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodfatcon IS NULL) OR (NEW.bdcodfatcon = 0)) THEN
    BEGIN
       IF ((NEW.bdcodprod IS NULL) OR (NEW.bdcodprod = 0)) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODPROD)), 1) FROM tcadpro INTO vcodprod;
            NEW.bdcodprod = vcodprod;
         END
       SELECT COALESCE((MAX(bdcodfatcon)+1), 1) FROM tfatconv
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodprod = NEW.bdcodprod) INTO vcodfatcon;
       NEW.bdcodfatcon = vcodfatcon;
    END
  ELSE
    BEGIN
       IF ((NEW.bdcodprod IS NULL) OR (NEW.bdcodprod = 0)) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODPROD)), 1) FROM tcadpro INTO vcodprod;
            NEW.bdcodprod = vcodprod;
         END

       SELECT bdcodfatcon FROM tfatconv
       WHERE (bdcodfatcon = NEW.bdcodfatcon) AND (bdcodprod = NEW.bdcodprod) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodfatcon)+1), 1) FROM tfatconv
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodprod = NEW.bdcodprod) AND (bdcodfatcon = NEW.bdcodfatcon) INTO vcodfatcon;
           NEW.bdcodfatcon = vcodfatcon;
         END

    END
END
^

CREATE OR ALTER TRIGGER TFERIADOSNOVO_BI0 FOR TFERIADOSNOVO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodferi IS NULL) OR (NEW.bdcodferi = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdcodferi)+1), 1) FROM TFERIADOSNOVO INTO vcodigo;
       NEW.bdcodferi = vcodigo;
     END
END
^

CREATE OR ALTER TRIGGER TFICHA_DIPJ_BI FOR TFICHA_DIPJ
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  IF (NEW.BDCODFICHA_DIPJ IS NULL OR NEW.BDCODFICHA_DIPJ = 0)  THEN
    NEW.BDCODFICHA_DIPJ = GEN_ID(GEN_TFICHA_DIPJ_ID,1);
END
^

CREATE OR ALTER TRIGGER TFICHA_ITENS_DIPJ_BI FOR TFICHA_ITENS_DIPJ
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  IF (NEW.BDCODITEM_DIPJ IS NULL OR NEW.BDCODITEM_DIPJ = 0) THEN
    NEW.BDCODITEM_DIPJ = GEN_ID(GEN_TFICHA_ITENS_DIPJ_ID,1);
END
^

CREATE OR ALTER TRIGGER TFORMULA_BIO FOR TFORMULA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodfor IS NULL) OR (NEW.bdcodfor = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdcodfor)+1), 1)
       FROM tformula
       INTO vcodigo;

       NEW.bdcodfor = vcodigo;
     END
END
^

CREATE OR ALTER TRIGGER THIST_CONTAS_BI0 FOR THIST_CONTAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.bdcodhistconta IS NULL) OR (NEW.bdcodhistconta = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodhistconta) + 1, 1)
       FROM thist_contas
       INTO :vNovoCod;

       NEW.bdcodhistconta = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER TIMPORTACAO_VSUP_BI0 FOR TIMPORTACAO_VSUP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vnovocod INTEGER;

BEGIN
  IF (NEW.bdcodivsup IS NULL OR (NEW.bdcodivsup = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODIVSUP) + 1, 1) FROM TIMPORTACAO_VSUP INTO :vnovocod;
       NEW.bdcodivsup = :vnovocod;
     END
END
^



CREATE OR ALTER trigger timposto_ai0 for timposto
active after insert or update position 0
AS
--  DECLARE VARIABLE vcodemp INTEGER;
--  DECLARE VARIABLE vrefemp INTEGER;
  DECLARE VARIABLE vextinto INTEGER;
BEGIN
  -- Augusto - 09/04/2024 - criado para caso encontre registro na tebela referente a obrigação atual, alterar data final para a data de extinção caso seja maior.
  if (new.BDDATAEXTINTO is not null) then
  begin
     :vextinto = cast((extract(year from NEW.bddataextinto) || lpad(extract(month from NEW.bddataextinto),2,0)) as integer);

     UPDATE vct_tributario_empresa y
     SET y.bdreffin = :vextinto
     WHERE (y.BDCODIMP = :new.BDCODIMP) AND ((y.bdreffin IS NULL) OR (y.bdreffin > :vextinto));

  END
  else
    begin
     :vextinto = cast((extract(year from OLD.bddataextinto) || lpad(extract(month from OLD.bddataextinto),2,0)) as integer);
--       if (old.bddataextinto <> :new.bddataextinto) then
       if (old.bddataextinto is not null) then
       begin
           UPDATE vct_tributario_empresa y
           SET y.bdreffin = null
           WHERE (y.BDCODIMP = :NEW.BDCODIMP) AND (coalesce(y.bdreffin,0)  = coalesce(:vextinto,0));
       end
    end
/* Gilberto - 25/03/2015 - ALT:#11161 - Tirado para não inserir nos planos tributários
  INSERT INTO VCT_TRIBUTOS_PLANO_TRIBUTARIO
  SELECT NULL AS bdcodtrib, tpla.bdcodplatrib, timp.bdcodimp, NULL AS bdcodser, NULL AS bdcodobr
  FROM timposto timp
  INNER JOIN vct_plano_tributario tpla ON (tpla.bdcodplatrib IS NOT NULL)
  WHERE timp.bdtipoclassimp = 1
  AND NOT timp.bdcodimp IN (SELECT DISTINCT bdcodimp
                            FROM vct_tributos_plano_tributario
                            WHERE bdcodimp IS NOT NULL)
  AND timp.bdcodimp = NEW.bdcodimp;

  FOR SELECT ref.bdcodemp, ref.bdempref
      FROM vw_empresas_ref_atual ref
      INNER JOIN tempresas emp ON (emp.bdcodemp = ref.bdcodemp)-- gilberto - 26/09/2014 - ALT:#9986
      WHERE ref.bdcodemp IN (SELECT DISTINCT bdcodemp FROM vct_tributario_empresa)
      AND bdempref >= SUBSTRING(bddatainiativemp FROM 1 FOR 4)||SUBSTRING(bddatainiativemp FROM 6 FOR 2)-- gilberto - 26/09/2014 - ALT:#9986
      INTO :vcodemp, :vrefemp DO
      BEGIN
        EXECUTE STATEMENT 'insert into tempresaimposto (BDCODEMP, BDREFEMP, BDCODIMP, BDREFFIMIMP) values ('||vcodemp||', '||vrefemp||', '||NEW.bdcodimp||', null)';
      END
*/
END^

CREATE OR ALTER TRIGGER TINDICES_BI0 FOR TINDICES
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodind IS NULL) OR (NEW.bdcodind = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodind)+1),1) FROM tindices INTO vcodigo;
       NEW.bdcodind = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodind FROM tindices WHERE bdcodind = NEW.bdcodind INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodind)+1),1) FROM tindices INTO vcodigo;
            NEW.bdcodind = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TITEM_REPOSITORIO_BI0 FOR TITEM_REPOSITORIO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE x INTEGER;
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodrep = 0) OR (NEW.bdcodrep IS NULL))  THEN
     BEGIN
       SELECT COALESCE(MAX(x.bdcodrep),0) FROM trepositorio x INTO NEW.bdcodrep;
     END

  IF ((NEW.bdchave = 0) OR (NEW.bdchave IS NULL))  THEN
     BEGIN
       SELECT COALESCE(MAX(x.bdchave),0)+1 FROM titem_repositorio x WHERE x.bdcodrep = NEW.bdcodrep INTO NEW.bdchave;
     END

  IF (NEW.bddescricaolabel IS NULL) THEN
     BEGIN
       NEW.bddescricaolabel = NEW.BDDESCRIPTION;
     END

  IF (NEW.bdtabela IS NOT NULL) THEN
     BEGIN
       SELECT COALESCE(BDCODTABGER,0) FROM TTABELAGERADOR WHERE BDCODTABGER = NEW.bdtabela INTO x;

       IF ((x = 0) OR (x IS NULL)) THEN
          NEW.bdtabela = NULL;
     END
END
^

CREATE OR ALTER TRIGGER TITEM_REPOSITORIO_BU0 FOR TITEM_REPOSITORIO
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF (NEW.bddescricaolabel IS NULL) THEN
     BEGIN
       NEW.bddescricaolabel = NEW.BDDESCRIPTION;
     END
END
^

CREATE OR ALTER TRIGGER TITEMCONFIGONLINE_BI0 FOR TITEMCONFIGONLINE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcodigo INTEGER;
BEGIN
  /* Trigger text */
  IF ((NEW.bdcoditemonline IS NULL) OR (NEW.bdcoditemonline = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(x.bdcoditemonline),0)+1 FROM titemconfigonline x INTO vcodigo;
       NEW.bdcoditemonline = vcodigo;
     END
END
^

CREATE OR ALTER TRIGGER TLOG_BI0 FOR TLOG
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
    vcod = Gen_Id(gen_tlog_id,1);
    NEW.BDCODIGO = :vcod;

    --Salvando o último ID do log por usuário
    rdb$set_context('USER_SESSION', 'W_ULT_ID_LOG', :vcod);
END
^

CREATE OR ALTER TRIGGER TLOGRADOURO_BI0 FOR TLOGRADOURO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;

BEGIN
  IF ((NEW.bdcodlogr IS NULL) OR (NEW.bdcodlogr = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODLOGR), 0) + 1 FROM TLOGRADOURO INTO :vcod;
       NEW.bdcodlogr = vcod;
     END

  NEW.bdsiglalogr = UPPER(NEW.bdsiglalogr);
  NEW.bddescbuscalogr = UPPER(NEW.bddescbuscalogr);
END
^

CREATE OR ALTER TRIGGER TLOGRADOURO_BU0 FOR TLOGRADOURO
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  NEW.bdsiglalogr = UPPER(NEW.bdsiglalogr);
  NEW.bddescbuscalogr = UPPER(NEW.bddescbuscalogr);
END
^

CREATE OR ALTER TRIGGER TMENU_SPEED_BI0 FOR TMENU_SPEED
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF ((NEW.bdcodmsp IS NULL) OR (NEW.bdcodmsp = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODMSP) + 1, 1) FROM TMENU_SPEED INTO :vcod;
       NEW.bdcodmsp = vcod;
     END
END
^

CREATE OR ALTER TRIGGER TMODELO_ETIQUETA_BI0 FOR TMODELO_ETIQUETA
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodrep IS NULL) OR (NEW.bdcodrep = 0)) THEN
     BEGIN
       SELECT MAX(bdcodrep) FROM trepositorio INTO NEW.bdcodrep;
     END

  IF ((NEW.bdcodmod IS NULL) OR (NEW.bdcodmod = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodmod),0)+1 FROM tmodelo_etiqueta WHERE bdcodrep = NEW.bdcodrep INTO NEW.bdcodmod;
     END
END
^

CREATE OR ALTER TRIGGER TMODELO_REL_BI0 FOR TMODELO_REL
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF (NEW.bdcodrep IS NULL) THEN
     BEGIN
       SELECT MAX(bdcodrep) FROM trepositorio INTO NEW.bdcodrep;
     END

  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdchave),0)+1 FROM tmodelo_rel WHERE bdcodrep = NEW.bdcodrep INTO NEW.bdchave;
     END
END
^

CREATE OR ALTER TRIGGER TNCM_BI0 FOR TNCM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdncmprod IS NULL) OR (NEW.bdncmprod = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdncmprod)+1),1) FROM tncm INTO vcodigo;
       NEW.bdncmprod = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdncmprod FROM tncm WHERE bdncmprod = NEW.bdncmprod INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdncmprod)+1),1) FROM tncm INTO vcodigo;
            NEW.bdncmprod = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TNOTAS_BI0 FOR TNOTAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  -- Trigger text
  vcodigo = 0;
  IF ((NEW.bdcodtnotas IS NULL) OR (NEW.bdcodtnotas = 0))  THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodtnotas)+1), 1) FROM tnotas WHERE bdcodind = NEW.bdcodind INTO vNova_Chave;
      NEW.bdcodtnotas = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdcodtnotas FROM tnotas WHERE (bdcodtnotas = NEW.bdcodtnotas) AND (bdcodind = NEW.bdcodind) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodtnotas)+1), 1) FROM tnotas WHERE bdcodind = NEW.bdcodind INTO vNova_Chave;
           NEW.bdcodtnotas = vNova_Chave;
           --NEW.bdcodtmoe = GEN_ID(gen_moedas_tmoe, 1);
           --exception ex_valor_text+NEW.bdcodtpcc;
         END
    END
END
^

CREATE OR ALTER TRIGGER tol_pbm_tblocop_ad0 FOR tol_pbm_tblocop
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  /* Trigger text */
  --DELETE FROM tol_pbmrec_tblocopfilial a WHERE a.bdcodemp = OLD.bdcodemp AND a.bdref = OLD.bdref AND A.BDCODCONFBLOCOP = OLD.BDCODCONFBLOCOP;
--  DELETE FROM VRH_EMP_TPBM a WHERE a.bdcodemp = OLD.bdcodemp AND a.bdref = OLD.bdref AND A.BDCODCONFBLOCOP = OLD.BDCODCONFBLOCOP;
  --Elizeu - 17-08-2018 - Bloco P/Reinf - Integração com a folha #88354
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    DELETE FROM VRH_EMP_TPBM a WHERE a.bdcodemp = OLD.bdcodemp AND a.bdref = OLD.bdref;
  end
END^

CREATE OR ALTER trigger tol_unico_pag_darf_bi0 for tol_unico_pag_darf
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_UNICO_PAG_DARF_AD0 FOR TOL_UNICO_PAG_DARF
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_unico_prov_darf_bi0 for tol_unico_prov_darf
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_UNICO_PROV_DARF_AD0 FOR TOL_UNICO_PROV_DARF
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
  
  /* Deleta os lancamentos do Online no RH */
  DELETE FROM TOL_VEF_EMP_TLANRH_SN sn WHERE sn.BDCODEMP = OLD.BDCODEMP AND sn.BDCHAVEDARF = OLD.BDCHAVEDARF;
END
^

/* Trigger: TOL_VSUC_EMPRESAS_TPROCEVOLUCOBRA_AD0 */
CREATE OR ALTER TRIGGER TOL_VSUC_EMPRESAS_TPROCEVOLUCOBRA_AD0 FOR TOL_VSUC_EMPRESAS_TPROCEVOLUCOBRA
ACTIVE AFTER DELETE POSITION 0
AS
begin
  EXECUTE PROCEDURE sp_exclui_online(old.bdcodemp, old.bdchave);
end
^

CREATE OR ALTER TRIGGER TOL_VATI_EMPRESAS_IMP_ATIVACONTAB_AD FOR TOL_VATI_EMPRESAS_IMP_ATIVACONTAB
ACTIVE AFTER DELETE POSITION 0
as
begin
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(old.bdcodemp, old.bdchave);
end
^

CREATE OR ALTER TRIGGER TOL_VSUC_EMPRESAS_TTRANSFCUSTOINCOR_AD FOR TOL_VSUC_EMPRESAS_TTRANSFCUSTOINCOR
ACTIVE AFTER DELETE POSITION 0
as
begin
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(old.bdcodemp, old.bdchave);
end
^

CREATE OR ALTER TRIGGER TOL_VSUC_EMPRESAS_VALORPRESENTE_AD FOR TOL_VSUC_EMPRESAS_VALORPRESENTE
ACTIVE AFTER DELETE POSITION 0
as
begin
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(old.bdcodemp, old.bdchave);
end
^

CREATE OR ALTER TRIGGER TOL_EMPRESAS_TBEM_TRANSFERENCIA_AD FOR TOL_EMPRESAS_TBEM_TRANSFERENCIA
ACTIVE AFTER DELETE POSITION 0
as
begin
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(old.bdcodemp, old.bdchave);
end
^

CREATE OR ALTER TRIGGER TOL_EMPRESAS_TBEM_TRANSF_CONTA_AD FOR TOL_EMPRESAS_TBEM_TRANSF_CONTA
ACTIVE AFTER DELETE POSITION 0
as
begin
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(old.bdcodemp, old.bdchave);
end
^

CREATE OR ALTER trigger tol_update_conta_bi0 for tol_update_conta
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  IF (NEW.bdchavetitulo IS NULL) THEN
     NEW.bdchavetitulo = NEW.bdchave;
  end
END^

CREATE OR ALTER trigger tol_vef_emp_tdaconger_bi0 for tol_vef_emp_tdaconger
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TDACONGER_AD0 FOR TOL_VEF_EMP_TDACONGER
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);

END
^

CREATE OR ALTER trigger tol_vef_emp_tblocomger_bi0 for tol_vef_emp_tblocomger
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TBLOCOMGER_AD0 FOR TOL_VEF_EMP_TBLOCOMGER
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(old.BDCODEMPSUC,old.bdCHAVE);
END
^

/* Trigger: TOL_VEF_EMP_TBLOCOMGER_M220_AD0 */
CREATE OR ALTER TRIGGER TOL_VEF_EMP_TBLOCOMGER_M220_AD0 FOR TOL_VEF_EMP_TBLOCOMGER_M220
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  DELETE FROM VEF_EMP_TAJUAPUPCM220620 WHERE BDCODEMP = OLD.BDCODEMPM220 AND BDCHAVE = OLD.BDCHAVE;
END
^

CREATE OR ALTER trigger tol_vef_emp_ticmsspedger_bi0 for tol_vef_emp_ticmsspedger
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TICMSSPEDGER_AD0 FOR TOL_VEF_EMP_TICMSSPEDGER
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  /* TRIGGER TEXT */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(old.BDCODEMPSUC,old.bdCHAVE);
END
^

CREATE OR ALTER trigger tol_vef_emp_tdimescger_bi0 for tol_vef_emp_tdimescger
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TDIMESCGER_AD0 FOR TOL_VEF_EMP_TDIMESCGER
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vef_emp_tgiaesger_bi0 for tol_vef_emp_tgiaesger
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TGIAESGER_AD0 FOR TOL_VEF_EMP_TGIAESGER
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vef_emp_tgiamgger_bi0 for tol_vef_emp_tgiamgger
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TGIAMGGER_AD0 FOR TOL_VEF_EMP_TGIAMGGER
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vef_emp_tgiaspger_bi0 for tol_vef_emp_tgiaspger
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TGIASPGER_AD0 FOR TOL_VEF_EMP_TGIASPGER
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vef_emp_tgiaprger_bi0 for tol_vef_emp_tgiaprger
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

-- Alt.: 11359 - Apuração de ICMS - Contabilização
CREATE OR ALTER TRIGGER TOL_VEF_EMP_TGIAPRGER_AD0 FOR TOL_VEF_EMP_TGIAPRGER
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END^

CREATE OR ALTER trigger tol_vef_emp_tgiarjger_bi0 for tol_vef_emp_tgiarjger
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TGIARJGER_AD0 FOR TOL_VEF_EMP_TGIARJGER
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.BDCHAVE);
END
^

CREATE OR ALTER trigger tol_vef_emp_tgiatoger_bi0 for tol_vef_emp_tgiatoger
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TGIATOGER_AD0 FOR TOL_VEF_EMP_TGIATOGER
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.BDCHAVE);
END
^

CREATE OR ALTER trigger tol_vef_emp_tgiaroger_bi0 for tol_vef_emp_tgiaroger
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TGIATOGER_AD0 FOR TOL_VEF_EMP_TGIATOGER
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.BDCHAVE);
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TGIATOGER_BI0 FOR TOL_VEF_EMP_TGIATOGER
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
      new.bdcodempsuc = new.bdcodemp;
  end
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TGIAROGER_AD0 FOR TOL_VEF_EMP_TGIAROGER
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END^
-- Alt.: 11359 - Fim


CREATE OR ALTER trigger tol_vef_emp_tipiger_bi0 for tol_vef_emp_tipiger
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TIPIGER_AD0 FOR TOL_VEF_EMP_TIPIGER
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
  
END
^

CREATE OR ALTER trigger tol_vef_emp_tciapger_bi0 for tol_vef_emp_tciapger
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TCIAPGER_AD0 FOR TOL_VEF_EMP_TCIAPGER
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vef_emp_tirlpger_bi0 for tol_vef_emp_tirlpger
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TIRLPGER_AD0 FOR TOL_VEF_EMP_TIRLPGER
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);

END^

CREATE OR ALTER trigger tol_vef_emp_tmovdemaisdoc_bi0 for tol_vef_emp_tmovdemaisdoc
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVDEMAISDOC_AD0 FOR TOL_VEF_EMP_TMOVDEMAISDOC
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END
^

CREATE OR ALTER TRIGGER vsuc_tdist_lucro_bi0 FOR vsuc_tdist_lucro
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if ((new.bddistlucro is null) or (new.bddistlucro = 0)) then
    SELECT COALESCE(MAX(BDDISTLUCRO) + 1, 1) FROM vsuc_tdist_lucro WHERE BDCODEMP = NEW.bdcodemp INTO NEW.bddistlucro;
end
^

CREATE OR ALTER TRIGGER VSUC_TJUROS_SOB_CAP_BI0 FOR VSUC_TJUROS_SOB_CAP
ACTIVE BEFORE INSERT POSITION 0
AS
begin
    if ((new.BDJUROSSOBCAP is null) or (new.BDJUROSSOBCAP = 0)) then
    SELECT COALESCE(MAX(BDJUROSSOBCAP) + 1, 1)
    from VSUC_TJUROS_SOB_CAP
    where BDCODEMP = new.BDCODEMP
    into new.BDJUROSSOBCAP;
end
^

CREATE OR ALTER TRIGGER TOL_VSUC_TJUROS_SOB_CAP_AD0 FOR TOL_VSUC_TJUROS_SOB_CAP
ACTIVE AFTER DELETE POSITION 0
AS
begin
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodemp,OLD.bdchave);
end
^

CREATE OR ALTER TRIGGER tol_vsuc_tdist_lucro_ad0 FOR tol_vsuc_tdist_lucro
ACTIVE AFTER DELETE POSITION 0
AS
begin
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodemp,OLD.bdchave);
end
^

CREATE OR ALTER trigger tol_vef_emp_tcredestoqf150_bi0 for tol_vef_emp_tcredestoqf150
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER VCT_BASE_INSTRUCAO_BI0 FOR VCT_BASE_INSTRUCAO
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCODINS INTEGER;
BEGIN
  IF ((NEW.BDCODINS IS NULL) OR (NEW.BDCODINS = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODINS) + 1, 1)
       FROM VCT_BASE_INSTRUCAO
       INTO :vCODINS;

       NEW.BDCODINS = :vCODINS;
     END
END^

CREATE OR ALTER TRIGGER VCT_BASE_INSTRUCAO_EMP_BI0 FOR VCT_BASE_INSTRUCAO_EMP
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCODINS INTEGER;
BEGIN
  IF ((NEW.BDCODINS IS NULL) OR (NEW.BDCODINS = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODINS), 1)
       FROM vct_base_instrucao
       INTO :vCODINS;

       NEW.BDCODINS = :vCODINS;
     END
END^

/* Trigger: TOL_VEF_EMP_TCREDESTOQF150_AD0 */
CREATE OR ALTER TRIGGER TOL_VEF_EMP_TCREDESTOQF150_AD0 FOR TOL_VEF_EMP_TCREDESTOQF150
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(old.BDCODEMPSUC,old.bdCHAVE);
END
^

/* Trigger: VEF_EMP_TMOVK291_BI0 */
CREATE OR ALTER TRIGGER VEF_EMP_TMOVK291_BI0 FOR VEF_EMP_TMOVK291
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vChave INTEGER;
  DECLARE VARIABLE vORDEM INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_TMOVK290 WHERE (bdcodemp = NEW.bdcodemp) INTO vChave;
          NEW.bdchave = vChave;
        END

       SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vef_emp_TMOVK291
       WHERE (bdcodemp = NEW.bdcodemp) AND (BDCHAVE = NEW.BDCHAVE) INTO vOrdem;
       NEW.BDORDEM = vOrdem;
    END
  ELSE
    BEGIN
      IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_TMOVK290 WHERE (bdcodemp = NEW.bdcodemp) INTO vChave;
          NEW.bdchave = vChave;
        END
    END
END
^

/* Trigger: VEF_EMP_TMOVK292_BI0 */
CREATE OR ALTER TRIGGER VEF_EMP_TMOVK292_BI0 FOR VEF_EMP_TMOVK292
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vChave INTEGER;
  DECLARE VARIABLE vORDEM INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_TMOVK290 WHERE (bdcodemp = NEW.bdcodemp) INTO vChave;
          NEW.bdchave = vChave;
        END

       SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vef_emp_TMOVK292
       WHERE (bdcodemp = NEW.bdcodemp) AND (BDCHAVE = NEW.BDCHAVE) INTO vOrdem;
       NEW.BDORDEM = vOrdem;
    END
  ELSE
    BEGIN
      IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_TMOVK290 WHERE (bdcodemp = NEW.bdcodemp) INTO vChave;
          NEW.bdchave = vChave;
        END
    END
END
^

/* Trigger: VEF_EMP_TMOVK301_BI0 */
CREATE OR ALTER TRIGGER VEF_EMP_TMOVK301_BI0 FOR VEF_EMP_TMOVK301
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vChave INTEGER;
  DECLARE VARIABLE vORDEM INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_TMOVK300 WHERE (bdcodemp = NEW.bdcodemp) INTO vChave;
          NEW.bdchave = vChave;
        END

       SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vef_emp_TMOVK301
       WHERE (bdcodemp = NEW.bdcodemp) AND (BDCHAVE = NEW.BDCHAVE) INTO vOrdem;
       NEW.BDORDEM = vOrdem;
    END
  ELSE
    BEGIN
      IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_TMOVK300 WHERE (bdcodemp = NEW.bdcodemp) INTO vChave;
          NEW.bdchave = vChave;
        END
    END
END
^

/* Trigger: VEF_EMP_TMOVK302_BI0 */
CREATE OR ALTER TRIGGER VEF_EMP_TMOVK302_BI0 FOR VEF_EMP_TMOVK302
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vChave INTEGER;
  DECLARE VARIABLE vORDEM INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_TMOVK300 WHERE (bdcodemp = NEW.bdcodemp) INTO vChave;
          NEW.bdchave = vChave;
        END

       SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vef_emp_TMOVK302
       WHERE (bdcodemp = NEW.bdcodemp) AND (BDCHAVE = NEW.BDCHAVE) INTO vOrdem;
       NEW.BDORDEM = vOrdem;
    END
  ELSE
    BEGIN
      IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_TMOVK300 WHERE (bdcodemp = NEW.bdcodemp) INTO vChave;
          NEW.bdchave = vChave;
        END
    END
END
^

CREATE OR ALTER trigger tol_vef_emp_tmovent_bi0 for tol_vef_emp_tmovent
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVENT_AD0 FOR TOL_VEF_EMP_TMOVENT
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vef_emp_tmoventparpgto_bi0 for tol_vef_emp_tmoventparpgto
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVENTPARPGTO_AD0 FOR TOL_VEF_EMP_TMOVENTPARPGTO
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TDIMEGERREGESP_AD0 FOR TOL_VEF_EMP_TDIMEGERREGESP
ACTIVE AFTER DELETE POSITION 0
AS
begin
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodemp, OLD.bdchave);
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVOREC_AD0 FOR TOL_VEF_EMP_TMOVOREC
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodemp,OLD.bdchave);

END
^

CREATE OR ALTER trigger tol_vef_emp_tmovratent_bi0 for tol_vef_emp_tmovratent
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVRATENT_AD0 FOR TOL_VEF_EMP_TMOVRATENT
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vef_emp_tmovratsai_bi0 for tol_vef_emp_tmovratsai
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVRATSAI_AD0 FOR TOL_VEF_EMP_TMOVRATSAI
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vef_emp_tmovratser_bi0 for tol_vef_emp_tmovratser
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVRATSER_AD0 FOR TOL_VEF_EMP_TMOVRATSER
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVRATOPEIMOBPG_AD FOR TOL_VEF_EMP_TMOVRATOPEIMOBIPGTO
ACTIVE AFTER DELETE POSITION 0
AS
begin
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
end
^

CREATE OR ALTER trigger tol_vef_emp_tmovratopeimobp_bi0 for tol_vef_emp_tmovratopeimobipgto
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVRATOPEIMOBI_AD0 FOR TOL_VEF_EMP_TMOVRATOPEIMOBI
ACTIVE AFTER DELETE POSITION 0
AS
begin
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVRATDEMDOC_AD0 FOR TOL_VEF_EMP_TMOVRATDEMDOC
ACTIVE AFTER DELETE POSITION 0
AS
begin
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
end
^

CREATE OR ALTER trigger tol_vef_emp_tmovratopeimobi_bi0 for tol_vef_emp_tmovratopeimobi
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER trigger tol_vef_emp_tmovratdemdoc_bi0 for tol_vef_emp_tmovratdemdoc
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER trigger tol_vef_emp_tmovsai_bi0 for tol_vef_emp_tmovsai
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVSAI_AD0 FOR TOL_VEF_EMP_TMOVSAI
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vef_emp_tmovsaiparpgto_bi0 for tol_vef_emp_tmovsaiparpgto
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVSAIPARPGTO_AD0 FOR TOL_VEF_EMP_TMOVSAIPARPGTO
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vef_emp_tmovf100parpgto_bi0 for tol_vef_emp_tmovf100parpgto
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVF100PARPGTO_AD0 FOR TOL_VEF_EMP_TMOVF100PARPGTO
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vef_emp_tmovser_bi0 for tol_vef_emp_tmovser
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVSER_AD0 FOR TOL_VEF_EMP_TMOVSER
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vef_emp_tmovserparpgto_bi0 for tol_vef_emp_tmovserparpgto
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVSERPARPGTO_AD0 FOR TOL_VEF_EMP_TMOVSERPARPGTO
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vef_emp_tredzvarcfop_bi0 for tol_vef_emp_tredzvarcfop
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TREDZVARCFOP_AD0 FOR TOL_VEF_EMP_TREDZVARCFOP
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);

END
^

--#alt:83227. Ana - 14/06/2018
CREATE OR ALTER TRIGGER TOL_UNICO_APURACAO_LALUR_AD0 FOR TOL_UNICO_APURACAO_LALUR
ACTIVE AFTER DELETE POSITION 0                                             
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodemp,OLD.bdchave);
END
^
--#alt:83227. fim

CREATE OR ALTER trigger tol_vef_emp_tserautofolha_ad0 for tol_vef_emp_tserautofolha
active after delete position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    --  BDORIGEM null ou 0 = Escrita fiscal 1 = RH

  IF (COALESCE(OLD.BDORIGEM,0) = 0) THEN
     DELETE FROM vrh_base_tservterc tnf WHERE tnf.bdcodemp = OLD.bdcodemp AND tnf.bdcodserv = OLD.bdchaverh AND tnf.bdcodter = OLD.bdcodterrh;
  ELSE
     DELETE FROM VEF_EMP_TMOVSER tnf WHERE tnf.bdcodemp = OLD.bdcodemp AND tnf.BDCHAVE = OLD.bdchaveef;
  end
END^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TSERINSS_AD0 FOR TOL_VEF_EMP_TSERINSS
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    DELETE FROM vrhf_emp_tnotasfiscais tnf WHERE tnf.bdcodemp = OLD.bdcodemp AND tnf.bdchave = OLD.bdchaverh;
  end
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TSERINSSCONT_AD0 FOR TOL_VEF_EMP_TSERINSSCONT
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  DELETE FROM vrhf_emp_tnfcont tnf WHERE tnf.bdcodemp = OLD.bdcodemp AND tnf.bdchave = OLD.bdchaverh;
  end
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tcalc_13_bi0 for tol_vrhf_emp_tcalc_13
active before insert position 0
as
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
end^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TCALC_13_AD0 FOR TOL_VRHF_EMP_TCALC_13
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tcalc_a13_bi0 for tol_vrhf_emp_tcalc_a13
active before insert position 0
as
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
end^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TCALC_A13_AD0 FOR TOL_VRHF_EMP_TCALC_A13
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tcalc_ad_bi0 for tol_vrhf_emp_tcalc_ad
active before insert position 0
as
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
end^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TCALC_AD_AD0 FOR TOL_VRHF_EMP_TCALC_AD
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tcalc_aut_bi0 for tol_vrhf_emp_tcalc_aut
active before insert position 0
as
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
end^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TCALC_AUT_AD0 FOR TOL_VRHF_EMP_TCALC_AUT
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tcalc_c13_bi0 for tol_vrhf_emp_tcalc_c13
active before insert position 0
as
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
end^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TCALC_C13_AD0 FOR TOL_VRHF_EMP_TCALC_C13
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tcalc_fa_bi0 for tol_vrhf_emp_tcalc_fa
active before insert position 0
as
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
end^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TCALC_FA_AD0 FOR TOL_VRHF_EMP_TCALC_FA
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tcalc_fer_bi0 for tol_vrhf_emp_tcalc_fer
active before insert position 0
as
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
end^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TCALC_FER_AD0 FOR TOL_VRHF_EMP_TCALC_FER
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tcalc_fn_bi0 for tol_vrhf_emp_tcalc_fn
active before insert position 0
as
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
end^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TCALC_FN_AD0 FOR TOL_VRHF_EMP_TCALC_FN
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tcalc_fn_fc_bi0 for tol_vrhf_emp_tcalc_fn_fc
active before insert position 0
as
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
end^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TCALC_FN_FC_AD0 FOR TOL_VRHF_EMP_TCALC_FN_FC
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_tcalc_fn_fc_int_bi0 for tol_vrhf_emp_tcalc_fn_fc_int
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER trigger TOL_VRHF_TCALC_FN_FC_INT_ad0 for TOL_VRHF_EMP_TCALC_FN_FC_INT
active after delete position 0
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tcalc_ft_bi0 for tol_vrhf_emp_tcalc_ft
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TCALC_FT_AD0 FOR TOL_VRHF_EMP_TCALC_FT
ACTIVE AFTER DELETE POSITION 0 
AS
  DECLARE VARIABLE wConta INTEGER;

BEGIN
  /* Trigger text */
  SELECT COUNT(bdcodempsuc) FROM TOL_VRHF_EMP_TCALC_FT x WHERE x.bdcodempsuc = OLD.bdcodempsuc AND x.bdchave = OLD.bdchave INTO wConta;

  IF (wconta <= 0) THEN
     EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tcalc_ft_fc_bi0 for tol_vrhf_emp_tcalc_ft_fc
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TCALC_FT_FC_AD0 FOR TOL_VRHF_EMP_TCALC_FT_FC
ACTIVE AFTER DELETE POSITION 0 
AS
  DECLARE VARIABLE wConta INTEGER;

BEGIN
  /* Trigger text */
  SELECT COUNT(bdcodempsuc) FROM TOL_VRHF_EMP_TCALC_FT_FC x WHERE x.bdcodempsuc = OLD.bdcodempsuc AND x.bdchave = OLD.bdchave INTO wConta;

  IF (wconta <= 0) THEN
     EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_tcalc_ft_fc_int_bi0 for tol_vrhf_emp_tcalc_ft_fc_int
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER trigger TOL_VRHF_TCALC_FT_FC_INT_ad0 for TOL_VRHF_EMP_TCALC_FT_FC_INT
active after delete position 0
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tcompgp_bi0 for tol_vrhf_emp_tcompgp
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TCOMPGP_AD0 FOR TOL_VRHF_EMP_TCOMPGP
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchavelan);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_nf_bi0 for tol_vrhf_emp_nf
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.bdcodempsuc, 0) = 0)  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_NF_AD0 FOR TOL_VRHF_EMP_NF
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchavelan);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tfgts_13_bi0 for tol_vrhf_emp_tfgts_13
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TFGTS_13_AD0 FOR TOL_VRHF_EMP_TFGTS_13
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tfgts_a13_bi0 for tol_vrhf_emp_tfgts_a13
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TFGTS_A13_AD0 FOR TOL_VRHF_EMP_TFGTS_A13
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tfgts_c13_bi0 for tol_vrhf_emp_tfgts_c13
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TFGTS_C13_AD0 FOR TOL_VRHF_EMP_TFGTS_C13
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tfgts_fa_bi0 for tol_vrhf_emp_tfgts_fa
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TFGTS_FA_AD0 FOR TOL_VRHF_EMP_TFGTS_FA
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
    EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tfgts_fc_bi0 for tol_vrhf_emp_tfgts_fc
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TFGTS_FC_AD0 FOR TOL_VRHF_EMP_TFGTS_FC
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tfgts_fc_int_bi0 for tol_vrhf_emp_tfgts_fc_int
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER trigger TOL_VRHF_EMP_TFGTS_FC_INT_ad0 for TOL_VRHF_EMP_TFGTS_FC_INT
active after delete position 0
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tfgts_fn_bi0 for tol_vrhf_emp_tfgts_fn
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TFGTS_FN_AD0 FOR TOL_VRHF_EMP_TFGTS_FN
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
    EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tfgts_ft_bi0 for tol_vrhf_emp_tfgts_ft
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TFGTS_FT_AD0 FOR TOL_VRHF_EMP_TFGTS_FT
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tfgts_ft_fc_bi0 for tol_vrhf_emp_tfgts_ft_fc
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TFGTS_FT_FC_AD0 FOR TOL_VRHF_EMP_TFGTS_FT_FC
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_tfgts_ft_fc_int_bi0 for tol_vrhf_emp_tfgts_ft_fc_int
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER trigger TOL_VRHF_TFGTS_FT_FC_INT_ad0 for TOL_VRHF_EMP_TFGTS_FT_FC_INT
active after delete position 0
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tpgto_calc_bi0 for tol_vrhf_emp_tpgto_calc
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TPGTO_CALC_AD0 FOR TOL_VRHF_EMP_TPGTO_CALC
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tprov13_bi0 for tol_vrhf_emp_tprov13
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TPROV13_AD0 FOR TOL_VRHF_EMP_TPROV13
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
 EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tprov13_det_bi0 for tol_vrhf_emp_tprov13_det
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TPROV13_DET_AD0 FOR TOL_VRHF_EMP_TPROV13_DET
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
 EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tprovfer_bi0 for tol_vrhf_emp_tprovfer
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TPROVFER_AD0 FOR TOL_VRHF_EMP_TPROVFER
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
 EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tprovfer_det_bi0 for tol_vrhf_emp_tprovfer_det
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TPROVFER_DET_AD0 FOR TOL_VRHF_EMP_TPROVFER_DET
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
   EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tverba_13_bi0 for tol_vrhf_emp_tverba_13
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TVERBA_13_AD0 FOR TOL_VRHF_EMP_TVERBA_13
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tverba_a13_bi0 for tol_vrhf_emp_tverba_a13
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TVERBA_A13_AD0 FOR TOL_VRHF_EMP_TVERBA_A13
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tverba_ad_bi0 for tol_vrhf_emp_tverba_ad
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TVERBA_AD_AD0 FOR TOL_VRHF_EMP_TVERBA_AD
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tverba_aut_bi0 for tol_vrhf_emp_tverba_aut
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TVERBA_AUT_AD0 FOR TOL_VRHF_EMP_TVERBA_AUT
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tverba_c13_bi0 for tol_vrhf_emp_tverba_c13
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TVERBA_C13_AD0 FOR TOL_VRHF_EMP_TVERBA_C13
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tverba_fa_bi0 for tol_vrhf_emp_tverba_fa
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TVERBA_FA_AD0 FOR TOL_VRHF_EMP_TVERBA_FA
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tverba_fcint_bi0 for tol_vrhf_emp_tverba_fcint
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER trigger TOL_VRHF_EMP_TVERBA_FCINT_ad0 for TOL_VRHF_EMP_TVERBA_FCINT
active after delete position 0
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tverba_fer_bi0 for tol_vrhf_emp_tverba_fer
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TVERBA_FER_AD0 FOR TOL_VRHF_EMP_TVERBA_FER
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tverba_fn_bi0 for tol_vrhf_emp_tverba_fn
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TVERBA_FN_AD0 FOR TOL_VRHF_EMP_TVERBA_FN
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tverba_fn_fc_bi0 for tol_vrhf_emp_tverba_fn_fc
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TVERBA_FN_FC_AD0 FOR TOL_VRHF_EMP_TVERBA_FN_FC
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tverba_ft_bi0 for tol_vrhf_emp_tverba_ft
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TVERBA_FT_AD0 FOR TOL_VRHF_EMP_TVERBA_FT
ACTIVE AFTER DELETE POSITION 0 
AS
  DECLARE VARIABLE wConta INTEGER;

BEGIN
  /* Trigger text */
  SELECT first 1 bdcodempsuc FROM TOL_VRHF_EMP_TVERBA_FT x WHERE x.bdcodempsuc = OLD.bdcodempsuc AND x.bdchave = OLD.bdchave INTO wConta;

  IF (coalesce(wConta, 0) <= 0) THEN
     EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tverba_ft_fc_bi0 for tol_vrhf_emp_tverba_ft_fc
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TVERBA_FT_FC_AD0 FOR TOL_VRHF_EMP_TVERBA_FT_FC
ACTIVE AFTER DELETE POSITION 0 
AS
  DECLARE VARIABLE wConta INTEGER;

BEGIN
  /* Trigger text */
  SELECT COUNT(bdcodempsuc) FROM TOL_VRHF_EMP_TVERBA_FT_FC x WHERE x.bdcodempsuc = OLD.bdcodempsuc AND x.bdchave = OLD.bdchave INTO wConta;

  IF (wconta <= 0) THEN
     EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_tverba_ft_fc_int_bi0 for tol_vrhf_emp_tverba_ft_fc_int
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER trigger TOL_VRHF_TVERBA_FT_FC_INT_ad0 for TOL_VRHF_EMP_TVERBA_FT_FC_INT
active after delete position 0
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER TRIGGER TORDEMREL_BI0 FOR TORDEMREL
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT MAX(bdchave) FROM tmodelo_rel WHERE bdcodrep = NEW.bdcodrep INTO NEW.bdchave;
     END

  IF (NEW.bdordem IS NULL) THEN
     BEGIN
       SELECT COALESCE(MAX(bdordem),0)+1 FROM tordemrel x WHERE x.bdcodrep = NEW.bdcodrep AND x.bdchave = NEW.bdchave AND UPPER(x.bddataset) = UPPER(NEW.bddataset) INTO NEW.bdordem;
     END
END
^

CREATE OR ALTER TRIGGER TORGAO_RESP_ESOCIAL_BI0 FOR TORGAO_RESP_ESOCIAL
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodoresp IS NULL) OR (NEW.bdcodoresp = 0)) THEN
     SELECT COALESCE(MAX(bdcodoresp),0)+1 FROM torgao_resp_esocial INTO NEW.bdcodoresp;
END
^

CREATE OR ALTER TRIGGER TPIS_ESTRUTURA_BI0 FOR TPIS_ESTRUTURA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;

BEGIN
  IF ((NEW.bdcodca IS NULL) OR (NEW.bdcodca = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODCA), -1) + 1 FROM TPIS_ESTRUTURA WHERE BDREGCA = NEW.BDREGCA INTO :vcod;
       NEW.bdcodca = vcod;
     END
END
^

CREATE OR ALTER TRIGGER TPIS_ESTRUTURACAMPOS_BI0 FOR TPIS_ESTRUTURACAMPOS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;

BEGIN
  IF ((NEW.bdcodcam IS NULL) OR (NEW.bdcodcam = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODCAM), -1) + 1 FROM TPIS_ESTRUTURACAMPOS WHERE BDREGCA = NEW.BDREGCA AND BDCODCA = NEW.BDCODCA INTO :vcod;
       NEW.bdcodcam = vcod;
     END
END
^

CREATE OR ALTER TRIGGER TPIS_MENSAGEMRETORNO_BI0 FOR TPIS_MENSAGEMRETORNO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;

BEGIN
  IF ((NEW.bdcodmr IS NULL) OR (NEW.bdcodmr = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODMR), -1) + 1 FROM TPIS_MENSAGEMRETORNO INTO :vcod;
       NEW.bdcodmr = vcod;
     END

  NEW.bdgravidademr = UPPER(NEW.bdgravidademr);
END
^

CREATE OR ALTER TRIGGER TPIS_MENSAGEMRETORNO_BU0 FOR TPIS_MENSAGEMRETORNO
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  NEW.bdgravidademr = UPPER(NEW.bdgravidademr);
END
^

CREATE OR ALTER TRIGGER TPIS_ORGAOEMISSAO_BI0 FOR TPIS_ORGAOEMISSAO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;

BEGIN
  IF ((NEW.bdcodoe IS NULL) OR (NEW.bdcodoe = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODOE), 0) + 1 FROM TPIS_ORGAOEMISSAO INTO :vcod;
       NEW.bdcodoe = vcod;
     END

  NEW.bdsiglaoe = UPPER(NEW.bdsiglaoe);
END
^

CREATE OR ALTER TRIGGER TPIS_ORGAOEMISSAO_BU0 FOR TPIS_ORGAOEMISSAO
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  NEW.bdsiglaoe = UPPER(NEW.bdsiglaoe);
END
^

CREATE OR ALTER TRIGGER TPLANO_CONF_ONLINE_BI0 FOR TPLANO_CONF_ONLINE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODPLANOONLINE IS NULL) OR (NEW.BDCODPLANOONLINE = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDCODPLANOONLINE)+1),1) FROM TPLANO_CONF_ONLINE INTO vcodigo;
       NEW.BDCODPLANOONLINE = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDCODPLANOONLINE FROM TPLANO_CONF_ONLINE WHERE BDCODPLANOONLINE = NEW.BDCODPLANOONLINE INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODPLANOONLINE)+1),1) FROM TPLANO_CONF_ONLINE INTO vcodigo;
            NEW.BDCODPLANOONLINE = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TPLANO_PROGRAMAS_BI0 FOR TPLANO_PROGRAMAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF ((NEW.bdcodplaprog IS NULL) OR (NEW.bdcodplaprog = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODPLAPROG), 0) + 1 FROM TPLANO_PROGRAMAS INTO :vCodigo;
       NEW.bdcodplaprog = :vCodigo;
     END
END
^

CREATE OR ALTER TRIGGER TPLANOCONSCONF_BI0 FOR TPLANOCONSCONF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vCodigo = 0;
  IF ((NEW.bdcodplaconsconf IS NULL) OR (NEW.bdcodplaconsconf = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodplaconsconf)+1),1)
        FROM TPLANOCONSCONF
        WHERE bdcodsis = NEW.bdcodsis
        INTO vcodigo;
        NEW.bdcodplaconsconf = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodplaconsconf
       FROM TPLANOCONSCONF
       WHERE bdcodplaconsconf = NEW.bdcodplaconsconf
       AND bdcodsis = NEW.bdcodsis
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodplaconsconf)+1),1)
            FROM TPLANOCONSCONF
            WHERE bdcodsis = NEW.bdcodsis
            INTO vcodigo;
            NEW.bdcodplaconsconf = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TPLANOCONSCONF_Q_BI0 FOR TPLANOCONSCONF_Q
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vCodigo = 0;
  IF ((NEW.bdcodqplaconsconf IS NULL) OR (NEW.bdcodqplaconsconf = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodqplaconsconf)+1),1)
        FROM TPLANOCONSCONF_Q
        WHERE bdcodplaconsconf = NEW.bdcodplaconsconf
        AND bdcodsis = NEW.bdcodsis
        INTO vcodigo;
        NEW.bdcodqplaconsconf = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodqplaconsconf
       FROM TPLANOCONSCONF_Q
       WHERE bdcodqplaconsconf = NEW.bdcodqplaconsconf
       AND bdcodplaconsconf = NEW.bdcodplaconsconf
       AND bdcodsis = NEW.bdcodsis
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodqplaconsconf)+1),1)
            FROM TPLANOCONSCONF_Q
            WHERE bdcodplaconsconf = NEW.bdcodplaconsconf
            AND bdcodsis = NEW.bdcodsis
            INTO vcodigo;
            NEW.bdcodqplaconsconf = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TPROGRAMAS_BI0 FOR TPROGRAMAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  IF ((NEW.bdcodprog IS NULL) OR (NEW.bdcodprog = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODPROG), 0) + 1 FROM TPROGRAMAS WHERE BDCODPLAPROG = NEW.bdcodplaprog INTO :vCodigo;
       NEW.bdcodprog = :vCodigo;
     END
END
^

CREATE OR ALTER TRIGGER TPROPERTY_ETIQUETA_BI0 FOR TPROPERTY_ETIQUETA
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodrep IS NULL) OR (NEW.bdcodrep = 0)) THEN
     BEGIN
       SELECT MAX(bdcodrep) FROM trepositorio INTO NEW.bdcodrep;
     END

  IF ((NEW.bdcodmod IS NULL) OR (NEW.bdcodmod = 0))  THEN
     BEGIN
       SELECT MAX(bdcodmod) FROM tmodelo_etiqueta WHERE bdcodrep = NEW.bdcodrep INTO NEW.bdcodmod;
     END

  IF ((NEW.bdcodcomp IS NULL) OR (NEW.bdcodcomp = 0)) THEN
     BEGIN
       SELECT MAX(bdcodcomp) FROM tcomponentes_etiqueta WHERE bdcodrep = NEW.bdcodrep AND bdcodmod = NEW.bdcodmod INTO NEW.bdcodcomp;
     END

END
^

CREATE OR ALTER TRIGGER TQUADRO_ITENS_DIME_BI FOR TQUADRO_ITENS_DIME
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  IF (NEW.BDCODITEM_DIME IS NULL OR NEW.BDCODITEM_DIME = 0) THEN
    NEW.BDCODITEM_DIME = GEN_ID(GEN_TQUADRO_ITENS_DIME_ID,1);
END
^

CREATE OR ALTER TRIGGER TQUALIFICACAO_BI0 FOR TQUALIFICACAO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdCODQUA IS NULL) OR (NEW.bdCODQUA = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdCODQUA) + 1), 1) FROM TQUALIFICACAO  INTO vCodigo;
      NEW.bdCODQUA = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdCODQUA FROM TQUALIFICACAO WHERE bdCODQUA = NEW.bdCODQUA INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdCODQUA) + 1), 1) FROM TQUALIFICACAO  INTO vCodigo;
           NEW.bdCODQUA = vCodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TQUALIFICACAOSOC_BI0 FOR TQUALIFICACAOSOC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdqualificacaosoc IS NULL) OR (NEW.bdqualificacaosoc = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdqualificacaosoc)+1),1) FROM tqualificacaosoc INTO vcodigo;
       NEW.bdqualificacaosoc = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdqualificacaosoc FROM tqualificacaosoc WHERE bdqualificacaosoc = NEW.bdqualificacaosoc INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdqualificacaosoc)+1),1) FROM tqualificacaosoc INTO vcodigo;
            NEW.bdqualificacaosoc = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER tr_bf_delete_tdarfpadrao FOR tdarfpadrao
ACTIVE BEFORE DELETE POSITION 0
AS
  DECLARE VARIABLE vcodigo INTEGER;
BEGIN

--  delete from tdarfpadrao where BDORDEMCOMPL = old.bdordem and bdcodemp = old.bdcodemp and bdchavedarf <> old.bdchavedarf;

--  exception ex_date 'executando update';
  -- Gilberto - 11/09/2014 - Não pode excluir documento gerado, deve apenas eliminar sua referência com o imposto gerado
  UPDATE vct_empresa_docsgerados SET bdchavedarf = NULL WHERE (bdcodemp = OLD.bdcodemp) AND (bdchavedarf = OLD.bdchavedarf) AND (bdcodpts IS NOT NULL) AND (bdcodipts IS NOT NULL);
  -- gilberto - 12/12/2014 - quando excluir imposto deve manter histórico nos protocolos
  UPDATE vct_empresa_protodocsaida SET bdchavedarf = NULL WHERE bdcodemp = OLD.bdcodemp AND bdchavedarf = OLD.bdchavedarf;
--  DELETE FROM vct_empresa_docsgerados WHERE bdcodemp = OLD.bdcodemp AND bdchavedarf = OLD.bdchavedarf;

  -- gilberto - 24/02/2015 - ALT:#10494 - deve excluir documento gerados que não pertence a nenhumprotocolo quando excluir o imposto
  DELETE FROM vct_empresa_docsgerados WHERE (bdcodemp = OLD.bdcodemp) AND (bdchavedarf = OLD.bdchavedarf) AND (bdcodpts IS NULL) AND (bdcodipts IS NULL);

  UPDATE VSH_EMP_TCONFERENCIA_IMPOSTO
  SET BDCHAVEDARF     = NULL,
      BDCODUSUALT     = (SELECT BDCODUSU FROM SP_GET_USUARIO),
      BDDATAALTERACAO = localtimestamp
  WHERE BDCODEMP      = OLD.BDCODEMP
  AND BDCHAVEDARF     = OLD.BDCHAVEDARF
  AND BDCODAUTOTHREAD IN(6);

  IF ((SELECT FIRST 1 U.BDCODUSU FROM TUSUARIO U WHERE U.BDNOMUSU = 'schip') <> (SELECT BDCODUSU FROM SP_GET_USUARIO)) THEN
    BEGIN
      UPDATE VSH_EMP_TCONFERENCIA_IMPOSTO
      SET BDCHAVEDARF     = NULL
      WHERE BDCODEMP      = OLD.BDCODEMP
      AND BDCHAVEDARF     = OLD.BDCHAVEDARF
      AND BDCODAUTOTHREAD IN(7);
    END

  --sol:16476 - verifica se é um complemento pra remover o registro do VRH_EMP_TTRIBUTACAO_SN
  vcodigo = 0;

  SELECT bdORDEMCOMPL FROM tdarfpadrao WHERE (bdCODEMP = OLD.bdCODEMP) AND (bdCHAVEDARF = OLD.bdCHAVEDARF) INTO vcodigo;

  IF ((vcodigo IS NULL) OR (vcodigo = 0)) THEN
     BEGIN
       FOR EXECUTE STATEMENT 'SELECT bdCODFILIAL FROM tol_vef_emp_tlanrh_sn WHERE (bdCODEMP = '||OLD.bdCODEMP||') AND (bdCHAVEDARF = '||OLD.bdCHAVEDARF||')'
       INTO
         vcodigo
       DO
        BEGIN
          DELETE FROM tol_vef_emp_tlanrh_sn WHERE (bdCODEMP = OLD.bdCODEMP) AND (bdCHAVEDARF = OLD.bdCHAVEDARF) AND (bdCODFILIAL = :vcodigo);
          DELETE FROM VRH_EMP_TTRIBUTACAO_SN sn WHERE (sn.BDCODEMP = :vcodigo) AND (sn.BDREFERENCIA = OLD.BDREFERENCIA);
        END
     END
  ELSE
     DELETE FROM tol_vef_emp_tlanrh_sn WHERE (bdCODEMP = OLD.bdCODEMP) AND (bdCHAVEDARF = OLD.bdCHAVEDARF);
END^

CREATE OR ALTER TRIGGER TR_BF_I_VRH_BASE_TTERC_TDEP_IMG FOR VRH_BASE_TTERC_TDEP_IMG
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;
BEGIN
  IF ((NEW.bdcoddpnterc IS NULL) OR (NEW.bdcoddpnterc = 0)) THEN
     BEGIN
       SELECT MAX(bdcoddpnterc)
       FROM vrh_base_tterc_tdep
       WHERE NEW.bdcodter = bdcodter
       INTO :vNovoCod;

       NEW.bdcoddpnterc = vNovoCod;
     END
END
^
CREATE OR ALTER TRIGGER TR_BF_IN_TDARFGERPGTO_BI0 FOR TDARFGERPGTO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
   IF ((NEW.BDCODPGTO IS NULL) OR (NEW.BDCODPGTO = 0)) THEN
      BEGIN
        SELECT COALESCE(MAX(BDCODPGTO+1), 1) FROM tdarfgerpgto
        WHERE (bdcodemp = NEW.bdcodemp)  AND (BDCHAVEDARF = NEW.BDCHAVEDARF) INTO vCodigo;
        NEW.BDCODPGTO = vCodigo;
      END
   ELSE
      BEGIN
        SELECT bdcodpgto FROM tdarfgerpgto WHERE (bdcodpgto = NEW.bdcodpgto) AND (bdcodemp = NEW.bdcodemp) AND (bdchavedarf = NEW.bdchavedarf) INTO vCodigo;
        IF (vcodigo > 0) THEN
           BEGIN
              SELECT COALESCE(MAX(BDCODPGTO+1), 1) FROM tdarfgerpgto WHERE (bdcodemp = NEW.bdcodemp)  AND (BDCHAVEDARF = NEW.BDCHAVEDARF) INTO vCodigo;
              NEW.bdcodpgto = vCodigo;
           END
      END
END
^

CREATE OR ALTER trigger tr_bf_in_vef_emp_tmoventpar for vef_emp_tmoventpar
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.BDORDEMPAR IS NULL) OR (NEW.BDORDEMPAR = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       SELECT COALESCE((MAX(BDORDEMPAR)+1), 1) FROM vef_emp_tmoventpar WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Chave;
       NEW.BDORDEMPAR = vNova_Chave;
    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       SELECT BDORDEMPAR FROM vef_emp_tmoventpar
       WHERE (BDORDEMPAR = NEW.BDORDEMPAR) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMPAR)+1), 1) FROM vef_emp_tmoventpar
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
           NEW.BDORDEMPAR = vNova_Chave;
         END
    END
  end
END
^

CREATE OR ALTER trigger tr_bf_in_vef_emp_tmoventparpag for vef_emp_tmoventparpgto
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
  DECLARE VARIABLE vOrdemPar INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.BDCODPGTOPAR IS NULL) OR (NEW.BDCODPGTOPAR = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventpar WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END

       IF ((NEW.BDORDEMPAR IS NULL) OR (NEW.BDORDEMPAR = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDORDEMPAR)), 1) FROM vef_emp_tmoventpar WHERE (bdcodemp = NEW.bdcodemp)
                                                                            AND (bdChave = NEW.bdChave) INTO vOrdemPar;
            NEW.BDORDEMPAR = vOrdemPar;
          END

       SELECT COALESCE((MAX(BDCODPGTOPAR)+1), 1) FROM vef_emp_tmoventparpgto WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) AND (BDORDEMPAR = NEW.BDORDEMPAR) INTO vNova_Chave;
       NEW.BDCODPGTOPAR = vNova_Chave;
    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventpar WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END

       IF ((NEW.BDORDEMPAR IS NULL) OR (NEW.BDORDEMPAR = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDORDEMPAR)), 1) FROM vef_emp_tmoventpar WHERE (bdcodemp = NEW.bdcodemp)
                                                                            AND (bdChave = NEW.bdChave) INTO vOrdemPar;
            NEW.BDORDEMPAR = vOrdemPar;
          END

       SELECT BDCODPGTOPAR FROM vef_emp_tmoventparpgto
       WHERE (BDCODPGTOPAR = NEW.bdcodpgtopar) AND (BDORDEMPAR = NEW.BDORDEMPAR) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCODPGTOPAR)+1), 1) FROM vef_emp_tmoventparpgto
            WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (BDORDEMPAR = NEW.BDORDEMPAR) INTO vNova_Chave;
            NEW.BDCODPGTOPAR = vNova_Chave;
          END
    END
  end
END
^

CREATE OR ALTER trigger tr_bf_in_vef_emp_tmoventvaraliq for vef_emp_tmoventvaraliq
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
  DECLARE VARIABLE vOrdemItem INTEGER ;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.BDORDEMICMS IS NULL) OR (NEW.BDORDEMICMS = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.BDCHAVE) INTO vordemItem;
          NEW.bdordem = vOrdemItem;
        END

       SELECT COALESCE((MAX(BDORDEMICMS)+1), 1) FROM vef_emp_tmoventvaraliq WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.BDCHAVE) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
       NEW.BDORDEMICMS = vNova_Chave;

    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END
    
       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
          BEGIN
             SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.bdchave) INTO vordemItem;
             NEW.bdordem = vOrdemItem;
          END

       SELECT BDORDEMICMS FROM vef_emp_tmoventvaraliq
       WHERE (BDORDEMICMS = NEW.bdordemicms) AND (BDORDEM = NEW.BDORDEM) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMICMS)+1), 1) FROM vef_emp_tmoventvaraliq
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
           NEW.BDORDEMICMS = vNova_Chave;
         END
    END
  end
END
^

CREATE OR ALTER TRIGGER TR_BF_IN_VEF_EMP_TMOVF100PARPGT FOR VEF_EMP_TMOVF100PARPGTO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
  DECLARE VARIABLE vOrdemPar INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDCODPGTOPAR IS NULL) OR (NEW.BDCODPGTOPAR = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM VEF_EMP_TMOVF100PAR WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END

       IF ((NEW.BDORDEMPAR IS NULL) OR (NEW.BDORDEMPAR = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDORDEMPAR)), 1) FROM VEF_EMP_TMOVF100PAR WHERE (bdcodemp = NEW.bdcodemp)
                                                                            AND (bdChave = NEW.bdChave) INTO vOrdemPar;
            NEW.BDORDEMPAR = vOrdemPar;
          END

       SELECT COALESCE((MAX(BDCODPGTOPAR)+1), 1) FROM VEF_EMP_TMOVF100PARPGTO WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) AND (BDORDEMPAR = NEW.BDORDEMPAR) INTO vNova_Chave;
       NEW.BDCODPGTOPAR = vNova_Chave;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM VEF_EMP_TMOVF100PAR WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END

       IF ((NEW.BDORDEMPAR IS NULL) OR (NEW.BDORDEMPAR = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDORDEMPAR)), 1) FROM VEF_EMP_TMOVF100PAR WHERE (bdcodemp = NEW.bdcodemp)
                                                                            AND (bdChave = NEW.bdChave) INTO vOrdemPar;
            NEW.BDORDEMPAR = vOrdemPar;
          END

       SELECT BDCODPGTOPAR FROM VEF_EMP_TMOVF100PARPGTO
       WHERE (BDCODPGTOPAR = NEW.bdcodpgtopar) AND (BDORDEMPAR = NEW.BDORDEMPAR) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCODPGTOPAR)+1), 1) FROM VEF_EMP_TMOVF100PARPGTO
            WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (BDORDEMPAR = NEW.BDORDEMPAR) INTO vNova_Chave;
            NEW.BDCODPGTOPAR = vNova_Chave;
          END
    END
END
^

CREATE OR ALTER trigger tr_bf_in_vef_emp_tmovsaipar for vef_emp_tmovsaipar
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdORDEMPAR IS NULL) OR (NEW.bdORDEMPAR = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

        SELECT COALESCE((MAX(bdORDEMPAR)+1), 1) FROM vef_emp_tmovsaipar WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Chave;
        NEW.bdORDEMPAR = vNova_Chave;
    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       SELECT bdORDEMPAR FROM vef_emp_tmovsaipar
       WHERE (bdORDEMPAR = NEW.bdORDEMPAR) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdORDEMPAR)+1), 1) FROM vef_emp_tmovsaipar
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
           NEW.bdORDEMPAR = vNova_Chave;
         END
    END
  end
END
^

CREATE OR ALTER trigger tr_bf_in_vef_emp_tmovsaiparpag for vef_emp_tmovsaiparpgto
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
  DECLARE VARIABLE vOrdemItem INTEGER ;
  DECLARE VARIABLE bdORDEMPAR INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.BDCODPGTOPAR IS NULL) OR (NEW.BDCODPGTOPAR = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaipar WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END

       IF ((NEW.bdORDEMPAR IS NULL) OR (NEW.bdORDEMPAR = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(bdORDEMPAR)), 1) FROM vef_emp_tmovsaipar WHERE (bdcodemp = NEW.bdcodemp)
                                                                            AND (bdChave = NEW.bdChave) INTO bdORDEMPAR;
            NEW.bdORDEMPAR = bdORDEMPAR;
          END

       SELECT COALESCE((MAX(BDCODPGTOPAR)+1), 1) FROM vef_emp_tmovsaiparpgto WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) AND (bdORDEMPAR = NEW.bdORDEMPAR) INTO vNova_Chave;
       NEW.BDCODPGTOPAR = vNova_Chave;
    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaipar WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END

       IF ((NEW.bdORDEMPAR IS NULL) OR (NEW.bdORDEMPAR = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(bdORDEMPAR)), 1) FROM vef_emp_tmovsaipar WHERE (bdcodemp = NEW.bdcodemp)
                                                                            AND (bdChave = NEW.bdChave) INTO bdORDEMPAR;
            NEW.bdORDEMPAR = bdORDEMPAR;
          END

       SELECT BDCODPGTOPAR FROM vef_emp_tmovsaiparpgto
       WHERE (BDCODPGTOPAR = NEW.bdcodpgtopar) AND (bdORDEMPAR = NEW.bdORDEMPAR) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCODPGTOPAR)+1), 1) FROM vef_emp_tmovsaiparpgto
            WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdORDEMPAR = NEW.bdORDEMPAR) INTO vNova_Chave;
            NEW.BDCODPGTOPAR = vNova_Chave;
          END
    END
  end
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TCONTABAGRUPBAIXAPARC_AD0 FOR TOL_VEF_EMP_TCONTABAGRUPBAIXAPARC
ACTIVE AFTER DELETE POSITION 0
AS
begin
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);

end
^

CREATE OR ALTER trigger tol_vef_emp_tcontabagrupbaixaparc_bi0 for tol_vef_emp_tcontabagrupbaixaparc
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVENTPARPGTO_AD0 FOR VEF_EMP_TMOVENTPARPGTO
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  DELETE FROM TOL_VEF_EMP_TCONTABAGRUPBAIXAPARC TOL WHERE (TOL.BDCODEMP = OLD.BDCODEMP AND TOL.BDORDEMAGRUP = OLD.BDORDEMAGRUP);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAIPARPGTO_AD0 FOR VEF_EMP_TMOVSAIPARPGTO
ACTIVE AFTER DELETE POSITION 0
AS
begin
  DELETE FROM TOL_VEF_EMP_TCONTABAGRUPBAIXAPARC TOL WHERE (TOL.BDCODEMP = OLD.BDCODEMP AND TOL.BDORDEMAGRUP = OLD.BDORDEMAGRUP);
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERPARPGTO_AD0 FOR VEF_EMP_TMOVSERPARPGTO
ACTIVE AFTER DELETE POSITION 0
AS
begin
  DELETE FROM TOL_VEF_EMP_TCONTABAGRUPBAIXAPARC TOL WHERE (TOL.BDCODEMP = OLD.BDCODEMP AND TOL.BDORDEMAGRUP = OLD.BDORDEMAGRUP);
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVF100PARPGTO_AD0 FOR VEF_EMP_TMOVF100PARPGTO
ACTIVE AFTER DELETE POSITION 0
AS
begin
  DELETE FROM TOL_VEF_EMP_TCONTABAGRUPBAIXAPARC TOL WHERE (TOL.BDCODEMP = OLD.BDCODEMP AND TOL.BDORDEMAGRUP = OLD.BDORDEMAGRUP);
end
^

CREATE OR ALTER trigger tr_bf_in_vef_emp_tmovsaivaraliq for vef_emp_tmovsaivaraliq
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
  DECLARE VARIABLE vOrdemItem INTEGER ;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.BDORDEMICMS IS NULL) OR (NEW.BDORDEMICMS = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.bdchave) INTO vordemItem;
          NEW.bdordem = vOrdemItem;
        END

        SELECT COALESCE((MAX(BDORDEMICMS)+1), 1) FROM vef_emp_tmovsaivaraliq WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
      NEW.BDORDEMICMS = vNova_Chave;

    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.bdchave) INTO vordemItem;
          NEW.bdordem = vOrdemItem;
        END

        SELECT BDORDEMICMS FROM vef_emp_tmovsaivaraliq
        WHERE (BDORDEMICMS = NEW.bdordemicms) AND (BDORDEM = NEW.BDORDEM) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
        IF (vcodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(BDORDEMICMS)+1), 1) FROM vef_emp_tmovsaivaraliq
            WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
            NEW.BDORDEMICMS = vNova_Chave;
          END
    END
  end
END
^

CREATE OR ALTER trigger tr_bf_in_vef_emp_tmovserpar for vef_emp_tmovserpar
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdORDEMPAR IS NULL) OR (NEW.bdORDEMPAR = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

         SELECT COALESCE((MAX(bdORDEMPAR)+1), 1) FROM vef_emp_tmovserpar WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Chave;
         NEW.bdORDEMPAR = vNova_Chave;

    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       SELECT bdORDEMPAR FROM vef_emp_tmovserpar
       WHERE (bdORDEMPAR = NEW.bdORDEMPAR) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdORDEMPAR)+1), 1) FROM vef_emp_tmovserpar
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
           NEW.bdORDEMPAR = vNova_Chave;
         END
    END
  end
END
^

CREATE OR ALTER trigger tr_bf_in_vef_emp_tmovserparpag for vef_emp_tmovserparpgto
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
  DECLARE VARIABLE vOrdemPar INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.BDCODPGTOPAR IS NULL) OR (NEW.BDCODPGTOPAR = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovserpar WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END

       IF ((NEW.bdORDEMPAR IS NULL) OR (NEW.bdORDEMPAR = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(bdORDEMPAR)), 1) FROM vef_emp_tmovserpar WHERE (bdcodemp = NEW.bdcodemp)
                                                                            AND (bdChave = NEW.bdChave) INTO vOrdemPar;
            NEW.bdORDEMPAR = vOrdemPar;
          END

        SELECT COALESCE((MAX(BDCODPGTOPAR)+1), 1) FROM vef_emp_tmovserparpgto WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) AND (bdORDEMPAR = NEW.bdORDEMPAR) INTO vNova_Chave;
        NEW.BDCODPGTOPAR = vNova_Chave;
    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovserpar WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END

       IF ((NEW.bdORDEMPAR IS NULL) OR (NEW.bdORDEMPAR = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(bdORDEMPAR)), 1) FROM vef_emp_tmovserpar WHERE (bdcodemp = NEW.bdcodemp)
                                                                            AND (bdChave = NEW.bdChave) INTO vOrdemPar;
            NEW.bdORDEMPAR = vOrdemPar;
          END

       SELECT BDCODPGTOPAR FROM vef_emp_tmovserparpgto
       WHERE (BDCODPGTOPAR = NEW.bdcodpgtopar) AND (bdORDEMPAR = NEW.bdORDEMPAR) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCODPGTOPAR)+1), 1) FROM vef_emp_tmovserparpgto
            WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdORDEMPAR = NEW.bdORDEMPAR) INTO vNova_Chave;
            NEW.BDCODPGTOPAR = vNova_Chave;
          END
    END
  end
END
^

CREATE OR ALTER trigger tr_bf_in_vef_emp_tmovservaraliq for vef_emp_tmovservaraliq
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
  DECLARE VARIABLE vOrdemItem INTEGER ;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.BDORDEMICMS IS NULL) OR (NEW.BDORDEMICMS = 0)) THEN
    BEGIN

      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovseritens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovseritens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.bdchave) INTO vordemItem;
          NEW.bdordem = vOrdemItem;
        END

        SELECT COALESCE((MAX(BDORDEMICMS)+1), 1) FROM vef_emp_tmovservaraliq WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
        NEW.BDORDEMICMS = vNova_Chave;
    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovseritens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovseritens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.bdchave) INTO vordemItem;
          NEW.bdordem = vOrdemItem;
        END

        SELECT BDORDEMICMS FROM vef_emp_tmovservaraliq
        WHERE (BDORDEMICMS = NEW.bdordemicms) AND (BDORDEM = NEW.BDORDEM) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

        IF (vcodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(BDORDEMICMS)+1), 1) FROM vef_emp_tmovservaraliq
            WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
            NEW.BDORDEMICMS = vNova_Chave;
          END
    END
  end
END
^

CREATE OR ALTER TRIGGER TR_BF_IN_VRH_BASE_TSERV_PERIODO FOR VRH_BASE_TSERV_PERIODO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodseq IS NULL) OR (NEW.bdcodseq = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodseq)+1),1) FROM vrh_base_tserv_periodo WHERE NEW.bdcodemp = bdcodemp AND NEW.bdcodter = bdcodter INTO vcodigo;
        NEW.bdcodseq = vcodigo;
     END
  ELSE
    BEGIN
      SELECT bdcodseq FROM vrh_base_tserv_periodo WHERE NEW.bdcodemp = bdcodemp AND NEW.bdcodter = bdcodter AND NEW.bdcodseq = bdcodseq INTO vcodigo;

      IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodseq)+1),1) FROM vrh_base_tserv_periodo
           WHERE NEW.bdcodemp = bdcodemp AND NEW.bdcodter = bdcodter INTO vcodigo;
           NEW.bdcodseq = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INERT_VRH_EMP_TCAT_TES FOR VRH_EMP_TCAT_TESTEMUNHA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vrh_emp_tcat_testemunha WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
      NEW.BDORDEM = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT BDORDEM FROM vrh_emp_tcat_testemunha WHERE (BDORDEM = NEW.BDORDEM) AND (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) AND (bdChave = NEW.bdchave) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vrh_emp_tcat_testemunha WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
           NEW.BDORDEM = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INS_VRH_BASE_TSERVTERC FOR VRH_BASE_TSERVTERC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcodigo INTEGER;
  DECLARE VARIABLE vcodcentro INTEGER;
  DECLARE VARIABLE vcodtpcc INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  vcodcentro = 0;
  vcodtpcc = 0;
  IF ((NEW.bdcodserv IS NULL) OR (NEW.bdcodserv = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodserv) + 1, 1) FROM vrh_base_tservterc WHERE NEW.bdcodter = bdcodter AND NEW.bdcodemp = bdcodemp INTO :vcodigo;

       NEW.bdcodserv = :vcodigo;
     END
  ELSE
    BEGIN
      SELECT bdcodserv FROM vrh_base_tservterc WHERE NEW.bdcodter = bdcodter AND NEW.bdcodemp = bdcodemp AND NEW.bdcodserv = bdcodserv INTO :vcodigo;

      IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE(MAX(bdcodserv) + 1, 1) FROM vrh_base_tservterc WHERE NEW.bdcodter = bdcodter AND NEW.bdcodemp = bdcodemp INTO :vcodigo;
           NEW.bdcodserv = :vcodigo;
         END
    END

  if ((NEW.bdintegradofiscal IS NULL) AND (NEW.BDCODTIPO = 100)) then --Se inserido pelo Fiscal, marca direto como integrado no fiscal
      NEW.bdintegradofiscal = TRUE;

  NEW.bdrefserv = (SELECT CAST(bdaaaamm AS INTEGER) FROM aaaamm(NEW.bddataserv));

  IF (NEW.bdhoraserv IS NULL) THEN
     BEGIN
       NEW.bdhoraserv = '00:00:00';
     END

  NEW.bdrefpagserv = (SELECT CAST(bdaaaamm AS INTEGER) FROM aaaamm(NEW.bddatapagserv));

  -- Sol.126954  Leonardo Schwab - Automatiza o vínculo do participante com o tomador do serviço    INICIO
  IF (NEW.BDCODTPCC IS NULL) THEN
    BEGIN
      SELECT FIRST 1 BDCODCENTROS FROM TEMPRESAS_REF WHERE BDCODEMP = NEW.BDCODEMP AND BDREFEMP <= NEW.BDREFSERV ORDER BY BDREFEMP DESC INTO :vcodcentro;

      SELECT FIRST 1 BDCODTPCC FROM VRH_BASE_TCUSTOM WHERE BDCODCENTRO = :vcodcentro AND BDCODTER = NEW.BDCODTER ORDER BY BDCODTPCC INTO :vcodtpcc;

      IF ((vcodcentro > 0) and (vcodtpcc > 0)) THEN
        BEGIN
          NEW.BDCODCENTRO = vcodcentro;
          NEW.BDCODTPCC = vcodtpcc;
          NEW.BDCODTIPO = 100;
        END
    END
  -- Sol.126954  Leonardo Schwab - Automatiza o vínculo do participante com o tomador do serviço    FIM

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdrefserv, '1', 'BDPERFOLHAAUTONOMO'); -- 1 - Calculado
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTAB_SN_SERVICO_VI_BI FOR VEF_BASE_TTAB_SN_SERVICO_VI
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vCODCONFSIMPNAC INTEGER;
  DECLARE VARIABLE vNUMFAIXA INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumfaixa IS NULL) OR (NEW.bdnumfaixa = 0)) THEN
    BEGIN
      IF ((NEW.bdcodconfsimpnac IS NULL) OR (NEW.bdcodconfsimpnac = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdcodconfsimpnac)), 1) FROM vef_base_tconf_sn  INTO vcodconfsimpnac;
          NEW.bdcodconfsimpnac = vcodconfsimpnac;
        END

       SELECT COALESCE((MAX(bdnumfaixa)+1), 1) FROM vef_base_ttab_sn_servico_vi
       WHERE bdcodconfsimpnac = NEW.bdcodconfsimpnac INTO vnumfaixa;
       NEW.bdnumfaixa = vnumfaixa;
    END
  ELSE
    BEGIN
       IF ((NEW.bdcodconfsimpnac IS NULL) OR (NEW.bdcodconfsimpnac = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdcodconfsimpnac)), 1) FROM vef_base_tconf_sn  INTO vcodconfsimpnac;
          NEW.bdcodconfsimpnac = vcodconfsimpnac;
        END

       SELECT bdnumfaixa FROM vef_base_ttab_sn_servico_vi
       WHERE (bdnumfaixa = NEW.bdnumfaixa) AND (bdcodconfsimpnac = NEW.bdcodconfsimpnac) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumfaixa)+1), 1) FROM vef_base_ttab_sn_servico_vi WHERE (bdcodconfsimpnac = NEW.bdcodconfsimpnac) INTO vnumfaixa;
           NEW.bdnumfaixa = vnumfaixa;
         END

    END
END
^

/* Trigger: TSELCONTA_BI0 */
CREATE OR ALTER TRIGGER TSELCONTA_BI0 FOR TSELCONTA
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE wCodigo INTEGER;
BEGIN
  wCodigo = 0;
  IF ((NEW.BDCODSELCONTA IS NULL) OR (NEW.BDCODSELCONTA = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(BDCODSELCONTA)+1),1) FROM TSELCONTA INTO wCodigo;
       NEW.BDCODSELCONTA = wCodigo;
     END
  ELSE
     BEGIN
       SELECT BDCODSELCONTA FROM TSELCONTA WHERE BDCODSELCONTA = NEW.BDCODSELCONTA INTO wCodigo;

       IF (wCodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCODSELCONTA)+1),1) FROM TSELCONTA INTO wCodigo;
            NEW.BDCODIGOSELCONTA = wCodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER TR_BF_INS_VRH_BASE_TTERC_TDEP FOR VRH_BASE_TTERC_TDEP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodNovo INTEGER;

BEGIN
  IF ((NEW.bdcoddpnterc IS NULL) OR (NEW.bdcoddpnterc = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcoddpnterc) + 1, 1)
       FROM vrh_base_tterc_tdep
       WHERE bdcodter = NEW.bdcodter
       INTO :vCodNovo;

       NEW.bdcoddpnterc = :vCodNovo;
     END
END
^

CREATE OR ALTER TRIGGER TR_BF_INS_VRHF_BASE_TVNTER FOR VRHF_BASE_TVNTER
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdchave) + 1, 1)
       FROM vrhf_base_tvnter
       WHERE NEW.bdcodter = bdcodter
       INTO :vNovoCod;

       NEW.bdchave = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER TR_BF_INS_VRHF_BASE_TVSTER FOR VRHF_BASE_TVSTER
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdchave) + 1, 1)
       FROM vrhf_base_tvster
       WHERE NEW.bdcodter = bdcodter
       INTO :vNovoCod;

       NEW.bdchave = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER TR_BF_INS_VRHF_EMP_TPREPFN FOR VRHF_EMP_TPREPFN
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
   if (new.bddataentrada is null) then
      begin
         exception EX_DATE;
      end
   else
      begin
   vcodigo = 0;
   IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0))  THEN
      BEGIN
         SELECT FIRST 1 COALESCE((MAX(bdordem)+1),1) FROM VRHF_EMP_TPREPFN WHERE (NEW.bdcodemp = bdcodemp) AND (NEW.bdcodcol = bdcodcol) INTO vcodigo;
         NEW.bdordem = vcodigo;
      END
   ELSE
      BEGIN
         SELECT FIRST 1 bdordem FROM VRHF_EMP_TPREPFN WHERE (NEW.bdcodemp = bdcodemp AND NEW.bdcodcol = bdcodcol)  INTO vcodigo;
         IF (vcodigo < 0) THEN
            BEGIN
               SELECT FIRST 1 COALESCE((MAX(bdordem)+1),1) FROM VRHF_EMP_TPREPFN WHERE (NEW.bdcodemp = bdcodemp AND NEW.bdcodcol = bdcodcol) INTO vcodigo;
               NEW.bdordem = vcodigo;
            END
      END
     
   IF (NEW.bdhoraentrada IS NULL)  THEN
      NEW.bdhoraentrada = '00:00:00';
     
   IF (NEW.bdtipo IS NULL)  THEN
      NEW.bdtipo = 0;
     
   NEW.BDREFENTRADA = CAST((SUBSTRING(CAST(NEW.BDDATAENTRADA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDDATAENTRADA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
        -- Sempre atribui o plano de centros de custos correto
        select first 1 BDCODCENTROS from TEMPRESAS_REF where BDCODEMP = new.BDCODEMP and BDREFEMP <= new.BDREFENTRADA order by BDREFEMP DESC into new.BDCODCENTRO;
      end
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TPREPFN_BU0 FOR VRHF_EMP_TPREPFN
ACTIVE BEFORE UPDATE POSITION 0
AS
  declare variable wcodtpcc INTEGER;
  declare variable wcodcentro INTEGER;
BEGIN
   if (new.bddataentrada is null) then
      exception EX_DATE;
   else
     begin
       NEW.BDREFENTRADA = CAST((SUBSTRING(CAST(NEW.BDDATAENTRADA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDDATAENTRADA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       if (new.bddatasaida is not null) then
          new.bdrefsaida = CAST((SUBSTRING(CAST(NEW.BDDATASAIDA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDDATASAIDA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       else
          new.bdrefsaida = null;

        wcodcentro = null;
        -- Sempre atribui o plano de centros de custos correto
        select first 1 BDCODCENTROS from TEMPRESAS_REF where BDCODEMP = new.BDCODEMP and BDREFEMP <= new.BDREFENTRADA order by BDREFEMP DESC into :wcodcentro;
        wcodcentro = coalesce(wcodcentro, 0);

        wcodtpcc = null;
        select first 1 BDCODTPCC from CENTROS_TPCC where BDCODCENTRO = :wcodcentro and BDCODTPCC = new.bdcodtpcc into :wcodtpcc;

        if (coalesce(wcodtpcc, 0 ) > 0) then
           new.bdcodcentro = wcodcentro;
     end
END
^

CREATE OR ALTER TRIGGER EMPRESAS_TSOCCOTAS_PGTO_BIU0 FOR EMPRESAS_TSOCCOTAS_PGTO
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  IF (NEW.BDCOMPENVIO = 0) THEN
    NEW.BDCOMPENVIO = NULL;
end
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_CENTROS_TPCC FOR CENTROS_TPCC
ACTIVE BEFORE INSERT POSITION 0 
AS
   DECLARE VARIABLE vCodigo INTEGER;
   DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
   vcodigo = 0;
   IF ((NEW.bdcodtpcc IS NULL) OR (NEW.bdcodtpcc = 0))  THEN
      BEGIN
         SELECT COALESCE((MAX(bdcodtpcc)+1),1) FROM centros_tpcc WHERE bdcodcentro = NEW.bdcodcentro INTO vNova_Chave;
         NEW.bdcodtpcc = vNova_Chave;
      END
   ELSE
      BEGIN
         SELECT bdcodtpcc FROM centros_tpcc WHERE (bdcodcentro = NEW.bdcodcentro) AND (bdcodtpcc = NEW.bdcodtpcc)  INTO vcodigo;
         IF (vcodigo > 0) THEN
            BEGIN
               SELECT COALESCE((MAX(bdcodtpcc)+1),1) FROM centros_tpcc WHERE bdcodcentro = NEW.bdcodcentro INTO vNova_Chave;
               NEW.bdcodtpcc = vNova_Chave;
            END
      END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_EMPRESAS_TBAI FOR EMPRESAS_TBAI
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodbai IS NULL) OR (NEW.bdcodbai = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodbai)+1), 1) FROM empresas_tbai WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.bdcodbai = vNova_Chave;
     END
  ELSE
    BEGIN
       SELECT bdcodbai FROM empresas_tbai WHERE (bdcodbai = NEW.bdcodbai) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodbai)+1), 1) FROM empresas_tbai WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdcodbai = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_EMPRESAS_TBEM FOR EMPRESAS_TBEM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodbem IS NULL) OR (NEW.bdcodbem = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodbem)+1), 1) FROM empresas_tbem WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.bdcodbem = vNova_Chave;
     END
  ELSE
    BEGIN
       SELECT bdcodbem FROM empresas_tbem WHERE (bdcodbem = NEW.bdcodbem) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodbem)+1), 1) FROM empresas_tbem WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdcodbem = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_EMPRESAS_TBEM_ITEN FOR EMPRESAS_TBEM_ITENS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vUltimo_Bem INTEGER;
BEGIN
  /* Trigger text */
  --exception ex_date + ' TBEM_ITENS ' || NEW.bdcodbemitens;

  vcodigo = 0;
  IF ((NEW.bdcodbemitens IS NULL) OR (NEW.bdcodbemitens = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodbemitens)+1), 1) FROM empresas_tbem_itens WHERE bdcodemp = NEW.bdcodemp AND bdcodbem = NEW.bdcodbem INTO vNova_Chave;
      NEW.bdcodbemitens = vNova_Chave;

      SELECT COALESCE((MAX(BDCODBEM)), 1) FROM empresas_tbem WHERE bdcodemp = NEW.bdcodemp INTO vUltimo_Bem;
      NEW.bdcodbem = vUltimo_Bem;
     END


  /*else
    begin
       select bdcodbemitens from empresas_tbem_itens where (bdcodbemitens = NEW.bdcodbemitens) and (bdcodemp = new.bdcodemp) into vcodigo;

       if (vcodigo > 0) then
         BEGIN
           select coalesce((max(bdcodbemitens)+1), 1) from empresas_tbem_itens where bdcodemp = new.bdcodemp into vNova_Chave;
           NEW.bdcodbemitens = vNova_Chave;
         END
    end*/

END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_EMPRESAS_TIBE FOR EMPRESAS_TIBE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodibe IS NULL) OR (NEW.bdcodibe = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodibe)+1), 1) FROM empresas_tibe WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.bdcodibe = vNova_Chave;
     END
  ELSE
    BEGIN
       SELECT bdcodibe FROM empresas_tibe WHERE (bdcodibe = NEW.bdcodibe) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodibe)+1), 1) FROM empresas_tibe WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdcodibe = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_EMPRESAS_TSOC FOR EMPRESAS_TSOC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodsoc IS NULL) OR (NEW.bdcodsoc = 0)) THEN
    BEGIN
      --NEW.bdcodsoc = GEN_ID(gen_vsuc_empresas_tsoc, 1);
      SELECT COALESCE((MAX(bdcodsoc)+1), 1) FROM empresas_tsoc WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.bdcodsoc = vNova_Chave;
     END
  ELSE
    BEGIN
       SELECT bdcodsoc FROM empresas_tsoc WHERE (bdcodsoc = NEW.bdcodsoc) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodsoc)+1), 1) FROM empresas_tsoc WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdcodsoc = vNova_Chave;
           --NEW.bdcodsoc = GEN_ID(gen_vsuc_empresas_tsoc, 1);
           /*exception ex_valor_text+NEW.bdcodtpcc;*/
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_HIST_TPHI FOR HIST_TPHI
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodtphi IS NULL) OR (NEW.bdcodtphi = 0)) THEN
    --NEW.bdcodtphi = GEN_ID(gen_hist_tphi, 1);
    BEGIN
      SELECT COALESCE((MAX(bdcodtphi)+1), 1) FROM hist_tphi WHERE bdcodhist = NEW.bdcodhist INTO vNova_Chave;
      NEW.bdcodtphi = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdcodtphi FROM hist_tphi WHERE (bdcodhist = NEW.bdcodhist) AND (bdcodtphi = NEW.bdcodtphi) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodtphi)+1), 1) FROM hist_tphi WHERE bdcodhist = NEW.bdcodhist INTO vNova_Chave;
           NEW.bdcodtphi = vNova_Chave;
           --NEW.bdcodtphi = GEN_ID(gen_hist_tphi, 1);
           /*exception ex_valor_text+NEW.bdcodtpcc;*/
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_MOEDAS_TMOE FOR MOEDAS_TMOE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodtmoe IS NULL) OR (NEW.bdcodtmoe = 0))  THEN
    --NEW.bdcodtmoe = GEN_ID(gen_moedas_tmoe, 1);
    BEGIN
      SELECT COALESCE((MAX(bdcodtmoe)+1), 1) FROM moedas_tmoe WHERE bdcodmoedas = NEW.bdcodmoedas INTO vNova_Chave;
      NEW.bdcodtmoe = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdcodtmoe FROM moedas_tmoe WHERE (bdcodtmoe = NEW.bdcodtmoe) AND (bdcodmoedas = NEW.bdcodmoedas) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodtmoe)+1), 1) FROM moedas_tmoe WHERE bdcodmoedas = NEW.bdcodmoedas INTO vNova_Chave;
           NEW.bdcodtmoe = vNova_Chave;
           --NEW.bdcodtmoe = GEN_ID(gen_moedas_tmoe, 1);
           /*exception ex_valor_text+NEW.bdcodtpcc;*/
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_PLANOS_TPLA FOR PLANOS_TPLA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE  vCodigo INTEGER;
  DECLARE VARIABLE  vNova_Chave INTEGER;
  DECLARE VARIABLE  wparte VARCHAR(140);
  DECLARE VARIABLE  wrpos INTEGER;
  DECLARE VARIABLE  wnivel INTEGER;
BEGIN
  --Trigger text
  vcodigo = 0;
  wrpos = 0;
  IF ((NEW.bdcodtpla IS NULL) OR (NEW.bdcodtpla = 0))  THEN
    --NEW.bdcodtpla = GEN_ID(gen_planos_tpla, 1);
    BEGIN
      SELECT COALESCE((MAX(bdcodtpla)+1), 1) FROM planos_tpla WHERE bdcodplapadrao = NEW.bdcodplapadrao INTO vNova_Chave;
      NEW.bdcodtpla = vNova_Chave;
    END
  ELSE
    BEGIN
       --#alt:12280 - Criado novo procedimento para gerar novo código. Ana - 06/10/2016
       EXECUTE PROCEDURE SP_VERIFICA_NOVO_CODIGO(NEW.BDCODPLAPADRAO, NEW.BDCODTPLA, NEW.BDCTALON)
       RETURNING_VALUES :vCodigo;

       IF ((NOT (vCodigo IS NULL)) AND (vcodigo > 0)) THEN
          NEW.bdcodtpla = vCodigo;

       /*SELECT bdcodtpla FROM planos_tpla WHERE (bdcodtpla = NEW.bdcodtpla) AND (bdcodplapadrao = NEW.bdcodplapadrao) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodtpla)+1), 1) FROM planos_tpla WHERE bdcodplapadrao = NEW.bdcodplapadrao INTO vNova_Chave;
           NEW.bdcodtpla = vNova_Chave;
           --NEW.bdcodtpla = GEN_ID(gen_planos_tpla, 1);
           --*exception ex_valor_text+NEW.bdcodtpcc;
         END*/
       --#alt:12280. fim
    END

  --gravar bdclanom para ordernar por nome e classificacao  inicio
  wparte = NEW.bdctalon;
  --se nao for conta titulo
  IF (NEW.bdtipcta = 1) THEN
     BEGIN
       SELECT bdrpos FROM rpos('.',:wparte) INTO wrpos;
       IF (wrpos > 0) THEN
          BEGIN
            wparte = SUBSTRING(wparte FROM 1 FOR wrpos - 1);
            SELECT bdretorno FROM preenche_direita(:wparte,40,' ') INTO wparte;
            wparte = wparte || NEW.bdnomcta;
          END
     END

  NEW.bdclanom = wparte;
  /* gravar bdclanom para ordernar por nome e classificacao  fim*/
  EXECUTE PROCEDURE CONTAR_CHAR(NEW.BDCTALON, '.') RETURNING_VALUES :wNivel;
  NEW.bdnivel = :wNivel;

  --#148866 - Machado - 28/04/2021 - Grupo null causa erro em várias rotinas
  if (NEW.bdgrupocta IS NULL) then
    NEW.bdgrupocta = 0;
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TATIVO_EXTERIOR FOR TATIVO_EXTERIOR
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodatvext IS NULL) OR (NEW.bdcodatvext = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodatvext)+1),1) FROM tativo_exterior INTO vcodigo;
        NEW.bdcodatvext = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodatvext FROM tativo_exterior WHERE bdcodatvext = NEW.bdcodatvext INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodatvext)+1),1) FROM tativo_exterior INTO vcodigo;
            NEW.bdcodatvext = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TATIVO_TAXA FOR TATIVO_TAXA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodatvtx IS NULL) OR (NEW.bdcodatvtx = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodatvtx)+1),1) FROM tativo_taxa INTO vcodigo;
        NEW.bdcodatvtx = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodatvtx FROM tativo_taxa WHERE bdcodatvtx = NEW.bdcodatvtx INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodatvtx)+1),1) FROM tativo_taxa INTO vcodigo;
            NEW.bdcodatvtx = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TATVESTADUAL FOR TATVESTADUAL
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.BDCODSEQATE IS NULL) OR (NEW.BDCODSEQATE = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(BDCODSEQATE) + 1, 1) FROM tatvestadual INTO :vCodigo;
      NEW.BDCODSEQATE = :vcodigo;
      --new.BDCODSEQATE = gen_id(gen_tatvestadual,1);
    END
  ELSE
    BEGIN
       SELECT BDCODSEQATE FROM tatvestadual WHERE BDCODSEQATE = NEW.BDCODSEQATE INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCODSEQATE) + 1), 1) FROM tatvestadual  INTO vCodigo;
           NEW.BDCODSEQATE = vCodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TATVMUNICIPAL FOR TATVMUNICIPAL
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;
  -- RECOMPILAR
  IF ((NEW.BDCODATVM IS NULL) OR (NEW.BDCODATVM = 0)) THEN
    BEGIN
      --new.BDCODATVM = gen_id(gen_tatvmunicipal,1);
      SELECT COALESCE((MAX(BDCODATVM) + 1), 1) FROM tatvmunicipal  INTO vCodigo;
      NEW.BDCODATVM = vCodigo;
    END
  ELSE
    BEGIN
       SELECT BDCODATVM FROM tatvmunicipal WHERE BDCODATVM = NEW.BDCODATVM INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCODATVM) + 1), 1) FROM tatvmunicipal  INTO vCodigo;
           NEW.BDCODATVM = vCodigo;
         END
    END

  IF (NEW.bdidcnae = '') THEN
     NEW.bdidcnae = NULL;

  if (NEW.BDCODTRIBATVM = '') then
     NEW.BDCODTRIBATVM = NULL;

END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TBANCOS_AG FOR TBANCOS_AG
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdCODAG IS NULL) OR (NEW.bdCODAG = 0))  THEN
    BEGIN
      SELECT COALESCE((MAX(bdCODAG)+1), 1) FROM tbancos_ag WHERE bdcodban = NEW.bdcodban INTO vNova_Chave;
      NEW.bdCODAG = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdcodag FROM tbancos_ag WHERE (bdcodag = NEW.bdcodag) AND (bdcodban = NEW.bdcodban) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodag)+1), 1) FROM tbancos_ag WHERE bdcodban = NEW.bdcodban INTO vNova_Chave;
           NEW.bdcodag = vNova_Chave;
         END
    END

  IF (StrLen(NEW.bdcodag) > 7) THEN
     BEGIN
       NEW.bdcodag = 0;
       EXCEPTION ex_tamanhochave;
     END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TCENTROS FOR TCENTROS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodcentro IS NULL) OR (NEW.bdcodcentro = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdCODCENTRO)+1),1) FROM tcentros INTO vcodigo;
        NEW.bdcodcentro = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodcentro FROM tcentros WHERE bdcodcentro = NEW.bdcodcentro INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdCODCENTRO)+1),1) FROM tcentros INTO vcodigo;
           NEW.bdcodcentro = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TCIDADE FOR TCIDADE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdCODCID IS NULL) OR (NEW.bdCODCID = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdCODCID) + 1), 1) FROM TCIDADE WHERE bdcodcid < 999999  INTO vCodigo;
      NEW.bdCODCID = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdCODCID FROM TCIDADE WHERE bdCODCID = NEW.bdCODCID INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdCODCID) + 1), 1) FROM TCIDADE WHERE bdcodcid < 999999 INTO vCodigo;
           NEW.bdCODCID = vCodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TCODREC FOR TCODREC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodrec IS NULL) OR (NEW.bdcodrec = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodrec)+1),1) FROM tcodrec INTO vcodigo;
       NEW.bdcodrec = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodrec FROM tcodrec WHERE bdcodrec = NEW.bdcodrec INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodrec)+1),1) FROM tcodrec INTO vcodigo;
            NEW.bdcodrec = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_ESTADOS_TCONFDIMEQ_BI0 FOR VEF_ESTADOS_TCONFDIMEQ
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODQDIME IS NULL) OR (NEW.BDCODQDIME = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDCODQDIME)+1),1) FROM VEF_ESTADOS_TCONFDIMEQ INTO vcodigo;
       NEW.BDCODQDIME = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDCODQDIME FROM VEF_ESTADOS_TCONFDIMEQ WHERE BDCODQDIME = NEW.BDCODQDIME INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODQDIME)+1),1) FROM VEF_ESTADOS_TCONFDIMEQ INTO vcodigo;
            NEW.BDCODQDIME = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TTABFUMDES FOR VEF_BASE_TTABFUMDES
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdordemfumdes IS NULL) OR (NEW.bdordemfumdes = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdordemfumdes)+1),1) FROM VEF_BASE_TTABFUMDES INTO vcodigo;
       NEW.bdordemfumdes = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdordemfumdes FROM VEF_BASE_TTABFUMDES WHERE bdordemfumdes = NEW.bdordemfumdes INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdordemfumdes)+1),1) FROM VEF_BASE_TTABFUMDES INTO vcodigo;
            NEW.bdordemfumdes = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TTABTRIBNAC FOR VEF_BASE_TTABTRIBNAC
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODTRIBNAC IS NULL) OR (NEW.BDCODTRIBNAC = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDCODTRIBNAC)+1),1) FROM VEF_BASE_TTABTRIBNAC INTO vcodigo;
       NEW.BDCODTRIBNAC = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDCODTRIBNAC FROM VEF_BASE_TTABTRIBNAC WHERE BDCODTRIBNAC = NEW.BDCODTRIBNAC INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODTRIBNAC)+1),1) FROM VEF_BASE_TTABTRIBNAC INTO vcodigo;
            NEW.BDCODTRIBNAC = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TTABFUNDOSOCIAL FOR VEF_BASE_TTABFUNDOSOCIAL
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdordemfunsoc IS NULL) OR (NEW.bdordemfunsoc = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdordemfunsoc)+1),1) FROM VEF_BASE_TTABFUNDOSOCIAL INTO vcodigo;
       NEW.bdordemfunsoc = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdordemfunsoc FROM VEF_BASE_TTABFUNDOSOCIAL WHERE bdordemfunsoc = NEW.bdordemfunsoc INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdordemfunsoc)+1),1) FROM VEF_BASE_TTABFUNDOSOCIAL INTO vcodigo;
            NEW.bdordemfunsoc = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TCONTADOR_PADRAO FOR TCONTADOR_PADRAO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodcont IS NULL) OR (NEW.bdcodcont = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodcont)+1),1) FROM tcontador_padrao INTO vcodigo;
        NEW.bdcodcont = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodcont FROM tcontador_padrao WHERE bdcodcont = NEW.bdcodcont INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodcont)+1),1) FROM tcontador_padrao INTO vcodigo;
            NEW.bdcodcont = vcodigo;
         END
    END

  IF (NEW.bdcrccont IS NULL) THEN
     NEW.bdcrccont = '';
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TDARFPADRAO FOR TDARFPADRAO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vClassImp TYPE OF COLUMN TIMPOSTO.BDCLASSIMP;
BEGIN
  vcodigo = 0;
  --  elizeu - 22-08-18 - Simples nacional - Guia complementar #87346 #88848

  SELECT I.BDCLASSIMP FROM TIMPOSTO I WHERE I.BDCODIMP = NEW.BDCODIMP INTO :vClassImp;                                                     /*Busca classificação do imposto*/
  SELECT FIRST 1 DI.BDCLASSIFICACAO FROM VEF_BASE_DASHBOARD_IMPOSTO DI WHERE :vClassImp STARTING WITH(DI.BDCLASSIFICACAO) INTO :vClassImp; /*Busca a classificação principal do imposto*/

  /*Verifica se essa classificação foi enviada para o dashboard*/
  SELECT FIRST 1 BDCODEMP FROM VEF_DASHBOARD_ALERTA DA WHERE DA.BDCODEMP = NEW.BDCODEMP AND DA.BDREFERENCIA = NEW.BDREFERENCIA AND DA.BDCLASSIFICACAO = :vClassImp INTO :vCodigo;
  IF (ROW_COUNT > 0) THEN
    BEGIN
      UPDATE OR INSERT INTO VEF_DASHBOARD_ALERTA(BDCODEMP, BDREFERENCIA, BDCLASSIFICACAO, BDENVIADO)
      VALUES (NEW.BDCODEMP, NEW.BDREFERENCIA, :vClassImp, 'FALSE') MATCHING(BDCODEMP, BDREFERENCIA, BDCLASSIFICACAO);
    END

  vCodigo = 0;
  IF ((NEW.bdordem IS NOT NULL) OR (NEW.bdordem > 0)) THEN
    EXIT;

  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordem)+1), 1) FROM tdarfpadrao WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodImp = NEW.bdcodimp) AND (BDREFERENCIA = NEW.BDREFERENCIA) AND (bdquota = NEW.bdquota) AND (BDCODPERIODO = NEW.BDCODPERIODO) INTO vNova_Chave;
      NEW.bdordem = vNova_Chave;
     END
  ELSE
    BEGIN
       SELECT bdordem FROM tdarfpadrao WHERE (bdordem = NEW.bdordem) AND (bdcodemp = NEW.bdcodemp) AND (bdcodImp = NEW.bdcodimp) AND (BDREFERENCIA = NEW.BDREFERENCIA) AND (bdquota = NEW.bdquota) AND (BDCODPERIODO = NEW.BDCODPERIODO) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordem)+1), 1) FROM tdarfpadrao WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodImp = NEW.bdcodimp) AND (BDREFERENCIA = NEW.BDREFERENCIA) AND (bdquota = NEW.bdquota) AND (BDCODPERIODO = NEW.BDCODPERIODO) INTO vNova_Chave;
           NEW.bdordem = vNova_Chave;
         END
    END
END^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TEMPRESAS FOR TEMPRESAS
ACTIVE BEFORE INSERT POSITION 0
as
--  DECLARE VARIABLE vCodemp INTEGER;
declare variable VCODIGO integer;
declare variable VBDDATAINIESOCIAL date;
declare variable v_cod_agendamento_crtrab integer;
declare variable v_cod_emp_crtrab integer;
begin
  if ((new.BDCODEMP is null) or (new.BDCODEMP = 0)) then
  begin
    select coalesce((max(BDCODEMP) + 1), 1)
    from TEMPRESAS
    where (BDSTATUSEMP <> 1) --#Alt:16965 - Carlos Mello (06/10/2017) - A empresa de backup não pode interferir na sequência dos códigos das empresas novas
    into VCODIGO;

    new.BDCODEMP = VCODIGO;
  end
  else
  begin
    select BDCODEMP
    from TEMPRESAS
    where BDCODEMP = new.BDCODEMP
    into VCODIGO;

    if (VCODIGO > 0) then
    begin
      select coalesce((max(BDCODEMP) + 1), 1)
      from TEMPRESAS
      where (BDSTATUSEMP <> 1) --#Alt:16965 - Carlos Mello (06/10/2017) - A empresa de backup não pode interferir na sequência dos códigos das empresas novas
      into VCODIGO;

      new.BDCODEMP = VCODIGO;
    end
  end

  --#Alt:16965 - Carlos Mello (02/04/2018) - Caso não tenha nenhuma informação precisamos setar como sendo uma empresa "Normal"
  if (new.BDSTATUSEMP is null) then
    new.BDSTATUSEMP = 0;

  if (coalesce(new.BDCODMATRIZ, 0) <> 0) then
  begin
    select BDDATAINIESOCIAL
    from TEMPRESAS
    where BDCODEMP = new.BDCODMATRIZ
    into :VBDDATAINIESOCIAL;
    new.BDDATAINIESOCIAL = VBDDATAINIESOCIAL;
  end

  new.bdgerareventotoxicologico = 'TRUE';

  v_cod_agendamento_crtrab = null;
  select first 1 Y.BDCODAGENDAMENTO
  from VSH_BASE_TPLANO X
  join VSH_BASE_TAGENDAMENTO_PLANO Y on (Y.BDCODPLANOSCHIP = X.BDCODPLANOSCHIP)
  where X.BDCODPROCESSO = 58
  order by Y.BDCODAGENDAMENTO, Y.BDCODPLANOSCHIP desc into :v_cod_agendamento_crtrab;

  if (v_cod_agendamento_crtrab <> 0) then
     begin
       v_cod_emp_crtrab = null;

       select first 1 bdcodemp from VSH_EMP_TAGENDAMENTO_EMPRESAS where BDCODAGENDAMENTO = :v_cod_agendamento_crtrab and BDCODEMP = :new.bdcodemp into :v_cod_emp_crtrab;

       if (coalesce(v_cod_emp_crtrab,0) = 0) then
          insert into VSH_EMP_TAGENDAMENTO_EMPRESAS (BDCODAGENDAMENTO, BDCODEMP) values (:v_cod_agendamento_crtrab, new.BDCODEMP);
     end
end
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TESCRITORIO FOR TESCRITORIO
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vCodHist INTEGER;
  DECLARE VARIABLE vCODPLAPADRAO INTEGER;
  DECLARE VARIABLE vRefAtual VARCHAR(6);
--  declare variable vLog varchar(1000);
--  declare variable vcodcont integer;
--  declare variable vcodcontef integer;
--  declare variable vcodcontrh integer;
BEGIN
  /* somente na inserção */
  IF (OLD.bdcnpjesc IS NULL) THEN
     BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodesc IS NULL) OR (NEW.bdcodesc = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodesc)+1),1) FROM tescritorio INTO vcodigo;
       NEW.bdcodesc = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodesc FROM tescritorio WHERE bdcodesc = NEW.bdcodesc INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodesc)+1),1) FROM tescritorio INTO vcodigo;
            NEW.bdcodesc = vcodigo;
         END
    END
     END

  /*criar/atualizar empresa que representa o gestor para a online*/
  SELECT bdcodplapadrao, bdcodhist FROM TPLANO_CONF_ONLINE
  WHERE BDCODPLANOONLINE = (COALESCE(NEW.BDCODPLANOONLINE, OLD.bdcodplanoonline))
  INTO :vCODPLAPADRAO, :vcodhist;

  vRefAtual = (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database);

  IF (vRefAtual IS NULL) THEN
     vRefAtual = SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 6 FOR 2);

-- Gilberto - 21/02/2022 - Já faz dentro do sistema
  /*TEMPRESAS*/
--  IF (NEW.bdnomesc IS NOT NULL) THEN
--     vapelido = SUBSTRING(NEW.bdnomesc FROM 1 FOR 20);
--  ELSE
--     vapelido = SUBSTRING(OLD.bdnomesc FROM 1 FOR 20);
--
--  IF (NEW.bdnomesc IS NOT NULL) THEN
--     vNomeReduzido = SUBSTRING(NEW.bdnomesc FROM 1 FOR 40);
--  ELSE
--     vNomeReduzido = SUBSTRING(OLD.bdnomesc FROM 1 FOR 40);

--  IF (NEW.bdcodempinteg IS NOT NULL) THEN
--     BEGIN
--       UPDATE tempresas e SET
--       BDDATAINIATIVEMP = COALESCE(NEW.bdiniativesc, e.bddatainiativemp),
--       BDDATAFIMATIVEMP = COALESCE(NEW.bdfimativesc, e.bddatafimativemp),
--       BDAPELIDO = COALESCE(:vapelido, e.bdapelido),
--       BDIE = COALESCE(NEW.bdieesc, e.bdie)
--       WHERE BDCODEMP = NEW.bdcodempinteg;
--     END
--  ELSE
  IF (NEW.bdcodempinteg IS NULL) THEN
     BEGIN
        IF (OLD.bdcnpjesc IS NULL) THEN
          BEGIN
      INSERT INTO tempresas(BDCODEMP,BDCNPJEMP,BDDATAINIATIVEMP,BDDATAFIMATIVEMP,BDAPELIDO,BDIE,BDDATACADEMP,BDSTATUSEMP)
      VALUES (NEW.bdcodempinteg,COALESCE(NEW.bdCNPJESC, OLD.bdcnpjesc),COALESCE(NEW.bdiniativesc, OLD.bdiniativesc),
              COALESCE(NEW.bdfimativesc, OLD.bdfimativesc),substring(COALESCE(NEW.bdnomesc, OLD.bdnomesc) from 1 for 20),
              COALESCE(NEW.bdieesc, OLD.bdieesc),CURRENT_DATE,0);

          vRefAtual = CAST(SUBSTRING(CAST(NEW.bdiniativesc AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.bdiniativesc AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);
      UPDATE OR INSERT INTO TEMPRESAS_REF(BDCODEMP, BDREFEMP, BDCODPLAPADRAO, BDCODHIST, BDCODCID, BDCODCONT, BDCODCONTEF, BDCODCONTRH, BDCODCENTROS, BDCODCNAE,
                                          BDNOMEMP, BDAPEEMP, BDENDEMP, BDNUMEMP, BDBAIEMP, BDCEPEMP, BDDDDEMP, BDFONEEMP, BDFAXEMP, BDDDDCELULAREMP, BDCELULAREMP,
                                          BDEMAILEMP, BDCOMPLEMP, BDLOGREMP, BDIEEMP, BDIMEMP, BDSITEMP, BDDDDFAXEMP, BDCODPLANOONLINE, BDNOMREDUZEMP, BDCODPLATRIB)
      VALUES (NEW.bdcodempinteg, :vRefAtual, :vCODPLAPADRAO, :vcodhist,
                         COALESCE(NEW.bdcodcid, OLD.bdcodcid),
                         COALESCE(NEW.bdcodcont, OLD.bdcodcont),
                         COALESCE(NEW.bdCODCONTEF, OLD.bdcodcontef),
                         COALESCE(NEW.bdCODCONTRH, OLD.bdcodcontrh),
                         COALESCE(NEW.bdCODCENTRO, OLD.bdcodcentro),
                         COALESCE(NEW.bdCODCNAE, OLD.bdcodcnae),
                         COALESCE(NEW.BDNOMESC, OLD.bdnomesc),
              coalesce(SUBSTRING(NEW.bdnomesc from 1 for 20), SUBSTRING(old.bdnomesc FROM 1 FOR 20)),
                         COALESCE(NEW.bdendesc, OLD.bdendesc),
                         COALESCE(NEW.bdnumesc, OLD.bdnumesc),
                         COALESCE(NEW.bdbaiesc, OLD.bdbaiesc),
                         COALESCE(NEW.bdcepesc, OLD.bdcepesc),
                         COALESCE(NEW.bddddesc, OLD.bddddesc),
                         COALESCE(NEW.bdfoneesc, OLD.bdfoneesc),
                         COALESCE(NEW.bdfaxesc, OLD.bdfaxesc),
                         COALESCE(NEW.bddddcelularesc, OLD.bddddcelularesc),
                         COALESCE(NEW.bdcelularesc, OLD.bdcelularesc),
                         COALESCE(NEW.bdemailesc, OLD.bdemailesc),
                         COALESCE(NEW.bdcomplesc, OLD.bdcomplesc),
                         COALESCE(NEW.bdlogresc, OLD.bdlogresc),
                         COALESCE(NEW.bdieesc, OLD.bdieesc),
                         COALESCE(NEW.bdimesc, OLD.bdimesc),
                 'FALSE',
                         COALESCE(NEW.bddddfaxesc,OLD.bddddfaxesc),
                         COALESCE(NEW.bdcodplanoonline, OLD.bdcodplanoonline),
              SUBSTRING(coalesce(NEW.bdnomesc, OLD.bdnomesc) FROM 1 FOR 40),
              COALESCE(NEW.bdcodplatrib, OLD.bdcodplatrib)) MATCHING (BDCODEMP, BDREFEMP);


        SELECT COALESCE(MAX(bdcodemp),0) FROM tempresas
      WHERE (BDSTATUSEMP <> 1) INTO :vcodigo;

        IF (vcodigo > 0) THEN
          NEW.bdcodempinteg  = :vcodigo;

        UPDATE OR INSERT INTO TENQFED (BDCODENQFED, BDCODEMP, BDREFEMP)
        VALUES(3, NEW.bdcodempinteg, :vrefatual) MATCHING (BDCODENQFED, BDCODEMP, BDREFEMP);





      select count(*) from tterceiro_ref ter
      inner join vw_tterceiro_ref_max_min tref on (tref.bdcodter = ter.bdcodter and tref.bdrefemp = ter.bdrefemp)
      where ter.bdcgcter = new.bdcnpjesc and ter.bdieter = new.bdieesc
      into :vcodigo;
      if (coalesce(vcodigo, 0) = 0) then
    begin
        select first 1 coalesce(bdcodter, 0) +1 from tterceiro order by bdcodter desc into :vcodigo;
        insert into tterceiro (bdcodter, bdcgcter, bddataatu) values (:vcodigo,  new.bdcnpjesc, current_date);
        insert into tterceiro_ref (bdcodter, bdrefemp, bdapelidoter, bdnometer, bdlogrter, bdendter, bdcompter, bdcepter, bdbaiter, bddddter, bdfoneter, bdfaxter,
                                   bdemailter, bdieter, bddatacadter, bdimter, bdcodcid, bdcodpais,
                                   bddddfaxter, bdnumter, bddddcelularter, bdcelularter, bdcgcter)
        values (:vcodigo, :vrefatual,
                coalesce(substring(new.bdnomesc from 1 for 20), substring(old.bdnomesc from 1 for 20)),
                coalesce(new.bdnomesc, old.bdnomesc),
                coalesce(new.bdlogresc, old.bdlogresc),
                coalesce(new.bdendesc, old.bdendesc),
                coalesce(new.bdcomplesc, old.bdcomplesc),
                coalesce(new.bdcepesc, old.bdcepesc),
                coalesce(new.bdbaiesc, old.bdbaiesc),
                coalesce(new.bddddesc, old.bddddesc),
                coalesce(new.bdfoneesc, old.bdfoneesc),
                coalesce(new.bdfaxesc,  old.bdfaxesc),
                coalesce(new.bdemailesc, old.bdemailesc),
                coalesce(new.bdieesc, old.bdieesc),
                current_date,
                coalesce(new.bdimesc, old.bdimesc),
                coalesce(new.bdcodcid, old.bdcodcid),
                30,
                coalesce(new.bddddfaxesc, old.bddddfaxesc),
                coalesce(new.bdnumesc, old.bdnumesc),
                coalesce(new.bddddcelularesc, old.bddddcelularesc),
                coalesce(new.bdcelularesc, old.bdcelularesc),
                coalesce(new.bdcnpjesc, old.bdcnpjesc));
    end
    END
  END

-- Gilberto - 21/02/2022 - Não há necessidade pois é feito pelo sistema
--  -- Gilberto - 20/09/2019
--  -- Cadastro Escritório - Não permite alterar o contador #125792
--  -- Altera contador responsável no cadastro de empresa vinculada ao escritório
--  IF (((OLD.bdcnpjesc IS not NULL) AND (NEW.bdcodempinteg IS not NULL))) THEN
--  begin
--    execute statement 'select bdrefemp, bdcodcont, bdcodcontef, bdcodcontrh from vw_tempresas_ref where bdcodemp = '||new.bdcodempinteg
--    into :vrefatual, :vcodcont, :vcodcontef, vcodcontrh;
--
--    vlog = '';
--    if ((old.bdcodcont <> new.bdcodcont) or
--        (old.bdcodcontef <> new.bdcodcontef) or
--        (old.bdcodcontrh <> new.bdcodcontrh)) then
--       vlog = 'Contador responsável alterado pelo cadastro de escritório [Código: '||new.bdcodesc||'] vinculado a esta empresa:';
--
--    if (old.bdcodcont <> new.bdcodcont) then
--    begin
--      update tempresas_ref set bdcodcont = new.bdcodcont where bdcodemp = new.bdcodempinteg and bdrefemp = :vrefatual;
--      vlog = vlog||ASCII_CHAR(13)||ASCII_CHAR(10)||'Contábil: [DE: '||old.bdcodcont||'] <-> [PARA: '||new.bdcodcont||']';
--    end
--    if (old.bdcodcontef <> new.bdcodcontef) then
--    begin
--      update tempresas_ref set bdcodcontef = new.bdcodcontef where bdcodemp = new.bdcodempinteg and bdrefemp = :vrefatual;
--      vlog = vlog||ASCII_CHAR(13)||ASCII_CHAR(10)||'Escrita fiscal: [DE: '||old.bdcodcontef||'] <-> [PARA: '||new.bdcodcontef||']';
--    end
--    if (old.bdcodcontrh <> new.bdcodcontrh) then
--    begin
--      update tempresas_ref set bdcodcontrh = new.bdcodcontrh where bdcodemp = new.bdcodempinteg and bdrefemp = :vrefatual;
--      vlog = vlog||ASCII_CHAR(13)||ASCII_CHAR(10)||'RH/Folha: [DE: '||old.bdcodcontrh||'] <-> [PARA: '||new.bdcodcontrh||']';
--    end
--
--    if (vlog <> '') then
--       EXECUTE PROCEDURE sp_inserir_log(new.bdcodempinteg, NULL, null, NULL, null, NULL, CURRENT_DATE, CURRENT_TIME, :vlog, 0, 1,  null, null, 'TfrCadEscritorio', 'Cadastro de empresas', NULL, NULL, NULL, 'FALSE', CURRENT_DATE);
--  end
END^

CREATE OR ALTER TRIGGER TESCRITORIO_AI0 FOR TESCRITORIO
ACTIVE AFTER INSERT POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_INSERIR_OBS_FINANCEIRA(NEW.bdcodesc);
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TGRUPOCENTROS FOR TGRUPOCENTROS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodgrupocentros IS NULL) OR (NEW.bdcodgrupocentros = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodgrupocentros)+1),1) FROM tgrupocentros WHERE (bdcodcentro = NEW.bdcodcentro) INTO vcodigo;
        NEW.bdcodgrupocentros = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodgrupocentros FROM tgrupocentros WHERE (bdcodcentro = NEW.bdcodcentro) AND (bdcodgrupocentros = NEW.bdcodgrupocentros) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodgrupocentros)+1),1) FROM tgrupocentros WHERE (bdcodcentro = NEW.bdcodcentro) INTO vcodigo;
           NEW.bdcodgrupocentros = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TGRUPOCONTAS FOR TGRUPOCONTAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodgrupocontas IS NULL) OR (NEW.bdcodgrupocontas = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodgrupocontas)+1),1) FROM tgrupocontas WHERE (bdcodplapadrao = NEW.bdcodplapadrao) INTO vcodigo;
        NEW.bdcodgrupocontas = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodgrupocontas FROM tgrupocontas WHERE (bdcodplapadrao = NEW.bdcodplapadrao) AND (bdcodgrupocontas = NEW.bdcodgrupocontas) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodgrupocontas)+1),1) FROM tgrupocontas WHERE (bdcodplapadrao = NEW.bdcodplapadrao) INTO vcodigo;
           NEW.bdcodgrupocontas = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TGRUPOUSUARIO FOR TGRUPOUSUARIO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdCODGRUPO IS NULL) OR (NEW.BDCODGRUPO = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodgrupo)+1),1) FROM tgrupousuario INTO vcodigo;
       NEW.BDCODGRUPO = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdCODGRUPO FROM tgrupousuario WHERE bdCODGRUPO = NEW.bdCODGRUPO INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodgrupo)+1),1) FROM tgrupousuario INTO vcodigo;
            NEW.BDCODGRUPO = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_THIST FOR THIST
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodhist IS NULL) OR (NEW.bdcodhist = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdcodhist)+1),1) FROM thist INTO vcodigo;
       NEW.bdcodhist = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodhist FROM thist WHERE bdcodhist = NEW.bdcodhist INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodhist)+1),1) FROM thist INTO vcodigo;
            NEW.bdcodhist = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TIMPOSTO FOR TIMPOSTO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodimp IS NULL) OR (NEW.bdcodimp = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodimp)+1),1) FROM timposto INTO vcodigo;
       NEW.bdcodimp = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodimp FROM timposto WHERE bdcodimp = NEW.bdcodimp INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodimp)+1),1) FROM timposto INTO vcodigo;
            NEW.bdcodimp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TMOEDAS FOR TMOEDAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodmoedas IS NULL) OR (NEW.bdcodmoedas = 0)) THEN
    BEGIN 
       SELECT COALESCE((MAX(bdcodmoedas)+1),1) FROM tmoedas INTO vcodigo;
       NEW.bdcodmoedas = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodmoedas FROM tmoedas WHERE bdcodmoedas = NEW.bdcodmoedas INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodmoedas)+1),1) FROM tmoedas INTO vcodigo;
            NEW.bdcodmoedas = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TNATJUR FOR TNATJUR
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdCODNATJUR IS NULL) OR (NEW.bdCODNATJUR = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdCODNATJUR) + 1), 1)
      FROM TNATJUR
      INTO :vCodigo;

      NEW.bdCODNATJUR = :vCodigo;
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TOCUPACAO FOR TOCUPACAO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodocupa IS NULL) OR (NEW.bdcodocupa = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodocupa)+1),1) FROM tocupacao INTO vcodigo;
       NEW.bdcodocupa = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodocupa FROM tocupacao WHERE bdcodocupa = NEW.bdcodocupa INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodocupa)+1),1) FROM tocupacao INTO vcodigo;
            NEW.bdcodocupa = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TPAIS FOR TPAIS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodpais IS NULL) OR (NEW.bdcodpais = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodpais)+1),1) FROM tpais  WHERE bdcodpais < 9999 INTO vcodigo;
       NEW.bdcodpais = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodpais FROM tpais WHERE bdcodpais = NEW.bdcodpais INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodpais)+1),1) FROM tpais WHERE bdcodpais < 9999  INTO vcodigo;
            NEW.bdcodpais = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TPLANO_PADRAO FOR TPLANO_PADRAO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodplapadrao IS NULL) OR (NEW.bdcodplapadrao = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodplapadrao)+1),1) FROM tplano_padrao INTO vcodigo;
        NEW.bdcodplapadrao = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodplapadrao FROM tplano_padrao WHERE bdcodplapadrao = NEW.bdcodplapadrao INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodplapadrao)+1),1) FROM tplano_padrao INTO vcodigo;
            NEW.bdcodplapadrao = vcodigo;
         END
    END

  --#alt:17928 - Quando efetuava a cópia do plano de contabilização, e ja existia estes planos mas não o plano de contas padrao, estava gerando erro. Ana - 21/03/2017
  vCodigo = 0;
  SELECT bdcodplapadrao_sped FROM TPLANO_PADRAO_SPED WHERE bdcodplapadrao_sped = NEW.bdcodplapadrao INTO vcodigo;
  IF (vcodigo > 0) THEN
    DELETE FROM TPLANO_PADRAO_SPED WHERE bdcodplapadrao_sped = NEW.bdcodplapadrao;

  vCodigo = 0;
  SELECT bdcodplapadrao_fcont FROM TPLANO_PADRAO_FCONT WHERE bdcodplapadrao_fcont = NEW.bdcodplapadrao INTO vcodigo;
  IF (vcodigo > 0) THEN
    DELETE FROM TPLANO_PADRAO_FCONT WHERE bdcodplapadrao_fcont = NEW.bdcodplapadrao;
  --#alt:17928 .fim
END
^

--#alt:15089 - Triggers para as tabelas do registro I157. Ana - 15/03/2017
CREATE OR ALTER TRIGGER tr_bf_insert_tplano_ecd_i157 FOR tplano_padrao_ecd_i157
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF ((NEW.bdcodplapadraoi157 IS NULL) OR (NEW.bdcodplapadraoi157 = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodplapadraoi157)+1),1) FROM tplano_padrao_ecd_i157
        WHERE BDCODPLAPADRAO = NEW.bdcodplapadrao
        INTO vcodigo;
        NEW.bdcodplapadraoi157 = vcodigo;
     END
END
^

CREATE OR ALTER TRIGGER tr_bf_insert_tpla_ecd_i157 FOR planos_tpla_ecd_i157
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF ((NEW.bdcodplapadraoi157 IS NULL) OR (NEW.bdcodplapadraoi157 = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodplapadraoi157)+1),1) FROM tplano_padrao_ecd_i157 INTO vcodigo;
        NEW.bdcodplapadraoi157 = vcodigo;
     END
END
^
--#alt:15089. fim

CREATE OR ALTER trigger tr_bf_insert_TENCEXE_PREPPPLT for VSUC_EMPRESAS_TENCEXE_PREP_PPLT
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF ((NEW.BDCHAVEZER IS NULL) OR (NEW.BDCHAVEZER = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCHAVEZER)+1),1) FROM VSUC_EMPRESAS_TENCEXE_PREP_PPLT
        WHERE BDCODPLANOONLINE = NEW.BDCODPLANOONLINE AND BDTIPO = NEW.BDTIPO INTO vcodigo;
        NEW.BDCHAVEZER = vcodigo;
     END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TPLANO_PAGAMENTO FOR TPLANO_PAGAMENTO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodigopla IS NULL) OR (NEW.bdcodigopla = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodigopla)+1),1) FROM TPLANO_PAGAMENTO INTO vcodigo;
       NEW.bdcodigopla = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodigopla FROM TPLANO_PAGAMENTO WHERE bdcodigopla = NEW.bdcodigopla INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodigopla)+1),1) FROM TPLANO_PAGAMENTO INTO vcodigo;
            NEW.bdcodigopla = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TTIPOSERVICO FOR TTIPOSERVICO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.bdcodtiposerv IS NULL) OR (NEW.bdcodtiposerv = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodtiposerv) + 1, 1)
       FROM ttiposervico
       INTO :vNovoCod;

       NEW.bdcodtiposerv = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TUSUARIO FOR TUSUARIO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodusu  IS NULL) OR (NEW.bdcodusu = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodusu)+1),1) FROM tusuario INTO vcodigo;
       NEW.bdcodusu = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodusu FROM tusuario WHERE bdcodusu = NEW.bdcodusu INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodusu)+1),1) FROM tusuario INTO vcodigo;
            NEW.bdcodusu = vcodigo;
         END
    END
END
^

CREATE OR ALTER trigger tusuario_ai0 for tusuario
active after insert position 0
AS
begin
  /* Trigger text */
  UPDATE OR INSERT INTO TUSUARIO_ITEMSTELA_CONFIG (BDCODUSU, BDTELA, BDCOMPNAME, BDCOMPVALUE, BDCOMPINDEX, BDCOMPWIDTH)
                                         VALUES (new.bdcodusu, 'frProcessoDCTFWeb', 'spnavdctf&Navegação 2023', '0', 0, 0)
                                       MATCHING (BDCODUSU, BDTELA, BDCOMPNAME);
      UPDATE OR INSERT INTO TUSUARIO_ITEMSTELA_CONFIG (BDCODUSU, BDTELA, BDCOMPNAME, BDCOMPVALUE, BDCOMPINDEX, BDCOMPWIDTH)
                                         VALUES (new.bdcodusu, 'frProcessoDCTFWeb', 'spnavdctf&Navegação 2024', '0', 0, 0)
                                       MATCHING (BDCODUSU, BDTELA, BDCOMPNAME);
      UPDATE OR INSERT INTO TUSUARIO_ITEMSTELA_CONFIG (BDCODUSU, BDTELA, BDCOMPNAME, BDCOMPVALUE, BDCOMPINDEX, BDCOMPWIDTH)
                                         VALUES (new.bdcodusu, 'frProcessoDCTFWeb', 'spnavdctf&Navegação 2025', '-1', 0, 0)
                                       MATCHING (BDCODUSU, BDTELA, BDCOMPNAME);
      UPDATE OR INSERT INTO TUSUARIO_ITEMSTELA_CONFIG (BDCODUSU, BDTELA, BDCOMPNAME, BDCOMPVALUE, BDCOMPINDEX, BDCOMPWIDTH)
                                         VALUES (new.bdcodusu, 'frProcessoDCTFWeb', 'spnavdctf', 'False', 1, 0)
                                       MATCHING (BDCODUSU, BDTELA, BDCOMPNAME);
      /* FGTS Digital */
      UPDATE OR INSERT INTO TUSUARIO_ITEMSTELA_CONFIG (BDCODUSU, BDTELA, BDCOMPNAME, BDCOMPVALUE, BDCOMPINDEX, BDCOMPWIDTH)
                                         VALUES (new.bdcodusu, 'frProcessoFGTSDigital', 'spNavFGTS&Navegação 2024', '0', 0, 0)
                                       MATCHING (BDCODUSU, BDTELA, BDCOMPNAME);
      UPDATE OR INSERT INTO TUSUARIO_ITEMSTELA_CONFIG (BDCODUSU, BDTELA, BDCOMPNAME, BDCOMPVALUE, BDCOMPINDEX, BDCOMPWIDTH)
                                         VALUES (new.bdcodusu, 'frProcessoFGTSDigital', 'spNavFGTS&Navegação 2025', '-1', 0, 0)
                                       MATCHING (BDCODUSU, BDTELA, BDCOMPNAME);
      UPDATE OR INSERT INTO TUSUARIO_ITEMSTELA_CONFIG (BDCODUSU, BDTELA, BDCOMPNAME, BDCOMPVALUE, BDCOMPINDEX, BDCOMPWIDTH)
                                         VALUES (new.bdcodusu, 'frProcessoFGTSDigital', 'spNavFGTS', 'False', 1, 0)
                                       MATCHING (BDCODUSU, BDTELA, BDCOMPNAME);
      /* eSocial Download */
      UPDATE OR INSERT INTO TUSUARIO_ITEMSTELA_CONFIG (BDCODUSU, BDTELA, BDCOMPNAME, BDCOMPVALUE, BDCOMPINDEX, BDCOMPWIDTH)
                                         VALUES (new.bdcodusu, 'frCadDownloadESocial', 'spVersNav&Navegação 2024', '0', 0, 0)
                                       MATCHING (BDCODUSU, BDTELA, BDCOMPNAME);
      UPDATE OR INSERT INTO TUSUARIO_ITEMSTELA_CONFIG (BDCODUSU, BDTELA, BDCOMPNAME, BDCOMPVALUE, BDCOMPINDEX, BDCOMPWIDTH)
                                         VALUES (new.bdcodusu, 'frCadDownloadESocial', 'spVersNav&Navegação 2025', '-1', 0, 0)
                                       MATCHING (BDCODUSU, BDTELA, BDCOMPNAME);
      UPDATE OR INSERT INTO TUSUARIO_ITEMSTELA_CONFIG (BDCODUSU, BDTELA, BDCOMPNAME, BDCOMPVALUE, BDCOMPINDEX, BDCOMPWIDTH)
                                         VALUES (new.bdcodusu, 'frCadDownloadESocial', 'spVersNav', 'False', 1, 0)
                                       MATCHING (BDCODUSU, BDTELA, BDCOMPNAME);
end
^

CREATE OR ALTER TRIGGER TUSUARIO_AU0 FOR TUSUARIO
ACTIVE AFTER UPDATE POSITION 0
AS
begin
  if ((new.bdcontdesativousu = 'TRUE') and (new.bdcontdesativousu <> old.bdcontdesativousu)) then
  begin
    -- exclui usuário configurados na central de tarefas
    delete from VCT_EMPRESA_TAREFA_USUARIO usu
    where exists(select first 1 bdcodemp from vct_empresa_tsolicitatarefa
                 where bdcodemp=usu.bdcodemp
                 and bdcodst=usu.bdcodst
                 and bddatafim is null)
    and usu.bdcodusu = new.bdcodusu;

    -- insere trâmites nas tarefas onde o usuário é responsável
    insert into vct_empresa_thistoricotarefa(bdcodemp,bdcodst,bdcodusuresponsavel,bddata,bdhora,bdstatus,bdcodbhs)
    select BDCODEMP, BDCODST, BDCODUSU,
           current_date as BDDATA, current_time as BDHORA,
           7 as BDSTATUS,-- Troca de usuário
           41 as BDCODBHS -- conta de usuário desativada
    from (
    select usu.bdcodemp, usu.bdcodst, usu.bdcodusu
    from vct_empresa_tarefa_usuario usu
    join vct_empresa_tsolicitatarefa sol on(sol.bdcodemp=usu.bdcodemp and sol.bdcodst=usu.bdcodst)
    where sol.bddatafim is null
    and usu.bdcodusu = new.bdcodusu
    union
    select sol.bdcodemp, sol.bdcodst, imp.bdcodusu
    from vct_empresa_usuario_imp imp
    join vct_empresa_tsolicitatarefa sol on(sol.bdcodemp=imp.bdcodemp and sol.bdcodimp=imp.bdcodimp)
    where sol.bddatafim is null
    and imp.bdcodusu = new.bdcodusu
    union
    select sol.bdcodemp, sol.bdcodst, obr.bdcodusu
    from vct_empresa_usuario_obr obr
    join vct_empresa_tsolicitatarefa sol on(sol.bdcodemp=obr.bdcodemp and sol.bdcodobrigacao=obr.bdcodobrser)
    where sol.bddatafim is null
    and obr.bdcodusu = new.bdcodusu
    union
    select sol.bdcodemp, sol.bdcodst, ser.bdcodusu
    from vct_empresa_usuario_ser ser
    join vct_empresa_tsolicitatarefa sol on(sol.bdcodemp=ser.bdcodemp and sol.bdcodservico=ser.bdcodobrser)
    where sol.bddatafim is null
    and ser.bdcodusu = new.bdcodusu
    );

    -- exclui usuários configurados no plano de tarefas e processos recorrentes
    delete from VCT_USUARIO_TAREFA where bdcodusu = new.bdcodusu;
    delete from VCT_EMPRESA_USUARIO_IMP where bdcodusu = new.bdcodusu;
    delete from VCT_EMPRESA_USUARIO_OBR where bdcodusu = new.bdcodusu;
    delete from VCT_EMPRESA_USUARIO_SER where bdcodusu = new.bdcodusu;

    -- Insere o log da alteração
    EXECUTE PROCEDURE SP_INSERIR_LOG(null, NULL, (select bdcodusu from VW_USUARIOS_SECAO),
                                     NULL, (select bdcodsis from VW_GET_MODULO), NULL, null, null,
                                     'O cadastro do usuário '||new.bdcodusu||' - '||new.bdnomcomplusu||
                                     ' foi desativado, isto resultará na remoção das suas atribuições das tarefas '||
                                     'na Central de Tarefas e no Plano de Tarefas e Processos Recorrentes, caso haja.',
                                     0, 2, null, null, (select BDNOMETELA from vw_get_processo),
                                     (select BDCAPTIONTELA from vw_get_processo), NULL,
                                     'TUSUARIO', null, 'FALSE', current_date);
  end
end
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_BASE_TCFPS FOR VEF_BASE_TCFPS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF ((NEW.bdid IS NULL) OR (NEW.bdid = 0)) THEN
     BEGIN
       SELECT bdresult+1 FROM maxsci('bdid', 'bdid', '', 'vef_base_tcfps') INTO NEW.bdid;
     END
  ELSE
     BEGIN
       SELECT bdid FROM vef_base_tcfps WHERE bdid = NEW.bdid INTO :vcodigo;

       IF (NOT vcodigo IS NULL) THEN
          SELECT bdresult+1 FROM maxsci('bdid', 'bdid', '', 'vef_base_tcfps') INTO NEW.bdid;
     END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_BASE_TCST FOR VEF_BASE_TCST
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
   IF (NEW.bdcodcst IS NULL) THEN
      BEGIN
        SELECT BDCODCST FROM vef_base_tcst
        WHERE BDCODCST = NEW.BDCODCST AND
              BDCODCID = NEW.BDCODCID AND
              BDANOCST = NEW.BDANOCST INTO :vCodigo;

        IF (:vcodigo IS NULL) THEN
          BEGIN
            NEW.BDID = GEN_ID(GEN_VEF_BASE_TCST, 1);
            SELECT COALESCE((MAX(BDCODCST)+1), 1) FROM vef_base_tcst WHERE bdcodcid = NEW.bdcodcid INTO vNova_Chave;
            NEW.BDCODCST = vNova_Chave;
         END
      END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_BASE_TGRAFICA FOR VEF_BASE_TGRAFICA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodgra IS NULL) OR (NEW.bdcodgra = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodgra)+1),1) FROM vef_base_tgrafica INTO vcodigo;
       NEW.bdcodgra = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodgra FROM vef_base_tgrafica WHERE bdcodgra = NEW.bdcodgra INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodgra)+1),1) FROM vef_base_tgrafica INTO vcodigo;
            NEW.bdcodgra = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_BASE_TNATOP FOR VEF_BASE_TNATOP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE str VARCHAR(20);
  DECLARE VARIABLE wCont VARCHAR(5);  
BEGIN
  /* Trigger text */

  /* Alt.: 21963 - Marca o "bdCONTABILIZA" conforme estiver na classificação acima da que está sendo inserida */
  SELECT FIRST 1 bdCONTABILIZA
  FROM VEF_BASE_TNATOP
  WHERE bdCLASSIFICACAO LIKE ''||SUBSTRING(new.bdCODNAT FROM 1 FOR 1)||'.'||SUBSTRING(new.bdCODNAT FROM 2 FOR 2)||'0.'||SUBSTRING(new.bdCODNAT FROM 2 FOR 3)||''
     OR bdCLASSIFICACAO LIKE ''||SUBSTRING(new.bdCODNAT FROM 1 FOR 1)||'.'||SUBSTRING(new.bdCODNAT FROM 2 FOR 1)||'%.'||SUBSTRING(new.bdCODNAT FROM 2 FOR 3)||''
  ORDER BY bdCLASSIFICACAO
  INTO wCont;

  IF (wCont = 'TRUE') THEN
    new.bdCONTABILIZA = 'TRUE';

  vcodigo = 0;
  IF ((NEW.bdcodnat IS NULL) OR (NEW.bdcodnat = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodnat)+1),1) FROM vef_base_tnatop INTO vcodigo;
       NEW.bdcodnat = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodnat FROM vef_base_tnatop WHERE bdcodnat = NEW.bdcodnat INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodnat)+1),1) FROM vef_base_tnatop INTO vcodigo;
            NEW.bdcodnat = vcodigo;
         END
    END

  IF (CAST(SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 5) AS INTEGER) = 0) THEN
      -- 1
      NEW.bdclassificacao = SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1);
  ELSE
    BEGIN
      IF (CAST(SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 3) AS INTEGER) IN (100,150,200,250,300,350,400,450,500,550,600,650,700,750,800,850,900,950)) THEN
        --1.100
        NEW.bdclassificacao =  SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1) || '.' || SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 3);
      ELSE
        BEGIN
            IF (CAST(SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 3 FOR 2) AS INTEGER) < 50 ) THEN
              str = SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 1) ||'00';
            ELSE
              str = SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 1) ||'50';
    
            IF (CAST(SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 5 FOR 3) AS INTEGER) = 0) THEN
              --1.100.101
              NEW.bdclassificacao = SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1) || '.' ||str||'.'|| SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 3);-- substring( cast(new.bdcodnat as varchar(7)) from 2 for 3);
            ELSE
              --1.100.101.001
              NEW.bdclassificacao = SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1) || '.' ||str||'.'|| SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 3)||'.'|| SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 5 FOR 3);
        END
      /*Sol: 12368 Patrick T. Sá 28/10/2015. Deve buscar o bdliberacontabiliza do primeiro nivel da CFOP.*/
      IF (NEW.bdliberacontabiliza IS NULL) THEN
        BEGIN
          SELECT NATOP.bdliberacontabiliza FROM VEF_BASE_TNATOP NATOP WHERE NATOP.bdclassificacao = SUBSTRING(NEW.bdclassificacao FROM 1 FOR 9) INTO NEW.bdliberacontabiliza;
          IF (NEW.bdliberacontabiliza IS NULL) THEN
            SELECT NATOP.bdliberacontabiliza FROM VEF_BASE_TNATOP NATOP WHERE NATOP.bdclassificacao = SUBSTRING(NEW.bdclassificacao FROM 1 FOR 5) INTO NEW.bdliberacontabiliza;
        END
    END


END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_BASE_TNBM FOR VEF_BASE_TNBM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodnbm IS NULL) OR (NEW.bdcodnbm = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodnbm)+1),1) FROM vef_base_tnbm INTO vcodigo;
       NEW.bdcodnbm = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodnbm FROM vef_base_tnbm WHERE bdcodnbm = NEW.bdcodnbm INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodnbm)+1),1) FROM vef_base_tnbm INTO vcodigo;
            NEW.bdcodnbm = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_BASE_TOBSERVAC FOR VEF_BASE_TOBSERVACAO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodtipo = 101) OR (NEW.bdcodtipo = 102)) THEN
     BEGIN
      vcodigo = 0;
      IF ((NEW.bdcodobs IS NULL) OR (NEW.bdcodobs = 0)) THEN
        BEGIN
           SELECT COALESCE((MAX(bdcodobs)+1),1) FROM vef_base_tobservacao INTO vcodigo;
           NEW.bdcodobs = vcodigo;
        END
      ELSE
        BEGIN
           SELECT bdcodobs FROM vef_base_tobservacao WHERE bdcodobs = NEW.bdcodobs INTO vcodigo;
    
           IF (vcodigo > 0) THEN
             BEGIN
                SELECT COALESCE((MAX(bdcodobs)+1),1) FROM vef_base_tobservacao INTO vcodigo;
                NEW.bdcodobs = vcodigo;
             END
        END
     END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_BASE_TTABCODC FOR VEF_BASE_TTABCODCONS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDORDEMCONS IS NULL) OR (NEW.BDORDEMCONS = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDORDEMCONS)+1),1) FROM VEF_BASE_TTABCODCONS INTO vcodigo;
       NEW.BDORDEMCONS = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDORDEMCONS FROM VEF_BASE_TTABCODCONS WHERE BDORDEMCONS = NEW.BDORDEMCONS INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDORDEMCONS)+1),1) FROM VEF_BASE_TTABCODCONS INTO vcodigo;
            NEW.BDORDEMCONS = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_BASE_TTABCTA FOR VEF_BASE_TTABCTA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodcta IS NULL) OR (NEW.bdcodcta = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodcta)+1),1) FROM vef_base_ttabcta INTO vcodigo;
       NEW.bdcodcta = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodcta FROM vef_base_ttabcta WHERE bdcodcta = NEW.bdcodcta INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodcta)+1),1) FROM vef_base_ttabcta INTO vcodigo;
            NEW.bdcodcta = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_BASE_TTBDOCFIS FOR VEF_BASE_TTABDOCFIS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODDOCFIS IS NULL) OR (NEW.BDCODDOCFIS = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDCODDOCFIS)+1),1) FROM vef_base_ttabdocfis INTO vcodigo;
       NEW.BDCODDOCFIS = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDCODDOCFIS FROM vef_base_ttabdocfis WHERE BDCODDOCFIS = NEW.BDCODDOCFIS INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODDOCFIS)+1),1) FROM vef_base_ttabdocfis INTO vcodigo;
            NEW.BDCODDOCFIS = vcodigo;
         END
    END
END
^

CREATE OR ALTER trigger tr_bf_insert_vef_emp_tc100sai for vef_emp_tc100sai
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
  end
END
^

CREATE OR ALTER trigger tr_bf_insert_vef_emp_tc500ent for vef_emp_tc500ent
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
  end
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_EMP_TC500SAI FOR VEF_EMP_TC500SAI
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_EMP_TD400SAI FOR VEF_EMP_TD400SAI
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE VCHAVELAN INTEGER;
BEGIN
  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVE)), 1) FROM VEF_EMP_TMOVSAI WHERE (BDCODEMP = NEW.BDCODEMP) INTO VCHAVELAN;
      NEW.BDCHAVE = VCHAVELAN;
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_EMP_TD500SAI FOR VEF_EMP_TD500SAI
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_EMP_TD530SAI FOR VEF_EMP_TD530SAI
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchavelan INTEGER;
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

    IF ((NEW.BDORDEMTF IS NULL) OR (NEW.BDORDEMTF = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(BDORDEMTF) + 1), 1) FROM vef_emp_td530sai WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vCodigo;
       NEW.BDORDEMTF = vCodigo;
     END

END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_EMP_TMOVENT FOR VEF_EMP_TMOVENT
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
--  declare variable vNova_Chave integer;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
     begin
  -- só atribui o usuário se for nulo
  IF (NEW.bdcodusu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusu = vcodigo;
    END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  NEW.bdreflan = CAST( SUBSTRING(CAST(NEW.bddataentradaent AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.bddataentradaent AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);

  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;
  --TIPO DO LANCAMENTO DA TABELA TIPOS_LANCAMENTOS_PADRAO
  IF ((NEW.BDCODTIPO IS NULL) OR (NEW.BDCODTIPO = 0)) THEN
     NEW.BDCODTIPO = 101;
  end
END
^

CREATE OR ALTER trigger tr_bf_insert_vef_emp_tmoventite for vef_emp_tmoventitens
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;

BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Chave;
      NEW.BDORDEM = vNova_Chave;
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
          NEW.BDCHAVE = vchavelan;
        END
    END
    ELSE
    BEGIN
       SELECT BDORDEM FROM vef_emp_tmoventitens WHERE (BDORDEM = NEW.BDORDEM) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
           NEW.BDORDEM = vNova_Chave;
         END
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
           NEW.BDCHAVE = vchavelan;
         END
    END

    NEW.BDPREFIXONAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4)  AS INTEGER);
    NEW.BDDIGOPERNAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1)  AS INTEGER);
  end
END
^

CREATE OR ALTER trigger tr_bf_insert_vef_emp_tmoventret for vef_emp_tmoventret
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
  end
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_EMP_TMOVSAI FOR VEF_EMP_TMOVSAI
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
--  declare variable vNova_Chave integer;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
     begin

  -- só atribui o usuário se for nulo
  IF (NEW.bdcodusu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusu = vcodigo;
    END


--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  NEW.bdreflan = CAST( SUBSTRING(CAST(NEW.bddataemissao AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.bddataemissao AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);

  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;
  --TIPO DO LANCAMENTO DA TABELA TIPOS_LANCAMENTOS_PADRAO
  IF ((NEW.BDCODTIPO IS NULL) OR (NEW.BDCODTIPO = 0)) THEN
     NEW.BDCODTIPO = 101;

  end
END
^

CREATE OR ALTER trigger tr_bf_insert_vef_emp_tmovsaiite for vef_emp_tmovsaiitens
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Chave;
      NEW.BDORDEM = vNova_Chave;
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
          NEW.BDCHAVE = vchavelan;
        END
    END
    ELSE
    BEGIN
       SELECT BDORDEM FROM vef_emp_tmovsaiitens WHERE (BDORDEM = NEW.BDORDEM) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
           NEW.BDORDEM = vNova_Chave;
         END

       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
          NEW.BDCHAVE = vchavelan;
        END

    END

    NEW.BDPREFIXONAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4)  AS INTEGER);
    NEW.BDDIGOPERNAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1)  AS INTEGER);
  end
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_EMP_TMOVSAIRET FOR VEF_EMP_TMOVSAIRET
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_EMP_TMOVSER FOR VEF_EMP_TMOVSER
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE wTipoLan INTEGER;
  DECLARE VARIABLE wReferenciaParametro DATE;
  DECLARE VARIABLE wDataParametro VARCHAR(50);
  DECLARE VARIABLE wCampoServico VARCHAR(50);
  DECLARE VARIABLE wDataReferencia DATE;

BEGIN
  IF (COALESCE(RDB$GET_CONTEXT('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') THEN
    BEGIN

      IF (NEW.bdcodusu IS NULL) THEN
        BEGIN
          SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
          NEW.bdcodusu = vcodigo;
        END
    
      IF (NEW.bdcodusuinclu IS NULL) THEN
        BEGIN
          SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
          NEW.bdcodusuinclu = vcodigo;
        END

      wDataReferencia = NEW.BDDATAEMISSAO;

      wTipoLan = COALESCE(NEW.BDTIPLAN, 0);
      IF (wTipoLan = 0) THEN
        wCampoServico = 'BDSEREMIPOREXECUCAO';
      ELSE
      IF (wTipoLan = 1) THEN
        wCampoServico = 'BDSERRECPOREXECUCAO';

      IF (wCampoServico IS NOT NULL) THEN
        BEGIN
          SELECT P.BDVALOR FROM TPARGER P WHERE UPPER(P.BDCAMPO) = :wCampoServico INTO wDataParametro;
          IF (wDataParametro IS NOT NULL) THEN
            BEGIN
              wReferenciaParametro = CAST(SUBSTRING(wDataParametro FROM 7 FOR 4) ||'-'|| SUBSTRING(wDataParametro FROM 4 FOR 2) ||'-'|| SUBSTRING(wDataParametro FROM 1 FOR 2) AS DATE);
              IF (NEW.BDDATAEMISSAO >= wReferenciaParametro) THEN
                wDataReferencia = NEW.BDDT_EXE_SERV;
            END
        END

      NEW.BDREFLAN = CAST( SUBSTRING(CAST(wDataReferencia AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(wDataReferencia AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);
      
      NEW.bddatalan = CURRENT_DATE;
      NEW.bdhoralan = CURRENT_TIME;
    
      NEW.bddatainclusao = NEW.bddatalan;
      NEW.bdhorainclusao = NEW.bdhoralan;
    
      --TIPO DO LANCAMENTO DA TABELA TIPOS_LANCAMENTOS_PADRAO
      IF ((NEW.BDCODTIPO IS NULL) OR (NEW.BDCODTIPO = 0)) THEN
        NEW.BDCODTIPO = 101;
    
      IF ((NEW.BDTIPOLANINCLU IS NULL) OR (NEW.BDTIPOLANINCLU = 0)) THEN
        NEW.BDTIPOLANINCLU = NEW.BDCODTIPO;
    
      /* sol.: #9828 Jean 16/12/2014: SUBSERIE não pode mais ser NULL*/
      IF (NEW.BDSUBSERIE IS NULL) THEN
        NEW.BDSUBSERIE = '';

      IF ((NEW.BDCONDPGTO IS NULL) OR (NEW.BDCONDPGTO = 0)) THEN
        NEW.BDCONDPGTO = 0;
    END
END
^

CREATE OR ALTER trigger tr_bf_insert_vef_emp_tmoventded for vef_emp_tmoventded
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovENT WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
  end
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_EMP_TMOVSAIDED FOR VEF_EMP_TMOVSAIDED
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovSAI WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
END
^


CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAIDED_BI0 FOR VEF_EMP_TMOVSAIDED
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
END
^

CREATE OR ALTER trigger vef_emp_tmoventded_bi0 for vef_emp_tmoventded
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
  end
END
^

CREATE OR ALTER trigger tr_bf_insert_vef_emp_tmovserded for vef_emp_tmovserded
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
  end
END
^

CREATE OR ALTER trigger tr_bf_insert_vef_emp_tmovserite for vef_emp_tmovseritens
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordem)+1), 1) FROM vef_emp_tmovseritens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Chave;
      NEW.bdordem = vNova_Chave;

      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
          NEW.BDCHAVE = vchavelan;
        END
    END
    ELSE
    BEGIN
      SELECT bdordem FROM vef_emp_tmovseritens WHERE (bdordem = NEW.bdordem) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

      IF (vcodigo > 0) THEN
        BEGIN
          SELECT COALESCE((MAX(bdordem)+1), 1) FROM vef_emp_tmovseritens WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
          NEW.bdordem = vNova_Chave;
        END

      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
          NEW.BDCHAVE = vchavelan;
        END
    END

    NEW.BDPREFIXONAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4)  AS INTEGER);
    NEW.BDDIGOPERNAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1)  AS INTEGER);
  end
END
^

CREATE OR ALTER trigger tr_bf_insert_vef_emp_tmovserret for vef_emp_tmovserret
active before insert position 0
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
  DECLARE VARIABLE vcodigo INTEGER;
  DECLARE VARIABLE vordem INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
  end
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_EMP_TMSVLTRAN FOR VEF_EMP_TMOVSAIVLTRAN
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VEF_INT_TSPEDICMS FOR VEF_INT_TSPEDICMS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdcodigo IS NULL) OR (NEW.bdcodigo = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodigo) + 1), 1) FROM VEF_INT_TSPEDICMS WHERE bdcodemp = NEW.bdcodemp AND bdcodigo < 999999  INTO vCodigo;
      NEW.bdcodigo = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodigo FROM VEF_INT_TSPEDICMS WHERE bdcodemp = NEW.bdcodemp AND bdcodigo = NEW.bdcodigo INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodigo) + 1), 1) FROM VEF_INT_TSPEDICMS WHERE bdcodemp = NEW.bdcodemp AND bdcodigo < 999999 INTO vCodigo;
           NEW.bdcodigo = vCodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_vef_emp_tdadosd695 FOR vef_emp_tdadosd695
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdcodigo IS NULL) OR (NEW.bdcodigo = 0)) THEN
    BEGIN
--      SELECT COALESCE((MAX(bdcodigo) + 1), 1) FROM vef_emp_tdadosd695 WHERE bdcodemp = NEW.bdcodemp AND bdcodigo < 999999  INTO vCodigo;
--      NEW.bdcodigo = vCodigo;

      SELECT BDCODIGO FROM VEF_EMP_TDADOSD695 WHERE BDCODEMP = NEW.BDCODEMP AND BDREFERENCIA = NEW.BDREFERENCIA AND BDNOMEARQ = NEW.BDNOMEARQ INTO VCODIGO;
      IF ((vCodigo IS NULL) OR (vCodigo = 0)) THEN
        SELECT COALESCE((MAX(bdcodigo) + 1), 1) FROM vef_emp_tdadosd695 WHERE bdcodemp = NEW.bdcodemp AND bdcodigo < 999999  INTO vCodigo;
      NEW.bdcodigo = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodigo FROM vef_emp_tdadosd695 WHERE bdcodemp = NEW.bdcodemp AND bdcodigo = NEW.bdcodigo INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodigo) + 1), 1) FROM vef_emp_tdadosd695 WHERE bdcodemp = NEW.bdcodemp AND bdcodigo < 999999 INTO vCodigo;
           NEW.bdcodigo = vCodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VLAL_BASE_TEMP FOR VLAL_BASE_TEMP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT bdresult FROM maxsci('bdcodemp', 'bdcodemp', ' (bdstatusemp <> 1) ', 'tempresas') INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018
        NEW.bdcodemp = vcodigo;
     END
  ELSE
     BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
          BEGIN
            SELECT bdresult FROM maxsci('bdcodemp', 'bdcodemp', ' (bdstatusemp <> 1) ', 'tempresas') INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018
            NEW.bdcodemp = vcodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VLAL_BASE_TRIBUT FOR VLAL_BASE_LALUR_TRIBUTACAO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodtribut IS NULL) OR (NEW.bdcodtribut = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodtribut)+1),1) FROM vlal_base_lalur_tributacao INTO vcodigo;
       NEW.bdcodtribut = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodtribut FROM vlal_base_lalur_tributacao WHERE bdcodtribut = NEW.bdcodtribut INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodtribut)+1),1) FROM vlal_base_lalur_tributacao INTO vcodigo;
            NEW.bdcodtribut = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VLAL_EMPRESAS_TLLB FOR VLAL_EMPRESAS_TLLB
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodllb IS NULL) OR (NEW.bdcodllb = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodllb)+1), 1) FROM vlal_empresas_tllb WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.bdcodllb = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdcodllb FROM vlal_empresas_tllb WHERE (bdcodllb = NEW.bdcodllb) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodllb)+1), 1) FROM vlal_empresas_tllb WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdcodllb = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VLAL_EMPRESAS_TLLE FOR VLAL_EMPRESAS_TLLE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodlle IS NULL) OR (NEW.bdcodlle = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodlle)+1), 1) FROM vlal_empresas_tlle WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.bdcodlle = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdcodlle FROM vlal_empresas_tlle WHERE (bdcodlle = NEW.bdcodlle) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodlle)+1), 1) FROM vlal_empresas_tlle WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdcodlle = vNova_Chave;
         END
    END

  IF ((NEW.bdcodtip IS NULL) OR (NEW.bdcodtip = 0)) THEN
     NEW.bdcodtip = 1;
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VLAL_LALUR_PARTEA FOR VLAL_BASE_LALUR_PARTEA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodpartea IS NULL) OR (NEW.bdcodpartea = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodpartea)+1),1) FROM vlal_base_lalur_partea INTO vcodigo;
       NEW.bdcodpartea = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodpartea FROM vlal_base_lalur_partea WHERE bdcodpartea = NEW.bdcodpartea INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodpartea)+1),1) FROM vlal_base_lalur_partea INTO vcodigo;
            NEW.bdcodpartea = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VLAL_PLANOS_TLPA FOR VLAL_PLANOS_TLPA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;

  IF ((NEW.bdcodlpa IS NULL) OR (NEW.bdcodlpa = 0))  THEN
    BEGIN
      --NEW.bdcodtdep = GEN_ID(gen_departamentos_tdep, 1);
      SELECT COALESCE((MAX(bdcodlpa)+1), 1) FROM vlal_planos_tlpa WHERE bdcodpartea = NEW.bdcodpartea INTO vNova_Chave;
      NEW.bdcodlpa = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdcodlpa FROM vlal_planos_tlpa WHERE (bdcodlpa = NEW.bdcodlpa) AND (bdcodpartea = NEW.bdcodpartea) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodlpa)+1), 1) FROM vlal_planos_tlpa WHERE bdcodpartea = NEW.bdcodpartea INTO vNova_Chave;
           NEW.bdcodlpa = vNova_Chave;
           --NEW.bdcodtdep = GEN_ID(gen_departamentos_tdep, 1);
           /*exception ex_valor_text+NEW.bdcodtpcc;*/
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VLAL_PLANOS_TLPB FOR VLAL_PLANOS_TLPB
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vCodHist INTEGER;
BEGIN
  /* Trigger text */

  /*select emp.BDCODHIST from vlal_base_temp temp, tempresas emp
  where temp.bdcodparteb = new.bdcodparteb
  and   temp.bdcodemp = emp.bdcodemp
  into vCodHist;*/

  vcodigo = 0;
  IF ((NEW.bdcodlpb IS NULL) OR (NEW.bdcodlpb = 0))  THEN
    BEGIN
      --NEW.bdcodtdep = GEN_ID(gen_departamentos_tdep, 1);
      SELECT COALESCE((MAX(bdcodlpb)+1), 1) FROM vlal_planos_tlpb WHERE bdcodparteb = NEW.bdcodparteb INTO vNova_Chave;
      NEW.bdcodlpb = vNova_Chave;
      --new.bdcodhist = vcodhist;
    END
  ELSE
    BEGIN
       SELECT bdcodlpb FROM vlal_planos_tlpb WHERE (bdcodlpb = NEW.bdcodlpb) AND (bdcodparteb = NEW.bdcodparteb) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodlpb)+1), 1) FROM vlal_planos_tlpb WHERE bdcodparteb = NEW.bdcodparteb INTO vNova_Chave;
           NEW.bdcodlpb = vNova_Chave;
           --new.bdcodhist = vcodhist;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VLAL_PLANOS_TLTR FOR VLAL_PLANOS_TLTR
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodltr IS NULL) OR (NEW.bdcodltr = 0))  THEN
    BEGIN
      --NEW.bdcodtdep = GEN_ID(gen_departamentos_tdep, 1);
      SELECT COALESCE((MAX(bdcodltr)+1), 1) FROM vlal_planos_tltr WHERE bdcodtribut = NEW.bdcodtribut INTO vNova_Chave;
      NEW.bdcodltr = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdcodltr FROM vlal_planos_tltr WHERE (bdcodltr = NEW.bdcodltr) AND (bdcodtribut = NEW.bdcodtribut) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodltr)+1), 1) FROM vlal_planos_tltr WHERE bdcodtribut = NEW.bdcodtribut INTO vNova_Chave;
           NEW.bdcodltr = vNova_Chave;
           --NEW.bdcodtdep = GEN_ID(gen_departamentos_tdep, 1);
           /*exception ex_valor_text+NEW.bdcodtpcc;*/
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VRH_BASE_TRESPEMP FOR VRH_BASE_TRESPEMP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;
BEGIN
  IF ((NEW.BDCODRESP IS NULL) OR (NEW.BDCODRESP = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODRESP) + 1, 1) FROM vrh_base_trespemp
       WHERE BDCODEMP = NEW.BDCODEMP
       INTO :vNovoCod;

       NEW.BDCODRESP = :vNovoCod;
     END
END
^

CREATE OR ALTER trigger tr_bf_insert_vrh_emp_tcat for vrh_emp_tcat
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrh_emp_tcat WHERE (bdcodemp = NEW.bdcodemp)  AND (bdCodcol = NEW.bdcodcol) INTO vNova_Chave;
      NEW.bdchave = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM vrh_emp_tcat WHERE (bdchave = NEW.bdchave) AND (bdcodcol = NEW.bdcodcol) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrh_emp_tcat WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) INTO vNova_Chave;
           NEW.bdchave = vNova_Chave;
         END
    END

  if (NEW.BDCODSITGER = 0) then
     NEW.BDCODSITGER = NULL;

  NEW.bdrefcat = CAST((SUBSTRING(CAST(NEW.bddataemissao AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.bddataemissao AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
END^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VSUC_BASE_TEMP FOR VSUC_BASE_TEMP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodemp)+1),1) FROM vsuc_base_temp INTO vcodigo;
       NEW.bdcodemp = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodemp FROM vsuc_base_temp WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)+1),1) FROM vsuc_base_temp INTO vcodigo;
            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VSUC_BASE_TFORMULA FOR VSUC_BASE_TFORMULA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  SELECT bdCODPLAPADRAO FROM TPLANO_PADRAO tpla
  WHERE tpla.bdcodplapadrao = NEW.bdCODPLAPADRAO
  INTO :vcodigo;

  IF (vcodigo IS NULL) THEN
     NEW.bdcodplapadrao = NULL;

  vcodigo = 0;
  IF ((NEW.bdcodpfor IS NULL) OR (NEW.bdcodpfor = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodpfor)+1),1) FROM vsuc_base_tformula INTO vcodigo;
       NEW.bdcodpfor = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodpfor FROM vsuc_base_tformula WHERE bdcodpfor = NEW.bdcodpfor INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodpfor)+1),1) FROM vsuc_base_tformula INTO vcodigo;
           NEW.bdcodpfor = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VSUC_BASE_TFTFPO FOR VSUC_BASE_TFORMULA_TPFO
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;  
  DECLARE VARIABLE wNivel INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodfor IS NULL) OR (NEW.bdcodfor = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodfor)+1), 1) FROM vsuc_base_tformula_tpfo WHERE bdcodpfor = NEW.bdcodpfor INTO vNova_Chave;
      NEW.bdcodfor = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdcodfor FROM vsuc_base_tformula_tpfo WHERE (bdcodpfor = NEW.bdcodpfor) AND (bdcodfor = NEW.bdcodfor) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodfor)+1), 1) FROM vsuc_base_tformula_tpfo WHERE bdcodpfor = NEW.bdcodpfor INTO vNova_Chave;
           NEW.bdcodfor = vNova_Chave;
         END
    END
  --#138309 - Machado - 15/06/2020
  EXECUTE PROCEDURE CONTAR_CHAR(NEW.BDCLAFOR, '.') RETURNING_VALUES :wNivel;
  NEW.BDNIVELFOR = :wNivel+1;
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VSUC_BASE_TPLANILH FOR VSUC_BASE_TPLANILHAS
ACTIVE BEFORE INSERT POSITION 0 
AS
   DECLARE VARIABLE vCodigo INTEGER;
BEGIN
   vCodigo = 0;
   IF ((NEW.bdCODPLANILHA IS NULL) OR (NEW.bdCODPLANILHA = 0)) THEN
      BEGIN
         SELECT COALESCE((MAX(bdcodplanilha)+1),1) FROM vsuc_base_tplanilhas INTO vcodigo;
         NEW.bdCODPLANILHA = vcodigo;
      END
   ELSE
      BEGIN
         SELECT bdcodplanilha FROM vsuc_base_tplanilhas WHERE bdcodplanilha = NEW.bdcodplanilha INTO vcodigo;

         IF (vcodigo > 0) THEN
            BEGIN
               SELECT COALESCE((MAX(bdcodplanilha)+1),1) FROM vsuc_base_tplanilhas INTO vcodigo;
               NEW.bdCODPLANILHA = vcodigo;
            END
      END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VSUC_EMPRESAS_TCON FOR VSUC_EMPRESAS_TCON
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodcon IS NULL) OR (NEW.bdcodcon = 0)) THEN
    --NEW.bdcodcon = GEN_ID(gen_vsuc_empresas_tcon, 1);
    BEGIN
      SELECT COALESCE((MAX(bdcodcon)+1), 1) FROM vsuc_empresas_tcon WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.bdcodcon = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdcodcon FROM vsuc_empresas_tcon WHERE (bdcodcon = NEW.bdcodcon) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodcon)+1), 1) FROM vsuc_empresas_tcon WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdcodcon = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VSUC_EMPRESAS_TCTT FOR VSUC_EMPRESAS_TCTT
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodtctt IS NULL) OR (NEW.bdcodtctt = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodtctt)+1), 1) FROM vsuc_empresas_tctt WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.bdcodtctt = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdcodtctt FROM vsuc_empresas_tctt WHERE (bdcodtctt = NEW.bdcodtctt) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodtctt)+1), 1) FROM vsuc_empresas_tctt WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdcodtctt = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VSUC_EMPRESAS_TENC FOR VSUC_EMPRESAS_TENCEXE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  --alt:9720 - Comentado isso pois não permitia gravar o código do usuário. Não sabemos porque fazia isso. Pedro
  --new.bdcodusu = null;

  IF ((NEW.bdchavezer IS NULL) OR (NEW.bdchavezer = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchavezer)+1), 1) FROM vsuc_empresas_tencexe INTO vNova_Chave;
      NEW.bdchavezer = vNova_Chave;
    END
END
^

CREATE OR ALTER trigger tr_bf_insert_vsuc_empresas_tlan for vsuc_empresas_tlan
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
--  declare variable vNova_Chave integer;
--  declare variable vusuario varchar(20);
  DECLARE VARIABLE vCodUsu INTEGER;
  DECLARE VARIABLE VRECONTABILIZANDO dm_boolean;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  vcodigo = 0;

  /* Almir 19/06/2012 */
  /* Não pode ser lançado nenhum lançamento sem a chave pois a chave não pode ser gerada uma pelo banco e outra pelo servidor pq senão da erro */
  --  if ((NEW.bdchave is null) or (NEW.bdchave = 0)) then
  --      exception EX_GETCHAVELAN;

  -- Carlos Mello(05/10/2011) - Caso seja "Importação TXT" ou "Importação Extrato Bancário" não precisa fazer os
  -- tratamentos porque o sistema já está garantindo as informações passada, desta forma torna as importações mais rápidas.
  -- Fabiano 03/07/2013: Não pode gerar nova chave aqui. Tem que usar o servidor de aplicação
  /*
    if ((NEW.BDTIPOLAN <> 2) and (NEW.BDTIPOLAN <> 21) and (NEW.BDTIPOLAN <> 100) and (NEW.BDTIPOLAN <> 200)) then
    begin
      if ((NEW.bdchave is null) or (NEW.bdchave = 0)) then
        begin
          select bdresult+1 from maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||new.bdcodemp, 'vsuc_empresas_tlan') into vNova_Chave;
--          select coalesce((max(bdchave)+1), 1) from vsuc_empresas_tlan where bdcodemp = new.bdcodemp into vNova_Chave;
          NEW.bdchave = vNova_Chave;
        end
      else
        begin
          -- Fabiano - Na importacao do Visual Sucessor ja mando a chave, estou sozinho na importacao ninguem mandara mais nada.
          if (NEW.BDTIPOLAN <> 300) then
            begin
               select bdchave from vsuc_empresas_tlan where (bdchave = NEW.bdchave) and (bdcodemp = NEW.bdcodemp) into vcodigo;

               if (vcodigo > 0) then
                 begin
                   select bdresult+1 from maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||new.bdcodemp, 'vsuc_empresas_tlan') into vNova_Chave;
--                   select coalesce((max(bdchave)+1), 1) from vsuc_empresas_tlan where bdcodemp = new.bdcodemp into vNova_Chave;
                   NEW.bdchave = vNova_Chave;
                 end
            end
        end
    end */

  SELECT CAST(BDAAAAMM AS INTEGER) FROM AAAAMM(NEW.bddata) INTO NEW.bdreferencia;
  -- GRAVA OS CAMPOS AUTOMATICO --

--  if ((new.bdcodusu is null) or (new.bdcodusu = 0)) then
--  begin
--    select bdcodusu from vw_variaveis_sessao_banco into vcodigo;
--    new.bdcodusu = vcodigo;
--  end

  -- Fabiano - Na importacao do Visual Sucessor ja estou trazendo este valor
  IF (NEW.bddatalan IS NULL) THEN
    NEW.bddatalan = CURRENT_DATE;

  -- Fabiano - Na importacao do Visual Sucessor ja estou trazendo este valor
  IF (NEW.bdhoralan IS NULL) THEN
    NEW.bdhoralan = CURRENT_TIME;

  IF ((NEW.BDTIPOLAN IS NULL) OR (NEW.BDTIPOLAN = 0)) THEN
     NEW.BDTIPOLAN = 1;

  --Carlos Mello(12/06/2013) - Alt: 5837. Quando for lançamento de online deve setar o BDTIPOLANCFILIAL = 0(Nenhum) e o BDCONTABILIZACAO = 0(Ambos)
  IF ((NEW.BDTIPOLAN = 100) OR--online
      (NEW.BDTIPOLAN = 200) OR--online
      (NEW.BDTIPOLAN = 400) OR--online com lalur - gilberto - 04/07/2014
      (NEW.BDTIPOLAN = 10) OR--zeramento
      (NEW.bdtipolan = 2) OR--importação TXT
      (NEW.bdtipolan = 21) OR--importação extrato bancário
      (NEW.bdtipolan = 9) OR--lançamento de planilha
      (NEW.bdtipolan = 3000)) THEN --online do financeiro
    BEGIN
      IF (NEW.bdtipolancfilial IS NULL) THEN
        NEW.bdtipolancfilial = 0;
      IF (NEW.bdcontabilizacao IS NULL) THEN
        NEW.bdcontabilizacao = 0;
    END

  IF (NEW.BDTIPOLAN = 26) THEN
    NEW.bdcontabilizacao = NEW.bdcontabilizacao + 1; --#alt:15359 - No combo do valor presente so tem fiscal e societária, por isso soma. 0 - ambas, 1 - fiscal, 2 - societária. Ana - 07/10/2016

  -- Gilberto - 21/05/2012 - rotina responsável por vetar os lançamentos bloqueados para on-line
  IF ((NEW.bdtipolan <> 2) AND (NEW.bdtipolan <> 300)) THEN
     BEGIN
  -- sol:5822 - Elizeu - 06-04-2013 - comentado o codigo abaixo porque, estava pegando o código do usuário do lançamento e não o usuário logado
  --isso ocasionava problema quando o usuário que fez o lançamento estava bloqueado e o que estava alterando não estava ex:
  -- usuário 6 fez o lançamento sem permissão
  -- usuário 11 está alterando com permissão
--       if ((new.bdcodusu is not null) and (new.bdcodusu <> 0)) then
--          vCodUsu = new.bdcodusu;
--       else
          SELECT FIRST 1 bdcodusu FROM sp_get_usuario INTO :vCodUsu;

       /* sol.: #10892 Jean 19/01/2015: para verificar se esta executando processo de recontabilização */ 
       SELECT TRIM(UPPER(COALESCE(RDB$GET_CONTEXT('USER_SESSION', 'W_RECONTABILIZA'), '')))
       FROM RDB$DATABASE
       INTO :VRECONTABILIZANDO;
     
--       SELECT COUNT(*) Denicio 05/07/2016: Não precisa fazer o COUNT da tabela. Pode apenas ver se tem algum registro. Dessa forma é mais rápido.
       vcodigo = NULL;
       SELECT FIRST 1 BDCODUSU
       FROM tbloqlan_usuario tblu
       INNER JOIN tbloqlan_empresa tble ON (tble.bdcodemp = tblu.bdcodemp AND tble.bdcodblq = tblu.bdcodblq AND tble.bdcodble = tblu.bdcodble)
       INNER JOIN tbloqlan tbloq ON (tbloq.bdcodblq = tble.bdcodblq)
       WHERE tbloq.bdcodsis = 4
       AND UPPER(tbloq.bdrecurso) = UPPER('frlancamento')
       AND ((bddatainicial >= NEW.bddata AND (bddatafinal <= NEW.bddata OR bddatafinal IS NULL))
       OR (bddatainicial <= NEW.bddata AND ((bddatafinal BETWEEN NEW.bddata AND NEW.bddata) OR bddatafinal IS NULL))
       OR (bddatainicial <= NEW.bddata AND (bddatafinal >= NEW.bddata OR bddatafinal IS NULL)) )
       AND tble.bdcodemp = NEW.bdcodemp
       AND tblu.bdcodusu = :vcodusu
       INTO :vcodigo;

       /* sol.: #10892 Jean 19/01/2015: Lançar exceção somente se não estiver recontabilizando */
       IF ((vcodigo IS NOT NULL) AND (vcodigo > 0) AND (VRECONTABILIZANDO <> 'TRUE')) THEN
          EXCEPTION ex_bloqlan;
     END

     --#alt:13456 - Atribui ao novo campo o valor de 0 se este não possui nenhum valor. Ana - 28/10/2016
     IF (NEW.bdtipoconc IS NULL) THEN
        NEW.bdtipoconc = 0;
     --#alt:13456. fim

  --#alt:131955 - Adicionado tratamentos para evitar que estes campos sejam inseridos nulos. Ana - 17/01/2020
  IF (((NEW.bddebito = 0) or (NEW.bddebito is null)) AND ((NEW.bdcredito = 0) or (NEW.bdcredito is null))) THEN
    EXCEPTION EX_LAN_DEBCRE_VAZIO;

  --#alt:152665 - Carlos Machado - 02/07/2021 - Alterado para <=, estava vindo online negativa
  IF ((NEW.bdvalor <= 0) or (NEW.bdvalor is null)) THEN
    EXCEPTION EX_LAN_VALORZERADO;

  IF ((((NEW.BDCODTPHI = 0) or (NEW.BDCODTPHI is null)) AND ((NEW.bdcompl is null) or (trim(NEW.bdcompl) = ''))) and (NEW.bdtipolan IN (15,47,100,200,400,3000))) THEN
    EXCEPTION EX_LAN_COMPL_VAZIO;
  --#alt:131955. fim

  
  --#127667.
  NEW.bdtipolanorig = NEW.bdtipolan;
  end
END^

CREATE OR ALTER trigger vsuc_empresas_tlan_ai0 for vsuc_empresas_tlan
active after insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    if (new.bdchaveprocevolucobra is not null) then
      INSERT INTO TOL_VSUC_EMPRESAS_TPROCEVOLUCOBRA(BDCODEMP, BDCHAVE, BDCHAVEPROCEVOLUCOBRA) VALUES (NEW.BDCODEMP, NEW.BDCHAVE, NEW.BDCHAVEPROCEVOLUCOBRA);
    if (new.bdcodimpativa is not null) then
      INSERT INTO TOL_VATI_EMPRESAS_IMP_ATIVACONTAB(BDCODEMP, BDCHAVE, BDCODIMPATIVA) VALUES (NEW.BDCODEMP, NEW.BDCHAVE, NEW.BDCODIMPATIVA);
    if (new.BDCHAVETRANSFCUSTOINCORP is not null) then
      INSERT INTO TOL_VSUC_EMPRESAS_TTRANSFCUSTOINCOR(BDCODEMP, BDCHAVE, BDCHAVETRANSFCUSTOINCORP) VALUES (NEW.BDCODEMP, NEW.BDCHAVE, NEW.BDCHAVETRANSFCUSTOINCORP);
    if (new.BDCODVLRPRES is not null) then
      INSERT INTO TOL_VSUC_EMPRESAS_VALORPRESENTE(BDCODEMP, BDCHAVE, BDCODVLRPRES) VALUES (NEW.BDCODEMP, NEW.BDCHAVE, NEW.BDCODVLRPRES);
    if (new.bdchavetransfbem is not null) then
      INSERT INTO TOL_EMPRESAS_TBEM_TRANSFERENCIA(BDCODEMP, BDCHAVE, bdcodtransf) VALUES (NEW.BDCODEMP, NEW.BDCHAVE, NEW.bdchavetransfbem);
    if (new.BDCODTRANS_CONTA is not null) then
      INSERT INTO TOL_EMPRESAS_TBEM_TRANSF_CONTA(BDCODEMP, BDCHAVE, BDCODTRANS_CONTA) VALUES (NEW.BDCODEMP, NEW.BDCHAVE, NEW.BDCODTRANS_CONTA);
  end
end^

CREATE OR ALTER trigger vsuc_empresas_tlan_biu1 for vsuc_empresas_tlan
active before insert or update position 1
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((New.BDCODEMP is not null) and (NEW.BDCODEMP is distinct from OLD.BDCODEMP) and (not exists(SELECT FIRST 1 BDCODEMP FROM TEMPRESAS WHERE BDCODEMP = NEW.BDCODEMP))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VSUC_EMPRESAS_TLAN', NEW.BDCODEMP, 'BDCODEMP', 'TEMPRESAS');

  if ((New.bdfilial is not null) and (NEW.BDFILIAL is distinct from OLD.BDFILIAL) and (not exists(SELECT FIRST 1 BDCODEMP FROM TEMPRESAS WHERE BDCODEMP = NEW.BDFILIAL))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VSUC_EMPRESAS_TLAN', NEW.BDFILIAL, 'BDFILIAL', 'TEMPRESAS');

  if ((New.bdtipolan is not null) and (NEW.BDTIPOLAN is distinct from OLD.BDTIPOLAN) and (not exists(SELECT FIRST 1 BDCODTIPO FROM TIPOS_LANCAMENTOS_PADRAO WHERE BDCODTIPO = NEW.BDTIPOLAN))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VSUC_EMPRESAS_TLAN', NEW.BDTIPOLAN, 'BDTIPOLAN', 'TIPOS_LANCAMENTOS_PADRAO');

  if ((New.bdtipolanorig is not null) and (NEW.BDTIPOLANORIG is distinct from OLD.BDTIPOLANORIG) and (not exists(SELECT FIRST 1 BDCODTIPO FROM TIPOS_LANCAMENTOS_PADRAO WHERE BDCODTIPO = NEW.BDTIPOLANORIG))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VSUC_EMPRESAS_TLAN', NEW.BDTIPOLANORIG, 'BDTIPOLANORIG', 'TIPOS_LANCAMENTOS_PADRAO');

  if ((New.bddebito is not null and new.bdcodplapadrao is not null)
  and (NEW.bddebito is distinct from OLD.bddebito or NEW.bdcodplapadrao is distinct from OLD.bdcodplapadrao)
  and (not exists(SELECT FIRST 1 BDCODTPLA FROM planos_tpla WHERE BDCODPLAPADRAO = NEW.bdcodplapadrao and BDCODTPLA = NEW.bddebito))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VSUC_EMPRESAS_TLAN', NEW.bddebito, 'BDDEBITO', 'PLANOS_TPLA');

  if ((New.bdcredito is not null and new.bdcodplapadrao is not null)
  and (NEW.bdcredito is distinct from OLD.bdcredito or NEW.bdcodplapadrao is distinct from OLD.bdcodplapadrao)
  and (not exists(SELECT FIRST 1 BDCODTPLA FROM planos_tpla WHERE BDCODPLAPADRAO = NEW.bdcodplapadrao and BDCODTPLA = NEW.bdcredito))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VSUC_EMPRESAS_TLAN', NEW.bdcredito, 'BDCREDITO', 'PLANOS_TPLA');

  if ((New.bdcodtipofol is not null) and (NEW.bdcodtipofol is distinct from OLD.bdcodtipofol) and (not exists(SELECT FIRST 1 BDCODFOL FROM VRH_TIPOFOL_VSUC WHERE BDCODFOL = NEW.bdcodtipofol))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VSUC_EMPRESAS_TLAN', NEW.bdcodtipofol, 'BDCODTIPOFOL', 'VRH_TIPOFOL_VSUC');

  if ((new.bdcodusualteracao is not null) and (new.bdcodusualteracao is distinct from old.bdcodusualteracao) and (not exists(select first 1 BDCODUSU FROM TUSUARIO WHERE BDCODUSU = NEW.bdcodusualteracao))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VSUC_EMPRESAS_TLAN', NEW.bdcodusualteracao, 'BDCODUSUALTERACAO', 'TUSUARIO');
  end
end^

CREATE OR ALTER trigger tipos_lancamentos_padrao_bd0 for tipos_lancamentos_padrao
active before delete position 0
AS
BEGIN
  IF (EXISTS(SELECT FIRST 1 LAN.BDCODEMP
             FROM VSUC_EMPRESAS_TLAN LAN
             WHERE OLD.BDCODTIPO IN (LAN.BDTIPOLAN, LAN.BDTIPOLANORIG))) THEN
    EXCEPTION EX_DELETE 'VSUC_EMPRESAS_TLAN';

  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVSAI SAI
             WHERE (SAI.BDCODTIPO = OLD.BDCODTIPO) OR
                   (SAI.BDTIPOLANINCLU = OLD.BDCODTIPO))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVSAI';
  if (EXISTS(SELECT FIRST 1 BDCODTIPO
             FROM VEF_EMP_TC195SAI SAI
             WHERE (SAI.BDCODTIPO = OLD.BDCODTIPO))) then
    EXCEPTION ex_delete 'VEF_EMP_TC195SAI';

  if (OLD.bdqtdarquivado > 0) then
    EXCEPTION ex_delete 'TARQUIVAMENTO';
END^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAI_BIU1 FOR VEF_EMP_TMOVSAI
ACTIVE BEFORE INSERT OR UPDATE POSITION 1
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((NEW.BDMODELO IS NOT NULL) AND (NEW.BDMODELO is distinct from OLD.BDMODELO) and (not exists(SELECT FIRST 1 A.BDMODELO FROM VEF_BASE_TTABMODELOLAN A WHERE A.BDMODELO = NEW.BDMODELO))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSAI', NEW.BDMODELO, 'BDMODELO', 'VEF_BASE_TTABMODELOLAN');
  if ((NEW.BDCODTIPO IS NOT NULL) AND (NEW.BDCODTIPO is distinct from OLD.BDCODTIPO) and (not exists(SELECT FIRST 1 A.BDCODTIPO FROM TIPOS_LANCAMENTOS_PADRAO A WHERE A.BDCODTIPO = NEW.BDCODTIPO))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSAI', NEW.BDCODTIPO, 'BDCODTIPO', 'TIPOS_LANCAMENTOS_PADRAO');
  if ((NEW.BDTIPOLANINCLU IS NOT NULL) AND (NEW.BDTIPOLANINCLU is distinct from OLD.BDTIPOLANINCLU) and (not exists(SELECT FIRST 1 A.BDCODTIPO FROM TIPOS_LANCAMENTOS_PADRAO A WHERE A.BDCODTIPO = NEW.BDTIPOLANINCLU))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSAI', NEW.BDTIPOLANINCLU, 'BDCODTIPO', 'TIPOS_LANCAMENTOS_PADRAO');
  if ((NEW.BDCODUSU IS NOT NULL) AND (NEW.BDCODUSU is distinct from OLD.BDCODUSU) and (not exists(SELECT FIRST 1 A.BDCODUSU FROM TUSUARIO A WHERE A.BDCODUSU = NEW.BDCODUSU))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSAI', NEW.BDCODUSU, 'BDMODELO', 'TUSUARIO');
  if ((NEW.BDCODUSUINCLU IS NOT NULL) AND (NEW.BDCODUSUINCLU is distinct from OLD.BDCODUSUINCLU) and (not exists(SELECT FIRST 1 A.BDCODUSU FROM TUSUARIO A WHERE A.BDCODUSU = NEW.BDCODUSUINCLU))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSAI', NEW.BDCODUSUINCLU, 'BDCODUSU', 'TUSUARIO');
  if ((NEW.BDCODCID IS NOT NULL) AND (NEW.BDCODCID is distinct from OLD.BDCODCID) and (not exists(SELECT FIRST 1 A.BDCODCID FROM TCIDADE A WHERE A.BDCODCID = NEW.BDCODCID))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSAI', NEW.BDCODCID, 'BDCODCID', 'TCIDADE');
  if ((NEW.BDCODSTATUSLAN IS NOT NULL) AND (NEW.BDCODSTATUSLAN is distinct from OLD.BDCODSTATUSLAN) and (not exists(SELECT FIRST 1 A.BDCODSTATUSLAN FROM VEF_BASE_STATUSLANC A WHERE A.BDCODSTATUSLAN = NEW.BDCODSTATUSLAN))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSAI', NEW.BDCODSTATUSLAN, 'BDCODSTATUSLAN', 'VEF_BASE_STATUSLANC');
  if ((NEW.BDCODEMP IS NOT NULL) AND (NEW.BDCODEMP is distinct from OLD.BDCODEMP) and (not exists(SELECT FIRST 1 A.BDCODEMP FROM TEMPRESAS A WHERE A.BDCODEMP = NEW.BDCODEMP))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSAI', NEW.BDCODEMP, 'BDCODEMP', 'TEMPRESAS');
  if ((NEW.BDCODSITNF IS NOT NULL) AND (NEW.BDCODSITNF is distinct from OLD.BDCODSITNF) and (not exists(SELECT FIRST 1 A.BDCODSITNF FROM VEF_BASE_TTABSITNF A WHERE A.BDCODSITNF = NEW.BDCODSITNF))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSAI', NEW.BDCODSITNF, 'BDCODSITNF', 'VEF_BASE_TTABSITNF');
  if ((NEW.BDCODMOEDAS IS NOT NULL) AND (NEW.BDCODMOEDAS is distinct from OLD.BDCODMOEDAS) and (not exists(SELECT FIRST 1 A.BDCODMOEDAS FROM TMOEDAS A WHERE A.BDCODMOEDAS = NEW.BDCODMOEDAS))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSAI', NEW.BDCODMOEDAS, 'BDCODMOEDAS', 'TMOEDAS');
  if ((NEW.BDCODTER IS NOT NULL) AND (NEW.BDCODTER is distinct from OLD.BDCODTER) and (not exists(SELECT FIRST 1 A.BDCODTER FROM TTERCEIRO A WHERE A.BDCODTER = NEW.BDCODTER))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSAI', NEW.BDCODTER, 'BDCODTER', 'TTERCEIRO');
  end
end^

CREATE or ALTER  trigger VEF_EMP_TMOVPROENT_ad0 for VEF_EMP_TMOVPROENT
active after delete position 0
AS
begin
  DELETE FROM VEF_EMP_TAUDIMENDES A WHERE A.bdcodemp = OLD.BDCODEMP AND A.BDCHAVE = OLD.BDCHAVE AND A.BDORDEM = OLD.BDORDEM AND A.BDORDEMPRO = OLD.BDORDEMPRO AND A.BDMOVIMENTO = 0;
end
^

CREATE or ALTER trigger VEF_EMP_TMOVPROSAI_ad0 for VEF_EMP_TMOVPROSAI
active after delete position 0
AS
begin                                                                                                                                                            
  DELETE FROM VEF_EMP_TAUDIMENDES A WHERE A.bdcodemp = OLD.BDCODEMP AND A.BDCHAVE = OLD.BDCHAVE AND A.BDORDEM = OLD.BDORDEM AND A.BDORDEMPRO = OLD.BDORDEMPRO AND A.BDMOVIMENTO = 1;
end
^

CREATE OR ALTER trigger vef_emp_tmovprosai_aiud0 for vef_emp_tmovprosai
active after insert or update or delete position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    EXECUTE PROCEDURE FK_MANUAL_INSERT('PLANOS_TPLA', 'VEF_EMP_TMOVPROSAI', OLD.BDCODPLAPADRAO, OLD.BDCODTPLA, NEW.BDCODPLAPADRAO, NEW.BDCODTPLA, 1);
  end
END
^

CREATE or ALTER trigger VEF_EMP_TREDZC425_ad0 for VEF_EMP_TREDZC425
active after delete position 0
AS
begin                                                                                              
  DELETE FROM VEF_EMP_TAUDIMENDES A WHERE A.bdcodemp = OLD.BDCODEMP AND A.BDCHAVE = OLD.BDCHAVE AND A.BDORDEM = OLD.BDORDEMTOT AND A.BDORDEMPRO = OLD.BDORDEMC425 AND A.BDMOVIMENTO = 2;
end
^

CREATE or ALTER trigger VEF_EMP_TREDZC425ALIQ_ad0 for VEF_EMP_TREDZC425ALIQ
active after delete position 0
AS
begin                                                                                
  DELETE FROM VEF_EMP_TAUDIMENDES A WHERE A.bdcodemp = OLD.BDCODEMP AND A.BDCHAVE = OLD.BDCHAVE AND A.BDORDEM = OLD.BDORDEMICMS AND A.BDORDEMPRO = OLD.BDORDEMC425 AND A.BDMOVIMENTO = 2;
end
^

CREATE or ALTER trigger VEF_EMP_TREDZ60I_ad0 for VEF_EMP_TREDZ60I
active after delete position 0
AS
begin                                                                                                                                           
  DELETE FROM VEF_EMP_TAUDIMENDES A WHERE A.bdcodemp = OLD.BDCODEMP AND A.BDCHAVE = OLD.BDCHAVE /*AND A.BDORDEM = OLD.BDORDEM*/ AND A.BDORDEMPRO = OLD.BDORDEM60I AND A.BDMOVIMENTO = 2;
end
^

CREATE or ALTER trigger VEF_EMP_TITEMDOCECF_ad0 for VEF_EMP_TITEMDOCECF
active after delete position 0
AS
begin      
  DELETE FROM VEF_EMP_TAUDIMENDES A WHERE A.bdcodemp = OLD.BDCODEMP AND A.BDCHAVE = OLD.BDCHAVE AND A.BDORDEM = OLD.BDORDEMDOCECF AND A.BDORDEMPRO = OLD.BDORDEMITEM AND A.BDMOVIMENTO = 2;
end
^

CREATE or ALTER trigger vef_emp_tmovprosai_biu_comprefnull for vef_emp_tmovprosai
active before insert or update position 0
AS
begin
  IF (NEW.BDAJUSTECOMP_REF = 0) THEN
    NEW.BDAJUSTECOMP_REF = NULL;
end
^

CREATE OR ALTER trigger vef_emp_tmovprosai_biu1 for vef_emp_tmovprosai
active before insert or update position 1
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    if ((NEW.BDCODFATCON IS NOT NULL) AND ((NEW.BDCODFATCON is distinct from OLD.BDCODFATCON) or (NEW.BDCODPROD is distinct from OLD.BDCODPROD) or (NEW.BDCODEMP is distinct from OLD.BDCODEMP)) and (not exists(SELECT FIRST 1 A.BDCODFATCON FROM TFATCONV A WHERE A.BDCODPROD = NEW.BDCODPROD AND A.BDCODEMP = NEW.BDCODEMP AND A.BDCODFATCON = NEW.BDCODFATCON))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVPROSAI', NEW.BDCODFATCON, 'BDCODFATCON', 'TFATCONV');
    if ((NEW.BDCODCSTIPI IS NOT NULL) AND (NEW.BDCODCSTIPI is distinct from OLD.BDCODCSTIPI) and (not exists(SELECT FIRST 1 A.BDCODCSTIPI FROM VEF_BASE_TTABCSTIPI A WHERE A.BDCODCSTIPI = NEW.BDCODCSTIPI))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVPROSAI', NEW.BDCODCSTIPI, 'BDCODCSTIPI', 'VEF_BASE_TTABCSTIPI');
    if ((NEW.BDCODCSTPIS IS NOT NULL) AND (NEW.BDCODCSTPIS is distinct from OLD.BDCODCSTPIS) and (not exists(SELECT FIRST 1 A.BDCODCSTPIS FROM VEF_BASE_TTABCSTPIS A WHERE A.BDCODCSTPIS = NEW.BDCODCSTPIS))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVPROSAI', NEW.BDCODCSTPIS, 'BDCODCSTPIS', 'VEF_BASE_TTABCSTPIS');
    if ((NEW.BDCODCSTCOF IS NOT NULL) AND (NEW.BDCODCSTCOF is distinct from OLD.BDCODCSTCOF) and (not exists(SELECT FIRST 1 A.BDCODCSTCOF FROM VEF_BASE_TTABCSTCOF A WHERE A.BDCODCSTCOF = NEW.BDCODCSTCOF))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVPROSAI', NEW.BDCODCSTCOF, 'BDCODCSTCOF', 'VEF_BASE_TTABCSTCOF');
    if ((NEW.BDCODTPLA IS NOT NULL) AND ((NEW.BDCODPLAPADRAO is distinct from OLD.BDCODPLAPADRAO) or (NEW.BDCODTPLA is distinct from OLD.BDCODTPLA)) and (not exists(SELECT FIRST 1 A.BDCODTPLA FROM PLANOS_TPLA A WHERE A.BDCODPLAPADRAO = NEW.BDCODPLAPADRAO AND A.BDCODTPLA = NEW.BDCODTPLA))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVPROSAI', NEW.BDCODTPLA, 'BDCODTPLA', 'PLANOS_TPLA');
    if ((NEW.BDCODNATREC IS NOT NULL) AND (NEW.BDCODNATREC is distinct from OLD.BDCODNATREC) and (not exists(SELECT FIRST 1 A.BDCODNATREC FROM VEF_BASE_TTAB_NATREC A WHERE A.BDCODNATREC = NEW.BDCODNATREC))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVPROSAI', NEW.BDCODNATREC, 'BDCODNATREC', 'VEF_BASE_TTAB_NATREC');
    if ((NEW.BDCODCSTICMS IS NOT NULL) AND (NEW.BDCODCSTICMS is distinct from OLD.BDCODCSTICMS) and (not exists(SELECT FIRST 1 A.BDCODCSTICMS FROM VEF_BASE_TTABCSTICMS A WHERE A.BDCODCSTICMS = NEW.BDCODCSTICMS))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVPROSAI', NEW.BDCODCSTICMS, 'BDCODCSTICMS', 'VEF_BASE_TTABCSTICMS');
    if ((NEW.BDCBNEF IS NOT NULL) AND (NEW.BDCBNEF is distinct from OLD.BDCBNEF) and (not exists(SELECT FIRST 1 A.BDORDEM52 FROM VEF_BASE_TTABINFAD52 A WHERE A.BDORDEM52 = NEW.BDCBNEF))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVPROSAI', NEW.BDCBNEF, 'BDORDEM52', 'VEF_BASE_TTABINFAD52');
    if ((NEW.BDCODCTA IS NOT NULL) AND (NEW.BDCODCTA is distinct from OLD.BDCODCTA) and (not exists(SELECT FIRST 1 A.BDCODCTA FROM VEF_BASE_TTABCTA A WHERE A.BDCODCTA = NEW.BDCODCTA))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVPROSAI', NEW.BDCODCTA, 'BDCODCTA', 'VEF_BASE_TTABCTA');
    if ((NEW.BDCODPROD IS NOT NULL) AND (NEW.BDCODPROD is distinct from OLD.BDCODPROD) and (not exists(SELECT FIRST 1 A.BDCODPROD FROM TCADPRO A WHERE A.BDCODPROD = NEW.BDCODPROD))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVPROSAI', NEW.BDCODPROD, 'BDCODPROD', 'TCADPRO');
  end
end^

CREATE OR ALTER TRIGGER VEF_BASE_TPLANOACOESTROCA_BIU0 FOR VEF_BASE_TPLANOACOESTROCA
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  if ((NEW.BDORDEMTAB6_TPSER IS NOT NULL) AND (NEW.BDORDEMTAB6_TPSER is distinct from OLD.BDORDEMTAB6_TPSER) and (not exists(SELECT FIRST 1 A.BDORDEMTAB6_TPSER FROM VEF_BASE_TTAB6_TIPOSER A WHERE A.BDORDEMTAB6_TPSER = NEW.BDORDEMTAB6_TPSER))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_BASE_TPLANOACOESTROCA', NEW.BDORDEMTAB6_TPSER, 'BDORDEMTAB6_TPSER', 'VEF_BASE_TTAB6_TIPOSER');
end
^

CREATE OR ALTER TRIGGER VEF_BASE_TTAB6_TIPOSER_BD0 FOR VEF_BASE_TTAB6_TIPOSER
ACTIVE BEFORE DELETE POSITION 0
AS
begin
  if (EXISTS(SELECT FIRST 1 A.BDORDEMTAB6_TPSER
             FROM VEF_BASE_TPLANOACOESTROCA A
             WHERE (A.BDORDEMTAB6_TPSER = OLD.BDORDEMTAB6_TPSER))) then
    EXCEPTION ex_delete 'VEF_BASE_TPLANOACOESTROCA';
end
^

CREATE OR ALTER trigger vef_emp_tmovsaiitens_biu1 for vef_emp_tmovsaiitens
active before insert or update position 1
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((NEW.BDCODOBS IS NOT NULL) AND (NEW.BDCODOBS is distinct from OLD.BDCODOBS) and (not exists(SELECT FIRST 1 A.BDCODOBS FROM VEF_BASE_TOBSERVACAO A WHERE A.BDCODOBS = NEW.BDCODOBS))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSAIITENS', NEW.BDCODOBS, 'BDCODOBS', 'VEF_BASE_TOBSERVACAO');
  if ((NEW.BDCODCID IS NOT NULL) AND (NEW.BDCODCID is distinct from OLD.BDCODCID) and (not exists(SELECT FIRST 1 A.BDCODCID FROM TCIDADE A WHERE A.BDCODCID = NEW.BDCODCID))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSAIITENS', NEW.BDCODCID, 'BDCODCID', 'TCIDADE');
  if ((NEW.BDCODCSTICMS IS NOT NULL) AND (NEW.BDCODCSTICMS is distinct from OLD.BDCODCSTICMS) and (not exists(SELECT FIRST 1 A.BDCODCSTICMS FROM VEF_BASE_TTABCSTICMS A WHERE A.BDCODCSTICMS = NEW.BDCODCSTICMS))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSAIITENS', NEW.BDCODCSTICMS, 'BDCODCSTICMS', 'VEF_BASE_TTABMODELOLAN');
  if ((NEW.BDCODNAT IS NOT NULL) AND (NEW.BDCODNAT is distinct from OLD.BDCODNAT) and (not exists(SELECT FIRST 1 A.BDCODNAT FROM VEF_BASE_TNATOP A WHERE A.BDCODNAT = NEW.BDCODNAT))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSAIITENS', NEW.BDCODNAT, 'BDCODNAT', 'VEF_BASE_TNATOP');

  -- Verifica se os campos não são nulos e se foram alterados
IF (NEW.BDCODEMP IS NOT NULL AND NEW.BDCHAVE IS NOT NULL AND (NEW.BDCODEMP IS DISTINCT FROM OLD.BDCODEMP OR NEW.BDCHAVE IS DISTINCT FROM OLD.BDCHAVE)) THEN
  BEGIN
    -- Verifica se os novos valores existem na tabela VEF_EMP_TMOVSAI
    IF (NOT EXISTS (
      SELECT 1
      FROM VEF_EMP_TMOVSAI A
      WHERE A.BDCODEMP = NEW.BDCODEMP
        AND A.BDCHAVE = NEW.BDCHAVE
    )) THEN
    BEGIN
      -- Lança exceção se não existir
      EXCEPTION EX_CHAVE_ESTRANGEIRA USING (
        'VEF_EMP_TMOVSAIITENS',
        NEW.BDCODEMP || ',' || NEW.BDCHAVE,
        'BDCODEMP,BDCHAVE',
        'VEF_EMP_TMOVSAI'
      );
    END
  END

  -- Verifica se os campos não são nulos e se foram alterados
IF (NEW.BDCODEMP IS NOT NULL AND NEW.BDREFSOC IS NOT NULL AND NEW.BDCODSCP IS NOT NULL AND (NEW.BDCODEMP IS DISTINCT FROM OLD.BDCODEMP OR NEW.BDREFSOC IS DISTINCT FROM OLD.BDREFSOC OR NEW.BDCODSCP IS DISTINCT FROM OLD.BDCODSCP)) THEN
  BEGIN
    -- Verifica se os novos valores existem na tabela TEMPRESAS_SCP
    IF (NOT EXISTS (
      SELECT 1
      FROM TEMPRESAS_SCP A
      WHERE A.BDCODEMP = NEW.BDCODEMP
        AND A.BDREFEMP = NEW.BDREFSOC
        AND A.BDCODSCP = NEW.BDCODSCP
    )) THEN
    BEGIN
      -- Lança exceção se não existir
      EXCEPTION EX_CHAVE_ESTRANGEIRA USING (
        'VEF_EMP_TMOVSAIITENS',
        NEW.BDCODEMP || ',' || NEW.BDREFSOC || ',' || NEW.BDCODSCP,
        'BDCODEMP,BDREFEMP,BDCODSCP',
        'TEMPRESAS_SCP'
      );
    END
  END
  end
end^

CREATE OR ALTER trigger vef_emp_tc190sai_biu1 for vef_emp_tc190sai
active before insert or update position 1
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    if ((NEW.BDCODOBS IS NOT NULL) AND (NEW.BDCODOBS is distinct from OLD.BDCODOBS) and (not exists(SELECT FIRST 1 A.BDCODOBS FROM VEF_BASE_TOBSERVACAO A WHERE A.BDCODOBS = NEW.BDCODOBS))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TC190SAI', NEW.BDCODOBS, 'BDCODOBS', 'VEF_BASE_TOBSERVACAO');
    if ((NEW.BDCODCSTICMS IS NOT NULL) AND (NEW.BDCODCSTICMS is distinct from OLD.BDCODCSTICMS) and (not exists(SELECT FIRST 1 A.BDCODCSTICMS FROM VEF_BASE_TTABCSTICMS A WHERE A.BDCODCSTICMS = NEW.BDCODCSTICMS))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TC190SAI', NEW.BDCODCSTICMS, 'BDCODCSTICMS', 'VEF_BASE_TTABMODELOLAN');
  end
end
^
   
CREATE OR ALTER trigger vef_emp_tc197sai_biu1 for vef_emp_tc197sai
active before insert or update position 1
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    if ((NEW.BDCODAJU IS NOT NULL) AND (NEW.BDCODAJU is distinct from OLD.BDCODAJU) and (not exists(SELECT FIRST 1 A.BDCODAJU FROM VEF_BASE_TTABCODAJU A WHERE A.BDCODAJU = NEW.BDCODAJU))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TC197SAI', NEW.BDCODAJU, 'BDCODAJU', 'VEF_BASE_TTABCODAJU');
    if ((NEW.BDORDEMITEM1400 IS NOT NULL) AND (NEW.BDORDEMITEM1400 is distinct from OLD.BDORDEMITEM1400) and (not exists(SELECT FIRST 1 A.BDORDEMITEM1400 FROM VEF_BASE_TTABCODITEM1400 A WHERE A.BDORDEMITEM1400 = NEW.BDORDEMITEM1400))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TC197SAI', NEW.BDORDEMITEM1400, 'BDORDEMITEM1400', 'VEF_BASE_TTABCODITEM1400');
    if ((NEW.BDCODPROD IS NOT NULL) AND (NEW.BDCODPROD is distinct from OLD.BDCODPROD) and (not exists(SELECT FIRST 1 A.BDCODPROD FROM TCADPRO A WHERE A.BDCODPROD = NEW.BDCODPROD))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TC197SAI', NEW.BDCODPROD, 'BDCODPROD', 'TCADPRO');
  end
end
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABMODELOLAN_BD0 FOR VEF_BASE_TTABMODELOLAN
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVSAI SAI
             WHERE (SAI.BDMODELO = OLD.BDMODELO))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVSAI';
END
^

CREATE OR ALTER TRIGGER TUSUARIO_BD0 FOR TUSUARIO
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVSAI SAI
             WHERE (SAI.BDCODUSU  = OLD.BDCODUSU) OR
                   (SAI.BDCODUSUINCLU = OLD.BDCODUSU))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVSAI';
  if (EXISTS(SELECT FIRST 1 TLAN.BDCODEMP
             FROM VSUC_EMPRESAS_TLAN TLAN
             WHERE (TLAN.BDCODUSU  = OLD.BDCODUSU) OR
                   (TLAN.bdcodusualteracao = OLD.BDCODUSU))) then
    EXCEPTION ex_delete 'VSUC_EMPRESAS_TLAN';
END
^

CREATE OR ALTER TRIGGER TCIDADE_BD0 FOR TCIDADE
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVSAI SAI
             WHERE (SAI.BDCODCID = OLD.BDCODCID))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVSAI';   

  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVSAIITENS SAI
             WHERE (SAI.BDCODCID = OLD.BDCODCID))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVSAIITENS';
END
^

CREATE OR ALTER TRIGGER VEF_BASE_STATUSLANC_BD0 FOR VEF_BASE_STATUSLANC
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVSAI SAI
             WHERE (SAI.BDCODSTATUSLAN = OLD.BDCODSTATUSLAN))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVSAI';
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABSITNF_BD0 FOR VEF_BASE_TTABSITNF
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVSAI SAI
             WHERE (SAI.BDCODSITNF = OLD.BDCODSITNF))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVSAI';
END
^   
  
CREATE OR ALTER TRIGGER TFATCONV_BD0 FOR TFATCONV
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVPROSAI SAI
             WHERE (SAI.BDCODPROD = OLD.BDCODPROD and SAI.BDCODEMP = OLD.BDCODEMP and SAI.BDCODFATCON = OLD.BDCODFATCON))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVPROSAI';
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABCSTIPI_BD0 FOR VEF_BASE_TTABCSTIPI
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVPROSAI SAI
             WHERE (SAI.BDCODCSTIPI = OLD.BDCODCSTIPI))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVPROSAI';
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVPROSAIIMPORI SAI
             WHERE (SAI.BDCODCSTIPI = OLD.BDCODCSTIPI))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVPROSAIIMPORI';
END^

CREATE OR ALTER trigger vef_base_ttabcstpis_bd0 for vef_base_ttabcstpis
active before delete position 0
AS
BEGIN
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVPROSAI SAI
             WHERE (SAI.BDCODCSTPIS = OLD.BDCODCSTPIS))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVPROSAI';

  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVPROSAIIMPORI SAI
             WHERE (SAI.BDCODCSTPIS = OLD.BDCODCSTPIS))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVPROSAIIMPORI';
END^

CREATE OR ALTER trigger vef_base_ttabcstcof_bd0 for vef_base_ttabcstcof
active before delete position 0
AS
BEGIN
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVPROSAI SAI
             WHERE (SAI.BDCODCSTCOF = OLD.BDCODCSTCOF))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVPROSAI';
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVPROSAIIMPORI SAI
             WHERE (SAI.BDCODCSTCOF = OLD.BDCODCSTCOF))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVPROSAIIMPORI';
END^

CREATE OR ALTER TRIGGER VEF_BASE_TTAB_NATREC_BD0 FOR VEF_BASE_TTAB_NATREC
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVPROSAI SAI
             WHERE (SAI.BDCODNATREC = OLD.BDCODNATREC))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVPROSAI';
END
^                 

CREATE OR ALTER trigger vef_base_tobservacao_bd0 for vef_base_tobservacao
active before delete position 0
AS
BEGIN
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVSAIITENS SAI
             WHERE (SAI.BDCODOBS = OLD.BDCODOBS))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVSAIITENS';
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TC190SAI  SAI
             WHERE (SAI.BDCODOBS = OLD.BDCODOBS))) then
    EXCEPTION ex_delete 'VEF_EMP_TC190SAI ';
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TC195SAI  SAI
             WHERE (SAI.BDCODOBS = OLD.BDCODOBS))) then
    EXCEPTION ex_delete 'VEF_EMP_TC195SAI';

  if (OLD.bdqtdarquivado > 0) then
    EXCEPTION ex_delete 'TARQUIVAMENTO';
END^

CREATE OR ALTER TRIGGER VEF_BASE_TTABCSTICMS_BD0 FOR VEF_BASE_TTABCSTICMS
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVSAIITENS SAI
             WHERE (SAI.BDCODCSTICMS = OLD.BDCODCSTICMS))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVSAIITENS';

  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVPROSAI SAI
             WHERE (SAI.BDCODCSTICMS = OLD.BDCODCSTICMS))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVPROSAI';

  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TC190SAI SAI
             WHERE (SAI.BDCODCSTICMS = OLD.BDCODCSTICMS))) then
    EXCEPTION ex_delete 'VEF_EMP_TC190SAI';

  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVPROSAIIMPORI SAI
             WHERE (SAI.BDCODCSTICMS = OLD.BDCODCSTICMS))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVPROSAIIMPORI';
END^

CREATE OR ALTER TRIGGER VEF_BASE_TNATOP_BD0 FOR VEF_BASE_TNATOP
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVSAIITENS SAI
             WHERE (SAI.BDCODNAT = OLD.BDCODNAT))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVSAIITENS';
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABCODAJU_BD0 FOR VEF_BASE_TTABCODAJU
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TC197SAI SAI
             WHERE (SAI.BDCODAJU = OLD.BDCODAJU))) then
    EXCEPTION ex_delete 'VEF_EMP_TC197SAI';
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABCODITEM1400_BD0 FOR VEF_BASE_TTABCODITEM1400
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TC197SAI SAI
             WHERE (SAI.BDORDEMITEM1400 = OLD.BDORDEMITEM1400))) then
    EXCEPTION ex_delete 'VEF_EMP_TC197SAI';
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VSUC_EMPRESAS_TTRF FOR VSUC_EMPRESAS_TTRF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1), 1) FROM vsuc_empresas_ttrf WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.bdchave = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM vsuc_empresas_ttrf WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM vsuc_empresas_ttrf WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdchave = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VSUC_PLANILHAS_TLA FOR VSUC_PLANILHAS_TLAN
ACTIVE BEFORE INSERT POSITION 0 
AS
   DECLARE VARIABLE vCodigo INTEGER;
   DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
   vCodigo = 0;
   IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0))  THEN
      BEGIN
         SELECT COALESCE((MAX(bdchave)+1),1) FROM vsuc_planilhas_tlan WHERE bdcodplanilha = NEW.bdcodplanilha INTO vnova_chave;
         NEW.bdchave = vnova_chave;
      END
   ELSE
      BEGIN
         SELECT bdchave FROM vsuc_planilhas_tlan WHERE (bdchave = NEW.bdchave) AND (bdcodplanilha = NEW.bdcodplanilha) INTO vcodigo;

         IF (vcodigo > 0) THEN
            BEGIN
               SELECT COALESCE((MAX(bdchave)+1),1) FROM vsuc_planilhas_tlan WHERE bdcodplanilha = NEW.bdcodplanilha INTO vnova_chave;
               NEW.bdchave = vnova_chave;
            END
      END
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERT_VSUC_PLANILHAS_TLC FOR VSUC_PLANILHAS_TLCC
ACTIVE BEFORE INSERT POSITION 0 
AS
   DECLARE VARIABLE vCodigo INTEGER;
   DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vCodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
        SELECT COALESCE(MAX(bdchave),1) FROM vsuc_planilhas_tlan WHERE bdcodplanilha = NEW.bdcodplanilha INTO vNova_Chave;
        NEW.bdchave = vNova_Chave;
     END

/*  else
     begin
        select coalesce((max(bdchave)),1) from vsuc_planilhas_tlan where (bdcodplanilha = new.bdcodplanilha) and (bdchave = NEW.bdchave) into vcodigo;

        if (vcodigo > 0) then
           begin
              select coalesce(max(bdchave),1) from vsuc_planilhas_tlan where bdcodplanilha = new.bdcodplanilha into vNova_Chave;
              NEW.bdchave = vNova_Chave;
           end
      end*/
END
^

CREATE OR ALTER TRIGGER TR_BF_INSERTVEF_BASE_TTABCODSER FOR VEF_BASE_TTABCODSER
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDORDENSER IS NULL) OR (NEW.BDORDENSER = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDORDENSER)+1),1) FROM VEF_BASE_TTABCODSER INTO vcodigo;
       NEW.BDORDENSER = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDORDENSER FROM VEF_BASE_TTABCODSER WHERE BDORDENSER = NEW.BDORDENSER INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDORDENSER)+1),1) FROM VEF_BASE_TTABCODSER INTO vcodigo;
            NEW.BDORDENSER = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_ISERT_VEF_BASE_TCONFIPI FOR VEF_BASE_TCONFIPI
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODCONFIPI IS NULL) OR (NEW.BDCODCONFIPI = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODCONFIPI)+1),1) FROM vef_base_tconfIPI INTO vcodigo;
        NEW.BDCODCONFIPI = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODCONFIPI FROM vef_base_tconfIPI WHERE BDCODCONFIPI = NEW.BDCODCONFIPI INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODCONFIPI)+1),1) FROM vef_base_tconfIPI INTO vcodigo;
            NEW.BDCODCONFIPI = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_ISERT_VEF_BASE_TCONFIRLP FOR VEF_BASE_TCONFIRLP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODCONFIRLP IS NULL) OR (NEW.BDCODCONFIRLP = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODCONFIRLP)+1),1) FROM VEF_BASE_TCONFIRLP INTO vcodigo;
        NEW.BDCODCONFIRLP = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODCONFIRLP FROM VEF_BASE_TCONFIRLP WHERE BDCODCONFIRLP = NEW.BDCODCONFIRLP INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODCONFIRLP)+1),1) FROM VEF_BASE_TCONFIRLP INTO vcodigo;
            NEW.BDCODCONFIRLP = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_ISERT_VEF_BASE_TCONFQIPI FOR VEF_BASE_TCONFIPIQ
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODQIPI IS NULL) OR (NEW.BDCODQIPI = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODQIPI)+1),1) FROM VEF_BASE_TCONFIPIQ INTO vcodigo;
        NEW.BDCODQIPI = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODQIPI FROM VEF_BASE_TCONFIPIQ WHERE BDCODQIPI = NEW.BDCODQIPI INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODQIPI)+1),1) FROM VEF_BASE_TCONFIPIQ INTO vcodigo;
            NEW.BDCODQIPI = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TR_BF_ISERT_VEF_BASE_TCONFQIRLP FOR VEF_BASE_TCONFIRLPQ
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODQIRLP IS NULL) OR (NEW.BDCODQIRLP = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODQIRLP)+1),1) FROM VEF_BASE_TCONFIRLPQ INTO vcodigo;
        NEW.BDCODQIRLP = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODQIRLP FROM VEF_BASE_TCONFIRLPQ WHERE BDCODQIRLP = NEW.BDCODQIRLP INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODQIRLP)+1),1) FROM VEF_BASE_TCONFIRLPQ INTO vcodigo;
            NEW.BDCODQIRLP = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER "TR_BF-INSERT_VLAL_LALUR_PARTEB" FOR VLAL_BASE_LALUR_PARTEB
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodparteb IS NULL) OR (NEW.bdcodparteb = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodparteb)+1),1) FROM vlal_base_lalur_parteb INTO vcodigo;
       NEW.bdcodparteb = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodparteb FROM vlal_base_lalur_parteb WHERE bdcodparteb = NEW.bdcodparteb INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodparteb)+1),1) FROM vlal_base_lalur_parteb INTO vcodigo;
            NEW.bdcodparteb = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TRELATORIOS_PERSONALIZADOS_BI0 FOR TRELATORIOS_PERSONALIZADOS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCod INTEGER;
BEGIN
  IF ((NEW.bdcodrp IS NULL) OR (NEW.bdcodrp = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODRP) + 1, 1) FROM TRELATORIOS_PERSONALIZADOS INTO :vCod;
       NEW.bdcodrp = :vCod;
     END
END
^

--#alt:15432. Novas triggers que atribuem o valor para o campo BDTIPOTER. Ana - 30/08/2016
CREATE OR ALTER TRIGGER tr_bf_insert_tterceiro FOR tterceiro
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  NEW.BDCODTIPOORIG = NEW.BDCODTIPO;
  NEW.BDDATAINCLUSAOORIG = CURRENT_DATE;
  NEW.BDHORAINCLUSAOORIG = CURRENT_TIME;

  IF (NEW.BDTIPOTER IS NULL) THEN
     NEW.BDTIPOTER = 0;
  ELSE
    IF(NEW.BDTIPOTER > 3) THEN
     NEW.BDTIPOTER = NULL;

  -- 144124 - Raphael Teodoro - 04/12/2020
  IF (NEW.BDCGCTER IS NOT NULL) THEN
     BEGIN
       UPDATE VRHF_MVAUT
       SET BDMODIFICADO = 'TRUE'
       WHERE (BDCPF = NEW.BDCGCTER);
     END
END
^

CREATE OR ALTER trigger tr_bf_update_tterceiro for tterceiro
active before update position 0
AS
    DECLARE VARIABLE wTipo INTEGER;
BEGIN

    IF ((NEW.bdcodtipo <> 1) AND (NEW.bdcodtipo <> 23) AND (NEW.bdcodtipo <> 42) AND (trim(replace(replace(replace(replace(NEW.bdcgcter, '.', ''), '-', ''), '/', ''), '0', '')) <>
                                                                                      trim(replace(replace(replace(replace(OLD.bdcgcter, '.', ''), '-', ''), '/', ''), '0', '')))) THEN
    BEGIN
      EXCEPTION ALT_PARTICIPANTE;
    END

  SELECT tterceiro.bdtipoter
  FROM   tterceiro
  WHERE  tterceiro.bdcodter = NEW.bdcodter
  INTO :wTipo;

  IF ((NEW.BDTIPOTER IS NULL) OR (NEW.BDTIPOTER > 3)) THEN
     NEW.BDTIPOTER = NULL;
  ELSE
    IF (wTipo = 2) THEN
      NEW.BDTIPOTER = 3;
    ELSE
       IF (wTipo = 0) THEN
          NEW.BDTIPOTER = 1;
END^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TTERCEIRO_REF FOR TTERCEIRO_REF
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE BDENQSIMPLESFEDTER INTEGER;
DECLARE VARIABLE BDPRURALTER DM_BOOLEAN;  
DECLARE VARIABLE BDCODAQUIRUR INTEGER;
DECLARE VARIABLE BDCODTRIBRUR INTEGER;
DECLARE VARIABLE BDCARACTRIBUTARIATER INTEGER;  
DECLARE VARIABLE BDPRODPF DM_BOOLEAN;
DECLARE VARIABLE BDCPFPROD DM_CNPJ_CPF;
BEGIN
-- #91190 - Os dados não devem atualizar para null em nenhum processo
    SELECT FIRST 1 BDENQSIMPLESFEDTER, BDPRURALTER, BDCODAQUIRUR, BDCODTRIBRUR, BDCARACTRIBUTARIATER, BDPRODPF, BDCPFPROD
    FROM TTERCEIRO_REF
    WHERE BDCODTER = NEW.BDCODTER
    ORDER BY BDREFEMP DESC INTO :BDENQSIMPLESFEDTER, :BDPRURALTER, :BDCODAQUIRUR, :BDCODTRIBRUR, :BDCARACTRIBUTARIATER, :BDPRODPF, :BDCPFPROD;

    IF (NEW.BDENQSIMPLESFEDTER IS NULL) THEN
        BEGIN
            IF (:BDENQSIMPLESFEDTER IS NOT NULL) THEN
                NEW.BDENQSIMPLESFEDTER = :BDENQSIMPLESFEDTER;
            ELSE
                NEW.BDENQSIMPLESFEDTER = 2;
        END
           
    IF (NEW.BDPRURALTER IS NULL) THEN
        NEW.BDPRURALTER = :BDPRURALTER;

    IF (NEW.BDCODAQUIRUR IS NULL) THEN
        NEW.BDCODAQUIRUR = Coalesce(:BDCODAQUIRUR,0);

    IF (NEW.BDCODTRIBRUR IS NULL) THEN
        NEW.BDCODTRIBRUR = Coalesce(:BDCODTRIBRUR,0);
        
    IF (NEW.BDPRODPF IS NULL) THEN
        NEW.BDPRODPF = :BDPRODPF;
        
    IF (NEW.BDCPFPROD IS NULL) THEN
        NEW.BDCPFPROD = :BDCPFPROD;

    IF (NEW.BDCARACTRIBUTARIATER IS NULL) THEN
        NEW.BDCARACTRIBUTARIATER = Coalesce(:BDCARACTRIBUTARIATER,-1);

    if (new.bdutilizadescsimplificado is null) then
        new.bdutilizadescsimplificado = 'TRUE';
END
^

CREATE OR ALTER TRIGGER tr_bf_update_tterceiro_ref FOR tterceiro_ref
ACTIVE BEFORE UPDATE POSITION 0
AS
    DECLARE VARIABLE wTipo INTEGER;
BEGIN

  IF ((NEW.bdCODTER <> OLD.bdCODTER) /*OR -- Alt.: #185860 - Vai lançar uma exceção quando tentar alterar o participante, pois estavam sumindo alguns e não foi possível identificar qual a rotina que estava gerando o problema...
      (TRIM(REPLACE(REPLACE(REPLACE(REPLACE(NEW.bdCGCTER, '.', ''), '-', ''), '/', ''), '0', '')) <>
       TRIM(REPLACE(REPLACE(REPLACE(REPLACE(OLD.bdCGCTER, '.', ''), '-', ''), '/', ''), '0', '')))*/) THEN
    BEGIN
      EXCEPTION ALT_PARTICIPANTE;
    END

  -- #183828 - Rotina de atualizar nome de participante nao deve passar na trigger, por conta de performance
  if (Coalesce((SELECT FIRST 1 TRIM(rdb$get_context('USER_SESSION', 'W_ATUALIZANDO_PARTICIPANTE')) FROM rdb$database),'FALSE') <> 'TRUE') then
    BEGIN
  SELECT tterceiro.bdtipoter
  FROM   tterceiro
  WHERE  tterceiro.bdcodter = NEW.bdcodter
  INTO :wTipo;

  IF (wTipo = 0) THEN
    BEGIN
      UPDATE tterceiro SET BDTIPOTER = 1
      WHERE tterceiro.bdcodter = NEW.bdcodter;
    END
  ELSE
    IF (wTipo = 2) THEN
       BEGIN
         UPDATE tterceiro SET BDTIPOTER = 3
         WHERE tterceiro.bdcodter = NEW.bdcodter;
       END
    ELSE
       IF ((wTipo IS NULL) OR (wTipo > 3)) THEN
          BEGIN
            UPDATE tterceiro SET BDTIPOTER = NULL
            WHERE tterceiro.bdcodter = NEW.bdcodter;
          END
    END

-- #91190 - Os dados não devem atualizar para null em nenhum processo
   IF (New.BDENQSIMPLESFEDTER IS NULL) THEN
      NEW.BDENQSIMPLESFEDTER = OLD.BDENQSIMPLESFEDTER;
      
   IF (New.BDPRURALTER IS NULL) THEN
      NEW.BDPRURALTER = OLD.BDPRURALTER;

   IF (New.BDCODAQUIRUR IS NULL) THEN
      NEW.BDCODAQUIRUR = OLD.BDCODAQUIRUR;

   IF (New.BDCODTRIBRUR IS NULL) THEN
      NEW.BDCODTRIBRUR = OLD.BDCODTRIBRUR;

   IF (New.BDPRODPF IS NULL) THEN
      NEW.BDPRODPF = OLD.BDPRODPF;

   IF (New.BDCPFPROD IS NULL) THEN
      NEW.BDCPFPROD = OLD.BDCPFPROD;
      
   IF (New.BDCARACTRIBUTARIATER IS NULL) THEN
      NEW.BDCARACTRIBUTARIATER = OLD.BDCARACTRIBUTARIATER;
END
^
--#alt:15432. fim

CREATE OR ALTER TRIGGER TCIDADE_BU0 FOR TCIDADE
ACTIVE BEFORE UPDATE POSITION 0
AS   
  DECLARE VARIABLE wAlt DM_BOOLEAN;
BEGIN
  SELECT COALESCE(RDB$GET_CONTEXT('USER_SESSION', 'W_UPT_ISSLEGAL'), '') FROM RDB$DATABASE INTO :wAlt;
  if (((old.BDISSLEGAL <> new.BDISSLEGAL) or
      ((new.BDISSLEGAL is null) and (old.BDISSLEGAL is not null)) or
      ((old.BDISSLEGAL is null) and (new.BDISSLEGAL is not null)))
      AND (:wAlt <> 'TRUE')) then
    EXCEPTION EX_CID_ISSLEGAL;
END
^

CREATE OR ALTER TRIGGER TREPOSITORIO_BI0 FOR TREPOSITORIO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodrep IS NULL) OR (NEW.bdcodrep <= 0))  THEN
     BEGIN
       SELECT COALESCE((MAX(bdcodrep)+1), 1) FROM trepositorio INTO :vcodigo;
       NEW.bdcodrep = vcodigo;
     END
  ELSE
     BEGIN
       SELECT bdcodrep FROM trepositorio WHERE (bdcodrep = NEW.bdcodrep) INTO vcodigo;

       IF (vcodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdcodrep)+1), 1) FROM trepositorio INTO :vcodigo;
            NEW.bdcodrep = vcodigo;
          END
     END

  NEW.bdaltero = 'TRUE';

  IF (NEW.bdchave = 0) THEN
     NEW.bdchave = NULL;
END
^

CREATE OR ALTER TRIGGER TSELECOESEMP_BI0 FOR TSELECOESEMP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.bdcodigosel IS NULL) OR (NEW.bdcodigosel = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodigosel) + 1, 1)
       FROM tselecoesemp
       INTO :vNovoCod;

       NEW.bdcodigosel = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER TSELEMP_BI0 FOR TSELEMP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.bdcodigosel IS NULL) OR (NEW.bdcodigosel = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodigosel), 1)
       FROM tselecoesemp
       INTO :vNovoCod;

       NEW.bdcodigosel = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER TSOFTWAREHOUSE_BI0 FOR TSOFTWAREHOUSE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCod INTEGER;

BEGIN
  IF ((NEW.bdcodigo IS NULL) OR (NEW.bdcodigo = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODIGO) + 1, 1) FROM TSOFTWAREHOUSE INTO :vCod;
       NEW.bdcodigo = vCod;
     END
END
^

CREATE OR ALTER TRIGGER tr_bf_insert_empresas_timovrur FOR empresas_timovrur
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODIMOVRUR IS NULL) OR (NEW.BDCODIMOVRUR = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODIMOVRUR)+1), 1) FROM empresas_timovrur WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.BDCODIMOVRUR = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT BDCODIMOVRUR FROM empresas_timovrur WHERE (BDCODIMOVRUR = NEW.BDCODIMOVRUR) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCODIMOVRUR)+1), 1) FROM empresas_timovrur WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.BDCODIMOVRUR = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER tr_bf_insert_emp_texplocontrat FOR empresas_texplocontrat
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vCodDep INTEGER;
BEGIN
  vCodigo = 0;
  IF ((NEW.bdcodimovrur IS NULL) OR (NEW.bdcodimovrur = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdcodimovrur)), 1) FROM EMPRESAS_TIMOVRUR WHERE (bdcodemp = NEW.bdcodemp) INTO vCodigo;
       NEW.bdcodimovrur = vCodigo;
     END

  IF ((NEW.bdcodexplo IS NULL) OR (NEW.bdcodexplo = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdcodexplo)+1), 1) FROM empresas_texplocontrat
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodimovrur = NEW.bdcodimovrur) INTO vcoddep;
       NEW.bdcodexplo = vcoddep;
     END
END
^

CREATE OR ALTER TRIGGER VSUC_BASE_EXT_TBANDEIRAS_BI0 FOR VSUC_BASE_EXT_TBANDEIRAS
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (NEW.BDCODBAN IS NULL or NEW.BDCODBAN = 0) then
    BEGIN
      SELECT COALESCE(max(BDCODBAN) + 1, 1) from VSUC_BASE_EXT_TBANDEIRAS INTO NEW.BDCODBAN;
    END
end^

CREATE OR ALTER TRIGGER VSUC_BASE_EXT_TOPERADORAS_BI0 FOR VSUC_BASE_EXT_TOPERADORAS
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (NEW.BDCODOPE IS NULL or NEW.BDCODOPE = 0) then
    BEGIN
      SELECT COALESCE(max(BDCODOPE) + 1, 1) from VSUC_BASE_EXT_TOPERADORAS INTO NEW.BDCODOPE;
    END
end^

CREATE OR ALTER TRIGGER VSUC_BASE_TFORMULA_AUTO_BI0 FOR VSUC_BASE_TFORMULA_AUTO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (NEW.BDCHAVE IS NULL or NEW.BDCHAVE = 0) then
    SELECT FIRST 1 BDCHAVE+1 FROM VSUC_BASE_TFORMULA_AUTO
    WHERE BDDEMONSTRATIVO = NEW.BDDEMONSTRATIVO ORDER BY BDDEMONSTRATIVO DESC, BDCHAVE DESC
    INTO NEW.BDCHAVE;
  if (NEW.BDCHAVE IS NULL or NEW.BDCHAVE = 0) then
    NEW.BDCHAVE = 1;
end^

CREATE OR ALTER TRIGGER VSUC_EMP_EXT_CARTAOCREDITO_BI0 FOR VSUC_EMP_EXT_CARTAOCREDITO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (NEW.BDCHAVE IS NULL or NEW.BDCHAVE = 0) then
    BEGIN
      SELECT COALESCE(max(BDCHAVE) + 1, 1) from VSUC_EMP_EXT_CARTAOCREDITO WHERE BDCODEMP = NEW.BDCODEMP INTO NEW.BDCHAVE;
    END
end^

CREATE OR ALTER trigger planos_tpla_carne_leao_ref_bi0 for planos_tpla_carne_leao_ref
active before insert position 0
AS
BEGIN
  IF (NEW.BDCODCARNE_LEAO IS NULL OR NEW.BDCODCARNE_LEAO = 0) THEN
  BEGIN
    INSERT INTO PLANOS_TPLA_CARNE_LEAO_PADRAO (BDCODCARNE_LEAO)
    VALUES (null)
    RETURNING BDCODCARNE_LEAO
    INTO NEW.BDCODCARNE_LEAO;
  END
END^

CREATE OR ALTER trigger planos_tpla_carne_leao_pad_bi0 for planos_tpla_carne_leao_padrao
active before insert position 0
AS
  DECLARE VARIABLE wCodigo INTEGER;
BEGIN
  SELECT COALESCE((MAX(BDCODCARNE_LEAO) + 1), 1)
  FROM PLANOS_TPLA_CARNE_LEAO_PADRAO
  INTO :WCODIGO;
  IF (NEW.BDCODCARNE_LEAO IS NULL OR NEW.BDCODCARNE_LEAO = 0) THEN
    NEW.BDCODCARNE_LEAO = :WCODIGO;
END^

CREATE OR ALTER trigger vsuc_tconfig_imp_lanc_plan_bi0 for vsuc_tconfig_imp_lanc_plan
active before insert position 0
AS
DECLARE VARIABLE WCODIGO INTEGER;
BEGIN
  WCODIGO = 0;
  IF ((NEW.BDCODIMPLANC IS NULL) OR (NEW.BDCODIMPLANC = 0)) THEN
  BEGIN
    SELECT COALESCE((MAX(BDCODIMPLANC) + 1), 1)
    FROM VSUC_TCONFIG_IMP_LANC_PLAN
    INTO WCODIGO;

    NEW.BDCODIMPLANC = WCODIGO;
  END
END^

CREATE OR ALTER TRIGGER VSUC_BASE_TFORMULA_TPFO_BU0 FOR VSUC_BASE_TFORMULA_TPFO
ACTIVE BEFORE UPDATE POSITION 0
AS           
  DECLARE VARIABLE wNivel INTEGER;
begin
  /* Trigger text */
  --#138309 - Machado - 15/06/2020
  EXECUTE PROCEDURE CONTAR_CHAR(NEW.BDCLAFOR, '.') RETURNING_VALUES :wNivel;
  NEW.BDNIVELFOR = :wNivel+1;
end^

CREATE OR ALTER TRIGGER VSUC_EMP_ECF_TARQECD_CTAZER_BI0 FOR VSUC_EMP_ECF_TARQUIVOECD_CTAZER
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF ((NEW.BDCODCTA IS NULL) OR (NEW.BDCODCTA = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODCTA)+1),1) FROM VSUC_EMP_ECF_TARQUIVOECD_CTAZER
        WHERE BDCODEMP = NEW.BDCODEMP AND
              BDANO    = NEW.BDANO AND
              BDCODPLAECF = NEW.BDCODPLAECF
        INTO vcodigo;
        NEW.BDCODCTA = vcodigo;
     END
END^

CREATE OR ALTER TRIGGER VSUC_EMP_ECF_TARQUIVOECD_BI0 FOR VSUC_EMP_ECF_TARQUIVOECD
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF ((NEW.BDCODPLAECF IS NULL) OR (NEW.BDCODPLAECF = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODPLAECF)+1),1) FROM VSUC_EMP_ECF_TARQUIVOECD
        WHERE BDCODEMP = NEW.BDCODEMP AND
              BDANO    = NEW.BDANO
        INTO vcodigo;
        NEW.BDCODPLAECF = vcodigo;
     END
END^

CREATE OR ALTER TRIGGER VSUC_EMPRESAS_TGRPECO_BI0 FOR VSUC_EMPRESAS_TGRPECO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (COALESCE(NEW.BDCODECD, 0) = 0 or (exists(SELECT BDCODECD FROM VSUC_EMPRESAS_TGRPECO
                                            WHERE BDCODEMPGRPECO = NEW.BDCODEMPGRPECO
                                              AND BDCODGRPECO = NEW.BDCODGRPECO
                                              AND BDCODECD = NEW.BDCODECD))) then
    begin
      SELECT COALESCE((MAX(BDCODECD)+1), 1) FROM VSUC_EMPRESAS_TGRPECO
      WHERE BDCODEMPGRPECO = NEW.BDCODEMPGRPECO AND BDCODGRPECO = NEW.BDCODGRPECO
      INTO NEW.BDCODECD;
    end
end^

/* Trigger: TDEPENDENTE_CARNE_LEAO_BI0 */
CREATE OR ALTER TRIGGER TDEPENDENTE_CARNE_LEAO_BI0 FOR TDEPENDENTE_CARNE_LEAO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  --Trigger text
  IF ((NEW.BDCODDEP IS NULL) OR (NEW.BDCODDEP = 0)
  OR EXISTS(SELECT BDCODDEP FROM TDEPENDENTE_CARNE_LEAO WHERE BDCODTER = NEW.BDCODTER AND BDCODDEP = NEW.BDCODDEP))  THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODDEP)+1), 1) FROM TDEPENDENTE_CARNE_LEAO WHERE BDCODTER = NEW.BDCODTER INTO NEW.BDCODDEP;
    END
end
^

/* Trigger: TR_BF_INSERT_TPLANO_SECUNDARIO */
CREATE OR ALTER TRIGGER TR_BF_INSERT_TPLANO_SECUNDARIO FOR TPLANO_SECUNDARIO
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODPLAPADRAO_SEC IS NULL) OR (NEW.BDCODPLAPADRAO_SEC = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODPLAPADRAO_SEC)+1),1) FROM TPLANO_SECUNDARIO INTO vcodigo;
        NEW.BDCODPLAPADRAO_SEC = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODPLAPADRAO_SEC FROM TPLANO_SECUNDARIO WHERE BDCODPLAPADRAO_SEC = NEW.BDCODPLAPADRAO_SEC INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODPLAPADRAO_SEC)+1),1) FROM TPLANO_SECUNDARIO INTO vcodigo;
            NEW.BDCODPLAPADRAO_SEC = vcodigo;
         END
    END
END
^

/* Trigger: PLANOS_TPLA_SECUNDARIO_BI0 */
CREATE OR ALTER TRIGGER PLANOS_TPLA_SECUNDARIO_BI0 FOR PLANOS_TPLA_SECUNDARIO
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodtpla IS NULL) OR (NEW.bdcodtpla = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodtpla)+1), 1) FROM planos_tpla_secundario WHERE BDCODPLAPADRAO_SEC = NEW.BDCODPLAPADRAO_SEC INTO vNova_Chave;
      NEW.bdcodtpla = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdcodtpla FROM planos_tpla_secundario WHERE (BDCODPLAPADRAO_SEC = NEW.BDCODPLAPADRAO_SEC) AND (bdcodtpla = NEW.bdcodtpla) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodtpla)+1), 1) FROM planos_tpla_secundario WHERE BDCODPLAPADRAO_SEC = NEW.BDCODPLAPADRAO_SEC INTO vNova_Chave;
           NEW.bdcodtpla = vNova_Chave;
         END
    END

  if ((NEW.bdctalon starting with '3.0') or (NEW.bdctalon starting with '9.0')) then
    execute procedure sp_remove_class_zeradas(new.bdctalon,'TRUE') RETURNING_VALUES new.bdctalon_unico;
  else
    execute procedure sp_remove_class_zeradas(new.bdctalon) RETURNING_VALUES new.bdctalon_unico;
END
^

/* Trigger: PLANOS_TPLA_SECUNDARIO_BU0 */
CREATE OR ALTER TRIGGER PLANOS_TPLA_SECUNDARIO_BU0 FOR PLANOS_TPLA_SECUNDARIO
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  if ((NEW.bdctalon starting with '3.0') or (NEW.bdctalon starting with '9.0')) then
    execute procedure sp_remove_class_zeradas(new.bdctalon,'TRUE') RETURNING_VALUES new.bdctalon_unico;
  else
    execute procedure sp_remove_class_zeradas(new.bdctalon) RETURNING_VALUES new.bdctalon_unico;
end
^

CREATE OR ALTER trigger planos_tpla_secundario_bd0 for planos_tpla_secundario
active before delete position 0
AS
  DECLARE VARIABLE vlength INTEGER;
BEGIN
  IF (OLD.bdtipcta = 0) THEN
     BEGIN
       vlength = strlen(OLD.bdctalon);

       DELETE FROM planos_tpla_secundario
       WHERE bdcodplapadrao_sec = OLD.bdcodplapadrao_sec
       AND SUBSTRING(bdctalon FROM 1 FOR :vlength) = OLD.bdctalon
       AND bdctalon <> OLD.bdctalon;

       IF (EXISTS(SELECT * FROM planos_tpla_secundario
                  WHERE bdcodplapadrao_sec = OLD.bdcodplapadrao_sec
                  AND SUBSTRING(bdctalon FROM 1 FOR :vlength) = OLD.bdctalon
                  AND bdctalon <> OLD.bdctalon)) THEN
          EXCEPTION nao_excluir_titulo;

     END
END^

CREATE OR ALTER trigger tsmtp_sci_au0 for tsmtp_sci
active after update or delete position 0
AS
begin
  if (OLD.bdoauth2 is not null and new.bdoauth2 is null) then
    delete from toauth2 where bdid = old.bdoauth2;
end^

/* Trigger: VSUC_BASE_FORMULA_TMENSAL_BI0 */
CREATE OR ALTER TRIGGER VSUC_BASE_FORMULA_TMENSAL_BI0 FOR VSUC_BASE_FORMULA_TMENSAL
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodfor IS NULL) OR (NEW.bdcodfor = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodfor)+1), 1) FROM VSUC_BASE_FORMULA_TMENSAL WHERE bdcodpfor = NEW.bdcodpfor and bdquadro = NEW.BDQUADRO INTO vCodigo;
      NEW.bdcodfor = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodfor FROM VSUC_BASE_FORMULA_TMENSAL WHERE (bdcodpfor = NEW.bdcodpfor) AND (bdcodfor = NEW.bdcodfor) and bdquadro = NEW.BDQUADRO INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodfor)+1), 1) FROM VSUC_BASE_FORMULA_TMENSAL WHERE bdcodpfor = NEW.bdcodpfor and bdquadro = NEW.BDQUADRO INTO vCodigo;
           NEW.bdcodfor = vCodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TSWS_TFORMREL_BI0 FOR TSWS_TFORMREL
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdchaverel IS NULL) OR (NEW.bdchaverel = 0) ) THEN
     SELECT COALESCE(MAX(bdchaverel),0)+1 FROM tsws_tformrel INTO NEW.bdchaverel;
END
^

CREATE OR ALTER TRIGGER TSWS_TITEMRELATORIO_BI0 FOR TSWS_TITEMRELATORIO
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdchaveitem IS NULL) OR (NEW.bdchaveitem = 0)) THEN
     SELECT COALESCE(MAX(bdchaveitem),0)+1 FROM tsws_titemrelatorio INTO NEW.bdchaveitem;
END
^

CREATE OR ALTER TRIGGER TSWS_TQUEBRASGERADOR_BI0 FOR TSWS_TQUEBRASGERADOR
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdchavequebra IS NULL) OR (NEW.bdchavequebra = 0))  THEN
     SELECT COALESCE(MAX(bdchavequebra),0) FROM tsws_tquebrasgerador INTO NEW.bdchavequebra;
END
^

CREATE OR ALTER TRIGGER TSWS_TQUEBRASREL_BI0 FOR TSWS_TQUEBRASREL
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdchavequeba IS NULL) OR (NEW.bdchavequeba = 0) ) THEN
     SELECT COALESCE(MAX(bdchavequeba),0)+1 FROM tsws_tquebrasrel INTO NEW.bdchavequeba;
END
^

CREATE OR ALTER TRIGGER TSWS_TRELATORIOS_BI0 FOR TSWS_TRELATORIOS
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
--  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
--     SELECT COALESCE(MAX(bdchave),0)+1 FROM tsws_trelatorios INTO NEW.bdchave;
  /* gilberto - 30/03/2020 - #121314 */
  if ((new.bdchave is null) and (new.bddaweb = 1)) then
  begin
    SELECT COALESCE(MAX(bdchave),0)+1 FROM tsws_trelatorios INTO NEW.bdchave;
    if (new.bdchave < 1000) then
       new.bdchave = 1000;
  end
  else
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     SELECT COALESCE(MAX(bdchave),0)+1 FROM tsws_trelatorios
     where bdchave < 1000 -- Gilberto - 30/03/2020 - Inserido condição para os relatórios padrões ficarem abaixo de 1000
     INTO NEW.bdchave;
END
^

CREATE OR ALTER TRIGGER TSWS_TRELATORIOS_EMP_BI0 FOR TSWS_TRELATORIOS_EMP
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdchave),0)+1 FROM tsws_trelatorios_emp INTO NEW.bdchave;
     END
END
^

CREATE OR ALTER TRIGGER TSWS_TTAGPOSSIVEIS_BI0 FOR TSWS_TTAGPOSSIVEIS
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     SELECT COALESCE(MAX(bdchave),0)+1 FROM tsws_ttagpossiveis INTO NEW.bdchave;
END
^

CREATE OR ALTER trigger ttabelagerador_bi0 for ttabelagerador
active before insert position 0
AS
DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodtabger IS NULL) OR (NEW.bdcodtabger = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodtabger)+1,1) FROM ttabelagerador where bdcodtabger <> 999 INTO NEW.bdcodtabger;
     END
  ELSE
     BEGIN
       SELECT bdcodtabger FROM ttabelagerador WHERE bdcodtabger = NEW.bdcodtabger INTO vCodigo;

       IF ((vCodigo <> 0) AND (vCodigo IS NOT NULL)) THEN
          BEGIN
            SELECT COALESCE(MAX(bdcodtabger)+1,1) FROM ttabelagerador where bdcodtabger <> 999 INTO NEW.bdcodtabger;
          END
     END

  NEW.bdaltero = 'T';
END
^

CREATE OR ALTER TRIGGER TTABELAGERADOR_BU0 FOR TTABELAGERADOR
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  /* Trigger text */
  NEW.bdaltero = 'T';
END
^

CREATE OR ALTER TRIGGER TTABVENCIMENTOS_BI0 FOR TTABVENCIMENTOS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCHAVE) + 1, 1)
       FROM ttabvencimentos
       INTO :vNovoCod;

       NEW.bdCHAVE = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER TTIPO_DECLARANTE_DIRF_BI0 FOR TTIPO_DECLARANTE_DIRF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCod INTEGER;
BEGIN
  IF ((NEW.bdcoddecdirf IS NULL) OR (NEW.bdcoddecdirf = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcoddecdirf), 0) + 1 FROM ttipo_declarante_dirf INTO :vCod;
       NEW.bdcoddecdirf = :vCod;
     END
END
^

CREATE OR ALTER TRIGGER TTIPOCONTAONLINE_BI0 FOR TTIPOCONTAONLINE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODTIPOCONTA IS NULL) OR (NEW.BDCODTIPOCONTA = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDCODTIPOCONTA)+1),1) FROM ttipocontaonline INTO vcodigo;
       NEW.BDCODTIPOCONTA = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDCODTIPOCONTA FROM ttipocontaonline WHERE BDCODTIPOCONTA = NEW.BDCODTIPOCONTA INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODTIPOCONTA)+1),1) FROM ttipocontaonline INTO vcodigo;
            NEW.BDCODTIPOCONTA = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TTST_AUTO_BI0 FOR TTST_AUTO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDID IS NULL) OR (NEW.BDID = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDID)+1),1) FROM ttst_auto INTO vcodigo;
       NEW.BDID = vcodigo;
    END

  SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
  NEW.bdcodusu = vcodigo;
END
^

CREATE OR ALTER TRIGGER TTST_AUTO_BLOB_BI0 FOR TTST_AUTO_BLOB
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vid INTEGER;

BEGIN
  vcodigo = 0;
  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM TTST_AUTO_BLOB WHERE (BDID = NEW.BDID) INTO vNova_Chave;
      NEW.BDCHAVE = vNova_Chave;
      IF ((NEW.BDID IS NULL) OR (NEW.BDID = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDID)), 1) FROM TTST_AUTO INTO vid;
          NEW.BDID = vid;
        END
    END
  ELSE
    BEGIN
       SELECT BDCHAVE FROM TTST_AUTO_BLOB WHERE (BDCHAVE = NEW.BDCHAVE) AND (BDID = NEW.BDID) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM TTST_AUTO_BLOB WHERE (BDID = NEW.BDID) INTO vNova_Chave;
           NEW.BDCHAVE = vNova_Chave;
         END
       IF ((NEW.BDID IS NULL) OR (NEW.BDID = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDID)), 1) FROM TTST_AUTO INTO vid;
           NEW.BDID = vid;
         END
    END

END
^

CREATE OR ALTER TRIGGER TTST_AUTO_ITEM_BI0 FOR TTST_AUTO_ITEM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vid INTEGER;

BEGIN
  vcodigo = 0;
  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM TTST_AUTO_ITEM WHERE (BDID = NEW.BDID) INTO vNova_Chave;
      NEW.BDCHAVE = vNova_Chave;
      IF ((NEW.BDID IS NULL) OR (NEW.BDID = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDID)), 1) FROM TTST_AUTO INTO vid;
          NEW.BDID = vid;
        END
    END
  ELSE
    BEGIN
       SELECT BDCHAVE FROM TTST_AUTO_ITEM WHERE (BDCHAVE = NEW.BDCHAVE) AND (BDID = NEW.BDID) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM TTST_AUTO_ITEM WHERE (BDID = NEW.BDID) INTO vNova_Chave;
           NEW.BDCHAVE = vNova_Chave;
         END
       IF ((NEW.BDID IS NULL) OR (NEW.BDID = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDID)), 1) FROM TTST_AUTO INTO vid;
           NEW.BDID = vid;
         END
    END

END
^

CREATE OR ALTER TRIGGER TUF_ALIQEXT_BI0 FOR TUF_ALIQEXT
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vcoduf INTEGER;
BEGIN
  vcodigo = 0;

  IF ((NEW.bdcoduf IS NULL) OR (NEW.bdcoduf = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdcoduf)), 1) FROM tuf INTO vcoduf;
       NEW.BDCODUF = vcoduf;
     END

  IF ((NEW.bdcodaliqext IS NULL) OR (NEW.bdcodaliqext = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODALIQEXT)+1),1) FROM tuf_aliqext WHERE bdcoduf = NEW.bdcoduf INTO vcodigo;
        NEW.bdcodaliqext = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODALIQEXT FROM tuf_aliqext WHERE bdcoduf = NEW.bdcoduf AND BDCODALIQEXT = NEW.bdcodaliqext INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCODALIQEXT)+1),1) FROM tuf_aliqext  WHERE bdcoduf = NEW.bdcoduf INTO vcodigo;
           NEW.BDCODALIQEXT = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TUNIDADEMEDIDA_BI0 FOR TUNIDADEMEDIDA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodtipo = 1) OR (NEW.bdcodtipo = 101) OR (NEW.bdcodtipo = 102)) THEN
     BEGIN
       vcodigo = 0;
       IF ((NEW.bdcodunimed IS NULL) OR (NEW.bdcodunimed = 0)) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodunimed)+1),1) FROM tunidademedida INTO vcodigo;
            NEW.bdcodunimed = vcodigo;
         END
       ELSE
         BEGIN
            SELECT bdcodunimed FROM tunidademedida WHERE bdcodunimed = NEW.bdcodunimed INTO vcodigo;
    
            IF (vcodigo > 0) THEN
              BEGIN
                 SELECT COALESCE((MAX(bdcodunimed)+1),1) FROM tunidademedida INTO vcodigo;
                 NEW.bdcodunimed = vcodigo;
              END
       END
     END
END
^

CREATE OR ALTER TRIGGER TVARIACAO_RECEITA_BI0 FOR TVARIACAO_RECEITA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vcodrec INTEGER;
  DECLARE VARIABLE vvariacao INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdvariacao IS NULL) OR (NEW.bdvariacao = 0)) THEN
    BEGIN
      IF ((NEW.bdcodrec IS NULL) OR (NEW.bdcodrec = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCODREC)), 1) FROM tcodrec INTO vcodrec;
          NEW.bdcodrec = vcodrec;
        END

       SELECT COALESCE((MAX(bdvariacao)+1), 1) FROM tvariacao_receita
       WHERE (bdcodrec = NEW.bdcodrec) INTO vvariacao;
       NEW.bdvariacao = vvariacao;
    END
  ELSE
    BEGIN
       IF ((NEW.bdcodrec IS NULL) OR (NEW.bdcodrec = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCODREC)), 1) FROM tcodrec INTO vcodrec;
          NEW.bdcodrec = vcodrec;
        END

       SELECT bdvariacao FROM tvariacao_receita
       WHERE (bdvariacao = NEW.bdvariacao) AND (bdcodrec = NEW.bdcodrec) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdvariacao)+1), 1) FROM tvariacao_receita WHERE (bdcodrec = NEW.bdcodrec) INTO vvariacao;
           NEW.bdvariacao = vvariacao;
         END

    END
END
^

CREATE OR ALTER TRIGGER TVARIAVEIS_COMP_HIST_BI0 FOR TVARIAVEIS_COMP_HIST
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcodigo INTEGER;
BEGIN
  /* Trigger text */
  IF ((NEW.BDCODIGO IS NULL) OR (NEW.BDCODIGO = 0) )THEN
     BEGIN
       SELECT COALESCE(MAX(x.BDCODIGO),0)+1 FROM tvariaveis_comp_hist x INTO vcodigo;
       NEW.BDCODIGO = vcodigo;
     END
END
^

CREATE OR ALTER TRIGGER VCT_BASE_DOCUMENTO_BI0 FOR VCT_BASE_DOCUMENTO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCODDOC INTEGER;
BEGIN
  IF ((NEW.bdcoddoc IS NULL) OR (NEW.bdcoddoc = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODDOC) + 1, 1)
       FROM vct_base_documento
       INTO :vCODDOC;

       NEW.bdcoddoc = :vCODDOC;
     END
END
^

CREATE OR ALTER TRIGGER vct_base_tipocontrole_bi0 FOR vct_base_tipocontrole
ACTIVE BEFORE INSERT POSITION 0
AS
   DECLARE VARIABLE vCodigo INTEGER;
BEGIN
   vcodigo = 0;
   IF ((NEW.bdcodtipctrl IS NULL) OR (NEW.bdcodtipctrl = 0))  THEN
      BEGIN
         SELECT COALESCE((MAX(bdcodtipctrl)+1),1) FROM vct_base_tipocontrole INTO vcodigo;
         NEW.bdcodtipctrl = vcodigo;
      END
   ELSE
      BEGIN
         SELECT bdcodtipctrl FROM vct_base_tipocontrole WHERE (bdcodtipctrl = NEW.bdcodtipctrl)  INTO vcodigo;
         IF (vcodigo > 0) THEN
            BEGIN
               SELECT COALESCE((MAX(bdcodtipctrl)+1),1) FROM vct_base_tipocontrole INTO vcodigo;
               NEW.bdcodtipctrl = vcodigo;
            END
      END
END
^

CREATE OR ALTER TRIGGER VCT_BASE_OBRIGACAO_AI0 FOR VCT_BASE_OBRIGACAO
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
--  DECLARE VARIABLE vcodemp INTEGER;
--  DECLARE VARIABLE vrefemp INTEGER;
  DECLARE VARIABLE vextinto INTEGER;
BEGIN
  -- Augusto - #190234 - 29/02/2024 - criado para caso encontre registro na tebela referente a obrigação atual, alterar data final para a data de extinção caso seja maior.
  if (new.bdextinto is not null) then
  begin
  /* Augusto - 09/04/2024 - não é necessário puxar a data de extinção como já existe na própria tabela*/
--     SELECT FIRST 1 (extract(year from y.BDEXTINTO) || lpad(extract(month from y.BDEXTINTO),2,0))
--     from vct_base_servico y
--     inner join vct_tributario_empresa x on (x.bdcodser = y.bdcodobrser)
--     WHERE (y.bdcodobrser = :new.bdcodobrser) AND ((x.bdreffin IS NULL) OR (x.bdreffin > extract(year from y.BDEXTINTO) || lpad(extract(month from y.BDEXTINTO),2,0)))
--     INTO :vextinto;

     :vextinto = cast((extract(year from NEW.BDEXTINTO) || lpad(extract(month from NEW.BDEXTINTO),2,0)) as integer);

     UPDATE vct_tributario_empresa y
     SET y.bdreffin = :vextinto
     WHERE (y.bdcodobr = new.bdcodobrser) AND ((y.bdreffin IS NULL) OR (y.bdreffin > :vextinto));
     END
  else
    begin
       :vextinto = cast((extract(year from OLD.BDEXTINTO) || lpad(extract(month from OLD.BDEXTINTO),2,0)) as integer);

--       if (:old.BDEXTINTO <> :new.BDEXTINTO) then
       if (old.BDEXTINTO is not null) then
       begin
           UPDATE vct_tributario_empresa y
           SET y.bdreffin = null
           WHERE (y.bdcodobr = NEW.bdcodobrser) AND (coalesce(y.bdreffin,0)  = coalesce(:vextinto,0));
       end
    end
/* Gilberto - 25/03/2015 - ALT:#11161 - Tirado para não inserir nos planos tributários
  INSERT INTO VCT_TRIBUTOS_PLANO_TRIBUTARIO
  SELECT NULL AS bdcodtrib, tpla.bdcodplatrib, NULL AS bdcodimp, NULL AS bdcodser, tobr.bdcodobrser
  FROM vct_base_obrigacao tobr
  INNER JOIN vct_plano_tributario tpla ON (tpla.bdcodplatrib IS NOT NULL)
  WHERE tobr.bdtipo = 1
  AND NOT tobr.bdcodobrser IN (SELECT DISTINCT bdcodobr
                               FROM vct_tributos_plano_tributario
                               WHERE bdcodobr IS NOT NULL)
  AND tobr.bdcodobrser = NEW.bdcodobrser;


  FOR SELECT bdcodemp, bdempref FROM vw_empresas_ref_atual
      WHERE bdcodemp IN (SELECT DISTINCT bdcodemp FROM vct_tributario_empresa)
      INTO :vcodemp, vrefemp DO
      BEGIN
        EXECUTE STATEMENT 'insert into vct_tributario_empresa (BDCODEMP, BDCODOBR, BDREFINI, BDREFFIN) values ('||vcodemp||', '||NEW.bdcodobrser||',  '||vrefemp||', null)';
      END
*/
END
^

CREATE OR ALTER TRIGGER VCT_BASE_OBRIGACAO_BI0 FOR VCT_BASE_OBRIGACAO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodobrser IS NULL) OR (NEW.bdcodobrser = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodobrser)+1),1) FROM vct_base_obrigacao INTO vcodigo;
       NEW.bdcodobrser = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodobrser FROM vct_base_obrigacao WHERE bdcodobrser = NEW.bdcodobrser INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodobrser)+1),1) FROM vct_base_obrigacao INTO vcodigo;
            NEW.bdcodobrser = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VCT_BASE_SERVICO_AI0 FOR VCT_BASE_SERVICO
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
--  DECLARE VARIABLE vcodemp INTEGER;
--  DECLARE VARIABLE vrefemp INTEGER;
  DECLARE VARIABLE vextinto integer;
BEGIN
  -- Augusto - #190234 - 29/02/2024 - criado para caso encontre registro na tebela referente a obrigação atual, alterar data final para a data de extinção caso seja maior.
  if (:new.bdextinto is not null) then
  begin
  /* Augusto - 09/04/2024 - não é necessário puxar a data de extinção como já existe na própria tabela*/
--     SELECT FIRST 1 (extract(year from y.BDEXTINTO) || lpad(extract(month from y.BDEXTINTO),2,0))
--     from vct_base_servico y
--     inner join vct_tributario_empresa x on (x.bdcodser = y.bdcodobrser)
--     WHERE (y.bdcodobrser = :new.bdcodobrser) AND ((x.bdreffin IS NULL) OR (x.bdreffin > extract(year from y.BDEXTINTO) || lpad(extract(month from y.BDEXTINTO),2,0)))
--     INTO :vextinto;
     :vextinto = cast((extract(year from NEW.BDEXTINTO) || lpad(extract(month from NEW.BDEXTINTO),2,0)) as integer);

     UPDATE vct_tributario_empresa y
     SET y.bdreffin = :vextinto
     WHERE (y.bdcodser = :new.bdcodobrser) AND ((y.bdreffin IS NULL) OR (y.bdreffin > :vextinto));
     END
  else
    begin
      vextinto = cast((extract(year from NEW.BDEXTINTO) || lpad(extract(month from NEW.BDEXTINTO),2,0)) as integer);
--       if (:old.BDEXTINTO <> :new.BDEXTINTO) then
       if (:old.BDEXTINTO is not null) then
       begin
          UPDATE vct_tributario_empresa y
          SET y.bdreffin = null
          WHERE (y.bdcodser = :NEW.bdcodobrser) AND (coalesce(y.bdreffin,0)  = coalesce(:vextinto,0));
       end
    end
/* Gilberto - 25/03/2015 - ALT:#11161 - Tirado para não inserir nos planos tributários
  INSERT INTO VCT_TRIBUTOS_PLANO_TRIBUTARIO
  SELECT NULL AS bdcodtrib, tpla.bdcodplatrib, NULL AS bdcodimp, tser.bdcodobrser, NULL AS bdcodobr
  FROM vct_base_servico tser
  INNER JOIN vct_plano_tributario tpla ON (tpla.bdcodplatrib IS NOT NULL)
  WHERE tser.bdtipo = 1
  AND NOT tser.bdcodobrser IN (SELECT DISTINCT bdcodser
                               FROM vct_tributos_plano_tributario
                               WHERE bdcodser IS NOT NULL)
  AND tser.bdcodobrser = NEW.bdcodobrser;


  FOR SELECT bdcodemp, bdempref FROM vw_empresas_ref_atual
      WHERE bdcodemp IN (SELECT DISTINCT bdcodemp FROM vct_tributario_empresa)
      INTO :vcodemp, vrefemp DO
      BEGIN
        EXECUTE STATEMENT 'insert into vct_tributario_empresa (BDCODEMP, BDCODSER, BDREFINI, BDREFFIN) values ('||vcodemp||', '||NEW.bdcodobrser||',  '||vrefemp||', null)';
      END
*/
  /*Adilson Hasckel: sol. 14282 - 04/05/2016 - criar automaticamente os serviços na configuração de Online do Financeiro. */
--  EXECUTE PROCEDURE vfin_insert_novo_servico_online(NEW.bdclassificacao,NEW.bdcodobrser);
  IF (OLD.bdclassificacao <> NEW.bdclassificacao) THEN
     BEGIN
--       Adilson Hasckel: sol. 14282 - 04/05/2016 - atualizar a configuração de serviços da online, caso ocorra a troca de classificação do serviço
       EXECUTE PROCEDURE vfin_update_servico_online(OLD.bdclassificacao,NEW.bdclassificacao,NEW.BDCODOBRSER);
     END  IF (OLD.bdclassificacao <> NEW.bdclassificacao) THEN
  BEGIN
--       Adilson Hasckel: sol. 14282 - 04/05/2016 - atualizar a configuração de serviços da online, caso ocorra a troca de classificação do serviço
     EXECUTE PROCEDURE vfin_update_servico_online(OLD.bdclassificacao,NEW.bdclassificacao,NEW.BDCODOBRSER);
END
END

^

CREATE OR ALTER TRIGGER VCT_BASE_SERVICO_BI0 FOR VCT_BASE_SERVICO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodobrser IS NULL) OR (NEW.bdcodobrser = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodobrser)+1),1) FROM vct_base_servico INTO vcodigo;
       NEW.bdcodobrser = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodobrser FROM vct_base_servico WHERE bdcodobrser = NEW.bdcodobrser INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodobrser)+1),1) FROM vct_base_servico INTO vcodigo;
            NEW.bdcodobrser = vcodigo;
         END
    END
END
^


/*Adilson Hasckel: sol. 14282 - 04/05/2016 - atualizar os serviços na configuração de Online do Financeiro. */
CREATE OR ALTER TRIGGER VCT_BASE_SERVICO_AU0 FOR VCT_BASE_SERVICO
ACTIVE AFTER UPDATE POSITION 1
AS
BEGIN
-- Augusto - #190234 - 01/03/2024 - não é mais usado a trigger de update e sim usando apenas a trigger de insert.
--  IF (OLD.bdclassificacao <> NEW.bdclassificacao) THEN
--     BEGIN
--       --Adilson Hasckel: sol. 14282 - 04/05/2016 - atualizar a configuração de serviços da online, caso ocorra a troca de classificação do serviço
--       EXECUTE PROCEDURE vfin_update_servico_online(OLD.bdclassificacao,NEW.bdclassificacao,NEW.BDCODOBRSER);
--     END
     END
^

CREATE OR ALTER trigger vct_empresa_docsgerados_bd0 for vct_empresa_docsgerados
active before delete position 0
AS
begin
  UPDATE VCT_EMPRESA_PROTODOCSAIDA SET BDCODCOL = OLD.BDCODCOL WHERE BDCODEMP = OLD.BDCODEMP AND BDCODPTS = OLD.BDCODPTS;
end
^

CREATE OR ALTER TRIGGER vct_empresa_docsgerados_bi0 FOR vct_empresa_docsgerados
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCODDOCGER INTEGER;
  DECLARE VARIABLE vSeqProcess INTEGER;
BEGIN
  /* Augusto - 24/06/2024 - Se W_SEQPROCESS tem valor, use-o para BDSEQPROCESS */
  vSeqProcess = CAST(rdb$get_context('USER_SESSION', 'W_SEQPROCESS') AS INTEGER);

  IF (vSeqProcess IS NOT NULL) THEN
    NEW.BDSEQPROCESS = vSeqProcess;
  IF ((NEW.bdcoddocger IS NULL) OR (NEW.bdcoddocger = 0)) THEN
     BEGIN
    vCODDOCGER = 1;
    if (GEN_ID(gen_vct_empresa_docsgerados, 0) = 0) then
    begin
      SELECT first 1 BDCODDOCGER FROM vct_empresa_docsgerados order by BDCODDOCGER desc INTO :vCODDOCGER;
      vCODDOCGER = coalesce(vCODDOCGER, 0) + 1000;
--      SET GENERATOR GEN_VCT_EMPRESA_DOCSGERADOS TO coalesce(vcoddocger, 0) +1000;
     END
    NEW.bdcoddocger = GEN_ID(gen_vct_empresa_docsgerados, vcoddocger);
     END

  IF (NEW.bdchavedarf IS NOT NULL) THEN
     BEGIN
       SELECT bdcodimp, bddatavcto, bdtotal FROM tdarfpadrao
       WHERE bdcodemp = NEW.bdcodemp
       AND bdchavedarf = NEW.bdchavedarf
       INTO NEW.bdcodimp, NEW.bddatavcto, NEW.bdvalor;
     END

  IF (NEW.bddata IS NULL) THEN
     NEW.bddata = CURRENT_DATE;

  /* gilberto - 01/04/2015 - ALT:#11246 - não pode haver valor nesses campos caso um deles esteja nulo, isso faz com que os documentos fiquem duplicados e/ou não apareçam na tela de protocolo */
  IF ((NEW.bdcodpts IS NULL) OR (NEW.bdcodipts IS NULL)) THEN
     BEGIN
       NEW.bdcodpts = NULL;
       NEW.bdcodipts = NULL;
     END
END^

CREATE OR ALTER TRIGGER vct_empresa_docsgerados_au0 FOR vct_empresa_docsgerados
ACTIVE AFTER UPDATE POSITION 0
AS
BEGIN
  IF ((NEW.bdcodpts IS NOT NULL) AND (NEW.bdcodipts IS NOT NULL)) THEN
     BEGIN
       IF (NOT NEW.bdcodimp IS NULL) THEN
          BEGIN
            UPDATE vct_empresa_protodocsaida SET
            bdvalor = NEW.bdvalor, bdvencimento = NEW.bddatavcto, bdcomplemento = NEW.bdcomplemento, bdobservacao = NEW.bdobservacao, bdreferencia = NEW.bdreferencia
            WHERE bdcodemp = NEW.bdcodemp
            AND bdcodpts = NEW.bdcodpts
            AND bdcodipts = NEW.bdcodipts;
          END
       ELSE
          BEGIN
            UPDATE vct_empresa_protodocsaida SET
            bdvalor = NEW.bdvalor, bdcomplemento = NEW.bdcomplemento, bdobservacao = NEW.bdobservacao, bdreferencia = NEW.bdreferencia
            WHERE bdcodemp = NEW.bdcodemp
            AND bdcodpts = NEW.bdcodpts
            AND bdcodipts = NEW.bdcodipts;
          END
     END
END
^

CREATE OR ALTER TRIGGER VCT_EMPRESA_PROTOCOLOSAIDA_AU0 FOR VCT_EMPRESA_PROTOCOLOSAIDA
ACTIVE AFTER UPDATE POSITION 0 
AS
BEGIN
  IF (NEW.bddatabaixa IS NOT NULL) THEN
     DELETE FROM vct_empresa_docsgerados WHERE bdcodemp = NEW.bdcodemp AND bdcodpts = NEW.bdcodpts;

  IF (NEW.bddatabaixa IS NOT NULL) THEN
     BEGIN
       UPDATE vct_empresa_protodocsaida SET
       bddatabaixa = NEW.bddatabaixa
       WHERE bddatabaixa IS NULL
       AND bdcodemp = NEW.bdcodemp
       AND bdcodpts = NEW.bdcodpts;
     END
END
^

CREATE OR ALTER TRIGGER VCT_EMPRESA_PROTODOCENT_BI0 FOR VCT_EMPRESA_PROTODOCENTRADA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCODIPTE INTEGER;
BEGIN
  IF ((NEW.bdcodpte IS NULL) OR (NEW.bdcodpte = 0)) THEN
     SELECT MAX(bdcodpte) FROM vct_empresa_protocoloentrada WHERE bdcodemp = NEW.bdcodemp INTO NEW.bdcodpte;

  IF ((NEW.bdcodipte IS NULL) OR (NEW.bdcodipte = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODIPTE) + 1, 1)
       FROM vct_empresa_protodocentrada
       WHERE BDCODEMP = NEW.bdcodemp
       AND BDCODPTE = NEW.bdcodpte
       INTO :vCODIPTE;

       NEW.bdcodipte = :vCODIPTE;
     END

  IF (NEW.bdgerasaida IS NULL) THEN
     NEW.bdgerasaida = 1;
END
^

CREATE OR ALTER TRIGGER vct_empresa_protodocentrada_au0 FOR vct_empresa_protodocentrada
ACTIVE AFTER UPDATE POSITION 0
AS
  DECLARE VARIABLE vCount INTEGER;
BEGIN
  SELECT COUNT(bdcodipte) FROM vct_empresa_protodocentrada
  WHERE bddatabaixa IS NULL
  AND bdcodemp = NEW.bdcodemp
  AND bdcodpte = NEW.bdcodpte
  INTO :vcount;

  IF (vcount = 0) THEN
     BEGIN
       UPDATE vct_empresa_protocoloentrada SET
       bddatabaixa = (SELECT MAX(bddatabaixa)
                      FROM vct_empresa_protodocentrada
                      WHERE bdcodemp = NEW.bdcodemp
                      AND bdcodpte = NEW.bdcodpte)
       WHERE bdcodemp = NEW.bdcodemp
       AND bdcodpte = NEW.bdcodpte
       AND bddatabaixa IS NULL;
     END
  ELSE
     BEGIN
       UPDATE vct_empresa_protocoloentrada SET
       bddatabaixa = NULL
       WHERE bdcodemp = NEW.bdcodemp
       AND bdcodpte = NEW.bdcodpte;
     END
/*
  IF (NEW.bddatabaixa IS NULL) THEN
     BEGIN
       IF ((NEW.bdgerasaida IS NOT NULL) AND (NEW.bdgerasaida <> 0)) THEN
          BEGIN
            UPDATE OR INSERT INTO vct_empresa_docsgerados (bdcodemp, bdcodpte, bdcodipte) VALUES (NEW.bdcodemp, NEW.bdcodpte, NEW.bdcodipte) MATCHING (bdcodemp, bdcodpte, bdcodipte);
          END
       ELSE
          BEGIN
            DELETE FROM vct_empresa_docsgerados
            WHERE bdcodemp = NEW.bdcodemp
            AND bdcodpte = NEW.bdcodpte
            AND bdcodipte = NEW.bdcodipte;
          END
     END
*/
END
^

CREATE OR ALTER TRIGGER vct_empresa_protodocsaida_au0 FOR vct_empresa_protodocsaida
ACTIVE AFTER UPDATE POSITION 0
AS
  DECLARE VARIABLE vcount INTEGER;
BEGIN
/*
  SELECT COUNT(bdcodipts) FROM vct_empresa_protodocsaida
  WHERE bddatabaixa IS NULL
  AND bdcodemp = NEW.bdcodemp
  AND bdcodpts = NEW.bdcodpts
  INTO :vcount;

  IF (vcount = 0) THEN
     BEGIN
       UPDATE vct_empresa_protocolosaida SET
       bddatabaixa = (SELECT MAX(bddatabaixa)
                      FROM vct_empresa_protodocsaida
                      WHERE bdcodemp = NEW.bdcodemp
                      AND bdcodpts = NEW.bdcodpts)
       WHERE bdcodemp = NEW.bdcodemp
       AND bdcodpts = NEW.bdcodpts
       AND bddatabaixa IS NULL;
     END
  ELSE
     BEGIN
       UPDATE vct_empresa_protocolosaida SET
       bddatabaixa = NULL
       WHERE bdcodemp = NEW.bdcodemp
       AND bdcodpts = NEW.bdcodpts;
     END
*/
  IF ((NEW.bdcodpte IS NOT NULL) AND (NEW.bdcodipte IS NOT NULL)) THEN
     BEGIN
       IF (NEW.bddatabaixa IS NOT NULL) THEN
          BEGIN
            UPDATE vct_empresa_protodocentrada SET
            bddevolvido = 1
            WHERE bdcodemp = NEW.bdcodemp
            AND bdcodpte = NEW.bdcodpte
            AND bdcodipte = NEW.bdcodipte;
          END
     END
END
^

CREATE OR ALTER TRIGGER vct_empresa_protodocsaida_bi0 FOR vct_empresa_protodocsaida
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCODIPTS INTEGER;
BEGIN
  IF ((NEW.bdcodpts IS NULL) OR (NEW.bdcodpts = 0)) THEN
     BEGIN
       SELECT MAX(bdcodpts)
       FROM vct_empresa_protocolosaida
       WHERE bdcodemp = NEW.bdcodemp
       INTO NEW.bdcodpts;
     END

  IF ((NEW.bdcodipts IS NULL) OR (NEW.bdcodipts = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODIPTS) + 1, 1)
       FROM vct_empresa_protodocsaida
       WHERE BDCODEMP = NEW.bdcodemp
       AND BDCODPTS = NEW.bdcodpts
       INTO :vCODIPTS;

       NEW.bdcodipts = :vCODIPTS;
     END

  IF (NEW.bdchavedarf IS NOT NULL) THEN
     BEGIN
       SELECT darf.bdcodimp, darf.bdcodcentro, darf.bdcodtpcc, darf.bddatavcto, darf.bdtotal, darf.bdreferencia
       FROM tdarfpadrao darf
       WHERE darf.bdcodemp = NEW.bdcodemp
       AND darf.bdchavedarf = NEW.bdchavedarf
       INTO NEW.bdcodimp, NEW.bdcodcentro, NEW.bdcodtpcc, NEW.bdvencimento, NEW.bdvalor, NEW.bdreferencia;
     END
/*
  if ((new.bdcodpte is not null) and (new.bdcodipte is not null) and (new.bdobservacao is null)) then
     begin
       select bdobservacao
       from vct_empresa_protodocentrada
       where bdcodemp = new.bdcodemp
       and bdcodpte = new.bdcodpte
       and bdcodipte = new.bdcodipte
       into new.bdobservacao;
     end
*/
END
^

create or alter procedure VCT_PROTOCOLO_SERIE (
    PRCODEMP integer,
    PRCODESC integer,
    PRENTSAI integer)
returns (
    BDSERIE varchar(100))
as
declare variable WBDSEQ integer;
declare variable WTIPOEMPESC integer;
declare variable WCODEMP integer;
declare variable WCODESC integer;
declare variable WPOS integer;
begin
  if (:prentsai = 0) then
  begin
    select first 1 cnf.bdtipo, cnf.bdserieent, cnf.bdseqent, cnf.bdcodemp, cnf.bdcodesc from (
    select first 1 0 as bdtipo, cnf.bdserieent, cnf.bdseqent+1 as bdseqent, cnf.bdcodemp, cnf.bdcodesc
    from VCT_CONFIG_PROTO_EMP cnf where cnf.bdcodemp = :prCODEMP and cnf.bdcodesc = :prCODESC
    union all
    select first 1 1 as bdtipo, cnf.bdserieent, cnf.bdseqent+1 as bdseqent, emp.bdcodemp, cnf.bdcodesc
    from  VCT_CONFIG_PROTO_ESC cnf
    join tempresas emp on(emp.bdcodesc=cnf.bdcodesc)
    where emp.bdcodemp = :prcodemp
    union all
    select first 1 1 as bdtipo, cnf.bdserieent, cnf.bdseqent+1 as bdseqent, :prcodemp as bdcodemp, cnf.bdcodesc
    from  VCT_CONFIG_PROTO_ESC cnf where cnf.bdcodesc = :prCODESC
    ) cnf into :wtipoempesc, :bdserie, :wbdseq, :wcodemp, :wcodesc;
  end
  else
  begin
    select first 1 cnf.bdtipo, cnf.bdseriesai, cnf.bdseqsai, cnf.bdcodemp, cnf.bdcodesc from (
    select first 1 0 as bdtipo, cnf.bdseriesai, cnf.bdseqsai+1 as bdseqsai, cnf.bdcodemp, cnf.bdcodesc
    from VCT_CONFIG_PROTO_EMP cnf where cnf.bdcodemp = :prCODEMP and cnf.bdcodesc = :prCODESC
    union all
    select first 1 1 as bdtipo, cnf.bdseriesai, cnf.bdseqsai+1 as bdseqsai, emp.bdcodemp, cnf.bdcodesc
    from  VCT_CONFIG_PROTO_ESC cnf
    join tempresas emp on(emp.bdcodesc=cnf.bdcodesc)
    where emp.bdcodemp = :prcodemp
    union all
    select first 1 1 as bdtipo, cnf.bdseriesai, cnf.bdseqsai+1 as bdseqsai, :prcodemp as bdcodemp, cnf.bdcodesc
    from  VCT_CONFIG_PROTO_ESC cnf where cnf.bdcodesc = :prCODESC
    union all
    select first 1 1 as bdtipo, cnf.bdseriesai, cnf.bdseqsai+1 as bdseqsai, :prcodemp as bdcodemp, cnf.bdcodesc
    from  VCT_CONFIG_PROTO_ESC  cnf
    ) cnf into :wtipoempesc, :bdserie, :wbdseq, :wcodemp, :wcodesc;
  end

-- Gilberto - 07/10/2024 - #212208 - dependendo das configurações do servidor, não consegue destinguir letras maiusculas de minusculas
--  bdserie = replace(bdserie, '*ANO', extract(year from current_date));
--  bdserie = replace(bdserie, '*MES', lpad(extract(month from current_date), 2, 0));
--  bdserie = replace(bdserie, '*MÊS', lpad(extract(month from current_date), 2, 0));
--  bdserie = replace(bdserie, '*DIA', lpad(extract(day from current_date), 2, 0));
--  bdserie = replace(bdserie, '*HOR', lpad(extract(hour from current_time), 2, 0));
--  bdserie = replace(bdserie, '*MIN', lpad(extract(minute from current_time), 2, 0));
--  bdserie = replace(bdserie, '*SEG', lpad(extract(second from current_time), 2,0));
--  bdserie = replace(bdserie, '*EMP', coalesce(:prCODEMP, ''));
--  bdserie = replace(bdserie, '*ESC', coalesce(:prCODESC, ''));
--
--  bdserie = replace(bdserie, '*SEQ', LPAD(CAST(wbdseq AS VARCHAR(10)), 5, '0'));

  wPos = position('*ANO', upper(bdserie));
  while (wPos > 0) do
  begin
    bdserie = substring(bdserie from 1 for :wpos-1)||extract(year from current_date)||substring(bdserie from :wpos+4 for strlen(bdserie));
    wPos = position('*ANO', upper(bdserie));
  end

  wPos = position('*MES', upper(bdserie));
  while (wpos > 0) do
  begin
    bdserie = substring(bdserie from 1 for :wpos-1)||lpad(extract(month from current_date), 2, 0)||substring(bdserie from :wpos+4 for strlen(bdserie));
    wPos = position('*MES', upper(bdserie));
  end

  wPos = position('*MÊS', upper(bdserie));
  while (wPos > 0) do
  begin
    bdserie = substring(bdserie from 1 for :wpos-1)||lpad(extract(month from current_date), 2, 0)||substring(bdserie from :wpos+4 for strlen(bdserie));
    wPos = position('*MÊS', upper(bdserie));
  end

  wPos = position('*DIA', upper(bdserie));
  while (wPos > 0) do
  begin
    bdserie = substring(bdserie from 1 for :wpos-1)||lpad(extract(day from current_date), 2, 0)||substring(bdserie from :wpos+4 for strlen(bdserie));
    wPos = position('*DIA', upper(bdserie));
  end

  wPos = position('*HOR', upper(bdserie));
  while (wPos > 0) do
  begin
    bdserie = substring(bdserie from 1 for :wpos-1)||lpad(extract(hour from current_time), 2, 0)||substring(bdserie from :wpos+4 for strlen(bdserie));
    wPos = position('*HOR', upper(bdserie));
  end

  wPos = position('*MIN', upper(bdserie));
  while (wPos > 0) do
  begin
    bdserie = substring(bdserie from 1 for :wpos)||lpad(extract(minute from current_time), 2, 0)||substring(bdserie from :wpos+4 for strlen(bdserie));
    wPos = position('*MIN', upper(bdserie));
  end

  wPos = position('*SEG', upper(bdserie));
  while (wPos > 0) do
  begin
    bdserie = substring(bdserie from 1 for :wpos-1)||lpad(extract(second from current_time), 2,0)||substring(bdserie from :wpos+4 for strlen(bdserie));
    wPos = position('*SEG', upper(bdserie));
  end

  wPos = position('*EMP', upper(bdserie));
  while (wPos > 0) do
  begin
    bdserie = substring(bdserie from 1 for :wpos-1)||coalesce(:prCODEMP, '')||substring(bdserie from :wpos+4 for strlen(bdserie));
    wPos = position('*EMP', upper(bdserie));
  end

  wPos = position('*ESC', upper(bdserie));
  while (wPos > 0) do
  begin
    bdserie = substring(bdserie from 1 for :wpos-1)||coalesce(:prCODESC, '')||substring(bdserie from :wpos+4 for strlen(bdserie));
    wPos = position('*ESC', upper(bdserie));
  end

  wPos = position('*SEQ', upper(bdserie));
  while (wPos > 0) do
  begin
    bdserie = substring(bdserie from 1 for :wpos-1)||LPAD(CAST(wbdseq AS VARCHAR(10)), 5, '0')||substring(bdserie from :wpos+4 for strlen(bdserie));
    wPos = position('*SEQ', upper(bdserie));
  end

--Julio Cesar - 25/11/2024 - #213911 - Ajuste para tratar quando for protocolo de entrada e saída
  if (:prentsai = 0) then --Entrada
  begin
    if (wtipoempesc = 0) then
      UPDATE vct_config_proto_emp cnf SET cnf.BDSEQENT = :wbdseq WHERE cnf.bdcodemp = :wCODEMP and cnf.bdcodesc = :wCODESC;
    else
      UPDATE vct_config_proto_esc cnf SET cnf.BDSEQENT = :wbdseq WHERE cnf.bdcodesc = :wcodesc;
  end
  else --Saída
  begin
    if (wtipoempesc = 0) then
      UPDATE vct_config_proto_emp cnf SET cnf.BDSEQSAI = :wbdseq WHERE cnf.bdcodemp = :wCODEMP and cnf.bdcodesc = :wCODESC;
    else
      UPDATE vct_config_proto_esc cnf SET cnf.BDSEQSAI = :wbdseq WHERE cnf.bdcodesc = :wcodesc;
  end
  suspend;
end^

create or alter procedure SET_PROTCOLO_SEQUEINCIAPROCESSO (
    PRSEQPROCESS integer = 0)
as
declare variable WSEQPROCESS integer;
begin
  IF (coalesce(:prseqprocess,0) <> 0) THEN
    rdb$set_context('USER_SESSION', 'W_SEQPROCESS', GEN_ID(GEN_SEQPROCESS, 1));
  ELSE
  begin
    -- Realiza a baixa do protocolo na exportação da sequencia de processos
    SELECT first 1 CAST((TRIM(rdb$get_context('USER_SESSION', 'W_SEQPROCESS'))) AS INTEGER) FROM rdb$database into :wseqprocess;
    if (:wseqprocess <> 0) then
    begin
      update vct_empresa_protocolosaida set
      bddatabaixa = current_date, bdhorabaixa = lpad(extract(hour from current_time), 2, 0)||':'||lpad(extract(minute from current_time), 2, 0),
      BDCODUSUBAIXA = (select first 1 bdcodusu from vw_usuarios_secao),
      bdobsbaixa = 'Baixado automaticamente pelo sequência de processos'
      where bdseqprocess = :wseqprocess;
    end
    rdb$set_context('USER_SESSION', 'W_SEQPROCESS', NULL);
  end

--  IF (:prseqprocess <= 0) THEN
--    rdb$set_context('USER_SESSION', 'W_SEQPROCESS', GEN_ID(GEN_SEQPROCESS, 1));
--  ELSE
--    rdb$set_context('USER_SESSION', 'W_SEQPROCESS', :prseqprocess);
end^

create or alter procedure VCT_PROTOCOLO_SEQUENCIAPROCESSO
as
declare variable WUSUARIO integer;
declare variable WSERIE varchar(100);
declare variable WCODPTS integer;
declare variable WCODESC integer;
declare variable WCODEMP integer;
declare variable WSEQPROCESS integer;
begin
  wSEQPROCESS = CAST(rdb$get_context('USER_SESSION', 'W_SEQPROCESS') AS INTEGER);

  IF (wSEQPROCESS IS NOT NULL) THEN
  begin
     FOR SELECT distinct BDCODEMP, BDCODESC, BDCODUSU
         FROM VCT_EMPRESA_DOCSGERADOS
         WHERE BDSEQPROCESS = :wSEQPROCESS
         order by bdcodemp, bdcodesc
         INTO :wcodemp, :wCodEsc, :wusuario DO
     BEGIN
         select bdserie from vct_protocolo_serie(:wcodemp,:wcodesc,1) into :wserie;

         INSERT INTO VCT_EMPRESA_PROTOCOLOSAIDA (BDCODEMP,bdserie,BDDATA,BDHORA,BDDATAEMISSAO,BDHORAEMISSAO,BDCODUSUEMISAO,BDCODESC,BDSEQPROCESS)
         VALUES (:wcodemp,:wserie, CURRENT_DATE,(extract(hour from current_time)|| ':'||extract(minute from current_time)),CURRENT_DATE,(extract(hour from current_time)|| ':'||extract(minute from current_time)),:wusuario,:wCodEsc,:wSEQPROCESS)
         RETURNING BDCODPTS INTO :wcodpts;

         if (coalesce(:wcodpts, 0) = 0) then
         begin
           select first 1 bdcodpts from VCT_EMPRESA_PROTOCOLOSAIDA pts where pts.bdcodemp = :wcodemp and pts.bdseqprocess = :wseqprocess into :wcodpts;
         end

         INSERT INTO VCT_EMPRESA_PROTODOCSAIDA (BDCODEMP, BDCODPTS, BDCODCENTRO, BDCODTPCC, BDCODTELASIS, BDCODIMP, BDCODDOC, BDCODPTE, BDCODIPTE, BDCHAVEDARF,
                                                BDOBSERVACAO, BDDATA, BDVENCIMENTO, BDVALOR, BDCODSIS, BDCODUSU, BDCOMPLEMENTO, BDREFERENCIA, BDCODTER, BDNOTAFISCAL, BDCODCOL)
         select BDCODEMP, :wcodpts, BDCODCENTRO, BDCODTPCC, BDCODTELASIS, BDCODIMP, BDCODDOC, BDCODPTE, BDCODIPTE, BDCHAVEDARF,
                                                BDOBSERVACAO, BDDATA, BDDATAVCTO, BDVALOR, BDCODSIS, BDCODUSU, BDCOMPLEMENTO, BDREFERENCIA, BDCODTER, BDNOTAFISCAL, BDCODCOL
         from VCT_EMPRESA_DOCSGERADOS where bdcodemp = :wcodemp and (coalesce(bdcodesc,0) = coalesce(:wCodEsc,0)) and BDSEQPROCESS = :wSEQPROCESS;

     END
     DELETE FROM VCT_EMPRESA_DOCSGERADOS WHERE BDSEQPROCESS = :wSEQPROCESS;

  END
end^
/* Augusto - 01/07/2024 - fim das implementações para a sequência de relatórios */

CREATE OR ALTER TRIGGER VCT_EMPRESA_PROTOENT_BI0 FOR VCT_EMPRESA_PROTOCOLOENTRADA
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCODPTE INTEGER;
--  DECLARE VARIABLE vseq INTEGER;
--  DECLARE VARIABLE vesc INTEGER;
--  DECLARE VARIABLE vemp INTEGER;
  declare variable vserie varchar (120);
BEGIN
  IF ((NEW.bdcodpte IS NULL) OR (NEW.bdcodpte = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODPTE) + 1, 1)
       FROM vct_empresa_protocoloentrada
       WHERE BDCODEMP = NEW.bdcodemp
       INTO :vCODPTE;

       NEW.bdcodpte = :vCODPTE;
     END

   if ((new.bdserie is null) or (new.bdserie = '')) then
   begin
      select bdserie from vct_protocolo_serie(NEW.BDCODEMP, NEW.BDCODESC, 0) into :vserie;
      new.bdserie = substring(:vserie from 1 for 100);
   end

 /* Julio Cesar - 23/11/2024 - #213911 - O controle de incremento da série já é realizado na procedure vct_protocolo_serie
  SELECT FIRST 1 cnf.bdseqent,
         cnf.bdcodesc, cnf.bdcodemp
  FROM VCT_CONFIG_PROTO_EMP cnf
  WHERE ((cnf.bdserieent IS NOT NULL) AND (cnf.bdserieent <> '') and (cnf.bdcodesc = new.bdcodesc) and (cnf.bdcodemp =  new.bdcodemp))
  INTO :vseq, :vesc, :vemp;

  IF (vseq IS NOT NULL) THEN
     BEGIN
       UPDATE vct_config_proto_emp SET bdseqent = bdseqent+1 WHERE bdcodesc = :vesc AND bdcodemp = :vemp;
     END
  ELSE
     BEGIN
       SELECT FIRST 1 cnf.bdseqent, cnf.bdcodesc
       FROM VCT_CONFIG_PROTO_ESC cnf
       WHERE ((cnf.bdserieent IS NOT NULL) AND (cnf.bdserieent <> '') and (cnf.bdcodesc =  new.bdcodesc))
       AND NOT EXISTS (SELECT * FROM VCT_CONFIG_PROTO_EMP x
                       WHERE x.bdcodemp = new.bdcodemp AND x.bdcodesc = cnf.bdcodesc)
       INTO :vseq, :vesc;


       IF (vseq IS NOT NULL) THEN
          BEGIN
            UPDATE vct_config_proto_esc SET bdseqent = bdseqent+1 WHERE bdcodesc = :vesc;
          END
     END */
END^

CREATE OR ALTER trigger vct_empresa_protosai_bi0 for vct_empresa_protocolosaida
active before insert position 0
as
  DECLARE VARIABLE vCODPTS INTEGER;
--  DECLARE VARIABLE vseq INTEGER;
--  DECLARE VARIABLE vesc INTEGER;
--  DECLARE VARIABLE vemp INTEGER;
  DECLARE VARIABLE vSeqProcess INTEGER;
  declare variable vserie varchar (120);
BEGIN
  /* Augusto - 24/06/2024 - Se W_SEQPROCESS tem valor, use-o para BDSEQPROCESS */
  vSeqProcess = CAST(rdb$get_context('USER_SESSION', 'W_SEQPROCESS') AS INTEGER);

  IF (vSeqProcess IS NOT NULL) THEN
     NEW.BDSEQPROCESS = vSeqProcess;

  IF ((NEW.bdcodpts IS NULL) OR (NEW.bdcodpts = 0)) THEN
  BEGIN
    SELECT COALESCE(MAX(BDCODPTS) + 1, 1)
    FROM vct_empresa_protocolosaida
    WHERE BDCODEMP = NEW.bdcodemp
    INTO :vCODPTS;

    NEW.bdcodpts = :vcodpts;
  END

  -- Gilberto - 18/09/2024 - #201953 - Forçando escritório
  if (coalesce(new.bdcodesc,0)=0) then
  begin
    select first 1 coalesce(bdcodesc, (select first 1 bdcodesc from tescritorio order by bdcodesc))
    from tempresas where bdcodemp = new.bdcodemp
    into new.bdcodesc;
  end

  if ((new.bdserie is null) or (new.bdserie = '')) then
  begin
    select bdserie from vct_protocolo_serie(NEW.BDCODEMP, NEW.BDCODESC, 1) into :vserie;
    new.bdserie = substring(:vserie from 1 for 100);
  end

 /* Julio Cesar - 23/11/2024 - #213911 - O controle de incremento da série já é realizado na procedure vct_protocolo_serie
  SELECT FIRST 1 cnf.bdseqsai, cnf.bdcodesc, cnf.bdcodemp FROM VCT_CONFIG_PROTO_EMP cnf
  WHERE ((cnf.bdseriesai IS NOT NULL)
  AND (cnf.bdseriesai <> '')
  and (cnf.bdcodesc = new.bdcodesc)
  and (cnf.bdcodemp =  new.bdcodemp))
  INTO :vseq, :vesc, :vemp;

  IF (vseq IS NOT NULL) THEN
     UPDATE vct_config_proto_emp SET bdseqsai = bdseqsai+1 WHERE bdcodesc = :vesc AND bdcodemp = :vemp;
  ELSE
  BEGIN
    SELECT FIRST 1 cnf.bdseqsai, cnf.bdcodesc
    FROM VCT_CONFIG_PROTO_ESC cnf
    WHERE ((cnf.bdseriesai IS NOT NULL) AND (cnf.bdseriesai <> '') and (cnf.bdcodesc =  new.bdcodesc))
    AND NOT EXISTS (SELECT * FROM VCT_CONFIG_PROTO_EMP x
                    WHERE x.bdcodemp = new.bdcodemp AND x.bdcodesc = cnf.bdcodesc)
    INTO :vseq, :vesc;

    IF (vseq IS NOT NULL) THEN
       UPDATE vct_config_proto_esc SET bdseqsai = bdseqsai+1 WHERE bdcodesc = :vesc;
  END */
END^

CREATE OR ALTER TRIGGER VCT_EMPRESA_TAREFASWEBOBS_BI0 FOR VCT_EMPRESA_TAREFASWEBOBS
ACTIVE BEFORE INSERT POSITION 0 
AS
   DECLARE VARIABLE vCodigo INTEGER;
BEGIN
   vcodigo = 0;
   IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
      BEGIN
        SELECT MAX(bdchave) FROM vct_empresa_tarefasweb WHERE bdcodemp = NEW.bdcodemp INTO :vcodigo;
        NEW.bdchave = vcodigo;
      END

   IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0))  THEN
      BEGIN
         SELECT COALESCE((MAX(bdordem)+1),1) FROM vct_empresa_tarefaswebobs WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave INTO vcodigo;
         NEW.bdordem = vcodigo;
      END
   ELSE
      BEGIN
         SELECT bdordem FROM vct_empresa_tarefaswebobs WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vcodigo;
         IF (vcodigo > 0) THEN
            BEGIN
               SELECT COALESCE((MAX(bdordem)+1),1) FROM vct_empresa_tarefaswebobs WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave INTO vcodigo;
               NEW.bdordem = vcodigo;
            END
      END
END
^

CREATE OR ALTER TRIGGER VCT_EMPRESA_THISTTAREFA_BI0 FOR VCT_EMPRESA_THISTORICOTAREFA
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  declare variable vCodObrServPres integer;
  declare variable vCodObrServTom integer;
  declare variable vCodObrigacao integer;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodst IS NULL) OR (NEW.bdcodst = 0)) THEN
  BEGIN
    SELECT MAX(bdcodst) FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = NEW.bdcodemp INTO :vcodigo;
    NEW.bdcodst = vcodigo;
  END


  vcodigo = 0;
  IF ((NEW.bdCODHT IS NULL) OR (NEW.bdCODHT = 0)) THEN
  BEGIN
    SELECT first 1 bdCODHT FROM vct_empresa_thistoricotarefa WHERE bdcodemp = NEW.bdcodemp AND bdCODST = NEW.bdCODST order by bdcodemp, bdcodst, bdcodht desc INTO vcodigo;
    NEW.bdCODHT = coalesce(vcodigo, 0)+1;
  END
  ELSE
  BEGIN
    SELECT bdCODHT FROM vct_empresa_thistoricotarefa WHERE bdcodemp = NEW.bdcodemp AND bdCODST = NEW.bdCODST AND bdCODHT = NEW.bdCODHT INTO vcodigo;

    IF (vcodigo > 0) THEN
    BEGIN
      SELECT first 1 bdCODHT FROM vct_empresa_thistoricotarefa WHERE bdcodemp = NEW.bdcodemp AND bdCODST = NEW.bdCODST order by bdcodemp, bdcodst, bdcodht desc INTO vcodigo;
      NEW.bdCODHT = coalesce(vcodigo, 0)+1;
    END
  END

  IF (NEW.bddata IS NULL) THEN
     NEW.bddata = CURRENT_DATE;
  IF (NEW.bdhora IS NULL) THEN
     NEW.bdhora = CURRENT_TIME;

  /* Somente atribuir um valor ao campo BDCODSITWEB se ele vier nulo.
  Se a tarefa for automática, esta informação já é setada ao inseri-la */
  IF (NEW.BDCODSITWEB IS NULL) THEN
     BEGIN
-- Gilberto - 01/12/2021 - Aqui é sempre inserção
--    vcodigo = 0;
--    SELECT FIRST 1 BDCODHT FROM vct_empresa_thistoricotarefa WHERE BDCODEMP = NEW.BDCODEMP AND BDCODST = NEW.BDCODST INTO vcodigo;
--    IF (vcodigo = 0) THEN
--       NEW.BDCODSITWEB = 2; --Inserção pendente
--    ELSE
--       NEW.BDCODSITWEB = 3; --Edição pendente
            NEW.BDCODSITWEB = 2; --Inserção pendente
          END

  if (new.bdstatus = 6) then --Lançada
  begin
    select bdcodobrigacao from VCT_EMPRESA_TSOLICITATAREFA where bdcodemp = new.bdcodemp and bdcodst = new.bdcodst into :vCodObrigacao;
    if ((:vCodObrigacao is not null) or (:vCodObrigacao > 0))  then
    begin
      select bdcodobrser from VCT_BASE_OBRIGACAO where bdcodobrser = :vCodObrigacao and bddescricao like 'Serviços tomados de Rio do Sul%' into :vcodobrServTom;
      select bdcodobrser from VCT_BASE_OBRIGACAO where bdcodobrser = :vCodObrigacao and bddescricao like 'Serviços prestados de Rio do Sul%' into :vcodobrServPres;
    
      if ((:vcodobrServTom > 0) or (:vcodobrServPres > 0)) then
      begin
        new.bdstatus = 5;
        update VCT_EMPRESA_TSOLICITATAREFA  set bdaguard = 1 where bdcodemp = new.bdcodemp and bdcodst = new.bdcodst;
      END
    end
  end
  else
  --Leonardo Pereira - 25/02/2020 - Atualizar tabela de tarefas, porque se sempre que precisar saber o status ficava muito lento se usar o histórico
  if (new.bdstatus = 7) then
  begin
    -- Gilberto - 01/09/2020 - Nunca alterar para o status 7, porque a nova tela de tarefas não lista, e ambas não contabilizam
     update vct_empresa_tsolicitatarefa set --BDCODUSUATUAL = NEW.BDCODUSURESPONSAVEL,
                                            BDDATAALT = NEW.BDDATA, BDHORAALT = NEW.BDHORA,
--                                            BDCODGRUPOATUAL = NEW.BDCODGRUPO,
                                            BDCODSITWEBATUAL = NEW.BDCODSITWEB
     where BDCODEMP = NEW.BDCODEMP and BDCODST = NEW.BDCODST;
   end
   else
     /* Apenas inserir BDDATAFIM quando está finalizando a tarefa */
     if (new.bdstatus = 4) then
     begin
       update vct_empresa_tsolicitatarefa set BDSTATUSATUAL = NEW.BDSTATUS,
                                             --BDCODUSUATUAL = NEW.BDCODUSURESPONSAVEL,
                                           BDDATAALT = NEW.BDDATA, BDHORAALT = NEW.BDHORA,
--                                           BDCODGRUPOATUAL = NEW.BDCODGRUPO,
                                           BDCODSITWEBATUAL = NEW.BDCODSITWEB, BDDATAFIM = NEW.bddata, BDAGUARD = NULL
       where BDCODEMP = NEW.BDCODEMP and BDCODST = NEW.BDCODST;
     end
     else
     begin
       update vct_empresa_tsolicitatarefa set BDSTATUSATUAL = NEW.BDSTATUS,
                                              --BDCODUSUATUAL = NEW.BDCODUSURESPONSAVEL,
                                              BDDATAALT = NEW.BDDATA, BDHORAALT = NEW.BDHORA,
--                                              BDCODGRUPOATUAL = NEW.BDCODGRUPO,
                                              BDCODSITWEBATUAL = NEW.BDCODSITWEB
       where BDCODEMP = NEW.BDCODEMP and BDCODST = NEW.BDCODST;
     end
END
^

CREATE OR ALTER TRIGGER VCT_EMPRESA_THISTORICOTAREFA_AIUD0 FOR VCT_EMPRESA_THISTORICOTAREFA
ACTIVE AFTER INSERT OR UPDATE OR DELETE POSITION 0
AS
DECLARE VARIABLE vcodst INTEGER;
DECLARE VARIABLE vcodemp INTEGER;
DECLARE VARIABLE v_BDDATATAREFA DATE;
BEGIN
  SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_VCTATUHIST'))) AS INTEGER)
  FROM rdb$database
  INTO :v_BDDATATAREFA;

  IF (v_BDDATATAREFA = CURRENT_DATE) THEN
    EXIT;

  SELECT FIRST 1 bddatatarefa
  FROM vct_config_datas
  INTO :v_BDDATATAREFA;

  IF (v_BDDATATAREFA IS NOT NULL) THEN
  BEGIN
    vcodemp = NEW.bdcodemp;
    vcodst  = NEW.bdcodst;

    UPDATE vct_empresa_tsolicitatarefa H
    SET BDCODSITWEBATUAL = 3
    WHERE (bdcodemp = :vcodemp) AND (bdcodst = :vcodst) and coalesce(BDCODSITWEBATUAL,0) <> 3;

    UPDATE vct_empresa_tsolicitatarefa H
    SET BDCODHT = NEW.BDCODHT
    WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodst = NEW.bdcodst) and (coalesce(BDCODHT,0) <> coalesce(NEW.BDCODHT,0));

    IF (NEW.BDSTATUS = 4) THEN
    BEGIN
      UPDATE vct_empresa_tsolicitatarefa H
      SET BDDATAFIM=NEW.BDDATA,BDHORAFIM=NEW.BDHORA
      WHERE(bdcodemp=NEW.bdcodemp)AND(bdcodst=NEW.bdcodst)
      and(((bddatafim is null)or(bddatafim<>NEW.BDDATA))or(coalesce(BDHORAFIM,'00:00:00')<>NEW.BDHORA));
    END

    if (new.bdstatus in (1,2,3,4,5,10,11)) then
    begin
      UPDATE vct_empresa_tsolicitatarefa H
      SET BDDATAINI=NEW.BDDATA,BDHORAINI=NEW.BDHORA
      WHERE(bdcodemp=NEW.bdcodemp)AND(bdcodst=NEW.bdcodst)
      and(BDDATAINI is null)and(BDHORAINI is null);
    end

    if (new.bdstatus <> 6) then
    begin
      UPDATE vct_empresa_tsolicitatarefa H
      SET BDDATAALT=NEW.BDDATA,BDHORAALT=NEW.BDHORA
      WHERE(bdcodemp=NEW.bdcodemp)AND(bdcodst=NEW.bdcodst);
    end
  END
END^

CREATE OR ALTER TRIGGER VCT_EMPRESA_TOBSTAREFA_BI0 FOR VCT_EMPRESA_TOBSTAREFA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodst IS NULL) OR (NEW.bdcodst = 0)) THEN
     BEGIN
       SELECT MAX(bdcodst) FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = NEW.bdcodemp INTO :vcodigo;
       NEW.bdcodst = vcodigo;
     END


  vcodigo = 0;
  IF ((NEW.bdcodobs IS NULL) OR (NEW.bdcodobs = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdCODOBS)+1),1) FROM vct_empresa_tobstarefa WHERE bdcodemp = NEW.bdcodemp AND bdCODST = NEW.bdCODST INTO vcodigo;
       NEW.bdcodobs = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdCODOBS FROM vct_empresa_tobstarefa WHERE bdcodemp = NEW.bdcodemp AND bdCODST = NEW.bdCODST AND bdcodusu = NEW.bdcodusu AND bdCODOBS = NEW.bdcodobs INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdCODOBS)+1),1) FROM vct_empresa_tobstarefa WHERE bdcodemp = NEW.bdcodemp AND bdCODST = NEW.bdCODST INTO vcodigo;
            NEW.bdcodobs = vcodigo;
         END
    END
END
^

CREATE OR ALTER trigger vct_empresa_tsolicitatarefa_ad0 for vct_empresa_tsolicitatarefa
active after delete position 0
AS
DECLARE VARIABLE v_BDDATATAREFA DATE;
BEGIN
  SELECT first 1 bddatatarefa FROM vct_config_datas INTO :v_BDDATATAREFA;

  IF (v_BDDATATAREFA IS NOT NULL) THEN
  begin
  if (OLD.bdchaveweb is not null) then
     INSERT INTO VCT_EMPRESA_SOLICTAREFA_DEL (BDCODEMP, BDCODST, bdchaveweb) VALUES (OLD.BDCODEMP, old.bdcodst, OLD.bdchaveweb);

  /* Augusto #185627 Verifica se v_BDDATATAREFA é nulo antes de continuar */
    /* Deletar subordinadas */
    DELETE FROM VCT_EMPRESA_TSOLICITATAREFA
    WHERE BDCODST IN (
      SELECT SOL.BDCODST
      FROM VCT_EMPRESA_TAREFASUBORDINADA SUB
      LEFT OUTER JOIN VCT_EMPRESA_TSOLICITATAREFA SOL ON (SOL.BDCODEMP = SUB.BDCODEMP AND SOL.BDCODST = SUB.BDCODST)
      WHERE SUB.BDCODSTSUB = OLD.bdcodst AND SUB.bdcodemp = OLD.BDCODEMP
    ) AND BDCODEMP = OLD.BDCODEMP;
  END
END
^

CREATE OR ALTER TRIGGER VCT_EMPRESA_TSOLICITATAREFA_AI0 FOR VCT_EMPRESA_TSOLICITATAREFA
ACTIVE AFTER INSERT POSITION 0
AS
  DECLARE VARIABLE vcodser INTEGER;
  DECLARE VARIABLE vcodusu INTEGER;
  DECLARE VARIABLE vcodgrupo INTEGER;
  DECLARE VARIABLE vcodst INTEGER;
  DECLARE VARIABLE vprioridadesub INTEGER;
  declare variable vInseriu Boolean;
  declare variable vHist boolean;
BEGIN
  IF (NEW.bdcodtipo = 501) THEN
  BEGIN
    -- Lançamento de usuários para solicitações de impostos
    IF (NEW.bdcodimp IS NOT NULL) THEN
    begin
      vInseriu = false;
      for select y.bdcodgrupo,y.bdcodusu, y.BDHIST
          from (select EMP.BDCODGRUPO,EMP.BDCODUSU, TRUE as BDHIST from vct_empresa_usuario_imp EMP
                where(EMP.bdcodimp=new.bdcodimp)and(emp.bdcodemp=new.bdcodemp) and (coalesce(emp.bdcodproc, 0) = coalesce(new.bdcodproc,0))
-- Gilberto - 28/11/2024 - Não pode inserir todos os usuários, a tabela aumenta exponencialmente e gera lentidão no SQL
--                union
--                select grp.bdcodgrupo,grp.BDCODUSU, FALSE as BDHIST from VCT_EMPRESA_USUARIO_IMP EMP
--                left join tgrupousuario_usuario grp on(grp.bdcodgrupo=emp.bdcodgrupo)
--                where(EMP.bdcodimp=new.bdcodimp)and(emp.bdcodemp=new.bdcodemp)and(EMP.bdcodusu is null)
--                union
--                select null as bdcodgrupo,usu.bdcodusu, FALSE as BDHIST from tusuario usu
--                where exists(select first 1 bdcodusu from VCT_EMPRESA_USUARIO_IMP emp
--                             where(EMP.bdcodimp=new.bdcodimp)and(emp.bdcodemp=new.bdcodemp)
--                               and(bdcodgrupo is null)and(bdcodusu is null))
--                and(Upper(coalesce(USU.BDCONTDESATIVOUSU,'FALSE'))<>'TRUE')
                ) y
          join tusuario usu on(usu.bdcodusu=y.bdcodusu and
                      (Upper(coalesce(USU.BDCONTDESATIVOUSU,'FALSE'))<>'TRUE')AND(USU.BDCODUSU>3)AND
                                     ((upper(USU.BDNOMUSU)<>upper('schip '))AND(upper(USU.BDNOMCOMPLUSU)<>upper('SChIp'))))
--                where--(usu.bdcodusu is null)or
--                      (Upper(coalesce(USU.BDCONTDESATIVOUSU,'FALSE'))<>'TRUE')AND(USU.BDCODUSU>3)AND
--                      ((upper(USU.BDNOMUSU)<>upper('schip '))AND(upper(USU.BDNOMCOMPLUSU)<>upper('SChIp')))
      into :vcodgrupo, :vcodusu, :vhist do
      begin
        vInseriu = true;
        if (vhist) then
           INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDCODBHS, BDCODSITWEB)
                                             VALUES (NEW.bdcodemp, NEW.bdcodst, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, 12, 2, 2);
-- Gilberto - 03/12/2024 - #212329 - Não deve mais lançar nessa tabela, apenas troca de usuários
--        if (coalesce(:vcodusu,0)>0) then
--        begin
--          if ((select first 1 bdcodemp from vct_empresa_tarefa_usuario
--               where bdcodemp=new.bdcodemp and bdcodst=new.bdcodst
--               and coalesce(bdcodgrupo,0)=coalesce(:vcodgrupo,0)
--               and coalesce(bdcodusu,0)=coalesce(:vcodusu,0)) is null) then
--          insert into vct_empresa_tarefa_usuario(BDCODEMP,BDCODST,BDCODGRUPO,BDCODUSU)VALUES(NEW.bdcodemp,NEW.bdcodst,:vcodgrupo,:vcodusu);
--        end
        end
      if (not vinseriu) then
        INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDCODBHS, BDCODSITWEB)
                                          VALUES (NEW.bdcodemp, NEW.bdcodst, null, null, CURRENT_DATE, CURRENT_TIME, 6, 2, 2);
    end
    -- Lançamento de usuários para solicitações de obrigações
    IF (NEW.bdcodobrigacao IS NOT NULL) THEN
    begin
      vInseriu = false;
      for select y.bdcodgrupo, y.bdcodusu, y.BDHIST
          from (select EMP.BDCODGRUPO,EMP.BDCODUSU, TRUE as BDHIST from VCT_EMPRESA_USUARIO_OBR EMP
                where(EMP.BDCODOBRSER=new.bdcodobrigacao)and(emp.bdcodemp=new.bdcodemp) and (coalesce(emp.bdcodproc, 0) = coalesce(new.bdcodproc,0))
-- Gilberto - 28/11/2024 - Não pode inserir todos os usuários, a tabela aumenta exponencialmente e gera lentidão no SQL
--                union
--                select grp.bdcodgrupo,grp.BDCODUSU, FALSE as BDHIST from VCT_EMPRESA_USUARIO_OBR EMP
--                left join tgrupousuario_usuario grp on(grp.bdcodgrupo=emp.bdcodgrupo)
--                where(EMP.BDCODOBRSER=new.bdcodobrigacao)and(emp.bdcodemp=new.bdcodemp)and(EMP.bdcodusu is null)
--                union
--                select null as bdcodgrupo,usu.bdcodusu, FALSE as BDHIST from tusuario usu
--                where exists(select first 1 bdcodusu from VCT_EMPRESA_USUARIO_OBR emp
--                             where(EMP.BDCODOBRSER=new.bdcodobrigacao)and(emp.bdcodemp=new.bdcodemp)
--                               and(bdcodgrupo is null)and(bdcodusu is null))
--                and(Upper(coalesce(USU.BDCONTDESATIVOUSU,'FALSE'))<>'TRUE')
                ) y
                join tusuario usu on(usu.bdcodusu=y.bdcodusu and
                                          ((Upper(coalesce(USU.BDCONTDESATIVOUSU,'FALSE'))<>'TRUE')AND(USU.BDCODUSU>3)AND
                                           ((upper(USU.BDNOMUSU)<>upper('schip '))AND(upper(USU.BDNOMCOMPLUSU)<>upper('SChIp')))))
--                where--(usu.bdcodusu is null)or
--                      ((Upper(coalesce(USU.BDCONTDESATIVOUSU,'FALSE'))<>'TRUE')AND(USU.BDCODUSU>3)AND(upper(USU.BDNOMUSU)<>upper('schip '))AND(upper(USU.BDNOMCOMPLUSU)<>upper('SChIp')))
      into :vcodgrupo, :vcodusu, :vhist do
      begin
        vInseriu = true;
        if (vhist) then
           INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDCODBHS, BDCODSITWEB)
                                             VALUES (NEW.bdcodemp, NEW.bdcodst, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, 12, 2, 2);
-- Gilberto - 03/12/2024 - #212329 - Não deve mais lançar nessa tabela, apenas troca de usuários
--        if (coalesce(:vcodusu,0)>0) then
--           insert into vct_empresa_tarefa_usuario(BDCODEMP,BDCODST,BDCODGRUPO,BDCODUSU)VALUES(NEW.bdcodemp,NEW.bdcodst,:vcodgrupo,:vcodusu);
      end
      if (not vinseriu) then
        INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDCODBHS, BDCODSITWEB)
                                          VALUES (NEW.bdcodemp, NEW.bdcodst, null, null, CURRENT_DATE, CURRENT_TIME, 6, 2, 2);
    end
    -- Lançamento de usuários para solicitações de serviços
    IF (NEW.bdcodservico IS NOT NULL) THEN
    begin
      vInseriu = false;
      for select y.bdcodgrupo, y.bdcodusu, y.BDHIST
          from (select EMP.BDCODGRUPO,EMP.BDCODUSU, TRUE as BDHIST from vct_empresa_usuario_ser EMP
                where(EMP.BDCODOBRSER=new.bdcodservico)and(emp.bdcodemp=new.bdcodemp) and (coalesce(emp.bdcodproc, 0) = coalesce(new.bdcodproc,0))
-- Gilberto - 28/11/2024 - Não pode inserir todos os usuários, a tabela aumenta exponencialmente e gera lentidão no SQL
--                union
--                select grp.bdcodgrupo,grp.BDCODUSU, FALSE as BDHIST from VCT_EMPRESA_USUARIO_SER EMP
--                left join tgrupousuario_usuario grp on(grp.bdcodgrupo=emp.bdcodgrupo)
--                where(EMP.BDCODOBRSER=new.bdcodservico)and(emp.bdcodemp=new.bdcodemp)and(EMP.bdcodusu is null)
--                union
--                select null as bdcodgrupo,usu.bdcodusu, FALSE as BDHIST from tusuario usu
--                where exists(select first 1 bdcodusu from VCT_EMPRESA_USUARIO_SER emp
--                             where(EMP.BDCODOBRSER=new.bdcodservico)and(emp.bdcodemp=new.bdcodemp)
--                               and(bdcodgrupo is null)and(bdcodusu is null))
--                and(Upper(coalesce(USU.BDCONTDESATIVOUSU,'FALSE'))<>'TRUE')
                ) y
                join tusuario usu on(usu.bdcodusu=y.bdcodusu and
                                          ((Upper(coalesce(USU.BDCONTDESATIVOUSU,'FALSE'))<>'TRUE')AND(USU.BDCODUSU>3)AND
                                           ((upper(USU.BDNOMUSU)<>upper('schip '))AND(upper(USU.BDNOMCOMPLUSU)<>upper('SChIp')))))
--                where--(usu.bdcodusu is null)or
--                ((Upper(coalesce(USU.BDCONTDESATIVOUSU,'FALSE'))<>'TRUE')AND(USU.BDCODUSU>3)AND(upper(USU.BDNOMUSU)<>upper('schip '))AND(upper(USU.BDNOMCOMPLUSU)<>upper('SChIp')))
      into :vcodgrupo, :vcodusu, :vhist do
      begin
        vInseriu = true;
        if (vhist) then
           INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDCODBHS, BDCODSITWEB)
                                             VALUES (NEW.bdcodemp, NEW.bdcodst, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, 12, 2, 2);
-- Gilberto - 03/12/2024 - #212329 - Não deve mais lançar nessa tabela, apenas troca de usuários
--        if (coalesce(:vcodusu,0)>0) then
--           insert into vct_empresa_tarefa_usuario(BDCODEMP,BDCODST,BDCODGRUPO,BDCODUSU)VALUES(NEW.bdcodemp,NEW.bdcodst,:vcodgrupo,:vcodusu);
      end
      if (not vinseriu) then
        INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDCODBHS, BDCODSITWEB)
                                          VALUES (NEW.bdcodemp, NEW.bdcodst, null, null, CURRENT_DATE, CURRENT_TIME, 6, 2, 2);
    end
  END


  -- Serviços subordinadas
  IF (NEW.bdcodservico IS NOT NULL) THEN
     BEGIN
       FOR SELECT BDCODSERSUB FROM VCT_BASE_SERVICOSUBORDINADO WHERE BDCODOBRSER = NEW.bdcodservico INTO :vcodser DO
           BEGIN
             INSERT INTO vct_empresa_tsolicitatarefa
             (BDCODEMP, BDCODST, BDCODUSU, BDCODCOL, BDCODIMP, BDCODOBRIGACAO, BDCODSERVICO,
              BDCODTIPO, BDDATASOL, BDDATASOLICITADA, BDDATAPREVISAO, BDDATAFIM,
              BDREFSOL, BDTIPOSOLICITACAO, BDCHAVEWEB, BDAGUARD, BDVENCIMENTO, BDENTREGA,
              BDALERTA, BDHORAPREVISAO, BDTEMPOESTIMADO, BDCODSITWEBATUAL)
             VALUES
             (NEW.BDCODEMP, null, NEW.BDCODUSU, NEW.BDCODCOL, NULL, NULL, :vcodser,
              NEW.BDCODTIPO, NEW.BDDATASOL, NEW.BDDATASOLICITADA, NEW.BDDATAPREVISAO, NEW.BDDATAFIM,
              NEW.BDREFSOL, NEW.BDTIPOSOLICITACAO, NEW.BDCHAVEWEB, NEW.BDAGUARD, NEW.BDVENCIMENTO, NEW.BDENTREGA,
              NEW.BDALERTA, NEW.BDHORAPREVISAO, NEW.BDTEMPOESTIMADO, 2);

       ---Criar vinculo das subordinadas pro processo automatico
       SELECT COALESCE((MAX(BDPRIORIDADE)+1),1) FROM VCT_EMPRESA_TAREFASUBORDINADA WHERE bdcodemp = NEW.bdcodemp and BDCODSTSUB = NEW.BDCODST INTO :vprioridadesub;
       SELECT COALESCE((MAX(bdCODST)),1) FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = NEW.bdcodemp and bdcodtipo = new.bdcodtipo INTO :vcodst;
       INSERT INTO VCT_EMPRESA_TAREFASUBORDINADA (BDCODEMP, BDCODST, BDCODSTSUB, BDTARAUTO, BDPRIORIDADE) VALUES (new.BDCODEMP, :vcodst,  NEW.BDCODST, 'TRUE',:vprioridadesub);
    END
  END
END
^


CREATE OR ALTER TRIGGER VCT_EMPRESA_TSOLICITATAREFA_BI0 FOR VCT_EMPRESA_TSOLICITATAREFA
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vClass VARCHAR(40);
  DECLARE VARIABLE vCount INTEGER;
BEGIN
  /* lançamento automático dos serviços */
  IF (NEW.bdcodservico IS NOT NULL) THEN
     BEGIN
       SELECT tser.bdtipo, tser.bdclassificacao FROM vct_base_servico tser WHERE tser.bdcodobrser = NEW.bdcodservico INTO :vcodigo, :vclass;
       IF (vcodigo = 0) THEN
          BEGIN
            vCount = 0;
            FOR SELECT tser.bdcodobrser
                FROM vct_base_servico tser
                WHERE SUBSTRING(tser.bdclassificacao FROM 1 FOR CHAR_LENGTH(:vclass)) = :vclass
                AND tser.bdtipo = 1
                INTO :vcodigo DO
                BEGIN
                  IF (vCount = 0) THEN
                     NEW.bdcodservico = :vcodigo;
                  ELSE
                     BEGIN
                       INSERT INTO vct_empresa_tsolicitatarefa
                       (BDCODEMP, BDCODST, BDCODUSU, BDCODCOL, BDCODIMP,
                        BDCODOBRIGACAO, BDCODSERVICO, BDCODTIPO, BDDATASOL,
                        BDDATASOLICITADA, BDDATAPREVISAO,
                        BDDATAFIM, BDREFSOL,
                        BDTIPOSOLICITACAO, BDCHAVEWEB)
                       VALUES
                       (NEW.BDCODEMP, NULL, NEW.BDCODUSU, NEW.BDCODCOL, NEW.BDCODIMP,
                        NEW.BDCODOBRIGACAO, :vcodigo, NEW.BDCODTIPO, NEW.BDDATASOL,
                        NEW.BDDATASOLICITADA, NEW.BDDATAPREVISAO,
                        NEW.BDDATAFIM, NEW.BDREFSOL,
                        NEW.BDTIPOSOLICITACAO, NEW.BDCHAVEWEB);
                      END
                  vCount = vcount + 1;
                END
          END
     END
  /* lançamento automático das obrigações */
  IF (NEW.bdcodobrigacao IS NOT NULL) THEN
     BEGIN
       SELECT tobr.bdtipo, tobr.bdclassificacao FROM vct_base_obrigacao tobr WHERE tobr.bdcodobrser = NEW.bdcodobrigacao INTO :vcodigo, :vclass;
       IF (vcodigo = 0) THEN
          BEGIN
            vCount = 0;
            FOR SELECT DISTINCT tobr.bdcodobrser
                FROM vct_base_obrigacao tobr
                /* considerar apenas obrigações configuradas para empresa _____________________________________________________*/
                INNER JOIN VCT_TRIBUTARIO_EMPRESA temp ON (temp.bdcodemp = NEW.bdcodemp AND temp.bdcodobr = tobr.bdcodobrser)
                INNER JOIN vw_empresas_ref_atual tref ON (tref.bdcodemp = temp.bdcodemp AND ((tref.bdempref >= temp.bdrefini) AND
                                                                                             ((tref.bdempref <= temp.bdreffin) OR
                                                                                              (temp.bdreffin IS NULL))))
                /* ___________________________________________________________________________________________________________ */
                WHERE SUBSTRING(tobr.bdclassificacao FROM 1 FOR CHAR_LENGTH(:vclass)) = :vclass
                AND tobr.bdtipo = 1
                INTO :vcodigo DO
                BEGIN
                  IF (:vcount = 0) THEN
                     NEW.bdcodobrigacao = :vcodigo;
                  ELSE
                     BEGIN
                       INSERT INTO vct_empresa_tsolicitatarefa
                       (BDCODEMP, BDCODST, BDCODUSU, BDCODCOL, BDCODIMP,
                        BDCODOBRIGACAO, BDCODSERVICO, BDCODTIPO, BDDATASOL,
                        BDDATASOLICITADA, BDDATAPREVISAO,
                        BDDATAFIM, BDREFSOL,
                        BDTIPOSOLICITACAO, BDCHAVEWEB)
                       VALUES
                       (NEW.BDCODEMP, NULL, NEW.BDCODUSU, NEW.BDCODCOL, NEW.BDCODIMP,
                        :vcodigo, NEW.bdcodservico, NEW.BDCODTIPO, NEW.BDDATASOL,
                        NEW.BDDATASOLICITADA, NEW.BDDATAPREVISAO,
                        NEW.BDDATAFIM, NEW.BDREFSOL,
                        NEW.BDTIPOSOLICITACAO, NEW.BDCHAVEWEB);
                     END
                  vcount = vcount + 1;
                END
          END
     END

  -- Lívia - 20/03/2026 - #232581
  IF (NEW.BDDATASOL IS NULL) THEN
      NEW.BDDATASOL = CURRENT_DATE;

  /* gerador automático da chave */
  -- Gilberto - 19/11/2024 - #214976
  vcodigo = 0;
  if (coalesce(new.bdcodst,0)>0) then
  begin
    select bdcodst from vct_empresa_tsolicitatarefa where bdcodemp = new.bdcodemp and bdcodst = new.bdcodst into :vcodigo;
    if (coalesce(vcodigo,0)=0) then
       exit;
  end
  -- Não importa onde a tarefa é gerada, SEMPRE gera nova chave
  vcodigo = 1;
  if (GEN_ID(GEN_VCT_TAREFAS, 0) = 0) then
     select coalesce(max(bdcodst), 0)+1 from vct_empresa_tsolicitatarefa into :vcodigo;
  NEW.bdcodst = GEN_ID(GEN_VCT_TAREFAS, :vcodigo);
END
^

CREATE OR ALTER TRIGGER VCT_ARQUIVOS_TAREFAS_BI0 FOR VCT_ARQUIVOS_TAREFAS
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vID INTEGER;
BEGIN
  vID = 1;
  if (GEN_ID(GEN_VCT_ARQUIVOS, 0) = 0) then
     select coalesce(max(bdid), 0) + 1 from VCT_ARQUIVOS_TAREFAS into :vID;
  NEW.bdid = GEN_ID(gen_vct_arquivos,  :vID);
END
^

CREATE OR ALTER TRIGGER VCT_ARQUIVOS_TAREFAS_BU0 FOR VCT_ARQUIVOS_TAREFAS
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  if ((new.bdcodst is null) and (old.bdcodst is not null)) then
     new.bdstatus = null;
end
^

CREATE OR ALTER TRIGGER VCT_PLANO_TRIBUTARIO_AI0 FOR VCT_PLANO_TRIBUTARIO
ACTIVE AFTER INSERT POSITION 0 
AS
BEGIN
  INSERT INTO vct_tributos_plano_tributario
  SELECT 1 AS BDCODTRIB,
         NEW.bdcodplatrib AS BDCODPLATRIB, BDCODIMP, BDCODSER, BDCODOBR
  FROM vct_tributos_plano_tributario
  WHERE BDCODPLATRIB = NEW.bdcodplatribcopia;
END
^

CREATE OR ALTER TRIGGER VCT_PLANO_TRIBUTARIO_BI0 FOR VCT_PLANO_TRIBUTARIO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodplatrib IS NULL) OR (NEW.bdcodplatrib = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodplatrib)+1),1) FROM vct_plano_tributario INTO vcodigo;
       NEW.bdcodplatrib = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodplatrib FROM vct_plano_tributario WHERE bdcodplatrib = NEW.bdcodplatrib INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodplatrib)+1),1) FROM vct_plano_tributario INTO vcodigo;
            NEW.bdcodplatrib = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VCT_TRIBUTARIO_EMPRESA_BU0 FOR VCT_TRIBUTARIO_EMPRESA
ACTIVE BEFORE UPDATE OR DELETE POSITION 1
AS
  declare variable vtributos boolean;
  declare variable vcodemp integer;
  declare variable vcodempaux integer;
  declare variable vMsg varchar(200);
  declare variable vmsgref varchar(100);
  declare variable vTipoAcao integer;
  declare variable vtemlancamento smallint;
  declare variable vsql varchar(1000);
  declare variable vcount integer;
  declare variable vrefstr varchar(7);
begin
  vtemlancamento = 0;
  /* extraindo informações para compor no log */
  if (old.bdcodemp is null) then
  begin
    vTipoAcao = 0;
    vcodemp = new.bdcodemp;
    vmsg = 'Inserção ';
    if (new.bdcodimp is not null) then
       vMsg = vmsg||'do imposto: '||coalesce(new.bdcodimp, 0);
    else
    if (new.bdcodobr is not null) then
       vMsg = vmsg||'da obrigação: '||coalesce(new.bdcodobr, 0);
    else
    if (new.bdcodser is not null) then
       vMsg = vmsg||'do serviço: '||coalesce(new.bdcodser, 0);
 if (new.bdcodproc is not null) then
    vMsg = vmsg||' Processo: '||new.bdcodproc;
    if (new.bdcodemp is not null) then
       vmsg = vmsg||' Empresa: '||coalesce(new.bdcodemp, 0);
    vmsg = vmsg||' [Competência inicial] '||coalesce(new.bdrefini, 'vazio');
    vmsg = vmsg||' [Competência final] '||coalesce(new.bdreffin, 'vazio');
  end
  else
  begin
     vTipoAcao = 2;
    vcodemp = old.bdcodemp;
    if (new.bdcodemp is null) then
    begin
      vmsg = 'Exclusão ';
    end
    else
    begin
      vTipoAcao = 1;
      vmsg = 'Alteração ';
    end

    if (old.bdcodimp is not null) then
       vmsg = vmsg||'do imposto: '|| coalesce(old.bdcodimp, 0);
    else
    if (old.bdcodobr is not null) then
       vmsg = vmsg||'da obrigação: '||coalesce(old.bdcodobr,0);
    else
    if (old.bdcodser is not null) then
       vmsg = vmsg||'do serviço: '||coalesce(old.bdcodser,0);
 if (old.bdcodproc is not null) then
    vMsg = vmsg||' Processo: '||old.bdcodproc;
    if (old.bdcodemp is not null) then
       vmsg = vmsg||' Empresa: '||coalesce(old.bdcodemp,0);

    vmsgref = ' [Competência inicial] '||coalesce(old.bdrefini, 'vazio');
    if (new.bdcodemp is not null) then
       vmsgref = vmsgref||' [Para] '||coalesce(new.bdrefini, 'vazio')||']';
    vmsgref = vmsgref||' [Competência final] '||coalesce(old.bdreffin, 'vazio');
    if (new.bdcodemp is not null) then
       vmsgref = vmsgref||' [Para] '||coalesce(new.bdreffin, 'vazio')||']';
  end


  if ((((new.bdcodemp is null)and(old.bdcodemp is not null)) or -- Exclusão
       ((new.bdcodemp is not null) and (old.bdcodemp is not null)))and -- alteração
      ((coalesce(old.bdreffin,0)>0)or(coalesce(new.bdreffin,0)>0))) then
  begin
    vcount = 1;
    while (vcount <= 2) do
    begin
      vsql = 'select first 1 bdcodst from vct_empresa_tsolicitatarefa ';
      if (old.bdcodemp is not null) then
      vsql = vsql||'where bdcodemp = '||old.bdcodemp ;
      else
         vsql = vsql||'where bdcodemp = '||new.bdcodemp;
      if (vcount = 1) then
         vsql = vsql||' and bdrefsol >= '||old.bdrefini;
      else
      if (new.bdcodemp is null) then
      begin
        vsql = vsql||' and bdrefsol > '||old.bdreffin;
        vrefstr = old.bdreffin;
      end
      else
      begin
        vsql = vsql||' and bdrefsol > '||new.bdreffin;
        vrefstr = new.bdreffin;
      end

      if (old.bdcodimp is not null) then
         vsql = vsql||' and bdcodimp = '||old.bdcodimp;
      else
      if (new.bdcodimp is not null) then
         vsql = vsql||' and bdcodimp = '||new.bdcodimp;
      else
      if (old.bdcodobr is not null) then
         vsql = vsql||' and bdcodobrigacao = '||old.bdcodobr;
      else
      if (new.bdcodobr is not null) then
         vsql = vsql||' and bdcodobrigacao = '||new.bdcodobr;
      else
      if (old.bdcodser is not null) then
         vsql = vsql||' and bdcodservico = '||old.bdcodser;
      else
      if (new.bdcodser is not null) then
         vsql = vsql||' and bdcodservico = '||new.bdcodser;
  
   if (old.bdcodproc is not null) then
    vsql = vsql||' and bdcodproc = '||old.bdcodproc;
      else
      if (new.bdcodproc is not null) then
         vsql = vsql||' and bdcodproc = '||new.bdcodproc;
  
      vcodempaux = null;
      execute statement vsql into :vcodempaux;

      -- na referência inicial, se retornar dados, é porque há lançamentos
      if ((vcount = 1) and (coalesce(:vcodempaux, 0) > 0)) then
         vtemlancamento = 1;
      else
      -- na referência final, se não houver lançamentos, finaliza sem exceção
      if ((vcount = 2) and (coalesce(:vcodempaux, 0) = 0)) then
         vtemlancamento = 0;

      -- se não houver referência final, finaliza nesse momento com exceção
      if ((coalesce(new.bdcodemp,0)=0) and (coalesce(old.bdreffin,0)=0)) then
         break;
      else
      if (((new.bdcodemp is not null) and (old.bdcodemp is not null)) and (coalesce(new.bdreffin,0)=0)) then
      begin
        vtemlancamento = 0;
        break;
      end

      vcount = vcount + 1;
    end

    vrefstr = substring(vrefstr from 5 for 2)||'/'||substring(vrefstr from 1 for 4);
    if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE' and vtemlancamento > 0) then
       EXCEPTION EX_CUSTOM vmsg||'. Não pode ser realizado porque há tarefas lançadas no período. Deverá indicar a referência final igual, ou maior, ou excluir as tarefas lançadas a partir da competência '||vrefstr||'.';
  end

  EXECUTE PROCEDURE SP_INSERIR_LOG(:vcodemp, NULL, (select bdcodusu from VW_USUARIOS_SECAO),
                                   NULL, (select bdcodsis from VW_GET_MODULO), NULL, null, null,
                                   :vmsg,
                                   0, :vtipoacao, null, null, (select BDNOMETELA from vw_get_processo),
                                   (select BDCAPTIONTELA from vw_get_processo), NULL,
                                   'VCT_TRIBUTARIO_EMPRESA', null, 'FALSE', current_date);
end
^

/* Augusto - 23/09/2024 - #208339 - Criado exclusão nas tabelas de usuarios para não ocorrer da tarefa ser excluida e logo em
                                    seguida o usuario cria ela novamente e trás os usuários antigos */
CREATE OR ALTER trigger vct_tributario_empresa_bud0 for vct_tributario_empresa
active before delete position 2
AS
begin
  if (old.bdcodimp is not null) then
     delete from VCT_EMPRESA_USUARIO_IMP imp  where imp.bdcodemp = old.bdcodemp and imp.bdcodimp = old.BDCODIMP;
  else
  if (old.bdcodobr is not null) then
     delete from vct_empresa_usuario_obr obr where obr.bdcodemp = old.bdcodemp and obr.BDCODOBRSER = old.bdcodobr;
  else
     delete from vct_empresa_usuario_ser ser where ser.bdcodemp = old.bdcodemp and ser.BDCODOBRSER = old.bdcodser;
end^

CREATE OR ALTER trigger vct_tributario_empresa_bi0 for vct_tributario_empresa
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
  BEGIN
    SELECT COALESCE((MAX(bdchave)+1),1) FROM vct_tributario_empresa WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;
    NEW.bdchave = vcodigo;
  END
  ELSE
  BEGIN
    SELECT bdchave FROM vct_tributario_empresa WHERE bdchave = NEW.bdchave AND bdcodemp = NEW.bdcodemp INTO vcodigo;

    IF (vcodigo > 0) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1),1) FROM vct_tributario_empresa WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;
      NEW.bdchave = vcodigo;
    END
  END

  -- gilberto - ALT:#10115 - dias úteis para entrega
  IF ((NEW.bdcodser IS NOT NULL) AND (NEW.bdentrega IS NULL)) THEN --#150975 - Antony Rairon - adicionado bdentrega ao if
     SELECT bdentrega FROM vct_base_servico WHERE bdcodobrser = NEW.bdcodser INTO NEW.bdentrega;
  ELSE
  IF ((NEW.bdcodobr IS NOT NULL) AND (NEW.bdentrega IS NULL)) THEN
     SELECT bdentrega FROM vct_base_obrigacao WHERE bdcodobrser = NEW.bdcodser INTO NEW.bdentrega;
  else
  if ((new.bdcodimp is not null) and (NEW.bdentrega IS NULL)) then
     select bdentrega from timposto where bdcodimp = new.bdcodimp into new.bdentrega;
END^

CREATE OR ALTER TRIGGER VCT_TRIBUTOS_PLANO_TRIBUT_BI0 FOR VCT_TRIBUTOS_PLANO_TRIBUTARIO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vcount INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodtrib IS NULL) OR (NEW.bdcodtrib = 0)) THEN
    BEGIN
      vcount = 0;
      FOR SELECT bdcodtrib FROM vct_tributos_plano_tributario ORDER BY bdcodtrib INTO :vcodigo DO
         BEGIN
           IF (vcodigo <> vcount) THEN
              BEGIN
                NEW.bdcodtrib = vcount;
                BREAK;
              END
           vcount = vcount + 1;
         END

      IF (NEW.bdcodtrib IS NULL) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodtrib)+1),1) FROM VCT_TRIBUTOS_PLANO_TRIBUTARIO INTO vcodigo;
           NEW.bdcodtrib = vcodigo;
         END
    END
  ELSE
    BEGIN
       SELECT bdcodtrib FROM VCT_TRIBUTOS_PLANO_TRIBUTARIO WHERE bdcodtrib = NEW.bdcodtrib INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodtrib)+1),1) FROM VCT_TRIBUTOS_PLANO_TRIBUTARIO INTO vcodigo;
            NEW.bdcodtrib = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER vct_empresa_protocolosaida_bd0 FOR vct_empresa_protocolosaida
ACTIVE BEFORE DELETE POSITION 0
AS
  DECLARE VARIABLE vcodst INTEGER;
BEGIN
  FOR SELECT BDCODST FROM (SELECT TAR.BDCODST,
                                  CASE WHEN ((tar.bddatafim IS NOT NULL) AND (tar.BDAGUARD IS NOT NULL)) THEN 5 -- aguardando
                                              WHEN ((tar.bddatafim IS NOT NULL) AND (this.bdstatus = 4)) THEN 3 -- finalizada
                                              WHEN (this.bdstatus = 3) THEN 2 -- pauzada
                                              WHEN (this.bdstatus IN (1,2)) THEN 1 -- iniciada
                                              WHEN (tar.bdentrega <= CURRENT_DATE) THEN 4 -- atrasada
                                              ELSE 0 -- sem alteracao
                                         END AS bdSTATUS
                           FROM vct_empresa_tsolicitatarefa TAR
                           INNER JOIN VCT_EMPRESA_PROTOCOLO_TAREFA PT ON (PT.BDCODEMP = TAR.BDCODEMP AND PT.BDCODST = TAR.BDCODST AND PT.BDCODPTS = OLD.BDCODPTS)
                           LEFT OUTER JOIN VCT_EMPRESA_THISTORICOTAREFA THIS ON (THIS.BDCODEMP = TAR.BDCODEMP AND THIS.BDCODST = TAR.BDCODST AND THIS.BDCODHT = (SELECT FIRST 1 BDCODHT
                                                                                                                                                                 FROM VCT_EMPRESA_THISTORICOTAREFA
                                                                                                                                                                 WHERE BDCODEMP = THIS.BDCODEMP AND
                                                                                                                                                                       BDCODST = THIS.BDCODST
                                                                                                                                                                 ORDER BY BDCODHT DESC))
                           WHERE TAR.BDCODEMP = OLD.BDCODEMP
      ) WHERE BDSTATUS IN (0,4)
      INTO :vcodst DO
      BEGIN
        IF (vcodst IS NOT NULL) THEN
           DELETE FROM vct_empresa_tsolicitatarefa WHERE bdcodemp = OLD.bdcodemp AND bdcodst = :vcodst;
        ELSE
           EXCEPTION ex_delete 'PROTOCOLO_TAREFA';
      END
END^

CREATE OR ALTER TRIGGER VEF_BASE_TCADIMPOSTOSN_BI0 FOR VEF_BASE_TCADIMPOSTOSN
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODIMPOSTO IS NULL) OR (NEW.BDCODIMPOSTO = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODIMPOSTO)+1),1) FROM VEF_BASE_TCADIMPOSTOSN INTO vcodigo;
        NEW.BDCODIMPOSTO = vcodigo;
     END
END
^

CREATE OR ALTER TRIGGER vef_base_tcadinfcom_bi0 FOR vef_base_tcadinfcom
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  IF ((NEW.bdcodtipo = 101) OR (NEW.bdcodtipo = 102)) THEN
     BEGIN
       vCodigo = 0;
       IF ((NEW.bdordeminfcom IS NULL) OR (NEW.bdordeminfcom = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(bdORDEMINFCOM) + 1), 1) FROM vef_base_tcadinfcom  INTO vCodigo;
           NEW.bdordeminfcom = vCodigo;
         END
       ELSE
         BEGIN
           SELECT bdordeminfcom FROM vef_base_tcadinfcom WHERE bdordeminfcom = NEW.bdordeminfcom INTO vCodigo;
           IF (vCodigo > 0) THEN
             BEGIN
               SELECT COALESCE((MAX(bdordeminfcom) + 1), 1) FROM vef_base_tcadinfcom  INTO vCodigo;
               NEW.bdordeminfcom = vCodigo;
             END
        END
     END

  NEW.BDDESCINFCOMHASH = HASH(UPPER(NEW.BDDESCINFCOM));
  if (NEW.bdsonumeros IS null) then
    NEW.BDSONUMEROS      =  (select BDRESULT from  SONUMEROS(NEW.BDCODINFCOM));

END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCADINFCOM_BD0 FOR VEF_BASE_TCADINFCOM
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  /* Trigger text */
  DELETE FROM TMP_VEF_BASE_TCADINFCOM WHERE BDEDITCHAVE = OLD.bdordeminfcom;
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCADMAQMRC_BI0 FOR VEF_BASE_TCADMAQMRC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdordemmaq IS NULL) OR (NEW.bdordemmaq = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordemmaq) + 1), 1) FROM  vef_base_tcadmaqmrc WHERE bdcodemp = NEW.bdcodemp INTO vCodigo;
       NEW.bdordemmaq = vCodigo;
     END
  ELSE
     BEGIN
       SELECT bdordemmaq FROM vef_base_tcadmaqmrc WHERE bdordemmaq = NEW.bdordemmaq AND bdcodemp = NEW.bdcodemp INTO vCodigo;

       IF (vCodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdordemmaq) + 1), 1) FROM vef_base_tcadmaqmrc WHERE bdcodemp = NEW.bdcodemp INTO vCodigo;
            NEW.bdordemmaq = vCodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCADOREC_BI0 FOR VEF_BASE_TCADOREC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodorec IS NULL) OR (NEW.bdcodorec = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodorec)+1),1) FROM VEF_BASE_TCADOREC INTO vcodigo;
        NEW.bdcodorec = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodorec FROM VEF_BASE_TCADOREC WHERE bdcodorec = NEW.bdcodorec INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodorec)+1),1) FROM VEF_BASE_TCADOREC INTO vcodigo;
            NEW.bdcodorec = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCADTIPODEMDOC_BI0 FOR VEF_BASE_TCADTIPODEMDOC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodtipodoc IS NULL) OR (NEW.bdcodtipodoc = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodtipodoc)+1),1) FROM VEF_BASE_TCADTIPODEMDOC INTO vcodigo;
        NEW.bdcodtipodoc = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodtipodoc FROM VEF_BASE_TCADTIPODEMDOC WHERE bdcodtipodoc = NEW.bdcodtipodoc INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodtipodoc)+1),1) FROM VEF_BASE_TCADTIPODEMDOC INTO vcodigo;
            NEW.bdcodtipodoc = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCADTIPOIMPOSTO_BI0 FOR VEF_BASE_TCADTIPOIMPOSTO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODTIPOIMPOSTO IS NULL) OR (NEW.BDCODTIPOIMPOSTO = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODTIPOIMPOSTO)+1),1) FROM VEF_BASE_TCADTIPOIMPOSTO INTO vcodigo;
        NEW.BDCODTIPOIMPOSTO = vcodigo;
     END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONF_SN_BI0 FOR VEF_BASE_TCONF_SN
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodconfsimpnac IS NULL) OR (NEW.bdcodconfsimpnac = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodconfsimpnac)+1),1) FROM vef_base_tconf_sn INTO vcodigo;
        NEW.bdcodconfsimpnac = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodconfsimpnac FROM vef_base_tconf_sn WHERE bdcodconfsimpnac = NEW.bdcodconfsimpnac INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodconfsimpnac)+1),1) FROM vef_base_tconf_sn  WHERE bdcodconfsimpnac = NEW.bdcodconfsimpnac INTO vcodigo;
           NEW.bdcodconfsimpnac = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONF_SN_FORM_BI0 FOR VEF_BASE_TCONF_SN_FORM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vnumcamposimpnac INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumcamposimpnac IS NULL) OR (NEW.bdnumcamposimpnac = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdnumcamposimpnac)+1), 1) FROM vef_base_tconf_sn_form
      WHERE (bdcodconfsimpnac = NEW.bdcodconfsimpnac) AND (bdcodqsimpnac = NEW.bdcodqsimpnac) INTO vnumcamposimpnac;
      NEW.bdnumcamposimpnac = vnumcamposimpnac;
    END
  ELSE
    BEGIN
       SELECT bdnumcamposimpnac FROM vef_base_tconf_sn_form
       WHERE (bdnumcamposimpnac = NEW.bdnumcamposimpnac) AND (bdcodconfsimpnac = NEW.bdcodconfsimpnac) AND (bdcodqsimpnac = NEW.bdcodqsimpnac) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumcamposimpnac)+1), 1) FROM vef_base_tconf_sn_form
           WHERE (bdcodconfsimpnac = NEW.bdcodconfsimpnac) AND (bdcodqsimpnac = NEW.bdcodqsimpnac) INTO vnumcamposimpnac;
           NEW.bdnumcamposimpnac = vnumcamposimpnac;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONF_SN_Q_BI0 FOR VEF_BASE_TCONF_SN_Q
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodqsimpnac IS NULL) OR (NEW.bdcodqsimpnac = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodqsimpnac)+1),1) FROM vef_base_tconf_sn_q INTO vcodigo;
        NEW.bdcodqsimpnac = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodqsimpnac FROM vef_base_tconf_sn_q WHERE bdcodqsimpnac = NEW.bdcodqsimpnac INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodqsimpnac)+1),1) FROM vef_base_tconf_sn_q  WHERE bdcodqsimpnac = NEW.bdcodqsimpnac INTO vcodigo;
           NEW.bdcodqsimpnac = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFATIVA_BI0 FOR VEF_BASE_TCONFATIVA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodconfativo IS NULL) OR (NEW.bdcodconfativo = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodconfativo)+1),1) FROM vef_base_tconfativa INTO vcodigo;
        NEW.bdcodconfativo = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodconfativo FROM vef_base_tconfativa WHERE bdcodconfativo = NEW.bdcodconfativo INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodconfativo)+1),1) FROM vef_base_tconfativa WHERE bdcodconfativo = NEW.bdcodconfativo INTO vcodigo;
           NEW.bdcodconfativo = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFATIVAFORM_BI0 FOR VEF_BASE_TCONFATIVAFORM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNumCampo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumcampo IS NULL) OR (NEW.bdnumcampo = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdnumcampo)+1), 1) FROM vef_base_tconfativaform
      WHERE (bdcodconfativo = NEW.bdcodconfativo) INTO vnumcampo;
      NEW.bdnumcampo = vnumcampo;
    END
  ELSE
    BEGIN
       SELECT bdnumcampo FROM vef_base_tconfativaform
       WHERE (bdnumcampo = NEW.bdnumcampo) AND (bdcodconfativo = NEW.bdcodconfativo) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumcampo)+1), 1) FROM vef_base_tconfativaform
           WHERE (bdcodconfativo = NEW.bdcodconfativo) INTO vnumcampo;
           NEW.bdnumcampo = vnumcampo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFBLOCOP_BI0 FOR VEF_BASE_TCONFBLOCOP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODCONFBLOCOP IS NULL) OR (NEW.BDCODCONFBLOCOP = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODCONFBLOCOP)+1),1) FROM VEF_BASE_TCONFBLOCOP INTO vcodigo;
        NEW.BDCODCONFBLOCOP = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODCONFBLOCOP FROM VEF_BASE_TCONFBLOCOP WHERE BDCODCONFBLOCOP = NEW.BDCODCONFBLOCOP INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODCONFBLOCOP)+1),1) FROM VEF_BASE_TCONFBLOCOP INTO vcodigo;
            NEW.BDCODCONFBLOCOP = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFBLOCOPFORM_BI0 FOR VEF_BASE_TCONFBLOCOPFORM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumcampoBLOCOP IS NULL) OR (NEW.bdnumcampoBLOCOP = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdnumcampoBLOCOP)+1),1) FROM VEF_BASE_TCONFBLOCOPFORM
        WHERE bdcodconfBLOCOP = NEW.bdcodconfBLOCOP
        AND bdcodqBLOCOP = NEW.bdcodqBLOCOP
        INTO vcodigo;
        NEW.bdnumcampoBLOCOP = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdnumcampoBLOCOP FROM VEF_BASE_TCONFBLOCOPFORM
       WHERE bdcodconfBLOCOP = NEW.bdcodconfBLOCOP
       AND bdcodqBLOCOP = NEW.bdcodqBLOCOP
       AND bdnumcampoBLOCOP = NEW.bdnumcampoBLOCOP
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumcampoBLOCOP)+1),1) FROM VEF_BASE_TCONFBLOCOPFORM
           WHERE bdcodconfBLOCOP = NEW.bdcodconfBLOCOP
           AND bdcodqBLOCOP = NEW.bdcodqBLOCOP
           INTO vcodigo;
           NEW.bdnumcampoBLOCOP = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFBLOCOPQ_BI0 FOR VEF_BASE_TCONFBLOCOPQ
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vAux INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODQBLOCOP IS NULL) OR (NEW.BDCODQBLOCOP = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODQBLOCOP)+1),1) FROM VEF_BASE_TCONFBLOCOPQ INTO vcodigo;
        NEW.BDCODQBLOCOP = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODQBLOCOP FROM VEF_BASE_TCONFBLOCOPQ WHERE BDCODQBLOCOP = NEW.BDCODQBLOCOP INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODQBLOCOP)+1),1) FROM VEF_BASE_TCONFBLOCOPQ INTO vcodigo;
            NEW.BDCODQBLOCOP = vcodigo;
         END
    END

   /* ADICIONA AUTOMATICAMENTO O CODIGO PRINCIPAL DA CLASSIFICACAO... */
   SELECT FIRST 1 tpos.pos FROM pos('.',  NEW.BDCLASSIFICACAO) tpos INTO :vaux;

   IF (vaux > 1) THEN /* classificacao titulo */
      BEGIN
        SELECT BDCODQBLOCOP FROM VEF_BASE_TCONFBLOCOPQ WHERE bdclassificacao = SUBSTRING(NEW.bdclassificacao FROM 1 FOR :vaux-1) INTO vcodigo;
        NEW.BDCODQBLOCOPPRINC = vcodigo;
      END
   ELSE
     BEGIN
        NEW.BDCODQBLOCOPPRINC = NEW.bdcodqBLOCOP;
     END


END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFBLOCOPQ_BU0 FOR VEF_BASE_TCONFBLOCOPQ
ACTIVE BEFORE UPDATE POSITION 0 
AS
DECLARE VARIABLE vCodigo INTEGER;
DECLARE VARIABLE vaux INTEGER;
BEGIN
  /* Trigger text */

   /* ADICIONA AUTOMATICAMENTO O CODIGO PRINCIPAL DA CLASSIFICACAO... */
   SELECT FIRST 1 tpos.pos FROM pos('.',  NEW.BDCLASSIFICACAO) tpos INTO :vaux;

   IF (vaux > 1) THEN /* classificacao titulo */
      BEGIN
        SELECT BDCODQBLOCOP FROM VEF_BASE_TCONFBLOCOPQ WHERE bdclassificacao = SUBSTRING(NEW.bdclassificacao FROM 1 FOR :vaux-1) INTO vcodigo;
        NEW.BDCODQBLOCOPPRINC = vcodigo;
      END
   ELSE
     BEGIN
        NEW.BDCODQBLOCOPPRINC = NEW.bdcodqBLOCOP;
     END

END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFCIAP_BI0 FOR VEF_BASE_TCONFCIAP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODCONFCIAP IS NULL) OR (NEW.BDCODCONFCIAP = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODCONFCIAP)+1),1) FROM VEF_BASE_TCONFCIAP INTO vcodigo;
        NEW.BDCODCONFCIAP = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODCONFCIAP FROM VEF_BASE_TCONFCIAP WHERE BDCODCONFCIAP = NEW.BDCODCONFCIAP INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODCONFCIAP)+1),1) FROM VEF_BASE_TCONFCIAP INTO vcodigo;
            NEW.BDCODCONFCIAP = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFCIAPFORM_BI0 FOR VEF_BASE_TCONFCIAPFORM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumcampoCIAP IS NULL) OR (NEW.bdnumcampoCIAP = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdnumcampoCIAP)+1),1) FROM VEF_BASE_TCONFCIAPFORM
        WHERE bdcodconfCIAP = NEW.bdcodconfCIAP
        AND bdcodqciap = NEW.bdcodqciap
        INTO vcodigo;
        NEW.bdnumcampoCIAP = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdnumcampoCIAP FROM VEF_BASE_TCONFCIAPFORM
       WHERE bdcodconfCIAP = NEW.bdcodconfCIAP
       AND bdcodqciap = NEW.bdcodqciap
       AND bdnumcampoCIAP = NEW.bdnumcampoCIAP
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumcampoCIAP)+1),1) FROM VEF_BASE_TCONFCIAPFORM
           WHERE bdcodconfCIAP = NEW.bdcodconfCIAP
           AND bdcodqciap = NEW.bdcodqciap
           INTO vcodigo;
           NEW.bdnumcampoCIAP = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFCIAPQ_BI0 FOR VEF_BASE_TCONFCIAPQ
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vAux INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODQCIAP IS NULL) OR (NEW.BDCODQCIAP = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODQCIAP)+1),1) FROM VEF_BASE_TCONFCIAPQ INTO vcodigo;
        NEW.BDCODQCIAP = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODQCIAP FROM VEF_BASE_TCONFCIAPQ WHERE BDCODQCIAP = NEW.BDCODQCIAP INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODQCIAP)+1),1) FROM VEF_BASE_TCONFCIAPQ INTO vcodigo;
            NEW.BDCODQCIAP = vcodigo;
         END
    END

   /* ADICIONA AUTOMATICAMENTO O CODIGO PRINCIPAL DA CLASSIFICACAO... */
   SELECT FIRST 1 tpos.pos FROM pos('.',  NEW.BDCLASSIFICACAO) tpos INTO :vaux;

   IF (vaux > 1) THEN /* classificacao titulo */
      BEGIN
        SELECT BDCODQCIAP FROM VEF_BASE_TCONFCIAPQ WHERE bdclassificacao = SUBSTRING(NEW.bdclassificacao FROM 1 FOR :vaux-1) INTO vcodigo;
        NEW.BDCODQCIAPPRINC = vcodigo;
      END
   ELSE
     BEGIN
        NEW.BDCODQCIAPPRINC = NEW.bdcodqCIAP;
     END


END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFCIAPQ_BU0 FOR VEF_BASE_TCONFCIAPQ
ACTIVE BEFORE UPDATE POSITION 0 
AS
DECLARE VARIABLE vCodigo INTEGER;
DECLARE VARIABLE vaux INTEGER;
BEGIN
  /* Trigger text */

   /* ADICIONA AUTOMATICAMENTO O CODIGO PRINCIPAL DA CLASSIFICACAO... */
   SELECT FIRST 1 tpos.pos FROM pos('.',  NEW.BDCLASSIFICACAO) tpos INTO :vaux;

   IF (vaux > 1) THEN /* classificacao titulo */
      BEGIN
        SELECT BDCODQCIAP FROM VEF_BASE_TCONFCIAPQ WHERE bdclassificacao = SUBSTRING(NEW.bdclassificacao FROM 1 FOR :vaux-1) INTO vcodigo;
        NEW.BDCODQCIAPPRINC = vcodigo;
      END
   ELSE
     BEGIN
        NEW.BDCODQCIAPPRINC = NEW.bdcodqCIAP;
     END

END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFDACON_BI0 FOR VEF_BASE_TCONFDACON
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODCONFDACON IS NULL) OR (NEW.BDCODCONFDACON = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODCONFDACON)+1),1) FROM VEF_BASE_TCONFDACON INTO vcodigo;
        NEW.BDCODCONFDACON = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODCONFDACON FROM VEF_BASE_TCONFDACON WHERE BDCODCONFDACON = NEW.BDCODCONFDACON INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODCONFDACON)+1),1) FROM VEF_BASE_TCONFDACON INTO vcodigo;
            NEW.BDCODCONFDACON = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFDACONFORM_BI0 FOR VEF_BASE_TCONFDACONFORM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumcampoDACON IS NULL) OR (NEW.bdnumcampoDACON = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdnumcampoDACON)+1),1) FROM VEF_BASE_TCONFDACONFORM
        WHERE bdcodconfDACON = NEW.bdcodconfDACON AND BDCODQDACON = NEW.bdcodqdacon
        INTO vcodigo;
        NEW.bdnumcampoDACON = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdnumcampoDACON FROM VEF_BASE_TCONFDACONFORM
       WHERE bdcodconfDACON = NEW.bdcodconfDACON AND BDCODQDACON = NEW.bdcodqdacon
       AND bdnumcampoDACON = NEW.bdnumcampoDACON
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumcampoDACON)+1),1) FROM VEF_BASE_TCONFDACONFORM
           WHERE bdcodconfDACON = NEW.bdcodconfDACON AND BDCODQDACON = NEW.bdcodqdacon
           INTO vcodigo;
           NEW.bdnumcampoDACON = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFDACONQ_BI0 FOR VEF_BASE_TCONFDACONQ
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vAux INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODQDACON IS NULL) OR (NEW.BDCODQDACON = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODQDACON)+1),1) FROM VEF_BASE_TCONFDACONQ INTO vcodigo;
        NEW.BDCODQDACON = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODQDACON FROM VEF_BASE_TCONFDACONQ WHERE BDCODQDACON = NEW.BDCODQDACON INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODQDACON)+1),1) FROM VEF_BASE_TCONFDACONQ INTO vcodigo;
            NEW.BDCODQDACON = vcodigo;
         END
    END

   /* ADICIONA AUTOMATICAMENTO O CODIGO PRINCIPAL DA CLASSIFICACAO... */
   SELECT FIRST 1 tpos.pos FROM pos('.',  NEW.BDCLASSIFICACAO) tpos INTO :vaux;

   IF (vaux > 1) THEN /* classificacao titulo */
      BEGIN
        SELECT BDCODQDACON FROM VEF_BASE_TCONFDACONQ WHERE (BDCODCONFDACON = NEW.bdcodconfdacon) AND (bdclassificacao = SUBSTRING(NEW.bdclassificacao FROM 1 FOR :vaux-1)) INTO vcodigo;
        NEW.BDCODQDACONPRINC = vcodigo;
      END
   ELSE
     BEGIN
        NEW.BDCODQDACONPRINC = NEW.bdcodqDACON;
     END


END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFDACONQ_BU0 FOR VEF_BASE_TCONFDACONQ
ACTIVE BEFORE UPDATE POSITION 0 
AS
DECLARE VARIABLE vCodigo INTEGER;
DECLARE VARIABLE vaux INTEGER;
BEGIN
  /* Trigger text */

   /* ADICIONA AUTOMATICAMENTO O CODIGO PRINCIPAL DA CLASSIFICACAO... */
   SELECT FIRST 1 tpos.pos FROM pos('.',  NEW.BDCLASSIFICACAO) tpos INTO :vaux;

   IF (vaux > 1) THEN /* classificacao titulo */
      BEGIN
        SELECT BDCODQDACON FROM VEF_BASE_TCONFDACONQ WHERE (BDCODCONFDACON = NEW.bdcodconfdacon) AND (bdclassificacao = SUBSTRING(NEW.bdclassificacao FROM 1 FOR :vaux-1)) INTO vcodigo;
        NEW.BDCODQDACONPRINC = vcodigo;
      END
   ELSE
     BEGIN
        NEW.BDCODQDACONPRINC = NEW.bdcodqDACON;
     END

END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFDAMEF_BI0 FOR VEF_BASE_TCONFDAMEF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodconfdamef IS NULL) OR (NEW.bdcodconfdamef = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodconfdamef)+1),1) FROM vef_base_tconfdamef INTO vcodigo;
        NEW.bdcodconfdamef = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodconfdamef FROM vef_base_tconfdamef WHERE bdcodconfdamef = NEW.bdcodconfdamef INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodconfdamef)+1),1) FROM vef_base_tconfdamef INTO vcodigo;
            NEW.bdcodconfdamef = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFDAMEFFORM_BI0 FOR VEF_BASE_TCONFDAMEFFORM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDNUMCAMPODAMEF IS NULL) OR (NEW.BDNUMCAMPODAMEF = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDNUMCAMPODAMEF)+1),1) FROM VEF_BASE_TCONFDAMEFFORM
        WHERE bdcodconfDAMEF = NEW.bdcodconfDAMEF
        AND BDCODQDAMEF = NEW.BDCODQDAMEF
        INTO vcodigo;
        NEW.BDNUMCAMPODAMEF = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDNUMCAMPODAMEF FROM VEF_BASE_TCONFDAMEFFORM
       WHERE bdcodconfDAMEF = NEW.bdcodconfDAMEF
       AND BDCODQDAMEF = NEW.BDCODQDAMEF
       AND BDNUMCAMPODAMEF = NEW.BDNUMCAMPODAMEF
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDNUMCAMPODAMEF)+1),1) FROM VEF_BASE_TCONFDAMEFFORM
           WHERE bdcodconfDAMEF = NEW.bdcodconfDAMEF
           AND BDCODQDAMEF = NEW.BDCODQDAMEF
           INTO vcodigo;
           NEW.BDNUMCAMPODAMEF = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFDAMEFQ_BI0 FOR VEF_BASE_TCONFDAMEFQ
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vAux INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODQDAMEF IS NULL) OR (NEW.BDCODQDAMEF = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODQDAMEF)+1),1) FROM VEF_BASE_TCONFDAMEFQ INTO vcodigo;
        NEW.BDCODQDAMEF = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODQDAMEF FROM VEF_BASE_TCONFDAMEFQ WHERE BDCODQDAMEF = NEW.BDCODQDAMEF INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODQDAMEF)+1),1) FROM VEF_BASE_TCONFDAMEFQ INTO vcodigo;
            NEW.BDCODQDAMEF = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFDASN_BI0 FOR VEF_BASE_TCONFDASN
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODCONFDASN IS NULL) OR (NEW.BDCODCONFDASN = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODCONFDASN)+1),1) FROM VEF_BASE_TCONFDASN INTO vcodigo;
        NEW.bdcodconfdasn = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODCONFDASN FROM VEF_BASE_TCONFDASN WHERE BDCODCONFDASN = NEW.BDCODCONFDASN INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODCONFDASN)+1),1) FROM VEF_BASE_TCONFDASN INTO vcodigo;
            NEW.BDCODCONFDASN = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFDASNFORM_BI0 FOR VEF_BASE_TCONFDASNFORM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumcampodasn IS NULL) OR (NEW.bdnumcampodasn = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdnumcampodasn)+1),1) FROM VEF_BASE_TCONFDASNFORM
        WHERE bdcodconfdasn = NEW.bdcodconfdasn
        AND bdcodqdasn = NEW.bdcodqdasn
        INTO vcodigo;
        NEW.bdnumcampodasn = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdnumcampodasn FROM VEF_BASE_TCONFDASNFORM
       WHERE bdcodconfdasn = NEW.bdcodconfdasn
       AND bdcodqdasn = NEW.bdcodqdasn
       AND bdnumcampodasn = NEW.bdnumcampodasn
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumcampodasn)+1),1) FROM VEF_BASE_TCONFDASNFORM
           WHERE bdcodconfdasn = NEW.bdcodconfdasn
           AND bdcodqdasn = NEW.bdcodqdasn
           INTO vcodigo;
           NEW.bdnumcampodasn = vcodigo;
         END
    END



END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFDASNQ_BI0 FOR VEF_BASE_TCONFDASNQ
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODQDASN IS NULL) OR (NEW.BDCODQDASN = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODQDASN)+1),1) FROM VEF_BASE_TCONFDASNQ INTO vcodigo;
        NEW.BDCODQDASN = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODQDASN FROM VEF_BASE_TCONFDASNQ WHERE BDCODQDASN = NEW.BDCODQDASN INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODQDASN)+1),1) FROM VEF_BASE_TCONFDASNQ INTO vcodigo;
            NEW.BDCODQDASN = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFICMSSPED_BI0 FOR VEF_BASE_TCONFICMSSPED
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODCONFICMSSPED IS NULL) OR (NEW.BDCODCONFICMSSPED = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODCONFICMSSPED)+1),1) FROM VEF_BASE_TCONFICMSSPED INTO vcodigo;
        NEW.BDCODCONFICMSSPED = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODCONFICMSSPED FROM VEF_BASE_TCONFICMSSPED WHERE BDCODCONFICMSSPED = NEW.BDCODCONFICMSSPED INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODCONFICMSSPED)+1),1) FROM VEF_BASE_TCONFICMSSPED INTO vcodigo;
            NEW.BDCODCONFICMSSPED = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFICMSSPEDFORM_BI0 FOR VEF_BASE_TCONFICMSSPEDFORM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumcampoICMSSPED IS NULL) OR (NEW.bdnumcampoICMSSPED = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdnumcampoICMSSPED)+1),1) FROM VEF_BASE_TCONFICMSSPEDFORM
        WHERE bdcodconfICMSSPED = NEW.bdcodconfICMSSPED
        AND bdcodqicmssped = NEW.bdcodqicmssped
        INTO vcodigo;
        NEW.bdnumcampoICMSSPED = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdnumcampoICMSSPED FROM VEF_BASE_TCONFICMSSPEDFORM
       WHERE bdcodconfICMSSPED = NEW.bdcodconfICMSSPED
       AND bdcodqicmssped = NEW.bdcodqicmssped
       AND bdnumcampoICMSSPED = NEW.bdnumcampoICMSSPED
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumcampoICMSSPED)+1),1) FROM VEF_BASE_TCONFICMSSPEDFORM
           WHERE bdcodconfICMSSPED = NEW.bdcodconfICMSSPED
           AND bdcodqicmssped = NEW.bdcodqicmssped
           INTO vcodigo;
           NEW.bdnumcampoICMSSPED = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFICMSSPEDQ_BI0 FOR VEF_BASE_TCONFICMSSPEDQ
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vAux INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODQICMSSPED IS NULL) OR (NEW.BDCODQICMSSPED = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODQICMSSPED)+1),1) FROM VEF_BASE_TCONFICMSSPEDQ INTO vcodigo;
        NEW.BDCODQICMSSPED = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODQICMSSPED FROM VEF_BASE_TCONFICMSSPEDQ WHERE BDCODQICMSSPED = NEW.BDCODQICMSSPED INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODQICMSSPED)+1),1) FROM VEF_BASE_TCONFICMSSPEDQ INTO vcodigo;
            NEW.BDCODQICMSSPED = vcodigo;
         END
    END

   /* ADICIONA AUTOMATICAMENTO O CODIGO PRINCIPAL DA CLASSIFICACAO... */
   SELECT FIRST 1 tpos.pos FROM pos('.',  NEW.BDCLASSIFICACAO) tpos INTO :vaux;

   IF (vaux > 1) THEN /* classificacao titulo */
      BEGIN
        SELECT BDCODQICMSSPED FROM VEF_BASE_TCONFICMSSPEDQ WHERE bdclassificacao = SUBSTRING(NEW.bdclassificacao FROM 1 FOR :vaux-1) INTO vcodigo;
        NEW.BDCODQICMSSPEDPRINC = vcodigo;
      END
   ELSE
     BEGIN
        NEW.BDCODQICMSSPEDPRINC = NEW.bdcodqICMSSPED;
     END


END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFICMSSPEDQ_BU0 FOR VEF_BASE_TCONFICMSSPEDQ
ACTIVE BEFORE UPDATE POSITION 0 
AS
DECLARE VARIABLE vCodigo INTEGER;
DECLARE VARIABLE vaux INTEGER;
BEGIN
  /* Trigger text */

   /* ADICIONA AUTOMATICAMENTO O CODIGO PRINCIPAL DA CLASSIFICACAO... */
   SELECT FIRST 1 tpos.pos FROM pos('.',  NEW.BDCLASSIFICACAO) tpos INTO :vaux;

   IF (vaux > 1) THEN /* classificacao titulo */
      BEGIN
        SELECT BDCODQICMSSPED FROM VEF_BASE_TCONFICMSSPEDQ WHERE bdclassificacao = SUBSTRING(NEW.bdclassificacao FROM 1 FOR :vaux-1) INTO vcodigo;
        NEW.BDCODQICMSSPEDPRINC = vcodigo;
      END
   ELSE
     BEGIN
        NEW.BDCODQICMSSPEDPRINC = NEW.bdcodqICMSSPED;
     END

END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFIPIFORM_BI0 FOR VEF_BASE_TCONFIPIFORM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumcampoipi IS NULL) OR (NEW.bdnumcampoipi = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdnumcampoipi)+1),1) FROM vef_base_tconfipiform
        WHERE bdcodconfipi = NEW.bdcodconfipi
        AND bdcodqipi = NEW.bdcodqipi
        INTO vcodigo;
        NEW.bdnumcampoipi = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdnumcampoipi FROM vef_base_tconfipiform
       WHERE bdcodconfipi = NEW.bdcodconfipi
       AND bdcodqipi = NEW.bdcodqipi
       AND bdnumcampoipi = NEW.bdnumcampoipi
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumcampoipi)+1),1) FROM vef_base_tconfipiform
           WHERE bdcodconfipi = NEW.bdcodconfipi
           AND bdcodqipi = NEW.bdcodqipi
           INTO vcodigo;
           NEW.bdnumcampoipi = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFIRLPFORM_BI0 FOR VEF_BASE_TCONFIRLPFORM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumcampoirlp IS NULL) OR (NEW.bdnumcampoirlp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdnumcampoirlp)+1),1) FROM VEF_BASE_TCONFIRLPFORM
        WHERE bdcodconfirlp = NEW.bdcodconfirlp
        AND bdcodqirlp = NEW.bdcodqirlp
        INTO vcodigo;
        NEW.bdnumcampoirlp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdnumcampoirlp FROM VEF_BASE_TCONFIRLPFORM
       WHERE bdcodconfirlp = NEW.bdcodconfirlp
       AND bdcodqirlp = NEW.bdcodqirlp
       AND bdnumcampoirlp = NEW.bdnumcampoirlp
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumcampoirlp)+1),1) FROM VEF_BASE_TCONFIRLPFORM
           WHERE bdcodconfirlp = NEW.bdcodconfirlp
           AND bdcodqirlp = NEW.bdcodqirlp
           INTO vcodigo;
           NEW.bdnumcampoirlp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TEMPCADATV_BI0 FOR VEF_BASE_TEMPCADATV
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018
        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018
            NEW.bdcodemp = vcodigo;
         END
    END
/*
  select first 1 BDREFEMP from SP_CONSULTA_EMP_POR_REF(new.bdcodemp, new.bdrefemp)
  into new.bdrefemp;

  delete from vef_base_tempcadatv tatv
  where tatv.bdcodemp = new.bdcodemp
  and tatv.bdrefemp = new.bdrefemp;
*/
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TEMPITEMSATV_BI0 FOR VEF_BASE_TEMPITEMSATV
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018
        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018
            NEW.bdcodemp = vcodigo;
         END
    END

/*
  select first 1 tsp.bdrefemp from SP_CONSULTA_EMP_POR_REF(new.bdcodemp, new.bdrefemp) tsp
  into new.bdrefemp;

  delete from vef_base_tempitemsatv tatv
  where tatv.bdcodemp = new.bdcodemp
  and tatv.bdrefemp = new.bdrefemp;
*/
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TEMPPAREST_BIO FOR VEF_BASE_TEMPPAREST
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018
        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TEMPPARESTES_BI0 FOR VEF_BASE_TEMPPARESTES
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END

END
^

CREATE OR ALTER TRIGGER VEF_BASE_TEMPPARESTMG_BI0 FOR VEF_BASE_TEMPPARESTMG
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TEMPPARESTPR_BI0 FOR VEF_BASE_TEMPPARESTPR
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TEMPPARESTRO_BI0 FOR VEF_BASE_TEMPPARESTRO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TEMPPARESTRJ_BI0 FOR VEF_BASE_TEMPPARESTRJ
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;
  IF ((NEW.BDCODEMP IS NULL) OR (NEW.BDCODEMP = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODEMP)),1) FROM TEMPRESAS
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.BDCODEMP = vCodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODEMP FROM TEMPRESAS WHERE BDCODEMP = NEW.BDCODEMP INTO vCodigo;

       IF (vCodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODEMP)),1) FROM TEMPRESAS
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.BDCODEMP = vCodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TEMPPARESTSC_BIO FOR VEF_BASE_TEMPPARESTSC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TEMPPARESTTO_BI0 FOR VEF_BASE_TEMPPARESTTO
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
  vCodigo = 0;
  IF ((NEW.BDCODEMP IS NULL) OR (NEW.BDCODEMP = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODEMP)),1) FROM TEMPRESAS
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.BDCODEMP = vCodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODEMP FROM TEMPRESAS WHERE BDCODEMP = NEW.BDCODEMP INTO vCodigo;

       IF (vCodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODEMP)),1) FROM TEMPRESAS
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.BDCODEMP = vCodigo;
         END
    END
end
^

CREATE OR ALTER TRIGGER VEF_BASE_TEMPPARESTSP_BI0 FOR VEF_BASE_TEMPPARESTSP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TEMPPARESTPE_BI0 FOR VEF_BASE_TEMPPARESTPE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo;

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo;

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TEMPPARFED_BIO FOR VEF_BASE_TEMPPARFED
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TEMPPARFEDPORATV_BI0 FOR VEF_BASE_TEMPPARFEDPORATV
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
/*
  select first 1 BDREFEMP from SP_CONSULTA_EMP_POR_REF(new.bdcodemp, new.bdrefemp)
  into new.bdrefemp;

  delete from VEF_BASE_TEMPPARFEDPORATV tatv
  where tatv.bdcodemp = new.bdcodemp
  and tatv.bdrefemp = new.bdrefemp;
*/
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TEMPPARGER_BIO FOR VEF_BASE_TEMPPARGER
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TEMPPARINTEG_BI0 FOR VEF_BASE_TEMPPARINTEG
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TNATBCPISCOFINS_BI0 FOR VEF_BASE_TNATBCPISCOFINS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdcodnatbc IS NULL) OR (NEW.bdcodnatbc = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdcodnatbc) + 1), 1) FROM VEF_BASE_TNATBCPISCOFINS  INTO vCodigo;
       NEW.bdcodnatbc = vCodigo;
     END
  ELSE
     BEGIN
       SELECT bdcodnatbc FROM VEF_BASE_TNATBCPISCOFINS WHERE bdcodnatbc = NEW.bdcodnatbc INTO vCodigo;

       IF (vCodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdcodnatbc) + 1), 1) FROM VEF_BASE_TNATBCPISCOFINS INTO vCodigo;
            NEW.bdcodnatbc = vCodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TNATOP_BU0 FOR VEF_BASE_TNATOP
ACTIVE BEFORE UPDATE POSITION 0 
AS
  DECLARE VARIABLE Str VARCHAR(20);
  DECLARE VARIABLE wAltNatOp DM_BOOLEAN;
BEGIN
  SELECT COALESCE(RDB$GET_CONTEXT('USER_SESSION', 'W_UPT_NATOP'), '') FROM RDB$DATABASE INTO :wAltNatOp;
  IF (:wAltNatOp <> 'TRUE') THEN
    EXCEPTION EX_NATOP_ALT;
    
  /* Trigger text */
  IF (CAST(SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 5) AS INTEGER) = 0) THEN
      -- 1
      NEW.bdclassificacao = SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1);
  ELSE
    BEGIN
      IF (CAST(SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 3) AS INTEGER) IN (100,150,200,250,300,350,400,450,500,550,600,650,700,750,800,850,900,950)) THEN
        --1.100
        NEW.bdclassificacao =  SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1) || '.' || SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 3);
      ELSE
        BEGIN
            IF (CAST(SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 3 FOR 2) AS INTEGER) < 50 ) THEN
              str = SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 1) ||'00';
            ELSE
              str = SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 1) ||'50';
    
            IF (CAST(SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 5 FOR 3) AS INTEGER) = 0) THEN
              --1.100.101
              NEW.bdclassificacao = SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1) || '.' ||str||'.'|| SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 3);-- substring( cast(new.bdcodnat as varchar(7)) from 2 for 3);
            ELSE
              --1.100.101.001
              NEW.bdclassificacao = SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1) || '.' ||str||'.'|| SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 2 FOR 3)||'.'|| SUBSTRING( CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 5 FOR 3);
        END

    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTAB_NATREC_BI0 FOR VEF_BASE_TTAB_NATREC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodnatrec IS NULL) OR (NEW.bdcodnatrec = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodnatrec)+1),1) FROM VEF_BASE_TTAB_NATREC INTO vcodigo;
       NEW.bdcodnatrec = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodnatrec FROM VEF_BASE_TTAB_NATREC
       WHERE bdcodnatrec = NEW.bdcodnatrec INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodnatrec)+1),1) FROM VEF_BASE_TTAB_NATREC INTO vcodigo;
            NEW.bdcodnatrec = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTAB_OR_CRED_DACON_BI0 FOR VEF_BASE_TTAB_OR_CRED_DACON
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODORCREDDACON IS NULL) OR (NEW.BDCODORCREDDACON = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDCODORCREDDACON)+1),1) FROM vef_base_ttab_or_cred_dacon INTO vcodigo;
       NEW.BDCODORCREDDACON = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDCODORCREDDACON FROM vef_base_ttab_or_cred_dacon WHERE BDCODORCREDDACON = NEW.BDCODORCREDDACON INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODORCREDDACON)+1),1) FROM vef_base_ttab_or_cred_dacon INTO vcodigo;
            NEW.BDCODORCREDDACON = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTAB_R_SERSN_BI0 FOR VEF_BASE_TTAB_R_SERSN
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODIGOR  IS NULL) OR (NEW.BDCODIGOR = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDCODIGOR)+1),1) FROM VEF_BASE_TTAB_R_SERSN INTO vcodigo;
       NEW.BDCODIGOR = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDCODIGOR FROM VEF_BASE_TTAB_R_SERSN WHERE BDCODIGOR = NEW.BDCODIGOR INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODIGOR)+1),1) FROM VEF_BASE_TTAB_R_SERSN INTO vcodigo;
            NEW.BDCODIGOR = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTAB_SN_COMERCIO_BI0 FOR VEF_BASE_TTAB_SN_COMERCIO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vCODCONFSIMPNAC INTEGER;
  DECLARE VARIABLE vNUMFAIXA INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumfaixa IS NULL) OR (NEW.bdnumfaixa = 0)) THEN
    BEGIN
      IF ((NEW.bdcodconfsimpnac IS NULL) OR (NEW.bdcodconfsimpnac = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdcodconfsimpnac)), 1) FROM vef_base_tconf_sn  INTO vcodconfsimpnac;
          NEW.bdcodconfsimpnac = vcodconfsimpnac;
        END

       SELECT COALESCE((MAX(bdnumfaixa)+1), 1) FROM vef_base_ttab_sn_comercio
       WHERE bdcodconfsimpnac = NEW.bdcodconfsimpnac INTO vnumfaixa;
       NEW.bdnumfaixa = vnumfaixa;
    END
  ELSE
    BEGIN
       IF ((NEW.bdcodconfsimpnac IS NULL) OR (NEW.bdcodconfsimpnac = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdcodconfsimpnac)), 1) FROM vef_base_tconf_sn  INTO vcodconfsimpnac;
          NEW.bdcodconfsimpnac = vcodconfsimpnac;
        END

       SELECT bdnumfaixa FROM vef_base_ttab_sn_comercio
       WHERE (bdnumfaixa = NEW.bdnumfaixa) AND (bdcodconfsimpnac = NEW.bdcodconfsimpnac) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumfaixa)+1), 1) FROM vef_base_ttab_sn_comercio WHERE (bdcodconfsimpnac = NEW.bdcodconfsimpnac) INTO vnumfaixa;
           NEW.bdnumfaixa = vnumfaixa;
         END

    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTAB_SN_INDUSTRIA_BI0 FOR VEF_BASE_TTAB_SN_INDUSTRIA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vCODCONFSIMPNAC INTEGER;
  DECLARE VARIABLE vNUMFAIXA INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumfaixa IS NULL) OR (NEW.bdnumfaixa = 0)) THEN
    BEGIN
      IF ((NEW.bdcodconfsimpnac IS NULL) OR (NEW.bdcodconfsimpnac = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdcodconfsimpnac)), 1) FROM vef_base_tconf_sn  INTO vcodconfsimpnac;
          NEW.bdcodconfsimpnac = vcodconfsimpnac;
        END

       SELECT COALESCE((MAX(bdnumfaixa)+1), 1) FROM vef_base_ttab_sn_industria
       WHERE bdcodconfsimpnac = NEW.bdcodconfsimpnac INTO vnumfaixa;
       NEW.bdnumfaixa = vnumfaixa;
    END
  ELSE
    BEGIN
       IF ((NEW.bdcodconfsimpnac IS NULL) OR (NEW.bdcodconfsimpnac = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdcodconfsimpnac)), 1) FROM vef_base_tconf_sn  INTO vcodconfsimpnac;
          NEW.bdcodconfsimpnac = vcodconfsimpnac;
        END

       SELECT bdnumfaixa FROM vef_base_ttab_sn_industria
       WHERE (bdnumfaixa = NEW.bdnumfaixa) AND (bdcodconfsimpnac = NEW.bdcodconfsimpnac) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumfaixa)+1), 1) FROM vef_base_ttab_sn_industria WHERE (bdcodconfsimpnac = NEW.bdcodconfsimpnac) INTO vnumfaixa;
           NEW.bdnumfaixa = vnumfaixa;
         END

    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTAB_SN_SERIII_BI0 FOR VEF_BASE_TTAB_SN_SERVICO_III
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vCODCONFSIMPNAC INTEGER;
  DECLARE VARIABLE vNUMFAIXA INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumfaixa IS NULL) OR (NEW.bdnumfaixa = 0)) THEN
    BEGIN
      IF ((NEW.bdcodconfsimpnac IS NULL) OR (NEW.bdcodconfsimpnac = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdcodconfsimpnac)), 1) FROM vef_base_tconf_sn  INTO vcodconfsimpnac;
          NEW.bdcodconfsimpnac = vcodconfsimpnac;
        END

       SELECT COALESCE((MAX(bdnumfaixa)+1), 1) FROM vef_base_ttab_sn_servico_iii
       WHERE bdcodconfsimpnac = NEW.bdcodconfsimpnac INTO vnumfaixa;
       NEW.bdnumfaixa = vnumfaixa;
    END
  ELSE
    BEGIN
       IF ((NEW.bdcodconfsimpnac IS NULL) OR (NEW.bdcodconfsimpnac = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdcodconfsimpnac)), 1) FROM vef_base_tconf_sn  INTO vcodconfsimpnac;
          NEW.bdcodconfsimpnac = vcodconfsimpnac;
        END

       SELECT bdnumfaixa FROM vef_base_ttab_sn_servico_iii
       WHERE (bdnumfaixa = NEW.bdnumfaixa) AND (bdcodconfsimpnac = NEW.bdcodconfsimpnac) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumfaixa)+1), 1) FROM vef_base_ttab_sn_servico_iii WHERE (bdcodconfsimpnac = NEW.bdcodconfsimpnac) INTO vnumfaixa;
           NEW.bdnumfaixa = vnumfaixa;
         END

    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTAB_SN_SERVICO_IV_BI0 FOR VEF_BASE_TTAB_SN_SERVICO_IV
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vCODCONFSIMPNAC INTEGER;
  DECLARE VARIABLE vNUMFAIXA INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumfaixa IS NULL) OR (NEW.bdnumfaixa = 0)) THEN
    BEGIN
      IF ((NEW.bdcodconfsimpnac IS NULL) OR (NEW.bdcodconfsimpnac = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdcodconfsimpnac)), 1) FROM vef_base_tconf_sn  INTO vcodconfsimpnac;
          NEW.bdcodconfsimpnac = vcodconfsimpnac;
        END

       SELECT COALESCE((MAX(bdnumfaixa)+1), 1) FROM vef_base_ttab_sn_servico_iv
       WHERE bdcodconfsimpnac = NEW.bdcodconfsimpnac INTO vnumfaixa;
       NEW.bdnumfaixa = vnumfaixa;
    END
  ELSE
    BEGIN
       IF ((NEW.bdcodconfsimpnac IS NULL) OR (NEW.bdcodconfsimpnac = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdcodconfsimpnac)), 1) FROM vef_base_tconf_sn  INTO vcodconfsimpnac;
          NEW.bdcodconfsimpnac = vcodconfsimpnac;
        END

       SELECT bdnumfaixa FROM vef_base_ttab_sn_servico_iv
       WHERE (bdnumfaixa = NEW.bdnumfaixa) AND (bdcodconfsimpnac = NEW.bdcodconfsimpnac) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumfaixa)+1), 1) FROM vef_base_ttab_sn_servico_iv WHERE (bdcodconfsimpnac = NEW.bdcodconfsimpnac) INTO vnumfaixa;
           NEW.bdnumfaixa = vnumfaixa;
         END

    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTAB_SN_SERVICO_V_BI0 FOR VEF_BASE_TTAB_SN_SERVICO_V
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDEMTABSER IS NULL) OR (NEW.BDORDEMTABSER = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEMTABSER)+1), 1) FROM VEF_BASE_TTAB_SN_SERVICO_V WHERE BDCODCONFSIMPNAC = NEW.BDCODCONFSIMPNAC INTO vNova_Chave;
      NEW.BDORDEMTABSER = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT BDORDEMTABSER FROM VEF_BASE_TTAB_SN_SERVICO_V WHERE (BDORDEMTABSER = NEW.BDORDEMTABSER) AND (BDCODCONFSIMPNAC = NEW.BDCODCONFSIMPNAC) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMTABSER)+1), 1) FROM VEF_BASE_TTAB_SN_SERVICO_V WHERE BDCODCONFSIMPNAC = NEW.BDCODCONFSIMPNAC INTO vNova_Chave;
           NEW.BDORDEMTABSER = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTAB_TP_CRED_DACON_BI0 FOR VEF_BASE_TTAB_TP_CRED_DACON
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODTPCREDDACON IS NULL) OR (NEW.BDCODTPCREDDACON = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDCODTPCREDDACON)+1),1) FROM vef_base_ttab_tp_cred_dacon INTO vcodigo;
       NEW.BDCODTPCREDDACON = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDCODTPCREDDACON FROM vef_base_ttab_tp_cred_dacon WHERE BDCODTPCREDDACON = NEW.BDCODTPCREDDACON INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODTPCREDDACON)+1),1) FROM vef_base_ttab_tp_cred_dacon INTO vcodigo;
            NEW.BDCODTPCREDDACON = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABAJUICMS_BI0 FOR VEF_BASE_TTABAJUICMS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vOrdem INTEGER;
BEGIN

  IF ((NEW.bdcodajuicms IS NULL) OR (NEW.bdcodajuicms = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodajuicms)+1), 1) FROM vef_base_ttabajuicms INTO vOrdem;
      NEW.bdcodajuicms = vOrdem;
    END

  NEW.bdprefixocodaju = CAST(SUBSTRING(NEW.bdcodajupad FROM 3 FOR 2) AS INTEGER);

END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABAJUICMS_BU0 FOR VEF_BASE_TTABAJUICMS
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  NEW.bdprefixocodaju = CAST(SUBSTRING(NEW.bdcodajupad FROM 3 FOR 2) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABAJUICMSST_BI0 FOR VEF_BASE_TTABAJUICMSST
ACTIVE BEFORE INSERT POSITION 0 
AS
  /* Trigger text */
  DECLARE VARIABLE vOrdem INTEGER;
BEGIN

  IF ((NEW.bdcodajuicmsst IS NULL) OR (NEW.bdcodajuicmsst = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodajuicmsst)+1), 1) FROM vef_base_ttabajuicmsst INTO vOrdem;
      NEW.bdcodajuicmsst = vOrdem;
    END

  NEW.bdprefixocodaju = CAST(SUBSTRING(NEW.BDCODAJUST FROM 3 FOR 2) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABAJUICMSST_BU0 FOR VEF_BASE_TTABAJUICMSST
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
   NEW.bdprefixocodaju = CAST(SUBSTRING(NEW.BDCODAJUST FROM 3 FOR 2) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABCODAJU_BI0 FOR VEF_BASE_TTABCODAJU
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodaju IS NULL) OR (NEW.bdcodaju = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDCODAJU)+1),1) FROM vef_base_ttabcodaju INTO vcodigo;
       NEW.bdcodaju = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDCODAJU FROM vef_base_ttabcodaju WHERE BDCODAJU = NEW.bdcodaju INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODAJU)+1),1) FROM vef_base_ttabcodaju INTO vcodigo;
            NEW.bdcodaju = vcodigo;
         END
    END

  NEW.bdprefixocodaju = CAST(SUBSTRING(NEW.bdcodajupad FROM 3 FOR 2) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABCODAJU_BU0 FOR VEF_BASE_TTABCODAJU
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  NEW.bdprefixocodaju = CAST(SUBSTRING(NEW.bdcodajupad FROM 3 FOR 2) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABCSTCOF_BI0 FOR VEF_BASE_TTABCSTCOF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdcodcstcof IS NULL) OR (NEW.bdcodcstcof = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdcodcstcof) + 1), 1) FROM vef_base_ttabcstcof  INTO vCodigo;
       NEW.bdcodcstcof = vCodigo;
     END
  ELSE
     BEGIN
       SELECT bdcodcstcof FROM vef_base_ttabcstcof WHERE bdcodcstcof = NEW.bdcodcstcof INTO vCodigo;

       IF (vCodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdcodcstcof) + 1), 1) FROM vef_base_ttabcstcof INTO vCodigo;
            NEW.bdcodcstcof = vCodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABCSTICMS_BI0 FOR VEF_BASE_TTABCSTICMS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdcodcsticms IS NULL) OR (NEW.bdcodcsticms = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdcodcsticms) + 1), 1) FROM vef_base_ttabcsticms  INTO vCodigo;
       NEW.bdcodcsticms = vCodigo;
     END
  ELSE
     BEGIN
       SELECT bdcodcsticms FROM vef_base_ttabcsticms WHERE bdcodcsticms = NEW.bdcodcsticms INTO vCodigo;

       IF (vCodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdcodcsticms) + 1), 1) FROM vef_base_ttabcsticms INTO vCodigo;
            NEW.bdcodcsticms = vCodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABCSTPIS_BI0 FOR VEF_BASE_TTABCSTPIS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdcodcstpis IS NULL) OR (NEW.bdcodcstpis = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdcodcstpis) + 1), 1) FROM vef_base_ttabcstpis  INTO vCodigo;
       NEW.bdcodcstpis = vCodigo;
     END
  ELSE
     BEGIN
       SELECT bdcodcstpis FROM vef_base_ttabcstpis WHERE bdcodcstpis = NEW.bdcodcstpis INTO vCodigo;

       IF (vCodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdcodcstpis) + 1), 1) FROM vef_base_ttabcstpis INTO vCodigo;
            NEW.bdcodcstpis = vCodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABSITNFISS_BI0 FOR VEF_BASE_TTABSITNFISS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODSITNF IS NULL) OR (NEW.BDCODSITNF = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDCODSITNF)+1),1) FROM vef_base_ttabsitnfiss INTO vcodigo;
       NEW.BDCODSITNF = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDCODSITNF FROM vef_base_ttabsitnfiss WHERE BDCODSITNF = NEW.BDCODSITNF INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODSITNF)+1),1) FROM vef_base_ttabsitnfiss INTO vcodigo;
            NEW.BDCODSITNF = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABTOTPAR_BI0 FOR VEF_BASE_TTABTOTPAR
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDORDEMTOT IS NULL) OR (NEW.bdordemtot = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDORDEMTOT)+1),1) FROM VEF_BASE_TTABTOTPAR INTO vcodigo;
       NEW.BDORDEMTOT = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDORDEMTOT FROM VEF_BASE_TTABTOTPAR
       WHERE BDORDEMTOT = NEW.BDORDEMTOT INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDORDEMTOT)+1),1) FROM VEF_BASE_TTABTOTPAR INTO vcodigo;
            NEW.BDORDEMTOT = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABTPNF_BI0 FOR VEF_BASE_TTABTPNF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODTPNF IS NULL) OR (NEW.BDCODTPNF = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDCODTPNF)+1),1) FROM vef_base_ttabtpnf INTO vcodigo;
       NEW.BDCODTPNF = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDCODTPNF FROM vef_base_ttabtpnf WHERE BDCODTPNF = NEW.BDCODTPNF INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODTPNF)+1),1) FROM vef_base_ttabtpnf INTO vcodigo;
            NEW.BDCODTPNF = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TTABVAL_R_SERSN_BI0 FOR VEF_BASE_TTABVAL_R_SERSN
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;

  IF ((NEW.BDORDEMTABSER IS NULL) OR (NEW.BDORDEMTABSER = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEMTABSER)), 1) FROM VEF_BASE_TTAB_SN_SERVICO_V WHERE BDCODCONFSIMPNAC = NEW.BDCODCONFSIMPNAC INTO vNova_Chave;
      NEW.BDORDEMTABSER = vNova_Chave;
    END

  IF ((NEW.BDCODVALR IS NULL) OR (NEW.BDCODVALR = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODVALR)+1), 1) FROM VEF_BASE_TTABVAL_R_SERSN WHERE BDCODCONFSIMPNAC = NEW.BDCODCONFSIMPNAC AND BDORDEMTABSER = NEW.BDORDEMTABSER INTO vNova_Chave;
      NEW.BDCODVALR = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT BDCODVALR FROM VEF_BASE_TTABVAL_R_SERSN WHERE (BDCODVALR = NEW.BDCODVALR) AND (BDORDEMTABSER = NEW.BDORDEMTABSER) AND (BDCODCONFSIMPNAC = NEW.BDCODCONFSIMPNAC) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCODVALR)+1), 1) FROM VEF_BASE_TTABVAL_R_SERSN WHERE (BDORDEMTABSER = NEW.BDORDEMTABSER) AND BDCODCONFSIMPNAC = NEW.BDCODCONFSIMPNAC INTO vNova_Chave;
           NEW.BDCODVALR = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TA110_BI0 FOR VEF_EMP_TA110
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

END
^

CREATE OR ALTER TRIGGER VEF_EMP_TA120_BI0 FOR VEF_EMP_TA120
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

         SELECT COALESCE((MAX(bdORDEM)+1), 1) FROM VEF_EMP_TA120 WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Chave;
         NEW.bdORDEM = vNova_Chave;

    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       SELECT bdORDEM FROM VEF_EMP_TA120
       WHERE (bdORDEM = NEW.bdORDEM) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdORDEM)+1), 1) FROM VEF_EMP_TA120
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
           NEW.bdORDEM = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER trigger vef_emp_tcredito_m220_m620_bd0 for vef_emp_tcredito_m220_m620
active before delete position 0
AS
declare variable WCONTROLCRED DM_BOOLEAN;
BEGIN
  select BDCONTROLCRED from VW_INT_SPEDPISCOFINS_REF where BDCODEMP = old.BDCODEMP into :WCONTROLCRED;
  if (:WCONTROLCRED = 'TRUE') then
    begin
     UPDATE VEF_EMP_TBLOCOM220_M620 X set X.bdvl_aj_saldo = (old.BDVL_AJ_SALDO_REF)
     where x.BDCODPERIODO = old.bdcodperiodo and
         x.BDCODEMP = old.BDCODEMP and
         x.BDCODMATRIZ = old.BDCODMATRIZ and
         x.BDCODQUADRO = old.BDCODQUADRO and
         x.BDREFERENCIA = old.BDREFLANM220 and
         x.BDCHAVE = old.BDCHAVE and
         x.BDORDEM = old.BDORDEM;
    end

END
^

/* Trigger: TTIPOSEQREL_BI0 */
CREATE OR ALTER TRIGGER TTIPOSEQREL_BI0 FOR TTIPOSEQREL
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (NEW.BDTIPO IS NULL OR NEW.BDTIPO = 0) THEN
    SELECT COALESCE(MAX(BDTIPO), 0) + 1 FROM TTIPOSEQREL INTO NEW.BDTIPO;
END
^

/* Trigger: TFORMSEQREL_BI0 */
CREATE OR ALTER TRIGGER TFORMSEQREL_BI0 FOR TFORMSEQREL
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (NEW.BDCHAVE IS NULL OR NEW.BDCHAVE = 0) THEN
    SELECT COALESCE(MAX(BDCHAVE), 0) + 1 FROM TFORMSEQREL INTO NEW.BDCHAVE;
END
^

CREATE OR ALTER trigger vef_emp_ta170_bi0 for vef_emp_ta170
active before insert position 0
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
  DECLARE VARIABLE vcodigo INTEGER;
  DECLARE VARIABLE vordem INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

    IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmovseritens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Ordem;
      NEW.BDORDEM = vNova_Ordem;
    END
  end
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TAJUICMSE111_BI0 FOR VEF_EMP_TAJUICMSE111
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vORDEME111220 INTEGER;
BEGIN
 /* vcodigo = 0;
  IF ((NEW.bdordemE111220 IS NULL) OR (NEW.bdordeme111220 = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordemE111220)+1), 1) FROM vef_emp_tajuicmse111 WHERE bdcodemp = NEW.bdcodemp INTO vordemE111220;
      NEW.bdordemE111220 = vordemE111220;
    END
  ELSE
    BEGIN
       SELECT bdordemE111220 FROM vef_emp_tajuicmse111 WHERE (bdordemE111220 = NEW.bdordemE111220) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemE111220)+1), 1) FROM vef_emp_tajuicmse111 WHERE bdcodemp = NEW.bdcodemp INTO vordemE111220;
           NEW.bdordemE111220 = vordemE111220;
         END
    END*/
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TAJUICMSE112_BI0 FOR VEF_EMP_TAJUICMSE112
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vORDEME111220 INTEGER;
  DECLARE VARIABLE vORDEME112230 INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordeme112230 IS NULL) OR (NEW.bdordeme112230 = 0)) THEN
    BEGIN
      IF ((NEW.bdordeme111220 IS NULL) OR (NEW.bdordeme111220 = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdordeme111220)), 1) FROM vef_emp_tajuicmse111 WHERE (bdcodemp = NEW.bdcodemp) INTO vordeme111220;
          NEW.bdordeme111220 = vordeme111220;
        END

       SELECT COALESCE((MAX(bdordeme112230)+1), 1) FROM vef_emp_tajuicmse112
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdordeme111220 = NEW.bdordeme111220) INTO vordeme112230;
       NEW.bdordeme112230 = vordeme112230;
    END
  ELSE
    BEGIN
       IF ((NEW.bdordeme111220 IS NULL) OR (NEW.bdordeme111220 = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdordeme111220)), 1) FROM vef_emp_tajuicmse111 WHERE (bdcodemp = NEW.bdcodemp) INTO vordeme111220;
          NEW.bdordeme111220 = vordeme111220;
        END

       SELECT bdordeme112230 FROM vef_emp_tajuicmse112
       WHERE (bdordeme112230 = NEW.bdordeme112230) AND (bdordeme111220 = NEW.bdordeme111220) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordeme112230)+1), 1) FROM vef_emp_tajuicmse112 WHERE (bdcodemp = NEW.bdcodemp) AND (bdordeme111220 = NEW.bdordeme111220) INTO vordeme112230;
           NEW.bdordeme112230 = vordeme112230;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TAJUICMSE113_BI0 FOR VEF_EMP_TAJUICMSE113
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vORDEME111220 INTEGER;
  DECLARE VARIABLE vORDEME113240 INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordeme113240 IS NULL) OR (NEW.bdordeme113240 = 0)) THEN
    BEGIN
      IF ((NEW.bdordeme111220 IS NULL) OR (NEW.bdordeme111220 = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdordeme111220)), 1) FROM vef_emp_tajuicmse111 WHERE (bdcodemp = NEW.bdcodemp) INTO vordeme111220;
          NEW.bdordeme111220 = vordeme111220;
        END

       SELECT COALESCE((MAX(bdordeme113240)+1), 1) FROM vef_emp_tajuicmse113
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdordeme111220 = NEW.bdordeme111220) INTO vORDEME113240;
       NEW.bdordeme113240 = vORDEME113240;
    END
  ELSE
    BEGIN
       IF ((NEW.bdordeme111220 IS NULL) OR (NEW.bdordeme111220 = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdordeme111220)), 1) FROM vef_emp_tajuicmse111 WHERE (bdcodemp = NEW.bdcodemp) INTO vordeme111220;
          NEW.bdordeme111220 = vordeme111220;
        END

       SELECT bdordeme113240 FROM vef_emp_tajuicmse113
       WHERE (bdordeme113240 = NEW.bdordeme113240) AND (bdordeme111220 = NEW.bdordeme111220) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordeme113240)+1), 1) FROM vef_emp_tajuicmse113 WHERE (bdcodemp = NEW.bdcodemp) AND (bdordeme111220 = NEW.bdordeme111220) INTO vORDEME113240;
           NEW.bdordeme113240 = vORDEME113240;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TAJUICMSE115_BI0 FOR VEF_EMP_TAJUICMSE115
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vORDEME115 INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdORDEME115 IS NULL) OR (NEW.bdORDEME115 = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEME115)+1), 1) FROM vef_emp_tajuicmse115 WHERE bdcodemp = NEW.bdcodemp INTO vORDEME115;
      NEW.bdORDEME115 = vORDEME115;
    END
  ELSE
    BEGIN
       SELECT bdORDEME115 FROM vef_emp_tajuicmse115 WHERE (bdORDEME115 = NEW.bdORDEME115) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdORDEME115)+1), 1) FROM vef_emp_tajuicmse115 WHERE bdcodemp = NEW.bdcodemp INTO vORDEME115;
           NEW.bdORDEME115 = vORDEME115;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TID_DECLARACAO_SN_IC_BI0 FOR VEF_EMP_TID_DECLARACAO_SN_IC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  /* Trigger text */
IF (COALESCE(NEW.BDORDEM_DECLARACAO, 0) = 0) THEN
    BEGIN
      SELECT MAX(BDORDEM_DECLARACAO) + 1
      FROM VEF_EMP_TID_DECLARACAO_SN_IC IC
      WHERE IC.BDCODEMP = NEW.BDCODEMP
      INTO NEW.BDORDEM_DECLARACAO;
      NEW.BDORDEM_DECLARACAO = COALESCE(NEW.BDORDEM_DECLARACAO, 1);
    END
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TNUMERODAS_SN_IC_BI0 FOR VEF_EMP_TNUMERODAS_SN_IC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  /* Trigger text */
IF (COALESCE(NEW.BDORDEM_NUMERODAS, 0) = 0) THEN
    BEGIN
      SELECT MAX(BDORDEM_NUMERODAS) + 1
      FROM VEF_EMP_TNUMERODAS_SN_IC IC
      WHERE IC.BDCODEMP = NEW.BDCODEMP
      INTO NEW.BDORDEM_NUMERODAS;
      NEW.BDORDEM_NUMERODAS = COALESCE(NEW.BDORDEM_NUMERODAS, 1);
    END
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TAJUICMSE116_BI0 FOR VEF_EMP_TAJUICMSE116
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vORDEME116250 INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordeme116250 IS NULL) OR (NEW.bdordeme116250 = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordemE116250)+1), 1) FROM vef_emp_tajuicmse116 WHERE bdcodemp = NEW.bdcodemp INTO vORDEME116250;
      NEW.bdordemE116250 = vORDEME116250;
    END
  ELSE
    BEGIN
       SELECT bdordemE116250 FROM vef_emp_tajuicmse116 WHERE (bdordemE116250 = NEW.bdordemE116250) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemE116250)+1), 1) FROM vef_emp_tajuicmse116 WHERE bdcodemp = NEW.bdcodemp INTO vORDEME116250;
           NEW.bdordemE116250 = vORDEME116250;
         END
    END
END
^

CREATE OR ALTER trigger vef_emp_tajuicmsste316_bi0 for vef_emp_tajuicmsste316
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vORDEME116250 INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDEME116250 IS NULL) OR (NEW.BDORDEME116250 = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEME116250)+1), 1) FROM VEF_EMP_TAJUICMSSTE316 WHERE bdcodemp = NEW.bdcodemp INTO vORDEME116250;
      NEW.BDORDEME116250 = vORDEME116250;
    END
  ELSE
    BEGIN
       SELECT BDORDEME116250 FROM VEF_EMP_TAJUICMSSTE316 WHERE (BDORDEME116250 = NEW.BDORDEME116250) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEME116250)+1), 1) FROM VEF_EMP_TAJUICMSSTE316 WHERE bdcodemp = NEW.bdcodemp INTO vORDEME116250;
           NEW.BDORDEME116250 = vORDEME116250;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TAJUICMSSTE220_BI0 FOR VEF_EMP_TAJUICMSSTE220
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vORDEME111220 INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemE111220 IS NULL) OR (NEW.bdordeme111220 = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordemE111220)+1), 1) FROM vef_emp_tajuicmsste220 WHERE bdcodemp = NEW.bdcodemp INTO vordemE111220;
      NEW.bdordemE111220 = vordemE111220;
    END
  ELSE
    BEGIN
       SELECT bdordemE111220 FROM vef_emp_tajuicmsste220 WHERE (bdordemE111220 = NEW.bdordemE111220) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemE111220)+1), 1) FROM vef_emp_tajuicmsste220 WHERE bdcodemp = NEW.bdcodemp INTO vordemE111220;
           NEW.bdordemE111220 = vordemE111220;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TAJUICMSSTE230_BI0 FOR VEF_EMP_TAJUICMSSTE230
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vORDEME111220 INTEGER;
  DECLARE VARIABLE vORDEME112230 INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordeme112230 IS NULL) OR (NEW.bdordeme112230 = 0)) THEN
    BEGIN
      IF ((NEW.bdordeme111220 IS NULL) OR (NEW.bdordeme111220 = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdordeme111220)), 1) FROM vef_emp_tajuicmsste220 WHERE (bdcodemp = NEW.bdcodemp) INTO vordeme111220;
          NEW.bdordeme111220 = vordeme111220;
        END

       SELECT COALESCE((MAX(bdordeme112230)+1), 1) FROM VEF_EMP_TAJUICMSSTE230
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdordeme111220 = NEW.bdordeme111220) INTO vordeme112230;
       NEW.bdordeme112230 = vordeme112230;
    END
  ELSE
    BEGIN
       IF ((NEW.bdordeme111220 IS NULL) OR (NEW.bdordeme111220 = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdordeme111220)), 1) FROM vef_emp_tajuicmsste220 WHERE (bdcodemp = NEW.bdcodemp) INTO vordeme111220;
          NEW.bdordeme111220 = vordeme111220;
        END

       SELECT bdordeme112230 FROM VEF_EMP_TAJUICMSSTE230
       WHERE (bdordeme112230 = NEW.bdordeme112230) AND (bdordeme111220 = NEW.bdordeme111220) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordeme112230)+1), 1) FROM VEF_EMP_TAJUICMSSTE230 WHERE (bdcodemp = NEW.bdcodemp) AND (bdordeme111220 = NEW.bdordeme111220) INTO vordeme112230;
           NEW.bdordeme112230 = vordeme112230;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TAJUICMSSTE240_BI0 FOR VEF_EMP_TAJUICMSSTE240
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vORDEME111220 INTEGER;
  DECLARE VARIABLE vORDEME113240 INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordeme113240 IS NULL) OR (NEW.bdordeme113240 = 0)) THEN
    BEGIN
      IF ((NEW.bdordeme111220 IS NULL) OR (NEW.bdordeme111220 = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdordeme111220)), 1) FROM vef_emp_tajuicmsste220 WHERE (bdcodemp = NEW.bdcodemp) INTO vordeme111220;
          NEW.bdordeme111220 = vordeme111220;
        END

       SELECT COALESCE((MAX(bdordeme113240)+1), 1) FROM VEF_EMP_TAJUICMSSTE240
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdordeme111220 = NEW.bdordeme111220) INTO vORDEME113240;
       NEW.bdordeme113240 = vORDEME113240;
    END
  ELSE
    BEGIN
       IF ((NEW.bdordeme111220 IS NULL) OR (NEW.bdordeme111220 = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdordeme111220)), 1) FROM vef_emp_tajuicmsste220 WHERE (bdcodemp = NEW.bdcodemp) INTO vordeme111220;
          NEW.bdordeme111220 = vordeme111220;
        END

       SELECT bdordeme113240 FROM VEF_EMP_TAJUICMSSTE240
       WHERE (bdordeme113240 = NEW.bdordeme113240) AND (bdordeme111220 = NEW.bdordeme111220) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordeme113240)+1), 1) FROM VEF_EMP_TAJUICMSSTE240 WHERE (bdcodemp = NEW.bdcodemp) AND (bdordeme111220 = NEW.bdordeme111220) INTO vORDEME113240;
           NEW.bdordeme113240 = vORDEME113240;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TAJUICMSSTE250_BI0 FOR VEF_EMP_TAJUICMSSTE250
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vORDEME116250 INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordeme116250 IS NULL) OR (NEW.bdordeme116250 = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordemE116250)+1), 1) FROM vef_emp_tajuicmsste250 WHERE bdcodemp = NEW.bdcodemp INTO vORDEME116250;
      NEW.bdordemE116250 = vORDEME116250;
    END
  ELSE
    BEGIN
       SELECT bdordemE116250 FROM vef_emp_tajuicmsste250 WHERE (bdordemE116250 = NEW.bdordemE116250) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemE116250)+1), 1) FROM vef_emp_tajuicmsste250 WHERE bdcodemp = NEW.bdcodemp INTO vORDEME116250;
           NEW.bdordemE116250 = vORDEME116250;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TAJUSTEEFDC_BI0 FOR VEF_EMP_TAJUSTEEFDC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
        SELECT bdresult +1 FROM maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||NEW.bdcodemp || ' AND ' || 'BDCODTIPOREG = '||NEW.BDCODTIPOREG , 'VEF_EMP_TAJUSTEEFDC') INTO vCodigo;
        NEW.bdchave = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdchave FROM VEF_EMP_TAJUSTEEFDC WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) AND (BDCODTIPOREG = NEW.BDCODTIPOREG) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT bdresult +1 FROM maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||NEW.bdcodemp || ' AND ' || 'BDCODTIPOREG = '||NEW.BDCODTIPOREG , 'VEF_EMP_TAJUSTEEFDC') INTO vCodigo;
            NEW.bdchave = vcodigo;
         END
    END

END
^

CREATE OR ALTER TRIGGER VEF_EMP_TAJUSTEEXCLUSAO_BI0 FOR VEF_EMP_TAJUSTEEXCLUSAO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM VEF_EMP_TAJUSTEEXCLUSAO WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.BDCHAVE = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT BDCHAVE FROM VEF_EMP_TAJUSTEEXCLUSAO WHERE (BDCHAVE = NEW.BDCHAVE) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM VEF_EMP_TAJUSTEEXCLUSAO WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.BDCHAVE = vNova_Chave;
         END
    END

END
^

CREATE OR ALTER TRIGGER VEF_EMP_TAJUSTEIPIE530_BI0 FOR VEF_EMP_TAJUSTEIPIE530
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
     BEGIN
        SELECT bdresult +1 FROM maxsci('BDCHAVE', 'bdcodemp, BDCHAVE', 'bdcodemp = '||NEW.bdcodemp , 'VEF_EMP_TAJUSTEIPIE530') INTO vCodigo;
        NEW.BDCHAVE = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCHAVE FROM VEF_EMP_TAJUSTEIPIE530 WHERE (BDCHAVE = NEW.BDCHAVE) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
            SELECT bdresult +1 FROM maxsci('BDCHAVE', 'bdcodemp, BDCHAVE', 'bdcodemp = '||NEW.bdcodemp , 'VEF_EMP_TAJUSTEIPIE530') INTO vCodigo;
            NEW.BDCHAVE = vcodigo;
         END
    END


END
^

CREATE OR ALTER TRIGGER VEF_EMP_TBEM_BI0 FOR VEF_EMP_TBEM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodbem IS NULL) OR (NEW.bdcodbem = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodbem)), 1) FROM empresas_tbem WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.bdcodbem = vNova_Chave;
     END
  ELSE
    BEGIN
       SELECT bdcodbem FROM empresas_tbem WHERE (bdcodbem = NEW.bdcodbem) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodbem)), 1) FROM empresas_tbem WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdcodbem = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER trigger vef_emp_tc100ent_bi0 for vef_emp_tc100ent
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_tc190ent_bi0 for vef_emp_tc190ent
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
  DECLARE VARIABLE vOrdemItem INTEGER ;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.BDCODIGO IS NULL) OR (NEW.BDCODIGO = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.BDCHAVE) INTO vordemItem;
          NEW.bdordem = vOrdemItem;
        END

       SELECT COALESCE((MAX(BDCODIGO)+1), 1) FROM vef_emp_tc190ent WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.BDCHAVE) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
       NEW.BDCODIGO = vNova_Chave;

    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END
    
       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
          BEGIN
             SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.bdchave) INTO vordemItem;
             NEW.bdordem = vOrdemItem;
          END

       SELECT BDCODIGO FROM vef_emp_tc190ent
       WHERE (BDCODIGO = NEW.BDCODIGO) AND (BDORDEM = NEW.BDORDEM) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCODIGO)+1), 1) FROM vef_emp_tc190ent
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
           NEW.BDCODIGO = vNova_Chave;
         END
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_tc190sai_bi0 for vef_emp_tc190sai
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
  DECLARE VARIABLE vOrdemItem INTEGER ;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  vcodigo = 0;
  IF ((NEW.BDCODIGO IS NULL) OR (NEW.BDCODIGO = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovSAIitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovSAIitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.BDCHAVE) INTO vordemItem;
          NEW.bdordem = vOrdemItem;
        END

       SELECT COALESCE((MAX(BDCODIGO)+1), 1) FROM vef_emp_tc190SAI WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.BDCHAVE) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
       NEW.BDCODIGO = vNova_Chave;

    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovSAIitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END
    
       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
          BEGIN
             SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovSAIitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.bdchave) INTO vordemItem;
             NEW.bdordem = vOrdemItem;
          END

       SELECT BDCODIGO FROM vef_emp_tc190SAI
       WHERE (BDCODIGO = NEW.BDCODIGO) AND (BDORDEM = NEW.BDORDEM) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCODIGO)+1), 1) FROM vef_emp_tc190SAI
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
           NEW.BDCODIGO = vNova_Chave;
         END

    END
  end
END^

CREATE OR ALTER trigger vef_emp_tc195ent_bi0 for vef_emp_tc195ent
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1)
       FROM vef_emp_tmovent
       WHERE (bdcodemp = NEW.bdcodemp)
       INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

    vcodigo = 0;
    IF ((NEW.bdordemobs IS NULL) OR (NEW.bdordemobs = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordemobs)+1), 1) FROM vef_emp_tc195ent WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave INTO vcodigo;
      NEW.bdordemobs = vcodigo;
    END
    ELSE
    BEGIN
       SELECT bdordemobs FROM vef_emp_tc195ent WHERE (bdordemobs = NEW.bdordemobs) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemobs)+1), 1) FROM vef_emp_tc195ent WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave INTO vcodigo;
           NEW.bdordemobs = vcodigo;
         END
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_tc195sai_bi0 for vef_emp_tc195sai
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1)
       FROM vef_emp_tmovsai
       WHERE (bdcodemp = NEW.bdcodemp)
       INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

  vcodigo = 0;
  IF ((NEW.bdordemobs IS NULL) OR (NEW.bdordemobs = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordemobs)+1), 1) FROM vef_emp_tc195sai WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave INTO vcodigo;
      NEW.bdordemobs = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdordemobs FROM vef_emp_tc195sai WHERE (bdordemobs = NEW.bdordemobs) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemobs)+1), 1) FROM vef_emp_tc195sai WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave INTO vcodigo;
           NEW.bdordemobs = vcodigo;
         END
    END
  end
END^

CREATE OR ALTER trigger vef_emp_tc197ent_bi0 for vef_emp_tc197ent
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1)
       FROM vef_emp_tmovent
       WHERE (bdcodemp = NEW.bdcodemp)
       INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

    vcodigo = 0;
    IF ((NEW.bdordemobs IS NULL) OR (NEW.bdordemobs = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordemobs)), 1)
       FROM vef_emp_tc195ent
       WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave)
       INTO vcodigo;
       NEW.bdordemobs = vcodigo;
     END

    vcodigo = 0;
    IF ((NEW.BDORDEMOUTOBR IS NULL) OR (NEW.BDORDEMOUTOBR = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEMOUTOBR)+1), 1) FROM vef_emp_tc197ent WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordemobs = NEW.bdordemobs INTO vcodigo;
      NEW.BDORDEMOUTOBR = vcodigo;
    END
    ELSE
    BEGIN
       SELECT BDORDEMOUTOBR FROM vef_emp_tc197ent WHERE (BDORDEMOUTOBR = NEW.BDORDEMOUTOBR) AND (bdordemobs = NEW.bdordemobs) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMOUTOBR)+1), 1) FROM vef_emp_tc197ent WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordemobs = NEW.bdordemobs INTO vcodigo;
           NEW.BDORDEMOUTOBR = vcodigo;
         END
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_tc197sai_bi0 for vef_emp_tc197sai
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1)
       FROM vef_emp_tmovsai
       WHERE (bdcodemp = NEW.bdcodemp)
       INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

  vcodigo = 0;
  IF ((NEW.bdordemobs IS NULL) OR (NEW.bdordemobs = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordemobs)), 1)
       FROM vef_emp_tc195sai
       WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave)
       INTO vcodigo;
       NEW.bdordemobs = vcodigo;
     END

  vcodigo = 0;
  IF ((NEW.BDORDEMOUTOBR IS NULL) OR (NEW.BDORDEMOUTOBR = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEMOUTOBR)+1), 1) FROM vef_emp_tc197sai WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordemobs = NEW.bdordemobs INTO vcodigo;
      NEW.BDORDEMOUTOBR = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDORDEMOUTOBR FROM vef_emp_tc197sai WHERE (BDORDEMOUTOBR = NEW.BDORDEMOUTOBR) AND (bdordemobs = NEW.bdordemobs) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMOUTOBR)+1), 1) FROM vef_emp_tc197sai WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordemobs = NEW.bdordemobs INTO vcodigo;
           NEW.BDORDEMOUTOBR = vcodigo;
         END
    END
 end
END^

CREATE OR ALTER trigger VEF_EMP_TAJUAPUPCM220620_BI0 for VEF_EMP_TAJUAPUPCM220620
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM VEF_EMP_TAJUAPUPCM220620 WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;
      NEW.BDCHAVE = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDCHAVE FROM VEF_EMP_TAJUAPUPCM220620 WHERE (BDCHAVE = NEW.BDCHAVE) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)+1), 1)  FROM VEF_EMP_TAJUAPUPCM220620 WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;
           NEW.BDCHAVE = vcodigo;
         END
    END

  IF ((new.bdDATALAN IS NULL) OR (new.bdDATALAN = 0)) THEN
    new.bdDATALAN = CURRENT_DATE;

  IF ((new.bdHORALAN IS NULL) OR (new.bdHORALAN = 0)) THEN
    new.bdHORALAN = CURRENT_TIME;
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TAJUAPUPCM220620_BU0 FOR VEF_EMP_TAJUAPUPCM220620
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
 /* Trigger text */
 new.bdDATALAN = CURRENT_DATE;
 new.bdHORALAN = CURRENT_TIME;
end
^

CREATE OR ALTER trigger VEF_EMP_TBLOCOPGER_NCONT_BI0 for VEF_EMP_TBLOCOPGER_NCONT
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
     BEGIN
        SELECT COALESCE(MAX(n.bdORDEM),0) +1 FROM VEF_EMP_TBLOCOPGER_NCONT n WHERE n.BDCODEMP = NEW.bdCODEMP AND n.bdCODMATRIZ = NEW.bdCODMATRIZ AND
        n.bdCODPERIODO = NEW.bdCODPERIODO AND n.bdREFERENCIA = NEW.bdREFERENCIA AND n.bdCODCONFBLOCOP = NEW.bdCODCONFBLOCOP INTO VCODIGO;
       NEW.BDORDEM = vCODIGO;
     END
  ELSE
    BEGIN
        SELECT bdORDEM FROM VEF_EMP_TBLOCOPGER_NCONT n WHERE n.BDCODEMP = NEW.bdCODEMP AND n.bdCODMATRIZ = NEW.bdCODMATRIZ AND
        n.bdCODPERIODO = NEW.bdCODPERIODO AND n.bdREFERENCIA = NEW.bdREFERENCIA AND n.bdCODCONFBLOCOP = NEW.bdCODCONFBLOCOP AND N.BDORDEM = NEW.BDORDEM INTO vcodigo;

        IF (vcodigo > 0) THEN
          BEGIN
            SELECT COALESCE(MAX(n.bdORDEM),0) +1 FROM VEF_EMP_TBLOCOPGER_NCONT n WHERE n.BDCODEMP = NEW.bdCODEMP AND n.bdCODMATRIZ = NEW.bdCODMATRIZ AND
            n.bdCODPERIODO = NEW.bdCODPERIODO AND n.bdREFERENCIA = NEW.bdREFERENCIA AND n.bdCODCONFBLOCOP = NEW.bdCODCONFBLOCOP INTO VCODIGO;
            NEW.BDORDEM = vCODIGO;
          END
    END
END
^

CREATE OR ALTER trigger TMP_VEF_EMP_TREDZVARCFOP_TMP_BI for TMP_VEF_EMP_TREDZVARCFOP_TEMP
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDORDEMVARCFOP IS NULL) OR (NEW.BDORDEMVARCFOP = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEMVARCFOP)+1), 1) FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP WHERE bdcodemp = NEW.bdcodemp AND BDCHAVE = NEW.BDCHAVE INTO vcodigo;
      NEW.BDORDEMVARCFOP = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDORDEMVARCFOP FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP WHERE bdcodemp = NEW.bdcodemp AND BDCHAVE = NEW.BDCHAVE
       AND NEW.BDORDEMVARCFOP = BDORDEMVARCFOP INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMVARCFOP)+1), 1) FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP WHERE bdcodemp = NEW.bdcodemp AND BDCHAVE = NEW.BDCHAVE INTO vcodigo;
           NEW.BDORDEMVARCFOP = vcodigo;
         END
    END

end^

CREATE OR ALTER trigger TMP_VEF_EMP_TREDZVARALIQ_BI for TMP_VEF_EMP_TREDZVARALIQ_TEMP
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
  vcodigo = 0;
  IF ((NEW.BDORDEMICMS IS NULL) OR (NEW.BDORDEMICMS = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEMICMS)+1), 1) FROM TMP_VEF_EMP_TREDZVARALIQ_TEMP WHERE bdcodemp = NEW.bdcodemp AND BDCHAVE = NEW.BDCHAVE and BDSESSAO = NEW.BDSESSAO
      INTO vcodigo;
      NEW.BDORDEMICMS = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDORDEMICMS FROM TMP_VEF_EMP_TREDZVARALIQ_TEMP WHERE (BDCHAVE = NEW.BDCHAVE) AND (bdcodemp = NEW.bdcodemp)
       and BDSESSAO = NEW.BDSESSAO AND BDORDEMICMS = NEW.BDORDEMICMS INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMICMS)+1), 1)  FROM TMP_VEF_EMP_TREDZVARALIQ_TEMP WHERE bdcodemp = NEW.bdcodemp AND BDCHAVE = NEW.BDCHAVE and BDSESSAO = NEW.BDSESSAO INTO vcodigo;
           NEW.BDORDEMICMS = vcodigo;
         END
    END

end^

CREATE OR ALTER TRIGGER TMP_VEF_EMP_TREDZC425_BI FOR TMP_VEF_EMP_TREDZC425_TEMP
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
  vcodigo = 0;
  IF ((NEW.BDORDEMC425 IS NULL) OR (NEW.BDORDEMC425 = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEMC425)+1), 1) FROM TMP_VEF_EMP_TREDZC425_TEMP WHERE bdcodemp = NEW.bdcodemp AND BDCHAVE = NEW.BDCHAVE and BDSESSAO = NEW.BDSESSAO
      AND BDORDEMTOT = NEW.BDORDEMTOT INTO vcodigo;
      NEW.BDORDEMC425 = vcodigo;
    END
  ELSE
    BEGIN
       SELECT BDORDEMC425 FROM TMP_VEF_EMP_TREDZC425_TEMP WHERE (BDCHAVE = NEW.BDCHAVE) AND (bdcodemp = NEW.bdcodemp)
       and BDSESSAO = NEW.BDSESSAO AND BDORDEMC425 = NEW.BDORDEMC425 AND BDORDEMTOT = NEW.BDORDEMTOT INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMC425)+1), 1)  FROM TMP_VEF_EMP_TREDZC425_TEMP WHERE bdcodemp = NEW.bdcodemp AND BDCHAVE = NEW.BDCHAVE and BDSESSAO = NEW.BDSESSAO
           AND BDORDEMTOT = NEW.BDORDEMTOT INTO vcodigo;
           NEW.BDORDEMC425 = vcodigo;
         END
    END

end^

CREATE OR ALTER TRIGGER VEF_EMP_TC300350ENT_BI0 FOR VEF_EMP_TC300350ENT
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TC300350SAI_BI0 FOR VEF_EMP_TC300350SAI
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
END
^

CREATE OR ALTER trigger vef_emp_tc590totent_bi0 for vef_emp_tc590totent
active before insert position 0
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

    IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Ordem;
      NEW.BDORDEM = vNova_Ordem;
    END
  end
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TCADBICO_BI0 FOR VEF_EMP_TCADBICO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vBICO INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDCODBICO IS NULL) OR (NEW.BDCODBICO = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODBICO)+1), 1) FROM vef_emp_tcadBICO WHERE bdcodemp = NEW.bdcodemp AND BDCODTANQUE = NEW.bdcodtanque AND BDCODBOMBA = NEW.bdcodbomba INTO vBICO;
      NEW.BDCODBICO = vBICO;
    END
  ELSE
    BEGIN
       SELECT BDCODBICO FROM vef_emp_tcadBICO WHERE (BDCODBICO = NEW.BDCODBICO) AND (bdcodemp = NEW.bdcodemp) AND BDCODTANQUE = NEW.bdcodtanque AND BDCODBOMBA = NEW.bdcodbomba INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCODBICO)+1), 1) FROM vef_emp_tcadBICO WHERE bdcodemp = NEW.bdcodemp AND BDCODTANQUE = NEW.bdcodtanque AND BDCODBOMBA = NEW.bdcodbomba INTO vBICO;
           NEW.BDCODBICO = vBICO;
         END
    END
END
^

CREATE OR ALTER trigger vef_emp_tcadbomba_bi0 for vef_emp_tcadbomba
active before insert position 0
AS
  DECLARE VARIABLE vBOMBA INTEGER;
BEGIN
  IF ((NEW.BDCODBOMBA IS not NULL) and (NEW.BDCODBOMBA > 0)) THEN
    begin
      exit;
    end

  IF ((NEW.BDCODBOMBA IS NULL) OR (NEW.BDCODBOMBA = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODBOMBA)+1), 1) FROM vef_emp_tcadBOMBA WHERE bdcodemp = NEW.bdcodemp INTO vBOMBA;
      NEW.BDCODBOMBA = vBOMBA;
    END
END^


CREATE OR ALTER TRIGGER VEF_EMP_TCADTANQUE_BI0 FOR VEF_EMP_TCADTANQUE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vTANQUE INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDCODTANQUE IS NULL) OR (NEW.BDCODTANQUE = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODTANQUE)+1), 1) FROM vef_emp_tcadtanque WHERE bdcodemp = NEW.bdcodemp INTO vTANQUE;
      NEW.BDCODTANQUE = vTANQUE;
    END
  ELSE
    BEGIN
       SELECT BDCODTANQUE FROM vef_emp_tcadtanque WHERE (BDCODTANQUE = NEW.BDCODTANQUE) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCODTANQUE)+1), 1) FROM vef_emp_tcadtanque WHERE bdcodemp = NEW.bdcodemp INTO vTANQUE;
           NEW.BDCODTANQUE = vTANQUE;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TCAT44_BI0 FOR VEF_EMP_TCAT44
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vordem INTEGER;
BEGIN
  vordem = 0;
  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordem)+1), 1) FROM vef_emp_tcat44
       WHERE (bdcodemp = NEW.bdcodemp) INTO vordem;

       NEW.bdordem = vordem;
     END
  ELSE
     BEGIN
       SELECT bdordem FROM vef_emp_tcat44
       WHERE (bdordem = NEW.bdordem) AND (bdcodemp = NEW.bdcodemp) INTO vordem;

       IF (vordem > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdordem)+1), 1) FROM vef_emp_tcat44 WHERE (bdcodemp = NEW.bdcodemp) INTO vordem;
            NEW.bdordem = vordem;
          END
     END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TCONSUB_BI0 FOR VEF_EMP_TCONSUB
ACTIVE BEFORE INSERT POSITION 0 
AS
   DECLARE VARIABLE vCodigo INTEGER;
BEGIN
   vcodigo = 0;
   IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
      BEGIN
        SELECT COALESCE(MAX(bdcodemp), 1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vCodigo;
      END

   IF ((NEW.bdcodconsub IS NULL) OR (NEW.bdcodconsub = 0))  THEN
      BEGIN
         SELECT COALESCE((MAX(bdcodconsub)+1),1) FROM vef_emp_tconsub WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;
         NEW.bdcodconsub = vcodigo;
      END
   ELSE
      BEGIN
         SELECT bdcodconsub FROM vef_emp_tconsub WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodconsub = NEW.bdcodconsub) INTO vcodigo;

         IF (vcodigo > 0) THEN
            BEGIN
               SELECT COALESCE((MAX(bdcodconsub)+1),1) FROM vef_emp_tconsub WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;
               NEW.bdcodconsub = vcodigo;
            END
      END
END
^

CREATE OR ALTER trigger vef_emp_td100ent_bi0 for vef_emp_td100ent
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_td100sai_bi0 for vef_emp_td100sai
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
  end
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TD110SAI_BI0 FOR VEF_EMP_TD110SAI
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN

  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai
       WHERE (bdcodemp = NEW.bdcodemp)
       INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

  vcodigo = 0;
  IF ((NEW.bdordemst IS NULL) OR (NEW.bdordemst = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordemst)+1), 1) FROM vef_emp_td110sai WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave INTO vcodigo;
      NEW.bdordemst = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdordemst FROM vef_emp_td110sai WHERE (bdordemst = NEW.bdordemst) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemst)+1), 1) FROM  vef_emp_td110sai WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave INTO vcodigo;
           NEW.bdordemst = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TD120COMPCON_BI0 FOR VEF_EMP_TD120COMPCON
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vordemd120 INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemst INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemd120 IS NULL) OR (NEW.bdordemd120 = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_td110sai WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordemst IS NULL) OR (NEW.bdordemst = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEMST)), 1) FROM vef_emp_td110sai WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemst;
          NEW.bdordemst = vordemst;
        END

      SELECT COALESCE((MAX(bdordemd120)+1), 1) FROM vef_emp_td120compcon
      WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemst = NEW.bdordemst) INTO vordemd120;
      NEW.bdordemd120 = vordemd120;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_td110sai WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordemst IS NULL) OR (NEW.bdordemst = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMST)), 1) FROM vef_emp_td110sai WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemst;
           NEW.bdordemst = vordemst;
         END

       SELECT bdordemd120 FROM vef_emp_td120compcon
       WHERE (bdordemd120 = NEW.bdordemd120) AND (bdOrdemst = NEW.bdordemst) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemd120)+1), 1) FROM vef_emp_td120compcon WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemst = NEW.bdordemst) INTO vordemd120;
           NEW.bdordemd120 = vordemd120;
         END

    END
END
^

CREATE OR ALTER trigger vef_emp_td130compcon_bi0 for vef_emp_td130compcon
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_td160cargatrans_bi0 for vef_emp_td160cargatrans
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemcartrans INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdordemcartrans IS NULL) OR (NEW.bdordemcartrans = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

       SELECT COALESCE((MAX(bdordemcartrans)+1), 1) FROM vef_emp_td160cargatrans
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vordemcartrans;
       NEW.bdordemcartrans = vordemcartrans;
    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       SELECT bdordemcartrans FROM vef_emp_td160cargatrans
       WHERE (bdordemcartrans = NEW.bdordemcartrans) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemcartrans)+1), 1) FROM vef_emp_td160cargatrans WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vordemcartrans;
           NEW.bdordemcartrans = vordemcartrans;
         END
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_td162docfis_bi0 for vef_emp_td162docfis
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemcartrans INTEGER;
  DECLARE VARIABLE vordemdocfis INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdordemdocfis IS NULL) OR (NEW.bdordemdocfis = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_td160cargatrans WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordemcartrans IS NULL) OR (NEW.bdordemcartrans = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdordemcartrans)), 1) FROM vef_emp_td160cargatrans WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemcartrans;
          NEW.bdordemcartrans = vordemcartrans;
        END

       SELECT COALESCE((MAX(bdordemdocfis)+1), 1) FROM vef_emp_td162docfis
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemcartrans = NEW.bdordemcartrans) INTO vordemdocfis;

       NEW.bdordemdocfis = vordemdocfis;
    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_td160cargatrans WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordemcartrans IS NULL) OR (NEW.bdordemcartrans = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdordemcartrans)), 1) FROM vef_emp_td160cargatrans WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemcartrans;
          NEW.bdordemcartrans = vordemcartrans;
        END

       SELECT bdordemdocfis FROM vef_emp_td162docfis
       WHERE (bdordemdocfis = NEW.bdordemdocfis) AND (bdOrdemcartrans = NEW.bdordemcartrans) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemdocfis)+1), 1) FROM vef_emp_td162docfis
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemcartrans = NEW.bdordemcartrans) INTO vordemdocfis;
           NEW.bdordemdocfis = vordemdocfis;
         END

    END
  end
END
^

CREATE OR ALTER trigger vef_emp_td195ent_bi0 for vef_emp_td195ent
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1)
       FROM vef_emp_tmovent
       WHERE (bdcodemp = NEW.bdcodemp)
       INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

    vcodigo = 0;
    IF ((NEW.bdordemobs IS NULL) OR (NEW.bdordemobs = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordemobs)+1), 1) FROM vef_emp_td195ent WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave INTO vcodigo;
      NEW.bdordemobs = vcodigo;
    END
    ELSE
    BEGIN
       SELECT bdordemobs FROM vef_emp_td195ent WHERE (bdordemobs = NEW.bdordemobs) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemobs)+1), 1) FROM vef_emp_td195ent WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave INTO vcodigo;
           NEW.bdordemobs = vcodigo;
         END
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_td195sai_bi0 for vef_emp_td195sai
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1)
       FROM vef_emp_tmovsai
       WHERE (bdcodemp = NEW.bdcodemp)
       INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

    vcodigo = 0;
    IF ((NEW.bdordemobs IS NULL) OR (NEW.bdordemobs = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordemobs)+1), 1) FROM vef_emp_td195sai WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave INTO vcodigo;
      NEW.bdordemobs = vcodigo;
    END
    ELSE
    BEGIN
       SELECT bdordemobs FROM vef_emp_td195sai WHERE (bdordemobs = NEW.bdordemobs) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemobs)+1), 1) FROM vef_emp_td195sai WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave INTO vcodigo;
           NEW.bdordemobs = vcodigo;
         END
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_td197ent_bi0 for vef_emp_td197ent
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1)
       FROM vef_emp_tmovent
       WHERE (bdcodemp = NEW.bdcodemp)
       INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

    vcodigo = 0;
    IF ((NEW.bdordemobs IS NULL) OR (NEW.bdordemobs = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordemobs)), 1)
       FROM vef_emp_td195ent
       WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave)
       INTO vcodigo;
       NEW.bdordemobs = vcodigo;
     END

    vcodigo = 0;
    IF ((NEW.BDORDEMOUTOBR IS NULL) OR (NEW.BDORDEMOUTOBR = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEMOUTOBR)+1), 1) FROM vef_emp_td197ent WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordemobs = NEW.bdordemobs INTO vcodigo;
      NEW.BDORDEMOUTOBR = vcodigo;
    END
    ELSE
    BEGIN
       SELECT BDORDEMOUTOBR FROM vef_emp_td197ent WHERE (BDORDEMOUTOBR = NEW.BDORDEMOUTOBR) AND (bdordemobs = NEW.bdordemobs) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMOUTOBR)+1), 1) FROM vef_emp_td197ent WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordemobs = NEW.bdordemobs INTO vcodigo;
           NEW.BDORDEMOUTOBR = vcodigo;
         END
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_td197sai_bi0 for vef_emp_td197sai
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1)
       FROM vef_emp_tmovsai
       WHERE (bdcodemp = NEW.bdcodemp)
       INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

    vcodigo = 0;
    IF ((NEW.bdordemobs IS NULL) OR (NEW.bdordemobs = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordemobs)), 1)
       FROM vef_emp_td195sai
       WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave)
       INTO vcodigo;
       NEW.bdordemobs = vcodigo;
     END

    vcodigo = 0;
    IF ((NEW.BDORDEMOUTOBR IS NULL) OR (NEW.BDORDEMOUTOBR = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEMOUTOBR)+1), 1) FROM vef_emp_td197sai WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordemobs = NEW.bdordemobs INTO vcodigo;
      NEW.BDORDEMOUTOBR = vcodigo;
    END
    ELSE
    BEGIN
       SELECT BDORDEMOUTOBR FROM vef_emp_td197sai WHERE (BDORDEMOUTOBR = NEW.BDORDEMOUTOBR) AND (bdordemobs = NEW.bdordemobs) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMOUTOBR)+1), 1) FROM vef_emp_td197sai WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordemobs = NEW.bdordemobs INTO vcodigo;
           NEW.BDORDEMOUTOBR = vcodigo;
         END
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_td500ent_bi0 for vef_emp_td500ent
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_td590totent_bi0 for vef_emp_td590totent
active before insert position 0
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

    IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Ordem;
      NEW.BDORDEM = vNova_Ordem;
    END
  end
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TDIMEGERDEBESP_BI0 FOR VEF_EMP_TDIMEGERDEBESP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vORDEM INTEGER;
BEGIN

  vcodigo = 0;
  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordem)+1), 1) FROM vef_emp_tdimegerdebesp WHERE bdcodemp = NEW.bdcodemp INTO vordem;
      NEW.bdordem = vordem;
    END
  ELSE
    BEGIN
       SELECT bdordem FROM vef_emp_tdimegerdebesp WHERE ( bdordem = NEW.bdordem) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordem)+1), 1) FROM vef_emp_tdimegerdebesp WHERE bdcodemp = NEW.bdcodemp INTO vORDEM;
           NEW.bdordem = vORDEM;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TDIMEGERNAT_BI0 FOR VEF_EMP_TDIMEGERNAT
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
    NEW.BDPREFIXONAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4)  AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TDIMEGERNAT_BU0 FOR VEF_EMP_TDIMEGERNAT
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
    NEW.BDPREFIXONAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4)  AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TDIMEGERPAGTOIMP_BI0 FOR VEF_EMP_TDIMEGERPAGTOIMP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vORDEM INTEGER;
BEGIN

  vcodigo = 0;
  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordem)+1), 1) FROM vef_emp_tdimegerpagtoimp WHERE bdcodemp = NEW.bdcodemp INTO vordem;
      NEW.bdordem = vordem;
    END
  ELSE
    BEGIN
       SELECT bdordem FROM vef_emp_tdimegerpagtoimp WHERE ( bdordem = NEW.bdordem) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordem)+1), 1) FROM vef_emp_tdimegerpagtoimp WHERE bdcodemp = NEW.bdcodemp INTO vORDEM;
           NEW.bdordem = vORDEM;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TDIMEGERQ47_BI0 FOR VEF_EMP_TDIMEGERQ47
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordem) + 1), 1) FROM VEF_EMP_TDIMEGERQ47  INTO vCodigo;
      NEW.bdordem = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdordem FROM VEF_EMP_TDIMEGERQ47 WHERE bdordem = NEW.bdordem INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordem) + 1), 1) FROM VEF_EMP_TDIMEGERQ47  INTO vCodigo;
           NEW.bdordem = vCodigo;
         END
    END
END
^

CREATE OR ALTER trigger vef_emp_tdimegerq48_bi0 for vef_emp_tdimegerq48
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
    BEGIN
      --SELECT COALESCE((MAX(bdordem) + 1), 1) FROM VEF_EMP_TDIMEGERQ48  INTO vCodigo;
      SELECT first 1 bdordem FROM VEF_EMP_TDIMEGERQ48 order by bdordem desc INTO vCodigo;
      vcodigo = vcodigo + 1;
      NEW.bdordem = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdordem FROM VEF_EMP_TDIMEGERQ48 WHERE bdordem = NEW.bdordem INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           --SELECT COALESCE((MAX(bdordem) + 1), 1) FROM VEF_EMP_TDIMEGERQ48  INTO vCodigo;
           SELECT first 1 bdordem FROM VEF_EMP_TDIMEGERQ48 order by bdordem desc INTO vCodigo;
           vCodigo = vCodigo + 1;
           NEW.bdordem = vCodigo;
         END
    END
END^

CREATE OR ALTER TRIGGER VEF_EMP_TDIMEGERQ49_BI0 FOR VEF_EMP_TDIMEGERQ49
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordem) + 1), 1) FROM VEF_EMP_TDIMEGERQ49  INTO vCodigo;
      NEW.bdordem = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdordem FROM VEF_EMP_TDIMEGERQ49 WHERE bdordem = NEW.bdordem INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordem) + 1), 1) FROM VEF_EMP_TDIMEGERQ49  INTO vCodigo;
           NEW.bdordem = vCodigo;
         END
    END
END
^

CREATE OR ALTER trigger vef_emp_tdimegerq50_bi0 for vef_emp_tdimegerq50
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
    BEGIN
      SELECT first 1 bdordem FROM VEF_EMP_TDIMEGERQ50 order by bdordem desc INTO vCodigo;
      vCodigo = vCodigo + 1;
      NEW.bdordem = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdordem FROM VEF_EMP_TDIMEGERQ50 WHERE bdordem = NEW.bdordem INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT first 1 bdordem FROM VEF_EMP_TDIMEGERQ50 order by bdordem desc INTO vCodigo;
           vCodigo = vCodigo + 1;
           NEW.bdordem = vCodigo;
         END
    END
END^

/* Trigger: VEF_EMP_TGIARJGERQ21_BI0 */
CREATE OR ALTER TRIGGER VEF_EMP_TGIARJGERQ21_BI0 FOR VEF_EMP_TGIARJGERQ21
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEM) + 1), 1) FROM VEF_EMP_TGIARJGERQ21 INTO vCodigo;
      NEW.BDORDEM = vCodigo;
    END
  ELSE
    BEGIN
       SELECT BDORDEM FROM VEF_EMP_TGIARJGERQ21 WHERE BDORDEM = NEW.BDORDEM INTO vCodigo;
       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM) + 1), 1) FROM VEF_EMP_TGIARJGERQ21 INTO vCodigo;
           NEW.BDORDEM = vCodigo;
         END
    END
END
^

/* Trigger: VEF_EMP_TGIARJGERQ22_BI0 */
CREATE OR ALTER TRIGGER VEF_EMP_TGIARJGERQ22_BI0 FOR VEF_EMP_TGIARJGERQ22
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEM) + 1), 1) FROM VEF_EMP_TGIARJGERQ22 INTO vCodigo;
      NEW.BDORDEM = vCodigo;
    END
  ELSE
    BEGIN
       SELECT BDORDEM FROM VEF_EMP_TGIARJGERQ22 WHERE BDORDEM = NEW.BDORDEM INTO vCodigo;
       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM) + 1), 1) FROM VEF_EMP_TGIARJGERQ22 INTO vCodigo;
           NEW.BDORDEM = vCodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TGIATOGERQ_07_01_BI0 FOR VEF_EMP_TGIATOGERQ_07_01
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEM) + 1), 1) FROM vef_emp_tgiatogerq_07_01 INTO vCodigo;
      NEW.BDORDEM = vCodigo;
    END
  ELSE
    BEGIN
       SELECT BDORDEM FROM vef_emp_tgiatogerq_07_01 WHERE BDORDEM = NEW.BDORDEM INTO vCodigo;
       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM) + 1), 1) FROM vef_emp_tgiatogerq_07_01 INTO vCodigo;
           NEW.BDORDEM = vCodigo;
         END
    END
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TGIATOGERQ_07_02_BI0 FOR VEF_EMP_TGIATOGERQ_07_02
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEM) + 1), 1) FROM vef_emp_tgiatogerq_07_02 INTO vCodigo;
      NEW.BDORDEM = vCodigo;
    END
  ELSE
    BEGIN
       SELECT BDORDEM FROM vef_emp_tgiatogerq_07_02 WHERE BDORDEM = NEW.BDORDEM INTO vCodigo;
       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM) + 1), 1) FROM vef_emp_tgiatogerq_07_02 INTO vCodigo;
           NEW.BDORDEM = vCodigo;
         END
    END
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TDIMEGERREGESP_BI0 FOR VEF_EMP_TDIMEGERREGESP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vORDEM INTEGER;
BEGIN

  vcodigo = 0;
  IF ((NEW.bdordemregesp IS NULL) OR (NEW.bdordemregesp = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordemregesp)+1), 1) FROM vef_emp_tdimegerregesp WHERE bdcodemp = NEW.bdcodemp INTO vordem;
      NEW.bdordemregesp = vordem;
    END
  ELSE
    BEGIN
       SELECT bdordemregesp FROM vef_emp_tdimegerregesp WHERE ( bdordemregesp = NEW. bdordemregesp) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemregesp)+1), 1) FROM vef_emp_tdimegerregesp WHERE bdcodemp = NEW.bdcodemp INTO vORDEM;
           NEW.bdordemregesp = vORDEM;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TDOCECF_BI0 FOR VEF_EMP_TDOCECF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemdocecf INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemdocecf IS NULL) OR (NEW.bdordemdocecf = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tredz WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

       SELECT COALESCE((MAX(bdordemdocecf)+1), 1) FROM vef_emp_tdocecf
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vordemdocecf;
       NEW.bdordemdocecf = vordemdocecf;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tredz WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       SELECT bdordemdocecf FROM vef_emp_tdocecf
       WHERE (bdordemdocecf = NEW.bdordemdocecf) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemdocecf)+1), 1) FROM vef_emp_tdocecf WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vordemdocecf;
           NEW.bdordemdocecf = vordemdocecf;
         END

    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TENEGAS_BI0 FOR VEF_EMP_TENEGAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER;
  DECLARE VARIABLE vordempro INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(bdchave), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
      NEW.bdchave = vchave;
    END

  IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(bdORDEM), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vOrdem;
      NEW.BDORDEM = vOrdem;
    END

  IF ((NEW.bdordempro IS NULL) OR (NEW.bdORDEMPRO = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(bdORDEMPRO), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) AND (bdORDEM = NEW.bdordem) INTO vordempro;
      NEW.bdordempro = vordempro;
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TENETELE_BI0 FOR VEF_EMP_TENETELE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER;
  DECLARE VARIABLE vordempro INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
      NEW.bdchave = vchave;
    END

  IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vOrdem;
      NEW.BDORDEM = vOrdem;
    END

  IF ((NEW.bdordempro IS NULL) OR (NEW.bdORDEMPRO = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEMPRO)), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) AND (bdORDEM = NEW.bdordem) INTO vordempro;
      NEW.bdordempro = vordempro;
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TF1323A_DACON_BI0 FOR VEF_EMP_TF1323A_DACON
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDCHAVEF1323ADACON IS NULL) OR (NEW.BDCHAVEF1323ADACON = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVEF1323ADACON)+1), 1) FROM VEF_EMP_TF1323A_DACON WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.BDCHAVEF1323ADACON = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT BDCHAVEF1323ADACON FROM VEF_EMP_TF1323A_DACON WHERE (BDCHAVEF1323ADACON = NEW.BDCHAVEF1323ADACON) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVEF1323ADACON)+1), 1) FROM VEF_EMP_TF1323A_DACON WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.BDCHAVEF1323ADACON = vNova_Chave;
         END
    END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  --Não está buscando o código do usuário, por isso esse código é setado na tela mesmo
  --select bdcodusu from vw_variaveis_sessao_banco into vcodigo;
  --new.bdcodusu = vcodigo;
  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TF500REDZ_BI0 FOR VEF_EMP_TF500REDZ
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem500 INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemf500 IS NULL) OR (NEW.bdordemf500 = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tredz WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

       SELECT COALESCE((MAX(bdordemf500)+1), 1) FROM VEF_EMP_TF500REDZ
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vordem500;
       NEW.bdordemf500 = vordem500;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tredz WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       SELECT bdordemf500 FROM VEF_EMP_TF500REDZ
       WHERE (bdordemf500 = NEW.bdordemf500) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemf500)+1), 1) FROM VEF_EMP_TF500REDZ WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vordem500;
           NEW.bdordemf500 = vordem500;
         END

    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TF500SAI_BI0 FOR VEF_EMP_TF500SAI
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
  DECLARE VARIABLE vOrdemItem INTEGER ;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDEMF500 IS NULL) OR (NEW.BDORDEMF500 = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.bdchave) INTO vordemItem;
          NEW.bdordem = vOrdemItem;
        END

        SELECT COALESCE((MAX(BDORDEMF500)+1), 1) FROM VEF_EMP_TF500SAI WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
      NEW.BDORDEMF500 = vNova_Chave;

    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.bdchave) INTO vordemItem;
          NEW.bdordem = vOrdemItem;
        END

        SELECT BDORDEMF500 FROM VEF_EMP_TF500SAI
        WHERE (BDORDEMF500 = NEW.BDORDEMF500) AND (BDORDEM = NEW.BDORDEM) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
        IF (vcodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(BDORDEMF500)+1), 1) FROM VEF_EMP_TF500SAI
            WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
            NEW.BDORDEMF500 = vNova_Chave;
          END
    END

END
^

CREATE OR ALTER TRIGGER VEF_EMP_TGIAESGERNAT_BI0 FOR VEF_EMP_TGIAESGERNAT
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
    NEW.BDPREFIXONAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4)  AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TGIAESGERNAT_BU0 FOR VEF_EMP_TGIAESGERNAT
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
    NEW.BDPREFIXONAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4)  AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TGIAMGGERNAT_BI0 FOR VEF_EMP_TGIAMGGERNAT
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
    NEW.BDPREFIXONAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4)  AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TGIAMGGERNAT_BU0 FOR VEF_EMP_TGIAMGGERNAT
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
    NEW.BDPREFIXONAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4)  AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TGIAPRGERNAT_BI FOR VEF_EMP_TGIAPRGERNAT
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  NEW.bdprefixonat = CAST(SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TGIAPRGERNAT_BU FOR VEF_EMP_TGIAPRGERNAT
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  NEW.bdprefixonat = CAST(SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TGIARJGERNAT_BI FOR VEF_EMP_TGIARJGERNAT
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  NEW.BDPREFIXONAT = CAST(SUBSTRING(CAST(NEW.BDCODNAT AS VARCHAR(7)) FROM 1 FOR 4) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TGIARJGERNAT_BU FOR VEF_EMP_TGIARJGERNAT
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  NEW.BDPREFIXONAT = CAST(SUBSTRING(CAST(NEW.BDCODNAT AS VARCHAR(7)) FROM 1 FOR 4) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TGIATOGERNAT_BI FOR VEF_EMP_TGIATOGERNAT
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  NEW.BDPREFIXONAT = CAST(SUBSTRING(CAST(NEW.BDCODNAT AS VARCHAR(7)) FROM 1 FOR 4) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TGIATOGERNAT_BU FOR VEF_EMP_TGIATOGERNAT
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  NEW.BDPREFIXONAT = CAST(SUBSTRING(CAST(NEW.BDCODNAT AS VARCHAR(7)) FROM 1 FOR 4) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TGIAROGERNAT_BI0 FOR VEF_EMP_TGIAROGERNAT
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  NEW.BDPREFIXONAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4)  AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TGIAROGERNAT_BU0 FOR VEF_EMP_TGIAROGERNAT
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  NEW.BDPREFIXONAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4)  AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TGIASPGERNAT_BI0 FOR VEF_EMP_TGIASPGERNAT
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
    NEW.BDPREFIXONAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4)  AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TGIASPGERNAT_BU0 FOR VEF_EMP_TGIASPGERNAT
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
    NEW.BDPREFIXONAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4)  AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TITEMDOCECF_BI0 FOR VEF_EMP_TITEMDOCECF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemdocecf INTEGER;
  DECLARE VARIABLE vordemitem INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemitem IS NULL) OR (NEW.bdordemitem = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tdocecf WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordemdocecf IS NULL) OR (NEW.bdordemdocecf = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEMDOCECF)), 1) FROM  vef_emp_tdocecf WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemdocecf;
          NEW.bdordemdocecf = vordemdocecf;
        END

       SELECT COALESCE((MAX(bdordemitem)+1), 1) FROM vef_emp_titemdocecf
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemdocecf = NEW.bdordemdocecf) INTO vordemitem;

       NEW.bdordemitem = vordemitem;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tdocecf WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordemdocecf IS NULL) OR (NEW.bdordemdocecf = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEMDOCECF)), 1) FROM  vef_emp_tdocecf WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemdocecf;
          NEW.bdordemdocecf = vordemdocecf;
        END

       SELECT bdordemitem FROM vef_emp_titemdocecf
       WHERE (bdordemitem = NEW.bdordemitem) AND (bdOrdemdocecf = NEW.bdordemdocecf) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemitem)+1), 1) FROM vef_emp_titemdocecf WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemdocecf = NEW.bdordemdocecf) INTO vordemitem;
           NEW.bdordemitem = vordemitem;
         END

    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOV_OCORR_DCIP_BI0 FOR VEF_EMP_TMOV_OCORR_DCIP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdchavedcip IS NULL) OR (NEW.bdchavedcip = 0)) THEN
     BEGIN
--        select coalesce((max(bdcodprod)+1),1) from tcadpro into vcodigo;
        SELECT bdresult +1 FROM maxsci('bdchavedcip', 'bdcodemp, bdchavedcip', 'bdcodemp = '||NEW.bdcodemp || ' AND ' || 'BDCODTIPODISC = '||NEW.bdcodtipodisc , 'VEF_EMP_TMOV_OCORR_DCIP') INTO vCodigo;
        NEW.bdchavedcip = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdchavedcip FROM VEF_EMP_TMOV_OCORR_DCIP WHERE (bdchavedcip = NEW.bdchavedcip) AND (bdcodemp = NEW.bdcodemp) AND (BDCODTIPODISC = NEW.BDCODTIPODISC) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
  --          select coalesce((max(bdcodprod)+1),1) from VEF_EMP_TMOV_OCORR_DCIP into vcodigo;
            SELECT bdresult +1 FROM maxsci('bdchavedcip', 'bdcodemp, bdchavedcip', 'bdcodemp = '||NEW.bdcodemp || ' AND ' || 'BDCODTIPODISC = '||NEW.bdcodtipodisc , 'VEF_EMP_TMOV_OCORR_DCIP') INTO vCodigo;
            NEW.bdchavedcip = vcodigo;
         END
    END

  --new.BDTIPDISC = New.bdcodtipodisc;
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVCCENT_BI0 FOR VEF_EMP_TMOVCCENT
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vCodigo;
          NEW.bdordem = vCodigo;
        END

  IF ((NEW.bdordemcc IS NULL) OR (NEW.bdordemcc = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordemcc) + 1), 1) FROM VEF_EMP_TMOVCCENT WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem ) INTO vCodigo;
       NEW.bdordemcc = vCodigo;
     END
  ELSE
     BEGIN
       SELECT bdordemcc FROM VEF_EMP_TMOVCCENT WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem AND bdordemcc = NEW.bdordemcc) INTO vCodigo;

       IF (vCodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdordemcc) + 1), 1) FROM VEF_EMP_TMOVCCENT WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem) INTO vCodigo;
            NEW.bdordemcc = vCodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVCCREDZ_BI0 FOR VEF_EMP_TMOVCCREDZ
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tredz WHERE (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

      IF ((NEW.bdordemvarcfop IS NULL) OR (NEW.bdordemvarcfop = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEMVARCFOP)), 1) FROM vef_emp_tredzvarcfop WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vCodigo;
          NEW.bdordemvarcfop = vCodigo;
        END

  IF ((NEW.bdordemcc IS NULL) OR (NEW.bdordemcc = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordemcc) + 1), 1) FROM VEF_EMP_TMOVCCredz WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordemvarcfop = NEW.bdordemvarcfop) INTO vCodigo;
       NEW.bdordemcc = vCodigo;
     END
  ELSE
     BEGIN
       SELECT bdordemcc FROM VEF_EMP_TMOVCCredz WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordemvarcfop = NEW.bdordemvarcfop AND bdordemcc = NEW.bdordemcc) INTO vCodigo;

       IF (vCodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdordemcc) + 1), 1) FROM VEF_EMP_TMOVCCredz WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordemvarcfop = NEW.bdordemvarcfop) INTO vCodigo;
            NEW.bdordemcc = vCodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVCCSAI_BI0 FOR VEF_EMP_TMOVCCSAI
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vCodigo;
          NEW.bdordem = vCodigo;
        END

  IF ((NEW.bdordemcc IS NULL) OR (NEW.bdordemcc = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordemcc) + 1), 1) FROM VEF_EMP_TMOVCCSAI WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem ) INTO vCodigo;
       NEW.bdordemcc = vCodigo;
     END
  ELSE
     BEGIN
       SELECT bdordemcc FROM VEF_EMP_TMOVCCSAI WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem AND bdordemcc = NEW.bdordemcc) INTO vCodigo;

       IF (vCodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdordemcc) + 1), 1) FROM VEF_EMP_TMOVCCSAI WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem) INTO vCodigo;
            NEW.bdordemcc = vCodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVCCSER_BI0 FOR VEF_EMP_TMOVCCSER
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovSER WHERE (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovSERitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vCodigo;
          NEW.bdordem = vCodigo;
        END

  IF ((NEW.bdordemcc IS NULL) OR (NEW.bdordemcc = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordemcc) + 1), 1) FROM VEF_EMP_TMOVCCSER WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem ) INTO vCodigo;
       NEW.bdordemcc = vCodigo;
     END
  ELSE
     BEGIN
       SELECT bdordemcc FROM VEF_EMP_TMOVCCSER WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem AND bdordemcc = NEW.bdordemcc) INTO vCodigo;

       IF (vCodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdordemcc) + 1), 1) FROM VEF_EMP_TMOVCCSER WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem) INTO vCodigo;
            NEW.bdordemcc = vCodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVCOMB_BI0 FOR VEF_EMP_TMOVCOMB
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vCHAVE INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM VEF_EMP_TMOVCOMB WHERE bdcodemp = NEW.bdcodemp/* and BDCODTANQUE = new.BDCODTANQUE*/  INTO vCHAVE;
      NEW.BDCHAVE = vCHAVE;
    END
  ELSE
    BEGIN
       SELECT BDCHAVE FROM VEF_EMP_TMOVCOMB WHERE (BDCHAVE = NEW.BDCHAVE) AND (bdcodemp = NEW.bdcodemp)/* and BDCODTANQUE = new.BDCODTANQUE*/ INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM VEF_EMP_TMOVCOMB WHERE bdcodemp = NEW.bdcodemp/* and BDCODTANQUE = new.BDCODTANQUE*/ INTO vCHAVE;
           NEW.BDCHAVE = vCHAVE;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVCOMBVENDAS_BI0 FOR VEF_EMP_TMOVCOMBVENDAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;

BEGIN
  vcodigo = 0;
  IF ((NEW.BDCHAVEVENDAS IS NULL) OR (NEW.BDCHAVEVENDAS = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVEVENDAS)+1), 1) FROM VEF_EMP_TMOVCOMBVENDAS WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Chave;
      NEW.BDCHAVEVENDAS = vNova_Chave;
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM VEF_EMP_TMOVCOMB WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
          NEW.BDCHAVE = vchavelan;
        END
    END
  ELSE
    BEGIN
       SELECT BDCHAVEVENDAS FROM VEF_EMP_TMOVCOMBVENDAS WHERE (BDCHAVEVENDAS = NEW.BDCHAVEVENDAS) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVEVENDAS)+1), 1) FROM VEF_EMP_TMOVCOMBVENDAS WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
           NEW.BDCHAVEVENDAS = vNova_Chave;
         END
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM VEF_EMP_TMOVCOMB WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
           NEW.BDCHAVE = vchavelan;
         END
    END


END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVDEMAISDOC_F100_BI0 FOR VEF_EMP_TMOVDEMAISDOC_F100
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  NEW.bdreflan = CAST( SUBSTRING(CAST(NEW.bddt_oper AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.bddt_oper AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);
END
^


CREATE OR ALTER TRIGGER VEF_EMP_TMOVDEMRET_BI0 FOR VEF_EMP_TMOVDEMRET
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM VEF_EMP_TMOVDEMAISDOC_F100 WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVENT_IVA_BI0 FOR VEF_EMP_TMOVENT_IVA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
  DECLARE VARIABLE vOrdemItem INTEGER ;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemiva IS NULL) OR (NEW.bdordemiva = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.BDCHAVE) INTO vordemItem;
          NEW.bdordem = vOrdemItem;
        END

       SELECT COALESCE((MAX(bdordemiva)+1), 1) FROM vef_emp_tmovent_iva WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.BDCHAVE) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
       NEW.bdordemiva = vNova_Chave;

    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END
    
       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
          BEGIN
             SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.bdchave) INTO vordemItem;
             NEW.bdordem = vOrdemItem;
          END

       SELECT bdordemiva FROM vef_emp_tmovent_iva
       WHERE (bdordemiva = NEW.bdordemiva) AND (BDORDEM = NEW.BDORDEM) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemiva)+1), 1) FROM vef_emp_tmovent_iva
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
           NEW.bdordemiva = vNova_Chave;
         END

    END

END
^

CREATE OR ALTER trigger vef_emp_tmoventantimp_bi0 for vef_emp_tmoventantimp
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
  DECLARE VARIABLE vOrdemItem INTEGER ;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdordemant IS NULL) OR (NEW.bdordemant = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.BDCHAVE) INTO vordemItem;
          NEW.bdordem = vOrdemItem;
        END

       SELECT COALESCE((MAX(bdordemant)+1), 1) FROM VEF_EMP_TMOVENTANTIMP WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.BDCHAVE) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
       NEW.bdordemant = vNova_Chave;

    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END
    
       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
          BEGIN
             SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.bdchave) INTO vordemItem;
             NEW.bdordem = vOrdemItem;
          END

       SELECT bdordemant FROM VEF_EMP_TMOVENTANTIMP
       WHERE (bdordemant = NEW.bdordemant) AND (BDORDEM = NEW.BDORDEM) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemant)+1), 1) FROM VEF_EMP_TMOVENTANTIMP
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
           NEW.bdordemant = vNova_Chave;
         END
    END
  end
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVENTCUPREF_BI0 FOR VEF_EMP_TMOVENTCUPREF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemic INTEGER;
  DECLARE VARIABLE vordemcupref INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemcupref IS NULL) OR (NEW.bdordemcupref = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemic;
          NEW.bdordemic = vordemic;
        END

       SELECT COALESCE((MAX(bdordemcupref)+1), 1) FROM vef_emp_tmoventcupref
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemcupref;

       NEW.bdordemcupref = vordemcupref;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemic;
           NEW.bdordemic = vordemic;
         END

       SELECT bdordemcupref FROM vef_emp_tmoventcupref
       WHERE (bdordemcupref = NEW.bdordemcupref) AND (bdOrdemic = NEW.bdordemic) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemcupref)+1), 1) FROM vef_emp_tmoventcupref WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemcupref;
           NEW.bdordemcupref = vordemcupref;
         END

    END
END
^

CREATE OR ALTER trigger vef_emp_tmoventdcip_bi0 for vef_emp_tmoventdcip
active before insert position 0
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
  DECLARE VARIABLE vcodigo INTEGER;
  DECLARE VARIABLE vordem INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

    IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Ordem;
      NEW.BDORDEM = vNova_Ordem;
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_tmoventdifaliq_bi0 for vef_emp_tmoventdifaliq
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
  DECLARE VARIABLE vOrdemItem INTEGER ;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdordemdifaliq IS NULL) OR (NEW.bdordemdifaliq = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.BDCHAVE) INTO vordemItem;
          NEW.bdordem = vOrdemItem;
        END

       SELECT COALESCE((MAX(bdordemdifaliq)+1), 1) FROM VEF_EMP_TMOVENTDIFALIQ WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.BDCHAVE) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
       NEW.bdordemdifaliq = vNova_Chave;

    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END
    
       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
          BEGIN
             SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.bdchave) INTO vordemItem;
             NEW.bdordem = vOrdemItem;
          END

       SELECT bdordemdifaliq FROM VEF_EMP_TMOVENTDIFALIQ
       WHERE (bdordemdifaliq = NEW.bdordemdifaliq) AND (BDORDEM = NEW.BDORDEM) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemdifaliq)+1), 1) FROM VEF_EMP_TMOVENTDIFALIQ
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
           NEW.bdordemdifaliq = vNova_Chave;
         END

    END
  end
END
^

CREATE OR ALTER trigger vef_emp_tmoventdocaref_bi0 for vef_emp_tmoventdocaref
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vordemdocaref INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemic INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdordemdocaref IS NULL) OR (NEW.bdordemdocaref = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemic;
          NEW.bdordemic = vordemic;
        END

      SELECT COALESCE((MAX(bdordemdocaref)+1), 1) FROM VEF_EMP_TMOVENTDOCAREF
      WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemdocaref;

      NEW.bdordemdocaref = vordemdocaref;

    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemic;
           NEW.bdordemic = vordemic;
         END

       SELECT bdordemdocaref FROM VEF_EMP_TMOVENTDOCAREF
       WHERE (bdordemdocaref = NEW.bdordemdocaref) AND (bdOrdemic = NEW.bdordemic) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemdocaref)+1), 1) FROM vef_emp_tmoventdocaref WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemdocaref;
           NEW.bdordemdocaref = vordemdocaref;
         END
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_tmoventdocfref_bi0 for vef_emp_tmoventdocfref
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemic INTEGER;
  DECLARE VARIABLE vordemdocfref INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdordemdocfref IS NULL) OR (NEW.bdordemdocfref = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemic;
          NEW.bdordemic = vordemic;
        END

       SELECT COALESCE((MAX(bdordemdocfref)+1), 1) FROM vef_emp_tmoventdocfref
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemdocfref;

       NEW.bdordemdocfref = vordemdocfref;
    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemic;
           NEW.bdordemic = vordemic;
         END

       SELECT bdordemdocfref FROM vef_emp_tmoventdocfref
       WHERE (bdordemdocfref = NEW.bdordemdocfref) AND (bdOrdemic = NEW.bdordemic) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemdocfref)+1), 1) FROM vef_emp_tmoventdocfref WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemdocfref;
           NEW.bdordemdocfref = vordemdocfref;
         END
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_tmoventfunrural_bi0 for vef_emp_tmoventfunrural
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_tmoventgrf_bi0 for vef_emp_tmoventgrf
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
  DECLARE VARIABLE vcodigo INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
  end
END^

CREATE OR ALTER trigger vef_emp_tmoventimpretsp_bi0 for vef_emp_tmoventimpretsp
active before insert position 0
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
  DECLARE VARIABLE vcodigo INTEGER;
  DECLARE VARIABLE vordem INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

    IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Ordem;
      NEW.BDORDEM = vNova_Ordem;
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_tmoventinfcom_bi0 for vef_emp_tmoventinfcom
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vCodigo = 0;
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

    IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordemic) + 1), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave ) INTO vCodigo;
       NEW.bdordemic = vCodigo;
     END
    ELSE
    BEGIN
       SELECT bdordemic FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordemic = NEW.bdordemic) INTO vCodigo;

       IF (vCodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdordemic) + 1), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordemic = NEW.bdordemic) INTO vCodigo;
            NEW.bdordemic = vCodigo;
          END
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_tmoventitens_bu0 for vef_emp_tmoventitens
active before update position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    NEW.BDPREFIXONAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4)  AS INTEGER);
    NEW.BDDIGOPERNAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1)  AS INTEGER);
  end
END^

CREATE OR ALTER trigger vef_emp_tmoventmva_bi0 for vef_emp_tmoventmva
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
  DECLARE VARIABLE vOrdemItem INTEGER ;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdordemmva IS NULL) OR (NEW.bdordemmva = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.BDCHAVE) INTO vordemItem;
          NEW.bdordem = vOrdemItem;
        END

       SELECT COALESCE((MAX(bdordemmva)+1), 1) FROM VEF_EMP_TMOVENTMVA WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.BDCHAVE) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
       NEW.bdordemmva = vNova_Chave;

    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END
    
       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
          BEGIN
             SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.bdchave) INTO vordemItem;
             NEW.bdordem = vOrdemItem;
          END

       SELECT bdordemmva FROM VEF_EMP_TMOVENTMVA
       WHERE (bdordemmva = NEW.bdordemmva) AND (BDORDEM = NEW.BDORDEM) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemmva)+1), 1) FROM VEF_EMP_TMOVENTMVA
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
           NEW.bdordemmva = vNova_Chave;
         END

    END
  end
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVENTOCOSP_BI0 FOR VEF_EMP_TMOVENTOCOSP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
  DECLARE VARIABLE vcodigo INTEGER;
  DECLARE VARIABLE vordem INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

  IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Ordem;
      NEW.BDORDEM = vNova_Ordem;
    END
END
^

CREATE OR ALTER trigger vef_emp_tmoventopimp_bi0 for vef_emp_tmoventopimp
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemopimp INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdordemopimp IS NULL) OR (NEW.bdordemopimp = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

       SELECT COALESCE((MAX(bdordemopimp)+1), 1) FROM vef_emp_tmoventopimp
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vordemopimp;

       NEW.bdordemopimp = vordemopimp;
    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       SELECT bdordemopimp FROM vef_emp_tmoventopimp
       WHERE (bdordemopimp = NEW.bdordemopimp) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemopimp)+1), 1) FROM vef_emp_tmoventopimp WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vordemopimp;
           NEW.bdordemopimp = vordemopimp;
         END
    END
  end
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVENTPMPF_BI0 FOR VEF_EMP_TMOVENTPMPF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
  DECLARE VARIABLE vOrdemItem INTEGER ;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordempmpf IS NULL) OR (NEW.bdordempmpf = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.BDCHAVE) INTO vordemItem;
          NEW.bdordem = vOrdemItem;
        END

       SELECT COALESCE((MAX(bdordempmpf)+1), 1) FROM vef_emp_tmoventpmpf WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.BDCHAVE) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
       NEW.bdordempmpf = vNova_Chave;

    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END
    
       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
          BEGIN
             SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.bdchave) INTO vordemItem;
             NEW.bdordem = vOrdemItem;
          END

       SELECT bdordempmpf FROM vef_emp_tmoventpmpf
       WHERE (bdordempmpf = NEW.bdordempmpf) AND (BDORDEM = NEW.BDORDEM) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordempmpf)+1), 1) FROM vef_emp_tmoventpmpf
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
           NEW.bdordempmpf = vNova_Chave;
         END

    END

END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVENTPROREF_BI0 FOR VEF_EMP_TMOVENTPROREF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemic INTEGER;
  DECLARE VARIABLE vordemproref INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemproref IS NULL) OR (NEW.bdordemproref = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemic;
          NEW.bdordemic = vordemic;
        END

       SELECT COALESCE((MAX(bdordemproref)+1), 1) FROM vef_emp_tmoventproref
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemproref;

       NEW.bdordemproref = vordemproref;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmoventinfcom WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemic;
           NEW.bdordemic = vordemic;
         END

       SELECT bdordemproref FROM vef_emp_tmoventproref
       WHERE (bdordemproref = NEW.bdordemproref) AND (bdOrdemic = NEW.bdordemic) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemproref)+1), 1) FROM vef_emp_tmoventproref WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemproref;
           NEW.bdordemproref = vordemproref;
         END

    END
END
^

CREATE OR ALTER trigger vef_emp_tmoventsn_bi0 for vef_emp_tmoventsn
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER;
  DECLARE VARIABLE vChavesn INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdchavesn IS NULL) OR (NEW.bdchavesn = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
          NEW.bdordem = vordem;
        END

       SELECT COALESCE((MAX(bdchavesn)+1), 1) FROM vef_emp_tmoventsn
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vChavesn;

       NEW.bdchavesn = vChavesn;
    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
           NEW.bdordem = vordem;
         END

       SELECT bdchavesn FROM vef_emp_tmoventsn
       WHERE (bdchavesn = NEW.bdchavesn) AND (bdOrdem = NEW.bdordem) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchavesn)+1), 1) FROM vef_emp_tmoventsn WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vChavesn;
           NEW.bdchavesn = vChavesn;
         END
    END
  end
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVENTSTDAPI_BI0 FOR VEF_EMP_TMOVENTSTDAPI
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
  DECLARE VARIABLE vOrdemItem INTEGER ;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemst IS NULL) OR (NEW.bdordemst = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.BDCHAVE) INTO vordemItem;
          NEW.bdordem = vOrdemItem;
        END

       SELECT COALESCE((MAX(bdordemst)+1), 1) FROM VEF_EMP_TMOVENTSTDAPI WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.BDCHAVE) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
       NEW.bdordemst = vNova_Chave;

    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END
    
       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
          BEGIN
             SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.bdchave) INTO vordemItem;
             NEW.bdordem = vOrdemItem;
          END

       SELECT bdordemst FROM VEF_EMP_TMOVENTSTDAPI
       WHERE (bdordemst = NEW.bdordemst) AND (BDORDEM = NEW.BDORDEM) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemst)+1), 1) FROM VEF_EMP_TMOVENTSTDAPI
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
           NEW.bdordemst = vNova_Chave;
         END

    END

END
^

CREATE OR ALTER trigger vef_emp_tmoventsva_bi0 for vef_emp_tmoventsva
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vCodigo = 0;
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       NEW.bdchave = vcodigo;
    END
  end
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVENTTELCONV_BI0 FOR VEF_EMP_TMOVENTTELCONV
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDEMTEL IS NULL) OR (NEW.BDORDEMTEL = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEMTEL)+1), 1) FROM vef_emp_tmoventtelconv WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Chave;
      NEW.BDORDEMTEL = vNova_Chave;
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
          NEW.BDCHAVE = vchavelan;
        END
    END
  ELSE
    BEGIN
       SELECT BDORDEMTEL FROM vef_emp_tmoventtelconv WHERE (BDORDEMTEL = NEW.BDORDEMTEL) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMTEL)+1), 1) FROM vef_emp_tmoventtelconv WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
           NEW.BDORDEMTEL = vNova_Chave;
         END

       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
          NEW.BDCHAVE = vchavelan;
        END

    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVENTVINCBEM_BI0 FOR VEF_EMP_TMOVENTVINCBEM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER;
  DECLARE VARIABLE vordvinc INTEGER;
BEGIN
  vcodigo = 0;

  IF ((NEW.BDORDVINC IS NULL) OR (NEW.BDORDVINC = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
          NEW.bdordem = vordem;
        END

       SELECT COALESCE((MAX(BDORDVINC)+1), 1) FROM vef_emp_tmoventvincbem
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vordvinc;
       NEW.BDORDVINC = vordvinc;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
           NEW.bdordem = vordem;
         END
  
       SELECT COALESCE((MAX(BDORDVINC)+1), 1) FROM vef_emp_tmoventvincbem
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDVINC)+1), 1) FROM vef_emp_tmoventvincbem
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vordvinc;
           NEW.BDORDVINC = vordvinc;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVEXPINDIRETA_BI0 FOR VEF_EMP_TMOVEXPINDIRETA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER;
  DECLARE VARIABLE vordemed INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemed IS NULL) OR (NEW.bdordemed = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovexpnfsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovexpnfsai WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
          NEW.bdordem = vordem;
        END

       SELECT COALESCE((MAX(bdordemed)+1), 1) FROM vef_emp_tmovexpindireta
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vordemed;

       NEW.bdordemed = vordemed;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovexpnfsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovexpnfsai WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
           NEW.bdordem = vordem;
         END

       SELECT bdordemed FROM vef_emp_tmovexpindireta
       WHERE (bdordemed = NEW.bdordemed) AND (bdOrdem = NEW.bdordem) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemed)+1), 1) FROM vef_emp_tmovexpindireta WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vordemed;
           NEW.bdordemed = vordemed;
         END

    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVF111_BI0 FOR VEF_EMP_TMOVF111
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vcodproref INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodproref IS NULL) OR (NEW.bdcodproref = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
            SELECT COALESCE((MAX(BDChave)), 1) FROM vef_emp_tmovdemaisdoc_f100 WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
            NEW.bdchave = vchave;
         END
       SELECT COALESCE((MAX(bdcodproref)+1), 1) FROM vef_emp_tmovf111
       WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodproref;
       NEW.bdcodproref = vcodproref;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
            SELECT COALESCE((MAX(BDChave)), 1) FROM vef_emp_tmovdemaisdoc_f100 WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
            NEW.bdchave = vchave;
         END

       SELECT bdcodproref FROM vef_emp_tmovf111
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) AND (bdcodproref = NEW.bdcodproref) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodproref)+1), 1) FROM vef_emp_tmovf111
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) AND (bdcodproref = NEW.bdcodproref) INTO vcodproref;
           NEW.bdcodproref = vcodproref;
         END

    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVINV_BI0 FOR VEF_EMP_TMOVINV
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vChave INTEGER;
BEGIN
  IF ((NEW.bdcodtipo = 101) OR (NEW.bdcodtipo = 102)) THEN
     BEGIN
       vcodigo = 0;
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tmovinv WHERE bdcodemp = NEW.bdcodemp INTO vChave;
           NEW.bdchave = vChave;
         END
       ELSE
         BEGIN
           SELECT bdchave FROM vef_emp_tmovinv WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
    
           IF (vcodigo > 0) THEN
             BEGIN
               SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tmovinv WHERE bdcodemp = NEW.bdcodemp INTO vChave;
               NEW.bdchave = vChave;
             END
         END
     END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  -- só atribui o usuário se for nulo
  IF (NEW.bdcodusu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusu = vcodigo;
    END
  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;
  --TIPO DO LANCAMENTO DA TABELA TIPOS_LANCAMENTOS_PADRAO
  IF ((NEW.BDCODTIPO IS NULL) OR (NEW.BDCODTIPO = 0)) THEN
     NEW.BDCODTIPO = 101;

END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVOCO_GIASP_BI0 FOR VEF_EMP_TMOVOCO_GIASP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;

  IF ((NEW.bdchaveocogiasp IS NULL) OR (NEW.bdchaveocogiasp = 0)) THEN
     BEGIN
        SELECT bdresult +1 FROM maxsci('bdchaveocogiasp', 'bdcodemp, bdchaveocogiasp', 'bdcodemp = '||NEW.bdcodemp || ' AND ' || 'BDCODTIPOOCOGIA = '||NEW.bdcodtipoocogia , 'VEF_EMP_TMOVOCO_GIASP') INTO vCodigo;
        NEW.bdchaveocogiasp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdchaveocogiasp FROM VEF_EMP_TMOVOCO_GIASP WHERE (bdchaveocogiasp = NEW.bdchaveocogiasp) AND (bdcodemp = NEW.bdcodemp) AND (bdcodtipoocogia = NEW.bdcodtipoocogia) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT bdresult +1 FROM maxsci('bdchaveocogiasp', 'bdcodemp, bdchaveocogiasp', 'bdcodemp = '||NEW.bdcodemp || ' AND ' || 'bdcodtipoocogia = '||NEW.bdcodtipoocogia , 'VEF_EMP_TMOVOCO_GIASP') INTO vCodigo;
            NEW.bdchaveocogiasp = vcodigo;
         END
    END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  --Não está buscando o código do usuário, por isso esse código é setado na tela mesmo
  --select bdcodusu from vw_variaveis_sessao_banco into vcodigo;
  --new.bdcodusu = vcodigo;
  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVOPECARTAO_BI0 FOR VEF_EMP_TMOVOPECARTAO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vCHAVE INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM vef_emp_tmovopecartao WHERE bdcodemp = NEW.bdcodemp INTO vCHAVE;
      NEW.BDCHAVE = vCHAVE;
    END
  ELSE
    BEGIN
       SELECT BDCHAVE FROM vef_emp_tmovopecartao WHERE (BDCHAVE = NEW.BDCHAVE) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM vef_emp_tmovopecartao WHERE bdcodemp = NEW.bdcodemp INTO vCHAVE;
           NEW.BDCHAVE = vCHAVE;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVOREC_BI0 FOR VEF_EMP_TMOVOREC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  IF ((NEW.bdcodtipo <> 101) OR (NEW.bdcodtipo <> 102))  THEN
     BEGIN
       vcodigo = 0;
       IF ((NEW.bdchaveorec IS NULL) OR (NEW.bdchaveorec = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchaveorec)+1), 1) FROM vef_emp_tmovorec WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdchaveorec = vNova_Chave;
         END
       ELSE
         BEGIN
           SELECT bdchaveorec FROM vef_emp_tmovorec WHERE (bdchaveorec = NEW.bdchaveorec) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
           IF (vcodigo > 0) THEN
             BEGIN
               SELECT COALESCE((MAX(bdchaveorec)+1), 1) FROM vef_emp_tmovorec WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
               NEW.bdchaveorec = vNova_Chave;
             END
        END
     END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  if (new.BDCODUSU is null) then
  begin
    select BDCODUSU from VW_VARIAVEIS_SESSAO_BANCO into VCODIGO;
    new.BDCODUSU = VCODIGO;
  end

  if (new.BDCODUSUINCLU is null) then
  begin
    select BDCODUSU from VW_VARIAVEIS_SESSAO_BANCO into VCODIGO;
    new.BDCODUSUINCLU = VCODIGO;
  end
  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;
  --TIPO DO LANCAMENTO DA TABELA TIPOS_LANCAMENTOS_PADRAO
  IF ((NEW.BDCODTIPO IS NULL) OR (NEW.BDCODTIPO = 0)) THEN
     NEW.BDCODTIPO = 101;

END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVOUTCREDCIAP_BI0 FOR VEF_EMP_TMOVOUTCREDCIAP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDCODOUTCREDCIAP IS NULL) OR (NEW.BDCODOUTCREDCIAP = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODOUTCREDCIAP)+1), 1) FROM VEF_EMP_TMOVOUTCREDCIAP WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.BDCODOUTCREDCIAP = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT BDCODOUTCREDCIAP FROM VEF_EMP_TMOVOUTCREDCIAP WHERE (BDCODOUTCREDCIAP = NEW.BDCODOUTCREDCIAP) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCODOUTCREDCIAP)+1), 1) FROM VEF_EMP_TMOVOUTCREDCIAP WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.BDCODOUTCREDCIAP = vNova_Chave;
         END
    END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  --Não está buscando o código do usuário, por isso esse código é setado na tela mesmo
  --select bdcodusu from vw_variaveis_sessao_banco into vcodigo;
  --new.bdcodusu = vcodigo;
  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;
END
^

CREATE OR ALTER trigger vef_emp_tmovproent_bi0 for vef_emp_tmovproent
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER;
  DECLARE VARIABLE vordempro INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdordempro IS NULL) OR (NEW.bdordempro = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
          NEW.bdordem = vordem;
        END

       SELECT COALESCE((MAX(bdordempro)+1), 1) FROM vef_emp_tmovproent
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vordempro;

       NEW.bdordempro = vordempro;
    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
           NEW.bdordem = vordem;
         END

       SELECT bdordempro FROM vef_emp_tmovproent
       WHERE (bdordempro = NEW.bdordempro) AND (bdOrdem = NEW.bdordem) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordempro)+1), 1) FROM vef_emp_tmovproent WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vordempro;
           NEW.bdordempro = vordempro;
         END

    END
  end
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVPROENTGRF_BI0 FOR VEF_EMP_TMOVPROENTGRF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER;
  DECLARE VARIABLE vordempro INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(bdchave), 1) FROM vef_emp_tmovproent WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
      NEW.bdchave = vchave;
    END

  IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(bdORDEM), 1) FROM vef_emp_tmovproent WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vOrdem;
      NEW.BDORDEM = vOrdem;
    END

  IF ((NEW.bdordempro IS NULL) OR (NEW.bdORDEMPRO = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(bdORDEMPRO), 1) FROM vef_emp_tmovproent WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) AND (bdORDEM = NEW.bdordem) INTO vordempro;
      NEW.bdordempro = vordempro;
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVPROSAI_BI0 FOR VEF_EMP_TMOVPROSAI
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER;
  DECLARE VARIABLE vordempro INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  vcodigo = 0;
  IF ((NEW.bdordempro IS NULL) OR (NEW.bdordempro = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
          NEW.bdordem = vordem;
        END

       SELECT COALESCE((MAX(bdordempro)+1), 1) FROM vef_emp_tmovprosai
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vordempro;

       NEW.bdordempro = vordempro;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
           NEW.bdordem = vordem;
         END

       SELECT bdordempro FROM vef_emp_tmovprosai
       WHERE (bdordempro = NEW.bdordempro) AND (bdOrdem = NEW.bdordem) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordempro)+1), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vordempro;
           NEW.bdordempro = vordempro;
         END

    END
  end
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVPROSAIC177_BI0 FOR VEF_EMP_TMOVPROSAIC177
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER;
  DECLARE VARIABLE vordempro INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
      NEW.bdchave = vchave;
    END

  IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vOrdem;
      NEW.BDORDEM = vOrdem;
    END

  IF ((NEW.bdordempro IS NULL) OR (NEW.bdORDEMPRO = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEMPRO)), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) AND (bdORDEM = NEW.bdordem) INTO vordempro;
      NEW.bdordempro = vordempro;
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVPROSAIC178_BI0 FOR VEF_EMP_TMOVPROSAIC178
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER;
  DECLARE VARIABLE vordempro INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
      NEW.bdchave = vchave;
    END

  IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vOrdem;
      NEW.BDORDEM = vOrdem;
    END

  IF ((NEW.bdordempro IS NULL) OR (NEW.bdORDEMPRO = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEMPRO)), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) AND (bdORDEM = NEW.bdordem) INTO vordempro;
      NEW.bdordempro = vordempro;
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVPROSAIGRF_BI0 FOR VEF_EMP_TMOVPROSAIGRF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER;
  DECLARE VARIABLE vordempro INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(bdchave), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
      NEW.bdchave = vchave;
    END

  IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(bdORDEM), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vOrdem;
      NEW.BDORDEM = vOrdem;
    END

  IF ((NEW.bdordempro IS NULL) OR (NEW.bdORDEMPRO = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(bdORDEMPRO), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) AND (bdORDEM = NEW.bdordem) INTO vordempro;
      NEW.bdordempro = vordempro;
    END
END
^

CREATE OR ALTER trigger vef_emp_tmovratent_bi0 for vef_emp_tmovratent
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vCodigo = 0;
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vCodigo;
          NEW.bdordem = vCodigo;
        END

    IF ((NEW.bdordemrat IS NULL) OR (NEW.bdordemrat = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordemrat) + 1), 1) FROM VEF_EMP_TMOVRATENT WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem ) INTO vCodigo;
       NEW.bdordemrat = vCodigo;
     END
    ELSE
     BEGIN
       SELECT bdordemrat FROM VEF_EMP_TMOVRATENT WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem AND bdordemrat = NEW.bdordemrat) INTO vCodigo;

       IF (vCodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdordemrat) + 1), 1) FROM VEF_EMP_TMOVRATENT WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem) INTO vCodigo;
            NEW.bdordemrat = vCodigo;
          END
     END
  end
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVRATSAI_BI0 FOR VEF_EMP_TMOVRATSAI
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vCodigo;
          NEW.bdordem = vCodigo;
        END

  IF ((NEW.bdordemrat IS NULL) OR (NEW.bdordemrat = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordemrat) + 1), 1) FROM VEF_EMP_TMOVRATSAI WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem ) INTO vCodigo;
       NEW.bdordemrat = vCodigo;
     END
  ELSE
     BEGIN
       SELECT bdordemrat FROM VEF_EMP_TMOVRATSAI WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem AND bdordemrat = NEW.bdordemrat) INTO vCodigo;

       IF (vCodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdordemrat) + 1), 1) FROM VEF_EMP_TMOVRATSAI WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem) INTO vCodigo;
            NEW.bdordemrat = vCodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVRATSER_BI0 FOR VEF_EMP_TMOVRATSER
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovSER WHERE (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovSERitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vCodigo;
          NEW.bdordem = vCodigo;
        END

  IF ((NEW.bdordemrat IS NULL) OR (NEW.bdordemrat = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordemrat) + 1), 1) FROM VEF_EMP_TMOVRATSER WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem ) INTO vCodigo;
       NEW.bdordemrat = vCodigo;
     END
  ELSE
     BEGIN
       SELECT bdordemrat FROM VEF_EMP_TMOVRATSER WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem AND bdordemrat = NEW.bdordemrat) INTO vCodigo;

       IF (vCodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdordemrat) + 1), 1) FROM VEF_EMP_TMOVRATSER WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordem = NEW.bdordem) INTO vCodigo;
            NEW.bdordemrat = vCodigo;
          END
     END
END
^


CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAI_INF_NF_SP_BI0 FOR VEF_EMP_TMOVSAI_INF_NF_SP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
  DECLARE VARIABLE vcodigo INTEGER;
  DECLARE VARIABLE vordem INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdCHAVE = NEW.bdchave) INTO vNova_Ordem;
      NEW.BDORDEM = vNova_Ordem;
    END
END
^

CREATE OR ALTER trigger vef_emp_tmovsaicartr_bi0 for vef_emp_tmovsaicartr
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChave INTEGER;
  DECLARE VARIABLE vOrdemItem INTEGER ;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
     BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
            NEW.BDCHAVE = vchave;
          END
 
       SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vef_emp_tmovsaicartr WHERE
            (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem)/* and (bdcodter = new.bdcodter)*/ INTO vNova_Chave;
       NEW.bdordem = vNova_Chave;
     END
    ELSE
     BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
            NEW.BDCHAVE = vchave;
          END

       SELECT BDORDEM FROM vef_emp_tmovsaicartr
       WHERE (BDORDEM = NEW.BDORDEM) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) /*and (bdcodter = new.bdcodter)*/ INTO vcodigo;
       IF (vcodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vef_emp_tmovsaicartr
            WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem)/* and (bdcodter = new.bdcodter)*/ INTO vNova_Chave;
            NEW.BDORDEM = vNova_Chave;
          END
     END
  end
END
^

CREATE OR ALTER trigger vef_emp_tmovsaictr_bi0 for vef_emp_tmovsaictr
active before insert position 0
AS
  DECLARE VARIABLE vcodigo INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vcodigo;
      NEW.bdchave = vcodigo;
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_tmovsaicupref_bi0 for vef_emp_tmovsaicupref
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemic INTEGER;
  DECLARE VARIABLE vordemcupref INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdordemcupref IS NULL) OR (NEW.bdordemcupref = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemic;
          NEW.bdordemic = vordemic;
        END

       SELECT COALESCE((MAX(bdordemcupref)+1), 1) FROM vef_emp_tmovsaicupref
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemcupref;

       NEW.bdordemcupref = vordemcupref;
    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemic;
           NEW.bdordemic = vordemic;
         END

       SELECT bdordemcupref FROM vef_emp_tmovsaicupref
       WHERE (bdordemcupref = NEW.bdordemcupref) AND (bdOrdemic = NEW.bdordemic) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemcupref)+1), 1) FROM vef_emp_tmovsaicupref WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemcupref;
           NEW.bdordemcupref = vordemcupref;
         END
    END
  end
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAIDOCAREF_BI0 FOR VEF_EMP_TMOVSAIDOCAREF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vordemdocaref INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemic INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemdocaref IS NULL) OR (NEW.bdordemdocaref = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemic;
          NEW.bdordemic = vordemic;
        END

      SELECT COALESCE((MAX(bdordemdocaref)+1), 1) FROM VEF_EMP_TMOVSAIDOCAREF
      WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemdocaref;
      NEW.bdordemdocaref = vordemdocaref;
    END
  ELSE
    BEGIN

       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemic;
           NEW.bdordemic = vordemic;
         END

       SELECT bdordemdocaref FROM VEF_EMP_TMOVSAIDOCAREF
       WHERE (bdordemdocaref = NEW.bdordemdocaref) AND (bdOrdemic = NEW.bdordemic) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemdocaref)+1), 1) FROM VEF_EMP_TMOVSAIDOCAREF WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemdocaref;
           NEW.bdordemdocaref = vordemdocaref;
         END

    END
END
^

CREATE OR ALTER trigger vef_emp_tmovsaidocfref_bi0 for vef_emp_tmovsaidocfref
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemic INTEGER;
  DECLARE VARIABLE vordemdocfref INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdordemdocfref IS NULL) OR (NEW.bdordemdocfref = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemic;
          NEW.bdordemic = vordemic;
        END

       SELECT COALESCE((MAX(bdordemdocfref)+1), 1) FROM vef_emp_tmovsaidocfref
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemdocfref;

       NEW.bdordemdocfref = vordemdocfref;
    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemic;
           NEW.bdordemic = vordemic;
         END

       SELECT bdordemdocfref FROM vef_emp_tmovsaidocfref
       WHERE (bdordemdocfref = NEW.bdordemdocfref) AND (bdOrdemic = NEW.bdordemic) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemdocfref)+1), 1) FROM vef_emp_tmovsaidocfref WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemdocfref;
           NEW.bdordemdocfref = vordemdocfref;
         END
    END
  end
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAIEXP_BI0 FOR VEF_EMP_TMOVSAIEXP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1)
       FROM vef_emp_tmovsai
       WHERE (bdcodemp = NEW.bdcodemp)
       INTO vcodigo;
       NEW.bdchave = vcodigo;
     END
/*
  if ((new.bdordem is null) or (new.bdordem = 0)) then
     begin
*/
       SELECT COALESCE((MAX(bdordem) + 1), 1)  FROM  vef_emp_tmovsaiexp
       WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave  INTO vCodigo;
       NEW.bdordem = vCodigo;
/*
     end
  else
     begin
       select bdordem from vef_emp_tmovsaiexp where (bdcodemp = new.bdcodemp and bdchave = new.bdchave and bdordem = new.bdordem) into vCodigo;

       if (vCodigo > 0) then
          begin
            select coalesce((max(bdordem) + 1), 1) from vef_emp_tmovsaiexp
            where (bdcodemp = new.bdcodemp and bdchave = new.bdchave and bdordem = new.bdordem) into vCodigo;
            new.bdordem = vCodigo;
          end
     end
*/
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAIEXPSP_BI0 FOR VEF_EMP_TMOVSAIEXPSP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
  DECLARE VARIABLE vcodigo INTEGER;
  DECLARE VARIABLE vordem INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdCHAVE = NEW.bdchave) INTO vNova_Ordem;
      NEW.BDORDEM = vNova_Ordem;
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAIGRF_BI0 FOR VEF_EMP_TMOVSAIGRF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchavelan INTEGER;
  DECLARE VARIABLE vcodigo INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

END
^

CREATE OR ALTER trigger vef_emp_tmovsaiimpretsp_bi0 for vef_emp_tmovsaiimpretsp
active before insert position 0
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
  DECLARE VARIABLE vcodigo INTEGER;
  DECLARE VARIABLE vordem INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

    IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdCHAVE = NEW.bdchave) INTO vNova_Ordem;
      NEW.BDORDEM = vNova_Ordem;
    END
  end
END
^

/* Trigger: VEF_EMP_TMOVSAIECREDAC_BI0 */
CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAIECREDAC_BI0 FOR VEF_EMP_TMOVSAIECREDAC
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdCHAVE = NEW.bdchave) INTO vNova_Ordem;
      NEW.BDORDEM = vNova_Ordem;
    END
END
^

CREATE OR ALTER trigger vef_emp_tmovsaiinfcom_bi0 for vef_emp_tmovsaiinfcom
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vCodigo = 0;

    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdchave)), 1)
       FROM vef_emp_tmovsai
       WHERE (bdcodemp = NEW.bdcodemp)
       INTO vcodigo;
       NEW.bdchave = vcodigo;
    END

    IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordemic) + 1), 1)  FROM  vef_emp_tmovsaiinfcom
       WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave  INTO vCodigo;
       NEW.bdordemic = vCodigo;
     END
    ELSE
     BEGIN
       SELECT bdordemic FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordemic = NEW.bdordemic) INTO vCodigo;

       IF (vCodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdordemic) + 1), 1) FROM vef_emp_tmovsaiinfcom
            WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordemic = NEW.bdordemic) INTO vCodigo;
            NEW.bdordemic = vCodigo;
          END
     END
  end
END
^

CREATE OR ALTER trigger vef_emp_tmovsaiitens_bu0 for vef_emp_tmovsaiitens
active before update position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    NEW.BDPREFIXONAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4)  AS INTEGER);
    NEW.BDDIGOPERNAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1)  AS INTEGER);
  end
END^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAIITENSCTR_BI0 FOR VEF_EMP_TMOVSAIITENSCTR
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdCHAVE = NEW.bdchave) INTO vNova_Ordem;
      NEW.BDORDEM = vNova_Ordem;
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAILOCCOL_BI0 FOR VEF_EMP_TMOVSAILOCCOL
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemic INTEGER;
  DECLARE VARIABLE vordemloccol INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemloccol IS NULL) OR (NEW.bdordemloccol = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemic;
          NEW.bdordemic = vordemic;
        END

       SELECT COALESCE((MAX(bdordemloccol)+1), 1) FROM vef_emp_tmovsailoccol
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemloccol;

       NEW.bdordemloccol = vordemloccol;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemic;
           NEW.bdordemic = vordemic;
         END

       SELECT bdordemloccol FROM vef_emp_tmovsailoccol
       WHERE (bdordemloccol = NEW.bdordemloccol) AND (bdOrdemic = NEW.bdordemic) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemloccol)+1), 1) FROM vef_emp_tmovsailoccol WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemloccol;
           NEW.bdordemloccol = vordemloccol;
         END

    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAIOCOSP_BI0 FOR VEF_EMP_TMOVSAIOCOSP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
  DECLARE VARIABLE vcodigo INTEGER;
  DECLARE VARIABLE vordem INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdCHAVE = NEW.bdchave) INTO vNova_Ordem;
      NEW.BDORDEM = vNova_Ordem;
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAIPROREF_BI0 FOR VEF_EMP_TMOVSAIPROREF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemic INTEGER;
  DECLARE VARIABLE vordemproref INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemproref IS NULL) OR (NEW.bdordemproref = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordemic;
          NEW.bdordemic = vordemic;
        END

       SELECT COALESCE((MAX(bdordemproref)+1), 1) FROM vef_emp_tmovsaiproref
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemproref;

       NEW.bdordemproref = vordemproref;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordemic IS NULL) OR (NEW.bdordemic = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMIC)), 1) FROM vef_emp_tmovsaiinfcom WHERE (bdordemic = NEW.bdordemic) INTO vordemic;
           NEW.bdordemic = vordemic;
         END

       SELECT bdordemproref FROM vef_emp_tmovsaiproref
       WHERE (bdordemproref = NEW.bdordemproref) AND (bdOrdemic = NEW.bdordemic) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemproref)+1), 1) FROM vef_emp_tmovsaiproref WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdemic = NEW.bdordemic) INTO vordemproref;
           NEW.bdordemproref = vordemproref;
         END

    END
END
^

CREATE OR ALTER trigger vef_emp_tmovsaisn_bi0 for vef_emp_tmovsaisn
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER;
  DECLARE VARIABLE vChavesn INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdchavesn IS NULL) OR (NEW.bdchavesn = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_TMOVSAIitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_TMOVSAIitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
          NEW.bdordem = vordem;
        END

       SELECT COALESCE((MAX(bdchavesn)+1), 1) FROM vef_emp_TMOVSAIsn
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vChavesn;

       NEW.bdchavesn = vChavesn;
    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_TMOVSAIitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_TMOVSAIitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
           NEW.bdordem = vordem;
         END

       SELECT bdchavesn FROM vef_emp_TMOVSAIsn
       WHERE (bdchavesn = NEW.bdchavesn) AND (bdOrdem = NEW.bdordem) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchavesn)+1), 1) FROM vef_emp_TMOVSAIsn WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vChavesn;
           NEW.bdchavesn = vChavesn;
         END
    END
  end
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAISTDAPI_BI0 FOR VEF_EMP_TMOVSAISTDAPI
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
  DECLARE VARIABLE vOrdemItem INTEGER ;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemst IS NULL) OR (NEW.bdordemst = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.BDCHAVE) INTO vordemItem;
          NEW.bdordem = vOrdemItem;
        END

       SELECT COALESCE((MAX(bdordemst)+1), 1) FROM VEF_EMP_TMOVSAISTDAPI WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.BDCHAVE) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
       NEW.bdordemst = vNova_Chave;

    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END
    
       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
          BEGIN
             SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp)
                                                                       AND (bdChave = NEW.bdchave) INTO vordemItem;
             NEW.bdordem = vOrdemItem;
          END

       SELECT bdordemst FROM VEF_EMP_TMOVSAISTDAPI
       WHERE (bdordemst = NEW.bdordemst) AND (BDORDEM = NEW.BDORDEM) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemst)+1), 1) FROM VEF_EMP_TMOVSAISTDAPI
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vNova_Chave;
           NEW.bdordemst = vNova_Chave;
         END

    END

END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAISVA_BI0 FOR VEF_EMP_TMOVSAISVA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAITELCONV_BI0 FOR VEF_EMP_TMOVSAITELCONV
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDEMTEL IS NULL) OR (NEW.BDORDEMTEL = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEMTEL)+1), 1) FROM vef_emp_tmovsaitelconv WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Chave;
      NEW.BDORDEMTEL = vNova_Chave;
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
          NEW.BDCHAVE = vchavelan;
        END
    END
  ELSE
    BEGIN
       SELECT BDORDEMTEL FROM vef_emp_tmovsaitelconv WHERE (BDORDEMTEL = NEW.BDORDEMTEL) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMTEL)+1), 1) FROM vef_emp_tmovsaitelconv WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
           NEW.BDORDEMTEL = vNova_Chave;
         END

       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
          NEW.BDCHAVE = vchavelan;
        END

    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAIVINCBEM_BI0 FOR VEF_EMP_TMOVSAIVINCBEM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER; 
  DECLARE VARIABLE vordvinc INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDVINC IS NULL) OR (NEW.BDORDVINC = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
          NEW.bdordem = vordem;
        END

       SELECT COALESCE((MAX(BDORDVINC)+1), 1) FROM vef_emp_tmovsaivincbem
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vordvinc;
       NEW.BDORDVINC = vordvinc;

    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
           NEW.bdordem = vordem;
         END

       SELECT COALESCE((MAX(BDORDVINC)+1), 1) FROM vef_emp_tmovsaivincbem
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDVINC)+1), 1) FROM vef_emp_tmovsaivincbem
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vordvinc;
           NEW.BDORDVINC = vordvinc;
         END

    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSER_AJISSFLO_BI0 FOR VEF_EMP_TMOVSER_AJISSFLO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDCHAVEAJISSFLO IS NULL) OR (NEW.BDCHAVEAJISSFLO = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVEAJISSFLO)+1), 1) FROM VEF_EMP_TMOVSER_AJISSFLO WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.BDCHAVEAJISSFLO = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT BDCHAVEAJISSFLO FROM VEF_EMP_TMOVSER_AJISSFLO WHERE (BDCHAVEAJISSFLO = NEW.BDCHAVEAJISSFLO) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVEAJISSFLO)+1), 1) FROM VEF_EMP_TMOVSER_AJISSFLO WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.BDCHAVEAJISSFLO = vNova_Chave;
         END
    END
END
^


CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERBHISS_BI0 FOR VEF_EMP_TMOVSERBHISS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERDEDISS_BI0 FOR VEF_EMP_TMOVSERDEDISS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN

  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser
       WHERE (bdcodemp = NEW.bdcodemp)
       INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

  vcodigo = 0;
  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordem)+1), 1) FROM vef_emp_tmovserdediss WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave INTO vcodigo;
      NEW.bdordem = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdordem FROM vef_emp_tmovserdediss WHERE (bdordem = NEW.bdordem) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordem)+1), 1) FROM  vef_emp_tmovserdediss WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave INTO vcodigo;
           NEW.bdordem = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERDEISS_BI0 FOR VEF_EMP_TMOVSERDEISS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVVALAGRE1400_AD0 FOR TOL_VEF_EMP_TMOVVALAGRE1400
ACTIVE AFTER DELETE POSITION 0
AS
begin
  DELETE FROM VEF_EMP_TMOVVALAGRE1400 aju where aju.bdcodemp = old.bdcodemp and aju.BDCHAVE = old.BDCHAVE1400;
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERDMED_BI0 FOR VEF_EMP_TMOVSERDMED
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERGISSONLINE_BI0 FOR VEF_EMP_TMOVSERGISSONLINE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERINDISS_BI0 FOR VEF_EMP_TMOVSERINDISS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERIPM_BI0 FOR VEF_EMP_TMOVSERIPM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

  IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmovseritens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Ordem;
      NEW.BDORDEM = vNova_Ordem;
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERISS_BI0 FOR VEF_EMP_TMOVSERISS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
END
^

CREATE OR ALTER trigger vef_emp_tmovseritens_bu0 for vef_emp_tmovseritens
active before update position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    NEW.BDPREFIXONAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 4)  AS INTEGER);
    NEW.BDDIGOPERNAT = CAST( SUBSTRING(CAST(NEW.bdcodnat AS VARCHAR(7)) FROM 1 FOR 1)  AS INTEGER);
  end
END^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERMATBETHA_BI0 FOR VEF_EMP_TMOVSERMATBETHA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

  IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmovseritens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Ordem;
      NEW.BDORDEM = vNova_Ordem;
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERITENSCUR_BI0 FOR VEF_EMP_TMOVSERITENSCUR
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE wOrdem INTEGER;
  DECLARE VARIABLE wChave INTEGER;
BEGIN
  IF ((NEW.bdCHAVE IS NULL) OR (NEW.bdCHAVE = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdCHAVE)), 1) FROM VEF_EMP_TMOVSER WHERE (bdCODEMP = NEW.bdCODEMP) INTO wChave;
      NEW.bdCHAVE = wChave;
    END

  IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM VEF_EMP_TMOVSERITENS WHERE (bdCODEMP = NEW.bdCODEMP)  AND (bdCHAVE = NEW.bdCHAVE) INTO wOrdem;
      NEW.bdORDEM = wOrdem;
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERPERDCOMP_BI0 FOR VEF_EMP_TMOVSERPERDCOMP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

END
^

CREATE OR ALTER trigger vef_emp_tmovsersn_bi0 for vef_emp_tmovsersn
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER;
  DECLARE VARIABLE vChavesn INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdchavesn IS NULL) OR (NEW.bdchavesn = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_TMOVSERitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_TMOVSERitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
          NEW.bdordem = vordem;
        END

       SELECT COALESCE((MAX(bdchavesn)+1), 1) FROM vef_emp_TMOVSERsn
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vChavesn;

       NEW.bdchavesn = vChavesn;
    END
    ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_TMOVSERitens WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_TMOVSERitens WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
           NEW.bdordem = vordem;
         END

       SELECT bdchavesn FROM vef_emp_TMOVSERsn
       WHERE (bdchavesn = NEW.bdchavesn) AND (bdOrdem = NEW.bdordem) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchavesn)+1), 1) FROM vef_emp_TMOVSERsn WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vChavesn;
           NEW.bdchavesn = vChavesn;
         END
    END
  end
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVTALONSAI_BI0 FOR VEF_EMP_TMOVTALONSAI
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vChave INTEGER;
BEGIN

  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tmovtalonsai WHERE bdcodemp = NEW.bdcodemp INTO vChave;
      NEW.bdchave = vChave;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM vef_emp_tmovtalonsai WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tmovtalonsai WHERE bdcodemp = NEW.bdcodemp INTO vChave;
           NEW.bdchave = vChave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVTALONSER_BI0 FOR VEF_EMP_TMOVTALONSER
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vChave INTEGER;
BEGIN

  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tmovtalonser WHERE bdcodemp = NEW.bdcodemp INTO vChave;
      NEW.bdchave = vChave;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM vef_emp_tmovtalonser WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tmovtalonser WHERE bdcodemp = NEW.bdcodemp INTO vChave;
           NEW.bdchave = vChave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TNUMFUNC_BI0 FOR VEF_EMP_TNUMFUNC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM vef_emp_tnumfunc WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.BDCHAVE = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT BDCHAVE FROM vef_emp_tnumfunc WHERE (BDCHAVE = NEW.BDCHAVE) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM vef_emp_tnumfunc WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.BDCHAVE = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TOCODEBCREMG_BI0 FOR VEF_EMP_TOCODEBCREMG
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;

  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
        SELECT bdresult +1 FROM maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||NEW.bdcodemp || ' AND ' || 'BDCODTPOCO = '||NEW.BDCODTPOCO , 'VEF_EMP_TOCODEBCREMG') INTO vCodigo;
        NEW.bdchave = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdchave FROM vef_emp_tocodebcremg WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) AND (BDCODTPOCO = NEW.BDCODTPOCO) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT bdresult +1 FROM maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||NEW.bdcodemp || ' AND ' || 'BDCODTPOCO = '||NEW.BDCODTPOCO , 'VEF_EMP_TOCODEBCREMG') INTO vCodigo;
            NEW.bdchave = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TOCOGIAES_BI0 FOR VEF_EMP_TOCOGIAES
ACTIVE BEFORE INSERT POSITION 0 
AS
   DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vCodigo = 0;

  IF((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
     BEGIN
       SELECT bdresult + 1 FROM maxsci('bdordem', 'bdcodemp, bdordem', 'bdcodemp = ' ||NEW.bdcodemp || ' AND ' || 'BDCODTIPOOCO ='|| NEW.bdcodtipooco ,'VEF_EMP_TOCOGIAES') INTO vCodigo;
       NEW.bdordem = vcodigo;
     END
   ELSE
     BEGIN
       SELECT bdOrdem FROM vef_emp_tocogiaes WHERE (bdordem = NEW.bdordem) AND (bdcodemp = NEW.bdcodemp) AND (bdcodtipooco = NEW.bdcodtipooco) INTO vCodigo;

       IF ((vCodigo > 0)) THEN
          BEGIN
            SELECT bdresult + 1 FROM maxsci('bdordem', 'bdcodemp, bdordem', 'bdcodemp = ' ||NEW.bdcodemp || ' AND ' || 'BDCODTIPOOCO ='|| NEW.bdcodtipooco ,'VEF_EMP_TOCOGIAES') INTO vCodigo;
            NEW.bdordem = vcodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TOCOGIARO_BI0 FOR VEF_EMP_TOCOGIARO
ACTIVE BEFORE INSERT POSITION 0 
AS
   DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vCodigo = 0;

  IF((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
     BEGIN
       SELECT bdresult + 1 FROM maxsci('bdordem', 'bdcodemp, bdordem', 'bdcodemp = ' ||NEW.bdcodemp || ' AND ' || 'BDCODTIPOOCOGIA ='|| NEW.BDCODTIPOOCOGIA ,'VEF_EMP_TOCOGIARO') INTO vCodigo;
       NEW.bdordem = vcodigo;
     END
   ELSE
     BEGIN
       SELECT bdOrdem FROM vef_emp_tocogiaro WHERE (bdordem = NEW.bdordem) AND (bdcodemp = NEW.bdcodemp) AND (BDCODTIPOOCOGIA = NEW.BDCODTIPOOCOGIA) INTO vCodigo;

       IF ((vCodigo > 0)) THEN
          BEGIN
            SELECT bdresult + 1 FROM maxsci('bdordem', 'bdcodemp, bdordem', 'bdcodemp = ' ||NEW.bdcodemp || ' AND ' || 'BDCODTIPOOCOGIA ='|| NEW.BDCODTIPOOCOGIA ,'VEF_EMP_TOCOGIARO') INTO vCodigo;
            NEW.bdordem = vcodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TOCOMG_BI0 FOR VEF_EMP_TOCOMG
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;

  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
        SELECT bdresult +1 FROM maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||NEW.bdcodemp || ' AND ' || 'BDCODTPOCO = '||NEW.BDCODTPOCO , 'VEF_EMP_TOCOMG') INTO vCodigo;
        NEW.bdchave = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdchave FROM VEF_EMP_TOCOMG WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) AND (BDCODTPOCO = NEW.BDCODTPOCO) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT bdresult +1 FROM maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||NEW.bdcodemp || ' AND ' || 'BDCODTPOCO = '||NEW.BDCODTPOCO , 'VEF_EMP_TOCOMG') INTO vCodigo;
            NEW.bdchave = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TOCOMG070_BI0 FOR VEF_EMP_TOCOMG070
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vChave INTEGER;
BEGIN
    vcodigo = 0;
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)+1), 1) FROM VEF_EMP_TOCOMG070 WHERE bdcodemp = NEW.bdcodemp INTO vChave;
       NEW.bdchave = vChave;
     END
    ELSE
     BEGIN
       SELECT bdchave FROM VEF_EMP_TOCOMG070 WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
    
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM VEF_EMP_TOCOMG070 WHERE bdcodemp = NEW.bdcodemp INTO vChave;
           NEW.bdchave = vChave;
         END
     END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TOCOMG090_BI0 FOR VEF_EMP_TOCOMG090
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vChave INTEGER;
BEGIN
    vcodigo = 0;
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)+1), 1) FROM VEF_EMP_TOCOMG090 WHERE bdcodemp = NEW.bdcodemp INTO vChave;
       NEW.bdchave = vChave;
     END
    ELSE
     BEGIN
       SELECT bdchave FROM VEF_EMP_TOCOMG090 WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
    
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM VEF_EMP_TOCOMG090 WHERE bdcodemp = NEW.bdcodemp INTO vChave;
           NEW.bdchave = vChave;
         END
     END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TOCOMG095_BI0 FOR VEF_EMP_TOCOMG095
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vChave INTEGER;
BEGIN
    vcodigo = 0;
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)+1), 1) FROM VEF_EMP_TOCOMG095 WHERE bdcodemp = NEW.bdcodemp INTO vChave;
       NEW.bdchave = vChave;
     END
    ELSE
     BEGIN
       SELECT bdchave FROM VEF_EMP_TOCOMG095 WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
    
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM VEF_EMP_TOCOMG095 WHERE bdcodemp = NEW.bdcodemp INTO vChave;
           NEW.bdchave = vChave;
         END
     END
END
^

CREATE OR ALTER trigger vef_emp_topmedent_bi0 for vef_emp_topmedent
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER;
  DECLARE VARIABLE vordempro INTEGER;
  DECLARE VARIABLE vordemopmed INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdordemopmed IS NULL) OR (NEW.bdordemopmed = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovproent WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovproent WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
          NEW.bdordem = vordem;
        END

       IF ((NEW.bdordempro IS NULL) OR (NEW.bdordempro = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(bdordempro)), 1) FROM vef_emp_tmovproent
            WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vordempro;
            NEW.bdordempro = vordempro;
          END

      SELECT COALESCE((MAX(bdordemopmed)+1), 1) FROM vef_emp_topmedent
      WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) AND (bdordempro = NEW.bdordempro) INTO vcodigo;
      NEW.bdordemopmed = vcodigo;

     END
    ELSE
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovproent WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovproent WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
           NEW.bdordem = vordem;
         END

      IF ((NEW.bdordempro IS NULL) OR (NEW.bdordempro = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordempro)), 1) FROM vef_emp_tmovproent WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vordempro;
           NEW.bdordempro = vordempro;
         END

      SELECT bdordemopmed FROM vef_emp_topmedent
      WHERE (bdordemopmed = NEW.bdordemopmed) AND (bdordempro = NEW.bdordempro) AND (bdordem = NEW.bdordem) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

      IF (vcodigo > 0) THEN
        BEGIN
          SELECT COALESCE((MAX(bdordemopmed)+1), 1) FROM vef_emp_topmedent
          WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) AND (bdordemopmed = NEW.bdordemopmed) INTO vordemopmed;
          NEW.bdordemopmed = vordemopmed;
        END

    END
  end
END
^

CREATE OR ALTER trigger vef_emp_topmedsai_bi0 for vef_emp_topmedsai
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER;
  DECLARE VARIABLE vordempro INTEGER;
  DECLARE VARIABLE vordemopmed INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    vcodigo = 0;
    IF ((NEW.bdordemopmed IS NULL) OR (NEW.bdordemopmed = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
          NEW.bdordem = vordem;
        END

       IF ((NEW.bdordempro IS NULL) OR (NEW.bdordempro = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(bdordempro)), 1) FROM vef_emp_tmovprosai
            WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vordempro;
            NEW.bdordempro = vordempro;
          END

      SELECT COALESCE((MAX(bdordemopmed)+1), 1) FROM vef_emp_topmedsai
      WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) AND (bdordempro = NEW.bdordempro) INTO vcodigo;
      NEW.bdordemopmed = vcodigo;

     END
    ELSE
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
           NEW.bdordem = vordem;
         END

      IF ((NEW.bdordempro IS NULL) OR (NEW.bdordempro = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordempro)), 1) FROM vef_emp_tmovprosai WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vordempro;
           NEW.bdordempro = vordempro;
         END

      SELECT bdordemopmed FROM vef_emp_topmedsai
      WHERE (bdordemopmed = NEW.bdordemopmed) AND (bdordempro = NEW.bdordempro) AND (bdordem = NEW.bdordem) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

      IF (vcodigo > 0) THEN
        BEGIN
          SELECT COALESCE((MAX(bdordemopmed)+1), 1) FROM vef_emp_topmedsai
          WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) AND (bdordemopmed = NEW.bdordemopmed) INTO vordemopmed;
          NEW.bdordemopmed = vordemopmed;
        END
    END
  end
END
^

CREATE OR ALTER TRIGGER vef_emp_tplasncreddarf_ad0 FOR vef_emp_tplasncreddarf
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  DELETE FROM VEF_EMP_TPLANILHASNCRED sn WHERE (sn.BDCODEMP = OLD.bdcodfilial) AND (sn.bdcodplasn = OLD.bdcodplasn);
END
^

CREATE OR ALTER TRIGGER vef_emp_tplasndebdarf_ad0 FOR vef_emp_tplasndebdarf
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  DELETE FROM VEF_EMP_TPLANILHASNDEB sn WHERE (sn.BDCODEMP = OLD.bdcodfilial) AND (sn.bdcodplasn = OLD.bdcodplasn);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TREDZ_BI0 FOR VEF_EMP_TREDZ
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vChave INTEGER;
BEGIN
  IF ((NEW.bdcodtipo = 101) OR (NEW.bdcodtipo = 102)) THEN
     BEGIN
       vcodigo = 0;
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tredz WHERE bdcodemp = NEW.bdcodemp INTO vChave;
           NEW.bdchave = vChave;
         END
       ELSE
         BEGIN
           SELECT bdchave FROM vef_emp_tredz WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
    
           IF (vcodigo > 0) THEN
             BEGIN
               SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tredz WHERE bdcodemp = NEW.bdcodemp INTO vChave;
               NEW.bdchave = vChave;
             END
       END

       SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
       NEW.bdcodusu = vcodigo;
     END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;
  --TIPO DO LANCAMENTO DA TABELA TIPOS_LANCAMENTOS_PADRAO
  IF ((NEW.BDCODTIPO IS NULL) OR (NEW.BDCODTIPO = 0)) THEN
     NEW.BDCODTIPO = 101;

  NEW.bdreflan = CAST(SUBSTRING(CAST(NEW.BDDATAREDZ AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.BDDATAREDZ AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);
END
^


CREATE OR ALTER TRIGGER VEF_EMP_TREDZC425_BI0 FOR VEF_EMP_TREDZC425
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemc425 INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemc425 IS NULL) OR (NEW.bdordemc425 = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tredz WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

       SELECT COALESCE((MAX(bdordemc425)+1), 1) FROM vef_emp_tredzc425
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdORDEMTOT = NEW.bdordemtot) INTO vordemc425;
       NEW.bdordemc425 = vordemc425;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tredz WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       SELECT bdordemc425 FROM vef_emp_tredzc425
       WHERE (bdordemc425 = NEW.bdordemc425) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) AND (bdORDEMTOT = NEW.bdordemtot) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemc425)+1), 1) FROM vef_emp_tredzc425 WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdORDEMTOT = NEW.bdordemtot) INTO vordemc425;
           NEW.bdordemc425 = vordemc425;
         END

    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TREDZC425ALIQ_BI0 FOR VEF_EMP_TREDZC425ALIQ
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemc425 INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemc425 IS NULL) OR (NEW.bdordemc425 = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tredz WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

       SELECT COALESCE((MAX(bdordemc425)+1), 1) FROM vef_emp_tredzc425aliq
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdORDEMTOT = NEW.bdordemtot) AND (BDORDEMICMS = NEW.BDORDEMICMS) INTO vordemc425;
       NEW.bdordemc425 = vordemc425;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tredz WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       SELECT bdordemc425 FROM vef_emp_tredzc425aliq
       WHERE (bdordemc425 = NEW.bdordemc425) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) AND (bdORDEMTOT = NEW.bdordemtot) AND (BDORDEMICMS = NEW.BDORDEMICMS) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemc425)+1), 1) FROM vef_emp_tredzc425aliq WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdORDEMTOT = NEW.bdordemtot) AND (BDORDEMICMS = NEW.BDORDEMICMS) INTO vordemc425;
           NEW.bdordemc425 = vordemc425;
         END

    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TREDZC490_BI0 FOR VEF_EMP_TREDZC490
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemtot INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemtot IS NULL) OR (NEW.bdordemtot = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tredz WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

       SELECT COALESCE((MAX(bdordemtot)+1), 1) FROM vef_emp_tredzc490
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vordemtot;
       NEW.bdordemtot = vordemtot;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tredz WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       SELECT bdordemtot FROM vef_emp_tredzc490
       WHERE (bdordemtot = NEW.bdordemtot) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemtot)+1), 1) FROM vef_emp_tredzc490 WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vordemtot;
           NEW.bdordemtot = vordemtot;
         END

    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TREDZDADOSSPED_BI0 FOR VEF_EMP_TREDZDADOSSPED
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vORDEMDSPED INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDEMDSPED IS NULL) OR (NEW.BDORDEMDSPED = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tredz WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

       SELECT COALESCE((MAX(BDORDEMDSPED)+1), 1) FROM VEF_EMP_TREDZDADOSSPED
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vORDEMDSPED;
       NEW.BDORDEMDSPED = vORDEMDSPED;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tredz WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       SELECT BDORDEMDSPED FROM VEF_EMP_TREDZDADOSSPED
       WHERE (BDORDEMDSPED = NEW.BDORDEMDSPED) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMDSPED)+1), 1) FROM VEF_EMP_TREDZDADOSSPED WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vORDEMDSPED;
           NEW.BDORDEMDSPED = vORDEMDSPED;
         END

    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TREDZSN_BI0 FOR VEF_EMP_TREDZSN
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordemSN INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemsnredz IS NULL) OR (NEW.bdordemsnredz = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tredz WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

       SELECT COALESCE((MAX(bdordemsnredz)+1), 1) FROM vef_emp_tredzsn
       WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (BDORDEMVARCFOP = NEW.BDORDEMVARCFOP) INTO vordemSN;
       NEW.bdordemsnredz = vordemSN;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM vef_emp_tredz WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       SELECT bdordemsnredz FROM vef_emp_tredzsn
       WHERE (bdordemsnredz = NEW.bdordemsnredz) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) AND (BDORDEMVARCFOP = NEW.BDORDEMVARCFOP) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemsnredz)+1), 1) FROM vef_emp_tredzsn WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (BDORDEMVARCFOP = NEW.BDORDEMVARCFOP) INTO vordemSN;
           NEW.bdordemsnredz = vordemSN;
         END

    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TREDZVARALIQ_BI0 FOR VEF_EMP_TREDZVARALIQ
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDEMICMS IS NULL) OR (NEW.BDORDEMICMS = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM VEF_EMP_TREDZ WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       SELECT COALESCE((MAX(BDORDEMICMS)+1), 1) FROM VEF_EMP_TREDZVARALIQ WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.BDCHAVE) INTO vNova_Chave;
       NEW.BDORDEMICMS = vNova_Chave;

    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM VEF_EMP_TREDZ WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END
    
       SELECT BDORDEMICMS FROM VEF_EMP_TREDZVARALIQ
       WHERE (BDORDEMICMS = NEW.bdordemicms) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMICMS)+1), 1) FROM VEF_EMP_TREDZVARALIQ
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
           NEW.BDORDEMICMS = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TREDZVARCFOP_BI0 FOR VEF_EMP_TREDZVARCFOP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vChaveItem INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemvarcfop IS NULL) OR (NEW.bdordemvarcfop = 0)) THEN
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM VEF_EMP_TREDZ WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
          NEW.BDCHAVE = vchaveitem;
        END

       SELECT COALESCE((MAX(bdordemvarcfop)+1), 1) FROM VEF_EMP_TREDZVARCFOP WHERE
             (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.BDCHAVE) INTO vNova_Chave;
       NEW.bdordemvarcfop = vNova_Chave;

    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
          BEGIN
            SELECT COALESCE((MAX(BDCHAVE)), 1) FROM VEF_EMP_TREDZ WHERE (bdcodemp = NEW.bdcodemp) INTO vchaveItem;
            NEW.BDCHAVE = vchaveitem;
          END
    
       SELECT bdordemvarcfop FROM VEF_EMP_TREDZVARCFOP
       WHERE (bdordemvarcfop = NEW.bdordemvarcfop) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemvarcfop)+1), 1) FROM VEF_EMP_TREDZVARCFOP
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
           NEW.bdordemvarcfop = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TSALDOSN_BI0 FOR VEF_EMP_TSALDOSN
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDCHAVESALDOSN IS NULL) OR (NEW.BDCHAVESALDOSN = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVESALDOSN)+1), 1) FROM vef_emp_tsaldosn WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.BDCHAVESALDOSN = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT BDCHAVESALDOSN FROM vef_emp_tsaldosn WHERE (BDCHAVESALDOSN = NEW.BDCHAVESALDOSN) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVESALDOSN)+1), 1) FROM vef_emp_tsaldosn WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.BDCHAVESALDOSN = vNova_Chave;
         END
    END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  --Não está buscando o código do usuário, por isso esse código é setado na tela mesmo
  --select bdcodusu from vw_variaveis_sessao_banco into vcodigo;
  --new.bdcodusu = vcodigo;
  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TSIMPLESNACIONAL_BI0 FOR VEF_EMP_TSIMPLESNACIONAL
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
--  elizeu - 22-08-18 - Simples nacional - Guia complementar #87346 #88848
  IF ((NEW.bdordem IS NOT NULL) OR (NEW.bdordem > 0)) THEN
    EXIT;

  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDORDEM)+1),1) FROM VEF_EMP_TSIMPLESNACIONAL
        WHERE BDCODEMP = NEW.bdcodemp AND BDCODIMP = NEW.bdcodimp AND BDREFERENCIA = NEW.bdreferencia INTO vcodigo;
        NEW.BDORDEM = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDORDEM FROM VEF_EMP_TSIMPLESNACIONAL
       WHERE BDORDEM = NEW.BDORDEM AND BDCODEMP = NEW.bdcodemp AND BDCODIMP = NEW.bdcodimp AND BDREFERENCIA = NEW.bdreferencia INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDORDEM)+1),1) FROM VEF_EMP_TSIMPLESNACIONAL
            WHERE BDCODEMP = NEW.bdcodemp AND BDCODIMP = NEW.bdcodimp AND BDREFERENCIA = NEW.bdreferencia INTO vcodigo;
            NEW.BDORDEM = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_ESTADOS_TCONFDIMEFORM_BI0 FOR VEF_ESTADOS_TCONFDIMEFORM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumcampodime IS NULL) OR (NEW.bdnumcampodime = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdnumcampodime)+1),1) FROM vef_estados_tconfdimeform
        WHERE bdcodconfdimesc = NEW.bdcodconfdimesc
        AND bdcodqdime = NEW.bdcodqdime
        INTO vcodigo;
        NEW.bdnumcampodime = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdnumcampodime FROM vef_estados_tconfdimeform
       WHERE bdcodconfdimesc = NEW.bdcodconfdimesc
       AND bdcodqdime = NEW.bdcodqdime
       AND bdnumcampodime = NEW.bdnumcampodime
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumcampodime)+1),1) FROM vef_estados_tconfdimeform
           WHERE bdcodconfdimesc = NEW.bdcodconfdimesc
           AND bdcodqdime = NEW.bdcodqdime
           INTO vcodigo;
           NEW.bdnumcampodime = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_ESTADOS_TCONFDIMEFQ12_BI0 FOR VEF_ESTADOS_TCONFDIMEFQ12
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumcampodimeq12 IS NULL) OR (NEW.bdnumcampodimeq12 = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdnumcampodimeq12)+1),1) FROM vef_estados_tconfdimefq12
        WHERE bdcodconfdimesc = NEW.bdcodconfdimesc
        AND bdcodqdime = NEW.bdcodqdime
        INTO vcodigo;
        NEW.bdnumcampodimeq12 = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdnumcampodimeq12 FROM vef_estados_tconfdimefq12
       WHERE bdcodconfdimesc = NEW.bdcodconfdimesc
       AND bdcodqdime = NEW.bdcodqdime
       AND bdnumcampodimeq12 = NEW.bdnumcampodimeq12
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumcampodimeq12)+1),1) FROM vef_estados_tconfdimefq12
           WHERE bdcodconfdimesc = NEW.bdcodconfdimesc
           AND bdcodqdime = NEW.bdcodqdime
           INTO vcodigo;
           NEW.bdnumcampodimeq12 = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_ESTADOS_TCONFDIMEFQ46_BI0 FOR VEF_ESTADOS_TCONFDIMEFQ46
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumcampodimeq46 IS NULL) OR (NEW.bdnumcampodimeq46 = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdnumcampodimeq46)+1),1) FROM vef_estados_tconfdimefq46
        WHERE bdcodconfdimesc = NEW.bdcodconfdimesc
        AND bdcodqdime = NEW.bdcodqdime
        INTO vcodigo;
        NEW.bdnumcampodimeq46 = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdnumcampodimeq46 FROM vef_estados_tconfdimefq46
       WHERE bdcodconfdimesc = NEW.bdcodconfdimesc
       AND bdcodqdime = NEW.bdcodqdime
       AND bdnumcampodimeq46 = NEW.bdnumcampodimeq46
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumcampodimeq46)+1),1) FROM vef_estados_tconfdimefq46
           WHERE bdcodconfdimesc = NEW.bdcodconfdimesc
           AND bdcodqdime = NEW.bdcodqdime
           INTO vcodigo;
           NEW.bdnumcampodimeq46 = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_ESTADOS_TCONFDIMEQ_BU0 FOR VEF_ESTADOS_TCONFDIMEQ
ACTIVE BEFORE UPDATE POSITION 0 
AS
DECLARE VARIABLE vCodigo INTEGER;
DECLARE VARIABLE vaux INTEGER;
BEGIN
  /* Trigger text */

   /* ADICIONA AUTOMATICAMENTO O CODIGO PRINCIPAL DA CLASSIFICACAO... */
   SELECT FIRST 1 tpos.pos FROM pos('.',  NEW.BDCLASSIFICACAO) tpos INTO :vaux;

   IF (vaux > 1) THEN /* classificacao titulo */
      BEGIN
        SELECT FIRST 1 BDCODQDIME FROM VEF_ESTADOS_TCONFDIMEQ WHERE bdclassificacao = SUBSTRING(NEW.bdclassificacao FROM 1 FOR :vaux-1) INTO vcodigo;
        NEW.BDCODQDIMEPRINC = vcodigo;
      END
   ELSE
     BEGIN
        NEW.BDCODQDIMEPRINC = NEW.bdcodqdime;
     END

END
^

CREATE OR ALTER TRIGGER VEF_ESTADOS_TCONFGIAESFORM_BI0 FOR VEF_ESTADOS_TCONFGIAESFORM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumcampo IS NULL) OR (NEW.bdnumcampo = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdnumcampo)+1),1) FROM vef_estados_tconfgiaesform
        WHERE bdcodconf = NEW.bdcodconf
        AND bdcodquadro = NEW.bdcodquadro
        INTO vcodigo;
        NEW.bdnumcampo = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdnumcampo FROM vef_estados_tconfgiaesform
       WHERE bdcodconf = NEW.bdcodconf
       AND bdcodquadro = NEW.bdcodquadro
       AND bdnumcampo = NEW.bdnumcampo
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumcampo)+1),1) FROM vef_estados_tconfgiaesform
           WHERE bdcodconf = NEW.bdcodconf
           AND bdcodquadro = NEW.bdcodquadro
           INTO vcodigo;
           NEW.bdnumcampo = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_ESTADOS_TCONFGIAMGFORM_BI0 FOR VEF_ESTADOS_TCONFGIAMGFORM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumcampo IS NULL) OR (NEW.bdnumcampo = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdnumcampo)+1),1) FROM vef_estados_tconfgiamgform
        WHERE bdcodconf = NEW.bdcodconf
        AND bdcodquadro = NEW.bdcodquadro
        INTO vcodigo;
        NEW.bdnumcampo = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdnumcampo FROM vef_estados_tconfgiamgform
       WHERE bdcodconf = NEW.bdcodconf
       AND bdcodquadro = NEW.bdcodquadro
       AND bdnumcampo = NEW.bdnumcampo
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumcampo)+1),1) FROM vef_estados_tconfgiamgform
           WHERE bdcodconf = NEW.bdcodconf
           AND bdcodquadro = NEW.bdcodquadro
           INTO vcodigo;
           NEW.bdnumcampo = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_ESTADOS_TCONFGIAMGIX_BI0 FOR VEF_ESTADOS_TCONFGIAMGIX
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumcampo IS NULL) OR (NEW.bdnumcampo = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdnumcampo)+1),1) FROM VEF_ESTADOS_TCONFGIAMGIX
        WHERE bdcodconf = NEW.bdcodconf
        AND bdcodquadro = NEW.bdcodquadro
        INTO vcodigo;
        NEW.bdnumcampo = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdnumcampo FROM VEF_ESTADOS_TCONFGIAMGIX
       WHERE bdcodconf = NEW.bdcodconf
       AND bdcodquadro = NEW.bdcodquadro
       AND bdnumcampo = NEW.bdnumcampo
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumcampo)+1),1) FROM VEF_ESTADOS_TCONFGIAMGIX
           WHERE bdcodconf = NEW.bdcodconf
           AND bdcodquadro = NEW.bdcodquadro
           INTO vcodigo;
           NEW.bdnumcampo = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_ESTADOS_TCONFGIAMGQ_BU0 FOR VEF_ESTADOS_TCONFGIAMGQ
ACTIVE BEFORE UPDATE POSITION 0 
AS
DECLARE VARIABLE vCodigo INTEGER;
DECLARE VARIABLE vaux INTEGER;
BEGIN
   /* ADICIONA AUTOMATICAMENTO O CODIGO PRINCIPAL DA CLASSIFICACAO... */
   SELECT FIRST 1 tpos.BDRPOS FROM rpos('.',  NEW.BDCLASSIFICACAO) tpos INTO :vaux;

   IF (vaux > 1) THEN /* classificacao titulo */
      BEGIN
        SELECT FIRST 1 BDCODQUADRO FROM VEF_ESTADOS_TCONFGIAMGQ WHERE bdclassificacao = SUBSTRING(NEW.bdclassificacao FROM 1 FOR :vaux-1) INTO vcodigo;
        NEW.BDCODQPRINC = vcodigo;
      END
   ELSE
     BEGIN
        NEW.BDCODQPRINC = NEW.BDCODQUADRO;
     END
END
^

CREATE OR ALTER TRIGGER VEF_ESTADOS_TCONFGIASPFORM_BI0 FOR VEF_ESTADOS_TCONFGIASPFORM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdnumcampo IS NULL) OR (NEW.bdnumcampo = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdnumcampo)+1),1) FROM vef_estados_tconfgiaspform
        WHERE bdcodconf = NEW.bdcodconf
        AND bdcodquadro = NEW.bdcodquadro
        INTO vcodigo;
        NEW.bdnumcampo = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdnumcampo FROM vef_estados_tconfgiaspform
       WHERE bdcodconf = NEW.bdcodconf
       AND bdcodquadro = NEW.bdcodquadro
       AND bdnumcampo = NEW.bdnumcampo
       INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdnumcampo)+1),1) FROM vef_estados_tconfgiaspform
           WHERE bdcodconf = NEW.bdcodconf
           AND bdcodquadro = NEW.bdcodquadro
           INTO vcodigo;
           NEW.bdnumcampo = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_INT_TDACON_BI0 FOR VEF_INT_TDACON
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodigo IS NULL) OR (NEW.bdcodigo = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodigo)+1),1) FROM vef_int_tdacon INTO vcodigo;
        NEW.bdcodigo = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodigo FROM vef_int_tdacon WHERE bdcodigo = NEW.bdcodigo INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodigo)+1),1) FROM vef_int_tdacon INTO vcodigo;
            NEW.bdcodigo = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER vef_int_tdestda_bi0 FOR vef_int_tdestda
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodigo IS NULL) OR (NEW.bdcodigo = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodigo)+1),1) FROM vef_int_tdestda INTO vcodigo;
        NEW.bdcodigo = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodigo FROM vef_int_tdestda WHERE bdcodigo = NEW.bdcodigo INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodigo)+1),1) FROM vef_int_tdestda INTO vcodigo;
            NEW.bdcodigo = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_INT_TDCTF_BI0 FOR VEF_INT_TDCTF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodigo IS NULL) OR (NEW.bdcodigo = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodigo)+1),1) FROM vef_int_tdctf INTO vcodigo;
        NEW.bdcodigo = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodigo FROM vef_int_tdctf WHERE bdcodigo = NEW.bdcodigo INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodigo)+1),1) FROM vef_int_tdctf INTO vcodigo;
            NEW.bdcodigo = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_INT_TRETENCAO_BI0 FOR VEF_INT_TRETENCAO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodigo IS NULL) OR (NEW.bdcodigo = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodigo)+1),1) FROM vef_int_tretencao WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;
        NEW.bdcodigo = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodigo FROM vef_int_tretencao WHERE (bdcodigo = NEW.bdcodigo) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodigo)+1),1) FROM vef_int_tretencao WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;
            NEW.bdcodigo = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_INT_TDIFALIQ_BI0 FOR VEF_INT_TDIFALIQ
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodigo IS NULL) OR (NEW.bdcodigo = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodigo)+1),1) FROM VEF_INT_TDIFALIQ INTO vcodigo;
        NEW.bdcodigo = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodigo FROM VEF_INT_TDIFALIQ WHERE (bdcodigo = NEW.bdcodigo) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodigo)+1),1) FROM VEF_INT_TDIFALIQ INTO vcodigo;
            NEW.bdcodigo = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_INT_TSPED_PIS_COFINS_BI0 FOR VEF_INT_TSPED_PIS_COFINS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodigo IS NULL) OR (NEW.bdcodigo = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodigo)+1),1) FROM vef_int_tsped_pis_cofins INTO vcodigo;
        NEW.bdcodigo = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodigo FROM vef_int_tsped_pis_cofins WHERE bdcodigo = NEW.bdcodigo INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodigo)+1),1) FROM vef_int_tsped_pis_cofins INTO vcodigo;
            NEW.bdcodigo = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_TABELAS_TREDICMSFXSSN_BI0 FOR VEF_TABELAS_TREDICMSFAIXASSN
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdcodredfaixa IS NULL) OR (NEW.bdcodredfaixa = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodredfaixa) + 1), 1) FROM vef_tabelas_tredicmsfaixassn WHERE BDCODRED = NEW.BDCODRED  INTO vCodigo;
      NEW.bdcodredfaixa = vCodigo;

      IF ((NEW.BDCODRED IS NULL) OR (NEW.BDCODRED = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCODRED)), 1) FROM vef_tabelas_tredicmssn isssn INTO vCodigo;
          NEW.BDCODRED = vCodigo;
        END
    END
  ELSE
    BEGIN
       SELECT bdcodredfaixa FROM vef_tabelas_tredicmsfaixassn WHERE (BDCODRED = NEW.BDCODRED) AND (bdcodredfaixa = NEW.bdcodredfaixa) INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodredfaixa) + 1), 1) FROM vef_tabelas_tredicmsfaixassn  INTO vCodigo;
           NEW.bdcodredfaixa = vCodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_TABELAS_TREDICMSSN_BI0 FOR VEF_TABELAS_TREDICMSSN
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.BDCODRED IS NULL) OR (NEW.BDCODRED = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODRED) + 1), 1) FROM vef_tabelas_tredicmssn  INTO vCodigo;
      NEW.BDCODRED = vCodigo;
    END
  ELSE
    BEGIN
       SELECT BDCODRED FROM vef_tabelas_tredicmssn WHERE BDCODRED = NEW.BDCODRED INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCODRED) + 1), 1) FROM vef_tabelas_tredicmssn  INTO vCodigo;
           NEW.BDCODRED = vCodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_TABELAS_TREDISSFXSN_BI0 FOR VEF_TABELAS_TREDISSFAIXASN
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdcodredfaixa IS NULL) OR (NEW.bdcodredfaixa = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodredfaixa) + 1), 1) FROM vef_tabelas_tredissfaixasn WHERE BDCODRED = NEW.BDCODRED  INTO vCodigo;
      NEW.bdcodredfaixa = vCodigo;

      IF ((NEW.BDCODRED IS NULL) OR (NEW.BDCODRED = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCODRED)), 1) FROM vef_tabelas_tredisssn INTO vCodigo;
          NEW.BDCODRED = vCodigo;
        END
    END
  ELSE
    BEGIN
       SELECT bdcodredfaixa FROM vef_tabelas_tredissfaixasn WHERE (BDCODRED = NEW.BDCODRED) AND (bdcodredfaixa = NEW.bdcodredfaixa) INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodredfaixa) + 1), 1) FROM vef_tabelas_tredissfaixasn INTO vCodigo;
           NEW.bdcodredfaixa = vCodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_TABELAS_TREDISSSN_BI0 FOR VEF_TABELAS_TREDISSSN
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.BDCODRED IS NULL) OR (NEW.BDCODRED = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODRED) + 1), 1) FROM vef_tabelas_tredisssn  INTO vCodigo;
      NEW.BDCODRED = vCodigo;
    END
  ELSE
    BEGIN
       SELECT BDCODRED FROM vef_tabelas_tredisssn WHERE BDCODRED = NEW.BDCODRED INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCODRED) + 1), 1) FROM vef_tabelas_tredisssn  INTO vCodigo;
           NEW.BDCODRED = vCodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEF_TIPOOCO_GIA_BI0 FOR VEF_BASE_TTAB_TIPOOCO_GIA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodtipoocogia IS NULL) OR (NEW.bdcodtipoocogia = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodtipoocogia)+1),1) FROM VEF_BASE_TTAB_TIPOOCO_GIA INTO vcodigo;
       NEW.bdcodtipoocogia = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodtipoocogia FROM VEF_BASE_TTAB_TIPOOCO_GIA WHERE bdcodtipoocogia = NEW.bdcodtipoocogia INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodtipoocogia)+1),1) FROM VEF_BASE_TTAB_TIPOOCO_GIA INTO vcodigo;
            NEW.bdcodtipoocogia = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VEFLISTAOCO_GIASP_BI0 FOR VEF_BASE_TTAB_LISTAOCO_GIASP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodlisocogiasp IS NULL) OR (NEW.bdcodlisocogiasp = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcodlisocogiasp)+1),1) FROM VEF_BASE_TTAB_LISTAOCO_GIASP INTO vcodigo;
       NEW.bdcodlisocogiasp = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodlisocogiasp FROM VEF_BASE_TTAB_LISTAOCO_GIASP WHERE bdcodlisocogiasp = NEW.bdcodlisocogiasp INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodlisocogiasp)+1),1) FROM VEF_BASE_TTAB_LISTAOCO_GIASP INTO vcodigo;
            NEW.bdcodlisocogiasp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VINT_EMP_PROCESSOTROCA_BI0 FOR VINT_EMP_PROCESSOTROCA
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF (NEW.bdcodint = 0) THEN
     NEW.bdcodint = NULL;

  IF ((NEW.bdordem = 0) OR (NEW.bdordem IS NULL)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdordem),0) + 1 FROM vint_emp_processotroca WHERE bdcodemp = NEW.bdcodemp INTO NEW.bdordem;
     END
END
^

CREATE OR ALTER TRIGGER VLAL_BASE_TCONF_CONT_LAU_BI0 FOR VLAL_BASE_TCONF_CONTAB_LALUR
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodcontablalur IS NULL) OR (NEW.bdcodcontablalur = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodcontablalur)+1),1) FROM VLAL_BASE_TCONF_CONTAB_LALUR INTO vcodigo;
        NEW.bdcodcontablalur = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodcontablalur FROM VLAL_BASE_TCONF_CONTAB_LALUR WHERE bdcodcontablalur = NEW.bdcodcontablalur INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodcontablalur)+1),1) FROM VLAL_BASE_TCONF_CONTAB_LALUR INTO vcodigo;
            NEW.bdcodcontablalur = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VLAL_EMPRESAS_APURACAO_BI0 FOR VLAL_EMPRESAS_APURACAO
ACTIVE BEFORE INSERT POSITION 0 
AS
   DECLARE VARIABLE vCodigo INTEGER;
   DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
   vcodigo = 0;
   IF ((NEW.bdcodapu IS NULL) OR (NEW.bdcodapu = 0))  THEN
      BEGIN
         SELECT COALESCE((MAX(bdcodapu)+1),1)
         FROM vlal_empresas_apuracao
         WHERE bdcodemp = NEW.bdcodemp
         INTO vNova_Chave;
         NEW.bdcodapu = vNova_Chave;
      END
   ELSE
      BEGIN
         SELECT bdcodapu
         FROM vlal_empresas_apuracao
         WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodapu = NEW.bdcodapu)
         INTO vcodigo;
         IF (vcodigo > 0) THEN
            BEGIN
               SELECT COALESCE((MAX(bdcodapu)+1),1)
               FROM vlal_empresas_apuracao
               WHERE bdcodemp = NEW.bdcodemp
               INTO vNova_Chave;
               NEW.bdcodapu = vNova_Chave;
            END
      END
END
^

CREATE OR ALTER TRIGGER VLAL_EMPRESAS_IMP_CONTABLAL_BI0 FOR VLAL_EMPRESAS_IMP_CONTABLALUR
ACTIVE BEFORE INSERT POSITION 0 
AS
   DECLARE VARIABLE vCodigo INTEGER;
   DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
   vcodigo = 0;
   IF ((NEW.bdcodimp IS NULL) OR (NEW.bdcodimp = 0))  THEN
      BEGIN
         SELECT COALESCE((MAX(bdcodimp)+1),1)
         FROM VLAL_EMPRESAS_IMP_CONTABLALUR
         INTO vNova_Chave;
         NEW.bdcodimp = vNova_Chave;
      END
   ELSE
      BEGIN
         SELECT bdcodimp
         FROM VLAL_EMPRESAS_IMP_CONTABLALUR
         WHERE (bdcodimp = NEW.bdcodimp)
         INTO vcodigo;
         IF (vcodigo > 0) THEN
            BEGIN
               SELECT COALESCE((MAX(bdcodimp)+1),1)
               FROM VLAL_EMPRESAS_IMP_CONTABLALUR
               INTO vNova_Chave;
               NEW.bdcodimp = vNova_Chave;
            END
      END
END
^

CREATE OR ALTER TRIGGER VLAL_EMPRESAS_TLLA_ANUAL_BI0 FOR VLAL_EMPRESAS_TLLA_ANUAL
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  IF (NEW.bdcodhist = 0) THEN
     NEW.bdcodhist = NULL;
END
^

CREATE OR ALTER TRIGGER VRH_BASE_BAIXA_CALC_AUTO_BI0 FOR VRH_BASE_BAIXA_CALC_AUTO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodbaixa IS NULL) OR (NEW.bdcodbaixa = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodbaixa),0)+1 FROM VRH_BASE_BAIXA_CALC_AUTO INTO :vCodigo;
       NEW.bdcodbaixa = vCodigo;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_CBO_TSIN_BI0 FOR VRH_BASE_CBO_TSIN
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vnovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCBOTSIN IS NULL) OR (NEW.BDCODCBOTSIN = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODCBOTSIN) + 1, 1)
       FROM vrh_base_cbo_tsin
       WHERE BDCODCBO = NEW.BDCODCBO
       INTO :vnovocod;

       NEW.BDCODCBOTSIN = :vnovocod;
     END

  NEW.bddesccboupper = REPLACE(UPPER(NEW.bddesccbotsin), ' ', '');
END
^

CREATE OR ALTER TRIGGER VRH_BASE_CBO_TSIN_BU0 FOR VRH_BASE_CBO_TSIN
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  NEW.bddesccboupper = REPLACE(UPPER(NEW.bddesccbotsin), ' ', '');
END
^

CREATE OR ALTER TRIGGER VRH_BASE_CBO_TSIN_SCI_BI0 FOR VRH_BASE_CBO_TSIN_SCI
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vnovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCBOTSIN IS NULL) OR (NEW.BDCODCBOTSIN = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODCBOTSIN) + 1, 1)
       FROM vrh_base_cbo_tsin_sci
       WHERE BDCODCBO = NEW.BDCODCBO
       INTO :vnovocod;

       NEW.BDCODCBOTSIN = :vnovocod;
     END

  NEW.bddesccboupper = REPLACE(UPPER(NEW.bddesccbotsin), ' ', '');
END
^

CREATE OR ALTER TRIGGER VRH_BASE_CBO_TSIN_SCI_BU0 FOR VRH_BASE_CBO_TSIN_SCI
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  NEW.bddesccboupper = REPLACE(UPPER(NEW.bddesccbotsin), ' ', '');
END
^

CREATE OR ALTER TRIGGER VRH_BASE_CONVENIO_OPER_BI0 FOR VRH_BASE_CONVENIO_OPERADORAS
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.BDCODCONVENIO IS NULL) OR (NEW.BDCODCONVENIO = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODCONVENIO)+1,1) FROM vrh_base_convenio_operadoras
       WHERE NEW.bdcodoperadora = bdcodoperadora AND NEW.bdcodplaconvsau = bdcodplaconvsau
       INTO NEW.bdcodconvenio;
     END


  if (upper(coalesce(new.bdmensformula, 'FALSE')) = 'FALSE') then
     begin
       new.bdcodvertitmens = null;
       new.bdcodvertitcop  = null;
       new.bdcodverdepmens = null;
       new.bdcodverdepcop  = null;
END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_CONVENIO_OPER_BU0 FOR VRH_BASE_CONVENIO_OPERADORAS
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  if (upper(coalesce(new.bdmensformula, 'FALSE')) = 'FALSE') then
     begin
       new.bdcodvertitmens = null;
       new.bdcodvertitcop  = null;
       new.bdcodverdepmens = null;
       new.bdcodverdepcop  = null;
     end
end
^

CREATE OR ALTER TRIGGER VRH_BASE_FAIXAS_CONVENIOS_BI0 FOR VRH_BASE_FAIXAS_CONVENIOS
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdordem)+1,1) FROM VRH_BASE_FAIXAS_CONVENIOS
       WHERE NEW.bdcodoperadora = bdcodoperadora AND NEW.bdcodplaconvsau = bdcodplaconvsau AND NEW.bdcodconvenio = bdcodconvenio AND NEW.bdref = bdref
       INTO NEW.bdordem;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_ITEMS_MEDIASSIND_BI0 FOR VRH_BASE_ITEMS_MEDIASSIND
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODIMS IS NULL) OR (NEW.BDCODIMS = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODIMS) + 1, 1)
       FROM vrh_base_items_mediassind
       WHERE BDCODPMS = NEW.BDCODPMS
       INTO :vNovoCod;

       NEW.BDCODIMS = :vNovoCod;
     END

  IF (NEW.BDRANGEIMS > NEW.BDMESESIMS) THEN
     NEW.BDRANGEIMS = NEW.BDMESESIMS;

  IF (NEW.bdtiporangeims IS NULL OR (NEW.bdtiporangeims = 0)) THEN
     NEW.bdrangeims = 0;

END
^

CREATE OR ALTER TRIGGER VRH_BASE_ITEMS_MEDIASSIND_BU0 FOR VRH_BASE_ITEMS_MEDIASSIND
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  IF (NEW.BDRANGEIMS > NEW.BDMESESIMS) THEN
     NEW.BDRANGEIMS = NEW.BDMESESIMS;

  IF (NEW.bdtiporangeims IS NULL OR (NEW.bdtiporangeims = 0)) THEN
     NEW.bdrangeims = 0;
END
^

CREATE OR ALTER TRIGGER VRH_BASE_MTE_TCONFRESC_BI0 FOR VRH_BASE_MTE_TCONFRESC
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdchaveconf IS NULL) OR (NEW.bdchaveconf = 0))  THEN
     BEGIN
       SELECT COALESCE(MAX(bdchaveconf),0)+1 FROM vrh_base_mte_tconfresc INTO NEW.bdchaveconf;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_MTE_TVERBASCONF_BI0 FOR VRH_BASE_MTE_TVERBASCONF
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdchaveconf IS NULL) OR (NEW.bdchaveconf = 0)) THEN
     BEGIN
       SELECT MAX(bdchAVECONF) FROM vrh_base_mte_tconfresc INTO NEW.bdchaveconf;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_PLANO_MEDIAS_SIND_BI0 FOR VRH_BASE_PLANO_MEDIAS_SIND
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODPMS IS NULL) OR (NEW.BDCODPMS = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODPMS) + 1, 1)
       FROM vrh_base_plano_medias_sind
       INTO :vNovoCod;

       NEW.BDCODPMS = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TAGENTE_ESTAGIO_BI0 FOR VRH_BASE_TAGENTE_ESTAGIO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCod INTEGER;

BEGIN
  IF ((NEW.bdcodagenteest IS NULL) OR (NEW.bdcodagenteest = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODAGENTEEST) + 1, 1) FROM VRH_BASE_TAGENTE_ESTAGIO INTO :vCod;
       NEW.bdcodagenteest = :vcod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TCALCITENS_BI0 FOR VRH_BASE_TCALCITENS
ACTIVE BEFORE INSERT POSITION 0 
AS
DECLARE VARIABLE novocod INTEGER;
BEGIN
  IF ((NEW.bdCODCIT IS NULL) OR (NEW.BDCODCIT = 0))  THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODCIT) + 1, 1)
       FROM VRH_BASE_TCALCITENS
       WHERE BDCODCTP = NEW.BDCODCTP
       INTO
         novocod;
       NEW.BDCODCIT = novocod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TCALCVESP_BI0 FOR VRH_BASE_TCALCVESP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCVE IS NULL) OR (NEW.BDCODCVE = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODCVE) + 1, 1)
       FROM VRH_BASE_TCALCVESP
       INTO :vNovoCod;

       NEW.BDCODCVE = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TCBO_BI0 FOR VRH_BASE_TCBO
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE novocod INTEGER;
BEGIN
  IF ((NEW.bdCODCBO IS NULL) OR (NEW.BDCODCBO = 0))  THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodcbo)+1,1) FROM vrh_base_tcbo INTO novocod;
       NEW.bdcodcbo = novocod;
     END

  NEW.bddesccboupper = REPLACE(UPPER(NEW.bddesccbo), ' ', '');
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TCBO_BU0 FOR VRH_BASE_TCBO
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  NEW.bddesccboupper = REPLACE(UPPER(NEW.bddesccbo), ' ', '');
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TCBO_SCI_BI0 FOR VRH_BASE_TCBO_SCI
ACTIVE BEFORE INSERT POSITION 0 
AS
DECLARE VARIABLE novocod INTEGER;

BEGIN
  IF ((NEW.bdCODCBO IS NULL) OR (NEW.BDCODCBO = 0))  THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodcbo)+1,1) FROM vrh_base_tcbo INTO novocod;
       NEW.bdcodcbo = novocod;
     END

  NEW.bddesccboupper = REPLACE(UPPER(NEW.bddesccbo), ' ', '');
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TCBO_SCI_BU0 FOR VRH_BASE_TCBO_SCI
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  NEW.bddesccboupper = REPLACE(UPPER(NEW.bddesccbo), ' ', '');
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TCLASSE_BI0 FOR VRH_BASE_TCLASSE
ACTIVE BEFORE INSERT POSITION 0 
AS
DECLARE VARIABLE novocod INTEGER;
BEGIN
  IF ((NEW.bdCODCLA IS NULL) OR (NEW.BDCODCLA = 0))  THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodcla)+1,1) FROM vrh_base_tclasse INTO novocod;
       NEW.bdcodcla = novocod;
     END

END
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_HE_BI0 FOR VRH_BASE_TCONF_FICHA_HE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vclass VARCHAR(20);

BEGIN
  SELECT BDCLAVER FROM VRH_BASE_TVERBAS WHERE BDCODVER = NEW.BDCODVER INTO :vclass;
  NEW.BDCLAVER = :vclass;
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_HE_BU0 FOR VRH_BASE_TCONF_FICHA_HE
ACTIVE BEFORE UPDATE POSITION 0 
AS
  DECLARE VARIABLE vclass VARCHAR(20);

BEGIN
  SELECT BDCLAVER FROM VRH_BASE_TVERBAS WHERE BDCODVER = NEW.BDCODVER INTO :vclass;
  NEW.BDCLAVER = :vclass;
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_HN_BI0 FOR VRH_BASE_TCONF_FICHA_HN
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vclass VARCHAR(20);

BEGIN
  SELECT BDCLAVER FROM VRH_BASE_TVERBAS WHERE BDCODVER = NEW.BDCODVER INTO :vclass;
  NEW.BDCLAVER = :vclass;
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_HN_BU0 FOR VRH_BASE_TCONF_FICHA_HN
ACTIVE BEFORE UPDATE POSITION 0 
AS
  DECLARE VARIABLE vclass VARCHAR(20);

BEGIN
  SELECT BDCLAVER FROM VRH_BASE_TVERBAS WHERE BDCODVER = NEW.BDCODVER INTO :vclass;
  NEW.BDCLAVER = :vclass;
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_RV_BI0 FOR VRH_BASE_TCONF_FICHA_RV
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vclass VARCHAR(20);

BEGIN
  SELECT BDCLAVER FROM VRH_BASE_TVERBAS WHERE BDCODVER = NEW.BDCODVER INTO :vclass;
  NEW.BDCLAVER = :vclass;
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_RV_BU0 FOR VRH_BASE_TCONF_FICHA_RV
ACTIVE BEFORE UPDATE POSITION 0 
AS
  DECLARE VARIABLE vclass VARCHAR(20);

BEGIN
  SELECT BDCLAVER FROM VRH_BASE_TVERBAS WHERE BDCODVER = NEW.BDCODVER INTO :vclass;
  NEW.BDCLAVER = :vclass;
END
^

CREATE OR ALTER trigger vrh_base_tconf_ficha_out_bi0 for vrh_base_tconf_ficha_out
active before insert position 0
AS
  DECLARE VARIABLE vclass VARCHAR(20);

BEGIN
  SELECT BDCLAVER FROM VRH_BASE_TVERBAS WHERE BDCODVER = NEW.BDCODVER INTO :vclass;
  NEW.BDCLAVER = :vclass;
END
^

CREATE OR ALTER trigger vrh_base_tconf_ficha_out_bu0 for vrh_base_tconf_ficha_out
active before update position 0
AS
  DECLARE VARIABLE vclass VARCHAR(20);

BEGIN
  SELECT BDCLAVER FROM VRH_BASE_TVERBAS WHERE BDCODVER = NEW.BDCODVER INTO :vclass;
  NEW.BDCLAVER = :vclass;
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONVSAUDE_BI0 FOR VRH_BASE_TCONVSAUDE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.BDCODCONVENIO = 0) OR ((NEW.BDCODCONVENIO IS NULL)) ) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODCONVENIO) + 1), 1) FROM vrh_base_tconvsaude  INTO vCodigo;
      NEW.BDCODCONVENIO = vCodigo;
    END
  ELSE
    BEGIN
       SELECT BDCODCONVENIO FROM vrh_base_tconvsaude WHERE BDCODCONVENIO = NEW.BDCODCONVENIO INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCODCONVENIO) + 1), 1) FROM vrh_base_tconvsaude  INTO vCodigo;
           NEW.BDCODCONVENIO = vCodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TDOENCAS_BI0 FOR VRH_BASE_TDOENCAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.bdcoddoe IS NULL) OR (NEW.bdcoddoe = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcoddoe) + 1, 1) FROM vrh_base_tdoencas INTO :vNovoCod;
       NEW.bdcoddoe = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TEMPVINC_BIO FOR VRH_BASE_TEMPVINC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
 -- DECLARE VARIABLE vcodemp INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo IS NULL OR (vcodigo = 0)) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END

 /*vcodemp = NULL;
  SELECT FIRST 1 BDCODEMP FROM VRHF_BASE_TVERBASEMP WHERE BDCODEMP = NEW.bdcodemp INTO :vcodemp;

  IF (vcodemp IS NULL) THEN
     BEGIN
       EXECUTE PROCEDURE SP_VRH_VERIFICAVERBASEMP_PADRAO(NEW.bdcodemp);
     END   */
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TFPAS_BI0 FOR VRH_BASE_TFPAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodNovo INTEGER;

BEGIN
  IF ((NEW.BDCODFPAS IS NULL) OR (NEW.BDCODFPAS = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODFPAS) + 1, 1)
       FROM vrh_base_tfpas
       INTO :vCodNovo;

       NEW.BDCODFPAS = :vCodNovo;

     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TFPAS_TERCEIROS_BI0 FOR VRH_BASE_TFPAS_TERCEIROS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODFPASTERC IS NULL) OR (NEW.BDCODFPASTERC = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(X.BDCODFPASTERC) + 1, 1)
       FROM VRH_BASE_TFPAS_TERCEIROS X
       INTO :vNovoCod;

       NEW.BDCODFPASTERC = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TFUNCOES_BI0 FOR VRH_BASE_TFUNCOES
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODPLAFUC IS NULL) OR (NEW.BDCODPLAFUC = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODPLAFUC) + 1, 1)
       FROM vrh_base_tfuncoes
       INTO :vNovoCod;

       NEW.BDCODPLAFUC = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_THOMOLOGANET_BI0 FOR VRH_BASE_THOMOLOGANET
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;
BEGIN
  IF (NEW.BDCODHNET IS NULL OR (NEW.BDCODHNET = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(X.BDCODHNET), 0) + 1 FROM VRH_BASE_THOMOLOGANET X INTO vNovoCod;

       NEW.BDCODHNET = vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TINST_ESTAGIO_BI0 FOR VRH_BASE_TINST_ESTAGIO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCod INTEGER;

BEGIN
  IF ((NEW.bdcodinstest IS NULL) OR (NEW.bdcodinstest = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODINSTEST) + 1, 1) FROM VRH_BASE_TINST_ESTAGIO INTO :vCod;
       NEW.bdcodinstest = :vcod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TIPO_MEDIASSIND_BI0 FOR VRH_BASE_TIPO_MEDIASSIND
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODTMS IS NULL) OR (NEW.BDCODTMS = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODTMS) + 1, 1)
       FROM vrh_base_tipo_mediassind
       INTO :vNovoCod;

       NEW.BDCODTMS = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TMEDICOS_BI0 FOR VRH_BASE_TMEDICOS
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodmed IS NULL) OR (NEW.bdcodmed = 0)) THEN
     SELECT COALESCE(MAX(bdcodmed),0)+1 FROM vrh_base_tmedicos INTO NEW.bdcodmed;

  IF (NEW.bdcrm IS NOT NULL AND NEW.bdcrm <> 0 AND NEW.bdnummed IS NULL) THEN
     NEW.bdnummed = SUBSTRING(NEW.bdcrm FROM 1 FOR 14);
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TMEDICOS_BU0 FOR VRH_BASE_TMEDICOS
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  IF (NEW.bdcrm IS NOT NULL AND NEW.bdcrm <> 0 AND NEW.bdnummed IS NULL) THEN
     NEW.bdnummed = SUBSTRING(NEW.bdcrm FROM 1 FOR 14);
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TMENSAGENS_BI0 FOR VRH_BASE_TMENSAGENS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODMEN IS NULL) OR (NEW.BDCODMEN = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODMEN) + 1, 1)
       FROM vrh_base_tmensagens
       INTO :vNovoCod;

       NEW.BDCODMEN = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TMOTAUMSAL_BI0 FOR VRH_BASE_TMOTAUMSAL
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODMAS IS NULL) OR (NEW.BDCODMAS = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODMAS) + 1, 1)
       FROM vrh_base_tmotaumsal
       INTO :vNovoCod;

       NEW.BDCODMAS = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TMOTCAGED_BI0 FOR VRH_BASE_TMOTCAGED
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODMCAG IS NULL) OR (NEW.BDCODMCAG = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODMCAG) + 1, 1)
       FROM vrh_base_tmotcaged
       INTO :vNovoCod;

       NEW.BDCODMCAG = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TMOTESOCIAL_RESC_BI0 FOR VRH_BASE_TMOTESOCIAL_RESC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF ((NEW.bdcodmotesresc IS NULL) OR (NEW.bdcodmotesresc = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODMOTESRESC), 0) + 1 FROM VRH_BASE_TMOTESOCIAL_RESC INTO :vcod;
       NEW.bdcodmotesresc = :vcod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TMOTESOCIAL_SIT_BI0 FOR VRH_BASE_TMOTESOCIAL_SIT
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF ((NEW.bdcodmotessit IS NULL) OR (NEW.bdcodmotessit = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODMOTESSIT), 0) + 1 FROM VRH_BASE_TMOTESOCIAL_SIT INTO :vcod;
       NEW.bdcodmotessit = :vcod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TMOTFGTS_BI0 FOR VRH_BASE_TMOTFGTS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODMFG IS NULL) OR (NEW.BDCODMFG = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODMFG) + 1, 1)
       FROM vrh_base_tmotfgts
       INTO :vNovoCod;

       NEW.BDCODMFG = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TMOTRAIS_BI0 FOR VRH_BASE_TMOTRAIS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODMRAIS IS NULL) OR (NEW.BDCODMRAIS = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODMRAIS) + 1, 1)
       FROM vrh_base_tmotrais
       INTO :vNovoCod;

       NEW.BDCODMRAIS = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TMOTRAIS_SIT_BI0 FOR VRH_BASE_TMOTRAIS_SIT
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODMRAISSIT IS NULL) OR (NEW.BDCODMRAISSIT = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODMRAISSIT) + 1, 1)
       FROM vrh_base_tmotrais_sit
       INTO :vNovoCod;

       NEW.BDCODMRAISSIT = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TMS_CLASS_BI0 FOR VRH_BASE_TMS_CLASS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;

BEGIN
  IF ((NEW.bdcodtmsc IS NULL) OR (NEW.bdcodtmsc = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODTMSC) + 1, 1) FROM VRH_BASE_TMS_CLASS WHERE BDCODTMS = NEW.BDCODTMS INTO :vcod;
       NEW.BDCODTMSC = vcod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TNATUREZA_VERBAS_BI0 FOR VRH_BASE_TNATUREZA_VERBAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.bdcodigo IS NULL) OR (NEW.bdcodigo = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodigo) + 1, 1)
       FROM vrh_base_tnatureza_verbas
       INTO :vNovoCod;

       NEW.bdcodigo = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TNOMESELTERC_BI0 FOR VRH_BASE_TNOMESELTERC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.bdcodigosel IS NULL) OR (NEW.bdcodigosel = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodigosel) + 1, 1)
       FROM vrh_base_tnomeselterc
       INTO :vNovoCod;

       NEW.bdcodigosel = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TPLACONFVERPTITEM_BI0 FOR VRH_BASE_TPLACONFVERBAPONTOITEM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCod INTEGER;
BEGIN
  IF (NEW.bdordem IS NULL OR (NEW.bdordem = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdordem), 0) + 1 FROM VRH_BASE_TPLACONFVERBAPONTOITEM WHERE BDCODPLACONF = NEW.bdcodplaconf INTO :vCod;
       NEW.bdordem = :vCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TPLANO_CONVSAUDE_BI0 FOR VRH_BASE_TPLANO_CONVSAUDE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNCod INTEGER;
BEGIN
  IF (NEW.bdcodplaconvsau IS NULL OR (NEW.bdcodplaconvsau = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodplaconvsau) + 1, 1) FROM VRH_BASE_TPLANO_CONVSAUDE INTO :vNCod;
       NEW.bdcodplaconvsau = vNCod;
     END
END
^

/*Sol. 15795 - Aterado para que, se o resultado de MAX(BDCODPLPL) for maior que 9999, gere outro código vago.
Caso todo o range de 1..9999 esteja ocupado, é atribuído null para  BDCODPLPL - Bruno L. R. */
CREATE OR ALTER TRIGGER VRH_BASE_TPLANO_LPL_BI0 FOR VRH_BASE_TPLANO_LPL
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNumero INTEGER;
  DECLARE VARIABLE vCount INTEGER;
BEGIN
  IF ((NEW.bdcodplpl IS NULL) OR (NEW.bdcodplpl = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODPLPL), 0) + 1 FROM VRH_BASE_TPLANO_LPL INTO :vCodigo;

       IF (vCodigo > 9999) THEN
          BEGIN
            vNumero = 1;
            vCount = 1;

            WHILE (vCount <> 0) DO
              BEGIN
                SELECT COUNT(*) FROM VRH_BASE_TPLANO_LPL WHERE BDCODPLPl = :vNumero AND BDCODPLPL <= 9999 INTO :vCount;
                vCodigo = vNumero;
                vNumero = vNumero + 1;
                IF (vCodigo > 9999) THEN
                   vCodigo = NULL;
              END
          END
       NEW.bdcodplpl = :vCodigo;
     END
END
^                 

CREATE OR ALTER TRIGGER VRH_BASE_TPLANO_QUADRO_BI0 FOR VRH_BASE_TPLANO_QUADRO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDCODPQUA IS NULL) OR (NEW.BDCODPQUA = 0)) THEN
     BEGIN
        SELECT COALESCE(MAX(BDCODPQUA) + 1,1) FROM VRH_BASE_TPLANO_QUADRO INTO vcodigo;
        NEW.BDCODPQUA = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODPQUA FROM VRH_BASE_TPLANO_QUADRO WHERE BDCODPQUA = NEW.BDCODPQUA INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE(MAX(BDCODPQUA),1) FROM VRH_BASE_TPLANO_QUADRO INTO vcodigo;
            NEW.BDCODPQUA = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TPLANOBLUESOFT_BI0 FOR VRH_BASE_TPLANOBLUESOFT
ACTIVE BEFORE INSERT POSITION 0 
AS
DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF ((NEW.bdcodplabs IS NULL) OR (NEW.bdcodplabs = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODPLABS) + 1, 1) FROM VRH_BASE_TPLANOBLUESOFT INTO :vcod;
       NEW.bdcodplabs = :vcod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TPREPRESC_BI0 FOR VRH_BASE_TPREPRESC
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODPRES IS NULL) OR (NEW.BDCODPRES = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODPRES) + 1, 1)
       FROM vrh_base_tprepresc
       INTO :vNovoCod;

       NEW.BDCODPRES = :vNovoCod;
     END

  IF (NEW.BDTIPOMOV IS NULL) THEN
     NEW.BDTIPOMOV = 0;

  IF (COALESCE(NEW.bdpercmultafgts, 0) > 0) THEN
     NEW.bdmultapres = 'FALSE';
  ELSE
     NEW.bdmultapres = 'TRUE';

  IF (COALESCE(NEW.bdpercmultafgtscs, 0) > 0) THEN
     NEW.bdmulta10pres = 'TRUE';
  ELSE
     NEW.bdmulta10pres = 'FALSE';

END
^

CREATE OR ALTER TRIGGER VRH_BASE_TPREPRESC_BU0 FOR VRH_BASE_TPREPRESC
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  IF (COALESCE(NEW.bdpercmultafgts, 0) > 0) THEN
     NEW.bdmultapres = 'FALSE';
  ELSE
     NEW.bdmultapres = 'TRUE';

  IF (COALESCE(NEW.bdpercmultafgtscs, 0) > 0) THEN
     NEW.bdmulta10pres = 'TRUE';
  ELSE
     NEW.bdmulta10pres = 'FALSE';
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TPREPSIT_BI0 FOR VRH_BASE_TPREPSIT
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODSIT IS NULL) OR (NEW.BDCODSIT = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODSIT) + 1, 1)
       FROM vrh_base_tprepsit
       INTO :vNovoCod;

       NEW.BDCODSIT = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TQH_BI0 FOR VRH_BASE_TQH
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODQH IS NULL) OR (NEW.BDCODQH = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODQH) + 1, 1)
       FROM vrh_base_tqh WHERE BDCODPQUA = NEW.BDCODPQUA
       INTO :vNovoCod;

       NEW.BDCODQH = :vNovoCod;
     END

  if (NEW.bddescesocial is null) then
     NEW.bddescesocial = NEW.BDDESCQH;
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TQH_DIAS_BI0 FOR VRH_BASE_TQH_DIAS
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  NEW.bddsr = NULL;
  IF (NEW.BDTIPODSR = 1) THEN
     NEW.bddsr = 'TRUE';
  ELSE
  IF (NEW.BDTIPODSR = 2) THEN
     NEW.bddsr = 'FALSE';
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TQH_DIAS_BU0 FOR VRH_BASE_TQH_DIAS
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  /* Trigger text */
  NEW.bddsr = NULL;
  IF (NEW.BDTIPODSR = 1) THEN
     NEW.bddsr = 'TRUE';
  ELSE
  IF (NEW.BDTIPODSR = 2) THEN
     NEW.bddsr = 'FALSE';
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TQH_HORARIO_BI0 FOR VRH_BASE_TQH_HORARIO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODQHH IS NULL) OR (NEW.BDCODQHH = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODQHH) + 1, 1)
       FROM vrh_base_tqh_horario
       INTO :vNovoCod;

       NEW.bdcodqhh = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TQH_HORAS_BI0 FOR VRH_BASE_TQH_HORAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodqhhs IS NULL) OR (NEW.bdcodqhhs = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodqhhs)+1), 1) FROM VRH_BASE_TQH_HORAS WHERE bdCODQHH = NEW.bdCODQHH INTO vNova_Chave;
      NEW.bdcodqhhs = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdcodqhhs FROM VRH_BASE_TQH_HORAS WHERE (bdcodqhhs = NEW.bdcodqhhs) AND (bdCODQHH = NEW.bdCODQHH) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodqhhs)+1), 1) FROM VRH_BASE_TQH_HORAS WHERE bdCODQHH = NEW.bdCODQHH INTO vNova_Chave;
           NEW.bdcodqhhs = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TROCUPACIONAL_BI0 FOR VRH_BASE_TROCUPACIONAL
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodrocup IS NULL) OR (NEW.bdcodrocup = 0)) THEN
     SELECT COALESCE(MAX(bdcodrocup),0)+1 bdcodrocup FROM vrh_base_trocupacional INTO NEW.bdcodrocup;
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TRUBRICAS_BI0 FOR VRH_BASE_TRUBRICAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  vCodigo = 0;

  IF ((NEW.bdchave = 0) OR ((NEW.bdchave IS NULL)) ) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave) + 1), 1) FROM VRH_BASE_TRUBRICAS  INTO vCodigo;
      NEW.bdchave = vCodigo;
    END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TRUBRICAS_VERBA_BI0 FOR VRH_BASE_TRUBRICAS_VERBA
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     SELECT COALESCE(MAX(bdchave),0)+1 FROM vrh_base_trubricas_verba WHERE BDCHAVERUB = NEW.BDCHAVERUB INTO NEW.bdchave;
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSALHORESP_BI0 FOR VRH_BASE_TSALHORESP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODSHE IS NULL) OR (NEW.BDCODSHE = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODSHE), 0) + 1
       FROM VRH_BASE_TSALHORESP
       WHERE BDCODEMP = NEW.BDCODEMP
       INTO :vNovoCod;

       NEW.BDCODSHE = :vNovoCod;
     END

  IF (NEW.BDDESCVERBASHE IS NULL) THEN
     NEW.BDDESCVERBASHE = 'FALSE';
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSELCOL_BI0 FOR VRH_BASE_TSELCOL
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.bdcodigosel IS NULL) OR (NEW.bdcodigosel = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodigosel), 1)
       FROM vrh_base_tselecoescol
       INTO :vNovoCod;

       NEW.bdcodigosel = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSELECOESCOL_BI0 FOR VRH_BASE_TSELECOESCOL
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.bdcodigosel IS NULL) OR (NEW.bdcodigosel = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodigosel) + 1, 1)
       FROM vrh_base_tselecoescol
       INTO :vNovoCod;

       NEW.bdcodigosel = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSELTERC_BI0 FOR VRH_BASE_TSELTERC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.bdcodigosel IS NULL) OR (NEW.bdcodigosel = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodigosel), 1)
       FROM vrh_base_tnomeselterc
       INTO :vNovoCod;

       NEW.bdcodigosel = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSERVTERC_BU0 FOR VRH_BASE_TSERVTERC
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  /* Trigger text */
  NEW.bdrefserv = (SELECT CAST(bdaaaamm AS INTEGER) FROM aaaamm(NEW.bddataserv));
  NEW.bdrefpagserv = (SELECT CAST(bdaaaamm AS INTEGER) FROM aaaamm(NEW.bddatapagserv));

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdrefserv, '1', 'BDPERFOLHAAUTONOMO'); -- 1 - Calculado
END
^

-- 125979 - Raphael Teodoro - 15/01/2020
CREATE OR ALTER TRIGGER VRH_BASE_TSERVTERC_AD0 FOR VRH_BASE_TSERVTERC
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE sp_vrh_painel_update(OLD.bdcodemp, OLD.bdrefserv, '2', 'BDPERFOLHAAUTONOMO'); -- 2 - Excluido
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSIND_AVPREV_BI0 FOR VRH_BASE_TSIND_AVPREV
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDITEMSAV IS NULL) OR (NEW.BDITEMSAV = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDITEMSAV) + 1, 1)
       FROM vrh_base_tsind_avprev
       WHERE BDCODSINTRAB = NEW.BDCODSINTRAB
       INTO :vNovoCod;

       NEW.BDITEMSAV = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSIND_FERIAS_BI0 FOR VRH_BASE_TSIND_FERIAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCod INTEGER;

BEGIN
  IF (NEW.BDITEMSIND IS NULL OR (NEW.BDITEMSIND = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDITEMSIND), 0) + 1 FROM VRH_BASE_TSIND_FERIAS WHERE BDCODSINTRAB = NEW.BDCODSINTRAB INTO :vCod;
       NEW.BDITEMSIND = :vCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSINDTRAB_AI0 FOR VRH_BASE_TSINDTRAB
ACTIVE AFTER INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodVer INTEGER;

BEGIN
  SELECT FIRST 1 BDCODVER FROM VRH_BASE_TVERBAS WHERE STRLEN(BDCLAVER) > 9 AND SUBSTRING(BDCLAVER FROM 1 FOR 9) = '0.004.0.1' INTO :vcodver;

  IF (:vcodver IS NOT NULL AND :vcodver <> 0) THEN
     BEGIN
       INSERT INTO VRHF_BASE_TVNSIND (BDCODVER,BDCODSINTRAB,BDANOINIVNSIND,BDMESINIVNSIND,BDDIAINIVNSIND,BDDESCCONDSIND)
         VALUES (:vcodver,  NEW.bdcodsintrab, 0, 0, 0, 'NOT CONTSIND()');
     END

END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSINDTRAB_BI0 FOR VRH_BASE_TSINDTRAB
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodNovo INTEGER;

BEGIN
  IF ((NEW.BDCODSINTRAB IS NULL) OR (NEW.BDCODSINTRAB = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODSINTRAB) + 1, 1)
       FROM vrh_base_tsindtrab
       INTO :vCodNovo;

       NEW.BDCODSINTRAB = :vCodNovo;

     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSINDTRAB_DOC_BI0 FOR VRH_BASE_TSINDTRAB_DOC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCod INTEGER;
BEGIN
  IF (NEW.bdcoddocsind IS NULL OR (NEW.bdcoddocsind = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODDOCSIND) + 1, 1) FROM VRH_BASE_TSINDTRAB_DOC WHERE BDCODSINTRAB = NEW.BDCODSINTRAB INTO :vCod;
       NEW.bdcoddocsind = :vcod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSINDTRAB_INDICES_BI0 FOR VRH_BASE_TSINDTRAB_INDICES
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF ((NEW.bdcodlanind IS NULL) OR (NEW.bdcodlanind = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODLANIND) + 1, 1) FROM VRH_BASE_TSINDTRAB_INDICES WHERE BDCODSINTRAB = NEW.BDCODSINTRAB INTO :vcod;
       NEW.bdcodlanind = :vcod;
     END

END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSINDTREF_BI0 FOR VRH_BASE_TSINDTREF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodNovo INTEGER;

BEGIN
  IF ((NEW.BDCODSINTRAB IS NULL) OR (NEW.BDCODSINTRAB = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODSINTRAB) , 1)
       FROM vrh_base_tsindtrab
       INTO :vCodNovo;

       NEW.BDCODSINTRAB = :vCodNovo;

     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TTABSD_FAIXAS_BI0 FOR VRH_BASE_TTABSD_FAIXAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF ((NEW.bdcodsd IS NULL) OR (NEW.bdcodsd = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodsd) + 1, 1) FROM vrh_base_ttabsd_faixas WHERE bdrefsd = NEW.bdrefsd INTO :vcod;
       NEW.bdcodsd = vcod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TTABSD_FORMULA_BI0 FOR VRH_BASE_TTABSD_FORMULA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF ((NEW.bdcodsd IS NULL) OR (NEW.bdcodsd = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodsd) + 1, 1) FROM vrh_base_ttabsd_formula WHERE bdrefsd = NEW.bdrefsd INTO :vcod;
       NEW.bdcodsd = vcod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TTABSD_PARCELA_BI0 FOR VRH_BASE_TTABSD_PARCELA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF ((NEW.bdcodsd IS NULL) OR (NEW.bdcodsd = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodsd) + 1, 1) FROM vrh_base_ttabsd_parcela WHERE bdrefsd = NEW.bdrefsd INTO :vcod;
       NEW.bdcodsd = vcod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TTERC_DOC_AI0 FOR VRH_BASE_TTERC_DOC
ACTIVE AFTER INSERT POSITION 0 
AS
BEGIN
  INSERT INTO VRH_BASE_TTERC_CNIS (BDCODTER,BDCOD_NIS_INV,BDCOD_CPF_INV,BDCOD_NOME_INV,BDCOD_DN_INV,BDCOD_CNIS_NIS,BDCOD_CNIS_DN,BDCOD_CNIS_OBITO,BDCOD_CNIS_CPF,
    BDCOD_CNIS_CPF_NAO_INF,BDCOD_CPF_NAO_CONSTA,BDCOD_CPF_NULO,BDCOD_CPF_CANCELADO,BDCOD_CPF_SUSPENSO,BDCOD_CPF_DN,BDCOD_CPF_NOME,BDCOD_ORIENTACAO_CPF,BDCOD_ORIENTACAO_NIS)
  VALUES (NEW.bdcodter,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99);
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TTERCEIROS_BI0 FOR VRH_BASE_TTERCEIROS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODIGO IS NULL) OR (NEW.BDCODIGO < 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODIGO) + 1, 1)
       FROM vrh_base_tterceiros
       INTO :vNovoCod;

       NEW.BDCODIGO = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TTIPOCALCAVUL_AI0 FOR VRH_BASE_TTIPOCALCAVUL
ACTIVE AFTER INSERT POSITION 0 
AS
BEGIN
  EXECUTE PROCEDURE SP_INSERT_FOLHAAVULSA_ONLINE(NEW.bdcodtca);
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TTIPOCALCAVUL_BI0 FOR VRH_BASE_TTIPOCALCAVUL
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodtca IS NULL) OR (NEW.bdcodtca = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodtca)+1),1) FROM VRH_BASE_TTIPOCALCAVUL INTO vcodigo;
        NEW.bdcodtca = vcodigo;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBAS_AI0 FOR VRH_BASE_TVERBAS
ACTIVE AFTER INSERT POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_INSERT_NOVA_VERBA_ONLINE(NEW.bdclaver,NEW.bdcodver);
  execute procedure SP_INSEREVERBA_CONFMEDIAS(new.bdcodver, new.bdclaver, 'VRH_BASE_TCONF_FICHA_HE', 0);
  execute procedure SP_INSEREVERBA_CONFMEDIAS(new.bdcodver, new.bdclaver, 'VRH_BASE_TCONF_FICHA_RV', 1);
  execute procedure SP_INSEREVERBA_CONFMEDIAS(new.bdcodver, new.bdclaver, 'VRH_BASE_TCONF_FICHA_HN', 2);
  execute procedure SP_INSEREVERBA_CONFMEDIAS(new.bdcodver, new.bdclaver, 'VRH_BASE_TCONF_FICHA_OUT', 3);
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBAS_AU0 FOR VRH_BASE_TVERBAS
ACTIVE AFTER UPDATE POSITION 0
AS
  declare variable wnada BIGINT;
BEGIN
  wnada = GEN_ID(GEN_ALTVERBAS, 1);

  IF (OLD.bdclaver <> NEW.bdclaver) THEN
     BEGIN
       EXECUTE PROCEDURE SP_UPDATE_VERBA_ONLINE(OLD.bdclaver,NEW.bdclaver,NEW.BDCODVER);
       UPDATE VRH_BASE_TCONF_FICHA_HE SET BDCLAVER = NEW.BDCLAVER WHERE BDCODVER = NEW.BDCODVER;
       UPDATE VRH_BASE_TCONF_FICHA_HN SET BDCLAVER = NEW.BDCLAVER WHERE BDCODVER = NEW.BDCODVER;
       UPDATE VRH_BASE_TCONF_FICHA_RV SET BDCLAVER = NEW.BDCLAVER WHERE BDCODVER = NEW.BDCODVER;
       UPDATE VRH_BASE_TCONF_FICHA_OUT SET BDCLAVER = NEW.BDCLAVER WHERE BDCODVER = NEW.BDCODVER;
       UPDATE VRH_BASE_TIPO_MEDIASSIND SET BDCLASSTMS = NEW.BDCLAVER WHERE BDCLASSTMS = OLD.BDCLAVER;
       UPDATE VRH_BASE_TMS_CLASS SET BDCLASS = NEW.BDCLAVER WHERE BDCLASS = OLD.BDCLAVER;
       execute procedure SP_APAGAVERBA_CONFMEDIAS(new.bdcodver, old.bdclaver, 'VRH_BASE_TCONF_FICHA_HE');
       execute procedure SP_APAGAVERBA_CONFMEDIAS(new.bdcodver, old.bdclaver, 'VRH_BASE_TCONF_FICHA_RV');
       execute procedure SP_APAGAVERBA_CONFMEDIAS(new.bdcodver, old.bdclaver, 'VRH_BASE_TCONF_FICHA_HN');
       execute procedure SP_APAGAVERBA_CONFMEDIAS(new.bdcodver, old.bdclaver, 'VRH_BASE_TCONF_FICHA_OUT');
       execute procedure SP_INSEREVERBA_CONFMEDIAS(new.bdcodver, new.bdclaver, 'VRH_BASE_TCONF_FICHA_HE', 0);
       execute procedure SP_INSEREVERBA_CONFMEDIAS(new.bdcodver, new.bdclaver, 'VRH_BASE_TCONF_FICHA_RV', 1);
       execute procedure SP_INSEREVERBA_CONFMEDIAS(new.bdcodver, new.bdclaver, 'VRH_BASE_TCONF_FICHA_HN', 2);
       execute procedure SP_INSEREVERBA_CONFMEDIAS(new.bdcodver, new.bdclaver, 'VRH_BASE_TCONF_FICHA_OUT', 3);
       update VRHF_BASE_TVERBASEMP set BDCLASSIFVEREMP = substring(new.bdclaver from 1 for 9) where BDCODVER = new.bdcodver;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBAS_BI0 FOR VRH_BASE_TVERBAS
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;
  declare variable wnada BIGINT;
BEGIN
  wnada = GEN_ID(GEN_ALTVERBAS, 1);

  SELECT FIRST 1 Y.BDORDEMVER
  FROM vrh_base_tverbas Y
  WHERE SUBSTRING(Y.BDCLAVER FROM 1 FOR 9) = SUBSTRING(NEW.BDCLAVER FROM 1 FOR 9)
  INTO :vNovoCod;

  IF (vnovocod IS NULL OR (vnovocod = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(Y.BDORDEMVER) + 1, 1)
       FROM vrh_base_tverbas Y
       INTO :vNovoCod;
     END

  NEW.bdordemver = :vnovocod;

  IF (NEW.bdtipover IS NULL) THEN
     NEW.bdtipover = 0;

  IF (COALESCE(NEW.bdcodver, 0) = 0) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODVER) + 1, 1) FROM VRH_BASE_TVERBAS INTO :vnovocod;
       NEW.bdcodver = :vnovocod;
     END

  new.bdnivelver = strlen(trim(new.bdclaver));
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBAS_BU0 FOR VRH_BASE_TVERBAS
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  new.bdnivelver = strlen(trim(new.bdclaver));
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBAS_PADRAO_BI0 FOR VRH_BASE_TVERBAS_PADRAO
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  NEW.bdtipoverpd = 1;
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBAS_PADRAO_BU0 FOR VRH_BASE_TVERBAS_PADRAO
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
     NEW.bdtipoverpd = 1;
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBAS_REF_BI0 FOR VRH_BASE_TVERBAS_REF
ACTIVE BEFORE INSERT POSITION 0 
AS
  declare variable wnada BIGINT;
BEGIN
  SELECT first 1 GEN_ID(GEN_ALTVERBAS, 1) FROM RDB$DATABASE into :wnada;

  IF ((SELECT COUNT(*) FROM vrh_base_tverbas_ref x WHERE x.bdcodver = NEW.bdcodver) = 0) THEN
     NEW.bdrefver = 190001;
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBASBLUESOFT_BI0 FOR VRH_BASE_TVERBASBLUESOFT
ACTIVE BEFORE INSERT POSITION 0 
AS
DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF ((NEW.bdcodverbs IS NULL) OR (NEW.bdcodverbs = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODVERBS) + 1, 1) FROM VRH_BASE_TVERBASBLUESOFT WHERE BDCODPLABS = NEW.bdcodplabs INTO :vcod;
       NEW.bdcodverbs = :vcod;
     END

  IF (NEW.bdtipoverbs = 1) THEN
     DELETE FROM VRH_BASE_TITENSBLUESOFT WHERE BDCODPLABS = NEW.bdcodplabs AND BDCODVERBS = NEW.bdcodverbs;
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBASBLUESOFT_BU0 FOR VRH_BASE_TVERBASBLUESOFT
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  IF (NEW.bdtipoverbs = 1) THEN
     DELETE FROM VRH_BASE_TITENSBLUESOFT WHERE BDCODPLABS = NEW.bdcodplabs AND BDCODVERBS = NEW.bdcodverbs;
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBASEMP_PADRAO_BI0 FOR VRH_BASE_TVERBASEMP_PADRAO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;
  DECLARE VARIABLE vClass VARCHAR(9);

BEGIN
  IF ((NEW.bdcodigoveremppd IS NULL) OR (NEW.bdcodigoveremppd = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODIGOVEREMPPD) + 1, 1) FROM VRH_BASE_TVERBASEMP_PADRAO
       INTO :vNovoCod;

       NEW.bdcodigoveremppd = :vNovoCod;
     END

  IF (NEW.bdclassifveremppd IS NULL) THEN
    BEGIN
      SELECT SUBSTRING(X.BDCLAVER FROM 1 FOR 9)
      FROM VRH_BASE_TVERBAS X
      WHERE X.BDCODVER = NEW.BDCODVER
      INTO :vClass;

      NEW.bdclassifveremppd = :vClass;
    END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBASEMP_PADRAO_BU0 FOR VRH_BASE_TVERBASEMP_PADRAO
ACTIVE BEFORE UPDATE POSITION 0 
AS
  DECLARE VARIABLE vClass VARCHAR(9);

BEGIN
  SELECT SUBSTRING(X.BDCLAVER FROM 1 FOR 9)
  FROM VRH_BASE_TVERBAS X
  WHERE X.BDCODVER = NEW.BDCODVER
  INTO :vClass;
  NEW.bdclassifveremppd = :vClass;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_CONTAB_GPS_BI0 FOR VRH_EMP_CONTAB_GPS
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
     SELECT COALESCE(MAX(bdordem),0)+1 FROM VRH_EMP_CONTAB_GPS WHERE bdcodemp = NEW.bdcodemp AND bdchavedarf = NEW.bdchavedarf INTO NEW.bdordem;


  IF (NEW.bdcodtpcc = 0) THEN
     BEGIN
       NEW.bdcodtpcc = NULL;
       NEW.bdcodcentro = NULL;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_HRCOMP_BI0 FOR VRH_EMP_HRCOMP
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
     SELECT MAX(bdordem) FROM vrh_emp_treembolso WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = NEW.bdcodimp INTO NEW.bdordem;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_HRDED_BI0 FOR VRH_EMP_HRDED
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
     SELECT MAX(bdordem) FROM vrh_emp_treembolso WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = NEW.bdcodimp INTO NEW.bdordem;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_HRNF_BI0 FOR VRH_EMP_HRNF
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
     SELECT MAX(bdordem) FROM vrh_emp_treembolso WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = NEW.bdcodimp INTO NEW.bdordem;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_RCOMP_BI0 FOR VRH_EMP_RCOMP
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
     SELECT MAX(bdordem) FROM vrh_emp_treembolso WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = NEW.bdcodimp INTO NEW.bdordem;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_RNF_BI0 FOR VRH_EMP_RNF
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
     SELECT MAX(bdordem) FROM vrh_emp_treembolso WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = NEW.bdcodimp INTO NEW.bdordem;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TACERTOCAGED_BI0 FOR VRH_EMP_TACERTOCAGED
ACTIVE BEFORE INSERT POSITION 0 
AS
DECLARE VARIABLE novocod INTEGER;
BEGIN
  IF ((NEW.bdCODACCAGED IS NULL) OR (NEW.BDCODACCAGED = 0))  THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODACCAGED) + 1, 1)
       FROM VRH_EMP_TACERTOCAGED WHERE BDCODEMP = NEW.BDCODEMP INTO novocod;
       NEW.BDCODACCAGED = novocod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TBENEFINCAPACIDADE_BI0 FOR VRH_EMP_TBENEFINCAPACIDADE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;

BEGIN
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrh_emp_tbenefincapacidade WHERE (bdcodemp = NEW.bdcodemp)  AND (bdCodcol = NEW.bdcodcol) INTO vNova_Chave;
      NEW.bdchave = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM vrh_emp_tbenefincapacidade WHERE (bdchave = NEW.bdchave) AND (bdcodcol = NEW.bdcodcol) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrh_emp_tbenefincapacidade WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) INTO vNova_Chave;
           NEW.bdchave = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCAT_AGCAUSADOR_BI0 FOR VRH_EMP_TCAT_AGCAUSADOR
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vrh_emp_tcat_agcausador WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
      NEW.BDORDEM = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT BDORDEM FROM vrh_emp_tcat_agcausador WHERE (BDORDEM = NEW.BDORDEM) AND (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) AND (bdChave = NEW.bdchave) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vrh_emp_tcat_agcausador WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
           NEW.BDORDEM = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCAT_ATESTADO_BI0 FOR VRH_EMP_TCAT_ATESTADO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vrh_emp_tcat_atestado WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
      NEW.BDORDEM = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT BDORDEM FROM vrh_emp_tcat_atestado WHERE (BDORDEM = NEW.BDORDEM) AND (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) AND (bdChave = NEW.bdchave) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vrh_emp_tcat_atestado WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
           NEW.BDORDEM = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER trigger vrh_emp_tcat_bu0 for vrh_emp_tcat
active before update position 0
AS
BEGIN
  if (NEW.BDCODSITGER = 0) then
     NEW.BDCODSITGER = NULL;

  NEW.bdrefcat = CAST((SUBSTRING(CAST(NEW.bddataemissao AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.bddataemissao AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
END^

CREATE OR ALTER TRIGGER VRH_EMP_TCAT_PATINGIDAS_BI0 FOR VRH_EMP_TCAT_PATINGIDAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vrh_emp_tcat_patingidas WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
      NEW.BDORDEM = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT BDORDEM FROM vrh_emp_tcat_patingidas WHERE (BDORDEM = NEW.BDORDEM) AND (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) AND (bdChave = NEW.bdchave) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vrh_emp_tcat_patingidas WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) AND (bdChave = NEW.bdchave) INTO vNova_Chave;
           NEW.BDORDEM = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_ADM_BI0 FOR VRH_EMP_TCOL_ADM
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;
  DECLARE VARIABLE vdataadm DATE;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;
       NEW.BDCODCOL = :vNovoCod;
     END

--  IF (NEW.bdvincempcol is null) then
--    new.bdvincempcol = 0;

  IF ((NEW.bdficharegcol IS NULL) OR (TRIM(NEW.bdficharegcol) = ''))  THEN
     BEGIN
       NEW.bdficharegcol = CAST(NEW.bdcodcol AS VARCHAR(10));
     END

  IF (NEW.bddatainiaquicol IS NULL) THEN
     BEGIN
       SELECT FIRST 1 BDDATAADMCOL FROM VRH_EMP_TCOLCON WHERE BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol INTO :vdataadm;
       NEW.bddatainiaquicol = :vdataadm;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_ASO_BI0 FOR VRH_EMP_TCOL_ASO
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodaso IS NULL) OR (NEW.bdcodaso = 0)) THEN
     SELECT COALESCE(MAX(bdcodaso),0)+1 FROM vrh_emp_tcol_aso WHERE bdcodemp = NEW.bdcodemp AND bdcodcol = NEW.bdcodcol INTO NEW.bdcodaso;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_ASO_EXAME_BI0 FOR VRH_EMP_TCOL_ASO_EXAME
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodexame IS NULL) OR (NEW.bdcodexame = 0)) THEN
     SELECT COALESCE(MAX(bdcodexame),0)+1 FROM vrh_emp_tcol_aso_exame WHERE bdcodemp = NEW.bdcodemp AND bdcodcol = NEW.bdcodcol AND bdcodaso = NEW.bdcodaso INTO NEW.bdcodexame;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_ASO_MONITBIO_BI0 FOR VRH_EMP_TCOL_ASO_MONITBIO
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodmonit IS NULL) OR (NEW.bdcodmonit = 0)) THEN
     SELECT COALESCE(MAX(bdcodmonit),0)+1 FROM vrh_emp_tcol_aso_monitbio WHERE bdcodemp = NEW.bdcodemp AND bdcodcol = NEW.bdcodcol AND bdcodaso = NEW.bdcodaso INTO NEW.bdcodmonit;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_DOC_BI0 FOR VRH_EMP_TCOL_DOC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;
--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_FIS_BI0 FOR VRH_EMP_TCOL_FIS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
      SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_HIST_BI0 FOR VRH_EMP_TCOL_HIST
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
      SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER vrh_emp_tcol_hist_au0 FOR vrh_emp_tcol_hist
ACTIVE AFTER UPDATE POSITION 0
AS
  DECLARE VARIABLE vCODSOC INTEGER;
BEGIN
/* Gilberto - 25/10/2017 - 20915 - Esse processo é feito pelo único

  vCODSOC = NULL;
  SELECT FIRST 1 x.bdCODSOC FROM empresas_tsoc x
  WHERE (x.BDCODEMP = NEW.bdcodemp)
  AND (x.bdcgcceisoc = (select first 1 BDCPFCOL from vrh_emp_tcolcon where bdcodemp = new.bdcodemp and bdcodcol = new.bdcodcol))
  INTO :vcodsoc;

  if ((vCODSOC is not null) and (new.bdcontrcol = 1)) then
  begin
    update empresas_tsoc set
    BDCODPAISORIG = NEW.BDCODPAISNAS,
    BDNATURALIZADO = NEW.BDNATURALIZADOCOL,
    BDPORTNAT = NEW.BDPORTNAT,
    BDDATANATURALIZACAO = NEW.BDDATANATURALIZACAO,
    BDDATACHEBRASIL = new.BDDTAPOSENT
    WHERE (BDCODEMP = NEW.BDCODEMP)
    AND (BDCODSOC = :vCODSOC);
  end
*/
END^

CREATE OR ALTER TRIGGER vrh_emp_tcolcon_cad_au0 FOR vrh_emp_tcolcon_cad
ACTIVE AFTER UPDATE POSITION 0
AS
  DECLARE VARIABLE vcodsoc INTEGER;
  DECLARE VARIABLE vexterior VARCHAR (5);
BEGIN
/* Gilberto - 25/10/2017 - 20915 - Esse processo é feito pelo único

 vCODSOC = NULL;
  SELECT FIRST 1 x.bdCODSOC FROM empresas_tsoc x
  WHERE (x.BDCODEMP = NEW.bdcodemp)
  AND (x.bdcgcceisoc = (select first 1 BDCPFCOL from vrh_emp_tcolcon where bdcodemp = new.bdcodemp and bdcodcol = new.bdcodcol))
  INTO :vcodsoc;

  select case when (upper(bddescpais) = 'BRASIL') then 'FALSE' else 'TRUE' end bdexterior from tpais where bdcodpais = new.bdcodpaisres into :vexterior;

  if ((vCODSOC is not null) and (new.bdcontrcol = 1)) then
  begin
    update empresas_tsoc set
    bdcodpais = NEW.bdcodpaisres,
    bdexteriorsoc = :vexterior
    WHERE (BDCODEMP = NEW.BDCODEMP)
    AND (BDCODSOC = :vCODSOC);
  end
*/
END^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_PARENT_BI0 FOR VRH_EMP_TCOL_PARENT
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
      SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_VINC_BI0 FOR VRH_EMP_TCOL_VINC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
      SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END

  IF (NEW.BDCONTRCOL = 1) THEN
     NEW.BDCODSINTRAB = NULL;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_VINC_BU0 FOR VRH_EMP_TCOL_VINC
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  IF (NEW.BDCONTRCOL = 1) THEN
     NEW.BDCODSINTRAB = NULL;

END
^

CREATE OR ALTER trigger vrh_emp_tcolcon_calcdia_bu0 for vrh_emp_tcolcon_calcdia
active before update position 0
AS
begin
  if ((OLD.BDDATAEFEITO is null) and (NEW.BDDATAEFEITO is null)) then
    begin
        NEW.BDDATAEFEITO = NEW.bddatacol;
    end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_VINCDIA_BI0 FOR VRH_EMP_TCOL_VINCDIA
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;
  DECLARE VARIABLE vAnoMes VARCHAR(6);
  DECLARE VARIABLE vData DATE;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(X.BDCODCOL) from vrh_emp_tcolcon X where X.BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(X.BDCODCOL) from vrh_emp_tcolcon X where X.BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END

  vAnoMes =  SUBSTRING(CAST(NEW.BDDATACOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDDATACOL AS VARCHAR(10)) FROM 6 FOR 2);

  new.bdrefcol = cast(vanomes as integer);

  IF (NEW.BDCODPLAFUC IS NULL OR (NEW.BDCODPLAFUC = 0)) THEN
     BEGIN
       SELECT FIRST 1 X.BDCODPLAFUC
       FROM  SP_FUNCOES_PLANO_EMP(NEW.BDCODEMP, 0, CAST(:vAnoMes AS INTEGER)) X
       INTO :vNovoCod;

       IF (vNovoCod IS NULL) THEN
          BEGIN
            SELECT CURRENT_DATE
            FROM rdb$database
            INTO :vData;

            vAnoMes =  EXTRACT(YEAR FROM :vData )||EXTRACT(MONTH FROM :vData);

            SELECT FIRST 1 X.BDCODPLAFUC
            FROM SP_FUNCOES_PLANO_EMP(NEW.BDCODEMP, 0, CAST(:vAnoMes AS INTEGER)) X
            INTO :vNovoCod;
          END

       NEW.BDCODPLAFUC = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_AI0 FOR VRH_EMP_TCOLCON
ACTIVE AFTER INSERT POSITION 0 
AS
BEGIN
  INSERT INTO VRH_EMP_TCOLCON_CNIS (BDCODEMP,BDCODCOL,BDCOD_NIS_INV,BDCOD_CPF_INV,BDCOD_NOME_INV,BDCOD_DN_INV,BDCOD_CNIS_NIS,BDCOD_CNIS_DN,BDCOD_CNIS_OBITO,BDCOD_CNIS_CPF,
    BDCOD_CNIS_CPF_NAO_INF,BDCOD_CPF_NAO_CONSTA,BDCOD_CPF_NULO,BDCOD_CPF_CANCELADO,BDCOD_CPF_SUSPENSO,BDCOD_CPF_DN,BDCOD_CPF_NOME,BDCOD_ORIENTACAO_CPF,BDCOD_ORIENTACAO_NIS)
  VALUES (NEW.bdcodemp, NEW.bdcodcol,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99);
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_BD0 FOR VRH_EMP_TCOLCON
ACTIVE BEFORE DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  DELETE FROM VRHF_EMP_TFOLHATOMADOR WHERE bdcodemp = OLD.bdcodemp AND bdcodcol = OLD.bdcodcol;
  DELETE FROM VRH_RHNET_TREGISTRO WHERE BDCODEMP = old.BDCODEMP and BDSTATUS = 0 and BDCODTIPO = 5 and BDCHAVEARQIND like '%.'||old.BDIDRHNET||'.%' ;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_FD FOR VRH_EMP_TCOLCON
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  /* Trigger text */
  DELETE FROM VRHF_EMP_FGTSDIG_TRAB WHERE bdcodemp = OLD.bdcodemp AND bdcodcol = OLD.bdcodcol;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_BD1 FOR VRH_EMP_TCOLCON
ACTIVE BEFORE DELETE POSITION 0
AS
  DECLARE VARIABLE vNovoCod    INTEGER;
  DECLARE VARIABLE vNOMECOL    VARCHAR (70);
  DECLARE VARIABLE vCATESOCIAL INTEGER;
  DECLARE VARIABLE vVINCEMPCOL INTEGER;
  DECLARE VARIABLE vCODPLAFUC  INTEGER;
  DECLARE VARIABLE vCODTFUC    INTEGER;
  DECLARE VARIABLE vSQL        VARCHAR (5000);
  DECLARE VARIABLE vREF        INTEGER;
  DECLARE VARIABLE vDATA       DATE;
  DECLARE VARIABLE vHORA       TIME;

begin
  select coalesce(max(X.BDCODIGO) + 1, 1) from VRH_EMP_TCOL_EMAIL X into :vNovoCod;
  select current_date from RDB$DATABASE into :vDATA;
  select current_time from RDB$DATABASE into :vHORA;

  select cast(substring(cast(current_date as varchar(10)) from 1 for 4) || substring(cast(current_date as varchar(10)) from 6 for 2) as integer)
  from RDB$DATABASE into :vREF;

  vSQL = 'select CAD.BDNOMCOL, FGTS.BDCATEGORIAESOCIAL, coalesce(ADMREF.BDVINCEMPCOL, SEFIP.BDCATSEFIPEMP) BDVINCEMPCOL, PARTIDA.BDCODPLAFUC, PARTIDA.BDCODTFUC ' ||
         'from VRH_EMP_TCOLCON_CAD CAD ' ||
         'left join VRHF_EMP_TCOLCON_FGTSGPS FGTS on (FGTS.BDCODEMP = ' || old.bdcodemp || ') and (FGTS.BDCODCOL = ' || old.bdcodcol || ') and (FGTS.BDREFCOL = (select max(BDREFCOL) ' ||
                                                                                                                                                                 'from VRHF_EMP_TCOLCON_FGTSGPS ' ||
                                                                                                                                                                 'where BDREFCOL <= ' || vREF || ' and ' ||
                                                                                                                                                                       'BDCODEMP = ' || old.bdcodemp || ' and ' ||
                                                                                                                                                                       'BDCODCOL = ' || old.bdcodcol || ')) ' ||
         'left join VRH_EMP_TCOL_ADMREF ADMREF on (ADMREF.BDCODEMP = ' || old.bdcodemp || ') and (ADMREF.BDCODCOL = ' || old.bdcodcol || ') and (ADMREF.BDREFCOL = (select max(BDREFCOL) ' ||
                                                                                                                                                                    'from VRH_EMP_TCOL_ADMREF ' ||
                                                                                                                                                                    'where BDREFCOL <= ' || vREF || ' and ' ||
                                                                                                                                                                          'BDCODEMP = ' || old.bdcodemp || ' and ' ||
                                                                                                                                                                          'BDCODCOL = ' || old.bdcodcol || ')) ' ||
         'left join VRHF_BASE_TEMPSEFIP SEFIP on (SEFIP.BDCODEMP = ' || old.bdcodemp || ') and (SEFIP.BDREFEMP = (select max(BDREFEMP) ' ||
                                                                                                                 'from VRHF_BASE_TEMPSEFIP ' ||
                                                                                                                 'where BDREFEMP <= ' || vREF || ' and ' ||
                                                                                                                       'BDCODEMP = ' || old.bdcodemp || ')) ' ||
         'left join VRH_EMP_TCOLCON_PARTIDA PARTIDA on (PARTIDA.BDCODEMP = ' || old.bdcodemp || ') and (PARTIDA.BDCODCOL = ' || old.bdcodcol || ')' ||
         'where CAD.BDCODEMP = ' || old.bdcodemp || ' and ' ||
               'CAD.BDCODCOL = ' || old.bdcodcol || ' and ' ||
               'CAD.BDREFCOL = (select max(BDREFCOL) ' ||
                               'from VRH_EMP_TCOLCON_CAD ' ||
                               'where BDREFCOL <= ' || vREF || ' and ' ||
                                     'BDCODEMP = ' || old.bdcodemp || ' and ' ||
                                     'BDCODCOL = ' || old.bdcodcol || ')';

  FOR EXECUTE STATEMENT vSQL INTO :vNOMECOL, :vCATESOCIAL, :vVINCEMPCOL, :vCODPLAFUC, :vCODTFUC DO
    begin
      insert into VRH_EMP_TCOL_EMAIL(BDCODIGO, BDCODEMP, BDCODCOL, BDCPFCOL, BDNOMCOL, BDMATRICULA, BDMATRICULASEMVINC, BDDATANASCCOL, BDDATAADMCOL, BDCATEGORIAESOCIAL, BDVINCEMPCOL, BDDATAINCLUSAO, BDHORAINCLUSAO, BDPODEDELETAR, BDCODTFUC, BDCODPLAFUC)
      values(:vNovoCod, old.bdcodemp, old.bdcodcol, old.bdcpfcol, :vNOMECOL, old.bdmatricula, old.bdmatriculasemvinc, old.bddatanasccol, old.bddataadmcol, :vCATESOCIAL, :vVINCEMPCOL, :vDATA, :vHORA, 'True', :vCODTFUC, :vCODPLAFUC);
    end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_BENEF_BI0 FOR VRH_EMP_TCOLCON_BENEF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF (NEW.BDCODBENEF IS NULL OR (NEW.BDCODBENEF = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODBENEF), 0) + 1 FROM VRH_EMP_TCOLCON_BENEF WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL INTO :vNovoCod;
       NEW.BDCODBENEF = :vNovoCod;
     END
END
^

CREATE OR ALTER trigger VRH_EMP_BUSINESSSEGMENT_BI0 for VRH_EMP_BUSINESSSEGMENT
active before insert position 0
AS
  DECLARE VARIABLE vNovoCod Integer;
begin
  IF ((NEW.BDCODIGO IS NULL) or (NEW.BDCODIGO = 0))  THEN
    BEGIN
      SELECT COALESCE(MAX(BDCODIGO) + 1, 1) FROM VRH_EMP_BUSINESSSEGMENT INTO :vNovoCod;

      NEW.BDCODIGO = vNovoCod;
    END

END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_BI0 FOR VRH_EMP_TCOLCON
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  NEW.bdcontrcol = coalesce(NEW.bdcontrcol, 0);
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
     IF (NEW.bdcontrcol = 1) THEN
          BEGIN
            SELECT COALESCE(MAX(X.BDCODCOL) + 1, 1)
            FROM vrh_emp_tcolcon X
            WHERE X.BDCODEMP = NEW.BDCODEMP AND coalesce(bdcontrcol, 0) = 1
--            where X.BDCODEMP = new.BDCODEMP and X.bdCodCol >= 900000
            INTO :vNovoCod;

            IF ((vnovocod IS NULL) OR (vnovocod = 0) OR (vnovocod = 1)) THEN
               vnovocod = 900000;

             SELECT bdcodcol FROM SP_EXISTE_COLABORADOR_NOVO(NEW.bdcodemp,:vnovocod) INTO :vnovocod;
          END
       ELSE
          BEGIN
            SELECT COALESCE(MAX(X.BDCODCOL) + 1, 1)
            FROM vrh_emp_tcolcon X
            WHERE X.BDCODEMP = NEW.BDCODEMP AND coalesce(bdcontrcol, 0) <> 1
--            where X.BDCODEMP = new.BDCODEMP and X.BDCodCol < 900000
            INTO :vNovoCod;

             SELECT bdcodcol FROM SP_EXISTE_COLABORADOR_NOVO(NEW.bdcodemp,:vnovocod) INTO :vnovocod;
          END

       NEW.BDCODCOL = :vNovoCod;
     END

  IF (NEW.bdcodtipo IS NULL) THEN
     BEGIN
       SELECT bdcodtipo FROM tipos_lancamentos_padrao WHERE bdcodtipo = 201 INTO NEW.bdcodtipo;
     END

  -- 144124 - Raphael Teodoro - 04/12/2020
  IF (NEW.BDCPFCOL IS NOT NULL) THEN
     BEGIN
       UPDATE VRHF_MVAUT
       SET BDMODIFICADO = 'TRUE'
       WHERE (BDCPF = NEW.BDCPFCOL)
         AND ((COALESCE(BDREFFIM, 0) = 0) OR (BDREFFIM >= ((EXTRACT(YEAR FROM NEW.BDDATAADMCOL) * 100) + EXTRACT(MONTH FROM NEW.BDDATAADMCOL))));
     END

--  NEW.BDNOMCOLUPPER = UPPER(NEW.BDNOMCOL);

  IF (NEW.bdcontrcol = 1) THEN
     NEW.bddtpcol = 'Contribuinte';
  ELSE
     NEW.bddtpcol = 'Colaborador';


  new.bdrefadmcol = CAST((substring(CAST(new.bddataadmcol as varchar(10)) from 1 for 4)||substring(CAST(new.bddataadmcol as varchar(10)) from 6 for 2)) AS INTEGER);

  new.bdpensaonova = 1; -- para novos colaboradores, deve setar essa informação para calcular as pensões pela nova forma de cálculo.
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_BU0 FOR VRH_EMP_TCOLCON
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
--  NEW.BDNOMCOLUPPER = UPPER(NEW.BDNOMCOL);

  UPDATE VRH_EMP_TCOL_ADMPREL SET BDSTATUSQC = NEW.BDSTATUSQC, BDCADCOLCON = 'TRUE' WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL;

  -- Não pode mudar o tipo de cadastramento inicial
  if (old.BDCODTIPO is not null) then
     new.BDCODTIPO = old.BDCODTIPO;

  new.bdrefadmcol = CAST((substring(CAST(new.bddataadmcol as varchar(10)) from 1 for 4)||substring(CAST(new.bddataadmcol as varchar(10)) from 6 for 2)) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_CALCDIA_BI0 FOR VRH_EMP_TCOLCON_CALCDIA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
      SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END

  if (NEW.BDDATAEFEITO is null) then
    BEGIN
      NEW.BDDATAEFEITO = NEW.BDDATACOL;
    END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_DIA_BI0 FOR VRH_EMP_TCOLCON_DIA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
      SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_DOC_BI0 FOR VRH_EMP_TCOLCON_DOC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
      SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_ESTAGIO_BI0 FOR VRH_EMP_TCOLCON_ESTAGIO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCod INTEGER;

BEGIN
  IF ((NEW.bdcodest IS NULL) OR (NEW.bdcodest = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODEST) + 1, 1) FROM VRH_EMP_TCOLCON_ESTAGIO WHERE BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol INTO :vCod;
       NEW.bdcodest = :vcod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_IMG_BI0 FOR VRH_EMP_TCOLCON_IMG
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;
  DECLARE VARIABLE vCodImg INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
    BEGIN
      SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;
      NEW.BDCODCOL = :vNovoCod;
    END

  IF (COALESCE(NEW.bdisrhnet, 0) = 1) THEN   -- RH NET Social
     BEGIN
      IF (TRIM(COALESCE(NEW.BDFOTORHNET, '')) = '') THEN
         NEW.BDFOTOCOL_IMG = NULL;
      ELSE
         BEGIN
           vCodImg = 0;
           SELECT BDCODIMG FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTORHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTORHNET))) INTO vCodImg;
           IF (vCodImg > 0) THEN
             BEGIN
               NEW.BDFOTOCOL_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTORHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTORHNET))));
               DELETE FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTORHNET);
             END
           ELSE
             NEW.BDFOTOCOL_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTORHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTORHNET))));
         END

      NEW.BDFOTORHNET = '';

      IF (TRIM(COALESCE(NEW.BDCPFRHNET, '')) = '') THEN
         NEW.BDCPF_IMG = NULL;
      ELSE
         BEGIN
           vCodImg = 0;
           SELECT BDCODIMG FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCPFRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCPFRHNET))) INTO vCodImg;
           IF (vCodImg > 0) THEN
             BEGIN
               NEW.BDCPF_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCPFRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCPFRHNET))));
               DELETE FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCPFRHNET);
             END
           ELSE
             NEW.BDCPF_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCPFRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCPFRHNET))));
         END

      NEW.BDCPFRHNET = '';

      IF (TRIM(COALESCE(NEW.BDRGRHNET, '')) = '') THEN
         NEW.BDRG_IMG = NULL;
      ELSE
         BEGIN
           vCodImg = 0;
           SELECT BDCODIMG FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDRGRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDRGRHNET))) INTO vCodImg;
           IF (vCodImg > 0) THEN
             BEGIN
               NEW.BDRG_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDRGRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDRGRHNET))));
               DELETE FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDRGRHNET);
             END
           ELSE
             NEW.BDRG_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDRGRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDRGRHNET))));
         END

      NEW.BDRGRHNET = '';

      IF (TRIM(COALESCE(NEW.BDPISRHNET, '')) = '') THEN
         NEW.BDPIS_IMG = NULL;
      ELSE
         BEGIN
           vCodImg = 0;
           SELECT BDCODIMG FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDPISRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDPISRHNET))) INTO vCodImg;
           IF (vCodImg > 0) THEN
             BEGIN
               NEW.BDPIS_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDPISRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDPISRHNET))));
               DELETE FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDPISRHNET);
             END
           ELSE
             NEW.BDPIS_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDPISRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDPISRHNET))));
         END

      NEW.BDPISRHNET = '';

      IF (TRIM(COALESCE(NEW.BDTITRHNET, '')) = '') THEN
         NEW.BDTITELEITOR_IMG = NULL;
      ELSE
         BEGIN
           vCodImg = 0;
           SELECT BDCODIMG FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDTITRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDTITRHNET))) INTO vCodImg;
           IF (vCodImg > 0) THEN
             BEGIN
               NEW.BDTITELEITOR_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDTITRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDTITRHNET))));
               DELETE FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDTITRHNET);
             END
           ELSE
             NEW.BDTITELEITOR_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDTITRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDTITRHNET))));
         END

      NEW.BDTITRHNET = '';

      IF (TRIM(COALESCE(NEW.BDCNHRHNET, '')) = '') THEN
         NEW.BDCNH_IMG = NULL;
      ELSE
         BEGIN
           vCodImg = 0;
           SELECT BDCODIMG FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCNHRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCNHRHNET))) INTO vCodImg;
           IF (vCodImg > 0) THEN
             BEGIN
               NEW.BDCNH_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCNHRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCNHRHNET))));
               DELETE FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCNHRHNET);
             END
           ELSE
             NEW.BDCNH_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCNHRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCNHRHNET))));
         END

      NEW.BDCNHRHNET = '';

      IF (TRIM(COALESCE(NEW.BDCTPSRHNET, '')) = '') THEN
         NEW.BDCTPS_IMG = NULL;
      ELSE
         BEGIN
           vCodImg = 0;
           SELECT BDCODIMG FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCTPSRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCTPSRHNET))) INTO vCodImg;
           IF (vCodImg > 0) THEN
             BEGIN
               NEW.BDCTPS_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCTPSRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCTPSRHNET))));
               DELETE FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCTPSRHNET);
             END
           ELSE
             NEW.BDCTPS_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCTPSRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCTPSRHNET))));
         END

      NEW.BDCTPSRHNET = '';
    END
  NEW.bdisrhnet = 0;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_PARTIDA_BI0 FOR VRH_EMP_TCOLCON_PARTIDA
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;
BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;
       NEW.BDCODCOL = :vNovoCod;
     END

--  IF (NEW.bddatatrfcol IS NULL) THEN
--    BEGIN
--      UPDATE OR INSERT INTO vrh_emp_tcolcon_dia (BDCODEMP, BDCODCOL, BDDATACOL, BDCONTRCOL) VALUES (NEW.BDCODEMP, NEW.BDCODCOL, NEW.BDDATAADMCOL, NEW.BDCONTRCOL) MATCHING (BDCODEMP,BDCODCOL,BDDATACOL);
--      UPDATE OR INSERT INTO vrh_emp_tcolcon_calcdia (BDCODEMP, BDCODCOL, BDDATACOL, BDSALBASECOL, BDCONTRCOL, BDDESCSALVAR) VALUES (NEW.BDCODEMP, NEW.BDCODCOL, NEW.BDDATAADMCOL, NEW.BDSALINICOL, NEW.BDCONTRCOL, new.bddescsalvar) MATCHING (BDCODEMP,BDCODCOL,BDDATACOL);
--      UPDATE OR INSERT INTO vrh_emp_tcol_vincdia (BDCODEMP, BDCODCOL, BDDATACOL, BDCODPLAFUC, BDCODTFUC, BDCODPQUA, BDCODQH, BDCONTRCOL, BDDESCTPJORNADA, BDTIPOJORNADA) VALUES (NEW.BDCODEMP, NEW.BDCODCOL, NEW.BDDATAADMCOL, NEW.BDCODPLAFUC, NEW.BDCODTFUC, NEW.BDCODPQUA, NEW.BDCODQH, NEW.BDCONTRCOL, new.BDDESCTPJORNADA, new.bdtipojornada) MATCHING (BDCODEMP,BDCODCOL,BDDATACOL);
--    END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_REF_BI0 FOR VRH_EMP_TCOLCON_REF
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
      SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END

   if (new.bdutilizadescsimplificado is null) then
      begin
        new.bdutilizadescsimplificado = 'TRUE';
      end
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_VINC_BI0 FOR VRH_EMP_TCOLCON_VINC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END
END
^
--Sol. 16982 - Inclusão do campo da data de pagamento
CREATE OR ALTER TRIGGER VRH_EMP_TCON_DOC_BI0 FOR VRH_EMP_TCON_DOC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;
  DECLARE VARIABLE vCodPResc INTEGER;

/*  declare variable vCodSoc integer;
  declare variable vCODCID integer;
  declare variable vNOMCOL dm_bdnomcol;
  declare variable vENDCOL dm_bdendereco;
  declare variable vNUMCOL integer;
  declare variable vCOMPLCOL dm_bdcompendereco;
  declare variable vBAICOL dm_bdbairro;
  declare variable vCEPCOL varchar(9);
  declare variable vDDDCOL integer;
  declare variable vFONECOL dm_bdtelefone;
  declare variable vDDDCELCOL integer;
  declare variable vCELCOL dm_bdtelefone;
  declare variable vEMAILCOL dm_bdemail;
  declare variable vLOGRCOL varchar(15);
  declare variable vDATANASCCOL date;
  declare variable vDATAENTSOC date;
  declare variable vRG varchar(13);
  declare variable vORGEMIRG varchar(20);
  declare variable vCODUF integer;
  declare variable vCODCBO integer; */

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END

/* Essa atualização da TEMPRESAS_SOC vai ser feita por dentro do sistema porque depende de mais de uma tabela para atualizar os sócios.
   Tentamos fazer por trigger mas dá erro no banco porque quando grava na tabela de sócios, ele tem outra trigger pra atualizar os dados dos contribuintes e entra em loop.
   -- Seleciona dados basicos do colaboradores e joga nas variáveis.
   select col.BDCODCID,
          col.BDNOMCOL,
          col.BDENDCOL,
          col.BDNUMCOL,
          col.BDCOMPLCOL,
          col.BDBAICOL,
          col.BDCEPCOL,
          col.BDDDDCOL,
          col.BDFONECOL,
          col.BDDDDCELCOL,
          col.BDCELCOL,
          col.BDEMAILCOL,
          col.BDLOGRCOL,
          col.BDDATANASCCOL,
          col.BDDATAADMCOL,
          doc.BDRGCOL,
          doc.BDORGEMIRGCOL,
          doc.BDCODUFRG,
          tfuc.BDCODCBO
   from vrh_emp_tcolcon col
   left outer join vrh_emp_tcolcon_doc doc on (doc.BDCODEMP = col.BDCODEMP and doc.BDCODCOL = col.BDCODCOL)
   left outer join vw_vrh_emp_tcol_vincdia dia on (dia.BDCODEMP = col.BDCODEMP and dia.BDCODCOL = col.BDCODCOL)
   left outer join vrh_funcoes_tfuc tfuc on (tfuc.BDCODPLAFUC = dia.BDCODPLAFUC and tfuc.BDCODTFUC = dia.BDCODTFUC)
   where (col.BDCODEMP = new.bdcodemp) and (col.BDCODCOL = new.BDCODCOL)
       into :vCODCID, :vNOMCOL, :vENDCOL, :vNUMCOL, :vCOMPLCOL, :vBAICOL, :vCEPCOL,
            :vDDDCOL, :vFONECOL, :vDDDCELCOL, :vCELCOL, :vEMAILCOL, :vLOGRCOL, :vDATANASCCOL,
            :vDATAENTSOC, :vRG, :vORGEMIRG, :vCODUF, :vCODCBO;

   -- Cadastra o contribuinte na tabela de socios. Todo contribuinte eh um socio.

   select first 1 bdCODSOC from EMPRESAS_TSOC
   where (BDCODEMP = new.bdcodemp) and
         (BDCGCCEISOC = new.bdcpfcol) into :vCodSoc;

   if ((vCodSoc is null) or (vCodSoc = 0)) then
     begin
       INSERT INTO EMPRESAS_TSOC (BDCODEMP, BDCODCID, BDNOMSOC, BDENDSOC, BDNUMSOC,
                                  BDCOMPLSOC, BDBAISOC, BDCEPSOC, BDCGCCEISOC,
                                  BDDDSOC, BDTELRESSOC, BDDDCELSOC, BDTELCELSOC, BDEMAILSOC,
                                  BDLOGRSOC, BDDATANASCSOC, BDDATAENTSOC, BDDATASAISOC,
                                  BDRGSOC, BDORGEMISOC, BDCODUFRG, BDCODCBO)
              VALUES (new.bdcodemp, :vCODCID, :vNOMCOL,
                      :vENDCOL, :vNUMCOL, :vCOMPLCOL, :vBAICOL, :vCEPCOL, new.bdcpfcol,
                      :vDDDCOL, :vFONECOL, :vDDDCELCOL, :vCELCOL, :vEMAILCOL, :vLOGRCOL, :vDATANASCCOL,
                      :vDATAENTSOC, new.bddatabaixacol, :vRG, :vORGEMIRG, :vCODUF, :vCODCBO);

     end
   else
     begin
       UPDATE EMPRESAS_TSOC
         SET BDCODEMP      = new.bdcodemp,
             BDCODCID      = :vCODCID,
             BDNOMSOC      = :vNOMCOL,
             BDENDSOC      = :vENDCOL,
             BDNUMSOC      = :vNUMCOL,
             BDCOMPLSOC    = :vCOMPLCOL,
             BDBAISOC      = :vBAICOL,
             BDCEPSOC      = :vCEPCOL,
             BDDDSOC       = :vDDDCOL,
             BDTELRESSOC   = :vFONECOL,
             BDDDCELSOC    = :vDDDCELCOL,
             BDTELCELSOC   = :vCELCOL,
             BDEMAILSOC    = :vEMAILCOL,
             BDLOGRSOC     = :vLOGRCOL,
             BDDATANASCSOC = :vDATANASCCOL,
             BDDATAENTSOC  = :vDATAENTSOC,
             BDDATASAISOC  = new.BDDATABAIXACOL,
             BDRGSOC       = :vRG,
             BDORGEMISOC   = :vORGEMIRG,
             BDCODUFRG     = :vCODUF,
             BDCODCBO      = :vCODCBO

       WHERE (BDCODEMP = new.bdcodemp) and
             (BDCODSOC = :vCodSoc) and (
             (BDCODCID      <> :vCODCID) or
             (BDNOMSOC      <> :vNOMCOL) or
             (BDENDSOC      <> :vENDCOL) or
             (BDNUMSOC      <> :vNUMCOL) or
             (BDCOMPLSOC    <> :vCOMPLCOL) or
             (BDBAISOC      <> :vBAICOL) or
             (BDCEPSOC      <> :vCEPCOL) or
             (BDDDSOC       <> :vDDDCOL) or
             (BDTELRESSOC   <> :vFONECOL) or
             (BDDDCELSOC    <> :vDDDCELCOL) or
             (BDTELCELSOC   <> :vCELCOL) or
             (BDEMAILSOC    <> :vEMAILCOL) or
             (BDLOGRSOC     <> :vLOGRCOL) or
             (BDDATANASCSOC <> :vDATANASCCOL) or
             (BDDATAENTSOC  <> :vDATAENTSOC) or
             (BDDATASAISOC  <> new.BDDATABAIXACOL) or
             (BDRGSOC       <> :vRG) or
             (BDORGEMISOC   <> :vORGEMIRG) or
             (BDCODUFRG     <> :vCODUF) or
             (BDCODCBO      <> :vCODCBO) );
     end
*/

  IF (NEW.BDDATABAIXACOL IS NOT NULL) THEN
    BEGIN
      SELECT BDCODPRES FROM VRH_BASE_TPREPRESC WHERE BDCODPRES = 22 INTO :vCodPResc;   -- Demissão indireta

      IF (vCodPResc IS NOT NULL AND vCodPResc <> 0) THEN
        BEGIN
          IF ((NEW.BDDATABAIXACOL IS NOT NULL) AND (NEW.BDDATAPAGBAIXACOL IS NULL)) THEN    --Sol. 16982 - Bruno L. R. - 06/02/2017
             NEW.BDDATAPAGBAIXACOL = NEW.BDDATABAIXACOL;
          ELSE
          IF (NEW.BDDATABAIXACOL IS NULL) THEN
             NEW.BDDATAPAGBAIXACOL = NULL;

          UPDATE OR INSERT INTO VRH_EMP_TRESCISAO (BDCODEMP,BDCODCOL,BDDATARESCISAO,BDCODPRES,BDDATANOTIF,BDDATAPAGRESCISAO,BDINDPENALIM,BDPERFGTSRESC,BDVALFGTSRESC) VALUES (NEW.BDCODEMP,NEW.BDCODCOL,NEW.BDDATABAIXACOL,:vcodpresc,NEW.BDDATABAIXACOL,NEW.BDDATAPAGBAIXACOL,NEW.BDINDPENALIM,NEW.BDPERFGTSRESC,NEW.BDVALFGTSRESC);   --Sol. 16982 - Bruno L. R. - 06/02/2017
        END
    END
  ELSE
    BEGIN
      DELETE FROM VRH_EMP_TRESCISAO WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL;
    END
END
^

--Sol. 16982 - Inclusão do campo da data de pagamento
CREATE OR ALTER TRIGGER VRH_EMP_TCON_DOC_BU0 FOR VRH_EMP_TCON_DOC
ACTIVE BEFORE UPDATE POSITION 0
AS
  DECLARE VARIABLE vCodPResc INTEGER;
  DECLARE VARIABLE WEXISTEBAIXA INTEGER;
  DECLARE VARIABLE WDATAPREVCALCULO DATE;

/*  declare variable vCodSoc integer;
  declare variable vCODCID integer;
  declare variable vNOMCOL dm_bdnomcol;
  declare variable vENDCOL dm_bdendereco;
  declare variable vNUMCOL integer;
  declare variable vCOMPLCOL dm_bdcompendereco;
  declare variable vBAICOL dm_bdbairro;
  declare variable vCEPCOL varchar(9);
  declare variable vDDDCOL integer;
  declare variable vFONECOL dm_bdtelefone;
  declare variable vDDDCELCOL integer;
  declare variable vCELCOL dm_bdtelefone;
  declare variable vEMAILCOL dm_bdemail;
  declare variable vLOGRCOL varchar(15);
  declare variable vDATANASCCOL date;
  declare variable vDATAENTSOC date; */
BEGIN

/*
   -- Seleciona dados basicos do colaborados e joga nas variaveis
   select BDCODCID,BDNOMCOL,BDENDCOL,BDNUMCOL,BDCOMPLCOL,BDBAICOL,
          BDCEPCOL,BDDDDCOL,BDFONECOL,BDDDDCELCOL,BDCELCOL,BDEMAILCOL,BDLOGRCOL,BDDATANASCCOL,
          BDDATAADMCOL
   from vrh_emp_tcolcon where (BDCODEMP = new.bdcodemp) and (BDCODCOL = new.BDCODCOL) into :vCODCID, :vNOMCOL, :vENDCOL, :vNUMCOL, :vCOMPLCOL, :vBAICOL, :vCEPCOL,
                                                                                           :vDDDCOL, :vFONECOL, :vDDDCELCOL, :vCELCOL, :vEMAILCOL, :vLOGRCOL, :vDATANASCCOL,
                                                                                           :vDATAENTSOC;

   -- Cadastra o contribuinte na tabela de socios. Todo contribuinte eh um socio.

   select first 1 bdCODSOC from EMPRESAS_TSOC
   where (BDCODEMP = new.bdcodemp) and
         (BDCGCCEISOC = new.bdcpfcol) into :vCodSoc;

   if ((vCodSoc is null) or (vCodSoc = 0)) then
      begin
        INSERT INTO EMPRESAS_TSOC (BDCODEMP, BDCODCID, BDNOMSOC, BDENDSOC, BDNUMSOC,
                                   BDCOMPLSOC, BDBAISOC, BDCEPSOC, BDCGCCEISOC,
                                   BDDDSOC, BDTELRESSOC, BDDDCELSOC, BDTELCELSOC, BDEMAILSOC,
                                   BDLOGRSOC, BDDATANASCSOC, BDDATAENTSOC, BDDATASAISOC) VALUES (new.bdcodemp, :vCODCID, :vNOMCOL,
                                                     :vENDCOL, :vNUMCOL, :vCOMPLCOL, :vBAICOL, :vCEPCOL, new.bdcpfcol,
                                                     :vDDDCOL, :vFONECOL, :vDDDCELCOL, :vCELCOL, :vEMAILCOL, :vLOGRCOL, :vDATANASCCOL,
                                                     :vDATAENTSOC, new.bddatabaixacol);
      end
   else
      begin
        UPDATE EMPRESAS_TSOC
          SET BDCODEMP      = new.bdcodemp,
              BDCODCID      = :vCODCID,
              BDNOMSOC      = :vNOMCOL,
              BDENDSOC      = :vENDCOL,
              BDNUMSOC      = :vNUMCOL,
              BDCOMPLSOC    = :vCOMPLCOL,
              BDBAISOC      = :vBAICOL,
              BDCEPSOC      = :vCEPCOL,
              BDDDSOC       = :vDDDCOL,
              BDTELRESSOC   = :vFONECOL,
              BDDDCELSOC    = :vDDDCELCOL,
              BDTELCELSOC   = :vCELCOL,
              BDEMAILSOC    = :vEMAILCOL,
              BDLOGRSOC     = :vLOGRCOL,
              BDDATANASCSOC = :vDATANASCCOL,
              BDDATAENTSOC  = :vDATAENTSOC,
              BDDATASAISOC  = new.bddatabaixacol
        WHERE (BDCODEMP = new.bdcodemp) and
              (BDCODSOC = :vCodSoc) and (
              (BDCODCID      <> :vCODCID) or
              (BDNOMSOC      <> :vNOMCOL) or
              (BDENDSOC      <> :vENDCOL) or
              (BDNUMSOC      <> :vNUMCOL) or
              (BDCOMPLSOC    <> :vCOMPLCOL) or
              (BDBAISOC      <> :vBAICOL) or
              (BDCEPSOC      <> :vCEPCOL) or
              (BDDDSOC       <> :vDDDCOL) or
              (BDTELRESSOC   <> :vFONECOL) or
              (BDDDCELSOC    <> :vDDDCELCOL) or
              (BDTELCELSOC   <> :vCELCOL) or
              (BDEMAILSOC    <> :vEMAILCOL) or
              (BDLOGRSOC     <> :vLOGRCOL) or
              (BDDATANASCSOC <> :vDATANASCCOL) or
              (BDDATAENTSOC  <> :vDATAENTSOC) or
              (BDDATASAISOC  <> new.bddatabaixacol) );
      end
  */

  IF (NEW.BDDATABAIXACOL IS NOT NULL) THEN
     BEGIN
       SELECT BDCODPRES FROM VRH_BASE_TPREPRESC WHERE BDCODPRES = 22 INTO :vCodPResc;   -- Demissão indireta
       IF (vCodPResc IS NOT NULL AND vCodPResc <> 0) THEN
          BEGIN
            IF ((NEW.BDDATABAIXACOL IS NOT NULL) AND (NEW.BDDATAPAGBAIXACOL IS NULL)) THEN    --Sol. 16982 - Bruno L. R. - 06/02/2017
               NEW.BDDATAPAGBAIXACOL = NEW.BDDATABAIXACOL;
            ELSE
            IF (NEW.BDDATABAIXACOL IS NULL) THEN
               NEW.BDDATAPAGBAIXACOL = NULL;

            UPDATE OR INSERT INTO VRH_EMP_TRESCISAO (BDCODEMP,BDCODCOL,BDDATARESCISAO,BDCODPRES,BDDATANOTIF,BDDATAPAGRESCISAO,BDINDPENALIM,BDPERFGTSRESC,BDVALFGTSRESC) VALUES (NEW.BDCODEMP,NEW.BDCODCOL,NEW.BDDATABAIXACOL,:vcodpresc,NEW.BDDATABAIXACOL,NEW.BDDATAPAGBAIXACOL,NEW.BDINDPENALIM,NEW.BDPERFGTSRESC,NEW.BDVALFGTSRESC);   --Sol. 16982 - Bruno L. R. - 06/02/2017

            WEXISTEBAIXA = 0;
            SELECT BAIXA.BDCHAVE FROM VRHF_EMP_TDADOSCALC_BAIXA BAIXA
            JOIN VRHF_EMP_TPGTO_CALC PGTO ON (BAIXA.BDCODEMP = PGTO.BDCODEMP AND BAIXA.BDCHAVE = PGTO.BDCHAVEPGTO)
            WHERE BAIXA.BDCODEMP = NEW.BDCODEMP AND
                  BAIXA.BDCODCOL = NEW.BDCODCOL AND
                  BAIXA.BDTIPOCALC = 6 AND
                  BAIXA.BDREFERENCIA = CAST((SELECT BDAAAAMM FROM AAAAMM(NEW.BDDATABAIXACOL)) AS INTEGER)
            INTO :WEXISTEBAIXA;

            IF (COALESCE(WEXISTEBAIXA, 0) = 0) THEN
               BEGIN
                 UPDATE VRHF_EMP_TFOLHANORMAL SET BDDATAIRRFESOCIAL = NEW.BDDATAPAGBAIXACOL, BDDATAPGTOFN = NEW.BDDATAPAGBAIXACOL, BDREFIRRFESOCIAL = CAST((SELECT BDAAAAMM FROM AAAAMM(NEW.BDDATAPAGBAIXACOL)) AS INTEGER)
                 WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL AND BDREFFN = CAST((SELECT BDAAAAMM FROM AAAAMM(NEW.BDDATABAIXACOL)) AS INTEGER);

                 UPDATE VRHF_EMP_TFOLHATOMADOR SET BDDATAIRRFESOCIAL = NEW.BDDATAPAGBAIXACOL, BDDATAPGTOFT = NEW.BDDATAPAGBAIXACOL, BDREFIRRFESOCIAL = CAST((SELECT BDAAAAMM FROM AAAAMM(NEW.BDDATAPAGBAIXACOL)) AS INTEGER)
                 WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL AND BDREFTOMADOR = CAST((SELECT BDAAAAMM FROM AAAAMM(NEW.BDDATABAIXACOL)) AS INTEGER);
               END
          END
     END
  ELSE
     BEGIN
       DELETE FROM VRH_EMP_TRESCISAO WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL;

       IF (OLD.BDDATABAIXACOL IS NOT NULL) THEN
          BEGIN
            WEXISTEBAIXA = 0;
            SELECT BAIXA.BDCHAVE FROM VRHF_EMP_TDADOSCALC_BAIXA BAIXA
            JOIN VRHF_EMP_TPGTO_CALC PGTO ON (BAIXA.BDCODEMP = PGTO.BDCODEMP AND BAIXA.BDCHAVE = PGTO.BDCHAVEPGTO)
            WHERE BAIXA.BDCODEMP = NEW.BDCODEMP AND
                  BAIXA.BDCODCOL = NEW.BDCODCOL AND
                  BAIXA.BDTIPOCALC = 6 AND
                  BAIXA.BDREFERENCIA = CAST((SELECT BDAAAAMM FROM AAAAMM(OLD.BDDATABAIXACOL)) AS INTEGER)
            INTO :WEXISTEBAIXA;
     
            IF (COALESCE(WEXISTEBAIXA, 0) = 0) THEN
               BEGIN
                 WDATAPREVCALCULO = null;
                 SELECT BDDATAPREVCALCULO FROM VRHF_EMP_TFOLHANORMAL
                 WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL AND BDREFFN = CAST((SELECT BDAAAAMM FROM AAAAMM(OLD.BDDATABAIXACOL)) AS INTEGER)
                 UNION
                 SELECT FIRST 1 BDDATAPREVCALCULO FROM VRHF_EMP_TFOLHATOMADOR
                 WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL AND BDREFTOMADOR = CAST((SELECT BDAAAAMM FROM AAAAMM(OLD.BDDATABAIXACOL)) AS INTEGER)
                 INTO WDATAPREVCALCULO;

                 IF (WDATAPREVCALCULO IS NOT NULL) THEN
                    BEGIN
                      UPDATE VRHF_EMP_TFOLHANORMAL SET BDDATAIRRFESOCIAL = BDDATAPREVCALCULO, BDDATAPGTOFN = BDDATAPREVCALCULO, BDREFIRRFESOCIAL = CAST((SELECT BDAAAAMM FROM AAAAMM(BDDATAPREVCALCULO)) AS INTEGER)
                      WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL AND BDREFFN = CAST((SELECT BDAAAAMM FROM AAAAMM(OLD.BDDATABAIXACOL)) AS INTEGER);
          
                      UPDATE VRHF_EMP_TFOLHATOMADOR SET BDDATAIRRFESOCIAL = BDDATAPREVCALCULO, BDDATAPGTOFT = BDDATAPREVCALCULO, BDREFIRRFESOCIAL = CAST((SELECT BDAAAAMM FROM AAAAMM(BDDATAPREVCALCULO)) AS INTEGER)
                      WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL AND BDREFTOMADOR = CAST((SELECT BDAAAAMM FROM AAAAMM(OLD.BDDATABAIXACOL)) AS INTEGER);
                    END
               END
          END
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCONDDIFTRAB_BI0 FOR VRH_EMP_TCONDDIFTRAB
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;

BEGIN
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrh_emp_tconddiftrab WHERE (bdcodemp = NEW.bdcodemp)  AND (bdCodcol = NEW.bdcodcol) INTO vNova_Chave;
      NEW.bdchave = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM vrh_emp_tconddiftrab WHERE (bdchave = NEW.bdchave) AND (bdcodcol = NEW.bdcodcol) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrh_emp_tconddiftrab WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) INTO vNova_Chave;
           NEW.bdchave = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TDEP_BI0 FOR VRH_EMP_TDEP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodNovo INTEGER;

BEGIN
  IF ((NEW.BDCODDPN IS NULL) OR (NEW.BDCODDPN = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODDPN) + 1, 1)
       FROM vrh_emp_tdep
       WHERE BDCODEMP = NEW.BDCODEMP AND
             BDCODCOL = NEW.BDCODCOL
       INTO :vCodNovo;
       NEW.BDCODDPN = :vCodNovo;
     END

  IF (StrLen(NEW.bdcoddpn) > 2) THEN
     BEGIN
       NEW.bdcoddpn = 0;
       EXCEPTION ex_tamanhochave;
     END

  IF (NEW.bdcodtipo IS NULL) THEN
     BEGIN
       SELECT bdcodtipo FROM tipos_lancamentos_padrao WHERE bdcodtipo = 201 INTO NEW.bdcodtipo;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TDEP_BU0 FOR VRH_EMP_TDEP
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  -- Não pode mudar o tipo de cadastramento inicial
  if (old.bdcodtipo is not null) then
     new.bdcodtipo = old.bdcodtipo;
end
^


CREATE OR ALTER TRIGGER VRH_EMP_TDEP_IMG_BI0 FOR VRH_EMP_TDEP_IMG
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;
  DECLARE VARIABLE vCodImg INTEGER;
BEGIN
  IF ((NEW.bdcoddpn IS NULL) OR (NEW.bdcoddpn = 0)) THEN
     BEGIN
       SELECT MAX(bdcoddpn)
       FROM vrh_emp_tdep
       WHERE NEW.bdcodemp = bdcodemp AND
             NEW.bdcodcol = bdcodcol
       INTO :vNovoCod;

       NEW.bdcoddpn = vNovoCod;
     END

  IF ((NEW.BDFOTODEPRHNET <> '') AND (NOT NEW.BDFOTODEPRHNET IS NULL)) THEN
    BEGIN
      vCodImg = 0;
      SELECT BDCODIMG FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTODEPRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTODEPRHNET))) INTO vCodImg;
      IF (vCodImg > 0) THEN
        BEGIN
          NEW.BDFOTODEP_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTODEPRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTODEPRHNET))));
          DELETE FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTODEPRHNET);
        END
      ELSE
        NEW.BDFOTODEP_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTODEPRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTODEPRHNET))));

      NEW.BDFOTODEPRHNET = '';
    END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TDEP_IMG_BU0 FOR VRH_EMP_TDEP_IMG
ACTIVE BEFORE UPDATE POSITION 0
AS
  DECLARE VARIABLE vCodImg INTEGER;
BEGIN
  IF ((NEW.BDFOTODEPRHNET <> '') AND (NOT NEW.BDFOTODEPRHNET IS NULL)) THEN
    BEGIN
      vCodImg = 0;
      SELECT BDCODIMG FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTODEPRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTODEPRHNET))) INTO vCodImg;
      IF (vCodImg > 0) THEN
        BEGIN
          NEW.BDFOTODEP_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTODEPRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTODEPRHNET))));
          DELETE FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTODEPRHNET);
        END
      ELSE
        NEW.BDFOTODEP_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTODEPRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTODEPRHNET))));

      NEW.BDFOTODEPRHNET = '';
    END

END
^

CREATE OR ALTER TRIGGER VRH_EMP_TESTABILIDADE_BI0 FOR VRH_EMP_TESTABILIDADE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;

BEGIN
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrh_emp_testabilidade WHERE (bdcodemp = NEW.bdcodemp)  AND (bdCodcol = NEW.bdcodcol) INTO vNova_Chave;
      NEW.bdchave = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM vrh_emp_testabilidade WHERE (bdchave = NEW.bdchave) AND (bdcodcol = NEW.bdcodcol) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrh_emp_testabilidade WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) INTO vNova_Chave;
           NEW.bdchave = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TFERIAS_AD0 FOR VRH_EMP_TFERIAS
ACTIVE AFTER DELETE POSITION 0
AS
  DECLARE VARIABLE wRefIni INTEGER;
  DECLARE VARIABLE vmeses INTEGER;
BEGIN
  /* Trigger text */
  DELETE FROM VRHF_EMP_TFICHAIRRF WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDCODFERFIR = OLD.BDCODFE AND BDINIPERAQUISFIR = OLD.BDINIPERAQUISFE AND BDTIPOCALCFIR IN (2, 200);
  DELETE FROM vrhf_emp_tdadoscalc_baixa WHERE bdtipocalc = 10 AND bdcodemp = OLD.bdcodemp AND bdcodcol = OLD.bdcodcol AND bdiniperaqui = OLD.bdiniperaquisfe AND bdcodfer = OLD.bdcodfe;
  DELETE FROM vrhf_emp_ta13sal WHERE bdcodemp = OLD.bdcodemp AND bdcodcol = OLD.bdcodcol AND ((bdrefa13 = OLD.bdrefinife) or (BDDATAPGTOA13 = OLD.BDDATAPAGFE)) AND bdcalcfera13 = 'TRUE';

  IF (OLD.bdinipergozofe IS NULL) THEN
     BEGIN
       wRefIni = OLD.bdrefpagabofe;
       vmeses  = 0;
     END
  ELSE
     BEGIN
       wRefIni = CAST((SUBSTRING(CAST(OLD.bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(OLD.bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
       vmeses  = DATEDIFF (MONTH, OLD.bdinipergozofe, OLD.bdfimpergozofe);
     END

  WHILE (vmeses >= 0) DO
    BEGIN
      EXECUTE PROCEDURE sp_vrh_painel_update(OLD.bdcodemp, wRefIni, '2', 'BDPERFOLHAFERIAS'); -- 2 - Excluido

      IF (MOD(wRefIni,100) = 12) THEN
         wRefIni = wRefIni + 100 - 11;
      ELSE
         wRefIni = wRefIni + 1;

      vmeses = vmeses - 1;
    END

  update VRH_EMP_TPARCELAMENTOS_ITENS set BDVALORDESC_FER = null, BDDESCCALCPAR_FER = null, BDMAXIMOPAR_FER = null where BDCODEMP = old.bdcodemp and BDCODCOL = old.bdcodcol and BDREFPI = old.bdrefinife;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TFERIAS_AI0 FOR VRH_EMP_TFERIAS
ACTIVE AFTER INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
--  execute procedure VRHF_SP_DADOS_BAIXA_CALCULO(new.bdcodemp,null,null,new.bdcodcol,10,null, null,null,new.bdiniperaquisfe,new.bdcodfe,new.bdliquido,new.bdinipergozofe,new.bdrefpagabofe);
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TFERIAS_BI0 FOR VRH_EMP_TFERIAS
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE wRefIni INTEGER;
  DECLARE VARIABLE wRefFim INTEGER;
  DECLARE VARIABLE vdata DATE;
  DECLARE VARIABLE vhora TIME;
  DECLARE VARIABLE vmeses INTEGER;
  DECLARE VARIABLE VCODUSU INTEGER; /* Augusto - 02/04/2024 - #192435 */
BEGIN
  IF (NEW.bdinipergozofe IS NULL) THEN
     BEGIN
       wRefIni = NEW.bdrefpagabofe;
       wRefFim = NEW.bdrefpagabofe;
       vmeses  = 0;
     END
  ELSE
     BEGIN
       wRefIni = CAST((SUBSTRING(CAST(NEW.bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
       wRefFim = CAST((SUBSTRING(CAST(NEW.bdfimpergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.bdfimpergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       if (coalesce(new.bdrefpagabofe, 0) > 0) then
          begin
            if (coalesce(new.bdrefpagabofe, 0) < wRefIni) then
               wRefIni = coalesce(new.bdrefpagabofe, 0);
          end

       vmeses  = DATEDIFF (MONTH, NEW.bdinipergozofe, NEW.bdfimpergozofe);
     END

  NEW.bdrefinife = wRefIni;
  NEW.bdreffimfe = wRefFim;

  SELECT CURRENT_DATE, CURRENT_TIME FROM rdb$database INTO :vdata,:vhora;

  IF (NEW.bddataprocfe IS NULL) THEN
     NEW.bddataprocfe = vdata;

  IF (NEW.bdhoraprocfe IS NULL) THEN
     NEW.bdhoraprocfe = vhora;

  if (new.bddatapagfe is not null) then
     new.bdrefpagfe = cast((SUBSTRING(CAST(new.bddatapagfe as VARCHAR(10)) from 1 for 4)||SUBSTRING(CAST(new.bddatapagfe as VARCHAR(10)) from 6 for 2)) as INTEGER);
  else
     new.bdrefpagfe = cast((SUBSTRING(CAST(new.bdinipergozofe as VARCHAR(10)) from 1 for 4)||SUBSTRING(CAST(new.bdinipergozofe as VARCHAR(10)) from 6 for 2)) as INTEGER);

  WHILE (vmeses >= 0) DO
    BEGIN
      EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, wRefIni, '1', 'BDPERFOLHAFERIAS'); -- 1 - Calculado

      IF (MOD(wRefIni,100) = 12) THEN
         wRefIni = wRefIni + 100 - 11;
      ELSE
         wRefIni = wRefIni + 1;

      vmeses = vmeses - 1;
    END
   /* Augusto - 02/04/2024 - #192435 */
  SELECT FIRST 1 BDCODUSU FROM VW_USUARIOS_SECAO INTO :VCODUSU;
  NEW.BDCODUSU = :VCODUSU;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TFERIAS_BU0 FOR VRH_EMP_TFERIAS
ACTIVE BEFORE UPDATE POSITION 0
AS
  DECLARE VARIABLE wRefIni INTEGER;
  DECLARE VARIABLE wRefFim INTEGER;
  DECLARE VARIABLE vmeses INTEGER;

BEGIN
  IF (NEW.bdinipergozofe IS NULL) THEN
     BEGIN
       wRefIni = NEW.bdrefpagabofe;
       wRefFim = NEW.bdrefpagabofe;
       vmeses  = 0;
     END
  ELSE
     BEGIN
       wRefIni = CAST((SUBSTRING(CAST(NEW.bdinipergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.bdinipergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
       wRefFim = CAST((SUBSTRING(CAST(NEW.bdfimpergozofe AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.bdfimpergozofe AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

       if (coalesce(new.bdrefpagabofe, 0) > 0) then
          begin
            if (coalesce(new.bdrefpagabofe, 0) < wRefIni) then
               wRefIni = coalesce(new.bdrefpagabofe, 0);
          end

       vmeses  = DATEDIFF (MONTH, NEW.bdinipergozofe, NEW.bdfimpergozofe);
     END

  NEW.bdrefinife = wRefIni;
  NEW.bdreffimfe = wRefFim;

  if (new.bddatapagfe is not null) then
     new.bdrefpagfe = cast((SUBSTRING(CAST(new.bddatapagfe as VARCHAR(10)) from 1 for 4)||SUBSTRING(CAST(new.bddatapagfe as VARCHAR(10)) from 6 for 2)) as INTEGER);
  else
     new.bdrefpagfe = cast((SUBSTRING(CAST(new.bdinipergozofe as VARCHAR(10)) from 1 for 4)||SUBSTRING(CAST(new.bdinipergozofe as VARCHAR(10)) from 6 for 2)) as INTEGER);

  WHILE (vmeses >= 0) DO
    BEGIN
      EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, wRefIni, '1', 'BDPERFOLHAFERIAS'); -- 1 - Calculado

      IF (MOD(wRefIni,100) = 12) THEN
         wRefIni = wRefIni + 100 - 11;
      ELSE
         wRefIni = wRefIni + 1;

      vmeses = vmeses - 1;
    END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TFERIAS_COLETIVAS_AD0 FOR VRH_EMP_TFERIAS_COLETIVAS
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  DELETE FROM vrh_emp_tferias WHERE bdcodemp = OLD.bdcodemp AND bdcodcol = OLD.bdcodcol AND BDINIPERAQUISFE = OLD.BDINIPERAQUISFE AND bdcodfe = OLD.bdcodfe;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_THIST_AUM_AD0 FOR VRH_EMP_THIST_AUM
ACTIVE AFTER DELETE POSITION 0 
AS
  DECLARE VARIABLE vContrCol INTEGER;

BEGIN
  SELECT BDCONTRCOL FROM VRH_EMP_TCOLCON WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL INTO :vContrCol;

  /* Registro alterado */
  IF (OLD.BDTIPOREGHAUM = 1) THEN
     BEGIN
       IF (:vContrCol IS NOT NULL) THEN
         BEGIN
           IF (OLD.BDSALBASEANTHAUM > 0) THEN
              BEGIN
                UPDATE OR INSERT INTO VRH_EMP_TCOLCON_DIA (BDCODEMP, BDCODCOL, BDDATACOL, BDCONTRCOL) VALUES (OLD.BDCODEMP,OLD.BDCODCOL,OLD.BDDATAHAUM,:vContrCol) MATCHING (BDCODEMP,BDCODCOL,BDDATACOL);
                UPDATE OR INSERT INTO VRH_EMP_TCOLCON_CALCDIA (BDCODEMP,BDCODCOL,BDDATACOL,BDCODMAS,BDSALBASECOL,BDCONTRCOL) VALUES (OLD.BDCODEMP,OLD.BDCODCOL,OLD.BDDATAHAUM,NULL,OLD.BDSALBASEANTHAUM,:vContrCol) MATCHING (BDCODEMP,BDCODCOL,BDDATACOL);
              END
           ELSE
              DELETE FROM VRH_EMP_TCOLCON_CALCDIA  WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDDATACOL = OLD.BDDATAHAUM;
         END
     END
  ELSE
     BEGIN
       DELETE FROM VRH_EMP_TCOLCON_DIA WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDDATACOL = OLD.BDDATAHAUM;
     END

  DELETE FROM VRH_EMP_TFOLHACOMP WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDDATAHAUMFC = OLD.BDDATAHAUM;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_THIST_AUM_BI0 FOR VRH_EMP_THIST_AUM
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vContrCol INTEGER;
  DECLARE VARIABLE vStatus INTEGER;
  DECLARE VARIABLE vCodPlaFuc INTEGER;
  DECLARE VARIABLE vCodPQua INTEGER;
  DECLARE VARIABLE vCodTFuc INTEGER;
  DECLARE VARIABLE vCodQH INTEGER;
  DECLARE VARIABLE vCodHAum INTEGER;
  DECLARE VARIABLE vHorNot INTEGER;
  DECLARE VARIABLE vDescSalVar VARCHAR(255);
  DECLARE VARIABLE vRegJorTrab INTEGER;
  DECLARE VARIABLE vTipoJornada INTEGER;
  DECLARE VARIABLE vDescTPJornada VARCHAR(100);
  DECLARE VARIABLE vTemAumento Integer;

BEGIN
  if (coalesce(new.bdnaomexedia, 0) = 0) then
     begin
       SELECT BDCONTRCOL FROM VRH_EMP_TCOLCON WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL INTO :vContrCol;
       UPDATE OR INSERT INTO VRH_EMP_TCOLCON_DIA (BDCODEMP,BDCODCOL,BDDATACOL,BDCONTRCOL) VALUES (NEW.BDCODEMP,NEW.BDCODCOL,NEW.BDDATAHAUM,:vContrCol) MATCHING (BDCODEMP,BDCODCOL,BDDATACOL);
     end

  SELECT BDCODCOL FROM VRH_EMP_TCOLCON_CALCDIA WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL AND BDDATACOL = NEW.BDDATAHAUM AND BDDATAEFEITO = NEW.bddataefeitohaum INTO :vStatus;

  if (coalesce(new.bdnaomexedia, 0) = 0) then
     SELECT first 1 BDDESCSALVAR FROM VRH_EMP_TCOLCON_CALCDIA WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL AND BDDATACOL <= NEW.BDDATAHAUM order by BDDATACOL DESC INTO :vDescSalVar;

  IF (NEW.BDTIPOREGHAUM IS NULL) THEN
     BEGIN
       /* ? um registro novo */
       IF (:vStatus IS NULL OR (:vStatus = 0)) THEN
          NEW.BDTIPOREGHAUM = 0;
       ELSE  /* Esta alterando um registro de sal?rio que j? existe */
          NEW.BDTIPOREGHAUM = 1;
     END

  IF (NEW.BDCODHAUM IS NULL OR NEW.BDCODHAUM = 0) THEN
     BEGIN
       SELECT FIRST 1 COALESCE((BDCODHAUM + 1), 1) FROM VRH_EMP_THIST_AUM
       WHERE BDCODEMP = NEW.BDCODEMP AND
             BDCODCOL = NEW.BDCODCOL AND
             BDDATAHAUM = NEW.BDDATAHAUM
       ORDER BY BDCODHAUM DESC	 
       INTO  vCodHAum;
       
       if (vCodHAum is null) then
           vCodHAum = 1;
 
       NEW.BDCODHAUM = vCodHAum;
     END

    if (coalesce(new.bdnaomexedia, 0) = 0) then
       begin
         SELECT FIRST 1 X.BDCODCOL
         FROM VRH_EMP_TCOLCON_CALCDIA X
         WHERE X.BDCODEMP = NEW.BDCODEMP and X.BDCODCOL = NEW.BDCODCOL and X.BDDATACOL = NEW.BDDATAHAUM and X.BDDATAEFEITO = NEW.BDDATAEFEITOHAUM
         INTO :vTemAumento;

         vTemAumento = COALESCE(vTemAumento, 0);

         IF (vTemAumento > 0) then
            begin
              -- Allmir 15/03/2022 Em algumas situações não alterava o dado diário devido as validações do motivo do aumento
              UPDATE OR INSERT INTO VRH_EMP_TCOLCON_CALCDIA (BDCODEMP,BDCODCOL,BDDATACOL,BDCODMAS,BDSALBASECOL,BDCONTRCOL,BDDESCSALVAR,BDDATAEFEITO)
              VALUES (NEW.BDCODEMP,NEW.BDCODCOL,NEW.BDDATAHAUM,NEW.BDCODMAS,NEW.BDSALBASEHAUM,:vContrCol,:vDescSalvar,NEW.BDDATAEFEITOHAUM)
              MATCHING (BDCODEMP,BDCODCOL,BDDATACOL,BDDATAEFEITO);
            end
         else
            begin
              UPDATE OR INSERT INTO VRH_EMP_TCOLCON_CALCDIA (BDCODEMP,BDCODCOL,BDDATACOL,BDCODMAS,BDSALBASECOL,BDCONTRCOL,BDDESCSALVAR,BDDATAEFEITO)
              VALUES (NEW.BDCODEMP,NEW.BDCODCOL,NEW.BDDATAHAUM,NEW.BDCODMAS,NEW.BDSALBASEHAUM,:vContrCol,:vDescSalvar,NEW.BDDATAEFEITOHAUM)
              MATCHING (BDCODEMP,BDCODCOL,BDDATACOL,BDDATAEFEITO);
            end

         SELECT FIRST 1 X.BDCODPLAFUC, X.BDCODTFUC, X.BDCODQH, X.BDCODPQUA, X.BDREGJORTRAB, X.BDTIPOJORNADA, X.BDDESCTPJORNADA, X.BDINDHORARIONOT
         FROM VRH_EMP_TCOL_VINCDIA X
         WHERE X.BDCODEMP = NEW.bdcodemp AND X.BDCODCOL = NEW.bdcodcol AND X.BDDATACOL <= NEW.bddatahaum ORDER BY X.BDDATACOL DESC
         INTO :vCodPlaFuc, :vCodTFuc, :vCodQH, :vCodPQua, :vRegJorTrab, :vTipoJornada, :vDescTPJornada, :vHorNot;
        
         IF (vcodplafuc IS NULL AND vcodtfuc IS NULL AND vcodqh IS NULL AND vcodpqua IS NULL) THEN
            BEGIN
              SELECT FIRST 1 X.BDCODPLAFUC, X.BDCODTFUC, X.BDCODQH, X.BDCODPQUA, X.BDREGJORTRAB, X.BDTIPOJORNADA, X.BDDESCTPJORNADA, X.BDINDHORARIONOT
              FROM VRH_EMP_TCOL_VINCDIA X
              WHERE X.BDCODEMP = NEW.bdcodemp AND X.BDCODCOL = NEW.bdcodcol AND X.BDREFCOL <= EXTRACT(YEAR FROM NEW.BDDATAHAUM) * 100 + EXTRACT(MONTH FROM NEW.BDDATAHAUM)
                ORDER BY X.BDDATACOL DESC INTO :vCodPlaFuc, :vCodTFuc, :vCodQH, :vCodPQua, :vRegJorTrab, :vTipoJornada, :vDescTPJornada, :vHorNot;
            END
        
         UPDATE OR INSERT INTO VRH_EMP_TCOL_VINCDIA (BDCODEMP,BDCODCOL,BDDATACOL,BDCODPLAFUC,BDCODTFUC,BDCODPQUA,BDCODQH,BDCONTRCOL,BDREGJORTRAB,BDTIPOJORNADA,BDDESCTPJORNADA, BDINDHORARIONOT)
         VALUES (NEW.BDCODEMP, NEW.BDCODCOL, NEW.BDDATAHAUM, :vCodPlaFuc, :vCodTFuc, :vCodPQua, :vCodQH, :vContrCol, :vRegJorTrab, :vTipoJornada, :vDescTPJornada, :vHorNot)
         MATCHING (BDCODEMP,BDCODCOL,BDDATACOL);
       end
END
^

CREATE OR ALTER TRIGGER VRH_EMP_THIST_AUMHE_AD0 FOR VRH_EMP_THIST_AUMHE
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Registro foi alterado */
  IF (OLD.BDTIPOREGHAUMHE = 1) THEN
     UPDATE OR INSERT INTO VRH_EMP_TCOL_SHE (BDCODEMPSHE,BDCODEMP,BDCODCOL,BDCODSHE,BDDATASHE,BDCODMAS,BDSALSHE,BDDATAEFEITOHE) VALUES (OLD.BDCODEMP,OLD.BDCODEMP,OLD.BDCODCOL,OLD.BDCODSHE,OLD.BDDATAHAUMHE,OLD.BDCODMAS,OLD.BDSALBASEANTHAUMHE,OLD.BDDATAEFEITOHAUMHE) MATCHING (BDCODEMPSHE,BDCODCOL,BDCODEMP,BDDATASHE,BDCODSHE);
  ELSE
     DELETE FROM VRH_EMP_TCOL_SHE WHERE BDCODEMPSHE = OLD.BDCODEMP AND BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDCODSHE = OLD.BDCODSHE AND BDDATASHE = OLD.BDDATAHAUMHE;

  DELETE FROM VRH_EMP_TFOLHACOMP WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDDATAHAUMFC = OLD.BDDATAHAUMHE;
END
^

--Sol. 18901 - Bruno L. R. - 10/07/2017 - Implementado auto-incremento para o campo BDCODHAUMHE
CREATE OR ALTER TRIGGER VRH_EMP_THIST_AUMHE_BI0 FOR VRH_EMP_THIST_AUMHE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vStatus INTEGER;
  DECLARE VARIABLE vCodHAumHe INTEGER;

BEGIN
  SELECT BDCODCOL FROM VRH_EMP_TCOL_SHE WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL AND BDDATASHE = NEW.BDDATAHAUMHE AND BDCODSHE = NEW.bdcodshe and BDDATAEFEITOHE = NEW.BDDATAEFEITOHAUMHE INTO :vStatus;

  IF (NEW.BDTIPOREGHAUMHE IS NULL) THEN
     BEGIN
       /* É um registro novo */
       IF (:vStatus IS NULL OR (:vStatus = 0)) THEN
          NEW.BDTIPOREGHAUMHE = 0;
       ELSE  /* Esta alterando um registro de salário que já existe */
          NEW.BDTIPOREGHAUMHE = 1;
     END

  --Sol. 18901 - Bruno L. R. - 05/07/2017
  IF (NEW.BDCODHAUMHE IS NULL OR NEW.BDCODHAUMHE = 0) THEN
     BEGIN
       SELECT COALESCE((MAX(BDCODHAUMHE) + 1), 1) FROM VRH_EMP_THIST_AUMHE INTO vCodHAumHe;
       NEW.BDCODHAUMHE = vCodHAumHe;
     END
  --Sol. 18901 - Bruno L. R. - 05/07/2017

  UPDATE OR INSERT INTO VRH_EMP_TCOL_SHE (BDCODEMPSHE,BDCODEMP,BDCODCOL,BDCODSHE,BDDATASHE,BDCODMAS,BDSALSHE,BDDATAEFEITOHE) VALUES (NEW.BDCODEMP,NEW.BDCODEMP,NEW.BDCODCOL,NEW.BDCODSHE,NEW.BDDATAHAUMHE,NEW.BDCODMAS,NEW.BDSALBASEHAUMHE,NEW.BDDATAEFEITOHAUMHE) MATCHING (BDCODEMPSHE,BDCODCOL,BDCODEMP,BDCODSHE,BDDATASHE,BDDATAEFEITOHE);
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_SHE_BI0 FOR VRH_EMP_TCOL_SHE
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (NEW.BDDATAEFEITOHE is null) then
    BEGIN
      NEW.BDDATAEFEITOHE = NEW.BDDATASHE;
    END
  new.bdrefshe = cast((substring(CAST(new.bddatashe as varchar(10)) from 1 for 4)||substring(CAST(new.bddatashe as varchar(10)) from 6 for 2)) as integer);
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_SHE_BU0 FOR VRH_EMP_TCOL_SHE
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  if ((OLD.BDDATAEFEITOHE is null) and (NEW.BDDATAEFEITOHE is null)) then
    begin
        NEW.BDDATAEFEITOHE = NEW.BDDATASHE;
    end
  new.bdrefshe = cast((substring(CAST(new.bddatashe as varchar(10)) from 1 for 4)||substring(CAST(new.bddatashe as varchar(10)) from 6 for 2)) as integer);
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TLANFATRISCO_BI0 FOR VRH_EMP_TLANFATRISCO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNova_Chave INTEGER;

BEGIN
  IF ((NEW.bdcodseq IS NULL) OR (NEW.bdcodseq = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodseq)+1), 1) FROM vrh_emp_tlanfatrisco WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) AND (bdchave = NEW.bdchave) INTO vNova_Chave;
      NEW.bdcodseq = vNova_Chave;
    END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TLANFATRISCO_EPI_BI0 FOR VRH_EMP_TLANFATRISCO_EPI
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNova_Chave INTEGER;

BEGIN
  IF ((NEW.bdcodepi IS NULL) OR (NEW.bdcodepi = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodseq)+1), 1) FROM vrh_emp_tlanfatrisco_epi
      WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) AND (bdchave = NEW.bdchave) AND (bdcodseq = NEW.bdcodseq)
      INTO vNova_Chave;
      NEW.bdcodepi = vNova_Chave;
    END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TLANMENSAGENS_BI0 FOR VRH_EMP_TLANMENSAGENS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdchavelan IS NULL) OR (NEW.bdchavelan = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchavelan)+1), 1) FROM vrh_emp_tlanmensagens WHERE bdcodemp = NEW.bdcodemp AND
                                                   bdcodcol = NEW.bdcodcol INTO vNova_Chave;
      NEW.bdchavelan = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdchavelan FROM vrh_emp_tlanmensagens
       WHERE (bdchavelan = NEW.bdchavelan) AND (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchavelan)+1), 1) FROM vrh_emp_tlanmensagens
           WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) INTO vNova_Chave;
           NEW.bdchavelan = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TMANDCIPA_BI0 FOR VRH_EMP_TMANDCIPA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCIPA IS NULL) OR (NEW.BDCODCIPA = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODCIPA) + 1, 1) FROM VRH_EMP_TMANDCIPA WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL INTO :vNovoCod;
       NEW.BDCODCIPA = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TNOTIFICACOES_AD0 FOR VRH_EMP_TNOTIFICACOES
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  DELETE FROM vrh_emp_tfaltas_itens WHERE BDCODEMP = OLD.bdcodemp AND BDCODCOL = OLD.bdcodcol AND BDCODNOTIF = OLD.bdcodnotif;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TNOTIFICACOES_BI0 FOR VRH_EMP_TNOTIFICACOES
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;
  DECLARE VARIABLE vref INTEGER;
  DECLARE VARIABLE vdata DATE;

BEGIN
  IF (NEW.bdcodnotif IS NULL OR (NEW.bdcodnotif = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODNOTIF) + 1, 1) FROM vrh_emp_tnotificacoes WHERE BDCODEMP = NEW.bdcodemp INTO :vcod;
       NEW.bdcodnotif = :vcod;
     END

             -- suspensão
  IF (NEW.bdtiponotif = 1 AND UPPER(NEW.bdfaltasnotif) = 'TRUE') THEN
     BEGIN
       vcod = 1;
       vdata = NEW.bddatasuspnotif;
       WHILE (vcod <= NEW.bddiasnotif) DO
         BEGIN
           vref = CAST((SUBSTRING(CAST(vdata AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(vdata AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
           UPDATE OR INSERT INTO vrh_emp_tfaltas (BDCODEMP,BDCODCOL,BDREFFAL) VALUES (NEW.bdcodemp, NEW.bdcodcol, :vref) MATCHING (BDCODEMP,BDCODCOL,BDREFFAL);
           UPDATE OR INSERT INTO vrh_emp_tfaltas_itens (BDCODEMP,BDCODCOL,BDREFFAL,BDDATAFAL,BDTIPOFAL,BDHORASFAL,BDTIPODSRFAL,BDTIPODESCFAL,BDCODTIPO,BDCODNOTIF) VALUES
                   (NEW.bdcodemp, NEW.bdcodcol, :vref, :vdata, 2, 1, 0, 0, 201, NEW.bdcodnotif) MATCHING (BDCODEMP,BDCODCOL,BDREFFAL,BDDATAFAL);
           vcod = vcod + 1;
           vdata = vdata + 1;
         END
     END

END
^

CREATE OR ALTER TRIGGER VRH_EMP_TNOTIFICACOES_BU0 FOR VRH_EMP_TNOTIFICACOES
ACTIVE BEFORE UPDATE POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;
  DECLARE VARIABLE vref INTEGER;
  DECLARE VARIABLE vdata DATE;

BEGIN
  DELETE FROM vrh_emp_tfaltas_itens WHERE BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol AND BDCODNOTIF = NEW.bdcodnotif;

  IF (UPPER(NEW.bdfaltasnotif) = 'TRUE') THEN
     BEGIN
       vcod = 1;
       vdata = NEW.bddatasuspnotif;
       WHILE (vcod <= NEW.bddiasnotif) DO
         BEGIN
           vref = CAST((SUBSTRING(CAST(vdata AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(vdata AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
           UPDATE OR INSERT INTO vrh_emp_tfaltas (BDCODEMP,BDCODCOL,BDREFFAL) VALUES (NEW.bdcodemp, NEW.bdcodcol, :vref) MATCHING (BDCODEMP,BDCODCOL,BDREFFAL);
           UPDATE OR INSERT INTO vrh_emp_tfaltas_itens (BDCODEMP,BDCODCOL,BDREFFAL,BDDATAFAL,BDTIPOFAL,BDHORASFAL,BDTIPODSRFAL,BDTIPODESCFAL,BDCODTIPO,BDCODNOTIF) VALUES
                   (NEW.bdcodemp, NEW.bdcodcol, :vref, :vdata, 2, 1, 0, 0, 201, NEW.bdcodnotif) MATCHING (BDCODEMP,BDCODCOL,BDREFFAL,BDDATAFAL);
           vcod = vcod + 1;
           vdata = vdata + 1;
         END
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TNOTIFICACOES_TE_BI0 FOR VRH_EMP_TNOTIFICACOES_TE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF (NEW.bdcod_te IS NULL OR (NEW.bdcod_te = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCOD_TE) + 1, 1) FROM vrh_emp_tnotificacoes_te WHERE BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol AND BDCODNOTIF = NEW.bdcodnotif INTO :vcod;
       NEW.bdcod_te = :vcod;
     END

END
^

CREATE OR ALTER TRIGGER VRH_EMP_TPARCELAMENTOS_BI0 FOR VRH_EMP_TPARCELAMENTOS
ACTIVE BEFORE INSERT POSITION 0 
AS
DECLARE VARIABLE novocod INTEGER;
BEGIN
  IF ((NEW.bdCODPARC IS NULL) OR (NEW.BDCODPARC = 0))  THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODPARC) + 1, 1)
       FROM VRH_EMP_TPARCELAMENTOS WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL INTO novocod;
       NEW.BDCODPARC = novocod;
     END

  if (NEW.bdeconsignado) then
     NEW.bdreadonly = 'TRUE';
  ELSE
     NEW.bdreadonly = 'FALSE';
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TPBM_REC_BI0 FOR VRH_EMP_TPBM_REC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdchave),0) + 1 FROM vrh_emp_tpbm_rec WHERE bdcodemp = NEW.bdcodemp AND bdref = NEW.bdref INTO vcodigo;
       NEW.bdchave = vcodigo;
     END
  ELSE
     BEGIN
       SELECT COALESCE(bdchave,0) FROM vrh_emp_tpbm_rec WHERE bdcodemp = NEW.bdcodemp AND bdref = NEW.bdref AND bdchave = NEW.bdchave INTO vcodigo;

       IF (vcodigo <> 0) THEN
          BEGIN
            SELECT COALESCE(MAX(bdchave),0) + 1 FROM vrh_emp_tpbm_rec WHERE bdcodemp = NEW.bdcodemp AND bdref = NEW.bdref INTO vcodigo;
            NEW.bdchave = vcodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TPROCESSO_DIRF_BI0 FOR VRH_EMP_TPROCESSO_DIRF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF (NEW.bdcodpdirf IS NULL OR (NEW.bdcodpdirf = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodpdirf) + 1, 1) FROM VRH_EMP_TPROCESSO_DIRF INTO :vcod;
       NEW.bdcodpdirf = :vcod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TPROCESSO_DIRF_ITEM_BI0 FOR VRH_EMP_TPROCESSO_DIRF_ITEM
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF (NEW.bdcoditempdirf IS NULL OR (NEW.bdcoditempdirf = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdCODITEMPDIRF) + 1, 1) FROM VRH_EMP_TPROCESSO_DIRF_ITEM WHERE BDCODPDIRF = NEW.BDCODPDIRF INTO :vcod;
       NEW.bdcoditempdirf = :vcod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TPROCESSOS_AU0 FOR VRH_EMP_TPROCESSOS
ACTIVE AFTER UPDATE POSITION 0 
AS
BEGIN
  IF (NEW.bdtipoprocesso NOT IN (3,4,5,6)) THEN
     BEGIN
       DELETE FROM VRH_EMP_TPROCESSOS_VERBAS WHERE BDCODEMP = NEW.BDCODEMP AND BDCODPROCESSO = NEW.BDCODPROCESSO;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TPROCESSOS_BI0 FOR VRH_EMP_TPROCESSOS
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodprocesso IS NULL) OR (NEW.bdcodprocesso = 0)) THEN
     SELECT COALESCE(MAX(bdcodprocesso),0)+1 FROM vrh_emp_tprocessos WHERE bdcodemp = NEW.bdcodemp INTO NEW.bdcodprocesso;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRDE_BI0 FOR VRH_EMP_TRDE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNCod INTEGER;
BEGIN
  IF (NEW.BDCODRDE IS NULL OR (NEW.BDCODRDE = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODRDE), 0) + 1 FROM VRH_EMP_TRDE WHERE BDCODEMP = NEW.BDCODEMP INTO :vNCod;

       NEW.BDCODRDE = :vNCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRDE_SECAO_2_BI0 FOR VRH_EMP_TRDE_SECAO_2
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNCod INTEGER;
BEGIN
  IF (NEW.BDCODRDE IS NULL OR (NEW.BDCODRDE = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODRDE), 1) FROM VRH_EMP_TRDE WHERE BDCODEMP = NEW.BDCODEMP INTO :vNCod;
       NEW.BDCODRDE = :vNCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRDE_SECAO_3_BI0 FOR VRH_EMP_TRDE_SECAO_3
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNCod INTEGER;
BEGIN
  IF (NEW.BDCODRDE IS NULL OR (NEW.BDCODRDE = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODRDE), 1) FROM VRH_EMP_TRDE WHERE BDCODEMP = NEW.BDCODEMP INTO :vNCod;
       NEW.BDCODRDE = :vNCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRDE_SECAO_31_DE_BI0 FOR VRH_EMP_TRDE_SECAO_31_DE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNCod INTEGER;
BEGIN
  IF (NEW.BDCODRDE IS NULL OR (NEW.BDCODRDE = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODRDE), 1) FROM VRH_EMP_TRDE WHERE BDCODEMP = NEW.BDCODEMP INTO :vNCod;
       NEW.BDCODRDE = :vNCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRDE_SECAO_31_PARA_BI0 FOR VRH_EMP_TRDE_SECAO_31_PARA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNCod INTEGER;
BEGIN
  IF (NEW.BDCODRDE IS NULL OR (NEW.BDCODRDE = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODRDE), 1) FROM VRH_EMP_TRDE WHERE BDCODEMP = NEW.BDCODEMP INTO :vNCod;
       NEW.BDCODRDE = :vNCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRDE_SECAO_4_BI0 FOR VRH_EMP_TRDE_SECAO_4
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNCod INTEGER;
BEGIN
  IF (NEW.BDCODRDE IS NULL OR (NEW.BDCODRDE = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODRDE), 1) FROM VRH_EMP_TRDE WHERE BDCODEMP = NEW.BDCODEMP INTO :vNCod;
       NEW.BDCODRDE = :vNCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRDE_SECAO_5_BI0 FOR VRH_EMP_TRDE_SECAO_5
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNCod INTEGER;
BEGIN
  IF (NEW.BDCODRDE IS NULL OR (NEW.BDCODRDE = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODRDE), 1) FROM VRH_EMP_TRDE WHERE BDCODEMP = NEW.BDCODEMP INTO :vNCod;
       NEW.BDCODRDE = :vNCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRDT_BI0 FOR VRH_EMP_TRDT
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNCod INTEGER;

BEGIN
  IF (NEW.BDCODRDT IS NULL OR (NEW.BDCODRDT = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODRDT), 0) + 1 FROM VRH_EMP_TRDT WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL INTO :vNCod;

       NEW.BDCODRDT = :vNCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRDT_SECAO_3_BI0 FOR VRH_EMP_TRDT_SECAO_3
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNCod INTEGER;
BEGIN
  IF (NEW.BDCODRDT IS NULL OR (NEW.BDCODRDT = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODRDT), 1) FROM VRH_EMP_TRDT WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL INTO :vNCod;
       NEW.BDCODRDT = :vNCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRDT_SECAO_4_BI0 FOR VRH_EMP_TRDT_SECAO_4
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNCod INTEGER;
BEGIN
  IF (NEW.BDCODRDT IS NULL OR (NEW.BDCODRDT = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODRDT), 1) FROM VRH_EMP_TRDT WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL INTO :vNCod;
       NEW.BDCODRDT = :vNCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRDT_SECAO_5_BI0 FOR VRH_EMP_TRDT_SECAO_5
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNCod INTEGER;
BEGIN
  IF (NEW.BDCODRDT IS NULL OR (NEW.BDCODRDT = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODRDT), 1) FROM VRH_EMP_TRDT WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL INTO :vNCod;
       NEW.BDCODRDT = :vNCod;
     END

  IF (NEW.BDCODRDTS5 IS NULL OR (NEW.BDCODRDTS5 = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODRDTS5), 0) + 1 FROM VRH_EMP_TRDT_SECAO_5 WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL AND BDCODRDT = NEW.BDCODRDT INTO :vNCod;
       NEW.BDCODRDTS5 = :vNCod;
     END

END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRDT_SECAO_6_BI0 FOR VRH_EMP_TRDT_SECAO_6
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNCod INTEGER;
BEGIN
  IF (NEW.BDCODRDT IS NULL OR (NEW.BDCODRDT = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODRDT), 1) FROM VRH_EMP_TRDT WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL INTO :vNCod;
       NEW.BDCODRDT = :vNCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRDT_SECAO_7_BI0 FOR VRH_EMP_TRDT_SECAO_7
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNCod INTEGER;
BEGIN
  IF (NEW.BDCODRDT IS NULL OR (NEW.BDCODRDT = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODRDT), 1) FROM VRH_EMP_TRDT WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL INTO :vNCod;
       NEW.BDCODRDT = :vNCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TREEMBOLSO_BI0 FOR VRH_EMP_TREEMBOLSO
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0))  THEN
     SELECT COALESCE(MAX(bdordem),0)+1 FROM vrh_emp_treembolso WHERE bdcodemp = NEW.bdcodemp AND bdcodimp = NEW.bdcodimp INTO NEW.bdordem;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRESCISAO_BI0 FOR VRH_EMP_TRESCISAO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  NEW.BDREFRESCISAO = CAST((SUBSTRING(CAST(NEW.BDDATARESCISAO AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDDATARESCISAO AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

  IF (NEW.BDDATAPAGRESCISAO IS NULL) THEN
     NEW.BDDATAPAGRESCISAO = NEW.BDDATARESCISAO;

  NEW.BDREFPAGRESCISAO = CAST((SUBSTRING(CAST(NEW.BDDATAPAGRESCISAO AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDDATAPAGRESCISAO AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

  IF (NEW.bdprojecaoaviso IS NOT NULL) THEN
     NEW.BDREFPROJECAOAVISO = CAST((SUBSTRING(CAST(NEW.BDPROJECAOAVISO AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDPROJECAOAVISO AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
  ELSE
     NEW.BDREFPROJECAOAVISO = NULL;

  if (trim(new.bdcalcfgtsmesant) = '') then
     new.bdcalcfgtsmesant = null;

END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRESCISAO_AI0 FOR VRH_EMP_TRESCISAO
ACTIVE AFTER INSERT POSITION 0
AS
  declare variable ws VARCHAR(300);
  declare variable wcat INTEGER;
  declare variable wcatES INTEGER;
  declare variable whora TIME;
begin
  ws = 'select first 1 BDCATEGORIACOL, BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS where BDCODEMP = '||new.bdcodemp||' and BDCODCOL = '||new.bdcodcol||' and BDREFCOL <= '||new.bdrefrescisao||' order by BDREFCOL DESC';
  wcat = null;
  wcatES = null;
  execute statement ws into :wcat, :wcatES;

  -- intermitente. Deve verificar se tem convocação lançada, senão deve gerar uma convocação "fantasma"
  if (coalesce(wcat, 0) = 4 and coalesce(wcatES, 0) = 111) then
     begin
       wcat = null;
       select first 1 BDCODCONTTI from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and
          ((SUBSTRING(CAST(BDDATAINISERVTI AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISERVTI AS VARCHAR(10)) FROM 6 FOR 2) = new.bdrefrescisao) or
           (SUBSTRING(CAST(BDDATAFIMSERVTI AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSERVTI AS VARCHAR(10)) FROM 6 FOR 2) = new.bdrefrescisao)) and
          upper(coalesce(BDCONVRESCTI, 'FALSE')) = 'TRUE'
       into :wcat;

       -- Não existe contrato no mês
       if (coalesce(wcat, 0) <= 0) then
          begin
            insert into VRH_EMP_TINTERMITENTE(BDCODEMP, BDCODCOL, BDCODCONTTI, BDDESCCONTRATOTI, BDDATAINISERVTI, BDDATAFIMSERVTI, BDDATAPAGTI, BDAPENASRESCISAO, BDCONVRESCTI)
            values (new.bdcodemp, new.bdcodcol, 999999, 'RESCISÃO INTERMITENTE', new.bddatarescisao, new.bddatarescisao, new.bddatapagrescisao, 'TRUE', 'TRUE');

            select CURRENT_TIME from RDB$DATABASE into :whora;

            insert into VRH_EMP_TINTERMITENTE_ACEI(BDCODEMP,BDCODCOL,BDCODCONTTI,BDDATAACEITETI,BDHORAACEITETI,BDCOMUNICACEITETI,BDSTATUSACEITETI)
            values (new.bdcodemp, new.bdcodcol, 999999, new.bddatarescisao, :whora, 'RESCISÃO INTERMITENTE', 2);
          end
     end
     
  --Excluir os alertas de vencimento de colaboradores demitidos
  delete from VRH_BASE_ALERTA_VENC where BDCODEMP = new.bdcodemp and BDCOLCON = new.bdcodcol;

  wcat = 0;
  SELECT BDGRRFPRES FROM VRH_BASE_TPREPRESC WHERE BDCODPRES = new.bdcodpres into wcat;
  if (COALESCE(wcat, 0) > 0) then
     begin
       wcat = 0;
       select SUBSTRING(CAST(BDDATAFGTSDIGITAL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFGTSDIGITAL AS VARCHAR(10)) FROM 6 FOR 2) from VRH_ESOCIAL_TFASEAMENTO WHERE BDCODEMP = new.BDCODEMP into wcat;

       -- Ao fazer um novo lançamento de rescisão faz o disparo para rodar o processo de exportação de grrf automaticamente
       if ((COALESCE(wcat,0) > 0) and (new.bdrefrescisao >= wcat)) then
          UPDATE OR INSERT INTO TTHREAD (BDPARAM,BDVALORINT) VALUES ('TTHREADIMP_'||new.bdcodemp||'_'||new.bdcodcol||'_'||new.bdrefrescisao||'_40', 0) MATCHING (BDPARAM);
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRESCISAO_BU0 FOR VRH_EMP_TRESCISAO
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  NEW.BDREFRESCISAO = CAST((SUBSTRING(CAST(NEW.BDDATARESCISAO AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDDATARESCISAO AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

  IF (NEW.BDDATAPAGRESCISAO IS NULL) THEN
     NEW.BDDATAPAGRESCISAO = NEW.BDDATARESCISAO;

  NEW.BDREFPAGRESCISAO = CAST((SUBSTRING(CAST(NEW.BDDATAPAGRESCISAO AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDDATAPAGRESCISAO AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

  IF (NEW.bdprojecaoaviso IS NOT NULL) THEN
     NEW.BDREFPROJECAOAVISO = CAST((SUBSTRING(CAST(NEW.BDPROJECAOAVISO AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDPROJECAOAVISO AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
  ELSE
     NEW.BDREFPROJECAOAVISO = NULL;

  if (trim(new.bdcalcfgtsmesant) = '') then
     new.bdcalcfgtsmesant = null;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRESCISAO_PREVIA_BI0 FOR VRH_EMP_TRESCISAO_PREVIA
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  NEW.BDREFRESCISAOPREV = CAST((SUBSTRING(CAST(NEW.BDDATARESCISAOPREV AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDDATARESCISAOPREV AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
  IF (NEW.BDDATAPAGRESCISAOPREV  IS NULL) THEN
     NEW.BDDATAPAGRESCISAOPREV = NEW.BDDATARESCISAOPREV;

  NEW.BDREFPAGRESCISAOPREV = CAST((SUBSTRING(CAST(NEW.BDDATAPAGRESCISAOPREV AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDDATAPAGRESCISAOPREV AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

  IF (NEW.bdprojecaoavisoprev IS NOT NULL) THEN
     NEW.BDREFPROJECAOAVISOPREV = CAST((SUBSTRING(CAST(NEW.BDPROJECAOAVISOPREV AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDPROJECAOAVISOPREV AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
  ELSE
     NEW.BDREFPROJECAOAVISOPREV = NULL;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TRESCISAO_PREVIA_BU0 FOR VRH_EMP_TRESCISAO_PREVIA
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  NEW.BDREFRESCISAOPREV = CAST((SUBSTRING(CAST(NEW.BDDATARESCISAOPREV AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDDATARESCISAOPREV AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
  NEW.BDREFPAGRESCISAOPREV = CAST((SUBSTRING(CAST(NEW.BDDATAPAGRESCISAOPREV AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDDATAPAGRESCISAOPREV AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

  IF (NEW.bdprojecaoavisoprev IS NOT NULL) THEN
     NEW.BDREFPROJECAOAVISOPREV = CAST((SUBSTRING(CAST(NEW.BDPROJECAOAVISOPREV AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDPROJECAOAVISOPREV AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
  ELSE
     NEW.BDREFPROJECAOAVISOPREV = NULL;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TTRANSCOL_BI0 FOR VRH_EMP_TTRANSCOL
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE vCodTrans INTEGER;
BEGIN
  NEW.BDREFTRF = CAST((SUBSTRING(CAST(NEW.BDDATATRF AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.BDDATATRF AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

  IF ((NEW.BDCODTRANS IS NULL) OR (NEW.BDCODTRANS = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(BDCODTRANS) + 1, 1) FROM VRH_EMP_TTRANSCOL INTO :vCodTrans;
      NEW.BDCODTRANS = vCodTrans;
    END

  if (new.bdcodemporig is not null and new.bdcodcolorig is not null and new.bdcodempdest is not null and new.bdcodcoldest is not null) then
     begin
       if (new.bdcodemporig = new.bdcodempdest and new.bdcodcolorig = new.bdcodcoldest) then
          exception EX_TRANSFERENCIA;
     end

END
^


CREATE OR ALTER TRIGGER VRH_EMP_TTRANSCOL_BU0 FOR VRH_EMP_TTRANSCOL
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  NEW.bdreftrf = CAST((SUBSTRING(CAST(NEW.bddatatrf AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.bddatatrf AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

  if (new.bdcodemporig is not null and new.bdcodcolorig is not null and new.bdcodempdest is not null and new.bdcodcoldest is not null) then
     begin
       if (new.bdcodemporig = new.bdcodempdest and new.bdcodcolorig = new.bdcodcoldest) then
          exception EX_TRANSFERENCIA;
     end

END
^

CREATE OR ALTER TRIGGER VRH_EMP_TTRANSCOL_AD0 FOR VRH_EMP_TTRANSCOL
ACTIVE AFTER DELETE POSITION 0
AS
  DECLARE VARIABLE vref INTEGER;
BEGIN
  DELETE FROM VRHF_EMP_TFOLHAAVULSA WHERE BDCODEMP = OLD.BDCODEMPDEST AND BDCODCOL = OLD.BDCODCOLDEST;
  DELETE FROM VRH_EMP_TCOLCON WHERE BDCODEMP = OLD.BDCODEMPDEST AND BDCODCOL = OLD.BDCODCOLDEST;
  DELETE FROM VRH_EMP_TRESCISAO WHERE BDCODEMP = OLD.BDCODEMPORIG AND BDCODCOL = OLD.BDCODCOLORIG;

  vref = CAST((SUBSTRING(CAST((OLD.bddatatrf - 1) AS VARCHAR(10)) FROM 1 FOR 4)|| SUBSTRING(CAST((OLD.bddatatrf - 1) AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

  IF (CAST((SUBSTRING(vref FROM 5 FOR 2)) AS INTEGER) = EXTRACT(MONTH FROM OLD.bddatatrf)) THEN
     BEGIN
       DELETE FROM VRHF_EMP_TFOLHANORMAL WHERE BDCODEMP = OLD.BDCODEMPORIG AND BDCODCOL = OLD.BDCODCOLORIG AND BDREFFN = :vref;
       DELETE FROM VRHF_EMP_TFOLHATOMADOR WHERE BDCODEMP = OLD.BDCODEMPORIG AND BDCODCOL = OLD.BDCODCOLORIG AND BDREFTOMADOR = :vref;
     END
END
^

CREATE OR ALTER TRIGGER VRH_FUNCOES_TFUC_BI0 FOR VRH_FUNCOES_TFUC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODTFUC IS NULL) OR (NEW.BDCODTFUC = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODTFUC) + 1, 1)
       FROM vrh_funcoes_tfuc
       WHERE BDCODPLAFUC = NEW.BDCODPLAFUC
       INTO :vNovoCod;

       NEW.BDCODTFUC = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_LISTACOL_IMPOSTO_BI0 FOR VRH_LISTACOL_IMPOSTO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodempaux IS NULL) OR (NEW.bdcodempaux = 0)) THEN
     NEW.bdcodempaux = NEW.bdcodemp;

  IF ((NEW.bdchavelistacol IS NULL) OR (NEW.bdchavelistacol = 0))  THEN
     BEGIN
       SELECT COALESCE(MAX(BDCHAVELISTACOL)+1,1) FROM vrh_listacol_imposto WHERE NEW.bdcodemp = bdcodemp INTO NEW.bdchavelistacol;
     END
  ELSE
     BEGIN
       SELECT BDCHAVELISTACOL FROM vrh_listacol_imposto WHERE NEW.bdcodemp = bdcodemp AND
                                                              NEW.bdchavelistacol = bdchavelistacol
                                                              INTO vcodigo;

       IF (vcodigo <> 0) THEN
          SELECT COALESCE(MAX(BDCHAVELISTACOL)+1,1) FROM vrh_listacol_imposto WHERE NEW.bdcodemp = bdcodemp
                                                                                    INTO NEW.bdchavelistacol;
     END
END
^

CREATE OR ALTER TRIGGER VRH_RHNET_TARQUIVO_BI0 FOR VRH_RHNET_TARQUIVO
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wcod INTEGER;
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodarq IS NULL) or (NEW.bdcodarq = 0))  THEN
     BEGIN
       wcod = gen_id(GEN_RHNETSOCIAL, 1);
       NEW.bdcodarq = :wcod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_RHNET_TREGISTRO_BI0 FOR VRH_RHNET_TREGISTRO
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.BDCODREG IS NULL) OR (NEW.BDCODREG = 0))  THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodreg),0) + 1 FROM vrh_rhnet_tregistro WHERE bdcodarq = NEW.bdcodarq INTO NEW.bdcodreg;
     END

  IF ((NEW.BDCODTIPOIMPORTACAO IS NULL) OR (NEW.BDCODTIPOIMPORTACAO = 0)) THEN
    BEGIN
      NEW.BDCODTIPOIMPORTACAO = 253;
    END
END
^

CREATE OR ALTER TRIGGER VRH_SN_CONF_RH_BI0 FOR VRH_SN_CONF_RH
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     SELECT COALESCE(MAX(bdchave),0)+1 FROM vrh_sn_conf_rh INTO NEW.bdchave;
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_CALC_TERC_AD0 FOR VRHF_BASE_CALC_TERC
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdtipocalc = 1 AND bdcodemp = OLD.bdcodemp AND bdcodserv = OLD.bdcodserv AND bdcodter = OLD.bdcodter;

  DELETE FROM VRHF_EMP_MV_AUT_CALC WHERE BDTIPOCALC = 4 AND bdcodemp = OLD.bdcodemp AND BDCODCONTRATO = OLD.bdcodserv AND BDCODTER = OLD.bdcodter;
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_CALC_TERC_AI0 FOR VRHF_BASE_CALC_TERC
ACTIVE AFTER INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
--  execute procedure VRHF_SP_DADOS_BAIXA_CALCULO(new.bdcodemp,new.bdcodter,new.bdcodserv,null,1,null, null,null,null,null,new.bdliquido,null,null);
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_CALC_TERC_BI0 FOR VRHF_BASE_CALC_TERC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vref  VARCHAR(6);
  DECLARE VARIABLE VCODUSU INTEGER; /* Augusto - 02/04/2024 - #192435 */

BEGIN
  vref = SUBSTRING(CAST(NEW.bddataserv AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.bddataserv AS VARCHAR(10)) FROM 6 FOR 2);

  NEW.bdrefinssserv = CAST(vref AS INTEGER);

  vref = SUBSTRING(CAST(NEW.bddatapagserv AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.bddatapagserv AS VARCHAR(10)) FROM 6 FOR 2);

  NEW.bdrefirserv = CAST(vref AS INTEGER);

  /* Augusto - 02/04/2024 - #192435 */
  SELECT FIRST 1 BDCODUSU FROM VW_USUARIOS_SECAO INTO :VCODUSU;
  NEW.BDCODUSU = :VCODUSU;
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_CALC_TERC_BU0 FOR VRHF_BASE_CALC_TERC
ACTIVE BEFORE UPDATE POSITION 0 
AS
  DECLARE VARIABLE vref  VARCHAR(6);

BEGIN
  vref = SUBSTRING(CAST(NEW.bddataserv AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.bddataserv AS VARCHAR(10)) FROM 6 FOR 2);

  NEW.bdrefinssserv = CAST(vref AS INTEGER);

  vref = SUBSTRING(CAST(NEW.bddatapagserv AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.bddatapagserv AS VARCHAR(10)) FROM 6 FOR 2);

  NEW.bdrefirserv = CAST(vref AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TCOLCON_ESMOV_BI0 FOR VRHF_BASE_TCOLCON_ESMOV
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNCod INTEGER;

BEGIN
  IF (NEW.BDORDEMMS IS NULL OR (NEW.BDORDEMMS = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDORDEMMS), 0) + 1 FROM VRHF_BASE_TCOLCON_ESMOV WHERE BDCOMPMS = NEW.BDCOMPMS INTO :vNCod;
       NEW.BDORDEMMS = :vNCod;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TCOLCON_EXPSEFIP_BI0 FOR VRHF_BASE_TCOLCON_EXPSEFIP
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNCod INTEGER;

BEGIN
  IF (NEW.BDORDEMECOL IS NULL OR (NEW.BDORDEMECOL = 0)) THEN
     BEGIN
       SELECT MAX(BDORDEMECOL) FROM VRHF_BASE_TCOLCON_EXPSEFIP WHERE BDCOMPECOL = NEW.BDCOMPECOL INTO :VNCod;

       IF (:vncod IS NULL) THEN
         vncod = 0;

       NEW.BDORDEMECOL = :vNCod + 1;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TCONVREFEICAO_REF_BI0 FOR VRHF_BASE_TCONVREFEICAO_REF
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF (COALESCE(NEW.bdcodconvref,0) = 0) THEN
     BEGIN
       SELECT MAX(bdcodconvref) FROM vrhf_base_tconvrefeicao INTO NEW.bdcodconvref;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TEMP_EXPSEFIP_BI0 FOR VRHF_BASE_TEMP_EXPSEFIP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNCod INTEGER;

BEGIN
  IF (NEW.BDORDEMEEMP IS NULL OR (NEW.BDORDEMEEMP = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDORDEMEEMP), 0) + 1 FROM VRHF_BASE_TEMP_EXPSEFIP WHERE BDCOMPEEMP = NEW.BDCOMPEEMP /*and BDCODEMP = new.BDCODEMP*/ INTO :vNCod;
       NEW.BDORDEMEEMP = :vNCod;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TEMPCALC_BI0 FOR VRHF_BASE_TEMPCALC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END

  IF (NEW.bdtipcalcfercolinf IS NULL) THEN
     NEW.bdtipcalcfercolinf = 2;

  IF (NEW.bdtipcalcfercolsup IS NULL) THEN
     NEW.bdtipcalcfercolsup = 4;
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TEMPDIRF_BI0 FOR VRHF_BASE_TEMPDIRF
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TEMPESOCIAL_BI0 FOR VRHF_BASE_TEMPESOCIAL
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TEMPGPS_BI0 FOR VRHF_BASE_TEMPGPS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TEMPGRCS_BI0 FOR VRHF_BASE_TEMPGRCS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TEMPPAR_BI0 FOR VRHF_BASE_TEMPPAR
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TEMPPROP_BI0 FOR VRHF_BASE_TEMPPROP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TEMPRAIS_BI0 FOR VRHF_BASE_TEMPRAIS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TEMPSEFIP_BI0 FOR VRHF_BASE_TEMPSEFIP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TEMPVINC_BI0 FOR VRHF_BASE_TEMPVINC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo; --#alt:16965 - A empresa de backup não pode interferir na sequência dos códigos das empresas novas. Ana - 09/02/2018

            NEW.bdcodemp = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TFERISIND_BI0 FOR VRHF_BASE_TFERISIND
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vMes VARCHAR(2);
  DECLARE VARIABLE vDia VARCHAR(2);

BEGIN
  IF (STRLEN(CAST(NEW.BDDIAMESFES AS VARCHAR(4))) < 4) THEN
     BEGIN
       vDia = '0'||SUBSTRING(CAST(NEW.BDDIAMESFES AS VARCHAR(4)) FROM 1 FOR 1);
       vMes = SUBSTRING(CAST(NEW.BDDIAMESFES AS VARCHAR(4)) FROM 2 FOR 2);
     END
  ELSE
     BEGIN
       vDia = SUBSTRING(CAST(NEW.BDDIAMESFES AS VARCHAR(4)) FROM 1 FOR 2);
       vMes = SUBSTRING(CAST(NEW.BDDIAMESFES AS VARCHAR(4)) FROM 3 FOR 2);
     END

  NEW.BDMESDIAFES = vMes||vDia;
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TFERISIND_BU0 FOR VRHF_BASE_TFERISIND
ACTIVE BEFORE UPDATE POSITION 0 
AS
  DECLARE VARIABLE vMes VARCHAR(2);
  DECLARE VARIABLE vDia VARCHAR(2);

BEGIN
  IF (STRLEN(CAST(NEW.BDDIAMESFES AS VARCHAR(4))) < 4) THEN
     BEGIN
       vDia = '0'||SUBSTRING(CAST(NEW.BDDIAMESFES AS VARCHAR(4)) FROM 1 FOR 1);
       vMes = SUBSTRING(CAST(NEW.BDDIAMESFES AS VARCHAR(4)) FROM 2 FOR 2);
     END
  ELSE
     BEGIN
       vDia = SUBSTRING(CAST(NEW.BDDIAMESFES AS VARCHAR(4)) FROM 1 FOR 2);
       vMes = SUBSTRING(CAST(NEW.BDDIAMESFES AS VARCHAR(4)) FROM 3 FOR 2);
     END

  NEW.BDMESDIAFES = vMes||vDia;
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TITINERARIO_REF_BI0 FOR VRHF_BASE_TITINERARIO_REF
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF (COALESCE(NEW.bdcoditi,0) = 0) THEN
     BEGIN
       SELECT MAX(bdcoditi) FROM vrhf_base_titinerarios INTO NEW.bdcoditi;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TITINERARIOS_BI0 FOR VRHF_BASE_TITINERARIOS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodNovo INTEGER;

BEGIN
  IF ((NEW.BDCODITI IS NULL) OR (NEW.BDCODITI = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODITI) + 1, 1)
       FROM vrhf_base_titinerarios
       INTO :vCodNovo;

       NEW.BDCODITI = :vCodNovo;

     END
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TSINDPATRONAL_BI0 FOR VRHF_BASE_TSINDPATRONAL
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodNovo INTEGER;

BEGIN
  IF ((NEW.BDCODSINPAT IS NULL) OR (NEW.BDCODSINPAT = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODSINPAT) + 1, 1)
       FROM vrhf_base_tsindpatronal
       INTO :vCodNovo;

       NEW.BDCODSINPAT = :vCodNovo;

     END
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TVERBASEMP_BI0 FOR VRHF_BASE_TVERBASEMP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;
  DECLARE VARIABLE vClass VARCHAR(9);

BEGIN
  IF ((NEW.bdcodigoveremp IS NULL) OR (NEW.bdcodigoveremp = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODIGOVEREMP) + 1, 1)
       FROM VRHF_BASE_TVERBASEMP
       WHERE BDCODEMP = NEW.bdcodemp
       INTO :vNovoCod;

       NEW.bdcodigoveremp = :vNovoCod;
     END

  IF (NEW.bdclassifveremp IS NULL) THEN
    BEGIN
      SELECT SUBSTRING(X.BDCLAVER FROM 1 FOR 9)
      FROM VRH_BASE_TVERBAS X
      WHERE X.BDCODVER = NEW.BDCODVER
      INTO :vClass;

      NEW.bdclassifveremp = :vClass;
    END
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TVERBASEMP_BU0 FOR VRHF_BASE_TVERBASEMP
ACTIVE BEFORE UPDATE POSITION 0 
AS
  DECLARE VARIABLE vClass VARCHAR(9);

BEGIN
  SELECT SUBSTRING(X.BDCLAVER FROM 1 FOR 9)
  FROM VRH_BASE_TVERBAS X
  WHERE X.BDCODVER = NEW.BDCODVER
  INTO :vClass;
  
  NEW.BDCLASSIFVEREMP = :vClass;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_DARF_PIS_IND_BI0 FOR VRHF_EMP_DARF_PIS_IND
ACTIVE BEFORE INSERT POSITION 0 
AS
DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF (NEW.bdcodempcol IS NULL) THEN
     NEW.bdcodempcol = NEW.bdcodemp;

  /* Trigger text */
  IF ((NEW.bdchavedarfpisind IS NULL) OR (NEW.bdchavedarfpisind = 0))  THEN
     BEGIN
       SELECT COALESCE(MAX(x.bdchavedarfpisind)+1,0) FROM VRHF_EMP_DARF_PIS_IND x WHERE x.bdcodemp = NEW.bdcodemp INTO NEW.bdchavedarfpisind;
     END
  ELSE
     BEGIN
       SELECT x.bdchavedarfpisind FROM VRHF_EMP_DARF_PIS_IND x WHERE x.bdcodemp = NEW.bdcodemp AND x.bdchavedarfpisind = NEW.bdchavedarfpisind INTO vCodigo;

       IF (vcodigo <> 0) THEN
          BEGIN
            SELECT COALESCE(MAX(x.bdchavedarfpisind)+1,0) FROM VRHF_EMP_DARF_PIS_IND x WHERE x.bdcodemp = NEW.bdcodemp INTO NEW.bdchavedarfpisind;
          END
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_DARF_TNFCONT_BI0 FOR VRHF_EMP_DARF_TNFCONT
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vcod INTEGER;

BEGIN
  IF ((NEW.BDCHAVENFCONT IS NULL) OR (NEW.BDCHAVENFCONT  = 0) ) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCHAVENFCONT),0)+1 FROM VRHF_EMP_DARF_TNFCONT WHERE BDCODEMP = NEW.bdcodemp INTO :vcod;
       NEW.BDCHAVENFCONT = :vcod;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_GPS_IND_BI0 FOR VRHF_EMP_GPS_IND
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF (NEW.bdcodempcol IS NULL) THEN
     NEW.bdcodempcol = NEW.bdcodemp;

  if (coalesce(new.bdchave, 0) <= 0) then
  SELECT (x.BDRESULT+1) FROM maxsci('bdchave','BDCODEMP,BDCHAVEDARF,BDCHAVE',
                                  'BDCODEMP = '||NEW.bdcodemp||' and BDCHAVEDARF = '||NEW.BDCHAVEDARF,
                                  'vrhf_emp_gps_ind') x INTO NEW.bdchave;

  if (coalesce(new.bdchavedarfgpsind, 0) <= 0) then
  SELECT (x.BDRESULT+1) FROM maxsci('BDCHAVEDARFGPSIND','BDCODEMP,BDCHAVEDARFGPSIND',
                                  'BDCODEMP = '||NEW.bdcodemp,
                                  'vrhf_emp_gps_ind') x INTO NEW.BDCHAVEDARFGPSIND;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_T13SAL_AD0 FOR VRHF_EMP_T13SAL
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  DELETE FROM VRHF_EMP_TFICHAIRRF WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFIR = OLD.BDREF13 AND BDTIPOCALCFIR = 132;
  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdtipocalc = 2 AND bdcodemp = OLD.bdcodemp AND bdcodcol = OLD.bdcodcol AND bdreferencia = OLD.bdref13;

  EXECUTE PROCEDURE sp_vrh_painel_update(OLD.bdcodemp, OLD.bdref13, '2', 'BDPERFOLHA13SALARIO'); -- 2 - Excluido
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_T13SAL_AI0 FOR VRHF_EMP_T13SAL
ACTIVE AFTER INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
--  execute procedure VRHF_SP_DADOS_BAIXA_CALCULO(new.bdcodemp,null,null,new.bdcodcol,2,new.bdref13, null,null,null,null,new.bdliquido,null,null);
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_T13SAL_AU0 FOR VRHF_EMP_T13SAL
ACTIVE AFTER UPDATE POSITION 0 
AS
BEGIN
  IF (OLD.bdfgts13 <> NEW.bdfgts13) THEN
     BEGIN
       EXECUTE PROCEDURE sp_atu_fgts_cont_13(NEW.bdfgts13,NEW.bdcodemp,NEW.bdcodcol,NEW.bdref13,OLD.bdfgts13);
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_T13SAL_BI0 FOR VRHF_EMP_T13SAL
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
  DECLARE VARIABLE vdata DATE;
  DECLARE VARIABLE vhora TIME;
  DECLARE VARIABLE VCODUSU INTEGER; /* Augusto - 02/04/2024 - #192435 */

BEGIN
  SELECT CURRENT_DATE, CURRENT_TIME FROM rdb$database INTO :vdata, :vhora;

  IF (NEW.bddataproc13 IS NULL) THEN
     NEW.bddataproc13 = vdata;

  IF (NEW.bdhoraproc13 IS NULL) THEN
     NEW.bdhoraproc13 = vhora;

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdref13, '1', 'BDPERFOLHA13SALARIO'); -- 1 - Calculado

   /* AUGUSTO - 02/04/2024 - #192435 */
  SELECT FIRST 1 BDCODUSU FROM VW_USUARIOS_SECAO INTO :VCODUSU;
  NEW.BDCODUSU = :VCODUSU;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TA13SAL_AD0 FOR VRHF_EMP_TA13SAL
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdtipocalc = 3 AND bdcodemp = OLD.bdcodemp AND bdcodcol = OLD.bdcodcol AND bdreferencia = OLD.bdrefa13;

  EXECUTE PROCEDURE sp_vrh_painel_update(OLD.bdcodemp, OLD.bdrefa13, '2', 'BDPERFOLHAAD13SALARIO'); -- 2 - Excluido
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TA13SAL_AU0 FOR VRHF_EMP_TA13SAL
ACTIVE AFTER UPDATE POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF (OLD.bdfgtsa13 <> NEW.bdfgtsa13) THEN
     BEGIN
       EXECUTE PROCEDURE sp_atu_fgts_cont_a13(NEW.bdfgtsa13,NEW.bdcodemp,NEW.bdcodcol,NEW.bdrefa13,OLD.bdfgtsa13);
     END

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdrefa13, '1', 'BDPERFOLHAAD13SALARIO'); -- 1 - Calculado
END
^

-- 125979 - Raphael Teodoro - 15/01/2020
CREATE OR ALTER TRIGGER VRHF_EMP_TA13SAL_BI0 FOR VRHF_EMP_TA13SAL
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE VCODUSU INTEGER; /* Augusto - 02/04/2024 - #192435 */
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdrefa13, '1', 'BDPERFOLHAAD13SALARIO'); -- 1 - Calculado

  /* Augusto - 02/04/2024 - #192435 */
  SELECT FIRST 1 BDCODUSU FROM VW_USUARIOS_SECAO INTO :VCODUSU;
  NEW.BDCODUSU = :VCODUSU;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TADSAL_AD0 FOR VRHF_EMP_TADSAL
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  /* Trigger text */
  DELETE FROM VRHF_EMP_TFICHAIRRF WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDDATAFIR = OLD.BDDATAAD AND BDTIPOCALCFIR = 4;
  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdtipocalc = 4 AND bdcodemp = OLD.bdcodemp AND bdcodcol = OLD.bdcodcol AND bddata = OLD.bddataad;

  EXECUTE PROCEDURE sp_vrh_painel_update(OLD.bdcodemp, OLD.bdrefad, '2', 'BDPERFOLHAADSALARIO'); -- 2 - Excluido

  update VRH_EMP_TPARCELAMENTOS_ITENS set BDVALORDESC_ADS = null, BDDESCCALCPAR_ADS = null, BDMAXIMOPAR_ADS = null, BDDESCCALCPROPPAR_ADS = null where BDCODEMP = old.bdcodemp and BDCODCOL = old.bdcodcol and BDREFPI = old.bdrefad;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TADSAL_AI0 FOR VRHF_EMP_TADSAL
ACTIVE AFTER INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
--  execute procedure VRHF_SP_DADOS_BAIXA_CALCULO(new.bdcodemp,null,null,new.bdcodcol,4,NULL, new.bddataad,null,null,null,new.bdliquido,null,null);
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TADSAL_BI0 FOR VRHF_EMP_TADSAL
ACTIVE BEFORE INSERT OR UPDATE POSITION 0 
AS
  DECLARE VARIABLE vdata DATE;
  DECLARE VARIABLE vhora TIME;
  DECLARE VARIABLE VCODUSU INTEGER; /* Augusto - 02/04/2024 - #192435 */
BEGIN
  NEW.BDREFAD = CAST((SUBSTRING(CAST(NEW.BDDATAAD AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.BDDATAAD AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

  NEW.BDDATAIRRFESOCIAL = NEW.bddataad;
  NEW.BDREFIRRFESOCIAL = NEW.bdrefad;

  SELECT CURRENT_DATE, CURRENT_TIME FROM rdb$database INTO :vdata, :vhora;

  IF (NEW.bddataprocad IS NULL) THEN
     NEW.bddataprocad = vdata;

  IF (NEW.bdhoraprocad IS NULL) THEN
     NEW.bdhoraprocad = vhora;

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdrefad, '1', 'BDPERFOLHAADSALARIO'); -- 1 - Calculado

  /* Augusto - 02/04/2024 - #192435 */
  SELECT FIRST 1 BDCODUSU FROM VW_USUARIOS_SECAO INTO :VCODUSU;
  NEW.BDCODUSU = :VCODUSU;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TC13SAL_AD0 FOR VRHF_EMP_TC13SAL
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  /* Trigger text */
  DELETE FROM VRHF_EMP_TFICHAIRRF WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFIR = OLD.BDREFC13 AND BDTIPOCALCFIR = 133;
  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdtipocalc = 5 AND bdcodemp = OLD.bdcodemp AND
                                                                bdcodcol = OLD.bdcodcol AND
                                                                bdreferencia = OLD.bdref13 AND
                                                                bdrefcomp = OLD.bdrefc13;

  EXECUTE PROCEDURE sp_vrh_painel_update(OLD.bdcodemp, OLD.bdrefc13, '2', 'BDPERFOLHACOMP13SALARIO'); -- 2 - Excluido
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TC13SAL_AI0 FOR VRHF_EMP_TC13SAL
ACTIVE AFTER INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
--  execute procedure VRHF_SP_DADOS_BAIXA_CALCULO(new.bdcodemp,null,null,new.bdcodcol,5,new.bdref13, null,new.bdrefc13,null,null,new.bdliquido,null,null);
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TC13SAL_AU0 FOR VRHF_EMP_TC13SAL
ACTIVE AFTER UPDATE POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF (OLD.bdfgtsc13 <> NEW.bdfgtsc13) THEN
     BEGIN
       EXECUTE PROCEDURE sp_atu_fgts_cont_c13(NEW.bdfgtsc13,NEW.bdcodemp,NEW.bdcodcol,NEW.bdref13,NEW.bdrefc13,OLD.bdfgtsc13);
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TC13SAL_BI0 FOR VRHF_EMP_TC13SAL
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
  DECLARE VARIABLE vdata DATE;
  DECLARE VARIABLE vhora TIME;
  DECLARE VARIABLE VCODUSU INTEGER; /* Augusto - 02/04/2024 - #192435 */
BEGIN
  SELECT CURRENT_DATE, CURRENT_TIME FROM rdb$database INTO :vdata, :vhora;

  IF (NEW.bddataprocc13 IS NULL) THEN
     NEW.bddataprocc13 = vdata;

  IF (NEW.bdhoraprocc13 IS NULL) THEN
     NEW.bdhoraprocc13 = vhora;

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdrefc13, '1', 'BDPERFOLHACOMP13SALARIO'); -- 1 - Calculado

  /* Augusto - 02/04/2024 - #192435 */
  SELECT FIRST 1 BDCODUSU FROM VW_USUARIOS_SECAO INTO :VCODUSU;
  NEW.BDCODUSU = :VCODUSU;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TCOL_ANO_BI0 FOR VRHF_EMP_TCOL_ANO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TCOL_CALC_BI0 FOR VRHF_EMP_TCOL_CALC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TCOL_HIST_BI0 FOR VRHF_EMP_TCOL_HIST
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;
       NEW.BDCODCOL = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TCOLCON_BANCO_BI0 FOR VRHF_EMP_TCOLCON_BANCO
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TCOLCON_CALC_BI0 FOR VRHF_EMP_TCOLCON_CALC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TCOLCON_FGTSGPS_BI0 FOR VRHF_EMP_TCOLCON_FGTSGPS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TCOMPGPS_BI0 FOR VRHF_EMP_TCOMPGPS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrhf_emp_tcompgps WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.bdchave = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM vrhf_emp_tcompgps WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrhf_emp_tcompgps WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdchave = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TCON_VINC_BI0 FOR VRHF_EMP_TCON_VINC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM vrh_emp_tcolcon WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;

--       if (new.BDCONTRCOL = 1) then
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL >= 900000 into :vNovoCod;
--       else
--          select max(BDCODCOL) from vrh_emp_tcolcon where BDCODEMP = new.BDCODEMP and BDCODCOL < 900000 into :vNovoCod;

       NEW.BDCODCOL = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TDADOSCALC_BAIXA_BD0 FOR VRHF_EMP_TDADOSCALC_BAIXA
ACTIVE BEFORE DELETE POSITION 0
as
declare variable VCODIGOUSU integer;
declare variable VREFERENCIA integer;
declare variable VTIPOCALC integer;
declare variable VCODEMP integer;
begin
  select BDCODUSU from VW_VARIAVEIS_SESSAO_BANCO into VCODIGOUSU;

  select first 1 BDCODEMP, BDREFERENCIA, BDTIPOCALC, BDCODUSU
  from VRHF_EMP_TDADOSCALC_BAIXA_LX
  where BDCODEMP = old.BDCODEMP and
        BDREFERENCIA = old.BDREFERENCIA and
        BDTIPOCALC = old.BDTIPOCALC and
        BDCODUSU = old.BDCODUSU
  into VCODEMP, VREFERENCIA, VTIPOCALC, VCODIGOUSU;

  if ((:VCODEMP <> null) and
      (:VREFERENCIA <> null) and
      (:VTIPOCALC <> null)) then
  begin
    update VRHF_EMP_TDADOSCALC_BAIXA_LX
    set BDCODEMP = old.BDCODEMP,
        BDREFERENCIA = old.BDREFERENCIA,
        BDTIPOCALC = old.BDTIPOCALC,
        BDCODUSU = :VCODIGOUSU,
        BDTOTAL = old.BDLIQUIDO
    where BDCODEMP = :VCODEMP and
          BDREFERENCIA = :VREFERENCIA and
          BDTIPOCALC = :VTIPOCALC;
  end
  else
  begin
    insert into VRHF_EMP_TDADOSCALC_BAIXA_LX
    values (old.BDCODEMP, old.BDREFERENCIA, old.BDTIPOCALC, :VCODIGOUSU, old.BDLIQUIDO);
  end

  insert into TMP_VRHF_EMP_TDADOSCALC_BAIXA
  values (old.BDCODEMP, old.BDCODTER, old.BDCODSERV, old.BDCODCOL, old.BDTIPOCALC, old.BDREFERENCIA, old.BDDATA,
          old.BDREFCOMP, old.BDINIPERAQUI, old.BDCODFER, old.BDCODTCA, old.BDCODCONTTI, old.BDREFERENCIAFIM,
          old.BDCODACCONV);
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TDADOSCALC_BAIXA_BI0 FOR VRHF_EMP_TDADOSCALC_BAIXA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vCount INTEGER;
BEGIN
  /* Trigger text */
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0) ) THEN
     BEGIN
       SELECT bdresult+1 FROM maxsci('bdCHAVE','bdcodemp,bdchave','bdcodemp = '||NEW.bdcodemp,'VRHF_EMP_TDADOSCALC_BAIXA') INTO NEW.bdchave;
     END
  ELSE
     BEGIN
       SELECT COALESCE(bdchave,0) FROM vrhf_emp_tdadoscalc_baixa WHERE bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave INTO vcodigo;

       IF (vcodigo <> 0) THEN
          SELECT bdresult+1 FROM maxsci('bdCHAVE','bdcodemp,bdchave','bdcodemp = '||NEW.bdcodemp,'VRHF_EMP_TDADOSCALC_BAIXA') INTO NEW.bdchave;
     END

  IF (NEW.bdreferencia IS NULL) THEN
     BEGIN
       IF (NEW.bddata IS NOT NULL) THEN
          BEGIN
            SELECT CAST(bdaaaamm AS INTEGER) FROM aaaamm(NEW.bddata) INTO NEW.bdreferencia;
          END
       ELSE
       IF (NEW.bdinigozo IS NOT NULL) THEN
          BEGIN
            SELECT CAST(bdaaaamm AS INTEGER) FROM aaaamm(NEW.bdinigozo) INTO NEW.bdreferencia;
          END
       ELSE
       IF (NEW.bdrefabono IS NOT NULL) THEN
          BEGIN
            NEW.bdreferencia = NEW.bdrefabono;
          END
     END

  IF (NEW.bdtipocalc IN (6,7)) THEN
     NEW.bdordemcalc = 1;
  ELSE
  IF (NEW.bdtipocalc IN (8,9, 16)) THEN
     NEW.bdordemcalc = 2;
  ELSE
  IF (NEW.bdtipocalc IN (1)) THEN
     NEW.bdordemcalc = 3;
  ELSE
  IF (NEW.bdtipocalc IN (4)) THEN
     NEW.bdordemcalc = 4;
  ELSE
  IF (NEW.bdtipocalc IN (3)) THEN
     NEW.bdordemcalc = 5;
  ELSE
  IF (NEW.bdtipocalc IN (2)) THEN
     NEW.bdordemcalc = 6;
  ELSE
  IF (NEW.bdtipocalc IN (5)) THEN
     NEW.bdordemcalc = 7;
  ELSE
     NEW.bdordemcalc = NEW.bdtipocalc;

  select count(*)
  from TMP_VRHF_EMP_TDADOSCALC_BAIXA
  where (BDCODEMP is null or BDCODEMP = new.BDCODEMP) and
        (BDCODTER is null or BDCODTER = new.BDCODTER) and
        (BDCODSERV is null or BDCODSERV = new.BDCODSERV) and
        (BDCODCOL is null or BDCODCOL = new.BDCODCOL) and
        (BDTIPOCALC is null or BDTIPOCALC = new.BDTIPOCALC) and
        (BDREFERENCIA is null or BDREFERENCIA = new.BDREFERENCIA) and
        (BDDATA is null or BDDATA = new.BDDATA) and
        (BDREFCOMP is null or BDREFCOMP = new.BDREFCOMP) and
        (BDINIPERAQUI is null or BDINIPERAQUI = new.BDINIPERAQUI) and
        (BDCODFER is null or BDCODFER = new.BDCODFER) and
        (BDCODTCA is null or BDCODTCA = new.BDCODTCA) and
        (BDCODCONTTI is null or BDCODCONTTI = new.BDCODCONTTI) and
        (BDREFERENCIAFIM is null or BDREFERENCIAFIM = new.BDREFERENCIAFIM) and
        (BDCODACCONV is null or BDCODACCONV = new.BDCODACCONV)
  into :VCOUNT;

  if (:vCount > 0) then
    begin
      new.bdrecalc = TRUE;

      delete from TMP_VRHF_EMP_TDADOSCALC_BAIXA
      where (BDCODEMP is null or BDCODEMP = new.BDCODEMP) and
            (BDCODTER is null or BDCODTER = new.BDCODTER) and
            (BDCODSERV is null or BDCODSERV = new.BDCODSERV) and
            (BDCODCOL is null or BDCODCOL = new.BDCODCOL) and
            (BDTIPOCALC is null or BDTIPOCALC = new.BDTIPOCALC) and
            (BDREFERENCIA is null or BDREFERENCIA = new.BDREFERENCIA) and
            (BDDATA is null or BDDATA = new.BDDATA) and
            (BDREFCOMP is null or BDREFCOMP = new.BDREFCOMP) and
            (BDINIPERAQUI is null or BDINIPERAQUI = new.BDINIPERAQUI) and
            (BDCODFER is null or BDCODFER = new.BDCODFER) and
            (BDCODTCA is null or BDCODTCA = new.BDCODTCA) and
            (BDCODCONTTI is null or BDCODCONTTI = new.BDCODCONTTI) and
            (BDREFERENCIAFIM is null or BDREFERENCIAFIM = new.BDREFERENCIAFIM) and
            (BDCODACCONV is null or BDCODACCONV = new.BDCODACCONV);
    end

  NEW.bdcodusu = CAST((TRIM(rdb$get_context('USER_SESSION', 'W_USUARIO'))) AS INTEGER);

  select BDORIGEM from SP_VRH_GET_ORIGEM_CALC into new.bdorigem;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFICHAIRRF_AD0 FOR VRHF_EMP_TFICHAIRRF
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
--  IF (OLD.bdtipocalcfir >= 9000) THEN
--     BEGIN
--       DELETE FROM VRHF_EMP_TFIPENSAO_DEP WHERE BDCODEMP = OLD.bdcodemp AND BDCODCOL = OLD.bdcodcol AND BDCOMPPEND = OLD.bdreffir AND BDTIPOPEND = OLD.bdtipocalcfir and BDCODFIR = OLD.BDCODFIR;
--     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFICHAIRRF_BI0 FOR VRHF_EMP_TFICHAIRRF
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcount INTEGER;
  DECLARE VARIABLE vi INTEGER;
  DECLARE VARIABLE vben INTEGER;
  DECLARE VARIABLE vtot NUMERIC(18, 6);
  DECLARE VARIABLE wtipoCalculo INTEGER;
  DECLARE VARIABLE WPOSSUITODOSPERCENTUAIS INTEGER;
  DECLARE VARIABLE WPERCDEP NUMERIC(18,2);
BEGIN
  /* Trigger text */

  IF (NEW.bdcodtca IS NULL) THEN
     NEW.bdcodtca = 0;

  IF ((NEW.BDCODFIR IS NULL) OR (NEW.BDCODFIR = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODFIR) + 1, 1) FROM VRHF_EMP_TFICHAIRRF WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL INTO :vi;
       NEW.BDCODFIR = vi;
     END

  IF (NEW.bdcodtipo IS NULL) THEN
    BEGIN
      SELECT bdcodtipo FROM tipos_lancamentos_padrao WHERE bdcodtipo = 201 INTO NEW.bdcodtipo;
    END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFICHAIRRF_AI0 FOR VRHF_EMP_TFICHAIRRF
ACTIVE AFTER INSERT POSITION 0
AS
  DECLARE VARIABLE vcount INTEGER;
  DECLARE VARIABLE vi INTEGER;
  DECLARE VARIABLE vben INTEGER;
  DECLARE VARIABLE vtot NUMERIC(18, 6);
  DECLARE VARIABLE wtipoCalculo INTEGER;
  DECLARE VARIABLE WPOSSUITODOSPERCENTUAIS INTEGER;
  DECLARE VARIABLE WPERCDEP NUMERIC(18,2);
  DECLARE VARIABLE WPERCDEPTOTAL NUMERIC(18,2);
  DECLARE VARIABLE WVALORPENSAO NUMERIC(18,2);
  declare variable wcountb integer;
  declare variable wdif numeric(18,2);
begin
  /* Trigger text */
  IF (NEW.bdtipocalcfir >= 9000 AND NEW.bdpenalimfir > 0) THEN
     BEGIN
       DELETE FROM VRHF_EMP_TFIPENSAO_DEP WHERE BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol AND BDCOMPPEND = NEW.bdreffir and BDCODFIR = NEW.BDCODFIR;
       SELECT COUNT(*) FROM VRH_EMP_TCOLCON_BENEF WHERE BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol INTO :vcount;
       vi = 1;
       vtot = 0;
       wcountb = 0;
       wdif = 0;

       if (NEW.bdtipocalcfir = 9000) then           -- Folha normal IMPORTACAO
          wtipocalculo = 1;                        -- Folha normal
       else
       if ((NEW.bdtipocalcfir = 9001) or (NEW.bdtipocalcfir = 9002)             -- Folha normal rescisão IMPORTACAO
           or (NEW.bdtipocalcfir = 9011) or (NEW.bdtipocalcfir = 9012))  then   -- Folha complementar rescisão IMPORTACAO
          wtipocalculo = 9;                         -- Rescisão
       else if (NEW.bdtipocalcfir = 9010) then      -- Folha complementar IMPORTACAO
          wtipocalculo = 8;                         -- Folha complementar
       else if (NEW.bdtipocalcfir = 9020) then      -- Ad. Sal. IMPORTACAO
          wtipocalculo = 2;                         -- Ad. Sal.
       else if (NEW.bdtipocalcfir = 9030) then      -- Férias IMPORTACAO
          wtipocalculo = 6;                         -- Férias
       else if (NEW.bdtipocalcfir = 9099) then      -- Ad. 13 IMPORTACAO
          wtipocalculo = 3;                         -- Ad. 13
       else if (NEW.bdtipocalcfir = 9100) then      -- 13 IMPORTACAO
          wtipocalculo = 4;                         -- 13
       else if (NEW.bdtipocalcfir = 9110) then      -- Comp. 13 IMPORTACAO
          wtipocalculo = 5;                         -- Comp. 13
       else if (NEW.bdtipocalcfir = 9500) then      -- Folha avulsa IMPORTACAO
          wtipocalculo = 7;                         -- Folha avulsa

       WPOSSUITODOSPERCENTUAIS = 0;
       SELECT COUNT(*), SUM(BDPERCDEPP) FROM VRH_EMP_TDEP_PENSAO
       WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL AND BDCODCTP = :wtipocalculo AND
             (BDREFDEPP <= NEW.BDREFFIR AND ((COALESCE(BDREFFIMDEPP, 0) = 0) or (BDREFFIMDEPP >= NEW.BDREFFIR))) AND
             COALESCE(BDPERCDEPP, 0) > 0
       INTO :WPOSSUITODOSPERCENTUAIS, :WPERCDEPTOTAL;

       FOR SELECT BDCODBENEF FROM VRH_EMP_TCOLCON_BENEF WHERE BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol INTO :vben DO
       BEGIN
         wcountb = wcountb + 1;
         IF (WPOSSUITODOSPERCENTUAIS = vcount) THEN
            BEGIN
              SELECT BDPERCDEPP FROM VRH_EMP_TDEP_PENSAO
              WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL AND BDCODDPN = :VBEN AND BDCODCTP = :wtipocalculo AND
                    (BDREFDEPP <= NEW.BDREFFIR AND ((COALESCE(BDREFFIMDEPP, 0) = 0) or (BDREFFIMDEPP >= NEW.BDREFFIR)))
              INTO :WPERCDEP;

              IF (vi = vcount) THEN
                UPDATE OR INSERT  INTO VRHF_EMP_TFIPENSAO_DEP (BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDREFPAGPEND,BDREFPEND,BDREFAUXPEND,BDVALPEND,BDTIPOPEND,BDCODFIR,BDFICHA)
                VALUES (NEW.bdcodemp, NEW.bdcodcol, :vben, NEW.bdreffir, NEW.bdrefirfir, 0, 0, NEW.bdpenalimfir - :vtot, NEW.bdtipocalcfir, NEW.BDCODFIR, TRUE)
                MATCHING(BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDTIPOPEND,BDCODFIR);
              ELSE
                BEGIN
                  WVALORPENSAO = (NEW.bdpenalimfir / :vcount) ;

                  vtot = vtot + WVALORPENSAO;
                  if ((wcountb = vcount) and (vtot < NEW.bdpenalimfir)) then
                    begin
                      wdif = NEW.bdpenalimfir - vtot;
                      wvalorpensao = wvalorpensao + wdif;
                    end

                  UPDATE OR INSERT  INTO VRHF_EMP_TFIPENSAO_DEP (BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDREFPAGPEND,BDREFPEND,BDREFAUXPEND,BDVALPEND,BDTIPOPEND,BDCODFIR,BDFICHA)
                  VALUES (NEW.bdcodemp, NEW.bdcodcol, :vben, NEW.bdreffir, NEW.bdrefirfir, 0, 0, :WVALORPENSAO, NEW.bdtipocalcfir, NEW.BDCODFIR, TRUE)
                  MATCHING(BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDTIPOPEND,BDCODFIR);
                END
            END
         ELSE
         IF (vi = vcount) THEN
            UPDATE OR INSERT  INTO VRHF_EMP_TFIPENSAO_DEP (BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDREFPAGPEND,BDREFPEND,BDREFAUXPEND,BDVALPEND,BDTIPOPEND,BDCODFIR,BDFICHA)
            VALUES (NEW.bdcodemp, NEW.bdcodcol, :vben, NEW.bdreffir, NEW.bdrefirfir, 0, 0, NEW.bdpenalimfir - :vtot, NEW.bdtipocalcfir, NEW.BDCODFIR, TRUE)
            MATCHING(BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDTIPOPEND,BDCODFIR);
         ELSE
            BEGIN
              vtot = vtot + NEW.bdpenalimfir / :vcount;
              UPDATE OR INSERT  INTO VRHF_EMP_TFIPENSAO_DEP (BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDREFPAGPEND,BDREFPEND,BDREFAUXPEND,BDVALPEND,BDTIPOPEND,BDCODFIR,BDFICHA)
              VALUES (NEW.bdcodemp, NEW.bdcodcol, :vben, NEW.bdreffir, NEW.bdrefirfir, 0, 0, NEW.bdpenalimfir / :vcount, NEW.bdtipocalcfir, NEW.BDCODFIR, TRUE)
              MATCHING(BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDTIPOPEND,BDCODFIR);
            END
       END
     END
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFICHAIRRF_BU0 FOR VRHF_EMP_TFICHAIRRF
ACTIVE BEFORE UPDATE POSITION 0
AS
  DECLARE VARIABLE vcount INTEGER;
  DECLARE VARIABLE vi INTEGER;
  DECLARE VARIABLE vben INTEGER;
  DECLARE VARIABLE vtot NUMERIC(18, 6);
  DECLARE VARIABLE wtipoCalculo INTEGER;
  DECLARE VARIABLE WPOSSUITODOSPERCENTUAIS INTEGER;
  DECLARE VARIABLE WPERCDEP NUMERIC(18,2);
  DECLARE VARIABLE WTOTALDEPPENSAO NUMERIC(18,6);
  DECLARE VARIABLE WPERCDEPTOTAL NUMERIC(18,2);
  DECLARE VARIABLE WVALORPENSAO NUMERIC(18,2);
  declare variable wcodtipo integer;
  declare variable WCOUNTB INTEGER;
  declare variable WDIF NUMERIC(18,2);
BEGIN

  IF (((new.bdcodtipo IS NULL) or (new.bdcodtipo <> 201)) or ((old.bdcodtipo is null) or (OLD.bdcodtipo <> 201)))  THEN
    BEGIN
      SELECT bdcodtipo FROM tipos_lancamentos_padrao WHERE bdcodtipo = 201 INTO WCODTIPO;
      NEW.BDCODTIPO = wcodtipo;
    END

  IF (NEW.bdpenalimfir = 0) THEN
     BEGIN
  IF (OLD.bdtipocalcfir >= 9000) THEN
     BEGIN
            DELETE FROM VRHF_EMP_TFIPENSAO_DEP WHERE BDCODEMP = OLD.bdcodemp AND BDCODCOL = OLD.bdcodcol AND BDCOMPPEND = OLD.bdreffir AND BDTIPOPEND = OLD.bdtipocalcfir and BDCODFIR = OLD.BDCODFIR;
     END
     END

  IF (NEW.bdtipocalcfir >= 9000 AND NEW.bdpenalimfir > 0) THEN
     BEGIN
       WTOTALDEPPENSAO = 0;
       SELECT SUM(BDVALPEND)
       FROM VRHF_EMP_TFIPENSAO_DEP
       WHERE BDCODEMP = NEW.BDCODEMP AND
             BDCODCOL = NEW.BDCODCOL AND
             BDCOMPPEND = NEW.BDREFFIR AND
             BDTIPOPEND = NEW.BDTIPOCALCFIR AND
             BDCODFIR = NEW.BDCODFIR
       INTO WTOTALDEPPENSAO;

       IF (COALESCE(WTOTALDEPPENSAO, 0) <> NEW.BDPENALIMFIR) THEN
          BEGIN
       SELECT COUNT(*) FROM VRH_EMP_TCOLCON_BENEF WHERE BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol INTO :vcount;
       vi = 1;
       vtot = 0;
        
             if (NEW.bdtipocalcfir = 9000) then           -- Folha normal IMPORTACAO
                wtipocalculo = 1;                         -- Folha normal
             else
             if ((NEW.bdtipocalcfir = 9001) or (NEW.bdtipocalcfir = 9002)             -- Folha normal rescisão IMPORTACAO
                 or (NEW.bdtipocalcfir = 9011) or (NEW.bdtipocalcfir = 9012))  then   -- Folha complementar rescisão IMPORTACAO
                wtipocalculo = 9;                         -- Rescisão
             else if (NEW.bdtipocalcfir = 9010) then      -- Folha complementar IMPORTACAO
                wtipocalculo = 8;                         -- Folha complementar
             else if (NEW.bdtipocalcfir = 9020) then      -- Ad. Sal. IMPORTACAO
                wtipocalculo = 2;                         -- Ad. Sal.
             else if (NEW.bdtipocalcfir = 9030) then      -- Férias IMPORTACAO
                wtipocalculo = 6;                         -- Férias
             else if (NEW.bdtipocalcfir = 9099) then      -- Ad. 13 IMPORTACAO
                wtipocalculo = 3;                         -- Ad. 13
             else if (NEW.bdtipocalcfir = 9100) then      -- 13 IMPORTACAO
                wtipocalculo = 4;                         -- 13
             else if (NEW.bdtipocalcfir = 9110) then      -- Comp. 13 IMPORTACAO
                wtipocalculo = 5;                         -- Comp. 13
             else if (NEW.bdtipocalcfir = 9500) then      -- Folha avulsa IMPORTACAO
                wtipocalculo = 7;                         -- Folha avulsa
        
             WPOSSUITODOSPERCENTUAIS = 0;
             SELECT COUNT(*), SUM(BDPERCDEPP) FROM VRH_EMP_TDEP_PENSAO
             WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL AND BDCODCTP = :wtipocalculo AND
                   (BDREFDEPP <= NEW.BDREFFIR AND ((COALESCE(BDREFFIMDEPP, 0) = 0) or (BDREFFIMDEPP >= NEW.BDREFFIR))) AND
                   COALESCE(BDPERCDEPP, 0) > 0
             INTO :WPOSSUITODOSPERCENTUAIS, :WPERCDEPTOTAL;

       WCOUNTB = 0;
       FOR SELECT BDCODBENEF FROM VRH_EMP_TCOLCON_BENEF WHERE BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol INTO :vben DO
       BEGIN
         WCOUNTB = WCOUNTB + 1;
         IF (WPOSSUITODOSPERCENTUAIS = vcount) THEN
           BEGIN
             SELECT count(*) FROM VRH_EMP_TDEP_PENSAO WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL AND BDCODDPN = :VBEN AND BDCODCTP = :wtipocalculo AND
             (BDREFDEPP <= NEW.BDREFFIR AND ((COALESCE(BDREFFIMDEPP, 0) = 0) or (BDREFFIMDEPP >= NEW.BDREFFIR)))
             INTO :WPERCDEP;

              IF (vi = vcount) THEN
                begin
                  UPDATE OR INSERT  INTO VRHF_EMP_TFIPENSAO_DEP (BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDREFPAGPEND,BDREFPEND,BDREFAUXPEND,BDVALPEND,BDTIPOPEND,BDCODFIR,BDFICHA)
                  VALUES (NEW.bdcodemp, NEW.bdcodcol, :vben, NEW.bdreffir, NEW.bdrefirfir, 0, 0, NEW.bdpenalimfir - :vtot, NEW.bdtipocalcfir, NEW.BDCODFIR, TRUE)
                  MATCHING(BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDTIPOPEND,BDCODFIR);
                end
              ELSE
                BEGIN
                   WVALORPENSAO = (NEW.bdpenalimfir / :vcount);

                   vtot = vtot + WVALORPENSAO;
                   if ((WCOUNTB = vcount) and (vtot < NEW.bdpenalimfir)) then
                    begin
                      wdif = NEW.bdpenalimfir - vtot;
                      wvalorpensao = wvalorpensao + wdif;
                    end

                   UPDATE OR INSERT  INTO VRHF_EMP_TFIPENSAO_DEP (BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDREFPAGPEND,BDREFPEND,BDREFAUXPEND,BDVALPEND,BDTIPOPEND,BDCODFIR,BDFICHA)
                   VALUES (NEW.bdcodemp, NEW.bdcodcol, :vben, NEW.bdreffir, NEW.bdrefirfir, 0, 0, :WVALORPENSAO, NEW.bdtipocalcfir, NEW.BDCODFIR, TRUE)
                   MATCHING(BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDTIPOPEND,BDCODFIR);
                END
           END
         ELSE
           BEGIN
             IF (vi = vcount) THEN
               BEGIN
                  UPDATE OR INSERT INTO VRHF_EMP_TFIPENSAO_DEP (BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDREFPAGPEND,BDREFPEND,BDREFAUXPEND,BDVALPEND,BDTIPOPEND,BDCODFIR,BDFICHA)
                  VALUES (NEW.bdcodemp, NEW.bdcodcol, :vben, NEW.bdreffir, NEW.bdrefirfir, 0, 0, NEW.bdpenalimfir - :vtot, NEW.bdtipocalcfir, NEW.BDCODFIR, TRUE)
                  MATCHING(BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDTIPOPEND,BDCODFIR);
               END
             ELSE
               BEGIN
                 vtot = vtot + NEW.bdpenalimfir / :vcount;
                 UPDATE OR INSERT INTO VRHF_EMP_TFIPENSAO_DEP (BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDREFPAGPEND,BDREFPEND,BDREFAUXPEND,BDVALPEND,BDTIPOPEND,BDCODFIR,BDFICHA)
                 VALUES (NEW.bdcodemp, NEW.bdcodcol, :vben, NEW.bdreffir, NEW.bdrefirfir, 0, 0, NEW.bdpenalimfir / :vcount, NEW.bdtipocalcfir, NEW.BDCODFIR, TRUE)
                 MATCHING(BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDTIPOPEND,BDCODFIR);
               END
           END
       END
     END
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHAAVULSA_AD0 FOR VRHF_EMP_TFOLHAAVULSA
ACTIVE AFTER DELETE POSITION 0 
AS
BEGIN
  DELETE FROM VRHF_EMP_TFICHAIRRF WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDCODTCA = OLD.BDCODTCA AND BDDATAFIR = OLD.BDDATAFA AND BDTIPOCALCFIR = 5;
  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdtipocalc = 15 AND bdcodemp = OLD.bdcodemp AND bdcodcol = OLD.bdcodcol AND BDCODTCA = OLD.BDCODTCA AND BDDATA = OLD.BDDATAFA;

  EXECUTE PROCEDURE sp_vrh_painel_update(OLD.bdcodemp, OLD.bdref, '2', 'BDPERFOLHAAVULSA'); -- 2 - Excluido
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHAAVULSA_BI0 FOR VRHF_EMP_TFOLHAAVULSA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE VCODUSU INTEGER; /* Augusto - 02/04/2024 - #192435 */
BEGIN
  /* Trigger text */
  SELECT bdaaaamm FROM aaaamm(NEW.bddatafa) INTO NEW.bdref;

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdref, '1', 'BDPERFOLHAAVULSA'); -- 1 - Calculado

  /* Augusto - 02/04/2024 - #192435 */
  SELECT FIRST 1 BDCODUSU FROM VW_USUARIOS_SECAO INTO :VCODUSU;
  NEW.BDCODUSU = :VCODUSU;
END
^

-- 125979 - Raphael Teodoro - 15/01/2020
CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHAAVULSA_BU0 FOR VRHF_EMP_TFOLHAAVULSA
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdref, '1', 'BDPERFOLHAAVULSA'); -- 1 - Calculado
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHACOMP_AD0 FOR VRHF_EMP_TFOLHACOMP
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  /* Trigger text */
  DELETE FROM VRHF_EMP_TFICHAIRRF WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFIR = OLD.BDREFFN AND BDDATAFIR = OLD.BDDATAPAGFC AND BDTIPOCALCFIR IN (1,13);
  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdtipocalc = 8 AND bdcodemp = OLD.bdcodemp AND
                                                               bdcodcol = OLD.bdcodcol AND
                                                               bdreferencia = OLD.BDREFFN AND
                                                               bdDATA = OLD.BDDATAPAGFC;

  /* 185737 Leonardo Schwab 23/10/2023 */                                                               
  if ((coalesce(old.bdreffnini,0) > 0) and coalesce(old.bdreffnfim,0) > 0) then
     DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdtipocalc = 16 AND bdcodemp = OLD.bdcodemp AND
                                                                     bdcodcol = OLD.bdcodcol AND
                                                                     bdreferencia = old.bdreffnini AND
                                                                     bdreferenciafim = old.bdreffnfim and
                                                                     bdDATA = OLD.BDDATAPAGFC;

  if (old.bdcodacconv<>0) then
     begin
  DELETE FROM VRHF_CALC_IR_DETALHAMENTO WHERE BDCODEMP     = OLD.bdcodemp AND
                                              BDCODCOL     = OLD.bdcodcol AND
                                                    BDCODACD     = OLD.bdcodacconv;
     end
  else
     begin
       DELETE FROM VRHF_CALC_IR_DETALHAMENTO WHERE BDCODEMP     = OLD.bdcodemp AND
                                                   BDCODCOL     = OLD.bdcodcol AND
                                                   BDREFINICIAL = iif(BDREFINICIAL = -1, -1, OLD.bdreffn) and
                                              BDREFFIM     = OLD.bdreffnfim AND
                                                   BDREFERENCIA = iif(BDREFERENCIA = -1, -1, OLD.bdreffc);
     end

--  DELETE FROM VRHF_CALC_IR_DETALHAMENTO WHERE BDCODEMP     = OLD.bdcodemp AND
--                                              BDCODCOL     = OLD.bdcodcol AND
--                                              BDTIPOCALC   = 1 AND
--                                              BDREFINICIAL = iif(BDREFINICIAL = -1, -1, OLD.bdreffn) AND
--                                              BDREFFIM     = OLD.bdreffnfim AND
--                                              BDCODACD     = iif(OLD.bdcodacconv <> 0, OLD.bdcodacconv, 0) AND
--                                              BDREFERENCIA = iif(BDREFERENCIA = -1, -1, OLD.bdreffc) AND
--                                              BDORDEM      = 0;


  EXECUTE PROCEDURE sp_vrh_painel_update(OLD.bdcodemp, OLD.bdrefcomp, '2', 'BDPERFOLHACOMPLEMENTAR'); -- 2 - Excluido
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHACOMP_AI0 FOR VRHF_EMP_TFOLHACOMP
ACTIVE AFTER INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
--  execute procedure VRHF_SP_DADOS_BAIXA_CALCULO(new.bdcodemp,null,null,new.bdcodcol,8,new.bdreffn, new.bddatapagfc,NEW.bdrefcomp,NULL,null,new.bdliquido,null,null);
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHACOMP_AU0 FOR VRHF_EMP_TFOLHACOMP
ACTIVE AFTER UPDATE POSITION 0 
AS
DECLARE VARIABLE wstr VARCHAR(100);
BEGIN
  /* Trigger text */
  IF (OLD.bdfgtsfc <> NEW.bdfgtsfc) THEN
     BEGIN
       wstr = 'FGTSFCSEFIP';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc(NEW.bdcodemp,NEW.bdcodcol,NEW.bdreffn,NEW.bdreffc,NULL,NEW.bdfgtsfc,wstr,OLD.bdfgtsfc);
       wstr = 'FGTSFNGRRF';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc(NEW.bdcodemp,NEW.bdcodcol,NEW.bdreffn,NEW.bdreffc,NULL,NEW.bdfgtsfc,wstr,OLD.bdfgtsfc);
       wstr = 'FGTSFNRESCSEFIP';            
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc(NEW.bdcodemp,NEW.bdcodcol,NEW.bdreffn,NEW.bdreffc,NULL,NEW.bdfgtsfc,wstr,OLD.bdfgtsfc);
     END

  IF (OLD.bdfgtsfefc <> NEW.bdfgtsfefc) THEN
     BEGIN
       wstr = 'FGTSFESEFIP';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc(NEW.bdcodemp,NEW.bdcodcol,NEW.bdreffn,NEW.bdreffc,NULL,NEW.bdfgtsfefc,wstr,OLD.bdfgtsfefc);
       wstr = 'FGTSFERGRRF';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc(NEW.bdcodemp,NEW.bdcodcol,NEW.bdreffn,NEW.bdreffc,NULL,NEW.bdfgtsfefc,wstr,OLD.bdfgtsfefc);
       wstr = 'FGTSFERESCSEFIP';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc(NEW.bdcodemp,NEW.bdcodcol,NEW.bdreffn,NEW.bdreffc,NULL,NEW.bdfgtsfefc,wstr,OLD.bdfgtsfefc);
     END

  IF (OLD.bdfgts13fc <> NEW.bdfgts13fc) THEN
     BEGIN
       wstr = 'FGTS13RESCSEFIP';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc(NEW.bdcodemp,NEW.bdcodcol,NEW.bdreffn,NEW.bdreffc,NULL,NEW.bdfgts13fc,wstr,OLD.bdfgts13fc);
       wstr = 'FGTS13RESCGRRF';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc(NEW.bdcodemp,NEW.bdcodcol,NEW.bdreffn,NEW.bdreffc,NULL,NEW.bdfgts13fc,wstr,OLD.bdfgts13fc);
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHACOMP_BI0 FOR VRHF_EMP_TFOLHACOMP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
  DECLARE VARIABLE wstr VARCHAR(100);
  DECLARE VARIABLE wano VARCHAR(4);
  DECLARE VARIABLE wmes VARCHAR(2);
  DECLARE VARIABLE wdia VARCHAR(2);
  DECLARE VARIABLE wdata INTEGER;
  DECLARE VARIABLE vdata DATE;
  DECLARE VARIABLE vhora TIME;
  DECLARE VARIABLE VCODUSU INTEGER; /* Augusto - 02/04/2024 - #192435 */

BEGIN
  if ((new.bddatapagfc is null) or (new.bddatapagfc = '12-30-1899') ) then
     exception EX_DATAVAZIA;

  if (new.bddatairrfesocial is null) then
     new.bddatairrfesocial = new.bddatapagfc;

  if (new.bdrefirrfesocial is null) then
     begin
       select bdaaaamm from aaaamm(new.bddatairrfesocial) into new.bdrefirrfesocial;
     end

  /* Trigger text */
  wstr = 'select BDRETORNO from preenche_esquerda(EXTRACT(year from cast('||''''||NEW.bddatapagfc||''''||' as date)),4,'||''||'0'||''||') y';
  EXECUTE STATEMENT wstr INTO :wano;
  wstr = 'select BDRETORNO from preenche_esquerda(EXTRACT(month from cast('||''''||NEW.bddatapagfc||''''||' as date)),2,'||''||'0'||''||') y';
  EXECUTE STATEMENT wstr INTO :wMes;
  wstr = 'select BDRETORNO from preenche_esquerda(EXTRACT(day from cast('||''''||NEW.bddatapagfc||''''||' as date)),2,'||''||'0'||''||') y';
  EXECUTE STATEMENT wstr INTO :wDia;

  wdata = CAST(wano||wMes AS INTEGER);
  NEW.bdrefcomp = wdata;

  wdata = CAST(wano||wMes||wdia AS INTEGER);
  NEW.bdreffc = wdata;

  SELECT CURRENT_DATE, CURRENT_TIME FROM rdb$database INTO :vdata, :vhora;

  IF (NEW.bddataprocfc IS NULL) THEN
     NEW.bddataprocfc = vdata;

  IF (NEW.bdhoraprocfc IS NULL) THEN
     NEW.bdhoraprocfc = vhora;

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdrefcomp, '1', 'BDPERFOLHACOMPLEMENTAR'); -- 1 - Calculado

  /* Augusto - 02/04/2024 - #192435 */
  SELECT FIRST 1 BDCODUSU FROM VW_USUARIOS_SECAO INTO :VCODUSU;
  NEW.BDCODUSU = :VCODUSU;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHANORMAL_AD0 FOR VRHF_EMP_TFOLHANORMAL
ACTIVE AFTER DELETE POSITION 0
AS
DECLARE VARIABLE vCOMP13NAFOLHA VARCHAR(5);
DECLARE VARIABLE vSQL VARCHAR(1000);
BEGIN
  /* Trigger text */
  DELETE FROM VRHF_EMP_TFICHARV WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFRV = OLD.BDREFFN AND BDTIPOFRV = 0;
  DELETE FROM VRHF_EMP_TFICHAHE WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFHE = OLD.BDREFFN AND BDTIPOFHE = 0;
  DELETE FROM VRHF_EMP_TFICHAHN WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFHN = OLD.BDREFFN AND BDTIPOFHN = 0;
  DELETE FROM VRHF_EMP_TFICHAOUTRAS WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFOT = OLD.BDREFFN AND BDTIPOFOT = 0;
  DELETE FROM VRHF_EMP_TFICHAIRRF WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFIR = OLD.BDREFFN AND BDTIPOCALCFIR IN (0,3);

  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdtipocalc = 6 AND bdcodemp = OLD.bdcodemp AND
                                                               bdcodcol = OLD.bdcodcol AND
                                                               bdreferencia = OLD.BDREFFN;

  IF (SUBSTRING(OLD.BDREFFN FROM 5 FOR 2) = '12') THEN
     BEGIN
       vCOMP13NAFOLHA = '';
       vSQL = 'SELECT FIRST 1 UPPER(BDCALCC13NAFNEMP) FROM VRHF_BASE_TEMPPAR WHERE BDCODEMP = '||OLD.BDCODEMP||' AND BDREFEMP <= '||OLD.BDREFFN||' ORDER BY BDREFEMP DESC';
       EXECUTE STATEMENT vSQL INTO :vCOMP13NAFOLHA;

       IF (vCOMP13NAFOLHA = 'TRUE') THEN
          DELETE FROM VRHF_EMP_TC13SAL WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFC13 = OLD.BDREFFN;
     END

  EXECUTE PROCEDURE sp_vrh_painel_update(OLD.bdcodemp, OLD.bdreffn, '2', 'BDPERFOLHANORMAL'); -- 2 - Excluido

  update VRH_EMP_TPARCELAMENTOS_ITENS set BDVALORDESC = null, BDDESCCALCPAR = null, BDMAXIMOPAR = null where BDCODEMP = old.bdcodemp and BDCODCOL = old.bdcodcol and BDREFPI = old.bdreffn;
  delete from VRHF_EMP_TPARCDETCALC where BDCODEMP = old.bdcodemp and BDCODCOL = old.bdcodcol and BDREFCALC = old.bdreffn and BDTIPOCALC = 1;
END
^


CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHANORMAL_BI0 FOR VRHF_EMP_TFOLHANORMAL
ACTIVE BEFORE INSERT OR UPDATE POSITION 0 
AS
  DECLARE VARIABLE vdata DATE;
  DECLARE VARIABLE vhora TIME;
  DECLARE VARIABLE VCODUSU INTEGER; /* Augusto - 02/04/2024 - #192435 */
BEGIN
  /* Trigger text */
--  execute procedure VRHF_SP_DADOS_BAIXA_CALCULO(new.bdcodemp,null,null,new.bdcodcol,6,new.bdreffn, null,null,NULL,null,new.bdliquido,null,null);

  SELECT CURRENT_DATE, CURRENT_TIME FROM rdb$database INTO :vdata, :vhora;

  IF (NEW.bddataprocfn IS NULL) THEN
     NEW.bddataprocfn = vdata;

  IF (NEW.bdhoraprocfn IS NULL) THEN
     NEW.bdhoraprocfn = vhora;

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdreffn, '1', 'BDPERFOLHANORMAL'); -- 1 - Calculado

  /* Augusto - 02/04/2024 - #192435 */
  SELECT FIRST 1 BDCODUSU FROM VW_USUARIOS_SECAO INTO :VCODUSU;
  NEW.BDCODUSU = :VCODUSU;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHATOMADOR_AD0 FOR VRHF_EMP_TFOLHATOMADOR
ACTIVE AFTER DELETE POSITION 0
AS
  DECLARE VARIABLE vCOMP13NAFOLHA VARCHAR(5);
  DECLARE VARIABLE vSQL VARCHAR(1000);
BEGIN
  DELETE FROM VRHF_EMP_TFICHARV WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFRV = OLD.BDREFTOMADOR AND BDTIPOFRV = 100 AND BDCCFRV = OLD.BDORDEM;
  DELETE FROM VRHF_EMP_TFICHAHE WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFHE = OLD.BDREFTOMADOR AND BDTIPOFHE = 100 AND BDCCFHE = OLD.BDORDEM;
  DELETE FROM VRHF_EMP_TFICHAHN WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFHN = OLD.BDREFTOMADOR AND BDTIPOFHN = 100 AND BDCCFHN = OLD.BDORDEM;
  DELETE FROM VRHF_EMP_TFICHAOUTRAS WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFOT = OLD.BDREFTOMADOR AND BDTIPOFOT = 100 AND BDCCFOT = OLD.BDORDEM;
  DELETE FROM VRHF_EMP_TFICHAIRRF WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFIR = OLD.BDREFTOMADOR AND BDTIPOCALCFIR IN (100,300) AND BDCCFIR = OLD.BDORDEM;
  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdtipocalc = 7 AND bdcodemp = OLD.bdcodemp AND bdcodcol = OLD.bdcodcol AND bdreferencia = OLD.BDREFTOMADOR;

  IF (SUBSTRING(OLD.BDREFTOMADOR FROM 5 FOR 2) = '12') THEN
     BEGIN
       vCOMP13NAFOLHA = '';
       vSQL = 'SELECT FIRST 1 UPPER(BDCALCC13NAFNEMP) FROM VRHF_BASE_TEMPPAR WHERE BDCODEMP = '||OLD.BDCODEMP||' AND BDREFEMP <= '||OLD.BDREFTOMADOR||' ORDER BY BDREFEMP DESC';
       EXECUTE STATEMENT vSQL INTO :vCOMP13NAFOLHA;

       IF (vCOMP13NAFOLHA = 'TRUE') THEN
          DELETE FROM VRHF_EMP_TC13SAL WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFC13 = OLD.BDREFTOMADOR;
     END

  EXECUTE PROCEDURE sp_vrh_painel_update(OLD.bdcodemp, OLD.bdreftomador, '2', 'BDPERFOLHANORMAL'); -- 2 - Excluido

  update VRH_EMP_TPARCELAMENTOS_ITENS set BDVALORDESC = null, BDDESCCALCPAR = null, BDMAXIMOPAR = null where BDCODEMP = old.bdcodemp and BDCODCOL = old.bdcodcol and BDREFPI = old.bdreftomador;
  delete from VRHF_EMP_TPARCDETCALC where BDCODEMP = old.bdcodemp and BDCODCOL = old.bdcodcol and BDREFCALC = old.bdreftomador and BDTIPOCALC = 1;
END
^


CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHATOMADOR_BI0 FOR VRHF_EMP_TFOLHATOMADOR
ACTIVE BEFORE INSERT OR UPDATE POSITION 0 
AS
  DECLARE VARIABLE vdata DATE;
  DECLARE VARIABLE vhora TIME;
  DECLARE VARIABLE VCODUSU INTEGER; /* Augusto - 02/04/2024 - #192435 */

BEGIN
  SELECT CURRENT_DATE, CURRENT_TIME FROM rdb$database INTO :vdata, :vhora;

  IF (NEW.bddataprocft IS NULL) THEN
     NEW.bddataprocft = vdata;

  IF (NEW.bdhoraprocft IS NULL) THEN
     NEW.bdhoraprocft = vhora;

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdreftomador, '1', 'BDPERFOLHANORMAL'); -- 1 - Calculado

  /* Augusto - 02/04/2024 - #192435 */
  SELECT FIRST 1 BDCODUSU FROM VW_USUARIOS_SECAO INTO :VCODUSU;
  NEW.BDCODUSU = :VCODUSU;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLTOMCOMP_AD0 FOR VRHF_EMP_TFOLTOMCOMP
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  DELETE FROM VRHF_EMP_TFICHARV WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFRV = OLD.BDREFTOMADOR AND BDTIPOFRV = 101 AND BDCCFRV = OLD.BDORDEM;
  DELETE FROM VRHF_EMP_TFICHAHE WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFHE = OLD.BDREFTOMADOR AND BDTIPOFHE = 101 AND BDCCFHE = OLD.BDORDEM;
  DELETE FROM VRHF_EMP_TFICHAHN WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFHN = OLD.BDREFTOMADOR AND BDTIPOFHN = 101 AND BDCCFHN = OLD.BDORDEM;
  DELETE FROM VRHF_EMP_TFICHAOUTRAS WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFOT = OLD.BDREFTOMADOR AND BDTIPOFOT = 101 AND BDCCFOT = OLD.BDORDEM;
  DELETE FROM VRHF_EMP_TFICHAIRRF WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFIR = OLD.BDREFTOMADOR AND BDTIPOCALCFIR IN (101,301) AND BDCCFIR = OLD.BDORDEM;
  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdtipocalc = 9 AND bdcodemp = OLD.bdcodemp AND
                                                               bdcodcol = OLD.bdcodcol AND
                                                               bdreferencia = OLD.BDREFTOMADOR AND
                                                               bdDATA = OLD.BDDATAPAGFC;
                                                               
  /* 185737 Leonardo Schwab 23/10/2023 */
  if ((coalesce(old.bdreffnini,0) > 0) and coalesce(old.bdreffnfim,0) > 0) then
     DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdtipocalc = 16 AND bdcodemp = OLD.bdcodemp AND
                                                                     bdcodcol = OLD.bdcodcol AND
                                                                     bdreferencia = old.bdreffnini AND
                                                                     bdreferenciafim = old.bdreffnfim and
                                                                     bdDATA = OLD.BDDATAPAGFC;


  if (old.bdcodacconv<>0) then
     begin
  DELETE FROM VRHF_CALC_IR_DETALHAMENTO WHERE BDCODEMP     = OLD.bdcodemp AND
                                              BDCODCOL     = OLD.bdcodcol AND
                                                    BDCODACD     = OLD.bdcodacconv;
     end
  else
     begin
       DELETE FROM VRHF_CALC_IR_DETALHAMENTO WHERE BDCODEMP     = OLD.bdcodemp AND
                                                   BDCODCOL     = OLD.bdcodcol AND
                                                   BDREFINICIAL = iif(BDREFINICIAL = -1, -1, OLD.bdreftomador) and
                                              BDREFFIM     = OLD.bdreffnfim AND
                                                   BDREFERENCIA = iif(BDREFERENCIA = -1, -1, OLD.bdreffc);
     end


--                                              BDTIPOCALC   = 1 AND
-- AND
--        BDCODACD     = iif(OLD.bdcodacconv <> 0, OLD.bdcodacconv, 0) AND
--                                              BDORDEM      = iif(BDORDEM <> 0, old.bdordem, 0);

  EXECUTE PROCEDURE sp_vrh_painel_update(OLD.bdcodemp, OLD.bdreftomador, '2', 'BDPERFOLHACOMPLEMENTAR'); -- 2 - Excluido
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLTOMCOMP_AI0 FOR VRHF_EMP_TFOLTOMCOMP
ACTIVE AFTER INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
--  execute procedure VRHF_SP_DADOS_BAIXA_CALCULO(new.bdcodemp,null,null,new.bdcodcol,9,new.bdreftomador, new.bddatapagfc,NEW.bdrefcomp,NULL,null,new.bdliquido,null,null);
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLTOMCOMP_AU0 FOR VRHF_EMP_TFOLTOMCOMP
ACTIVE AFTER UPDATE POSITION 0 
AS
DECLARE VARIABLE wstr VARCHAR(100);
DECLARE VARIABLE wano VARCHAR(4);
DECLARE VARIABLE wmes VARCHAR(2);
DECLARE VARIABLE wdia VARCHAR(2);
DECLARE VARIABLE wdata INTEGER;
BEGIN
  /* Trigger text */
  IF (OLD.bdfgtsfc <> NEW.bdfgtsfc) THEN
     BEGIN
       wstr = 'FGTSFCSEFIP';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc(NEW.bdcodemp,NEW.bdcodcol,NEW.bdreftomador,NEW.bdreffc,NEW.bdordem,NEW.bdfgtsfc,wstr,OLD.bdfgtsfc);
       wstr = 'FGTSFNGRRF';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc(NEW.bdcodemp,NEW.bdcodcol,NEW.bdreftomador,NEW.bdreffc,NEW.bdordem,NEW.bdfgtsfc,wstr,OLD.bdfgtsfc);
       wstr = 'FGTSFNRESCSEFIP';            
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc(NEW.bdcodemp,NEW.bdcodcol,NEW.bdreftomador,NEW.bdreffc,NEW.bdordem,NEW.bdfgtsfc,wstr,OLD.bdfgtsfc);
     END

  IF (OLD.bdfgtsfefc <> NEW.bdfgtsfefc) THEN
     BEGIN
       wstr = 'FGTSFESEFIP';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc(NEW.bdcodemp,NEW.bdcodcol,NEW.bdreftomador,NEW.bdreffc,NEW.bdordem,NEW.bdfgtsfefc,wstr,OLD.bdfgtsfefc);
       wstr = 'FGTSFERGRRF';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc(NEW.bdcodemp,NEW.bdcodcol,NEW.bdreftomador,NEW.bdreffc,NEW.bdordem,NEW.bdfgtsfefc,wstr,OLD.bdfgtsfefc);
       wstr = 'FGTSFERESCSEFIP';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc(NEW.bdcodemp,NEW.bdcodcol,NEW.bdreftomador,NEW.bdreffc,NEW.bdordem,NEW.bdfgtsfefc,wstr,OLD.bdfgtsfefc);
     END

  IF (OLD.bdfgts13fc <> NEW.bdfgts13fc) THEN
     BEGIN
       wstr = 'FGTS13RESCSEFIP';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc(NEW.bdcodemp,NEW.bdcodcol,NEW.bdreftomador,NEW.bdreffc,NEW.bdordem,NEW.bdfgts13fc,wstr,OLD.bdfgts13fc);
       wstr = 'FGTS13RESCGRRF';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc(NEW.bdcodemp,NEW.bdcodcol,NEW.bdreftomador,NEW.bdreffc,NEW.bdordem,NEW.bdfgts13fc,wstr,OLD.bdfgts13fc);
     END

END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLTOMCOMP_BU0 FOR VRHF_EMP_TFOLTOMCOMP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
  DECLARE VARIABLE wstr VARCHAR(100);
  DECLARE VARIABLE wano VARCHAR(4);
  DECLARE VARIABLE wmes VARCHAR(2);
  DECLARE VARIABLE wdia VARCHAR(2);
  DECLARE VARIABLE wdata INTEGER;
  DECLARE VARIABLE vdata DATE;
  DECLARE VARIABLE vhora TIME;
  DECLARE VARIABLE VCODUSU INTEGER; /* Augusto - 02/04/2024 - #192435 */

BEGIN
  if ((new.bddatapagfc is null) or (new.bddatapagfc = '12-30-1899') ) then
     exception EX_DATAVAZIA;

  if (new.bddatairrfesocial is null) then
     new.bddatairrfesocial = new.bddatapagfc;

  if (new.bdrefirrfesocial is null) then
     begin
       select bdaaaamm from aaaamm(new.bddatairrfesocial) into new.bdrefirrfesocial;
     end

  /* Trigger text */
  wstr = 'select BDRETORNO from preenche_esquerda(EXTRACT(year from cast('||''''||NEW.bddatapagfc||''''||' as date)),4,'||''||'0'||''||') y';
  EXECUTE STATEMENT wstr INTO :wano;
  wstr = 'select BDRETORNO from preenche_esquerda(EXTRACT(month from cast('||''''||NEW.bddatapagfc||''''||' as date)),2,'||''||'0'||''||') y';
  EXECUTE STATEMENT wstr INTO :wMes;
  wstr = 'select BDRETORNO from preenche_esquerda(EXTRACT(day from cast('||''''||NEW.bddatapagfc||''''||' as date)),2,'||''||'0'||''||') y';
  EXECUTE STATEMENT wstr INTO :wDia;

  wdata = CAST(wano||wMes AS INTEGER);
  NEW.bdrefcomp = wdata;

  wdata = CAST(wano||wMes||wdia AS INTEGER);
  NEW.bdreffc = wdata;

  SELECT CURRENT_DATE, CURRENT_TIME FROM rdb$database INTO :vdata, :vhora;

  IF (NEW.bddataprocfc IS NULL) THEN
     NEW.bddataprocfc = vdata;

  IF (NEW.bdhoraprocfc IS NULL) THEN
     NEW.bdhoraprocfc = vhora;

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdreftomador, '1', 'BDPERFOLHACOMPLEMENTAR'); -- 1 - Calculado

  /* Augusto - 02/04/2024 - #192435 */
  SELECT FIRST 1 BDCODUSU FROM VW_USUARIOS_SECAO INTO :VCODUSU;
  NEW.BDCODUSU = :VCODUSU;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_THIST_FOLHACOMP_BI0 FOR VRHF_EMP_THIST_FOLHACOMP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vReferencia VARCHAR(6);

BEGIN
  IF (NEW.BDREFFN IS NOT NULL AND NEW.BDREFFN <> 0) THEN
     BEGIN
       vReferencia = CAST(NEW.BDREFFN AS VARCHAR(6));
       NEW.BDDETALHEHFC = 'Competencia: '||SUBSTRING(vReferencia FROM 5 FOR 2)||'/'||SUBSTRING(vReferencia FROM 1 FOR 4);
     END

   NEW.bdrefcomp = CAST(SUBSTRING(CAST(NEW.bdreffc AS VARCHAR(8)) FROM 1 FOR 6) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_THIST_FOLHACOMP_BU0 FOR VRHF_EMP_THIST_FOLHACOMP
ACTIVE BEFORE UPDATE POSITION 0 
AS
  DECLARE VARIABLE vReferencia VARCHAR(6);

BEGIN
  IF (NEW.BDREFFN IS NOT NULL AND NEW.BDREFFN <> 0) THEN
     BEGIN
       vReferencia = CAST(NEW.BDREFFN AS VARCHAR(6));
       NEW.BDDETALHEHFC = 'Competencia: '||SUBSTRING(vReferencia FROM 5 FOR 2)||'/'||SUBSTRING(vReferencia FROM 1 FOR 4);
     END

  NEW.bdrefcomp = CAST(SUBSTRING(CAST(NEW.bdreffc AS VARCHAR(8)) FROM 1 FOR 6) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_THISTCOMP_BI0 FOR VRHF_EMP_THISTCOMP
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  IF ((NEW.bdchavedarfhistcomp IS NULL) OR (NEW.bdchavedarfhistcomp = 0) ) THEN
     SELECT COALESCE(MAX(bdchavedarfhistcomp),0)+1 FROM vrhf_emp_thistcomp WHERE bdcodemp = NEW.bdcodemp INTO NEW.bdchavedarfhistcomp;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_THISTNF_BI0 FOR VRHF_EMP_THISTNF
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.BDCHAVEDARFHISTNF IS NULL) OR (NEW.BDCHAVEDARFHISTNF = 0) ) THEN
     SELECT COALESCE(MAX(BDCHAVEDARFHISTNF),0)+1 FROM VRHF_EMP_THISTNF WHERE bdcodemp = NEW.bdcodemp INTO NEW.BDCHAVEDARFHISTNF;
END
^

--alt:14717 - 05/07/2016 - Alterada trigger para: quando o valor do campo BDORDEMGUIA for nulo ou 0 (zero), atribuir o MAX + 1 desse campo. - Bruno L. R.  
CREATE OR ALTER TRIGGER VRHF_EMP_THISTORICOGPS_INS FOR VRHF_EMP_THISTORICOGPS
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  IF ((NEW.bdchavedarfhistgps IS NULL) OR (NEW.bdchavedarfhistgps = 0) ) THEN
     SELECT COALESCE(MAX(bdchavedarfhistgps),0)+1 FROM VRHF_EMP_THISTORICOGPS WHERE bdcodemp = NEW.bdcodemp INTO NEW.bdchavedarfhistgps;
  IF ((NEW.BDORDEMGUIA IS NULL) OR (NEW.BDORDEMGUIA = 0)) THEN      
     SELECT COALESCE(MAX(BDORDEMGUIA),0)+1 FROM VRHF_EMP_THISTORICOGPS WHERE bdcodemp = NEW.bdcodemp INTO NEW.BDORDEMGUIA;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TNFCONT_BI0 FOR VRHF_EMP_TNFCONT
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrhf_emp_tnfcont WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.bdchave = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM vrhf_emp_tnfcont WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrhf_emp_tnfcont WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdchave = vNova_Chave;
         END
    END

 IF (NEW.bdcodcentro = 0) THEN
    NEW.bdcodcentro = NULL;

 IF (NEW.bdcodtpcc = 0) THEN
    NEW.bdcodtpcc = NULL;

 IF (NEW.BDCODTER = 0) THEN
    NEW.BDCODTER = NULL;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TNFCONT_BU0 FOR VRHF_EMP_TNFCONT
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  /* Trigger text */
 IF (NEW.bdcodcentro = 0) THEN
    NEW.bdcodcentro = NULL;

 IF (NEW.bdcodtpcc = 0) THEN
    NEW.bdcodtpcc = NULL;

 IF (NEW.BDCODTER = 0) THEN
    NEW.BDCODTER = NULL;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TNFCOOP_BI0 FOR VRHF_EMP_TNFCOOP
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrhf_emp_tnfcoop WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.bdchave = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM vrhf_emp_tnfcoop WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrhf_emp_tnfcoop WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdchave = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TNFPRODRURAL_BI0 FOR VRHF_EMP_TNFPRODRURAL
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrhf_emp_tnfprodrural WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.bdchave = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM vrhf_emp_tnfprodrural WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrhf_emp_tnfprodrural WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdchave = vNova_Chave;
         END
    END

  if (coalesce(new.BDCODAQUIRUR, 0) <> 0) then
     new.BDESOCIALNF = 'TRUE';
  else
     new.BDESOCIALNF = 'FALSE';

  new.bdtiponf = 0;

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdrefnf, '1', 'BDPERNFFUNRURAL'); -- 1 - Calculado
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TNFPRODRURAL_BU0 FOR VRHF_EMP_TNFPRODRURAL
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  if (coalesce(new.BDCODAQUIRUR, 0) <> 0) then
     new.BDESOCIALNF = 'TRUE';
  else
     new.BDESOCIALNF = 'FALSE';

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdrefnf, '1', 'BDPERNFFUNRURAL'); -- 1 - Calculado
end
^

-- 125979 - Raphael Teodoro - 15/01/2020
CREATE OR ALTER TRIGGER VRHF_EMP_TNFPRODRURAL_AD0 FOR VRHF_EMP_TNFPRODRURAL
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE sp_vrh_painel_update(OLD.bdcodemp, OLD.bdrefnf, '2', 'BDPERNFFUNRURAL'); -- 2 - Excluido
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TNOTASFISCAIS_BI0 FOR VRHF_EMP_TNOTASFISCAIS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrhf_emp_tnotasfiscais WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.bdchave = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM vrhf_emp_tnotasfiscais WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM vrhf_emp_tnotasfiscais WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdchave = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TNOTASFISCAIS_AD0 FOR VRHF_EMP_TNOTASFISCAIS
ACTIVE AFTER DELETE POSITION 0
AS
begin
  DELETE FROM TOL_VRHF_EMP_NF WHERE BDCODEMP = OLD.BDCODEMP AND BDCHAVENF = OLD.BDCHAVE;
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TPLANLANC_ADSAL_BI0 FOR VRHF_EMP_TPLANLANC_ADSAL
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF (NEW.BDCOMPLANC IS NULL OR (NEW.BDCOMPLANC = 0)) THEN
     BEGIN
       NEW.bdcomplanc = CAST((SUBSTRING(NEW.bddatalanc FROM 1 FOR 4)||SUBSTRING(NEW.bddatalanc FROM 6 FOR 2)) AS INTEGER);
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TPLANLANC_ADSAL_BU0 FOR VRHF_EMP_TPLANLANC_ADSAL
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  /* Trigger text */
  NEW.bdcomplanc = CAST((SUBSTRING(NEW.bddatalanc FROM 1 FOR 4)||SUBSTRING(NEW.bddatalanc FROM 6 FOR 2)) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TPLANLANC_BI0 FOR VRHF_EMP_TPLANLANC
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  IF (NEW.BDCOMPLANC IS NULL OR (NEW.BDCOMPLANC = 0)) THEN
     BEGIN
       NEW.bdcomplanc = CAST((SUBSTRING(NEW.bddatalanc FROM 1 FOR 4)||SUBSTRING(NEW.bddatalanc FROM 6 FOR 2)) AS INTEGER);
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TPLANLANC_BU0 FOR VRHF_EMP_TPLANLANC
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  NEW.bdcomplanc = CAST((SUBSTRING(NEW.bddatalanc FROM 1 FOR 4)||SUBSTRING(NEW.bddatalanc FROM 6 FOR 2)) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TPLANLANC_FA_BI0 FOR VRHF_EMP_TPLANLANC_FA
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF (NEW.bdcompfa IS NULL OR (NEW.bdcompfa = 0)) THEN
     BEGIN
       NEW.bdcompfa = CAST((SUBSTRING((CAST(NEW.bddatalancfa AS VARCHAR(10))) FROM 1 FOR 4)||SUBSTRING((CAST(NEW.bddatalancfa AS VARCHAR(10))) FROM 6 FOR 2)) AS INTEGER);
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TPLANLANC_FA_BU0 FOR VRHF_EMP_TPLANLANC_FA
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  NEW.bdcompfa = CAST((SUBSTRING(NEW.bddatalancfa FROM 1 FOR 4)||SUBSTRING(NEW.bddatalancfa FROM 6 FOR 2)) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TRATEIO_VERBAS_BI0 FOR VRHF_EMP_TRATEIO_VERBAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNCod INTEGER;

BEGIN
  IF (NEW.BDCODRTV IS NULL OR (NEW.BDCODRTV = 0)) THEN
     BEGIN
        SELECT COALESCE(MAX(X.BDCODRTV), 0) + 1 FROM VRHF_EMP_TRATEIO_VERBAS X INTO :vNCod;
        NEW.BDCODRTV = :vNCod;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAFC_BI0 FOR VRHF_EMP_TVERBAFC
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  NEW.bdrefcomp = CAST(SUBSTRING(CAST(NEW.bdreffc AS VARCHAR(8)) FROM 1 FOR 6) AS INTEGER);

  if (NEW.bdvalvfc is null) then
     NEW.bdvalvfc = 0;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAFC_BU0 FOR VRHF_EMP_TVERBAFC
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  NEW.bdrefcomp = CAST(SUBSTRING(CAST(NEW.bdreffc AS VARCHAR(8)) FROM 1 FOR 6) AS INTEGER);
  
  if (NEW.bdvalvfc is null) then
     NEW.bdvalvfc = 0;  
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAFCTOMADOR_BI0 FOR VRHF_EMP_TVERBAFCTOMADOR
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  NEW.bdrefcomp = CAST(SUBSTRING(CAST(NEW.bdreffc AS VARCHAR(8)) FROM 1 FOR 6) AS INTEGER);

  if (NEW.bdvalvfc is null) then
     NEW.bdvalvfc = 0;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAFCTOMADOR_BU0 FOR VRHF_EMP_TVERBAFCTOMADOR
ACTIVE BEFORE UPDATE POSITION 0 
AS
BEGIN
  NEW.bdrefcomp = CAST(SUBSTRING(CAST(NEW.bdreffc AS VARCHAR(8)) FROM 1 FOR 6) AS INTEGER);

  if (NEW.bdvalvfc is null) then
     NEW.bdvalvfc = 0;
END
^

-- 27813 - Raphael Teodoro - 14/02/2020
CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAFCTOMINT_BIU0 FOR VRHF_EMP_TVERBAFCTOMINT
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
BEGIN
  NEW.bdrefcomp = TRUNC(NEW.bdreffc / 100);
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAFN_DET_BI0 FOR VRHF_EMP_TVERBAFN_DET
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
--  IF (coalesce(NEW.BDITEMFND, 0) = 0) THEN
--     BEGIN
       SELECT COALESCE(MAX(X.BDITEMFND) + 1, 1)
       FROM vrhf_emp_tverbafn_det X
       WHERE X.BDCODEMP = NEW.BDCODEMP AND X.BDCODCOL = NEW.BDCODCOL AND X.BDREFFN = NEW.BDREFFN AND X.BDCODVER = NEW.BDCODVER
       INTO
         :vNovoCod;

       NEW.BDITEMFND = vNovoCod;
--     END
     END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAFT_DET_BI0 FOR VRHF_EMP_TVERBAFT_DET
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
--  IF (coalesce(NEW.BDITEMFTD, 0) = 0) THEN
--     BEGIN
       SELECT COALESCE(MAX(X.BDITEMFTD) + 1, 1)
       FROM vrhf_emp_tverbaft_det X
       WHERE X.BDCODEMP = NEW.BDCODEMP AND X.BDCODCOL = NEW.BDCODCOL AND X.BDREFTOMADOR = NEW.BDREFTOMADOR AND X.BDCODVER = NEW.BDCODVER AND NEW.BDORDEM = X.BDORDEM
       INTO
         :vNovoCod;

       NEW.BDITEMFTD = vNovoCod;
--     END
     END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBARFE_BI0 FOR VRHF_EMP_TVERBARFE
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vData VARCHAR(10);

BEGIN
  IF (NEW.BDINIPERAQUISFE IS NOT NULL) THEN
     BEGIN
       vData = CAST(NEW.BDINIPERAQUISFE AS VARCHAR(10));

       NEW.BDDETALHERFE = 'Cód. férias: '||NEW.BDCODFE||'. Per. aquisitivo: '||SUBSTRING(vData FROM 9 FOR 2)||'/'||
                          SUBSTRING(vData FROM 6 FOR 2)||'/'||
                          SUBSTRING(vData FROM 1 FOR 4);
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBARFE_BU0 FOR VRHF_EMP_TVERBARFE
ACTIVE BEFORE UPDATE POSITION 0 
AS
  DECLARE VARIABLE vData VARCHAR(10);

BEGIN
  IF (NEW.BDINIPERAQUISFE IS NOT NULL) THEN
     BEGIN
       vData = CAST(NEW.BDINIPERAQUISFE AS VARCHAR(10));

       NEW.BDDETALHERFE = 'Cód. férias: '||NEW.BDCODFE||'. Per. aquisitivo: '||SUBSTRING(vData FROM 9 FOR 2)||'/'||
                          SUBSTRING(vData FROM 6 FOR 2)||'/'||
                          SUBSTRING(vData FROM 1 FOR 4);
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBATOMADOR_BI0 FOR VRHF_EMP_TVERBATOMADOR
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vData VARCHAR(10);
  DECLARE VARIABLE vCta VARCHAR(100);
  DECLARE VARIABLE vDtInt INTEGER;
  DECLARE VARIABLE vCodCC INTEGER;

BEGIN
  --Comentário de ajuste
  IF (NEW.BDDATAENTRADAVFT IS NOT NULL) THEN
     BEGIN
       SELECT X.BDNOMCTA,X.BDCODTPCC FROM VW_UNION_DADOS_CC X WHERE
              X.BDCODEMP = NEW.BDCODEMP AND X.BDCODCOL = NEW.BDCODCOL AND X.BDORDEM = NEW.BDORDEM
       INTO vCta,vCodCC;
       vData = CAST(NEW.BDDATAENTRADAVFT AS VARCHAR(10));
       vDtInt = CAST((SUBSTRING(vData FROM 1 FOR 4)||SUBSTRING(vData FROM 6 FOR 2)||SUBSTRING(vData FROM 9 FOR 2)) AS INTEGER);

       IF (vCodCC IS NOT NULL) THEN
          NEW.BDDETALHEVFT = SUBSTRING(('Alocação iniciada em '||SUBSTRING(vData FROM 9 FOR 2)||'/'||SUBSTRING(vData FROM 6 FOR 2)||'/'||SUBSTRING(vData FROM 1 FOR 4)||
                             ' no Centro/tomador: '||vCta) FROM 1 FOR 500);
       ELSE
          NEW.BDDETALHEVFT = SUBSTRING(('Alocação iniciada em '||SUBSTRING(vData FROM 9 FOR 2)||'/'||SUBSTRING(vData FROM 6 FOR 2)||'/'||SUBSTRING(vData FROM 1 FOR 4)||
                             ' na Empresa: '||vCta) FROM 1 FOR 500);

       NEW.BDITEMVFT = vDtInt;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBATOMADOR_BU0 FOR VRHF_EMP_TVERBATOMADOR
ACTIVE BEFORE UPDATE POSITION 0 
AS
  DECLARE VARIABLE vData VARCHAR(10);
  DECLARE VARIABLE vCta VARCHAR(100);
  DECLARE VARIABLE vCodCC INTEGER;
  DECLARE VARIABLE vDtInt INTEGER;

BEGIN
  --Comentário de ajuste
  IF (NEW.BDDATAENTRADAVFT IS NOT NULL) THEN
     BEGIN
       SELECT X.BDNOMCTA,X.BDCODTPCC FROM VW_UNION_DADOS_CC X WHERE
              X.BDCODEMP = NEW.BDCODEMP AND X.BDCODCOL = NEW.BDCODCOL AND X.BDORDEM = NEW.BDORDEM
       INTO vCta,vCodCC;
       vData = CAST(NEW.BDDATAENTRADAVFT AS VARCHAR(10));
       vDtInt = CAST((SUBSTRING(vData FROM 1 FOR 4)||SUBSTRING(vData FROM 6 FOR 2)||SUBSTRING(vData FROM 9 FOR 2)) AS INTEGER);

       IF (vCodCC IS NOT NULL) THEN
          NEW.BDDETALHEVFT = SUBSTRING(('Alocação iniciada em '||SUBSTRING(vData FROM 9 FOR 2)||'/'||SUBSTRING(vData FROM 6 FOR 2)||'/'||SUBSTRING(vData FROM 1 FOR 4)||
                             ' no Centro/tomador: '||vCta) FROM 1 FOR 500);
       ELSE
          NEW.BDDETALHEVFT = SUBSTRING(('Alocação iniciada em '||SUBSTRING(vData FROM 9 FOR 2)||'/'||SUBSTRING(vData FROM 6 FOR 2)||'/'||SUBSTRING(vData FROM 1 FOR 4)||
                             ' na Empresa: '||vCta) FROM 1 FOR 500);

       NEW.BDITEMVFT = vDtInt;

     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVSCOL_BI0 FOR VRHF_EMP_TVSCOL
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
BEGIN
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAINIVSCOL, new.BDMESINIVSCOL, new.BDANOINIVSCOL) into new.bdcompini;
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAFIMVSCOL, new.BDMESFIMVSCOL, new.BDANOFIMVSCOL, 1) into new.bdcompfim;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVSEMP_BIU0 FOR VRHF_EMP_TVSEMP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAINIVSEMP, new.BDMESINIVSEMP, new.BDANOINIVSEMP) into new.bdcompini;
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAFIMVSEMP, new.BDMESFIMVSEMP, new.BDANOFIMVSEMP, 1) into new.bdcompfim;
END
^

CREATE OR ALTER TRIGGER VRHF_BASE_TVSSIND_BIU0 FOR VRHF_BASE_TVSSIND
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAINIVSSIND, new.BDMESINIVSSIND, new.BDANOINIVSSIND) into new.bdcompini;
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAFIMVSSIND, new.BDMESFIMVSSIND, new.BDANOFIMVSSIND, 1) into new.bdcompfim;
end
^

CREATE OR ALTER TRIGGER VRHF_FUNCOES_TVSFUC_BIU0 FOR VRHF_FUNCOES_TVSFUC
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAINIVSFUC, new.BDMESINIVSFUC, new.BDANOINIVSFUC) into new.bdcompini;
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAFIMVSFUC, new.BDMESFIMVSFUC, new.BDANOFIMVSFUC, 1) into new.bdcompfim;
end
^

CREATE OR ALTER TRIGGER VRHF_BASE_TVSPRES_BIU0 FOR VRHF_BASE_TVSPRES
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAINIVSPRES, new.BDMESINIVSPRES, new.BDANOINIVSPRES) into new.bdcompini;
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAFIMVSPRES, new.BDMESFIMVSPRES, new.BDANOFIMVSPRES, 1) into new.bdcompfim;
end
^

CREATE OR ALTER TRIGGER VRHF_CUSTOS_TVSCUSTO_BIU0 FOR VRHF_CUSTOS_TVSCUSTO
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAINIVSCUSTO, new.BDMESINIVSCUSTO, new.BDANOINIVSCUSTO) into new.bdcompini;
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAFIMVSCUSTO, new.BDMESFIMVSCUSTO, new.BDANOFIMVSCUSTO, 1) into new.bdcompfim;
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVNCOL_BIU0 FOR VRHF_EMP_TVNCOL
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAINIVNCOL, new.BDMESINIVNCOL, new.BDANOINIVNCOL) into new.bdcompini;
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAFIMVNCOL, new.BDMESFIMVNCOL, new.BDANOFIMVNCOL, 1) into new.bdcompfim;
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVNEMP_BIU0 FOR VRHF_EMP_TVNEMP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAINIVNEMP, new.BDMESINIVNEMP, new.BDANOINIVNEMP) into new.bdcompini;
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAFIMVNEMP, new.BDMESFIMVNEMP, new.BDANOFIMVNEMP, 1) into new.bdcompfim;
end
^

CREATE OR ALTER TRIGGER VRHF_BASE_TVNSIND_BIU0 FOR VRHF_BASE_TVNSIND
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAINIVNSIND, new.BDMESINIVNSIND, new.BDANOINIVNSIND) into new.bdcompini;
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAFIMVNSIND, new.BDMESFIMVNSIND, new.BDANOFIMVNSIND, 1) into new.bdcompfim;
end
^

CREATE OR ALTER TRIGGER VRHF_FUNCOES_TVNFUC_BIU0 FOR VRHF_FUNCOES_TVNFUC
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAINIVNFUC, new.BDMESINIVNFUC, new.BDANOINIVNFUC) into new.bdcompini;
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAFIMVNFUC, new.BDMESFIMVNFUC, new.BDANOFIMVNFUC, 1) into new.bdcompfim;
end
^

CREATE OR ALTER TRIGGER VRHF_BASE_TVNPRES_BIU0 FOR VRHF_BASE_TVNPRES
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAINIVNPRES, new.BDMESINIVNPRES, new.BDANOINIVNPRES) into new.bdcompini;
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAFIMVNPRES, new.BDMESFIMVNPRES, new.BDANOFIMVNPRES, 1) into new.bdcompfim;
end
^

CREATE OR ALTER TRIGGER VRHF_CUSTOS_TVNCUSTO_BIU0 FOR VRHF_CUSTOS_TVNCUSTO
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAINIVNCUSTO, new.BDMESINIVNCUSTO, new.BDANOINIVNCUSTO) into new.bdcompini;
  select BDCOMPETENCIA from SP_GET_MONTA_COMP_VERBA(new.BDDIAFIMVNCUSTO, new.BDMESFIMVNCUSTO, new.BDANOFIMVNCUSTO, 1) into new.bdcompfim;
end
^

CREATE OR ALTER TRIGGER VRHF_TABELAS_TCONTRSIND_BI0 FOR VRHF_TABELAS_TCONTRSIND
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCONTRSIND IS NULL) OR (NEW.BDCODCONTRSIND = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODCONTRSIND) + 1, 1)
       FROM vrhf_tabelas_tcontrsind
       INTO :vNovoCod;

       NEW.BDCODCONTRSIND = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_TABELAS_TINSS_BI0 FOR VRHF_TABELAS_TINSS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODINSS IS NULL) OR (NEW.BDCODINSS = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODINSS) + 1, 1)
       FROM vrhf_tabelas_tinss
       INTO :vNovoCod;

       NEW.BDCODINSS = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_TABELAS_TINSSFAIXAS_BI0 FOR VRHF_TABELAS_TINSSFAIXAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
  DECLARE VARIABLE vCount INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vrhf_tabelas_tinssfaixas
            WHERE (bdCodINSS = NEW.bdcodinss) AND (bdrefinss = NEW.bdrefinss) INTO vNova_Chave;

      NEW.BDORDEM = vNova_Chave;
      IF ((NEW.bdrefinss IS NULL) OR (NEW.bdrefinss = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdrefinss)), 1) FROM vrhf_tabelas_tinssdados WHERE (bdcodinss = NEW.bdcodinss) INTO vchavelan;
          NEW.bdrefinss = vchavelan;
        END
    END
  ELSE
    BEGIN
       SELECT BDORDEM FROM vrhf_tabelas_tinssfaixas WHERE (BDORDEM = NEW.BDORDEM)
            AND (bdRefinss = NEW.bdrefinss) AND (bdcodinss = NEW.bdcodinss) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vrhf_tabelas_tinssfaixas WHERE (bdcodinss = NEW.bdcodinss)
           AND (bdRefInss = NEW.bdcodinss) INTO vNova_Chave;
           NEW.BDORDEM = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRHF_TABELAS_TIR_BI0 FOR VRHF_TABELAS_TIR
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODIR IS NULL) OR (NEW.BDCODIR = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODIR) + 1, 1)
       FROM vrhf_tabelas_tir
       INTO :vNovoCod;

       NEW.BDCODIR = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_TABELAS_TIRDADOS_BI0 FOR VRHF_TABELAS_TIRDADOS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCod INTEGER;
BEGIN
  IF (NEW.bdcoddir IS NULL OR (NEW.bdcoddir = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODDIR) + 1, 1) FROM VRHF_TABELAS_TIRDADOS WHERE BDCODIR = NEW.BDCODIR INTO :vCod;
       NEW.bdCODDIR = :vCod;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_TABELAS_TIRFAIXAS_BI0 FOR VRHF_TABELAS_TIRFAIXAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vcoddir INTEGER;
  DECLARE VARIABLE vref INTEGER;
  DECLARE VARIABLE vTipoCalc INTEGER;

BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemir IS NULL) OR (NEW.bdordemir = 0)) THEN
    BEGIN
      IF (NEW.bdcoddir IS NULL OR (NEW.bdcoddir = 0)) THEN
         SELECT MAX(bdcoddir) FROM vrhf_tabelas_tirdados WHERE bdcodir = NEW.bdcodir INTO :vcoddir;
      ELSE
         vcoddir = NEW.bdcoddir;

      SELECT COALESCE((MAX(bdordemir)+1), 1) FROM vrhf_tabelas_tirfaixas
            WHERE (bdcodir = NEW.bdcodir) AND (bdcoddir = :vcoddir) INTO vNova_Chave;
      NEW.bdordemir = vNova_Chave;

      SELECT BDREFIR, BDTIPOCALCFIR FROM vrhf_tabelas_tirdados WHERE BDCODIR = NEW.bdcodir AND BDCODDIR = :vcoddir INTO :vref,:vtipocalc;
      NEW.bdrefir = :vref;
      NEW.bdtipocalcfir = :vtipocalc;
    END
  ELSE
    BEGIN
      IF (NEW.bdcoddir IS NULL OR (NEW.bdcoddir = 0)) THEN
         SELECT MAX(bdcoddir) FROM vrhf_tabelas_tirdados WHERE bdcodir = NEW.bdcodir INTO :vcoddir;
      ELSE
         vcoddir = NEW.bdcoddir;

      SELECT bdordemir FROM vrhf_tabelas_tirfaixas WHERE (bdordemir = NEW.bdordemir)
            AND (bdcoddir = :vcoddir) AND (bdcodir = NEW.bdcodir) INTO vcodigo;

      SELECT BDREFIR, BDTIPOCALCFIR FROM vrhf_tabelas_tirdados WHERE BDCODIR = NEW.bdcodir AND BDCODDIR = :vcoddir INTO :vref,:vtipocalc;
      NEW.bdrefir = :vref;
      NEW.bdtipocalcfir = :vtipocalc;

      IF (vcodigo > 0) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEMIR)+1), 1) FROM vrhf_tabelas_tirfaixas WHERE (bdcodir = NEW.bdcodir)
          AND (bdcoddir = NEW.bdcoddir) INTO vNova_Chave;
          NEW.bdordemir = vNova_Chave;
        END
    END
END
^

CREATE OR ALTER TRIGGER VRHF_TABELAS_TSALFAMFAIXAS_BI0 FOR VRHF_TABELAS_TSALFAMFAIXAS
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNovaChave INTEGER;
  DECLARE VARIABLE vChaveLan INTEGER;
BEGIN
  vCodigo = 0;
  vNovaChave = 0;
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM VRHF_TABELAS_TSALFAMFAIXAS
            WHERE (BDREFSF = NEW.BDREFSF) INTO vNovaChave;
      NEW.BDORDEM = vNovaChave;
      IF ((NEW.BDREFSF IS NULL) OR (NEW.BDREFSF = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDREFSF)), 1) FROM VRHF_TABELAS_TSALFAM INTO vChaveLan;
          NEW.BDREFSF = vChaveLan;
        END
    END
  ELSE
    BEGIN
       SELECT BDORDEM FROM VRHF_TABELAS_TSALFAMFAIXAS WHERE (BDORDEM = NEW.BDORDEM)
            AND (BDREFSF = NEW.BDREFSF) INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM VRHF_TABELAS_TSALFAMFAIXAS
              WHERE (BDREFSF = NEW.BDREFSF) INTO vNovaChave;
           NEW.BDORDEM = vNovaChave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VRHM_BASE_TTIPOCONVENIO_BI0 FOR VRHM_BASE_TTIPOCONVENIO
ACTIVE BEFORE INSERT POSITION 0 
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodtipoconv IS NULL) OR (NEW.bdcodtipoconv = 0))  THEN
     SELECT COALESCE(MAX(bdcodtipoconv)+1,1) FROM vrhm_base_ttipoconvenio INTO NEW.bdcodtipoconv;
END
^

CREATE OR ALTER TRIGGER vrh_esocial_inconformidades_au0 FOR vrh_esocial_inconformidades
ACTIVE AFTER UPDATE POSITION 0
AS
BEGIN
END^


CREATE OR ALTER TRIGGER VRH_ESOCIAL_INCONFORMIDADES_BI0 FOR VRH_ESOCIAL_INCONFORMIDADES
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCHAVE INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
  BEGIN
    SELECT COALESCE(MAX(BDCHAVE), 0) + 1 BDCHAVE
    FROM VRH_ESOCIAL_INCONFORMIDADES
    WHERE BDCODEMP = NEW.bdcodemp
    AND BDEVENTO = NEW.bdevento
    AND BDCAMPO = NEW.bdcampo
    INTO :vchave;
    NEW.bdchave = vchave;
  END
END
^

-- XXXXXX - Raphael Teodoro - 07/04/2020 - Inclusão do cartão ponto
CREATE OR ALTER TRIGGER VRHP_EMP_PONTO_BIU0 FOR VRHP_EMP_PONTO
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
BEGIN
  NEW.BDDATAINT = (EXTRACT(YEAR  FROM NEW.BDDATA) * 10000) +
                  (EXTRACT(MONTH FROM NEW.BDDATA) * 100) +
                  (EXTRACT(DAY   FROM NEW.BDDATA));
END^

-- 138704 - Raphael Teodoro - 22/09/2020 - Criada tabela para armazenar NF-e consultada
CREATE OR ALTER TRIGGER VAUD_EMP_NFE_BIU0 FOR VAUD_EMP_NFE
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
BEGIN
  NEW.BDDATAEMISSAOINT = (EXTRACT(YEAR  FROM NEW.BDDATAEMISSAO) * 10000) +
                         (EXTRACT(MONTH FROM NEW.BDDATAEMISSAO) * 100) +
                         (EXTRACT(DAY   FROM NEW.BDDATAEMISSAO));
END
^

CREATE OR ALTER TRIGGER VSUC_BASE_TNOTAEXPLICATIVA_BI0 FOR VSUC_BASE_TNOTAEXPLICATIVA
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdchave)+1),1) FROM vsuc_base_tnotaexplicativa INTO vcodigo;
       NEW.bdchave = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM vsuc_base_tnotaexplicativa WHERE bdchave = NEW.bdchave INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdchave)+1),1) FROM vsuc_base_tnotaexplicativa INTO vcodigo;
            NEW.bdchave = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VSUC_EMP_TLAN_SPED_I012_BI0 FOR VSUC_EMP_TLAN_SPED_I012
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdlivro IS NULL) OR (NEW.bdlivro = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdlivro)+1), 1) FROM VSUC_EMP_TLAN_SPED_I012 WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.bdlivro = vNova_Chave;
     END
  ELSE
    BEGIN
       SELECT bdlivro FROM VSUC_EMP_TLAN_SPED_I012 WHERE (bdlivro = NEW.bdlivro) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdlivro)+1), 1) FROM VSUC_EMP_TLAN_SPED_I012 WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdlivro = vNova_Chave;
           --NEW.bdlivro = GEN_ID(gen_vsuc_VSUC_EMP_TLAN_SPED_I012, 1);
           /*exception ex_valor_text+NEW.bdcodtpcc;*/
         END
    END
END
^

CREATE OR ALTER TRIGGER VSUC_EMP_TLAN_SPED_I015_BI0 FOR VSUC_EMP_TLAN_SPED_I015
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
  DECLARE VARIABLE vLivro012 INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdsequencia IS NULL) OR (NEW.bdsequencia = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdsequencia)+1), 1) FROM VSUC_EMP_TLAN_SPED_I015 WHERE bdcodemp = NEW.bdcodemp AND bdlivro = NEW.bdlivro INTO vNova_Chave;
      NEW.bdsequencia = vNova_Chave;
     END
  ELSE
    BEGIN
       SELECT bdsequencia FROM VSUC_EMP_TLAN_SPED_I015 WHERE (bdsequencia = NEW.bdsequencia) AND (bdcodemp = NEW.bdcodemp) AND (bdlivro = NEW.bdlivro) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdsequencia)+1), 1) FROM VSUC_EMP_TLAN_SPED_I015 WHERE bdcodemp = NEW.bdcodemp AND (bdlivro = NEW.bdlivro) INTO vNova_Chave;
           NEW.bdsequencia = vNova_Chave;
           --NEW.bdsequencia = GEN_ID(gen_vsuc_VSUC_EMP_TLAN_SPED_I015, 1);
           /*exception ex_valor_text+NEW.bdcodtpcc;*/
         END
    END

   IF ((NEW.bdlivro IS NULL) OR (NEW.bdlivro = 0)) THEN
      BEGIN
        SELECT COALESCE((MAX(bdlivro)), 1) FROM VSUC_EMP_TLAN_SPED_I012 WHERE (bdcodemp = NEW.bdcodemp) INTO vLivro012;
        NEW.bdlivro = vLivro012;
      END
END
^

CREATE OR ALTER TRIGGER VSUC_EMP_TVINCTRAN_BD0 FOR VSUC_EMPRESAS_TVINCTRANSACAO
ACTIVE BEFORE DELETE POSITION 0 
AS
BEGIN
  -- Ao excluir um vínculo preciso eliminar as transações geradas por ela no lançamento
  UPDATE vsuc_empresas_tlan SET bdTRANFECHADA = 'FALSE',bdTRANSACAO = NULL,bdCHAVEVINC = NULL
  WHERE
  (bdCHAVEVINC = OLD.bdchavevinc) AND
  (bdCODEMP IN (SELECT bdCODEMP FROM tempresas
                WHERE
                ((bdcodemp = (SELECT CASE WHEN (bdCODMATRIZ > 0) THEN bdCODMATRIZ ELSE bdCODEMP END FROM tempresas WHERE bdcodemp = OLD.bdcodemp)) OR
                 (bdcodmatriz = (SELECT CASE WHEN (bdCODMATRIZ > 0) THEN bdCODMATRIZ ELSE bdCODEMP END FROM tempresas WHERE bdcodemp = OLD.bdcodemp)))));
END
^

CREATE OR ALTER TRIGGER VSUC_EMPRESAS_TENCEXE_BD0 FOR VSUC_EMPRESAS_TENCEXE
ACTIVE BEFORE DELETE POSITION 0 
AS
  DECLARE VARIABLE vcodblq INTEGER;  
  DECLARE VARIABLE vcodble INTEGER;
BEGIN
  SELECT bdcodblq, bdcodble
  FROM vsuc_empresas_bloqencexe
  WHERE bdcodemp = OLD.bdcodemp
  AND bdchavezer = OLD.bdchavezer
  INTO :vcodblq, :vcodble;

  DELETE FROM vsuc_empresas_bloqencexe
  WHERE bdcodemp = OLD.bdcodemp
  AND bdchavezer = OLD.bdchavezer;

  DELETE FROM tbloqlan_empresa
  WHERE bdcodemp = OLD.bdcodemp
  AND bdcodblq = :vcodblq
  AND bdcodble = :vcodble;
END
^

CREATE OR ALTER trigger vsuc_empresas_tlan_bd0 for vsuc_empresas_tlan
active before delete position 0
AS
  DECLARE VARIABLE vCodUsu INTEGER;
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE VRECONTABILIZANDO DM_BOOLEAN;
  DECLARE VARIABLE vDataHora TIMESTAMP;
  DECLARE VARIABLE vEmpresaDeletandoLanRecont INTEGER;
  DECLARE VARIABLE vEmpDest INTEGER;
  DECLARE VARIABLE vChaveDest INTEGER;
  DECLARE VARIABLE vContadorExclusao INTEGER;
BEGIN
  --#alt:16965 - Não executa a trigger quando estiver deletando para a recontabilização com plano de contas diferentes. Ana - 12/02/2018
  select trim(upper(coalesce(RDB$GET_CONTEXT('USER_SESSION', 'W_RECONTABILIZA_DELETE_EMPRESA'), 0)))
  from RDB$DATABASE
  into :VEMPRESADELETANDOLANRECONT;

  if ((VEMPRESADELETANDOLANRECONT <> 0) and (VEMPRESADELETANDOLANRECONT = OLD.BDCODEMP)) then
    exit;
  --#alt:16965.fim

  if (coalesce(old.bdtipolanorig, old.bdtipolan) not in (10, 15, 23, 26, 37, 39, 100, 200, 400, 600, 601, 3000) and old.BDEXCLUINDO is null and coalesce(RDB$GET_CONTEXT('USER_SESSION', 'W_RECUPERAR_TLAN'), 0) = 1) then
    begin
      execute procedure vsuc_sp_move_lanc_lixeira(old.bdcodemp, old.bdchave);
    end

  --#alt:70867. Lançar A. Ana - 01/08/2017
  if ((old.bdfilial > 0) and (old.bdfilial is not null)) then
    begin
      select first 1 bdcodempdestino, bdchavelandestino from vsuc_empresas_tlancara where bdcodemporigem = old.bdcodemp and bdchavelanorigem = old.bdchave
      into :vEmpDest, :vChaveDest;
      if ((vEmpDest > 0) and (vEmpDest is not null)) then
        begin
          delete from vsuc_empresas_tlancara where bdcodempdestino = :vEmpDest and bdchavelandestino = :vChaveDest and bdcodemporigem = old.bdcodemp and bdchavelanorigem = old.bdchave;
          delete from vsuc_empresas_tlan where bdcodemp = :vEmpDest and bdchave = :vChaveDest;
        end
    end
  --#alt:70867. fim

     SELECT FIRST 1 bdcodusu FROM sp_get_usuario INTO :vCodUsu;

  /* sol.: #10892 Jean 19/01/2015: para verificar se esta executando processo de recontabilização */ 
  SELECT TRIM(UPPER(COALESCE(RDB$GET_CONTEXT('USER_SESSION', 'W_RECONTABILIZA'), '')))
  FROM RDB$DATABASE
  INTO :VRECONTABILIZANDO;

  SELECT COUNT(*)
  FROM tbloqlan_usuario tblu
  INNER JOIN tbloqlan_empresa tble ON (tble.bdcodemp = tblu.bdcodemp AND tble.bdcodblq = tblu.bdcodblq AND tble.bdcodble = tblu.bdcodble)
  INNER JOIN tbloqlan tbloq ON (tbloq.bdcodblq = tble.bdcodblq)
  WHERE tbloq.bdcodsis = 4
  AND UPPER(tbloq.bdrecurso) = UPPER('frlancamento')
  AND ((bddatainicial >= OLD.bddata AND (bddatafinal <= OLD.bddata OR bddatafinal IS NULL))
  OR (bddatainicial <= OLD.bddata AND ((bddatafinal BETWEEN OLD.bddata AND OLD.bddata) OR bddatafinal IS NULL))
  OR (bddatainicial <= OLD.bddata AND (bddatafinal >= OLD.bddata OR bddatafinal IS NULL)) )
  AND tble.bdcodemp = OLD.bdcodemp
  AND tblu.bdcodusu = :vcodusu
  INTO :vcodigo;

  /* sol.: #10892 Jean 19/01/2015: Lançar exceção somente se não estiver recontabilizando */
  IF ((VCODIGO > 0) AND (VRECONTABILIZANDO <> 'TRUE')) THEN
    EXCEPTION EX_BLOQLAN;

  --alt:15642 - 13/09/2016 - Quando for excluir lançamento manual, grava na tabela de log o tempo e quantidade de lançamentos, para não perder a estatística dos trabalhos realizados. Pedro
  IF (OLD.BDTIPOLAN = 1) THEN
    BEGIN
      -- gilberto - 14/08/2019 - estava inserindo log de exclusão de lançamento com usuários aleatórios
      if ((select upper(bdvalue) from vw_get_excluirempresas) <> 'TRUE') then
      begin
        vDataHora = DATEADD(SECOND, DATEDIFF(SECOND, CAST(OLD.BDDATALAN||' '||OLD.BDHORALAN AS TIMESTAMP), CAST(OLD.BDDATALANINICIAL||' '||OLD.BDHORALANINICIAL AS TIMESTAMP)), localtimestamp);
        EXECUTE PROCEDURE SP_INSERIR_LOG(OLD.BDCODEMP, NULL, OLD.BDCODUSU, NULL, 4, NULL, vDataHora, vDataHora, '', 0, 13, 
                                         CURRENT_USER, 'SERVIDOR', 'TFRLANCAMENTO', 'Lançamentos contábeis', NULL, 'VSUC_EMPRESAS_TLAN', NULL, 'FALSE', vDataHora);
      end
    END
  VCONTADOREXCLUSAO = 0;
  select BDCOUNTER
  from VCT_LX_EMPRESAS_TLAN
  where BDCODEMP = old.BDCODEMP and
        BDCHAVE = old.BDCHAVE
  into :VCONTADOREXCLUSAO;
  if (VCONTADOREXCLUSAO >= 1) then
  begin
    VCONTADOREXCLUSAO = VCONTADOREXCLUSAO + 1;
    update or insert into VCT_LX_EMPRESAS_TLAN (BDCODEMP, BDCHAVE, BDTIPOLAN, BDCODUSU, BDCOUNTER)
    values (old.BDCODEMP, old.BDCHAVE, old.BDTIPOLAN, old.BDCODUSU, :VCONTADOREXCLUSAO)
    matching (BDCODEMP, BDCHAVE);
  end
  else
  begin
    VCONTADOREXCLUSAO = 1;
    insert into VCT_LX_EMPRESAS_TLAN (BDCODEMP, BDCHAVE, BDTIPOLAN, BDCODUSU)
    values (old.BDCODEMP, old.BDCHAVE, old.BDTIPOLAN, old.BDCODUSU);
  end
END^

CREATE OR ALTER trigger vsuc_empresas_tlanform_bi0 for vsuc_empresas_tlanform
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT bdresult FROM maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||NEW.bdcodemp, 'vsuc_empresas_tlan') INTO vCodigo;
      NEW.bdchave = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM vsuc_empresas_tlan WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           --select bdresult from maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||new.bdcodemp, 'vsuc_empresas_tlan') into vCodigo;
           NEW.bdchave = vCodigo;
         END
    END
  end
END^

CREATE OR ALTER trigger vsuc_empresas_tlanne_bi0 for vsuc_empresas_tlanne
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT bdresult FROM maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||NEW.bdcodemp, 'vsuc_empresas_tlan') INTO vCodigo;
      NEW.bdchave = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM vsuc_empresas_tlan WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           NEW.bdchave = vCodigo;
         END
    END
  end
END^

CREATE OR ALTER trigger vsuc_empresas_tlcc_bi0 for vsuc_empresas_tlcc
active before insert position 0
AS
   DECLARE VARIABLE vCodigo INTEGER;
   DECLARE VARIABLE vrefemp INTEGER;
   DECLARE VARIABLE vcodcentro INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT bdresult FROM maxsci('bdchave', 'bdcodemp, bdchave', 'bdcodemp = '||NEW.bdcodemp, 'vsuc_empresas_tlan') INTO  vcodigo;
     END
  ELSE
     BEGIN
       SELECT tlan.bdchave
       FROM vsuc_empresas_tlan tlan
       WHERE tlan.bdcodemp = NEW.bdcodemp
       AND tlan.bdchave = NEW.bdchave
       INTO :vcodigo;
     END


  NEW.bdchave = vcodigo;
  end
END^

CREATE OR ALTER trigger vsuc_empresas_tnot_explic_bi0 for vsuc_empresas_tnot_explicativas
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNota INTEGER;

BEGIN

  /* Trigger text */
  vcodigo = 0;
  vNota = 0;

  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdchave)+1),1) FROM VSUC_EMPRESAS_TNOT_EXPLICATIVAS INTO vcodigo;
        NEW.bdchave = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdchave FROM VSUC_EMPRESAS_TNOT_EXPLICATIVAS WHERE bdchave = NEW.bdchave INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdchave)+1),1) FROM VSUC_EMPRESAS_TNOT_EXPLICATIVAS INTO vcodigo;
            NEW.bdchave = vcodigo;
         END
    END

  IF ((NEW.bdcodnota IS NULL) OR (NEW.bdcodnota = 0)) THEN
     BEGIN
        -- select coalesce((max(bdcodnota)+1),1) from VSUC_EMPRESAS_TNOT_EXPLICATIVAS into vNota;
        IF (NEW.bdcodemp > 0) THEN
           SELECT COALESCE((MAX(bdcodnota)+1), 1) FROM VSUC_EMPRESAS_TNOT_EXPLICATIVAS WHERE (bdcodemp = NEW.bdcodemp) AND (BDCODPLAPADRAO = NEW.BDCODPLAPADRAO)
                                                       AND (BDCODTPLA = NEW.BDCODTPLA) AND (BDREFERENCIA = NEW.BDREFERENCIA) INTO vNota;
        ELSE
           SELECT COALESCE((MAX(bdcodnota)+1), 1) FROM VSUC_EMPRESAS_TNOT_EXPLICATIVAS WHERE  (bdcodemp IS NULL) AND (BDCODPLAPADRAO = NEW.BDCODPLAPADRAO)
                                                       AND (BDCODTPLA = NEW.BDCODTPLA) AND (BDREFERENCIA = NEW.BDREFERENCIA) INTO vNota;

        NEW.bdcodnota = vNota;
     END
  ELSE
    BEGIN
       SELECT bdcodnota FROM VSUC_EMPRESAS_TNOT_EXPLICATIVAS WHERE (bdcodnota = NEW.bdcodnota)
                                                       AND (BDCODEMP = NEW.BDCODEMP)
                                                       AND (BDCODPLAPADRAO = NEW.BDCODPLAPADRAO)
                                                       AND (BDCODTPLA = NEW.BDCODTPLA)
                                                       AND (BDREFERENCIA = NEW.BDREFERENCIA)
                                                       INTO vNota;

       IF (vNota > 0) THEN
         BEGIN
            IF (NEW.bdcodemp > 0) THEN
               SELECT COALESCE((MAX(bdcodnota)+1), 1) FROM VSUC_EMPRESAS_TNOT_EXPLICATIVAS WHERE (bdcodemp = NEW.bdcodemp) AND (BDCODPLAPADRAO = NEW.BDCODPLAPADRAO)
                                                        AND (BDCODTPLA = NEW.BDCODTPLA) AND (BDREFERENCIA = NEW.BDREFERENCIA) INTO vNota;
            ELSE
           SELECT COALESCE((MAX(bdcodnota)+1), 1) FROM VSUC_EMPRESAS_TNOT_EXPLICATIVAS WHERE  (bdcodemp IS NULL) AND (BDCODPLAPADRAO = NEW.BDCODPLAPADRAO)
                                                       AND (BDCODTPLA = NEW.BDCODTPLA) AND (BDREFERENCIA = NEW.BDREFERENCIA) INTO vNota;

            NEW.bdcodnota = vNota;
         END
    END



END
^

CREATE OR ALTER TRIGGER VSUC_EMPRESAS_TORC_BI0 FOR VSUC_EMPRESAS_TORC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Ordem INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdOrdem IS NULL) OR (NEW.bdOrdem = 0)) THEN
    BEGIN
      SELECT bdresult+1 FROM maxsci('bdOrdem', 'bdcodemp, bdano, bdOrdem', 'bdcodemp = '||NEW.bdcodemp || ' AND ' || 'bdano = '||NEW.bdano , 'VSUC_EMPRESAS_TORC') INTO vNova_Ordem;

      NEW.bdOrdem = vNova_Ordem;
    END
  ELSE
    BEGIN
       SELECT bdOrdem FROM VSUC_EMPRESAS_TORC WHERE (bdOrdem = NEW.bdOrdem) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT bdresult+1 FROM maxsci('bdOrdem', 'bdcodemp, bdano, bdOrdem', 'bdcodemp = '||NEW.bdcodemp || ' AND ' || 'bdano = '||NEW.bdano, 'VSUC_EMPRESAS_TORC') INTO vNova_Ordem;
           NEW.bdOrdem = vNova_Ordem;
         END
    END

END
^

CREATE OR ALTER TRIGGER VSUC_EMPRESAS_TPRE_EXT_BAN_BI0 FOR VSUC_EMPRESAS_TPRE_EXT_BANCARIO
ACTIVE BEFORE INSERT POSITION 0 
AS
   DECLARE VARIABLE vCodigo INTEGER;
   DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
   vCodigo = 0;
   IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0))  THEN
      BEGIN
         SELECT COALESCE((MAX(bdchave)+1),1) FROM VSUC_EMPRESAS_TPRE_EXT_BANCARIO WHERE bdcodemp = NEW.bdcodemp and new.BDTIPOCONTA = BDTIPOCONTA  INTO vnova_chave;
         NEW.bdchave = vnova_chave;
      END
   ELSE
      BEGIN
         SELECT bdchave FROM VSUC_EMPRESAS_TPRE_EXT_BANCARIO WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) and (new.BDTIPOCONTA = BDTIPOCONTA) INTO vcodigo;

         IF (vcodigo > 0) THEN
            BEGIN
               SELECT COALESCE((MAX(bdchave)+1),1) FROM VSUC_EMPRESAS_TPRE_EXT_BANCARIO WHERE bdcodemp = NEW.bdcodemp and new.BDTIPOCONTA = BDTIPOCONTA INTO vnova_chave;
               NEW.bdchave = vnova_chave;
            END
      END
END
^

CREATE OR ALTER TRIGGER VSUC_TCONFIG_IMP_CC_BI0 FOR VSUC_TCONFIG_IMP_CC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE wCodigoCC INTEGER;
  DECLARE VARIABLE wCodigoLanc INTEGER;
BEGIN
  wCodigoCC = 0;
  wCodigoLanc = 0;

  IF ((NEW.BDCODIMPLANC IS NULL) OR (NEW.BDCODIMPLANC = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODIMPLANC), 1) FROM VSUC_TCONFIG_IMP_LANC INTO wCodigoLanc;
       NEW.BDCODIMPLANC = wCodigoLanc;
     END

  IF ((NEW.BDCODIMPCC IS NULL) OR (NEW.BDCODIMPCC = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODIMPCC)+1), 1) FROM VSUC_TCONFIG_IMP_CC WHERE (BDCODIMPLANC = NEW.BDCODIMPLANC) INTO wCodigoCC;
      NEW.BDCODIMPCC = wCodigoCC;
    END
  ELSE
    BEGIN
      SELECT BDCODIMPCC FROM VSUC_TCONFIG_IMP_CC
      WHERE (BDCODIMPCC = NEW.BDCODIMPCC) AND (BDCODIMPLANC = NEW.BDCODIMPLANC) INTO wCodigoCC;

      IF (wCodigoCC > 0) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCODIMPCC)+1), 1) FROM VSUC_TCONFIG_IMP_CC
          WHERE (BDCODIMPCC = NEW.BDCODIMPCC) INTO wCodigoCC;
          NEW.BDCODIMPCC = wCodigoCC;
        END
    END
END
^

CREATE OR ALTER TRIGGER VSUC_TCONFIG_IMP_EXT_BIO FOR VSUC_TCONFIG_IMP_EXT
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE wCodigo INTEGER;
BEGIN
  wCodigo = 0;
  IF ((NEW.BDCODEXTBANC IS NULL) OR (NEW.BDCODEXTBANC = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(BDCODEXTBANC)+1), 1)
       FROM VSUC_TCONFIG_IMP_EXT
       INTO wCodigo;

       NEW.BDCODEXTBANC = wCodigo;
     END
END
^

/* Trigger: TARQUIVOS_SCI_BI0 */
CREATE OR ALTER TRIGGER TARQUIVOS_SCI_BI0 FOR TARQUIVOS_SCI
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;

BEGIN
  IF ((NEW.bdcodarqsci IS NULL) OR (NEW.bdcodarqsci = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodarqsci) + 1, 1) FROM TARQUIVOS_SCI INTO :vcod;
       NEW.bdcodarqsci = vcod;
     END
END
^

CREATE OR ALTER TRIGGER VSUC_TCONFIG_IMP_LANC_BIO FOR VSUC_TCONFIG_IMP_LANC
ACTIVE BEFORE INSERT POSITION 0 
AS
  DECLARE VARIABLE wCodigo INTEGER;
BEGIN
  wCodigo = 0;
  IF ((NEW.BDCODIMPLANC IS NULL) OR (NEW.BDCODIMPLANC = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(BDCODIMPLANC)+1), 1)
       FROM VSUC_TCONFIG_IMP_LANC
       INTO wCodigo;

       NEW.BDCODIMPLANC = wCodigo;
     END
END
^

CREATE OR ALTER TRIGGER VSUC_BASE_FORMULA_TLINHAS_BI0 FOR VSUC_BASE_FORMULA_TLINHAS
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcodigo INTEGER;
BEGIN
  IF ((NEW.bdcodlinha IS NULL) OR (NEW.bdcodlinha = 0)) THEN
  BEGIN
    SELECT COALESCE(MAX(bdcodlinha), 0)+1 FROM vsuc_base_formula_tlinhas WHERE bdcodpfor = NEW.bdcodpfor INTO :vcodigo;
    NEW.bdcodlinha = vcodigo;
  END
END
^

CREATE OR ALTER TRIGGER VSUC_BASE_FORMULA_TCOLUNAS_BI0 FOR VSUC_BASE_FORMULA_TCOLUNAS
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcodigo INTEGER;
BEGIN
  IF ((NEW.bdcodcoluna IS NULL) OR (NEW.bdcodcoluna = 0)) THEN
  BEGIN
    SELECT COALESCE(MAX(bdcodcoluna), 0)+1 FROM vsuc_base_formula_tcolunas WHERE bdcodpfor = NEW.bdcodpfor INTO :vcodigo;
    NEW.bdcodcoluna = vcodigo;
  END
END
^

CREATE OR ALTER TRIGGER vct_empresa_tobstarefa_ai0 FOR vct_empresa_tobstarefa
ACTIVE AFTER INSERT POSITION 0
AS
BEGIN
  IF (((NEW.bdassunto IS NULL) OR (NEW.bdassunto = '')) AND ((NEW.bddescricao IS NULL) OR (NEW.bddescricao = ''))) THEN
     BEGIN
       DELETE FROM vct_empresa_tobstarefa
       WHERE bdcodemp = NEW.bdcodemp
       AND bdcodusu = NEW.bdcodusu
       AND bdcodst = NEW.bdcodst
       AND bdcodobs = NEW.bdcodobs;
     END
  ELSE
    BEGIN
      UPDATE VCT_EMPRESA_THISTORICOTAREFA HIST SET HIST.BDCODSITWEB = 3 WHERE HIST.BDCODEMP = NEW.BDCODEMP AND HIST.BDCODST = NEW.BDCODST
      AND HIST.BDCODHT = (SELECT MAX(BDCODHT) FROM VCT_EMPRESA_THISTORICOTAREFA WHERE BDCODEMP = HIST.BDCODEMP AND BDCODST = HIST.BDCODST);
    END
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERRECIFE_BI0 FOR VEF_EMP_TMOVSERRECIFE
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
END
^


CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERCABIPM_BI0 FOR VEF_EMP_TMOVSERCABIPM
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END


END
^

CREATE OR ALTER trigger vef_emp_tmoventpr_bi0 for vef_emp_tmoventpr
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
  declare variable VORDEMLAN INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    VCHAVELAN = NEW.BDCHAVE;
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

    if ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) then
     BEGIN
       SELECT COALESCE((MAX(BDCHAVE)+1),1) FROM VEF_EMP_TMOVENTITENS WHERE BDCODEMP = NEW.BDCODEMP AND BDCHAVE = :VCHAVELAN INTO VORDEMLAN;
       NEW.BDORDEM = VORDEMLAN;
     END
  end
END
^

CREATE OR ALTER trigger vef_emp_tmovsaipr_bi0 for vef_emp_tmovsaipr
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
  DECLARE VARIABLE vORDEMLAN INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  VCHAVELAN = NEW.BDCHAVE;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

  if ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) then
     BEGIN
       SELECT COALESCE((MAX(BDCHAVE)+1),1) FROM VEF_EMP_TMOVSAIITENS WHERE BDCODEMP = NEW.BDCODEMP AND BDCHAVE = :VCHAVELAN INTO VORDEMLAN;
       NEW.BDORDEM = VORDEMLAN;
     END
  end
END
^

CREATE OR ALTER trigger vef_emp_tmovserpr_bi0 for vef_emp_tmovserpr
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
  DECLARE VARIABLE vORDEMLAN INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    VCHAVELAN = NEW.BDCHAVE;
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

     if ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) then
     BEGIN
       SELECT COALESCE((MAX(BDCHAVE)+1),1) FROM VEF_EMP_TMOVSERITENS WHERE BDCODEMP = NEW.BDCODEMP AND BDCHAVE = :VCHAVELAN INTO VORDEMLAN;
       NEW.BDORDEM = VORDEMLAN;
     END
  end
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVDEMAISDOCPR_BI0 FOR VEF_EMP_TMOVDEMAISDOCPR
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tmovdemaisdoc_F100 WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
END
^


/* Início sol: 16067 Morgana */
CREATE OR ALTER TRIGGER vfin_esc_tcontrato_au0 FOR vfin_esc_tcontrato
ACTIVE AFTER UPDATE POSITION 0
AS
  DECLARE VARIABLE vnewbddatafin INTEGER;
  DECLARE VARIABLE voldbddatafin INTEGER;
BEGIN
   /* Sol: 18826 Morgana. 30/06/2017. Comentado implementação abaixo pois ao alterar a data final do contrato
   não deverá mais atualizar a referência final de todos os serviços fixos. Codificação feita na aplicação.*/

   /*if (new.bddatafin is null) then
      vnewbddatafin = 0;
   else
     vnewbddatafin = cast((select bdaaaamm FROM aaaamm(new.bddatafin)) as integer);

   if (old.bddatafin is null) then
      voldbddatafin = 0;
   else
     voldbddatafin = cast((select bdaaaamm FROM aaaamm(old.bddatafin)) as integer);

   if (vnewbddatafin <> voldbddatafin) then
      begin
       update vfin_esc_tservicofixo set bdreffin = :vnewbddatafin
       where (bdcodcli = new.bdcodcli) and
             (bdcodesc = new.bdcodesc) and
             (bdcodcontr = new.bdcodcontr);
     end*/
END
^
/* Fim sol: 16067 Morgana */

CREATE OR ALTER TRIGGER VRH_BASE_TRETORNO_QC_BI0 FOR VRH_BASE_TRETORNO_QC
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  /* Trigger text */
  IF (NEW.BDCODIGO IS NULL) THEN
    BEGIN
      SELECT COALESCE(MAX(BDCODIGO),0) + 1 FROM VRH_BASE_TRETORNO_QC INTO NEW.BDCODIGO;
    END
END
^

CREATE OR ALTER TRIGGER vfin_esc_tregprorrogsitcli_bi0 FOR vfin_esc_tregprorrogsitcli
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdordemprorrog IS NULL) OR (NEW.bdordemprorrog = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordemprorrog)+1),1) FROM VFIN_ESC_TREGPRORROGSITCLI WHERE bdcodcli = NEW.bdcodcli INTO vCodigo;
      NEW.bdordemprorrog = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdordemprorrog FROM VFIN_ESC_TREGPRORROGSITCLI WHERE bdcodcli = NEW.bdcodcli AND bdordemprorrog = NEW.bdordemprorrog INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemprorrog) + 1), 1) FROM VFIN_ESC_TREGPRORROGSITCLI WHERE bdcodcli = NEW.bdcodcli INTO vCodigo;
           NEW.bdordemprorrog = vCodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TOL_VEF_DRCST_TC197SAI_AD0 FOR TOL_VEF_DRCST_TC197SAI
ACTIVE AFTER DELETE POSITION 0
AS
begin
  DELETE FROM VEF_EMP_TC197SAI WHERE BDCODEMP = OLD.BDCODEMP AND BDCHAVE = OLD.BDCHAVE AND BDORDEMOBS = OLD.BDORDEMOBS AND BDORDEMOUTOBR = OLD.BDORDEMOUTOBR;
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_DRCST_TE111_AD0 FOR TOL_VEF_EMP_DRCST_TE111
ACTIVE AFTER DELETE POSITION 0
AS
begin
  DELETE FROM VEF_EMP_TAJUICMSE111 WHERE BDCODEMP = OLD.BDCODEMP AND BDORDEME111220 = OLD.BDORDEME111220;
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TICMSSPEDGER_E1_AD0 FOR TOL_VEF_EMP_TICMSSPEDGER_E111
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  DELETE FROM VEF_EMP_TAJUICMSE111 WHERE BDCODEMP = OLD.BDCODEMP AND BDORDEME111220 = OLD.BDORDEME111220;
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TBLOCOPGER_CPRB_AD0 FOR TOL_VEF_EMP_TBLOCOPGER_CPRB
ACTIVE AFTER DELETE POSITION 0
AS
begin
  DELETE FROM VEF_EMP_TLANAJU_R2060 WHERE BDCODEMP = OLD.BDCODEMP AND BDCHAVE = OLD.BDCHAVE;
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TICMSSPED_C185_AD0 FOR TOL_VEF_EMP_TICMSSPED_C185
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  DELETE FROM VEF_EMP_TMOVC185_1250 C185 WHERE C185.BDCODEMP = OLD.BDCODEMP AND C185.BDCHAVE = OLD.BDCHAVE AND C185.BDORDEM = OLD.BDORDEM AND C185.BDORDEMPRO = OLD.BDORDEMPRO;
END^


CREATE OR ALTER TRIGGER TOL_VEF_EMP_TICMSSPEDE116_AD0 FOR TOL_VEF_EMP_TICMSSPEDGER_E116
ACTIVE AFTER DELETE POSITION 0
AS
begin
  DELETE FROM VEF_EMP_TAJUICMSE116 WHERE BDCODEMP = OLD.BDCODEMP AND BDORDEME116250 = OLD.BDORDEME116250;
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TICMSSPED_C380_AD0 FOR TOL_VEF_EMP_TICMSSPED_C380
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  DELETE FROM VEF_EMP_TMOVC380_1250 C380 WHERE C380.BDCODEMP = OLD.BDCODEMP AND C380.BDCHAVE = OLD.BDCHAVE AND C380.BDORDEM = OLD.BDORDEM AND C380.BDORDEMPRO = OLD.BDORDEMPRO;
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TICMSSPED_C480_AD0 FOR TOL_VEF_EMP_TICMSSPED_C480
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  DELETE FROM VEF_EMP_TMOVC480_1250 C480 WHERE C480.BDCODEMP = OLD.BDCODEMP AND C480.BDCHAVE = OLD.BDCHAVE AND C480.BDORDEMDOCECF = OLD.BDORDEMDOCECF AND C480.BDORDEMITEM = OLD.BDORDEMITEM;
END
^
CREATE OR ALTER TRIGGER TOL_VEF_EMP_TICMSSPED_C180_AD0 FOR TOL_VEF_EMP_TICMSSPED_C180
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
    UPDATE VEF_EMP_TMOVC180_1250 C180 SET
    BDCODARRECADACO      = NULL,
    BDQTDCONVERTIDA      = NULL,
    BDVLRUNICONVERTIDO   = NULL,
    BDVLRUNITICMSST      = NULL,
    BDBCUNITICMSST       = NULL,
    BDVLRUNITICMSOP      = NULL,
    BDVLRUNITFCPST       = NULL
    WHERE C180.BDCODEMP = OLD.BDCODEMP
          AND C180.BDCHAVE = OLD.BDCHAVE
          AND C180.BDORDEM = OLD.BDORDEM
          AND C180.BDORDEMPRO = OLD.BDORDEMPRO;
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TICMSSPED_C186_AD0 FOR TOL_VEF_EMP_TICMSSPED_C186
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  DELETE FROM VEF_EMP_TMOVC186_1250 C186 WHERE C186.BDCODEMP = OLD.BDCODEMP AND C186.BDCHAVE = OLD.BDCHAVE AND C186.BDORDEM = OLD.BDORDEM AND C186.BDORDEMPRO = OLD.BDORDEMPRO;
END
^

CREATE OR ALTER trigger TOL_VEF_EMP_TICMSSPED_C181_AD0 for TOL_VEF_EMP_TICMSSPED_C181
active after delete position 0
AS
begin
  /* Trigger text */
  UPDATE VEF_EMP_TMOVC181_1250 C181 SET
  BDQTDCONVERTIDA              = NULL,
  BDVLRUNICONVERTIDO           = NULL,
  BDVLRUNITICMSEFETIVO         = NULL,
  BDVLRUNITICMSOPESTOQUE       = NULL,
  BDVLRUNITICMSSTESTOQUE       = NULL,
  BDVLRUNITICMSSTRESTITUIR     = NULL,
  BDVLRUNITICMSSTCOMPLEMENTAR  = NULL,
  BDCODUNIMED                  = NULL,
  BDVLRUNITICMSOP              = NULL,
  BDVLRUNITFCPSTESTOQUE        = NULL,
  BDVLRUNITFCPSTRESTITUIR      = NULL,
  BDVLRUNITFCPSTCOMPLEMENTAR   = NULL
  WHERE BDCODEMP = OLD.BDCODEMP
  AND BDCHAVE = OLD.BDCHAVE
  AND BDORDEM = OLD.BDORDEM
  AND BDORDEMPRO = OLD.BDORDEMPRO;
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_TFASEAMENTO_BI0 FOR VRH_ESOCIAL_TFASEAMENTO
ACTIVE BEFORE INSERT POSITION 0
as
declare variable VDATAINIATIVEMP date;
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  IF ((NEW.bdcodemp IS NULL) OR (NEW.bdcodemp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
        WHERE (bdstatusemp <> 1) INTO vcodigo;

        NEW.bdcodemp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodemp FROM tempresas WHERE bdcodemp = NEW.bdcodemp INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodemp)),1) FROM tempresas
            WHERE (bdstatusemp <> 1) INTO vcodigo;

            NEW.bdcodemp = vcodigo;
         END
    END

  if ((new.BDDATAINITABELA is null) and (new.BDOPCAOESOCIAL = 2)) then
  begin
    select EMP.BDDATAINIATIVEMP
    from TEMPRESAS EMP
    where EMP.BDCODEMP = new.BDCODEMP
    into VDATAINIATIVEMP;

    new.BDDATAINITABELA = VDATAINIATIVEMP;
    new.BDDATAININAOPERIOD = VDATAINIATIVEMP;
    new.BDDATAINIPERIOD = VDATAINIATIVEMP;
    new.BDDATAINISST = VDATAINIATIVEMP;

    if (VDATAINIATIVEMP <= '01-01-2017') then
      new.BDDATAINITABELA = '01-01-2018';

    if (VDATAINIATIVEMP <= '03-01-2017') then
      new.BDDATAININAOPERIOD = '03-01-2018';

    if (VDATAINIATIVEMP <= '05-01-2017') then
      new.BDDATAINIPERIOD = '05-01-2018';

    if (VDATAINIATIVEMP <= '01-01-2018') then
      new.BDDATAINISST = '01-01-2018';

  end

  select BDDATA
  from SP_PARSE_DATE(new.BDDATAINITABELA, 'YYYYMM')
  into new.BDREFINITABELA;

  select BDDATA
  from SP_PARSE_DATE(new.BDDATAININAOPERIOD, 'YYYYMM')
  into new.BDREFININAOPERIOD;

  select BDDATA
  from SP_PARSE_DATE(new.BDDATAINIPERIOD, 'YYYYMM')
  into new.BDREFINIPERIOD;

  select BDDATA
  from SP_PARSE_DATE(new.BDDATAINISST, 'YYYYMM')
  into new.BDREFINISST;

  update TEMPRESAS
  set BDDATAINIESOCIAL = new.BDDATAINITABELA
  where BDCODEMP = new.BDCODEMP;
end
^


CREATE OR ALTER TRIGGER VRH_ESOCIAL_TFASEAMENTO_BU0 FOR VRH_ESOCIAL_TFASEAMENTO
ACTIVE BEFORE UPDATE POSITION 0
as
declare variable VDATAINIATIVEMP date;
begin

  if ((new.BDDATAINITABELA is null) and (new.BDOPCAOESOCIAL = 2)) then
  begin
    select EMP.BDDATAINIATIVEMP
    from TEMPRESAS EMP
    where EMP.BDCODEMP = new.BDCODEMP
    into VDATAINIATIVEMP;

    new.BDDATAINITABELA = VDATAINIATIVEMP;
    new.BDDATAININAOPERIOD = VDATAINIATIVEMP;
    new.BDDATAINIPERIOD = VDATAINIATIVEMP;
    new.BDDATAINISST = VDATAINIATIVEMP;    

    if (VDATAINIATIVEMP <= '01-01-2017') then
      new.BDDATAINITABELA = '01-01-2018';

    if (VDATAINIATIVEMP <= '03-01-2017') then
      new.BDDATAININAOPERIOD  = '03-01-2018';

    if (VDATAINIATIVEMP <= '05-01-2017') then
      new.BDDATAINIPERIOD = '05-01-2018';

    if (VDATAINIATIVEMP <= '01-01-2018') then
      new.BDDATAINISST = '01-01-2018';

  end

  select BDDATA
  from SP_PARSE_DATE(new.BDDATAINITABELA, 'YYYYMM')
  into new.BDREFINITABELA;
    
  select BDDATA
  from SP_PARSE_DATE(new.BDDATAININAOPERIOD, 'YYYYMM')
  into new.BDREFININAOPERIOD;
    
  select BDDATA
  from SP_PARSE_DATE(new.BDDATAINIPERIOD, 'YYYYMM')
  into new.BDREFINIPERIOD;
    
  select BDDATA
  from SP_PARSE_DATE(new.BDDATAINISST, 'YYYYMM')
  into new.BDREFINISST;

  update TEMPRESAS
  set BDDATAINIESOCIAL = new.BDDATAINITABELA
  where BDCODEMP = new.BDCODEMP;

  if ((old.BDOPCAOESOCIAL = 1) and (new.BDOPCAOESOCIAL <> old.BDOPCAOESOCIAL)) then
  begin
    update TEMPRESAS E
    set BDEXPINIESOCIAL = 'FALSE'
    where E.BDCODEMP in (select E2.BDCODEMP
                         from TEMPRESAS E2
                         where E2.BDCODEMP = new.BDCODEMP or E2.BDCODMATRIZ = new.BDCODEMP);

    /*delete from VRH_ESOCIAL_INCONFORMIDADES INC
    where INC.BDCODEMP = new.BDCODEMP;*/
  end

end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TF100AUTOFOLHA_AD0 FOR TOL_VEF_EMP_TF100AUTOFOLHA
ACTIVE AFTER DELETE POSITION 0
AS
begin
  /* Trigger text */
  IF (COALESCE(OLD.BDORIGEM,0) = 0) THEN
     DELETE FROM vrh_base_tservterc tnf WHERE tnf.bdcodemp = OLD.bdcodemp AND tnf.bdcodserv = OLD.bdchaverh AND tnf.bdcodter = OLD.bdcodterrh;
end
^

CREATE OR ALTER procedure SP_GET_DATAS_FASEAMENTO (
    BDTERECEIROGRUPO integer,
    BDDATAINIATIVEMP date,
    BDDATAEVTTABELA date)
returns (
    BDDATAINITABELA date,
    BDDATAININAOPERIOD date,
    BDDATAINIPERIOD date,
    BDDATAINISST date,
    BDREFINIDCTFWEB integer)
as
declare variable VDATASSTGRUPO3 date;
declare variable VDATASSTGRUPO2 date;
declare variable VDATASSTGRUPO1 date;
declare variable VDATAPERIODICOSGRUPO3 date;
declare variable VDATAPERIODICOSGRUPO2 date;
declare variable VDATAPERIODICOSGRUPO1 date;
declare variable VDATANAOPERIODICOSGRUPO3 date;
declare variable VDATANAOPERIODICOSGRUPO2 date;
declare variable VDATANAOPERIODICOSGRUPO1 date;
declare variable VDATATABELAGRUPO3 date;
declare variable VDATATABELAGRUPO2 date;
declare variable VDATATABELAGRUPO1 date;
declare variable VDATAINIATIVEMP date;
declare variable VREFINIDCTFWEBGRUPO3 integer;
declare variable VREFINIDCTFWEBGRUPO2 integer;
declare variable VREFINIDCTFWEBGRUPO1 integer;
begin
  VDATATABELAGRUPO1 = '01-01-2018';
  VDATANAOPERIODICOSGRUPO1 = '03-01-2018';
  VDATAPERIODICOSGRUPO1 = '05-01-2018';
  VDATASSTGRUPO1 = '06-08-2021';
  VREFINIDCTFWEBGRUPO1 = 201808;

  VDATATABELAGRUPO2 = '07-01-2018';
  VDATANAOPERIODICOSGRUPO2 = '10-10-2018';
  VDATAPERIODICOSGRUPO2 = '01-01-2019';
  VDATASSTGRUPO2 = '09-08-2021';
  VREFINIDCTFWEBGRUPO2 = 201904;
  if (BDDATAINIATIVEMP >= '01-01-2018') then
    VREFINIDCTFWEBGRUPO2 = 202107;

  VDATATABELAGRUPO3 = '01-01-2019';
  VDATANAOPERIODICOSGRUPO3 = '04-10-2019';
  VDATAPERIODICOSGRUPO3 = '05-01-2021';
  VDATASSTGRUPO3 = '01-10-2022';
  VREFINIDCTFWEBGRUPO3 = 202107;

  if (BDTERECEIROGRUPO = 1 and BDDATAEVTTABELA >= VDATATABELAGRUPO3) then
    begin
      BDDATAINITABELA = VDATATABELAGRUPO3;
      BDDATAININAOPERIOD = VDATANAOPERIODICOSGRUPO3;
      BDDATAINIPERIOD = VDATAPERIODICOSGRUPO3;
      BDDATAINISST = VDATASSTGRUPO3;
      BDREFINIDCTFWEB = VREFINIDCTFWEBGRUPO3;

      if (BDDATAINIATIVEMP > BDDATAINITABELA) then
        BDDATAINITABELA = BDDATAINIATIVEMP;

      if (BDDATAINIATIVEMP > BDDATAININAOPERIOD) then
        BDDATAININAOPERIOD = BDDATAINIATIVEMP;

      if (BDDATAINIATIVEMP > BDDATAINIPERIOD) then
        BDDATAINIPERIOD = BDDATAINIATIVEMP;

      if (BDDATAINIATIVEMP > BDDATAINISST) then
        BDDATAINISST = BDDATAINIATIVEMP;
    end
  else if (BDTERECEIROGRUPO = 1 and BDDATAEVTTABELA >= VDATATABELAGRUPO2) then
    begin
      BDDATAINITABELA = VDATATABELAGRUPO2;
      BDDATAININAOPERIOD = VDATANAOPERIODICOSGRUPO3;
      BDDATAINIPERIOD = VDATAPERIODICOSGRUPO3;
      BDDATAINISST = VDATASSTGRUPO3;
      BDREFINIDCTFWEB = VREFINIDCTFWEBGRUPO3;

      if (BDDATAINIATIVEMP > BDDATAINITABELA) then
        BDDATAINITABELA = BDDATAINIATIVEMP;

      if (BDDATAINIATIVEMP > BDDATAININAOPERIOD) then
        BDDATAININAOPERIOD = BDDATAINIATIVEMP;

      if (BDDATAINIATIVEMP > BDDATAINIPERIOD) then
        BDDATAINIPERIOD = BDDATAINIATIVEMP;

      if (BDDATAINIATIVEMP > BDDATAINISST) then
        BDDATAINISST = BDDATAINIATIVEMP;
    end
  else if (BDTERECEIROGRUPO = 0 and BDDATAEVTTABELA >= VDATATABELAGRUPO2) then
    begin
      BDDATAINITABELA = VDATATABELAGRUPO2;
      BDDATAININAOPERIOD = VDATANAOPERIODICOSGRUPO2;
      BDDATAINIPERIOD = VDATAPERIODICOSGRUPO2;
      BDDATAINISST = VDATASSTGRUPO2;
      BDREFINIDCTFWEB = VREFINIDCTFWEBGRUPO2;

      if (BDDATAINIATIVEMP > BDDATAINITABELA) then
        BDDATAINITABELA = BDDATAINIATIVEMP;

      if (BDDATAINIATIVEMP > BDDATAININAOPERIOD) then
        BDDATAININAOPERIOD = BDDATAINIATIVEMP;

      if (BDDATAINIATIVEMP > BDDATAINIPERIOD) then
        BDDATAINIPERIOD = BDDATAINIATIVEMP;

      if (BDDATAINIATIVEMP > BDDATAINISST) then
        BDDATAINISST = BDDATAINIATIVEMP;
    end
  else if ((BDTERECEIROGRUPO = 0) or ((BDTERECEIROGRUPO = 1 and BDDATAEVTTABELA = VDATATABELAGRUPO1))) then
    begin
      BDDATAINITABELA = VDATATABELAGRUPO1;
      BDDATAININAOPERIOD = VDATANAOPERIODICOSGRUPO1;
      BDDATAINIPERIOD = VDATAPERIODICOSGRUPO1;
      BDDATAINISST = VDATASSTGRUPO1;
      BDREFINIDCTFWEB = VREFINIDCTFWEBGRUPO1;
    end

  suspend;
end^

CREATE OR ALTER procedure SP_VRHF_SEGDESEMPREGO3MESES (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer = 0,
    PRCOVID19 integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDMAIORREMUNERACAO numeric(18,6),
    BDORIGEM smallint)
as
declare variable WREFRESCISAO integer;
declare variable WSQL varchar(10000);
declare variable WULTDIA integer;
declare variable WDATAFIM date;
declare variable WDATAINI date;
declare variable WCONTA integer;
declare variable WREMUNERACAO numeric(18,6);
declare variable WTIPOCOL integer;
declare variable WHORASMES numeric(18,6);
declare variable WTEMCALC smallint;
declare variable WVERMAIORREM DM_BOOLEAN;
declare variable WCLAVER varchar(7);
declare variable WSALBASE numeric(18,6);
declare variable WVINTREMUNERACAO numeric(18,6);
declare variable WREF integer;
declare variable W_PRIDIAMES date;
declare variable W_ULTDIAMES date;
declare variable WDATAADMCOL date;
declare variable WREFMAIORREMUN integer;
BEGIN
/*
  O retorno de BDORIGEM:

  1 = Cálculo
  2 = Ficha financeira de FGTS
  3 = Salário base atual
  0 = Não tem nada

*/
  wsql = 'SELECT TRIM(rdb$get_context(''USER_SESSION'', ''W_ANOMES'')), cast (rdb$get_context(''USER_SESSION'', ''W_PRIDIAMES'') as date), cast (rdb$get_context(''USER_SESSION'', ''W_ULTDIAMES'') as date) '||
         'FROM rdb$database ';
  EXECUTE STATEMENT wsql INTO :WREF, :W_PRIDIAMES, :W_ULTDIAMES;

  wtipocol = 0;
  wrefrescisao = NULL;
  IF ((prref IS NULL) OR (prref = 0)) THEN
     SELECT BDREFRESCISAO FROM VRH_EMP_TRESCISAO WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol INTO :wrefrescisao;
  ELSE
     wrefrescisao = prref;

  IF (wrefrescisao IS NOT NULL) THEN
     BEGIN
       IF (SUBSTRING(:wrefrescisao FROM 5 FOR 2) = '01') THEN
          wrefrescisao = CAST((CAST((CAST((SUBSTRING(:wrefrescisao FROM 1 FOR 4)) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
       ELSE
       IF (CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)) AS INTEGER) > 10) THEN
          wrefrescisao = SUBSTRING(:wrefrescisao FROM 1 FOR 4)||CAST((CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2));
       ELSE
          wrefrescisao = SUBSTRING(:wrefrescisao FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1));

       wconta = 1;
       WHILE (wconta <= 3) DO
         BEGIN
           bdcodemp = prcodemp;
           bdcodcol = prcodcol;
           bdreffn  = wrefrescisao;
           bdmaiorremuneracao = 0;
           wtemcalc = 0;
           bdorigem = 0;
           wsql = 'select COALESCE(VFOL.BDVALVFN,0.0), COALESCE(VFOL.BDVALVIFN,0.0), UPPER(VERREF.BDBASEMAIORVER), SUBSTRING(VER.BDCLAVER FROM 1 FOR 7) from VRHF_EMP_TVERBAFN VFOL '||
                  'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = VFOL.BDCODVER) '||
                  'join VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = VFOL.BDCODVER and '||
                  '                                     VERREF.BDREFVER = coalesce((select first 1 D2.BDREFVER '||
                  '                                                                 from VRH_BASE_TVERBAS_REF D2 '||
                  '                                                                 where VFOL.BDCODVER = D2.BDCODVER and '||
                  '                                                                       D2.BDREFVER <= (select cast(rdb$get_context(''USER_SESSION'', ''W_ANOMES'') as integer) '||
                  '                                                                                       from RDB$DATABASE) '||
                  '                                                                 order by D2.BDREFVER DESC), '||
                  '                                                                 (select first 1 D1.BDREFVER '||
                  '                                                                  from VRH_BASE_TVERBAS_REF D1 '||
                  '                                                                  where VFOL.BDCODVER = D1.BDCODVER))) '||
                  'where VFOL.BDCODEMP = '||prcodemp||' and VFOL.BDCODCOL = '||prcodcol||' and VFOL.BDREFFN = '||wrefrescisao;

           wsql = wsql||' UNION ALL ';
           wsql = wsql||
                  'select COALESCE(VFOL.BDVALVFT,0.0), COALESCE(VFOL.BDVALVIFT,0.0), UPPER(VERREF.BDBASEMAIORVER), SUBSTRING(VER.BDCLAVER FROM 1 FOR 7) from VRHF_EMP_TVERBATOMADOR VFOL '||
                  'join VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = VFOL.BDCODVER and '||
                  '                                     VERREF.BDREFVER = coalesce((select first 1 D2.BDREFVER '||
                  '                                                                 from VRH_BASE_TVERBAS_REF D2 '||
                  '                                                                 where VFOL.BDCODVER = D2.BDCODVER and '||
                  '                                                                       D2.BDREFVER <= (select cast(rdb$get_context(''USER_SESSION'', ''W_ANOMES'') as integer) '||
                  '                                                                                       from RDB$DATABASE) '||
                  '                                                                 order by D2.BDREFVER DESC), '||
                  '                                                                 (select first 1 D1.BDREFVER '||
                  '                                                                  from VRH_BASE_TVERBAS_REF D1 '||
                  '                                                                  where VFOL.BDCODVER = D1.BDCODVER))) '||
                  'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = VFOL.BDCODVER) '||
                  'where VFOL.BDCODEMP = '||prcodemp||' and VFOL.BDCODCOL = '||prcodcol||' and VFOL.BDREFTOMADOR = '||wrefrescisao;


           SELECT ULTDIA FROM ultimo_dia_mes(CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)) AS SMALLINT), CAST((SUBSTRING(:wrefrescisao FROM 1 FOR 4)) AS INTEGER)) INTO :wultdia;

           IF (wultdia < 10) THEN
              wdatafim = CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)||'-0'||wultdia||'-'||SUBSTRING(:wrefrescisao FROM 1 FOR 4)) AS DATE);
           ELSE
              wdatafim = CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)||'-'||wultdia||'-'||SUBSTRING(:wrefrescisao FROM 1 FOR 4)) AS DATE);

           wdataini = CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)||'-01-'||SUBSTRING(:wrefrescisao FROM 1 FOR 4)) AS DATE);

           wremuneracao = 0;
           wvintremuneracao = 0;

           SELECT BDTIPOCOL FROM VW_VRHF_EMP_TCOL_CALC WHERE BDCODEMP = :prcodemp AND BDCODCOL = :prcodcol  INTO :wtipocol;

           EXECUTE PROCEDURE sp_seta_competencia(:wrefrescisao, :wdataini, :wdatafim);
           FOR EXECUTE STATEMENT wsql INTO :wremuneracao, :wvintremuneracao, :wvermaiorrem, :wclaver DO
             BEGIN
               wtemcalc = 1;

               IF ((wtipocol <> 4) AND (wvermaiorrem = 'TRUE' AND wclaver <> '0.001.0' AND wclaver <> '0.001.1' AND wclaver <> '0.001.2')) THEN
                 BEGIN
                   IF (wvintremuneracao > 0) THEN
                     bdmaiorremuneracao = bdmaiorremuneracao + wvintremuneracao;
                   ELSE
                     bdmaiorremuneracao = bdmaiorremuneracao + wremuneracao;
                 END
               ELSE
                 IF ((wtipocol = 4) AND (wvermaiorrem = 'TRUE' AND wclaver <> '0.001.0' AND wclaver <> '0.001.2')) THEN --Para horistas especiais deve se considerar a verba '0.001.1'.
                   BEGIN
                     IF (wvintremuneracao > 0) THEN
                       bdmaiorremuneracao = bdmaiorremuneracao + wvintremuneracao;
                     ELSE
                       bdmaiorremuneracao = bdmaiorremuneracao + wremuneracao;
                   END
             END

           wsql = 'select first 1 COALESCE(COLVINCDIA.BDSALBASECOL,0.0), COALESCE(COLCALC.BDHORASMENSAISCOL,0.0) '||
                  'from VRH_EMP_TCOLCON COLCON '||
                  'left outer join VRH_EMP_TCOLCON_CALCDIA COLVINCDIA on (COLCON.BDCODEMP = COLVINCDIA.BDCODEMP and '||
                  '                                                       COLCON.BDCODCOL = COLVINCDIA.BDCODCOL and '||
                  '                                                       COLVINCDIA.BDDATACOL = coalesce((select first 1 D2.BDDATACOL '||
                  '                                                                                        from VRH_EMP_TCOLCON_CALCDIA D2 '||
                  '                                                                                        where D2.BDCODEMP = COLCON.BDCODEMP and '||
                  '                                                                                              D2.BDCODCOL = COLCON.BDCODCOL and '||
                  '                                                                                              D2.BDDATACOL <= (select cast(rdb$get_context(''USER_SESSION'', ''W_ULTDIAMES'') as date) '||
                  '                                                                                        from RDB$DATABASE) '||
                  '                                                                                        order by D2.BDDATACOL desc), '||
                  '                                                                                       (select first 1 D1.BDDATACOL '||
                  '                                                                                        from VRH_EMP_TCOLCON_CALCDIA D1 '||
                  '                                                                                        where D1.BDCODEMP = COLCON.BDCODEMP and '||
                  '                                                                                              D1.BDCODCOL = COLCON.BDCODCOL))) '||
                  'left outer join VRHF_EMP_TCOL_CALC COLCALC on (COLCALC.BDCODEMP = COLVINCDIA.BDCODEMP and '||
                  '                                               COLCALC.BDCODCOL = COLVINCDIA.BDCODCOL and '||
                  '                                               COLCALC.BDREFCOL = coalesce((select first 1 D2.BDREFCOL '||
                  '                                                                            from VRHF_EMP_TCOL_CALC D2 '||
                  '                                                                            where D2.BDCODEMP = COLVINCDIA.BDCODEMP and '||
                  '                                                                                  D2.BDCODCOL = COLVINCDIA.BDCODCOL and '||
                  '                                                                                  D2.BDREFCOL <= (select cast(rdb$get_context(''USER_SESSION'', ''W_ANOMES'') as integer) '||
                  '                                                                                                  from RDB$DATABASE) '||
                  '                                                                           order by D2.BDREFCOL DESC), '||
                  '                                                                           (select first 1 D1.BDREFCOL '||
                  '                                                                            from VRHF_EMP_TCOL_CALC D1 '||
                  '                                                                            where D1.BDCODEMP = COLVINCDIA.BDCODEMP and '||
                  '                                                                                  D1.BDCODCOL = COLVINCDIA.BDCODCOL))) '||
                  'where COLCON.BDCODEMP = '||prcodemp||' and COLCON.BDCODCOL = '||prcodcol;

           wremuneracao = 0;
           whorasmes = 0;
           wsalbase = 0;

           EXECUTE STATEMENT wsql INTO :wremuneracao, :whorasmes;

           IF (wtipocol = 2) THEN   -- Horista
              wsalbase = CAST((wremuneracao * whorasmes / 30 * wultdia) AS NUMERIC(18,2));
           ELSE
              wsalbase = CAST(wremuneracao AS NUMERIC(18,2));

           IF (wtemcalc = 1) THEN
              BEGIN
                bdmaiorremuneracao = bdmaiorremuneracao + wsalbase;
                bdorigem = 1;
              END

           IF (bdmaiorremuneracao = 0) THEN   -- Se não tiver cálculo o salário do mês não será adicionado e irá buscar da ficha de FGTS
              BEGIN
                wremuneracao = 0;
                wsql = 'select first 1 coalesce(FN.BDBFGTS_FFGTS, 0) from VRHF_EMP_TFICHAFGTS FN '||
                       'where FN.BDTIPO_FFGTS = 1 and FN.BDCODEMP = '||prcodemp||' and FN.BDCODCOL = '||prcodcol||' and FN.BDREF_FFGTS = '||wrefrescisao;
                EXECUTE STATEMENT wsql INTO :wremuneracao;
                bdmaiorremuneracao = bdmaiorremuneracao + wremuneracao;
              END


           wrefmaiorremun = 0;

           if (:PRREF > 0) then
             begin
               if (CAST((SUBSTRING(:PRREF FROM 5 FOR 2)) AS INTEGER) <= 10) then
                 wrefmaiorremun = SUBSTRING(:PRREF FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(:PRREF FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1));
               else
                 wrefmaiorremun = SUBSTRING(:PRREF FROM 1 FOR 4)|| CAST((CAST((SUBSTRING(:PRREF FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2));
             end

           IF (bdmaiorremuneracao = 0) THEN   -- Se não tiver ficha de FGTS o sistema joga o salário base atual
              BEGIN
                IF (((PRCOVID19 IS NULL) OR (PRCOVID19 = 0)) OR
                    (BDREFFN = wrefmaiorremun)) THEN
                   BEGIN
                     bdmaiorremuneracao = wsalbase;
                     bdorigem = 3;    -- Salário base
                   END
                ELSE
                   BEGIN
                     EXECUTE STATEMENT 'Select BDDATAADMCOL from VRH_EMP_TCOLCON WHERE BDCODEMP = ' || :BDCODEMP || ' AND BDCODCOL = '  || :BDCODCOL INTO :WDATAADMCOL;
                     if (BDREFFN >= CAST(SUBSTRING(:WDATAADMCOL FROM 1 FOR 4) || SUBSTRING(:WDATAADMCOL FROM 6 FOR 2) AS INTEGER)) then
                        BEGIN
                          bdmaiorremuneracao = wsalbase;
                          bdorigem = 3;    -- Salário base
                        END
                   END
              END
           ELSE
           IF ((bdorigem IS NULL) OR (bdorigem = 0)) THEN
              bdorigem = 2;  -- Ficha de FGTS


           SUSPEND;

           wconta = wconta + 1;

           IF (SUBSTRING(:wrefrescisao FROM 5 FOR 2) = '01') THEN
              wrefrescisao = CAST((CAST((CAST((SUBSTRING(:wrefrescisao FROM 1 FOR 4)) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
           ELSE
           IF (CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)) AS INTEGER) > 10) THEN
              wrefrescisao = SUBSTRING(:wrefrescisao FROM 1 FOR 4)||CAST((CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(2));
           ELSE
              wrefrescisao = SUBSTRING(:wrefrescisao FROM 1 FOR 4)||'0'||CAST((CAST((SUBSTRING(:wrefrescisao FROM 5 FOR 2)) AS INTEGER) - 1) AS VARCHAR(1));
         END
     END
  ELSE
     BEGIN
       bdcodemp = prcodemp;
       bdcodcol = prcodcol;
       bdreffn = NULL;
       bdmaiorremuneracao = 0;
       bdorigem = 0;
       SUSPEND;
     END

  EXECUTE PROCEDURE sp_seta_competencia(:WREF, :W_PRIDIAMES, :W_ULTDIAMES);
END^

CREATE OR ALTER PROCEDURE SP_VRHF_SIMULACAO_SEGDESEMPREGO (
    PRCODEMP INTEGER,
    PRCODCOL INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDQTDMESES INTEGER,
    BDMAIORREMUN NUMERIC(18,6))
AS
DECLARE VARIABLE WSQL VARCHAR(3000);
DECLARE VARIABLE WREF INTEGER;
BEGIN
  wsql = 'SELECT TRIM(rdb$get_context(''USER_SESSION'', ''W_ANOMES'')) FROM rdb$database';

  EXECUTE STATEMENT wsql INTO :WREF;

  wsql = 'select SD.BDCODEMP, SD.BDCODCOL, count(SD.BDREFFN) BDMESES, sum(SD.BDMAIORREMUNERACAO) BDSOMAMAIORREMUNERACAO '||
         'from SP_VRHF_SEGDESEMPREGO3MESES('||PRCODEMP||', '||PRCODCOL||', '||:WREF||') SD '||
         'group by SD.BDCODEMP, SD.BDCODCOL ';

  /* Ajustes na SP para executar novamente na atualizacao */
  EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDQTDMESES, :BDMAIORREMUN;
  SUSPEND;
END^


create or alter procedure VCT_EMPRESA_THISTORICO_STATUS (
    CODEMP integer,
    CODST integer,
    STATUS integer,
    OBRIGACAO integer = null,
    SERVICO integer = null,
    IMPOSTO integer = null,
    OBSERVACAO varchar(200) = null)
as
declare variable VNOMUSU varchar(40);
declare variable VCODUSU integer;
declare variable VCODEMP integer;
declare variable VCODIMP integer;
declare variable VCODGRUPO integer;
declare variable VCODST integer;
begin
  if ((OBSERVACAO is not null) and (trim(OBSERVACAO) = '')) then
     OBSERVACAO = null;

  -- Lançamento de usuários para solicitações de impostos
  if (imposto is not null) then
  begin
    if (codst is null) then
       select max(bdcodst) from VCT_EMPRESA_TSOLICITATAREFA where bdcodemp = :codemp and bdcodimp = :imposto into :vcodst;
    else
       vcodst = codst;

    IF (EXISTS (SELECT first 1 bdcodemp FROM vct_empresa_usuario_imp WHERE bdcodemp = :CODEMP AND bdcodimp = :IMPOSTO)) THEN
    BEGIN
      IF (EXISTS (SELECT first 1 bdcodemp FROM vct_empresa_usuario_imp WHERE bdcodemp = :codemp AND bdcodimp = :IMPOSTO AND bdcodusu IS NULL AND bdcodgrupo IS NULL)) THEN
      BEGIN
        INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODBHS, BDCODSITWEB)
                                                  VALUES (:CODEMP, :vCODST, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, :status, :OBSERVACAO, 2, 2);
      END
      ELSE
      BEGIN
        FOR SELECT DISTINCT sol.bdcodemp, sol.bdcodimp, sol.bdcodgrupo, sol.bdcodusu, usu.bdnomusu FROM (
            SELECT emp.bdcodemp, emp.bdcodimp, emp.bdcodgrupo, emp.bdcodusu FROM vct_empresa_usuario_imp emp
            INNER JOIN tusuario usu ON (usu.bdcodusu = emp.bdcodusu)
            WHERE(bdcodgrupo IS NULL)AND(emp.bdcodimp = :IMPOSTO)AND(emp.bdcodemp = :CODEMP)
            UNION ALL
            SELECT emp.bdcodemp, emp.bdcodimp, emp.bdcodgrupo, emp.bdcodusu FROM vct_empresa_usuario_imp emp
            INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = emp.bdcodgrupo AND usu.bdcodusu = emp.bdcodusu)
            WHERE(emp.bdcodgrupo IS NOT NULL)AND(emp.bdcodimp = :IMPOSTO)AND(emp.bdcodemp = :CODEMP)
            UNION ALL
            SELECT emp.bdcodemp, emp.bdcodimp, emp.bdcodgrupo, usu.bdcodusu FROM vct_empresa_usuario_imp emp
            INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = emp.bdcodgrupo)
            WHERE(emp.bdcodgrupo IS NOT NULL)AND(emp.bdcodusu IS NULL)AND(emp.bdcodimp = :IMPOSTO)AND(emp.bdcodemp = :CODEMP)
            ) AS sol
            LEFT OUTER JOIN tusuario usu ON (usu.bdcodusu = sol.bdcodusu)
            WHERE USU.BDCONTDESATIVOUSU = 'FALSE' --W154493 - Antony R. (17/03/2022)- Não lançar histórico para usuarios desativados
            ORDER BY bdcodemp, bdcodimp, bdcodgrupo, bdcodusu
            INTO :vcodemp, :vcodimp, :vcodgrupo, :vcodusu, :vnomusu DO
        BEGIN
          INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODBHS, BDCODSITWEB)
                                            VALUES (:vcodemp, :vCODST, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, :status, :OBSERVACAO, 2, 2);
        END
      END
    END
    ELSE
    BEGIN
      INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODBHS, BDCODSITWEB)
                                        VALUES (:CODEMP, :vCODST, NULL, NULL, CURRENT_DATE, CURRENT_TIME, :status, :OBSERVACAO, 2, 2);
    END
  end



  -- Lançamento de usuários para solicitações de obrigações
  if (obrigacao is not null) then
  begin
    if (codst is null) then
       select max(bdcodst) from VCT_EMPRESA_TSOLICITATAREFA where bdcodemp = :codemp and bdcodobrigacao = :obrigacao into :vcodst;
    else
       vcodst = codst;

    IF (EXISTS (SELECT first 1 bdcodemp FROM vct_empresa_usuario_obr WHERE bdcodemp = :CODEMP AND bdcodobrser = :OBRIGACAO)) THEN
    BEGIN
      IF (EXISTS (SELECT first 1 bdcodemp FROM vct_empresa_usuario_obr WHERE bdcodemp = :CODEMP AND bdcodobrser = :OBRIGACAO AND bdcodusu IS NULL AND bdcodgrupo IS NULL)) THEN
      BEGIN
        INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODBHS, BDCODSITWEB)
                                                  VALUES (:CODEMP, :vCODST, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, :status, :OBSERVACAO, 2, 2);
      END
      ELSE
      BEGIN
        FOR SELECT DISTINCT sol.bdcodemp, sol.bdcodobrser, sol.bdcodgrupo, sol.bdcodusu, usu.bdnomusu FROM (
            SELECT emp.bdcodemp, emp.bdcodobrser, emp.bdcodgrupo, emp.bdcodusu FROM vct_empresa_usuario_obr emp
            INNER JOIN tusuario usu ON (usu.bdcodusu = emp.bdcodusu)
            WHERE(bdcodgrupo IS NULL)AND(emp.bdcodobrser = :OBRIGACAO)
            UNION ALL
            SELECT emp.bdcodemp, emp.bdcodobrser, emp.bdcodgrupo, emp.bdcodusu FROM vct_empresa_usuario_obr emp
            INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = emp.bdcodgrupo AND usu.bdcodusu = emp.bdcodusu)
            WHERE(emp.bdcodgrupo IS NOT NULL)AND(emp.bdcodobrser = :OBRIGACAO)
            UNION ALL
            SELECT emp.bdcodemp, emp.bdcodobrser, emp.bdcodgrupo, usu.bdcodusu FROM vct_empresa_usuario_obr emp
            INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = emp.bdcodgrupo)
            WHERE(emp.bdcodgrupo IS NOT NULL)AND(emp.bdcodusu IS NULL)AND(emp.bdcodobrser = :OBRIGACAO)
            ) AS sol
            LEFT OUTER JOIN tusuario usu ON (usu.bdcodusu = sol.bdcodusu)
            WHERE sol.bdcodemp = :CODEMP AND USU.BDCONTDESATIVOUSU = 'FALSE' --W154493 - Antony R. (17/03/2022)- Não lançar histórico para usuarios desativados
            ORDER BY bdcodemp, bdcodobrser, bdcodgrupo, bdcodusu
            INTO :vcodemp, :vcodimp, :vcodgrupo, :vcodusu, :vnomusu DO
        BEGIN
          INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODBHS, BDCODSITWEB)
                                             VALUES (:vcodemp, :vCODST, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, :status, :OBSERVACAO, 2, 2);
        END
      END
    END
    ELSE
    BEGIN
      INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODBHS, BDCODSITWEB)
                                        VALUES (:CODEMP, :vCODST, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, :status, :OBSERVACAO, 2, 2);
    END
  end



  -- Lançamento de usuários para solicitações de serviços
  if (servico is not null) then
  begin
    if (codst is null) then
       select max(bdcodst) from VCT_EMPRESA_TSOLICITATAREFA where bdcodemp = :codemp and bdcodservico = :servico into :vcodst;
    else
       vcodst = codst;

    IF (EXISTS (SELECT first 1 bdcodemp FROM vct_empresa_usuario_ser WHERE bdcodemp = :CODEMP AND bdcodobrser = :SERVICO)) THEN
    BEGIN
      IF (EXISTS (SELECT first 1 bdcodemp FROM vct_empresa_usuario_ser WHERE bdcodemp = :CODEMP AND bdcodobrser = :SERVICO AND bdcodusu IS NULL AND bdcodgrupo IS NULL)) THEN
      BEGIN
        INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODBHS, BDCODSITWEB)
                                          VALUES (:CODEMP, :vCODST, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, :status, :OBSERVACAO, 2, 2);
      END
      ELSE
      BEGIN
        FOR SELECT DISTINCT sol.bdcodemp, sol.bdcodobrser, sol.bdcodgrupo, sol.bdcodusu, usu.bdnomusu FROM (
            SELECT emp.bdcodemp, emp.bdcodobrser, emp.bdcodgrupo, emp.bdcodusu FROM vct_empresa_usuario_ser emp
            INNER JOIN tusuario usu ON (usu.bdcodusu = emp.bdcodusu)
            WHERE(bdcodgrupo IS NULL)AND(emp.bdcodobrser = :SERVICO)
            UNION ALL
            SELECT emp.bdcodemp, emp.bdcodobrser, emp.bdcodgrupo, emp.bdcodusu FROM vct_empresa_usuario_ser emp
            INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = emp.bdcodgrupo AND usu.bdcodusu = emp.bdcodusu)
            WHERE(emp.bdcodgrupo IS NOT NULL)AND(emp.bdcodobrser = :SERVICO)
            UNION ALL
            SELECT emp.bdcodemp, emp.bdcodobrser, emp.bdcodgrupo, usu.bdcodusu FROM vct_empresa_usuario_ser emp
            INNER JOIN tgrupousuario_usuario usu ON (usu.bdcodgrupo = emp.bdcodgrupo)
            WHERE(emp.bdcodgrupo IS NOT NULL)AND(emp.bdcodusu IS NULL)AND(emp.bdcodobrser = :SERVICO)
            ) AS sol
            LEFT OUTER JOIN tusuario usu ON (usu.bdcodusu = sol.bdcodusu)
            WHERE sol.bdcodemp = :CODEMP AND USU.BDCONTDESATIVOUSU = 'FALSE' --W154493 - Antony R. (17/03/2022)- Não lançar histórico para usuarios desativados
            ORDER BY bdcodemp, bdcodobrser, bdcodgrupo, bdcodusu
            INTO :vcodemp, :vcodimp, :vcodgrupo, :vcodusu, :vnomusu DO
        BEGIN
          INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODBHS, BDCODSITWEB)
                                    VALUES (:vcodemp, :vCODST, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, :status, :OBSERVACAO, 2, 2);
        END
    END
    END
    ELSE
    BEGIN
      INSERT INTO VCT_EMPRESA_THISTORICOTAREFA (BDCODEMP, BDCODST, BDCODGRUPO, BDCODUSURESPONSAVEL, BDDATA, BDHORA, BDSTATUS, BDOBSERVACAO, BDCODBHS, BDCODSITWEB)
                                        VALUES (:CODEMP, :vCODST, :vcodgrupo, :vcodusu, CURRENT_DATE, CURRENT_TIME, :status, :OBSERVACAO, 2, 2);
    END
  END
end^

create or alter procedure VCT_ORCADO_REALIZADO (
    PRDATAINICIAL date,
    PRDATAFINAL date,
    PRTIPOCALCULO integer,
    PRCODEMP integer = null,
    PRREF integer = null,
    PRORCAMENTO boolean = true)
returns (
    BDCODEMP integer,
    BDNOMEMP varchar(100),
    BDREFEMP integer,
    BDFORMATRIBUTA_REAL varchar(15),
    BDCODENQFED_ORC varchar(15),
    BDCODENQFED_REAL varchar(15),
    BDFORMATRIBUTA_ORC varchar(15),
    BDREFCALC integer,
    BDCODSIS integer,
    BDNOMSIS varchar(100),
    BDDATA date,
    BD_ORC integer,
    BD_REAL integer,
    BDMAX integer,
    BDREFORC integer,
    BDDESCORC varchar(200))
as
declare variable WSELECT varchar(4000);
declare variable VDATA date;
declare variable WJOIN varchar(4000);
declare variable WSQL varchar(5000);
declare variable WCODSIS integer;
declare variable VDATAFINAL date;
BEGIN
  wcodsis = 0;
  if (prref is not null) then
  begin
    select bddata from sp_referencia_to_data(:prref, False) into :vdata;
    select bddata from sp_referencia_to_data(:prref, True) into :vdatafinal;
  end
  else
  begin
  VDATA = PRDATAINICIAL;
    vdatafinal = prdatafinal;
  end

  WHILE (VDATA <= vDATAFINAL) DO
  BEGIN
    BDREFCALC = EXTRACT(YEAR FROM VDATA)||LPAD(EXTRACT(MONTH FROM VDATA), 2, 0);

    /* SE VOCÊ SE PERGUNTAR PORQUÊ EXISTE ESSA REPETIÇÃO DE FOR EXECUTE STATEMENT É SIMPLES, AS TABELAS TODAS POSSUEM ALGUM CAMPO SENDO VIRTUAL OU NÃO DIFERENTES
       E PARA NÃO PRECISAR QUEBRAR A CABEÇA E FAZER UMNA TRABALHEIRA FOI IMPLEMENTADO DESSA MANEIRA SEPARADA PARA CADA ORCAMENTO*/
    IF (PRTIPOCALCULO = 1) THEN -- ORCAMENTO_CONTABIL
    BEGIN
      if (prorcamento) then
      begin
        WSQL = ' COALESCE(ORC.BDLANCTAQTD,0) AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDLANCTAMAX,0) AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(SELECT COUNT(TLAN.BDCHAVE) AS BDTOTLAN ';
      WSQL = WSQL||'FROM VSUC_EMPRESAS_TLAN TLAN ';
      WSQL = WSQL||'WHERE (TLAN.BDCODEMP = ORCEMP.BDCODEMP) ';
      WSQL = WSQL||'AND (TLAN.BDREFERENCIA = '||BDREFCALC||')';
      WSQL = WSQL||') AS BD_REAL,';
      WSQL = WSQL||'4 AS BDCODSIS,''CONTÁBIL'' AS BDNOMSIS';
      wcodsis = 4;
    END
    ELSE
    IF (PRTIPOCALCULO = 2) THEN -- ORCAMENTO_FISCAL_ENTRADAS
    BEGIN
      if (prorcamento) then
      begin
        WSQL = ' COALESCE(ORC.BDLANENTQTD,0) AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDLANENTMAX,0) AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(SELECT COUNT(TLAN.BDCHAVE) AS BDTOTLAN ';
      WSQL = WSQL||'FROM VEF_EMP_TMOVENT TLAN ';
      WSQL = WSQL||'WHERE(TLAN.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'AND(TLAN.BDREFLAN='||BDREFCALC||')) AS BD_REAL,';
      WSQL = WSQL||'3 AS BDCODSIS,''FISCAL'' AS BDNOMSIS';
      wcodsis = 3;
    END
    ELSE
    IF (PRTIPOCALCULO = 3) THEN -- ORCAMENTO_FISCAL_SAIDAS
    BEGIN
      if (prorcamento) then
      begin
        WSQL = ' COALESCE(ORC.BDLANSAIQTD,0) AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDLANSAIMAX,0) AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(SELECT COUNT(TLAN.BDCHAVE) AS BDTOTLAN ';
      WSQL = WSQL||'FROM VEF_EMP_TMOVSAI TLAN ';
      WSQL = WSQL||'WHERE(TLAN.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'AND(TLAN.BDREFLAN='||BDREFCALC||')) AS BD_REAL,';
      WSQL = WSQL||'3 AS BDCODSIS,''FISCAL'' AS BDNOMSIS';
      wcodsis = 3;
    END
    ELSE
    IF (PRTIPOCALCULO = 4) THEN -- ORCAMENTO_FISCAL_SERVICO
    BEGIN
      if (prorcamento) then
      begin
        WSQL = '((COALESCE(ORC.BDLANENTQTD,0)+COALESCE(ORC.BDLANSAIQTD,0))) AS BD_ORC,';
        WSQL = WSQL||'((COALESCE(ORC.BDSERENTMAX,0)+COALESCE(ORC.BDSERSAIMAX,0)) / 2) AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(SELECT COUNT(TLAN.BDCHAVE) AS BDTOTLAN ';
      WSQL = WSQL||'FROM VEF_EMP_TMOVSER TLAN ';
      WSQL = WSQL||'WHERE(TLAN.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'AND(TLAN.BDREFLAN='||BDREFCALC||')) AS BD_REAL,';
      WSQL = WSQL||'3 AS BDCODSIS,''FISCAL'' AS BDNOMSIS';
      wcodsis = 3;
    END
    ELSE
    IF (PRTIPOCALCULO = 5) THEN -- ORCAMENTO_FISCAL_RECEBIDO
    BEGIN
      if (prorcamento) then
      begin
        WSQL = 'COALESCE(ORC.BDSERENTQTD,0) AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDSERENTMAX,0) AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(SELECT COUNT(TLAN.BDCHAVE) AS BDTOTLAN ';
      WSQL = WSQL||'FROM VEF_EMP_TMOVSER TLAN ';
      WSQL = WSQL||'LEFT JOIN TOL_VEF_EMP_TSERAUTOFOLHA RH ON(RH.BDCODEMP=TLAN.BDCODEMP AND RH.BDCHAVEEF=TLAN.BDCHAVE)';
      WSQL = WSQL||'WHERE(TLAN.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'AND(TLAN.BDTIPLAN=1)';
      if (prorcamento) then
      begin
        WSQL = WSQL||'AND(((COALESCE(ORC.BDSERRECAUTRH,''FALSE'')=''TRUE'')OR((COALESCE(ORC.BDSERRECAUTRH,''FALSE'')=''FALSE'')';
        WSQL = WSQL||'AND(RH.BDCODEMP IS NULL))))';
      end
      WSQL = WSQL||'AND(TLAN.BDREFLAN='||BDREFCALC||')) AS BD_REAL,';
      WSQL = WSQL||'3 AS BDCODSIS,''FISCAL'' AS BDNOMSIS';
      wcodsis = 3;
    END
    ELSE
    IF (PRTIPOCALCULO = 6) THEN -- ORCAMENTO_FISCAL_EMITIDO
    BEGIN
      if (prorcamento) then
      begin
        WSQL = 'COALESCE(ORC.BDSERSAIQTD,0) AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDSERSAIMAX,0) AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(SELECT COUNT(TLAN.BDCHAVE) AS BDTOTLAN ';
      WSQL = WSQL||'FROM VEF_EMP_TMOVSER TLAN ';
      WSQL = WSQL||'WHERE(TLAN.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'AND((TLAN.BDTIPLAN IS NULL)OR(TLAN.BDTIPLAN=0))';
      WSQL = WSQL||'AND(TLAN.BDREFLAN='||BDREFCALC||')';
      WSQL = WSQL||') AS BD_REAL,';
      WSQL = WSQL||'3 AS BDCODSIS,''FISCAL'' AS BDNOMSIS';
      wcodsis = 3;
    END
    ELSE
    IF (PRTIPOCALCULO = 7) THEN -- FOLHA - Colaboradores Ativos
    BEGIN
      if (prorcamento) then
      begin
        WSQL = 'COALESCE(ORC.BDQTDCALCCOL,0)AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDCALCCOLMAX,0)AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
--      WSQL = WSQL||'(select COUNT(COLCON.BDCODCOL) as BDTOTLAN from VRH_EMP_TCOLCON COLCON ';
--      WSQL = WSQL||'left outer join VRH_EMP_TRESCISAO RESC on(RESC.BDCODEMP=COLCON.BDCODEMP and RESC.BDCODCOL=COLCON.BDCODCOL)';
--      WSQL = WSQL||'where(COLCON.BDCODEMP=orcemp.bdcodemp)';
--      WSQL = WSQL||'and(cast(extract(year from COLCON.BDDATAADMCOL)||lpad(extract(month from COLCON.BDDATAADMCOL),2,0) as integer)<='||BDREFCALC;
--      -- Gilberto - 28/01/2026 - #238516
----      WSQL = WSQL||'and((RESC.BDDATARESCISAO is null)or(cast(extract(year from RESC.BDDATARESCISAO)||lpad(extract(month from RESC.BDDATARESCISAO),2,0) as integer)>='||BDREFCALC||'))';
--      WSQL = WSQL||'and((RESC.BDDATARESCISAO is null)or(RESC.BDREFRESCISAO>='||BDREFCALC||'))';
--      -- Exceto estagiários, autônomos e pró-labore
--      WSQL = WSQL||'and not exists(select first 1 BDCODCOL from VRH_EMP_TCOLCON_VINC A ';
--      WSQL = WSQL||'join VRH_BASE_TCLASSE C on(C.BDCODCLA=A.BDCODCLA)';
--      WSQL = WSQL||'where(A.BDCODEMP=COLCON.BDCODEMP)';
--      WSQL = WSQL||'and(A.BDCODCOL=COLCON.BDCODCOL)';
--      WSQL = WSQL||'and(A.BDREFCOL=(select first 1 BDREFCOL from VRH_EMP_TCOLCON_VINC ';
--      WSQL = WSQL||'where(BDCODEMP=A.BDCODEMP)';
--      WSQL = WSQL||'and(BDCODCOL=A.BDCODCOL)';
--      WSQL = WSQL||'and(BDREFCOL<='||BDREFCALC||')';
--      WSQL = WSQL||'order by BDREFCOL desc))';
--      WSQL = WSQL||'and(C.BDGRUPOCLA in(2,3,5))';
--
--      WSQL = WSQL||'))) AS BD_REAL,';

-- Gilberto - 02/02/2026 - #238516
      wsql = wsql||'(select count(BDCHAVE) from(';
      wsql = wsql||'select X.BDCODCOL as BDCHAVE,X.BDCODEMP,X.BDREFERENCIA,X.BDTIPOCALC ';
      wsql = wsql||'from VRHF_EMP_TDADOSCALC_BAIXA X ';
      wsql = wsql||'join VW_VRH_EMP_TCOLCON_VINC A on(A.BDCODEMP=X.BDCODEMP and A.BDCODCOL=X.BDCODCOL)';
      wsql = wsql||'join VRH_BASE_TCLASSE C on(A.BDCODCLA=C.BDCODCLA and A.BDCODEMP=X.BDCODEMP and ';
      wsql = wsql||'A.BDCODCOL=X.BDCODCOL and C.BDGRUPOCLA=1)';
      wsql = wsql||'where(X.BDCODEMP=ORCEMP.BDCODEMP)';
      wsql = wsql||'and(X.BDREFERENCIA='||BDREFCALC||')';
      wsql = wsql||'and(X.BDTIPOCALC in(0,6,7)))';
      wsql = wsql||') AS BD_REAL,';
      WSQL = WSQL||'2 AS BDCODSIS,''FOLHA'' AS BDNOMSIS';
      wcodsis = 2;
    END
    ELSE
    IF (PRTIPOCALCULO = 8) THEN -- ORCAMENTO_LALUR_A
    BEGIN
      if (prorcamento) then
      begin
        WSQL = ' COALESCE(ORC.BDLALURAQTD,0) AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDLALURAMAX,0) AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(SELECT COUNT(TLAN.BDCODLLA) AS BDTOTLAN ';
      WSQL = WSQL||'FROM VLAL_EMPRESAS_TLLA TLAN ';
      WSQL = WSQL||'WHERE(TLAN.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'AND(CAST(EXTRACT(YEAR FROM TLAN.BDDATALANLLA)||LPAD(EXTRACT(MONTH FROM TLAN.BDDATALANLLA),2,0) AS INTEGER)='||BDREFCALC||')';
      WSQL = WSQL||') AS BD_REAL,';
      WSQL = WSQL||'7 AS BDCODSIS,''LALUR'' AS BDNOMSIS';
      wcodsis = 7;
    END
    ELSE
    IF (PRTIPOCALCULO = 9) THEN -- ORCAMENTO_LALUR_B
    BEGIN
      if (prorcamento) then
      begin
        WSQL = ' COALESCE(ORC.BDLALURBQTD,0) AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDLALURBMAX,0) AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(SELECT COUNT(TLAN.BDCODLLB) AS BDTOTLAN ';
      WSQL = WSQL||'FROM VLAL_EMPRESAS_TLLB TLAN ';
      WSQL = WSQL||'WHERE(TLAN.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'AND(CAST(EXTRACT(YEAR FROM TLAN.BDDATLANLLB)||LPAD(EXTRACT(MONTH FROM TLAN.BDDATLANLLB),2,0) AS INTEGER)='||BDREFCALC||')';
      WSQL = WSQL||') AS BD_REAL,';
      WSQL = WSQL||'7 AS BDCODSIS,''LALUR'' AS BDNOMSIS';
      wcodsis = 7;
    END
    ELSE
    IF (PRTIPOCALCULO = 10) THEN --  ORCAMENTO_BENS
    BEGIN
      if (prorcamento) then
      begin
        WSQL = ' COALESCE(ORC.BDATIVAQTD,0) AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDATIVAMAX,0) AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(SELECT COUNT(TLAN.BDCODBEM) AS BDTOTLAN ';
      WSQL = WSQL||'FROM EMPRESAS_TBEM TLAN ';
      WSQL = WSQL||'WHERE(TLAN.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'AND(CAST(EXTRACT(YEAR FROM TLAN.BDDATORIAQUIBEM)||LPAD(EXTRACT(MONTH FROM TLAN.BDDATORIAQUIBEM),2,0) AS INTEGER)='||BDREFCALC||')';
      WSQL = WSQL||') AS BD_REAL,';
      WSQL = WSQL||'6 AS BDCODSIS,''PATRIMÔNIO'' AS BDNOMSIS';
      wcodsis = 6;
    END
    ELSE
    IF (PRTIPOCALCULO = 11) THEN -- ORCAMENTO_ENQUADRAMENTO
    BEGIN
      WSQL = '0 AS BD_ORC, 0 AS BDMAX, 0 AS BD_REAL,';
      WSQL = WSQL||'0 AS BDCODSIS,'' '' AS BDNOMSIS';
      wcodsis = 1;
    END
    ELSE
    IF (PRTIPOCALCULO = 12) THEN -- ORCAMENTO_HONORARIO
    BEGIN
      if (prorcamento) then
      begin
        WSQL = ' COALESCE(ORC.BDHONORARIO,0) AS BD_ORC,';
        WSQL = WSQL||'0 AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(SELECT SUM(COALESCE(FAT.BDVALORFATURA, 0)) BDTOTLAN ';
      WSQL = WSQL||'FROM VFIN_ESC_TFATURA FAT ';
      WSQL = WSQL||'WHERE(FAT.BDCODCLI=EMP.BDCODCLI AND FAT.BDREFFAT='||BDREFCALC||')) AS BD_REAL,';
      WSQL = WSQL||'5 AS BDCODSIS,''FINANCEIRO'' AS BDNOMSIS';
      wcodsis = 5;
    END
    ELSE
    IF (PRTIPOCALCULO = 13) THEN --  ORCAMENTO_FATURAMENTO_FISCAL
    BEGIN
      if (prorcamento) then
      begin
        WSQL = ' COALESCE(ORC.BDVALFAT,0) AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDVALFATMAX,0) AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'0 AS BD_REAL,';
      WSQL = WSQL||'3 AS BDCODSIS,''FISCAL'' AS BDNOMSIS';
      wcodsis = 3;
    END
    ELSE
    IF (PRTIPOCALCULO = 14) THEN -- Folha Normal
    BEGIN
      if (prorcamento) then
      begin
        WSQL = ' COALESCE(ORC.BDQTDCALCCOL,0) AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDCALCCOLMAX,0) AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
--      WSQL = WSQL||'(select count(BDCODEMP) as BDTOTLAN ';
--     WSQL = WSQL||'from VRHF_EMP_TDADOSCALC_BAIXA TFN ';
--      WSQL = WSQL||'where(TFN.BDCODEMP=ORCEMP.BDCODEMP)';
--      WSQL = WSQL||'and(TFN.BDTIPOCALC in(0,6,7))';
--      WSQL = WSQL||'and(TFN.BDREFERENCIA='||BDREFCALC||')';
--      -- Exceto estagiários, autônomos e pró-labore
--      WSQL = WSQL||'and(not exists(select first 1 BDCODCOL from VRH_EMP_TCOLCON_VINC A ';
--      WSQL = WSQL||'join VRH_BASE_TCLASSE C on(C.BDCODCLA=A.BDCODCLA)';
--      WSQL = WSQL||'where(A.BDCODEMP=TFN.BDCODEMP)';
--      WSQL = WSQL||'and(A.BDCODCOL=TFN.BDCODCOL)';
--      WSQL = WSQL||'and(A.BDREFCOL=(select first 1 BDREFCOL from VRH_EMP_TCOLCON_VINC ';
--      WSQL = WSQL||'where(BDCODEMP=A.BDCODEMP)and(BDCODCOL=A.BDCODCOL)';
--      WSQL = WSQL||'and(BDREFCOL<=TFN.BDREFERENCIA)order by BDREFCOL desc))';
--      WSQL = WSQL||'and C.BDGRUPOCLA in(2,3,5)))';
--
--      WSQL = WSQL||') AS BD_REAL,';
--      WSQL = WSQL||'2 AS BDCODSIS,''FOLHA'' AS BDNOMSIS';
      
-- Gilberto - 02/02/2026 - #238516
      wsql = wsql||'(select count(BDCHAVE) from(';
      wsql = wsql||'select X.BDCODCOL as BDCHAVE,X.BDCODEMP,X.BDREFERENCIA,X.BDTIPOCALC ';
      wsql = wsql||'from VRHF_EMP_TDADOSCALC_BAIXA X ';
      wsql = wsql||'join VW_VRH_EMP_TCOLCON_VINC A on(A.BDCODEMP=X.BDCODEMP and A.BDCODCOL=X.BDCODCOL)';
      wsql = wsql||'join VRH_BASE_TCLASSE C on(A.BDCODCLA=C.BDCODCLA and A.BDCODEMP=X.BDCODEMP and ';
      wsql = wsql||'A.BDCODCOL=X.BDCODCOL and not C.BDGRUPOCLA in(2,3,5))';--C.BDGRUPOCLA in(2,3,5)
      wsql = wsql||'where(X.BDCODEMP=ORCEMP.BDCODEMP)';
      wsql = wsql||'and(X.BDREFERENCIA='||BDREFCALC||')';
      wsql = wsql||'and(X.BDTIPOCALC in(0,6,7)))';
      wsql = wsql||') AS BD_REAL,';
      WSQL = WSQL||'2 AS BDCODSIS,''FOLHA'' AS BDNOMSIS';      
      
      wcodsis = 2;
    END
    ELSE
    IF (PRTIPOCALCULO = 15) THEN -- Folha Complementar
    BEGIN
      if (prorcamento) then
      begin
        WSQL = 'COALESCE(ORC.BDQTDCALCFOLCOMP,0)AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDCALCFOLCOMPMAX,0)AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(select count(BDCODEMP) as BDTOTLAN ';
      WSQL = WSQL||'from VRHF_EMP_TDADOSCALC_BAIXA TFC ';
      WSQL = WSQL||'where(TFC.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'and(TFC.BDTIPOCALC=8)';
      WSQL = WSQL||'and(TFC.BDREFERENCIA='||BDREFCALC||')) AS BD_REAL,';
      WSQL = WSQL||'2 AS BDCODSIS,''FOLHA'' AS BDNOMSIS';
      wcodsis = 2;
    END
    ELSE
    IF (PRTIPOCALCULO = 16) THEN -- Serviços autônomos
    BEGIN
      if (prorcamento) then
      begin
        WSQL = 'COALESCE(ORC.BDQTDCALCAUT,0)AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDCALCAUTMAX,0)AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(select count(BDCODEMP) as BDTOTLAN ';
      WSQL = WSQL||'from VRHF_EMP_TDADOSCALC_BAIXA TSA ';
      WSQL = WSQL||'where(TSA.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'and(TSA.BDTIPOCALC=1)';
      WSQL = WSQL||'and(TSA.BDREFERENCIA='||BDREFCALC||')) AS BD_REAL,';
      WSQL = WSQL||'2 AS BDCODSIS,''FOLHA'' AS BDNOMSIS';
      wcodsis = 2;
    END
    ELSE
    IF (PRTIPOCALCULO = 17) THEN -- 13º salário
    BEGIN
      if (prorcamento) then
      begin
        WSQL = 'COALESCE(ORC.BDQTDCALC13,0)AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDCALC13MAX,0)AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(select count(BDCODEMP) as BDTOTLAN ';
      WSQL = WSQL||'from VRHF_EMP_TDADOSCALC_BAIXA T13SA ';
      WSQL = WSQL||'where(T13SA.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'and(T13SA.BDTIPOCALC=2)';
      WSQL = WSQL||'and(T13SA.BDREFERENCIA='||BDREFCALC||')) AS BD_REAL,';
      WSQL = WSQL||'2 AS BDCODSIS,''FOLHA'' AS BDNOMSIS';
      wcodsis = 2;
    END
    ELSE
    IF (PRTIPOCALCULO = 18) THEN -- Adiantamento 13º
    BEGIN
      if (prorcamento) then
      begin
        WSQL = 'COALESCE(ORC.BDQTDCALCADI13,0)AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDCALCADI13MAX,0)AS BDMAX, ';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(select count(BDCODEMP) as BDTOTLAN ';
      WSQL = WSQL||'from VRHF_EMP_TDADOSCALC_BAIXA TAD13 ';
      WSQL = WSQL||'where(TAD13.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'and(TAD13.BDTIPOCALC=3)';
      WSQL = WSQL||'and(TAD13.BDREFERENCIA='||BDREFCALC||')) AS BD_REAL,';
      WSQL = WSQL||'2 AS BDCODSIS,''FOLHA'' AS BDNOMSIS';
      wcodsis = 2;
    END
    ELSE
    IF (PRTIPOCALCULO = 19) THEN -- Adiantamento Salarial
    BEGIN
      if (prorcamento) then
      begin
        WSQL = 'COALESCE(ORC.BDQTDCALCADISAL,0)AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDCALCADISALMAX,0)AS BDMAX, ';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(select count(BDCODEMP) as BDTOTLAN ';
      WSQL = WSQL||'from VRHF_EMP_TDADOSCALC_BAIXA TADSAL ';
      WSQL = WSQL||'where(TADSAL.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'and(TADSAL.BDTIPOCALC=4)';
      WSQL = WSQL||'and(TADSAL.BDREFERENCIA='||BDREFCALC||')) AS BD_REAL,';
      WSQL = WSQL||'2 AS BDCODSIS,''FOLHA'' AS BDNOMSIS';
      wcodsis = 2;
    END
    ELSE
    IF (PRTIPOCALCULO = 20) THEN -- Complemento de 13º
    BEGIN
      if (prorcamento) then
      begin
        WSQL = 'COALESCE(ORC.BDQTDCALCCOMP13,0)AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDCALCCOMP13MAX,0)AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(select count(BDCODEMP) as BDTOTLAN ';
      WSQL = WSQL||'from VRHF_EMP_TDADOSCALC_BAIXA TCOMP13 ';
      WSQL = WSQL||'where(TCOMP13.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'and(TCOMP13.BDTIPOCALC=5)';
      WSQL = WSQL||'and(TCOMP13.BDREFERENCIA='||BDREFCALC||')) AS BD_REAL,';
      WSQL = WSQL||'2 AS BDCODSIS,''FOLHA'' AS BDNOMSIS';
      wcodsis = 2;
    END
    ELSE
    IF (PRTIPOCALCULO = 21) THEN -- Férias
    BEGIN
      if (prorcamento) then
      begin
        WSQL = 'COALESCE(ORC.BDQTDCALCFERIND,0)AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDCALCFERINDMAX,0)AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(select count(BDCODEMP) as BDTOTLAN ';
      WSQL = WSQL||'from VRHF_EMP_TDADOSCALC_BAIXA TFERIAS ';
      WSQL = WSQL||'where(TFERIAS.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'and(TFERIAS.BDTIPOCALC=10)';
      WSQL = WSQL||'and(TFERIAS.BDREFERENCIA='||BDREFCALC||')) AS BD_REAL,';
      WSQL = WSQL||'2 AS BDCODSIS,''FOLHA'' AS BDNOMSIS';
      wcodsis = 2;
    END
    ELSE
    IF (PRTIPOCALCULO = 22) THEN -- Recisão
    BEGIN
      if (prorcamento) then
      begin
        WSQL = 'COALESCE(ORC.BDQTDCALCRESC,0)AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDCALCRESCMAX,0)AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(select count(BDCODEMP) as BDTOTLAN ';
      WSQL = WSQL||'from VRH_EMP_TRESCISAO TRECISAO ';
      WSQL = WSQL||'where(TRECISAO.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'and(TRECISAO.BDREFRESCISAO='||BDREFCALC||')) AS BD_REAL,';
      WSQL = WSQL||'2 AS BDCODSIS,''FOLHA'' AS BDNOMSIS';
      wcodsis = 2;
    END
    ELSE
    IF (PRTIPOCALCULO = 23) THEN -- PLR
    BEGIN
      if (prorcamento) then
      begin
        WSQL = 'COALESCE(ORC.BDQTDCALCPLR,0)AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDCALCPLRMAX,0)AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(select count(BDCODEMP) as BDTOTLAN ';
      WSQL = WSQL||'from VRHF_EMP_TDADOSCALC_BAIXA TPLR ';
      WSQL = WSQL||'where(TPLR.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'and(TPLR.BDTIPOCALC=15)';
      WSQL = WSQL||'and(TPLR.BDREFERENCIA='||BDREFCALC||')) AS BD_REAL,';
      WSQL = WSQL||'2 AS BDCODSIS,''FOLHA'' AS BDNOMSIS';
      wcodsis = 2;
    END
    ELSE
    IF (PRTIPOCALCULO = 24) THEN -- Intermitente
    BEGIN
      if (prorcamento) then
      begin
        WSQL = 'COALESCE(ORC.BDQTDINTER,0)AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDCALCINTERMAX,0)AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(select count(BDCODEMP) as BDTOTLAN ';
      WSQL = WSQL||'from VRHF_EMP_TDADOSCALC_BAIXA TINTERMITENTE ';
      WSQL = WSQL||'where(TINTERMITENTE.BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'and(TINTERMITENTE.BDCODCONTTI is not null)';
      WSQL = WSQL||'and(TINTERMITENTE.BDREFERENCIA='||BDREFCALC||')) AS BD_REAL,';
      WSQL = WSQL||'2 AS BDCODSIS,''FOLHA'' AS BDNOMSIS';
      wcodsis = 2;
    END
    ELSE
    IF (PRTIPOCALCULO = 25) THEN -- Autônomo
    BEGIN
      if (prorcamento) then
      begin
        WSQL = 'COALESCE(ORC.BDQTDCALCAUT,0)AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDCALCAUTMAX,0)AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(select count(BDCODEMP) as BDTOTLAN from';
      WSQL = WSQL||'(select BDCODEMP from VRHF_EMP_TDADOSCALC_BAIXA ';
      WSQL = WSQL||'where(BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'and(BDTIPOCALC=1)';
      WSQL = WSQL||'and(BDREFERENCIA='||BDREFCALC||')';
      WSQL = WSQL||'union all ';
      WSQL = WSQL||'select X.BDCODEMP from VRHF_EMP_TDADOSCALC_BAIXA X ';
      WSQL = WSQL||'where(BDCODEMP=ORCEMP.BDCODEMP)';
      WSQL = WSQL||'and(BDTIPOCALC<>1)';
      WSQL = WSQL||'and(BDREFERENCIA='||BDREFCALC||')';
      WSQL = WSQL||'and(exists(select first 1 A.BDCODEMP from VW_VRH_EMP_TCOLCON_VINC A ';
      WSQL = WSQL||'join VRH_BASE_TCLASSE C on(C.BDCODCLA=A.BDCODCLA and A.BDCODEMP=X.BDCODEMP and A.BDCODCOL=X.BDCODCOL)';
      WSQL = WSQL||'where(C.BDGRUPOCLA=3)and(not exists(select first 1 X.BDCODEMP from VRHF_EMP_TDADOSCALC_BAIXA X ';
      WSQL = WSQL||'join VRH_EMP_TRESCISAO R on (X.BDCODEMP=R.BDCODEMP and X.BDCODCOL = R.BDCODCOL and X.BDREFERENCIA = R.BDREFRESCISAO)';
      WSQL = WSQL||'where(X.BDTIPOCALC in(6,7))and(X.BDCODEMP=A.BDCODEMP)';
      WSQL = WSQL||'and(X.BDCODCOL=A.BDCODCOL)and(X.BDREFERENCIA=A.BDREFCOL)))))';
      WSQL = WSQL||')) AS BD_REAL,';
      WSQL = WSQL||'2 AS BDCODSIS,''FOLHA'' AS BDNOMSIS';
      wcodsis = 2;
    END
    ELSE
    IF (PRTIPOCALCULO = 26) THEN -- Estagiário
    BEGIN
      if (prorcamento) then
      begin
        WSQL = 'COALESCE(ORC.BDQTDCALCESTAG, 0)AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDCALCESTAGMAX,0)AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
-- Gilberto - 28/01/2026 - #236657
--      wsql = wsql||'(select count(BDCHAVE) from(select distinct X.BDCODCOL as BDCHAVE from VRHF_EMP_TDADOSCALC_BAIXA X ';
--      wsql = wsql||'join VRH_EMP_TCOLCON_VINC A on(A.BDCODEMP=X.BDCODEMP and A.BDCODCOL=X.BDCODCOL)';
--      wsql = wsql||'join VRH_BASE_TCLASSE C on(A.BDCODCLA=C.BDCODCLA and A.BDCODEMP=X.BDCODEMP and ';
--      wsql = wsql||'A.BDCODCOL=X.BDCODCOL and C.BDGRUPOCLA=5)';
--      wsql = wsql||'left join VRH_EMP_TRESCISAO R on(R.BDCODEMP=X.BDCODEMP and R.BDCODCOL=X.BDCODCOL ';
--      wsql = wsql||'and R.BDREFRESCISAO=X.BDREFERENCIA)';
--      wsql = wsql||'where(X.BDCODEMP=ORCEMP.BDCODEMP)and(X.BDREFERENCIA='||BDREFCALC;
--      wsql = wsql||')and(not X.BDTIPOCALC in(1,6,7))and(R.BDCODCOL is null))) AS BD_REAL,';
      wsql = wsql||'(select count(BDCHAVE) from(';
      wsql = wsql||'select X.BDCODCOL as BDCHAVE,x.bdcodemp,x.bdreferencia,x.bdtipocalc ';
      wsql = wsql||'from VRHF_EMP_TDADOSCALC_BAIXA X ';
      wsql = wsql||'join VW_VRH_EMP_TCOLCON_VINC A on(A.BDCODEMP=X.BDCODEMP and A.BDCODCOL=X.BDCODCOL)';
      wsql = wsql||'join VRH_BASE_TCLASSE C on(A.BDCODCLA=C.BDCODCLA and A.BDCODEMP=X.BDCODEMP and A.BDCODCOL=X.BDCODCOL and C.BDGRUPOCLA=5)';
      wsql = wsql||'where(X.BDCODEMP=ORCEMP.BDCODEMP)';
      wsql = wsql||'and(X.BDREFERENCIA='||BDREFCALC||')';
      wsql = wsql||'and(X.BDTIPOCALC in(0,6,7)))';
      wsql = wsql||') AS BD_REAL,';
      WSQL = WSQL||'2 AS BDCODSIS,''FOLHA'' AS BDNOMSIS';
      wcodsis = 2;
    END
    ELSE
    IF (PRTIPOCALCULO = 27) THEN -- Pro-Labore
    BEGIN
      if (prorcamento) then
      begin
        WSQL = 'COALESCE(ORC.BDQTDCALCPROLAB, 0)AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDCALCPROLABMAX,0)AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
      WSQL = WSQL||'(select count(X.BDCODEMP) as BDTOTLAN from VRHF_EMP_TDADOSCALC_BAIXA X ';
      WSQL = WSQL||'where BDCODEMP = ORCEMP.BDCODEMP and BDTIPOCALC <> 1 and ';
      WSQL = WSQL||'BDREFERENCIA = '||BDREFCALC||' and (exists(select first 1 A.BDCODEMP ';
      WSQL = WSQL||'from VW_VRH_EMP_TCOLCON_VINC A  ';
      WSQL = WSQL||'join VRH_BASE_TCLASSE C on (A.BDCODCLA = C.BDCODCLA and ';
      WSQL = WSQL||'A.BDCODEMP = X.BDCODEMP and A.BDCODCOL = X.BDCODCOL) ';
      WSQL = WSQL||'where C.BDGRUPOCLA = 2 and ';
      WSQL = WSQL||'not exists(select first 1 X.BDCODEMP ';
      WSQL = WSQL||'from VRHF_EMP_TDADOSCALC_BAIXA X join VRH_EMP_TRESCISAO R on (X.BDCODEMP = R.BDCODEMP and ';
      WSQL = WSQL||'X.BDCODCOL = R.BDCODCOL and X.BDREFERENCIA = R.BDREFRESCISAO) ';
      WSQL = WSQL||'where X.BDTIPOCALC in (6, 7) and X.BDCODEMP = A.BDCODEMP and ';
      WSQL = WSQL||'X.BDCODCOL = A.BDCODCOL and X.BDREFERENCIA = A.BDREFCOL)))) AS BD_REAL,';
      WSQL = WSQL||'2 AS BDCODSIS,''FOLHA'' AS BDNOMSIS';
      wcodsis = 2;
    END
    else
    IF (PRTIPOCALCULO = 28) THEN -- Doméstica
    begin
      if (prorcamento) then
      begin
        WSQL = 'COALESCE(ORC.BDQTDCALCPROLAB, 0)AS BD_ORC,';
        WSQL = WSQL||'COALESCE(ORC.BDCALCPROLABMAX,0)AS BDMAX,';
      end
      else
         WSQL = ' 0 AS BD_ORC,0 AS BDMAX,';
-- Gilberto - 28/01/2026 - #236657
--      WSQL = WSQL||'(select count(X.BDCODEMP) as BDTOTLAN from VRHF_EMP_TDADOSCALC_BAIXA X ';
--      WSQL = WSQL||'where BDCODEMP = ORCEMP.BDCODEMP and BDTIPOCALC <> 1 and ';
--      WSQL = WSQL||'BDREFERENCIA = '||BDREFCALC||' and (exists(select first 1 A.BDCODEMP ';
--      WSQL = WSQL||'from VW_VRH_EMP_TCOLCON_VINC A  ';
--      WSQL = WSQL||'join VRH_BASE_TCLASSE C on (A.BDCODCLA = C.BDCODCLA and ';
--      WSQL = WSQL||'A.BDCODEMP = X.BDCODEMP and A.BDCODCOL = X.BDCODCOL) ';
--      WSQL = WSQL||'where C.BDGRUPOCLA = 7 and ';
--      WSQL = WSQL||'not exists(select first 1 X.BDCODEMP ';
--      WSQL = WSQL||'from VRHF_EMP_TDADOSCALC_BAIXA X join VRH_EMP_TRESCISAO R on (X.BDCODEMP = R.BDCODEMP and ';
--      WSQL = WSQL||'X.BDCODCOL = R.BDCODCOL and X.BDREFERENCIA = R.BDREFRESCISAO) ';
--      WSQL = WSQL||'where X.BDTIPOCALC in (6, 7) and X.BDCODEMP = A.BDCODEMP and ';
--      WSQL = WSQL||'X.BDCODCOL = A.BDCODCOL and X.BDREFERENCIA = A.BDREFCOL)))) AS BD_REAL,';
      wsql = wsql||'(select count(BDCHAVE) from(';
      wsql = wsql||'select X.BDCODCOL as BDCHAVE,x.bdcodemp,x.bdreferencia,x.bdtipocalc ';
      wsql = wsql||'from VRHF_EMP_TDADOSCALC_BAIXA X ';
      wsql = wsql||'join VW_VRH_EMP_TCOLCON_VINC A on(A.BDCODEMP=X.BDCODEMP and A.BDCODCOL=X.BDCODCOL)';
      wsql = wsql||'join VRH_BASE_TCLASSE C on(A.BDCODCLA=C.BDCODCLA and A.BDCODEMP=X.BDCODEMP and A.BDCODCOL=X.BDCODCOL and C.BDGRUPOCLA=7)';
      wsql = wsql||'where(X.BDCODEMP=ORCEMP.BDCODEMP)';
      wsql = wsql||'and(X.BDREFERENCIA='||BDREFCALC||')';
      wsql = wsql||'and(X.BDTIPOCALC in(0,6,7)))';
      wsql = wsql||') AS BD_REAL,';
      WSQL = WSQL||'2 AS BDCODSIS,''FOLHA'' AS BDNOMSIS';
      wcodsis = 2;
    end

    wselect = 'SELECT ORCEMP.BDCODEMP,TREF.BDNOMEMP,TREF.BDREFEMP,';
    if (prorcamento) then
       wselect = wselect||'ORC.BDREFORC,';
    else
       wselect = wselect||'TREF.BDREFEMP as BDREFORC,';
    wselect = wselect||'(select first 1 BDDATA from VCT_EMPRESA_AVISOORCAMENTO ';
    wselect = wselect||'where bdcodemp=ORCEMP.BDCODEMP and bdcodsis='||wcodsis;
    wselect = wselect||' order by bddata desc) as BDDATA,';
    if (prorcamento) then
    begin
      wselect = wselect||'ORC.BDDESCORC,COALESCE(EF_ORC.BDDESCENQFED,''ME'') AS BDCODENQFED_ORC,';
      wselect = wselect||'CASE WHEN(ORC.BDFORMATRIBUTACAOEMP=1)THEN''LUCRO PRESUMIDO''';
      wselect = wselect||'WHEN(ORC.BDFORMATRIBUTACAOEMP=2)THEN''LUCRO REAL''';
      wselect = wselect||'WHEN(ORC.BDFORMATRIBUTACAOEMP=3)THEN''IMUNE DO IRPJ''';
      wselect = wselect||'WHEN(ORC.BDFORMATRIBUTACAOEMP=4)THEN''ISENTO DO IRPJ''';
      wselect = wselect||'ELSE''NENHUM''';
      wselect = wselect||'END AS BDFORMATRIBUTA_ORC,';
    end
    else
       wselect = wselect||'null as BDDESCORC,null AS BDCODENQFED_ORC,null as BDFORMATRIBUTA_ORC,';
    wselect = wselect||'EF_REAL.BDDESCENQFED BDCODENQFED_REAL,';
    wselect = wselect||'CASE WHEN(TENQ.BDFORMATRIBUTACAO=1)THEN''LUCRO PRESUMIDO''';
    wselect = wselect||'WHEN(TENQ.BDFORMATRIBUTACAO=2)THEN''LUCRO REAL''';
    wselect = wselect||'WHEN(TENQ.BDFORMATRIBUTACAO=3)THEN''IMUNE DO IRPJ''';
    wselect = wselect||'WHEN(TENQ.BDFORMATRIBUTACAO=4)THEN''ISENTO DO IRPJ''';
    wselect = wselect||'ELSE''NENHUM''';
    wselect = wselect||'END AS BDFORMATRIBUTA_REAL,';


    if (prorcamento) then
       wjoin = ' FROM VCT_BASE_ORCADO_EMP ORCEMP ';
    else
       wjoin = ' FROM tempresas ORCEMP ';

    if (prcodemp is null) then
       wjoin = wjoin||'JOIN TMP_EMPRESAS_SELECT X ON(X.BDCODEMP=ORCEMP.BDCODEMP)';

    if (prorcamento) then
       wjoin = wjoin||'join tempresas emp on(emp.bdcodemp=ORCEMP.bdcodemp)';

    if (prorcamento) then
       wjoin = wjoin||'JOIN VCT_BASE_ORCADO ORC ON(ORC.BDCHAVEORC=ORCEMP.BDCHAVEORC)';
    wjoin = wjoin||'LEFT JOIN TEMPRESAS_REF TREF ON(TREF.BDCODEMP=ORCEMP.BDCODEMP AND  ';
    wjoin = wjoin||'TREF.BDREFEMP=(SELECT FIRST 1 BDREFEMP FROM TEMPRESAS_REF ';
    wjoin = wjoin||'WHERE BDCODEMP=ORCEMP.BDCODEMP ORDER BY BDREFEMP DESC))';
    wjoin = wjoin||'LEFT JOIN TENQFED TENQ ON(TENQ.BDCODEMP=TREF.BDCODEMP AND TENQ.BDREFEMP=TREF.BDREFEMP)';
    wjoin = wjoin||'LEFT JOIN TCADENQFED EF_REAL ON(EF_REAL.BDCODENQFED=TENQ.BDCODENQFED)';
    if (prorcamento) then
    begin
      wjoin = wjoin||'LEFT JOIN TCADENQFED EF_ORC ON(EF_ORC.BDCODENQFED=ORC.BDCODENQFED)';
      wjoin = wjoin||'where(orc.bdreforc=(select first 1 x.bdreforc from vct_base_orcado x ';
      wjoin = wjoin||'join vct_base_orcado_emp y on(y.bdchaveorc=x.bdchaveorc and y.bdcodemp=orcemp.bdcodemp)';
      wjoin = wjoin||'where ORC.bdreforc<='||BDREFCALC;
      if (prcodemp is not null) then
         wjoin = wjoin||' and ORCEMP.bdcodemp='||prcodemp;
      wjoin = wjoin||' order by ORC.bdreforc desc))';
    end
    else
      if (prcodemp is not null) then
         wjoin = wjoin||'WHERE ORCEMP.bdcodemp='||prcodemp;


    for execute statement wselect||wsql||wjoin
    into :bdcodemp, :bdnomemp, :bdrefemp, :bdreforc, :bddata, :bddescorc,
         :bdcodenqfed_orc, :bdformatributa_orc, :bdcodenqfed_real, :bdformatributa_real,
         :bd_orc, :bdmax, :bd_real, :bdcodsis, :bdnomsis do
    begin
      bdmax = :bd_orc + (:bd_orc * (:bdmax / 100));
      suspend;
    end

    VDATA = ADDMONTH(VDATA,  1);
  END
END^

create or alter procedure VCT_ORCAMENTO_RELATORIO (
    PRCODEMP varchar(5000),
    PRREFINI integer,
    PRREFFIN integer,
    PRFISCAL integer,
    PRCONTABIL integer,
    PRFOLHA integer,
    PRFINANCEIRO integer,
    PRTIPOQTDFOLHA integer)
returns (
    BDCODEMP integer,
    BDREFEMP integer,
    BDNOMEFANTASIA varchar(200),
    BDRAZAOSOCIAL varchar(100),
    BDCODMATRIZ integer,
    BDCNPJEMP varchar(18),
    BDDOCAUXILIAR varchar(19),
    BDTRIBUTACAO varchar(20),
    BDCOMERCIO varchar(5),
    BDINDUSTRIA varchar(5),
    BDSERVICO varchar(5),
    BDIEEMP varchar(20),
    BDIMEMP varchar(20),
    BDSUFRAMA varchar(9),
    BDCODCNAE integer,
    BDDESCCNAE varchar(200),
    BDORGAOEMP varchar(8),
    BDDESCCARTEMPREF varchar(40),
    BDFATURAMENTO numeric(15,2),
    BDQTDLANCONTABIL integer,
    BDQTDMOVSAIFISCAL integer,
    BDQTDMOVENTFISCAL integer,
    BDQTDMOVSERFISCAL integer,
    BDQTDLANFISCAL integer,
    BDQTDCOLFOLHA integer,
    BDQTDFOLHANORMAL integer,
    BDQTDFOLHAPROLABORE integer,
    BDQTDFOLAAUTONOMO integer,
    BDQTDFILIAIS integer,
    BDQTDFISCALNFSEPRESTADO integer,
    BDQTDFISCALNFSETOMADO integer,
    BDQTDFOLHAESTAGIARIO integer,
    BDQTDFOLHADOMESTICA integer,
    BDSITEMP varchar(5),
    BDUFEMP char(4),
    BDCIDEMP varchar(150),
    BDNOMECENTROS varchar(40),
    BDDESCPLATRIB varchar(50))
as
declare variable WREFEMP integer;
declare variable WDATA timestamp;
declare variable WSQL varchar(30000);
declare variable WULTDIA varchar(4);
begin
  wsql = '';
  if ((select POS from pos('WHERE', upper(:prcodemp))) <= 0) then
     wsql = 'where ';
  wsql = wsql||prcodemp;
  for execute statement 'select bdcodemp from tempresas '||wsql||' order by bdcodemp' into :bdcodemp do
  begin
    wrefemp = prrefini;
    select count(bdcodemp) from tempresas where bdcodmatriz = :bdcodemp into :bdqtdfiliais;
    while (wrefemp <= prreffin) do
    begin
      bdrefemp = wrefemp;

      select first 1 ref.bdnomfanemp, ref.bdnomemp, emp.bdcodmatriz, emp.bdcnpjemp, ref.bdieemp, ref.bdimemp,
             ref.bdsuframa, ref.bdcodcnae, cnae.bddesccnae, ref.bdorgaoemp, ref.bddesccartempref, ref.bddocauxiliar,
             ref.bdsitemp, cen.bdnome ,cid.bdnomcid,uf.bdsiglauf, platrib.bddescplatrib
      from tempresas_ref ref
      inner join tempresas emp on (emp.bdcodemp = ref.bdcodemp)
      inner join tcidade cid on (cid.bdcodcid = ref.bdcodcid)
      inner join tuf uf on (cid.bdcoduf = uf.bdcoduf)
      left outer join tcentros cen on (cen.bdcodcentro = ref.bdcodcentros)
      left outer join tcnae cnae on (cnae.bdcodcnae = ref.bdcodcnae)
      left outer join VCT_PLANO_TRIBUTARIO platrib on (platrib.bdcodplatrib = ref.bdcodplatrib)
      where ref.bdcodemp = :bdcodemp
      and ref.bdrefemp <= :bdrefemp
      order by ref.bdrefemp desc
      into :bdnomefantasia, :bdrazaosocial, :bdcodmatriz, :bdcnpjemp, :bdieemp, :bdimemp, :bdsuframa, bdcodcnae, :bddesccnae, :bdorgaoemp, :bddesccartempref, :bddocauxiliar, :bdsitemp, :bdnomecentros,:bdcidemp,:bdufemp,:bddescplatrib;

      select first 1 case
                       when descr.bdcodenqfed = 1 then 'Simples Nacional'
                       when descr.bdcodenqfed = 2 then 'Simples Nacional'
                       when descr.bdcodenqfed = 3 and enq.bdformatributacao = 0 then 'Nenhum'
                       when descr.bdcodenqfed = 3 and enq.bdformatributacao = 1 then 'Lucro Presumido'
                       when descr.bdcodenqfed = 3 and enq.bdformatributacao = 2 then 'Lucro real'
                       when descr.bdcodenqfed = 3 and enq.bdformatributacao = 3 then 'Imune do IRPJ'
                       when descr.bdcodenqfed = 3 and enq.bdformatributacao = 4 then 'Isento do IRPJ'
                       when descr.bdcodenqfed = 4 then 'MEI' end bddescenqfed
                        from tcadenqfed descr
      inner join tenqfed enq on (enq.bdcodenqfed = descr.bdcodenqfed)
      where enq.bdcodemp =:bdcodemp and enq.bdrefemp <= :bdrefemp
      order by enq.bdrefemp desc
      into :bdtributacao;

      select first 1 bdcomercio, bdindustria, bdservico from VEF_BASE_TEMPCADATV
      where bdcodemp = :bdcodemp
      and bdrefemp <= :bdrefemp
      order by bdrefemp desc
      into :bdcomercio, :bdindustria, :bdservico;

      if (coalesce(prfinanceiro,0) >= 1) then
         select sum(bdvalorfatura) from vfin_esc_tfatura where bdcodcli = :bdcodemp and bdreffat = :wrefemp into :bdfaturamento;
    
      if (coalesce(prfiscal,0) >= 1) then
      begin
        select count(*) from vef_emp_tmovent where bdcodemp = :bdcodemp and bdreflan = :wrefemp into :bdqtdmoventfiscal;
        select count(*) from vef_emp_tmovsai where bdcodemp = :bdcodemp and bdreflan = :wrefemp into :bdqtdmovsaifiscal;
        select count(*) from vef_emp_tmovser where bdcodemp = :bdcodemp and bdreflan = :wrefemp into :bdqtdmovserfiscal;
        bdqtdlanfiscal = bdqtdmoventfiscal + bdqtdmovsaifiscal + bdqtdmovserfiscal;
        select count(*) from vef_emp_tmovser where bdcodemp = :bdcodemp and bdreflan = :wrefemp and bdtiplan = 0 into :bdqtdfiscalnfseprestado;
        select count(*) from vef_emp_tmovser where bdcodemp = :bdcodemp and bdreflan = :wrefemp and bdtiplan = 1 into :bdqtdfiscalnfsetomado;
      end
    
      if (coalesce(prcontabil,0) >= 1) then
         select count(*) from vsuc_empresas_tlan where bdcodemp = :bdcodemp and bdreferencia = :wrefemp into :bdqtdlancontabil;
    
      if (coalesce(prfolha,0) >= 1) then
      begin
        select first 1 ultdia from ultimo_dia_mes(cast(substring(:wrefemp from 5 for 2)as smallint),cast(substring(:wrefemp from 1 for 4) as integer)) into :wultdia;
        wdata = cast(substring(:wrefemp from 5 for 2)||'/'||wultdia||'/'||substring(:wrefemp from 1 for 4) as date);

        if (coalesce(prtipoqtdfolha,0) in (0,1)) then
        begin
          -- Colaboradores
         select BD_REAL from vct_orcado_realizado(null, null, 7, :bdcodemp, :wrefemp, False) into :bdqtdcolfolha;
          -- Pró-labore
         select BD_REAL from vct_orcado_realizado(null, null, 27, :bdcodemp, :wrefemp, False) into :bdqtdfolhaprolabore;
          -- Cálculos Autônomos
          select BD_REAL from vct_orcado_realizado(null, null, 25, :bdcodemp, :wrefemp, False) into :bdqtdfolaautonomo;
          -- Estagiarios
          select BD_REAL from vct_orcado_realizado(null, null, 26, :bdcodemp, :wrefemp, False) into :bdqtdfolhaestagiario;
          -- Domésticas
          select BD_REAL from vct_orcado_realizado(null, null, 28, :bdcodemp, :wrefemp, False) into :bdqtdfolhadomestica;
        end
        -- Cálculos folha normal
        select BD_REAL from vct_orcado_realizado(null, null, 14, :bdcodemp, :wrefemp, False) into :bdqtdfolhanormal;
      end
  
      suspend;
  
      wdata = cast(substring(wrefemp from 5 for 2)||'-01-'||substring(wrefemp from 1 for 4) as timestamp);
      wdata = addmonth(wdata, 1);
      wrefemp = cast(substring(wdata from 1 for 4)||substring(wdata from 6 for 2) as integer);
    end
  end
end^

create or alter procedure VCT_TAREFA_SEFIPSEMMOVIMENTO (
    PRCODEMP integer,
    PRDATA date)
returns (
    BDRESULT varchar(5))
as
declare variable WDATA date;
declare variable WREF integer;
declare variable WCOUNT1 integer;
declare variable WCOUNT2 integer;
begin
  bdresult = 'FALSE';-- é falso a menos que a rotina a baixo diga o contrário
/*
  wdata = addmonth(prdata, -2);
    wref = cast(substring(wdata from 1 for 4)||substring(wdata from 6 for 2) as integer);
    select count(fn.bdcodemp) from (select BDCODEMP, BDCODCOL from VRHF_EMP_TFOLHANORMAL where BDREFFN = :wref
                                    union all
                                    select BDCODEMP, BDCODCOL from VRHF_EMP_TFOLHATOMADOR where BDREFTOMADOR = :wref
                                    union all
                                    select BDCODEMP, BDCODCOL from VRHF_EMP_TFOLHAINT where BDREFFN = :wref
                                    union all
                                    select BDCODEMP, BDCODCOL from VRHF_EMP_TFOLHATOMINT where BDREFTOMADOR = :wref) FN
    inner join VRH_EMP_TCOLCON C on (C.BDCODEMP = FN.BDCODEMP and C.BDCODCOL = FN.BDCODCOL and coalesce(C.BDCONTRCOL, 0) in (0,1))
    where FN.BDCODEMP = :prcodemp
    into :wcount1;

  wdata = addmonth(prdata, -1);
    wref = cast(substring(wdata from 1 for 4)||substring(wdata from 6 for 2) as integer);
    select count(fn.bdcodemp) from (select BDCODEMP, BDCODCOL from VRHF_EMP_TFOLHANORMAL where BDREFFN = :wref
                                    union all
                                    select BDCODEMP, BDCODCOL from VRHF_EMP_TFOLHATOMADOR where BDREFTOMADOR = :wref
                                    union all
                                    select BDCODEMP, BDCODCOL from VRHF_EMP_TFOLHAINT where BDREFFN = :wref
                                    union all
                                    select BDCODEMP, BDCODCOL from VRHF_EMP_TFOLHATOMINT where BDREFTOMADOR = :wref) FN
    inner join VRH_EMP_TCOLCON C on (C.BDCODEMP = FN.BDCODEMP and C.BDCODCOL = FN.BDCODCOL and coalesce(C.BDCONTRCOL, 0) in (0,1))
    where FN.BDCODEMP = :prcodemp
    into :wcount2;

    if ((wcount1 > 0) and (wcount2 = 0)) then
  begin
    if ((select count(BDCODCOL)
         from VRH_SP_CONS_COL_NOVO(:wref, :prcodemp, '(COLCON_REF.BDGRUPOCLA in (1,4,5,7,8,9,10) OR COLCON.BDCONTRCOL = 0)', :prdata)
         where cast(substring(BDDATAADMCOL from 1 for 4)||substring(BDDATAADMCOL from 6 for 2) as integer) <= :wref
         and((BDDATARESCISAO is null)or(cast(substring(BDDATARESCISAO from 1 for 4)||substring(BDDATARESCISAO from 6 for 2) as integer) = :wref))) = 0) then
       bdresult = 'TRUE';
  end
*/

  wdata = addmonth(prdata, -2);
  wref = cast(substring(wdata from 1 for 4)||substring(wdata from 6 for 2) as integer);
  select count(BDCODCOL)
  from VRH_SP_CONS_COL_NOVO(:wref, :prcodemp, '(COLCON_REF.BDGRUPOCLA in (1,4,5,7,8,9,10) OR COLCON.BDCONTRCOL = 0)', addmonth(:wdata, 2))
  where cast(substring(BDDATAADMCOL from 1 for 4)||substring(BDDATAADMCOL from 6 for 2) as integer) <= :wref
  and((BDDATARESCISAO is null)or(cast(substring(BDDATARESCISAO from 1 for 4)||substring(BDDATARESCISAO from 6 for 2) as integer) = :wref))
  into :wcount1;

  wdata = addmonth(prdata, -1);
  wref = cast(substring(wdata from 1 for 4)||substring(wdata from 6 for 2) as integer);
  select count(BDCODCOL)
  from VRH_SP_CONS_COL_NOVO(:wref, :prcodemp, '(COLCON_REF.BDGRUPOCLA in (1,4,5,7,8,9,10) OR COLCON.BDCONTRCOL = 0)', addmonth(:wdata, 2))
  where cast(substring(BDDATAADMCOL from 1 for 4)||substring(BDDATAADMCOL from 6 for 2) as integer) <= :wref
  and((BDDATARESCISAO is null)or(cast(substring(BDDATARESCISAO from 1 for 4)||substring(BDDATARESCISAO from 6 for 2) as integer) = :wref))
  into :wcount2;

  if ((wcount1 > 0) and (wcount2 = 0)) then
     bdresult = 'TRUE';
  suspend;
end^

create or alter procedure GET_VENCIMENTO_TAREFAS (
    PRDATA date,
    PRDIA integer,
    PRANTECIPA varchar(5),
    PRVENCE integer,
    PRAPURACAO integer,
    PRALERTA integer,
    PRENTREGA integer,
    PRMES integer = 0,
    PRCODEMP integer = 0,
    PRTIPOTAREFA integer = 0,
    PRDIASEMANA integer = 0)
returns (
    BDDATA date,
    BDALERTA date,
    BDENTREGA date)
as
declare variable WDIA integer;
declare variable WMES integer;
declare variable WANO integer;
declare variable WDATA date;
declare variable WCOUNT integer;
declare variable WCOUNTX integer;
declare variable WDATAALERTA date;
declare variable WDATAENTREGA date;
BEGIN
  /*
  PRDIA = dia de vencimento do mês
  PRANTECIPA = 1 - antecipa domingos e feriados
  PRVENCE = 0 - No mês do movimento
            1 - No mês seguinte
            2 - No mês subsequente
            3 - Dias úteis
            4 - Imposto = No terceiro mês subsequente
                Obrigação e serviço = No início das atividades da empresa
  PRAPURACAO =  0 - Semanal
                1 - 1º Decendio
                2 - 2º Decendio
                3 - 3º Decendio
                4 - 1ª Quinzena
                5 - 2ª Quinzena
                6 - Mensal
                7 - Trimestral
                8 - Trimestral parcelado
                9 - Trimestral antecipado
               10 - Anual
               11 - Indefinido
               12 - Diário
               13 - Semestral
               14 - Dias úteis
  PRDIASEMANA = 0 - Domingo
                1 - Segunda
                2 - Terça
                3 - Quarta
                4 - Quinta
                5 - Sexta
                6 - Sábado
  */


  IF (PRDATA IS NULL) THEN
     EXIT;

  /* inicializa variáveis */
  IF (coalesce(prvence, 0) <> 3) THEN
     wdia = prdia;
  ELSE
     wdia = SUBSTRING(prdata FROM 9 FOR 2);
  IF ((prdia = 0) OR (prdia IS NULL)) THEN
     wdia = 1;
  IF ((prmes IS NOT NULL) AND (coalesce(prmes, 0) <> 0) AND (PRAPURACAO = 10)) THEN
     wmes = prmes;
  ELSE
     wmes = SUBSTRING(prdata FROM 6 FOR 2);
  wano = SUBSTRING(prdata FROM 1 FOR 4);

  IF ((PRTIPOTAREFA <> 0) and (coalesce(prvence, 0) = 4)) THEN
  BEGIN
    SELECT bddatainiativemp FROM tempresas WHERE bdcodemp = :prcodemp INTO :wdata;
--  1991-02-27
    wdia = SUBSTRING(wdata FROM 9 FOR 2);
    wmes = SUBSTRING(wdata FROM 6 FOR 2);
  END
  ELSE
     wdata = prdata;

  /* apuração */
  IF (prapuracao =  0) THEN -- 0 - Semanal
  begin
    wdata = prdata;
    while (extract(weekday from wdata) <> prdiasemana) do
    begin
      if (extract(weekday from wdata) > prdiasemana) then
         wdata = addday(wdata, -1);
      else
         wdata = addday(wdata, 1);
    end
    wdata = addday(wdata, 7);
    wdia = extract(day from wdata);
    wmes = extract(month from wdata);
    wano = extract(year from wdata);
  end
  ELSE
  IF (prapuracao =  1) THEN -- 1 - 1º Decendio
  begin
--    wdia = 11;
    if (coalesce(prdia, 0) = 0) then
       wdia = 10;
  ELSE
       wdia = prdia;
  end
  ELSE
  IF (prapuracao =  2) THEN -- 2 - 2º Decendio
  begin
--    wdia = 21;
    if (coalesce(prdia, 0) = 0) then
       wdia = 20;
  ELSE
       wdia = prdia;
  end
  ELSE
  IF (prapuracao =  3) THEN -- 3 - 3º Decendio
  begin
--    wdia = 31; -- não há necessidade de verificar mês e ano bisexto, pois isso acontecerá no processo "add dia"
    if (coalesce(prdia, 0) = 0) then
       wdia = 30;
  ELSE
       wdia = prdia;
  end
  ELSE
  IF (prapuracao =  4) THEN -- 4 - 1ª Quinzena
  BEGIN
    IF (prdia IS NULL) THEN
       wdia = SUBSTRING(prdata FROM 9 FOR 2);
    ELSE
       wdia = prdia;
-- Gilberto - 29/01/2024 - Como os decêncios foram padronizados para que o usuário possa escolher o dia de vencimento, assuminmos o mesmo padrão para as quinzenas
    -- Gilberto - 15/01/2024 - Ajustado para caso o dia seja maior que 15
--    if (wdia > 15) then
--       wdia = 15;
  END
  ELSE
  IF (prapuracao =  5) THEN -- 5 - 2ª Quinzena
  BEGIN
    IF (prdia IS NULL) THEN
       wdia = SUBSTRING(prdata FROM 9 FOR 2);
    ELSE
       wdia = prdia;
-- Gilberto - 29/01/2024 - Como os decêncios foram padronizados para que o usuário possa escolher o dia de vencimento, assuminmos o mesmo padrão para as quinzenas
    -- Gilberto - 15/01/2024 - Ajustado para que a data fique dentro da segunda quinzena
--    if ((wdia < 16) or (wdia > 31)) then
--       wdia = 30;
  END
  ELSE
  IF (prapuracao =  6) THEN -- 6 - Mensal
     wdata = prdata;
  ELSE
  IF (prapuracao =  7) THEN -- 7 - Trimestral
  BEGIN
    IF (wmes IN (1,2,3)) THEN
    begin
      if (coalesce(prvence, 0) = 3) then
         wmes = 4;
      ELSE
         wmes = 3;
    end
    ELSE
    IF (wmes IN (4,5,6)) THEN
    begin
      if (coalesce(prvence, 0) = 3) then
         wmes = 7;
      ELSE
        wmes = 6;
    end
    ELSE
    IF (wmes IN (7,8,9)) THEN
    begin
      if (coalesce(prvence, 0) = 3) then
          wmes = 10;
      ELSE
        wmes = 9;
    end
    ELSE
    IF (wmes IN (10,11,12)) THEN
    BEGIN
      if (coalesce(prvence, 0) = 3) then
      BEGIN
        wmes = 1;
        wano = wano+1;
      END
      ELSE
         wmes = 12;
    END
  END
--  ELSE
--  IF (prapuracao =  8) THEN -- 8 - Trimestral parcelado
--  BEGIN
-- Gilberto - 06/10/2021 - W153866 - Gerar quotas do imposto parcelado - vctos
-- Não funciona desta forma
--    IF (wmes IN (1,2,3)) THEN
--       wmes = 4;
--    ELSE
--    IF (wmes IN (4,5,6)) THEN
--       wmes = 7;
--    ELSE
--    IF (wmes IN (7,8,9)) THEN
--       wmes = 10;
--    ELSE
--    IF (wmes IN (10,11,12)) THEN
--    BEGIN
--      wmes = 1;
--      wano = wano + 1;
--    END
--  END
--  ELSE
--  IF (prapuracao =  9) THEN -- 9 - Trimestral antecipado
--  BEGIN
-- gilberto - 30/10/2014 - retirado pois incrementa 2 meses quando opção mês seguinte estiver habilitada
--    if (wmes < 12) then
--       wmes = wmes + 1;
--    else
--       begin
--         wmes = 1;
--         wano = wano + 1;
--       end
--
--  END
  ELSE
  IF (prapuracao =  9) THEN -- 9 - Trimestral antecipado
  BEGIN
/* gilberto - 30/10/2014 - retirado pois incrementa 2 meses quando opção mês seguinte estiver habilitada
    if (wmes < 12) then
       wmes = wmes + 1;
    else
       begin
         wmes = 1;
         wano = wano + 1;
       end
*/
  END
  ELSE
  IF (prapuracao = 10) THEN -- 10 - Anual
  BEGIN
--    if (coalesce(prvence, 0) in (0,1,2)) then
--    begin
--      -- Gilberto - 15/07/2020 - já retorna com o dia a mês correto, para mês seguinte e subsequente é tratado abaixo
--    end
--    else
    IF (coalesce(prvence, 0) <> 4) THEN
    BEGIN
      wdia = prdia;
      wmes = prmes;
-- Gilberto - 30/01/2025 - #238834 - Backup para o caso da base não ter dia e mês cadastrado ou estar cadastrado fora da faixa
      if ((wdia <= 0) or (wdia > 31)) then
         wdia = extract(day from prdata);
      if ((wmes <= 0) or (wmes > 12)) then
         wmes = extract(month from prdata);      
    END
  END
  ELSE
  IF (prapuracao = 11) THEN -- 11 - Indefinido
     wdata = prdata;
  else
-- Gilberto - 20/03/2025 - #217624
  IF (prapuracao = 12) THEN -- 12 - Diário
  begin
    wdata = prdata;
    wdia = extract(day from wdata);
    wmes = extract(month from wdata);
    wano = extract(year from wdata);
  end
  else
  if (prapuracao = 14) then-- 14 - Dias úteis
  begin
    -- deve lançar com uma semana de antecedencia
    -- não deve lançar para sábados e domingos
    -- não deve lançar quando houver feriado nacional
--    wdata = addday(prdata, 7);
    wdata = prdata;-- GIlberto - 20/03/2025 - #217624
    IF ((UPPER(sdow(wdata)) = 'SÁB') OR
        (UPPER(sdow(wdata)) = 'SUN') or
        (UPPER(sdow(wdata)) = 'DOM') OR
        (UPPER(sdow(wdata)) = 'WES')) THEN
       wdata = null;
    else
    if ((SELECT FIRST 1 fer.bdcodferi FROM tferiadosnovo fer
         WHERE ((fer.bddataferi = :wdata)
         OR (fer.bdmesdiaferi = CAST(SUBSTRING(:wdata FROM 9 FOR 2)||SUBSTRING(:wdata FROM 6 FOR 2) AS VARCHAR(4))))
         AND fer.bdcodcid IS NULL) is not null) then
       wdata = null;

    wdia = extract(day from wdata);
    wmes = extract(month from wdata);
    wano = extract(year from wdata);
  end

  /* add mês e ano */
  IF (coalesce(prvence, 0) = 1) THEN
  BEGIN
    wmes = wmes + prvence;
    IF (wmes > 12) THEN
    BEGIN
      wmes = 1;
      wano = wano + 1;
    END
  END
  ELSE
  IF (coalesce(prvence, 0) = 2) THEN
  BEGIN
    wmes = wmes + prvence;
    IF (wmes > 12) THEN
    BEGIN
      wmes = wmes - 12;
      wano = wano + 1;
    END
  END
  else
  -- Terceiro mês subsequente
  if ((prtipotarefa = 0) and (coalesce(prvence, 0) = 4)) then
  BEGIN
    wmes = wmes + 3;
    IF (wmes > 12) THEN
    BEGIN
      wmes = wmes - 12;
      wano = wano + 1;
    END
  END

  /* add dia */
  IF (wmes = 2) THEN
  BEGIN
    IF ((wano / 4 * 4) = wano) THEN
    BEGIN
      IF (wdia > 29) THEN
         wdia = 29;
    END
    ELSE
    BEGIN
      IF (wdia > 28) THEN
         wdia = 28;
    END
  END
  ELSE
  IF (wmes IN (1,3,5,7,8,10,12)) THEN
  BEGIN
    IF (wdia > 31) THEN
       wdia = 31;
  END
  ELSE
  IF (wmes IN (4,6,9,11)) THEN
  BEGIN
    IF (wdia > 30) THEN
       wdia = 30;
  END

  /* monta data atual */
  wdata = CAST(wano||'/'||wmes||'/'||wdia AS DATE);

  /* dias úteis */
  IF (coalesce(prvence, 0) = 3) THEN
  BEGIN
    wcount = 0;
    WHILE (wcount < prdia) DO
    BEGIN
      wdata = addday(wdata, 1);
      wcount = wcount + 1;

      SELECT FIRST 1 fer.bdcodferi FROM tferiadosnovo fer
      WHERE ((fer.bddataferi = :wdata)
      OR (fer.bdmesdiaferi = CAST(SUBSTRING(:wdata FROM 9 FOR 2)||SUBSTRING(:wdata FROM 6 FOR 2) AS VARCHAR(4))))
      AND fer.bdcodcid IS NULL
      INTO :wdia;
      IF ((wdia IS NOT NULL) AND (coalesce(wDia, 0) <> 0)) THEN
         wdata = addday(wdata, 1);

      IF ((UPPER(sdow(wdata)) = 'SÁB') OR
          (UPPER(sdow(wdata)) = 'SUN')) THEN
         wdata = addday(wdata, 1);

      IF ((UPPER(sdow(wdata)) = 'DOM') OR
          (UPPER(sdow(wdata)) = 'WES')) THEN
         wdata = addday(wdata, 1);
    END
  END

  /* antecipa vencimento */
  IF ((UPPER(prantecipa) = 'TRUE') OR (UPPER(prantecipa) = '1')) THEN
  BEGIN
    IF (((coalesce(prvence, 0) = 3) AND (wdata - prdata > 0)) OR (coalesce(prvence, 0) <> 3))  THEN
    BEGIN
      wcount = 0;
      wDia = 0;
      WHILE ((wcount = 0) OR
             (((wdia IS NOT NULL) AND (coalesce(wdia, 0) <> 0)) OR
             ((UPPER(sdow(wdata)) = 'DOM') OR (UPPER(sdow(wdata)) = 'WES')) OR
             ((UPPER(sdow(wdata)) = 'SÁB') OR (UPPER(sdow(wdata)) = 'SUN')))) DO
      BEGIN
        wdia = 0;
        SELECT FIRST 1 fer.bdcodferi FROM tferiadosnovo fer
        WHERE (fer.bddataferi = :wdata)
--                or (fer.bdmesdiaferi = cast(substring(:wdata from 9 for 2)||substring(:wdata from 6 for 2) as varchar(4))))
        AND fer.bdcodcid IS NULL
        INTO :wdia;
        IF (((wdia IS NOT NULL) AND (coalesce(wdia, 0) <> 0)) OR
           ((UPPER(sdow(wdata)) = 'DOM') OR (UPPER(sdow(wdata)) = 'WES')) OR
           ((UPPER(sdow(wdata)) = 'SÁB') OR (UPPER(sdow(wdata)) = 'SUN'))) THEN
           wcount = 0;
        ELSE
           wcount = 1;

        IF (wcount = 0) THEN
           wdata = addday(wdata, -1);
      END
    END
  END
  ELSE
  /* posterga vencimento */
  BEGIN
    IF (((coalesce(prvence, 0) = 3) AND (wdata - prdata > 0)) OR (coalesce(prvence, 0) <> 3))  THEN
    BEGIN
      wcount = 0;
      wDia = 0;
      WHILE ((wcount = 0) OR
             (((wDia IS NOT NULL) AND (coalesce(wdia, 0) <> 0)) OR
             ((UPPER(sdow(wdata)) = 'DOM') OR (UPPER(sdow(wdata)) = 'WES')) OR
             ((UPPER(sdow(wdata)) = 'SÁB') OR (UPPER(sdow(wdata)) = 'SUN')))) DO
      BEGIN
        wdia = 0;
        SELECT FIRST 1 fer.bdcodferi
        FROM tferiadosnovo fer
        WHERE (fer.bddataferi = :wdata)
--                or (fer.bdmesdiaferi = cast(substring(:wdata from 9 for 2)||substring(:wdata from 6 for 2) as varchar(4))))
        AND fer.bdcodcid IS NULL
        INTO :wdia;
        IF (((wdia IS NOT NULL) AND (coalesce(wdia, 0) <> 0)) OR
           ((UPPER(sdow(wdata)) = 'DOM') OR (UPPER(sdow(wdata)) = 'WES')) OR
           ((UPPER(sdow(wdata)) = 'SÁB') OR (UPPER(sdow(wdata)) = 'SUN'))) THEN
           wcount = 0;
        ELSE
           wcount = 1;

        IF (wcount = 0) THEN
           wdata = addday(wdata, 1);
      END
    END
  END

  /* alreta */
  wdataalerta = wdata;
  IF ((pralerta IS NOT NULL) AND (pralerta > 0)) THEN
  BEGIN
    wcount = 1;
    wcountx = 0;
    wDia = 0;
    WHILE ((wcount <= pralerta) OR
           ((((wDia IS NOT NULL) AND (coalesce(wdia, 0) <> 0)) OR
            ((UPPER(sdow(wdataalerta)) = 'DOM') OR (UPPER(sdow(wdataalerta)) = 'WES')) OR
            ((UPPER(sdow(wdataalerta)) = 'SÁB') OR (UPPER(sdow(wdataalerta)) = 'SUN'))))) DO
    BEGIN
      wdia = 0;
      SELECT FIRST 1 fer.bdcodferi
      FROM tferiadosnovo fer
      WHERE (fer.bddataferi = :wdataalerta)
--           or (fer.bdmesdiaferi = cast(substring(:wdata from 9 for 2)||substring(:wdata from 6 for 2) as varchar(4))))
      AND fer.bdcodcid IS NULL
      INTO :wdia;
      IF (((wdia IS NOT NULL) AND (coalesce(wdia, 0) <> 0)) OR
         ((UPPER(sdow(wdataalerta)) = 'DOM') OR (UPPER(sdow(wdataalerta)) = 'WES')) OR
         ((UPPER(sdow(wdataalerta)) = 'SÁB') OR (UPPER(sdow(wdataalerta)) = 'SUN'))) THEN
         wdataalerta = addday(wdataalerta, -1);
      ELSE
         wcount = wcount + 1;

      wdataalerta = addday(wdataalerta, -1);
    END
  END

  /* entrega */
  wdataentrega = wdata;
  IF ((prentrega IS NOT NULL) AND (prentrega > 0)) THEN
  BEGIN
    wcount = 1;
    wcountx = 0;
    wDia = 0;
    WHILE ((wcount <= prentrega) OR
           ((((wDia IS NOT NULL) AND (coalesce(wdia, 0) <> 0)) OR
            ((UPPER(sdow(wdataentrega)) = 'DOM') OR (UPPER(sdow(wdataentrega)) = 'WES')) OR
            ((UPPER(sdow(wdataentrega)) = 'SÁB') OR (UPPER(sdow(wdataentrega)) = 'SUN'))))) DO
    BEGIN
      wdia = 0;
      SELECT FIRST 1 fer.bdcodferi
      FROM tferiadosnovo fer
      WHERE (fer.bddataferi = :wdataentrega)
--           or (fer.bdmesdiaferi = cast(substring(:wdata from 9 for 2)||substring(:wdata from 6 for 2) as varchar(4))))
      AND fer.bdcodcid IS NULL
      INTO :wdia;
      IF (((wdia IS NOT NULL) AND (coalesce(wdia, 0) <> 0)) OR
         ((UPPER(sdow(wdataentrega)) = 'DOM') OR (UPPER(sdow(wdataentrega)) = 'WES')) OR
         ((UPPER(sdow(wdataentrega)) = 'SÁB') OR (UPPER(sdow(wdataentrega)) = 'SUN'))) THEN
         wdataentrega = addday(wdataentrega, -1);
      ELSE
         wcount = wcount + 1;

      wdataentrega = addday(wdataentrega, -1);
    END
  END

  bddata = wdata;
---- Gilberto - 10/02/2025 - #206950 - Alerta é dias corridos.
----  bdalerta = wdataalerta;
--  bdalerta = wdata - pralerta;
--  bdentrega = wdataentrega;
-- Gilberto - 20/03/2025 - #217624
  if (prapuracao in (12,14)) then
  begin
    bdalerta = wdata;
    bdentrega = wdata;
  end
  else
  begin
    bdalerta = wdata - pralerta;
    bdentrega = wdataentrega;
  end
  SUSPEND;
END^

create or alter procedure SP_REFERENCIA_TO_DATA (
    PRREFERENCIA integer,
    PRULTIMO_DIA boolean = false)
returns (
    BDDATA date)
as
declare variable VULTDIA integer;
begin
  bddata = cast(substring(prreferencia from 5 for 2)||'-01-'||substring(prreferencia from 1 for 4) as date);
  if (prultimo_dia) then
     bddata = addmonth(bddata, 1)-1;
  suspend;
end^

create or alter procedure VCT_TAREFAS_AUTORIZADAS (
    PRDATA date)
returns (
    BDAUTORIZADA boolean)
as
begin
  BDAUTORIZADA = True;
  -- não gerar tarefas automáticas para clientes que não estejam personalizados para o controles
  if (((select first 1 BDCODIGO
        from TPERSONALIZACAO
        where (BDSISTEMAS containing '58') or (BDSISTEMAS containing '1506')) is null) or
      -- caso houver uma data de finalização anterior a data atual
      ((select first 1 bddatafinal from tpessoatosistema
        where(bdsistema in(1506,58))
        and((bddatafinal is not null)and(bddatafinal<=current_date))) is not null) or
      -- não gerar tarefas antes da data configurada
      ((select first 1 BDDATATAREFA
        from VCT_CONFIG_DATAS
        where BDDATATAREFA <= :prdata) is null) or
      -- não deixar gerar tarefas automáticas no cadastro de empresas
      (coalesce((select cast((trim(rdb$get_context('USER_SESSION', 'W_CADEMPRESA'))) as integer)
                 from RDB$DATABASE), 0) <> 0)) then
  begin
    BDAUTORIZADA = False;
  end
  suspend;
end^

create or alter procedure VCT_TAREFAS_EXEC_THREAD (
    PRCODEMP integer = null,
    PRCODIMP integer = null,
    PRCODOBR integer = null,
    PRCODSER integer = null,
    PRCODPROC integer = null)
as
declare variable VPARAM varchar(50);
declare variable VSQL varchar(1000);
begin
  /* Quando houver alteração nos cadastros de usuário, grupo de usuário e plano de tarefas */
  vparam = 'TThreadGeraTarefas_Usuarios_'||coalesce(prcodemp,0)||'_'||coalesce(prcodimp,0)||'_'||coalesce(prcodobr,0)||'_'||coalesce(prcodser,0)||'_'||coalesce(prcodproc,0);
  vsql = 'insert into TTHREAD(BDPARAM)select '||''''||vparam||''''||' as BDPARAM from vct_config_datas x ';
  vsql = vsql||'where(x.BDDATATAREFA is not null)';
  vsql = vsql||'and not exists(select first 1 bdparam from TTHREAD where bdparam = '||''''||vparam||''''||');';
  execute statement vsql;
end^

CREATE OR ALTER trigger tgrupousuario_usuario_au0 for tgrupousuario_usuario
active after insert or update or delete position 0
AS
begin
  execute procedure vct_tarefas_exec_thread;
end^

CREATE OR ALTER trigger vct_empresa_usuario_imp_aiud0 for vct_empresa_usuario_imp
active after insert or update or delete position 0
AS
begin
  if (old.bdcodemp is not null) then-- exclusão/alteração
     execute procedure vct_tarefas_exec_thread(old.bdcodemp, old.bdcodimp, null, null, old.bdcodproc);
  else
     execute procedure vct_tarefas_exec_thread(new.bdcodemp, new.bdcodimp, null, null, new.bdcodproc);
end^

CREATE OR ALTER trigger vct_empresa_usuario_obr_aiud0 for vct_empresa_usuario_obr
active after insert or update or delete position 0
AS
begin
  if (old.bdcodemp is not null) then-- exclusão/alteração
     execute procedure vct_tarefas_exec_thread(old.bdcodemp, null, old.bdcodobrser, null, old.bdcodproc);
  else
     execute procedure vct_tarefas_exec_thread(new.bdcodemp, null, new.bdcodobrser, null, new.bdcodproc);
end^

CREATE OR ALTER trigger vct_empresa_usuario_ser_aiud0 for vct_empresa_usuario_ser
active after insert or update or delete position 0
AS
begin
  if (old.bdcodemp is not null) then-- exclusão/alteração
     execute procedure vct_tarefas_exec_thread(old.bdcodemp, null, null, old.bdcodobrser, old.bdcodproc);
  else
     execute procedure vct_tarefas_exec_thread(new.bdcodemp, null, null, new.bdcodobrser, new.bdcodproc);
end^

--VCT_TAREFAS_AUTOMATICAS - Lívia Falcão - 20/05/2026 - #243814
create or alter procedure VCT_TAREFAS_AUTOMATICAS_INSERT (
    BDCODEMP integer,
    BDCODST integer,
    BDCODCOL integer,
    BDCODIMP integer,
    BDCODOBRIGACAO integer,
    BDCODSERVICO integer,
    BDCODTIPO integer,
    BDDATASOL date,
    BDDATASOLICITADA date,
    BDDATAPREVISAO date,
    BDDATAFIM date,
    BDREFSOL integer,
    BDTIPOSOLICITACAO smallint,
    BDVENCIMENTO date,
    BDENTREGA date,
    BDALERTA date,
    BDAGUARD smallint,
    BDSTATUSATUAL integer,
    BDCODPROC integer,
    BDCODSTVINCPROCESSO integer)
AS
BEGIN
    INSERT INTO VCT_EMPRESA_TSOLICITATAREFA (
        BDCODEMP, BDCODST, BDCODCOL, BDCODIMP, BDCODOBRIGACAO,
        BDCODSERVICO, BDCODTIPO, BDDATASOL, BDDATASOLICITADA,
        BDDATAPREVISAO, BDDATAFIM, BDREFSOL, BDTIPOSOLICITACAO,
        BDVENCIMENTO, BDENTREGA, BDALERTA, BDAGUARD,
        BDSTATUSATUAL, BDCODPROC, BDCODSTVINCPROCESSO
    ) VALUES (
        :BDCODEMP, :BDCODST, :BDCODCOL, :BDCODIMP, :BDCODOBRIGACAO,
        :BDCODSERVICO, :BDCODTIPO, :BDDATASOL, :BDDATASOLICITADA,
        :BDDATAPREVISAO, :BDDATAFIM, :BDREFSOL, :BDTIPOSOLICITACAO,
        :BDVENCIMENTO, :BDENTREGA, :BDALERTA, :BDAGUARD,
        :BDSTATUSATUAL, :BDCODPROC, :BDCODSTVINCPROCESSO
    );

    -- Se o status atual não for 6 (e não for nulo), registra no histórico
    IF ((:BDSTATUSATUAL IS NOT NULL) AND (:BDSTATUSATUAL <> 6)) THEN
        EXECUTE PROCEDURE VCT_EMPRESA_THISTORICO_STATUS(:BDCODEMP, NULL, :BDSTATUSATUAL,:BDCODOBRIGACAO, :BDCODSERVICO, :BDCODIMP);
END^

create or alter procedure VCT_TAREFAS_AUTOMATICAS_OBR (
    CODEMP integer = 0,
    data date = current_date,
    OBRIGACAO integer = null,
    STATUS integer = null,
    PROCESSO integer = null,
    "MANUAL" boolean = false,
    ESOCIAL integer = null)
returns (
    TOTAL integer,
    OBRIGACOES integer)
as
declare variable WCURRENT_DATE date;
declare variable WCURRENT_REF integer;
declare variable WBDCODEMP integer;
declare variable WBDCODCOL integer;
declare variable WBDCODIMP integer;
declare variable WBDCODOBRIGACAO integer;
declare variable WBDCODSERVICO integer;
declare variable WBDCODTIPO integer;
declare variable WBDDATASOL date;
declare variable WBDDATASOLICITADA date;
declare variable WBDDATAPREVISAO date;
declare variable WBDDATAFIM date;
declare variable WBDPERIODICIDADE integer;
declare variable WBDREFSOL integer;
declare variable WBDTIPOSOLICITACAO smallint;
declare variable WBDVENCIMENTO date;
declare variable WBDENTREGA date;
declare variable WBDALERTA date;
declare variable WBDDIASEMANA integer;
declare variable WBDANTECIPAR varchar(5);
declare variable WBDDIAENTREGACAD integer;
declare variable WBDCODCID integer;
declare variable WBDCLASSIFICACAO varchar(60);
declare variable WBDDESCRICAO varchar(100);
declare variable WDIA_CAD integer;
declare variable WANTECIPAR_CAD varchar(5);
declare variable WVENCE_CAD integer;
declare variable WPERIODICIDADE_CAD integer;
declare variable WALERTA_CAD integer;
declare variable WENTREGA_CAD integer;
declare variable WCODCID_CAD integer;
declare variable WMESVENCE_CAD integer;
declare variable WBDCODPROC integer;
declare variable WBDCODSTVINCPROCESSO integer;
declare variable WBDAGUARD smallint;
declare variable WBDSTATUS integer;
declare variable WCONT integer;
declare variable WDATA date;
declare variable WMES integer;
declare variable WANO integer;
declare variable WDATAVENC date;
declare variable WSEFIP varchar(5);
declare variable WCODEMPCOMPARA integer;
declare variable WCONFIG_EMP smallint;
BEGIN
    WCURRENT_DATE = DATA;
    WCURRENT_REF = CAST(EXTRACT(YEAR FROM DATA) || LPAD(EXTRACT(MONTH FROM DATA), 2, 0) AS INTEGER);
    WBDSTATUS = COALESCE(STATUS, 6);
    WBDAGUARD = CASE WHEN STATUS = 5 THEN 1 ELSE NULL END;
    TOTAL = 0;
    OBRIGACOES = 0;
    WCODEMPCOMPARA = NULL;

    WCONFIG_EMP = 0;
    IF (EXISTS(SELECT 1 FROM VCT_CONFIG_TAREFA_EMPRESA)) THEN
        WCONFIG_EMP = 1;

    FOR
        SELECT
            TRIB.BDCODEMP,
            CASE WHEN (:ESOCIAL IS NOT NULL) THEN COL.BDCODCOL ELSE NULL END AS BDCODCOL,
            NULL AS BDCODIMP,
            TOBR.BDCODOBRSER AS BDCODOBRIGACAO,
            NULL AS BDCODSERVICO,
            501 AS BDCODTIPO,
            CAST(:WCURRENT_DATE AS DATE) AS BDDATASOL,
            CASE WHEN (:ESOCIAL IS NOT NULL) THEN ARQ.BDDATAGERADO ELSE NULL END AS BDDATASOLICITADA,
            NULL AS BDDATAPREVISAO,
            NULL AS BDDATAFIM,
            TOBR.BDPERIODICIDADE,
            CASE WHEN (:ESOCIAL IS NOT NULL) THEN ARQ.BDREFARQ ELSE :WCURRENT_REF END AS BDREFSOL,
            1 AS BDTIPOSOLICITACAO,
            CASE WHEN (:ESOCIAL IS NOT NULL) THEN ARQ.BDDATAGERADO + 1 ELSE NULL END AS BDVENCIMENTO,
            CASE WHEN (:ESOCIAL IS NOT NULL) THEN ARQ.BDDATAGERADO ELSE NULL END AS BDENTREGA,
            CASE WHEN (:ESOCIAL IS NOT NULL) THEN ARQ.BDDATAGERADO ELSE NULL END AS BDALERTA,
            COALESCE(TOBR.BDDIASEMANA, 0) AS BDDIASEMANA,
            TOBR.BDANTECIPAR,
            COALESCE(TOBR.BDENTREGA, 0) AS BDDIAENTREGACAD,
            TOBR.BDCODCID,
            TOBR.BDCLASSIFICACAO,
            TOBR.BDDESCRICAO,
            TOBR.BDDIA AS WDIA_CAD,
            TOBR.BDANTECIPAR AS WANTECIPAR_CAD,
            TOBR.BDVENCE AS WVENCE_CAD,
            TOBR.BDPERIODICIDADE AS WPERIODICIDADE_CAD,
            TOBR.BDALERTA AS WALERTA_CAD,
            TOBR.BDENTREGA AS WENTREGA_CAD,
            TOBR.BDCODCID AS WCODCID_CAD,
            TOBR.BDMESVENCE AS WMESVENCE_CAD,
            TRIB.BDCODPROC
        FROM VCT_TRIBUTARIO_EMPRESA TRIB
        JOIN VCT_BASE_OBRIGACAO TOBR ON TOBR.BDCODOBRSER = TRIB.BDCODOBR
        JOIN TEMPRESAS TEMP ON TEMP.BDCODEMP = TRIB.BDCODEMP AND (
            CASE
                WHEN :MANUAL THEN
                    CAST(EXTRACT(YEAR FROM TEMP.BDDATAINIATIVEMP) || LPAD(EXTRACT(MONTH FROM TEMP.BDDATAINIATIVEMP), 2, 0) AS INTEGER) < :WCURRENT_REF
                    AND CAST(EXTRACT(YEAR FROM TEMP.BDDATAINIATIVEMP) || LPAD(EXTRACT(MONTH FROM TEMP.BDDATAINIATIVEMP), 2, 0) AS INTEGER) > :WCURRENT_REF
                ELSE
                    TEMP.BDDATAINIATIVEMP < :WCURRENT_DATE AND (TEMP.BDDATAFIMATIVEMP > :WCURRENT_DATE)
            END OR TEMP.BDDATAFIMATIVEMP IS NULL
        )
        LEFT JOIN VFIN_BASE_TCLIENTE CLI ON CLI.BDCODCLI = TEMP.BDCODCLI
        LEFT JOIN VRH_ESOCIAL_TARQUIVO ARQ ON ARQ.BDCODEMP = TEMP.BDCODEMP
            AND ARQ.BDCODTIPO = TOBR.BDCODEVTESOCIAL
            AND ARQ.BDREFARQ = :WCURRENT_REF
        LEFT JOIN VRH_ESOCIAL_TCOLABORADOR COL ON COL.BDCODEMP = ARQ.BDCODEMP AND COL.BDCODIGO = ARQ.BDCODIGO
        WHERE ((TOBR.BDCRIACAO <= :WCURRENT_DATE) OR (TOBR.BDCRIACAO IS NULL))
          AND ((TOBR.BDEXTINTO >= :WCURRENT_DATE) OR (TOBR.BDEXTINTO IS NULL))
          AND ((:ESOCIAL IS NULL) OR (ARQ.BDCODIGO IS NOT NULL))
          AND (COALESCE(CLI.BDCODTIPOCLI, 0) <> 3)
          AND TOBR.BDTIPO = 1
          AND COALESCE(TOBR.BDPERIODICIDADE, 0) <> 11
          AND ((:ESOCIAL IS NULL AND TOBR.BDCODEVTESOCIAL IS NULL) OR (:ESOCIAL IS NOT NULL AND TOBR.BDCODEVTESOCIAL IS NOT NULL))
          AND ((COALESCE(:CODEMP, 0) <> 0 AND TRIB.BDCODEMP = :CODEMP) OR COALESCE(:CODEMP, 0) = 0)
          AND ((:OBRIGACAO IS NULL) OR (TOBR.BDCODOBRSER = :OBRIGACAO))
          AND (
              (TOBR.BDPERIODICIDADE = 10 AND CAST(SUBSTRING(TRIB.BDREFINI FROM 1 FOR 4) AS INTEGER) <= CAST(SUBSTRING(:WCURRENT_REF FROM 1 FOR 4) AS INTEGER))
              OR
              (TOBR.BDPERIODICIDADE <> 10 AND TRIB.BDREFINI <= :WCURRENT_REF)
          )
          AND (COALESCE(TRIB.BDREFFIN, :WCURRENT_REF) >= :WCURRENT_REF OR COALESCE(TRIB.BDREFFIN, 0) = 0)
          AND ((:PROCESSO IS NULL) OR (COALESCE(TRIB.BDREFFINPROC, :WCURRENT_REF) >= :WCURRENT_REF))
          AND ((:PROCESSO IS NULL AND TRIB.BDCODPROC IS NULL) OR (:PROCESSO IS NOT NULL AND TRIB.BDCODPROC = :PROCESSO))
          AND ((:WCONFIG_EMP = 0) OR EXISTS(SELECT 1 FROM VCT_CONFIG_TAREFA_EMPRESA WHERE BDCODEMP = TRIB.BDCODEMP))
        INTO
            :WBDCODEMP, :WBDCODCOL, :WBDCODIMP, :WBDCODOBRIGACAO, :WBDCODSERVICO, :WBDCODTIPO,
            :WBDDATASOL, :WBDDATASOLICITADA, :WBDDATAPREVISAO, :WBDDATAFIM,
            :WBDPERIODICIDADE, :WBDREFSOL, :WBDTIPOSOLICITACAO,
            :WBDVENCIMENTO, :WBDENTREGA, :WBDALERTA, :WBDDIASEMANA, :WBDANTECIPAR, :WBDDIAENTREGACAD,
            :WBDCODCID, :WBDCLASSIFICACAO, :WBDDESCRICAO,
            :WDIA_CAD, :WANTECIPAR_CAD, :WVENCE_CAD, :WPERIODICIDADE_CAD, :WALERTA_CAD,
            :WENTREGA_CAD, :WCODCID_CAD, :WMESVENCE_CAD, :WBDCODPROC
    DO
    BEGIN
      WCURRENT_DATE=data; -- resetar data antes de gerar
      if((WBDDATASOLICITADA is null)or(WBDVENCIMENTO is null)or(WBDENTREGA is null)or(WBDALERTA is null))then
        select first 1 BDDATA as BDDATASOLICITADA,BDDATA as BDVENCIAMENTO,BDALERTA,BDENTREGA
        from GET_VENCIMENTO_TAREFAS(:WCURRENT_DATE,:WDIA_CAD,:WANTECIPAR_CAD,:WVENCE_CAD,:WPERIODICIDADE_CAD,coalesce(:WALERTA_CAD,0),coalesce(:WENTREGA_CAD,0),:WMESVENCE_CAD,:WBDCODEMP,1,:WBDDIASEMANA)
        into :WBDDATASOLICITADA,:WBDVENCIMENTO,:WBDALERTA,:WBDENTREGA;

      -- Para garantir que não lance as próximas tarefas como aguardando retorno indevidamente
      WBDSTATUS=6;
      WBDAGUARD=null;
      if(STATUS is not null)then
      begin
        WBDSTATUS=STATUS;
        if(STATUS=5)then
          WBDAGUARD=1;
      end

      WSEFIP='';
      if(WBDCLASSIFICACAO='01.01.01.01.0014')then -- SEFIP-Sem movimento
      begin
        WDATA=cast(substring(WBDREFSOL from 5 for 2)||'-01-'||substring(WBDREFSOL from 1 for 4)as date);
        WDATA=ADDMONTH(WDATA,-1);
        WBDREFSOL=substring(WDATA from 1 for 4)||substring(WDATA from 6 for 2);
        select first 1 upper(BDRESULT)
        from VCT_TAREFA_SEFIPSEMMOVIMENTO(:WBDCODEMP,:WCURRENT_DATE)
        into :WSEFIP;
        WBDSTATUS=5;
        WBDAGUARD=1;
      end

      if((upper(WBDDESCRICAO)starting upper('Serviços Prestados'))or(upper(WBDDESCRICAO)starting upper('Serviços tomados')))then
      begin
        WBDSTATUS=5;
        WBDAGUARD=1;
      end

      if((WBDPERIODICIDADE=10)and
         ((WBDCLASSIFICACAO='01.01.02.01.0009')or(WBDCODOBRIGACAO=23)))then
        WBDAGUARD=1;

      -- Apenas empresas ativas
      if(((select first 1 BDSITEMP
            from TEMPRESAS_REF
            where BDCODEMP=:WBDCODEMP and
                  BDREFEMP<=:WBDREFSOL
            order by BDREFEMP desc)<> 'TRUE')and
         ((WSEFIP='')or(WSEFIP='TRUE')))then
      begin
        if((PROCESSO is not null)and
           ((WBDCODSTVINCPROCESSO is null)or(coalesce(WCODEMPCOMPARA,0)<> WBDCODEMP)))then
        begin
          WBDCODSTVINCPROCESSO=null;
          select first 1 TSOL.BDCODSTVINCPROCESSO
          from VCT_EMPRESA_TSOLICITATAREFA TSOL
          where(TSOL.BDCODEMP=:WBDCODEMP and
                TSOL.BDCODPROC=:WBDCODPROC and
                TSOL.BDREFSOL=:WBDREFSOL)
          into :WBDCODSTVINCPROCESSO;
        end

        -- mensal-vencimento conforme parâmetros
        if((WBDPERIODICIDADE in(0,1,2,3,4,5,6))or
            -- trimestral-gera março,junho,setembro,dezembro com vencimento conforme parametros
           ((WBDPERIODICIDADE=7)and(substring(WBDREFSOL from 5 for 2)in(3,6,9,12)))or
            -- semestral-gera junho,dezembro
           ((WBDPERIODICIDADE=13)and(substring(WBDREFSOL from 5 for 2)in(6,12)))or
            -- anual
           (WBDPERIODICIDADE=10))then
        begin
          if(WBDPERIODICIDADE=0)then -- se for segunda feira criar tarefa automática semanal
          begin
            -- verifica se há a obrigação nas tarefas
            if((select first 1 BDCODST
                 from VCT_EMPRESA_TSOLICITATAREFA
                 where BDCODEMP=:WBDCODEMP and BDCODOBRIGACAO=:WBDCODOBRIGACAO and
                       BDREFSOL=:WBDREFSOL and
                       -- Gilberto-06/02/2025-#213616
                       -- BDVENCIMENTO=:WDATAVENCAUX and BDVENCIMENTO=:WBDVENCIMENTO and
                       coalesce(BDCODPROC,0)=coalesce(:WBDCODPROC,0))is null)then
            begin
              execute procedure VCT_TAREFAS_AUTOMATICAS_INSERT(:WBDCODEMP,null,:WBDCODCOL,:WBDCODIMP,:WBDCODOBRIGACAO,:WBDCODSERVICO,:WBDCODTIPO,:WBDDATASOL,:WBDDATASOLICITADA,
              :WBDDATAPREVISAO,:WBDDATAFIM,:WBDREFSOL,:WBDTIPOSOLICITACAO,:WBDVENCIMENTO,:WBDENTREGA,:WBDALERTA,:WBDAGUARD,:WBDSTATUS,:WBDCODPROC,:WBDCODSTVINCPROCESSO);

              OBRIGACOES=OBRIGACOES+1;
              TOTAL=TOTAL+1;
            end
          end
          else
          begin
            -- Tarefas mensais
            if(WBDPERIODICIDADE in(1,2,3,4,5,6))then
            begin
              if(WDIA_CAD is null or WDIA_CAD=0)then
                WDIA_CAD=1;

              select first 1 BDDATA
              from GET_VENCIMENTO_TAREFAS(:WCURRENT_DATE,:WDIA_CAD,:WANTECIPAR_CAD,:WVENCE_CAD,:WPERIODICIDADE_CAD,coalesce(:WALERTA_CAD,0),coalesce(:WENTREGA_CAD,0),0,:WBDCODEMP,1,:WBDDIASEMANA)
              into :WDATAVENC;

              if(WCURRENT_DATE<=WDATAVENC)then
              begin
                WMES=WBDREFSOL;
              end
              else
              begin
                WMES=WBDREFSOL+1;
                if(substring(WMES from 5 for 2)='13')then
                  WMES=(extract(year from WCURRENT_DATE)+ 1)* 100+1;

                select first 1 BDDATA,BDALERTA,BDENTREGA
                from GET_VENCIMENTO_TAREFAS(ADDMONTH(:WCURRENT_DATE,1),:WDIA_CAD,:WANTECIPAR_CAD,:WVENCE_CAD,:WPERIODICIDADE_CAD,coalesce(:WALERTA_CAD,0),coalesce(:WENTREGA_CAD,0),0,:WBDCODEMP,1,:WBDDIASEMANA)
                into :WBDVENCIMENTO,:WBDALERTA,:WBDENTREGA;

                WBDREFSOL=WMES;
              end
            end
            else

            -- Tarefas anuais
            if(WBDPERIODICIDADE=10)then
            begin
              if(WDIA_CAD is null or WDIA_CAD=0)then
                WDIA_CAD=1;
              if(WMESVENCE_CAD is null or WMESVENCE_CAD=0)then
                WMESVENCE_CAD=1;

              select first 1 BDDATA from GET_VENCIMENTO_TAREFAS(cast(extract(year from :WCURRENT_DATE)||'-01-01' as date), :WDIA_CAD, :WANTECIPAR_CAD, 0,
                :WPERIODICIDADE_CAD, coalesce(:WALERTA_CAD,0), coalesce(:WENTREGA_CAD,0), :WMESVENCE_CAD, :WBDCODEMP, 1, :WBDDIASEMANA)
                into :WDATAVENC;

                if (WCURRENT_DATE <= WDATAVENC) then
                 WANO = extract(year from WCURRENT_DATE);
                else
                 WANO = extract(year from WCURRENT_DATE) + 1;


              WBDREFSOL=((WANO-1)* 100+1);

              select first 1 BDDATA,BDALERTA,BDENTREGA
              from GET_VENCIMENTO_TAREFAS(cast(:WANO||'-01-01' as date),:WDIA_CAD,:WANTECIPAR_CAD, 0,:WPERIODICIDADE_CAD,coalesce(:WALERTA_CAD,0),coalesce(:WENTREGA_CAD,0),:WMESVENCE_CAD,:WBDCODEMP,1,:WBDDIASEMANA)
              into :WBDVENCIMENTO,:WBDALERTA,:WBDENTREGA;
            end

            -- verifica se há a obrigação nas tarefas
            if((select first 1 BDCODST from VCT_EMPRESA_TSOLICITATAREFA
             where BDCODEMP=:WBDCODEMP and
             BDCODOBRIGACAO=:WBDCODOBRIGACAO and
             BDREFSOL=:WBDREFSOL and
             coalesce(BDCODPROC,0)=coalesce(:WBDCODPROC,0))is null)then
            begin
              execute procedure VCT_TAREFAS_AUTOMATICAS_INSERT(:WBDCODEMP,null,:WBDCODCOL,:WBDCODIMP,:WBDCODOBRIGACAO,:WBDCODSERVICO,:WBDCODTIPO,:WBDDATASOL,:WBDDATASOLICITADA,
              :WBDDATAPREVISAO,:WBDDATAFIM,:WBDREFSOL,:WBDTIPOSOLICITACAO, :WBDVENCIMENTO,:WBDENTREGA,:WBDALERTA,:WBDAGUARD,:WBDSTATUS,:WBDCODPROC,:WBDCODSTVINCPROCESSO);

              OBRIGACOES=OBRIGACOES+1;
              TOTAL=TOTAL+1;
            end
          end
        end
        else
        if(((WBDPERIODICIDADE=8)and(substring(WBDREFSOL from 5 for 2)in(3,6,9,12)))or
           ((WBDPERIODICIDADE=9)and(substring(WBDREFSOL from 5 for 2)in(1,4,7,10))))then
        begin
          WCONT=0;
          -- Gerar quotas do imposto parcelado-vctos
          if(WBDPERIODICIDADE=9)then
            WCURRENT_DATE=ADDMONTH(:WCURRENT_DATE,-1);
          WDATA=:WCURRENT_DATE;
          while(WCONT<=2)do
          begin
            -- Gerar quotas do imposto parcelado-vctos
            if(WCONT>0)then
              WDATA=ADDMONTH(:WCURRENT_DATE,WCONT);
            -- Gerar quotas do imposto parcelado-vctos
            WBDREFSOL=cast(substring(WCURRENT_DATE from 1 for 4)||substring(WCURRENT_DATE from 6 for 2)as integer);
            -- Alterado para usar a nova rotina
            select first 1 BDDATA as BDDATASOLICITADA,BDDATA as BDVENCIMENTO,BDALERTA,BDENTREGA
            from GET_VENCIMENTO_TAREFAS(:WDATA,:WDIA_CAD,:WANTECIPAR_CAD,:WVENCE_CAD,:WPERIODICIDADE_CAD,coalesce(:WALERTA_CAD,0),coalesce(:WENTREGA_CAD,0),:WMESVENCE_CAD,:WBDCODEMP,1,:WBDDIASEMANA)
            into :WBDDATASOLICITADA,:WBDVENCIMENTO,:WBDENTREGA,:WBDALERTA;

            if((select first 1 BDCODST
                 from VCT_EMPRESA_TSOLICITATAREFA
                 where BDCODEMP=:WBDCODEMP and
                       BDCODOBRIGACAO=:WBDCODOBRIGACAO and
                       BDREFSOL=:WBDREFSOL and
                       BDVENCIMENTO=:WBDVENCIMENTO and
                       coalesce(BDCODPROC,0)=coalesce(:WBDCODPROC,0))is null)then
            begin
              execute procedure VCT_TAREFAS_AUTOMATICAS_INSERT(:WBDCODEMP,null,:WBDCODCOL,:WBDCODIMP,:WBDCODOBRIGACAO,:WBDCODSERVICO,:WBDCODTIPO,:WBDDATASOL,:WBDDATASOLICITADA,
              :WBDDATAPREVISAO,:WBDDATAFIM,:WBDREFSOL,:WBDTIPOSOLICITACAO,:WBDVENCIMENTO,:WBDENTREGA,:WBDALERTA,:WBDAGUARD,:WBDSTATUS,:WBDCODPROC,:WBDCODSTVINCPROCESSO);

              OBRIGACOES=OBRIGACOES+1;
              TOTAL=TOTAL+1;
            end
            WCONT=WCONT+1;
          end
        end
        else
        if((WBDPERIODICIDADE=12)or --Periodicidade diária,verificação todos os dias(não usa parâmetro de antecipação de vencimento é o próprio dia)
           ((WBDPERIODICIDADE=14)and(WBDVENCIMENTO is not null)and(WBDENTREGA is not null)and(WBDALERTA is not null)))then -- dias úteis
        begin
          if((select first 1 BDCODST
               from VCT_EMPRESA_TSOLICITATAREFA
               where BDCODEMP=:WBDCODEMP and
                     BDCODOBRIGACAO=:WBDCODOBRIGACAO and
                     BDREFSOL=:WBDREFSOL and
                     BDVENCIMENTO=:WCURRENT_DATE and
                     coalesce(BDCODPROC,0)=coalesce(:WBDCODPROC,0))is null)then
          begin
            if(WBDPERIODICIDADE <> 14)then
            begin
              WBDVENCIMENTO=WCURRENT_DATE;
              WBDENTREGA=WCURRENT_DATE;
              WBDALERTA=WCURRENT_DATE;
            end
            execute procedure VCT_TAREFAS_AUTOMATICAS_INSERT(:WBDCODEMP,null,:WBDCODCOL,:WBDCODIMP,:WBDCODOBRIGACAO,:WBDCODSERVICO,:WBDCODTIPO,:WBDDATASOL,:WBDDATASOLICITADA,
            :WBDDATAPREVISAO,:WBDDATAFIM,:WBDREFSOL,:WBDTIPOSOLICITACAO,:WBDVENCIMENTO,:WBDENTREGA,:WBDALERTA,:WBDAGUARD,:WBDSTATUS,:WBDCODPROC,:WBDCODSTVINCPROCESSO);

            OBRIGACOES=OBRIGACOES+1;
            TOTAL=TOTAL+1;
          end
        end
      end
      WCODEMPCOMPARA=:WBDCODEMP;
    end
    SUSPEND;
  end^

create or alter procedure VCT_TAREFAS_AUTOMATICAS_SER (
    CODEMP integer = 0,
    data date = current_date,
    SERVICO integer = null,
    STATUS integer = null,
    PROCESSO integer = null,
    "MANUAL" boolean = false)
returns (
    TOTAL integer,
    SERVICOS integer)
as
declare variable WCURRENT_DATE date;
declare variable WCURRENT_REF integer;
declare variable WBDCODEMP integer;
declare variable WBDCODCOL integer;
declare variable WBDCODIMP integer;
declare variable WBDCODOBRIGACAO integer;
declare variable WBDCODSERVICO integer;
declare variable WBDCODTIPO integer;
declare variable WBDDATASOL date;
declare variable WBDDATASOLICITADA date;
declare variable WBDDATAPREVISAO date;
declare variable WBDDATAFIM date;
declare variable WBDPERIODICIDADE integer;
declare variable WBDREFSOL integer;
declare variable WBDTIPOSOLICITACAO smallint;
declare variable WBDVENCIMENTO date;
declare variable WBDENTREGA date;
declare variable WBDALERTA date;
declare variable WBDDIASEMANA integer;
declare variable WBDANTECIPAR varchar(5);
declare variable WBDDIAENTREGACAD integer;
declare variable WBDCODCID integer;
declare variable WBDCLASSIFICACAO varchar(60);
declare variable WBDDESCRICAO varchar(100);
declare variable WDIA_CAD integer;
declare variable WANTECIPAR_CAD varchar(5);
declare variable WVENCE_CAD integer;
declare variable WPERIODICIDADE_CAD integer;
declare variable WALERTA_CAD integer;
declare variable WENTREGA_CAD integer;
declare variable WCODCID_CAD integer;
declare variable WMESVENCE_CAD integer;
declare variable WBDCODPROC integer;
declare variable WBDCODSTVINCPROCESSO integer;
declare variable WBDAGUARD smallint;
declare variable WBDSTATUS integer;
declare variable WCONT integer;
declare variable WDATA date;
declare variable WMES integer;
declare variable WANO integer;
declare variable WDATAVENC date;
declare variable WCODEMPCOMPARA integer;
declare variable WCONFIG_EMP smallint;
BEGIN
    WCURRENT_DATE = DATA;
    WCURRENT_REF = CAST(EXTRACT(YEAR FROM DATA) || LPAD(EXTRACT(MONTH FROM DATA), 2, 0) AS INTEGER);
    WBDSTATUS = COALESCE(STATUS, 6);
    WBDAGUARD = CASE WHEN STATUS = 5 THEN 1 ELSE NULL END;
    TOTAL = 0;
    SERVICOS = 0;
    WCODEMPCOMPARA = NULL;

    WCONFIG_EMP = 0;
    IF (EXISTS(SELECT 1 FROM VCT_CONFIG_TAREFA_EMPRESA)) THEN
        WCONFIG_EMP = 1;

    FOR
        SELECT
            TRIB.BDCODEMP,
            NULL AS BDCODCOL,
            NULL AS BDCODIMP,
            NULL AS BDCODOBRIGACAO,
            TSER.BDCODOBRSER AS BDCODSERVICO,
            501 AS BDCODTIPO,
            CAST(:WCURRENT_DATE AS DATE) AS BDDATASOL,
            NULL AS BDDATASOLICITADA,
            NULL AS BDDATAPREVISAO,
            NULL AS BDDATAFIM,
            TSER.BDPERIODICIDADE,
            :WCURRENT_REF AS BDREFSOL,
            2 AS BDTIPOSOLICITACAO,
            NULL AS BDVENCIMENTO,
            NULL AS BDENTREGA,
            NULL AS BDALERTA,
            COALESCE(TSER.BDDIASEMANA, 0) AS BDDIASEMANA,
            TSER.BDANTECIPAR,
            COALESCE(TSER.BDENTREGA, 0) AS BDDIAENTREGACAD,
            NULL AS BDCODCID,
            NULL AS BDCLASSIFICACAO,
            TSER.BDDESCRICAO,
            TSER.BDDIA AS WDIA_CAD,
            TSER.BDANTECIPAR AS WANTECIPAR_CAD,
            TSER.BDVENCE AS WVENCE_CAD,
            TSER.BDPERIODICIDADE AS WPERIODICIDADE_CAD,
            TSER.BDALERTA AS WALERTA_CAD,
            TSER.BDENTREGA AS WENTREGA_CAD,
            NULL AS WCODCID_CAD,
            TSER.BDMESVENCE AS WMESVENCE_CAD,
            TRIB.BDCODPROC
        FROM VCT_TRIBUTARIO_EMPRESA TRIB
        JOIN VCT_BASE_SERVICO TSER ON TSER.BDCODOBRSER = TRIB.BDCODSER
        JOIN TEMPRESAS TEMP ON TEMP.BDCODEMP = TRIB.BDCODEMP AND (
            CASE
                WHEN :MANUAL THEN
                    CAST(EXTRACT(YEAR FROM TEMP.BDDATAINIATIVEMP) || LPAD(EXTRACT(MONTH FROM TEMP.BDDATAINIATIVEMP), 2, 0) AS INTEGER) < :WCURRENT_REF
                    AND CAST(EXTRACT(YEAR FROM TEMP.BDDATAINIATIVEMP) || LPAD(EXTRACT(MONTH FROM TEMP.BDDATAINIATIVEMP), 2, 0) AS INTEGER) > :WCURRENT_REF
                ELSE
                    TEMP.BDDATAINIATIVEMP < :WCURRENT_DATE AND (TEMP.BDDATAFIMATIVEMP > :WCURRENT_DATE)
            END OR TEMP.BDDATAFIMATIVEMP IS NULL
        )
        LEFT JOIN VFIN_BASE_TCLIENTE CLI ON CLI.BDCODCLI = TEMP.BDCODCLI
        WHERE ((TSER.BDCRIACAO <= :WCURRENT_DATE) OR (TSER.BDCRIACAO IS NULL))
          AND ((TSER.BDEXTINTO >= :WCURRENT_DATE) OR (TSER.BDEXTINTO IS NULL))
          AND (COALESCE(CLI.BDCODTIPOCLI, 0) <> 3)
          AND TSER.BDTIPO = 1
          AND COALESCE(TSER.BDPERIODICIDADE, 0) <> 11
          AND ((COALESCE(:CODEMP, 0) <> 0 AND TRIB.BDCODEMP = :CODEMP) OR COALESCE(:CODEMP, 0) = 0)
          AND ((:SERVICO IS NULL) OR (TSER.BDCODOBRSER = :SERVICO))
          AND (
              (TSER.BDPERIODICIDADE = 10 AND CAST(SUBSTRING(TRIB.BDREFINI FROM 1 FOR 4) AS INTEGER) <= CAST(SUBSTRING(:WCURRENT_REF FROM 1 FOR 4) AS INTEGER))
              OR
              (TSER.BDPERIODICIDADE <> 10 AND TRIB.BDREFINI <= :WCURRENT_REF)
          )
          AND (COALESCE(TRIB.BDREFFIN, :WCURRENT_REF) >= :WCURRENT_REF OR COALESCE(TRIB.BDREFFIN, 0) = 0)
          AND ((:PROCESSO IS NULL) OR (COALESCE(TRIB.BDREFFINPROC, :WCURRENT_REF) >= :WCURRENT_REF))
          AND ((:PROCESSO IS NULL AND TRIB.BDCODPROC IS NULL) OR (:PROCESSO IS NOT NULL AND TRIB.BDCODPROC = :PROCESSO))
          AND ((:WCONFIG_EMP = 0) OR EXISTS(SELECT 1 FROM VCT_CONFIG_TAREFA_EMPRESA WHERE BDCODEMP = TRIB.BDCODEMP))
        INTO
            :WBDCODEMP, :WBDCODCOL, :WBDCODIMP, :WBDCODOBRIGACAO, :WBDCODSERVICO, :WBDCODTIPO,
            :WBDDATASOL, :WBDDATASOLICITADA, :WBDDATAPREVISAO, :WBDDATAFIM,
            :WBDPERIODICIDADE, :WBDREFSOL, :WBDTIPOSOLICITACAO,
            :WBDVENCIMENTO, :WBDENTREGA, :WBDALERTA, :WBDDIASEMANA, :WBDANTECIPAR, :WBDDIAENTREGACAD,
            :WBDCODCID, :WBDCLASSIFICACAO, :WBDDESCRICAO,
            :WDIA_CAD, :WANTECIPAR_CAD, :WVENCE_CAD, :WPERIODICIDADE_CAD, :WALERTA_CAD,
            :WENTREGA_CAD, :WCODCID_CAD, :WMESVENCE_CAD, :WBDCODPROC
    DO
    BEGIN
        WCURRENT_DATE=data; -- Resetar data antes de gerar
        if((WBDDATASOLICITADA is null)or(WBDVENCIMENTO is null)or(WBDENTREGA is null)or(WBDALERTA is null))then
          select first 1 BDDATA as BDDATASOLICITADA,BDDATA as BDVENCIAMENTO,BDALERTA,BDENTREGA
          from GET_VENCIMENTO_TAREFAS(:WCURRENT_DATE,:WDIA_CAD,:WANTECIPAR_CAD,:WVENCE_CAD,:WPERIODICIDADE_CAD,coalesce(:WALERTA_CAD,0),coalesce(:WENTREGA_CAD,0),:WMESVENCE_CAD,:WBDCODEMP,2,:WBDDIASEMANA)
          into :WBDDATASOLICITADA,:WBDVENCIMENTO,:WBDALERTA,:WBDENTREGA;
        -- Apenas empresas ativas
        if(((select first 1 BDSITEMP
              from TEMPRESAS_REF
              where BDCODEMP=:WBDCODEMP and
                    BDREFEMP<=:WBDREFSOL
              order by BDREFEMP desc)<> 'TRUE'))then
        begin
          if((PROCESSO is not null)and
             ((WBDCODSTVINCPROCESSO is null)or(coalesce(WCODEMPCOMPARA,0)<> WBDCODEMP)))then
          begin
            select first 1 TSOL.BDCODSTVINCPROCESSO
            from VCT_EMPRESA_TSOLICITATAREFA TSOL
            where(TSOL.BDCODEMP=:WBDCODEMP and
                  TSOL.BDCODPROC=:WBDCODPROC and
                  TSOL.BDREFSOL=:WBDREFSOL)
            into WBDCODSTVINCPROCESSO;
          end
          -- mensal-vencimento conforme parâmetros
          if((WBDPERIODICIDADE in(0,1,2,3,4,5,6))or
              -- trimestral-gera março,junho,setembro,dezembro com vencimento conforme parametros
             ((WBDPERIODICIDADE=7)and
             (substring(WBDREFSOL from 5 for 2)in(3,6,9,12)))or
              -- semestral-gera junho,dezembro
             ((WBDPERIODICIDADE=13)and
             (substring(WBDREFSOL from 5 for 2)in(6,12)))or
              -- anual-gera no primeiro mês do ano com vencimento no ano seguinte
             (WBDPERIODICIDADE=10))then
          begin
            if(WBDPERIODICIDADE=0)then -- se for segunda feira criar tarefa automática semanal
            begin
              -- verifica se há o serviço nas tarefas
              if((select first 1 BDCODST
                   from VCT_EMPRESA_TSOLICITATAREFA
                   where BDCODEMP=:WBDCODEMP and
                         BDCODSERVICO=:WBDCODSERVICO and
                         BDREFSOL=:WBDREFSOL and
                         -- Gilberto-06/02/2025-#213616
                         BDVENCIMENTO=:WBDVENCIMENTO and
                         coalesce(BDCODPROC,0)=coalesce(:WBDCODPROC,0))is null)then
              begin
                execute procedure VCT_TAREFAS_AUTOMATICAS_INSERT(:WBDCODEMP,null,:WBDCODCOL,:WBDCODIMP,:WBDCODOBRIGACAO,:WBDCODSERVICO,:WBDCODTIPO,:WBDDATASOL,:WBDDATASOLICITADA,
                :WBDDATAPREVISAO,:WBDDATAFIM,:WBDREFSOL,:WBDTIPOSOLICITACAO,:WBDVENCIMENTO,:WBDENTREGA,:WBDALERTA,:WBDAGUARD,:WBDSTATUS,:WBDCODPROC,:WBDCODSTVINCPROCESSO);

                SERVICOS=SERVICOS+1;
                TOTAL=TOTAL+1;
              end
            end
            else
            begin
              -- TAREFAS MENSAIS
              if(WBDPERIODICIDADE in(1,2,3,4,5,6))then
              begin
                if(WDIA_CAD is null or WDIA_CAD=0)then
                  WDIA_CAD=1;

                select first 1 BDDATA  from GET_VENCIMENTO_TAREFAS(:WCURRENT_DATE, :WDIA_CAD, :WANTECIPAR_CAD, :WVENCE_CAD, :WPERIODICIDADE_CAD, coalesce(:WALERTA_CAD,0), coalesce(:WENTREGA_CAD,0),
                0, :WBDCODEMP, 2, :WBDDIASEMANA)
                into :WDATAVENC;

                if (WCURRENT_DATE <= WDATAVENC) then
                begin
                  WMES=WBDREFSOL;
                end
                else
                begin
                  WMES=WBDREFSOL+1;
                  if(substring(WMES from 5 for 2)=13)then
                    WMES=(extract(year from WCURRENT_DATE)+ 1)* 100+1;

                  select first 1 BDDATA,BDALERTA,BDENTREGA
                  from GET_VENCIMENTO_TAREFAS(cast(substring(:WMES from 1 for 4)||'-'||substring(:WMES from 5 for 2)||'-01' as date),:WDIA_CAD,:WANTECIPAR_CAD,:WVENCE_CAD,:WPERIODICIDADE_CAD,coalesce(:WALERTA_CAD,0),coalesce(:WENTREGA_CAD,0),:WMESVENCE_CAD,:WBDCODEMP,1,:WBDDIASEMANA)
                  into :WBDVENCIMENTO,:WBDALERTA,:WBDENTREGA;
                  WBDDATASOLICITADA=WBDVENCIMENTO;
                  WBDREFSOL=WMES;
                end
              end
              else
              -- TAREFAS ANUAIS
              if(WBDPERIODICIDADE=10)then
              begin
                if(WDIA_CAD is null or WDIA_CAD=0)then
                  WDIA_CAD=1;
                if(WMESVENCE_CAD is null or WMESVENCE_CAD=0)then
                  WMESVENCE_CAD=1;

                select first 1 BDDATA from GET_VENCIMENTO_TAREFAS(cast(extract(year from :WCURRENT_DATE)||'-01-01' as date), 0, :WANTECIPAR_CAD, 0,
                :WPERIODICIDADE_CAD, coalesce(:WALERTA_CAD,0), coalesce(:WENTREGA_CAD,0), :WMESVENCE_CAD, :WBDCODEMP, 2, :WBDDIASEMANA)
                into :WDATAVENC;

                if (WCURRENT_DATE <= WDATAVENC) then
                 WANO = extract(year from WCURRENT_DATE);
                else
                 WANO = extract(year from WCURRENT_DATE) + 1;

                WBDREFSOL=((WANO-1)* 100+1);

                select first 1 BDDATA,BDALERTA,BDENTREGA
                from GET_VENCIMENTO_TAREFAS(cast(:WANO||'-01-01' as date),:WDIA_CAD,:WANTECIPAR_CAD, 0,:WPERIODICIDADE_CAD,coalesce(:WALERTA_CAD,0),coalesce(:WENTREGA_CAD,0),:WMESVENCE_CAD,:WBDCODEMP,1,:WBDDIASEMANA)
                into :WBDVENCIMENTO,:WBDALERTA,:WBDENTREGA;
              end
              -- verifica se há o serviço nas tarefas
              if((select first 1 BDCODST
                   from VCT_EMPRESA_TSOLICITATAREFA
                   where BDCODEMP=:WBDCODEMP and
                         BDCODSERVICO=:WBDCODSERVICO and
                         BDREFSOL=:WBDREFSOL and
                         coalesce(BDCODPROC,0)=coalesce(:WBDCODPROC,0))is null)then
              begin
                execute procedure VCT_TAREFAS_AUTOMATICAS_INSERT(:WBDCODEMP,null,:WBDCODCOL,:WBDCODIMP,:WBDCODOBRIGACAO,:WBDCODSERVICO,:WBDCODTIPO,:WBDDATASOL,:WBDDATASOLICITADA,
                :WBDDATAPREVISAO,:WBDDATAFIM,:WBDREFSOL,:WBDTIPOSOLICITACAO,:WBDVENCIMENTO,:WBDENTREGA,:WBDALERTA,:WBDAGUARD,:WBDSTATUS,:WBDCODPROC,:WBDCODSTVINCPROCESSO);

                SERVICOS=SERVICOS+1;
                TOTAL=TOTAL+1;
              end
            end
          end
          else
          if(((WBDPERIODICIDADE=8)and(substring(WBDREFSOL from 5 for 2)in(3,6,9,12)))or
             ((WBDPERIODICIDADE=9)and(substring(WBDREFSOL from 5 for 2)in(1,4,7,10))))then
          begin
            WCONT=0;
            -- Gerar quotas do imposto parcelado-vctos
            if(WBDPERIODICIDADE=9)then
              WCURRENT_DATE=ADDMONTH(:WCURRENT_DATE,-1);
            WDATA=:WCURRENT_DATE;
            while(WCONT<=2)do
            begin
              -- Gerar quotas do imposto parcelado-vctos
              if(WCONT>0)then
                WDATA=ADDMONTH(:WCURRENT_DATE,WCONT);
              -- Gerar quotas do imposto parcelado-vctos
              WBDREFSOL=cast(substring(WCURRENT_DATE from 1 for 4)||substring(WCURRENT_DATE from 6 for 2)as integer);
              select first 1 BDDATA as BDDATASOLICITADA,BDDATA as BDVENCIMENTO,BDALERTA,BDENTREGA
              from GET_VENCIMENTO_TAREFAS(:WDATA,:WDIA_CAD,:WANTECIPAR_CAD,:WVENCE_CAD,:WPERIODICIDADE_CAD,coalesce(:WALERTA_CAD,0),coalesce(:WENTREGA_CAD,0),:WMESVENCE_CAD,:WBDCODEMP,2,:WBDDIASEMANA)
              into :WBDDATASOLICITADA,:WBDVENCIMENTO,:WBDENTREGA,:WBDALERTA;

              -- verifica se há o serviço nas tarefas
              if((select first 1 BDCODST
                   from VCT_EMPRESA_TSOLICITATAREFA
                   where BDCODEMP=:WBDCODEMP and
                         BDCODSERVICO=:WBDCODSERVICO and
                         BDREFSOL=:WBDREFSOL and
                         BDVENCIMENTO=:WBDVENCIMENTO and
                         coalesce(BDCODPROC,0)=coalesce(:WBDCODPROC,0))is null)then
              begin
                execute procedure VCT_TAREFAS_AUTOMATICAS_INSERT(:WBDCODEMP,null,:WBDCODCOL,:WBDCODIMP,:WBDCODOBRIGACAO,:WBDCODSERVICO,:WBDCODTIPO,:WBDDATASOL,:WBDDATASOLICITADA,
                :WBDDATAPREVISAO,:WBDDATAFIM,:WBDREFSOL,:WBDTIPOSOLICITACAO,:WBDVENCIMENTO,:WBDENTREGA,:WBDALERTA,:WBDAGUARD,:WBDSTATUS,:WBDCODPROC,:WBDCODSTVINCPROCESSO);

                SERVICOS=SERVICOS+1;
                TOTAL=TOTAL+1;
              end
              WCONT=WCONT+1;
            end
          end
          else
          if((WBDPERIODICIDADE=12)or --Periodicidade diária,verificação todos os dias(não usa parâmetro de antecipação de vencimento é o próprio dia)
             ((WBDPERIODICIDADE=14)and(WBDVENCIMENTO is not null)and (WBDENTREGA is not null)and
             (WBDALERTA is not null)))then -- dias úteis
          begin
            if((select first 1 BDCODST
                 from VCT_EMPRESA_TSOLICITATAREFA
                 where BDCODEMP=:WBDCODEMP and
                       BDCODSERVICO=:WBDCODSERVICO and
                       BDREFSOL=:WBDREFSOL and
                       BDVENCIMENTO=:WCURRENT_DATE and
                       coalesce(BDCODPROC,0)=coalesce(:WBDCODPROC,0))is null)then
            begin
              if(WBDPERIODICIDADE <> 14)then
              begin
                WBDVENCIMENTO=WCURRENT_DATE;
                WBDENTREGA=WCURRENT_DATE;
                WBDALERTA=WCURRENT_DATE;
              end
              execute procedure VCT_TAREFAS_AUTOMATICAS_INSERT(:WBDCODEMP,null,:WBDCODCOL,:WBDCODIMP,:WBDCODOBRIGACAO,:WBDCODSERVICO,:WBDCODTIPO,:WBDDATASOL,:WBDDATASOLICITADA,
              :WBDDATAPREVISAO,:WBDDATAFIM,:WBDREFSOL,:WBDTIPOSOLICITACAO,:WBDVENCIMENTO,:WBDENTREGA,:WBDALERTA,:WBDAGUARD,:WBDSTATUS,:WBDCODPROC,:WBDCODSTVINCPROCESSO);

              SERVICOS=SERVICOS+1;
              TOTAL=TOTAL+1;

            end
          end
        end
        WCODEMPCOMPARA=:WBDCODEMP;
      end
      SUSPEND;
  end^

create or alter procedure VCT_TAREFAS_AUTOMATICAS_IMP (
    CODEMP integer = 0,
    data date = current_date,
    IMPOSTO integer = null,
    STATUS integer = null,
    PROCESSO integer = null,
    "MANUAL" boolean = false)
returns (
    TOTAL integer,
    IMPOSTOS integer)
as
declare variable WCURRENT_DATE date;
declare variable WCURRENT_REF integer;
declare variable WBDCODEMP integer;
declare variable WBDCODCOL integer;
declare variable WBDCODIMP integer;
declare variable WBDCODOBRIGACAO integer;
declare variable WBDCODSERVICO integer;
declare variable WBDCODTIPO integer;
declare variable WBDDATASOL date;
declare variable WBDDATASOLICITADA date;
declare variable WBDDATAPREVISAO date;
declare variable WBDDATAFIM date;
declare variable WBDPERIODICIDADE integer;
declare variable WBDREFSOL integer;
declare variable WBDTIPOSOLICITACAO smallint;
declare variable WBDVENCIMENTO date;
declare variable WBDENTREGA date;
declare variable WBDALERTA date;
declare variable WBDDIASEMANA integer;
declare variable WBDANTECIPAR varchar(5);
declare variable WBDDIAENTREGACAD integer;
declare variable WBDCODCID integer;
declare variable WBDCLASSIFICACAO varchar(60);
declare variable WBDDESCRICAO varchar(100);
declare variable WDIA_CAD integer;
declare variable WANTECIPAR_CAD varchar(5);
declare variable WVENCE_CAD integer;
declare variable WPERIODICIDADE_CAD integer;
declare variable WALERTA_CAD integer;
declare variable WENTREGA_CAD integer;
declare variable WCODCID_CAD integer;
declare variable WMESVENCE_CAD integer;
declare variable WBDCODPROC integer;
declare variable WBDCODSTVINCPROCESSO integer;
declare variable WBDAGUARD smallint;
declare variable WBDSTATUS integer;
declare variable WCONT integer;
declare variable WDATA date;
declare variable WMES integer;
declare variable WANO integer;
declare variable WDATAVENC date;
declare variable WCODEMPCOMPARA integer;
declare variable WCONFIG_EMP smallint;
BEGIN
    WCURRENT_DATE = DATA;
    WCURRENT_REF = CAST(EXTRACT(YEAR FROM DATA) || LPAD(EXTRACT(MONTH FROM DATA), 2, 0) AS INTEGER);
    WBDSTATUS = COALESCE(STATUS, 6);
    WBDAGUARD = CASE WHEN STATUS = 5 THEN 1 ELSE NULL END;
    TOTAL = 0;
    IMPOSTOS = 0;
    WCODEMPCOMPARA = NULL;

    WCONFIG_EMP = 0;
    IF (EXISTS(SELECT 1 FROM VCT_CONFIG_TAREFA_EMPRESA)) THEN
        WCONFIG_EMP = 1;

     FOR
        SELECT
            TRIB.BDCODEMP,
            NULL AS BDCODCOL,
            TIMP.BDCODIMP AS BDCODIMP,
            NULL AS BDCODOBRIGACAO,
            NULL AS BDCODSERVICO,
            501 AS BDCODTIPO,
            CAST(:WCURRENT_DATE AS DATE) AS BDDATASOL,
            NULL AS BDDATASOLICITADA,
            NULL AS BDDATAPREVISAO,
            NULL AS BDDATAFIM,
            COALESCE(TIMP.BDPERAPURACAO, 0) AS BDPERIODICIDADE,
            :WCURRENT_REF AS BDREFSOL,
            0 AS BDTIPOSOLICITACAO,
            NULL AS BDVENCIMENTO,
            NULL AS BDENTREGA,
            NULL AS BDALERTA,
            COALESCE(TIMP.BDDIASEMANA, 0) AS BDDIASEMANA,
            TIMP.BDANTECIPA AS BDANTECIPAR,
            COALESCE(TIMP.BDENTREGA, 0) AS BDDIAENTREGACAD,
            TIMP.BDCODCID,
            TIMP.BDDIAVENCTO AS WDIA_CAD,
            TIMP.BDANTECIPA AS WANTECIPAR_CAD,
            TIMP.BDMESVENCTO AS WVENCE_CAD,
            TIMP.BDPERAPURACAO AS WPERIODICIDADE_CAD,
            TIMP.BDALERTADIAS AS WALERTA_CAD,
            TIMP.BDENTREGA AS WENTREGA_CAD,
            TIMP.BDCODCID AS WCODCID_CAD,
            TIMP.BDMESVENCE AS WMESVENCE_CAD,
            TRIB.BDCODPROC
        FROM VCT_TRIBUTARIO_EMPRESA TRIB
        JOIN TIMPOSTO TIMP ON TIMP.BDCODIMP = TRIB.BDCODIMP
        JOIN TEMPRESAS TEMP ON TEMP.BDCODEMP = TRIB.BDCODEMP AND (
            CASE
                WHEN :MANUAL THEN
                    CAST(EXTRACT(YEAR FROM TEMP.BDDATAINIATIVEMP) || LPAD(EXTRACT(MONTH FROM TEMP.BDDATAINIATIVEMP), 2, 0) AS INTEGER) < :WCURRENT_REF
                    AND CAST(EXTRACT(YEAR FROM TEMP.BDDATAINIATIVEMP) || LPAD(EXTRACT(MONTH FROM TEMP.BDDATAINIATIVEMP), 2, 0) AS INTEGER) > :WCURRENT_REF
                ELSE
                    TEMP.BDDATAINIATIVEMP < :WCURRENT_DATE AND (TEMP.BDDATAFIMATIVEMP > :WCURRENT_DATE)
            END OR TEMP.BDDATAFIMATIVEMP IS NULL
        )
        LEFT JOIN VFIN_BASE_TCLIENTE CLI ON CLI.BDCODCLI = TEMP.BDCODCLI
        WHERE ((TIMP.BDDATACRIACAO <= :WCURRENT_DATE) OR (TIMP.BDDATACRIACAO IS NULL))
          AND ((TIMP.BDDATAEXTINTO >= :WCURRENT_DATE) OR (TIMP.BDDATAEXTINTO IS NULL))
          AND (COALESCE(CLI.BDCODTIPOCLI, 0) <> 3)
          AND TIMP.BDTIPOCLASSIMP = 1
          AND COALESCE(TIMP.BDPERAPURACAO, 0) <> 11
          AND ((COALESCE(:CODEMP, 0) <> 0 AND TRIB.BDCODEMP = :CODEMP) OR COALESCE(:CODEMP, 0) = 0)
          AND ((:IMPOSTO IS NULL) OR (TRIB.BDCODIMP = :IMPOSTO))
          AND (
              (TIMP.BDPERAPURACAO = 10 AND CAST(SUBSTRING(TRIB.BDREFINI FROM 1 FOR 4) AS INTEGER) <= CAST(SUBSTRING(:WCURRENT_REF FROM 1 FOR 4) AS INTEGER))
              OR
              (TIMP.BDPERAPURACAO <> 10 AND TRIB.BDREFINI <= :WCURRENT_REF)
          )
          AND (COALESCE(TRIB.BDREFFIN, :WCURRENT_REF) >= :WCURRENT_REF OR COALESCE(TRIB.BDREFFIN, 0) = 0)
          AND ((:PROCESSO IS NULL) OR (COALESCE(TRIB.BDREFFINPROC, :WCURRENT_REF) >= :WCURRENT_REF))
          AND ((:PROCESSO IS NULL AND TRIB.BDCODPROC IS NULL) OR (:PROCESSO IS NOT NULL AND TRIB.BDCODPROC = :PROCESSO))
          AND ((:WCONFIG_EMP = 0) OR EXISTS(SELECT 1 FROM VCT_CONFIG_TAREFA_EMPRESA WHERE BDCODEMP = TRIB.BDCODEMP))
        INTO
            :WBDCODEMP, :WBDCODCOL, :WBDCODIMP, :WBDCODOBRIGACAO, :WBDCODSERVICO, :WBDCODTIPO,
            :WBDDATASOL, :WBDDATASOLICITADA, :WBDDATAPREVISAO, :WBDDATAFIM,
            :WBDPERIODICIDADE, :WBDREFSOL, :WBDTIPOSOLICITACAO,
            :WBDVENCIMENTO, :WBDENTREGA, :WBDALERTA, :WBDDIASEMANA, :WBDANTECIPAR, :WBDDIAENTREGACAD,
            :WBDCODCID, :WDIA_CAD, :WANTECIPAR_CAD, :WVENCE_CAD, :WPERIODICIDADE_CAD, :WALERTA_CAD,
            :WENTREGA_CAD, :WCODCID_CAD, :WMESVENCE_CAD, :WBDCODPROC
    DO
    BEGIN
        WCURRENT_DATE=data; -- Resetar data antes de gerar
        if((WBDDATASOLICITADA is null)or(WBDVENCIMENTO is null)or(WBDENTREGA is null)or(WBDALERTA is null))then
          select first 1 BDDATA as BDDATASOLICITADA,BDDATA as BDVENCIAMENTO,BDALERTA,BDENTREGA
          from GET_VENCIMENTO_TAREFAS(:WCURRENT_DATE,:WDIA_CAD,:WANTECIPAR_CAD,:WVENCE_CAD,:WPERIODICIDADE_CAD,coalesce(:WALERTA_CAD,0),coalesce(:WENTREGA_CAD,0),:WMESVENCE_CAD,:WBDCODEMP,0,:WBDDIASEMANA)
          into :WBDDATASOLICITADA,:WBDVENCIMENTO,:WBDALERTA,:WBDENTREGA;

        -- Apenas empresas ativas
        if(((select first 1 BDSITEMP
              from TEMPRESAS_REF
              where BDCODEMP=:WBDCODEMP and
                    BDREFEMP<=:WBDREFSOL
              order by BDREFEMP desc)<> 'TRUE'))then
        begin
          if((PROCESSO is not null)and
             ((WBDCODSTVINCPROCESSO is null)or(coalesce(WCODEMPCOMPARA,0)<> WBDCODEMP)))then
          begin
            select first 1 TSOL.BDCODSTVINCPROCESSO
            from VCT_EMPRESA_TSOLICITATAREFA TSOL
            where(TSOL.BDCODEMP=:WBDCODEMP and
                  TSOL.BDCODPROC=:WBDCODPROC and
                  TSOL.BDREFSOL=:WBDREFSOL)
            into WBDCODSTVINCPROCESSO;
          end
          -- mensal-vencimento conforme parâmetros
          if((WBDPERIODICIDADE in(0,1,2,3,4,5,6))or
              -- trimestral-gera março,junho,setembro,dezembro com vencimento conforme parametros
             ((WBDPERIODICIDADE=7)and(substring(WBDREFSOL from 5 for 2)in(3,6,9,12)))or
              -- semestral-gera junho,dezembro
             ((WBDPERIODICIDADE=13)and(substring(WBDREFSOL from 5 for 2)in(6,12)))or
              -- anual
             (WBDPERIODICIDADE=10))then

          begin
            if(WBDPERIODICIDADE=0)then -- se for segunda feira criar tarefa automática semanal
            begin
              -- verifica se há a obrigação nas tarefas
              if((select first 1 BDCODST
                   from VCT_EMPRESA_TSOLICITATAREFA
                   where BDCODEMP=:WBDCODEMP and
                         BDCODIMP=:WBDCODIMP and
                         BDREFSOL=:WBDREFSOL and
                         BDVENCIMENTO=:WBDVENCIMENTO and
                         coalesce(BDCODPROC,0)=coalesce(:WBDCODPROC,0))is null)then
              begin
                execute procedure VCT_TAREFAS_AUTOMATICAS_INSERT(:WBDCODEMP,null,:WBDCODCOL,:WBDCODIMP,:WBDCODOBRIGACAO,:WBDCODSERVICO,:WBDCODTIPO,:WBDDATASOL,:WBDDATASOLICITADA,
                :WBDDATAPREVISAO,:WBDDATAFIM,:WBDREFSOL,:WBDTIPOSOLICITACAO,:WBDVENCIMENTO,:WBDENTREGA,:WBDALERTA,:WBDAGUARD,:WBDSTATUS,:WBDCODPROC,:WBDCODSTVINCPROCESSO);

                IMPOSTOS=IMPOSTOS+1;
                TOTAL=TOTAL+1;
              end
            end
            else
            begin
              -- TAREFAS MENSAIS
              if(WBDPERIODICIDADE in(1,2,3,4,5,6))then
              begin
                if(WDIA_CAD is null or WDIA_CAD=0)then
                  WDIA_CAD=1;

                select first 1 BDDATA from GET_VENCIMENTO_TAREFAS(:WCURRENT_DATE, :WDIA_CAD, :WANTECIPAR_CAD, :WVENCE_CAD, :WPERIODICIDADE_CAD, coalesce(:WALERTA_CAD,0), coalesce(:WENTREGA_CAD,0),
                0, :WBDCODEMP, 0, :WBDDIASEMANA)
                into :WDATAVENC;

                if (WCURRENT_DATE <= WDATAVENC) then
                begin
                WMES = WBDREFSOL;
                end
                else
                begin
                  WMES=WBDREFSOL+1;
                  if(substring(WMES from 5 for 2)=13)then
                    WMES=(extract(year from WCURRENT_DATE)+ 1)* 100+1;

                  select first 1 BDDATA,BDALERTA,BDENTREGA
                  from GET_VENCIMENTO_TAREFAS(cast(substring(:WMES from 1 for 4)||'-'||substring(:WMES from 5 for 2)||'-01' as date),:WDIA_CAD,:WANTECIPAR_CAD,:WVENCE_CAD,:WPERIODICIDADE_CAD,coalesce(:WALERTA_CAD,0),coalesce(:WENTREGA_CAD,0),:WMESVENCE_CAD,:WBDCODEMP,1,:WBDDIASEMANA)
                  into :WBDVENCIMENTO,:WBDALERTA,:WBDENTREGA;
                  WBDDATASOLICITADA=WBDVENCIMENTO;
                  WBDREFSOL=WMES;
                end
              end
              else
              -- TAREFAS ANUAIS
              if(WBDPERIODICIDADE=10)then
              begin
                if(WDIA_CAD is null or WDIA_CAD=0)then
                  WDIA_CAD=1;
                if(WMESVENCE_CAD is null or WMESVENCE_CAD=0)then
                  WMESVENCE_CAD=1;

                select first 1 BDDATA from GET_VENCIMENTO_TAREFAS(cast(extract(year from :WCURRENT_DATE)||'-01-01' as date), :WDIA_CAD, :WANTECIPAR_CAD, 0,
                :WPERIODICIDADE_CAD, coalesce(:WALERTA_CAD,0), coalesce(:WENTREGA_CAD,0), :WMESVENCE_CAD, :WBDCODEMP, 0, :WBDDIASEMANA)
                into :WDATAVENC;

                if (WCURRENT_DATE <= WDATAVENC) then
                 WANO = extract(year from WCURRENT_DATE);
                else
                 WANO = extract(year from WCURRENT_DATE) + 1;

                WBDREFSOL=((WANO-1)* 100+1);

                select first 1 BDDATA,BDALERTA,BDENTREGA
                from GET_VENCIMENTO_TAREFAS(cast(:WANO||'-01-01' as date),:WDIA_CAD,:WANTECIPAR_CAD, 0,:WPERIODICIDADE_CAD,coalesce(:WALERTA_CAD,0),coalesce(:WENTREGA_CAD,0),:WMESVENCE_CAD,:WBDCODEMP,0,:WBDDIASEMANA)
                into :WBDVENCIMENTO,:WBDALERTA,:WBDENTREGA;
              end

              -- verifica se há o imposto nas tarefas
              if((select first 1 BDCODST
                   from VCT_EMPRESA_TSOLICITATAREFA
                   where BDCODEMP=:WBDCODEMP and
                         BDCODIMP=:WBDCODIMP and
                         BDREFSOL=:WBDREFSOL and
                         coalesce(BDCODPROC,0)=coalesce(:WBDCODPROC,0))is null)then
              begin
                execute procedure VCT_TAREFAS_AUTOMATICAS_INSERT(:WBDCODEMP,null,:WBDCODCOL,:WBDCODIMP,:WBDCODOBRIGACAO,:WBDCODSERVICO,:WBDCODTIPO,:WBDDATASOL,:WBDDATASOLICITADA,
                :WBDDATAPREVISAO,:WBDDATAFIM,:WBDREFSOL,:WBDTIPOSOLICITACAO,:WBDVENCIMENTO,:WBDENTREGA,:WBDALERTA,:WBDAGUARD,:WBDSTATUS,:WBDCODPROC,:WBDCODSTVINCPROCESSO);

                IMPOSTOS=IMPOSTOS+1;
                TOTAL=TOTAL+1;
              end
            end
          end
          else
          if(((WBDPERIODICIDADE=8)and(substring(WBDREFSOL from 5 for 2)in(3,6,9,12)))or
             ((WBDPERIODICIDADE=9)and(substring(WBDREFSOL from 5 for 2)in(1,4,7,10))))then
          begin
            WCONT=0;
            -- Gerar quotas do imposto parcelado-vctos
            if(WBDPERIODICIDADE=9)then
              WCURRENT_DATE=ADDMONTH(:WCURRENT_DATE,-1);
            WDATA=:WCURRENT_DATE;
            while(WCONT<=2)do
            begin
              -- Gerar quotas do imposto parcelado-vctos
              if(WCONT>0)then
                WDATA=ADDMONTH(:WCURRENT_DATE,WCONT);
              -- Gerar quotas do imposto parcelado-vctos
              WBDREFSOL=cast(substring(WCURRENT_DATE from 1 for 4)||substring(WCURRENT_DATE from 6 for 2)as integer);

              select first 1 BDDATA as BDDATASOLICITADA,BDDATA as BDVENCIMENTO,BDALERTA,BDENTREGA
              from GET_VENCIMENTO_TAREFAS(:WDATA,:WDIA_CAD,:WANTECIPAR_CAD,:WVENCE_CAD,:WPERIODICIDADE_CAD,coalesce(:WALERTA_CAD,0),coalesce(:WENTREGA_CAD,0),:WMESVENCE_CAD,:WBDCODEMP,0,:WBDDIASEMANA)
              into :WBDDATASOLICITADA,:WBDVENCIMENTO,:WBDENTREGA,:WBDALERTA;

              -- verifica se há o imposto nas tarefas
              -- Gerar quotas do imposto parcelado-vctos
              if((select first 1 BDCODST
                   from VCT_EMPRESA_TSOLICITATAREFA
                   where BDCODEMP=:WBDCODEMP and
                         BDCODIMP=:WBDCODIMP and
                         BDREFSOL=:WBDREFSOL and
                         BDVENCIMENTO=:WBDVENCIMENTO and
                         coalesce(BDCODPROC,0)=coalesce(:WBDCODPROC,0))is null)then
              begin
                execute procedure VCT_TAREFAS_AUTOMATICAS_INSERT(:WBDCODEMP,null,:WBDCODCOL,:WBDCODIMP,:WBDCODOBRIGACAO,:WBDCODSERVICO,:WBDCODTIPO,:WBDDATASOL,:WBDDATASOLICITADA,:WBDDATAPREVISAO,:WBDDATAFIM,:WBDREFSOL,:WBDTIPOSOLICITACAO,
                :WBDVENCIMENTO,:WBDENTREGA,:WBDALERTA,:WBDAGUARD,:WBDSTATUS,:WBDCODPROC,:WBDCODSTVINCPROCESSO);

                IMPOSTOS=IMPOSTOS+1;
                TOTAL=TOTAL+1;
              end
              WCONT=WCONT+1;
            end
          end
          else
          if((WBDPERIODICIDADE=12)or --Periodicidade diária,verificação todos os dias(não usa parâmetro de antecipação de vencimento é o próprio dia)
             ((WBDPERIODICIDADE=14)and(WBDVENCIMENTO is not null)and(WBDENTREGA is not null)and
             (WBDALERTA is not null)))then -- dias úteis
          begin
            if((select first 1 BDCODST
                 from VCT_EMPRESA_TSOLICITATAREFA
                 where BDCODEMP=:WBDCODEMP and BDCODIMP=:WBDCODIMP and BDREFSOL=:WBDREFSOL and BDVENCIMENTO=:WCURRENT_DATE and coalesce(BDCODPROC,0)=coalesce(:WBDCODPROC,0))is null)then
            begin
              if(WBDPERIODICIDADE <> 14)then
              begin
                WBDVENCIMENTO=WCURRENT_DATE;
                WBDENTREGA=WCURRENT_DATE;
                WBDALERTA=WCURRENT_DATE;
              end
              execute procedure VCT_TAREFAS_AUTOMATICAS_INSERT(:WBDCODEMP,null,:WBDCODCOL,:WBDCODIMP,:WBDCODOBRIGACAO,:WBDCODSERVICO,:WBDCODTIPO,:WBDDATASOL,:WBDDATASOLICITADA,
              :WBDDATAPREVISAO,:WBDDATAFIM,:WBDREFSOL,:WBDTIPOSOLICITACAO,:WBDVENCIMENTO,:WBDENTREGA,:WBDALERTA,:WBDAGUARD,:WBDSTATUS,:WBDCODPROC,:WBDCODSTVINCPROCESSO);

              IMPOSTOS=IMPOSTOS+1;
              TOTAL=TOTAL+1;
            end
          end
        end
        WCODEMPCOMPARA=:WBDCODEMP;
      end
      SUSPEND;
  end^


create or alter procedure VCT_TAREFA_ADD_USUARIO(PRHISTORICO boolean = false)as begin end^

CREATE OR ALTER procedure VCT_TAREFAS_AUTOMATICAS (
    CODEMP integer = 0,
    data date = current_date,
    IMPOSTO integer = null,
    OBRIGACAO integer = null,
    SERVICO integer = null,
    STATUS integer = null,
    ESOCIAL integer = null,
    PERIODICIDADE integer = null,
    PROCESSO integer = null,
    "MANUAL" boolean = false)
returns (
    TOTAL integer,
    IMPOSTOS integer,
    OBRIGACOES integer,
    SERVICOS integer)
as
declare variable WCURRENT_DATE date;
declare variable WCURRENT_REF integer;
declare variable WRECONTABILIZANDO DM_BOOLEAN;
declare variable WCONFIG_EMP smallint;
declare variable WPROCESSO varchar(30);
declare variable WBDCODSTVINCPROCESSO integer;
declare variable WDATAVENCAUX date;
declare variable WCODEMPCOMPARA integer;
declare variable WPROCESSOLOG varchar(30);
declare variable TOTAL_OBR integer;
declare variable OBRIGACOES_OBR integer;
declare variable TOTAL_SER integer;
declare variable SERVICOS_SER integer;
declare variable TOTAL_IMP integer;
declare variable IMPOSTOS_IMP integer;
BEGIN
    WCURRENT_DATE = DATA;
    WCURRENT_REF = CAST(EXTRACT(YEAR FROM DATA) || LPAD(EXTRACT(MONTH FROM DATA), 2, 0) AS INTEGER);

    --não gerar tarefas automáticas para clientes que não estejam personalizados para o controles
    IF (((SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO WHERE BDSISTEMAS CONTAINING '58' OR BDSISTEMAS CONTAINING '1506') IS NULL) OR
        -- caso houver uma data de finalização anterior a data atual
        ((SELECT FIRST 1 BDDATAFINAL FROM TPESSOATOSISTEMA WHERE BDSISTEMA IN (1506,58) AND BDDATAFINAL IS NOT NULL AND BDDATAFINAL <= CURRENT_DATE) IS NOT NULL) OR
        -- não gerar tarefas antes da data configurada
        ((SELECT FIRST 1 BDDATATAREFA FROM VCT_CONFIG_DATAS WHERE BDDATATAREFA <= :WCURRENT_DATE) IS NULL) OR
        -- não deixar gerar tarefas automáticas no cadastro de empresas
        (COALESCE((SELECT CAST(TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_CADEMPRESA')) AS INTEGER) FROM RDB$DATABASE), 0) <> 0)) THEN
        EXIT;

    SELECT FIRST 1 TRIM(UPPER(COALESCE(RDB$GET_CONTEXT('USER_SESSION', 'W_RECONTABILIZA'), ''))) FROM RDB$DATABASE INTO :WRECONTABILIZANDO;
    IF (WRECONTABILIZANDO = 'TRUE') THEN
        EXIT;

    WCONFIG_EMP = 0;
    IF (EXISTS(SELECT 1 FROM VCT_CONFIG_TAREFA_EMPRESA)) THEN
        WCONFIG_EMP = 1;

    WPROCESSO = 'TRIB.BDCODPROC IS NULL';
    IF (PROCESSO IS NOT NULL) THEN
        WPROCESSO = 'TRIB.BDCODPROC=' || PROCESSO;

    WBDCODSTVINCPROCESSO = NULL;
    TOTAL = 0;
    IMPOSTOS = 0;
    OBRIGACOES = 0;
    SERVICOS = 0;

    -- para evitar deadlook verifica antes se existe registro nessa data
    SELECT FIRST 1 BDDATA FROM VCT_BASE_PARAMETROS WHERE BDDATA = :WCURRENT_DATE INTO :WDATAVENCAUX;
    IF (WDATAVENCAUX IS NULL) THEN
        INSERT INTO VCT_BASE_PARAMETROS (BDDATA) VALUES (:WCURRENT_DATE);

    WCODEMPCOMPARA = NULL;

    -- OBRIGAÇÕES
    IF (((IMPOSTO IS NULL) AND (OBRIGACAO IS NULL) AND (SERVICO IS NULL)) OR (OBRIGACAO IS NOT NULL)) THEN
    BEGIN
        EXECUTE PROCEDURE VCT_TAREFAS_AUTOMATICAS_OBR(CODEMP, DATA, OBRIGACAO, STATUS, PROCESSO, MANUAL, ESOCIAL)
            RETURNING_VALUES :TOTAL_OBR, :OBRIGACOES_OBR;
        TOTAL = TOTAL + COALESCE(:TOTAL_OBR, 0);
        OBRIGACOES = OBRIGACOES + COALESCE(:OBRIGACOES_OBR, 0);
    END

    -- SERVIÇOS
    IF (ESOCIAL IS NULL) THEN
    BEGIN
        IF (((IMPOSTO IS NULL) AND (OBRIGACAO IS NULL) AND (SERVICO IS NULL)) OR (SERVICO IS NOT NULL)) THEN
        BEGIN
            EXECUTE PROCEDURE VCT_TAREFAS_AUTOMATICAS_SER(CODEMP, DATA, SERVICO, STATUS, PROCESSO, MANUAL)
                RETURNING_VALUES :TOTAL_SER, :SERVICOS_SER;
            TOTAL = TOTAL + COALESCE(:TOTAL_SER, 0);
            SERVICOS = SERVICOS + COALESCE(:SERVICOS_SER, 0);
        END
    END

    -- IMPOSTOS
    IF (ESOCIAL IS NULL) THEN
    BEGIN
        IF (((IMPOSTO IS NULL) AND (OBRIGACAO IS NULL) AND (SERVICO IS NULL)) OR (IMPOSTO IS NOT NULL)) THEN
        BEGIN
            EXECUTE PROCEDURE VCT_TAREFAS_AUTOMATICAS_IMP(CODEMP, DATA, IMPOSTO, STATUS, PROCESSO, MANUAL)
                RETURNING_VALUES :TOTAL_IMP, :IMPOSTOS_IMP;
            TOTAL = TOTAL + COALESCE(:TOTAL_IMP, 0);
            IMPOSTOS = IMPOSTOS + COALESCE(:IMPOSTOS_IMP, 0);
        END
    END

    -- LOG
    WPROCESSOLOG = '';
    IF (PROCESSO IS NOT NULL) THEN
        WPROCESSOLOG = ' para o processo: ' || PROCESSO;

    EXECUTE PROCEDURE SP_INSERIR_LOG(
        :CODEMP, NULL, COALESCE((SELECT BDCODUSU FROM SP_GET_USUARIO), 1), NULL, 8, NULL,
        :WCURRENT_DATE, CURRENT_TIME,
        'O servidor executou a rotina de geração das tarefas automáticas' || WPROCESSOLOG || ASCII_CHAR(13) ||
        'Impostos: ' || :IMPOSTOS || ASCII_CHAR(13) ||
        'Obrigações: ' || :OBRIGACOES || ASCII_CHAR(13) ||
        'Serviços: ' || :SERVICOS || ASCII_CHAR(13) ||
        'Total: ' || :TOTAL,
        0, 0, 'Servidor', 'Servidor', 'ServidorSCI', 'Thread de tarefas automáticas',
        NULL, 'VCT_TAREFAS_AUTOMATICAS', NULL, 'FALSE', :WCURRENT_DATE
    );

    -- Gilberto - 03/07/2026 - #247644 - não utilizar, gera muitos registros na tabela vct_tarefa_usuario gerando lentidão na central de tarefas
    -- Gilberto - 30/06/2026 - #246890
    -- execute procedure VCT_TAREFA_ADD_USUARIO(false);

    SUSPEND;
end^

create or alter procedure VCT_TAREFA_TROCA_USUARIOS (
    PRCODEMP integer,
    PRCODST integer,
    PRDATA date = null)
as
declare variable VWHERE varchar(500);
declare variable VSQL varchar(4096);
declare variable VDATA date;
declare variable VSQLCONCLUSAO varchar(512);
begin
  /* Mantem apenas as trocas e insereções de usuários executadas pelas central de tarefas e/ou solicitação de tarefas,
     na tabela vct_empresa_tarefa_usuario, que representa os usuários das tarefas */
  vdata = null;
  if ((select RDB$RELATION_FIELDS.RDB$FIELD_NAME from rdb$relation_fields
       where RDB$RELATION_FIELDS.rdb$relation_name = 'VCT_CONFIG_DATAS'
       AND RDB$RELATION_FIELDS.RDB$FIELD_NAME = 'BDTROCAUSUARIOSEXECUTADA') is null) then
  begin
    execute statement 'select first 1 BDTROCAUSUARIOSEXECUTADA from VCT_CONFIG_DATAS '||
                      'where bddatatarefa is not null '||
                      'and exists(select first 1 bdcodigo from tpersonalizacao '||
                      'where(BDSISTEMAS containing'''||'58'||''')or(BDSISTEMAS containing'''||'1506'||'''))'
    into :vdata;
    vsqlconclusao = 'update VCT_CONFIG_DATAS set BDTROCAUSUARIOSEXECUTADA = current_date';
  end
  else
  begin
    execute statement 'select first 1 BDTROCAUSUARIOEXECUTADA from VCT_CONFIG_DATAS '||
                      'where bddatatarefa is not null '||
                      'and exists(select first 1 bdcodigo from tpersonalizacao '||
                      'where(BDSISTEMAS containing'''||'58'||''')or(BDSISTEMAS containing'''||'1506'||'''))'
    into :vdata;
    vsqlconclusao = 'update VCT_CONFIG_DATAS set BDTROCAUSUARIOEXECUTADA = current_date';
  end


  if (((:vdata is null)and(exists(select first 1 bdcodemp from vct_usuario_tarefa))) or (prdata is not null)) then
  begin
    /* deve limpar toda a tabela */
    vsql = 'delete from vct_empresa_tarefa_usuario his ';
    vwhere = '';
    if (prcodemp is not null) then
       vwhere = ' where his.bdcodemp='||prcodemp;
    if ((prcodemp is not null) and (prcodst is not null)) then
       vwhere = vwhere||' and ';
    else
    if (prcodst is not null) then
       vwhere = vwhere||' where ';
    if (prcodst is not null) then
      vwhere = vwhere||'his.bdcodst='||prcodst;
  
    execute statement vsql||vwhere;
  
    vwhere = replace(upper(vwhere), ' WHERE ', ' AND ');
    
    /* Insere conforme os tramites da tabela de histórico */
    vsql = 'insert into vct_empresa_tarefa_usuario (bdcodemp,bdcodst,bdcodusu)';
    -- lançamentos antigos em grupos
    vsql = vsql||'select  his.bdcodemp,his.bdcodst,usu.bdcodusu ';
    vsql = vsql||'from vct_empresa_thistoricotarefa his ';
    vsql = vsql||'join vct_empresa_tsolicitatarefa sol on(sol.bdcodemp=his.bdcodemp and sol.bdcodst=his.bdcodst)';
    vsql = vsql||'join tgrupousuario_usuario grp on(grp.bdcodgrupo=his.bdcodgrupo)';
    vsql = vsql||'join tusuario usu on(usu.bdcodusu=grp.bdcodusu)';
    vsql = vsql||'where(his.bdstatus=12)and(his.bdcodusuresponsavel is null)and(his.bdcodgrupo is not null)';
    vsql = vsql||'and(usu.bdlistarusu=TRUE)';
    vsql = vsql||'and not exists(select first 1 bdcodemp from vct_usuario_tarefa ';
    vsql = vsql||'where(bdcodemp=his.bdcodemp)';
    vsql = vsql||'and(bdcodimp=coalesce(sol.bdcodimp,0))';
    vsql = vsql||'and(bdcodobr=coalesce(sol.bdcodobrigacao,0))';
    vsql = vsql||'and(bdcodser=coalesce(sol.bdcodservico,0))';
    vsql = vsql||'and(bdcodproc=coalesce(sol.bdcodproc,0))';
    vsql = vsql||'and(bdcodusu=usu.bdcodusu))';
    vsql = vsql||' union ';
    -- todos os usuários inseridos com seu código
    vsql = vsql||'select distinct his.bdcodemp,his.bdcodst,his.bdcodusuresponsavel from vct_empresa_thistoricotarefa his ';
    vsql = vsql||'join tusuario usu on(usu.bdcodusu=his.bdcodusuresponsavel)';
    vsql = vsql||'where(((his.bdcodusuresponsavel is not null)and(his.bdcodgrupo is null))or((his.bdcodusuresponsavel is not null)and(his.bdcodgrupo is not null)))';
    vsql = vsql||'and(usu.bdlistarusu=TRUE)';
    vsql = vsql||'and(his.bdcodbhs=14)'||vwhere;
    vsql = vsql||' union ';
    -- todos os usuários, sem grupo e sem código do usuário
    vsql = vsql||'select distinct his.bdcodemp,his.bdcodst,usu.bdcodusu from vct_empresa_thistoricotarefa his, tusuario usu ';
    vsql = vsql||'where((his.bdcodusuresponsavel is null)and(his.bdcodgrupo is null))';
    vsql = vsql||'and(usu.bdlistarusu=TRUE)';
    vsql = vsql||'and(usu.bdcodusu>3)';
    vsql = vsql||'and(his.bdcodbhs=14)'||vwhere;
    vsql = vsql||' union ';
    -- todos os usuários por grupo
    vsql = vsql||'select distinct his.bdcodemp,his.bdcodst,grp.bdcodusu from vct_empresa_thistoricotarefa his ';
    vsql = vsql||'join tgrupousuario_usuario grp on(grp.bdcodgrupo=his.bdcodgrupo)';
    vsql = vsql||'join tusuario usu on(usu.bdcodusu=grp.bdcodusu)';
    vsql = vsql||'where((his.bdcodusuresponsavel is null)and(his.bdcodgrupo is not null))';
    vsql = vsql||'and(usu.bdlistarusu=TRUE)';
    vsql = vsql||'and(his.bdcodbhs=14)'||vwhere;
    vsql = vsql||' union ';
    -- usuários adicionados ao histórico no método antigo
    vsql = vsql||'select his.bdcodemp,his.bdcodst,usu.bdcodusu from vct_empresa_thistoricotarefa his ';
    vsql = vsql||'join vct_empresa_tsolicitatarefa sol on(sol.bdcodemp=his.bdcodemp and sol.bdcodst=his.bdcodst)';
    vsql = vsql||'join tusuario usu on(usu.bdcodusu=his.bdcodusuresponsavel)';
    vsql = vsql||'where(his.bdstatus=12)and(his.bdcodusuresponsavel is not null)and(usu.bdlistarusu=TRUE)';
    vsql = vsql||'and not exists(select first 1 bdcodemp from vct_usuario_tarefa '; 
    vsql = vsql||'where(bdcodemp=his.bdcodemp)';
    vsql = vsql||'and(bdcodimp=coalesce(sol.bdcodimp,0))';
    vsql = vsql||'and(bdcodobr=coalesce(sol.bdcodobrigacao,0))';
    vsql = vsql||'and(bdcodser=coalesce(sol.bdcodservico,0))';
    vsql = vsql||'and(bdcodproc=coalesce(sol.bdcodproc,0))';
    vsql = vsql||'and(bdcodusu=usu.bdcodusu))'||vwhere;


    execute statement vsql;

    if (Trim(vsqlconclusao)<>'') then
       execute statement vsqlconclusao;
  end
end^

create or alter procedure VCT_TAREFA_PLANO_USUARIOS (
    PRCODEMP integer,
    PRCODIMP integer,
    PRCODOBR integer,
    PRCODSER integer,
    PRCODPROC integer)
as
declare variable VSQL varchar(5000);
declare variable VSQLIMP varchar(2000);
declare variable VWHERE varchar(500);
declare variable VSQLOBR varchar(2000);
declare variable VSQLSER varchar(2000);
begin
  /* Insere todos usuários por tarefa e empresa, com base no plano de tarefas, para auxiliar nos filtros da central de tarefas */

  vwhere = '';

  vsql = 'delete from vct_usuario_tarefa tar ';

  if (prcodimp is not null) then
     vwhere = ' where tar.bdcodimp='||prcodimp;
  else
  if (prcodobr is not null) then
     vwhere = ' where tar.bdcodobr='||prcodobr;
  else
  if (prcodser is not null) then
     vwhere = ' where tar.bdcodser='||prcodser;
  else
  if (prcodproc is not null) then
     vwhere = ' where tar.bdcodproc='||prcodproc;

  if (prcodemp is not null) then
  begin
    if (:vwhere <> '') then
       vwhere = vwhere||' and ';
    else
       vwhere = ' where ';
    vwhere = vwhere||'tar.bdcodemp='||prcodemp;
  end
  execute statement vsql||vwhere;

  vwhere = replace(upper(vwhere), ' WHERE ', ' AND ');
  vwhere = replace(upper(vwhere), 'BDCODOBR', 'BDCODOBRSER');
  vwhere = replace(upper(vwhere), 'BDCODSER', 'BDCODOBRSER');

  -- Impostos
  if ((prcodimp is not null)or(prcodproc is not null)or((prcodimp is null)and(prcodobr is null)and(prcodser is null))) then
  begin
    -- todos usuários por grupo
    vsqlimp = 'select tar.bdcodemp,tar.bdcodimp,0 as bdcodobr,0 as bdcodser,usu.bdcodusu,coalesce(tar.bdcodproc,0) as bdcodproc ';
    vsqlimp = vsqlimp||'from VCT_EMPRESA_USUARIO_IMP TAR ';
    vsqlimp = vsqlimp||'join tgrupousuario_usuario grp on(grp.bdcodgrupo=tar.bdcodgrupo)';
    vsqlimp = vsqlimp||'join tusuario usu on(usu.bdcodusu=grp.bdcodusu)';
    vsqlimp = vsqlimp||'where((tar.BDCODGRUPO is not null)and(tar.bdcodusu is null))and(upper(coalesce(usu.bdcontdesativousu,'||'''FALSE'''||'))='||'''FALSE'''||')';
    vsqlimp = vsqlimp||'and(usu.bdlistarusu=TRUE)';
    if (vwhere <> '') then
       vsqlimp = vsqlimp||vwhere;
    -- todos os usuário
    vsqlimp = vsqlimp||' union ';
    vsqlimp = vsqlimp||'select tar.bdcodemp,tar.bdcodimp,0 as bdcodobr,0 as bdcodser,usu.bdcodusu,coalesce(tar.bdcodproc,0) as bdcodproc ';
    vsqlimp = vsqlimp||'from VCT_EMPRESA_USUARIO_IMP TAR, tusuario usu ';
    vsqlimp = vsqlimp||'where((tar.BDCODGRUPO is null)and(tar.bdcodusu is null))and(upper(coalesce(usu.bdcontdesativousu,'||'''FALSE'''||'))='||'''FALSE'''||')';
    vsqlimp = vsqlimp||'and(usu.bdlistarusu=TRUE)';
    vsqlimp = vsqlimp||'and(usu.bdcodusu>3)';
    if (vwhere <> '') then
       vsqlimp = vsqlimp||vwhere;
    -- todos os usuário inseridos com código de usuário
    vsqlimp = vsqlimp||' union ';
    vsqlimp = vsqlimp||'select tar.bdcodemp,tar.bdcodimp,0 as bdcodobr,0 as bdcodser,usu.bdcodusu,coalesce(tar.bdcodproc,0) as bdcodproc ';
    vsqlimp = vsqlimp||'from VCT_EMPRESA_USUARIO_IMP TAR ';
    vsqlimp = vsqlimp||'join tusuario usu on(usu.bdcodusu=tar.bdcodusu)';
    vsqlimp = vsqlimp||'where(((tar.BDCODGRUPO is null)and(tar.bdcodusu is not null))';
    vsqlimp = vsqlimp||'or((tar.BDCODGRUPO is not null)and(tar.bdcodusu is not null)))';
    vsqlimp = vsqlimp||'and(upper(coalesce(usu.bdcontdesativousu,'||'''FALSE'''||'))='||'''FALSE'''||')';
    vsqlimp = vsqlimp||'and(usu.bdlistarusu=TRUE)';
    if (vwhere <> '') then
       vsqlimp = vsqlimp||vwhere;
  end

  -- obrigações
  if ((prcodobr is not null)or(prcodproc is not null)or((prcodimp is null)and(prcodobr is null)and(prcodser is null))) then
  begin
    -- todos usuários por grupo
    vsqlobr = 'select tar.bdcodemp,0 as bdcodimp,tar.bdcodobrser as bdcodobr,0 as bdcodser,usu.bdcodusu,coalesce(tar.bdcodproc,0) as bdcodproc ';
    vsqlobr = vsqlobr||'from VCT_EMPRESA_USUARIO_OBR TAR ';
    vsqlobr = vsqlobr||'join tgrupousuario_usuario grp on(grp.bdcodgrupo=tar.bdcodgrupo)';
    vsqlobr = vsqlobr||'join tusuario usu on(usu.bdcodusu=grp.bdcodusu)';
    vsqlobr = vsqlobr||'where((tar.BDCODGRUPO is not null)and(tar.bdcodusu is null))and(upper(coalesce(usu.bdcontdesativousu,'||'''FALSE'''||'))='||'''FALSE'''||')';
    vsqlobr = vsqlobr||'and(usu.bdlistarusu=TRUE)';
    if (vwhere <> '') then
       vsqlobr = vsqlobr||vwhere;
    -- todos os usuário
    vsqlobr = vsqlobr||' union ';
    vsqlobr = vsqlobr||'select tar.bdcodemp,0 as bdcodimp,tar.bdcodobrser as bdcodobr,0 as bdcodser,usu.bdcodusu,coalesce(tar.bdcodproc,0) as bdcodproc ';
    vsqlobr = vsqlobr||'from VCT_EMPRESA_USUARIO_OBR TAR, tusuario usu ';
    vsqlobr = vsqlobr||'where((tar.BDCODGRUPO is null)and(tar.bdcodusu is null))and(upper(coalesce(usu.bdcontdesativousu,'||'''FALSE'''||'))='||'''FALSE'''||')';
    vsqlobr = vsqlobr||'and(usu.bdlistarusu=TRUE)';
    vsqlobr = vsqlobr||'and(usu.bdcodusu>3)';
    if (vwhere <> '') then
       vsqlobr = vsqlobr||vwhere;
    -- todos os usuário inseridos com código de usuário
    vsqlobr = vsqlobr||' union ';
    vsqlobr = vsqlobr||'select tar.bdcodemp,0 as bdcodimp,tar.bdcodobrser as bdcodobr,0 as bdcodser,usu.bdcodusu,coalesce(tar.bdcodproc,0) as bdcodproc ';
    vsqlobr = vsqlobr||'from VCT_EMPRESA_USUARIO_OBR TAR ';
    vsqlobr = vsqlobr||'join tusuario usu on(usu.bdcodusu=tar.bdcodusu)';
    vsqlobr = vsqlobr||'where(((tar.BDCODGRUPO is null)and(tar.bdcodusu is not null))';
    vsqlobr = vsqlobr||'or((tar.BDCODGRUPO is not null)and(tar.bdcodusu is not null)))';
    vsqlobr = vsqlobr||'and(upper(coalesce(usu.bdcontdesativousu,'||'''FALSE'''||'))='||'''FALSE'''||')';
    vsqlobr = vsqlobr||'and(usu.bdlistarusu=TRUE)';
    if (vwhere <> '') then
       vsqlobr = vsqlobr||vwhere;
  end

  -- serviços
  if ((prcodser is not null)or(prcodproc is not null)or((prcodimp is null)and(prcodobr is null)and(prcodser is null))) then
  begin
    -- todos usuários por grupo
    vsqlser = 'select tar.bdcodemp,0 as bdcodimp,0 as bdcodobr,tar.bdcodobrser as bdcodser,usu.bdcodusu,coalesce(tar.bdcodproc,0) as bdcodproc ';
    vsqlser = vsqlser||'from VCT_EMPRESA_USUARIO_SER TAR ';
    vsqlser = vsqlser||'join tgrupousuario_usuario grp on(grp.bdcodgrupo=tar.bdcodgrupo)';
    vsqlser = vsqlser||'join tusuario usu on(usu.bdcodusu=grp.bdcodusu)';
    vsqlser = vsqlser||'where((tar.BDCODGRUPO is not null)and(tar.bdcodusu is null))and(upper(coalesce(usu.bdcontdesativousu,'||'''FALSE'''||'))='||'''FALSE'''||')';
    vsqlser = vsqlser||'and(usu.bdlistarusu=TRUE)';
    if (vwhere <> '') then
       vsqlser = vsqlser||vwhere;
    -- todos os usuário
    vsqlser = vsqlser||' union ';
    vsqlser = vsqlser||'select tar.bdcodemp,0 as bdcodimp,0 as bdcodobr,tar.bdcodobrser as bdcodser,usu.bdcodusu,coalesce(tar.bdcodproc,0) as bdcodproc ';
    vsqlser = vsqlser||'from VCT_EMPRESA_USUARIO_SER TAR, tusuario usu ';
    vsqlser = vsqlser||'where((tar.BDCODGRUPO is null)and(tar.bdcodusu is null))and(upper(coalesce(usu.bdcontdesativousu,'||'''FALSE'''||'))='||'''FALSE'''||')';
    vsqlser = vsqlser||'and(usu.bdlistarusu=TRUE)';
    vsqlser = vsqlser||'and(usu.bdcodusu>3)';
    if (vwhere <> '') then
       vsqlser = vsqlser||vwhere;
    -- todos os usuário inseridos com código de usuário
    vsqlser = vsqlser||' union ';
    vsqlser = vsqlser||'select tar.bdcodemp,0 as bdcodimp,0 as bdcodobr,tar.bdcodobrser as bdcodser,usu.bdcodusu,coalesce(tar.bdcodproc,0) as bdcodproc ';
    vsqlser = vsqlser||'from VCT_EMPRESA_USUARIO_SER TAR ';
    vsqlser = vsqlser||'join tusuario usu on(usu.bdcodusu=tar.bdcodusu)';
    vsqlser = vsqlser||'where(((tar.BDCODGRUPO is null)and(tar.bdcodusu is not null))';
    vsqlser = vsqlser||'or((tar.BDCODGRUPO is not null)and(tar.bdcodusu is not null)))';
    vsqlser = vsqlser||'and(upper(coalesce(usu.bdcontdesativousu,'||'''FALSE'''||'))='||'''FALSE'''||')';
    vsqlser = vsqlser||'and(usu.bdlistarusu=TRUE)';
    if (vwhere <> '') then
       vsqlser = vsqlser||vwhere;
  end

  vsql = 'insert into vct_usuario_tarefa(bdcodemp,bdcodimp,bdcodobr,bdcodser,bdcodusu,bdcodproc)';
  if (vsqlimp <> '') then
     vsql = vsql||vsqlimp;
  if ((vsqlimp <> '')and(vsqlobr <> '')) then
     vsql = vsql||' union ';
  if (vsqlobr <> '') then
     vsql = vsql||vsqlobr;
  if ((vsqlobr <> '')and(vsqlser <> '')) then
     vsql = vsql||' union ';
  if (vsqlser <> '') then
     vsql = vsql||vsqlser;

  execute statement vsql;
  
  execute procedure VCT_TAREFA_TROCA_USUARIOS(null, null);
end^

create or alter procedure VCT_ORC_SETREFGERADOR (
    PRDATAINI date,
    PRDATAFIN date)
as
declare variable VDATAINI date;
begin
  vdataini = prdataini;

  delete from tmp_vct_orc_getrefgerador;
  while (:vdataini <= :prdatafin) do
  begin
    insert into tmp_vct_orc_getrefgerador (bdref)values(cast(extract(year from :vdataini)||lpad(extract(month from :vdataini), 2, 0) as integer));
    vdataini = addmonth(:vdataini, 1);
  end
end^

CREATE OR ALTER procedure VCT_TAREFAS_PROTOCOLADA (
    PRCODEMP integer,
    PRCODPTS integer,
    PRPORTADOR varchar(300),
    PRDATAEMISSAO date,
    PRHORAEMISSAO time,
    PRCLASSNAME varchar(256))
as
declare variable VDATAEMISSAO date;
declare variable VCODST integer;
declare variable VCODOBR integer;
declare variable VCODSER integer;
declare variable VCODUSU integer;
declare variable VREFMICRO integer;
declare variable VTIPOSOLICITACAO smallint;
declare variable VCODOBRANT integer;
declare variable VBDREFERENCIAFOR varchar(8);
declare variable VBDREFERENCIA integer;
declare variable VBDCOMPLEMENTO varchar(200);
declare variable VBDCODDOC varchar(200);
declare variable VBDVENCIMENTO date;
declare variable VBDVALOR numeric(15,2);
declare variable VBDCODSIS integer;
declare variable VBDOBSERVACAO varchar(200);
declare variable VBDDATA date;
declare variable WSQL varchar(32000);
declare variable VCODSERANT integer;
declare variable CODDOCUMENTO varchar(200);
begin
  select first 1 BDDATAEMISSAO from VCT_EMPRESA_PROTOCOLOSAIDA where bdcodemp = :prCODEMP and bdcodpts = :prcodpts into :vdataemissao;
  if ((vdataemissao is null)/* or (vdataemissao = 0)*/)  then
  begin
    select first 1 bdcodusu from vw_usuarios_secao into :vcodusu;
    SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES')) FROM RDB$DATABASE INTO :vrefmicro;
    update VCT_EMPRESA_PROTOCOLOSAIDA set
    bddataemissao = :prDataEmissao, BDHORAEMISSAO = :prHoraEmissao,
    BDCODUSUEMISAO = :vcodusu,
    bdportador = :prportador
    where bdcodemp = :prCODEMP and bdcodpts = :prcodpts;

    if ((select first 1 BDAUTORIZADA from VCT_TAREFAS_AUTORIZADAS(current_date)) = true) then
    begin
      select bdcodst from VCT_EMPRESA_PROTOCOLO_TAREFA
      where bdcodemp = :prCODEMP and bdcodpts = :prcodpts
      into :vcodst;

      for select bdcodobrigacao, bdcodservico from (
          select cfg.bdcodobrigacao, null as bdcodservico from tempresas emp
          inner join ttela_sistema tela on (upper(tela.bdnometela) = upper(:prClassName))
          inner join vct_config_telaobrser cfg on (cfg.bdcodtela = tela.bdcodtelasis)
          inner join vct_base_obrigacao obr on (obr.bdcodobrser = cfg.bdcodobrigacao and obr.bdperiodicidade = 11)
          where emp.bdcodemp = :prCODEMP
          union all
          select null as bdcodobrigacao, cfg.bdcodservico from tempresas emp
          inner join ttela_sistema tela on (upper(tela.bdnometela) = upper(:prclassname))
          inner join vct_config_telaobrser cfg on (cfg.bdcodtela = tela.bdcodtelasis)
          inner join vct_base_servico ser on (ser.bdcodobrser = cfg.bdcodservico and ser.bdperiodicidade = 11)
          where emp.bdcodemp = :prCODEMP
          ) order by bdcodobrigacao, bdcodservico
      into :vcodobr, :vcodser do
      begin
        if ((coalesce(vcodobr, 0) <> coalesce(vcodobrant, 0)) or
            (coalesce(vcodser, 0) <> coalesce(vcodserant, 0))) then
        begin
          if (vcodobr is null) then
             vtiposolicitacao = 2;-- serviço
          else
             vtiposolicitacao = 1;-- obrigação
          insert into vct_empresa_tsolicitatarefa
          (BDCODEMP, BDCODUSU, BDCODOBRIGACAO, BDCODSERVICO, BDCODTIPO, BDDATASOL, BDDATASOLICITADA,
           BDDATAPREVISAO, BDREFSOL,
           BDTIPOSOLICITACAO, BDVENCIMENTO, BDENTREGA, BDALERTA)
          values (:prCODEMP,:vCODUSU,:vcodobr,:vcodser,501,current_date,current_date,current_date,
                  :vrefmicro,:vtiposolicitacao,current_date,current_date,current_date);

          select max(bdcodst) from vct_empresa_tsolicitatarefa where bdcodemp = :prcodemp into :vcodst;
        end

        if ((select first 1 bdcodemp from vct_empresa_protocolo_tarefa
             where BDCODEMP = :prcodemp and BDCODPTS = :prcodpts and BDCODST = :vcodst) is null) then
           insert into vct_empresa_protocolo_tarefa (BDCODEMP, BDCODPTS, BDCODST) values (:prCODEMP,:prcodpts,:vcodst);

        vcodobrant = :vcodobr;
        vcodserant = :vcodser;
      end
    end
    wSQL = '';
    for
      select
        vep.BDREFERENCIA,
        vep.BDCOMPLEMENTO,
        cast(
          coalesce(
            nullif(trim(doc.bddescricao), ''),
            nullif(trim(tt.bdcaptiontela), ''),
            nullif(trim(ti.bddescimp), ''),
            nullif(trim(vep.BDCHAVEDARF), '')
          ) as varchar(200)
        ) as CODDOCUMENTO,
        vep.BDVENCIMENTO,
        vep.BDVALOR,
        vep.BDOBSERVACAO,
        vep.BDCODSIS,
        vep.BDDATA
      from VCT_EMPRESA_PROTODOCSAIDA vep
      left outer join ttela_sistema tt on vep.BDCODTELASIS = tt.bdcodtelasis
      left outer join timposto ti on vep.bdcodimp = ti.bdcodimp
      left outer join tdarfpadrao tdr on (vep.BDCODEMP = tdr.bdcodemp) and (vep.BDCHAVEDARF = tdr.bdchavedarf)
      left outer join VCT_BASE_DOCUMENTO doc on vep.bdcoddoc = doc.bdcoddoc
      where vep.BDCODEMP = :prCODEMP
        and vep.BDCODPTS = :prCODPTS
      into
        :VBDREFERENCIA,
        :VBDCOMPLEMENTO,
        :VBDCODDOC,
        :VBDVENCIMENTO,
        :VBDVALOR,
        :VBDOBSERVACAO,
        :VBDCODSIS,
        :VBDDATA
    do
    begin
        wSQL = coalesce(wSQL, '')
         || 'Referencia: '
         || coalesce(
              nullif(:VBDREFERENCIAFOR, ''),
              lpad(
                cast(
                  (:VBDREFERENCIA - floor(:VBDREFERENCIA / 100) * 100)
                  as varchar(2)
                ),
                2,'0'
              )
              || '/'
              || cast(floor(:VBDREFERENCIA / 100) as varchar(4))
            )
        || ascii_char(13)||ascii_char(10)
        || 'Complemento: '
           || coalesce(:vbdcomplemento, '')
        || ascii_char(13)||ascii_char(10)
        || 'Documento: '
           || coalesce(cast(:vbdcoddoc as varchar(200)), '')
        || ascii_char(13)||ascii_char(10)
        || 'Vencimento: '
        || CASE
             WHEN :vbdvencimento IS NULL THEN ''
             ELSE
               LPAD(
                 CAST(EXTRACT(DAY   FROM :vbdvencimento) AS VARCHAR(2)),
                 2,'0'
               )
               || '/'
               || LPAD(
                    CAST(EXTRACT(MONTH FROM :vbdvencimento) AS VARCHAR(2)),
                    2,'0'
                  )
               || '/'
               || CAST(EXTRACT(YEAR  FROM :vbdvencimento) AS VARCHAR(4))
           END
        || ASCII_CHAR(13)||ASCII_CHAR(10)
        || 'Valor: '
           || coalesce(cast(format_numeric(:vbdvalor) as varchar(20)), '')
        || ascii_char(13)||ascii_char(10)
        || 'Observação: '
        || coalesce(:vbdobservacao, '')
        || ascii_char(13)||ascii_char(10);
    end


    execute procedure SP_INSERIR_LOG(PRCODEMP, NULL, :VCODUSU, NULL, :VBDCODSIS, NULL, cast(addday(current_date, 1) as date), NULL,
        wSQL, 0, 0, CURRENT_USER, 'SERVIDOR', 'TfrRelProtocolo', 'Relatorios de Protocolos',
        NULL, 'TEMPRESAS', NULL, 'FALSE', cast(addday(current_date, 1) as
         date));
  end
end^


create or alter procedure VCT_EMPRESA_BAIXATAREFA (
    PRCODEMP integer,
    PRCODST integer,
    PRAGUARDANDO integer,
    PRCODUSU integer,
    PRMENSAGEM varchar(500),
    PRCODBHS integer)
as
declare variable VDATAFIM date;
declare variable VAGUARD integer;
begin
  SELECT FiRST 1 tar.bddatafim, coalesce(tar.bdaguard,0)
  FROM vct_empresa_tsolicitatarefa tar
  WHERE tar.bdcodemp = :prCodEmp AND tar.bdcodst = :prCodST INTO :vdatafim, :vaguard;

  if ((:praguardando > 0) AND (:vdatafim IS NULL) and (:vaguard<>1)) THEN
  begin
    update vct_empresa_tsolicitatarefa set bddatafim = null, bdaguard = 1
    where (bdcodemp = :prcodemp) and (bdcodst = :prcodst) and ((bddatafim is not null) or (coalesce(bdaguard, 0) <> 1));

    update or insert into vct_empresa_thistoricotarefa(bdcodemp,bdcodst,bdcodusuresponsavel,bdstatus,bdobservacao,bdcodbhs)
    values(:prcodemp, :prcodst, :prcodusu,5,:prmensagem,:prcodbhs)
    matching(bdcodemp,bdcodst,bdcodusuresponsavel,bdstatus,bdobservacao,bdcodbhs);

    --Gilberto - 21/09/2021 - Script para resolver o problema de gerar histórico finalizado e aguardando no relatório do sismples nacional
    delete from vct_empresa_thistoricotarefa his where(exists(select first 1 bdcodst from vct_empresa_thistoricotarefa x
    where(x.bdcodemp=his.bdcodemp) and (x.bdcodst=his.bdcodst) and (x.bddata=his.bddata)
    and(x.bdhora=his.bdhora) and (x.bdcodusuresponsavel=his.bdcodusuresponsavel) and (x.bdstatus=5)))
    and(his.bdstatus=4) and (his.bdcodemp=:prcodemp)
    and(his.bdcodst=:prcodst);
  end
  else
  if ((coalesce(:praguardando,0) = 0) and (:vdatafim is null)) then
  begin
    update vct_empresa_tsolicitatarefa set bddatafim = current_date, bdaguard = null, bdstatusatual = 4
    where (bdcodemp = :prcodemp) and (bdcodst = :prcodst)
    and (((bddatafim is null) or (bddatafim <> current_date)) or (bdaguard is not null) or (coalesce(bdstatusatual, 0) <> 4));

    update or insert into vct_empresa_thistoricotarefa(bdcodemp,bdcodst,bdcodusuresponsavel,bdstatus,bdobservacao,bdcodbhs)
    values(:prcodemp, :prcodst, :prcodusu,4,:prmensagem,:prcodbhs)
    matching(bdcodemp,bdcodst,bdcodusuresponsavel,bdstatus,bdobservacao,bdcodbhs);
  end
end^

--alt:12049 - 14/10/2015 - Criada nova procedure para o Relatório de Análises. Pedro
CREATE OR ALTER PROCEDURE VSUC_SP_RETORNA_BALANCO_PATRI_X (
    PRCODEMP VARCHAR(1024),
    PRDATINI DATE,
    PRDATFIN DATE,
    PRIGNZER INTEGER,
    PRCTALONINI VARCHAR(40),
    PRCTALONFIN VARCHAR(40),
    PRINDICE INTEGER,
    PRCODPLAPADRAO INTEGER,
    PRNAOMOSTRACONTACOMP INTEGER,
    PRCTASEMMOV INTEGER,
    PRREFEMP INTEGER,
    PRCONSOLIDADA INTEGER,
    PRDETALHARCTAPARTICIPANTE INTEGER,
    PRCONCATENACODPARTICIPANTE INTEGER,
    PRNIVEISCONTA VARCHAR(50),
    PRCONTABILIZACAO INTEGER,
    PRMATRIZFILIALCONSOLIDADO INTEGER,
    PRCONTATITULO INTEGER = NULL,
    PRSALDOCOMPARACAO INTEGER = 1)
RETURNS (
    BDCODEMP INTEGER,
    BDCODMATRIZ INTEGER,
    BDCODEMPFILIAL INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP VARCHAR(20),
    BDCODPLAPADRAO INTEGER,
    BDCODCTA INTEGER,
    BDCTALON VARCHAR(40),
    BDNOMCTA VARCHAR(100),
    BDTIPCTA INTEGER,
    BDSEQCTA VARCHAR(40),
    BDSALANT NUMERIC(15,2),
    BDSALMOV NUMERIC(15,2),
    BDSALATU NUMERIC(15,2),
    BDANAVER NUMERIC(15,2),
    BDANAHOR NUMERIC(15,2),
    BDFORMULA VARCHAR(1024),
    BDGRPCTA INTEGER,
    BDAPECTA VARCHAR(20),
    BDCONTATITULO INTEGER,
    BDSALDOCOMPARACAO NUMERIC(15,2))
AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODMATRIZ INTEGER;
DECLARE VARIABLE WCODEMPFILIAL INTEGER;
DECLARE VARIABLE WNOMEMP DM_BDNOMEMP;
DECLARE VARIABLE WCNPJEMP VARCHAR(20);
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODCTA INTEGER;
DECLARE VARIABLE WCTALON VARCHAR(40);
DECLARE VARIABLE WNOMCTA VARCHAR(100);
DECLARE VARIABLE WTIPCTA INTEGER;
DECLARE VARIABLE WFORMULA VARCHAR(1024);
DECLARE VARIABLE WGRPCTA INTEGER;
DECLARE VARIABLE WAPECTA VARCHAR(20);
DECLARE VARIABLE WSALANT NUMERIC(15,2);
DECLARE VARIABLE WSALATU NUMERIC(15,2);
DECLARE VARIABLE WPARTICIPANTE INTEGER;
DECLARE VARIABLE WCODCTAINI INTEGER;
DECLARE VARIABLE WCODCTAFIN INTEGER;
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WVALTIT NUMERIC(15,2);
DECLARE VARIABLE WSEQCTA VARCHAR(100);
DECLARE VARIABLE WCONTAANT INTEGER;
DECLARE VARIABLE WTERCEIROANT INTEGER;
DECLARE VARIABLE WEMPRESAANT INTEGER;
DECLARE VARIABLE WSQL VARCHAR(2048);
DECLARE VARIABLE WCONTATITULO INTEGER;
DECLARE VARIABLE WSALAUX NUMERIC(15,2);
BEGIN
  -- retorna a primeira conta referente a classificacao
  SELECT FIRST 1 planos_tpla.bdcodtpla FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdctalon = :prctalonini
  ORDER BY planos_tpla.bdctalon ASC INTO :wcodctaini;
  -- retorna a ultima conta referente a classificacao
  SELECT FIRST 1 planos_tpla.bdcodtpla FROM planos_tpla
  WHERE planos_tpla.bdcodplapadrao = :prcodplapadrao
  AND planos_tpla.bdctalon = :prctalonfin
  ORDER BY planos_tpla.bdctalon ASC INTO :wcodctafin;
    
  DELETE FROM vsuc_empresas_tbalancete_3 WHERE bdcodemp <> 0;
  wcontaant = 0;
  wterceiroant = 0;
  wempresaant = 0;
  --#alt:122374 - Variáveis de conta título para análise vertical por conta título
  if (PRCONTATITULO IS NULL) then
    PRCONTATITULO = 0;

  -- laco do calculo dos saldos do plano de contas
  wSQL = 'select bdcodemp, bdcodmatriz, bdcodempfilial, bdnomemp, bdcnpjemp,';
  wSQL = wSQL||'   bdcodplapadrao, bdcodcta, bdctalon, bdnomcta, bdtipcta, bdformula, bdgrpcta, bdapecta,';
  wSQL = wSQL||'   bdsaldo_anterior, bdsaldo_atual, bdcodter, IIF('||PRCONTATITULO||' = BDCODCTA, 0, 1) AS WCONTATITULO';
  wSQL = wSQL||' from vsuc_sp_retorna_balancete('''||:prcodemp||''', '''||:prdatini||''', '''||:prdatfin||''', '||:prignzer||', '||:wcodctaini||', '||:wcodctafin||', '||:prindice||', '''||''||''', ';
  wSQL = wSQL||'                                '||:prrefemp||', 0, 0, '||:prnaomostracontacomp||', '||:prconsolidada||', '||:prdetalharctaparticipante||', 0, ';
  wSQL = wSQL||'                                '||:prconcatenacodparticipante||', '''||:prniveisconta||''', 0, '||:prcontabilizacao||', 0, '||'0)';
/* #alt:151736 15/06/2021 - Carlos Machado - Removido order by do getBalancete, lentidão na MG
  IF (prmatrizfilialconsolidado = 0) THEN
    wSQL = wSQL||' order by BDCODEMPFILIAL, IIF('||PRCONTATITULO||' = BDCODCTA, 0, 1), BDCTALON';
  ELSE
    wSQL = wSQL||' order by IIF('||PRCONTATITULO||' = BDCODCTA, 0, 1), BDCTALON, BDCODEMPFILIAL';
*/
  FOR EXECUTE STATEMENT wSQL INTO :wcodemp, :wcodmatriz, :wcodempfilial, :wnomemp, :wcnpjemp,
                                  :wcodplapadrao, :wcodcta, :wctalon, :wnomcta, :wtipcta, :wformula, :wgrpcta, :wapecta,
                                  :wsalant, :wsalatu, :wparticipante,:WCONTATITULO DO
  BEGIN
    IF ((((prctasemmov = 0) AND ((bdsalatu <> 0) OR (bdsalmov <> 0))) OR (prctasemmov = 1)) AND
        (((wcontaant > 0) AND (wcontaant <> wcodcta)) OR (wterceiroant <> wparticipante)  OR ((prmatrizfilialconsolidado = 0) AND (wempresaant > 0) AND (wempresaant <> wcodempfilial)))) THEN
      BEGIN
        SUSPEND;
        if (BDCONTATITULO = 0 AND PRCTALONINI <> BDCTALON) then
          BEGIN
            BDCONTATITULO = 1;
            SUSPEND;
          END
        BDCODEMP = 0;
        BDCODMATRIZ = 0;
        BDCODEMPFILIAL = 0;
        BDNOMEMP = '';
        BDCNPJEMP = '';
        BDCODPLAPADRAO = 0;
        BDCODCTA = 0;
        BDCTALON = '';
        BDCONTATITULO = null;
        BDNOMCTA = '';
        BDTIPCTA = 0;
        BDSEQCTA = '';
        BDSALANT = 0;
        BDSALMOV = 0;
        BDSALATU = 0;
        BDANAVER = 0;
        BDFORMULA = '';
        BDGRPCTA = 0;
        BDAPECTA = '';
      END

    -- Detalhado por participante
    IF ((prdetalharctaparticipante = 1) AND (wparticipante > 0) AND (bdtipcta = 1) AND (prconcatenacodparticipante = 1)) THEN
      BEGIN
        wpos     = CHARACTER_LENGTH(:wparticipante);
                   -- 100 -> máximo de caracteres para nome da conta
                   -- 03 -> qtd de caracteres " - ";
        wpos     = ((100 - wpos) - 3);
        bdnomcta = wparticipante||' - '||SUBSTRING(bdnomcta FROM 1 FOR wpos);
      END

    BDCODEMP = wcodemp;
    BDNOMEMP = wnomemp;
    BDCNPJEMP = wcnpjemp;
    BDCODPLAPADRAO = wcodplapadrao;
    BDCODCTA = wcodcta;
    BDCTALON = wctalon;
    BDCONTATITULO = WCONTATITULO;
    BDNOMCTA = wnomcta;
    BDTIPCTA = wtipcta;
    BDAPECTA = wapecta;
    BDSEQCTA = wseqcta;
    BDSALANT = COALESCE(BDSALANT, 0) + wSalAnt;
    BDSALATU = COALESCE(BDSALATU, 0) + wSalAtu;
    BDSALMOV = BDSALATU - BDSALANT;
    BDFORMULA = wformula;
    BDGRPCTA = wgrpcta;

    IF (prmatrizfilialconsolidado = 1) THEN
      BEGIN
        BDCODMATRIZ =  wcodemp;
        BDCODEMPFILIAL = wcodemp;
      END
    ELSE
      BEGIN
        BDCODMATRIZ =  wcodmatriz;
        BDCODEMPFILIAL = wcodempfilial;
      END

    if ((POSITION('.', bdctalon) = 0)) then
      wseqcta = bdctalon;
    else
      wseqcta = substring(bdctalon from 1 for POSITION('.', bdctalon) - 1);

    if (PRSALDOCOMPARACAO = 0) then
      BDSALDOCOMPARACAO = BDSALMOV;
    ELSE
    if (PRSALDOCOMPARACAO = 1) then
      BDSALDOCOMPARACAO = BDSALATU;
    ELSE
    if (PRSALDOCOMPARACAO = 2) THEN
    BEGIN
      if (BDGRPCTA < 2) then
        BDSALDOCOMPARACAO = BDSALATU;
      else
        BDSALDOCOMPARACAO = BDSALMOV;
    END


    -- sql para verificar se a conta atual é uma titulo geral
    IF ((PRCONTATITULO > 0 and BDCONTATITULO = 0) or ((PRCONTATITULO <= 0) and ((POSITION('.', bdctalon) = 0)) OR ((prmatrizfilialconsolidado = 0) AND (wempresaant > 0) AND (wempresaant <> wcodempfilial)))) THEN
      BEGIN
        IF (BDSALDOCOMPARACAO IS NULL) THEN
          wvaltit = 0;
        ELSE
          wvaltit = BDSALDOCOMPARACAO;
      END
    bdseqcta = wseqcta;

    -- cálculo do percentual da analise vertical
    IF (wvaltit = 0) THEN
      bdanaver = 0;
    ELSE
      bdanaver = (BDSALDOCOMPARACAO * 100) / wvaltit;

    wcontaant = bdcodcta;
    wterceiroant = wparticipante;
    wempresaant = bdcodempfilial;
  END

  IF ((((prctasemmov = 0) AND ((bdsalatu <> 0) OR (bdsalmov <> 0))) OR (prctasemmov = 1)) AND
     --#alt:16143 - Removida a verificação das contas pois quando selecionava apenas uma conta não estava sendo mostrada. Ana - 06/02/2017
     --(((wcontaant > 0) and (wcontaant <> wcodcta)) or (wterceiroant <> wparticipante) or ((prmatrizfilialconsolidado = 0) and (wempresaant > 0) and (wempresaant <> wcodempfilial)))) then
       ((wcontaant > 0) OR (wterceiroant <> wparticipante) OR ((prmatrizfilialconsolidado = 0) AND (wempresaant > 0) AND (wempresaant <> wcodempfilial)))) THEN
    BEGIN
    SUSPEND;
      if (BDCONTATITULO = 0 AND PRCTALONINI <> BDCTALON) then
        BEGIN
          BDCONTATITULO = 1;
          SUSPEND;
        END
    END
END
^

CREATE OR ALTER PROCEDURE SP_BI_DRE (
    EMPRESA INTEGER,
    PLANO INTEGER,
    DATA_INICIAL DATE,
    DATA_FINAL DATE,
    TIPO_CONTABILIZACAO SMALLINT,
    IGNORA_ZERAMENTO SMALLINT,
    DETALHAR_FILIAIS SMALLINT)
RETURNS (
    BDCODEMP INTEGER,
    BDCODEMPFILIAL INTEGER,
    BDCODPFOR INTEGER,
    BDNOMPFOR VARCHAR(40),
    BDCODCONTA INTEGER,
    BDCLASSIFICACAO VARCHAR(40),
    BDNOMFOR VARCHAR(100),
    BDTIPO_CONTA INTEGER,
    BDVALOR NUMERIC(15,6))
AS
DECLARE VARIABLE ID INTEGER;
DECLARE VARIABLE WPRONTO SMALLINT;
DECLARE VARIABLE WITERATION INTEGER;
DECLARE VARIABLE WDATAHORABI TIMESTAMP;
BEGIN

  IN AUTONOMOUS TRANSACTION DO
  BEGIN
  select bdvalortime from tparametro where bdparam = 'data_hora_bi' into :wdatahorabi;
  if (wdatahorabi is null or datediff(minute from wdatahorabi to localtimestamp) > 10) then
    EXCEPTION ex_custom 'A base atual não está conectada a um ServidorSCI no momento, revise o caminho da base ou tente novamente mais tarde';

    INSERT INTO TPEDIDOS_BI (BDTIPO) VALUES (1) RETURNING BDID INTO :ID;
    INSERT INTO TPEDIDOS_BI_DRE (BDID, BDCODEMP, BDPLANO, BDDATAINI, BDDATAFIN, BDTIPOCONTABILIZACAO, BDIGNORAZERAMENTO, BDDETALHARFILIAIS) VALUES (:ID, :EMPRESA, :PLANO, :DATA_INICIAL, :DATA_FINAL, :TIPO_CONTABILIZACAO, :IGNORA_ZERAMENTO, :DETALHAR_FILIAIS);
  END

  WPRONTO = 0;
  wIteration = 0;
  WHILE (WPRONTO <> 1) DO
  BEGIN
    if (wIteration = 0) then
      execute procedure wait_sleep(1000);
    else if (wIteration = 1) then
      execute procedure wait_sleep(2000);
    else
      execute procedure wait_sleep(4000);

    IN AUTONOMOUS TRANSACTION DO
    BEGIN
      SELECT BDPRONTO FROM TPEDIDOS_BI WHERE BDID = :ID INTO :WPRONTO;
    END

    wIteration = wIteration + 1;
  END

  FOR EXECUTE STATEMENT 'select r.BDCODEMP, r.BDCODEMPFILIAL, r.BDCODPFOR, form.BDNOMPFOR, r.BDCODCTA, r.BDCLASSIFICACAO, r.BDNOMFOR, r.BDTIPOCTA, r.BDVALOR from TPEDIDOS_BI_DRE_RESULTADOS r ' || 
                        ' left outer join VSUC_BASE_TFORMULA form on (form.BDCODPFOR = r.BDCODPFOR) ' ||
                        ' where r.bdid = ' || :ID
          WITH AUTONOMOUS TRANSACTION
          INTO :BDCODEMP, :BDCODEMPFILIAL, :BDCODPFOR, :BDNOMPFOR, :BDCODCONTA, :BDCLASSIFICACAO, :BDNOMFOR, :BDTIPO_CONTA, :BDVALOR
  DO
  BEGIN
    SUSPEND;
  END

END^

COMMENT ON PROCEDURE SP_BI_DRE IS
'Geração da DRE - BI Connection'^

COMMENT ON PARAMETER SP_BI_DRE.EMPRESA IS
'Código da Empresa'^

COMMENT ON PARAMETER SP_BI_DRE.PLANO IS
'Código do Plano de Fórmulas'^

COMMENT ON PARAMETER SP_BI_DRE.DATA_INICIAL IS
'Data Inicial (DD.MM.AAAA)'^

COMMENT ON PARAMETER SP_BI_DRE.DATA_FINAL IS
'Data Final (DD.MM.AAAA)'^

COMMENT ON PARAMETER SP_BI_DRE.TIPO_CONTABILIZACAO IS
'Tipo de Contabilização (1 - Fiscal, 2 - Societária)'^

COMMENT ON PARAMETER SP_BI_DRE.IGNORA_ZERAMENTO IS
'Se deve ou não ignorar zeramento (0 - Não, 1 - Sim) '^

COMMENT ON PARAMETER SP_BI_DRE.DETALHAR_FILIAIS IS
'Se deve ou não detalhar por filial (0 - Não, 1 - Sim)'^

CREATE OR ALTER PROCEDURE SP_BI_FAT (
    EMPRESA INTEGER,
    PLANO INTEGER,
    QUADRO INTEGER,
    DATA_INICIAL DATE,
    DATA_FINAL DATE,
    SOMAMATRIZFILIAL SMALLINT)
RETURNS (
    BDCODEMP INTEGER,
    BDREF INTEGER,
    BDORDEM INTEGER,
    BDDESCRICAO VARCHAR(152),
    BDVALOR NUMERIC(15,6))
AS
DECLARE VARIABLE ID INTEGER;
DECLARE VARIABLE WPRONTO SMALLINT;
DECLARE VARIABLE WITERATION INTEGER;
DECLARE VARIABLE WDATAHORABI TIMESTAMP;
BEGIN

  IN AUTONOMOUS TRANSACTION DO
  BEGIN
  select bdvalortime from tparametro where bdparam = 'data_hora_bi' into :wdatahorabi;
  if (wdatahorabi is null or datediff(minute from wdatahorabi to localtimestamp) > 10) then
    EXCEPTION ex_custom 'A base atual não está conectada a um ServidorSCI no momento, revise o caminho da base ou tente novamente mais tarde';

    INSERT INTO TPEDIDOS_BI (BDTIPO) VALUES (2) RETURNING BDID INTO :ID;
    INSERT INTO TPEDIDOS_BI_FAT (BDID, BDCODEMP, BDPLANO, BDQUADRO, BDDATAINI, BDDATAFIN, BDSOMAMATRIZFILIAL) VALUES (:ID, :EMPRESA, :PLANO, :QUADRO, :DATA_INICIAL, :DATA_FINAL, :SOMAMATRIZFILIAL);
  END

  WPRONTO = 0;
  wIteration = 0;
  WHILE (WPRONTO <> 1) DO
  BEGIN
    if (wIteration = 0) then
      execute procedure wait_sleep(1000);
    else if (wIteration = 1) then
      execute procedure wait_sleep(2000);
    else
      execute procedure wait_sleep(4000);

    IN AUTONOMOUS TRANSACTION DO
    BEGIN
      SELECT BDPRONTO FROM TPEDIDOS_BI WHERE BDID = :ID INTO :WPRONTO;
    END

    wIteration = wIteration + 1;
  END

  FOR EXECUTE STATEMENT 'select BDCODEMP, BDREF, BDORDEM, BDDESCRICAO, BDVALOR from TPEDIDOS_BI_FAT_RESULTADOS r where r.bdid = ' || :ID
          WITH AUTONOMOUS TRANSACTION
          INTO :BDCODEMP, :BDREF, :BDORDEM, :BDDESCRICAO, :BDVALOR
  DO
  BEGIN
    SUSPEND;
  END

END^

COMMENT ON PROCEDURE SP_BI_FAT IS
'Geração do Relatório do Faturamento de um Período/Configurável'^

COMMENT ON PARAMETER SP_BI_FAT.EMPRESA IS
'Código da Empresa'^

COMMENT ON PARAMETER SP_BI_FAT.PLANO IS
'Código do Plano'^

COMMENT ON PARAMETER SP_BI_FAT.QUADRO IS
'Código do Quadro'^

COMMENT ON PARAMETER SP_BI_FAT.DATA_INICIAL IS
'Data Inicial (Só a referencia será considerada)'^

COMMENT ON PARAMETER SP_BI_FAT.DATA_FINAL IS
'Data Final (Só a referencia será considerada)'^

COMMENT ON PARAMETER SP_BI_FAT.SOMAMATRIZFILIAL IS
'Se deve ou não somar matriz e filiais (0 - Não, 1 - Sim)'^

CREATE OR ALTER PROCEDURE GETINTEGERLIST("AINTEGERLIST" VARCHAR(32000))
returns (
  ID integer
)
as
  declare variable IntegerList varchar(32000);
  declare variable CommaPos integer;
  declare variable IntegerVal varchar(10);
begin
  IntegerList = AIntegerList || ' ';
  CommaPos = Position(',', IntegerList);

  while (CommaPos > 0) do
  begin
    IntegerVal = Trim(SubString(IntegerList from 1 for CommaPos - 1));

    if (Char_Length(IntegerVal) > 0) then
    begin
      if (IntegerVal similar to '[0-9]*') then
      begin
        ID = Cast(IntegerVal as integer);
        suspend;
      end
    end

    if (Char_Length(IntegerList) > CommaPos) then
      IntegerList = SubString(IntegerList from CommaPos + 1);
    else
      IntegerList = '';

    CommaPos = Position(',', IntegerList);
  end

  IntegerList = Trim(IntegerList);

  if (Char_Length(IntegerList) > 0) then
  begin
    if (IntegerList similar to '[0-9]*') then
    begin
      ID = Cast(IntegerList as integer);
      suspend;
    end
  end
end^

create or alter procedure GETINTEGERLISTBLOB (
    AIntegerList blob sub_type text
)
returns (
    ID integer
)
as
declare variable IntegerList blob sub_type text;
declare variable wPedaco varchar(32765);
declare variable IntegerVal varchar(100);
declare variable CommaPos integer;
declare variable wOffset integer;
declare variable wPedacoSize integer;
declare variable wTemp varchar(32765);
declare variable wRemainder varchar(1000);
begin
  IntegerList = AIntegerList;
  wPedacoSize = 32000;
  wOffset = 1;
  wRemainder = '';

  while (wOffset <= char_length(IntegerList)) do
  begin
    -- pedaço do blob (até 32k)
    wPedaco = cast(substring(IntegerList from wOffset for wPedacoSize) as varchar(32765));
    wOffset = wOffset + wPedacoSize;

    -- concatena o resto que sobrou do bloco anterior
    wTemp = wRemainder || wPedaco;

    -- processa o pedaço até a última vírgula completa
    CommaPos = position(',', wTemp);
    while (CommaPos > 0) do
    begin
      IntegerVal = trim(substring(wTemp from 1 for CommaPos - 1));

      if (char_length(IntegerVal) > 0) then
      begin
        if (IntegerVal similar to '[0-9]*') then
        begin
          ID = cast(IntegerVal as integer);
          suspend;
        end
      end

      wTemp = substring(wTemp from CommaPos + 1);
      CommaPos = position(',', wTemp);
    end

    wRemainder = wTemp;
  end

  wRemainder = trim(wRemainder);
  if (char_length(wRemainder) > 0) then
  begin
    if (wRemainder similar to '[0-9]*') then
    begin
      ID = cast(wRemainder as integer);
      suspend;
    end
  end
end^

CREATE OR ALTER PROCEDURE SP_BI_FAT_TODAS (
    PLANO INTEGER,
    QUADRO INTEGER,
    DATA_INICIAL DATE,
    DATA_FINAL DATE,
    SOMAMATRIZFILIAL SMALLINT)
RETURNS (
    BDCODEMP INTEGER,
    BDREF INTEGER,
    BDORDEM INTEGER,
    BDDESCRICAO VARCHAR(152),
    BDVALOR NUMERIC(15,6))
AS
DECLARE VARIABLE ID INTEGER;
DECLARE VARIABLE EMPRESA INTEGER;
DECLARE VARIABLE WPRONTO SMALLINT;
DECLARE VARIABLE WITERATION INTEGER;
DECLARE VARIABLE WDATAHORABI TIMESTAMP;
BEGIN

  IN AUTONOMOUS TRANSACTION DO
  BEGIN
  select bdvalortime from tparametro where bdparam = 'data_hora_bi' into :wdatahorabi;
  if (wdatahorabi is null or datediff(minute from wdatahorabi to localtimestamp) > 10) then
    EXCEPTION ex_custom 'A base atual não está conectada a um ServidorSCI no momento, revise o caminho da base ou tente novamente mais tarde';

   DELETE FROM TMP_EMPRESAS_SELECT;
  END

  FOR EXECUTE STATEMENT 'SELECT BDCODEMP FROM TEMPRESAS' INTO :EMPRESA
  DO
  BEGIN
    IN AUTONOMOUS TRANSACTION DO
    BEGIN
      INSERT INTO TPEDIDOS_BI (BDTIPO) VALUES (2) RETURNING BDID INTO :ID;
      INSERT INTO TPEDIDOS_BI_FAT (BDID, BDCODEMP, BDPLANO, BDQUADRO, BDDATAINI, BDDATAFIN, BDSOMAMATRIZFILIAL) VALUES (:ID, :EMPRESA, :PLANO, :QUADRO, :DATA_INICIAL, :DATA_FINAL, :SOMAMATRIZFILIAL);
      INSERT INTO TMP_EMPRESAS_SELECT (BDCODEMP) VALUES (:ID);
    END
  END

  WPRONTO = 1;
  wIteration = 0;
  WHILE (WPRONTO > 0) DO
  BEGIN
    if (wIteration = 0) then
      execute procedure wait_sleep(1000);
    else if (wIteration = 1) then
      execute procedure wait_sleep(2000);
    else
      execute procedure wait_sleep(4000);

    IN AUTONOMOUS TRANSACTION DO
    BEGIN
      SELECT COUNT(BDID) FROM TMP_EMPRESAS_SELECT TMP
      INNER JOIN TPEDIDOS_BI P ON P.bdid = TMP.bdcodemp
      WHERE BDPRONTO <> 1 INTO :WPRONTO;
    END

    wIteration = wIteration + 1;
  END


  FOR EXECUTE STATEMENT 'select r.BDCODEMP, r.BDREF, r.BDORDEM, r.BDDESCRICAO, r.BDVALOR from TMP_EMPRESAS_SELECT TMP INNER JOIN TPEDIDOS_BI_FAT_RESULTADOS r ON r.bdid = TMP.bdcodemp'
          WITH AUTONOMOUS TRANSACTION
          INTO :BDCODEMP, :BDREF, :BDORDEM, :BDDESCRICAO, :BDVALOR
  DO
  BEGIN
    SUSPEND;
  END
END^

CREATE OR ALTER PROCEDURE SP_BI_CONF_FOLHA (
    EMPRESA INTEGER,
    CODIGO_RELATORIO INTEGER,
    DATA_INICIAL DATE,
    DATA_FINAL DATE,
    AGRUPAR_POR SMALLINT)
RETURNS (
    BDCODEMP INTEGER,
    BDREF INTEGER,
    BDCODCOL INTEGER,
    BDCODTER INTEGER,
    BDORDEM INTEGER,
    BDDESCRICAO VARCHAR(152),
    BDVALOR NUMERIC(15,6),
    BDCODTPCC INTEGER)
AS
DECLARE VARIABLE ID INTEGER;
DECLARE VARIABLE WPRONTO SMALLINT;
DECLARE VARIABLE WITERATION INTEGER;
DECLARE VARIABLE WDATAHORABI TIMESTAMP;
BEGIN

  IN AUTONOMOUS TRANSACTION DO
  BEGIN
  select bdvalortime from tparametro where bdparam = 'data_hora_bi' into :wdatahorabi;
  if (wdatahorabi is null or datediff(minute from wdatahorabi to localtimestamp) > 10) then
    EXCEPTION ex_custom 'A base atual não está conectada a um ServidorSCI no momento, revise o caminho da base ou tente novamente mais tarde';

    INSERT INTO TPEDIDOS_BI (BDTIPO) VALUES (4) RETURNING BDID INTO :ID;
    INSERT INTO TPEDIDOS_BI_CONF_FOLHA (BDID, BDCODEMP, BDCODIGO_RELATORIO, BDDATAINI, BDDATAFIN, BDAGRUPARPOR) VALUES (:ID, :EMPRESA, :CODIGO_RELATORIO, :DATA_INICIAL, :DATA_FINAL, :AGRUPAR_POR);
  END

  WPRONTO = 0;
  wIteration = 0;
  WHILE (WPRONTO <> 1) DO
  BEGIN
    if (wIteration = 0) then
      execute procedure wait_sleep(1000);
    else if (wIteration = 1) then
      execute procedure wait_sleep(2000);
    else
      execute procedure wait_sleep(4000);

    IN AUTONOMOUS TRANSACTION DO
    BEGIN
      SELECT BDPRONTO FROM TPEDIDOS_BI WHERE BDID = :ID INTO :WPRONTO;
    END

    wIteration = wIteration + 1;
  END

  FOR EXECUTE STATEMENT 'select BDCODEMP, BDREF, BDCODCOL, BDCODTER, BDORDEM, BDDESCRICAO, BDVALOR, BDCODTPCC from tpedidos_bi_conf_folha_resultados r where r.bdid = ' || :ID
          WITH AUTONOMOUS TRANSACTION
          INTO :BDCODEMP, :BDREF, :BDCODCOL, :BDCODTER, :BDORDEM, :BDDESCRICAO, :BDVALOR, :BDCODTPCC
  DO
  BEGIN
    SUSPEND;
  END

END^

CREATE OR ALTER PROCEDURE SP_BI_CONF_FOLHA_TODAS (
    CODIGO_RELATORIO INTEGER,
    DATA_INICIAL DATE,
    DATA_FINAL DATE,
    AGRUPAR_POR SMALLINT)
RETURNS (
    BDCODEMP INTEGER,
    BDREF INTEGER,
    BDCODCOL INTEGER,
    BDCODTER INTEGER,
    BDORDEM INTEGER,
    BDDESCRICAO VARCHAR(152),
    BDVALOR NUMERIC(15,6),
    BDCODTPCC INTEGER)
AS
DECLARE VARIABLE ID INTEGER;
DECLARE VARIABLE EMPRESA INTEGER;
DECLARE VARIABLE WPRONTO SMALLINT;
DECLARE VARIABLE WITERATION INTEGER;
DECLARE VARIABLE WDATAHORABI TIMESTAMP;
BEGIN

  IN AUTONOMOUS TRANSACTION DO
  BEGIN
  select bdvalortime from tparametro where bdparam = 'data_hora_bi' into :wdatahorabi;
  if (wdatahorabi is null or datediff(minute from wdatahorabi to localtimestamp) > 10) then
    EXCEPTION ex_custom 'A base atual não está conectada a um ServidorSCI no momento, revise o caminho da base ou tente novamente mais tarde';

     DELETE FROM TMP_EMPRESAS_SELECT;
  END

  FOR EXECUTE STATEMENT 'SELECT BDCODEMP FROM TEMPRESAS'
  WITH AUTONOMOUS TRANSACTION
  INTO :EMPRESA
  DO
  BEGIN
    IN AUTONOMOUS TRANSACTION DO
    BEGIN
      INSERT INTO TPEDIDOS_BI (BDTIPO) VALUES (4) RETURNING BDID INTO :ID;
      INSERT INTO TPEDIDOS_BI_CONF_FOLHA (BDID, BDCODEMP, BDCODIGO_RELATORIO, BDDATAINI, BDDATAFIN, BDAGRUPARPOR) VALUES (:ID, :EMPRESA, :CODIGO_RELATORIO, :DATA_INICIAL, :DATA_FINAL, :AGRUPAR_POR);
      INSERT INTO TMP_EMPRESAS_SELECT (BDCODEMP) VALUES (:ID);
    END
  END

  WPRONTO = 1;
  wIteration = 0;
  WHILE (WPRONTO > 0) DO
  BEGIN
    if (wIteration = 0) then
      execute procedure wait_sleep(1000);
    else if (wIteration = 1) then
      execute procedure wait_sleep(2000);
    else
      execute procedure wait_sleep(4000);

    IN AUTONOMOUS TRANSACTION DO
    BEGIN
      SELECT COUNT(BDID) FROM TMP_EMPRESAS_SELECT TMP
      INNER JOIN TPEDIDOS_BI P ON P.bdid = TMP.bdcodemp
      WHERE BDPRONTO <> 1 INTO :WPRONTO;
    END

    wIteration = wIteration + 1;
  END

  FOR EXECUTE statement 'SELECT P.BDCODEMP, P.BDREF, P.BDCODCOL, P.BDCODTER, P.BDORDEM, P.BDDESCRICAO, P.BDVALOR, P.BDCODTPCC FROM TMP_EMPRESAS_SELECT TMP INNER JOIN tpedidos_bi_conf_folha_resultados P ON P.bdid = TMP.bdcodemp'
  WITH AUTONOMOUS TRANSACTION
   INTO :BDCODEMP, :BDREF, :BDCODCOL, :BDCODTER, :BDORDEM, :BDDESCRICAO, :BDVALOR, :BDCODTPCC
  DO
  BEGIN
    SUSPEND;
  END

END^

CREATE OR ALTER PROCEDURE SP_BI_RELATORIOS (
    NOME_RELATORIO VARCHAR(80),
    CODIGO_EMPRESA INTEGER,
    PARAMS_REL VARCHAR(5000),
    TIPO_SAIDA INTEGER)
RETURNS (
    RETORNO VARCHAR(32000))
AS
DECLARE VARIABLE ID INTEGER;
DECLARE VARIABLE WPRONTO SMALLINT;
DECLARE VARIABLE WDATAHORABI TIMESTAMP;
BEGIN

  IN AUTONOMOUS TRANSACTION DO
   BEGIN
  select bdvalortime from tparametro where bdparam = 'data_hora_bi' into :wdatahorabi;
  if (wdatahorabi is null or datediff(minute from wdatahorabi to localtimestamp) > 10) then
    EXCEPTION ex_custom 'A base atual não está conectada a um ServidorSCI no momento, revise o caminho da base ou tente novamente mais tarde';

      INSERT INTO TPEDIDOS_BI (BDTIPO) VALUES (3) RETURNING BDID INTO :ID;
      INSERT INTO TPEDIDOS_BI_RELATORIOS (BDID, BDCODEMP, BDNOMEREL, BDPARAMETROS, BDTIPOSAIDA) VALUES (:ID, :CODIGO_EMPRESA, :NOME_RELATORIO, :PARAMS_REL, :TIPO_SAIDA);
    END

  WPRONTO = 0;
  WHILE (WPRONTO <> 1) DO
  BEGIN
    EXECUTE PROCEDURE WAIT_SLEEP(3000);

    IN AUTONOMOUS TRANSACTION DO
    BEGIN
      SELECT BDPRONTO FROM TPEDIDOS_BI WHERE BDID = :ID INTO :WPRONTO;
    END
  END

  FOR EXECUTE STATEMENT 'SELECT BDRESULTADO from TPEDIDOS_BI_RELATORIOS_RESULTADOS where BDID = ' || :ID
    WITH AUTONOMOUS TRANSACTION
    INTO :RETORNO
  DO
  BEGIN
    SUSPEND;
  END
END^

COMMENT ON PARAMETER SP_BI_RELATORIOS.TIPO_SAIDA IS 'Tipo da saída 1-PDF, 2-TXT, 3-BI, 4-XLSX, 5-CSV, 6-BI DETALHADO'^

CREATE OR ALTER TRIGGER vct_tributos_plano_trib_ai0 FOR vct_tributos_plano_tributario
ACTIVE AFTER INSERT POSITION 0
AS
  DECLARE VARIABLE vcodtrib INTEGER;
  DECLARE VARIABLE vcodplatrib INTEGER;
  DECLARE VARIABLE vCODIMP INTEGER;
  DECLARE VARIABLE vCODOBRSER INTEGER;
  DECLARE VARIABLE vcodplatribcopia INTEGER;

  DECLARE VARIABLE wTotal INTEGER;
BEGIN
--  select total from vct_tarefas_automaticas(0) into wTotal;-- Gilberto - 04/09/2014 - ALT:#9748 - Centralização da rotina
END^

CREATE OR ALTER trigger tempresaimposto_biud0 for tempresaimposto
active before insert or update or delete position 0
AS
  declare variable vtributos boolean;
  declare variable vcodemp integer;
  declare variable vMsg varchar(1000);
  declare variable vstatus integer;
  declare variable vverba integer;
  declare variable vref integer;
  declare variable vEhPis integer;
  declare variable vcodmatriz integer;
  declare variable vretificou1010pis boolean;
begin
  /* Trigger criada exclusivamente para rastrear tributos alterados fora do ambiente de configuração de tributos por empresa */
  vtributos = (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_TRIBUTOS')) FROM rdb$database);
  /* extraindo informações para compor no log */
  vstatus = 0;
  if (old.bdcodemp is null) then
  begin
    vcodemp = new.bdcodemp;
    if (new.bdcodimp is not null) then
       vMsg = 'Inserção do imposto: '||new.bdcodimp;
    vmsg = vmsg||' [Competência inicial] '||new.bdrefemp;
    if (new.bdreffimimp is not null) then
       vmsg = vmsg||' [Competência final] '||new.bdreffimimp;

    vstatus = 0;
  end
  else
  begin
    vcodemp = old.bdcodemp;
    if (new.bdcodemp is null) then
    begin
      vmsg = 'Exclusão ';
      if (old.bdcodimp is not null) then
         vmsg = vmsg||' do imposto: '||old.bdcodimp;
      vmsg = vmsg||' [Competência inicial] '||old.bdrefemp;
      if (old.bdreffimimp is not null) then
         vmsg = vmsg||' [Competência final] '||old.bdreffimimp;

      vstatus = 1;
    end
    else
    begin
      vmsg = 'Alteração ';
      if (old.bdcodimp is not null) then
         vmsg = vmsg||' do imposto: '||old.bdcodimp;
      vmsg = vmsg||' [Competência inicial [de] '||old.bdrefemp||' [Para] '||new.bdrefemp||']';
      if (old.bdreffimimp is not null) then
         vmsg = vmsg||' [Competência final [de] '||old.bdreffimimp||' [Para] '||new.bdreffimimp||']';

      vstatus = 0;
    end
  end
  /* Caso variável de sessão estiver desabilitada, deve retornar como erro, impedindo a inserção, alteração ou exclusão do tributo */
  if (not vtributos) then
  begin
    EXECUTE PROCEDURE SP_INSERIR_LOG(:vcodemp, NULL, (select bdcodusu from VW_USUARIOS_SECAO),
                                     NULL, (select bdcodsis from VW_GET_MODULO), NULL, null, null,
                                     'Houve uma tentativa de alterar os tributos por empresa, fora do seu ambiente de configuração de tributos. '||vmsg,
                                     0, 1, null, null, (select BDNOMETELA from vw_get_processo),
                                     (select BDCAPTIONTELA from vw_get_processo), NULL,
                                     'VCT_TRIBUTARIO_EMPRESA', NULL, 'FALSE', current_date);

    EXCEPTION EX_CUSTOM 'Os tributos por empresa não podem ser alterados fora do seu ambiente de configuração de tributos.';
  end
  else
  begin
    EXECUTE PROCEDURE SP_INSERIR_LOG(:vcodemp, NULL, (select bdcodusu from VW_USUARIOS_SECAO),
                                     NULL, (select bdcodsis from VW_GET_MODULO), NULL, null, null,
                                     :vmsg,
                                     0, 1, null, null, (select BDNOMETELA from vw_get_processo),
                                     (select BDCAPTIONTELA from vw_get_processo), NULL,
                                     'VCT_TRIBUTARIO_EMPRESA', NULL, 'FALSE', current_date);
  end

  vEhPis = -1;
  if (vstatus = 0) then
     begin
        SELECT IMP.BDCODIMP
        FROM TIMPOSTO IMP
        WHERE IMP.BDCODIMP = new.BDCODIMP AND
              IMP.BDDOCARRECADACAO = 1 AND
              IMP.BDCODSIS = 2 AND
              IMP.BDCODTIPIMP = 6
        INTO vEhPis;

        if (coalesce(vEhPis, 0) > 0) then
           begin
               vcodmatriz = 0;
               vretificou1010pis = false;
               SELECT BDCODMATRIZ, BDRETIFICOU1010PIS FROM TEMPRESAS WHERE BDCODEMP = new.BDCODEMP INTO :vcodmatriz, :vretificou1010pis;

               if ((coalesce(vcodmatriz, 0) = 0) and (COALESCE(vretificou1010pis, FALSE) = FALSE)) then
                  begin
                       FOR SELECT ARQ.BDCODVER, MIN(ARQ.BDREFARQ)
                       FROM VRH_ESOCIAL_TARQUIVO ARQ
                       JOIN VRH_BASE_TVERBAS VER ON (ARQ.BDCODVER = VER.BDCODVER)
                       WHERE ARQ.BDCODEMP = new.BDCODEMP
                       GROUP BY ARQ.BDCODVER
                       INTO :vverba, :vref DO
                       BEGIN
                            UPDATE OR INSERT INTO VRH_ESOCIAL_RETIFICA_S_1010 (BDCODEMP, BDCODVER, BDREF) VALUES (new.BDCODEMP, :vverba, :vref) MATCHING (BDCODEMP, BDCODVER, BDREF);
                       END

                       UPDATE TEMPRESAS SET BDRETIFICOU1010PIS = TRUE WHERE BDCODEMP = new.BDCODEMP;
                  end
           end
     end
end^

CREATE OR ALTER TRIGGER tempresaimposto_bi0 FOR tempresaimposto
ACTIVE BEFORE INSERT POSITION 1
AS
BEGIN
  -- gilberto - ALT:#10115 - dias úteis para entrega
  IF (NEW.bdentrega IS NULL) THEN -- #150975 - Antony Rairon
  SELECT bdentrega FROM timposto WHERE bdcodimp = NEW.bdcodimp INTO NEW.bdentrega;
END
^

CREATE OR ALTER PROCEDURE SP_SETA_CADEMPRESA (
    prvalue INTEGER)
AS
BEGIN
  -- gilberto - 15/09/2014 - responsável por não deixar gerar tarefas automáticas no cadastro de empresas
  IF (prvalue IS NOT NULL AND prvalue <> 0) THEN
     rdb$set_context('USER_SESSION', 'W_CADEMPRESA', CAST(prvalue AS VARCHAR(6)));
  ELSE
     rdb$set_context('USER_SESSION', 'W_CADEMPRESA', NULL);
END^


CREATE OR ALTER TRIGGER vef_base_tcadinfcom_bu0 FOR vef_base_tcadinfcom
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  /* Trigger text */
  NEW.BDDESCINFCOMHASH = HASH(UPPER(NEW.BDDESCINFCOM));
  if (NEW.bdsonumeros IS null) then
    NEW.BDSONUMEROS      =  (select BDRESULT from  SONUMEROS(NEW.BDCODINFCOM));
END^

--#alt: 12280 - Criado novo procedimento para gerar novo código do plano de conta. Ana - 06/10/2016
CREATE OR ALTER PROCEDURE SP_VERIFICA_NOVO_CODIGO (
    PRCODPLAPADRAO INTEGER,
    PRCODTPLA INTEGER,
    PRCTALON VARCHAR(40))
RETURNS (
    BDCODIGO INTEGER)
AS
DECLARE VARIABLE WNOVACHAVE INTEGER;
DECLARE VARIABLE WCODIGO2 INTEGER;
DECLARE VARIABLE WCODIGO1 INTEGER;
BEGIN
  -- verifica se ja existe aguma conta
  SELECT bdcodtpla FROM planos_tpla
  WHERE (bdcodtpla = :prCodTpla)
  AND (bdcodplapadrao = :prCodPlaPadrao)
  INTO wCodigo1;

  IF (wCodigo1> 0) THEN
     BEGIN
       -- se existir, então deve verificar se a classificação também é a mesma
       -- como o sistema não permite inserir uma nova conta com classifição ja existente, então o registro deve estar vindo da importação
       SELECT bdcodtpla FROM planos_tpla
       WHERE (bdcodtpla = :prCodTpla)
       AND (bdcodplapadrao = :prCodPlaPadrao)
       AND (bdctalon = :prCtalon)
       INTO wCodigo2;

       IF (wCodigo2 > 0) THEN
          DELETE FROM planos_tpla WHERE bdcodplapadrao = :prcodplapadrao AND bdcodtpla = :prcodtpla;
       ELSE
          BEGIN
             SELECT COALESCE((MAX(bdcodtpla)+1), 1) FROM planos_tpla WHERE bdcodplapadrao = :prcodplapadrao INTO wNovaChave;
             bdcodigo = wNovaChave;
    
             SUSPEND;
          END
    END
END
^
--#ALT: 12280. FIM

/* Restore proc. body: SP_VRHF_UNION_FN_FT_MES */
create or alter procedure SP_VRHF_UNION_FN_FT_MES (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRANOMES integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDCODVER integer,
    BDCLAVER varchar(20),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDREFVFN_SUM numeric(15,6),
    BDREFAUXVFN_SUM numeric(15,6),
    BDREFVFN_MAX numeric(15,6),
    BDREFAUXVFN_MAX numeric(15,6),
    BDVALVFN numeric(15,6),
    BDVALVIFN numeric(15,6),
    BDIGNREFVFN DM_BOOLEAN,
    BDIGNREFAVFN DM_BOOLEAN,
    BDIGNVALVFN DM_BOOLEAN,
    BDORVERBA integer,
    BDALTINT boolean)
as
declare variable WCLAVER varchar(20);
declare variable WSQL varchar(32700);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WVERATU integer;
declare variable WHOREMP DM_BOOLEAN;
declare variable WTIPOREFVER integer;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREFFN integer;
declare variable WCODVER integer;
declare variable WCOMPESP varchar(300);
declare variable WFORMREFAUX varchar(5000);
declare variable WFORMREF varchar(5000);
declare variable WFORMVAL varchar(5000);
declare variable WREFVSUM numeric(15,6);
declare variable WREFAUXVSUM numeric(15,6);
declare variable WREFVMAX numeric(15,6);
declare variable WREFAUXVMAX numeric(15,6);
declare variable WVALV numeric(15,6);
declare variable WVALIV numeric(15,6);
declare variable WIGREF DM_BOOLEAN;
declare variable WIGREFAUX DM_BOOLEAN;
declare variable WIGVAL DM_BOOLEAN;
declare variable WORVERBA integer;
declare variable WCOMPESPANT varchar(300);
declare variable WFORMREFAUXANT varchar(5000);
declare variable WFORMREFANT varchar(5000);
declare variable WFORMVALANT varchar(5000);
declare variable WREFVSUMANT numeric(15,6);
declare variable WREFAUXVSUMANT numeric(15,6);
declare variable WVALVANT numeric(15,6);
declare variable WVALIVANT numeric(15,6);
declare variable WIGREFANT DM_BOOLEAN;
declare variable WIGREFAUXANT DM_BOOLEAN;
declare variable WIGVALANT DM_BOOLEAN;
declare variable WORVERBAANT integer;
declare variable WFRACAO numeric(15,6);
declare variable WCLAVERATU varchar(20);
declare variable WALTINT boolean;
declare variable WALTINTANT boolean;
BEGIN
  wsql = 'SELECT '||
           'FN.BDCODEMP, '||
           'FN.BDCODCOL, '||
           'FN.BDREFFN, '||
           'FN.BDCODVER, '||
           'FN.BDCOMPESP, '||
           'FN.BDFORMREFAUX, '||
           'FN.BDFORMREF, '||
           'FN.BDFORMVAL, '||
           'FN.BDREFVFN, '||
           'FN.BDREFAUXVFN, '||
           'FN.BDREFVFN, '||
           'FN.BDREFAUXVFN, '||
           'FN.BDVALVFN, '||
           'FN.BDVALVIFN, '||
           'FN.BDIGNREFVFN, '||
           'FN.BDIGNREFAVFN, '||
           'FN.BDIGNVALVFN, '||
           'FN.BDORVERBAFN, '||
           'FN.BDALTINT '||
         'FROM '||
           'VRHF_EMP_TVERBAFN FN ';

  wsql = wsql||
         'where FN.BDREFFN = '||pranomes;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wsql = wsql||' and '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     END

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFFN,
    :BDCODVER,
    :BDCOMPESP,
    :BDFORMREFAUX,
    :BDFORMREF,
    :BDFORMVAL,
    :BDREFVFN_SUM,
    :BDREFAUXVFN_SUM,
    :BDREFVFN_MAX,
    :BDREFAUXVFN_MAX,
    :BDVALVFN,
    :BDVALVIFN,
    :BDIGNREFVFN,
    :BDIGNREFAVFN,
    :BDIGNVALVFN,
    :BDORVERBA,
    :BDALTINT
  DO
    SUSPEND;


  wsql = 'SELECT '||
           'FN.BDCODEMP, '||
           'FN.BDCODCOL, '||
           'FN.BDREFTOMADOR, '||
           'FN.BDCODVER, '||
           'FN.BDCOMPESP, '||
           'FN.BDFORMREFAUX, '||
           'FN.BDFORMREF, '||
           'FN.BDFORMVAL, '||
           'FN.BDREFVFT, '||
           'FN.BDREFAUXVFT, '||
           'FN.BDVALVFT, '||
           'FN.BDVALVIFT, '||
           'FN.BDIGNREFVFT, '||
           'FN.BDIGNREFAVFT,'||
           'FN.BDIGNVALVFT, '||
           'FN.BDORVERBAFT, '||
           'FN.BDALTINT, '||
           'EMPCALC.BDREFHOREMP, '||
           'VERREF.BDTIPOREFVER, '||
           'VERREF.BDCLAVER '||
         'FROM '||
           'VRHF_EMP_TVERBATOMADOR FN '||
         'left outer join VW_VRHF_BASE_TEMPCALC EMPCALC on (EMPCALC.BDCODEMP = FN.BDCODEMP) '||
         'left outer join VW_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER) '||
         'where FN.BDREFTOMADOR = '||pranomes;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wsql = wsql||' and '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;
     END
  wsql = wsql||' order by FN.BDCODEMP, FN.BDCODCOL, FN.BDREFTOMADOR, FN.BDCODVER';

  wempatu     = 0;
  wcolatu     = 0;
  wrefatu     = 0;
  wveratu     = 0;
  wcompesp    = '';
  wformrefaux = '';
  wformref    = '';
  wformval    = '';
  wrefvsum    = 0;
  wrefauxvsum = 0;
  wrefvmax    = 0;
  wrefauxvmax = 0;
  wvalv       = 0;
  wvaliv      = 0;
  wigref      = '';
  wigrefaux   = '';
  wigval      = '';
  worverba    = -1;
  waltint     = false;
  wclaveratu  = '';
  waltint     = false;


  FOR EXECUTE STATEMENT wsql INTO
    :wcodemp,
    :wcodcol,
    :wreffn,
    :wcodver,
    :wcompespant,
    :wformrefauxant,
    :wformrefant,
    :wformvalant,
    :wrefvsumant,
    :wrefauxvsumant,
    :wvalvant,
    :wvalivant,
    :wigrefant,
    :wigrefauxant,
    :wigvalant,
    :worverbaant,
    :waltintant,
    :whoremp,
    :wtiporefver,
    :wclaver
  DO
    BEGIN
      IF (wempatu = 0) THEN
         wempatu = wcodemp;

      IF (wcolatu = 0) THEN
         wcolatu = wcodcol;

      IF (wrefatu = 0) THEN
         wrefatu = wreffn;

      IF (wveratu = 0) THEN
         wveratu = wcodver;

      if (wclaveratu = '') then
         wclaveratu = wclaver;

      IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wrefatu <> wreffn) OR (wveratu <> wcodver)) THEN
         BEGIN
           BDCODEMP        = wempatu;
           BDCODCOL        = wcolatu;
           BDREFFN         = wrefatu;
           BDCODVER        = wveratu;
           BDCOMPESP       = wcompesp;
           BDFORMREFAUX    = wformrefaux;
           BDFORMREF       = wformref;
           BDFORMVAL       = wformval;
           BDREFVFN_SUM    = wrefvsum;
           BDREFAUXVFN_SUM = wrefauxvsum;
           BDREFVFN_MAX    = wrefvmax;
           BDREFAUXVFN_MAX = wrefauxvmax;
           BDVALVFN        = wvalv;
           BDVALVIFN       = wvaliv;
           BDIGNREFVFN     = wigref;
           BDIGNREFAVFN    = wigrefaux;
           BDIGNVALVFN     = wigval;
           BDORVERBA       = worverba;
           BDALTINT        = waltint;
           BDCLAVER        = wclaveratu;
           SUSPEND;

           wempatu     = wcodemp;
           wcolatu     = wcodcol;
           wrefatu     = wreffn;
           wveratu     = wcodver;
           wcompesp    = '';
           wformrefaux = '';
           wformref    = '';
           wformval    = '';
           wrefvsum    = 0;
           wrefauxvsum = 0;
           wrefvmax    = 0;
           wrefauxvmax = 0;
           wvalv       = 0;
           wvaliv      = 0;
           wigref      = '';
           wigrefaux   = '';
           wigval      = '';
           worverba    = -1;
           waltint     = false;
           wclaveratu  = wclaver;
         END

      --#Alt:90057. Carlos Mello(17/09/2018) - Ocorria erro quando passava de 300 caracteres
      --IF (wcompesp <> '') THEN
      --   wcompesp = wcompesp||'. ' ;
      --wcompesp = SUBSTRING((wcompesp||wcompespant) FROM 1 FOR 300);
      IF (wcompesp <> '') THEN
         wcompesp = SUBSTRING((wcompesp||'. '||wcompespant) FROM 1 FOR 300);
      ELSE
      wcompesp = SUBSTRING((wcompesp||wcompespant) FROM 1 FOR 300);

--      IF (wformrefaux <> '') THEN
--         wformrefaux = SUBSTRING((wformrefaux||'. ') FROM 1 FOR 5000) ;

      IF (wformrefaux = '') THEN
      wformrefaux = SUBSTRING((wformrefaux||wformrefauxant) FROM 1 FOR 5000);

--      IF (wformref <> '') THEN
--         wformref = SUBSTRING((wformref||'. ') FROM 1 FOR 5000) ;

      IF (wformref = '') THEN
      wformref = SUBSTRING((wformref||wformrefant) FROM 1 FOR 5000);

--      IF (wformval <> '') THEN
--         wformval = SUBSTRING((wformval||'. ') FROM 1 FOR 5000);

      IF (wformval = '') THEN
      wformval = SUBSTRING((wformval||wformvalant) FROM 1 FOR 5000);

      -- Converte horas e tipo de referência da verba é Horas
      IF (UPPER(whoremp) = 'TRUE' AND wtiporefver = 1 AND wrefvsumant > 0) THEN
         BEGIN
           -- Converte a referencia atual de Horas para Valor
           wfracao      = wrefvsumant - CAST((wrefvsumant - 0.5) AS INTEGER);
           IF (wrefvsumant > 0) THEN
              BEGIN
                wrefvsumant = wrefvsumant - wfracao;
                wfracao     = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                wrefvsumant = wrefvsumant + wfracao;
              END

           -- Converte a soma atual de Horas para Valor
           wfracao  = wrefvsum - CAST((wrefvsum - 0.5) AS INTEGER);
           IF (wrefvsum > 0) THEN
              BEGIN
                wrefvsum = wrefvsum - wfracao;
                wfracao  = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                wrefvsum = wrefvsum + wfracao;
              END

           -- Soma os VALORES
           wrefvsum = wrefvsum +  wrefvsumant;

           -- Converte o resultado novamente em Horas
           wfracao  = wrefvsum - CAST((wrefvsum - 0.5) AS INTEGER);
           IF (wrefvsum > 0) THEN
              BEGIN
                wrefvsum = wrefvsum - wfracao;
                wfracao  = CAST((wfracao / 100 * 60) AS NUMERIC(15,2));
                wrefvsum = wrefvsum + wfracao;
              END
         END
      ELSE
         wrefvsum = wrefvsum + wrefvsumant;

      wrefauxvsum = wrefauxvsum + wrefauxvsumant;

      IF (wrefvmax < wrefvsumant) THEN
         wrefvmax    = wrefvsumant;

      IF (wrefauxvmax < wrefauxvsumant) THEN
         wrefauxvmax = wrefauxvsumant;

      wvalv       = wvalv + wvalvant;
      wvaliv      = wvaliv + wvalivant;

      wigref      = wigrefant;
      wigrefaux   = wigrefauxant;
      wigval      = wigvalant;
      worverba    = worverbaant;
      waltint     = waltintant;
    END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wveratu <> 0) THEN
     BEGIN
       BDCODEMP        = wempatu;
       BDCODCOL        = wcolatu;
       BDREFFN         = wrefatu;
       BDCODVER        = wveratu;
       BDCOMPESP       = wcompesp;
       BDFORMREFAUX    = wformrefaux;
       BDFORMREF       = wformref;
       BDFORMVAL       = wformval;
       BDREFVFN_SUM    = wrefvsum;
       BDREFAUXVFN_SUM = wrefauxvsum;
       BDREFVFN_MAX    = wrefvmax;
       BDREFAUXVFN_MAX = wrefauxvmax;
       BDVALVFN        = wvalv;
       BDVALVIFN       = wvaliv;
       BDIGNREFVFN     = wigref;
       BDIGNREFAVFN    = wigrefaux;
       BDIGNVALVFN     = wigval;
       BDORVERBA       = worverba;
       BDALTINT        = waltint;
       SUSPEND;
     END
END^


/* Restore proc. body: SP_VRHF_UNION_INT_INTTOM_MES */
create or alter procedure SP_VRHF_UNION_INT_INTTOM_MES (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRCONTRATO integer,
    PRANOMES integer,
    PRMOSTRARCLAVERBA integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDCODCONTTI integer,
    BDCODVER integer,
    BDCLAVER varchar(20),
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDREFVFN_SUM numeric(15,6),
    BDREFAUXVFN_SUM numeric(15,6),
    BDREFVFN_MAX numeric(15,6),
    BDREFAUXVFN_MAX numeric(15,6),
    BDVALVFN numeric(15,6),
    BDVALVIFN numeric(15,6),
    BDIGNREFVFN DM_BOOLEAN,
    BDIGNREFAVFN DM_BOOLEAN,
    BDIGNVALVFN DM_BOOLEAN,
    BDORVERBA integer,
    BDALTINT boolean)
as
declare variable WSQL varchar(32700);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WVERATU integer;
declare variable WCLAVERATU varchar(20);
declare variable WCONTTIATU integer;
declare variable WHOREMP DM_BOOLEAN;
declare variable WTIPOREFVER integer;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREFFN integer;
declare variable WCODVER integer;
declare variable WCLAVER varchar(20);
declare variable WCODCONTTI integer;
declare variable WCOMPESP varchar(300);
declare variable WFORMREFAUX varchar(5000);
declare variable WFORMREF varchar(5000);
declare variable WFORMVAL varchar(5000);
declare variable WREFVSUM numeric(15,6);
declare variable WREFAUXVSUM numeric(15,6);
declare variable WREFVMAX numeric(15,6);
declare variable WREFAUXVMAX numeric(15,6);
declare variable WVALV numeric(15,6);
declare variable WVALIV numeric(15,6);
declare variable WIGREF DM_BOOLEAN;
declare variable WIGREFAUX DM_BOOLEAN;
declare variable WIGVAL DM_BOOLEAN;
declare variable WORVERBA integer;
declare variable WCOMPESPANT varchar(300);
declare variable WFORMREFAUXANT varchar(5000);
declare variable WFORMREFANT varchar(5000);
declare variable WFORMVALANT varchar(5000);
declare variable WREFVSUMANT numeric(15,6);
declare variable WREFAUXVSUMANT numeric(15,6);
declare variable WVALVANT numeric(15,6);
declare variable WVALIVANT numeric(15,6);
declare variable WIGREFANT DM_BOOLEAN;
declare variable WIGREFAUXANT DM_BOOLEAN;
declare variable WIGVALANT DM_BOOLEAN;
declare variable WORVERBAANT integer;
declare variable WFRACAO numeric(15,6);
declare variable WALTINT boolean;
declare variable WALTINTANT boolean;
BEGIN
  wsql = 'SELECT '||
           'FOL.BDCODEMP, '||
           'FOL.BDCODCOL, '||
           'FOL.BDREFFN, '||
           'FOL.BDCODCONTTI, '||
           'FOL.BDCODVER, ' ;
  if (PRMOSTRARCLAVERBA = 1) then
     wsql = wsql || 'VERB.BDCLAVER, ';
  else
     wsql = wsql || ''''' BDCLAVER, ';
  wsql = wsql ||
           'FOL.BDCOMPESP, '||
           'FOL.BDFORMREFAUX, '||
           'FOL.BDFORMREF, '||
           'FOL.BDFORMVAL, '||
           'FOL.BDREFVFN, '||
           'FOL.BDREFAUXVFN, '||
           'FOL.BDVALVFN, '||
           'FOL.BDVALIFN, '||
           'FOL.BDIGNREFVFN, '||
           'FOL.BDIGNREFAVFN, '||
           'FOL.BDIGNVALVFN, '||
           'FOL.BDORVERBAFN, '||
           'FOL.BDALTINT, '||
           'EMPCALC.BDREFHOREMP, '||
           'VERREF.BDTIPOREFVER '||
         'FROM (';

  wsql = wsql||'SELECT '||
           'FN.BDCODEMP, '||
           'FN.BDCODCOL, '||
           'FN.BDREFFN, '||
           'FN.BDCODCONTTI, '||
           'FN.BDCODVER, '||
           'FN.BDCOMPESP, '||
           'FN.BDFORMREFAUX, '||
           'FN.BDFORMREF, '||
           'FN.BDFORMVAL, '||
           'FN.BDREFVFN, '||
           'FN.BDREFAUXVFN, '||
           'FN.BDVALVFN, '||
           'FN.BDVALIFN, '||
           'FN.BDIGNREFVFN, '||
           'FN.BDIGNREFAVFN, '||
           'FN.BDIGNVALVFN, '||
           'FN.BDORVERBAFN, '||
           'FN.BDALTINT '||
         'FROM '||
           'VRHF_EMP_TVERBAINT FN ';

  wsql = wsql||
         'where FN.BDREFFN = '||pranomes;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wsql = wsql||' and '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       if (coalesce(prcontrato, 0) <> 0) then
          wsql = wsql||' and FN.BDCODCONTTI = '||prcontrato;
     END

  wsql = wsql||' union all ';

  wsql = wsql||'SELECT '||
           'FN.BDCODEMP, '||
           'FN.BDCODCOL, '||
           'FN.BDREFTOMADOR, '||
           'FN.BDCODCONTTI,'||
           'FN.BDCODVER, '||
           'FN.BDCOMPESP, '||
           'FN.BDFORMREFAUX, '||
           'FN.BDFORMREF, '||
           'FN.BDFORMVAL, '||
           'FN.BDREFVFT, '||
           'FN.BDREFAUXVFT, '||
           'FN.BDVALVFT, '||
           'FN.BDVALIFT, '||
           'FN.BDIGNREFVFT, '||
           'FN.BDIGNREFAVFT,'||
           'FN.BDIGNVALVFT, '||
           'FN.BDORVERBAFT, '||
           'FN.BDALTINT '||
         'FROM '||
           'VRHF_EMP_TVERBATOMINT FN '||
         'where FN.BDREFTOMADOR = '||pranomes;

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     BEGIN
       wsql = wsql||' and '||prcodemp;

       IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
          wsql = wsql||' and '||prcodcol;

       if (coalesce(prcontrato, 0) <> 0) then
          wsql = wsql||' and FN.BDCODCONTTI = '||prcontrato;
     END

  wsql = wsql||') FOL '||
         'left outer join VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FOL.BDCODVER) '||
         '   and VERREF.BDREFVER =   ' ||
         '      COALESCE((SELECT FIRST 1 x.BDREFVER FROM VRH_BASE_TVERBAS_REF x ' ||
         '                WHERE x.bdcodver = FOL.bdcodver ' ||
         '                  AND X.BDREFVER <= ' || pranomes ||
         '                  ORDER BY x.BDREFVER DESC), ' ||
         '              (SELECT FIRST 1 x.BDREFVER FROM VRH_BASE_TVERBAS_REF x ' ||
         '                WHERE x.bdcodver = FOL.bdcodver ' ||
         '                ORDER BY x.BDREFVER)) ' ;

  if (PRMOSTRARCLAVERBA = 1) then
     wsql = wsql||
         'JOIN VRH_BASE_TVERBAS VERB ON (VERB.BDCODVER = FOL.BDCODVER) ';

  wsql = wsql||
         'left outer join VRHF_BASE_TEMPCALC EMPCALC on (EMPCALC.BDCODEMP = FOL.BDCODEMP) '||
         '   and EMPCALC.BDREFEMP =   ' ||
         '      COALESCE((SELECT FIRST 1 x.BDREFEMP FROM VRHF_BASE_TEMPCALC x ' ||
         '                WHERE x.bdcodemp = FOL.bdcodemp ' ||
         '                  AND X.BDREFEMP <= ' || pranomes ||
         '                  ORDER BY x.BDREFEMP DESC), ' ||
         '              (SELECT FIRST 1 x.BDREFEMP FROM VRHF_BASE_TEMPCALC x ' ||
         '                WHERE x.bdcodemp = FOL.bdcodemp ' ||
         '                ORDER BY x.BDREFEMP)) ' ||

         ' order by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDCODCONTTI, FOL.BDCODVER';

  wempatu     = 0;
  wcolatu     = 0;
  wrefatu     = 0;
  wveratu     = 0;
  wclaveratu  = '';
  wconttiatu  = 0;
  wcompesp    = '';
  wformrefaux = '';
  wformref    = '';
  wformval    = '';
  wrefvsum    = 0;
  wrefauxvsum = 0;
  wrefvmax    = 0;
  wrefauxvmax = 0;
  wvalv       = 0;
  wvaliv      = 0;
  wigref      = '';
  wigrefaux   = '';
  wigval      = '';
  worverba    = -1;
  waltint     = false;

  FOR EXECUTE STATEMENT wsql INTO
    :wcodemp,
    :wcodcol,
    :wreffn,
    :wcodcontti,
    :wcodver,
    :wclaver,
    :wcompespant,
    :wformrefauxant,
    :wformrefant,
    :wformvalant,
    :wrefvsumant,
    :wrefauxvsumant,
    :wvalvant,
    :wvalivant,
    :wigrefant,
    :wigrefauxant,
    :wigvalant,
    :worverbaant,
    :waltintant,
    :whoremp,
    :wtiporefver
  DO
    BEGIN
      IF (wempatu = 0) THEN
         wempatu = wcodemp;

      IF (wcolatu = 0) THEN
         wcolatu = wcodcol;

      IF (wrefatu = 0) THEN
         wrefatu = wreffn;

      IF (wveratu = 0) THEN
         wveratu = wcodver;

      IF (wclaveratu = '') THEN
         wclaveratu = wclaver;

      IF (wconttiatu = 0) THEN
         wconttiatu = wcodcontti;


      IF ((wempatu <> wcodemp) OR (wcolatu <> wcodcol) OR (wrefatu <> wreffn) OR (wveratu <> wcodver) OR (wconttiatu <> wcodcontti)) THEN
         BEGIN
           BDCODEMP        = wempatu;
           BDCODCOL        = wcolatu;
           BDREFFN         = wrefatu;
           BDCODVER        = wveratu;
           BDCLAVER        = wclaveratu;
           BDCODCONTTI     = wconttiatu;
           BDCOMPESP       = wcompesp;
           BDFORMREFAUX    = wformrefaux;
           BDFORMREF       = wformref;
           BDFORMVAL       = wformval;
           BDREFVFN_SUM    = wrefvsum;
           BDREFAUXVFN_SUM = wrefauxvsum;
           BDREFVFN_MAX    = wrefvmax;
           BDREFAUXVFN_MAX = wrefauxvmax;
           BDVALVFN        = wvalv;
           BDVALVIFN       = wvaliv;
           BDIGNREFVFN     = wigref;
           BDIGNREFAVFN    = wigrefaux;
           BDIGNVALVFN     = wigval;
           BDORVERBA       = worverba;
           BDALTINT        = waltint;
           SUSPEND;

           wempatu     = wcodemp;
           wcolatu     = wcodcol;
           wrefatu     = wreffn;
           wveratu     = wcodver;
           wclaveratu  = wclaver;
           wconttiatu  = wcodcontti;
           wcompesp    = '';
           wformrefaux = '';
           wformref    = '';
           wformval    = '';
           wrefvsum    = 0;
           wrefauxvsum = 0;
           wrefvmax    = 0;
           wrefauxvmax = 0;
           wvalv       = 0;
           wvaliv      = 0;
           wigref      = '';
           wigrefaux   = '';
           wigval      = '';
           worverba    = -1;
           waltint     = false;
         END

      IF (wcompesp <> '') THEN
         wcompesp = SUBSTRING((wcompesp||'. ') FROM 1 FOR 300) ;

      wcompesp = SUBSTRING((wcompesp||wcompespant) FROM 1 FOR 300);

      IF (wformrefaux <> '') THEN
         wformrefaux = SUBSTRING((wformrefaux||'. ') FROM 1 FOR 5000) ;

      wformrefaux = SUBSTRING((wformrefaux||wformrefauxant) FROM 1 FOR 5000);

      IF (wformref <> '') THEN
         wformref = SUBSTRING((wformref||'. ') FROM 1 FOR 5000) ;

      wformref = SUBSTRING((wformref||wformrefant) FROM 1 FOR 5000);

      IF (wformval <> '') THEN
         wformval = SUBSTRING((wformval||'. ') FROM 1 FOR 5000) ;

      wformval = SUBSTRING((wformval||wformvalant) FROM 1 FOR 5000);

      -- Converte horas e tipo de referência da verba é Horas
      IF (UPPER(whoremp) = 'TRUE' AND wtiporefver = 1 AND wrefvsumant > 0) THEN
         BEGIN
           -- Converte a referencia atual de Horas para Valor
           wfracao      = wrefvsumant - CAST((wrefvsumant - 0.5) AS INTEGER);
           IF (wrefvsumant > 0) THEN
              BEGIN
                wrefvsumant = wrefvsumant - wfracao;
                wfracao     = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                wrefvsumant = wrefvsumant + wfracao;
              END

           -- Converte a soma atual de Horas para Valor
           wfracao  = wrefvsum - CAST((wrefvsum - 0.5) AS INTEGER);
           IF (wrefvsum > 0) THEN
              BEGIN
                wrefvsum = wrefvsum - wfracao;
                wfracao  = CAST((wfracao / 60 * 100) AS NUMERIC(15,2));
                wrefvsum = wrefvsum + wfracao;
              END

           -- Soma os VALORES
           wrefvsum = wrefvsum +  wrefvsumant;

           -- Converte o resultado novamente em Horas
           wfracao  = wrefvsum - CAST((wrefvsum - 0.5) AS INTEGER);
           IF (wrefvsum > 0) THEN
              BEGIN
                wrefvsum = wrefvsum - wfracao;
                wfracao  = CAST((wfracao / 100 * 60) AS NUMERIC(15,2));
                wrefvsum = wrefvsum + wfracao;
              END
         END
      ELSE
         wrefvsum = wrefvsum + wrefvsumant;

      wrefauxvsum = wrefauxvsum + wrefauxvsumant;

      IF (wrefvmax < wrefvsumant) THEN
         wrefvmax    = wrefvsumant;

      IF (wrefauxvmax < wrefauxvsumant) THEN
         wrefauxvmax = wrefauxvsumant;

      wvalv       = wvalv + wvalvant;
      wvaliv      = wvaliv + wvalivant;

      wigref      = wigrefant;
      wigrefaux   = wigrefauxant;
      wigval      = wigvalant;
      worverba    = worverbaant;
      waltint     = waltintant;
    END

  IF (wempatu <> 0 AND wcolatu <> 0 AND wrefatu <> 0 AND wveratu <> 0 and wconttiatu <> 0) THEN
     BEGIN
       BDCODEMP        = wempatu;
       BDCODCOL        = wcolatu;
       BDREFFN         = wrefatu;
       BDCODVER        = wveratu;
       BDCLAVER        = wclaveratu;
       BDCODCONTTI     = wconttiatu;
       BDCOMPESP       = wcompesp;
       BDFORMREFAUX    = wformrefaux;
       BDFORMREF       = wformref;
       BDFORMVAL       = wformval;
       BDREFVFN_SUM    = wrefvsum;
       BDREFAUXVFN_SUM = wrefauxvsum;
       BDREFVFN_MAX    = wrefvmax;
       BDREFAUXVFN_MAX = wrefauxvmax;
       BDVALVFN        = wvalv;
       BDVALVIFN       = wvaliv;
       BDIGNREFVFN     = wigref;
       BDIGNREFAVFN    = wigrefaux;
       BDIGNVALVFN     = wigval;
       BDORVERBA       = worverba;
       BDALTINT        = waltint;
       SUSPEND;
     END
END^

create or alter procedure VTPO_INDICADOR_TEMPO (
    PRCODEMP integer,
    PRCODSIS integer,
    PRDATAINI date,
    PRDATAFIN date,
    PRREF integer = null,
    PRLISTARTEMPOZERADO boolean = false,
    PRTIPOREGISTRO integer = -1,
    PRRETORNOVASIO boolean = false)
returns (
    BDCODEMP integer,
    BDTEMPO_LIQUIDO integer,
    BDTEMPO_SOBREPOSTO integer,
    BDDATAINI date,
    BDHORAINI time,
    BDDATAFIN date,
    BDHORAFIN time,
    BDTEMPO_BRUTO integer,
    BDCODUSU integer,
    BDCODSIS integer,
    BDDESCTIPOREGISTRO varchar(10),
    BDDESCRICAO varchar(200),
    BDTIPOREGISTRO varchar(10),
    BDTIPOLAN integer,
    BDCODATI integer,
    BDCODTELASIS integer)
as
declare variable WCODEMP integer;
declare variable WDATAINIANT date;
declare variable WHORAINIANT time;
declare variable WDATAFINANT date;
declare variable WHORAFINANT time;
declare variable WCODUSUANT integer;
declare variable WSQL varchar(2000);
declare variable WCODSISANT integer;
declare variable WOCIOSO integer;
declare variable WCODATI integer;
declare variable WCODTELASIS integer;
declare variable WNORMAL integer;
begin
  wdatainiant = null;
  whorainiant = '00:00:00';
  wdatafinant = null;
  whorafinant = '00:00:00';
  wcodemp = 0;
  wcodusuant = -1;
  wcodsisant = -1;

  wsql = 'SELECT ati.BDCODEMP, ATI.bdcodusu, ATI.bdcodsis, ATI.BDDATAINI, ATI.BDHORAINI, ATI.BDDATAFIN, ATI.BDHORAFIN, ';
  wsql = wsql||'datediff(second, cast(BDDATAINI||'||''''||' '||''''||'||BDHORAINI as timestamp), cast(BDDATAFIN||'||''''||' '||''''||'||BDHORAFIN as timestamp)) as BDSECONDSDIFF,';
  wsql = wsql||'ATI.BDDESCTIPOREGISTRO,';
  wsql = wsql||'case when ati.bdcodtelasis is null then atiexe.bddescricao else coalesce(tela.bdcaptiontela,tela.bdnometela) end as BDDESCRICAO, ';
  wsql = wsql||'case when(coalesce(ATIEXE.BDTEMPOOCIOSO,'||'''FALSE'''||')='||'''TRUE'''||')then '||'''OCIOSO''';
  wsql = wsql||' when(ATI.BDCODATI is not null AND ATI.BDCODTELASIS is null) then '||'''ATIVIDADE''';
  wsql = wsql||' when(ATI.BDCODTELASIS is not null) then '||'''PROCESSO''';
  wsql = wsql||' else '||'''OUTRO'''||' end as bdtiporegistro ';
  wsql = wsql||',ATI.BDTIPOREGISTRO as BDTIPOLAN ';
  wsql = wsql||',ATI.bdcodati, ATI.bdcodtelasis ';
  wsql = wsql||'FROM VTPO_ATIVIDADE_EXE_REGISTRO ATI ';
  wsql = wsql||'LEFT JOIN vtpo_atividade_exe ATIEXE on (ATIEXE.bdcodati=ATI.BDCODATI) ';
  wsql = wsql||'LEFT JOIN TTELA_SISTEMA TELA on (TELA.BDCODTELASIS=ATI.BDCODTELASIS) ';
  -- Filtro por usuário
  execute statement 'Select first 1 bdcodusu from TMP_TUSUARIO' into :WCODUSUANT;
  if (wcodusuant is not null) then
     wsql = wsql||'INNER JOIN TMP_TUSUARIO USU ON (USU.BDCODUSU = ATI.BDCODUSU) ';
  -- Desempenho - listar empresas inseridas na tabela temporária
  if (prcodemp is null) then
     wsql = wsql||'join tmp_empresas_select EMP on(emp.bdcodemp=coalesce(ati.bdcodemp,0))';
  -- filtro de processos e atividades
  if (prcodsis is null) then
     wsql = wsql||'JOIN TMP_TSISTEMA_SELECT SIS on(SIS.BDCODSIS=ATI.BDCODSIS)';
  -- quando inserido em um SQL que use competência inves de datas
  if (prref is not null) then
  begin
    wsql = wsql||'where((extract(year from bddataini)||lpad(extract(month from bddataini),2,0)='||prref;
    wsql = wsql||')and(extract(year from bddatafin)||lpad(extract(month from bddatafin),2,0)<='||prref||'))';
  end
  else
  begin
    wsql = wsql||'where bddataini >= coalesce('''||:prdataini||''', current_date)';
    wsql = wsql||'and bddatafin <= coalesce('''||:prdatafin||''', current_date)';
  end
  -- quando inserido em um SQL com tabela que tenham o código de empresa
  if (prcodemp is not null) then
     wsql = wsql||'and(ATI.BDCODEMP='||prcodemp||')';
  -- Tipo de registro (0 - Automático, 1 - Manual, 2 - Importado)
  if (coalesce(prtiporegistro,0) >= 0) then
     wsql = wsql||'and(ATI.BDTIPOREGISTRO='||prtiporegistro||')';
  -- Filtro por atividades/telas
  select first 1 bdcodati from TMP_VTPO_ATIVIDADE_EXE_SELECT order by bdcodati into :wcodati;
  select first 1 bdcodtelasis from TMP_TTELA_SISTEMA_SELECT into :wcodtelasis;
  if ((wcodati is not null) or (wcodtelasis is not null)) then
     wsql = wsql||' and(';
  if (wcodati is not null) then
     --wsql = wsql||'(coalesce(ATI.BDCODATI,0)IN(SELECT BDCODATI FROM TMP_VTPO_ATIVIDADE_EXE_SELECT))';
     wsql = wsql||'(ATI.BDCODATI IS NOT NULL AND ATI.BDCODATI IN(SELECT BDCODATI FROM TMP_VTPO_ATIVIDADE_EXE_SELECT WHERE BDCODATI <> -1))';
  if ((wcodati is not null) and (wcodtelasis is not null)) then
     wsql = wsql||' or ';
  if (wcodtelasis is not null) then
     --wsql = wsql||'(coalesce(ATI.BDCODTELASIS,0)IN(SELECT BDCODTELASIS FROM TMP_TTELA_SISTEMA_SELECT))';
     wsql = wsql||'(ATI.BDCODTELASIS IS NOT NULL AND ATI.BDCODTELASIS IN(SELECT BDCODTELASIS FROM TMP_TTELA_SISTEMA_SELECT WHERE BDCODTELASIS <> -1))';
  if ((wcodati is not null) or (wcodtelasis is not null)) then
     wsql = wsql||')';
  -- quando houver filtro por sistema
  if (prcodsis is not null) then
     wsql = wsql||'and(ATI.bdcodsis='||prcodsis||')';
  -- Desempenho - listar apenas tempos maior que zero
  if (prlistartempozerado) then
  begin
   --wsql = wsql||'and(DATEDIFF(SECOND FROM cast((cast(bddataini as date) + cast(bdhoraini as time)) as timestamp) TO ';
    --wsql = wsql||'cast((cast(bddatafin as date) + cast(bdhorafin as time)) as timestamp))>0)';
    WSQL = WSQL || 'AND (DATEDIFF(SECOND, CAST(BDDATAINI||'' ''||BDHORAINI AS TIMESTAMP), CAST(BDDATAFIN||'' ''||BDHORAFIN AS TIMESTAMP)) > 0) ';
  end

  -- Verifica quantos ociosos e quanto normais existem
  select count(case when(coalesce(ati.bdtempoocioso,'FALSE')='FALSE')then 1 end) BDNORMAL,
         count(case when(coalesce(ati.bdtempoocioso,'FALSE')='TRUE')then 1 end) BDOCIOSO
  from TMP_VTPO_ATIVIDADE_EXE_SELECT x
  join vtpo_atividade_exe ati on(ati.bdcodati=x.bdcodati)
  into :wnormal, :wocioso;
  -- apenas normais
  if ((coalesce(wnormal,0) > 0) and (coalesce(wocioso,0) = 0)) then
     wsql = wsql||'and(UPPER(COALESCE(ATIEXE.BDTEMPOOCIOSO,'''||'FALSE'||'''))='||'FALSE'||')';
  else
  -- apenas ociosos
  if ((coalesce(wocioso,0) > 0) and (coalesce(wnormal,0) = 0)) then
     wsql = wsql||'and(UPPER(COALESCE(ATIEXE.BDTEMPOOCIOSO,'''||'FALSE'||'''))='||'TRUE'||')';


--  wsql = wsql||'order by BDCODEMP, bdcodusu, ATI.bdcodsis, BDDATAINI, BDHORAINI';
  wsql = wsql||'order by ATI.bdcodusu, ATI.BDDATAINI, ATI.BDHORAINI';

  for execute statement wsql
      into :bdCODEMP, :bdcodusu, :bdcodsis, :bdDATAINI, :bdHORAINI, :bdDATAFIN, :bdHORAFIN,
           :bdtempo_bruto, :BDDESCTIPOREGISTRO, :BDDESCRICAO, :bdtiporegistro, :bdtipolan,
           :bdcodati, :bdcodtelasis do
  begin
    if (wdatainiant is null) then
       wdatainiant = bddataini;
    if (wdatafinant is null) then
       wdatafinant = bddatafin;

    -- novo registro caso mude de usuário
    if (coalesce(bdcodusu,0) <> coalesce(wcodusuant,0)) then -- Gilberto - 02/06/2026 - #245880 - Distorção apenas para usuários
    begin
      bdtempo_liquido = bdtempo_bruto;
      bdtempo_sobreposto = 0;
      wdatainiant = bddataini;
      whorainiant = bdhoraini;
      wdatafinant = bddatafin;
      whorafinant = bdhorafin;
    end
    else
    --if ((bddataini + bdhoraini) >= (wdatafinant + whorafinant)) then
    IF (CAST(BDDATAINI || ' ' || BDHORAINI AS TIMESTAMP) >= CAST(WDATAFINANT || ' ' || WHORAFINANT AS TIMESTAMP)) THEN
    begin
      bdtempo_liquido = bdtempo_bruto;
      bdtempo_sobreposto = 0;
      wdatainiant = bddataini;
      whorainiant = bdhoraini;
      wdatafinant = bddatafin;
      whorafinant = bdhorafin;
    end
    else
    --if (((bddataini + bdhoraini) > (wdatainiant + whorainiant)) and
     --((bddatafin + bdhorafin) > (wdatafinant + whorafinant))) then
    IF ((CAST(BDDATAINI || ' ' || BDHORAINI AS TIMESTAMP) > CAST(WDATAINIANT || ' ' || WHORAINIANT AS TIMESTAMP)) AND
       (CAST(BDDATAFIN || ' ' || BDHORAFIN AS TIMESTAMP) > CAST(WDATAFINANT || ' ' || WHORAFINANT AS TIMESTAMP))) THEN
    begin
     -- bdtempo_sobreposto = DATEDIFF(SECOND FROM cast((cast(bddataini as date) + cast(bdhoraini as time)) as timestamp) TO
      --                                          cast((cast(wdatafinant as date) + cast(whorafinant as time)) as timestamp));

      BDTEMPO_SOBREPOSTO = DATEDIFF(SECOND, CAST(BDDATAINI || ' ' || BDHORAINI AS TIMESTAMP), CAST(WDATAFINANT || ' ' || WHORAFINANT AS TIMESTAMP));

      bdtempo_liquido = bdtempo_bruto - bdtempo_sobreposto;
      wdatafinant = bddatafin;
      whorafinant = bdhorafin;
    end
    else
   -- if (((bddatafin + bdhorafin) <= (wdatafinant + whorafinant))or
   --     ((bddatafin + bdhorafin) >= (wdatafinant + whorafinant))) then
    begin
      bdtempo_liquido = 0;
      bdtempo_sobreposto = bdtempo_bruto;
    end

    wcodemp = bdcodemp;
    wcodusuant = bdcodusu;
    wcodsisant = bdcodsis;
    suspend;
  end
  
  -- Gilberto - 11/02/2026 - #237062
  if ((bdcodemp is null) and (prretornovasio)) then
  begin
    bdcodemp = prcodemp;
    bdcodusu = null;
    bdcodsis = PRCODSIS;
    bdDATAINI = prdataini;
    bdHORAINI = null;
    bdDATAFIN = prdataini;
    bdHORAFIN = null;
    bdtempo_bruto = 0;
    BDDESCTIPOREGISTRO = null;
    BDDESCRICAO = null;
    bdtiporegistro = 'Outro';
    bdtipolan = 0;
    bdcodati = null;
    bdcodtelasis = null;
    suspend;
  end
end^

create or alter procedure VTPO_TEMPO_USUARIO (
    PRCODEMP integer,
    PRDATAINI date,
    PRDATAFIN date,
    PRREF integer = null)
returns (
    BDCODEMP integer,
    BDTEMPO_LIQUIDO integer,
    BDTEMPO_SOBREPOSTO integer,
    BDDATAINI date,
    BDHORAINI time,
    BDDATAFIN date,
    BDHORAFIN time,
    BDTEMPO_BRUTO integer,
    BDCODUSU integer,
    BDCODSIS integer,
    BDDESCTIPOREGISTRO varchar(10),
    BDDESCRICAO varchar(200),
    BDTIPOREGISTRO varchar(10),
    BDTIPOLAN integer,
    BDCODATI integer,
    BDCODTELASIS integer)
as
declare variable WDATAINIANT date;
declare variable WHORAINIANT time;
declare variable WDATAFINANT date;
declare variable WHORAFINANT time;
declare variable WCODUSUANT integer;
declare variable WTEM_USU integer;
begin
  wdatainiant = null;
  whorainiant = '00:00:00';
  wdatafinant = null;
  whorafinant = '00:00:00';
  wcodusuant = -1;

  -- Verifica se há dados na tabela temporária de usuários para uso como filtro/join
  select count(bdcodusu) from TMP_TUSUARIO into :wtem_usu;

  for
    select
        ATI.BDCODEMP,
        ATI.BDCODUSU,
        ATI.BDCODSIS,
        ATI.BDDATAINI,
        ATI.BDHORAINI,
        ATI.BDDATAFIN,
        ATI.BDHORAFIN,
        datediff(second,
            cast(ATI.BDDATAINI || ' ' || ATI.BDHORAINI as timestamp),
            cast(ATI.BDDATAFIN || ' ' || ATI.BDHORAFIN as timestamp)
        ) as BDSECONDSDIFF,
        ATI.BDDESCTIPOREGISTRO,
        case
            when ATI.BDCODTELASIS is null then ATIEXE.BDDESCRICAO
            else coalesce(TELA.BDCAPTIONTELA, TELA.BDNOMETELA)
        end as BDDESCRICAO,
        case
            when (coalesce(ATIEXE.BDTEMPOOCIOSO,'FALSE') = 'TRUE')  then 'OCIOSO'
            when (ATI.BDCODATI    is not null and ATI.BDCODTELASIS is null) then 'ATIVIDADE'
            when (ATI.BDCODTELASIS is not null)                             then 'PROCESSO'
            else 'OUTRO'
        end as BDTIPOREGISTRO,
        ATI.BDTIPOREGISTRO as BDTIPOLAN,
        ATI.BDCODATI,
        ATI.BDCODTELASIS
    from VTPO_ATIVIDADE_EXE_REGISTRO ATI
    left join VTPO_ATIVIDADE_EXE         ATIEXE on (ATIEXE.BDCODATI    = ATI.BDCODATI)
    left join TTELA_SISTEMA              TELA   on (TELA.BDCODTELASIS  = ATI.BDCODTELASIS)
    -- Join com usuários: ativo somente quando há dados na tabela temporária
    left join TMP_TUSUARIO               USU    on (USU.BDCODUSU = ATI.BDCODUSU)
    -- Join com empresas: ativo somente quando prcodemp é nulo (usa a tabela temporária)
    left join tmp_empresas_select        EMP    on (:prcodemp is null
                                                    and EMP.BDCODEMP = coalesce(ATI.BDCODEMP, 0))
    where
        -- Filtro de usuário: exige match quando a tabela temporária tem dados
        (:wtem_usu = 0 or USU.BDCODUSU is not null)
        -- Filtro de empresa via tabela temporária (quando prcodemp é nulo)
        and (:prcodemp is not null or EMP.BDCODEMP is not null)
        -- Filtro por competência (quando prref informado) ou por intervalo de datas
        and (
            (:prref is not null
             and (extract(year from ATI.BDDATAINI) || lpad(extract(month from ATI.BDDATAINI), 2, 0)) = :prref
             and (extract(year from ATI.BDDATAFIN) || lpad(extract(month from ATI.BDDATAFIN), 2, 0)) <= :prref
            )
            or
            (:prref is null
             and ATI.BDDATAINI >= coalesce(:prdataini, current_date)
             and ATI.BDDATAFIN <= coalesce(:prdatafin, current_date)
            )
        )
        -- Filtro de empresa quando informado diretamente
        and (:prcodemp is null or ATI.BDCODEMP = :prcodemp)

    order by ATI.BDCODUSU, ATI.BDDATAINI, ATI.BDHORAINI, ATI.BDCHAVE, ATI.BDCODEMP

  into :bdCODEMP, :bdcodusu, :bdcodsis, :bdDATAINI, :bdHORAINI, :bdDATAFIN, :bdHORAFIN,
       :bdtempo_bruto, :BDDESCTIPOREGISTRO, :BDDESCRICAO, :bdtiporegistro, :bdtipolan,
       :bdcodati, :bdcodtelasis
  do
  begin
    if (wdatainiant is null) then
       wdatainiant = bddataini;
    if (wdatafinant is null) then
       wdatafinant = bddatafin;

    -- Novo registro ao mudar de usuário: reseta a janela de sobreposição
    if (coalesce(bdcodusu,0) <> coalesce(wcodusuant,0)) then
    begin
      bdtempo_liquido    = bdtempo_bruto;
      bdtempo_sobreposto = 0;
      wdatainiant  = bddataini;
      whorainiant  = bdhoraini;
      wdatafinant  = bddatafin;
      whorafinant  = bdhorafin;
    end
    else
    -- Sem sobreposição: o registro começa depois do fim do anterior
    if ((bddataini + bdhoraini) >= (wdatafinant + whorafinant)) then
    begin
      bdtempo_liquido    = bdtempo_bruto;
      bdtempo_sobreposto = 0;
      wdatainiant  = bddataini;
      whorainiant  = bdhoraini;
      wdatafinant  = bddatafin;
      whorafinant  = bdhorafin;
    end
    else
    -- Sobreposição parcial à direita: o registro começa dentro do anterior e termina além
    if (((bddataini + bdhoraini) > (wdatainiant + whorainiant)) and
        ((bddatafin + bdhorafin) > (wdatafinant + whorafinant))) then
    begin
      bdtempo_sobreposto = DATEDIFF(SECOND
                             FROM cast((cast(bddataini  as date) + cast(bdhoraini  as time)) as timestamp)
                             TO   cast((cast(wdatafinant as date) + cast(whorafinant as time)) as timestamp));
      bdtempo_liquido = bdtempo_bruto - bdtempo_sobreposto;
      wdatafinant = bddatafin;
      whorafinant = bdhorafin;
    end
    else
    -- Sobreposição total: o registro está completamente dentro da janela do anterior
    if (((bddatafin + bdhorafin) <= (wdatafinant + whorafinant)) or
        ((bddatafin + bdhorafin) >= (wdatafinant + whorafinant))) then
    begin
      bdtempo_liquido    = 0;
      bdtempo_sobreposto = bdtempo_bruto;
    end

    wcodusuant = bdcodusu;
    suspend;
  end
end^

create or alter procedure VTPO_CONSULTA_TEMPOS (
    PREMPRESAS DM_LISTA,
    PRSISTEMAS DM_LISTA,
    PRUSUARIOS DM_LISTA,
    PRPROCESSOS DM_LISTA,
    PRDATAINI date,
    PRDATAFIM date,
    PRFIELDS varchar(500),
    PRREPORT integer,
    PRORDER integer = 0,
    PRVINCULOEMPRESA integer = 1,
    PRMANTIP integer = 0,
    PRATIVIDADES DM_LISTA = '')
returns (
    BDCODEMP integer,
    BDNOMEMP varchar(120),
    BDCODSIS integer,
    BDORDEMSCI integer,
    BDDESCSIS varchar(60),
    BDCODUSU integer,
    BDNOMCOMPLUSU varchar(60),
    BDCODTELASIS integer,
    BDCAPTIONTELA varchar(170),
    BDQUANTIDADE integer,
    BDTEMPOATIVO timestamp,
    BDTEMPOINATIVO timestamp,
    BDPERCENTUAL double precision,
    BDTEMPOMEDIO timestamp,
    BDTIPOREGISTRO integer)
as
declare variable WSQL DM_MAXVARCHAR;
declare variable WFILTERLOG DM_MAXVARCHAR;
declare variable WFILTERLAN DM_MAXVARCHAR = '';
declare variable WDESCTOTAL varchar(6) = 'Total ';
declare variable WCODEMP integer;
declare variable WCODSIS integer;
declare variable WORDEMSCI integer;
declare variable WCODUSU integer;
declare variable WCODTELASIS integer;
declare variable WCODEMP_AUX integer = -1;
declare variable WCODSIS_AUX integer = -1;
declare variable WCODUSU_AUX integer = -1;
declare variable WCODTELASIS_AUX integer = -1;
declare variable WNOMEMP varchar(120);
declare variable WDESCSIS varchar(60);
declare variable WNOMCOMPLUSU varchar(60);
declare variable WCAPTIONTELA varchar(170);
declare variable WNOMEMP_AUX varchar(120);
declare variable WDESCSIS_AUX varchar(60);
declare variable WNOMCOMPLUSU_AUX varchar(60);
declare variable WCAPTIONTELA_AUX varchar(170);
declare variable WTEMPOATIVO decimal(18,9) = 0;
declare variable WTEMPOATIVOATU decimal(18,9) = 0;
declare variable WTEMPOINATIVO decimal(18,9) = 0;
declare variable WTEMPOINATIVOATU decimal(18,9) = 0;
declare variable WTEMPOATIVOSOMA1 decimal(18,9) = 0;
declare variable WTEMPOATIVOSOMA2 decimal(18,9) = 0;
declare variable WTEMPOATIVOSOMA3 decimal(18,9) = 0;
declare variable WTEMPOATIVOTOTAL decimal(18,9) = 0;
declare variable WTEMPOINATIVOSOMA1 decimal(18,9) = 0;
declare variable WTEMPOINATIVOSOMA2 decimal(18,9) = 0;
declare variable WTEMPOINATIVOSOMA3 decimal(18,9) = 0;
declare variable WTEMPOINATIVOTOTAL decimal(18,9) = 0;
declare variable WQUANTIDADE integer = 0;
declare variable WQUANTIDADEATU integer = 0;
declare variable WQUANTIDADESOMA1 integer = 0;
declare variable WQUANTIDADESOMA2 integer = 0;
declare variable WQUANTIDADESOMA3 integer = 0;
declare variable WQUANTIDADETOTAL integer = 0;
declare variable WCOLUMN1 integer;
declare variable WCOLUMN2 integer;
declare variable WCOLUMN3 integer;
declare variable WCOLUMN4 integer;
declare variable WREPRINTLEVEL integer = 0;
declare variable WSEQEMP integer;
declare variable WSEQSIS integer;
declare variable WSEQUSU integer;
declare variable WSEQTELA integer;
declare variable WSEQUENCE integer;
declare variable WPOSITION integer;
declare variable WLASTLEVEL integer;
declare variable WAUXVARCHAR DM_MAXVARCHAR;
declare variable WFILTERATI DM_MAXVARCHAR;
declare variable WCODATI integer;
declare variable WDESCATI varchar(200);
declare variable WCODATI_AUX integer;
BEGIN
  /*******************************
   BDTIPOREGISTRO:
    0 - Linha de registro comum;
    1 - Cabeçalho dos registros;
    2 - Totalizador dos registros;
  *******************************/

  --Corta os campos extras e retira a ordenação para que seja usado como campos dinâmicos.
  prFields = UPPER(prFields);
  wLastLevel = CHAR_LENGTH(prFields) - CHAR_LENGTH(REPLACE(prFields, ',', '')) +1;
  WHILE (CHAR_LENGTH(prFields) > (CHAR_LENGTH(REPLACE(prFields, ',', '')) + 3)) DO --Somente serão filtradas as 4 primeiras colunas
    prFields = SUBSTRING(prFields FROM 1 FOR CHAR_LENGTH(prFields) -1);

  --Calcula a sequência dos campos.
  wPosition = 1;
  wSeqEmp = CASE WHEN POSITION('BDNOMEMP', UPPER(:prFields)) = 0 THEN CHAR_LENGTH(prFields) ELSE POSITION('BDNOMEMP', UPPER(:prFields)) END;
  wSeqSis = CASE WHEN POSITION('BDDESCSIS', UPPER(:prFields)) = 0 THEN CHAR_LENGTH(prFields) ELSE POSITION('BDDESCSIS', UPPER(:prFields)) END;
  wSeqUsu = CASE WHEN POSITION('BDNOMCOMPLUSU', UPPER(:prFields)) = 0 THEN CHAR_LENGTH(prFields) ELSE POSITION('BDNOMCOMPLUSU', UPPER(:prFields)) END;
  wSeqTela = CASE WHEN POSITION('BDCAPTIONTELA', UPPER(:prFields)) = 0 THEN CHAR_LENGTH(prFields) ELSE POSITION('BDCAPTIONTELA', UPPER(:prFields)) END;
  DELETE FROM LISTA_LANC WHERE BDCODEMP = BDCODEMP;
  INSERT INTO LISTA_LANC (BDCODEMP, BDCHAVE, BDTIPOLANCFILIAL) VALUES (:wSeqEmp, 0, 0);
  INSERT INTO LISTA_LANC (BDCODEMP, BDCHAVE, BDTIPOLANCFILIAL) VALUES (:wSeqSis, 0, 0);
  INSERT INTO LISTA_LANC (BDCODEMP, BDCHAVE, BDTIPOLANCFILIAL) VALUES (:wSeqUsu, 0, 0);
  INSERT INTO LISTA_LANC (BDCODEMP, BDCHAVE, BDTIPOLANCFILIAL) VALUES (:wSeqTela, 0, 0);
  FOR SELECT BDCODEMP FROM LISTA_LANC WHERE BDCODEMP > 0 ORDER BY BDCHAVE INTO :wSequence DO
    BEGIN
      wSeqEmp = CASE WHEN wSeqEmp = wSequence THEN wPosition ELSE wSeqEmp END;
      wSeqSis = CASE WHEN wSeqSis = wSequence THEN wPosition ELSE wSeqSis END;
      wSeqUsu = CASE WHEN wSeqUsu = wSequence THEN wPosition ELSE wSeqUsu END;
      wSeqTela = CASE WHEN wSeqTela = wSequence THEN wPosition ELSE wSeqTela END;
      wPosition = wPosition + 1;
    END
  DELETE FROM LISTA_LANC WHERE BDCODEMP = BDCODEMP;
  SELECT BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTO' INTO :wCodTelaSis;

  --Primeiro crio um filtro padrão para que quando necessite alterar, altere em um único lugar, para que não ocorra erros e esquecimentos nas alterações.
  if (PRMANTIP <> 2) then -- #93513 - Carlos Machado - 03/12/2018
    BEGIN
      IF (TRIM(prDataIni) <> '') THEN
        wFilterLan = wFilterLan||' and (/*DATAINICIAL*/ >= '''||prDataIni||''')';
      IF (TRIM(prDataFim) <> '') THEN
        wFilterLan = wFilterLan||' and (/*DATAFINAL*/ <= '''||prDataFim||''')';
    END
  IF (TRIM(prSistemas) <> '') THEN
    wFilterLan = wFilterLan||' and (/*SISTEMA*/ in ('||prSistemas||'))';
  IF (TRIM(prUsuarios) <> '') THEN
    wFilterLan = wFilterLan||' and (/*USUARIO*/ in ('||prUsuarios||'))';
  IF (TRIM(prProcessos) <> '') THEN
    wFilterLan = wFilterLan||' and (/*PROCESSO*/ in ('||prProcessos||'))';
  if (TRIM(PRATIVIDADES) <> '') then
    wFilterLan = wFilterLan||' and (/*ATIVIDADE*/ in ('||PRATIVIDADES||'))';

  if (PRMANTIP = 2) then
    BEGIN
      IF (TRIM(prEmpresas) <> '') THEN
        wFilterLan = wFilterLan||' and (BDCODEMP in ('||prEmpresas||'))';
    END
  ELSE
    BEGIN
      IF (TRIM(prEmpresas) <> '') THEN
        wFilterLan = wFilterLan||' and (/*EMPRESA*/ in ('||prEmpresas||'))';
      ELSE IF (PRVINCULOEMPRESA = 0) then
        wFilterLan = wFilterLan||' and (BDCODEMP IS NOT NULL)';
    END
  WAUXVARCHAR = '';

  if (PRMANTIP = 1) then
    wFilterLog = 'select COALESCE(BDCODEMP, 0) AS BDCODEMP';
  ELSE
    wFilterLog = 'select BDCODEMP';
  wFilterLog = wFilterLog||', /*SISTEMA*/ as BDCODSIS, /*USUARIO*/ as BDCODUSU, /*PROCESSO*/ as BDCODTELASIS, /*TIPOACAO*/ as BDTIPOACAO,';
  wFilterLog = wFilterLog||' /*DATAINICIAL*/ as BDDATAINICIAL, /*DATAFINAL*/ as BDDATAFINAL, /*HORAINICIAL*/ as BDHORAINICIAL, /*HORAFINAL*/ as BDHORAFINAL,';
  wFilterLog = wFilterLog||' /*QUANTIDADE*/ as BDQUANTIDADE, /*ATIVIDADE*/ as BDATIVIDADE from /*TABELA*/ /*APELIDO*/';
  --alt:16527 - 09/12/2016 - Não tem mais necessidade desta filtragem, já foi corrigido nas bases através de script. Pedro
  --wFilterLog = wFilterLog||' where (DateDiff(Second, Time '||'''00:00'''||', /*HORAINICIAL*/) > 0)';
  --wFilterLog = wFilterLog||'   and (DateDiff(Second, Time '||'''00:00'''||', /*HORAFINAL*/) > 0)';
  IF (wFilterLan <> '') THEN
      WAUXVARCHAR = ' where '||SUBSTRING(wFilterLan FROM 5 FOR CHAR_LENGTH(wFilterLan));
    wFilterLog = wFilterLog||WAUXVARCHAR;
  wFilterLan = wFilterLog; --Copio o filtro para o Lançamento
  WFILTERATI = wFilterLog;

  --Agora faço as adaptações dos nomes dos campos para a tabela do Log.
  wFilterLog = REPLACE(wFilterLog, '/*EMPRESA*/',     'coalesce(BDCODEMP, 0)');
  wFilterLog = REPLACE(wFilterLog, '/*SISTEMA*/',     'BDCODSIS');
  wFilterLog = REPLACE(wFilterLog, '/*USUARIO*/',     'BDCODUSU');
  wFilterLog = REPLACE(wFilterLog, '/*PROCESSO*/',    'BDCODTELASIS');
  wFilterLog = REPLACE(wFilterLog, '/*TIPOACAO*/',    'case when BDTIPOACAO = 11 then BDTIPOACAO else 0 end');
  wFilterLog = REPLACE(wFilterLog, '/*DATAINICIAL*/', 'BDDATASISTEMA');
  wFilterLog = REPLACE(wFilterLog, '/*DATAFINAL*/',   'BDDATA');
  wFilterLog = REPLACE(wFilterLog, '/*HORAINICIAL*/', 'BDHORAINICIAL');
  wFilterLog = REPLACE(wFilterLog, '/*HORAFINAL*/',   'BDHORAFINAL');
  wFilterLog = REPLACE(wFilterLog, '/*QUANTIDADE*/',  'coalesce(BDQUANTIDADE, 1)');
  wFilterLog = REPLACE(wFilterLog, '/*TABELA*/',      'TLOG');
  wFilterLog = REPLACE(wFilterLog, '/*APELIDO*/',     'logsis');  
  wFilterLog = REPLACE(wFilterLog, '/*ATIVIDADE*/',   '0');

  --Agora faço as adaptações dos nomes dos campos para a tabela de Lançamentos.  
  wFilterLan = REPLACE(wFilterLan, '/*EMPRESA*/',     'BDCODEMP');
  wFilterLan = REPLACE(wFilterLan, '/*SISTEMA*/',     '4');
  wFilterLan = REPLACE(wFilterLan, '/*USUARIO*/',     'BDCODUSU');
  wFilterLan = REPLACE(wFilterLan, '/*PROCESSO*/',    wCodTelaSis);
  wFilterLan = REPLACE(wFilterLan, '/*TIPOACAO*/',    '0');
  wFilterLan = REPLACE(wFilterLan, '/*DATAINICIAL*/', 'BDDATALANINICIAL');
  wFilterLan = REPLACE(wFilterLan, '/*DATAFINAL*/',   'BDDATALAN');
  wFilterLan = REPLACE(wFilterLan, '/*HORAINICIAL*/', 'BDHORALANINICIAL');
  wFilterLan = REPLACE(wFilterLan, '/*HORAFINAL*/',   'BDHORALAN');
  wFilterLan = REPLACE(wFilterLan, '/*QUANTIDADE*/',  '1');
  wFilterLan = REPLACE(wFilterLan, '/*TABELA*/',      'VSUC_EMPRESAS_TLAN');
  wFilterLan = REPLACE(wFilterLan, '/*APELIDO*/',     'lan');
  wFilterLan = REPLACE(wFilterLan, '/*ATIVIDADE*/',   '0');

  --Agora faço as adaptações dos nomes dos campos para a tabela de Atividades.  
  WFILTERATI = REPLACE(WFILTERATI, '/*EMPRESA*/',     'coalesce(BDCODEMP, 0)');
  WFILTERATI = REPLACE(WFILTERATI, '/*SISTEMA*/',     'BDCODSIS');
  WFILTERATI = REPLACE(WFILTERATI, '/*USUARIO*/',     'BDCODUSU');
  WFILTERATI = REPLACE(WFILTERATI, '/*PROCESSO*/',    '0');
  WFILTERATI = REPLACE(WFILTERATI, '/*TIPOACAO*/',    '0');
  WFILTERATI = REPLACE(WFILTERATI, '/*DATAINICIAL*/', 'BDDATAINI');
  WFILTERATI = REPLACE(WFILTERATI, '/*DATAFINAL*/',   'BDDATAFIN');
  WFILTERATI = REPLACE(WFILTERATI, '/*HORAINICIAL*/', 'BDHORAINI');
  WFILTERATI = REPLACE(WFILTERATI, '/*HORAFINAL*/',   'BDHORAFIN');
  WFILTERATI = REPLACE(WFILTERATI, '/*QUANTIDADE*/',  '1');
  WFILTERATI = REPLACE(WFILTERATI, '/*TABELA*/',      'VTPO_ATIVIDADE_EXE_REGISTRO');
  WFILTERATI = REPLACE(WFILTERATI, '/*APELIDO*/',     'ati');
  WFILTERATI = REPLACE(WFILTERATI, '/*ATIVIDADE*/',   'BDCODATI');

  wSQL = '';
  if (PRPROCESSOS <> '0' and PRATIVIDADES <> '0') then
    wFilterLog = wFilterLog||' union all '||wFilterLan||' union all '||WFILTERATI;
  else
  if (PRPROCESSOS <> '0') then
    wFilterLog = wFilterLog||' union all '||wFilterLan;
  else
  if (PRATIVIDADES <> '0') then
    wFilterLog = WFILTERATI;
  else
    wFilterLog = wFilterLog||' union all '||wFilterLan||' union all '||WFILTERATI;

  --SQL completo dos tempos.
  if (PRMANTIP = 1) then -- #93513 - Carlos Machado - 03/12/2018
    BEGIN
      DELETE FROM TMP_VTPO_CONSULTA_TEMPOS;
      wSQL = wSQL||'insert into TMP_VTPO_CONSULTA_TEMPOS (BDCODEMP, BDCODSIS, BDCODUSU, BDCODTELASIS, BDTIPOACAO, BDDATAINICIAL, BDDATAFINAL, BDHORAINICIAL, BDHORAFINAL, BDQUANTIDADE, bdatividade) ';
      WSQL = WSQL||'SELECT * FROM ('||wFilterLog||')';
      EXECUTE STATEMENT WSQL;
      EXIT;
    END
  ELSE
  if (PRMANTIP = 2) THEN
    BEGIN
      wFilterLog = 'SELECT * FROM TMP_VTPO_CONSULTA_TEMPOS';
      if (WAUXVARCHAR <> '') then
        wFilterLog = wFilterLog||WAUXVARCHAR;
      wFilterLog = REPLACE(wFilterLog, '/*SISTEMA*/',    'BDCODSIS');
      wFilterLog = REPLACE(wFilterLog, '/*USUARIO*/',    'BDCODUSU');
      wFilterLog = REPLACE(wFilterLog, '/*PROCESSO*/',   'BDCODTELASIS');
      wFilterLog = REPLACE(wFilterLog, '/*TIPOACAO*/',   'BDTIPOACAO');
      wFilterLog = REPLACE(wFilterLog, '/*DATAINICIAL*/','BDDATAINICIAL');
      wFilterLog = REPLACE(wFilterLog, '/*DATAFINAL*/',  'BDDATAFINAL');
      wFilterLog = REPLACE(wFilterLog, '/*HORAINICIAL*/','BDHORAINICIAL');
      wFilterLog = REPLACE(wFilterLog, '/*HORAFINAL*/',  'BDHORAFINAL');
      wFilterLog = REPLACE(wFilterLog, '/*QUANTIDADE*/', 'BDQUANTIDADE)');  
      WFILTERATI = REPLACE(WFILTERATI, '/*ATIVIDADE*/',  'bdatividade');
    END

  wSQL = wSQL||'select * from (';
  wSQL = wSQL||' select emp.BDCODEMP, sis.BDCODSIS, sis.BDORDEMSCI, usu.BDCODUSU, tela.BDCODTELASIS, ';
  wSQL = wSQL||' emp.BDNOMEMP, sis.BDDESCSIS, usu.BDNOMCOMPLUSU, tela.BDCAPTIONTELA, ati.BDCODATI, ATI.BDDESCRICAO || '' ('' || iif(ATI.BDLOCAL = 1, ''Exterior'', ''Interior'') || '')'' AS BDDESCRICAOATI,';
  wSQL = wSQL||' sum(case when BDTIPOACAO = 0 then BDQUANTIDADE else 0 end) as BDQUANTIDADE,';
  wSQL = wSQL||' Sum(Abs(case when BDTIPOACAO = 0 then (BDDATAFINAL + BDHORAFINAL) - (BDDATAINICIAL + BDHORAINICIAL) else 0 end)) as BDTEMPOATIVO,';
  wSQL = wSQL||' Sum(Abs(case when BDTIPOACAO = 0 then 0 else (BDDATAFINAL + BDHORAFINAL) - (BDDATAINICIAL + BDHORAINICIAL) end)) as BDTEMPOINATIVO';
  wSQL = wSQL||' from ('||wFilterLog||') tempos';
  wSQL = wSQL||' join TUSUARIO usu on (usu.BDCODUSU = tempos.BDCODUSU)';
  wSQL = wSQL||' left join VW_TEMPRESAS_REF emp on (emp.BDCODEMP = tempos.BDCODEMP)';
  wSQL = wSQL||' left join TSISTEMA sis on (sis.BDCODSIS = tempos.BDCODSIS)';
  wSQL = wSQL||' left join TTELA_SISTEMA tela on (tela.BDCODTELASIS = tempos.BDCODTELASIS)';
  wSQL = wSQL||' left join VTPO_ATIVIDADE_EXE ati on (tempos.BDATIVIDADE = ati.BDCODATI)';
  wSQL = wSQL||' group by emp.BDCODEMP, emp.BDNOMEMP, sis.BDCODSIS, sis.BDORDEMSCI, sis.BDDESCSIS, usu.BDCODUSU, usu.BDNOMCOMPLUSU, tela.BDCODTELASIS, tela.BDCAPTIONTELA, ati.BDCODATI, ati.BDDESCRICAO, ATI.BDLOCAL';
  wSQL = wSQL||' union';
  wSQL = wSQL||' select first 1 null, null, null, null, null, null, null, null, null, null, null, null, null, null from RDB$FIELDS)';
  --Carlos Machado - 12/09/2018 - #89507 
  wSQL = wSQL||' where (BDTEMPOATIVO > 0 or BDTEMPOINATIVO > 0 or BDTEMPOINATIVO is null)';
  wSQL = wSQL||' order by case when (BDCODUSU is null) then 1 else 0 end, ';
  wSQL = wSQL||REPLACE(REPLACE(REPLACE(prFields, 'BDNOMEMP', 'BDCODEMP'), 'BDDESCSIS', 'BDORDEMSCI'), 'BDNOMCOMPLUSU', 'BDCODUSU');
  wSQL = wSQL||', BDTEMPOATIVO '||CASE WHEN prOrder = 0 THEN 'asc' ELSE 'desc' END;

  IF (prReport = 0) THEN
    BEGIN
      FOR EXECUTE STATEMENT wSQL INTO :wCODEMP, :wCODSIS, :wORDEMSCI, :wCODUSU, :wCODTELASIS,
                                      :wNOMEMP, :wDESCSIS, :wNOMCOMPLUSU, :wCAPTIONTELA,
                                      :WCODATI, :WDESCATI,
                                      :wQuantidade, wTempoAtivo, :wTempoInativo DO
      BEGIN
        wTempoAtivoTotal = wTempoAtivoTotal + COALESCE(wTempoAtivo, 0);
        wTempoInativoTotal = wTempoInativoTotal + COALESCE(wTempoInativo, 0);
        wQuantidadeTotal = wQuantidadeTotal + COALESCE(wQuantidade, 0);
      END
    
      rdb$set_context('USER_SESSION', 'W_LOG_QUANTIDADE', :wQuantidadeTotal);
      rdb$set_context('USER_SESSION', 'W_LOG_TEMPOATIVOTOTAL', CAST('12/30/1899 00:00:00' AS TIMESTAMP) + :wTempoAtivoTotal);
      rdb$set_context('USER_SESSION', 'W_LOG_TEMPOINATIVOTOTAL', CAST('12/30/1899 00:00:00' AS TIMESTAMP) + :wTempoInativoTotal);
      rdb$set_context('USER_SESSION', 'W_LOG_TEMPOMEDIO', CAST('12/30/1899 00:00:00' AS TIMESTAMP) + CASE WHEN :wQuantidadeTotal > 0 THEN CAST(:wTempoAtivoTotal AS DECIMAL(18,9)) / :wQuantidadeTotal ELSE 0 END);
    END

  FOR EXECUTE STATEMENT wSQL INTO :wCODEMP, :wCODSIS,  :wORDEMSCI, :wCODUSU, :wCODTELASIS,
                                  :wNOMEMP, :wDESCSIS, :wNOMCOMPLUSU, :wCAPTIONTELA,
                                  :WCODATI, :WDESCATI, :wQuantidade, wTempoAtivo, :wTempoInativo DO
  BEGIN
    wColumn1 = 0;
    wColumn2 = 0;
    wColumn3 = 0;
    wColumn4 = 0;
    wPosition = wLastLevel;
    wReprintLevel = MINVALUE(CASE WHEN wCodUSU IS NULL THEN 0 ELSE 999 END,
                             CASE WHEN COALESCE(wCODEMP, 0) <> COALESCE(wCODEMP_AUX, 0) THEN wSeqEmp ELSE 999 END,
                             CASE WHEN COALESCE(wCODSIS, 0) <> COALESCE(wCODSIS_AUX, 0) THEN wSeqSis ELSE 999 END,
                             CASE WHEN COALESCE(wCODUSU, 0) <> COALESCE(wCODUSU_AUX, 0) THEN wSeqUsu ELSE 999 END,
                             CASE WHEN (COALESCE(wCODTELASIS, 0) <> COALESCE(wCODTELASIS_AUX, 0) or COALESCE(WCODATI, 0) <> COALESCE(WCODATI_AUX, 0) ) THEN wSeqTela ELSE 999 END);
    WHILE (wPosition > 0) DO
    BEGIN
      wColumn1 = CASE WHEN wSeqEmp = wPosition THEN wPosition ELSE 0 END;
      wColumn2 = CASE WHEN wSeqSis = wPosition THEN wPosition ELSE 0 END;
      wColumn3 = CASE WHEN wSeqUsu = wPosition THEN wPosition ELSE 0 END;
      wColumn4 = CASE WHEN wSeqTela = wPosition THEN wPosition ELSE 0 END;
      BDNOMEMP = TRIM(CASE WHEN wPosition = wLastLevel THEN '' ELSE wDescTotal END||CASE WHEN wColumn1 = wPosition AND (wColumn1 >= wReprintLevel) THEN (CASE WHEN wCODEMP_AUX IS NULL THEN 'Sem vínculo de empresa' ELSE wNOMEMP_AUX END) END);
      BDDESCSIS = TRIM(CASE WHEN wPosition = wLastLevel THEN '' ELSE wDescTotal END||CASE WHEN wColumn2 = wPosition AND (wColumn2 >= wReprintLevel) THEN wDESCSIS_AUX END);
      BDNOMCOMPLUSU = TRIM(CASE WHEN wPosition = wLastLevel THEN '' ELSE wDescTotal END||CASE WHEN wColumn3 = wPosition AND (wColumn3 >= wReprintLevel) THEN wNOMCOMPLUSU_AUX END);
      BDCAPTIONTELA = TRIM(CASE WHEN wPosition = wLastLevel THEN '' ELSE wDescTotal END||CASE WHEN wColumn4 = wPosition AND (wColumn4 >= wReprintLevel) THEN wCAPTIONTELA_AUX END);
      BDTIPOREGISTRO = CASE WHEN wPosition = wLastLevel THEN 0 ELSE 2 END;
    IF ((BDNOMEMP IS NOT NULL) OR (BDDESCSIS IS NOT NULL) OR (BDNOMCOMPLUSU IS NOT NULL) OR (BDCAPTIONTELA IS NOT NULL)) THEN
      BEGIN
          IF (wPosition = 1) THEN
            BEGIN
              wTempoAtivoAtu = wTempoAtivoSoma1;
              wTempoAtivoSoma1 = 0;
              wTempoInativoAtu = wTempoInativoSoma1;
              wTempoInativoSoma1 = 0;
              wQuantidadeAtu = wQuantidadeSoma1;
              wQuantidadeSoma1 = 0;
      END
          ELSE IF (wPosition = 2) THEN
      BEGIN
              wTempoAtivoAtu = wTempoAtivoSoma2;
              wTempoAtivoSoma2 = 0;
              wTempoInativoAtu = wTempoInativoSoma2;
              wTempoInativoSoma2 = 0;
              wQuantidadeAtu = wQuantidadeSoma2;
        wQuantidadeSoma2 = 0;
      END
          ELSE IF (wPosition = 3) THEN
            BEGIN
              wTempoAtivoAtu = wTempoAtivoSoma3;
              wTempoAtivoSoma3 = 0;
              wTempoInativoAtu = wTempoInativoSoma3;
              wTempoInativoSoma3 = 0;
              wQuantidadeAtu = wQuantidadeSoma3;
              wQuantidadeSoma3 = 0;
            END

          BDTEMPOATIVO = CAST('12/30/1899 00:00:00' AS TIMESTAMP) + wTempoAtivoAtu;
          BDTEMPOINATIVO = CAST('12/30/1899 00:00:00' AS TIMESTAMP) + wTempoInativoAtu;
          BDQUANTIDADE = wQuantidadeAtu;
          BDTEMPOMEDIO = CAST('12/30/1899 00:00:00' AS TIMESTAMP) + CASE WHEN wQuantidadeAtu > 0 THEN CAST(wTempoAtivoAtu AS DECIMAL(18,9)) / wQuantidadeAtu ELSE 0 END;
          BDPERCENTUAL = CASE WHEN (prReport = 0) AND (wTempoAtivoAtu > 0) THEN 100 / wTempoAtivoTotal ELSE 0 END;
          BDPERCENTUAL = wTempoAtivoAtu * BDPERCENTUAL;
          SUSPEND;
        END
      wPosition = wPosition -1;
    END

    --Se o código da empresa for nulo, é o registro extra adicionado no final apenas para totalizar, então não deve imprimir nem contabilizar nada que é feito abaixo.
    IF (wCodUsu IS NULL) THEN
      BEGIN
        --Uso estas variáveis posteriormente para calcular a porcentagem de cada registro e apresentar totais.
        rdb$set_context('USER_SESSION', 'W_LOG_QUANTIDADE', :wQuantidadeTotal);
        rdb$set_context('USER_SESSION', 'W_LOG_TEMPOATIVOTOTAL', CAST('12/30/1899 00:00:00' AS TIMESTAMP) + :wTempoAtivoTotal);
        rdb$set_context('USER_SESSION', 'W_LOG_TEMPOINATIVOTOTAL', CAST('12/30/1899 00:00:00' AS TIMESTAMP) + :wTempoInativoTotal);
        rdb$set_context('USER_SESSION', 'W_LOG_TEMPOMEDIO', CAST('12/30/1899 00:00:00' AS TIMESTAMP) + CASE WHEN :wQuantidadeTotal > 0 THEN CAST(:wTempoAtivoTotal AS DECIMAL(18,9)) / :wQuantidadeTotal ELSE 0 END);
        LEAVE;
      END

    BDCODEMP = wCODEMP;
    BDCODSIS = wCODSIS;
    BDORDEMSCI = wORDEMSCI;
    BDCODUSU = wCODUSU;
    if (WCODATI > 0) then
      BDCODTELASIS = WCODATI;
    else
      BDCODTELASIS = wCODTELASIS;

    BDTEMPOATIVO = NULL;
    BDTEMPOINATIVO = NULL;
    BDQUANTIDADE = NULL;
    BDTEMPOMEDIO = NULL;
    BDPERCENTUAL = NULL;
    BDTIPOREGISTRO = 1;

    wColumn1 = 999;
    wColumn2 = 999;
    wColumn3 = 999;
    wColumn4 = 999;
    wPosition = 1;
    --Não dá pra fazer a linha de registro aqui, pois precisa somar todos os registros quando está com um nível a menos.
    WHILE (wPosition < wLastLevel) DO
      BEGIN
      wColumn1 = CASE WHEN wSeqEmp = wPosition AND (COALESCE(wCODEMP, 0) <> COALESCE(wCODEMP_AUX, 0) OR (wReprintLevel <= wSeqEmp)) THEN wPosition ELSE wColumn1 END;
      wColumn2 = CASE WHEN wSeqSis = wPosition AND (COALESCE(wCODSIS, 0) <> COALESCE(wCODSIS_AUX, 0) OR (wReprintLevel <= wSeqSis)) THEN wPosition ELSE wColumn2 END;
      wColumn3 = CASE WHEN wSeqUsu = wPosition AND (COALESCE(wCODUSU, 0) <> COALESCE(wCODUSU_AUX, 0) OR (wReprintLevel <= wSeqUsu)) THEN wPosition ELSE wColumn3 END;
      wColumn4 = CASE WHEN wSeqTela = wPosition AND (COALESCE(wCODTELASIS, 0) <> COALESCE(wCODTELASIS_AUX, 0) OR COALESCE(WCODATI, 0) <> COALESCE(WCODATI_AUX, 0)  OR (wReprintLevel <= wSeqTela)) THEN wPosition ELSE wColumn4 END;
      wReprintLevel = MINVALUE(wColumn1, wColumn2, wColumn3, wColumn4);
      BDNOMEMP = TRIM(CASE WHEN wColumn1 = wPosition THEN (CASE WHEN wCODEMP IS NULL THEN 'Sem vínculo de empresa' ELSE wNOMEMP END) END);
      BDDESCSIS = TRIM(CASE WHEN wColumn2 = wPosition THEN wDESCSIS END);
      BDNOMCOMPLUSU = TRIM(CASE WHEN wColumn3 = wPosition THEN wNOMCOMPLUSU END);
      BDCAPTIONTELA = TRIM(CASE WHEN wColumn4 = wPosition THEN iif(WCODATI > 0, WDESCATI, wCAPTIONTELA) END);
      wPosition = wPosition + 1;
      IF ((BDNOMEMP IS NOT NULL) OR (BDDESCSIS IS NOT NULL) OR (BDNOMCOMPLUSU IS NOT NULL) OR (BDCAPTIONTELA IS NOT NULL)) THEN
        SUSPEND;
    END

    wCODEMP_AUX = wCODEMP;
    wCODSIS_AUX = wCODSIS;
    wCODUSU_AUX = wCODUSU;
    wCODTELASIS_AUX = wCODTELASIS;
    WCODATI_AUX     = WCODATI;
    wNOMEMP_AUX = wNOMEMP;
    wDESCSIS_AUX = wDESCSIS;
    wNOMCOMPLUSU_AUX = wNOMCOMPLUSU;
    if (WCODATI_AUX > 0) then
      wCAPTIONTELA_AUX = WDESCATI;
    ELSE
      wCAPTIONTELA_AUX = wCAPTIONTELA;

    wTempoAtivoAtu = wTempoAtivo;
    wTempoAtivoSoma1 = wTempoAtivoSoma1 + wTempoAtivo;
    wTempoAtivoSoma2 = wTempoAtivoSoma2 + wTempoAtivo;
    wTempoAtivoSoma3 = wTempoAtivoSoma3 + wTempoAtivo;
    wTempoInativoAtu = wTempoInativo;
    wTempoInativoSoma1 = wTempoInativoSoma1 + wTempoInativo;
    wTempoInativoSoma2 = wTempoInativoSoma2 + wTempoInativo;
    wTempoInativoSoma3 = wTempoInativoSoma3 + wTempoInativo;
    wQuantidadeAtu = wQuantidade;
    wQuantidadeSoma1 = wQuantidadeSoma1 + wQuantidade;
    wQuantidadeSoma2 = wQuantidadeSoma2 + wQuantidade;
    wQuantidadeSoma3 = wQuantidadeSoma3 + wQuantidade;
    IF (prReport = 1) THEN
      BEGIN
        wTempoAtivoTotal = wTempoAtivoTotal + COALESCE(wTempoAtivo, 0);
        wTempoInativoTotal = wTempoInativoTotal + COALESCE(wTempoInativo, 0);
        wQuantidadeTotal = wQuantidadeTotal + COALESCE(wQuantidade, 0);
      END
  END
END
^

/* Restore proc. body: SP_SOCIOPROPRIETARIO */
CREATE OR ALTER procedure SP_SOCIOPROPRIETARIO (
    PRCODEMP varchar(25000),
    PRANOMES integer)
returns (
    BDCODEMP integer,
    BDNROPROPSOC integer,
    BDNROPROPEMP integer)
as
declare variable WSQL varchar(32700);
begin
  WSQL = 'select EMP.BDCODEMP, COALESCE(EMPSOC.BDTOTSOC,0) BDNROPROPSOC, COALESCE(EMPRAIS.BDNROPROPEMP,0) BDNROPROPEMP ' ||
         'from TEMPRESAS EMP ' ||
         'left outer join ( ' ||
           'select EMPS.BDCODEMP, COUNT(*) BDTOTSOC ' || 'from EMPRESAS_TSOC EMPS ' ||
           'join TQUALIFICACAOSOC QUAS on (QUAS.BDQUALIFICACAOSOC = EMPS.BDQUALIFICACAOSOC) ' ||
           'where (COALESCE(QUAS.BDTIPOQUALISOC,0) = 0) and ' ||
                 '(SUBSTRING((CAST(EMPS.BDDATAENTSOC AS VARCHAR(10))) FROM 1 FOR 4)||SUBSTRING((CAST(EMPS.BDDATAENTSOC AS VARCHAR(10))) FROM 6 FOR 2) <=  ' || pranomes || ') ' || ' and ' ||
                 '((EMPS.BDDATASAISOC is null) or (SUBSTRING((CAST(EMPS.BDDATASAISOC AS VARCHAR(10))) FROM 1 FOR 4) >=  ' || substring((cast(:PRANOMES as varchar(10))) from 1 for 4) || ')) ' ||
           'group by EMPS.BDCODEMP ' ||
         ') EMPSOC on (EMPSOC.BDCODEMP = EMP.BDCODEMP) ' ||
         'left outer join VW_VRHF_BASE_TEMPRAIS EMPRAIS on (EMPRAIS.BDCODEMP = EMP.BDCODEMP) ';

  if (PRCODEMP is not null and
      PRCODEMP <> '') then
    WSQL = WSQL || ' where ' || PRCODEMP;

  for execute statement WSQL
          into :BDCODEMP, :BDNROPROPSOC, :BDNROPROPEMP
  do
    suspend;
END
^


CREATE OR ALTER PROCEDURE VSUC_SP_COPIA_CONFIG_IDIOMAS (
    PRIDIOMA INTEGER,
    PRCODPLANO_DE INTEGER,
    PRCODPLANO_PARA INTEGER,
    PRPLANO INTEGER,
    PROPCAOTROCA INTEGER)
AS
DECLARE VARIABLE wSQL VARCHAR(1000);
DECLARE VARIABLE wCODIDIOMA INTEGER;
DECLARE VARIABLE wCODPLANO INTEGER;
DECLARE VARIABLE wCODITEM INTEGER;
DECLARE VARIABLE wNOMCTAIDIOMA VARCHAR(100);
BEGIN
  IF (:prOpcaoTroca = 1) THEN
    BEGIN
      IF (prPlano = 0) THEN
        DELETE FROM PLANOS_TPLA_IDIOMAS WHERE BDCODPLAPADRAO = :prCodPlano_PARA AND BDCODIDIOMA = :prIdioma;
      ELSE IF (prPlano = 1) THEN
        DELETE FROM PLANOS_TPCC_IDIOMAS WHERE BDCODCENTRO = :prCodPlano_PARA AND BDCODIDIOMA = :prIdioma;
      ELSE IF (prPlano = 2) THEN
        DELETE FROM PLANOS_TFOR_IDIOMAS WHERE BDCODPFOR = :prCodPlano_PARA AND BDCODIDIOMA = :prIdioma;
    END

  wSQL = 'select config.BDCODIDIOMA, config.BDNOMCTAIDIOMA, '||:prCodPlano_PARA;

  IF (prPlano = 0) THEN
    BEGIN
      wSQL = wSQL||' as BDCODPLAPADRAO, PARA.BDCODTPLA from PLANOS_TPLA_IDIOMAS config';
      wSQL = wSQL||' inner join PLANOS_TPLA DE on (DE.BDCODPLAPADRAO = config.BDCODPLAPADRAO and DE.BDCODTPLA = config.BDCODTPLA)';
      wSQL = wSQL||'  left join PLANOS_TPLA PARA on (PARA.BDCODPLAPADRAO = '||:prCodPlano_PARA||')';
      wSQL = wSQL||' where config.BDCODIDIOMA = '||:prIdioma;
      wSQL = wSQL||'   and config.BDCODPLAPADRAO = '||:prCodPlano_DE;
      wSQL = wSQL||'   and Upper(DE.BDNOMCTA) = Upper(PARA.BDNOMCTA)';
    END
  ELSE IF (prPlano = 1) THEN
    BEGIN
      wSQL = wSQL||' as BDCODCENTRO, PARA.BDCODTPCC from PLANOS_TPCC_IDIOMAS config';
      wSQL = wSQL||' inner join CENTROS_TPCC DE on (DE.BDCODCENTRO = config.BDCODCENTRO and DE.BDCODTPCC = config.BDCODTPCC)';
      wSQL = wSQL||'  left join CENTROS_TPCC PARA on (PARA.BDCODCENTRO = '||:prCodPlano_PARA||')';
      wSQL = wSQL||' where config.BDCODIDIOMA = '||:prIdioma;
      wSQL = wSQL||'   and config.BDCODCENTRO = '||:prCodPlano_DE;
      wSQL = wSQL||'   and Upper(DE.BDNOMCTA) = Upper(PARA.BDNOMCTA)';
    END
  ELSE IF (prPlano = 2) THEN
    BEGIN
      wSQL = wSQL||' as BDCODPFOR, PARA.BDCODFOR from PLANOS_TFOR_IDIOMAS config';
      wSQL = wSQL||' inner join VSUC_BASE_TFORMULA_TPFO DE on (DE.BDCODPFOR = config.BDCODPFOR and DE.BDCODFOR = config.BDCODFOR)';
      wSQL = wSQL||'  left join VSUC_BASE_TFORMULA_TPFO PARA on (PARA.BDCODPFOR = '||:prCodPlano_PARA||')';
      wSQL = wSQL||' where config.BDCODIDIOMA = '||:prIdioma;
      wSQL = wSQL||'   and config.BDCODPFOR = '||:prCodPlano_DE;
      wSQL = wSQL||'   and Upper(DE.BDNOMFOR) = Upper(PARA.BDNOMFOR)';
    END

  IF (:prOpcaoTroca = 3) THEN
    BEGIN
      IF (prPlano = 0) THEN
        BEGIN
          wSQL = wSQL||'   and not exists(select * from PLANOS_TPLA_IDIOMAS ';
          wSQL = wSQL||'                  where BDCODPLAPADRAO = PARA.BDCODPLAPADRAO';
          wSQL = wSQL||'                    and BDCODTPLA = PARA.BDCODTPLA';
          wSQL = wSQL||'                    and BDCODIDIOMA = '||:prIdioma||')';
        END
      ELSE IF (prPlano = 1) THEN
        BEGIN
          wSQL = wSQL||'   and not exists(select * from PLANOS_TPCC_IDIOMAS ';
          wSQL = wSQL||'                  where BDCODCENTRO = PARA.BDCODCENTRO';
          wSQL = wSQL||'                    and BDCODTPCC = PARA.BDCODTPCC';
          wSQL = wSQL||'                    and BDCODIDIOMA = '||:prIdioma||')';
        END
      ELSE IF (prPlano = 2) THEN
        BEGIN
          wSQL = wSQL||'   and not exists(select * from PLANOS_TFOR_IDIOMAS ';
          wSQL = wSQL||'                  where BDCODPFOR = PARA.BDCODPFOR';
          wSQL = wSQL||'                    and BDCODFOR = PARA.BDCODFOR';
          wSQL = wSQL||'                    and BDCODIDIOMA = '||:prIdioma||')';
        END
    END

  FOR EXECUTE STATEMENT wSQL INTO :wCodIdioma, :wNomCtaIdioma, :wCodPlano, :wCodItem DO
  BEGIN
    IF (prPlano = 0) THEN
      UPDATE OR INSERT INTO PLANOS_TPLA_IDIOMAS VALUES (:wCodIdioma, :wCodPlano, :wCodItem, :wNomCtaIdioma) MATCHING (BDCODIDIOMA, BDCODPLAPADRAO, BDCODTPLA);
    ELSE IF (prPlano = 1) THEN
      UPDATE OR INSERT INTO PLANOS_TPCC_IDIOMAS VALUES (:wCodIdioma, :wCodPlano, :wCodItem, :wNomCtaIdioma) MATCHING (BDCODIDIOMA, BDCODCENTRO, BDCODTPCC);
    ELSE IF (prPlano = 2) THEN
      UPDATE OR INSERT INTO PLANOS_TFOR_IDIOMAS VALUES (:wCodIdioma, :wCodPlano, :wCodItem, :wNomCtaIdioma) MATCHING (BDCODIDIOMA, BDCODPFOR, BDCODFOR);
  END
END
^

CREATE OR ALTER PROCEDURE SP_TIPODESCIDIOMAS (
    PRABRIRPLANOS VARCHAR(5))
RETURNS (
    BDCODTIPODESCIDIOMA INTEGER,
    BDCLASSIFICACAO VARCHAR(100),
    BDCONFIGURA DM_BOOLEAN,
    BDPERMITEABREVIADO DM_BOOLEAN,
    BDPLANO INTEGER,
    BDNIVEL INTEGER,
    BDNIVEL1 VARCHAR(100),
    BDNIVEL2 VARCHAR(100),
    BDNIVEL3 VARCHAR(100),
    BDCONSTANTE VARCHAR(30),
    BDDESCRICAO VARCHAR(100))
AS
BEGIN
    FOR SELECT tipos.BDCODTIPODESCIDIOMA, tipos.BDCLASSIFICACAO, tipos.BDCONFIGURA, tipos.BDPERMITEABREVIADO, tipos.BDCONSTANTE,
               CHAR_LENGTH(tipos.BDCLASSIFICACAO) - CHAR_LENGTH(REPLACE(tipos.BDCLASSIFICACAO, '.', '')),
               CASE WHEN planoCTA.BDCODPLAPADRAO IS NOT NULL THEN planoCTA.BDCODPLAPADRAO
                    WHEN planoCC.BDCODCENTRO IS NOT NULL THEN planoCC.BDCODCENTRO
                    WHEN planoFOR.BDCODPFOR IS NOT NULL THEN planoFOR.BDCODPFOR END AS BDCODPLANO,
               CASE WHEN planoCTA.BDCODPLAPADRAO IS NOT NULL THEN planoCTA.BDCODPLAPADRAO||' - '||planoCTA.BDNOME
                    WHEN planoCC.BDCODCENTRO IS NOT NULL THEN planoCC.BDCODCENTRO||' - '||planoCC.BDNOME
                    WHEN planoFOR.BDCODPFOR IS NOT NULL THEN planoFOR.BDCODPFOR||' - '||planoFOR.BDNOMPFOR
                    ELSE tipos.BDDESCRICAO END AS BDDESCRICAO
        FROM TTIPODESCIDIOMAS tipos
        LEFT JOIN TPLANO_PADRAO planoCTA ON (tipos.BDCLASSIFICACAO = '03.00001.000001')
        LEFT JOIN TCENTROS planoCC ON (tipos.BDCLASSIFICACAO = '03.00002.000001')
        LEFT JOIN VSUC_BASE_TFORMULA planoFOR ON (tipos.BDCLASSIFICACAO = '03.00003.000001')
        ORDER BY tipos.BDCLASSIFICACAO, planoCTA.BDCODPLAPADRAO, planoCC.BDCODCENTRO, planoFOR.BDCODPFOR
    INTO :BDCODTIPODESCIDIOMA, :BDCLASSIFICACAO, :BDCONFIGURA, :BDPERMITEABREVIADO, :BDCONSTANTE, :BDNIVEL, :BDPLANO, :BDDESCRICAO DO
    BEGIN
      IF ((BDNIVEL = 0) AND ((BDCONFIGURA = 'FALSE') OR (BDPLANO IS NOT NULL))) THEN
        BDNIVEL1 = BDDESCRICAO;
      ELSE IF ((BDNIVEL = 1) AND ((BDCONFIGURA = 'FALSE') OR (BDPLANO IS NOT NULL))) THEN
        BDNIVEL2 = BDDESCRICAO;
      ELSE IF ((BDNIVEL = 2) AND ((BDCONFIGURA = 'FALSE') OR (BDPLANO IS NOT NULL))) THEN
        BDNIVEL3 = BDDESCRICAO;

      IF (BDNIVEL < 2) THEN
        BDNIVEL3 = NULL;
    
      IF (BDNIVEL < 1) THEN
        BDNIVEL2 = NULL;

      SUSPEND;
    END
END^

create or alter procedure VSUC_SP_EMP_TLAN_RH_GROUP_NEW (
    PRCODEMP      integer,
    PRCHAVEONLINE varchar(120),
    PRDATA        date,
    PRDEBITO      integer,
    PRCREDITO     integer,
    PRWHERE       varchar(8192) = null)
returns (
    BDCODEMP              integer,
    BDCHAVE               integer,
    BDCODPLAPADRAO        integer,
    BDCODHIST             integer,
    BDLOTE                varchar(10),
    BDDATA                date,
    BDDEBITO              integer,
    BDCONCD               varchar(5),
    BDCREDITO             integer,
    BDCONCC               varchar(5),
    BDVALOR               numeric(15,2),
    BDDATALAN             date,
    BDHORALAN             time,
    BDDATALANALT          date,
    BDHORALANALT          time,
    BDCODUSU              integer,
    BDCODUSUALTERACAO     integer,
    BDCODTPHI             integer,
    BDNOMEHIST            varchar(100),
    BDCOMPL               varchar(200),
    BDDCTO                varchar(15),
    BDCODTERCEIROD        integer,
    BDCODTERCEIROC        integer,
    BDTIPLAN              varchar(100),
    BDTRANSFERIDO         integer,
    BDGRUPO               integer,
    BDTOTLAN              integer,
    BDAGRUPADOR           integer,
    BDTIPOLAN             integer,
    BDCHAVEONLINE         varchar(120),
    BDCODTPCC             integer,
    BDTRANSACAO           integer,
    BDTRANFECHADA         varchar(5),
    BDCONCILIACAOPENDENTE integer,
    BDOBSERVACAODEB       type of column VSUC_EMPRESAS_TOBS.BDOBSERVACAO,
    BDOBSERVACAOCRE       type of column VSUC_EMPRESAS_TOBS.BDOBSERVACAO)
as
declare variable WSQL             varchar(10240);
declare variable WSQLAUX          varchar(10240);
declare variable WCOUNT           integer;
declare variable WDATA            date;
declare variable WDATAANT         date;
declare variable WDEBITO          integer;
declare variable WDEBANT          integer;
declare variable WCREDITO         integer;
declare variable WCREANT          integer;
declare variable WCHAVEONLINE     varchar(120);
declare variable WCHAVEONLINEANT  varchar(120);
declare variable WVALOR           numeric(15,2);
declare variable WTOTAL           numeric(15,2);
declare variable WCHAVEANT        integer;
declare variable WGRUPO           integer;
declare variable WGRUPOANT        integer;
declare variable WTOTLAN          integer;
declare variable WTOTLANANT       integer;
declare variable WAGRUPADOR       integer;
declare variable WAGRUPADORANT    integer;
declare variable WTIPLANANT       varchar(100);
declare variable WCOMPL1          varchar(200);
declare variable WCOMPL2          varchar(200);
declare variable WCODPLAPADRAOANT integer;
declare variable WTIPOLANANT      integer;
declare variable WCODHISTANT      integer;
declare variable WCODEMP          integer;
declare variable WCODEMPANT       integer;
BEGIN
  --Rotina otimizada para consulta de lançamentos, não usar no diário
  wchaveonlineant = '';
  wdataant = NULL;
  wdebant = 0;
  wcreant = 0;
  wtotal = 0;
  wcount = 0;
  --#alt:123476 - 29/07/2019 - Carlos Machado - Estava deixando a empresa anterior ocasionalmente.
  wcodempant = 0;
  wcodplapadraoant = 0;
  wtipolanant = 0;
  wcodhistant = 0;
  wtiplanant = 0;
  wcompl2 = '';

  --#alt:149942 - Machado - 07/05/2021 - Alterado visualização de razão com lançamentos agrupados - MAX(LAN.BDCOMPL) as BDCOMPL
  wsql = 'select lan.bdcodemp, MAX(lan.bdcodplapadrao), max(lan.bdtipolan), MAX(lan.bdcodhist), lan.bddata, MAX(lan.bddebito), MAX(lan.bdcredito), MAX(lan.bdchaveonline), max(tip.bddescricao) bdTIPLAN, ';
  wsql = wsql||' min(lan.bdchave), count(lan.bdchave), case when count(lan.bdchave) > 1 then 1 else 0 end as bdagrupador, ';
  wsql = wsql||' sum(lan.bdvalor), null as bdcodtpcc, MAX(LAN.BDCOMPL) as BDCOMPL ';
  wsql = wsql||' from (select * from VSUC_EMPRESAS_TLAN LAN where lan.BDCODEMP IN ('||prcodemp||') AND LAN.BDTIPOLAN = 200 AND '||prwhere||' order by BDCODEMP, BDDATA) LAN ';
  wsql = wsql||' left outer join tipos_lancamentos_padrao tip on (tip.bdcodtipo = lan.bdtipolan) ';
  wsql = wsql||' left outer join vsuc_empresas_translan trans on ((trans.bdcodemp = lan.bdcodemp and trans.bdchave = lan.bdchave) or (trans.bdcodemprec = lan.bdcodemp and trans.bdchaverec = lan.bdchave)) ';
  wsql = wsql||' ';
  wsql = wsql||' group by lan.bdcodemp, lan.bddata';
  FOR EXECUTE STATEMENT wsql INTO :WCODEMP, :bdcodplapadrao, :bdtipolan, :bdcodhist, :wdata, :wdebito, :wcredito, :wchaveonline, :bdtiplan, :wgrupo, :wtotlan, :wagrupador, :wvalor, :bdcodtpcc, :WCOMPL1 DO
  BEGIN
   bdchave = wchaveant;
   bddata = wdataant;
   bdgrupo = wgrupoant;
   bdtotlan = wtotlanant;
   bdagrupador = wagrupadorant;
   bdchaveonline = wchaveonlineant;
   BDCODEMP = WCODEMPANT;
   bdcompl = wcompl2;
   IF (wcount >= 2) THEN
      BEGIN
        IF (wtotal < 0) THEN
           BEGIN
             bddebito = wdebant;
             bdcredito = wcreant;
             bdvalor = wtotal * -1;
           END
        ELSE
           BEGIN
             bddebito = wcreant;
             bdcredito = wdebant;
             bdvalor = wtotal;
           END
      END
   ELSE
      BEGIN
        bddebito = wdebant;
        bdcredito = wcreant;
        bdvalor = wtotal;
      END

   IF (wchaveant IS NOT NULL) THEN
     SUSPEND;
   wtotal = 0;
   wdebant = wdebito;
   wcreant = wcredito;
   wdataant = wdata;
   wcompl2 = wcompl1;
   wcount = 0;
   wtotlanant = 0;

   IF ((wchaveonline = prchaveonline) AND (wdata = prdata) AND (COALESCE(wdebito, 0) = COALESCE(prdebito, 0)) AND (COALESCE(wcredito, 0) = COALESCE(prcredito, 0))) THEN
    BEGIN
      wsqlaux = 'select lan.bdCHAVE,  lan.bdCODEMP, lan.bdcodplapadrao, lan.bdcodhist, lan.BDLOTE, ';
      wsqlaux = wsqlaux||'lan.BDDATA, lan.BDDEBITO, lan.BDTIPOLAN,  lan.bdCONCD, lan.BDCREDITO, ';
      wsqlaux = wsqlaux||'lan.bdCONCC, lan.bddatalan, lan.bdhoralan, lan.bddatalanalt, ';
      wsqlaux = wsqlaux||'lan.bdhoralanalt, lan.bdcodusu, lan.bdcodusualteracao, lan.BDCODTPHI, ';
      wsqlaux = wsqlaux||'hist.bdNOME,lan.BDCOMPL,  lan.BDDCTO ,lan.bdcodterceirod, lan.bdcodterceiroc, ';
      wsqlaux = wsqlaux||'tip.bddescricao bdTIPLAN, ';
      wsqlaux = wsqlaux||'case when (lan.bdcodemp = trans.bdcodemp) then trans.bdcodemprec when (lan.bdcodemp = trans.bdcodemprec) then trans.bdcodemp end bdtransferido , ';
      wsqlaux = wsqlaux||'null as bdtotlan, 0 as bdagrupador, lan.bdchaveonline, lan.bdtransacao, lan.bdtranfechada, ';
      --alt:17776 - 09/03/2017 - Adicionadas colunas do status de conciliação e observação, acrescentadas para a central de conciliações. Pedro
      wsqlaux = wsqlaux||'lan.bdconciliacaopendente, tObsDeb.BDOBSERVACAO as BDOBSERVACAODEB, tobsCre.BDOBSERVACAO as BDOBSERVACAOCRE, ';
      wsqlaux = wsqlaux||'lan.bdvalor, null as bdcodtpcc ';
      wsqlaux = wsqlaux||'from VSUC_EMPRESAS_TLAN lan ';
      wsqlaux = wsqlaux||'left join HIST_TPHI hist on ((hist.bdcodhist = lan.bdcodhist) and (hist.bdcodtphi = lan.bdcodtphi)) ';
      wsqlaux = wsqlaux||'left outer join tipos_lancamentos_padrao tip on (tip.bdcodtipo = lan.bdtipolan) ';
      wsqlaux = wsqlaux||'left outer join vsuc_empresas_translan trans on ((trans.bdcodemp = lan.bdcodemp and trans.bdchave = lan.bdchave) or (trans.bdcodemprec = lan.bdcodemp and trans.bdchaverec = lan.bdchave)) ';
      --alt:17776 - 09/03/2017 - Adicionadas colunas do status de conciliação e observação, acrescentadas para a central de conciliações. Pedro
      wsqlaux = wsqlaux||'left join VSUC_EMPRESAS_TOBS tObsDeb on (tObsDeb.BDCODEMP = lan.BDCODEMP and tObsDeb.BDCHAVE = lan.BDCHAVE and tObsDeb.BDDEBCRE = 0) ';
      wsqlaux = wsqlaux||'left join VSUC_EMPRESAS_TOBS tObsCre on (tObsCre.BDCODEMP = lan.BDCODEMP and tObsCre.BDCHAVE = lan.BDCHAVE and tObsCre.BDDEBCRE = 1) ';
      wsqlaux = wsqlaux||' WHERE lan.BDCODEMP IN ('||prcodemp||') AND LAN.BDTIPOLAN = 200 AND '||prwhere||' order by lan.BDCODEMP, lan.BDDATA';
      FOR EXECUTE STATEMENT wsqlaux
          INTO :bdchave, :bdcodemp, :bdcodplapadrao, :bdcodhist, :bdlote, :bddata, :bddebito, :bdtipolan, :bdconcd, :bdcredito, :bdconcc,
               :bddatalan, :bdhoralan, :bddatalanalt, :bdhoralanalt, :bdcodusu, :bdcodusualteracao, :bdcodtphi, :bdnomehist, :bdcompl, :bddcto,
               :bdcodterceirod, :bdcodterceiroc, :bdtiplan, :bdtransferido, :bdtotlan, :bdagrupador, :bdchaveonline, :bdtransacao, :bdtranfechada,
               :bdconciliacaopendente, :bdobservacaodeb, :bdobservacaocre, :bdvalor, :bdcodtpcc DO
          BEGIN
            BDGRUPO = :wGrupo; --alt:11759 - 04/02/2016 - Preciso que o grupo seja o mesmo que o do lançamento agrupado, para poder ordenar corretamente, já que nem sempre é agrupada a ChaveOnline inteira. Pedro
            SUSPEND;
          END
      --#alt:149942
      wcompl1 = NULL;
      wcompl2 = NULL;
      bdcompl = NULL;
    END

    IF ((wdebant = wcredito) AND (wcreant = wdebito) AND (wdataant = wdata)) THEN
       BEGIN
         wtotal = wtotal - wvalor;
         wcount = wcount + 1;
       END
    ELSE
       BEGIN
         wtotal = wtotal + wvalor;
         wcount = wcount + 1;
       END
    wtotlanant = wtotlanant + wtotlan;


    wchaveant = wgrupo;
    wdataant = wdata;
    wdebant = wdebito;
    wcreant = wcredito;
    wchaveonlineant = wchaveonline;
    wgrupoant = wgrupo;
    wagrupadorant = wagrupador;
    wcodempant = wcodemp;
    wcodplapadraoant = bdcodplapadrao;
    wtipolanant = bdtipolan;
    wcodhistant = bdcodhist;
    wtiplanant = bdtiplan;
    wcompl2 = wcompl1;

    BDCODEMP = NULL;
    BDCHAVE = NULL;
    BDCODPLAPADRAO = NULL;
    BDCODHIST = NULL;
    BDLOTE = NULL;
    BDDATA = NULL;
    BDDEBITO = NULL;
    BDCONCD = NULL;
    BDCREDITO = NULL;
    BDCONCC = NULL;
    BDVALOR = NULL;
    BDDATALAN = NULL;
    BDHORALAN = NULL;
    BDDATALANALT = NULL;
    BDHORALANALT = NULL;
    BDCODUSU = NULL;
    BDCODUSUALTERACAO = NULL;
    BDCODTPHI = NULL;
    BDNOMEHIST = NULL;
    BDCOMPL = NULL;
    BDDCTO = NULL;
    BDCODTERCEIROD = NULL;
    BDCODTERCEIROC = NULL;
    BDTIPLAN = NULL;
    BDTRANSFERIDO = NULL;
    BDGRUPO = NULL;
    BDTOTLAN = NULL;
    BDAGRUPADOR = NULL;
    BDTIPOLAN = NULL;
    BDCHAVEONLINE = NULL;
    BDCODTPCC = NULL;
    BDTRANSACAO = NULL;
    BDTRANFECHADA = NULL;
    BDCONCILIACAOPENDENTE = NULL;
    BDOBSERVACAODEB = NULL;
    BDOBSERVACAOCRE = NULL;
  END

  IF (wchaveant IS NOT NULL) THEN
     BEGIN
       bdchave = wchaveant;
       bddata = wdataant;
       bdgrupo = wgrupoant;
       bdtotlan = wtotlanant;
       bdagrupador = wagrupadorant;
       bdchaveonline = wchaveonlineant;
       bdcodemp = wcodempant;
       bdcodplapadrao = wcodplapadraoant;
       bdtipolan = wtipolanant;
       bdcodhist = wcodhistant;
       bdtiplan = wtiplanant;
       bdcompl = wcompl2;

       IF (wcount >= 2) THEN
          BEGIN
            IF (wtotal < 0) THEN
               BEGIN
                 bddebito = wdebant;
                 bdcredito = wcreant;
                 bdvalor = wtotal * -1;
               END
            ELSE
               BEGIN
                 bddebito = wcreant;
                 bdcredito = wdebant;
                 bdvalor = wtotal;
               END
          END
       ELSE
          BEGIN
            bddebito = wdebant;
            bdcredito = wcreant;
            bdvalor = wtotal;
          END

       IF (wchaveant IS NOT NULL) THEN
          BEGIN
            SUSPEND;
-- alt:#6537 - gilberto - 29/08/2013
--            if (wchaveonlineant = prchaveonline and wdataant = prdata) then
            IF ((wchaveonlineant <> wchaveonline) OR (wdataant <> wdata) OR (COALESCE(wdebant, 0) <> COALESCE(wdebito, 0)) OR (COALESCE(wcreant, 0) <> COALESCE(wcredito, 0))) THEN
               BEGIN
                 wsqlaux = 'select lan.bdCHAVE,  lan.bdCODEMP, lan.bdcodplapadrao, lan.bdcodhist, lan.BDLOTE, ';
                 wsqlaux = wsqlaux||'lan.BDDATA, lan.BDDEBITO, lan.BDTIPOLAN,  lan.bdCONCD, lan.BDCREDITO, ';
                 wsqlaux = wsqlaux||'lan.bdCONCC, lan.bddatalan, lan.bdhoralan, lan.bddatalanalt, ';
                 wsqlaux = wsqlaux||'lan.bdhoralanalt, lan.bdcodusu, lan.bdcodusualteracao, lan.BDCODTPHI, ';
                 wsqlaux = wsqlaux||'hist.bdNOME,lan.BDCOMPL,  lan.BDDCTO ,lan.bdcodterceirod, lan.bdcodterceiroc, ';
                 wsqlaux = wsqlaux||'tip.bddescricao bdTIPLAN, ';
                 wsqlaux = wsqlaux||'case when (lan.bdcodemp = trans.bdcodemp) then trans.bdcodemprec when (lan.bdcodemp = trans.bdcodemprec) then trans.bdcodemp end bdtransferido , ';
                 wsqlaux = wsqlaux||'null as bdtotlan, 0 as bdagrupador, lan.bdchaveonline, lan.bdtransacao, lan.bdtranfechada, ';
                 --alt:17776 - 09/03/2017 - Adicionadas colunas do status de conciliação e observação, acrescentadas para a central de conciliações. Pedro
                 wsqlaux = wsqlaux||'lan.bdconciliacaopendente, tObsDeb.BDOBSERVACAO as BDOBSERVACAODEB, tobsCre.BDOBSERVACAO as BDOBSERVACAOCRE, ';
                      wsqlaux = wsqlaux||'lan.bdvalor, null as bdcodtpcc ';
                      wsqlaux = wsqlaux||'from VSUC_EMPRESAS_TLAN lan ';
                 wsqlaux = wsqlaux||'left join HIST_TPHI hist on ((hist.bdcodhist = lan.bdcodhist) and (hist.bdcodtphi = lan.bdcodtphi)) ';
                 wsqlaux = wsqlaux||'left outer join tipos_lancamentos_padrao tip on (tip.bdcodtipo = lan.bdtipolan) ';
                 wsqlaux = wsqlaux||'left outer join vsuc_empresas_translan trans on ((trans.bdcodemp = lan.bdcodemp and trans.bdchave = lan.bdchave) or (trans.bdcodemprec = lan.bdcodemp and trans.bdchaverec = lan.bdchave)) ';
                 --alt:17776 - 09/03/2017 - Adicionadas colunas do status de conciliação e observação, acrescentadas para a central de conciliações. Pedro
                 wsqlaux = wsqlaux||'left join VSUC_EMPRESAS_TOBS tObsDeb on (tObsDeb.BDCODEMP = tlan.BDCODEMP and tObsDeb.BDCHAVE = tlan.BDCHAVE and tObsDeb.BDDEBCRE = 0) ';
                 wsqlaux = wsqlaux||'left join VSUC_EMPRESAS_TOBS tObsCre on (tObsCre.BDCODEMP = tlan.BDCODEMP and tObsCre.BDCHAVE = tlan.BDCHAVE and tObsCre.BDDEBCRE = 1) ';
                 wsqlaux = wsqlaux||' WHERE lan.BDCODEMP IN ('||prcodemp||') AND LAN.BDTIPOLAN = 200 AND '||prwhere||' order by lan.BDCODEMP, lan.BDDATA';
                 FOR EXECUTE STATEMENT wsqlaux
                     INTO :bdchave, :bdcodemp, :bdcodplapadrao, :bdcodhist, :bdlote, :bddata, :bddebito, :bdtipolan, :bdconcd, :bdcredito, :bdconcc,
                          :bddatalan, :bdhoralan, :bddatalanalt, :bdhoralanalt, :bdcodusu, :bdcodusualteracao, :bdcodtphi, :bdnomehist, :bdcompl, :bddcto,
                          :bdcodterceirod, :bdcodterceiroc, :bdtiplan, :bdtransferido, :bdtotlan, :bdagrupador, :bdchaveonline, :bdtransacao, :bdtranfechada,
                          :bdconciliacaopendente, :bdobservacaodeb, :bdobservacaocre, :bdvalor, :bdcodtpcc DO
                     BEGIN
                        BDGRUPO = :wGrupo; --alt:11759 - 04/02/2016 - Preciso que o grupo seja o mesmo que o do lançamento agrupado, para poder ordenar corretamente, já que nem sempre é agrupada a ChaveOnline inteira. Pedro
                        SUSPEND;
                      END
               END
          END
     END
END^

create or alter procedure VSUC_SP_EMP_TLAN_EF_GROUP_NEW (
    PRCODEMP varchar(1024),
    PRTIPOLAN varchar(100),
    PRCONTABILIZACAO integer,
    PRDATA date,
    PRTRANSACAO integer,
    PRCODTPCC varchar(8192) = null,
    PRWHERE varchar(4000) = null)
returns (
    BDCODEMP integer,
    BDCHAVE integer,
    BDCODPLAPADRAO integer,
    BDCODHIST integer,
    BDLOTE varchar(10),
    BDDATA date,
    BDDEBITO integer,
    BDCONCD varchar(5),
    BDCREDITO integer,
    BDCONCC varchar(5),
    BDVALOR numeric(15,2),
    BDDATALAN date,
    BDHORALAN time,
    BDDATALANALT date,
    BDHORALANALT time,
    BDCODUSU integer,
    BDCODUSUALTERACAO integer,
    BDCODTPHI integer,
    BDNOMEHIST varchar(100),
    BDCOMPL varchar(200),
    BDDCTO varchar(15),
    BDCODTERCEIROD integer,
    BDCODTERCEIROC integer,
    BDTIPLAN varchar(100),
    BDTRANSFERIDO integer,
    BDGRUPO integer,
    BDTOTLAN integer,
    BDAGRUPADOR integer,
    BDTIPOLAN integer,
    BDCHAVEONLINE varchar(120),
    BDCODTPCC integer,
    BDTRANSACAO integer,
    BDTRANFECHADA varchar(5),
    BDCONCILIACAOPENDENTE integer,
    BDOBSERVACAODEB type of column VSUC_EMPRESAS_TOBS.BDOBSERVACAO,
    BDOBSERVACAOCRE type of column VSUC_EMPRESAS_TOBS.BDOBSERVACAO)
as
declare variable WSQL varchar(10240);
declare variable WTRANSANT integer;
BEGIN
  wTransAnt = -1;
  wsql = 'select * from (';
  wsql = wsql||'select lan.bdcodemp, lan.bdcodplapadrao, max(lan.bdcodhist) as bdcodhist, lan.bddata, lan.BDTRANSACAO, lan.bdtipolan, tip.bddescricao as bdTIPLAN, ';
  wSQL = wSQL||'max(lan.BDDEBITO) as BDDEBITO, max(lan.BDCREDITO) as BDCREDITO, max(lan.BDCODTPHI) as BDCODTPHI, ';
  wsql = wsql||'min(lan.BDCHAVE) as BDCHAVE, count(lan.bdchave) as BDCOUNT, 1 as bagrupador, ';

  wSQL = wSQL||'max(lan.BDLOTE) as BDLOTE, null as BDCONCD, null as BDCONCC, null as BDDATALAN, null as BDHORALAN, null as BDDATALANALT, ';
  wSQL = wSQL||'null as BDHORALANALT, null as BDCODUSU, null as BDCODUSUALTERACAO, null as BDNOMEHIST, max(lan.BDCOMPL) as BDCOMPL, ';
  wSQL = wSQL||'max(lan.BDDCTO) as BDDCTO, max(lan.BDCODTERCEIROD) as BDCODTERCEIROD, max(lan.BDCODTERCEIROC) as BDCODTERCEIROC, null as BDTRANFECHADA, null as BDTRANSFERIDO, ';
  wSQL = wSQL||'null as BDCONCILIACAOPENDENTE, null as BDOBSERVACAODEB, null as BDOBSERVACAOCRE, ';

  IF (prcodtpcc IS NULL OR (prcodtpcc = '')) THEN
     BEGIN
       wsql = wsql||'avg(lan.bdvalor) as BDVALOR, null as bdcodtpcc ';
       wsql = wsql||'from VSUC_EMPRESAS_TLAN lan ';
     END
  ELSE
     BEGIN
       wsql = wsql||'avg(tlcc.BDVALOR) as BDVALOR, tlcc.bdcodtpcc from vsuc_empresas_tlcc tlcc ';
       wsql = wsql||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
     END
  wsql = wsql||'left outer join tipos_lancamentos_padrao tip on (tip.bdcodtipo = lan.bdtipolan) ';
  wsql = wsql||'left outer join vsuc_empresas_translan trans on ((trans.bdcodemp = lan.bdcodemp and trans.bdchave = lan.bdchave) or (trans.bdcodemprec = lan.bdcodemp and trans.bdchaverec = lan.bdchave)) ';
  wsql = wsql||'WHERE (lan.bdtipolan in ('||prtipolan||')) ';
  
  IF (prcodtpcc IS NOT NULL AND (prcodtpcc <> '')) THEN
     wsql = wsql||' and tlcc.bdcodtpcc in ('||prcodtpcc||')';

  --1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (lan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';

  wsql = wsql||'and ((lan.BDDEBITO is null) or (lan.BDCREDITO is null)) ';
  wsql = wsql||'and (lan.BDTRANFECHADA = ''TRUE'') ';
  wsql = wsql||'and (lan.BDCODEMP in ('||prcodemp||')) ';
  if (prwhere IS NOT NULL AND prwhere <> '') then
    wsql = wsql||' and '||PRWHERE;
  wsql = wsql||'group by lan.bdcodemp, lan.bdcodplapadrao, lan.bdtipolan, lan.bdcodhist, lan.bddata, lan.BDTRANSACAO, tip.bddescricao ';
  wsql = wsql||'having (count(lan.bdchave) = 2) and (sum(case when BDDEBITO is null then 0 else BDVALOR end) = sum(case when BDCREDITO is null then 0 else BDVALOR end))';
  
  wsql = wsql||' union all '; /**********************************************************************************************************************************************/

  wSQL = wSQL||'select lan.bdcodemp, lan.bdcodplapadrao, lan.bdcodhist, lan.bddata, lan.BDTRANSACAO, lan.bdtipolan, tip.bddescricao as bdTIPLAN, ';
  wSQL = wSQL||'lan.BDDEBITO, lan.BDCREDITO, lan.BDCODTPHI, ';
  wsql = wsql||'lan.bdchave, 1 as BDCOUNT, 0 as bagrupador, ';

  wSQL = wSQL||'BDLOTE, BDCONCD, BDCONCC, BDDATALAN, BDHORALAN, BDDATALANALT, BDHORALANALT, BDCODUSU, BDCODUSUALTERACAO, ';
  wSQL = wSQL||'null as BDNOMEHIST, BDCOMPL, BDDCTO, BDCODTERCEIROD, BDCODTERCEIROC, BDTRANFECHADA, ';
  wSQL = wSQL||'case when (lan.bdcodemp = trans.bdcodemp) then trans.bdcodemprec when (lan.bdcodemp = trans.bdcodemprec) then trans.bdcodemp end BDTRANSFERIDO, ';
  wSQL = wSQL||'lan.BDCONCILIACAOPENDENTE, tObsDeb.BDOBSERVACAO as BDOBSERVACAODEB, tobsCre.BDOBSERVACAO as BDOBSERVACAOCRE, ';
  IF (prcodtpcc IS NULL OR (prcodtpcc = '')) THEN
     BEGIN
       wSQL = wSQL||'lan.bdvalor, null as bdcodtpcc ';
       wSQL = wSQL||'from VSUC_EMPRESAS_TLAN lan ';
     END
  ELSE
     BEGIN
       wSQL = wSQL||'tlcc.BDVALOR, tlcc.bdcodtpcc from vsuc_empresas_tlcc tlcc ';
       wSQL = wSQL||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
     END
  wSQL = wSQL||'left outer join tipos_lancamentos_padrao tip on (tip.bdcodtipo = lan.bdtipolan) ';
  wSQL = wSQL||'left outer join vsuc_empresas_translan trans on ((trans.bdcodemp = lan.bdcodemp and trans.bdchave = lan.bdchave) or (trans.bdcodemprec = lan.bdcodemp and trans.bdchaverec = lan.bdchave)) ';
  wSQL = wSQL||'left join VSUC_EMPRESAS_TOBS tObsDeb on (tObsDeb.BDCODEMP = lan.BDCODEMP and tObsDeb.BDCHAVE = lan.BDCHAVE and tObsDeb.BDDEBCRE = 0) ';
  wSQL = wSQL||'left join VSUC_EMPRESAS_TOBS tObsCre on (tObsCre.BDCODEMP = lan.BDCODEMP and tObsCre.BDCHAVE = lan.BDCHAVE and tObsCre.BDDEBCRE = 1) ';
  wSQL = wSQL||'where (lan.bdtipolan in ('||prtipolan||')) ';
  
  IF (prcodtpcc IS NOT NULL AND (prcodtpcc <> '')) THEN
     wsql = wsql||' and tlcc.bdcodtpcc in ('||prcodtpcc||')';

  --1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (lan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  wsql = wsql||'and (lan.BDCODEMP in ('||prcodemp||')) ';
  if (prwhere IS NOT NULL AND prwhere <> '') then
    wsql = wsql||' and '||PRWHERE;


  wsql = wsql||') order by BDTRANSACAO, BDDATA desc, BAGRUPADOR DESC ';
  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodplapadrao, :bdcodhist, :bddata, :bdtransacao, :bdtipolan, :bdtiplan,
                                  :bddebito, :bdcredito, :bdcodtphi,
                                  :bdchave, :bdtotlan, :bdagrupador,
                                  :BDLOTE, :BDCONCD, :BDCONCC, :BDDATALAN, :BDHORALAN, :BDDATALANALT, :BDHORALANALT, :BDCODUSU, :BDCODUSUALTERACAO,
                                  :BDNOMEHIST, :BDCOMPL, :BDDCTO, :BDCODTERCEIROD, :BDCODTERCEIROC, :BDTRANFECHADA, :BDTRANSFERIDO,
                                  :bdconciliacaopendente, :bdobservacaodeb, :bdobservacaocre, :bdvalor, :bdcodtpcc DO
    BEGIN
      BDGRUPO = BDTRANSACAO;

      IF ((BDAGRUPADOR = 1) OR (BDTRANSACAO IS NULL) OR (BDTRANSACAO <> wTransAnt) OR ((BDTRANSACAO = prTRANSACAO) AND (BDDATA = prDATA))) THEN
        SUSPEND;
      --11/11/2019 #124434 Carlos Machado - Caso não tenha agrupador deve exibir todos os lançamentos (Transações com mais de 2 lançamentos).
      IF (BDAGRUPADOR = 1) then
        wTransAnt = BDTRANSACAO;
    END
END^

create or alter procedure VSUC_SP_EMP_TLAN_GROUP (
    PRSESSAO integer,
    PRCODIGO integer,
    PREMPRESAS varchar(1024),
    PRSQL varchar(32000),
    PRFOLHA integer,
    PRFISCAL integer,
    PRCHAVEONLINE varchar(120),
    PRDATAFOLHA date,
    PRDEBITO integer,
    PRCREDITO integer,
    PRDATAFISCAL date,
    PRTRANSACAO integer,
    PREXPORTTXT integer = 0)
returns (
    BDCHAVE integer,
    BDCHAVELCC integer,
    BDCODEMP integer,
    BDCODPLAPADRAO integer,
    BDCODHIST integer,
    BDLOTE varchar(10),
    BDDATA date,
    BDDEBITO integer,
    BDCODTERCEIROD integer,
    BDCONCD varchar(5),
    BDCREDITO integer,
    BDCODTERCEIROC integer,
    BDCONCC varchar(5),
    BDCONCILIACAOPENDENTE integer,
    BDVALOR numeric(18,2),
    BDCODTPHI integer,
    BDCOMPL varchar(200),
    BDDCTO varchar(15),
    BDTIPOLAN integer,
    BDDATALAN date,
    BDHORALAN time,
    BDCODUSU integer,
    BDCODUSUALTERACAO integer,
    BDDATALANALT date,
    BDHORALANALT time,
    BDRECLIXEIRA varchar(5),
    BDTIPLAN varchar(100),
    BDTIPOFCONT integer,
    BDFILIAL integer,
    BDTIPOLANCFILIAL integer,
    BDCONTABILIZACAO integer,
    BDTRANSACAO integer,
    BDTRANFECHADA varchar(5),
    BDOBSERVACAODEB varchar(255),
    BDOBSERVACAOCRE varchar(255),
    BDCOMPLEMENTOCOMPLETO blob sub_type 1 segment size 100,
    BDTRANSFERIDO integer,
    BDGRUPO integer,
    BDTOTLAN integer,
    BDAGRUPADOR integer,
    BDCHAVEONLINE varchar(120),
    BDLANCAEXTEMPORANEO varchar(5),
    BDCHECK varchar(5),
    BDDATAEXTEMPORANEO date,
    USULAN varchar(20),
    USUALT varchar(20),
    BDCODEMPREENDIMENTODEB integer,
    BDCODINUSIMOBDEB integer,
    BDCODEMPREENDIMENTOCRE integer,
    BDCODINUSIMOBCRE integer,
    BDLANORIGINAL integer,
    BDDESCLANORIG varchar(100),
    BDCGCTERC varchar(18),
    BDCGCTERD varchar(18),
    BDDESCRICAO_NE varchar(32700))
as
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(300);
declare variable WTESTE varchar(200);
declare variable WTESTEAUX varchar(200);
begin
--Quando adicionar um campo adicionar no agrupamento fiscal e folha
  WTESTEAUX = '';
  WSQL = PRSQL || 'order by BDCODEMP desc, BDCHAVE desc';

  delete from TMP_VSUC_TLAN_GROUP_TEMP
  where BDSESSAO = :PRSESSAO;

  for execute statement WSQL
          into :BDCHAVE, :BDCHAVELCC, :BDCODEMP, :BDCODPLAPADRAO, :BDCODHIST, :BDLOTE, :BDDATA, :BDDEBITO,
          :BDCODTERCEIROD, :BDCONCD, :BDCREDITO, :BDCODTERCEIROC, :BDCONCC, :BDCONCILIACAOPENDENTE, :BDVALOR,
          :BDCODTPHI, :BDCOMPL, :BDDCTO, :BDTIPOLAN, :BDDATALAN, :BDHORALAN, :BDCODUSU, :BDCODUSUALTERACAO,
          :BDDATALANALT, :BDHORALANALT, :BDRECLIXEIRA, :BDTIPLAN, :BDTIPOFCONT, :BDFILIAL, :BDTIPOLANCFILIAL, :BDCONTABILIZACAO,
          :BDTRANSACAO, :BDTRANFECHADA, :BDOBSERVACAODEB, :BDOBSERVACAOCRE, :BDCOMPLEMENTOCOMPLETO, :BDTRANSFERIDO,
          :BDGRUPO, :BDTOTLAN, :BDAGRUPADOR, :BDCHAVEONLINE, :BDLANCAEXTEMPORANEO, :BDDATAEXTEMPORANEO, :USULAN, :USUALT,
          :BDCODEMPREENDIMENTODEB, :BDCODINUSIMOBDEB, :BDCODEMPREENDIMENTOCRE, :BDCODINUSIMOBCRE, :BDLANORIGINAL, :bdcheck, :BDDESCLANORIG,
          :BDCGCTERC, :BDCGCTERD, :BDDESCRICAO_NE
  do
  begin
    if (BDTIPOLAN = 200 and PRFOLHA <> 0 and BDCHAVEONLINE is not null and 
       ((PREXPORTTXT = 0) or (PREXPORTTXT = 1 and BDCHAVELCC is null))) then
    begin
      wteste = 'FOLHA'||bdcodemp||'.'||coalesce(BDCHAVEONLINE, '')||'.'||coalesce(BDDATA, '01/01/1000')||'.'||coalesce(BDDEBITO, 0)||'.'||coalesce(BDCREDITO, 0);
      if (WTESTE <> WTESTEAUX) then
      begin
        BDCODEMPREENDIMENTODEB = null;
        BDCODINUSIMOBDEB = null;
        BDCODEMPREENDIMENTOCRE = null;
        BDCODINUSIMOBCRE = null;
    
        wtesteaux = null;
        SELECT BDVALUE FROM TMP_VSUC_TLAN_GROUP_TEMP WHERE BDSESSAO = :prsessao AND BDCODIGO = :prcodigo AND BDVALUE = :wteste into :wtesteaux;
        if (wtesteaux is null) then
        begin
          wtesteaux = wteste;
          insert into TMP_VSUC_TLAN_GROUP_TEMP values (:prsessao, :prcodigo, :wteste);
          if (BDCHAVEONLINE is null) then
            WWHERE = 'BDCHAVEONLINE IS NULL';
          else
            WWHERE = 'BDCHAVEONLINE = ''' || BDCHAVEONLINE || '''';
  
          if (BDDATA is null) then
            WWHERE = WWHERE || ' and bddata IS NULL';
          else
            WWHERE = WWHERE || ' and bddata = ''' || BDDATA || '''';
  
          if (BDCREDITO is null) then
            WWHERE = WWHERE || ' and bdcredito IS NULL';
          else
            WWHERE = WWHERE || ' and bdcredito = ' || BDCREDITO;
  
          if (BDDEBITO is null) then
            WWHERE = WWHERE || ' and bddebito IS NULL';
          else
            WWHERE = WWHERE || ' and bddebito = ' || BDDEBITO;
        
          for select BDCHAVE,
                     case
                       when (BDCODTPCC is not null) then BDCHAVE
                       else null
                     end as BDCHAVELCC,
                     BDCODEMP, BDCODPLAPADRAO, BDCODHIST, BDLOTE, BDDATA, BDDEBITO, BDCODTERCEIROD, BDCONCD, BDCREDITO,
                           BDCODTERCEIROC, BDCONCC, BDCONCILIACAOPENDENTE, BDVALOR, BDCODTPHI,
                           iif(position('col.', BDCOMPL) > 0 and BDAGRUPADOR = 1 and :PREXPORTTXT = 1, substring(BDCOMPL from 1 for position('col.', BDCOMPL) - 1), BDCOMPL) BDCOMPL,
                           BDDCTO, BDTIPOLAN, BDDATALAN, BDHORALAN, BDCODUSU, BDCODUSUALTERACAO, BDDATALANALT, BDHORALANALT, BDTIPLAN,
                     null as BDTIPOFCONT, null as BDFILIAL, null as BDTIPOLANCFILIAL, null as BDCONTABILIZACAO,
                     (iif(:PREXPORTTXT = 1, (select first 1 BDTRANSACAO from VSUC_EMPRESAS_TLAN where bdcodemp = :BDCODEMP and bdchave = :BDCHAVE), BDTRANSACAO)),
                     BDTRANFECHADA, BDTRANSFERIDO, BDOBSERVACAODEB, BDOBSERVACAOCRE,
                     null as BDCOMPLEMENTOCOMPLETO, BDGRUPO, BDTOTLAN, BDAGRUPADOR, BDCHAVEONLINE,
                     null as BDLANCAEXTEMPORANEO, null as BDDATAEXTEMPORANEO, null as USULAN, null as USUALT

              from  VSUC_SP_EMP_TLAN_RH_GROUP_NEW(:bdcodemp, :prchaveonline, :prdatafolha, :prdebito, :prcredito, :wwhere)
              order by BDDATA desc, BDCHAVEONLINE, BDGRUPO, BDAGRUPADOR desc, BDDEBITO, BDCREDITO, BDDATALAN, BDHORALAN
              into :BDCHAVE, :BDCHAVELCC, :BDCODEMP, :BDCODPLAPADRAO, :BDCODHIST, :BDLOTE, :BDDATA, :BDDEBITO,
                   :BDCODTERCEIROD, :BDCONCD, :BDCREDITO, :BDCODTERCEIROC, :BDCONCC, :BDCONCILIACAOPENDENTE, :BDVALOR,
                   :BDCODTPHI, :BDCOMPL, :BDDCTO, :BDTIPOLAN, :BDDATALAN, :BDHORALAN, :BDCODUSU, :BDCODUSUALTERACAO,
                   :BDDATALANALT, :BDHORALANALT, :BDTIPLAN, :BDTIPOFCONT, :BDFILIAL, :BDTIPOLANCFILIAL, :BDCONTABILIZACAO,
                   :BDTRANSACAO, :BDTRANFECHADA, :BDOBSERVACAODEB, :BDOBSERVACAOCRE, :BDCOMPLEMENTOCOMPLETO,
                   :BDTRANSFERIDO, :BDGRUPO, :BDTOTLAN, :BDAGRUPADOR, :BDCHAVEONLINE, :BDLANCAEXTEMPORANEO,
                   :BDDATAEXTEMPORANEO, :USULAN, :USUALT
          do
            suspend;
        end
      end
    end
    else
    if (BDTIPOLAN = 100 and PRFISCAL <> 0) then
    begin
      wteste = 'FISCAL'||COALESCE(BDTRANSACAO, 0)||'.'||coalesce(BDDATA, '01/01/1000');
      if (WTESTE <> WTESTEAUX) then
      begin
        BDCODEMPREENDIMENTODEB = null;
        BDCODINUSIMOBDEB = null;
        BDCODEMPREENDIMENTOCRE = null;
        BDCODINUSIMOBCRE = null;
        
        wtesteaux = null;
        SELECT BDVALUE FROM TMP_VSUC_TLAN_GROUP_TEMP WHERE BDSESSAO = :prsessao AND BDCODIGO = :prcodigo AND BDVALUE = :wteste into :wtesteaux;
        if (wtesteaux is null) then
        begin
          wtesteaux = wteste;
          insert into TMP_VSUC_TLAN_GROUP_TEMP values (:prsessao, :prcodigo, :wteste);
          if (bdtransacao is null) then
            wwhere = 'BDTRANSACAO is null ';
          else
            wwhere = 'BDTRANSACAO = ' || BDTRANSACAO;
          wwhere = wwhere||' and bddata = ''' || BDDATA || '''';
          for select BDCHAVE,
                     case
                       when (BDCODTPCC is not null) then BDCHAVE
                       else null
                     end as BDCHAVELCC,
                     BDCODEMP, BDCODPLAPADRAO, BDCODHIST, BDLOTE, BDDATA, BDDEBITO, BDCODTERCEIROD, BDCONCD, BDCREDITO,
                     BDCODTERCEIROC, BDCONCC, BDCONCILIACAOPENDENTE, BDVALOR, BDCODTPHI, BDCOMPL, BDDCTO, BDTIPOLAN,
                     BDDATALAN, BDHORALAN, BDCODUSU, BDCODUSUALTERACAO, BDDATALANALT, BDHORALANALT, BDTIPLAN,
                     null as BDTIPOFCONT, null as BDFILIAL, null as BDTIPOLANCFILIAL, null as BDCONTABILIZACAO,
                     BDTRANSACAO, BDTRANFECHADA, BDTRANSFERIDO, BDOBSERVACAODEB, BDOBSERVACAOCRE,
                     null as BDCOMPLEMENTOCOMPLETO, BDGRUPO, BDTOTLAN, BDAGRUPADOR, BDCHAVEONLINE,
                     null as BDLANCAEXTEMPORANEO, null as BDDATAEXTEMPORANEO, null as USULAN, null as USUALT
              from  VSUC_SP_EMP_TLAN_EF_GROUP_NEW(:PREMPRESAS, '100', 99, :PRDATAFISCAL, :PRTRANSACAO, null, :wwhere)
              into :BDCHAVE, :BDCHAVELCC, :BDCODEMP, :BDCODPLAPADRAO, :BDCODHIST, :BDLOTE, :BDDATA, :BDDEBITO,
                   :BDCODTERCEIROD, :BDCONCD, :BDCREDITO, :BDCODTERCEIROC, :BDCONCC, :BDCONCILIACAOPENDENTE, :BDVALOR,
                   :BDCODTPHI, :BDCOMPL, :BDDCTO, :BDTIPOLAN, :BDDATALAN, :BDHORALAN, :BDCODUSU, :BDCODUSUALTERACAO,
                   :BDDATALANALT, :BDHORALANALT, :BDTIPLAN, :BDTIPOFCONT, :BDFILIAL, :BDTIPOLANCFILIAL, :BDCONTABILIZACAO,
                   :BDTRANSACAO, :BDTRANFECHADA, :BDOBSERVACAODEB, :BDOBSERVACAOCRE, :BDCOMPLEMENTOCOMPLETO,
                   :BDTRANSFERIDO, :BDGRUPO, :BDTOTLAN, :BDAGRUPADOR, :BDCHAVEONLINE, :BDLANCAEXTEMPORANEO,
                   :BDDATAEXTEMPORANEO, :USULAN, :USUALT
          do
            suspend;
        end
      end
    end
    else
      begin     
        bdgrupo = null;
        suspend;
      end
  end
end
^

CREATE OR ALTER PROCEDURE VSUC_LANCAMENTOS_EF_AGRUPADOS(
    PRCODEMP VARCHAR(1024),
    PRTIPOLAN VARCHAR(100),
    PRCONTABILIZACAO INTEGER,
    PRDATA DATE,
    PRTRANSACAO INTEGER,
    PRCODTPCC VARCHAR(8192) = NULL)
RETURNS (
    BDCODEMP INTEGER,
    BDCHAVE INTEGER,
    BDCODPLAPADRAO INTEGER,
    BDCODHIST INTEGER,
    BDLOTE VARCHAR(10),
    BDDATA DATE,
    BDDEBITO INTEGER,
    BDCONCD VARCHAR(5),
    BDCREDITO INTEGER,
    BDCONCC VARCHAR(5),
    BDVALOR NUMERIC(15,2),
    BDDATALAN DATE,
    BDHORALAN TIME,
    BDDATALANALT DATE,
    BDHORALANALT TIME,
    BDCODUSU INTEGER,
    BDCODUSUALTERACAO INTEGER,
    BDCODTPHI INTEGER,
    BDNOMEHIST VARCHAR(100),
    BDCOMPL VARCHAR(200),
    BDDCTO VARCHAR(15),
    BDCODTERCEIROD INTEGER,
    BDCODTERCEIROC INTEGER,
    BDTIPLAN VARCHAR(100),
    BDTRANSFERIDO INTEGER,
    BDGRUPO INTEGER,
    BDTOTLAN INTEGER,
    BDAGRUPADOR INTEGER,
    BDTIPOLAN INTEGER,
    BDCHAVEONLINE VARCHAR(120),
    BDCODTPCC INTEGER,
    BDTRANSACAO INTEGER,
    BDTRANFECHADA VARCHAR(5),
    BDCONCILIACAOPENDENTE INTEGER,
    BDOBSERVACAODEB TYPE OF COLUMN VSUC_EMPRESAS_TOBS.BDOBSERVACAO,
    BDOBSERVACAOCRE TYPE OF COLUMN VSUC_EMPRESAS_TOBS.BDOBSERVACAO)
AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WTRANSANT INTEGER;
BEGIN
  wsql = 'select * from (';
  wsql = wsql||'select lan.bdcodemp, lan.bdcodplapadrao, max(lan.bdcodhist) as bdcodhist, lan.bddata, lan.BDTRANSACAO, lan.bdtipolan, tip.bddescricao as bdTIPLAN, ';
  wSQL = wSQL||'max(lan.BDDEBITO) as BDDEBITO, max(lan.BDCREDITO) as BDCREDITO, max(lan.BDCODTPHI) as BDCODTPHI, ';
  wsql = wsql||'min(lan.BDCHAVE) as BDCHAVE, count(lan.bdchave) as BDCOUNT, 1 as bagrupador, ';

  wSQL = wSQL||'max(lan.BDLOTE) as BDLOTE, null as BDCONCD, null as BDCONCC, null as BDDATALAN, null as BDHORALAN, null as BDDATALANALT, ';
  wSQL = wSQL||'null as BDHORALANALT, null as BDCODUSU, null as BDCODUSUALTERACAO, null as BDNOMEHIST, max(lan.BDCOMPL) as BDCOMPL, ';
  wSQL = wSQL||'max(lan.BDDCTO) as BDDCTO, max(lan.BDCODTERCEIROD) as BDCODTERCEIROD, max(lan.BDCODTERCEIROC) as BDCODTERCEIROC, null as BDTRANFECHADA, null as BDTRANSFERIDO, ';
  wSQL = wSQL||'null as BDCONCILIACAOPENDENTE, null as BDOBSERVACAODEB, null as BDOBSERVACAOCRE, ';

  IF (prcodtpcc IS NULL OR (prcodtpcc = '')) THEN
     BEGIN
       wsql = wsql||'avg(lan.bdvalor) as BDVALOR, null as bdcodtpcc ';
       wsql = wsql||'from VSUC_EMPRESAS_TLAN lan ';
     END
  ELSE
     BEGIN
       wsql = wsql||'avg(tlcc.BDVALOR) as BDVALOR, tlcc.bdcodtpcc from vsuc_empresas_tlcc tlcc ';
       wsql = wsql||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
     END
  wsql = wsql||'left outer join tipos_lancamentos_padrao tip on (tip.bdcodtipo = lan.bdtipolan) ';
  wsql = wsql||'left outer join vsuc_empresas_translan trans on ((trans.bdcodemp = lan.bdcodemp and trans.bdchave = lan.bdchave) or (trans.bdcodemprec = lan.bdcodemp and trans.bdchaverec = lan.bdchave)) ';
  wsql = wsql||'WHERE (lan.bdtipolan in ('||prtipolan||')) ';
  
  IF (prcodtpcc IS NOT NULL AND (prcodtpcc <> '')) THEN
     wsql = wsql||' and tlcc.bdcodtpcc in ('||prcodtpcc||')';

  --1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (lan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';

  wsql = wsql||'and ((lan.BDDEBITO is null) or (lan.BDCREDITO is null)) ';
  wsql = wsql||'and (lan.BDTRANFECHADA = ''TRUE'') ';
  wsql = wsql||'and (lan.BDCODEMP in ('||prcodemp||')) ';
  wsql = wsql||'group by lan.bdcodemp, lan.bdcodplapadrao, lan.bdtipolan, lan.bddata, lan.BDTRANSACAO, tip.bddescricao ';
  wsql = wsql||'having (count(lan.bdchave) = 2) and (sum(case when BDDEBITO is null then 0 else BDVALOR end) = sum(case when BDCREDITO is null then 0 else BDVALOR end))';
  
  wsql = wsql||' union '; /**********************************************************************************************************************************************/

  wSQL = wSQL||'select lan.bdcodemp, lan.bdcodplapadrao, lan.bdcodhist, lan.bddata, lan.BDTRANSACAO, lan.bdtipolan, tip.bddescricao as bdTIPLAN, ';
  wSQL = wSQL||'lan.BDDEBITO, lan.BDCREDITO, lan.BDCODTPHI, ';
  wsql = wsql||'lan.bdchave, 1 as BDCOUNT, 0 as bagrupador, ';

  wSQL = wSQL||'BDLOTE, BDCONCD, BDCONCC, BDDATALAN, BDHORALAN, BDDATALANALT, BDHORALANALT, BDCODUSU, BDCODUSUALTERACAO, ';
  wSQL = wSQL||'null as BDNOMEHIST, BDCOMPL, BDDCTO, BDCODTERCEIROD, BDCODTERCEIROC, BDTRANFECHADA, ';
  wSQL = wSQL||'case when (lan.bdcodemp = trans.bdcodemp) then trans.bdcodemprec when (lan.bdcodemp = trans.bdcodemprec) then trans.bdcodemp end BDTRANSFERIDO, ';
  wSQL = wSQL||'lan.BDCONCILIACAOPENDENTE, tObsDeb.BDOBSERVACAO as BDOBSERVACAODEB, tobsCre.BDOBSERVACAO as BDOBSERVACAOCRE, ';
  IF (prcodtpcc IS NULL OR (prcodtpcc = '')) THEN
     BEGIN
       wSQL = wSQL||'lan.bdvalor, null as bdcodtpcc ';
       wSQL = wSQL||'from VSUC_EMPRESAS_TLAN lan ';
     END
  ELSE
     BEGIN
       wSQL = wSQL||'tlcc.BDVALOR, tlcc.bdcodtpcc from vsuc_empresas_tlcc tlcc ';
       wSQL = wSQL||'inner join vsuc_empresas_tlan tlan on (tlan.bdcodemp = tlcc.bdcodemp and tlan.bdchave = tlcc.bdchave) ';
     END
  wSQL = wSQL||'left outer join tipos_lancamentos_padrao tip on (tip.bdcodtipo = lan.bdtipolan) ';
  wSQL = wSQL||'left outer join vsuc_empresas_translan trans on ((trans.bdcodemp = lan.bdcodemp and trans.bdchave = lan.bdchave) or (trans.bdcodemprec = lan.bdcodemp and trans.bdchaverec = lan.bdchave)) ';
  wSQL = wSQL||'left join VSUC_EMPRESAS_TOBS tObsDeb on (tObsDeb.BDCODEMP = lan.BDCODEMP and tObsDeb.BDCHAVE = lan.BDCHAVE and tObsDeb.BDDEBCRE = 0) ';
  wSQL = wSQL||'left join VSUC_EMPRESAS_TOBS tObsCre on (tObsCre.BDCODEMP = lan.BDCODEMP and tObsCre.BDCHAVE = lan.BDCHAVE and tObsCre.BDDEBCRE = 1) ';
  wSQL = wSQL||'where (lan.bdtipolan in ('||prtipolan||')) ';
  
  IF (prcodtpcc IS NOT NULL AND (prcodtpcc <> '')) THEN
     wsql = wsql||' and tlcc.bdcodtpcc in ('||prcodtpcc||')';

  --1 -> Fiscal | 2 -> Societário | 99 -> Todos
  IF (prcontabilizacao <> 99) THEN
    wsql = wsql||'and (lan.bdcontabilizacao in (0,'||prcontabilizacao||')) ';
  wsql = wsql||'and (lan.BDCODEMP in ('||prcodemp||')) ';


  wsql = wsql||') order by BDTRANSACAO, BDDATA, BAGRUPADOR DESC ';
  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodplapadrao, :bdcodhist, :bddata, :bdtransacao, :bdtipolan, :bdtiplan,
                                  :bddebito, :bdcredito, :bdcodtphi,
                                  :bdchave, :bdtotlan, :bdagrupador,
                                  :BDLOTE, :BDCONCD, :BDCONCC, :BDDATALAN, :BDHORALAN, :BDDATALANALT, :BDHORALANALT, :BDCODUSU, :BDCODUSUALTERACAO,
                                  :BDNOMEHIST, :BDCOMPL, :BDDCTO, :BDCODTERCEIROD, :BDCODTERCEIROC, :BDTRANFECHADA, :BDTRANSFERIDO,
                                  :bdconciliacaopendente, :bdobservacaodeb, :bdobservacaocre, :bdvalor, :bdcodtpcc DO
    BEGIN
      BDGRUPO = BDTRANSACAO;

      IF ((BDAGRUPADOR = 1) OR (BDTRANSACAO IS NULL) OR (BDTRANSACAO <> wTransAnt) OR ((BDTRANSACAO = prTRANSACAO) AND (BDDATA = prDATA))) THEN
        SUSPEND;

      wTransAnt = BDTRANSACAO;
    END
END^

create OR ALTER procedure VSUC_SP_CONCILIACAO (
    PRCODEMP varchar(2000),
    PRCODPLAPADRAO integer,
    PRCLASSINI type of column PLANOS_TPLA.BDCTALON,
    PRTERCEIROINI integer,
    PRCLASSFIM type of column PLANOS_TPLA.BDCTALON,
    PRTERCEIROFIM integer,
    PRDEBCRE integer,
    PRDATAINI date,
    PRDATAFIM date,
    PRCOMPARANRDOC DM_BOOLEAN,
    PRCONSIDERAZERO DM_BOOLEAN,
    PRCOMPARADATA DM_BOOLEAN,
    PRVALOREXATO DM_BOOLEAN,
    PRRECONCILIAR DM_BOOLEAN,
    PRAGRUPARPARTICIPANTECNPJ DM_BOOLEAN,
    PRAGRUPARPARTICIPANTECPF DM_BOOLEAN,
    PRNRODOCCOMPL boolean)
returns (
    BDCODEMP integer,
    BDCHAVE integer,
    BDTIPOLANCFILIAL smallint)
as
declare variable WSQL2 DM_MAXVARCHAR;
declare variable WCOD integer;
declare variable WSQL DM_MAXVARCHAR;
declare variable WSQL1 DM_MAXVARCHAR;
declare variable WSQLPRINCIPAL DM_MAXVARCHAR;
declare variable WSQLSECUNDARIO DM_MAXVARCHAR;
declare variable WSQLUPDATE varchar(500);
declare variable WSQLDEBITO varchar(1000);
declare variable WSQLCREDITO varchar(1000);
declare variable WSQLAUX DM_MAXVARCHAR;
declare variable WCONTA integer;
declare variable WCONTAANT integer;
declare variable WTERCEIRO integer;
declare variable WTERCEIROANT integer;
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WDCTO DM_BDDCTO;
declare variable WDCTOANT DM_BDDCTO;
declare variable WDATA date;
declare variable WDATAANT date;
declare variable WDEBITO integer;
declare variable WTERCEIRODEB integer;
declare variable WCREDITO integer;
declare variable WTERCEIROCRE integer;
declare variable WVALOR decimal(15,2);
declare variable WVALORDEB decimal(15,2);
declare variable WVALORCRE decimal(15,2);
declare variable WTIPOLANCFILIAL integer;
declare variable WCODEMPSEC integer;
declare variable WCHAVESEC integer;
declare variable WTIPOLANCFILIALSEC integer;
declare variable WVALORSEC decimal(15,2);
declare variable WCNPJRAIZ varchar(18);
declare variable WTERAGRUP blob sub_type 1 segment size 20;
declare variable WCNPJRAIZD varchar(18);
declare variable WCNPJRAIZC varchar(18);
declare variable WCPF varchar(18);
declare variable WCNPJCPF varchar(18);
declare variable WCNPJCPFANT varchar(18);
declare variable WDCTOCOMPL DM_BDDCTO;
declare variable WDCTOCOMPLANT DM_BDDCTO;
BEGIN
  DELETE FROM LISTA_LANC WHERE BDCODEMP IS NOT NULL;

  wCONTAANT = 0;
  wTERCEIROANT = 0;
  wDCTOANT = '';
  wDATAANT = '01/01/1900';
  wVALORDEB = 0.00;
  wVALORCRE = 0.00;
  prComparaNrDoc = UPPER(prComparaNrDoc);
  prCONSIDERAZERO = UPPER(prCONSIDERAZERO);
  PRCOMPARADATA = UPPER(PRCOMPARADATA);
  PRVALOREXATO = UPPER(PRVALOREXATO);
  PRRECONCILIAR = UPPER(PRRECONCILIAR);
  pragruparparticipantecnpj = UPPER(pragruparparticipantecnpj);
  pragruparparticipantecpf = UPPER(pragruparparticipantecpf);
  wDctoComplAnt = '';
  --Faz um laço de todas as contas (entre a classificação inicial e final) e todos os participantes (entre o participante inicial e final)
  wSQL = 'select cta.BDCODTPLA, ';
  IF ((prterceiroini IS NOT NULL) AND (prterceiroini > 0) AND (prterceirofim IS NOT NULL) AND (prterceirofim > 0)) THEN
    begin
      wSQL = wSQL||' TER.BDCODTER,';
      wSQL = wSQL||' TER.BDCGCTER';
    end
  ELSE
    BEGIN
      wSQL = wSQL||' null as BDCODTER,';
      wSQL = wSQL||' null as BDCGCTER';
    END
  wSQL = wSQL||' from PLANOS_TPLA cta';
  IF ((prterceiroini IS NOT NULL) AND (prterceiroini > 0) AND (prterceirofim IS NOT NULL) AND (prterceirofim > 0)) THEN
  begin
    --wSQL2 = 'select list(CODTERCEIRO) from (select BDCODTERCEIROD as CODTERCEIRO';
    wSQL2 = 'insert into TLIST_FORN (BDCODFOR) ';
    wsql2 = wSQL2 || 'select BDCODTERCEIROD as CODTERCEIRO ';
    wSQL2 = wSQL2 || '    from VSUC_EMPRESAS_TLAN';
    wSQL2 = wSQL2 || '    where ';
    wSQL2 = wSQL2 || '          (BDDATA between ''' || prdataini ||''' and ''' || prdatafim || ''') and';
    wSQL2 = wSQL2 || '          (((BDCODEMP in ('||prCODEMP||')) ))';
    wSQL2 = wSQL2 || 'group by BDCODTERCEIROD';
    wSQL2 = wSQL2 || ' having BDCODTERCEIROD is not null ';
    wSQL2 = wSQL2 || ' union '; --union mesmo e não union all
    wSQL2 = wSQL2 || ' select BDCODTERCEIROC as CODTERCEIRO';
    wSQL2 = wSQL2 || '    from VSUC_EMPRESAS_TLAN';
    wSQL2 = wSQL2 || '    where ';
    wSQL2 = wSQL2 || '          (BDDATA between ''' || prdataini ||''' and ''' || prdatafim || ''') and';
    wSQL2 = wSQL2 || '          (((BDCODEMP in ('||prCODEMP||')) ))';
    wSQL2 = wSQL2 || 'group by BDCODTERCEIROC';
    wSQL2 = wSQL2 || ' having BDCODTERCEIROC is not null ';
    ---Leonardo Pereira - 19/10/2020 - estava dando erro no in com muitos números
    execute statement wSQL2;-- into :wlist;
    wSQL = wSQL||' join VW_TTERCEIRO ter on (cta.BDPARTICIPANTE = 1 and ter.BDCODTER between '||:prTERCEIROINI||' and '||:prTERCEIROFIM||')'; --and ter.BDCODTER in (' || :wlist || ')';
    wSQL = wSQL||' inner join TLIST_FORN FORN on (TER.BDCODTER = FORN.BDCODFOR) ';
  end
  wSQL = wSQL||' where cta.BDCODPLAPADRAO = '||:prCodPlaPadrao||' and cta.BDCTALON between '''||:prCLASSINI||''' and '''||:prCLASSFIM||'''';
  IF ((prterceiroini IS NOT NULL) AND (prterceiroini > 0) AND (prterceirofim IS NOT NULL) AND (prterceirofim > 0)) THEN
    BEGIN
  wSQL = wSQL||' and ter.bdcodpais = 30';
  wSQL = wSQL||' order by cta.BDCTALON, ter.BDCGCTER, ter.BDCODTER';
    end
  else
    wSQL = wSQL||' order by BDCGCTER, cta.BDCTALON, BDCODTER';

  FOR EXECUTE STATEMENT wSQL INTO :wConta, :wTerceiro, :wcnpjcpf DO
    BEGIN

      if ((:wcnpjcpf <> :wcnpjcpfAnt) or (:wcnpjcpfAnt is null)) then
        begin
          wSQL1 = 'insert into tmp_tterceiro_aux (bdcodter)';
          wSQL1 = wSQL1 || 'select bdcodter';
          wSQL1 = wSQL1 || ' from TTERCEIRO ';
          wSQL1 = wSQL1 || ' where (BDCODTER between '||:prTERCEIROINI||' and '||:prTERCEIROFIM||')';
          DELETE FROM TMP_TTERCEIRO_AUX;
    
          if ((pragruparparticipantecnpj = 'TRUE') and (CHAR_LENGTH(TRIM(:wcnpjcpf)) = 18)) then
            BEGIN
              :wcnpjraiz = substring(:wcnpjcpf from 1 for 10);
              wSQL1 = wSQL1 || ' and bdcgcter like '''||:wcnpjraiz||'%''';
              EXECUTE STATEMENT wSQL1;
              :wteragrup = 'SELECT BDCODTER FROM tmp_tterceiro_aux';
            END
          else
          if ((pragruparparticipantecpf = 'TRUE') AND (CHAR_LENGTH(TRIM(:wcnpjcpf)) = 14)) THEN
            BEGIN
              :wcpf = :wcnpjcpf;
              wSQL1 = wSQL1 || ' and bdcgcter = '''||:wcpf||'''';
              EXECUTE STATEMENT wSQL1;
            
              :wteragrup = 'SELECT BDCODTER FROM tmp_tterceiro_aux';
            END
        end
      ELSE
        :wteragrup = NULL;
      --*************************************************************************************************************************************************
      --/alt:14942 - 25/01/2017 - Sempre que alterar uma regra de conciliação, alterar também no uConciliacaoClientesFornecedores > SetConciliacaoCliFor e
      --/    SetConciliacaoEmMemoria, uConsultaLancamento, uConsultaRazaoVideo e as procedures VSUC_SP_CONCILIACAO e VSUC_SP_CONCILIACAO_AUTOMATICA. Pedro
      --***********************************************************************************************************************************************
      --Se marcado para reconciliar, atualiza os lançamentos marcando todos como desconciliados no período e conta informados
      IF (prRECONCILIAR = 'TRUE') THEN
        BEGIN
          wSQL = 'update VSUC_EMPRESAS_TLAN set BDCONCD = null, BDCONCC = null, BDTIPOCONC = 0';      --#alt:13456 - adicionado indice nenhum ao tipo de conciliação. Ana - 28/10/2016
          wSQL = wSQL||' where (BDDATA >= '''||:prDATAINI||''') and (BDDATA <= '''||:prDATAFIM||''')';
          wSQL = wSQL||' and (BDCODEMP in ('||:prCODEMP||'))';
          IF ((wTERCEIRO IS NULL) OR (wTERCEIRO = 0)) THEN
            wSQL = wSQL||' and ((BDDEBITO = '||:wConta||') or (BDCREDITO = '||:wConta||'))';
          ELSE
            BEGIN
              wSQL = wSQL||' and (((BDDEBITO = '||:wConta||') and (BDCODTERCEIROD IN ('||COALESCE(:wteragrup,:wTERCEIRO)||')))';
              wSQL = wSQL||'   or ((BDCREDITO = '||:wConta||') and (BDCODTERCEIROC IN ('||COALESCE(:wteragrup,:wTERCEIRO)||'))))';
            END
          wSQL = wSQL||' and ((bdtipoconc >=4) or (bdtipoconc = 0)) ';       --#alt:13456 - Permite reconciliar apenas as conciliações automáticas. Ana - 28/10/2016
          EXECUTE STATEMENT wSQL;
        END
      --Faz um select para retornar todos os lançamentos no período que podem ser conciliados
      --alt:17706 - 03/05/2017 - Criado tratamento no documento para desconsiderar números/caracteres depois dos símbolos "/", "\" ou "-". Pedro
      wSQL = 'select EMP.BDCODEMP, EMP.BDCHAVE, EMP.BDDEBITO, EMP.BDCODTERCEIROD, EMP.BDCREDITO, EMP.BDCODTERCEIROC, EMP.BDVALOR, EMP.BDTIPOLANCFILIAL, EMP.BDDATA, ';
      wSQLAux = 'Substring(bddcto from 1 for';
      wSQLAux = wSQLAux||' case when (bddcto containing '''||'/'||''') then position('''||'/'||''', bddcto) -1';
      wSQLAux = wSQLAux||'      when (bddcto containing '''||'\'||''') then position('''||'\'||''', bddcto) -1';
      wSQLAux = wSQLAux||'      when (bddcto containing '''||'-'||''') then position('''||'-'||''', bddcto) -1';
      wSQLAux = wSQLAux||' else char_length(bddcto) end)';
      IF (prCONSIDERAZERO = 'TRUE') THEN
        wSQL = wSQL||wSQLAux||' as BDDCTO,';
      ELSE
        wSQL = wSQL||'lpad('||wSQLAux||', 15, ''0'') as BDDCTO,';
      if (CHAR_LENGTH(TRIM(:wcnpjcpf)) = 18) then
        wSQL = wSQL||' substring(ter.BDCGCTER from 1 for 10) AS BDCGCTER,';
      else
        wSQL = wSQL||' ter.BDCGCTER AS BDCGCTER,';


      if (PRNRODOCCOMPL) then
        wSQL = wSQL||' (select WNUMERODCTO from SP_PRIMEIRO_NUMERO(EMP.BDCOMPL)) BDCOMPL';
      else
        WSQL = WSQL||' null as BDCOMPL';
        
      wSQL = wSQL||' from VSUC_EMPRESAS_TLAN EMP';
      IF ((wTERCEIRO IS NULL) OR (wTERCEIRO = 0)) THEN --Se NÃO está fazendo o laço numa conta de participante
        wSQL = wSQL||' LEFT JOIN TTERCEIRO TER ON ((EMP.BDCODTERCEIROD <> 0 AND EMP.BDCODTERCEIROD = TER.BDCODTER) OR (EMP.BDCODTERCEIROC <> 0 AND EMP.BDCODTERCEIROC = TER.BDCODTER))';
      else
        wSQL = wSQL||' LEFT JOIN TTERCEIRO TER ON ((EMP.BDCODTERCEIROD in ('||COALESCE(:wteragrup,:wTERCEIRO)||') AND EMP.BDCODTERCEIROD = TER.BDCODTER) OR (EMP.BDCODTERCEIROC in ('||COALESCE(:wteragrup,:wTERCEIRO)||') AND EMP.BDCODTERCEIROC = TER.BDCODTER))';
      wSQL = wSQL||' where (EMP.BDCONTABILIZACAO +0 in (0,1))';
      wSQL = wSQL||'   and (EMP.BDDATA between '''||:prDATAINI||''' and '''||:prDATAFIM||''')';
      IF ((wTERCEIRO IS NULL) OR (wTERCEIRO = 0)) THEN --Se NÃO está fazendo o laço numa conta de participante
        WSQLDEBITO = '   ((EMP.BDCODEMP in ('||:prCODEMP||')) and (EMP.BDDEBITO = '||:wConta||') and ((Upper(EMP.BDCONCD) = ''FALSE'') or (EMP.BDCONCD is null))) ';
      ELSE                                             --Se está fazendo o laço numa conta de participante
        WSQLDEBITO = '   ((EMP.BDCODEMP in ('||:prCODEMP||')) and (EMP.BDDEBITO = '||:wConta||') and (EMP.BDCODTERCEIROD in ('||COALESCE(:wteragrup,:wTERCEIRO)||')) and ((Upper(EMP.BDCONCD) = ''FALSE'') or (EMP.BDCONCD is null))) ';
      IF ((wTERCEIRO IS NULL) OR (wTERCEIRO = 0)) THEN --Se NÃO está fazendo o laço numa conta de participante
        WSQLCREDITO = '  ((EMP.BDCODEMP in ('||:prCODEMP||')) and (EMP.BDCREDITO = '||:wConta||') and ((Upper(EMP.BDCONCC) = ''FALSE'') or (EMP.BDCONCC is null)))';
      ELSE                                             --Se está fazendo o laço numa conta de participante
        WSQLCREDITO = '  ((EMP.BDCODEMP in ('||:prCODEMP||')) and (EMP.BDCREDITO = '||:wConta||') and (EMP.BDCODTERCEIROC in ('||COALESCE(:wteragrup,:wTERCEIRO)||')) and ((Upper(EMP.BDCONCC) = ''FALSE'') or (EMP.BDCONCC is null)))';

      --*************************************************************************************************************************************************
      --alt:14942 - 25/01/2017 - Sempre que alterar uma regra de conciliação, alterar também no uConciliacaoClientesFornecedores > SetConciliacaoCliFor e
      --    SetConciliacaoEmMemoria, uConsultaLancamento, uConsultaRazaoVideo e as procedures VSUC_SP_CONCILIACAO e VSUC_SP_CONCILIACAO_AUTOMATICA. Pedro
      --***********************************************************************************************************************************************
      --Preciso de um registro vazio no final para poder comitar o último registro oficial, senão
      --precisaria fazer toda a validação do valor e os updates replicados no final da procedure
      wSQLAux = ' union all';
      wSQLAux = wSQLAux||' select first 1 null as BDCODEMP, null as BDCHAVE, null as BDDEBITO, null as BDCODTERCEIROD, null as BDCREDITO,';
      wSQLAux = wSQLAux||' null as BDCODTERCEIROC, null as BDVALOR, null as BDTIPOLANCFILIAL, null as BDDATA, null as BDDCTO, null as BDCGCTER,';
      wSQLAux = wSQLAux||' null as BDCOMPL';

      wSQLAux = wSQLAux||' from VSUC_EMPRESAS_TLAN EMP';
      wSQLAux = wSQLAux||' LEFT JOIN TTERCEIRO TER ON ((EMP.BDCODTERCEIROD <> 0 AND EMP.BDCODTERCEIROD = TER.BDCODTER) OR (EMP.BDCODTERCEIROC <> 0 AND EMP.BDCODTERCEIROC = TER.BDCODTER)))';
      wSQLAux = wSQLAux||' order by case when BDCODEMP is null then 1 else 0 end';
      IF (prComparaNrDoc = 'TRUE') THEN --Se marcou para comparar por número de documento
        wSQLAux = wSQLAux||', BDDCTO, BDDATA';
      ELSE
      IF (PRCOMPARADATA = 'TRUE') THEN --Se marcou para comparar por data
        wSQLAux = wSQLAux||', BDDATA, BDVALOR';
      ELSE
      IF (PRNRODOCCOMPL) THEN
        wSQLAux = wSQLAux||', BDCOMPL, BDDATA';
      ELSE
        wSQLAux = wSQLAux||', BDVALOR';       --Se marcou para comparar apenas por valor exato
      --#alt:90070. Ana - 03/10/2018
      IF ((prComparaNrDoc = 'FALSE') and (PRCOMPARADATA = 'FALSE') and (PRVALOREXATO = 'TRUE')) THEN
        BEGIN
          IF (prdebcre = 0) THEN
            BEGIN
              WSQLPRINCIPAL  = 'select BDCODEMP, BDCHAVE, BDVALOR, BDTIPOLANCFILIAL, BDCGCTER from ('||wSQL||' and ('||WSQLDEBITO||'))';
              WSQLSECUNDARIO = 'select first 1 BDCODEMP, BDCHAVE, BDVALOR, BDTIPOLANCFILIAL, BDCGCTER from ('||wSQL||' and ('||WSQLCREDITO||'))';
            END
          ELSE
            BEGIN
              WSQLPRINCIPAL  = 'select BDCODEMP, BDCHAVE, BDVALOR, BDTIPOLANCFILIAL, BDCGCTER from ('||wSQL||' and ('||WSQLCREDITO||'))';
              WSQLSECUNDARIO = 'select first 1 BDCODEMP, BDCHAVE, BDVALOR, BDTIPOLANCFILIAL, BDCGCTER from ('||wSQL||' and ('||WSQLDEBITO||'))';
            END
          FOR EXECUTE STATEMENT (WSQLPRINCIPAL)
          INTO :wCODEMP, :wCHAVE, :wVALOR, :wTIPOLANCFILIAL, :wcnpjraizd DO
            BEGIN
              WVALORSEC = 0;
              wVALORCRE = 0;
              INSERT INTO LISTA_LANC (BDCODEMP, BDCHAVE, BDTIPOLANCFILIAL) VALUES (:wCODEMP, :wCHAVE, :wTIPOLANCFILIAL);
              EXECUTE STATEMENT WSQLSECUNDARIO||' where bdvalor = '||wVALOR
              INTO :wCODEMPSEC, :wCHAVESEC, :wVALORSEC, :wTIPOLANCFILIALSEC, :wcnpjraizc;
              IF (wVALORSEC > 0) THEN
                INSERT INTO LISTA_LANC (BDCODEMP, BDCHAVE, BDTIPOLANCFILIAL) VALUES (:wCODEMPSEC, :wCHAVESEC, :wTIPOLANCFILIALSEC);
              IF ((wVALOR = wVALORSEC) AND (wVALOR > 0)) THEN
                BEGIN
                  FOR SELECT BDCODEMP, BDCHAVE, BDTIPOLANCFILIAL FROM LISTA_LANC INTO :BDCODEMP, :BDCHAVE, :BDTIPOLANCFILIAL DO
                    BEGIN
                      --Atualiza o lançamento como conciliado no caso do débito
                      WSQLUPDATE = 'update VSUC_EMPRESAS_TLAN set BDCONCD = '''||'TRUE'||''', ';
                      WSQLUPDATE = WSQLUPDATE||' bdtipoconc = case';
                      WSQLUPDATE = WSQLUPDATE||'   when ((bdconcc is null) or ((upper(bdconcc)= '''||'FALSE'||''')))then 4 ';
                      WSQLUPDATE = WSQLUPDATE||'   when (bdtipoconc = 8)  or (bdtipoconc = 5) then 6 ';
                      WSQLUPDATE = WSQLUPDATE||'   when (bdtipoconc = 2)  or (bdtipoconc = 3) then 7';
                      WSQLUPDATE = WSQLUPDATE||'   else bdtipoconc ';
                      WSQLUPDATE = WSQLUPDATE||' end ';
                      WSQLUPDATE = WSQLUPDATE||' where (BDCHAVE = '||:BDCHAVE||') and (BDCODEMP = '||:BDCODEMP||')';
                      WSQLUPDATE = WSQLUPDATE||' and (BDDEBITO = '||:wConta||') and ((Upper(BDCONCD) = '''||'FALSE'||''') or (BDCONCD is null))';
                      IF ((wTERCEIRO IS NOT NULL) AND (wTERCEIRO > 0)) THEN
                        WSQLUPDATE = WSQLUPDATE||' and (BDCODTERCEIROD in ('||COALESCE(:wteragrup,:wTERCEIRO)||'));';
                      EXECUTE STATEMENT WSQLUPDATE;
                      --Atualiza o lançamento como conciliado no caso do crédito
                      WSQLUPDATE = 'update VSUC_EMPRESAS_TLAN set BDCONCC = '''||'TRUE'||''', ';
                      WSQLUPDATE = WSQLUPDATE||' bdtipoconc = case';
                      WSQLUPDATE = WSQLUPDATE||'   when ((bdconcd is null) or ((upper(bdconcd) = '''||'FALSE'||''')))then 5 ';
                      WSQLUPDATE = WSQLUPDATE||'   when (bdtipoconc = 7)  or (bdtipoconc = 4) then 6 ';
                      WSQLUPDATE = WSQLUPDATE||'   when (bdtipoconc = 1)  or (bdtipoconc = 3) then 8 ';
                      WSQLUPDATE = WSQLUPDATE||'   else bdtipoconc ';
                      WSQLUPDATE = WSQLUPDATE||' end ';
                      WSQLUPDATE = WSQLUPDATE||' where (BDCHAVE = '||:BDCHAVE||') and (BDCODEMP = '||:BDCODEMP||')';
                      WSQLUPDATE = WSQLUPDATE||' and (BDCREDITO = '||:wConta||') and ((Upper(BDCONCC) = '''||'FALSE'||''') or (BDCONCC is null))';
                      IF ((wTERCEIRO IS NOT NULL) AND (wTERCEIRO > 0)) THEN
                        WSQLUPDATE = WSQLUPDATE||' and (BDCODTERCEIROC in ('||COALESCE(:wteragrup,:wTERCEIRO)||'));';
                      EXECUTE STATEMENT WSQLUPDATE;
                      SUSPEND;
                    END
                END
              DELETE FROM LISTA_LANC WHERE BDCODEMP IS NOT NULL;
            END
        END
      --#alt:90070. fim
      ELSE
        BEGIN
          FOR EXECUTE STATEMENT ('select * from ('||wSQL||' and ('||WSQLDEBITO||' or '||WSQLCREDITO||')'||wSQLAux)
          INTO :wCODEMP, :wCHAVE, :wDEBITO, :wTERCEIRODEB, :wCREDITO, :wTERCEIROCRE, :wVALOR, :wTIPOLANCFILIAL, :wDATA, :wDCTO, :wcnpjraizd, :wDctoCompl DO
            BEGIN
              IF ((wConta <> COALESCE(wContaANT, 0)) OR ((wCONTA <> wDEBITO) AND (wCONTA <> wCREDITO))      --Se o laço passou para a próxima conta
                 OR (
                    IIF(((pragruparparticipantecnpj = 'TRUE') and (CHAR_LENGTH(TRIM(:wcnpjraizd)) = 10)),
                    (:wcnpjraizd <> :wcnpjraiz),IIF(((pragruparparticipantecpf = 'TRUE') and (CHAR_LENGTH(TRIM(:wcnpjraizd)) = 14)),(:wcnpjraizd <> :wcpf),
                    ((COALESCE(wTerceiro, 0) <> COALESCE(wTerceiroANT, 0))                                  --Se o laço trocou de participante
                     OR (wTERCEIRO IS NOT NULL) AND (((wCONTA = wDEBITO) AND (wTERCEIRO <> wTERCEIRODEB))
                                                  OR ((wCONTA = wCREDITO) AND (wTERCEIRO <> wTERCEIROCRE))) --Se passou para o próximo participante
                    ))))
                 OR ((prValorExato = 'TRUE') AND (wVALORDEB > 0) AND (wVALORCRE > 0))                       --Se marcou para validar o valor exato
                 OR ((prComparaData = 'TRUE') AND (wDATA <> wDATAANT))                                      --Se marcou para validar data
                 OR ((prComparaNrDoc = 'TRUE') AND (COALESCE(wDCTO, '') <> COALESCE(wDCTOANT, '')))         --Se marcou para validar documento
                 OR ((prNroDocCompl = 'TRUE') AND (COALESCE(wDctoCompl, '') <> COALESCE(wDctoComplAnt, '')))--Se marcou para validar documento dentro do complemento
                 ) THEN
                BEGIN
                  IF ((wVALORDEB = wVALORCRE) AND (wVALORDEB > 0)) THEN
                    BEGIN
                      FOR SELECT BDCODEMP, BDCHAVE, BDTIPOLANCFILIAL FROM LISTA_LANC INTO :BDCODEMP, :BDCHAVE, :BDTIPOLANCFILIAL DO
                        BEGIN
                          --Atualiza o lançamento como conciliado no caso do débito
                          wSQL = 'update VSUC_EMPRESAS_TLAN set BDCONCD = '''||'TRUE'||''', ';
                          --#alt:13456 - adicionado indice para o tipo de conciliação. Ana - 28/10/2016
                          wSQL = wSQL||' bdtipoconc = case';
                          wSQL = wSQL||'   when ((bdconcc is null) or ((upper(bdconcc) = '''||'FALSE'||''')))then 4 ';
                          wSQL = wSQL||'   when (bdtipoconc = 8)  or (bdtipoconc = 5) then 6 ';
                          wSQL = wSQL||'   when (bdtipoconc = 2)  or (bdtipoconc = 3) then 7';
                          wSQL = wSQL||'   else bdtipoconc ';
                          wSQL = wSQL||' end ';
                          --#alt:13456. fim
                          wSQL = wSQL||' where (BDCHAVE = '||:BDCHAVE||') and (BDCODEMP = '||:BDCODEMP||')';  --#alt:13456 - adicionado indice Conciliado automaticamente débito e crédito. Ana - 28/10/2016
                          wSQL = wSQL||' and (BDDEBITO = '||:wConta||') and ((Upper(BDCONCD) = '''||'FALSE'||''') or (BDCONCD is null))';
                          IF ((wTERCEIRO IS NOT NULL) AND (wTERCEIRO > 0)) THEN
                            wSQL = wSQL||' and (BDCODTERCEIROD in ('||COALESCE(:wteragrup,:wTERCEIRO)||'));';
                          EXECUTE STATEMENT wSQL;
                          --*************************************************************************************************************************************************
                          --alt:14942 - 25/01/2017 - Sempre que alterar uma regra de conciliação, alterar também no uConciliacaoClientesFornecedores > SetConciliacaoCliFor e
                          --    SetConciliacaoEmMemoria, uConsultaLancamento, uConsultaRazaoVideo e as procedures VSUC_SP_CONCILIACAO e VSUC_SP_CONCILIACAO_AUTOMATICA. Pedro
                          --***********************************************************************************************************************************************
                          --Atualiza o lançamento como conciliado no caso do crédito
                          wSQL = 'update VSUC_EMPRESAS_TLAN set BDCONCC = '''||'TRUE'||''', ';
                          --#alt:13456 - adicionado indice para o tipo de conciliação. Ana - 28/10/2016
                          wSQL = wSQL||' bdtipoconc = case';
                          wSQL = wSQL||'   when ((bdconcd is null) or ((upper(bdconcd) = '''||'FALSE'||''')))then 5 ';
                          wSQL = wSQL||'   when (bdtipoconc = 7)  or (bdtipoconc = 4) then 6 ';
                          wSQL = wSQL||'   when (bdtipoconc = 1)  or (bdtipoconc = 3) then 8 ';
                          wSQL = wSQL||'   else bdtipoconc ';
                          wSQL = wSQL||' end ';
                          --#alt:13456. fim
                          wSQL = wSQL||' where (BDCHAVE = '||:BDCHAVE||') and (BDCODEMP = '||:BDCODEMP||')';  --#alt:13456 - adicionado indice Conciliado automaticamente débito e crédito. Ana - 28/10/2016
                          wSQL = wSQL||' and (BDCREDITO = '||:wConta||') and ((Upper(BDCONCC) = '''||'FALSE'||''') or (BDCONCC is null))';
                          IF ((wTERCEIRO IS NOT NULL) AND (wTERCEIRO > 0)) THEN
                            wSQL = wSQL||' and (BDCODTERCEIROC in ('||COALESCE(:wteragrup,:wTERCEIRO)||'));';
                          EXECUTE STATEMENT wSQL;
                          --Retorna o lançamento na Stored Procedure que posteriormente será inserido na tabela
                          --LISTA_LANC e utilizado para filtrar o lançamentos que serão exibidos na tela de
                          --consulta de lançamentos como os lançamentos que foram conciliados por este processo
                          SUSPEND;
                        END
                    END
                  wVALORDEB = 0;
                  wVALORCRE = 0;
                  DELETE FROM LISTA_LANC WHERE BDCODEMP IS NOT NULL;
                END
              --*************************************************************************************************************************************************
              --alt:14942 - 25/01/2017 - Sempre que alterar uma regra de conciliação, alterar também no uConciliacaoClientesFornecedores > SetConciliacaoCliFor e
              --    SetConciliacaoEmMemoria, uConsultaLancamento, uConsultaRazaoVideo e as procedures VSUC_SP_CONCILIACAO e VSUC_SP_CONCILIACAO_AUTOMATICA. Pedro
              --***********************************************************************************************************************************************
              --Insere na tabela temporária para poder armazenar todas as chaves do "grupo" atual (pode ser um
              --grupo pelo documento, data, valor, depende da opção selecioanda). Posteriormente, quando tiver
              --passado por todos os lançamentos deste grupo, verifica se o valor do débito e crédito fecharam,
              --caso positivo, marca todos os lançamentos encontrados nesta lista como conciliados e retorna eles
              --na Stored Procedure para que a rotina utilize para mostrar quais lançamentos foram conciliados.
              IF (wCODEMP IS NOT NULL) THEN
                INSERT INTO LISTA_LANC (BDCODEMP, BDCHAVE, BDTIPOLANCFILIAL) VALUES (:wCODEMP, :wCHAVE, :wTIPOLANCFILIAL);
              IF ((wCONTA <> wCONTAANT)
              OR IIF(((pragruparparticipantecnpj = 'TRUE') and (CHAR_LENGTH(TRIM(:wcnpjraizd)) = 10)),
                    (:wcnpjraizd <> :wcnpjraiz),IIF(((pragruparparticipantecpf = 'TRUE') and (CHAR_LENGTH(TRIM(:wcnpjraizd)) = 14)),(:wcnpjraizd <> :wcpf),
                 (COALESCE(wTERCEIRO, 0) <> COALESCE(wTERCEIROANT, 0))))) THEN
                BEGIN
                  wVALORDEB = 0;
                  wVALORCRE = 0;
                END
              IF (wCONTA = wDEBITO) THEN
                wVALORDEB = wVALORDEB + wVALOR;
              IF (wCONTA = wCREDITO) THEN
                wVALORCRE = wVALORCRE + wVALOR;
              wDCTOANT = wDCTO;
              wDATAANT = wDATA;
              wCONTAANT = wCONTA;
              wTERCEIROANT = wTERCEIRO;
              wDctoComplAnt = wDctoCompl;
            END
        END
      if (:wcnpjcpf <> '') then
        :wcnpjcpfAnt = :wcnpjcpf;
    END
  DELETE FROM LISTA_LANC WHERE BDCODEMP IS NOT NULL;
  DELETE FROM  TLIST_FORN;
END^

/* Restore proc. body: SP_INCLUICLASSECOL_ONLINE */
CREATE OR ALTER PROCEDURE SP_INCLUICLASSECOL_ONLINE (
    PRGRUPOCLA INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE WCODPLANOONLINE INTEGER;
DECLARE VARIABLE WCODTIPOCONTA INTEGER;
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCODTPHI INTEGER;
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(100);
DECLARE VARIABLE WFORMULA VARCHAR(100);
DECLARE VARIABLE WCODTCA INTEGER;
DECLARE VARIABLE WCLASS VARCHAR(9);
BEGIN
  wsql = 'select distinct BDCODPLANOONLINE, BDCODTIPOCONTA, BDCODPLAPADRAO, BDCODTPHI, BDCODCENTRO, BDCODTPCC,'||
           'SUBSTRING(BDCLASSIFICACAO FROM 1 FOR (STRLEN(BDCLASSIFICACAO) - 9)) BDCLASSIFICACAO,'||
           'SUBSTRING(BDFORMULA FROM 1 FOR (POSITION(''('' in BDFORMULA) - 1)) BDFORMULA '||
         'from TCONF_CONTAS_ONLINE '||
         'where BDCODGRUPOCLA is not null and BDCODTCA is null';

  wclass = TRIM(prgrupocla);
  WHILE (STRLEN(wclass) < 9) DO
    wclass = '0'||wclass;

  FOR EXECUTE STATEMENT wsql INTO :wcodplanoonline, :wcodtipoconta, :wcodplapadrao, :wcodtphi, :wcodcentro, :wcodtpcc, :wclassificacao, :wformula DO
    BEGIN
      INSERT INTO TCONF_CONTAS_ONLINE (BDCODPLANOONLINE, BDCODTIPOCONTA, BDCODPLAPADRAO, BDCODTPHI, BDCODCENTRO, BDCODTPCC, BDCLASSIFICACAO, BDFORMULA) VALUES
                                      (:wcodplanoonline,:wcodtipoconta,:wcodplapadrao,:wcodtphi,:wcodcentro,:wcodtpcc,TRIM(:wclassificacao)||:wclass, TRIM(:wformula)||'('||:prgrupocla||')');
    END

  wsql = 'select distinct BDCODPLANOONLINE, BDCODTIPOCONTA, BDCODPLAPADRAO, BDCODTPHI, BDCODCENTRO, BDCODTPCC,'||
           'SUBSTRING(BDCLASSIFICACAO FROM 1 FOR (STRLEN(BDCLASSIFICACAO) - 9)) BDCLASSIFICACAO,'||
           'SUBSTRING(BDFORMULA FROM 1 FOR (POSITION(''('' in BDFORMULA) - 1)) BDFORMULA, BDCODTCA '||
         'from TCONF_CONTAS_ONLINE '||
         'where BDCODGRUPOCLA is not null and BDCODTCA is not null';

  FOR EXECUTE STATEMENT wsql INTO :wcodplanoonline, :wcodtipoconta, :wcodplapadrao, :wcodtphi, :wcodcentro, :wcodtpcc, :wclassificacao, :wformula, :wcodtca DO
    BEGIN
      INSERT INTO TCONF_CONTAS_ONLINE (BDCODPLANOONLINE, BDCODTIPOCONTA, BDCODPLAPADRAO, BDCODTPHI, BDCODCENTRO, BDCODTPCC, BDCLASSIFICACAO, BDFORMULA, BDCODTCA) VALUES
                                      (:wcodplanoonline,:wcodtipoconta,:wcodplapadrao,:wcodtphi,:wcodcentro,:wcodtpcc,TRIM(:wclassificacao)||:wclass, TRIM(:wformula)||'('||:wcodtca||','||:prgrupocla||')', :wcodtca);
    END
END
^

/* Restore proc. body: SP_VRH_REORDENA_VERBAS */
CREATE OR ALTER PROCEDURE SP_VRH_REORDENA_VERBAS (
    PRCLASSINI VARCHAR(20) = 0,
    PRCLASSFIM VARCHAR(20) = 9.999,
    PRORDEMINICIAL INTEGER = 1,
    PRLISTACLASS1 VARCHAR(100) = NULL,
    PRLISTACLASS2 VARCHAR(5000) = NULL,
    PRLISTACLASS3 VARCHAR(10000) = NULL) 
RETURNS (
    BDORDEMFINAL INTEGER,
    BDCLASS1 VARCHAR(100),
    BDCLASS2 VARCHAR(5000),
    BDCLASS3 VARCHAR(10000)) 
AS
DECLARE VARIABLE WCLASS1 VARCHAR(100);
DECLARE VARIABLE WCLASS2 VARCHAR(5000);
DECLARE VARIABLE WCLASS3 VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WCLAVER VARCHAR(20);
DECLARE VARIABLE WTEMCLA SMALLINT;
DECLARE VARIABLE WINC INTEGER;
DECLARE VARIABLE WORDEM INTEGER;
BEGIN
  wclass1 = prlistaclass1;
  wclass2 = prlistaclass2;
  wclass3 = prlistaclass3;

  IF (wclass1 IS NULL) THEN
     wclass1 = '';
  IF (wclass2 IS NULL) THEN
     wclass2 = '';
  IF (wclass3 IS NULL) THEN
     wclass3 = '';

  wordem = prordeminicial;

  wsql = 'select BDCLAVER from VRH_BASE_TVERBAS where BDCLAVER >= '''||prclassini||''' and BDCLAVER <= '''||prclassfim||''' and STRLEN(BDCLAVER) = 9 order by BDCLAVER, BDCODVER';

  FOR EXECUTE STATEMENT wsql INTO :wclaver DO
  BEGIN
    -- Nivel 1
    wtemcla = 0;
    winc = 1;
    WHILE (SUBSTRING(:wclass1 FROM :winc FOR 1) <> '' AND wtemcla = 0) DO
      BEGIN
        IF (SUBSTRING(:wclass1 FROM :winc FOR 1) = SUBSTRING(:wclaver FROM 1 FOR 1)) THEN
           wtemcla = 1;

        winc = winc + 1;
      END

    IF (wtemcla = 0) THEN
       BEGIN
         wclass1 = wclass1||SUBSTRING(:wclaver FROM 1 FOR 1);
         UPDATE VRH_BASE_TVERBAS SET BDORDEMVER = :wordem WHERE BDCLAVER = SUBSTRING(:wclaver FROM 1 FOR 1);
       END

    -- Nivel 2
    wtemcla = 0;
    winc = 1;
    WHILE (SUBSTRING(:wclass2 FROM :winc FOR 5) <> '' AND wtemcla = 0) DO
      BEGIN
        IF (SUBSTRING(:wclass2 FROM :winc FOR 5) = SUBSTRING(:wclaver FROM 1 FOR 5)) THEN
           wtemcla = 1;

        winc = winc + 5;
      END

    IF (wtemcla = 0) THEN
       BEGIN
         wclass2 = wclass2||SUBSTRING(:wclaver FROM 1 FOR 5);
         UPDATE VRH_BASE_TVERBAS SET BDORDEMVER = :wordem WHERE BDCLAVER = SUBSTRING(:wclaver FROM 1 FOR 5);
       END

    -- Nivel 3
    wtemcla = 0;
    winc = 1;
    WHILE (SUBSTRING(:wclass3 FROM :winc FOR 7) <> '' AND wtemcla = 0) DO
      BEGIN
        IF (SUBSTRING(:wclass3 FROM :winc FOR 7) = SUBSTRING(:wclaver FROM 1 FOR 7)) THEN
           wtemcla = 1;

        winc = winc + 7;
      END

    IF (wtemcla = 0) THEN
       BEGIN
         wclass3 = wclass3||SUBSTRING(:wclaver FROM 1 FOR 7);
         UPDATE VRH_BASE_TVERBAS SET BDORDEMVER = :wordem WHERE BDCLAVER = SUBSTRING(:wclaver FROM 1 FOR 7);
       END

    wclaver = wclaver||'%';

    UPDATE VRH_BASE_TVERBAS SET BDORDEMVER = :wOrdem WHERE BDCLAVER LIKE :wclaver;
    wordem = wordem + 1;
  END

  bdordemfinal = wordem;
  bdclass1 = wclass1;
  bdclass2 = wclass2;
  bdclass3 = wclass3;
  SUSPEND;
END
^

create or alter procedure SP_CRIA_REFERENCIA_EMPRESAS_REF (
    PRAAAAMM integer,
    PRWHERE varchar(32000) = '',
    PRINCPOSTERIOR integer = 0)
as
declare variable WTAB varchar(300);
declare variable WEMP integer;
declare variable WREFEMP integer;
declare variable WCRIARREF smallint;
declare variable WSQLNOMECAMPOS1 varchar(120);
declare variable WSQLNOMECAMPOS2 varchar(150);
declare variable WNCAMPO varchar(300);
declare variable WSQL varchar(30000);
declare variable WSQLI varchar(30000);
BEGIN
  /* SQL que retorna o nome dos campos da tabela */
  wsqlnomecampos1 = 'SELECT TRIM(A.RDB$FIELD_NAME) FROM RDB$RELATION_FIELDS A, RDB$FIELDS B, RDB$TYPES C WHERE ';
  wsqlnomecampos2 = ' (B.RDB$FIELD_NAME = A.RDB$FIELD_SOURCE) AND (C.RDB$TYPE = B.RDB$FIELD_TYPE) AND (C.RDB$FIELD_NAME = '''||'RDB$FIELD_TYPE'||''') ORDER BY RDB$FIELD_POSITION';


  /* Laço das empresas */
  FOR EXECUTE STATEMENT 'select bdcodemp from TEMPRESAS '||TRIM(prwhere) INTO :wemp DO
  BEGIN
    wrefemp = NULL;
    SELECT MAX(BDREFEMP) FROM TEMPRESAS_REF WHERE BDCODEMP = :wemp AND BDREFEMP <= :praaaamm INTO :wrefemp;
    /* Verifica se a tabela TEMPRESAS_REF tem referência informada. Senão tiver cria a referência */

    if ((PRINCPOSTERIOR = 1) and (wrefemp is null)) then
       begin
         SELECT min(BDREFEMP) FROM TEMPRESAS_REF WHERE BDCODEMP = :wemp INTO :wrefemp;

         IF (wrefemp is not null) THEN
           wcriarref = 1;
         ELSE
           wcriarref = 0;
       end
    else
    IF (wrefemp < praaaamm) THEN
      wcriarref = 1;
    ELSE
      wcriarref = 0;

    wsql = '';
    IF (wcriarref = 1) THEN
      BEGIN
        wsql  = 'insert into tempresas_ref (BDCODEMP,BDREFEMP';
        wsqli = 'select BDCODEMP,'||praaaamm;
        FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||'TEMPRESAS_REF'||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
        BEGIN
          IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDREFEMP') THEN
            BEGIN
              wsql  = wsql||','||wncampo;
              wsqli = wsqli||','||wncampo;
            END
        END
        wsql  = wsql||') ';
        wsqli = wsqli||' from TEMPRESAS_REF where BDCODEMP = '||wemp||' and BDREFEMP = '||wrefemp;
        EXECUTE STATEMENT wsql||wsqli;
      END

    /* Laço com as tabelas que são dependentes da tabela TEMPRESAS_REF */
    FOR SELECT DISTINCT TRIM(CONSTRAINTSORIGEM.RDB$RELATION_NAME)
        FROM
          RDB$RELATION_CONSTRAINTS CONSTRAINTSORIGEM,
          RDB$RELATION_CONSTRAINTS CONSTRAINTSDESTINO,
          RDB$INDEX_SEGMENTS INDICES,
          RDB$REF_CONSTRAINTS RELACIONAMENTOS
        WHERE
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' AND
          CONSTRAINTSORIGEM.RDB$INDEX_NAME = INDICES.RDB$INDEX_NAME AND
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_NAME =
                    RELACIONAMENTOS.RDB$CONSTRAINT_NAME AND
          RELACIONAMENTOS.RDB$CONST_NAME_UQ =
                    CONSTRAINTSDESTINO.RDB$CONSTRAINT_NAME
          AND RELACIONAMENTOS.RDB$CONST_NAME_UQ = 'PK_TEMPRESAS_REF'
    INTO :wtab DO
      BEGIN
        wrefemp = NULL;
        EXECUTE STATEMENT 'select MAX(BDREFEMP) from '||wtab||' where BDCODEMP = '||wemp||' and BDREFEMP <= '||praaaamm INTO :wrefemp;
        /* Verifica se a tabela tem referência informada. Senão tiver cria a referência */

        if ((PRINCPOSTERIOR = 1) and (wrefemp is null)) then
           begin
            EXECUTE STATEMENT 'select min(BDREFEMP) from '||wtab||' where BDCODEMP = '||wemp INTO :wrefemp;

             IF (wrefemp is not null) THEN
               wcriarref = 1;
             ELSE
               wcriarref = 0;
           end
        else
        IF (wrefemp < praaaamm) THEN
          wcriarref = 1;
        ELSE
          wcriarref = 0;
    
        wsql = '';
        IF (wcriarref = 1) THEN
          BEGIN
            wsql  = 'insert into '||wtab||' (BDCODEMP,BDREFEMP';
            wsqli = 'select BDCODEMP,'||praaaamm;
            FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||wtab||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
            BEGIN
              IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDREFEMP') THEN
                BEGIN
                  wsql  = wsql||','||wncampo;
                  wsqli = wsqli||','||wncampo;
                END
            END
            wsql  = wsql||') ';
            wsqli = wsqli||' from '||wtab||' where BDCODEMP = '||wemp||' and BDREFEMP = '||wrefemp;
            EXECUTE STATEMENT wsql||wsqli;
          END

      END


    /* Laço com as tabelas que são dependentes da tabela VEF_BASE_TEMPCADATV */
    FOR SELECT DISTINCT TRIM(CONSTRAINTSORIGEM.RDB$RELATION_NAME)
        FROM
          RDB$RELATION_CONSTRAINTS CONSTRAINTSORIGEM,
          RDB$RELATION_CONSTRAINTS CONSTRAINTSDESTINO,
          RDB$INDEX_SEGMENTS INDICES,
          RDB$REF_CONSTRAINTS RELACIONAMENTOS
        WHERE
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' AND
          CONSTRAINTSORIGEM.RDB$INDEX_NAME = INDICES.RDB$INDEX_NAME AND
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_NAME =
                    RELACIONAMENTOS.RDB$CONSTRAINT_NAME AND
          RELACIONAMENTOS.RDB$CONST_NAME_UQ =
                    CONSTRAINTSDESTINO.RDB$CONSTRAINT_NAME
          AND RELACIONAMENTOS.RDB$CONST_NAME_UQ = 'PK_VEF_BASE_TEMPCADATV'
    INTO :wtab DO
      BEGIN
        wrefemp = NULL;
        EXECUTE STATEMENT 'select MAX(BDREFEMP) from '||wtab||' where BDCODEMP = '||wemp||' and BDREFEMP <= '||praaaamm INTO :wrefemp;
        /* Verifica se a tabela tem referência informada. Senão tiver cria a referência */
        IF (wrefemp < praaaamm) THEN
          wcriarref = 1;
        ELSE
          wcriarref = 0;
    
        wsql = '';
        IF (wcriarref = 1) THEN
          BEGIN
            wsql  = 'insert into '||wtab||' (BDCODEMP,BDREFEMP';
            wsqli = 'select BDCODEMP,'||praaaamm;
            FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||wtab||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
            BEGIN
              IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDREFEMP') THEN
                BEGIN
                  wsql  = wsql||','||wncampo;
                  wsqli = wsqli||','||wncampo;
                END
            END
            wsql  = wsql||') ';
            wsqli = wsqli||' from '||wtab||' where BDCODEMP = '||wemp||' and BDREFEMP = '||wrefemp;
            EXECUTE STATEMENT wsql||wsqli;
          END

      END



    /* Laço com as tabelas que são dependentes da tabela VEF_BASE_TEMPPAREST */
    FOR SELECT DISTINCT TRIM(CONSTRAINTSORIGEM.RDB$RELATION_NAME)
        FROM
          RDB$RELATION_CONSTRAINTS CONSTRAINTSORIGEM,
          RDB$RELATION_CONSTRAINTS CONSTRAINTSDESTINO,
          RDB$INDEX_SEGMENTS INDICES,
          RDB$REF_CONSTRAINTS RELACIONAMENTOS
        WHERE
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' AND
          CONSTRAINTSORIGEM.RDB$INDEX_NAME = INDICES.RDB$INDEX_NAME AND
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_NAME =
                    RELACIONAMENTOS.RDB$CONSTRAINT_NAME AND
          RELACIONAMENTOS.RDB$CONST_NAME_UQ =
                    CONSTRAINTSDESTINO.RDB$CONSTRAINT_NAME
          AND RELACIONAMENTOS.RDB$CONST_NAME_UQ = 'PK_VEF_BASE_TEMPPAREST'
    INTO :wtab DO
      BEGIN
        wrefemp = NULL;
        EXECUTE STATEMENT 'select MAX(BDREFEMP) from '||wtab||' where BDCODEMP = '||wemp||' and BDREFEMP <= '||praaaamm INTO :wrefemp;
        /* Verifica se a tabela tem referência informada. Senão tiver cria a referência */
        IF (wrefemp < praaaamm) THEN
          wcriarref = 1;
        ELSE
          wcriarref = 0;
    
        wsql = '';
        IF (wcriarref = 1) THEN
          BEGIN
            wsql  = 'insert into '||wtab||' (BDCODEMP,BDREFEMP';
            wsqli = 'select BDCODEMP,'||praaaamm;
            FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||wtab||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
            BEGIN
              IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDREFEMP') THEN
                BEGIN
                  wsql  = wsql||','||wncampo;
                  wsqli = wsqli||','||wncampo;
                END
            END
            wsql  = wsql||') ';
            wsqli = wsqli||' from '||wtab||' where BDCODEMP = '||wemp||' and BDREFEMP = '||wrefemp;
            EXECUTE STATEMENT wsql||wsqli;
          END

      END
    --Cria competencia nessa tabela(VRH_BASE_TEMPVINC), ela não estava criando porque não tem vinculo com TEMPRESAS_REF
    EXECUTE STATEMENT 'select MAX(BDREFEMP) from VRH_BASE_TEMPVINC where BDCODEMP = '||wemp||' and BDREFEMP <= '||praaaamm INTO :wrefemp;
    IF (wrefemp < praaaamm) THEN
          wcriarref = 1;
        ELSE
          wcriarref = 0;
    IF (wcriarref = 1) THEN
       begin
        wsql  = 'insert into VRH_BASE_TEMPVINC (BDCODEMP,BDREFEMP';
        wsqli = 'select BDCODEMP,'||praaaamm;
        FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = ''VRH_BASE_TEMPVINC'') AND ' ||wsqlnomecampos2 INTO :wncampo DO
          begin
            IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDREFEMP') THEN
                BEGIN
                  wsql  = wsql||','||wncampo;
                  wsqli = wsqli||','||wncampo;
                END
          end
        wsql  = wsql||') ';
        wsqli = wsqli||' from VRH_BASE_TEMPVINC where BDCODEMP = '||wemp||' and BDREFEMP = '||wrefemp;
        EXECUTE STATEMENT wsql||wsqli;
       end
  END
END^


CREATE OR ALTER PROCEDURE SP_CRIA_REFERENCIA_COLCON_REF (
    PRAAAAMM INTEGER,
    PRWHERE VARCHAR(32000) = '')
AS
DECLARE VARIABLE WTAB VARCHAR(300);
DECLARE VARIABLE WEMP INTEGER;
DECLARE VARIABLE WCOL INTEGER;
DECLARE VARIABLE WREFCOL INTEGER;
DECLARE VARIABLE WCRIARREF SMALLINT;
DECLARE VARIABLE WSQLNOMECAMPOS1 VARCHAR(120);
DECLARE VARIABLE WSQLNOMECAMPOS2 VARCHAR(150);
DECLARE VARIABLE WNCAMPO VARCHAR(300);
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WSQLI VARCHAR(30000);
BEGIN
  /* SQL que retorna o nome dos campos da tabela */
  wsqlnomecampos1 = 'SELECT TRIM(A.RDB$FIELD_NAME) FROM RDB$RELATION_FIELDS A, RDB$FIELDS B, RDB$TYPES C WHERE ';
  wsqlnomecampos2 = ' (B.RDB$FIELD_NAME = A.RDB$FIELD_SOURCE) AND (C.RDB$TYPE = B.RDB$FIELD_TYPE) AND (C.RDB$FIELD_NAME = '''||'RDB$FIELD_TYPE'||''') ORDER BY RDB$FIELD_POSITION';


  /* Laço das empresas */
  FOR EXECUTE STATEMENT 'select bdcodemp, bdcodcol from VRH_EMP_TCOLCON '||TRIM(prwhere) INTO :wemp, :wcol DO
  BEGIN
    wrefcol = NULL;
    SELECT coalesce(MAX(BDREFCOL), 0) BDREFCOL FROM VRH_EMP_TCOLCON_REF WHERE BDCODEMP = :wemp AND BDCODCOL = :wcol AND BDREFCOL <= :praaaamm INTO :wrefcol;
    /* Verifica se a tabela VRH_EMP_TCOLCON_REF tem referência informada. Senão tiver cria a referência */
    IF (wrefcol < praaaamm) THEN
      wcriarref = 1;
    ELSE
      wcriarref = 0;

    wsql = '';
    IF (wcriarref = 1) THEN
      BEGIN
        wsql  = 'insert into VRH_EMP_TCOLCON_REF (BDCODEMP,BDCODCOL,BDREFCOL';
        wsqli = 'select BDCODEMP,BDCODCOL,'||praaaamm;
        FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||'VRH_EMP_TCOLCON_REF'||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
        BEGIN
          IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDCODCOL' AND wncampo <> 'BDREFCOL') THEN
            BEGIN
              wsql  = wsql||','||wncampo;
              wsqli = wsqli||','||wncampo;
            END
        END
        wsql  = wsql||') ';
        wsqli = wsqli||' from VRH_EMP_TCOLCON_REF where BDCODEMP = '||wemp||' and BDCODCOL = '||wcol||' and BDREFCOL = '||wrefcol;
        EXECUTE STATEMENT wsql||wsqli;
      END

    /* Laço com as tabelas que são dependentes da tabela VRH_EMP_TCOLCON_REF */
    FOR SELECT DISTINCT TRIM(CONSTRAINTSORIGEM.RDB$RELATION_NAME)
        FROM
          RDB$RELATION_CONSTRAINTS CONSTRAINTSORIGEM,
          RDB$RELATION_CONSTRAINTS CONSTRAINTSDESTINO,
          RDB$INDEX_SEGMENTS INDICES,
          RDB$REF_CONSTRAINTS RELACIONAMENTOS
        WHERE
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' AND
          CONSTRAINTSORIGEM.RDB$INDEX_NAME = INDICES.RDB$INDEX_NAME AND
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_NAME =
                    RELACIONAMENTOS.RDB$CONSTRAINT_NAME AND
          RELACIONAMENTOS.RDB$CONST_NAME_UQ =
                    CONSTRAINTSDESTINO.RDB$CONSTRAINT_NAME
          AND RELACIONAMENTOS.RDB$CONST_NAME_UQ = 'PK_VRH_EMP_TCOLCON_REF'
    INTO :wtab DO
      BEGIN
        wrefcol = NULL;
        EXECUTE STATEMENT 'select MAX(BDREFCOL) from '||wtab||' where BDCODEMP = '||wemp||' and BDCODCOL = '||wcol||' and BDREFCOL <= '||praaaamm INTO :wrefcol;
        /* Verifica se a tabela tem referência informada. Senão tiver cria a referência */
        IF (wrefcol < praaaamm) THEN
          wcriarref = 1;
        ELSE
          wcriarref = 0;
    
        wsql = '';
        IF (wcriarref = 1) THEN
          BEGIN
            wsql  = 'insert into '||wtab||' (BDCODEMP,BDCODCOL,BDREFCOL';
            wsqli = 'select BDCODEMP,BDCODCOL,'||praaaamm;
            FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||wtab||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
            BEGIN
              IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDCODCOL' AND wncampo <> 'BDREFCOL') THEN
                BEGIN
                  wsql  = wsql||','||wncampo;
                  wsqli = wsqli||','||wncampo;
                END
            END
            wsql  = wsql||') ';
            wsqli = wsqli||' from '||wtab||' where BDCODEMP = '||wemp||' and BDCODCOL = '||wcol||' and BDREFCOL = '||wrefcol;
            EXECUTE STATEMENT wsql||wsqli;
          END

      END
  END
END^

CREATE OR ALTER procedure SP_CRIA_REF_ESOCIAL_EMP_REF (
    PRAAAAMM integer,
    PRWHERE varchar(32000) = '')
as
declare variable WTAB varchar(300);
declare variable WEMP integer;
declare variable WREFEMP integer;
declare variable WCRIARREF smallint;
declare variable WSQLNOMECAMPOS1 varchar(120);
declare variable WSQLNOMECAMPOS2 varchar(150);
declare variable WNCAMPO varchar(300);
declare variable WSQL varchar(30000);
declare variable WSQLI varchar(30000);
BEGIN
  /* SQL que retorna o nome dos campos da tabela */
  wsqlnomecampos1 = 'SELECT TRIM(A.RDB$FIELD_NAME) FROM RDB$RELATION_FIELDS A, RDB$FIELDS B, RDB$TYPES C WHERE ';
  wsqlnomecampos2 = ' (B.RDB$FIELD_NAME = A.RDB$FIELD_SOURCE) AND (C.RDB$TYPE = B.RDB$FIELD_TYPE) AND (C.RDB$FIELD_NAME = '''||'RDB$FIELD_TYPE'||''') ORDER BY RDB$FIELD_POSITION';


  /* Laço das empresas */
  FOR EXECUTE STATEMENT 'select bdcodemp from TEMPRESAS '||TRIM(prwhere) INTO :wemp DO
  BEGIN
    wrefemp = NULL;
    SELECT MIN(BDREFEMP) FROM TEMPRESAS_REF WHERE BDCODEMP = :wemp AND ((BDREFEMP <= :praaaamm) or (BDREFEMP >= :praaaamm)) INTO :wrefemp;
    /* Verifica se a tabela TEMPRESAS_REF tem referência informada. Senão tiver cria a referência */
    IF (wrefemp > praaaamm) THEN
      wcriarref = 1;
    ELSE
      wcriarref = 0;

    wsql = '';
    IF (wcriarref = 1) THEN
      BEGIN
        wsql  = 'insert into tempresas_ref (BDCODEMP,BDREFEMP';
        wsqli = 'select BDCODEMP,'||praaaamm;
        FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||'TEMPRESAS_REF'||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
        BEGIN
          IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDREFEMP') THEN
            BEGIN
              wsql  = wsql||','||wncampo;
              wsqli = wsqli||','||wncampo;
            END
        END
        wsql  = wsql||') ';
        wsqli = wsqli||' from TEMPRESAS_REF where BDCODEMP = '||wemp||' and BDREFEMP = '||wrefemp;
        EXECUTE STATEMENT wsql||wsqli;
      END

    /* Laço com as tabelas que são dependentes da tabela TEMPRESAS_REF */
    FOR SELECT DISTINCT TRIM(CONSTRAINTSORIGEM.RDB$RELATION_NAME)
        FROM
          RDB$RELATION_CONSTRAINTS CONSTRAINTSORIGEM,
          RDB$RELATION_CONSTRAINTS CONSTRAINTSDESTINO,
          RDB$INDEX_SEGMENTS INDICES,
          RDB$REF_CONSTRAINTS RELACIONAMENTOS
        WHERE
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' AND
          CONSTRAINTSORIGEM.RDB$INDEX_NAME = INDICES.RDB$INDEX_NAME AND
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_NAME =
                    RELACIONAMENTOS.RDB$CONSTRAINT_NAME AND
          RELACIONAMENTOS.RDB$CONST_NAME_UQ =
                    CONSTRAINTSDESTINO.RDB$CONSTRAINT_NAME
          AND RELACIONAMENTOS.RDB$CONST_NAME_UQ = 'PK_TEMPRESAS_REF'
    INTO :wtab DO
      BEGIN
        wrefemp = NULL;
        EXECUTE STATEMENT 'select MIN(BDREFEMP) from '||wtab||' where BDCODEMP = '||wemp||' and (BDREFEMP <= '||praaaamm||' or BDREFEMP >= '||praaaamm||')' INTO :wrefemp;
        /* Verifica se a tabela tem referência informada. Senão tiver cria a referência */
        IF (wrefemp > praaaamm) THEN
          wcriarref = 1;
        ELSE
          wcriarref = 0;
    
        wsql = '';
        IF (wcriarref = 1) THEN
          BEGIN
            wsql  = 'insert into '||wtab||' (BDCODEMP,BDREFEMP';
            wsqli = 'select BDCODEMP,'||praaaamm;
            FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||wtab||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
            BEGIN
              IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDREFEMP') THEN
                BEGIN
                  wsql  = wsql||','||wncampo;
                  wsqli = wsqli||','||wncampo;
                END
            END
            wsql  = wsql||') ';
            wsqli = wsqli||' from '||wtab||' where BDCODEMP = '||wemp||' and BDREFEMP = '||wrefemp;
            EXECUTE STATEMENT wsql||wsqli;
          END

      END


    /* Laço com as tabelas que são dependentes da tabela VEF_BASE_TEMPCADATV */
    FOR SELECT DISTINCT TRIM(CONSTRAINTSORIGEM.RDB$RELATION_NAME)
        FROM
          RDB$RELATION_CONSTRAINTS CONSTRAINTSORIGEM,
          RDB$RELATION_CONSTRAINTS CONSTRAINTSDESTINO,
          RDB$INDEX_SEGMENTS INDICES,
          RDB$REF_CONSTRAINTS RELACIONAMENTOS
        WHERE
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' AND
          CONSTRAINTSORIGEM.RDB$INDEX_NAME = INDICES.RDB$INDEX_NAME AND
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_NAME =
                    RELACIONAMENTOS.RDB$CONSTRAINT_NAME AND
          RELACIONAMENTOS.RDB$CONST_NAME_UQ =
                    CONSTRAINTSDESTINO.RDB$CONSTRAINT_NAME
          AND RELACIONAMENTOS.RDB$CONST_NAME_UQ = 'PK_VEF_BASE_TEMPCADATV'
    INTO :wtab DO
      BEGIN
        wrefemp = NULL;
        EXECUTE STATEMENT 'select MIN(BDREFEMP) from '||wtab||' where BDCODEMP = '||wemp||' and (BDREFEMP <= '||praaaamm||' or BDREFEMP >= '||praaaamm||')' INTO :wrefemp;
        /* Verifica se a tabela tem referência informada. Senão tiver cria a referência */
        IF (wrefemp > praaaamm) THEN
          wcriarref = 1;
        ELSE
          wcriarref = 0;
    
        wsql = '';
        IF (wcriarref = 1) THEN
          BEGIN
            wsql  = 'insert into '||wtab||' (BDCODEMP,BDREFEMP';
            wsqli = 'select BDCODEMP,'||praaaamm;
            FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||wtab||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
            BEGIN
              IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDREFEMP') THEN
                BEGIN
                  wsql  = wsql||','||wncampo;
                  wsqli = wsqli||','||wncampo;
                END
            END
            wsql  = wsql||') ';
            wsqli = wsqli||' from '||wtab||' where BDCODEMP = '||wemp||' and BDREFEMP = '||wrefemp;
            EXECUTE STATEMENT wsql||wsqli;
          END

      END



    /* Laço com as tabelas que são dependentes da tabela VEF_BASE_TEMPPAREST */
    FOR SELECT DISTINCT TRIM(CONSTRAINTSORIGEM.RDB$RELATION_NAME)
        FROM
          RDB$RELATION_CONSTRAINTS CONSTRAINTSORIGEM,
          RDB$RELATION_CONSTRAINTS CONSTRAINTSDESTINO,
          RDB$INDEX_SEGMENTS INDICES,
          RDB$REF_CONSTRAINTS RELACIONAMENTOS
        WHERE
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' AND
          CONSTRAINTSORIGEM.RDB$INDEX_NAME = INDICES.RDB$INDEX_NAME AND
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_NAME =
                    RELACIONAMENTOS.RDB$CONSTRAINT_NAME AND
          RELACIONAMENTOS.RDB$CONST_NAME_UQ =
                    CONSTRAINTSDESTINO.RDB$CONSTRAINT_NAME
          AND RELACIONAMENTOS.RDB$CONST_NAME_UQ = 'PK_VEF_BASE_TEMPPAREST'
    INTO :wtab DO
      BEGIN
        wrefemp = NULL;
        EXECUTE STATEMENT 'select MIN(BDREFEMP) from '||wtab||' where BDCODEMP = '||wemp||' and (BDREFEMP <= '||praaaamm||' or BDREFEMP >= '||praaaamm||')' INTO :wrefemp;
        /* Verifica se a tabela tem referência informada. Senão tiver cria a referência */
        IF (wrefemp > praaaamm) THEN
          wcriarref = 1;
        ELSE
          wcriarref = 0;
    
        wsql = '';
        IF (wcriarref = 1) THEN
          BEGIN
            wsql  = 'insert into '||wtab||' (BDCODEMP,BDREFEMP';
            wsqli = 'select BDCODEMP,'||praaaamm;
            FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||wtab||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
            BEGIN
              IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDREFEMP') THEN
                BEGIN
                  wsql  = wsql||','||wncampo;
                  wsqli = wsqli||','||wncampo;
                END
            END
            wsql  = wsql||') ';
            wsqli = wsqli||' from '||wtab||' where BDCODEMP = '||wemp||' and BDREFEMP = '||wrefemp;
            EXECUTE STATEMENT wsql||wsqli;
          END

      END
    --Cria competencia nessa tabela(VRH_BASE_TEMPVINC), ela não estava criando porque não tem vinculo com TEMPRESAS_REF
    EXECUTE STATEMENT 'select MIN(BDREFEMP) from VRH_BASE_TEMPVINC where BDCODEMP = '||wemp||' and (BDREFEMP <= '||praaaamm||' or BDREFEMP >= '||praaaamm||')' INTO :wrefemp;
    IF (wrefemp > praaaamm) THEN
          wcriarref = 1;
        ELSE
          wcriarref = 0;
    IF (wcriarref = 1) THEN
       begin
        wsql  = 'insert into VRH_BASE_TEMPVINC (BDCODEMP,BDREFEMP';
        wsqli = 'select BDCODEMP,'||praaaamm;
        FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = ''VRH_BASE_TEMPVINC'') AND ' ||wsqlnomecampos2 INTO :wncampo DO
          begin
            IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDREFEMP') THEN
                BEGIN
                  wsql  = wsql||','||wncampo;
                  wsqli = wsqli||','||wncampo;
                END
          end
        wsql  = wsql||') ';
        wsqli = wsqli||' from VRH_BASE_TEMPVINC where BDCODEMP = '||wemp||' and BDREFEMP = '||wrefemp;
        EXECUTE STATEMENT wsql||wsqli;
       end
  END
END^


create or alter procedure SP_CRIA_DATA_COLCON_DIA (
    PRDATA date,
    PRWHERE varchar(32700))
as
declare variable WTAB varchar(300);
declare variable WEMP integer;
declare variable WCOL integer;
declare variable WDATACOL date;
declare variable WCRIADATA smallint;
declare variable WSQLNOMECAMPOS1 varchar(120);
declare variable WSQLNOMECAMPOS2 varchar(150);
declare variable WNCAMPO varchar(300);
declare variable WSQL varchar(30000);
declare variable WSQLI varchar(30000);
begin
  /* SQL que retorna o nome dos campos da tabela */
  wsqlnomecampos1 = 'SELECT TRIM(A.RDB$FIELD_NAME) FROM RDB$RELATION_FIELDS A, RDB$FIELDS B, RDB$TYPES C WHERE ';
  wsqlnomecampos2 = ' (B.RDB$FIELD_NAME = A.RDB$FIELD_SOURCE) AND (C.RDB$TYPE = B.RDB$FIELD_TYPE) AND (C.RDB$FIELD_NAME = '''||'RDB$FIELD_TYPE'||''') ORDER BY RDB$FIELD_POSITION';


  /* Laço das empresas */
  FOR EXECUTE STATEMENT 'select bdcodemp, bdcodcol from VRH_EMP_TCOLCON '||TRIM(prwhere) INTO :wemp, :wcol DO
  BEGIN
    wdatacol = null;
    SELECT MAX(BDDATACOL) FROM VRH_EMP_TCOLCON_DIA WHERE BDCODEMP = :wemp AND BDCODCOL = :wcol AND BDDATACOL <= :prdata INTO :wdatacol;
    /* Verifica se a tabela VRH_EMP_TCOLCON_DIA tem data informada. Senão tiver cria a data */
    IF (wdatacol < prdata) THEN
      wcriadata = 1;
    ELSE
      wcriadata = 0;

    wsql = '';
    IF (wcriadata = 1) THEN
      BEGIN
        wsql  = 'insert into VRH_EMP_TCOLCON_DIA (BDCODEMP,BDCODCOL,BDDATACOL';
        wsqli = 'select BDCODEMP,BDCODCOL,'''||CAST(:prdata as VARCHAR(10))||'''';
        FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||'VRH_EMP_TCOLCON_DIA'||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
        BEGIN
          IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDCODCOL' AND wncampo <> 'BDDATACOL') THEN
            BEGIN
              wsql  = wsql||','||wncampo;
              wsqli = wsqli||','||wncampo;
            END
        END
        wsql  = wsql||') ';
        wsqli = wsqli||' from VRH_EMP_TCOLCON_DIA where BDCODEMP = '||wemp||' and BDCODCOL = '||wcol||' and BDDATACOL = '''||CAST(:wdatacol AS VARCHAR(10))||'''';
        EXECUTE STATEMENT wsql||wsqli;
      END

    /* Laço com as tabelas que são dependentes da tabela VRH_EMP_TCOLCON_DIA */
    FOR SELECT DISTINCT TRIM(CONSTRAINTSORIGEM.RDB$RELATION_NAME)
        FROM
          RDB$RELATION_CONSTRAINTS CONSTRAINTSORIGEM,
          RDB$RELATION_CONSTRAINTS CONSTRAINTSDESTINO,
          RDB$INDEX_SEGMENTS INDICES,
          RDB$REF_CONSTRAINTS RELACIONAMENTOS
        WHERE
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' AND
          CONSTRAINTSORIGEM.RDB$INDEX_NAME = INDICES.RDB$INDEX_NAME AND
          CONSTRAINTSORIGEM.RDB$CONSTRAINT_NAME =
                    RELACIONAMENTOS.RDB$CONSTRAINT_NAME AND
          RELACIONAMENTOS.RDB$CONST_NAME_UQ =
                    CONSTRAINTSDESTINO.RDB$CONSTRAINT_NAME
          AND RELACIONAMENTOS.RDB$CONST_NAME_UQ = 'PK_VRH_EMP_TCOLCON_DIA'
    INTO :wtab DO
      BEGIN
        wdatacol = null;
        EXECUTE STATEMENT 'select MAX(BDDATACOL) from '||wtab||' where BDCODEMP = '||wemp||' and BDCODCOL = '||wcol||' and BDDATACOL <= '''||CAST(:prdata AS VARCHAR(10))||'''' INTO :wdatacol;
        /* Verifica se a tabela tem data informada. Senão tiver cria a data */
        IF (wdatacol < prdata) THEN
          wcriadata = 1;
        ELSE
          wcriadata = 0;
    
        wsql = '';
        IF (wcriadata = 1) THEN
          BEGIN
            wsql  = 'insert into '||wtab||' (BDCODEMP,BDCODCOL,BDDATACOL';
            wsqli = 'select BDCODEMP,BDCODCOL,'''||CAST(:prdata AS VARCHAR(10))||'''' ;
            FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||wtab||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
            BEGIN
              IF (wncampo <> 'BDCODEMP' AND wncampo <> 'BDCODCOL' AND wncampo <> 'BDDATACOL') THEN
                BEGIN
                  wsql  = wsql||','||wncampo;
                  wsqli = wsqli||','||wncampo;
                END
            END
            wsql  = wsql||') ';
            wsqli = wsqli||' from '||wtab||' where BDCODEMP = '||wemp||' and BDCODCOL = '||wcol||' and BDDATACOL = '''||CAST(:wdatacol AS VARCHAR(10))||'''';
            EXECUTE STATEMENT wsql||wsqli;
          END

      END
  END
end^


create or alter procedure SP_VRH_REORDENA_TODAS_VERBAS
as
declare variable WORDEM integer;
declare variable WCLASS1 varchar(100);
declare variable WCLASS2 varchar(5000);
declare variable WCLASS3 varchar(10000);
BEGIN
  wclass1 = '';
  wclass2 = '';
  wclass3 = '';
  wordem  = 1;

  SELECT BDORDEMFINAL, BDCLASS1, BDCLASS2, BDCLASS3 FROM SP_VRH_REORDENA_VERBAS('0', '0.001.9.9.999', :wordem, :wclass1, :wclass2, :wclass3) INTO :wordem, :wclass1, :wclass2, :wclass3;
  SELECT BDORDEMFINAL, BDCLASS1, BDCLASS2, BDCLASS3 FROM SP_VRH_REORDENA_VERBAS('0.800', '0.800.5.9.999', :wordem, :wclass1, :wclass2, :wclass3) INTO :wordem, :wclass1, :wclass2, :wclass3;
  SELECT BDORDEMFINAL, BDCLASS1, BDCLASS2, BDCLASS3 FROM SP_VRH_REORDENA_VERBAS('7', '7.999', :wordem, :wclass1, :wclass2, :wclass3) INTO :wordem, :wclass1, :wclass2, :wclass3;
  SELECT BDORDEMFINAL, BDCLASS1, BDCLASS2, BDCLASS3 FROM SP_VRH_REORDENA_VERBAS('8', '8.999', :wordem, :wclass1, :wclass2, :wclass3) INTO :wordem, :wclass1, :wclass2, :wclass3;
  SELECT BDORDEMFINAL, BDCLASS1, BDCLASS2, BDCLASS3 FROM SP_VRH_REORDENA_VERBAS('0.002', '0.004.9.9.999', :wordem, :wclass1, :wclass2, :wclass3) INTO :wordem, :wclass1, :wclass2, :wclass3;
  SELECT BDORDEMFINAL, BDCLASS1, BDCLASS2, BDCLASS3 FROM SP_VRH_REORDENA_VERBAS('0.800.6', '0.800.9.9.999', :wordem, :wclass1, :wclass2, :wclass3) INTO :wordem, :wclass1, :wclass2, :wclass3;
  SELECT BDORDEMFINAL, BDCLASS1, BDCLASS2, BDCLASS3 FROM SP_VRH_REORDENA_VERBAS('0.100', '1.001.9.9.999', :wordem, :wclass1, :wclass2, :wclass3) INTO :wordem, :wclass1, :wclass2, :wclass3;
  SELECT BDORDEMFINAL, BDCLASS1, BDCLASS2, BDCLASS3 FROM SP_VRH_REORDENA_VERBAS('0.006', '0.006.9.9.999', :wordem, :wclass1, :wclass2, :wclass3) INTO :wordem, :wclass1, :wclass2, :wclass3;
  SELECT BDORDEMFINAL, BDCLASS1, BDCLASS2, BDCLASS3 FROM SP_VRH_REORDENA_VERBAS('0.005', '0.005.9.9.999', :wordem, :wclass1, :wclass2, :wclass3) INTO :wordem, :wclass1, :wclass2, :wclass3;
  SELECT BDORDEMFINAL, BDCLASS1, BDCLASS2, BDCLASS3 FROM SP_VRH_REORDENA_VERBAS('0.007', '0.070.9.9.999', :wordem, :wclass1, :wclass2, :wclass3) INTO :wordem, :wclass1, :wclass2, :wclass3;
  SELECT BDORDEMFINAL, BDCLASS1, BDCLASS2, BDCLASS3 FROM SP_VRH_REORDENA_VERBAS('2', '6.999', :wordem, :wclass1, :wclass2, :wclass3) INTO :wordem, :wclass1, :wclass2, :wclass3;
  SELECT BDORDEMFINAL, BDCLASS1, BDCLASS2, BDCLASS3 FROM SP_VRH_REORDENA_VERBAS('9', '9.999', :wordem, :wclass1, :wclass2, :wclass3) INTO :wordem, :wclass1, :wclass2, :wclass3;
END^


CREATE OR ALTER trigger vef_emp_tmovserdir_bi for vef_emp_tmovserdir
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
  end
END
^

CREATE OR ALTER trigger vef_emp_tmovsercampinas_bi0 for vef_emp_tmovsercampinas
active before insert position 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovser WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
  end
END
^

CREATE OR ALTER TRIGGER vef_emp_tmovccdemdocf100_bi0 FOR vef_emp_tmovccdemdocf100
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovdemaisdoc_f100 WHERE (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

  IF ((NEW.bdordemcc IS NULL) OR (NEW.bdordemcc = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordemcc) + 1), 1) FROM vef_emp_tmovccdemdocf100 WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave) INTO vCodigo;
       NEW.bdordemcc = vCodigo;
     END
  ELSE
     BEGIN
       SELECT bdordemcc FROM vef_emp_tmovccdemdocf100 WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave AND bdordemcc = NEW.bdordemcc) INTO vCodigo;

       IF (vCodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdordemcc) + 1), 1) FROM vef_emp_tmovccdemdocf100 WHERE (bdcodemp = NEW.bdcodemp AND bdchave = NEW.bdchave) INTO vCodigo;
            NEW.bdordemcc = vCodigo;
          END
     END
END
^

/* Create Views... */

/* Alter Procedure... */
SET TERM ; ^

CREATE OR ALTER VIEW VW_VRH_EMP_TTRANSCOL_DESTINO(
    BDCODEMPORIG,
    BDCODCOLORIG,
    BDCODEMP,
    BDCODPTRAN,
    BDDATATRF,
    BDCODCOL)
AS
SELECT
    bdcodemporig,
    bdcodcolorig,
    bdcodempdest,
    bdcodptran,
    bddatatrf,
    bdcodcoldest
FROM vrh_emp_ttranscol
;

/* CREATE OR ALTER VIEW: VW_SN_ENCARGOS_SALARIOS_SEMGRRF (ViwData.CreateDependDef) */
CREATE OR ALTER VIEW VW_SN_ENCARGOS_SALARIOS_SEMGRRF(
    BDCODEMP,
    BDREF,
    BDTIPOCODVER,
    BDSALARIO)
AS
SELECT bdcodemp,bdref,bdtipocodver,SUM(bdsalario) bdsalario FROM (

SELECT vfn.bdcodemp,vfn.bdreffn bdref,v.bdtipocodver, vfn.bdvalvfn bdsalario FROM vrhf_emp_tverbafn vfn
JOIN vw_verbas_ref_atual v ON (vfn.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vfT.bdcodemp,vfT.bdreftomador bdref,v.bdtipocodver,vfT.bdvalvfT bdsalario FROM vrhf_emp_tverbatomador vfT
JOIN vw_verbas_ref_atual v ON (vfT.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vfC.bdcodemp,vfC.bdreffn bdref,v.bdtipocodver,vfC.bdvalvfc bdsalario FROM vrhf_emp_tverbafc vfC
JOIN vw_verbas_ref_atual v ON (vfC.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vfCt.bdcodemp,vfCt.bdreftomador bdref,v.bdtipocodver,vfCt.bdvalvfc bdsalario FROM vrhf_emp_tverbafctomador vfCt
JOIN vw_verbas_ref_atual v ON (vfCt.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vaut.bdcodemp,serv.BDREFSERV bdref,v.bdtipocodver,vaut.bdvalor bdsalario FROM VRHF_BASE_ITEMS_CALCTERC vaut
JOIN vw_verbas_ref_atual v ON (vaut.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
JOIN vrh_base_tservterc serv ON (serv.bdcodter = vaut.bdcodter AND vaut.bdcodemp = serv.bdcodemp AND vaut.bdcodserv = serv.bdcodserv)
UNION ALL

SELECT vad.bdcodemp,ad.BDREFAD bdref,v.bdtipocodver,vad.bdvalvad bdsalario FROM vrhf_emp_tverbaad vad
JOIN vw_verbas_ref_atual v ON (vad.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
JOIN vrhf_emp_tadsal ad ON (vad.bdcodemp = ad.bdcodemp AND vad.bdcodcol = ad.bdcodcol AND vad.bddataad = ad.bddataad)
UNION ALL

SELECT va13.bdcodemp,va13.bdrefa13 bdref,v.bdtipocodver,va13.bdvalva13 bdsalario FROM vrhf_emp_tverbaa13 va13
JOIN vw_verbas_ref_atual v ON (va13.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT v13.bdcodemp,v13.bdref13 bdref,v.bdtipocodver,v13.bdvalv13 bdsalario FROM vrhf_emp_tverba13 v13
JOIN vw_verbas_ref_atual v ON (v13.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vc13.bdcodemp,vc13.bdrefc13 bdref,v.bdtipocodver,vc13.bdvalvc13 bdsalario FROM vrhf_emp_tverbac13 vc13
JOIN vw_verbas_ref_atual v ON (vc13.bdcodver = v.bdcodver AND UPPER(v.bdsimplesnacional) = 'TRUE')
UNION ALL

SELECT vimp.bdcodemp, vimp.bdreferencia, 0 bdtipocodver, CASE WHEN imp.bddocarrecadacao = 12 THEN vimp.bdvalempgps ELSE vimp.bdtotal END
FROM vw_sn_impostos_ref vimp
JOIN timposto imp ON ((vimp.bdcodimp = imp.bdcodimp) AND
                      (imp.bdcodsis = 2) AND
                      ((imp.bddocarrecadacao IN (19,12)) OR ((imp.bddocarrecadacao IN (1)) AND (imp.bdtiporetencao = 1))))

)

GROUP BY bdcodemp, bdref, bdtipocodver
;

SET TERM ^ ;

CREATE OR ALTER PROCEDURE SP_APAGA_CONFIG_TELA (
    PRTELA VARCHAR(100),
    PRUSUARIO INTEGER = NULL)
AS
DECLARE VARIABLE WSQL VARCHAR(2000);
BEGIN
  wsql = 'delete from tusuario_itemstela_config where UPPER(BDTELA) = UPPER('''||prtela||''') ';

  IF (prusuario IS NOT NULL AND prusuario > 0) THEN
     wsql = wsql||' and BDCODUSU = '||prusuario;

  EXECUTE STATEMENT wsql;
END^


CREATE OR ALTER TRIGGER tr_bf_insert_vef_emp_tmovsai FOR vef_emp_tmovsai
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
--  declare variable vNova_Chave integer;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
     begin
  -- só atribui o usuário se for nulo
  IF (NEW.bdcodusu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusu = vcodigo;
    END

  IF (NEW.bdcodusuinclu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusuinclu = vcodigo;
    END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  NEW.bdreflan = CAST( SUBSTRING(CAST(NEW.bddataemissao AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.bddataemissao AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);

  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;

  NEW.bddatainclusao = NEW.bddatalan;
  NEW.bdhorainclusao = NEW.bdhoralan;

  --TIPO DO LANCAMENTO DA TABELA TIPOS_LANCAMENTOS_PADRAO
  IF ((NEW.BDCODTIPO IS NULL) OR (NEW.BDCODTIPO = 0)) THEN
     NEW.BDCODTIPO = 101;

  IF ((NEW.BDTIPOLANINCLU IS NULL) OR (NEW.BDTIPOLANINCLU = 0)) THEN
     NEW.BDTIPOLANINCLU = NEW.BDCODTIPO;
  
  --CAMPO FUNDAP PADRAO FALSE Sol. 193804
  if ((NEW.BDFUNDAP is null) or (NEW.bdfundap = ''))  then
     NEW.BDFUNDAP = 'FALSE';
  end
END
^


CREATE OR ALTER trigger vef_emp_tmovsai_bu0 for vef_emp_tmovsai
active before update position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.BDCODTIPO not in (101, 102, 200, 3000)) and (new.BDNUMDOCINI <> old.BDNUMDOCINI)) then
    begin
        exception EX_CHAVE_EM_USO;
        exit;
    end 
  NEW.bdreflan = CAST( SUBSTRING(CAST(NEW.bddataemissao AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.bddataemissao AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);

  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;

  SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
  IF ((vcodigo <> 0 ) AND (vcodigo IS NOT NULL )) THEN
    NEW.bdcodusu = vcodigo;

  if (OLD.BDCODTER <> NEW.BDCODTER AND EXISTS (SELECT FIRST 1 BDORDEM FROM VEF_EMP_TMOVSAIPR PR WHERE PR.BDCODEMP = NEW.BDCODEMP AND PR.BDCHAVE = NEW.BDCHAVE)) then
     BEGIN
       UPDATE VEF_EMP_TMOVSAIPR PR SET
       PR.BDCODTER = NEW.BDCODTER
       WHERE PR.BDCODEMP = NEW.BDCODEMP
       AND   PR.BDCHAVE  = NEW.BDCHAVE;
  END
  end
END^

CREATE OR ALTER TRIGGER tr_bf_insert_vef_emp_tmovent FOR vef_emp_tmovent
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
--  declare variable vNova_Chave integer;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
     begin
  -- só atribui o usuário se for nulo
  IF (NEW.bdcodusu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusu = vcodigo;
    END

  IF (NEW.bdcodusuinclu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusuinclu = vcodigo;
    END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  NEW.bdreflan = CAST( SUBSTRING(CAST(NEW.bddataentradaent AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.bddataentradaent AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);

  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;

  NEW.bddatainclusao = NEW.bddatalan;
  NEW.bdhorainclusao = NEW.bdhoralan;

  --TIPO DO LANCAMENTO DA TABELA TIPOS_LANCAMENTOS_PADRAO
  IF ((NEW.BDCODTIPO IS NULL) OR (NEW.BDCODTIPO = 0)) THEN
     NEW.BDCODTIPO = 101;

  IF ((NEW.BDTIPOLANINCLU IS NULL) OR (NEW.BDTIPOLANINCLU = 0)) THEN
     NEW.BDTIPOLANINCLU = NEW.BDCODTIPO;
  
  --CAMPO FUNDAP PADRAO FALSE Sol. 193804
  if ((NEW.BDFUNDAP is null) or (NEW.bdfundap = ''))  then
     NEW.BDFUNDAP = 'FALSE';
  end
END
^


CREATE OR ALTER trigger vef_emp_tmovent_bu0 for vef_emp_tmovent
active before update position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.BDCODTIPO not in (101, 102, 200, 3000)) and (new.BDNUMDOCINI <> old.BDNUMDOCINI)) then
    begin
        exception EX_CHAVE_EM_USO;
        exit;
    end  
  NEW.bdreflan = CAST( SUBSTRING(CAST(NEW.bddataentradaent AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.bddataentradaent AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);

  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;

  SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
  IF ((vcodigo <> 0 ) AND (vcodigo IS NOT NULL )) THEN
    NEW.bdcodusu = vcodigo;

    /*Atualizado a tabela de movimentação de produtor rural*/
  if (OLD.BDCODTER <> NEW.BDCODTER AND EXISTS (SELECT FIRST 1 BDORDEM FROM VEF_EMP_TMOVENTPR PR WHERE PR.BDCODEMP = NEW.BDCODEMP AND PR.BDCHAVE = NEW.BDCHAVE)) then
     BEGIN
      UPDATE VEF_EMP_TMOVENTPR PR SET
      PR.BDCODTER = NEW.BDCODTER
      WHERE PR.BDCODEMP = NEW.BDCODEMP
      AND   PR.BDCHAVE  = NEW.BDCHAVE;
  END
  end
END
^

CREATE OR ALTER TRIGGER tr_bf_insert_vef_emp_tmovser FOR vef_emp_tmovser
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE wTipoLan INTEGER;
  DECLARE VARIABLE wReferenciaParametro DATE;
  DECLARE VARIABLE wDataParametro VARCHAR(50);
  DECLARE VARIABLE wCampoServico VARCHAR(50);
  DECLARE VARIABLE wDataReferencia DATE;

BEGIN
  IF (COALESCE(RDB$GET_CONTEXT('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') THEN
    BEGIN

      IF (NEW.bdcodusu IS NULL) THEN
        BEGIN
          SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
          NEW.bdcodusu = vcodigo;
        END
    
      IF (NEW.bdcodusuinclu IS NULL) THEN
        BEGIN
          SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
          NEW.bdcodusuinclu = vcodigo;
        END

      wDataReferencia = NEW.BDDATAEMISSAO;

      wTipoLan = COALESCE(NEW.BDTIPLAN, 0);
      IF (wTipoLan = 0) THEN
        wCampoServico = 'BDSEREMIPOREXECUCAO';
      ELSE
      IF (wTipoLan = 1) THEN
        wCampoServico = 'BDSERRECPOREXECUCAO';

      IF (wCampoServico IS NOT NULL) THEN
        BEGIN
          SELECT P.BDVALOR FROM TPARGER P WHERE UPPER(P.BDCAMPO) = :wCampoServico INTO wDataParametro;
          IF (wDataParametro IS NOT NULL) THEN
            BEGIN
              wReferenciaParametro = CAST(SUBSTRING(wDataParametro FROM 7 FOR 4) ||'-'|| SUBSTRING(wDataParametro FROM 4 FOR 2) ||'-'|| SUBSTRING(wDataParametro FROM 1 FOR 2) AS DATE);
              IF (NEW.BDDATAEMISSAO >= wReferenciaParametro) THEN
                wDataReferencia = NEW.BDDT_EXE_SERV;
            END
        END

      NEW.BDREFLAN = CAST( SUBSTRING(CAST(wDataReferencia AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(wDataReferencia AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);
      
      NEW.bddatalan = CURRENT_DATE;
      NEW.bdhoralan = CURRENT_TIME;
    
      NEW.bddatainclusao = NEW.bddatalan;
      NEW.bdhorainclusao = NEW.bdhoralan;
    
      --TIPO DO LANCAMENTO DA TABELA TIPOS_LANCAMENTOS_PADRAO
      IF ((NEW.BDCODTIPO IS NULL) OR (NEW.BDCODTIPO = 0)) THEN
        NEW.BDCODTIPO = 101;
    
      IF ((NEW.BDTIPOLANINCLU IS NULL) OR (NEW.BDTIPOLANINCLU = 0)) THEN
        NEW.BDTIPOLANINCLU = NEW.BDCODTIPO;
    
      /* sol.: #9828 Jean 16/12/2014: SUBSERIE não pode mais ser NULL*/
      IF (NEW.BDSUBSERIE IS NULL) THEN
        NEW.BDSUBSERIE = '';
    END
END
^

CREATE OR ALTER trigger vef_emp_tmovser_bu0 for vef_emp_tmovser
active before update position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE wTipoLan INTEGER;
  DECLARE VARIABLE wReferenciaParametro DATE;
  DECLARE VARIABLE wDataParametro VARCHAR(50);
  DECLARE VARIABLE wCampoServico VARCHAR(50);
  DECLARE VARIABLE wDataReferencia DATE;
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.BDCODTIPO not in (101, 102, 200, 3000)) and (new.BDNUMDOCINI <> old.BDNUMDOCINI)) then
    begin
        exception EX_CHAVE_EM_USO;
        exit;
    end
 
  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;

  SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
  IF ((vcodigo <> 0 ) AND (vcodigo IS NOT NULL )) THEN
    NEW.bdcodusu = vcodigo;
    
  wDataReferencia = NEW.BDDATAEMISSAO;

  wTipoLan = COALESCE(NEW.BDTIPLAN, 0);
  IF (wTipoLan = 0) THEN
    wCampoServico = 'BDSEREMIPOREXECUCAO';
  ELSE
  IF (wTipoLan = 1) THEN
    wCampoServico = 'BDSERRECPOREXECUCAO';

  IF (wCampoServico IS NOT NULL) THEN
    BEGIN
      SELECT P.BDVALOR FROM TPARGER P WHERE UPPER(P.BDCAMPO) = :wCampoServico INTO wDataParametro;
      IF (wDataParametro IS NOT NULL) THEN
        BEGIN
          wReferenciaParametro = CAST(SUBSTRING(wDataParametro FROM 7 FOR 4) ||'-'|| SUBSTRING(wDataParametro FROM 4 FOR 2) ||'-'|| SUBSTRING(wDataParametro FROM 1 FOR 2) AS DATE);
          IF (NEW.BDDATAEMISSAO >= wReferenciaParametro) THEN
            wDataReferencia = NEW.BDDT_EXE_SERV;
        END
    END

  NEW.BDREFLAN = CAST( SUBSTRING(CAST(wDataReferencia AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(wDataReferencia AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);

  /* sol.: #9828 Jean 16/12/2014: SUBSERIE não pode mais ser NULL*/
  IF (NEW.BDSUBSERIE IS NULL) THEN
     NEW.BDSUBSERIE = '';
  /*ATUALIZAR O CÓDIGO DO TERCEIRO NA TABELA DE MOV DO PRODUTOR RURAL*/
  if (OLD.BDCODTER <> NEW.BDCODTER AND EXISTS (SELECT FIRST 1 BDORDEM FROM VEF_EMP_TMOVSERPR PR WHERE PR.BDCODEMP = NEW.BDCODEMP AND PR.BDCHAVE = NEW.BDCHAVE)) then
     BEGIN
       UPDATE VEF_EMP_TMOVSERPR PR SET
       PR.BDCODTER = NEW.BDCODTER
       WHERE PR.BDCODEMP = NEW.BDCODEMP
       AND   PR.BDCHAVE  = NEW.BDCHAVE;
     END
  end
END
^

CREATE OR ALTER TRIGGER vef_emp_tmovinv_bi0 FOR vef_emp_tmovinv
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vChave INTEGER;
BEGIN
  IF ((NEW.bdcodtipo = 101) OR (NEW.bdcodtipo = 102)) THEN
     BEGIN
       vcodigo = 0;
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tmovinv WHERE bdcodemp = NEW.bdcodemp INTO vChave;
           NEW.bdchave = vChave;
         END
       ELSE
         BEGIN
           SELECT bdchave FROM vef_emp_tmovinv WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
    
           IF (vcodigo > 0) THEN
             BEGIN
               SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tmovinv WHERE bdcodemp = NEW.bdcodemp INTO vChave;
               NEW.bdchave = vChave;
             END
         END
     END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --
  -- só atribui o usuário se for nulo
  IF (NEW.bdcodusu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusu = vcodigo;
    END

  IF (NEW.bdcodusuinclu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusuinclu = vcodigo;
    END

  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;

  NEW.bddatainclusao = NEW.bddatalan;
  NEW.bdhorainclusao = NEW.bdhoralan;

  --TIPO DO LANCAMENTO DA TABELA TIPOS_LANCAMENTOS_PADRAO
  IF ((NEW.BDCODTIPO IS NULL) OR (NEW.BDCODTIPO = 0)) THEN
     NEW.BDCODTIPO = 101;

  IF ((NEW.BDTIPOLANINCLU IS NULL) OR (NEW.BDTIPOLANINCLU = 0)) THEN
     NEW.BDTIPOLANINCLU = NEW.BDCODTIPO;
END
^


CREATE OR ALTER TRIGGER vef_emp_tmovinv_bu0 FOR vef_emp_tmovinv
ACTIVE BEFORE UPDATE POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;

  SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
  IF ((vcodigo <> 0 ) AND (vcodigo IS NOT NULL )) THEN
    NEW.bdcodusu = vcodigo;
END
^

CREATE OR ALTER TRIGGER vef_emp_tmovdemaisdoc_f100_bi0 FOR vef_emp_tmovdemaisdoc_f100
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  NEW.bdreflan = CAST( SUBSTRING(CAST(NEW.bddt_oper AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.bddt_oper AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);

  IF (NEW.bdcodusu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusu = vcodigo;
    END

  IF (NEW.bdcodusuinclu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusuinclu = vcodigo;
    END

  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;

  NEW.bddatainclusao = NEW.bddatalan;
  NEW.bdhorainclusao = NEW.bdhoralan;

  --TIPO DO LANCAMENTO DA TABELA TIPOS_LANCAMENTOS_PADRAO
  IF ((NEW.BDCODTIPO IS NULL) OR (NEW.BDCODTIPO = 0)) THEN
     NEW.BDCODTIPO = 101;

  IF ((NEW.BDTIPOLANINCLU IS NULL) OR (NEW.BDTIPOLANINCLU = 0)) THEN
     NEW.BDTIPOLANINCLU = NEW.BDCODTIPO;
END
^

CREATE OR ALTER trigger VEF_EMP_TMOVDEMAISDOC_F100_BU0 for VEF_EMP_TMOVDEMAISDOC_F100
active before update position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  NEW.bdreflan = CAST( SUBSTRING(CAST(NEW.bddt_oper AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.bddt_oper AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);

  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;

  SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
  IF ((vcodigo <> 0 ) AND (vcodigo IS NOT NULL )) THEN
    NEW.bdcodusu = vcodigo;

  if ((OLD.BDIND_OPER <> NEW.BDIND_OPER AND OLD.BDCODTER = NEW.BDCODTER) AND EXISTS (SELECT FIRST 1 BDCHAVE FROM VEF_EMP_TMOVDEMAISDOCPR PR WHERE PR.BDCODEMP = NEW.BDCODEMP AND PR.BDCHAVE = NEW.BDCHAVE)) then
     BEGIN
      UPDATE VEF_EMP_TMOVDEMAISDOCPR PR SET
      PR.BDTIPOPE = IIF(NEW.BDIND_OPER = 1,0,1)
      WHERE PR.BDCODEMP = NEW.BDCODEMP
      AND   PR.BDCHAVE  = NEW.BDCHAVE;
END

END
^


CREATE OR ALTER TRIGGER vef_emp_tredz_bi0 FOR vef_emp_tredz
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vChave INTEGER;
BEGIN
  IF ((NEW.bdcodtipo = 101) OR (NEW.bdcodtipo = 102)) THEN
     BEGIN
       vcodigo = 0;
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tredz WHERE bdcodemp = NEW.bdcodemp INTO vChave;
           NEW.bdchave = vChave;
         END
       ELSE
         BEGIN
           SELECT bdchave FROM vef_emp_tredz WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
    
           IF (vcodigo > 0) THEN
             BEGIN
               SELECT COALESCE((MAX(bdchave)+1), 1) FROM vef_emp_tredz WHERE bdcodemp = NEW.bdcodemp INTO vChave;
               NEW.bdchave = vChave;
             END
       END

       SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
       NEW.bdcodusu = vcodigo;
     END

--////////////////////////////////////////////////////////////////////////////////////////////////--
  -- GRAVA OS CAMPOS AUTOMATICO --

  IF (NEW.bdcodusuinclu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
      NEW.bdcodusuinclu = vcodigo;
    END

  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;

  NEW.bddatainclusao = NEW.bddatalan;
  NEW.bdhorainclusao = NEW.bdhoralan;

  --TIPO DO LANCAMENTO DA TABELA TIPOS_LANCAMENTOS_PADRAO
  IF ((NEW.BDCODTIPO IS NULL) OR (NEW.BDCODTIPO = 0)) THEN
     NEW.BDCODTIPO = 101;

  IF ((NEW.BDTIPOLANINCLU IS NULL) OR (NEW.BDTIPOLANINCLU = 0)) THEN
     NEW.BDTIPOLANINCLU = NEW.BDCODTIPO;

  NEW.bdreflan = CAST(SUBSTRING(CAST(NEW.BDDATAREDZ AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.BDDATAREDZ AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER vef_emp_tredz_bu0 FOR vef_emp_tredz
ACTIVE BEFORE UPDATE POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  NEW.bdreflan = CAST(SUBSTRING(CAST(NEW.BDDATAREDZ AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.BDDATAREDZ AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);

  NEW.bddatalan = CURRENT_DATE;
  NEW.bdhoralan = CURRENT_TIME;

  SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodigo;
  IF ((vcodigo <> 0 ) AND (vcodigo IS NOT NULL )) THEN
    NEW.bdcodusu = vcodigo;
END
^


CREATE OR ALTER TRIGGER vsuc_empresas_valorpresente_bi0 FOR vsuc_empresas_valorpresente
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF ((NEW.bdcodvlrpres IS NULL) OR (NEW.bdcodvlrpres = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodvlrpres)+1), 1) FROM vsuc_empresas_valorpresente WHERE bdcodemp = NEW.bdcodemp INTO :vcodigo;
      NEW.bdcodvlrpres = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodvlrpres FROM vsuc_empresas_valorpresente WHERE (bdcodvlrpres = NEW.bdcodvlrpres) AND (bdcodemp = NEW.bdcodemp) INTO :vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodvlrpres)+1), 1) FROM vsuc_empresas_valorpresente WHERE bdcodemp = NEW.bdcodemp INTO :vcodigo;
           NEW.bdcodvlrpres = vcodigo;
         END
    END
  NEW.bdcontabilizacao = NEW.bdcontabilizacao + 1; --#alt:15359 - No combo so tem fiscal e societária, por isso soma. 0 - ambas, 1 - fiscal, 2 - societária. Ana - 07/10/2016
END
^

--#alt:15359 - Criada novas triggers para controle da contabilização. Ana - 10/10/2016
CREATE OR ALTER TRIGGER tr_bf_update_vsuc_empresas_tlan FOR vsuc_empresas_tlan
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
   IF (NEW.BDTIPOLAN = 26) THEN
    IF (NEW.bdcontabilizacao <= 0) THEN
        NEW.bdcontabilizacao = 1;
      ELSE
        IF (NEW.bdcontabilizacao >= 1) THEN
            NEW.bdcontabilizacao = 2; --#alt:15359 - No combo so tem fiscal e societária, por isso soma. 0 - ambas, 1 - fiscal, 2 - societária. Ana - 07/10/2016

   --#alt:13456 - Atribui ao novo campo o valor de 0 se este não possui nenhum valor. Ana - 28/10/2016
   IF ((NEW.bdtipoconc IS NULL) AND (OLD.bdtipolan IS NULL)) THEN
        NEW.bdtipoconc = 0;
   --#alt:13456. fim
    
   IF (old.bddata <> new.bddata) then
     BEGIN
       SELECT CAST(BDAAAAMM AS INTEGER) FROM AAAAMM(NEW.bddata) INTO NEW.bdreferencia;
     END
     
   --alt:14942 - 18/01/2017 - Caso marque os lançamentos como conciliados que antes eram pendentes, deve demover o devido status. Pedro
   IF ((UPPER(COALESCE(OLD.BDCONCD, 'FALSE')) = 'FALSE') AND (UPPER(COALESCE(NEW.BDCONCD, 'FALSE')) = 'TRUE') AND (OLD.BDCONCILIACAOPENDENTE IN (1,3))) THEN
     BEGIN
       NEW.BDCONCILIACAOPENDENTE = OLD.BDCONCILIACAOPENDENTE -1;
       DELETE FROM VSUC_EMPRESAS_TOBS WHERE BDCODEMP = NEW.BDCODEMP AND BDCHAVE = NEW.BDCHAVE AND BDDEBCRE = 0;
     END

   IF ((UPPER(COALESCE(OLD.BDCONCC, 'FALSE')) = 'FALSE') AND (UPPER(COALESCE(NEW.BDCONCC, 'FALSE')) = 'TRUE') AND (OLD.BDCONCILIACAOPENDENTE IN (2,3))) THEN
     BEGIN
       NEW.BDCONCILIACAOPENDENTE = OLD.BDCONCILIACAOPENDENTE -2;
       DELETE FROM VSUC_EMPRESAS_TOBS WHERE BDCODEMP = NEW.BDCODEMP AND BDCHAVE = NEW.BDCHAVE AND BDDEBCRE = 1;
     END
   --alt:14942 - Fim
   
   if (coalesce(OLD.BDTIPOLANORIG, 0) = 0) then
      NEW.BDTIPOLANORIG = OLD.bdtipolan;

  IF (NEW.bddatalanalt IS NULL) THEN
    NEW.bddatalanalt = CURRENT_DATE;

  IF (NEW.bdhoralanalt IS NULL) THEN
    NEW.bdhoralanalt = CURRENT_TIME;
END^

CREATE OR ALTER TRIGGER tr_bf_update_vsuc_empresas_vp FOR vsuc_empresas_valorpresente
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  IF (NEW.bdcontabilizacao <= 0) THEN
    NEW.bdcontabilizacao = 1;
  ELSE
    IF (NEW.bdcontabilizacao >= 1) THEN
        NEW.bdcontabilizacao = 2; --#alt:15359 - No combo so tem fiscal e societária, por isso soma. 0 - ambas, 1 - fiscal, 2 - societária. Ana - 07/10/2016
END^
--#alt:15359. fim



CREATE OR ALTER TRIGGER TMP_VEF_EMP_TMOVSER_BI FOR TMP_VEF_EMP_TMOVSER
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  /* sol.: #9828 Jean 17/12/2014: os campos são comparados com igual (sem fazer coalesce)
  se algum comparado no where estiver nulo, o resultado sempre será nulo */
  IF (NEW.bdtiplan IS NULL) THEN
    NEW.bdtiplan = 0;

  IF (NEW.bdnumdocini IS NULL) THEN
    NEW.bdnumdocini = '';

  IF (NEW.bdnumdocfim IS NULL) THEN
    NEW.bdnumdocfim = '';

  IF (NEW.bdespecie IS NULL) THEN
    NEW.bdespecie = '';

  IF (NEW.bdserie IS NULL) THEN
    NEW.bdserie = '';

  IF (NEW.bdsubserie IS NULL) THEN
    NEW.bdsubserie = '';

  IF (NEW.bddataemissao IS NULL) THEN
    NEW.bddataemissao = CURRENT_DATE;
END
^

CREATE OR ALTER TRIGGER TMP_VEF_EMP_TMOVSER_BU FOR TMP_VEF_EMP_TMOVSER
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  /* sol.: #9828 Jean 17/12/2014: os campos são comparados com igual (sem fazer coalesce)
  se algum comparado no where estiver nulo, o resultado sempre será nulo */
  IF (NEW.bdtiplan IS NULL) THEN
    NEW.bdtiplan = 0;

  IF (NEW.bdnumdocini IS NULL) THEN
    NEW.bdnumdocini = '';

  IF (NEW.bdnumdocfim IS NULL) THEN
    NEW.bdnumdocfim = '';

  IF (NEW.bdespecie IS NULL) THEN
    NEW.bdespecie = '';

  IF (NEW.bdserie IS NULL) THEN
    NEW.bdserie = '';

  IF (NEW.bdsubserie IS NULL) THEN
    NEW.bdsubserie = '';

  IF (NEW.bddataemissao IS NULL) THEN
    NEW.bddataemissao = CURRENT_DATE;
END
^

CREATE OR ALTER TRIGGER vrhf_base_tconf_impcp_bi0 FOR vrhf_base_tconf_impcp
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF ((NEW.bdcodficp IS NULL) OR (NEW.bdcodficp = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodficp), 0) + 1 FROM VRHF_BASE_TCONF_IMPCP INTO :vCodigo;
       NEW.bdcodficp = :vCodigo;
     END
END^

CREATE OR ALTER TRIGGER vrhf_base_tferiemp_bi0 FOR vrhf_base_tferiemp
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE vMes VARCHAR(2);
DECLARE VARIABLE vDia VARCHAR(2);
BEGIN
  /* Trigger text */
  IF (strlen(CAST(NEW.bddiamesfes AS VARCHAR(4))) < 4) THEN
    BEGIN
      vDia = '0'||SUBSTRING(CAST(NEW.bddiamesfes AS VARCHAR(4)) FROM 1 FOR 1);
      vMes = SUBSTRING(CAST(NEW.bddiamesfes AS VARCHAR(4)) FROM 2 FOR 2);
    END
  ELSE
    BEGIN
      vDia = SUBSTRING(CAST(NEW.bddiamesfes AS VARCHAR(4)) FROM 1 FOR 2);
      vMes = SUBSTRING(CAST(NEW.bddiamesfes AS VARCHAR(4)) FROM 3 FOR 2);
    END

  NEW.bdmesdiafes = vMes||vDia;
END^

CREATE OR ALTER TRIGGER vrhf_base_tferiemp_bu0 FOR vrhf_base_tferiemp
ACTIVE BEFORE UPDATE POSITION 0
AS
DECLARE VARIABLE vMes VARCHAR(2);
DECLARE VARIABLE vDia VARCHAR(2);
BEGIN
  /* Trigger text */
  IF (strlen(CAST(NEW.bddiamesfes AS VARCHAR(4))) < 4) THEN
    BEGIN
      vDia = '0'||SUBSTRING(CAST(NEW.bddiamesfes AS VARCHAR(4)) FROM 1 FOR 1);
      vMes = SUBSTRING(CAST(NEW.bddiamesfes AS VARCHAR(4)) FROM 2 FOR 2);
    END
  ELSE
    BEGIN
      vDia = SUBSTRING(CAST(NEW.bddiamesfes AS VARCHAR(4)) FROM 1 FOR 2);
      vMes = SUBSTRING(CAST(NEW.bddiamesfes AS VARCHAR(4)) FROM 3 FOR 2);
    END

  NEW.bdmesdiafes = vMes||vDia;
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER PROCEDURE SP_PRODEXISTENTES (
    BDCODEMP INTEGER,
    BDEAN VARCHAR(20),
    BDCODTER INTEGER,
    BDCODENTRADA VARCHAR(60),
    BDDESCPRODBUSCA VARCHAR(200))
RETURNS (
    CODPROD INTEGER,
    ORDEMCADPART INTEGER,
    CODSAIDA VARCHAR(60),
    CODNCM INTEGER)
AS
DECLARE VARIABLE WEAN13 VARCHAR(20);
DECLARE VARIABLE WTMP INTEGER;
DECLARE VARIABLE WPRIMVEZ INTEGER;
DECLARE VARIABLE WIGNORA INTEGER;
DECLARE VARIABLE WEAN VARCHAR(20);
DECLARE VARIABLE WDESCPRODBUSCA VARCHAR(200);
DECLARE VARIABLE WCODENTRADA VARCHAR(60);
DECLARE VARIABLE WACHOU INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WTMPORDEM INTEGER;
BEGIN
  CODPROD = 0;
  ordemcadpart = 0;
  codsaida = '';
  codncm = 0;

  --Metodo 1
  FOR SELECT BDCODPROD, BDCODENTRADA, BDDESCPRODBUSCA, bdORDEM
      FROM TCADPRO_PART
      WHERE
      BDCODTER=:BDCODTER AND BDCODENTRADA=:BDCODENTRADA
      ORDER BY BDCODPROD,BDORDEM
  INTO WCODTER, WCODENTRADA, WDESCPRODBUSCA, WTMPORDEM
  DO
  BEGIN
    IF (UPPER(WDESCPRODBUSCA) = UPPER(BDDESCPRODBUSCA)) THEN
    BEGIN
      CODPROD = wCODTER;
      BREAK;
    END
  END

  --Metodo2
  IF ((CODPROD = 0) AND (BDEAN <> '') AND (BDEAN <> '#')) THEN
  BEGIN
    --select BDCODIGOEAN, BDCODTER, BDCODENTRADA, BDCODPROD from TCADPRO where
    wIgnora = 0;
    wPrimVez = 1;
    FOR SELECT cadpro.BDCODIGOEAN, part.BDCODTER, part.BDCODENTRADA, cadpro.BDDESCRICAOUNICA, cadpro.BDCODPROD, part.bdORDEM
    FROM TCADPRO CADPRO
    LEFT OUTER JOIN TCADPRO_PART part ON (part.bdcodprod = cadpro.bdcodprod)
    WHERE cadpro.BDCODIGOEAN=:BDEAN AND part.BDCODTER=:BDCODTER AND part.BDCODENTRADA=:BDCODENTRADA
    INTO :wean, :wcodter, :wcodentrada, :wdescprodbusca, :wTmp, :WTMPORDEM DO
    BEGIN
      IF (wPrimVez = 1) THEN
      BEGIN
        IF (UPPER(wdescprodbusca) <> UPPER(bddescprodbusca)) THEN
        BEGIN
          wIgnora = 1;
        END
      END

      IF (wIgnora = 0) THEN --not wIgnora
      BEGIN
        IF (UPPER(wdescprodbusca) = UPPER(bddescprodbusca)) THEN
        BEGIN
          CODPROD = wTmp;
          BREAK;
        END
      END

      wIgnora = 0;
      wPrimVez = 0;
    END
  END

  IF (codprod > 0) THEN
    ordemcadpart = :wtmpordem;

  --feito o ean ser o terceiro metodo de pesquisa (GetEAN)
  IF ((CODPROD = 0) AND (BDEAN <> '') AND (BDEAN <> '#')) THEN
  BEGIN
    IF ((CHARACTER_LENGTH(BDEAN) = 14) AND (SUBSTRING(bdean FROM 1 FOR 1) = '0')) THEN
       wEAN13 = SUBSTRING(bdean FROM 2 FOR 13);
     ELSE
       wEAN13 = BDEAN;

     wIgnora = 0;
     FOR SELECT BDCODPROD, BDCODIGOEAN, BDDESCRICAOUNICA FROM TCADPRO WHERE BDCODIGOEAN = :wEAN13
     INTO :wTMP, :wEAN, :WDESCPRODBUSCA DO
     BEGIN
       CODPROD = :wTMP;
       IF (UPPER(wdescprodbusca) = UPPER(bddescprodbusca)) THEN
         wIgnora = 1;

       IF (wIgnora = 0) THEN --not wIgnora
       BEGIN
         IF (UPPER(wdescprodbusca) = UPPER(bddescprodbusca)) THEN
         BEGIN
           CODPROD = :wTMP;
           BREAK;
         END
       END

       wIgnora = 0;
     END

     --if FDAOCadPart.DAOProdutosExistentes.SearchKey(['BDCODTER', 'BDCODENTRADA','BDDESCPRODBUSCA'], [FCodTer, FCodProdLay, FDescProdLay]) then //alt.:9666
     FOR SELECT CADPRO.BDDESCRICAOUNICA, part.BDORDEM
     FROM TCADPRO_PART part
     LEFT OUTER JOIN TCADPRO CADPRO ON (part.bdcodprod = cadpro.bdcodprod)
     WHERE BDCODTER=:BDCODTER AND BDCODENTRADA=:BDCODENTRADA AND BDDESCPRODBUSCA = :BDDESCPRODBUSCA
     INTO :wDESCPRODBUSCA, :wTmpOrdem DO
     BEGIN
       ordemcadpart = :wTmpOrdem;
       IF (UPPER(wDESCPRODBUSCA) = UPPER(BDDESCPRODBUSCA)) THEN
       BEGIN
         BREAK;
       END
     END
  END

  --metódo 3
  IF ((CODPROD = 0)) THEN
  BEGIN
    --Procura pela descricao naquela empresa
--    select first 1 coalesce(CADPRO.bdcodprod, 0)
--    from TCADPRO CADPRO
--    left outer join TCADPRO_VINC VINC on (vinc.bdcodprod = cadpro.bdcodprod and vinc.bdcodemp = :BDCODEMP)
--    where (CADPRO.BDDESCRICAOUNICA collate WIN1252) = :bddescprodbusca into :CODPROD;
    SELECT FIRST 1 COALESCE(CADPRO.bdcodprod, 0)
    FROM (
          SELECT *
          FROM TCADPRO
          WHERE BDDESCRICAOUNICA = :bddescprodbusca
          )CADPRO
    LEFT OUTER JOIN TCADPRO_VINC VINC ON (vinc.bdcodprod = cadpro.bdcodprod AND vinc.bdcodemp = :BDCODEMP)
    INTO :CODPROD;
  --alt:14920 - Elizeu - 27/06/16 - criado opção pra não carregar os dados cadastrais dos produtos na memória

    --Se nao achar procura unicamente pela descricao
    IF (CODPROD = 0) THEN
    BEGIN
      SELECT FIRST 1 CADPRO.bdcodprod
      FROM TCADPRO CADPRO
      WHERE CADPRO.BDDESCRICAOUNICA  = :bddescprodbusca INTO :CODPROD;
    END
  END

  IF (CODPROD > 0) THEN
  BEGIN
    SELECT bdCODSAIDA, bdNCMPROD FROM TCADPRO_VINC WHERE bdcodemp=:BDCODEMP AND bdcodprod = :codprod INTO :codsaida, :codNCM;
  END

  SUSPEND;
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vrh_rhnet_tfotos_bi0 FOR vrh_rhnet_tfotos
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  /* Trigger text */
  IF (NEW.bdcodimg IS NULL) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodimg), 0) + 1 FROM vrh_rhnet_tfotos INTO NEW.bdcodimg;
     END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER VRH_RHNET_TFOTOS_EXP_BI0 FOR VRH_RHNET_TFOTOS_EXP
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  /* Trigger text */
  IF (coalesce(NEW.bdcodimg, 0) <= 0) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodimg), 0) + 1 FROM vrh_rhnet_tfotos_exp INTO NEW.bdcodimg;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_EMP_INSTESTADIC_BI0 FOR VRH_BASE_EMP_INSTESTAGIOADIC
ACTIVE BEFORE INSERT POSITION 0
AS
declare variable vcod INTEGER;
begin
  if (COALESCE(new.bdcodentedu, 0) = 0) then
     begin
       select COALESCE(MAX(BDCODENTEDU) + 1, 1) from VRH_BASE_EMP_INSTESTAGIOADIC where BDCODEMP = new.bdcodemp into :vcod;
       new.bdcodentedu = :vcod;
     end
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TAPUE115_AD0 FOR TOL_VEF_EMP_TAPUE115
ACTIVE AFTER DELETE POSITION 0
AS
begin
  DELETE FROM vef_emp_tajuicmse115 aju where aju.bdcodemp = old.bdcodemp and aju.bdordeme115 = old.bdordeme115;
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TAJUENTM220620_AD0 FOR TOL_VEF_EMP_TAJUENTAPUPCM220620
ACTIVE AFTER DELETE POSITION 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
     delete from VEF_EMP_TAJUAPUPCM220620 M where M.bdcodemp = old.bdcodemp and M.bdchave = old.BDCHAVEM220620;
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TAJUSTEIPIE531_BI0 FOR VEF_EMP_TAJUSTEIPIE531
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vORDEME530 INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT (MAX(bdchave)) FROM vef_emp_tajusteipie530 WHERE bdcodemp = NEW.bdcodemp INTO vORDEME530;
      NEW.bdchave = vORDEME530;
    END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_IMG_BU0 FOR VRH_EMP_TCOLCON_IMG
ACTIVE BEFORE UPDATE POSITION 0
AS
  DECLARE VARIABLE vCodImg INTEGER;
BEGIN
  IF (COALESCE(NEW.bdisrhnet, 0) = 1) THEN
    BEGIN
      IF (TRIM(COALESCE(NEW.BDFOTORHNET, '')) = '') THEN
         NEW.BDFOTOCOL_IMG = NULL;
      ELSE
         BEGIN
           vCodImg = 0;
           SELECT BDCODIMG FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTORHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTORHNET))) INTO vCodImg;
           IF (vCodImg > 0) THEN
             BEGIN
               NEW.BDFOTOCOL_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTORHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTORHNET))));
               DELETE FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTORHNET);
             END
           ELSE
             NEW.BDFOTOCOL_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTORHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDFOTORHNET))));
         END

      NEW.BDFOTORHNET = '';

      IF (TRIM(COALESCE(NEW.BDCPFRHNET, '')) = '') THEN
         NEW.BDCPF_IMG = NULL;
      ELSE
         BEGIN
           vCodImg = 0;
           SELECT BDCODIMG FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCPFRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCPFRHNET))) INTO vCodImg;
           IF (vCodImg > 0) THEN
             BEGIN
               NEW.BDCPF_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCPFRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCPFRHNET))));
               DELETE FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCPFRHNET);
             END
           ELSE
             NEW.BDCPF_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCPFRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCPFRHNET))));
         END

      NEW.BDCPFRHNET = '';

      IF (TRIM(COALESCE(NEW.BDRGRHNET, '')) = '') THEN
         NEW.BDRG_IMG = NULL;
      ELSE
         BEGIN
           vCodImg = 0;
           SELECT BDCODIMG FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDRGRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDRGRHNET))) INTO vCodImg;
           IF (vCodImg > 0) THEN
             BEGIN
               NEW.BDRG_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDRGRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDRGRHNET))));
               DELETE FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDRGRHNET);
             END
           ELSE
             NEW.BDRG_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDRGRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDRGRHNET))));
         END

      NEW.BDRGRHNET = '';

      IF (TRIM(COALESCE(NEW.BDPISRHNET, '')) = '') THEN
         NEW.BDPIS_IMG = NULL;
      ELSE
         BEGIN
           vCodImg = 0;
           SELECT BDCODIMG FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDPISRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDPISRHNET))) INTO vCodImg;
           IF (vCodImg > 0) THEN
             BEGIN
               NEW.BDPIS_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDPISRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDPISRHNET))));
               DELETE FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDPISRHNET);
             END
           ELSE
             NEW.BDPIS_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDPISRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDPISRHNET))));
         END

      NEW.BDPISRHNET = '';

      IF (TRIM(COALESCE(NEW.BDTITRHNET, '')) = '') THEN
         NEW.BDTITELEITOR_IMG = NULL;
      ELSE
         BEGIN
           vCodImg = 0;
           SELECT BDCODIMG FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDTITRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDTITRHNET))) INTO vCodImg;
           IF (vCodImg > 0) THEN
             BEGIN
               NEW.BDTITELEITOR_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDTITRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDTITRHNET))));
               DELETE FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDTITRHNET);
             END
           ELSE
             NEW.BDTITELEITOR_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDTITRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDTITRHNET))));
         END

      NEW.BDTITRHNET = '';

      IF (TRIM(COALESCE(NEW.BDCNHRHNET, '')) = '') THEN
         NEW.BDCNH_IMG = NULL;
      ELSE
         BEGIN
           vCodImg = 0;
           SELECT BDCODIMG FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCNHRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCNHRHNET))) INTO vCodImg;
           IF (vCodImg > 0) THEN
             BEGIN
               NEW.BDCNH_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCNHRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCNHRHNET))));
               DELETE FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCNHRHNET);
             END
           ELSE
             NEW.BDCNH_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCNHRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCNHRHNET))));
         END

      NEW.BDCNHRHNET = '';

      IF (TRIM(COALESCE(NEW.BDCTPSRHNET, '')) = '') THEN
         NEW.BDCTPS_IMG = NULL;
      ELSE
         BEGIN
           vCodImg = 0;
           SELECT BDCODIMG FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCTPSRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCTPSRHNET))) INTO vCodImg;
           IF (vCodImg > 0) THEN
             BEGIN
               NEW.BDCTPS_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCTPSRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCTPSRHNET))));
               DELETE FROM VRH_RHNET_TFOTOS WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCTPSRHNET);
             END
           ELSE
             NEW.BDCTPS_IMG = (SELECT BDIMAGEM FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCTPSRHNET) AND (BDCODIMG = (SELECT MAX(BDCODIMG) FROM VRH_RHNET_TFOTOS_EXP WHERE UPPER(BDNOMEIMG) = UPPER(NEW.BDCTPSRHNET))));
         END

      NEW.BDCTPSRHNET = '';
    END

  NEW.bdisrhnet = 0;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_PARTIDA_BU0 FOR VRH_EMP_TCOLCON_PARTIDA
ACTIVE BEFORE UPDATE POSITION 0
AS
--  DECLARE VARIABLE vdataadm DATE;
--  DECLARE VARIABLE vcontrcol INTEGER;
--  DECLARE VARIABLE vsalbase NUMERIC(18,6);
--  DECLARE VARIABLE vsql VARCHAR(500);
--  DECLARE VARIABLE vcodmas INTEGER;
--  DECLARE VARIABLE vcodplafuc INTEGER;
--  DECLARE VARIABLE vcodtfuc INTEGER;
--  DECLARE VARIABLE vcodpqua INTEGER;
--  DECLARE VARIABLE vcodqh INTEGER;
--  DECLARE VARIABLE vregjor INTEGER;
--  DECLARE VARIABLE vtipjor INTEGER;

BEGIN
  /* Trigger text */
--  SELECT FIRST 1 BDDATAADMCOL, BDCONTRCOL FROM VRH_EMP_TCOLCON WHERE BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol INTO :vdataadm, :vcontrcol;

--  IF (vdataadm IS NOT NULL) THEN
--    BEGIN
--       if (COALESCE(old.bdsalinicol, 0) <> COALESCE(new.bdsalinicol, 0)) then
--          begin
--            UPDATE OR INSERT INTO VRH_EMP_TCOLCON_DIA (BDCODEMP, BDCODCOL, BDDATACOL, BDCONTRCOL) VALUES (NEW.bdcodemp, NEW.bdcodcol, :vdataadm, :vcontrcol) MATCHING (BDCODEMP, BDCODCOL, BDDATACOL);
--            UPDATE OR INSERT INTO VRH_EMP_TCOLCON_CALCDIA (BDCODEMP, BDCODCOL, BDDATACOL, BDSALBASECOL, BDCONTRCOL, bddescsalvar) VALUES (NEW.bdcodemp, NEW.bdcodcol, :vdataadm, NEW.bdsalinicol, :vcontrcol, new.bddescsalvar) MATCHING (BDCODEMP, BDCODCOL, BDDATACOL);
--          end
--
--       if ((COALESCE(old.bdcodplafuc, 0) <> COALESCE(new.bdcodplafuc, 0)) or (COALESCE(old.bdcodtfuc, 0) <> COALESCE(new.bdcodtfuc, 0)) or
--           (COALESCE(old.bdcodpqua, 0) <> COALESCE(new.bdcodpqua, 0)) or (COALESCE(old.bdcodqh, 0) <> COALESCE(new.bdcodqh, 0)) or
--           (COALESCE(old.bddesctpjornada, '') <> COALESCE(new.bddesctpjornada, '')) or (COALESCE(old.bdtipojornada, 0) <> COALESCE(new.bdtipojornada, 0))) then
--          begin
--            UPDATE OR INSERT INTO VRH_EMP_TCOLCON_DIA (BDCODEMP, BDCODCOL, BDDATACOL, BDCONTRCOL) VALUES (NEW.bdcodemp, NEW.bdcodcol, :vdataadm, :vcontrcol) MATCHING (BDCODEMP, BDCODCOL, BDDATACOL);
--            UPDATE OR INSERT INTO VRH_EMP_TCOL_VINCDIA (BDCODEMP,BDCODCOL,BDDATACOL,BDCODPLAFUC,BDCODTFUC,BDCODQH,BDCONTRCOL,BDCODPQUA,BDDESCTPJORNADA,BDTIPOJORNADA) VALUES (NEW.bdcodemp,  NEW.bdcodcol,  :vdataadm, NEW.bdcodplafuc, NEW.bdcodtfuc, NEW.bdcodqh, :vcontrcol, NEW.bdcodpqua, new.BDDESCTPJORNADA, new.bdtipojornada) MATCHING (BDCODEMP,BDCODCOL,BDDATACOL);
--          end
--
--       IF (NEW.bddatacol IS NOT NULL AND NEW.bddatacol > :vdataadm) THEN
--          BEGIN
--            UPDATE OR INSERT INTO VRH_EMP_TCOLCON_DIA (BDCODEMP, BDCODCOL, BDDATACOL, BDCONTRCOL) VALUES (NEW.bdcodemp, NEW.bdcodcol, NEW.bddatacol, :vcontrcol) MATCHING (BDCODEMP, BDCODCOL, BDDATACOL);
--
----            vsql = 'select first 1 BDSALBASECOL, BDCODMAS from VRH_EMP_TCOLCON_CALCDIA where BDCODEMP = '||NEW.bdcodemp||' and BDCODCOL = '||NEW.bdcodcol||' and BDDATACOL <= '''||NEW.bddatacol||''' order by BDDATACOL DESC ';
--            vsql = 'select first 1 CALC.BDSALBASECOL, CALC.BDCODMAS from VRH_EMP_TCOLCON_CALCDIA CALC ' ||
--                   'where CALC.BDCODEMP = '||NEW.bdcodemp||' and '||
--                         'CALC.BDCODCOL = '||NEW.bdcodcol||' and '||
--                         'CALC.BDDATACOL <= '''||NEW.bddatacol||''' and ' ||
--                         'CALC.BDDATAEFEITO =  (select max(BDDATAEFEITO) ' ||
--                                               'from VRH_EMP_TCOLCON_CALCDIA ' ||
--                                               'where BDCODEMP = '||NEW.bdcodemp||' and ' ||
--                                                     'BDCODCOL = '||NEW.bdcodcol||' and ' ||
--                                                     'BDDATACOL = CALC.BDDATACOL)' ||
--                         'order by BDDATACOL DESC ';
--            EXECUTE STATEMENT vsql INTO :vsalbase, :vcodmas;
--
--            UPDATE OR INSERT INTO VRH_EMP_TCOLCON_CALCDIA (BDCODEMP, BDCODCOL, BDDATACOL, BDSALBASECOL, BDCODMAS, BDCONTRCOL, BDDESCSALVAR) VALUES (NEW.bdcodemp, NEW.bdcodcol, NEW.bddatacol, :vsalbase, :vcodmas, :vcontrcol, new.bddescsalvar) MATCHING (BDCODEMP, BDCODCOL, BDDATACOL);
--
--            vsql = 'select first 1 BDCODPLAFUC, BDCODTFUC, BDCODPQUA, BDCODQH, BDREGJORTRAB, BDTIPOJORNADA from VRH_EMP_TCOL_VINCDIA where BDCODEMP = '||NEW.bdcodemp||' and BDCODCOL = '||NEW.bdcodcol||' and BDDATACOL <= '''||NEW.bddatacol||''' order by BDDATACOL DESC ';            
--/*            vsql = 'select first 1 CALC.BDSALBASECOL, CALC.BDCODMAS from VRH_EMP_TCOLCON_CALCDIA CALC ' ||
--                   'where CALC.BDCODEMP = '||NEW.bdcodemp||' and '||
--                         'CALC.BDCODCOL = '||NEW.bdcodcol||' and '||
--                         'CALC.BDDATACOL <= '''||NEW.bddatacol||''' and ' ||
--                         'CALC.BDDATAEFEITO =  (select max(BDDATAEFEITO) ' ||
--                                               'from VRH_EMP_TCOLCON_CALCDIA ' ||
--                                               'where BDCODEMP = '||NEW.bdcodemp||' and ' ||
--                                                     'BDCODCOL = '||NEW.bdcodcol||' and ' ||
--                                                     'BDDATACOL = CALC.BDDATACOL)' ||
--                         'order by BDDATACOL DESC ';*/
--            EXECUTE STATEMENT vsql INTO :vcodplafuc, :vcodtfuc, :vcodpqua, :vcodqh, :vregjor, :vtipjor;
--            UPDATE OR INSERT INTO VRH_EMP_TCOL_VINCDIA (BDCODEMP,BDCODCOL,BDDATACOL,BDCODPLAFUC,BDCODTFUC,BDCODQH,BDCONTRCOL,BDCODPQUA,BDREGJORTRAB,BDTIPOJORNADA) VALUES (NEW.bdcodemp,  NEW.bdcodcol, NEW.bddatacol, :vcodplafuc, :vcodtfuc, :vcodqh, :vcontrcol, :vcodpqua, :vregjor, :vtipjor) MATCHING (BDCODEMP,BDCODCOL,BDDATACOL);
--          END
--     END

  NEW.bddatacol = NULL;
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVSAI_SER_AD0 FOR TOL_VEF_EMP_TMOVSAI_SER
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE STATEMENT 'DELETE FROM VEF_EMP_TMOVSER WHERE BDCODEMP = '||OLD.BDCODEMP||' AND BDCHAVE = '||OLD.BDCHAVESER;
END
^

CREATE OR ALTER TRIGGER vef_emp_tmovk230_k250_bi0 FOR vef_emp_tmovk230_k250
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF ((NEW.bdreflan IS NULL) OR (NEW.bdreflan = 0)) THEN
    NEW.bdreflan = CAST( SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);
END
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER vef_emp_tmovk230_k250_bu0 FOR vef_emp_tmovk230_k250
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  IF ((NEW.bdreflan IS NULL) OR (NEW.bdreflan = 0)) THEN
       NEW.bdreflan = CAST( SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);
END
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER vef_emp_tmovestoquek220_bi0 FOR vef_emp_tmovestoquek220
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF ((NEW.bdreflan IS NULL) OR (NEW.bdreflan = 0)) THEN
       NEW.bdreflan = CAST( SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);

END
^

CREATE OR ALTER PROCEDURE VEF_TOTAIS_EXPORTACAO_SEFINNET (
    PREMP VARCHAR(9),
    PRDATAINI VARCHAR(12),
    PRDATAFIM VARCHAR(12),
    PRINDICADORISS VARCHAR(1),
    PRTIPOLANC VARCHAR(1))
RETURNS (
    BDCODEMP INTEGER,
    BDREFLAN INTEGER,
    BDIDCNAE VARCHAR(12),
    BDCODCFPS VARCHAR(9),
    BDCODCST INTEGER,
    BDQTDENFS INTEGER,
    BDNFS VARCHAR(4000),
    BDNFSCANC VARCHAR(4000),
    BDVLRCONTABTOTAL NUMERIC(15,2),
    BDBCISSSERTOTAL NUMERIC(15,2),
    BDALIQREDISSSER NUMERIC(15,6),
    BDVLRISSTOTAL NUMERIC(15,2))
AS
DECLARE WSQL VARCHAR(10000);
BEGIN

   wSQL =         'select BDCODEMP,  ';
   wSQL = wSQL || '       BDREFLAN,  ';
   wSQL = wSQL || '       BDIDCNAE,  ';
   wSQL = wSQL || '       BDCODCFPS,  ';
   wSQL = wSQL || '       BDCODCST,  ';
   wSQL = wSQL || '       SUM(BDQTDENFS) BDQTDENFS,  ';
   wSQL = wSQL || '       LIST(BDNFS) BDNFS,  ';
   wSQL = wSQL || '       LIST(BDNFSCANC) BDNFSCANC,  ';
   wSQL = wSQL || '       SUM(BDVLRCONTABTOTAL) as BDVLRCONTABTOTAL,  ';
   wSQL = wSQL || '       SUM(BDBCISSSERTOTAL) as BDBCISSSERTOTAL,  ';
   wSQL = wSQL || '       BDALIQREDISSSER, ';
   wSQL = wSQL || '       SUM(BDVLRISSTOTAL) as BDVLRISSTOTAL  ';
   wSQL = wSQL || 'from (  ';
   wSQL = wSQL || '       select BDCODEMP, BDREFLAN, BDIDCNAE, BDCODCFPS, BDCODCST,  ';
   wSQL = wSQL || '              Count(*) BDQTDENFS,  ';
   wSQL = wSQL || '              LIST(BDNUMDOCINI) BDNFS,  ';
   wSQL = wSQL || '              null BDNFSCANC,  ';
   wSQL = wSQL || '              SUM(BDVLRCONTAB) as BDVLRCONTABTOTAL, ';
   wSQL = wSQL || '              SUM(BDBCISSSER) as BDBCISSSERTOTAL, ';
   wSQL = wSQL || '              BDALIQREDISSSER, ';
   wSQL = wSQL || '              ((SUM(BDBCISSSER)*BDALIQREDISSSER)/100) BDVLRISSTOTAL  ';
   wSQL = wSQL || '       from (  ';
   wSQL = wSQL || '              select SER.BDCODEMP, SER.BDCHAVE, SER.BDTIPLAN, SER.BDESPECIE, SER.BDSERIE, SER.BDREFLAN, SER.BDDATAEMISSAO, ';
   wSQL = wSQL || '                     SER.BDNUMDOCINI, SER.BDNUMDOCFIM, SUM(ITENS.BDVLRCONTAB) as BDVLRCONTAB, SUM(ITENS.BDBCISSSER) as BDBCISSSER, ITENS.BDOBSERVACAO, ';
   wSQL = wSQL || '                     ATV.BDCODMUNATVM as BDIDCNAE, ';
   wSQL = wSQL || '                     iif(ITENS.BDALIQREDISSSER <> 0, ITENS.BDALIQREDISSSER, ATV.BDALIQATVM) as BDALIQREDISSSER, ';
   wSQL = wSQL || '                     SUM(((ITENS.BDBCISSSER * (iif(ITENS.BDALIQREDISSSER <> 0, ITENS.BDALIQREDISSSER, ATV.BDALIQATVM))) / 100)) as BDVLRISS, ';
   wSQL = wSQL || '                     coalesce(CFPS.BDCODCFPS, '''') as BDCODCFPS, coalesce(CST.BDCODCST, 0) as BDCODCST ';

   wSQL = wSQL || '               from ( select *  ';
   wSQL = wSQL || '                      from vef_emp_tmovser s  ';
   wSQL = wSQL || '                      where (s.bdcodemp = '||PREMP||') ';
   IF (PRTIPOLANC = '1') THEN /* Tipo do Lançamento */
     wSQL = wSQL || '                        AND s.BDTIPLAN = 0 ';
   ELSE
   IF (PRTIPOLANC = '2') THEN
     wSQL = wSQL || '                        AND s.BDTIPLAN = 1 ';
   wSQL = wSQL || '                        and (s.bddataemissao between '''||PRDATAINI||''' and '''||PRDATAFIM||''') ';
   wSQL = wSQL || '                        and (S.BDCODSITNF not in (2, 3, 4, 5))   ) ser ';
   wSQL = wSQL || '               left outer join VEF_EMP_TMOVSERITENS itens on ( itens.BDCODEMP = ser.BDCODEMP and itens.BDCHAVE = ser.BDCHAVE )  ';
   wSQL = wSQL || '               left outer join TATVMUNICIPAL atv on ( atv.BDCODATVM = itens.BDCODATVM )  ';
   wSQL = wSQL || '               join VEF_EMP_TMOVSERINDISS iss on ( iss.BDCODEMP = ser.BDCODEMP and iss.BDCHAVE = ser.BDCHAVE and iss.BDINDICADORISS = '||PRINDICADORISS||' ) ';
   wSQL = wSQL || '               left outer join VEF_BASE_TCST cst on ( cst.BDID = iss.BDIDCST )  ';
   wSQL = wSQL || '               left outer join VEF_BASE_TCFPS cfps on ( cfps.BDID = iss.BDIDCFPS ) ';
   wSQL = wSQL || '               group by ser.BDCODEMP,ser.BDCHAVE,ser.BDTIPLAN,ser.BDESPECIE,ser.BDSERIE,ser.BDREFLAN,ser.BDDATAEMISSAO,ser.BDNUMDOCINI,ser.BDNUMDOCFIM, ';
   wSQL = wSQL || '                        itens.BDOBSERVACAO,BDIDCNAE,BDALIQREDISSSER,BDCODCFPS,BDCODCST ';
   wSQL = wSQL || '               order by ser.BDCODEMP, ser.BDREFLAN, ser.BDDATAEMISSAO, ser.BDNUMDOCINI  ';
   wSQL = wSQL || '             ) Group by BDCODEMP, BDREFLAN, BDIDCNAE, BDCODCFPS, BDCODCST, BDALIQREDISSSER ';
   wSQL = wSQL || '       UNION ALL ';
   wSQL = wSQL || '       select BDCODEMP, BDREFLAN, BDIDCNAE, BDCODCFPS, BDCODCST, ';
   wSQL = wSQL || '              0 BDQTDENFS,  ';
   wSQL = wSQL || '              null BDNFS,  ';
   wSQL = wSQL || '              LIST(BDNUMDOCINI) BDNFSCANC,  ';
   wSQL = wSQL || '              SUM(BDVLRCONTAB) as BDVLRCONTABTOTAL, ';
   wSQL = wSQL || '              SUM(BDBCISSSER) as BDBCISSSERTOTAL, ';
   wSQL = wSQL || '              BDALIQREDISSSER, ';
   wSQL = wSQL || '              ((SUM(BDBCISSSER)*BDALIQREDISSSER)/100) BDVLRISSTOTAL  ';
   wSQL = wSQL || '       from ( ';
   wSQL = wSQL || '              select ser.BDCODEMP, ser.BDTIPLAN, ser.BDESPECIE, ser.BDSERIE, ser.BDREFLAN, ser.BDDATAEMISSAO, ser.BDNUMDOCINI, ser.BDNUMDOCFIM,  ';
   wSQL = wSQL || '                     itens.BDVLRCONTAB, itens.BDBCISSSER, itens.BDOBSERVACAO, ';
   wSQL = wSQL || '                     0 as BDIDCNAE, ';
   wSQL = wSQL || '                     0 as BDALIQREDISSSER, ';
   wSQL = wSQL || '                     0 as BDVLRISS, ';
   wSQL = wSQL || '                     '''' as BDCODCFPS, ';
   wSQL = wSQL || '                     0 as BDCODCST ';

   wSQL = wSQL || '              from ( select *  ';
   wSQL = wSQL || '                     from vef_emp_tmovser s  ';
   wSQL = wSQL || '                     where (s.bdcodemp = '||PREMP||') ';
   IF (PRTIPOLANC = '1') THEN /* Tipo do Lançamento */
     wSQL = wSQL || '                        AND s.BDTIPLAN = 0 ';
   ELSE
   IF (PRTIPOLANC = '2') THEN
     wSQL = wSQL || '                        AND s.BDTIPLAN = 1 ';
   wSQL = wSQL || '                       and (s.bddataemissao between '''||PRDATAINI||''' and '''||PRDATAFIM||''') ) ser ';
   wSQL = wSQL || '              left outer join VEF_EMP_TMOVSERITENS itens on ( itens.BDCODEMP = ser.BDCODEMP and itens.BDCHAVE = ser.BDCHAVE )  ';
   wSQL = wSQL || '              left outer join TATVMUNICIPAL atv on ( atv.BDCODATVM = itens.BDCODATVM )  ';
   wSQL = wSQL || '              join VEF_EMP_TMOVSERINDISS iss on ( iss.BDCODEMP = ser.BDCODEMP and iss.BDCHAVE = ser.BDCHAVE and iss.BDINDICADORISS = '||PRINDICADORISS||' ) ';
   wSQL = wSQL || '              left outer join VEF_BASE_TCST cst on ( cst.BDID = iss.BDIDCST )  ';
   wSQL = wSQL || '              left outer join VEF_BASE_TCFPS cfps on ( cfps.BDID = iss.BDIDCFPS ) ';
   wSQL = wSQL || '              where ser.bdcodsitnf in (2,3,4,5) ';
   wSQL = wSQL || '              order by ser.BDCODEMP, ser.BDREFLAN, ser.BDDATAEMISSAO, ser.BDNUMDOCINI  ';
   wSQL = wSQL || '             ) group by BDCODEMP, BDREFLAN, BDIDCNAE, BDCODCFPS, BDCODCST, BDALIQREDISSSER  ';
   wSQL = wSQL || '      ) group by BDCODEMP,BDREFLAN,BDIDCNAE,BDCODCFPS,BDCODCST, BDALIQREDISSSER ';

   FOR EXECUTE STATEMENT WSQL
   INTO :BDCODEMP,
        :BDREFLAN,
        :BDIDCNAE,
        :BDCODCFPS,
        :BDCODCST,
        :BDQTDENFS,
        :BDNFS,
        :BDNFSCANC,
        :BDVLRCONTABTOTAL,
        :BDBCISSSERTOTAL,
        :BDALIQREDISSSER,
        :BDVLRISSTOTAL
   DO
   SUSPEND;

END
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER vef_emp_tmovestoquek220_bu0 FOR vef_emp_tmovestoquek220
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  IF ((NEW.bdreflan IS NULL) OR (NEW.bdreflan = 0)) THEN
       NEW.bdreflan = CAST( SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);
END
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER TCADPRO_INSUMOS_BI0 FOR TCADPRO_INSUMOS
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF ((NEW.bdreferencia IS NULL) OR (NEW.bdreferencia = 0)) THEN
    NEW.bdreferencia = CAST( SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);
END
^

CREATE OR ALTER TRIGGER vrh_emp_tcolcon_qc_bi0 FOR vrh_emp_tcolcon_qc
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  /* Trigger text */
  IF ((NEW.BDCODQC IS NULL) OR (NEW.BDCODQC = 0)) THEN
    SELECT COALESCE(MAX(BDCODQC), 0) + 1 FROM VRH_EMP_TCOLCON_QC WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL INTO NEW.BDCODQC;
END^

CREATE OR ALTER TRIGGER vrh_base_tterc_qc_bi0 FOR vrh_base_tterc_qc
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  /* Trigger text */
  IF ((NEW.BDCODQC IS NULL) OR (NEW.BDCODQC = 0)) THEN
    SELECT COALESCE(MAX(BDCODQC), 0) + 1 FROM VRH_BASE_TTERC_QC WHERE BDCODTER = NEW.BDCODTER INTO NEW.BDCODQC;
END^

CREATE OR ALTER TRIGGER tol_vef_emp_tsaiinss_ad0 FOR tol_vef_emp_tsaiinss
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  DELETE FROM VRHF_EMP_TNOTASFISCAIS tnf WHERE tnf.bdcodemp = OLD.bdcodemp AND tnf.bdchave = OLD.bdchaverh;
END^

CREATE OR ALTER TRIGGER tol_vef_emp_tlanrh_sn_ad0 FOR tol_vef_emp_tlanrh_sn
ACTIVE AFTER DELETE POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  --sol:16476 - removido daqui pois é preciso saber se o darf é um complemento e nesse momento o registro ja foi apagado
  /*vcodigo = 0;

  SELECT bdORDEMCOMPL FROM tdarfpadrao WHERE (bdCODEMP = OLD.bdCODEMP) AND (bdCHAVEDARF = OLD.bdCHAVEDARF) into vcodigo;

  IF ((vcodigo IS NULL) or (vcodigo = 0)) THEN
     DELETE FROM VRH_EMP_TTRIBUTACAO_SN sn WHERE sn.BDCODEMP = OLD.bdcodfilial AND sn.BDREFERENCIA = OLD.BDREFERENCIA;*/
END^

SET TERM ; ^


CREATE OR ALTER VIEW VW_INT_DESTDA_REF(
    BDCODEMP,
    BDCODIGO,
    BDREFERENCIA,
    BDEXIGESCRIISS,
    BDEXIGESCRIICMS,
    BDESCRICONT,
    BDEXIGIMPDOCFISC,
    BDEXIGREGUTIDOCFISC,
    BDEXIGLIVROMOVCOMB,
    BDEXIGREGVEIC,
    BDEXIGANUALREGINV,
    BDOPEISS,
    BDOPERETISS,
    BDOPEICMS,
    BDOPESTICMS,
    BDOPEATICMSENT,
    BDOPEIPI,
    BDAPAVULSAREGINV)
AS
SELECT
    c.BDCODEMP,
    c.BDCODIGO,
    c.BDREFERENCIA,
    c.BDEXIGESCRIISS,
    c.BDEXIGESCRIICMS,
    c.BDESCRICONT,
    c.BDEXIGIMPDOCFISC,
    c.BDEXIGREGUTIDOCFISC,
    c.BDEXIGLIVROMOVCOMB,
    c.BDEXIGREGVEIC,
    c.BDEXIGANUALREGINV,
    c.BDOPEISS,
    c.BDOPERETISS,
    c.BDOPEICMS,
    c.BDOPESTICMS,
    c.BDOPEATICMSENT,
    c.BDOPEIPI,
    c.BDAPAVULSAREGINV
FROM
(SELECT p.BDCODEMP,
        p.BDCODIGO,
        p.BDREFERENCIA,
        p.BDEXIGESCRIISS,
        p.BDEXIGESCRIICMS,
        p.BDESCRICONT,
        p.BDEXIGIMPDOCFISC,
        p.BDEXIGREGUTIDOCFISC,
        p.BDEXIGLIVROMOVCOMB,
        p.BDEXIGREGVEIC,
        p.BDEXIGANUALREGINV,
        p.BDOPEISS,
        p.BDOPERETISS,
        p.BDOPEICMS,
        p.BDOPESTICMS,
        p.BDOPEATICMSENT,
        p.BDOPEIPI,
        p.BDAPAVULSAREGINV
FROM vef_int_tDESTDA p
WHERE p.bdreferencia = (SELECT FIRST 1 ref.bdreferencia
                        FROM vef_int_tDESTDA ref
                        WHERE ref.bdcodemp = p.bdcodemp
                          AND ref.bdreferencia <= (COALESCE(
                                                      (SELECT MAX(r1.bdreferencia) FROM vef_int_tDESTDA r1 WHERE r1.bdcodemp = p.bdcodemp AND r1.bdreferencia <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
                                                      (SELECT MIN(r2.bdreferencia) FROM vef_int_tDESTDA r2 WHERE r2.bdcodemp = p.bdcodemp)
                                                  ))
                        ORDER BY ref.bdreferencia DESC)
GROUP BY p.BDCODEMP,
         p.BDCODIGO,
         p.BDREFERENCIA,
         p.BDEXIGESCRIISS,
         p.BDEXIGESCRIICMS,
         p.BDESCRICONT,
         p.BDEXIGIMPDOCFISC,
         p.BDEXIGREGUTIDOCFISC,
         p.BDEXIGLIVROMOVCOMB,
         p.BDEXIGREGVEIC,
         p.BDEXIGANUALREGINV,
         p.BDOPEISS,
         p.BDOPERETISS,
         p.BDOPEICMS,
         p.BDOPESTICMS,
         p.BDOPEATICMSENT,
         p.BDOPEIPI,
         p.BDAPAVULSAREGINV
) c
;

SET TERM ^ ;

create or alter procedure SP_COPIA_PLANOCCAUTOMATICO (
    PRCODPLANO integer,
    PRCODPLANOCOPIADO integer)
as
declare variable WSQL varchar(10000);
declare variable WCAMPOSINSERT varchar(5000);
declare variable WCAMPO varchar(64);
BEGIN
WSQL = 'SELECT R.RDB$FIELD_NAME AS BDCAMPO '||
         'FROM RDB$RELATION_FIELDS R '||
         'WHERE R.RDB$RELATION_NAME = ''VEF_BASE_TPLANOACOESCCAUTO'' ';
  WCAMPOSINSERT = '';
  FOR EXECUTE STATEMENT WSQL
    INTO WCAMPO DO
      BEGIN
        IF (WCAMPO <> 'BDCODPLANOCCAUTO') THEN
          WCAMPOSINSERT = WCAMPOSINSERT||','||TRIM(WCAMPO);
      END
  /* CRIA INSERT DA TABELA DE PLANO DE AÇÕES A COPIAR PARA O NOVO PLANO */
  WSQL = 'INSERT INTO VEF_BASE_TPLANOACOESCCAUTO (BDCODPLANOCCAUTO'||WCAMPOSINSERT||') '||
         'SELECT '||prCODPLANO||WCAMPOSINSERT||' FROM VEF_BASE_TPLANOACOESCCAUTO WHERE BDCODPLANOCCAUTO = '||prCODPLANOCOPIADO;
  EXECUTE STATEMENT wSQL;
END^

SET TERM ; ^

SET TERM ^ ;

create or alter procedure SP_CONSULTA_TER_CFOP_CCAUTO (
    PRCODPLANO integer,
    PRCHAVE integer)
returns (
    BDCODTER integer,
    BDFORN varchar(100),
    BDCODNAT integer)
as
declare variable WULTIMOCODIGO integer;
declare variable WSTR varchar(255);
declare variable WCODNAT varchar(255);
BEGIN
  WULTIMOCODIGO = -1;
  FOR SELECT BDCODNAT
      FROM VEF_BASE_TPLANOACOESCCAUTO_CFOP
      WHERE BDCODPLANOCCAUTO = :prcodplano AND
            BDCHAVE = :prchave
      INTO :WCODNAT
  DO
  BEGIN
    BDFORN = '';
    BDCODNAT = WCODNAT;
    WSTR = '';

    SELECT FIRST 1 TERREF.BDNOMETER, TER.BDCODTER
    FROM VEF_BASE_TPLANOACOESCCAUTO_TER TER
    LEFT OUTER JOIN TTERCEIRO_REF TERREF ON (TER.BDCODTER = TERREF.BDCODTER)
    WHERE TER.BDCODPLANOCCAUTO = :prcodplano AND
          TER.BDCHAVE = :prchave AND
          TER.BDCODTER > :WULTIMOCODIGO
    ORDER BY TER.BDCODTER, TERREF.BDREFEMP DESC
    INTO :WSTR, :WULTIMOCODIGO;

    if (WSTR <> '') then
      begin
        BDCODTER = WULTIMOCODIGO;
        BDFORN = WSTR;
      end
    else
      begin
        BDCODTER = 0;
        BDFORN = '';
      end

    SUSPEND;
  END

  FOR select TER.BDNOMETER, TER.BDCODTER
      from TTERCEIRO_REF TER
      inner join(select TER.BDCODTER, max(TERREF.BDREFEMP) BDREFEMP
                 from VEF_BASE_TPLANOACOESCCAUTO_TER TER
                 inner join TTERCEIRO_REF TERREF on (TER.BDCODTER = TERREF.BDCODTER)
                 where TER.BDCODPLANOCCAUTO = :prcodplano and
                       TER.BDCHAVE = :prchave and
                       TER.BDCODTER > :WULTIMOCODIGO
                 group by TER.BDCODTER
                 order by TER.BDCODTER) T on (TER.BDCODTER = T.BDCODTER and
            TER.BDREFEMP = T.BDREFEMP)
      INTO :WSTR, :WULTIMOCODIGO
  DO
  BEGIN
    BDCODTER = WULTIMOCODIGO;
    BDFORN = WSTR;
    BDCODNAT = 0;
    SUSPEND;
  END
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER procedure SP_COPIA_PLANOTROCA (
    PRCODPLANO integer,
    PRCODPLANOCOPIADO integer)
as
declare variable WSQL varchar(10000);
declare variable WCAMPOSINSERT varchar(5000);
declare variable WCAMPO varchar(64);
BEGIN

  /*PRCODPLANO        | Código do plano que foi cadastrado
    PRCODPLANOCOPIADO | Código do plano que será copiado para o plano cadastrado.

    VEF_BASE_TPLANOACOESTROCA - Tabela principal 1º
    VEF_BASE_TTIPOTROCA - Tabela Secundaria      2º
    VEF_BASE_TSOMABC - Tabela dependente         3º
    VEF_BASE_TSUBTRACAOBC - Tabela depedente     3º
  */

  /* Alt.: 15144 - A partir de agora vai carregar os campo da tabela e gerar o sql com base nesses campos,
                   Feito assim para não ter mais problemas de quando forem incluídos campos novos nos planos. */

  /* OBTÉM OS CAMPOS DA TABELA DE PLANO DE AÇÕES */
  WSQL = 'SELECT R.RDB$FIELD_NAME AS BDCAMPO '||
         'FROM RDB$RELATION_FIELDS R '||
         'WHERE R.RDB$RELATION_NAME = ''VEF_BASE_TPLANOACOESTROCA'' ';
  WCAMPOSINSERT = '';
  FOR EXECUTE STATEMENT WSQL
    INTO WCAMPO DO
      BEGIN
        IF (WCAMPO <> 'BDCODPLATROCA') THEN
          WCAMPOSINSERT = WCAMPOSINSERT||','||TRIM(WCAMPO);
      END
  /* CRIA INSERT DA TABELA DE PLANO DE AÇÕES A COPIAR PARA O NOVO PLANO */
  WSQL = 'INSERT INTO VEF_BASE_TPLANOACOESTROCA (BDCODPLATROCA'||WCAMPOSINSERT||') '||
         'SELECT '||prCODPLANO||WCAMPOSINSERT||' FROM VEF_BASE_TPLANOACOESTROCA WHERE BDCODPLATROCA = '||prCODPLANOCOPIADO;
  EXECUTE STATEMENT wSQL;

  /* OBTÉM OS CAMPOS DA TABELA "VEF_BASE_TTIPOTROCA" */
  WSQL = 'SELECT R.RDB$FIELD_NAME AS BDCAMPO '||
         'FROM RDB$RELATION_FIELDS R '||
         'WHERE R.RDB$RELATION_NAME = ''VEF_BASE_TTIPOTROCA'' ';
  WCAMPOSINSERT = '';
  FOR EXECUTE STATEMENT WSQL
    INTO WCAMPO DO
      BEGIN
        IF (WCAMPO <> 'BDCODPLATROCA') THEN
          WCAMPOSINSERT = WCAMPOSINSERT||','||TRIM(WCAMPO);
      END
  /* CRIA INSERT DA TABELA "VEF_BASE_TTIPOTROCA" A COPIAR PARA O NOVO PLANO */
  wSQL = 'INSERT INTO VEF_BASE_TTIPOTROCA (BDCODPLATROCA'||WCAMPOSINSERT||') '||
         'SELECT '||prCODPLANO||WCAMPOSINSERT||' FROM VEF_BASE_TTIPOTROCA WHERE BDCODPLATROCA = '||prCODPLANOCOPIADO;
  EXECUTE STATEMENT wSQL;

  /* OBTÉM OS CAMPOS DA TABELA "VEF_BASE_TSOMABC" */
  WSQL = 'SELECT R.RDB$FIELD_NAME AS BDCAMPO '||
         'FROM RDB$RELATION_FIELDS R '||
         'WHERE R.RDB$RELATION_NAME = ''VEF_BASE_TSOMABC'' ';
  WCAMPOSINSERT = '';
  FOR EXECUTE STATEMENT WSQL
    INTO WCAMPO DO
      BEGIN
        IF (WCAMPO <> 'BDCODPLATROCA') THEN
          WCAMPOSINSERT = WCAMPOSINSERT||','||TRIM(WCAMPO);
      END
  /* CRIA INSERT DA TABELA "VEF_BASE_TSOMABC" A COPIAR PARA O NOVO PLANO */
  wSQL = 'INSERT INTO VEF_BASE_TSOMABC (BDCODPLATROCA'||WCAMPOSINSERT||') '||
         'SELECT '||prCODPLANO||WCAMPOSINSERT||' FROM VEF_BASE_TSOMABC WHERE BDCODPLATROCA = '||prCODPLANOCOPIADO;
  EXECUTE STATEMENT wSQL;

  /* OBTÉM OS CAMPOS DA TABELA "VEF_BASE_TSUBTRACAOBC" */
  WSQL = 'SELECT R.RDB$FIELD_NAME AS BDCAMPO '||
         'FROM RDB$RELATION_FIELDS R '||
         'WHERE R.RDB$RELATION_NAME = ''VEF_BASE_TSUBTRACAOBC'' ';
  WCAMPOSINSERT = '';
  FOR EXECUTE STATEMENT WSQL
    INTO WCAMPO DO
      BEGIN
        IF (WCAMPO <> 'BDCODPLATROCA') THEN
          WCAMPOSINSERT = WCAMPOSINSERT||','||TRIM(WCAMPO);
      END
  /* CRIA INSERT DA TABELA "VEF_BASE_TSUBTRACAOBC" A COPIAR PARA O NOVO PLANO */
  wSQL = 'INSERT INTO VEF_BASE_TSUBTRACAOBC (BDCODPLATROCA'||WCAMPOSINSERT||') '||
         'SELECT '||prCODPLANO||WCAMPOSINSERT||' FROM VEF_BASE_TSUBTRACAOBC WHERE BDCODPLATROCA = '||prCODPLANOCOPIADO;
  EXECUTE STATEMENT wSQL;


  /* OBTÉM OS CAMPOS DA TABELA "VEF_BASE_TPLANOACOESTROCA_TER" */
  WSQL = 'SELECT R.RDB$FIELD_NAME AS BDCAMPO '||
         'FROM RDB$RELATION_FIELDS R '||
         'WHERE R.RDB$RELATION_NAME = ''VEF_BASE_TPLANOACOESTROCA_TER'' ';
  WCAMPOSINSERT = '';
  FOR EXECUTE STATEMENT WSQL
    INTO WCAMPO DO
      BEGIN
        IF (WCAMPO <> 'BDCODPLATROCA') THEN
          WCAMPOSINSERT = WCAMPOSINSERT||','||TRIM(WCAMPO);
      END
  /* CRIA INSERT DA TABELA "VEF_BASE_TPLANOACOESTROCA_TER" A COPIAR PARA O NOVO PLANO */
  wSQL = 'INSERT INTO VEF_BASE_TPLANOACOESTROCA_TER (BDCODPLATROCA'||WCAMPOSINSERT||') '||
         'SELECT '||prCODPLANO||WCAMPOSINSERT||' FROM VEF_BASE_TPLANOACOESTROCA_TER WHERE BDCODPLATROCA = '||prCODPLANOCOPIADO;
  EXECUTE STATEMENT wSQL;

  /* OBTÉM OS CAMPOS DA TABELA "VEF_BASE_TPLANOACOESTROCA_NCM" */
  WSQL = 'SELECT R.RDB$FIELD_NAME AS BDCAMPO '||
         'FROM RDB$RELATION_FIELDS R '||
         'WHERE R.RDB$RELATION_NAME = ''VEF_BASE_TPLANOACOESTROCA_NCM'' ';
  WCAMPOSINSERT = '';
  FOR EXECUTE STATEMENT WSQL
    INTO WCAMPO DO
      BEGIN
        IF (WCAMPO <> 'BDCODPLATROCA') THEN
          WCAMPOSINSERT = WCAMPOSINSERT||','||TRIM(WCAMPO);
      END
  /* CRIA INSERT DA TABELA "VEF_BASE_TPLANOACOESTROCA_NCM" A COPIAR PARA O NOVO PLANO */
  wSQL = 'INSERT INTO VEF_BASE_TPLANOACOESTROCA_NCM (BDCODPLATROCA'||WCAMPOSINSERT||') '||
         'SELECT '||prCODPLANO||WCAMPOSINSERT||' FROM VEF_BASE_TPLANOACOESTROCA_NCM WHERE BDCODPLATROCA = '||prCODPLANOCOPIADO;
  EXECUTE STATEMENT wSQL;

  /* OBTÉM OS CAMPOS DA TABELA "VEF_BASE_TPLANOACOESTROCACFOPS" */
  WSQL = 'SELECT R.RDB$FIELD_NAME AS BDCAMPO '||
         'FROM RDB$RELATION_FIELDS R '||
         'WHERE R.RDB$RELATION_NAME = ''VEF_BASE_TPLANOACOESTROCACFOPS'' ';
  WCAMPOSINSERT = '';
  FOR EXECUTE STATEMENT WSQL
    INTO WCAMPO DO
      BEGIN
        IF (WCAMPO <> 'BDCODPLATROCA') THEN
          WCAMPOSINSERT = WCAMPOSINSERT||','||TRIM(WCAMPO);
      END
  /* CRIA INSERT DA TABELA "VEF_BASE_TPLANOACOESTROCACFOPS" A COPIAR PARA O NOVO PLANO */
  wSQL = 'INSERT INTO VEF_BASE_TPLANOACOESTROCACFOPS (BDCODPLATROCA'||WCAMPOSINSERT||') '||
         'SELECT '||prCODPLANO||WCAMPOSINSERT||' FROM VEF_BASE_TPLANOACOESTROCACFOPS WHERE BDCODPLATROCA = '||prCODPLANOCOPIADO;
  EXECUTE STATEMENT wSQL;

    /* OBTÉM OS CAMPOS DA TABELA "VEF_BASE_TPLANOACOESTROCA_CLASSENETEL" */
  WSQL = 'SELECT R.RDB$FIELD_NAME AS BDCAMPO '||
         'FROM RDB$RELATION_FIELDS R '||
         'WHERE R.RDB$RELATION_NAME = ''VEF_BASE_TPLANOACOESTROCA_CLASSENETEL'' ';
  WCAMPOSINSERT = '';
  FOR EXECUTE STATEMENT WSQL
    INTO WCAMPO DO
      BEGIN
        IF (WCAMPO <> 'BDCODPLATROCA') THEN
          WCAMPOSINSERT = WCAMPOSINSERT||','||TRIM(WCAMPO);
      END
  /* CRIA INSERT DA TABELA "VEF_BASE_TPLANOACOESTROCA_CLASSENETEL" A COPIAR PARA O NOVO PLANO */
  wSQL = 'INSERT INTO VEF_BASE_TPLANOACOESTROCA_CLASSENETEL (BDCODPLATROCA'||WCAMPOSINSERT||') '||
         'SELECT '||prCODPLANO||WCAMPOSINSERT||' FROM VEF_BASE_TPLANOACOESTROCA_CLASSENETEL WHERE BDCODPLATROCA = '||prCODPLANOCOPIADO;
  EXECUTE STATEMENT wSQL;
  
END^

CREATE OR ALTER procedure SP_ATU_ESTRUTURA_COPIA_PLAN_TEMP (
    PRTABELA varchar(63))
as
declare variable WSQL varchar(10000);
declare variable W_ISNULL varchar(20);
declare variable W_COLUMNS varchar(10000);
declare variable W_SQL_CREATE varchar(10000);
declare variable W_COUNT integer;
begin
  /* Vamos primeiro descobrir em qual caminho iremos percorrer*/
  select count(*)
  from RDB$RELATIONS
  where trim(upper(RDB$RELATION_NAME)) = trim(upper('TMP_AGRUP_ACOES_PLANO_TEMP')) and
        RDB$SYSTEM_FLAG = 0
  into :W_COUNT; -- Exclui tabelas de sistema

  --Tabela tempor?ria n?o existe, ent?o vamos CRIAR uma
  if (W_COUNT = 0) then
  begin
    --primeiro vamos levantar quais as colunas da tabela...
    select list(TBS.FIELDS, ',')
    from (select trim(F.RDB$FIELD_NAME) || ' ' || iif(substring(F.RDB$FIELD_SOURCE from 1 for 3) <> 'DM_',
                 case
                   when FF.RDB$FIELD_TYPE = 7 then 'SMALLINT'
                   when FF.RDB$FIELD_TYPE = 8 then 'INTEGER'
                   when FF.RDB$FIELD_TYPE = 10 then 'FLOAT'
                   when FF.RDB$FIELD_TYPE = 12 then 'DATE'
                   when FF.RDB$FIELD_TYPE = 13 then 'TIME'
                   when FF.RDB$FIELD_TYPE = 14 then 'DOUBLE PRECISION'
                   when FF.RDB$FIELD_TYPE = 16 then 'BIGINT'
                   when FF.RDB$FIELD_TYPE = 23 then 'BOOLEAN'
                   when FF.RDB$FIELD_TYPE = 27 then 'DOUBLE PRECISION'
                   when FF.RDB$FIELD_TYPE = 35 then 'TIMESTAMP'
                   when FF.RDB$FIELD_TYPE = 37 then 'VARCHAR(' || FF.RDB$CHARACTER_LENGTH || ')'
                   when FF.RDB$FIELD_TYPE = 261 then 'BLOB SUB_TYPE ' || FF.RDB$FIELD_SUB_TYPE || ' SEGMENT SIZE ' || FF.RDB$SEGMENT_LENGTH
                   else 'UNKNOWN'
                 end, '') ||
                 case
                   when substring(F.RDB$FIELD_SOURCE from 1 for 3) = 'DM_' then trim(F.RDB$FIELD_SOURCE)
                   else ''
                 end ||
                 case
                   when F.RDB$NULL_FLAG = 1 then ' '
                   else ''
                 end as FIELDS,
                 F.RDB$FIELD_POSITION
          from RDB$RELATION_FIELDS F
          join RDB$FIELDS FF on F.RDB$FIELD_SOURCE = FF.RDB$FIELD_NAME
          where trim(upper(F.RDB$RELATION_NAME)) = trim(upper(:PRTABELA))
          order by 2) TBS
    into :W_COLUMNS;

    W_COLUMNS = 'BDSESSAO INTEGER NOT NULL, BDEDITCHAVE INTEGER, BDROW_EXCLUIDA integer,  ' || :W_COLUMNS;

    --Agora vamos montar os SQLs que far?o o paranau? todo

    --Recria??o da tabela tempor?ria
    W_SQL_CREATE = 'CREATE TABLE TMP_AGRUP_ACOES_PLANO_TEMP ( ' || :W_COLUMNS || ')';

    --Senta a lenha no SQL....
    execute statement :W_SQL_CREATE;

    WSQL = 'CREATE INDEX TMP_AGRUP_ACOES_PLANO_TEMP_IDX1 ON TMP_AGRUP_ACOES_PLANO_TEMP (BDSESSAO) ';
    execute statement :WSQL;
    WSQL = 'CREATE INDEX TMP_AGRUP_ACOES_PLANO_TEMP_IDX2 ON TMP_AGRUP_ACOES_PLANO_TEMP (BDCODPLATROCA) ';
    execute statement :WSQL;
    WSQL = 'CREATE INDEX TMP_AGRUP_ACOES_PLANO_TEMP_IDX3 ON TMP_AGRUP_ACOES_PLANO_TEMP (BDCHAVE) ';
    execute statement :WSQL;

  end
  else
  begin
    --a tabela j? existe, logo precisa apenas adicionar os campos novos que foram criados...
    select list('ADD ' || trim(F.RDB$FIELD_NAME) || ' ' || iif(substring(F.RDB$FIELD_SOURCE from 1 for 3) <> 'DM_',
           case
             when FF.RDB$FIELD_TYPE = 7 then 'SMALLINT'
             when FF.RDB$FIELD_TYPE = 8 then 'INTEGER'
             when FF.RDB$FIELD_TYPE = 10 then 'FLOAT'
             when FF.RDB$FIELD_TYPE = 12 then 'DATE'
             when FF.RDB$FIELD_TYPE = 13 then 'TIME'
             when FF.RDB$FIELD_TYPE = 14 then 'DOUBLE PRECISION'
             when FF.RDB$FIELD_TYPE = 16 then 'BIGINT'
             when FF.RDB$FIELD_TYPE = 23 then 'BOOLEAN'
             when FF.RDB$FIELD_TYPE = 27 then 'DOUBLE PRECISION'
             when FF.RDB$FIELD_TYPE = 35 then 'TIMESTAMP'
             when FF.RDB$FIELD_TYPE = 37 then 'VARCHAR(' || FF.RDB$CHARACTER_LENGTH || ')'
             when FF.RDB$FIELD_TYPE = 261 then 'BLOB SUB_TYPE ' || FF.RDB$FIELD_SUB_TYPE || ' SEGMENT SIZE ' || FF.RDB$SEGMENT_LENGTH
             else 'UNKNOWN'
           end, '') ||
           case
             when substring(F.RDB$FIELD_SOURCE from 1 for 3) = 'DM_' then trim(F.RDB$FIELD_SOURCE)
             else ''
           end ||
           case
             when F.RDB$NULL_FLAG = 1 then ' '
             else ''
           end, ',')
    from RDB$RELATION_FIELDS F
    join RDB$FIELDS FF on F.RDB$FIELD_SOURCE = FF.RDB$FIELD_NAME
    where trim(upper(F.RDB$RELATION_NAME)) = trim(upper(:PRTABELA)) and
          not exists(select 1
                     from RDB$RELATION_FIELDS F2
                     where trim(upper(F2.RDB$RELATION_NAME)) = trim(upper('TMP_AGRUP_ACOES_PLANO_TEMP')) and
                           F2.RDB$FIELD_NAME = F.RDB$FIELD_NAME)
    into :W_COLUMNS;

    select first 1 1
    from RDB$RELATION_FIELDS F2
    where (trim(upper(F2.RDB$RELATION_NAME)) = trim(upper('TMP_AGRUP_ACOES_PLANO_TEMP'))) and
    ((F2.RDB$FIELD_NAME = 'BDCODNATCAPA') or
    (F2.RDB$FIELD_NAME = 'BDCODNATF11')  or
    (F2.RDB$FIELD_NAME = 'BDCODTERCAPA') or
    (F2.RDB$FIELD_NAME = 'BDCODTERF11' ))
    into :W_ISNULL;

    if (W_ISNULL is null) then
        Begin
         if ((W_COLUMNS <> '') or (W_COLUMNS is null))  then
          :W_COLUMNS = W_COLUMNS||', add BDCODNATCAPA Integer, add BDCODNATF11 Integer,  add BDCODTERCAPA Integer, add BDCODTERF11 Integer';
         else
          :W_COLUMNS = ' add BDCODNATCAPA Integer, add BDCODNATF11 Integer,  add BDCODTERCAPA Integer, add BDCODTERF11 Integer';
     End


    --verificando se tem os campos pr prios daa tabelas tempor rias
    select count(RDB$FIELD_NAME)
    from RDB$RELATION_FIELDS
    where trim(upper(RDB$RELATION_NAME)) = trim(upper('TMP_AGRUP_ACOES_PLANO_TEMP')) and
          RDB$FIELD_NAME = 'BDEDITCHAVE'
    into :W_COUNT;

    if (W_COUNT = 0) then
    begin
        W_COLUMNS = ' ADD BDEDITCHAVE INTEGER ' || Coalesce(',' || :W_COLUMNS, '');
    end

     select count(RDB$FIELD_NAME)
    from RDB$RELATION_FIELDS
    where trim(upper(RDB$RELATION_NAME)) = trim(upper('TMP_AGRUP_ACOES_PLANO_TEMP')) and
          RDB$FIELD_NAME = 'BDROW_EXCLUIDA'
    into :W_COUNT;

    if (W_COUNT = 0) then
    begin
        W_COLUMNS = ' ADD BDROW_EXCLUIDA INTEGER ' || Coalesce(',' || :W_COLUMNS, '');
    end

    if (coalesce(:W_COLUMNS, '') <> '') then
    begin
      --montando o ALTER TABLE
      W_SQL_CREATE = 'ALTER TABLE TMP_AGRUP_ACOES_PLANO_TEMP ' || :W_COLUMNS;

      --Senta a lenha no SQL....
      execute statement :W_SQL_CREATE;
    end
  end
end ^

CREATE OR ALTER procedure SP_AGRUPAR_NOVO_PLANO (
    PRSESSAO integer,
    PRCODPLANO integer,
    PRCODPLANOCOPIADO integer)
as
declare variable WCAMPOSNOTNULL varchar(10000);
declare variable WCAMPOLIST varchar(200);
declare variable WSELECTTER varchar(500);
declare variable WDESCPLANO varchar(100);
declare variable WQNTREGISTROS integer;
declare variable WAGRUPARPLANO integer;
declare variable WCAMPOSSELECT varchar(10000);
declare variable WCAMPOSINSERT varchar(10000);
declare variable WCHAVE varchar(500);
declare variable WCODTER varchar(500);
declare variable WCODPLATROCA varchar(500);
declare variable WSQL varchar(10000);
begin
    WSQL = 'select List(iif((Trim(R.RDB$FIELD_NAME) = ''BDNCMPROD''), null ,Trim(R.RDB$FIELD_NAME))) as BDCAMPOINSERT, ';
    WSQL = WSQL||' list(iif((R.RDB$NULL_FLAG = 1),trim(R.RDB$FIELD_NAME) || '' is not null'', null), '' AND '') as BDCAMPONOTNULL, ';
    WSQL = WSQL||' List(iif((Trim(R.RDB$FIELD_NAME) = ''BDNCMPROD''), null ,Trim(R.RDB$FIELD_NAME))) as BDCAMPOSELECT ';
    WSQL = WSQL||' from RDB$RELATION_FIELDS R ';
    WSQL = WSQL||' where R.RDB$RELATION_NAME = ''VEF_BASE_TPLANOACOESTROCA'' AND (Trim(R.RDB$FIELD_NAME) <> ''BDCODPLATROCA'') AND (Trim(R.RDB$FIELD_NAME) <> ''BDCHAVE'') AND (Trim(R.RDB$FIELD_NAME) <> ''BDCODNAT'') AND (Trim(R.RDB$FIELD_NAME) <> ''BDCODTER'') ';

    EXECUTE STATEMENT :WSQL INTO :WCAMPOSINSERT, :WCAMPOSNOTNULL, :WCAMPOSSELECT;
      Begin
        WSQL = ' SELECT FIRST 1 BDDESCRICAO FROM VEF_BASE_TPLATROCA WHERE BDCODPLATROCA = '||:PRCODPLANOCOPIADO;
        EXECUTE STATEMENT WSQL INTO WDESCPLANO;

        WDESCPLANO = Substring((WDESCPLANO||' - Agrupamento do plano: '||PRCODPLANOCOPIADO) from 1 for 100);
        WSQL = 'INSERT INTO VEF_BASE_TPLATROCA(BDCODPLATROCA, BDDESCRICAO) Values ('||:PRCODPLANO||', '''||WDESCPLANO||''') ';
        EXECUTE STATEMENT WSQL;

        /*Aqui vai jogar os dados respectivos da tabela VEF_BASE_TPLANOACOESTROCA*/
        WSQL =       ' INSERT INTO VEF_BASE_TPLANOACOESTROCA (BDCODPLATROCA, BDCHAVE, '||:WCAMPOSINSERT||') ';
        WSQL = WSQL||' SELECT DISTINCT S.BDCODPLATROCA, S.BDCHAVE, '||:WCAMPOSSELECT||' FROM TMP_AGRUP_ACOES_PLANO_TEMP S ';
        WSQL = WSQL||' LEFT OUTER JOIN VEF_BASE_TPLANOACOESTROCA A ON ';
        WSQL = WSQL||' ((SELECT FIRST 1 D.BDCODPLATROCA_ANTIGO FROM TMP_AGRUP_ACOES_PLANO_TEMP D WHERE D.BDCODPLATROCA = S.BDCODPLATROCA AND D.BDCHAVE = S.BDCHAVE) = A.BDCODPLATROCA AND ';
        WSQL = WSQL||'  (SELECT FIRST 1 D.BDCHAVE_ANTIGA FROM TMP_AGRUP_ACOES_PLANO_TEMP D WHERE D.BDCODPLATROCA = S.BDCODPLATROCA AND D.BDCHAVE = S.BDCHAVE) = A.BDCHAVE) ';

        WSQL = WSQL||' WHERE S.BDCODPLATROCA = '||:PRCODPLANO||' and S.BDSESSAO = '||:PRSESSAO||' ';
        EXECUTE STATEMENT WSQL;

        /*Aqui vai jogar os dados respectivos da tabela VEF_BASE_TPLANOACOESTROCACFOPS*/
        WSQL = 'select List(Trim(R.RDB$FIELD_NAME)) as BDCAMPOINSERT, ';
        WSQL = WSQL||'list(iif((R.RDB$NULL_FLAG = 1) and ((trim(R.RDB$FIELD_NAME) = ''BDCODNAT'')) , ''((''||trim(R.RDB$FIELD_NAME)||''CAPA''|| '' is not null) or (''||trim(R.RDB$FIELD_NAME)||''F11''|| '' is not null))'', iif((R.RDB$NULL_FLAG = 1),trim(R.RDB$FIELD_NAME) || '' is not null'', null)), '' AND '') as BDCAMPONOTNULL, ';
        WSQL = WSQL||'list(iif((trim(R.RDB$FIELD_NAME) = ''BDCODNAT''), ''CFOP.BDCODNAT'', trim(R.RDB$FIELD_NAME))) as BDCAMPOSELECT ';
        WSQL = WSQL||'from RDB$RELATION_FIELDS R ';
        WSQL = WSQL||'where R.RDB$RELATION_NAME = ''VEF_BASE_TPLANOACOESTROCACFOPS'' AND (Trim(R.RDB$FIELD_NAME) <> ''BDCODPLATROCA'') ';
        WSQL = WSQL||' AND (Trim(R.RDB$FIELD_NAME) <> ''BDCHAVE'')  ';
    
        EXECUTE STATEMENT :WSQL INTO :WCAMPOSINSERT, :WCAMPOSNOTNULL, :WCAMPOSSELECT;
    
        WSQL =       'INSERT INTO VEF_BASE_TPLANOACOESTROCACFOPS (BDCODPLATROCA, BDCHAVE, '||:WCAMPOSINSERT||') ';
        WSQL = WSQL||' SELECT DISTINCT S.BDCODPLATROCA, S.BDCHAVE, '||:WCAMPOSSELECT||' FROM TMP_AGRUP_ACOES_PLANO_TEMP S ';
        WSQL = WSQL||' LEFT OUTER JOIN VEF_BASE_TPLANOACOESTROCA A ON (S.BDCODPLATROCA_ANTIGO = A.BDCODPLATROCA AND S.BDCHAVE_ANTIGA = A.BDCHAVE) ';
        WSQL = WSQL||' LEFT OUTER JOIN VEF_BASE_TPLANOACOESTROCACFOPS AC ON (A.BDCODPLATROCA = AC.BDCODPLATROCA AND A.BDCHAVE = AC.BDCHAVE) ';
        WSQL = WSQL||' LEFT OUTER JOIN VEF_BASE_TNATOP CFOP ON ((AC.BDCODNAT = CFOP.BDCODNAT) OR (replace(CFOP.BDCLASSIFICACAO,''.'','''') STARTING WITH replace(A.BDCODNAT,''.'',''''))) ';
        WSQL = WSQL||' WHERE S.BDCODPLATROCA = '||:PRCODPLANO||' and S.BDSESSAO = '||:PRSESSAO||' and CFOP.BDCODNAT IS NOT NULL';

        EXECUTE STATEMENT :WSQL;

    
        /*Aqui vai jogar os dados respectivos da tabela VEF_BASE_TPLANOACOESTROCA_TER*/
    

        WSQL = 'select List(Trim(R.RDB$FIELD_NAME)) as BDCAMPOINSERT, ';
        WSQL = WSQL||'list(iif((R.RDB$NULL_FLAG = 1),trim(R.RDB$FIELD_NAME) || '' is not null'', null), '' AND '') as BDCAMPONOTNULL, ';
        WSQL = WSQL||'list(iif((trim(R.RDB$FIELD_NAME) = ''BDCODTER''), ''Coalesce(AC.BDCODTER, A.BDCODTER)'', trim(R.RDB$FIELD_NAME))) as BDCAMPOSELECT ';
        WSQL = WSQL||'from RDB$RELATION_FIELDS R ';
        WSQL = WSQL||'where R.RDB$RELATION_NAME = ''VEF_BASE_TPLANOACOESTROCA_TER'' AND (Trim(R.RDB$FIELD_NAME) <> ''BDCODPLATROCA'') AND (Trim(R.RDB$FIELD_NAME) <> ''BDCHAVE'') ';
    
        EXECUTE STATEMENT :WSQL INTO :WCAMPOSINSERT, :WCAMPOSNOTNULL, :WCAMPOSSELECT;

        WSQL =       ' INSERT INTO VEF_BASE_TPLANOACOESTROCA_TER (BDCODPLATROCA, BDCHAVE,'||:WCAMPOSINSERT||') ';
        WSQL = WSQL||' SELECT DISTINCT S.BDCODPLATROCA, S.BDCHAVE, '||:WCAMPOSSELECT||' FROM TMP_AGRUP_ACOES_PLANO_TEMP S ';
        WSQL = WSQL||' LEFT OUTER JOIN VEF_BASE_TPLANOACOESTROCA A ON (S.BDCODPLATROCA_ANTIGO = A.BDCODPLATROCA AND S.BDCHAVE_ANTIGA = A.BDCHAVE) ';
        WSQL = WSQL||' LEFT OUTER JOIN VEF_BASE_TPLANOACOESTROCA_TER AC ON (S.BDCODPLATROCA_ANTIGO = AC.BDCODPLATROCA AND S.BDCHAVE_ANTIGA = AC.BDCHAVE) ';
        WSQL = WSQL||' WHERE S.BDCODPLATROCA = '||:PRCODPLANO||' and S.BDSESSAO = '||:PRSESSAO||' AND Coalesce(A.BDCODTER, AC.BDCODTER) IS NOT NULL ';
        EXECUTE STATEMENT :WSQL;

        /*Aqui vai jogar os dados respectivos da tabela VEF_BASE_TPLANOACOESTROCA_NCM*/
        WSQL = 'select List(Trim(R.RDB$FIELD_NAME)) as BDCAMPOINSERT, ';
        WSQL = WSQL||'list(iif((R.RDB$NULL_FLAG = 1),trim(R.RDB$FIELD_NAME) || '' is not null'', null), '' AND '') as BDCAMPONOTNULL, ';
        WSQL = WSQL||'list(iif((trim(R.RDB$FIELD_NAME) = ''BDNCMPROD''), ''Coalesce(A.BDNCMPROD, AC.BDNCMPROD)'', trim(R.RDB$FIELD_NAME))) as BDCAMPOSELECT ';
        WSQL = WSQL||'from RDB$RELATION_FIELDS R ';
        WSQL = WSQL||'where R.RDB$RELATION_NAME = ''VEF_BASE_TPLANOACOESTROCA_NCM'' AND (Trim(R.RDB$FIELD_NAME) <> ''BDCODPLATROCA'') AND (Trim(R.RDB$FIELD_NAME) <> ''BDCHAVE'') ';
    
        EXECUTE STATEMENT :WSQL INTO :WCAMPOSINSERT, :WCAMPOSNOTNULL, :WCAMPOSSELECT;
--    
        WSQL =       'INSERT INTO VEF_BASE_TPLANOACOESTROCA_NCM (BDCODPLATROCA, BDCHAVE,'||:WCAMPOSINSERT||') ';
        WSQL = WSQL||'SELECT DISTINCT S.BDCODPLATROCA, S.BDCHAVE, '||:WCAMPOSSELECT||' FROM TMP_AGRUP_ACOES_PLANO_TEMP S ';
        WSQL = WSQL||' LEFT OUTER JOIN VEF_BASE_TPLANOACOESTROCA A ON (S.BDCODPLATROCA_ANTIGO = A.BDCODPLATROCA AND S.BDCHAVE_ANTIGA = A.BDCHAVE) ';
        WSQL = WSQL||' LEFT OUTER JOIN VEF_BASE_TPLANOACOESTROCA_NCM AC ON (S.BDCODPLATROCA_ANTIGO = AC.BDCODPLATROCA AND S.BDCHAVE_ANTIGA = AC.BDCHAVE) ';
        WSQL = WSQL||'WHERE S.BDCODPLATROCA = '||:PRCODPLANO||' and S.BDSESSAO = '||:PRSESSAO||' AND Coalesce(A.BDNCMPROD, AC.BDNCMPROD) IS NOT NULL ';
    
        EXECUTE STATEMENT :WSQL;

        /*Aqui vai jogar os dados respectivos da tabela VEF_BASE_TPLANOACOESTROCA_CLASSENETEL*/
        WSQL = 'select List(Trim(R.RDB$FIELD_NAME)) as BDCAMPOINSERT, ';
        WSQL = WSQL||'list(iif((R.RDB$NULL_FLAG = 1),trim(R.RDB$FIELD_NAME) || '' is not null'', null), '' AND '') as BDCAMPONOTNULL, ';
        WSQL = WSQL||'list(iif((trim(R.RDB$FIELD_NAME) = ''BDCODCLAENETEL''), ''Coalesce(A.BDCODCLAENETEL, AC.BDCODCLAENETEL)'', trim(R.RDB$FIELD_NAME))) as BDCAMPOSELECT ';
        WSQL = WSQL||'from RDB$RELATION_FIELDS R ';
        WSQL = WSQL||'where R.RDB$RELATION_NAME = ''VEF_BASE_TPLANOACOESTROCA_CLASSENETEL'' AND (Trim(R.RDB$FIELD_NAME) <> ''BDCODPLATROCA'') AND (Trim(R.RDB$FIELD_NAME) <> ''BDCHAVE'') ';
    
        EXECUTE STATEMENT :WSQL INTO :WCAMPOSINSERT, :WCAMPOSNOTNULL, :WCAMPOSSELECT;
--    
        WSQL =       'INSERT INTO VEF_BASE_TPLANOACOESTROCA_CLASSENETEL (BDCODPLATROCA, BDCHAVE,'||:WCAMPOSINSERT||') ';
        WSQL = WSQL||'SELECT DISTINCT S.BDCODPLATROCA, S.BDCHAVE, '||:WCAMPOSSELECT||' FROM TMP_AGRUP_ACOES_PLANO_TEMP S ';
        WSQL = WSQL||' LEFT OUTER JOIN VEF_BASE_TPLANOACOESTROCA A ON (S.BDCODPLATROCA_ANTIGO = A.BDCODPLATROCA AND S.BDCHAVE_ANTIGA = A.BDCHAVE) ';
        WSQL = WSQL||' LEFT OUTER JOIN VEF_BASE_TPLANOACOESTROCA_CLASSENETEL AC ON (S.BDCODPLATROCA_ANTIGO = AC.BDCODPLATROCA AND S.BDCHAVE_ANTIGA = AC.BDCHAVE) ';
        WSQL = WSQL||'WHERE S.BDCODPLATROCA = '||:PRCODPLANO||' and S.BDSESSAO = '||:PRSESSAO||' AND Coalesce(A.BDCODCLAENETEL, AC.BDCODCLAENETEL) IS NOT NULL ';
    
        EXECUTE STATEMENT :WSQL;
    
        /*Aqui vai jogar os dados respectivos da tabela VEF_BASE_TTIPOTROCA*/
        WSQL = 'select List(Trim(R.RDB$FIELD_NAME)) as BDCAMPOINSERT, ';
        WSQL = WSQL||'list(iif((R.RDB$NULL_FLAG = 1),trim(R.RDB$FIELD_NAME) || '' is not null'', null), '' AND '') as BDCAMPONOTNULL, ';
        WSQL = WSQL||'list(trim(R.RDB$FIELD_NAME)) as BDCAMPOSELECT ';
        WSQL = WSQL||'from RDB$RELATION_FIELDS R ';
        WSQL = WSQL||'where R.RDB$RELATION_NAME = ''VEF_BASE_TTIPOTROCA'' AND (Trim(R.RDB$FIELD_NAME) <> ''BDCODPLATROCA'') AND (Trim(R.RDB$FIELD_NAME) <> ''BDCHAVE'') ';
    
        EXECUTE STATEMENT :WSQL INTO :WCAMPOSINSERT, :WCAMPOSNOTNULL, :WCAMPOSSELECT;
    
        WSQL =       'INSERT INTO VEF_BASE_TTIPOTROCA (BDCODPLATROCA, BDCHAVE,'||:WCAMPOSINSERT||') ';
        WSQL = WSQL||'SELECT DISTINCT S.BDCODPLATROCA, S.BDCHAVE, '||:WCAMPOSSELECT||' FROM TMP_AGRUP_ACOES_PLANO_TEMP S ';
        WSQL = WSQL||'JOIN VEF_BASE_TTIPOTROCA T ON (T.BDCODPLATROCA = S.BDCODPLATROCA_ANTIGO AND T.BDCHAVE = S.BDCHAVE_ANTIGA) ';
        WSQL = WSQL||'WHERE S.BDCODPLATROCA = '||:PRCODPLANO||' and S.BDSESSAO = '||:PRSESSAO||' ';
    
        EXECUTE STATEMENT :WSQL;
    
        /*Aqui vai jogar os dados respectivos da tabela VEF_BASE_TSOMABC*/
        WSQL = 'select List(Trim(R.RDB$FIELD_NAME)) as BDCAMPOINSERT, ';
        WSQL = WSQL||'list(iif((R.RDB$NULL_FLAG = 1),trim(R.RDB$FIELD_NAME) || '' is not null'', null), '' AND '') as BDCAMPONOTNULL, ';
        WSQL = WSQL||'list(iif((trim(R.RDB$FIELD_NAME) = ''BDCODTPIMP''), ''TS.BDCODTPIMP'', ''Coalesce(''||trim(R.RDB$FIELD_NAME)||'',''''False'''')'')) as BDCAMPOSELECT ';
        WSQL = WSQL||'from RDB$RELATION_FIELDS R ';
        WSQL = WSQL||'where R.RDB$RELATION_NAME = ''VEF_BASE_TSOMABC'' AND (Trim(R.RDB$FIELD_NAME) <> ''BDCODPLATROCA'') AND (Trim(R.RDB$FIELD_NAME) <> ''BDCHAVE'') ';
    
        EXECUTE STATEMENT :WSQL INTO :WCAMPOSINSERT, :WCAMPOSNOTNULL, :WCAMPOSSELECT;
    
        WSQL =       'INSERT INTO VEF_BASE_TSOMABC (BDCODPLATROCA, BDCHAVE,'||:WCAMPOSINSERT||') ';
        WSQL = WSQL||'SELECT DISTINCT S.BDCODPLATROCA, S.BDCHAVE, '||:WCAMPOSSELECT||' FROM TMP_AGRUP_ACOES_PLANO_TEMP S ';    
        WSQL = WSQL||'JOIN VEF_BASE_TTIPOTROCA T ON (T.BDCODPLATROCA = S.BDCODPLATROCA_ANTIGO AND T.BDCHAVE = S.BDCHAVE_ANTIGA) ';
        WSQL = WSQL||'JOIN VEF_BASE_TSOMABC TS ON (TS.BDCODTPIMP = T.BDCODTPIMP AND TS.BDCODPLATROCA = T.BDCODPLATROCA AND TS.BDCHAVE = T.BDCHAVE) ';
        WSQL = WSQL||'WHERE S.BDCODPLATROCA = '||:PRCODPLANO||' and S.BDSESSAO = '||:PRSESSAO||' ';
    
        EXECUTE STATEMENT :WSQL;
    
        /*Aqui vai jogar os dados respectivos da tabela VEF_BASE_TSUBTRACAOBC*/
        WSQL = 'select List(Trim(R.RDB$FIELD_NAME)) as BDCAMPOINSERT, ';
        WSQL = WSQL||'list(iif((R.RDB$NULL_FLAG = 1),trim(R.RDB$FIELD_NAME) || '' is not null'', null), '' AND '') as BDCAMPONOTNULL, ';
        WSQL = WSQL||'list(iif((trim(R.RDB$FIELD_NAME) = ''BDCODTPIMP''), ''TS.BDCODTPIMP'', ''Coalesce(''||trim(R.RDB$FIELD_NAME)||'',''''False'''')'')) as BDCAMPOSELECT ';
        WSQL = WSQL||'from RDB$RELATION_FIELDS R ';
        WSQL = WSQL||'where R.RDB$RELATION_NAME = ''VEF_BASE_TSUBTRACAOBC'' AND (Trim(R.RDB$FIELD_NAME) <> ''BDCODPLATROCA'') AND (Trim(R.RDB$FIELD_NAME) <> ''BDCHAVE'') ';
    
        EXECUTE STATEMENT :WSQL INTO :WCAMPOSINSERT, :WCAMPOSNOTNULL, :WCAMPOSSELECT;
    
        WSQL =       'INSERT INTO VEF_BASE_TSUBTRACAOBC (BDCODPLATROCA, BDCHAVE,'||:WCAMPOSINSERT||') ';
        WSQL = WSQL||'SELECT DISTINCT S.BDCODPLATROCA, S.BDCHAVE, '||:WCAMPOSSELECT||' FROM TMP_AGRUP_ACOES_PLANO_TEMP S ';    
        WSQL = WSQL||'JOIN VEF_BASE_TTIPOTROCA T ON (T.BDCODPLATROCA = S.BDCODPLATROCA_ANTIGO AND T.BDCHAVE = S.BDCHAVE_ANTIGA) ';
        WSQL = WSQL||'JOIN VEF_BASE_TSUBTRACAOBC TS ON (TS.BDCODTPIMP = T.BDCODTPIMP AND TS.BDCODPLATROCA = T.BDCODPLATROCA AND TS.BDCHAVE = T.BDCHAVE) ';
        WSQL = WSQL||'WHERE S.BDCODPLATROCA = '||:PRCODPLANO||' and S.BDSESSAO = '||:PRSESSAO||' ';
    
        EXECUTE STATEMENT :WSQL;
    End
end^ 

CREATE OR ALTER procedure SP_COPIA_ACOES_PLANOTROCA (
    PRCODPLANOTROCA integer,
    PRTIPOLANDE integer,
    PRTIPOLANPARA integer,
    PRCODPLANOCOPIADO integer,
    PRAGRUPARPLANO varchar(5) = false /* COLLATE WIN1252 - default */ ,
    PRSESSAO integer = 0)
as
declare variable WSQL3 varchar(30000);
declare variable WCAMPOSCOMCOALESCE2 varchar(20000);
declare variable WSOMAESUBTRACAO varchar(10000);
declare variable WCAMPOSPLANO varchar(20000);
declare variable WCODTPIMP integer;
declare variable WCAMPOSFILTROF11 varchar(20000);
declare variable WCOMPLEMENTAINSERT varchar(20000);
declare variable WCAMPOSINSERT varchar(20000);
declare variable WDESC varchar(5);
declare variable WCAMPOSSELECT varchar(20000);
declare variable WBASEISS varchar(5);
declare variable WREDBC varchar(5);
declare variable WST varchar(5);
declare variable WCAMPOSF11 varchar(20000);
declare variable WIPI varchar(5);
declare variable WFRETE varchar(5);
declare variable WDESPACE varchar(5);
declare variable WNFPROD varchar(5);
declare variable WCHAVETPIMP integer;
declare variable WSQL2 varchar(30000);
declare variable WCHAVEANT integer;
declare variable WCHAVE integer;
declare variable WSQL varchar(30000);
declare variable WCODNAT integer;
declare variable WCAMPOSCOMCOALESCE varchar(30000);
declare variable WCAMPOSSOMAESUB varchar(20000);
declare variable WTEXT blob sub_type 1 segment size 64000;
declare variable WCODNATEXIS integer;
declare variable WVERSAO integer;
declare variable WCOUNTVERSAO integer;
declare variable WCOUNTVERSAONOVA integer;
BEGIN

if (:PRAGRUPARPLANO = TRUE) then
    Begin
    
      SETORDEM_AGRUPAMENTO_PLANO(0);
      
      WCAMPOSCOMCOALESCE2 = '';
      WCAMPOSSELECT = '';
      WCAMPOSF11 = '';
      WCOMPLEMENTAINSERT = '';
      WCAMPOSINSERT = '';
      WCAMPOSPLANO = '';
      /*Aqui vamos pegar os campos das tabelas
      -WCAMPOSF11 vai ter os campos que vão estar no select
      -WCAMPOSINSERT vai ter os campos que vão estar no INSERT da TMP
      -WCAMPOSCOMCOALESCE vai ter os campos que vão formar a chave sequencial*/

      /*Aqui vamos pegar os campos que vão ser comparados no JOIN da tabela de plano, para pegar todas as informações que forem idênticas
      -WCAMPOSFILTROF11 aqui vai estar os campos para ser usado no JOIN*/
      

      WSOMAESUBTRACAO = ' (select replace(replace(BDSOMA, ''FALSE'', ''F''), ''TRUE'', ''T'') BDSOMA ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' from (select list(BDPARAMETRO) BDSOMA ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' from (select S.BDCODTPIMP || ''|'' || coalesce(upper(BDSOMAABATNT), ''FALSE'') || ''|'' || coalesce(upper(BDSOMANFPROD), ''FALSE'') || ''|'' || coalesce(upper(BDSOMADESPACE), ''FALSE'') || ''|'' || coalesce(upper(BDSOMAFRETE), ''FALSE'') || ''|'' || coalesce(upper(BDSOMAIPI), ''FALSE'') || ''|'' || coalesce(upper(BDSOMAST), ''FALSE'') || ''|'' || coalesce(upper(BDSOMAREDBC), ''FALSE'') || ''|'' || coalesce(upper(BDSOMABASEISS), ''FALSE'') || ''|'' || coalesce(upper(BDSOMAICMS), ''FALSE'') || ''|'' || coalesce(upper(BDSOMADESCONTO), ''FALSE'') || ''|'' || coalesce(upper(BDSOMAISS), ''FALSE'') || ''|'' || coalesce(upper(BDSOMAPEDAGIO), ''FALSE'') || ''|'' || coalesce(upper(BDSOMABCICMSST), ''FALSE'') || ''|'' || coalesce(upper(BDSOMAVLRSEGURO), ''FALSE'') || ''|'' || coalesce(upper(BDSOMAFCP), ''FALSE'') || ''|'' || coalesce(upper(BDSOMAICMSCONC), ''FALSE'') || ''|'' || coalesce(upper(BDSOMAICMSORIGINAL), ''FALSE'') || ''|'' || coalesce(upper(BDSOMABCICMS), ''FALSE'') || ''|'' || coalesce(upper(BDSOMAIPIORIGINAL), ''FALSE'') BDPARAMETRO ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' from VEF_BASE_TTIPOTROCA T ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' join VEF_BASE_TSOMABC S on (S.BDCODTPIMP = T.BDCODTPIMP and ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' S.BDCODPLATROCA = T.BDCODPLATROCA and ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' S.BDCHAVE = T.BDCHAVE) ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' where T.BDCODPLATROCA = '||:PRCODPLANOCOPIADO||' and ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' T.BDCHAVE = coalesce(TA.BDCHAVE_ANTIGA, A.BDCHAVE) ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' order by T.BDCODTPIMP asc))) || ''|'' || ';
    

      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' (select replace(replace(BDSUB, ''FALSE'', ''F''), ''TRUE'', ''T'') BDSUB ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' from (select list(BDPARAMETRO) BDSUB ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' from (select S.BDCODTPIMP || ''|'' || coalesce(upper(BDSUBREDBC), ''FALSE'') || ''|'' || coalesce(upper(BDSUBNFPROD), ''FALSE'') || ''|'' || coalesce(upper(BDSUBDESPACE), ''FALSE'') || ''|'' || coalesce(upper(BDSUBFRETE), ''FALSE'') || ''|'' || coalesce(upper(BDSUBDESC), ''FALSE'') || ''|'' || coalesce(upper(BDSUBIPI), ''FALSE'') || ''|'' || coalesce(upper(BDSUBST), ''FALSE'') || ''|'' || coalesce(upper(BDSUBBASEISS), ''FALSE'') || ''|'' || coalesce(upper(BDSUBICMS), ''FALSE'') || ''|'' || coalesce(upper(BDSUBDESCONTO), ''FALSE'') || ''|'' || coalesce(upper(BDSUBISS), ''FALSE'') || ''|'' || coalesce(upper(BDSUBPEDAGIO), ''FALSE'') || ''|'' || coalesce(upper(BDSUBBCICMSST), ''FALSE'') || ''|'' || coalesce(upper(BDSUBVLRSEGURO), ''FALSE'') || ''|'' || coalesce(upper(BDSUBABATNT), ''FALSE'') || ''|'' || coalesce(upper(BDSUBFCP), ''FALSE'') || ''|'' || coalesce(upper(BDSUBICMSCONC), ''FALSE'') || ''|'' || coalesce(upper(BDSUBICMSORIGINAL), ''FALSE'') || ''|'' || coalesce(upper(BDSUBBCICMS), ''FALSE'') || ''|'' || coalesce(upper(BDSUBIPIORIGINAL), ''FALSE'') BDPARAMETRO ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' from VEF_BASE_TTIPOTROCA T ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' join VEF_BASE_TSUBTRACAOBC S on (S.BDCODTPIMP = T.BDCODTPIMP and ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' S.BDCODPLATROCA = T.BDCODPLATROCA and ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' S.BDCHAVE = T.BDCHAVE) ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' where T.BDCODPLATROCA = '||:PRCODPLANOCOPIADO||' and ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' T.BDCHAVE = coalesce(TA.BDCHAVE_ANTIGA, A.BDCHAVE) ';
      WSOMAESUBTRACAO = WSOMAESUBTRACAO ||' order by T.BDCODTPIMP asc))) ';

      WSQL = ' select distinct List(BDCAMPO, '' AND '') from( ';
      WSQL = WSQL||' select distinct (iif((RF.RDB$FIELD_SOURCE = ''DM_BOOLEAN'') or (F.RDB$FIELD_TYPE = 23), ''COALESCE(Upper(A.'' || trim(RF.RDB$FIELD_NAME) || ''), ''''FALSE'''')'' || '' = '' || ''COALESCE(Upper(X.'' || trim(RF.RDB$FIELD_NAME) || ''), ''''FALSE'''')'', iif((position(''BDCHAVE'', RF.RDB$FIELD_NAME) > 0) or (position(''BDCODPLATROCA'', RF.RDB$FIELD_NAME) > 0),''(A.''||trim(RF.RDB$FIELD_NAME) || '' = X.'' || trim(RF.RDB$FIELD_NAME)||'')'', iif((position(''A.BDCONSUFINALFIL'', RF.RDB$FIELD_NAME) > 0), '' COALESCE(A.'' || trim(RF.RDB$FIELD_NAME) || '', -1)'' || '' = '' || ''COALESCE(X.'' || trim(RF.RDB$FIELD_NAME) || '', -1)'', iif(F.RDB$FIELD_TYPE in (8), ''COALESCE(A.'' || trim(RF.RDB$FIELD_NAME) || '', -1)'' || '' = '' || ''COALESCE(X.'' || trim(RF.RDB$FIELD_NAME) || '', -1)'', iif(F.RDB$FIELD_TYPE in (37), ''COALESCE(A.'' || trim(RF.RDB$FIELD_NAME) || '', '''''''')'' || '' = '' || ''COALESCE(X.'' || trim(RF.RDB$FIELD_NAME) || '', '''''''')'', iif(F.RDB$FIELD_TYPE in (16), ''COALESCE(A.'' || trim(RF.RDB$FIELD_NAME) || '',0.00)'' || '' = '' || ''COALESCE(X.'' || trim(RF.RDB$FIELD_NAME) || '',0.00)'', trim(RF.RDB$FIELD_NAME) || '' = '' || trim(RF.RDB$FIELD_NAME)))))))) BDCAMPO ';
      WSQL = WSQL||' from RDB$RELATION_FIELDS RF ';
      WSQL = WSQL||' join RDB$FIELDS F on (F.RDB$FIELD_NAME = RF.RDB$FIELD_SOURCE) ';
      WSQL = WSQL||' where upper(trim(RF.RDB$RELATION_NAME)) = upper(trim(''VEF_BASE_TPLANOACOESTROCA''))   ';
      WSQL = WSQL||' ) ';
      EXECUTE STATEMENT :WSQL INTO :WCAMPOSFILTROF11;



      WSQL = 'SELECT list(iif((position(''BDNCMPROD'', RF.RDB$FIELD_NAME) > 0) or (position(''BDCODTER'', RF.RDB$FIELD_NAME) > 0) or (''BDCODNAT'' = RF.RDB$FIELD_NAME) or (position(''BDCODCLAENETEL'', RF.RDB$FIELD_NAME) > 0) or (''BDCHAVE'' = RF.RDB$FIELD_NAME), null, iif((position(''BDCHAVE'', RF.RDB$FIELD_NAME) > 0), null, iif((position(''BDCODPLATROCA'', RF.RDB$FIELD_NAME) > 0), null , Trim(RF.RDB$FIELD_NAMEFILTRO)))), '', ''), ';
      WSQL = WSQL||'      list(iif((position(''BDNCMPROD'', RF.RDB$FIELD_NAME) > 0) or (position(''BDCODTER'', RF.RDB$FIELD_NAME) > 0) or (''BDCODNAT'' = RF.RDB$FIELD_NAME) or (position(''BDCODCLAENETEL'', RF.RDB$FIELD_NAME) > 0) or (''BDCHAVE'' = RF.RDB$FIELD_NAME), null, iif((position(''BDCHAVE'', RF.RDB$FIELD_NAME) > 0), null, iif((position(''BDCODPLATROCA'', RF.RDB$FIELD_NAME) > 0), null ,trim(RF.RDB$FIELD_NAME)))), '', ''), ';
      WSQL = WSQL||'      list(iif((position(''BDNCMPROD'', RF.RDB$FIELD_NAME) > 0) or (position(''BDCODTER'', RF.RDB$FIELD_NAME) > 0) or (''BDCODNAT'' = RF.RDB$FIELD_NAME) or (position(''BDCODCLAENETEL'', RF.RDB$FIELD_NAME) > 0) or (''BDCHAVE'' = RF.RDB$FIELD_NAME) or (''BDQTDFILTRO'' = RF.RDB$FIELD_NAME), null, ''COALESCE(''||trim(RF.RDB$FIELD_NAME)||'', '''' '''')''), ''||''''|''''||'') ';
      WSQL = WSQL||'  from (select  iif(FK.CAMPOCOMFK is not null, ''Coalesce(A.'' || trim(FK.CAMPOCOMFK) || '',null) '' || FK.CAMPOCOMFK || '''', iif((RF.RDB$FIELD_SOURCE = ''DM_BOOLEAN'') or (FF.RDB$FIELD_TYPE = 23), ''Coalesce(Upper(A.'' || trim(RF.RDB$FIELD_NAME) || ''),''''FALSE'''') '' || RF.RDB$FIELD_NAME || '''',iif(FF.RDB$FIELD_TYPE = 37, ''Coalesce(A.'' || trim(RF.RDB$FIELD_NAME) || '','''''''') '' || RF.RDB$FIELD_NAME || '''', iif(FF.RDB$FIELD_TYPE = 8, ''Coalesce(A.'' || trim(RF.RDB$FIELD_NAME) || '',null) '' || RF.RDB$FIELD_NAME || '''', iif(FF.RDB$FIELD_TYPE = 16, ''Coalesce(A.'' || trim(RF.RDB$FIELD_NAME) || '',0.00)  '' || RF.RDB$FIELD_NAME || '''', RF.RDB$FIELD_NAME))))) RDB$FIELD_NAMEFILTRO, RF.RDB$FIELD_NAME ';
      WSQL = WSQL||'FROM RDB$RELATION_FIELDS RF ';
      WSQL = WSQL||'JOIN RDB$FIELDS F ON (F.RDB$FIELD_NAME = RF.RDB$FIELD_SOURCE) ';
      WSQL = WSQL||'join RDB$FIELDS FF on (RF.RDB$FIELD_SOURCE = FF.RDB$FIELD_NAME) ';
      WSQL = WSQL||'LEFT OUTER JOIN (SELECT ';
      WSQL = WSQL||'RCI.RDB$FIELD_NAME AS CAMPOCOMFK ';
      WSQL = WSQL||'FROM ';
      WSQL = WSQL||'RDB$RELATION_CONSTRAINTS RC ';
      WSQL = WSQL||'JOIN RDB$REF_CONSTRAINTS RI ON RC.RDB$CONSTRAINT_NAME = RI.RDB$CONSTRAINT_NAME ';
      WSQL = WSQL||'JOIN RDB$INDEX_SEGMENTS RCI ON RC.RDB$INDEX_NAME = RCI.RDB$INDEX_NAME ';
      WSQL = WSQL||'WHERE ';
      WSQL = WSQL||'RC.RDB$CONSTRAINT_TYPE = ''FOREIGN KEY''  AND ';
      WSQL = WSQL||'RC.RDB$RELATION_NAME = ''VEF_BASE_TPLANOACOESTROCA'') FK ON (FK.CAMPOCOMFK = RF.RDB$FIELD_NAME) ';
      WSQL = WSQL||'WHERE RF.RDB$RELATION_NAME = ''VEF_BASE_TPLANOACOESTROCA'' AND ';
      WSQL = WSQL||'      RF.RDB$FIELD_NAME <> ''BDCODEMP'' AND RF.RDB$FIELD_NAME <> ''BDCHAVE'' ) RF ';
      EXECUTE STATEMENT :WSQL INTO :WCAMPOSF11, :WCAMPOSINSERT, :WCAMPOSCOMCOALESCE;
    
      WCAMPOSSELECT = :WCAMPOSF11;
      WCAMPOSF11 = '';
      WCOMPLEMENTAINSERT = :WCAMPOSINSERT;
      WCAMPOSINSERT = '';
      WCAMPOSCOMCOALESCE2 = :WCAMPOSCOMCOALESCE;
    
      WSQL = 'SELECT LIST(iif((position(''BDCODPLATROCA'', RF.RDB$FIELD_NAME) > 0) or (position(''BDCHAVE'', RF.RDB$FIELD_NAME) > 0), null, TRIM(RF.RDB$FIELD_NAMEFILTRO))), ';
      WSQL = WSQL||'LIST(iif((position(''BDCODPLATROCA'', RF.RDB$FIELD_NAME) > 0) or (position(''BDCHAVE'', RF.RDB$FIELD_NAME) > 0), null, TRIM(RF.RDB$FIELD_NAME))) ';
    --      WSQL = WSQL||'list(iif((RF.RDB$FIELD_NAME <> ''BDCODTPIMP''), null, ''COALESCE(''||trim(RF.RDB$FIELD_NAME)||'', '''' '''')''), ''||''''|''''||'') ';
      WSQL = WSQL||'  from (select  iif(FK.CAMPOCOMFK is not null, ''Coalesce(TIP.'' || trim(FK.CAMPOCOMFK) || '',null) '' || FK.CAMPOCOMFK || '''', iif((RF.RDB$FIELD_SOURCE = ''DM_BOOLEAN'') or (FF.RDB$FIELD_TYPE = 23), ''Coalesce(Upper(TIP.'' || trim(RF.RDB$FIELD_NAME) || ''),''''FALSE'''') '' || RF.RDB$FIELD_NAME || '''',iif(FF.RDB$FIELD_TYPE = 37, ''Coalesce(TIP.'' || trim(RF.RDB$FIELD_NAME) || '','''''''') '' || RF.RDB$FIELD_NAME || '''', iif(FF.RDB$FIELD_TYPE = 8, ''Coalesce(TIP.'' || trim(RF.RDB$FIELD_NAME) || '',null) '' || RF.RDB$FIELD_NAME || '''', iif(FF.RDB$FIELD_TYPE = 16, ''Coalesce(TIP.'' || trim(RF.RDB$FIELD_NAME) || '',0.00)  '' || RF.RDB$FIELD_NAME || '''', RF.RDB$FIELD_NAME))))) RDB$FIELD_NAMEFILTRO, RF.RDB$FIELD_NAME ';
      WSQL = WSQL||'FROM RDB$RELATION_FIELDS RF ';
      WSQL = WSQL||'JOIN RDB$FIELDS F ON (F.RDB$FIELD_NAME = RF.RDB$FIELD_SOURCE) ';
      WSQL = WSQL||'join RDB$FIELDS FF on (RF.RDB$FIELD_SOURCE = FF.RDB$FIELD_NAME) ';
      WSQL = WSQL||'LEFT OUTER JOIN (SELECT ';
      WSQL = WSQL||'RCI.RDB$FIELD_NAME AS CAMPOCOMFK ';
      WSQL = WSQL||'FROM ';
      WSQL = WSQL||'RDB$RELATION_CONSTRAINTS RC ';
      WSQL = WSQL||'JOIN RDB$REF_CONSTRAINTS RI ON RC.RDB$CONSTRAINT_NAME = RI.RDB$CONSTRAINT_NAME ';
      WSQL = WSQL||'JOIN RDB$INDEX_SEGMENTS RCI ON RC.RDB$INDEX_NAME = RCI.RDB$INDEX_NAME ';
      WSQL = WSQL||'WHERE ';
      WSQL = WSQL||'RC.RDB$CONSTRAINT_TYPE = ''FOREIGN KEY''  AND ';
      WSQL = WSQL||'RC.RDB$RELATION_NAME = ''VEF_BASE_TTIPOTROCA'') FK ON (FK.CAMPOCOMFK = RF.RDB$FIELD_NAME) ';
      WSQL = WSQL||'WHERE RF.RDB$RELATION_NAME = ''VEF_BASE_TTIPOTROCA'' ) RF ';
    
      EXECUTE STATEMENT :WSQL INTO :WCAMPOSF11, :WCAMPOSINSERT;--, :WCAMPOSCOMCOALESCE;
    
      WCAMPOSPLANO = :WCOMPLEMENTAINSERT||','||:WCAMPOSINSERT;
      WCAMPOSSELECT = WCAMPOSSELECT||','||:WCAMPOSF11;
      WCOMPLEMENTAINSERT = :WCOMPLEMENTAINSERT||','||:WCAMPOSINSERT;
      WCAMPOSF11 = '';
      WCAMPOSINSERT = '';
      --WCAMPOSCOMCOALESCE2 = :WCAMPOSCOMCOALESCE2||'|| ''|'' ||'||:WCAMPOSCOMCOALESCE;
    
    
      /*Aqui vamos pegar e inserir os dados que retornar no SQL para a TMP
      Percebe-se que por conta das tabelas relacionadas com a do plano, no SQL vamos ter registros duplicados, porém há uma explicação para isso;
      -> Os registros vão ir duplicados para a TMP para que seja possível fazer a inclusão dos dados corretamente das tabelas de soma,
         subtração e das tabelas do F11 de terceiro, CFOP e NCM; */
      WCOUNTVERSAO = 1;
      WCOUNTVERSAONOVA = 0;
      WVERSAO = 0;
      WHILE (WCOUNTVERSAO <> WCOUNTVERSAONOVA) DO
        BEGIN                             
          SETORDEM_AGRUPAMENTO_PLANO(0);

          WCOUNTVERSAO = WCOUNTVERSAONOVA;
          WVERSAO = WVERSAO + 1;

          WSQL = 'INSERT INTO TMP_AGRUP_ACOES_PLANO_TEMP(BDSESSAO,BDVERSAO,BDCODPLATROCA, BDCHAVE, BDCODPLATROCA_ANTIGO, BDCHAVE_ANTIGA) ';
          WSQL = WSQL||'SELECT A.BDSESSAO, '||:WVERSAO||' BDVERSAO, A.BDCODPLATROCA, GETORDEM_AGRUPAMENTO_PLANO(BDPARAMETROS'||' || '||WSOMAESUBTRACAO||', A.BDCODNATF11, A.BDNCMPROD, A.BDCODTERF11) BDCHAVE, ';
          WSQL = WSQL||'       '||PRCODPLANOCOPIADO||' BDCODPLATROCA_ANTIGO, Coalesce(TA.BDCHAVE_ANTIGA, A.BDCHAVE) BDCHAVE_ANTIGA ';
    --      WSQL = WSQL||' from (select BDCHAVE, BDSESSAO, BDCODNATCAPA, BDCODTERCAPA, BDCODPLATROCA, BDPARAMETROS,  BDNCMPROD, ';
    --      WSQL = WSQL||'              BDCODNATF11, BDCODTERF11, '||WCOMPLEMENTAINSERT;
          WSQL = WSQL||' from (select BDCHAVE, BDSESSAO, BDCODPLATROCA, BDPARAMETROS, list(distinct BDNCMPROD, ''|'') BDNCMPROD, ';
          WSQL = WSQL||'             list(distinct Coalesce(BDCODNATF11, BDCODNATCAPA), ''|'') BDCODNATF11, list(distinct Coalesce(BDCODTERF11, BDCODTERCAPA), ''|'') BDCODTERF11, list(distinct coalesce(BDCODENETELF11, BDCODENETELCAPA), ''|'') BDCODENETELF11 ';
                                                                                                                   
          WSQL = WSQL||' from (select A.*, ';
          WSQL = WSQL||'             Replace(Replace(Replace(Replace(Replace('||WCAMPOSCOMCOALESCE2||',''0.00'',''''),''0.0000'',''''),''|00'',''''),''|0'',''||''),''||'','''') BDPARAMETROS ';
          WSQL = WSQL||' FROM( select ';
    
    
          WSQL2 = :PRSESSAO||' BDSESSAO, BDCHAVE,BDNCMPROD,BDCODNATF11, BDCODNATCAPA, BDCODTERF11, BDCODTERCAPA, BDCODENETELF11, BDCODENETELCAPA,'||:PRCODPLANOTROCA||' BDCODPLATROCA, '||WCOMPLEMENTAINSERT||' FROM( ';
          WSQL2 = WSQL2||'SELECT DISTINCT A.* FROM ( ';
          WSQL2 = WSQL2||'SELECT DISTINCT bdncmprodlistf11, Coalesce(NCM2.BDNCMPROD, A.BDNCMPROD) BDNCMPROD, BDCODNATLISTF11, cfop2.bdcodnat bdcodnatf11, A.BDCODNAT BDCODNATCAPA , BDCODTERLISTF11, ter2.bdcodter bdcodterf11, a.bdcodter BDCODTERCAPA, BDCODENETELLISTF11, ENETEL2.bdcodclaenetel BDCODENETELF11, A.bdcodclaenetel bdcodenetelCAPA, a.BDCODPLATROCA, Coalesce(t.bdchave,a.bdchave) bdchave, '||WCAMPOSSELECT||' FROM (';
          WSQL2 = WSQL2||'select * ';
          WSQL2 = WSQL2||'from VEF_BASE_TPLANOACOESTROCA A ';
          WSQL2 = WSQL2||'where A.BDCODPLATROCA = '||PRCODPLANOCOPIADO||' ) A ';    
          WSQL2 = WSQL2||' LEFT OUTER JOIN TMP_AGRUP_ACOES_PLANO_TEMP T ON (T.BDSESSAO = '||:PRSESSAO||' AND T.BDVERSAO = '||(:WVERSAO-1)||' AND T.BDCODPLATROCA_ANTIGO = A.BDCODPLATROCA AND T.BDCHAVE_ANTIGA = A.BDCHAVE) ';
        
          WSQL3 = ' LEFT OUTER JOIN (select list(bdncmprod,''.'') BDNCMPRODLISTF11, bdchave, bdcodplatroca from VEF_BASE_TPLANOACOESTROCA_NCM where bdcodplatroca = '||:PRCODPLANOCOPIADO||' group by bdchave, bdcodplatroca) NCM on (NCM.BDCODPLATROCA = A.BDCODPLATROCA and A.BDCHAVE = NCM.BDCHAVE) ';
          WSQL3 = WSQL3||'LEFT OUTER JOIN (select list(bdcodnat,''.'') bdcodnatLISTf11, bdchave,bdcodplatroca from VEF_BASE_TPLANOACOESTROCACFOPS where bdcodplatroca = '||:PRCODPLANOCOPIADO||' group by bdcodplatroca, bdchave) CFOP on (CFOP.BDCODPLATROCA = A.BDCODPLATROCA and A.BDCHAVE = CFOP.BDCHAVE) ';
          WSQL3 = WSQL3||'left outer join(select list(BDCODCLAENETEL, ''.'') BDCODENETELLISTF11, BDCHAVE, BDCODPLATROCA from VEF_BASE_TPLANOACOESTROCA_CLASSENETEL where BDCODPLATROCA = '||:PRCODPLANOCOPIADO||' group by BDCODPLATROCA, BDCHAVE) ENETEL on (ENETEL.BDCODPLATROCA = A.BDCODPLATROCA and A.BDCHAVE = ENETEL.BDCHAVE) ';
          WSQL3 = WSQL3||'LEFT OUTER JOIN VEF_BASE_TTIPOTROCA TIP ON (TIP.BDCODPLATROCA = A.BDCODPLATROCA AND TIP.BDCHAVE = A.BDCHAVE) ';
          WSQL3 = WSQL3||'LEFT OUTER JOIN VEF_BASE_TSOMABC SOM ON (SOM.BDCODPLATROCA = TIP.BDCODPLATROCA AND SOM.BDCHAVE = TIP.BDCHAVE AND SOM.BDCODTPIMP = TIP.BDCODTPIMP) ';
          WSQL3 = WSQL3||'LEFT OUTER JOIN VEF_BASE_TSUBTRACAOBC SUB ON (SUB.BDCODPLATROCA = TIP.BDCODPLATROCA AND SUB.BDCHAVE = TIP.BDCHAVE AND SUB.BDCODTPIMP = TIP.BDCODTPIMP) ';
          WSQL3 = WSQL3||'LEFT OUTER JOIN (select list(bdcodter,''.'') bdcodterLISTF11, bdchave,bdcodplatroca from VEF_BASE_TPLANOACOESTROCA_TER where bdcodplatroca = '||:PRCODPLANOCOPIADO||' group by bdchave,bdcodplatroca) TER on (TER.BDCODPLATROCA = A.BDCODPLATROCA and A.BDCHAVE = TER.BDCHAVE) ';
          WSQL3 = WSQL3||'      left outer join VEF_BASE_TPLANOACOESTROCA_NCM NCM2 on (NCM2.BDCODPLATROCA = A.BDCODPLATROCA and ';
          WSQL3 = WSQL3||' A.BDCHAVE = NCM2.BDCHAVE) ';
          WSQL3 = WSQL3||' left outer join VEF_BASE_TPLANOACOESTROCACFOPS CFOP2 on (CFOP2.BDCODPLATROCA = A.BDCODPLATROCA and ';
          WSQL3 = WSQL3||' A.BDCHAVE = CFOP2.BDCHAVE) ';
          WSQL3 = WSQL3||' left outer join VEF_BASE_TPLANOACOESTROCA_TER TER2 on (TER2.BDCODPLATROCA = A.BDCODPLATROCA and ';
          WSQL3 = WSQL3||' A.BDCHAVE = TER2.BDCHAVE) ';
          WSQL3 = WSQL3||' left outer join VEF_BASE_TPLANOACOESTROCA_CLASSENETEL ENETEL2 on (ENETEL2.BDCODPLATROCA = A.BDCODPLATROCA and A.BDCHAVE = ENETEL2.BDCHAVE) ';
          WSQL3 = WSQL3||' join VEF_BASE_TPLANOACOESTROCA X on ('||WCAMPOSFILTROF11||') ';
          WSQL3 = WSQL3||' and coalesce(A.BDCODNAT, -1) = coalesce(X.BDCODNAT, -1) and ';
          WSQL3 = WSQL3||'coalesce(A.BDNCMPROD, -1) = coalesce(X.BDNCMPROD, -1) and ';
          WSQL3 = WSQL3||'coalesce(A.BDCODTER, -1) = coalesce(X.BDCODTER, -1) and ';
          WSQL3 = WSQL3||' coalesce(a.bdcodclaenetel, -1) = coalesce(x.bdcodclaenetel, -1) ';
          WSQL3 = WSQL3||' ) A ';
          WSQL3 = WSQL3||'   )A ';
          WSQL3 = WSQL3||'   )A ';
          WSQL3 = WSQL3||'   )A ';
          WSQL3 = WSQL3||' group by BDCHAVE, BDSESSAO, BDCODPLATROCA, BDPARAMETROS ';
          WSQL3 = WSQL3||'   )A ';
          WSQL3 = WSQL3||' LEFT OUTER JOIN TMP_AGRUP_ACOES_PLANO_TEMP TA ON (TA.BDSESSAO = '||:PRSESSAO||' AND TA.BDVERSAO = '||(:WVERSAO-1)||' AND TA.BDCODPLATROCA = A.BDCODPLATROCA AND TA.BDCHAVE = A.BDCHAVE) ';
          --WSQL3 = WSQL3||' LEFT OUTER JOIN TMP_AGRUP_ACOES_PLANO_TEMP T ON (T.BDSESSAO = '||:PRSESSAO||' AND T.BDVERSAO = '||(:WVERSAO-1)||' AND TA.BDCODPLATROCA_ANTIGO = T.BDCODPLATROCA AND TA.BDCHAVE_ANTIGA = T.BDCHAVE) ';
        
          WTEXT = :WSQL || :WSQL2 || :WSQL3;
          EXECUTE STATEMENT WTEXT;
                                                                 
          WSQL = 'SELECT COUNT(DISTINCT BDCHAVE) FROM TMP_AGRUP_ACOES_PLANO_TEMP WHERE BDSESSAO = '||:PRSESSAO||' and BDCODPLATROCA = '||:PRCODPLANOTROCA || ' AND BDVERSAO = '||:WVERSAO;
          EXECUTE STATEMENT :WSQL INTO WCOUNTVERSAONOVA;  
       END

     /*Aqui nas SP abaixo vai pegar os dados que foram inseridos na TMP e agrupar corretamente em cada tabela correspondente*/  
     WSQL = ' DELETE FROM TMP_AGRUP_ACOES_PLANO_TEMP WHERE BDSESSAO = '||:PRSESSAO||' and BDCODPLATROCA = '||:PRCODPLANOTROCA || ' AND BDVERSAO <> '||:WVERSAO;
     EXECUTE STATEMENT :WSQL;

     EXECUTE PROCEDURE SP_AGRUPAR_NOVO_PLANO(:PRSESSAO,:PRCODPLANOTROCA, :PRCODPLANOCOPIADO);
     WSQL = ' DELETE FROM TMP_AGRUP_ACOES_PLANO_TEMP WHERE BDSESSAO = '||:PRSESSAO||' and BDCODPLATROCA = '||:PRCODPLANOTROCA;
     EXECUTE STATEMENT :WSQL;

    End
  if (:PRAGRUPARPLANO = FALSE) then
    Begin
  WSQL = ' INSERT INTO VEF_BASE_TPLANOACOESTROCA ';
  WSQL = WSQL||' (BDCODPLATROCA, BDCHAVE,  BDCODCSTPISENTFIL, BDNCMPROD, BDCODCSTICMSENTFIL, BDCODCSTCOFENTFIL, ';
  WSQL = WSQL||' BDCODCSTIPIENTFIL, BDCODCSTPISSAIFIL, BDCODCSTIPISAIFIL, BDCODCSTCOFSAIFIL, BDCODTER, BDCODCSTCOFENTACAO, ';
  WSQL = WSQL||' BDCODCSTICMSSAIFIL, BDCODCSTICMSENTACAO, BDCODNATBCCOFACAO, BDCODNATRECCOFACAO, BDCODCSTCOFSAIACAO, ';
  WSQL = WSQL||' BDCODCSTIPIENTACAO, BDCODCSTPISENTACAO, BDCODCSTPISSAIACAO, BDCODCSTIPISAIACAO, BDCODNATBCPISACAO, ';
  WSQL = WSQL||' BDCODNATRECPISACAO, BDCODPROD, BDCODNAT, BDCODCSTICMSSAIACAO, BDTIPOLAN, BDMODELO, BDESPECIE, ';
  WSQL = WSQL||' BDSERIE, BDQTDFILTRO, BDAPLICAACOES, BDZERARVLR, BDCSTICMSACAO, BDCSTIPIACAO, BDCSTPISACAO, BDCSTCOFINSACAO, ';
  WSQL = WSQL||' BDALIQICMSACAO, BDALIQICMSSTACAO, BDALIQIPIACAO, BDALIQPISACAO, BDALIQCOFINSACAO, BDALIQICMS, BDALIQICMSST, ';
  WSQL = WSQL||' BDALIQPIS, BDALIQIPI, BDALIQCOFINS, BDVALORICMSACAO, BDVALORICMSSTACAO, BDVALORPISACAO, BDVALORIPIACAO, ';
  WSQL = WSQL||' BDVALORCOFINSACAO, BDLANCAREMICMSACAO, BDNATCREPISACAO, BDNATCRECOFINSACAO, BDNATRECPISACAO, BDNATRECCOFINSACAO, ';
  WSQL = WSQL||' BDBCICMSACAO, BDBCICMSSTACAO, BDBCIPIACAO, BDBCPISACAO, BDBCCOFINSACAO, BDCODNATLANCACAO, BDSERIELANCACAO, ';
  WSQL = WSQL||' BDORDEMFRETELANCACAO, BDALIQICMSFIL, BDBCICMSC197ACAO, BDALIQICMSC197ACAO, BDVALORICMSC197ACAO, BDALIQICMSC197, ';
  WSQL = WSQL||' BDCODOBSC195, BDCODAJUC197, BDBCRETPISACAO, BDBCRETCOFINSACAO, BDBCRETCSLLACAO, BDBCRETIRRFACAO, BDBCRETINSSACAO, ';
  WSQL = WSQL||' BDALIQRETPISACAO, BDALIQRETCOFINSACAO, BDALIQRETCSLLACAO, BDALIQRETIRRFACAO, BDALIQRETINSSACAO, BDALIQRETPIS, ';
  WSQL = WSQL||' BDALIQRETCOFINS, BDALIQRETCSLL, BDALIQRETIRRF, BDALIQRETINSS, BDVALORRETPISACAO, BDVALORRETCOFINSACAO, ';
  WSQL = WSQL||' BDVALORRETCSLLACAO, BDVALORRETIRRFACAO, BDVALORRETINSSACAO, BDCODRECRETPISACAO, BDCODRECRETPIS, ';
  WSQL = WSQL||' BDCODRECRETCOFINSACAO, BDCODRECRETCOFINS, BDCODRECRETCSLLACAO, BDCODRECRETCSLL, BDCODRECRETIRRFACAO, ';
  WSQL = WSQL||' BDCODRECRETIRRF, BDCODRECRETINSSACAO, BDCODRECRETINSS, BDVLRIGUALA, BDVLRMENORQUE, BDVLRMAIORQUE,BDCODNATFLANCACAO, ';
  WSQL = WSQL||' BDCODNATRENDPIS, BDCODNATRENDCOFINS, BDCODNATRENDCSLL, BDCODNATRENDIRRF, BDCODNATRENDPISACAO, BDCODNATRENDCOFINSACAO, BDCODNATRENDCSLLACAO, BDCODNATRENDIRRFACAO) ';
    
    
    
  WSQL = WSQL||' SELECT BDCODPLATROCA, (SELECT MAX(BDCHAVE)+1 FROM VEF_BASE_TPLANOACOESTROCA WHERE BDCODPLATROCA = '||prcodplanotroca||') AS BDCHAVE, ';
  WSQL = wSQL||'        BDCODCSTPISENTFIL, BDNCMPROD, BDCODCSTICMSENTFIL, BDCODCSTCOFENTFIL, BDCODCSTIPIENTFIL, BDCODCSTPISSAIFIL, BDCODCSTIPISAIFIL, ';
  WSQL = WSQL||'        BDCODCSTCOFSAIFIL, BDCODTER, BDCODCSTCOFENTACAO, BDCODCSTICMSSAIFIL, BDCODCSTICMSENTACAO, BDCODNATBCCOFACAO, BDCODNATRECCOFACAO, BDCODCSTCOFSAIACAO, ';
  WSQL = WSQL||'        BDCODCSTIPIENTACAO, BDCODCSTPISENTACAO, BDCODCSTPISSAIACAO, BDCODCSTIPISAIACAO, BDCODNATBCPISACAO, BDCODNATRECPISACAO, BDCODPROD, BDCODNAT, ';
  WSQL = WSQL||'        BDCODCSTICMSSAIACAO,'||prtipolanpara||' AS BDTIPOLAN, ';
    
  IF (prtipolanpara = 3) THEN --Redução Z não tem modelo
    BEGIN
      WSQL = WSQL||'      NULL AS BDMODELO, ';
    END
  ELSE
    BEGIN
      WSQL = WSQL||'      BDMODELO, ';
    END
    
  WSQL = WSQL||'        BDESPECIE, BDSERIE, BDQTDFILTRO, BDAPLICAACOES, BDZERARVLR, BDCSTICMSACAO, BDCSTIPIACAO, BDCSTPISACAO, ';
  WSQL = WSQL||'        BDCSTCOFINSACAO, BDALIQICMSACAO, BDALIQICMSSTACAO, BDALIQIPIACAO, BDALIQPISACAO, BDALIQCOFINSACAO, BDALIQICMS, BDALIQICMSST, BDALIQPIS, BDALIQIPI, ';
  WSQL = WSQL||'        BDALIQCOFINS, BDVALORICMSACAO, BDVALORICMSSTACAO, BDVALORPISACAO, BDVALORIPIACAO, BDVALORCOFINSACAO, BDLANCAREMICMSACAO, BDNATCREPISACAO, BDNATCRECOFINSACAO, ';
  WSQL = WSQL||'        BDNATRECPISACAO, BDNATRECCOFINSACAO, BDBCICMSACAO, BDBCICMSSTACAO, BDBCIPIACAO, BDBCPISACAO, BDBCCOFINSACAO, BDCODNATLANCACAO, BDSERIELANCACAO, ';
  WSQL = WSQL||'        BDORDEMFRETELANCACAO, BDALIQICMSFIL, BDBCICMSC197ACAO, BDALIQICMSC197ACAO, BDVALORICMSC197ACAO, BDALIQICMSC197, BDCODOBSC195, BDCODAJUC197, BDBCRETPISACAO, ';
  WSQL = WSQL||'        BDBCRETCOFINSACAO, BDBCRETCSLLACAO, BDBCRETIRRFACAO, BDBCRETINSSACAO, BDALIQRETPISACAO, BDALIQRETCOFINSACAO, BDALIQRETCSLLACAO, BDALIQRETIRRFACAO, ';
  WSQL = WSQL||'        BDALIQRETINSSACAO, BDALIQRETPIS, BDALIQRETCOFINS, BDALIQRETCSLL, BDALIQRETIRRF, BDALIQRETINSS, BDVALORRETPISACAO, BDVALORRETCOFINSACAO, BDVALORRETCSLLACAO, ';
  WSQL = WSQL||'        BDVALORRETIRRFACAO, BDVALORRETINSSACAO, BDCODRECRETPISACAO, BDCODRECRETPIS, BDCODRECRETCOFINSACAO, BDCODRECRETCOFINS, BDCODRECRETCSLLACAO, BDCODRECRETCSLL, ';
  WSQL = WSQL||'        BDCODRECRETIRRFACAO, BDCODRECRETIRRF, BDCODRECRETINSSACAO, BDCODRECRETINSS, BDVLRIGUALA, BDVLRMENORQUE, BDVLRMAIORQUE,BDCODNATFLANCACAO, ';
  WSQL = WSQL||'        BDCODNATRENDPIS, BDCODNATRENDCOFINS, BDCODNATRENDCSLL, BDCODNATRENDIRRF, BDCODNATRENDPISACAO, BDCODNATRENDCOFINSACAO, BDCODNATRENDCSLLACAO, BDCODNATRENDIRRFACAO ';
  WSQL = WSQL||' FROM VEF_BASE_TPLANOACOESTROCA ';
  WSQL = WSQL||' WHERE bdcodplatroca = '||prcodplanotroca;
  WSQL = WSQL||' AND bdtipolan = '||prtipolande;
  EXECUTE STATEMENT WSQL;
    
  SELECT MAX(BDCHAVE)+1 FROM VEF_BASE_TPLANOACOESTROCA WHERE BDCODPLATROCA = :prcodplanotroca AND BDTIPOLAN = :prtipolanpara INTO :wchavetpimp;
    
  wChaveAnt = 0;
  FOR SELECT TT.bdchave, TT.bdcodtpimp FROM VEF_BASE_TTIPOTROCA TT
      JOIN VEF_BASE_TPLANOACOESTROCA TP ON(TP.bdcodplatroca = TT.bdcodplatroca AND TP.bdchave = TT.bdchave AND TP.bdtipolan = :prtipolande)
      WHERE TT.bdcodplatroca = :prcodplanotroca ORDER BY TT.bdchave DESC, TT.bdcodtpimp DESC INTO :wchave, :wcodtpimp DO
    BEGIN
      IF (:wChaveant <> :wChave) THEN
        BEGIN
          wChaveAnt = :wChave;
          wchavetpimp = :wchavetpimp - 1;
        END
      INSERT INTO VEF_BASE_TTIPOTROCA(BDCODPLATROCA, BDCHAVE, bdcodtpimp) VALUES(:prcodplanotroca, :wchavetpimp, :wcodtpimp);
    END
    
  SELECT MAX(BDCHAVE)+1 FROM VEF_BASE_TPLANOACOESTROCA WHERE BDCODPLATROCA = :prcodplanotroca AND BDTIPOLAN = :prtipolanpara INTO :wchavetpimp;
    
  wChaveAnt = 0;
  FOR SELECT SM.bdchave, SM.bdcodtpimp, SM.bdsomanfprod, SM.bdsomadespace, sm.bdsomafrete, sm.bdsomaipi, sm.bdsomast, sm.bdsomaredbc, sm.bdsomabaseiss FROM VEF_BASE_TSOMABC SM
      JOIN VEF_BASE_TPLANOACOESTROCA PA ON(PA.bdcodplatroca = SM.bdcodplatroca AND PA.bdchave = SM.bdchave AND PA.bdtipolan = :prtipolande)
      WHERE SM.bdcodplatroca = :prcodplanotroca ORDER BY SM.bdchave DESC, SM.bdcodtpimp DESC INTO :wchave, :wcodtpimp, :wnfprod, :wdespace, :wfrete, :wipi, :wst, :wredbc, :wbaseiss DO
  BEGIN
    IF (:wChaveAnt <> :wChave) THEN
      BEGIN
        wChaveAnt = :wChave;
        wchavetpimp = :wchavetpimp - 1;
      END
    
      INSERT INTO VEF_BASE_TSOMABC(BDCODTPIMP, BDCODPLATROCA, BDCHAVE, BDSOMANFPROD, BDSOMADESPACE, BDSOMAFRETE, BDSOMAIPI, BDSOMAST, BDSOMAREDBC, BDSOMABASEISS)
      VALUES(:wcodtpimp, :prcodplanotroca, :wchavetpimp, :wnfprod, :wdespace, :wfrete, :wipi, :wst, :wredbc, :wbaseiss);
  END
    
  SELECT MAX(BDCHAVE)+1 FROM VEF_BASE_TPLANOACOESTROCA WHERE BDCODPLATROCA = :prcodplanotroca AND BDTIPOLAN = :prtipolanpara INTO :wchavetpimp;
    
  wChaveAnt = 0;
  FOR SELECT SUB.bdchave, SUB.bdcodtpimp, SUB.bdsubnfprod, SUB.bdsubdespace, SUB.bdsubfrete, SUB.bdsubipi, SUB.bdsubst, SUB.bdsubredbc, SUB.bdsubbaseiss, SUB.bdsubdesc FROM VEF_BASE_TSUBTRACAOBC SUB
      JOIN VEF_BASE_TPLANOACOESTROCA PA ON(PA.bdcodplatroca = SUB.bdcodplatroca AND PA.bdchave = SUB.bdchave AND PA.bdtipolan = :prtipolande)
      WHERE SUB.bdcodplatroca = :prcodplanotroca ORDER BY SUB.bdchave DESC, SUB.bdcodtpimp DESC INTO :wchave, :wcodtpimp, :wnfprod, :wdespace, :wfrete, :wipi, :wst, :wredbc, :wbaseiss, :wdesc DO
  BEGIN
    IF (:wChaveAnt <> :wChave) THEN
      BEGIN
        wChaveAnt = :wChave;
        wchavetpimp = :wchavetpimp - 1;
      END
    
      INSERT INTO VEF_BASE_TSUBTRACAOBC(BDCODTPIMP, BDCODPLATROCA, BDCHAVE, BDSUBNFPROD, BDSUBDESPACE, BDSUBFRETE, BDSUBIPI, BDSUBST, BDSUBREDBC, BDSUBBASEISS, BDSUBDESC)
      VALUES(:wcodtpimp, :prcodplanotroca, :wchavetpimp, :wnfprod, :wdespace, :wfrete, :wipi, :wst, :wredbc, :wbaseiss, :wDesc);
  END
    
    SELECT MAX(BDCHAVE)+1 FROM VEF_BASE_TPLANOACOESTROCA WHERE BDCODPLATROCA = :prcodplanotroca AND BDTIPOLAN = :prtipolanpara INTO :wchavetpimp;
    
  --   elizeu - 08-10-19 - Varias cfops na mesma chave de troca - Plano de troca F11 Filtro CFOP #Fatos!
  wChaveAnt = 0;
  FOR SELECT c.bdchave, c.bdcodnat FROM VEF_BASE_TPLANOACOESTROCACFOPS c
      JOIN VEF_BASE_TPLANOACOESTROCA PA ON(PA.bdcodplatroca = c.bdcodplatroca AND PA.bdchave = c.bdchave AND PA.bdtipolan = :prtipolande)
      WHERE c.bdcodplatroca = :prcodplanotroca
      ORDER BY c.bdchave DESC INTO :wchave, :wcodNat DO
  BEGIN
    WCODNATEXIS = 0;
    IF (:wChaveAnt <> :wChave) THEN
      BEGIN
        wChaveAnt = :wChave;
        wchavetpimp = :wchavetpimp - 1;
      END
      SELECT BDCODNAT FROM VEF_BASE_TPLANOACOESTROCACFOPS C WHERE C.BDCODPLATROCA = :prcodplanotroca AND C.BDCHAVE = :wchavetpimp
      AND C.BDCODNAT = :WCODNAT INTO WCODNATEXIS; --Quando insere o plano, ele já insere a CFOP, quando chega nessa rotina, tenta inserir novamente e da erro
    
      if (:WCODNATEXIS <= 0) then
         begin
           INSERT INTO VEF_BASE_TPLANOACOESTROCACFOPS(BDCODPLATROCA, BDCHAVE, BDCODNAT)
                                          VALUES(:prcodplanotroca, :wchavetpimp, :wCodNat);
         end
  END
 End
END^
SET TERM ; ^

SET TERM ^ ;

create or alter procedure SP_TOTSERDESPPERIODO (
    PRCODESC varchar(500),
    PRDATAINICIAL varchar(10),
    PRDATAFINAL varchar(10),
    PRCHAVECTABAN varchar(500),
    PRTIPOSERDESP integer,
    PRCODSERDESP integer,
    PRCODCLI varchar(10240),
    PRCODFOR varchar(10240),
    PRDEMLANCREEMBOLSO DM_BOOLEAN,
    PRDEMTRANSFBANCARIAS DM_BOOLEAN,
    PRMODELO integer,
    PRCLASSSERDESP varchar(60),
    PRDESCONTO varchar(5),
    PRNUMPERATU integer,
    PRDESCPERIODO varchar(12))
returns (
    BDTOTSERDESPPERIODO numeric(15,2))
as
declare variable VSQL varchar(20000);
declare variable VCODCLIFOR integer;
declare variable VTOTALPERIODOSEL numeric(15,2);
declare variable VSQLTOTALPERIODO varchar(500);
declare variable VTOTALGERAL numeric(15,2);
BEGIN
  BDTOTSERDESPPERIODO = 0;
  if (prmodelo = 0) then
    begin
      vsql = 'select coalesce(sum(lan.bdvalorlanc),0) from vfin_esc_tlancbancario lan ';

      IF (:prtiposerdesp = 0) THEN
         BEGIN
           vsql = vsql || 'where lan.bdcodobrser = '||:prcodserdesp||' ';
         END
      ELSE
        vsql = vsql || 'where lan.bdcoddesp = '||:prcodserdesp||' ';
    
      IF ((:prcodesc <> '') AND (:prcodesc IS NOT NULL)) THEN
         vsql = vsql || 'and lan.bdcodesc in ('||:prcodesc||') ';
    
      IF ((:prchavectaban <> '') AND (:prchavectaban IS NOT NULL)) THEN
         vsql = vsql || 'and lan.bdchavectaban in ('||:prchavectaban||') ';
    
      IF (:prtiposerdesp IS NOT NULL) THEN
         vsql = vsql || 'and lan.bdtiposervdesp = '||:prtiposerdesp||' ';
    
      IF ((:prdatainicial <> '') AND (:prdatainicial IS NOT NULL)) THEN
          vsql = vsql || 'and lan.bddatalan >='||''''||:prdatainicial||''''||' ';
    
      IF ((:prdatafinal <> '') AND (:prdatafinal IS NOT NULL)) THEN
         vsql = vsql || 'and lan.bddatalan <= '||''''||:prdatafinal||''''||' ';
    
      IF ((:prcodcli <> '') AND (:prcodcli IS NOT NULL)) THEN
         vsql = vsql || 'and lan.bdcodcli in ('||:prcodcli||') ';
    
      IF ((:prcodfor <> '') AND (:prcodfor IS NOT NULL)) THEN
         vsql = vsql || 'and lan.bdcodfor in ('||:prcodfor||') ';
    
      if (Upper(:prdemlancreembolso) = 'FALSE') then
         begin
            if (:prtiposerdesp = 0) then
               begin
                vsql = vsql || 'and not exists (';
                vsql = vsql || '   select rec.* from VFIN_ESC_TRECFATURASERVICO rec ';
                vsql = vsql || '   inner join VFIN_ESC_TORIGEMSERFAT orig on (orig.bdcodcli = rec.bdcodcli and orig.bdcodesc = rec.bdcodesc and orig.bdchavefatura = rec.bdchavefatura and orig.bdordemser = rec.bdordemser) ';
                vsql = vsql || '   inner join VFIN_ESC_TSERVICOFIXO serfix on (serfix.bdcodcli = orig.bdcodcli and serfix.bdcodesc = orig.bdcodesc and serfix.bdchaveserfix = orig.bdchaveserfix ';
                vsql = vsql || '   and serfix.bdordemserfix = orig.bdordemserfix) ';
                vsql = vsql || '   inner join VFIN_ESC_TVINC_PAG_SERVIC vinc on (vinc.bdcodcli = serfix.bdcodcli and vinc.bdcodesc = serfix.bdcodesc and vinc.bdchaveserfix = serfix.bdchaveserfix and ';
                vsql = vsql || '   vinc.bdordemserfix = serfix.bdordemserfix) ';
                vsql = vsql || '   where rec.bdcodesc = lan.bdcodesc and ';
                vsql = vsql || '   rec.bdcodcli = lan.bdcodcli and ';
                vsql = vsql || '   rec.bdchavefatura = lan.bdchavefatura and ';
                vsql = vsql || '   rec.bdordemser = lan.bdordemser and ';
                vsql = vsql || '   rec.bdordemrecser = lan.bdordemrecser ';
                vsql = vsql || ')';
              end
            else
              begin
                if (Upper(:prdemlancreembolso) = 'FALSE') then
                  begin
                    vsql = vsql || 'and not exists ';
                    vsql = vsql || '(';
                    vsql = vsql || 'select bdcoddesp from vfin_esc_tlancbancario lanaux ';
                    vsql = vsql || 'inner join vfin_esc_tvinc_pag_servic vinc on (vinc.bdcodesc = lanaux.bdcodesc and vinc.BDCHAVECTAPAG = lanaux.bdchavectapag and vinc.bdordemdesp = lanaux.bdordemdesp) ';
                    vsql = vsql || 'and lanaux.bdchavelan = lan.bdchavelan ';
                    vsql = vsql || ') ';
                  end
              end
         end

         if (Upper(:prdemtransfbancarias) = 'FALSE') then
         begin
           vsql = vsql || ' and lan.bdcodtipo <> 3006 ';
         end

      EXECUTE STATEMENT :vsql INTO :BDTOTSERDESPPERIODO;
      SUSPEND;
    end
  else
     begin
       if (:prtiposerdesp = 0) then
         begin
           vsql = 'select lan.bdcodcli as BDCODCLIFOR, coalesce(sum(lan.bdvalorlanc),0) from vfin_esc_tlancbancario lan ';
           vsql = vsql || 'where lan.bdcodobrser = '||:prcodserdesp||' ';

           IF ((:prcodesc <> '') AND (:prcodesc IS NOT NULL)) THEN
              vsql = vsql || 'and lan.bdcodesc in ('||:prcodesc||') ';
        
           IF ((:prchavectaban <> '') AND (:prchavectaban IS NOT NULL)) THEN
              vsql = vsql || 'and lan.bdchavectaban in ('||:prchavectaban||') ';

           vsql = vsql || 'and lan.bdtiposervdesp = 0 ';

           IF ((:prdatainicial <> '') AND (:prdatainicial IS NOT NULL)) THEN
              vsql = vsql || 'and lan.bddatalan >='||''''||:prdatainicial||''''||' ';
        
           IF ((:prdatafinal <> '') AND (:prdatafinal IS NOT NULL)) THEN
             vsql = vsql || 'and lan.bddatalan <= '||''''||:prdatafinal||''''||' ';
        
           IF ((:prcodcli <> '') AND (:prcodcli IS NOT NULL)) THEN
             vsql = vsql || 'and lan.bdcodcli in ('||:prcodcli||') ';

           if (Upper(:prdemlancreembolso) = 'FALSE') then
             begin
               vsql = vsql || 'and not exists (';
               vsql = vsql || '   select rec.* from VFIN_ESC_TRECFATURASERVICO rec ';
               vsql = vsql || '   inner join VFIN_ESC_TORIGEMSERFAT orig on (orig.bdcodcli = rec.bdcodcli and orig.bdcodesc = rec.bdcodesc and orig.bdchavefatura = rec.bdchavefatura and orig.bdordemser = rec.bdordemser) ';
               vsql = vsql || '   inner join VFIN_ESC_TSERVICOFIXO serfix on (serfix.bdcodcli = orig.bdcodcli and serfix.bdcodesc = orig.bdcodesc and serfix.bdchaveserfix = orig.bdchaveserfix ';
               vsql = vsql || '   and serfix.bdordemserfix = orig.bdordemserfix) ';
               vsql = vsql || '   inner join VFIN_ESC_TVINC_PAG_SERVIC vinc on (vinc.bdcodcli = serfix.bdcodcli and vinc.bdcodesc = serfix.bdcodesc and vinc.bdchaveserfix = serfix.bdchaveserfix and ';
               vsql = vsql || '   vinc.bdordemserfix = serfix.bdordemserfix) ';
               vsql = vsql || '   where rec.bdcodesc = lan.bdcodesc and ';
               vsql = vsql || '   rec.bdcodcli = lan.bdcodcli and ';
               vsql = vsql || '   rec.bdchavefatura = lan.bdchavefatura and ';
               vsql = vsql || '   rec.bdordemser = lan.bdordemser and ';
               vsql = vsql || '   rec.bdordemrecser = lan.bdordemrecser ';
               vsql = vsql || ')';
              end

           if (Upper(:prdemtransfbancarias) = 'FALSE') then
             begin
               vsql = vsql || ' and lan.bdcodtipo <> 3006 ';
             end

           vsql = vsql || 'group by BDCODCLIFOR ';
         end
       else
         begin
           vsql = 'select lan.bdcodfor as BDCODCLIFOR, coalesce(sum(lan.bdvalorlanc),0) from vfin_esc_tlancbancario lan ';
           vsql = vsql || 'where lan.bdcoddesp = '||:prcodserdesp||' ';

           IF ((:prcodesc <> '') AND (:prcodesc IS NOT NULL)) THEN
              vsql = vsql || 'and lan.bdcodesc in ('||:prcodesc||') ';
        
           IF ((:prchavectaban <> '') AND (:prchavectaban IS NOT NULL)) THEN
              vsql = vsql || 'and lan.bdchavectaban in ('||:prchavectaban||') ';

           vsql = vsql || 'and lan.bdtiposervdesp = 1 ';

           IF ((:prdatainicial <> '') AND (:prdatainicial IS NOT NULL)) THEN
              vsql = vsql || 'and lan.bddatalan >='||''''||:prdatainicial||''''||' ';
        
           IF ((:prdatafinal <> '') AND (:prdatafinal IS NOT NULL)) THEN
             vsql = vsql || 'and lan.bddatalan <= '||''''||:prdatafinal||''''||' ';

           IF ((:prcodfor <> '') AND (:prcodfor IS NOT NULL)) THEN
             vsql = vsql || 'and lan.bdcodfor in ('||:prcodfor||') ';

           if (Upper(:prdemlancreembolso) = 'FALSE') then
              begin
                vsql = vsql || 'and not exists ';
                vsql = vsql || '(';
                vsql = vsql || 'select bdcoddesp from vfin_esc_tlancbancario lanaux ';
                vsql = vsql || 'inner join vfin_esc_tvinc_pag_servic vinc on (vinc.bdcodesc = lanaux.bdcodesc and vinc.BDCHAVECTAPAG = lanaux.bdchavectapag and vinc.bdordemdesp = lanaux.bdordemdesp) ';
                vsql = vsql || 'and lanaux.bdchavelan = lan.bdchavelan ';
                vsql = vsql || ') ';
              end

           if (Upper(:prdemtransfbancarias) = 'FALSE') then
              begin
                vsql = vsql || ' and lan.bdcodtipo <> 3006 ';
              end

           vsql = vsql || 'group by BDCODCLIFOR ';
         end


      VSQLTOTALPERIODO = '';
      vCodCliFor = 0;
      vTotalPeriodoSel = 0;
      FOR
      EXECUTE STATEMENT :vSql
      INTO
      :vCodCliFor,
      :vTotalPeriodoSel
      DO
      begin
        if (vCodCliFor is not null) then
           begin
            if (:prdesconto =  'TRUE') then
                vTotalPeriodoSel = - vTotalPeriodoSel;
    
             vtotalgeral = vTotalPeriodoSel;
             if (:prnumperatu <> 1) then
                begin
                  VSQLTOTALPERIODO = 'select (coalesce(BDVLRTOTPERIODO, 0) + '||:vTotalPeriodoSel||') from TMP_DEMRECDESP_ANALITICAS ';
                  VSQLTOTALPERIODO = VSQLTOTALPERIODO||'where BDCODOBRSER = '||:PRCODSERDESP||' and BDCODCLIFOR = '||vCodCliFor;
                  EXECUTE STATEMENT :VSQLTOTALPERIODO INTO :vtotalgeral;
                end
    
    
                if (:prnumperatu = 1) then
                    begin
                      update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO01, BDVLRPERIODO01, BDVLRTOTPERIODO)
                      VALUES (:PRCODSERDESP, :vCodCliFor, :prclassserdesp, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
                    end
                 else
                 if (:prnumperatu = 2) then
                    begin
                      update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO02, BDVLRPERIODO02, BDVLRTOTPERIODO)
                      VALUES (:PRCODSERDESP, :vCodCliFor, :prclassserdesp, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
                    end
                 else
                 if (:prnumperatu = 3) then
                    begin
                      update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO03, BDVLRPERIODO03, BDVLRTOTPERIODO)
                      VALUES (:PRCODSERDESP, :vCodCliFor, :prclassserdesp, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
                    end
                 else
                 if (:prnumperatu = 4) then
                    begin
                      update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO04, BDVLRPERIODO04, BDVLRTOTPERIODO)
                      VALUES (:PRCODSERDESP, :vCodCliFor, :prclassserdesp, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
                    end
                 else
                 if (:prnumperatu = 5) then
                    begin
                      update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO05, BDVLRPERIODO05, BDVLRTOTPERIODO)
                      VALUES (:PRCODSERDESP, :vCodCliFor, :prclassserdesp, 1,:PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
                    end
                 else
                 if (:prnumperatu = 6) then
                    begin
                      update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO06, BDVLRPERIODO06, BDVLRTOTPERIODO)
                      VALUES (:PRCODSERDESP, :vCodCliFor, :prclassserdesp, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
                    end
                 else
                 if (:prnumperatu = 7) then
                    begin
                      update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO07, BDVLRPERIODO07, BDVLRTOTPERIODO)
                      VALUES (:PRCODSERDESP, :vCodCliFor, :prclassserdesp, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
                    end
                 else
                 if (:prnumperatu = 8) then
                    begin
                      update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO08, BDVLRPERIODO08, BDVLRTOTPERIODO)
                      VALUES (:PRCODSERDESP, :vCodCliFor, :prclassserdesp, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
                    end
                 else
                 if (:prnumperatu = 9) then
                    begin
                      update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO09, BDVLRPERIODO09, BDVLRTOTPERIODO)
                      VALUES (:PRCODSERDESP, :vCodCliFor, :prclassserdesp, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
                    end
                 else
                 if (:prnumperatu = 10) then
                    begin
                      update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO10, BDVLRPERIODO10, BDVLRTOTPERIODO)
                      VALUES (:PRCODSERDESP, :vCodCliFor, :prclassserdesp, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
                    end
                 else
                 if (:prnumperatu = 11) then
                    begin
                      update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO11, BDVLRPERIODO11, BDVLRTOTPERIODO)
                      VALUES (:PRCODSERDESP, :vCodCliFor, :prclassserdesp, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
                    end
                 else
                 if (:prnumperatu = 12) then
                    begin
                      update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO12, BDVLRPERIODO12, BDVLRTOTPERIODO)
                      VALUES (:PRCODSERDESP, :vCodCliFor, :prclassserdesp, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
                    end
           end
      end
    suspend;
  end
END^

SET TERM ; ^


SET TERM ^ ;

create or alter procedure SP_TOTSERPREVPERIODO (
    PRREFINI varchar(6),
    PRREFFIM varchar(6),
    PRCODSER integer,
    PRCLASSIFICACAO varchar(60),
    PRDESCONTO varchar(5),
    PRNUMPERATU integer,
    PRDESCPERIODO varchar(12),
    PRMODELO integer,
    PRFLAGPROC integer)
as
declare variable VSQL varchar(1000);
declare variable VSQLTOTALPERIODO varchar(500);
declare variable VCODCLI integer;
declare variable VTOTALPERIODOSEL numeric(15,2);
declare variable VTOTALGERAL numeric(15,2);
BEGIN
  if (:prmodelo = 0) then
     begin
       vsql = 'select 0 as bdcodcli, coalesce(sum(serfat.bdvlrtotser),0) from TMP_VFIN_ESC_TSERVICOFATURADO serfat ';
       vsql = vsql || 'inner join tmp_vfin_esc_tfatura fat on (fat.bdcodcli = serfat.bdcodcli and fat.bdcodesc = serfat.bdcodesc and fat.bdchavefatura = serfat.bdchavefatura and fat.bdflagproc = '||PRFLAGPROC||' ) ';

       vsql = vsql || 'where serfat.bdflagproc = '||PRFLAGPROC||' and serfat.bdcodobrser = '||:prcodser||' ';

       IF ((:prRefIni > 0) AND (:prRefIni IS NOT NULL)) THEN
           vsql = vsql || 'and fat.bdreffat >= '||:PRREFINI;
    
       IF ((:prRefFim > 0) AND (:prRefFim IS NOT NULL)) THEN
           vsql = vsql || 'and fat.bdreffat <= '||:PRREFFIM;
     end
  else
    begin
      -- agrupar clientes que estão na tabela temporária para o serviço e período
      vsql = 'select serfat.bdcodcli, coalesce(sum(serfat.bdvlrtotser),0) from TMP_VFIN_ESC_TSERVICOFATURADO serfat ';
      vsql = vsql || 'inner join tmp_vfin_esc_tfatura fat on (fat.bdcodcli = serfat.bdcodcli and fat.bdcodesc = serfat.bdcodesc and fat.bdchavefatura = serfat.bdchavefatura and fat.bdflagproc = '||PRFLAGPROC||' ) ';
    
      vsql = vsql || 'where serfat.bdflagproc = '||PRFLAGPROC||' and serfat.bdcodobrser = '||:prcodser||' ';
    
      IF ((:prRefIni > 0) AND (:prRefIni IS NOT NULL)) THEN
          vsql = vsql || 'and fat.bdreffat >= '||:PRREFINI;
    
      IF ((:prRefFim > 0) AND (:prRefFim IS NOT NULL)) THEN
          vsql = vsql || 'and fat.bdreffat <= '||:PRREFFIM;
      vsql = vsql || 'group by BDCODCLI ';
    end

  VSQLTOTALPERIODO = '';
  vCodCli = 0;
  vTotalPeriodoSel = 0;

  FOR
  EXECUTE STATEMENT :vSql
  INTO
  :vCodCli,
  :vTotalPeriodoSel
  DO
  begin
     if (:prdesconto =  'TRUE') then
        vTotalPeriodoSel = - vTotalPeriodoSel;
     vtotalgeral = vTotalPeriodoSel;

     if (:prnumperatu <> 1) then
        begin
           VSQLTOTALPERIODO = 'select (coalesce(BDVLRTOTPERIODO, 0) + '||:vTotalPeriodoSel||') from TMP_DEMRECDESP_ANALITICAS ';
           VSQLTOTALPERIODO = VSQLTOTALPERIODO||'where BDCODOBRSER = '||:PRCODSER||' and BDCODCLIFOR = '||vCodCli;
           EXECUTE STATEMENT :VSQLTOTALPERIODO INTO :vtotalgeral;
        end

        if (:prnumperatu = 1) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO01, BDVLRPERIODO01, BDVLRTOTPERIODO)
              VALUES (:PRCODSER, :vCodCli, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 2) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO02, BDVLRPERIODO02, BDVLRTOTPERIODO)
              VALUES (:PRCODSER, :vCodCli, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 3) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO03, BDVLRPERIODO03, BDVLRTOTPERIODO)
              VALUES (:PRCODSER, :vCodCli, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 4) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO04, BDVLRPERIODO04, BDVLRTOTPERIODO)
              VALUES (:PRCODSER, :vCodCli, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 5) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO05, BDVLRPERIODO05, BDVLRTOTPERIODO)
              VALUES (:PRCODSER, :vCodCli, :prclassificacao, 1,:PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 6) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO06, BDVLRPERIODO06, BDVLRTOTPERIODO)
              VALUES (:PRCODSER, :vCodCli, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 7) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO07, BDVLRPERIODO07, BDVLRTOTPERIODO)
              VALUES (:PRCODSER, :vCodCli, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 8) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO08, BDVLRPERIODO08, BDVLRTOTPERIODO)
              VALUES (:PRCODSER, :vCodCli, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 9) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO09, BDVLRPERIODO09, BDVLRTOTPERIODO)
              VALUES (:PRCODSER, :vCodCli, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 10) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO10, BDVLRPERIODO10, BDVLRTOTPERIODO)
              VALUES (:PRCODSER, :vCodCli, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 11) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO11, BDVLRPERIODO11, BDVLRTOTPERIODO)
              VALUES (:PRCODSER, :vCodCli, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 12) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO12, BDVLRPERIODO12, BDVLRTOTPERIODO)
              VALUES (:PRCODSER, :vCodCli, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
      end
  --suspend;
END^

SET TERM ; ^



SET TERM ^ ;

CREATE OR ALTER procedure SP_TOTDESPPREVPERIODO (
    PRCODESC varchar(500),
    PRREFINI varchar(6),
    PRREFFIM varchar(6),
    PRCHAVECTABAN varchar(500),
    PRCODDESP integer,
    PRCODFOR varchar(10240),
    PRCLASSIFICACAO varchar(60),
    PRDESCONTO varchar(5),
    PRNUMPERATU integer,
    PRDESCPERIODO varchar(12),
    PRMODELO integer)
as
declare variable VSQL varchar(1000);
declare variable VSQLTOTALPERIODO varchar(500);
declare variable VCODFOR integer;
declare variable VTOTALPERIODOSEL numeric(15,2);
declare variable VTOTALGERAL numeric(15,2);
BEGIN
  if (:prmodelo = 0) then
     begin
       vsql = 'select 0 as bdcodfor, coalesce(sum(cp.bdvalortotaldesp), 0) ';
       vsql = vsql || 'from vfin_esc_tcontaspagardesp cpd ';
       vsql = vsql || 'left outer join vfin_esc_tcontasapagar cp on (cp.bdcodesc = cpd.bdcodesc and cp.bdchavectapag = cpd.bdchavectapag) ';
       vsql = vsql || 'left outer join VFIN_ESC_TPARCELAPAGAR par on (par.bdcodesc = cpd.bdcodesc and par.bdchavectapag = cpd.bdchavectapag) ';
       vsql = vsql || 'left outer join VFIN_ESC_TPAGAMENTOS pag on (pag.bdcodesc = cpd.bdcodesc and pag.bdchavectapag = cpd.bdchavectapag) ';
       vsql = vsql || 'where cpd.bdcoddesp = '||:prcoddesp||' ';
    
       IF ((:prcodesc <> '') AND (:prcodesc IS NOT NULL)) THEN
          vsql = vsql || 'and cp.bdcodesc in ('||:prcodesc||') ';
    
       IF ((:prchavectaban <> '') AND (:prchavectaban IS NOT NULL)) THEN
          vsql = vsql || 'and cp.bdchavectaban in ('||:prchavectaban||') ';
    
       IF ((:prRefIni > 0) AND (:prRefIni IS NOT NULL)) THEN
           vsql = vsql || 'and ((select bdreferencia from INC_REFERENCIA(cp.bdreferencia, coalesce(par.bdordempar,1)-1)) >=  '||:PRREFINI || ') ';
    
       IF ((:prRefFim > 0) AND (:prRefFim IS NOT NULL)) THEN
           vsql = vsql || 'and ((select bdreferencia from INC_REFERENCIA(cp.bdreferencia, coalesce(par.bdordempar,1)-1)) <=  '||:PRREFFIM || ') ';
     end
  else
    begin
      -- agrupar fornecedores que estão no contas a pagar para a despesa e período
      vsql = 'select cp.bdcodfor, coalesce(sum(cp.bdvalortotaldesp), 0) ';
      vsql = vsql || 'from vfin_esc_tcontaspagardesp cpd ';
      vsql = vsql || 'left outer join vfin_esc_tcontasapagar cp on (cp.bdcodesc = cpd.bdcodesc and cp.bdchavectapag = cpd.bdchavectapag) ';
      vsql = vsql || 'left outer join VFIN_ESC_TPARCELAPAGAR par on (par.bdcodesc = cpd.bdcodesc and par.bdchavectapag = cpd.bdchavectapag) ';
      vsql = vsql || 'left outer join VFIN_ESC_TPAGAMENTOS pag on (pag.bdcodesc = cpd.bdcodesc and pag.bdchavectapag = cpd.bdchavectapag) ';
      vsql = vsql || 'where cpd.bdcoddesp = '||:prcoddesp||' ';
    
      IF ((:prcodesc <> '') AND (:prcodesc IS NOT NULL)) THEN
         vsql = vsql || 'and cp.bdcodesc in ('||:prcodesc||') ';
    
      IF ((:prchavectaban <> '') AND (:prchavectaban IS NOT NULL)) THEN
         vsql = vsql || 'and cp.bdchavectaban in ('||:prchavectaban||') ';

      IF ((:prRefIni > 0) AND (:prRefIni IS NOT NULL)) THEN
          vsql = vsql || 'and ((select bdreferencia from INC_REFERENCIA(cp.bdreferencia, coalesce(par.bdordempar,1)-1)) >=  '||:PRREFINI || ') ';
    
      IF ((:prRefFim > 0) AND (:prRefFim IS NOT NULL)) THEN
          vsql = vsql || 'and ((select bdreferencia from INC_REFERENCIA(cp.bdreferencia, coalesce(par.bdordempar,1)-1)) <=  '||:PRREFFIM || ') ';
    
      IF ((:prcodfor <> '') AND (:prcodfor IS NOT NULL)) THEN
         vsql = vsql || 'and cp.bdcodfor in ('||:prcodfor||') ';
    
      vsql = vsql || 'group by BDCODFOR';
    end

  VSQLTOTALPERIODO = '';
  vCodFor = 0;
  vTotalPeriodoSel = 0;

  FOR
  EXECUTE STATEMENT :vSql
  INTO
  :vCodFor,
  :vTotalPeriodoSel
  DO
  begin
     if (:prdesconto =  'TRUE') then
        vTotalPeriodoSel = - vTotalPeriodoSel;
     vtotalgeral = vTotalPeriodoSel;

     if (:prnumperatu <> 1) then
        begin
           VSQLTOTALPERIODO = 'select (coalesce(BDVLRTOTPERIODO, 0) + '||:vTotalPeriodoSel||') from TMP_DEMRECDESP_ANALITICAS ';
           VSQLTOTALPERIODO = VSQLTOTALPERIODO||'where BDCODOBRSER = '||:prcoddesp||' and BDCODCLIFOR = '||vCodFor;
           EXECUTE STATEMENT :VSQLTOTALPERIODO INTO :vtotalgeral;
        end

        if (:prnumperatu = 1) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO01, BDVLRPERIODO01, BDVLRTOTPERIODO)
              VALUES (:PRCODDESP, :vCodFor, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 2) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO02, BDVLRPERIODO02, BDVLRTOTPERIODO)
              VALUES (:PRCODDESP, :vCodFor, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 3) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO03, BDVLRPERIODO03, BDVLRTOTPERIODO)
              VALUES (:PRCODDESP, :vCodFor, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 4) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO04, BDVLRPERIODO04, BDVLRTOTPERIODO)
              VALUES (:PRCODDESP, :vCodFor, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 5) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO05, BDVLRPERIODO05, BDVLRTOTPERIODO)
              VALUES (:PRCODDESP, :vCodFor, :prclassificacao, 1,:PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 6) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO06, BDVLRPERIODO06, BDVLRTOTPERIODO)
              VALUES (:PRCODDESP, :vCodFor, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 7) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO07, BDVLRPERIODO07, BDVLRTOTPERIODO)
              VALUES (:PRCODDESP, :vCodFor, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 8) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO08, BDVLRPERIODO08, BDVLRTOTPERIODO)
              VALUES (:PRCODDESP, :vCodFor, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 9) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO09, BDVLRPERIODO09, BDVLRTOTPERIODO)
              VALUES (:PRCODDESP, :vCodFor, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 10) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO10, BDVLRPERIODO10, BDVLRTOTPERIODO)
              VALUES (:PRCODDESP, :vCodFor, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 11) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO11, BDVLRPERIODO11, BDVLRTOTPERIODO)
              VALUES (:PRCODDESP, :vCodFor, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
         else
         if (:prnumperatu = 12) then
            begin
              update or insert INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, BDCODCLIFOR, BDCLASSIFICACAO, BDTIPO, BDPERIODO12, BDVLRPERIODO12, BDVLRTOTPERIODO)
              VALUES (:PRCODDESP, :vCodFor, :prclassificacao, 1, :PRDESCPERIODO, :vTotalPeriodoSel, :vtotalgeral) matching (BDCODOBRSER, BDCODCLIFOR);
            end
      end
  --suspend;
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER procedure SP_REF_TO_PERIODO (
    PRREF integer,
    PRTIPO char(3))
returns (
    BDPERIODO integer)
as
declare variable WANO integer;
declare variable WMES integer;
declare variable WBIM integer;
declare variable WTRI integer;
declare variable WSEM integer;
begin
  wAno = SUBSTRING(:PRREF FROM 1 FOR 4);
  wMes = SUBSTRING(:PRREF FROM 5 FOR 2);
  PRTIPO = UPPER(:PRTIPO);

  IF (:PRTIPO = 'BIM') THEN
    BEGIN
      wBim = CASE WHEN :wMes IN(1, 2) THEN 1
                  WHEN :wMes IN(3, 4) THEN 2
                  WHEN :wMes IN(5, 6) THEN 3
                  WHEN :wMes IN(7, 8) THEN 4
                  WHEN :wMes IN(9, 10) THEN 5
                  WHEN :wMes IN(11, 12) THEN 6
               ELSE
                 0
             END;

      BDPERIODO = :wAno || LPAD(:wBim, 2, '0');
    END
  ELSE
    IF (:PRTIPO = 'TRI') THEN
       BEGIN
         wTri = CASE WHEN :wMes IN(1, 2, 3) THEN 1
                     WHEN :wMes IN(4, 5, 6) THEN 2
                     WHEN :wMes IN(7, 8, 9) THEN 3
                     WHEN :wMes IN(10, 11, 12) THEN 4
                  ELSE
                    0
                END;
    
         BDPERIODO = :wAno || LPAD(:wTri, 2, '0');
       END
    ELSE
      IF (:PRTIPO = 'SEM') THEN
         BEGIN
           wSem = CASE WHEN :wMes IN(1, 2, 3, 4, 5, 6) THEN 1
                       WHEN :wMes IN(7, 8, 9, 10, 11, 12) THEN 2
                    ELSE
                      0
                  END;
        
           BDPERIODO = :wAno || LPAD(:wSem, 2, '0');
         END
  SUSPEND;
end^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER procedure SP_RELDEMRECDESP (
    PRCODESC varchar(500),
    PRTIPODEM integer,
    PRDATAINICIAL varchar(10),
    PRDATAFINAL varchar(10),
    PRCHAVECTABAN varchar(500),
    PRCODOBRSER varchar(10240),
    PRCODDESP varchar(10240),
    PRNIVEL integer,
    PRTIPORECDESP integer,
    PRDEMLANCREEMBOLSO DM_BOOLEAN,
    PRDEMTRANSFBANCARIAS DM_BOOLEAN,
    PRCODCLI varchar(10240),
    PRCODFOR varchar(10240),
    PRMODELO integer)
as
declare variable VULTDIAMES integer;
declare variable VPERIODOFINAL varchar(10);
declare variable VPERIODOINICIAL varchar(10);
declare variable VPOSICAOPONTO integer;
declare variable VSQLSERDESP varchar(10240);
declare variable VSQL varchar(10240);
declare variable VSTOP varchar(5);
declare variable VCLASSAUX varchar(60);
declare variable VCODSERDESPAUX integer;
declare variable VGUARDASERDESP varchar(10240);
declare variable VTIPOSERDESP integer;
declare variable VDESCSERDESP varchar(100);
declare variable VCLASSSERDESP varchar(60);
declare variable VCODSERDESP integer;
declare variable VNUMPERIODO integer;
declare variable VPERIODO01 varchar(12);
declare variable VVLRPERIODO01 numeric(15,2);
declare variable VPERIODO02 varchar(12);
declare variable VVLRPERIODO02 numeric(15,2);
declare variable VPERIODO03 varchar(12);
declare variable VVLRPERIODO03 numeric(15,2);
declare variable VPERIODO04 varchar(12);
declare variable VVLRPERIODO04 numeric(15,2);
declare variable VPERIODO05 varchar(12);
declare variable VVLRPERIODO05 numeric(15,2);
declare variable VPERIODO06 varchar(12);
declare variable VVLRPERIODO06 numeric(15,2);
declare variable VPERIODO07 varchar(12);
declare variable VVLRPERIODO07 numeric(15,2);
declare variable VPERIODO08 varchar(12);
declare variable VVLRPERIODO08 numeric(15,2);
declare variable VPERIODO09 varchar(12);
declare variable VVLRPERIODO09 numeric(15,2);
declare variable VPERIODO10 varchar(12);
declare variable VVLRPERIODO10 numeric(15,2);
declare variable VPERIODO11 varchar(12);
declare variable VVLRPERIODO11 numeric(15,2);
declare variable VPERIODO12 varchar(12);
declare variable VVLRPERIODO12 numeric(15,2);
declare variable VVLRTOTPERIODO numeric(15,2);
declare variable VDESCONTO varchar(5);
declare variable VSQLCLIFOR varchar(20000);
declare variable VCODCLIFORATUAL integer;
declare variable VCOUNT integer;
begin
  vguardaserdesp = '';
  vclassaux = '';
  vcodserdespaux = 0;
  vsql = '';
  vsqlserdesp = '';
  vultdiames = 0;
  vnumperiodo = 0;
  vperiodoinicial = '';
  vperiodofinal = '';

  vperiodo01 = '';
  vvlrperiodo01 = 0;
  vperiodo02 = '';
  vvlrperiodo02 = 0;
  vperiodo03 = '';
  vvlrperiodo03 = 0;
  vperiodo04 = '';
  vvlrperiodo04 = 0;
  vperiodo05 = '';
  vvlrperiodo05 = 0;
  vperiodo06 = '';
  vvlrperiodo06 = 0;
  vperiodo07 = '';
  vvlrperiodo07 = 0;
  vperiodo08 = '';
  vvlrperiodo08 = 0;
  vperiodo09 = '';
  vvlrperiodo09 = 0;
  vperiodo10 = '';
  vvlrperiodo10 = 0;
  vperiodo11 = '';
  vvlrperiodo11 = 0;
  vperiodo12 = '';
  vvlrperiodo12 = 0;
  vSQLCliFor = '';
  vCodCliForAtual = 0;
  vCount = 0;

  DELETE FROM TMP_DEMRECDESP_ANALITICAS;

  IF (prtiporecdesp = 0) THEN -- Serviços
     BEGIN
       /* Antes de tudo, obter os serviços selecionados de acordo com as opções "títulos" e "analíticas".
       prnivel = 0: apenas a opção "títulos" está checada.
       prnivel = 1: apenas a opção "analíticas" está checada.
       prnivel = 2: ambas opções estão checadas. */

       -- montagem da lista de clientes para quebra
       if (prModelo = 0) then
          -- somente para trazer um registro com cliente 0 para não ficar controlando se executa o laço de clientes ou não conforme o modelo
          vSqlCliFor = 'select 0 as bdcodcli, count(bdcodcli) bdcount from vfin_base_tcliente ';
       else
          begin
             vSqlCliFor = 'select cli.bdcodcli, 0 as bdcount from vfin_base_tcliente cli ';
             vSqlCliFor = vSqlCliFor || 'where exists ';
             vSqlCliFor = vSqlCliFor || ' (';
             vSqlCliFor = vSqlCliFor || '    select bdcodcli from vfin_esc_tlancbancario lan ';
             vSqlCliFor = vSqlCliFor || '    where (lan.bdcodcli = cli.bdcodcli) ';
             vSqlCliFor = vSqlCliFor || '    and lan.bdtiposervdesp = 0 ';
             vSqlCliFor = vSqlCliFor || '    and lan.bdvalorlanc > 0 ';
        
             IF ((:prcodesc <> '') AND (:prcodesc IS NOT NULL)) THEN
                vSqlCliFor = vSqlCliFor || 'and lan.bdcodesc in ('||:prcodesc||') ';
        
             IF ((:prchavectaban <> '') AND (:prchavectaban IS NOT NULL)) THEN
                vSqlCliFor = vSqlCliFor || 'and lan.bdchavectaban in ('||:prchavectaban||') ';

             IF ((:prdatainicial <> '') AND (:prdatainicial IS NOT NULL)) THEN
                vSqlCliFor = vSqlCliFor || 'and lan.bddatalan >='||''''||:prdatainicial||''''||' ';

             IF ((:prdatafinal <> '') AND (:prdatafinal IS NOT NULL)) THEN
                vSqlCliFor = vSqlCliFor || 'and lan.bddatalan <= '||''''||:prdatafinal||''''||' ';

             if (Upper(:prdemtransfbancarias) = 'FALSE') then
                vSqlCliFor = vSqlCliFor || ' and lan.bdcodtipo <> 3006 ';

             vSqlCliFor = vSqlCliFor || ' )';

             IF ((:prcodcli <> '') AND (:prcodcli IS NOT NULL)) THEN
               vSqlCliFor = vSqlCliFor || 'and cli.bdcodcli in ('||:prcodcli||') ';
          end

       IF (prnivel = 0) THEN
          BEGIN
            vsqlserdesp = 'select s.bdcodobrser, s.bdclassificacao, s.bddescricao, s.bdtipo ';
            vsqlserdesp = vsqlserdesp || 'from (';
            vsqlserdesp = vsqlserdesp || '       select bdcodobrser, bdclassificacao, bddescricao, bdtipo ';
            vsqlserdesp = vsqlserdesp || '       from vct_base_servico ';

            IF (:prcodobrser <> '') THEN
                vsqlserdesp = vsqlserdesp || 'where bdcodobrser in ('||:prcodobrser||') ';

            vsqlserdesp = vsqlserdesp || '      ) ser ';
            vsqlserdesp = vsqlserdesp || 'left outer join vct_base_servico s on(s.bdclassificacao like (ser.bdclassificacao)||''%'') ';

            /* Se prnivel = 0 então apenas a opção "título" está selecionada. Neste caso
            iremos trazer também as analíticas para que seja feito o cálculo dos períodos.
            Posteriormente apenas exibimos as títulos no relatório. */

            vsqlserdesp = vsqlserdesp || 'group by bdcodobrser, bdclassificacao, bddescricao, bdtipo ';
            vsqlserdesp = vsqlserdesp || 'order by bdclassificacao ';
          END
       ELSE
         IF (prnivel = 1) THEN
            BEGIN
              /* Se apenas a opção "analíticas" está selecionada, então basta
              trazer as próprias analíticas selecionadas. */
              vsqlserdesp = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bdtipo ';
              vsqlserdesp = vsqlserdesp || 'from vct_base_servico ser ';
              vsqlserdesp = vsqlserdesp || 'where ser.bdtipo = 1';
      
              IF (:prcodobrser <> '') THEN
                 vsqlserdesp = vsqlserdesp || 'and ser.bdcodobrser in ('||:prcodobrser||') ';

              vsqlserdesp = vsqlserdesp || 'order by bdclassificacao ';
            END
         ELSE -- Então possui títulos e analíticas selecionadas
           IF (prnivel = 2) THEN
              BEGIN
                if (prcodobrser = '') then
                   begin
                     vguardaserdesp = '';
                     vsqlserdesp = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bdtipo ';
                     vsqlserdesp = vsqlserdesp || 'from vct_base_servico ser ';
                     vsqlserdesp = vsqlserdesp || 'order by bdclassificacao';
                   end
                else
                   begin
                    /* Se títulos e analíticas foram selecionadas, deverá trazer as analíticas das títulos
                    que estão selecionadas e também deverá trazer as títulos das analíticas que foram selecionadas.*/
        
                    -- Primeiramente pegar as títulos que foram selecionadas
                    vsql = 'select list(ser.bdcodobrser) from vct_base_servico ser ';
                    vsql = vsql || 'where ser.bdtipo = 0 ';
    
                    IF (:prcodobrser <> '') THEN
                       vsql = vsql || 'and ser.bdcodobrser in ('||:prcodobrser||') ';
                    EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
        
                    IF (vguardaserdesp IS NOT NULL) THEN
                       BEGIN
                         -- Em seguida, obter as analíticas destas títulos e guardar em vguardaservicos.
                         vsql = 'select s.bdcodobrser, s.bdclassificacao ';
                         vsql = vsql || 'from (';
                         vsql = vsql || '       select bdcodobrser, bdclassificacao, bddescricao ';
                         vsql = vsql || '       from vct_base_servico ';
                         vsql = vsql || '       where bdcodobrser in('||:vguardaserdesp||') ';
                         vsql = vsql || '      ) ser ';
                         vsql = vsql || 'left outer join vct_base_servico s on(s.bdclassificacao like (ser.bdclassificacao)||''%'')';

                         IF (:prcodobrser <> '') THEN
                             vsql = vsql || 'and s.bdcodobrser in ('||:prcodobrser||') ';
                         vguardaserdesp = '';
        
                         FOR
                         EXECUTE STATEMENT :vsql
                         INTO
                         :vcodserdesp,
                         :vclassserdesp
                         DO
                         BEGIN
                           vguardaserdesp = :vguardaserdesp||:vcodserdesp||',';
                         END
                       END
                    ELSE
                      vguardaserdesp = '';
    
    
                    -- Obtendo somente as analíticas selecionadas
                    vsql = 'select ser.bdcodobrser, ser.bdclassificacao ';
                    vsql = vsql || 'from (';
                    vsql = vsql || 'select bdcodobrser, bdclassificacao ';
                    vsql = vsql || 'from vct_base_servico ';
                    vsql = vsql || 'where bdtipo = 1 ';
    
                    IF (:prcodobrser <> '') THEN
                    vsql = vsql || 'and bdcodobrser in ('||:prcodobrser||') ';
    
                    vsql = vsql || ') ser ';
              
                    FOR
                    EXECUTE STATEMENT :vsql
                    INTO
                    :vcodserdesp,
                    :vclassserdesp
                    DO
                    BEGIN
                      vstop = 'FALSE';
                      vguardaserdesp = :vguardaserdesp||:vcodserdesp||',';
                      vclassaux = :vclassserdesp;
          
                      /* A implementação abaixo vai removendo sempre o último nível da classificação
                      para obter todas as títulos que compoem a analítica, e vai guardando o código
                      de cada título na variável vguardaserdesp. */
                      WHILE (UPPER(:vstop) = 'FALSE') DO
                        BEGIN
                          SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto;
    
                          IF (vposicaoponto > 0) THEN
                             BEGIN
                               SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo a classificação
                               SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto; -- Localizando o primeiro ponto (sem a inversão seria o último ponto)
                               SELECT SUBSTRING(:vclassaux FROM :vposicaoponto +1 FOR CHAR_LENGTH(:vclassaux)) FROM rdb$database INTO :vclassaux; -- Selecionando o que vem depois do primeiro ponto
                               SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo novamente

                               SELECT COALESCE(bdcodobrser,0) FROM vct_base_servico WHERE bdclassificacao = :vclassaux INTO :vcodserdespaux;
    
                               IF ((vcodserdespaux > 0) and (position(vcodserdespaux, vguardaserdesp) = 0)) THEN
                                  vguardaserdesp = :vguardaserdesp||:vcodserdespaux||',';
                             END
                          ELSE
                            BEGIN
                              vstop = 'TRUE';
                            END
                        END
                    END
                    vguardaserdesp = SUBSTRING(:vguardaserdesp FROM 1 FOR (CHAR_LENGTH(:vguardaserdesp) -1));
        
                    -- Por fim, junta todos os serviços relacionados em um sql.
                    vsqlserdesp = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bdtipo ';
                    vsqlserdesp = vsqlserdesp || 'from vct_base_servico ser ';
                    vsqlserdesp = vsqlserdesp || 'where ser.bdcodobrser in ('||:vguardaserdesp||') ';
                    vsqlserdesp = vsqlserdesp || 'order by bdclassificacao';
                 end
              END


       -- Depois de ter obtido todos os serviços, trazer apenas os que possuem relação com os lançamentos financeiros.

       if (:vguardaserdesp <> '') then
          begin
             vguardaserdesp = '';
             vsql = 'select list(ser.bdcodobrser) from ('||:vsqlserdesp||') ser where ser.bdtipo = 1';
             EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
          end

       vsql = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bddesconto ';
       vsql = vsql || 'from vct_base_servico ser ';
       vsql = vsql || 'where exists ';
       vsql = vsql || ' (';
       vsql = vsql || '    select bdcodobrser from vfin_esc_tlancbancario lan ';
       vsql = vsql || '    where (lan.bdcodobrser = ser.bdcodobrser) ';
       vsql = vsql || '    and lan.bdtiposervdesp = 0 ';
       vsql = vsql || '    and lan.bdvalorlanc > 0 ';

       IF ((:prcodesc <> '') AND (:prcodesc IS NOT NULL)) THEN
          vsql = vsql || 'and lan.bdcodesc in ('||:prcodesc||') ';

       IF ((:prchavectaban <> '') AND (:prchavectaban IS NOT NULL)) THEN
          vsql = vsql || 'and lan.bdchavectaban in ('||:prchavectaban||') ';

       IF ((:prcodcli <> '') AND (:prcodcli IS NOT NULL)) THEN
          vsql = vsql || 'and lan.bdcodcli in ('||:prcodcli||') ';

       IF ((:prdatainicial <> '') AND (:prdatainicial IS NOT NULL)) THEN
          vsql = vsql || 'and lan.bddatalan >='||''''||:prdatainicial||''''||' ';
    
       IF ((:prdatafinal <> '') AND (:prdatafinal IS NOT NULL)) THEN
         vsql = vsql || 'and lan.bddatalan <= '||''''||:prdatafinal||''''||' ';

       IF (Upper(:prdemtransfbancarias) = 'FALSE') then
         vsql = vsql || ' and lan.bdcodtipo <> 3006 ';

       vsql = vsql || ' )';

       IF (:vguardaserdesp <> '') THEN
          vsql = vsql || 'and ser.bdcodobrser in ('||:vguardaserdesp||') ';

     END
  ELSE
    BEGIN -- Despesas
       -- montagem da lista de fornecedores para quebra
       if (prModelo = 0) then
          -- somente para trazer um registro com fornecedor 0 para não ficar controlando se executa o laço de fornecedores ou não, conforme o modelo
          vSqlCliFor = 'select 0 as bdcodfor, count(bdcodfor) bdcount from vfin_base_tfornecedor ';
       else
          begin
             vSqlCliFor = 'select forn.bdcodfor, 0 as bdcodcount from vfin_base_tfornecedor forn ';
             vSqlCliFor = vSqlCliFor || 'where exists ';
             vSqlCliFor = vSqlCliFor || ' (';
             vSqlCliFor = vSqlCliFor || '    select bdcodfor from vfin_esc_tlancbancario lan ';
             vSqlCliFor = vSqlCliFor || '    where (lan.bdcodfor = forn.bdcodfor) ';
             vSqlCliFor = vSqlCliFor || '    and lan.bdtiposervdesp = 1 ';
             vSqlCliFor = vSqlCliFor || '    and lan.bdvalorlanc > 0 ';
        
             IF ((:prcodesc <> '') AND (:prcodesc IS NOT NULL)) THEN
                vSqlCliFor = vSqlCliFor || 'and lan.bdcodesc in ('||:prcodesc||') ';
        
             IF ((:prchavectaban <> '') AND (:prchavectaban IS NOT NULL)) THEN
                vSqlCliFor = vSqlCliFor || 'and lan.bdchavectaban in ('||:prchavectaban||') ';

             IF ((:prdatainicial <> '') AND (:prdatainicial IS NOT NULL)) THEN
                vSqlCliFor = vSqlCliFor || 'and lan.bddatalan >='||''''||:prdatainicial||''''||' ';

             IF ((:prdatafinal <> '') AND (:prdatafinal IS NOT NULL)) THEN
                vSqlCliFor = vSqlCliFor || 'and lan.bddatalan <= '||''''||:prdatafinal||''''||' ';

             IF (Upper(:prdemtransfbancarias) = 'FALSE') then
                vSqlCliFor = vSqlCliFor || ' and lan.bdcodtipo <> 3006 ';

             vSqlCliFor = vSqlCliFor || ' )';

             IF ((:prcodcli <> '') AND (:prcodcli IS NOT NULL)) THEN
               vSqlCliFor = vSqlCliFor || 'and forn.bdcodfor in ('||:prCodFor||') ';
          end

      IF (prnivel = 0) THEN -- Então só possui títulos selecionadas
         BEGIN
           vsqlserdesp = 'select d.bdcoddesp, d.bdclassdesp, d.bddescdesp, d.bdtipodesp ';
           vsqlserdesp = vsqlserdesp || 'from (';
           vsqlserdesp = vsqlserdesp || '       select bdcoddesp, bdclassdesp, bddescdesp, bdtipodesp ';
           vsqlserdesp = vsqlserdesp || '       from vfin_base_tdespesa ';

           IF (:prcoddesp <> '') THEN
              vsqlserdesp = vsqlserdesp || 'where bdcoddesp in ('||:prcoddesp||') ';

           vsqlserdesp = vsqlserdesp || '      ) desp ';
           vsqlserdesp = vsqlserdesp || 'left outer join vfin_base_tdespesa d on(d.bdclassdesp like (desp.bdclassdesp)||''%'')';

           /* Se prnivel = 0 então apenas a opção "título" está selecionada. Neste caso
           iremos trazer também as analíticas para que seja feito o cálculo dos períodos.
           Posteriormente apenas exibimos as títulos no relatório. */

           vsqlserdesp = vsqlserdesp || 'group by bdcoddesp, bdclassdesp, bddescdesp, bdtipodesp ';
           vsqlserdesp = vsqlserdesp || 'order by bdclassdesp ';
         END
      ELSE
        IF (prnivel = 1) THEN -- Então só possui analíticas selecionadas
           BEGIN
             /* Se apenas a opção "analíticas" está selecionada, então basta
             trazer as próprias analíticas selecionadas. */
             vsqlserdesp = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, desp.bdtipodesp ';
             vsqlserdesp = vsqlserdesp || 'from vfin_base_tdespesa desp ';
             vsqlserdesp = vsqlserdesp || 'where desp.bdtipodesp = 1 ';

             IF (:prcoddesp <> '') THEN
                vsqlserdesp = vsqlserdesp || 'and desp.bdcoddesp in ('||:prcoddesp||') ';

             vsqlserdesp = vsqlserdesp || 'order by bdclassdesp ';
           END
        ELSE -- Então possui títulos e analíticas selecionadas, e obrigatoriamente as duas opções "títulos" e "analíticas" estão checadas.
          IF (prnivel = 2) THEN
             BEGIN

                if (prcoddesp = '') then
                   begin
                     vguardaserdesp = '';
                     vsqlserdesp = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, desp.bdtipodesp ';
                     vsqlserdesp = vsqlserdesp || 'from vfin_base_tdespesa desp ';
                     vsqlserdesp = vsqlserdesp || 'order by bdclassdesp';
                   end
                else
                   begin
                       /* Se títulos e analíticas foram selecionadas, deverá trazer as analíticas das títulos
                       que estão selecionadas e também deverá trazer as títulos das analíticas que foram selecionadas.*/
            
                       -- Primeiramente pegar as títulos que foram selecionadas
                       vsql = 'select list(desp.bdcoddesp) from vfin_base_tdespesa desp ';
                       vsql = vsql || 'where desp.bdtipodesp = 0 ';
        
                       IF (:prcoddesp <> '') THEN
                          vsql = vsql || 'and desp.bdcoddesp in ('||:prcoddesp||')';
        
                       EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
              
                       IF (vguardaserdesp IS NOT NULL) THEN
                          BEGIN
                            -- Em seguida, obter as analíticas destas títulos e guardar em vguardaservicos.
                            vsql = 'select d.bdcoddesp, d.bdclassdesp ';
                            vsql = vsql || 'from (';
                            vsql = vsql || '       select bdcoddesp, bdclassdesp, bddescdesp ';
                            vsql = vsql || '       from vfin_base_tdespesa ';
                            vsql = vsql || '       where bdcoddesp in('||:vguardaserdesp||') ';
                            vsql = vsql || '      ) desp ';
                            vsql = vsql || 'left outer join vfin_base_tdespesa d on(d.bdclassdesp like (desp.bdclassdesp)||''%'')';
                            IF (:prcoddesp <> '') THEN
                               vsql = vsql || 'and d.bdcoddesp in ('||:prcoddesp||')';

                            vguardaserdesp = '';
                         
                            FOR
                            EXECUTE STATEMENT :vsql
                            INTO
                            :vcodserdesp,
                            :vclassserdesp
                            DO
                            BEGIN
                              vguardaserdesp = :vguardaserdesp||:vcodserdesp||',';
                            END
                          END
                       ELSE
                         vguardaserdesp = '';
        
                       -- Obtendo somente as analíticas selecionadas
                       vsql = 'select desp.bdcoddesp, desp.bdclassdesp ';
                       vsql = vsql || 'from (';
                       vsql = vsql || 'select bdcoddesp, bdclassdesp ';
                       vsql = vsql || 'from vfin_base_tdespesa ';
                       vsql = vsql || 'where bdtipodesp = 1';
        
                       IF (:prcoddesp <> '') THEN
                          vsql = vsql || 'and bdcoddesp in ('||:prcoddesp||') ';
        
                       vsql = vsql || ') desp ';
            
                       FOR
                       EXECUTE STATEMENT :vsql
                       INTO
                       :vcodserdesp,
                       :vclassserdesp
                       DO
                       BEGIN
                         vstop = 'FALSE';
                         vguardaserdesp = :vguardaserdesp||:vcodserdesp||',';
                         vclassaux = :vclassserdesp;
                  
                         /* A implementação abaixo vai removendo sempre o último nível da classificação
                         para obter todas as títulos que compoem a analítica, e vai guardando o código
                         de cada título na variável vguardaserdesp. */
                         WHILE (UPPER(:vstop) = 'FALSE') DO
                           BEGIN
                             SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto;
                  
                             IF (vposicaoponto > 0) THEN
                                BEGIN
                                  SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo a classificação
                                  SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto; -- Localizando o primeiro ponto (sem a inversão seria o último ponto)
                                  SELECT SUBSTRING(:vclassaux FROM :vposicaoponto +1 FOR CHAR_LENGTH(:vclassaux)) FROM rdb$database INTO :vclassaux; -- Selecionando o que vem depois do primeiro ponto
                                  SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo novamente
                                  SELECT first 1 COALESCE(bdcoddesp,0) FROM vfin_base_tdespesa WHERE bdclassdesp = :vclassaux INTO :vcodserdespaux;
            
                                  IF ((vcodserdespaux > 0) and (position(vcodserdespaux, vguardaserdesp) = 0)) THEN
                                     vguardaserdesp = :vguardaserdesp||:vcodserdespaux||',';
                                END
                             ELSE
                               BEGIN
                                 vstop = 'TRUE';
                               END
                           END
                       END
        
                       vguardaserdesp = SUBSTRING(:vguardaserdesp FROM 1 FOR (CHAR_LENGTH(:vguardaserdesp) -1));
                
                       -- Por fim, junta todos os serviços relacionados em um sql.
                       vsqlserdesp = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, desp.bdtipodesp ';
                       vsqlserdesp = vsqlserdesp || 'from vfin_base_tdespesa desp ';
                       vsqlserdesp = vsqlserdesp || 'where desp.bdcoddesp in ('||:vguardaserdesp||') ';
                       vsqlserdesp = vsqlserdesp || 'order by bdclassdesp';
                end
             END



      -- Depois de ter obtido todos os serviços, trazer apenas os que possuem relação com os lançamentos financeiros.
      if (vguardaserdesp <> '') then
         begin
            vguardaserdesp = '';
            vsql = 'select list(desp.bdcoddesp) from ('||:vsqlserdesp||') desp where desp.bdtipodesp = 1';
            EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
         end

      vsql = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, desp.bddesconto bddesconto ';
      vsql = vsql || 'from vfin_base_tdespesa desp ';
      vsql = vsql || 'where exists ';
      vsql = vsql || ' (';

     vsql = vsql || 'select bdcoddesp from vfin_esc_tlancbancario lan ';
     vsql = vsql || 'where (lan.bdcoddesp = desp.bdcoddesp) ';
     vsql = vsql || 'and lan.bdtiposervdesp = 1 ';
     vsql = vsql || 'and lan.bdvalorlanc > 0 ';

      if ((:prcodesc <> '') and (:prcodesc is not null)) then
         vsql = vsql || 'and lan.bdcodesc in ('||:prcodesc||') ';

      IF ((:prchavectaban <> '') AND (:prchavectaban IS NOT NULL)) THEN
         vsql = vsql || 'and lan.bdchavectaban in ('||:prchavectaban||') ';

      IF ((:prcodfor <> '') AND (:prcodfor IS NOT NULL)) THEN
          vsql = vsql || 'and lan.bdcodfor in ('||:prcodfor||') ';

      IF ((:prdatainicial <> '') AND (:prdatainicial IS NOT NULL)) THEN
          vsql = vsql || 'and lan.bddatalan >='||''''||:prdatainicial||''''||' ';
    
      IF ((:prdatafinal <> '') AND (:prdatafinal IS NOT NULL)) THEN
         vsql = vsql || 'and lan.bddatalan <= '||''''||:prdatafinal||''''||' ';

      IF ((:prcodcli <> '') AND (:prcodcli IS NOT NULL)) THEN
         vsql = vsql || 'and lan.bdcodcli in ('||:prcodcli||') ';

      if (Upper(:prdemtransfbancarias) = 'FALSE') then
         vsql = vsql || ' and lan.bdcodtipo <> 3006 ';


      vsql = vsql || ' )';

      IF (:vguardaserdesp <> '') THEN
         vsql = vsql || 'and desp.bdcoddesp in ('||:vguardaserdesp||') ';
    END

  /* Adicionar todas as analíticas em uma tabela temporária com os valores de seus períodos */
    FOR
    EXECUTE STATEMENT :vsql
    INTO
    :vcodserdesp,
    :vclassserdesp,
    :vdescserdesp,
    :vDesconto
    DO
    BEGIN
    vstop = 'FALSE';
    vperiodoinicial = '';
    vperiodofinal = '';
    vnumperiodo = 0;

    WHILE (UPPER(vstop) = 'FALSE') DO
      BEGIN
        vnumperiodo = :vnumperiodo +1;
    
        IF (:prtipodem = 0) THEN -- Demonstrativo total
           BEGIN
             vperiodoinicial = :prdatainicial;
             vperiodofinal = :prdatafinal;
    
             SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 1, '')
             INTO :vvlrperiodo01;
           END
        ELSE
          IF (:prtipodem = 1) THEN -- Demonstrativo mensal
             BEGIN
               IF (:vperiodoinicial = '') THEN
                  BEGIN
                    vperiodoinicial = prdatainicial;
                  END
               ELSE
                 BEGIN
                   -- Acrescentando um mês á data
                   SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 1) INTO :vperiodoinicial;
                   vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                 END
    
                 -- Obtendo o último dia do mês
                 SELECT ultdia FROM ultimo_dia_mes(CAST(SUBSTRING(:vperiodoinicial FROM 1 FOR 2) AS INTEGER), CAST(SUBSTRING(:vperiodoinicial FROM 7 FOR 4) AS INTEGER)) INTO :vultdiames;
                 vperiodofinal = SUBSTRING(:vperiodoinicial FROM 1 FOR 3)||:vultdiames||SUBSTRING(:vperiodoinicial FROM 6 FOR 5);
    
    
                 -- Guardando o período e o valor do período para posteriormente inserir um registro na tablela temporária contendo estas informações.
                 IF (:vnumperiodo = 1) THEN
                    BEGIN
                      vperiodo01 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 1, :vperiodo01)
                      INTO :vvlrperiodo01;
                    END
                 ELSE
                 IF (:vnumperiodo = 2) THEN
                    BEGIN
                      vperiodo02 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 2, :vperiodo02)
                      INTO :vvlrperiodo02;
                    END
                 ELSE
                 IF (:vnumperiodo = 3) THEN
                    BEGIN
                      vperiodo03 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 3, :vperiodo03)
                      INTO :vvlrperiodo03;
                    END
                 ELSE
                 IF (:vnumperiodo = 4) THEN
                    BEGIN
                      vperiodo04 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 4, :vperiodo04)
                      INTO :vvlrperiodo04;
                    END
                 ELSE
                 IF (:vnumperiodo = 5) THEN
                    BEGIN
                      vperiodo05 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 5, :vperiodo05)
                      INTO :vvlrperiodo05;
                    END
                 ELSE
                 IF (:vnumperiodo = 6) THEN
                    BEGIN
                      vperiodo06 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 6, :vperiodo06)
                      INTO :vvlrperiodo06;
                    END
                 ELSE
                 IF (:vnumperiodo = 7) THEN
                    BEGIN
                      vperiodo07 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 7, :vperiodo07)
                      INTO :vvlrperiodo07;
                     END
                 ELSE
                 IF (:vnumperiodo = 8) THEN
                    BEGIN
                      vperiodo08 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 8, :vperiodo08)
                      INTO :vvlrperiodo08;
                    END
                 ELSE
                 IF (:vnumperiodo = 9) THEN
                    BEGIN
                      vperiodo09 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 9, :vperiodo09)
                      INTO :vvlrperiodo09;
                    END
                 ELSE
                 IF (:vnumperiodo = 10) THEN
                    BEGIN
                      vperiodo10 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 10, :vperiodo10)
                      INTO :vvlrperiodo10;
                    END
                 ELSE
                 IF (:vnumperiodo = 11) THEN
                    BEGIN
                      vperiodo11 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 11, :vperiodo11)
                      INTO :vvlrperiodo11;
                    END
                 ELSE
                 IF (:vnumperiodo = 12) THEN
                    BEGIN
                      vperiodo12 = SUBSTRING(:vperiodoinicial FROM 1 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 12, :vperiodo12)
                      INTO :vvlrperiodo12;
                    END
             END
          ELSE
            IF (:prtipodem = 2) THEN -- Demonstrativo bimestral
               BEGIN
                 IF (:vperiodoinicial = '') THEN
                    BEGIN
                      vperiodoinicial = :prdatainicial;
                    END
                 ELSE
                   BEGIN
                     -- Por ser bimestral, deverá acrescentar dois meses á data
                     SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 2) INTO :vperiodoinicial;
                     vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                   END
    
                 /* Acrescentando um mês à referência final com base na referência inicial e obtendo o último dia deste mês.
                 Ex: Se o período inicial for 01/01/2017, o período final deverá ser 28/02/2017 */
                 SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 1) INTO :vperiodofinal;
                 SELECT ultdia FROM ultimo_dia_mes(CAST(SUBSTRING(:vperiodofinal FROM 6 FOR 2) AS INTEGER), CAST(SUBSTRING(:vperiodofinal FROM 1 FOR 4) AS INTEGER)) INTO :vultdiames;
                 vperiodofinal = SUBSTRING(:vperiodofinal FROM 6 FOR 2)||'/'||:vultdiames||'/'||SUBSTRING(:vperiodofinal FROM 1 FOR 4);
    
                 -- Guardando o período e o valor do período para posteriormente inserir um registro na tablela temporária contendo estas informações.
                 IF (:vnumperiodo = 1) THEN
                    BEGIN
                      vperiodo01 = '1º bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 1, :vperiodo01)
                      INTO :vvlrperiodo01;
                    END
                 ELSE
                 IF (:vnumperiodo = 2) THEN
                    BEGIN
                      vperiodo02 = '2º bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 2, :vperiodo02)
                      INTO :vvlrperiodo02;
                    END
                 ELSE
                 IF (:vnumperiodo = 3) THEN
                    BEGIN
                      vperiodo03 = '3º bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 3, :vperiodo03)
                      INTO :vvlrperiodo03;
                    END
                 ELSE
                 IF (:vnumperiodo = 4) THEN
                    BEGIN
                      vperiodo04 = '4º bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 4, :vperiodo04)
                      INTO :vvlrperiodo04;
                    END
                 ELSE
                 IF (:vnumperiodo = 5) THEN
                    BEGIN
                      vperiodo05 = '5º bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 5, :vperiodo05)
                      INTO :vvlrperiodo05;
                     END
                 ELSE
                 IF (:vnumperiodo = 6) THEN
                    BEGIN
                      vperiodo06 = '6º bimestre';
                      SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 6, :vperiodo06)
                      INTO :vvlrperiodo06;
                    END
               END
            ELSE
              IF (:prtipodem = 3) THEN -- Demonstrativo trimestral
                 BEGIN
                   IF (:vperiodoinicial = '') THEN
                       BEGIN
                         vperiodoinicial = :prdatainicial;
                       END
                   ELSE
                     BEGIN
                       -- Por ser trimestral, deverá acrescentar três meses á data
                       SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 3) INTO :vperiodoinicial;
                       vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                     END
    
                   /* Acrescentando três meses á referência final com base na referência inicial e obtendo o último dia deste mês.
                   Ex: Se o período inicial for 01/01/2017, o período final deverá ser 31/03/2017 */
                   SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 2) INTO :vperiodofinal;
                   SELECT ultdia FROM ultimo_dia_mes(CAST(SUBSTRING(:vperiodofinal FROM 6 FOR 2) AS INTEGER), CAST(SUBSTRING(:vperiodofinal FROM 1 FOR 4) AS INTEGER)) INTO :vultdiames;
                   vperiodofinal = SUBSTRING(:vperiodofinal FROM 6 FOR 2)||'/'||:vultdiames||'/'||SUBSTRING(:vperiodofinal FROM 1 FOR 4);
                   -- Guardando o período e o valor do período para posteriormente inserir um registro na tablela temporária contendo estas informações.
                   IF (:vnumperiodo = 1) THEN
                      BEGIN
                        vperiodo01 = '1º trimestre';
                        SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 1, :vperiodo01)
                        INTO :vvlrperiodo01;
                      END
                   ELSE
                   IF (:vnumperiodo = 2) THEN
                      BEGIN
                        vperiodo02 = '2º trimestre';
                        SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 2, :vperiodo02)
                        INTO :vvlrperiodo02;
                      END
                   ELSE
                   IF (:vnumperiodo = 3) THEN
                      BEGIN
                        vperiodo03 = '3º trimestre';
                        SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 3, :vperiodo03)
                        INTO :vvlrperiodo03;
                      END
                   ELSE
                   IF (:vnumperiodo = 4) THEN
                      BEGIN
                        vperiodo04 = '4º trimestre';
                        SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 4, :vperiodo04)
                        INTO :vvlrperiodo04;
                      END
                 END
              ELSE
                IF (:prtipodem = 4) THEN -- Demonstrativo semestral
                   BEGIN
                     IF (:vperiodoinicial = '') THEN
                       BEGIN
                         vperiodoinicial = :prdatainicial;
                       END
                     ELSE
                       BEGIN
                         -- Por ser semestral, deverá acrescentar seis meses á data
                         SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 6) INTO :vperiodoinicial;
                         vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                       END
    
                     /* Acrescentando cinco meses á referência final com base na referência inicial e obtendo o último dia deste mês.
                     Ex: Se o período inicial for 01/01/2017, o período final deverá ser 30/06/2017 */
                     SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 5) INTO :vperiodofinal;
                     SELECT ultdia FROM ultimo_dia_mes(CAST(SUBSTRING(:vperiodofinal FROM 6 FOR 2) AS INTEGER), CAST(SUBSTRING(:vperiodofinal FROM 1 FOR 4) AS INTEGER)) INTO :vultdiames;
                     vperiodofinal = SUBSTRING(:vperiodofinal FROM 6 FOR 2)||'/'||:vultdiames||'/'||SUBSTRING(:vperiodofinal FROM 1 FOR 4);
    
                     -- Guardando o período e o valor do período para posteriormente inserir um registro na tablela temporária contendo estas informações.
                     IF (:vnumperiodo = 1) THEN
                        BEGIN
                          vperiodo01 = '1º semestre';
                          SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 1, :vperiodo01)
                          INTO :vvlrperiodo01;
                        END
                     ELSE
                     IF (:vnumperiodo = 2) THEN
                        BEGIN
                          vperiodo02 = '2º semestre';
                          SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 2, :vperiodo02)
                          INTO :vvlrperiodo02;
                        END
                   END
                ELSE
                  BEGIN
                    IF (:prtipodem = 5) THEN -- Desmonstrativo anual
                       BEGIN
                         IF (:vperiodoinicial = '') THEN
                             BEGIN
                               vperiodoinicial = :prdatainicial;
                             END
                         ELSE
                           BEGIN
                             -- Por ser anual, deverá acrescentar um ano á data
                             SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vperiodoinicial, 12) INTO :vperiodoinicial;
                             vperiodoinicial = SUBSTRING(:vperiodoinicial FROM 6 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 9 FOR 2)||'/'||SUBSTRING(:vperiodoinicial FROM 1 FOR 4);
                           END
                         -- O último dia do ano sempre será 31/12/ + o ano que foi incrementado no vperiodoinicial
                         vperiodofinal = '12/31/'||SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
             
                         -- Guardando o período e o valor do período para posteriormente inserir um registro na tablela temporária contendo estas informações.
                         IF (:vnumperiodo = 1) THEN
                            BEGIN
                              vperiodo01 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 1, :vperiodo01)
                              INTO :vvlrperiodo01;
                            END
                         ELSE
                         IF (:vnumperiodo = 2) THEN
                            BEGIN
                              vperiodo02 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 2, :vperiodo02)
                              INTO :vvlrperiodo02;
                            END
                         ELSE
                         IF (:vnumperiodo = 3) THEN
                            BEGIN
                              vperiodo03 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 3, :vperiodo03)
                              INTO :vvlrperiodo03;
                            END
                         ELSE
                         IF (:vnumperiodo = 4) THEN
                            BEGIN
                              vperiodo04 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 4, :vperiodo04)
                              INTO :vvlrperiodo04;
                            END
                         ELSE
                         IF (:vnumperiodo = 5) THEN
                            BEGIN
                              vperiodo05 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 5, :vperiodo05)
                              INTO :vvlrperiodo05;
                            END
                         ELSE
                         IF (:vnumperiodo = 6) THEN
                            BEGIN
                              vperiodo06 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 6, :vperiodo06)
                              INTO :vvlrperiodo06;
                            END
                         ELSE
                         IF (:vnumperiodo = 7) THEN
                            BEGIN
                              vperiodo07 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 7, :vperiodo07)
                              INTO :vvlrperiodo07;
                            END
                         ELSE
                         IF (:vnumperiodo = 8) THEN
                            BEGIN
                              vperiodo08 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 8, :vperiodo08)
                              INTO :vvlrperiodo08;
                            END
                         ELSE
                         IF (:vnumperiodo = 9) THEN
                            BEGIN
                              vperiodo09 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 9, :vperiodo09)
                              INTO :vvlrperiodo09;
                            END
                         ELSE
                         IF (:vnumperiodo = 10) THEN
                            BEGIN
                              vperiodo10 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 10, :vperiodo10)
                              INTO :vvlrperiodo10;
                            END
                         ELSE
                         IF (:vnumperiodo = 11) THEN
                            BEGIN
                              vperiodo11 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 11, :vperiodo11)
                              INTO :vvlrperiodo11;
                            END
                         ELSE
                         IF (:vnumperiodo = 12) THEN
                            BEGIN
                              vperiodo12 = SUBSTRING(:vperiodoinicial FROM 7 FOR 4);
                              SELECT BDTOTSERDESPPERIODO FROM SP_TOTSERDESPPERIODO(:prcodesc, :vperiodoinicial, :vperiodofinal, :prchavectaban, :prtiporecdesp, :vcodserdesp, :PRCODCLI, :PRCODFOR, :prdemlancreembolso, :prdemtransfbancarias, :prmodelo, :vclassserdesp, :vDesconto, 12, :vperiodo12)
                              INTO :vvlrperiodo12;
                            END
                       END
                  END
    
        IF (:vperiodofinal = :prdatafinal) THEN
           vstop = 'TRUE';
      END

      if (prmodelo = 0) then
        begin
          vvlrtotperiodo = :vvlrperiodo01 + :vvlrperiodo02 + :vvlrperiodo03 + :vvlrperiodo04 + :vvlrperiodo05 + :vvlrperiodo06 + :vvlrperiodo07 +
                           :vvlrperiodo08 + :vvlrperiodo09 + :vvlrperiodo10 + :vvlrperiodo11 + :vvlrperiodo12;

          if (Upper(:vdesconto) = 'TRUE') then
             begin
               vvlrtotperiodo = - :vvlrtotperiodo;
               vvlrperiodo01 = - :vvlrperiodo01;
               vvlrperiodo02 = - :vvlrperiodo02;
               vvlrperiodo03 = - :vvlrperiodo03;
               vvlrperiodo04 = - :vvlrperiodo04;
               vvlrperiodo05 = - :vvlrperiodo05;
               vvlrperiodo06 = - :vvlrperiodo06;
               vvlrperiodo07 = - :vvlrperiodo07;
               vvlrperiodo08 = - :vvlrperiodo08;
               vvlrperiodo09 = - :vvlrperiodo09;
               vvlrperiodo10 = - :vvlrperiodo10;
               vvlrperiodo11 = - :vvlrperiodo11;
               vvlrperiodo12 = - :vvlrperiodo12;
             end
        
          INSERT INTO TMP_DEMRECDESP_ANALITICAS (BDCODCLIFOR, BDCODOBRSER, BDCLASSIFICACAO, BDTIPO, BDPERIODO01, BDVLRPERIODO01, BDPERIODO02, BDVLRPERIODO02, BDPERIODO03, BDVLRPERIODO03,
          BDPERIODO04, BDVLRPERIODO04, BDPERIODO05, BDVLRPERIODO05, BDPERIODO06, BDVLRPERIODO06, BDPERIODO07, BDVLRPERIODO07, BDPERIODO08, BDVLRPERIODO08,
          BDPERIODO09, BDVLRPERIODO09, BDPERIODO10, BDVLRPERIODO10, BDPERIODO11, BDVLRPERIODO11, BDPERIODO12, BDVLRPERIODO12, BDVLRTOTPERIODO)
          VALUES (0, :vcodserdesp, :vclassserdesp, 1, :vperiodo01, :vvlrperiodo01, :vperiodo02, :vvlrperiodo02, :vperiodo03, :vvlrperiodo03, :vperiodo04, :vvlrperiodo04,
          :vperiodo05, :vvlrperiodo05, :vperiodo06, :vvlrperiodo06, :vperiodo07, :vvlrperiodo07, :vperiodo08, :vvlrperiodo08, :vperiodo09, :vvlrperiodo09,
          :vperiodo10, :vvlrperiodo10, :vperiodo11, :vvlrperiodo11, :vperiodo12, :vvlrperiodo12, :vvlrtotperiodo);
        end
    END -- end dos serviços/despesas

    if (:prmodelo = 1) then
       begin
          if (:vperiodo01 <> '') then
             update TMP_DEMRECDESP_ANALITICAS set BDPERIODO01 = :vperiodo01, BDVLRPERIODO01 = 0 where (bdperiodo01 is null) and (BDVLRPERIODO01 is null);
          if (:vperiodo02 <> '') then
             update TMP_DEMRECDESP_ANALITICAS set BDPERIODO02 = :vperiodo02, BDVLRPERIODO02 = 0 where (bdperiodo02 is null) and (BDVLRPERIODO02 is null);
          if (:vperiodo03 <> '') then
             update TMP_DEMRECDESP_ANALITICAS set BDPERIODO03 = :vperiodo03, BDVLRPERIODO03 = 0 where (bdperiodo03 is null) and (BDVLRPERIODO03 is null);
          if (:vperiodo04 <> '') then
             update TMP_DEMRECDESP_ANALITICAS set BDPERIODO04 = :vperiodo04, BDVLRPERIODO04 = 0 where (bdperiodo04 is null) and (BDVLRPERIODO04 is null);
          if (:vperiodo05 <> '') then
             update TMP_DEMRECDESP_ANALITICAS set BDPERIODO05 = :vperiodo05, BDVLRPERIODO05 = 0 where (bdperiodo05 is null) and (BDVLRPERIODO05 is null);
          if (:vperiodo06 <> '') then
             update TMP_DEMRECDESP_ANALITICAS set BDPERIODO06 = :vperiodo06, BDVLRPERIODO06 = 0 where (bdperiodo06 is null) and (BDVLRPERIODO06 is null);
          if (:vperiodo07 <> '') then
             update TMP_DEMRECDESP_ANALITICAS set BDPERIODO07 = :vperiodo07, BDVLRPERIODO07 = 0 where (bdperiodo07 is null) and (BDVLRPERIODO07 is null);
          if (:vperiodo08 <> '') then
             update TMP_DEMRECDESP_ANALITICAS set BDPERIODO08 = :vperiodo08, BDVLRPERIODO08 = 0 where (bdperiodo08 is null) and (BDVLRPERIODO08 is null);
          if (:vperiodo09 <> '') then
             update TMP_DEMRECDESP_ANALITICAS set BDPERIODO09 = :vperiodo09, BDVLRPERIODO09 = 0 where (bdperiodo09 is null) and (BDVLRPERIODO09 is null);
          if (:vperiodo10 <> '') then
             update TMP_DEMRECDESP_ANALITICAS set BDPERIODO10 = :vperiodo10, BDVLRPERIODO10 = 0 where (bdperiodo10 is null) and (BDVLRPERIODO10 is null);
          if (:vperiodo11 <> '') then
             update TMP_DEMRECDESP_ANALITICAS set BDPERIODO11 = :vperiodo11, BDVLRPERIODO11 = 0 where (bdperiodo11 is null) and (BDVLRPERIODO11 is null);
          if (:vperiodo12 <> '') then
            update TMP_DEMRECDESP_ANALITICAS set BDPERIODO12 = :vperiodo12, BDVLRPERIODO12 = 0 where (bdperiodo12 is null) and (BDVLRPERIODO12 is null);
        end

   FOR
   EXECUTE STATEMENT :vsqlCliFor
   INTO
   :vCodCliForAtual,
   :vCount
   DO
   BEGIN
     FOR
       EXECUTE STATEMENT :vsqlserdesp
       INTO
       :vcodserdesp,
       :vclassserdesp,
       :vdescserdesp,
       :vtiposerdesp
       DO
       BEGIN
         --bdcodserdesp = :vcodserdesp;
         --bdclassificacao = :vclassserdesp;
         ---bddescricao = :vdescserdesp;
         --bdtipo = :vtiposerdesp;
         --bdvlrtotperiodo = 0;

         if (:vtiposerdesp = 0) then
            begin
                vperiodo01    = '';
                vvlrperiodo01 = 0;
                vperiodo02    = '';
                vvlrperiodo02 = 0;
                vperiodo03    = '';
                vvlrperiodo03 = 0;
                vperiodo04    = '';
                vvlrperiodo04 = 0;
                vperiodo05    = '';
                vvlrperiodo05 = 0;
                vperiodo06    = '';
                vvlrperiodo06 = 0;
                vperiodo07    = '';
                vvlrperiodo07 = 0;
                vperiodo08    = '';
                vvlrperiodo08 = 0;
                vperiodo09    = '';
                vvlrperiodo09 = 0;
                vperiodo10    = '';
                vvlrperiodo10 = 0;
                vperiodo11    = '';
                vvlrperiodo11 = 0;
                vperiodo12    = '';
                vvlrperiodo12 = 0;

                vvlrtotperiodo = 0;

                SELECT bdperiodo01, SUM(bdvlrperiodo01) bdvlrperiodo01, bdperiodo02, SUM(bdvlrperiodo02) bdvlrperiodo02, bdperiodo03, SUM(bdvlrperiodo03) bdvlrperiodo03,
                bdperiodo04, SUM(bdvlrperiodo04) bdvlrperiodo04, bdperiodo05, SUM(bdvlrperiodo05) bdvlrperiodo05, bdperiodo06, SUM(bdvlrperiodo06) bdvlrperiodo06,
                bdperiodo07, SUM(bdvlrperiodo07) bdvlrperiodo07, bdperiodo08, SUM(bdvlrperiodo08) bdvlrperiodo08, bdperiodo09, SUM(bdvlrperiodo09) bdvlrperiodo09,
                bdperiodo10, SUM(bdvlrperiodo10) bdvlrperiodo10, bdperiodo11, SUM(bdvlrperiodo11) bdvlrperiodo11, bdperiodo12, SUM(bdvlrperiodo12) bdvlrperiodo12,
                SUM(bdvlrtotperiodo) bdvlrtotperiodo
                FROM TMP_DEMRECDESP_ANALITICAS
                WHERE bdtipo = 1 and bdcodclifor = :vCodCliForAtual and bdclassificacao LIKE :vclassserdesp||'%' -- se for modelo realizado vCodCliForAtual virá 0!
                GROUP BY bdperiodo01, bdperiodo02, bdperiodo03, bdperiodo04, bdperiodo05, bdperiodo06, bdperiodo07,
                bdperiodo08, bdperiodo09, bdperiodo10, bdperiodo11, bdperiodo12
                INTO :vperiodo01, :vvlrperiodo01, :vperiodo02, :vvlrperiodo02, :vperiodo03, :vVlrperiodo03, :vperiodo04, :vvlrperiodo04,
                :vperiodo05, :vvlrperiodo05, :vperiodo06, :vvlrperiodo06, :vperiodo07, :vvlrperiodo07, :vperiodo08, :vvlrperiodo08,
                :vperiodo09, :vvlrperiodo09, :vperiodo10, :vvlrperiodo10, :vperiodo11, :vvlrperiodo11, :vperiodo12, :vvlrperiodo12,
                :vvlrtotperiodo;

                 -- Serviços de desconto vem negativos
                IF (:vvlrtotperiodo <> 0) THEN
                   BEGIN
                     INSERT INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, bdcodclifor, BDCLASSIFICACAO, BDTIPO, BDPERIODO01, bdvlrperiodo01, BDPERIODO02, bdvlrperiodo02, BDPERIODO03, bdvlrperiodo03,
                                                            BDPERIODO04, bdvlrperiodo04, BDPERIODO05, bdvlrperiodo05, BDPERIODO06, bdvlrperiodo06,  BDPERIODO07, bdvlrperiodo07,
                                                            BDPERIODO08, bdvlrperiodo08, BDPERIODO09, bdvlrperiodo09, BDPERIODO10, bdvlrperiodo10, BDPERIODO11, bdvlrperiodo11,
                                                            BDPERIODO12, bdvlrperiodo12, BDVLRTOTPERIODO)
                     values(:vcodserdesp, :vCodCliForAtual, :vclassserdesp, :vtiposerdesp, :vperiodo01, :vvlrperiodo01, :vperiodo02, :vvlrperiodo02, :vperiodo03, :vvlrperiodo03, :vperiodo04, :vvlrperiodo04,
                            :vperiodo05, :vvlrperiodo05, :vperiodo06, :vvlrperiodo06, :vperiodo07, :vvlrperiodo07, :vperiodo08, :vvlrperiodo08, :vperiodo09, :vvlrperiodo09, :vperiodo10, :vvlrperiodo10,
                            :vperiodo11, :vvlrperiodo11, :vperiodo12, :vvlrperiodo12, :vvlrtotperiodo);
                     --SUSPEND;
                   END
            end
     END
   END
   --suspend;
END^

SET TERM ; ^


SET TERM ^ ;

create or alter procedure SP_FLUXOCAIXA (
    PRCHAVECTABAN varchar(10000),
    PRDATAINI varchar(10),
    PRDATAFIN varchar(10),
    PRFLAGPROC integer)
returns (
    BDTIPO integer,
    BDCODCLI integer,
    BDNOMCLI varchar(100),
    BDSERIE varchar(6),
    BDREFFAT integer,
    BDCHAVECTABAN integer,
    BDDATAVENC date,
    BDDESCCTABAN varchar(200),
    BDVALORPREV numeric(15,2),
    BDVALORREAL numeric(15,2),
    BDSALDOANT numeric(15,2),
    BDSALDOATUAL numeric(15,2),
    BDCODFOR integer,
    BDNOMEFOR varchar(100),
    BDCHAVECTAPAG integer,
    BDNUMPARC varchar(50),
    BDREFLANC integer,
    BDOBS varchar(1024),
    BDDATARECPAG date)
as
declare variable WCHAVECTABAN integer;
declare variable WSQL varchar(15000);
declare variable WREF varchar(6);
declare variable WSALDOANT numeric(15,2);
begin
  wsql = 'select (substring('||''''||:prdatafin||''''||' from 7 for 4)||(substring('||''''||:prdatafin||''''||' from 1 for 2))) from rdb$database';
  execute statement :wsql into :wref;

  execute procedure sp_seta_competencia(:wref, null, null);

  wsql = 'select FLUXO.* ';
  wsql = wsql || 'from (select 0 as BDTIPO, FAT.*, CTA.BDDESCCTABAN, CLI.BDNOMCLI ';
  wsql = wsql || 'from (select TMPFAT.BDCODCLI, TMPFAT.BDSERIE, null as BDREFFAT, null as BDCHAVECTAPAG, null as BDCODFOR, ';
  wsql = wsql || 'null as BDNOMEFOR, null as BDNUMPARC, null as BDREFLANC, TMPFAT.BDCHAVECTABAN, TMPFAT.BDDATAVENC, ';
  wsql = wsql || 'coalesce(TMPFAT.BDVALORFATURA, 0) as BDVALORPREV, 0 as BDVALORREAL, null as BDOBS, null as BDDATARECPAG ';
  wsql = wsql || 'from TMP_VFIN_ESC_TFATURA TMPFAT ';
  wsql = wsql || 'left outer join VFIN_ESC_TFATURA FAT on (FAT.BDCODCLI = TMPFAT.BDCODCLI and FAT.BDCODESC = TMPFAT.BDCODESC and FAT.BDCHAVEFATURA = TMPFAT.BDCHAVEFATURA) ';
  wsql = wsql || 'where TMPFAT.BDFLAGPROC = '||:prflagproc||' AND ((TMPFAT.BDDATAVENC >='||''''||:prdataini||''''||') and (TMPFAT.BDDATAVENC <='||''''||:prdatafin||''''||')) and coalesce(fat.bdtotrec,0) = 0 ';

  if (:prchavectaban <> '') then
     wsql = wsql || 'and TMPFAT.BDCHAVECTABAN in ('|| :prchavectaban ||') ';

  wsql = wsql || 'union ';

  wsql = wsql || 'select distinct FAT.BDCODCLI, FAT.BDSERIE, ';
  wsql = wsql || 'null as BDREFFAT, ';
  wsql = wsql || 'null as BDCHAVECTAPAG, null as BDCODFOR, null as BDNOMEFOR, null as BDNUMPARC, null as BDREFLANC, ';
  wsql = wsql || 'LAN.BDCHAVECTABAN, FAT.BDDATAVENC, ';
  wsql = wsql || '(case when LAN.BDDATALAN = FAT.BDDATAVENC and LAN.bdchavectaban = FAT.bdchavectaban then FAT.BDVALORFATURA when LAN.BDDATALAN is null then FAT.BDVALORFATURA else 0 end) as BDVALORPREV, ';
  wsql = wsql || '(coalesce((select sum(LANC.BDVALORLANC) from VFIN_ESC_TLANCBANCARIO LANC ';
  wsql = wsql || 'where LANC.BDCODESC = FAT.BDCODESC and LANC.BDCODCLI = FAT.BDCODCLI and ';
  wsql = wsql || 'LANC.BDCHAVEFATURA = FAT.BDCHAVEFATURA and LANC.BDCHAVECTABAN = LAN.BDCHAVECTABAN and ';
  wsql = wsql || 'LANC.BDDATALAN = LAN.BDDATALAN and LANC.BDTIPOMOV = 0),0) - coalesce((select sum(LANC.BDVALORLANC) from VFIN_ESC_TLANCBANCARIO LANC ';
  wsql = wsql || 'where LANC.BDCODESC = FAT.BDCODESC and LANC.BDCODCLI = FAT.BDCODCLI and ';
  wsql = wsql || 'LANC.BDCHAVEFATURA = FAT.BDCHAVEFATURA and LANC.BDCHAVECTABAN = LAN.BDCHAVECTABAN and ';
  wsql = wsql || 'LANC.BDDATALAN = LAN.BDDATALAN and LANC.BDTIPOMOV = 1), 0)) as BDVALORREAL, null as BDOBS, ';
  wsql = wsql || 'LAN.BDDATALAN as BDDATARECPAG ';
  wsql = wsql || 'from VFIN_ESC_TLANCBANCARIO LAN ';
  wsql = wsql || 'inner join VFIN_ESC_TFATURA FAT on (FAT.BDCODCLI = LAN.BDCODCLI and FAT.BDCODESC = LAN.BDCODESC and FAT.BDCHAVEFATURA = LAN.BDCHAVEFATURA) ';
  wsql = wsql || 'where lan.bdcodtipo <> 3008 and ((lan.bddatalan >= '||''''||:prdataini||''''||') and (lan.bddatalan <= '||''''||:prdatafin||''''||'))';

  if (:prchavectaban <> '') then
     wsql = wsql || 'and LAN.BDCHAVECTABAN in ('|| :prchavectaban ||') ';

  wsql = wsql || 'union ';

  wsql = wsql || 'select FAT.BDCODCLI, FAT.BDSERIE, null as BDREFFAT, null as BDCHAVECTAPAG, null as BDCODFOR, ';
  wsql = wsql || 'null as BDNOMEFOR, null as BDNUMPARC, null as BDREFLANC, FAT.BDCHAVECTABAN, ';
  wsql = wsql || 'FAT.BDDATAVENC, coalesce(FAT.BDVALORFATURA, 0) as BDVALORPREV, (coalesce((select sum(LANC.BDVALORLANC) from VFIN_ESC_TLANCBANCARIO LANC ';
  wsql = wsql || 'where LANC.BDCODESC = FAT.BDCODESC and LANC.BDCODCLI = FAT.BDCODCLI and LANC.BDCHAVEFATURA = FAT.BDCHAVEFATURA and LANC.bdchavectaban = FAT.bdchavectaban and LANC.BDDATALAN = FAT.BDDATAVENC AND LANC.BDTIPOMOV = 0),0) - coalesce((select sum(LANC.BDVALORLANC) from VFIN_ESC_TLANCBANCARIO LANC ';
  wsql = wsql || 'where LANC.BDCODESC = FAT.BDCODESC and LANC.BDCODCLI = FAT.BDCODCLI and ';
  wsql = wsql || 'LANC.BDCHAVEFATURA = FAT.BDCHAVEFATURA and LANC.bdchavectaban = FAT.bdchavectaban and ';
  wsql = wsql || 'LANC.BDDATALAN = FAT.BDDATAVENC and LANC.BDTIPOMOV = 1), 0)) as BDVALORREAL, ';
  wsql = wsql || 'null as BDOBS, coalesce((select first 1 LANC.bddatalan from VFIN_ESC_TLANCBANCARIO LANC where LANC.BDCODESC = FAT.BDCODESC and ';
  wsql = wsql || 'LANC.BDCODCLI = FAT.BDCODCLI and LANC.BDCHAVEFATURA = FAT.BDCHAVEFATURA and LANC.bdchavectaban = FAT.bdchavectaban and LANC.BDDATALAN = FAT.BDDATAVENC), null) as BDDATARECPAG ';
  wsql = wsql || 'from VFIN_ESC_TFATURA FAT ';
  wsql = wsql || 'where ((fat.bddatavenc >= '||''''||:prdataini||''''||') and (fat.bddatavenc <= '||''''||:prdatafin||''''||')) ';

  if (:prchavectaban <> '') then
     wsql = wsql || 'and fat.BDCHAVECTABAN in ('|| :prchavectaban ||') ';

  wsql = wsql || ') FAT ';
  wsql = wsql || 'inner join VFIN_ESC_TCONTASBAN CTA on (CTA.BDCHAVECTABAN = FAT.BDCHAVECTABAN) ';
  wsql = wsql || 'inner join VW_VFIN_CLIENTES_REF CLI on (CLI.BDCODCLI = FAT.BDCODCLI) ';
  wsql = wsql || 'union ';

  wsql = wsql || 'select BDTIPO, BDCODCLI, BDSERIE, BDREFFAT, BDCHAVECTAPAG, BDCODFOR, BDNOMEFOR, BDNUMPARC, BDREFLANC, BDCHAVECTABAN, ';
  wsql = wsql || 'BDDATAVENC, BDVALORPREV, sum(CP.BDVALORREAL) as BDVALORREAL, BDOBS, BDDATARECPAG, BDDESCCTABAN, BDNOMCLI ';
  wsql = wsql || 'from (select distinct 1 as BDTIPO, null as BDCODCLI, null as BDSERIE, null as BDREFFAT, CP.BDCHAVECTAPAG, CP.BDCODFOR, FORN.BDNOMEFOR, ';
  wsql = wsql || '(case when PAR.BDORDEMPAR is not null then PAR.BDNUMPAR || ''/'' || CP.BDNUMPARC end) as BDNUMPARC, ';
  wsql = wsql || 'null as BDREFLANC, ';
  wsql = wsql || 'pag.BDCHAVECTABAN, ';
  wsql = wsql || '(case when PAR.BDORDEMPAR is null then CP.BDDATAVENC else PAR.BDDATAVENCPAR end) BDDATAVENC, ';
  wsql = wsql || '(case when pag.bddatapag = (case when PAR.BDORDEMPAR is null then CP.BDDATAVENC else PAR.BDDATAVENCPAR end) and pag.bdchavectaban = cp.bdchavectaban then ';
  wsql = wsql || '(case when PAR.BDORDEMPAR is null then CP.BDVALORTOTALDESP else PAR.BDVALORPAR end) else 0 end) as BDVALORPREV, ';
  wsql = wsql || 'coalesce(PAG.BDVLRPAG + PAG.bdjurospag + PAG.bdmultapag - PAG.bddescpag, 0) as BDVALORREAL, null as BDOBS, pag.bddatapag as BDDATARECPAG, CTA.BDDESCCTABAN, null as BDNOMCLI ';
  wsql = wsql || 'from VFIN_ESC_TPAGAMENTOS PAG ';
  wsql = wsql || 'inner join VFIN_ESC_TCONTASAPAGAR CP on (CP.BDCODESC = pag.BDCODESC and CP.BDCHAVECTAPAG = pag.BDCHAVECTAPAG) ';
  wsql = wsql || 'left outer join VFIN_ESC_TPARCELAPAGAR par on (par.bdcodesc = cp.bdcodesc and par.bdchavectapag = cp.bdchavectapag and par.bdordempar = pag.bdordempar) ';
  wsql = wsql || 'left outer join VFIN_ESC_TCONTASBAN CTA on (CTA.BDCHAVECTABAN = pag.BDCHAVECTABAN) ';
  wsql = wsql || 'left outer join VW_VFIN_BASE_TFORNECEDOR FORN on (FORN.BDCODFOR = cp.BDCODFOR) ';
  wsql = wsql || 'where ((pag.bddatapag >= '||''''||:prdataini||''''||') and (pag.bddatapag <= '||''''||:prdatafin||''''||'))';

  if (:prchavectaban <> '') then
     wsql = wsql || 'and pag.BDCHAVECTABAN in ('|| :prchavectaban ||') ';

  wsql = wsql || ') CP ';
  wsql = wsql || 'group by BDTIPO, BDCODCLI, BDSERIE, BDREFFAT, BDCHAVECTAPAG, BDCODFOR, BDNOMEFOR, BDNUMPARC, BDREFLANC, ';
  wsql = wsql || 'BDCHAVECTABAN, BDDATAVENC, BDVALORPREV, BDOBS, BDDATARECPAG, BDDESCCTABAN, BDNOMCLI ';

  wsql = wsql || 'union ';

  wsql = wsql || 'select BDTIPO, BDCODCLI, BDSERIE, BDREFFAT, BDCHAVECTAPAG, BDCODFOR, BDNOMEFOR, BDNUMPARC, BDREFLANC, ';
  wsql = wsql || 'BDCHAVECTABAN, BDDATAVENC, BDVALORPREV, sum(CP.BDVALORREAL) as BDVALORREAL, BDOBS, BDDATARECPAG, BDDESCCTABAN, BDNOMCLI ';
  wsql = wsql || 'from (select distinct 1 as BDTIPO, null as BDCODCLI, null as BDSERIE, null as BDREFFAT, CP.BDCHAVECTAPAG, ';
  wsql = wsql || 'CP.BDCODFOR, FORN.BDNOMEFOR, (case when PAR.BDORDEMPAR is not null then PAR.BDNUMPAR || ''/'' || CP.BDNUMPARC end) as BDNUMPARC, ';
  wsql = wsql || 'null as BDREFLANC, CP.BDCHAVECTABAN, (case when PAR.BDORDEMPAR is null then CP.BDDATAVENC else PAR.BDDATAVENCPAR end) BDDATAVENC, ';
  wsql = wsql || '(case when PAR.BDORDEMPAR is null then CP.BDVALORTOTALDESP else PAR.BDVALORPAR end) as BDVALORPREV, ';
  wsql = wsql || '(select coalesce(sum(pgto.BDVLRPAG + pgto.BDJUROSPAG + pgto.BDMULTAPAG - pgto.BDDESCPAG),0) from VFIN_ESC_TPAGAMENTOS pgto ';
  wsql = wsql || 'where pgto.bdcodesc = cp.bdcodesc and pgto.bdchavectapag = cp.bdchavectapag and ((pgto.BDORDEMPAR = PAR.BDORDEMPAR) or (pgto.BDORDEMPAR is null)) ';
  wsql = wsql || 'and pgto.bdchavectaban = cp.bdchavectaban and pgto.bddatapag = (case when PAR.BDORDEMPAR is null then CP.BDDATAVENC else PAR.BDDATAVENCPAR end)) as BDVALORREAL, ';
  wsql = wsql || 'null as BDOBS, (select first 1 pgto.bddatapag from VFIN_ESC_TPAGAMENTOS pgto where pgto.bdcodesc = cp.bdcodesc and pgto.bdchavectapag = cp.bdchavectapag and ((pgto.BDORDEMPAR = PAR.BDORDEMPAR) or (pgto.BDORDEMPAR is null)) ';
  wsql = wsql || 'and pgto.bdchavectaban = cp.bdchavectaban and pgto.bddatapag = (case when PAR.BDORDEMPAR is null then CP.BDDATAVENC else PAR.BDDATAVENCPAR end)) as BDDATARECPAG, ';
  wsql = wsql || '(case when CTA.BDCHAVECTABAN is null then ''Sem conta bancária'' else CTA.BDDESCCTABAN end) as BDDESCCTABAN, null as BDNOMCLI ';
  wsql = wsql || 'from VFIN_ESC_TCONTASAPAGAR CP ';
  wsql = wsql || 'left outer join VFIN_ESC_TPARCELAPAGAR PAR on (PAR.BDCODESC = CP.BDCODESC and PAR.BDCHAVECTAPAG = CP.BDCHAVECTAPAG) ';
  wsql = wsql || 'left outer join VFIN_ESC_TCONTASBAN CTA on (CTA.BDCHAVECTABAN = CP.BDCHAVECTABAN) ';
  wsql = wsql || 'left outer join VW_VFIN_BASE_TFORNECEDOR FORN on (FORN.BDCODFOR = CP.BDCODFOR) ';
  wsql = wsql || 'left outer join VFIN_ESC_TPAGAMENTOS PAG ON (PAG.bdcodesc = CP.bdcodesc AND PAG.bdchavectapag = CP.bdchavectapag and ((PAG.BDORDEMPAR = PAR.BDORDEMPAR) or (pag.bdordempar is null))) ';
  wsql = wsql || 'where (case when PAR.BDORDEMPAR is null then CP.BDDATAVENC else PAR.BDDATAVENCPAR end) >= '||''''||:prdataini||''''||' and ';
  wsql = wsql || '(case when PAR.BDORDEMPAR is null then CP.BDDATAVENC else PAR.BDDATAVENCPAR end) <= '||''''||:prdatafin||''''||' ';

  if (:prchavectaban <> '') then
     wsql = wsql || 'and cp.BDCHAVECTABAN in ('|| :prchavectaban ||') ';

  wsql = wsql || ') CP ';
  wsql = wsql || 'group by BDTIPO, BDCODCLI, BDSERIE, BDREFFAT, BDCHAVECTAPAG, BDCODFOR, BDNOMEFOR, BDNUMPARC, BDREFLANC, ';
  wsql = wsql || 'BDCHAVECTABAN, BDDATAVENC, BDVALORPREV, BDOBS, BDDATARECPAG, BDDESCCTABAN, BDNOMCLI ';

  wsql = wsql || 'union ';

  wsql = wsql || 'select 0 as bdtipo, null as bdcodcli, null as bdserie, null as bdreffat, null as bdchavectapag, ';
  wsql = wsql || 'null as bdcodfor, null as bdnomefor, null as bdnumparc, null as bdreflanc, rec.bdchavectaban, ';
  wsql = wsql || 'rec.bddatarec as bddatavenc, 0 as bdvalorprev, rec.bdsaldorecant as bdvalorreal, recobs.bdobsrecant as bdobs, ';
  wsql = wsql || 'rec.bddatarec as bddatarecpag, cta.bddescctaban, null as bdnomcli ';
  wsql = wsql || 'from VFIN_ESC_TRECANTECIPADO rec ';
  wsql = wsql || 'left outer join VFIN_ESC_TRECANTECIPADOOBS recobs on (recobs.bdcodesc = rec.bdcodesc and recobs.bdcodcli = rec.bdcodcli and recobs.bdchaverecant = rec.bdchaverecant) ';
  wsql = wsql || 'left outer join VFIN_ESC_TCONTASBAN CTA on (CTA.BDCHAVECTABAN = rec.BDCHAVECTABAN) ';
  wsql = wsql || 'where rec.bdsaldorecant > 0 ';
  wsql = wsql || 'and ((rec.bddatarec >= '||''''||:prdataini||''''||') and (rec.bddatarec <= '||''''||:prdatafin||''''||')) ';

  if (:prchavectaban <> '') then
     wsql = wsql || 'and rec.BDCHAVECTABAN in ('|| :prchavectaban ||') ';

  wsql = wsql || 'union ';
  wsql = wsql || 'select 0 as bdtipo, recd.bdcodcli, fat.bdserie, null as bdreffat, null as bdchavectapag, ';
  wsql = wsql || 'null as bdcodfor, null as bdnomefor, null as bdnumparc, null as bdreflanc, rec.bdchavectaban, ';
  wsql = wsql || 'fat.bddatavenc, fat.bdvalorfatura as bdvalorprev, ';
  wsql = wsql || '(case when fat.bddatavenc = rec.bddatarec and fat.bdchavectaban = rec.bdchavectaban then recd.bdvalrecdest else 0 end) as bdvalorreal, ';
  wsql = wsql || 'recobs.bdobsrecant as bdobs, (case when fat.bddatavenc = rec.bddatarec and fat.bdchavectaban = rec.bdchavectaban then rec.bddatarec else null end) as bddatarecpag, ';
  wsql = wsql || 'cta.bddescctaban, cli.bdnomcli ';
  wsql = wsql || 'from VFIN_ESC_TRECANTECIPADO rec ';
  wsql = wsql || 'inner join VFIN_ESC_TRECANTECIP_DEST recd on (recd.bdcodesc = rec.bdcodesc and recd.bdcodcli = rec.bdcodcli and recd.bdchaverecant = rec.bdchaverecant) ';
  wsql = wsql || 'left outer join VFIN_ESC_TRECANTECIPADOOBS recobs on (recobs.bdcodesc = rec.bdcodesc and recobs.bdcodcli = rec.bdcodcli and recobs.bdchaverecant = rec.bdchaverecant) ';
  wsql = wsql || 'inner join VFIN_ESC_TFATURA fat on (fat.bdcodesc = recd.bdcodesc and fat.bdcodcli = recd.bdcodcli and fat.bdchavefatura = recd.bdchavefatura) ';
  wsql = wsql || 'left outer join VW_VFIN_CLIENTES_REF CLI on (CLI.BDCODCLI = recd.BDCODCLI) ';
  wsql = wsql || 'left outer join VFIN_ESC_TCONTASBAN CTA on (CTA.BDCHAVECTABAN = rec.BDCHAVECTABAN) ';
  wsql = wsql || 'where ((rec.bddatarec >= '||''''||:prdataini||''''||') and (rec.bddatarec <= '||''''||:prdatafin||''''||')) ';

  if (:prchavectaban <> '') then
     wsql = wsql || 'and rec.BDCHAVECTABAN in ('|| :prchavectaban ||') ';

  wsql = wsql || 'union ';
  wsql = wsql || 'select 0 as bdtipo, recd.bdcodcli, fat.bdserie, null as bdreffat, null as bdchavectapag, ';
  wsql = wsql || 'null as bdcodfor, null as bdnomefor, null as bdnumparc, null as bdreflanc, rec.bdchavectaban, ';
  wsql = wsql || 'fat.bddatavenc, (case when fat.bddatavenc = rec.bddatarec and fat.bdchavectaban = rec.bdchavectaban then recd.bdvalrecdest else 0 end) as bdvalorprev, ';
  wsql = wsql || '(recd.bdvalrecdest) as bdvalorreal, ';
  wsql = wsql || 'recobs.bdobsrecant as bdobs, (rec.bddatarec) as bddatarecpag, ';
  wsql = wsql || 'cta.bddescctaban, cli.bdnomcli ';
  wsql = wsql || 'from VFIN_ESC_TRECANTECIP_DEST recd ';
  wsql = wsql || 'inner join VFIN_ESC_TRECANTECIPADO rec on (rec.bdcodesc = recd.bdcodesc and rec.bdcodcli = recd.bdcodcli and rec.bdchaverecant = recd.bdchaverecant) ';
  wsql = wsql || 'left outer join VFIN_ESC_TRECANTECIPADOOBS recobs on (recobs.bdcodesc = rec.bdcodesc and recobs.bdcodcli = rec.bdcodcli and recobs.bdchaverecant = rec.bdchaverecant) ';
  wsql = wsql || 'inner join VFIN_ESC_TFATURA fat on (fat.bdcodesc = recd.bdcodesc and fat.bdcodcli = recd.bdcodcli and fat.bdchavefatura = recd.bdchavefatura) ';
  wsql = wsql || 'left outer join VW_VFIN_CLIENTES_REF CLI on (CLI.BDCODCLI = recd.BDCODCLI) ';
  wsql = wsql || 'left outer join VFIN_ESC_TCONTASBAN CTA on (CTA.BDCHAVECTABAN = rec.BDCHAVECTABAN) ';
  wsql = wsql || 'where ((rec.bddatarec >= '||''''||:prdataini||''''||') and (rec.bddatarec <= '||''''||:prdatafin||''''||'))';

  if (:prchavectaban <> '') then
     wsql = wsql || 'and rec.BDCHAVECTABAN in ('|| :prchavectaban ||') ';

  wsql = wsql || 'union ';

  wsql = wsql || 'select LAN.BDTIPOMOV as BDTIPO, LAN.BDCODCLI, null as BDSERIE, null as BDREFFAT, null as BDCHAVECTAPAG, LAN.BDCODFOR, ';
  wsql = wsql || 'FORN.BDNOMEFOR, null as BDNUMPARC, ';
  wsql = wsql || 'null as BDREFLANC, LAN.BDCHAVECTABAN, ';
  wsql = wsql || 'LAN.BDDATALAN as BDDATAVENC, coalesce(LAN.BDVALORLANC,0) as BDVALORPREV, coalesce(LAN.BDVALORLANC,0) as BDVALORREAL, ';
  wsql = wsql || 'LANOBS.BDCOMPLEMENTO, LAN.BDDATALAN as BDDATARECPAG, CTA.BDDESCCTABAN, CLI.BDNOMCLI ';
  wsql = wsql || 'from VFIN_ESC_TLANCBANCARIO LAN ';
  wsql = wsql || 'left outer join VW_VFIN_BASE_TFORNECEDOR FORN on (FORN.BDCODFOR = LAN.BDCODFOR) ';
  wsql = wsql || 'left outer join VW_VFIN_CLIENTES_REF CLI on (CLI.BDCODCLI = LAN.BDCODCLI) ';
  wsql = wsql || 'left outer join VFIN_ESC_TCONTASBAN CTA on (CTA.BDCHAVECTABAN = LAN.BDCHAVECTABAN) ';
  wsql = wsql || 'left outer join VFIN_ESC_TLANCBANCARIOOBS LANOBS on (LANOBS.BDCHAVELAN = LAN.BDCHAVELAN) ';
  wsql = wsql || 'where lan.bdcodtipo <> 3008 and lan.bdchavefatura is null and lan.bdchavectapag is null ';
  wsql = wsql || 'and lan.bddatalan >= '||''''||:prdataini||''''||' and lan.bddatalan <= '||''''||:prdatafin||''''||' ';

  if (:prchavectaban <> '') then
     wsql = wsql || 'and LAN.BDCHAVECTABAN in ('|| :prchavectaban ||') ';

  wsql = wsql || ') FLUXO ';
  wsql = wsql || 'order by FLUXO.BDCHAVECTABAN, FLUXO.BDDATAVENC, FLUXO.BDDATARECPAG ';

  wchavectaban = 0;

  for execute statement :wsql
  into
  :bdtipo,
  :bdcodcli,
  :bdserie,
  :bdreffat,
  :bdchavectapag,
  :bdcodfor,
  :bdnomefor,
  :bdnumparc,
  :bdreflanc,
  :bdchavectaban,
  :bddatavenc,
  :bdvalorprev,
  :bdvalorreal,
  :bdobs,
  :bddatarecpag,
  :bddescctaban,
  :bdnomcli
  do
  begin
    if (:bdchavectaban <> wchavectaban) then
       begin
         wchavectaban = bdchavectaban;
         bdsaldoant = 0;
         bdsaldoatual = 0;
         wsaldoant = 0;

         wsql = 'select coalesce(sum(SAI.BDVALORLANC),0) - coalesce((select sum(ENT.BDVALORLANC) ';
         wsql = wsql ||                                              'from VFIN_ESC_TLANCBANCARIO ENT ';
         wsql = wsql ||                                              'where ENT.BDCHAVECTABAN = '||:bdchavectaban||' and ';
         wsql = wsql ||                                              '(ENT.BDDATALAN < '||''''||:prdataini||''''||') and ';
         wsql = wsql ||                                              'ENT.BDTIPOMOV = 1), 0) ';
         wsql = wsql || 'from VFIN_ESC_TLANCBANCARIO SAI where SAI.BDCHAVECTABAN = '||:bdchavectaban||' and ';
         wsql = wsql || '(SAI.BDDATALAN < '||''''||:prdataini||''''||') and ';
         wsql = wsql || 'SAI.BDTIPOMOV = 0';
         execute statement wsql into :wsaldoant;
       end

      if (bdtipo = 0) then
         begin
           bdsaldoatual = wsaldoant + bdvalorprev;
           bdsaldoant = wsaldoant;
           wsaldoant = wsaldoant + bdvalorprev;
         end
      else
        begin
          bdsaldoatual = wsaldoant - bdvalorprev;
          bdsaldoant = wsaldoant;
          wsaldoant = wsaldoant - bdvalorprev;
        end

      if (bdsaldoant is null) then
         bdsaldoant = 0;
      if (bdsaldoatual is null) then
         bdsaldoatual = 0;
    suspend;
  end

end^

SET TERM ; ^

SET TERM ^ ;

create or alter procedure SP_RELDEMRECDESP_RECPREV (
    PRTIPODEM integer,
    PRNIVEL integer,
    PRREFINI varchar(6),
    PRREFFIM varchar(6),
    PRCODOBRSER varchar(10240),
    PRCODCLI varchar(10240),
    PRMODELO integer,
    PRFLAGPROC integer)
as
declare variable VREFINI varchar(6);
declare variable VREFFIM varchar(6);
declare variable VPOSICAOPONTO integer;
declare variable VSQLSER varchar(10240);
declare variable VSQL varchar(10240);
declare variable VSTOP varchar(5);
declare variable VCLASSAUX varchar(60);
declare variable VCODSERDESPAUX integer;
declare variable VGUARDASERDESP varchar(10240);
declare variable VTIPOSERDESP integer;
declare variable VDESCSERDESP varchar(100);
declare variable VCLASSSERDESP varchar(60);
declare variable VCODSER integer;
declare variable VNUMPERIODO integer;
declare variable VPERIODO01 varchar(12);
declare variable VVLRPERIODO01 numeric(15,2);
declare variable VPERIODO02 varchar(12);
declare variable VVLRPERIODO02 numeric(15,2);
declare variable VPERIODO03 varchar(12);
declare variable VVLRPERIODO03 numeric(15,2);
declare variable VPERIODO04 varchar(12);
declare variable VVLRPERIODO04 numeric(15,2);
declare variable VPERIODO05 varchar(12);
declare variable VVLRPERIODO05 numeric(15,2);
declare variable VPERIODO06 varchar(12);
declare variable VVLRPERIODO06 numeric(15,2);
declare variable VPERIODO07 varchar(12);
declare variable VVLRPERIODO07 numeric(15,2);
declare variable VPERIODO08 varchar(12);
declare variable VVLRPERIODO08 numeric(15,2);
declare variable VPERIODO09 varchar(12);
declare variable VVLRPERIODO09 numeric(15,2);
declare variable VPERIODO10 varchar(12);
declare variable VVLRPERIODO10 numeric(15,2);
declare variable VPERIODO11 varchar(12);
declare variable VVLRPERIODO11 numeric(15,2);
declare variable VPERIODO12 varchar(12);
declare variable VVLRPERIODO12 numeric(15,2);
declare variable VVLRTOTPERIODO numeric(15,2);
declare variable VDESCONTO varchar(5);
declare variable VDATAREF varchar(10);
declare variable VSQLCLIENTES varchar(20000);
declare variable VCODCLIATUAL integer;
begin
  vguardaserdesp = '';
  vclassaux = '';
  vcodserdespaux = 0;
  vsql = '';
  vsqlser = '';
  vnumperiodo = 0;
  vRefIni = '';
  vRefFim = '';
  vperiodo01 = '';
  vvlrperiodo01 = 0;
  vperiodo02 = '';
  vvlrperiodo02 = 0;
  vperiodo03 = '';
  vvlrperiodo03 = 0;
  vperiodo04 = '';
  vvlrperiodo04 = 0;
  vperiodo05 = '';
  vvlrperiodo05 = 0;
  vperiodo06 = '';
  vvlrperiodo06 = 0;
  vperiodo07 = '';
  vvlrperiodo07 = 0;
  vperiodo08 = '';
  vvlrperiodo08 = 0;
  vperiodo09 = '';
  vvlrperiodo09 = 0;
  vperiodo10 = '';
  vvlrperiodo10 = 0;
  vperiodo11 = '';
  vvlrperiodo11 = 0;
  vperiodo12 = '';
  vvlrperiodo12 = 0;

  DELETE FROM TMP_DEMRECDESP_ANALITICAS;

  if (prModelo = 0) then
     -- somente para trazer um registro com cliente 0 para não ficar controlando se executa o laço de clientes ou não conforme o modelo
     vSqlClientes = 'select 0 as bdcodcli from vfin_base_tcliente ';
  else
    begin
      -- montar lista de clientes para posteriomente calcular o valor previsto por serviço/cliente por período
      vSqlClientes = 'select cli.bdcodcli from vfin_base_tcliente cli ';
      vSqlClientes = vSqlClientes || 'where exists ';
      vSqlClientes = vSqlClientes || ' (';
      vSqlClientes = vSqlClientes || '    select bdcodcli from TMP_VFIN_ESC_TSERVICOFATURADO serfat ';
      vSqlClientes = vSqlClientes || '    where (serfat.bdcodcli = cli.bdcodcli) and serfat.bdflagproc = '||PRFLAGPROC;
      vSqlClientes = vSqlClientes || ' )';
    
      IF ((:prcodcli <> '') AND (:prcodcli IS NOT NULL)) THEN
         vSqlClientes = vSqlClientes || 'and cli.bdcodcli in ('||:prcodcli||') ';
    end


    /* Antes de tudo, obter os serviços selecionados de acordo com as opções "títulos" e "analíticas".
    prnivel = 0: apenas a opção "títulos" está checada.
    prnivel = 1: apenas a opção "analíticas" está checada.
    prnivel = 2: ambas opções estão checadas. */
    
    IF (prnivel = 0) THEN
      BEGIN
        vsqlser = 'select s.bdcodobrser, s.bdclassificacao, s.bddescricao, s.bdtipo ';
        vsqlser = vsqlser || 'from (';
        vsqlser = vsqlser || '       select bdcodobrser, bdclassificacao, bddescricao, bdtipo ';
        vsqlser = vsqlser || '       from vct_base_servico ';
    
        IF (:prcodobrser <> '') THEN
            vsqlser = vsqlser || 'where bdcodobrser in ('||:prcodobrser||') ';
    
        vsqlser = vsqlser || '      ) ser ';
        vsqlser = vsqlser || 'left outer join vct_base_servico s on(s.bdclassificacao like (ser.bdclassificacao)||''%'') ';
    
        /* Se prnivel = 0 então apenas a opção "título" está selecionada. Neste caso
        iremos trazer também as analíticas para que seja feito o cálculo dos períodos.
        Posteriormente apenas exibimos as títulos no relatório. */
    
        vsqlser = vsqlser || 'group by bdcodobrser, bdclassificacao, bddescricao, bdtipo ';
        vsqlser = vsqlser || 'order by bdclassificacao ';
      END
    ELSE
     IF (prnivel = 1) THEN
        BEGIN
          /* Se apenas a opção "analíticas" está selecionada, então basta
          trazer as próprias analíticas selecionadas. */
          vsqlser = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bdtipo ';
          vsqlser = vsqlser || 'from vct_base_servico ser ';
          vsqlser = vsqlser || 'where ser.bdtipo = 1';
    
          IF (:prcodobrser <> '') THEN
             vsqlser = vsqlser || 'and ser.bdcodobrser in ('||:prcodobrser||') ';
    
          vsqlser = vsqlser || 'order by bdclassificacao ';
        END
     ELSE -- Então possui títulos e analíticas selecionadas
       IF (prnivel = 2) THEN
          BEGIN
            if (prcodobrser = '') then
               begin
                 vguardaserdesp = '';
                 vsqlser = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bdtipo ';
                 vsqlser = vsqlser || 'from vct_base_servico ser ';
                 vsqlser = vsqlser || 'order by bdclassificacao';
               end
            else
               begin
                /* Se títulos e analíticas foram selecionadas, deverá trazer as analíticas das títulos
                que estão selecionadas e também deverá trazer as títulos das analíticas que foram selecionadas.*/
    
                -- Primeiramente pegar as títulos que foram selecionadas
                vsql = 'select list(ser.bdcodobrser) from vct_base_servico ser ';
                vsql = vsql || 'where ser.bdtipo = 0 ';
    
                IF (:prcodobrser <> '') THEN
                   vsql = vsql || 'and ser.bdcodobrser in ('||:prcodobrser||') ';
                EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
    
                IF (vguardaserdesp IS NOT NULL) THEN
                   BEGIN
                     -- Em seguida, obter as analíticas destas títulos e guardar em vguardaservicos.
                     vsql = 'select s.bdcodobrser, s.bdclassificacao ';
                     vsql = vsql || 'from (';
                     vsql = vsql || '       select bdcodobrser, bdclassificacao, bddescricao ';
                     vsql = vsql || '       from vct_base_servico ';
                     vsql = vsql || '       where bdcodobrser in('||:vguardaserdesp||') ';
                     vsql = vsql || '      ) ser ';
                     vsql = vsql || 'left outer join vct_base_servico s on(s.bdclassificacao like (ser.bdclassificacao)||''%'')';
              
                     vguardaserdesp = '';
    
                     FOR
                     EXECUTE STATEMENT :vsql
                     INTO
                     :vCodSer,
                     :vclassserdesp
                     DO
                     BEGIN
                       vguardaserdesp = :vguardaserdesp||:vCodSer||',';
                     END
                   END
                ELSE
                  vguardaserdesp = '';
    
    
                -- Obtendo somente as analíticas selecionadas
                vsql = 'select ser.bdcodobrser, ser.bdclassificacao ';
                vsql = vsql || 'from (';
                vsql = vsql || 'select bdcodobrser, bdclassificacao ';
                vsql = vsql || 'from vct_base_servico ';
                vsql = vsql || 'where bdtipo = 1 ';
    
                IF (:prcodobrser <> '') THEN
                vsql = vsql || 'and bdcodobrser in ('||:prcodobrser||') ';
    
                vsql = vsql || ') ser ';
          
                FOR
                EXECUTE STATEMENT :vsql
                INTO
                :vCodSer,
                :vclassserdesp
                DO
                BEGIN
                  vstop = 'FALSE';
                  vguardaserdesp = :vguardaserdesp||:vCodSer||',';
                  vclassaux = :vclassserdesp;
      
                  /* A implementação abaixo vai removendo sempre o último nível da classificação
                  para obter todas as títulos que compoem a analítica, e vai guardando o código
                  de cada título na variável vguardaserdesp. */
                  WHILE (UPPER(:vstop) = 'FALSE') DO
                    BEGIN
                      SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto;
    
                      IF (vposicaoponto > 0) THEN
                         BEGIN
                           SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo a classificação
                           SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto; -- Localizando o primeiro ponto (sem a inversão seria o último ponto)
                           SELECT SUBSTRING(:vclassaux FROM :vposicaoponto +1 FOR CHAR_LENGTH(:vclassaux)) FROM rdb$database INTO :vclassaux; -- Selecionando o que vem depois do primeiro ponto
                           SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo novamente
    
                           SELECT COALESCE(bdcodobrser,0) FROM vct_base_servico WHERE bdclassificacao = :vclassaux INTO :vcodserdespaux;
    
                           IF ((vcodserdespaux > 0) and (position(vcodserdespaux, vguardaserdesp) = 0)) THEN
                              vguardaserdesp = :vguardaserdesp||:vcodserdespaux||',';
                         END
                      ELSE
                        BEGIN
                          vstop = 'TRUE';
                        END
                    END
                END
                vguardaserdesp = SUBSTRING(:vguardaserdesp FROM 1 FOR (CHAR_LENGTH(:vguardaserdesp) -1));
    
                -- Por fim, junta todos os serviços relacionados em um sql.
                vsqlser = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bdtipo ';
                vsqlser = vsqlser || 'from vct_base_servico ser ';
                vsqlser = vsqlser || 'where ser.bdcodobrser in ('||:vguardaserdesp||') ';
                vsqlser = vsqlser || 'order by bdclassificacao';
             end
          END


       -- Depois de ter obtido todos os serviços, trazer apenas os que possuem relação com a prévia do faturamento (tabela temporária que já está com os dados relativos aos filtros do relatório)
       if (:vguardaserdesp <> '') then
          begin
             vguardaserdesp = '';
             vsql = 'select list(ser.bdcodobrser) from ('||:vsqlser||') ser where ser.bdtipo = 1';
             EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
          end

       vsql = 'select ser.bdcodobrser, ser.bdclassificacao, ser.bddescricao, ser.bddesconto ';
       vsql = vsql || 'from vct_base_servico ser ';
       vsql = vsql || 'where exists ';
       vsql = vsql || ' (';
       vSql = vSql || '    select bdcodobrser from TMP_VFIN_ESC_TSERVICOFATURADO serfat ';
       vSql = vSql || '    where (serfat.bdcodobrser = ser.bdcodobrser) and serfat.bdflagproc = '||prflagproc;
       vsql = vsql || ' )';

       IF (:vguardaserdesp <> '') THEN
          vsql = vsql || 'and ser.bdcodobrser in ('||:vguardaserdesp||') ';


  /* Adicionar todas as analíticas em uma tabela temporária com os valores de seus períodos */
  FOR
  EXECUTE STATEMENT :vsql
  INTO
  :vCodSer,
  :vclassserdesp,
  :vdescserdesp,
  :vDesconto
  DO
  BEGIN
    vstop = 'FALSE';
    vRefIni = '';
    vRefFim = '';
    vnumperiodo = 0;
  
    WHILE (UPPER(vstop) = 'FALSE') DO
      BEGIN
        vnumperiodo = :vnumperiodo +1;
  
        IF (:prtipodem = 0) THEN -- Demonstrativo total
           BEGIN
             vRefIni       = :prrefini;
             vRefFim       = :prreffim;
             execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, 1, '', :prmodelo,prflagproc);
           END
        ELSE
          IF (:prtipodem = 1) THEN -- Demonstrativo mensal
             BEGIN
               IF (:vRefIni = '') THEN
                  BEGIN
                    vRefIni = prRefIni;
                  END
               ELSE
                 BEGIN
                   -- Incrementando a referência
                   vDataRef = substring(:vRefIni FROM 5 FOR 2)||'/01/'||substring(:vRefIni FROM 1 FOR 4);
                   SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vDataRef, 1) INTO :vDataRef;
                   vRefIni = SUBSTRING(:vDataRef FROM 1 FOR 4)||SUBSTRING(:vDataRef FROM 6 FOR 2);
                 END

                 vRefFim = vRefIni;

                 -- Guardando o período e o valor do período para posteriormente inserir um registro na tablela temporária contendo estas informações.
                 IF (:vnumperiodo = 1) THEN
                    BEGIN
                      vperiodo01 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, :vnumperiodo, vperiodo01, :prmodelo, prflagproc);
                    END
                 ELSE
                 IF (:vnumperiodo = 2) THEN
                    BEGIN
                      vperiodo02 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo02, :prmodelo, prflagproc);
                    END
                 ELSE
                 IF (:vnumperiodo = 3) THEN
                    BEGIN
                      vperiodo03 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo03, :prmodelo, prflagproc);
                    END
                 ELSE
                 IF (:vnumperiodo = 4) THEN
                    BEGIN
                      vperiodo04 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo04, :prmodelo, prflagproc);
                    END
                 ELSE
                 IF (:vnumperiodo = 5) THEN
                    BEGIN
                      vperiodo05 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo05, :prmodelo, prflagproc);
                    END
                 ELSE
                 IF (:vnumperiodo = 6) THEN
                    BEGIN
                      vperiodo06 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo06, :prmodelo, prflagproc);
                    END
                 ELSE
                 IF (:vnumperiodo = 7) THEN
                    BEGIN
                      vperiodo07 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo07, :prmodelo, prflagproc);
                    END
                 ELSE
                 IF (:vnumperiodo = 8) THEN
                    BEGIN
                      vperiodo08 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo08, :prmodelo, prflagproc);
                    END
                 ELSE
                 IF (:vnumperiodo = 9) THEN
                    BEGIN
                      vperiodo09 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo09, :prmodelo, prflagproc);
                    END
                 ELSE
                 IF (:vnumperiodo = 10) THEN
                    BEGIN
                      vperiodo10 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo10, :prmodelo, prflagproc);
                    END
                 ELSE
                 IF (:vnumperiodo = 11) THEN
                    BEGIN
                      vperiodo11 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo11, :prmodelo, prflagproc);
                    END
                 ELSE
                 IF (:vnumperiodo = 12) THEN
                    BEGIN
                      vperiodo12 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo12, :prmodelo, prflagproc);
                    END
             END
          ELSE
            IF (:prtipodem = 2) THEN -- Demonstrativo bimestral
               BEGIN
                 IF (:vRefIni = '') THEN
                    BEGIN
                      vRefIni = prRefIni;
                    END
                 ELSE
                   BEGIN
                     -- Por ser bimestral, deverá acrescentar dois meses á data
                     vDataRef = substring(:vRefIni FROM 5 FOR 2)||'/01/'||substring(:vRefIni FROM 1 FOR 4);
                     SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vDataRef, 2) INTO :vDataRef;
                     vRefIni = SUBSTRING(:vDataRef FROM 1 FOR 4)||SUBSTRING(:vDataRef FROM 6 FOR 2);
                   END

                 /* Acrescentando um mês à referência final com base na referência inicial e obtendo o último dia deste mês.
                 Ex: Se o período inicial for 01/01/2017, o período final deverá ser 28/02/2017 */
                 vDataRef = substring(:vRefIni FROM 5 FOR 2)||'/01/'||substring(:vRefIni FROM 1 FOR 4);
                 SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vDataRef, 1) INTO :vDataRef;
                 vRefFim = SUBSTRING(:vDataRef FROM 1 FOR 4)||SUBSTRING(:vDataRef FROM 6 FOR 2);

                 -- Guardando o período e o valor do período para posteriormente inserir um registro na tablela temporária contendo estas informações.
                 IF (:vnumperiodo = 1) THEN
                    BEGIN
                      vperiodo01 = '1º bimestre';
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo01, :prmodelo,prflagproc);
                    END
                 ELSE
                 IF (:vnumperiodo = 2) THEN
                    BEGIN
                      vperiodo02 = '2º bimestre';
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo02, :prmodelo,prflagproc);
                    END
                 ELSE
                 IF (:vnumperiodo = 3) THEN
                    BEGIN
                      vperiodo03 = '3º bimestre';
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo03, :prmodelo,prflagproc);
                    END
                 ELSE
                 IF (:vnumperiodo = 4) THEN
                    BEGIN
                      vperiodo04 = '4º bimestre';
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo04, :prmodelo,prflagproc);
                    END
                 ELSE
                 IF (:vnumperiodo = 5) THEN
                    BEGIN
                      vperiodo05 = '5º bimestre';
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo05, :prmodelo,prflagproc);
                    END
                 ELSE
                 IF (:vnumperiodo = 6) THEN
                    BEGIN
                      vperiodo06 = '6º bimestre';
                      execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo06, :prmodelo,prflagproc);
                    END
               END
            ELSE
              IF (:prtipodem = 3) THEN -- Demonstrativo trimestral
                 BEGIN
                   IF (:vRefIni = '') THEN
                     BEGIN
                        vRefIni = prRefIni;
                     END
                   ELSE
                     BEGIN
                       -- Por ser trimestral, deverá acrescentar três meses á data
                       vDataRef = substring(:vRefIni FROM 5 FOR 2)||'/01/'||substring(:vRefIni FROM 1 FOR 4);
                       SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vDataRef, 3) INTO :vDataRef;
                       vRefIni = SUBSTRING(:vDataRef FROM 1 FOR 4)||SUBSTRING(:vDataRef FROM 6 FOR 2);
                     END

                   /* Acrescentando três meses á referência final com base na referência inicial e obtendo o último dia deste mês.
                   Ex: Se o período inicial for 01/01/2017, o período final deverá ser 31/03/2017 */
                   vDataRef = substring(:vRefIni FROM 5 FOR 2)||'/01/'||substring(:vRefIni FROM 1 FOR 4);
                   SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vDataRef, 2) INTO :vDataRef;
                   vRefFim = SUBSTRING(:vDataRef FROM 1 FOR 4)||SUBSTRING(:vDataRef FROM 6 FOR 2);

                   -- Guardando o período e o valor do período para posteriormente inserir um registro na tablela temporária contendo estas informações.
                   IF (:vnumperiodo = 1) THEN
                      BEGIN
                        vperiodo01 = '1º trimestre';
                        execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo01, :prmodelo,prflagproc);
                      END
                   ELSE
                   IF (:vnumperiodo = 2) THEN
                      BEGIN
                        vperiodo02 = '2º trimestre';
                        execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo02, :prmodelo,prflagproc);
                      END
                   ELSE
                   IF (:vnumperiodo = 3) THEN
                      BEGIN
                        vperiodo03 = '3º trimestre';
                        execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo03, :prmodelo,prflagproc);
                      END
                   ELSE
                   IF (:vnumperiodo = 4) THEN
                      BEGIN
                        vperiodo04 = '4º trimestre';
                        execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo04, :prmodelo,prflagproc);
                      END
                 END
              ELSE
                IF (:prtipodem = 4) THEN -- Demonstrativo semestral
                   BEGIN
                     IF (:vRefIni = '') THEN
                       BEGIN
                         vRefIni = prRefIni;
                       END
                     ELSE
                       BEGIN
                         -- Por ser semestral, deverá acrescentar seis meses á data
                         vDataRef = substring(:vRefIni FROM 5 FOR 2)||'/01/'||substring(:vRefIni FROM 1 FOR 4);
                         SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vDataRef, 6) INTO :vDataRef;
                         vRefIni = SUBSTRING(:vDataRef FROM 1 FOR 4)||SUBSTRING(:vDataRef FROM 6 FOR 2);
                       END

                     /* Acrescentando cinco meses á referência final com base na referência inicial e obtendo o último dia deste mês.
                     Ex: Se o período inicial for 01/01/2017, o período final deverá ser 30/06/2017 */
                     vDataRef = substring(:vRefIni FROM 5 FOR 2)||'/01/'||substring(:vRefIni FROM 1 FOR 4);
                     SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vDataRef, 5) INTO :vDataRef;
                     vRefFim = SUBSTRING(:vDataRef FROM 1 FOR 4)||SUBSTRING(:vDataRef FROM 6 FOR 2);

                     -- Guardando o período e o valor do período para posteriormente inserir um registro na tablela temporária contendo estas informações.
                     IF (:vnumperiodo = 1) THEN
                        BEGIN
                          vperiodo01 = '1º semestre';
                          execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo01, :prmodelo, prflagproc);
                        END
                     ELSE
                     IF (:vnumperiodo = 2) THEN
                        BEGIN
                          vperiodo02 = '2º semestre';
                         execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo02, :prmodelo, prflagproc);
                        END
                   END
                ELSE
                  BEGIN
                    IF (:prtipodem = 5) THEN -- Desmonstrativo anual
                       BEGIN
                          IF (:vRefIni = '') THEN
                            BEGIN
                              vRefIni = prRefIni;
                            END
                         ELSE
                           BEGIN
                             -- Por ser anual, deverá acrescentar um ano á data
                             vDataRef = substring(:vRefIni FROM 5 FOR 2)||'/01/'||substring(:vRefIni FROM 1 FOR 4);
                             SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vDataRef, 12) INTO :vDataRef;
                             vRefIni = SUBSTRING(:vDataRef FROM 1 FOR 4)||SUBSTRING(:vDataRef FROM 6 FOR 2);
                           END

                         -- O último dia do ano sempre será 31/12/ + o ano que foi incrementado no vperiodoinicial
                        vRefFim = SUBSTRING(:vRefIni FROM 1 FOR 4)||'12';

                         -- Guardando o período e o valor do período para posteriormente inserir um registro na tablela temporária contendo estas informações.
                         IF (:vnumperiodo = 1) THEN
                            BEGIN
                              vperiodo01 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo01, :prmodelo, prflagproc);
                            END
                         ELSE
                         IF (:vnumperiodo = 2) THEN
                            BEGIN
                              vperiodo02 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo02, :prmodelo, prflagproc);
                            END
                         ELSE
                         IF (:vnumperiodo = 3) THEN
                            BEGIN
                              vperiodo03 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo03, :prmodelo, prflagproc);
                            END
                         ELSE
                         IF (:vnumperiodo = 4) THEN
                            BEGIN
                              vperiodo04 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo04, :prmodelo, prflagproc);
                            END
                         ELSE
                         IF (:vnumperiodo = 5) THEN
                            BEGIN
                              vperiodo05 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo05, :prmodelo, prflagproc);
                            END
                         ELSE
                         IF (:vnumperiodo = 6) THEN
                            BEGIN
                              vperiodo06 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo06, :prmodelo, prflagproc);
                            END
                         ELSE
                         IF (:vnumperiodo = 7) THEN
                            BEGIN
                              vperiodo07 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo07, :prmodelo, prflagproc);
                            END
                         ELSE
                         IF (:vnumperiodo = 8) THEN
                            BEGIN
                              vperiodo08 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo08, :prmodelo, prflagproc);
                            END
                         ELSE
                         IF (:vnumperiodo = 9) THEN
                            BEGIN
                              vperiodo09 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo09, :prmodelo, prflagproc);
                            END
                         ELSE
                         IF (:vnumperiodo = 10) THEN
                            BEGIN
                              vperiodo10 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo10, :prmodelo, prflagproc);
                            END
                         ELSE
                         IF (:vnumperiodo = 11) THEN
                            BEGIN
                              vperiodo11 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo11, :prmodelo, prflagproc);
                            END
                         ELSE
                         IF (:vnumperiodo = 12) THEN
                            BEGIN
                              vperiodo12 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totserprevperiodo(:vRefIni, :vRefFim, :vCodSer, :vclassserdesp, :vDesconto, vnumperiodo, vperiodo12, :prmodelo, prflagproc);
                            END
                       END
                  END

        IF (:vRefFim = :PRREFFIM) THEN
           vstop = 'TRUE';
      END
   END

   if (:vperiodo01 <> '') then
      update TMP_DEMRECDESP_ANALITICAS set BDPERIODO01 = :vperiodo01, BDVLRPERIODO01 = 0 where (bdperiodo01 is null) and (BDVLRPERIODO01 is null);
   if (:vperiodo02 <> '') then
      update TMP_DEMRECDESP_ANALITICAS set BDPERIODO02 = :vperiodo02, BDVLRPERIODO02 = 0 where (bdperiodo02 is null) and (BDVLRPERIODO02 is null);
    if (:vperiodo03 <> '') then
      update TMP_DEMRECDESP_ANALITICAS set BDPERIODO03 = :vperiodo03, BDVLRPERIODO03 = 0 where (bdperiodo03 is null) and (BDVLRPERIODO03 is null);
    if (:vperiodo04 <> '') then
      update TMP_DEMRECDESP_ANALITICAS set BDPERIODO04 = :vperiodo04, BDVLRPERIODO04 = 0 where (bdperiodo04 is null) and (BDVLRPERIODO04 is null);
    if (:vperiodo05 <> '') then
       update TMP_DEMRECDESP_ANALITICAS set BDPERIODO05 = :vperiodo05, BDVLRPERIODO05 = 0 where (bdperiodo05 is null) and (BDVLRPERIODO05 is null);
    if (:vperiodo06 <> '') then
       update TMP_DEMRECDESP_ANALITICAS set BDPERIODO06 = :vperiodo06, BDVLRPERIODO06 = 0 where (bdperiodo06 is null) and (BDVLRPERIODO06 is null);
    if (:vperiodo07 <> '') then
       update TMP_DEMRECDESP_ANALITICAS set BDPERIODO07 = :vperiodo07, BDVLRPERIODO07 = 0 where (bdperiodo07 is null) and (BDVLRPERIODO07 is null);
    if (:vperiodo08 <> '') then
       update TMP_DEMRECDESP_ANALITICAS set BDPERIODO08 = :vperiodo08, BDVLRPERIODO08 = 0 where (bdperiodo08 is null) and (BDVLRPERIODO08 is null);
    if (:vperiodo09 <> '') then
       update TMP_DEMRECDESP_ANALITICAS set BDPERIODO09 = :vperiodo09, BDVLRPERIODO09 = 0 where (bdperiodo09 is null) and (BDVLRPERIODO09 is null);
    if (:vperiodo10 <> '') then
        update TMP_DEMRECDESP_ANALITICAS set BDPERIODO10 = :vperiodo10, BDVLRPERIODO10 = 0 where (bdperiodo10 is null) and (BDVLRPERIODO10 is null);
    if (:vperiodo11 <> '') then
        update TMP_DEMRECDESP_ANALITICAS set BDPERIODO11 = :vperiodo11, BDVLRPERIODO11 = 0 where (bdperiodo11 is null) and (BDVLRPERIODO11 is null);
    if (:vperiodo12 <> '') then
        update TMP_DEMRECDESP_ANALITICAS set BDPERIODO12 = :vperiodo12, BDVLRPERIODO12 = 0 where (bdperiodo12 is null) and (BDVLRPERIODO12 is null);


   FOR
   EXECUTE STATEMENT :vSqlClientes
   INTO
   :vCodCliAtual
   DO
   BEGIN
       FOR
       EXECUTE STATEMENT :vsqlser
       INTO
       :vCodSer,
       :vclassserdesp,
       :vdescserdesp,
       :vtiposerdesp
       DO
       BEGIN
         if (:vtiposerdesp = 0) then
            begin
              vperiodo01    = '';
              vvlrperiodo01 = 0;
              vperiodo02    = '';
              vvlrperiodo02 = 0;
              vperiodo03    = '';
              vvlrperiodo03 = 0;
              vperiodo04    = '';
              vvlrperiodo04 = 0;
              vperiodo05    = '';
              vvlrperiodo05 = 0;
              vperiodo06    = '';
              vvlrperiodo06 = 0;
              vperiodo07    = '';
              vvlrperiodo07 = 0;
              vperiodo08    = '';
              vvlrperiodo08 = 0;
              vperiodo09    = '';
              vvlrperiodo09 = 0;
              vperiodo10    = '';
              vvlrperiodo10 = 0;
              vperiodo11    = '';
              vvlrperiodo11 = 0;
              vperiodo12    = '';
              vvlrperiodo12 = 0;

              vvlrtotperiodo = 0;

              SELECT bdperiodo01, SUM(bdvlrperiodo01) bdvlrperiodo01, bdperiodo02, SUM(bdvlrperiodo02) bdvlrperiodo02, bdperiodo03, SUM(bdvlrperiodo03) bdvlrperiodo03,
              bdperiodo04, SUM(bdvlrperiodo04) bdvlrperiodo04, bdperiodo05, SUM(bdvlrperiodo05) bdvlrperiodo05, bdperiodo06, SUM(bdvlrperiodo06) bdvlrperiodo06,
              bdperiodo07, SUM(bdvlrperiodo07) bdvlrperiodo07, bdperiodo08, SUM(bdvlrperiodo08) bdvlrperiodo08, bdperiodo09, SUM(bdvlrperiodo09) bdvlrperiodo09,
              bdperiodo10, SUM(bdvlrperiodo10) bdvlrperiodo10, bdperiodo11, SUM(bdvlrperiodo11) bdvlrperiodo11, bdperiodo12, SUM(bdvlrperiodo12) bdvlrperiodo12,
              SUM(bdvlrtotperiodo) bdvlrtotperiodo
              FROM TMP_DEMRECDESP_ANALITICAS
              WHERE bdtipo = 1 and bdcodclifor = :vCodCliAtual and bdclassificacao LIKE :vclassserdesp||'%' -- se for modelo realizado vCodCliForAtual virá 0!
              GROUP BY bdperiodo01, bdperiodo02, bdperiodo03, bdperiodo04, bdperiodo05, bdperiodo06, bdperiodo07,
              bdperiodo08, bdperiodo09, bdperiodo10, bdperiodo11, bdperiodo12
              INTO :vperiodo01, :vvlrperiodo01, :vperiodo02, :vvlrperiodo02, :vperiodo03, :vvlrperiodo03, :vperiodo04, :vvlrperiodo04,
                   :vperiodo05, :vvlrperiodo05, :vperiodo06, :vvlrperiodo06, :vperiodo07, :vvlrperiodo07, :vperiodo08, :vvlrperiodo08,
                   :vperiodo09, :vvlrperiodo09, :vperiodo10, :vvlrperiodo10, :vperiodo11, :vvlrperiodo11, :vperiodo12, :vvlrperiodo12,
                   :vvlrtotperiodo;
            
                 -- Serviços de desconto vem negativos
                IF (:vvlrtotperiodo <> 0) THEN
                   BEGIN
                     INSERT INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, bdcodclifor, BDCLASSIFICACAO, BDTIPO, BDPERIODO01, bdvlrperiodo01, BDPERIODO02, bdvlrperiodo02, BDPERIODO03, bdvlrperiodo03,
                                                            BDPERIODO04, bdvlrperiodo04, BDPERIODO05, bdvlrperiodo05, BDPERIODO06, bdvlrperiodo06,  BDPERIODO07, bdvlrperiodo07,
                                                            BDPERIODO08, bdvlrperiodo08, BDPERIODO09, bdvlrperiodo09, BDPERIODO10, bdvlrperiodo10, BDPERIODO11, bdvlrperiodo11,
                                                            BDPERIODO12, bdvlrperiodo12, BDVLRTOTPERIODO)
                     values(:vcodser, :vCodCliAtual, :vclassserdesp, :vtiposerdesp, :vperiodo01, :vvlrperiodo01, :vperiodo02, :vvlrperiodo02, :vperiodo03, :vvlrperiodo03, :vperiodo04, :vvlrperiodo04,
                            :vperiodo05, :vvlrperiodo05, :vperiodo06, :vvlrperiodo06, :vperiodo07, :vvlrperiodo07, :vperiodo08, :vvlrperiodo08, :vperiodo09, :vvlrperiodo09, :vperiodo10, :vvlrperiodo10,
                            :vperiodo11, :vvlrperiodo11, :vperiodo12, :vvlrperiodo12, :vvlrtotperiodo);
                   END
          end
       END
   end
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER procedure SP_RELDEMRECDESP_DESPPREV (
    PRCODESC varchar(500),
    PRTIPODEM integer,
    PRREFINI varchar(6),
    PRREFFIM varchar(6),
    PRCHAVECTABAN varchar(500),
    PRCODDESP varchar(10240),
    PRNIVEL integer,
    PRCODFOR varchar(10240),
    PRMODELO integer)
as
declare variable VREFINI varchar(6);
declare variable VREFFIM varchar(6);
declare variable VPOSICAOPONTO integer;
declare variable VSQLSERDESP varchar(10240);
declare variable VSQL varchar(10240);
declare variable VSTOP varchar(5);
declare variable VCLASSAUX varchar(60);
declare variable VCODSERDESPAUX integer;
declare variable VGUARDASERDESP varchar(10240);
declare variable VTIPOSERDESP integer;
declare variable VDESCSERDESP varchar(100);
declare variable VCLASSSERDESP varchar(60);
declare variable VCODDESP integer;
declare variable VNUMPERIODO integer;
declare variable VPERIODO01 varchar(12);
declare variable VVLRPERIODO01 numeric(15,2);
declare variable VPERIODO02 varchar(12);
declare variable VVLRPERIODO02 numeric(15,2);
declare variable VPERIODO03 varchar(12);
declare variable VVLRPERIODO03 numeric(15,2);
declare variable VPERIODO04 varchar(12);
declare variable VVLRPERIODO04 numeric(15,2);
declare variable VPERIODO05 varchar(12);
declare variable VVLRPERIODO05 numeric(15,2);
declare variable VPERIODO06 varchar(12);
declare variable VVLRPERIODO06 numeric(15,2);
declare variable VPERIODO07 varchar(12);
declare variable VVLRPERIODO07 numeric(15,2);
declare variable VPERIODO08 varchar(12);
declare variable VVLRPERIODO08 numeric(15,2);
declare variable VPERIODO09 varchar(12);
declare variable VVLRPERIODO09 numeric(15,2);
declare variable VPERIODO10 varchar(12);
declare variable VVLRPERIODO10 numeric(15,2);
declare variable VPERIODO11 varchar(12);
declare variable VVLRPERIODO11 numeric(15,2);
declare variable VPERIODO12 varchar(12);
declare variable VVLRPERIODO12 numeric(15,2);
declare variable VVLRTOTPERIODO numeric(15,2);
declare variable VDESCONTO varchar(5);
declare variable VDATAREF varchar(10);
declare variable VSQLFORNECEDORES varchar(2000);
declare variable VCODFORATUAL integer;
begin
  vguardaserdesp = '';
  vclassaux = '';
  vcodserdespaux = 0;
  vsql = '';
  vsqlserdesp = '';
  vnumperiodo = 0;
  vRefIni = '';
  vRefFim = '';

  vperiodo01 = '';
  vvlrperiodo01 = 0;
  vperiodo02 = '';
  vvlrperiodo02 = 0;
  vperiodo03 = '';
  vvlrperiodo03 = 0;
  vperiodo04 = '';
  vvlrperiodo04 = 0;
  vperiodo05 = '';
  vvlrperiodo05 = 0;
  vperiodo06 = '';
  vvlrperiodo06 = 0;
  vperiodo07 = '';
  vvlrperiodo07 = 0;
  vperiodo08 = '';
  vvlrperiodo08 = 0;
  vperiodo09 = '';
  vvlrperiodo09 = 0;
  vperiodo10 = '';
  vvlrperiodo10 = 0;
  vperiodo11 = '';
  vvlrperiodo11 = 0;
  vperiodo12 = '';
  vvlrperiodo12 = 0;
  DELETE FROM TMP_DEMRECDESP_ANALITICAS;

  if (prModelo = 0) then
     -- somente para trazer um registro com fornecedor 0 para não ficar controlando se executa o laço de fornecedores ou não, conforme o modelo
     vSqlFornecedores = 'select 0 as bdcodfor from vfin_base_tfornecedor ';
  else
    begin
      vSqlFornecedores = 'select forn.bdcodfor from VFIN_BASE_TFORNECEDOR forn ';
      vSqlFornecedores = vSqlFornecedores || 'where exists ';
      vSqlFornecedores = vSqlFornecedores || ' (';
      vSqlFornecedores = vSqlFornecedores || 'select cp.bdcodfor from vfin_esc_tcontasapagar cp ';
      vSqlFornecedores = vSqlFornecedores || 'inner join VFIN_ESC_TCONTASPAGARDESP cpd on (cpd.bdcodesc = cp.bdcodesc and cpd.bdchavectapag = cp.bdchavectapag) ';
      vSqlFornecedores = vSqlFornecedores || 'where cp.bdcodfor = forn.bdcodfor ';
    
      if ((:prcodesc <> '') and (:prcodesc is not null)) then
         vSqlFornecedores = vSqlFornecedores || 'and cp.bdcodesc in ('||:prcodesc||') ';
    
      IF ((:prchavectaban <> '') AND (:prchavectaban IS NOT NULL)) THEN
         vSqlFornecedores = vSqlFornecedores || 'and cp.bdchavectaban in ('||:prchavectaban||') ';
    
      IF (:prcoddesp <> '') THEN
         vSqlFornecedores = vSqlFornecedores || 'and cpd.bdcoddesp in ('||:prcoddesp||') ';
      vSqlFornecedores = vSqlFornecedores || ' )';
    
      IF ((:prcodfor <> '') AND (:prcodfor IS NOT NULL)) THEN
          vSqlFornecedores = vSqlFornecedores || 'and forn.bdcodfor in ('||:prcodfor||') ';
    end


  IF (prnivel = 0) THEN -- Então só possui títulos selecionadas
     BEGIN
       vsqlserdesp = 'select d.bdcoddesp, d.bdclassdesp, d.bddescdesp, d.bdtipodesp ';
       vsqlserdesp = vsqlserdesp || 'from (';
       vsqlserdesp = vsqlserdesp || '       select bdcoddesp, bdclassdesp, bddescdesp, bdtipodesp ';
       vsqlserdesp = vsqlserdesp || '       from vfin_base_tdespesa ';

       IF (:prcoddesp <> '') THEN
          vsqlserdesp = vsqlserdesp || 'where bdcoddesp in ('||:prcoddesp||') ';

       vsqlserdesp = vsqlserdesp || '      ) desp ';
       vsqlserdesp = vsqlserdesp || 'left outer join vfin_base_tdespesa d on(d.bdclassdesp like (desp.bdclassdesp)||''%'')';

       /* Se prnivel = 0 então apenas a opção "título" está selecionada. Neste caso
       iremos trazer também as analíticas para que seja feito o cálculo dos períodos.
       Posteriormente apenas exibimos as títulos no relatório. */

       vsqlserdesp = vsqlserdesp || 'group by bdcoddesp, bdclassdesp, bddescdesp, bdtipodesp ';
       vsqlserdesp = vsqlserdesp || 'order by bdclassdesp ';
     END
  ELSE
    IF (prnivel = 1) THEN -- Então só possui analíticas selecionadas
       BEGIN
         /* Se apenas a opção "analíticas" está selecionada, então basta
         trazer as próprias analíticas selecionadas. */
         vsqlserdesp = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, desp.bdtipodesp ';
         vsqlserdesp = vsqlserdesp || 'from vfin_base_tdespesa desp ';
         vsqlserdesp = vsqlserdesp || 'where desp.bdtipodesp = 1 ';

         IF (:prcoddesp <> '') THEN
            vsqlserdesp = vsqlserdesp || 'and desp.bdcoddesp in ('||:prcoddesp||') ';

         vsqlserdesp = vsqlserdesp || 'order by bdclassdesp ';
       END
    ELSE -- Então possui títulos e analíticas selecionadas, e obrigatoriamente as duas opções "títulos" e "analíticas" estão checadas.
      IF (prnivel = 2) THEN
         BEGIN

            if (prcoddesp = '') then
               begin
                 vguardaserdesp = '';
                 vsqlserdesp = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, desp.bdtipodesp ';
                 vsqlserdesp = vsqlserdesp || 'from vfin_base_tdespesa desp ';
                 vsqlserdesp = vsqlserdesp || 'order by bdclassdesp';
               end
            else
               begin
                   /* Se títulos e analíticas foram selecionadas, deverá trazer as analíticas das títulos
                   que estão selecionadas e também deverá trazer as títulos das analíticas que foram selecionadas.*/
        
                   -- Primeiramente pegar as títulos que foram selecionadas
                   vsql = 'select list(desp.bdcoddesp) from vfin_base_tdespesa desp ';
                   vsql = vsql || 'where desp.bdtipodesp = 0 ';
    
                   IF (:prcoddesp <> '') THEN
                      vsql = vsql || 'and desp.bdcoddesp in ('||:prcoddesp||')';
    
                   EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
          
                   IF (vguardaserdesp IS NOT NULL) THEN
                      BEGIN
                        -- Em seguida, obter as analíticas destas títulos e guardar em vguardaservicos.
                        vsql = 'select d.bdcoddesp, d.bdclassdesp ';
                        vsql = vsql || 'from (';
                        vsql = vsql || '       select bdcoddesp, bdclassdesp, bddescdesp ';
                        vsql = vsql || '       from vfin_base_tdespesa ';
                        vsql = vsql || '       where bdcoddesp in('||:vguardaserdesp||') ';
                        vsql = vsql || '      ) desp ';
                        vsql = vsql || 'left outer join vfin_base_tdespesa d on(d.bdclassdesp like (desp.bdclassdesp)||''%'')';
               
                        vguardaserdesp = '';
                     
                        FOR
                        EXECUTE STATEMENT :vsql
                        INTO
                        :vcoddesp,
                        :vclassserdesp
                        DO
                        BEGIN
                          vguardaserdesp = :vguardaserdesp||:vcoddesp||',';
                        END
                      END
                   ELSE
                     vguardaserdesp = '';
    
                   -- Obtendo somente as analíticas selecionadas
                   vsql = 'select desp.bdcoddesp, desp.bdclassdesp ';
                   vsql = vsql || 'from (';
                   vsql = vsql || 'select bdcoddesp, bdclassdesp ';
                   vsql = vsql || 'from vfin_base_tdespesa ';
                   vsql = vsql || 'where bdtipodesp = 1';
    
                   IF (:prcoddesp <> '') THEN
                      vsql = vsql || 'and bdcoddesp in ('||:prcoddesp||') ';
    
                   vsql = vsql || ') desp ';
        
                   FOR
                   EXECUTE STATEMENT :vsql
                   INTO
                   :vcoddesp,
                   :vclassserdesp
                   DO
                   BEGIN
                     vstop = 'FALSE';
                     vguardaserdesp = :vguardaserdesp||:vcoddesp||',';
                     vclassaux = :vclassserdesp;
              
                     /* A implementação abaixo vai removendo sempre o último nível da classificação
                     para obter todas as títulos que compoem a analítica, e vai guardando o código
                     de cada título na variável vguardaserdesp. */
                     WHILE (UPPER(:vstop) = 'FALSE') DO
                       BEGIN
                         SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto;
              
                         IF (vposicaoponto > 0) THEN
                            BEGIN
                              SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo a classificação
                              SELECT POSITION('.', CAST(:vclassaux AS VARCHAR(60))) FROM rdb$database INTO :vposicaoponto; -- Localizando o primeiro ponto (sem a inversão seria o último ponto)
                              SELECT SUBSTRING(:vclassaux FROM :vposicaoponto +1 FOR CHAR_LENGTH(:vclassaux)) FROM rdb$database INTO :vclassaux; -- Selecionando o que vem depois do primeiro ponto
                              SELECT REVERSE(:vclassaux) FROM rdb$database INTO :vclassaux; -- Invertendo novamente
                              SELECT first 1 COALESCE(bdcoddesp,0) FROM vfin_base_tdespesa WHERE bdclassdesp = :vclassaux INTO :vcodserdespaux;
                              IF ((vcodserdespaux > 0) and (position(vcodserdespaux, vguardaserdesp) = 0)) THEN
                                 vguardaserdesp = :vguardaserdesp||:vcodserdespaux||',';
                            END
                         ELSE
                           BEGIN
                             vstop = 'TRUE';
                           END
                       END
                   END
    
                   vguardaserdesp = SUBSTRING(:vguardaserdesp FROM 1 FOR (CHAR_LENGTH(:vguardaserdesp) -1));
            
                   -- Por fim, junta todos as despesas relacionados em um sql.
                   vsqlserdesp = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, desp.bdtipodesp ';
                   vsqlserdesp = vsqlserdesp || 'from vfin_base_tdespesa desp ';
                   vsqlserdesp = vsqlserdesp || 'where desp.bdcoddesp in ('||:vguardaserdesp||') ';
                   vsqlserdesp = vsqlserdesp || 'order by bdclassdesp';
            end
         END



  -- Depois de ter obtido todos as despesas, trazer apenas os que possuem relação com os lançamentos de contas a pagar.
  if (vguardaserdesp <> '') then
     begin
        vguardaserdesp = '';
        vsql = 'select list(desp.bdcoddesp) from ('||:vsqlserdesp||') desp where desp.bdtipodesp = 1';
        EXECUTE STATEMENT :vsql INTO :vguardaserdesp;
     end

  vsql = 'select desp.bdcoddesp, desp.bdclassdesp, desp.bddescdesp, desp.bddesconto bddesconto ';
  vsql = vsql || 'from vfin_base_tdespesa desp ';
  vsql = vsql || 'where exists ';
  vsql = vsql || ' (';

  vSql = vSql || 'select cpd.bdcoddesp from vfin_esc_tcontaspagardesp cpd ';
  vSql = vSql || 'inner join vfin_esc_tcontasapagar cp on (cp.bdcodesc = cpd.bdcodesc and cp.bdchavectapag = cpd.bdchavectapag) ';
  vSql = vSql || 'where cpd.bdcoddesp = desp.bdcoddesp ';

  if ((:prcodesc <> '') and (:prcodesc is not null)) then
     vsql = vsql || 'and cp.bdcodesc in ('||:prcodesc||') ';

  IF ((:prchavectaban <> '') AND (:prchavectaban IS NOT NULL)) THEN
     vsql = vsql || 'and cp.bdchavectaban in ('||:prchavectaban||') ';

   IF ((:prcodfor <> '') AND (:prcodfor IS NOT NULL)) THEN
      vsql = vsql || 'and cp.bdcodfor in ('||:prcodfor||') ';

  vsql = vsql || ' )';

  IF (:vguardaserdesp <> '') THEN
     vsql = vsql || 'and desp.bdcoddesp in ('||:vguardaserdesp||') ';


  /* Adicionar todas as analíticas em uma tabela temporária com os valores de seus períodos */
  FOR
  EXECUTE STATEMENT :vsql
  INTO
  :vcoddesp,
  :vclassserdesp,
  :vdescserdesp,
  :vDesconto
  DO
  BEGIN
    vstop = 'FALSE';
    vRefIni = '';
    vRefFim = '';
    vnumperiodo = 0;
  
    WHILE (UPPER(vstop) = 'FALSE') DO
      BEGIN
        vnumperiodo = :vnumperiodo +1;
  
        IF (:prtipodem = 0) THEN -- Demonstrativo total
           BEGIN
             vRefIni = :prRefIni;
             vRefFim = :prRefFim;
             execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, 1, '', :prmodelo);
           END
        ELSE
          IF (:prtipodem = 1) THEN -- Demonstrativo mensal
             BEGIN
               IF (:vRefIni = '') THEN
                  BEGIN
                    vRefIni = prRefIni;
                  END
               ELSE
                 BEGIN
                   -- Acrescentando um mês a referência
                   vDataRef = substring(:vRefIni FROM 5 FOR 2)||'/01/'||substring(:vRefIni FROM 1 FOR 4);
                   SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vDataRef, 1) INTO :vDataRef;
                   vRefIni = SUBSTRING(:vDataRef FROM 1 FOR 4)||SUBSTRING(:vDataRef FROM 6 FOR 2);
                 END

                 vRefFim = vRefIni;

                  -- Guardando o período e o valor do período para posteriormente inserir um registro na tablela temporária contendo estas informações.
                 IF (:vnumperiodo = 1) THEN
                    BEGIN
                      vperiodo01 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo01, :prmodelo);
                     END
                 ELSE
                 IF (:vnumperiodo = 2) THEN
                    BEGIN
                      vperiodo02 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo02, :prmodelo);
                    END
                 ELSE
                 IF (:vnumperiodo = 3) THEN
                    BEGIN
                      vperiodo03 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo03, :prmodelo);
                    END
                 ELSE
                 IF (:vnumperiodo = 4) THEN
                    BEGIN
                      vperiodo04 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo04, :prmodelo);
                    END
                 ELSE
                 IF (:vnumperiodo = 5) THEN
                    BEGIN
                      vperiodo05 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo05, :prmodelo);
                    END
                 ELSE
                 IF (:vnumperiodo = 6) THEN
                    BEGIN
                      vperiodo06 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo06, :prmodelo);
                    END
                 ELSE
                 IF (:vnumperiodo = 7) THEN
                    BEGIN
                      vperiodo07 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo07, :prmodelo);
                    END
                 ELSE
                 IF (:vnumperiodo = 8) THEN
                    BEGIN
                      vperiodo08 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo08, :prmodelo);
                    END
                 ELSE
                 IF (:vnumperiodo = 9) THEN
                    BEGIN
                      vperiodo09 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo09, :prmodelo);
                    END
                 ELSE
                 IF (:vnumperiodo = 10) THEN
                    BEGIN
                      vperiodo10 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo10, :prmodelo);
                    END
                 ELSE
                 IF (:vnumperiodo = 11) THEN
                    BEGIN
                      vperiodo11 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo11, :prmodelo);
                    END
                 ELSE
                 IF (:vnumperiodo = 12) THEN
                    BEGIN
                      vperiodo12 = SUBSTRING(:vRefIni FROM 5 FOR 2)||'/'||SUBSTRING(:vRefIni FROM 1 FOR 4);
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo12, :prmodelo);
                    END
             END
          ELSE
            IF (:prtipodem = 2) THEN -- Demonstrativo bimestral
               BEGIN
                 IF (:vRefIni = '') THEN
                    BEGIN
                     vRefIni = prRefIni;
                    END
                 ELSE
                   BEGIN
                     -- Por ser bimestral, deverá acrescentar dois meses á data
                     vDataRef = substring(:vRefIni FROM 5 FOR 2)||'/01/'||substring(:vRefIni FROM 1 FOR 4);
                     SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vDataRef, 2) INTO :vDataRef;
                     vRefIni = SUBSTRING(:vDataRef FROM 1 FOR 4)||SUBSTRING(:vDataRef FROM 6 FOR 2);
                   END

                 /* Acrescentando um mês á referência final com base na referência inicial e obtendo o último dia deste mês.
                 Ex: Se o período inicial for 01/01/2017, o período final deverá ser 28/02/2017 */
                 vDataRef = substring(:vRefIni FROM 5 FOR 2)||'/01/'||substring(:vRefIni FROM 1 FOR 4);
                 SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vDataRef, 1) INTO :vDataRef;
                 vRefFim = SUBSTRING(:vDataRef FROM 1 FOR 4)||SUBSTRING(:vDataRef FROM 6 FOR 2);

                 -- Guardando o período e o valor do período para posteriormente inserir um registro na tablela temporária contendo estas informações.
                 IF (:vnumperiodo = 1) THEN
                    BEGIN
                      vperiodo01 = '1º bimestre';
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo01, :prmodelo);
                    END
                 ELSE
                 IF (:vnumperiodo = 2) THEN
                    BEGIN
                      vperiodo02 = '2º bimestre';
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo02, :prmodelo);
                    END
                 ELSE
                 IF (:vnumperiodo = 3) THEN
                    BEGIN
                      vperiodo03 = '3º bimestre';
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo03, :prmodelo);
                    END
                 ELSE
                 IF (:vnumperiodo = 4) THEN
                    BEGIN
                      vperiodo04 = '4º bimestre';
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo04, :prmodelo);
                    END
                 ELSE
                 IF (:vnumperiodo = 5) THEN
                    BEGIN
                      vperiodo05 = '5º bimestre';
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo05, :prmodelo);
                    END
                 ELSE
                 IF (:vnumperiodo = 6) THEN
                    BEGIN
                      vperiodo06 = '6º bimestre';
                      execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo06, :prmodelo);
                    END
               END
            ELSE
              IF (:prtipodem = 3) THEN -- Demonstrativo trimestral
                 BEGIN
                   IF (:vRefIni = '') THEN
                       BEGIN
                         vRefIni = :prRefIni;
                       END
                   ELSE
                     BEGIN
                       -- Por ser trimestral, deverá acrescentar três meses á data
                       vDataRef = substring(:vRefIni FROM 5 FOR 2)||'/01/'||substring(:vRefIni FROM 1 FOR 4);
                       SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vDataRef, 3) INTO :vDataRef;
                       vRefIni = SUBSTRING(:vDataRef FROM 1 FOR 4)||SUBSTRING(:vDataRef FROM 6 FOR 2);
                     END

                   /* Acrescentando três meses á referência final com base na referência inicial e obtendo o último dia deste mês.
                   Ex: Se o período inicial for 01/01/2017, o período final deverá ser 31/03/2017 */
                   vDataRef = substring(:vRefIni FROM 5 FOR 2)||'/01/'||substring(:vRefIni FROM 1 FOR 4);
                   SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vDataRef, 2) INTO :vDataRef;
                   vRefFim = SUBSTRING(:vDataRef FROM 1 FOR 4)||SUBSTRING(:vDataRef FROM 6 FOR 2);

                   -- Guardando o período e o valor do período para posteriormente inserir um registro na tablela temporária contendo estas informações.
                   IF (:vnumperiodo = 1) THEN
                      BEGIN
                        vperiodo01 = '1º trimestre';
                        execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo01, :prmodelo);
                      END
                   ELSE
                   IF (:vnumperiodo = 2) THEN
                      BEGIN
                        vperiodo02 = '2º trimestre';
                        execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo02, :prmodelo);
                      END
                   ELSE
                   IF (:vnumperiodo = 3) THEN
                      BEGIN
                        vperiodo03 = '3º trimestre';
                        execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo03, :prmodelo);
                      END
                   ELSE
                   IF (:vnumperiodo = 4) THEN
                      BEGIN
                        vperiodo04 = '4º trimestre';
                        execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo04, :prmodelo);
                      END
                 END
              ELSE
                IF (:prtipodem = 4) THEN -- Demonstrativo semestral
                   BEGIN
                     IF (:vRefIni = '') THEN
                       BEGIN
                         vRefIni = :prRefIni;
                       END
                     ELSE
                       BEGIN
                         -- Por ser semestral, deverá acrescentar seis meses á data
                         vDataRef = substring(:vRefIni FROM 5 FOR 2)||'/01/'||substring(:vRefIni FROM 1 FOR 4);
                         SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vDataRef, 6) INTO :vDataRef;
                         vRefIni = SUBSTRING(:vDataRef FROM 1 FOR 4)||SUBSTRING(:vDataRef FROM 6 FOR 2);
                       END

                     /* Acrescentando cinco meses á referência final com base na referência inicial e obtendo o último dia deste mês.
                     Ex: Se o período inicial for 01/01/2017, o período final deverá ser 30/06/2017 */
                     vDataRef = substring(:vRefIni FROM 5 FOR 2)||'/01/'||substring(:vRefIni FROM 1 FOR 4);
                     SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vDataRef, 5) INTO :vDataRef;
                     vRefFim = SUBSTRING(:vDataRef FROM 1 FOR 4)||SUBSTRING(:vDataRef FROM 6 FOR 2);
  
                     -- Guardando o período e o valor do período para posteriormente inserir um registro na tablela temporária contendo estas informações.
                     IF (:vnumperiodo = 1) THEN
                        BEGIN
                          vperiodo01 = '1º semestre';
                          execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo01, :prmodelo);
                        END
                     ELSE
                     IF (:vnumperiodo = 2) THEN
                        BEGIN
                          vperiodo02 = '2º semestre';
                          execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo02, :prmodelo);
                        END
                   END
                ELSE
                  BEGIN
                    IF (:prtipodem = 5) THEN -- Desmonstrativo anual
                       BEGIN
                         IF (:vRefIni  = '') THEN
                             BEGIN
                               vRefIni = :prRefIni;
                             END
                         ELSE
                           BEGIN
                             -- Por ser anual, deverá acrescentar um ano á data
                             vDataRef = substring(:vRefIni FROM 5 FOR 2)||'/01/'||substring(:vRefIni FROM 1 FOR 4);
                             SELECT CAST(bdnovadata AS VARCHAR(10)) FROM add_meses(:vDataRef, 12) INTO :vDataRef;
                             vRefIni = SUBSTRING(:vDataRef FROM 1 FOR 4)||SUBSTRING(:vDataRef FROM 6 FOR 2);
                           END

                         vRefFim = SUBSTRING(:vRefIni FROM 1 FOR 4)||'12';
             
                         -- Guardando o período e o valor do período para posteriormente inserir um registro na tablela temporária contendo estas informações.
                         IF (:vnumperiodo = 1) THEN
                            BEGIN
                              vperiodo01 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo01, :prmodelo);
                            END
                         ELSE
                         IF (:vnumperiodo = 2) THEN
                            BEGIN
                              vperiodo02 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo02, :prmodelo);
                            END
                         ELSE
                         IF (:vnumperiodo = 3) THEN
                            BEGIN
                              vperiodo03 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo03, :prmodelo);
                            END
                         ELSE
                         IF (:vnumperiodo = 4) THEN
                            BEGIN
                              vperiodo04 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo04, :prmodelo);
                            END
                         ELSE
                         IF (:vnumperiodo = 5) THEN
                            BEGIN
                              vperiodo05 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo05, :prmodelo);
                            END
                         ELSE
                         IF (:vnumperiodo = 6) THEN
                            BEGIN
                              vperiodo06 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo06, :prmodelo);
                            END
                         ELSE
                         IF (:vnumperiodo = 7) THEN
                            BEGIN
                              vperiodo07 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo07, :prmodelo);
                            END
                         ELSE
                         IF (:vnumperiodo = 8) THEN
                            BEGIN
                              vperiodo08 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo08, :prmodelo);
                            END
                         ELSE
                         IF (:vnumperiodo = 9) THEN
                            BEGIN
                              vperiodo09 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo09, :prmodelo);
                            END
                         ELSE
                         IF (:vnumperiodo = 10) THEN
                            BEGIN
                              vperiodo10 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo10, :prmodelo);
                            END
                         ELSE
                         IF (:vnumperiodo = 11) THEN
                            BEGIN
                              vperiodo11 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo11, :prmodelo);
                            END
                         ELSE
                         IF (:vnumperiodo = 12) THEN
                            BEGIN
                              vperiodo12 = SUBSTRING(:vRefIni FROM 1 FOR 4);
                              execute procedure sp_totdespprevperiodo(:prCodEsc, :vRefIni, :vRefFim, :prchavectaban, :vcoddesp, :prcodfor, :vclassserdesp, :vdesconto, vnumperiodo, vperiodo12, :prmodelo);
                            END
                       END
                  END

        IF (:vRefFim = :prRefFim) THEN
           vstop = 'TRUE';
      END
   END

   if (:vperiodo01 <> '') then
      update TMP_DEMRECDESP_ANALITICAS set BDPERIODO01 = :vperiodo01, BDVLRPERIODO01 = 0 where (bdperiodo01 is null) and (BDVLRPERIODO01 is null);
   if (:vperiodo02 <> '') then
      update TMP_DEMRECDESP_ANALITICAS set BDPERIODO02 = :vperiodo02, BDVLRPERIODO02 = 0 where (bdperiodo02 is null) and (BDVLRPERIODO02 is null);
   if (:vperiodo03 <> '') then
      update TMP_DEMRECDESP_ANALITICAS set BDPERIODO03 = :vperiodo03, BDVLRPERIODO03 = 0 where (bdperiodo03 is null) and (BDVLRPERIODO03 is null);
   if (:vperiodo04 <> '') then
      update TMP_DEMRECDESP_ANALITICAS set BDPERIODO04 = :vperiodo04, BDVLRPERIODO04 = 0 where (bdperiodo04 is null) and (BDVLRPERIODO04 is null);
   if (:vperiodo05 <> '') then
      update TMP_DEMRECDESP_ANALITICAS set BDPERIODO05 = :vperiodo05, BDVLRPERIODO05 = 0 where (bdperiodo05 is null) and (BDVLRPERIODO05 is null);
   if (:vperiodo06 <> '') then
      update TMP_DEMRECDESP_ANALITICAS set BDPERIODO06 = :vperiodo06, BDVLRPERIODO06 = 0 where (bdperiodo06 is null) and (BDVLRPERIODO06 is null);
   if (:vperiodo07 <> '') then
      update TMP_DEMRECDESP_ANALITICAS set BDPERIODO07 = :vperiodo07, BDVLRPERIODO07 = 0 where (bdperiodo07 is null) and (BDVLRPERIODO07 is null);
   if (:vperiodo08 <> '') then
      update TMP_DEMRECDESP_ANALITICAS set BDPERIODO08 = :vperiodo08, BDVLRPERIODO08 = 0 where (bdperiodo08 is null) and (BDVLRPERIODO08 is null);
   if (:vperiodo09 <> '') then
      update TMP_DEMRECDESP_ANALITICAS set BDPERIODO09 = :vperiodo09, BDVLRPERIODO09 = 0 where (bdperiodo09 is null) and (BDVLRPERIODO09 is null);
   if (:vperiodo10 <> '') then
      update TMP_DEMRECDESP_ANALITICAS set BDPERIODO10 = :vperiodo10, BDVLRPERIODO10 = 0 where (bdperiodo10 is null) and (BDVLRPERIODO10 is null);
   if (:vperiodo11 <> '') then
      update TMP_DEMRECDESP_ANALITICAS set BDPERIODO11 = :vperiodo11, BDVLRPERIODO11 = 0 where (bdperiodo11 is null) and (BDVLRPERIODO11 is null);
   if (:vperiodo12 <> '') then
      update TMP_DEMRECDESP_ANALITICAS set BDPERIODO12 = :vperiodo12, BDVLRPERIODO12 = 0 where (bdperiodo12 is null) and (BDVLRPERIODO12 is null);

   FOR
   EXECUTE STATEMENT :vSqlFornecedores
   INTO
   :vCodForAtual
   DO
   BEGIN
     FOR
     EXECUTE STATEMENT :vsqlserdesp
     INTO
     :vcoddesp,
     :vclassserdesp,
     :vdescserdesp,
     :vtiposerdesp
     DO
     BEGIN
       if (:vtiposerdesp = 0) then
         begin
           vperiodo01    = '';
           vvlrperiodo01 = 0;
           vperiodo02    = '';
           vvlrperiodo02 = 0;
           vperiodo03    = '';
           vvlrperiodo03 = 0;
           vperiodo04    = '';
           vvlrperiodo04 = 0;
           vperiodo05    = '';
           vvlrperiodo05 = 0;
           vperiodo06    = '';
           vvlrperiodo06 = 0;
           vperiodo07    = '';
           vvlrperiodo07 = 0;
           vperiodo08    = '';
           vvlrperiodo08 = 0;
           vperiodo09    = '';
           vvlrperiodo09 = 0;
           vperiodo10    = '';
           vvlrperiodo10 = 0;
           vperiodo11    = '';
           vvlrperiodo11 = 0;
           vperiodo12    = '';
           vvlrperiodo12 = 0;

           vvlrtotperiodo = 0;

           SELECT bdperiodo01, SUM(bdvlrperiodo01) bdvlrperiodo01, bdperiodo02, SUM(bdvlrperiodo02) bdvlrperiodo02, bdperiodo03, SUM(bdvlrperiodo03) bdvlrperiodo03,
                  bdperiodo04, SUM(bdvlrperiodo04) bdvlrperiodo04, bdperiodo05, SUM(bdvlrperiodo05) bdvlrperiodo05, bdperiodo06, SUM(bdvlrperiodo06) bdvlrperiodo06,
                  bdperiodo07, SUM(bdvlrperiodo07) bdvlrperiodo07, bdperiodo08, SUM(bdvlrperiodo08) bdvlrperiodo08, bdperiodo09, SUM(bdvlrperiodo09) bdvlrperiodo09,
                  bdperiodo10, SUM(bdvlrperiodo10) bdvlrperiodo10, bdperiodo11, SUM(bdvlrperiodo11) bdvlrperiodo11, bdperiodo12, SUM(bdvlrperiodo12) bdvlrperiodo12,
                  SUM(bdvlrtotperiodo) bdvlrtotperiodo
           FROM TMP_DEMRECDESP_ANALITICAS
           WHERE bdtipo = 1 and bdcodclifor = :vCodForAtual and bdclassificacao LIKE :vclassserdesp||'%' -- se for modelo realizado vCodCliForAtual virá 0!
           GROUP BY bdperiodo01, bdperiodo02, bdperiodo03, bdperiodo04, bdperiodo05, bdperiodo06, bdperiodo07,
           bdperiodo08, bdperiodo09, bdperiodo10, bdperiodo11, bdperiodo12
           INTO :vperiodo01, :vvlrperiodo01, :vperiodo02, :vvlrperiodo02, :vperiodo03, :vvlrperiodo03, :vperiodo04, :vvlrperiodo04,
                :vperiodo05, :vvlrperiodo05, :vperiodo06, :vvlrperiodo06, :vperiodo07, :vvlrperiodo07, :vperiodo08, :vvlrperiodo08,
                :vperiodo09, :vvlrperiodo09, :vperiodo10, :vvlrperiodo10, :vperiodo11, :vvlrperiodo11, :vperiodo12, :vvlrperiodo12,
                :vvlrtotperiodo;
            
           -- Serviços de desconto vem negativos
           IF (:vvlrtotperiodo <> 0) THEN
             BEGIN
               INSERT INTO TMP_DEMRECDESP_ANALITICAS(BDCODOBRSER, bdcodclifor, BDCLASSIFICACAO, BDTIPO, BDPERIODO01, bdvlrperiodo01, BDPERIODO02, bdvlrperiodo02, BDPERIODO03, bdvlrperiodo03,
                                                     BDPERIODO04, bdvlrperiodo04, BDPERIODO05, bdvlrperiodo05, BDPERIODO06, bdvlrperiodo06,  BDPERIODO07, bdvlrperiodo07,
                                                     BDPERIODO08, bdvlrperiodo08, BDPERIODO09, bdvlrperiodo09, BDPERIODO10, bdvlrperiodo10, BDPERIODO11, bdvlrperiodo11,
                                                     BDPERIODO12, bdvlrperiodo12, BDVLRTOTPERIODO)
               values(:vcodDesp, :vCodForAtual, :vclassserdesp, :vtiposerdesp, :vperiodo01, :vvlrperiodo01, :vperiodo02, :vvlrperiodo02, :vperiodo03, :vvlrperiodo03, :vperiodo04, :vvlrperiodo04,
                      :vperiodo05, :vvlrperiodo05, :vperiodo06, :vvlrperiodo06, :vperiodo07, :vvlrperiodo07, :vperiodo08, :vvlrperiodo08, :vperiodo09, :vvlrperiodo09, :vperiodo10, :vvlrperiodo10,
                      :vperiodo11, :vvlrperiodo11, :vperiodo12, :vvlrperiodo12, :vvlrtotperiodo);
             END
        end
     END
   END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER PROCEDURE SP_INSERIR_OBS_FINANCEIRA (
    PRCODESC INTEGER)
AS
BEGIN
  INSERT INTO VFIN_ESC_TCONFIGVAROBS (bdcodesc, bdchaveconfig, bdcodtipconfig, bdobsconfig) VALUES (:prcodesc, NULL, 1, 'Recebimento de fatura do cliente: *CODCLI-*NOMCLI, referência: *REFFAT, serviço: *CODSER-*NOMSER, forma de pagamento: *FORMPGTO.');

END^

CREATE OR ALTER trigger tol_vef_emp_tmovopimob_f200_bi0 for tol_vef_emp_tmovopimob_f200
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

CREATE OR ALTER trigger tol_vef_emp_tmovopimo_f200pg_bi for tol_vef_emp_tmovopimobi_f200_pg
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

--Sol: 12882 Patrick T .Sá 10/03/2016. Exclusão do lançamento no contábil ao excluir lançamento de operações imobiliárias no fiscal.
CREATE OR ALTER TRIGGER tol_f200_delete FOR tol_vef_emp_tmovopimob_f200
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC, OLD.bdchave);
END^

CREATE OR ALTER TRIGGER tol_f200_pgto_delete FOR tol_vef_emp_tmovopimobi_f200_pg
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC, OLD.bdchave);
END^

CREATE OR ALTER  TRIGGER VEF_EMP_DARF_RET_BI0 FOR VEF_EMP_DARF_RET
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE ORDEM INTEGER;
BEGIN
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDORDEM) + 1, 1) FROM VEF_EMP_DARF_RET INTO :ORDEM;
       NEW.BDORDEM = ORDEM;
     END
END^

/*TRIGGER DOS AJUSTES AUTOMÁTICOS DO C195*/

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TC195ENT_AD0 FOR TOL_VEF_EMP_TC195ENT
ACTIVE AFTER DELETE POSITION 0
AS
declare variable WCODIGO integer;
begin
--  DELETE FROM tol_vef_emp_tc195ent WHERE BDCODEMP = OLD.BDCODEMP AND BDCHAVE = OLD.BDCHAVE AND BDORDEMOBS = OLD.BDORDEMOBS;
  
  SELECT FIRST 1 BDCODEMP FROM TOL_VEF_EMP_TC195ENT WHERE BDCODEMP = OLD.BDCODEMP AND BDCHAVE = OLD.BDCHAVE AND BDORDEMOBS = OLD.BDORDEMOBS AND (BDORDEM <> OLD.BDORDEM OR BDORDEMDIF <> OLD.BDORDEMDIF)
  INTO :WCODIGO;
       --BDCODEMP,BDCHAVE,BDORDEM,BDORDEMDIF

  if (:WCODIGO IS NULL) then
    DELETE FROM VEF_EMP_TC195ENT c195
    WHERE c195.BDCODEMP = OLD.BDCODEMP
      AND c195.BDCHAVE = OLD.BDCHAVE
      AND c195.BDORDEMOBS = OLD.BDORDEMOBS
      AND (NOT EXISTS(SELECT * -- Alt.: #163627 - Apenas quando o C195 não estiver ligado a outro diferencial...
                      FROM TOL_VEF_EMP_TC195ENTPR x
                      WHERE x.BDCODEMP = c195.BDCODEMP
                        AND x.BDCHAVE = c195.BDCHAVE
                        AND x.BDORDEMOBS = c195.BDORDEMOBS));
end
^


/* Trigger: TOL_VEF_EMP_TC195ENT_BI0 */
CREATE OR ALTER TRIGGER TOL_VEF_EMP_TC195ENT_BI0 FOR TOL_VEF_EMP_TC195ENT
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1)
       FROM vef_emp_tmovent
       WHERE (bdcodemp = NEW.bdcodemp)
       INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

  if ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0))  then
     BEGIN
       SELECT COALESCE((MAX(BDORDEM)), 1)
       FROM VEF_EMP_TMOVENTITENS
       WHERE (bdcodemp = NEW.bdcodemp)
       AND (BDCHAVE = NEW.BDCHAVE)
       INTO vcodigo;
       NEW.BDORDEM = vcodigo;
     END

end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TC195ENTPR_AD0 FOR TOL_VEF_EMP_TC195ENTPR
ACTIVE AFTER DELETE POSITION 0
AS
declare variable WCODIGO integer;
begin
--  DELETE FROM TOL_VEF_EMP_TC195ENTPR WHERE BDCODEMP = OLD.BDCODEMP AND BDCHAVE = OLD.BDCHAVE AND BDORDEMOBS = OLD.BDORDEMOBS;
--  DELETE FROM VEF_EMP_TC195ENT WHERE BDCODEMP = OLD.BDCODEMP AND BDCHAVE = OLD.BDCHAVE AND BDORDEMOBS = OLD.BDORDEMOBS;
  
  SELECT FIRST 1 BDCODEMP FROM TOL_VEF_EMP_TC195ENTPR WHERE BDCODEMP = OLD.BDCODEMP AND BDCHAVE = OLD.BDCHAVE AND BDORDEMOBS = OLD.BDORDEMOBS AND (BDORDEM <> OLD.BDORDEM OR BDORDEMDIF <> OLD.BDORDEMDIF)
  INTO :WCODIGO;

  if (:WCODIGO IS NULL) then
    DELETE FROM VEF_EMP_TC195ENT c195
    WHERE c195.BDCODEMP = OLD.BDCODEMP
      AND c195.BDCHAVE = OLD.BDCHAVE
      AND c195.BDORDEMOBS = OLD.BDORDEMOBS
      AND (NOT EXISTS(SELECT * -- Alt.: #163627 - Apenas quando o C195 não estiver ligado a outro diferencial...
                      FROM TOL_VEF_EMP_TC195ENT x
                      WHERE x.BDCODEMP = c195.BDCODEMP
                        AND x.BDCHAVE = c195.BDCHAVE
                        AND x.BDORDEMOBS = c195.BDORDEMOBS))
      AND (NOT EXISTS(SELECT * -- Alt.: 232467 - Apenas quando o C195 nao estiver ligado a outro IVA...
                      FROM TOL_VEF_EMP_TC195IVASP x
                      WHERE x.BDCODEMP = c195.BDCODEMP
                        AND x.BDCHAVE = c195.BDCHAVE
                        AND x.BDORDEMOBS = c195.BDORDEMOBS));

end
^


CREATE OR ALTER trigger tol_vef_emp_tc195entpr_bi0 for tol_vef_emp_tc195entpr
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1)
       FROM vef_emp_tmovent
       WHERE (bdcodemp = NEW.bdcodemp)
       INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

     IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0))  THEN
     BEGIN
       SELECT COALESCE((MAX(BDORDEM)), 1)
       FROM VEF_EMP_TMOVENTITENS
       WHERE (bdcodemp = NEW.bdcodemp)
       AND (BDCHAVE = NEW.BDCHAVE)
       INTO vcodigo;
       NEW.BDORDEM = vcodigo;
     END
  end
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVENTDIFALIQ_AD0 FOR VEF_EMP_TMOVENTDIFALIQ
ACTIVE AFTER DELETE POSITION 0
AS
begin
  --DELETE FROM TOL_VEF_EMP_TC195ENT WHERE BDCODEMP = OLD.BDCODEMP AND BDCHAVE = OLD.BDCHAVE AND BDORDEM = OLD.BDORDEM;
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVENTDIFPR_AD0 FOR VEF_EMP_TMOVENTDIFPR
ACTIVE AFTER DELETE POSITION 0
AS
begin
  --DELETE FROM TOL_VEF_EMP_TC195ENTPR WHERE BDCODEMP = OLD.BDCODEMP AND BDCHAVE = OLD.BDCHAVE AND BDORDEM = OLD.BDORDEM;
end
^

create or alter procedure SP_ATUALIZA_TMP_TTERCEIRO_TEMP (
    PRSESSAO integer,
    PRATUALIZARDADOS DM_BOOLEAN,
    PRGERARINCONSISTENCIAS DM_BOOLEAN,
    PRREF integer,
    PRCODEMP integer,
    PRPUSH DM_BOOLEAN,
    PRTIPOVINCULO integer)
as
declare variable WCODTER integer;
declare variable WCGCTER varchar(18);
declare variable WIETER varchar(20);
declare variable WNOMETER varchar(100);
declare variable WCODTERENCONTRADO integer;
declare variable WCODBRASIL integer;
declare variable WCODCID integer;
declare variable WCODPAIS integer;
declare variable WAPELIDO varchar(20);
BEGIN
  PRATUALIZARDADOS       = UPPER(:PRATUALIZARDADOS);
  PRGERARINCONSISTENCIAS = UPPER(:PRGERARINCONSISTENCIAS);
  --execute procedure SP_CARREGAR_TMP_TTERCEIRO('FALSE');

  IF (:PRGERARINCONSISTENCIAS = 'TRUE') THEN
    BEGIN
      DELETE FROM VEF_INCON_TTERCEIROS WHERE BDSESSAO = :PRSESSAO;
      EXECUTE PROCEDURE SP_GERAR_INCON_TERCEIRO(:PRSESSAO, :PRREF, :PRCODEMP, :PRPUSH);
    END

  SELECT P.BDCODPAIS FROM TPAIS P WHERE UPPER(BDDESCPAIS) = 'BRASIL' INTO :wCodBrasil;

  FOR SELECT A.BDCODTER,
             COALESCE(A.BDCGCTER, ''),
             COALESCE(A.BDIETER, ''),
             COALESCE(A.BDNOMETER, ''),
             A.BDCODCID,
             A.BDCODPAIS,
             A.BDAPELIDOTER
      FROM TMP_TTERCEIRO_A_VALIDAR A
     /*Se não existir o editchave é porque é a primeira vez que esse participante vem para o servidor*/
      WHERE ((A.BDEDITCHAVE IS NULL) OR (A.BDEDITCHAVE = 0))
      INTO :wCodTer,
           :wCGCTer,
           :wIETer,
           :wNomeTer,
           :wCodCid,
           :wCodPais,
           :wApelido
  DO
    BEGIN
      --#alt:90366. Controle para retornar o apelido. Ana - 24/09/2018
      IF (TRIM(wApelido) = '') THEN
        wApelido = IIF(:wCgcTer = '', SUBSTRING(:wNomeTer FROM 1 FOR 20), :wCgcTer);

      /**************************************************Vínculo**************************************************/
      wCodTerEncontrado = NULL;
      IF ((:wCGCTER IS NULL) OR (:wCGCTER = '')) THEN /*Se não tiver CPF/CNPJ/CEI já procura direto pelo participante do exterior*/
        BEGIN
          SELECT FIRST 1 T.BDEDITCHAVE
          FROM TMP_TTERCEIRO T
          WHERE T.BDNOMETER = :wNomeTer
          AND T.BDCODPAIS <> :wCodBrasil
          INTO :wCodTerEncontrado;
        END
      ELSE /*É do Brasil*/
        BEGIN
          /*CPF/CNPJ/CEI + I.E*/
          SELECT FIRST 1 T.BDEDITCHAVE
          FROM TMP_TTERCEIRO T
          WHERE T.BDCGCTER = :wCGCTER
          AND (Coalesce((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(T.BDIETER)),'') = Coalesce((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(:WIETER)),''))
          INTO :wCodTerEncontrado;

          /*Só por CNPJ se não encontrar por CPF/CNPJ/CEI + IE, visto com Elizeu, Graci e Joice.*/
          /*#122191 #122354 - Deve cadastrar participante novo quando for IE diferente, se for isento vincula com qualquer um de mesmo CNPJ*/
          IF ((:wCodTerEncontrado IS NULL) OR (:wCodTerEncontrado = 0)) THEN
            BEGIN
              IF (:PRTIPOVINCULO = 0) THEN -- Vinculo somente por CNPJ
                BEGIN  
              SELECT FIRST 1 T.BDEDITCHAVE
              FROM TMP_TTERCEIRO T
              WHERE T.BDCGCTER = :wCGCTER
              INTO :wCodTerEncontrado;
            END
            END
        END
      /***********************************************************************************************************/

      /*Não encontrou o participante, então insere*/
      IF ((:wCodTerEncontrado IS NULL) OR (:wCodTerEncontrado = 0)) THEN
        BEGIN
          INSERT INTO TMP_TTERCEIRO (BDSESSAO, BDEDITCHAVE, BDCODTER, BDCGCTER, BDIETER,
                                     BDAPELIDOTER, BDNOMETER, BDCODCID, BDCODPAIS, BDPARTEXIST)
          VALUES (:PRSESSAO, 0, :wCodTer, :wCgcTer, :wIETer, :wApelido, :wNomeTer,
                  :wCodCid, :wCodPais, 'FALSE');
        END
      ELSE
        BEGIN
          /*Atualiza com os dados da importação*/
          IF (:PRATUALIZARDADOS = 'TRUE') THEN
            BEGIN
              UPDATE TMP_TTERCEIRO T SET T.BDSESSAO = :PRSESSAO, T.BDCODTER = :wCodTer,
                                         T.BDCGCTER = :wCgcTer,  T.BDIETER = :wIETer,
                                         T.BDAPELIDOTER = :wApelido, T.BDNOMETER = :wNomeTer,
                                         T.BDCODCID = :wCodCid, T.BDCODPAIS = :wCodPais,
                                         T.BDPARTEXIST = 'TRUE'
              WHERE T.BDEDITCHAVE = :wCodTerEncontrado;
            END
          ELSE
            BEGIN
              UPDATE TMP_TTERCEIRO T SET T.BDSESSAO = :PRSESSAO,
                                         T.BDCODTER = :wCodTer,
                                         T.BDPARTEXIST = 'TRUE'
              WHERE T.BDEDITCHAVE = :wCodTerEncontrado;
            END
        END

    END

  /* Caso não tenha a data de cadastro, atualiza para a data atual #Erro143 */
  UPDATE TMP_TTERCEIRO_TEMP t
  SET t.bdDATACADTER = localtimestamp
  WHERE t.bdDATACADTER IS NULL
    AND t.bdSESSAO = :prSESSAO;

  UPDATE TMP_TTERCEIRO_TEMP TM SET TM.BDREF_MAX = (COALESCE((SELECT FIRST 1 T.BDREF_MAX FROM TMP_TTERCEIRO T WHERE T.BDEDITCHAVE = TM.BDEDITCHAVE), TM.BDREFEMP)) WHERE TM.BDSESSAO = :PRSESSAO;
  /*Verifica se o participante existe na tabela fisica*/
  UPDATE TMP_TTERCEIRO T SET T.BDPARTEXIST_FIS = (SELECT 'TRUE' BDPARTEXIST_FIS FROM TTERCEIRO TER WHERE TER.BDCODTER = T.BDEDITCHAVE) WHERE T.BDSESSAO = :PRSESSAO AND T.BDEDITCHAVE IS NOT NULL;
END^

CREATE OR ALTER procedure SP_INSERT_OR_UPDATE_TTERCEIRO (
    PRSESSAO integer,
    PRREFEMP integer,
    PRCODEMP integer,
    PRPUSH varchar(5),
    PRATT varchar(5))
as
declare variable FVALUES varchar(500);
declare variable FCEPTERAUX varchar(9);
declare variable FCOMPTERAUX varchar(60);
declare variable FNUMTERAUX DM_NUMEND;
declare variable FENDTERAUX varchar(60);
declare variable FNOMETERAUX varchar(100);
declare variable FAPELIDOTERAUX varchar(20);
declare variable FCODTERAUX integer;
declare variable FSQL varchar(3000);
declare variable FCODPLANOINCO integer;
declare variable FATUALIZACAD varchar(5);
declare variable FCODTER integer;
declare variable FCGCTER varchar(18);
declare variable FIETER varchar(20);
declare variable FAPELIDOTER varchar(20);
declare variable FNOMETER varchar(100);
declare variable FCODCID integer;
declare variable FCODPAIS integer;
declare variable FCODTIPO integer;
declare variable FLOGRTER DM_LOGRADOURO;
declare variable FENDTER DM_BDENDERECO;
declare variable FCOMPTER DM_BDCOMPENDERECO;
declare variable FCEPTER varchar(9);
declare variable FBAITER varchar(60);
declare variable FDDDTER varchar(3);
declare variable FFONETER DM_BDTELEFONE;
declare variable FEMAILTER DM_BDEMAIL;
declare variable FFAXTER DM_BDTELEFONE;
declare variable FDATACADTER date;
declare variable FIMTER varchar(16);
declare variable FPRURALTER varchar(5);
declare variable FENQSIMPLESFEDTER integer;
declare variable FINSCSUFRAMATER varchar(10);
declare variable FCODGPS integer;
declare variable FNUMTER DM_NUMEND;
declare variable FPRODPF varchar(5);
declare variable FCPFPROD varchar(18);
declare variable FDDDFAXTER varchar(3);
declare variable FCODCIDAUX integer;
declare variable FEMAILTERAUX varchar(200);
declare variable FFONETERAUX varchar(15);
declare variable FDDDTERAUX varchar(3);
declare variable FBAITERAUX varchar(60);
declare variable WCODTER_REF integer;
declare variable WNOMETER_REF varchar(100);
declare variable WENDTER_REF DM_BDENDERECO;
declare variable WNUMTER_REF DM_NUMEND;
declare variable WCOMPTER_REF DM_BDCOMPENDERECO;
declare variable WCEP_REF varchar(9);
declare variable WBAITER_REF varchar(60);
declare variable WDDDTER_REF varchar(3);
declare variable WFONETER_REF DM_BDTELEFONE;
declare variable WEMAILTER_REF DM_BDEMAIL;
declare variable WCODCIDAUX_REF integer;
declare variable WREFEMP_REF integer;
declare variable FCODAQUIRUR integer;
declare variable FCODTRIBRUR integer;
declare variable WENQSIMPLESFEDTER_REF integer;
declare variable FENQSIMPLESFEDTERAUX integer;
declare variable FNAOATUALIZACAD varchar(5);
declare variable FCGCEMP varchar(18);
declare variable FCODCNAE integer;
declare variable FCARACTRIBUTARIATER integer;
begin
  if ((:PRCODEMP is not null) and
      (:PRCODEMP <> 0)) then
    select S.BDCODPLANOINCONS
    from SP_CONSULTAEMPRESAS_SIS(:PRREFEMP, :PRCODEMP, null) S
    into :FCODPLANOINCO;

  if ((:FCODPLANOINCO is null) or (:FCODPLANOINCO = 0)) then
    select I.BDCODPLANOINCONS
    from VEF_BASE_TACOESINCONS I
    where upper(I.BDPLANODEFAULT) = 'TRUE'
    into :FCODPLANOINCO;

  FATUALIZACAD = 'FALSE';
  if ((:FCODPLANOINCO is not null) or (:FCODPLANOINCO <> 0)) then
    select coalesce(I.BDATUPART, 'FALSE') BDATUPART
    from VEF_BASE_TACOESINCONS I
    where I.BDCODPLANOINCONS = :FCODPLANOINCO
    into :FATUALIZACAD;

  /*Deve atualizar os cadastros com os dados da importação*/
  if (:FATUALIZACAD = 'TRUE' or PRPUSH = 'TRUE') then
  begin
    for select T.BDEDITCHAVE BDCODTER, T.BDCGCTER, T.BDIETER, T.BDAPELIDOTER, T.BDNOMETER, T.BDCODCID, T.BDCODPAIS,
               T.BDCODTIPO, T.BDREFEMP, T.BDLOGRTER, T.BDENDTER, T.BDCOMPTER, T.BDCEPTER, T.BDBAITER, T.BDDDDTER,
               T.BDFONETER, T.BDEMAILTER, T.BDFAXTER, T.BDDATACADTER, T.BDIMTER, T.BDPRURALTER, T.BDENQSIMPLESFEDTER,
               T.BDINSCSUFRAMATER, T.BDCODGPS, T.BDDDDFAXTER, T.BDNUMTER, T.BDPRODPF, T.BDCPFPROD, T.BDCODAQUIRUR,
               T.BDCODTRIBRUR, T.BDCODCNAE, T.BDCARACTRIBUTARIATER
        from TMP_TTERCEIRO_TEMP T
        where T.BDSESSAO = :PRSESSAO and
              ((T.BDINCONSISTENTE is null) or (T.BDINCONSISTENTE = 0)) and
              T.BDEDITCHAVE is not null and
              not exists(select TI.BDCODINCONSISTENCIA
                         from VEF_INCON_TTERCEIROS TI
                         where TI.BDSESSAO = T.BDSESSAO and
                               TI.BDCODTER = T.BDCODTER)
        order by T.bdcodter
        into :FCODTER, :FCGCTER, :FIETER, :FAPELIDOTER, :FNOMETER, :FCODCID, :FCODPAIS, :FCODTIPO, :PRREFEMP, :FLOGRTER,
             :FENDTER, :FCOMPTER, :FCEPTER, :FBAITER, :FDDDTER, :FFONETER, :FEMAILTER, :FFAXTER, :FDATACADTER, :FIMTER,
             :FPRURALTER, :FENQSIMPLESFEDTER, :FINSCSUFRAMATER, :FCODGPS, :FDDDFAXTER, :FNUMTER, :FPRODPF, :FCPFPROD,
             :FCODAQUIRUR, :FCODTRIBRUR, :FCODCNAE, :FCARACTRIBUTARIATER
    do
    begin
        if (PRPUSH = 'FALSE') then
        begin
          update or insert into TTERCEIRO (BDCODTER, BDCODPLAPADRAO, BDCODTPLA, BDCGCTER, BDCODTIPO)
          values (:FCODTER, null, null, :FCGCTER, :FCODTIPO)
          matching (BDCODTER);

          update or insert into TTERCEIRO_REF (BDCODTER, BDREFEMP, BDAPELIDOTER, BDNOMETER, BDLOGRTER, BDENDTER,
                                               BDCOMPTER, BDCEPTER, BDBAITER, BDDDDTER, BDFONETER, BDFAXTER, BDEMAILTER,
                                               BDIETER, BDDATACADTER, BDIMTER, BDPRURALTER, BDENQSIMPLESFEDTER,
                                               BDINSCSUFRAMATER, BDCODGPS, BDCODCID, BDCODPAIS, BDDDDFAXTER, BDNUMTER,
                                               BDCGCTER, BDPRODPF, BDCPFPROD, BDCODAQUIRUR, BDCODTRIBRUR, BDCODCNAE,
                                               BDCARACTRIBUTARIATER)
          values (:FCODTER, :PRREFEMP, :FAPELIDOTER, :FNOMETER, :FLOGRTER, :FENDTER, :FCOMPTER, :FCEPTER, :FBAITER,
                  :FDDDTER, :FFONETER, :FFAXTER, :FEMAILTER, :FIETER, :FDATACADTER, :FIMTER, :FPRURALTER,
                  :FENQSIMPLESFEDTER, :FINSCSUFRAMATER, :FCODGPS, :FCODCID, :FCODPAIS, :FDDDFAXTER, :FNUMTER, :FCGCTER,
                  :FPRODPF, :FCPFPROD, :FCODAQUIRUR, :FCODTRIBRUR, :FCODCNAE, :FCARACTRIBUTARIATER)
          matching (BDCODTER, BDREFEMP);
        end
        else
        begin
          FCODTERAUX = null;

          update TTERCEIRO
          set BDDATAATU = cast('NOW' as date)
          where BDCODTER = :FCODTER;
          execute statement 'select BDCODTER from TTERCEIRO where BDCODTER = ' || :FCODTER
              into :FCODTERAUX;

          if ((FCODTERAUX is null) or (FCODTERAUX = 0)) then
          begin
            update or insert into TTERCEIRO (BDCODTER, BDCODPLAPADRAO, BDCODTPLA, BDCGCTER, BDCODTIPO)
            values (:FCODTER, null, null, :FCGCTER, :FCODTIPO)
            matching (BDCODTER);

            update or insert into TTERCEIRO_REF (BDCODTER, BDREFEMP, BDAPELIDOTER, BDNOMETER, BDLOGRTER, BDENDTER,
                                                 BDCOMPTER, BDCEPTER, BDBAITER, BDDDDTER, BDFONETER, BDFAXTER,
                                                 BDEMAILTER, BDIETER, BDDATACADTER, BDIMTER, BDPRURALTER,
                                                 BDENQSIMPLESFEDTER, BDINSCSUFRAMATER, BDCODGPS, BDCODCID, BDCODPAIS,
                                                 BDDDDFAXTER, BDNUMTER, BDCGCTER, BDPRODPF, BDCPFPROD, BDCODAQUIRUR,
                                                 BDCODTRIBRUR, BDCODCNAE, BDCARACTRIBUTARIATER)
            values (:FCODTER, :PRREFEMP, :FAPELIDOTER, :FNOMETER, :FLOGRTER, :FENDTER, :FCOMPTER, :FCEPTER, :FBAITER,
                    :FDDDTER, :FFONETER, :FFAXTER, :FEMAILTER, :FIETER, :FDATACADTER, :FIMTER, :FPRURALTER,
                    :FENQSIMPLESFEDTER, :FINSCSUFRAMATER, :FCODGPS, :FCODCID, :FCODPAIS, :FDDDFAXTER, :FNUMTER,
                    :FCGCTER, :FPRODPF, :FCPFPROD, :FCODAQUIRUR, :FCODTRIBRUR, :FCODCNAE, :FCARACTRIBUTARIATER)
            matching (BDCODTER, BDREFEMP);
          end
          else
          begin
            FCODTERAUX = null;
            execute statement 'select BDCODTER, BDAPELIDOTER, BDNOMETER, BDENDTER, BDNUMTER, BDCOMPTER, BDCEPTER, BDBAITER, BDDDDTER, BDFONETER,BDEMAILTER, BDCODCID, BDENQSIMPLESFEDTER from TTERCEIRO_REF where BDCODTER = ' || :FCODTER || ' and BDREFEMP = ' || :PRREFEMP
                into :FCODTERAUX, :FAPELIDOTERAUX, :FNOMETERAUX, :FENDTERAUX, :FNUMTERAUX, :FCOMPTERAUX, :FCEPTERAUX,
                :FBAITERAUX, :FDDDTERAUX, :FFONETERAUX, :FEMAILTERAUX, :FCODCIDAUX, :FENQSIMPLESFEDTERAUX;

            if ((FCODTERAUX is null) or (FCODTERAUX = 0)) then
            begin
              FSQL = 'insert into TTERCEIRO_REF (BDCODTER, BDREFEMP, BDAPELIDOTER, BDNOMETER, BDLOGRTER, BDENDTER, BDCOMPTER, ' || 'BDCEPTER, BDBAITER, BDDDDTER, BDFONETER, BDFAXTER, BDEMAILTER, BDIETER, ' || 'BDDATACADTER, BDIMTER, BDPRURALTER, BDENQSIMPLESFEDTER, BDINSCSUFRAMATER, ' || 'BDCODGPS, BDCODCID, BDCODPAIS, BDDDDFAXTER, BDNUMTER, BDORGAOPUBLICO, ' || 'BDDDDCELULARTER, BDCELULARTER, BDINATIVO, BDCGCTER, BDCODIGOPOSTAL, BDNUMERONIF, ' || 'BDINDNIF, BDINDIMUNEISE, BDCODREND, BDPRODPF, BDCPFPROD, BDCODAQUIRUR, BDCODTRIBRUR) ' || 'select T.BDCODTER, ' || :PRREFEMP || ', T.BDAPELIDOTER, T.BDNOMETER, T.BDLOGRTER, T.BDENDTER, T.BDCOMPTER, T.BDCEPTER, ' || 'T.BDBAITER, T.BDDDDTER, T.BDFONETER, T.BDFAXTER, T.BDEMAILTER, T.BDIETER, T.BDDATACADTER, T.BDIMTER, ' || 'T.BDPRURALTER, T.BDENQSIMPLESFEDTER, T.BDINSCSUFRAMATER, T.BDCODGPS, T.BDCODCID, T.BDCODPAIS, ' || 'T.BDDDDFAXTER, T.BDNUMTER, T.BDORGAOPUBLICO, T.BDDDDCELULARTER, T.BDCELULARTER, T.BDINATIVO, ' || 'T.BDCGCTER, T.BDCODIGOPOSTAL, T.BDNUMERONIF, T.BDINDNIF, T.BDINDIMUNEISE, T.BDCODREND, T.BDPRODPF, ' || 'T.BDCPFPROD, T.BDCODAQUIRUR, T.BDCODTRIBRUR ' || 'from TTERCEIRO_REF T ' || 'where T.BDCODTER = ' || :FCODTER || ' and ' || ' T.BDREFEMP = (select first 1 A.BDREFEMP ' || ' from TTERCEIRO_REF A ' || ' where A.BDCODTER = ' || :FCODTER || ' order by A.BDREFEMP desc)';

              execute statement FSQL;
            end

            select BDCODTER, BDREFEMP, BDNOMETER, BDENDTER, BDNUMTER, BDCOMPTER, BDCEPTER, BDBAITER, BDDDDTER,
                   BDFONETER, BDEMAILTER, BDCODCID, BDENQSIMPLESFEDTER
            from TTERCEIRO_REF
            where BDCODTER = :FCODTER and
                  BDREFEMP = :PRREFEMP
            into :WCODTER_REF, :WREFEMP_REF, :WNOMETER_REF, :WENDTER_REF, :WNUMTER_REF, :WCOMPTER_REF, :WCEP_REF,
                 :WBAITER_REF, :WDDDTER_REF, :WFONETER_REF, :WEMAILTER_REF, :WCODCIDAUX_REF, :WENQSIMPLESFEDTER_REF;

            if ((FNOMETERAUX is null or trim(FNOMETERAUX) = '') or (PRATT = 'TRUE' and
                FNOMETER is not null and
                trim(FNOMETER) <> '')) then
            begin
              if (FNOMETER is null) then
                WNOMETER_REF = null;
              else
                WNOMETER_REF = :FNOMETER;
            end

            if ((FENDTERAUX is null or trim(FENDTERAUX) = '') or (PRATT = 'TRUE' and
                FENDTER is not null and
                trim(FENDTER) <> '')) then
            begin
              if (FENDTER is null) then
                WENDTER_REF = null;
              else
                WENDTER_REF = :FENDTER;
            end

            if ((FNUMTERAUX is null or trim(FNUMTERAUX) = '') or (PRATT = 'TRUE' and
                FNUMTER is not null and
                trim(FNUMTER) <> '')) then
            begin
              if (FNUMTER is null) then
                WNUMTER_REF = null;
              else
                WNUMTER_REF = :FNUMTER;
            end

            if ((FCOMPTERAUX is null or trim(FCOMPTERAUX) = '') or (PRATT = 'TRUE' and
                FCOMPTER is not null and
                trim(FCOMPTER) <> '')) then
            begin
              if (FCOMPTER is null) then
                WCOMPTER_REF = null;
              else
                WCOMPTER_REF = :FCOMPTER;
            end

            if ((FCEPTERAUX is null or trim(FCEPTERAUX) = '') or (PRATT = 'TRUE' and
                FCEPTER is not null and
                trim(FCEPTER) <> '')) then
            begin
              if (FCEPTER is null) then
                WCEP_REF = null;
              else
                WCEP_REF = :FCEPTER;
            end

            if ((FBAITERAUX is null or trim(FBAITERAUX) = '') or (PRATT = 'TRUE' and
                FBAITER is not null and
                trim(FBAITER) <> '')) then
            begin
              if (FBAITER is null) then
                WBAITER_REF = null;
              else
                WBAITER_REF = :FBAITER;
            end

            if ((FDDDTERAUX is null or trim(FDDDTERAUX) = '') or (PRATT = 'TRUE' and
                FDDDTER is not null and
                trim(FDDDTER) <> '')) then
            begin
              if (FDDDTER is null) then
                WDDDTER_REF = null;
              else
                WDDDTER_REF = :FDDDTER;
            end

            if ((FFONETERAUX is null or trim(FFONETERAUX) = '') or (PRATT = 'TRUE' and
                FFONETER is not null and
                trim(FFONETER) <> '')) then
            begin
              if (FFONETER is null) then
                WFONETER_REF = null;
              else
                WFONETER_REF = :FFONETER;
            end

            if ((FEMAILTERAUX is null or trim(FEMAILTERAUX) = '') or (PRATT = 'TRUE' and
                FEMAILTER is not null and
                trim(FEMAILTER) <> '')) then
            begin
              if (FEMAILTER is null) then
                WEMAILTER_REF = null;
              else
                WEMAILTER_REF = :FEMAILTER;
            end

            if ((FCODCIDAUX is null or trim(FCODCIDAUX) = '') or (PRATT = 'TRUE' and
                FCODCID is not null and
                trim(FCODCID) <> '')) then
            begin
              if (FCODCID is null) then
                WCODCIDAUX_REF = null;
              else
                WCODCIDAUX_REF = :FCODCID;
            end

            if ((FENQSIMPLESFEDTERAUX is null or trim(FENQSIMPLESFEDTERAUX) = '') or (PRATT = 'TRUE' and
                FENQSIMPLESFEDTER is not null and
                trim(FENQSIMPLESFEDTER) <> '')) then
            begin
              if (FENQSIMPLESFEDTER is null) then
                WENQSIMPLESFEDTER_REF = null;
              else
                WENQSIMPLESFEDTER_REF = :FENQSIMPLESFEDTER;
            end
               

            update or insert into TTERCEIRO_REF (BDCODTER, BDREFEMP, BDNOMETER, BDENDTER, BDNUMTER, BDCOMPTER, BDCEPTER,
                                                 BDBAITER, BDDDDTER, BDFONETER, BDEMAILTER, BDCODCID,
                                                 BDENQSIMPLESFEDTER)
            values (:WCODTER_REF, :WREFEMP_REF, :WNOMETER_REF, :WENDTER_REF, :WNUMTER_REF, :WCOMPTER_REF, :WCEP_REF,
                    :WBAITER_REF, :WDDDTER_REF, :WFONETER_REF, :WEMAILTER_REF, :WCODCIDAUX_REF, :WENQSIMPLESFEDTER_REF)
            matching (BDCODTER, BDREFEMP);
          end
        end
      

      if (PRPUSH = 'TRUE') then
      begin
        --        update TTERCEIRO T set BDDATAATU = cast('NOW' as date)
        --        where --BDCODTER = :FCODTER;
        --              exists(select TI.BDCODINCONSISTENCIA
        --                     from VEF_INCON_TTERCEIROS TI
        --                     left outer join TMP_TTERCEIRO_TEMP tp on (tp.bdsessao = ti.bdsessao and tp.bdcodter = ti.bdcodter)
        --                      where TI.BDSESSAO = :PRSESSAO and
        --                            Tp.bdeditchave = T.BDCODTER);
        --elizeu - 04-03-20 - lentidão no update quando tinha varios participantes inconsistentes ou da importação ou de outras.. não fazia filtro de sessão - cartao:Lentidão na importação de terceiros #134412
        update TTERCEIRO T
        set BDDATAATU = cast('NOW' as date)
        where exists(select TI.BDCODINCONSISTENCIA, TI.BDCODTER
                     from (select TI.BDCODINCONSISTENCIA, TI.BDCODTER
                           from VEF_INCON_TTERCEIROS TI
                           where TI.BDSESSAO = :PRSESSAO) TI
                     join TMP_TTERCEIRO_TEMP TP on (TP.BDSESSAO = :PRSESSAO and
                           TP.BDCODTER = TI.BDCODTER)
                     where TP.BDEDITCHAVE = T.BDCODTER);

        --Jaques - 16/01/2023 - #Alt:171143 - atualizar todas as referências no caso da característica tributária e do CNAE
        update TTERCEIRO_REF
        set BDCARACTRIBUTARIATER = :FCARACTRIBUTARIATER
        where BDCODTER = :FCODTER
          and COALESCE(BDCARACTRIBUTARIATER, -1) <= 0;

        update TTERCEIRO_REF
        set BDCODCNAE = :FCODCNAE
        where BDCODTER = :FCODTER
          and BDCODCNAE IS NULL;
      end
    end
  end
  else
  /*Não deve atualizar os cadastros com os dados da importação*/
  begin
    insert into TTERCEIRO (BDCODTER, BDCODPLAPADRAO, BDCODTPLA, BDCGCTER, BDCODTIPO)
    select TER.BDCODTER, TER.BDCODPLAPADRAO, TER.BDCODTPLA, TER.BDCGCTER, TER.BDCODTIPO
    from (select T.BDEDITCHAVE BDCODTER, T.BDCODPLAPADRAO, T.BDCODTPLA, T.BDCGCTER, T.BDCODTIPO, T.BDIETER,
                 T.BDREF_MAX
          from TMP_TTERCEIRO_TEMP T
          where T.BDSESSAO = :PRSESSAO
                /*Se estiver com o BDEDITCHAVE como NULL é porque o registro é inconsistente, não precisa fazer o not exists com a tabela de inconsistencias(VEF_INCON_TTERCEIROS)*/
                and
                ((T.BDEDITCHAVE is not null) or (T.BDEDITCHAVE <> 0)) and
                not exists(select TI.BDCODINCONSISTENCIA
                           from VEF_INCON_TTERCEIROS TI
                           where TI.BDSESSAO = :PRSESSAO and
                                 TI.BDCODTER = T.BDCODTER)) TER
    ------------------------------
    --                                método antigo
    --      LEFT OUTER JOIN TTERCEIRO T ON (T.BDCODTER = TER.BDCODTER)
    --      LEFT OUTER JOIN TTERCEIRO_REF REF ON (REF.BDCGCTER = TER.BDCGCTER AND REF.BDIETER = TER.BDIETER)
    --      WHERE REF.BDCGCTER IS NULL;
    --      AND T.BDCGCTER IS NULL;
    --      WHERE T.BDCODTER IS NULL;
    -----------------------------------------
    --                                       método antigo 2
    --      LEFT OUTER JOIN TTERCEIRO T ON (T.BDCGCTER = TER.BDCGCTER)
    --      LEFT OUTER JOIN TTERCEIRO_REF REF ON (REF.BDCGCTER = TER.BDCGCTER AND REF.BDIETER = TER.BDIETER)
    --      WHERE ref.BDCGCTER IS NULL
    --      and t.bdcgcter is null;
    -----------------------------------------
    --      LEFT OUTER JOIN TTERCEIRO T ON (T.BDCGCTER = TER.BDCGCTER)
    --      LEFT OUTER JOIN TTERCEIRO_REF REF ON (REF.BDCGCTER = TER.BDCGCTER AND REF.BDIETER = TER.BDIETER AND REF.BDREFEMP = TER.BDREF_MAX)
    left outer join TTERCEIRO T on (T.BDCODTER = TER.BDCODTER)
    left outer join TTERCEIRO_REF REF on (REF.BDCODTER = TER.BDCODTER and
          REF.BDREFEMP = TER.BDREF_MAX)
          --      WHERE ref.BDCGCTER IS NULL
    where T.BDCODTER is null
    group by TER.BDCODTER, TER.BDCODPLAPADRAO, TER.BDCODTPLA, TER.BDCGCTER, TER.BDCODTIPO;

    insert into TTERCEIRO_REF (BDCODTER, BDREFEMP, BDAPELIDOTER, BDNOMETER, BDLOGRTER, BDENDTER, BDCOMPTER, BDCEPTER,
                               BDBAITER, BDDDDTER, BDFONETER, BDFAXTER, BDEMAILTER, BDIETER, BDDATACADTER, BDIMTER,
                               BDPRURALTER, BDENQSIMPLESFEDTER, BDINSCSUFRAMATER, BDCODGPS, BDCODCID, BDCODPAIS,
                               BDDDDFAXTER, BDNUMTER, BDCGCTER, BDPRODPF, BDCPFPROD, BDCODAQUIRUR, BDCODTRIBRUR)
    select TR.BDCODTER, TR.BDREFEMP, TR.BDAPELIDOTER, TR.BDNOMETER, TR.BDLOGRTER, TR.BDENDTER, TR.BDCOMPTER,
           TR.BDCEPTER, TR.BDBAITER, TR.BDDDDTER, TR.BDFONETER, TR.BDFAXTER, TR.BDEMAILTER, TR.BDIETER, TR.BDDATACADTER,
           TR.BDIMTER, TR.BDPRURALTER, TR.BDENQSIMPLESFEDTER, TR.BDINSCSUFRAMATER, TR.BDCODGPS, TR.BDCODCID,
           TR.BDCODPAIS, TR.BDDDDFAXTER, TR.BDNUMTER, TR.BDCGCTER, TR.BDPRODPF, TR.BDCPFPROD, TR.BDCODAQUIRUR,
           TR.BDCODTRIBRUR
    from (select T.BDEDITCHAVE BDCODTER, T.BDREFEMP, T.BDAPELIDOTER, T.BDNOMETER, T.BDLOGRTER, T.BDENDTER, T.BDCOMPTER,
                 T.BDCEPTER, T.BDBAITER, T.BDDDDTER, T.BDFONETER, T.BDFAXTER, T.BDEMAILTER, T.BDIETER, T.BDDATACADTER,
                 T.BDIMTER, T.BDPRURALTER, T.BDENQSIMPLESFEDTER, T.BDINSCSUFRAMATER, T.BDCODGPS, T.BDCODCID,
                 T.BDCODPAIS, T.BDDDDFAXTER, T.BDNUMTER, T.BDCGCTER, T.BDREF_MAX, T.BDPRODPF, T.BDCPFPROD,
                 T.BDCODAQUIRUR, T.BDCODTRIBRUR
          from TMP_TTERCEIRO_TEMP T
          where T.BDSESSAO = :PRSESSAO and
                ((T.BDEDITCHAVE is not null) or (T.BDEDITCHAVE <> 0)) and
                not exists(select TI.BDCODINCONSISTENCIA
                           from VEF_INCON_TTERCEIROS TI
                           where TI.BDSESSAO = :PRSESSAO and
                                 TI.BDCODTER = T.BDCODTER)) TR
    --      LEFT OUTER JOIN TTERCEIRO_REF T ON(T.BDCODTER = TR.BDCODTER)
    left outer join TTERCEIRO_REF R on (TR.BDCODTER = R.BDCODTER and
          R.BDREFEMP = TR.BDREF_MAX)
          --      LEFT OUTER JOIN TTERCEIRO_REF R ON (/*TR.BDCODTER = R.BDCODTER AND */R.BDCGCTER = TR.BDCGCTER AND R.BDIETER = TR.BDIETER AND R.BDREFEMP = TR.BDREF_MAX)
    where R.BDCODTER is null;
    --      AND T.BDCODTER IS NOT NULL;
    --      WHERE T.BDCODTER IS NULL;
  end
end

^

-- Sol: 13805 Maicon S. Silva Chave conf DOT

CREATE OR ALTER TRIGGER VEF_BASE_TCONFDOT_BI0 FOR VEF_BASE_TCONFDOT
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodconfdot IS NULL) OR (NEW.bdcodconfdot = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodconfdot)+1),1) FROM vef_base_tconfdot INTO vcodigo;
        NEW.bdcodconfdot = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodconfdot FROM vef_base_tconfdot WHERE bdcodconfdot = NEW.bdcodconfdot INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodconfdot)+1),1) FROM vef_base_tconfdot INTO vcodigo;
            NEW.bdcodconfdot = vcodigo;
         END
    END
END
^


SET TERM ; ^

SET TERM ^ ;



CREATE OR ALTER TRIGGER VEF_BASE_TCONFDOTQ_BI0 FOR VEF_BASE_TCONFDOTQ
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vAux INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODQDOT IS NULL) OR (NEW.BDCODQDOT = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODQDOT)+1),1) FROM VEF_BASE_TCONFDOTQ INTO vcodigo;
        NEW.BDCODQDOT = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODQDOT FROM VEF_BASE_TCONFDOTQ WHERE BDCODQDOT = NEW.BDCODQDOT INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODQDOT)+1),1) FROM VEF_BASE_TCONFDOTQ INTO vcodigo;
            NEW.BDCODQDOT = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVENTRURAL_AD0 FOR TOL_VEF_EMP_TMOVENTRURAL
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    EXECUTE STATEMENT 'DELETE FROM VRHF_EMP_TNFPRODRURAL WHERE BDCODEMP = '||OLD.BDCODEMP||' AND BDCHAVE = '||OLD.BDCHAVERH;
  end
END
^

CREATE OR ALTER TRIGGER TMP_TELAS_TESTES_BI0 FOR TMP_TELAS_TESTES
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDID IS NULL) OR (NEW.BDID = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDID)+1),1) FROM TMP_TELAS_TESTES INTO vcodigo;
       NEW.BDID = vcodigo;
    END
END
^



CREATE OR ALTER PROCEDURE SP_PEGAR_TRIGGER (
    PRTABELA VARCHAR(200),
    PRTIPO INTEGER) 
RETURNS (
    BDTRIGGER VARCHAR(200)) 
AS
DECLARE VARIABLE WSQL VARCHAR(3000);
BEGIN
  wsql = 'select RDB$TRIGGER_NAME from RDB$TRIGGERS where RDB$RELATION_NAME = ''' || UPPER(prtabela) || ''' and RDB$TRIGGER_TYPE = ' || prtipo;
  FOR EXECUTE STATEMENT wsql INTO :bdtrigger DO
  SUSPEND;
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER vef_emp_tmoventitensctr_bi0 FOR vef_emp_tmoventitensctr
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdCHAVE)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdCHAVE = NEW.bdchave) INTO vNova_Ordem;
      NEW.BDORDEM = vNova_Ordem;
    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER vef_int_tconvicms115_bi0 FOR vef_int_tconvicms115
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdcodigo IS NULL) OR (NEW.bdcodigo = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodigo) + 1), 1) FROM VEF_INT_TCONVICMS115 WHERE bdcodemp = NEW.bdcodemp AND bdcodigo < 999999  INTO vCodigo;
      NEW.bdcodigo = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodigo FROM VEF_INT_TCONVICMS115 WHERE bdcodemp = NEW.bdcodemp AND bdcodigo = NEW.bdcodigo INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodigo) + 1), 1) FROM VEF_INT_TCONVICMS115 WHERE bdcodemp = NEW.bdcodemp AND bdcodigo < 999999 INTO vCodigo;
           NEW.bdcodigo = vCodigo;
         END
    END
END^


CREATE OR ALTER procedure SP_CONSULTA_DARF_RETENCAO (
    PRVERORGAOPUBLICO varchar(5),
    PRREFTELA varchar(12),
    PRCODEMP integer,
    PRDATAINI varchar(12),
    PRDATAFIN varchar(12),
    PRTIPOAPURACAORET integer,
    PRTIPOAPURACAORETIR integer,
    PRTIPOAPURACAORETIRTOM integer,
    PRCAMPODATA varchar(100))
returns (
    BDCODMATRIZ integer,
    BDCODEMP integer,
    BDCHAVE integer,
    BDTIPLAN integer,
    BDNUMDOCINI varchar(15),
    BDDATAEMISSAO date,
    BDVALORNOTA numeric(15,2),
    BDVALORPAGO numeric(15,2),
    BDVLRPIS numeric(15,2),
    BDVLRCOFINS numeric(15,2),
    BDVLRCSOCIAL numeric(15,2),
    BDVLRINSS numeric(15,2),
    BDVLRIR numeric(15,2),
    BDISSRET numeric(15,2),
    BDCODTER integer,
    BDNOMETER varchar(100),
    BDCGCTER varchar(18))
as
declare variable WCODMATRIZ integer;
declare variable WCONSOLIDARMATRIZFILIAL varchar(10);
declare variable WSQL varchar(32000);
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WTIPLAN integer;
declare variable WNUMDOCINI varchar(15);
declare variable WDATAEMISSAO date;
declare variable WVALORNOTA numeric(15,2);
declare variable WVALORPAGO numeric(15,2);
declare variable WVLRPIS numeric(15,2);
declare variable WVLRCOFINS numeric(15,2);
declare variable WVLRCSOCIAL numeric(15,2);
declare variable WVLRINSS numeric(15,2);
declare variable WVLRIR numeric(15,2);
declare variable WISSRET numeric(15,2);
declare variable WCODTER integer;
declare variable WNOMETER varchar(100);
declare variable WCGCTER varchar(18);
begin
  select BDVALOR
  from TPARGER
  where BDCAMPO = 'BDCONSOLIDARMATRIZFILIAL'
  into :WCONSOLIDARMATRIZFILIAL;

  WCONSOLIDARMATRIZFILIAL = upper(coalesce(:WCONSOLIDARMATRIZFILIAL, 'FALSE'));

  delete from TMP_TEMPRESAS;
  insert into TMP_TEMPRESAS (BDCODEMP)
  values (:PRCODEMP);

  if (WCONSOLIDARMATRIZFILIAL = 'TRUE') then
  begin
    insert into TMP_TEMPRESAS (BDCODEMP)
    select E.BDCODEMP
    from TEMPRESAS E
    where E.BDCODMATRIZ = :PRCODEMP;
  end

  WSQL = 'SELECT COALESCE(E.BDCODMATRIZ, E.BDCODEMP) BDCODMATRIZ, mov.BDCODEMP, mov.BDCHAVE, mov.BDTIPLAN, ';
  WSQL = WSQL || '       mov.BDNUMDOCINI, mov.BDDATAEMISSAO, mov.BDVALORNOTA, mov.BDVALORPAGO, mov.BDVLRPIS, ';
  WSQL = WSQL || '       mov.BDVLRCOFINS, mov.BDVLRCSOCIAL, mov.BDVLRINSS, mov.BDVLRIR, mov.BDISSRET, ter.BDCODTER, ';
  WSQL = WSQL || '       ter.BDNOMETER, ter.BDCGCTER ';
  WSQL = WSQL || 'from ( ';
    /* Serviços */
    /* Tipo de apuração das retenções (PIS/Cofins/CSLL) */
  WSQL = WSQL || '            select ser.BDCODEMP, ser.BDCHAVE, ser.BDTIPLAN, ser.BDNUMDOCINI, ser.BDDATAEMISSAO, ';
  WSQL = WSQL || '                   ser.BDVALORNOTA, ser.BDVALORNOTA as BDVALORPAGO, ';
  WSQL = WSQL || '                   ser.BDCODTER, ';
  WSQL = WSQL || '                   ret.BDVLRPIS, ret.BDVLRCOFINS, ret.BDVLRCSOCIAL, ret.BDVLRINSS, 0 as BDVLRIR, ret.BDISSRET ';
  WSQL = WSQL || '            from (';
  WSQL = WSQL || '                  SELECT ser.* ';
  WSQL = WSQL || '                  FROM VEF_EMP_TMOVSER ser ';
  WSQL = WSQL || '                  JOIN TMP_TEMPRESAS EMP ON(EMP.BDCODEMP = SER.BDCODEMP) ';
  WSQL = WSQL || '                  WHERE '||:PRCAMPODATA||' between ''' || PRDATAINI || ''' and ''' || PRDATAFIN || '''';
  WSQL = WSQL || '                 ) ser ';
  WSQL = WSQL || '            left outer join VEF_EMP_TMOVSERRET ret on (ret.BDCODEMP = ser.BDCODEMP and ret.BDCHAVE = ser.BDCHAVE) ';
  WSQL = WSQL || '            WHERE ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or (ret.BDVLRINSS > 0) or (ret.BDISSRET > 0)) ';

  if (PRTIPOAPURACAORET = 1) then
  begin
    WSQL = WSQL || '            and ser.BDCONDPGTO <> 1 ';
    WSQL = WSQL || '            union all ';
    WSQL = WSQL || '            select pgto.BDCODEMP, pgto.BDCHAVE, ser.BDTIPLAN, ser.BDNUMDOCINI, ser.BDDATAEMISSAO, ser.BDVALORNOTA, pgto.BDVALORPGTOPAR as BDVALORPAGO,  ser.BDCODTER, ';
    WSQL = WSQL || '                   pgto.BDVALORRETPIS as BDVLRPIS, pgto.BDVALORRETCOFINS as BDVLRCOFINS, pgto.BDVALORRETCSLL as BDVLRCSOCIAL, pgto.BDVALORRETINSS as BDVLRINSS, 0 as BDVLRIR, pgto.BDVALORRETISSQN as BDISSRET ';
    WSQL = WSQL || '            from (select PGTO.* from VEF_EMP_TMOVSERPARPGTO pgto ';
    WSQL = WSQL || '                  JOIN TMP_TEMPRESAS EMP ON (EMP.BDCODEMP = PGTO.BDCODEMP) ';
    WSQL = WSQL || '                  WHERE (pgto.BDDATAPGTOPAR between ''' || PRDATAINI || ''' and ''' || PRDATAFIN || ''') ';
    WSQL = WSQL || '                  and (pgto.BDCODTIPOBAIXA = 1)) pgto ';/* #94385 Levar apenas pagamento/recebimento */
    WSQL = WSQL || '            join (select ser.BDCODEMP, ser.BDCHAVE, ser.BDTIPLAN, ser.BDNUMDOCINI, ser.BDDATAEMISSAO, ser.BDVALORNOTA, ser.BDCODTER, ';
    WSQL = WSQL || '                         ret.BDVLRPIS, ret.BDVLRCOFINS, ret.BDVLRCSOCIAL, ret.BDVLRINSS, 0 as BDVLRIR, ret.BDISSRET ';
    WSQL = WSQL || '                  from (';
    WSQL = WSQL || '                        SELECT SER.* FROM VEF_EMP_TMOVSER SER ';
    WSQL = WSQL || '                        JOIN TMP_TEMPRESAS EMP ON (EMP.BDCODEMP = SER.BDCODEMP) ';
    WSQL = WSQL || '                       ) SER ';
    WSQL = WSQL || '                  left outer join VEF_EMP_TMOVSERRET ret on (ret.BDCODEMP = ser.BDCODEMP and ret.BDCHAVE = ser.BDCHAVE) ';
    WSQL = WSQL || '                  WHERE ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or (ret.BDVLRINSS > 0) or (ret.BDISSRET > 0)) ';
    WSQL = WSQL || '                  and ser.BDCONDPGTO = 1 ) ser on (ser.BDCODEMP = pgto.BDCODEMP and ser.BDCHAVE = pgto.BDCHAVE) ';
  end
  WSQL = WSQL || '            union all ';
    /* Tipo de apuração das retenções IR */

  WSQL = WSQL || '            select ser.BDCODEMP, ser.BDCHAVE, ser.BDTIPLAN, ser.BDNUMDOCINI, ser.BDDATAEMISSAO, ';
  WSQL = WSQL || '                   ser.BDVALORNOTA as BDVALORNOTA, ';
  WSQL = WSQL || '                   ser.BDVALORNOTA as BDVALORPAGO, ';
  WSQL = WSQL || '                   ser.BDCODTER, ';
  WSQL = WSQL || '                   0 as BDVLRPIS, 0 as BDVLRCOFINS, 0 as BDVLRCSOCIAL, 0 as BDVLRINSS, ret.BDVLRIR, 0 as BDISSRET ';
  WSQL = WSQL || '            from (';
  WSQL = WSQL || '                  SELECT SER.* FROM VEF_EMP_TMOVSER SER ';
  WSQL = WSQL || '                  JOIN TMP_TEMPRESAS EMP ON (EMP.BDCODEMP = SER.BDCODEMP) ';
  WSQL = WSQL || '                  WHERE '||:PRCAMPODATA||' between ''' || PRDATAINI || ''' and ''' || PRDATAFIN || '''';
  WSQL = WSQL || '                 ) SER ';
  WSQL = WSQL || '            left outer join VEF_EMP_TMOVSERRET ret on (ret.BDCODEMP = ser.BDCODEMP and ret.BDCHAVE = ser.BDCHAVE) ';
  if (PRVERORGAOPUBLICO = true) then
  begin
    WSQL = WSQL || '            left outer join(select BDCODTER, RF2.BDORGAOPUBLICO, RF2.BDCGCTER, RF2.BDNOMETER, RF2.BDREFEMP ';
    WSQL = WSQL || '                            from TTERCEIRO_REF RF2 ';
    WSQL = WSQL || '                            where RF2.BDREFEMP = coalesce((select first 1 BDREFEMP ';
    WSQL = WSQL || '                                                           from TTERCEIRO_REF RF3 ';
    WSQL = WSQL || '                                                           where RF3.BDCODTER = RF2.BDCODTER and ';
    WSQL = WSQL || '                                                                 RF3.BDREFEMP <= ''' || PRREFTELA || ''' ';
    WSQL = WSQL || '                                                           order by RF3.BDREFEMP desc), (select first 1 BDREFEMP ';
    WSQL = WSQL || '                                                                                         from TTERCEIRO_REF RF3 ';
    WSQL = WSQL || '                                                                                         where RF3.BDCODTER = RF2.BDCODTER ';
    WSQL = WSQL || '                                                                                         order by RF3.BDCODTER, RF3.BDREFEMP))) as TER on TER.BDCODTER = SER.BDCODTER ';
  end
  WSQL = WSQL || '            WHERE (ret.BDVLRIR > 0) ';
  WSQL = WSQL || '            AND (SELECT BDISVALID FROM SP_FILTER_REGIME_SERVICO(SER.BDTIPLAN, SER.BDCONDPGTO, ';
  if (PRVERORGAOPUBLICO = true) then
    WSQL = WSQL || ' IIF(TER.BDORGAOPUBLICO = TRUE, 1, ' || :PRTIPOAPURACAORETIR || '), ' || :PRTIPOAPURACAORETIRTOM || ')) = ''TRUE'' ';
  else
    WSQL = WSQL || ' ' || :PRTIPOAPURACAORETIR || ', ' || :PRTIPOAPURACAORETIRTOM || ')) = ''TRUE'' ';

  WSQL = WSQL || ' union all ';
  /*Sql refeito para verIFicar órgão publico - #153689 - Kleiton Melo*/
  WSQL = WSQL || '      select PGTO.BDCODEMP, PGTO.BDCHAVE, PGTO.BDTIPLAN, PGTO.BDNUMDOCINI, PGTO.BDDATAEMISSAO, PGTO.BDVALORNOTA, ';
  WSQL = WSQL || '             PGTO.BDVALORPGTOPAR as BDVALORPAGO, PGTO.BDCODTER, 0 as BDVLRPIS, 0 as BDVLRCOFINS, 0 as BDVLRCSOCIAL, ';
  WSQL = WSQL || '             0 as BDVLRINSS, PGTO.BDVALORRETIRRF as BDVLRIR, 0 as BDISSRET ';
  WSQL = WSQL || '      from (select PGTO.BDCODEMP, PGTO.BDCHAVE, PGTO.BDVALORRETPIS, PGTO.BDVALORRETCOFINS, PGTO.BDVALORRETCSLL, ';
  WSQL = WSQL || '                   PGTO.BDVALORRETIRRF, PGTO.BDDATAPGTOPAR, PGTO.BDCODTIPOBAIXA, PGTO.BDVALORPGTOPAR, MOV.BDVALORNOTA, ';
  WSQL = WSQL || '                   MOV.BDDATAEMISSAO, MOV.BDCONDPGTO, MOV.BDNUMDOCINI, MOV.BDTIPLAN, MOV.BDCODTER';
  WSQL = WSQL || '            from VEF_EMP_TMOVSERPARPGTO PGTO ';
  WSQL = WSQL || '            join TMP_TEMPRESAS EMP on (EMP.BDCODEMP = PGTO.BDCODEMP) ';
  WSQL = WSQL || '            join VEF_EMP_TMOVSER MOV on (PGTO.BDCODEMP = MOV.BDCODEMP and ';
  WSQL = WSQL || '                  PGTO.BDCHAVE = MOV.BDCHAVE) ';
  if (PRVERORGAOPUBLICO = true) then
  begin
    WSQL = WSQL || '            left outer join(select BDCODTER, RF2.BDORGAOPUBLICO, RF2.BDCGCTER, RF2.BDNOMETER, RF2.BDREFEMP ';
    WSQL = WSQL || '                            from TTERCEIRO_REF RF2 ';
    WSQL = WSQL || '                            where RF2.BDREFEMP = coalesce((select first 1 BDREFEMP ';
    WSQL = WSQL || '                                                           from TTERCEIRO_REF RF3 ';
    WSQL = WSQL || '                                                           where RF3.BDCODTER = RF2.BDCODTER and ';
    WSQL = WSQL || '                                                                 RF3.BDREFEMP <= ''' || PRREFTELA || ''' ';
    WSQL = WSQL || '                                                           order by RF3.BDREFEMP desc), (select first 1 BDREFEMP ';
    WSQL = WSQL || '                                                                                         from TTERCEIRO_REF RF3 ';
    WSQL = WSQL || '                                                                                         where RF3.BDCODTER = RF2.BDCODTER ';
    WSQL = WSQL || '                                                                                         order by RF3.BDCODTER, RF3.BDREFEMP))) as TER on TER.BDCODTER = MOV.BDCODTER ';
    WSQL = WSQL || ' where IIF(' || :PRTIPOAPURACAORETIR || ' = 1 , MOV.bdcondpgto, IIF(TER.BDORGAOPUBLICO = TRUE, MOV.bdcondpgto, 0)) = 1 and ';
  end
  else
    WSQL = WSQL || ' where MOV.bdcondpgto = 1 and ';
  WSQL = WSQL || '                  (PGTO.BDDATAPGTOPAR between ''' || PRDATAINI || ''' and ''' || PRDATAFIN || ''') and ';
  WSQL = WSQL || '                  (PGTO.BDCODTIPOBAIXA = 1) and ';
  WSQL = WSQL || '                  IIF(MOV.BDTIPLAN = 0, ';
  if (PRVERORGAOPUBLICO = true) then
    WSQL = WSQL || ' IIF(TER.BDORGAOPUBLICO = TRUE, 1, ' || :PRTIPOAPURACAORETIR || ' ) , ' || :PRTIPOAPURACAORETIRTOM || ') = 1 ';
  else
    WSQL = WSQL || ' ' || :PRTIPOAPURACAORETIR || ' , ' || :PRTIPOAPURACAORETIRTOM || ') = 1 ';
  WSQL = WSQL || '            order by PGTO.BDCHAVE desc) PGTO ';
  WSQL = WSQL || '      join VEF_EMP_TMOVSERRET RET on (RET.BDCODEMP = PGTO.BDCODEMP and ';
  WSQL = WSQL || '            RET.BDCHAVE = PGTO.BDCHAVE) ';
  WSQL = WSQL || '      where (RET.BDVLRIR > 0) ';

  WSQL = WSQL || '      union all ';
    /* Demais Documentos */
    /* Tipo de apuração das retenções (PIS/Cofins/CSLL) */
  WSQL = WSQL || '        SELECT MOV.* FROM( ';
  WSQL = WSQL || '            select dem.BDCODEMP, dem.BDCHAVE, dem.BDIND_OPER + 1 as BDTIPLAN, dem.BDNUMDOC as BDNUMDOCINI, ';
  WSQL = WSQL || '                   dem.BDDT_OPER as BDDATAEMISSAO, ';
  WSQL = WSQL || '                   dem.BDVL_OPER as BDVALORNOTA, dem.BDVL_OPER as BDVALORPAGO, ';
  WSQL = WSQL || '                   dem.BDCODTER, ret.BDVLRPIS, ret.BDVLRCOFINS, ';
  WSQL = WSQL || '                   ret.BDVLRCSOCIAL, 0 as BDVLRINSS, 0 as BDVLRIR, ret.BDISSRET ';
  WSQL = WSQL || '            from (';
  WSQL = WSQL || '                  SELECT dem.* FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
  WSQL = WSQL || '                  JOIN TMP_TEMPRESAS EMP ON (EMP.BDCODEMP = dem.BDCODEMP) ';
  WSQL = WSQL || '                  WHERE dem.BDDT_OPER between ''' || PRDATAINI || ''' and ''' || PRDATAFIN || '''';
  WSQL = WSQL || '                 ) dem ';
  WSQL = WSQL || '            left outer join VEF_EMP_TMOVDEMRET ret on (ret.BDCODEMP = dem.BDCODEMP and ret.BDCHAVE = dem.BDCHAVE) ';
  WSQL = WSQL || '            WHERE ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or /*(ret.BDVLRIR > 0) or*/ (ret.BDISSRET > 0)) ';
  if (PRTIPOAPURACAORET = 1) then
  begin
    WSQL = WSQL || '              and dem.BDCONDPGTO <> 1 ';
    WSQL = WSQL || '            union all ';
    WSQL = WSQL || '            select pgto.BDCODEMP, pgto.BDCHAVE, dem.BDTIPLAN, dem.BDNUMDOCINI, dem.BDDATAEMISSAO, dem.BDVL_OPER as BDVALORNOTA, pgto.BDVALORPGTOPAR as BDVALORPAGO, dem.BDCODTER, ';
    WSQL = WSQL || '                   pgto.BDVALORRETPIS as BDVLRPIS, pgto.BDVALORRETCOFINS as BDVLRCOFINS, pgto.BDVALORRETCSLL as BDVLRCSOCIAL, pgto.BDVALORRETINSS as BDVLRINSS, 0 as BDVLRIR, pgto.BDVALORRETISSQN as BDISSRET ';
    WSQL = WSQL || '            from (select PGTO.* from VEF_EMP_TMOVF100PARPGTO pgto ';
    WSQL = WSQL || '                  JOIN TMP_TEMPRESAS EMP ON (EMP.BDCODEMP = PGTO.BDCODEMP) ';
    WSQL = WSQL || '                  WHERE (pgto.BDDATAPGTOPAR between ''' || PRDATAINI || ''' and ''' || PRDATAFIN || ''') ';
    WSQL = WSQL || '                  and (pgto.BDCODTIPOBAIXA = 1)) pgto ';/* #94385 Levar apenas pagamento/recebimento */
    WSQL = WSQL || '            join (select dem.BDCODEMP, dem.BDCHAVE, dem.BDIND_OPER + 1 as BDTIPLAN, dem.BDNUMDOC as BDNUMDOCINI, ';
    WSQL = WSQL || '                         dem.BDDT_OPER as BDDATAEMISSAO, dem.BDVL_OPER, dem.BDCODTER, ret.BDVLRPIS, ret.BDVLRCOFINS, ';
    WSQL = WSQL || '                         ret.BDVLRCSOCIAL, 0 as BDVLRINSS, 0 as BDVLRIR, ret.BDISSRET ';
    WSQL = WSQL || '                  from (';
    WSQL = WSQL || '                        SELECT dem.* FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
    WSQL = WSQL || '                        JOIN TMP_TEMPRESAS EMP ON (EMP.BDCODEMP = dem.BDCODEMP) ';
    WSQL = WSQL || '                       ) dem ';
    WSQL = WSQL || '                  left outer join VEF_EMP_TMOVDEMRET ret on (ret.BDCODEMP = dem.BDCODEMP and ret.BDCHAVE = dem.BDCHAVE) ';
    WSQL = WSQL || '                  WHERE ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or /*(ret.BDVLRIR > 0) or*/ (ret.BDISSRET > 0)) ';
    WSQL = WSQL || '                  and dem.BDCONDPGTO = 1 ) dem on (dem.BDCODEMP = pgto.BDCODEMP and dem.BDCHAVE = pgto.BDCHAVE) ';
  end
  WSQL = WSQL || '            union all ';
    /* Tipo de apuração das retenções IR */
  WSQL = WSQL || '            select dem.BDCODEMP, dem.BDCHAVE, dem.BDIND_OPER + 1 as BDTIPLAN, dem.BDNUMDOC as BDNUMDOCINI, ';
  WSQL = WSQL || '                   dem.BDDT_OPER as BDDATAEMISSAO, ';
  WSQL = WSQL || '                   dem.BDVL_OPER as BDVALORNOTA, dem.BDVL_OPER as BDVALORPAGO, ';
  WSQL = WSQL || '                   dem.BDCODTER, 0 as BDVLRPIS, 0 as BDVLRCOFINS, ';
  WSQL = WSQL || '                   0 as BDVLRCSOCIAL, 0 as BDVLRINSS, ret.BDVLRIR, 0 as BDISSRET ';
  WSQL = WSQL || '            from (';
  WSQL = WSQL || '                  SELECT dem.* FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
  WSQL = WSQL || '                  JOIN TMP_TEMPRESAS EMP ON (EMP.BDCODEMP = dem.BDCODEMP) ';
  WSQL = WSQL || '                  WHERE dem.BDDT_OPER between ''' || PRDATAINI || ''' and ''' || PRDATAFIN || '''';
  WSQL = WSQL || '                 ) dem ';
  WSQL = WSQL || '            left outer join VEF_EMP_TMOVDEMRET ret on (ret.BDCODEMP = dem.BDCODEMP and ret.BDCHAVE = dem.BDCHAVE) ';

  if (PRVERORGAOPUBLICO = true) then
  begin
    WSQL = WSQL || '            left outer join(select BDCODTER, RF2.BDORGAOPUBLICO, RF2.BDCGCTER, RF2.BDNOMETER, RF2.BDREFEMP ';
    WSQL = WSQL || '                            from TTERCEIRO_REF RF2 ';
    WSQL = WSQL || '                            where RF2.BDREFEMP = coalesce((select first 1 BDREFEMP ';
    WSQL = WSQL || '                                                           from TTERCEIRO_REF RF3 ';
    WSQL = WSQL || '                                                           where RF3.BDCODTER = RF2.BDCODTER and ';
    WSQL = WSQL || '                                                                 RF3.BDREFEMP <= ''' || PRREFTELA || ''' ';
    WSQL = WSQL || '                                                           order by RF3.BDREFEMP desc), (select first 1 BDREFEMP ';
    WSQL = WSQL || '                                                                                         from TTERCEIRO_REF RF3 ';
    WSQL = WSQL || '                                                                                         where RF3.BDCODTER = RF2.BDCODTER ';
    WSQL = WSQL || '                                                                                         order by RF3.BDCODTER, RF3.BDREFEMP))) as TER on TER.BDCODTER = DEM.BDCODTER ';
  end

  WSQL = WSQL || '   where          (/*(ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or*/ (ret.BDVLRIR > 0) /*or (ret.BDISSRET > 0)*/) ';
  WSQL = WSQL || '            AND (SELECT BDISVALID FROM SP_FILTER_REGIME_DEMDOC(DEM.BDIND_OPER, DEM.BDCONDPGTO, ';
  if (PRVERORGAOPUBLICO = true) then
    WSQL = WSQL || ' IIF(TER.BDORGAOPUBLICO = TRUE, 1, ' || :PRTIPOAPURACAORETIR || ' ) , ' || :PRTIPOAPURACAORETIRTOM || ')) = ''TRUE'' ';
  else
    WSQL = WSQL || ' ' || :PRTIPOAPURACAORETIR || ' , ' || :PRTIPOAPURACAORETIRTOM || ')) = ''TRUE'' ';

  WSQL = WSQL || '            union all ';

  /*Sql refeito para verificar órgão publico - #153689 - Kleiton Melo*/
  WSQL = WSQL || 'select PGTO.BDCODEMP, PGTO.BDCHAVE, PGTO.BDTIPLAN, PGTO.BDNUMDOCINI, PGTO.BDDATAEMISSAO, ';
  WSQL = WSQL || '                   PGTO.BDVL_OPER as BDVALORNOTA, PGTO.BDVALORPGTOPAR as BDVALORPAGO, PGTO.BDCODTER, 0 as BDVLRPIS, ';
  WSQL = WSQL || '               0 as BDVLRCOFINS, 0 as BDVLRCSOCIAL, 0 as BDVLRINSS, PGTO.BDVALORRETIRRF as BDVLRIR, 0 as BDISSRET ';
  WSQL = WSQL || '      from (select PGTO.BDCODEMP, PGTO.BDCHAVE, PGTO.BDVALORRETIRRF, PGTO.BDVALORPGTOPAR, ';
  WSQL = WSQL || '                       MOV.BDIND_OPER + 1 as BDTIPLAN, MOV.BDNUMDOC as BDNUMDOCINI, MOV.BDDT_OPER as BDDATAEMISSAO, ';
  WSQL = WSQL || '                     MOV.BDVL_OPER, MOV.BDCODTER, MOV.BDCONDPGTO ';
  WSQL = WSQL || '              from VEF_EMP_TMOVF100PARPGTO PGTO ';
  WSQL = WSQL || '             join TMP_TEMPRESAS EMP on (EMP.BDCODEMP = PGTO.BDCODEMP) ';
  WSQL = WSQL || '             join VEF_EMP_TMOVDEMAISDOC_F100 MOV on (PGTO.BDCODEMP = MOV.BDCODEMP and ';
  WSQL = WSQL || '                   PGTO.BDCHAVE = MOV.BDCHAVE) ';
  if (PRVERORGAOPUBLICO = true) then
  begin
    WSQL = WSQL || '            left outer join(select BDCODTER, RF2.BDORGAOPUBLICO, RF2.BDCGCTER, RF2.BDNOMETER, RF2.BDREFEMP ';
    WSQL = WSQL || '                            from TTERCEIRO_REF RF2 ';
    WSQL = WSQL || '                            where RF2.BDREFEMP = coalesce((select first 1 BDREFEMP ';
    WSQL = WSQL || '                                                           from TTERCEIRO_REF RF3 ';
    WSQL = WSQL || '                                                            where RF3.BDCODTER = RF2.BDCODTER and ';
    WSQL = WSQL || '                                                                 RF3.BDREFEMP <= ''' || PRREFTELA || '''  ';
    WSQL = WSQL || '                                                           order by RF3.BDREFEMP desc), (select first 1 BDREFEMP ';
    WSQL = WSQL || '                                                                                         from TTERCEIRO_REF RF3 ';
    WSQL = WSQL || '                                                                                         where RF3.BDCODTER = RF2.BDCODTER ';
    WSQL = WSQL || '                                                                                          order by RF3.BDCODTER, RF3.BDREFEMP))) as TER on TER.BDCODTER = MOV.BDCODTER ';
    WSQL = WSQL || ' where IIF(' || :PRTIPOAPURACAORETIR || ' = 1 , MOV.bdcondpgto, IIF(TER.BDORGAOPUBLICO = TRUE, MOV.bdcondpgto, 0)) = 1 and ';
  end
  else
    WSQL = WSQL || ' where bdcondpgto = 1 and';
  WSQL = WSQL || '               (PGTO.BDDATAPGTOPAR between ''' || PRDATAINI || ''' and ''' || PRDATAFIN || ''') and ';
  WSQL = WSQL || '               (PGTO.BDCODTIPOBAIXA = 1) and ';
  WSQL = WSQL || '               IIF(MOV.BDIND_OPER = 1, ' || :PRTIPOAPURACAORETIRTOM || ', ';
  if (PRVERORGAOPUBLICO = true) then
    WSQL = WSQL || '  IIF(TER.BDORGAOPUBLICO = TRUE, 1, ' || :PRTIPOAPURACAORETIR || ')) = 1 ';
  else
    WSQL = WSQL || ' ' || :PRTIPOAPURACAORETIR || ') = 1 ';

  WSQL = WSQL || '           order by PGTO.BDCHAVE desc) PGTO ';
  WSQL = WSQL || '     join VEF_EMP_TMOVDEMRET RET on (RET.BDCODEMP = PGTO.BDCODEMP and ';
  WSQL = WSQL || '            RET.BDCHAVE = PGTO.BDCHAVE) ';
  WSQL = WSQL || '      where (/*(RET.BDVLRPIS > 0) or (RET.BDVLRCOFINS > 0) or (RET.BDVLRCSOCIAL > 0) or*/ (RET.BDVLRIR > 0) /*or (RET.BDISSRET > 0)*/) ';
  WSQL = WSQL || ' ) MOV ';
  WSQL = WSQL || ' WHERE ((MOV.BDVLRPIS > 0) OR (MOV.BDVLRCOFINS > 0) OR (MOV.BDVLRCSOCIAL > 0) OR (MOV.BDVLRIR > 0) OR (MOV.BDISSRET > 0)) ';
  WSQL = WSQL || '      union all ';
    /* Entradas */
    /* Tipo de apuração das retenções (PIS/Cofins/CSLL) */
  WSQL = WSQL || '            select ent.BDCODEMP, ent.BDCHAVE, 5 as BDTIPLAN, ent.BDNUMDOCINI, ent.BDDATAEMISSAO, ';
  WSQL = WSQL || '                   ent.BDVALORNOTA, ent.BDVALORNOTA as BDVALORPAGO, ent.BDCODTER, ';
  WSQL = WSQL || '                   ret.BDVLRPIS, ret.BDVLRCOFINS, ret.BDVLRCSOCIAL, ded.BDRETINSS as BDVLRINSS, 0 as BDVLRIR, ret.BDISSRET ';
  WSQL = WSQL || '            from (';
  WSQL = WSQL || '                  SELECT ENT.* FROM VEF_EMP_TMOVENT ENT ';
  WSQL = WSQL || '                  JOIN TMP_TEMPRESAS EMP ON (EMP.BDCODEMP = ENT.BDCODEMP) ';
  WSQL = WSQL || '                  WHERE ent.BDDATAEMISSAO between ''' || PRDATAINI || ''' and ''' || PRDATAFIN || ''' ';
  WSQL = WSQL || '                 ) ENT';
  WSQL = WSQL || '            left outer join VEF_EMP_TMOVENTRET ret on (ret.BDCODEMP = ent.BDCODEMP and ret.BDCHAVE = ent.BDCHAVE) ';
  WSQL = WSQL || '            left outer join VEF_EMP_TMOVENTDED ded on (ded.BDCODEMP = ent.BDCODEMP and ded.BDCHAVE = ent.BDCHAVE) ';
  WSQL = WSQL || '            WHERE ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or (ret.BDISSRET > 0)) ';

  if (PRTIPOAPURACAORET = 1) then
  begin
    WSQL = WSQL || '              and ent.BDCONDPGTO <> 1 ';
    WSQL = WSQL || '            union all ';
    WSQL = WSQL || '            select pgto.BDCODEMP, pgto.BDCHAVE, 5 as BDTIPLAN, ent.BDNUMDOCINI, ent.BDDATAEMISSAO, ent.BDVALORNOTA, pgto.BDVALORPGTOPAR as BDVALORPAGO, ent.BDCODTER, ';
    WSQL = WSQL || '                   pgto.BDVALORRETPIS as BDVLRPIS, pgto.BDVALORRETCOFINS as BDVLRCOFINS, pgto.BDVALORRETCSLL as BDVLRCSOCIAL, pgto.BDVALORRETINSS as BDVLRINSS, 0 as BDVLRIR, pgto.BDVALORRETISSQN as BDISSRET ';
    WSQL = WSQL || '            from (select PGTO.* from VEF_EMP_TMOVENTPARPGTO pgto ';
    WSQL = WSQL || '                  JOIN TMP_TEMPRESAS EMP ON (EMP.BDCODEMP = PGTO.BDCODEMP) ';
    WSQL = WSQL || '                  WHERE (pgto.BDDATAPGTOPAR between ''' || PRDATAINI || ''' and ''' || PRDATAFIN || ''') ';
    WSQL = WSQL || '                  and (pgto.BDCODTIPOBAIXA = 1)) pgto ';/* #94385 Levar apenas pagamento/recebimento */
    WSQL = WSQL || '            join (select ent.BDCODEMP, ent.BDCHAVE, 5 as BDTIPLAN, ent.BDNUMDOCINI, ent.BDDATAEMISSAO, ent.BDVALORNOTA, ent.BDCODTER, ';
    WSQL = WSQL || '                         ret.BDVLRPIS, ret.BDVLRCOFINS, ret.BDVLRCSOCIAL, ded.BDRETINSS as BDVLRINSS, 0 as BDVLRIR, ret.BDISSRET ';
    WSQL = WSQL || '                  from (';
    WSQL = WSQL || '                        SELECT ENT.* FROM VEF_EMP_TMOVENT ENT';
    WSQL = WSQL || '                        JOIN TMP_TEMPRESAS EMP ON (EMP.BDCODEMP = ENT.BDCODEMP) ';
    WSQL = WSQL || '                       ) ENT ';
    WSQL = WSQL || '                  left outer join VEF_EMP_TMOVENTRET ret on (ret.BDCODEMP = ent.BDCODEMP and ret.BDCHAVE = ent.BDCHAVE) ';
    WSQL = WSQL || '                  left outer join VEF_EMP_TMOVENTDED ded on (ded.BDCODEMP = ent.BDCODEMP and ded.BDCHAVE = ent.BDCHAVE) ';
    WSQL = WSQL || '                  WHERE ((ret.BDVLRPIS > 0) or (ret.BDVLRCOFINS > 0) or (ret.BDVLRCSOCIAL > 0) or (ret.BDISSRET > 0)) ';
    WSQL = WSQL || '                  and ent.BDCONDPGTO = 1 ) ent on (ent.BDCODEMP = pgto.BDCODEMP and ent.BDCHAVE = pgto.BDCHAVE) ';
  end

  WSQL = WSQL || '            union all ';
    /* Tipo de apuração das retenções IR */
  WSQL = WSQL || '            select ent.BDCODEMP, ent.BDCHAVE, 5 as BDTIPLAN, ent.BDNUMDOCINI, ent.BDDATAEMISSAO, ';
  WSQL = WSQL || '                   ent.BDVALORNOTA, ent.BDVALORNOTA as BDVALORPAGO, ent.BDCODTER, ';
  WSQL = WSQL || '                   0 as BDVLRPIS, 0 as BDVLRCOFINS, 0 as BDVLRCSOCIAL, 0 as BDVLRINSS, ret.BDVLRIR, 0 as BDISSRET ';
  WSQL = WSQL || '            from (';
  WSQL = WSQL || '                  SELECT ENT.* FROM VEF_EMP_TMOVENT ENT ';
  WSQL = WSQL || '                  JOIN TMP_TEMPRESAS EMP ON (EMP.BDCODEMP = ENT.BDCODEMP) ';
  WSQL = WSQL || '                  WHERE ent.BDDATAEMISSAO between ''' || PRDATAINI || ''' and ''' || PRDATAFIN || ''' ';
  WSQL = WSQL || '                 ) ENT ';
  WSQL = WSQL || '            left outer join VEF_EMP_TMOVENTRET ret on (ret.BDCODEMP = ent.BDCODEMP and ret.BDCHAVE = ent.BDCHAVE) ';
  WSQL = WSQL || '            WHERE (ret.BDVLRIR > 0) ';
  if (PRTIPOAPURACAORETIRTOM = 1) then
  begin
    WSQL = WSQL || '            and ent.BDCONDPGTO <> 1 ';
    WSQL = WSQL || '            union all ';
    WSQL = WSQL || '            select pgto.BDCODEMP, pgto.BDCHAVE, 5 as BDTIPLAN, ent.BDNUMDOCINI, ent.BDDATAEMISSAO, ';
    WSQL = WSQL || '                   ent.BDVALORNOTA, pgto.BDVALORPGTOPAR as BDVALORPAGO, ent.BDCODTER, ';
    WSQL = WSQL || '                   0 as BDVLRPIS, 0 as BDVLRCOFINS, 0 as BDVLRCSOCIAL, 0 as BDVLRINSS, pgto.BDVALORRETIRRF as BDVLRIR, 0 as BDISSRET ';
    WSQL = WSQL || '            from (select PGTO.* from VEF_EMP_TMOVENTPARPGTO pgto ';
    WSQL = WSQL || '                  JOIN TMP_TEMPRESAS EMP ON (EMP.BDCODEMP = PGTO.BDCODEMP) ';
    WSQL = WSQL || '                  WHERE (pgto.BDDATAPGTOPAR between ''' || PRDATAINI || ''' and ''' || PRDATAFIN || ''') ';
    WSQL = WSQL || '                  and (pgto.BDCODTIPOBAIXA = 1)) pgto ';/* #94385 Levar apenas pagamento/recebimento */
    WSQL = WSQL || '            join (select ent.BDCODEMP, ent.BDCHAVE, 5 as BDTIPLAN, ent.BDNUMDOCINI, ent.BDDATAEMISSAO, ent.BDVALORNOTA, ent.BDCODTER, ';
    WSQL = WSQL || '                         ret.BDVLRPIS, ret.BDVLRCOFINS, ret.BDVLRCSOCIAL, ded.BDRETINSS as BDVLRINSS, 0 as BDVLRIR, ret.BDISSRET ';
    WSQL = WSQL || '                  from (';
    WSQL = WSQL || '                        SELECT ENT.* FROM VEF_EMP_TMOVENT ENT';
    WSQL = WSQL || '                        JOIN TMP_TEMPRESAS EMP ON (EMP.BDCODEMP = ENT.BDCODEMP) ';
    WSQL = WSQL || '                       ) ENT ';
    WSQL = WSQL || '                  left outer join VEF_EMP_TMOVENTRET ret on (ret.BDCODEMP = ent.BDCODEMP and ret.BDCHAVE = ent.BDCHAVE) ';
    WSQL = WSQL || '                  left outer join VEF_EMP_TMOVENTDED ded on (ded.BDCODEMP = ent.BDCODEMP and ded.BDCHAVE = ent.BDCHAVE) ';
    WSQL = WSQL || '                  WHERE (ret.BDVLRIR > 0) ';
    WSQL = WSQL || '                  and ent.BDCONDPGTO = 1 ) ent on (ent.BDCODEMP = pgto.BDCODEMP and ent.BDCHAVE = pgto.BDCHAVE) ';
  end
  WSQL = WSQL || '      ) mov ';
  WSQL = WSQL || 'left outer join VW_TTERCEIRO ter on (ter.BDCODTER = mov.BDCODTER) ';
  WSQL = WSQL || 'LEFT OUTER JOIN TEMPRESAS E ON(E.BDCODEMP = MOV.BDCODEMP) ';
  WSQL = WSQL || 'order by mov.BDCODEMP, mov.BDTIPLAN, mov.BDCHAVE ';

  for execute statement WSQL
          into WCODMATRIZ, WCODEMP, WCHAVE, WTIPLAN, WNUMDOCINI, WDATAEMISSAO, WVALORNOTA, WVALORPAGO, WVLRPIS,
          WVLRCOFINS, WVLRCSOCIAL, WVLRINSS, WVLRIR, WISSRET, WCODTER, WNOMETER, WCGCTER
  do
  begin
    if ((BDCODEMP <> WCODEMP) or (BDCHAVE <> WCHAVE) or (BDTIPLAN <> WTIPLAN)) then
    begin
      suspend;

        BDVLRPIS      = 0;
        BDVLRCOFINS   = 0;
        BDVLRCSOCIAL  = 0;
        BDVLRINSS     = 0;
        BDVLRIR       = 0;
        BDISSRET      = 0;
        BDVALORPAGO   = 0;
    end

    BDCODMATRIZ = WCODMATRIZ;
    BDCODEMP = WCODEMP;
    BDCHAVE = WCHAVE;
    BDTIPLAN = WTIPLAN;
    BDNUMDOCINI = WNUMDOCINI;
    BDDATAEMISSAO = WDATAEMISSAO;
    BDVALORNOTA = WVALORNOTA;

    BDVLRPIS = coalesce(WVLRPIS, 0) + coalesce(BDVLRPIS, 0);
    BDVLRCOFINS = coalesce(WVLRCOFINS, 0) + coalesce(BDVLRCOFINS, 0);
    BDVLRCSOCIAL = coalesce(WVLRCSOCIAL, 0) + coalesce(BDVLRCSOCIAL, 0);
    BDVLRINSS = coalesce(WVLRINSS, 0) + coalesce(BDVLRINSS, 0);
    BDVLRIR = coalesce(WVLRIR, 0) + coalesce(BDVLRIR, 0);
    BDISSRET = coalesce(WISSRET, 0) + coalesce(BDISSRET, 0);

    if ((BDCODEMP = WCODEMP) and
        (BDCHAVE = WCHAVE) and
        (BDTIPLAN = WTIPLAN)) then
    begin
      BDVALORPAGO = coalesce(WVALORPAGO, 0);
    end
    else
    begin
      BDVALORPAGO = coalesce(WVALORPAGO, 0) + coalesce(BDVALORPAGO, 0);
    end

    BDCODTER = WCODTER;
    BDNOMETER = WNOMETER;
    BDCGCTER = WCGCTER;
  end

  if ((WCODEMP is not null) and
      (WCHAVE is not null) and
      (WTIPLAN is not null)) then
    suspend;

end^

-- alt:14201 - 07/06/2016 - Trigger de auto incremento da tabela VRH_BASE_TAVISOPREVIO - Bruno L. R.
CREATE OR ALTER TRIGGER vrh_base_tavisoprevio_bi0 FOR vrh_base_tavisoprevio
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vCodigo = 0;
  IF ((NEW.bdcodavp IS NULL) OR (NEW.bdcodavp = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdcodavp) + 1), 0) FROM vrh_base_tavisoprevio INTO vCodigo;
       NEW.bdcodavp = vCodigo;
     END
END^

--14648 - 08/07/2016 - Criação da trigger (before insert) na tabela VRHF_BASE_TRUBRICAS_DOM_PADRAO para retornar o próximo código para o campo BDCODIGO - Bruno L. R.
CREATE OR ALTER TRIGGER vrhf_base_trubr_dom_pad_bi0 FOR vrhf_base_trubricas_dom_padrao
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF ((NEW.bdcodigo IS NULL) OR (NEW.bdcodigo = 0) ) THEN
     SELECT COALESCE(MAX(bdcodigo),0)+1 FROM VRHF_BASE_TRUBRICAS_DOM_PADRAO INTO NEW.bdcodigo;
END^

CREATE OR ALTER PROCEDURE SP_PRODEXISTENTES_SAIDA (
    BDCODEMP INTEGER,
    BDEAN VARCHAR(20),
    BDCODSAIDA VARCHAR(60),
    BDDESCPRODBUSCA VARCHAR(200))
RETURNS (
    CODPROD INTEGER,
    CODSAIDA VARCHAR(60),
    CODNCM INTEGER)
AS
DECLARE VARIABLE WTMP INTEGER;
DECLARE VARIABLE WPRIMVEZ INTEGER;
DECLARE VARIABLE WIGNORA INTEGER;
DECLARE VARIABLE WEAN VARCHAR(20);
DECLARE VARIABLE WDESCPRODBUSCA VARCHAR(200);
BEGIN
  CODPROD = 0;
  codsaida = '';
  codncm = 0;


  --alt:14920 - Elizeu - 27/06/16 - criado opção pra não carregar os dados cadastrais dos produtos na memória
  --Metodo 1 direto o codigo de saída
  SELECT FIRST 1 v.bdcodprod,v.bdcodsaida,v.bdncmprod FROM tcadpro_vinc v WHERE V.BDCODEMP = :bdcodemp AND v.bdcodsaida = :BDCODSAIDA
  INTO :CODPROD ,:CODSAIDA ,:CODNCM;


  --Metodo2 por ncm
  IF ((CODPROD = 0) AND (BDEAN <> '') AND (BDEAN <> '#')) THEN
  BEGIN
    --select BDCODIGOEAN, BDCODTER, BDCODENTRADA, BDCODPROD from TCADPRO where
    wIgnora = 0;
    wPrimVez = 1;
    FOR SELECT cadpro.BDCODIGOEAN, cadpro.BDDESCRICAOUNICA, cadpro.BDCODPROD
    FROM TCADPRO CADPRO
    WHERE cadpro.BDCODIGOEAN=:BDEAN
    INTO :wean, :wdescprodbusca, :wTmp DO
    BEGIN
      IF (wPrimVez = 1) THEN
      BEGIN
        IF (UPPER(wdescprodbusca) <> UPPER(bddescprodbusca)) THEN
        BEGIN
          wIgnora = 1;
        END
      END

      IF (wIgnora = 0) THEN --not wIgnora
      BEGIN
        IF (UPPER(wdescprodbusca) = UPPER(bddescprodbusca)) THEN
        BEGIN
          CODPROD = wTmp;
          BREAK;
        END
      END

      wIgnora = 0;
      wPrimVez = 0;
    END
  END


--metódo 3
  IF ((CODPROD = 0)) THEN
  BEGIN
    --Procura pela descricao naquela empresa

    SELECT FIRST 1 COALESCE(CADPRO.bdcodprod, 0)
    FROM (
          SELECT bdcodprod
          FROM TCADPRO
          WHERE BDDESCRICAOUNICA  = :bddescprodbusca
          ) CADPRO
    LEFT OUTER JOIN TCADPRO_VINC VINC ON (vinc.bdcodprod = cadpro.bdcodprod AND vinc.bdcodemp = :BDCODEMP)
    INTO :CODPROD;

    --Se nao achar procura unicamente pela descricao
    IF (CODPROD = 0) THEN
    BEGIN
      SELECT FIRST 1 CADPRO.bdcodprod
      FROM TCADPRO CADPRO
      WHERE CADPRO.BDDESCRICAOUNICA  = :bddescprodbusca
      INTO :CODPROD;
    END
  END


  IF (CODPROD > 0) THEN
  BEGIN
    SELECT bdCODSAIDA, bdNCMPROD FROM TCADPRO_VINC WHERE bdcodemp=:BDCODEMP AND bdcodprod = :codprod INTO :codsaida, :codNCM;
  END


  SUSPEND;

END^

CREATE OR ALTER TRIGGER VRH_BASE_TAMBIENTETRABALHO_BI0 FOR VRH_BASE_TAMBIENTETRABALHO
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vCodigo = 0;
  IF ((NEW.bdcodamb IS NULL) OR (NEW.bdcodamb = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodamb)+1),1) FROM VRH_BASE_TAMBIENTETRABALHO INTO vCodigo;
      NEW.bdcodamb = vCodigo;
    END
END^

CREATE OR ALTER TRIGGER VRH_BASE_TAMBTRAB_FR_BI0 FOR VRH_BASE_TAMBTRAB_FR
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vCodigo = 0;
  IF ((NEW.bdcodframb IS NULL) OR (NEW.bdcodframb = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodframb)+1),1) FROM VRH_BASE_TAMBTRAB_FR WHERE bdcodemp = NEW.bdcodemp AND bdcodamb = NEW.bdcodamb INTO vCodigo;
      NEW.bdcodframb = vCodigo;
    END
END^

CREATE OR ALTER TRIGGER VRH_EMP_TTRABAVULSO_BI0 FOR VRH_EMP_TTRABAVULSO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (COALESCE(NEW.bdchave, 0) = 0) THEN
    SELECT COALESCE(MAX(bdchave), 0) + 1
    FROM vrh_emp_ttrabavulso
    WHERE bdcodemp = NEW.bdcodemp AND
          bdref = NEW.bdref
    INTO NEW.bdchave;
END^

CREATE OR ALTER TRIGGER VRH_BASE_TRUBRICAES_VER_PD_AIU0 FOR VRH_BASE_TRUBRICAES_VER_PD
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
begin
  /* Trigger text */
  update VRH_BASE_TVERBAS_PADRAO set BDCODRESPD = new.bdchave where BDCODVERPD = new.bdcodver;
end^

CREATE OR ALTER trigger vfin_base_tescparfat_bi0 for vfin_base_tescparfat
active before insert or update position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vRefAtual INTEGER;
  DECLARE VARIABLE vFormaTributacao INTEGER;
  DECLARE VARIABLE vCODEMP INTEGER;
BEGIN
  vFormaTributacao = 0;
  /* somente na inserção */
  IF (OLD.bdcodesc IS NULL) THEN
     BEGIN
      vcodigo = 0;
      IF ((NEW.bdcodesc IS NULL) OR (NEW.bdcodesc = 0)) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodesc)),1) FROM tescritorio INTO vcodigo;
            NEW.bdcodesc = vcodigo;
         END
      ELSE
        BEGIN
           SELECT bdcodesc FROM tescritorio WHERE bdcodesc = NEW.bdcodesc INTO vcodigo;
    
           IF (vcodigo = 0) THEN
             BEGIN
                SELECT COALESCE((MAX(bdcodesc)),1) FROM tescritorio INTO vcodigo;
                NEW.bdcodesc = vcodigo;
             END
        END
     END

  /*Atualizar empresa por referência - deve-se criar registros em todas tabelas por referência????, comentado por enquanto*/
  /*criar atualizar dados referente ao enqudramento federal na tabela de empresa que representa o gestor*/
--  vCodigo = 0;
--  SELECT BDCODEMPINTEG FROM tescritorio
--  WHERE BDCODESC = NEW.BDCODESC INTO vCodigo;
--  IF (vCodigo > 0) THEN
--    BEGIN
--      vRefAtual = (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database);
--      IF (vRefAtual IS NULL) THEN
--         vRefAtual = SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(CURRENT_DATE AS VARCHAR(10)) FROM 6 FOR 2);
--
--
--      SELECT BDCODEMP FROM TEMPRESAS_REF WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual
--      INTO :vCODEMP;
--
--      IF (:vcodemp IS  NULL) THEN --pegar a última referência lançada
--        BEGIN
--         SELECT MAX(BDREFEMP) FROM TEMPRESAS_REF WHERE BDCODEMP = :vCodigo
--         INTO :vRefAtual;
--        END

          --TENQFED
--        IF (NEW.bdcodenqfed <> 3) THEN
--           vformatributacao = 0;


--        vCODEMP = 0;
--        SELECT BDCODEMP FROM TEMPRESAS_REF WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual
--        INTO :vCODEMP;
--
--        IF (:vcodemp > 0) THEN
--           BEGIN
--             --inserção
--             IF (OLD.bdcodesc IS NULL) THEN
--                BEGIN
--                  DELETE FROM TENQFED WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual;
--                END
--             ELSE
--                BEGIN
--                  SELECT BDFORMATRIBUTACAO FROM TENQFED WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual INTO vFormaTributacao;
--                  DELETE FROM TENQFED WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual;
--                END

--              UPDATE OR INSERT INTO TENQFED (BDCODENQFED, BDCODEMP, BDREFEMP, BDFORMATRIBUTACAO)
--              VALUES(NEW.bdcodenqfed, :vcodigo, :vrefatual, :vformatributacao) MATCHING (BDCODENQFED, BDCODEMP, BDREFEMP);
            
              --VEF_BASE_TEMPCADATV e VEF_BASE_TEMPPARFEDPORATV
              --retirado update or insert, pois gerava erros ao salvar empresa que tinha gestor associado
--              IF ((UPPER(NEW.BDANEXOIII) = 'TRUE') OR (UPPER(NEW.BDANEXOIV) = 'TRUE') OR (UPPER(NEW.BDANEXOV) = 'TRUE') OR (UPPER(NEW.BDANEXOVI) = 'TRUE')) THEN
--                 BEGIN
--                   vcodemp = 0;
--                   SELECT BDCODEMP FROM VEF_BASE_TEMPCADATV WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual
--                   INTO :vCODEMP;
--
--                   IF (:vCodEmp > 0) THEN
--                      BEGIN
--                        --exception ex_date vCodEmp||' U '||vRefAtual;
--                        UPDATE VEF_BASE_TEMPCADATV SET BDSERVICO = 'TRUE' WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual;
--                      END
--                   ELSE
--                      BEGIN
--                        --exception ex_date vCodEmp||' I '||vRefAtual;
--                        INSERT INTO VEF_BASE_TEMPCADATV (BDCODEMP, BDREFEMP, BDSERVICO) VALUES (:vCodigo, :vrefatual, 'TRUE');
--                      END
--
--                   vcodemp = 0;
--                   SELECT BDCODEMP FROM VEF_BASE_TEMPPARFEDPORATV WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual
--                   INTO :vCODEMP;
--
--                   IF (:vCodEmp > 0) THEN
--                      UPDATE VEF_BASE_TEMPPARFEDPORATV SET BDSERVICO = 'TRUE' WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual;
--                   ELSE
--                      INSERT INTO VEF_BASE_TEMPPARFEDPORATV (BDCODEMP, BDREFEMP, BDSERVICO, BDCOMERCIO, BDINDUSTRIA, BDLRISSSN) VALUES (:vCodigo, :vrefatual, 'TRUE', 'FALSE', 'FALSE', 0);
--
--                   --update or insert into VEF_BASE_TEMPCADATV(BDCODEMP, BDREFEMP, BDSERVICO)
--                   --values (:vCodigo, :vrefatual, 'TRUE') matching (BDCODEMP, BDREFEMP);
--
--                   --update or insert into VEF_BASE_TEMPPARFEDPORATV(BDCODEMP, BDREFEMP, BDSERVICO)
--                   --values (:vCodigo, :vrefatual, 'TRUE') matching (BDCODEMP, BDREFEMP);
--                 END
--              ELSE
--                 BEGIN
--                   vcodemp = 0;
--                   SELECT BDCODEMP FROM VEF_BASE_TEMPCADATV WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual
--                   INTO :vCODEMP;
--
--                   IF (:vCodEmp > 0) THEN
--                      UPDATE VEF_BASE_TEMPCADATV SET BDCOMERCIO = 'FALSE', BDINDUSTRIA = 'FALSE', BDSERVICO = 'FALSE' WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual;
--                   ELSE
--                      INSERT INTO VEF_BASE_TEMPCADATV (BDCODEMP, BDREFEMP, BDCOMERCIO, BDINDUSTRIA, BDSERVICO) VALUES (:vCodigo, :vrefatual, 'FALSE', 'FALSE', 'FALSE');
--
--
--                   vcodemp = 0;
--                   SELECT BDCODEMP FROM VEF_BASE_TEMPPARFEDPORATV WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual
--                   INTO :vCODEMP;
--
--                   IF (:vCodEmp > 0) THEN
--                      UPDATE VEF_BASE_TEMPPARFEDPORATV SET BDCOMERCIO = 'FALSE', BDINDUSTRIA = 'FALSE', BDSERVICO = 'FALSE' WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual;
--                   ELSE
--                      INSERT INTO VEF_BASE_TEMPPARFEDPORATV (BDCODEMP, BDREFEMP, BDCOMERCIO, BDINDUSTRIA, BDSERVICO, BDLRISSSN) VALUES (:vCodigo, :vrefatual, 'FALSE', 'FALSE', 'FALSE', 0);
--
--                   --update or insert into VEF_BASE_TEMPCADATV(BDCODEMP, BDREFEMP, BDCOMERCIO, BDINDUSTRIA, BDSERVICO)
--                   --values (:vCodigo, :vrefatual, 'FALSE', 'FALSE', 'FALSE') matching (BDCODEMP, BDREFEMP);
--
--                   --update or insert into VEF_BASE_TEMPPARFEDPORATV(BDCODEMP, BDREFEMP, BDCOMERCIO, BDINDUSTRIA, BDSERVICO)
--                   --values(:vCodigo, :vRefAtual, 'FALSE', 'FALSE', 'FALSE') matching (BDCODEMP, BDREFEMP);
--                 END
            

--              vcodemp = 0;
--              SELECT BDCODEMP FROM VEF_BASE_TEMPITEMSATV WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual
--              INTO :vCODEMP;
--
--              IF (:vCodEmp > 0) THEN
--                 UPDATE VEF_BASE_TEMPITEMSATV SET
--                 BDANEXOIII_2018 = NEW.BDANEXOIII,
--                 BDANEXOIV_2018 = NEW.BDANEXOIV,
--                 BDANEXOV_2018 = NEW.bdanexov
--                 WHERE BDCODEMP = :vCodigo AND BDREFEMP = :vrefatual;
--              ELSE
--                 INSERT INTO VEF_BASE_TEMPITEMSATV (BDCODEMP, BDREFEMP, BDANEXOIII_2018, BDANEXOIV_2018, BDANEXOV_2018)
--                 VALUES (:vCodigo, :vrefatual, NEW.BDANEXOIII, NEW.BDANEXOIV, NEW.BDANEXOV);
--              --VEF_BASE_TEMPITEMSATV
--              --update or insert into VEF_BASE_TEMPITEMSATV(BDCODEMP, BDREFEMP, BDANEXOIII, BDANEXOIV, BDANEXOV, BDANEXOVI)
--              --values(:vcodigo, :vrefatual, new.BDANEXOIII, new.BDANEXOIV, new.BDANEXOV, new.BDANEXOVI) matching (BDCODEMP, BDREFEMP);
--          END
--    END
END
^

CREATE OR ALTER PROCEDURE SP_VALIDACHAVE_NFE_CTE (
    PRCHAVENFE DM_CHAVENFE)
RETURNS (
    BDISVALID VARCHAR(5))
AS
DECLARE VARIABLE WVERIFICADOR INTEGER;
DECLARE VARIABLE WSOMA INTEGER;
BEGIN
  /*Patrick T. Sá - Rotina desenvolvida para validação de Chave de NFe e CTe no banco*/
  wSoma = 0;

  SELECT UPPER(RESULT) FROM SP_TIRATODOSSINAIS(:PRCHAVENFE) INTO :PRCHAVENFE;

  IF (CHAR_LENGTH(:PRCHAVENFE) <> 44) THEN
    BEGIN
      BDISVALID = 'FALSE';
      SUSPEND;
      EXIT;
    END

  SELECT SUM (
              (CAST(SUBSTRING(:PRCHAVENFE FROM 43 FOR 1) AS INTEGER) * 2) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 42 FOR 1) AS INTEGER) * 3) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 41 FOR 1) AS INTEGER) * 4) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 40 FOR 1) AS INTEGER) * 5) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 39 FOR 1) AS INTEGER) * 6) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 38 FOR 1) AS INTEGER) * 7) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 37 FOR 1) AS INTEGER) * 8) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 36 FOR 1) AS INTEGER) * 9) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 35 FOR 1) AS INTEGER) * 2) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 34 FOR 1) AS INTEGER) * 3) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 33 FOR 1) AS INTEGER) * 4) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 32 FOR 1) AS INTEGER) * 5) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 31 FOR 1) AS INTEGER) * 6) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 30 FOR 1) AS INTEGER) * 7) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 29 FOR 1) AS INTEGER) * 8) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 28 FOR 1) AS INTEGER) * 9) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 27 FOR 1) AS INTEGER) * 2) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 26 FOR 1) AS INTEGER) * 3) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 25 FOR 1) AS INTEGER) * 4) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 24 FOR 1) AS INTEGER) * 5) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 23 FOR 1) AS INTEGER) * 6) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 22 FOR 1) AS INTEGER) * 7) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 21 FOR 1) AS INTEGER) * 8) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 20 FOR 1)) - 48) * 9) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 19 FOR 1)) - 48) * 2) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 18 FOR 1)) - 48) * 3) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 17 FOR 1)) - 48) * 4) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 16 FOR 1)) - 48) * 5) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 15 FOR 1)) - 48) * 6) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 14 FOR 1)) - 48) * 7) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 13 FOR 1)) - 48) * 8) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 12 FOR 1)) - 48) * 9) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 11 FOR 1)) - 48) * 2) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 10 FOR 1)) - 48) * 3) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 9  FOR 1)) - 48) * 4) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 8  FOR 1)) - 48) * 5) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 7  FOR 1)) - 48) * 6) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 6 FOR 1) AS INTEGER) * 7) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 5 FOR 1) AS INTEGER) * 8) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 4 FOR 1) AS INTEGER) * 9) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 3 FOR 1) AS INTEGER) * 2) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 2 FOR 1) AS INTEGER) * 3) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 1 FOR 1) AS INTEGER) * 4)
             )
  FROM RDB$DATABASE
  INTO :wSOMA;

  IF ((:wSOMA IS NULL) OR (:wSOMA = 0)) THEN
    BEGIN
      BDISVALID = 'FALSE';
      SUSPEND;
    END
  ELSE
    BEGIN
      wSoma = wSoma - (11 * (TRUNC(wSoma / 11)));
      IF ((wSoma = 0) OR (wSoma = 1)) THEN
        BEGIN
          wVerificador = 0;
        END
      ELSE
        BEGIN
          wVerificador = 11 - wSoma;
        END

      IF (wVerificador = (CAST(SUBSTRING(:PRCHAVENFE FROM 44 FOR 1) AS INTEGER))) THEN
        BEGIN
          BDISVALID = 'TRUE';
          SUSPEND;
        END
      ELSE
        BEGIN
          BDISVALID = 'FALSE';
          SUSPEND;
        END
    END
END^

CREATE OR ALTER PROCEDURE SP_VALIDA_LANCAMENTO_EXISTENTE (
    PRSERIE VARCHAR(6),
    PRDATAEMI DATE,
    PRNRNOTA INTEGER,
    PRMODELO VARCHAR(10),
    PRESPECIE VARCHAR(5),
    PRTIPLAN VARCHAR(3))
RETURNS (
    BDCHAVE INTEGER,
    BDCODEMP INTEGER,
    BDEXISTE VARCHAR(5))
AS
DECLARE VARIABLE FSQL VARCHAR(10000);
DECLARE VARIABLE FNRNOTASAI VARCHAR(5);
DECLARE VARIABLE FDATAEMISAI VARCHAR(5);
DECLARE VARIABLE FSERIESAI VARCHAR(5);
DECLARE VARIABLE FESPECIESAI VARCHAR(5);
DECLARE VARIABLE FNATOPSAI VARCHAR(5);
DECLARE VARIABLE FMODELOSAI VARCHAR(5);
DECLARE VARIABLE FCHAVE INTEGER;
DECLARE VARIABLE FCODEMP INTEGER;
BEGIN
  /*PRTIPLAN = ENT, SAI ou SER*/

  SELECT R.BDNRNOTASAI, R.BDDATAEMISAI, R.BDSERIESAI, R.BDESPECIESAI, R.BDNATOPSAI, R.BDMODELOSAI
  FROM VEF_BASE_TCONFLANCREPETIDOS R INTO :FNRNOTASAI, :FDATAEMISAI, :FSERIESAI, :FESPECIESAI, :FNATOPSAI, :FMODELOSAI;

  FSQL = '';
  IF (:PRTIPLAN = 'SAI') THEN
    BEGIN
      FSQL = 'SELECT S.BDCODEMP, S.BDCHAVE FROM VEF_EMP_TMOVSAI S ';

      IF (UPPER(:FNRNOTASAI) = 'TRUE') THEN
        FSQL = FSQL || ' WHERE S.BDNUMDOCINI = '||:PRNRNOTA||' AND BDNUMDOCFIM = '||:PRNRNOTA;

      IF (UPPER(:FMODELOSAI) = 'TRUE') THEN
        FSQL = FSQL || ' AND S.BDMODELO = '||:PRMODELO;

      IF (UPPER(:FDATAEMISAI) = 'TRUE') THEN
        FSQL = FSQL || ' AND S.BDDATAEMISSAO = '||:PRDATAEMI;

      IF (UPPER(:FSERIESAI) = 'TRUE') THEN
        FSQL = FSQL || ' AND S.BDSERIE = '||:PRSERIE;

      IF (UPPER(:FESPECIESAI) = 'TRUE') THEN
        FSQL = FSQL || ' AND S.BDESPECIE = '||:PRESPECIE;

    END

  EXECUTE STATEMENT FSQL
  INTO
    :FCODEMP,
    :FCHAVE;

  IF (:FCHAVE > 0) THEN
    BEGIN
      BDEXISTE = 'TRUE';
      BDCODEMP = :FCODEMP;
      BDCHAVE  = :FCHAVE;
    END
  ELSE
    BEGIN
      BDEXISTE = 'FALSE';
      BDCODEMP = -1;
      BDCHAVE  = -1;
    END
  SUSPEND;
END^

CREATE OR ALTER TRIGGER tmp_tmovsai_temp_gera_chave FOR tmp_vef_emp_tmovsai_temp
ACTIVE BEFORE UPDATE POSITION 0
AS
DECLARE VARIABLE wChave INTEGER;
BEGIN
  IF (OLD.BDEDITCHAVE IS NULL) THEN
    BEGIN
      wChave = GETORDEMSEQUENCIAL(1);
      NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - :wChave)+1;
    END
END^

CREATE OR ALTER PROCEDURE SP_CRIA_PRE_CONTABILIZACAODIFAL (
    PRSESSAO INTEGER,
    PRCODPLANOONLINE INTEGER,
    PRTIPOLAN VARCHAR(5),
    PREF INTEGER)
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_CRIA_PRE_CONTABILIZACAO_AUX (
    PRSESSAO INTEGER,
    PRCODPLANOONLINE INTEGER,
    prtipolan VARCHAR(4),
    prTipoIntDesc INTEGER)
AS
BEGIN

END^

create or alter procedure SP_CRIA_CONTAB_RET_FUNRURAL (
    PRSESSAO integer,
    PRCODPLANOONLINE integer,
    PRENQFED integer,
    PRTIPOLAN varchar(5),
    PRFORMATRIBUTACAO integer = 0)
as
BEGIN

END^

create or alter procedure SP_CRIA_PRE_CONTABILIZACAO_RET (
    PRSESSAO integer,
    PRCODPLANOONLINE integer,
    PRENQFED integer,
    PRTIPOLAN varchar(5),
    PRFORMATRIBUTACAO integer = 0)
as
BEGIN

END^

create or alter procedure SP_CRIA_PRE_CONTABILIZACAO (
    PRSESSAO integer,
    PRCODPLANOONLINE integer,
    PRENQFED integer,
    PRCODCONFIRLP integer,
    PRTIPOLAN varchar(5),
    PRCODCONFDIMESC integer = 0,
    PRFORMATRIBUTACAO integer = 0)
as
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_TRANSFERENCIA_LAN (
    PRID_TERMINAL INTEGER,
    PRCODEMPORI INTEGER,
    PRCODEMPDEST INTEGER,
    PRREFTRANS INTEGER,
    PRTIPOLAN CHAR(3))
AS
BEGIN

END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_MOVPROSAI_TEMP (
    PRSESSAO INTEGER,
    PRCODPLANOINCO INTEGER,
    PRVALIDARCST VARCHAR(5),
    PRSESSAOPRO INTEGER)
AS
DECLARE VARIABLE WCADPROAUTO VARCHAR(5);
BEGIN
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_MOVPROSAI_TEMP','1');
  DELETE FROM VEF_INCON_TMOVSAI INCO
  WHERE INCO.BDSESSAO = :PRSESSAO
  AND INCO.BDTIPOINCON = 3;
  SELECT UPPER(I.BDCADPROAUTO) FROM VEF_BASE_TACOESINCONS I
  WHERE I.BDCODPLANOINCONS = :PRCODPLANOINCO INTO :wCadProAuto;
--  IF ((:wCadProAuto = 'TRUE') and (:PRSESSAOPRO > 0)) THEN
--    BEGIN                                              
--/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_MOVPROSAI_TEMP','1.1');
--      UPDATE TMP_TCADPRO_TEMP P
--      SET P.BDCODCSTIPISAI = (SELECT FIRST 1 M.BDCODCSTIPI  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
--          P.BDCODCSTPISSAI = (SELECT FIRST 1 M.BDCODCSTPIS  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
--          P.BDCODCSTCOFSAI = (SELECT FIRST 1 M.BDCODCSTCOF  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
--          P.BDCODCSTICMS   = (SELECT FIRST 1 M.BDCODCSTICMS FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
--          P.BDCODCSTIPIENT = (SELECT FIRST 1 M.BDCODCSTIPI  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
--          P.BDCODCSTPISENT = (SELECT FIRST 1 M.BDCODCSTPIS  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
--          P.BDCODCSTCOFENT = (SELECT FIRST 1 M.BDCODCSTCOF  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
--          P.BDALIQICMS     = Coalesce(P.BDALIQICMS,(SELECT FIRST 1 M.BDALIQICMS   FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC)),
--          P.BDALIQPIS      = (SELECT FIRST 1 M.BDALIQPIS    FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
--          P.BDALIQCOF      = (SELECT FIRST 1 M.BDALIQCOFINS FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
--          P.BDALIQPISENT   = (SELECT FIRST 1 M.BDALIQPIS    FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
--          P.BDALIQCOFENT   = (SELECT FIRST 1 M.BDALIQCOFINS FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
--          P.BDALIQIPI      = (SELECT FIRST 1 M.BDALIQIPI    FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC),
--          P.BDALIQICMSST   = (SELECT FIRST 1 M.BDALIQST     FROM TMP_VEF_EMP_TMOVPROSAI_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND M.BDALTCODPROD = P.BDEDITCHAVE ORDER BY M.BDSESSAO, M.BDCODEMP, M.BDCHAVE DESC, M.BDORDEM DESC, M.BDORDEMPRO DESC)
--      WHERE P.BDSESSAO = :PRSESSAOPRO;                                    
--/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_MOVPROSAI_TEMP','1.2');
--      EXECUTE PROCEDURE SP_ATUALIZAR_CST_PROD(:PRSESSAOPRO, 'TRUE');      
--/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_MOVPROSAI_TEMP','1.3');
--    END
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_MOVPROSAI_TEMP','2');
--  IF (:wCadProAuto <> 'TRUE') THEN
--    BEGIN
--      INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, bdordempro, BDTIPOINCON)
--      SELECT P.BDCODEMP, P.BDCHAVE, P.BDORDEM, P.BDSESSAO, 66 BDCODINCONSISTENCIA, P.BDORDEMPRO, 3 BDTIPOINCON
--      FROM TMP_VEF_EMP_TMOVPROSAI_TEMP P
--      LEFT OUTER JOIN TMP_TCADPRO_TEMP CP ON(CP.BDSESSAO = :PRSESSAOPRO AND CP.BDEDITCHAVE = P.BDALTCODPROD)
--       WHERE P.BDSESSAO = :PRSESSAO
--      AND (CP.BDSITUACAO = 0); /*Produto não cadastrado e o usuário não optou por cadastrar.*/
--    END
  /*Inconsistencia do valor de desconto maior do que o valor do item*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, bdordempro, BDTIPOINCON)
  SELECT P.BDCODEMP, P.BDCHAVE, P.BDORDEM, P.BDSESSAO, 34 BDCODINCONSISTENCIA, P.BDORDEMPRO, 3 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND BDVLRDESC > BDVLRITEM;
  PRVALIDARCST = COALESCE(UPPER(:PRVALIDARCST), 'FALSE');
  IF (:PRVALIDARCST = 'TRUE') THEN
    BEGIN
      /*35 - PIS*/
      INSERT INTO VEF_INCON_TMOVSAI(bdsessao, bdcodemp, bdchave, bdordem, bdordempro, bdcodinconsistencia, BDTIPOINCON)
      SELECT P.BDSESSAO, P.BDCODEMP, P.BDCHAVE, P.BDORDEM, P.BDORDEMPRO, 35 BDCODINCONSISTENCIA, 3 BDTIPOINCON
      FROM TMP_VEF_EMP_TMOVPROSAI_TEMP P
      JOIN TMP_VEF_EMP_TMOVSAI_TEMP M ON(M.BDSESSAO = P.BDSESSAO AND M.BDCODEMP = P.BDCODEMP AND M.BDCHAVE = P.BDCHAVE AND M.BDMODELO NOT IN(06, 28, 29))
      LEFT OUTER JOIN (SELECT BDCODCSTPIS FROM VEF_BASE_TTABCSTPIS WHERE ((BDCODCSTPIS BETWEEN 1 AND 49) OR (BDCODCSTPIS = 99))) PIS ON(PIS.BDCODCSTPIS = P.BDCODCSTPIS)
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDVLRPIS > 0
      AND ((P.BDCODCSTPIS IS NOT NULL) AND (P.BDCODCSTPIS > 0))
      AND PIS.BDCODCSTPIS IS NULL;
      /*36 - Cofins*/
      INSERT INTO VEF_INCON_TMOVSAI(bdsessao, bdcodemp, bdchave, bdordem, bdordempro, bdcodinconsistencia, BDTIPOINCON)
      SELECT P.BDSESSAO, P.BDCODEMP, P.BDCHAVE, P.BDORDEM, P.BDORDEMPRO, 36 BDCODINCONSISTENCIA, 3 BDTIPOINCON
      FROM TMP_VEF_EMP_TMOVPROSAI_TEMP P
      JOIN TMP_VEF_EMP_TMOVSAI_TEMP M ON(M.BDSESSAO = P.BDSESSAO AND M.BDCODEMP = P.BDCODEMP AND M.BDCHAVE = P.BDCHAVE AND M.BDMODELO NOT IN(06, 28, 29))
      LEFT OUTER JOIN (SELECT BDCODCSTCOF FROM VEF_BASE_TTABCSTCOF WHERE ((BDCODCSTCOF BETWEEN 1 AND 49) OR (BDCODCSTCOF = 99))) COF ON(COF.BDCODCSTCOF = P.BDCODCSTCOF)
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDVLRCOFINS > 0
      AND ((P.BDCODCSTCOF IS NOT NULL) AND (P.BDCODCSTCOF > 0))
      AND COF.BDCODCSTCOF IS NULL;
      /*37 - IPI*/
      INSERT INTO VEF_INCON_TMOVSAI(bdsessao, bdcodemp, bdchave, bdordem, bdordempro, bdcodinconsistencia, BDTIPOINCON)
      SELECT P.BDSESSAO, P.BDCODEMP, P.BDCHAVE, P.BDORDEM, P.BDORDEMPRO, 37 BDCODINCONSISTENCIA, 3 BDTIPOINCON
      FROM TMP_VEF_EMP_TMOVPROSAI_TEMP P
      JOIN TMP_VEF_EMP_TMOVSAI_TEMP M ON(M.BDSESSAO = P.BDSESSAO AND M.BDCODEMP = P.BDCODEMP AND M.BDCHAVE = P.BDCHAVE AND M.BDMODELO NOT IN(06, 28, 29))
      LEFT OUTER JOIN (SELECT BDCODCSTIPI FROM VEF_BASE_TTABCSTIPI WHERE BDCODEXPCSTIPI BETWEEN 50 AND 99) IPI ON(IPI.BDCODCSTIPI = P.BDCODCSTIPI)
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDVLRIPI > 0
      AND ((P.BDCODCSTIPI IS NOT NULL) AND (P.BDCODCSTIPI > 0))
      AND IPI.BDCODCSTIPI IS NULL;
    END
  /*Se a situação do produto estiver como 0 - Não relacionado ele não irá ser importado e tudo que tiver produto deve se tornar inconsistente*/
  --73 - Produto não cadastrado.
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, bdordempro, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDSESSAO, 73 BDCODINCONSISTENCIA, S.BDORDEMPRO, 3 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP S
  LEFT OUTER JOIN TMP_TCADPRO_TEMP P ON(P.BDSESSAO = :PRSESSAOPRO AND P.BDCODPROD = S.BDCODPROD)    
  LEFT OUTER JOIN TCADPRO PRO ON (PRO.bdcodprod = S.bdcodprod)
  WHERE S.BDSESSAO = :PRSESSAO AND ((P.BDSITUACAO = 0) or ((P.BDCODPROD IS NULL) AND (PRO.BDCODPROD IS NULL)));

  /*Se o produto for inconsistente, torna o lançamento inconsistente tambem*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, bdordempro, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDSESSAO, 76 BDCODINCONSISTENCIA, S.BDORDEMPRO, 3 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVPROSAI_TEMP S
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :PRSESSAOPRO AND PRO.BDCODEMP = S.BDCODEMP AND PRO.BDCODPROD = S.BDALTCODPROD)
  LEFT OUTER JOIN VEF_INCON_TMOVSAI SAI ON(SAI.BDSESSAO = :PRSESSAO AND SAI.BDCODEMP = S.BDCODEMP AND SAI.BDCHAVE = S.BDCHAVE AND SAI.BDORDEM = S.BDORDEM AND SAI.BDORDEMPRO = S.BDORDEMPRO AND SAI.BDCODINCONSISTENCIA = 73)
  WHERE S.BDSESSAO = :PRSESSAO
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  AND SAI.BDCODINCONSISTENCIA IS NULL
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDSESSAO, BDCODINCONSISTENCIA, S.BDORDEMPRO;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_MOVPROSAI_TEMP','3');
END^

CREATE OR ALTER PROCEDURE SP_INSERT_INCONSIS_CONTA_REDZ (
    PRSESSAO INTEGER,
    PRCODPLANOONLINE INTEGER,
    PRENQFED INTEGER)
AS
BEGIN

END^

create or alter procedure SP_INSERE_COMPLEMENTO_HIST_CP (
    PRTIPOLAN varchar(5) collate WIN_PTBR,
    PRSESSAO integer,
    PRTABLE varchar(32) collate WIN_PTBR,
    PRTABLEITEM varchar(32) collate WIN_PTBR,
    PRTABLERAT varchar(32) collate WIN_PTBR)
as
begin
end^

CREATE OR ALTER PROCEDURE SP_INSERE_COMPLEMENTO_HIST (
    PRCODPLANOONLINE INTEGER,
    PRSESSAO INTEGER,
    PRTIPOLAN VARCHAR(5))
AS
BEGIN

END^

create or alter procedure SP_ATUALIZAR_TMP_MOVCCSAI (
    PRSESSAO integer,
    PRREF integer)
as
declare variable WNAOPERMITERATEIOGRUPO boolean;
declare variable WCODEMP integer;
begin
  /* Procedure Text */
  select first 1 BDCODEMP
  from TMP_VEF_EMP_TMOVCCSAI_TEMP
  where BDSESSAO = :PRSESSAO and
        BDCODEMP is not null
  into :WCODEMP;

  if ((:WCODEMP is null) or (:WCODEMP = 0)) then
    exit;

  /* Plano de centro de custo não existente na base ou inconsistente */
  insert into VEF_INCON_TMOVSAI (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMCC, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
  select S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDORDEMCC, S.BDSESSAO, 199 BDCODINCONSISTENCIA, 23 BDTIPOINCON
  from (select CC.BDCODEMP, CC.BDCHAVE, CC.BDORDEM, CC.BDORDEMCC, CC.BDSESSAO, CC.BDCODCENTRO
        from TMP_VEF_EMP_TMOVCCSAI_TEMP CC
        where CC.BDSESSAO = :PRSESSAO) S
  where S.BDCODCENTRO = 0 or (S.BDCODCENTRO is null);

  /* Centro de custo não existente na base ou inconsistente */
  insert into VEF_INCON_TMOVSAI (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMCC, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
  select S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDORDEMCC, S.BDSESSAO, 200 BDCODINCONSISTENCIA, 23 BDTIPOINCON
  from (select CC.BDCODEMP, CC.BDCHAVE, CC.BDORDEM, CC.BDORDEMCC, CC.BDSESSAO, CC.BDCODTPCC
        from TMP_VEF_EMP_TMOVCCSAI_TEMP CC
        where CC.BDSESSAO = :PRSESSAO) S
  where S.BDCODTPCC = 0 or (S.BDCODTPCC is null);

  /* Percentual total dos CC não fecha 100% */
  insert into VEF_INCON_TMOVSAI (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMCC, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
  select S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDORDEMCC, S.BDSESSAO, 201 BDCODINCONSISTENCIA, 23 BDTIPOINCON
  from (select CC.BDCODEMP, CC.BDCHAVE, CC.BDORDEM, max(CC.BDORDEMCC) BDORDEMCC, CC.BDSESSAO,
               sum(CC.BDPERCENTUAL) BDPERCTOTAL
        from TMP_VEF_EMP_TMOVCCSAI_TEMP CC
        where CC.BDSESSAO = :PRSESSAO and
              (CC.BDDEBCRED in (2, 1)) /* CC a crédito */
        group by CC.BDCODEMP, CC.BDCHAVE, CC.BDORDEM, CC.BDSESSAO
        union all
        select CC.BDCODEMP, CC.BDCHAVE, CC.BDORDEM, max(CC.BDORDEMCC) BDORDEMCC, CC.BDSESSAO,
               sum(CC.BDPERCENTUAL) BDPERCTOTAL
        from TMP_VEF_EMP_TMOVCCSAI_TEMP CC
        where CC.BDSESSAO = :PRSESSAO and
              (CC.BDDEBCRED in (2, 0)) /* CC a débito */
        group by CC.BDCODEMP, CC.BDCHAVE, CC.BDORDEM, CC.BDSESSAO) S
  where S.BDPERCTOTAL <> 100;

  select SP.BDNAOPERMITERATEIOGRUPO
  from SP_CONSULTAEMPRESAS_SIS(:PRREF, :WCODEMP, null) SP
  into :WNAOPERMITERATEIOGRUPO;

  if (WNAOPERMITERATEIOGRUPO) then
  begin
    -- CC a débito, empresa não permite lançar nas contas ativo, passivo e PL por este motivo não será integrado
    insert into VEF_INCON_TMOVSAI (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMCC, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
    select S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDORDEMCC, S.BDSESSAO, 202 BDCODINCONSISTENCIA, 23 BDTIPOINCON
    from (select CC.BDCODEMP, CC.BDCHAVE, CC.BDORDEM, CC.BDORDEMCC, CC.BDSESSAO, CC.BDDEBCRED
          from TMP_VEF_EMP_TMOVCCSAI_TEMP CC
          where CC.BDSESSAO = :PRSESSAO) S
    where S.BDDEBCRED <> 1; -- 1 = Crédito
  end
end^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_TMOVSAIITENS (
    PRCODPLANOONLINE INTEGER,
    PRSESSAO INTEGER,
    PRCODPLANOINCON INTEGER,
    PRUFEMP VARCHAR(2),
    PRVALIDARCSTMOVPRO VARCHAR(5),
    PRSESSAOPRO integer,
    PRREF integer)
AS
declare variable WSEGREGACAO DM_BOOLEAN;
DECLARE VARIABLE WIMPVLRCONTABDIFIPI VARCHAR(5);
DECLARE VARIABLE WIMPVLRCONTABDIF VARCHAR(5);
BEGIN
  SELECT Coalesce(rdb$get_context('USER_SESSION', 'W_SEGREGACAO_FISCAL'),'FALSE') FROM rdb$database INTO WSEGREGACAO;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAIITENS','1');
  /*Se a empresa não tiver plano de inconsistencia, deve buscar o plano que está setado como default*/
  IF ((:PRCODPLANOINCON = 0) OR (:PRCODPLANOINCON IS NULL)) THEN
    SELECT A.BDSAIIMPICMSDIF, A.BDSAIIMPIPIDIF FROM VEF_BASE_TACOESINCONS A WHERE UPPER(A.BDPLANODEFAULT) = 'TRUE' INTO :wIMPVLRCONTABDIF, :wIMPVLRCONTABDIFIPI;
  ELSE
    SELECT A.BDSAIIMPICMSDIF, A.BDSAIIMPIPIDIF FROM VEF_BASE_TACOESINCONS A WHERE A.BDCODPLANOINCONS = :PRCODPLANOINCON INTO :wIMPVLRCONTABDIF, :wIMPVLRCONTABDIFIPI;

  /*Se o lançamento for inconsistente, torna o item inconsistente
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, bdordempro)
  SELECT IT.BDCODEMP, IT.BDCHAVE, NULL, IT.BDSESSAO, 26 BDCODINCONSISTENCIA, NULL
  FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP IT
  JOIN VEF_INCON_TMOVSAI INCO ON(INCO.BDSESSAO = IT.BDSESSAO AND INCO.BDCODEMP = IT.BDCODEMP AND INCO.BDCHAVE = IT.BDCHAVE AND INCO.BDORDEM IS NULL AND INCO.BDORDEMPRO IS NULL)
  WHERE IT.BDSESSAO = :PRSESSAO;*/

  /*Inconsistencia do valor de ipi diferente do valor contábil*/
  IF ((UPPER(:wIMPVLRCONTABDIFIPI) = 'FALSE') OR (:wIMPVLRCONTABDIFIPI IS NULL) and (UPPER(:WSEGREGACAO) <> 'TRUE')) THEN
    BEGIN
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, BDTIPOINCON)
      SELECT mov.BDCODEMP, mov.BDCHAVE, mov.BDORDEM, mov.BDSESSAO, 25 BDCODINCONSISTENCIA, 2 BDTIPOINCON
      FROM (
            SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDVLRCONTAB,
                   (COALESCE(I.BDBASEIPI, 0) + COALESCE(I.BDVLRIPI, 0) + COALESCE(I.BDISENTASIPI, 0) + COALESCE(I.BDOUTRASIPI, 0)) BDTOTALIPI
            FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
            LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP M ON (M.BDCODEMP = I.BDCODEMP AND M.BDCHAVE = I.BDCHAVE AND M.BDSESSAO = I.BDSESSAO)
            WHERE I.BDSESSAO = :PRSESSAO and (NOT M.BDCODSITNF IN (6,7))
           ) mov
      WHERE MOV.BDTOTALIPI > 0
      AND MOV.BDTOTALIPI <> mov.BDVLRCONTAB;
    END

  /*Inconsistencia do valor de icms diferente do valor contábil*/
  IF ((UPPER(:wIMPVLRCONTABDIF) = 'FALSE') OR (:wIMPVLRCONTABDIF IS NULL) and (UPPER(:WSEGREGACAO) <> 'TRUE')) THEN
    BEGIN
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, BDTIPOINCON)
      SELECT mov.BDCODEMP, mov.BDCHAVE, mov.BDORDEM, mov.BDSESSAO, 24 BDCODINCONSISTENCIA, 2 BDTIPOINCON
  FROM (
            SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDVLRCONTAB,
                   (COALESCE(I.BDBASEICMS, 0) + COALESCE(I.BDISENTASICMS, 0) + COALESCE(I.BDOUTRASICMS, 0) + COALESCE(I.BDOUTROSIMP, 0) +
                    COALESCE(I.BDFCPRETIDO, 0) + --  Alt.: #163545 - Incluido o "FCP ST"...
                    IIF(UPPER(CFOP.BDNAOSOMARSTISEOUT) = 'TRUE', COALESCE(I.BDVLRST, 0), 0)) BDTOTAL
            FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
            LEFT OUTER JOIN VEF_BASE_TNATOP CFOP ON(CFOP.BDCODNAT = I.BDCODNAT)   
            LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP M ON (M.BDCODEMP = I.BDCODEMP AND M.BDCHAVE = I.BDCHAVE AND M.BDSESSAO = I.BDSESSAO)
            WHERE I.BDSESSAO = :PRSESSAO and (NOT M.BDCODSITNF IN (6,7))
           ) mov
      WHERE MOV.BDTOTAL > 0
      AND MOV.BDTOTAL <> mov.BDVLRCONTAB;
    END

  /*Joga como inconsistente os lançamentos com cfop não cadastrada*/
  if (UPPER(:WSEGREGACAO) <> 'TRUE') then
    begin
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDSESSAO, 23 BDCODINCONSISTENCIA, 2 BDTIPOINCON
                  FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
                  LEFT OUTER JOIN VEF_BASE_TNATOP N ON(N.BDCODNAT = I.BDCODNAT)
  WHERE I.BDSESSAO = :PRSESSAO
  AND N.BDCODNAT IS NULL;
    end

  /*cfop não pertence ao estado do participante*/
  if (UPPER(:WSEGREGACAO) <> 'TRUE') then
    begin
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT CFOP.BDCODEMP, CFOP.BDCHAVE, CFOP.BDORDEM, CFOP.BDSESSAO, CFOP.BDINCONSISTENTE, 2 BDTIPOINCON
  FROM (
        SELECT MOV.BDSESSAO, MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDORDEM, MOV.BDSIGLAUFTER, MOV.BDSIGLAUFEMP, MOV.BDCODNAT, MOV.BDMODELO,
               MOV.BDCLASSIFICACAO,
               CASE WHEN MOV.BDMODELO IN (59,65) THEN NULL -- Sol. 21385 notas de modelo 59 e 65 não precisam da validação
                    WHEN MOV.BDSIGLAUFTER = MOV.BDSIGLAUFEMP THEN IIF(MOV.BDDIG = '5', NULL, 38)
                    WHEN MOV.BDSIGLAUFTER = 'EX' THEN IIF(SUBSTRING(MOV.BDCODNAT FROM 1 FOR 1) = '7', NULL, 38)
                    ELSE
                      IIF(SUBSTRING(MOV.BDCODNAT FROM 1 FOR 1) = '6', NULL,38)
               END BDINCONSISTENTE
        FROM (
              SELECT I.BDSESSAO, L.BDMODELO, I.BDCODEMP, I.BDCHAVE, I.BDORDEM,
                     I.BDCODNAT, I.BDSIGLAUFTER, :PRUFEMP BDSIGLAUFEMP, NULL BDINCONSISTENTE, NAT.BDCLASSIFICACAO, I.BDPODECFOP,
                   SUBSTRING(I.BDCODNAT FROM 1 FOR 1) BDDIG
                 FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
              LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP L ON (L.BDSESSAO = I.BDSESSAO AND L.BDCODEMP = I.BDCODEMP AND L.BDCHAVE = I.BDCHAVE)
              LEFT OUTER JOIN VEF_INCON_TMOVSAI INCO ON(INCO.BDSESSAO = I.BDSESSAO AND INCO.BDCODEMP = I.BDCODEMP AND INCO.BDCHAVE = I.BDCHAVE AND INCO.BDORDEM = I.BDORDEM AND INCO.BDCODINCONSISTENCIA = 23)              
              LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT)
              WHERE I.BDSESSAO = :PRSESSAO
                AND INCO.BDCODINCONSISTENCIA IS NULL
                AND Coalesce(I.BDPODECFOP,0) <> 1
             ) MOV
       ) CFOP
  WHERE CFOP.BDINCONSISTENTE IS NOT NULL
  AND NOT ((CFOP.BDMODELO IN(7, 8, 9, 10, 11, 12, 13, 57, 67, 63)) AND ((POSITION('.350', CFOP.BDCLASSIFICACAO) > 0) OR (POSITION('.200.206', CFOP.BDCLASSIFICACAO) > 0) OR (POSITION('.900.932', CFOP.BDCLASSIFICACAO) > 0)));
    end

/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAIITENS','2');
  /*Monta o complemento de histórico dos lançamentos*/
  EXECUTE PROCEDURE SP_INSERE_COMPLEMENTO_HIST (:prCODPLANOONLINE, :prSESSAO, 'SAI');
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAIITENS','3');


  /*Inconsistencia do lançamento de produto*/
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_MOVPROSAI_TEMP(:PRSESSAO, :PRCODPLANOINCON, :PRVALIDARCSTMOVPRO, :PRSESSAOPRO);
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAIITENS','4');
  /* Inconsistência do lançamento de CC */
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_MOVCCSAI(:PRSESSAO, :PRREF);
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_MOVCC','5');
END^


CREATE OR ALTER procedure SP_ATUALIZAR_CAMPO_CHAVE_TEMP (
    PRSESSAO integer,
    PRTABLE varchar(50),
    PRKEYFIELD varchar(255) = 'BDCHAVE')
as
declare variable WPOS integer;
declare variable WKEYS integer;
declare variable WSTR varchar(255);
declare variable WFIELD varchar(64);
declare variable WSQL varchar(1000);
declare variable WTABLE varchar(100);
BEGIN
  wKeys =  IIF(POSITION(',', :PRKEYFIELD) > 0, 1, 0);

  IF (:wKeys = 1) THEN
    PRKEYFIELD = :PRKEYFIELD||',';

  FOR SELECT RDB$RELATION_NAME BDTABLE
      FROM RDB$RELATION_FIELDS
      WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
      AND RDB$RELATION_NAME <> 'TMP_VEF_EMP_TMOVSAI_TEMP'
      AND RDB$RELATION_NAME <> 'TMP_TTERCEIRO_TEMP'
      AND RDB$RELATION_NAME <> 'TMP_TCADPRO_TEMP'
      AND RDB$RELATION_NAME <> 'TMP_TUNIDADEMEDIDA_TEMP'
      AND RDB$RELATION_NAME <> 'TMP_VEF_BASE_TEQUIPASAT_TEMP'     
      AND RDB$RELATION_NAME <> 'TMP_TCADPRO_INSUMOS_TEMP'
      AND RDB$RELATION_NAME <> 'TMP_VEF_EMP_TAJUICMSE115_TEMP' -- ALT.: 11938 - Não pode incluir a tabela de lançamento de ajuste do E115
      AND RDB$RELATION_NAME <> 'TMP_VEF_BASE_TCADMAQMRC_TEMP'
      AND RDB$RELATION_NAME <> 'TMP_VEF_BASE_TOBSERVACAO_TEMP'
      AND RDB$RELATION_NAME <> 'TMP_VEF_BASE_TCADINFCOM_TEMP'   
      AND RDB$RELATION_NAME <> ''||:PRTABLE||''
      AND RDB$FIELD_NAME = 'BDEDITCHAVE'
      GROUP BY RDB$RELATION_NAME
      INTO :wTable
  DO
    BEGIN
      IF (:wKeys = 1) THEN
        BEGIN
          wSql =          'SELECT FIRST 1 ''BDFIELD'' ';
          wSql = :wSql || 'FROM ( ';
          wSql = :wSql ||       'SELECT LIST(TRIM(RDB$FIELD_NAME)) BDFIELDS ';
          wSql = :wSql ||       'FROM RDB$RELATION_FIELDS ';
          wSql = :wSql ||       'WHERE RDB$RELATION_NAME = '''||:wTable||'''';
          wSql = :wSql ||      ') T ';
          FOR SELECT TRIM(BDDADO), BDPOS FROM SP_SPLIT(:PRKEYFIELD, ',') INTO :wStr, :wPos DO
            BEGIN
              wSql = :wSql || IIF(:wPos = 0, 'WHERE', 'AND');
              wSql = :wSql || ' POSITION('','||:wStr||','', T.BDFIELDS) > 0 ';
            END
          EXECUTE STATEMENT :wSQL INTO :wField;
        END
      ELSE
        SELECT TRIM(RDB$FIELD_NAME) FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME = :wTable AND RDB$FIELD_NAME = :PRKEYFIELD INTO :wField;

      IF (COALESCE(:wField, '') <> '') THEN
        BEGIN
      wSql =         'UPDATE '||:wTable||' T ';
      wSql = wSql || 'SET T.BDEDITCHAVE = ( ';
      wSql = wSql || '                     SELECT BDEDITCHAVE ';
      wSql = wSql || '                     FROM '||:PRTABLE||' S ';
      wSql = wSql || '                     WHERE S.BDSESSAO = T.BDSESSAO ';
      wSql = wSql || '                     AND S.BDCODEMP = T.BDCODEMP ';

          IF (:wKeys = 1) THEN
            BEGIN
              FOR SELECT TRIM(BDDADO) FROM SP_SPLIT(:PRKEYFIELD, ',') INTO :wStr DO
                wSql = wSql ||                'AND S.'||:wStr||' = T.'||:wStr||' ';
            END
          ELSE
            wSql = wSql ||                    'AND S.'||:PRKEYFIELD||' = T.'||:PRKEYFIELD;

      wSql = wSql || '                    ) ';
      wSql = wSql || 'WHERE T.BDSESSAO = '||:PRSESSAO;
      EXECUTE STATEMENT wSql;
    END

      wField = NULL;
    END
END^

COMMENT ON PARAMETER SP_ATUALIZAR_CAMPO_CHAVE_TEMP.PRTABLE IS 'Nome da tabela principal'^
COMMENT ON PARAMETER SP_ATUALIZAR_CAMPO_CHAVE_TEMP.PRKEYFIELD IS 'Para passar mais de um campo, utilizar o separador ,'^

create or alter procedure SP_INSERT_INCONSISTENCIAS_CONTA (
    PRSESSAO integer,
    PRCODPLANOONLINE integer,
    PRENQFED integer,
    PRCODCONFIRLP integer,
    PRTIPOLAN varchar(5),
    PRFORMATRIB integer = 0)
as
BEGIN

END^

create or alter procedure SP_PRE_VALIDA_CONTA_ONLINE_TEMP (
    PRCODPLANOONLINE integer,
    PRSESSAO integer,
    PRENQFED integer,
    PRCODCONFIRLP integer,
    PRTIPOLAN varchar(4))
as
declare variable WVLRMVAIVA numeric(15,2);
declare variable WVLRICMSFCPOP numeric(15,2);
declare variable WVLRICMSCONC numeric(15,2);
declare variable WSQL varchar(10000);
declare variable WVLRCOFINS numeric(15,2);
declare variable WVLRIPI numeric(15,2);
declare variable WVLRPIS numeric(15,2);
declare variable WVLRICMS numeric(15,2);
declare variable WVLRCONTAB numeric(15,2);
declare variable WVLRST numeric(15,2);
declare variable WVLRICMSFCPST numeric(15,2);
declare variable WCODNAT integer;
declare variable WVLRDESCONTO numeric(15,2);
declare variable WFIELDREF varchar(200);
declare variable WFIELDDATA varchar(32);
declare variable WTABLE varchar(31);
declare variable WTABLEITEM varchar(31);
declare variable WTABLEAUXDATA varchar(32);
declare variable WTIPOCONTA integer;
declare variable WREFERENCIA integer;
declare variable WTIPOINTDESCONTO integer;
BEGIN
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_PRE_VALIDA_CONTA_ONLINE_TEMP','1');
  -- Alt.: #147969 - Ajuste para jogar o conteúdo da View em uma tabela temporária e evitar lentidão na contabilização...
  --DELETE FROM TCONF_CONTAS_TODAS_REF_TMP;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_PRE_VALIDA_CONTA_ONLINE_TEMP','2');

--  INSERT INTO TCONF_CONTAS_TODAS_REF_TMP (bdCODPLANOONLINE, bdCHAVE, bdREFCTA, bdCODPLAPADRAO, bdCODTPHI, bdCONTADEBPROV,
--                                          bdCONTACREDPROV, bdCODHISTPROV, bdCODCOMPHISTPROV, bdCONTADEBPGTO, bdCONTACREDPGTO,
--                                          bdCODHISTPGTO, bdCODCOMPHISTPGTO, bdCOPYTITULO, bdCHAVEVINC)
--  SELECT onl.bdCODPLANOONLINE, onl.bdCHAVE, ref_pai.bdREFCTA, ref.bdCODPLAPADRAO, ref.bdCODTPHI, ref.bdCONTADEBPROV,
--         ref.bdCONTACREDPROV, ref.bdCODHISTPROV, ref.bdCODCOMPHISTPROV, ref.bdCONTADEBPGTO, ref.bdCONTACREDPGTO,
--         ref.bdCODHISTPGTO, ref.bdCODCOMPHISTPGTO, ref.bdCOPYTITULO, onl.bdCHAVEVINC
--  FROM TCONF_CONTAS_ONLINE onl
--  LEFT OUTER JOIN TCONF_CONTAS_ONLINE_REF ref_pai ON (onl.bdCODPLANOONLINE = ref_pai.bdCODPLANOONLINE AND ref_pai.bdCHAVE = COALESCE(onl.bdCHAVEVINC, onl.bdCHAVE))
--  LEFT OUTER JOIN TCONF_CONTAS_ONLINE_REF ref ON (onl.bdCODPLANOONLINE = ref.bdCODPLANOONLINE AND onl.bdCHAVE = ref.bdCHAVE AND ref_pai.bdREFCTA = ref.bdREFCTA)
--  WHERE onl.bdCODPLANOONLINE = :prCODPLANOONLINE
--    AND ONL.BDCLASSIFICACAO LIKE '03.%'; -- Apenas contas do fiscal
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_PRE_VALIDA_CONTA_ONLINE_TEMP','3');

  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTable     = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItem = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      WFIELDDATA = 'BDDATAENTRADAENT';
    END
  ELSE
  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTable     = 'TMP_VEF_EMP_TMOVSAI_TEMP';
      wTableItem = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
      WFIELDDATA = 'BDDATAEMISSAO';
    END    
  ELSE  
  IF (:PRTIPOLAN = 'REDZ') THEN
    BEGIN
      wTable     = 'TMP_VEF_EMP_TREDZVARCFOP_TEMP';
      wTableItem = 'TMP_VEF_EMP_TREDZVARCFOP_TEMP';
      WFIELDDATA = 'BDDATAREDZ';
      WTABLEAUXDATA = 'TMP_VEF_EMP_TREDZ_TEMP';
    END
  ELSE
  IF(POSITION('SER', :PRTIPOLAN) > 0) THEN
    BEGIN
      wTable     = 'TMP_VEF_EMP_TMOVSER_TEMP';
      wTableItem = 'TMP_VEF_EMP_TMOVSERITENS_TEMP';
      WFIELDDATA = 'BDDATAEMISSAO';
    END

  /*
    0 - Desconto nota a nota
    1 - Desconto por CFOP
  */
  SELECT COALESCE(C.BDTIPOINTDESCONTO, 0)
  FROM TPLANO_CONF_ONLINE C
  WHERE C.BDCODPLANOONLINE = :PRCODPLANOONLINE
  INTO :wTipoIntDesconto;

  if (wtableauxdata IS NULL) then
    wtableauxdata = wtable;

  WFIELDDATA = 'data.'||WFIELDDATA;
  WFIELDREF = 'EXTRACT(YEAR FROM '||WFIELDDATA||')*100+EXTRACT(MONTH FROM '||WFIELDDATA||')';

  /*Remover esse delete, a tabela é temporária*/
  DELETE FROM TMP_TCFOP_TMOV WHERE BDSESSAO = :PRSESSAO;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_PRE_VALIDA_CONTA_ONLINE_TEMP','4');

  /*Agrupa os lan?amentos por CFOP e condi??o de pagamento(Vista, prazo e outras) e grava na tabela tempor?ria*/
  wSQL = 'SELECT CASE ';
  wSQL = wSQL ||  ' WHEN COALESCE(M.BDCONDPGTO, 0) = 0 THEN 50 ';
  wSQL = wSQL ||  '                WHEN COALESCE(M.BDCONDPGTO, 0) = 1 THEN 51 ';
  wSQL = wSQL ||  '                WHEN COALESCE(M.BDCONDPGTO, 0) = 2 THEN 406 ';
  wSQL = wSQL ||  '              END BDCONDPGTO, I.BDCODNAT, ';
  wSQL = wSQL ||  '              SUM(COALESCE(I.BDVLRCONTAB, 0)) BDVLRCONTAB, ';

  IF (POSITION('SER', :PRTIPOLAN) > 0) THEN
    wSQL = wSQL || ' 0 BDVLRICMS, ';
  ELSE
    wSQL = wSQL || ' SUM(COALESCE(I.BDVLRICMS, 0)) BDVLRICMS, ';

  IF (:PRTIPOLAN = 'REDZ') THEN
    BEGIN
      wSQL = wSQL ||  '              0 BDVLRIPI, ';
      wSQL = wSQL ||  '              0 BDDESCONTO, ';
    END
  ELSE
    BEGIN
      IF (POSITION('SER', :PRTIPOLAN) > 0) THEN
        wSQL = wSQL ||  '              0 BDVLRIPI, ';
      ELSE
        wSQL = wSQL ||  '              SUM(COALESCE(I.BDVLRIPI, 0)) BDVLRIPI, ';

      wSQL = wSQL ||  '              SUM(COALESCE(I.BDDESCONTO, 0)) BDDESCONTO, ';
    END

  wSQL = wSQL ||  '              SUM(COALESCE(I.BDVLRPIS, 0)) BDVLRPIS, ';
  wSQL = wSQL ||  '              SUM(COALESCE(I.BDVLRCOFINS, 0)) BDVLRCOFINS, ';

  IF (POSITION('SER', :PRTIPOLAN) > 0) THEN
    wSQL = wSQL ||  '              0 BDVLRST, ';
  ELSE
    wSQL = wSQL ||  '              SUM(COALESCE(I.BDVLRST, 0)) BDVLRST, ';

  IF ((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SAI')) THEN
    BEGIN
      wSQL = wSQL ||  '              SUM(COALESCE(i.bdFCPRETIDO,0)) AS bdVLRICMSFCPST, ';
      wSQL = wSQL ||  '              SUM(COALESCE(i.BDVLRICMSCONC,0)) AS BDVLRICMSCONC, ';
      wSQL = wSQL ||  '              SUM(COALESCE(i.BDVLRFCP,0)) AS BDVLRFCP, ';
      
        IF (:PRTIPOLAN = 'ENT') THEN
            wSQL = wSQL ||  ' SUM(COALESCE(i.BDMVAIVA,0)) AS BDMVAIVA, ';
        ELSE
            wSQL = wSQL ||  ' 0 AS BDMVAIVA, ';
    
     END
  ELSE
    BEGIN
      wSQL = wSQL ||  '              0 AS bdVLRICMSFCPST, ';
      wSQL = wSQL ||  '              0 AS BDVLRICMSCONC, ';
      wSQL = wSQL ||  '              0 AS BDVLRFCP, ';
      wSQL = wSQL ||  '              0 AS BDMVAIVA, ';      
    END

  wSQL = wSQL ||  '             '||:wfieldref||' as BDREFERENCIA';
  wSQL = wSQL ||  '       FROM '||:wTable||' M ';
  wSQL = wSQL ||  '       LEFT OUTER JOIN '||:wTableItem||' I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE AND I.BDSESSAO = M.BDSESSAO) ';
  wSQL = wSQL ||  '     LEFT OUTER JOIN '||:wtableauxdata||' data ON(data.BDCODEMP = M.BDCODEMP AND data.BDCHAVE = M.BDCHAVE AND data.BDSESSAO = M.BDSESSAO)';
  wSQL = wSQL ||  '       WHERE M.BDSESSAO = '||:PRSESSAO;

  IF (POSITION('SER', :PRTIPOLAN) > 0) THEN
    wSQL = wSQL || '      AND M.BDTIPLAN = '||IIF(:PRTIPOLAN = 'SERE', '0', '1');

  wSQL = wSQL ||  '       GROUP BY M.BDCONDPGTO, I.BDCODNAT, '||:wfieldref;

  FOR EXECUTE STATEMENT wSQL INTO :wTipoConta, :wCodNat, :wVlrContab, :wVlrIcms, :wVlrIpi, :wVlrDesconto, :wVlrPis, :wVlrCofins, :wVlrSt, :wVLRICMSFCPST, :wVlrIcmsConc, :WVLRICMSFCPOP, :WVLRMVAIVA, :WREFERENCIA
  DO
    BEGIN
      IF ((:wVlrContab > 0) or (:wVlrDesconto > 0)) THEN
        INSERT INTO TMP_TCFOP_TMOV(bdsessao, bdcodnat, bdcondpgto, bdcoditemonline, BDREFERENCIA) VALUES(:PRSESSAO, :wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 111 /*A vista*/
                                                                                                                                  WHEN :wTipoConta = 51  THEN 117 /*Prazo*/
                                                                                                                                  WHEN :wTipoConta = 406 THEN 170 /*Outras*/
                                                                                                                             END, :WREFERENCIA);

      IF (:wVlrIcms > 0) THEN
        BEGIN
        INSERT INTO TMP_TCFOP_TMOV(bdsessao, bdcodnat, bdcondpgto, bdcoditemonline, BDREFERENCIA) VALUES(:PRSESSAO, :wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 112
                                                                                                                                  WHEN :wTipoConta = 51  THEN 118
                                                                                                                                  WHEN :wTipoConta = 406 THEN 171
                                                                                                                             END, :WREFERENCIA);
        INSERT INTO TMP_TCFOP_TMOV(bdsessao, bdcodnat, bdcondpgto, bdcoditemonline, BDREFERENCIA) VALUES(:PRSESSAO, :wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 290
                                                                                                                                  WHEN :wTipoConta = 51  THEN 291
                                                                                                                                  WHEN :wTipoConta = 406 THEN 292
                                                                                                                             END, :WREFERENCIA);
        END

      IF (:wVlrSt > 0) THEN
        INSERT INTO TMP_TCFOP_TMOV(bdsessao, bdcodnat, bdcondpgto, bdcoditemonline, BDREFERENCIA) VALUES(:PRSESSAO, :wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 113
                                                                                                                                  WHEN :wTipoConta = 51  THEN 119
                                                                                                                                  WHEN :wTipoConta = 406 THEN 172
                                                                                                                             END, :WREFERENCIA);

      IF (:wVlrIpi > 0) THEN
        INSERT INTO TMP_TCFOP_TMOV(bdsessao, bdcodnat, bdcondpgto, bdcoditemonline, BDREFERENCIA) VALUES(:PRSESSAO, :wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 114
                                                                                                                                  WHEN :wTipoConta = 51  THEN 120
                                                                                                                                  WHEN :wTipoConta = 406 THEN 173
                                                                                                                             END, :WREFERENCIA);

      IF (:wVlrPis > 0) THEN
        INSERT INTO TMP_TCFOP_TMOV(bdsessao, bdcodnat, bdcondpgto, bdcoditemonline, BDREFERENCIA) VALUES(:PRSESSAO, :wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 115
                                                                                                                                  WHEN :wTipoConta = 51  THEN 121
                                                                                                                                  WHEN :wTipoConta = 406 THEN 174
                                                                                                                             END, :WREFERENCIA);

      IF (:wVlrCofins > 0) THEN
        INSERT INTO TMP_TCFOP_TMOV(bdsessao, bdcodnat, bdcondpgto, bdcoditemonline, BDREFERENCIA) VALUES(:PRSESSAO, :wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 116
                                                                                                                                  WHEN :wTipoConta = 51  THEN 122
                                                                                                                                  WHEN :wTipoConta = 406 THEN 175
                                                                                                                             END, :WREFERENCIA);

      /*Desconto por CFOP*/
      IF ((:wTipoIntDesconto = 1) AND (:wVlrDesconto > 0)) THEN
         INSERT INTO TMP_TCFOP_TMOV(bdsessao, bdcodnat, bdcondpgto, bdcoditemonline, BDREFERENCIA) VALUES(:PRSESSAO, :wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 243
                                                                                                                                   WHEN :wTipoConta = 51  THEN 244
                                                                                                                                   WHEN :wTipoConta = 406 THEN 245
                                                                                                                              END, :WREFERENCIA);
      /* ICMS FCP ST */
      IF (:wVLRICMSFCPST > 0) THEN
         INSERT INTO TMP_TCFOP_TMOV(bdSESSAO, bdCODNAT, bdCONDPGTO, bdCODITEMONLINE, BDREFERENCIA) VALUES(:prSESSAO, :wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 286 -- A vista
                                                                                                                                   WHEN :wTipoConta = 51  THEN 287 -- Prazo
                                                                                                                                   WHEN :wTipoConta = 406 THEN 288 -- Outra
                                                                                                                              END, :WREFERENCIA);
      /* ICMS Concomitante */
      IF (:wVlrIcmsConc > 0) THEN
         INSERT INTO TMP_TCFOP_TMOV(bdSESSAO, bdCODNAT, bdCONDPGTO, bdCODITEMONLINE, BDREFERENCIA) VALUES(:prSESSAO, :wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 640 -- A vista
                                                                                                                                   WHEN :wTipoConta = 51  THEN 641 -- Prazo
                                                                                                                                   WHEN :wTipoConta = 406 THEN 642 -- Outra
                                                                                                                              END, :WREFERENCIA);
      /* ICMS FCP OP */                                                                                                                           
      IF (:WVLRICMSFCPOP > 0) THEN
         INSERT INTO TMP_TCFOP_TMOV(bdSESSAO, bdCODNAT, bdCONDPGTO, bdCODITEMONLINE, BDREFERENCIA) VALUES(:prSESSAO, :wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 663 -- A vista
                                                                                                                                   WHEN :wTipoConta = 51  THEN 664 -- Prazo
                                                                                                                                   WHEN :wTipoConta = 406 THEN 665 -- Outra
                                                                                                                              END, :WREFERENCIA);
      /* MVA / IVA */
      IF (:WVLRMVAIVA > 0) THEN
         INSERT INTO TMP_TCFOP_TMOV(bdSESSAO, bdCODNAT, bdCONDPGTO, bdCODITEMONLINE, BDREFERENCIA) VALUES(:prSESSAO, :wCODNAT, :wTipoConta, CASE WHEN :wTipoConta = 50  THEN 666 -- A vista
                                                                                                                                   WHEN :wTipoConta = 51  THEN 667 -- Prazo
                                                                                                                                   WHEN :wTipoConta = 406 THEN 668 -- Outra
                                                                                                                              END, :WREFERENCIA);


      wVlrContab = 0;
      wVlrCofins = 0;
      wVlrIcms   = 0;
      wVlrIpi    = 0;
      wVlrPis    = 0;
      wVlrSt     = 0;
      wVlrDesconto = 0;
        WVLRMVAIVA = 0;
    END

/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_PRE_VALIDA_CONTA_ONLINE_TEMP','5');
END
^

create or alter procedure SP_VALIDA_CONTA_ONLINE_TEMP (
    PRCODPLANOONLINE integer,
    PRSESSAO integer,
    PRENQFED integer,
    PRCODCONFIRLP integer,
    PRTIPOLAN varchar(4),
    PRFORMATRIB integer = 0)
as
declare variable WCODITEMINSS25 integer;
declare variable WCODITEMINSS20 integer;
declare variable WCODITEMINSS15 integer;
declare variable WCLASSIFIBUSCA varchar(100); /* PRTIPOLAN */
declare variable WCHAVECONF integer;
declare variable WACHOUCONTA varchar(5);
declare variable WCONTADEBPROV integer;
declare variable WCONTACREDPROV integer;
declare variable WTIPOCONTA integer;
declare variable WCHAVE integer;
declare variable WCLASS varchar(100);
declare variable WCODITEMONLINE integer;
declare variable WCOMPLEMENTO blob sub_type 1 segment size 1000;
declare variable WCODHIST integer;
declare variable WCODTPHI integer;
declare variable WTABLE varchar(31);
declare variable WTABLEITEM varchar(31);
declare variable WTABLERET varchar(31);
declare variable WTABLEC100 varchar(31);
declare variable WTABLED100 varchar(31);
declare variable WTABLEINSS varchar(31);
declare variable WTABLERAT varchar(31);
declare variable WSQL varchar(10000);
declare variable WTIPOINTDESCONTO integer;
declare variable WTABLEFUNRURAL varchar(32);
declare variable WCODITEMPIS integer;
declare variable WCODITEMCOF integer;
declare variable WCODITEMCS integer;
declare variable WCODITEMIR integer;
declare variable WCODITEMINSS integer;
declare variable WCODITEMISS integer;
declare variable WCODITEMFUNRURAL integer;
declare variable WCODITEMROYALTIES integer;
declare variable WTABLEDIFALIQ varchar(32);
declare variable WTABLEDIFALIQPR varchar(32);
declare variable WFIELDDATA varchar(32);
declare variable WFIELDREF varchar(200);
declare variable WTABLEAUXDATA varchar(32);
declare variable WLEFT_TABLEDATA varchar(200);
declare variable WREFERENCIA integer;
declare variable WSQLCONTAS varchar(1000);
begin
  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', '1');
  PRTIPOLAN = upper(:PRTIPOLAN);
  WTABLE = '';
  WTABLEITEM = '';
  WTABLERET = '';
  WTABLEFUNRURAL = '';
  WTABLEINSS     = '';
  WCODITEMROYALTIES = 0;
  WSQLCONTAS = 'SELECT onl.bdCODPLANOONLINE, onl.bdCHAVE, ref_pai.bdREFCTA, ref.bdCODPLAPADRAO, ref.bdCODTPHI, ref.bdCONTADEBPROV, ';
  WSQLCONTAS = WSQLCONTAS ||'       ref.bdCONTACREDPROV, ref.bdCODHISTPROV, ref.bdCODCOMPHISTPROV, ref.bdCONTADEBPGTO, ref.bdCONTACREDPGTO, ';
  WSQLCONTAS = WSQLCONTAS ||'       ref.bdCODHISTPGTO, ref.bdCODCOMPHISTPGTO, ref.bdCOPYTITULO, onl.bdCHAVEVINC ';
  WSQLCONTAS = WSQLCONTAS ||'FROM TCONF_CONTAS_ONLINE onl ';
  WSQLCONTAS = WSQLCONTAS ||'LEFT OUTER JOIN TCONF_CONTAS_ONLINE_REF ref_pai ON (onl.bdCODPLANOONLINE = ref_pai.bdCODPLANOONLINE AND ref_pai.bdCHAVE = COALESCE(onl.bdCHAVEVINC, onl.bdCHAVE)) ';
  WSQLCONTAS = WSQLCONTAS ||'LEFT OUTER JOIN TCONF_CONTAS_ONLINE_REF ref ON (onl.bdCODPLANOONLINE = ref.bdCODPLANOONLINE AND onl.bdCHAVE = ref.bdCHAVE AND ref_pai.bdREFCTA = ref.bdREFCTA) ';
  WSQLCONTAS = WSQLCONTAS ||'WHERE onl.bdCODPLANOONLINE = '||:prCODPLANOONLINE;
  WSQLCONTAS = WSQLCONTAS ||'  AND ONL.BDCLASSIFICACAO LIKE ''03.%'' ';
  /*
    0 - Desconto nota a nota
    1 - Desconto por CFOP
  */
  select coalesce(C.BDTIPOINTDESCONTO, 0)
  from TPLANO_CONF_ONLINE C
  where C.BDCODPLANOONLINE = :PRCODPLANOONLINE
  into :WTIPOINTDESCONTO;

  WTABLERAT = '';
  if (:PRTIPOLAN = 'ENT') then
  begin
    WTABLE = 'TMP_VEF_EMP_TMOVENT_TEMP';
    WTABLEITEM = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
    WTABLERET = 'TMP_VEF_EMP_TMOVENTRET_TEMP';
    WTABLEC100 = 'TMP_VEF_EMP_TC100ENT_TEMP';
    WTABLED100 = 'TMP_VEF_EMP_TD100ENT_TEMP';
    WTABLEFUNRURAL = 'TMP_VEF_TMOVENTFUNRURAL_TEMP';
    WTABLEINSS = 'TMP_VEF_EMP_TMOVENTDED_TEMP';
    WCODITEMPIS = 82;
    WCODITEMCOF = 83;
    WCODITEMCS = 84;
    WCODITEMIR = 163;
    WCODITEMINSS = 164;
    WCODITEMISS = 165;
    WCODITEMFUNRURAL = 85;
    WCODITEMROYALTIES = 86;
    WTABLEDIFALIQ = 'TMP_VEF_EMP_TMOVENTDIFALIQ_TEMP';
    WTABLEDIFALIQPR = 'TMP_VEF_EMP_TMOVENTDIFPR_TEMP';
    WCODITEMINSS15 = 313; -- Contabilização INSS aposentadoria especial #123489 #128660 #101172 #100393 #DBS! Mesma regra INSS - Matheus Amaral - 09/03/2020
    WCODITEMINSS20 = 314;
    WCODITEMINSS25 = 315;
      WFIELDDATA = 'BDDATAENTRADAENT';
  end
  else
  if (:PRTIPOLAN = 'SAI') then
  begin
    WTABLE = 'TMP_VEF_EMP_TMOVSAI_TEMP';
    WTABLEITEM = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
    WTABLERET = 'TMP_VEF_EMP_TMOVSAIRET_TEMP';
    WTABLEC100 = 'TMP_VEF_EMP_TC100SAI_TEMP';
    WTABLED100 = 'TMP_VEF_EMP_TD100SAI_TEMP';
    WTABLEFUNRURAL = 'TMP_VEF_TMOVSAIFUNRURAL_TEMP';
    WTABLEINSS = 'TMP_VEF_EMP_TMOVSAIDED_TEMP';
    WCODITEMPIS = 89;
    WCODITEMCOF = 90;
    WCODITEMCS = 91;
    WCODITEMIR = 92;
    WCODITEMINSS = 93;
    WCODITEMISS = 94;
    WCODITEMFUNRURAL = 246;
    WTABLEDIFALIQ = 'TMP_VEF_EMP_TMOVSAIDIFALIQ_TEMP';
    WTABLEDIFALIQPR = 'TMP_VEF_EMP_TMOVSAIDIFPR_TEMP';
    WCODITEMINSS15 = 304; -- Contabilização INSS aposentadoria especial #123489 - Matheus Amaral - 09/03/2020
    WCODITEMINSS20 = 305;
    WCODITEMINSS25 = 306;
      WFIELDDATA = 'BDDATAEMISSAO';
  end
  else
  if (:PRTIPOLAN = 'REDZ') then
  begin
    WTABLE = 'TMP_VEF_EMP_TREDZVARCFOP_TEMP';
    WTABLEITEM = 'TMP_VEF_EMP_TREDZVARCFOP_TEMP';
      WFIELDDATA = 'BDDATAREDZ';
      WTABLEAUXDATA = 'TMP_VEF_EMP_TREDZ_TEMP';
  end
  else
  if (position('SER', :PRTIPOLAN) > 0) then
  begin
    WTABLE = 'TMP_VEF_EMP_TMOVSER_TEMP';
    WTABLEITEM = 'TMP_VEF_EMP_TMOVSERITENS_TEMP';
    WTABLERET = 'TMP_VEF_EMP_TMOVSERRET_TEMP';
    WTABLEINSS = 'TMP_VEF_EMP_TMOVSERDED_TEMP';
    WTABLERAT = 'TMP_VEF_EMP_TMOVRATSER_TEMP';
      WFIELDDATA = 'BDDATAEMISSAO';

    if (:PRTIPOLAN = 'SERE') then
    begin
      WCODITEMPIS = 99;
      WCODITEMCOF = 100;
      WCODITEMCS = 101;
      WCODITEMIR = 97;
      WCODITEMINSS = 98;
      WCODITEMISS = 102;
      WCODITEMINSS15 = 307;
      WCODITEMINSS20 = 308;
      WCODITEMINSS25 = 309;
    end
    else
    begin
      WCODITEMPIS = 107;
      WCODITEMCOF = 108;
      WCODITEMCS = 109;
      WCODITEMIR = 105;
      WCODITEMINSS = 106;
      WCODITEMISS = 110;
      WCODITEMINSS15 = 310;
      WCODITEMINSS20 = 311;
      WCODITEMINSS25 = 312;
    end
  end

  execute procedure SP_PRE_VALIDA_CONTA_ONLINE_TEMP(PRCODPLANOONLINE, PRSESSAO, PRENQFED, PRCODCONFIRLP, PRTIPOLAN);
  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', '2');

  if (WTABLEAUXDATA is null) then
    WTABLEAUXDATA = WTABLE;

  WFIELDDATA = 'data.' || WFIELDDATA;
  WFIELDREF = 'EXTRACT(YEAR FROM ' || WFIELDDATA || ')*100+EXTRACT(MONTH FROM ' || WFIELDDATA || ')';

  WLEFT_TABLEDATA = ' LEFT OUTER JOIN ' || :WTABLEAUXDATA || ' data on(data.BDCODEMP = R.BDCODEMP AND data.BDCHAVE = R.BDCHAVE AND data.BDSESSAO = R.BDSESSAO)';
  if (:WTABLERET <> '') then
  begin
      /*Insere na tabela todas as retenções que vão ser usadas na importação*/
    WSQL = 'INSERT INTO TMP_TCFOP_TMOV(bdsessao, bdcoditemonline, bdcodrec,BDREFERENCIA) ';
    WSQL = WSQL || 'SELECT ' || :PRSESSAO || ' BDSESSAO, ';
    WSQL = WSQL || '       CASE WHEN MOV.BDVLRPIS > 0     THEN ' || WCODITEMPIS;
    WSQL = WSQL || ' WHEN MOV.BDVLRCOFINS  > 0 THEN ' || WCODITEMCOF;
    WSQL = WSQL || ' WHEN MOV.BDVLRCSOCIAL > 0 THEN ' || WCODITEMCS;
    WSQL = WSQL || ' WHEN MOV.BDVLRIR      > 0 THEN ' || WCODITEMIR;
    WSQL = WSQL || ' WHEN MOV.BDRETINSS    > 0 THEN ' || WCODITEMINSS;
    WSQL = WSQL || ' WHEN MOV.BDISSRET     > 0 THEN ' || WCODITEMISS;
    WSQL = WSQL || ' WHEN MOV.BDVLRAPOS15  > 0 THEN ' || WCODITEMINSS15; -- Contabilização INSS aposentadoria especial #123489 #128660 #101172 #100393 #DBS! Mesma regra INSS - Matheus Amaral - 09/03/2020
    WSQL = WSQL || ' WHEN MOV.BDVLRAPOS20  > 0 THEN ' || WCODITEMINSS20; -- Contabilização INSS aposentadoria especial #123489 #128660 #101172 #100393 #DBS! Mesma regra INSS - Matheus Amaral - 09/03/2020
    WSQL = WSQL || ' WHEN MOV.BDVLRAPOS25  > 0 THEN ' || WCODITEMINSS25; -- Contabilização INSS aposentadoria especial #123489 #128660 #101172 #100393 #DBS! Mesma regra INSS - Matheus Amaral - 09/03/2020
    WSQL = WSQL || ' END BDCODITEMONLINE, MOV.BDCODREC, bdreferencia ';
    WSQL = WSQL || 'FROM (';
    WSQL = WSQL || ' SELECT ' || WFIELDREF || ' as bdreferencia, R.BDCODRECPIS BDCODREC, ''PIS'' BDTIPO, SUM(COALESCE(R.BDVLRPIS, 0)) BDVLRPIS, 0 BDVLRCOFINS, 0 BDVLRCSOCIAL, 0 BDVLRIR, 0 BDRETINSS, 0 BDISSRET, 0 BDVLRAPOS15, 0 BDVLRAPOS20, 0 BDVLRAPOS25 ';
    WSQL = WSQL || ' FROM ' || :WTABLERET || ' R ';
    WSQL = WSQL || WLEFT_TABLEDATA;
    WSQL = WSQL || ' WHERE R.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || ' GROUP BY ' || WFIELDREF || ', R.BDCODEMP, R.BDSESSAO, R.BDCODRECPIS ';
    WSQL = WSQL || '   UNION ALL ';
    WSQL = WSQL || ' SELECT ' || WFIELDREF || ' as bdreferencia, R.BDCODRECCOFINS BDCODREC, ''COFINS'' BDTIPO, 0 BDVLRPIS, SUM(COALESCE(R.BDVLRCOFINS, 0)) BDVLRCOFINS, 0 BDVLRCSOCIAL, 0 BDVLRIR, 0 BDRETINSS, 0 BDISSRET, 0 BDVLRAPOS15, 0 BDVLRAPOS20, 0 BDVLRAPOS25 ';
    WSQL = WSQL || ' FROM ' || :WTABLERET || ' R ';
    WSQL = WSQL || WLEFT_TABLEDATA;
    WSQL = WSQL || ' WHERE R.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || ' GROUP BY ' || WFIELDREF || ', R.BDCODEMP, R.BDSESSAO, R.BDCODRECCOFINS ';
    WSQL = WSQL || '   UNION ALL ';
    WSQL = WSQL || ' SELECT ' || WFIELDREF || ' as bdreferencia, R.BDCODRECCSOCIAL BDCODREC, ''CSOCIAL'' BDTIPO, 0 BDVLRPIS, 0 BDVLRCOFINS, SUM(COALESCE(R.BDVLRCSOCIAL, 0)), 0 BDVLRIR, 0 BDRETINSS, 0 BDISSRET, 0 BDVLRAPOS15, 0 BDVLRAPOS20, 0 BDVLRAPOS25 ';
    WSQL = WSQL || ' FROM ' || :WTABLERET || ' R ';
    WSQL = WSQL || WLEFT_TABLEDATA;
    WSQL = WSQL || ' WHERE R.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || ' GROUP BY ' || WFIELDREF || ', R.BDCODEMP, R.BDSESSAO, R.BDCODRECCSOCIAL ';
    WSQL = WSQL || '   UNION ALL ';

    if (position('SER', :PRTIPOLAN) = 0) then
    begin
      WSQL = WSQL || ' SELECT ' || WFIELDREF || ' as bdreferencia, R.BDCODRECIR BDCODREC, ''IR'' BDTIPO, 0 BDVLRPIS, 0 BDVLRCOFINS, 0 BDVLRCSOCIAL, SUM(COALESCE(R.BDVLRIR, 0)) BDVLRIR, 0 BDINSSRET, 0 BDISSRET, 0 BDVLRAPOS15, 0 BDVLRAPOS20, 0 BDVLRAPOS25 ';
      WSQL = WSQL || ' FROM ' || :WTABLERET || ' R ';
      WSQL = WSQL || WLEFT_TABLEDATA;
      WSQL = WSQL || ' WHERE R.BDSESSAO = ' || :PRSESSAO;
      WSQL = WSQL || ' GROUP BY ' || WFIELDREF || ', R.BDCODEMP, R.BDSESSAO, R.BDCODRECIR ';
    end
    else
    begin
      WSQL = WSQL || ' SELECT ' || WFIELDREF || ' as bdreferencia, R.BDCODREC BDCODREC, ''IR'' BDTIPO, 0 BDVLRPIS, 0 BDVLRCOFINS, 0 BDVLRCSOCIAL, SUM(COALESCE(R.BDVLRIRSER, 0)) BDVLRIR, 0 BDINSSRET, 0 BDISSRET, 0 BDVLRAPOS15, 0 BDVLRAPOS20, 0 BDVLRAPOS25 ';
      WSQL = WSQL || ' FROM ' || :WTABLEITEM || ' R ';
      WSQL = WSQL || WLEFT_TABLEDATA;
      WSQL = WSQL || ' WHERE R.BDSESSAO = ' || :PRSESSAO;
      WSQL = WSQL || ' GROUP BY ' || WFIELDREF || ', R.BDCODEMP, R.BDSESSAO, R.BDCODREC ';
    end

    WSQL = WSQL || '   UNION ALL ';
    WSQL = WSQL || ' SELECT ' || WFIELDREF || ' as bdreferencia, ' || iif((position('SER', :PRTIPOLAN) = 0), 'R.BDCODRECISS', '0') || ' BDCODREC, ''ISS'' BDTIPO, 0 BDVLRPIS, 0 BDVLRCOFINS, 0 BDVLRCSOCIAL, 0 BDVLRIR, 0 BDRETINSS, SUM(COALESCE(R.BDISSRET, 0)) BDISSRET, 0 BDVLRAPOS15, 0 BDVLRAPOS20, 0 BDVLRAPOS25 ';
    WSQL = WSQL || ' FROM ' || :WTABLERET || ' R ';
    WSQL = WSQL || WLEFT_TABLEDATA;
    WSQL = WSQL || ' WHERE R.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || ' GROUP BY ' || WFIELDREF || ', R.BDCODEMP, R.BDSESSAO, BDCODREC ';
    WSQL = WSQL || '   UNION ALL ';
    WSQL = WSQL || ' SELECT ' || WFIELDREF || ' as bdreferencia, COALESCE(R.BDCODRECINSS, 0) BDCODREC, ''INSS'' BDTIPO, 0 BDVLRPIS, 0 BDVLRCOFINS, 0 BDVLRCSOCIAL, 0 BDVLRIR, SUM(COALESCE(R.BDRETINSS, 0)) BDINSSRET, 0 BDISSRET, SUM(COALESCE(R.BDVLRAPOS15, 0)) BDVLRAPOS15, SUM(COALESCE(R.BDVLRAPOS20, 0)) BDVLRAPOS20, SUM(COALESCE(R.BDVLRAPOS25, 0)) BDVLRAPOS25 ';
    WSQL = WSQL || ' FROM ' || :WTABLEINSS || ' R ';
    WSQL = WSQL || WLEFT_TABLEDATA;
    WSQL = WSQL || ' WHERE R.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || ' GROUP BY ' || WFIELDREF || ', R.BDCODEMP, R.BDSESSAO, R.BDCODRECINSS ';
    WSQL = WSQL || '   UNION ALL ';
    WSQL = WSQL || ' SELECT ' || WFIELDREF || ' as bdreferencia, 0 BDCODREC, ''INSS15'' BDTIPO, 0 BDVLRPIS, 0 BDVLRCOFINS, 0 BDVLRCSOCIAL, 0 BDVLRIR, 0 BDINSSRET, 0 BDISSRET, SUM(COALESCE(R.BDVLRAPOS15, 0)) BDVLRAPOS15, 0 BDVLRAPOS20, 0 BDVLRAPOS25 ';
    WSQL = WSQL || ' FROM ' || :WTABLEINSS || ' R ';
    WSQL = WSQL || WLEFT_TABLEDATA;
    WSQL = WSQL || ' WHERE R.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || ' GROUP BY ' || WFIELDREF || ', R.BDCODEMP, R.BDSESSAO, R.BDCODRECINSS ';
    WSQL = WSQL || '   UNION ALL ';
    WSQL = WSQL || ' SELECT ' || WFIELDREF || ' as bdreferencia, 0 BDCODREC, ''INSS20'' BDTIPO, 0 BDVLRPIS, 0 BDVLRCOFINS, 0 BDVLRCSOCIAL, 0 BDVLRIR, 0 BDINSSRET, 0 BDISSRET, 0 BDVLRAPOS15, SUM(COALESCE(R.BDVLRAPOS20, 0)) BDVLRAPOS20, 0 BDVLRAPOS25 ';
    WSQL = WSQL || ' FROM ' || :WTABLEINSS || ' R ';
    WSQL = WSQL || WLEFT_TABLEDATA;
    WSQL = WSQL || ' WHERE R.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || ' GROUP BY ' || WFIELDREF || ', R.BDCODEMP, R.BDSESSAO, R.BDCODRECINSS ';
    WSQL = WSQL || '   UNION ALL ';
    WSQL = WSQL || ' SELECT ' || WFIELDREF || ' as bdreferencia, 0 BDCODREC, ''INSS25'' BDTIPO, 0 BDVLRPIS, 0 BDVLRCOFINS, 0 BDVLRCSOCIAL, 0 BDVLRIR, 0 BDINSSRET, 0 BDISSRET, 0 BDVLRAPOS15, 0 BDVLRAPOS20, SUM(COALESCE(R.BDVLRAPOS25, 0)) BDVLRAPOS25 ';
    WSQL = WSQL || ' FROM ' || :WTABLEINSS || ' R ';
    WSQL = WSQL || WLEFT_TABLEDATA;
    WSQL = WSQL || ' WHERE R.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || ' GROUP BY ' || WFIELDREF || ', R.BDCODEMP, R.BDSESSAO, R.BDCODRECINSS ';
    WSQL = WSQL || ') MOV ';
    WSQL = WSQL || 'WHERE ((MOV.BDVLRPIS > 0) OR (BDVLRCOFINS > 0) OR (BDVLRCSOCIAL > 0) OR (BDVLRIR > 0) OR (BDRETINSS > 0) OR (BDISSRET > 0) OR (BDVLRAPOS15 > 0) OR (BDVLRAPOS20 > 0) OR (BDVLRAPOS25 > 0));';
    execute statement WSQL;
  end
  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', '3');

  /*Buscando contas para os valores do FunRural */
  if (:WTABLEFUNRURAL <> '') then
  begin
      /*Insere na tabela todas os Funrurais que vão ser usadas na importação*/
    WSQL = 'insert INTO TMP_TCFOP_TMOV(bdSESSAO, bdCODITEMONLINE, bdCODREC, bdreferencia) ';
    WSQL = WSQL || 'select /*first 1*/ ' || :PRSESSAO || ' as bdSESSAO, '; -- Alt.: 179132 - Deve carregar todoas as contas e não só a primeira, quando contabilizava vários meses juntos, não contabilizava o Funrural após o primeiro mês, pois não carregava as contas aqui...
    if (:PRTIPOLAN = 'SAI') then
      WSQL = WSQL || '       iif(o_ref.bdchave is not null, o.bdCODITEMONLINE, ' || WCODITEMFUNRURAL || ') AS bdCODITEMONLINE, ';
    else
      WSQL = WSQL || '       ' || WCODITEMFUNRURAL || ' as bdCODITEMONLINE, ';
    WSQL = WSQL || '       0 as bdCODREC, ' || WFIELDREF;
    WSQL = WSQL || 'from ' || :WTABLE || ' mov ';
    WSQL = WSQL || 'join ' || :WTABLEFUNRURAL || ' f on (f.bdCODEMP = mov.bdCODEMP and f.bdCHAVE = mov.bdCHAVE and f.bdSESSAO = mov.bdSESSAO) ';
    WSQL = WSQL || 'LEFT OUTER JOIN ' || :WTABLEAUXDATA || ' data on(data.BDCODEMP = mov.BDCODEMP AND data.BDCHAVE = mov.BDCHAVE AND data.BDSESSAO = mov.BDSESSAO) ';
    if (:PRTIPOLAN = 'SAI') then -- Alt.: #131080 - Nas saidas vai buscar a conatbuilização da "Conta FunRural PJ", quando tiver essa conta informada vai buscar apenas ela e não a retencao do Funrural... Alt.: #172283 - Ajustado para olhar se tem contas informadas...
      WSQL = WSQL || 'LEFT OUTER JOIN TCONF_CONTAS_ONLINE o ON (o.bdCODPLANOONLINE = ' || :PRCODPLANOONLINE || ' AND o.bdCODITEMONLINE = 301) ' || 'LEFT OUTER JOIN (SELECT r.* ' || 'FROM TCONF_CONTAS_ONLINE o ' || 'LEFT OUTER JOIN ('||:WSQLCONTAS||') r ON (r.BDCODPLANOONLINE = O.BDCODPLANOONLINE AND r.BDCHAVE = O.BDCHAVE) ' || 'WHERE O.BDCODPLANOONLINE = ' || :PRCODPLANOONLINE || '  AND O.BDCODITEMONLINE = 301 AND (R.bdCONTADEBPROV IS NOT NULL /*OR o.bdCONTACREDPROV IS NOT NULL*/)) o_ref on (o_ref.BDCODPLANOONLINE = o.BDCODPLANOONLINE and o_ref.BDCHAVE = o.BDCHAVE and ' || '  ((o_ref.BDREFCTA IS NULL) OR (o_ref.BDREFCTA = 0) OR (o_ref.BDREFCTA = (' -- Alt.: #148890 - Quando a referencia estiver zerada, deve considerar ela...
      || 'SELECT FIRST 1 bdREFCTA FROM ('||:WSQLCONTAS||') ' || 'WHERE bdCODPLANOONLINE = o.bdCODPLANOONLINE AND bdCHAVE = o.bdCHAVE AND bdREFCTA <= ' || WFIELDREF || ' ORDER BY bdCODPLANOONLINE DESC, bdCHAVE DESC, bdREFCTA DESC) AND o_ref.bdCONTADEBPROV > 0 AND o_ref.bdCONTACREDPROV > 0))) ';
    WSQL = WSQL || 'where mov.bdSESSAO = ' || :PRSESSAO;
    if (:PRTIPOLAN = 'ENT') then
      WSQL = WSQL || '  and ((f.bdVLRFUNRURAL > 0) or (f.bdVLRGILRAT > 0) or (f.BDVLRFPAS > 0)) ';
    else
      WSQL = WSQL || '  and ((f.bdVLRFUNRURAL > 0) or (f.bdVLRGILRAT > 0) or (f.bdVLRSENAR > 0)) ';
      --elizeu - 27-07-18 - estava contabilizando o funRural matriciando Troca Global - Contabilização Funrural #8737
    WSQL = WSQL || '    GROUP BY mov.BDCODEMP, mov.BDSESSAO, ' || WFIELDREF;
    if (:PRTIPOLAN = 'SAI') then
      WSQL = WSQL || ', o_ref.bdchave, o.bdCODITEMONLINE';
    WSQL = WSQL || ';';
    execute statement WSQL;
    if (WCODITEMROYALTIES > 0) then -- Alt.: #98173 - Não estava aplicando os valores de Royalties nos Plano de trocas, Troca global e Recontabilizacao
    begin
          /*Insere na tabela todas os Royalties que vão ser usadas na importação*/
      WSQL = 'INSERT INTO TMP_TCFOP_TMOV (bdSESSAO, bdCODITEMONLINE, bdCODREC, bdreferencia) ';
      WSQL = WSQL || 'SELECT FIRST 1 ' || :PRSESSAO || ' AS bdSESSAO, ' || WCODITEMROYALTIES || ' AS bdCODITEMONLINE, 0 AS bdCODREC, ' || WFIELDREF;
      WSQL = WSQL || 'FROM ' || :WTABLE || ' mov ';
      WSQL = WSQL || 'JOIN ' || :WTABLEFUNRURAL || ' f ON (f.bdCODEMP = mov.bdCODEMP AND f.bdCHAVE = mov.bdCHAVE AND f.bdSESSAO = mov.bdSESSAO) ';
      WSQL = WSQL || 'LEFT OUTER JOIN ' || :WTABLEAUXDATA || ' data on(data.BDCODEMP = mov.BDCODEMP AND data.BDCHAVE = mov.BDCHAVE AND data.BDSESSAO = mov.BDSESSAO) ';
      WSQL = WSQL || 'WHERE mov.bdSESSAO = ' || :PRSESSAO || ' ';
      WSQL = WSQL || '  AND f.bdROYALTIES > 0 ';
      WSQL = WSQL || 'GROUP BY mov.bdCODEMP, mov.bdSESSAO, ' || WFIELDREF || '; ';
      execute statement WSQL;
    end
  end
  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', '4');

  /*Buscando contas para os valores da Difal*/
  if ((:PRTIPOLAN = 'ENT') or (:PRTIPOLAN = 'SAI')) then
  begin
      /*Verifica se tem o Valor do FCP da UF de destino em algum lançamento*/
    WSQL = 'INSERT INTO TMP_TCFOP_TMOV(BDSESSAO, BDCODNAT, BDCONDPGTO, BDCODITEMONLINE, bdreferencia) ';
    WSQL = WSQL || 'SELECT FCP.BDSESSAO, I.BDCODNAT, ';
    WSQL = WSQL || ' CASE WHEN COALESCE(mov.BDCONDPGTO, 0) = 0 THEN 50 ';
    WSQL = WSQL || 'WHEN COALESCE(mov.BDCONDPGTO, 0) = 1 THEN 51 ';
    WSQL = WSQL || 'WHEN COALESCE(mov.BDCONDPGTO, 0) = 2 THEN 406 ';
    WSQL = WSQL || ' END BDCONDPGTO, ';
    WSQL = WSQL || ' CASE WHEN COALESCE(mov.BDCONDPGTO, 0) = 0 THEN 225 ';/*A vista*/
    WSQL = WSQL || 'WHEN COALESCE(mov.BDCONDPGTO, 0) = 1 THEN 226 ';/*A prazo*/
    WSQL = WSQL || 'WHEN COALESCE(mov.BDCONDPGTO, 0) = 2 THEN 227 ';/*Outras*/
    WSQL = WSQL || ' END BDTIPOCONTA, ' || WFIELDREF || ' as bdreferencia ';
    WSQL = WSQL || 'FROM ( ';
    WSQL = WSQL || 'SELECT DC.BDSESSAO, SUM(DC.BDVLR_FCP_UF_DEST) BDVLR_FCP_UF_DEST ';
    WSQL = WSQL || 'FROM ( ';
    WSQL = WSQL || ' SELECT D.BDSESSAO, SUM(COALESCE(D.BDVLR_FCP_UF_DEST, 0)) BDVLR_FCP_UF_DEST ';
    WSQL = WSQL || ' FROM ' || :WTABLED100 || ' D ';
    WSQL = WSQL || ' WHERE D.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || ' GROUP BY D.BDSESSAO, D.BDCODEMP ';
    WSQL = WSQL || ' UNION ALL ';
    WSQL = WSQL || ' SELECT C.BDSESSAO, SUM(COALESCE(C.BDVLR_FCP_UF_DEST, 0)) BDVLR_FCP_UF_DEST ';
    WSQL = WSQL || ' FROM ' || :WTABLEC100 || ' C ';
    WSQL = WSQL || ' WHERE C.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || ' GROUP BY C.BDSESSAO, C.BDCODEMP ';
    WSQL = WSQL || ') DC ';
    WSQL = WSQL || 'GROUP BY DC.BDSESSAO ';
    WSQL = WSQL || ') FCP ';
    WSQL = WSQL || 'JOIN ' || :WTABLEITEM || ' I ON(I.BDSESSAO = FCP.BDSESSAO) ';
    WSQL = WSQL || 'LEFT OUTER JOIN ' || :WTABLE || ' mov ON(mov.BDSESSAO = I.BDSESSAO AND mov.BDCODEMP = I.BDCODEMP AND mov.BDCHAVE = I.BDCHAVE) ';
    WSQL = WSQL || 'LEFT OUTER JOIN ' || :WTABLEAUXDATA || ' data on(data.BDCODEMP = mov.BDCODEMP AND data.BDCHAVE = mov.BDCHAVE AND data.BDSESSAO = mov.BDSESSAO) ';
    WSQL = WSQL || 'WHERE FCP.BDVLR_FCP_UF_DEST > 0 ';
    WSQL = WSQL || 'UNION ';
      /*Verifica se tem o Valor do ICMS interestadual para UF de destino em algum lançamento*/
    WSQL = WSQL || 'SELECT FCP.BDSESSAO, I.BDCODNAT, ';
    WSQL = WSQL || ' CASE WHEN COALESCE(mov.BDCONDPGTO, 0) = 0 THEN 50 ';
    WSQL = WSQL || 'WHEN COALESCE(mov.BDCONDPGTO, 0) = 1 THEN 51 ';
    WSQL = WSQL || 'WHEN COALESCE(mov.BDCONDPGTO, 0) = 2 THEN 406 ';
    WSQL = WSQL || ' END BDCONDPGTO, ';
    WSQL = WSQL || ' CASE WHEN COALESCE(mov.BDCONDPGTO, 0) = 0 THEN 228 ';/*A vista*/
    WSQL = WSQL || 'WHEN COALESCE(mov.BDCONDPGTO, 0) = 1 THEN 229 ';/*A prazo*/
    WSQL = WSQL || 'WHEN COALESCE(mov.BDCONDPGTO, 0) = 2 THEN 230 ';/*Outras*/
    WSQL = WSQL || ' END BDTIPOCONTA, ' || WFIELDREF || ' as bdreferencia ';
    WSQL = WSQL || 'FROM ( ';
    WSQL = WSQL || 'SELECT DC.BDSESSAO, SUM(DC.BDVLRICMS_UF_DEST) BDVLRICMS_UF_DEST ';
    WSQL = WSQL || 'FROM ( ';
    WSQL = WSQL || ' SELECT D.BDSESSAO, SUM(COALESCE(D.BDVLRICMS_UF_DEST, 0)) BDVLRICMS_UF_DEST ';
    WSQL = WSQL || ' FROM ' || :WTABLED100 || ' D ';
    WSQL = WSQL || ' WHERE D.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || ' GROUP BY D.BDSESSAO, D.BDCODEMP ';
    WSQL = WSQL || ' UNION ALL ';
    WSQL = WSQL || ' SELECT C.BDSESSAO, SUM(COALESCE(C.BDVLRICMS_UF_DEST, 0)) BDVLRICMS_UF_DEST ';
    WSQL = WSQL || ' FROM ' || :WTABLEC100 || ' C ';
    WSQL = WSQL || ' WHERE C.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || ' GROUP BY C.BDSESSAO, C.BDCODEMP ';
    WSQL = WSQL || ') DC ';
    WSQL = WSQL || 'GROUP BY DC.BDSESSAO ';
    WSQL = WSQL || ') FCP ';
    WSQL = WSQL || 'JOIN ' || :WTABLEITEM || ' I ON(I.BDSESSAO = FCP.BDSESSAO) ';
    WSQL = WSQL || 'LEFT OUTER JOIN ' || :WTABLE || ' mov ON(mov.BDSESSAO = I.BDSESSAO AND mov.BDCODEMP = I.BDCODEMP AND mov.BDCHAVE = I.BDCHAVE) ';
    WSQL = WSQL || 'LEFT OUTER JOIN ' || :WTABLEAUXDATA || ' data on(data.BDCODEMP = mov.BDCODEMP AND data.BDCHAVE = mov.BDCHAVE AND data.BDSESSAO = mov.BDSESSAO) ';
    WSQL = WSQL || 'WHERE FCP.BDVLRICMS_UF_DEST > 0 ';
    WSQL = WSQL || 'UNION ';
      /*Verifica se tem o Valor do ICMS interestadual para UF do remetente em algum lançamento*/
    WSQL = WSQL || 'SELECT FCP.BDSESSAO, I.BDCODNAT, ';
    WSQL = WSQL || ' CASE WHEN COALESCE(mov.BDCONDPGTO, 0) = 0 THEN 50 ';
    WSQL = WSQL || 'WHEN COALESCE(mov.BDCONDPGTO, 0) = 1 THEN 51 ';
    WSQL = WSQL || 'WHEN COALESCE(mov.BDCONDPGTO, 0) = 2 THEN 406 ';
    WSQL = WSQL || ' END BDCONDPGTO, ';
    WSQL = WSQL || ' CASE WHEN COALESCE(mov.BDCONDPGTO, 0) = 0 THEN 231 ';/*A vista*/
    WSQL = WSQL || 'WHEN COALESCE(mov.BDCONDPGTO, 0) = 1 THEN 232 ';/*A prazo*/
    WSQL = WSQL || 'WHEN COALESCE(mov.BDCONDPGTO, 0) = 2 THEN 233 ';/*Outras*/
    WSQL = WSQL || ' END BDTIPOCONTA, ' || WFIELDREF || ' as bdreferencia ';
    WSQL = WSQL || 'FROM ( ';
    WSQL = WSQL || 'SELECT DC.BDSESSAO, SUM(DC.BDVLRICMS_UF_REM) BDVLRICMS_UF_REM ';
    WSQL = WSQL || 'FROM ( ';
    WSQL = WSQL || ' SELECT D.BDSESSAO, SUM(COALESCE(D.BDVLRICMS_UF_REM, 0)) BDVLRICMS_UF_REM ';
    WSQL = WSQL || ' FROM ' || :WTABLED100 || ' D ';
    WSQL = WSQL || ' WHERE D.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || ' GROUP BY D.BDSESSAO, D.BDCODEMP ';
    WSQL = WSQL || ' UNION ALL ';
    WSQL = WSQL || ' SELECT C.BDSESSAO, SUM(COALESCE(C.BDVLRICMS_UF_REM, 0)) BDVLRICMS_UF_REM ';
    WSQL = WSQL || ' FROM ' || :WTABLEC100 || ' C ';
    WSQL = WSQL || ' WHERE C.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || ' GROUP BY C.BDSESSAO, C.BDCODEMP ';
    WSQL = WSQL || ') DC ';
    WSQL = WSQL || 'GROUP BY DC.BDSESSAO ';
    WSQL = WSQL || ') FCP ';
    WSQL = WSQL || 'JOIN ' || :WTABLEITEM || ' I ON(I.BDSESSAO = FCP.BDSESSAO) ';
    WSQL = WSQL || 'LEFT OUTER JOIN ' || :WTABLE || ' mov ON(mov.BDSESSAO = I.BDSESSAO AND mov.BDCODEMP = I.BDCODEMP AND mov.BDCHAVE = I.BDCHAVE) ';
    WSQL = WSQL || 'LEFT OUTER JOIN ' || :WTABLEAUXDATA || ' data on(data.BDCODEMP = mov.BDCODEMP AND data.BDCHAVE = mov.BDCHAVE AND data.BDSESSAO = mov.BDSESSAO) ';
    WSQL = WSQL || 'WHERE FCP.BDVLRICMS_UF_REM > 0 ';
    execute statement WSQL;
  end
  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', '5');
  /******************************************/

  /*Buscando contas para os valores de Diferencial de alíquota*/
  if ((:PRTIPOLAN = 'ENT') or (:PRTIPOLAN = 'SAI')) then
  begin
    WSQL = 'INSERT INTO TMP_TCFOP_TMOV(BDSESSAO, BDCODNAT, BDCONDPGTO, BDCODITEMONLINE, bdreferencia) ';
    WSQL = WSQL || 'SELECT DIF.BDSESSAO, I.BDCODNAT, ';
    WSQL = WSQL || '       CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
    WSQL = WSQL || '            WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
    WSQL = WSQL || '            WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
    WSQL = WSQL || '       END BDCONDPGTO, ';
    WSQL = WSQL || '       CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 219  /*A vista*/ ';
    WSQL = WSQL || '            WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 220  /*A prazo*/ ';
    WSQL = WSQL || '            WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 221  /*Outras*/ ';
    WSQL = WSQL || '       END BDTIPOCONTA, extract(year from MOV.BDDATAEMISSAO) * 100 + extract(month from MOV.BDDATAEMISSAO) as BDREFERENCIA ';
    WSQL = WSQL || 'FROM ' || WTABLEDIFALIQ || ' DIF ';
    WSQL = WSQL || 'JOIN ' || WTABLEITEM || ' I ON(I.BDSESSAO = DIF.BDSESSAO AND I.BDCODEMP = DIF.BDCODEMP AND I.BDCHAVE = DIF.BDCHAVE AND I.BDORDEM = DIF.BDORDEM) ';
    WSQL = WSQL || 'JOIN ' || WTABLE || ' MOV ON(MOV.BDSESSAO = I.BDSESSAO AND MOV.BDCODEMP = I.BDCODEMP AND MOV.BDCHAVE = I.BDCHAVE) ';
    WSQL = WSQL || 'WHERE DIF.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || 'AND DIF.BDVLRDIFENTALIQ > 0 ';
    WSQL = WSQL || 'GROUP BY DIF.BDSESSAO, MOV.BDCONDPGTO, I.BDCODNAT, extract(year from MOV.BDDATAEMISSAO) * 100 + extract(month from MOV.BDDATAEMISSAO) ';
    WSQL = WSQL || 'UNION ';
    WSQL = WSQL || 'SELECT DIFPR.BDSESSAO, I.BDCODNAT, ';
    WSQL = WSQL || '       CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
    WSQL = WSQL || '            WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
    WSQL = WSQL || '            WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
    WSQL = WSQL || '       END BDCONDPGTO, ';
    WSQL = WSQL || '       CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 219  /*A vista*/ ';
    WSQL = WSQL || '            WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 220  /*A prazo*/ ';
    WSQL = WSQL || '            WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 221  /*Outras*/ ';
    WSQL = WSQL || '       END BDTIPOCONTA, extract(year from MOV.BDDATAEMISSAO) * 100 + extract(month from MOV.BDDATAEMISSAO) as BDREFERENCIA ';
    WSQL = WSQL || 'FROM ' || WTABLEDIFALIQPR || ' DIFPR ';
    WSQL = WSQL || 'JOIN ' || WTABLEITEM || ' I ON(I.BDSESSAO = DIFPR.BDSESSAO AND I.BDCODEMP = DIFPR.BDCODEMP AND I.BDCHAVE = DIFPR.BDCHAVE AND I.BDORDEM = DIFPR.BDORDEM) ';
    WSQL = WSQL || 'JOIN ' || WTABLE || ' MOV ON(MOV.BDSESSAO = I.BDSESSAO AND MOV.BDCODEMP = I.BDCODEMP AND MOV.BDCHAVE = I.BDCHAVE) ';
    WSQL = WSQL || 'WHERE DIFPR.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || 'AND DIFPR.BDIMPRECOLHER > 0 ';
    WSQL = WSQL || 'GROUP BY DIFPR.BDSESSAO, MOV.BDCONDPGTO, I.BDCODNAT, extract(year from MOV.BDDATAEMISSAO) * 100 + extract(month from MOV.BDDATAEMISSAO) ';
    execute statement WSQL;
  end
  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', '6');

  if (:PRTIPOLAN = 'ENT') then
  begin
      /*ANTECIPAÇÃO DE ICMS  */
    WSQL = 'INSERT INTO TMP_TCFOP_TMOV(BDSESSAO, BDCODNAT, BDCONDPGTO, BDCODITEMONLINE, bdreferencia) ';
    WSQL = WSQL || 'SELECT ANT.BDSESSAO, I.BDCODNAT, ';
    WSQL = WSQL || '       CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
    WSQL = WSQL || '            WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
    WSQL = WSQL || '            WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
    WSQL = WSQL || '       END BDCONDPGTO, ';
    WSQL = WSQL || '       CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 298  /*A vista*/ ';
    WSQL = WSQL || '            WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 299  /*A prazo*/ ';
    WSQL = WSQL || '            WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 300  /*Outras*/ ';
    WSQL = WSQL || '       END BDTIPOCONTA, ' || WFIELDREF || ' as bdreferencia ';
    WSQL = WSQL || 'FROM TMP_VEF_EMP_TMOVENTANTIMP_TEMP ANT ';
    WSQL = WSQL || 'JOIN TMP_VEF_EMP_TMOVENTITENS_TEMP I ON(I.BDSESSAO = ANT.BDSESSAO AND I.BDCODEMP = ANT.BDCODEMP AND I.BDCHAVE = ANT.BDCHAVE) ';
    WSQL = WSQL || 'JOIN TMP_VEF_EMP_TMOVENT_TEMP MOV ON(MOV.BDSESSAO = I.BDSESSAO AND MOV.BDCODEMP = I.BDCODEMP AND MOV.BDCHAVE = I.BDCHAVE) ';
    WSQL = WSQL || 'LEFT OUTER JOIN ' || :WTABLEAUXDATA || ' data on (data.BDCODEMP = mov.BDCODEMP AND data.BDCHAVE = mov.BDCHAVE AND data.BDSESSAO = mov.BDSESSAO) ';
    WSQL = WSQL || 'WHERE ANT.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || 'AND ANT.BDIMPRECOLHER > 0 ';
    WSQL = WSQL || 'GROUP BY ANT.BDSESSAO, MOV.BDCONDPGTO, I.BDCODNAT, ' || WFIELDREF || ' ';
    WSQL = WSQL || 'UNION ';
    WSQL = WSQL || 'SELECT ANTPR.BDSESSAO, I.BDCODNAT, ';
    WSQL = WSQL || '       CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
    WSQL = WSQL || '            WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
    WSQL = WSQL || '            WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
    WSQL = WSQL || '       END BDCONDPGTO, ';
    WSQL = WSQL || '       CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 298  /*A vista*/ ';
    WSQL = WSQL || '            WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 299  /*A prazo*/ ';
    WSQL = WSQL || '            WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 300  /*Outras*/ ';
    WSQL = WSQL || '       END BDTIPOCONTA, ' || WFIELDREF || ' as bdreferencia ';
    WSQL = WSQL || 'FROM TMP_VEF_EMP_TMOVENTANTPR_TEMP ANTPR ';
    WSQL = WSQL || 'JOIN TMP_VEF_EMP_TMOVENTITENS_TEMP I ON(I.BDSESSAO = ANTPR.BDSESSAO AND I.BDCODEMP = ANTPR.BDCODEMP AND I.BDCHAVE = ANTPR.BDCHAVE) ';
    WSQL = WSQL || 'JOIN TMP_VEF_EMP_TMOVENT_TEMP MOV ON(MOV.BDSESSAO = I.BDSESSAO AND MOV.BDCODEMP = I.BDCODEMP AND MOV.BDCHAVE = I.BDCHAVE) ';
    WSQL = WSQL || 'LEFT OUTER JOIN ' || :WTABLEAUXDATA || ' data on (data.BDCODEMP = mov.BDCODEMP AND data.BDCHAVE = mov.BDCHAVE AND data.BDSESSAO = mov.BDSESSAO) ';
    WSQL = WSQL || 'WHERE ANTPR.BDSESSAO = ' || :PRSESSAO;
    WSQL = WSQL || 'AND ANTPR.BDVLRANT > 0 ';
    WSQL = WSQL || 'GROUP BY ANTPR.BDSESSAO, MOV.BDCONDPGTO, I.BDCODNAT, ' || WFIELDREF || ' ';

    execute statement WSQL;
  end
  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', '7');

  WSQL = '';

  /*Remover esse delete, a tabela é temporária*/
  delete from TCONTAS_ONLINE_TEMP
  where BDSESSAO = :PRSESSAO;
  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', '8');

  /*Pega as contas dos lan?amentos(CFOPS e condi??es de pagamento) que tem na tabela temporaria*/
  insert into TCONTAS_ONLINE_TEMP (BDSESSAO, BDCHAVE, BDREFERENCIA, BDCODTIPOCONTA, BDCODNAT, BDCLASSIFICACAO,
                                   BDCONTADEBPROV, BDCONTACREDPROV, BDCODITEMONLINE, BDCODPLAPADRAO, BDFORMULA,
                                   BDCLASS_TITULO, BDCHAVECONF, BDCLASSCODNAT, BDCOMPLEMENTO, BDCODHIST, BDCODTPHI,
                                   BDEMPREENDIMENTOPROVD, BDEMPREENDIMENTOPROVC)
  select :PRSESSAO, C.BDCHAVE, CF.BDREFERENCIA, C.BDCODTIPOCONTA, C.BDCODNAT, C.BDCLASSIFICACAO, O_REF.BDCONTADEBPROV,
         O_REF.BDCONTACREDPROV, C.BDCODITEMONLINE, C.BDCODPLAPADRAO, C.BDFORMULA, C.BDCLASSIFICACAO, C.BDCHAVE,
         NAT.BDCLASSIFICACAO, H.BDCOMPLEMENTO, O_REF.BDCODTPHI, O_REF.BDCODHISTPROV,
         PLAD.BDCTAEMPREENDIMENTOSIMOB BDEMPREENDIMENTOPROVD, PLAC.BDCTAEMPREENDIMENTOSIMOB BDEMPREENDIMENTOPROVC
  from TCONF_CONTAS_ONLINE C
  join TMP_TCFOP_TMOV CF on (CF.BDSESSAO = :PRSESSAO and
        CF.BDCODNAT = C.BDCODNAT and
        CF.BDCONDPGTO = C.BDCODTIPOCONTA and
        CF.BDCODITEMONLINE = C.BDCODITEMONLINE)
  left outer join(select ONL.BDCODPLANOONLINE, ONL.BDCHAVE, REF_PAI.BDREFCTA, REF.BDCODPLAPADRAO, REF.BDCODTPHI,
                         REF.BDCONTADEBPROV, REF.BDCONTACREDPROV, REF.BDCODHISTPROV, REF.BDCODCOMPHISTPROV,
                         REF.BDCONTADEBPGTO, REF.BDCONTACREDPGTO, REF.BDCODHISTPGTO, REF.BDCODCOMPHISTPGTO,
                         REF.BDCOPYTITULO, ONL.BDCHAVEVINC
                  from TCONF_CONTAS_ONLINE ONL
                  left outer join TCONF_CONTAS_ONLINE_REF REF_PAI on (ONL.BDCODPLANOONLINE = REF_PAI.BDCODPLANOONLINE and
                        REF_PAI.BDCHAVE = coalesce(ONL.BDCHAVEVINC, ONL.BDCHAVE))
                  left outer join TCONF_CONTAS_ONLINE_REF REF on (ONL.BDCODPLANOONLINE = REF.BDCODPLANOONLINE and
                        ONL.BDCHAVE = REF.BDCHAVE and
                        REF_PAI.BDREFCTA = REF.BDREFCTA)
                  where ONL.BDCODPLANOONLINE = :PRCODPLANOONLINE and
                        ONL.BDCLASSIFICACAO like '03.%') O_REF on (O_REF.BDCODPLANOONLINE = C.BDCODPLANOONLINE and
        O_REF.BDCHAVE = C.BDCHAVE and
        O_REF.BDREFCTA = (select first 1 BDREFCTA
                          from (select ONL.BDCODPLANOONLINE, ONL.BDCHAVE, REF_PAI.BDREFCTA, REF.BDCODPLAPADRAO,
                                       REF.BDCODTPHI, REF.BDCONTADEBPROV, REF.BDCONTACREDPROV, REF.BDCODHISTPROV,
                                       REF.BDCODCOMPHISTPROV, REF.BDCONTADEBPGTO, REF.BDCONTACREDPGTO,
                                       REF.BDCODHISTPGTO, REF.BDCODCOMPHISTPGTO, REF.BDCOPYTITULO, ONL.BDCHAVEVINC
                                from TCONF_CONTAS_ONLINE ONL
                                left outer join TCONF_CONTAS_ONLINE_REF REF_PAI on (ONL.BDCODPLANOONLINE = REF_PAI.BDCODPLANOONLINE and
                                      REF_PAI.BDCHAVE = coalesce(ONL.BDCHAVEVINC, ONL.BDCHAVE))
                                left outer join TCONF_CONTAS_ONLINE_REF REF on (ONL.BDCODPLANOONLINE = REF.BDCODPLANOONLINE and
                                      ONL.BDCHAVE = REF.BDCHAVE and
                                      REF_PAI.BDREFCTA = REF.BDREFCTA)
                                where ONL.BDCODPLANOONLINE = :PRCODPLANOONLINE and
                                      ONL.BDCLASSIFICACAO like '03.%')
                          where BDCODPLANOONLINE = C.BDCODPLANOONLINE and
                                BDCHAVE = C.BDCHAVE and
                                BDREFCTA <= CF.BDREFERENCIA
                          order by BDCODPLANOONLINE desc, BDCHAVE desc, BDREFCTA desc))
  left outer join TCOMPLEMENTO_HIST H on (H.BDCODCOMPHIST = O_REF.BDCODCOMPHISTPROV)
  left outer join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = C.BDCODNAT)
  left outer join PLANOS_TPLA PLAD on (PLAD.BDCODPLAPADRAO = O_REF.BDCODPLAPADRAO and
        PLAD.BDCODTPLA = O_REF.BDCONTADEBPROV)
  left outer join PLANOS_TPLA PLAC on (PLAC.BDCODPLAPADRAO = O_REF.BDCODPLAPADRAO and
        PLAC.BDCODTPLA = O_REF.BDCONTACREDPROV)
  where C.BDCODPLANOONLINE = :PRCODPLANOONLINE and
        C.BDCHAVEVINC is null -- Alt.: 18904 - Para não carregar as contas por rateio e evitar "multiple rows"...
        and
        NAT.BDCODNAT is not null;
  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', '9');

  /*Insere as contas que tem código de receita na tabela temporária de contas*/
  WSQL = 'INSERT INTO TCONTAS_ONLINE_TEMP (BDSESSAO, BDCHAVE, BDREFERENCIA, BDCONTACREDPROV, BDCONTADEBPROV, BDCLASSIFICACAO, BDCODITEMONLINE, BDCODPLAPADRAO, BDFORMULA, BDCLASS_TITULO, BDCHAVECONF, BDCODREC, BDCOMPLEMENTO, BDCODHIST, BDCODTPHI) ';
  WSQL = WSQL || 'SELECT ' || :PRSESSAO || ', O.BDCHAVE, CF.BDREFERENCIA, o_ref.BDCONTACREDPROV, o_ref.BDCONTADEBPROV, O.BDCLASSIFICACAO, CF.BDCODITEMONLINE, o_ref.BDCODPLAPADRAO, O.BDFORMULA, O.BDCLASSIFICACAO, O.BDCHAVE, CF.BDCODREC, H.BDCOMPLEMENTO, o_ref.BDCODTPHI, o_ref.BDCODHISTPROV ';
  WSQL = WSQL || 'FROM TCONF_CONTAS_ONLINE O ';
  WSQL = WSQL || 'JOIN ('||:WSQLCONTAS||') o_ref on (o_ref.BDCODPLANOONLINE = o.BDCODPLANOONLINE and o_ref.BDCHAVE = o.BDCHAVE) ';/* XXX */

  WSQL = WSQL || 'JOIN ( ';
  WSQL = WSQL || 'SELECT CM.BDCODITEMONLINE, CM.BDCODREC, ' || :PRCODPLANOONLINE || ' AS BDCODPLANOONLINE, ';
  WSQL = WSQL || 'CASE ';
                                     /* Entrada */
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  82 THEN ''ENTRETPIS'' ';
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  83 THEN ''ENTRETCOFINS'' ';
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  84 THEN ''ENTRETCS'' ';
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE = 163 THEN ''ENTRETIR'' ';
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE = 164 THEN ''ENTRETINSS'' ';
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE = 165 THEN ''ENTRETISS'' ';
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE = 313 THEN ''ENTRETAPOSESP15'' '; -- Contabilização INSS aposentadoria especial #123489 #128660 #101172 #100393 #DBS! Mesma regra INSS - Matheus Amaral - 09/03/2020
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE = 314 THEN ''ENTRETAPOSESP20'' '; -- Contabilização INSS aposentadoria especial
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE = 315 THEN ''ENTRETAPOSESP25'' '; -- Contabilização INSS aposentadoria especial
                                     /* Saída */
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  89 THEN ''SAIRETPIS'' ';
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  90 THEN ''SAIRETCOFINS'' ';
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  91 THEN ''SAIRETCS'' ';
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  92 THEN ''SAIRETIR'' ';
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  93 THEN ''SAIRETINSS'' ';
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  94 THEN ''SAIRETISS'' ';
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE = 304 THEN ''SAIRETAPOSESP15'' '; -- Contabilização INSS aposentadoria especial #123489 #128660 #101172 #100393 #DBS! Mesma regra INSS - Matheus Amaral - 09/03/2020
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE = 305 THEN ''SAIRETAPOSESP20'' '; -- Contabilização INSS aposentadoria especial
  WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE = 306 THEN ''SAIRETAPOSESP25'' '; -- Contabilização INSS aposentadoria especial
                                     /* Serviço */
  if (:PRTIPOLAN = 'SERE') then
  /*Emitido*/
  begin
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =   99 THEN ''SEREMIRETPIS'' ';
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  100 THEN ''SEREMIRETCOFINS'' ';
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  101 THEN ''SEREMIRETCS'' ';
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =   97 THEN ''SEREMIRETIRRF'' ';
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =   98 THEN ''SEREMIRET11INSS'' ';
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  102 THEN ''SEREMIRETISS'' ';
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  307 THEN ''SEREMTRETAPOSESP15'' '; -- Contabilização INSS aposentadoria especial #123489 #128660 #101172 #100393 #DBS! Mesma regra INSS - Matheus Amaral - 09/03/2020
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  308 THEN ''SEREMTRETAPOSESP20'' '; -- Contabilização INSS aposentadoria especial #123489 #128660 #101172 #100393 #DBS! Mesma regra INSS - Matheus Amaral - 09/03/2020
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  309 THEN ''SEREMTRETAPOSESP25'' '; -- Contabilização INSS aposentadoria especial #123489 #128660 #101172 #100393 #DBS! Mesma regra INSS - Matheus Amaral - 09/03/2020
  end
  else
  if (:PRTIPOLAN = 'SERR') then
  /*Recebido*/
  begin
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  107 THEN ''SERRECRETPIS'' ';
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  108 THEN ''SERRECCOFINS'' ';
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  109 THEN ''SERRECRETCS'' ';
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  105 THEN ''SERRECRETIRRF'' ';
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  106 THEN ''SERRECRET11INSS'' ';
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  110 THEN ''SERRECRETISS'' ';
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  310 THEN ''SERRECRETAPOSESP15'' '; -- Contabilização INSS aposentadoria especial #123489 #128660 #101172 #100393 #DBS! Mesma regra INSS - Matheus Amaral - 09/03/2020
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  311 THEN ''SERRECRETAPOSESP20'' '; -- Contabilização INSS aposentadoria especial #123489 #128660 #101172 #100393 #DBS! Mesma regra INSS - Matheus Amaral - 09/03/2020
    WSQL = WSQL || 'WHEN CM.BDCODITEMONLINE =  312 THEN ''SERRECRETAPOSESP25'' '; -- Contabilização INSS aposentadoria especial #123489 #128660 #101172 #100393 #DBS! Mesma regra INSS - Matheus Amaral - 09/03/2020
  end

  WSQL = WSQL || 'END AS BDFORMULA, CM.BDREFERENCIA ';
  WSQL = WSQL || 'FROM TMP_TCFOP_TMOV CM ';
  WSQL = WSQL || 'WHERE CM.BDSESSAO = ' || :PRSESSAO;
  WSQL = WSQL || 'AND CM.BDCODNAT IS NULL ';
  WSQL = WSQL || 'AND CM.BDCONDPGTO IS NULL ';
  WSQL = WSQL || 'AND cm.bdCODREC > 0 '; -- Alt.: #139462 - Apenas caso tenha alguma coisa no código de receita, caso contrário, insere os duas vezes(aqui e ali em baixo onde busca por código "0") e ficava o valor duplicado na contabilização...
  if (:PRTIPOLAN <> 'SAI') then
    /*NAS IMPORTAÇÕES DE SAÍDA, DEVE CONTABILIZAR COM A CONTA PRINCIPAL, QUANDO NÃO TEM CÓDIGO DE RECEITA*/
    WSQL = WSQL || 'AND (CM.BDCODREC IS NOT NULL) and (cm.bdcodrec <> 0) ';

  WSQL = WSQL || ') CF ON(cf.bdCODPLANOONLINE = o.bdCODPLANOONLINE AND cf.bdCODITEMONLINE = o.bdCODITEMONLINE and o_ref.BDREFCTA = (' || 'SELECT FIRST 1 bdrefcta FROM ('||:WSQLCONTAS||') WHERE bdcodplanoonline = o.bdCODPLANOONLINE AND bdchave = o.BDCHAVE AND ' || 'bdrefcta <= CF.BDREFERENCIA ORDER BY bdcodplanoonline DESC, bdchave DESC, bdrefcta DESC) AND ';
  if ((:PRTIPOLAN = 'ENT') or (:PRTIPOLAN = 'SERR')) then
    WSQL = WSQL || '((cf.bdCODREC = o.bdCODREC AND o_ref.BDCONTACREDPROV IS NOT NULL) OR '; -- Busca as contas pelo código de receita, caso não tenha busca pela formula as contas padrão...
  else
  if ((:PRTIPOLAN = 'SAI') or (:PRTIPOLAN = 'SERE') or (:PRTIPOLAN = 'REDZ')) then
    WSQL = WSQL || '((cf.bdCODREC = o.bdCODREC AND o_ref.BDCONTADEBPROV IS NOT NULL) OR '; -- Busca as contas pelo código de receita, caso não tenha busca pela formula as contas padrão...

  WSQL = WSQL || '(cf.bdFORMULA = o.bdFORMULA AND (NOT EXISTS(SELECT * ';
  WSQL = WSQL || 'FROM TCONF_CONTAS_ONLINE x ';
  WSQL = WSQL || 'WHERE x.bdCODPLANOONLINE = cf.bdCODPLANOONLINE ';
  WSQL = WSQL || 'AND x.bdCODITEMONLINE = cf.bdCODITEMONLINE ';
  if ((:PRTIPOLAN = 'ENT') or (:PRTIPOLAN = 'SERR')) then
    WSQL = WSQL || 'AND x.BDCONTACREDPROV IS NOT NULL ';
  else
  if ((:PRTIPOLAN = 'SAI') or (:PRTIPOLAN = 'SERE') or (:PRTIPOLAN = 'REDZ')) then
    WSQL = WSQL || 'AND x.BDCONTADEBPROV IS NOT NULL ';
  WSQL = WSQL || 'AND x.bdCODREC = cf.bdCODREC))) ) ) ';
  WSQL = WSQL || 'LEFT OUTER JOIN TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = o_ref.BDCODCOMPHISTPROV); ';

  execute statement WSQL;
  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', '10');

  -- Alt.: #171368 - Quando tem preparacao de conta nas receitas e nas contas titulo das retencoes, estava contabilizando duas vezes em cada retencao, aqui vai excluir as contas repetidas da titulo...
  DELETE FROM TCONTAS_ONLINE_TEMP C 
  WHERE C.BDSESSAO = :PRSESSAO
    AND C.BDCODITEMONLINE IN (:wCodItemPis,:wCodItemCof,:wCodItemCS,:wCodItemIr,:wCodItemInss,:wCodItemIss,:wCodItemFunRural)
    AND C.BDFORMULA NOT LIKE '%('||C.BDCODREC||')'
    AND EXISTS(SELECT X.*
               FROM TCONTAS_ONLINE_TEMP X
               WHERE X.BDCODITEMONLINE = C.BDCODITEMONLINE
                 AND X.BDCODREC = C.BDCODREC
                 AND X.BDFORMULA LIKE '%('||X.BDCODREC||')' );
  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', '11');

  if (:WTABLERAT <> '') then
  begin
    WSQL = 'INSERT INTO TCONTAS_ONLINE_TEMP(BDSESSAO, BDCHAVE, bdreferencia, BDCODTIPOCONTA, BDCODNAT, BDCLASSIFICACAO, BDCONTADEBPROV, BDCONTACREDPROV, ';
    WSQL = WSQL || 'BDCODITEMONLINE, BDCODPLAPADRAO, BDFORMULA, BDCLASS_TITULO, BDCHAVECONF, BDCLASSCODNAT, ';
    WSQL = WSQL || 'BDCOMPLEMENTO, BDCODHIST, BDCODTPHI, BDCONTARATEIO) ';
    WSQL = WSQL || 'SELECT ' || :PRSESSAO || ', C.BDCHAVE, RAT.bdreferencia, C.BDCODTIPOCONTA, C.BDCODNAT, C.BDCLASSIFICACAO, o_ref.BDCONTADEBPROV, o_ref.BDCONTACREDPROV, ';
    WSQL = WSQL || 'C.BDCODITEMONLINE, o_ref.BDCODPLAPADRAO, C.BDFORMULA, C.BDCLASSIFICACAO, C.BDCHAVE, NAT.BDCLASSIFICACAO, ';
    WSQL = WSQL || 'H.BDCOMPLEMENTO, o_ref.BDCODTPHI, o_ref.BDCODHISTPROV, ''TRUE'' ';
    WSQL = WSQL || 'FROM (';
    WSQL = WSQL || 'SELECT RAT.BDCODPLANOONLINE, RAT.BDCHAVEONLINE, ' || WFIELDREF || ' as bdreferencia ';
    WSQL = WSQL || 'FROM ' || :WTABLERAT || ' RAT ';
    WSQL = WSQL || 'LEFT OUTER JOIN ' || :WTABLEAUXDATA || ' data on (data.BDCODEMP = RAT.BDCODEMP AND data.BDCHAVE = RAT.BDCHAVE AND data.BDSESSAO = RAT.BDSESSAO) ';
    WSQL = WSQL || 'WHERE RAT.BDSESSAO = ' || :PRSESSAO || ' ';
    WSQL = WSQL || 'AND RAT.BDCODPLANOONLINE = ' || :PRCODPLANOONLINE || ' ';
    WSQL = WSQL || 'AND COALESCE(RAT.BDVALOR, 0) > 0 ';
    WSQL = WSQL || 'GROUP BY RAT.BDCODPLANOONLINE, RAT.BDCHAVEONLINE, ' || WFIELDREF;
    WSQL = WSQL || ') RAT ';
    WSQL = WSQL || 'JOIN TCONF_CONTAS_ONLINE C ON (C.BDCODPLANOONLINE = RAT.BDCODPLANOONLINE AND C.BDCHAVE = RAT.BDCHAVEONLINE) ';
    WSQL = WSQL || 'LEFT OUTER JOIN ('||:WSQLCONTAS||') o_ref on (o_ref.BDCODPLANOONLINE = C.BDCODPLANOONLINE and o_ref.BDCHAVE = C.BDCHAVE and o_ref.BDREFCTA = (';
    WSQL = WSQL || 'SELECT FIRST 1 bdrefcta FROM ('||:WSQLCONTAS||') WHERE bdcodplanoonline = C.bdCODPLANOONLINE AND bdchave = C.BDCHAVE AND ';
    WSQL = WSQL || 'bdrefcta <= RAT.bdreferencia ORDER BY bdcodplanoonline DESC, bdchave DESC, bdrefcta DESC)) ';
    WSQL = WSQL || 'LEFT OUTER JOIN TCOMPLEMENTO_HIST H ON (H.BDCODCOMPHIST = o_ref.BDCODCOMPHISTPROV) ';
    WSQL = WSQL || 'LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = C.BDCODNAT) ';
    execute statement WSQL;
  end
  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', '12');

  /*Insere as contas que não tem código de receita(Se não tiveram conta de débito para provisão já são inconsistentes)*/
  insert into TCONTAS_ONLINE_TEMP (BDSESSAO, BDCHAVE, BDREFERENCIA, BDCONTACREDPROV, BDCONTADEBPROV, BDCLASSIFICACAO,
                                   BDCODITEMONLINE, BDCODPLAPADRAO, BDFORMULA, BDCLASS_TITULO, BDCHAVECONF, BDCODREC,
                                   BDCOMPLEMENTO, BDCODHIST, BDCODTPHI)
  select :PRSESSAO, O.BDCHAVE, CF.BDREFERENCIA, O_REF.BDCONTACREDPROV, O_REF.BDCONTADEBPROV, O.BDCLASSIFICACAO,
         CF.BDCODITEMONLINE, O_REF.BDCODPLAPADRAO, O.BDFORMULA, O.BDCLASSIFICACAO, O.BDCHAVE, CF.BDCODREC,
         H.BDCOMPLEMENTO, O_REF.BDCODTPHI, O_REF.BDCODHISTPROV
  from TCONF_CONTAS_ONLINE O join(select CM.BDCODITEMONLINE, CM.BDCODREC, CM.BDREFERENCIA
                                  from TMP_TCFOP_TMOV CM
                                  where CM.BDSESSAO = :PRSESSAO and
                                        CM.BDCODNAT is null and
                                        CM.BDCONDPGTO is null and
                                        CM.BDCODREC = 0 /*0 é o valor default do campo na tabela de retenções*/
  ) CF on (CF.BDCODITEMONLINE = O.BDCODITEMONLINE)
  left outer join(select ONL.BDCODPLANOONLINE, ONL.BDCHAVE, REF_PAI.BDREFCTA, REF.BDCODPLAPADRAO, REF.BDCODTPHI,
                         REF.BDCONTADEBPROV, REF.BDCONTACREDPROV, REF.BDCODHISTPROV, REF.BDCODCOMPHISTPROV,
                         REF.BDCONTADEBPGTO, REF.BDCONTACREDPGTO, REF.BDCODHISTPGTO, REF.BDCODCOMPHISTPGTO,
                         REF.BDCOPYTITULO, ONL.BDCHAVEVINC
                  from TCONF_CONTAS_ONLINE ONL
                  left outer join TCONF_CONTAS_ONLINE_REF REF_PAI on (ONL.BDCODPLANOONLINE = REF_PAI.BDCODPLANOONLINE and
                        REF_PAI.BDCHAVE = coalesce(ONL.BDCHAVEVINC, ONL.BDCHAVE))
                  left outer join TCONF_CONTAS_ONLINE_REF REF on (ONL.BDCODPLANOONLINE = REF.BDCODPLANOONLINE and
                        ONL.BDCHAVE = REF.BDCHAVE and
                        REF_PAI.BDREFCTA = REF.BDREFCTA)
                  where ONL.BDCODPLANOONLINE = :PRCODPLANOONLINE and
                        ONL.BDCLASSIFICACAO like '03.%') O_REF on (O_REF.BDCODPLANOONLINE = O.BDCODPLANOONLINE and
        O_REF.BDCHAVE = O.BDCHAVE and
        O_REF.BDREFCTA = (select first 1 BDREFCTA
                          from (select ONL.BDCODPLANOONLINE, ONL.BDCHAVE, REF_PAI.BDREFCTA, REF.BDCODPLAPADRAO,
                                       REF.BDCODTPHI, REF.BDCONTADEBPROV, REF.BDCONTACREDPROV, REF.BDCODHISTPROV,
                                       REF.BDCODCOMPHISTPROV, REF.BDCONTADEBPGTO, REF.BDCONTACREDPGTO,
                                       REF.BDCODHISTPGTO, REF.BDCODCOMPHISTPGTO, REF.BDCOPYTITULO, ONL.BDCHAVEVINC
                                from TCONF_CONTAS_ONLINE ONL
                                left outer join TCONF_CONTAS_ONLINE_REF REF_PAI on (ONL.BDCODPLANOONLINE = REF_PAI.BDCODPLANOONLINE and
                                      REF_PAI.BDCHAVE = coalesce(ONL.BDCHAVEVINC, ONL.BDCHAVE))
                                left outer join TCONF_CONTAS_ONLINE_REF REF on (ONL.BDCODPLANOONLINE = REF.BDCODPLANOONLINE and
                                      ONL.BDCHAVE = REF.BDCHAVE and
                                      REF_PAI.BDREFCTA = REF.BDREFCTA)
                                where ONL.BDCODPLANOONLINE = :PRCODPLANOONLINE and
                                      ONL.BDCLASSIFICACAO like '03.%')
                          where BDCODPLANOONLINE = O.BDCODPLANOONLINE and
                                BDCHAVE = O.BDCHAVE and
                                BDREFCTA <= CF.BDREFERENCIA
                          order by BDCODPLANOONLINE desc, BDCHAVE desc, BDREFCTA desc))
  left outer join TCOMPLEMENTO_HIST H on (H.BDCODCOMPHIST = O_REF.BDCODCOMPHISTPROV)
  where O.BDCODPLANOONLINE = :PRCODPLANOONLINE and
        O.BDCODREC is null;
  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', '13');

  /*Pega as chaves que estão sem conta de cred ou deb da provisão e procura nos outros niveis da cfop
  EX: 5.305.001, 5.305.000, 5.300.000, 5.000.000*/
  WACHOUCONTA = 'FALSE';
  WCONTADEBPROV = null;
  WCONTACREDPROV = null;
  WCHAVECONF = null;
  WCLASSIFIBUSCA = null;

  --    //elizeu - 29-10-18 - Criado parametro pra não buscar as contas da classificação titulo - Importação de NFe (Contabilização) #92071
  WSQL = 'SELECT C.BDCLASSCODNAT, C.BDCODTIPOCONTA, C.BDCODITEMONLINE, C.BDCHAVE, C.BDREFERENCIA ';
  WSQL = WSQL || '      FROM TCONTAS_ONLINE_TEMP C ';
  WSQL = WSQL || '      WHERE C.BDSESSAO = ' || :PRSESSAO;
  WSQL = WSQL || '      AND ((C.BDCONTADEBPROV IS NULL) OR (C.BDCONTACREDPROV IS NULL)) ';
  WSQL = WSQL || '      AND C.BDCODNAT IS NOT NULL ';
  WSQL = WSQL || '      AND C.BDCODTIPOCONTA IS NOT NULL ';
  WSQL = WSQL || '      and c.bdcoditemonline not in(219,220,221,225,226,227,228,229,230,231,232,233,298,299,300,';
  WSQL = WSQL || '243,244,245'; -- Alt.: #132080 - Contas de desconto deve pegar apenas das CFOPs e nao pesquisar das titulos.
  if ((:PRENQFED in (1, 2)) and
      (:PRTIPOLAN = 'SAI')) then
  begin
    WSQL = WSQL || ',113,119,172';
  end

  WSQL = WSQL || ')';

  for execute statement WSQL
          into :WCLASS, :WTIPOCONTA, :WCODITEMONLINE, :WCHAVE, :WREFERENCIA
  do
  begin
    WACHOUCONTA = 'FALSE';
    while (:WACHOUCONTA = 'FALSE') do
    begin
      if (char_length(:WCLASS) = 13) then
        WCLASS = substring(:WCLASS from 1 for (char_length(:WCLASS) - 4));/*Ex: CFOP 5.300.303.001 fica 5.300.303*/
      else
      if (char_length(:WCLASS) = 9) then
        WCLASS = substring(:WCLASS from 1 for (char_length(:WCLASS) - 4));/*Ex: CFOP 5.300.303 fica 5.300*/
      else
      if (char_length(:WCLASS) = 5) then
        WCLASS = substring(:WCLASS from 1 for (char_length(:WCLASS) - 4));/*Ex: CFOP 5.300 fica 5*/
      else
        WACHOUCONTA = 'TRUE';

      if (:WACHOUCONTA = 'FALSE') then
      begin                                                
--  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', 'WCLASS:'||:WCLASS);
--  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', 'WTIPOCONTA:'|| :WTIPOCONTA);
--  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', 'WCODITEMONLINE:'|| :WCODITEMONLINE);
--  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', 'PRCODPLANOONLINE:'|| :PRCODPLANOONLINE);
        select first 1 C_REF.BDCONTACREDPROV, C_REF.BDCONTADEBPROV, C.BDCHAVE, C.BDCLASSIFICACAO, H.BDCOMPLEMENTO,
               C_REF.BDCODTPHI, C_REF.BDCODHISTPROV
        from (select SUB.BDCODPLANOONLINE, SUB.BDCHAVE, SUB.BDCLASSIFICACAO
              from TCONF_CONTAS_ONLINE SUB
              left outer join VEF_BASE_TNATOP NT on (NT.BDCLASSIFICACAO = :WCLASS)
              where SUB.BDCODTIPOCONTA = :WTIPOCONTA and
                    SUB.BDCODNAT = NT.BDCODNAT and
                    SUB.BDCODITEMONLINE = :WCODITEMONLINE and
                    SUB.BDCODPLANOONLINE = :PRCODPLANOONLINE and
                    SUB.BDCHAVEVINC is null -- Para não buscar as contas de centro de custo
                    ) C
        left outer join(select REF.BDCODPLANOONLINE, REF.BDCHAVE, REF.BDREFCTA, REF.BDCODPLAPADRAO, REF.BDCODTPHI,
                               REF.BDCONTADEBPROV, REF.BDCONTACREDPROV, REF.BDCODHISTPROV, REF.BDCODCOMPHISTPROV,
                               REF.BDCONTADEBPGTO, REF.BDCONTACREDPGTO, REF.BDCODHISTPGTO, REF.BDCODCOMPHISTPGTO,
                               REF.BDCOPYTITULO
                        from TCONF_CONTAS_ONLINE_REF REF
                                ) C_REF on (C_REF.BDCODPLANOONLINE = C.BDCODPLANOONLINE and
              C_REF.BDCHAVE = C.BDCHAVE and
              C_REF.BDREFCTA = (select first 1 (BDREFCTA)
                                from (select REF.BDCODPLANOONLINE, REF.BDCHAVE, REF.BDREFCTA, REF.BDCODPLAPADRAO,
                                             REF.BDCODTPHI, REF.BDCONTADEBPROV, REF.BDCONTACREDPROV, REF.BDCODHISTPROV,
                                             REF.BDCODCOMPHISTPROV, REF.BDCONTADEBPGTO, REF.BDCONTACREDPGTO,
                                             REF.BDCODHISTPGTO, REF.BDCODCOMPHISTPGTO, REF.BDCOPYTITULO
                                      from TCONF_CONTAS_ONLINE_REF REF
                               )
                                where BDCODPLANOONLINE = C.BDCODPLANOONLINE and
                                      BDCHAVE = C.BDCHAVE and
                                      BDREFCTA <= :WREFERENCIA
                                order by BDCODPLANOONLINE desc,BDCHAVE desc,BDREFCTA desc
                                ))
        left outer join TCOMPLEMENTO_HIST H on (H.BDCODCOMPHIST = C_REF.BDCODCOMPHISTPROV)
        into :WCONTACREDPROV, :WCONTADEBPROV, :WCHAVECONF, :WCLASSIFIBUSCA, :WCOMPLEMENTO, :WCODHIST, :WCODTPHI;
      end

      if ((((:WCONTACREDPROV is null and
          not(:WCODITEMONLINE in (284, 285, 286))) or (:WCONTADEBPROV is null))) and
          (:WACHOUCONTA <> 'TRUE')) then
        WACHOUCONTA = 'FALSE';
      else
      begin
        if (((:WCONTADEBPROV is not null) and
            (:WCONTACREDPROV is not null)) or ((:WCODITEMONLINE in (290, 291, 292)) and
            (:WCONTADEBPROV is not null))) then
          update TCONTAS_ONLINE_TEMP
          set BDCONTADEBPROV = :WCONTADEBPROV,
              BDCONTACREDPROV = :WCONTACREDPROV,
              BDCHAVECONF = :WCHAVECONF,
              BDCLASS_TITULO = :WCLASSIFIBUSCA,
              BDCOMPLEMENTO = :WCOMPLEMENTO,
              BDCODHIST = :WCODHIST,
              BDCODTPHI = :WCODTPHI
          where BDSESSAO = :PRSESSAO and
                BDCHAVE = :WCHAVE and
                BDREFERENCIA = :WREFERENCIA;

        WACHOUCONTA = 'TRUE';
      end
    end
    WCHAVE = 0;
  end
  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', '14');

  WCODITEMONLINE = null;
  WCHAVE = null;
  for select CT.BDCHAVE, CT.BDCODITEMONLINE, CT.BDREFERENCIA
      from TCONTAS_ONLINE_TEMP CT
      join TMP_TCFOP_TMOV O on (O.BDSESSAO = :PRSESSAO and
            O.BDCODITEMONLINE = CT.BDCODITEMONLINE and
            O.BDCODREC is not null and
            CT.BDREFERENCIA = O.BDREFERENCIA)
      where CT.BDSESSAO = :PRSESSAO and
            CT.BDCONTADEBPROV is null
      into :WCHAVE, :WCODITEMONLINE, :WREFERENCIA
  do
  begin
    WCHAVECONF = null;
    WCONTADEBPROV = null;
    WCLASSIFIBUSCA = null;
    select FIRST 1 CO_REF.BDCONTADEBPROV, CO.BDCLASSIFICACAO, CO.BDCHAVE, H.BDCOMPLEMENTO, CO_REF.BDCODTPHI,
           CO_REF.BDCODHISTPROV
    from TCONF_CONTAS_ONLINE CO
    left outer join(select ONL.BDCODPLANOONLINE, ONL.BDCHAVE, REF_PAI.BDREFCTA, REF.BDCODPLAPADRAO, REF.BDCODTPHI,
                           REF.BDCONTADEBPROV, REF.BDCONTACREDPROV, REF.BDCODHISTPROV, REF.BDCODCOMPHISTPROV,
                           REF.BDCONTADEBPGTO, REF.BDCONTACREDPGTO, REF.BDCODHISTPGTO, REF.BDCODCOMPHISTPGTO,
                           REF.BDCOPYTITULO, ONL.BDCHAVEVINC
                    from TCONF_CONTAS_ONLINE ONL
                    left outer join TCONF_CONTAS_ONLINE_REF REF_PAI on (ONL.BDCODPLANOONLINE = REF_PAI.BDCODPLANOONLINE and
                          REF_PAI.BDCHAVE = coalesce(ONL.BDCHAVEVINC, ONL.BDCHAVE))
                    left outer join TCONF_CONTAS_ONLINE_REF REF on (ONL.BDCODPLANOONLINE = REF.BDCODPLANOONLINE and
                          ONL.BDCHAVE = REF.BDCHAVE and
                          REF_PAI.BDREFCTA = REF.BDREFCTA)
                    where ONL.BDCODPLANOONLINE = :PRCODPLANOONLINE and
                          ONL.BDCLASSIFICACAO like '03.%') CO_REF on (CO_REF.BDCODPLANOONLINE = CO.BDCODPLANOONLINE and
          CO_REF.BDCHAVE = CO.BDCHAVE and
          CO_REF.BDREFCTA = (select first 1 BDREFCTA
                             from (select ONL.BDCODPLANOONLINE, ONL.BDCHAVE, REF_PAI.BDREFCTA, REF.BDCODPLAPADRAO,
                                          REF.BDCODTPHI, REF.BDCONTADEBPROV, REF.BDCONTACREDPROV, REF.BDCODHISTPROV,
                                          REF.BDCODCOMPHISTPROV, REF.BDCONTADEBPGTO, REF.BDCONTACREDPGTO,
                                          REF.BDCODHISTPGTO, REF.BDCODCOMPHISTPGTO, REF.BDCOPYTITULO, ONL.BDCHAVEVINC
                                   from TCONF_CONTAS_ONLINE ONL
                                   left outer join TCONF_CONTAS_ONLINE_REF REF_PAI on (ONL.BDCODPLANOONLINE = REF_PAI.BDCODPLANOONLINE and
                                         REF_PAI.BDCHAVE = coalesce(ONL.BDCHAVEVINC, ONL.BDCHAVE))
                                   left outer join TCONF_CONTAS_ONLINE_REF REF on (ONL.BDCODPLANOONLINE = REF.BDCODPLANOONLINE and
                                         ONL.BDCHAVE = REF.BDCHAVE and
                                         REF_PAI.BDREFCTA = REF.BDREFCTA)
                                   where ONL.BDCODPLANOONLINE = :PRCODPLANOONLINE and
                                         ONL.BDCLASSIFICACAO like '03.%')
                             where BDCODPLANOONLINE = CO.BDCODPLANOONLINE and
                                   BDCHAVE = CO.BDCHAVE and
                                   BDREFCTA <= :WREFERENCIA
                             order by BDCODPLANOONLINE desc, BDCHAVE desc, BDREFCTA desc))
    left outer join TCOMPLEMENTO_HIST H on (H.BDCODCOMPHIST = CO_REF.BDCODCOMPHISTPROV)
    where CO.BDCODITEMONLINE = :WCODITEMONLINE and
          CO.BDCODPLANOONLINE = :PRCODPLANOONLINE and
          CO.BDCODREC is null
    into :WCONTADEBPROV, :WCLASSIFIBUSCA, :WCHAVECONF, :WCOMPLEMENTO, :WCODHIST, :WCODTPHI;

    if (:WCONTADEBPROV is not null) then
      update TCONTAS_ONLINE_TEMP
      set BDCONTADEBPROV = :WCONTADEBPROV,
          BDCHAVECONF = :WCHAVECONF,
          BDCLASS_TITULO = :WCLASSIFIBUSCA,
          BDCOMPLEMENTO = :WCOMPLEMENTO,
          BDCODHIST = :WCODHIST,
          BDCODTPHI = :WCODTPHI
      where BDSESSAO = :PRSESSAO and
            BDCHAVE = :WCHAVE and
            BDREFERENCIA = :WREFERENCIA;

    WCODITEMONLINE = null;
    WCHAVE = null;
  end
  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', '15');

  if (:WTIPOINTDESCONTO = 0) then
  /*Nota a nota*/
  begin
      /*-----------------------CONTA DESCONTO-----------------------------*/
      /*Busca a conta do desconto, caso tenha desconto em algum lançamento*/
    WCODITEMONLINE = null;
    WCODITEMONLINE = case
                       when (:PRTIPOLAN = 'SAI') then 88 /*Desconto de saída*/
                       when (:PRTIPOLAN = 'ENT') then 81 /*Desconto de entrada*/
                       when (:PRTIPOLAN = 'SERE') then 96 /*Desconto de serviços emitidos*/
                       when (:PRTIPOLAN = 'SERR') then 104 /*Desconto de recebidos*/
                       when (:PRTIPOLAN = 'REDZ') then 207 /*Desconto de redução Z*/
                     end;

    if (:WCODITEMONLINE > 0) then
    begin
      WSQL = 'INSERT INTO TCONTAS_ONLINE_TEMP(bdsessao, bdchave, bdreferencia, bdcodtipoconta, bdcodnat, bdclassificacao, bdcontadebprov, bdcontacredprov, bdcoditemonline, bdcodplapadrao, BDFORMULA, BDCLASS_TITULO, BDCHAVECONF, BDCLASSCODNAT, BDCOMPLEMENTO, BDCODHIST, BDCODTPHI) ';
      WSQL = WSQL || 'SELECT ' || :PRSESSAO || ', C.BDCHAVE, mov.bdreferencia, C.BDCODTIPOCONTA, C.BDCODNAT, C.BDCLASSIFICACAO, o_ref.BDCONTADEBPROV, o_ref.BDCONTACREDPROV, C.BDCODITEMONLINE, o_ref.BDCODPLAPADRAO, C.BDFORMULA, ';
      WSQL = WSQL || 'C.BDCLASSIFICACAO, C.BDCHAVE, NULL BDCLASSCODNAT, H.BDCOMPLEMENTO, o_ref.BDCODTPHI, o_ref.BDCODHISTPROV ';
      WSQL = WSQL || 'FROM TCONF_CONTAS_ONLINE C ';
      WSQL = WSQL || 'LEFT OUTER JOIN (SELECT ' || WFIELDREF || ' as bdreferencia from ' || WTABLEAUXDATA || ' data where data.bdsessao = ' || PRSESSAO || ' group by ' || WFIELDREF || ') mov on (1=1)';
      WSQL = WSQL || 'LEFT OUTER JOIN ('||:WSQLCONTAS||') o_ref on (o_ref.BDCODPLANOONLINE = C.BDCODPLANOONLINE and o_ref.BDCHAVE = C.BDCHAVE and o_ref.BDREFCTA = (';
      WSQL = WSQL || 'SELECT FIRST 1 bdrefcta FROM ('||:WSQLCONTAS||') WHERE bdcodplanoonline = C.bdCODPLANOONLINE AND bdchave = C.BDCHAVE AND ';
      WSQL = WSQL || 'bdrefcta <= mov.bdreferencia ORDER BY bdcodplanoonline DESC, bdchave DESC, bdrefcta DESC)) ';
      WSQL = WSQL || 'LEFT OUTER JOIN TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = o_ref.BDCODCOMPHISTPROV) ';
      WSQL = WSQL || 'WHERE C.BDCODPLANOONLINE = ' || :PRCODPLANOONLINE;
      WSQL = WSQL || ' AND  C.BDCODITEMONLINE = ' || :WCODITEMONLINE;
      WSQL = WSQL || ' AND  C.BDCHAVEVINC IS NULL ';
      if ((:PRTIPOLAN = 'ENT') or (:PRTIPOLAN = 'SERR')) then
        WSQL = WSQL || '  AND o_ref.BDCONTACREDPROV IS NOT NULL ';
      else
      if ((:PRTIPOLAN = 'SAI') or (:PRTIPOLAN = 'SERE') or (:PRTIPOLAN = 'REDZ')) then
        WSQL = WSQL || '  AND o_ref.BDCONTADEBPROV IS NOT NULL ';

      execute statement WSQL;
    end
  end
  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', '16');

  IF (PRFORMATRIB IS NULL) THEN
    PRFORMATRIB = 0;
  execute procedure SP_INSERT_INCONSISTENCIAS_CONTA(:PRSESSAO, :PRCODPLANOONLINE, :PRENQFED, :PRCODCONFIRLP, :PRTIPOLAN, :PRFORMATRIB);
  /**/ execute procedure SP_GERALOG_TEMP('SP_VALIDA_CONTA_ONLINE_TEMP', '17');

  when any do
  begin
    in autonomous transaction do
      execute procedure LANCA_EXCEPTION('SP_VALIDA_CONTA_ONLINE_TEMP', sqlcode, gdscode);
    exception;
  end
end^


CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMOVENTSAIINFCOM (
    PRSESSAO INTEGER,
    PRSESSAOTER INTEGER,
    PRTIPOMOV VARCHAR(3))
AS
BEGIN
  PRTIPOMOV = UPPER(:PRTIPOMOV);

  IF (:PRTIPOMOV = 'SAI') THEN
    BEGIN
      /*120 - Informação complementar não informada.*/
      INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEMIC, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
      SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEMIC, S.BDSESSAO, 120 BDCODINCONSISTENCIA, 4 BDTIPOINCON
      FROM TMP_VEF_EMP_TMOVSAIINFCOM_TEMP S
      WHERE S.BDSESSAO = :PRSESSAO
      AND ((S.BDALTORDEMINFCOM IS NULL) OR (S.BDALTORDEMINFCOM = 0))
      GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDORDEMIC, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;

      /*120 - Informação complementar não informada. | D500*/
      INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEMIC, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
      SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEMINFCOM, S.BDSESSAO, 120 BDCODINCONSISTENCIA, 24 BDTIPOINCON
      FROM TMP_VEF_EMP_TD500SAI_TEMP S
      WHERE S.BDSESSAO = :PRSESSAO
      AND (((S.BDALTORDEMINFCOM IS NULL) OR (S.BDALTORDEMINFCOM = 0)) AND (S.BDCODINFCOM <> ''))
      GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDORDEMINFCOM, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;

      /*******************************************Validaçao C113*******************************************/
      /*19 - Chave NFe inválida*/
      INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEMIC, BDORDEMDOCFREF, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
      SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEMIC, S.BDORDEMDOCFREF, S.BDSESSAO, S.BDCODINCONSISTENCIA, S.BDTIPOINCON
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEMIC, S.BDORDEMDOCFREF, S.BDSESSAO, 19 BDCODINCONSISTENCIA, 6 BDTIPOINCON,
                  (SELECT BDISVALID FROM SP_VALIDACHAVE_NFE_CTE(S.BDCHAVENFE)) BDISVALID
            FROM TMP_VEF_EMP_TMOVSAIDOCFREF_TEMP S
            WHERE S.BDSESSAO = :PRSESSAO
            AND S.BDCODDOCFIS IN(30, 31)
           ) S
      WHERE S.BDISVALID = 'FALSE';

      /*12 - Participante não cadastrado ou inconsistente*/
      INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEMIC, BDORDEMDOCFREF, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
      SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEMIC, S.BDORDEMDOCFREF, S.BDSESSAO, 12 BDCODINCONSISTENCIA, 6 BDTIPOINCON
      FROM TMP_VEF_EMP_TMOVSAIDOCFREF_TEMP S
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOC ON (DOC.BDCODDOCFIS = S.BDCODDOCFIS)
      WHERE S.BDSESSAO = :PRSESSAO
      AND (DOC.BDDOCFIS <> '65') -- #128861 - Modelo 65 não precisa de participante
      AND ((S.BDCODTER IS NULL) OR (S.BDCODTER = 0))
      AND (Coalesce(S.BDNUMDOC,0) <> 0)
      GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDORDEMIC, S.BDORDEMDOCFREF, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;

      INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
      SELECT S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 12 BDCODINCONSISTENCIA, 6 BDTIPOINCON
      FROM TMP_VEF_EMP_TMOVSAIDOCFREF_TEMP S
      JOIN VEF_INCON_TTERCEIROS T ON(T.BDSESSAO = :PRSESSAOTER AND T.BDCODTER = S.BDCODTER)
      WHERE S.BDSESSAO = :PRSESSAO
      AND (S.BDCODTER > 0)
      GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;
      /****************************************************************************************************/


      /*******************************************Validaçao C115*******************************************/
      /*121 - Participante de coleta não informado ou inconsistente.*/
      INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEMIC, BDORDEMLOCCOL, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
      SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEMIC, S.BDORDEMLOCCOL, S.BDSESSAO, 121 BDCODINCONSISTENCIA, 5 BDTIPOINCON
      FROM TMP_VEF_EMP_TMOVSAILOCCOL_TEMP S
      WHERE S.BDSESSAO = :PRSESSAO
      AND ((S.BDCODTERCOLETA IS NULL) OR (S.BDCODTERCOLETA = 0))
      GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDORDEMIC, S.BDORDEMLOCCOL, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;

      INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEMIC, BDORDEMLOCCOL, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
      SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEMIC, S.BDORDEMLOCCOL, S.BDSESSAO, 121 BDCODINCONSISTENCIA, 5 BDTIPOINCON
      FROM TMP_VEF_EMP_TMOVSAILOCCOL_TEMP S
      JOIN VEF_INCON_TTERCEIROS T ON(T.BDSESSAO = :PRSESSAOTER AND T.BDCODTER = S.BDCODTERCOLETA)
      WHERE S.BDSESSAO = :PRSESSAO
      AND (S.BDCODTERCOLETA > 0)
      GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDORDEMIC, S.BDORDEMLOCCOL, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;

      /*122 - Participante de entrega não informado ou inconsistente.*/
      INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEMIC, BDORDEMLOCCOL, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
      SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEMIC, S.BDORDEMLOCCOL, S.BDSESSAO, 122 BDCODINCONSISTENCIA, 5 BDTIPOINCON
      FROM TMP_VEF_EMP_TMOVSAILOCCOL_TEMP S
      WHERE S.BDSESSAO = :PRSESSAO
      AND ((S.BDCODTERENTREGA IS NULL) OR (S.BDCODTERENTREGA = 0));

      INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEMIC, BDORDEMLOCCOL, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
      SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEMIC, S.BDORDEMLOCCOL, S.BDSESSAO, 121 BDCODINCONSISTENCIA, 5 BDTIPOINCON
      FROM TMP_VEF_EMP_TMOVSAILOCCOL_TEMP S
      JOIN VEF_INCON_TTERCEIROS T ON(T.BDSESSAO = :PRSESSAOTER AND T.BDCODTER = S.BDCODTERENTREGA)
      WHERE S.BDSESSAO = :PRSESSAO
      AND (S.BDCODTERENTREGA > 0)
      GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDORDEMIC, S.BDORDEMLOCCOL, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;
    END
END^

COMMENT ON PARAMETER SP_ATUALIZAR_TMOVENTSAIINFCOM.PRTIPOMOV IS 'ENT/SAI'^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_D411_D420 (
    PRSESSAO INTEGER)
AS
BEGIN

  /*cidade inválida*/
  INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCODCID)
  SELECT D.BDCODEMP, D.BDCHAVE, D.BDSESSAO, 7 BDCODINCONSISTENCIA, 22 BDTIPOINCON, D.bdcodcid
  FROM TMP_VEF_EMP_TD420SAI_TEMP D
    LEFT JOIN tcidade CID ON D.bdcodcid = CID.bdcodcid
  WHERE D.BDSESSAO = :PRSESSAO
    AND CID.bdcodcid IS NULL;

  /*documento cancelado inválido*/
  INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDNUMDOC)
  SELECT DISTINCT D.BDCODEMP, D.BDCHAVE, D.BDSESSAO, 199 BDCODINCONSISTENCIA, 21 BDTIPOINCON, D.bdnumdoc
  FROM TMP_VEF_EMP_TD411SAI_TEMP D
    LEFT JOIN tmp_vef_emp_tmovsai_TEMP SAI ON D.bdchave = SAI.bdchave and D.bdSESSAO = SAI.bdSESSAO
  WHERE D.BDSESSAO = :PRSESSAO
    AND ((D.bdNUMDOC < SAI.bdnumdocini) OR (D.bdNUMDOC > SAI.bdnumdocfim));
END
^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_C160 (
    PRSESSAO INTEGER,
    PRSESSAOTER INTEGER)
AS
BEGIN

  /*12 - Participante não cadastrado ou inconsistente*/
  INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 12 BDCODINCONSISTENCIA, 7 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSAIVLTRAN_TEMP S
  JOIN VEF_INCON_TTERCEIROS T ON(T.BDSESSAO = :PRSESSAOTER AND T.BDCODTER = S.BDCODTER)
  WHERE S.BDSESSAO = :PRSESSAO
  AND (S.BDCODTER > 0)
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;  

END
^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_C195_D195 (
    PRSESSAO INTEGER,
    PRSESSAOPRO INTEGER,
    PRTIPOLAN CHAR(3))
AS
BEGIN
  PRTIPOLAN = UPPER(:PRTIPOLAN);

  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      /*********************************************VALIDAÇÃO DO C190*********************************************/
      /*56 - Código de CST de ICMS não cadastrado*/
      INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
      SELECT C.BDCODEMP, C.BDCHAVE, C.BDORDEM, C.BDCODIGO, C.BDSESSAO, 56 BDCODINCONSISTENCIA, 15 BDTIPOINCON
      FROM TMP_VEF_EMP_TC190SAI_TEMP C
      LEFT OUTER JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = C.BDCODCSTICMS)
      WHERE C.BDSESSAO = :PRSESSAO
      AND CST.BDCODCSTICMS IS NULL;
      /***********************************************************************************************************/    
    
      /*********************************************VALIDAÇÃO DO C195*********************************************/
      /*123 - Observação não informada ou inconsistente.*/
      INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEMOBS, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
      SELECT C.BDCODEMP, C.BDCHAVE, C.BDORDEMOBS, C.BDSESSAO, 123 BDCODINCONSISTENCIA, 8 BDTIPOINCON
      FROM TMP_VEF_EMP_TC195SAI_TEMP C
      WHERE C.BDSESSAO = :PRSESSAO
      AND ((C.BDALTCODOBS IS NULL) OR (C.BDALTCODOBS = 0));

      /*********************************************VALIDAÇÃO DO C197*********************************************/
      /*Se o produto for inconsistente, torna o lançamento inconsistente tambem*/
      INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordemobs, bdordemoutobr, bdsessao, bdcodinconsistencia, BDTIPOINCON)
      SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEMOBS, S.BDORDEMOUTOBR, S.BDSESSAO, 76 BDCODINCONSISTENCIA, 9 BDTIPOINCON
      FROM TMP_VEF_EMP_TC197SAI_TEMP S
      LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :PRSESSAOPRO AND PRO.BDCODEMP = S.BDCODEMP AND PRO.BDCODPROD = S.BDALTCODPROD)
      WHERE S.BDSESSAO = :PRSESSAO
      AND S.BDALTCODPROD IS NOT NULL
      AND PRO.BDCODINCONSISTENCIA IS NOT NULL
      GROUP BY BDCODEMP, BDCHAVE, BDORDEMOBS, BDORDEMOUTOBR, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;
      /***********************************************************************************************************/

      /*********************************************VALIDAÇÃO DO D195*********************************************/
      /*123 - Observação não informada ou inconsistente.*/
      INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEMOBS, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
      SELECT C.BDCODEMP, C.BDCHAVE, C.BDORDEMOBS, C.BDSESSAO, 123 BDCODINCONSISTENCIA, 10 BDTIPOINCON
      FROM TMP_VEF_EMP_TD195SAI_TEMP C
      WHERE C.BDSESSAO = :PRSESSAO
      AND ((C.BDALTCODOBS IS NULL) OR (C.BDALTCODOBS = 0));
      
      /*********************************************VALIDAÇÃO DO D197*********************************************/
      /*Se o produto for inconsistente, torna o lançamento inconsistente tambem*/
      INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordemobs, bdordemoutobr, bdsessao, bdcodinconsistencia, BDTIPOINCON)
      SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEMOBS, S.BDORDEMOUTOBR, S.BDSESSAO, 76 BDCODINCONSISTENCIA, 11 BDTIPOINCON
      FROM TMP_VEF_EMP_TD197SAI_TEMP S
      LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :PRSESSAOPRO AND PRO.BDCODEMP = S.BDCODEMP AND PRO.BDCODPROD = S.BDALTCODPROD)
      WHERE S.BDSESSAO = :PRSESSAO
      AND ((S.BDALTCODPROD IS NOT NULL) AND (S.BDALTCODPROD > 0))
      AND PRO.BDCODINCONSISTENCIA IS NOT NULL
      GROUP BY BDCODEMP, BDCHAVE, BDORDEMOBS, BDORDEMOUTOBR, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;
      /***********************************************************************************************************/      
    END
END^

COMMENT ON PARAMETER SP_ATUALIZAR_TMP_C195_D195.PRTIPOLAN IS 'ENT/SAI'^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_C800 (
    PRSESSAO INTEGER,
    PRSESSAOPRO INTEGER,
    PRTIPOLAN CHAR(3))
AS
BEGIN
  PRTIPOLAN = UPPER(:PRTIPOLAN);

  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      /******************************************** VALIDAÇÃO DO C850 ********************************************/
      /*56 - Código de CST de ICMS não cadastrado*/
      INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
      SELECT C.BDCODEMP, C.BDCHAVE, C.BDORDEM, C.BDCODIGO, C.BDSESSAO, 56 BDCODINCONSISTENCIA, 15 BDTIPOINCON
      FROM TMP_VEF_EMP_TC850SAI_TEMP C
      LEFT OUTER JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = C.BDCODCSTICMS)
      WHERE C.BDSESSAO = :PRSESSAO
        AND CST.BDCODCSTICMS IS NULL;

      /*123 - Observação não informada ou inconsistente.
      INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
      SELECT C.BDCODEMP, C.BDCHAVE, C.BDORDEM, C.BDCODIGO, C.BDSESSAO, 123 BDCODINCONSISTENCIA, 8 BDTIPOINCON
      FROM TMP_VEF_EMP_TC850SAI_TEMP C
      WHERE C.BDSESSAO = :PRSESSAO
        AND ((C.BDALTCODOBS IS NULL) OR (C.BDALTCODOBS = 0)); */

      /***********************************************************************************************************/
    END
END
^

COMMENT ON PARAMETER SP_ATUALIZAR_TMP_C800.PRTIPOLAN IS 'ENT/SAI'^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_D1XX (
    PRSESSAO INTEGER,
    PRSESSAOPRO INTEGER,
    PRSESSAOTER INTEGER)
AS
BEGIN
  /***********************************************D110***********************************************/
  /*Se o produto for inconsistente, torna o lançamento inconsistente tambem*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordemst, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEMST, S.BDSESSAO, 76 BDCODINCONSISTENCIA, 12 BDTIPOINCON
  FROM TMP_VEF_EMP_TD110SAI_TEMP S
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :PRSESSAOPRO AND PRO.BDCODEMP = S.BDCODEMP AND PRO.BDCODPROD = S.BDALTCODPROD)
  WHERE S.BDSESSAO = :PRSESSAO
  AND S.BDALTCODPROD IS NOT NULL
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY BDCODEMP, BDCHAVE, BDORDEMST, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;
  /**************************************************************************************************/

  /***********************************************D130***********************************************/
  /*74 - Participante inconsistente*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 74 BDCODINCONSISTENCIA, 13 BDTIPOINCON
  FROM TMP_VEF_EMP_TD130COMPCON_TEMP S
  JOIN VEF_INCON_TTERCEIROS T ON(T.BDSESSAO = :PRSESSAOTER AND T.BDCODTER = S.BDALTCODTER)
  WHERE S.BDSESSAO = :PRSESSAO
  AND S.BDALTCODTER IS NOT NULL
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;

  /*124 - Participante redespachado inconsistente.*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 124 BDCODINCONSISTENCIA, 13 BDTIPOINCON
  FROM TMP_VEF_EMP_TD130COMPCON_TEMP S
  JOIN VEF_INCON_TTERCEIROS T ON(T.BDSESSAO = :PRSESSAOTER AND T.BDCODTER = S.BDALTCODTERREDESPACHANTE)
  WHERE S.BDSESSAO = :PRSESSAO
  AND S.BDALTCODTERREDESPACHANTE IS NOT NULL
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;
  /**************************************************************************************************/
  
  /***********************************************D160***********************************************/
  /*74 - Participante inconsistente - Remetente*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, BDORDEMCARTRANS, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEMCARTRANS, S.BDSESSAO, 74 BDCODINCONSISTENCIA, 14 BDTIPOINCON
  FROM TMP_VEF_EMP_TD160CARTRANS_TEMP S
  JOIN VEF_INCON_TTERCEIROS T ON(T.BDSESSAO = :PRSESSAOTER AND T.BDCODTER = S.BDALTCODTERREMETENTE)
  WHERE S.BDSESSAO = :PRSESSAO
  AND S.BDALTCODTERREMETENTE IS NOT NULL
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDORDEMCARTRANS, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;

  /*125 - Participante destinatário inconsistente. - Destinatário*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, BDORDEMCARTRANS, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEMCARTRANS, S.BDSESSAO, 125 BDCODINCONSISTENCIA, 14 BDTIPOINCON
  FROM TMP_VEF_EMP_TD160CARTRANS_TEMP S
  JOIN VEF_INCON_TTERCEIROS T ON(T.BDSESSAO = :PRSESSAOTER AND T.BDCODTER = S.BDALTCODTERDESTINATARIO)
  WHERE S.BDSESSAO = :PRSESSAO
  AND S.BDALTCODTERDESTINATARIO IS NOT NULL
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDORDEMCARTRANS, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;

  /*121 - Participante de coleta não informado ou inconsistente. - Coleta*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, BDORDEMCARTRANS, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEMCARTRANS, S.BDSESSAO, 121 BDCODINCONSISTENCIA, 14 BDTIPOINCON
  FROM TMP_VEF_EMP_TD160CARTRANS_TEMP S
  JOIN VEF_INCON_TTERCEIROS T ON(T.BDSESSAO = :PRSESSAOTER AND T.BDCODTER = S.BDALTCODTERCOLETA)
  WHERE S.BDSESSAO = :PRSESSAO
  AND S.BDALTCODTERCOLETA IS NOT NULL
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDORDEMCARTRANS, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;

  /*122 - Participante de entrega não informado ou inconsistente. - Entrega*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, BDORDEMCARTRANS, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEMCARTRANS, S.BDSESSAO, 122 BDCODINCONSISTENCIA, 14 BDTIPOINCON
  FROM TMP_VEF_EMP_TD160CARTRANS_TEMP S
  JOIN VEF_INCON_TTERCEIROS T ON(T.BDSESSAO = :PRSESSAOTER AND T.BDCODTER = S.BDALTCODTERENTREGA)
  WHERE S.BDSESSAO = :PRSESSAO
  AND S.BDALTCODTERENTREGA IS NOT NULL
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDORDEMCARTRANS, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;
  /**************************************************************************************************/  
END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_TC17X (
    PRSESSAO INTEGER,
    PRSESSAOTER INTEGER)
AS
BEGIN
  /***********************************************C176***********************************************/
  /*12 - Participante não cadastrado ou inconsistente*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdordempro, bdordemc176, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDORDEMPRO, S.BDORDEMC176, S.BDSESSAO, 12 BDCODINCONSISTENCIA, 16 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSTC176_TEMP S
  JOIN VEF_INCON_TTERCEIROS T ON(T.BDSESSAO = :PRSESSAOTER AND T.BDCODTER = S.BDALTCODTER)
  WHERE S.BDSESSAO = :PRSESSAO
  AND ((S.BDALTCODTER IS NULL) OR (T.BDCODINCONSISTENCIA IS NOT NULL))
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDORDEMPRO, S.BDORDEMC176, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;

  /*127 - O modelo informado deve ser 1 ou 55.*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdordempro, bdordemc176, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDORDEMPRO, S.BDORDEMC176, S.BDSESSAO, 140 BDCODINCONSISTENCIA, 16 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSTC176_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO
  AND S.BDMODELO NOT IN(1, 55);

  /*128 - Participante do emitente não existente na base ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdordempro, bdordemc176, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDORDEMPRO, S.BDORDEMC176, S.BDSESSAO, 141 BDCODINCONSISTENCIA, 16 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSTC176_TEMP S
  JOIN VEF_INCON_TTERCEIROS T ON(T.BDSESSAO = :PRSESSAOTER AND T.BDCODTER = S.BDALTCODTER_NFE)
  WHERE S.BDSESSAO = :PRSESSAO
  AND S.BDALTCODTER_NFE IS NOT NULL
  AND T.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDORDEMPRO, S.BDORDEMC176, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;

  /*13 - Número do documento inicial não pode ser zero*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdordempro, bdordemc176, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDORDEMPRO, S.BDORDEMC176, S.BDSESSAO, 13 BDCODINCONSISTENCIA, 16 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSTC176_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO
  AND ((S.BDNUM_DOC_ULT_E IS NULL) OR (S.BDNUM_DOC_ULT_E = 0));

  /*129 - Data da última entrada deve ser informada.*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdordempro, bdordemc176, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDORDEMPRO, S.BDORDEMC176, S.BDSESSAO, 142 BDCODINCONSISTENCIA, 16 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSTC176_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO
  AND S.BDDT_ULT_E IS NULL;

  /*88 - A Quantidade deve ser informada.*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdordempro, bdordemc176, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDORDEMPRO, S.BDORDEMC176, S.BDSESSAO, 88 BDCODINCONSISTENCIA, 16 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSTC176_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO
  AND ((S.BDQUANT_ULT_E IS NULL) OR (S.BDQUANT_ULT_E = 0));

  /*130 - Valor da mercadoria deve ser informado.*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdordempro, bdordemc176, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDORDEMPRO, S.BDORDEMC176, S.BDSESSAO, 143 BDCODINCONSISTENCIA, 16 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSTC176_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO
  AND ((S.BDVL_UNIT_ULT_E IS NULL) OR (S.BDVL_UNIT_ULT_E = 0));

  /*131 - Valor da base de cálculo de ST deve ser informado.*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdordempro, bdordemc176, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDORDEMPRO, S.BDORDEMC176, S.BDSESSAO, 144 BDCODINCONSISTENCIA, 16 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSTC176_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO
  AND ((S.BDVL_UNIT_BC_ST IS NULL) OR (S.BDVL_UNIT_BC_ST = 0));
  /**************************************************************************************************/
END^

create or alter procedure SP_ATUALIZAR_TMP_CTR (
    PRSESSAO integer,
    PRSESSAOTER integer)
as
BEGIN
  /*CTR*/
  /*12 - Participante não cadastrado ou inconsistente*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 12 BDCODINCONSISTENCIA, 17 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSAICTR_TEMP S
  LEFT OUTER JOIN VEF_INCON_TTERCEIROS T ON(T.BDSESSAO = :PRSESSAOTER AND T.BDCODTER = S.BDALTCODTER)
  WHERE S.BDSESSAO = :PRSESSAO
  AND ((S.BDALTCODTER IS NULL) OR (T.BDCODINCONSISTENCIA IS NOT NULL))
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;

  /*Carga Transportada*/
  /*12 - Participante não cadastrado ou inconsistente*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDSESSAO, 12 BDCODINCONSISTENCIA, 18 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSAICARTR_TEMP S
  LEFT OUTER JOIN VEF_INCON_TTERCEIROS T ON(T.BDSESSAO = :PRSESSAOTER AND T.BDCODTER = S.BDALTCODTER)
  WHERE S.BDSESSAO = :PRSESSAO
  AND ((S.BDALTCODTER IS NULL) OR (T.BDCODINCONSISTENCIA IS NOT NULL))
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDORDEM, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;

  /*196 - Cidade de origem ou destino inválida*/
  INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, NULL BDORDEM, S.BDSESSAO, 196 BDCODINCONSISTENCIA, 20 BDTIPOINCON
  FROM TMP_VEF_EMP_TD100SAI_TEMP S
  WHERE (S.BDSESSAO = :PRSESSAO) AND
        (((S.BDCIDORIGEM <= 0) OR (S.BDCIDORIGEM IS NULL)) OR ((S.BDCIDDEST <= 0) OR (S.BDCIDDEST IS NULL)))
  GROUP BY S.BDCODEMP, S.BDCHAVE, BDORDEM, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;

  /*120 - Informação complementar não informada.*/
  INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEMIC, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDORDEMINFCOM, S.BDSESSAO, 120 BDCODINCONSISTENCIA, 20 BDTIPOINCON
  FROM TMP_VEF_EMP_TD100SAI_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO
  AND (((S.BDALTORDEMINFCOM IS NULL) OR (S.BDALTORDEMINFCOM = 0)) AND (S.BDCODINFCOM <> ''))
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDORDEMINFCOM, S.BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON;

END^

CREATE OR ALTER PROCEDURE SP_CANCELAR_LAN_BASE (
    PRSESSAO INTEGER,
    PREXCLUIRLAN DM_BOOLEAN)
AS
DECLARE VARIABLE FCODEMP INTEGER;
DECLARE VARIABLE FCODSITNF_CANC INTEGER;
DECLARE VARIABLE WZERARNFCANC DM_BOOLEAN;
BEGIN
  /***********************************Tratamento Nfe's canceladas***********************************/
  /*Patrick T. Sá - Todos comandos da solicitação 18626 foram refeitos porque estavam levando
                    mais de 1 hora para executar no banco da GFisco, ocasionando travamento
                    nos outros terminais que estão importando*/
  FCODSITNF_CANC = 2; /*2 - Documento cancelado*/

  SELECT FIRST 1 BDCODEMP FROM TMP_VEF_EMP_TMOVSAI_TEMP WHERE BDSESSAO = :PRSESSAO AND BDCODEMP IS NOT NULL INTO :FCodEmp;

  /*Se não pegou empresa significa que não tem lançamento, então pode sair da SP*/
  IF (:FCodEmp IS NULL) THEN
    EXIT;  

  /*149 - Inconsistencia de bloqueio de lançamento*/
  INSERT INTO VEF_INCON_TMOVSAI (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 149, 1 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  JOIN TBLOQLAN_USUARIO BLOQ_U ON (BLOQ_U.BDCODEMP = S.BDCODEMP AND BLOQ_U.BDCODUSU = (SELECT BDCODUSU FROM SP_GET_USUARIO))
  JOIN TBLOQLAN_EMPRESA BLOQ_E ON (BLOQ_E.BDCODEMP = BLOQ_U.BDCODEMP AND BLOQ_E.BDCODBLQ = BLOQ_U.BDCODBLQ AND BLOQ_E.BDCODBLE = BLOQ_U.BDCODBLE AND
                                  (S.BDDATAEMISSAO BETWEEN BLOQ_E.BDDATAINICIAL AND BLOQ_E.BDDATAFINAL))
  JOIN TBLOQLAN BLOQ ON (BLOQ.BDCODBLQ = BLOQ_U.BDCODBLQ AND BLOQ.BDCODSIS = 3 AND (UPPER(BLOQ.BDRECURSO) = 'FRLANCAMENTOSAIDA'))
  WHERE S.BDSESSAO = :PRSESSAO AND
        S.BDCODEMP = :FCODEMP
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDSESSAO;

  /*193 - Lançamento bloqueado nesse período, verifique o encerramento de exercício*/
  INSERT INTO VEF_INCON_TMOVSAI (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 193, 1 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  JOIN VSUC_EMPRESAS_TENCEXE TENC ON (TENC.BDCODEMP = S.BDCODEMP)
  WHERE S.BDSESSAO = :PRSESSAO AND
        S.BDCODEMP = :FCODEMP AND
        ((S.BDDATAEMISSAO BETWEEN TENC.BDDATAINIZER AND TENC.BDDATAFIMZER) OR (TENC.BDDATAINIZER <= S.BDDATAEMISSAO AND
        TENC.BDDATAFIMZER IS NULL)) AND
        NOT EXISTS(SELECT FIRST 1 I.BDCODEMP
                   FROM TINICIO_CONTABILIZACAO I
                   WHERE I.BDCODEMP = S.BDCODEMP AND
                         I.BDCODSIS = 3 AND
                         I.BDDATA > S.BDDATAEMISSAO)
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDSESSAO;

  UPDATE TMP_VEF_EMP_TMOVSAI_TEMP TMP SET TMP.BDCHAVENFECANC = TMP.BDCHAVENFE
  WHERE TMP.BDSESSAO = :PRSESSAO AND TMP.BDCODSITNF = :FCODSITNF_CANC AND TMP.BDCHAVENFECANC IS NULL AND
  NOT EXISTS(SELECT S.BDCODEMP, S.BDSESSAO, S.BDCHAVE
             FROM VEF_INCON_TMOVSAI S
             WHERE S.BDCODEMP = TMP.BDCODEMP
               AND S.BDSESSAO = TMP.BDSESSAO
               AND S.BDCHAVE = TMP.BDCHAVE);

  SELECT UPPER(P.BDVALOR)
  FROM TPARGER P
  WHERE UPPER(P.BDCAMPO) = 'BDZERANFCANCELADA'
  INTO :wZerarNFCanc;

  DELETE FROM TMP_TLANC_REPETIDOS WHERE BDCHAVE IS NOT NULL;

  /* Alt.: #234888 - Inserido o campo CHAVE NF-e na tabela de TMP_TLANC_REPETIDOS, por que quando importa as NFe-s, pode ter 2 sessoes nas tabelas temporarias,
  uma das notas "normais" e outra dos eventos de cancelamento e quando aplicava os updates abaixo, estava olhando na tabela apenas as chaves e com isso aplicava em lancamentos errados.
    Por exemplo: Nos eventos de cancelamentos vinha uma chave 13(chave do lancamento no banco), com isso acabava zerando os valores da da nota chave 13 da importacao normal(chave sequencial),
  mesmo que eles sejam registros totalmente diferentes, por isso foi incluido a Chave NF-e para garantir que está sempre buscando o lançamento correto... */
  /*Insere nessa temporária para no update ter os campos chave, então o update usa o indice primário*/
  INSERT INTO TMP_TLANC_REPETIDOS(BDCODEMP, BDCHAVE, BDDATACANC, BDCHAVENFE)
  SELECT SAI.BDCODEMP, SAI.BDCHAVE, COALESCE(S.BDDATACANC, SAI.BDDATAEMISSAO) BDDATACANC, S.BDCHAVENFECANC
  FROM (
        SELECT S.BDCODEMP, S.BDCHAVE, S.BDCHAVENFE, S.BDCHAVENFECANC, S.BDDATACANC
        FROM TMP_VEF_EMP_TMOVSAI_TEMP S
        WHERE S.BDSESSAO = :PRSESSAO
        AND S.BDCODEMP = :FCODEMP
        AND S.BDCODSITNF = :FCODSITNF_CANC
        AND ((S.BDCHAVENFE IS NOT NULL) AND (S.BDCHAVENFE <> ''))
        AND ((S.BDCHAVENFECANC IS NOT NULL) AND (S.BDCHAVENFECANC <> ''))
        AND NOT EXISTS(SELECT S.BDCODEMP, S.BDSESSAO, S.BDCHAVE
                       FROM VEF_INCON_TMOVSAI I
                       WHERE I.BDCODEMP = S.BDCODEMP
                       AND I.BDSESSAO = S.BDSESSAO
                       AND I.BDCHAVE = S.BDCHAVE)
       ) S
  JOIN VEF_EMP_TMOVSAI SAI ON(SAI.BDCODEMP = S.BDCODEMP AND SAI.BDCHAVENFE = S.BDCHAVENFE AND SAI.BDCHAVENFE = S.BDCHAVENFECANC);

  UPDATE VEF_EMP_TMOVSAI S
  SET S.BDCODSITNF = :FCODSITNF_CANC,
      S.BDDATACANC = (
                      SELECT REP.BDDATACANC
                      FROM TMP_TLANC_REPETIDOS REP
                      WHERE REP.BDCODEMP = S.BDCODEMP
                      AND REP.BDCHAVE = S.BDCHAVE
                      AND REP.BDCHAVENFE = S.BDCHAVENFE-- Alt.: #234888
                     )
  WHERE S.BDCODEMP = :FCODEMP
  AND EXISTS (
              SELECT REP.BDCHAVE
              FROM TMP_TLANC_REPETIDOS REP
              WHERE REP.BDCODEMP = S.BDCODEMP
              AND REP.BDCHAVE = S.BDCHAVE
              AND REP.BDCHAVENFE = S.BDCHAVENFE
             );

  DELETE FROM TOL_VEF_EMP_TMOVSAI TOL
  WHERE TOL.BDCODEMP = :FCODEMP
  AND EXISTS(
             SELECT REP.BDCHAVE
             FROM TMP_TLANC_REPETIDOS REP
             JOIN TMP_VEF_EMP_TMOVSAI_TEMP MOV ON(MOV.BDCODEMP = REP.BDCODEMP AND MOV.BDCHAVE = REP.BDCHAVE AND MOV.BDCHAVENFE = REP.BDCHAVENFE)-- Alt.: #234888
             WHERE REP.BDCODEMP = TOL.BDCODEMP
             AND REP.BDCHAVE = TOL.BDCHAVESAI
            );
  /*************************************************************************************************/

  /* Alt.: 18626 - Caso seja um evento de cancelamento sem nota na base ou importando a nota junto */
  INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
  SELECT tmp.BDCODEMP, tmp.BDCHAVE, NULL, tmp.BDSESSAO, 126 BDCODINCONSISTENCIA, 1 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSAI_TEMP tmp
  WHERE tmp.BDSESSAO = :PRSESSAO
  AND TMP.BDCODEMP = :FCODEMP
  AND tmp.BDCODSITNF = :FCODSITNF_CANC
--  AND tmp.BDDATACANC IS NULL -- Alt.: 18626 - Evento de cancelamento...
  AND tmp.BDNUMDOCINI IS NULL
  AND tmp.BDNUMDOCFIM IS NULL
  AND NOT EXISTS(
                 SELECT s.BDCODEMP
                 FROM VEF_EMP_TMOVSAI s
                 WHERE s.BDCODEMP = tmp.BDCODEMP
                 AND s.BDCHAVENFE = tmp.BDCHAVENFECANC
                 AND s.BDCODSITNF = :FCODSITNF_CANC
                 AND ((S.BDCHAVENFE IS NOT NULL) AND (S.BDCHAVENFE <> ''))
                );

  /* Alt.: 18626 - Remove as notas de evento de cancelamento, pois já aplicou o cancelamento acima... */
  DELETE FROM TMP_VEF_EMP_TMOVSAI_TEMP tmp
  WHERE tmp.BDSESSAO = :PRSESSAO
  AND TMP.BDCODEMP = :FCODEMP
  AND tmp.BDCODSITNF = :FCODSITNF_CANC
--  AND tmp.BDDATACANC IS NULL -- Evento de cancelamento não vai vir a data de cancelamento...
  AND Coalesce(tmp.BDCHAVENFE,'') = Coalesce(tmp.BDCHAVENFECANC,'')
  AND EXISTS(
             SELECT S.BDCHAVE
             FROM VEF_EMP_TMOVSAI s
             WHERE s.BDCODEMP = tmp.BDCODEMP
             AND s.BDCHAVENFE = tmp.BDCHAVENFECANC
             AND ((S.BDCHAVENFE IS NOT NULL) AND (S.BDCHAVENFE <> ''))
            )
  AND NOT EXISTS(
                   SELECT S.BDCODEMP, S.BDSESSAO, S.BDCHAVE
                   FROM VEF_INCON_TMOVSAI S
                   WHERE S.BDCODEMP = TMP.BDCODEMP
                   AND S.BDSESSAO = TMP.BDSESSAO
                   AND S.BDCHAVE = TMP.BDCHAVE
            );

  /************************************** Zerar valores de NFe cancelada **************************************/
  IF (:wZerarNFCanc = 'TRUE') THEN
    BEGIN
      /*Zera valores da capa*/
      UPDATE VEF_EMP_TMOVSAI MOV
      SET MOV.BDVALORNOTA = 0,
          MOV.BDDESCONTONOTA = 0
      WHERE MOV.BDCODEMP = :FCODEMP
      AND EXISTS (
                  SELECT REP.BDCHAVE
                  FROM TMP_TLANC_REPETIDOS REP
                  WHERE REP.BDCODEMP = MOV.BDCODEMP
                  AND REP.BDCHAVE = MOV.BDCHAVE
                  AND REP.BDCHAVENFE = MOV.BDCHAVENFE-- Alt.: #234888
                 );

      /*Zera valores dos itens*/
      UPDATE VEF_EMP_TMOVSAIITENS I
      SET -- Alt.: #137131 #132536 - Quando for zerar uma nova váriavel, procurar por essa solucitação para zerar em todo os pontos...
          -- Item / CFOP
          I.BDVLRCONTAB   = 0, -- Valor contábil
          I.BDDESCONTO    = 0,  -- Desconto
          I.BDREDBCICMS   = 0, -- Redução base cálculo
          -- ICMS
          I.BDBASEICMS    = 0, -- Base
          I.BDALIQICMS    = 0, -- Alíquota
          I.BDVLRICMS     = 0, -- Valor
          I.BDISENTASICMS = 0, -- Isentas
          I.BDOUTRASICMS  = 0, -- Outras
          I.BDICMSFRETESAI = 0, -- ICMS frete
          I.BDOUTROSIMP   = 0, -- Outros impostos
          -- IPI
          I.BDBASEIPI     = 0, --  Base
          I.BDVLRIPI      = 0, --  Valor
          I.BDISENTASIPI  = 0, --  Isentas
          I.BDOUTRASIPI   = 0, --  Outras
          -- Substituição tributária - ICMS
          I.BDBASEST      = 0, --  Base
          I.BDALIQST      = 0, --  Alíquota
          I.BDVLRST       = 0, --  Valor
          --I.BDVALNTRIBST = 0, --  Não retido
          --I.BDICMSRETENT = 0, --  Retido
          I.BDFCPRETIDO   = 0, --  FCP ST
          -- Pis e Cofins
          I.BDVLRPIS      = 0,
          I.BDVLRCOFINS   = 0,
          -- FCP Operacao Propria
          I.BDVLRFCP      = 0
      WHERE I.BDCODEMP = :FCODEMP
      AND EXISTS (
                  SELECT REP.BDCHAVE
                  FROM TMP_TLANC_REPETIDOS REP
                  JOIN TMP_VEF_EMP_TMOVSAI_TEMP MOV ON(MOV.BDCODEMP = REP.BDCODEMP AND MOV.BDCHAVE = REP.BDCHAVE AND MOV.BDCHAVENFE = REP.BDCHAVENFE)-- Alt.: #234888
                  WHERE REP.BDCODEMP = I.BDCODEMP
                  AND REP.BDCHAVE = I.BDCHAVE
                 );

      /*Zera valores dos produtos*/
      UPDATE TMP_VEF_EMP_TMOVPROSAI_TEMP P
      SET -- Alt.: #137131 #132536 - Quando for zerar uma nova váriavel, procurar por essa solucitação para zerar em todo os pontos...
          -- Produto
          P.BDQTDITEM          = 0, -- Quantidade
          P.BDVLRABATNT        = 0, -- Valor do abatimento
          P.BDVLRITEM          = 0, -- Valor total do produto
          P.BDREDBCICMS        = 0, -- Redução base de cálculo
          P.BDVLRSEGURO        = 0, -- Seguro
          P.BDVLRDESC          = 0, -- Valor do desconto
          P.BDVLRFRETE         = 0, -- Frete
          P.BDVLRDESPACESSORIA = 0, -- Despesas acessórias
          -- Impostos
          -- ICMS
          P.BDBCICMS           = 0, -- Base de cálculo
          P.BDALIQICMS         = 0, -- Alíquota
          P.BDVLRICMS          = 0, -- Valor
          -- IPI
          P.BDBCIPI            = 0, -- Base de cálculo
          P.BDALIQIPI          = 0, -- Alíquota
          P.BDVLRIPI           = 0, -- Valor
          -- PIS
          P.BDBCPIS            = 0, -- Base de cálculo
          P.BDALIQPIS          = 0, -- Alíquota
          P.BDVLRPIS           = 0, -- Valor
          -- Cofins
          P.BDBCCOFINS         = 0, -- Base de cálculo
          P.BDALIQCOFINS       = 0, -- Alíquota
          P.BDVLRCOFINS        = 0, -- Valor
          -- ISSQN
          P.BDBCISSQN          = 0, -- Base de cálculo
          P.BDALIQISSQN        = 0, -- Alíquota
          P.BDVLRISSQN         = 0, -- Valor
          -- ICMS ST
          P.BDBCST             = 0, -- Base de cálculo
          P.BDALIQST           = 0, -- Alíquota
          P.BDVLRST            = 0, -- Valor
          -- FCP Retido por ST
          P.BDBCFCPRETIDO      = 0, -- Base de cálculo
          P.BDALIQFCPRETIDO    = 0, -- Alíquota
          P.BDFCPRETIDO        = 0, -- Valor
          -- ICMS ST Retido
          P.BDBCICMSSTRET      = 0, -- Base de cálculo
          P.BDALIQIMCSSTRET    = 0, -- Alíquota
          P.BDVLRICMSSTRET     = 0, -- Valor
          -- FCP Retido ant.
          P.BDBCFCPSTRET       = 0, -- Base de cálculo
          P.BDALIQFCPSTRET     = 0, -- Alíquota
          P.BDVLRFCPSTRET      = 0, -- Valor
          -- ICMS Efetiva
          P.BDBCICMSEFET       = 0, -- Base de cálculo
          P.BDALIQICMSEFET     = 0, -- Alíquota
          P.BDVLRICMSEFET      = 0, -- Valor
    -- FCP Operacao Propria
    P.BDVLRFCP           = 0, -- Valor
    P.BDALQFCP           = 0, -- Alíquota
          P.BDBCFCP            = 0, -- Base de cálculo
          -- Credito Presumido
          P.BDALIQCREDPRESUMIDO= 0, -- Alíquota
          P.BDVLRCREDPRESUMIDO = 0  -- Base de cálculo
      WHERE P.BDCODEMP = :FCODEMP
      AND EXISTS (
                  SELECT REP.BDCHAVE
                  FROM TMP_TLANC_REPETIDOS REP
                  JOIN TMP_VEF_EMP_TMOVSAI_TEMP MOV ON(MOV.BDCODEMP = REP.BDCODEMP AND MOV.BDCHAVE = REP.BDCHAVE AND MOV.BDCHAVENFE = REP.BDCHAVENFE)-- Alt.: #234888
                  WHERE REP.BDCODEMP = P.BDCODEMP
                  AND REP.BDCHAVE = P.BDCHAVE
                  AND MOV.BDSESSAO = P.BDSESSAO
                 );
    END

  IF (:PREXCLUIRLAN = 'TRUE') THEN
    BEGIN
        DELETE FROM TMP_VEF_EMP_TMOVSAI_TEMP TMP
        WHERE TMP.BDSESSAO = :PRSESSAO
        AND TMP.BDCODEMP = :FCODEMP
        AND NOT EXISTS(
                       SELECT S.BDCODEMP, S.BDSESSAO, S.BDCHAVE
                       FROM VEF_INCON_TMOVSAI S
                       WHERE S.BDCODEMP = TMP.BDCODEMP
                       AND S.BDSESSAO = TMP.BDSESSAO
                       AND S.BDCHAVE = TMP.BDCHAVE
                     );
    END
END^

create or alter procedure SP_ATUALIZAR_TMP_TMOVSAI (
    PRSESSAO integer,
    PRREF integer,
    PRCHAVEFIMBASE integer,
    PRVALIDARCSTMOVPRO varchar(5),
    PRSESSAOPRO integer,
    PRSESSAOTER integer,
    PRSESSAOEQUIPSAT integer,
    PRGERALOG varchar(5))
as
declare variable WSEGREGACAO varchar(5);
declare variable FCODEMP integer;
declare variable FENQFED integer;
declare variable FCODCONFICMSSPED integer;
declare variable FSQL varchar(700);
declare variable FCODPLANOONLINE integer;
declare variable FUFEMP varchar(2);
declare variable FCODPLANOINCON integer;
declare variable FNRNOTASAI varchar(5);
declare variable FDATAEMISAI varchar(5);
declare variable FSERIESAI varchar(5);
declare variable FESPECIESAI varchar(5);
declare variable FMODELOSAI varchar(5);
declare variable FCHAVENFSAI varchar(5);
declare variable WCFOPPADRAOCANC integer;
declare variable WCFOPPADRAO integer;
declare variable WAJUSTARCFOPPART varchar(5);
declare variable FCODCONFIRLP integer;
declare variable FFORMATRIBUTACAO integer;
BEGIN
  RDB$SET_CONTEXT('USER_SESSION','W_GERALOG_TEMP',:PRGERALOG);
  SELECT Coalesce(rdb$get_context('USER_SESSION', 'W_SEGREGACAO_FISCAL'),'FALSE') FROM rdb$database INTO WSEGREGACAO;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAI','1');

  DELETE FROM VEF_INCON_TMOVSAI WHERE BDSESSAO = :PRSESSAO;
  SELECT FIRST 1 BDCODEMP FROM TMP_VEF_EMP_TMOVSAI_TEMP WHERE BDSESSAO = :PRSESSAO AND BDCODEMP IS NOT NULL INTO :FCodEmp;
  /*Se não pegou empresa significa que não tem lançamento, então pode sair da SP*/
  IF (:FCodEmp IS NULL) THEN
    EXIT;
  IF (:PRCHAVEFIMBASE > 0) THEN
    BEGIN
      SETORDEMSEQUENCIAL(0);
      UPDATE TMP_VEF_EMP_TMOVSAI_TEMP SET BDEDITCHAVE = :PRCHAVEFIMBASE WHERE BDSESSAO = :PRSESSAO AND BDEDITCHAVE IS NULL;
    END
  /*Joga a cidade do participante na capa da nota se não vier na importação*/
  UPDATE TMP_VEF_EMP_TMOVSAI_TEMP S SET S.BDCODCID = (SELECT FIRST 1
                                                             COALESCE(
                                                                      (SELECT FIRST 1 T.BDCODCID
                                                                       FROM TMP_TTERCEIRO_TEMP T
                                                                       WHERE T.BDSESSAO = :PRSESSAOTER
                                                                       AND T.BDCODTER = S.BDCODTER),
                                                                      (SELECT FIRST 1 VW.BDCODCID
                                                                       FROM VW_TTERCEIRO_SIMPLES VW
                                                                       WHERE VW.BDCGCTER = S.BDCNPJ)
                                                                     )
                                                      FROM RDB$DATABASE)
  WHERE S.BDSESSAO = :PRSESSAO
  AND ((S.BDCODCID IS NULL) OR (S.BDCODCID = 0));
  /*Busca dados usados nas inconsistencias do lançamento e do item*/
  SELECT SP.BDCODCONFICMSSPED, SP.BDCODPLANOONLINE, SP.BDSIGLAUF, SP.BDCODPLANOINCONS, SP.BDCODENQFED, SP.BDCODCONFIRLP, SP.BDFORMATRIBUTACAO

  FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :FCODEMP, NULL) SP INTO :FCODCONFICMSSPED, :FCODPLANOONLINE, :FUFEMP, :FCODPLANOINCON, :FENQFED, :FCODCONFIRLP, :FFORMATRIBUTACAO;

  /***********************************Tratamento Nfe's canceladas***********************************/
  EXECUTE PROCEDURE SP_CANCELAR_LAN_BASE(:PRSESSAO, 'FALSE');
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAI','2');
  /*************************************************************************************************/
  /*Verifica se não existe o lançamento na base */
  SELECT R.BDNRNOTASAI, R.BDDATAEMISAI, R.BDSERIESAI, R.BDESPECIESAI, R.BDMODELOSAI,r.BDCHAVENFSAI
  FROM VEF_BASE_TCONFLANCREPETIDOS R INTO :FNRNOTASAI, :FDATAEMISAI, :FSERIESAI, :FESPECIESAI, :FMODELOSAI,:FCHAVENFSAI;
  /*Se não tem configuração de lançamento repetido, usa todos os parametros para comparar.*/
  IF (ROW_COUNT = 0) THEN
    BEGIN
      FNRNOTASAI  = 'TRUE';
      FMODELOSAI  = 'TRUE';
      FCHAVENFSAI = 'TRUE';
      FDATAEMISAI = 'TRUE';
      FSERIESAI   = 'TRUE';
      FESPECIESAI = 'TRUE';
    END
  /* Insere incosistência de lançamentos repetidos */
  /* Caso a nota seja cancelada e já exista na base, está importando evento de cancelamento, apenas vai cancelar a nota existente... */

  IF (Coalesce(:WSEGREGACAO,'FALSE') <> 'TRUE') THEN
    BEGIN
  FSQL = '         INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, BDTIPOINCON) ';
  FSQL = FSQL || ' SELECT T.BDCODEMP, T.BDCHAVE, NULL, T.BDSESSAO, 22 BDCODINCONSISTENCIA, 1 BDTIPOINCON ';
  FSQL = FSQL || ' FROM TMP_VEF_EMP_TMOVSAI_TEMP T ';
  FSQL = FSQL || ' JOIN VEF_EMP_TMOVSAI S ON (S.BDCODEMP = T.BDCODEMP ';
  IF (UPPER(:FNRNOTASAI) = 'TRUE') THEN
    FSQL = FSQL || ' AND S.BDNUMDOCINI = T.BDNUMDOCINI AND S.BDNUMDOCFIM = T.BDNUMDOCFIM ';
  IF (UPPER(:FMODELOSAI) = 'TRUE') THEN
    FSQL = FSQL || ' AND S.BDMODELO = T.BDMODELO ';
  IF (UPPER(:FDATAEMISAI) = 'TRUE') THEN
    FSQL = FSQL || ' AND S.BDDATAEMISSAO = T.BDDATAEMISSAO ';
  IF (UPPER(:FSERIESAI)   = 'TRUE') THEN
    FSQL = FSQL || ' AND COALESCE(S.BDSERIE, '''') = COALESCE(T.BDSERIE, '''') ';
  IF (UPPER(:FESPECIESAI) = 'TRUE') THEN
    FSQL = FSQL || ' AND COALESCE(S.BDESPECIE, '''') = COALESCE(T.BDESPECIE, '''') ';
  IF (UPPER(:FCHAVENFSAI) = 'TRUE') THEN
    FSQL = FSQL || ' AND COALESCE(S.BDCHAVENFE, '''') = COALESCE(T.BDCHAVENFE, '''') ';
  FSQL = FSQL || ') WHERE T.BDSESSAO = '||:PRSESSAO;
  /*Sol: 18928 Patrick T. Sá 30/05/2017. CFe valida no comando abaixo*/
  EXECUTE STATEMENT (FSQL || ' AND T.BDMODELO <> 59');
  /*CFe*/
  EXECUTE STATEMENT (FSQL || '  AND T.BDMODELO = 59 AND (Coalesce(S.BDCODEQUIPSAT,0) = Coalesce(T.BDCODEQUIPSAT,0)) ');
    END
  /*Inconsistencia de número do documento vazio(Inicial e final)*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, NULL, S.BDSESSAO,
         CASE WHEN ((S.BDNUMDOCINI = 0) OR (S.BDNUMDOCINI IS NULL)) THEN 13 /*NUMDOCINI vazio*/
              WHEN ((S.BDNUMDOCFIM = 0) OR (S.BDNUMDOCFIM IS NULL)) THEN 14 /*NUMDOCFIM vazio*/
              WHEN (S.BDNUMDOCINI > S.BDNUMDOCFIM)                  THEN 16 /*NUMDOCINI maior do que o NUMDOCFIM*/
         END BDCODINCONSISTENCIA, 1 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO
  AND (((S.BDNUMDOCINI = 0) OR (S.BDNUMDOCINI IS NULL)) OR ((S.BDNUMDOCFIM = 0) OR (S.BDNUMDOCFIM IS NULL)) OR (S.BDNUMDOCINI > S.BDNUMDOCFIM))
  AND (s.BDCHAVENFECANC IS NULL); -- Alt.: 18626 - Evento de cancelamento não precisa verificar...
  /*************************************************************************************************/
  /*Se a nfe tiver chave, valida a chave*/
  IF (:FCODCONFICMSSPED > 0) THEN
    BEGIN
      INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, BDTIPOINCON)
      SELECT MOV.BDCODEMP, MOV.BDCHAVE, NULL, MOV.BDSESSAO, 19 BDCODINCONSISTENCIA, 1 BDTIPOINCON
      FROM (
            SELECT S.BDSESSAO, S.BDCODEMP, S.BDCHAVE, (SELECT BDISVALID FROM SP_VALIDACHAVE_NFE_CTE(S.BDCHAVENFE))
            FROM TMP_VEF_EMP_TMOVSAI_TEMP S
            WHERE S.BDSESSAO = :PRSESSAO
            AND S.BDMODELO IN(55, 65)
            AND S.BDCODSITNF <> 5
           ) MOV
      WHERE BDISVALID = 'FALSE';
    END
  /*Inconsistencia dos lançamentos de modelo 57 que tem chave da nfe vazia ou data de emissão maior do que data de saida*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT MOV.BDCODEMP, MOV.BDCHAVE, NULL, MOV.
         BDSESSAO, CASE WHEN ((TRIM(MOV.bdchavenfe) = '') OR (MOV.bdchavenfe IS NULL)) THEN 18
                        WHEN (BDISVALID = 'FALSE')                                     THEN 20
                   END BDCODINCONSISTENCIA, 1 BDTIPOINCON
  FROM (
        SELECT S.BDSESSAO, S.BDCODEMP, S.BDCHAVE, S.BDCHAVENFE,
               (SELECT BDISVALID FROM SP_VALIDACHAVE_NFE_CTE(S.BDCHAVENFE)), S.BDDATAEMISSAO, S.BDDATASAIDA
        FROM TMP_VEF_EMP_TMOVSAI_TEMP S
        WHERE S.BDSESSAO = :PRSESSAO
        AND S.BDMODELO = 57
        AND ((TRIM(s.bdchavenfe) = '') OR (S.bdchavenfe IS NULL))
        AND s.bdCODSITNF <> 5 -- Alt.: #129608 #29319 - Ignora quando for nota inutilizada #
       ) MOV;
  /*21 - Data da emissão não pode ser maior que a data de saída*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 21 BDCODINCONSISTENCIA, 1 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO
  AND S.BDDATAEMISSAO > S.BDDATASAIDA;
  /*Apartir de agora(08/11/2016) não filtra mas por modelo, toda nf tem que ter esse campo preenchido.*/
  /*Inconsistencia para cidade de destino obrigatória nos modelos 07, 08, 57 e 8B*/
--  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia)
--  SELECT S.BDCODEMP, S.BDCHAVE, NULL, S.BDSESSAO, 15 BDCODINCONSISTENCIA
--  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
--  WHERE S.BDSESSAO = :prsessao
--  AND ((S.BDCODCID = 0) OR (S.BDCODCID IS NULL));
  /*Se não tiver participante vinculado o lançamento é inconsistente*/
  INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, NULL, S.BDSESSAO, 17 BDCODINCONSISTENCIA, 1 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO
  AND ((S.BDALTCODTER IS NULL) OR (S.BDALTCODTER = 0)); /*Este campo deve estar preenchido, é o código do banco no participante*/
--  AND ((S.BDCODTER IS NULL) OR (S.BDCODTER = 0));
  /*Torna o lançamento inconsistente se o cadastro do participante está inconsistente*/
  INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, NULL, S.BDSESSAO, 74 BDCODINCONSISTENCIA, 1 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  JOIN VEF_INCON_TTERCEIROS T ON(T.BDSESSAO = :PRSESSAOTER AND T.BDCODTER = S.BDALTCODTER/*S.BDCODTER*/)
  WHERE S.BDSESSAO = :PRSESSAO
  AND ((S.BDPARTEXISTENTE IS NULL) OR (S.BDPARTEXISTENTE <> 'TRUE'))
  AND (S.BDCODTER > 0);
  /*75 - Lançamentos sem item são inconsistentes*/
  INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, NULL, S.BDSESSAO, 75 BDCODINCONSISTENCIA, 1 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP I ON(I.BDCODEMP = S.BDCODEMP AND I.BDCHAVE = S.BDCHAVE AND I.BDSESSAO = S.BDSESSAO)
  WHERE S.BDSESSAO = :PRSESSAO
    AND (s.BDCHAVENFECANC IS NULL) -- Alt.: 18626 - Evento de cancelamento não precisa verificar...
  GROUP BY S.BDSESSAO, S.BDCODEMP, S.BDCHAVE, I.BDORDEM
  HAVING COUNT(I.BDORDEM) = 0;
  /*11 - Espécie não informado*/
  INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, NULL, S.BDSESSAO, 11 BDCODINCONSISTENCIA, 1 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO
  AND ((S.BDESPECIE IS NULL) OR (S.BDESPECIE = ''))
  AND s.bdCODSITNF <> 5; -- Alt.: #129608 #29319 - Ignora quando for nota inutilizada #
  /*149 - Inconsistencia de bloqueio de lançamento*/
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 149, 1 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  JOIN TBLOQLAN_USUARIO BLOQ_U ON (BLOQ_U.BDCODEMP = S.BDCODEMP AND BLOQ_U.BDCODUSU = (SELECT BDCODUSU FROM SP_GET_USUARIO))
  JOIN TBLOQLAN_EMPRESA BLOQ_E ON (BLOQ_E.BDCODEMP = BLOQ_U.BDCODEMP AND BLOQ_E.BDCODBLQ = BLOQ_U.BDCODBLQ AND BLOQ_E.BDCODBLE = BLOQ_U.BDCODBLE AND (S.BDDATAEMISSAO BETWEEN BLOQ_E.BDDATAINICIAL AND BLOQ_E.BDDATAFINAL))
  JOIN TBLOQLAN BLOQ ON (BLOQ.BDCODBLQ = BLOQ_U.BDCODBLQ AND BLOQ.BDCODSIS = 3 AND (UPPER(BLOQ.BDRECURSO) = 'FRLANCAMENTOSAIDA'))
  WHERE S.BDSESSAO = :PRSESSAO
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDSESSAO;
                                                      
  /*193 - Lançamento bloqueado nesse período, verifique o encerramento de exercício*/   
  INSERT INTO VEF_INCON_TMOVSAI(bdcodemp, bdchave, bdsessao, bdcodinconsistencia, BDTIPOINCON)
  select S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 193, 1 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  JOIN VSUC_EMPRESAS_TENCEXE TENC ON (TENC.BDCODEMP = S.BDCODEMP)
  WHERE S.BDSESSAO = :PRSESSAO AND
       ((S.BDDATAEMISSAO BETWEEN TENC.BDDATAINIZER AND TENC.BDDATAFIMZER) OR
        (TENC.BDDATAINIZER <= S.BDDATAEMISSAO AND TENC.BDDATAFIMZER IS NULL)) AND
        not exists(select first 1 I.BDCODEMP
                   from TINICIO_CONTABILIZACAO I
                   where I.BDCODEMP = S.BDCODEMP and
                         I.BDCODSIS = 3 and
                         I.BDDATA > S.BDDATAEMISSAO)
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDSESSAO;

  /*190 - Equipamento SAT não existente ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
  SELECT S.BDCODEMP, S.BDCHAVE, NULL, S.BDSESSAO, 190 BDCODINCONSISTENCIA, 1 BDTIPOINCON
  FROM TMP_VEF_EMP_TMOVSAI_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO
  AND (S.BDCODEQUIPSAT IS NOT NULL)
  AND EXISTS(SELECT FIRST 1 I.BDCODINCONSISTENCIA FROM VEF_INCON_TEQUIPSAT I WHERE I.BDSESSAO = :PRSESSAOEQUIPSAT AND I.BDCODEMP = S.BDCODEMP AND I.BDCODEQUIPSAT = S.BDCODEQUIPSAT);
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAI','3');
  /***************************************************************************************************************************/
  /*Troca a CFOP dos items aqui, porque se trocar depois de buscar as contas não vai mais encontrar porque já trocou as cfops*/
  /***************************************************************************************************************************/
  /*Busca a sigla da uf do terceiro da tabela de lançamento para tabela de item*/
  UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP I SET I.BDSIGLAUFTER = (SELECT S.BDSIGLAUFTER
                                                               FROM TMP_VEF_EMP_TMOVSAI_TEMP S
                                                               WHERE S.BDCODEMP = I.BDCODEMP
                                                               AND S.BDCHAVE = I.BDCHAVE
                                                               AND S.BDSESSAO = I.BDSESSAO)
  WHERE I.BDSESSAO = :PRSESSAO;
  /*Se a empresa não tiver plano de inconsistencia, deve buscar o plano que está setado como default*/
  IF ((:FCODPLANOINCON = 0) OR (:FCODPLANOINCON IS NULL)) THEN
    SELECT A.BDCODPLANOINCONS, A.BDSAICFOPNCAD, A.BDSAIAJUCFOP, A.BDSAICFOPCANC
    FROM VEF_BASE_TACOESINCONS A
    WHERE UPPER(A.BDPLANODEFAULT) = 'TRUE'
    INTO :FCODPLANOINCON, :wCFOPPADRAO, :wAJUSTARCFOPPART, :wCFOPPADRAOCANC;
  ELSE
    SELECT A.BDCODPLANOINCONS, A.BDSAICFOPNCAD, A.BDSAIAJUCFOP, A.BDSAICFOPCANC
    FROM VEF_BASE_TACOESINCONS A
    WHERE A.BDCODPLANOINCONS = :FCODPLANOINCON
    INTO :FCODPLANOINCON, :wCFOPPADRAO, :wAJUSTARCFOPPART, :wCFOPPADRAOCANC;

  if (UPPER(:WSEGREGACAO) <> 'TRUE') then
    BEGIN
     SELECT FIRST 0 A.BDCODPLANOINCONS, A.BDSAICFOPNCAD, A.BDSAIAJUCFOP, A.BDSAICFOPCANC
     FROM VEF_BASE_TACOESINCONS A
     WHERE A.BDCODPLANOINCONS = :FCODPLANOINCON
     INTO :FCODPLANOINCON, :wCFOPPADRAO, :wAJUSTARCFOPPART, :wCFOPPADRAOCANC;
    END

 /*Só executa se for para ajustar a cfop de acordo com a região*/
  IF ((UPPER(:wAJUSTARCFOPPART) = 'TRUE') and (UPPER(:WSEGREGACAO) <> 'TRUE')) THEN
    BEGIN
      DELETE FROM TMP_VEF_BASE_TNATOP_TEMP WHERE bdcodnat IS NOT NULL;
      /*Busca as cfops existentes na importação, agrupa e insere na tabela*/
      INSERT INTO TMP_VEF_BASE_TNATOP_TEMP (bdcodnat, BDNAOSOMARSTISEOUT, bdclassificacao, bdCODNATEX, bdCODNATufigual, bdCODNATufdif)
      SELECT I.BDCODNAT, COALESCE(N.BDNAOSOMARSTISEOUT, 'FALSE') BDNAOSOMARSTISEOUT, N.BDCLASSIFICACAO,
             ('7'||SUBSTRING(N.BDCODNAT FROM 2 FOR CHAR_LENGTH(N.BDCODNAT)-1)) BDEXTERIOR,
             ('5'||SUBSTRING(N.BDCODNAT FROM 2 FOR CHAR_LENGTH(N.BDCODNAT)-1)) BDUFIGUAL,
             ('6'||SUBSTRING(N.BDCODNAT FROM 2 FOR CHAR_LENGTH(N.BDCODNAT)-1)) BDUFDIF
      FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
      LEFT OUTER JOIN VEF_BASE_TNATOP N ON(N.BDCODNAT = I.BDCODNAT)
      WHERE I.BDSESSAO = :PRSESSAO
      AND I.BDCODNAT IS NOT NULL
      GROUP BY I.BDCODNAT, N.BDNAOSOMARSTISEOUT, N.BDCLASSIFICACAO, BDEXTERIOR, BDUFIGUAL, BDUFDIF;
      /*Muda a cfop se tiver setado para mudar no plano de inconsistencias - troca inicio da cfop para 5, 6 ou 7*/
      /*                  EX                */
      UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP U
      SET BDCODNAT = (
                      COALESCE(
                               (
                                SELECT N.BDCODNATEX
                                FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP IT
                                LEFT OUTER JOIN TMP_VEF_BASE_TNATOP_TEMP N ON(N.BDCODNAT = IT.BDCODNAT)
                                WHERE IT.BDSESSAO = :PRSESSAO
                                AND N.BDCODNATEX IS NOT NULL
                                AND IT.BDSIGLAUFTER = 'EX'
                                AND u.bdcodemp = it.bdcodemp
                                AND u.bdsessao = it.bdsessao
                                AND u.bdchave  = it.bdchave
                                AND u.bdordem  = it.bdordem
                               ), BDCODNAT)
                     )
      WHERE U.BDSIGLAUFTER = 'EX'
      AND u.bdsessao = :PRSESSAO
      AND Coalesce(u.BDPODECFOP,0) <> 1;
      /*                UF IGUAL          */
      UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP U
      SET BDCODNAT = (
                      COALESCE(
                               (
                                SELECT N.BDCODNATUFIGUAL
                                FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP IT
                                LEFT OUTER JOIN TMP_VEF_BASE_TNATOP_TEMP N ON(N.BDCODNAT = IT.BDCODNAT)
                                WHERE IT.BDSESSAO = :PRSESSAO
                                AND N.BDCODNATEX IS NOT NULL
                                AND IT.BDSIGLAUFTER = :FUFEMP
                                AND u.bdcodemp = it.bdcodemp
                                AND u.bdsessao = it.bdsessao
                                AND u.bdchave  = it.bdchave
                                AND u.bdordem  = it.bdordem
                               ), BDCODNAT)
                             )
      WHERE U.BDSIGLAUFTER = :FUFEMP
      AND u.bdsessao = :PRSESSAO
      AND Coalesce(u.BDPODECFOP,0) <> 1;
      /*                UF DIF            */
      UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP U
      SET BDCODNAT = (
                      COALESCE(
                               (
                                SELECT N.BDCODNATUFDIF
                                FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP IT
                                LEFT OUTER JOIN TMP_VEF_BASE_TNATOP_TEMP N ON(N.BDCODNAT = IT.BDCODNAT)
                                WHERE IT.BDSESSAO = :PRSESSAO
                                AND N.BDCODNATEX IS NOT NULL
                                AND ((IT.BDSIGLAUFTER <> :FUFEMP) AND (IT.BDSIGLAUFTER <> 'EX'))
                                AND u.bdcodemp = it.bdcodemp
                                AND u.bdsessao = it.bdsessao
                                AND u.bdchave  = it.bdchave
                                AND u.bdordem  = it.bdordem
                               ), BDCODNAT)
                     )
      WHERE ((U.BDSIGLAUFTER <> :FUFEMP) AND (U.BDSIGLAUFTER <> 'EX'))
      AND u.bdsessao = :PRSESSAO
      AND Coalesce(u.BDPODECFOP,0) <> 1;
    END
  /*Altera para cfop padrao as notas canceladas*/
   IF ((:wCFOPPADRAOCANC > 0) and (UPPER(:WSEGREGACAO) <> 'TRUE')) THEN
     BEGIN
       UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP U
       SET U.BDCODNAT = :wCFOPPADRAOCANC
       WHERE U.BDSESSAO = :PRSESSAO
       AND EXISTS(
                  SELECT I.BDCHAVE
                  FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
                  LEFT OUTER JOIN VEF_BASE_TNATOP N ON(N.BDCODNAT = I.BDCODNAT)
                  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO)
                  WHERE I.BDSESSAO = U.BDSESSAO
                  AND S.BDCODSITNF IN(2, 3)
                  AND N.BDCODNAT IS NULL
                  AND I.BDCODEMP = U.BDCODEMP
                  AND I.BDCHAVE  = U.BDCHAVE
                  AND I.BDORDEM  = U.BDORDEM
                  AND I.BDSESSAO = U.BDSESSAO
                 );
     END
  /*Altera para cfop padrao as notas não canceladas*/
  IF ((:wCFOPPADRAO > 0) and (UPPER(:WSEGREGACAO) <> 'TRUE')) THEN
    BEGIN
      UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP U
      SET U.BDCODNAT = :wCFOPPADRAO
      WHERE U.BDSESSAO = :PRSESSAO
      AND EXISTS(
                 SELECT I.BDCHAVE
                 FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I
                 LEFT OUTER JOIN VEF_BASE_TNATOP N ON(N.BDCODNAT = I.BDCODNAT)
                 LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO)
                 WHERE I.BDSESSAO = U.BDSESSAO
                 AND S.BDCODSITNF NOT IN(2, 3)
                 AND N.BDCODNAT IS NULL
                 AND I.BDCODEMP = U.BDCODEMP
                 AND I.BDCHAVE  = U.BDCHAVE
                 AND I.BDORDEM  = U.BDORDEM
                 AND I.BDSESSAO = U.BDSESSAO
                );
    END
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAI','4');

/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAI','5');
  EXECUTE PROCEDURE SP_ATUALIZAR_CAMPO_CHAVE_TEMP(:PRSESSAO, 'TMP_VEF_EMP_TMOVSAI_TEMP'); /*Joga a chave do lan??amento para os dependentes*/
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAI','6');
  EXECUTE PROCEDURE SP_VALIDA_CONTA_ONLINE_TEMP(:FCODPLANOONLINE, :PRSESSAO, :FENQFED, :FCODCONFIRLP, 'SAI'); /*Busca as contas para contabiliza????o*/
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAI','7');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_TMOVSAIITENS(:FCODPLANOONLINE, :PRSESSAO, :FCODPLANOINCON, :FUFEMP, :PRVALIDARCSTMOVPRO, :PRSESSAOPRO, :PRREF); /*Valida os itens*/  
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAI','8');
  EXECUTE PROCEDURE SP_CRIA_PRE_CONTABILIZACAO(:PRSESSAO, :FCODPLANOONLINE, :FENQFED, :FCODCONFIRLP, 'SAI', 0, :FFORMATRIBUTACAO); /*Cria a contaliza????o em uma tabela TEMP*/
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAI','9');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMOVENTSAIINFCOM(:PRSESSAO, :PRSESSAOTER, 'SAI'); /*Valida a informa????o complementar da entrada/sa??da - C110*/
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAI','10');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_C160(:PRSESSAO, :PRSESSAOTER); /*Valida o registro C160*/
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAI','11');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_C195_D195(:PRSESSAO, :PRSESSAOPRO, 'SAI'); /*Valida o registro C195*/
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAI','12');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_C800(:PRSESSAO, :PRSESSAOPRO, 'SAI'); /*Valida os registros do grupo C800*/
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAI','13');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_D1XX(:PRSESSAO, :PRSESSAOPRO, :PRSESSAOTER); /*Valida todos os registros D*/
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAI','14');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_TC17X(:PRSESSAO, :PRSESSAOTER); /*Valida os registros C17X*/
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAI','15');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_CTR(:PRSESSAO, :PRSESSAOTER); /*Valida os registros do CTe*/
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAI','16');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_DAPI(:PRSESSAO, 'SAI'); /*Valida os registros da DAPI*/
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_D411_D420(:PRSESSAO); /*Validando registros D411 e D420*/
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVSAI','17');
RDB$SET_CONTEXT('USER_SESSION','W_GERALOG_TEMP','FALSE');
END^

/* Restore proc. body: SP_ATUALIZAR_TMP_TTERCEIRO */
create or alter procedure SP_ATUALIZAR_TMP_TTERCEIRO (
    PRSESSAO integer not null,
    PRLANCAMENTOMANUAL DM_BOOLEAN not null,
    PRGERARINCONSISTENCIAS DM_BOOLEAN not null,
    PRATUALIZARDADOS DM_BOOLEAN not null,
    PRHUGEFILE DM_BOOLEAN not null,
    PRCODTIPO integer,
    PRTIPOVINCULO integer,
    PRVINCPORCNPJ_IE integer = 0)
as
declare variable WINCONSISTENTE DM_BOOLEAN collate WIN_PTBR;
declare variable WCODBRASIL integer;
declare variable WCODCIDENCONTRADO integer;
declare variable WEDITCHAVE integer;
declare variable WCODTER integer;
declare variable WCGCTER varchar(18) collate WIN_PTBR;
declare variable WIETER varchar(20) collate WIN_PTBR;
declare variable WAPELIDOTER varchar(20);
declare variable WNOMETER varchar(100) collate WIN_PTBR;
declare variable WCODCID integer;
declare variable WCODPAIS integer;
declare variable WAPELIDO varchar(20);
declare variable WCODTEREXIST integer;
declare variable WROW_COUNT integer;
declare variable WCGCTERBASE varchar(18) collate WIN_PTBR;
BEGIN
  PRLANCAMENTOMANUAL     = UPPER(:PRLANCAMENTOMANUAL);
  PRGERARINCONSISTENCIAS = UPPER(:PRGERARINCONSISTENCIAS);
  PRATUALIZARDADOS       = UPPER(:PRATUALIZARDADOS);
  PRHUGEFILE             = UPPER(:PRHUGEFILE);

  /*Sintegra, não vem o nome do participante no arquivo, deve usar do banco. No sintegra só vem participante do Brasil, então só busca por CPF/CNPJ*/
  IF (:PRCODTIPO = 105) THEN
    BEGIN
        IF (PRVINCPORCNPJ_IE = 1) THEN
          UPDATE TMP_TTERCEIRO_A_VALIDAR TA SET TA.BDNOMETER = (SELECT FIRST 1 T.BDNOME FROM VW_TTERCEIRO_SIMPLES T WHERE T.BDCGCTER = TA.BDCGCTER AND T.BDIETER = TA.BDIETER);
        ELSE
          UPDATE TMP_TTERCEIRO_A_VALIDAR TA SET TA.BDNOMETER = (SELECT FIRST 1 T.BDNOME FROM VW_TTERCEIRO_SIMPLES T WHERE T.BDCGCTER = TA.BDCGCTER);
    END
  /* Select para verificar se a tabela TMP_TTERCEIRO está vazia */
  SELECT FIRST 1 BDCODTER
  FROM TMP_TTERCEIRO
  INTO :WCODTER;

  IF (ROW_COUNT = 0) THEN
  BEGIN
    /* Se for lançamento manual pode encerrar a execução da SP, pois quando for importar algo,
    todos os registros da tabela TTERCEIRO serão carregados para a temporária */
    IF (:PRLANCAMENTOMANUAL = 'TRUE') THEN
      EXIT;

    /* Copiar todos os participantes para a tabela temporária */
    INSERT INTO TMP_TTERCEIRO (BDSESSAO, BDEDITCHAVE, BDCODTER, BDCGCTER, BDIETER, BDAPELIDOTER,
                               BDNOMETER, BDCODCID, BDCODPAIS, BDPARTEXIST, BDREF_MAX, BDPARTEXIST_FIS)
    SELECT 0 BDSESSAO,
           X.BDCODTER BDEDITCHAVE,
           X.BDCODTER,
           COALESCE(TER.BDCGCTER, '') BDCGCTER,
           COALESCE(REF.BDIETER, '') BDIETER,
           COALESCE(REF.BDAPELIDOTER, '') BDAPELIDOTER,
           COALESCE(REF.BDNOMETER, '') BDNOMETER,
           COALESCE(REF.BDCODCID, 0) BDCODCID,
           COALESCE(REF.BDCODPAIS, 0) BDCODPAIS,
           'TRUE' BDPARTEXIST,
           REF.BDREFEMP, 'TRUE' BDPARTEXIST_FIS
    FROM (SELECT R.BDCODTER,
                 MAX(R.BDREFEMP) BDREFEMP
          FROM TTERCEIRO_REF R
          GROUP BY R.BDCODTER) X
    INNER JOIN TTERCEIRO TER ON TER.BDCODTER = X.BDCODTER
    INNER JOIN TTERCEIRO_REF REF ON REF.BDCODTER = X.BDCODTER AND REF.BDREFEMP = X.BDREFEMP
    WHERE ((ter.bdINATIVO IS NULL) or (ter.bdINATIVO = 'FALSE')); -- Alt.: #203025 - Nao deve carregar participantes inativos
  END

  /* Guarda o código de pais do brasil, posteriormente pode ser necessário
  verificar se o participante é do exterior */
  SELECT P.BDCODPAIS
  FROM TPAIS P
  WHERE UPPER(BDDESCPAIS) = 'BRASIL'
  INTO :WCODBRASIL;

  FOR SELECT V.BDEDITCHAVE,
             V.BDCODTER,
             V.BDCGCTER,
             V.BDIETER,
             V.BDAPELIDOTER,
             V.BDNOMETER,
             V.BDCODCID,
             V.BDCODPAIS
      FROM TMP_TTERCEIRO_A_VALIDAR V
      ORDER BY V.BDCODTER
      INTO :WEDITCHAVE,
           :WCODTER,
           :WCGCTER,
           :WIETER,
           :WAPELIDOTER,
           :WNOMETER,
           :WCODCID,
           :WCODPAIS
  DO
  BEGIN
    /* Tratamento de campos a validar */
    WEDITCHAVE  = COALESCE(:WEDITCHAVE, 0);
    WCODTER     = COALESCE(:WCODTER, 0);
    WCGCTER     = COALESCE(:WCGCTER, '');
    WIETER      = COALESCE(:WIETER, '');
    WAPELIDOTER = COALESCE(:WAPELIDOTER, '');
    WNOMETER    = COALESCE(:WNOMETER, '');
    WCODPAIS    = COALESCE(:WCODPAIS, 0);
    WCGCTERBASE = '';
    /*Sol: 14207 Patrick T. Sá 15/03/2017. Quando é participante do exterior, não tem cpf/cnpj então o apelido é o nome*/
    wApelido    = IIF(:wCgcTer = '', SUBSTRING(:wNomeTer FROM 1 FOR 20), :wCgcTer);

    /* independente do registro já existir, precisa verificar se a cidade é válida */
    /* Verificar inconsistencias antes de fazer o update/insert */
    WINCONSISTENTE = 'FALSE';

    /* Se não teve inconsistencia, faz update/insert do registro */
    IF (:WINCONSISTENTE <> 'TRUE') THEN
    BEGIN
      /* Se já tem edit chave, é uma alteração de registro existente na tabela */
      IF (:WEDITCHAVE > 0) THEN
      BEGIN
        wCodTerExist = 0;
        SELECT FIRST 1 T.BDCODTER FROM TTERCEIRO T WHERE T.BDCODTER = :wEditChave INTO :wCodTerExist;
        wCodTerExist = COALESCE(:wCodTerExist, 0);

        /* Verifica se o apelido já está cadastrado, mas não deve marcar como inconsistente ainda...*/
        WINCONSISTENTE = 'FALSE';

        IF (:WINCONSISTENTE <> 'TRUE') THEN
        BEGIN
          IF (:PRATUALIZARDADOS = 'TRUE') THEN
          BEGIN
            UPDATE OR INSERT INTO TMP_TTERCEIRO (BDSESSAO, BDEDITCHAVE, BDCODTER, BDCGCTER, BDIETER,
                                                 BDAPELIDOTER, BDNOMETER, BDCODCID, BDCODPAIS,BDPARTEXIST, BDPARTEXIST_FIS)
            VALUES (:PRSESSAO, :WEDITCHAVE, :WCODTER, :WCGCTER, :WIETER, :WAPELIDO, :WNOMETER,
                    :WCODCID, :WCODPAIS, 'TRUE', 'TRUE')
            MATCHING (BDEDITCHAVE, BDSESSAO);
          END
          ELSE
          BEGIN
            UPDATE TMP_TTERCEIRO
            SET BDCODTER = :WCODTER,
                BDPARTEXIST = IIF(:wCodTerExist > 0, 'TRUE', 'FALSE'),
                BDPARTEXIST_FIS = IIF(:wCodTerExist > 0, 'TRUE', 'FALSE')
            WHERE BDEDITCHAVE = :WEDITCHAVE and (BDSESSAO = :PRSESSAO);

            IF (ROW_COUNT = 0) THEN
            BEGIN
              INSERT INTO TMP_TTERCEIRO (BDSESSAO, BDEDITCHAVE, BDCODTER, BDCGCTER, BDIETER,
                                         BDAPELIDOTER, BDNOMETER, BDCODCID, BDCODPAIS, BDPARTEXIST, BDPARTEXIST_FIS)
              VALUES (:PRSESSAO, :WEDITCHAVE, :WCODTER, :WCGCTER, :WIETER, :WAPELIDO, :WNOMETER,
                      :WCODCID, :WCODPAIS, 'FALSE', 'FALSE');
            END

          END
        END
      END
      ELSE
      BEGIN
        /* NOVO REGISTRO (EDITCHAVE=0) */
        /* Primeiro procurar pelo CNPJ e IE */
        IF ((:wCGCTER IS NOT NULL) AND (:WCGCTER <> '')) THEN
          BEGIN
            IF (:prATUALIZARDADOS = 'TRUE') THEN
            BEGIN
              /*
                 Quando for atualizar por CNPJ, primeiro verificar se existe com mesmo CNPJ e IE, caso não exista, busca pelo CNPJ
                 Por exemplo em importacoes, onde pode nao vir uma inscricao estadual mas ter o participante cadastradao na base com inscricao estadual.
               */
              wROW_COUNT = 0;
              IF (:prTIPOVINCULO <> 0) THEN -- Vinculo somente por CNPJ - Alt.: #203786 - Estava vinculando o participante incorreto, haviam dois participantes na base e deveria atualizar o de menor codigo, porem estava atualizando o de mesmo IE...
                BEGIN
                  UPDATE TMP_TTERCEIRO t
                  SET t.bdSESSAO = :prSESSAO,
                      t.bdEDITCHAVE = COALESCE(T.BDEDITCHAVE, :WEDITCHAVE),
                      t.bdCODTER = :WCODTER,
                      t.bdCGCTER = :WCGCTER,
                      t.bdIETER = :WIETER,
                      t.bdAPELIDOTER = :WAPELIDO,
                      t.bdNOMETER = :WNOMETER,
                      t.bdCODCID = :WCODCID,
                      t.bdCODPAIS = :WCODPAIS,
                      t.bdPARTEXIST = 'TRUE'
                  WHERE (t.bdCGCTER = :wCGCTER)
                    AND (t.bdCODPAIS = :wCodBrasil)
                    AND (COALESCE((SELECT bdNUMERO FROM SP_RETORNA_NUMEROS(t.bdIETER)),'') = COALESCE((SELECT bdNUMERO FROM SP_RETORNA_NUMEROS(:wIETER)),''))
                  ORDER BY BDCGCTER,BDEDITCHAVE -- Alt.: #199980 #196697 - Deve sempre buscar o menor participante
                  ROWS 1 TO 1;
    
                  wROW_COUNT = ROW_COUNT;
                END

              IF ((wROW_COUNT = 0) AND (:prTIPOVINCULO = 0)) THEN -- Vinculo somente por CNPJ
                BEGIN
                  UPDATE TMP_TTERCEIRO t
                  SET t.bdSESSAO = :prSESSAO,
                      t.bdEDITCHAVE = COALESCE(t.bdEDITCHAVE, :wEDITCHAVE),
                      t.bdCODTER = :wCODTER,
                      t.bdCGCTER = :wCGCTER,
                      t.bdIETER = :wIETER,
                      t.bdAPELIDOTER = :wAPELIDO,
                      t.bdNOMETER = :wNOMETER,
                      t.bdCODCID = :wCODCID,
                      t.bdCODPAIS = :wCODPAIS,
                      t.bdPARTEXIST = 'TRUE'
                  WHERE (t.bdCGCTER = :wCGCTER)
                    AND (t.bdCODPAIS = :wCodBrasil)
                  ORDER BY BDCGCTER,BDEDITCHAVE -- Alt.: #199980 #196697 - Deve sempre buscar o menor participante
                  ROWS 1 TO 1;
                END
            END
            ELSE
            BEGIN
              /*
                 Quando for atualizar por CNPJ, primeiro verificar se existe com mesmo CNPJ e IE, caso não exista, busca pelo CNPJ
                 Por exemplo em importacoes, onde pode nao vir uma inscricao estadual mas ter o participante cadastradao na base com inscricao estadual.
               */
              wROW_COUNT = 0;
              IF (:prTIPOVINCULO <> 0) THEN -- Vinculo somente por CNPJ - Alt.: #203786 - Estava vinculando o participante incorreto, haviam dois participantes na base e deveria atualizar o de menor codigo, porem estava atualizando o de mesmo IE...
                BEGIN
                  UPDATE TMP_TTERCEIRO t
                  SET t.bdSESSAO = :prSESSAO,
                      t.bdCODTER = :wCODTER,
                      t.bdPARTEXIST = 'TRUE',
                      t.bdNOMETER = (IIF(((t.bdNOMETER IS NULL) OR (TRIM(t.bdNOMETER) = '')), :wNOMETER, t.bdNOMETER)), -- Alt.: #171360 - Verifica se o participante tem o nome na TMP, caso não tenha, atualiza...
                      t.bdCODCID = (IIF(((t.bdCODCID IS NULL) OR (t.bdCODCID = 0)), :wCODCID, t.bdCODCID))  -- Alt.: #171360 - Verifica se o participante tem a cidade na TMP, caso não tenha, atualiza...
                  WHERE (t.bdCGCTER = :wCGCTER)
                    AND (t.bdCODPAIS = :wCodBrasil)
                    AND (COALESCE((SELECT bdNUMERO FROM SP_RETORNA_NUMEROS(t.bdIETER)),'') = COALESCE((SELECT bdNUMERO FROM SP_RETORNA_NUMEROS(:wIETER)),''))                        
                  ORDER BY BDCGCTER,BDEDITCHAVE -- Alt.: #199980 #196697 - Deve sempre buscar o menor participante
                  ROWS 1 TO 1;
    
                  wROW_COUNT = ROW_COUNT;
                END

              IF ((wROW_COUNT = 0) AND (:prTIPOVINCULO = 0)) THEN -- Vinculo somente por CNPJ
                BEGIN
                  UPDATE TMP_TTERCEIRO t
                  SET t.bdSESSAO = :prSESSAO,
                      t.bdCODTER = :wCODTER,
                      t.bdPARTEXIST = 'TRUE'
                  WHERE (t.bdCGCTER = :wCGCTER)
                    AND (t.bdCODPAIS = :wCodBrasil)
                  ORDER BY BDCGCTER,BDEDITCHAVE -- Alt.: #199980 #196697 - Deve sempre buscar o menor participante
                  ROWS 1 TO 1;
                END
            END
          END

        /* Se não achou pelo CNPJ e IE, pode ser participante do exterior,
        então é procurado pelo NOME e PAIS */
        --IF (ROW_COUNT = 0) THEN #Alt:21995 - Não estava importando/alterando participantes do exterior
        IF ((ROW_COUNT = 0) OR
            ((:wCGCTER IS NULL) OR (:wCGCTER = ''))) THEN
        BEGIN
          IF ((:wCGCTER IS NULL) OR (:WCGCTER = '')) THEN
            BEGIN
              IF (:PRATUALIZARDADOS = 'TRUE') THEN
              BEGIN
                UPDATE TMP_TTERCEIRO T
                SET T.BDSESSAO = :PRSESSAO,
                    T.BDEDITCHAVE = COALESCE(T.BDEDITCHAVE, :WEDITCHAVE),
                    T.BDCODTER = :WCODTER,
                    T.BDCGCTER = :WCGCTER,
                    T.BDIETER = :WIETER,
                    T.BDAPELIDOTER = :WAPELIDO,
                    T.BDNOMETER = :WNOMETER,
                    T.BDCODCID = :WCODCID,
                    T.BDCODPAIS = :WCODPAIS,
                    T.BDPARTEXIST = 'TRUE'
                WHERE (T.BDNOMETER = :WNOMETER) AND
                      ((T.BDCODPAIS <> :WCODBRASIL) AND
                      (T.BDCGCTER = ''))
                ORDER BY BDCGCTER,BDEDITCHAVE -- Alt.: #199980 #196697 - Deve sempre buscar o menor participante
                ROWS 1 TO 1;
              END
              ELSE
              BEGIN
                UPDATE TMP_TTERCEIRO T
                SET T.BDSESSAO = :PRSESSAO,
                    T.BDCODTER = :WCODTER,
                    T.BDPARTEXIST = 'TRUE'
                WHERE (T.BDNOMETER = :WNOMETER) AND
                      ((T.BDCODPAIS <> :WCODBRASIL) AND
                      (T.BDCGCTER = ''))
                ORDER BY BDCGCTER,BDEDITCHAVE -- Alt.: #199980 #196697 - Deve sempre buscar o menor participante
                ROWS 1 TO 1;
              END

            /* Se ainda não achou, será inserido um novo participante */
            IF (ROW_COUNT = 0) THEN
              BEGIN
                /* Verifica se o apelido já está cadastrado, mas não deve marcar como inconsistente ainda...*/
                WINCONSISTENTE = 'FALSE';
    
                INSERT INTO TMP_TTERCEIRO (BDSESSAO, BDEDITCHAVE, BDCODTER, BDCGCTER, BDIETER,
                                           BDAPELIDOTER, BDNOMETER, BDCODCID, BDCODPAIS, BDPARTEXIST)
                VALUES (:PRSESSAO, :WEDITCHAVE, :WCODTER, :WCGCTER, :WIETER, :WAPELIDO, :WNOMETER,
                        :WCODCID, :WCODPAIS, 'FALSE');
    
                UPDATE TMP_TTERCEIRO_TEMP T SET T.BDAPELIDOTER = :WAPELIDO WHERE (T.bdcodter = :WCODTER);
              END
            END
          ELSE
            BEGIN
              IF (:prATUALIZARDADOS = 'TRUE') THEN
                BEGIN
                  /*
                     Quando for atualizar por CNPJ, primeiro verificar se existe com mesmo CNPJ e IE, caso não exista, busca pelo CNPJ
                     Por exemplo em importacoes, onde pode nao vir uma inscricao estadual mas ter o participante cadastradao na base com inscricao estadual.
                   */
                  wROW_COUNT = 0;
                  IF (:prTIPOVINCULO <> 0) THEN -- Vinculo somente por CNPJ - Alt.: #203786 - Estava vinculando o participante incorreto, haviam dois participantes na base e deveria atualizar o de menor codigo, porem estava atualizando o de mesmo IE...
                    BEGIN
                      UPDATE TMP_TTERCEIRO t
                      SET t.bdSESSAO = :prSESSAO,
                          t.bdEDITCHAVE = COALESCE(t.bdEDITCHAVE, :wEDITCHAVE),
                          t.bdCODTER = :wCODTER,
                          t.bdCGCTER = :wCGCTER,
                          t.bdIETER = :wIETER,
                          t.bdAPELIDOTER = :wAPELIDO,
                          t.bdNOMETER = :wNOMETER,
                          t.bdCODCID = :wCODCID,
                          t.bdCODPAIS = :wCODPAIS,
                          t.bdPARTEXIST = 'TRUE'
                      WHERE (t.bdCGCTER = :wCGCTER)
                        AND (t.bdCODPAIS = :wCodBrasil)
                        AND (COALESCE((SELECT bdNUMERO FROM SP_RETORNA_NUMEROS(t.bdIETER)),'') = COALESCE((SELECT bdNUMERO FROM SP_RETORNA_NUMEROS(:wIETER)),''))
                      ORDER BY BDCGCTER,BDEDITCHAVE -- Alt.: #199980 #196697 - Deve sempre buscar o menor participante
                      ROWS 1 TO 1;
    
                      wROW_COUNT = ROW_COUNT;
                    END

                  IF ((wROW_COUNT = 0) AND (:prTIPOVINCULO = 0)) THEN -- Vinculo somente por CNPJ
                    BEGIN
                      UPDATE TMP_TTERCEIRO t
                      SET t.bdSESSAO = :prSESSAO,
                          t.bdEDITCHAVE = COALESCE(t.bdEDITCHAVE, :wEDITCHAVE),
                          t.bdCODTER = :wCODTER,
                          t.bdCGCTER = :wCGCTER,
                          t.bdIETER = :wIETER,
                          t.bdAPELIDOTER = :wAPELIDO,
                          t.bdNOMETER = :wNOMETER,
                          t.bdCODCID = :wCODCID,
                          t.bdCODPAIS = :wCODPAIS,
                          t.bdPARTEXIST = 'TRUE'
                      WHERE (T.BDCGCTER = :wCGCTER)
                        AND (t.bdCODPAIS = :wCodBrasil)
                      ORDER BY BDCGCTER,BDEDITCHAVE -- Alt.: #199980 #196697 - Deve sempre buscar o menor participante
                      ROWS 1 TO 1;
                    END

                END
              ELSE
                BEGIN
                 /*
                    Quando for atualizar por CNPJ, primeiro verificar se existe com mesmo CNPJ e IE, caso não exista, busca pelo CNPJ
                    Por exemplo em importacoes, onde pode nao vir uma inscricao estadual mas ter o participante cadastradao na base com inscricao estadual.
                  */
                 wROW_COUNT = 0;
                 IF (:prTIPOVINCULO <> 0) THEN -- Vinculo somente por CNPJ - Alt.: #203786 - Estava vinculando o participante incorreto, haviam dois participantes na base e deveria atualizar o de menor codigo, porem estava atualizando o de mesmo IE...
                   BEGIN
                     UPDATE TMP_TTERCEIRO t
                     SET t.bdSESSAO = :prSESSAO,
                         t.bdCODTER = :wCODTER,
                         t.bdPARTEXIST = 'TRUE'
                     WHERE (t.bdCGCTER = :wCGCTER)
                       AND (t.bdCODPAIS = :wCodBrasil)
                       AND (COALESCE((SELECT bdNUMERO FROM SP_RETORNA_NUMEROS(t.bdIETER)),'') = COALESCE((SELECT bdNUMERO FROM SP_RETORNA_NUMEROS(:wIETER)),''))                            
                     ORDER BY BDCGCTER,BDEDITCHAVE -- Alt.: #199980 #196697 - Deve sempre buscar o menor participante
                     ROWS 1 TO 1;
   
                     wROW_COUNT = ROW_COUNT;
                   END

                 IF ((wROW_COUNT = 0) AND (:prTIPOVINCULO = 0)) THEN -- Vinculo somente por CNPJ
                   BEGIN
                     UPDATE TMP_TTERCEIRO t
                     SET t.bdSESSAO = :prSESSAO,
                         t.bdCODTER = :wCODTER,
                         t.bdPARTEXIST = 'TRUE'
                     WHERE (t.bdCGCTER = :wCGCTER)
                       AND (t.bdCODPAIS = :wCodBrasil)
                     ORDER BY BDCGCTER,BDEDITCHAVE -- Alt.: #199980 #196697 - Deve sempre buscar o menor participante
                     ROWS 1 TO 1;
                   END
                END

              /* Se ainda não achou, será inserido um novo participante */

              IF (ROW_COUNT = 0) THEN
              BEGIN
                /* Verifica se o apelido já está cadastrado, mas não deve marcar como inconsistente ainda...*/
                WINCONSISTENTE = 'FALSE';

                INSERT INTO TMP_TTERCEIRO (BDSESSAO, BDEDITCHAVE, BDCODTER, BDCGCTER, BDIETER,
                                           BDAPELIDOTER, BDNOMETER, BDCODCID, BDCODPAIS, BDPARTEXIST)
                VALUES (:PRSESSAO, :WEDITCHAVE, :WCODTER, :WCGCTER, :WIETER, :WAPELIDO, :WNOMETER,
                        :WCODCID, :WCODPAIS, 'FALSE');

                UPDATE TMP_TTERCEIRO_TEMP T SET T.BDAPELIDOTER = :WAPELIDO WHERE (T.bdcodter = :WCODTER);
              END
            END
        END
      END

      /* Caso o registro esteja inconsistente, e tenha editchave deve ser eliminado */
      IF ((:WINCONSISTENTE = 'TRUE') AND (:WEDITCHAVE > 0)) THEN
      BEGIN
        DELETE FROM TMP_TTERCEIRO
        WHERE BDEDITCHAVE = :WEDITCHAVE;
      END
      
      IF ((WEDITCHAVE is null) or (WEDITCHAVE = 0)) THEN
        BEGIN
          SELECT FIRST 1 T.BDEDITCHAVE
          FROM TMP_TTERCEIRO T
          WHERE t.bdSESSAO = :prSESSAO AND t.bdCODTER = :wCODTER AND t.bdPARTEXIST = 'TRUE'
          INTO :WEDITCHAVE;
    END

      IF (:WEDITCHAVE > 0) THEN
        BEGIN
          SELECT FIRST 1 T.BDCGCTER FROM TTERCEIRO T WHERE T.BDCODTER = :wEditChave INTO :wCGCTerBase;

          IF ((WCODPAIS = WCODBRASIL) AND -- Participantes do exterior podem gravar sem CNPJ
              (WCGCTERBASE <> '') AND
              (WCGCTER <> '') AND
              (WCGCTERBASE <> WCGCTER)) THEN
          BEGIN
            /*EXECUTE PROCEDURE LANCA_EXCEPTION('Vínculo incorreto de participantes: '||
                                              ' Participante do arquivo: '||WCODTER||' - '||WCGCTER ||
                                              ' | Participante da base que tentou vincular: '||wCodTerExist||' - '||WCGCTERBASE
                                              , null, null);

            --EXCEPTION ALT_PARTICIPANTE; */

            /* Alt.: #229884 - Se chegou aqui e pegou o participante errado, vai recarregar os participantes para a temporaria e recarregar apenas eles da tabela real */
            -- Vamos guardar os dados da tamporaria e o que estava validando
            INSERT INTO VEF_INCON_TTERCEIROS_VINCULO (BDDATA, BDHORA, BDTMP, BDAVALIDAR, BDPARAM)
            SELECT CURRENT_DATE,
                   CURRENT_TIME,
                   -- Dados da temporaria
                   'BDSESSAO='||COALESCE(BDSESSAO,'NULL')||
                   ',BDEDITCHAVE='||COALESCE(BDEDITCHAVE,'NULL')||
                   ',BDCODTER='||COALESCE(BDCODTER,'NULL')||
                   ',BDCGCTER='||COALESCE(BDCGCTER,'NULL')||
                   ',BDIETER='||COALESCE(BDIETER,'NULL')||
                   ',BDAPELIDOTER='||COALESCE(BDAPELIDOTER,'NULL')||
                   ',BDNOMETER='||COALESCE(BDNOMETER,'NULL')||
                   ',BDCODCID='||COALESCE(BDCODCID,'NULL')||
                   ',BDCODPAIS='||COALESCE(BDCODPAIS,'NULL')||
                   ',BDCODTIPO='||COALESCE(BDCODTIPO,'NULL')||
                   ',BDINCONSISTENTE='||COALESCE(BDINCONSISTENTE,'NULL')||
                   ',BDPARTEXIST='||COALESCE(BDPARTEXIST,'NULL')||
                   ',BDREF_MAX='||COALESCE(BDREF_MAX,'NULL')||
                   ',BDPARTEXIST_FIS='||COALESCE(BDPARTEXIST_FIS,'NULL'),
                   -- Dados do participante validando
                   ':wEDITCHAVE='||COALESCE(:wEDITCHAVE,'NULL')||
                   ',:wCODTER='||COALESCE(:wCODTER,'NULL')||
                   ',:wCGCTER='||COALESCE(:wCGCTER,'NULL')||
                   ',:wIETER='||COALESCE(:wIETER,'NULL')||
                   ',:wAPELIDOTER='||COALESCE(:wAPELIDOTER,'NULL')||
                   ',:wNOMETER='||COALESCE(:wNOMETER,'NULL')||
                   ',:wCODCID='||COALESCE(:wCODCID,'NULL')||
                   ',:wCODPAIS='||COALESCE(:wCODPAIS,'NULL'),
                   -- Paramentros, sei la, vai que precisa
                   ':PRSESSAO='||COALESCE(:PRSESSAO,'NULL')||
                   ',:PRLANCAMENTOMANUAL='||COALESCE(:PRLANCAMENTOMANUAL,'NULL')||
                   ',:PRGERARINCONSISTENCIAS='||COALESCE(:PRGERARINCONSISTENCIAS,'NULL')||
                   ',:PRATUALIZARDADOS='||COALESCE(:PRATUALIZARDADOS,'NULL')||
                   ',:PRHUGEFILE='||COALESCE(:PRHUGEFILE,'NULL')||
                   ',:PRCODTIPO='||COALESCE(:PRCODTIPO,'NULL')||
                   ',:PRTIPOVINCULO='||COALESCE(:PRTIPOVINCULO,'NULL')||
                   ',:PRVINCPORCNPJ_IE='||COALESCE(:PRVINCPORCNPJ_IE,'NULL')
            FROM TMP_TTERCEIRO t
            WHERE t.bdEDITCHAVE = :wEDITCHAVE;

            -- Apaga os dados da temporaria
            DELETE FROM TMP_TTERCEIRO t
            WHERE t.bdSESSAO = :prSESSAO
              AND ((t.bdCODTER = :wEDITCHAVE AND t.bdPARTEXIST = 'TRUE') -- Apaga o participante que pegou a chave, pois est? com CNPJ/CPF errado
                OR (t.bdCGCTER = :wCGCTER)); -- Apaga o que tem o mesmo CNPJ, pois o vinculo deu errado

            -- Insere os mesmos participantes novamente, buscando pelo codigo ou CNPJ/CPF
            INSERT INTO TMP_TTERCEIRO (bdSESSAO, bdEDITCHAVE, bdCODTER, bdCGCTER, bdIETER, bdAPELIDOTER,
                                       bdNOMETER, bdCODCID, bdCODPAIS, bdPARTEXIST, bdREF_MAX, bdPARTEXIST_FIS)
            SELECT 0 bdSESSAO, x.bdCODTER, x.bdCODTER, COALESCE(ter.bdCGCTER, ''), COALESCE(ref.bdIETER, ''), COALESCE(ref.bdAPELIDOTER, ''),
                   COALESCE(ref.bdNOMETER, ''), COALESCE(ref.bdCODCID, 0), COALESCE(ref.bdCODPAIS, 0), 'TRUE', ref.bdREFEMP, 'TRUE'
            FROM (SELECT r.bdCODTER, MAX(r.bdREFEMP) bdREFEMP
                  FROM TTERCEIRO_REF r
                  WHERE r.bdCODTER = :wEDITCHAVE
                     OR r.bdCGCTER = :wCGCTER
                  GROUP BY r.bdCODTER ) X
            INNER JOIN TTERCEIRO ter ON ter.bdCODTER = x.bdCODTER
            INNER JOIN TTERCEIRO_REF ref ON(ref.bdCODTER = x.bdCODTER AND ref.bdREFEMP = x.bdREFEMP)
            WHERE ((ter.bdINATIVO IS NULL) or (ter.bdINATIVO = 'FALSE')); -- Alt.: #203025 - Nao deve carregar participantes inativos

            IF (:prTIPOVINCULO <> 0) THEN -- Vinculo por "CNPJ + IE"
              UPDATE TMP_TTERCEIRO t SET t.bdSESSAO = :prSESSAO WHERE t.bdCGCTER = :wCGCTER AND (COALESCE((SELECT bdNUMERO FROM SP_RETORNA_NUMEROS(t.bdIETER)),'') = COALESCE((SELECT bdNUMERO FROM SP_RETORNA_NUMEROS(:wIETER)),''));

            IF ((wROW_COUNT = 0) OR (:prTIPOVINCULO = 0)) THEN -- Vinculo somente por "CNPJ" ou se nao conseguiu atualizar por CNPJ + IE
              UPDATE TMP_TTERCEIRO t SET t.bdSESSAO = :prSESSAO WHERE t.bdCGCTER = :wCGCTER;

            IF (ROW_COUNT = 0) THEN
              BEGIN -- Se nao encontrou com o mesmo CNPJ
                INSERT INTO TMP_TTERCEIRO (bdSESSAO , bdEDITCHAVE, bdCODTER, bdCGCTER, bdIETER, bdAPELIDOTER, bdNOMETER, bdCODCID, bdCODPAIS, bdPARTEXIST, bdPARTEXIST_FIS)
                                   VALUES (:prSESSAO, /*:wEDITCHAVE*/0, :wCODTER, :wCGCTER, :wIETER, :wAPELIDO   , :wNOMETER, :wCODCID, :wCODPAIS, 'FALSE'    , 'FALSE');
              END
          END
        END
    END
  END
    /*Todos os participantes novos tem como apelido o CPF/CNPJ/CEI*/
    UPDATE TMP_TTERCEIRO T SET T.BDAPELIDOTER = IIF(T.BDCGCTER = '', SUBSTRING(T.BDNOMETER FROM 1 FOR 20), T.BDCGCTER)
    WHERE T.BDSESSAO = :PRSESSAO
    AND T.BDAPELIDOTER <> T.BDCGCTER
    AND T.BDEDITCHAVE = 0;
    IF (:PRHUGEFILE = 'TRUE') THEN
      BEGIN
        UPDATE TMP_TTERCEIRO_TEMP T SET T.BDAPELIDOTER = T.BDCGCTER
        WHERE T.BDSESSAO = :PRSESSAO
        AND ((T.BDCGCTER IS NOT NULL) OR (T.BDCGCTER <> ''));
        UPDATE TMP_TTERCEIRO_TEMP T SET T.BDAPELIDOTER = SUBSTRING(T.BDNOMETER FROM 1 FOR 20)
        WHERE T.BDSESSAO = :PRSESSAO
        AND ((T.BDCGCTER IS NULL) OR (T.BDCGCTER = ''));
      END
    ELSE
      BEGIN
        /*Verifica se o participante existe na tabela fisica*/
        UPDATE TMP_TTERCEIRO T SET T.BDPARTEXIST_FIS = (SELECT 'TRUE' BDPARTEXIST_FIS FROM TTERCEIRO TER WHERE TER.BDCODTER = T.BDEDITCHAVE)
        WHERE T.BDSESSAO = :PRSESSAO
        AND T.BDEDITCHAVE IS NOT NULL;
      END
END
^

CREATE OR ALTER PROCEDURE SP_CONTABILIZAR_LANCAMENTO (
    PRSESSAO INTEGER,
    PRULTCHAVE INTEGER,
    PRUSUARIO INTEGER,
    PRTRANSACAO INTEGER,
    PRTIPOLAN VARCHAR(4))
AS
DECLARE VARIABLE WTABLE VARCHAR(50);
DECLARE VARIABLE WTABLEITENS VARCHAR(50);
DECLARE VARIABLE WTABLERATEIO VARCHAR(50);
DECLARE VARIABLE WCAMPOTOL VARCHAR(20);
DECLARE VARIABLE WSQL VARCHAR(3000);
DECLARE VARIABLE WTABLECC VARCHAR(32);
DECLARE VARIABLE WRATEIOIMPOSTOS VARCHAR(5);
DECLARE VARIABLE WREFLAN INTEGER;
declare variable WCODEMPSCP integer;
declare variable WQTDSCP integer;
BEGIN
  /*Sol : 14207 Patrick T. Sá 09/06/2016. Criada contabilização no banco.*/

  /*Insere os registros no contábil*/
  /*Cria o gerador para o sequencial. Por Exemplo: Chave 1 tem valor contábil e icms, então há 2 registros com chave 1 na tabela TMP_TLANC_CONTABILIZACAO_TEMP, porém são 2 chaves para o
  contábil, se fizer bdchave(1) - bdchave_vsuc(8) = 8(faz na trigger da tabela), chaves duplicadas, com o gerador isso não acontece, é criado e destruido um gerador para cada sessão(terminal)*/
  SETTRANSACAO_CONTABIL(:PRSESSAO, :PRTRANSACAO);
  wSql = 'CREATE SEQUENCE GEN_ICMS115_'||:PRSESSAO;
  EXECUTE STATEMENT wSql;

  wSql =         'UPDATE TMP_TLANC_CONTABILIZACAO_TEMP I SET I.BDCHAVE_VSUC = '||:PRULTCHAVE||', ';
  wSql = wSql || 'I.BDTRANSACAO = GETTRANSACAO_CONTABIL(I.BDSESSAO, I.BDCODEMP, I.BDCHAVE), ';
  wSql = wSql || 'I.BDSEQ = GEN_ID(GEN_ICMS115_'||:PRSESSAO||', 1) ';
  wSql = wSql || 'WHERE BDSESSAO = '||:PRSESSAO;
  wSql = wSql || 'AND ((BDCODEMPSCP IS NULL) OR (BDCODEMPSCP = 0)) ';
  wSql = wSql || 'ORDER BY BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM DESC, BDORD DESC, BDFORMULA DESC'; -- Alt.: #169309 - Incluido o campo "bdORDEM" para ordenar quando tiver mais de uma CFOP na nota...

  EXECUTE STATEMENT wSql;

  REMOVERTRANSACAO_CONTABIL(:PRSESSAO);
  wSql = 'DROP SEQUENCE GEN_ICMS115_'||:PRSESSAO;
  EXECUTE STATEMENT wSql;

  FOR
    SELECT c.bdCODEMPSCP, COUNT(*) AS bdQTD, cscp.bdCHAVECONT, cscp.bdTRANSACAO
    FROM TMP_TLANC_CONTABILIZACAO_TEMP c
    JOIN TMP_TLANC_CONTAB_CODEMPSCP_TEMP cscp ON(cscp.bdCODEMPSCP = c.bdCODEMPSCP AND cscp.bdSESSAO = c.bdSESSAO)
    WHERE c.bdSESSAO = :PRSESSAO
      AND c.bdCODEMPSCP IS NOT NULL
    GROUP BY c.bdCODEMPSCP, cscp.bdCHAVECONT, cscp.bdTRANSACAO
    INTO WCODEMPSCP,WQTDSCP,prULTCHAVE,prTRANSACAO
  DO
  BEGIN
      /*PEGAR A CHAVE SEQUENCIAL CONTÁBIL DO SCP */
      SETTRANSACAO_CONTABIL(:PRSESSAO, :PRTRANSACAO);
      wSql = 'CREATE SEQUENCE GEN_SCP'||:PRSESSAO;
      EXECUTE STATEMENT wSql;
    
      wSql =         'UPDATE TMP_TLANC_CONTABILIZACAO_TEMP I SET I.BDCHAVE_VSUC = '||:PRULTCHAVE||', ';
      wSql = wSql || 'I.BDTRANSACAO = GETTRANSACAO_CONTABIL(I.BDSESSAO, I.BDCODEMP, I.BDCHAVE), ';
      wSql = wSql || 'I.BDSEQ = GEN_ID(GEN_SCP'||:PRSESSAO||', 1) ';
      wSql = wSql || 'WHERE BDSESSAO = '||:PRSESSAO;
      wSql = wSql || 'AND BDCODEMPSCP = '||:WCODEMPSCP;
      wSql = wSql || 'ORDER BY BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM DESC, BDORD DESC, BDFORMULA DESC'; -- Alt.: #169309 - Incluido o campo "bdORDEM" para ordenar quando tiver mais de uma CFOP na nota...
    
      EXECUTE STATEMENT wSql;
    
      REMOVERTRANSACAO_CONTABIL(:PRSESSAO);
      wSql = 'DROP SEQUENCE GEN_SCP'||:PRSESSAO;
      EXECUTE STATEMENT wSql;
  END
  
  /*Para não dar problemas nos COALESCE*/
  UPDATE TMP_TLANC_CONTABILIZACAO_TEMP SET
  BDCODEMPSCP = NULL
  WHERE BDCODEMPSCP = 0 AND BDSESSAO = :PRSESSAO;  

  wTable = '';
  wCampoTol = '';
  wTableRateio = '';
  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTable = 'VEF_EMP_TMOVENT';
      wTableItens = 'VEF_EMP_TMOVENTITENS';
      wCampoTol = 'BDCHAVEENT';
      --wTableRateio = 'VEF_EMP_TMOVRATENT'; #Não vamos fazer rateio até segunda ordem, o Elizeu quer fazer algumas configurações para validação e seleção das contas.#
      wTableCC = 'VEF_EMP_TMOVCCENT';
    END
  ELSE
  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTable = 'VEF_EMP_TMOVSAI';
      wTableItens = 'VEF_EMP_TMOVSAIITENS';
      wCampoTol = 'BDCHAVESAI';
      --wTableRateio = 'VEF_EMP_TMOVRATSAI'; #Não vamos fazer rateio até segunda ordem, o Elizeu quer fazer algumas configurações para validação e seleção das contas.#
      wTableCC = 'VEF_EMP_TMOVCCSAI';
    END
  ELSE
  IF (:PRTIPOLAN = 'SER') THEN
    BEGIN
      wTable = 'VEF_EMP_TMOVSER';
      wTableItens = 'VEF_EMP_TMOVSERITENS';
      wCampoTol = 'BDCHAVESER';
      wTableRateio = 'VEF_EMP_TMOVRATSER';
      wTableCC = 'VEF_EMP_TMOVCCSER';
    END
  ELSE
  IF (:PRTIPOLAN = 'REDZ') THEN
    wTable = 'VEF_EMP_TREDZ';

  IF (:wTable = '') THEN
    EXIT;

  wREFLAN = 0;
  wSQL =          ' SELECT (EXTRACT (YEAR FROM BDDATA) || LPAD(EXTRACT (MONTH FROM BDDATA),2,''0'')) BDREFLAN ';
  wSQL = :wSQL || ' FROM ( SELECT MIN(C.BDDATA) AS BDDATA FROM TMP_TLANC_CONTABILIZACAO_TEMP C ';
  wSQL = :wSQL || ' WHERE C.BDSESSAO = '||:prSESSAO || ')';
  EXECUTE STATEMENT :wSQL INTO :wREFLAN;

  IF (:wREFLAN > 0) THEN
    EXECUTE PROCEDURE SP_SETA_COMPETENCIA (:wREFLAN);

  wSQL =           ' select cc.bdRATEIOIMPOSTOS ';
  wSQL = :wSQL ||  ' from VW_EMPRESAS_REF_ATUAL emp ';
  wSQL = :wSQL ||  ' left outer join TCENTROS cc on (cc.bdCODCENTRO = emp.bdCODCENTROS) ';
  wSQL = :wSQL ||  ' where emp.bdCODEMP = (select first 1 mov.bdCODEMP ';
  wSQL = :wSQL ||                          'from TMP_'||:wTable||'_TEMP mov ';
  wSQL = :wSQL ||                          'where mov.bdSESSAO = '||:PRSESSAO||'); ';
  EXECUTE STATEMENT :wSQL INTO :wRATEIOIMPOSTOS;

    /*Camilla M. 11/09/2020 - Ajuste para contabilizar o SCP*/
  wSQL =          'INSERT INTO VSUC_EMPRESAS_TLAN(BDCODEMP, BDCHAVE, BDCODPLAPADRAO, BDCODUSU, BDDEBITO, BDCREDITO, BDCOMPL, ';
  wSQL = :wSQL ||                                'BDDATA, BDVALOR, BDTIPOLAN, BDDCTO, BDTRANSACAO, BDTRANFECHADA, BDCODHIST, BDCODTPHI, BDCODTERCEIROD, BDCODTERCEIROC) ';
  wSQL = :wSQL || 'SELECT COALESCE(C.BDCODEMPSCP,C.BDCODEMP) BDCODEMP, C.BDCHAVE_VSUC, C.BDCODPLAPADRAO, '||:PRUSUARIO||', C.BDDEBITO, C.BDCREDITO, SUBSTRING(C.BDCOMPL from 1 for 200) , C.BDDATA, ';
  wSQL = :wSQL ||        'C.BDVALOR, C.BDTIPOLAN, C.BDDCTO, C.BDTRANSACAO, C.BDTRANFECHADA, C.BDCODHIST, C.BDCODTPHI, ';
  --elizeu - 12-11-18 - Ajuste para gravar o código do participante na importação da redução z e todos dos demais lugares que usam contabilização - Importação Sped Fiscal - Redução Z - Contabilização #92609
  IF (:PRTIPOLAN = 'REDZ') THEN
    wSQL = :wSQL ||        'IIF(pDeb.bdPARTICIPANTE = 1, CFOP.bdCODTER, NULL), IIF(pCre.bdPARTICIPANTE = 1, CFOP.bdCODTER, NULL) ';
  ELSE
    wSQL = :wSQL ||        'IIF(pDeb.bdPARTICIPANTE = 1, mov.bdCODTER, NULL), IIF(pCre.bdPARTICIPANTE = 1, mov.bdCODTER, NULL) ';
  wSQL = :wSQL || 'FROM TMP_TLANC_CONTABILIZACAO_TEMP C ';
  wSQL = :wSQL || 'JOIN '||:wTable||' mov ON(mov.BDCODEMP = C.BDCODEMP AND mov.BDCHAVE = C.BDCHAVE) ';
  IF (:PRTIPOLAN = 'REDZ') THEN
    wSQL = :wSQL || 'LEFT OUTER JOIN VEF_EMP_TREDZVARCFOP CFOP ON (MOV.BDCODEMP = CFOP.BDCODEMP AND MOV.BDCHAVE = CFOP.BDCHAVE) ';

  wSQL = :wSQL || 'LEFT OUTER JOIN PLANOS_TPLA pDeb ON (pDeb.bdCODPLAPADRAO = c.bdCODPLAPADRAO AND pDeb.bdCODTPLA = c.bdDEBITO) ';
  wSQL = :wSQL || 'LEFT OUTER JOIN PLANOS_TPLA pCre ON (pCre.bdCODPLAPADRAO = c.bdCODPLAPADRAO AND pCre.bdCODTPLA = c.bdCREDITO) ';
  wSQL = :wSQL || 'WHERE C.BDSESSAO = '||:PRSESSAO;
  IF (:PRTIPOLAN = 'REDZ') THEN
    wSQL = :wSQL || 'AND CFOP.bdordemvarcfop = COALESCE((SELECT MIN(CF.bdordemvarcfop) FROM VEF_EMP_TREDZVARCFOP CF WHERE CF.BDCODEMP = MOV.BDCODEMP AND CF.BDCHAVE = MOV.BDCHAVE GROUP BY  BDCODEMP, BDCHAVE), 1) ';

  wSQL = :wSQL || 'ORDER BY C.BDSESSAO, C.BDCODEMP, C.BDCHAVE, C.BDORD;';
  EXECUTE STATEMENT :wSQL;

  INSERT INTO VSUC_EMPRESAS_TLINCORP (BDCODEMP, BDCHAVE, BDDEBCRE, BDCODEMPREENDIMENTO, BDCODIGOUNIIMOB) -- Alt.: Vínculo de Empreendimento nas Saídas #Contábil!
  SELECT c.bdCODEMP, c.bdCHAVE_VSUC, c.bdDEBCRE, c.bdCODEMPREENDIMENTO, c.BDCODIGOUNIIMOB
  FROM (
        --SELECT c.bdCODEMP, c.bdCHAVE_VSUC, 0 AS bdDEBCRE, c.bdCODEMPREENDIMENTO, NULL AS BDCODIGOUNIIMOB Alt.: #243754 - Deve contabilizar corretamente nas SCPs
        SELECT COALESCE(c.bdCODEMPSCP,c.bdCODEMP) AS bdCODEMP, c.bdCHAVE_VSUC, 0 AS bdDEBCRE, c.bdCODEMPREENDIMENTO, NULL AS BDCODIGOUNIIMOB
        FROM TMP_TLANC_CONTABILIZACAO_TEMP c
        WHERE c.bdSESSAO = :prSESSAO
          AND c.bdEMPREENDIMENTOPROVD = 'TRUE'
          AND c.bdCODEMPREENDIMENTO > 0
        UNION ALL
        --SELECT c.bdCODEMP, c.bdCHAVE_VSUC, 1 AS bdDEBCRE, c.bdCODEMPREENDIMENTO, NULL AS BDCODIGOUNIIMOB
        SELECT COALESCE(c.bdCODEMPSCP,c.bdCODEMP) AS bdCODEMP, c.bdCHAVE_VSUC, 1 AS bdDEBCRE, c.bdCODEMPREENDIMENTO, NULL AS BDCODIGOUNIIMOB
        FROM TMP_TLANC_CONTABILIZACAO_TEMP c
        WHERE c.bdSESSAO = :prSESSAO
          AND c.bdEMPREENDIMENTOPROVC = 'TRUE'
          AND c.bdCODEMPREENDIMENTO > 0
        ) c
  ORDER BY c.bdCODEMP, c.bdCHAVE_VSUC, c.bdDEBCRE;

  /*Insert na tol*/
  IF ((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SER')) THEN
    BEGIN
      /*Insert na VSUC_EMPRESAS_TLCC */
      wSQL =          'insert into VSUC_EMPRESAS_TLCC (bdCODEMP, bdCHAVE, bdCODCENTRO, bdCODTPCC, bdDEBCRE, bdPERCENTUAL, bdVALOR) ';
      wSQL = :wSQL || 'select COALESCE(C.BDCODEMPSCP,c.bdCODEMP) BDCODEMP, c.bdCHAVE_VSUC, cc.bdCODCENTRO, cc.bdCODTPCC, ';
      wSQL = :wSQL ||       ' CASE WHEN '''||:prTIPOLAN||''' = ''ENT'' THEN IIF((c.bdCODITEMONLINE in (111,117,170)), Coalesce(cc.BDDEBCRED,0), IIF(Coalesce(cc.BDDEBCRED,0) = 0,1,0))  ';
      wSQL = :wSQL ||            ' WHEN '''||:prTIPOLAN||''' = ''SAI'' THEN IIF((c.bdCODITEMONLINE in (111,117,170)), Coalesce(cc.BDDEBCRED,1), IIF(Coalesce(cc.BDDEBCRED,1) = 1,0,1))  ';
      wSQL = :wSQL ||       ' ELSE -1 ';
      wSQL = :wSQL ||       ' END as bdDEBCRE, cc.bdPERCENTUAL, ';

      IF (:PRTIPOLAN = 'SER') THEN
        BEGIN
          wSQL = :wSQL ||       ' CASE ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (148,149,176)) THEN (i.bdVLRISSSER*cc.bdPERCENTUAL)/100 /* ISS */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (115,121,174)) THEN (i.bdVLRPIS*cc.bdPERCENTUAL)/100 /* PIS */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (116,122,175)) THEN (i.bdVLRCOFINS*cc.bdPERCENTUAL)/100 /* Cofins */ ';
          wSQL = :wSQL ||       ' ELSE cc.bdVALOR ';
          wSQL = :wSQL ||       ' END as BDVALOR ';
        END
      ELSE
        BEGIN
          wSQL = :wSQL ||       ' CASE ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (112,118,171)) THEN (i.bdVLRICMS*cc.bdPERCENTUAL)/100 /* ICMS */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (113,119,172)) THEN (i.bdVLRST*cc.bdPERCENTUAL)/100 /* ST */ ';
          IF (:PRTIPOLAN = 'ENT') THEN
            wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (219,220,221)) THEN (i.bdDIFALIQENT*cc.bdPERCENTUAL)/100 /* Dif. Aliq. */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (114,120,173)) THEN (i.bdVLRIPI*cc.bdPERCENTUAL)/100 /* IPI */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (115,121,174)) THEN (i.bdVLRPIS*cc.bdPERCENTUAL)/100 /* PIS */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (116,122,175)) THEN (i.bdVLRCOFINS*cc.bdPERCENTUAL)/100 /* Cofins */ ';
          wSQL = :wSQL ||       ' ELSE cc.bdVALOR ';
          wSQL = :wSQL ||       ' END as BDVALOR ';
        END

      wSQL = :wSQL || 'from TMP_TLANC_CONTABILIZACAO_TEMP c ';
      wSQL = :wSQL || 'join '||wTableItens||' i on (i.bdCODEMP = c.bdCODEMP and i.bdCHAVE = c.bdCHAVE and i.bdORDEM = c.bdORDEM) ';
      wSQL = :wSQL || 'join '||wTableCC||' cc on (cc.bdCODEMP = c.bdCODEMP and cc.bdCHAVE = c.bdCHAVE and cc.bdORDEM = c.bdORDEM) ';
      wSQL = :wSQL || 'where c.bdSESSAO = '||:PRSESSAO;
      wSQL = :wSQL || '  and Coalesce(cc.BDDEBCRED,0) <> 2 ';
      wSQL = :wSQL || '  and c.bdCODITEMONLINE in (111/*NATVLAN*/, 117/*NATPLAN*/, 170/*NATOLAN*/'; /* Valor Contabil */ -- Valor contáil sempre lança centro de custo...
      IF (:wRATEIOIMPOSTOS = 'TRUE') THEN
        BEGIN
          wSQL = :wSQL ||                       ', 112/*NATVICMS*/,   118/*NATPICMS*/,   171/*NATOICMS*/, '; /* ICMS */
          wSQL = :wSQL ||                         '113/*NATVICMSST*/, 119/*NATPICMSST*/, 172/*NATOICMSST*/, '; /* ST */
          wSQL = :wSQL ||                         '219/*NATVDIF*/,    220/*NATPDIF*/,    221/*NATODIF*/, '; /* Dif. Aliq. */
          wSQL = :wSQL ||                         '114/*NATVIPI*/,    120/*NATPIPI*/,    173/*NATOIPI*/, '; /* IPI */
          wSQL = :wSQL ||                         '115/*NATVPIS*/,    121/*NATPPIS*/,    174/*NATOPIS*/, '; /* PIS */
          wSQL = :wSQL ||                         '116/*NATVCOFINS*/, 122/*NATPCOFINS*/, 175/*NATOCOFINS*/, '; /* Cofins */
          wSQL = :wSQL ||                         '148/*NATVISS*/,    149/*NATPISS*/,    176/*NATOISS*/'; /* ISS */
        END
      wSQL = :wSQL ||                             ') ';
      wSQL = :wSQL || 'order by c.bdSESSAO, c.bdCODEMP, c.bdCHAVE, c.bdORD; ';
      EXECUTE STATEMENT :wSQL;

      -- REALIZA O LANCAMENTO DO DEBITO PARA CC CONFIGURADO COMO 'AMBOS'
      wSQL =          'insert into VSUC_EMPRESAS_TLCC (bdCODEMP, bdCHAVE, bdCODCENTRO, bdCODTPCC, bdDEBCRE, bdPERCENTUAL, bdVALOR) ';
      wSQL = :wSQL || 'select COALESCE(C.BDCODEMPSCP,c.bdCODEMP) BDCODEMP, c.bdCHAVE_VSUC, cc.bdCODCENTRO, cc.bdCODTPCC, ';
      wSQL = :wSQL ||       ' 0 bdDEBCRE, cc.bdPERCENTUAL, ';

      IF (:PRTIPOLAN = 'SER') THEN
        BEGIN
          wSQL = :wSQL ||       ' CASE ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (148,149,176)) THEN (i.bdVLRISSSER*cc.bdPERCENTUAL)/100 /* ISS */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (115,121,174)) THEN (i.bdVLRPIS*cc.bdPERCENTUAL)/100 /* PIS */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (116,122,175)) THEN (i.bdVLRCOFINS*cc.bdPERCENTUAL)/100 /* Cofins */ ';
          wSQL = :wSQL ||       ' ELSE cc.bdVALOR ';
          wSQL = :wSQL ||       ' END as BDVALOR ';
        END
      ELSE
        BEGIN
          wSQL = :wSQL ||       ' CASE ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (112,118,171)) THEN (i.bdVLRICMS*cc.bdPERCENTUAL)/100 /* ICMS */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (113,119,172)) THEN (i.bdVLRST*cc.bdPERCENTUAL)/100 /* ST */ ';
          IF (:PRTIPOLAN = 'ENT') THEN
            wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (219,220,221)) THEN (i.bdDIFALIQENT*cc.bdPERCENTUAL)/100 /* Dif. Aliq. */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (114,120,173)) THEN (i.bdVLRIPI*cc.bdPERCENTUAL)/100 /* IPI */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (115,121,174)) THEN (i.bdVLRPIS*cc.bdPERCENTUAL)/100 /* PIS */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (116,122,175)) THEN (i.bdVLRCOFINS*cc.bdPERCENTUAL)/100 /* Cofins */ ';
          wSQL = :wSQL ||       ' ELSE cc.bdVALOR ';
          wSQL = :wSQL ||       ' END as BDVALOR ';
        END

      wSQL = :wSQL || 'from TMP_TLANC_CONTABILIZACAO_TEMP c ';
      wSQL = :wSQL || 'join '||wTableItens||' i on (i.bdCODEMP = c.bdCODEMP and i.bdCHAVE = c.bdCHAVE and i.bdORDEM = c.bdORDEM) ';
      wSQL = :wSQL || 'join '||wTableCC||' cc on (cc.bdCODEMP = c.bdCODEMP and cc.bdCHAVE = c.bdCHAVE and cc.bdORDEM = c.bdORDEM) ';
      wSQL = :wSQL || 'where c.bdSESSAO = '||:PRSESSAO;          
      wSQL = :wSQL || '  and Coalesce(cc.BDDEBCRED,0) = 2 ';
      wSQL = :wSQL || '  and c.bdCODITEMONLINE in (111/*NATVLAN*/, 117/*NATPLAN*/, 170/*NATOLAN*/'; /* Valor Contabil */ -- Valor contáil sempre lança centro de custo...
      IF (:wRATEIOIMPOSTOS = 'TRUE') THEN
        BEGIN
          wSQL = :wSQL ||                       ', 112/*NATVICMS*/,   118/*NATPICMS*/,   171/*NATOICMS*/, '; /* ICMS */
          wSQL = :wSQL ||                         '113/*NATVICMSST*/, 119/*NATPICMSST*/, 172/*NATOICMSST*/, '; /* ST */
          wSQL = :wSQL ||                         '219/*NATVDIF*/,    220/*NATPDIF*/,    221/*NATODIF*/, '; /* Dif. Aliq. */
          wSQL = :wSQL ||                         '114/*NATVIPI*/,    120/*NATPIPI*/,    173/*NATOIPI*/, '; /* IPI */
          wSQL = :wSQL ||                         '115/*NATVPIS*/,    121/*NATPPIS*/,    174/*NATOPIS*/, '; /* PIS */
          wSQL = :wSQL ||                         '116/*NATVCOFINS*/, 122/*NATPCOFINS*/, 175/*NATOCOFINS*/, '; /* Cofins */
          wSQL = :wSQL ||                         '148/*NATVISS*/,    149/*NATPISS*/,    176/*NATOISS*/'; /* ISS */
        END
      wSQL = :wSQL ||                             ') ';
      wSQL = :wSQL || 'order by c.bdSESSAO, c.bdCODEMP, c.bdCHAVE, c.bdORD; ';
      EXECUTE STATEMENT :wSQL;
                            
      -- REALIZA O LANCAMENTO DO CREDITO PARA CC CONFIGURADO COMO 'AMBOS'
      wSQL =          'insert into VSUC_EMPRESAS_TLCC (bdCODEMP, bdCHAVE, bdCODCENTRO, bdCODTPCC, bdDEBCRE, bdPERCENTUAL, bdVALOR) ';
      wSQL = :wSQL || 'select COALESCE(C.BDCODEMPSCP,c.bdCODEMP) BDCODEMP, c.bdCHAVE_VSUC, cc.bdCODCENTRO, cc.bdCODTPCC, ';
      wSQL = :wSQL ||       ' 1 bdDEBCRE, cc.bdPERCENTUAL, ';

      IF (:PRTIPOLAN = 'SER') THEN
        BEGIN
          wSQL = :wSQL ||       ' CASE ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (148,149,176)) THEN (i.bdVLRISSSER*cc.bdPERCENTUAL)/100 /* ISS */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (115,121,174)) THEN (i.bdVLRPIS*cc.bdPERCENTUAL)/100 /* PIS */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (116,122,175)) THEN (i.bdVLRCOFINS*cc.bdPERCENTUAL)/100 /* Cofins */ ';
          wSQL = :wSQL ||       ' ELSE cc.bdVALOR ';
          wSQL = :wSQL ||       ' END as BDVALOR ';
        END
      ELSE
        BEGIN
          wSQL = :wSQL ||       ' CASE ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (112,118,171)) THEN (i.bdVLRICMS*cc.bdPERCENTUAL)/100 /* ICMS */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (113,119,172)) THEN (i.bdVLRST*cc.bdPERCENTUAL)/100 /* ST */ ';
          IF (:PRTIPOLAN = 'ENT') THEN
            wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (219,220,221)) THEN (i.bdDIFALIQENT*cc.bdPERCENTUAL)/100 /* Dif. Aliq. */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (114,120,173)) THEN (i.bdVLRIPI*cc.bdPERCENTUAL)/100 /* IPI */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (115,121,174)) THEN (i.bdVLRPIS*cc.bdPERCENTUAL)/100 /* PIS */ ';
          wSQL = :wSQL ||          ' WHEN (c.bdCODITEMONLINE in (116,122,175)) THEN (i.bdVLRCOFINS*cc.bdPERCENTUAL)/100 /* Cofins */ ';
          wSQL = :wSQL ||       ' ELSE cc.bdVALOR ';
          wSQL = :wSQL ||       ' END as BDVALOR ';
        END

      wSQL = :wSQL || 'from TMP_TLANC_CONTABILIZACAO_TEMP c ';
      wSQL = :wSQL || 'join '||wTableItens||' i on (i.bdCODEMP = c.bdCODEMP and i.bdCHAVE = c.bdCHAVE and i.bdORDEM = c.bdORDEM) ';
      wSQL = :wSQL || 'join '||wTableCC||' cc on (cc.bdCODEMP = c.bdCODEMP and cc.bdCHAVE = c.bdCHAVE and cc.bdORDEM = c.bdORDEM) ';
      wSQL = :wSQL || 'where c.bdSESSAO = '||:PRSESSAO;          
      wSQL = :wSQL || '  and Coalesce(cc.BDDEBCRED,0) = 2 ';
      wSQL = :wSQL || '  and c.bdCODITEMONLINE in (111/*NATVLAN*/, 117/*NATPLAN*/, 170/*NATOLAN*/'; /* Valor Contabil */ -- Valor contáil sempre lança centro de custo...
      IF (:wRATEIOIMPOSTOS = 'TRUE') THEN
        BEGIN
          wSQL = :wSQL ||                       ', 112/*NATVICMS*/,   118/*NATPICMS*/,   171/*NATOICMS*/, '; /* ICMS */
          wSQL = :wSQL ||                         '113/*NATVICMSST*/, 119/*NATPICMSST*/, 172/*NATOICMSST*/, '; /* ST */
          wSQL = :wSQL ||                         '219/*NATVDIF*/,    220/*NATPDIF*/,    221/*NATODIF*/, '; /* Dif. Aliq. */
          wSQL = :wSQL ||                         '114/*NATVIPI*/,    120/*NATPIPI*/,    173/*NATOIPI*/, '; /* IPI */
          wSQL = :wSQL ||                         '115/*NATVPIS*/,    121/*NATPPIS*/,    174/*NATOPIS*/, '; /* PIS */
          wSQL = :wSQL ||                         '116/*NATVCOFINS*/, 122/*NATPCOFINS*/, 175/*NATOCOFINS*/, '; /* Cofins */
          wSQL = :wSQL ||                         '148/*NATVISS*/,    149/*NATPISS*/,    176/*NATOISS*/'; /* ISS */
        END
      wSQL = :wSQL ||                             ') ';
      wSQL = :wSQL || 'order by c.bdSESSAO, c.bdCODEMP, c.bdCHAVE, c.bdORD; ';
      EXECUTE STATEMENT :wSQL;

      /*Insert na TOL_VEF_EMP_TMOVXXX */
      wSQL =          'INSERT INTO TOL_'||wTable||'(BDCHAVE, BDCODEMP, '||wCampoTol||', BDORDEM, BDFORMULA, BDCODEMPSUC) ';
      wSQL = :wSQL || 'SELECT C.BDCHAVE_VSUC, C.BDCODEMP, C.BDCHAVE, C.BDORDEM, C.BDFORMULA, COALESCE(C.BDCODEMPSCP,C.BDCODEMP) BDCODEMPSUC ';
      wSQL = :wSQL || 'FROM TMP_TLANC_CONTABILIZACAO_TEMP C ';
      wSQL = :wSQL || 'JOIN '||wTable||' mov ON(mov.BDCODEMP = C.BDCODEMP AND mov.BDCHAVE = C.BDCHAVE) ';
      IF (wTableRateio <> '') THEN
        wSQL = :wSQL || 'left outer join TMP_'||wTableRateio||'_TEMP rat on (rat.bdCODEMP = c.bdCODEMP and rat.bdCHAVE = c.bdCHAVE and rat.bdORDEM = c.bdORDEM and rat.bdSESSAO = c.bdSESSAO) '; -- Rateio vão fazer contabilização própria e não aqui
      wSQL = :wSQL || 'WHERE C.BDSESSAO =  '||:PRSESSAO;
      IF (wTableRateio <> '') THEN
        wSQL = :wSQL ||  ' and rat.bdCODEMP IS NULL '; -- Somente quando não tiver rateio no lançamento
                      --AND ((mov.BDCHAVE IS NOT NULL) OR (mov.BDCHAVE > 0))
      wSQL = :wSQL || 'ORDER BY C.BDSESSAO, C.BDCODEMP, C.BDCHAVE, C.BDORD; ';
      EXECUTE STATEMENT :wSQL;

    --PRODUTOR RURAL

      INSERT INTO VSUC_EMPRESAS_TLPR (bdcodemp, bdchave, bdcodimovrur, bdtipmov, bdctacor, bdcodter, bdtipdoc, bdtiplan, bdtipope,
                                      bdtransferencia, bdtranstipmov,  bdtranstipope)
      SELECT bdcodemp, bdCHAVE_VSUC, bdcodimovrur, bdtipmov, bdctacor, bdcodter, bdtipdoc, bdtiplan, bdtipope,
             'FALSE' BDTRANSFERENCIA,IIF(BDTIPOPE=0,'0','1') BDTRANSTIPMOV, IIF(BDTIPOPE=0,'1','0')  bdtranstipope
      FROM (
            SELECT c.bdCODEMP, c.bdCHAVE_VSUC, bdcodimovrur, bdtipmov, bdctacor, bdcodter, bdtipdoc, bdtiplan, bdtipope
            FROM (
                  SELECT c.bdCODEMP, c.bdCHAVE_VSUC, bdcodimovrur, bdtipmov, bdctacor, bdcodter, bdtipdoc, bdtiplan, bdtipope,C.bdCODPLAPADRAO,C.bddebito,C.bdcredito
                  FROM TMP_TLANC_CONTABILIZACAO_TEMP c
                  WHERE c.bdSESSAO = :prSESSAO
                    AND c.bdcodimovrur > 0
                  ) C
            LEFT OUTER JOIN PLANOS_TPLA pDeb ON (pDeb.bdCODPLAPADRAO = c.bdCODPLAPADRAO AND pDeb.bdCODTPLA = c.bdDEBITO)
            LEFT OUTER JOIN PLANOS_TPLA pCre ON (pCre.bdCODPLAPADRAO = c.bdCODPLAPADRAO AND pCre.bdCODTPLA = c.bdCREDITO)
            WHERE ((PDEB.BDCTACAIXAPR = 'TRUE') or (PDEB.bdctabancopr = 'TRUE'))
               OR ((pCre.BDCTACAIXAPR = 'TRUE') or (pCre.bdctabancopr = 'TRUE'))
            ) c   ;
    --------

      /*Insert na TOL_VEF_EMP_TMOVRATXXX */
      IF (wTableRateio <> '') THEN
        BEGIN
          wSQL =          'insert into TOL_'||wTableRateio||' (bdCHAVE, bdCODEMP, bdCHAVELAN, bdORDEM, bdORDEMRAT, bdFORMULA, BDCODEMPSUC) ';
          wSQL = :wSQL || 'select c.bdCHAVE_VSUC, c.bdCODEMP, rat.bdCHAVE, rat.bdORDEM, rat.bdORDEMRAT, c.bdFORMULA, COALESCE(C.BDCODEMPSCP,C.BDCODEMP) BDCODEMPSUC ';
          wSQL = :wSQL || 'from TMP_TLANC_CONTABILIZACAO_TEMP c ';
          wSQL = :wSQL || 'join '||wTable||' mov on (mov.bdCODEMP = c.bdCODEMP and mov.bdCHAVE = c.bdCHAVE) ';
          wSQL = :wSQL || 'join TMP_'||wTableRateio||'_TEMP rat on (rat.bdCODEMP = c.bdCODEMP and rat.bdCHAVE = c.bdCHAVE and rat.bdORDEM = c.bdORDEM and rat.bdSESSAO = c.bdSESSAO and '; -- Rateio vão fazer contabilização própria e não aqui
          wSQL = :wSQL ||                                         ' rat.bdVALOR = c.bdVALOR and COALESCE(rat.bdDEB, 0) = COALESCE(c.bdDEBITO, 0) and COALESCE(rat.bdCRED, 0) = COALESCE(c.bdCREDITO, 0)) ';
          wSQL = :wSQL || 'where c.bdSESSAO = '||:PRSESSAO;
                          --AND ((mov.BDCHAVE IS NOT NULL) OR (mov.BDCHAVE > 0))
          wSQL = :wSQL || 'order by c.bdSESSAO, c.bdCODEMP, c.bdCHAVE, c.bdORD; ';
          EXECUTE STATEMENT :wSQL;
        END

      /*Insert na TOL_UPDATE_CONTA */
      wSQL =          'INSERT INTO TOL_UPDATE_CONTA(BDCODPLANOONLINE, BDCHAVE, BDCODEMP, BDCHAVELAN, BDCHAVETITULO, BDTIPOLAN, BDCLASSIFBUSCA, BDCLASSIFTITULO)  ';
      wSQL = :wSQL || 'SELECT C.BDCODPLANOONLINE, C.BDCHAVECONTA, COALESCE(C.BDCODEMPSCP,C.BDCODEMP) BDCODEMP, C.BDCHAVE_VSUC, C.BDCHAVETITULO, 0 BDTIPOLAN, C.BDCLASSIFBUSCA, C.BDCLASSIFTITULO  ';
      wSQL = :wSQL || 'FROM TMP_TLANC_CONTABILIZACAO_TEMP C ';
      wSQL = :wSQL || 'JOIN '||wTable||' mov ON(mov.BDCODEMP = C.BDCODEMP AND mov.BDCHAVE = C.BDCHAVE) ';
      wSQL = :wSQL || 'WHERE C.BDSESSAO =  '||:PRSESSAO;
                      --AND ((mov.BDCHAVE IS NOT NULL) or (mov.BDCHAVE > 0))
      wSQL = :wSQL || 'ORDER BY C.BDSESSAO, C.BDCODEMP, C.BDCHAVE, C.BDORD; ';
      EXECUTE STATEMENT :wSQL;      

      /*Apaga as contabilizações que já foram gravadas da tabela temporária*/
      wSQL =          'DELETE FROM TMP_TLANC_CONTABILIZACAO_TEMP C ';
      wSQL = :wSQL || 'WHERE C.BDSESSAO = '||:PRSESSAO;
      wSQL = :wSQL || ' AND ( ';
      wSQL = :wSQL ||      ' (EXISTS( ';
      wSQL = :wSQL ||              ' SELECT tol.bdCHAVE ';
      wSQL = :wSQL ||              ' FROM TOL_'||wTable||' TOL ';
      IF (wTableRateio <> '') THEN
        wSQL = :wSQL ||              ' left outer join TMP_'||wTableRateio||'_TEMP rat on (rat.bdCODEMP = tol.bdCODEMP and rat.bdCHAVE = tol.'||wCampoTol||' and rat.bdORDEM = tol.bdORDEM and rat.bdSESSAO = c.bdSESSAO) '; -- Rateio vão fazer contabilização própria e não aqui
      wSQL = :wSQL ||              ' WHERE tol.bdCODEMP = c.bdCODEMP ';
      wSQL = :wSQL ||                ' AND tol.bdCHAVE = c.bdCHAVE_VSUC ';
      wSQL = :wSQL ||                ' AND tol.'||wCampoTol||' = c.bdCHAVE ';
      wSQL = :wSQL ||                ' AND tol.bdORDEM = c.bdORDEM ';
      IF (wTableRateio <> '') THEN
        wSQL = :wSQL ||                ' and rat.bdCODEMP IS NULL '; -- Somente quando não tiver rateio no lançamento
      wSQL = :wSQL ||              ' )) ';

      IF (wTableRateio <> '') THEN
        BEGIN
          wSQL = :wSQL ||      ' OR ';
          wSQL = :wSQL ||      ' (EXISTS( ';
          wSQL = :wSQL ||              ' SELECT rat.bdCHAVE ';
          wSQL = :wSQL ||              ' FROM TOL_'||wTableRateio||' rat ';
          wSQL = :wSQL ||              ' WHERE rat.bdCODEMP = c.bdCODEMP ';
          wSQL = :wSQL ||                ' AND rat.bdCHAVE = c.bdCHAVE_VSUC ';
          wSQL = :wSQL ||                ' AND rat.bdCHAVELAN = c.bdCHAVE ';
          wSQL = :wSQL ||                ' AND rat.bdORDEM = c.bdORDEM ';
          wSQL = :wSQL ||              ' )) ';
        END
      wSQL = :wSQL ||      ' ) ';
      EXECUTE STATEMENT :wSQL;
    END
  ELSE
  IF (:PRTIPOLAN = 'REDZ') THEN
    BEGIN
      INSERT INTO TOL_VEF_EMP_TREDZVARCFOP(BDCHAVE, BDCODEMP, BDCHAVECFOP, BDORDEMVARCFOP, BDCODEMPSUC)
      SELECT C.BDCHAVE_VSUC, C.BDCODEMP, C.BDCHAVE, C.BDORDEM, COALESCE(C.BDCODEMPSCP,C.BDCODEMP) BDCODEMPSUC
      FROM TMP_TLANC_CONTABILIZACAO_TEMP C
      JOIN VEF_EMP_TREDZVARCFOP CFOP ON(CFOP.BDCODEMP = C.BDCODEMP AND CFOP.BDCHAVE = C.BDCHAVE AND CFOP.BDORDEMVARCFOP = C.BDORDEM)
      WHERE C.BDSESSAO = :PRSESSAO
      ORDER BY C.BDSESSAO, C.BDCODEMP, C.BDCHAVE, C.BDORD;

      /*Insert na TOL_UPDATE_CONTA*/
      INSERT INTO TOL_UPDATE_CONTA(BDCODPLANOONLINE, BDCHAVE, BDCODEMP, BDCHAVELAN, BDCHAVETITULO, BDTIPOLAN, BDCLASSIFBUSCA, BDCLASSIFTITULO)
      SELECT C.BDCODPLANOONLINE, C.BDCHAVECONTA, COALESCE(C.BDCODEMPSCP,C.BDCODEMP) BDCODEMP, C.BDCHAVE_VSUC, C.BDCHAVETITULO, 0 BDTIPOLAN, C.BDCLASSIFBUSCA, C.BDCLASSIFTITULO
      FROM TMP_TLANC_CONTABILIZACAO_TEMP C
      JOIN VEF_EMP_TREDZVARCFOP CFOP ON(CFOP.BDCODEMP = C.BDCODEMP AND CFOP.BDCHAVE = C.BDCHAVE AND CFOP.BDORDEMVARCFOP = C.BDORDEM)
      WHERE C.BDSESSAO = :PRSESSAO
      -- AND ((S.BDCHAVE IS NOT NULL) OR (S.BDCHAVE > 0))
      ORDER BY C.BDSESSAO, C.BDCODEMP, C.BDCHAVE, C.BDORD;

      /* Alt:127314 - Insert do Centro de Custo na VSUC_EMPRESAS_TLCC */
      wSQL =          'insert into VSUC_EMPRESAS_TLCC (bdCODEMP, bdCHAVE, bdCODCENTRO, bdCODTPCC, bdDEBCRE, bdPERCENTUAL, bdVALOR) ';
      wSQL = :wSQL || 'select COALESCE(C.BDCODEMPSCP,c.bdCODEMP) BDCODEMP, c.bdCHAVE_VSUC, cc.bdCODCENTRO, cc.bdCODTPCC, ';
      wSQL = :wSQL ||       ' IIF((c.bdCODITEMONLINE in (111,117,170)), Coalesce(cc.BDDEBCRED,1), IIF(Coalesce(cc.BDDEBCRED,1) = 1,0,1)) as bdDEBCRE, ';
      wSQL = :wSQL ||       ' cc.bdPERCENTUAL, cc.bdVALOR ';
      wSQL = :wSQL || 'from TMP_TLANC_CONTABILIZACAO_TEMP c ';
      wSQL = :wSQL || 'join VEF_EMP_TMOVCCREDZ cc on (cc.bdCODEMP = c.bdCODEMP and cc.bdCHAVE = c.bdCHAVE and cc.bdORDEMVARCFOP = c.bdORDEM) ';
      wSQL = :wSQL || 'where c.bdSESSAO = '||:PRSESSAO;
      wSQL = :wSQL || '  and Coalesce(cc.BDDEBCRED,0) <> 2 ';
      wSQL = :wSQL || '  and c.bdCODITEMONLINE in (111/*NATVLAN*/, 117/*NATPLAN*/, 170/*NATOLAN*/'; /* Valor Contabil */ -- Valor contábil sempre lança centro de custo...
      wSQL = :wSQL ||                             ') ';
      wSQL = :wSQL || 'order by c.bdSESSAO, c.bdCODEMP, c.bdCHAVE, c.bdORD; ';
      EXECUTE STATEMENT :wSQL;

      -- Alt:127314 - REALIZA O LANCAMENTO DO DEBITO PARA CC CONFIGURADO COMO 'AMBOS'
      wSQL =          'insert into VSUC_EMPRESAS_TLCC (bdCODEMP, bdCHAVE, bdCODCENTRO, bdCODTPCC, bdDEBCRE, bdPERCENTUAL, bdVALOR) ';
      wSQL = :wSQL || 'select COALESCE(C.BDCODEMPSCP,c.bdCODEMP) BDCODEMP, c.bdCHAVE_VSUC, cc.bdCODCENTRO, cc.bdCODTPCC, ';
      wSQL = :wSQL ||       ' 0 bdDEBCRE, cc.bdPERCENTUAL, cc.bdVALOR ';
      wSQL = :wSQL || 'from TMP_TLANC_CONTABILIZACAO_TEMP c ';
      wSQL = :wSQL || 'join VEF_EMP_TMOVCCREDZ cc on (cc.bdCODEMP = c.bdCODEMP and cc.bdCHAVE = c.bdCHAVE and cc.bdORDEMVARCFOP = c.bdORDEM) ';
      wSQL = :wSQL || 'where c.bdSESSAO = '||:PRSESSAO;          
      wSQL = :wSQL || '  and Coalesce(cc.BDDEBCRED,0) = 2 ';
      wSQL = :wSQL || '  and c.bdCODITEMONLINE in (111/*NATVLAN*/, 117/*NATPLAN*/, 170/*NATOLAN*/'; /* Valor Contabil */ -- Valor contábil sempre lança centro de custo...
      wSQL = :wSQL ||                             ') ';
      wSQL = :wSQL || 'order by c.bdSESSAO, c.bdCODEMP, c.bdCHAVE, c.bdORD; ';
      EXECUTE STATEMENT :wSQL;

      -- Alt:127314 - REALIZA O LANCAMENTO DO CREDITO PARA CC CONFIGURADO COMO 'AMBOS'
      wSQL =          'insert into VSUC_EMPRESAS_TLCC (bdCODEMP, bdCHAVE, bdCODCENTRO, bdCODTPCC, bdDEBCRE, bdPERCENTUAL, bdVALOR) ';
      wSQL = :wSQL || 'select COALESCE(C.BDCODEMPSCP,c.bdCODEMP) BDCODEMP, c.bdCHAVE_VSUC, cc.bdCODCENTRO, cc.bdCODTPCC, ';
      wSQL = :wSQL ||       ' 1 bdDEBCRE, cc.bdPERCENTUAL, cc.bdVALOR ';
      wSQL = :wSQL || 'from TMP_TLANC_CONTABILIZACAO_TEMP c ';
      wSQL = :wSQL || 'join VEF_EMP_TMOVCCREDZ cc on (cc.bdCODEMP = c.bdCODEMP and cc.bdCHAVE = c.bdCHAVE and cc.bdORDEMVARCFOP = c.bdORDEM) ';
      wSQL = :wSQL || 'where c.bdSESSAO = '||:PRSESSAO;          
      wSQL = :wSQL || '  and Coalesce(cc.BDDEBCRED,0) = 2 ';
      wSQL = :wSQL || '  and c.bdCODITEMONLINE in (111/*NATVLAN*/, 117/*NATPLAN*/, 170/*NATOLAN*/'; /* Valor Contabil */ -- Valor contábil sempre lança centro de custo...
      wSQL = :wSQL ||                             ') ';
      wSQL = :wSQL || 'order by c.bdSESSAO, c.bdCODEMP, c.bdCHAVE, c.bdORD; ';
      EXECUTE STATEMENT :wSQL;

      DELETE FROM TMP_TLANC_CONTABILIZACAO_TEMP C
      WHERE C.BDSESSAO = :PRSESSAO
      AND (
           (
            EXISTS(
                   SELECT tol.bdCHAVE
                   FROM TOL_VEF_EMP_TREDZVARCFOP TOL
                   WHERE tol.bdCODEMP = c.bdCODEMP
                   AND tol.bdCHAVE = c.bdCHAVE_VSUC
                   AND tol.BDCHAVECFOP = c.bdCHAVE
                   AND tol.bdORDEMVARCFOP = c.bdORDEM
                  )
           )
          );      
    END

END
^

create or alter procedure SP_LANCA_INTEGRACAO_FOLHA (
    PRSESSAO integer,
    PRSESSAOTER integer,
    PRCHAVERH integer,
    PRISPRODRURAL boolean = false)
as
declare variable WCODEMP integer;
declare variable WCHAVEEF integer;
declare variable WDATAEMISSAO date;
declare variable WNUMDOC integer;
declare variable WREFNF varchar(6);
declare variable WRETINSS numeric(15,2);
declare variable WVLRNF numeric(15,2);
declare variable WCHAVERH integer;
declare variable WTPCOMERC integer;
declare variable WCNPJTER varchar(18);
declare variable WSERIE integer;
declare variable WVLRFUNRURAL numeric(15,2);
declare variable BDVLRGILRAT numeric(15,2);
declare variable BDVLRSENAR numeric(15,2);
begin
  WCHAVERH = PRCHAVERH;


  if (PRISPRODRURAL = TRUE) then
   begin
      For 
      SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE BDCHAVE, (SELECT BDDATA FROM SP_PARSE_DATE(BDDATAEMISSAO, 'YYYYMM')) BDREFNF,
             MOV.BDNUMDOCINI, MOV.BDDATAEMISSAO, (MOV.BDVALORNOTA) BDVALNF,
             CASE RURAL.BDORDEMINDCOM
               WHEN 5 THEN '1'
               WHEN 4 THEN '3'
               WHEN 3 THEN '5'
             END AS BDORDEMINDCOM,
             MOV.BDCNPJ, MOV.BDSERIE,
             RURAL.BDVLRFUNRURAL, RURAL.BDVLRGILRAT, RURAL.BDVLRSENAR
      FROM (SELECT *
            FROM TMP_VEF_EMP_TMOVSAI_TEMP S
            WHERE S.BDSESSAO = :PRSESSAO
              and (NOT S.BDCODSITNF IN(2, 3, 4, 5))
            AND NOT EXISTS (
                            SELECT INCO.BDCODINCONSISTENCIAMOVSAI
                            FROM VEF_INCON_TMOVSAI INCO
                            WHERE INCO.BDSESSAO = S.BDSESSAO
                            AND INCO.BDCODEMP = S.BDCODEMP
                            AND INCO.BDCHAVE = S.BDCHAVE
                           )
           ) MOV  
      LEFT OUTER JOIN TMP_VEF_TMOVSAIFUNRURAL_TEMP RURAL ON(RURAL.BDSESSAO = MOV.BDSESSAO AND RURAL.BDCODEMP = MOV.BDCODEMP AND RURAL.BDCHAVE = MOV.BDCHAVE)
      LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER ON(TER.BDSESSAO = :PRSESSAOTER AND TER.BDEDITCHAVE = MOV.BDALTCODTER)
      WHERE  RURAL.BDORDEMINDCOM in (3,4,5) AND
             NOT EXISTS(
                       SELECT T.BDCODTER
                       FROM VEF_INCON_TTERCEIROS T
                       WHERE T.BDSESSAO = :PRSESSAOTER
                       AND T.BDCODTER = TER.BDCODTER
                      )
      AND ((MOV.BDALTCODTER IS NOT NULL) OR (MOV.BDALTCODTER > 0)) AND CHAR_LENGTH(MOV.BDCNPJ) = 14
      INTO
        :WCODEMP, :WCHAVEEF, :WREFNF, :WNUMDOC, :WDATAEMISSAO, :WVLRNF, :WTPCOMERC, :WCNPJTER, :WSERIE, :WVLRFUNRURAL, :BDVLRGILRAT, :BDVLRSENAR do
        BEGIN
            UPDATE OR INSERT INTO VRH_EMP_TCOMERCNFPRODRURAL (BDCODEMP, BDCHAVE, BDREFNF, BDTPCOMERC, BDCNPJADQ, BDSERIENF, BDNOTAFISCAL, BDEMISSAONF, BDVALNF, BDINSS, BDGILRAT, BDSENAR, BDTIPOLAN)
            VALUES(:WCODEMP, :WCHAVERH, :WREFNF, :WTPCOMERC, :WCNPJTER, :WSERIE, :WNUMDOC, :WDATAEMISSAO, :WVLRNF, :WVLRFUNRURAL, :BDVLRGILRAT, :BDVLRSENAR, 100) MATCHING (BDCODEMP, BDCHAVE); -- Integra  o fiscal
        
            UPDATE OR INSERT INTO TOL_VEF_EMP_TCOMERCNFPRODRURAL (BDCODEMP, BDCHAVE_RH, BDCHAVE_EF)
            VALUES(:WCODEMP, :WCHAVERH, :WCHAVEEF)MATCHING(BDCODEMP, BDCHAVE_RH, BDCHAVE_EF);
            WCHAVERH = WCHAVERH - 1;
        END
        exit;
       END


  -- Lança em VRHF_EMP_TNOTASFISCAIS
  For 
  SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE BDCHAVE, (SELECT BDDATA FROM SP_PARSE_DATE(BDDATAEMISSAO, 'YYYYMM')) BDREFNF,
         MOV.BDNUMDOCINI, MOV.BDDATAEMISSAO, (MOV.BDVALORNOTA - Coalesce(DED.BDVLRMATERIAIS,0) - Coalesce(DED.BDVLRSUBEMPREITEIRAS,0)) BDVALNF,
         DED.BDRETINSS
  FROM (SELECT *
        FROM TMP_VEF_EMP_TMOVSAI_TEMP S
        WHERE S.BDSESSAO = :PRSESSAO
          and (NOT S.BDCODSITNF IN(2, 3, 4, 5))
        AND NOT EXISTS (
                        SELECT INCO.BDCODINCONSISTENCIAMOVSAI
                        FROM VEF_INCON_TMOVSAI INCO
                        WHERE INCO.BDSESSAO = S.BDSESSAO
                        AND INCO.BDCODEMP = S.BDCODEMP
                        AND INCO.BDCHAVE = S.BDCHAVE
                       )
       ) MOV  
  LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAIDED_TEMP DED ON(DED.BDSESSAO = MOV.BDSESSAO AND DED.BDCODEMP = MOV.BDCODEMP AND DED.BDCHAVE = MOV.BDCHAVE)
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER ON(TER.BDSESSAO = :PRSESSAOTER AND TER.BDEDITCHAVE = MOV.BDALTCODTER)
  WHERE NOT EXISTS(
                   SELECT T.BDCODTER
                   FROM VEF_INCON_TTERCEIROS T
                   WHERE T.BDSESSAO = :PRSESSAOTER
                   AND T.BDCODTER = TER.BDCODTER
                  )
  AND ((MOV.BDALTCODTER IS NOT NULL) OR (MOV.BDALTCODTER > 0)) AND (DED.BDRETINSS > 0)
  INTO
    :WCODEMP, :WCHAVEEF, :WREFNF, :WNUMDOC, :WDATAEMISSAO, :WVLRNF, :WRETINSS do
    BEGIN
        IF (:WREFNF < 202301) THEN
          BEGIN
        INSERT INTO VRHF_EMP_TNOTASFISCAIS (BDCODEMP, BDCHAVE, BDREFNF, BDNOTAFISCAL, BDDATAEMINF, BDVALNF, BDVALDESCNF, BDPERCRETENCAONF, BDTIPOLAN)
            VALUES(:WCODEMP, :WCHAVERH, :WREFNF, cast(:WNUMDOC AS VARCHAR(15)), :WDATAEMISSAO, :WVLRNF, :WRETINSS, IIF(:WVLRNF <=0,0, (:WRETINSS*100/:WVLRNF)), 100); -- Integra  o fiscal
    
        INSERT INTO TOL_VEF_EMP_TSAIINSS (BDCODEMP, BDCHAVERH, BDCHAVEEF)
        VALUES(:WCODEMP, :WCHAVERH, :WCHAVEEF);  
        WCHAVERH = WCHAVERH - 1;
    END
    END
end^

create or alter procedure SP_COMMIT_IMP_SAIDA_P2 (
    PRSESSAO integer,
    PRSESSAOTER integer,
    PRSESSAOPROD integer)
as
declare variable WSEGREGACAO varchar(5);
BEGIN
  SELECT Coalesce(rdb$get_context('USER_SESSION', 'W_SEGREGACAO_FISCAL'),'FALSE') FROM rdb$database INTO WSEGREGACAO;
  IF(:WSEGREGACAO = 'TRUE') THEN
    BEGIN
     UPDATE TMP_CHAVE_SEGREG_CFOP S SET BDIMPORTOU = 'TRUE' WHERE NOT EXISTS (
                                                                            SELECT INCO.BDCODINCONSISTENCIAMOVSAI
                                                                            FROM VEF_INCON_TMOVSAI INCO
                                                                            JOIN TMP_VEF_EMP_TMOVSAI_TEMP TMP ON (INCO.BDSESSAO = TMP.BDSESSAO AND INCO.BDCODEMP = TMP.BDCODEMP AND INCO.BDCHAVE = TMP.BDCHAVE)
                                                                            WHERE (S.BDVINCULO = COALESCE(TMP.BDDATASAIDA, '') || '|' || COALESCE(TMP.BDSERIE, '') || '|' || COALESCE(TMP.BDESPECIE, '') || '|' || COALESCE(TMP.BDMODELO, '') || '|' || COALESCE(TMP.BDCODTER, '') || '|' || COALESCE(TMP.BDCHAVENFE, ''))
                                                                            );

     UPDATE TMP_CHAVE_SEGREG_CFOP TMP SET BDCHAVENOVA = (SELECT FIRST 1 MOV.BDEDITCHAVE FROM TMP_VEF_EMP_TMOVSAI_TEMP MOV
                                                         WHERE (TMP.BDVINCULO = COALESCE(MOV.BDDATASAIDA, '') || '|' || COALESCE(MOV.BDSERIE, '') || '|' || COALESCE(MOV.BDESPECIE, '') || '|' || COALESCE(MOV.BDMODELO, '') || '|' || COALESCE(MOV.BDCODTER, '') || '|' || COALESCE(MOV.BDCHAVENFE, '')));
    END


 /*Camilla M. Registro do  1250*/
  /*C185*/
  INSERT INTO VEF_EMP_TMOVC185_1250(BDCODEMP,BDCHAVE,BDORDEM,BDORDEMPRO,BDCODPROD,BDCODMOTIVO,BDQTDCONVERTIDA,BDVLRUNICONVERTIDO,BDVLRUNITICMSEFETIVO,BDVLRUNITICMSOPESTOQUE,
                                    BDVLRUNITICMSSTESTOQUE,BDVLRUNITICMSSTRESTITUIR,BDVLRUNITICMSSTCOMPLEMENTAR,BDCODUNIMED,BDVLRUNITICMSOP,
                                    BDVLRUNITFCPSTESTOQUE,BDVLRUNITFCPSTRESTITUIR,BDVLRUNITFCPSTCOMPLEMENTAR,BDTIPOLANCAMENTO)
  SELECT C.BDCODEMP, C.BDEDITCHAVE BDCHAVE, C.BDORDEM,C.BDORDEMPRO,S.BDCODPROD,C.BDCODMOTIVO,C.BDQTDCONVERTIDA,C.BDVLRUNICONVERTIDO,C.BDVLRUNITICMSEFETIVO,C.BDVLRUNITICMSOPESTOQUE,
         C.BDVLRUNITICMSSTESTOQUE,C.BDVLRUNITICMSSTRESTITUIR,C.BDVLRUNITICMSSTCOMPLEMENTAR,C.BDCODUNIMED,C.BDVLRUNITICMSOP,
         C.BDVLRUNITFCPSTESTOQUE,C.BDVLRUNITFCPSTRESTITUIR,C.BDVLRUNITFCPSTCOMPLEMENTAR,C.BDTIPOLANCAMENTO
  FROM TMP_VEF_EMP_TMOVC185_1250_TEMP C
  JOIN VEF_EMP_TMOVPROSAI S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDEDITCHAVE AND S.BDORDEM = C.BDORDEM AND S.BDORDEMPRO = C.BDORDEMPRO)
  WHERE C.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = C.BDSESSAO
                 AND I.BDCODEMP = C.BDCODEMP
                 AND I.BDCHAVE = C.BDCHAVE
                );
  /*C186*/
  INSERT INTO VEF_EMP_TMOVC186_1250 (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODPROD, BDCODMOTIVO, BDQTDCONVERTIDA, BDVLRUNICONVERTIDO,
                                     BDVLRUNITICMSST, BDBCUNITICMSST, BDVLRUNITICMSOP, BDVLRUNITFCPST, BDCODUNIMED, BDMODELO, BDSERIE,
                                     BDCHAVENFE, BDDTEMISSAO, BDNUMDOC, BDORDEMPRODORIG, BDTIPOLANCAMENTO)
  SELECT C.BDCODEMP, C.BDEDITCHAVE BDCHAVE, C.BDORDEM,C.BDORDEMPRO,S.BDCODPROD,C.BDCODMOTIVO,C.BDQTDCONVERTIDA,C.BDVLRUNICONVERTIDO,
         C.BDVLRUNITICMSST,C.BDBCUNITICMSST,C.BDVLRUNITICMSOP,C.BDVLRUNITFCPST,C.BDCODUNIMED,C.BDMODELO,C.BDSERIE,
         C.BDCHAVENFE,C.BDDTEMISSAO,C.BDNUMDOC,C.BDORDEMPRODORIG,C.BDTIPOLANCAMENTO
  FROM TMP_VEF_EMP_TMOVC186_1250_TEMP C
  JOIN VEF_EMP_TMOVPROSAI S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDEDITCHAVE AND S.BDORDEM = C.BDORDEM AND S.BDORDEMPRO = C.BDORDEMPRO)
  WHERE C.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = C.BDSESSAO
                 AND I.BDCODEMP = C.BDCODEMP
                 AND I.BDCHAVE = C.BDCHAVE
                );                      
                
  /*C380*/
  INSERT INTO VEF_EMP_TMOVC380_1250(BDCODEMP,BDCHAVE,BDORDEM,BDORDEMPRO,BDCODPROD,BDCODMOTIVO,BDQTDCONVERTIDA,BDVLRUNICONVERTIDO,BDVLRUNITICMSEFETIVO,BDVLRUNITICMSOPESTOQUE,
                                    BDVLRUNITICMSSTESTOQUE,BDVLRUNITICMSSTRESTITUIR,BDVLRUNITICMSSTCOMPLEMENTAR,BDCODUNIMED,BDVLRUNITICMSOP,
                                    BDVLRUNITFCPSTESTOQUE,BDVLRUNITFCPSTRESTITUIR,BDVLRUNITFCPSTCOMPLEMENTAR,BDTIPOLANCAMENTO)
  SELECT C.BDCODEMP, C.BDEDITCHAVE BDCHAVE, C.BDORDEM,C.BDORDEMPRO,S.BDCODPROD,C.BDCODMOTIVO,C.BDQTDCONVERTIDA,C.BDVLRUNICONVERTIDO,C.BDVLRUNITICMSEFETIVO,C.BDVLRUNITICMSOPESTOQUE,
         C.BDVLRUNITICMSSTESTOQUE,C.BDVLRUNITICMSSTRESTITUIR,C.BDVLRUNITICMSSTCOMPLEMENTAR,C.BDCODUNIMED,C.BDVLRUNITICMSOP,
         C.BDVLRUNITFCPSTESTOQUE,C.BDVLRUNITFCPSTRESTITUIR,C.BDVLRUNITFCPSTCOMPLEMENTAR,C.BDTIPOLANCAMENTO
  FROM TMP_VEF_EMP_TMOVC380_1250_TEMP C
  JOIN VEF_EMP_TMOVPROSAI S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDEDITCHAVE AND S.BDORDEM = C.BDORDEM AND S.BDORDEMPRO = C.BDORDEMPRO)
  WHERE C.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = C.BDSESSAO
                 AND I.BDCODEMP = C.BDCODEMP
                 AND I.BDCHAVE = C.BDCHAVE
                );

  /* Mov CC */
  INSERT INTO VEF_EMP_TMOVCCSAI (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMCC, BDCODCENTRO, BDCODTPCC, BDVALOR, BDPERCENTUAL, BDVLRIMP, BDDEBCRED)
  SELECT CC.BDCODEMP, CC.BDEDITCHAVE BDCHAVE, CC.BDORDEM, CC.BDORDEMCC, CC.BDCODCENTRO, CC.BDCODTPCC, CC.BDVALOR, CC.BDPERCENTUAL, CC.BDVLRIMP, CC.BDDEBCRED
  FROM TMP_VEF_EMP_TMOVCCSAI_TEMP CC
  LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS SAI ON (SAI.BDCODEMP = CC.BDCODEMP and SAI.BDCHAVE = CC.BDEDITCHAVE and SAI.BDORDEM = CC.BDORDEM)
  WHERE CC.BDSESSAO = :PRSESSAO
  AND((SAI.BDCHAVE is not null) or (SAI.BDCHAVE > 0))
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = CC.BDSESSAO
                 AND I.BDCODEMP = CC.BDCODEMP
                 AND I.BDCHAVE = CC.BDCHAVE
                );    

  /* F500 */
  INSERT INTO VEF_EMP_TF500SAI (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMF500, BDCODCSTCOF, BDCODCSTPIS, BDCODNATREC,
                                BDBASEPIS, BDALIQPIS, BDVLRPIS, BDBASECOF, BDALIQCOF, BDVLRCOF, BDVLRREC)
  SELECT T.BDCODEMP, T.BDEDITCHAVE, T.BDORDEM, T.BDORDEMF500, T.BDCODCSTCOF, T.BDCODCSTPIS, T.BDCODNATREC, T.BDBASEPIS,
         T.BDALIQPIS, T.BDVLRPIS, T.BDBASECOF, T.BDALIQCOF, T.BDVLRCOF, T.BDVLRREC
  FROM TMP_VEF_EMP_TF500SAI_TEMP T
  JOIN VEF_EMP_TMOVSAIITENS ITENS ON (T.BDCODEMP = ITENS.BDCODEMP AND T.BDEDITCHAVE = ITENS.BDCHAVE AND T.BDORDEM = ITENS.BDORDEM)
  WHERE T.BDSESSAO = :PRSESSAO;

  /*IBS-CBS*/
  INSERT INTO VEF_EMP_TMOVSAI_IBSCBS (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMLAN, BDCCLASSTRIB, BDCST, BDBASECALCULO, BDIBS_MUN_REDUCAO,
                                      BDIBS_MUN_ALIQ_VIGENTE, BDIBS_MUN_ALIQ_APLICADA, BDIBS_MUN_VALOR, BDIBS_MUN_ALIQ_DIF, BDIBS_MUN_DIFERIMENTO,
                                      BDIBS_MUN_DEVOLVIDO, BDIBS_UF_REDUCAO, BDIBS_UF_ALIQ_VIGENTE, BDIBS_UF_ALIQ_APLICADA, BDIBS_UF_VALOR,
                                      BDIBS_UF_ALIQ_DIF, BDIBS_UF_DIFERIMENTO, BDIBS_UF_DEVOLVIDO, BDCBS_REDUCAO, BDCBS_ALIQ_VIGENTE,
                                      BDCBS_ALIQ_APLICADA, BDCBS_VALOR, BDCBS_ALIQ_DIF, BDCBS_DIFERIMENTO, BDCBS_DEVOLVIDO, BDIBS_COD_CRED_PRES,
                                      BDIBS_CRED_PRES_ALIQ, BDIBS_CRED_PRES_VALOR, BDIBS_CRED_PRES_SUSP, BDCBS_COD_CRED_PRES, BDCBS_CRED_PRES_ALIQ, BDCBS_CRED_PRES_VALOR, BDCBS_CRED_PRES_SUSP)
  SELECT BS.BDCODEMP, BS.BDEDITCHAVE, BS.BDORDEM, BS.BDORDEMLAN, BS.BDCCLASSTRIB, BS.BDCST, BS.BDBASECALCULO, BS.BDIBS_MUN_REDUCAO,
         BS.BDIBS_MUN_ALIQ_VIGENTE, BS.BDIBS_MUN_ALIQ_APLICADA, BS.BDIBS_MUN_VALOR, BS.BDIBS_MUN_ALIQ_DIF, BS.BDIBS_MUN_DIFERIMENTO, BS.BDIBS_MUN_DEVOLVIDO, BS.BDIBS_UF_REDUCAO,
         BS.BDIBS_UF_ALIQ_VIGENTE, BS.BDIBS_UF_ALIQ_APLICADA, BS.BDIBS_UF_VALOR, BS.BDIBS_UF_ALIQ_DIF, BS.BDIBS_UF_DIFERIMENTO, BS.BDIBS_UF_DEVOLVIDO,
         BS.BDCBS_REDUCAO, BS.BDCBS_ALIQ_VIGENTE, BS.BDCBS_ALIQ_APLICADA, BS.BDCBS_VALOR, BS.BDCBS_ALIQ_DIF, BS.BDCBS_DIFERIMENTO, BS.BDCBS_DEVOLVIDO,
         BS.BDIBS_COD_CRED_PRES, BS.BDIBS_CRED_PRES_ALIQ, BS.BDIBS_CRED_PRES_VALOR, BS.BDIBS_CRED_PRES_SUSP, BS.BDCBS_COD_CRED_PRES, BS.BDCBS_CRED_PRES_ALIQ,
         BS.BDCBS_CRED_PRES_VALOR, BS.BDCBS_CRED_PRES_SUSP
  FROM TMP_VEF_EMP_TMOVSAI_IBSCBS_TEMP BS
  JOIN VEF_EMP_TMOVSAIITENS ITENS ON (BS.BDCODEMP = ITENS.BDCODEMP AND BS.BDEDITCHAVE = ITENS.BDCHAVE AND BS.BDORDEM = ITENS.BDORDEM)
  WHERE BS.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = BS.BDSESSAO
                 AND I.BDCODEMP = BS.BDCODEMP
                 AND I.BDCHAVE = BS.BDCHAVE
                );

  /*LCDPR - Importação Lançamento Produtor Rural */
  INSERT INTO VEF_EMP_TMOVSAIPR (BDCODEMP, BDCHAVE, BDORDEM, BDCODIMOVRUR, BDTIPMOV, BDCTACOR, BDCODTER, BDTIPDOC, BDTIPLAN)
  SELECT PR.BDCODEMP, PR.BDEDITCHAVE, PR.BDORDEM, PR.BDCODIMOVRUR, PR.BDTIPMOV, PR.BDCTACOR, PR.BDALTCODTER, PR.BDTIPDOC, PR.BDTIPLAN
  FROM TMP_VEF_EMP_TMOVSAIPR_TEMP PR
  JOIN VEF_EMP_TMOVSAIITENS ITENS ON (PR.BDCODEMP = ITENS.BDCODEMP AND PR.BDEDITCHAVE = ITENS.BDCHAVE AND PR.BDORDEM = ITENS.BDORDEM)
  WHERE PR.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = PR.BDSESSAO
                 AND I.BDCODEMP = PR.BDCODEMP
                 AND I.BDCHAVE = PR.BDCHAVE
                ); 

  --Nota débito/crédito
  INSERT INTO VEF_EMP_TMOVSAI_DEBCRED (BDCODEMP, BDCHAVE, BDORDEM, BDCHAVENF, BDNUMITEM)
  SELECT DC.BDCODEMP, DC.BDEDITCHAVE, DC.BDORDEM, DC.BDCHAVENF, DC.BDNUMITEM
  FROM TMP_VEF_EMP_TMOVSAI_DEBCRED_TEMP DC
  WHERE DC.BDSESSAO = :PrSessao
    AND NOT EXISTS(
                   SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO 
                   FROM VEF_INCON_TMOVSAI I
                   WHERE I.BDSESSAO = DC.BDSESSAO
                     AND I.BDCODEMP = DC.BDCODEMP
                     AND I.BDCHAVE  = DC.BDCHAVE
                  );
END^

create or alter procedure SP_COMMIT_SEGREGACAO_SAIDA (
    PRSESSAO integer)
as
BEGIN

      DELETE FROM TMP_VEF_EMP_TMOVSAIIMPORI_TEMP
      WHERE BDCODEMP = (SELECT FIRST 1 BDCODEMP FROM TMP_VEF_EMP_TMOVSAI_TEMP WHERE BDSESSAO = :PRSESSAO);

      INSERT INTO TMP_VEF_EMP_TMOVSAIIMPORI_TEMP (BDSESSAO, BDCODEMP, BDCHAVE, BDEDITCHAVE, BDORDEM, BDORDEMHIST, BDBCICMS, BDALIQICMS, BDVLRICMS, BDBCIPI, BDALIQIPI, BDVLRIPI,
                                                 BDBCST, BDALIQST, BDVLRST, BDBCPIS, BDALIQPIS, BDVLRPIS, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDBCISSQN,
                                                 BDALIQISSQN, BDVLRISSQN, BDBCICMSEFET, BDALIQICMSEFET, BDVLRICMSEFET, BDBCICMSSTRET, BDALIQIMCSSTRET,
                                                 BDVLRICMSSTRET, BDBCFCPSTRET, BDALIQFCPSTRET, BDVLRFCPSTRET, BDALTCODPROD,BDALIQFCPRETIDO,BDBCFCPRETIDO,BDFCPRETIDO,BDCODNAT,BDCODCSTICMS,
                                                 BDCODSAIDA, BDBCFCP, BDALQFCP, BDVLRFCP, BDNCMPROD, BDCODUNIMED, BDCODCSTPIS, BDCODCSTCOF, BDCODCSTIPI, BDORDEMPROORIG)
      SELECT :PRSESSAO BDSESSAO, ORI.BDCODEMP, TMP.BDCHAVE, TMP.BDEDITCHAVE, ORI.BDORDEM, ORI.BDORDEMHIST, ORI.BDBCICMS, ORI.BDALIQICMS, ORI.BDVLRICMS, ORI.BDBCIPI, ORI.BDALIQIPI, ORI.BDVLRIPI,
             ORI.BDBCST, ORI.BDALIQST, ORI.BDVLRST, ORI.BDBCPIS, ORI.BDALIQPIS, ORI.BDVLRPIS, ORI.BDBCCOFINS, ORI.BDALIQCOFINS, ORI.BDVLRCOFINS, ORI.BDBCISSQN,
             ORI.BDALIQISSQN, ORI.BDVLRISSQN, ORI.BDBCICMSEFET, ORI.BDALIQICMSEFET, ORI.BDVLRICMSEFET, ORI.BDBCICMSSTRET, ORI.BDALIQIMCSSTRET,
             ORI.BDVLRICMSSTRET, ORI.BDBCFCPSTRET, ORI.BDALIQFCPSTRET, ORI.BDVLRFCPSTRET, ORI.BDCODPROD,ORI.BDALIQFCPRETIDO,ORI.BDBCFCPRETIDO,ORI.BDFCPRETIDO,ORI.BDCODNAT,ORI.BDCODCSTICMS,
             ORI.BDCODSAIDA, ORI.BDBCFCP, ORI.BDALQFCP, ORI.BDVLRFCP, ORI.BDNCMPROD, ORI.BDCODUNIMED, ORI.BDCODCSTPIS, ORI.BDCODCSTCOF, ORI.BDCODCSTIPI, ORI.BDORDEMPROORIG
      FROM VEF_EMP_TMOVPROSAIIMPORI ORI
      JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = ORI.BDCODEMP AND SEG.BDCHAVE = ORI.BDCHAVE)
      JOIN TMP_VEF_EMP_TMOVSAI_TEMP TMP ON (TMP.BDCODEMP = SEG.BDCODEMP AND TMP.BDSESSAO = :PRSESSAO)
      LEFT OUTER JOIN TTERCEIRO T ON (TMP.BDCODTER = T.BDCODTER)
      WHERE (SEG.BDVINCULO = COALESCE(TMP.BDDATAEMISSAO, '') || '|' || COALESCE(TMP.BDSERIE, '') || '|' || COALESCE(TMP.BDESPECIE, '') || '|' || COALESCE(TMP.BDMODELO, '') || '|' || COALESCE(T.BDCGCTER, '') || '|' || COALESCE(TMP.BDCHAVENFE, ''));

       UPDATE TMP_VEF_EMP_TMOVSAI_TEMP
       SET BDCODTIPO = 162
      WHERE BDSESSAO = :PRSESSAO;
    
      DELETE FROM VEF_EMP_TMOVSAI
      WHERE BDCODEMP =  (SELECT FIRST 1 BDCODEMP
                         FROM TMP_VEF_EMP_TMOVSAI_TEMP
                         WHERE BDSESSAO = :PRSESSAO)
      AND BDCHAVE IN (SELECT TMP.BDCHAVE
                      FROM TMP_VEF_EMP_TMOVSAI_TEMP S
                      LEFT OUTER JOIN TTERCEIRO T ON (S.BDCODTER = T.BDCODTER)
                      JOIN TMP_CHAVE_SEGREG_CFOP TMP ON (TMP.BDVINCULO = COALESCE(S.BDDATAEMISSAO, '') || '|' || COALESCE(S.BDSERIE, '') || '|' || COALESCE(S.BDESPECIE, '') || '|' || COALESCE(S.BDMODELO, '') || '|' || COALESCE(T.BDCGCTER, '') || '|' || COALESCE(S.BDCHAVENFE, ''))
                      WHERE S.BDSESSAO = :PRSESSAO
                      AND NOT EXISTS
                                     (SELECT INCO.BDCODINCONSISTENCIA
                      FROM VEF_INCON_TMOVSAI INCO
                                      WHERE INCO.BDSESSAO = S.BDSESSAO
                                      AND INCO.BDCODEMP = S.BDCODEMP
                                      AND INCO.BDCHAVE = S.BDCHAVE));



END^

CREATE OR ALTER procedure SP_COMMIT_IMP_SAIDA (
    PRSESSAO integer,
    PRSESSAOTER integer,
    PRSESSAOPROD integer)
as
declare variable WSEGREGACAO varchar(5);
BEGIN
  SELECT Coalesce(rdb$get_context('USER_SESSION', 'W_SEGREGACAO_FISCAL'),'FALSE') FROM rdb$database INTO WSEGREGACAO;
  IF(:WSEGREGACAO = 'TRUE') THEN
    BEGIN
      execute procedure SP_COMMIT_SEGREGACAO_SAIDA(:PRSESSAO);
    END

  /*Commit do lançamento de saída - registros não inconsistentes*/
  INSERT INTO VEF_EMP_TMOVSAI(BDCODEMP, BDCHAVE, BDCODTER, BDNUMDOCINI, BDDATAEMISSAO, BDESPECIE, BDSERIE, BDNUMDOCFIM, BDTIPLAN,
                              BDMODELO, BDEMITENTE,BDCONSUFINAL, BDDATASAIDA, BDCODSITNF, BDREFLAN, BDCIFFOB, BDCODTIPO, BDCODUSU, BDDATALAN,
                              BDHORALAN, BDDATACANC, BDCHAVETALON, BDVALORNOTA, BDDESCONTONOTA, BDCHAVENFE, BDCONDPGTO, BDOPINTERNA, BDSUBSERIE,
                              BDCODSTATUSLAN, BDFUNDAP, BDDATAINCLUSAO, BDHORAINCLUSAO, BDCODUSUINCLU, BDTIPOLANINCLU, BDCODCID,
                              BDCODEQUIPSAT, BDCNPJDESTCFE, bdVLRTOTPIS, bdVLRTOTCOFINS, bdVLRTOTPISST, bdVLRTOTCOFINSST, bdVLRTOTOUT, BDCODSITTIPO, bdORIGEM) -- Alt.: #76595 #89560 #98636 #121104 - Importação do C800/C850 - Importação mod 59 layout Sped Fiscal
  SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE BDCHAVE, MOV.BDALTCODTER, MOV.BDNUMDOCINI, MOV.BDDATAEMISSAO, MOV.BDESPECIE,
         MOV.BDSERIE, MOV.BDNUMDOCFIM, MOV.BDTIPLAN, MOV.BDMODELO, MOV.BDEMITENTE,mov.BDCONSUFINAL, MOV.BDDATASAIDA, MOV.BDCODSITNF,
         MOV.BDREFLAN, MOV.BDCIFFOB, MOV.BDCODTIPO, MOV.BDCODUSU, MOV.BDDATALAN, MOV.BDHORALAN, MOV.BDDATACANC,
         MOV.BDCHAVETALON, MOV.BDVALORNOTA, MOV.BDDESCONTONOTA, MOV.BDCHAVENFE, MOV.BDCONDPGTO, MOV.BDOPINTERNA, MOV.BDSUBSERIE,
         MOV.BDCODSTATUSLAN, NULL BDFUNDAP, MOV.BDDATAINCLUSAO, MOV.BDHORAINCLUSAO, MOV.BDCODUSUINCLU,
         MOV.BDTIPOLANINCLU, IIF(MOV.BDCODCID = 0, NULL, MOV.BDCODCID) BDCODCID, 
   MOV.BDCODEQUIPSAT, MOV.BDCNPJDESTCFE, bdVLRTOTPIS, bdVLRTOTCOFINS, bdVLRTOTPISST, bdVLRTOTCOFINSST, bdVLRTOTOUT, BDCODSITTIPO, bdORIGEM
  FROM (
        SELECT S.*
        FROM TMP_VEF_EMP_TMOVSAI_TEMP S
        WHERE S.BDSESSAO = :PRSESSAO
        AND NOT EXISTS (
                        SELECT INCO.BDCODINCONSISTENCIAMOVSAI
                        FROM VEF_INCON_TMOVSAI INCO
                        WHERE INCO.BDSESSAO = S.BDSESSAO
                        AND INCO.BDCODEMP = S.BDCODEMP
                        AND INCO.BDCHAVE = S.BDCHAVE
                       )
       ) MOV
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER ON(TER.BDSESSAO = :PRSESSAOTER AND TER.BDEDITCHAVE = MOV.BDALTCODTER)
  WHERE NOT EXISTS(
                   SELECT T.BDCODTER
                   FROM VEF_INCON_TTERCEIROS T
                   WHERE T.BDSESSAO = :PRSESSAOTER
                   AND T.BDCODTER = TER.BDCODTER
                  )
  /*AND MOV.BDSESSAO = :PRSESSAO*/
  AND ((MOV.BDALTCODTER IS NOT NULL) OR (MOV.BDALTCODTER > 0));

  /*Commit dos itens do lançamento de saída - registros commitados acima*/
  INSERT INTO VEF_EMP_TMOVSAIITENS (
                                   BDCODEMP, BDCHAVE, BDORDEM, BDCODOBS, BDOBSERVACAO, BDCODCID, BDCODCSTICMS,
                                   BDCODNAT, BDALIQICMS, BDALIQST, BDBASEICMS, BDBASEIPI, BDBASEST,
                                   BDISENTASICMS, BDISENTASIPI, BDOUTRASICMS, BDOUTRASIPI, BDVLRICMS,
                                   BDVLRIPI, BDVLRST, BDIMPEXCLUIDAS, BDOUTROSIMP, BDREDBCICMS, BDVLRCONTAB,
                                   BDDESCONTO, BDICMSFRETESAI, BDACRECFINSAI, BDREGEXPSAI, BDDIGOPERNAT,
                                   BDPREFIXONAT, BDVLRPIS, BDVLRCOFINS, BDFCPRETIDO, BDVLRFCP, BDBICMSCONC, BDALIQICMSCONC, BDVLRICMSCONC,
                                   BDVLRMONOST, BDVLRMONOCONTAB, BDCBS_BASE, BDCBS_ALIQ, BDCBS_VALOR, BDCBS_NAOTRIBU, BDIBS_BASE,
                                   BDIBS_ALIQ_MUN, BDIBS_ALIQ_UF, BDIBS_VALOR, BDIBS_NAOTRIBU, BDIS_BASE, BDIS_ALIQ, BDIS_VALOR
                                   )
  SELECT T.BDCODEMP, T.BDEDITCHAVE BDCHAVE, T.BDORDEM, T.BDCODOBS, BDOBSERVACAO, T.BDCODCID, T.BDCODCSTICMS, T.BDCODNAT, T.BDALIQICMS,
         T.BDALIQST, T.BDBASEICMS, T.BDBASEIPI, T.BDBASEST, T.BDISENTASICMS, T.BDISENTASIPI, T.BDOUTRASICMS,
         T.BDOUTRASIPI, T.BDVLRICMS, T.BDVLRIPI, T.BDVLRST, T.BDIMPEXCLUIDAS, T.BDOUTROSIMP, T.BDREDBCICMS,
         T.BDVLRCONTAB, T.BDDESCONTO, T.BDICMSFRETESAI, T.BDACRECFINSAI, T.BDREGEXPSAI, T.BDDIGOPERNAT,
         T.BDPREFIXONAT, T.BDVLRPIS, T.BDVLRCOFINS, T.BDFCPRETIDO, T.BDVLRFCP, T.BDBICMSCONC, T.BDALIQICMSCONC, T.BDVLRICMSCONC,
         T.BDVLRMONOST, T.BDVLRMONOCONTAB, T.BDCBS_BASE, T.BDCBS_ALIQ, T.BDCBS_VALOR, BDCBS_NAOTRIBU, T.BDIBS_BASE,
         T.BDIBS_ALIQ_MUN, T.BDIBS_ALIQ_UF, T.BDIBS_VALOR, BDIBS_NAOTRIBU, T.BDIS_BASE, T.BDIS_ALIQ, T.BDIS_VALOR
  FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP T
  --Faz esse left pra saber se o lançamento existe na base, se sim então insere o item
  LEFT OUTER JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = T.BDCODEMP AND S.BDCHAVE = T.BDEDITCHAVE)
  WHERE T.BDSESSAO = :PRSESSAO
  AND ((S.BDCHAVE IS NOT NULL) OR (S.BDCHAVE > 0))
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = T.BDSESSAO
                 AND I.BDCODEMP = T.BDCODEMP
                 AND I.BDCHAVE = T.BDCHAVE
                );

  /*Commit do movimento de produto de saída*/
  INSERT INTO VEF_EMP_TMOVPROSAI (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODCTA, BDCODPROD, BDCODCSTCOF, BDCODCSTICMS,
                                  BDCODCSTPIS, BDCODCSTIPI, BDCODFATCON, BDMOVFISICO, BDQTDITEM,
                                  BDVLRITEM, BDVLRDESC, BDVLRDESPACESSORIA, BDREDBCICMS, BDBCICMS, BDBCPIS, BDBCST,
                                  BDBCIPI, BDBCCOFINS, BDBCISSQN, BDALIQICMS, BDALIQPIS, BDALIQST, BDALIQIPI,
                                  BDALIQCOFINS, BDALIQISSQN, BDVLRICMS, BDVLRPIS, BDVLRST, BDVLRIPI, BDVLRCOFINS,
                                  BDVLRISSQN, BDCODNATREC, BDVLRFRETE, BDFCPRETIDO,BDVLRABATNT,BDVLRSEGURO,BDBCICMSEFET,
                                  BDALIQICMSEFET,BDVLRICMSEFET,BDBCICMSSTRET,BDALIQIMCSSTRET,BDVLRICMSSTRET,BDBCFCPSTRET,
                                  BDALIQFCPSTRET,BDVLRFCPSTRET,BDALIQFCPRETIDO,BDBCFCPRETIDO, BDBCFCP, BDALQFCP, BDVLRFCP, BDPISCOFQTD, BDCBNEF,
                                  BDBCICMSMONO, BDALIQICMSMONO, BDVLRICMSMONO, BDBCICMSMONORET, BDALIQICMSMONORET, BDVLRICMSMONORET,
                                  BDBCICMSMONODIF, BDALIQICMSMONODIF, BDVLRICMSMONODIF, BDBCICMSMONORETANT, BDALIQICMSMONORETANT, BDVLRICMSMONORETANT,
                                  BDVLRCBENEF, BDMOTDESONERACAO, BDCODCREDPRES, BDALIQCREDPRESUMIDO, BDVLRCREDPRESUMIDO, BDORDEMPROORIG, BDIBS_CBS_CODCCLASSTRIB, BDIBS_CBS_CST, BDIBS_CBS_BASE,
                                  BDIBS_MUN_REDUCAO, BDIBS_MUN_ALIQ_VIGENTE, BDIBS_MUN_ALIQ_MUNICIP, BDIBS_MUN_VALOR_MUNICIP, BDIBS_MUN_ALIQ_DIF, BDIBS_MUN_VALOR_DIF, 
                                  BDIBS_MUN_VALOR_DEVOL, BDIBS_UF_REDUCAO, BDIBS_UF_ALIQ_VIGENTE, BDIBS_UF_ALIQ_UF, BDIBS_UF_VALOR_UF, BDIBS_UF_ALIQ_DIF, BDIBS_UF_VALOR_DIF, 
                                  BDIBS_UF_VALOR_DEVOL, BDIBS_CBS_REDUCAO, BDIBS_CBS_ALIQ_VIGENTE, BDIBS_CBS_ALIQ_CBS, BDIBS_CBS_VALOR_CBS, BDIBS_CBS_ALIQ_DIF, BDIBS_CBS_VALOR_DIF,
                                  BDIBS_CBS_VALOR_DEVOL, BDIBS_PRES_COD_CRED, BDIBS_PRES_ALIQUOTA, BDIBS_PRES_VALOR, BDIBS_PRES_VLR_COND_SUP, BDCBS_PRES_COD_CRED, BDCBS_PRES_ALIQUOTA,
                                  BDCBS_PRES_VALOR, BDCBS_PRES_VLR_COND_SUP, BDIBS_MONO_BASE, BDIBS_MONO_ALIQ, BDIBS_MONO_VALOR, BDIBS_MONO_BASE_RET, BDIBS_MONO_ALIQ_RET, BDIBS_MONO_VALOR_RET,
                                  BDIBS_MONO_BASE_RET_ANT, BDIBS_MONO_ALIQ_RET_ANT, BDIBS_MONO_VALOR_RET_ANT, BDIBS_MONO_BASE_DIFERIDO, BDIBS_MONO_ALIQ_DIFERIDO, BDIBS_MONO_VALOR_DIFERIDO,
                                  BDCBS_MONO_BASE, BDCBS_MONO_ALIQ, BDCBS_MONO_VALOR, BDCBS_MONO_BASE_RET, BDCBS_MONO_ALIQ_RET, BDCBS_MONO_VALOR_RET, BDCBS_MONO_BASE_RET_ANT,
                                  BDCBS_MONO_ALIQ_RET_ANT, BDCBS_MONO_VALOR_RET_ANT, BDCBS_MONO_BASE_DIFERIDO, BDCBS_MONO_ALIQ_DIFERIDO, BDCBS_MONO_VALOR_DIFERIDO, 
                                  BDIS_CODCCLASSTRIB, BDIS_CST, BDIS_UN_TRIB, BDIS_ALIQUOTA, BDIS_BASE, BDIS_ALIQUOTA_ESPECIFICO, BDIS_BASE_ESPECIFICO, BDIS_VALOR_TOTAL, BDCOD_IS_UN_TRIB,
                                  BDVLRICMSSTDESON, BDMOTICMSSTDESON, BDIBS_ESTCRED_VALOR, BDCBS_ESTCRED_VALOR, BDAJUSTECOMP_REF, BDIBS_AJUSTECOMP_VALOR, BDCBS_AJUSTECOMP_VALOR)
  SELECT MOVPRO.BDCODEMP, MOVPRO.BDEDITCHAVE BDCHAVE, MOVPRO.BDORDEM, MOVPRO.BDORDEMPRO, MOVPRO.BDCODCTA, MOVPRO.BDALTCODPROD BDCODPROD, MOVPRO.BDCODCSTCOF,
         MOVPRO.BDCODCSTICMS, MOVPRO.BDCODCSTPIS, MOVPRO.BDCODCSTIPI,  MOVPRO.BDCODFATCON, MOVPRO.BDMOVFISICO, MOVPRO.BDQTDITEM,
         MOVPRO.BDVLRITEM, MOVPRO.BDVLRDESC, MOVPRO.BDVLRDESPACESSORIA, MOVPRO.BDREDBCICMS, MOVPRO.BDBCICMS, MOVPRO.BDBCPIS, MOVPRO.BDBCST, MOVPRO.BDBCIPI,
         MOVPRO.BDBCCOFINS, MOVPRO.BDBCISSQN, MOVPRO.BDALIQICMS, MOVPRO.BDALIQPIS, MOVPRO.BDALIQST, MOVPRO.BDALIQIPI, MOVPRO.BDALIQCOFINS, MOVPRO.BDALIQISSQN,
         MOVPRO.BDVLRICMS, MOVPRO.BDVLRPIS, MOVPRO.BDVLRST, MOVPRO.BDVLRIPI, MOVPRO.BDVLRCOFINS, MOVPRO.BDVLRISSQN,
         iif(MOVPRO.BDCODNATREC = 0, null, MOVPRO.BDCODNATREC) as BDCODNATREC,
         MOVPRO.BDVLRFRETE,
         MOVPRO.BDFCPRETIDO,movpro.BDVLRABATNT,movpro.BDVLRSEGURO,BDBCICMSEFET,BDALIQICMSEFET,BDVLRICMSEFET,BDBCICMSSTRET,BDALIQIMCSSTRET,BDVLRICMSSTRET,
         BDBCFCPSTRET,BDALIQFCPSTRET,BDVLRFCPSTRET,BDALIQFCPRETIDO,BDBCFCPRETIDO, BDBCFCP, BDALQFCP, BDVLRFCP, BDPISCOFQTD, BDCBNEF,
         BDBCICMSMONO, BDALIQICMSMONO, BDVLRICMSMONO, BDBCICMSMONORET, BDALIQICMSMONORET, BDVLRICMSMONORET,
         BDBCICMSMONODIF, BDALIQICMSMONODIF, BDVLRICMSMONODIF, BDBCICMSMONORETANT, BDALIQICMSMONORETANT, BDVLRICMSMONORETANT, BDVLRCBENEF, BDMOTDESONERACAO, BDCODCREDPRES,
         BDALIQCREDPRESUMIDO, BDVLRCREDPRESUMIDO, BDORDEMPROORIG, BDIBS_CBS_CODCCLASSTRIB, BDIBS_CBS_CST, BDIBS_CBS_BASE,
         BDIBS_MUN_REDUCAO, BDIBS_MUN_ALIQ_VIGENTE, BDIBS_MUN_ALIQ_MUNICIP, BDIBS_MUN_VALOR_MUNICIP, BDIBS_MUN_ALIQ_DIF, BDIBS_MUN_VALOR_DIF, 
         BDIBS_MUN_VALOR_DEVOL, BDIBS_UF_REDUCAO, BDIBS_UF_ALIQ_VIGENTE, BDIBS_UF_ALIQ_UF, BDIBS_UF_VALOR_UF, BDIBS_UF_ALIQ_DIF, BDIBS_UF_VALOR_DIF, 
         BDIBS_UF_VALOR_DEVOL, BDIBS_CBS_REDUCAO, BDIBS_CBS_ALIQ_VIGENTE, BDIBS_CBS_ALIQ_CBS, BDIBS_CBS_VALOR_CBS, BDIBS_CBS_ALIQ_DIF, BDIBS_CBS_VALOR_DIF,
         BDIBS_CBS_VALOR_DEVOL, BDIBS_PRES_COD_CRED, BDIBS_PRES_ALIQUOTA, BDIBS_PRES_VALOR, BDIBS_PRES_VLR_COND_SUP, BDCBS_PRES_COD_CRED, BDCBS_PRES_ALIQUOTA,
         BDCBS_PRES_VALOR, BDCBS_PRES_VLR_COND_SUP, BDIBS_MONO_BASE, BDIBS_MONO_ALIQ, BDIBS_MONO_VALOR, BDIBS_MONO_BASE_RET, BDIBS_MONO_ALIQ_RET, BDIBS_MONO_VALOR_RET,
         BDIBS_MONO_BASE_RET_ANT, BDIBS_MONO_ALIQ_RET_ANT, BDIBS_MONO_VALOR_RET_ANT, BDIBS_MONO_BASE_DIFERIDO, BDIBS_MONO_ALIQ_DIFERIDO, BDIBS_MONO_VALOR_DIFERIDO,
          BDCBS_MONO_BASE, BDCBS_MONO_ALIQ, BDCBS_MONO_VALOR, BDCBS_MONO_BASE_RET, BDCBS_MONO_ALIQ_RET, BDCBS_MONO_VALOR_RET, BDCBS_MONO_BASE_RET_ANT,
         BDCBS_MONO_ALIQ_RET_ANT, BDCBS_MONO_VALOR_RET_ANT, BDCBS_MONO_BASE_DIFERIDO, BDCBS_MONO_ALIQ_DIFERIDO, BDCBS_MONO_VALOR_DIFERIDO, 
         BDIS_CODCCLASSTRIB, BDIS_CST, BDIS_UN_TRIB, BDIS_ALIQUOTA, BDIS_BASE, BDIS_ALIQUOTA_ESPECIFICO, BDIS_BASE_ESPECIFICO, BDIS_VALOR_TOTAL, BDCOD_IS_UN_TRIB,
         BDVLRICMSSTDESON, BDMOTICMSSTDESON, MOVPRO.BDIBS_ESTCRED_VALOR, MOVPRO.BDCBS_ESTCRED_VALOR, BDAJUSTECOMP_REF, BDIBS_AJUSTECOMP_VALOR, BDCBS_AJUSTECOMP_VALOR
  FROM (
        SELECT P.*
        FROM TMP_VEF_EMP_TMOVPROSAI_TEMP P
        JOIN VEF_EMP_TMOVSAIITENS S ON(S.BDCODEMP = P.BDCODEMP AND S.BDCHAVE = P.BDEDITCHAVE AND S.BDORDEM = P.BDORDEM)
        WHERE P.BDSESSAO = :PRSESSAO
        AND S.BDCHAVE IS NOT NULL
       ) MOVPRO
  WHERE NOT EXISTS(
                   SELECT I.BDCODINCONSISTENCIA
                   FROM VEF_INCON_TMOVSAI I
                   WHERE I.BDSESSAO = MOVPRO.BDSESSAO
                   AND I.BDCODEMP = MOVPRO.BDCODEMP
                   AND I.BDCHAVE = MOVPRO.BDCHAVE
                  );

  /* Commit das operações com medicamentos - C173 */
  INSERT INTO VEF_EMP_TOPMEDSAI (bdCODEMP, bdCHAVE, bdORDEM, bdORDEMPRO, bdORDEMOPMED, bdNRLOTE, bdQTDITEM,
                                 bdDTFABMED, bdDTVALMED, bdINDTIPOMED, bdTIPOMED, bdVLRMAXMED)
  SELECT bdCODEMP, bdEDITCHAVE, bdORDEM, bdORDEMPRO, bdORDEMOPMED, bdNRLOTE, bdQTDITEM,
         bdDTFABMED, bdDTVALMED, bdINDTIPOMED, bdTIPOMED, bdVLRMAXMED
  FROM (
        SELECT op.*
        FROM TMP_VEF_EMP_TOPMEDSAI_TEMP op
        JOIN VEF_EMP_TMOVPROSAI p ON (p.bdCODEMP = op.bdCODEMP AND p.bdCHAVE = op.bdEDITCHAVE AND p.bdORDEM = op.bdORDEM AND p.bdORDEMPRO = op.bdORDEMPRO)
        WHERE op.bdSESSAO = :prSESSAO
          AND p.bdCHAVE IS NOT NULL
       ) op
  WHERE NOT EXISTS(
                    SELECT i.bdCODINCONSISTENCIA
                    FROM VEF_INCON_TMOVSAI i
                    WHERE i.bdSESSAO = op.bdSESSAO
                      AND i.bdCODEMP = op.bdCODEMP
                      AND i.bdCHAVE  = op.bdCHAVE
                   );

  /*C100*/
  INSERT INTO VEF_EMP_TC100SAI(BDCODEMP, BDCHAVE, BDINDFRETE, BDVLRFRETE, BDVLRSEGURO, BDVLROUTDESP, BDVLRTOTPIS, BDVLRTOTCOFINS,
                               BDVLRTOTPISST, BDVLRTOTCOFINSST, BDVLR_FCP_UF_DEST, BDVLRICMS_UF_DEST, BDVLRICMS_UF_REM, BDVLRABATNT)
  SELECT C.BDCODEMP, C.BDEDITCHAVE, C.BDINDFRETE, C.BDVLRFRETE, C.BDVLRSEGURO, C.BDVLROUTDESP, C.BDVLRTOTPIS, C.BDVLRTOTCOFINS,
         C.BDVLRTOTPISST, C.BDVLRTOTCOFINSST, C.BDVLR_FCP_UF_DEST, C.BDVLRICMS_UF_DEST, C.BDVLRICMS_UF_REM, C.BDVLRABATNT
  FROM TMP_VEF_EMP_TC100SAI_TEMP C
  JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDEDITCHAVE)
  WHERE C.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                   SELECT I.BDCODINCONSISTENCIA
                   FROM VEF_INCON_TMOVSAI I
                   WHERE I.BDSESSAO = C.BDSESSAO
                   AND I.BDCODEMP = C.BDCODEMP
                   AND I.BDCHAVE = C.BDCHAVE
                  );

  /*C110 - Informação complementar do lançamento*/
  INSERT INTO VEF_EMP_TMOVSAIINFCOM(BDCODEMP, BDCHAVE, BDORDEMIC, BDORDEMINFCOM, BDDESCCOMPIC)
  SELECT C.BDCODEMP, C.BDEDITCHAVE, C.BDORDEMIC, C.BDALTORDEMINFCOM, C.BDDESCCOMPIC
  FROM TMP_VEF_EMP_TMOVSAIINFCOM_TEMP C
  JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDEDITCHAVE)
  WHERE C.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = C.BDSESSAO
                 AND I.BDCODEMP = C.BDCODEMP
                 AND I.BDCHAVE = C.BDCHAVE
                );

  /*C111 - Processo referenciado*/
  INSERT INTO VEF_EMP_TMOVSAIPROREF(BDCODEMP, BDCHAVE, BDORDEMIC, BDORDEMPROREF, BDNUMPROC, BDINDPROCESSO)
  SELECT S.BDCODEMP, S.BDEDITCHAVE BDCHAVE, S.BDORDEMIC, S.BDORDEMPROREF, S.BDNUMPROC, S.BDINDPROCESSO
  FROM TMP_VEF_EMP_TMOVSAIPROREF_TEMP S
  JOIN VEF_EMP_TMOVSAIINFCOM C ON(C.BDCODEMP = S.BDCODEMP AND C.BDCHAVE = S.BDEDITCHAVE AND C.BDORDEMIC = S.BDORDEMIC)
  WHERE S.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = S.BDSESSAO
                 AND I.BDCODEMP = S.BDCODEMP
                 AND I.BDCHAVE = S.BDCHAVE
                );

  /*C112 - Documento de arrecadação referenciado*/
  INSERT INTO VEF_EMP_TMOVSAIDOCAREF(BDCODEMP, BDCHAVE, BDORDEMIC, BDORDEMDOCAREF, BDCODUF, BDMODCODDA, BDNUMDA, BDCODAUT, BDVLRDA, BDDTVCTO, BDDTPGTO)
  SELECT S.BDCODEMP, S.BDEDITCHAVE BDCHAVE, S.BDORDEMIC, S.BDORDEMDOCAREF, S.BDCODUF, S.BDMODCODDA, S.BDNUMDA, S.BDCODAUT, S.BDVLRDA, S.BDDTVCTO, S.BDDTPGTO
  FROM TMP_VEF_EMP_TMOVSAIDOCAREF_TEMP S
  JOIN VEF_EMP_TMOVSAIINFCOM C ON(C.BDCODEMP = S.BDCODEMP AND C.BDCHAVE = S.BDEDITCHAVE AND C.BDORDEMIC = S.BDORDEMIC)
  WHERE S.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = S.BDSESSAO
                 AND I.BDCODEMP = S.BDCODEMP
                 AND I.BDCHAVE = S.BDCHAVE
                );

  /*C113 - Documento fiscal referenciado*/
  INSERT INTO VEF_EMP_TMOVSAIDOCFREF(BDCODEMP, BDCHAVE, BDORDEMIC, BDORDEMDOCFREF, BDCODTER, BDCODDOCFIS, BDINDEMIT, BDSERIE, BDSUBSERIE, BDNUMDOC, BDDTEMISSAO, BDINDOPER, BDCHAVENFE)
  SELECT S.BDCODEMP, S.BDEDITCHAVE BDCHAVE, S.BDORDEMIC, S.BDORDEMDOCFREF, S.BDALTCODTER BDCODTER, S.BDCODDOCFIS,
         S.BDINDEMIT, S.BDSERIE, S.BDSUBSERIE, S.BDNUMDOC, S.BDDTEMISSAO, S.BDINDOPER, S.BDCHAVENFE
  FROM TMP_VEF_EMP_TMOVSAIDOCFREF_TEMP S
  JOIN VEF_EMP_TMOVSAIINFCOM C ON(C.BDCODEMP = S.BDCODEMP AND C.BDCHAVE = S.BDEDITCHAVE AND C.BDORDEMIC = S.BDORDEMIC)
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER ON(TER.BDSESSAO = :PRSESSAOTER AND TER.BDEDITCHAVE = S.BDALTCODTER)
  WHERE S.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = S.BDSESSAO
                 AND I.BDCODEMP = S.BDCODEMP
                 AND I.BDCHAVE = S.BDCHAVE
                )
  AND NOT EXISTS(
                 SELECT T.BDCODTER
                 FROM VEF_INCON_TTERCEIROS T
                 WHERE T.BDSESSAO = :PRSESSAOTER
                 AND T.BDCODTER = TER.BDCODTER
                );

  /*C114 - Cupom fiscal referenciado*/
  INSERT INTO VEF_EMP_TMOVSAICUPREF(BDCODEMP, BDCHAVE, BDORDEMIC, BDORDEMCUPREF, BDCODDOCFIS, BDNRSERCAIXA, BDNUMCAIXA, BDNUMDOC, BDDTDOC)
  SELECT S.BDCODEMP, S.BDEDITCHAVE BDCHAVE, S.BDORDEMIC, S.BDORDEMCUPREF, S.BDCODDOCFIS, S.BDNRSERCAIXA, S.BDNUMCAIXA, S.BDNUMDOC, S.BDDTDOC
  FROM TMP_VEF_EMP_TMOVSAICUPREF_TEMP S
  JOIN VEF_EMP_TMOVSAIINFCOM C ON(C.BDCODEMP = S.BDCODEMP AND C.BDCHAVE = S.BDEDITCHAVE AND C.BDORDEMIC = S.BDORDEMIC)
  WHERE S.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = S.BDSESSAO
                 AND I.BDCODEMP = S.BDCODEMP
                 AND I.BDCHAVE = S.BDCHAVE
                );

  /*C115*/
  INSERT INTO VEF_EMP_TMOVSAILOCCOL(BDCODEMP, BDCHAVE, BDORDEMIC, BDORDEMLOCCOL, BDCODTRAN, BDCODCIDCOLETA, BDCODTERCOLETA, BDCODTERENTREGA, BDCODCIDENTREGA)
  SELECT C.BDCODEMP, C.BDEDITCHAVE BDCHAVE, C.BDORDEMIC, C.BDORDEMLOCCOL, C.BDCODTRAN,
         C.BDCODCIDCOLETA, C.BDCODTERCOLETA, C.BDCODTERENTREGA, C.BDCODCIDENTREGA
  FROM TMP_VEF_EMP_TMOVSAILOCCOL_TEMP C
  JOIN VEF_EMP_TMOVSAIINFCOM S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDEDITCHAVE AND S.BDORDEMIC = C.BDORDEMIC)
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER ON(TER.BDSESSAO = :PRSESSAOTER AND TER.BDEDITCHAVE = C.BDALTCODTERCOLETA)
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER_ENT ON(TER_ENT.BDSESSAO = :PRSESSAOTER AND TER_ENT.BDEDITCHAVE = C.BDALTCODTERENTREGA)
  WHERE C.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = C.BDSESSAO
                 AND I.BDCODEMP = C.BDCODEMP
                 AND I.BDCHAVE = C.BDCHAVE
                )
  AND NOT EXISTS(
                 SELECT T.BDCODTER
                 FROM VEF_INCON_TTERCEIROS T
                 WHERE T.BDSESSAO = :PRSESSAOTER
                 AND T.BDCODTER = TER.BDCODTER
                )
  AND NOT EXISTS(
                 SELECT T.BDCODTER
                 FROM VEF_INCON_TTERCEIROS T
                 WHERE T.BDSESSAO = :PRSESSAOTER
                 AND T.BDCODTER = TER_ENT.BDCODTER
                );

  /*C116
  */
  INSERT INTO VEF_EMP_TMOVSAICUPOMREF (bdcodemp, bdchave, bdordemic, bdordemcupom, bdmodelo, bdcodequipsat, bdchavecfe, bdnumcupom, bddatadoc)
  SELECT s.bdcodemp, s.bdeditchave, s.bdordemic, s.bdordemcupom, s.bdmodelo, s.bdcodequipsat, s.bdchavecfe, s.bdnumcupom, s.bddatadoc
  FROM TMP_VEF_EMP_TMOVSAICUPOM_TEMP S
  JOIN VEF_EMP_TMOVSAIINFCOM C ON(C.BDCODEMP = S.BDCODEMP AND C.BDORDEMIC = S.bdordemic AND C.bdchave = S.bdeditchave)
  WHERE S.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = S.BDSESSAO
                 AND I.BDCODEMP = S.BDCODEMP
                 AND I.BDCHAVE = S.BDCHAVE
                );


  /*C160 - Volumes transportados*/
  INSERT INTO VEF_EMP_TMOVSAIVLTRAN(BDCODEMP, BDCHAVE, BDCODTER, BDCODUF, BDQTDVOLTRAN, BDPESOBRUTO, BDPESOLIQUIDO, BDPLACAID)
  SELECT S.BDCODEMP, S.BDEDITCHAVE BDCHAVE, S.BDALTCODTER BDCODTER, S.BDCODUF,
         S.BDQTDVOLTRAN, S.BDPESOBRUTO, S.BDPESOLIQUIDO, S.BDPLACAID
  FROM TMP_VEF_EMP_TMOVSAIVLTRAN_TEMP S
  JOIN VEF_EMP_TMOVSAI C ON(C.BDCODEMP = S.BDCODEMP AND C.BDCHAVE = S.BDEDITCHAVE)
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER ON(TER.BDSESSAO = :PRSESSAOTER AND TER.BDEDITCHAVE = S.BDALTCODTER)
  WHERE S.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = S.BDSESSAO
                 AND I.BDCODEMP = S.BDCODEMP
                 AND I.BDCHAVE = S.BDCHAVE
                )
  AND NOT EXISTS(
                 SELECT T.BDCODTER
                 FROM VEF_INCON_TTERCEIROS T
                 WHERE T.BDSESSAO = :PRSESSAOTER
                 AND T.BDCODTER = TER.BDCODTER
                );

  /*C195 - Observação*/
  INSERT INTO VEF_EMP_TC195SAI(BDCODEMP, BDCHAVE, BDORDEMOBS, BDCODOBS, BDDESCCOMPL, bdCODTIPO, BDTIPOOPERACAO)
  SELECT S.BDCODEMP, S.BDEDITCHAVE BDCHAVE, S.BDORDEMOBS, S.BDALTCODOBS BDCODOBS, S.BDDESCCOMPL, s.bdCODTIPO, S.BDTIPOOPERACAO
  FROM TMP_VEF_EMP_TC195SAI_TEMP S
  JOIN VEF_EMP_TMOVSAI C ON(C.BDCODEMP = S.BDCODEMP AND C.BDCHAVE = S.BDEDITCHAVE)
  WHERE S.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = S.BDSESSAO
                 AND I.BDCODEMP = S.BDCODEMP
                 AND I.BDCHAVE = S.BDCHAVE
                );

  /*C197 - Outras obrigações tributáveis*/
  INSERT INTO VEF_EMP_TC197SAI(BDCODEMP, BDCHAVE, BDORDEMOBS, BDORDEMOUTOBR, BDCODPROD, BDCODAJU, BDDESCCOMPL, BDBICMS, BDALIQICMS, BDVLRICMS, BDOUTVLR, BDORDEMITEM1400, BDBENEFICIO)
  SELECT S.BDCODEMP, S.BDEDITCHAVE BDCHAVE, S.BDORDEMOBS, S.BDORDEMOUTOBR,
         IIF((S.BDALTCODPROD > 0), S.BDALTCODPROD, NULL) AS BDCODPROD, -- Alt.: #88192 - Estava tentado gravar o C197 com produto zero quando é gerado pelo plano de ações...
         S.BDCODAJU, S.BDDESCCOMPL, S.BDBICMS, S.BDALIQICMS, S.BDVLRICMS, S.BDOUTVLR, S.BDORDEMITEM1400, S.BDBENEFICIO
  FROM TMP_VEF_EMP_TC197SAI_TEMP S
  JOIN VEF_EMP_TC195SAI C ON(C.BDCODEMP = S.BDCODEMP AND C.BDCHAVE = S.BDEDITCHAVE AND C.BDORDEMOBS = S.BDORDEMOBS)
  WHERE S.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = S.BDSESSAO
                 AND I.BDCODEMP = S.BDCODEMP
                 AND I.BDCHAVE = S.BDCHAVE
                );

  /*C300*/
  INSERT INTO VEF_EMP_TC300350SAI(BDCODEMP, BDCHAVE, BDCODCTA, BDVLRTOTPIS, BDVLRTOTCOFINS)
  SELECT S.BDCODEMP, S.BDEDITCHAVE BDCHAVE, S.BDCODCTA, S.BDVLRTOTPIS, S.BDVLRTOTCOFINS
  FROM TMP_VEF_EMP_TC300350SAI_TEMP S
  JOIN VEF_EMP_TMOVSAI C ON(C.BDCODEMP = S.BDCODEMP AND C.BDCHAVE = S.BDEDITCHAVE)
  WHERE S.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = S.BDSESSAO
                 AND I.BDCODEMP = S.BDCODEMP
                 AND I.BDCHAVE = S.BDCHAVE
                );
    
  /* Alt.: #76595 #89560 #98636 #121104 - Importação do C800/C850 - Importação mod 59 layout Sped Fiscal
     C850 - REGISTRO C850: REGISTRO ANALÍTICO DO CF-E-SAT (CODIGO 59)*/
  INSERT INTO VEF_EMP_TC850SAI(bdCODEMP, bdCHAVE, bdORDEM, bdCODIGO, bdCODCSTICMS, bdVLROPER, bdVLRBCICMS, bdALIQICMS, bdVLRICMS, bdCODOBS)
  SELECT c.bdCODEMP, c.bdEDITCHAVE AS bdCHAVE, c.bdORDEM, c.bdCODIGO, c.bdCODCSTICMS, c.bdVLROPER, c.bdVLRBCICMS, c.bdALIQICMS, c.bdVLRICMS, c.bdALTCODOBS AS bdCODOBS
  FROM TMP_VEF_EMP_TC850SAI_TEMP c
--  JOIN VEF_EMP_TMOVSAI s ON(s.bdCODEMP = c.bdCODEMP AND s.bdCHAVE = c.bdEDITCHAVE)
  JOIN VEF_EMP_TMOVSAIITENS S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDEDITCHAVE AND S.BDORDEM = C.BDORDEM)
  WHERE c.BDSESSAO = :prSESSAO
  AND NOT EXISTS(
                 SELECT i.bdCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI i
                 WHERE i.bdSESSAO = c.bdSESSAO
                   AND i.bdCODEMP = c.bdCODEMP
                   AND i.bdCHAVE = c.bdCHAVE
                );

  /*D195 - Observação*/
  INSERT INTO VEF_EMP_TD195SAI(BDCODEMP, BDCHAVE, BDORDEMOBS, BDCODOBS, BDDESCCOMPL, bdCODTIPO)
  SELECT D.BDCODEMP, D.BDEDITCHAVE BDCHAVE, D.BDORDEMOBS, D.BDALTCODOBS BDCODOBS, D.BDDESCCOMPL, d.bdCODTIPO
  FROM TMP_VEF_EMP_TD195SAI_TEMP D
  JOIN VEF_EMP_TMOVSAI C ON(C.BDCODEMP = D.BDCODEMP AND C.BDCHAVE = D.BDEDITCHAVE)
  WHERE D.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = D.BDSESSAO
                 AND I.BDCODEMP = D.BDCODEMP
                 AND I.BDCHAVE = D.BDCHAVE
                );

  /*D197 - Outras obrigações tributáveis*/
  INSERT INTO VEF_EMP_TD197SAI(BDCODEMP, BDCHAVE, BDORDEMOBS, BDORDEMOUTOBR, BDCODPROD, BDCODAJU, BDDESCCOMPL, BDBICMS, BDALIQICMS, BDVLRICMS, BDOUTVLR, BDORDEMITEM1400, BDBENEFICIO)
  SELECT D.BDCODEMP, D.BDEDITCHAVE BDCHAVE, D.BDORDEMOBS, D.BDORDEMOUTOBR, D.BDALTCODPROD BDCODPROD,
         D.BDCODAJU, D.BDDESCCOMPL, D.BDBICMS, D.BDALIQICMS, D.BDVLRICMS, D.BDOUTVLR, D.BDORDEMITEM1400, D.bdbeneficio
  FROM TMP_VEF_EMP_TD197SAI_TEMP D
  JOIN VEF_EMP_TD195SAI C ON(C.BDCODEMP = D.BDCODEMP AND C.BDCHAVE = D.BDEDITCHAVE AND C.BDORDEMOBS = D.BDORDEMOBS)
  WHERE D.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODINCONSISTENCIA
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = D.BDSESSAO
                 AND I.BDCODEMP = D.BDCODEMP
                 AND I.BDCHAVE = D.BDCHAVE
                );                
                
  /*D100*/
  INSERT INTO VEF_EMP_TD100SAI(BDCODEMP, BDCHAVE, BDCODCTA, BDORDEMINFCOM, BDCHAVECTE, BDTIPOCTE, BDCHAVECTEREF, BDINDFRETE, BDVLRPIS,
                               BDVLRCOFINS, BDCODCSTPIS, BDVL_BC_PIS, BDALIQ_PIS, BDCODCSTCOF, BDVL_BC_COF, BDALIQ_COF, BDCODNATREC,
                               BDVLR_FCP_UF_DEST, BDVLRICMS_UF_DEST, BDVLRICMS_UF_REM, BDCIDORIGEM, BDCIDDEST)
  SELECT D.BDCODEMP, D.BDEDITCHAVE, D.BDCODCTA, IIF(D.BDALTORDEMINFCOM <> 0, D.BDALTORDEMINFCOM, NULL) BDALTORDEMINFCOM, D.BDCHAVECTE, D.BDTIPOCTE, D.BDCHAVECTEREF, D.BDINDFRETE, D.BDVLRPIS,
         D.BDVLRCOFINS, D.BDCODCSTPIS, D.BDVL_BC_PIS, D.BDALIQ_PIS, D.BDCODCSTCOF, D.BDVL_BC_COF, D.BDALIQ_COF, D.BDCODNATREC,
         D.BDVLR_FCP_UF_DEST, D.BDVLRICMS_UF_DEST, D.BDVLRICMS_UF_REM, D.BDCIDORIGEM, D.BDCIDDEST
  FROM TMP_VEF_EMP_TD100SAI_TEMP D
  JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = D.BDCODEMP AND S.BDCHAVE = D.BDEDITCHAVE)
  WHERE D.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = D.BDSESSAO
                 AND I.BDCODEMP = D.BDCODEMP
                 AND I.BDCHAVE = D.BDCHAVE
                );        
                
  /*D110*/
  INSERT INTO VEF_EMP_TD110SAI(BDCODEMP, BDCHAVE, BDORDEMST, BDCODPROD, BDVLRSER, BDOUTVAL)
  SELECT D.BDCODEMP, D.BDEDITCHAVE BDCHAVE, D.BDORDEMST, D.BDALTCODPROD BDCODPROD, D.BDVLRSER, D.BDOUTVAL
  FROM TMP_VEF_EMP_TD110SAI_TEMP D
  JOIN VEF_EMP_TD100SAI S ON(S.BDCODEMP = D.BDCODEMP AND S.BDCHAVE = D.BDEDITCHAVE)
  WHERE D.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = D.BDSESSAO
                 AND I.BDCODEMP = D.BDCODEMP
                 AND I.BDCHAVE = D.BDCHAVE
                );            

  /*D120*/
  INSERT INTO VEF_EMP_TD120COMPCON(BDCODEMP, BDCHAVE, BDORDEMST, BDORDEMD120, BDCODCIDORIG, BDCODUF, BDCODCIDDEST, BDPLACAVEICULO)
  SELECT D.BDCODEMP, D.BDEDITCHAVE BDCHAVE, D.BDORDEMST, D.BDORDEMD120, D.BDCODCIDORIG, D.BDCODUF, D.BDCODCIDDEST, D.BDPLACAVEICULO
  FROM TMP_VEF_EMP_TD120COMPCON_TEMP D
  JOIN VEF_EMP_TD110SAI S ON(S.BDCODEMP = D.BDCODEMP AND S.BDCHAVE = D.BDEDITCHAVE AND S.BDORDEMST = D.BDORDEMST)
  WHERE D.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = D.BDSESSAO
                 AND I.BDCODEMP = D.BDCODEMP
                 AND I.BDCHAVE = D.BDCHAVE
                );            

  /*D130*/
  INSERT INTO VEF_EMP_TD130COMPCON(BDCODEMP, BDCHAVE, BDORDEM,BDCODTERCONSIGNATARIO, BDCODUF, BDCODTERREDESPACHANTE, BDCODCIDDESTINO, BDCODCIDORIGEM,
                                   BDINDFRETERED, BDPLACAID, BDVLRLIQFRETE, BDVLRSECCAT, BDVLRDESPACHO, BDVLRPEDAGIO, BDVLROUTVAL, BDVLRTOTALFRETE)
  SELECT D.BDCODEMP, D.BDEDITCHAVE BDCHAVE, BDORDEM ,D.BDALTCODTER BDCODTERCONSIGNATARIO, D.BDCODUF, D.BDALTCODTERREDESPACHANTE BDCODTERREDESPACHANTE,
         D.BDCODCIDDESTINO, D.BDCODCIDORIGEM, D.BDINDFRETERED, D.BDPLACAID, D.BDVLRLIQFRETE, D.BDVLRSECCAT, D.BDVLRDESPACHO, D.BDVLRPEDAGIO,
         D.BDVLROUTVAL, D.BDVLRTOTALFRETE
  FROM TMP_VEF_EMP_TD130COMPCON_TEMP D
  JOIN VEF_EMP_TD100SAI S ON(S.BDCODEMP = D.BDCODEMP AND S.BDCHAVE = D.BDEDITCHAVE)
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER_C ON(TER_C.BDSESSAO = :PRSESSAOTER AND TER_C.BDEDITCHAVE = D.BDALTCODTER)
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER_R ON(TER_R.BDSESSAO = :PRSESSAOTER AND TER_R.BDEDITCHAVE = D.BDALTCODTERREDESPACHANTE)
  WHERE D.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = D.BDSESSAO
                 AND I.BDCODEMP = D.BDCODEMP
                 AND I.BDCHAVE = D.BDCHAVE
                )
  AND NOT EXISTS(
                 SELECT T.BDCODTER
                 FROM VEF_INCON_TTERCEIROS T
                 WHERE T.BDSESSAO = :PRSESSAOTER
                 AND T.BDCODTER = TER_C.BDCODTER
                )
  AND NOT EXISTS(
                 SELECT T.BDCODTER
                 FROM VEF_INCON_TTERCEIROS T
                 WHERE T.BDSESSAO = :PRSESSAOTER
                 AND T.BDCODTER = TER_R.BDCODTER
                );

  /*D160*/
  INSERT INTO VEF_EMP_TD160CARGATRANS(BDCODEMP, BDCHAVE, BDORDEMCARTRANS, BDCODTERREMETENTE, BDCODTERDESTINATARIO, BDNRDESPACHO,
                                      BDCODCIDREMETENTE, BDCODCIDDESTINATARIO, BDCODTERCOLETA, BDCODCIDCOLETA, BDCODTERENTREGA,
                                      BDCODCIDENTREGA, BDCODTRAN, BDGERAD161)
  SELECT D.BDCODEMP, D.BDEDITCHAVE BDCHAVE, D.BDORDEMCARTRANS, D.BDALTCODTERREMETENTE BDCODTERREMETENTE,
         D.BDALTCODTERDESTINATARIO BDCODTERDESTINATARIO, D.BDNRDESPACHO, D.BDCODCIDREMETENTE, D.BDCODCIDDESTINATARIO,
         D.BDALTCODTERCOLETA BDCODTERCOLETA, D.BDCODCIDCOLETA, D.BDALTCODTERENTREGA BDCODTERENTREGA, D.BDCODCIDENTREGA,
         D.BDCODTRAN, D.BDGERAD161
  FROM TMP_VEF_EMP_TD160CARTRANS_TEMP D
  JOIN VEF_EMP_TD100SAI S ON(S.BDCODEMP = D.BDCODEMP AND S.BDCHAVE = D.BDEDITCHAVE)
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER_REM ON(TER_REM.BDSESSAO = :PRSESSAOTER AND TER_REM.BDEDITCHAVE = D.BDALTCODTERREMETENTE)
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER_DEST ON(TER_DEST.BDSESSAO = :PRSESSAOTER AND TER_DEST.BDEDITCHAVE = D.BDALTCODTERDESTINATARIO)
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER_COL ON(TER_COL.BDSESSAO = :PRSESSAOTER AND TER_COL.BDEDITCHAVE = D.BDALTCODTERCOLETA)
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER_ENT ON(TER_ENT.BDSESSAO = :PRSESSAOTER AND TER_ENT.BDEDITCHAVE = D.BDALTCODTERENTREGA)
  WHERE D.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = D.BDSESSAO
                 AND I.BDCODEMP = D.BDCODEMP
                 AND I.BDCHAVE = D.BDCHAVE
                )
  AND NOT EXISTS(
                 SELECT T.BDCODTER
                 FROM VEF_INCON_TTERCEIROS T
                 WHERE T.BDSESSAO = :PRSESSAOTER
                 AND T.BDCODTER = TER_REM.BDCODTER
                )
  AND NOT EXISTS(
                 SELECT T.BDCODTER
                 FROM VEF_INCON_TTERCEIROS T
                 WHERE T.BDSESSAO = :PRSESSAOTER
                 AND T.BDCODTER = TER_DEST.BDCODTER
                )
  AND NOT EXISTS(
                 SELECT T.BDCODTER
                 FROM VEF_INCON_TTERCEIROS T
                 WHERE T.BDSESSAO = :PRSESSAOTER
                 AND T.BDCODTER = TER_COL.BDCODTER
                )
  AND NOT EXISTS(
                 SELECT T.BDCODTER
                 FROM VEF_INCON_TTERCEIROS T
                 WHERE T.BDSESSAO = :PRSESSAOTER
                 AND T.BDCODTER = TER_ENT.BDCODTER
                );

  /*D162*/
  INSERT INTO VEF_EMP_TD162DOCFIS(BDCODEMP, BDCHAVE, BDORDEMCARTRANS, BDORDEMDOCFIS, BDCODDOCFIS, BDSERIE, BDNRDOC, BDDTDOC, BDVLRDOC,
                                  BDVLRMER, BDQTDVOL, BDPESOBRUTO, BDPESOLIQ, BDCHAVENFE)
  SELECT D.BDCODEMP, D.BDEDITCHAVE BDCHAVE, D.BDORDEMCARTRANS, D.BDORDEMDOCFIS, D.BDCODDOCFIS, D.BDSERIE, D.BDNRDOC,
         D.BDDTDOC, D.BDVLRDOC, D.BDVLRMER, D.BDQTDVOL, D.BDPESOBRUTO, D.BDPESOLIQ, D.BDCHAVENFE
  FROM TMP_VEF_EMP_TD162DOCFIS_TEMP D
  JOIN VEF_EMP_TD160CARGATRANS S ON(S.BDCODEMP = D.BDCODEMP AND S.BDCHAVE = D.BDEDITCHAVE AND S.BDORDEMCARTRANS = D.BDORDEMCARTRANS)
  WHERE D.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = D.BDSESSAO
                 AND I.BDCODEMP = D.BDCODEMP
                 AND I.BDCHAVE = D.BDCHAVE
                );                

  /*C190 - Saída*/
  INSERT INTO VEF_EMP_TC190SAI(BDCODEMP, BDCHAVE, BDORDEM, BDCODIGO, BDCODOBS, BDCODCSTICMS, BDALIQICMS, BDVLROPER,
                               BDVLRBCICMS, BDVLRICMS, BDVLRBCICMSST, BDVLRICMSST, BDVLRREDBC, BDVLRIPI, BDFCPRETIDO)
  SELECT C.BDCODEMP, C.BDEDITCHAVE BDCHAVE, C.BDORDEM, C.BDCODIGO, C.BDALTCODOBS BDCODOBS, C.BDCODCSTICMS,
         C.BDALIQICMS, C.BDVLROPER, C.BDVLRBCICMS, C.BDVLRICMS, C.BDVLRBCICMSST, C.BDVLRICMSST, C.BDVLRREDBC, C.BDVLRIPI, c.BDFCPRETIDO
  FROM TMP_VEF_EMP_TC190SAI_TEMP C
  JOIN VEF_EMP_TMOVSAIITENS S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDEDITCHAVE AND S.BDORDEM = C.BDORDEM)
  WHERE C.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = C.BDSESSAO
                 AND I.BDCODEMP = C.BDCODEMP
                 AND I.BDCHAVE = C.BDCHAVE
                );

  /*C178*/
  INSERT INTO VEF_EMP_TMOVPROSAIC178(BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDORDEMCLAIPI, BDVLRUNIDADE, BDQTDUNIDADE)
  SELECT C.BDCODEMP, C.BDEDITCHAVE BDCHAVE, C.BDORDEM, C.BDORDEMPRO,
         C.BDORDEMCLAIPI, C.BDVLRUNIDADE, C.BDQTDUNIDADE
  FROM TMP_VEF_EMP_TMOVPROSAIC178_TEMP C
  JOIN VEF_EMP_TMOVPROSAI S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDEDITCHAVE AND S.BDORDEM = C.BDORDEM AND S.BDORDEMPRO = C.BDORDEMPRO)
  WHERE C.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = C.BDSESSAO
                 AND I.BDCODEMP = C.BDCODEMP
                 AND I.BDCHAVE = C.BDCHAVE
                );            

  /*C177*/
  INSERT INTO VEF_EMP_TMOVPROSAIC177(BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODSELOIPI, BDQTDSELOIPI, BDCODINFAD,
                                     BDINCENTIVOTRANSP,BDOPEINCENTIVADA,BDSAIINCENTIVADAPORIMP,BDVLRBASECREDPRESUMIDO,BDPERCREDPRESUMIDO, BDCODTIPO)
  SELECT C.BDCODEMP, C.BDEDITCHAVE BDCHAVE, C.BDORDEM, C.BDORDEMPRO, C.BDCODSELOIPI, C.BDQTDSELOIPI, C.BDCODINFAD, C.BDINCENTIVOTRANSP,
  C.BDOPEINCENTIVADA,C.BDSAIINCENTIVADAPORIMP,C.BDVLRBASECREDPRESUMIDO, C.BDPERCREDPRESUMIDO, C.BDCODTIPO
  FROM TMP_VEF_EMP_TMOVPROSAIC177_TEMP C
  JOIN VEF_EMP_TMOVPROSAI S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDEDITCHAVE AND S.BDORDEM = C.BDORDEM AND S.BDORDEMPRO = C.BDORDEMPRO)
  WHERE C.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = C.BDSESSAO
                 AND I.BDCODEMP = C.BDCODEMP
                 AND I.BDCHAVE = C.BDCHAVE
                );                
                
  /*C176*/
  INSERT INTO VEF_EMP_TMOVSTC176(BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDORDEMC176, BDMODELO, BDORDEMMOTRES, BDCODTER, BDCODTER_NFE, BDNUM_DOC_ULT_E,
                                 BDSER_ULT_E, BDDT_ULT_E, BDQUANT_ULT_E, BDVL_UNIT_ULT_E, BDVL_UNIT_BC_ST, BDCHAVE_NFE_ULT_E, BDNUM_ITEM_ULT_E,
                                 BDVL_UNIT_BC_ICMS_ULT_E, BDALIQ_ICMS_ULT_E, BDVL_UNIT_LIM_BC_ICMS_ULT_E, BDVL_UNIT_ICMS_ULT_E, BDALIQ_ST_ULT_E,
                                 BDVL_UNIT_RES, BDCOD_RESP_RET, BDCHAVE_NFE_RET, BDSER_NFE_RET, BDNUM_NFE_RET, BDCOD_DA, BDNUM_DA, BDITEM_NFE_RET,BDVL_UNIT_RES_FC)
  SELECT C.BDCODEMP, C.BDEDITCHAVE BDCHAVE, C.BDORDEM, C.BDORDEMPRO, C.BDORDEMC176, C.BDMODELO, C.BDORDEMMOTRES, C.BDALTCODTER BDCODTER,
         C.BDALTCODTER_NFE BDCODTER_NFE, C.BDNUM_DOC_ULT_E, C.BDSER_ULT_E, C.BDDT_ULT_E, C.BDQUANT_ULT_E, C.BDVL_UNIT_ULT_E, C.BDVL_UNIT_BC_ST,
         C.BDCHAVE_NFE_ULT_E, C.BDNUM_ITEM_ULT_E, C.BDVL_UNIT_BC_ICMS_ULT_E, C.BDALIQ_ICMS_ULT_E, C.BDVL_UNIT_LIM_BC_ICMS_ULT_E, C.BDVL_UNIT_ICMS_ULT_E,
         C.BDALIQ_ST_ULT_E, C.BDVL_UNIT_RES, C.BDCOD_RESP_RET, C.BDCHAVE_NFE_RET, C.BDSER_NFE_RET, C.BDNUM_NFE_RET, C.BDCOD_DA, C.BDNUM_DA, C.BDITEM_NFE_RET,c.BDVL_UNIT_RES_FC
  FROM TMP_VEF_EMP_TMOVSTC176_TEMP C
  JOIN VEF_EMP_TMOVPROSAI S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDEDITCHAVE AND S.BDORDEM = C.BDORDEM AND S.BDORDEMPRO = C.BDORDEMPRO)
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER ON(TER.BDSESSAO = :PRSESSAOTER AND TER.BDEDITCHAVE = C.BDALTCODTER)
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER_NFE ON(TER_NFE.BDSESSAO = :PRSESSAOTER AND TER_NFE.BDEDITCHAVE = C.BDALTCODTER_NFE)
  WHERE C.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = C.BDSESSAO
                 AND I.BDCODEMP = C.BDCODEMP
                 AND I.BDCHAVE = C.BDCHAVE
                )
  AND NOT EXISTS(
                 SELECT T.BDCODTER
                 FROM VEF_INCON_TTERCEIROS T
                 WHERE T.BDSESSAO = :PRSESSAOTER
                 AND T.BDCODTER = TER.BDCODTER
                )
  AND NOT EXISTS(
                 SELECT T.BDCODTER
                 FROM VEF_INCON_TTERCEIROS T
                 WHERE T.BDSESSAO = :PRSESSAOTER
                 AND T.BDCODTER = TER_NFE.BDCODTER
                );

  /*D500*/
  INSERT INTO VEF_EMP_TD500SAI(BDCODEMP, BDCHAVE, BDORDEMINFCOM, BDCODCTA, BDTIPOASSINANTE, BDVLRSER,BDVLRSERNTRIB,
  BDVLRCOBTERC,BDVLROUTDESP,BDVLRPIS,BDVLRCOFINS,BDCODCSTPIS,BDVL_BC_PIS,BDALIQ_PIS,BDVL_PIS,BDCODCSTCOF,BDVL_BC_COF,BDALIQ_COF,
  BDVL_COF,BDCODNATREC,BDCODTPREC,BDCODCLAENETEL,BDIDCONSASSI,BDCODCONS,BDCODTIPOCLI,BDNRFATCOMER,BDCODPLAPADRAO,BDCODTPLA,BDFINALIDADE,BDTP_FATURAMENTO, BDCODCONS62, BDFORMA_PAGAMENTO,BDDOCREF_MODELO, BDDOCREF_HASH, BDDOCREF_SERIE, BDDOCREF_NUMERO, BDDOCREF_REFERENCIA, BDDOCREF_CHAVEDFE)
  SELECT D.BDCODEMP, D.BDEDITCHAVE, D.BDORDEMINFCOM, D.BDCODCTA, D.BDTIPOASSINANTE, D.BDVLRSER, D.BDVLRSERNTRIB, D.BDVLRCOBTERC,
  D.BDVLROUTDESP, D.BDVLRPIS, D.BDVLRCOFINS, D.BDCODCSTPIS, D.BDVL_BC_PIS, D.BDALIQ_PIS, D.BDVL_PIS, D.BDCODCSTCOF, D.BDVL_BC_COF,
  D.BDALIQ_COF,D.BDVL_COF, D.BDCODNATREC, D.BDCODTPREC, D.BDCODCLAENETEL, D.BDIDCONSASSI, D.BDCODCONS, D.BDCODTIPOCLI, D.BDNRFATCOMER,
  D.BDCODPLAPADRAO, D.BDCODTPLA, D.BDFINALIDADE, D.BDTP_FATURAMENTO, D.BDCODCONS62, D.BDFORMA_PAGAMENTO,
  D.BDDOCREF_MODELO, D.BDDOCREF_HASH, D.BDDOCREF_SERIE, D.BDDOCREF_NUMERO, D.BDDOCREF_REFERENCIA, D.BDDOCREF_CHAVEDFE
  FROM TMP_VEF_EMP_TD500SAI_TEMP D
  JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = D.BDCODEMP AND S.BDCHAVE = D.BDEDITCHAVE)
  WHERE D.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = D.BDSESSAO
                 AND I.BDCODEMP = D.BDCODEMP
                 AND I.BDCHAVE = D.BDCHAVE
                );

  /*D530*/
  INSERT INTO VEF_EMP_TD530SAI(BDCODEMP, BDCHAVE,BDORDEMTF , BDCODTIPOSER, BDDATAINISER, BDDATAFIMSER, BDPERIODOSER,BDCODAREATER,BDINDTER)
  SELECT D.BDCODEMP,D.BDEDITCHAVE, D.BDORDEMTF, D.BDCODTIPOSER, D.BDDATAINISER, D.BDDATAFIMSER, D.BDPERIODOSER, D.BDCODAREATER, D.BDINDTER
  FROM TMP_VEF_EMP_TD530SAI_TEMP D
  JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = D.BDCODEMP AND S.BDCHAVE = D.BDEDITCHAVE)
  WHERE D.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = D.BDSESSAO
                 AND I.BDCODEMP = D.BDCODEMP
                 AND I.BDCHAVE = D.BDCHAVE
                );


  /*D510*/
  INSERT INTO VEF_EMP_TENETELE(BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODCLAENETEL, BDINDREC)
  SELECT C.BDCODEMP, C.BDEDITCHAVE BDCHAVE, C.BDORDEM, C.BDORDEMPRO,
         C.BDCODCLAENETEL, C.BDINDREC
  FROM TMP_VEF_EMP_TENETELE_TEMP C
  JOIN VEF_EMP_TMOVPROSAI S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDEDITCHAVE AND S.BDORDEM = C.BDORDEM AND S.BDORDEMPRO = C.BDORDEMPRO)
  WHERE C.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = C.BDSESSAO
                 AND I.BDCODEMP = C.BDCODEMP
                 AND I.BDCHAVE = C.BDCHAVE
                );   

  /*Várias alíquotas*/
  INSERT INTO VEF_EMP_TMOVSAIVARALIQ(BDCODEMP, BDCHAVE, BDORDEM, BDORDEMICMS, BDBASEICMS, BDREDBCICMS, BDBASEREDICMS,
                                     BDALIQICMS, BDVLRICMS, BDISENTASICMS, BDOUTRASICMS)
  SELECT V.BDCODEMP, V.BDEDITCHAVE BDCHAVE, V.BDORDEM, V.BDORDEMICMS, V.BDBASEICMS, V.BDREDBCICMS,
         V.BDBASEREDICMS, V.BDALIQICMS, V.BDVLRICMS, V.BDISENTASICMS, V.BDOUTRASICMS
  FROM TMP_VEF_EMP_TMOVSAIVARALIQ_TEMP V
  JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = V.BDCODEMP AND S.BDCHAVE = V.BDEDITCHAVE)
  WHERE V.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = V.BDSESSAO
                 AND I.BDCODEMP = V.BDCODEMP
                 AND I.BDCHAVE = V.BDCHAVE
                );

  /*GRF*/
  INSERT INTO VEF_EMP_TMOVSAIGRF(BDCODEMP, BDCHAVE, BDCODTERSAI, BDCODUF1, BDCODUF2, BDCODTERENT,
                                 BDCODTERTRANS, BDCODUF3, BDMODFRETE, BDMODTRANS, BDPLACA1,
                                 BDPLACA2, BDPLACA3)
  SELECT GRF.BDCODEMP, GRF.BDEDITCHAVE BDCHAVE, GRF.BDALTCODTER, GRF.BDCODUF1, GRF.BDCODUF2, GRF.BDALTCODTERENT,
         GRF.BDALTCODTERTRANS, GRF.BDCODUF3, GRF.BDMODFRETE, GRF.BDMODTRANS, GRF.BDPLACA1,
         GRF.BDPLACA2, GRF.BDPLACA3
  FROM TMP_VEF_EMP_TMOVSAIGRF_TEMP GRF
  JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = GRF.BDCODEMP AND S.BDCHAVE = GRF.BDEDITCHAVE)
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER_S ON(TER_S.BDSESSAO = :PRSESSAOTER AND TER_S.BDEDITCHAVE = GRF.BDALTCODTER)
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER_E ON(TER_E.BDSESSAO = :PRSESSAOTER AND TER_E.BDEDITCHAVE = GRF.BDALTCODTERENT)
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER_T ON(TER_T.BDSESSAO = :PRSESSAOTER AND TER_T.BDEDITCHAVE = GRF.BDALTCODTERTRANS)
  WHERE GRF.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = GRF.BDSESSAO
                 AND I.BDCODEMP = GRF.BDCODEMP
                 AND I.BDCHAVE = GRF.BDCHAVE
                )
  AND NOT EXISTS(
                 SELECT T.BDCODTER
                 FROM VEF_INCON_TTERCEIROS T
                 WHERE T.BDSESSAO = :PRSESSAOTER
                 AND T.BDCODTER = TER_S.BDCODTER
                )
  AND NOT EXISTS(
                 SELECT T.BDCODTER
                 FROM VEF_INCON_TTERCEIROS T
                 WHERE T.BDSESSAO = :PRSESSAOTER
                 AND T.BDCODTER = TER_E.BDCODTER
                )
  AND NOT EXISTS(
                 SELECT T.BDCODTER
                 FROM VEF_INCON_TTERCEIROS T
                 WHERE T.BDSESSAO = :PRSESSAOTER
                 AND T.BDCODTER = TER_T.BDCODTER
                );

  /*CTR*/
  INSERT INTO VEF_EMP_TMOVSAICTR(BDCODEMP, BDCHAVE, BDREMETENTE, BDCIFFOB, BDVLRPEDAGIO)
  SELECT CTR.BDCODEMP, CTR.BDEDITCHAVE BDCHAVE, CTR.BDALTCODTER BDREMETENTE, CTR.BDCIFFOB, CTR.BDVLRPEDAGIO
  FROM TMP_VEF_EMP_TMOVSAICTR_TEMP CTR
  JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = CTR.BDCODEMP AND S.BDCHAVE = CTR.BDEDITCHAVE)
  WHERE CTR.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = CTR.BDSESSAO
                 AND I.BDCODEMP = CTR.BDCODEMP
                 AND I.BDCHAVE = CTR.BDCHAVE
                );

  /*Carga transportada*/
  INSERT INTO VEF_EMP_TMOVSAICARTR(BDCODEMP, BDCHAVE, BDORDEM, BDCODTER, BDNRNOTA, BDMODELNOTA, BDSERIENOTA, BDDATAEMI, BDVALTOT, BDVALMERC,
                                   BDQTDVOL, BDPESOBRUTO, BDPESOLIQUI, BDCHAVENFE)
  SELECT CARTR.BDCODEMP, CARTR.BDEDITCHAVE BDCHAVE, CARTR.BDORDEM, CARTR.BDALTCODTER, CARTR.BDNRNOTA,
         CARTR.BDMODELNOTA, CARTR.BDSERIENOTA, CARTR.BDDATAEMI, CARTR.BDVALTOT, CARTR.BDVALMERC,
         CARTR.BDQTDVOL, CARTR.BDPESOBRUTO, CARTR.BDPESOLIQUI, CARTR.BDCHAVENFE
  FROM TMP_VEF_EMP_TMOVSAICARTR_TEMP CARTR
  JOIN VEF_EMP_TMOVSAICTR CTR ON(CTR.BDCODEMP = CARTR.BDCODEMP AND CTR.BDCHAVE = CARTR.BDEDITCHAVE)
  LEFT OUTER JOIN TMP_TTERCEIRO_TEMP TER ON(TER.BDSESSAO = :PRSESSAOTER AND TER.BDEDITCHAVE = CARTR.BDALTCODTER)
  WHERE CARTR.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = CARTR.BDSESSAO
                 AND I.BDCODEMP = CARTR.BDCODEMP
                 AND I.BDCHAVE = CARTR.BDCHAVE
                )
  AND NOT EXISTS(
                 SELECT T.BDCODTER
                 FROM VEF_INCON_TTERCEIROS T
                 WHERE T.BDSESSAO = :PRSESSAOTER
                 AND T.BDCODTER = TER.BDCODTER
                );

  /*Quadro 48 - Dime SC*/
  INSERT INTO VEF_EMP_TMOVSAIQ48(BDCODEMP, BDCHAVE, BDORDEM, BDCODCID, BDVLRSAIDA, BDVLRESTORNOS, BDVLRREMESSA, BDVLRRETORNO, BDVLRANULACOES,
                                 BDVLRCANCELAMENTOS, BDVLRDEVOLUCOES, BDVLRREGDUPLICI, BDVLROUTRENTRADAS, BDVLRTOTALLIQUIDO)
  SELECT Q.BDCODEMP, Q.BDEDITCHAVE BDCHAVE, Q.BDORDEM, Q.BDCODCID, Q.BDVLRSAIDA, Q.BDVLRESTORNOS, Q.BDVLRREMESSA, Q.BDVLRRETORNO, Q.BDVLRANULACOES,
         Q.BDVLRCANCELAMENTOS, Q.BDVLRDEVOLUCOES, Q.BDVLRREGDUPLICI, Q.BDVLROUTRENTRADAS, Q.BDVLRTOTALLIQUIDO
  FROM TMP_VEF_EMP_TMOVSAIQ48_TEMP Q
  WHERE Q.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = Q.BDSESSAO
                 AND I.BDCODEMP = Q.BDCODEMP
                 AND I.BDCHAVE = Q.BDCHAVE
                );

--ELIZEU- 17-07-2018 - Sprint E.F Azul 16/07 - 1.18.8.0 -Erro NFe saída Push - Versão Redução Z #urgente! #Trunk!
  /*C197 - movprosai - vinculo do produto com C197 */
  INSERT INTO VEF_EMP_TMOVSAIVINCC197(BDCODEMP, BDCHAVE, BDORDEM, BDORDEMOBS, BDORDEMOUTOBR, BDORDEMPRO)
  SELECT v.BDCODEMP, v.BDEDITCHAVE BDCHAVE, v.BDORDEM, v.BDORDEMOBS, v.BDORDEMOUTOBR, v.BDORDEMPRO
  FROM TMP_VEF_EMP_TMSVINCC197_TEMP v
  WHERE v.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = v.BDSESSAO
                 AND I.BDCODEMP = v.BDCODEMP
                 AND I.BDCHAVE = v.BDCHAVE
                );

--ELIZEU- 04-08-18 - Importação CT-e - Atividade Bloco P #87887 #Urgente! #Trunk!
  INSERT INTO vef_emp_tmovsaiitensctr(BDCODEMP, BDCHAVE, BDORDEM, BDORDENATVPREV)
  SELECT v.BDCODEMP, v.BDEDITCHAVE BDCHAVE, v.BDORDEM,v.bdordenatvprev
  FROM TMP_VEF_EMP_TMOVSAIITCTR_TEMP v
  WHERE v.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = v.BDSESSAO
                 AND I.BDCODEMP = v.BDCODEMP
                 AND I.BDCHAVE = v.BDCHAVE
                );

  /*Sol: 89310 Patrick T. Sá 30/08/2018. DAPI - Preenchimento Automático na importação*/
  INSERT INTO VEF_EMP_TMOVSAISTDAPI(BDCODEMP, BDCHAVE, BDORDEM, BDTIPOISEOUT, BDORDEMST, BDCODTIPODAPI, BDVALOR)
  SELECT DAPI.BDCODEMP, DAPI.BDEDITCHAVE, DAPI.BDORDEM, DAPI.BDTIPOISEOUT, DAPI.BDORDEMST, DAPI.BDCODTIPODAPI, DAPI.BDVALOR
  FROM TMP_VEF_EMP_TMOVSAISTDAPI_TEMP DAPI
  JOIN VEF_EMP_TMOVSAIITENS S ON(S.BDCODEMP = DAPI.BDCODEMP AND S.BDCHAVE = DAPI.BDEDITCHAVE AND S.BDORDEM = DAPI.BDORDEM)
  WHERE DAPI.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                 FROM VEF_INCON_TMOVSAI I
                 WHERE I.BDSESSAO = DAPI.BDSESSAO
                 AND I.BDCODEMP = DAPI.BDCODEMP
                 AND I.BDCHAVE = DAPI.BDCHAVE
                );


    --  elizeu - 22-11-18 - Nova forma de configurar a tributação - Simples Nacional - Cálculo simples nacional #81223 #68755 #89517 #89811 #Cartão9!
    insert into VEF_EMP_TMOVSAISN (BDCODEMP, BDCHAVE, BDORDEM, BDCHAVESN, BDCODBASESN, BDCODPLANOCONFSN, BDCODTIPOIMPPIS,
                                   BDCODTIPOIMPCOFINS, BDCODTIPOIMPCSLL, BDCODTIPOIMPICMS, BDCODTIPOIMPINSSCPP,
                                   BDCODTIPOIMPIRPJ, BDCODTIPOIMPIPI, BDCODTIPOIMPISS, BDVLRBASE, BDCODNAT,
                                   BDCODATIVSIMPNAC, BDCODCONFSN)
    select SN.BDCODEMP, SN.BDEDITCHAVE, SN.BDORDEM, SN.BDCHAVESN, SN.BDCODBASESN, SN.BDCODPLANOCONFSN, SN.BDCODTIPOIMPPIS,
           SN.BDCODTIPOIMPCOFINS, SN.BDCODTIPOIMPCSLL, SN.BDCODTIPOIMPICMS, SN.BDCODTIPOIMPINSSCPP, SN.BDCODTIPOIMPIRPJ,
           SN.BDCODTIPOIMPIPI, SN.BDCODTIPOIMPISS, SN.BDVLRBASE, SN.BDCODNAT, SN.BDCODATIVSIMPNAC, SN.BDCODCONFSN
    from TMP_VEF_EMP_TMOVSAISN_TEMP SN
    left outer join VEF_EMP_TMOVSAIITENS S on (S.BDCODEMP = SN.BDCODEMP and S.BDCHAVE = SN.BDEDITCHAVE and S.BDORDEM = SN.BDORDEM)
    where SN.BDSESSAO = :PRSESSAO
      AND((S.BDCHAVE is not null) or (S.BDCHAVE > 0))
      and not exists(select I.BDCODINCONSISTENCIAMOVSAI, I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDSESSAO,
                            I.BDCODINCONSISTENCIA, I.BDORDEMPRO
                     from VEF_INCON_TMOVSAI I
                     where I.BDSESSAO = SN.BDSESSAO and
                           I.BDCODEMP = SN.BDCODEMP and
                           I.BDCHAVE = SN.BDCHAVE);

    INSERT INTO VEF_EMP_TMOVPROSAIIMPORI (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMHIST, BDBCICMS, BDALIQICMS, BDVLRICMS, BDBCIPI, BDALIQIPI, BDVLRIPI,
                                          BDBCST, BDALIQST, BDVLRST, BDBCPIS, BDALIQPIS, BDVLRPIS, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDBCISSQN,
                                          BDALIQISSQN, BDVLRISSQN, BDBCICMSEFET, BDALIQICMSEFET, BDVLRICMSEFET, BDBCICMSSTRET, BDALIQIMCSSTRET,
                                          BDVLRICMSSTRET, BDBCFCPSTRET, BDALIQFCPSTRET, BDVLRFCPSTRET, BDCODPROD,BDALIQFCPRETIDO,BDBCFCPRETIDO,BDFCPRETIDO,BDCODNAT,BDCODCSTICMS,
                                          BDCODSAIDA, BDBCFCP, BDALQFCP, BDVLRFCP, BDNCMPROD, BDCODUNIMED, BDCODCSTPIS, BDCODCSTCOF, BDCODCSTIPI, BDORDEMPROORIG)
    SELECT IMP.BDCODEMP, IMP.BDEDITCHAVE, IMP.BDORDEM, IMP.BDORDEMHIST, IMP.BDBCICMS, IMP.BDALIQICMS, IMP.BDVLRICMS, IMP.BDBCIPI, IMP.BDALIQIPI, IMP.BDVLRIPI,
           IMP.BDBCST, IMP.BDALIQST, IMP.BDVLRST, IMP.BDBCPIS, IMP.BDALIQPIS, IMP.BDVLRPIS, IMP.BDBCCOFINS, IMP.BDALIQCOFINS, IMP.BDVLRCOFINS, IMP.BDBCISSQN,
           IMP.BDALIQISSQN, IMP.BDVLRISSQN, IMP.BDBCICMSEFET, IMP.BDALIQICMSEFET, IMP.BDVLRICMSEFET, IMP.BDBCICMSSTRET, IMP.BDALIQIMCSSTRET,
           IMP.BDVLRICMSSTRET, IMP.BDBCFCPSTRET, IMP.BDALIQFCPSTRET, IMP.BDVLRFCPSTRET, IMP.BDALTCODPROD,BDALIQFCPRETIDO,IMP.BDBCFCPRETIDO,IMP.BDFCPRETIDO,IMP.BDCODNAT,IMP.BDCODCSTICMS,
           IMP.BDCODSAIDA, IMP.BDBCFCP, IMP.BDALQFCP, IMP.BDVLRFCP, IMP.BDNCMPROD, IMP.BDCODUNIMED, IMP.BDCODCSTPIS, IMP.BDCODCSTCOF, IMP.BDCODCSTIPI, IMP.BDORDEMPROORIG
    FROM TMP_VEF_EMP_TMOVSAIIMPORI_TEMP IMP
    --#124206 #124710 #124858 - Pedro Roweder - 10/10/2019 - Feita verificação se os lançamentos dependentes da FK foram feitos, só lança se sim.
    LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = IMP.BDCODEMP and SAI.BDCHAVE = IMP.BDEDITCHAVE)
    WHERE IMP.BDSESSAO = :PRSESSAO
    AND((SAI.BDCHAVE is not null) or (SAI.BDCHAVE > 0))
    AND NOT EXISTS(
                   SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                   FROM VEF_INCON_TMOVSAI I
                   WHERE I.BDSESSAO = IMP.BDSESSAO
                   AND I.BDCODEMP = IMP.BDCODEMP
                   AND I.BDCHAVE = IMP.BDCHAVE
                  );        



  --Elizeu - 08-08-19 - funRural nas saídas, o plano de trocas vai criar
    INSERT INTO VEF_EMP_TMOVSAIFUNRURAL (BDCODEMP,BDCHAVE,BDORDEMINDCOM,BDALIQFUNRURAL,BDVLRFUNRURAL,BDALIQGILRAT,BDALIQSENAR,BDVLRGILRAT,BDVLRSENAR)
    SELECT F.BDCODEMP,F.BDEDITCHAVE,F.BDORDEMINDCOM,F.BDALIQFUNRURAL,F.BDVLRFUNRURAL,F.BDALIQGILRAT,F.BDALIQSENAR,F.BDVLRGILRAT,F.BDVLRSENAR
    FROM TMP_VEF_TMOVSAIFUNRURAL_TEMP F
    LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = F.BDCODEMP and SAI.BDCHAVE = F.BDEDITCHAVE)
    WHERE F.BDSESSAO = :PRSESSAO
    AND((SAI.BDCHAVE is not null) or (SAI.BDCHAVE > 0))
    AND NOT EXISTS(
                   SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO
                   FROM VEF_INCON_TMOVSAI I
                   WHERE I.BDSESSAO = F.BDSESSAO
                   AND I.BDCODEMP = F.BDCODEMP
                   AND I.BDCHAVE = F.BDCHAVE
                  );

    -- Camilla M. -  16/12/19 - Importação do C590 nas saídas
  INSERT INTO VEF_EMP_TC590TOTSAI(BDCODEMP, BDCHAVE, BDORDEM, BDORDEMTOT, BDCODCSTICMS, BDALIQICMS, BDVLROPERACAO, BDBCICMS,
                                  BDVLRICMS, BDBCICMSST, BDVLRICMSST, BDVLRNTRIBICMS)
  SELECT C.BDCODEMP, C.BDEDITCHAVE, C.BDORDEM, C.BDORDEMTOT, C.BDCODCSTICMS, C.BDALIQICMS, C.BDVLROPERACAO, C.BDBCICMS,
         C.BDVLRICMS, C.BDBCICMSST, C.BDVLRICMSST, C.BDVLRNTRIBICMS
  FROM TMP_VEF_EMP_TC590TOTSAI_TEMP C
  JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = C.BDCODEMP AND S.BDCHAVE = C.BDEDITCHAVE)
  WHERE C.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                   SELECT I.BDCODINCONSISTENCIA
                   FROM VEF_INCON_TMOVSAI I
                   WHERE I.BDSESSAO = C.BDSESSAO
                   AND I.BDCODEMP = C.BDCODEMP
                   AND I.BDCHAVE = C.BDCHAVE
                  );

  -- #127752 - Diferencial de aliquota
  INSERT INTO VEF_EMP_TMOVSAIDIFALIQ(bdCODEMP, bdCHAVE, bdORDEM, bdORDEMDIFALIQ,
                                     bdBCDIFENTALIQ, bdALIQORIDIFENTALIQ, bdALIQDESDIFENTALIQ, bdVLRDIFENTALIQ)
  SELECT t.bdCODEMP, t.bdEDITCHAVE, t.bdORDEM, t.bdORDEMDIFALIQ,
         t.bdBCDIFENTALIQ, t.bdALIQORIDIFENTALIQ, t.bdALIQDESDIFENTALIQ, t.bdVLRDIFENTALIQ
  FROM TMP_VEF_EMP_TMOVSAIDIFALIQ_TEMP t
  JOIN VEF_EMP_TMOVSAI s ON (s.bdCODEMP = t.bdCODEMP AND s.bdCHAVE = t.bdEDITCHAVE)
  WHERE t.bdSESSAO = :prSESSAO
    AND NOT EXISTS(
                   SELECT i.bdCODINCONSISTENCIA
                   FROM VEF_INCON_TMOVSAI i
                   WHERE i.bdSESSAO = t.bdSESSAO
                     AND i.bdCODEMP = t.bdCODEMP
                     AND i.bdCHAVE  = t.bdCHAVE
                   );

  -- #127752 - Diferencial de aliquota PR
  INSERT INTO VEF_EMP_TMOVSAIDIFPR(bdCODEMP, bdCHAVE, bdORDEM, bdORDEMDIF, bdBASECALCULO, bdICMSORIGEM,
                                   bdPRECINTRA, bdBASEESTADO, bdALIQINTERNA, bdICMSINTERNO, bdIMPRECOLHER)
  SELECT t.bdCODEMP, t.bdEDITCHAVE, t.bdORDEM, t.bdORDEMDIF, t.bdBASECALCULO, t.bdICMSORIGEM,
         t.bdPRECINTRA, t.bdBASEESTADO, t.bdALIQINTERNA, t.bdICMSINTERNO, t.bdIMPRECOLHER
  FROM TMP_VEF_EMP_TMOVSAIDIFPR_TEMP t
  JOIN VEF_EMP_TMOVSAI s ON (s.bdCODEMP = t.bdCODEMP AND s.bdCHAVE = t.bdEDITCHAVE)
  WHERE t.bdSESSAO = :prSESSAO
    AND NOT EXISTS(
                   SELECT i.bdCODINCONSISTENCIA
                   FROM VEF_INCON_TMOVSAI i
                   WHERE i.bdSESSAO = t.bdSESSAO
                     AND i.bdCODEMP = t.bdCODEMP
                     AND i.bdCHAVE  = t.bdCHAVE
                   );

  -- 144153 - Imposto substituido
  INSERT INTO VEF_EMP_TMOVSAIIMPRETSP(BDCODEMP, BDCHAVE, BDORDEM, BDIMPSUBSTITUTO, BDIMPSUBSTITUIDO)
  SELECT T.BDCODEMP, T.bdEDITCHAVE, T.BDORDEM, T.BDIMPSUBSTITUTO, T.BDIMPSUBSTITUIDO
  FROM TMP_VEF_EMP_TSAIIMPRETSP_TEMP t
  JOIN VEF_EMP_TMOVSAIITENS s ON (s.bdCODEMP = t.bdCODEMP AND s.bdCHAVE = t.bdEDITCHAVE AND s.BDORDEM = t.BDORDEM)
  WHERE t.bdSESSAO = :prSESSAO
    AND NOT EXISTS(
                   SELECT i.bdCODINCONSISTENCIA
                   FROM VEF_INCON_TMOVSAI i
                   WHERE i.bdSESSAO = t.bdSESSAO
                     AND i.bdCODEMP = t.bdCODEMP
                     AND i.bdCHAVE  = t.bdCHAVE
                   );

  -- #144559 #144616 #144614 #144972 #145136 #145260 #145271 #145272 - Parcelamento de saídas
  INSERT INTO VEF_EMP_TMOVSAIPAR (BDCODEMP, BDCHAVE, BDORDEMPAR, BDCODIGOPLA, BDPARCELAPAR, BDDUPLICATAPAR, BDVALORPAR,
                                BDDATAVENCTOPAR, BDVALORRETPIS, BDVALORRETCOFINS, BDVALORRETCSLL, BDVALORRETIRRF,
                                BDVALORRETISSQN, BDVALORRETINSS, BDVALORBRUTO)
  SELECT T.BDCODEMP, T.BDEDITCHAVE, T.BDORDEMPAR, T.BDCODIGOPLA, T.BDORDEMPAR, T.BDDUPLICATAPAR, T.BDVALORPAR,
         T.BDDATAVENCTOPAR, T.BDVALORRETPIS, T.BDVALORRETCOFINS, T.BDVALORRETCSLL, T.BDVALORRETIRRF, T.BDVALORRETISSQN,
         T.BDVALORRETINSS, T.BDVALORBRUTO
  FROM TMP_VEF_EMP_TMOVSAIPAR_TEMP t
  JOIN VEF_EMP_TMOVSAI s ON (s.bdCODEMP = t.bdCODEMP AND s.bdCHAVE = t.bdEDITCHAVE)
  WHERE t.bdSESSAO = :prSESSAO
    AND NOT EXISTS(
                   SELECT i.bdCODINCONSISTENCIA
                   FROM VEF_INCON_TMOVSAI i
                   WHERE i.bdSESSAO = t.bdSESSAO
                     AND i.bdCODEMP = t.bdCODEMP
                     AND i.bdCHAVE  = t.bdCHAVE
                   );

  -- #144559 #144616 #144614 #144972 #145136 #145260 #145271 #145272 - Retenção de saídas
  INSERT INTO VEF_EMP_TMOVSAIRET(bdcodemp, bdchave, bdvlrpis, bdvlrcofins, bdvlrcsocial, bdvlrir, bdissret, bdcodind_nat_ret,
                                 bdcodreccsocial, bdcodrecpis, bdcodreccofins, bdcodrecir, bdcodreciss, bdtiponatrec)
  SELECT T.bdcodemp, T.bdeditchave bdchave, T.bdvlrpis, T.bdvlrcofins, T.bdvlrcsocial, T.bdvlrir, T.bdissret,
         T.bdcodind_nat_ret, T.bdcodreccsocial, T.bdcodrecpis, T.bdcodreccofins, T.bdcodrecir, T.bdcodreciss, T.bdtiponatrec
  FROM TMP_VEF_EMP_TMOVSAIRET_TEMP t
  JOIN VEF_EMP_TMOVSAI s ON (s.bdCODEMP = t.bdCODEMP AND s.bdCHAVE = t.bdEDITCHAVE)
  WHERE t.bdSESSAO = :prSESSAO
    AND NOT EXISTS(
                   SELECT i.bdCODINCONSISTENCIA
                   FROM VEF_INCON_TMOVSAI i
                   WHERE i.bdSESSAO = t.bdSESSAO
                     AND i.bdCODEMP = t.bdCODEMP
                     AND i.bdCHAVE  = t.bdCHAVE
                   );

  -- #144559 #144616 #144614 #144972 #145136 #145260 #145271 #145272 - Retenção de INSS saídas
  INSERT INTO VEF_EMP_TMOVSAIDED(bdcodemp, bdchave, bdretinss, bdcodrecinss, BDORDEMTAB6_TPSER, BDVLRBASEINSS, BDCNO, BDINDICADOROBRA, BDVLRREDINSS)
  SELECT t.bdcodemp, t.bdeditchave bdchave, t.bdretinss, t.bdcodrecinss, t.BDORDEMTAB6_TPSER, t.bdvlrbaseinss, T.BDCNO, T.BDINDICADOROBRA, T.BDVLRREDINSS
  FROM TMP_VEF_EMP_TMOVSAIDED_TEMP t
  JOIN VEF_EMP_TMOVSAI s ON (s.bdCODEMP = t.bdCODEMP AND s.bdCHAVE = t.bdEDITCHAVE)
  WHERE t.bdSESSAO = :prSESSAO
    AND NOT EXISTS(
                   SELECT i.bdCODINCONSISTENCIA
                   FROM VEF_INCON_TMOVSAI i
                   WHERE i.bdSESSAO = t.bdSESSAO
                     AND i.bdCODEMP = t.bdCODEMP
                     AND i.bdCHAVE  = t.bdCHAVE
                   );
  
/*Continuação da SP*/

  execute procedure SP_COMMIT_IMP_SAIDA_P2(:PRSESSAO,:PRSESSAOTER,:PRSESSAOPROD);        
END^

CREATE OR ALTER TRIGGER tmp_tlanc_contab_temp_bu0 FOR tmp_tlanc_contabilizacao_temp
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  IF ((OLD.BDCHAVE_VSUC IS NULL) OR (OLD.BDCHAVE_VSUC = 0)) THEN
    NEW.BDCHAVE_VSUC = ((NEW.BDCHAVE_VSUC - NEW.BDSEQ)+1);

--  IF ((OLD.BDTRANSACAO IS NULL) OR (OLD.BDTRANSACAO = 0)) THEN
--    NEW.BDTRANSACAO = ((NEW.BDTRANSACAO - NEW.BDSEQ)+1);
END^

CREATE OR ALTER PROCEDURE SP_IMPORTACAO_SEM_PART (
    PRSESSAO INTEGER,
    PRCODPARTDEFAULT INTEGER)
AS
BEGIN
  /*sp executada quando o usuário quer importar só os lançamentos, o participante já deve ter sido importado,
    senão irá ficar com inconsistencia no lançamento*/

  PRCODPARTDEFAULT = COALESCE(:PRCODPARTDEFAULT, 0);

  /*Atualiza o código do participante*/
  UPDATE TMP_VEF_EMP_TMOVSAI_TEMP S
  SET S.BDCODTER = COALESCE((SELECT FIRST 1 T.BDCODTER FROM VW_TTERCEIRO T WHERE T.BDCGCTER = S.BDCNPJ), :PRCODPARTDEFAULT)
  WHERE S.BDSESSAO = :PRSESSAO;

  /*Atualiza o nome do participante*/
  UPDATE TMP_VEF_EMP_TMOVSAI_TEMP S
  SET S.BDNOMETER = (
                     SELECT FIRST 1 T.BDNOMETER FROM VW_TTERCEIRO T
                     WHERE T.BDCODTER = S.BDCODTER
                    ),
      S.BDALTCODTER = S.BDCODTER,
      S.BDSIGLAUFTER = (
                        SELECT FIRST 1 UF.BDSIGLAUF FROM VW_TTERCEIRO_SIMPLES T
                        LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = T.BDCODCID)
                        LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
                        WHERE T.BDCODTER = S.BDCODTER
                       )
  WHERE S.BDSESSAO = :PRSESSAO;

  UPDATE TMP_VEF_EMP_TMOVSAI_TEMP S
  SET S.BDCODCID = (
                    SELECT FIRST 1 T.BDCODCID FROM VW_TTERCEIRO_SIMPLES T
                    WHERE T.BDCODTER = S.BDCODTER
                   )
  WHERE S.BDSESSAO = :PRSESSAO
  AND S.BDCODCID IS NULL;
END^

create or alter procedure SP_CANCELAR_LAN_BASE_ENT (
    PRSESSAO integer,
    PRCODEMP integer,
    PREXCLUIRLAN DM_BOOLEAN)
as
declare variable FCODSITNF_CANC integer;
declare variable WZERARNFCANC DM_BOOLEAN;
BEGIN
  /***********************************Tratamento Nfe's canceladas***********************************/
  /*Patrick T. Sá - Todos comandos da solicitação 18626 foram refeitos porque estavam levando
                    mais de 1 hora para executar no banco da GFisco, ocasionando travamento
                    nos outros terminais que estão importando*/
  FCODSITNF_CANC = 2; /*2 - Documento cancelado*/

  --SELECT FIRST 1 BDCODEMP FROM TMP_VEF_EMP_TMOVSAI_TEMP WHERE BDSESSAO = :PRSESSAO AND BDCODEMP IS NOT NULL INTO :FCodEmp;
  --SELECT FIRST 1 BDCODEMP FROM TMP_VEF_EMP_TMOVSAI_TEMP WHERE BDSESSAO = :PRSESSAO AND BDCODEMP IS NOT NULL INTO :FCodEmp;

  /*Se não pegou empresa significa que não tem lançamento, então pode sair da SP*/
  --IF (:FCodEmp IS NULL) THEN
  --  EXIT;

  --UPDATE TMP_VEF_EMP_TMOVSAI_TEMP SET BDCHAVENFECANC = BDCHAVENFE WHERE BDSESSAO = :PRSESSAO AND BDCODSITNF = :FCODSITNF_CANC AND BDCHAVENFECANC IS NULL;

  SELECT UPPER(P.BDVALOR)
  FROM TPARGER P
  WHERE UPPER(P.BDCAMPO) = 'BDZERANFCANCELADA'
  INTO :wZerarNFCanc;

  DELETE FROM TMP_TLANC_REPETIDOS WHERE BDCHAVE IS NOT NULL;

  /*Insere nessa temporária para no update ter os campos chave, então o update usa o indice primário*/
  INSERT INTO TMP_TLANC_REPETIDOS(BDCODEMP, BDCHAVE, BDDATACANC)
  SELECT SAI.BDCODEMP, SAI.BDCHAVE, COALESCE(S.BDDATACANC, SAI.BDDATAEMISSAO) BDDATACANC
  FROM (
        SELECT :PRCODEMP BDCODEMP, S.BDCHAVENFE, S.BDDATACANC
        FROM TMP_VEF_EMP_TCANC_INUT_TEMP S
        WHERE S.BDSESSAO = :PRSESSAO
        AND ((S.BDCHAVENFE IS NOT NULL) AND (S.BDCHAVENFE <> ''))
       ) S
  JOIN VEF_EMP_TMOVENT SAI ON(SAI.BDCODEMP = S.BDCODEMP AND SAI.BDCHAVENFE = S.BDCHAVENFE);

  UPDATE VEF_EMP_TMOVENT S
  SET S.BDCODSITNF = :FCODSITNF_CANC,
      S.BDDATACANC = (
                      SELECT REP.BDDATACANC
                      FROM TMP_TLANC_REPETIDOS REP
                      WHERE REP.BDCODEMP = S.BDCODEMP
                      AND REP.BDCHAVE = S.BDCHAVE
                     )
  WHERE S.BDCODEMP = :PRCODEMP
  AND EXISTS (
              SELECT REP.BDCHAVE
              FROM TMP_TLANC_REPETIDOS REP
              WHERE REP.BDCODEMP = S.BDCODEMP
              AND REP.BDCHAVE = S.BDCHAVE
             );

  DELETE FROM TOL_VEF_EMP_TMOVENT TOL
  WHERE TOL.BDCODEMP = :PRCODEMP
  AND EXISTS(
             SELECT REP.BDCHAVE
             FROM TMP_TLANC_REPETIDOS REP
             WHERE REP.BDCODEMP = TOL.BDCODEMP
             AND REP.BDCHAVE = TOL.BDCHAVEENT
            );
  /*************************************************************************************************/

  /* Alt.: 18626 - Caso seja um evento de cancelamento sem nota na base ou importando a nota junto */
--  INSERT INTO VEF_INCON_TMOVSAI(BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON)
--  SELECT tmp.BDCODEMP, tmp.BDCHAVE, NULL, tmp.BDSESSAO, 126 BDCODINCONSISTENCIA, 1 BDTIPOINCON
--  FROM TMP_VEF_EMP_TMOVSAI_TEMP tmp
--  WHERE tmp.BDSESSAO = :PRSESSAO
--  AND TMP.BDCODEMP = :FCODEMP
--  AND tmp.BDCODSITNF = :FCODSITNF_CANC
----  AND tmp.BDDATACANC IS NULL -- Alt.: 18626 - Evento de cancelamento...
--  AND tmp.BDNUMDOCINI IS NULL
--  AND tmp.BDNUMDOCFIM IS NULL
--  AND NOT EXISTS(
--                 SELECT s.BDCODEMP
--                 FROM VEF_EMP_TMOVSAI s
--                 WHERE s.BDCODEMP = tmp.BDCODEMP
--                 AND s.BDCHAVENFE = tmp.BDCHAVENFECANC
--                 AND s.BDCODSITNF = :FCODSITNF_CANC
--                 AND ((S.BDCHAVENFE IS NOT NULL) AND (S.BDCHAVENFE <> ''))
--                );

  /* Alt.: 18626 - Remove as notas de evento de cancelamento, pois já aplicou o cancelamento acima... */
--  DELETE FROM TMP_VEF_EMP_TMOVSAI_TEMP tmp
--  WHERE tmp.BDSESSAO = :PRSESSAO
--  AND TMP.BDCODEMP = :FCODEMP
--  AND tmp.BDCODSITNF = :FCODSITNF_CANC
----  AND tmp.BDDATACANC IS NULL -- Evento de cancelamento não vai vir a data de cancelamento...
--  AND Coalesce(tmp.BDCHAVENFE,'') = Coalesce(tmp.BDCHAVENFECANC,'')
--  AND EXISTS(
--             SELECT S.BDCHAVE
--             FROM VEF_EMP_TMOVSAI s
--             WHERE s.BDCODEMP = tmp.BDCODEMP
--             AND s.BDCHAVENFE = tmp.BDCHAVENFECANC
--             AND ((S.BDCHAVENFE IS NOT NULL) AND (S.BDCHAVENFE <> ''))
--            );

  /************************************** Zerar valores de NFe cancelada **************************************/
  IF (:wZerarNFCanc = 'TRUE') THEN
    BEGIN
      /*Zera valores da capa*/
      UPDATE VEF_EMP_TMOVENT MOV
      SET MOV.BDVALORNOTA = 0,
          MOV.BDDESCONTONOTA = 0
      WHERE MOV.BDCODEMP = :PRCODEMP
      AND EXISTS (
                  SELECT REP.BDCHAVE
                  FROM TMP_TLANC_REPETIDOS REP
                  WHERE REP.BDCODEMP = MOV.BDCODEMP
                  AND REP.BDCHAVE = MOV.BDCHAVE
                 );

      /*Zera valores dos itens*/
      UPDATE VEF_EMP_TMOVENTITENS I
      SET -- Alt.: #137131 #132536 - Quando for zerar uma nova váriavel, procurar por essa solucitação para zerar em todo os pontos...
          -- Item / CFOP
          I.BDVLRCONTAB   = 0, -- Valor contábil
          I.BDDESCONTO    = 0,  -- Desconto
          I.BDREDBCICMS   = 0, -- Redução base cálculo
          -- ICMS
          I.BDBASEICMS    = 0, -- Base
          I.BDALIQICMS    = 0, -- Alíquota
          I.BDVLRICMS     = 0, -- Valor
          I.BDISENTASICMS = 0, -- Isentas
          I.BDOUTRASICMS  = 0, -- Outras
          I.BDICMSRETENT  = 0, -- ICMS frete
          I.BDOUTROSIMP   = 0, -- Outros impostos
          -- IPI
          I.BDBASEIPI     = 0, --  Base
          I.BDVLRIPI      = 0, --  Valor
          I.BDISENTASIPI  = 0, --  Isentas
          I.BDOUTRASIPI   = 0, --  Outras
          -- Substituição tributária - ICMS
          I.BDBASEST      = 0, --  Base
          I.BDALIQST      = 0, --  Alíquota
          I.BDVLRST       = 0, --  Valor
          --I.BDVALNTRIBST = 0, --  Não retido
          --I.BDICMSRETENT = 0, --  Retido
          I.BDFCPRETIDO   = 0, --  FCP ST
          -- Pis e Cofins
          I.BDVLRPIS      = 0,
          I.BDVLRCOFINS   = 0,
          -- FCP Operacao Propria
          I.BDVLRFCP      = 0
      WHERE I.BDCODEMP = :PRCODEMP
      AND EXISTS (
                  SELECT REP.BDCHAVE
                  FROM TMP_TLANC_REPETIDOS REP
                  WHERE REP.BDCODEMP = I.BDCODEMP
                  AND REP.BDCHAVE = I.BDCHAVE
                 );

      /*Zera valores dos produtos*/
      UPDATE VEF_EMP_TMOVPROENT P
      SET -- Alt.: #137131 #132536 - Quando for zerar uma nova váriavel, procurar por essa solucitação para zerar em todo os pontos...
          -- Produto
          P.BDQTDITEM          = 0, -- Quantidade
          P.BDVLRABATNT        = 0, -- Valor do abatimento
          P.BDVLRITEM          = 0, -- Valor total do produto
          P.BDREDBCICMS        = 0, -- Redução base de cálculo
          P.BDVLRSEGURO        = 0, -- Seguro
          P.BDVLRDESC          = 0, -- Valor do desconto
          P.BDVLRFRETE         = 0, -- Frete
          P.BDVLRDESPACESSORIA = 0, -- Despesas acessórias
          -- Impostos
          -- ICMS
          P.BDBCICMS           = 0, -- Base de cálculo
          P.BDALIQICMS         = 0, -- Alíquota
          P.BDVLRICMS          = 0, -- Valor
          -- IPI
          P.BDBCIPI            = 0, -- Base de cálculo
          P.BDALIQIPI          = 0, -- Alíquota
          P.BDVLRIPI           = 0, -- Valor
          -- PIS
          P.BDBCPIS            = 0, -- Base de cálculo
          P.BDALIQPIS          = 0, -- Alíquota
          P.BDVLRPIS           = 0, -- Valor
          -- Cofins
          P.BDBCCOFINS         = 0, -- Base de cálculo
          P.BDALIQCOFINS       = 0, -- Alíquota
          P.BDVLRCOFINS        = 0, -- Valor
          -- ISSQN
          P.BDBCISSQN          = 0, -- Base de cálculo
          P.BDALIQISSQN        = 0, -- Alíquota
          P.BDVLRISSQN         = 0, -- Valor
          -- ICMS ST
          P.BDBCST             = 0, -- Base de cálculo
          P.BDALIQST           = 0, -- Alíquota
          P.BDVLRST            = 0, -- Valor
          -- FCP Retido por ST
          P.BDBCFCPRETIDO      = 0, -- Base de cálculo
          P.BDALIQFCPRETIDO    = 0, -- Alíquota
          P.BDFCPRETIDO        = 0, -- Valor
          -- ICMS ST Retido
          P.BDBCICMSSTRET      = 0, -- Base de cálculo
          P.BDALIQIMCSSTRET    = 0, -- Alíquota
          P.BDVLRICMSSTRET     = 0, -- Valor
          -- FCP Retido ant.
          P.BDBCFCPSTRET       = 0, -- Base de cálculo
          P.BDALIQFCPSTRET     = 0, -- Alíquota
          P.BDVLRFCPSTRET      = 0, -- Valor
          -- ICMS Efetiva
          P.BDBCICMSEFET       = 0, -- Base de cálculo
          P.BDALIQICMSEFET     = 0, -- Alíquota
          P.BDVLRICMSEFET      = 0, -- Valor
    -- FCP Operacao Propria
    P.BDVLRFCP           = 0, -- Valor
    P.BDALQFCP           = 0, -- Alíquota
    P.BDBCFCP            = 0  -- Base de cálculo
      WHERE P.BDCODEMP = :PRCODEMP
      AND EXISTS (
                  SELECT REP.BDCHAVE
                  FROM TMP_TLANC_REPETIDOS REP
                  WHERE REP.BDCODEMP = P.BDCODEMP
                  AND REP.BDCHAVE = P.BDCHAVE
                 );
    END

--  IF (:PREXCLUIRLAN = 'TRUE') THEN
--    DELETE FROM TMP_VEF_EMP_TMOVSAI_TEMP WHERE BDSESSAO = :PRSESSAO;
END^

CREATE OR ALTER PROCEDURE SP_VINCULAR_PRODUTO (
    PRSESSAO INTEGER,
    PRID_TERMINAL INTEGER)
AS
DECLARE VARIABLE WFIELDNAME VARCHAR(9);
DECLARE VARIABLE WTABLE VARCHAR(50);
DECLARE VARIABLE WSESSAOATU INTEGER;
DECLARE VARIABLE WSQL VARCHAR(600);
BEGIN
  /*Tabelas de saída com produto devem ter o campo BDCODSAIDA para que a sp jogue o BDALTCODPROD(Chave do produto gerada no servidor) no lançamento*/
  FOR SELECT TRIM(UPPER(T.RDB$RELATION_NAME)) BDTABLE
      FROM RDB$RELATION_FIELDS T
      WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
      AND RDB$FIELD_NAME = 'BDALTCODPROD'
      AND EXISTS(
                 SELECT F.RDB$RELATION_NAME BDTABLE
                 FROM RDB$RELATION_FIELDS F
                 WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
                 AND (RDB$FIELD_NAME = 'BDCODSAIDA')
                 AND T.RDB$RELATION_NAME = F.RDB$RELATION_NAME
                 GROUP BY F.RDB$RELATION_NAME
                )
      INTO :wTable
  DO
    BEGIN
      wSessaoAtu = NULL;

      SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = :wTable INTO :wSessaoAtu;
      IF (:wSessaoAtu IS NOT NULL) THEN
        BEGIN
          wFieldName = NULL;

          /*Desvincula todos os produtos*/
          wSql = 'UPDATE '||:wTable||' T SET T.BDALTCODPROD = NULL, T.BDDESCPROD = NULL WHERE T.BDSESSAO = '||:wSessaoAtu;
          EXECUTE STATEMENT :wSql;
    
          /*1 - Busca os produtos na tabela TEMP, contém os registros que estão sendo importados*/
          wSql = 'UPDATE '||:wTable||' T SET T.BDALTCODPROD = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = '||:PRSESSAO||' AND P.BDCODSAIDA = T.BDCODSAIDA), ';
          wSql = :wSql || 'T.BDDESCPROD = ( ';
          wSql = :wSql || '                SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '''', P.BDDESCRICAOUNICA, P.BDDESCPROD) ';
          wSql = :wSql || '                FROM TMP_TCADPRO_TEMP P ';
          wSql = :wSql || '                WHERE P.BDSESSAO = '||:PRSESSAO;
          wSql = :wSql || '                AND P.BDCODSAIDA = T.BDCODSAIDA ';
          wSql = :wSql || '               ) ';
          wSql = :wSql || 'WHERE T.BDSESSAO = '||:wSessaoAtu;
          wSql = :wSql || ' AND ((T.BDCODSAIDA IS NOT NULL) AND (T.BDCODSAIDA <> ''''))';
          EXECUTE STATEMENT :wSql;
    
          /*2 - Busca os produtos na tabela TMP, contém todos os registros de produto do banco*/
          wSql =  'UPDATE '||:wTable||' T SET T.BDALTCODPROD = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO P WHERE P.BDCODEMP = T.BDCODEMP AND P.BDCODSAIDA = T.BDCODSAIDA), ';
          wSql = :wSql || 'T.BDDESCPROD = ( ';
          wSql = :wSql || '                SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '''', P.BDDESCRICAOUNICA, P.BDDESCPROD) ';
          wSql = :wSql || '                FROM TMP_TCADPRO P ';
          wSql = :wSql || '                WHERE P.BDCODEMP = T.BDCODEMP ';
          wSql = :wSql || '                AND P.BDCODSAIDA = T.BDCODSAIDA ';
          wSql = :wSql || '               ) ';
          wSql = :wSql || 'WHERE T.BDSESSAO = '||:wSessaoAtu;
          wSql = :wSql || 'AND T.BDALTCODPROD IS NULL ';
          wSql = :wSql || 'AND ((T.BDCODSAIDA IS NOT NULL) AND (T.BDCODSAIDA <> ''''))';
          EXECUTE STATEMENT :wSql;
    
          IF (UPPER(:wTable) = 'TMP_TCADPRO_CORREITENS_TEMP') THEN
            BEGIN
              /* Alt.: #201741 - Na importacao do SPED, estava vindo, dois registros 0200 iguais, mudando apenas o codigo, com isso apresentava erro de chaves ao tentar atualizar.
              Quando mandava importar e o parametro das acoes de inconsistencias "Verificar apenas código dos produtos nas saídas" estava desmarcado,
              acabava vinculando ambos no mesmo produto, pois em "SP_ATUALIZAR_TMP_TCADPRO", acabava olhando apenas por descrição e EAN e encontrava um produto igual.
              Exemplo do arquivo SPED:
              |0200|SAAM_000005_380898144|TUBAINA FUNADA 6X2000 ML PET|17896718700222||PT|00|22021000||22||20|0301001|
              |0221|SAAM_000005_380898144|1|
              |0200|SAAM_000005_131266277|TUBAINA FUNADA 6X2000 ML PET|17896718700222||PT|00|22021000||22||20|0301001|
              |0221|SAAM_000005_131266277|1|
              */
              -- Apaga os registros duplicados
              DELETE FROM TMP_TCADPRO_CORREITENS_TEMP t
              WHERE T.BDSESSAO = :wSessaoAtu
                AND EXISTS(
                           SELECT x.bdSESSAO, x.bdALTCODPROD,x.bdCODEMP, x.bdORDEM, COUNT(*), MIN(x.bdCODPROD)
                           FROM TMP_TCADPRO_CORREITENS_TEMP x
                           WHERE x.bdSESSAO = t.bdSESSAO
                             AND x.bdALTCODPROD = t.bdALTCODPROD
                             AND x.bdCODEMP = t.bdCODEMP
                             AND x.bdORDEM = t.bdORDEM
                           GROUP BY x.bdSESSAO, x.bdALTCODPROD,x.bdCODEMP, x.bdORDEM
                           HAVING MIN(x.bdCODPROD) <> t.bdCODPROD
                           );
            END
  
          /*Se o campo de produto estiver na PK da tabela tem que transformar todos os códigos de produto para
            um código negativo, para que não corra risco de ter pk duplicada enquanto faz o update.
            Ex: Registro 70: BDCODPROD = 78 (Sequencial)
            Quando vai fazer o update o registro 2 que tem BDALTCODPROD 78 setando no BDCODPROD, vai dar erro de pk.*/
          SELECT IDX.RDB$FIELD_NAME
          FROM RDB$RELATION_CONSTRAINTS REL
          JOIN RDB$INDEX_SEGMENTS IDX ON(IDX.RDB$INDEX_NAME = REL.RDB$INDEX_NAME AND IDX.RDB$FIELD_NAME = 'BDCODPROD')
          WHERE REL.RDB$RELATION_NAME = :wTable
          AND REL.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY'
          INTO :wFieldName;
       
          IF (:wFieldName IS NOT NULL) THEN
            BEGIN
              wSql =          ' UPDATE '||:wTable||' T SET T.BDCODPROD = (T.BDCODPROD * -1) ';
              wSql = :wSql || ' WHERE T.BDSESSAO = '||:wSessaoAtu;
              wSql = :wSql || ' AND T.BDALTCODPROD IS NOT NULL';
              EXECUTE STATEMENT :wSql;
            END
    
          /*Apenas joga o altcodprod para o bdcodprod*/
          wSql =          ' UPDATE '||:wTable||' T SET T.BDCODPROD = T.BDALTCODPROD ';
          wSql = :wSql || ' WHERE T.BDSESSAO = '||:wSessaoAtu;
          wSql = :wSql || ' AND T.BDALTCODPROD IS NOT NULL';
          IF (UPPER(:wTable) = 'TMP_TFATCONV_TEMP') THEN    
            wSql = :wSql || ' AND T.BDCODPROD < 0 '; -- Alt.: #219552 - So atualiza os que estiverem vinculados a produtos...    
          EXECUTE STATEMENT :wSql;
       
          IF (:wFieldName IS NOT NULL) THEN
            BEGIN
              wSql =          ' UPDATE '||:wTable||' T SET T.BDCODPROD = (T.BDCODPROD * -1) ';
              wSql = :wSql || ' WHERE T.BDSESSAO = '||:wSessaoAtu;
              wSql = :wSql || ' AND T.BDCODPROD < 0';
              EXECUTE STATEMENT :wSql;
    END
    END

    END

END
^

create or alter procedure SP_VINCULAR_PARTICIPANTE (
    PRID_TERMINAL integer,
    PRVINCPORCNPJ_IE integer)
as
declare variable WSESSAOATU integer;
declare variable WSQL varchar(600);
declare variable WTABLE varchar(50);
declare variable WNOMECAMPO varchar(30);
declare variable WMANTERPART DM_BOOLEAN;
declare variable WIETER varchar(30);
declare variable WCNPJ varchar(30);
declare variable WNOMETER varchar(30);
declare variable WMANTERPARTCAMPO varchar(30);
declare variable WALTCODTER varchar(30);
declare variable WCODTER varchar(30);
declare variable WIETERCAMPO varchar(30);
declare variable WPOSFIXO varchar(30);
BEGIN
  FOR SELECT
          UPPER(TRIM(T.RDB$RELATION_NAME)) BDTABLE, RDB$FIELD_NAME BDNOME,
          'BDIETER' ||SUBSTRING(RDB$FIELD_NAME FROM 12 FOR char_length(RDB$FIELD_NAME)) BDIETER,
          SUBSTRING(RDB$FIELD_NAME FROM 12 FOR char_length(RDB$FIELD_NAME)) BDPOSFIXO
      FROM RDB$RELATION_FIELDS T
      WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
      AND (
            (RDB$FIELD_NAME = 'BDALTCODTER')  or
            (RDB$FIELD_NAME = 'BDALTCODTERREDESPACHANTE')or
            (RDB$FIELD_NAME = 'BDALTCODTERREMETENTE')or
            (RDB$FIELD_NAME = 'BDALTCODTERCOLETA')or
            (RDB$FIELD_NAME = 'BDALTCODTERENTREGA')or
            (RDB$FIELD_NAME = 'BDALTCODTERENT')or
            (RDB$FIELD_NAME = 'BDALTCODTERTRANS') or
            (RDB$FIELD_NAME = 'BDALTCODTERDESTINATARIO')
          )
      INTO :wTable ,:wNomecampo, :WIETERCAMPO, :WPOSFIXO
  DO
    BEGIN
      wSessaoAtu = NULL;

      SELECT S.BDSESSAO
      FROM TMP_TSESSAO_IMP S
      WHERE S.BDID_TERMINAL = :PRID_TERMINAL
      AND S.BDTABLE = :wTable
      INTO :wSessaoAtu;

      IF (:wSessaoAtu IS NOT NULL) THEN
        BEGIN
          WIETER           = '';
          WCNPJ            = '';
          WNOMETER         = '';
          WALTCODTER       = '';
          WMANTERPARTCAMPO = '';
          WCODTER          = '';

          WIETERCAMPO      = TRIM(WIETERCAMPO);
          WPOSFIXO         = TRIM(WPOSFIXO);

          /*Verifica se existe o campo na tabela*/
          IF (COALESCE(WPOSFIXO, WPOSFIXO, '') <> '') THEN
            BEGIN
                SELECT RDB$FIELD_NAME BDCNPJ
                FROM RDB$RELATION_FIELDS T
                WHERE RDB$RELATION_NAME = :wTable
                AND   RDB$FIELD_NAME LIKE 'BDCNPJ%'||:WPOSFIXO||'%'
                INTO :WCNPJ;
            END
          ELSE
            BEGIN
                SELECT RDB$FIELD_NAME BDCNPJ
                FROM RDB$RELATION_FIELDS T
                WHERE RDB$RELATION_NAME = :wTable
                AND   RDB$FIELD_NAME = 'BDCNPJ'
                INTO :WCNPJ;
            END

          /*Verifica se existe o campo na tabela*/
          IF (COALESCE(WPOSFIXO, WPOSFIXO, '') <> '') THEN
          BEGIN
              SELECT RDB$FIELD_NAME BDNOMETER
              FROM RDB$RELATION_FIELDS T
              WHERE RDB$RELATION_NAME = :wTable
              AND   RDB$FIELD_NAME LIKE 'BDNOMETER%'||:WPOSFIXO||'%'
              INTO :WNOMETER;
          END
          ELSE
          BEGIN
              SELECT RDB$FIELD_NAME BDNOMETER
              FROM RDB$RELATION_FIELDS T
              WHERE RDB$RELATION_NAME = :wTable
              AND   RDB$FIELD_NAME = 'BDNOMETER'
              INTO :WNOMETER;
          END

          /*Verifica se existe o campo na tabela*/
          IF (COALESCE(WPOSFIXO, WPOSFIXO, '') <> '') THEN
          BEGIN
              SELECT RDB$FIELD_NAME BDALTCODTER
              FROM RDB$RELATION_FIELDS T
              WHERE RDB$RELATION_NAME = :wTable
              AND   RDB$FIELD_NAME LIKE 'BDALTCODTER%'||:WPOSFIXO||'%'
              INTO :WALTCODTER;
          END
          ELSE
          BEGIN
              SELECT RDB$FIELD_NAME BDALTCODTER
              FROM RDB$RELATION_FIELDS T
              WHERE RDB$RELATION_NAME = :wTable
              AND   RDB$FIELD_NAME = 'BDALTCODTER'
              INTO :WALTCODTER;
          END

          /*Verifica se existe o campo na tabela*/
          IF (COALESCE(WPOSFIXO, WPOSFIXO, '') <> '') THEN
          BEGIN
              SELECT RDB$FIELD_NAME BDCODTER
              FROM RDB$RELATION_FIELDS T
              WHERE RDB$RELATION_NAME = :wTable
              AND   RDB$FIELD_NAME LIKE 'BDCODTER%'||:WPOSFIXO||'%'
              INTO :WCODTER;
          END
          ELSE
          BEGIN
              SELECT RDB$FIELD_NAME BDCODTER
              FROM RDB$RELATION_FIELDS T
              WHERE RDB$RELATION_NAME = :wTable
              AND   RDB$FIELD_NAME = 'BDCODTER'
              INTO :WCODTER;
          END

          /*Verifica se existe o campo na tabela*/
          SELECT RDB$FIELD_NAME
          FROM RDB$RELATION_FIELDS
          WHERE RDB$RELATION_NAME = :wTable
          AND RDB$FIELD_NAME = :WIETERCAMPO
          INTO :WIETER;

          WMANTERPART      = TRIM(WMANTERPART);
          WIETER           = TRIM(WIETER);
          WCNPJ            = TRIM(WCNPJ);
          WNOMETER         = TRIM(WNOMETER);
          WALTCODTER       = TRIM(WALTCODTER);
          WCODTER          = TRIM(WCODTER);

          /*Verifica se existe o campo na tabela*/
          SELECT RDB$FIELD_NAME
          FROM RDB$RELATION_FIELDS
          WHERE RDB$RELATION_NAME = :wTABLE
          AND RDB$FIELD_NAME = 'BDMANTERPART'
          INTO :WMANTERPARTCAMPO;
        
          WMANTERPARTCAMPO = TRIM(WMANTERPARTCAMPO);
        
          wManterPart = IIF(ROW_COUNT > 0, 'TRUE', 'FALSE');

          wSql =         ' UPDATE '||:wTABLE||' TB SET TB.'||:wALTCODTER||' = (';
          wSql = wSql ||                                                         ' SELECT FIRST 1 COALESCE(BDEDITCHAVE, 0) BDCODTER FROM TMP_TTERCEIRO T ';
          wSql = wSql ||                                                         ' WHERE T.BDCGCTER = TB.'||:wCNPJ;
          IF ((COALESCE(:wIETER, '') <> '') AND (:PRVINCPORCNPJ_IE = 1)) THEN
          wSql = wSql ||                                                         '       AND LPAD(REPLACE(REPLACE(REPLACE(T.BDIETER, ''.'', ''''), ''/'', ''''), ''-'', ''''),20,''0'') = COALESCE(LPAD(REPLACE(REPLACE(REPLACE(TB.'||:wIETER||', ''.'', ''''), ''/'', ''''), ''-'', ''''),20,''0''), '''') ';
          wSql = wSql ||                                                         ' order BY BDCGCTER,BDEDITCHAVE '; -- Alt.: #196697 - Estava causando lentidão nas importações, pois ordenava pela chave e depois buscava pelo CNPJ, colocado o campo do CNPJ para matar o indice da chave...
          wSql = wSql ||                                                     ')';
          wSql = wSql || ' WHERE TB.BDSESSAO = '||:wSESSAOATU;
          wSql = wSql || ' AND ((TB.'||:wCNPJ||' IS NOT NULL) OR (TB.'||:wCNPJ||' <> ''''))';
          IF ((:wManterPart = 'TRUE') AND (COALESCE(:WMANTERPARTCAMPO, :WMANTERPARTCAMPO, '') <> '')) THEN
          wSql = wSql || ' AND TB.BDMANTERPART <> UPPER(''T'')'; /*Se for pra manter, não atualiza*/
          EXECUTE STATEMENT :wSql;

          /*Participante do exterior*/
          wSql =         ' UPDATE '||:wTABLE||' TB SET TB.'||:wALTCODTER||' = (';
          wSql = wSql ||                                               ' SELECT FIRST 1 COALESCE(BDEDITCHAVE, 0) BDCODTER FROM TMP_TTERCEIRO T ';
          wSql = wSql ||                                               ' WHERE T.BDNOMETER = TB.'||:wNOMETER||'';
          wSql = wSql ||                                               ')';
          wSql = wSql || ' WHERE TB.BDSESSAO = '||:wSESSAOATU;
          wSql = wSql || ' AND ((TB.'||:wCNPJ||' IS NULL) OR (TB.'||:wCNPJ||' = ''''))';
          IF ((:wManterPart = 'TRUE') AND (COALESCE(:WMANTERPARTCAMPO, :WMANTERPARTCAMPO, '') <> '')) THEN
          wSql = wSql || ' AND TB.BDMANTERPART <> UPPER(''T'')';
          EXECUTE STATEMENT :wSql;

          IF ((:wManterPart = 'TRUE') AND (COALESCE(:WMANTERPARTCAMPO, :WMANTERPARTCAMPO, '') <> '')) THEN
            EXECUTE STATEMENT 'UPDATE '||:wTABLE||' TB SET TB.'||:wALTCODTER||' = TB.'||:wCODTER||' WHERE TB.BDSESSAO = '||:wSESSAOATU||' AND TB.BDMANTERPART = ''T''';
        
          /*Altera o nome dos participantes*/
          wSql =         ' UPDATE '||:wTABLE||' TB SET TB.'||:wNOMETER||' = (';
          wSql = wSql ||                                               ' SELECT FIRST 1 BDNOMETER FROM TMP_TTERCEIRO T ';
          wSql = wSql ||                                               ' WHERE T.BDEDITCHAVE = TB.'||:wALTCODTER||'';
          wSql = wSql ||                                               ')';
          wSql = wSql || ' WHERE TB.BDSESSAO = '||:wSESSAOATU;
          wSql = wSql || ' AND TB.'||:wALTCODTER||' IS NOT NULL';
          EXECUTE STATEMENT :wSql;
        
          EXECUTE STATEMENT 'UPDATE '||:wTABLE||' TB SET TB.'||:wCODTER||' = TB.'||:wALTCODTER||' WHERE TB.BDSESSAO = '||:wSESSAOATU||' AND TB.'||:wALTCODTER||' IS NOT NULL';
        END
    END
END^

create or alter procedure SP_ATUALIZAR_UNIDADE_MEDIDA (
    PRSESSAO integer,
    PRULTCHAVE integer,
    PRSESSAOMOV integer)
as
declare variable WTABLE varchar(50);
declare variable WCODUNIMED integer;
declare variable WAPEUNIMED varchar(5);
BEGIN

  IF (:PRULTCHAVE IS NULL) THEN
    BEGIN
      /*Atualiza a chave das unidades de medida já existentes no banco*/
      UPDATE TMP_TUNIDADEMEDIDA_TEMP UN
      SET UN.BDEDITCHAVE = (
                            SELECT FIRST 1 U.BDCODUNIMED FROM TUNIDADEMEDIDA U
                            WHERE UPPER(U.BDAPEUNIMED) = UPPER(UN.BDAPEUNIMED) --Larissa, 02/2021, Importações - Cadastro Unidade de Medida #122201 #122008
                            AND U.BDCODUNIMED IS NOT NULL
                            ORDER BY U.BDCODUNIMED
                           )
      WHERE UN.BDSESSAO = :PRSESSAO;

      UPDATE TMP_TUNIDADEMEDIDA_TEMP UN
      SET UN.BDCODUNIMED = UN.BDEDITCHAVE
      WHERE UN.BDSESSAO = :PRSESSAO
        AND un.bdEDITCHAVE IS NOT NULL;

        
      UPDATE TMP_TUNIDADEMEDIDA_TEMP UN
      SET UN.BDDESCUNIMED = (
                            SELECT FIRST 1 U.BDDESCUNIMED FROM TUNIDADEMEDIDA U
                            WHERE U.BDCODUNIMED = UN.BDCODUNIMED
                            )
      WHERE UN.BDSESSAO = :PRSESSAO
        AND UN.BDCODUNIMED IS NOT NULL
        AND UN.BDDESCUNIMED IS NULL;
    END
  ELSE
    BEGIN
      /*Coloca o novo código para os registros que não existem no banco(NOVOS REGISTROS)*/
      FOR SELECT U.BDCODUNIMED
          FROM TMP_TUNIDADEMEDIDA_TEMP U
          WHERE U.BDSESSAO = :PRSESSAO
          AND ((U.BDEDITCHAVE IS NULL) OR (U.BDEDITCHAVE = 0))
          INTO :wCodUniMed
      DO
        BEGIN
          UPDATE TMP_TUNIDADEMEDIDA_TEMP U
          SET U.BDEDITCHAVE = :PRULTCHAVE,
              u.bdCODUNIMED = :PRULTCHAVE
          WHERE U.BDSESSAO = :PRSESSAO
            AND ((U.BDEDITCHAVE IS NULL) OR (U.BDEDITCHAVE = 0))
            AND U.BDCODUNIMED = :wCodUniMed;

          PRULTCHAVE = :PRULTCHAVE - 1;
        END

      /*Setando as unidades de medida na DLL*/
      FOR SELECT U.BDEDITCHAVE, U.BDAPEUNIMED
          FROM TMP_TUNIDADEMEDIDA_TEMP U
          WHERE U.BDSESSAO = :PRSESSAO
          INTO :wCodUniMed, :wApeUniMed
      DO
        SETAPEUNIMED(:wCodUniMed, :wApeUniMed);

      /*Atualiza o código da unidade de medida nas tabelas dependentes*/
      FOR SELECT T.RDB$RELATION_NAME BDTABLE
          FROM RDB$RELATION_FIELDS T
          WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
          AND RDB$FIELD_NAME = 'BDALTCODUNIMED'
          INTO :wTable
      DO
        BEGIN
          EXECUTE STATEMENT 'UPDATE '||:wTable||' T SET T.BDALTCODUNIMED = IIF(GETCODUNIMED(T.BDAPEUNIMED) = -1, NULL, GETCODUNIMED(T.BDAPEUNIMED)) WHERE T.BDSESSAO = '||:PRSESSAO;

          EXECUTE STATEMENT 'UPDATE '||:wTable||' T SET T.BDCODUNIMED = BDALTCODUNIMED WHERE T.BDSESSAO = '||:PRSESSAO;
        END


      FOR SELECT T.RDB$RELATION_NAME BDTABLE
          FROM RDB$RELATION_FIELDS T
          WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
          AND RDB$FIELD_NAME = 'BDALTCODUNTRIBUTAVEL'
          INTO :wTable
      DO
        BEGIN
          EXECUTE STATEMENT 'UPDATE '||:wTable||' T SET T.BDALTCODUNTRIBUTAVEL = IIF(GETCODUNIMED(T.BDAPEUNTRIBUTAVEL) = -1, NULL, GETCODUNIMED(T.BDAPEUNTRIBUTAVEL)) WHERE T.BDSESSAO = '||:PRSESSAO;

          EXECUTE STATEMENT 'UPDATE '||:wTable||' T SET T.BDCODUNTRIBUTAVEL = BDALTCODUNTRIBUTAVEL WHERE T.BDSESSAO = '||:PRSESSAO;
        END

      if ((:PRSESSAOMOV IS NOT NULL) or (:PRSESSAOMOV > 0)) then
        BEGIN
         EXECUTE STATEMENT 'UPDATE TMP_VEF_EMP_TMOVPROSAI_TEMP T SET T.BDCOD_IS_UN_TRIB = IIF(GETCODUNIMED(T.BDIS_UN_TRIB) = -1, NULL, GETCODUNIMED(T.BDIS_UN_TRIB)) WHERE T.BDSESSAO = '||:PRSESSAOMOV;
        END

    END

    FREEANDNIL_LISTAUNIMED(0);
END
^

CREATE OR ALTER PROCEDURE SP_COMMIT_UNIDADEMEDIDA (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS
DECLARE VARIABLE WCODINCONSISTENCIA INTEGER;
DECLARE VARIABLE wAtuUnidMed VARCHAR(5);
DECLARE VARIABLE wEditChave  INTEGER;
DECLARE VARIABLE wDescUnimed VARCHAR(100);
DECLARE VARIABLE wApeUniMed  VARCHAR(5);
DECLARE VARIABLE wCodTipo    INTEGER;
BEGIN
  wCodInconsistencia = NULL;
  SELECT S.BDCODPLANOINCONS FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :PRCODEMP, NULL) S INTO :wCodInconsistencia;

  IF ((:wCodInconsistencia IS NULL) OR (:wCodInconsistencia = 0)) THEN
    SELECT I.BDCODPLANOINCONS FROM VEF_BASE_TACOESINCONS I WHERE UPPER(I.BDPLANODEFAULT) = 'TRUE' INTO :wCodInconsistencia;

  /* **********************Insere unidades de medida que não existem no banco********************** */
  INSERT INTO TUNIDADEMEDIDA(bdcodunimed, bddescunimed, bdapeunimed, bdcodtipo)
  SELECT un.bdeditchave bdcodunimed, un.bddescunimed, un.bdapeunimed, un.bdcodtipo
  FROM TMP_TUNIDADEMEDIDA_TEMP un
  WHERE un.bdsessao = :PRSESSAO
  AND NOT EXISTS(
                 SELECT u.bdcodunimed, u.bddescunimed,
                        u.bdapeunimed, u.bdcodtipo
                 FROM TUNIDADEMEDIDA U
                 WHERE UPPER(U.BDAPEUNIMED) = UPPER(un.BDAPEUNIMED) --Larissa, 02/2021, Importações - Cadastro Unidade de Medida #122201 #122008
                );

  /*Existe plano de inconsistencia no cadastro da empresa ou plano default*/
  IF ((:wCodInconsistencia IS NOT NULL) OR (:wCodInconsistencia > 0)) THEN
    BEGIN
      SELECT COALESCE(UPPER(I.BDATUUNIDMED), 'FALSE') BDATUUNIDMED FROM VEF_BASE_TACOESINCONS I WHERE I.BDCODPLANOINCONS = :wCodInconsistencia INTO :wAtuUnidMed;

      /*Atualiza as unidades de medida*/
      IF (:wAtuUnidMed = 'TRUE') THEN
        BEGIN
          FOR SELECT un.bdeditchave bdcodunimed, un.bddescunimed, un.bdapeunimed, un.bdcodtipo
              FROM TMP_TUNIDADEMEDIDA_TEMP un
              WHERE un.bdsessao = :PRSESSAO
              AND EXISTS(
                         SELECT u.bdcodunimed, u.bddescunimed,
                                u.bdapeunimed, u.bdcodtipo
                         FROM TUNIDADEMEDIDA U
                         WHERE UPPER(U.BDAPEUNIMED) = UPPER(un.BDAPEUNIMED)
                        )
              INTO :wEditChave, :wDescUniMed, :wApeUniMed, :wCodTipo
          DO
            UPDATE TUNIDADEMEDIDA U SET U.BDDESCUNIMED = :wDescUniMed, U.BDAPEUNIMED = :wApeUniMed, U.BDCODTIPO = :wCodTipo WHERE U.BDCODUNIMED = :wEditChave;
        END
    END


END^

CREATE OR ALTER PROCEDURE SP_UPDATE_FATCONV_TEMP (
    PRSESSAO integer)
as
BEGIN     
  /*Desvincula todas as Unidade de Medida*/

  UPDATE TMP_TFATCONV_TEMP T SET T.BDCODUNIMED = NULL WHERE T.BDSESSAO = :PRSESSAO;
    
  /*1 - Busca as unidades de medida na tabela TEMP, contém os registros que estão sendo importados*/
  UPDATE TMP_TFATCONV_TEMP T
  SET T.BDCODUNIMED = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TUNIDADEMEDIDA_TEMP P WHERE P.BDSESSAO = :PRSESSAO AND P.BDAPEUNIMED = T.BDAPEUNIMED)
  WHERE T.BDSESSAO = :PRSESSAO;
    
  /*2 - Busca as unidades de medida na tabela TMP, contém todos os registros do banco*/
  UPDATE TMP_TFATCONV_TEMP T
  SET T.BDCODUNIMED = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO P WHERE P.BDCODEMP = T.BDCODEMP AND P.BDAPEUNIMED = T.BDAPEUNIMED)
  WHERE T.BDSESSAO = :PRSESSAO
  AND T.BDCODUNIMED IS NULL;

END^

CREATE OR ALTER PROCEDURE SP_UPDATE_INSUMOS_TEMP (
    PRSESSAO INTEGER)
AS
BEGIN
  /*Desvincula todos os produtos*/
  UPDATE TMP_TCADPRO_INSUMOS_TEMP T SET T.BDCODPROINSUMO = NULL, T.BDDESCPROD = NULL WHERE T.BDSESSAO = :PRSESSAO;
    
  /*1 - Busca os produtos na tabela TEMP, contém os registros que estão sendo importados*/
  UPDATE TMP_TCADPRO_INSUMOS_TEMP T
  SET T.BDCODPROINSUMO = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :PRSESSAO AND P.BDCODSAIDA = T.BDCODSAIDAPROD),
      T.BDDESCPROD = (
                      SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                      FROM TMP_TCADPRO_TEMP P
                      WHERE P.BDSESSAO = :PRSESSAO
                      AND P.BDCODSAIDA = T.BDCODSAIDAPROD
                     )
  WHERE T.BDSESSAO = :PRSESSAO;
    
  /*2 - Busca os produtos na tabela TMP, contém todos os registros de produto do banco*/
  UPDATE TMP_TCADPRO_INSUMOS_TEMP T
  SET T.BDCODPROINSUMO = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO P WHERE P.BDCODEMP = T.BDCODEMP AND P.BDCODSAIDA = T.BDCODSAIDAPROD),
      T.BDDESCPROD = (
                      SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                      FROM TMP_TCADPRO P
                      WHERE P.BDCODEMP = T.BDCODEMP
                      AND P.BDCODSAIDA = T.BDCODSAIDAPROD
                     )
  WHERE T.BDSESSAO = :PRSESSAO
  AND T.BDCODPROINSUMO IS NULL;
    
  /*Apenas joga o altcodprod para o bdcodprod*/
--  UPDATE TMP_TCADPRO_INSUMOS_TEMP T SET T.BDCODPROINSUMO = T.BDALTCODPROD
--  WHERE T.BDSESSAO = :PRSESSAO
--  AND T.BDALTCODPROD IS NOT NULL;
END^

CREATE OR ALTER PROCEDURE SP_UPDATE_CORREITENS_TEMP (
    PRSESSAO integer)
AS
BEGIN
  /*Desvincula todos os produtos*/
  UPDATE TMP_TCADPRO_CORREITENS_TEMP T SET T.BDCODITEM = NULL, T.BDDESCPROD = NULL WHERE T.BDSESSAO = :PRSESSAO;
    
  /*1 - Busca os produtos na tabela TEMP, contém os registros que estão sendo importados*/
  UPDATE TMP_TCADPRO_CORREITENS_TEMP T
  SET T.BDCODITEM = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :PRSESSAO AND P.BDCODSAIDA = T.BDCODSAIDAPROD),
      T.BDDESCPROD = (
                      SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                      FROM TMP_TCADPRO_TEMP P
                      WHERE P.BDSESSAO = :PRSESSAO
                      AND P.BDCODSAIDA = T.BDCODSAIDAPROD
                     )
  WHERE T.BDSESSAO = :PRSESSAO;
    
  /*2 - Busca os produtos na tabela TMP, contém todos os registros de produto do banco*/
  UPDATE TMP_TCADPRO_CORREITENS_TEMP T
  SET T.BDCODITEM = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO P WHERE P.BDCODEMP = T.BDCODEMP AND P.BDCODSAIDA = T.BDCODSAIDAPROD),
      T.BDDESCPROD = (
                      SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                      FROM TMP_TCADPRO P
                      WHERE P.BDCODEMP = T.BDCODEMP
                      AND P.BDCODSAIDA = T.BDCODSAIDAPROD
                     )
  WHERE T.BDSESSAO = :PRSESSAO
  AND T.BDCODITEM IS NULL;
END^

CREATE OR ALTER PROCEDURE SP_ELIMINA_DUPLICIDADE_IMP (
    PRSESSAO INTEGER,
    PRORIGEM VARCHAR(3),
    PRCFE DM_BOOLEAN)
AS
DECLARE VARIABLE WI INTEGER;
DECLARE VARIABLE WSQL VARCHAR(500);
DECLARE VARIABLE WC INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCHAVES VARCHAR(200);
DECLARE VARIABLE WTABLE VARCHAR(200);
DECLARE VARIABLE WLISTACHAVE VARCHAR(200);
BEGIN
  PRORIGEM = UPPER(:PRORIGEM);
  PRCFE    = UPPER(:PRCFE);

  IF (:PRORIGEM = 'SAI') THEN
    BEGIN
      wI = 1;
      WHILE (:wI <= 2) DO
        BEGIN
          wSQL =         ' SELECT S.BDCODEMP, LIST(S.BDCHAVE) FROM TMP_VEF_EMP_TMOVSAI_TEMP S ';
          wSQL = wSQL || ' WHERE S.BDSESSAO = '||:PRSESSAO;

          IF (:PRCFE = 'TRUE') THEN
            wSQL = wSQL || ' AND ((s.BDCHAVENFECANC IS NOT NULL) AND (s.BDDATACANC IS NOT NULL) AND (s.BDNUMDOCINI IS NOT NULL) AND (s.BDNUMDOCFIM IS NOT NULL)) '; -- Alt.: 18626 - Não considerar eventos de cancelamento...

          wSQL = wSQL || ' GROUP BY S.BDCODEMP, S.BDDATAEMISSAO, S.BDNUMDOCINI, S.BDNUMDOCFIM, ';

          IF (:wI = 1) THEN
            wSQL = wSQL || '          S.BDSERIEORIGINAL, S.BDESPECIE, S.BDMODELO, S.BDNOMETER, Coalesce(S.BDCODEQUIPSAT,0) ';
          ELSE
            wSQL = wSQL || '          S.BDSERIEORIGINAL, S.BDESPECIE, S.BDMODELO, S.BDCNPJ, Coalesce(S.BDCODEQUIPSAT,0) ';

          wSQL = wSQL || ' HAVING COUNT(BDCHAVE) > 1 ';

          FOR EXECUTE STATEMENT :wSQL INTO :wCodEmp, :wListaChave DO
            BEGIN
              wChaves = '';
              wSQL =         ' SELECT SKIP 1 s.bdchave ';
              wSQL = wSQL || ' FROM TMP_VEF_EMP_TMOVSAI_TEMP S ';
              wSQL = wSQL || '               WHERE s.bdsessao = '||:PRSESSAO;
              wSQL = wSQL || '               AND s.bdcodemp = '||:wCodEmp;
              wSQL = wSQL || '               AND s.bdchave IN ('||:wListaChave||')';
              wSQL = wSQL || '               ORDER BY s.bdsessao, s.bdcodemp, s.bdchave';
    
              FOR EXECUTE STATEMENT :wSQL INTO :wC
              DO
                BEGIN
                  IF (:wChaves = '') THEN
                    wChaves = wChaves || :wC;
                  ELSE
                    wChaves = wChaves || ', '|| :wC;
                END
    
              FOR SELECT TRIM(RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME) AS BDTABLE
                  FROM RDB$RELATION_CONSTRAINTS, RDB$INDICES, RDB$RELATION_FIELDS
                  WHERE RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME LIKE '%TMP_%_TEMP%'
                  AND RDB$RELATION_CONSTRAINTS.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY'
                  AND RDB$RELATION_CONSTRAINTS.RDB$INDEX_NAME = RDB$INDICES.RDB$INDEX_NAME
                  AND RDB$RELATION_FIELDS.RDB$RELATION_NAME = RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME
                  AND RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME <> 'TMP_TCADPRO_INSUMOS_TEMP'
                  AND RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME <> 'TMP_VEF_BASE_TNATOP_TEMP'
                  AND RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME <> 'TMP_TTERCEIRO_TEMP'
                  AND RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME <> 'TMP_TUNIDADEMEDIDA_TEMP'
                  AND RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME <> 'TMP_TCADPRO_TEMP'
                  AND RDB$RELATION_CONSTRAINTS.RDB$CONSTRAINT_NAME CONTAINING('SAI')
                  AND RDB$RELATION_FIELDS.RDB$FIELD_NAME = 'BDCHAVE'
                  GROUP BY RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME, RDB$RELATION_CONSTRAINTS.RDB$CONSTRAINT_NAME
                  ORDER BY RDB$RELATION_CONSTRAINTS.RDB$CONSTRAINT_NAME
                  INTO :wTable
              DO
                EXECUTE STATEMENT 'DELETE FROM '||:wTable||' T WHERE T.BDSESSAO = '||:PRSESSAO||' AND T.BDCODEMP = '||:wCodEmp||' AND T.BDCHAVE IN('||:wChaves||')';
            END
          wI = wI + 1;
        END
    END
END^ 

CREATE OR ALTER procedure SP_DIGITOS_IGUAIS (
    PRVALUE varchar(100))
returns (
    BDRESULT varchar(5))
as
declare variable WFIRSTDIG integer;
declare variable WI integer;
begin
  wI = 0;
  wFirstDig = SUBSTRING(:PRVALUE FROM 1 FOR 1);

  BDRESULT = 'TRUE';
  WHILE (wI <> CHAR_LENGTH(:PRVALUE)) DO
    BEGIN
      wI = wI + 1;
      IF (:wFirstDig <> SUBSTRING(:PRVALUE FROM wI FOR 1)) THEN
        BEGIN
          BDRESULT = 'FALSE';
          BREAK;
        END
    END
  SUSPEND;
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER PROCEDURE SP_VALIDA_CPF (
    PRCPF VARCHAR(14))
RETURNS (
    BDISVALID VARCHAR(5))
AS
DECLARE VARIABLE WI INTEGER;
DECLARE VARIABLE WSOMA1 INTEGER;
DECLARE VARIABLE WSOMA2 INTEGER;
DECLARE VARIABLE FRESULT VARCHAR(5);
DECLARE VARIABLE FDIGITO CHAR(2);
DECLARE VARIABLE wDigAux1 INTEGER;
DECLARE VARIABLE wDigAux2 INTEGER;
BEGIN
  BDISVALID = 'TRUE';

  SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(:PRCPF) INTO :PRCPF;

  FDIGITO = SUBSTRING(:PRCPF FROM 10 FOR 2);

  /*Verifica se tem letras no CPF*/
  SELECT BDRESULT FROM SONUMEROS(:PRCPF) INTO :FRESULT;
  IF (:FRESULT = '0') THEN
    BDISVALID = 'FALSE';
  ELSE
      BEGIN
        SELECT BDRESULT FROM SP_DIGITOS_IGUAIS(:PRCPF) INTO :FRESULT;
        IF (:FRESULT = 'TRUE') THEN
          BDISVALID = 'TRUE';
        ELSE
          BEGIN
            wI = 1;
            wSoma1 = 0;
            WHILE (wI <= 9) DO
              BEGIN
                wSoma1 = wSoma1 + (wI + 1) * CAST(SUBSTRING(:PRCPF FROM 10 - wI FOR 1) AS INTEGER);
                wI = wI + 1;
              END

            wDigAux1 =  11 - (:wSoma1 -  ((:wSoma1 / CAST(11 AS INTEGER) ) * 11));
            IF (:wDigAux1 > 9) THEN
              wDigAux1 = 0;

            wI = 1;
            wSoma2 = 0;
            WHILE (wI <= 10) DO
              BEGIN
                wSoma2 = wSoma2 + (wI + 1) * CAST(SUBSTRING(:PRCPF FROM 11 - wI FOR 1) AS INTEGER);
                wI = wI + 1;
              END

            wDigAux2 =  11 - (:wSoma2 -  ((:wSoma2 / CAST(11 AS INTEGER) ) * 11));
            IF (:wDigAux2 > 9) THEN
              wDigAux2 = 0;

            IF (:FDIGITO <> (CAST(:wDigAux1 AS CHAR(1)) || CAST(:wDigAux2 AS CHAR(1)))) THEN
              BDISVALID = 'FALSE';
          END
      END
  SUSPEND;
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER PROCEDURE SP_VALIDA_CNPJ (
    PRCNPJ VARCHAR(18))
RETURNS (
    BDISVALID VARCHAR(5))
AS
DECLARE VARIABLE FSOMA INTEGER;
DECLARE VARIABLE FRESULT VARCHAR(5);
DECLARE VARIABLE FCNPJ CHAR(13);
DECLARE VARIABLE FDIGITO CHAR(2);
DECLARE VARIABLE FMULT CHAR(13);
DECLARE VARIABLE FI INTEGER;
DECLARE VARIABLE FDigCnpj INTEGER;
DECLARE VARIABLE FDigMult INTEGER;
DECLARE VARIABLE FResto INTEGER;
DECLARE VARIABLE FFirstDig INTEGER;
DECLARE VARIABLE FSecDig INTEGER;
DECLARE VARIABLE FDigCalc CHAR(2);
BEGIN
  FMULT = '543298765432';
  BDISVALID = 'TRUE';

  /*Retira pontos, barras...*/
  SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(:PRCNPJ) INTO :PRCNPJ;

  /*Se todos os digitos forem iguais é valido*/
  SELECT BDRESULT FROM SP_DIGITOS_IGUAIS(:PRCNPJ) INTO :FRESULT;
  IF (:FRESULT = 'TRUE') THEN
    BEGIN
      BDISVALID = 'TRUE';
      SUSPEND;
      EXIT;
    END

  FDIGITO = SUBSTRING(:PRCNPJ FROM 13 FOR 2);
  FCNPJ   = SUBSTRING(:PRCNPJ FROM 1 FOR 12);

  /*Verifica se tem letras no CNPJ*/
  SELECT BDRESULT FROM SONUMEROS(:PRCNPJ) INTO :FRESULT;

  IF (:FRESULT = '0') THEN
    BDISVALID = 'FALSE';
  ELSE
  IF (CHAR_LENGTH(:FCNPJ) < 12) THEN
    BDISVALID = 'FALSE';

  FSOMA = 0;
  FI = 1;
  WHILE (:FI <= 12) DO
    BEGIN
      FDigCnpj = CAST(SUBSTRING(:FCNPJ FROM FI FOR 1) AS INTEGER);
      FDigMult = CAST(SUBSTRING(:FMult FROM FI FOR 1) AS INTEGER);
      FSoma    = FSoma + (FDigCnpj * FDigMult);
      FI = :FI + 1;
    END

  FResto = :FSoma - ((:FSoma/11) * 11);

  FFirstDig = 11 - :FResto;

  IF ((:FResto = 1) OR (:FResto = 0)) THEN
    FFirstDig = 0;

  FDigCalc = CAST(:FFirstDig AS CHAR(1));

  FCNPJ = TRIM(FCNPJ) || FDigCalc;

  FMult = '6543298765432';

  IF (CHAR_LENGTH(:FCNPJ) < 13) THEN
    BEGIN
      BDISVALID = 'FALSE';
      SUSPEND;
      EXIT;
    END

  FSoma = 0;
  FI = 1;
  WHILE (FI <= 13) DO
    BEGIN
      FDigCnpj = CAST(SUBSTRING(:FCNPJ FROM :FI FOR 1) AS INTEGER);
      FDigMult = CAST(SUBSTRING(:FMult FROM :FI FOR 1) AS INTEGER);
      FSoma    = :FSoma + (:FDigCnpj * FDigMult);
      FI = :FI + 1;
    END

  FResto = :FSoma - ((:FSoma/11) * 11);
  FSecDig= 11 - FResto;
  IF ((:FResto = 1) OR (:FResto = 0)) THEN
    FSecDig = 0;

  FDigCalc = TRIM(:FDigCalc) || :FSecDig;
  IF (:FDigito <> :FDigCalc) THEN
    BDISVALID = 'FALSE';

  SUSPEND;
END^

create or alter procedure SP_TROCA_NOME_ITEMMENU (
    PR_NOME_DE varchar(60),
    PR_NOME_PARA varchar(60))
as
declare variable V_NOME_DE_UPPER varchar(60);
declare variable V_NOME_PARA_UPPER varchar(60);
begin
  /* Procedure Text */
  -- Script para modificar privilegio na tela de Lançamento de contas a pagar
  V_NOME_DE_UPPER   = upper(PR_NOME_DE);
  V_NOME_PARA_UPPER = upper(PR_NOME_PARA);

  insert into TPRIVILEGIO (BDITEMPRIV, BDCODSIS)
  select :PR_NOME_PARA as BDITEMPRIV, BDCODSIS
  from TPRIVILEGIO
  where upper(BDITEMPRIV) = :V_NOME_DE_UPPER and
        not exists(select *
                   from TPRIVILEGIO
                   where upper(BDITEMPRIV) = :V_NOME_PARA_UPPER);

  insert into TPRIVILEGIO_GRUPOUSUARIO (BDCODGRUPO, BDITEMPRIV, BDCODSIS)
  select BDCODGRUPO, :PR_NOME_PARA as BDITEMPRIV, BDCODSIS
  from TPRIVILEGIO_GRUPOUSUARIO
  where upper(BDITEMPRIV) = :V_NOME_DE_UPPER and
        not exists(select *
                   from TPRIVILEGIO_GRUPOUSUARIO
                   where upper(BDITEMPRIV) = :V_NOME_PARA_UPPER);

  insert into TPERMISSAO_PRIVILEGIO (BDCODPER, BDITEMPRIV, BDCODGRUPO)
  select BDCODPER, :PR_NOME_PARA as BDITEMPRIV, BDCODGRUPO
  from TPERMISSAO_PRIVILEGIO
  where upper(BDITEMPRIV) = :V_NOME_DE_UPPER and
        not exists(select *
                   from TPERMISSAO_PRIVILEGIO
                   where upper(BDITEMPRIV) = :V_NOME_PARA_UPPER);

  delete from TPRIVILEGIO where upper(BDITEMPRIV) = :V_NOME_DE_UPPER;

  delete from TPRIVILEGIO_GRUPOUSUARIO where upper(BDITEMPRIV) = :V_NOME_DE_UPPER;

  delete from TPERMISSAO_PRIVILEGIO where upper(BDITEMPRIV) = :V_NOME_DE_UPPER;

end^

create or alter procedure SP_GERAR_INCON_TERCEIRO (
    PRSESSAO integer,
    PRREF integer,
    PRCODEMP integer,
    PRPUSH DM_BOOLEAN)
as
declare variable FCODPLANOINCO integer;
declare variable FPARTIEISE varchar(5);
BEGIN
  IF ((:PRCODEMP IS NOT NULL) AND (:PRCODEMP <> 0)) THEN
    SELECT SP.BDCODPLANOINCONS FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :PRCODEMP, NULL) SP INTO :FCODPLANOINCO;

  IF ((:FCODPLANOINCO IS NULL) OR (:FCODPLANOINCO = 0)) THEN
    SELECT INCO.BDCODPLANOINCONS FROM VEF_BASE_TACOESINCONS INCO WHERE UPPER(INCO.BDPLANODEFAULT) = 'TRUE' INTO :FCODPLANOINCO;

  IF ((:FCODPLANOINCO IS NOT NULL) OR (:FCODPLANOINCO > 0)) THEN
    BEGIN
      SELECT UPPER(INCO.BDPARTIEISE) FROM VEF_BASE_TACOESINCONS INCO WHERE INCO.BDCODPLANOINCONS = :FCODPLANOINCO INTO :FPARTIEISE;
      IF (:FPARTIEISE = 'TRUE') THEN
        UPDATE TMP_TTERCEIRO_TEMP T SET T.BDIETER = 'ISENTO', T.BDIEVALIDA = 'TRUE' WHERE T.BDSESSAO = :PRSESSAO AND T.BDIEVALIDA = 'FALSE';
    END

  /*1 - Apelido vazio*/
  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
  SELECT 1 BDCODINCONSISTENCIA, T.BDSESSAO, T.BDCODTER
  FROM TMP_TTERCEIRO_TEMP T
  WHERE T.BDSESSAO = :PRSESSAO
  AND ((TRIM(T.BDAPELIDOTER) = '') OR (T.BDAPELIDOTER IS NULL));

  /*3 - Nome vazio*/
  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
  SELECT 3 BDCODINCONSISTENCIA, T.BDSESSAO, T.BDCODTER
  FROM TMP_TTERCEIRO_TEMP T
  WHERE T.BDSESSAO = :PRSESSAO
  AND ((TRIM(T.BDNOMETER) = '') OR (T.BDNOMETER IS NULL));

  /*4 - CPF/CNPJ vazio*/
  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
  SELECT 4 BDCODINCONSISTENCIA, T.BDSESSAO, T.BDCODTER
  FROM TMP_TTERCEIRO_TEMP T
  WHERE T.BDSESSAO = :PRSESSAO
  AND T.BDCODPAIS = 30 /*Participante do exterior não tem cnpj mesmo*/
  AND ((TRIM(T.BDCGCTER) = '') OR (T.BDCGCTER IS NULL));

  /******************Validar CPF e CNPJ******************/
  /*CPF*/
  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
  SELECT 5 BDCODINCONSISTENCIA, BDSESSAO, BDCODTER
  FROM (
        SELECT T.BDSESSAO, T.BDCODTER, (SELECT SP.BDISVALID FROM SP_VALIDA_CPF(T.BDCGCTER) SP) BDISVALID
        FROM (
              SELECT T.BDCODTER, T.BDSESSAO, CHAR_LENGTH(T.BDCGCTER) BDTIPO, BDCGCTER
              FROM TMP_TTERCEIRO_TEMP T
              WHERE T.BDSESSAO = :PRSESSAO
              AND ((T.BDCGCTER IS NOT NULL) OR (TRIM(T.BDCGCTER) <> ''))
             ) T
        WHERE T.BDTIPO = 14
       )
  WHERE BDISVALID = 'FALSE';

  /*CNPJ*/
  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
  SELECT 5 BDCODINCONSISTENCIA, BDSESSAO, BDCODTER
  FROM (
        SELECT T.BDCODTER, T.BDSESSAO, (SELECT SP.BDISVALID FROM SP_VALIDA_CNPJ(T.BDCGCTER) SP)
        FROM (
              SELECT T.BDCODTER, T.BDSESSAO, CHAR_LENGTH(T.BDCGCTER) BDTIPO, BDCGCTER
              FROM TMP_TTERCEIRO_TEMP T
              WHERE T.BDSESSAO = :PRSESSAO
              AND ((T.BDCGCTER IS NOT NULL) OR (TRIM(T.BDCGCTER) <> ''))
             ) T
        WHERE T.BDTIPO = 18
       )
  WHERE BDISVALID = 'FALSE';
  /************************************/

  /*8 - Inscrição Estadual vazia*/
  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
  SELECT 8 BDCODINCONSISTENCIA, T.BDSESSAO, T.BDCODTER  
  FROM TMP_TTERCEIRO_TEMP T
  WHERE T.BDSESSAO = :PRSESSAO
  AND TRIM(T.BDIETER) = '';

  /*9 - Inscrição estadual inválida*/
  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
  SELECT 9 BDCODINCONSISTENCIA, T.BDSESSAO, T.BDCODTER
  FROM TMP_TTERCEIRO_TEMP T
  WHERE T.BDSESSAO = :PRSESSAO
  AND TRIM(T.BDIEVALIDA) = 'FALSE';
  
  
  if (PRPUSH = 'TRUE') then   --vai igonar o participante PF a inconsistencia da cidade
    begin
      /*7 - Cidade inválida - Todos participante sem cidade*/
      INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
      SELECT 7 BDCODINCONSISTENCIA, T.BDSESSAO, T.BDCODTER
      FROM TMP_TTERCEIRO_TEMP T
      WHERE (T.BDSESSAO = :PRSESSAO)
      AND ((T.BDCODCID IS NULL) or (T.BDCODCID = 0))
      and (CHAR_LENGTH(t.bdcgcter) = 18);

      /*7 - Cidade inválida - Todos participantes que tem cidade mas é cidade inconsistente*/
      INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
      SELECT 7 BDCODINCONSISTENCIA, T.BDSESSAO, T.BDCODTER
      FROM TMP_TTERCEIRO_TEMP T
      LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = T.BDCODCID)
      WHERE T.BDSESSAO = :PRSESSAO
      AND T.BDCODCID IS NOT NULL
      AND C.BDCODCID IS NULL
      and (CHAR_LENGTH(t.bdcgcter) = 18);
    end
  else
    begin
      /*7 - Cidade inválida - Todos participante sem cidade*/
      INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
      SELECT 7 BDCODINCONSISTENCIA, T.BDSESSAO, T.BDCODTER
      FROM TMP_TTERCEIRO_TEMP T
      WHERE (T.BDSESSAO = :PRSESSAO)
      AND ((T.BDCODCID IS NULL) or (T.BDCODCID = 0));


  /*7 - Cidade inválida - Todos participantes que tem cidade mas é cidade inconsistente*/
  INSERT INTO VEF_INCON_TTERCEIROS(BDCODINCONSISTENCIA, BDSESSAO, BDCODTER)
  SELECT 7 BDCODINCONSISTENCIA, T.BDSESSAO, T.BDCODTER
  FROM TMP_TTERCEIRO_TEMP T
  LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = T.BDCODCID)
  WHERE T.BDSESSAO = :PRSESSAO
  AND T.BDCODCID IS NOT NULL
  AND C.BDCODCID IS NULL;  


    end

END^

CREATE OR ALTER PROCEDURE SP_ATUALIZA_CODPRODARQ (
    PRSESSAO INTEGER,
    PRCODPRODARQOLD VARCHAR(60),
    PRCODPRODARQNEW VARCHAR(60),
    PRCAMPO VARCHAR(12))
AS
DECLARE VARIABLE FSQL VARCHAR(255);
DECLARE VARIABLE FTABLENAME VARCHAR(50);
BEGIN
  PRCAMPO = UPPER(TRIM(:PRCAMPO));

  FOR SELECT RDB$RELATION_NAME
      FROM RDB$RELATION_FIELDS
      WHERE RDB$FIELD_NAME = :PRCAMPO
      AND RDB$RELATION_NAME LIKE '%TMP_%%_TEMP%'
      AND RDB$RELATION_NAME <> 'TMP_TCADPRO_TEMP'
      GROUP BY RDB$RELATION_NAME
      INTO :FTableName
  DO
    BEGIN                       
      FSQL = 'UPDATE '||:FTableName||' SET '||:PrCampo||' = '||''''||:PrCodProdArqNew||''''||' WHERE BDSESSAO = '||:PrSessao||' AND '||:PrCampo||' = '||''''||:PRCODPRODARQOLD||'''';
      EXECUTE STATEMENT FSQL;
    END
END^

CREATE OR ALTER procedure SP_DIGITOS_IGUAIS (
    PRVALUE varchar(100))
returns (
    BDRESULT varchar(5))
as
declare variable WFIRSTDIG integer;
declare variable WI integer;
begin
  wI = 0;
  wFirstDig = SUBSTRING(:PRVALUE FROM 1 FOR 1);

  BDRESULT = 'TRUE';
  WHILE (wI <> CHAR_LENGTH(:PRVALUE)) DO
    BEGIN
      wI = wI + 1;
      IF (:wFirstDig <> SUBSTRING(:PRVALUE FROM wI FOR 1)) THEN
        BEGIN
          BDRESULT = 'FALSE';
          BREAK;
        END
    END
  SUSPEND;
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER PROCEDURE SP_VALIDA_CPF (
    PRCPF VARCHAR(14))
RETURNS (
    BDISVALID VARCHAR(5))
AS
DECLARE VARIABLE WI INTEGER;
DECLARE VARIABLE WSOMA1 INTEGER;
DECLARE VARIABLE WSOMA2 INTEGER;
DECLARE VARIABLE FRESULT VARCHAR(5);
DECLARE VARIABLE FDIGITO CHAR(2);
DECLARE VARIABLE wDigAux1 INTEGER;
DECLARE VARIABLE wDigAux2 INTEGER;
BEGIN
  BDISVALID = 'TRUE';

  SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(:PRCPF) INTO :PRCPF;

  FDIGITO = SUBSTRING(:PRCPF FROM 10 FOR 2);

  /*Verifica se tem letras no CPF*/
  SELECT BDRESULT FROM SONUMEROS(:PRCPF) INTO :FRESULT;
  IF (:FRESULT = '0') THEN
    BDISVALID = 'FALSE';
  ELSE
      BEGIN
        SELECT BDRESULT FROM SP_DIGITOS_IGUAIS(:PRCPF) INTO :FRESULT;
        IF (:FRESULT = 'TRUE') THEN
          BDISVALID = 'TRUE';
        ELSE
          BEGIN
            wI = 1;
            wSoma1 = 0;
            WHILE (wI <= 9) DO
              BEGIN
                wSoma1 = wSoma1 + (wI + 1) * CAST(SUBSTRING(:PRCPF FROM 10 - wI FOR 1) AS INTEGER);
                wI = wI + 1;
              END

            wDigAux1 =  11 - (:wSoma1 -  ((:wSoma1 / CAST(11 AS INTEGER) ) * 11));
            IF (:wDigAux1 > 9) THEN
              wDigAux1 = 0;

            wI = 1;
            wSoma2 = 0;
            WHILE (wI <= 10) DO
              BEGIN
                wSoma2 = wSoma2 + (wI + 1) * CAST(SUBSTRING(:PRCPF FROM 11 - wI FOR 1) AS INTEGER);
                wI = wI + 1;
              END

            wDigAux2 =  11 - (:wSoma2 -  ((:wSoma2 / CAST(11 AS INTEGER) ) * 11));
            IF (:wDigAux2 > 9) THEN
              wDigAux2 = 0;

            IF (:FDIGITO <> (CAST(:wDigAux1 AS CHAR(1)) || CAST(:wDigAux2 AS CHAR(1)))) THEN
              BDISVALID = 'FALSE';
          END
      END
  SUSPEND;
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER PROCEDURE SP_VALIDA_CNPJ (
    PRCNPJ VARCHAR(18))
RETURNS (
    BDISVALID VARCHAR(5))
AS
DECLARE VARIABLE FSOMA INTEGER;
DECLARE VARIABLE FRESULT VARCHAR(5);
DECLARE VARIABLE FCNPJ CHAR(13);
DECLARE VARIABLE FDIGITO CHAR(2);
DECLARE VARIABLE FMULT CHAR(13);
DECLARE VARIABLE FI INTEGER;
DECLARE VARIABLE FDigCnpj INTEGER;
DECLARE VARIABLE FDigMult INTEGER;
DECLARE VARIABLE FResto INTEGER;
DECLARE VARIABLE FFirstDig INTEGER;
declare variable FSecDig INTEGER;
DECLARE VARIABLE FDigCalc CHAR(2);
BEGIN
  FMULT = '543298765432';
  BDISVALID = 'TRUE';

  /*Retira pontos, barras...*/
  SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(:PRCNPJ) INTO :PRCNPJ;

  /*Se todos os digitos forem iguais é valido*/
  SELECT BDRESULT FROM SP_DIGITOS_IGUAIS(:PRCNPJ) INTO :FRESULT;
  IF (:FRESULT = 'TRUE') THEN
    BEGIN
      BDISVALID = 'TRUE';
      SUSPEND;
      EXIT;
    END

  FDIGITO = SUBSTRING(:PRCNPJ FROM 13 FOR 2);
  FCNPJ   = SUBSTRING(:PRCNPJ FROM 1 FOR 12);

  /*Verifica se tem letras no CNPJ*/
  SELECT BDRESULT FROM SONUMEROS(:PRCNPJ) INTO :FRESULT;

  IF (:FRESULT = '0') THEN
    BDISVALID = 'FALSE';
  ELSE
  IF (CHAR_LENGTH(:FCNPJ) < 12) THEN
    BDISVALID = 'FALSE';

  FSOMA = 0;
  FI = 1;
  WHILE (:FI <= 12) DO
    BEGIN
      FDigCnpj = CAST(SUBSTRING(:FCNPJ FROM FI FOR 1) AS INTEGER);
      FDigMult = CAST(SUBSTRING(:FMult FROM FI FOR 1) AS INTEGER);
      FSoma    = FSoma + (FDigCnpj * FDigMult);
      FI = :FI + 1;
    END

  FResto = :FSoma - ((:FSoma/11) * 11);

  FFirstDig = 11 - :FResto;

  IF ((:FResto = 1) OR (:FResto = 0)) THEN
    FFirstDig = 0;

  FDigCalc = CAST(:FFirstDig AS CHAR(1));

  FCNPJ = TRIM(FCNPJ) || FDigCalc;

  FMult = '6543298765432';

  IF (CHAR_LENGTH(:FCNPJ) < 13) THEN
    BEGIN
      BDISVALID = 'FALSE';
      SUSPEND;
      EXIT;
    END

  FSoma = 0;
  FI = 1;
  WHILE (FI <= 13) DO
    BEGIN
      FDigCnpj = CAST(SUBSTRING(:FCNPJ FROM :FI FOR 1) AS INTEGER);
      FDigMult = CAST(SUBSTRING(:FMult FROM :FI FOR 1) AS INTEGER);
      FSoma    = :FSoma + (:FDigCnpj * FDigMult);
      FI = :FI + 1;
    END

  FResto = :FSoma - ((:FSoma/11) * 11);
  FSecDig= 11 - FResto;
  if ((:FResto = 1) OR (:FResto = 0)) then
    FSecDig = 0;

  FDigCalc = TRIM(:FDigCalc) || :FSecDig;
  IF (:FDigito <> :FDigCalc) THEN
    BDISVALID = 'FALSE';

  SUSPEND;
END^

CREATE OR ALTER procedure SP_ATUALIZA_CODPRODARQ (
    PRSESSAO integer,
    PRCODPRODARQOLD varchar(60),
    PRCODPRODARQNEW varchar(60),
    PRCAMPO varchar(12))
as
declare variable FSQL varchar(255);
declare variable FTABLENAME varchar(50);
begin
  PRCAMPO = UPPER(TRIM(:PRCAMPO));

  FOR SELECT RDB$RELATION_NAME
      FROM RDB$RELATION_FIELDS
      WHERE RDB$FIELD_NAME = :PRCAMPO
      AND RDB$RELATION_NAME LIKE '%TMP_%%_TEMP%'
      AND RDB$RELATION_NAME <> 'TMP_TCADPRO_TEMP'
      GROUP BY RDB$RELATION_NAME
      INTO :FTableName
  DO
    BEGIN                       
      FSQL = 'UPDATE '||:FTableName||' SET '||:PrCampo||' = '||''''||:PrCodProdArqNew||''''||' WHERE BDSESSAO = '||:PrSessao||' AND '||:PrCampo||' = '||''''||:PRCODPRODARQOLD||'''';
      EXECUTE STATEMENT FSQL;
    END
end^

CREATE OR ALTER trigger vfin_base_tescparcontas_bi0 for vfin_base_tescparcontas
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodesc IS NULL) OR (NEW.bdcodesc = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodesc)),1) FROM tescritorio INTO vcodigo;
        NEW.bdcodesc = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodesc FROM tescritorio WHERE bdcodesc = NEW.bdcodesc INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodesc)),1) FROM tescritorio INTO vcodigo;
            NEW.bdcodesc = vcodigo;
         END
    END
END
^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER trigger vfin_base_tescpardesp_bi0 for vfin_base_tescpardesp
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodesc IS NULL) OR (NEW.bdcodesc = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodesc)),1) FROM tescritorio INTO vcodigo;
        NEW.bdcodesc = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodesc FROM tescritorio WHERE bdcodesc = NEW.bdcodesc INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodesc)),1) FROM tescritorio INTO vcodigo;
            NEW.bdcodesc = vcodigo;
         END
    END
END 
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_base_tescparger_bi0 FOR vfin_base_tescparger
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodesc IS NULL) OR (NEW.bdcodesc = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodesc)),1) FROM tescritorio INTO vcodigo;
        NEW.bdcodesc = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodesc FROM tescritorio WHERE bdcodesc = NEW.bdcodesc INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodesc)),1) FROM tescritorio INTO vcodigo;
            NEW.bdcodesc = vcodigo;
         END
    END
END
^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_base_ttabsitcli_bi0 FOR vfin_base_ttabsitcli
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdcodsitcli IS NULL) OR (NEW.bdcodsitcli = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodsitcli) + 1), 1) FROM vfin_base_ttabsitcli  INTO vCodigo;
      NEW.bdcodsitcli = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdCODSITCLI FROM vfin_base_ttabsitcli WHERE bdCODSITCLI = NEW.bdcodsitcli INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdCODSITCLI) + 1), 1) FROM vfin_base_ttabsitcli  INTO vCodigo;
           NEW.bdcodsitcli = vCodigo;
         END
    END
END
^

SET TERM ; ^



SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_base_tcliente_bi0 FOR vfin_base_tcliente
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vCodCli INTEGER;
  DECLARE VARIABLE vCodEmp INTEGER;
  DECLARE VARIABLE vControle INTEGER;
  DECLARE VARIABLE vControleCliente INTEGER;
  DECLARE VARIABLE vCNPJEmp VARCHAR(18);
BEGIN
  /* Trigger text */
  vcodigo = 0;
  if (coalesce(NEW.bdcodcli, 0) = 0) then
  begin
    SELECT first 1 bdcodcli FROM vfin_base_tcliente order by bdcodcli desc into :vcodigo;
    NEW.bdcodcli = coalesce(vcodigo, 0) + 1;
  end
  else
  begin
     SELECT bdcodcli FROM vfin_base_tcliente WHERE bdcodcli = NEW.bdcodcli INTO vcodigo;
    if (vcodigo > 0) then
    begin
    SELECT first 1 bdcodcli FROM vfin_base_tcliente order by bdcodcli desc into :vcodigo;
      NEW.bdcodcli = coalesce(vcodigo, 0) + 1;
    end
  end
   /*Adilson Hasckel: sol. 14103 em 15/04/2016 - buscar corretamente o código do cliente que foi lançado. Pode ocorrer de ser digitado um código para inserção
    porém já existe na empresa e então é inserido outro código*/
  rdb$set_context('USER_SESSION', 'W_CodCli_Atual', NEW.bdcodcli);
END^

SET TERM ; ^



SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_base_tcliente_ref_bi0 FOR vfin_base_tcliente_ref
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodcli IS NULL) OR (NEW.bdcodcli = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodcli)),1) FROM vfin_base_tcliente INTO vcodigo;
        NEW.bdcodcli = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodcli FROM vfin_base_tcliente WHERE bdcodcli = NEW.bdcodcli INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodcli)),1) FROM vfin_base_tcliente INTO vcodigo;
            NEW.bdcodcli = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER VFIN_BASE_TCLIENTEHIST_BI0 FOR VFIN_BASE_TCLIENTEHIST
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
--  vcodigo = 0;
--  IF ((NEW.bdcodcli IS NULL) OR (NEW.bdcodcli = 0)) THEN
--  BEGIN
--    SELECT COALESCE(MAX(bdcodcli),1) FROM vfin_base_tcliente INTO vcodigo;
--    NEW.bdcodcli = vcodigo;
--  END
--  ELSE
--  BEGIN
--    SELECT bdcodcli FROM vfin_base_tcliente WHERE bdcodcli = NEW.bdcodcli INTO vcodigo;
--
--    IF (vcodigo = 0) THEN
--    BEGIN
--      SELECT COALESCE(MAX(bdcodcli),1) FROM vfin_base_tcliente INTO vcodigo;
--      NEW.bdcodcli = vcodigo;
--    END
--  END
  vcodigo = 0;
  IF (coalesce(NEW.bdcodcli, 0) <> 0) THEN
     SELECT bdcodcli FROM vfin_base_tcliente WHERE bdcodcli = NEW.bdcodcli INTO vcodigo;

  IF (vcodigo = 0) THEN
  BEGIN
    SELECT first 1 bdcodcli FROM vfin_base_tcliente order by bdcodcli desc into :vcodigo;
    NEW.bdcodcli = vcodigo;
END
END
^

SET TERM ; ^



SET TERM ^ ;

CREATE OR ALTER TRIGGER VFIN_ESC_TRPSEMITIDO_BD0 FOR VFIN_ESC_TRPSEMITIDO
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  UPDATE VFIN_ESC_TSERVICOFATURADO SET BDCHAVERPS = NULL
  WHERE BDCODESC = OLD.BDCODESC AND BDCHAVERPS = OLD.BDCHAVERPS;

  UPDATE VFIN_ESC_TNFSE SET BDCHAVERPS = NULL
  WHERE BDCODESC = OLD.BDCODESC AND BDCHAVERPS = OLD.BDCHAVERPS;
END
^

SET TERM ; ^



SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_base_tclicontato_bi0 FOR vfin_base_tclicontato
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodcli IS NULL) OR (NEW.bdcodcli = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodcli)),1) FROM vfin_base_tcliente INTO vcodigo;
        NEW.bdcodcli = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodcli FROM vfin_base_tcliente WHERE bdcodcli = NEW.bdcodcli INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodcli)),1) FROM vfin_base_tcliente INTO vcodigo;
            NEW.bdcodcli = vcodigo;
         END
    END
END
^

SET TERM ; ^



SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_base_tclienderecamento_bi0 FOR vfin_base_tclienderecamento
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodcli IS NULL) OR (NEW.bdcodcli = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodcli)),1) FROM vfin_base_tcliente INTO vcodigo;
        NEW.bdcodcli = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodcli FROM vfin_base_tcliente WHERE bdcodcli = NEW.bdcodcli INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodcli)),1) FROM vfin_base_tcliente INTO vcodigo;
            NEW.bdcodcli = vcodigo;
         END
    END
END
^

SET TERM ; ^




SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_base_tclienqfed_bi0 FOR vfin_base_tclienqfed
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodcli IS NULL) OR (NEW.bdcodcli = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodcli)),1) FROM vfin_base_tcliente INTO vcodigo;
        NEW.bdcodcli = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodcli FROM vfin_base_tcliente WHERE bdcodcli = NEW.bdcodcli INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodcli)),1) FROM vfin_base_tcliente INTO vcodigo;
            NEW.bdcodcli = vcodigo;
         END
    END
END
^

SET TERM ; ^



SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_base_tclifininfor_bi0 FOR vfin_base_tclifininfor
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodcli IS NULL) OR (NEW.bdcodcli = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodcli)),1) FROM vfin_base_tcliente INTO vcodigo;
        NEW.bdcodcli = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodcli FROM vfin_base_tcliente WHERE bdcodcli = NEW.bdcodcli INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodcli)),1) FROM vfin_base_tcliente INTO vcodigo;
            NEW.bdcodcli = vcodigo;
         END
    END
END
^

SET TERM ; ^



SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_base_tcliimposto_bi0 FOR vfin_base_tcliimposto
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodcli IS NULL) OR (NEW.bdcodcli = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodcli)),1) FROM vfin_base_tcliente INTO vcodigo;
        NEW.bdcodcli = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodcli FROM vfin_base_tcliente WHERE bdcodcli = NEW.bdcodcli INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodcli)),1) FROM vfin_base_tcliente INTO vcodigo;
            NEW.bdcodcli = vcodigo;
         END
    END
END
^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tcontasban_bi0 FOR vfin_esc_tcontasban
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdchavectaban IS NULL) OR (NEW.bdchavectaban = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchavectaban) + 1), 1) FROM vfin_esc_tcontasban  INTO vCodigo;
      NEW.bdchavectaban = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdchavectaban FROM vfin_esc_tcontasban WHERE bdchavectaban = NEW.bdchavectaban INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchavectaban) + 1), 1) FROM vfin_esc_tcontasban  INTO vCodigo;
           NEW.bdchavectaban = vCodigo;
         END
    END
END
^

SET TERM ; ^



SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_base_tmensagens_bi0 FOR vfin_base_tmensagens
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdcodmsg IS NULL) OR (NEW.bdcodmsg = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodmsg) + 1), 1) FROM VFIN_BASE_TMENSAGENS  INTO vCodigo;
      NEW.bdcodmsg = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodmsg FROM VFIN_BASE_TMENSAGENS WHERE bdcodmsg = NEW.bdcodmsg INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodmsg) + 1), 1) FROM VFIN_BASE_TMENSAGENS  INTO vCodigo;
           NEW.bdcodmsg = vCodigo;
         END
    END
END
^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tcontrato_bi0 FOR vfin_esc_tcontrato
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodcontr IS NULL) OR (NEW.bdcodcontr = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodcontr)+1),1) FROM VFIN_ESC_TCONTRATO WHERE bdcodesc = NEW.bdcodesc AND bdcodcli = NEW.bdcodcli INTO vcodigo;
        NEW.bdcodcontr = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodcontr FROM VFIN_ESC_TCONTRATO WHERE bdcodcontr = NEW.bdcodcontr AND bdcodesc = NEW.bdcodesc AND bdcodcli = NEW.bdcodcli INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodcontr)+1),1) FROM VFIN_ESC_TCONTRATO WHERE bdcodesc = NEW.bdcodesc AND bdcodcli = NEW.bdcodcli INTO vcodigo;
           NEW.bdcodcontr = vcodigo;
         END
    END
END
^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tservparamcontrato_bi0 FOR vfin_esc_tservparamcontrato
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcodcontr INTEGER;
  DECLARE VARIABLE vchavefaixa INTEGER;
BEGIN
  vchavefaixa = 0;
  IF ((NEW.bdchavefaixa IS NULL) OR (NEW.bdchavefaixa = 0)) THEN
    BEGIN
      IF ((NEW.bdcodcontr IS NULL) OR (NEW.bdcodcontr = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdcodcontr)), 1) FROM vfin_esc_tcontrato WHERE (bdcodesc = NEW.bdcodesc) AND (bdcodcli = NEW.bdcodcli) INTO vcodcontr;
          NEW.bdcodcontr = vcodcontr;
        END

       SELECT COALESCE((MAX(bdchavefaixa)+1), 1) FROM vfin_esc_tservparamcontrato
       WHERE (bdcodesc = NEW.bdcodesc) AND (bdcodcli = NEW.bdcodcli) AND (bdcodcontr = NEW.bdcodcontr) INTO vchavefaixa;

       NEW.bdchavefaixa = vchavefaixa;
    END
  ELSE
    BEGIN
       IF ((NEW.bdcodcontr IS NULL) OR (NEW.bdcodcontr = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodcontr)), 1) FROM vfin_esc_tcontrato WHERE (bdcodesc = NEW.bdcodesc) AND (bdcodcli = NEW.bdcodcli) INTO vcodcontr;
           NEW.bdcodcontr = vcodcontr;
         END

       SELECT bdchavefaixa FROM vfin_esc_tservparamcontrato
       WHERE (bdchavefaixa = NEW.bdchavefaixa) AND (bdcodesc = NEW.bdcodesc) AND (bdcodcli = NEW.bdcodcli) AND (bdcodcontr = NEW.bdcodcontr) INTO vchavefaixa;

       IF (vchavefaixa > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchavefaixa)+1), 1) FROM vfin_esc_tservparamcontrato WHERE (bdcodesc = NEW.bdcodesc) AND (bdcodcli = NEW.bdcodcli) AND (bdcodcontr = NEW.bdcodcontr) INTO vchavefaixa;
           NEW.bdchavefaixa = vchavefaixa;
         END

    END
END
^

SET TERM ; ^


SET TERM ^ ;



CREATE OR ALTER TRIGGER VFIN_ESC_TSERVPARAMVALOR_BI0 FOR VFIN_ESC_TSERVPARAMVALOR
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcodcontr INTEGER;
  DECLARE VARIABLE vchavefaixa INTEGER;
BEGIN
  vchavefaixa = 0;
  IF ((NEW.bdchavefaixa IS NULL) OR (NEW.bdchavefaixa = 0)) THEN
    BEGIN
      IF ((NEW.bdcodcontr IS NULL) OR (NEW.bdcodcontr = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdcodcontr)), 1) FROM vfin_esc_tcontrato WHERE (bdcodesc = NEW.bdcodesc) AND (bdcodcli = NEW.bdcodcli) INTO vcodcontr;
          NEW.bdcodcontr = vcodcontr;
        END

       SELECT COALESCE((MAX(bdchavefaixa)), 1) FROM vfin_esc_tservparamcontrato
       WHERE (bdcodesc = NEW.bdcodesc) AND (bdcodcli = NEW.bdcodcli) AND (bdcodcontr = NEW.bdcodcontr) INTO vchavefaixa;
       NEW.bdchavefaixa = vchavefaixa;
    END
  ELSE
    BEGIN
       IF ((NEW.bdcodcontr IS NULL) OR (NEW.bdcodcontr = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodcontr)), 1) FROM vfin_esc_tcontrato WHERE (bdcodesc = NEW.bdcodesc) AND (bdcodcli = NEW.bdcodcli) INTO vcodcontr;
           NEW.bdcodcontr = vcodcontr;
         END

       /*select bdchavefaixa from vfin_esc_tservparamcontrato
       where (bdchavefaixa = new.bdchavefaixa) and (bdcodesc = NEW.bdcodesc) and (bdcodcli = NEW.bdcodcli) and (bdcodcontr = new.bdcodcontr) into vchavefaixa;

       if (vchavefaixa > 0) then
         begin
           select coalesce(max(bdchavefaixa), 1) from vfin_esc_tservparamcontrato where (bdcodesc = new.bdcodesc) and (bdcodcli = new.bdcodcli) and (bdcodcontr = new.bdcodcontr) into vchavefaixa;
           NEW.bdchavefaixa = vchavefaixa;
         end
       */
    END
END
^
SET TERM ; ^


SET TERM ^ ;



CREATE OR ALTER TRIGGER VFIN_ESC_TCHEQUERECEBIDO_BI0 FOR VFIN_ESC_TCHEQUERECEBIDO
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
   vcodigo = 0;
   IF ((NEW.bdcodcheque IS NULL) OR (NEW.bdcodcheque = 0))  THEN
      BEGIN
         SELECT COALESCE((MAX(bdcodcheque)+1),1) FROM vfin_esc_tchequerecebido WHERE bdcodesc = NEW.bdcodesc INTO vcodigo;
         NEW.bdcodcheque = vcodigo;
      END
   ELSE
      BEGIN
         SELECT bdcodcheque FROM vfin_esc_tchequerecebido WHERE (bdcodcheque = NEW.bdcodcheque) AND (bdcodesc = NEW.bdcodesc)  INTO vcodigo;
         IF (vcodigo > 0) THEN
            BEGIN
               SELECT COALESCE((MAX(bdcodcheque)+1),1) FROM vfin_esc_tchequerecebido WHERE bdcodesc = NEW.bdcodesc INTO vcodigo;
               NEW.bdcodcheque = vcodigo;
            END
      END
END
^


SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tservicofixo_bi0 FOR vfin_esc_tservicofixo
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vordemserfix INTEGER;
  DECLARE VARIABLE vchaveserfix INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemserfix IS NULL) OR (NEW.bdordemserfix = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordemserfix)+1), 1) FROM vfin_esc_tservicofixo WHERE (bdcodcli = NEW.bdcodcli) AND (bdcodesc = NEW.bdcodesc)
                                                                                   AND (bdchaveserfix = NEW.bdchaveserfix) INTO vordemserfix;
      NEW.bdordemserfix = vordemserfix;

      IF ((NEW.bdchaveserfix IS NULL) OR (NEW.bdchaveserfix = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVESERFIX)), 1) FROM vfin_esc_tcabservicofixo WHERE (bdcodcli = NEW.bdcodcli) AND (bdcodesc = NEW.bdcodesc)
                                                                                 INTO vchaveserfix;
          NEW.bdchaveserfix = vchaveserfix;
        END
    END
  ELSE
    BEGIN
       SELECT BDORDEMSERFIX FROM vfin_esc_tservicofixo WHERE (BDORDEMSERFIX = NEW.bdordemserfix) AND (bdchaveserfix = NEW.bdchaveserfix)
                                                             AND (bdcodcli = NEW.bdcodcli) AND (bdcodesc = NEW.bdcodesc) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEMSERFIX)+1), 1) FROM vfin_esc_tservicofixo WHERE (bdchaveserfix = NEW.bdchaveserfix) AND (bdcodcli = NEW.bdcodcli)
                                                                                        AND (bdcodesc = NEW.bdcodesc) INTO vordemserfix;
           NEW.bdordemserfix = vordemserfix;
         END

       IF ((NEW.bdchaveserfix IS NULL) OR (NEW.bdchaveserfix = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVESERFIX)), 1) FROM vfin_esc_tcabservicofixo WHERE (bdcodcli = NEW.bdcodcli) AND (bdcodesc = NEW.bdcodesc)
                                                                                         INTO vchaveserfix;
           NEW.bdchaveserfix = vchaveserfix;
         END
    END
END
^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tservicofixo_aiu0 FOR vfin_esc_tservicofixo
ACTIVE AFTER INSERT OR UPDATE OR DELETE POSITION 0
AS
  DECLARE VARIABLE vvalortotserfix NUMERIC(15,4);
  DECLARE VARIABLE vcodcli INTEGER;
  DECLARE VARIABLE vcodesc INTEGER;
  DECLARE VARIABLE vchaveserfix INTEGER;
BEGIN
  IF (NEW.bdcodcli IS NULL) THEN
     vcodcli = OLD.bdcodcli;
  ELSE
     vcodcli = NEW.bdcodcli;

  IF (NEW.bdcodesc IS NULL) THEN
     vcodesc = OLD.bdcodesc;
  ELSE
     vcodesc = NEW.bdcodesc;

  IF (NEW.bdchaveserfix IS NULL) THEN
     vchaveserfix = OLD.bdchaveserfix;
  ELSE
     vchaveserfix = NEW.bdchaveserfix;

  /*if (old.bdcodcli is not null) then
     vcodcli = old.bdcodcli;
  else
     vcodcli = new.bdcodcli;

  if (old.bdcodesc is not null) then
     vcodesc = old.bdcodesc;
  else
     vcodesc = new.bdcodesc;

  if (old.bdcodcontr is not null) then
     vcodcontr = old.bdcodcontr;
  else
     vcodcontr = new.bdcodcontr;

  if (old.bdchaveserfix is not null) then
     vchaveserfix = old.bdchaveserfix;
  else
     vchaveserfix = new.bdchaveserfix;*/


  /*select sum(coalesce(BDVLRTOTSERFIX, 0)) from VFIN_ESC_TSERVICOFIXO
  where (bdcodcli = :vcodcli) and (bdcodesc = :vcodesc) and (bdcodcontr = :vcodcontr) and (bdchaveserfix = :vchaveserfix)
  into vVALORTOTSERFIX;*/

  SELECT SUM(CASE WHEN (UPPER(ser.bddesconto) = 'TRUE') THEN COALESCE(BDVLRTOTSERFIX, 0) * -1 ELSE COALESCE(BDVLRTOTSERFIX, 0) END)
  FROM VFIN_ESC_TSERVICOFIXO serfix
  JOIN vct_base_servico ser ON ser.bdcodobrser = serfix.bdcodobrser
  WHERE (bdcodcli = :vcodcli) AND (bdcodesc = :vcodesc) AND (bdchaveserfix = :vchaveserfix)
  INTO vVALORTOTSERFIX;

  UPDATE vfin_esc_tcabservicofixo SET BDVALORTOTSERFIX = :vVALORTOTSERFIX
  WHERE (bdcodcli = :vcodcli) AND (bdcodesc = :vcodesc) AND (bdchaveserfix = :vchaveserfix);


  --somente na exclusão de acordo, decorrente do cascade em BDCHAVEACOR, excluir cabeçalho caso não tenha mais serviços fixos
  --Leonardo Pereira - 22/08/2018 - 87669 - Serviços originados do tarefas excluir cabeçalho se não houver mais serviços
  IF ((OLD.bdcodesc IS NOT NULL) AND (NEW.bdcodesc IS NULL)) THEN
    BEGIN
      IF ((OLD.bdchaveacor IS NOT NULL) or ((OLD.bdcodemp IS NOT NULL) and (OLD.bdcodst IS NOT NULL))) THEN
         BEGIN
          DELETE FROM vfin_esc_tcabservicofixo cab
          WHERE
          bdcodcli = OLD.bdcodcli AND
          bdcodesc = OLD.bdcodesc AND
          bdchaveserfix = OLD.bdchaveserfix AND
          NOT EXISTS
            (
               SELECT bdordemserfix FROM vfin_esc_tservicofixo ser
               WHERE ser.bdcodcli = cab.bdcodcli AND
                     ser.bdcodesc = cab.bdcodesc AND
                     ser.bdchaveserfix = cab.bdchaveserfix
            );
    END


      -- Excluir lançamento geral caso não tenha mais serviços fixos vinculados. Morgana.
      IF (OLD.bdchaveger IS NOT NULL) THEN
         BEGIN
           DELETE FROM VFIN_ESC_TSERVICOFIXOGER ger
           WHERE ger.bdchaveger = OLD.bdchaveger AND
           NOT EXISTS (
                       SELECT * FROM vfin_esc_tservicofixo ser
                       WHERE ser.bdchaveger = OLD.bdchaveger
                       );

       -- Sol: 23103 Morgana. 17/05/2018. Excluir o cabeçalho caso não tenha mais serviços vinculados.
           DELETE FROM vfin_esc_tcabservicofixo cab
           WHERE
           bdcodcli = OLD.bdcodcli AND
           bdcodesc = OLD.bdcodesc AND
           bdchaveserfix = OLD.bdchaveserfix AND
           NOT EXISTS
             (
                SELECT bdordemserfix FROM vfin_esc_tservicofixo ser
                WHERE ser.bdcodcli = cab.bdcodcli AND
                      ser.bdcodesc = cab.bdcodesc AND
                      ser.bdchaveserfix = cab.bdchaveserfix
             );
         END
    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE or ALTER trigger vfin_esc_tservicofixo_ref_bi0 for vfin_esc_tservicofixo_ref
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchaveref INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdchaveref IS NULL) OR (NEW.bdchaveref = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchaveref)+1), 1) FROM vfin_esc_tservicofixo_ref WHERE (bdcodcli = NEW.bdcodcli) AND (bdcodesc = NEW.bdcodesc)
                                                                                   AND (bdchaveserfix = NEW.bdchaveserfix) AND (bdordemserfix = NEW.bdordemserfix) INTO vchaveref;
      NEW.bdchaveref = vchaveref;
    END
  ELSE
    BEGIN
       SELECT bdchaveref FROM vfin_esc_tservicofixo_ref WHERE (bdcodcli = NEW.bdcodcli) AND (bdcodesc = NEW.bdcodesc) AND
                                                              (bdchaveserfix = NEW.bdchaveserfix) AND (bdordemserfix = NEW.bdordemserfix) AND
                                                              (bdchaveref = NEW.bdchaveref) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchaveref)+1), 1) FROM vfin_esc_tservicofixo_ref WHERE (bdcodcli = NEW.bdcodcli) AND (bdcodesc = NEW.bdcodesc) AND
                                                                                        (bdchaveserfix = NEW.bdchaveserfix) AND (bdordemserfix = NEW.bdordemserfix) INTO vchaveref;
           NEW.bdchaveref = vchaveref;
         END
    END
END^

CREATE OR ALTER TRIGGER VFIN_ESC_TSERVICOFIXO_BD0 FOR VFIN_ESC_TSERVICOFIXO
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  IF (OLD.BDCODEMP IS NOT NULL AND OLD.BDCODST IS NOT NULL) THEN
  BEGIN
    IF ((SELECT FIRST 1 BDCODEMP FROM VCT_EMPRESA_TSOLICITATAREFA WHERE BDCODEMP = OLD.BDCODEMP AND BDCODST = OLD.BDCODST) IS NOT NULL) THEN
    BEGIN
      EXCEPTION EX_CUSTOM 'ESSE SERVIÇO PARA FATURAMENTO NÃO PODE SER EXCLUÍDO, PORQUE ESTÁ VINCULADO À TAREFA ' || OLD.BDCODST||' DA EMPRESA ' || OLD.BDCODEMP;
    END
  END
END^

CREATE OR ALTER TRIGGER VFIN_ESC_TORIGEMSERFAT_BD0 FOR VFIN_ESC_TORIGEMSERFAT
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  IF (OLD.BDCODEMP IS NOT NULL AND OLD.BDCODST IS NOT NULL) THEN
  BEGIN
    IF ((SELECT FIRST 1 BDCODEMP FROM VFIN_ESC_TORIGEMSERFAT WHERE BDCODEMP = OLD.BDCODEMP AND BDCODST = OLD.BDCODST) IS NOT NULL) THEN
    BEGIN
      EXCEPTION EX_CUSTOM 'ESSE SERVIÇO PARA FATURAMENTO NÃO PODE SER EXCLUÍDO, PORQUE ESTÁ VINCULADO À TAREFA ' || OLD.BDCODST||' DA EMPRESA ' || OLD.BDCODEMP;
    END
  END
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tservicofixoger_bi0 FOR vfin_esc_tservicofixoger
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcodusu INTEGER;
BEGIN
  -- GRAVA OS CAMPOS AUTOMATICO SE NÃO TIVER SIDO INFORMADO VALORES--
  IF (NEW.bdcodusu IS NULL) THEN
    BEGIN
      SELECT bdcodusu FROM vw_variaveis_sessao_banco INTO vcodusu;
      NEW.bdcodusu = vcodusu;
    END
  IF (NEW.bddatager IS NULL) THEN
     NEW.bddatager = CURRENT_DATE;
  IF (NEW.bdhorager IS NULL) THEN
     NEW.bdhorager = CURRENT_TIME;
END
^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tfatura_bi0 FOR vfin_esc_tfatura
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
   -- GRAVA OS CAMPOS AUTOMATICO --
  NEW.bdrefvenc = CAST( SUBSTRING(CAST(NEW.bddatavenc AS VARCHAR(10)) FROM 1 FOR 4) || SUBSTRING(CAST(NEW.bddatavenc AS VARCHAR(10)) FROM 6 FOR 2) AS INTEGER);
END
^

SET TERM ; ^



SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_base_tlimitededret_bi0 FOR vfin_base_tlimitededret
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcoddedret IS NULL) OR (NEW.bdcoddedret = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcoddedret)+1),1) FROM VFIN_BASE_TLIMITEDEDRET INTO vcodigo;
       NEW.bdcoddedret = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcoddedret FROM VFIN_BASE_TLIMITEDEDRET WHERE bdcoddedret = NEW.bdcoddedret INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcoddedret)+1),1) FROM VFIN_BASE_TLIMITEDEDRET INTO vcodigo;
            NEW.bdcoddedret = vcodigo;
         END
    END
END
^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_trecfatura_aiud0 FOR vfin_esc_trecebimentofatura
ACTIVE AFTER INSERT OR UPDATE OR DELETE POSITION 0
AS
  DECLARE VARIABLE vcodcli INTEGER;
  DECLARE VARIABLE vcodesc INTEGER;
  DECLARE VARIABLE vchavefatura INTEGER;
  DECLARE VARIABLE vTotRec NUMERIC(15,2);
  --declare variable vTotJur numeric(15,2);
  -- declare variable vTotDesc numeric(15,2);
  --declare variable vTotMul numeric(15, 2);
  DECLARE VARIABLE vTotGer NUMERIC(15, 2);
BEGIN
  IF (NEW.bdcodcli IS NULL) THEN
     vcodcli = OLD.bdcodcli;
  ELSE
     vcodcli = NEW.bdcodcli;

  IF (NEW.bdcodesc IS NULL) THEN
     vcodesc = OLD.bdcodesc;
  ELSE
     vcodesc = NEW.bdcodesc;

  IF (NEW.bdchavefatura IS NULL) THEN
     vchavefatura = OLD.bdchavefatura;
  ELSE
     vchavefatura = NEW.bdchavefatura;

  --os totais de multa e juros da tabela de faturas devem ser atualizados ao serem criados os serviços de multa/juros/desconto
  SELECT SUM(COALESCE(BDVALREC, 0)),
         --sum(coalesce(BDJURREC, 0)),
         --sum(coalesce(BDMULTAREC, 0)),
         --sum(coalesce(BDDESCREC, 0)),
         SUM(COALESCE(BDVALREC, 0) + COALESCE(BDJURREC, 0) + COALESCE(BDMULTAREC, 0) - COALESCE(BDDESCREC, 0))
         FROM vfin_esc_trecebimentofatura
         WHERE (bdcodcli = :vcodcli) AND
               (bdcodesc = :vcodesc) AND
               (bdchavefatura = :vchavefatura)
  --into vTotRec, vtotjur, vtotmul, vTotDesc, vtotger;
  INTO vTotRec, vtotger;

  if (DELETING) then
     begin
  --atualizar totais da fatura
  UPDATE vfin_esc_tFatura
  SET BDTOTREC  = :vtotrec,
           BDTOTGER = :vtotger,
           BDTOTPENDENTE = (BDVALORFATURA + COALESCE(BDTOTMUL, 0) + COALESCE(BDTOTJUR, 0) + COALESCE(BDMULPROVCOR, 0) + COALESCE(BDJURPROVCOR, 0) - COALESCE(BDTOTDESC, 0) + COALESCE(BDVLRBOLETO,0)) - COALESCE(:vtotger, 0)
                         + COALESCE(BDTOTMUL, 0) + COALESCE(BDTOTJUR, 0) + COALESCE(BDMULPROVCOR, 0) + COALESCE(BDJURPROVCOR, 0) - COALESCE(BDTOTDESC, 0) 
       WHERE (bdcodcli = :vcodcli) AND
             (bdcodesc = :vcodesc) AND
             (bdchavefatura = :vchavefatura);
     end
  else
    begin
      --atualizar totais da fatura
       UPDATE vfin_esc_tFatura
       SET BDTOTREC  = :vtotrec,
      /*BDTOTJUR  = :vtotjur,
      BDTOTMUL  = :vtotmul,
      BDTOTDESC = :vtotdesc,*/
      BDTOTGER = :vtotger,
      --BDTOTPENDENTE = (case when BDVALORFATURA - coalesce(:vtotrec, 0) > 0 then BDVALORFATURA - coalesce(:vtotrec, 0) else 0 end)
     --      BDTOTPENDENTE = (CASE WHEN (BDVALORFATURA + COALESCE(BDTOTMUL, 0) + COALESCE(BDTOTJUR, 0) + COALESCE(BDMULPROVCOR, 0) + COALESCE(BDJURPROVCOR, 0) - COALESCE(BDTOTDESC, 0)) - COALESCE(:vtotger, 0) > 0 THEN
     --                                (BDVALORFATURA + COALESCE(BDTOTMUL, 0) + COALESCE(BDTOTJUR, 0) + COALESCE(BDMULPROVCOR, 0) + COALESCE(BDJURPROVCOR, 0) - COALESCE(BDTOTDESC, 0)) - COALESCE(:vtotger, 0) ELSE 0 END)
     -- Gilberto - 30/10/2020 - W141189 - Valor Boleto
      BDTOTPENDENTE = (CASE WHEN (BDVALORFATURA + COALESCE(BDTOTMUL, 0) + COALESCE(BDTOTJUR, 0) + COALESCE(BDMULPROVCOR, 0) + COALESCE(BDJURPROVCOR, 0) - COALESCE(BDTOTDESC, 0) + COALESCE(BDVLRBOLETO,0)) - COALESCE(:vtotger, 0) > 0 THEN
                                 (BDVALORFATURA + COALESCE(BDTOTMUL, 0) + COALESCE(BDTOTJUR, 0) + COALESCE(BDMULPROVCOR, 0) + COALESCE(BDJURPROVCOR, 0) - COALESCE(BDTOTDESC, 0) + COALESCE(BDVLRBOLETO,0)) - COALESCE(:vtotger, 0) ELSE 0 END)
  WHERE (bdcodcli = :vcodcli) AND
        (bdcodesc = :vcodesc) AND
        (bdchavefatura = :vchavefatura);
    end


  IF (NEW.bdcodcli IS NULL) THEN --exclusão
     BEGIN
       --Adilson Hasckel - sol. 15757 - exclusão de recebimentos antecipados
       IF (OLD.bdchaverecant > 0) THEN
          BEGIN
            --excluir recebimento de faturas que foram beneficiadas pelo recebimento antecipado gerado a partir do recebimento que está sendo excluído
            DELETE FROM vfin_esc_trecebimentofatura rec
            WHERE BDCODESC = :vcodesc AND
                  BDCODCLI = :vcodcli AND
            EXISTS
                ( SELECT BDCHAVERECANT FROM vfin_esc_trecantecip_dest
                  WHERE BDCODESC = :vCodEsc AND
                        BDCODCLI = :vCodCli AND
                        BDCHAVEFATURA = rec.bdchavefatura AND
                        BDORDEMREC = rec.bdordemrec AND
                        BDCHAVERECANT = OLD.BDCHAVERECANT
                );

            --excluir recebimento antecipado que foi gerado a partir do recebimento a maior (vínculo com o recebimento que está sendo excluído)
            DELETE FROM vfin_esc_trecantecipado
            WHERE BDCODESC = :vCodEsc AND
                  BDCODCLI = :vcodcli AND
                  BDCHAVERECANT = OLD.bdchaverecant;
          END
     END

 --controle saldo recebimento antecipado - exclusão/inserção e ediçãom foi passado para VFIN_ESC_TRECANTECIP_DEST
 /*
 if (new.bdcodcli is null) then --exclusão
    begin
       if (old.bdchaverecantdest > 0) then --ao excluir recebimento da fatura que tenha sido beneficiado por recebimento antecipado repor o valor utilizado no saldo
          begin
            update VFIN_ESC_TRECANTECIPADO
            set bdsaldorecant = coalesce(bdsaldorecant, 0) + old.bdvalrec
            where
            BDCODESC = old.bdcodesc and
            BDCODCLI = old.bdcodcli and
            BDCHAVERECANT = old.bdchaverecantdest;
          end
    end
 else
 if (new.bdchaverecantdest > 0) then --controle saldo
    begin
      if (old.bdvalrec is null) then --inserção
         begin
           update VFIN_ESC_TRECANTECIPADO
           set bdsaldorecant = coalesce(bdsaldorecant, 0) - new.bdvalrec
           where
           BDCODESC = new.bdcodesc and
           BDCODCLI = new.bdcodcli and
           BDCHAVERECANT = new.bdchaverecantdest;
         end
      else
         begin -- edição
           update VFIN_ESC_TRECANTECIPADO
           set bdsaldorecant = coalesce(bdsaldorecant, 0) - old.bdvalrec + new.bdvalrec
           where
           BDCODESC = new.bdcodesc and
           BDCODCLI = new.bdcodcli and
           BDCHAVERECANT = new.bdchaverecantdest;
         end
    end
 */
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER VFIN_ESC_TRECEBFATURAFILE_BI0 FOR VFIN_ESC_TRECEBIMENTOFATURAFILE
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcodigo integer;
begin
  if ((new.bdid is null) or (new.bdid = 0)) then
  begin
    select first 1 bdid from vfin_esc_trecebimentofaturafile
    where bdcodcli = new.bdcodcli
    and bdcodesc = new.bdcodesc
    and bdchavefatura = new.bdchavefatura
    and bdordemrec = new.bdordemrec
    order by bdid desc
    into :vcodigo;
    new.bdid = coalesce(:vcodigo,0)+1;
  end

  update vfin_esc_trecebimentofatura set bdfiles = coalesce(bdfiles,0)+1
  where bdcodcli = new.bdcodcli
  and bdcodesc = new.bdcodesc
  and bdchavefatura = new.bdchavefatura
  and bdordemrec = new.bdordemrec;

-- Gilberto - 30/03/2022 - retirado porque isso só funciona bem com texto e xml
--  if (new.bdarquivo is not null) then
--     new.bdarquivo = zipblob(new.bdarquivo);
end
^
CREATE OR ALTER TRIGGER VFIN_ESC_TRECEBFATURAFILE_AD0 FOR VFIN_ESC_TRECEBIMENTOFATURAFILE
ACTIVE AFTER DELETE POSITION 0
AS
begin
  update vfin_esc_trecebimentofatura set bdfiles = coalesce(bdfiles,0)-1
  where bdcodcli = old.bdcodcli
  and bdcodesc = old.bdcodesc
  and bdchavefatura = old.bdchavefatura
  and bdordemrec = old.bdordemrec;
end
^

CREATE OR ALTER TRIGGER VFIN_ESC_TPAGAMENTOSFILE_BI0 FOR VFIN_ESC_TPAGAMENTOSFILE
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcodigo integer;
begin
  if ((new.bdordempag is null) or (new.bdordempag = 0)) then
  begin
    select first 1 bdordempag from vfin_esc_tpagamentos
    where bdcodesc = new.bdcodesc
    and bdchavectapag = new.bdchavectapag
    order by bdordempag desc
    into :vcodigo;
    new.bdordempag = :vcodigo;
  end

  if ((new.bdid is null) or (new.bdid = 0)) then
  begin
    select first 1 bdid from vfin_esc_tpagamentosfile
    where bdcodesc = new.bdcodesc
    and bdchavectapag = new.bdchavectapag
    and bdordempag = new.bdordempag
    order by bdid desc
    into :vcodigo;
    new.bdid = coalesce(:vcodigo,0)+1;
  end

  update vfin_esc_tpagamentos set bdfiles = coalesce(bdfiles,0)+1
  where bdcodesc = new.bdcodesc
  and bdchavectapag = new.bdchavectapag
  and bdordempag = new.bdordempag;

-- Gilberto - 30/03/2022 - retirado porque isso só funciona bem com texto e xml
--  if (new.bdarquivo is not null) then
--     new.bdarquivo = zipblob(new.bdarquivo);
end
^

CREATE OR ALTER TRIGGER VFIN_ESC_TPAGAMENTOSFILE_AD0 FOR VFIN_ESC_TPAGAMENTOSFILE
ACTIVE AFTER DELETE POSITION 0
AS
begin
  update vfin_esc_tpagamentos set bdfiles = coalesce(bdfiles,0)-1
  where bdcodesc = old.bdcodesc
  and bdchavectapag = old.bdchavectapag
  and bdordempag = old.bdordempag;
end
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_trecfaturaser_aiud0 FOR vfin_esc_trecfaturaservico
ACTIVE AFTER INSERT OR UPDATE OR DELETE POSITION 0
AS
  DECLARE VARIABLE vcodcli INTEGER;
  DECLARE VARIABLE vcodesc INTEGER;
  DECLARE VARIABLE vchavefatura INTEGER;
  DECLARE VARIABLE vOrdemSer INTEGER;
  DECLARE VARIABLE vTotRecSer NUMERIC(15,2);
BEGIN
  IF (NEW.bdcodcli IS NULL) THEN
     vcodcli = OLD.bdcodcli;
  ELSE
     vcodcli = NEW.bdcodcli;

  IF (NEW.bdcodesc IS NULL) THEN
     vcodesc = OLD.bdcodesc;
  ELSE
     vcodesc = NEW.bdcodesc;

  IF (NEW.bdchavefatura IS NULL) THEN
     vchavefatura = OLD.bdchavefatura;
  ELSE
     vchavefatura = NEW.bdchavefatura;

  IF (NEW.bdordemser IS NULL) THEN
     vordemser = OLD.bdordemser;
  ELSE
     vordemser = NEW.bdordemser;

  SELECT SUM(COALESCE(BDVALREC, 0))
         FROM vfin_esc_trecfaturaservico
         WHERE (bdcodcli = :vcodcli) AND
               (bdcodesc = :vcodesc) AND
               (bdchavefatura = :vchavefatura) AND
               (bdordemser = :vordemser)
  INTO vtotrecser;

  UPDATE vfin_esc_tservicofaturado
  SET BDTOTRECSER  = :vtotrecser,
      BDTOTPENDSER = (CASE WHEN BDVLRTOTSER - COALESCE(:vtotrecser, 0) > 0 THEN BDVLRTOTSER - COALESCE(:vtotrecser, 0) ELSE 0 END)
  WHERE (bdcodcli = :vcodcli) AND
        (bdcodesc = :vcodesc) AND
        (bdchavefatura = :vchavefatura) AND
        (bdordemser = :vordemser);
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tservicofaturado_bi0 FOR vfin_esc_tservicofaturado
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vordemser INTEGER;
  DECLARE VARIABLE vchavefatura INTEGER;

BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemser IS NULL) OR (NEW.bdordemser = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordemser)+1), 1) FROM vfin_esc_tservicofaturado WHERE (bdcodesc = NEW.bdcodesc) AND (bdcodcli = NEW.bdcodcli) AND (bdchavefatura = NEW.bdchavefatura) INTO vordemser;
      NEW.bdordemser = vordemser;
      IF ((NEW.bdchavefatura IS NULL) OR (NEW.bdchavefatura = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(bdchavefatura)), 1) FROM vfin_esc_tfatura WHERE (bdcodesc = NEW.bdcodesc) AND (bdcodcli = NEW.bdcodcli) INTO vchavefatura;
          NEW.bdchavefatura = vchavefatura;
        END
    END
  ELSE
    BEGIN
       SELECT bdordemser FROM vfin_esc_tservicofaturado WHERE (bdordemser = NEW.bdordemser) AND (bdchavefatura = NEW.bdchavefatura) AND (bdcodesc = NEW.bdcodesc) AND (bdcodcli = NEW.bdcodcli)
       INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordemser)+1), 1) FROM vfin_esc_tservicofaturado WHERE (bdcodesc = NEW.bdcodesc) AND (bdcodcli = NEW.bdcodcli) AND (bdchavefatura = NEW.bdchavefatura) INTO vordemser;
           NEW.bdordemser = vordemser;
         END
       IF ((NEW.bdchavefatura IS NULL) OR (NEW.bdchavefatura = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchavefatura)), 1) FROM vfin_esc_tfatura WHERE (bdcodesc = NEW.bdcodesc) AND (bdcodcli = NEW.bdcodcli) INTO vchavefatura;
           NEW.bdchavefatura = vchavefatura;
         END
    END
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tservico_gest_bi0 FOR vfin_esc_tservico_gest
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vchave INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)+1),1) FROM vfin_esc_tservico_gest
       WHERE bdcodesc = NEW.bdcodesc
       AND bdcodobrser = NEW.bdcodobrser
       INTO :vchave;
       NEW.bdchave = vchave;
     END
  ELSE
     BEGIN
       SELECT bdchave FROM vfin_esc_tservico_gest
       WHERE bdchave = NEW.bdchave AND bdcodesc = NEW.bdcodesc AND bdcodobrser = NEW.bdcodobrser INTO vchave;

       IF (vchave > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1),1) FROM vfin_esc_tservico_gest WHERE bdcodesc = NEW.bdcodesc AND bdcodobrser = NEW.bdcodobrser INTO vchave;
           NEW.bdchave = vchave;
         END
     END
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tbaixarapidafatura_ad0 FOR vfin_esc_tbaixarapidafatura
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  /*ao excluir um item de baixa rápida da fatura (quando não vier por exclusão por cascade da tabela master VFIN_ESC_TBAIXARAPIDA)
   atualizar o valor ba baixa rápida na tabela de baixa rápida que é por gestor...
  */
  UPDATE vfin_esc_tbaixarapida
  SET BDVALORBAIRAP = COALESCE(BDVALORBAIRAP, 0) - COALESCE(OLD.bdvalrec, 0)
  WHERE BDCODESC = OLD.bdcodesc AND
        BDCODBAIRAP = OLD.bdcodbairap;
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tobrigacao_gest_bi0 FOR vfin_esc_tobrigacao_gest
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vChave INTEGER;
BEGIN
  /* Trigger text */
  vchave = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdchave)+1),1) FROM vfin_esc_tobrigacao_gest
        WHERE bdcodesc = NEW.bdcodesc AND bdcodobrser = NEW.bdcodobrser INTO vChave;
        NEW.bdchave = vchave;
     END
  ELSE
    BEGIN
       SELECT bdchave FROM vfin_esc_tobrigacao_gest WHERE bdchave = NEW.bdchave AND bdcodesc = NEW.bdcodesc AND bdcodobrser = NEW.bdcodobrser INTO vchave;

       IF (vchave > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1),1) FROM vfin_esc_tobrigacao_gest WHERE bdcodesc = NEW.bdcodesc AND bdcodobrser = NEW.bdcodobrser INTO vchave;
           NEW.bdchave = vchave;
         END
    END
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_timposto_gest_bi0 FOR vfin_esc_timposto_gest
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vChave INTEGER;
BEGIN
  /* Trigger text */
  vchave = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdchave)+1),1) FROM vfin_esc_timposto_gest
        WHERE bdcodesc = NEW.bdcodesc AND bdcodimp = NEW.bdcodimp INTO vChave;
        NEW.bdchave = vchave;
     END
  ELSE
    BEGIN
       SELECT bdchave FROM vfin_esc_timposto_gest WHERE bdchave = NEW.bdchave AND bdcodesc = NEW.bdcodesc AND bdcodimp = NEW.bdcodimp INTO vchave;

       IF (vchave > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1),1) FROM vfin_esc_timposto_gest WHERE bdcodesc = NEW.bdcodesc AND bdcodimp = NEW.bdcodimp INTO vchave;
           NEW.bdchave = vchave;
         END
    END
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tservicofixoobs_bi0 FOR vfin_esc_tservicofixoobs
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchaveserfix INTEGER;
  DECLARE VARIABLE vordem INTEGER;
BEGIN
  IF ((NEW.bdchaveserfix IS NULL) OR (NEW.bdchaveserfix = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchaveserfix)), 1) FROM vfin_esc_tcabservicofixo
      WHERE (bdcodesc = NEW.bdcodesc) AND (bdcodcli = NEW.bdcodcli)
      INTO vchaveserfix;
      NEW.bdchaveserfix = vchaveserfix;
    END

   /*se for informado uma ordem que não existe no seriço fixo (tela), buscar nova ordem*/
   SELECT BDORDEMSERFIX FROM vfin_esc_tservicofixo
   WHERE (BDCODESC = NEW.BDCODESC) AND (BDCODCLI = NEW.bdcodcli) AND (bdchaveserfix = NEW.bdchaveserfix) AND (bdordemserfix = NEW.bdordemserfix) INTO vordem;

   IF (vordem IS NULL) THEN
      BEGIN
        /*selecionar a última ordem do serviço fixo vinculado, */
        SELECT COALESCE((MAX(BDORDEMSERFIX)), 1) FROM vfin_esc_tservicofixo
        WHERE (BDCODESC = NEW.BDCODESC) AND (BDCODCLI = NEW.bdcodcli) AND (bdchaveserfix = NEW.bdchaveserfix) INTO vNova_Ordem;
        NEW.bdordemserfix = vNova_ordem;
      END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_base_tparnfse_bi0 FOR vfin_base_tparnfse
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodesc IS NULL) OR (NEW.bdcodesc = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodesc)),1) FROM tescritorio INTO vcodigo;
        NEW.bdcodesc = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodesc FROM tescritorio WHERE bdcodesc = NEW.bdcodesc INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodesc)),1) FROM tescritorio INTO vcodigo;
            NEW.bdcodesc = vcodigo;
         END
    END
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_base_tconfclievent_bi0 FOR vfin_base_tconfclievent
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdcodconfcli IS NULL) OR (NEW.bdcodconfcli = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodconfcli) + 1), 1) FROM vfin_base_tconfclievent  INTO vCodigo;
      NEW.bdcodconfcli = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodconfcli FROM vfin_base_tconfclievent WHERE bdcodconfcli = NEW.bdcodconfcli INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodconfcli) + 1), 1) FROM vfin_base_tconfclievent  INTO vCodigo;
           NEW.bdcodconfcli = vCodigo;
         END
    END
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tvalservico_bi0 FOR vfin_esc_tvalservico
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vchave INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM VCT_TRIBUTARIO_EMPRESA WHERE (bdcodemp = NEW.bdcodemp) INTO vchave;
      NEW.bdchave = vchave;
    END
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tacordo_ad0 FOR vfin_esc_tacordo
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  --excluir recebimentos da fatura, originados pelo acordo
  DELETE FROM VFIN_ESC_TRECEBIMENTOFATURA rec
  WHERE (bdcodcli = OLD.bdcodcli) AND
        (bdcodesc = OLD.bdcodesc) AND
        (UPPER(bdrecacordo) = 'TRUE') AND
        bdchavefatura IN
        (
          SELECT bdchavefatura
          FROM VFIN_ESC_TACORDOFATBENEF
          WHERE bdcodcli = rec.bdcodcli AND
                bdcodesc = rec.bdcodesc AND
                bdchaveacor = OLD.bdchaveacor
         );

  UPDATE VFIN_ESC_TFATURA fat
  SET fat.BDTOTPENDENTE = (SELECT bdvlracorfat
                           FROM VFIN_ESC_TACORDOFATBENEF
                           WHERE bdcodcli = fat.bdcodcli AND
                           bdcodesc = fat.bdcodesc AND
                           bdchaveacor = OLD.bdchaveacor and
                           bdchavefatura = fat.bdchavefatura)
  WHERE fat.BDCODCLI = old.BDCODCLI
  AND fat.BDCODESC = old.BDCODESC
  AND bdchavefatura IN
        (
          SELECT bdchavefatura
          FROM VFIN_ESC_TACORDOFATBENEF
          WHERE bdcodcli = fat.bdcodcli AND
                bdcodesc = fat.bdcodesc AND
                bdchaveacor = OLD.bdchaveacor
         );
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tfaturadel_bi0 FOR vfin_esc_tfaturadel
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vChave INTEGER;
BEGIN
  SELECT COALESCE(MAX(bdchave),0) FROM vfin_esc_tfaturadel INTO vChave;
  NEW.bdchave = vChave +1;
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger vfin_esc_tacordofatbenef_bd0 for vfin_esc_tacordofatbenef
active before delete position 0
AS
begin
  UPDATE VFIN_ESC_TSERVICOFATURADO serfat
  set serfat.BDTOTPENDSER = (select sum(serfix.bdvlrtotserfix) from VFIN_ESC_TSERVICOFIXO serfix
                             inner join VFIN_ESC_TORIGEMSERFAT org on (org.bdcodcli = serfix.bdcodcli and org.bdcodesc = serfix.bdcodesc
                             and org.bdchaveserfix = serfix.bdchaveserfix and org.bdordemserfix = serfix.bdordemserfix)
                             where serfix.bdcodcli = serfat.bdcodcli and serfix.bdcodesc = serfat.bdcodesc and org.bdchavefatura = serfat.bdchavefatura
                             and org.bdordemser = serfat.bdordemser)
  where serfat.bdcodcli = old.bdcodcli
  and serfat.bdcodesc = old.bdcodesc
  and serfat.bdchavefatura = old.bdchavefatura;
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tfatura_ad0 FOR vfin_esc_tfatura
ACTIVE AFTER DELETE POSITION 0
AS
  DECLARE VARIABLE vCodEsc INTEGER;
  DECLARE VARIABLE vChaveRPS INTEGER;
BEGIN
  /*Adilson Hasckel- Controle de exclusão de RPS emitido vinculados aos serviços da fatura excluída!!!!*/
  /*FOR
    SELECT BDCODESC, BDCHAVERPS FROM vfin_esc_trpsemitido rps
      WHERE (bdcodesc = OLD.bdcodesc) AND (bdchaverps IN
        (
          SELECT bdchaverps FROM vfin_esc_tservicofaturado
          WHERE (bdcodesc = OLD.bdcodesc) AND (bdcodcli = OLD.bdcodcli) AND
            (bdchavefatura = OLD.bdchavefatura) AND (bdchaverps > 0) AND (bdchaverps = rps.bdchaverps)
        )
      )
  INTO :vCodEsc, :vChaveRPS DO
   BEGIN
      --UPDATE vfin_esc_tservicofaturado SET BDCHAVERPS = NULL
      --WHERE BDCODESC = OLD.bdcodesc AND
            --BDCODCLI = OLD.bdcodcli AND
            --BDCHAVEFATURA = OLD.bdchavefatura AND BDCHAVERPS = :vchaverps;

      DELETE FROM vfin_esc_trpsemitido WHERE BDCODESC = :vcodesc AND BDCHAVERPS = :vchaverps;
   END*/

   IF (OLD.bdnossonum <> '') THEN
     BEGIN
       INSERT INTO vfin_esc_tfaturadel (bdchave, bdcodesc, bdcodcli, bdreffat, bdserie,
                                        bdnossonum, bddatavenc, bdvalorfatura, bdchavectaban)
                                VALUES (NULL, OLD.bdcodesc, OLD.bdcodcli, OLD.bdreffat, OLD.bdserie,
                                        OLD.bdnossonum, OLD.bddatavenc, OLD.bdvalorfatura, OLD.bdchavectaban);
     END
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tfatura_bd0 FOR vfin_esc_tfatura
ACTIVE BEFORE DELETE POSITION 0
AS
 DECLARE VARIABLE vCodemp INTEGER;
 declare variable vcodpts integer;
BEGIN
  /*Adilson Hasckel - sol. 15952 - ao excluir uma fatura, cancelar as notas fiscais da EF vinculadas*/
 /* SELECT BDCODEMPINTEG FROM TESCRITORIO WHERE bdCODESC = OLD.bdcodesc INTO vCodEmp;*/
 /*Leonardo Pereira - 03/12/2018 - Não ira mais fazer essa exclusão, porque ao excluir a fatura estava deixando a nota em situação cancelada.
  IF (vcodemp > 0) THEN
     BEGIN
       UPDATE vef_emp_tmovser movser
       SET BDCODSITNF = 2
       WHERE BDCODEMP = :vCodEmp AND
       BDCHAVE =
                (
                  SELECT BDCHAVEEF
                  FROM TOL_VFIN_ESC_TFATMOVSER tolfat
                  WHERE bdcodemp = movser.bdcodemp AND
                        bdchaveef = movser.bdchave AND
                        bdcodcli = OLD.bdcodcli AND
                        bdcodesc = OLD.bdcodesc AND
                        bdchavefatura = OLD.bdchavefatura
                );
     END*/

  -- Sol: 96075 Morgana. 07/02/2019. Excluir o documento vinculado a fatura se ainda não estiver baixado, emitido ou gerado.
  -- Sol: 187762 Morgana. 28/09/2023. Colocado dentro de um for pois pode existir mais de um documento com as mesmas chaves da fatura.
  for select coalesce(bdcodpts,0) from VCT_EMPRESA_DOCSGERADOS
  where bdcodcli = old.bdcodcli
  and bdcodesc = old.bdcodesc
  and bdchavefatura = old.bdchavefatura
  into :vCodPts
  do
  begin
  if (:vCodPts = 0) then
     begin
       delete from VCT_EMPRESA_DOCSGERADOS
       where bdcodcli = old.bdcodcli
       and bdcodesc = old.bdcodesc
       and bdchavefatura = old.bdchavefatura
       and bdcodpts is null
       and bdcodipts is null;
     end
  else
    begin
      -- Remover o vínculo para poder excluir a fatura.
      update VCT_EMPRESA_DOCSGERADOS
      set bdcodcli = null, bdcodesc = null, bdchavefatura = null
      where bdcodcli = old.bdcodcli
      and bdcodesc = old.bdcodesc
      and bdchavefatura = old.bdchavefatura;
    end
  end

  if ((old.bdnumparc is not null) or (old.bdnumparc > 0)) then
     begin
       delete from VFIN_ESC_TPARCELAFATURA where bdcodesc = old.bdcodesc and bdcodcli = old.bdcodcli and bdchavefatura = old.bdchavefatura;
     end
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER VFIN_ESC_TFATURA_BU0 FOR VFIN_ESC_TFATURA
ACTIVE BEFORE UPDATE POSITION 0
AS
  declare variable vnossonum varchar(50);
  declare variable vnumrec varchar(40);
begin
  select coalesce(fat.bdnossonum,''), coalesce(fat.bdnumrec,'')
  from VFIN_ESC_TFATURA fat
  where fat.bdcodcli = new.bdcodcli
  and fat.bdcodesc = new.bdcodesc
  and fat.bdchavefatura = new.bdchavefatura
  into :vnossonum, :vnumrec;

  if ((:vnossonum = new.bdnossonum) and (:vnumrec = new.bdnumrec)) then
     begin
       delete from VFIN_ESC_TPDF_EMAIL pdf where pdf.bdcodcli = new.bdcodcli and pdf.bdcodesc = new.bdcodesc and pdf.bdchavefatura = new.bdchavefatura;
     end
end^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vct_base_servico_ref_bi0 FOR vct_base_servico_ref
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodobrser IS NULL) OR (NEW.bdcodobrser = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodobrser)),1) FROM VCT_BASE_SERVICO INTO vcodigo;
        NEW.bdcodobrser = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodobrser FROM VCT_BASE_SERVICO WHERE bdcodobrser = NEW.bdcodobrser INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodobrser)),1) FROM VCT_BASE_SERVICO INTO vcodigo;
            NEW.bdcodobrser = vcodigo;
         END
    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE or ALTER trigger vfin_esc_tservicofaturado_ad0 for vfin_esc_tservicofaturado
active after delete position 0
AS
  DECLARE VARIABLE vChaveRPS INTEGER;
begin
  select first 1 bdchaverps from VFIN_ESC_TSERVICOFATURADO where bdcodesc = old.bdcodesc and bdchaverps = old.bdchaverps into :vchaverps;

  if (:vchaverps is null) then
     begin
       DELETE FROM vfin_esc_trpsemitido WHERE BDCODESC = old.bdcodesc AND BDCHAVERPS = old.bdchaverps;
     end
end^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER TAVISOS_BI0 FOR TAVISOS
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF ((NEW.bdid IS NULL) OR (NEW.bdid = 0)) THEN
  BEGIN
    NEW.bdid = (SELECT COALESCE(MAX(bdid), 0)+1 FROM tavisos);
  END
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER tol_vfin_esc_tserfat_ad0 FOR tol_vfin_esc_tserfat
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
   /* Trigger text */
  if (not exists(select first 1 bdchavelan from tol_vfin_esc_tserfat x where x.bdcodemp = old.bdcodemp and x.bdchavelan = OLD.bdchavelan)) then
  begin
    EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodemp,OLD.bdchavelan);
  end
END^

SET TERM ; ^

SET TERM ^ ;

CREATE or alter trigger tol_vfin_esc_tcontaspagdesp_ad0 for tol_vfin_esc_tcontaspagardesp
active after delete position 0
AS
begin
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodemp,OLD.bdchave);
end^

SET TERM ; ^

SET TERM ^ ;

CREATE or alter trigger tol_vfin_esc_tpagdesp_ad0 for tol_vfin_esc_tpagdesp
active after delete position 0
AS
begin
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodemp,OLD.bdchave);
end^

SET TERM ; ^

SET TERM ^ ;

CREATE or alter trigger tol_vfin_esc_tlancbancario_ad0 for tol_vfin_esc_tlancbancario
active after delete position 0
AS
begin
  /* Trigger text */
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodemp,OLD.bdchave);
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tpdf_email_bi0 FOR vfin_esc_tpdf_email
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vChave INTEGER;
BEGIN
  /* Trigger text */
  vChave = 0;

  if (new.bdcodrel = 3) then
     begin
       select bdchave from VFIN_ESC_TPDF_EMAIL where bdcodcli = new.bdcodcli and bdcodesc = new.bdcodesc and
       bdchavefatura = new.bdchavefatura and bdcodrel = new.bdcodrel and bdnumlote = new.bdnumlote and bdchaverps = new.bdchaverps into :vChave;
     end
  else
    begin
      select bdchave from VFIN_ESC_TPDF_EMAIL where bdcodcli = new.bdcodcli and bdcodesc = new.bdcodesc and
       bdchavefatura = new.bdchavefatura and bdcodrel = new.bdcodrel into :vChave;
    end

  if (vchave > 0) then
     begin
       NEW.bdchave = vChave;
     end
  else
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdchave)+1),1) FROM VFIN_ESC_TPDF_EMAIL INTO vChave;
       NEW.bdchave = vChave;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM VFIN_ESC_TPDF_EMAIL WHERE bdchave = NEW.bdchave INTO vChave;

       IF (vChave > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdchave)+1),1) FROM VFIN_ESC_TPDF_EMAIL INTO vChave;
            NEW.bdchave = vChave;
         END
    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER VFIN_ESC_TCONTASBAN_AI0 FOR VFIN_ESC_TCONTASBAN
ACTIVE AFTER INSERT POSITION 0
AS
BEGIN
 /*Adilson Hasckel: sol. 14543 - 19/05/2016 - criar automaticamente as contas bancárias na configuração de Online do Financeiro. */
  EXECUTE PROCEDURE vfin_insert_contaban_online(NEW.bdchavectaban);
END
^

CREATE OR ALTER TRIGGER vfin_base_tcliente_ai0 FOR vfin_base_tcliente
ACTIVE AFTER INSERT POSITION 0
AS
BEGIN
   /*Adilson Hasckel: sol. 15117 - 14/07/2016 - criar automaticamente os clientes fixos na configuração de Online do Financeiro. */
-- Gilberto - 17/01/2023 - Gera lentidão no cadastro de clientes, segundo Morgana não é mais necessário esse processo nesse momento, caso precise, estudaremos uma forma de NÃO fazer aqui, para não voltar lentidão a no cadastro
--  IF (NEW.bdcodtipocli <> 3) THEN
--    EXECUTE PROCEDURE VFIN_INSERT_CLIENTE_ONLINE (NEW.bdcodcli);

    /*Sol: 18296 Morgana. 26/04/2017. Gerar uma situação financeira (ativo) ao inserir um cliente.*/
  IF (NEW.bdcodtipocli <> 3) THEN -- #151702 - Antony Rairon (14/06/2021) - Não gerar a situação padrão se for um cliente eventual
  INSERT INTO VFIN_BASE_TSITCLIENTE (bdcodcli, bdchavesitcli, bdcodsitcli, bddatasitcli)
         VALUES (NEW.bdcodcli, 1, 2, new.bddatacadcli);
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_base_tcliente_au0 FOR vfin_base_tcliente
ACTIVE AFTER UPDATE POSITION 0
AS
BEGIN
 /*Adilson Hasckel: sol. 15117 - 14/07/2016 - criar automaticamente os clientes fixos na configuração de Online do Financeiro. */
  IF (OLD.bdcodtipocli = 3 AND NEW.bdcodtipocli <> 3) THEN
    EXECUTE PROCEDURE VFIN_INSERT_CLIENTE_ONLINE (NEW.bdcodcli);

 /*#151702 - Antony Rairon (14/06/2021) - Gerar situação ATIVO quando o cliente deixar de ser eventual e não possuir uma situação com a chave 1. */
  IF (OLD.bdcodtipocli = 3 AND NEW.bdcodtipocli <> 3) THEN
    BEGIN
      IF ((select first(1) bdchavesitcli from vfin_base_tsitcliente where bdcodcli = NEW.bdcodcli and bdchavesitcli = 1) is null) THEN
         INSERT INTO VFIN_BASE_TSITCLIENTE (bdcodcli, bdchavesitcli, bdcodsitcli, bddatasitcli)
                VALUES (NEW.bdcodcli, 1, 2, new.bddatacadcli);
    END
END^

SET TERM ; ^


SET TERM ^ ;
CREATE OR ALTER TRIGGER TGERADORDOCS_MOD_BI0 FOR TGERADORDOCS_MOD
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdchavemod IS NULL) OR (NEW.bdchavemod = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdchavemod)+1),1) FROM TGERADORDOCS_MOD INTO vcodigo;
       NEW.bdchavemod = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdchavemod FROM TGERADORDOCS_MOD WHERE bdchavemod = NEW.bdchavemod INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdchavemod)+1),1) FROM TGERADORDOCS_MOD INTO vcodigo;
            NEW.bdchavemod = vcodigo;
         END
    END
END
^
SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER tol_vfin_esc_trecfatura_ad0 FOR tol_vfin_esc_trecfatura
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodemp,OLD.bdchavelan);
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_base_tdespesa_bi0 FOR vfin_base_tdespesa
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcoddesp IS NULL) OR (NEW.bdcoddesp = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(bdcoddesp)+1),1) FROM vfin_base_tdespesa INTO vcodigo;
       NEW.bdcoddesp = vcodigo;
    END
  ELSE
    BEGIN
       SELECT bdcoddesp FROM vfin_base_tdespesa WHERE bdcoddesp = NEW.bdcoddesp INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcoddesp)+1),1) FROM vfin_base_tdespesa INTO vcodigo;
            NEW.bdcoddesp = vcodigo;
         END
    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger vfin_base_tcategoriafin_bi0 for vfin_base_tcategoriafin
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdcodcat IS NULL) OR (NEW.bdcodcat = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodcat)+1),1) FROM VFIN_BASE_TCATEGORIAFIN INTO vCodigo;
      NEW.bdcodcat = vCodigo;
    END
  ELSE
    BEGIN
       SELECT bdcodcat FROM VFIN_BASE_TCATEGORIAFIN WHERE bdcodcat = NEW.bdcodcat INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodcat) + 1), 1) FROM VFIN_BASE_TCATEGORIAFIN INTO vCodigo;
           NEW.bdcodcat = vCodigo;
         END
    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger vfin_base_tcategoriafin_bd0 for vfin_base_tcategoriafin
active before delete position 0
AS
begin
  update VFIN_ESC_TSERVICOFIXO set bdcodcat = null
  where bdcodcat = old.bdcodcat;

  update VFIN_ESC_TSERVICOFATURADO set bdcodcat = null
  where bdcodcat = old.bdcodcat;
end^

CREATE OR ALTER TRIGGER vfin_base_tdespesa_ref_bi0 FOR vfin_base_tdespesa_ref
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcoddesp IS NULL) OR (NEW.bdcoddesp = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcoddesp)),1) FROM vfin_base_tdespesa INTO vcodigo;
        NEW.bdcoddesp = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcoddesp FROM vfin_base_tdespesa WHERE bdcoddesp = NEW.bdcoddesp INTO vcodigo;
        IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcoddesp)),1) FROM vfin_base_tdespesa INTO vcodigo;
            NEW.bdcoddesp = vcodigo;
         END
    END
END^

CREATE OR ALTER trigger vfin_base_tfornecedor_ai0 for vfin_base_tfornecedor
active after insert position 0
AS
--  declare variable vcodigo integer;
begin
-- Gilberto - 06/07/2022 - NÃO pode inserir pelo banco, o controle da chave é feita pelo sistema
--  if ((select count(bdcodter) from tterceiro where bdcgcter = new.bdcnpjfor) = 0) then
--  begin
--    select first 1 bdcodter from tterceiro order by bdcodter desc into :vcodigo;
--    vcodigo = coalesce(vcodigo,0)+1;
--    insert into tterceiro (bdcodter, bdcgcter) values (:vcodigo, new.bdcnpjfor);
--  end
end^

CREATE OR ALTER trigger vfin_base_tfornecedor_ref_ai0 for vfin_base_tfornecedor_ref
active after insert position 0
AS
  declare variable vcnpj varchar(18);
  declare variable vcodigo integer;
begin
  select bdcnpjfor from vfin_base_tfornecedor where bdcodfor = new.bdcodfor into :vcnpj;
  select bdcodter from tterceiro ter where bdcgcter = :vcnpj
  and not exists (select first 1 bdcodter from tterceiro_ref where bdcodter = ter.bdcodter)
  into :vcodigo;
  if (coalesce(:vcodigo, 0) <> 0) then
  begin
    insert into tterceiro_ref (bdcodter, bdrefemp, bdapelidoter, bdcgcter, bdnometer, bdlogrter, bdendter, bdcompter, bdcepter, bdbaiter, bdcodcid, bdcodpais, bdnumter,
                               bddddter, bdfoneter, bddddfaxter, bdfaxter, bddddcelularter, bdcelularter, bdemailter, bdieter, bdimter, bddatacadter)
    values
    (:vcodigo, new.bdreffor, new.bdapefor, :vcnpj, new.bdnomefor, new.bdlogrfor, new.bdendfor, new.bdcomplendfor, new.bdcepfor, new.bdbaifor, new.bdcodcid, new.bdcodpais, new.bdnumendfor,
     new.bddddfonefor, new.bdfonefor, new.bddddfaxfor, new.bdfaxfor, new.bddddcelfor, new.bdcelfor, new.bdemailfor, new.bdiefor, new.bdimfor, new.bddatacadfor);
  end
end^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_base_tfornecedor_bi0 FOR vfin_base_tfornecedor
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodfor IS NULL) OR (NEW.bdcodfor = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodfor)+1),1) FROM vfin_base_tfornecedor INTO vcodigo;
        NEW.bdcodfor = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodfor FROM vfin_base_tfornecedor WHERE bdcodfor = NEW.bdcodfor INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodfor)+1),1) FROM vfin_base_tfornecedor INTO vcodigo;
            NEW.bdcodfor = vcodigo;
         END
    END
END^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_base_tfornecedor_ref_bi0 FOR vfin_base_tfornecedor_ref
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodfor IS NULL) OR (NEW.bdcodfor = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodfor)),1) FROM vfin_base_tfornecedor INTO vcodigo;
        NEW.bdcodfor = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodfor FROM vfin_base_tfornecedor WHERE bdcodfor = NEW.bdcodfor INTO vcodigo;
        IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodfor)),1) FROM vfin_base_tfornecedor INTO vcodigo;
            NEW.bdcodfor = vcodigo;
         END
    END
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER VFIN_ESC_TCONTASPAGARDESP_BI0 FOR VFIN_ESC_TCONTASPAGARDESP
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordemdesp IS NULL) OR (NEW.bdordemdesp = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordemdesp)+1), 1) FROM vfin_esc_tcontaspagardesp WHERE (bdcodesc = NEW.bdcodesc)  AND (bdchavectapag = NEW.bdchavectapag) INTO vnova_ordem;
      NEW.bdordemdesp = vnova_ordem;

      IF ((NEW.bdchavectapag IS NULL) OR (NEW.bdchavectapag = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVECTAPAG)), 1) FROM vfin_esc_tcontasapagar WHERE (bdcodesc = NEW.bdcodesc) INTO vchavelan;
          NEW.bdchavectapag = vchavelan;
        END
    END
  ELSE
    BEGIN
      SELECT bdordemdesp FROM vfin_esc_tcontaspagardesp WHERE (bdordemdesp = NEW.bdordemdesp) AND (bdchavectapag = NEW.bdchavectapag) AND (bdcodesc = NEW.bdcodesc) INTO vcodigo;

      IF (vcodigo > 0) THEN
        BEGIN
          SELECT COALESCE((MAX(bdordemdesp)+1), 1) FROM vfin_esc_tcontaspagardesp WHERE (bdcodesc = NEW.bdcodesc) AND (bdChavectapag = NEW.bdchavectapag) INTO vnova_ordem;
          NEW.bdordemdesp = vnova_ordem;
        END

      IF ((NEW.bdchavectapag IS NULL) OR (NEW.bdchavectapag = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVECTAPAG)), 1) FROM vfin_esc_tcontasapagar WHERE (bdcodesc = NEW.bdcodesc) INTO vchavelan;
          NEW.bdchavectapag = vchavelan;
        END
    END
END
^


SET TERM ; ^


SET TERM ^ ;



CREATE OR ALTER TRIGGER VFIN_ESC_TPARCELAPAGAR_BI0 FOR VFIN_ESC_TPARCELAPAGAR
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordempar IS NULL) OR (NEW.bdordempar = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordempar)+1), 1) FROM vfin_esc_tparcelapagar WHERE (bdcodesc = NEW.bdcodesc)  AND (bdchavectapag = NEW.bdchavectapag) INTO vnova_ordem;
      NEW.bdordempar = vnova_ordem;

      IF ((NEW.bdchavectapag IS NULL) OR (NEW.bdchavectapag = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVECTAPAG)), 1) FROM vfin_esc_tcontasapagar WHERE (bdcodesc = NEW.bdcodesc) INTO vchavelan;
          NEW.bdchavectapag = vchavelan;
        END
    END
  ELSE
    BEGIN
      SELECT bdordempar FROM vfin_esc_tparcelapagar WHERE (bdordempar = NEW.bdordempar) AND (bdchavectapag = NEW.bdchavectapag) AND (bdcodesc = NEW.bdcodesc) INTO vcodigo;

      IF (vcodigo > 0) THEN
        BEGIN
          SELECT COALESCE((MAX(bdordempar)+1), 1) FROM vfin_esc_tparcelapagar WHERE (bdcodesc = NEW.bdcodesc) AND (bdChavectapag = NEW.bdchavectapag) INTO vnova_ordem;
          NEW.bdordempar = vnova_ordem;
        END

      IF ((NEW.bdchavectapag IS NULL) OR (NEW.bdchavectapag = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVECTAPAG)), 1) FROM vfin_esc_tcontasapagar WHERE (bdcodesc = NEW.bdcodesc) INTO vchavelan;
          NEW.bdchavectapag = vchavelan;
        END
    END
END
^


SET TERM ; ^


SET TERM ^ ;



CREATE OR ALTER TRIGGER VFIN_ESC_TRETPAGAR_BI0 FOR VFIN_ESC_TRETPAGAR
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchavectapag IS NULL) OR (NEW.bdchavectapag = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchavectapag)), 1) FROM vfiN_esc_tcontasapagar WHERE (bdcodesc = NEW.bdcodesc) INTO vchavelan;
      NEW.bdchavectapag = vchavelan;
    END
END
^


SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER TRIGGER vfin_esc_tcontaspagdespobs_bi0 FOR vfin_esc_tcontaspagardespobs
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavectapag INTEGER;
  DECLARE VARIABLE vordem INTEGER;
BEGIN
  IF ((NEW.bdchavectapag IS NULL) OR (NEW.bdchavectapag = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchavectapag)), 1) FROM vfin_esc_tcontasapagar
      WHERE (bdcodesc = NEW.bdcodesc) INTO vchavectapag;
      NEW.bdchavectapag = vchavectapag;
    END

   /*se for informado uma ordem que não existe, buscar nova ordem*/
   SELECT BDORDEMDESP FROM VFIN_ESC_TCONTASPAGARDESP
   WHERE (BDCODESC = NEW.BDCODESC) AND (bdchavectapag = NEW.bdchavectapag) AND (bdordemdesp = NEW.bdordemdesp) INTO vordem;

   IF (vordem IS NULL) THEN
      BEGIN
        /*selecionar a última ordem do serviço fixo vinculado, */
        SELECT COALESCE((MAX(BDORDEMDESP)), 1) FROM VFIN_ESC_TCONTASPAGARDESP
        WHERE (BDCODESC = NEW.BDCODESC) AND (bdchavectapag = NEW.bdchavectapag) INTO vNova_Ordem;
        NEW.bdordemdesp = vNova_ordem;
      END
END^

SET TERM ; ^


SET TERM ^ ;

CREATE OR ALTER trigger vfin_base_tformapagamento_bi0 for vfin_base_tformapagamento
active before insert position 0
AS
 declare variable wCOD integer;
begin 
  if (coalesce(new.bdcodformapgto,0)=0) then
   begin
    select coalesce (max(bdcodformapgto),0)+1 from vfin_base_tformapagamento into :wCOD;
    new.bdcodformapgto = wCOD;
   end
end^

CREATE OR ALTER TRIGGER vfin_esc_tpagamentosobs_bi0 FOR vfin_esc_tpagamentosobs
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavectapag INTEGER;
  DECLARE VARIABLE vordem INTEGER;
BEGIN
  IF ((NEW.bdchavectapag IS NULL) OR (NEW.bdchavectapag = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchavectapag)), 1) FROM vfin_esc_tcontasapagar
      WHERE (bdcodesc = NEW.bdcodesc) INTO vchavectapag;
      NEW.bdchavectapag = vchavectapag;
    END

   /*se for informado uma ordem que não existe, buscar nova ordem*/
   SELECT BDORDEMPAG FROM vfin_esc_tpagamentos
   WHERE (BDCODESC = NEW.BDCODESC) AND (bdchavectapag = NEW.bdchavectapag) AND (bdordempag = NEW.bdordempag) INTO vordem;

   IF (vordem IS NULL) THEN
      BEGIN
        /*selecionar a última ordem do serviço fixo vinculado, */
        SELECT COALESCE((MAX(BDORDEMPAG)), 1) FROM vfin_esc_tpagamentos
        WHERE (BDCODESC = NEW.BDCODESC) AND (bdchavectapag = NEW.bdchavectapag) INTO vNova_Ordem;
        NEW.bdordempag = vnova_ordem;
      END
END^

CREATE OR ALTER TRIGGER VFIN_ESC_TPAGAMENTOS_BI0 FOR VFIN_ESC_TPAGAMENTOS
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdordempag IS NULL) OR (NEW.bdordempag = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordempag)+1), 1) FROM vfin_esc_tpagamentos WHERE (bdcodesc = NEW.bdcodesc)  AND (bdchavectapag = NEW.bdchavectapag) INTO vnova_ordem;
      NEW.bdordempag = vnova_ordem;

      IF ((NEW.bdchavectapag IS NULL) OR (NEW.bdchavectapag = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVECTAPAG)), 1) FROM vfin_esc_tcontasapagar WHERE (bdcodesc = NEW.bdcodesc) INTO vchavelan;
          NEW.bdchavectapag = vchavelan;
        END
    END
  ELSE
    BEGIN
      SELECT bdordempag FROM vfin_esc_tpagamentos WHERE (bdordempag = NEW.bdordempag) AND (bdchavectapag = NEW.bdchavectapag) AND (bdcodesc = NEW.bdcodesc) INTO vcodigo;

      IF (vcodigo > 0) THEN
        BEGIN
          SELECT COALESCE((MAX(bdordempag)+1), 1) FROM vfin_esc_tpagamentos WHERE (bdcodesc = NEW.bdcodesc) AND (bdChavectapag = NEW.bdchavectapag) INTO vnova_ordem;
          NEW.bdordempag = vnova_ordem;
        END

      IF ((NEW.bdchavectapag IS NULL) OR (NEW.bdchavectapag = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVECTAPAG)), 1) FROM vfin_esc_tcontasapagar WHERE (bdcodesc = NEW.bdcodesc) INTO vchavelan;
          NEW.bdchavectapag = vchavelan;
        END
    END
END
^

/* Restore proc. body: SP_VRHF_RESUMO_AD13SAL */
create or alter procedure SP_VRHF_RESUMO_AD13SAL (
    PREMP varchar(20000),
    PRCOL varchar(32700),
    PRREF integer,
    PRPROXIMAREF integer,
    PRULTDIA date,
    PRFUCDET smallint = 0,
    PRPUXAFILIAL smallint = 0)
returns (
    GRUPO_CLASSE integer,
    CODIGO_EMPRESA integer,
    CODIGO_FILIAL integer,
    NOME_EMPRESA DM_BDNOMEMP,
    ENDERECO_EMPRESA DM_BDENDERECO,
    NUMERO_EMPRESA DM_NUMEND,
    BAIRRO_EMPRESA DM_BDBAIRRO,
    CEP_EMPRESA DM_CEP,
    CNPJ_EMPRESA DM_CNPJ_CPF,
    CODIGO_COLABORADOR integer,
    NOME_COLABORADOR DM_BDNOMCOL,
    ADMISSAO_COLABORADOR date,
    FUNCAO_COLABORADOR varchar(100),
    CPF_COLABORADOR varchar(14),
    PIS_COLABORADOR varchar(14),
    CODIGO_VERBA integer,
    DESCRICAO_VERBA varchar(40),
    REFERENCIA_VERBA numeric(18,6),
    REFERENCIA_AUXILIAR_VERBA numeric(18,6),
    BDTIPOCODVER integer,
    PROVENTOS_FOLHA numeric(18,6),
    DESCONTOS_FOLHA numeric(18,6),
    SALARIO_BASE numeric(18,6),
    BDCODENQFED integer,
    BDSIMPLESGPS integer,
    CTPS_COL DM_BDCTPS,
    SERIE_CTPS DM_SERIECTPS,
    CBO_COL integer,
    HORAS_MENSAIS numeric(18,6),
    RAT_APO_COL numeric(18,6),
    REFERENCIA_FOLHA integer,
    BDORDEM integer,
    BASE_FGTS numeric(18,6),
    FGTS_FOLHA numeric(18,6),
    IRRF_FOLHA numeric(18,6),
    BASE_RAIS numeric(18,6),
    REFERENCIAAUX varchar(6),
    DESCRICAO_RED_VERBA varchar(20),
    CIDADE_EMPRESA varchar(40),
    UF_EMPRESA varchar(2),
    COMPL_EMPRESA DM_BDCOMPENDERECO,
    PISVER DM_BOOLEAN,
    BDORDEMTIPOCODVER integer,
    CLASSIFICA_VERBA varchar(20),
    RESCISAO_COLABORADOR date,
    MOTIVO_RESCISAO varchar(110),
    TIPO_RESCISAO integer,
    SALARIO_FAMILIA numeric(18,6),
    BDTEMGRRF integer,
    BDORDEMVER integer,
    DATA_PAG_IR date,
    BDTIPOREFVER integer,
    BDREFHOREMP DM_BOOLEAN,
    BFGTS_MESPOST numeric(18,6),
    FGTS_MESPOST numeric(18,6),
    BDCCATVCONCOM DM_BOOLEAN,
    BDCATEGORIAESOCIAL integer,
    DEPSF integer,
    DEPIR integer,
    BDCONTRCOL integer,
    BDCODCLA integer,
    BDCODSINTRAB integer,
    BDCODTFUC integer)
as
declare variable WSQL varchar(32700);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WPLAFUC integer;
declare variable WCODTFUC integer;
declare variable WVALV numeric(18,6);
declare variable WCODCLA integer;
declare variable WREFRESCISAO integer;
declare variable WCODRES integer;
declare variable WBFGTS numeric(18,6);
declare variable WFGTS numeric(18,6);
declare variable WGRRFPRES integer;
declare variable WFGTSMENSANT DM_BOOLEAN;
declare variable WDEPIR integer;
declare variable WDEPSF integer;
declare variable WEMPOK integer;
declare variable WCODCID integer;
declare variable WCODUF integer;
begin
  if (trim(coalesce(premp, '')) <> '') then
     premp = upper(premp);

  if (trim(coalesce(prcol, '')) <> '') then
     prcol = upper(prcol);

  prpuxafilial = coalesce(prpuxafilial, 0);
  prfucdet = coalesce(prfucdet, 0);

  wsql = 'select COLCON.BDCODEMP,';

  if (prpuxafilial = 1) then
    wsql = wsql || ' coalesce(EMP.BDCODMATRIZ, COLCON.BDCODEMP),  ';
  else
    wsql = wsql || ' COLCON.BDCODEMP, ';

  wsql = wsql ||'COLCON.BDCODCOL, COLCON.BDREFA13, COLCON.BDCODVER, COLCON.BDREFAUXVA13, COLCON.BDREFVA13, COLCON.BDVALVA13, FOLN.BDORDEM, EMP.BDCNPJEMP, '||
                'VER.BDDESCVER, VERREF.BDTIPOCODVER, FOLN.BDSALBASEA13, FOLN.BDBASEFGTSA13, FOLN.BDFGTSA13, FOLN.BDBASEIRA13, FOLN.BDBRAISA13, lpad(COLCON.BDREFA13, 6, ''0''), '||
                'VER.BDDESCREDVER, VERREF.BDPISVER, VERREF.BDORDEMTIPOCODVER, VER.BDCLAVER, FOLN.BDBSALFAMA13, '||
                'VER.BDORDEMVER, VERREF.BDTIPOREFVER '||
         'from VRHF_EMP_TVERBAA13 COLCON '||
         'join TEMPRESAS EMP on (EMP.BDCODEMP = COLCON.BDCODEMP) '||
         'join VRHF_EMP_TA13SAL FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFA13 = COLCON.BDREFA13) '||
         'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = COLCON.BDCODVER) '||
         'join VW_TVERBAS_REF VERREF on (VERREF.BDCODVER = COLCON.BDCODVER) ';


--wsql = wsql||'where COLCON.BDREFA13 = '||prref||' and upper(coalesce(FOLN.BDCALCFERA13, ''FALSE'')) <> ''TRUE'' ' ; {167754 - João Victor - 09/01/2023 -Retirar bloqueio}
  wsql = wsql||'where COLCON.BDREFA13 = '||prref;

  if (premp <> '') then
     begin
       if (prpuxafilial <> 0) then
          wsql = wsql||' and (('||premp||') or ('||replace(premp, 'COLCON.BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';
       else
          begin
            wsql = wsql||' and '||premp||' ';

            if (prcol <> '') then
               wsql = wsql||' and '||prcol||' ';
          end
     end

  wsql = wsql||'order by COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFA13, COLCON.BDCODVER ';

  wempatu = 0;
  wcolatu = 0;
  wempok  = 0;

  for execute statement wsql into
    :CODIGO_FILIAL,
    :CODIGO_EMPRESA,
    :CODIGO_COLABORADOR,
    :REFERENCIA_FOLHA,
    :CODIGO_VERBA,
    :REFERENCIA_AUXILIAR_VERBA,
    :REFERENCIA_VERBA,
    :wvalv,
    :BDORDEM,
    :CNPJ_EMPRESA,
    :DESCRICAO_VERBA,
    :BDTIPOCODVER,
    :SALARIO_BASE,
    :wbfgts,
    :wfgts,
    :IRRF_FOLHA,
    :BASE_RAIS,
    :REFERENCIAAUX,
    :DESCRICAO_RED_VERBA,
    :PISVER,
    :BDORDEMTIPOCODVER,
    :CLASSIFICA_VERBA,
    :SALARIO_FAMILIA,
    :BDORDEMVER,
    :BDTIPOREFVER
  do
    begin
      if (wempatu <> CODIGO_FILIAL) then
         begin
           wempatu = CODIGO_FILIAL;
           wcolatu = 0;

           BDCODENQFED   = null;
           BDSIMPLESGPS  = null;
           BDCCATVCONCOM = null;

           select first 1 BDCODENQFED from TENQFED where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC into :BDCODENQFED;
           select first 1 BDSIMPLESGPS, BDCCATVCONCOM from VRHF_BASE_TEMPGPS where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC into :BDSIMPLESGPS, :BDCCATVCONCOM;
           select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC into :BDREFHOREMP;

           BDREFHOREMP   = upper(coalesce(BDREFHOREMP, 'FALSE'));
           BDCCATVCONCOM = upper(coalesce(BDCCATVCONCOM, 'FALSE'));

           NOME_EMPRESA     = null;
           ENDERECO_EMPRESA = null;
           NUMERO_EMPRESA   = null;
           BAIRRO_EMPRESA   = null;
           CEP_EMPRESA      = null;
           COMPL_EMPRESA    = null;
           wcodcid          = null;

           -- Sol.142437 | Leonardo Schwab | 15/12/2020 | Caso o parâmetro de puxar filiais estiver selecionado busca as informações da Matriz.
           if (prpuxafilial = 1) then
             begin
           select first 1 BDNOMEMP, trim(coalesce(BDENDEMP, '''')), BDNUMEMP, BDBAIEMP, BDCEPEMP, BDCOMPLEMP, BDCODCID
           from TEMPRESAS_REF
               where BDCODEMP = :CODIGO_EMPRESA
               order by BDREFEMP DESC
               into :NOME_EMPRESA, :ENDERECO_EMPRESA, :NUMERO_EMPRESA, :BAIRRO_EMPRESA, :CEP_EMPRESA, :COMPL_EMPRESA, :wcodcid;
             end
           else
             begin
               select first 1 BDNOMEMP, trim(coalesce(BDENDEMP, '''')), BDNUMEMP, BDBAIEMP, BDCEPEMP, BDCOMPLEMP, BDCODCID
               from TEMPRESAS_REF
           where BDCODEMP = :wempatu
           order by BDREFEMP DESC
           into :NOME_EMPRESA, :ENDERECO_EMPRESA, :NUMERO_EMPRESA, :BAIRRO_EMPRESA, :CEP_EMPRESA, :COMPL_EMPRESA, :wcodcid;
             end

           select first 1 E.BDCODEMP
           from SP_EMPRESAS_USU(:wempatu) E
           where E.BDCODEMP = :wempatu
           into :wempok;

           wempok = coalesce(wempok, 0);

           wcoduf         = null;
           CIDADE_EMPRESA = null;
           select first 1 BDNOMCID, BDCODUF from TCIDADE where BDCODCID = :wcodcid into :CIDADE_EMPRESA, :wcoduf;

           UF_EMPRESA = null;
           select first 1 BDSIGLAUF from TUF where BDCODUF = :wcoduf into :UF_EMPRESA;
         end

      if (wempok = wempatu) then
         begin
           if (wcolatu <> CODIGO_COLABORADOR) then
              begin
                wcolatu = CODIGO_COLABORADOR;
     
                NOME_COLABORADOR     = null;
                ADMISSAO_COLABORADOR = null;
                CPF_COLABORADOR      = null;
                PIS_COLABORADOR      = null;
                CTPS_COL             = null;
                SERIE_CTPS           = null;
                HORAS_MENSAIS        = null;
                RAT_APO_COL          = null;
                GRUPO_CLASSE         = null;
                BFGTS_MESPOST        = null;
                FGTS_MESPOST         = null;
                BDCATEGORIAESOCIAL   = null;
                BDCONTRCOL           = null;
                wdepir               = 0;
                wdepsf               = 0;
                BDCODCLA             = null;
                BDCODSINTRAB         = null;
                BDCODTFUC            = null;
     
                select first 1 CASE WHEN (FIS.BDNMSOCIAL <> '' and PAR.bdusanomesocial = 'TRUE') THEN FIS.BDNMSOCIAL ELSE cad.BDNOMCOL END Nome_Colaborador from VRH_EMP_TCOLCON_CAD cad
                left outer join VRH_EMP_TCOLCON_FIS FIS ON (FIS.BDCODEMP = cad.BDCODEMP AND FIS.BDCODCOL = cad.BDCODCOL AND FIS.bdrefcol=cad.bdrefcol)
                left outer join(select a.bdcodemp,max(a.bdrefemp)bdrefemp from VRHF_BASE_TEMPPAR a group by a.bdcodemp) pmax on  (pmax.BDCODEMP = cad.BDCODEMP)
                left outer join VRHF_BASE_TEMPPAR PAR  on (par.bdcodemp=pmax.bdcodemp and par.bdrefemp=pmax.bdrefemp)
                where cad.BDCODEMP = :wempatu and cad.BDCODCOL = :wcolatu and cad.BDREFCOL <= :prref
                order by cad.BDREFCOL DESC into :NOME_COLABORADOR; --Sol.161198 Quando tiver nome social e empresas opatar por usar ele, sera usado no nome social.
                select first 1 BDDATAADMCOL, BDCPFCOL, BDCONTRCOL from VRH_EMP_TCOLCON where BDCODEMP = :wempatu and BDCODCOL = :wcolatu into :ADMISSAO_COLABORADOR, :CPF_COLABORADOR, :BDCONTRCOL;
                select first 1 BDPISCOL from VRH_EMP_TCOLCON_DOCREF where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :PIS_COLABORADOR;
                select first 1 BDCTPSCOL, BDSERIECTPSCOL from VRH_EMP_TCOLCON_DOCREF where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :CTPS_COL, :SERIE_CTPS;
                select first 1 BDHORASMENSAISCOL, BDNRODEPSALFAMCOL from VRHF_EMP_TCOL_CALC where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :HORAS_MENSAIS, :wdepsf;
                select first 1 BDPERCRATCOL, BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :RAT_APO_COL, :BDCATEGORIAESOCIAL;
                select first 1 BDNRODEPIRCOL from VRHF_EMP_TCOLCON_CALC where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :wdepir;
                select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :BDCODSINTRAB;
     
                CTPS_COL      = trim(coalesce(CTPS_COL, ''));
                SERIE_CTPS    = trim(coalesce(SERIE_CTPS, ''));
                HORAS_MENSAIS = coalesce(HORAS_MENSAIS, 0);
                RAT_APO_COL   = coalesce(RAT_APO_COL, 0);
                BDCONTRCOL    = coalesce(BDCONTRCOL, 0);
                wdepir        = coalesce(wdepir, 0);
                wdepsf        = coalesce(wdepsf, 0);
     
                if (CTPS_COL = '' and SERIE_CTPS = '') then
                   begin
                     CTPS_COL   = substring(replace(replace(CPF_COLABORADOR, '.', ''), '-', '') from 1 for 7);
                     SERIE_CTPS = substring(replace(replace(CPF_COLABORADOR, '.', ''), '-', '') from 8 for 4);
                   end
     
                wplafuc  = null;
                wcodtfuc = null;
                select first 1 BDCODPLAFUC, BDCODTFUC from VRH_EMP_TCOL_VINCDIA where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDDATACOL <= :prultdia order by BDDATACOL DESC into :wplafuc, :wcodtfuc;
     
                BDCODTFUC = coalesce(wcodtfuc,0);
                FUNCAO_COLABORADOR = null;
                CBO_COL            = null;
     
                if (wplafuc is not null and wcodtfuc is not null) then
                   begin
                     if (prfucdet <> 0) then
                        select first 1 BDDESCFUNCDET, BDCODCBO from VRH_FUNCOES_TFUC where BDCODPLAFUC = :wplafuc and BDCODTFUC = :wcodtfuc into :FUNCAO_COLABORADOR, :CBO_COL;
     
                     if (trim(coalesce(FUNCAO_COLABORADOR, '')) = '') then
                        select first 1 BDDESCTFUC, BDCODCBO from VRH_FUNCOES_TFUC where BDCODPLAFUC = :wplafuc and BDCODTFUC = :wcodtfuc into :FUNCAO_COLABORADOR, :CBO_COL;
                   end
     
                wcodcla = null;
                select first 1 BDCODCLA from VRH_EMP_TCOLCON_VINC where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :wcodcla;
     
                BDCODCLA = coalesce(wcodcla, 0);
                if (coalesce(wcodcla, 0) <> 0) then
                   select first 1 BDGRUPOCLA from VRH_BASE_TCLASSE where BDCODCLA = :wcodcla into :GRUPO_CLASSE;
     
                GRUPO_CLASSE = coalesce(GRUPO_CLASSE, 0);
     
                BASE_FGTS            = null;
                FGTS_FOLHA           = null;
                RESCISAO_COLABORADOR = null;
                MOTIVO_RESCISAO      = null;
                TIPO_RESCISAO        = null;
                BDTEMGRRF            = null;
                wrefrescisao         = null;
                wgrrfpres            = null;
                wcodres              = null;
                wfgtsmensant         = null;
     
                select first 1 R.BDDATARESCISAO, R.BDREFRESCISAO, R.BDCODPRES, R.BDCALCFGTSMESANT, PR.BDGRRFPRES, substring(PR.BDDESCPRES from 1 for 110), PR.BDTIPOMOV
                from VRH_EMP_TRESCISAO R
                join VRH_BASE_TPREPRESC PR on (PR.BDCODPRES = R.BDCODPRES)
                where R.BDCODEMP = :wempatu and R.BDCODCOL = :wcolatu
                into :RESCISAO_COLABORADOR, :wrefrescisao, :wcodres, :wfgtsmensant, :wgrrfpres, :MOTIVO_RESCISAO, :TIPO_RESCISAO;
     
                wrefrescisao = coalesce(wrefrescisao, 0);
                wgrrfpres    = coalesce(wgrrfpres, 0);
                wcodres      = coalesce(wcodres, 0);
                wfgtsmensant = upper(coalesce(wfgtsmensant, 'FALSE'));
     
                if (wrefrescisao <> REFERENCIA_FOLHA) then
                   begin
                     RESCISAO_COLABORADOR = null;
                     MOTIVO_RESCISAO      = null;
                     TIPO_RESCISAO        = 0;
                   end
     
                if (wrefrescisao = prproximaref and wfgtsmensant = 'TRUE' and wgrrfpres in (1,2)) then
                   begin
                     BASE_FGTS     = 0;
                     FGTS_FOLHA    = 0;
                     BFGTS_MESPOST = wbfgts;
                     FGTS_MESPOST  = wfgts;
                   end
                else
                   begin
                     BASE_FGTS     = wbfgts;
                     FGTS_FOLHA    = wfgts;
                     BFGTS_MESPOST = 0;
                     FGTS_MESPOST  = 0;
                   end
     
                BASE_FGTS     = coalesce(BASE_FGTS, 0);
                FGTS_FOLHA    = coalesce(FGTS_FOLHA, 0);
                BFGTS_MESPOST = coalesce(BFGTS_MESPOST, 0);
                FGTS_MESPOST  = coalesce(FGTS_MESPOST, 0);
     
                if (wrefrescisao = REFERENCIA_FOLHA and wgrrfpres in (1,2)) then
                   BDTEMGRRF = 1;
                else
                   BDTEMGRRF = 0;
     
                DATA_PAG_IR = cast((substring(cast(REFERENCIA_FOLHA as varchar(6)) from 5 for 2)||'-20-'||substring(cast(REFERENCIA_FOLHA as varchar(6)) from 1 for 4)) as date);
     
                select count(*)
                from VW_VRH_EMP_TDEP_REF
                where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and
                      upper(coalesce(BDSALFAMDPN, 'FALSE')) = 'TRUE' and
                      coalesce(BDPARENESCODPN, 0) in (0, 4, 5, 6, 11) and
                      coalesce(BDPARENESCODPN, 0) <> 3 and
                      ((select BDAAAAMM
                        from AAAAMM(coalesce(BDDATANASCDPN, BDDATAENTREDPN))) <= :REFERENCIA_FOLHA) and
                      ((BDDATABAUXADPN is null) or ((select BDAAAAMM
                                                     from AAAAMM(BDDATABAUXADPN)) > :REFERENCIA_FOLHA)) and
                      ((upper(coalesce(BDINVALIDODPN, 'FALSE')) = 'TRUE') or ((BDDATANASCDPN is not null) and
                      (:REFERENCIA_FOLHA - cast((select BDAAAAMM
                                                 from AAAAMM(BDDATANASCDPN)) as integer) <= 1400)))
                into :DEPSF;
     
                DEPSF = coalesce(DEPSF, 0);
     
                select count(*)
                from VW_VRH_EMP_TDEP_REF
                where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and
                      upper(coalesce(BDDEPIRDPN, 'FALSE')) = 'TRUE' and
                      coalesce(BDPARENESCODPN, 0) <> 3 and
                      (select BDAAAAMM
                       from AAAAMM(coalesce(BDDATANASCDPN, BDDATAENTREDPN))) <= :REFERENCIA_FOLHA and
                      ((BDDATABAUXADPN is null) or ((select BDAAAAMM
                                                     from AAAAMM(BDDATABAUXADPN)) > :REFERENCIA_FOLHA)) and
                      ((BDREFIRDPN is null) or (coalesce(BDREFIRDPN, 0) = 0) or (coalesce(BDREFIRDPN, 0) >= :REFERENCIA_FOLHA)) and
                      ((upper(coalesce(BDINVALIDODPN, 'FALSE')) = 'TRUE') or (BDREFIRDPN >= :REFERENCIA_FOLHA) or ((coalesce(BDPARENESCODPN, 0) in (0, 4, 5, 6)) and
                      (:REFERENCIA_FOLHA - cast((select BDAAAAMM
                                                 from AAAAMM(BDDATANASCDPN)) as integer) < 2200)) or (coalesce(BDPARENESCODPN, 0) in (1, 2)))
                into :DEPIR;
     
                DEPIR = coalesce(DEPIR, 0);
     
                if (DEPSF + DEPIR <= 0) then
                   begin
                     DEPSF = wdepsf;
                     DEPIR = wdepir;
                   end
              end
     
           BDTIPOCODVER = coalesce(BDTIPOCODVER, 0);
           if (BDTIPOCODVER in (0, 2)) then
              PROVENTOS_FOLHA = wvalv;
           else
              DESCONTOS_FOLHA = wvalv;
     
           suspend;
         end
    end
end^


/* Restore proc. body: SP_VRHF_RESUMO_13SAL */
create or alter procedure SP_VRHF_RESUMO_13SAL (
    PREMP varchar(20000),
    PRCOL varchar(32700),
    PRREF integer,
    PRPROXIMAREF integer,
    PRULTDIA date,
    PREMISSAO integer = 0,
    PRFUCDET smallint = 0,
    PRPUXAFILIAL smallint = 0)
returns (
    GRUPO_CLASSE integer,
    CODIGO_EMPRESA integer,
    CODIGO_FILIAL integer,
    NOME_EMPRESA DM_BDNOMEMP,
    ENDERECO_EMPRESA DM_BDENDERECO,
    NUMERO_EMPRESA DM_NUMEND,
    BAIRRO_EMPRESA DM_BDBAIRRO,
    CEP_EMPRESA DM_CEP,
    CNPJ_EMPRESA DM_CNPJ_CPF,
    CODIGO_COLABORADOR integer,
    NOME_COLABORADOR DM_BDNOMCOL,
    ADMISSAO_COLABORADOR date,
    FUNCAO_COLABORADOR varchar(100),
    CPF_COLABORADOR varchar(14),
    PIS_COLABORADOR varchar(14),
    CODIGO_VERBA integer,
    DESCRICAO_VERBA varchar(40),
    REFERENCIA_VERBA numeric(18,6),
    REFERENCIA_AUXILIAR_VERBA numeric(18,6),
    BDTIPOCODVER integer,
    PROVENTOS_FOLHA numeric(18,6),
    DESCONTOS_FOLHA numeric(18,6),
    SALARIO_BASE numeric(18,6),
    BDCODENQFED integer,
    BDSIMPLESGPS integer,
    CTPS_COL DM_BDCTPS,
    SERIE_CTPS DM_SERIECTPS,
    CBO_COL integer,
    HORAS_MENSAIS numeric(18,6),
    RAT_APO_COL numeric(18,6),
    REFERENCIA_FOLHA integer,
    BDORDEM integer,
    BASE_INSS numeric(18,6),
    INSS_FOLHA numeric(18,6),
    BASE_FGTS numeric(18,6),
    FGTS_FOLHA numeric(18,6),
    IRRF_FOLHA numeric(18,6),
    BASE_RAIS numeric(18,6),
    REFERENCIAAUX varchar(6),
    DESCRICAO_RED_VERBA varchar(20),
    CIDADE_EMPRESA varchar(40),
    UF_EMPRESA varchar(2),
    COMPL_EMPRESA DM_BDCOMPENDERECO,
    PISVER DM_BOOLEAN,
    BDORDEMTIPOCODVER integer,
    CLASSIFICA_VERBA varchar(20),
    RESCISAO_COLABORADOR date,
    MOTIVO_RESCISAO varchar(110),
    TIPO_RESCISAO integer,
    SALARIO_FAMILIA numeric(18,6),
    BDTEMGRRF integer,
    BDORDEMVER integer,
    DATA_PAG_IR date,
    BDTIPOREFVER integer,
    BDREFHOREMP DM_BOOLEAN,
    BFGTS_MESPOST numeric(18,6),
    FGTS_MESPOST numeric(18,6),
    BDCCATVCONCOM DM_BOOLEAN,
    BDCATEGORIAESOCIAL integer,
    DEPSF integer,
    DEPIR integer,
    BDCONTRCOL integer,
    BASE_INSS13_MULTVINC numeric(18,6),
    BASE_IR13_MULTVINC numeric(18,6),
    VALOR_INSS13_MULTVINC numeric(18,6),
    VALOR_IR13_MULTVINC numeric(18,6),
    VINSSFN numeric(18,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCODCLA integer,
    BDCODSINTRAB integer,
    BDCODTFUC integer,
    BDSALFAM13GPS numeric(18,6),
    BDRATEIO13SAL integer,
    BASE_PIS NUMERIC(18,6))
as
declare variable WSQL varchar(32700);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WPLAFUC integer;
declare variable WCODTFUC integer;
declare variable WVALV numeric(18,6);
declare variable WCODCLA integer;
declare variable WREFRESCISAO integer;
declare variable WCODRES integer;
declare variable WBFGTS numeric(18,6);
declare variable WFGTS numeric(18,6);
declare variable WGRRFPRES integer;
declare variable WFGTSMENSANT DM_BOOLEAN;
declare variable WDEPIR integer;
declare variable WDEPSF integer;
declare variable WCODCID integer;
declare variable WEMPOK integer;
declare variable WCODUF integer;
declare variable WVALSALFAM13 numeric(18,6);
declare variable WVALV13 numeric(18,6);
declare variable WCLAVER varchar(20);
declare variable WINSSVER integer;
declare variable WBASEGPSVER DM_BOOLEAN;
declare variable WORDEMATU integer;
declare variable WSQLINSS varchar(10000);
declare variable WPISVER DM_BOOLEAN;
declare variable WCHAVEATUAL varchar(100);
declare variable WCODCENTROCHAVE integer;
declare variable WCODTPCCCHAVE integer;
begin
  if (trim(coalesce(premp, '')) <> '') then
     premp = upper(premp);

  if (trim(coalesce(prcol, '')) <> '') then
     prcol = upper(prcol);

  premissao = coalesce(premissao, 0);

  prpuxafilial = coalesce(prpuxafilial, 0);
  prfucdet = coalesce(prfucdet, 0);

  wsql = 'select COLCON.BDCODEMP, COLCON.BDCODMATRIZ, COLCON.BDCODCOL, COLCON.BDREF13, COLCON.BDCODVER, COLCON.BDREFAUXV13, COLCON.BDREFV13, COLCON.BDVALV13, '||
            'COLCON.BDORDEM, EMP.BDCNPJEMP, '||
--            'VER.BDDESCVER, COLCON.BDTIPOCODVER, FOLN.BDSALBASE13, FOLN.BDBASEINSS13, FOLN.BDVALORINSS13, FOLN.BDBASEFGTS13, FOLN.BDFGTS13, FOLN.BDBASEIR13, '||
            'VER.BDDESCVER, COLCON.BDTIPOCODVER, FOLN.BDSALBASE13, FOLN.BDVALORINSS13, FOLN.BDBASEFGTS13, FOLN.BDFGTS13, FOLN.BDBASEIR13, '||
            'FOLN.BDBRAIS13, lpad(COLCON.BDREF13, 6, ''0''), '||
            'VER.BDDESCREDVER, COLCON.BDPISVER, COLCON.BDORDEMTIPOCODVER, VER.BDCLAVER, FOLN.BDBSALFAM13, '||
            'VER.BDORDEMVER, COLCON.BDTIPOREFVER, FOLN.BDVALORINSS13, COLCON.BDCODCENTRO, COLCON.BDCODTPCC '||
         'from (';

  if (premissao <= 0) then
     begin
       wsql = wsql||
              'select COLCON.BDCODEMP,'||
                  'COLCON.BDCODMATRIZ, '||
                  'COLCON.BDREF13,'||
                  'cast(null as integer) BDCHAVE,'||
                  'COLCON.BDCODCOL,'||
                  'COLCON.BDCODVER,'||
                  'case when coalesce(VERREF.BDTIPOREFVER, 0) = 4 then COLCON.BDREFV13MAX else COLCON.BDREFV13SUM end BDREFV13, '||
                  'case when (substring(upper(VERREF.BDDEDFORMREFAUXVER) from 1 for 1) = ''T'') then COLCON.BDREFAUXV13SUM else COLCON.BDREFAUXV13MAX end BDREFAUXV13, '||
                  'COLCON.BDVALV13,'||
                  'COLCON.BDIGNREFV13,'||
                  'COLCON.BDIGNVALV13,'||
                  'COLCON.BDORVERBA13,'||
                  'COLCON.BDIGNREFAV13,'||
                  'cast(null as integer) BDCODCENTRO,'||
                  'cast(null as integer) BDCODTPCC,'||
                  'cast(null as integer) BDCODTOMADOR,'||
                  'cast(null as integer) BDORDEM,' ||
                  'COLCON.BDCOMPESP,'||
                  'COLCON.BDFORMREFAUX,'||
                  'COLCON.BDFORMREF,'||
                  'COLCON.BDFORMVAL, '||
                  'VERREF.BDTIPOCODVER, '||
                  'VERREF.BDTIPOREFVER, '||
                  'VERREF.BDORDEMTIPOCODVER, '||
                  'VERREF.BDPISVER '||
              'from ('||
              'select COLCON.BDCODEMP, ';

       if (prpuxafilial = 1) then
         wsql = wsql || ' coalesce(EMP.BDCODMATRIZ, COLCON.BDCODEMP) BDCODMATRIZ,  ';
       else
         wsql = wsql || ' COLCON.BDCODEMP BDCODMATRIZ, ';

       wsql = wsql ||
                  'COLCON.BDREF13,'||
                  'COLCON.BDCODCOL,'||
                  'COLCON.BDCODVER,'||
                  'MAX(COLCON.BDREFV13) BDREFV13MAX,'||
                  'SUM(COLCON.BDREFV13) BDREFV13SUM, '||
                  'SUM(COLCON.BDREFAUXV13) BDREFAUXV13SUM, '||
                  'MAX(COLCON.BDREFAUXV13) BDREFAUXV13MAX, '||
                  'SUM(COLCON.BDVALV13) BDVALV13,'||
                  'MAX(COLCON.BDIGNREFV13) BDIGNREFV13,'||
                  'MAX(COLCON.BDIGNVALV13) BDIGNVALV13,'||
                  'MAX(COLCON.BDORVERBA13) BDORVERBA13,'||
                  'MAX(COLCON.BDIGNREFAV13) BDIGNREFAV13,'||
                  'COLCON.BDCOMPESP,'||
                  'COLCON.BDFORMREFAUX,'||
                  'COLCON.BDFORMREF,'||
                  'COLCON.BDFORMVAL '||
              'FROM VRHF_EMP_TVERBA_13_RAT COLCON '||
              'join TEMPRESAS EMP on (EMP.BDCODEMP = COLCON.BDCODEMP) '||
              'where COLCON.BDREF13 = '||prref||' ';

              if (premp <> '') then
                 begin
                   if (prpuxafilial <> 0) then
                      wsql = wsql||' and (('||premp||') or ('||replace(premp, 'COLCON.BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';
                   else
                      begin
                        wsql = wsql||' and '||premp||' ';
            
                        if (prcol <> '') then
                           wsql = wsql||' and '||prcol||' ';
                      end
                 end

       wsql = wsql||
              'GROUP BY COLCON.bdcodemp, BDCODMATRIZ, COLCON.bdcodcol, COLCON.bdref13, COLCON.bdcodver, COLCON.BDCOMPESP, COLCON.BDFORMREFAUX, '||
              'COLCON.BDFORMREF, COLCON.BDFORMVAL ';

       wsql = wsql||') COLCON '||
              'left outer join VW_TVERBAS_REF VERREF on (VERREF.BDCODVER = COLCON.BDCODVER) ';

     end
  else
  if (premissao = 1) then
     begin
       wsql = wsql||
              'SELECT COLCON.BDCODEMP, '||
                  'COLCON.BDCODMATRIZ, '||
                  'COLCON.BDREF13, '||
                  'COLCON.BDCHAVE, '||
                  'COLCON.BDCODCOL, '||
                  'COLCON.BDCODVER, '||
                  'case when (coalesce(VERREF.BDTIPOREFVER, 0) = 4) then COLCON.BDREFV13max else COLCON.BDREFV13sum end BDREFV13, '||
                  'case when (substring(upper(coalesce(VERREF.BDDEDFORMREFAUXVER, ''FALSE'')) from 1 for 1) = ''T'') then COLCON.bdrefauxsum else COLCON.bdrefauxmax end BDREFAUXV13, '||
                  'COLCON.BDVALV13, '||
                  'COLCON.BDIGNREFV13, '||
                  'COLCON.BDIGNVALV13, '||
                  'COLCON.BDORVERBA13, '||
                  'COLCON.BDIGNREFAV13, '||
                  'COLCON.BDCODCENTRO, '||
                  'COLCON.BDCODTPCC, '||
                  'COLCON.BDCODTOMADOR, '||
                  'COLCON.BDCOMPESP, '||
                  'COLCON.BDFORMREFAUX, '||
                  'COLCON.BDFORMREF, '||
                  'COLCON.BDFORMVAL, '||
                  'VERREF.BDTIPOCODVER, '||
                  'VERREF.BDTIPOREFVER, '||
                  'VERREF.BDORDEMTIPOCODVER, '||
                  'VERREF.BDPISVER, '||
                  'COLCON.BDORDEM '||
              'FROM ( '||
                 'SELECT COLCON.BDCODEMP, ';

       if (prpuxafilial = 1) then
         wsql = wsql || ' coalesce(EMP.BDCODMATRIZ, COLCON.BDCODEMP) BDCODMATRIZ,  ';
       else
         wsql = wsql || ' COLCON.BDCODEMP BDCODMATRIZ, ';

       wsql = wsql ||
                     'COLCON.BDREF13, '||
                     'MAX(COLCON.BDCHAVE) BDCHAVE, '||
                     'COLCON.BDCODCOL, '||
                     'COLCON.BDCODVER, '||
                     'SUM(COLCON.BDREFV13) BDREFV13sum, '||
                     'MAX(COLCON.BDREFV13) BDREFV13max, '||
                     'SUM(COLCON.BDREFAUXV13) bdrefauxsum, '||
                     'MAX(COLCON.BDREFAUXV13) bdrefauxmax, '||
                     'SUM(COLCON.BDVALV13) BDVALV13, '||
                     'MAX(COLCON.BDIGNREFV13) BDIGNREFV13, '||
                     'MAX(COLCON.BDIGNVALV13) BDIGNVALV13, '||
                     'MAX(COLCON.BDORVERBA13) BDORVERBA13, '||
                     'MAX(COLCON.BDIGNREFAV13) BDIGNREFAV13, '||
                     'CC.BDCODCENTRO, '||
                     'CC.BDCODTPCC, '||
                     'TOM.BDCODTPCC BDCODTOMADOR, '||
                     'COLCON.BDCOMPESP, '||
                     'COLCON.BDFORMREFAUX, '||
                     'COLCON.BDFORMREF, '||
                     'COLCON.BDFORMVAL, '||
                     'Y.BDORDEM '||
                 'from VRHF_EMP_TVERBA_13_RAT COLCON '||
                 'join TEMPRESAS EMP on (EMP.BDCODEMP = COLCON.BDCODEMP) '||
                 'left outer join VRHF_EMP_T13SAL_RAT y on (y.bdcodemp = COLCON.bdcodemp and y.bdcodcol = COLCON.bdcodcol and y.bdchave = COLCON.bdchave and y.bdref13 = COLCON.bdref13) '||
                 'left outer join vrhf_emp_tprepfn CC on (cc.bdcodemp = y.bdcodemp and cc.bdcodcol = y.bdcodcol and cc.bdordem = y.bdordem) '||
                 'left outer join vrhf_sp_tomador(CC.bdcodtpcc, CC.bdcodcentro) TOM on (tom.bdcodcentro = CC.bdcodcentro and tom.bdcodcencus = cc.bdcodtpcc) '||
                 'where COLCON.BDREF13 = '||prref;

                 if (premp <> '') then
                    begin
                      if (prpuxafilial <> 0) then
                         wsql = wsql||' and (('||premp||') or ('||replace(premp, 'COLCON.BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';
                      else
                         begin
                           wsql = wsql||' and '||premp||' ';
               
                           if (prcol <> '') then
                              wsql = wsql||' and '||prcol||' ';
                         end
                    end

       wsql = wsql||
                 'group by COLCON.bdcodemp, BDCODMATRIZ, COLCON.bdcodcol, COLCON.bdref13, COLCON.bdcodver, CC.BDCODCENTRO, CC.BDCODTPCC, '||
                          'TOM.BDCODTPCC, COLCON.BDCOMPESP, COLCON.BDFORMREFAUX, COLCON.BDFORMREF, COLCON.BDFORMVAL, Y.BDORDEM '||
              ') COLCON '||
              'left outer join VW_VERBAS_REF_ATUAL VERREF on (VERREF.BDCODVER = COLCON.BDCODVER) ';

     end
  else
  if (premissao = 2) then
     begin
       wsql = wsql||
              'SELECT COLCON.BDCODEMP, '||
                  'COLCON.BDCODMATRIZ, '||
                  'COLCON.BDREF13, '||
                  'COLCON.BDCHAVE, '||
                  'COLCON.BDCODCOL, '||
                  'COLCON.BDCODVER, '||
                  'CASE WHEN (coalesce(VERREF.BDTIPOREFVER, 0) = 4) THEN COLCON.BDREFV13max ELSE COLCON.BDREFV13sum END BDREFV13, '||
                  'CASE WHEN (SUBSTRING(UPPER(coalesce(VERREF.BDDEDFORMREFAUXVER, ''FALSE'')) FROM 1 FOR 1) = ''T'') THEN COLCON.bdrefauxsum ELSE COLCON.bdrefauxmax END BDREFAUXV13, '||
                  'COLCON.BDVALV13, '||
                  'COLCON.BDIGNREFV13, '||
                  'COLCON.BDIGNVALV13, '||
                  'COLCON.BDORVERBA13, '||
                  'COLCON.BDIGNREFAV13, '||
                  'COLCON.BDCODCENTRO, '||
                  'COLCON.BDCODTPCC, '||
                  'COLCON.BDCODTOMADOR, '||
                  'COLCON.BDCOMPESP, '||
                  'COLCON.BDFORMREFAUX, '||
                  'COLCON.BDFORMREF, '||
                  'COLCON.BDFORMVAL, '||
                  'VERREF.BDTIPOCODVER, '||
                  'VERREF.BDTIPOREFVER, '||
                  'VERREF.BDORDEMTIPOCODVER, '||
                  'VERREF.BDPISVER, '||
                  'COLCON.BDORDEM '||
              'FROM ( '||
              'SELECT COLCON.BDCODEMP, ';

       if (prpuxafilial = 1) then
         wsql = wsql || ' coalesce(EMP.BDCODMATRIZ, COLCON.BDCODEMP) BDCODMATRIZ,  ';
       else
         wsql = wsql || ' COLCON.BDCODEMP BDCODMATRIZ, ';

       wsql = wsql ||
                  'COLCON.BDREF13, '||
                  'MAX(COLCON.BDCHAVE) BDCHAVE, '||
                  'COLCON.BDCODCOL, '||
                  'COLCON.BDCODVER, '||
                  'SUM(COLCON.BDREFV13) BDREFV13sum, '||
                  'MAX(COLCON.BDREFV13) BDREFV13max, '||
                  'SUM(COLCON.BDREFAUXV13) bdrefauxsum, '||
                  'MAX(COLCON.BDREFAUXV13) bdrefauxmax, '||
                  'SUM(COLCON.BDVALV13) BDVALV13, '||
                  'MAX(COLCON.BDIGNREFV13) BDIGNREFV13, '||
                  'MAX(COLCON.BDIGNVALV13) BDIGNVALV13, '||
                  'MAX(COLCON.BDORVERBA13) BDORVERBA13, '||
                  'MAX(COLCON.BDIGNREFAV13) BDIGNREFAV13, '||
                  'cc.bdcodcentro, '||
                  'cc.bdcodtpcc, '||
                  'tom.bdcodtpcc bdcodtomador, '||
                  'COLCON.BDCOMPESP, '||
                  'COLCON.BDFORMREFAUX, '||
                  'COLCON.BDFORMREF, '||
                  'COLCON.BDFORMVAL, '||
                  'FOLN.BDORDEM '||
              'FROM VRHF_EMP_TVERBA_13_RAT COLCON '||
              'join TEMPRESAS EMP on (EMP.BDCODEMP = COLCON.BDCODEMP) '||
              'LEFT OUTER JOIN VRHF_EMP_T13SAL_RAT FOLN ON (FOLN.bdcodemp = COLCON.bdcodemp AND FOLN.bdcodcol = COLCON.bdcodcol AND FOLN.bdchave = COLCON.bdchave AND FOLN.bdref13 = COLCON.bdref13) '||
              'LEFT OUTER JOIN vrhf_emp_tprepfn cc ON (cc.bdcodemp = FOLN.bdcodemp AND cc.bdcodcol = FOLN.bdcodcol AND cc.bdordem = FOLN.bdordem) '||
              'LEFT OUTER JOIN vrhf_sp_tomador(cc.bdcodtpcc, cc.bdcodcentro) tom ON (tom.bdcodcentro = cc.bdcodcentro AND tom.bdcodcencus = cc.bdcodtpcc) '||
              'where COLCON.BDREF13 = '||prref;

              if (premp <> '') then
                 begin
                   if (prpuxafilial <> 0) then
                      wsql = wsql||' and (('||premp||') or ('||replace(premp, 'COLCON.BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';
  else
                      begin
                        wsql = wsql||' and '||premp||' ';

                        if (prcol <> '') then
                           wsql = wsql||' and '||prcol||' ';
                      end
                 end

       wsql = wsql||
              'GROUP BY COLCON.bdcodemp, BDCODMATRIZ, COLCON.bdcodcol, COLCON.bdref13, COLCON.bdcodver, cc.bdcodcentro, cc.bdcodtpcc, tom.bdcodtpcc, '||
                       'COLCON.BDCOMPESP, COLCON.BDFORMREFAUX, COLCON.BDFORMREF, COLCON.BDFORMVAL, FOLN.BDORDEM '||
              ') COLCON '||
              'LEFT OUTER JOIN VW_VERBAS_REF_ATUAL VERREF ON (VERREF.bdcodver = COLCON.bdcodver) ';

     end
  else
     begin
       wsql = wsql||
              'select COLCON.*, ';

       if (prpuxafilial = 1) then
         wsql = wsql || ' coalesce(EMP.BDCODMATRIZ, COLCON.BDCODEMP) BDCODMATRIZ,  ';
       else
         wsql = wsql || ' COLCON.BDCODEMP BDCODMATRIZ, ';

       wsql = wsql ||
                  'cast(null as integer) bdcodcentro, '||
                  'cast(null as integer) bdcodtpcc, '||
                  'cast(null as integer) bdcodtomador, '||
                  'cast(null as integer) bdordem, '||
                  'VERREF.BDTIPOCODVER, '||
                  'VERREF.BDTIPOREFVER, '||
                  'VERREF.BDORDEMTIPOCODVER, '||
                  'VERREF.BDPISVER '||
              'from VRHF_EMP_TVERBA_13_RAT COLCON '||
              'join TEMPRESAS EMP on (EMP.BDCODEMP = COLCON.BDCODEMP) '||
              'left outer join VW_VERBAS_REF_ATUAL VERREF ON (VERREF.bdcodver = COLCON.bdcodver) '||
              'where COLCON.BDREF13 = '||prref;

              if (premp <> '') then
                 begin
                   if (prpuxafilial <> 0) then
                      wsql = wsql||' and (('||premp||') or ('||replace(premp, 'COLCON.BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';
                   else
                      begin
                        wsql = wsql||' and '||premp||' ';
            
                        if (prcol <> '') then
                           wsql = wsql||' and '||prcol||' ';
                      end
                 end
     end

  wsql = wsql||') COLCON '||
         'join ';

  if (premissao <= 0) then
     begin
       wsql = wsql||'('||
              'SELECT COLCON.bdcodemp, '||
                     'COLCON.bdref13, cast(null as integer) bdchave, COLCON.bdcodcol, cast(null as integer) bdordem, MAX(COLCON.bdmesesprop13) BDMESESPROP13, '||
                     'SUM(COLCON.bdbaseir13) BDBASEIR13, SUM(COLCON.bdbasefgts13) BDBASEFGTS13, '||
                     'SUM(COLCON.bdfgts13) BDFGTS13, SUM(COLCON.bdfgtscs13) BDFGTSCS13, MAX(COLCON.bddatabaixa13) BDDATABAIXA13, MAX(COLCON.bdrefbaixa13) BDREFBAIXA13, '||
                     'MAX(COLCON.bdpercir13) BDPERCIR13, SUM(COLCON.bdvalorir13) BDVALORIR13, '||
--                     'SUM(COLCON.bdbaseinss13) BDBASEINSS13, MAX(COLCON.bdpercinss13) BDPERCINSS13, '||
                     'MAX(COLCON.bdpercinss13) BDPERCINSS13, '||
                     'SUM(COLCON.bdvalorinss13) BDVALORINSS13, SUM(COLCON.bdbrais13) BDBRAIS13, '||
                     'MAX(COLCON.bdsalbase13) BDSALBASE13, MAX(COLCON.bddep13) BDDEP13, '||
                     'MAX(COLCON.bdarreprov13) BDARREPROV13, MAX(COLCON.bdarredesc13) BDARREDESC13, '||
                     'MAX(COLCON.bdval13) BDVAL13, MAX(COLCON.bdbsalfam13) BDBSALFAM13, '||
                     'MAX(COLCON.bdsalfam13) BDSALFAM13, MAX(COLCON.bdano13) BDANO13, SUM(COLCON.bdbasepis13) BDBASEPIS13, '||
                     'SUM(COLCON.bdbsalmatemp13) BDBSALMATEMP13, SUM(COLCON.bdsalmatemp13) BDSALMATEMP13, SUM(COLCON.bdbratapo13) BDBRATAPO13, '||
                     'SUM(COLCON.bdratapo13) BDRATAPO13, MAX(COLCON.bdestprov13) BDESTPROV13, MAX(COLCON.bdcredito13) BDCREDITO13, '||
                     'MAX(COLCON.bddebito13) BDDEBITO13, SUM(COLCON.bdliquido) BDLIQUIDO, MAX(COLCON.bddatapgto13) BDDATAPGTO13, '||
                     'MAX(COLCON.bdbinssmv13) BDBINSSMV13, MAX(COLCON.bdjan) BDJAN, MAX(COLCON.bdfev) BDFEV, '||
                     'MAX(COLCON.bdmar) BDMAR, MAX(COLCON.bdabr) BDABR, MAX(COLCON.bdmai) BDMAI, MAX(COLCON.bdjun) BDJUN, '||
                     'MAX(COLCON.bdjul) BDJUL, MAX(COLCON.bdago) BDAGO, MAX(COLCON.bdset) BDSET, MAX(COLCON.bdout) BDOUT, '||
                     'MAX(COLCON.bdnov) BDNOV, MAX(COLCON.bddez) BDDEZ, MAX(COLCON.bddataproc13) BDDATAPROC13, MAX(COLCON.bdhoraproc13) BDHORAPROC13, '||
                     'cast(null as integer) bdcodcentro, cast(null as integer) bdcodtpcc, cast(null as integer) bdcodtomador '||
              'FROM VRHF_EMP_T13SAL_RAT COLCON '||
              'join TEMPRESAS EMP on (EMP.BDCODEMP = COLCON.BDCODEMP) '||
              'where COLCON.BDREF13 = '||prref||' ';

       if (premp <> '') then
          begin
            if (prpuxafilial <> 0) then
               wsql = wsql||' and (('||premp||') or ('||replace(premp, 'COLCON.BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';
            else
               begin
                 wsql = wsql||' and '||premp||' ';
     
                 if (prcol <> '') then
                    wsql = wsql||' and '||prcol||' ';
               end
          end

       wsql = wsql||
              ' group by COLCON.bdcodemp, COLCON.bdcodcol, COLCON.bdref13 ';

       wsql = wsql||') FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.bdref13 = COLCON.bdref13) ';

     end
  else
  if (premissao = 1) then
     begin
       wsql = wsql||'('||
              'select COLCON.bdcodemp, COLCON.bdref13, MAX(COLCON.bdchave) bdchave, COLCON.bdcodcol, COLCON.bdordem, MAX(COLCON.bdmesesprop13) BDMESESPROP13, '||
                     'SUM(COLCON.bdbaseir13) BDBASEIR13, SUM(COLCON.bdbasefgts13) BDBASEFGTS13, '||
                     'SUM(COLCON.bdfgts13) BDFGTS13, SUM(COLCON.bdfgtscs13) BDFGTSCS13, MAX(COLCON.bddatabaixa13) BDDATABAIXA13, MAX(COLCON.bdrefbaixa13) BDREFBAIXA13, '||
                     'MAX(COLCON.bdpercir13) BDPERCIR13, SUM(COLCON.bdvalorir13) BDVALORIR13, '||
--                     'SUM(COLCON.bdbaseinss13) BDBASEINSS13, MAX(COLCON.bdpercinss13) BDPERCINSS13, '||
                     'MAX(COLCON.bdpercinss13) BDPERCINSS13, '||
                     'SUM(COLCON.bdvalorinss13) BDVALORINSS13, SUM(COLCON.bdbrais13) BDBRAIS13, '||
                     'MAX(COLCON.bdsalbase13) BDSALBASE13, MAX(COLCON.bddep13) BDDEP13, '||
                     'MAX(COLCON.bdarreprov13) BDARREPROV13, MAX(COLCON.bdarredesc13) BDARREDESC13, '||
                     'MAX(COLCON.bdval13) BDVAL13, MAX(COLCON.bdbsalfam13) BDBSALFAM13, '||
                     'MAX(COLCON.bdsalfam13) BDSALFAM13, MAX(COLCON.bdano13) BDANO13, SUM(COLCON.bdbasepis13) BDBASEPIS13, '||
                     'SUM(COLCON.bdbsalmatemp13) BDBSALMATEMP13, SUM(COLCON.bdsalmatemp13) BDSALMATEMP13, SUM(COLCON.bdbratapo13) BDBRATAPO13, '||
                     'SUM(COLCON.bdratapo13) BDRATAPO13, MAX(COLCON.bdestprov13) BDESTPROV13, MAX(COLCON.bdcredito13) BDCREDITO13, '||
                     'MAX(COLCON.bddebito13) BDDEBITO13, SUM(COLCON.bdliquido) BDLIQUIDO, MAX(COLCON.bddatapgto13) BDDATAPGTO13, '||
                     'MAX(COLCON.bdbinssmv13) BDBINSSMV13, MAX(COLCON.bdjan) BDJAN, MAX(COLCON.bdfev) BDFEV, '||
                     'MAX(COLCON.bdmar) BDMAR, MAX(COLCON.bdabr) BDABR, MAX(COLCON.bdmai) BDMAI, MAX(COLCON.bdjun) BDJUN, '||
                     'MAX(COLCON.bdjul) BDJUL, MAX(COLCON.bdago) BDAGO, MAX(COLCON.bdset) BDSET, MAX(COLCON.bdout) BDOUT, '||
                     'MAX(COLCON.bdnov) BDNOV, MAX(COLCON.bddez) BDDEZ, MAX(COLCON.bddataproc13) BDDATAPROC13, MAX(COLCON.bdhoraproc13) BDHORAPROC13 '||
              'from VRHF_EMP_T13SAL_RAT COLCON '||
              'join TEMPRESAS EMP on (EMP.BDCODEMP = COLCON.BDCODEMP) ';

              if (premp <> '') then
                 begin
                   if (prpuxafilial <> 0) then
                      wsql = wsql||' and (('||premp||') or ('||replace(premp, 'COLCON.BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';
                   else
                      begin
                        wsql = wsql||' and '||premp||' ';
            
                        if (prcol <> '') then
                           wsql = wsql||' and '||prcol||' ';
                      end
                 end

       wsql = wsql||
              'group by COLCON.bdcodemp, BDCODMATRIZ, COLCON.bdcodcol, COLCON.bdref13, COLCON.bdordem ';

       wsql = wsql||') FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.bdref13 = COLCON.bdref13 and colcon.bdchave = foln.bdchave) ';
     end
  else
  if (premissao = 2) then
     begin
       wsql = wsql||'('||
              'SELECT COLCON.bdcodemp, COLCON.bdref13, MAX(COLCON.bdchave) BDCHAVE, '||
                     'COLCON.bdcodcol, COLCON.bdordem, MAX(COLCON.bdmesesprop13) BDMESESPROP13, '||
                     'SUM(COLCON.bdbaseir13) BDBASEIR13, SUM(COLCON.bdbasefgts13) BDBASEFGTS13, '||
                     'SUM(COLCON.bdfgts13) BDFGTS13, SUM(COLCON.bdfgtscs13) BDFGTSCS13, MAX(COLCON.bddatabaixa13) BDDATABAIXA13, MAX(COLCON.bdrefbaixa13) BDREFBAIXA13, '||
                     'MAX(COLCON.bdpercir13) BDPERCIR13, SUM(COLCON.bdvalorir13) BDVALORIR13, '||
--                     'SUM(COLCON.bdbaseinss13) BDBASEINSS13, MAX(COLCON.bdpercinss13) BDPERCINSS13, '||
                     'MAX(COLCON.bdpercinss13) BDPERCINSS13, '||
                     'SUM(COLCON.bdvalorinss13) BDVALORINSS13, SUM(COLCON.bdbrais13) BDBRAIS13, '||
                     'MAX(COLCON.bdsalbase13) BDSALBASE13, MAX(COLCON.bddep13) BDDEP13, '||
                     'MAX(COLCON.bdarreprov13) BDARREPROV13, MAX(COLCON.bdarredesc13) BDARREDESC13, '||
                     'MAX(COLCON.bdval13) BDVAL13, MAX(COLCON.bdbsalfam13) BDBSALFAM13, '||
                     'MAX(COLCON.bdsalfam13) BDSALFAM13, MAX(COLCON.bdano13) BDANO13, SUM(COLCON.bdbasepis13) BDBASEPIS13, '||
                     'SUM(COLCON.bdbsalmatemp13) BDBSALMATEMP13, SUM(COLCON.bdsalmatemp13) BDSALMATEMP13, SUM(COLCON.bdbratapo13) BDBRATAPO13, '||
                     'SUM(COLCON.bdratapo13) BDRATAPO13, MAX(COLCON.bdestprov13) BDESTPROV13, MAX(COLCON.bdcredito13) BDCREDITO13, '||
                     'MAX(COLCON.bddebito13) BDDEBITO13, SUM(COLCON.bdliquido) BDLIQUIDO, MAX(COLCON.bddatapgto13) BDDATAPGTO13, '||
                     'MAX(COLCON.bdbinssmv13) BDBINSSMV13, MAX(COLCON.bdjan) BDJAN, MAX(COLCON.bdfev) BDFEV, '||
                     'MAX(COLCON.bdmar) BDMAR, MAX(COLCON.bdabr) BDABR, MAX(COLCON.bdmai) BDMAI, MAX(COLCON.bdjun) BDJUN, '||
                     'MAX(COLCON.bdjul) BDJUL, MAX(COLCON.bdago) BDAGO, MAX(COLCON.bdset) BDSET, MAX(COLCON.bdout) BDOUT, '||
                     'MAX(COLCON.bdnov) BDNOV, MAX(COLCON.bddez) BDDEZ, MAX(COLCON.bddataproc13) bddataproc13, MAX(COLCON.bdhoraproc13) BDHORAPROC13 '||
              'FROM VRHF_EMP_T13SAL_RAT COLCON '||
              'join TEMPRESAS EMP on (EMP.BDCODEMP = COLCON.BDCODEMP) '||
              'where COLCON.BDREF13 = '||prref;

              if (premp <> '') then
                 begin
                   if (prpuxafilial <> 0) then
                      wsql = wsql||' and (('||premp||') or ('||replace(premp, 'COLCON.BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';
  else
                      begin
                        wsql = wsql||' and '||premp||' ';

                        if (prcol <> '') then
                           wsql = wsql||' and '||prcol||' ';
                      end
                 end

  wsql = wsql||
              'GROUP BY COLCON.bdcodemp, COLCON.bdcodcol, COLCON.bdref13, COLCON.BDORDEM ';

       wsql = wsql||
              ') FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREF13 = COLCON.BDREF13 AND COLCON.BDCHAVE = FOLN.BDCHAVE) ';
     end
  else
     begin
       wsql = wsql||'('||
              'select COLCON.* '||
              'from VRHF_EMP_T13SAL_RAT COLCON '||
              'join TEMPRESAS EMP on (EMP.BDCODEMP = COLCON.BDCODEMP) '||
              'where COLCON.BDREF13 = '||prref;

              if (premp <> '') then
                 begin
                   if (prpuxafilial <> 0) then
                      wsql = wsql||' and (('||premp||') or ('||replace(premp, 'COLCON.BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';
                   else
                      begin
                        wsql = wsql||' and '||premp||' ';
            
                        if (prcol <> '') then
                           wsql = wsql||' and '||prcol||' ';
                      end
                 end

       wsql = wsql||
              ') FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.bdref13 = COLCON.bdref13 and foln.bdchave = colcon.bdchave) ';
     end


  wsql = wsql||
         'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = COLCON.BDCODVER) '||
         'join TEMPRESAS EMP on (EMP.BDCODEMP = COLCON.BDCODEMP) ';

  wsql = wsql||'where COLCON.BDREF13 = '||prref||' ' ;

  wsql = wsql||'order by COLCON.BDCODEMP,COLCON.BDCODCOL,COLCON.BDCODCENTRO, COLCON.BDCODTPCC, COLCON.BDREF13, COLCON.BDCODVER ';

  wempatu = 0;
  wcolatu = 0;
  wempok  = 0;
  BASE_INSS = 0;
  wordematu = -1;

  for execute statement wsql into
    :CODIGO_FILIAL,
    :CODIGO_EMPRESA,
    :CODIGO_COLABORADOR,
    :REFERENCIA_FOLHA,
    :CODIGO_VERBA,
    :REFERENCIA_AUXILIAR_VERBA,
    :REFERENCIA_VERBA,
    :wvalv,
    :BDORDEM,
    :CNPJ_EMPRESA,
    :DESCRICAO_VERBA,
    :BDTIPOCODVER,
    :SALARIO_BASE,
--    :BASE_INSS,
    :INSS_FOLHA,
    :wbfgts,
    :wfgts,
    :IRRF_FOLHA,
    :BASE_RAIS,
    :REFERENCIAAUX,
    :DESCRICAO_RED_VERBA,
    :PISVER,
    :BDORDEMTIPOCODVER,
    :CLASSIFICA_VERBA,
    :SALARIO_FAMILIA,
    :BDORDEMVER,
    :BDTIPOREFVER,
    :VINSSFN,
    :BDCODCENTRO,
    :BDCODTPCC
  do
    begin
      if (wempatu <> CODIGO_FILIAL) then
         begin
           wempatu = CODIGO_FILIAL;
           wcolatu = 0;
           WCHAVEATUAL = '';

           BDCODENQFED   = null;
           BDSIMPLESGPS  = null;
           BDCCATVCONCOM = null;
           BDRATEIO13SAL = null;

           select first 1 BDCODENQFED from TENQFED where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC into :BDCODENQFED;
           select first 1 BDSIMPLESGPS, BDCCATVCONCOM, BDRATEIO13SAL from VRHF_BASE_TEMPGPS where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC into :BDSIMPLESGPS, :BDCCATVCONCOM, :BDRATEIO13SAL;
           select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = :wempatu and BDREFEMP <= :prref order by BDREFEMP DESC into :BDREFHOREMP;

           BDREFHOREMP   = upper(coalesce(BDREFHOREMP, 'FALSE'));
           BDCCATVCONCOM = upper(coalesce(BDCCATVCONCOM, 'FALSE'));

           NOME_EMPRESA     = null;
           ENDERECO_EMPRESA = null;
           NUMERO_EMPRESA   = null;
           BAIRRO_EMPRESA   = null;
           CEP_EMPRESA      = null;
           COMPL_EMPRESA    = null;
           wcodcid          = null;

           -- Sol.142437 | Leonardo Schwab | 15/12/2020 | Caso o parâmetro de puxar filiais estiver selecionado busca as informações da Matriz.
           if (prpuxafilial = 1) then
             begin
           select first 1 BDNOMEMP, trim(coalesce(BDENDEMP, '''')), BDNUMEMP, BDBAIEMP, BDCEPEMP, BDCOMPLEMP, BDCODCID
           from TEMPRESAS_REF
               where BDCODEMP = :CODIGO_EMPRESA
               order by BDREFEMP DESC
               into :NOME_EMPRESA, :ENDERECO_EMPRESA, :NUMERO_EMPRESA, :BAIRRO_EMPRESA, :CEP_EMPRESA, :COMPL_EMPRESA, :wcodcid;
             end
           else
             begin
               select first 1 BDNOMEMP, trim(coalesce(BDENDEMP, '''')), BDNUMEMP, BDBAIEMP, BDCEPEMP, BDCOMPLEMP, BDCODCID
               from TEMPRESAS_REF
           where BDCODEMP = :wempatu
           order by BDREFEMP DESC
           into :NOME_EMPRESA, :ENDERECO_EMPRESA, :NUMERO_EMPRESA, :BAIRRO_EMPRESA, :CEP_EMPRESA, :COMPL_EMPRESA, :wcodcid;
             end

           select first 1 E.BDCODEMP
           from SP_EMPRESAS_USU(:wempatu) E
           where E.BDCODEMP = :wempatu
           into :wempok;

           wempok = coalesce(wempok, 0);

           wcoduf         = null;
           CIDADE_EMPRESA = null;
           select first 1 BDNOMCID, BDCODUF from TCIDADE where BDCODCID = :wcodcid into :CIDADE_EMPRESA, :wcoduf;

           UF_EMPRESA = null;
           select first 1 BDSIGLAUF from TUF where BDCODUF = :wcoduf into :UF_EMPRESA;
         end

      if (wempok = wempatu) then
         begin
           wcodcentrochave = coalesce(bdcodcentro,0);
           wcodtpccchave = coalesce(bdcodtpcc,0);           

      if (CODIGO_COLABORADOR || '-' || wcodcentrochave || '-' || wcodtpccchave <> WCHAVEATUAL)   then
         begin
           wcolatu = CODIGO_COLABORADOR;
           WCHAVEATUAL = CODIGO_COLABORADOR || '-' || wcodcentrochave || '-' || wcodtpccchave;


           NOME_COLABORADOR     = null;
           ADMISSAO_COLABORADOR = null;
           CPF_COLABORADOR      = null;
           PIS_COLABORADOR      = null;
           CTPS_COL             = null;
           SERIE_CTPS           = null;
           HORAS_MENSAIS        = null;
           RAT_APO_COL          = null;
           GRUPO_CLASSE         = null;
           BFGTS_MESPOST        = null;
           FGTS_MESPOST         = null;
           BDCATEGORIAESOCIAL   = null;
           BDCONTRCOL           = null;
                BDCODSINTRAB         = null;
           wdepir               = 0;
           wdepsf               = 0;
     
                select first 1 CASE WHEN (FIS.BDNMSOCIAL <> '' and PAR.bdusanomesocial = 'TRUE') THEN FIS.BDNMSOCIAL ELSE cad.BDNOMCOL END Nome_Colaborador from VRH_EMP_TCOLCON_CAD cad
           left outer join VRH_EMP_TCOLCON_FIS FIS ON (FIS.BDCODEMP = cad.BDCODEMP AND FIS.BDCODCOL = cad.BDCODCOL AND FIS.bdrefcol=cad.bdrefcol)
           left outer join(select a.bdcodemp,max(a.bdrefemp)bdrefemp from VRHF_BASE_TEMPPAR a group by a.bdcodemp) pmax on  (pmax.BDCODEMP = cad.BDCODEMP)
           left outer join VRHF_BASE_TEMPPAR PAR  on (par.bdcodemp=pmax.bdcodemp and par.bdrefemp=pmax.bdrefemp)  --Sol.161198 Quando tiver nome social e empresas opatar por usar ele, sera usado no nome do col original
           where cad.BDCODEMP = :wempatu and cad.BDCODCOL = :wcolatu and cad.BDREFCOL <= :prref
                order by cad.BDREFCOL DESC into :NOME_COLABORADOR; 
           select first 1 BDDATAADMCOL, BDCPFCOL, BDCONTRCOL from VRH_EMP_TCOLCON where BDCODEMP = :wempatu and BDCODCOL = :wcolatu into :ADMISSAO_COLABORADOR, :CPF_COLABORADOR, :BDCONTRCOL;
           select first 1 BDPISCOL from VRH_EMP_TCOLCON_DOCREF where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :PIS_COLABORADOR;
           select first 1 BDCTPSCOL, BDSERIECTPSCOL from VRH_EMP_TCOLCON_DOCREF where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :CTPS_COL, :SERIE_CTPS;
           select first 1 BDHORASMENSAISCOL, BDNRODEPSALFAMCOL from VRHF_EMP_TCOL_CALC where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :HORAS_MENSAIS, :wdepsf;
           select first 1 BDPERCRATCOL, BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :RAT_APO_COL, :BDCATEGORIAESOCIAL;
           select first 1 BDNRODEPIRCOL from VRHF_EMP_TCOLCON_CALC where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :wdepir;
                select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :BDCODSINTRAB;
     
           CTPS_COL      = trim(coalesce(CTPS_COL, ''));
           SERIE_CTPS    = trim(coalesce(SERIE_CTPS, ''));
           HORAS_MENSAIS = coalesce(HORAS_MENSAIS, 0);
           RAT_APO_COL   = coalesce(RAT_APO_COL, 0);
           BDCONTRCOL    = coalesce(BDCONTRCOL, 0);
           wdepir        = coalesce(wdepir, 0);
           wdepsf        = coalesce(wdepsf, 0);
     
           if (CTPS_COL = '' and SERIE_CTPS = '') then
              begin
                wcolatu = CODIGO_COLABORADOR;
     
                NOME_COLABORADOR     = null;
                ADMISSAO_COLABORADOR = null;
                CPF_COLABORADOR      = null;
                PIS_COLABORADOR      = null;
                CTPS_COL             = null;
                SERIE_CTPS           = null;
                HORAS_MENSAIS        = null;
                RAT_APO_COL          = null;
                GRUPO_CLASSE         = null;
                BFGTS_MESPOST        = null;
                FGTS_MESPOST         = null;
                BDCATEGORIAESOCIAL   = null;
                BDCONTRCOL           = null;
                wdepir               = 0;
                wdepsf               = 0;
                BDCODCLA             = null;
                     --BDCODSINTRAB         = null;
                BDCODTFUC            = null;
     
                     select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :NOME_COLABORADOR;
                select first 1 BDDATAADMCOL, BDCPFCOL, BDCONTRCOL from VRH_EMP_TCOLCON where BDCODEMP = :wempatu and BDCODCOL = :wcolatu into :ADMISSAO_COLABORADOR, :CPF_COLABORADOR, :BDCONTRCOL;
                select first 1 BDPISCOL from VRH_EMP_TCOLCON_DOCREF where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :PIS_COLABORADOR;
                select first 1 BDCTPSCOL, BDSERIECTPSCOL from VRH_EMP_TCOLCON_DOCREF where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :CTPS_COL, :SERIE_CTPS;
                select first 1 BDHORASMENSAISCOL, BDNRODEPSALFAMCOL from VRHF_EMP_TCOL_CALC where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :HORAS_MENSAIS, :wdepsf;
                select first 1 BDPERCRATCOL, BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :RAT_APO_COL, :BDCATEGORIAESOCIAL;
                select first 1 BDNRODEPIRCOL from VRHF_EMP_TCOLCON_CALC where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :wdepir;
                     --select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :BDCODSINTRAB;
     
                CTPS_COL      = trim(coalesce(CTPS_COL, ''));
                SERIE_CTPS    = trim(coalesce(SERIE_CTPS, ''));
                HORAS_MENSAIS = coalesce(HORAS_MENSAIS, 0);
                RAT_APO_COL   = coalesce(RAT_APO_COL, 0);
                BDCONTRCOL    = coalesce(BDCONTRCOL, 0);
                wdepir        = coalesce(wdepir, 0);
                wdepsf        = coalesce(wdepsf, 0);
     
                if (CTPS_COL = '' and SERIE_CTPS = '') then
                   begin
                     CTPS_COL   = substring(replace(replace(CPF_COLABORADOR, '.', ''), '-', '') from 1 for 7);
                     SERIE_CTPS = substring(replace(replace(CPF_COLABORADOR, '.', ''), '-', '') from 8 for 4);
                   end
     
                wplafuc  = null;
                wcodtfuc = null;
                select first 1 BDCODPLAFUC, BDCODTFUC from VRH_EMP_TCOL_VINCDIA where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDDATACOL <= :prultdia order by BDDATACOL DESC into :wplafuc, :wcodtfuc;
     
                BDCODTFUC = coalesce(wcodtfuc,0);
                FUNCAO_COLABORADOR = null;
                CBO_COL            = null;
     
                if (wplafuc is not null and wcodtfuc is not null) then
                   begin
                     if (prfucdet <> 0) then
                        select first 1 BDDESCFUNCDET, BDCODCBO from VRH_FUNCOES_TFUC where BDCODPLAFUC = :wplafuc and BDCODTFUC = :wcodtfuc into :FUNCAO_COLABORADOR, :CBO_COL;
     
                     if (trim(coalesce(FUNCAO_COLABORADOR, '')) = '') then
                        select first 1 BDDESCTFUC, BDCODCBO from VRH_FUNCOES_TFUC where BDCODPLAFUC = :wplafuc and BDCODTFUC = :wcodtfuc into :FUNCAO_COLABORADOR, :CBO_COL;
                   end
     
                wcodcla = null;
                select first 1 BDCODCLA from VRH_EMP_TCOLCON_VINC where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :wcodcla;
     
                BDCODCLA = coalesce(wcodcla, 0);
                if (coalesce(wcodcla, 0) <> 0) then
                   select first 1 BDGRUPOCLA from VRH_BASE_TCLASSE where BDCODCLA = :wcodcla into :GRUPO_CLASSE;
     
                GRUPO_CLASSE = coalesce(GRUPO_CLASSE, 0);
     
                BASE_FGTS            = null;
                FGTS_FOLHA           = null;
                CTPS_COL   = substring(replace(replace(CPF_COLABORADOR, '.', ''), '-', '') from 1 for 7);
                SERIE_CTPS = substring(replace(replace(CPF_COLABORADOR, '.', ''), '-', '') from 8 for 4);
              end
     
           wplafuc  = null;
           wcodtfuc = null;
           select first 1 BDCODPLAFUC, BDCODTFUC from VRH_EMP_TCOL_VINCDIA where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDDATACOL <= :prultdia order by BDDATACOL DESC into :wplafuc, :wcodtfuc;
     
           FUNCAO_COLABORADOR = null;
           CBO_COL            = null;
     
           if (wplafuc is not null and wcodtfuc is not null) then
              begin
                if (prfucdet <> 0) then
                   select first 1 BDDESCFUNCDET, BDCODCBO from VRH_FUNCOES_TFUC where BDCODPLAFUC = :wplafuc and BDCODTFUC = :wcodtfuc into :FUNCAO_COLABORADOR, :CBO_COL;
     
                if (trim(coalesce(FUNCAO_COLABORADOR, '')) = '') then
                   select first 1 BDDESCTFUC, BDCODCBO from VRH_FUNCOES_TFUC where BDCODPLAFUC = :wplafuc and BDCODTFUC = :wcodtfuc into :FUNCAO_COLABORADOR, :CBO_COL;
              end
     
           wcodcla = null;
           select first 1 BDCODCLA from VRH_EMP_TCOLCON_VINC where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :prref order by BDREFCOL DESC into :wcodcla;
     
           if (coalesce(wcodcla, 0) <> 0) then
              select first 1 BDGRUPOCLA from VRH_BASE_TCLASSE where BDCODCLA = :wcodcla into :GRUPO_CLASSE;
     
           GRUPO_CLASSE = coalesce(GRUPO_CLASSE, 0);
     
           BASE_FGTS            = null;
           FGTS_FOLHA           = null;
           RESCISAO_COLABORADOR = null;
           MOTIVO_RESCISAO      = null;
           TIPO_RESCISAO        = null;
           BDTEMGRRF            = null;
           wrefrescisao         = null;
           wgrrfpres            = null;
           wcodres              = null;
           wfgtsmensant         = null;
     
           select first 1 R.BDDATARESCISAO, R.BDREFRESCISAO, R.BDCODPRES, R.BDCALCFGTSMESANT, PR.BDGRRFPRES, substring(PR.BDDESCPRES from 1 for 110), PR.BDTIPOMOV
           from VRH_EMP_TRESCISAO R
           join VRH_BASE_TPREPRESC PR on (PR.BDCODPRES = R.BDCODPRES)
           where R.BDCODEMP = :wempatu and R.BDCODCOL = :wcolatu
           into :RESCISAO_COLABORADOR, :wrefrescisao, :wcodres, :wfgtsmensant, :wgrrfpres, :MOTIVO_RESCISAO, :TIPO_RESCISAO;
     
           wrefrescisao = coalesce(wrefrescisao, 0);
           wgrrfpres    = coalesce(wgrrfpres, 0);
           wcodres      = coalesce(wcodres, 0);
           wfgtsmensant = upper(coalesce(wfgtsmensant, 'FALSE'));
     
           if (wrefrescisao <> REFERENCIA_FOLHA) then
              begin
                RESCISAO_COLABORADOR = null;
                MOTIVO_RESCISAO      = null;
                TIPO_RESCISAO        = 0;
              end
     
           if (wrefrescisao = prproximaref and wfgtsmensant = 'TRUE' and wgrrfpres in (1,2)) then
              begin
                BASE_FGTS     = 0;
                FGTS_FOLHA    = 0;
                BFGTS_MESPOST = wbfgts;
                FGTS_MESPOST  = wfgts;
              end
           else
              begin
                BASE_FGTS     = wbfgts;
                FGTS_FOLHA    = wfgts;
                BFGTS_MESPOST = 0;
                FGTS_MESPOST  = 0;
              end
     
           BASE_FGTS     = coalesce(BASE_FGTS, 0);
           FGTS_FOLHA    = coalesce(FGTS_FOLHA, 0);
           BFGTS_MESPOST = coalesce(BFGTS_MESPOST, 0);
           FGTS_MESPOST  = coalesce(FGTS_MESPOST, 0);
     
           if (wrefrescisao = REFERENCIA_FOLHA and wgrrfpres in (1,2)) then
              BDTEMGRRF = 1;
           else
              BDTEMGRRF = 0;
     
           DATA_PAG_IR = cast((substring(cast(REFERENCIA_FOLHA as varchar(6)) from 5 for 2)||'-20-'||substring(cast(REFERENCIA_FOLHA as varchar(6)) from 1 for 4)) as date);
     
           select count(*)
           from VW_VRH_EMP_TDEP_REF
           where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and
                 upper(coalesce(BDSALFAMDPN, 'FALSE')) = 'TRUE' and
                 coalesce(BDPARENESCODPN, 0) in (0, 4, 5, 6, 11) and
                 coalesce(BDPARENESCODPN, 0) <> 3 and
                 ((select BDAAAAMM
                   from AAAAMM(coalesce(BDDATANASCDPN, BDDATAENTREDPN))) <= :REFERENCIA_FOLHA) and
                 ((BDDATABAUXADPN is null) or ((select BDAAAAMM
                                                from AAAAMM(BDDATABAUXADPN)) > :REFERENCIA_FOLHA)) and
                 ((upper(coalesce(BDINVALIDODPN, 'FALSE')) = 'TRUE') or ((BDDATANASCDPN is not null) and
                 (:REFERENCIA_FOLHA - cast((select BDAAAAMM
                                            from AAAAMM(BDDATANASCDPN)) as integer) <= 1400)))
           into :DEPSF;
     
           DEPSF = coalesce(DEPSF, 0);
     
           select count(*)
           from VW_VRH_EMP_TDEP_REF
           where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and
                 upper(coalesce(BDDEPIRDPN, 'FALSE')) = 'TRUE' and
                 coalesce(BDPARENESCODPN, 0) <> 3 and
                 (select BDAAAAMM
                  from AAAAMM(coalesce(BDDATANASCDPN, BDDATAENTREDPN))) <= :REFERENCIA_FOLHA and
                 ((BDDATABAUXADPN is null) or ((select BDAAAAMM
                                                from AAAAMM(BDDATABAUXADPN)) > :REFERENCIA_FOLHA)) and
                 ((BDREFIRDPN is null) or (coalesce(BDREFIRDPN, 0) = 0) or (coalesce(BDREFIRDPN, 0) >= :REFERENCIA_FOLHA)) and
                 ((upper(coalesce(BDINVALIDODPN, 'FALSE')) = 'TRUE') or (BDREFIRDPN >= :REFERENCIA_FOLHA) or ((coalesce(BDPARENESCODPN, 0) in (0, 4, 5, 6)) and
                 (:REFERENCIA_FOLHA - cast((select BDAAAAMM
                                            from AAAAMM(BDDATANASCDPN)) as integer) < 2200)) or (coalesce(BDPARENESCODPN, 0) in (1, 2)))
           into :DEPIR;
     
           DEPIR = coalesce(DEPIR, 0);
     
           if (DEPSF + DEPIR <= 0) then
              begin
                DEPSF = wdepsf;
                DEPIR = wdepir;
              end
     
           BASE_INSS13_MULTVINC  = null;
           BASE_IR13_MULTVINC    = null;
           VALOR_INSS13_MULTVINC = null;
           VALOR_IR13_MULTVINC   = null;
     
           select first 1 BDBASEINSS13COL, BDVALORINSS13COL, BDBASEIRRF13COL, BDVALORIRRF13COL
           from  SP_VRHF_EMP_TCOLCON_MVINC('BDCODEMP = '||:wempatu, 'BDCODCOL = '||:wcolatu, :REFERENCIA_FOLHA)
           into :BASE_INSS13_MULTVINC, :VALOR_INSS13_MULTVINC, :BASE_IR13_MULTVINC, :VALOR_IR13_MULTVINC;
     
           BASE_INSS13_MULTVINC  = coalesce(BASE_INSS13_MULTVINC, 0);
           BASE_IR13_MULTVINC    = coalesce(BASE_IR13_MULTVINC, 0);
           VALOR_INSS13_MULTVINC = coalesce(VALOR_INSS13_MULTVINC, 0);
           VALOR_IR13_MULTVINC   = coalesce(VALOR_IR13_MULTVINC, 0);
     
                BASE_INSS     = 0;
                BASE_PIS      = 0;
                BDSALFAM13GPS = 0;
                wvalsalfam13  = 0;
     
                if (coalesce(premissao, 0) = 0) then
                   wsqlinss = 'select case when VERREF.BDTIPOCODVER = 1 then FN.BDVALV13 * -1 when coalesce(VERREF.BDTIPOCODVER, 0) = 0 then FN.BDVALV13 else 0 end BDVALV13, '||
                                  'VER.BDCLAVER, coalesce(VERREF.BDINSSVER, 0) BDINSSVER, coalesce(upper(VERREF.BDBASEGPSVER), ''FALSE'') BDBASEGPSVER, coalesce(VERREF.BDPISVER, 0) BDPISVER '||
                             'from VRHF_EMP_TVERBA_13_RAT FN '||
                             'join VRHF_EMP_T13SAL_RAT FNR on (FNR.BDCODEMP = FN.BDCODEMP and FNR.BDCODCOL = FN.BDCODCOL and FNR.BDREF13 = FN.BDREF13 and FNR.BDCHAVE = FN.BDCHAVE) '||
                             'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) '||
                             'join VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER and '||
                                                                  'VERREF.BDREFVER = (select first 1 BDREFVER '||
                                                                                     'from VRH_BASE_TVERBAS_REF '||
                                                                                     'where BDCODVER = VERREF.BDCODVER and '||
                                                                                           'BDREFVER <= '||prref||' '||
                                                                                     'order by BDCODVER desc, BDREFVER desc '||
                                                                                     ')) '||
                             'where FN.BDCODEMP = '||wempatu||' and FN.BDCODCOL = '||wcolatu||' and FN.BDREF13 = '||prref;
                else
                   wsqlinss = 'select case when VERREF.BDTIPOCODVER = 1 then FN.BDVALV13 * -1 when coalesce(VERREF.BDTIPOCODVER, 0) = 0 then FN.BDVALV13 else 0 end BDVALV13, '||
                                  'VER.BDCLAVER, coalesce(VERREF.BDINSSVER, 0) BDINSSVER, coalesce(upper(VERREF.BDBASEGPSVER), ''FALSE'') BDBASEGPSVER, coalesce(VERREF.BDPISVER, 0) BDPISVER '||
                             'from VRHF_EMP_TVERBA_13_RAT FN '||
                             'join VRHF_EMP_T13SAL_RAT FNR on (FNR.BDCODEMP = FN.BDCODEMP and FNR.BDCODCOL = FN.BDCODCOL and FNR.BDREF13 = FN.BDREF13 and FNR.BDCHAVE = FN.BDCHAVE) '||
                             'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) '||
                             'join VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = FN.BDCODVER and '||
                                                                  'VERREF.BDREFVER = (select first 1 BDREFVER '||
                                                                                     'from VRH_BASE_TVERBAS_REF '||
                                                                                     'where BDCODVER = VERREF.BDCODVER and '||
                                                                                           'BDREFVER <= '||prref||' '||
                                                                                     'order by BDCODVER desc, BDREFVER desc '||
                                                                                     ')) '||
                             'where FN.BDCODEMP = '||wempatu||' and FN.BDCODCOL = '||wcolatu||' and FN.BDREF13 = '||prref||'  and coalesce(FNR.BDORDEM, 0) = '||coalesce(:bdordem, 0);


                for execute statement wsqlinss
                into
                    :wvalv13, :wclaver, :winssver, :wbasegpsver, :wpisver
                do
                    begin
                      if (winssver = 3) then
                         begin
                           BASE_INSS = BASE_INSS + wvalv13;
                           if (wpisver = true) then
                             BASE_PIS = BASE_PIS + wvalv13;
                         end

                      if (SUBSTRING(:wclaver from 1 for 5) = '5.010' and :wbasegpsver = 'FALSE') then
                         wvalsalfam13  = wvalsalfam13 + wvalv13;
         end

                bdsalfam13gps = wvalsalfam13;

                if (BASE_INSS < 0) then
                   BASE_INSS = 0;
     
              end
     
      BDTIPOCODVER = coalesce(BDTIPOCODVER, 0);
      if (BDTIPOCODVER in (0, 2)) then
         PROVENTOS_FOLHA = wvalv;
      else
         DESCONTOS_FOLHA = wvalv;
     
      suspend;
    end
    end
end^


CREATE OR ALTER TRIGGER vfin_esc_tpagamentos_aiud0 FOR vfin_esc_tpagamentos
ACTIVE AFTER INSERT OR UPDATE OR DELETE POSITION 0
AS
  DECLARE VARIABLE vcodesc INTEGER;
  DECLARE VARIABLE vchavectapag INTEGER;
  DECLARE VARIABLE vTotPago NUMERIC(15,2);
  DECLARE VARIABLE vTotPagMul NUMERIC(15,2);
  DECLARE VARIABLE vTotPagJur NUMERIC(15,2);
  DECLARE VARIABLE vTotPagDesc NUMERIC(15, 2);
  DECLARE VARIABLE vTotPagGer NUMERIC(15, 2);
  DECLARE VARIABLE vOrdemPar INTEGER;
BEGIN
  IF (NEW.bdcodesc IS NULL) THEN
     vcodesc = OLD.bdcodesc;
  ELSE
     vcodesc = NEW.bdcodesc;

  IF (NEW.bdchavectapag IS NULL) THEN
     vchavectapag  = OLD.bdchavectapag;
  ELSE
     vchavectapag = NEW.bdchavectapag;

  IF (NEW.bdordempar IS NULL) THEN
     vordempar = OLD.bdordempar;
  ELSE
     vordempar = NEW.bdordempar;

  SELECT SUM(COALESCE(BDVLRPAG, 0)),
         SUM(COALESCE(BDMULTAPAG, 0)),
         SUM(COALESCE(BDJUROSPAG, 0)),
         SUM(COALESCE(BDDESCPAG, 0)),
         SUM(COALESCE(BDVLRPAG, 0) + COALESCE(BDMULTAPAG, 0) + COALESCE(BDJUROSPAG, 0) - COALESCE(BDDESCPAG, 0))
         FROM vfin_esc_tpagamentos
         WHERE (bdcodesc = :vcodesc) AND
               (bdchavectapag = :vchavectapag)
  INTO vtotpago, vTotPagMul, vTotPagJur, vTotPagDesc, vTotPagGer;


  UPDATE vfin_esc_tcontasapagar
  SET BDTOTPAGO    = :vtotpago,
      BDTOTPAGMUL  = :vtotpagmul,
      BDTOTPAGJUR  = :vtotpagjur,
      BDTOTPAGDESC = :vtotpagdesc,
      BDTOTPAGGER  = :vtotpagger,
      BDTOTPENDENTE = (CASE WHEN (BDVALORTOTALDESP + COALESCE(:vTotPagMul, 0) + COALESCE(:vTotPagJur, 0) - COALESCE(:vTotPagDesc, 0)) - COALESCE(:vTotPagGer, 0) > 0 THEN
                                (BDVALORTOTALDESP + COALESCE(:vTotPagMul, 0) + COALESCE(:vTotPagJur, 0) - COALESCE(:vTotPagDesc, 0)) - COALESCE(:vTotPagGer, 0) ELSE 0 END)
  WHERE (bdcodesc = :vcodesc) AND
        (bdchavectapag = :vchavectapag);

  /*totalizadores do parcelamento*/
  IF (vOrdemPar IS NOT NULL) THEN
     BEGIN
       SELECT SUM(COALESCE(BDVLRPAG, 0)),
              SUM(COALESCE(BDMULTAPAG, 0)),
              SUM(COALESCE(BDJUROSPAG, 0)),
              SUM(COALESCE(BDDESCPAG, 0)),
              SUM(COALESCE(BDVLRPAG, 0) + COALESCE(BDMULTAPAG, 0) + COALESCE(BDJUROSPAG, 0) - COALESCE(BDDESCPAG, 0))
       FROM vfin_esc_tpagamentos
       WHERE (bdcodesc = :vcodesc) AND
             (bdchavectapag = :vchavectapag) AND
             (bdordempar = :vordempar)
       INTO vtotpago, vTotPagMul, vTotPagJur, vTotPagDesc, vTotPagGer;

       UPDATE vfin_esc_tparcelapagar
       SET BDTOTPAGO    = :vtotpago,
           BDTOTPAGMUL  = :vtotpagmul,
           BDTOTPAGJUR  = :vtotpagjur,
           BDTOTPAGDESC = :vtotpagdesc,
           BDTOTPAGGER  = :vtotpagger,
           BDTOTPENDENTE = (CASE WHEN (BDTOTALPARC + COALESCE(:vtotpagmul, 0) + COALESCE(:vtotpagjur, 0) - COALESCE(:vtotpagdesc, 0)) - COALESCE(:vTotPagGer, 0) > 0 THEN
                                      (BDTOTALPARC + COALESCE(:vtotpagmul, 0) + COALESCE(:vtotpagjur, 0) - COALESCE(:vtotpagdesc, 0)) - COALESCE(:vTotPagGer, 0) ELSE 0 END)
       WHERE (bdcodesc = :vcodesc) AND
             (bdchavectapag = :vchavectapag) AND
             (bdordempar = :vordempar);
     END
END^


CREATE OR ALTER TRIGGER VFIN_ESC_TCONTASPAGARDESPCC_BI0 FOR VFIN_ESC_TCONTASPAGARDESPCC
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;

  IF ((NEW.bdchavectapag IS NULL) OR (NEW.bdchavectapag = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchavectapag)), 1) FROM vfin_esc_tcontasapagar WHERE (bdcodesc = NEW.bdcodesc) INTO vcodigo;
       NEW.bdchavectapag = vcodigo;
     END

  IF ((NEW.bdordemdesp IS NULL) OR (NEW.bdordemdesp = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEMDESP)), 1) FROM vfin_esc_tcontaspagardesp WHERE (bdcodesc = NEW.bdcodesc) AND (bdchavectapag = NEW.bdchavectapag) INTO vCodigo;
      NEW.bdordemdesp = vCodigo;
    END

  IF ((NEW.bdordemcc IS NULL) OR (NEW.bdordemcc = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdordemcc) + 1), 1) FROM vfin_esc_tcontaspagardespcc WHERE (bdcodesc = NEW.bdcodesc AND bdchavectapag = NEW.bdchavectapag AND
                                                                                        bdordemdesp = NEW.bdordemdesp) INTO vCodigo;
       NEW.bdordemcc = vCodigo;
     END
  ELSE
     BEGIN
       SELECT bdordemcc FROM vfin_esc_tcontaspagardespcc WHERE (bdcodesc = NEW.bdcodesc AND bdchavectapag = NEW.bdchavectapag AND
                                                                bdordemdesp = NEW.bdordemdesp AND bdordemcc = NEW.bdordemcc) INTO vCodigo;

       IF (vCodigo > 0) THEN
          BEGIN
            SELECT COALESCE((MAX(bdordemcc) + 1), 1) FROM vfin_esc_tcontaspagardespcc
            WHERE (bdcodesc = NEW.bdcodesc AND bdchavectapag = NEW.bdchavectapag AND bdordemdesp = NEW.bdordemdesp) INTO vCodigo;
            NEW.bdordemcc = vCodigo;
          END
     END
END
^

CREATE OR ALTER TRIGGER VFIN_ESC_TRECANTECIP_DEST_BIUD0 FOR VFIN_ESC_TRECANTECIP_DEST
ACTIVE BEFORE INSERT OR UPDATE OR DELETE POSITION 0
AS
BEGIN
 --controle saldo recebimento antecipado - exclusão/inserção e ediçãom foi passado para VFIN_ESC_TRECANTECIP_DEST
 IF (NEW.bdcodcli IS NULL) THEN --exclusão
    BEGIN
       IF (OLD.bdchaverecant > 0) THEN --ao excluir recebimento da fatura que tenha sido beneficiado por recebimento antecipado repor o valor utilizado no saldo
          BEGIN
            UPDATE VFIN_ESC_TRECANTECIPADO
            SET bdsaldorecant = COALESCE(bdsaldorecant, 0) + OLD.bdvalrecdest
            WHERE
            BDCODESC = OLD.bdcodesc AND
            BDCODCLI = OLD.bdcodcli AND
            BDCHAVERECANT = OLD.bdchaverecant;
          END
    END
 ELSE
 IF (NEW.bdchaverecant > 0) THEN --controle saldo
    BEGIN
      IF (OLD.bdvalrecdest IS NULL) THEN --inserção
         BEGIN
           UPDATE VFIN_ESC_TRECANTECIPADO
           SET bdsaldorecant = COALESCE(bdsaldorecant, 0) - NEW.bdvalrecdest
           WHERE
           BDCODESC = NEW.bdcodesc AND
           BDCODCLI = NEW.bdcodcli AND
           BDCHAVERECANT = NEW.bdchaverecant;
         END
      ELSE
         BEGIN -- edição
           UPDATE VFIN_ESC_TRECANTECIPADO
           SET bdsaldorecant = COALESCE(bdsaldorecant, 0) - OLD.bdvalrecdest + NEW.bdvalrecdest
           WHERE
           BDCODESC = NEW.bdcodesc AND
           BDCODCLI = NEW.bdcodcli AND
           BDCHAVERECANT = NEW.bdchaverecant;
         END
    END
END
^


CREATE OR ALTER TRIGGER vfin_base_tdespesa_bd0 FOR vfin_base_tdespesa
ACTIVE BEFORE DELETE POSITION 0
AS
  DECLARE VARIABLE vlength INTEGER;
BEGIN
  IF (OLD.bdtipodesp = 0) THEN
     BEGIN
       vlength = strlen(OLD.bdclassdesp);

       DELETE FROM vfin_base_tdespesa
       WHERE SUBSTRING(bdclassdesp FROM 1 FOR :vlength) = OLD.bdclassdesp
       AND bdclassdesp <> OLD.bdclassdesp;

       IF (EXISTS(SELECT * FROM vfin_base_tdespesa
                  WHERE SUBSTRING(bdclassdesp FROM 1 FOR :vlength) = OLD.bdclassdesp
                  AND bdclassdesp <> OLD.bdclassdesp)) THEN
          EXCEPTION nao_excluir_titulo;

     END
END^


CREATE OR ALTER TRIGGER VFIN_ESC_TCONTASPAGARDESP_AIUD0 FOR VFIN_ESC_TCONTASPAGARDESP
ACTIVE AFTER INSERT OR UPDATE OR DELETE POSITION 0
AS
  DECLARE VARIABLE vVALORTOTALDESP DM_NUMERIC_15_2;
  DECLARE VARIABLE vcodesc INTEGER;
  DECLARE VARIABLE vchavectapag INTEGER;
  declare variable vTotPendente DM_NUMERIC_15_2;
BEGIN
  IF (NEW.bdcodesc IS NULL) THEN
     vcodesc = OLD.bdcodesc;
  ELSE
     vcodesc = NEW.bdcodesc;

  IF (NEW.bdchavectapag IS NULL) THEN
     vchavectapag = OLD.bdchavectapag;
  ELSE
     vchavectapag = NEW.bdchavectapag;

  /*SELECT SUM(COALESCE(BDVALORDESP, 0)) FROM vfin_esc_tcontaspagardesp
  WHERE (bdcodesc = :vcodesc) AND (bdchavectapag = :vchavectapag)
  INTO vVALORTOTALDESP;*/

  /* Morgana 18/07/2018. Soma das despesas que não são de desconto, substraindo pelas despesas de desconto.
  As despesas de multa/juros/desconto provenientes de um pagamento não devem ser inclusas nesta soma. */
  SELECT COALESCE(SUM(BDVALORDESP),0) - COALESCE((SELECT COALESCE(SUM(BDVALORDESP),0)
                                        FROM vfin_esc_tcontaspagardesp cpd
                                        left outer join vfin_base_tescpardesp pd on (pd.bdcodesc = cpd.bdcodesc)
                                        left outer join vfin_base_tdespesa desp on (desp.bdcoddesp = cpd.bdcoddesp)
                                        WHERE (cpd.bdcodesc = :vcodesc) AND (cpd.bdchavectapag = :vchavectapag)
                                        and cpd.bdcoddesp <> pd.bdctamultadesp
                                        and cpd.bdcoddesp <> pd.bdctajurdesp
                                        and cpd.bdcoddesp <> pd.bdctadescdesp
                                        and coalesce(desp.bddesconto, 'FALSE') = 'TRUE'),0)
  FROM vfin_esc_tcontaspagardesp cpd
  left outer join vfin_base_tescpardesp pd on (pd.bdcodesc = cpd.bdcodesc)
  left outer join vfin_base_tdespesa desp on (desp.bdcoddesp = cpd.bdcoddesp)
  WHERE (cpd.bdcodesc = :vcodesc) AND (cpd.bdchavectapag = :vchavectapag)
  and cpd.bdcoddesp <> pd.bdctamultadesp
  and cpd.bdcoddesp <> pd.bdctajurdesp
  and cpd.bdcoddesp <> pd.bdctadescdesp
  and coalesce(desp.bddesconto, 'FALSE') = 'FALSE'
  INTO vVALORTOTALDESP;

  UPDATE VFIN_ESC_TCONTASAPAGAR SET BDVALORTOTALDESP = :vVALORTOTALDESP
  WHERE (bdcodesc = :vcodesc) AND (bdchavectapag = :vchavectapag);

  select coalesce(sum(BDTOTPENDDESP),0) from vfin_esc_tcontaspagardesp
  where bdcodesc = :vcodesc and bdchavectapag = :vchavectapag into :vtotpendente;

  UPDATE VFIN_ESC_TCONTASAPAGAR SET BDTOTPENDENTE = :vtotpendente
  WHERE (bdcodesc = :vcodesc) AND (bdchavectapag = :vchavectapag);


  /* Zerar os valores de multa/juros/desconto do pagamento quando estas despesas forem excluidas. */
  if (DELETING) then
     begin
       update VFIN_ESC_TPAGAMENTOS set bdjurospag = 0
       where bdcodesc = :vcodesc
       and bdchavectapag = :vchavectapag
       and old.bdcoddesp = (select bdctajurdesp from vfin_base_tescpardesp where bdcodesc = :vcodesc);

       update VFIN_ESC_TPAGAMENTOS set bdmultapag = 0
       where bdcodesc = :vcodesc
       and bdchavectapag = :vchavectapag
       and old.bdcoddesp = (select bdctamultadesp from vfin_base_tescpardesp where bdcodesc = :vcodesc);

       update VFIN_ESC_TPAGAMENTOS set bddescpag = 0
       where bdcodesc = :vcodesc
       and bdchavectapag = :vchavectapag
       and old.bdcoddesp = (select bdctadescdesp from vfin_base_tescpardesp where bdcodesc = :vcodesc);
     end

  -- Sol: 19751 Morgana. 21/08/2017. Excluir o lançamento caso não possua mais despesas.
  DELETE FROM VFIN_ESC_TCONTASAPAGAR lan
  WHERE lan.bdcodesc = OLD.bdcodesc
  AND lan.bdchavectapag = OLD.bdchavectapag
  AND NOT EXISTS
    (
      SELECT desp.bdordemdesp FROM VFIN_ESC_TCONTASPAGARDESP desp
      WHERE desp.bdcodesc = lan.bdcodesc
      AND desp.bdchavectapag = lan.bdchavectapag
    );
END
^


CREATE OR ALTER TRIGGER vfin_esc_tcontaspagardesp_bd0 FOR vfin_esc_tcontaspagardesp
ACTIVE BEFORE DELETE POSITION 0
AS
  DECLARE VARIABLE vCodCli INTEGER;
  DECLARE VARIABLE vChaveSerFix INTEGER;
  DECLARE VARIABLE vOrdemSerFix INTEGER;
BEGIN
  SELECT BDCODCLI, BDCHAVESERFIX, BDORDEMSERFIX FROM VFIN_ESC_TVINC_PAG_SERVIC
  WHERE BDCODESC = OLD.bdcodesc AND
        BDCHAVECTAPAG = OLD.BDCHAVECTAPAG AND
        BDORDEMDESP = OLD.bdordemdesp
  INTO :vcodcli, :vchaveserfix, :vordemserfix;
  IF (vCodCli > 0) THEN
     BEGIN
       DELETE FROM vfin_esc_tservicofixo ser
       WHERE ser.bdcodesc = OLD.bdcodesc AND
             ser.bdcodcli = :vCodCli AND
             ser.bdchaveserfix = :vChaveSerFix AND
             ser.bdordemserfix = :vOrdemSerFix;

      /*excluir cabeçalho do serviço para faturamento se ficar vazio*/
      DELETE FROM vfin_esc_tcabservicofixo cab
      WHERE
      bdcodcli = :vCodCli AND
      bdcodesc = OLD.bdcodesc AND
      bdchaveserfix = :vChaveSerFix AND
      NOT EXISTS
        (
          SELECT bdordemserfix FROM vfin_esc_tservicofixo ser
          WHERE ser.bdcodcli = cab.bdcodcli AND
                ser.bdcodesc = cab.bdcodesc AND
                ser.bdchaveserfix = cab.bdchaveserfix
        );
     END
END^


CREATE OR ALTER TRIGGER vfin_esc_tpagdesp_aiud0 FOR vfin_esc_tpagdesp
ACTIVE AFTER INSERT OR UPDATE OR DELETE POSITION 0
AS
  DECLARE VARIABLE vcodesc INTEGER;
  DECLARE VARIABLE vchavectapag INTEGER;
  DECLARE VARIABLE vOrdemDesp INTEGER;
  DECLARE VARIABLE vTotpagDesp NUMERIC(15,2);
BEGIN
  IF (NEW.bdcodesc IS NULL) THEN
     vcodesc = OLD.bdcodesc;
  ELSE
     vcodesc = NEW.bdcodesc;

  IF (NEW.bdchavectapag IS NULL) THEN
     vchavectapag = OLD.bdchavectapag;
  ELSE
     vchavectapag = NEW.bdchavectapag;

  IF (NEW.bdordemdesp IS NULL) THEN
     vordemdesp = OLD.bdordemdesp;
  ELSE
     vordemdesp = NEW.bdordemdesp;

  SELECT SUM(COALESCE(BDVLRPAGDESP, 0))
         FROM vfin_esc_tpagdesp
         WHERE (bdcodesc = :vcodesc) AND
               (bdchavectapag = :vchavectapag) AND
               (bdordemdesp = :vordemdesp)
  INTO vTotpagDesp;

  UPDATE vfin_esc_tcontaspagardesp
  SET BDTOTPAGDESP  = :vTotPagDesp,
      BDTOTPENDDESP = (CASE WHEN BDVALORDESP - COALESCE(:vTotpagDesp, 0) > 0 THEN BDVALORDESP - COALESCE(:vTotpagDesp, 0) ELSE 0 END)
  WHERE (bdcodesc = :vcodesc) AND
        (bdchavectapag = :vchavectapag) AND
        (bdordemdesp = :vordemdesp);
END^


CREATE OR ALTER TRIGGER vfin_base_tcliente_bd0 FOR vfin_base_tcliente
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
  /*excluir tabelas que possuem vínculos quer não são CASCADE*/
  DELETE FROM VFIN_ESC_TFATURA WHERE bdcodcli = OLD.bdcodcli;
  DELETE FROM vfin_esc_tcabservicofixo WHERE bdcodcli = OLD.bdcodcli;
  /* Gilberto - 23/08/2021 - W154436 - quando excluir cliente, deve permitir alterção de situação financeira pelo cadastro de empresas */
  update tempresas set bdcontrsitfin = null where bdcodcli = old.bdcodcli;
  if (old.BDCODTIPOCLI = 3) then
     delete from tempresas where bdcodcli = old.bdcodcli and bdcnpjemp = old.bdcnpjcli;

  /* Gilberto - 25/08/2022 - criado para tentar rastrear qual processo está excluindo cliente */
  EXECUTE PROCEDURE SP_INSERIR_LOG((select first 1 bdcodemp from tempresas where bdcodcli = old.bdcodcli), NULL, null, NULL, null, NULL, null, null, 'Exclusão do cliente: '||old.bdcodcli, 0, 1, null, null, (select BDNOMETELA from vw_get_processo), (select BDCAPTIONTELA from vw_get_processo), NULL, 'VFIN_BASE_TCLIENTE', NULL, 'FALSE', null);
END^

CREATE OR ALTER TRIGGER VFIN_BASE_TCLIENTE_REF_BD0 FOR VFIN_BASE_TCLIENTE_REF
ACTIVE BEFORE DELETE POSITION 0
AS
begin
  /* Gilberto - 25/08/2022 - criado para tentar rastrear qual processo está excluindo cliente */
  EXECUTE PROCEDURE SP_INSERIR_LOG((select first 1 bdcodemp from tempresas where bdcodcli = old.bdcodcli), NULL, null, NULL, null, NULL, null, null, 'Exclusão de dados da refêrencia '||old.bdrefcli||' do cliente: '||old.bdcodcli, 0, 1, null, null, (select BDNOMETELA from vw_get_processo), (select BDCAPTIONTELA from vw_get_processo), NULL, 'VFIN_BASE_TCLIENTE_REF', NULL, 'FALSE', null);
end
^

SET TERM ; ^


/* View: VW_VFIN_BASE_TCLIENTEREF_MAXMIN */
CREATE OR ALTER VIEW VW_VFIN_BASE_TCLIENTEREF_MAXMIN(
    BDCODCLI,
    BDREFCLI)
AS
SELECT cli.bdcodcli,
       COALESCE((SELECT FIRST 1 x.bdrefcli FROM vfin_base_tcliente_ref x
                 WHERE x.bdcodcli = cli.bdcodcli AND
                 CAST(X.BDREFCLI AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
                 ORDER BY x.bdrefcli DESC),
                 (SELECT FIRST 1 x.bdrefcli FROM vfin_base_tcliente_ref x
                  WHERE x.bdcodcli = cli.bdcodcli
                  ORDER BY x.bdrefcli
                 )
                ) BDREFCLI
FROM VFIN_BASE_TCLIENTE cli
;


/* View: VW_VFIN_CLIENTES_REF */
CREATE OR ALTER VIEW VW_VFIN_CLIENTES_REF(
    BDCODCLI,
    BDCODEMP,
    BDREFCLI,
    BDCODCID,
    BDCODCNAE,
    BDCODNATJUR,
    BDCODSITCLI,
    BDCNPJCLI,
    BDAPECLI,
    BDNOMCLI,
    BDNOMREDUZCLI,
    BDCEPCLI,
    BDLOGRCLI,
    BDENDCLI,
    BDNUMCLI,
    BDCOMPLCLI,
    BDBAICLI,
    BDDDDCLI,
    BDFONECLI,
    BDDDDFAXCLI,
    BDFONEFAXCLI,
    BDDDDCELCLI,
    BDCELCLI,
    BDCXPCLI,
    BDIECLI,
    BDIMCLI,
    BDEMAILCLI,
    BDEMAILFINCLI,
    BDDATACADCLI,
    BDCAPITALSOC,
    BDORGAOPUBLICO,
    BDDATAENTRADA,
    BDDATASAIDA,
    BDNUMFUN,
    BDINATIVO,
    BDCODPLATRIB,
    BDCODPLANOONLINE,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDCODPLASITFIN,
    BDORGAOCLI,
    BDNUMREGCLI,
    BDNOMECARTORIO,
    BDDATAREGCLI,
    BDLIVROREG,
    BDFOLHAREG,
    BDDOCAUXREG,
    BDCODZONA,
    BDCODTIPOCLI,
    BDUSESOCIOOSTENSIVA)
AS
SELECT
    cli.BDCODCLI,
    emp.bdcodemp,
    cli.BDREFCLI,
    ref.BDCODCID,
    ref.BDCODCNAE,
    ref.BDCODNATJUR,
    ref.BDCODSITCLI,
    vcli.bdcnpjcli,
    ref.BDAPECLI,
    ref.BDNOMCLI,
    ref.BDNOMREDUZCLI,
    ref.BDCEPCLI,
    ref.BDLOGRCLI,
    ref.BDENDCLI,
    ref.BDNUMCLI,
    ref.BDCOMPLCLI,
    ref.BDBAICLI,
    ref.BDDDDCLI,
    ref.BDFONECLI,
    ref.BDDDDFAXCLI,
    ref.BDFONEFAXCLI,
    ref.BDDDDCELCLI,
    ref.BDCELCLI,
    ref.BDCXPCLI,
    ref.BDIECLI,
    ref.BDIMCLI,
    ref.BDEMAILCLI,
    ref.BDEMAILFINCLI,
    vcli.bddatacadcli,
    ref.BDCAPITALSOC,
    ref.BDORGAOPUBLICO,
    ref.BDDATAENTRADA,
    ref.BDDATASAIDA,
    ref.BDNUMFUN,
    ref.BDINATIVO,
    refemp.BDCODPLATRIB,
    refemp.bdcodplanoonline,
    refemp.bdcodplapadrao,
    refemp.bdcodhist,
    ref.bdcodplasitfin,
    ref.BDORGAOCLI,
    ref.BDNUMREGCLI,
    ref.BDNOMECARTORIO,
    ref.BDDATAREGCLI,
    ref.BDLIVROREG,
    ref.BDFOLHAREG,
    ref.BDDOCAUXREG,
    ref.bdcodzona,
    vcli.bdcodtipocli,
    ref.bdusesocioostensiva
FROM VW_VFIN_BASE_TCLIENTEREF_MAXMIN cli
inner JOIN vfin_base_tcliente_ref ref ON (ref.bdcodcli = cli.bdCODCLI AND ref.bdrefcli = cli.bdrefcli)
inner join vfin_base_tcliente vcli on (vcli.bdcodcli = cli.bdcodcli)
left outer join tempresas emp on (emp.bdcodcli = cli.bdcodcli and emp.bdstatusemp = 0)
left outer join tempresas_ref refemp on (refemp.bdcodemp = emp.bdcodemp and refemp.bdrefemp = cli.bdrefcli)
where((emp.bdexcluiremp is null)or(Upper(emp.bdexcluiremp)<>'TRUE'))
;

/* View: VW_VFIN_BASE_TCLICONTATO_MAXMIN */
CREATE OR ALTER VIEW VW_VFIN_BASE_TCLICONTATO_MAXMIN(
    BDCODCLI,
    BDREFCLI)
AS
SELECT
cli.bdcodcli,
  COALESCE(
    (
      SELECT FIRST 1 x.bdrefcli FROM vfin_base_tclicontato x
      WHERE x.bdcodcli = cli.bdcodcli AND
      CAST(X.bdrefcli AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
      ORDER BY x.bdrefcli DESC
     )
    ,
     (SELECT FIRST 1 x.bdrefcli FROM vfin_base_tclicontato x
       WHERE x.bdcodcli = cli.bdcodcli
       ORDER BY x.bdrefcli
      )
    ) BDREFCLI

FROM vfin_base_tcliente cli
;


/* View: VW_VFIN_BASE_TCLIENDERE_MAXMIN */
CREATE OR ALTER VIEW VW_VFIN_BASE_TCLIENDERE_MAXMIN(
    BDCODCLI,
    BDREFCLI)
AS
SELECT
cli.bdcodcli,
  COALESCE(
    (
      SELECT FIRST 1 x.bdrefcli FROM vfin_base_tclienderecamento x
      WHERE x.bdcodcli = cli.bdcodcli AND
      CAST(X.bdrefcli AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
      ORDER BY x.bdrefcli DESC
     )
    ,
     (SELECT FIRST 1 x.bdrefcli FROM vfin_base_tclienderecamento x
       WHERE x.bdcodcli = cli.bdcodcli
       ORDER BY x.bdrefcli
      )
    ) BDREFCLI

FROM vfin_base_tcliente cli
;



/* View: VW_VFIN_BASE_TCLIENQFED_MAXMIN */
CREATE OR ALTER VIEW VW_VFIN_BASE_TCLIENQFED_MAXMIN(
    BDCODCLI,
    BDREFCLI)
AS
SELECT
cli.bdcodcli,
  COALESCE(
    (
      SELECT FIRST 1 x.bdrefcli FROM vfin_base_tclienqfed x
      WHERE x.bdcodcli = cli.bdcodcli AND
      CAST(X.bdrefcli AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
      ORDER BY x.bdrefcli DESC
     )
    ,
     (SELECT FIRST 1 x.bdrefcli FROM vfin_base_tclienqfed x
       WHERE x.bdcodcli = cli.bdcodcli
       ORDER BY x.bdrefcli
      )
    ) BDREFCLI

FROM vfin_base_tcliente cli
;


/* View: VW_VFIN_BASE_TCLIIMPOSTO_MAXMIN */
CREATE OR ALTER VIEW VW_VFIN_BASE_TCLIIMPOSTO_MAXMIN(
    BDCODCLI,
    BDREFCLI)
AS
SELECT
cli.bdcodcli,
  COALESCE(
    (
      SELECT FIRST 1 x.bdrefcli FROM vfin_base_tcliimposto x
      WHERE x.bdcodcli = cli.bdcodcli AND
      CAST(X.bdrefcli AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
      ORDER BY x.bdrefcli DESC
     )
    ,
     (SELECT FIRST 1 x.bdrefcli FROM vfin_base_tcliimposto x
       WHERE x.bdcodcli = cli.bdcodcli
       ORDER BY x.bdrefcli
      )
    ) BDREFCLI

FROM vfin_base_tcliente cli
;


/* View: VW_VFIN_BASE_TCLICONTATO */
CREATE OR ALTER VIEW VW_VFIN_BASE_TCLICONTATO(
    BDCODCLI,
    BDREFCLI,
    BDCODCONT,
    BDCONTATO,
    BDPROFISCONTATO,
    BDDATANASCCON,
    BDCPFCON)
AS
SELECT
    cli.bdcodcli,
    cli.bdrefcli,
    x.bdcodcont,
    x.bdcontato,
    x.bdprofiscontato,
    x.bddatanasccon,
    x.bdcpfcon
FROM vw_vfin_base_tclicontato_maxmin cli
JOIN vfin_base_tclicontato x ON (x.bdcodcli = cli.bdCODCLI AND x.bdrefcli = cli.bdrefcli)
;


/* View: VW_VFIN_BASE_TCLIENDERECAMENTO */
CREATE OR ALTER VIEW VW_VFIN_BASE_TCLIENDERECAMENTO(
    BDCODCLI,
    BDREFCLI,
    BDCODCIDETI,
    BDNOMENDETI,
    BDLOGRETI,
    BDENDERECOETI,
    BDNUMEROETI,
    BDCOMPLETI,
    BDBAIRROETI,
    BDCEPETI,
    BDCXPETI,
    BDNOMCIDETI,
    BDSIGLAUFETI,
    BDCODIBGECIDETI,
    BDCODFEDCIDETI
    )
AS
SELECT
    cli.bdcodcli,
    cli.bdrefcli,
    x.bdcodcideti,
    x.bdnomendeti,
    x.bdlogreti,
    x.bdenderecoeti,
    x.bdnumeroeti,
    x.bdcompleti,
    x.bdbairroeti,
    x.bdcepeti,
    x.bdcxpeti,
    cid.bdnomcid,
    uf.bdsiglauf,
    cid.bdcodibge,
    cid.bdcodfed
FROM vw_vfin_base_tcliendere_maxmin cli
JOIN vfin_base_tclienderecamento x ON (x.bdcodcli = cli.bdCODCLI AND x.bdrefcli = cli.bdrefcli)
LEFT OUTER JOIN tcidade cid ON (cid.bdcodcid = x.bdcodcideti)
LEFT OUTER JOIN tuf uf ON (uf.bdcoduf = cid.bdcoduf)
;

/*Adilson Hasckel - Sol. 16529 - criado view para pegar somente o último código de enquadramento da referência por cliente*/
CREATE OR ALTER VIEW VW_VFIN_BASE_TCLIENQFED_ULT(
    BDCODCLI,
    BDREFCLI,
    BDCODENQFED,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO,
    BDANEXOIII,
    BDANEXOIV,
    BDANEXOV,
    BDANEXOVI)
AS
SELECT clienq.bdcodcli,
       clienq.bdrefcli,
       clienq.bdcodenqfed,
       clienq.bdcomercio,
       clienq.bdindustria,
       clienq.bdservico,
       clienq.bdanexoiii,
       clienq.bdanexoiv,
       clienq.bdanexov,
       clienq.bdanexovi
FROM vfin_base_tclienqfed clienq
INNER JOIN (SELECT bdcodcli, bdrefcli, MAX(BDCODENQFED) BDCODENQFED
            FROM vfin_base_tclienqfed
            GROUP BY bdcodcli, bdrefcli
            ) maxenq ON (maxenq.bdcodcli = clienq.bdcodcli AND maxenq.bdrefcli = clienq.bdrefcli AND maxenq.BDCODENQFED = clienq.bdcodenqfed)
;

/*Adilson Hasckel - Sol. 16529 - ajustado para utilizar VIEW VW_VFIN_BASE_TCLIENQFED_ULT que pega somente o último código de enquadramento da referência por cliente*/
CREATE OR ALTER VIEW VW_VFIN_BASE_TCLIENQFED(
    BDCODCLI,
    BDREFCLI,
    BDCODENQFED,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO,
    BDANEXOIII,
    BDANEXOIV,
    BDANEXOV,
    BDANEXOVI)
AS
SELECT
    cli.bdcodcli,
    cli.bdrefcli,
    x.bdcodenqfed,
    x.bdcomercio,
    x.bdindustria,
    x.bdservico,
    x.bdanexoiii,
    x.bdanexoiv,
    x.bdanexov,
    x.bdanexovi
FROM vw_vfin_base_tclienqfed_maxmin cli
JOIN VW_VFIN_BASE_TCLIENQFED_ULT x ON (x.bdcodcli = cli.bdCODCLI AND x.bdrefcli = cli.bdrefcli)
;

/* View: VW_VFIN_BASE_TCLIIMPOSTO */
CREATE OR ALTER VIEW VW_VFIN_BASE_TCLIIMPOSTO(
    BDCODCLI,
    BDREFCLI,
    BDPERINSS,
    BDDEDINSSNF,
    BDUSARPERISS,
    BDRETIR,
    BDRETCSLL,
    BDRETCOF,
    BDRETPIS,
    BDINCENTCULT,
    BDCODSITESP,
    BDRETIMP,
    BDDESTIR,
    BDDESTCSLL,
    BDDESTPIS,
    BDDESTCOF)
AS
SELECT
    cli.bdcodcli,
    cli.bdrefcli,
    x.bdperinss,
    x.bddedinssnf,
    x.bdusarperiss,
    x.bdretir,
    x.bdretcsll,
    x.bdretcof,
    x.bdretpis,
    x.bdincentcult,
    x.bdcodsitesp,
    x.bdretimp,
    x.bddestir, 
    x.bddestcsll, 
    x.bddestpis, 
    x.bddestcof
FROM vw_vfin_base_tcliimposto_maxmin cli
JOIN vfin_base_tcliimposto x ON (x.bdcodcli = cli.bdCODCLI AND x.bdrefcli = cli.bdrefcli)
;


SET TERM ^ ;

CREATE OR ALTER procedure SP_CONSULTACLIENTES (
    PRREFMICRO integer,
    PRCODCLI varchar(10240),
    PRCODSITCLI integer)
returns (
    BDCODCLI integer,
    BDCODESC integer,
    BDCODPRESER integer,
    BDCODCLIMATRIZ integer,
    BDCNPJCLI varchar(18),
    BDDATAINIATIVCLI date,
    BDDATAFIMATIVCLI date,
    BDORGAOCLI varchar(20),
    BDNUMREGCLI varchar(40),
    BDNOMECARTORIO varchar(100),
    BDDATAREGCLI date,
    BDLIVROREG varchar(15),
    BDFOLHAREG varchar(15),
    BDDOCAUXREG varchar(18),
    BDCODTIPOCLI integer,
    BDDATACADCLI date,
    BDCODCID integer,
    BDCODCNAE integer,
    BDCODNATJUR integer,
    BDDESCPLASITFIN varchar(50),
    BDCODPLASITFIN integer,
    BDAPECLI DM_BDAPEMP,
    BDNOMCLI DM_BDNOMEMP,
    BDNOMREDUZCLI DM_BDNOMREDUZEMP,
    BDCEPCLI varchar(9),
    BDLOGRCLI varchar(15),
    BDENDCLI DM_BDENDERECO,
    BDNUMCLI DM_NUMEND,
    BDCOMPLCLI DM_BDCOMPENDERECO,
    BDBAICLI DM_BDBAIRRO,
    BDDDDCLI integer,
    BDFONECLI DM_BDTELEFONE,
    BDDDDFAXCLI integer,
    BDFONEFAXCLI DM_BDTELEFONE,
    BDDDDCELCLI integer,
    BDCELCLI DM_BDTELEFONE,
    BDCXPCLI DM_CXPOSTAL,
    BDIECLI varchar(20),
    BDIMCLI varchar(20),
    BDEMAILCLI DM_BDEMAIL,
    BDEMAILFINCLI DM_BDEMAIL,
    BDCAPITALSOC DM_NUMERIC_15_2,
    BDORGAOPUBLICO DM_BOOLEAN,
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
    BDDESCCNAE varchar(200),
    BDDESCNAT varchar(100),
    BDNUMFUN integer,
    BDCODPLATRIB integer,
    BDINATIVO DM_BOOLEAN,
    BDDESCPLATRIB varchar(50),
    BDCODIBGECID integer,
    BDCODFEDCID integer,
    BDCODSPEDPAIS integer,
    BDCODPLANOONLINE integer,
    BDCODPLAPADRAO integer,
    BDCODHIST integer,
    BDCODSITCLI integer,
    BDCODZONA integer,
    BDNOMEZONA varchar(40),
    BDCODEMP integer,
    BDTIPOCLI varchar(50))
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(20000);
declare variable WPOS integer;
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);

  wSql = ' select ';
  wSql = wSql||'cli.BDCODCLI, cli.BDCODESC, cli.BDCODPRESER, cli.BDCODCLIMATRIZ, ';
  wSql = wSql||'cli.BDCNPJCLI, cli.BDDATAINIATIVCLI, cli.BDDATAFIMATIVCLI, ';
  wSql = wSql||'refcli.BDORGAOCLI, refcli.BDNUMREGCLI, refcli.BDNOMECARTORIO, refcli.BDDATAREGCLI, ';
  wSql = wSql||'refcli.BDLIVROREG, refcli.BDFOLHAREG, refcli.BDDOCAUXREG, cli.BDCODTIPOCLI, cli.BDDATACADCLI, ';
  wSql = wSql||'refcli.BDCODCID, refcli.BDCODCNAE, refcli.BDCODNATJUR, ';
  wSql = wSql||'/*refcli.BDCODSITCLI,*/ refcli.BDAPECLI, refcli.BDNOMCLI, ';
  wSql = wSql||'refcli.BDNOMREDUZCLI, refcli.BDCEPCLI, refcli.BDLOGRCLI, ';
  wSql = wSql||'refcli.BDENDCLI, refcli.BDNUMCLI, refcli.BDCOMPLCLI, ';
  wSql = wSql||'refcli.BDBAICLI, refcli.BDDDDCLI, refcli.BDFONECLI, ';
  wSql = wSql||'refcli.BDDDDFAXCLI, refcli.BDFONEFAXCLI, refcli.BDDDDCELCLI, ';
  wSql = wSql||'refcli.BDCELCLI, refcli.BDCXPCLI,refcli.BDIECLI, refcli.BDIMCLI, ';
  wSql = wSql||'refcli.BDEMAILCLI, refcli.BDEMAILFINCLI, refcli.BDCAPITALSOC, refcli.BDORGAOPUBLICO, ';
  wSql = wSql||'/*refcli.BDDATAENTRADA, refcli.BDDATASAIDA,*/ refcli.bdnumfun, refcli.bdinativo, refcli.bdcodplatrib, ';
  wSql = wSql||'refcli.BDCODPLANOONLINE, refcli.BDCODPLAPADRAO, refcli.BDCODHIST, ';
  wSql = wsql||'cid.bdnomcid, uf.bdsiglauf, ';
  wSql = wSql||'/*sitcli.bddescsitcli,*/ cnae.BDDESCCNAE, natjur.bddescnat, tplatrib.bddescplatrib, ';
  wSql = wSql||'cid.bdcodibge bdcodibgecid, cid.bdcodfed bdcodfedcid, pais.bdcodsped bdcodspedpais, ';
  wSql = wSql||'refcli.BDCODPLASITFIN, plasit.BDDESCPLASITFIN, ';
  wsql = wsql||'(select first 1 SIT.BDCODSITCLI  ';
  wsql = wsql||'from VFIN_BASE_TSITCLIENTE SIT '; /*Leonardo Pereira - 19/11/2018 - Incluido campo de situação do cliente*/
  wsql = wsql||'where substring(cast(SIT.BDDATASITCLI as varchar(10)) from 6 for 2)||substring(cast(SIT.BDDATASITCLI as varchar(10)) from 1 for 4) <= '||prrefmicro||' and ';
  wsql = wsql||'SIT.BDCODCLI = CLI.BDCODCLI ';
  wsql = wsql||' order by SIT.BDCODCLI, SIT.BDDATASITCLI desc, SIT.BDCHAVESITCLI desc) as BDCODSITCLI, Z.BDCODZONA, Z.BDNOMEZONA ';
  wsql = wsql||',emp.bdcodemp, tc.bddesctipocli ';
  wSql = wSql||'from VFIN_BASE_TCLIENTE cli ';
  wSql = wSql||'join vw_vfin_clientes_ref refcli on (refcli.bdcodcli = cli.bdcodcli)';
  wSql = wSql||'left outer join tcidade cid on (cid.bdcodcid = refcli.bdcodcid)';
  wSql = wSql||'left outer join tpais pais on (pais.bdcodpais = cid.bdcodpais)';
  wSql = wSql||'left outer join tuf uf on (uf.bdcoduf = cid.bdcoduf)';
  /*wSql = wSql||' left outer join vfin_base_ttabsitcli sitcli on (sitcli.bdcodsitcli = refcli.bdcodsitcli) ';*/
  wSql = wSql||'left outer join VFIN_BASE_TPLANOSITFIN plasit on (plasit.bdcodplasitfin = refcli.bdcodplasitfin)';
  wSql = wSql||'left outer join tcnae cnae on (cnae.bdcodcnae = refcli.bdcodcnae)';
  wSql = wSql||'left outer join tnatjur natjur on (natjur.bdcodnatjur = refcli.bdcodnatjur)';
  wSql = wSql||'left outer join VCT_PLANO_TRIBUTARIO tplatrib on (tplatrib.bdcodplatrib = refcli.bdcodplatrib)';
  wsql = wsql||'left outer join TZONA Z on (Z.bdcodcid = refcli.bdcodcid and z.bdcodzona = refcli.bdcodzona)';
  wsql = wsql||'left outer join tempresas emp on(emp.bdcodcli=cli.bdcodcli)';
  wsql = wsql||'left outer join vfin_base_ttipocliente tc on (tc.bdcodtipocli = cli.bdcodtipocli)';

  wwhere = '';

  IF ((prcodcli IS NOT NULL) AND (prcodcli <> '0') AND (prcodcli <> '')) THEN
     BEGIN
       SELECT POSITION('=', :prcodcli) FROM RDB$DATABASE INTO wpos;

       IF (wPos = 0) THEN
          SELECT POSITION(' in (', :prcodcli) FROM RDB$DATABASE INTO :wpos;

       IF (wPos = 0) THEN
          SELECT POSITION(' between ', :prcodcli) FROM RDB$DATABASE INTO :wpos;

       IF (wpos > 0) THEN
          wwhere = wwhere||' ('||prcodcli||') ';
       ELSE
          wwhere = wwhere||' cli.bdcodcli = '||prcodcli;
     END

  /*Comentado pois não existe mais o campo BDCODSITCLI na tabela de clientes*/
  /* filra situação do cliente*/
  /*if (PRCODSITCLI is not null and PRCODSITCLI <> 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wWhere = 'ref.bdCODSITCLI = '||prCODSITCLI;
     end*/

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By cli.BDCODCLI';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODCLI,
    BDCODESC,
    BDCODPRESER,
    BDCODCLIMATRIZ,
    BDCNPJCLI,
    BDDATAINIATIVCLI,
    BDDATAFIMATIVCLI,
    BDORGAOCLI,
    BDNUMREGCLI,
    BDNOMECARTORIO,
    BDDATAREGCLI,
    BDLIVROREG,
    BDFOLHAREG,
    BDDOCAUXREG,
    BDCODTIPOCLI,
    BDDATACADCLI,
    BDCODCID,
    BDCODCNAE,
    BDCODNATJUR,
    /*BDCODSITCLI,*/
    BDAPECLI,
    BDNOMCLI,
    BDNOMREDUZCLI,
    BDCEPCLI,
    BDLOGRCLI,
    BDENDCLI,
    BDNUMCLI,
    BDCOMPLCLI,
    BDBAICLI,
    BDDDDCLI,
    BDFONECLI,
    BDDDDFAXCLI,
    BDFONEFAXCLI,
    BDDDDCELCLI,
    BDCELCLI,
    BDCXPCLI,
    BDIECLI,
    BDIMCLI,
    BDEMAILCLI,
    BDEMAILFINCLI,
    BDCAPITALSOC,
    BDORGAOPUBLICO,
    /*BDDATAENTRADA,
    BDDATASAIDA,*/
    BDNUMFUN,
    BDINATIVO,
    BDCODPLATRIB,
    BDCODPLANOONLINE,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDNOMCID,
    BDSIGLAUF,
    /*BDDESCSITCLI,*/
    BDDESCCNAE,
    BDDESCNAT,
    BDDESCPLATRIB,
    BDCODIBGECID,
    BDCODFEDCID,
    BDCODSPEDPAIS,
    BDCODPLASITFIN,
    BDDESCPLASITFIN,
    BDCODSITCLI,
    BDCODZONA,
    BDNOMEZONA,
    bdcodemp,
    bdtipocli
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^


SET TERM ; ^


/******************************************************************************/
/***                                 Views                                  ***/
/******************************************************************************/

/*VIEW VW_VFIN_BASE_TCLIENTE_REF_TOTAL*/
CREATE OR ALTER VIEW VW_VFIN_BASE_TCLIENTE_REF_TOTAL(
    BDCODCLI,
    BDREFCLI,
    BDCODCID,
    BDCODCNAE,
    BDCODNATJUR,
    BDCODSITCLI,
    BDCNPJCLI,
    BDAPECLI,
    BDNOMCLI,
    BDNOMREDUZCLI,
    BDCEPCLI,
    BDLOGRCLI,
    BDENDCLI,
    BDNUMCLI,
    BDCOMPLCLI,
    BDBAICLI,
    BDDDDCLI,
    BDFONECLI,
    BDDDDFAXCLI,
    BDFONEFAXCLI,
    BDDDDCELCLI,
    BDCELCLI,
    BDCXPCLI,
    BDIECLI,
    BDIMCLI,
    BDEMAILCLI,
    BDEMAILFINCLI,
    BDCAPITALSOC,
    BDORGAOPUBLICO,
    BDDATAENTRADA,
    BDDATASAIDA,
    BDNUMFUN,
    BDINATIVO,
    BDCODPLATRIB,
    BDCODCONT,
    BDCONTATO,
    BDPROFISCONTATO,
    BDDATANASCCON,
    BDCPFCON,
    BDCODCIDETI,
    BDNOMENDETI,
    BDLOGRETI,
    BDENDERECOETI,
    BDNUMEROETI,
    BDCOMPLETI,
    BDBAIRROETI,
    BDCEPETI,
    BDCXPETI,
    BDNOMCIDETI,
    BDSIGLAUFETI,
    BDCODIBGECIDETI,
    BDCODFEDCIDETI,
    BDCODENQFED,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO,
    BDANEXOIII,
    BDANEXOIV,
    BDANEXOV,
    BDANEXOVI,
    BDRETIMP,
    BDPERINSS,
    BDDEDINSSNF,
    BDUSARPERISS,
    BDRETIR,
    BDRETCSLL,
    BDRETCOF,
    BDRETPIS,
    BDDESTIR,
    BDDESTCSLL,
    BDDESTPIS,
    BDDESTCOF,
    BDINCENTCULT,
    BDCODSITESP,
    BDCODPLASITFIN,
    BDDESCPLASITFIN,
    BDORGAOCLI,
    BDNUMREGCLI,
    BDNOMECARTORIO,
    BDDATAREGCLI,
    BDLIVROREG,
    BDFOLHAREG,
    BDDOCAUXREG,
    bdusesocioostensiva)
AS
SELECT  cli.BDCODCLI,
        cli.BDREFCLI,
        ref.BDCODCID,
        ref.BDCODCNAE,
        ref.BDCODNATJUR,
        ref.BDCODSITCLI,
        tcli.BDCNPJCLI,
        ref.BDAPECLI,
        ref.BDNOMCLI,
        ref.BDNOMREDUZCLI,
        ref.BDCEPCLI,
        ref.BDLOGRCLI,
        ref.BDENDCLI,
        ref.BDNUMCLI,
        ref.BDCOMPLCLI,
        ref.BDBAICLI,
        ref.BDDDDCLI,
        ref.BDFONECLI,
        ref.BDDDDFAXCLI,
        ref.BDFONEFAXCLI,
        ref.BDDDDCELCLI,
        ref.BDCELCLI,
        ref.BDCXPCLI,
        ref.BDIECLI,
        ref.BDIMCLI,
        ref.BDEMAILCLI,
        ref.BDEMAILFINCLI,
        ref.BDCAPITALSOC,
        ref.BDORGAOPUBLICO,
        ref.BDDATAENTRADA,
        ref.BDDATASAIDA,
        ref.BDNUMFUN,
        ref.BDINATIVO,
        refemp.bdcodplatrib,
        cont.BDCODCONT,
        cont.BDCONTATO,
        cont.BDPROFISCONTATO,
        cont.BDDATANASCCON,
        cont.BDCPFCON,
        endere.BDCODCIDETI,
        endere.BDNOMENDETI,
        endere.BDLOGRETI,
        endere.BDENDERECOETI,
        endere.BDNUMEROETI,
        endere.BDCOMPLETI,
        endere.BDBAIRROETI,
        endere.BDCEPETI,
        endere.BDCXPETI,
        endere.BDNOMCIDETI,
        endere.bdsiglaufeti,
        endere.BDCODIBGECIDETI,
        endere.BDCODFEDCIDETI,
        enqfed.BDCODENQFED,
        enqfed.BDCOMERCIO,
        enqfed.BDINDUSTRIA,
        enqfed.BDSERVICO,
        enqfed.BDANEXOIII,
        enqfed.BDANEXOIV,
        enqfed.BDANEXOV,
        enqfed.BDANEXOVI,
        /*case when(tcli.bdcodtipocli=3)then impevt.bdretimp else imp.bdretimp end as BDRETIMP,
        case when(tcli.bdcodtipocli=3)then impevt.bdperinss else imp.BDPERINSS end as BDPERINSS,
        case when(tcli.bdcodtipocli=3)then impevt.bddedinssnf else imp.BDDEDINSSNF end as BDDEDINSSNF,
        case when(tcli.bdcodtipocli=3)then impevt.bdusarperiss else imp.BDUSARPERISS end as BDUSARPERISS,
        case when(tcli.bdcodtipocli=3)then impevt.bdretir else imp.BDRETIR end as BDRETIR,
        case when(tcli.bdcodtipocli=3)then impevt.bdretcsll else imp.BDRETCSLL end as BDRETCSLL,
        case when(tcli.bdcodtipocli=3)then impevt.bdretcof else imp.BDRETCOF end as BDRETCOF,
        case when(tcli.bdcodtipocli=3)then impevt.bdretpis else imp.BDRETPIS end as BDRETPIS,*/
        imp.bdretimp,
        imp.BDPERINSS,
        imp.BDDEDINSSNF,
        imp.BDUSARPERISS,
        imp.BDRETIR,
        imp.BDRETCSLL,
        imp.BDRETCOF,
        imp.BDRETPIS,
        imp.BDDESTIR,
        imp.BDDESTCSLL,
        imp.BDDESTPIS,
        imp.BDDESTCOF,
        --case when(tcli.bdcodtipocli=3)then impevt.bdincentcult else imp.BDINCENTCULT end as BDINCENTCULT,
        imp.BDINCENTCULT,
        imp.bdcodsitesp,
        ref.bdcodplasitfin,
        pla.bddescplasitfin,
        ref.BDORGAOCLI,
        ref.BDNUMREGCLI,
        ref.BDNOMECARTORIO,
        ref.BDDATAREGCLI,
        ref.BDLIVROREG,
        ref.BDFOLHAREG,
        ref.BDDOCAUXREG,
        ref.bdusesocioostensiva
FROM VW_VFIN_BASE_TCLIENTEREF_MAXMIN cli
inner join vfin_base_tcliente tcli on (tcli.bdcodcli = cli.bdcodcli)-- Gilberto - 17/02/2021 - W142612 - tipo de cliente eventual
JOIN vfin_base_tcliente_ref ref ON (ref.bdcodcli = cli.bdcodcli AND ref.bdrefcli = cli.bdrefcli)
LEFT OUTER JOIN vw_vfin_base_tclicontato cont ON (cont.bdcodcli = cli.bdcodcli AND cont.bdrefcli = cli.bdrefcli)
LEFT OUTER JOIN vw_vfin_base_tclienderecamento endere ON (endere.bdcodcli = cli.bdcodcli AND endere.bdrefcli = cli.bdrefcli)
LEFT OUTER JOIN vw_vfin_base_tclienqfed enqfed ON (enqfed.bdcodcli = cli.bdcodcli AND enqfed.bdrefcli = cli.bdrefcli)
LEFT OUTER JOIN vw_vfin_base_tcliimposto imp ON (imp.bdcodcli = cli.bdcodcli AND imp.bdrefcli = (select first 1 BDREFCLI
                                                                                                 from VW_VFIN_BASE_TCLIIMPOSTO
                                                                                                 where BDCODCLI = CLI.BDCODCLI
                                                                                                 order by BDREFCLI desc))
LEFT OUTER JOIN vfin_base_tplanositfin pla ON (pla.bdcodplasitfin = ref.bdcodplasitfin)
left outer join tempresas emp on (emp.bdcodcli = cli.bdcodcli)
left outer join tempresas_ref refemp on (refemp.bdcodemp = emp.bdcodemp and refemp.bdrefemp = cli.bdrefcli)
--left outer join vfin_base_tconfclievent impevt on (impevt.bdcodconfcli = ref.bdcodconfcli)-- Gilberto - 17/02/2021 - W142612 - configurações tipo de cliente eventual
;


SET TERM ^ ;

CREATE OR ALTER PROCEDURE SP_CONSULTACLIENTES_SIS (
    PRREFMICRO INTEGER,
    PRCODCLI INTEGER,
    PRCODSITCLI INTEGER)
RETURNS (
    BDCODCLI INTEGER,
    BDCODESC INTEGER,
    BDCODPRESER INTEGER,
    BDCODCLIMATRIZ INTEGER,
    BDCNPJCLI VARCHAR(18),
    BDDATAINIATIVCLI DATE,
    BDDATAFIMATIVCLI DATE,
    BDORGAOCLI VARCHAR(20),
    BDNUMREGCLI VARCHAR(40),
    BDNOMECARTORIO VARCHAR(100),
    BDDATAREGCLI DATE,
    BDLIVROREG VARCHAR(15),
    BDFOLHAREG VARCHAR(15),
    BDDOCAUXREG VARCHAR(18),
    BDCODTIPOCLI INTEGER,
    BDDATACADCLI DATE,
    BDCODCID INTEGER,
    BDCODCNAE INTEGER,
    BDCODNATJUR INTEGER,
    BDAPECLI DM_BDAPEMP,
    BDNOMCLI DM_BDNOMEMP,
    BDNOMREDUZCLI DM_BDNOMREDUZEMP,
    BDCEPCLI VARCHAR(9),
    BDLOGRCLI VARCHAR(15),
    BDENDCLI DM_BDENDERECO,
    BDNUMCLI DM_NUMEND,
    BDCOMPLCLI DM_BDCOMPENDERECO,
    BDBAICLI DM_BDBAIRRO,
    BDDDDCLI INTEGER,
    BDFONECLI DM_BDTELEFONE,
    BDDDDFAXCLI INTEGER,
    BDFONEFAXCLI DM_BDTELEFONE,
    BDDDDCELCLI INTEGER,
    BDCELCLI DM_BDTELEFONE,
    BDCXPCLI DM_CXPOSTAL,
    BDIECLI VARCHAR(20),
    BDIMCLI VARCHAR(20),
    BDEMAILCLI DM_BDEMAIL,
    BDEMAILFINCLI DM_BDEMAIL,
    BDCAPITALSOC DM_NUMERIC_15_2,
    BDORGAOPUBLICO DM_BOOLEAN,
    BDDATAENTRADA DATE,
    BDDATASAIDA DATE,
    BDCODCONT INTEGER,
    BDCONTATO VARCHAR(60),
    BDPROFISCONTATO VARCHAR(60),
    BDDATANASCCON DATE,
    BDCPFCON VARCHAR(18),
    BDCODCIDETI INTEGER,
    BDNOMENDETI DM_BDNOMEMP,
    BDLOGRETI VARCHAR(15),
    BDENDERECOETI DM_BDENDERECO,
    BDNUMEROETI INTEGER,
    BDCOMPLETI DM_BDCOMPENDERECO,
    BDBAIRROETI DM_BDBAIRRO,
    BDCEPETI VARCHAR(9),
    BDCXPETI DM_CXPOSTAL,
    BDNOMCIDETI VARCHAR(40),
    BDSIGLAUFETI VARCHAR(2),
    BDCODENQFED INTEGER,
    BDCOMERCIO DM_BOOLEAN,
    BDINDUSTRIA DM_BOOLEAN,
    BDSERVICO DM_BOOLEAN,
    BDANEXOIII DM_BOOLEAN,
    BDANEXOIV DM_BOOLEAN,
    BDANEXOV DM_BOOLEAN,
    BDANEXOVI DM_BOOLEAN,
    BDPERINSS DM_NUMERIC_7_4_ALIQ,
    BDDEDINSSNF DM_BOOLEAN,
    BDUSARPERISS INTEGER,
    BDRETIR DM_BOOLEAN,
    BDRETCSLL DM_BOOLEAN,
    BDRETCOF DM_BOOLEAN,
    BDRETPIS DM_BOOLEAN,
    BDNOMCID VARCHAR(40),
    BDSIGLAUF VARCHAR(2),
    BDDESCSITCLI VARCHAR(100),
    BDDESCCNAE VARCHAR(200),
    BDDESCNAT VARCHAR(100),
    BDNUMFUN INTEGER,
    BDINATIVO DM_BOOLEAN,
    BDCODPLATRIB INTEGER,
    BDDESCPLATRIB VARCHAR(50),
    BDCODIBGECID INTEGER,
    BDCODFEDCID INTEGER,
    BDCODSPEDPAIS INTEGER,
    BDINCENTCULT DM_BOOLEAN,
    BDCODIBGECIDETI INTEGER,
    BDCODFEDCIDETI INTEGER,
    BDCODPLANOONLINE INTEGER,
    BDCODPLAPADRAO INTEGER,
    BDCODSITESP INTEGER,
    BDCODPLASITFIN INTEGER,
    BDDESCPLASITFIN VARCHAR(50),
    BDCODHIST INTEGER,
    BDRETIMP INTEGER,
    BDDESTIR varchar(5),
    BDDESTCOF varchar(5),
    BDDESTPIS varchar(5),
    BDDESTCSLL varchar(5),
    BDCODEMP integer)
AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
DECLARE VARIABLE WPAR VARCHAR(50);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefmicro, NULL, NULL);

  wSql = ' select ';
  wSql = wSql||'ref.BDCODCLI, ';
  wSql = wSql||'ref.BDCODESC, ';
  wSql = wSql||'ref.BDCODPRESER, ';
  wSql = wSql||'ref.BDCODCLIMATRIZ, ';
  wSql = wSql||'ref.BDCNPJCLI, ';
  wSql = wSql||'ref.BDDATAINIATIVCLI, ';
  wSql = wSql||'ref.BDDATAFIMATIVCLI, ';
  wSql = wSql||'ref.BDORGAOCLI, ';
  wSql = wSql||'ref.BDNUMREGCLI, ';
  wSql = wSql||'ref.BDNOMECARTORIO, ';
  wSql = wSql||'ref.BDDATAREGCLI, ';
  wSql = wSql||'ref.BDLIVROREG, ';
  wSql = wSql||'ref.BDFOLHAREG, ';
  wSql = wSql||'ref.BDDOCAUXREG, ';
  wSql = wSql||'ref.BDCODTIPOCLI, ';
  wSql = wSql||'ref.BDDATACADCLI, ';
  wSql = wSql||'ref.BDCODCID, ';
  wSql = wSql||'ref.BDCODCNAE, ';
  wSql = wSql||'ref.BDCODNATJUR, ';
  /*wSql = wSql||'ref.BDCODSITCLI, ';*/
  wSql = wSql||'ref.BDAPECLI, ';
  wSql = wSql||'ref.BDNOMCLI, ';
  wSql = wSql||'ref.BDNOMREDUZCLI, ';
  wSql = wSql||'ref.BDCEPCLI, ';
  wSql = wSql||'ref.BDLOGRCLI, ';
  wSql = wSql||'ref.BDENDCLI, ';
  wSql = wSql||'ref.BDNUMCLI, ';
  wSql = wSql||'ref.BDCOMPLCLI, ';
  wSql = wSql||'ref.BDBAICLI, ';
  wSql = wSql||'ref.BDDDDCLI, ';
  wSql = wSql||'ref.BDFONECLI, ';
  wSql = wSql||'ref.BDDDDFAXCLI, ';
  wSql = wSql||'ref.BDFONEFAXCLI, ';
  wSql = wSql||'ref.BDDDDCELCLI, ';
  wSql = wSql||'ref.BDCELCLI, ';
  wSql = wSql||'ref.BDCXPCLI, ';
  wSql = wSql||'ref.BDIECLI, ';
  wSql = wSql||'ref.BDIMCLI, ';
  wSql = wSql||'ref.BDEMAILCLI, ';
  wSql = wSql||'ref.BDEMAILFINCLI, ';
  wSql = wSql||'ref.BDCAPITALSOC, ';
  wSql = wSql||'ref.BDORGAOPUBLICO, ';
  /*wSql = wSql||'ref.BDDATAENTRADA, ';
  wSql = wSql||'ref.BDDATASAIDA, ';*/
  wSql = wSql||'ref.bdnomcid, ';
  wSql = wSql||'ref.bdsiglauf, ';
  /*wSql = wSql||'ref.bddescsitcli, ';*/
  wSql = wSql||'ref.bddesccnae, ';
  wSql = wSql||'ref.bddescnat, ';
  wSql = wSql||'ref.bdnumfun, ';
  wSql = wSql||'ref.bdinativo, ';
  wSql = wSql||'ref.bdcodplatrib, ';
  wSql = wSql||'ref.bddescplatrib, ';
  wSql = wSql||'ref.bdcodibgecid, ';
  wSql = wSql||'ref.bdcodfedcid, ';
  wSql = wSql||'ref.bdcodspedpais, ';
  wSql = wSql||'ref.BDCODPLANOONLINE, ';
  wSql = wSql||'ref.BDCODPLAPADRAO, ';
  wSql = wSql||'ref.BDCODHIST, ';
  wSql = wSql||'reftot.BDCODCONT, ';
  wSql = wSql||'reftot.BDCONTATO, ';
  wSql = wSql||'reftot.BDPROFISCONTATO, ';
  wSql = wSql||'reftot.BDDATANASCCON, ';
  wSql = wSql||'reftot.BDCPFCON, ';
  wSql = wSql||'reftot.BDCODCIDETI, ';
  wSql = wSql||'reftot.BDNOMENDETI, ';
  wSql = wSql||'reftot.BDLOGRETI, ';
  wSql = wSql||'reftot.BDENDERECOETI, ';
  wSql = wSql||'reftot.BDNUMEROETI, ';
  wSql = wSql||'reftot.BDCOMPLETI, ';
  wSql = wSql||'reftot.BDBAIRROETI, ';
  wSql = wSql||'reftot.BDCEPETI, ';
  wSql = wSql||'reftot.BDCXPETI, ';
  wSql = wSql||'reftot.BDNOMCIDETI, ';
  wSql = wSql||'reftot.BDSIGLAUFETI, ';
  wSql = wSql||'reftot.BDCODENQFED, ';
  wSql = wSql||'reftot.BDCOMERCIO, ';
  wSql = wSql||'reftot.BDINDUSTRIA, ';
  wSql = wSql||'reftot.BDSERVICO, ';
  wSql = wSql||'reftot.BDANEXOIII, ';
  wSql = wSql||'reftot.BDANEXOIV, ';
  wSql = wSql||'reftot.BDANEXOV, ';
  wSql = wSql||'reftot.BDANEXOVI, ';
  wSql = wSql||'reftot.BDRETIMP, ';
  wSql = wSql||'reftot.BDPERINSS, ';
  wSql = wSql||'reftot.BDDEDINSSNF, ';
  wSql = wSql||'reftot.BDUSARPERISS, ';
  wSql = wSql||'reftot.BDRETIR, ';
  wSql = wSql||'reftot.BDRETCSLL, ';
  wSql = wSql||'reftot.BDRETCOF, ';
  wSql = wSql||'reftot.BDRETPIS, ';
  wSql = wSql||'reftot.BDDESTIR, ';
  wSql = wSql||'reftot.BDDESTCSLL, ';
  wSql = wSql||'reftot.BDDESTCOF, ';
  wSql = wSql||'reftot.BDDESTPIS, ';
  wSql = wSql||'reftot.BDINCENTCULT, ';
  wSql = wSql||'reftot.BDCODIBGECIDETI, ';
  wSql = wSql||'reftot.BDCODFEDCIDETI, ';
  wSql = wSql||'reftot.BDCODSITESP, ';
  wSql = wSql||'ref.BDCODPLASITFIN, ';
  wSql = wSql||'ref.BDDESCPLASITFIN, ';
  wSql = wSql||'ref.BDCODEMP ';


  WPAR = 'from sp_consultaclientes('||prrefmicro;
  IF (prcodcli IS NOT NULL AND prcodcli <> 0) THEN
    wpar = wpar||','||prcodcli||',';
  ELSE
    wpar = wpar||',null,';

  IF (PRCODSITCLI IS NULL) THEN
    wpar = wpar||'0) ref';
  ELSE
    wpar = wpar||PRCODSITCLI||') ref';

  wSql = wsql || wpar;

  wSql = wsql || ' left outer join VW_VFIN_BASE_TCLIENTE_REF_TOTAL reftot on (reftot.bdcodcli = ref.bdcodcli) ';

  wwhere = '';

  IF (prcodcli IS NOT NULL AND prcodcli <> 0) THEN
     wwhere = wwhere || ' ref.bdcodcli = '||prcodcli;

  /*Comentado pois não existe mais o campo BDCODSITCLI na tabela de clientes*/
  /* filra empresas inativas */
  /*IF (prcodsitcli IS NOT NULL AND prcodsitcli <> 0) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = 'ref.BDCODSITCLI) = '||prcodsitcli;
     END*/

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By ref.BDCODCLI';


  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODCLI,
    BDCODESC,
    BDCODPRESER,
    BDCODCLIMATRIZ,
    BDCNPJCLI,
    BDDATAINIATIVCLI,
    BDDATAFIMATIVCLI,
    BDORGAOCLI,
    BDNUMREGCLI,
    BDNOMECARTORIO,
    BDDATAREGCLI,
    BDLIVROREG,
    BDFOLHAREG,
    BDDOCAUXREG,
    BDCODTIPOCLI,
    BDDATACADCLI,
    BDCODCID,
    BDCODCNAE,
    BDCODNATJUR,
    /*BDCODSITCLI,*/
    BDAPECLI,
    BDNOMCLI,
    BDNOMREDUZCLI,
    BDCEPCLI,
    BDLOGRCLI,
    BDENDCLI,
    BDNUMCLI,
    BDCOMPLCLI,
    BDBAICLI,
    BDDDDCLI,
    BDFONECLI,
    BDDDDFAXCLI,
    BDFONEFAXCLI,
    BDDDDCELCLI,
    BDCELCLI,
    BDCXPCLI,
    BDIECLI,
    BDIMCLI,
    BDEMAILCLI,
    BDEMAILFINCLI,
    BDCAPITALSOC,
    BDORGAOPUBLICO,
    /*BDDATAENTRADA,
    BDDATASAIDA,*/
    BDNOMCID,
    BDSIGLAUF,
    /*BDDESCSITCLI,*/
    BDDESCCNAE,
    BDDESCNAT,
    BDNUMFUN,
    BDINATIVO,
    BDCODPLATRIB,
    BDDESCPLATRIB,
    BDCODIBGECID,
    BDCODFEDCID,
    BDCODSPEDPAIS,
    BDCODPLANOONLINE,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDCODCONT,
    BDCONTATO,
    BDPROFISCONTATO,
    BDDATANASCCON,
    BDCPFCON,
    BDCODCIDETI,
    BDNOMENDETI,
    BDLOGRETI,
    BDENDERECOETI,
    BDNUMEROETI,
    BDCOMPLETI,
    BDBAIRROETI,
    BDCEPETI,
    BDCXPETI,
    BDNOMCIDETI,
    BDSIGLAUFETI,
    BDCODENQFED,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO,
    BDANEXOIII,
    BDANEXOIV,
    BDANEXOV,
    BDANEXOVI,
    BDRETIMP,
    BDPERINSS,
    BDDEDINSSNF,
    BDUSARPERISS,
    BDRETIR,
    BDRETCSLL,
    BDRETCOF,
    BDRETPIS,
    BDDESTIR,
    BDDESTCSLL,
    BDDESTCOF,
    BDDESTPIS,
    BDINCENTCULT,
    BDCODIBGECIDETI,
    BDCODFEDCIDETI,
    BDCODSITESP,
    BDCODPLASITFIN,
    BDDESCPLASITFIN,
    BDCODEMP
  DO
  SUSPEND;
  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

SET TERM ; ^


/******************************************************************************/
/***                                 Views                                  ***/
/******************************************************************************/


/* View: VW_VFIN_CLIMENSAL_ABA_ADIC */
CREATE OR ALTER VIEW VW_VFIN_CLIMENSAL_ABA_ADIC(
    BDCODCLI,
    BDREFCLI,
    BDDATAREGCLI,
    BDDOCAUXREG,
    BDUSESOCIOOSTENSIVA)
AS
SELECT
  cliref.bdcodcli,
  cliref.bdrefcli,
  cliref.BDDATAREGCLI,
  cliref.BDDOCAUXREG,
  cliref.BDUSESOCIOOSTENSIVA
FROM vfin_base_tcliente_ref cliref;


/* View: VW_VFIN_CLIMENSAL_ABA_CAD */
CREATE OR ALTER VIEW VW_VFIN_CLIMENSAL_ABA_CAD(
    BDCODCLI,
    BDREFCLI,
    BDAPECLI,
    BDNOMCLI,
    BDNOMREDUZCLI,
    BDCNPJCLI,
    /*BDCODSITCLI,
    BDDESCSITCLI,
    BDDATAENTRADA,
    BDDATASAIDA,*/
    BDCEPCLI,
    BDCXPCLI,
    BDLOGRCLI,
    BDENDCLI,
    BDNUMCLI,
    BDCOMPLCLI,
    BDBAICLI,
    BDCODCID,
    BDNOMCID,
    BDSIGLAUF,
    BDDDDCLI,
    BDFONECLI,
    BDDDDFAXCLI,
    BDFONEFAXCLI,
    BDDDDCELCLI,
    BDCELCLI,
    BDIECLI,
    BDIMCLI,
    BDEMAILCLI,
    BDEMAILFINCLI,
    BDINATIVO,
    BDDATACADCLI,
    BDCODZONA,
    BDNOMEZONA)
AS
SELECT
  cliref.BDCODCLI,
  cliref.BDREFCLI,
  cliref.bdapecli,
  cliref.bdnomcli,
  cliref.bdnomreduzcli,
  cli.bdcnpjcli,
  /*cliref.bdcodsitcli,
  sit.bddescsitcli,
  cliref.bddataentrada,
  cliref.bddatasaida,*/
  cliref.bdcepcli,
  cliref.bdcxpcli,
  cliref.bdlogrcli,
  cliref.bdendcli,
  cliref.bdnumcli,
  cliref.bdcomplcli,
  cliref.bdbaicli,
  cliref.bdcodcid,
  cid.bdnomcid,
  uf.bdsiglauf,
  cliref.bddddcli,
  cliref.bdfonecli,
  cliref.bddddfaxcli,
  cliref.bdfonefaxcli,
  cliref.bddddcelcli,
  cliref.bdcelcli,
  cliref.bdiecli,
  cliref.bdimcli,
  cliref.bdemailcli,
  cliref.bdemailfincli,
  cliref.bdinativo,
  cli.bddatacadcli,
  cliref.bdcodzona,
  z.BDNOMEZONA
FROM
  vfin_base_tcliente_ref cliref
JOIN vfin_base_tcliente cli ON (cli.bdcodcli = cliref.bdcodcli)
/*left outer join vfin_base_ttabsitcli sit on (sit.bdcodsitcli = cliref.bdcodsitcli)*/
LEFT OUTER JOIN tcidade cid ON (cid.bdcodcid = cliref.bdcodcid)
LEFT OUTER JOIN tuf uf ON (uf.bdcoduf = cid.bdcoduf)
LEFT OUTER JOIN tzona Z on (cliref.bdcodcid = z.bdcodcid and cliref.bdcodzona = z.bdcodzona)
;


/* View: VW_VFIN_CLIMENSAL_ABA_CONT */
CREATE OR ALTER VIEW VW_VFIN_CLIMENSAL_ABA_CONT(
    BDCODCLI,
    BDREFCLI,
    BDCODCONT,
    BDNOMECONT,
    BDCONTATO,
    BDPROFISCONTATO,
    BDDATANASCCON,
    BDCPFCON)
AS
SELECT
  clicont.bdcodcli,
  clicont.bdrefcli,
  clicont.bdcodcont,
  cont.bdnomecont,
  clicont.bdcontato,
  clicont.bdprofiscontato,
  clicont.bddatanasccon,
  clicont.bdcpfcon
FROM vfin_base_tclicontato clicont
LEFT OUTER JOIN tcontador_padrao cont ON (cont.bdcodcont = clicont.bdcodcont)
;


/* View: VW_VFIN_CLIMENSAL_ABA_END */
CREATE OR ALTER VIEW VW_VFIN_CLIMENSAL_ABA_END(
    BDCODCLI,
    BDREFCLI,
    BDNOMENDETI,
    BDLOGRETI,
    BDENDERECOETI,
    BDNUMEROETI,
    BDCOMPLETI,
    BDBAIRROETI,
    BDCODCIDETI,
    BDNOMCIDETI,
    BDSIGLAUFETI,
    BDCEPETI,
    BDCXPETI)
AS
SELECT
   cliend.bdcodcli,
   cliend.bdrefcli,
   cliend.bdnomendeti,
   cliend.bdlogreti,
   cliend.bdenderecoeti,
   cliend.bdnumeroeti,
   cliend.bdcompleti,
   cliend.bdbairroeti,
   cliend.bdcodcideti,
   cid.bdnomcid,
   uf.bdsiglauf,
   cliend.bdcepeti,
   cliend.bdcxpeti
FROM vfin_base_tclienderecamento cliend
LEFT OUTER JOIN tcidade cid ON (cid.bdcodcid = cliend.bdcodcideti)
LEFT OUTER JOIN tuf uf ON (uf.bdcoduf = cid.bdcoduf)
;


/* View: VW_VFIN_CLIMENSAL_ABA_IMP */
CREATE OR ALTER VIEW VW_VFIN_CLIMENSAL_ABA_IMP(
    BDCODCLI,
    BDREFCLI,
    BDPERINSS,
    BDDEDINSSNF,
    BDUSARPERISS,
    BDRETIR,
    BDRETCSLL,
    BDRETCOF,
    BDRETPIS,
    BDINCENTCULT,
    BDCODSITESP,
    BDCODEXPSITESP,
    BDDESCSITESP)
AS
SELECT
   cliimp.bdcodcli,
   cliimp.bdrefcli,
   COALESCE(cliimp.bdperinss, 0),
   COALESCE(cliimp.bddedinssnf, 'FALSE'),
   cliimp.bdusarperiss,
   COALESCE(cliimp.bdretir, 'FALSE'),
   COALESCE(cliimp.bdretcsll, 'FALSE'),
   COALESCE(cliimp.bdretcof, 'FALSE'),
   COALESCE(cliimp.bdretpis, 'FALSE'),
   COALESCE(cliimp.bdincentcult, 'FALSE'),
   cliimp.bdcodsitesp,
   sitesp.bdcodexpsitesp,
   sitesp.bddescsitesp
FROM vfin_base_tcliimposto cliimp
LEFT OUTER JOIN vfin_base_ttabsitesp sitesp ON (sitesp.bdcodsitesp = cliimp.bdcodsitesp)
;


/* View: VW_VFIN_CLIMENSAL_ABA_PLA */
CREATE OR ALTER VIEW VW_VFIN_CLIMENSAL_ABA_PLA(
    BDCODCLI,
    BDREFCLI,
    BDCODPLANOONLINE,
    BDDESCPLANOONLINE,
    BDCODPLAPADRAO,
    BDNOMEPLAP,
    BDCODHIST,
    BDNOMEPLAH,
    BDCODPLATRIB,
    BDDESCPLATRIB,
    BDCODPLASITFIN,
    BDDESCPLASITFIN)
AS
SELECT
  cliref.bdcodcli,
  cliref.bdrefcli,
  refemp.bdcodplanoonline,
  PLAOL.BDDESCRICAO,
  PLAOL.BDCODPLAPADRAO,
  PLAP.BDNOME,
  PLAOL.BDCODHIST,
  PLAH.BDNOME,
  PLAT.BDCODPLATRIB,
  PLAT.BDDESCPLATRIB,
  cliref.bdcodplasitfin, 
  plasit.BDDESCPLASITFIN
FROM
  VFIN_BASE_TCLIENTE_REF cliref
left outer join tempresas emp on (emp.bdcodcli = cliref.bdcodcli)
left outer join tempresas_ref refemp on (refemp.bdcodemp = emp.bdcodemp and refemp.bdrefemp = cliref.bdrefcli)
LEFT OUTER JOIN TPLANO_CONF_ONLINE PLAOL ON (PLAOL.BDCODPLANOONLINE = refemp.BDCODPLANOONLINE)
LEFT OUTER JOIN TPLANO_PADRAO PLAP ON (PLAP.BDCODPLAPADRAO = PLAOL.BDCODPLAPADRAO)
LEFT OUTER JOIN THIST PLAH ON (PLAH.BDCODHIST = PLAOL.BDCODHIST)
LEFT OUTER JOIN vct_plano_tributario PLAT ON (PLAT.bdcodplatrib = refemp.bdcodplatrib)
LEFT OUTER JOIN VFIN_BASE_TPLANOSITFIN plasit ON (plasit.BDCODPLASITFIN = cliref.BDCODPLASITFIN)
;


CREATE OR ALTER VIEW VW_VFIN_TSERVPARAMVALOR_MAXMIN(
    BDCODCLI,
    BDCODESC,
    BDCODCONTR,
    BDCHAVEFAIXA,
    BDREFFAIXA)
AS
SELECT serv.bdcodcli, serv.bdcodesc, serv.bdcodcontr, serv.bdchavefaixa,
       COALESCE((SELECT FIRST 1 x.bdreffaixa FROM vfin_esc_tservparamvalor x
                 WHERE x.bdcodcli     = serv.bdcodcli AND
                       x.bdcodesc     = serv.bdcodesc AND
                       x.bdcodcontr   = serv.bdcodcontr AND
                       x.bdchavefaixa = serv.bdchavefaixa AND
                 CAST(X.bdreffaixa AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
                 ORDER BY x.bdreffaixa DESC),
                 (SELECT FIRST 1 x.bdreffaixa FROM vfin_esc_tservparamvalor x
                  WHERE x.bdcodcli     = serv.bdcodcli AND
                        x.bdcodesc     = serv.bdcodesc AND
                        x.bdcodcontr   = serv.bdcodcontr AND
                        x.bdchavefaixa = serv.bdchavefaixa
                  ORDER BY x.bdreffaixa
                 )
                ) BDREFFAIXA
FROM vfin_esc_tservparamcontrato serv
;

CREATE OR ALTER VIEW VW_VFIN_TSERVPARAMCONTRATO(
    BDCODCLI,
    BDCODESC,
    BDCODCONTR,
    BDCHAVEFAIXA,
    BDREFFAIXA,
    BDMES01,
    BDMES02,
    BDMES03,
    BDMES04,
    BDMES05,
    BDMES06,
    BDMES07,
    BDMES08,
    BDMES09,
    BDMES10,
    BDMES11,
    BDMES12,
    BDCODOBRSER,
    BDDESCSERV,
    BDTIPSERV,
    BDFORMVALORFAIXA,
    BDVALORCALC)
AS
SELECT valmax.bdcodcli,
       valmax.bdcodesc,
       valmax.bdcodcontr, 
       valmax.bdchavefaixa,
       valmax.bdreffaixa,
       servparam.bdmes01,
       servparam.bdmes02,
       servparam.bdmes03,
       servparam.bdmes04,
       servparam.bdmes05,
       servparam.bdmes06,
       servparam.bdmes07,
       servparam.bdmes08,
       servparam.bdmes09,
       servparam.bdmes10,
       servparam.bdmes11,
       servparam.bdmes12,
       servparam.bdcodobrser,
       ser.bddescricao,
       ser.bdtipserv,
       servparamvalor.bdformvalorfaixa,
       servparamvalor.bdvalorcalc
FROM vfin_esc_tservparamcontrato servparam
JOIN vw_vfin_tservparamvalor_maxmin valmax ON (valmax.bdcodcli = servparam.bdcodcli AND valmax.bdcodesc = servparam.bdcodesc AND valmax.bdcodcontr = servparam.bdcodcontr
                                              AND valmax.bdchavefaixa = servparam.bdchavefaixa)
LEFT OUTER JOIN vfin_esc_tservparamvalor servparamvalor ON (servparamvalor.bdcodcli = valmax.bdcodcli AND servparamvalor.bdcodesc = valmax.bdcodesc
                                                       AND servparamvalor.bdcodcontr = valmax.bdcodcontr AND servparamvalor.bdchavefaixa = valmax.bdchavefaixa AND
                                                       servparamvalor.bdreffaixa = valmax.bdreffaixa
                                                       )
LEFT OUTER JOIN VCT_BASE_SERVICO ser ON (ser.bdcodobrser = servparam.bdcodobrser)
;

CREATE OR ALTER VIEW VWGR_FIN_ESCRITORIO(
    BDCODESC,
    BDNOMESC,
    BDCNPJESC,
    BDCRCESC,
    BDINIATIVESC,
    BDFIMATIVESC,
    BDCODESCMATRIZ,
    BDNOMESCMATRIZ,
    BDCODCNAEESC,
    BDDESCCNAEESC,
    BDCEPESC,
    BDLOGRESC,
    BDENDESC,
    BDNUMESC,
    BDCOMPLESC,
    BDBAIESC,
    BDCODCIDESC,
    BDNOMCIDESC,
    BDSIGLAUFESC,
    BDIMESC,
    BDIEESC,
    BDDDDESC,
    BDFONEESC,
    BDDDDFAXESC,
    BDFAXESC,
    BDDDDCELULARESC,
    BDCELULARESC,
    BDEMAILESC,
    BDCODCONTAB,
    BDNOMECONTAB,
    BDCPFCONTAB,
    BDRGCONTAB,
    BDCRCCONTAB,
    BDCMCCONTAB,
    BDDATANASCCONTAB,
    BDTIPOCONTCONTAB,
    BDQUALICONTAB,
    BDEXPQUALICONTAB,
    BDDESCQUALICONTAB,
    BDCODOCUPACONTAB,
    BDDESCOCUPACONTAB,
    BDINDCRCCONTAB,
    BDCEPCONTAB,
    BDLOGRCONTAB,
    BDENDCONTAB,
    BDNUMCONTAB,
    BDCOMPLCONTAB,
    BDCODCIDCONTAB,
    BDNOMCIDCONTAB,
    BDSIGLAUFCONTAB,
    BDDDDCONTAB,
    BDFONECONTAB,
    BDDDDFAXCONTAB,
    BDFAXCONTAB,
    BDDDDCELULARCONTAB,
    BDCELULARCONTAB,
    BDEMAILCONTAB,
    BDCODFISCAL,
    BDNOMEFISCAL,
    BDCPFFISCAL,
    BDRGFISCAL,
    BDCRCFISCAL,
    BDCMCFISCAL,
    BDDATANASCFISCAL,
    BDTIPOCONTFISCAL,
    BDQUALIFISCAL,
    BDEXPQUALIFISCAL,
    BDDESCQUALIFISCAL,
    BDCODOCUPAFISCAL,
    BDDESCOCUPAFISCAL,
    BDINDCRCFISCAL,
    BDCEPFISCAL,
    BDLOGRFISCAL,
    BDENDFISCAL,
    BDNUMFISCAL,
    BDCOMPLFISCAL,
    BDCODCIDFISCAL,
    BDNOMCIDFISCAL,
    BDSIGLAUFFISCAL,
    BDDDDFISCAL,
    BDFONEFISCAL,
    BDDDDFAXFISCAL,
    BDFAXFISCAL,
    BDDDDCELULARFISCAL,
    BDCELULARFISCAL,
    BDEMAILFISCAL,
    BDCODFOLHA,
    BDNOMEFOLHA,
    BDCPFFOLHA,
    BDRGFOLHA,
    BDCRCFOLHA,
    BDCMCFOLHA,
    BDDATANASCFOLHA,
    BDTIPOCONTFOLHA,
    BDQUALIFOLHA,
    BDEXPQUALIFOLHA,
    BDDESCQUALIFOLHA,
    BDCODOCUPAFOLHA,
    BDDESCOCUPAFOLHA,
    BDINDCRCFOLHA,
    BDCEPFOLHA,
    BDLOGRFOLHA,
    BDENDFOLHA,
    BDNUMFOLHA,
    BDCOMPLFOLHA,
    BDCODCIDFOLHA,
    BDNOMCIDFOLHA,
    BDSIGLAUFFOLHA,
    BDDDDFOLHA,
    BDFONEFOLHA,
    BDDDDFAXFOLHA,
    BDFAXFOLHA,
    BDDDDCELULARFOLHA,
    BDCELULARFOLHA,
    BDEMAILFOLHA,
    BDDESCENQFEDESC,
    BDANEXOIIIESC,
    BDANEXOIVESC,
    BDANEXOVESC,
    BDANEXOVIESC,
    BDPERMULATE,
    BDPERMULATEPOREXT,
    BDFORMACALCJUR,
    BDPERJURATE,
    BDPERJURATEPOREXT)
AS
SELECT esc.bdcodesc, esc.bdnomesc, esc.bdcnpjesc, esc.bdcrcesc, esc.bdiniativesc,
esc.bdfimativesc, esc.bdcodescmatriz, (mat.bdnomesc) bdnomescmatriz, (esc.bdcodcnae) bdcodcnaeesc,
(cnae.bddesccnae) bddesccnaeesc, esc.bdcepesc, esc.bdlogresc, esc.bdendesc, esc.bdnumesc,
esc.bdcomplesc, esc.bdbaiesc, (esc.bdcodcid) bdcodcidesc, (cidesc.bdnomcid) bdnomcidesc,
(ufesc.bdsiglauf) bdsiglaufesc, esc.bdimesc, esc.bdieesc, esc.bddddesc, esc.bdfoneesc, esc.bddddfaxesc,
esc.bdfaxesc, esc.bddddcelularesc, esc.bdcelularesc, esc.bdemailesc,

(contcontab.bdcodcont) bdcodcontab, (contcontab.bdnomecont) bdnomecontab,
(contcontab.bdcpfcont) bdcpfcontab, (contcontab.bdrgcont) bdrgcontab,
(contcontab.bdcrccont) bdcrccontab, (contcontab.bdcmccont) bdcmccontab,
(contcontab.bddatanasccont) bddatanasccontab,
(CASE WHEN contcontab.bdtipocontabilista = 0 THEN 'Contabilista'
      WHEN contcontab.bdtipocontabilista = 1 THEN 'Escritório'
      WHEN contcontab.bdtipocontabilista = 2 THEN 'Individual'
      ELSE 'Não informado' END) bdtipocontcontab,
(contcontab.bdqualificacaosoc) bdqualicontab, (quacontab.bdexpqualisoc) bdexpqualicontab,
(quacontab.bddescqualisoc) bddescqualicontab, (contcontab.bdcodocupa) bdcodocupacontab,
(ocucontab.bddescocupa) bddescocupacontab, (contcontab.bdindcrc) bdindcrccontab,
(contcontab.bdcepcont) bdcepcontab, (contcontab.bdlogrcont) bdlogrcontab,
(contcontab.bdendcont) bdendcontab, (contcontab.bdnumerocont) bdnumcontab,
(contcontab.bdcomplcont) bdcomplcontab, (contcontab.bdcodcid) bdcodcidcontab,
(cidcontab.bdnomcid) bdnomcidcontab, (ufcontab.bdsiglauf) bdsiglaufcontab,
(contcontab.bddddcont) bddddcontab, (contcontab.bdfonecont) bdfonecontab,
(contcontab.bddddfaxcont) bddddfaxcontab, (contcontab.bdfaxcont) bdfaxcontab,
(contcontab.bddddcelularcont) bddddcelularcontab, (contcontab.bdcelularcont) bdcelularcontab,
(contcontab.bdemailcont) bdemailcontab,

(contfiscal.bdcodcont) bdcodfiscal, (contfiscal.bdnomecont) bdnomefiscal,
(contfiscal.bdcpfcont) bdcpffiscal, (contfiscal.bdrgcont) bdrgfiscal,
(contfiscal.bdcrccont) bdcrcfiscal, (contfiscal.bdcmccont) bdcmcfiscal,
(contfiscal.bddatanasccont) bddatanascfiscal,
(CASE WHEN contfiscal.bdtipocontabilista = 0 THEN 'Contabilista'
      WHEN contfiscal.bdtipocontabilista = 1 THEN 'Escritório'
      WHEN contfiscal.bdtipocontabilista = 2 THEN 'Individual'
      ELSE 'Não informado' END) bdtipocontfiscal,
(contfiscal.bdqualificacaosoc) bdqualifiscal, (quafiscal.bdexpqualisoc) bdexpqualifiscal,
(quafiscal.bddescqualisoc) bddescqualifiscal, (contfiscal.bdcodocupa) bdcodocupafiscal,
(ocufiscal.bddescocupa) bddescocupafiscal, (contfiscal.bdindcrc) bdindcrcfiscal,
(contfiscal.bdcepcont) bdcepfiscal, (contfiscal.bdlogrcont) bdlogrfiscal,
(contfiscal.bdendcont) bdendfiscal, (contfiscal.bdnumerocont) bdnumfiscal,
(contfiscal.bdcomplcont) bdcomplfiscal, (contfiscal.bdcodcid) bdcodcidfiscal,
(cidfiscal.bdnomcid) bdnomcidfiscal, (uffiscal.bdsiglauf) bdsiglauffiscal,
(contfiscal.bddddcont) bddddfiscal, (contfiscal.bdfonecont) bdfonefiscal,
(contfiscal.bddddfaxcont) bddddfaxfiscal, (contfiscal.bdfaxcont) bdfaxfiscal,
(contfiscal.bddddcelularcont) bddddcelularfiscal, (contfiscal.bdcelularcont) bdcelularfiscal,
(contfiscal.bdemailcont) bdemailfiscal,

(contfolha.bdcodcont) bdcodfolha, (contfolha.bdnomecont) bdnomefolha,
(contfolha.bdcpfcont) bdcpffolha, (contfolha.bdrgcont) bdrgfolha,
(contfolha.bdcrccont) bdcrcfolha, (contfolha.bdcmccont) bdcmcfolha,
(contfolha.bddatanasccont) bddatanascfolha,
(CASE WHEN contfolha.bdtipocontabilista = 0 THEN 'Contabilista'
      WHEN contfolha.bdtipocontabilista = 1 THEN 'Escritório'
      WHEN contfolha.bdtipocontabilista = 2 THEN 'Individual'
      ELSE 'Não informado' END) bdtipocontfolha,
(contfolha.bdqualificacaosoc) bdqualifolha, (quafolha.bdexpqualisoc) bdexpqualifolha,
(quafolha.bddescqualisoc) bddescqualifolha, (contfolha.bdcodocupa) bdcodocupafolha,
(ocufolha.bddescocupa) bddescocupafolha, (contfolha.bdindcrc) bdindcrcfolha,
(contfolha.bdcepcont) bdcepfolha, (contfolha.bdlogrcont) bdlogrfolha,
(contfolha.bdendcont) bdendfolha, (contfolha.bdnumerocont) bdnumfolha,
(contfolha.bdcomplcont) bdcomplfolha, (contfolha.bdcodcid) bdcodcidfolha,
(cidfolha.bdnomcid) bdnomcidfolha, (uffolha.bdsiglauf) bdsiglauffolha,
(contfolha.bddddcont) bddddfolha, (contfolha.bdfonecont) bdfonefolha,
(contfolha.bddddfaxcont) bddddfaxfolha, (contfolha.bdfaxcont) bdfaxfolha,
(contfolha.bddddcelularcont) bddddcelularfolha, (contfolha.bdcelularcont) bdcelularfolha,
(contfolha.bdemailcont) bdemailfolha,

(enqfed.bddescenqfed) bddescenqfedesc,
(CASE WHEN UPPER(ef.bdanexoiii) = 'TRUE' THEN 'Sim' ELSE 'Não' END) bdanexoiiiesc,
(CASE WHEN UPPER(ef.bdanexoiv)  = 'TRUE' THEN 'Sim' ELSE 'Não' END) bdanexoivesc,
(CASE WHEN UPPER(ef.bdanexov) = 'TRUE' THEN 'Sim' ELSE 'Não' END) bdanexovesc,
(CASE WHEN UPPER(ef.bdanexovi) = 'TRUE' THEN 'Sim' ELSE 'Não' END) bdanexoviesc,
(parfat.bdpermulate||'%') bdpermulate, (parfat.bdpermulate||' por cento') bdpermulateporext,
(CASE WHEN parfat.bdformacalcjur = 0 THEN 'Diário' ELSE 'Mensal' END) bdformacalcjur,
(parfat.bdperjurate||'%') bdperjurate, (parfat.bdperjurate||' por cento') bdperjurateporext

FROM tescritorio esc
LEFT OUTER JOIN tescritorio mat ON (mat.bdcodesc = esc.bdcodescmatriz)
LEFT OUTER JOIN tcnae cnae ON (cnae.bdcodcnae = esc.bdcodcnae)
LEFT OUTER JOIN tcidade cidesc ON (cidesc.bdcodcid = esc.bdcodcid)
LEFT OUTER JOIN tuf ufesc ON (ufesc.bdcoduf = cidesc.bdcoduf)
LEFT OUTER JOIN vfin_base_tescparfat parfat ON (parfat.bdcodesc = esc.bdcodesc)
left outer join tempresas emp on (emp.bdcodemp = esc.bdcodempinteg)
left outer join VW_TEMPRESAS_REF_MAX_MIN ref on (ref.bdcodemp = emp.bdcodemp)
left outer join tenqfed enq on (enq.bdcodemp = ref.bdcodemp and enq.bdrefemp = ref.bdrefemp)
LEFT OUTER JOIN tcadenqfed enqfed ON (enqfed.bdcodenqfed = enq.bdcodenqfed)
left outer join VEF_BASE_TEMPITEMSATV ef on (ef.bdcodemp = ref.bdcodemp and ef.bdrefemp = ref.bdrefemp)

LEFT OUTER JOIN tcontador_padrao contcontab ON (contcontab.bdcodcont = esc.bdcodcont)
LEFT OUTER JOIN tqualificacaosoc quacontab ON (quacontab.bdqualificacaosoc = contcontab.bdqualificacaosoc)
LEFT OUTER JOIN tocupacao ocucontab ON (ocucontab.bdcodocupa = contcontab.bdcodocupa)
LEFT OUTER JOIN tcidade cidcontab ON (cidcontab.bdcodcid = contcontab.bdcodcid)
LEFT OUTER JOIN tuf ufcontab ON (ufcontab.bdcoduf = cidcontab.bdcoduf)

LEFT OUTER JOIN tcontador_padrao contfiscal ON (contfiscal.bdcodcont = esc.bdcodcontef)
LEFT OUTER JOIN tqualificacaosoc quafiscal ON (quafiscal.bdqualificacaosoc = contfiscal.bdqualificacaosoc)
LEFT OUTER JOIN tocupacao ocufiscal ON (ocufiscal.bdcodocupa = contfiscal.bdcodocupa)
LEFT OUTER JOIN tcidade cidfiscal ON (cidfiscal.bdcodcid = contfiscal.bdcodcid)
LEFT OUTER JOIN tuf uffiscal ON (uffiscal.bdcoduf = cidfiscal.bdcoduf)

LEFT OUTER JOIN tcontador_padrao contfolha ON (contfolha.bdcodcont = esc.bdcodcontrh)
LEFT OUTER JOIN tqualificacaosoc quafolha ON (quafolha.bdqualificacaosoc = contfolha.bdqualificacaosoc)
LEFT OUTER JOIN tocupacao ocufolha ON (ocufolha.bdcodocupa = contfolha.bdcodocupa)
LEFT OUTER JOIN tcidade cidfolha ON (cidfolha.bdcodcid = contfolha.bdcodcid)
LEFT OUTER JOIN tuf uffolha ON (uffolha.bdcoduf = cidfolha.bdcoduf)
ORDER BY esc.bdcodesc
;

CREATE OR ALTER VIEW VWGR_FIN_CONTRATO(
    BDCODCLI,
    BDCODESC,
    BDCODCONTR,
    BDDESCCONTR,
    BDDATAINI,
    BDDATAINIPOREXT,
    BDDATAFIN,
    BDDIAVENC,
    BDCHAVECTABAN,
    BDDESCCTABAN,
    BDNOMCLI,
    BDAPECLI,
    BDDATACADCLI,
    BDNOMREDUZCLI,
    BDCNPJCLI,
    BDCODCLIMATRIZ,
    BDNOMCLIMATRIZ,
    BDCEPCLI,
    BDCXPCLI,
    BDLOGRCLI,
    BDENDCLI,
    BDNUMCLI,
    BDCOMPLCLI,
    BDBAICLI,
    BDCODCID,
    BDNOMCID,
    BDSIGLAUF,
    BDIMCLI,
    BDIECLI,
    BDDDDCLI,
    BDFONECLI,
    BDDDDFAXCLI,
    BDFAXCLI,
    BDDDDCELCLI,
    BDCELCLI,
    BDEMAILCLI,
    BDEMAILFINCLI,
    BDDATAINIATIVCLI,
    BDDATAFIMATIVCLI,
    BDORGAOPUBLICO,
    BDCODCNAE,
    BDDESCCNAE,
    BDCODNATJUR,
    BDDESCNAT,
    BDORGAOCLI,
    BDNUMREGCLI,
    BDDATAREGCLI,
    BDNOMECARTORIO,
    BDLIVROREG,
    BDFOLHAREG,
    BDDOCAUXREG,
    BDCAPITALSOC,
    BDDESCENQFED,
    BDNUMFUN,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO,
    BDANEXOIII,
    BDANEXOIV,
    BDANEXOV,
    BDANEXOVI)
AS
SELECT cli.bdcodcli, contr.bdcodesc, contr.bdcodcontr, contr.bddesccontr, contr.bddataini,
(SELECT EXTRACT(DAY FROM bddataini)||' de '||
TRIM(CASE EXTRACT(MONTH FROM bddataini)
      WHEN 1 THEN 'janeiro'
      WHEN 2 THEN 'fevereiro'
      WHEN 3 THEN 'março'
      WHEN 4 THEN 'abril'
      WHEN 5 THEN 'maio'
      WHEN 6 THEN 'junho'
      WHEN 7 THEN 'julho'
      WHEN 8 THEN 'agosto'
      WHEN 9 THEN 'setembro'
      WHEN 10 THEN 'outubro'
      WHEN 11 THEN 'novembro'
      WHEN 12 THEN 'dezembro'
END)||' de '||EXTRACT(YEAR FROM bddataini)
FROM vfin_esc_tcontrato contraux
WHERE contraux.bdcodcli = contr.bdcodcli
AND contraux.bdcodesc = contr.bdcodesc
AND contraux.bdcodcontr = contr.bdcodcontr) bddatainiporext,
contr.bddatafin, contr.bddiavenc, contr.bdchavectaban, cta.bddescctaban, cliref.bdnomcli, cliref.bdapecli,
cli.bddatacadcli, cliref.bdnomreduzcli, cli.bdcnpjcli, cli.bdcodclimatriz,
(mat.bdnomcli) bdnomclimatriz, cliref.bdcepcli, cliref.bdcxpcli, cliref.bdlogrcli, cliref.bdendcli, cliref.bdnumcli,
cliref.bdcomplcli, cliref.bdbaicli, cliref.bdcodcid, cid.bdnomcid, uf.bdsiglauf, cliref.bdimcli, cliref.bdiecli, cliref.bddddcli,
cliref.bdfonecli, cliref.bddddfaxcli, (cliref.bdfonefaxcli) bdfaxcli, cliref.bddddcelcli,
cliref.bdcelcli, cliref.bdemailcli, cliref.bdemailfincli, cli.bddatainiativcli, cli.bddatafimativcli,
(CASE WHEN UPPER(cliref.bdorgaopublico) = 'TRUE' THEN 'Sim' ELSE 'Não' END) bdorgaopublico,
cliref.bdcodcnae, cnae.bddesccnae, cliref.bdcodnatjur, natjur.bddescnat, cliref.bdorgaocli,
cliref.bdnumregcli, cliref.bddataregcli, cliref.bdnomecartorio, cliref.bdlivroreg, cliref.bdfolhareg,
cliref.bddocauxreg, cliref.bdcapitalsoc, cadenq.bddescenqfed, cliref.bdnumfun,
(CASE WHEN UPPER(enqfed.bdcomercio) = 'TRUE' THEN 'Sim' ELSE 'Não' END) bdcomercio,
(CASE WHEN UPPER(enqfed.bdindustria) = 'TRUE' THEN 'Sim' ELSE 'Não' END) bdindustria,
(CASE WHEN UPPER(enqfed.bdservico) = 'TRUE' THEN 'Sim' ELSE 'Não' END) bdservico,
(CASE WHEN UPPER(enqfed.bdanexoiii) = 'TRUE' THEN 'Sim' ELSE 'Não' END) bdanexoiii,
(CASE WHEN UPPER(enqfed.bdanexoiv) = 'TRUE' THEN 'Sim' ELSE 'Não' END) bdanexoiv,
(CASE WHEN UPPER(enqfed.bdanexov) = 'TRUE' THEN 'Sim' ELSE 'Não' END) bdanexov,
(CASE WHEN UPPER(enqfed.bdanexovi) = 'TRUE' THEN 'Sim' ELSE 'Não' END) bdanexovi
FROM vfin_esc_tcontrato contr
LEFT OUTER JOIN vfin_esc_tcontasban cta ON (cta.bdchavectaban = contr.bdchavectaban)
LEFT OUTER JOIN vfin_base_tcliente cli ON (cli.bdcodcli = contr.bdcodcli)
LEFT OUTER JOIN vw_vfin_clientes_ref cliref ON (cliref.bdcodcli = contr.bdcodcli)
LEFT OUTER JOIN vw_vfin_clientes_ref mat ON (mat.bdcodcli = cli.bdcodclimatriz)
LEFT OUTER JOIN tcidade cid ON (cid.bdcodcid = cliref.bdcodcid)
LEFT OUTER JOIN tuf uf ON (uf.bdcoduf = cid.bdcoduf)
LEFT OUTER JOIN tcnae cnae ON (cnae.bdcodcnae = cliref.bdcodcnae)
LEFT OUTER JOIN tnatjur natjur ON (natjur.bdcodnatjur = cliref.bdcodnatjur)
LEFT OUTER JOIN vfin_base_tclienqfed enqfed ON (enqfed.bdcodcli = cli.bdcodcli AND enqfed.bdrefcli = cliref.bdrefcli)
LEFT OUTER JOIN tcadenqfed cadenq ON (cadenq.bdcodenqfed = enqfed.bdcodenqfed)
ORDER BY contr.bdcodcontr, contr.bdcodcli, contr.bdcodesc
;

CREATE OR ALTER VIEW VWGR_FIN_SOCIOS(
    BDCODEMP,
    BDCODSOC,
    BDNOMSOC,
    BDCGCCEISOC,
    BDRGSOC,
    BDORGEMISOC,
    BDCODUFRG,
    BDSIGLAUFRG,
    BDDATANASCSOC,
    BDESTCIVILSOC,
    BDESTCIVILSOCDESC,
    BDCODCBO,
    BDDESCCBO,
    BDDESCQUALISOC,
    BDCEPSOC,
    BDLOGRSOC,
    BDENDSOC,
    BDNUMSOC,
    BDCOMPLSOC,
    BDBAISOC,
    BDCODCID,
    BDNOMCIDSOC,
    BDSIGLAUFSOC,
    BDDDSOC,
    BDTELRESSOC,
    BDDDDFAXSOC,
    BDFAXSOC,
    BDDDCELSOC,
    BDTELCELSOC,
    BDEMAILSOC,
    BDSIGNATARIOSPED,
    BDDATAENTSOC,
    BDDATASAISOC,
    BDRESPONSAVELSOC,
    BDEXTERIORSOC,
    BDCODPAIS,
    BDDESCPAIS,
    BDPERSOC,
    BDCPFRESPLEGALSOC,
    BDREGESTCIVILSOC,
    BDQUALILEGALDIPJSOC,
    BDQUALIRESPLEGALSOC,
    BDQUALISPEDSOC)
AS
select emp.bdcodemp, emp.bdcodsoc, emp.bdnomsoc, emp.bdcgcceisoc, emp.BDRGSOC, emp.bdorgemisoc, emp.bdcodufrg, ufrg.bdsiglauf bdsiglaufrg, emp.bddatanascsoc,
       emp.BDESTCIVILSOC,
       (CASE WHEN emp.BDESTCIVILSOC = 0 THEN 'Solteiro'
        WHEN emp.BDESTCIVILSOC = 1 THEN 'Casado'
        WHEN emp.BDESTCIVILSOC = 2 THEN 'Divorciado'
        WHEN emp.BDESTCIVILSOC = 3 THEN 'Viúvo'
        WHEN emp.BDESTCIVILSOC = 4 THEN 'Separado judicialmente'
        WHEN emp.BDESTCIVILSOC = 5 THEN 'União estável'
        ELSE 'Outros' END) BDESTCIVILSOCDESC, emp.bdcodcbo, cbo.bddesccbo, Qsoc.bddescqualisoc,
       emp.bdcepsoc,
       emp.bdlogrsoc, emp.bdendsoc, emp.bdnumsoc,
       emp.bdcomplsoc, emp.bdbaisoc, emp.bdcodcid, cid.bdnomcid BDNOMCIDSOC, UF.BDSIGLAUF BDSIGLAUFSOC,
       emp.BDDDDSOC AS bdddsoc, emp.bdtelressoc, emp.BDDDDFAXSOC, emp.BDFAXSOC, emp.bdddcelsoc, emp.bdtelcelsoc, emp.bdemailsoc,
       emp.BDSIGNATARIOSPED, emp.bddataentsoc, emp.bddatasaisoc, emp.bdresponsavelsoc,
       emp.bdexteriorsoc, emp.bdcodpais, Pais.bddescpais,
       emp.BDPERSOC, emp.BDCPFRESPLEGALSOC,
       emp.BDREGESTCIVILSOC,
       qdipj.bddescqualisoc as BDQUALILEGALDIPJSOC,
       qresp.bddescqualisoc as BDQUALIRESPLEGALSOC,
       qsped.bddescqualisoc as BDQUALISPEDSOC
from VW_EMPRESAS_TSOC_REF emp
left outer join VRH_BASE_TCBO cbo on (cbo.bdcodcbo = emp.bdcodcbo)
left outer join TQUALIFICACAOSOC qsoc on (qsoc.BDQUALIFICACAOSOC = emp.BDQUALIFICACAOSOC)
left outer join tqualificacaosoc qsped on (qsped.bdqualificacaosoc = emp.bdqualispedsoc)
left outer join tqualificacaosoc qresp on (qresp.bdqualificacaosoc = emp.bdqualiresplegalsoc)
left outer join tqualificacaosoc qdipj on (qdipj.bdqualificacaosoc = emp.bdqualilegaldipjsoc)
left outer join TPAIS Pais on (pais.BDCODPAIS = emp.BDCODPAIS)
left outer join tcidade cid on (cid.bdcodcid = emp.bdcodcid)
left outer join TUF UF on (UF.BDCODUF = cid.BDCODUF)
left outer join TUF UFRG on (UFRG.bdcoduf = emp.bdcodufrg)
;
/******************************************************************************/
/***                                 Views                                  ***/
/******************************************************************************/


/* View: VW_VFIN_ESC_TSERVICOGEST_ATUAL */
CREATE OR ALTER VIEW VW_VFIN_ESC_TSERVICOGEST_ATUAL(
    BDCODESC,
    BDCODOBRSER,
    BDCHAVE,
    BDREFERENCIA,
    BDCODCID,
    BDCODATVM,
    BDVALORPADRAO,
    BDIDCST,
    BDCODCST,
    BDCODCNAE,
    BDCOD_NBS)
AS
SELECT
  sgest.bdcodesc,
  sgest.bdcodobrser,
  sgest.bdchave,
  sgest.bdreferencia,
  sgest.bdcodcid,
  sgest.bdcodatvm,
  sgest.bdvalorpadrao,
  sgest.bdidcst,
  cst.bdcodcst,
  sgest.bdcodcnae,
  sgest.bdcod_nbs
FROM
  (
    SELECT bdcodobrser, bdcodesc,
    COALESCE
      (
        (SELECT MAX(s2.bdreferencia) FROM vfin_esc_tservico_gest s2
         WHERE s2.bdcodesc = sg.bdcodesc AND s2.bdcodobrser = sg.bdcodobrser
         AND CAST(s2.bdreferencia AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),

        (SELECT MIN(s1.bdreferencia) FROM vfin_esc_tservico_gest s1
         WHERE s1.bdcodesc = sg.bdcodesc AND s1.bdcodobrser = sg.bdcodobrser)
       ) AS bdreferencia
    FROM vfin_esc_tservico_gest sg
    GROUP BY bdcodobrser, bdcodesc
  ) ref
JOIN vfin_esc_tservico_gest sgest ON sgest.bdcodobrser = ref.bdcodobrser AND sgest.bdcodesc = ref.bdcodesc
                                     AND sgest.bdreferencia = ref.bdreferencia
LEFT OUTER JOIN vef_base_tcst cst ON (cst.bdid = sgest.bdidcst)
;

/******************************************************************************/
/***                                 Views                                  ***/
/******************************************************************************/


/* View: VW_VFIN_ESC_TIMPOSTOGEST_ATUAL */
CREATE OR ALTER VIEW VW_VFIN_ESC_TIMPOSTOGEST_ATUAL(
    BDCODESC,
    BDCODIMP,
    BDCHAVE,
    BDREFERENCIA,
    BDCODCID,
    BDCODATVM)
AS
SELECT
  igest.bdcodesc,
  igest.bdcodimp,
  igest.bdchave,
  igest.bdreferencia,
  igest.bdcodcid,
  igest.bdcodatvm
FROM
  (
    SELECT bdcodimp, bdcodesc,
    COALESCE
      (
        (SELECT MAX(i2.bdreferencia) FROM vfin_esc_timposto_gest i2
         WHERE i2.bdcodesc = ig.bdcodesc AND i2.bdcodimp = ig.bdcodimp
         AND CAST(i2.bdreferencia AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),

        (SELECT MIN(i1.bdreferencia) FROM vfin_esc_timposto_gest i1
         WHERE i1.bdcodesc = ig.bdcodesc AND i1.bdcodimp = ig.bdcodimp)
       ) AS bdreferencia
    FROM vfin_esc_timposto_gest ig
    GROUP BY bdcodimp, bdcodesc
  ) ref
JOIN vfin_esc_timposto_gest igest ON igest.bdcodimp = ref.bdcodimp AND igest.bdcodesc = ref.bdcodesc
                                     AND igest.bdreferencia = ref.bdreferencia
;


/******************************************************************************/
/***                                 Views                                  ***/
/******************************************************************************/


/* View: VW_VFIN_ESC_TOBRIGGEST_ATUAL */
CREATE OR ALTER VIEW VW_VFIN_ESC_TOBRIGGEST_ATUAL(
    BDCODESC,
    BDCODOBRSER,
    BDCHAVE,
    BDREFERENCIA,
    BDCODCID,
    BDCODATVM)
AS
SELECT
  ogest.bdcodesc,
  ogest.bdcodobrser,
  ogest.bdchave,
  ogest.bdreferencia,
  ogest.bdcodcid,
  ogest.bdcodatvm
FROM
  (
    SELECT bdcodobrser, bdcodesc,
    COALESCE
      (
        (SELECT MAX(o2.bdreferencia) FROM vfin_esc_tobrigacao_gest o2
         WHERE o2.bdcodesc = og.bdcodesc AND o2.bdcodobrser = og.bdcodobrser
         AND CAST(o2.bdreferencia AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),

        (SELECT MIN(o1.bdreferencia) FROM vfin_esc_tobrigacao_gest o1
         WHERE o1.bdcodesc = og.bdcodesc AND o1.bdcodobrser = og.bdcodobrser)
       ) AS bdreferencia
    FROM vfin_esc_tobrigacao_gest og
    GROUP BY bdcodobrser, bdcodesc
  ) ref
JOIN vfin_esc_tobrigacao_gest ogest ON ogest.bdcodobrser = ref.bdcodobrser AND ogest.bdcodesc = ref.bdcodesc
                                   AND ogest.bdreferencia = ref.bdreferencia
;


/* View: VIEW VW_VFIN_ESC_TRPSEMITLOTE_ULT */
CREATE OR ALTER VIEW VW_VFIN_ESC_TRPSEMITLOTE_ULT(
    BDCODESC,
    BDNUMLOTE,
    BDCHAVERPS,
    BDNUMDOC,
    BDCODVERIFICACAO,
    BDDATANFSE,
    BDDATACANCNFSE,
    BDVALORDEDUCAO,
    BDDISCRIMINACAO,
    BDSTATUS,
    BDCODEMP,
    BDCHAVE)
AS
SELECT rpslot.bdcodesc,
       rpslot.bdnumlote,
       rpslot.bdchaverps,
       rpslot.bdnumdoc,
       rpslot.bdcodverificacao,
       rpslot.bddatanfse,
       rpslot.bddatacancnfse,
       rpslot.bdvalordeducao,
       rpslot.bddiscriminacao,
       rpslot.bdstatus,
       rpslot.bdcodemp,
       rpslot.bdchave
FROM VFIN_ESC_TRPSEMITLOTE rpslot
INNER JOIN (SELECT bdcodesc, bdchaverps, MAX(bdnumlote) bdnumlote FROM VFIN_ESC_TRPSEMITLOTE
            GROUP BY bdcodesc, bdchaverps
            ) rpsmai ON (rpsmai.bdcodesc = rpslot.bdcodesc AND rpsmai.bdchaverps = rpslot.bdchaverps AND rpsmai.bdnumlote = rpslot.bdnumlote)
;

/* View: VW_VFIN_ESC_TOLFATMOVSER_ULT */
CREATE OR ALTER VIEW VW_VFIN_ESC_TOLFATMOVSER_ULT
( bdcodcli,
  bdcodesc,
  bdchavefatura,
  bdcodemp,
  bdchaveef
 )
AS
SELECT tolfat.bdcodcli,
       tolfat.bdcodesc,
       tolfat.bdchavefatura,
       tolfat.bdcodemp,
       tolfat.bdchaveef
FROM tol_vfin_esc_tfatmovser tolfat
INNER JOIN (SELECT bdcodesc, bdcodcli, bdchavefatura, bdcodemp, MAX(bdchaveef) bdchaveef FROM tol_vfin_esc_tfatmovser
            GROUP BY bdcodesc, bdcodcli, bdchavefatura, bdcodemp
            )
tolfatmai ON (tolfatmai.bdcodesc = tolfat.bdcodesc AND tolfatmai.bdcodcli = tolfat.bdcodcli AND tolfatmai.bdchavefatura = tolfat.bdchavefatura AND
              tolfatmai.bdcodemp = tolfat.bdcodemp AND tolfatmai.bdchaveef = tolfat.bdchaveef)
;


/* View: VW_VCT_BASE_SERVICOREF_MAXMIN */
CREATE OR ALTER VIEW VW_VCT_BASE_SERVICOREF_MAXMIN(
    BDCODOBRSER,
    BDREFSER)
AS
SELECT ser.bdcodobrser,
       COALESCE((SELECT FIRST 1 x.bdrefser FROM vct_base_servico_ref x
                 WHERE x.bdcodobrser = ser.bdcodobrser AND
                 CAST(X.bdrefser AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
                 ORDER BY x.bdrefser DESC),
                 (SELECT FIRST 1 x.bdrefser FROM vct_base_servico_ref x
                  WHERE x.bdcodobrser = ser.bdcodobrser
                  ORDER BY x.bdrefser
                 )
                ) BDREFSER
FROM vct_base_servico ser
;

/* View: VW_VCT_BASE_SERVICO_REF */
CREATE OR ALTER VIEW VW_VCT_BASE_SERVICO_REF(
    BDCODOBRSER,
    BDREFSER,
    BDVALORPADRAO)
AS
SELECT serref.bdcodobrser,
       serref.bdrefser,
       ref.bdvalorpadrao
FROM vw_vct_base_servicoref_maxmin serref
JOIN vct_base_servico_ref ref ON (ref.bdcodobrser = serref.bdcodobrser AND ref.bdrefser = serref.bdrefser)
;


SET TERM ^ ;

CREATE OR ALTER PROCEDURE SP_CONSULTASERVICOS (
    PRREFSER INTEGER,
    PRCODOBRSER INTEGER)
RETURNS (
    BDCODOBRSER INTEGER,
    BDCHAVE INTEGER,
    BDCLASSIFICACAO VARCHAR(60),
    BDDESCRICAO VARCHAR(100),
    BDPERIODICIDADE INTEGER,
    BDDIA INTEGER,
    BDANTECIPAR VARCHAR(5),
    BDVENCE INTEGER,
    BDALERTA INTEGER,
    BDCRIACAO DATE,
    BDEXTINTO DATE,
    BDSITEGOVERNO VARCHAR(255),
    BDPREVHORAS VARCHAR(6),
    BDTIPO SMALLINT,
    BDPREVDIAS INTEGER,
    BDCODSIS INTEGER,
    BDMESVENCE INTEGER,
    BDENTREGA INTEGER,
    BDTEMPOESTIMADO INTEGER,
    BDSABDOMFER INTEGER,
    BDPERISS NUMERIC(15,4),
    BDPERIRRF NUMERIC(15,4),
    BDPERCSLL NUMERIC(15,4),
    BDPERCOF NUMERIC(15,4),
    BDPERPIS NUMERIC(15,4),
    BDDEDISS VARCHAR(5),
    BDDEDIRRF VARCHAR(5),
    BDDEDCSLL VARCHAR(5),
    BDDEDCOFINS VARCHAR(5),
    BDDEDPIS VARCHAR(5),
    BDTIPSERV INTEGER,
    BDCALCINSS VARCHAR(5),
    BDSOFREREAJ VARCHAR(5),
    BDDESCONTO VARCHAR(5),
    BDVALORPADRAO DM_NUMERIC_15_2,
    BDCODCOBSERV INTEGER,
    BDCODCAT integer,
    BDCONTABILIZAR VARCHAR(5))
AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefser, NULL, NULL);

  wSql = ' select ';
  wSql = wSql||'ser.BDCODOBRSER, ';
  wSql = wSql||'ser.BDCHAVE, ';
  wSql = wSql||'ser.BDCLASSIFICACAO, ';
  wSql = wSql||'ser.BDDESCRICAO, ';
  wSql = wSql||'ser.BDPERIODICIDADE, ';
  wSql = wSql||'ser.BDDIA, ';
  wSql = wSql||'ser.BDANTECIPAR, ';
  wSql = wSql||'ser.BDVENCE, ';
  wSql = wSql||'ser.BDALERTA, ';
  wSql = wSql||'ser.BDCRIACAO, ';
  wSql = wSql||'ser.BDEXTINTO, ';
  wSql = wSql||'ser.BDSITEGOVERNO, ';
  wSql = wSql||'ser.BDPREVHORAS, ';
  wSql = wSql||'ser.BDTIPO, ';
  wSql = wSql||'ser.BDPREVDIAS, ';
  wSql = wSql||'ser.BDCODSIS, ';
  wSql = wSql||'ser.BDMESVENCE, ';
  wSql = wSql||'ser.BDENTREGA, ';
  wSql = wSql||'ser.BDTEMPOESTIMADO, ';
  wSql = wSql||'ser.BDSABDOMFER, ';
  wSql = wSql||'ser.BDPERISS, ';
  wSql = wSql||'ser.BDPERIRRF, ';
  wSql = wSql||'ser.BDPERCSLL, ';
  wSql = wSql||'ser.BDPERCOF, ';
  wSql = wSql||'ser.BDPERPIS, ';
  wSql = wSql||'ser.BDDEDISS, ';
  wSql = wSql||'ser.BDDEDIRRF, ';
  wSql = wSql||'ser.BDDEDCSLL, ';
  wSql = wSql||'ser.BDDEDCOFINS, ';
  wSql = wSql||'ser.BDDEDPIS, ';
  wSql = wSql||'ser.BDTIPSERV, ';
  wSql = wSql||'ser.BDCALCINSS, ';
  wSql = wSql||'ser.BDSOFREREAJ, ';
  wSql = wSql||'ser.BDDESCONTO, ';
  wSql = wSql||'refser.BDVALORPADRAO, ';
  wSql = wSql||'ser.BDCODCOBSERV, ';
  wSql = wSql||'ser.BDCODCAT, ';
  wSql = wSql||'ser.BDCONTABILIZAR ';
  wSql = wSql||'from VCT_BASE_SERVICO ser ';
  wSql = wsql||'left outer join VW_VCT_BASE_SERVICO_REF refser on (refser.bdcodobrser = ser.bdcodobrser) ';

  wwhere = '';

  IF (prcodobrser IS NOT NULL AND prcodobrser <> 0) THEN
     wwhere = wwhere || ' ser.bdcodobrser = '||prcodobrser;

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By ser.BDCODOBRSER';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODOBRSER,
    BDCHAVE,
    BDCLASSIFICACAO,
    BDDESCRICAO,
    BDPERIODICIDADE,
    BDDIA,
    BDANTECIPAR,
    BDVENCE,
    BDALERTA,
    BDCRIACAO,
    BDEXTINTO,
    BDSITEGOVERNO,
    BDPREVHORAS,
    BDTIPO,
    BDPREVDIAS,
    BDCODSIS,
    BDMESVENCE,
    BDENTREGA,
    BDTEMPOESTIMADO,
    BDSABDOMFER,
    BDPERISS,
    BDPERIRRF,
    BDPERCSLL,
    BDPERCOF,
    BDPERPIS,
    BDDEDISS,
    BDDEDIRRF,
    BDDEDCSLL,
    BDDEDCOFINS,
    BDDEDPIS,
    BDTIPSERV,
    BDCALCINSS,
    BDSOFREREAJ,
    BDDESCONTO,
    BDVALORPADRAO,
    BDCODCOBSERV,
    BDCODCAT,
    BDCONTABILIZAR
  DO
  SUSPEND;
  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

/*Adilson Hasckel - Sol. 14282 - 05/05/2016 - SP do financeiro utilizados na ONLINE - automatismos dos serviços */

CREATE OR ALTER PROCEDURE VFIN_CLASSIFSERVICO_ONLINE (
    PRCLAANT VARCHAR(100),
    PRCLANOVA VARCHAR(100))
RETURNS (
    BDCLAANTSERVICO VARCHAR(100),
    BDCLANOVASERVICO VARCHAR(100))
AS
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WADD VARCHAR(10);
BEGIN
  /* Procedure Text */
  IF (prclaant IS NOT NULL) THEN
     BEGIN
       wsql = 'select x.pos from pos('||''''||'.'||''''||','||''''||prclaant||''''||') x';
       EXECUTE STATEMENT wsql INTO wpos;

       BDCLAANTSERVICO = '';
       WHILE (wpos > 0) DO
         BEGIN
           wsql = SUBSTRING(prclaant FROM 1 FOR wpos-1);
           wsql = 'select x.bdretorno from preenche_esquerda('||''''||wsql||''''||',9,'||''''||'0'||''''||') x';

           EXECUTE STATEMENT wsql INTO wadd;
           IF (BDCLAANTSERVICO <> '') THEN
              BDCLAANTSERVICO = BDCLAANTSERVICO||'.';

           BDCLAANTSERVICO = BDCLAANTSERVICO||wadd;

           prclaant = SUBSTRING(prclaant FROM wpos+1);
           wsql = 'select x.pos from pos('||''''||'.'||''''||','||''''||prclaant||''''||') x';
           EXECUTE STATEMENT wsql INTO wpos;
         END

       wsql = prclaant;
       wsql = 'select x.bdretorno from preenche_esquerda('||''''||wsql||''''||',9,'||''''||'0'||''''||') x';

       EXECUTE STATEMENT wsql INTO wadd;
       IF (BDCLAANTSERVICO <> '') THEN
          BDCLAANTSERVICO = BDCLAANTSERVICO||'.';
       BDCLAANTSERVICO = BDCLAANTSERVICO||wadd;
       BDCLAANTSERVICO = '08.001.000000002.'||BDCLAANTSERVICO;
     END

  IF (prclanova IS NOT NULL) THEN
     BEGIN
       wsql = 'select x.pos from pos('||''''||'.'||''''||','||''''||prclanova||''''||') x';
       EXECUTE STATEMENT wsql INTO wpos;

       BDCLANOVASERVICO = '';
       WHILE (wpos > 0) DO
         BEGIN
           wsql = SUBSTRING(prclanova FROM 1 FOR wpos-1);
           wsql = 'select x.bdretorno from preenche_esquerda('||''''||wsql||''''||',9,'||''''||'0'||''''||') x';

           EXECUTE STATEMENT wsql INTO wadd;
           IF (BDCLANOVASERVICO <> '') THEN
              BDCLANOVASERVICO = BDCLANOVASERVICO||'.';

           BDCLANOVASERVICO = BDCLANOVASERVICO||wadd;

           prclanova = SUBSTRING(prclanova FROM wpos+1);
           wsql = 'select x.pos from pos('||''''||'.'||''''||','||''''||prclanova||''''||') x';
           EXECUTE STATEMENT wsql INTO wpos;
         END

       wsql = prclanova;
       wsql = 'select x.bdretorno from preenche_esquerda('||''''||wsql||''''||',9,'||''''||'0'||''''||') x';

       EXECUTE STATEMENT wsql INTO wadd;
       IF (BDCLANOVASERVICO <> '') THEN
          BDCLANOVASERVICO = BDCLANOVASERVICO||'.';
       BDCLANOVASERVICO = BDCLANOVASERVICO||wadd;
       BDCLANOVASERVICO = '08.001.000000002.'||BDCLANOVASERVICO;
     END

  SUSPEND;
END^

CREATE OR ALTER PROCEDURE VFIN_INSERT_NOVO_SERVICO_ONLINE (
    PRCLASSIFICACAO VARCHAR(100),
    PRCODOBRSER INTEGER)
AS
DECLARE VARIABLE WPLANO INTEGER;
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WCLASERONLINE VARCHAR(100);
DECLARE VARIABLE WFORMULA VARCHAR(100);
DECLARE VARIABLE WCODTIPOCONTA INTEGER;
BEGIN
  /* Procedure Text */
  FOR SELECT bdcodplanoonline FROM tplano_conf_online
  INTO
    wplano
  DO
    BEGIN
      --classificação dos serviços na ONLINE
      wSql = 'select BDCODTIPOCONTA from TTIPOCONTAONLINE tc where BDCLASSIFICACAO = '''||'08.001.000000002'||'''';
      EXECUTE STATEMENT wsql INTO wCodTipoConta;

      IF (wCodTipoConta > 0) THEN
        BEGIN
          wsql = 'select x.BDCLANOVASERVICO from VFIN_CLASSIFSERVICO_ONLINE(null,'||''''||prclassificacao||''''||') x';
          EXECUTE STATEMENT wsql INTO wClaSerOnline;
    
          wformula = 'SERFIN('||PRCODOBRSER||')';
          wformula = ''''||wformula||'''';
          wsql = 'insert into tconf_contas_online(bdcodplanoonline,bdcodtipoconta,bdcodobrser,bdclassificacao,bdformula) values('||
                                                  wplano||','||wCodTipoConta||','||PRCODOBRSER||','||''''||wClaSerOnline||''''||','||wformula||')';
          EXECUTE STATEMENT wsql;
        END
    END

--  suspend;
END^

CREATE OR ALTER PROCEDURE VFIN_UPDATE_SERVICO_ONLINE (
    PRCLAANT VARCHAR(1000),
    PRCLANOVA VARCHAR(1000),
    PRCODOBRSER INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WCLAANT VARCHAR(100);
DECLARE VARIABLE WCLANOVA VARCHAR(100);
DECLARE VARIABLE WCODTIPOCONTA INTEGER;
BEGIN
  /* Procedure Text */
  --classificação dos serviços na ONLINE
  wSql = 'select BDCODTIPOCONTA from TTIPOCONTAONLINE tc where BDCLASSIFICACAO = '''||'08.001.000000002'||'''';
  EXECUTE STATEMENT wsql INTO wCodTipoConta;

  IF (wCodTipoConta > 0) THEN
     BEGIN
       wsql = 'select x.BDCLAANTSERVICO, x.BDCLANOVASERVICO from VFIN_CLASSIFSERVICO_ONLINE('||
              ''''||prclaant||''''||
              ','||''''||prclanova||''''||') x';
        
       EXECUTE STATEMENT wsql INTO wclaant, wclanova;
       UPDATE tconf_contas_online SET bdclassificacao = :wclanova WHERE BDCODobrser = :PRCODOBRSER AND BDCODTIPOCONTA = :wCodTipoConta;
     END
END^

CREATE OR ALTER PROCEDURE VFIN_INSERT_CONTABAN_ONLINE (
    PRCHAVECTABAN INTEGER)
AS
DECLARE VARIABLE WPLANO INTEGER;
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WCLACONTABANONLINE VARCHAR(100);
DECLARE VARIABLE WFORMULA VARCHAR(100);
DECLARE VARIABLE WCODTIPOCONTA INTEGER;
BEGIN
  /* Procedure Text */
  FOR SELECT bdcodplanoonline FROM tplano_conf_online
  INTO
    wplano
  DO
    BEGIN
      --classificação das contas bancarias na ONLINE
      wSql = 'select BDCODTIPOCONTA from TTIPOCONTAONLINE tc where BDCLASSIFICACAO = '''||'08.001.000000006'||'''';
      EXECUTE STATEMENT wsql INTO wCodTipoConta;

      wsql = PRCHAVECTABAN;
      wsql = 'select x.bdretorno from preenche_esquerda('||''''||wsql||''''||',9,'||''''||'0'||''''||') x';
      EXECUTE STATEMENT wsql INTO WCLACONTABANONLINE;

      WCLACONTABANONLINE = '08.001.000000006'||'.'||WCLACONTABANONLINE;

      wformula = 'CTABANFIN('||PRCHAVECTABAN||')';
      wformula = ''''||wformula||'''';
      wsql = 'insert into tconf_contas_online(bdcodplanoonline,bdcodtipoconta,bdchavectaban,bdclassificacao,bdformula) values('||
                                              wplano||','||wCodTipoConta||','||PRCHAVECTABAN||','||''''||WCLACONTABANONLINE||''''||','||wformula||')';
      EXECUTE STATEMENT wsql;
    END

--  suspend;
END^

CREATE OR ALTER PROCEDURE VFIN_INSERT_CLIENTE_ONLINE (PRCODCLI INTEGER)
AS
DECLARE VARIABLE WPLANO INTEGER;
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WCLACLIONLINE VARCHAR(100);
DECLARE VARIABLE WFORMULA VARCHAR(100);
DECLARE VARIABLE WCODTIPOCONTA INTEGER;
BEGIN
  /* Procedure Text */
  FOR SELECT bdcodplanoonline FROM tplano_conf_online
  INTO
    wplano
  DO
    BEGIN
      --classificação dos clientes na ONLINE
      wSql = 'select BDCODTIPOCONTA from TTIPOCONTAONLINE tc where BDCLASSIFICACAO = '''||'08.001.000000001.000000001'||'''';
      EXECUTE STATEMENT wsql INTO wCodTipoConta;

      wsql = PRCODCLI;
      wsql = 'select x.bdretorno from preenche_esquerda('||''''||wsql||''''||',9,'||''''||'0'||''''||') x';
      EXECUTE STATEMENT wsql INTO WCLACLIONLINE;

      WCLACLIONLINE = '08.001.000000001.000000001'||'.'||WCLACLIONLINE;

      wformula = 'CLIFIXFIN('||PRCODCLI||')';
      wformula = ''''||wformula||'''';
      wsql = 'insert into tconf_contas_online(bdcodplanoonline,bdcodtipoconta,bdcodcli,bdclassificacao,bdformula) values('||
                                              wplano||','||wCodTipoConta||','||PRCODCLI||','||''''||WCLACLIONLINE||''''||','||wformula||')';
      EXECUTE STATEMENT wsql;
    END

--  suspend;
END^

SET TERM ; ^

/* View: VW_VCT_BASE_DESPESAREF_MAXMIN */
CREATE OR ALTER VIEW VW_VCT_BASE_DESPESAREF_MAXMIN(
    BDCODDESP,
    BDREFDESP)
AS
SELECT desp.bdcoddesp,
       COALESCE((SELECT FIRST 1 x.bdrefdesp FROM vfin_base_tdespesa_ref x
                 WHERE x.bdcoddesp = desp.bdcoddesp AND
                 CAST(X.bdrefdesp AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
                 ORDER BY x.bdrefdesp DESC),
                 (SELECT FIRST 1 x.bdrefdesp FROM vfin_base_tdespesa_ref x
                  WHERE x.bdcoddesp = desp.bdcoddesp
                  ORDER BY x.bdrefdesp
                 )
                ) BDREFDESP
FROM vfin_base_tdespesa desp
;

/** View: VW_VFIN_BASE_TDESPESA_REF */
CREATE OR ALTER VIEW VW_VFIN_BASE_TDESPESA_REF(
    BDCODDESP,
    BDREFDESP,
    BDVALORDESP,
    BDDIAVENC,
    BDSABDOMFER)
AS
SELECT despref.bdcoddesp,
       despref.bdrefdesp,
       ref.bdvalordesp,
       ref.bddiavenc,
       ref.bdsabdomfer
FROM vw_vct_base_despesaref_maxmin despref
JOIN vfin_base_tdespesa_ref ref ON (ref.bdcoddesp = despref.bdcoddesp AND ref.bdrefdesp = despref.bdrefdesp)
;

SET TERM ^ ;

CREATE OR ALTER PROCEDURE SP_CONSULTADESPESAS (
    PRREFDESP INTEGER,
    PRCODDESP INTEGER)
RETURNS (
    BDCODDESP INTEGER,
    BDCLASSDESP DM_CLASSCONTAS,
    BDDESCDESP VARCHAR(100),
    BDSABDOMFER INTEGER,
    BDDIAVENC INTEGER,
    BDTIPODESP INTEGER,
    BDVALORDESP DM_NUMERIC_15_2,
    BDDESCONTO DM_BOOLEAN,
    BDCODCAT integer)
    
AS
DECLARE VARIABLE WSQL VARCHAR(10240);
DECLARE VARIABLE WWHERE VARCHAR(20000);
BEGIN
  EXECUTE PROCEDURE sp_seta_competencia(prrefdesp, NULL, NULL);

  wSql = ' select ';
  wSql = wSql||'desp.BDCODDESP, ';
  wSql = wSql||'desp.BDCLASSDESP, ';
  wSql = wSql||'desp.BDDESCDESP, ';
  wSql = wSql||'desp.BDDESCONTO, ';
  wSql = wSql||'desp.BDCODCAT, ';
  wSql = wSql||'refdesp.BDSABDOMFER, ';
  wSql = wSql||'refdesp.BDDIAVENC, ';
  wSql = wSql||'desp.BDTIPODESP, ';
  wSql = wSql||'refdesp.BDVALORDESP ';
  wSql = wSql||'from VFIN_BASE_TDESPESA desp ';
  wSql = wsql||'left outer join VW_VFIN_BASE_TDESPESA_REF refdesp on (refdesp.bdcoddesp = desp.bdcoddesp) ';

  wwhere = '';

  IF (prcoddesp IS NOT NULL AND prcoddesp <> 0) THEN
     wwhere = wwhere || ' desp.bdcoddesp = '||prcoddesp;

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By desp.BDCODDESP';

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODDESP,
    BDCLASSDESP,
    BDDESCDESP,
    BDDESCONTO,
    BDCODCAT,
    BDSABDOMFER,
    BDDIAVENC,
    BDTIPODESP,
    bdvalordesp
  DO
  SUSPEND;
  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

SET TERM ; ^


/* View: VW_VFIN_BASE_TFORREF_MAXMIN */
CREATE OR ALTER VIEW VW_VFIN_BASE_TFORREF_MAXMIN(
    BDCODFOR,
    BDREFFOR)
AS
SELECT forn.bdcodfor,
       COALESCE((SELECT FIRST 1 r.bdreffor FROM vfin_base_tfornecedor_ref r
                 WHERE r.bdcodfor = forn.bdcodfor AND
                 CAST(r.bdreffor AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
                 ORDER BY r.bdreffor DESC),
                 (SELECT FIRST 1 r.bdreffor FROM vfin_base_tfornecedor_ref r
                  WHERE r.bdcodfor = forn.bdcodfor
                  ORDER BY r.bdreffor
                 )
                ) BDREFFOR
FROM vfin_base_tfornecedor forn
;


/* View: VW_VFIN_BASE_TFORNECEDOR */
CREATE OR ALTER VIEW VW_VFIN_BASE_TFORNECEDOR(
    BDCODFOR,
    BDCNPJFOR,
    BDREFFOR,
    BDCODCID,
    BDCODPAIS,
    BDNOMEFOR,
    BDAPEFOR,
    BDCEPFOR,
    BDLOGRFOR,
    BDENDFOR,
    BDNUMENDFOR,
    BDBAIFOR,
    BDCOMPLENDFOR,
    BDIEFOR,
    BDIMFOR,
    BDDDDFONEFOR,
    BDFONEFOR,
    BDDDDFAXFOR,
    BDFAXFOR,
    BDEMAILFOR,
    BDDATACADFOR,
    BDDDDCELFOR,
    BDCELFOR,
    BDCODDESP)
AS
SELECT
    forn.bdcodfor,
    forn.bdcnpjfor,
    m.bdreffor,
    r.bdcodcid,
    r.bdcodpais,
    r.bdnomefor,
    r.bdapefor,
    r.bdcepfor,
    r.bdlogrfor,
    r.bdendfor,
    r.bdnumendfor,
    r.bdbaifor,
    r.bdcomplendfor,
    r.bdiefor,
    r.bdimfor,
    r.bddddfonefor,
    r.bdfonefor,
    r.bddddfaxfor,
    r.bdfaxfor,
    r.bdemailfor,
    r.bddatacadfor,
    r.bddddcelfor,
    r.bdcelfor,
    r.bdcoddesp
FROM vfin_base_tfornecedor forn
LEFT OUTER JOIN vw_vfin_base_tforref_maxmin m ON forn.bdcodfor = m.bdcodfor
JOIN vfin_base_tfornecedor_ref r ON (r.bdcodfor = forn.bdcodfor AND m.bdreffor = r.bdreffor)
;

SET TERM ^ ;

CREATE OR ALTER procedure VFIN_SP_CONSFORNECEDORES (
    PRCODFOR integer,
    PRREF integer,
    PRWHEREFOR varchar(20000))
returns (
    BDCODFOR integer,
    BDCNPJFOR varchar(18),
    BDREFFOR integer,
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
    BDCODPAIS integer,
    BDDESCPAIS varchar(60),
    BDNOMEFOR DM_BDNOMEMP,
    BDAPEFOR DM_BDAPEMP,
    BDCEPFOR varchar(9),
    BDLOGRFOR DM_LOGRADOURO,
    BDENDFOR DM_BDENDERECO,
    BDNUMENDFOR DM_BDENDERECO_NR,
    BDBAIFOR DM_BDBAIRRO,
    BDCOMPLENDFOR DM_BDCOMPENDERECO,
    BDIEFOR varchar(20),
    BDIMFOR varchar(20),
    BDDDDFONEFOR integer,
    BDFONEFOR DM_BDTELEFONE,
    BDDDDFAXFOR integer,
    BDFAXFOR DM_BDTELEFONE,
    BDEMAILFOR DM_BDEMAIL,
    BDDATACADFOR date,
    BDDDDCELFOR integer,
    BDCELFOR DM_BDTELEFONE,
    BDCODDESP integer,
    BDDESCDESP varchar(100))
as
declare variable WSQL varchar(10240);
declare variable WWHERE varchar(20000);
BEGIN
    IF (prref IS NOT NULL) THEN
      EXECUTE PROCEDURE sp_seta_competencia(prref,NULL,NULL);

    wSql = ' select ';
    wSql = wSql || 'forn.BDCODFOR, ';
    wSql = wSql || 'forn.BDCNPJFOR, ';
    wSql = wSql || 'forn.BDREFFOR, ';
    wSql = wsql || 'forn.bdcodcid, ';
    wSql = wSql || 'cid.bdnomcid, ';
    wSql = wSql || 'uf.bdsiglauf, ';
    wSql = wSql || 'forn.bdcodpais, ';
    wSql = wSql || 'pais.bddescpais, ';
    wSql = wSql || 'forn.BDNOMEFOR, ';
    wSql = wSql || 'forn.BDAPEFOR, ';
    wSql = wSql || 'forn.BDCEPFOR, ';
    wSql = wSql || 'forn.BDLOGRFOR, ';
    wSql = wSql || 'forn.BDENDFOR, ';
    wSql = wSql || 'forn.BDNUMENDFOR, ';
    wSql = wSql || 'forn.BDBAIFOR, ';
    wSql = wSql || 'forn.BDCOMPLENDFOR, ';
    wSql = wSql || 'forn.BDIEFOR, ';
    wSql = wSql || 'forn.BDIMFOR, ';
    wSql = wSql || 'forn.BDDDDFONEFOR, ';
    wSql = wSql || 'forn.BDFONEFOR, ';
    wSql = wSql || 'forn.BDDDDFAXFOR, ';
    wSql = wSql || 'forn.BDFAXFOR, ';
    wSql = wSql || 'forn.BDEMAILFOR, ';
    wSql = wSql || 'forn.BDDATACADFOR, ';
    wSql = wSql || 'forn.BDDDDCELFOR, ';
    wSql = wSql || 'forn.BDCELFOR, ';
    wsql = wsql || 'forn.bdcoddesp, ';
    wsql = wsql || 'desp.bddescdesp ';
    wSql = wsql || 'FROM VW_VFIN_BASE_TFORNECEDOR forn ';
    wSql = wsql || 'left outer join tcidade CID on (CID.bdCODCID = forn.BDCODCID) ';
    wSql = wsql || 'left outer join tuf UF on (UF.bdCODUF = CID.BDCODUF) ';
    wSql = wSql || 'left outer join tpais pais on (pais.bdCODPAIS = forn.bdcodpais) ';
    wSql = wSql || 'left outer join VFIN_BASE_TDESPESA desp on (desp.bdcoddesp = forn.bdcoddesp) ';

  wwhere = '';
  IF (prcodfor IS NOT NULL AND prcodfor <> 0) THEN
    wwhere = wwhere || ' forn.bdcodfor = '||prcodfor;

  IF (prwherefor IS NOT NULL AND prwherefor <> '')  THEN
    BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

        wwhere = wwhere ||prwherefor;
    END

  IF (wwhere <> '') THEN
     wsql = wsql||' where '||wwhere;

  wSql = wsql || ' order By forn.bdcodfor';

  FOR EXECUTE STATEMENT wsql
  INTO
     :BDCODFOR,
     :BDCNPJFOR,
     :BDREFFOR,
     :BDCODCID,
     :BDNOMCID,
     :BDSIGLAUF,
     :BDCODPAIS,
     :BDDESCPAIS,
     :BDNOMEFOR,
     :BDAPEFOR,
     :BDCEPFOR,
     :BDLOGRFOR,
     :BDENDFOR,
     :BDNUMENDFOR,
     :BDBAIFOR,
     :BDCOMPLENDFOR,
     :BDIEFOR,
     :BDIMFOR,
     :BDDDDFONEFOR,
     :BDFONEFOR,
     :BDDDDFAXFOR,
     :BDFAXFOR,
     :BDEMAILFOR,
     :BDDATACADFOR,
     :bddddcelfor,
     :bdcelfor,
     :bdcoddesp,
     :bddescdesp
  DO
  SUSPEND;

  EXECUTE PROCEDURE sp_seta_competencia(NULL, NULL, NULL);
END^

SET TERM ; ^

/* View: VW_VFIN_CLIENTE_GERAL */
CREATE OR ALTER VIEW VW_VFIN_CLIENTE_GERAL(
    BDCODCLI,
    BDCODESC,
    BDCODPRESER,
    BDCODCLIMATRIZ,
    BDCNPJCLI,
    BDDATAINIATIVCLI,
    BDDATAFIMATIVCLI,
    BDORGAOCLI,
    BDNUMREGCLI,
    BDNOMECARTORIO,
    BDDATAREGCLI,
    BDLIVROREG,
    BDFOLHAREG,
    BDDOCAUXREG,
    BDCODTIPOCLI,
    BDDATACADCLI,
    BDCODCID,
    BDCODCNAE,
    BDCODNATJUR,
    BDCODSITCLI,
    BDAPECLI,
    BDNOMCLI,
    BDNOMREDUZCLI,
    BDCEPCLI,
    BDLOGRCLI,
    BDENDCLI,
    BDNUMCLI,
    BDCOMPLCLI,
    BDBAICLI,
    BDDDDCLI,
    BDFONECLI,
    BDDDDFAXCLI,
    BDFONEFAXCLI,
    BDDDDCELCLI,
    BDCELCLI,
    BDCXPCLI,
    BDIECLI,
    BDIMCLI,
    BDEMAILCLI,
    BDEMAILFINCLI,
    BDCAPITALSOC,
    BDORGAOPUBLICO,
    BDDATAENTRADA,
    BDDATASAIDA,
    BDNUMFUN,
    BDINATIVO,
    BDCODPLATRIB,
    BDCODPLANOONLINE,
    BDCODPLAPADRAO,
    BDCODHIST,
    BDNOMCID,
    BDSIGLAUF,
    BDDESCSITCLI,
    BDDESCCNAE,
    BDDESCNAT,
    BDDESCPLATRIB,
    BDCODIBGECID,
    BDCODFEDCID,
    BDCODSPEDPAIS,
    BDCODCONT,
    BDCONTATO,
    BDPROFISCONTATO,
    BDDATANASCCON,
    BDCPFCON,
    BDCODCIDETI,
    BDNOMENDETI,
    BDLOGRETI,
    BDENDERECOETI,
    BDNUMEROETI,
    BDCOMPLETI,
    BDBAIRROETI,
    BDCEPETI,
    BDCXPETI,
    BDNOMCIDETI,
    BDSIGLAUFETI,
    BDCODIBGECIDETI,
    BDCODFEDCIDETI,
    BDCODENQFED,
    BDCOMERCIO,
    BDINDUSTRIA,
    BDSERVICO,
    BDANEXOIII,
    BDANEXOIV,
    BDANEXOV,
    BDPERINSS,
    BDDEDINSSNF,
    BDUSARPERISS,
    BDRETIR,
    BDRETCSLL,
    BDRETCOF,
    BDRETPIS,
    BDINCENTCULT,
    BDCODSITESP,
    BDCODEXPSITESP,
    bdusesocioostensiva)
AS
SELECT
  cli.BDCODCLI, cli.BDCODESC, cli.BDCODPRESER, cli.BDCODCLIMATRIZ,
  cli.BDCNPJCLI, cli.BDDATAINIATIVCLI, cli.BDDATAFIMATIVCLI,
  refcli.BDORGAOCLI, refcli.BDNUMREGCLI, refcli.BDNOMECARTORIO, refcli.BDDATAREGCLI,
  refcli.BDLIVROREG, refcli.BDFOLHAREG, refcli.BDDOCAUXREG, cli.BDCODTIPOCLI, cli.BDDATACADCLI,
  refcli.BDCODCID, refcli.BDCODCNAE, refcli.BDCODNATJUR,
  refcli.BDCODSITCLI, refcli.BDAPECLI, refcli.BDNOMCLI,
  refcli.BDNOMREDUZCLI, refcli.BDCEPCLI, refcli.BDLOGRCLI,
  refcli.BDENDCLI, refcli.BDNUMCLI, refcli.BDCOMPLCLI,
  refcli.BDBAICLI, refcli.BDDDDCLI, refcli.BDFONECLI,
  refcli.BDDDDFAXCLI, refcli.BDFONEFAXCLI, refcli.BDDDDCELCLI,
  refcli.BDCELCLI, refcli.BDCXPCLI,refcli.BDIECLI, refcli.BDIMCLI,
  refcli.BDEMAILCLI, refcli.BDEMAILFINCLI, refcli.BDCAPITALSOC, refcli.BDORGAOPUBLICO,
  refcli.BDDATAENTRADA, refcli.BDDATASAIDA, refcli.bdnumfun, refcli.bdinativo, refcli.bdcodplatrib,
  refcli.BDCODPLANOONLINE, refcli.BDCODPLAPADRAO, refcli.BDCODHIST,
  cid.bdnomcid, uf.bdsiglauf,
  sitcli.bddescsitcli, cnae.BDDESCCNAE, natjur.bddescnat, tplatrib.bddescplatrib,
  cid.bdcodibge bdcodibgecid, cid.bdcodfed bdcodfedcid, pais.bdcodsped bdcodspedpais,
  cont.BDCODCONT, cont.BDCONTATO, cont.BDPROFISCONTATO, cont.BDDATANASCCON, cont.BDCPFCON,
  endere.BDCODCIDETI, endere.BDNOMENDETI, endere.BDLOGRETI, endere.BDENDERECOETI, endere.BDNUMEROETI,
  endere.BDCOMPLETI, endere.BDBAIRROETI, endere.BDCEPETI, endere.BDCXPETI, endere.BDNOMCIDETI, endere.bdsiglaufeti,
  endere.BDCODIBGECIDETI, endere.BDCODFEDCIDETI, enqfed.BDCODENQFED, enqfed.BDCOMERCIO, enqfed.BDINDUSTRIA,
  enqfed.BDSERVICO, enqfed.BDANEXOIII, enqfed.BDANEXOIV, enqfed.BDANEXOV, imp.BDPERINSS, imp.BDDEDINSSNF,
  imp.BDUSARPERISS, imp.BDRETIR, imp.BDRETCSLL, imp.BDRETCOF, imp.BDRETPIS, imp.BDINCENTCULT,
  imp.BDCODSITESP, sitesp.BDCODEXPSITESP,
  refcli.bdusesocioostensiva
  FROM VFIN_BASE_TCLIENTE cli
  JOIN vw_vfin_clientes_ref refcli ON (refcli.bdcodcli = cli.bdcodcli)
  LEFT OUTER JOIN tcidade cid ON (cid.bdcodcid = refcli.bdcodcid)
  LEFT OUTER JOIN tpais pais ON pais.bdcodpais = cid.bdcodpais
  LEFT OUTER JOIN tuf uf ON (uf.bdcoduf = cid.bdcoduf)
  LEFT OUTER JOIN vfin_base_ttabsitcli sitcli ON (sitcli.bdcodsitcli = refcli.bdcodsitcli)
  LEFT OUTER JOIN tcnae cnae ON (cnae.bdcodcnae = refcli.bdcodcnae)
  LEFT OUTER JOIN tnatjur natjur ON (natjur.bdcodnatjur = refcli.bdcodnatjur)
  LEFT OUTER JOIN VCT_PLANO_TRIBUTARIO tplatrib ON (tplatrib.bdcodplatrib = refcli.bdcodplatrib)
  LEFT OUTER JOIN vw_vfin_base_tclicontato cont ON (cont.bdcodcli = cli.bdcodcli AND cont.bdrefcli = refcli.bdrefcli)
  LEFT OUTER JOIN vw_vfin_base_tclienderecamento endere ON (endere.bdcodcli = cli.bdcodcli AND endere.bdrefcli = refcli.bdrefcli)
  LEFT OUTER JOIN vw_vfin_base_tclienqfed enqfed ON (enqfed.bdcodcli = cli.bdcodcli AND enqfed.bdrefcli = refcli.bdrefcli)
  LEFT OUTER JOIN vw_vfin_base_tcliimposto imp ON (imp.bdcodcli = cli.bdcodcli AND imp.bdrefcli = refcli.bdrefcli)
  LEFT OUTER JOIN vfin_base_ttabsitesp sitesp ON (sitesp.bdcodsitesp = imp.bdcodsitesp)
;

--Alt:12607 - INÍCIO
--            Inclusão de SPs para a tabela TDADOS_EMPRESAS, para permitir a geração de dados não apenas
--            do mês imediatamente anterior, mas sim de todos os meses a partir de 2015.
SET TERM ^ ;

CREATE OR ALTER PROCEDURE SP_BASE_TDADOS_EMPRESAS
RETURNS (
    BDEMPRESA INTEGER,
    BDANO INTEGER,
    BDMES INTEGER,
    BDVALOR NUMERIC(15,2))
AS
BEGIN
  FOR EXECUTE STATEMENT
    'select bdempresa, bdano, 1 as BDMES, bd01 as valor from tdados_empresas where (BDANO >= 2015) '||
    'union all '||
    'select bdempresa, bdano, 2 as BDMES, bd02 as valor from tdados_empresas where (BDANO >= 2015) '||
    'union all '||
    'select bdempresa, bdano, 3 as BDMES, bd03 as valor from tdados_empresas where (BDANO >= 2015) '||
    'union all '||
    'select bdempresa, bdano, 4 as BDMES, bd04 as valor from tdados_empresas where (BDANO >= 2015) '||
    'union all '||
    'select bdempresa, bdano, 5 as BDMES, bd05 as valor from tdados_empresas where (BDANO >= 2015) '||
    'union all '||
    'select bdempresa, bdano, 6 as BDMES, bd06 as valor from tdados_empresas where (BDANO >= 2015) '||
    'union all '||
    'select bdempresa, bdano, 7 as BDMES, bd07 as valor from tdados_empresas where (BDANO >= 2015) '||
    'union all '||
    'select bdempresa, bdano, 8 as BDMES, bd08 as valor from tdados_empresas where (BDANO >= 2015) '||
    'union all '||
    'select bdempresa, bdano, 9 as BDMES, bd09 as valor from tdados_empresas where (BDANO >= 2015) '||
    'union all '||
    'select bdempresa, bdano, 10 as BDMES, bd10 as valor from tdados_empresas where (BDANO >= 2015) '||
    'union all '||
    'select bdempresa, bdano, 11 as BDMES, bd11 as valor from tdados_empresas where (BDANO >= 2015) '||
    'union all '||
    'select bdempresa, bdano, 12 as BDMES, bd12 as valor from tdados_empresas where (BDANO >= 2015) '
  INTO :BDEMPRESA, :bdano,  :BDMES, :BDVALOR DO
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_TDADOS_EMPRESAS_PROXIMA
RETURNS (
    BDCODEMP INTEGER,
    BDANO INTEGER,
    BDMES INTEGER,
    BDVALOR NUMERIC(15,2))
AS
DECLARE VARIABLE WANOI INTEGER;
DECLARE VARIABLE WANOA INTEGER;
DECLARE VARIABLE WMESA INTEGER;
DECLARE VARIABLE WMESMAX INTEGER;
DECLARE VARIABLE WTEM INTEGER;
BEGIN
  WANOI = 2015;
  WANOA = EXTRACT(YEAR FROM CURRENT_DATE);

  WHILE (WANOI <= wanoa) DO
  BEGIN
     WMESMAX = 12;

     IF (WANOI = WANOA) THEN
     BEGIN
        WMESMAX = EXTRACT(MONTH FROM DATEADD(-1 MONTH TO CURRENT_DATE));
     END

     WMESA = 1;

     WHILE (WMESA <= wmesmax) DO
     BEGIN
        FOR EXECUTE STATEMENT 'select bdcodemp from sp_consultaempresas(LPAD(EXTRACT(YEAR FROM CURRENT_DATE),4,'||'null'||')||LPAD(EXTRACT(MONTH FROM CURRENT_DATE),2,'||'0'||'),0,0)' INTO :BDCODEMP DO
        BEGIN
            EXECUTE STATEMENT 'SELECT COUNT(BDEMPRESA) FROM SP_BASE_TDADOS_EMPRESAS dadosEmp ' ||
                                  'where dadosEmp.bdempresa = ' || BDCODEMP||' and dadosEmp.bdANO = '||wanoI||' and dadosEmp.bdMES = '||WMESA INTO :wtem;

            IF (wTEM > 0) THEN
            BEGIN
               FOR EXECUTE STATEMENT 'SELECT '||WANOI||' AS BDANO, '||WMESA||' AS BDMES, dadosEmp.BDVALOR ' ||
                                  '                             FROM SP_BASE_TDADOS_EMPRESAS dadosEmp ' ||
                                  'where dadosEmp.bdempresa = ' || BDCODEMP||' and dadosEmp.bdANO = '||wanoI||' and dadosEmp.bdMES = '||WMESA
                                  INTO :BDANO, :BDmes, :BDvalor DO
               BEGIN
                  IF (BDVALOR IS NULL) THEN
                     SUSPEND;
               END
            END
            ELSE
            BEGIN
               BDano = wanoi;
               BDmes = wmesa;
               BDvalor = NULL;
               SUSPEND;
            END
        END
        WMESA = WMESA +1;
     END
     WANOI = WANOI+1;
  END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TFERIAS_BCALC_BI0 FOR VRH_EMP_TFERIAS_BCALC
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;
  IF ((NEW.BDCODFEBC IS NULL) OR (NEW.BDCODFEBC = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODFEBC)+1),1) FROM VRH_EMP_TFERIAS_BCALC INTO vCodigo;
        NEW.BDCODFEBC = vCodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODFEBC FROM VRH_EMP_TFERIAS_BCALC WHERE BDCODFEBC = NEW.BDCODFEBC INTO vCodigo;

       IF (vCodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODFEBC)+1),1) FROM VRH_EMP_TFERIAS_BCALC INTO vCodigo;
            NEW.BDCODFEBC = vCodigo;
         END
    END
END
^
--Alt:12607 - FIM

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_ITEMDOCECF (
    PRSESSAO integer,
    PRSESSAOPRO integer)
as
BEGIN
  /*73 - Produto não cadastrado.*/
  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMDOCECF, BDORDEMITEM, BDCODINCONSISTENCIA)
  SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEMDOCECF, I.BDORDEMITEM, 73 BDINCONSISTENCIA
  FROM TMP_VEF_EMP_TITEMDOCECF_TEMP I
  WHERE I.BDSESSAO = :PRSESSAO
  AND ((I.BDALTCODPROD IS NULL) OR (I.BDALTCODPROD = 0));

  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMDOCECF, BDORDEMITEM, BDCODINCONSISTENCIA)
  SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEMDOCECF, I.BDORDEMITEM, 76 BDINCONSISTENCIA
  FROM TMP_VEF_EMP_TITEMDOCECF_TEMP I
  LEFT OUTER JOIN VEF_INCON_TCADPRO P ON(P.BDSESSAO = :PRSESSAOPRO AND P.BDCODEMP = I.BDCODEMP AND P.BDCODPROD = I.BDALTCODPROD)
  WHERE I.BDSESSAO = :PRSESSAO
  AND ((I.BDALTCODPROD IS NOT NULL) AND (I.BDALTCODPROD > 0))
  AND P.BDCODINCONSISTENCIA > 0;

  /*180 - Lançamento sem data da emissão informado*/
  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMDOCECF, BDCODINCONSISTENCIA)
  SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEMDOCECF, 180 BDINCONSISTENCIA
  FROM TMP_VEF_EMP_TDOCECF_TEMP I
  WHERE I.BDSESSAO = :PRSESSAO
  AND ((I.BDDATAEMI IS NULL));
                      
  UPDATE TMP_TCADPRO_TEMP P
  SET P.BDALIQICMS = Coalesce(P.BDALIQICMS,(SELECT FIRST 1 M.BDALIQICMS FROM TMP_VEF_EMP_TITEMDOCECF_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND P.BDCODPROD = M.BDCODPROD ORDER BY M.BDCHAVE DESC))
  WHERE P.BDSESSAO = :PRSESSAOPRO;


/*  --Limpando as inconsistencias
  UPDATE TMP_VEF_EMP_TITEMDOCECF_TEMP I SET I.BDINCONSISTENTE = NULL WHERE I.BDSESSAO = :PRSESSAO;

  --Produtos inconsistentes torna o item em inconsistente
  UPDATE TMP_VEF_EMP_TITEMDOCECF_TEMP I SET BDINCONSISTENTE = 1
  WHERE I.BDSESSAO = :PRSESSAO
  AND EXISTS(
             SELECT P.BDCODINCONSISTENCIA
             FROM VEF_INCON_TCADPRO P
             WHERE P.BDSESSAO = :PRSESSAOPRODUTO
             AND P.BDCODPROD = I.BDCODPROD
            );

  --Itens sem produto (Não conseguiu encontrar o produto)
  UPDATE TMP_VEF_EMP_TITEMDOCECF_TEMP I SET I.BDINCONSISTENTE = 1
  WHERE I.BDSESSAO = :PRSESSAO
  AND ((I.BDCODPROD = 0) OR (I.BDCODPROD IS NULL));

  --Produto está como não relacionado, deixa o lançamento inconsistente
  UPDATE TMP_VEF_EMP_TITEMDOCECF_TEMP I SET I.BDINCONSISTENTE = 1
  WHERE I.BDSESSAO = :PRSESSAO
  AND I.BDCODPROD = (
                     SELECT FIRST 1 P.BDCODPROD
                     FROM TMP_TCADPRO_TEMP P
                     WHERE P.BDSESSAO = :PRSESSAOPRODUTO
                     AND P.bdeditchave = I.BDCODPROD
                     AND ((P.BDSITUACAO IS NULL) OR (P.BDSITUACAO = 0))
                    );    */
END^

CREATE OR ALTER procedure SP_GET_ACOES_INCONSISTENCIA (
    PRCODEMP integer,
    PRREF integer,
    PRSESSAO integer = null)
returns (
    BDCODPLANOINCONS integer,
    BDNCMPROD integer,
    BDSAICFOPNCAD integer,
    BDENTCFOPCANC integer,
    BDCODUNIMED integer,
    BDENTCFOPNCAD integer,
    BDSAICFOPCANC integer,
    BDDESCRICAO varchar(100),
    BDPLANODEFAULT DM_BOOLEAN,
    BDATUPROD DM_BOOLEAN,
    BDATUPART DM_BOOLEAN,
    BDATUUNIDMED DM_BOOLEAN,
    BDATUINFCOM DM_BOOLEAN,
    BDATUOBS DM_BOOLEAN,
    BDATUMAQREDZ DM_BOOLEAN,
    BDATUBICO DM_BOOLEAN,
    BDATUBOMBA DM_BOOLEAN,
    BDATUTANQUE DM_BOOLEAN,
    BDATUFATCONV DM_BOOLEAN,
    BDPARTIEISE DM_BOOLEAN,
    BDCADPROAUTO DM_BOOLEAN,
    BDENTAJUCFOP DM_BOOLEAN,
    BDENTIMPIPIDIF DM_BOOLEAN,
    BDENTIMPICMSDIF DM_BOOLEAN,
    BDSAIAJUCFOP DM_BOOLEAN,
    BDSAIIMPIPIDIF DM_BOOLEAN,
    BDSAIIMPICMSDIF DM_BOOLEAN,
    BDSERAJUCFOP DM_BOOLEAN,
    BDSERIMPISSDIF DM_BOOLEAN,
    BDPARTBUSCASITE DM_BOOLEAN,
    BDPRODNCMVAZIO DM_BOOLEAN,
    BDREDZCODTER integer,
    BDESPECIEMRC varchar(4),
    BDSERIEMRC varchar(3),
    BDCONDPGTOMRC integer,
    BDTIPOMAQMRC integer,
    BDCODOBSMRC integer,
    BDCODTERNFCE_CFE integer,
    BDTIPCONTADUP integer,
    BDCODTERSER integer,
    BDSERIESER varchar(6),
    BDESPECIESER varchar(5),
    BDDTEMISSAOSER integer,
    BDSUBSTITUIDUPLICATA DM_BOOLEAN,
    BDAPENASCODPRODSAI DM_BOOLEAN,
    BDVINCULOPART integer,
    BDNUMERODOCUMENTOSER integer,
    BDDATAVAZIASER varchar(5),
    BDINDICADORISSSER integer,
    BDDATAEXECUCAOSER integer,
    BDEXCECAONCM DM_BOOLEAN,
    BDTIPOITEM DM_BOOLEAN,
    BDCADPARTEXTNFSESP DM_BOOLEAN,
    BDNAOVERIFICAIEPART DM_BOOLEAN,
    BDATUEXISTLANCC DM_BOOLEAN,
    BDNAOATUALIZACSTENTRADA boolean,
    BDNAOATUALIZACSTSAIDA boolean,
    BDNAOIMPINFCOMP Boolean)
as
declare variable WCODPLANOINCO integer;
BEGIN
  wCodPlanoInco = NULL;

  /*IF ((:PRCODEMP IS NOT NULL) AND (:PRCODEMP > 0)) THEN
    SELECT SP.BDCODPLANOINCONS FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :PRCODEMP, NULL) SP INTO :wCodPlanoInco;*/

  -- Alt.: #138509 - Busca a configuração do plano de inconsistencias, ja pesquisada anteriormente...
  IF (:prSESSAO IS NOT NULL) THEN
    --SELECT TRIM(RDB$GET_CONTEXT('USER_SESSION',  'W_CONF_PLANOINC_'||:prSESSAO)) FROM RDB$DATABASE INTO :wCodPlanoInco;
    SELECT BDVALORINT FROM TTHREAD WHERE BDPARAM = 'W_CONF_PLANOINC_'||:prSESSAO INTO :wCodPlanoInco; -- Alt.: #201191 - Removida variavel de contexto...

  IF (:wCodPlanoInco IS NULL) THEN
    BEGIN
      EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREF, NULL, NULL);

      SELECT PARINTEG.BDCODPLANOINCONS
      FROM VW_TEMPRESAS_REF_MAX_MIN EMP
      INNER JOIN TEMPRESAS TEMP ON (TEMP.BDCODEMP = EMP.BDCODEMP AND TEMP.BDCODEMP = :prCODEMP)
      LEFT OUTER JOIN VW_VEF_BASE_TEMPPARINTEG PARINTEG ON (PARINTEG.BDCODEMP = EMP.BDCODEMP AND PARINTEG.BDREFEMP = EMP.BDREFEMP)
      INTO :wCodPlanoInco;
    END

  IF ((:wCodPlanoInco IS NULL) OR (:wCodPlanoInco = 0)) THEN
    SELECT A.BDCODPLANOINCONS FROM VEF_BASE_TACOESINCONS A WHERE UPPER(A.BDPLANODEFAULT) = 'TRUE' INTO :wCodPlanoInco;


  IF (((:wCodPlanoInco IS NOT NULL) OR (:wCodPlanoInco > 0))) THEN
    SELECT A.BDCODPLANOINCONS,
           A.BDNCMPROD,
           A.BDSAICFOPNCAD,
           A.BDENTCFOPCANC,
           A.BDCODUNIMED,
           A.BDENTCFOPNCAD,
           A.BDSAICFOPCANC,
           UPPER(A.BDDESCRICAO),
           UPPER(A.BDPLANODEFAULT),
           UPPER(A.BDATUPROD),
           UPPER(A.BDATUPART),
           UPPER(A.BDATUUNIDMED),
           UPPER(A.BDATUINFCOM),
           UPPER(A.BDATUOBS),
           UPPER(A.BDATUMAQREDZ),
           UPPER(A.BDATUBICO),
           UPPER(A.BDATUBOMBA),
           UPPER(A.BDATUTANQUE),
           UPPER(A.BDATUFATCONV),
           UPPER(A.BDPARTIEISE),
           UPPER(A.BDCADPROAUTO),
           UPPER(A.BDENTAJUCFOP),
           UPPER(A.BDENTIMPIPIDIF),
           UPPER(A.BDENTIMPICMSDIF),
           UPPER(A.BDSAIAJUCFOP),
           UPPER(A.BDSAIIMPIPIDIF),
           UPPER(A.BDSAIIMPICMSDIF),
           UPPER(A.BDSERAJUCFOP),
           UPPER(A.BDSERIMPISSDIF),
           UPPER(A.BDPARTBUSCASITE),
           UPPER(A.BDPRODNCMVAZIO),
           A.BDREDZCODTER,
           A.BDESPECIEMRC,
           A.BDSERIEMRC,
           A.BDCONDPGTOMRC,
           A.BDTIPOMAQMRC,
           A.BDCODOBSMRC,
           A.BDCODTERNFCE_CFE,
           A.BDTIPCONTADUP,
           A.BDCODTERSER,
           A.BDSERIESER,
           A.BDESPECIESER,
           A.BDDTEMISSAOSER,
           A.BDSUBSTITUIDUPLICATA,
           A.BDAPENASCODPRODSAI,
           a.bdVINCULOPART,
           A.BDNUMERODOCUMENTOSER,
           A.BDDATAVAZIASER,
           A.BDINDICADORISSSER,
           A.BDDATAEXECUCAOSER,
           A.BDEXCECAONCM,
           A.bdtipoitem,
           A.BDCADPARTEXTNFSESP,
           A.BDNAOVERIFICAIEPART,
           UPPER(A.BDATUEXISTLANCC),
           A.BDNAOATUALIZACSTENTRADA,
           A.BDNAOATUALIZACSTSAIDA,
           A.BDNAOIMPINFCOMP

    FROM VEF_BASE_TACOESINCONS A
    WHERE A.BDCODPLANOINCONS = :wCodPlanoInco
    INTO :BDCODPLANOINCONS,
         :BDNCMPROD,
         :BDSAICFOPNCAD,
         :BDENTCFOPCANC,
         :BDCODUNIMED,
         :BDENTCFOPNCAD,
         :BDSAICFOPCANC,
         :BDDESCRICAO,
         :BDPLANODEFAULT,
         :BDATUPROD,
         :BDATUPART,
         :BDATUUNIDMED,
         :BDATUINFCOM,
         :BDATUOBS,
         :BDATUMAQREDZ,
         :BDATUBICO,
         :BDATUBOMBA,
         :BDATUTANQUE,
         :BDATUFATCONV,
         :BDPARTIEISE,
         :BDCADPROAUTO,
         :BDENTAJUCFOP,
         :BDENTIMPIPIDIF,
         :BDENTIMPICMSDIF,
         :BDSAIAJUCFOP,
         :BDSAIIMPIPIDIF,
         :BDSAIIMPICMSDIF,
         :BDSERAJUCFOP,
         :BDSERIMPISSDIF,
         :BDPARTBUSCASITE,
         :BDPRODNCMVAZIO,
         :BDREDZCODTER,
         :BDESPECIEMRC,
         :BDSERIEMRC,
         :BDCONDPGTOMRC,
         :BDTIPOMAQMRC,
         :BDCODOBSMRC,
         :BDCODTERNFCE_CFE,
         :BDTIPCONTADUP,
         :BDCODTERSER,
         :BDSERIESER,
         :BDESPECIESER,
         :BDDTEMISSAOSER,
         :BDSUBSTITUIDUPLICATA,
         :BDAPENASCODPRODSAI,
         :bdVINCULOPART,
         :BDNUMERODOCUMENTOSER,
         :BDDATAVAZIASER,
         :BDINDICADORISSSER,
         :BDDATAEXECUCAOSER,
         :BDEXCECAONCM,
         :bdtipoitem,
         :BDCADPARTEXTNFSESP,
         :BDNAOVERIFICAIEPART,
         :BDATUEXISTLANCC,
         :BDNAOATUALIZACSTENTRADA,
         :BDNAOATUALIZACSTSAIDA,
         :BDNAOIMPINFCOMP;
  ELSE
    BEGIN
      BDCODPLANOINCONS         = 0;
      BDNCMPROD                = 0;
      BDSAICFOPNCAD            = 0;
      BDENTCFOPCANC            = 0;
      BDCODUNIMED              = 0;
      BDENTCFOPNCAD            = 0;
      BDSAICFOPCANC            = 0;
      BDDESCRICAO              = '';
      BDPLANODEFAULT           = 'FALSE';
      BDATUPROD                = 'FALSE';
      BDATUPART                = 'FALSE';
      BDATUUNIDMED             = 'FALSE';
      BDATUINFCOM              = 'FALSE';
      BDATUOBS                 = 'FALSE';
      BDATUMAQREDZ             = 'FALSE';
      BDATUBICO                = 'FALSE';
      BDATUBOMBA               = 'FALSE';
      BDATUTANQUE              = 'FALSE';
      BDATUFATCONV             = 'FALSE';
      BDPARTIEISE              = 'FALSE';
      BDCADPROAUTO             = 'FALSE';
      BDENTAJUCFOP             = 'FALSE';
      BDENTIMPIPIDIF           = 'FALSE';
      BDENTIMPICMSDIF          = 'FALSE';
      BDSAIAJUCFOP             = 'FALSE';
      BDSAIIMPIPIDIF           = 'FALSE';
      BDSAIIMPICMSDIF          = 'FALSE';
      BDSERAJUCFOP             = 'FALSE';
      BDSERIMPISSDIF           = 'FALSE';
      BDPARTBUSCASITE          = 'FALSE';
      BDPRODNCMVAZIO           = 'FALSE';
      BDREDZCODTER             = 0;
      BDESPECIEMRC             = '';
      BDSERIEMRC               = '';
      BDCONDPGTOMRC            = -1;
      BDTIPOMAQMRC             = -1;
      BDCODOBSMRC              = 0;
      BDCODTERNFCE_CFE         = 0;
      BDTIPCONTADUP            = -1;
      BDCODTERSER              = 0;
      BDSERIESER               = '';
      BDESPECIESER             = '';
      BDDTEMISSAOSER           = -1;
      BDSUBSTITUIDUPLICATA     = 'FALSE';
      BDAPENASCODPRODSAI       = 'FALSE';
      bdVINCULOPART            = 0;
      BDNUMERODOCUMENTOSER     = -1;
      BDDATAVAZIASER           = 'FALSE';
      BDINDICADORISSSER        = -1;
      BDDATAEXECUCAOSER        = -1;
      BDEXCECAONCM             = 'FALSE';
      bdtipoitem               = 'FALSE';
      BDCADPARTEXTNFSESP       = 'FALSE';
      BDNAOVERIFICAIEPART      = 'FALSE';
      BDATUEXISTLANCC          = 'FALSE';
      BDNAOATUALIZACSTENTRADA  = 'FALSE';
      BDNAOATUALIZACSTSAIDA    = 'FALSE';
      BDNAOIMPINFCOMP          = 'FALSE';
    END

  SUSPEND;
END
^

CREATE OR ALTER procedure SP_GERAR_INCON_TCADPRO (
    PRSESSAO integer,
    PRCODEMP integer,
    PRCODPLANOINCO integer,
    PRREF integer,
    PRIDTERMINAL integer)
as
declare variable WSESSAOUNIMED integer;
declare variable WNCMINVALIDO DM_BOOLEAN;
declare variable WISINDUSTRIA DM_BOOLEAN;
declare variable WNCMPADRAO integer;
declare variable WCODUNIMEDPADRAO integer;
declare variable WAPEUNIMEDPADRAO varchar(5);
declare variable WCONSISTIRCODPROD DM_BOOLEAN;
BEGIN
  DELETE FROM VEF_INCON_TCADPRO WHERE BDSESSAO = :PRSESSAO;

  SELECT I.BDPRODNCMVAZIO, I.BDNCMPROD, I.BDCODUNIMED
  FROM VEF_BASE_TACOESINCONS I
  WHERE I.BDCODPLANOINCONS = :PRCODPLANOINCO
  INTO :wNcmInvalido, :wNcmPadrao, :wCodUnimedPadrao;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREF);
  /*Faz esse select pra ver se a empresa não é industria*/
  SELECT IIF(((a.bdcodconficmssped > 0) AND (a.BDATIVIDADESPED = 0) AND (a.bddtobrigspedcont IS NOT NULL) AND (a.BDINDATIV = 1)), 'TRUE', 'FALSE') BDISINDUSTRIA
  FROM VW_VEF_BASE_TEMPPARFED a
  WHERE a.bdcodemp = :PRCODEMP
  INTO :wIsIndustria;

  SELECT T.BDCONSISTIRCODPROD
  FROM VW_VEF_BASE_TEMPPARINTEG T
  WHERE T.BDCODEMP = :PRCODEMP
  INTO :WCONSISTIRCODPROD;

  /*Transforma ncm's inv??lidas para vazio*/
  IF (:wNcmInvalido = 'TRUE') THEN
    BEGIN
      /*Verifica se a empresa não é Indústria, industria deve ter ncm válido, senão tiver é inconsistente*/
      IF (:wIsIndustria = 'FALSE') THEN
        BEGIN
          /*Altera na tabela TMP*/
          UPDATE TMP_TCADPRO P SET P.BDNCMPROD = NULL
          WHERE P.BDSESSAO = :PRSESSAO
          AND P.BDNCMPROD IS NOT NULL
          AND NOT EXISTS(
                         SELECT N.BDNCMPROD
                         FROM TNCM N
                         WHERE N.BDNCMPROD = P.BDNCMPROD
                        );

          /*Altera na tabela TEMP*/
          UPDATE TMP_TCADPRO_TEMP P SET P.BDNCMPROD = NULL
          WHERE P.BDSESSAO = :PRSESSAO
          AND P.BDNCMPROD IS NOT NULL
          AND NOT EXISTS(
                         SELECT N.BDNCMPROD
                         FROM TNCM N
                         WHERE N.BDNCMPROD = P.BDNCMPROD
                        );
        END
    END

  /*Muda as ncm's inválidas para ncm padrão, se a empresa for indústria principalmente(obrigatório)*/
  IF ((:wNcmPadrao IS NOT NULL) OR (:wNcmPadrao > 0)) THEN
    BEGIN
      /*Altera na tabela TMP*/
      UPDATE TMP_TCADPRO P SET P.BDNCMPROD = :wNcmPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDNCMPROD <> :wNcmPadrao /*Se já alterou, não vai alterar denovo*/
      AND NOT EXISTS(
                     SELECT N.BDNCMPROD
                     FROM TNCM N
                     WHERE N.BDNCMPROD = P.BDNCMPROD
                    );

      /*Altera na tabela TEMP*/
      UPDATE TMP_TCADPRO_TEMP P SET P.BDNCMPROD = :wNcmPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDNCMPROD <> :wNcmPadrao /*Se já alterou, não vai alterar denovo*/
      AND NOT EXISTS(
                     SELECT N.BDNCMPROD
                     FROM TNCM N
                     WHERE N.BDNCMPROD = P.BDNCMPROD
                    );
    END

  /*Se tiver uma unidade de medida padrão, coloca ela nos produtos que não tem unidade de medida*/
  IF ((:wCodUnimedPadrao IS NOT NULL) OR (:wCodUnimedPadrao > 0)) THEN
    BEGIN
      /*Busca apelido, apenas para mostrar na grid*/
      SELECT U.BDAPEUNIMED FROM TUNIDADEMEDIDA U WHERE U.BDCODUNIMED = :wCodUnimedPadrao INTO :wApeUnimedPadrao;

      /*Altera na tabela TMP*/
      UPDATE TMP_TCADPRO P SET P.BDCODUNIMED = :wCodUnimedPadrao, P.BDAPEUNIMED = :wApeUnimedPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND ((P.BDCODUNIMED IS NULL) OR (P.BDCODUNIMED = 0))
      AND P.BDCODUNIMED <> :wCodUnimedPadrao; /*Se já alterou, não vai alterar denovo*/

      /*Altera na tabela TEMP*/
      UPDATE TMP_TCADPRO_TEMP P SET P.BDALTCODUNIMED = :wCodUnimedPadrao, P.BDCODUNIMED = :wCodUnimedPadrao, P.BDAPEUNIMED = :wApeUnimedPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND ((P.BDALTCODUNIMED IS NULL) OR (P.BDALTCODUNIMED = 0))
      AND P.BDALTCODUNIMED <> :wCodUnimedPadrao;
    END

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRIDTERMINAL
  AND S.BDTABLE = 'TMP_TUNIDADEMEDIDA_TEMP'
  INTO :wSessaoUniMed;

  /*49 - Código de unidade de medida não cadastrado*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 49 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  LEFT OUTER JOIN TUNIDADEMEDIDA U ON(U.BDCODUNIMED = P.BDALTCODUNIMED)
  LEFT OUTER JOIN TMP_TUNIDADEMEDIDA_TEMP T ON(T.BDEDITCHAVE = P.BDALTCODUNIMED AND T.BDSESSAO = :wSessaoUniMed)
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDALTCODUNIMED IS NOT NULL) AND (P.BDALTCODUNIMED > 0))
  AND (U.BDCODUNIMED IS NULL) AND (T.BDCODUNIMED IS NULL);

  /*77 - O campo Unidade de medida não pode ficar em branco caso a empresa tenha Sped!*/
  IF (:wIsIndustria = 'TRUE') THEN
    BEGIN
      INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
      SELECT 77 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
      FROM TMP_TCADPRO_TEMP P
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDCODTIPOSER <> 10 /*Serviços, não deve obrigar ncm*/  
      AND ((P.BDALTCODUNIMED IS NULL) OR (P.BDALTCODUNIMED = 0));

      /*50 - Código de NCM não cadastrado*/
      INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
      SELECT 50 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
      FROM TMP_TCADPRO_TEMP P
      LEFT OUTER JOIN TNCM N ON(N.BDNCMPROD = P.BDNCMPROD)
      WHERE P.BDSESSAO = :PRSESSAO
      AND not (P.BDCODTIPOSER in (8,9,10,11,12)) /*#99586 - Inconsistência de falta de NCM no produto não deve ocorrer para TP_ITEM de 07, 08, 09, 10 ou 99*/
      AND ((P.BDNCMPROD IS NULL) OR ((P.BDNCMPROD IS NOT NULL) AND (N.BDNCMPROD IS NULL)));
    END

  /*50 - Código de NCM não cadastrado*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 50 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  LEFT OUTER JOIN TNCM N ON(N.BDNCMPROD = P.BDNCMPROD)
  WHERE P.BDSESSAO = :PRSESSAO
--  AND P.BDCODTIPOSER <> 10 /*Serviços, não deve obrigar ncm*/
  AND P.BDNCMPROD IS NOT NULL
  AND N.BDNCMPROD IS NULL;

  /*73 - Situação como Não relacionado(Está inconsistencia não aparece para o usuário, é somente para o controle de commit's)*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 73 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDSITUACAO IS NULL) OR (P.BDSITUACAO = 0));

  /*63 - Descrição do produto não pode estar vazia*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 63 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDDESCPROD IS NULL) OR (P.BDDESCPROD = ''));

  /*62 - Apelido do produto não pode estar vazio*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 62 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDAPEPROD IS NULL) OR (P.BDAPEPROD = ''));

  /*118 - NCM não possui o código de exceção.*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 118 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  LEFT OUTER JOIN TCODEXTIPI EX ON(EX.BDNCMPROD = P.BDNCMPROD AND EX.BDCODTIPI = P.BDCODTIPI)
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDCODTIPI IS NOT NULL) AND (P.BDCODTIPI > 0))
  AND EX.BDCODTIPI IS NULL;

  /*179 - Produto inativo.*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 179 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  LEFT OUTER JOIN tcadpro_vinc V ON (P.bdcodemp = V.bdcodemp AND P.bdeditchave = V.bdcodprod)
  WHERE P.BDSESSAO = :PRSESSAO
  AND (UPPER(V.bdinativo) = 'TRUE');

    /* 200 - Consistir produtos com o mesmo c?digo */
  IF (WCONSISTIRCODPROD = 'TRUE') THEN
    BEGIN
        INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
        SELECT 200 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
        FROM TMP_TCADPRO_TEMP P
        LEFT OUTER JOIN TCADPRO_VINC V ON (P.BDCODEMP = V.BDCODEMP AND P.BDEDITCHAVE = V.BDCODPROD)
        WHERE P.BDSESSAO = :PRSESSAO
        AND TRIM(P.BDDESCPROD) <> TRIM(V.BDDESCPROD);
    END
                   
                   
  DELETE FROM VEF_INCON_TUNIDADEMEDIDA WHERE BDSESSAO = :PRSESSAO;
  /*181 - Descrição da unidade de medida não preenchida.*/
  INSERT INTO VEF_INCON_TUNIDADEMEDIDA(BDCODINCONSISTENCIA, BDSESSAO, BDCODUNIMED)
  SELECT 181 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE
  FROM TMP_TUNIDADEMEDIDA_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
     AND Coalesce(P.BDDESCUNIMED,'') = '';

  /*182 - Unidade de medida inconsistente.*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 182 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND EXISTS (SELECT FIRST 1 I.BDCODINCONSISTENCIA FROM VEF_INCON_TUNIDADEMEDIDA I WHERE I.BDCODUNIMED = P.BDCODUNIMED AND I.BDSESSAO = :PRSESSAO);
END^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_TEQUIPSAT (
    PRSESSAO integer,
    PRULTCHAVE integer)
as
declare variable WCODEMP integer;
declare variable WCODEQUIPSAT integer;
declare variable WNRSERIE varchar(9) collate WIN_PTBR;
declare variable WNRCAIXA integer;
declare variable WDATAINIOBRI date;
declare variable WDATAFIMOBRI date;
declare variable WCODEQUIPSAT_TMP integer;
declare variable WDATAINIOBRI_TMP date;
declare variable WDATAFIMOBRI_TMP date;
BEGIN
  DELETE FROM VEF_INCON_TEQUIPSAT E WHERE E.BDSESSAO = :PRSESSAO;

  /*78 - Número de série não informado*/
  INSERT INTO VEF_INCON_TEQUIPSAT(BDSESSAO, BDCODEMP, BDCODEQUIPSAT, BDCODINCONSISTENCIA)
  SELECT E.BDSESSAO, E.BDCODEMP, E.BDCODEQUIPSAT, 78 BDCODINCONSISTENCIA
  FROM TMP_VEF_BASE_TEQUIPASAT_TEMP E
  WHERE E.BDSESSAO = :PRSESSAO
  AND ((E.BDNRSERIE IS NULL) OR (E.BDNRSERIE = ''));

  /*79 - Número do caixa não informado*/
  INSERT INTO VEF_INCON_TEQUIPSAT(BDSESSAO, BDCODEMP, BDCODEQUIPSAT, BDCODINCONSISTENCIA)
  SELECT E.BDSESSAO, E.BDCODEMP, E.BDCODEQUIPSAT, 79 BDCODINCONSISTENCIA
  FROM TMP_VEF_BASE_TEQUIPASAT_TEMP E
  WHERE E.BDSESSAO = :PRSESSAO
  AND ((E.BDNRCAIXA IS NULL) OR (E.BDNRCAIXA = 0));

  /*80 - Data de início das atividades não informada*/
  INSERT INTO VEF_INCON_TEQUIPSAT(BDSESSAO, BDCODEMP, BDCODEQUIPSAT, BDCODINCONSISTENCIA)
  SELECT E.BDSESSAO, E.BDCODEMP, E.BDCODEQUIPSAT, 80 BDCODINCONSISTENCIA
  FROM TMP_VEF_BASE_TEQUIPASAT_TEMP E
  WHERE E.BDSESSAO = :PRSESSAO
  AND (E.BDDATAINIOBRI IS NULL);

  FOR SELECT E.BDCODEMP, E.BDCODEQUIPSAT,
             E.BDNRSERIE, E.BDNRCAIXA,
             E.BDDATAINIOBRI, E.BDDATAFIMOBRI
      FROM TMP_VEF_BASE_TEQUIPASAT_TEMP E
      LEFT OUTER JOIN VEF_INCON_TEQUIPSAT EI ON(EI.BDSESSAO = E.BDSESSAO AND EI.BDCODEMP = E.BDCODEMP AND EI.BDCODEQUIPSAT = E.BDCODEQUIPSAT)
      WHERE E.BDSESSAO = :PRSESSAO
      AND E.BDCODEMP IS NOT NULL
      AND EI.BDCODINCONSISTENCIA IS NULL
      INTO :wCodEmp, :wCodEquipSat_tmp,
           :wNrSerie, :wNrCaixa,
           :wDataIniObri_tmp, :wDataFimObri_tmp
  DO
    BEGIN
      SELECT EQ.BDCODEQUIPSAT, EQ.BDDATAINIOBRI,
             EQ.BDDATAFIMOBRI
      FROM VEF_BASE_TEQUIPASAT EQ
      WHERE EQ.BDCODEMP = :wCodEmp
      AND EQ.BDNRSERIE = :wNrSerie
      AND EQ.BDNRCAIXA = :wNrCaixa
      INTO :wCodEquipSat, :wDataIniObri,
           :wDataFimObri;

      IF ((:wCodEquipSat IS NOT NULL) AND (:wCodEquipSat > 0)) THEN /*Achou uma máquina com mesma série e caixa*/
        BEGIN
          IF (:wDataIniObri_tmp > wDataIniObri) THEN
            wDataIniObri_tmp = :wDataIniObri;

          IF (:wDataFimObri IS NOT NULL) THEN
            wDataFimObri_tmp = :wDataFimObri;

          UPDATE TMP_VEF_BASE_TEQUIPASAT_TEMP T
          SET T.BDEDITCHAVE = :wCodEquipSat,
              T.BDDATAINIOBRI = :wDataIniObri_tmp,
              T.BDDATAFIMOBRI = :wDataFimObri_tmp
          WHERE T.BDSESSAO = :PRSESSAO
          AND T.BDCODEQUIPSAT = :wCodEquipSat_tmp;
        END
      ELSE
        BEGIN
          UPDATE TMP_VEF_BASE_TEQUIPASAT_TEMP T SET T.BDEDITCHAVE = :PRULTCHAVE
          WHERE T.BDSESSAO = :PRSESSAO
          AND T.BDCODEQUIPSAT = :wCodEquipSat_tmp;

          PRULTCHAVE = :PRULTCHAVE - 1;
        END
    END
END^

CREATE OR ALTER PROCEDURE SP_INSERT_OR_UPDATE_TEQUIPSAT (
    PRSESSAO INTEGER)
AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE wEditChave INTEGER;
DECLARE VARIABLE wNrSerie VARCHAR(9);
DECLARE VARIABLE wNrCaixa INTEGER;
DECLARE VARIABLE wDataIniObri DATE;
DECLARE VARIABLE wDataFimObri DATE;
BEGIN
  FOR SELECT E.BDCODEMP, E.BDEDITCHAVE, E.BDNRSERIE,
             E.BDNRCAIXA, E.BDDATAINIOBRI, E.BDDATAFIMOBRI
      FROM TMP_VEF_BASE_TEQUIPASAT_TEMP E
      LEFT OUTER JOIN VEF_INCON_TEQUIPSAT I ON(I.BDSESSAO = E.BDSESSAO AND I.BDCODEMP = E.BDCODEMP AND I.BDCODEQUIPSAT = E.BDCODEQUIPSAT)
      WHERE E.BDSESSAO = :PRSESSAO
      AND I.BDCODINCONSISTENCIA IS NULL
      INTO :wCodEmp, :wEditChave, :wNrSerie,
           :wNrCaixa, :wDataIniObri, :wDataFimObri
  DO
    BEGIN
      UPDATE OR INSERT INTO VEF_BASE_TEQUIPASAT(BDCODEMP, BDCODEQUIPSAT, BDNRSERIE, BDNRCAIXA, BDDATAINIOBRI, BDDATAFIMOBRI)
      VALUES(:wCodEmp, :wEditChave , :wNrSerie, :wNrCaixa, :wDataIniObri, :wDataFimObri) MATCHING(BDCODEMP, BDCODEQUIPSAT);
    END
END^

CREATE OR ALTER procedure SP_ATUALIZA_PART_TABLE_DEP (
    PRSESSAO integer,
    PRCODTER integer,
    PRFIELD varchar(20),
    PRVALUE varchar(100))
as
begin

end^

COMMENT ON PARAMETER SP_PRE_VALIDA_CONTA_ONLINE_TEMP.PRTIPOLAN IS 'ENT/SAI/SER/REDZ'^
COMMENT ON PARAMETER SP_VALIDA_CONTA_ONLINE_TEMP.PRTIPOLAN IS 'ENT/SAI/SER/REDZ'^
COMMENT ON PARAMETER SP_ATUALIZAR_CAMPO_CHAVE_TEMP.PRTABLE IS 'Nome da tabela principal'^ 
COMMENT ON PARAMETER SP_INSERT_INCONSISTENCIAS_CONTA.PRTIPOLAN IS 'ENT/SAI/SER/REDZ'^
COMMENT ON PARAMETER SP_INS_UPT_TMP_TCADPRO.PROPERATION IS '''INS'' = INSERIR NOVO - ''UPT'' = ATUALIZAR DADOS -  ''INUP'' = ''LANÇAMENTO MANUAL'''^
--Sol: 15461 - FIM

CREATE OR ALTER trigger tmp_vef_emp_tmovsaisn_temp_bi0 for tmp_vef_emp_tmovsaisn_temp
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER;
  DECLARE VARIABLE vChavesn INTEGER;
begin
  vcodigo = 0;
  IF ((NEW.bdchavesn IS NULL) OR (NEW.bdchavesn = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM tmp_vef_emp_TMOVSAIitens_temp WHERE (bdsessao = new.bdsessao) and (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM tmp_vef_emp_TMOVSAIitens_temp WHERE (bdsessao = new.bdsessao) and (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
          NEW.bdordem = vordem;
        END

       SELECT COALESCE((MAX(bdchavesn)+1), 1) FROM tmp_vef_emp_TMOVSAIsn_temp
       WHERE (bdsessao = new.bdsessao) and (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vChavesn;

       NEW.bdchavesn = vChavesn;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM tmp_vef_emp_TMOVSAIitens_temp WHERE (bdsessao = new.bdsessao) and (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)), 1) FROM tmp_vef_emp_TMOVSAIitens_temp WHERE (bdsessao = new.bdsessao) and (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
           NEW.bdordem = vordem;
         END

       SELECT bdchavesn FROM tmp_vef_emp_TMOVSAIsn_temp
       WHERE (bdsessao = new.bdsessao) and (bdchavesn = NEW.bdchavesn) AND (bdOrdem = NEW.bdordem) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchavesn)+1), 1) FROM tmp_vef_emp_TMOVSAIsn_temp
           WHERE (bdsessao = new.bdsessao)
           and (bdcodemp = NEW.bdcodemp)
           AND (bdChave = NEW.bdchave)
           AND (bdOrdem = NEW.bdordem) INTO vChavesn;
           NEW.bdchavesn = vChavesn;
         END

    END
end^

--Alt:12607 - FIM

CREATE OR ALTER PROCEDURE SP_GERAR_INCON_TCADPRO (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRCODPLANOINCO INTEGER,
    PRREF INTEGER,
    PRIDTERMINAL INTEGER)
AS
DECLARE VARIABLE WSESSAOUNIMED INTEGER;
DECLARE VARIABLE WNCMINVALIDO DM_BOOLEAN;
DECLARE VARIABLE WISINDUSTRIA DM_BOOLEAN;
DECLARE VARIABLE WNCMPADRAO INTEGER;
DECLARE VARIABLE WCODUNIMEDPADRAO INTEGER;
DECLARE VARIABLE WAPEUNIMEDPADRAO VARCHAR(5);
declare variable WCONSISTIRCODPROD DM_BOOLEAN;
BEGIN
  DELETE FROM VEF_INCON_TCADPRO WHERE BDSESSAO = :PRSESSAO;

  SELECT I.BDPRODNCMVAZIO, I.BDNCMPROD, I.BDCODUNIMED
  FROM VEF_BASE_TACOESINCONS I
  WHERE I.BDCODPLANOINCONS = :PRCODPLANOINCO
  INTO :wNcmInvalido, :wNcmPadrao, :wCodUnimedPadrao;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREF);
  /*Faz esse select pra ver se a empresa não é industria*/
  SELECT IIF(((a.bdcodconficmssped > 0) AND (a.BDATIVIDADESPED = 0) AND (a.bddtobrigspedcont IS NOT NULL) AND (a.BDINDATIV = 1)), 'TRUE', 'FALSE') BDISINDUSTRIA
  FROM VW_VEF_BASE_TEMPPARFED a
  WHERE a.bdcodemp = :PRCODEMP
  INTO :wIsIndustria;

  SELECT T.BDCONSISTIRCODPROD
  FROM VW_VEF_BASE_TEMPPARINTEG T
  WHERE T.BDCODEMP = :PRCODEMP
  INTO :WCONSISTIRCODPROD;

  /*Transforma ncm's inv??lidas para vazio*/
  IF (:wNcmInvalido = 'TRUE') THEN
    BEGIN
      /*Verifica se a empresa não é Indústria, industria deve ter ncm válido, senão tiver é inconsistente*/
      IF (:wIsIndustria = 'FALSE') THEN
        BEGIN
          /*Altera na tabela TMP*/
          UPDATE TMP_TCADPRO P SET P.BDNCMPROD = NULL
          WHERE P.BDSESSAO = :PRSESSAO
          AND P.BDNCMPROD IS NOT NULL
          AND NOT EXISTS(
                         SELECT N.BDNCMPROD
                         FROM TNCM N
                         WHERE N.BDNCMPROD = P.BDNCMPROD
                        );

          /*Altera na tabela TEMP*/
          UPDATE TMP_TCADPRO_TEMP P SET P.BDNCMPROD = NULL
          WHERE P.BDSESSAO = :PRSESSAO
          AND P.BDNCMPROD IS NOT NULL
          AND NOT EXISTS(
                         SELECT N.BDNCMPROD
                         FROM TNCM N
                         WHERE N.BDNCMPROD = P.BDNCMPROD
                        );
        END
    END

  /*Muda as ncm's inválidas para ncm padrão, se a empresa for indústria principalmente(obrigatório)*/
  IF ((:wNcmPadrao IS NOT NULL) OR (:wNcmPadrao > 0)) THEN
    BEGIN
      /*Altera na tabela TMP*/
      UPDATE TMP_TCADPRO P SET P.BDNCMPROD = :wNcmPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDNCMPROD <> :wNcmPadrao /*Se já alterou, não vai alterar denovo*/
      AND NOT EXISTS(
                     SELECT N.BDNCMPROD
                     FROM TNCM N
                     WHERE N.BDNCMPROD = P.BDNCMPROD
                    );

      /*Altera na tabela TEMP*/
      UPDATE TMP_TCADPRO_TEMP P SET P.BDNCMPROD = :wNcmPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDNCMPROD <> :wNcmPadrao /*Se já alterou, não vai alterar denovo*/
      AND NOT EXISTS(
                     SELECT N.BDNCMPROD
                     FROM TNCM N
                     WHERE N.BDNCMPROD = P.BDNCMPROD
                    );
    END

  /*Se tiver uma unidade de medida padrão, coloca ela nos produtos que não tem unidade de medida*/
  IF ((:wCodUnimedPadrao IS NOT NULL) OR (:wCodUnimedPadrao > 0)) THEN
    BEGIN
      /*Busca apelido, apenas para mostrar na grid*/
      SELECT U.BDAPEUNIMED FROM TUNIDADEMEDIDA U WHERE U.BDCODUNIMED = :wCodUnimedPadrao INTO :wApeUnimedPadrao;

      /*Altera na tabela TMP*/
      UPDATE TMP_TCADPRO P SET P.BDCODUNIMED = :wCodUnimedPadrao, P.BDAPEUNIMED = :wApeUnimedPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND ((P.BDCODUNIMED IS NULL) OR (P.BDCODUNIMED = 0))
      AND P.BDCODUNIMED <> :wCodUnimedPadrao; /*Se já alterou, não vai alterar denovo*/

      /*Altera na tabela TEMP*/
      UPDATE TMP_TCADPRO_TEMP P SET P.BDALTCODUNIMED = :wCodUnimedPadrao, P.BDCODUNIMED = :wCodUnimedPadrao, P.BDAPEUNIMED = :wApeUnimedPadrao
      WHERE P.BDSESSAO = :PRSESSAO
      AND ((P.BDALTCODUNIMED IS NULL) OR (P.BDALTCODUNIMED = 0))
      AND P.BDALTCODUNIMED <> :wCodUnimedPadrao;
    END

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRIDTERMINAL
  AND S.BDTABLE = 'TMP_TUNIDADEMEDIDA_TEMP'
  INTO :wSessaoUniMed;

  /*49 - Código de unidade de medida não cadastrado*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 49 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  LEFT OUTER JOIN TUNIDADEMEDIDA U ON(U.BDCODUNIMED = P.BDALTCODUNIMED)
  LEFT OUTER JOIN TMP_TUNIDADEMEDIDA_TEMP T ON(T.BDEDITCHAVE = P.BDALTCODUNIMED AND T.BDSESSAO = :wSessaoUniMed)
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDALTCODUNIMED IS NOT NULL) AND (P.BDALTCODUNIMED > 0))
  AND (U.BDCODUNIMED IS NULL) AND (T.BDCODUNIMED IS NULL);

  /*77 - O campo Unidade de medida não pode ficar em branco caso a empresa tenha Sped!*/
  IF (:wIsIndustria = 'TRUE') THEN
    BEGIN
      INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
      SELECT 77 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
      FROM TMP_TCADPRO_TEMP P
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDCODTIPOSER <> 10 /*Serviços, não deve obrigar ncm*/  
      AND ((P.BDALTCODUNIMED IS NULL) OR (P.BDALTCODUNIMED = 0));

      /*50 - Código de NCM não cadastrado*/
      INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
      SELECT 50 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
      FROM TMP_TCADPRO_TEMP P
      LEFT OUTER JOIN TNCM N ON(N.BDNCMPROD = P.BDNCMPROD)
      WHERE P.BDSESSAO = :PRSESSAO
      AND not (P.BDCODTIPOSER in (8,9,10,11,12)) /*#99586 - Inconsistência de falta de NCM no produto não deve ocorrer para TP_ITEM de 07, 08, 09, 10 ou 99*/
      AND ((P.BDNCMPROD IS NULL) OR ((P.BDNCMPROD IS NOT NULL) AND (N.BDNCMPROD IS NULL)));
    END

  /*50 - Código de NCM não cadastrado*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 50 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  LEFT OUTER JOIN TNCM N ON(N.BDNCMPROD = P.BDNCMPROD)
  WHERE P.BDSESSAO = :PRSESSAO
--  AND P.BDCODTIPOSER <> 10 /*Serviços, não deve obrigar ncm*/
  AND P.BDNCMPROD IS NOT NULL
  AND N.BDNCMPROD IS NULL;

  /*73 - Situação como Não relacionado(Está inconsistencia não aparece para o usuário, é somente para o controle de commit's)*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 73 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDSITUACAO IS NULL) OR (P.BDSITUACAO = 0));

  /*63 - Descrição do produto não pode estar vazia*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 63 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDDESCPROD IS NULL) OR (P.BDDESCPROD = ''));

  /*62 - Apelido do produto não pode estar vazio*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 62 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDAPEPROD IS NULL) OR (P.BDAPEPROD = ''));

  /*118 - NCM não possui o código de exceção.*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 118 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  LEFT OUTER JOIN TCODEXTIPI EX ON(EX.BDNCMPROD = P.BDNCMPROD AND EX.BDCODTIPI = P.BDCODTIPI)
  WHERE P.BDSESSAO = :PRSESSAO
  AND ((P.BDCODTIPI IS NOT NULL) AND (P.BDCODTIPI > 0))
  AND EX.BDCODTIPI IS NULL;

  /*179 - Produto inativo.*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 179 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  LEFT OUTER JOIN tcadpro_vinc V ON (P.bdcodemp = V.bdcodemp AND P.bdeditchave = V.bdcodprod)
  WHERE P.BDSESSAO = :PRSESSAO
  AND (UPPER(V.bdinativo) = 'TRUE');

    /* 200 - Consistir produtos com o mesmo código */
  IF (WCONSISTIRCODPROD = 'TRUE') THEN
    BEGIN
        INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
        SELECT 200 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
        FROM TMP_TCADPRO_TEMP P
        LEFT OUTER JOIN TCADPRO_VINC V ON (P.BDCODEMP = V.BDCODEMP AND P.BDEDITCHAVE = V.BDCODPROD)
        WHERE P.BDSESSAO = :PRSESSAO
        AND TRIM(P.BDDESCPROD) <> TRIM(V.BDDESCPROD);
    END
                   
                   
  DELETE FROM VEF_INCON_TUNIDADEMEDIDA WHERE BDSESSAO = :PRSESSAO;
  /*181 - Descrição da unidade de medida não preenchida.*/
  INSERT INTO VEF_INCON_TUNIDADEMEDIDA(BDCODINCONSISTENCIA, BDSESSAO, BDCODUNIMED)
  SELECT 181 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE
  FROM TMP_TUNIDADEMEDIDA_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
     AND Coalesce(P.BDDESCUNIMED,'') = '';

  /*182 - Unidade de medida inconsistente.*/
  INSERT INTO VEF_INCON_TCADPRO(BDCODINCONSISTENCIA, BDSESSAO, BDCODPROD, BDCODEMP)
  SELECT 182 BDCODINCONSISTENCIA, P.BDSESSAO, P.BDEDITCHAVE, P.BDCODEMP
  FROM TMP_TCADPRO_TEMP P
  WHERE P.BDSESSAO = :PRSESSAO
  AND EXISTS (SELECT FIRST 1 I.BDCODINCONSISTENCIA FROM VEF_INCON_TUNIDADEMEDIDA I WHERE I.BDCODUNIMED = P.BDCODUNIMED AND I.BDSESSAO = :PRSESSAO);


END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_TEQUIPSAT (
    PRSESSAO INTEGER,
    PRULTCHAVE INTEGER)
AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODEQUIPSAT INTEGER;
DECLARE VARIABLE WNRSERIE VARCHAR(9) COLLATE WIN_PTBR;
DECLARE VARIABLE WNRCAIXA INTEGER;
DECLARE VARIABLE WDATAINIOBRI DATE;
DECLARE VARIABLE WDATAFIMOBRI DATE;
DECLARE VARIABLE WCODEQUIPSAT_TMP INTEGER;
DECLARE VARIABLE WDATAINIOBRI_TMP DATE;
DECLARE VARIABLE WDATAFIMOBRI_TMP DATE;
BEGIN
  DELETE FROM VEF_INCON_TEQUIPSAT E WHERE E.BDSESSAO = :PRSESSAO;

  /*78 - Número de série não informado*/
  INSERT INTO VEF_INCON_TEQUIPSAT(BDSESSAO, BDCODEMP, BDCODEQUIPSAT, BDCODINCONSISTENCIA)
  SELECT E.BDSESSAO, E.BDCODEMP, E.BDCODEQUIPSAT, 78 BDCODINCONSISTENCIA
  FROM TMP_VEF_BASE_TEQUIPASAT_TEMP E
  WHERE E.BDSESSAO = :PRSESSAO
  AND ((E.BDNRSERIE IS NULL) OR (E.BDNRSERIE = ''));

  /*79 - Número do caixa não informado*/
  INSERT INTO VEF_INCON_TEQUIPSAT(BDSESSAO, BDCODEMP, BDCODEQUIPSAT, BDCODINCONSISTENCIA)
  SELECT E.BDSESSAO, E.BDCODEMP, E.BDCODEQUIPSAT, 79 BDCODINCONSISTENCIA
  FROM TMP_VEF_BASE_TEQUIPASAT_TEMP E
  WHERE E.BDSESSAO = :PRSESSAO
  AND ((E.BDNRCAIXA IS NULL));

  /*80 - Data de início das atividades não informada*/
  INSERT INTO VEF_INCON_TEQUIPSAT(BDSESSAO, BDCODEMP, BDCODEQUIPSAT, BDCODINCONSISTENCIA)
  SELECT E.BDSESSAO, E.BDCODEMP, E.BDCODEQUIPSAT, 80 BDCODINCONSISTENCIA
  FROM TMP_VEF_BASE_TEQUIPASAT_TEMP E
  WHERE E.BDSESSAO = :PRSESSAO
  AND (E.BDDATAINIOBRI IS NULL);

  FOR SELECT E.BDCODEMP, E.BDCODEQUIPSAT,
             E.BDNRSERIE, E.BDNRCAIXA,
             E.BDDATAINIOBRI, E.BDDATAFIMOBRI
      FROM TMP_VEF_BASE_TEQUIPASAT_TEMP E
      LEFT OUTER JOIN VEF_INCON_TEQUIPSAT EI ON(EI.BDSESSAO = E.BDSESSAO AND EI.BDCODEMP = E.BDCODEMP AND EI.BDCODEQUIPSAT = E.BDCODEQUIPSAT)
      WHERE E.BDSESSAO = :PRSESSAO
      AND E.BDCODEMP IS NOT NULL
      AND EI.BDCODINCONSISTENCIA IS NULL
      INTO :wCodEmp, :wCodEquipSat_tmp,
           :wNrSerie, :wNrCaixa,
           :wDataIniObri_tmp, :wDataFimObri_tmp
  DO
    BEGIN
      FOR SELECT EQ.BDCODEQUIPSAT, EQ.BDDATAINIOBRI,
                 EQ.BDDATAFIMOBRI
          FROM VEF_BASE_TEQUIPASAT EQ
          WHERE EQ.BDCODEMP = :wCodEmp
          AND EQ.BDNRSERIE = :wNrSerie
          AND EQ.BDNRCAIXA = :wNrCaixa
          ORDER BY EQ.BDCODEQUIPSAT
          INTO :wCodEquipSat, :wDataIniObri,
               :wDataFimObri
      DO
        BEGIN
          IF (((:wDataIniObri > :wDataIniObri_TMP) AND (((:wDataFimObri_TMP IS NULL) OR (:wDataFimObri_TMP = 0)) OR (:wDataIniObri <= :wDataFimObri_TMP))) OR
              ((:wDataIniObri <= :wDataIniObri_TMP) AND ((:wDataFimObri_TMP > :wDataIniObri) OR ((:wDataFimObri_TMP IS NULL) OR (:wDataFimObri_TMP = 0))))) THEN
            BREAK;
          ELSE
            wCodEquipSat = NULL;
        END

      IF ((:wCodEquipSat IS NOT NULL) AND (:wCodEquipSat > 0)) THEN /*Achou uma máquina com mesma série e caixa*/
        BEGIN
          IF (:wDataIniObri_tmp > wDataIniObri) THEN
            wDataIniObri_tmp = :wDataIniObri;

          IF (:wDataFimObri IS NOT NULL) THEN
            wDataFimObri_tmp = :wDataFimObri;

          UPDATE TMP_VEF_BASE_TEQUIPASAT_TEMP T
          SET T.BDEDITCHAVE = :wCodEquipSat,
              T.BDDATAINIOBRI = :wDataIniObri_tmp,
              T.BDDATAFIMOBRI = :wDataFimObri_tmp
          WHERE T.BDSESSAO = :PRSESSAO
          AND T.BDCODEQUIPSAT = :wCodEquipSat_tmp;
        END
      ELSE
        BEGIN
          UPDATE TMP_VEF_BASE_TEQUIPASAT_TEMP T SET T.BDEDITCHAVE = :PRULTCHAVE
          WHERE T.BDSESSAO = :PRSESSAO
          AND T.BDCODEQUIPSAT = :wCodEquipSat_tmp;

          PRULTCHAVE = :PRULTCHAVE - 1;
        END
     --alt:#23396 - w80794 - elizeu - 21-3-18 - Maquina com mesmo número de série e nr do caixa diferente uma já cadastrada e outra não

      wCodEquipSat = null;
      wDataIniObri = null;
      wDataFimObri = null;
    END
END^

CREATE OR ALTER PROCEDURE SP_INSERT_OR_UPDATE_TEQUIPSAT (
    PRSESSAO INTEGER)
AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE wEditChave INTEGER;
DECLARE VARIABLE wNrSerie VARCHAR(9);
DECLARE VARIABLE wNrCaixa INTEGER;
DECLARE VARIABLE wDataIniObri DATE;
DECLARE VARIABLE wDataFimObri DATE;
BEGIN
  FOR SELECT E.BDCODEMP, E.BDEDITCHAVE, E.BDNRSERIE,
             E.BDNRCAIXA, E.BDDATAINIOBRI, E.BDDATAFIMOBRI
      FROM TMP_VEF_BASE_TEQUIPASAT_TEMP E
      LEFT OUTER JOIN VEF_INCON_TEQUIPSAT I ON(I.BDSESSAO = E.BDSESSAO AND I.BDCODEMP = E.BDCODEMP AND I.BDCODEQUIPSAT = E.BDCODEQUIPSAT)
      WHERE E.BDSESSAO = :PRSESSAO
      AND I.BDCODINCONSISTENCIA IS NULL
      INTO :wCodEmp, :wEditChave, :wNrSerie,
           :wNrCaixa, :wDataIniObri, :wDataFimObri
  DO
    BEGIN
      UPDATE OR INSERT INTO VEF_BASE_TEQUIPASAT(BDCODEMP, BDCODEQUIPSAT, BDNRSERIE, BDNRCAIXA, BDDATAINIOBRI, BDDATAFIMOBRI)
      VALUES(:wCodEmp, :wEditChave , :wNrSerie, :wNrCaixa, :wDataIniObri, :wDataFimObri) MATCHING(BDCODEMP, BDCODEQUIPSAT);
    END
END^

CREATE OR ALTER PROCEDURE SP_PREPARA_PLANOTROCA_IMP (
    PRSESSAO INTEGER,
    PRTIPOMOV VARCHAR(3),
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS
DECLARE VARIABLE WCODIGOPLAEMPRESA INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WCODIGOPLA INTEGER;
DECLARE VARIABLE WSQL VARCHAR(3000);
DECLARE VARIABLE WTABLEMOV VARCHAR(40);
DECLARE VARIABLE WLANCAPARCELAAUTO VARCHAR(5);
BEGIN
  /*
     Alt.: #122344 - Antes de gerar as parcelas pela importação, precisa preencher a tabela "TMP_VEF_EMP_TMOVTROCA_CONDPGTO",
                     para carregar o plano de pagamento informado nas ações do plano de trocas.
     Pelo plano de trocas, cada ação pode ter um plano de pagamentos diferente, gerando uma quantidade de parcelas diferentes, não vai buscar fixo do cadastro da empresa...
   */
  DELETE FROM TMP_VEF_EMP_TMOVTROCA_CONDPGTO WHERE bdCODEMP = :prCODEMP;
   
  IF (:PRTIPOMOV = 'ENT') THEN
    wTABLEMOV   = 'TMP_VEF_EMP_TMOVENT_TEMP';
  ELSE
  IF (:PRTIPOMOV = 'SAI') THEN
    wTABLEMOV   = 'TMP_VEF_EMP_TMOVSAI_TEMP';
  ELSE
  IF (:PRTIPOMOV = 'SER') THEN
    wTABLEMOV   = 'TMP_VEF_EMP_TMOVSER_TEMP';
    
  SELECT sp.bdCODIGOPLA, sp.bdLANCAPARCELAAUTO
  FROM SP_CONSULTAEMPRESAS_SIS(:prREF, :prCODEMP, NULL) SP
  INTO :wCODIGOPLAEMPRESA, :wLANCAPARCELAAUTO;

  /* Vai jogar todos os dados dos lançamentos a "Prazo" na tabela temporária da troca de condição de pagamento, para gerar as parcelas... */
  wSQL =       'SELECT mov.bdCHAVE, mov.bdCODIGOPLAPLANOTROCA ';
  wSQL = wSQL||'FROM '||wTABLEMOV||' mov ';
  wSQL = wSQL||'WHERE mov.bdCONDPGTO = 1 ';
  --wSQL = wSQL||'  AND mov.bdCODIGOPLAPLANOTROCA > 0 ';
  wSQL = wSQL||'  AND mov.bdCODEMP = '||:prCODEMP;
  wSQL = wSQL||'  AND mov.bdSESSAO = '||:prSESSAO;

  FOR
      EXECUTE STATEMENT wSQL
      INTO :wCHAVE, :wCODIGOPLA
  DO
  BEGIN
    /* Caso o lançamento não tenha a informação do plano de pagamento da troca, busca do cadastro da empresa, caso tenha marcado para lançar parcelas automáticamente */
    IF ((wCODIGOPLA IS NULL) AND (wLANCAPARCELAAUTO = 'TRUE')) THEN
      wCODIGOPLA = wCODIGOPLAEMPRESA;

    IF (wCODIGOPLA IS NOT NULL) THEN
      INSERT INTO TMP_VEF_EMP_TMOVTROCA_CONDPGTO (BDCODEMP,BDCHAVE,BDCONDPGTODE,BDCONDPGTOPARA,BDMANTERPARCELAS,BDCODIGOPLA)
                                          VALUES (:prCODEMP,:wCHAVE,1,1,'FALSE',:wCODIGOPLA);
  END

END
^

CREATE OR ALTER PROCEDURE SP_GERAR_PARCELAS_AUT (
    PRSESSAO INTEGER,
    PRTIPOMOV VARCHAR(3),
    PRCODEMP INTEGER,
    PRREF INTEGER,
    PRPLANOTROCA VARCHAR(5) = 'FALSE')
AS
DECLARE VARIABLE WCODIGOPLA INTEGER;
DECLARE VARIABLE WQTDPARCELA INTEGER;
DECLARE VARIABLE WBDRETPARPIS DM_BOOLEAN;
DECLARE VARIABLE WBDRETPARCOFINS DM_BOOLEAN;
DECLARE VARIABLE WBDRETPARCSLL DM_BOOLEAN;
DECLARE VARIABLE WBDRETPARIRRF DM_BOOLEAN;
DECLARE VARIABLE WBDRETPARISSQN DM_BOOLEAN;
DECLARE VARIABLE WBDRETPARINSS DM_BOOLEAN;
DECLARE VARIABLE WBDRETFUNRURAL DM_BOOLEAN;
DECLARE VARIABLE WMANTERPARCELAS DM_BOOLEAN;
DECLARE VARIABLE WSQL VARCHAR(3000);
DECLARE VARIABLE WTABLEMOV VARCHAR(40);
DECLARE VARIABLE WTABLEITENS VARCHAR(40);
DECLARE VARIABLE WTABLERET VARCHAR(40);
DECLARE VARIABLE WTABLEPAR VARCHAR(40);
DECLARE VARIABLE WTABLEPARFIS VARCHAR(40);
DECLARE VARIABLE WINTERVALO INTEGER;
DECLARE VARIABLE WORDEMPAR INTEGER;
DECLARE VARIABLE WNUMDIASPAR INTEGER;
DECLARE VARIABLE WTABLEDED VARCHAR(32);
DECLARE VARIABLE WTABLEFUNRURAL VARCHAR(40);
DECLARE VARIABLE WDATAINIREC VARCHAR(10);
DECLARE VARIABLE WDATAINIEMI VARCHAR(10);
DECLARE VARIABLE WDATASER VARCHAR(200);
BEGIN
  /*
    Sol: 14207 Patrick T. Sá 26/10/2016. Criado parcelamento automático com hugefilefortpintegracao com sessão.
    Tabela TMP_TPARCELAMENTO_TEMP contém os valores que irão ser parcelados.
    Tabela TMP_TPARCELAS_TEMP contém as parcelas geradas, antes de dar commit na tabela real.
    Esta sp deve ser usada para entradas, saídas e serviços.
  */

  DELETE FROM TMP_TPARCELAMENTO_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_TPARCELAS_TEMP WHERE BDSESSAO = :PRSESSAO;

  SELECT SP.BDCODIGOPLA, SP.BDRETPARPIS, SP.BDRETPARCOFINS, SP.BDRETPARCSLL,
         SP.BDRETPARIRRF, SP.BDRETPARISSQN, SP.BDRETPARINSS, SP.BDRETPARFUNRURAL, SP.BDMANTERPARCELAS
  FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :PRCODEMP, NULL) SP
  INTO :wCodigoPla, :wBDRETPARPIS, :wBDRETPARCOFINS, :wBDRETPARCSLL,
       :wBDRETPARIRRF, :wBDRETPARISSQN, :wBDRETPARINSS, :wBDRETFUNRURAL,  :wManterParcelas;

  WTABLEFUNRURAL = '';
  IF (:PRTIPOMOV = 'ENT') THEN
    BEGIN
      wTableMov   = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItens = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      wTableRet   = 'TMP_VEF_EMP_TMOVENTRET_TEMP';
      wTablePar   = 'TMP_VEF_EMP_TMOVENTPAR_TEMP';
      wTableDed   = 'TMP_VEF_EMP_TMOVENTDED_TEMP';
      wTableParFis= 'VEF_EMP_TMOVENTPAR';
      WTABLEFUNRURAL = 'TMP_VEF_TMOVENTFUNRURAL_TEMP';
    END
  ELSE
  IF (:PRTIPOMOV = 'SAI') THEN
    BEGIN
      wTableMov   = 'TMP_VEF_EMP_TMOVSAI_TEMP';
      wTableItens = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
      wTableRet   = 'TMP_VEF_EMP_TMOVSAIRET_TEMP';
      wTablePar   = 'TMP_VEF_EMP_TMOVSAIPAR_TEMP';
      wTableDed   = 'TMP_VEF_EMP_TMOVSAIDED_TEMP';
      wTableParFis= 'VEF_EMP_TMOVSAIPAR';
    END
  ELSE
  IF (:PRTIPOMOV = 'SER') THEN
    BEGIN
      wTableMov   = 'TMP_VEF_EMP_TMOVSER_TEMP';
      wTableItens = 'TMP_VEF_EMP_TMOVSERITENS_TEMP';
      wTableRet   = 'TMP_VEF_EMP_TMOVSERRET_TEMP';
      wTablePar   = 'TMP_VEF_EMP_TMOVSERPAR_TEMP';
      wTableDed   = 'TMP_VEF_EMP_TMOVSERDED_TEMP';
      wTableParFis= 'VEF_EMP_TMOVSERPAR';

      SELECT first 1 BDVALOR FROM TPARGER WHERE UPPER(BDCAMPO) = 'BDSERRECPOREXECUCAO' into :WDATAINIREC;
      SELECT first 1 BDVALOR FROM TPARGER WHERE UPPER(BDCAMPO) = 'BDSEREMIPOREXECUCAO' into :WDATAINIEMI;
  
      if ((:wDataIniRec <> '') and (:wDataIniEmi <> '')) then
        WDATASER = 'IIF((m.BDTIPLAN = 1) AND (m.BDDATAEMISSAO >= ''' || :wDataIniRec || '''),'||
                       'm.BDDT_EXE_SERV,'||
                      'IIF((m.BDTIPLAN = 0) AND (m.BDDATAEMISSAO >= ''' || :wDataIniEmi || '''),'||
                       'm.BDDT_EXE_SERV,'||
                       'm.BDDATAEMISSAO))';
      else
      if (:wDataIniRec <> '') then
        WDATASER = 'IIF((m.BDTIPLAN = 1) AND (m.BDDATAEMISSAO >= ''' || :wDataIniRec || '''),'||
                       'm.BDDT_EXE_SERV,'||
                       'm.BDDATAEMISSAO)';
      else
      if (:wDataIniEmi <> '') then
        WDATASER = 'IIF((m.BDTIPLAN = 0) AND (m.BDDATAEMISSAO >= ''' || :wDataIniEmi || '''),'||
                       'm.BDDT_EXE_SERV,'||
                       'm.BDDATAEMISSAO)';
      ELSE
        WDATASER = 'm.bdDATAEMISSAO';
    END
  ELSE
  IF (:prTIPOMOV = 'DEM') THEN
    BEGIN
      wTablePar   = 'TMP_VEF_EMP_TMOVF100PAR_TEMP';
      wTableParFis= 'VEF_EMP_TMOVF100PAR';
    END

  /*Insere na tabela de parcelamento o valor total da nota com retenções somadas, e insere todas as retenções individuais*/
  wSQL =         'INSERT INTO TMP_TPARCELAMENTO_TEMP(BDSESSAO, BDCODEMP, BDCHAVE, BDDUPLICATAPAR, BDDATAVENCTOPAR, BDVLRCONTAB, BDVLRBRUTO, BDVLRPIS, BDVLRCOFINS, BDVLRCSOCIAL, BDVLRIR, BDVLRISS, BDVLRINSS, BDVLRFUNRURAL) ';
  IF (:PRTIPOMOV = 'DEM') THEN
    BEGIN -- Alt.: #70160 #96923 - Demais documentos não tem a estrutura de tabelas temporárias, por isso carrega das tabelas físicas...
      wSQL = wSQL || 'SELECT '||:PRSESSAO||' AS bdSESSAO, d.bdCODEMP, d.bdCHAVE, d.bdNUMDOC, ';
      wSQL = wSQL || '           d.bdDT_OPER AS bdDATAVENCTOPAR, ';
      wSQL = wSQL || '           SUM(COALESCE(d.bdVL_OPER, 0)) BDVLRCONTAB, SUM(COALESCE(d.bdVL_OPER, 0)) BDVLRBRUTO ';
      
      IF (:wBDRETPARPIS = 'TRUE') THEN
        wSQL = wSQL ||        ',SUM(COALESCE(r.bdVLRPIS, 0)) BDVLRPIS ';
      ELSE                                               
        wSQL = wSQL ||        ',0 BDVLRPIS ';
    
      IF (:wBDRETPARCOFINS = 'TRUE') THEN
        wSQL = wSQL ||        ',SUM(COALESCE(r.bdVLRCOFINS, 0)) BDVLRCOFINS ';
      ELSE                                               
        wSQL = wSQL ||        ',0 BDVLRCOFINS ';
    
      IF (:wBDRETPARCSLL = 'TRUE') THEN
        wSQL = wSQL ||        ',SUM(COALESCE(r.bdVLRCSOCIAL, 0)) BDVLRCSOCIAL ';
      ELSE                                               
        wSQL = wSQL ||        ',0 BDVLRCSOCIAL ';
    
      IF (:wBDRETPARIRRF = 'TRUE') THEN
        wSQL = wSQL ||        ',SUM(COALESCE(r.bdVLRIR, 0)) BDVLRIR ';
      ELSE                                               
        wSQL = wSQL ||        ',0 BDVLRIR ';
    
      IF (:wBDRETPARISSQN = 'TRUE') THEN
        wSQL = wSQL ||        ',SUM(COALESCE(r.bdISSRET, 0)) BDISSRET ';
      ELSE                                               
        wSQL = wSQL ||        ',0 BDISSRET ';

      wSQL = wSQL ||        ',0 BDRETINSS, 0 BDVLRFUNRURAL ';

      wSQL = wSQL || '    FROM VEF_EMP_TMOVDEMAISDOC_F100 d ';      
      wSQL = wSQL || '    LEFT OUTER JOIN VEF_EMP_TMOVDEMRET R ON(r.bdCODEMP = d.bdCODEMP AND r.bdCHAVE = d.bdCHAVE) ';      
      wSQL = wSQL || '    JOIN TMP_VEF_EMP_TMOVTROCA_CONDPGTO c ON (c.bdCODEMP = d.bdCODEMP AND c.bdCHAVE = d.bdCHAVE) ';
      wSQL = wSQL || '    WHERE d.bdCODEMP = '||:prCODEMP||' ';
      --wSQL = wSQL || '      AND d.bdREFLAN = '||:prREF||' ';
      wSQL = wSQL || '      AND c.bdCONDPGTOPARA = 1 ';
      wSQL = wSQL || '      AND c.bdCODIGOPLA > 0 ';
      wSQL = wSQL || '      AND ((C.BDMANTERPARCELAS <> ''TRUE'') OR ';
      wSQL = wSQL || '           ((C.BDMANTERPARCELAS = ''TRUE'') AND ';
      wSQL = wSQL || '            (NOT EXISTS (SELECT P.BDORDEMPAR ';
      wSQL = wSQL || '                         FROM VEF_EMP_TMOVF100PAR P ';
      wSQL = wSQL || '                         WHERE P.BDCODEMP = d.bdCODEMP ';
      wSQL = wSQL || '                           AND P.BDCHAVE = d.bdCHAVE))) ) ';
      wSQL = wSQL || '    GROUP BY d.BDCODEMP, d.BDCHAVE, d.bdNUMDOC, bdDATAVENCTOPAR; ';
    END
  ELSE
    BEGIN
      wSQL = wSQL || 'SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, M.BDNUMDOCINI, ';
    
      IF (:prPLANOTROCA = 'TRUE') THEN
        BEGIN
          IF (:PRTIPOMOV = 'ENT') THEN
            wSQL = wSQL||' CASE WHEN c.bdDATAVENCTO = 0 THEN m.bdDATAEMISSAO '||
                         '      WHEN c.bdDATAVENCTO = 1 THEN m.bdDATAENTRADAENT '||
                         ' ELSE m.bdDATAENTRADAENT '||                     
                         ' END AS bdDATAVENCTOPAR, ';
          ELSE
          IF (:PRTIPOMOV = 'SAI') THEN
            wSQL = wSQL||' CASE WHEN c.bdDATAVENCTO = 0 THEN m.bdDATAEMISSAO '||
                         '      WHEN c.bdDATAVENCTO = 1 THEN m.bdDATASAIDA '||
                         ' ELSE m.bdDATAEMISSAO '||                     
                         ' END AS bdDATAVENCTOPAR, ';
          ELSE
          IF (:PRTIPOMOV = 'SER') THEN
            wSQL = wSQL||' CASE WHEN c.bdDATAVENCTO = 0 THEN m.bdDATAEMISSAO '||
                         '      WHEN c.bdDATAVENCTO = 1 THEN m.bdDT_EXE_SERV '||
                         ' ELSE ('|| :WDATASER || ') '||
                         ' END AS bdDATAVENCTOPAR, ';
          ELSE
          IF (:PRTIPOMOV = 'DEM') THEN
            wSQL = wSQL||' m.bdDT_OPER AS bdDATAVENCTOPAR, ';
        END
      ELSE
        BEGIN
          IF (:PRTIPOMOV = 'ENT') THEN
            wSQL = wSQL ||        'M.BDDATAENTRADAENT, ';
          ELSE        
          IF (:PRTIPOMOV = 'DEM') THEN
            wSQL = wSQL||' m.bdDT_OPER, ';
          ELSE
            wSQL = wSQL ||        'M.BDDATAEMISSAO, ';
        END                                 
      wSQL = wSQL ||        'SUM(COALESCE(I.BDVLRCONTAB, 0)) BDVLRCONTAB, ';
      wSQL = wSQL ||        'SUM(COALESCE(I.BDVLRCONTAB, 0)) BDVLRBRUTO ';
        
      IF (:wBDRETPARPIS = 'TRUE') THEN
        wSQL = wSQL ||        ',SUM(COALESCE((R.BDVLRPIS/qtde.bdCOUNT), 0)) BDVLRPIS ';
      ELSE                                               
        wSQL = wSQL ||        ',0 BDVLRPIS ';
    
      IF (:wBDRETPARCOFINS = 'TRUE') THEN
        wSQL = wSQL ||        ',SUM(COALESCE((R.BDVLRCOFINS/qtde.bdCOUNT), 0)) BDVLRCOFINS ';
      ELSE                                               
        wSQL = wSQL ||        ',0 BDVLRCOFINS ';
    
      IF (:wBDRETPARCSLL = 'TRUE') THEN
        wSQL = wSQL ||        ',SUM(COALESCE((R.BDVLRCSOCIAL/qtde.bdCOUNT), 0)) BDVLRCSOCIAL ';
      ELSE                                               
        wSQL = wSQL ||        ',0 BDVLRCSOCIAL ';
    
      IF (:wBDRETPARIRRF = 'TRUE') THEN
        BEGIN                                   
          IF (:PRTIPOMOV = 'SER') THEN
            BEGIN
              wSQL = wSQL ||  ',Sum(iif(exists(select first 1 I.BDCODEMP ';
              wSQL = wSQL ||  '                from VEF_EMP_TMOVSERITENS I ';
              wSQL = wSQL ||  '                left outer join TCODREC R on (R.BDCODREC = I.BDCODREC) ';
              wSQL = wSQL ||  '                where I.BDCODEMP = M.BDCODEMP and ';
              wSQL = wSQL ||  '                      I.BDCHAVE = M.BDCHAVE and ';
              wSQL = wSQL ||  '                      R.BDSEMPROVIRRF = ''TRUE''), 0, COALESCE((R.BDVLRIR/qtde.bdCOUNT), 0))) BDVLRIR ';
            END
          ELSE
            wSQL = wSQL ||    ',SUM(COALESCE((R.BDVLRIR/qtde.bdCOUNT), 0)) BDVLRIR ';
        END
      ELSE                                               
        wSQL = wSQL ||        ',0 BDVLRIR ';
    
      IF (:wBDRETPARISSQN = 'TRUE') THEN
        wSQL = wSQL ||        ',SUM(COALESCE((R.BDISSRET/qtde.bdCOUNT), 0)) BDISSRET ';
      ELSE                                               
        wSQL = wSQL ||        ',0 BDISSRET ';
    
      IF (:wBDRETPARINSS = 'TRUE') THEN
        wSQL = wSQL ||        ',SUM(COALESCE(D.BDRETINSS, 0)) BDRETINSS ';
      ELSE                                               
        wSQL = wSQL ||        ',0 BDRETINSS ';
    
      IF ((:WTABLEFUNRURAL <> '') AND (wBDRETFUNRURAL = 'TRUE')) THEN
        wSQL = wSQL ||        ',SUM(COALESCE(F.BDVLRFUNRURAL, 0) + COALESCE(F.BDVLRGILRAT, 0) + COALESCE(F.BDVLRFPAS, 0)) BDVLRFUNRURAL ';
      ELSE                                               
        wSQL = wSQL ||        ',0 BDVLRFUNRURAL ';

      wSQL = wSQL || 'FROM '||:wTableItens||' I ';
      wSQL = wSQL || 'LEFT OUTER JOIN '||:wTableMov||' M ON(M.BDSESSAO = I.BDSESSAO AND M.BDCODEMP = I.BDCODEMP AND M.BDCHAVE = I.BDCHAVE) ';
      wSQL = wSQL || 'LEFT OUTER JOIN '||:wTableRet||' R ON(R.BDSESSAO = I.BDSESSAO AND R.BDCODEMP = I.BDCODEMP AND R.BDCHAVE = I.BDCHAVE) ';
      wSQL = wSQL || 'LEFT OUTER JOIN '||:wTableDed||' D ON(D.BDSESSAO = I.BDSESSAO AND D.BDCODEMP = I.BDCODEMP AND D.BDCHAVE = I.BDCHAVE) ';
                                         
      IF (:WTABLEFUNRURAL <> '') THEN
        wSQL = wSQL || 'LEFT OUTER JOIN '||:WTABLEFUNRURAL||' F ON(F.BDSESSAO = I.BDSESSAO AND F.BDCODEMP = I.BDCODEMP AND F.BDCHAVE = I.BDCHAVE) ';
      wSQL = wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDLANCPARCELAMENTO = ''TRUE'') '; 
      wSQL = wSQL || 'join (SELECT q.bdSESSAO, q.bdCODEMP, q.bdCHAVE, COUNT(q.bdCODEMP) AS bdCOUNT '; -- Alt.: #122344 - Estava matriciando os valores das retencoes quando tinham varias CFOPs
      wSQL = wSQL || '      FROM '||:wTableItens||' q ';
      wSQL = wSQL || '      WHERE q.BDSESSAO = '||:PRSESSAO||' ';
      wSQL = wSQL || '      GROUP BY q.BDSESSAO, q.bdCODEMP, q.bdCHAVE) qtde ON (qtde.bdSESSAO = i.bdSESSAO and qtde.bdCODEMP = i.bdCODEMP and qtde.bdCHAVE = i.bdCHAVE) ';      
      IF (:prPLANOTROCA = 'TRUE') THEN
        wSQL = wSQL || 'JOIN TMP_VEF_EMP_TMOVTROCA_CONDPGTO c ON (c.bdCODEMP = i.bdCODEMP AND c.bdCHAVE = i.bdCHAVE) ';
      wSQL = wSQL || 'WHERE I.BDSESSAO = '||:PRSESSAO||' ';
                                                
      wSQL = wSQL || 'AND I.BDVLRCONTAB > 0 ';
      IF (:prPLANOTROCA = 'TRUE') THEN
        BEGIN
          wSQL = wSQL || 'AND c.bdCONDPGTOPARA = 1 '; -- 1 - Prazo
          wSQL = wSQL || 'AND c.bdCODIGOPLA > 0 and (NOT m.BDCODSITNF IN(2, 3, 4, 5))  ';
          --wSQL = wSQL || 'AND c.bdMANTERPARCELAS <> ''TRUE'' ';
          wSQL = wSQL || '  AND ((C.BDMANTERPARCELAS <> ''TRUE'') OR '; 
          wSQL = wSQL || '       ((C.BDMANTERPARCELAS = ''TRUE'') AND '; -- #122344 - Quando mantém as parcelas, verifica se existem parcelas...
          wSQL = wSQL || '        (NOT EXISTS (SELECT P.BDORDEMPAR ';
          wSQL = wSQL || '                     FROM '||:wTableParFis||' P ';
          wSQL = wSQL || '                     WHERE P.BDCODEMP = I.BDCODEMP ';
          wSQL = wSQL || '                       AND P.BDCHAVE = I.BDCHAVE))) ) ';
        END
      ELSE
        BEGIN
          IF (:wManterParcelas = 'TRUE') THEN
            BEGIN
              wSQL = wSQL || 'AND NOT EXISTS (SELECT P.BDORDEMPAR FROM '||:wTablePar||' P ';
              wSQL = wSQL ||                 'WHERE P.BDSESSAO = I.BDSESSAO ';
              wSQL = wSQL ||                 'AND P.BDCODEMP = I.BDCODEMP ';
              wSQL = wSQL ||                 'AND P.BDCHAVE = I.BDCHAVE) ';
            END
        END
    
      IF (:prPLANOTROCA = 'TRUE') THEN
        wSQL = wSQL || 'GROUP BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, M.BDNUMDOCINI, bdDATAVENCTOPAR;';
      ELSE
      IF (:PRTIPOMOV = 'ENT') THEN
        wSQL = wSQL || 'GROUP BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, M.BDNUMDOCINI, M.BDDATAENTRADAENT;';
      ELSE
        wSQL = wSQL || 'GROUP BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, M.BDNUMDOCINI, M.BDDATAEMISSAO;';
    END
    
  EXECUTE STATEMENT :wSQL;

  /*Faz update somente das deduções que são marcadas no cadastro da empresa*/
  UPDATE TMP_TPARCELAMENTO_TEMP P SET P.BDVLRCONTAB = P.BDVLRCONTAB - (P.BDVLRPIS + P.BDVLRCOFINS + P.BDVLRCSOCIAL +
                                                                       P.BDVLRIR + P.BDVLRISS + P.BDVLRINSS + P.BDVLRFUNRURAL) WHERE P.BDSESSAO = :PRSESSAO;
  /*IF (:wBDRETPARPIS = 'TRUE') THEN
    UPDATE TMP_TPARCELAMENTO_TEMP P SET P.BDVLRCONTAB = (P.BDVLRCONTAB - P.BDVLRPIS) WHERE P.BDSESSAO = :PRSESSAO;

  IF (:wBDRETPARCOFINS = 'TRUE') THEN
    UPDATE TMP_TPARCELAMENTO_TEMP P SET P.BDVLRCONTAB = (P.BDVLRCONTAB - P.BDVLRCOFINS) WHERE P.BDSESSAO = :PRSESSAO;

  IF (:wBDRETPARCSLL = 'TRUE') THEN
    UPDATE TMP_TPARCELAMENTO_TEMP P SET P.BDVLRCONTAB = (P.BDVLRCONTAB - P.BDVLRCSOCIAL) WHERE P.BDSESSAO = :PRSESSAO;

  IF (:wBDRETPARIRRF = 'TRUE') THEN
    UPDATE TMP_TPARCELAMENTO_TEMP P SET P.BDVLRCONTAB = (P.BDVLRCONTAB - P.BDVLRIR) WHERE P.BDSESSAO = :PRSESSAO;

  IF (:wBDRETPARISSQN = 'TRUE') THEN
    UPDATE TMP_TPARCELAMENTO_TEMP P SET P.BDVLRCONTAB = (P.BDVLRCONTAB - P.BDVLRISS) WHERE P.BDSESSAO = :PRSESSAO;

  IF (:wBDRETPARINSS = 'TRUE') THEN
    UPDATE TMP_TPARCELAMENTO_TEMP P SET P.BDVLRCONTAB = (P.BDVLRCONTAB - P.BDVLRINSS) WHERE P.BDSESSAO = :PRSESSAO;

  IF (wBDRETFUNRURAL = 'TRUE') THEN
    UPDATE TMP_TPARCELAMENTO_TEMP P SET P.BDVLRCONTAB = (P.BDVLRCONTAB - P.BDVLRFUNRURAL) WHERE P.BDSESSAO = :PRSESSAO;  */

  IF (:prPLANOTROCA = 'TRUE') THEN -- Alt.: #122344 - Plano de troca, pode ser um plano de pagamento diferente por lançamento...
    BEGIN
      FOR SELECT p.bdCODIGOPLA, p.bdNUMPARPLA, p.bdNUMDIASPLA
          FROM TPLANO_PAGAMENTO p
          WHERE P.BDCODIGOPLA IN (SELECT DISTINCT(c.bdCODIGOPLA) FROM TMP_VEF_EMP_TMOVTROCA_CONDPGTO c)
          INTO  :wCodigoPla, :wQtdParcela, :wNumDiasPar
      DO BEGIN
           /*Se tiver intervalo no plano de parcelas, vai inserir os intervalos nessa tabela temporária*/
--           INSERT INTO TMP_TINTERVALO_PARC(BDCODIGOPLA, BDORDEM, BDINTERVALO)
--           SELECT I.BDCODIGOPLA, I.BDORDEM, I.BDINTERVALODIAS
--           FROM TPLANO_PAGAMENTO_INTDIAS I
--           WHERE I.BDCODIGOPLA = :wCodigoPla;
      
           wOrdemPar = 1;
           WHILE (:wOrdemPar <= :wQtdParcela) DO
             BEGIN
               INSERT INTO TMP_TINTERVALO_PARC(BDCODIGOPLA, BDORDEM, BDINTERVALO) VALUES(:wCodigoPla, :wOrdemPar, :wNumDiasPar);
               wOrdemPar = :wOrdemPar + 1;
             END

           /*Se tiver intervalo no plano de parcelas, vai inserir os intervalos nessa tabela temporária*/
           UPDATE TMP_TINTERVALO_PARC P
           SET P.BDINTERVALO = Coalesce((SELECT FIRST 1 i.BDINTERVALODIAS FROM TPLANO_PAGAMENTO_INTDIAS I WHERE I.BDCODIGOPLA = P.BDCODIGOPLA AND I.BDORDEM = P.BDORDEM) -
                                         Coalesce((SELECT SUM(IT.BDINTERVALO) FROM TMP_TINTERVALO_PARC IT WHERE IT.BDCODIGOPLA = P.BDCODIGOPLA AND IT.BDORDEM < P.BDORDEM),0)
                                        ,:wNumDiasPar)
           WHERE P.BDCODIGOPLA = :wCodigoPla;

         END
    END
  ELSE
    BEGIN
      SELECT P.BDNUMPARPLA, P.BDNUMDIASPLA FROM TPLANO_PAGAMENTO P WHERE P.BDCODIGOPLA = :wCodigoPla INTO :wQtdParcela, :wNumDiasPar;
                              
      wOrdemPar = 1;
      WHILE (:wOrdemPar <= :wQtdParcela) DO
        BEGIN
          INSERT INTO TMP_TINTERVALO_PARC(BDCODIGOPLA, BDORDEM, BDINTERVALO) VALUES(:wCodigoPla, :wOrdemPar, :wNumDiasPar);
          wOrdemPar = :wOrdemPar + 1;
        END

      /*Se tiver intervalo no plano de parcelas, vai inserir os intervalos nessa tabela temporária*/
      UPDATE TMP_TINTERVALO_PARC P
      SET P.BDINTERVALO = Coalesce((SELECT FIRST 1 i.BDINTERVALODIAS FROM TPLANO_PAGAMENTO_INTDIAS I WHERE I.BDCODIGOPLA = P.BDCODIGOPLA AND I.BDORDEM = P.BDORDEM) -
                                    Coalesce((SELECT SUM(IT.BDINTERVALO) FROM TMP_TINTERVALO_PARC IT WHERE IT.BDCODIGOPLA = P.BDCODIGOPLA AND IT.BDORDEM < P.BDORDEM),0)
                                    ,:wNumDiasPar)
      WHERE P.BDCODIGOPLA = :wCodigoPla;

      /*Se tiver intervalo no plano de parcelas, vai inserir os intervalos nessa tabela temporária*/
--      INSERT INTO TMP_TINTERVALO_PARC(BDCODIGOPLA, BDORDEM, BDINTERVALO)
--      SELECT I.BDCODIGOPLA, I.BDORDEM, I.BDINTERVALODIAS
--      FROM TPLANO_PAGAMENTO_INTDIAS I
--      WHERE I.BDCODIGOPLA = :wCodigoPla;
--    
--      /*Se entrar nesse if é porque não havia intervalo de dias no plano, então vai gerar as parcelas. EX: numDeParcelas = 4, numDias = 30. Vai gerar 1 - 30, 2 - 30, 3 - 30, 4 - 40*/
--      IF (ROW_COUNT = 0) THEN
--        BEGIN
--          wOrdemPar = 1;
--          WHILE (:wOrdemPar <= :wQtdParcela) DO
--            BEGIN
--              INSERT INTO TMP_TINTERVALO_PARC(BDCODIGOPLA, BDORDEM, BDINTERVALO) VALUES(:wCodigoPla, :wOrdemPar, :wNumDiasPar);
--              wOrdemPar = :wOrdemPar + 1;
--            END
--        END
    END

  /*Gera as parcelas, sem datas, apenas com valor*/
  IF (:prPLANOTROCA = 'TRUE') THEN -- Alt.: #122344 - Insere as parcelas de acordo com o plano de pagamento selecionado no plano de trocas...
    BEGIN
      INSERT INTO TMP_TPARCELAS_TEMP(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMPAR, BDDATAVENCTOPAR, BDDUPLICATAPAR, BDVALOR, BDVALORBRUTO, BDVALORTOTAL,
                                     BDVALORRETPIS, BDVALORRETCOFINS, BDVALORRETCSLL, BDVALORRETIRRF, BDVALORRETISSQN, BDVALORRETINSS, BDVALORRETFUNRURAL,
                                     BDTOTRETPIS, BDTOTRETCOFINS, BDTOTRETCSLL, BDTOTRETIRRF, BDTOTRETISSQN, BDTOTRETINSS, BDTOTRETFUNRURAL)
      SELECT P.BDSESSAO, P.BDCODEMP, P.BDCHAVE, I.BDORDEM, P.BDDATAVENCTOPAR, P.BDDUPLICATAPAR,
             CAST(P.BDVLRCONTAB / pla.bdNUMPARPLA AS NUMERIC(15, 2)) BDVALOR, /*Valor arredondado*/
             CAST(P.BDVLRBRUTO / pla.bdNUMPARPLA AS NUMERIC(15, 2)) BDVALORBRUTO, /*Valor bruto*/
             (COALESCE(P.BDVLRCONTAB, 0)+ /*Valor contábil da nota*/
              COALESCE(p.bdVLRPIS,0)+COALESCE(p.bdVLRCOFINS,0)+COALESCE(p.bdVLRCSOCIAL,0)+COALESCE(p.bdVLRIR,0)+COALESCE(p.bdVLRISS,0)+COALESCE(p.bdVLRINSS,0)+COALESCE(p.bdVLRFUNRURAL,0)),
             COALESCE(P.BDVLRPIS,0),COALESCE(P.BDVLRCOFINS,0),COALESCE(P.BDVLRCSOCIAL,0),COALESCE(P.BDVLRIR,0),COALESCE(P.BDVLRISS,0),COALESCE(P.BDVLRINSS,0),COALESCE(P.BDVLRFUNRURAL,0),
             COALESCE(P.BDVLRPIS,0),COALESCE(P.BDVLRCOFINS,0),COALESCE(P.BDVLRCSOCIAL,0),COALESCE(P.BDVLRIR,0),COALESCE(P.BDVLRISS,0),COALESCE(P.BDVLRINSS,0),COALESCE(P.BDVLRFUNRURAL,0)
      FROM TMP_TPARCELAMENTO_TEMP P
      JOIN TMP_VEF_EMP_TMOVTROCA_CONDPGTO c ON (c.bdCODEMP = p.bdCODEMP AND c.bdCHAVE = p.bdCHAVE)
      --LEFT OUTER JOIN TMP_TINTERVALO_PARC I ON(I.BDCODIGOPLA = :wCodigoPla)
      LEFT OUTER JOIN TMP_TINTERVALO_PARC I ON(I.BDCODIGOPLA = c.bdCODIGOPLA)
      LEFT OUTER JOIN TPLANO_PAGAMENTO pla ON (pla.bdCODIGOPLA = c.bdCODIGOPLA)
      WHERE P.BDSESSAO = :PRSESSAO;

      /*Colocar o resto na primeira parcela*/
      UPDATE TMP_TPARCELAS_TEMP P
      SET BDVALOR = (
                     SELECT FIRST 1 CAST(P.BDVALOR + (PARC.BDVLRCONTAB - (P.BDVALOR * pla.bdNUMPARPLA)) AS NUMERIC(15, 2)) BDVALOR
                     FROM TMP_TPARCELAMENTO_TEMP PARC
                     JOIN TMP_VEF_EMP_TMOVTROCA_CONDPGTO c ON (c.bdCODEMP = p.bdCODEMP AND c.bdCHAVE = p.bdCHAVE)
                     LEFT OUTER JOIN TPLANO_PAGAMENTO pla ON (pla.bdCODIGOPLA = c.bdCODIGOPLA)
                     WHERE PARC.BDSESSAO = P.BDSESSAO
                     AND PARC.BDCODEMP = P.BDCODEMP
                     AND PARC.BDCHAVE = P.BDCHAVE
                    ),
          BDVALORBRUTO = (
                          SELECT FIRST 1 CAST(P.BDVALORBRUTO + (PARC.BDVLRBRUTO - (P.BDVALORBRUTO * pla.bdNUMPARPLA)) AS NUMERIC(15, 2)) BDVALORBRUTO
                          FROM TMP_TPARCELAMENTO_TEMP PARC
                          JOIN TMP_VEF_EMP_TMOVTROCA_CONDPGTO c ON (c.bdCODEMP = p.bdCODEMP AND c.bdCHAVE = p.bdCHAVE)
                          LEFT OUTER JOIN TPLANO_PAGAMENTO pla ON (pla.bdCODIGOPLA = c.bdCODIGOPLA)
                          WHERE PARC.BDSESSAO = P.BDSESSAO
                          AND PARC.BDCODEMP = P.BDCODEMP
                          AND PARC.BDCHAVE = P.BDCHAVE
                         )
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDORDEMPAR = 1;
    END
  ELSE
    BEGIN
      INSERT INTO TMP_TPARCELAS_TEMP(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMPAR, BDDATAVENCTOPAR, BDDUPLICATAPAR, BDVALOR, BDVALORBRUTO, BDVALORTOTAL,
                                     BDVALORRETPIS,BDVALORRETCOFINS, BDVALORRETCSLL, BDVALORRETIRRF, BDVALORRETISSQN, BDVALORRETINSS, BDVALORRETFUNRURAL,
                                     BDTOTRETPIS,BDTOTRETCOFINS, BDTOTRETCSLL, BDTOTRETIRRF, BDTOTRETISSQN, BDTOTRETINSS, BDTOTRETFUNRURAL)
      SELECT P.BDSESSAO, P.BDCODEMP, P.BDCHAVE, I.BDORDEM, P.BDDATAVENCTOPAR, P.BDDUPLICATAPAR,
             CAST(P.BDVLRCONTAB / :wQtdParcela AS NUMERIC(15, 2)) BDVALOR, /*Valor arredondado*/
             CAST(P.BDVLRBRUTO / :wQtdParcela AS NUMERIC(15, 2)) BDVALORBRUTO, /*Valor bruto*/
             COALESCE(P.BDVLRCONTAB, 0), /*Valor contábil da nota*/
             COALESCE(P.BDVLRPIS,0),COALESCE(P.BDVLRCOFINS,0),COALESCE(P.BDVLRCSOCIAL,0),COALESCE(P.BDVLRIR,0),COALESCE(P.BDVLRISS,0),COALESCE(P.BDVLRINSS,0),COALESCE(P.BDVLRFUNRURAL,0),
             COALESCE(P.BDVLRPIS,0),COALESCE(P.BDVLRCOFINS,0),COALESCE(P.BDVLRCSOCIAL,0),COALESCE(P.BDVLRIR,0),COALESCE(P.BDVLRISS,0),COALESCE(P.BDVLRINSS,0),COALESCE(P.BDVLRFUNRURAL,0)
      FROM TMP_TPARCELAMENTO_TEMP P
      LEFT OUTER JOIN TMP_TINTERVALO_PARC I ON(I.BDCODIGOPLA = :wCodigoPla)
      WHERE P.BDSESSAO = :PRSESSAO;
      
      /*Colocar o resto na primeira parcela*/
      UPDATE TMP_TPARCELAS_TEMP P
      SET BDVALOR = (
                     SELECT FIRST 1 CAST(P.BDVALOR + (PARC.BDVLRCONTAB - (P.BDVALOR * :wQtdParcela)) AS NUMERIC(15, 2)) BDVALOR
                     FROM TMP_TPARCELAMENTO_TEMP PARC
                     WHERE PARC.BDSESSAO = P.BDSESSAO
                     AND PARC.BDCODEMP = P.BDCODEMP
                     AND PARC.BDCHAVE = P.BDCHAVE
                    ),
          BDVALORBRUTO = (
                          SELECT FIRST 1 CAST(P.BDVALORBRUTO + (PARC.BDVLRBRUTO - (P.BDVALORBRUTO * :wQtdParcela)) AS NUMERIC(15, 2)) BDVALORBRUTO
                          FROM TMP_TPARCELAMENTO_TEMP PARC
                          WHERE PARC.BDSESSAO = P.BDSESSAO
                          AND PARC.BDCODEMP = P.BDCODEMP
                          AND PARC.BDCHAVE = P.BDCHAVE
                         )
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDORDEMPAR = 1;
    END

  /*Colocando a data de vencimento da parcela*/
  wOrdemPar = NULL;
  FOR SELECT D.BDORDEM, D.BDINTERVALO
      FROM TMP_TINTERVALO_PARC D
      WHERE d.bdcodigopla = :wCodigoPla
      ORDER BY D.BDORDEM
      INTO :wOrdemPar, :wIntervalo
  DO
    BEGIN
      IF (:wOrdemPar > 1) THEN
        BEGIN
          UPDATE TMP_TPARCELAS_TEMP P SET P.BDDATAVENCTOPAR = (
                                                               SELECT FIRST 1 PD.BDDATAVENCTOPAR
                                                               FROM TMP_TPARCELAS_TEMP PD
                                                               WHERE PD.BDSESSAO = P.BDSESSAO
                                                               AND PD.BDCODEMP   = P.BDCODEMP
                                                               AND PD.BDCHAVE    = P.BDCHAVE
                                                               AND PD.BDORDEMPAR = (:wOrdemPar-1)
                                                              )
          WHERE P.BDSESSAO = :PRSESSAO
          AND P.BDORDEMPAR = :wOrdemPar;
        END

      UPDATE TMP_TPARCELAS_TEMP P SET P.BDDATAVENCTOPAR = DATEADD(:wIntervalo DAY TO P.BDDATAVENCTOPAR)
      WHERE P.BDSESSAO = :PRSESSAO
      AND P.BDORDEMPAR = :wOrdemPar;
    END

  DELETE FROM TMP_TINTERVALO_PARC WHERE BDCODIGOPLA > 0;

  /*Colocar retenções nas parcelas(PIS, Cofins, CSLL, IRRF, ISSQN, INSS)*/
  /*PIS*/
  IF (:wBDRETPARPIS = 'TRUE') THEN
    BEGIN
    UPDATE TMP_TPARCELAS_TEMP P SET P.BDVALORRETPIS = CAST((P.BDVALORRETPIS * (P.BDVALORBRUTO / P.BDVALORTOTAL)) AS NUMERIC(15, 2))
    WHERE P.BDSESSAO = :PRSESSAO AND P.BDVALORRETPIS > 0;
      
      /* Caso sobre diferença nas retenções, joga na ultima parcela */
      UPDATE TMP_TPARCELAS_TEMP P
      SET p.bdVALORRETPIS = p.bdVALORRETPIS + (p.bdTOTRETPIS - (SELECT SUM(COALESCE(t.bdVALORRETPIS,0))
                                                                FROM TMP_TPARCELAS_TEMP t
                                                                WHERE t.bdSESSAO = p.bdSESSAO
                                                                  AND t.bdCODEMP = p.bdCODEMP
                                                                  AND t.bdCHAVE  = p.bdCHAVE))
      WHERE P.BDSESSAO = :PRSESSAO
        AND P.BDVALORRETPIS > 0
        AND p.bdORDEMPAR = (SELECT MAX(x.bdORDEMPAR)
                            FROM TMP_TPARCELAS_TEMP x
                            WHERE x.bdSESSAO = p.bdSESSAO
                              AND x.bdCODEMP = p.bdCODEMP
                              AND x.bdCHAVE  = p.bdCHAVE);
    END

  /*COFINS*/
  IF (:wBDRETPARCOFINS = 'TRUE') THEN
    BEGIN
    UPDATE TMP_TPARCELAS_TEMP P SET P.BDVALORRETCOFINS = CAST((P.BDVALORRETCOFINS * (P.BDVALORBRUTO / P.BDVALORTOTAL)) AS NUMERIC(15, 2))
    WHERE P.BDSESSAO = :PRSESSAO AND P.BDVALORRETCOFINS > 0;
      
      /* Caso sobre diferença nas retenções, joga na ultima parcela */
      UPDATE TMP_TPARCELAS_TEMP P
      SET p.bdVALORRETCOFINS = p.bdVALORRETCOFINS + (p.bdTOTRETCOFINS - (SELECT SUM(COALESCE(t.bdVALORRETCOFINS,0))
                                                                         FROM TMP_TPARCELAS_TEMP t
                                                                         WHERE t.bdSESSAO = p.bdSESSAO
                                                                           AND t.bdCODEMP = p.bdCODEMP
                                                                           AND t.bdCHAVE  = p.bdCHAVE))
      WHERE P.BDSESSAO = :PRSESSAO
        AND P.BDVALORRETCOFINS > 0
        AND p.bdORDEMPAR = (SELECT MAX(x.bdORDEMPAR)
                            FROM TMP_TPARCELAS_TEMP x
                            WHERE x.bdSESSAO = p.bdSESSAO
                              AND x.bdCODEMP = p.bdCODEMP
                              AND x.bdCHAVE  = p.bdCHAVE);
    END

   /*CSLL*/
  IF (:wBDRETPARCSLL = 'TRUE') THEN
    BEGIN
    UPDATE TMP_TPARCELAS_TEMP P SET P.BDVALORRETCSLL = CAST((P.BDVALORRETCSLL * (P.BDVALORBRUTO / P.BDVALORTOTAL)) AS NUMERIC(15, 2))
    WHERE P.BDSESSAO = :PRSESSAO AND P.BDVALORRETCSLL > 0;
      
      /* Caso sobre diferença nas retenções, joga na ultima parcela */
      UPDATE TMP_TPARCELAS_TEMP P
      SET p.bdVALORRETCSLL = p.bdVALORRETCSLL + (p.bdTOTRETCSLL - (SELECT SUM(COALESCE(t.bdVALORRETCSLL,0))
                                                                   FROM TMP_TPARCELAS_TEMP t
                                                                   WHERE t.bdSESSAO = p.bdSESSAO
                                                                     AND t.bdCODEMP = p.bdCODEMP
                                                                     AND t.bdCHAVE  = p.bdCHAVE))
      WHERE P.BDSESSAO = :PRSESSAO
        AND P.BDVALORRETCSLL > 0
        AND p.bdORDEMPAR = (SELECT MAX(x.bdORDEMPAR)
                            FROM TMP_TPARCELAS_TEMP x
                            WHERE x.bdSESSAO = p.bdSESSAO
                              AND x.bdCODEMP = p.bdCODEMP
                              AND x.bdCHAVE  = p.bdCHAVE);
    END

  /*IRRF*/
  IF (:wBDRETPARIRRF = 'TRUE') THEN
    BEGIN
    UPDATE TMP_TPARCELAS_TEMP P SET P.BDVALORRETIRRF = CAST((P.BDVALORRETIRRF * (P.BDVALORBRUTO / P.BDVALORTOTAL)) AS NUMERIC(15, 2))
    WHERE P.BDSESSAO = :PRSESSAO AND P.BDVALORRETIRRF > 0;
      
      /* Caso sobre diferença nas retenções, joga na ultima parcela */
      UPDATE TMP_TPARCELAS_TEMP P
      SET p.bdVALORRETIRRF = p.bdVALORRETIRRF + (p.bdTOTRETIRRF - (SELECT SUM(COALESCE(t.bdVALORRETIRRF,0))
                                                                   FROM TMP_TPARCELAS_TEMP t
                                                                   WHERE t.bdSESSAO = p.bdSESSAO
                                                                     AND t.bdCODEMP = p.bdCODEMP
                                                                     AND t.bdCHAVE  = p.bdCHAVE))
      WHERE P.BDSESSAO = :PRSESSAO
        AND P.BDVALORRETIRRF > 0
        AND p.bdORDEMPAR = (SELECT MAX(x.bdORDEMPAR)
                            FROM TMP_TPARCELAS_TEMP x
                            WHERE x.bdSESSAO = p.bdSESSAO
                              AND x.bdCODEMP = p.bdCODEMP
                              AND x.bdCHAVE  = p.bdCHAVE);
    END

  /*ISSQN*/
  IF (:wBDRETPARISSQN = 'TRUE') THEN
    BEGIN
    UPDATE TMP_TPARCELAS_TEMP P SET P.BDVALORRETISSQN = CAST((P.BDVALORRETISSQN * (P.BDVALORBRUTO / P.BDVALORTOTAL)) AS NUMERIC(15, 2))
    WHERE P.BDSESSAO = :PRSESSAO AND P.BDVALORRETISSQN > 0;

      /* Caso sobre diferença nas retenções, joga na ultima parcela */
      UPDATE TMP_TPARCELAS_TEMP P
      SET p.bdVALORRETISSQN = p.bdVALORRETISSQN + (p.bdTOTRETISSQN - (SELECT SUM(COALESCE(t.bdVALORRETISSQN,0))
                                                                      FROM TMP_TPARCELAS_TEMP t
                                                                      WHERE t.bdSESSAO = p.bdSESSAO
                                                                        AND t.bdCODEMP = p.bdCODEMP
                                                                        AND t.bdCHAVE  = p.bdCHAVE))
      WHERE P.BDSESSAO = :PRSESSAO
        AND P.BDVALORRETISSQN > 0
        AND p.bdORDEMPAR = (SELECT MAX(x.bdORDEMPAR)
                            FROM TMP_TPARCELAS_TEMP x
                            WHERE x.bdSESSAO = p.bdSESSAO
                              AND x.bdCODEMP = p.bdCODEMP
                              AND x.bdCHAVE  = p.bdCHAVE);
    END

  /*INSS*/
  IF (:wBDRETPARINSS = 'TRUE') THEN
    BEGIN
    UPDATE TMP_TPARCELAS_TEMP P SET P.BDVALORRETINSS = CAST((P.BDVALORRETINSS * (P.BDVALORBRUTO / P.BDVALORTOTAL)) AS NUMERIC(15, 2))
    WHERE P.BDSESSAO = :PRSESSAO AND P.BDVALORRETINSS > 0;
      
      /* Caso sobre diferença nas retenções, joga na ultima parcela */
      UPDATE TMP_TPARCELAS_TEMP P
      SET p.bdVALORRETINSS = p.bdVALORRETINSS + (p.bdTOTRETINSS - (SELECT SUM(COALESCE(t.bdVALORRETINSS,0))
                                                                   FROM TMP_TPARCELAS_TEMP t
                                                                   WHERE t.bdSESSAO = p.bdSESSAO
                                                                     AND t.bdCODEMP = p.bdCODEMP
                                                                     AND t.bdCHAVE  = p.bdCHAVE))
      WHERE P.BDSESSAO = :PRSESSAO
        AND P.BDVALORRETINSS > 0
        AND p.bdORDEMPAR = (SELECT MAX(x.bdORDEMPAR)
                            FROM TMP_TPARCELAS_TEMP x
                            WHERE x.bdSESSAO = p.bdSESSAO
                              AND x.bdCODEMP = p.bdCODEMP
                              AND x.bdCHAVE  = p.bdCHAVE);
    END

  /*FUNRURAL*/
  IF (:WBDRETFUNRURAL = 'TRUE') THEN
    BEGIN
    UPDATE TMP_TPARCELAS_TEMP P SET P.BDVALORRETFUNRURAL = CAST((P.BDVALORRETFUNRURAL * (P.BDVALORBRUTO / P.BDVALORTOTAL)) AS NUMERIC(15, 2))
    WHERE P.BDSESSAO = :PRSESSAO AND P.BDVALORRETFUNRURAL > 0;
      
      /* Caso sobre diferença nas retenções, joga na ultima parcela */
      UPDATE TMP_TPARCELAS_TEMP P
      SET p.bdVALORRETFUNRURAL = p.bdVALORRETFUNRURAL + (p.bdTOTRETFUNRURAL - (SELECT SUM(COALESCE(t.bdVALORRETFUNRURAL,0))
                                                                               FROM TMP_TPARCELAS_TEMP t
                                                                               WHERE t.bdSESSAO = p.bdSESSAO
                                                                                 AND t.bdCODEMP = p.bdCODEMP
                                                                                 AND t.bdCHAVE  = p.bdCHAVE))
      WHERE P.BDSESSAO = :PRSESSAO
        AND P.BDVALORRETFUNRURAL > 0
        AND p.bdORDEMPAR = (SELECT MAX(x.bdORDEMPAR)
                            FROM TMP_TPARCELAS_TEMP x
                            WHERE x.bdSESSAO = p.bdSESSAO
                              AND x.bdCODEMP = p.bdCODEMP
                              AND x.bdCHAVE  = p.bdCHAVE);
    END

  /*Insere na tabela temporaria do parcelamento*/
  wSQL =         'INSERT INTO '||:wTablePar||'(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMPAR, BDCODIGOPLA, BDPARCELAPAR, BDDUPLICATAPAR, ';
  wSQL = :wSQL ||                              'BDVALORPAR, BDDATAVENCTOPAR, BDVALORRETPIS, BDVALORRETCOFINS, BDVALORRETCSLL, ';
  IF (:PRTIPOMOV = 'ENT') THEN                                                                                                  
    wSQL = :wSQL ||                            'BDVALORRETFUNRURAL, ';
  wSQL = :wSQL ||                              'BDVALORRETIRRF, BDVALORRETISSQN, BDVALORRETINSS, BDVALORBRUTO, BDNRDOC) ';
  wSQL = :wSQL || 'SELECT P.BDSESSAO, P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR, ';
  IF (:prPLANOTROCA = 'TRUE') THEN -- Alt.: #122344 - Busca o plano de pagamento selecionado no plano de trocas...
    wSQL = :wSQL ||        ' c.bdCODIGOPLA, ';
  ELSE
    wSQL = :wSQL ||        :wCodigoPla||' BDCODIGOPLA, ';
  wSQL = :wSQL ||        ' P.BDORDEMPAR, P.BDDUPLICATAPAR, ';
  wSQL = :wSQL ||        'P.BDVALOR, P.BDDATAVENCTOPAR, P.BDVALORRETPIS, P.BDVALORRETCOFINS, P.BDVALORRETCSLL, ';
  IF (:PRTIPOMOV = 'ENT') THEN                                                                                                  
    wSQL = :wSQL ||        'P.BDVALORRETFUNRURAL, ';
  wSQL = :wSQL ||        'P.BDVALORRETIRRF,P.BDVALORRETISSQN, P.BDVALORRETINSS, P.BDVALORBRUTO, P.BDDUPLICATAPAR ';
  wSQL = :wSQL || 'FROM TMP_TPARCELAS_TEMP P ';
  IF (:prPLANOTROCA = 'TRUE') THEN
    wSQL = :wSQL || 'LEFT OUTER JOIN TMP_VEF_EMP_TMOVTROCA_CONDPGTO c ON (c.bdCODEMP = p.bdCODEMP AND c.bdCHAVE = p.bdCHAVE) ';
  wSQL = :wSQL || 'WHERE P.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL || 'AND NOT EXISTS (';
  wSQL = :wSQL ||                 'SELECT PAR.BDCHAVE ';
  wSQL = :wSQL ||                 'FROM '||:wTablePar||' PAR ';
  wSQL = :wSQL ||                 'WHERE PAR.BDSESSAO = P.BDSESSAO ';
  wSQL = :wSQL ||                 'AND PAR.BDCODEMP = P.BDCODEMP ';
  wSQL = :wSQL ||                 'AND PAR.BDCHAVE = P.BDCHAVE ';
  IF (:prPLANOTROCA = 'TRUE') THEN -- Alt.: #122344 - Ajustes para inserir todas as parcelas, de todas as ordens...
    wSQL = :wSQL ||                 'AND PAR.bdORDEMPAR = p.bdORDEMPAR ';
  wSQL = :wSQL ||                ') ';
  
  EXECUTE STATEMENT :wSQL;
END
^

CREATE OR ALTER PROCEDURE SP_ATUALIZA_PART_TABLE_DEP (
    PRID_TERMINAL INTEGER,
    PRCODTER INTEGER,
    PRFIELD VARCHAR(20),
    PRVALUE VARCHAR(100))
AS
DECLARE VARIABLE WSESSAO INTEGER;
DECLARE VARIABLE WTABLE VARCHAR(50);
DECLARE VARIABLE WFIELD VARCHAR(250);
DECLARE VARIABLE wFieldAtu VARCHAR(50);
DECLARE VARIABLE wFieldCorr VARCHAR(50);
DECLARE VARIABLE WSQL VARCHAR(250);
DECLARE VARIABLE WQTD INTEGER;
BEGIN
  /*Sol: 14207 Patrick T. Sá 16/12/2016.
    Esta sp atualiza o campo cpf/cnpj em outra tabela.
    Exemplo: Ao alterar CPF/CNPJ no cadastro de participante,
    todas as tabelas que tem o participante precisam receber o novo CPF/CNPJ
  */
  PRFIELD = TRIM(IIF(UPPER(:PRFIELD) = 'BDCGCTER', 'BDCNPJ', UPPER(:PRFIELD)));

  FOR SELECT TRIM(T.RDB$RELATION_NAME) BDTABLE, S.BDSESSAO, LIST(TRIM(RDB$FIELD_NAME), ',')||',' BDFIELD
      FROM RDB$RELATION_FIELDS T
      JOIN TMP_TSESSAO_IMP S ON(S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = TRIM(T.RDB$RELATION_NAME))
      WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
      AND RDB$FIELD_NAME LIKE 'BDCODTER%'
      GROUP BY BDTABLE, S.BDSESSAO
      INTO :wTable, :wSessao, :wField
  DO
    BEGIN
      wQtd = SETFIELDS_TER((SELECT LIST(TRIM(RDB$FIELD_NAME), ',')||',' BDFIELD
                            FROM RDB$RELATION_FIELDS T
                            JOIN TMP_TSESSAO_IMP S ON(S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = TRIM(T.RDB$RELATION_NAME))
                            WHERE RDB$RELATION_NAME = :wTable
                            AND ((RDB$FIELD_NAME LIKE 'BDCODTER%') OR (RDB$FIELD_NAME LIKE :PRFIELD||'%'))));

      WHILE (wQtd > 0) DO
        BEGIN
          wFieldCorr = NULL;
          wFieldAtu  = SUBSTRING(:wField FROM 1 FOR POSITION(',', :wField)-1);
          wField     = REPLACE(:wField, :wFieldAtu||',', '');

          wFieldCorr = GETFIELDS_TER(:wFieldAtu);
          IF ((:wFieldCorr IS NULL) OR (:wFieldCorr = '')) THEN
            wFieldCorr = :PRFIELD;

          wSQL = 'UPDATE '||:wTable||' SET ';
          wSQL = :wSQL || :wFieldCorr || ' = ' || ''''||:PRVALUE||'''';
          wSQL = :wSQL || ' WHERE BDSESSAO = '||:wSessao;
          wSQL = :wSQL || ' AND '||:wFieldAtu||' = '||:PRCODTER;
          EXECUTE STATEMENT :wSQL;
          wQtd = :wQtd - 1;
        END

      wSessao = NULL;
    END
END^

COMMENT ON PARAMETER SP_GERAR_PARCELAS_AUT.PRTIPOMOV IS 'ENT/SAI/SER'^
--Sol: 15461 - FIM

CREATE OR ALTER TRIGGER tmp_vef_emp_tmovsaisn_temp_bi0 FOR tmp_vef_emp_tmovsaisn_temp
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vchave INTEGER;
  DECLARE VARIABLE vordem INTEGER;
  DECLARE VARIABLE vChavesn INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdchavesn IS NULL) OR (NEW.bdchavesn = 0)) THEN
    BEGIN
      IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDCHAVE)), 1) FROM tmp_vef_emp_TMOVSAIitens_temp WHERE (bdsessao = NEW.bdsessao) AND (bdcodemp = NEW.bdcodemp) INTO vchave;
          NEW.BDCHAVE = vchave;
        END

      IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
        BEGIN
          SELECT COALESCE((MAX(BDORDEM)), 1) FROM tmp_vef_emp_TMOVSAIitens_temp WHERE (bdsessao = NEW.bdsessao) AND (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
          NEW.bdordem = vordem;
        END

       SELECT COALESCE((MAX(bdchavesn)+1), 1) FROM tmp_vef_emp_TMOVSAIsn_temp
       WHERE (bdsessao = NEW.bdsessao) AND (bdcodemp = NEW.bdcodemp) AND (bdChave = NEW.bdchave) AND (bdOrdem = NEW.bdordem) INTO vChavesn;

       NEW.bdchavesn = vChavesn;
    END
  ELSE
    BEGIN
       IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)), 1) FROM tmp_vef_emp_TMOVSAIitens_temp WHERE (bdsessao = NEW.bdsessao) AND (bdcodemp = NEW.bdcodemp) INTO vchave;
           NEW.BDCHAVE = vchave;
         END

       IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
         BEGIN
           SELECT COALESCE((MAX(BDORDEM)), 1) FROM tmp_vef_emp_TMOVSAIitens_temp WHERE (bdsessao = NEW.bdsessao) AND (bdcodemp = NEW.bdcodemp) AND (bdchave = NEW.bdchave) INTO vordem;
           NEW.bdordem = vordem;
         END

       SELECT bdchavesn FROM tmp_vef_emp_TMOVSAIsn_temp
       WHERE (bdsessao = NEW.bdsessao) AND (bdchavesn = NEW.bdchavesn) AND (bdOrdem = NEW.bdordem) AND (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchavesn)+1), 1) FROM tmp_vef_emp_TMOVSAIsn_temp
           WHERE (bdsessao = NEW.bdsessao)
           AND (bdcodemp = NEW.bdcodemp)
           AND (bdChave = NEW.bdchave)
           AND (bdOrdem = NEW.bdordem) INTO vChavesn;
           NEW.bdchavesn = vChavesn;
         END

    END
END^

CREATE OR ALTER trigger vfin_base_tselserv_bi0 for vfin_base_tselserv
active before insert position 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM VFIN_BASE_TCADSELSERV order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0);
  end
END^


CREATE OR ALTER trigger vfin_base_tcadselserv_bi0 for vfin_base_tcadselserv
active before insert position 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM VFIN_BASE_TCADSELSERV order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0) + 1;
  end
END^

CREATE OR ALTER trigger vfin_base_tcadselcli_bi0 for vfin_base_tcadselcli
active before insert position 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM VFIN_BASE_TCADSELCLI order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0) + 1;
  end
END^

CREATE OR ALTER trigger vfin_base_tselcli_bi0 for vfin_base_tselcli
active before insert position 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM VFIN_BASE_TCADSELCLI order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0);
  end
END^

CREATE OR ALTER trigger vfin_base_tcadselfor_bi0 for vfin_base_tcadselfor
active before insert position 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM VFIN_BASE_TCADSELFOR order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0) + 1;
  end
END^

CREATE OR ALTER trigger vfin_base_tselfor_bi0 for vfin_base_tselfor
active before insert position 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM VFIN_BASE_TCADSELFOR order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0);
  end
END^

CREATE OR ALTER trigger vfin_base_tcadseldesp_bi0 for vfin_base_tcadseldesp
active before insert position 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM VFIN_BASE_TCADSELDESP order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0) + 1;
    end
END^

CREATE OR ALTER trigger vfin_base_tseldesp_bi0 for vfin_base_tseldesp
active before insert position 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM VFIN_BASE_TCADSELDESP order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0);
  end
END^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVENTE115_AD0 FOR TOL_VEF_EMP_TMOVENTE115
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  /* Trigger text */
  DELETE FROM VEF_EMP_TAJUICMSE115 e115 WHERE e115.BDCODEMP = OLD.BDCODEMP AND e115.BDORDEME115 = OLD.BDORDEME115;
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVSAIE115_AD0 FOR TOL_VEF_EMP_TMOVSAIE115
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  /* Trigger text */
  DELETE FROM VEF_EMP_TAJUICMSE115 e115 WHERE e115.BDCODEMP = OLD.BDCODEMP AND e115.BDORDEME115 = OLD.BDORDEME115;
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TREDZE115_AD0 FOR TOL_VEF_EMP_TREDZE115
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  /* Trigger text */
  DELETE FROM VEF_EMP_TAJUICMSE115 e115 WHERE e115.BDCODEMP = OLD.BDCODEMP AND e115.BDORDEME115 = OLD.BDORDEME115;
END
^

create or alter procedure SP_ATUALIZAR_TMP_BLOCO1100 (
    PRSESSAO integer,
    PRULTCHAVE integer,
    PRIDTERMINAL integer)
as
declare variable WSESSAOPRO integer;
begin

  DELETE FROM VEF_INCON_TBLOCO1100 K WHERE K.BDSESSAO = :PRSESSAO AND ((K.BDCHAVE IS NOT NULL) AND (K.BDCHAVE > 0));

  /* Procedure Text */
  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVEXP_TEMP K SET K.BDEDITCHAVE = :PRULTCHAVE WHERE K.BDSESSAO = :PRSESSAO;

/* Lançamento já existente na base de dados */
  INSERT INTO VEF_INCON_TBLOCO1100(BDCODEMP, BDSESSAO, BDCHAVE, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVEXP_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO and exists ( Select * from VEF_EMP_TMOVEXP L
                                            where L.BDCODEMP = K.BDCODEMP AND L.BDNUMDECLARACAO = K.BDNUMDECLARACAO);


/* Número da declaração obrigatório */
  INSERT INTO VEF_INCON_TBLOCO1100(BDCODEMP, BDSESSAO, BDCHAVE, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 205 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVEXP_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO and K.BDNUMDECLARACAO IS NULL;


/* Tipo conhecimento obrigatório */
  INSERT INTO VEF_INCON_TBLOCO1100(BDCODEMP, BDSESSAO, BDCHAVE, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 206 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVEXP_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO and K.BDORDEMDOCCARGA IS NULL;

/* Tipo conhecimento obrigatório */
  INSERT INTO VEF_INCON_TBLOCO1100(BDCODEMP, BDSESSAO, BDCHAVE, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 209 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVEXP_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO AND NOT EXISTS(SELECT A.BDORDEMDOCCARGA FROM VEF_BASE_TTABTIPODOCCARGA A WHERE K.BDORDEMDOCCARGA = A.BDORDEMDOCCARGA);


/* País não existente ou inválido. */
  INSERT INTO VEF_INCON_TBLOCO1100(BDCODEMP, BDSESSAO, BDCHAVE, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 119 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVEXP_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO and (K.BDCODPAIS IS NULL or K.BDCODPAIS = 0);

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRIDTERMINAL
  AND S.BDTABLE = 'TMP_TCADPRO_TEMP'
  INTO :wSessaoPro;



  /* ------ começo 1105 ------ */
  /*87 - Produto não informado ou inconsistente. */
  INSERT INTO VEF_INCON_TBLOCO1100(BDCODEMP, BDSESSAO, BDCHAVE, BDORDEM, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM , 87 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVEXPNFSAI_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDCODPROD IS NULL) OR (K.BDCODPROD = 0));

  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TBLOCO1100(BDCODEMP, BDSESSAO, BDCHAVE, BDORDEM, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVEXPNFSAI_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, BDCODINCONSISTENCIA;

  /* 208 - Modelo inválido para esse registro*/
  INSERT INTO VEF_INCON_TBLOCO1100(BDCODEMP, BDSESSAO, BDCHAVE, BDORDEM, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM , 208 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVEXPNFSAI_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO and K.BDMODELO NOT IN ('1', '55');

  /* 207 - Chave NFE obrigatório para esse modelo*/
  INSERT INTO VEF_INCON_TBLOCO1100(BDCODEMP, BDSESSAO, BDCHAVE, BDORDEM, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM , 207 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVEXPNFSAI_TEMP K
  WHERE (K.BDSESSAO = :PRSESSAO) and ((K.BDMODELO = 55) AND ((K.BDCHAVENFE IS NULL) or (K.BDCHAVENFE = '')));
  /* ------ fim 1105 ------ */




  /* ------ começo Lançamento operações de exportação indireta (registro 1110) ------ */
  /*17 - Participante não informado*/
  INSERT INTO VEF_INCON_TBLOCO1100(BDCODEMP, BDSESSAO, BDCHAVE, BDORDEM, BDORDEMDED, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, K.BDORDEMED, 17 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVEXPINDIRETA_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODTER IS NULL) OR (K.BDALTCODTER = 0));

  /*74 - Participante inconsistente*/
  INSERT INTO VEF_INCON_TBLOCO1100(BDCODEMP, BDSESSAO, BDCHAVE, BDORDEM, BDORDEMDED, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, K.BDORDEMED, 74 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVEXPINDIRETA_TEMP K
  JOIN TMP_TTERCEIRO T ON(T.BDEDITCHAVE = K.BDALTCODTER AND T.BDINCONSISTENTE IS NOT NULL AND T.BDINCONSISTENTE NOT IN(0, 2))
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODTER IS NOT NULL) AND (K.BDALTCODTER > 0))
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, K.BDORDEMED, BDCODINCONSISTENCIA;

  /* 208 - Modelo inválido para esse registro*/
  INSERT INTO VEF_INCON_TBLOCO1100(BDCODEMP, BDSESSAO, BDCHAVE, BDORDEM, BDORDEMDED, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, K.BDORDEMED , 208 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVEXPINDIRETA_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO and K.BDMODELO NOT IN ('1', '1B', '4', '55');

  /* 207 - Chave NFE obrigatório para esse modelo*/
  INSERT INTO VEF_INCON_TBLOCO1100(BDCODEMP, BDSESSAO, BDCHAVE, BDORDEM, BDORDEMDED, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, K.BDORDEMED , 207 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVEXPINDIRETA_TEMP K
  WHERE (K.BDSESSAO = :PRSESSAO) and ((K.BDMODELO = 55) AND ((K.BDCHAVENFE IS NULL) or (K.BDCHAVENFE = '')));


  /* 210 - Unidade de medida obrigatório*/
  INSERT INTO VEF_INCON_TBLOCO1100(BDCODEMP, BDSESSAO, BDCHAVE, BDORDEM, BDORDEMDED, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, K.BDORDEMED , 210 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVEXPINDIRETA_TEMP K
  WHERE (K.BDSESSAO = :PRSESSAO) and (K.BDCODUNIMED IS NULL);


  /* ------ Fim Lançamento operações de exportação indireta (registro 1110) ------ */

end^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_RENDDIRF (
    PRSESSAO integer,
    PRULTCHAVE integer,
    PRIDTERMINAL integer)
as
declare variable WSESSAOPRO integer;
BEGIN
  DELETE FROM VEF_INCON_TMOVDECRENDDIRF D WHERE D.BDSESSAO = :PRSESSAO AND ((D.BDCHAVE IS NOT NULL) AND (D.BDCHAVE > 0));

  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVDECRENDDIRF_TEMP D SET D.BDEDITCHAVE = :PRULTCHAVE WHERE D.BDSESSAO = :PRSESSAO;

  /*17 - Participante não informado*/
  INSERT INTO VEF_INCON_TMOVDECRENDDIRF(BDCODEMP, BDSESSAO, BDCHAVE, BDCODINCONSISTENCIA)
  SELECT D.BDCODEMP, D.BDSESSAO, D.BDCHAVE, 17 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVDECRENDDIRF_TEMP D
  WHERE D.BDSESSAO = :PRSESSAO
  AND ((D.BDCODTER IS NULL) OR (D.BDCODTER = 0));

  /*189 - Código de receita não informado - comentado este trecho pois o campo de código de receita não é mais obrigatório
  INSERT INTO VEF_INCON_TMOVDECRENDDIRF(BDCODEMP, BDSESSAO, BDCHAVE, BDCODINCONSISTENCIA)
  SELECT D.BDCODEMP, D.BDSESSAO, D.BDCHAVE, 189 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVDECRENDDIRF_TEMP D
  WHERE D.BDSESSAO = :PRSESSAO
  AND ((D.BDCODREC IS NULL) OR (D.BDCODREC = 0));*/

END^

create or alter procedure SP_ATUALIZAR_TMP_BLOCOK200 (
    PRSESSAO integer,
    PRULTCHAVE integer,
    PRIDTERMINAL integer)
as
declare variable WSESSAOPRO integer;
BEGIN
  DELETE FROM VEF_INCON_TMOVBLOCOK K WHERE K.BDSESSAO = :PRSESSAO AND ((K.BDCHAVEK200 IS NOT NULL) AND (K.BDCHAVEK200 > 0));

  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVK200_TEMP K SET K.BDEDITCHAVE = :PRULTCHAVE WHERE K.BDSESSAO = :PRSESSAO;

  /*87 - Produto não informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK200, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 87 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK200_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NULL) OR (K.BDALTCODPROD = 0));

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRIDTERMINAL
  AND S.BDTABLE = 'TMP_TCADPRO_TEMP'
  INTO :wSessaoPro;

  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK200, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK200_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA;

  /*22 - Lançamento já existente na base de dados*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK200, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK200_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND EXISTS(
             SELECT K200.BDCHAVE
             FROM VEF_EMP_TMOVK200 K200
             WHERE K200.BDCODEMP = K.BDCODEMP
             AND K200.BDDATAESTFIM = K.BDDATAESTFIM
             AND K200.BDCODPOSSE = K.BDCODPOSSE
             AND K200.BDCODPROD = K.BDALTCODPROD             
            );

  /*88 - A Quantidade deve ser informada.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK200, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 88 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK200_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDQTDESTOQUE <= 0;

  /*17 - Participante não informado*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK200, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 17 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK200_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDCODPOSSE IN(2, 3)
  AND ((K.BDALTCODTER IS NULL) OR (K.BDALTCODTER = 0));

  /*89 - O código SPED do item informado deve ser 00, 01, 02, 03, 04, 05, 06 ou 10*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK200, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 89 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK200_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDTIPOITEM IN(1, 2, 3, 4, 5, 6, 7, 11);
  
  /*74 - Participante inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK200, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 74 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK200_TEMP K
  JOIN TMP_TTERCEIRO T ON(T.BDEDITCHAVE = K.BDALTCODTER AND T.BDINCONSISTENTE IS NOT NULL AND T.BDINCONSISTENTE NOT IN(0, 2))
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODTER IS NOT NULL) AND (K.BDALTCODTER > 0))
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA; 

  /*192 - Código posse está inválido*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK200, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 192 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK200_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDCODPOSSE NOT IN(1, 2, 3);
  
END^

CREATE OR ALTER TRIGGER tmp_vef_emp_tmovk200_temp_gk FOR tmp_vef_emp_tmovk200_temp
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  IF ((OLD.BDEDITCHAVE IS NULL) AND (NEW.BDEDITCHAVE > 0)) THEN
    BEGIN
      NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - OLD.BDCHAVE)+1;
    END
END^

CREATE OR ALTER TRIGGER TMP_VEF_EMP_TMOVK200_TEMP_BI0 FOR TMP_VEF_EMP_TMOVK200_TEMP
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
  IF ( ((NEW.BDEDITCHAVE IS NULL) OR (NEW.BDEDITCHAVE = 0)) AND ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) AND (NEW.bdchaveaux > 0)) THEN
    BEGIN
        vCodigo = 0;
        SELECT COALESCE(MAX((BDCHAVE)+1), NEW.bdchaveaux) FROM TMP_VEF_EMP_TMOVK200_TEMP INTO vCodigo;
        NEW.BDCHAVE = vCodigo;
        NEW.BDEDITCHAVE = vCodigo;
    END
END^

CREATE OR ALTER PROCEDURE SP_UPDATE_K220 (
    PRID_TERMINAL INTEGER)
AS
DECLARE VARIABLE WSESSAOK220 INTEGER;
DECLARE VARIABLE WSESSAOPRO INTEGER;
BEGIN
  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = 'TMP_TCADPRO_TEMP' INTO :wSessaoPro;
  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = 'TMP_VEF_EMP_TMOVESTK220_TEMP' INTO :wSessaoK220;

  /*Desvincula todos os produtos*/
  UPDATE TMP_VEF_EMP_TMOVESTK220_TEMP T SET T.BDCODPRODDEST = NULL, T.BDDESCPRODDEST = NULL WHERE T.BDSESSAO = :wSessaoK220;
    
  /*1 - Busca os produtos na tabela TEMP, contém os registros que estão sendo importados*/
  UPDATE TMP_VEF_EMP_TMOVESTK220_TEMP T
  SET T.BDALTCODPRODDEST = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :wSessaoPro AND P.BDCODSAIDA = T.BDCODSAIDADEST),
      T.BDDESCPRODDEST = (
                          SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                          FROM TMP_TCADPRO_TEMP P
                          WHERE P.BDSESSAO = :wSessaoPro
                          AND P.BDCODSAIDA = T.BDCODSAIDADEST
                         )
  WHERE T.BDSESSAO = :wSessaoK220
  AND ((T.BDCODSAIDADEST IS NOT NULL) AND (T.BDCODSAIDADEST <> ''));
    
  /*2 - Busca os produtos na tabela TMP, contém todos os registros de produto do banco*/
  UPDATE TMP_VEF_EMP_TMOVESTK220_TEMP T
  SET T.BDALTCODPRODDEST = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO P WHERE P.BDCODEMP = T.BDCODEMP AND P.BDCODSAIDA = T.BDCODSAIDADEST),
      T.BDDESCPRODDEST = (
                          SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                          FROM TMP_TCADPRO P
                          WHERE P.BDCODEMP = T.BDCODEMP
                          AND P.BDCODSAIDA = T.BDCODSAIDADEST
                         )
  WHERE T.BDSESSAO = :wSessaoK220
  AND T.BDALTCODPRODDEST IS NULL
  AND ((T.BDCODSAIDADEST IS NOT NULL) AND (T.BDCODSAIDADEST <> ''));

  /*Apenas joga o altcodprod para o bdcodprod*/
  UPDATE TMP_VEF_EMP_TMOVESTK220_TEMP T SET T.BDCODPRODDEST = T.BDALTCODPRODDEST
  WHERE T.BDSESSAO = :wSessaoK220
  AND T.BDALTCODPRODDEST IS NOT NULL;
END^

CREATE OR ALTER TRIGGER tmp_vef_emp_tmovestk220_temp_gk FOR tmp_vef_emp_tmovestk220_temp
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  IF ((OLD.BDEDITCHAVE IS NULL) AND (NEW.BDEDITCHAVE > 0)) THEN
    BEGIN
      NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - OLD.BDCHAVE)+1;
    END
END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK220 (
    PRSESSAO INTEGER,
    PRULTCHAVE INTEGER,
    PRIDTERMINAL INTEGER)
AS
DECLARE VARIABLE WSESSAOPRO INTEGER;
BEGIN
  DELETE FROM VEF_INCON_TMOVBLOCOK K WHERE K.BDSESSAO = :PRSESSAO AND ((K.BDCHAVEK220 IS NOT NULL) AND (K.BDCHAVEK220 > 0));

  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVESTK220_TEMP K SET K.BDEDITCHAVE = :PRULTCHAVE WHERE K.BDSESSAO = :PRSESSAO;

  /*22 - Lançamento já existente na base de dados*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK220, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVESTK220_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND EXISTS(
             SELECT K220.BDCHAVE
             FROM VEF_EMP_TMOVESTOQUEK220 K220
             WHERE K220.BDCODEMP = K.BDCODEMP
             AND K220.BDDATAMOV = K.BDDATAMOV
             AND K220.BDCODPRODORI = K.BDALTCODPROD
             AND K220.BDCODPRODDEST = K.BDALTCODPRODDEST
            );

  /*90 - O produto de origem não informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK220, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 90 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVESTK220_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NULL) OR (K.BDALTCODPROD = 0));

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRIDTERMINAL
  AND S.BDTABLE = 'TMP_TCADPRO_TEMP'
  INTO :wSessaoPro;

  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK220, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVESTK220_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA;

  /*91 - O produto de destino não informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK220, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 91 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVESTK220_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPRODDEST IS NULL) OR (K.BDALTCODPRODDEST = 0));

  /*76 - Produto inconsistente - Produto de destino*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK220, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVESTK220_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPRODDEST)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPRODDEST IS NOT NULL) AND (K.BDALTCODPRODDEST > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA;

  /*88 - A Quantidade deve ser informada.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK220, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 88 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVESTK220_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDQTDMOV <= 0;

  /*127 - A Quantidade destino deve ser informada.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK220, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 127 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVESTK220_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDQTDDEST <= 0) AND (K.BDDATAMOV >= '01/01/2018'));

END^

CREATE OR ALTER TRIGGER tmp_vef_emp_tmovk230_k250_gk FOR tmp_vef_emp_tmovk230_k250_temp
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  IF ((OLD.BDEDITCHAVE IS NULL) AND (NEW.BDEDITCHAVE > 0)) THEN
    BEGIN
      NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - OLD.BDCHAVE)+1;
    END
END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK235K255 (
    PRSESSAO INTEGER,
    PRID_TERMINAL INTEGER)
AS
DECLARE VARIABLE WSESSAOPRO INTEGER;
BEGIN
  /*BDCODREG = 0 - K235
               1 - K255*/
  DELETE FROM VEF_INCON_TMOVBLOCOK I WHERE I.BDSESSAO = :PRSESSAO AND ((I.BDORDEMK235 IS NOT NULL) OR (I.BDORDEMK255 IS NOT NULL));               

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = 'TMP_TCADPRO_INSUMOS_TEMP' INTO :wSessaoPro;

  /*67 - Código do produto insumo não informado!*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, IIF(K.BDCODREG = 0, K.BDCHAVE, NULL) BDCHAVEK230, IIF(K.BDCODREG = 1, K.BDCHAVE, NULL) BDCHAVEK250,
         IIF(K.BDCODREG = 0, K.BDORDEM, NULL) BDORDEMK235, IIF(K.BDCODREG = 1, K.BDORDEM, NULL) BDORDEMK255,
         67 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVINK235K255_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NULL) OR (K.BDALTCODPROD = 0))
  AND K.BDDATASAIDA < '01/01/2022'; /*#alt:Sped Fiscal - 0210 alteração 2022 - 07/12/2021 - Guilherme Vargas */

  /*76 - Produto inconsistente - insumo*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, IIF(K.BDCODREG = 0, K.BDCHAVE, NULL) BDCHAVEK230, IIF(K.BDCODREG = 1, K.BDCHAVE, NULL) BDCHAVEK250,
         IIF(K.BDCODREG = 0, K.BDORDEM, NULL) BDORDEMK235, IIF(K.BDCODREG = 1, K.BDORDEM, NULL) BDORDEMK255,
         76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVINK235K255_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  AND K.BDDATASAIDA < '01/01/2022' /*#alt:Sped Fiscal - 0210 alteração 2022 - 07/12/2021 - Guilherme Vargas */
  GROUP BY K.BDCODEMP, K.BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA;

  /*111 - Produto substituto inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, IIF(K.BDCODREG = 0, K.BDCHAVE, NULL) BDCHAVEK230, IIF(K.BDCODREG = 1, K.BDCHAVE, NULL) BDCHAVEK250,
         IIF(K.BDCODREG = 0, K.BDORDEM, NULL) BDORDEMK235, IIF(K.BDCODREG = 1, K.BDORDEM, NULL) BDORDEMK255,
         111 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVINK235K255_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPRODSUB)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPRODSUB IS NOT NULL) AND (K.BDALTCODPRODSUB > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA;

  /*88 - A Quantidade deve ser informada.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, IIF(K.BDCODREG = 0, K.BDCHAVE, NULL) BDCHAVEK230, IIF(K.BDCODREG = 1, K.BDCHAVE, NULL) BDCHAVEK250,
         IIF(K.BDCODREG = 0, K.BDORDEM, NULL) BDORDEMK235, IIF(K.BDCODREG = 1, K.BDORDEM, NULL) BDORDEMK255,
         88 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVINK235K255_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDQTDCONSUMIDA <= 0;

  /*96 - O substituto deve constar no cadastro de insumo.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, IIF(K.BDCODREG = 0, K.BDCHAVE, NULL) BDCHAVEK230, IIF(K.BDCODREG = 1, K.BDCHAVE, NULL) BDCHAVEK250,
         IIF(K.BDCODREG = 0, K.BDORDEM, NULL) BDORDEMK235, IIF(K.BDCODREG = 1, K.BDORDEM, NULL) BDORDEMK255,
         96 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVINK235K255_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDCODSAIDASUB IS NOT NULL) AND (K.BDCODSAIDASUB <> ''))
  AND K.BDDATASAIDA < '01/01/2022' /*#alt:Sped Fiscal - 0210 alteração 2022 - 07/12/2021 - Guilherme Vargas */
  AND NOT EXISTS(
                 /*Seleciona os insumos que estão consistentes*/
                 SELECT I.BDCODPROD
                 FROM TMP_TCADPRO_INSUMOS_TEMP I
                 WHERE I.BDSESSAO = :wSessaoPro
                 AND NOT EXISTS(
                                SELECT INCO.BDCODSAIDA
                                FROM VEF_INCON_TCADPRO_INSUMO INCO
                                WHERE INCO.BDSESSAO = I.BDSESSAO
                                AND INCO.BDCODEMP = I.BDCODEMP
                                AND INCO.BDCODSAIDA = I.BDCODSAIDA
                                AND INCO.BDORDEM = INCO.BDORDEM
                               )
                 AND I.BDCODSAIDAPROD = K.BDCODSAIDASUB
                );

  /********************************************************K235********************************************************/
  /*97 - Insumo ou substituto igual ao produto.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, IIF(K.BDCODREG = 0, K.BDCHAVE, NULL) BDCHAVEK230, IIF(K.BDCODREG = 1, K.BDCHAVE, NULL) BDCHAVEK250,
         IIF(K.BDCODREG = 0, K.BDORDEM, NULL) BDORDEMK235, IIF(K.BDCODREG = 1, K.BDORDEM, NULL) BDORDEMK255,
         97 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVINK235K255_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDCODREG = 0 /*K235*/
  AND ((K.BDCODSAIDA = K.BDCODSAIDAK230K250) OR (K.BDCODSAIDASUB = K.BDCODSAIDAK230K250)) ;

  /*98 - Data de saída é obrigatória.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, IIF(K.BDCODREG = 0, K.BDCHAVE, NULL) BDCHAVEK230, IIF(K.BDCODREG = 1, K.BDCHAVE, NULL) BDCHAVEK250,
         IIF(K.BDCODREG = 0, K.BDORDEM, NULL) BDORDEMK235, IIF(K.BDCODREG = 1, K.BDORDEM, NULL) BDORDEMK255,
         98 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVINK235K255_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDCODREG = 0 /*K235*/
  AND K.BDDATASAIDA IS NULL;

  /********************************************************K255********************************************************/
  /*99 - Insumo não pode ser igual ao item produzido.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDORDEMK235, BDORDEMK255, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, IIF(K.BDCODREG = 0, K.BDCHAVE, NULL) BDCHAVEK230, IIF(K.BDCODREG = 1, K.BDCHAVE, NULL) BDCHAVEK250,
         IIF(K.BDCODREG = 0, K.BDORDEM, NULL) BDORDEMK235, IIF(K.BDCODREG = 1, K.BDORDEM, NULL) BDORDEMK255,
         99 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVINK235K255_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDCODREG = 1 /*K255*/
  AND K.BDCODSAIDA = K.BDCODSAIDAK230K250;
END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK230K250 (
    PRSESSAO INTEGER,
    PRULTCHAVE INTEGER,
    PRID_TERMINAL INTEGER)
AS
DECLARE VARIABLE WSESSAOPRO INTEGER;
BEGIN
  DELETE FROM VEF_INCON_TMOVBLOCOK K WHERE K.BDSESSAO = :PRSESSAO
  AND (((K.BDCHAVEK230 IS NOT NULL) AND (K.BDCHAVEK230 > 0)) OR ((K.BDCHAVEK250 IS NOT NULL) AND (K.BDCHAVEK250 > 0)));

  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVK230_K250_TEMP K SET K.BDEDITCHAVE = :PRULTCHAVE WHERE K.BDSESSAO = :PRSESSAO;

  /***************************************************K230************************************************************/
  /*22 - Lançamento já existente na base de dados*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, MOV.BDCHAVE, MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA,
               K.BDALTCODPROD, K.BDORDEMPROD
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDINDUSTRIALIZADOCAO = 0 /*K230*/
       ) MOV
  WHERE EXISTS(
               SELECT F.BDCHAVE FROM VEF_EMP_TMOVK230_K250 F
               WHERE F.BDCODEMP = MOV.BDCODEMP
               AND F.BDCODPROD = MOV.BDALTCODPROD
               AND F.BDORDEMPROD = MOV.BDORDEMPROD
              );

  /*92 - Data de início da produção deve ser informada.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, MOV.BDCHAVE, MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 92 BDCODINCONSISTENCIA,
               K.BDDATAPRODINI
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDINDUSTRIALIZADOCAO = 0 /*K230*/
       ) MOV
  WHERE MOV.BDDATAPRODINI IS NULL;

  /*93 - Data de início da produção deve ser menor ou igual a data de fim da produção.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, MOV.BDCHAVE, MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 93 BDCODINCONSISTENCIA,
               K.BDDATAPRODINI, K.BDDATAPRODFIN
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDINDUSTRIALIZADOCAO = 0 /*K230*/
       ) MOV
  WHERE MOV.BDDATAPRODFIN IS NOT NULL
  AND MOV.BDDATAPRODINI IS NOT NULL
  AND MOV.BDDATAPRODINI > MOV.BDDATAPRODFIN;

  /*94 - A ordem de produção deve ter no máximo 30 caracteres.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, MOV.BDCHAVE, MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 94 BDCODINCONSISTENCIA,
               COALESCE(CHAR_LENGTH(TRIM(K.BDORDEMPROD)), 0) BDQTDCARAC
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDINDUSTRIALIZADOCAO = 0 /*K230*/
       ) MOV
  WHERE MOV.BDQTDCARAC > 30;

  /***************************************************K250************************************************************/
  /*22 - Lançamento já existente na base de dados*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK250, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, MOV.BDCHAVE, MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA,
               K.BDALTCODPROD, K.BDDATAPRODINI
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDINDUSTRIALIZADOCAO = 1 /*K250*/
       ) MOV
  WHERE EXISTS(
               SELECT F.BDCHAVE FROM VEF_EMP_TMOVK230_K250 F
               WHERE F.BDCODEMP = MOV.BDCODEMP
               AND F.BDCODPROD = MOV.BDALTCODPROD
               AND F.BDDATAPRODINI = MOV.BDDATAPRODINI
              );

  /***********************************************K230 E K250*********************************************************/
  /*BDINDUSTRIALIZADOCAO = 0 então é K230, = 1 é K250*/

  /*87 - Produto não informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, IIF(MOV.BDTIPOREG = 0, MOV.BDCHAVE, NULL), IIF(MOV.BDTIPOREG = 1, MOV.BDCHAVE, NULL),
         MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 87 BDCODINCONSISTENCIA,
               K.BDALTCODPROD, K.BDINDUSTRIALIZADOCAO BDTIPOREG
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
       ) MOV
  WHERE ((MOV.BDALTCODPROD IS NULL) OR (MOV.BDALTCODPROD = 0));

  /*88 - A Quantidade deve ser informada.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, IIF(MOV.BDTIPOREG = 0, MOV.BDCHAVE, NULL), IIF(MOV.BDTIPOREG = 1, MOV.BDCHAVE, NULL),
         MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 88 BDCODINCONSISTENCIA,
               K.BDQTDPROD, K.BDINDUSTRIALIZADOCAO BDTIPOREG
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
       ) MOV
  WHERE ((MOV.BDQTDPROD IS NULL) OR (MOV.BDQTDPROD = 0));

  /*95 - O código de item SPED deve ser 03 ou 04.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, IIF(MOV.BDTIPOREG = 0, MOV.BDCHAVE, NULL), IIF(MOV.BDTIPOREG = 1, MOV.BDCHAVE, NULL),
         MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 95 BDCODINCONSISTENCIA,
               K.BDCODTIPOSER, K.BDINDUSTRIALIZADOCAO BDTIPOREG
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
       ) MOV
  WHERE MOV.BDCODTIPOSER NOT IN(4, 5);

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRID_TERMINAL
  AND S.BDTABLE = 'TMP_TCADPRO_TEMP'
  INTO :wSessaoPro;

  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK230, BDCHAVEK250, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, IIF(MOV.BDTIPOREG = 0, MOV.BDCHAVE, NULL), IIF(MOV.BDTIPOREG = 1, MOV.BDCHAVE, NULL),
         MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 76 BDCODINCONSISTENCIA, K.BDINDUSTRIALIZADOCAO BDTIPOREG
        FROM TMP_VEF_EMP_TMOVK230_K250_TEMP K
        LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
        WHERE K.BDSESSAO = :PRSESSAO
        AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
        AND PRO.BDCODINCONSISTENCIA IS NOT NULL
        GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA, BDTIPOREG
       ) MOV;

  EXECUTE PROCEDURE SP_ATUALIZAR_CAMPO_CHAVE_TEMP(:PRSESSAO, 'TMP_VEF_EMP_TMOVK230_K250_TEMP');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_BLOCOK235K255(:PRSESSAO, :PRID_TERMINAL);
END^

CREATE OR ALTER PROCEDURE SP_UPDATE_K235K255 (
    PRID_TERMINAL INTEGER)
AS
DECLARE VARIABLE WSESSAOPRO INTEGER;
DECLARE VARIABLE WSESSAOK235K255 INTEGER;
BEGIN
  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = 'TMP_TCADPRO_TEMP' INTO :wSessaoPro;
  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = 'TMP_VEF_EMP_TMOVINK235K255_TEMP' INTO :wSessaoK235K255;

  /*Desvincula todos os produtos*/
  UPDATE TMP_VEF_EMP_TMOVINK235K255_TEMP T SET T.BDCODPRODSUB = NULL, T.BDDESCPRODSUB = NULL WHERE T.BDSESSAO = :wSessaoK235K255;
    
  /*1 - Busca os produtos na tabela TEMP, contém os registros que estão sendo importados*/
  UPDATE TMP_VEF_EMP_TMOVINK235K255_TEMP T
  SET T.BDALTCODPRODSUB = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :wSessaoPro AND P.BDCODSAIDA = T.BDCODSAIDASUB),
      T.BDDESCPRODSUB = (
                         SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                         FROM TMP_TCADPRO_TEMP P
                         WHERE P.BDSESSAO = :wSessaoPro
                         AND P.BDCODSAIDA = T.BDCODSAIDASUB
                        )
  WHERE T.BDSESSAO = :wSessaoK235K255
  AND ((T.BDCODSAIDASUB IS NOT NULL) AND (T.BDCODSAIDASUB <> ''));
    
  /*2 - Busca os produtos na tabela TMP, contém todos os registros de produto do banco*/
  UPDATE TMP_VEF_EMP_TMOVINK235K255_TEMP T
  SET T.BDALTCODPRODSUB = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO P WHERE P.BDCODEMP = T.BDCODEMP AND P.BDCODSAIDA = T.BDCODSAIDASUB),
      T.BDDESCPRODSUB = (
                         SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                         FROM TMP_TCADPRO P
                         WHERE P.BDCODEMP = T.BDCODEMP
                         AND P.BDCODSAIDA = T.BDCODSAIDASUB
                        )
  WHERE T.BDSESSAO = :wSessaoK235K255
  AND T.BDALTCODPRODSUB IS NULL
  AND ((T.BDCODSAIDASUB IS NOT NULL) AND (T.BDCODSAIDASUB <> ''));

  /*Apenas joga o altcodprod para o bdcodprod*/
  UPDATE TMP_VEF_EMP_TMOVINK235K255_TEMP T SET T.BDCODPRODSUB = T.BDALTCODPRODSUB
  WHERE T.BDSESSAO = :wSessaoK235K255
  AND T.BDALTCODPRODSUB IS NOT NULL;
END^

CREATE OR ALTER TRIGGER tmp_vef_emp_tmovk210_temp_gk FOR tmp_vef_emp_tmovk210_temp
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  IF ((OLD.BDEDITCHAVE IS NULL) AND (NEW.BDEDITCHAVE > 0)) THEN
    BEGIN
      NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - OLD.BDCHAVE)+1;
    END
END^

CREATE OR ALTER trigger vrh_esocial_infoirrf_c_bi0 for vrh_esocial_infoirrf_c
active before insert position 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDCODINFO is null) or (new.BDCODINFO = 0)) then
  begin
    select coalesce((max(BDCODINFO) + 1), 1)
    from VRH_ESOCIAL_INFOIRRF_C
    where BDCODEMP = new.BDCODEMP and
          BDCODCOL = new.BDCODCOL and
          BDCODEVT = new.BDCODEVT
    into VCODIGO;

    new.BDCODINFO = VCODIGO;
  end

  if (new.bdrefevt is null) then
     select first 1 x.bdrefarq from vrh_esocial_tarquivo x where x.bdcodemp = new.BDCODEMP and x.bdcodigo = new.bdcodevt into new.bdrefevt;
end^

CREATE or alter trigger vrh_esocial_infoirrf_c_bu0 for vrh_esocial_infoirrf_c
active before update position 0
AS
begin
  /* Trigger text */
  if (new.bdrefevt is null) then
     select first 1 x.bdrefarq from vrh_esocial_tarquivo x where x.bdcodemp = new.BDCODEMP and x.bdcodigo = new.bdcodevt into new.bdrefevt;
end^


CREATE OR ALTER trigger vrh_base_tfilaqualifica_bu0 for vrh_base_tfilaqualifica
active before update position 0
AS
begin
  /* Trigger text */
  if ((coalesce(new.bdstatus,0) = 0) and (coalesce(old.bdstatus,0) = 1)) then
     begin
       new.bdstatus = 1;
       if ((new.BDNOME <> old.BDNOME) or
          (new.BDCPF <> old.BDCPF) or
          (new.BDPIS <> old.BDPIS) or
          (new.BDDATANASC <> old.BDDATANASC)) then
          begin
            new.bdstatus = 0;
          end
     end
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_INFOIRRF_TER_BI0 FOR VRH_ESOCIAL_INFOIRRF_TER
ACTIVE BEFORE INSERT POSITION 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDCODINFO is null) or (new.BDCODINFO = 0)) then
  begin
    select coalesce((max(BDCODINFO) + 1), 1)
    from VRH_ESOCIAL_INFOIRRF_TER
    where BDCODEMP = new.BDCODEMP and
          BDCODTER = new.BDCODTER and
          BDCODEVT = new.BDCODEVT
    into VCODIGO;

    new.BDCODINFO = VCODIGO;
  end

  if (new.bdrefevt is null) then
     select first 1 x.bdrefarq from vrh_esocial_tarquivo x where x.bdcodemp = new.BDCODEMP and x.bdcodigo = new.bdcodevt into new.bdrefevt;
end^

CREATE or alter trigger vrh_esocial_infoirrf_ter_bu0 for vrh_esocial_infoirrf_ter
active before update position 0
AS
begin
  /* Trigger text */
  if (new.bdrefevt is null) then
    select first 1 x.bdrefarq from vrh_esocial_tarquivo x where x.bdcodemp = new.BDCODEMP and x.bdcodigo = new.bdcodevt into new.bdrefevt;

end^


CREATE or alter trigger vrh_esocial_infobasecs_c_bi0 for VRH_ESOCIAL_INFOBASECS_C
active before insert position 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDCODINFO is null) or (new.BDCODINFO = 0)) then
  begin
    select coalesce((max(BDCODINFO) + 1), 1)
    from VRH_ESOCIAL_INFOBASECS_C
    where BDCODEMP = new.BDCODEMP and
          BDCODCOL = new.BDCODCOL and
          BDCODEVT = new.BDCODEVT
    into VCODIGO;

    new.BDCODINFO = VCODIGO;
  end
end^

CREATE or alter trigger vrh_esocial_infobasecs_ter_bi0 for vrh_esocial_infobasecs_ter
active before insert position 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDCODINFO is null) or (new.BDCODINFO = 0)) then
  begin
    select coalesce((max(BDCODINFO) + 1), 1)
    from VRH_ESOCIAL_INFOBASECS_ter
    where BDCODEMP = new.BDCODEMP and
          BDCODTER = new.BDCODTER and
          BDCODEVT = new.BDCODEVT
    into VCODIGO;

    new.BDCODINFO = VCODIGO;
  end
end^


CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK215 (
    PRSESSAO INTEGER,
    PRSESSAOPRO INTEGER)
AS
BEGIN
  /*105 - Já existe um lançamento de mesmo produto para essa chave na ordem */
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDORDEMK215, BDCODINCONSISTENCIA)
  SELECT K215.BDCODEMP, K215.BDSESSAO, K215.BDCHAVE, K215.BDORDEM, 105 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK215_TEMP K215
  WHERE K215.BDSESSAO = :PRSESSAO
  AND EXISTS (
              SELECT K.BDCHAVE
              FROM TMP_VEF_EMP_TMOVK215_TEMP K
              WHERE K.BDSESSAO = K215.BDSESSAO
              AND K.BDCODEMP = K215.BDCODEMP
              AND K.BDCHAVE = K215.BDCHAVE
              AND K.BDALTCODPROD = K215.BDALTCODPROD
              AND K.BDORDEM <> K215.BDORDEM
             );

  /*104 - O produto de destino não pode ser igual ao produto de origem*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDORDEMK215, BDCODINCONSISTENCIA)
  SELECT K215.BDCODEMP, K215.BDSESSAO, K215.BDCHAVE, K215.BDORDEM, 104 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK215_TEMP K215
  JOIN TMP_VEF_EMP_TMOVK210_TEMP K210 ON(K210.BDSESSAO = K215.BDSESSAO AND K210.BDCODEMP = K215.BDCODEMP AND K210.BDCHAVE = K215.BDCHAVE AND K210.BDALTCODPROD = K215.BDALTCODPROD)
  WHERE K215.BDSESSAO = :PRSESSAO;

  /*87 - Produto não informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDORDEMK215, BDCODINCONSISTENCIA)
  SELECT K215.BDCODEMP, K215.BDSESSAO, K215.BDCHAVE, K215.BDORDEM, 87 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK215_TEMP K215
  WHERE K215.BDSESSAO = :PRSESSAO
  AND ((K215.BDALTCODPROD IS NULL) OR (K215.BDALTCODPROD = 0));
  
  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDORDEMK215, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK215_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :PRSESSAOPRO AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, BDCODINCONSISTENCIA;

  /*101 - O código SPED do item informado deve ser 00, 01, 02, 03, 04, 05 ou 10*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 101 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK215_TEMP K
  JOIN TMP_TCADPRO_TEMP P ON(P.BDSESSAO = :PRSESSAOPRO AND P.BDEDITCHAVE = K.BDALTCODPROD AND P.BDCODTIPOSER NOT IN(1, 2, 3, 4, 5, 6, 11)) /*Está sendo importado*/
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
    UNION
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 101 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK215_TEMP K
  JOIN TCADPRO_VINC V ON(V.BDCODEMP = K.BDCODEMP AND V.BDCODPROD = K.BDALTCODPROD AND V.BDCODTIPOSER NOT IN(1, 2, 3, 4, 5, 6, 11)) /*Já gravado*/
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0));
END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK210 (
    PRSESSAO INTEGER,
    PRSESSAOPRO INTEGER,
    PRULTCHAVE INTEGER)
AS
BEGIN
  DELETE FROM VEF_INCON_TMOVBLOCOK WHERE BDSESSAO = :PRSESSAO AND BDCHAVEK210 IS NOT NULL;

  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVK210_TEMP K SET K.BDEDITCHAVE = :PRULTCHAVE WHERE K.BDSESSAO = :PRSESSAO;

  /*22 - Lançamento já existente na base de dados*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK210_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND EXISTS (
              SELECT FIRST 1 K210.BDCHAVE
              FROM VEF_EMP_TMOVK210 K210
              WHERE K210.BDCODEMP = K.BDCODEMP
              AND K210.BDREFERENCIA = K.BDREFERENCIA
              AND K210.BDORDEMPROD = K.BDORDEMPROD
              AND K210.BDCODPROD = K.BDALTCODPROD
             );

  /*87 - Produto não informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 87 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK210_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NULL) OR (K.BDALTCODPROD = 0));


  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK210_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :PRSESSAOPRO AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA;

  /*101 - O código SPED do item informado deve ser 00, 01, 02, 03, 04, 05 ou 10*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 101 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK210_TEMP K
  JOIN TMP_TCADPRO_TEMP P ON(P.BDSESSAO = :PRSESSAOPRO AND P.BDEDITCHAVE = K.BDALTCODPROD AND P.BDCODTIPOSER NOT IN(1, 2, 3, 4, 5, 6, 11)) /*Está sendo importado*/
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
    UNION
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 101 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK210_TEMP K
  JOIN TCADPRO_VINC V ON(V.BDCODEMP = K.BDCODEMP AND V.BDCODPROD = K.BDALTCODPROD AND V.BDCODTIPOSER NOT IN(1, 2, 3, 4, 5, 6, 11)) /*Já gravado*/
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0));

  /*102 - Data de fim do serviço tem que estar dentro da referência do lançamento!*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, MOV.BDCHAVE, MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 102 BDCODINCONSISTENCIA, K.BDDATAFIMPROD,
        K.BDREFERENCIA, CAST((SELECT BDAAAAMM FROM AAAAMM(K.BDDATAFIMPROD)) AS INTEGER) BDREFFIM
        FROM TMP_VEF_EMP_TMOVK210_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDDATAFIMPROD IS NOT NULL
       ) MOV
   WHERE MOV.BDREFFIM <> MOV.BDREFERENCIA;

  /*103 - Data de fim do serviço não pode ser menor que a data de início do serviço!*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK210, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 103 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK210_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDDATAFIMPROD IS NOT NULL
  AND K.BDDATAFIMPROD < K.BDDATAINIPROD;

  IF ((:PRULTCHAVE IS NOT NULL) AND (:PRULTCHAVE > 0)) THEN
    EXECUTE PROCEDURE SP_ATUALIZAR_CAMPO_CHAVE_TEMP(:PRSESSAO, 'TMP_VEF_EMP_TMOVK210_TEMP');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_BLOCOK215(:PRSESSAO, :PRSESSAOPRO);
END^

CREATE OR ALTER TRIGGER tmp_vef_emp_tmovk260_temp_gk FOR tmp_vef_emp_tmovk260_temp
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  IF ((OLD.BDEDITCHAVE IS NULL) AND (NEW.BDEDITCHAVE > 0)) THEN
    BEGIN
      NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - OLD.BDCHAVE)+1;
    END
END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK265 (
    PRSESSAO INTEGER,
    PRSESSAOPRO INTEGER)
AS
BEGIN
  /*105 - Já existe um lançamento de mesmo produto para essa chave na ordem */
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDORDEMK265, BDCODINCONSISTENCIA)
  SELECT K265.BDCODEMP, K265.BDSESSAO, K265.BDCHAVE, K265.BDORDEM, 105 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK265_TEMP K265
  WHERE K265.BDSESSAO = :PRSESSAO
  AND EXISTS (
              SELECT K.BDCHAVE
              FROM TMP_VEF_EMP_TMOVK265_TEMP K
              WHERE K.BDSESSAO = K265.BDSESSAO
              AND K.BDCODEMP = K265.BDCODEMP
              AND K.BDCHAVE = K265.BDCHAVE
              AND K.BDALTCODPROD = K265.BDALTCODPROD
              AND K.BDORDEM <> K265.BDORDEM
             );

  /*104 - O produto de destino não pode ser igual ao produto de origem*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDORDEMK265, BDCODINCONSISTENCIA)
  SELECT K265.BDCODEMP, K265.BDSESSAO, K265.BDCHAVE, K265.BDORDEM, 104 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK265_TEMP K265
  JOIN TMP_VEF_EMP_TMOVK260_TEMP K260 ON(K260.BDSESSAO = K265.BDSESSAO AND K260.BDCODEMP = K265.BDCODEMP AND K260.BDCHAVE = K265.BDCHAVE AND K260.BDALTCODPROD = K265.BDALTCODPROD)
  WHERE K265.BDSESSAO = :PRSESSAO;

  /*109 - É preciso preencher pelo menos um dos campos de quantidade.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDORDEMK265, BDCODINCONSISTENCIA)
  SELECT K265.BDCODEMP, K265.BDSESSAO, K265.BDCHAVE, K265.BDORDEM, 109 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK265_TEMP K265
  WHERE K265.BDSESSAO = :PRSESSAO
  AND ((K265.BDQTDCONSUMIDA IS NULL) OR (K265.BDQTDCONSUMIDA = 0))
  AND ((K265.BDQTDRETORNADA IS NULL) OR (K265.BDQTDRETORNADA = 0));

  /*87 - Produto não informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDORDEMK265, BDCODINCONSISTENCIA)
  SELECT K265.BDCODEMP, K265.BDSESSAO, K265.BDCHAVE, K265.BDORDEM, 87 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK265_TEMP K265
  WHERE K265.BDSESSAO = :PRSESSAO
  AND ((K265.BDALTCODPROD IS NULL) OR (K265.BDALTCODPROD = 0));

  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDORDEMK265, BDCODINCONSISTENCIA)
  SELECT K265.BDCODEMP, K265.BDSESSAO, K265.BDCHAVE, K265.BDORDEM, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK265_TEMP K265
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :PRSESSAOPRO AND PRO.BDCODEMP = K265.BDCODEMP AND PRO.BDCODPROD = K265.BDALTCODPROD)
  WHERE K265.BDSESSAO = :PRSESSAO
  AND ((K265.BDALTCODPROD IS NOT NULL) AND (K265.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K265.BDCODEMP, K265.BDSESSAO, K265.BDCHAVE, K265.BDORDEM, BDCODINCONSISTENCIA;

END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK260 (
    PRSESSAO INTEGER,
    PRULTCHAVE INTEGER,
    PRIDTERMINAL INTEGER)
AS
DECLARE VARIABLE WSESSAOPRO INTEGER;
BEGIN
  DELETE FROM VEF_INCON_TMOVBLOCOK WHERE BDSESSAO = :PRSESSAO AND BDCHAVEK260 IS NOT NULL;

  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVK260_TEMP K SET K.BDEDITCHAVE = :PRULTCHAVE WHERE K.BDSESSAO = :PRSESSAO;

  /*22 - Lançamento já existente na base de dados*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK260_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND EXISTS (
              SELECT FIRST 1 K260.BDCHAVE
              FROM VEF_EMP_TMOVK260 K260
              WHERE K260.BDCODEMP = K.BDCODEMP
              AND K260.BDREFERENCIA = K.BDREFERENCIA
              AND K260.BDORDEMPROD = K.BDORDEMPROD
              AND K260.BDCODPROD = K.BDALTCODPROD
             );

  /*87 - Produto não informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 87 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK260_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NULL) OR (K.BDALTCODPROD = 0));

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRIDTERMINAL
  AND S.BDTABLE = 'TMP_TCADPRO_TEMP'
  INTO :wSessaoPro;

  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK260_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA;

  /*98 - Data de saída é obrigatória.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 98 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK260_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDDATAINIPROD IS NULL;

  /*106 - Data de retorno ao estoque tem que estar dentro da referência do lançamento */
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDCODINCONSISTENCIA)
  SELECT MOV.BDCODEMP, MOV.BDSESSAO, MOV.BDCHAVE, MOV.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 106 BDCODINCONSISTENCIA, K.BDDATAFIMPROD,
        K.BDREFERENCIA, CAST((SELECT BDAAAAMM FROM AAAAMM(K.BDDATAFIMPROD)) AS INTEGER) BDREFFIM
        FROM TMP_VEF_EMP_TMOVK260_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDDATAFIMPROD IS NOT NULL
       ) MOV
   WHERE MOV.BDREFFIM <> MOV.BDREFERENCIA;

  /*107 - A Ordem de produção deverá ser informada caso a data de retorno não esteja preenchida*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 107 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK260_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDORDEMPROD IS NULL) OR (K.BDORDEMPROD = ''))
  AND K.BDDATAFIMPROD IS NULL;

  /*108 - O campo quantidade de retorno é obrigatório quando o campo data de retorno ao estoque estiver preenchido!*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 108 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK260_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDQTDRETORNO IS NULL) OR (K.BDQTDRETORNO = 0))
  AND K.BDDATAFIMPROD IS NOT NULL;
  
  IF (:PRULTCHAVE > 0) THEN
    EXECUTE PROCEDURE SP_ATUALIZAR_CAMPO_CHAVE_TEMP(:PRSESSAO, 'TMP_VEF_EMP_TMOVK260_TEMP');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_BLOCOK265(:PRSESSAO, :wSessaoPro);
END^

/* Trigger: VRH_BASE_TCUSTOM_PROC_BI0 */
CREATE OR ALTER TRIGGER VRH_BASE_TCUSTOM_PROC_BI0 FOR VRH_BASE_TCUSTOM_PROC
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodprocesso IS NULL) OR (NEW.bdcodprocesso = 0)) THEN
     SELECT COALESCE(MAX(bdcodprocesso),0)+1 FROM vrh_base_tcustom_proc WHERE BDCODCENTRO = NEW.BDCODCENTRO AND BDCODTPCC = NEW.BDCODTPCC INTO NEW.bdcodprocesso;
END
^

CREATE OR ALTER TRIGGER VHRF_EMP_CALC_A_PREV_R_BI0 FOR VHRF_EMP_CALC_AUTO_PREV_RESC
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
        NEW.bdchave = GEN_ID(gen_vhrf_emp_calc_auto_prev_res,1);
     END
END
^

CREATE OR ALTER PROCEDURE SP_VINCULAR_MAQMRC (
    PRSESSAO INTEGER,
    PRID_TERMINAL INTEGER)
AS
DECLARE VARIABLE WTABLE VARCHAR(50);
DECLARE VARIABLE WSQL VARCHAR(500);
DECLARE VARIABLE WSESSAOATU INTEGER;
BEGIN

  FOR SELECT UPPER(TRIM(T.RDB$RELATION_NAME)) BDTABLE
      FROM RDB$RELATION_FIELDS T
      WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
      AND RDB$RELATION_NAME <> 'TMP_VEF_BASE_TCADMAQMRC_TEMP'
      AND RDB$FIELD_NAME = 'BDORDEMMAQ'
      INTO :wTable
  DO
    BEGIN
      wSessaoAtu = NULL;

      SELECT S.BDSESSAO
      FROM TMP_TSESSAO_IMP S
      WHERE S.BDID_TERMINAL = :PRID_TERMINAL
      AND S.BDTABLE = :wTable
      INTO :wSessaoAtu;

      IF (:wSessaoAtu IS NOT NULL) THEN
        BEGIN
          wSQL =          'UPDATE '||:wTable||' T SET T.BDORDEMMAQ = COALESCE(';
          wSQL = :wSQL ||                                                    '(SELECT FIRST 1 M.BDEDITCHAVE FROM TMP_VEF_BASE_TCADMAQMRC_TEMP M WHERE M.BDSESSAO = '||:PRSESSAO||' ';
          wSQL = :wSQL ||                                                    ' AND M.BDNRMAQ = T.BDNRMAQ ';
          wSQL = :wSQL ||                                                    ' AND M.BDSERIEMAQ = T.BDSERIEMAQ), T.BDORDEMMAQ) ';
          wSQL = :wSQL || 'WHERE T.BDSESSAO = '||:wSessaoAtu;

          EXECUTE STATEMENT :wSQL;
        END
    END
END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_CADMAQMRC (
    PRSESSAO INTEGER,
    PRID_TERMINAL INTEGER,
    PRREF INTEGER,
    PRULTCHAVE INTEGER)
AS
DECLARE VARIABLE WTIPOMAQ INTEGER;
DECLARE VARIABLE WVALGTINI NUMERIC(15,2);
DECLARE VARIABLE WESPECIE VARCHAR(5);
DECLARE VARIABLE WSERIE VARCHAR(5);
DECLARE VARIABLE WEDITCHAVE INTEGER;
DECLARE VARIABLE WORDEMMAQ INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WATUDADOS DM_BOOLEAN;
BEGIN
  DELETE FROM VEF_INCON_TCADMAQMRC WHERE BDSESSAO = :PRSESSAO;

  /*Vincula as máquinas da importação com as que já existem cadastradas*/
  UPDATE TMP_VEF_BASE_TCADMAQMRC_TEMP C SET C.BDEDITCHAVE = (SELECT FIRST 1 M.BDORDEMMAQ FROM VEF_BASE_TCADMAQMRC M WHERE M.BDCODEMP = C.BDCODEMP AND M.BDNRMAQ = C.BDNRMAQ AND M.BDSERIEMAQ = C.BDSERIEMAQ)
  WHERE C.BDSESSAO = :PRSESSAO
  AND ((C.BDEDITCHAVE IS NULL) OR (C.BDEDITCHAVE = 0));

  SELECT FIRST 1 BDCODEMP FROM TMP_VEF_BASE_TCADMAQMRC_TEMP WHERE BDSESSAO = :PRSESSAO INTO :wCodEmp;
  SELECT SP.BDATUMAQREDZ FROM SP_GET_ACOES_INCONSISTENCIA(:wCodEmp, :PRREF) SP INTO :wAtuDados;

  /*Se não for pra atualizar com os dados da importação, busca os dados da máquina já cadastrada e joga na máquina que está sendo importada*/
  IF (:wAtuDados = 'FALSE') THEN
    BEGIN
      FOR SELECT C.BDTIPOMAQ, C.BDVALGTINI, C.BDESPECIE,
                 C.BDSERIE, T.BDEDITCHAVE
          FROM VEF_BASE_TCADMAQMRC C
          JOIN TMP_VEF_BASE_TCADMAQMRC_TEMP T ON(T.BDEDITCHAVE > 0 AND T.BDSESSAO = :PRSESSAO AND T.BDCODEMP = C.BDCODEMP AND T.BDEDITCHAVE = C.BDORDEMMAQ)
          INTO :wTipoMaq, :wValGtIni, :wEspecie, :wSerie, :wEditChave
      DO
        BEGIN
          UPDATE TMP_VEF_BASE_TCADMAQMRC_TEMP T SET T.BDTIPOMAQ = :wTipoMaq, T.BDVALGTINI = :wValGtIni, T.BDESPECIE = :wEspecie, T.BDSERIE = :wSerie
          WHERE T.BDSESSAO = :PRSESSAO AND T.BDEDITCHAVE = :wEditChave;
        END
    END
  ELSE
    BEGIN
      /*Senão lança inconsistencia das máquinas já cadastradas*/
/*      INSERT INTO VEF_INCON_TCADMAQMRC(BDSESSAO, BDCODEMP, BDORDEMMAQ, BDCODINCONSISTENCIA)
      SELECT C.BDSESSAO, C.BDCODEMP, C.BDORDEMMAQ, 146 BDINCONSISTENCIA FROM TMP_VEF_BASE_TCADMAQMRC_TEMP C
      WHERE C.BDSESSAO = :PRSESSAO
      AND ((C.BDEDITCHAVE IS NOT NULL) AND (C.BDEDITCHAVE > 0));
*/      
    END

  /*Gera chave para as máquinas novas*/
  IF (:PRULTCHAVE > 0) THEN
    BEGIN
      FOR SELECT T.BDORDEMMAQ
          FROM TMP_VEF_BASE_TCADMAQMRC_TEMP T
          WHERE T.BDSESSAO = :PRSESSAO
          AND ((T.BDEDITCHAVE IS NULL) OR (T.BDEDITCHAVE = 0))
          INTO :wOrdemMaq
      DO
        BEGIN
          UPDATE TMP_VEF_BASE_TCADMAQMRC_TEMP C SET C.BDEDITCHAVE = :PRULTCHAVE WHERE C.BDSESSAO = :PRSESSAO AND C.BDORDEMMAQ = :wOrdemMaq;
          PRULTCHAVE = :PRULTCHAVE - 1;
        END
    END

  EXECUTE PROCEDURE SP_VINCULAR_MAQMRC(:PRSESSAO, :PRID_TERMINAL);
END^

COMMENT ON PARAMETER SP_ATUALIZAR_TMP_CADMAQMRC.PRSESSAO IS 'Sessão do dao de cadastro da máquina MRC'^
COMMENT ON PARAMETER SP_ATUALIZAR_TMP_CADMAQMRC.PRULTCHAVE IS 'Ultima chave para as máquinas novas'^

CREATE OR ALTER PROCEDURE SP_COMMIT_CADMAQMRC (
    PRSESSAO INTEGER)
AS
DECLARE VARIABLE wCODEMP INTEGER;
DECLARE VARIABLE wORDEMMAQ INTEGER;
DECLARE VARIABLE wNRMAQ INTEGER;
DECLARE VARIABLE wSERIEMAQ VARCHAR(20);
DECLARE VARIABLE wTIPOMAQ INTEGER;
DECLARE VARIABLE wVALGTINI NUMERIC(15, 2);
DECLARE VARIABLE wESPECIE VARCHAR(5);
DECLARE VARIABLE wSERIE VARCHAR(5);
BEGIN
  FOR SELECT C.BDCODEMP, C.BDEDITCHAVE, C.BDNRMAQ, C.BDSERIEMAQ,
             C.BDTIPOMAQ, C.BDVALGTINI, C.BDESPECIE, C.BDSERIE
      FROM TMP_VEF_BASE_TCADMAQMRC_TEMP C
      LEFT OUTER JOIN VEF_INCON_TCADMAQMRC M ON(M.BDSESSAO = C.BDSESSAO AND M.BDCODEMP = C.BDCODEMP AND M.BDORDEMMAQ = C.BDORDEMMAQ)
      WHERE C.BDSESSAO = :PRSESSAO
      AND M.BDCODINCONSISTENCIA IS NULL
      INTO :wCodEmp, :wOrdemMaq, :wNrMaq, :wSerieMaq,
           :wTipoMaq, :wValGtIni, :wEspecie, :wSerie
  DO
    BEGIN
      UPDATE OR INSERT INTO VEF_BASE_TCADMAQMRC(BDCODEMP, BDORDEMMAQ, BDNRMAQ, BDSERIEMAQ, BDTIPOMAQ, BDVALGTINI, BDESPECIE, BDSERIE)
      VALUES(:wCodEmp, :wOrdemMaq, :wNrMaq, :wSerieMaq, :wTipoMaq, :wValGtIni, :wEspecie, :wSerie) MATCHING(BDCODEMP, BDORDEMMAQ);
    END
END^

CREATE OR ALTER TRIGGER tmp_vef_emp_tredz_temp_bu0 FOR tmp_vef_emp_tredz_temp
ACTIVE BEFORE UPDATE POSITION 0
AS
DECLARE VARIABLE wChave INTEGER;
BEGIN
  IF (OLD.BDEDITCHAVE IS NULL) THEN
    BEGIN
      wChave = GETORDEMSEQUENCIAL(1);
      NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - :wChave)+1;
    END
END^

create or alter procedure SP_ATUALIZAR_REDZC425 (
    PRSESSAO integer,
    PRSESSAOPRO integer,
    PRCODEMP integer,
    PRREF integer)
as
declare variable WGERAC490 DM_BOOLEAN;
BEGIN
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_REDZC425', '1');
  /* 73 - Produto não cadastrado */
  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMTOT, BDORDEMC425, BDCODINCONSISTENCIA)
  SELECT C.BDSESSAO, C.BDCODEMP, C.BDCHAVE, C.BDORDEMTOT, C.BDORDEMC425, 73 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TREDZC425_TEMP C
  WHERE C.BDSESSAO = :PRSESSAO
  AND ((C.BDALTCODPROD = 0));

  /* 76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMTOT, BDORDEMC425, BDCODINCONSISTENCIA)
  SELECT C.BDSESSAO, C.BDCODEMP, C.BDCHAVE, C.BDORDEMTOT, C.BDORDEMC425, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TREDZC425_TEMP C
  LEFT OUTER JOIN VEF_INCON_TCADPRO P ON(P.BDSESSAO = :PRSESSAOPRO AND P.BDCODEMP = C.BDCODEMP AND P.BDCODPROD = C.BDALTCODPROD)
  WHERE C.BDSESSAO = :PRSESSAO
  AND ((C.BDALTCODPROD IS NOT NULL) AND (C.BDALTCODPROD > 0))
  AND P.BDCODINCONSISTENCIA > 0;

  SELECT UPPER(SP.BDGERAC490) FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :PRCODEMP, NULL) SP INTO :wGeraC490;

  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_REDZC425', '2');
  IF (:wGeraC490 = 'TRUE') THEN
    BEGIN
      /* 23 - Natureza não cadastrada na base*/
      INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMTOT, BDORDEMC425, BDCODINCONSISTENCIA)
      SELECT A.BDSESSAO, A.BDCODEMP, A.BDCHAVE, A.BDORDEMTOT, A.BDORDEMC425, 23 BDCODINCONSISTENCIA
      FROM TMP_VEF_EMP_TREDZC425_TEMP A
      LEFT OUTER JOIN VEF_BASE_TNATOP N ON(N.BDCODNAT = A.BDCODNAT)
      WHERE A.BDSESSAO = :PRSESSAO
      AND N.BDCODNAT IS NULL;
    END
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_REDZC425', '3');

   /*****************************************************/
   /******************* REGISTRO D370 *******************/
   /*****************************************************/

    /* 197 - Cidade invalida - D370*/
  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMTOT, BDORDEMC425, BDCODINCONSISTENCIA)
  SELECT C.BDSESSAO, C.BDCODEMP, C.BDCHAVE, C.BDORDEMTOT, C.BDORDEMC425, 197 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TREDZC425_TEMP C
  JOIN TMP_VEF_EMP_TREDZ_TEMP RED ON (RED.bdcodemp = C.bdcodemp AND RED.bdchave = C.bdchave)
  JOIN TMP_VEF_BASE_TCADMAQMRC_TEMP CAD ON (CAD.bdcodemp = RED.bdcodemp AND CAD.bdeditchave = RED.bdordemmaq)
  WHERE (C.BDSESSAO = :PRSESSAO) AND (CAD.bdtipomaq = 3)
  AND ((C.bdcodcid <= 0) or (C.bdcodcid IS NULL));

  /* 198 - Importação sem D370 */
  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMTOT, BDORDEMC425, BDCODINCONSISTENCIA)
  SELECT RED.BDSESSAO, RED.BDCODEMP, RED.BDCHAVE, NULL, NULL, 198 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TREDZ_TEMP RED
  LEFT JOIN TMP_VEF_EMP_TREDZC425_TEMP C ON (RED.bdcodemp = C.bdcodemp AND RED.bdchave = C.bdchave)
  LEFT JOIN TMP_VEF_BASE_TCADMAQMRC_TEMP CAD ON (CAD.bdcodemp = RED.bdcodemp AND CAD.bdeditchave = RED.bdordemmaq)
  WHERE (RED.BDSESSAO = :PRSESSAO) AND (CAD.bdtipomaq = 3) and (C.bdvlracu is null);

  /**********************************************************/
  /******************* FIM REGISTRO D370 ********************/
  /**********************************************************/

  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_REDZC425', '4');
  UPDATE TMP_TCADPRO_TEMP P
  SET P.BDALIQICMS = Coalesce(P.BDALIQICMS,(SELECT FIRST 1 M.BDALIQTOT FROM TMP_VEF_EMP_TREDZC425_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND P.BDCODPROD = M.BDCODPROD ORDER BY M.BDCHAVE DESC))
  WHERE P.BDSESSAO = :PRSESSAOPRO;
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_REDZC425', '5');
END^

create or alter procedure SP_ATUALIZAR_TMP_MOVCCREDZ (
    PRSESSAO integer,
    PRREF integer)
as
declare variable WNAOPERMITERATEIOGRUPO boolean;
declare variable WCODEMP integer;
begin
  /* Procedure Text */
  select first 1 BDCODEMP
  from TMP_VEF_EMP_TMOVCCREDZ_TEMP
  where BDSESSAO = :PRSESSAO and
        BDCODEMP is not null
  into :WCODEMP;

  if ((:WCODEMP is null) or (:WCODEMP = 0)) then
    exit;

  /* Plano de centro de custo não existente na base ou inconsistente */
  insert into VEF_INCON_TREDZ (BDCODEMP, BDCHAVE, BDORDEMVARCFOP, BDORDEMCC, BDSESSAO, BDCODINCONSISTENCIA)
  select S.BDCODEMP, S.BDCHAVE, S.BDORDEMVARCFOP, S.BDORDEMCC, S.BDSESSAO, 199 BDCODINCONSISTENCIA
  from (select CC.BDCODEMP, CC.BDCHAVE, CC.BDORDEMVARCFOP, CC.BDORDEMCC, CC.BDSESSAO, CC.BDCODCENTRO
        from TMP_VEF_EMP_TMOVCCREDZ_TEMP CC
        where CC.BDSESSAO = :PRSESSAO) S
  where S.BDCODCENTRO = 0 or (S.BDCODCENTRO is null);

  /* Centro de custo não existente na base ou inconsistente */
  insert into VEF_INCON_TREDZ (BDCODEMP, BDCHAVE, BDORDEMVARCFOP, BDORDEMCC, BDSESSAO, BDCODINCONSISTENCIA)
  select S.BDCODEMP, S.BDCHAVE, S.BDORDEMVARCFOP, S.BDORDEMCC, S.BDSESSAO, 200 BDCODINCONSISTENCIA
  from (select CC.BDCODEMP, CC.BDCHAVE, CC.BDORDEMVARCFOP, CC.BDORDEMCC, CC.BDSESSAO, CC.BDCODTPCC
        from TMP_VEF_EMP_TMOVCCREDZ_TEMP CC
        where CC.BDSESSAO = :PRSESSAO) S
  where S.BDCODTPCC = 0 or (S.BDCODTPCC is null);

  /* Percentual total dos CC não fecha 100% */
  insert into VEF_INCON_TREDZ (BDCODEMP, BDCHAVE, BDORDEMVARCFOP, BDORDEMCC, BDSESSAO, BDCODINCONSISTENCIA)
  select S.BDCODEMP, S.BDCHAVE, S.BDORDEMVARCFOP, S.BDORDEMCC, S.BDSESSAO, 201 BDCODINCONSISTENCIA
  from (select CC.BDCODEMP, CC.BDCHAVE, CC.BDORDEMVARCFOP, max(CC.BDORDEMCC) BDORDEMCC, CC.BDSESSAO,
               sum(CC.BDPERCENTUAL) BDPERCTOTAL
        from TMP_VEF_EMP_TMOVCCREDZ_TEMP CC
        where CC.BDSESSAO = :PRSESSAO and
              (CC.BDDEBCRED in (2, 1)) /* CC a crédito */
        group by CC.BDCODEMP, CC.BDCHAVE, CC.BDORDEMVARCFOP, CC.BDSESSAO
        union all
        select CC.BDCODEMP, CC.BDCHAVE, CC.BDORDEMVARCFOP, max(CC.BDORDEMCC) BDORDEMCC, CC.BDSESSAO,
               sum(CC.BDPERCENTUAL) BDPERCTOTAL
        from TMP_VEF_EMP_TMOVCCREDZ_TEMP CC
        where CC.BDSESSAO = :PRSESSAO and
              (CC.BDDEBCRED in (2, 0)) /* CC a débito */
        group by CC.BDCODEMP, CC.BDCHAVE, CC.BDORDEMVARCFOP, CC.BDSESSAO) S
  where S.BDPERCTOTAL <> 100;

  select SP.BDNAOPERMITERATEIOGRUPO
  from SP_CONSULTAEMPRESAS_SIS(:PRREF, :WCODEMP, null) SP
  into :WNAOPERMITERATEIOGRUPO;

  if (WNAOPERMITERATEIOGRUPO) then
  begin
    -- CC a crédito, empresa não permite lançar nas contas ativo, passivo e PL por este motivo não será integrado
    insert into VEF_INCON_TREDZ (BDCODEMP, BDCHAVE, BDORDEMVARCFOP, BDORDEMCC, BDSESSAO, BDCODINCONSISTENCIA)
    select S.BDCODEMP, S.BDCHAVE, S.BDORDEMVARCFOP, S.BDORDEMCC, S.BDSESSAO, 203 BDCODINCONSISTENCIA
    from (select CC.BDCODEMP, CC.BDCHAVE, CC.BDORDEMVARCFOP, CC.BDORDEMCC, CC.BDSESSAO, CC.BDDEBCRED
          from TMP_VEF_EMP_TMOVCCREDZ_TEMP CC
          where CC.BDSESSAO = :PRSESSAO) S
    where S.BDDEBCRED <> 0; -- 1 = Débito
  end
end^

CREATE OR ALTER PROCEDURE sp_atualizar_tmp_redzvarcfop (
    prsessao INTEGER,
    prcodplanoonline INTEGER,
    prsessaomaqmrc INTEGER,
    PRREF integer)
AS
DECLARE VARIABLE wcodnat INTEGER;
DECLARE VARIABLE wcondpgto INTEGER;
DECLARE VARIABLE wcompldefault VARCHAR(100);
DECLARE VARIABLE wcomplementohist BLOB SUB_TYPE 1 SEGMENT SIZE 1000;
DECLARE VARIABLE wespecie VARCHAR(5);
DECLARE VARIABLE wserie VARCHAR(5);
DECLARE VARIABLE wcodemp INTEGER;
DECLARE VARIABLE wchave INTEGER;
DECLARE VARIABLE wordemvarcfop INTEGER;
DECLARE VARIABLE wnrmaq INTEGER;
DECLARE VARIABLE wrefredz INTEGER;
DECLARE VARIABLE wdataini DATE;
DECLARE VARIABLE wdatafin DATE;
BEGIN
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_REDZVARCFOP', '1');
  /*23 - Natureza não cadastrada na base*/
  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMTOT,
                              BDORDEMC425, BDORDEMVARCFOP, BDCODINCONSISTENCIA)
  SELECT V.BDSESSAO, V.BDCODEMP, V.BDCHAVE, NULL, NULL, V.BDORDEMVARCFOP, 23 BDINCONSISTENCIA
  FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP V
  LEFT OUTER JOIN VEF_BASE_TNATOP N ON(N.BDCODNAT = V.BDCODNAT)
  WHERE V.BDSESSAO = :PRSESSAO
  AND N.BDCODNAT IS NULL;
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_REDZVARCFOP', '2');
  
  --#95349 - Para levar complemento histórico de espécie e série
  FOR SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEMVARCFOP, C.BDSERIE, C.BDESPECIE, C.BDNRMAQ
    FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP I
    LEFT OUTER JOIN TMP_VEF_EMP_TREDZ_TEMP R ON (R.BDCODEMP = I.BDCODEMP AND R.BDCHAVE = I.BDCHAVE AND R.BDSESSAO = I.BDSESSAO)
    INNER JOIN TMP_VEF_BASE_TCADMAQMRC_TEMP C ON (C.BDSESSAO = :PRSESSAOMAQMRC AND C.BDCODEMP = R.BDCODEMP AND C.BDEDITCHAVE = R.BDORDEMMAQ)
    WHERE I.BDSESSAO = :PRSESSAO
    INTO :WCODEMP, :WCHAVE, :WORDEMVARCFOP, :WSERIE, :WESPECIE, :WNRMAQ
  DO
  BEGIN
    UPDATE TMP_VEF_EMP_TREDZVARCFOP_TEMP I
      SET I.BDSERIE   = :WSERIE,
          I.BDESPECIE = :WESPECIE,
          I.BDNRMAQ   = :WNRMAQ
      WHERE I.BDSESSAO = :PRSESSAO AND
            I.BDCODEMP = :WCODEMP AND
            I.BDCHAVE = :WCHAVE AND
            I.BDORDEMVARCFOP = :WORDEMVARCFOP;
  END
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_REDZVARCFOP', '3');
  
  /*******************************COMPLEMENTO DE HISTÓRICO**********************************/
  wComplDefault = 'Máquina: *NECF, Cupom Inicial: *CFINI, Cupom final: *CFFIM, CRZ: *REZD';
  FOR SELECT I.BDCODNAT, CASE WHEN COALESCE(I.BDCONDPGTO, 0) = 0 THEN 50
                              WHEN COALESCE(I.BDCONDPGTO, 0) = 1 THEN 51
                              WHEN COALESCE(I.BDCONDPGTO, 0) = 2 THEN 406
                         END BDCONDPGTO, EXTRACT(YEAR FROM S.BDDATAREDZ)*100+EXTRACT(MONTH FROM S.BDDATAREDZ) AS BDREFERENCIA, MIN(S.BDDATAREDZ), MAX(S.BDDATAREDZ)
    FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP I
    LEFT OUTER JOIN TMP_VEF_EMP_TREDZ_TEMP S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO)
    WHERE I.BDSESSAO = :PRSESSAO
    GROUP BY I.BDSESSAO, I.BDCODEMP, I.BDCODNAT, I.BDCONDPGTO, EXTRACT(YEAR FROM S.BDDATAREDZ)*100+EXTRACT(MONTH FROM S.BDDATAREDZ)
    INTO :wCodNat, :wCondPgto, :WREFREDZ, :WDATAINI, :WDATAFIN
  DO
  BEGIN
    /**********************Valor contábil*********************/
    SELECT FIRST 1 COALESCE(
                            (
                             SELECT T.BDCOMPLEMENTO
                             FROM TCONTAS_ONLINE_TEMP T
                             WHERE T.BDSESSAO = :PRSESSAO
                             AND T.BDCODNAT = :wCodNat
                             AND T.BDREFERENCIA = :wrefredz
                             AND T.BDCODTIPOCONTA = :wCondPgto
                             AND T.BDCODITEMONLINE = CASE WHEN :wCondPgto = 50 THEN 111 /*Valor contábil - A vista*/
                                                          WHEN :wCondPgto = 51 THEN 117 /*Valor contábil - Prazo*/
                                                          WHEN :wCondPgto = 406 THEN 170 /*Valor contábil - Outras*/
                                                     END
                            ),
                            (
                             /*Se não houver na conta, busca no vinculo de complemento e se lá não houver usa o complemento padrão*/
                             SELECT H.BDCOMPLEMENTO
                             FROM TCOMPLEMENTO_HIST_VINC HV
                             LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                             WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                             AND HV.BDCODIGOTIPO = 1
                            ),
                            (:wComplDefault) /*Default*/
                           ) BDCODCOMPHIST
    FROM RDB$DATABASE
    INTO :wComplementoHist;

    UPDATE TMP_VEF_EMP_TREDZVARCFOP_TEMP I
    SET I.BDCOMPHIST_VLRCONTAB = :wComplementoHist
    WHERE I.BDSESSAO = :PRSESSAO
    AND I.BDVLRCONTAB > 0
    AND I.BDCODNAT = :wCodNat
    AND EXISTS(SELECT FIRST 1 * FROM TMP_VEF_EMP_TREDZ_TEMP WHERE  BDDATAREDZ BETWEEN :WDATAINI AND :WDATAFIN)
    AND NOT EXISTS(SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                   FROM VEF_INCON_TREDZ INCO
                   WHERE INCO.BDCODEMP = I.BDCODEMP
                   AND INCO.BDCHAVE = I.BDCHAVE
                   AND INCO.BDSESSAO = I.BDSESSAO);
    /*********************************************************/

    /************************PIS******************************/
    wComplementoHist = NULL;
    SELECT FIRST 1 COALESCE(
                            (
                             SELECT T.BDCOMPLEMENTO
                             FROM TCONTAS_ONLINE_TEMP T
                             WHERE T.BDSESSAO = :PRSESSAO
                             AND T.BDCODNAT = :wCodNat    
                             AND T.BDREFERENCIA = :wrefredz
                             AND T.BDCODTIPOCONTA = :wCondPgto
--                             AND T.BDCODITEMONLINE IN(115, 121, 174) /*Avista, prazo e outras do valor do PIS*/
                             AND T.BDCODITEMONLINE = CASE WHEN :wCondPgto = 50 THEN 115 /*PIS - A vista*/
                                                          WHEN :wCondPgto = 51 THEN 121 /*PIS - Prazo*/
                                                          WHEN :wCondPgto = 406 THEN 174 /*PIS - Outras*/
                                                     END
                            ),
                            (
                             /*Se não houver na conta, busca no vinculo de complemento e se lá não houver usa o complemento padrão*/
                             SELECT H.BDCOMPLEMENTO
                             FROM TCOMPLEMENTO_HIST_VINC HV
                             LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                             WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                             AND HV.BDCODIGOTIPO = 17
                            ),
                             (:wComplDefault) /*Default*/
                            ) BDCODCOMPHIST
    FROM RDB$DATABASE
    INTO :wComplementoHist;

    UPDATE TMP_VEF_EMP_TREDZVARCFOP_TEMP I
    SET I.BDCOMPHIST_VLRPIS = :wComplementoHist
    WHERE I.BDSESSAO = :PRSESSAO
    AND I.BDVLRPIS > 0
    AND I.BDCODNAT = :wCodNat       
    AND EXISTS(SELECT FIRST 1 * FROM TMP_VEF_EMP_TREDZ_TEMP WHERE  BDDATAREDZ BETWEEN :WDATAINI AND :WDATAFIN)
    AND NOT EXISTS(SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                   FROM VEF_INCON_TREDZ INCO
                   WHERE INCO.BDCODEMP = I.BDCODEMP
                   AND INCO.BDCHAVE = I.BDCHAVE
                   AND INCO.BDSESSAO = I.BDSESSAO);
    /*********************************************************/

    /***************************ICMS**************************/
    wComplementoHist = NULL;
    SELECT FIRST 1 COALESCE(
                            (
                             SELECT T.BDCOMPLEMENTO
                             FROM TCONTAS_ONLINE_TEMP T
                             WHERE T.BDSESSAO = :PRSESSAO
                             AND T.BDCODNAT = :wCodNat     
                             AND T.BDREFERENCIA = :wrefredz
                             AND T.BDCODTIPOCONTA = :wCondPgto
--                             AND T.BDCODITEMONLINE IN(112, 118, 171) /*Avista, prazo e outras do valor de ICMS*/
                             AND T.BDCODITEMONLINE = CASE WHEN :wCondPgto = 50 THEN 112  /*ICMS - A vista*/
                                                          WHEN :wCondPgto = 51 THEN 118  /*ICMS - Prazo*/
                                                          WHEN :wCondPgto = 406 THEN 171 /*ICMS - Outras*/
                                                     END
                            ),
                            (
                             /*Se não houver na conta, busca no vinculo de complemento e se lá não houver usa o complemento padrão*/
                             SELECT H.BDCOMPLEMENTO
                             FROM TCOMPLEMENTO_HIST_VINC HV
                             LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                             WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                             AND HV.BDCODIGOTIPO = 7
                            ),
                             (:wComplDefault) /*Default*/
                            ) BDCODCOMPHIST
    FROM RDB$DATABASE
    INTO :wComplementoHist;

    UPDATE TMP_VEF_EMP_TREDZVARCFOP_TEMP I
    SET I.BDCOMPHIST_VLRICMS = :wComplementoHist
    WHERE I.BDSESSAO = :PRSESSAO
    AND I.BDVLRICMS > 0
    AND I.BDCODNAT = :wCodNat   
    AND EXISTS(SELECT FIRST 1 * FROM TMP_VEF_EMP_TREDZ_TEMP WHERE  BDDATAREDZ BETWEEN :WDATAINI AND :WDATAFIN)
    AND NOT EXISTS(SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                   FROM VEF_INCON_TREDZ INCO
                   WHERE INCO.BDCODEMP = I.BDCODEMP
                   AND INCO.BDCHAVE = I.BDCHAVE
                   AND INCO.BDSESSAO = I.BDSESSAO);
    /*********************************************************/

    /*************************ICMS ST*************************/
    wComplementoHist = NULL;
    SELECT FIRST 1 COALESCE(
                            (
                             SELECT T.BDCOMPLEMENTO
                             FROM TCONTAS_ONLINE_TEMP T
                             WHERE T.BDSESSAO = :PRSESSAO
                             AND T.BDCODNAT = :wCodNat     
                             AND T.BDREFERENCIA = :wrefredz
                             AND T.BDCODTIPOCONTA = :wCondPgto
--                             AND T.BDCODITEMONLINE IN(113, 119, 172) /*Avista, prazo e outras do valor de ICMS ST*/
                             AND T.BDCODITEMONLINE = CASE WHEN :wCondPgto = 50 THEN 113  /*ICMS ST - A vista*/
                                                          WHEN :wCondPgto = 51 THEN 119  /*ICMS ST - Prazo*/
                                                          WHEN :wCondPgto = 406 THEN 172 /*ICMS ST - Outras*/
                                                     END
                            ),
                            (
                             /*Se não houver na conta, busca no vinculo de complemento e se lá não houver usa o complemento padrão*/
                             SELECT H.BDCOMPLEMENTO
                             FROM TCOMPLEMENTO_HIST_VINC HV
                             LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                             WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                             AND HV.BDCODIGOTIPO = 12
                            ),
                             (:wComplDefault) /*Default*/
                           ) BDCODCOMPHIST
    FROM RDB$DATABASE
    INTO :wComplementoHist;

    UPDATE TMP_VEF_EMP_TREDZVARCFOP_TEMP I
    SET I.BDCOMPHIST_VLRICMSST = :wComplementoHist
    WHERE I.BDSESSAO = :PRSESSAO
    AND I.BDVLRST > 0
    AND I.BDCODNAT = :wCodNat   
    AND EXISTS(SELECT FIRST 1 * FROM TMP_VEF_EMP_TREDZ_TEMP WHERE  BDDATAREDZ BETWEEN :WDATAINI AND :WDATAFIN)
    AND NOT EXISTS(SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                   FROM VEF_INCON_TREDZ INCO
                   WHERE INCO.BDCODEMP = I.BDCODEMP
                   AND INCO.BDCHAVE = I.BDCHAVE
                   AND INCO.BDSESSAO = I.BDSESSAO);
    /*********************************************************/

    /**************************COFINS*************************/
    wComplementoHist = NULL;
    SELECT FIRST 1 COALESCE(
                            (
                             SELECT T.BDCOMPLEMENTO
                             FROM TCONTAS_ONLINE_TEMP T
                             WHERE T.BDSESSAO = :PRSESSAO
                             AND T.BDCODNAT = :wCodNat        
                             AND T.BDREFERENCIA = :wrefredz
                             AND T.BDCODTIPOCONTA = :wCondPgto
--                             AND T.BDCODITEMONLINE IN(116, 122, 175) /*Avista, prazo e outras do valor do Cofins*/
                             AND T.BDCODITEMONLINE = CASE WHEN :wCondPgto = 50 THEN 116  /*Cofins - A vista*/
                                                          WHEN :wCondPgto = 51 THEN 122  /*Cofins - Prazo*/
                                                          WHEN :wCondPgto = 406 THEN 175 /*Cofins - Outras*/
                                                     END
                            ),
                            (
                             /*Se não houver na conta, busca no vinculo de complemento e se lá não houver usa o complemento padrão*/
                             SELECT H.BDCOMPLEMENTO
                             FROM TCOMPLEMENTO_HIST_VINC HV
                             LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                             WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                             AND HV.BDCODIGOTIPO = 23
                            ),
                             (:wComplDefault) /*Default*/
                           ) BDCODCOMPHIST
    FROM RDB$DATABASE
    INTO :wComplementoHist;

    UPDATE TMP_VEF_EMP_TREDZVARCFOP_TEMP I
    SET I.BDCOMPHIST_VLRCOFINS = :wComplementoHist
    WHERE I.BDSESSAO = :PRSESSAO
    AND I.BDVLRCOFINS > 0
    AND I.BDCODNAT = :wCodNat     
    AND EXISTS(SELECT FIRST 1 * FROM TMP_VEF_EMP_TREDZ_TEMP WHERE  BDDATAREDZ BETWEEN :WDATAINI AND :WDATAFIN)
    AND NOT EXISTS(SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                   FROM VEF_INCON_TREDZ INCO
                   WHERE INCO.BDCODEMP = I.BDCODEMP
                   AND INCO.BDCHAVE = I.BDCHAVE
                   AND INCO.BDSESSAO = I.BDSESSAO);
    /*********************************************************/
    /************************DESCONTO*************************/
    wComplementoHist = NULL;
    SELECT C.BDCOMPLEMENTO FROM TCONTAS_ONLINE_TEMP C
    WHERE C.BDSESSAO = :PRSESSAO AND C.BDCODITEMONLINE = 88 /*Desconto*/ 
    AND C.BDREFERENCIA = :wrefredz INTO :wComplementoHist;
  
    SELECT FIRST 1 COALESCE(:wComplementoHist,
                            (
                             SELECT H.BDCOMPLEMENTO
                             FROM TCOMPLEMENTO_HIST_VINC HV
                             LEFT OUTER JOIN  TCOMPLEMENTO_HIST H ON(H.BDCODCOMPHIST = HV.BDCODCOMPHIST)
                             WHERE HV.BDCODPLANOONLINE = :PRCODPLANOONLINE
                             AND HV.BDCODIGOTIPO = 29
                            ),
                             (:wComplDefault) /*Default*/
                           ) BDCODCOMPHIST
    FROM RDB$DATABASE
    INTO :wComplementohist;
  
    UPDATE TMP_VEF_EMP_TREDZVARCFOP_TEMP I
    SET I.BDCOMPHIST_VLRDESCONTO = :wComplementoHist
    WHERE I.BDSESSAO = :PRSESSAO
    AND EXISTS(
               SELECT S.BDVALDESCICMS
               FROM TMP_VEF_EMP_TREDZ_TEMP S
               WHERE S.BDVALDESCICMS > 0
               AND S.BDCODEMP = I.BDCODEMP
               AND S.BDCHAVE  = I.BDCHAVE
               AND S.BDSESSAO = I.BDSESSAO
               AND BDDATAREDZ BETWEEN :WDATAINI AND :WDATAFIN
              )
    AND NOT EXISTS(
                   SELECT INCO.BDCODEMP, INCO.BDCHAVE, INCO.BDSESSAO
                   FROM VEF_INCON_TREDZ INCO
                   WHERE INCO.BDCODEMP = I.BDCODEMP
                   AND INCO.BDCHAVE = I.BDCHAVE
                   AND INCO.BDSESSAO = I.BDSESSAO
                  );
    /*********************************************************/
  END
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_REDZVARCFOP', '4');
  
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_MOVCCREDZ(:PRSESSAO, :PRREF);
END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_TREDZC425ALIQ (
    PRSESSAO INTEGER,
    PRSESSAOPRO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS
DECLARE VARIABLE WGERAC490 DM_BOOLEAN;
BEGIN
  /*73 - Produto não cadastrado.*/
  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMTOT, BDORDEMC425, BDORDEMICMS, BDCODINCONSISTENCIA)
  SELECT A.BDSESSAO, A.BDCODEMP, A.BDCHAVE, A.BDORDEMTOT, A.BDORDEMC425, A.BDORDEMICMS, 73 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TREDZC425ALIQ_TEMP A
  WHERE A.BDSESSAO = :PRSESSAO
  AND ((A.BDALTCODPROD = 0));

  /* 76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMTOT, BDORDEMC425, BDORDEMICMS, BDCODINCONSISTENCIA)
  SELECT A.BDSESSAO, A.BDCODEMP, A.BDCHAVE, A.BDORDEMTOT, A.BDORDEMC425, A.BDORDEMICMS, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TREDZC425ALIQ_TEMP A
  LEFT OUTER JOIN VEF_INCON_TCADPRO P ON(P.BDSESSAO = :PRSESSAOPRO AND P.BDCODEMP = A.BDCODEMP AND P.BDCODPROD = A.BDALTCODPROD)
  WHERE A.BDSESSAO = :PRSESSAO
  AND ((A.BDALTCODPROD IS NOT NULL) AND (A.BDALTCODPROD > 0))
  AND P.BDCODINCONSISTENCIA > 0;

  SELECT UPPER(SP.BDGERAC490) FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :PRCODEMP, NULL) SP INTO :wGeraC490;

  IF (:wGeraC490 = 'TRUE') THEN
    BEGIN
      /* 23 - Natureza não cadastrada na base*/
      INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMTOT, BDORDEMC425, BDORDEMICMS, BDCODINCONSISTENCIA)
      SELECT A.BDSESSAO, A.BDCODEMP, A.BDCHAVE, A.BDORDEMTOT, A.BDORDEMC425, A.BDORDEMICMS, 23 BDCODINCONSISTENCIA
      FROM TMP_VEF_EMP_TREDZC425ALIQ_TEMP A
      LEFT OUTER JOIN VEF_BASE_TNATOP N ON(N.BDCODNAT = A.BDCODNAT)
      WHERE A.BDSESSAO = :PRSESSAO
      AND N.BDCODNAT IS NULL;
    END
    
  UPDATE TMP_TCADPRO_TEMP P
  SET P.BDALIQICMS = Coalesce(P.BDALIQICMS,(SELECT FIRST 1 Coalesce(M.BDALIQICMS,M.BDALIQTOT) FROM TMP_VEF_EMP_TREDZC425ALIQ_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND P.BDCODPROD = M.BDCODPROD ORDER BY M.BDCHAVE DESC))
  WHERE P.BDSESSAO = :PRSESSAOPRO;
END^

CREATE OR ALTER procedure SP_ATUALIZAR_TREDZ60I (
    PRSESSAO integer,
    PRSESSAOPRO integer)
as
begin
  /*73 - Produto não cadastrado.*/
  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM60I, BDNUMCOO, BDCODINCONSISTENCIA)
  SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEM60I, I.BDNUMCOO, 73 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TREDZ60I_TEMP I
  WHERE I.BDSESSAO = :PRSESSAO
  AND ((I.BDALTCODPROD IS NULL) OR (I.BDALTCODPROD = 0));

  /* 76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM60I, BDNUMCOO, BDCODINCONSISTENCIA)
  SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEM60I, I.BDNUMCOO, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TREDZ60I_TEMP I
  LEFT OUTER JOIN VEF_INCON_TCADPRO P ON(P.BDSESSAO = :PRSESSAOPRO AND P.BDCODEMP = I.BDCODEMP AND P.BDCODPROD = I.BDALTCODPROD)
  WHERE I.BDSESSAO = :PRSESSAO
  AND ((I.BDALTCODPROD IS NOT NULL) AND (I.BDALTCODPROD > 0))
  AND P.BDCODINCONSISTENCIA > 0;
  
  UPDATE TMP_TCADPRO_TEMP P
  SET P.BDALIQICMS = Coalesce(P.BDALIQICMS,(SELECT FIRST 1 M.BDALIQICMS FROM TMP_VEF_EMP_TREDZ60I_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND P.BDCODPROD = M.BDCODPROD ORDER BY M.BDCHAVE DESC))
  WHERE P.BDSESSAO = :PRSESSAOPRO;

end^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_TREDZC425AQISS (
    PRSESSAO integer,
    PRSESSAOPRO integer,
    PRCODEMP integer,
    PRREF integer)
as
declare variable WGERAC490 DM_BOOLEAN;
BEGIN
  /*73 - Produto não cadastrado.*/
  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMTOT, BDORDEMC425, BDORDEMISS, BDCODINCONSISTENCIA)
  SELECT A.BDSESSAO, A.BDCODEMP, A.BDCHAVE, A.BDORDEMTOT, A.BDORDEMC425, A.BDORDEMISS, 73 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TREDZC425AQISS_TEMP A
  WHERE A.BDSESSAO = :PRSESSAO
  AND ((A.BDALTCODPROD = 0));

  /* 76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMTOT, BDORDEMC425, BDORDEMISS, BDCODINCONSISTENCIA)
  SELECT A.BDSESSAO, A.BDCODEMP, A.BDCHAVE, A.BDORDEMTOT, A.BDORDEMC425, A.BDORDEMISS, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TREDZC425AQISS_TEMP A
  LEFT OUTER JOIN VEF_INCON_TCADPRO P ON(P.BDSESSAO = :PRSESSAOPRO AND P.BDCODEMP = A.BDCODEMP AND P.BDCODPROD = A.BDALTCODPROD)
  WHERE A.BDSESSAO = :PRSESSAO
  AND ((A.BDALTCODPROD IS NOT NULL) AND (A.BDALTCODPROD > 0))
  AND P.BDCODINCONSISTENCIA > 0;

  SELECT UPPER(SP.BDGERAC490) FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :PRCODEMP, NULL) SP INTO :wGeraC490;

  IF (:wGeraC490 = 'TRUE') THEN
    BEGIN
      /* 23 - Natureza não cadastrada na base*/
      INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMTOT, BDORDEMC425, BDORDEMISS, BDCODINCONSISTENCIA)
      SELECT A.BDSESSAO, A.BDCODEMP, A.BDCHAVE, A.BDORDEMTOT, A.BDORDEMC425, A.BDORDEMISS, 23 BDCODINCONSISTENCIA
      FROM TMP_VEF_EMP_TREDZC425AQISS_TEMP A
      LEFT OUTER JOIN VEF_BASE_TNATOP N ON(N.BDCODNAT = A.BDCODNAT)
      WHERE A.BDSESSAO = :PRSESSAO
      AND N.BDCODNAT IS NULL;
    END
    
  UPDATE TMP_TCADPRO_TEMP P
  SET P.BDALIQICMS = Coalesce(P.BDALIQICMS,(SELECT FIRST 1 Coalesce(M.BDALIQICMS,M.BDALIQTOT) FROM TMP_VEF_EMP_TREDZC425AQISS_TEMP M WHERE M.BDSESSAO = :PRSESSAO AND P.BDCODPROD = M.BDCODPROD ORDER BY M.BDCHAVE DESC))
  WHERE P.BDSESSAO = :PRSESSAOPRO;
END^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_TREDZC490 (
    PRSESSAO integer)
as
BEGIN
  /*Quando for feito o desenvolvimento da observação, deve ser feita a validação do C490(BDCODOBS) aqui*/
END^

create or alter procedure SP_ATUALIZAR_TMP_TMOVREDZ (
    PRSESSAO integer,
    PRSESSAOMAQMRC integer,
    PRSESSAOPRO integer,
    PRULTCHAVE integer,
    PRREF integer,
    PRGERALOG varchar(5))
as
declare variable WCODENQFED integer;
declare variable WCODEMP integer;
declare variable WCODPLANOONLINE integer;
declare variable WCODCONFIRLP integer;
declare variable WFORMATRIBUTACAO integer;
BEGIN
  RDB$SET_CONTEXT('USER_SESSION','W_GERALOG_TEMP',:PRGERALOG);
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVREDZ', '1');
  DELETE FROM VEF_INCON_TREDZ WHERE BDSESSAO = :PRSESSAO;

  /*Define as chaves para os lançamentos - Dispara a trigger dessa tabela que decrementa da ultima chave até a primeira*/
  IF (:PRULTCHAVE > 0) THEN
    BEGIN
      SETORDEMSEQUENCIAL(0);
      UPDATE TMP_VEF_EMP_TREDZ_TEMP SET BDEDITCHAVE = :PRULTCHAVE WHERE BDSESSAO = :PRSESSAO AND ((BDEDITCHAVE IS NULL) OR (BDEDITCHAVE = 0));
    END
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVREDZ', '2');

  SELECT FIRST 1 BDCODEMP FROM TMP_VEF_EMP_TREDZ_TEMP WHERE BDSESSAO = :PRSESSAO INTO :wCodEmp;
  IF ((:wCodEmp IS NULL) OR (:wCodEmp = 0)) THEN
    EXIT;  

  /*Inconsistencia de número do documento vazio(Inicial e final)*/       
  --#95412 - Deve permitir cupom final menos que o inicial
  /*
  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDCODINCONSISTENCIA)
  SELECT S.BDSESSAO, S.BDCODEMP, S.BDCHAVE, 16 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TREDZ_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO
  AND S.BDNUMCUPINI > S.BDNUMCUPFIN;    */

  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVREDZ', '3');
  /*82 - Lançamento já existe na base de dados ou na própria importação (número, série da máquina, data de emissão do lançamento, CRO e CRZ)*/
  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMTOT, BDORDEMC425, BDCODINCONSISTENCIA)
  SELECT R.BDSESSAO, R.BDCODEMP, R.BDCHAVE, NULL, NULL, R.BDCODINCONSISTENCIA
  FROM (
        SELECT /*SKIP 1 - Alt.: #150913*/ T.BDSESSAO, T.BDCODEMP, T.BDCHAVE, 82 BDCODINCONSISTENCIA
        FROM TMP_VEF_EMP_TREDZ_TEMP T
        JOIN ( -- Alt.: #150913 - Verifica se o lançamento é repetido na importação, se for deve deixar importar a menor chave e bloquear as demais...
              SELECT r.bdSESSAO, r.bdCODEMP, r.bdNRMAQ, r.bdSERIEMAQ, r.bdDATAREDZ, r.bdPOSCRO, r.bdPOSCRZ, MIN(R.BDCHAVE) AS bdCHAVE
              FROM TMP_VEF_EMP_TREDZ_TEMP R
              WHERE ((R.BDNRMAQ IS NOT NULL) AND (R.BDNRMAQ > 0))
              GROUP BY r.bdSESSAO, r.bdCODEMP, r.bdNRMAQ, r.bdSERIEMAQ, r.bdDATAREDZ, r.bdPOSCRO, r.bdPOSCRZ
              HAVING COUNT(R.BDCHAVE) > 1
              ) R ON (r.bdSESSAO = t.bdSESSAO AND r.bdCODEMP = t.bdCODEMP AND r.bdNRMAQ = t.bdNRMAQ AND r.bdSERIEMAQ = t.bdSERIEMAQ AND
                      r.bdDATAREDZ = t.bdDATAREDZ AND r.bdPOSCRO = t.bdPOSCRO AND r.bdPOSCRZ = t.bdPOSCRZ AND r.bdCHAVE <> t.bdCHAVE)
        WHERE T.BDSESSAO = :PRSESSAO
        /* Alt.: #150913 - Estava buscando todos os lançamentos repetidos e deixando apenas importar o primeiro e bloqueando os demais, com isso, cada vez que manda importar na treeview, importava um novo lançamento, de um em um...
        AND EXISTS(
                   SELECT R.BDCODEMP, R.BDNRMAQ, R.BDSERIEMAQ, R.BDDATAREDZ
                   FROM TMP_VEF_EMP_TREDZ_TEMP R
                   WHERE ((R.BDNRMAQ IS NOT NULL) AND (R.BDNRMAQ > 0))
                   AND R.BDSESSAO = T.BDSESSAO
                   AND R.BDCODEMP = T.BDCODEMP
                   AND R.BDNRMAQ = T.BDNRMAQ
                   AND R.BDSERIEMAQ = T.BDSERIEMAQ
                   AND R.BDDATAREDZ = T.BDDATAREDZ
                   AND R.BDPOSCRO = T.BDPOSCRO
                   AND R.BDPOSCRZ = T.BDPOSCRZ
                   GROUP BY R.BDCODEMP, R.BDNRMAQ, R.BDSERIEMAQ, R.BDDATAREDZ, R.BDPOSCRO, R.BDPOSCRZ
                   HAVING COUNT(R.BDCHAVE) > 1
                  )*/
        ORDER BY T.BDCHAVE
       ) R
  UNION
  SELECT T.BDSESSAO, T.BDCODEMP, T.BDCHAVE, NULL, NULL, 82 BDCODINCONSISTENCIA
  FROM VEF_EMP_TREDZ REDZ
  JOIN TMP_VEF_EMP_TREDZ_TEMP T ON(T.BDSESSAO = :PRSESSAO AND T.BDCODEMP = REDZ.BDCODEMP AND T.BDDATAREDZ = REDZ.BDDATAREDZ AND T.BDPOSCRO = REDZ.BDPOSCRO AND T.BDPOSCRZ = REDZ.BDPOSCRZ)
  LEFT OUTER JOIN VEF_BASE_TCADMAQMRC MAQDB ON(MAQDB.BDCODEMP = REDZ.BDCODEMP AND MAQDB.BDORDEMMAQ = REDZ.BDORDEMMAQ)
  WHERE REDZ.BDCODEMP = :wCodEmp
  AND ((T.BDNRMAQ IS NOT NULL) AND (T.BDNRMAQ > 0))
  AND T.BDNRMAQ = MAQDB.BDNRMAQ
  AND T.BDSERIEMAQ = MAQDB.BDSERIEMAQ;
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVREDZ', '4');

  /*83 - ordem da máquina não cadastrada na base de dados!*/
  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMTOT, BDORDEMC425, BDCODINCONSISTENCIA)
  SELECT R.BDSESSAO, R.BDCODEMP, R.BDCHAVE, NULL, NULL, 83 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TREDZ_TEMP R
  WHERE R.BDSESSAO = :PRSESSAO
  AND ((R.BDORDEMMAQ IS NULL) OR (R.BDORDEMMAQ = 0));

  /*84 - máquina não existente na base ou inconsistente!*/
  INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMTOT, BDORDEMC425, BDCODINCONSISTENCIA)
  SELECT R.BDSESSAO, R.BDCODEMP, R.BDCHAVE, NULL, NULL, 84 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TREDZ_TEMP R
  LEFT OUTER JOIN VEF_INCON_TCADMAQMRC M ON(M.BDSESSAO = :PRSESSAOMAQMRC AND M.BDCODEMP = R.BDCODEMP AND M.BDORDEMMAQ = R.BDORDEMMAQ)
  WHERE R.BDSESSAO = :PRSESSAO
  AND M.BDCODINCONSISTENCIA > 0;

  /*85 - cupom final menor que o inicial!*/
  --#95412 - Deve permitir cupom final menos que o inicial
  /*INSERT INTO VEF_INCON_TREDZ(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMTOT, BDORDEMC425, BDCODINCONSISTENCIA)
  SELECT R.BDSESSAO, R.BDCODEMP, R.BDCHAVE, NULL, NULL, 85 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TREDZ_TEMP R
  WHERE R.BDSESSAO = :PRSESSAO
  AND R.BDNUMCUPFIN < R.BDNUMCUPINI;*/

  /*Busca dados usados nas inconsistencias do lançamento e do item*/
  SELECT SP.BDCODPLANOONLINE, SP.BDCODENQFED, SP.BDCODCONFIRLP, sp.BDFORMATRIBUTACAO
  FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :wCodEmp, NULL) SP
  INTO :wCodPlanoOnline, :wCodEnqFed, :wCODCONFIRLP, :WFORMATRIBUTACAO;

  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVREDZ', '5');
  EXECUTE PROCEDURE SP_ATUALIZAR_CAMPO_CHAVE_TEMP(:PRSESSAO, 'TMP_VEF_EMP_TREDZ_TEMP');
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVREDZ', '6');
  EXECUTE PROCEDURE SP_VALIDA_CONTA_ONLINE_TEMP(:wCodPlanoOnline, :PRSESSAO, :wCodEnqFed, :wCODCONFIRLP, 'REDZ');  
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVREDZ', '7');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_REDZVARCFOP(:PRSESSAO, :wCodPlanoOnline,:PRSESSAOMAQMRC, :PRREF); /*Várias CFOP's*/
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVREDZ', '8');
  EXECUTE PROCEDURE SP_ATUALIZAR_REDZC425(:PRSESSAO, :PRSESSAOPRO, :wCodEmp, :PRREF); /*C425*/
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVREDZ', '9');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_TREDZC425ALIQ(:PRSESSAO, :PRSESSAOPRO, :wCodEmp, :PRREF); /*C425 Alíquotas*/
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVREDZ', '10');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_TREDZC425AQISS(:PRSESSAO, :PRSESSAOPRO, :WCODEMP, :PRREF); /*C425 Alíquotas ISS*/
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVREDZ', '11');
  EXECUTE PROCEDURE SP_ATUALIZAR_TREDZ60I(:PRSESSAO, :PRSESSAOPRO); /*60I*/  
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVREDZ', '12');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_ITEMDOCECF(:PRSESSAO, :PRSESSAOPRO); /*Item do documento fiscal - C470*/  
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVREDZ', '13');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_TREDZC490(:PRSESSAO); /*C490*/
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVREDZ', '14');
  EXECUTE PROCEDURE SP_CRIA_PRE_CONTABILIZACAO(:PRSESSAO, :wCodPlanoOnline, :wCodEnqFed, :wCODCONFIRLP, 'REDZ', 0, :WFORMATRIBUTACAO);
  /**/ execute procedure SP_GERALOG_TEMP('SP_ATUALIZAR_TMP_TMOVREDZ', '15');
  RDB$SET_CONTEXT('USER_SESSION','W_GERALOG_TEMP','FALSE');
END^

CREATE OR ALTER procedure SP_IMPORTA_RMD (
    PRSESSAO integer)
as
declare variable WCODEMPATU integer;
declare variable WCODEMP integer;
declare variable WEDITCHAVE integer;
declare variable WCODIGO integer;
begin
   :wcodempatu = -1;

   --Pegando os RMD já cadastrados na base
   update TMP_VEF_EMP_TRESMOVDIARIO_TEMP C
   set C.bdeditchave = (SELECT FIRST 1 M.BDCODIGO
                        FROM VEF_EMP_TRESMOVDIARIO M
                        WHERE M.BDCODEMP = C.BDCODEMP
                          AND M.bdserie = C.bdserie
                          AND M.bdsubserie = C.bdsubserie
                          AND M.bdnumero = C.bdnumero)
   WHERE C.BDSESSAO = :PRSESSAO;


   --Atualizando um por um os próximos, lembrando que reinicia por empresa
   --Por enquanto vai ser uma empresa só, porém já fica preparado para se no futuro
   -- vierem matriz e filiais por exemplo
   FOR SELECT BDCODEMP, BDCODIGO
       FROM TMP_VEF_EMP_TRESMOVDIARIO_TEMP
       WHERE BDSESSAO = :prsessao
         AND ((BDEDITCHAVE IS NULL) OR (BDEDITCHAVE = 0))
       ORDER BY BDCODEMP
       INTO :wCODEMP, :WCODIGO
   DO
      BEGIN
         --obtendo a última chave da empresa atual, quando esta for diferente
         if (:wcodEmp <> :wcodempatu) then
            begin
               SELECT COALESCE(MAX(BDCODIGO) + 1, 1) FROM VEF_EMP_TRESMOVDIARIO INTO :weditchave;
               :wcodempatu = :wcodEmp;
            end
         --senão apenas incrementa a chave atual
         else
            begin
               :weditchave = :weditchave + 1;
            end

         UPDATE TMP_VEF_EMP_TRESMOVDIARIO_TEMP
         SET BDEDITCHAVE = :weditchave
         WHERE BDSESSAO = :PRSESSAO
           AND BDCODIGO = :wcodigo;
      END

   --Com os dados devidamente atualizados, vamos inserir dentro da base
   INSERT INTO VEF_EMP_TRESMOVDIARIO (BDCODEMP,   BDCODIGO   ,   BDSERIE,   BDSUBSERIE,   BDNUMERO,   BDDATAATIVINI,   BDDATAATIVFIM)
   SELECT                           C.BDCODEMP, C.BDEDITCHAVE, C.BDSERIE, C.BDSUBSERIE, C.BDNUMERO, C.BDDATAATIVINI, C.BDDATAATIVFIM
   FROM TMP_VEF_EMP_TRESMOVDIARIO_TEMP C
   WHERE C.BDSESSAO = :prsessao
     AND ((C.bdeditchave IS NOT NULL) OR (C.bdeditchave > 0))
     AND (not EXISTS(SELECT First 1 F.BDCODIGO
                     FROM VEF_EMP_TRESMOVDIARIO F
                     WHERE F.bdcodigo = C.bdeditchave));

   --Agora que inserimos os cadastros de RMD, vamos atualizar a tabela de D400 para colocar o código correto no momento da inserção
   UPDATE TMP_VEF_EMP_TD400SAI_TEMP C
   SET C.bdcodigo = (select first 1 M.BDEDITCHAVE
                     FROM TMP_VEF_EMP_TRESMOVDIARIO_TEMP M
                     WHERE M.bdsessao = C.bdsessao_rmd
                       AND M.bdcodemp = C.bdcodemp
                       AND M.bdserie = C.bdserie_rmd
                       AND COALESCE(M.bdsubserie, '') = Coalesce(C.bdsubserie_rmd, '')
                       AND M.bdnumero = C.bdnumero_rmd)
   WHERE C.bdsessao_rmd = :PRSESSAO;
end^

CREATE OR ALTER procedure SP_COMMIT_IMP_REDZ (
    PRSESSAO integer)
as
BEGIN
  /*Redução Z*/
  INSERT INTO VEF_EMP_TREDZ(BDCODEMP, BDCHAVE, BDORDEMMAQ, BDDATAREDZ, BDNUMCUPINI, BDNUMCUPFIN, BDPOSCRO, BDPOSCRZ, BDNUMCOO, BDVALGTFINAL, BDVALVENBRU,
                            BDCODUSU, BDCODTIPO, BDDATALAN, BDHORALAN, BDNAOINCIDICMS, BDSTICMS, BDISENTASICMS, BDISSQN, BDALIQISSQN, BDISENTASISS,
                            BDNAOINCIDISS, BDVALOPNFISCAIS, BDVALCANCOPNFISCAIS, BDVALACREOPNFISCAIS, BDVALDESCOPNFISCAIS, BDVALIOF, BDVALCANCICMS,
                            BDVALACREICMS, BDVALDESCICMS, BDVALCANCISSQN, BDVALACREISSQN, BDVALDESCISSQN, BDREFLAN, BDCODSTATUSLAN, BDDATAINCLUSAO,
                            BDHORAINCLUSAO, BDCODUSUINCLU, BDTIPOLANINCLU)
  SELECT R.BDCODEMP, R.BDEDITCHAVE, R.BDORDEMMAQ, R.BDDATAREDZ, R.BDNUMCUPINI, R.BDNUMCUPFIN, R.BDPOSCRO, R.BDPOSCRZ, R.BDNUMCOO, R.BDVALGTFINAL, R.BDVALVENBRU,
         R.BDCODUSU, R.BDCODTIPO, R.BDDATALAN, R.BDHORALAN, R.BDNAOINCIDICMS, R.BDSTICMS, R.BDISENTASICMS, R.BDISSQN, R.BDALIQISSQN, R.BDISENTASISS,
         R.BDNAOINCIDISS, R.BDVALOPNFISCAIS, R.BDVALCANCOPNFISCAIS, R.BDVALACREOPNFISCAIS, R.BDVALDESCOPNFISCAIS, R.BDVALIOF, R.BDVALCANCICMS,
         R.BDVALACREICMS, R.BDVALDESCICMS, R.BDVALCANCISSQN, R.BDVALACREISSQN, R.BDVALDESCISSQN, R.BDREFLAN, R.BDCODSTATUSLAN, R.BDDATAINCLUSAO,
         R.BDHORAINCLUSAO, R.BDCODUSUINCLU, R.BDTIPOLANINCLU
  FROM TMP_VEF_EMP_TREDZ_TEMP R
  WHERE R.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT BDCODINCONSISTENCIA
                 FROM VEF_INCON_TREDZ I
                 WHERE I.BDSESSAO = R.BDSESSAO
                 AND I.BDCODEMP = R.BDCODEMP
                 AND I.BDCHAVE = R.BDCHAVE
                );

  INSERT INTO VEF_EMP_TREDZC490(BDCODEMP, BDCHAVE, BDORDEMTOT, BDCODOBS, BDCODNAT, BDCODCSTICMS, BDALIQTOT, BDVLROPER, BDBASEICMS, BDVLRICMS)
  SELECT C.BDCODEMP, C.BDEDITCHAVE BDCHAVE, C.BDORDEMTOT, C.BDALTCODOBS BDCODOBS, C.BDCODNAT, C.BDCODCSTICMS, C.BDALIQTOT, C.BDVLROPER, C.BDBASEICMS, C.BDVLRICMS
  FROM TMP_VEF_EMP_TREDZC490_TEMP C
  WHERE C.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT BDCODINCONSISTENCIA
                 FROM VEF_INCON_TREDZ I
                 WHERE I.BDSESSAO = C.BDSESSAO
                 AND I.BDCODEMP = C.BDCODEMP
                 AND I.BDCHAVE = C.BDCHAVE
                );

  /*Váris aliquotas*/
  INSERT INTO VEF_EMP_TREDZVARALIQ(BDCODEMP, BDCHAVE, BDORDEMICMS, BDBASEICMS, BDREDBCICMS, BDBASEREDICMS, BDALIQICMS, BDVLRICMS, BDISENTASICMS, BDOUTRASICMS)
  SELECT VA.BDCODEMP, VA.BDEDITCHAVE BDCHAVE, VA.BDORDEMICMS, VA.BDBASEICMS, VA.BDREDBCICMS, VA.BDBASEREDICMS, VA.BDALIQICMS, VA.BDVLRICMS, VA.BDISENTASICMS, VA.BDOUTRASICMS
  FROM TMP_VEF_EMP_TREDZVARALIQ_TEMP VA
  WHERE VA.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT BDCODINCONSISTENCIA
                 FROM VEF_INCON_TREDZ I
                 WHERE I.BDSESSAO = VA.BDSESSAO
                 AND I.BDCODEMP = VA.BDCODEMP
                 AND I.BDCHAVE = VA.BDCHAVE
                );

  /*Várias CFOP's*/
  INSERT INTO VEF_EMP_TREDZVARCFOP(BDCODEMP, BDCHAVE, BDORDEMVARCFOP, BDCODNAT, BDCONDPGTO,
                                   BDREDBCICMS, BDBASEICMS, BDALIQICMS, BDVLRICMS, BDISENTASICMS,
                                   BDOUTRASICMS, BDBASEST, BDALIQST, BDVLRST, BDVLRCONTAB,
                                   BDVLRPIS, BDVLRCOFINS, BDCODTER, BDCODOBS, BDOBSERVACAO,BDBASEISS,BDVLRISS,BDALIQISS)
  SELECT V.BDCODEMP, V.BDEDITCHAVE BDCHAVE, V.BDORDEMVARCFOP, V.BDCODNAT, V.BDCONDPGTO,
         V.BDREDBCICMS, V.BDBASEICMS, V.BDALIQICMS, V.BDVLRICMS, V.BDISENTASICMS,
         V.BDOUTRASICMS, V.BDBASEST, V.BDALIQST, V.BDVLRST, V.BDVLRCONTAB,
         V.BDVLRPIS, V.BDVLRCOFINS, V.BDCODTER, V.BDCODOBS, V.BDOBSERVACAO,
         V.BDBASEISS, V.BDVLRISS, V.BDALIQISS
  FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP V
  WHERE V.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT BDCODINCONSISTENCIA
                 FROM VEF_INCON_TREDZ I
                 WHERE I.BDSESSAO = V.BDSESSAO
                 AND I.BDCODEMP = V.BDCODEMP
                 AND I.BDCHAVE = V.BDCHAVE
                );

  /*Simples nacional*/
  INSERT INTO VEF_EMP_TREDZSN(BDCODEMP, BDCHAVE, BDORDEMVARCFOP, BDORDEMSNREDZ, 
                              BDCODNAT, BDCODATIVSIMPNAC, BDCODCONFSN, BDCODTIPOIMPOSTO,
                              BDCODIMPOSTO, BDCODBASESN, BDVLRBASE,
                              bdCODPLANOCONFSN, bdCODTIPOIMPPIS, bdCODTIPOIMPCOFINS, bdCODTIPOIMPCSLL, bdCODTIPOIMPICMS, -- Alt.: #122601 - Nao estava gravando as informacoes do tipo de tributacao e quando iria apurar, estava levando o tipo de tributacao errada na apuracao. Ex.: Importando base de ICMS ST, estava apurando o ICMS como tributado integralmente e nao como Substituicao...
                              bdCODTIPOIMPINSSCPP, bdCODTIPOIMPIRPJ, bdCODTIPOIMPIPI, bdCODTIPOIMPISS)
  SELECT SN.BDCODEMP, SN.BDEDITCHAVE BDCHAVE, SN.BDORDEMVARCFOP, SN.BDORDEMSNREDZ,
         SN.BDCODNAT, SN.BDCODATIVSIMPNAC, SN.BDCODCONFSN, SN.BDCODTIPOIMPOSTO,
         SN.BDCODIMPOSTO, SN.BDCODBASESN, SN.BDVLRBASE,
         sn.bdCODPLANOCONFSN, sn.bdCODTIPOIMPPIS, sn.bdCODTIPOIMPCOFINS, sn.bdCODTIPOIMPCSLL, sn.bdCODTIPOIMPICMS,
         sn.bdCODTIPOIMPINSSCPP, sn.bdCODTIPOIMPIRPJ, sn.bdCODTIPOIMPIPI, sn.bdCODTIPOIMPISS
  FROM TMP_VEF_EMP_TREDZSN_TEMP SN
  WHERE SN.BDSESSAO = :PRSESSAO
  /*#124321 - Colocado essa verificação pq nos casos que dava erro em algum produto, ele n importa o lançamento de red z e se arrumado no grid o erro do produto
   e importado novamente,ficava na tabela do SN os registros que haviam sido importados mas com o Edit Chave nulo e aí dava erro de FK*/
  AND SN.BDEDITCHAVE IS NOT NULL
  AND NOT EXISTS(
                 SELECT BDCODINCONSISTENCIA
                 FROM VEF_INCON_TREDZ I
                 WHERE I.BDSESSAO = SN.BDSESSAO
                 AND I.BDCODEMP = SN.BDCODEMP
                 AND I.BDCHAVE = SN.BDCHAVE
                );

  /*C425*/
  INSERT INTO VEF_EMP_TREDZC425 (BDCODEMP, BDCHAVE, BDORDEMTOT, BDORDEMC425, BDCODCSTCOF, BDCODCSTPIS,
                                 BDCODNATREC, BDCODPROD, BDQTDACU, BDVLRACU, BDVLRPIS, BDVL_BC_PIS,
                                 BDALIQ_PIS, BDQUANT_BC_PIS, BDALIQ_PIS_QUANT, BDVL_BC_COFINS, BDALIQ_COFINS,
                                 BDQUANT_BC_COFINS, BDALIQ_COFINS_QUANT, BDNUMTOT, BDVLRCOFINS, BDCODNAT,
                                 BDCODCSTICMS, BDALIQTOT, BDBASEICMS, BDVLRICMS, BDCODOBS, BDCODCID)
  SELECT C.BDCODEMP, C.BDEDITCHAVE BDCHAVE, C.BDORDEMTOT, C.BDORDEMC425, C.BDCODCSTCOF, C.BDCODCSTPIS,
         C.BDCODNATREC, C.BDALTCODPROD BDCODPROD, C.BDQTDACU, C.BDVLRACU, C.BDVLRPIS, C.BDVL_BC_PIS,
         C.BDALIQ_PIS, C.BDQUANT_BC_PIS, C.BDALIQ_PIS_QUANT, C.BDVL_BC_COFINS, C.BDALIQ_COFINS,
         C.BDQUANT_BC_COFINS, C.BDALIQ_COFINS_QUANT, C.BDNUMTOT, C.BDVLRCOFINS, C.BDCODNAT,
         C.BDCODCSTICMS, C.BDALIQTOT, C.BDBASEICMS, C.BDVLRICMS, C.BDCODOBS, C.BDCODCID
  FROM TMP_VEF_EMP_TREDZC425_TEMP C
  WHERE C.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT BDCODINCONSISTENCIA
                 FROM VEF_INCON_TREDZ I
                 WHERE I.BDSESSAO = C.BDSESSAO
                 AND I.BDCODEMP = C.BDCODEMP
                 AND I.BDCHAVE = C.BDCHAVE
                );

  /*C425 - Várias alíquotas*/
  INSERT INTO VEF_EMP_TREDZC425ALIQ(BDORDEMTOT, BDCODEMP, BDCHAVE, BDORDEMICMS, BDORDEMC425, BDCODPROD,
                                    BDCODNATREC, BDCODCSTCOF, BDCODCSTPIS, BDQTDACU, BDVLRACU, BDVLRPIS,
                                    BDVL_BC_PIS, BDALIQ_PIS, BDQUANT_BC_PIS, BDALIQ_PIS_QUANT, BDVL_BC_COFINS,
                                    BDALIQ_COFINS, BDQUANT_BC_COFINS, BDALIQ_COFINS_QUANT, BDNUMTOT, BDVLRCOFINS,
                                    BDCODNAT, BDCODCSTICMS, BDALIQTOT, BDBASEICMS, BDVLRICMS, BDCODOBS, BDCODCID)
  SELECT A.BDORDEMTOT, A.BDCODEMP, A.BDEDITCHAVE, A.BDORDEMICMS, A.BDORDEMC425, A.BDALTCODPROD BDCODPROD,
         A.BDCODNATREC, A.BDCODCSTCOF, A.BDCODCSTPIS, A.BDQTDACU, A.BDVLRACU, A.BDVLRPIS,
         A.BDVL_BC_PIS, A.BDALIQ_PIS, A.BDQUANT_BC_PIS, A.BDALIQ_PIS_QUANT, A.BDVL_BC_COFINS,
         A.BDALIQ_COFINS, A.BDQUANT_BC_COFINS, A.BDALIQ_COFINS_QUANT, A.BDNUMTOT, A.BDVLRCOFINS,
         A.BDCODNAT, A.BDCODCSTICMS, A.BDALIQTOT, A.BDBASEICMS, A.BDVLRICMS, A.BDCODOBS, A.BDCODCID
  FROM TMP_VEF_EMP_TREDZC425ALIQ_TEMP A
  JOIN VEF_EMP_TREDZVARALIQ VARALIQ ON(VARALIQ.BDCODEMP = A.BDCODEMP AND VARALIQ.BDCHAVE = A.BDEDITCHAVE AND VARALIQ.BDORDEMICMS = A.BDORDEMICMS)  
  WHERE A.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT BDCODINCONSISTENCIA
                 FROM VEF_INCON_TREDZ I
                 WHERE I.BDSESSAO = A.BDSESSAO
                 AND I.BDCODEMP = A.BDCODEMP
                 AND I.BDCHAVE = A.BDCHAVE
                );

  /*60I*/
  INSERT INTO VEF_EMP_TREDZ60I(BDCODEMP, BDCHAVE, BDORDEM60I, BDNUMCOO, BDCODPROD, BDCODCSTICMS,
                               BDQUANTIDADE, BDVALORUNITARIO, BDBASECALCICMS, BDVLRICMS, BDALIQICMS)
  SELECT R60I.BDCODEMP, R60I.BDEDITCHAVE BDCHAVE, R60I.BDORDEM60I, R60I.BDNUMCOO, R60I.BDALTCODPROD BDCODPROD,
         R60I.BDCODCSTICMS, R60I.BDQUANTIDADE, R60I.BDVALORUNITARIO, R60I.BDBASECALCICMS, R60I.BDVLRICMS, R60I.BDALIQICMS
  FROM TMP_VEF_EMP_TREDZ60I_TEMP R60I
  WHERE R60I.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT BDCODINCONSISTENCIA
                 FROM VEF_INCON_TREDZ I
                 WHERE I.BDSESSAO = R60I.BDSESSAO
                 AND I.BDCODEMP = R60I.BDCODEMP
                 AND I.BDCHAVE = R60I.BDCHAVE
                );

  /*DOC ECF - C460*/
  INSERT INTO VEF_EMP_TDOCECF(BDCODEMP, BDCHAVE, BDORDEMDOCECF, BDCODSITNF, BDCODDOCFIS, BDCODTER, BDDATAEMI, 
                              BDNUMDOCCOO, BDVALTOT, BDVALPIS, BDVALCOFINS, BDDESCONTOTOT, BDACRESCIMOTOT)
  SELECT D.BDCODEMP, D.BDEDITCHAVE BDCHAVE, D.BDORDEMDOCECF, D.BDCODSITNF, D.BDCODDOCFIS, D.BDALTCODTER BDCODTER,
         D.BDDATAEMI, D.BDNUMDOCCOO, D.BDVALTOT, D.BDVALPIS, D.BDVALCOFINS, D.BDDESCONTOTOT, D.BDACRESCIMOTOT
  FROM TMP_VEF_EMP_TDOCECF_TEMP D
  WHERE D.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT BDCODINCONSISTENCIA
                 FROM VEF_INCON_TREDZ I
                 WHERE I.BDSESSAO = D.BDSESSAO
                 AND I.BDCODEMP = D.BDCODEMP
                 AND I.BDCHAVE = D.BDCHAVE
                );

  /*ITEM DOC ECF - C470*/
  INSERT INTO VEF_EMP_TITEMDOCECF(BDCODEMP, BDCHAVE, BDORDEMDOCECF, BDORDEMITEM, BDCODPRODFATCON,
                                  BDCODFATCON, BDCODPROD, BDCODNAT, BDCODCSTICMS, BDQTDITEM, BDQTDITEMCAN,
                                  BDVLRTOTPRO, BDALIQICMS, BDVLRPIS, BDVLRCOFINS, BDCODCSTCOF, BDCODCSTPIS,
                                  BDCODNATREC, BDVL_BC_PIS, BDALIQ_PIS, BDQUANT_BC_PIS, BDALIQ_PIS_QUANT,
                                  BDVL_BC_COFINS, BDALIQ_COFINS, BDQUANT_BC_COFINS, BDALIQ_COFINS_QUANT, BDVLRICMS, BDICMSEFETIVO)
  SELECT IT.BDCODEMP, IT.BDEDITCHAVE BDCHAVE, IT.BDORDEMDOCECF, IT.BDORDEMITEM, IT.BDCODPRODFATCON,
         IT.BDCODFATCON, IT.BDALTCODPROD BDCODPROD, IT.BDCODNAT, IT.BDCODCSTICMS, IT.BDQTDITEM,
         IT.BDQTDITEMCAN, IT.BDVLRTOTPRO, IT.BDALIQICMS, IT.BDVLRPIS, IT.BDVLRCOFINS, IT.BDCODCSTCOF,
         IT.BDCODCSTPIS, IT.BDCODNATREC, IT.BDVL_BC_PIS, IT.BDALIQ_PIS, IT.BDQUANT_BC_PIS,
         IT.BDALIQ_PIS_QUANT, IT.BDVL_BC_COFINS, IT.BDALIQ_COFINS, IT.BDQUANT_BC_COFINS,
         IT.BDALIQ_COFINS_QUANT, IT.BDVLRICMS, IT.BDICMSEFETIVO
  FROM TMP_VEF_EMP_TITEMDOCECF_TEMP IT
  JOIN VEF_EMP_TDOCECF D ON(D.BDCODEMP = IT.BDCODEMP AND D.BDCHAVE = IT.BDEDITCHAVE AND D.bdordemdocecf = IT.bdordemdocecf)
  WHERE IT.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT BDCODINCONSISTENCIA
                 FROM VEF_INCON_TREDZ I
                 WHERE I.BDSESSAO = IT.BDSESSAO
                 AND I.BDCODEMP = IT.BDCODEMP
                 AND I.BDCHAVE = IT.BDCHAVE
                );

  /*C480*/
  INSERT INTO VEF_EMP_TMOVC480_1250(BDCODEMP, BDCHAVE, BDORDEMDOCECF, BDORDEMITEM, BDNUMDOCCOO,
                                  BDDATAREDZ, BDCODMOTIVO, BDQTDCONVERTIDA, BDVLRUNICONVERTIDO, BDVLRUNITICMSEFETIVO, BDVLRUNITICMSOPESTOQUE,
                                  BDVLRUNITICMSSTESTOQUE, BDVLRUNITICMSSTRESTITUIR, BDVLRUNITICMSSTCOMPLEMENTAR, BDCODUNIMED, BDVLRUNITICMSOP, BDVLRUNITFCPSTESTOQUE,
                                  BDVLRUNITFCPSTRESTITUIR, BDVLRUNITFCPSTCOMPLEMENTAR, BDTIPOLANCAMENTO)
  SELECT IT.BDCODEMP, IT.BDEDITCHAVE BDCHAVE, IT.BDORDEMDOCECF, IT.BDORDEMITEM, IT.BDNUMDOCCOO,
         IT.BDDATAREDZ, IT.BDCODMOTIVO, IT.BDQTDCONVERTIDA, IT.BDVLRUNICONVERTIDO, IT.BDVLRUNITICMSEFETIVO,
         IT.BDVLRUNITICMSOPESTOQUE, IT.BDVLRUNITICMSSTESTOQUE, IT.BDVLRUNITICMSSTRESTITUIR, IT.BDVLRUNITICMSSTCOMPLEMENTAR, IT.BDCODUNIMED, IT.BDVLRUNITICMSOP,
         IT.BDVLRUNITFCPSTESTOQUE, IT.BDVLRUNITFCPSTRESTITUIR, IT.BDVLRUNITFCPSTCOMPLEMENTAR, IT.BDTIPOLANCAMENTO
  FROM TMP_VEF_EMP_TMOVC480_1250_TEMP IT
  JOIN VEF_EMP_TDOCECF D ON(D.BDCODEMP = IT.BDCODEMP AND D.BDCHAVE = IT.BDEDITCHAVE AND D.bdordemdocecf = IT.bdordemdocecf)
  WHERE IT.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT BDCODINCONSISTENCIA
                 FROM VEF_INCON_TREDZ I
                 WHERE I.BDSESSAO = IT.BDSESSAO
                 AND I.BDCODEMP = IT.BDCODEMP
                 AND I.BDCHAVE = IT.BDCHAVE
                );

  /*Várias Alíquotas ISS */

  INSERT INTO VEF_EMP_TREDZVARALIQISS(BDCODEMP, BDCHAVE, BDORDEMISS, BDBASEISS, BDREDBCISS, BDBASEREDISS, BDALIQISS, BDVLRISS, BDISENTASISS, BDOUTRASISS)
  SELECT VA.BDCODEMP, VA.BDEDITCHAVE BDCHAVE, VA.BDORDEMISS, VA.BDBASEISS, VA.BDREDBCISS, VA.BDBASEREDISS, VA.BDALIQISS, VA.BDVLRISS, VA.BDISENTASISS, VA.BDOUTRASISS
  FROM TMP_VEF_EMP_TREDZVARALIISS_TEMP VA
  WHERE VA.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT BDCODINCONSISTENCIA
                 FROM VEF_INCON_TREDZ I
                 WHERE I.BDSESSAO = VA.BDSESSAO
                 AND I.BDCODEMP = VA.BDCODEMP
                 AND I.BDCHAVE = VA.BDCHAVE
                );

  /*C425 - Várias Alíquotas ISS */

  INSERT INTO VEF_EMP_TREDZC425ALIQISS(BDORDEMTOT, BDCODEMP, BDCHAVE, BDORDEMISS, BDORDEMC425, BDCODPROD,
                                    BDCODNATREC, BDCODCSTCOF, BDCODCSTPIS, BDQTDACU, BDVLRACU, BDVLRPIS,
                                    BDVL_BC_PIS, BDALIQ_PIS, BDQUANT_BC_PIS, BDALIQ_PIS_QUANT, BDVL_BC_COFINS,
                                    BDALIQ_COFINS, BDQUANT_BC_COFINS, BDALIQ_COFINS_QUANT, BDNUMTOT, BDVLRCOFINS,
                                    BDCODNAT, BDALIQTOT, BDBASEISS, BDVLRISS, BDCODOBS, BDCODCID)
  SELECT A.BDORDEMTOT, A.BDCODEMP, A.BDEDITCHAVE, A.BDORDEMISS, A.BDORDEMC425, A.BDALTCODPROD BDCODPROD,
         A.BDCODNATREC, A.BDCODCSTCOF, A.BDCODCSTPIS, A.BDQTDACU, A.BDVLRACU, A.BDVLRPIS,
         A.BDVL_BC_PIS, A.BDALIQ_PIS, A.BDQUANT_BC_PIS, A.BDALIQ_PIS_QUANT, A.BDVL_BC_COFINS,
         A.BDALIQ_COFINS, A.BDQUANT_BC_COFINS, A.BDALIQ_COFINS_QUANT, A.BDNUMTOT, A.BDVLRCOFINS,
         A.BDCODNAT, A.BDALIQTOT, A.BDBASEISS, A.BDVLRISS, A.BDCODOBS, A.BDCODCID
  FROM TMP_VEF_EMP_TREDZC425AQISS_TEMP A
  JOIN VEF_EMP_TREDZVARALIQISS VARALIQ ON(VARALIQ.BDCODEMP = A.BDCODEMP AND VARALIQ.BDCHAVE = A.BDEDITCHAVE AND VARALIQ.BDORDEMISS = A.BDORDEMISS)
  WHERE A.BDSESSAO = :PRSESSAO
  AND NOT EXISTS(
                 SELECT BDCODINCONSISTENCIA
                 FROM VEF_INCON_TREDZ I
                 WHERE I.BDSESSAO = A.BDSESSAO
                 AND I.BDCODEMP = A.BDCODEMP
                 AND I.BDCHAVE = A.BDCHAVE
                );
  
  /* Centro de Custo */
  INSERT INTO VEF_EMP_TMOVCCREDZ(BDCODEMP, BDCHAVE, BDORDEMVARCFOP, BDORDEMCC, BDCODCENTRO, BDCODTPCC, BDVALOR,
                                 BDPERCENTUAL, BDVLRIMP, BDCODNAT, BDCONDPGTO, BDCODTER, BDDEBCRED)
  SELECT CC.BDCODEMP, CC.BDEDITCHAVE BDCHAVE, CC.BDORDEMVARCFOP, CC.BDORDEMCC, CC.BDCODCENTRO, CC.BDCODTPCC, CC.BDVALOR,
         CC.BDPERCENTUAL, CC.BDVLRIMP, CC.BDCODNAT, CC.BDCONDPGTO, CC.BDCODTER, CC.BDDEBCRED
  FROM TMP_VEF_EMP_TMOVCCREDZ_TEMP CC
  WHERE CC.BDSESSAO = :PRSESSAO
  AND CC.BDEDITCHAVE IS NOT NULL
  AND NOT EXISTS(
                 SELECT BDCODINCONSISTENCIA
                 FROM VEF_INCON_TREDZ I
                 WHERE I.BDSESSAO = CC.BDSESSAO
                 AND I.BDCODEMP = CC.BDCODEMP
                 AND I.BDCHAVE = CC.BDCHAVE
                );
END^

CREATE OR ALTER procedure SP_LIMPA_TABELAS
as
begin
  /*Sol: 14207 Patrick T. Sá 03/02/2017. Quando for limpada alguma tabela na inicialização/reinicialização do servidor deve ser usada essa stored procedure*/
  
  DELETE FROM TCONTAS_ONLINE_TEMP WHERE BDSESSAO IS NOT NULL;
  DELETE FROM TMP_TCFOP_TMOV WHERE BDSESSAO IS NOT NULL;
end^

CREATE OR ALTER trigger tmp_vef_emp_tredzvarcfop_tempch for tmp_vef_emp_tredzvarcfop_temp
active before update position 0
AS
DECLARE VARIABLE wComplemento VARCHAR(1000);
DECLARE VARIABLE wVar         VARCHAR(200);
DECLARE VARIABLE wValue       VARCHAR(100);
DECLARE VARIABLE wNumCupIni   INTEGER;
DECLARE VARIABLE wNumCupFin   INTEGER;
DECLARE VARIABLE wPosCRZ      INTEGER;
DECLARE VARIABLE wDataRedZ    DATE;
DECLARE VARIABLE wPos         INTEGER;
DECLARE VARIABLE wPosUltDel   INTEGER;
BEGIN
  /*Joga a chave do contábil na tabela*/
  IF (COALESCE(NEW.BDCHAVE_VSUC, 0) > 0) THEN
    BEGIN
      NEW.BDCHAVE_VSUC = (NEW.BDCHAVE_VSUC - (OLD.BDCHAVE))+1;
    END

  IF (COALESCE(NEW.BDTRANSACAO, 0) > 0) THEN
    BEGIN
      NEW.BDTRANSACAO = (NEW.BDTRANSACAO - (OLD.BDCHAVE))+1;
      EXIT;
    END

  wComplemento = NULL;
  IF ((COALESCE(NEW.BDCOMPHIST_VLRCONTAB, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRCONTAB) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRCONTAB||' ';
  ELSE
  IF ((COALESCE(NEW.BDCOMPHIST_VLRPIS, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRPIS) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRPIS||' ';
  ELSE
  IF ((COALESCE(NEW.BDCOMPHIST_VLRICMS, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRICMS) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRICMS||' ';
  ELSE
  IF ((COALESCE(NEW.BDCOMPHIST_VLRICMSST, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRICMSST) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRICMSST||' ';
  ELSE
  IF ((COALESCE(NEW.BDCOMPHIST_VLRCOFINS, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRCOFINS) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRCOFINS||' ';
  ELSE
  IF ((COALESCE(NEW.BDCOMPHIST_VLRDESCONTO, '') <> '') AND (POSITION('*', NEW.BDCOMPHIST_VLRDESCONTO) > 0))  THEN
    wComplemento = NEW.BDCOMPHIST_VLRDESCONTO||' ';
  ELSE
    EXIT;

  SELECT R.BDNUMCUPINI, R.BDNUMCUPFIN, R.BDPOSCRZ, R.BDDATAREDZ
  FROM TMP_VEF_EMP_TREDZ_TEMP R
  WHERE R.BDSESSAO = OLD.BDSESSAO
  AND R.BDCODEMP = OLD.BDCODEMP
  AND R.BDCHAVE = OLD.BDCHAVE
  INTO :wNumCupIni, :wNumCupFin, :wPosCrz, :wDataRedZ;

  WHILE (POSITION('*', :wComplemento) > 0) DO
    BEGIN
      wPosUltDel = 1000;
      wPos = POSITION(' ', SUBSTRING(:wComplemento FROM (POSITION('*', :wComplemento)) FOR CHAR_LENGTH(:wComplemento))); -- Não tem o -1 porque é um espaço, o Trim já remove ele.
      wPosUltDel = POSITION(',', SUBSTRING(:wComplemento FROM (POSITION('*', :wComplemento)) FOR CHAR_LENGTH(:wComplemento)))-1; -- -1 para não pegar a , junto

      IF ((:wPosUltDel > 0) AND (wPosUltDel < :wPos)) THEN
        wPos = :wPosUltDel;

      wPosUltDel = 1000;
      wPosUltDel = POSITION('.', SUBSTRING(:wComplemento FROM (POSITION('*', :wComplemento)) FOR CHAR_LENGTH(:wComplemento)))-1; -- -1 para não pegar o . junto

      IF ((:wPosUltDel > 0) AND (wPosUltDel < :wPos)) THEN
        wPos = :wPosUltDel;

      wVar = TRIM(SUBSTRING(:wComplemento FROM (POSITION('*', :wComplemento)) FOR :wPos));
      IF (:wVar = '*NECF') THEN
        wValue = COALESCE(OLD.BDNRMAQ, 0);
      ELSE
      IF ((:wVar = '*CFINI') OR (:wVar = '*NRDOC')) THEN
        wValue = COALESCE(:wNumCupIni, 0);
      ELSE
      IF ((:wVar = '*CFFIM') OR (:wVar = '*NRDOCATE')) THEN
        wValue = COALESCE(:wNumCupFin, 0);
      ELSE
      IF (:wVar = '*REZD') THEN
        wValue = COALESCE(:wPosCrz, 0);
      ELSE
      IF (:wVar = '*VLRNF') THEN
        wValue = COALESCE(OLD.BDVLRCONTAB, 0);
      ELSE
      IF (:wVar = '*ESPECIE') THEN
        wValue = COALESCE(OLD.BDESPECIE, '');
      ELSE
      IF (:wVar = '*SERIE') THEN
        wValue = COALESCE(OLD.BDSERIE, '');
      ELSE
      IF (:wVar = '*CFOP') THEN
        wValue = (SUBSTRING(OLD.BDCODNAT FROM 1 FOR 1)||'.'||SUBSTRING(OLD.BDCODNAT FROM 2 FOR 3)||'-'||SUBSTRING(OLD.BDCODNAT FROM 5 FOR 3));
      ELSE
      IF (:wVar = '*DATAEMISSAO') THEN
        wValue = :wDataRedZ;
      ELSE
      IF (:wVar = '*APELIDOPART') THEN
        wValue = COALESCE(OLD.BDAPELIDOTER, '');
      ELSE
      IF (:wVar = '*NOMEPART') THEN
        wValue = COALESCE(OLD.BDNOMETER, '');
      ELSE
      IF (:wVar = '*CNPJPART') THEN
        wValue = COALESCE(OLD.BDCGCTER, '');
      ELSE
      IF (:wVar = '*NOMCIDPART') THEN
        wValue = COALESCE(OLD.BDNOMCIDPART, '');
      ELSE
        EXIT; /*Se não encontrar a variável sai do while, senão fica em looping infinito*/

--      wComplemento = SUBSTRING(:wComplemento FROM 1 FOR (POSITION('*', :wComplemento)-1))||COALESCE(:wValue, wVar)||SUBSTRING(:wComplemento FROM (POSITION(' ', SUBSTRING(:wComplemento FROM (POSITION('*', :wComplemento)) FOR CHAR_LENGTH(:wComplemento)))+POSITION('*', :wComplemento)-1) FOR CHAR_LENGTH(:wComplemento));
      wComplemento = REPLACE(:wComplemento, :wVar, :wValue);
      wVar   = NULL;
      wValue = NULL;
    END

  IF (((NEW.BDCOMPHIST_VLRCONTAB <> '') OR (NEW.BDCOMPHIST_VLRCONTAB IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRCONTAB) AND (POSITION('*', NEW.BDCOMPHIST_VLRCONTAB) > 0))  THEN
    NEW.BDCOMPHIST_VLRCONTAB = :wComplemento;
  ELSE
  IF (((NEW.BDCOMPHIST_VLRPIS <> '') OR (NEW.BDCOMPHIST_VLRPIS IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRPIS) AND (POSITION('*', NEW.BDCOMPHIST_VLRPIS) > 0))  THEN
    NEW.BDCOMPHIST_VLRPIS = :wComplemento;
  ELSE
  IF (((NEW.BDCOMPHIST_VLRICMS <> '') OR (NEW.BDCOMPHIST_VLRICMS IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRICMS) AND (POSITION('*', NEW.BDCOMPHIST_VLRICMS) > 0))  THEN
    NEW.BDCOMPHIST_VLRICMS = :wComplemento;
  ELSE
  IF (((NEW.BDCOMPHIST_VLRICMSST <> '') OR (NEW.BDCOMPHIST_VLRICMSST IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRICMSST) AND (POSITION('*', NEW.BDCOMPHIST_VLRICMSST) > 0))  THEN
    NEW.BDCOMPHIST_VLRICMSST = :wComplemento;
  ELSE
  IF (((NEW.BDCOMPHIST_VLRCOFINS <> '') OR (NEW.BDCOMPHIST_VLRCOFINS IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRCOFINS) AND (POSITION('*', NEW.BDCOMPHIST_VLRCOFINS) > 0))  THEN
    NEW.BDCOMPHIST_VLRCOFINS = :wComplemento;
  ELSE
  IF (((NEW.BDCOMPHIST_VLRDESCONTO <> '') OR (NEW.BDCOMPHIST_VLRDESCONTO IS NOT NULL)) AND (:wComplemento <> NEW.BDCOMPHIST_VLRDESCONTO) AND (POSITION('*', NEW.BDCOMPHIST_VLRDESCONTO) > 0))  THEN
    NEW.BDCOMPHIST_VLRDESCONTO = :wComplemento;
END^

CREATE OR ALTER trigger tmp_vef_emp_tmovk270_temp_gk for tmp_vef_emp_tmovk270_temp
active before update position 0
AS
BEGIN
  IF ((OLD.BDEDITCHAVE IS NULL) AND (NEW.BDEDITCHAVE > 0)) THEN
    BEGIN
      NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - OLD.BDCHAVE)+1;
    END
END^

CREATE OR ALTER procedure SP_LANCA_AJUSTE_E115 (
    PRSESSAO integer)
as
declare variable WCODUF integer;
declare variable WCODEMP integer;
declare variable WCODPLAE115 integer;
declare variable WCODPLAE115REF integer;
BEGIN
  FOR
      SELECT DISTINCT(BDCODEMP) FROM TMP_VEF_EMP_TMOVSAI_TEMP WHERE BDSESSAO = :PRSESSAO INTO :wCODEMP
  DO
    BEGIN
      SETORDEMSEQUENCIAL(1);

      SELECT e.BDCODPLAE115 FROM VW_VEF_BASE_TEMPPARINTEG e WHERE e.BDCODEMP = :wCODEMP INTO :wCODPLAE115REF;

      IF (:wCODPLAE115REF > 0) THEN /* Se a empresa tiver um plano de importacao E115 cadastrado usa este... */
        SELECT pla.BDCODPLAE115 FROM VEF_BASE_TPLAIMPE115 pla
        WHERE (pla.BDCODPLAE115 = :wCODPLAE115REF)
          AND (pla.bdexecplano = 0) /*Nota a nota*/
        INTO :wCODPLAE115;
      ELSE /* ...Caso contrario buscar o plano default */
        SELECT pla.BDCODPLAE115 FROM VEF_BASE_TPLAIMPE115 pla
        WHERE (pla.BDPLANODEFAULT = 'TRUE')
          AND (pla.bdexecplano = 0) /*Nota a nota*/
        INTO :wCODPLAE115;

      IF (:wCODPLAE115 > 0) THEN
        BEGIN
          SELECT uf.BDCODUF
          FROM VW_EMPRESAS_REF_ATUAL ref
          JOIN TCIDADE cid ON (cid.BDCODCID = ref.BDCODCID)
          JOIN TUF uf ON (uf.BDCODUF = cid.BDCODUF)
          WHERE ref.BDCODEMP = :wCODEMP
          INTO :wCODUF;

          IF (:wCODUF = 23) THEN
            BEGIN
              /* Lançamentos de ajuste do E115 na tabela temporária */
          INSERT INTO TMP_VEF_EMP_TAJUICMSE115_TEMP (BDCODEMP, BDORDEME115, BDREFERENCIA, BDVLRINFADI, BDDESCINFADI, BDCODTIPO, BDORDEM52, BDCHAVESAI, BDORDEM, BDSESSAO, BDEDITCHAVE)
          SELECT mov.BDCODEMP, GETORDEMSEQUENCIAL_STR('E115.'||MOV.BDCODEMP, MOV.BDCODEMP),                                                                                                                                  -- BDCODEMP
                /* (COALESCE((SELECT MAX(BDORDEME115)+1 FROM TMP_VEF_EMP_TAJUICMSE115_TEMP l WHERE l.BDCODEMP = mov.BDCODEMP),1)),*/                                 -- BDORDEME115
                 COALESCE(mov.BDREFLAN,CAST(EXTRACT(YEAR FROM mov.bdDATAEMISSAO)||LPAD(EXTRACT(MONTH FROM mov.bdDATAEMISSAO), 2, '0') AS INTEGER)),              -- BDREFERENCIA
                 CASE WHEN (gia.BDCODCAMPOGIARS = 1) THEN i.BDVLRIPI        -- IPI
                      WHEN (gia.BDCODCAMPOGIARS = 2) THEN i.BDVLRST         -- Substituição tributária
                      WHEN (gia.BDCODCAMPOGIARS = 3) THEN i.BDISENTASICMS   -- Isentas
                      WHEN (gia.BDCODCAMPOGIARS = 4) THEN i.BDOUTRASICMS    -- Outras
                          ELSE i.BDVLRCONTAB                                    -- Frete e Exclusões                                                                 -- BDVLRINFADI
                 END,
                 SUBSTRING(i.BDCODNAT FROM 1 FOR 4)||', documento '||mov.BDNUMDOCINI||' '||
                           SUBSTRING(acao.BDINFCOMP FROM 1 FOR (255-StrLen(SUBSTRING(i.BDCODNAT FROM 1 FOR 4)||', documento '||mov.BDNUMDOCINI||' '))),          -- BDDESCINFADI
                 100,                                                                                                                                            -- BDCODTIPO
                 acao.BDORDEM52,                                                                                                                                 -- BDORDEM52
                 i.BDCHAVE,                                                                                                                                      -- BDCHAVESAI
                 i.BDORDEM,                                                                                                                                      -- BDORDEM
                 :prSESSAO,                                                                                                                                      -- BDSESSAO
                 0--(COALESCE((SELECT MAX(BDORDEME115)+1 FROM TMP_VEF_EMP_TAJUICMSE115_TEMP l WHERE l.BDCODEMP = mov.BDCODEMP),1))                               -- BDEDITCHAVE
          FROM (
                 SELECT m.BDCODEMP, m.BDREFLAN, m.BDCHAVE,
                  m.BDSESSAO, m.BDNUMDOCINI, m.bdDATAEMISSAO
                 FROM TMP_VEF_EMP_TMOVSAI_TEMP m
                 LEFT OUTER JOIN VEF_INCON_TMOVSAI inc ON (inc.BDCODEMP = m.BDCODEMP AND inc.BDCHAVE = m.BDCHAVE AND inc.BDSESSAO = m.BDSESSAO)
                     WHERE m.BDSESSAO = :prSESSAO
                       AND m.BDCODEMP = :wCODEMP
                       AND inc.BDCODINCONSISTENCIA IS NULL -- Só grava os lançamento que não estejam inconsistentes...
    
                ) mov
          JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP i ON (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE AND i.BDSESSAO = mov.BDSESSAO)
          JOIN VEF_BASE_TACOESIMPE115 acao ON (acao.BDCODPLAE115 = :wCODPLAE115 AND acao.BDCODNAT = i.BDCODNAT)
          LEFT OUTER JOIN VEF_BASE_TTABINFAD52 gia ON (gia.BDORDEM52 = acao.BDORDEM52)
              WHERE (((gia.BDCODCAMPOGIARS = 1) AND (i.BDVLRIPI > 0)) OR                                                -- IPI
                 ((gia.BDCODCAMPOGIARS = 2) AND (i.BDVLRST > 0)) OR                                                 -- Substituição tributária
                 ((gia.BDCODCAMPOGIARS = 3) AND (i.BDISENTASICMS > 0)) OR                                           -- Isentas
                 ((gia.BDCODCAMPOGIARS = 4) AND (i.BDOUTRASICMS > 0)) OR                                            -- Outras
                     (((gia.BDCODCAMPOGIARS NOT IN (1, 2, 3, 4)) OR (gia.BDCODCAMPOGIARS IS NULL)) AND (i.BDVLRCONTAB > 0)))  -- Frete e Exclusões
              --ORDER BY mov.BDCODEMP, mov.BDCHAVE, i.BDORDEM;
              ;
        END
    END
    END
END
^

CREATE OR ALTER PROCEDURE SP_GRAVA_AJUSTE_E115 (
    PRSESSAO INTEGER)
AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODPLAE115 INTEGER;
BEGIN
   /***************************************************************************/
   /*******************  Lancamentos agregados das saidas  ********************/
   /***************************************************************************/
   -- Grava lançamentos no ajustes E115
   INSERT INTO VEF_EMP_TAJUICMSE115 (BDCODEMP, BDORDEME115, BDREFERENCIA, BDVLRINFADI, BDDESCINFADI, BDCODTIPO, BDORDEM52)
   SELECT t.BDCODEMP, t.BDEDITCHAVE, t.BDREFERENCIA, t.BDVLRINFADI, t.BDDESCINFADI, t.BDCODTIPO, t.BDORDEM52
   FROM TMP_VEF_EMP_TAJUICMSE115_TEMP t
   JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP i ON (i.BDCODEMP = t.BDCODEMP AND i.BDCHAVE = t.BDCHAVESAI AND i.BDORDEM = t.BDORDEM AND i.BDSESSAO = t.BDSESSAO)
   LEFT OUTER JOIN VEF_INCON_TMOVSAI inc ON (inc.BDCODEMP = i.BDCODEMP AND inc.BDCHAVE = i.BDCHAVE AND inc.BDSESSAO = i.BDSESSAO)
   WHERE t.BDSESSAO = :prSESSAO
     AND t.bdCODTIPO = 100 -- "C_Integracao_escrita_fiscal_EF", lancamentos gerados pela integracao
     AND inc.BDCODINCONSISTENCIA IS NULL -- Apenas lançamentos não inconsistentes...
   ORDER BY i.BDCODEMP, i.BDCHAVE, i.BDORDEM;

   -- Cria lançamento da Tol...
   INSERT INTO TOL_VEF_EMP_TMOVSAIE115 (BDORDEME115, BDCODEMP, BDCHAVE, BDORDEM)
   SELECT t.BDEDITCHAVE, i.BDCODEMP, i.BDEDITCHAVE, i.BDORDEM
   FROM TMP_VEF_EMP_TAJUICMSE115_TEMP t
   JOIN TMP_VEF_EMP_TMOVSAIITENS_TEMP i ON (i.BDCODEMP = t.BDCODEMP AND i.BDCHAVE = t.BDCHAVESAI AND i.BDORDEM = t.BDORDEM AND i.BDSESSAO = t.BDSESSAO)
   LEFT OUTER JOIN VEF_INCON_TMOVSAI inc ON (inc.BDCODEMP = i.BDCODEMP AND inc.BDCHAVE = i.BDCHAVE AND inc.BDSESSAO = i.BDSESSAO)
   WHERE t.BDSESSAO = :prSESSAO
     AND inc.BDCODINCONSISTENCIA IS NULL -- Apenas lançamentos não inconsistentes...
   ORDER BY i.BDCODEMP, i.BDCHAVE, i.BDORDEM;
   
   /***************************************************************************/
   /*******************  Lancamentos importados do arquivo ********************/
   /***************************************************************************/
   -- Grava lançamentos no ajustes E115
   INSERT INTO VEF_EMP_TAJUICMSE115 (bdCODEMP, bdORDEME115, bdREFERENCIA, bdVLRINFADI, bdDESCINFADI, bdCODTIPO, bdORDEM52)
   SELECT t.bdCODEMP, t.bdEDITCHAVE, t.bdREFERENCIA, t.bdVLRINFADI, t.bdDESCINFADI, t.bdCODTIPO, t.bdORDEM52
   FROM TMP_VEF_EMP_TAJUICMSE115_TEMP t
   LEFT OUTER JOIN VEF_INCON_TMOVBLOCOE inc ON (inc.bdSESSAO = t.bdSESSAO AND inc.bdCODEMP = t.bdCODEMP AND inc.bdORDEME115 = t.bdORDEME115)
   WHERE t.BDSESSAO = :prSESSAO
     AND t.bdCODTIPO = 103 -- "C_Sped_ICMS_IPI_EF", lancamentos importados do arquivo do SPED
     AND inc.bdCODINCONSISTENCIA IS NULL -- Apenas lancamentos nao inconsistentes...
   ORDER BY t.bdCODEMP, t.bdEDITCHAVE, t.bdREFERENCIA;
END
^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_TAJUICMSE115 (
    PRSESSAO integer,
    PRULTCHAVE integer)
as
BEGIN
  DELETE FROM VEF_INCON_TMOVBLOCOE e WHERE e.bdSESSAO = :prSESSAO AND ((e.bdORDEME115 IS NOT NULL) AND (e.bdORDEME115 > 0));

  /* Atualiza as descricoes das informacoes */
  UPDATE TMP_VEF_EMP_TAJUICMSE115_TEMP t
  SET t.bdCODINFAD52 = (SELECT inf.bdCODINFAD52 FROM VEF_BASE_TTABINFAD52 inf WHERE inf.bdORDEM52 = t.bdORDEM52),
      t.bdDESC52     = (SELECT inf.bdDESCRICAO  FROM VEF_BASE_TTABINFAD52 inf WHERE inf.bdORDEM52 = t.bdORDEM52)
  WHERE t.bdSESSAO = :prSESSAO
    AND EXISTS(SELECT inf.bdORDEM52
               FROM VEF_BASE_TTABINFAD52 inf
               WHERE inf.bdORDEM52 = t.bdORDEM52);

  -- Atualiza o EDITCHAVE para a chave real que vai usar no lançamento,
  -- vai pegar a última chave cedida pelo servidor e decrementar do sequêncial gerado ao inserir os dados na tabela temporária...
  IF (:PRULTCHAVE > 0) THEN
    BEGIN
      SETORDEMSEQUENCIAL(0);

      UPDATE TMP_VEF_EMP_TAJUICMSE115_TEMP E
      SET E.BDEDITCHAVE = ((:PRULTCHAVE+1) - GETORDEMSEQUENCIAL(1))
      WHERE E.BDSESSAO  = :PRSESSAO;
    END

  /* 191 - Informação AD52 não informada ou inconsistente. */
  INSERT INTO VEF_INCON_TMOVBLOCOE(bdCODEMP, bdSESSAO, bdORDEME115, bdCODINCONSISTENCIA)
  SELECT t.bdCODEMP, t.bdSESSAO, t.bdORDEME115, 191 AS bdCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TAJUICMSE115_TEMP t
  LEFT OUTER JOIN VEF_BASE_TTABINFAD52 inf ON (inf.bdORDEM52 = t.bdORDEM52)
  LEFT OUTER JOIN VW_TEMPRESAS_REF_MAX_MIN emp ON (emp.bdCODEMP = t.bdCODEMP)
  LEFT OUTER JOIN TEMPRESAS_REF ref ON (ref.bdCODEMP = emp.bdCODEMP AND ref.bdREFEMP = emp.bdREFEMP)
  LEFT OUTER JOIN TCIDADE cid ON (cid.bdCODCID = ref.bdCODCID)
  LEFT OUTER JOIN TUF uf ON (uf.bdCODUF = cid.bdCODUF)
  WHERE t.bdSESSAO = :prSESSAO
    AND (((t.bdORDEM52 IS NULL) OR (inf.bdORDEM52 IS NULL)) -- Nao informado
      OR (uf.bdSIGLAUF <> SUBSTRING(inf.bdCODINFAD52 FROM 1 FOR 2))) -- Sufixo diferente do estado da empresa
  GROUP BY t.bdCODEMP, t.bdSESSAO, t.bdORDEME115, bdCODINCONSISTENCIA;

  /* 22 - Lançamento já existente na base de dados. */
  INSERT INTO VEF_INCON_TMOVBLOCOE(bdCODEMP, bdSESSAO, bdORDEME115, bdCODINCONSISTENCIA)
  SELECT t.bdCODEMP, t.bdSESSAO, t.bdORDEME115, 22 AS bdCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TAJUICMSE115_TEMP t
  WHERE t.bdSESSAO = :prSESSAO
    AND (t.bdORDEM52 IS NOT NULL) -- Nao informado
    AND EXISTS(
               SELECT e.bdCODEMP
               FROM VEF_EMP_TAJUICMSE115 e
               WHERE e.bdCODEMP = t.bdCODEMP
                 AND e.bdREFERENCIA = t.bdREFERENCIA
                 AND e.bdORDEM52 = t.bdORDEM52
                 AND e.bdVLRINFADI = t.bdVLRINFADI
                 AND e.bdDESCINFADI = t.bdDESCINFADI
               )
  GROUP BY t.bdCODEMP, t.bdSESSAO, t.bdORDEME115, bdCODINCONSISTENCIA;
END
^

CREATE OR ALTER TRIGGER tatvmunicipal_bu0 FOR tatvmunicipal
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  IF (NEW.bdidcnae = '') THEN
    NEW.bdidcnae = NULL;
  
  if (NEW.BDCODTRIBATVM = '') then
    NEW.BDCODTRIBATVM = NULL;
END^

CREATE OR ALTER PROCEDURE SP_ATUALIZA_DEP_UNIMED (
    PRCHAVE INTEGER,
    PRAPELIDO VARCHAR(5),
    PRDESC VARCHAR(100),
    PRSESSAOUNIMED INTEGER,
    PRSESSAOPRO INTEGER)
AS
DECLARE VARIABLE WCODUNIMED INTEGER;
BEGIN
  wCodUnimed = NULL;
  SELECT FIRST 1 UN.BDCODUNIMED
  FROM (
        SELECT U.BDCODUNIMED FROM TUNIDADEMEDIDA U
        WHERE UPPER(CAST(U.BDAPEUNIMED AS BLOB SUB_TYPE 1)) = UPPER(CAST(:PRAPELIDO AS BLOB SUB_TYPE 1))
        UNION
        SELECT UT.BDCODUNIMED FROM TMP_TUNIDADEMEDIDA_TEMP UT
        WHERE UT.BDSESSAO = :PRSESSAOUNIMED
        AND UPPER(CAST(UT.BDAPEUNIMED AS BLOB SUB_TYPE 1)) = UPPER(CAST(:PRAPELIDO AS BLOB SUB_TYPE 1))
       ) UN
  INTO :wCodUniMed;

  /*Nova unidade de medida*/
  IF ((:wCodUniMed IS NULL) OR (:wCodUniMed = 0)) THEN
    BEGIN
      SELECT FIRST 1 MAX(BDCODUNIMED) + 1 FROM TMP_TUNIDADEMEDIDA_TEMP WHERE BDSESSAO = :PRSESSAOUNIMED INTO :wCodUnimed;

      INSERT INTO TMP_TUNIDADEMEDIDA_TEMP(BDSESSAO, BDCODUNIMED, BDDESCUNIMED, BDAPEUNIMED, BDCODTIPO, BDEDITCHAVE)
      SELECT FIRST 1 U.BDSESSAO, :wCodUnimed, :PRDESC, :PRAPELIDO, U.BDCODTIPO, NULL
      FROM TMP_TUNIDADEMEDIDA_TEMP U
      WHERE U.BDSESSAO = :PRSESSAOUNIMED;
    END
  ELSE
    UPDATE TMP_TUNIDADEMEDIDA_TEMP SET BDEDITCHAVE = :wCodUnimed WHERE BDSESSAO = :PRSESSAOUNIMED AND BDEDITCHAVE = :PRCHAVE;

  UPDATE TMP_TCADPRO_TEMP P SET P.BDAPEUNIMED = :PRAPELIDO, P.BDCODUNIMED = :wCodUnimed, P.BDALTCODUNIMED = :wCodUnimed
  WHERE P.BDSESSAO = :PRSESSAOPRO
  AND P.BDALTCODUNIMED = :PRCHAVE;
END^

create or alter procedure SP_ATUALIZA_TRIBNAC (
    PRCODCID integer,
    PRREFATVM integer)
as
declare variable WCODATVM integer;
declare variable WCODATVMANT integer;
declare variable WCODCID integer;
declare variable WREFATVM integer;
declare variable WCODMUNATVM varchar(20);
declare variable WDESCATVM varchar(700);
declare variable WCOSER integer;
BEGIN
  WCODATVM = 0;
  WCODATVMANT = 0;
  FOR
    SELECT (SELECT MAX(BDCODATVM) + 1 FROM TATVMUNICIPAL), :PRCODCID, :PRREFATVM, BDCODMUNATVM, BDDESCATVM, BDCODSER FROM VEF_BASE_TTABTRIBNAC TRIB
    INTO :WCODATVM, :WCODCID, :WREFATVM, :WCODMUNATVM, :WDESCATVM, :WCOSER
  DO
    BEGIN
      IF (WCODATVMANT = 0) THEN
        WCODATVMANT = WCODATVM;
      ELSE
        WCODATVMANT = WCODATVMANT+1;
      UPDATE OR INSERT INTO TATVMUNICIPAL (BDCODATVM, BDCODCID, BDREFATVM, BDCODMUNATVM, BDDESCATVM, BDCODSER)
      VALUES(IIF ((SELECT FIRST 1 BDCODATVM FROM TATVMUNICIPAL WHERE (BDCODCID = :WCODCID) AND (BDCODMUNATVM = :WCODMUNATVM) AND (BDREFATVM = :WREFATVM)) IS NOT NULL,
                  (SELECT FIRST 1 BDCODATVM FROM TATVMUNICIPAL WHERE (BDCODCID = :WCODCID) AND (BDCODMUNATVM = :WCODMUNATVM) AND (BDREFATVM = :WREFATVM)), :WCODATVMANT),
                  :WCODCID, :WREFATVM, :WCODMUNATVM, :WDESCATVM, :WCOSER)
      MATCHING(BDCODATVM);
    END
END^

CREATE OR ALTER procedure SP_GERACODIGOS_TTERCEIRO (
    PRSESSAO integer,
    PRULTCHAVE integer)
as
declare variable FCODTER integer;
BEGIN
  UPDATE TMP_TTERCEIRO_TEMP TT SET TT.BDEDITCHAVE = (SELECT T.BDEDITCHAVE FROM TMP_TTERCEIRO T WHERE T.BDSESSAO = TT.BDSESSAO AND T.BDCODTER = TT.BDCODTER AND T.BDEDITCHAVE > 0) WHERE TT.BDSESSAO = :PRSESSAO;

  FOR SELECT T.BDCODTER
      FROM TMP_TTERCEIRO T
      WHERE T.BDSESSAO = :PRSESSAO
      AND T.BDEDITCHAVE = 0
      ORDER BY T.BDCODTER
      INTO :FCODTER
  DO
    BEGIN
      UPDATE TMP_TTERCEIRO T SET T.BDEDITCHAVE = :PRULTCHAVE WHERE T.BDSESSAO = :PRSESSAO AND T.BDCODTER = :FCODTER;
      UPDATE TMP_TTERCEIRO_TEMP TM SET TM.BDEDITCHAVE = :PRULTCHAVE WHERE TM.BDSESSAO = :PRSESSAO AND TM.BDCODTER = :FCODTER;

      PRULTCHAVE = :PRULTCHAVE - 1;
    END
END^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_BLOCOK275 (
    PRSESSAO integer,
    PRSESSAOPRO integer)
as
BEGIN
/*114 - Somente um dos campos de quantidade deverá ser preenchido.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDORDEMK275, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 114 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK275_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDQTDPOSITIVAK275 IS NOT NULL) AND (K.BDQTDPOSITIVAK275 > 0))
  AND ((K.BDQTDNEGATIVAK275 IS NOT NULL) AND (K.BDQTDNEGATIVAK275 > 0));

  /*115 - É preciso preencher um dos campos de quantidade.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDORDEMK275, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 115 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK275_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDQTDPOSITIVAK275 IS NULL) OR (K.BDQTDPOSITIVAK275 = 0))
  AND ((K.BDQTDNEGATIVAK275 IS NULL) OR (K.BDQTDNEGATIVAK275 = 0));

  /*22 - Lançamento já existente na base de dados*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDORDEMK275, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 22 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK275_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND EXISTS (
              SELECT FIRST 1 K275.BDCHAVE
              FROM VEF_EMP_TMOVK275 K275
              WHERE K275.BDCODEMP = K.BDCODEMP
              AND K275.BDCHAVE = K.BDEDITCHAVE
              AND K275.BDCODPRODITEM = K.BDALTCODPROD
             );

  /*101 - O código SPED do item informado deve ser 00, 01, 02, 03, 04, 05 ou 10.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDORDEMK275, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 101 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK275_TEMP K
  JOIN TMP_TCADPRO_TEMP P ON(P.BDSESSAO = :PRSESSAOPRO AND P.BDEDITCHAVE = K.BDALTCODPROD AND P.BDCODTIPOSER NOT IN(1, 2, 3, 4, 5, 6, 11)) /*Está sendo importado*/
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
    UNION
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 101 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK275_TEMP K
  JOIN TCADPRO_VINC V ON(V.BDCODEMP = K.BDCODEMP AND V.BDCODPROD = K.BDALTCODPROD AND V.BDCODTIPOSER NOT IN(1, 2, 3, 4, 5, 6, 11)) /*Já gravado*/
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0));

  /*87 - Produto não informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDORDEMK275, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 87 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK275_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NULL) OR (K.BDALTCODPROD = 0));

  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDORDEMK275, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK275_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :PRSESSAOPRO AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, BDCODINCONSISTENCIA;

  /*111 - Produto substituto inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDORDEMK275, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, 111 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK275_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :PRSESSAOPRO AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPRODSUB)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPRODSUB IS NOT NULL) AND (K.BDALTCODPRODSUB > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDORDEM, BDCODINCONSISTENCIA;
END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK270 (
    PRSESSAO INTEGER,
    PRULTCHAVE INTEGER,
    PRIDTERMINAL INTEGER)
AS
DECLARE VARIABLE WSESSAOPRO INTEGER;
BEGIN
  DELETE FROM VEF_INCON_TMOVBLOCOK K WHERE K.BDSESSAO = :PRSESSAO AND K.BDCHAVEK270 IS NOT NULL;

  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVK270_TEMP K SET K.BDEDITCHAVE = :PRULTCHAVE WHERE K.BDSESSAO = :PRSESSAO;

  /*110 - A origem deve ser informada.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 110 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK270_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDCODIGO = 0) OR (K.BDCODIGO IS NULL));

  /*87 - Produto não informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK260, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 87 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK270_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NULL) OR (K.BDALTCODPROD = 0));

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRIDTERMINAL
  AND S.BDTABLE = 'TMP_TCADPRO_TEMP'
  INTO :wSessaoPro;

  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK270_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA;

  /*112 - Data de fim da produção tem que ser menor que a referência do lançamento.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 112 BDCODINCONSISTENCIA,
               (SELECT A.BDAAAAMM FROM AAAAMM(K.BDDATAFIMPROD) A) BDREFFIM,
               K.BDREFERENCIA
        FROM TMP_VEF_EMP_TMOVK270_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDDATAFIMPROD IS NOT NULL
       ) K
  WHERE K.BDREFFIM >= K.BDREFERENCIA;

  /*113 - Data de início da produção tem que ser menor que a referência do lançamento.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, K.BDCODINCONSISTENCIA
  FROM (
        SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 113 BDCODINCONSISTENCIA,
               (SELECT A.BDAAAAMM FROM AAAAMM(K.BDDATAINIPROD) A) BDREFFIM,
               K.BDREFERENCIA
        FROM TMP_VEF_EMP_TMOVK270_TEMP K
        WHERE K.BDSESSAO = :PRSESSAO
        AND K.BDDATAINIPROD IS NOT NULL
       ) K
  WHERE K.BDREFFIM >= K.BDREFERENCIA;

  /*114 - Somente um dos campos de quantidade deverá ser preenchido.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 114 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK270_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDQTDPOSITIVA IS NOT NULL) AND (K.BDQTDPOSITIVA > 0))
  AND ((K.BDQTDNEGATIVA IS NOT NULL) AND (K.BDQTDNEGATIVA > 0));

  /*115 - É preciso preencher um dos campos de quantidade.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 115 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK270_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDQTDPOSITIVA IS NULL) OR (K.BDQTDPOSITIVA = 0))
  AND ((K.BDQTDNEGATIVA IS NULL) OR (K.BDQTDNEGATIVA = 0));

  /*22 - Lançamento já existente na base de dados*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK270, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK270_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND EXISTS (
              SELECT FIRST 1 K270.BDCHAVE
              FROM VEF_EMP_TMOVK270 K270
              WHERE K270.BDCODEMP = K.BDCODEMP
              AND K270.BDREFERENCIA = K.BDREFERENCIA
              AND K270.BDORDEMPROD = K.BDORDEMPROD
              AND K270.BDCODPROD = K.BDALTCODPROD
              AND K270.BDCODIGO = K.BDCODIGO
             );
             
  EXECUTE PROCEDURE SP_ATUALIZAR_CAMPO_CHAVE_TEMP(:PRSESSAO, 'TMP_VEF_EMP_TMOVK270_TEMP');
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_BLOCOK275(:PRSESSAO, :wSessaoPro);             
END^

CREATE OR ALTER PROCEDURE SP_UPDATE_K275 (
    PRID_TERMINAL INTEGER)
AS
DECLARE VARIABLE WSESSAOPRO INTEGER;
DECLARE VARIABLE WSESSAO INTEGER;
BEGIN
  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = 'TMP_TCADPRO_TEMP' INTO :wSessaoPro;
  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = 'TMP_VEF_EMP_TMOVK275_TEMP' INTO :wSessao;

  /*Desvincula todos os produtos*/
  UPDATE TMP_VEF_EMP_TMOVK275_TEMP T SET T.BDCODPRODSUB = NULL, T.BDDESCPRODSUB = NULL WHERE T.BDSESSAO = :wSessao;
    
  /*1 - Busca os produtos na tabela TEMP, contém os registros que estão sendo importados*/
  UPDATE TMP_VEF_EMP_TMOVK275_TEMP T
  SET T.BDALTCODPRODSUB = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO_TEMP P WHERE P.BDSESSAO = :wSessaoPro AND P.BDCODSAIDA = T.BDCODSAIDASUB),
      T.BDDESCPRODSUB = (
                         SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                         FROM TMP_TCADPRO_TEMP P
                         WHERE P.BDSESSAO = :wSessaoPro
                         AND P.BDCODSAIDA = T.BDCODSAIDASUB
                        )
  WHERE T.BDSESSAO = :wSessao
  AND ((T.BDCODSAIDASUB IS NOT NULL) AND (T.BDCODSAIDASUB <> ''));
    
  /*2 - Busca os produtos na tabela TMP, contém todos os registros de produto do banco*/
  UPDATE TMP_VEF_EMP_TMOVK275_TEMP T
  SET T.BDALTCODPRODSUB = (SELECT FIRST 1 P.BDEDITCHAVE FROM TMP_TCADPRO P WHERE P.BDCODEMP = T.BDCODEMP AND P.BDCODSAIDA = T.BDCODSAIDASUB),
      T.BDDESCPRODSUB = (
                         SELECT FIRST 1 IIF(TRIM(P.BDDESCPROD) = '', P.BDDESCRICAOUNICA, P.BDDESCPROD)
                         FROM TMP_TCADPRO P
                         WHERE P.BDCODEMP = T.BDCODEMP
                         AND P.BDCODSAIDA = T.BDCODSAIDASUB
                        )
  WHERE T.BDSESSAO = :wSessao
  AND T.BDALTCODPRODSUB IS NULL
  AND ((T.BDCODSAIDASUB IS NOT NULL) AND (T.BDCODSAIDASUB <> ''));

  /*Apenas joga o altcodprod para o bdcodprod*/
  UPDATE TMP_VEF_EMP_TMOVK275_TEMP T SET T.BDCODPRODSUB = T.BDALTCODPRODSUB
  WHERE T.BDSESSAO = :wSessao
  AND T.BDALTCODPRODSUB IS NOT NULL;
END^

CREATE OR ALTER TRIGGER tmp_vef_emp_tmovk280_temp_gk FOR tmp_vef_emp_tmovk280_temp
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  IF ((OLD.BDEDITCHAVE IS NULL) AND (NEW.BDEDITCHAVE > 0)) THEN
    BEGIN
      NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - OLD.BDCHAVE)+1;
    END
END^

CREATE OR ALTER TRIGGER TMP_VEF_EMP_TMOVK290_TEMP_GK FOR TMP_VEF_EMP_TMOVK290_TEMP
ACTIVE BEFORE UPDATE POSITION 0
AS
DECLARE VARIABLE WCHAVE INTEGER;
BEGIN
  IF ((OLD.BDEDITCHAVE IS NULL) AND (NEW.BDEDITCHAVE > 0)) THEN
    BEGIN
      WCHAVE = NEW.BDCHAVE;
      NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - OLD.BDCHAVE)+1;

      UPDATE TMP_VEF_EMP_TMOVK291_TEMP k
      SET k.bdEDITCHAVE = NEW.BDEDITCHAVE
      WHERE k.bdSESSAO = NEW.bdSESSAO
        AND k.bdCODEMP = NEW.bdCODEMP
        AND k.bdCHAVE  = :wCHAVE;

      UPDATE TMP_VEF_EMP_TMOVK292_TEMP k
      SET k.bdEDITCHAVE = NEW.BDEDITCHAVE
      WHERE k.bdSESSAO = NEW.bdSESSAO
        AND k.bdCODEMP = NEW.bdCODEMP
        AND k.bdCHAVE  = :wCHAVE;
    END
END
^

CREATE OR ALTER TRIGGER TMP_VEF_EMP_TMOVK300_TEMP_GK FOR TMP_VEF_EMP_TMOVK300_TEMP
ACTIVE BEFORE UPDATE POSITION 0
AS
DECLARE VARIABLE WCHAVE INTEGER;
BEGIN
  IF ((OLD.BDEDITCHAVE IS NULL) AND (NEW.BDEDITCHAVE > 0)) THEN
    BEGIN
      WCHAVE = NEW.BDCHAVE;
      NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - OLD.BDCHAVE)+1;

      UPDATE TMP_VEF_EMP_TMOVK301_TEMP k
      SET k.bdEDITCHAVE = NEW.BDEDITCHAVE
      WHERE k.bdSESSAO = NEW.bdSESSAO
        AND k.bdCODEMP = NEW.bdCODEMP
        AND k.bdCHAVE  = :wCHAVE;

      UPDATE TMP_VEF_EMP_TMOVK302_TEMP k
      SET k.bdEDITCHAVE = NEW.BDEDITCHAVE
      WHERE k.bdSESSAO = NEW.bdSESSAO
        AND k.bdCODEMP = NEW.bdCODEMP
        AND k.bdCHAVE  = :wCHAVE;
    END
END
^

create or alter procedure SP_ATUALIZAR_TMP_BLOCOK280 (
    PRSESSAO integer,
    PRULTCHAVE integer,
    PRID_TERMINAL integer)
as
declare variable WSESSAOPRO integer;
BEGIN
  DELETE FROM VEF_INCON_TMOVBLOCOK K WHERE K.BDSESSAO = :PRSESSAO AND K.BDCHAVEK280 IS NOT NULL;

  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVK280_TEMP K SET K.BDEDITCHAVE = :PRULTCHAVE WHERE K.BDSESSAO = :PRSESSAO;

  /*117 - Data de estoque final é de preenchimento obrigatório.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 117 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDDATAESTOQUE IS NULL;

  /*114 - Somente um dos campos de quantidade deverá ser preenchido.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 114 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDQTDCORPOS IS NOT NULL) AND (K.BDQTDCORPOS > 0))
  AND ((K.BDQTDCORNEG IS NOT NULL) AND (K.BDQTDCORNEG > 0));

  /*115 - É preciso preencher um dos campos de quantidade.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 115 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDQTDCORPOS IS NULL) OR (K.BDQTDCORPOS = 0))
  AND ((K.BDQTDCORNEG IS NULL) OR (K.BDQTDCORNEG = 0));

  /*116 - Participante é de preenchimento obrigatório para indicador de posse igual a 1 ou 2.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 116 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDCODPOSSE IN (2, 3)
  AND ((K.BDALTCODTER IS NULL) OR (K.BDALTCODTER = 0));

  /*22 - Lançamento já existente na base de dados - Sem participante*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND K.BDALTCODTER IS NULL
  AND EXISTS (
              SELECT FIRST 1 K280.BDCHAVE
              FROM VEF_EMP_TMOVK280 K280
              WHERE K280.BDCODEMP = K.BDCODEMP
              AND K280.BDREFERENCIA = K.BDREFERENCIA
              AND K280.BDCODPOSSE = K.BDCODPOSSE
              AND K280.BDCODPROD = K.BDALTCODPROD
             );

  /*22 - Lançamento já existente na base de dados - Com participante*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 22 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODTER IS NOT NULL) AND (K.BDALTCODTER > 0))
  AND EXISTS (
              SELECT FIRST 1 K280.BDCHAVE
              FROM VEF_EMP_TMOVK280 K280
              WHERE K280.BDCODEMP   = K.BDCODEMP
              AND K280.BDREFERENCIA = K.BDREFERENCIA
              AND K280.BDCODPOSSE   = K.BDCODPOSSE
              AND K280.BDCODPROD    = K.BDALTCODPROD
              AND K280.BDCODTER     = K.BDALTCODTER
             );

  /*87 - Produto não informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 87 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NULL) OR (K.BDALTCODPROD = 0));

  SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRID_TERMINAL
  AND S.BDTABLE = 'TMP_TCADPRO_TEMP'
  INTO :wSessaoPro;

  /*76 - Produto inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 76 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :wSessaoPro AND PRO.BDCODEMP = K.BDCODEMP AND PRO.BDCODPROD = K.BDALTCODPROD)
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODPROD IS NOT NULL) AND (K.BDALTCODPROD > 0))
  AND PRO.BDCODINCONSISTENCIA IS NOT NULL
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA;

  /*74 - Participante inconsistente*/
  INSERT INTO VEF_INCON_TMOVBLOCOK(BDCODEMP, BDSESSAO, BDCHAVEK280, BDCODINCONSISTENCIA)
  SELECT K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, 74 BDCODINCONSISTENCIA
  FROM TMP_VEF_EMP_TMOVK280_TEMP K
  JOIN TMP_TTERCEIRO T ON(T.BDEDITCHAVE = K.BDALTCODTER AND T.BDINCONSISTENTE IS NOT NULL AND T.BDINCONSISTENTE NOT IN(0, 2))
  WHERE K.BDSESSAO = :PRSESSAO
  AND ((K.BDALTCODTER IS NOT NULL) AND (K.BDALTCODTER > 0))
  GROUP BY K.BDCODEMP, K.BDSESSAO, K.BDCHAVE, BDCODINCONSISTENCIA;
END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK290_K300 (
    prSUFIXO VARCHAR(4),
    prSESSAO INTEGER,
    prID_TERMINAL INTEGER)
AS
DECLARE VARIABLE wSessaoPro INTEGER;
DECLARE VARIABLE wSQL VARCHAR(500);
DECLARE VARIABLE wAUX VARCHAR(3);
BEGIN
  IF (UPPER(:prSUFIXO) = 'K290') THEN
    wAux = 'K29';
  ELSE
  IF (UPPER(:prSUFIXO) = 'K300') THEN
    wAux = 'K30';
  ELSE
    EXIT;

  IF (UPPER(:prSUFIXO) = 'K290') THEN
    BEGIN
      /*112 - Data de fim da produção tem que ser menor que a referência do lançamento.*/
      wSQL =        'INSERT INTO VEF_INCON_TMOVBLOCOK (bdCODEMP, bdSESSAO, bdCHAVE'||wAux||'0, bdCODINCONSISTENCIA) ';
      wSQL = wSQL ||'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, k.bdCODINCONSISTENCIA ';
      wSQL = wSQL ||'FROM ( ';
      wSQL = wSQL ||      'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, 112 AS bdCODINCONSISTENCIA, ';
      wSQL = wSQL ||      '       (SELECT a.bdAAAAMM FROM AAAAMM(k.bdDATAFIN) a) AS bdREFFIM, ';
      wSQL = wSQL ||      '       k.bdREFLAN ';
      wSQL = wSQL ||      'FROM TMP_VEF_EMP_TMOV'||wAux||'0_TEMP k ';
      wSQL = wSQL ||      'WHERE k.bdSESSAO = '||:prSESSAO;
      wSQL = wSQL ||      '  AND k.bdDATAFIN IS NOT NULL ';
      wSQL = wSQL ||     ') k ';
      wSQL = wSQL ||'WHERE k.bdREFFIM > k.bdREFLAN; ';
      EXECUTE STATEMENT wSQL;
    
      /*113 - Data de início da produção tem que ser menor que a referência do lançamento.*/
      wSQL =        'INSERT INTO VEF_INCON_TMOVBLOCOK (bdCODEMP, bdSESSAO, bdCHAVE'||wAux||'0, bdCODINCONSISTENCIA) ';
      wSQL = wSQL ||'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, k.bdCODINCONSISTENCIA ';
      wSQL = wSQL ||'FROM ( ';
      wSQL = wSQL ||     ' SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, 113 AS bdCODINCONSISTENCIA, ';
      wSQL = wSQL ||     '        (SELECT a.bdAAAAMM FROM AAAAMM(k.bdDATAINI) a) AS bdREFINI, ';
      wSQL = wSQL ||     '        k.bdREFLAN ';
      wSQL = wSQL ||     ' FROM TMP_VEF_EMP_TMOV'||wAux||'0_TEMP k ';
      wSQL = wSQL ||     ' WHERE k.bdSESSAO = '||:prSESSAO;
      wSQL = wSQL ||     '   AND k.bdDATAINI IS NOT NULL ';
      wSQL = wSQL ||     ') k ';
      wSQL = wSQL ||'WHERE k.bdREFINI > k.bdREFLAN; ';
      EXECUTE STATEMENT wSQL;

      /*154 - É obrigatória a informação da ordem de produção.*/
      wSQL =        'INSERT INTO VEF_INCON_TMOVBLOCOK (bdCODEMP, bdSESSAO, bdCHAVE'||wAux||'0, bdCODINCONSISTENCIA) ';
      wSQL = wSQL ||'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, 154 AS bdCODINCONSISTENCIA ';
      wSQL = wSQL ||'FROM TMP_VEF_EMP_TMOV'||wAux||'0_TEMP k ';
      wSQL = wSQL ||'WHERE k.bdSESSAO = '||:prSESSAO;
      wSQL = wSQL ||'  AND k.bdDATAINI IS NOT NULL ';
      wSQL = wSQL ||'  AND k.bdORDEMPROD IS NULL; ';
      EXECUTE STATEMENT wSQL;
    
      /*153 - Ordem de produção já lançada, verifique e corrija a situação.*/
      wSQL =        'INSERT INTO VEF_INCON_TMOVBLOCOK (bdCODEMP, bdSESSAO, bdCHAVE'||wAux||'0, bdCODINCONSISTENCIA) ';
      wSQL = wSQL ||'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, 153 AS bdCODINCONSISTENCIA ';
      wSQL = wSQL ||'FROM TMP_VEF_EMP_TMOV'||wAux||'0_TEMP k ';
      wSQL = wSQL ||'WHERE k.bdSESSAO = '||:prSESSAO;
      wSQL = wSQL ||' AND EXISTS ( ';
      wSQL = wSQL ||            ' SELECT FIRST 1 '||wAux||'0.bdCHAVE ';
      wSQL = wSQL ||            ' FROM VEF_EMP_TMOV'||wAux||'0 '||wAux||'0 ';
      wSQL = wSQL ||            ' WHERE '||wAux||'0.bdCODEMP = k.bdCODEMP ';
      wSQL = wSQL ||              ' AND '||wAux||'0.bdORDEMPROD = k.bdORDEMPROD ';
      wSQL = wSQL ||            ' ); ';
      EXECUTE STATEMENT wSQL;
    END

  /*115 - É preciso preencher um dos campos de quantidade.*/
  wSQL =        'INSERT INTO VEF_INCON_TMOVBLOCOK (bdCODEMP, bdSESSAO, bdCHAVE'||wAux||'0, bdORDEM'||wAux||'1, bdCODINCONSISTENCIA) ';
  wSQL = wSQL ||'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, k.bdORDEM, 115 AS bdCODINCONSISTENCIA ';
  wSQL = wSQL ||'FROM TMP_VEF_EMP_TMOV'||wAux||'1_TEMP k ';
  wSQL = wSQL ||'WHERE K.bdSESSAO =  '||:PRSESSAO;
  wSQL = wSQL || ' AND ((k.bdQTDITEM IS NULL) OR (k.bdQTDITEM = 0)); ';
  EXECUTE STATEMENT wSQL;
  /*115 - É preciso preencher um dos campos de quantidade.*/
  wSQL =        'INSERT INTO VEF_INCON_TMOVBLOCOK (bdCODEMP, bdSESSAO, bdCHAVE'||wAux||'0, bdORDEM'||wAux||'2, bdCODINCONSISTENCIA) ';
  wSQL = wSQL ||'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, k.bdORDEM, 115 AS bdCODINCONSISTENCIA ';
  wSQL = wSQL ||'FROM TMP_VEF_EMP_TMOV'||wAux||'2_TEMP k ';
  wSQL = wSQL ||'WHERE K.bdSESSAO = '||:PRSESSAO;
  wSQL = wSQL || ' AND ((k.bdQTDITEM IS NULL) OR (k.bdQTDITEM = 0)); ';
  EXECUTE STATEMENT wSQL;

  /*22 - Lançamento já existente na base de dados*/
  wSQL =        'INSERT INTO VEF_INCON_TMOVBLOCOK (bdCODEMP, bdSESSAO, bdCHAVE'||wAux||'0, bdCODINCONSISTENCIA) ';
  wSQL = wSQL ||'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, 22 AS bdCODINCONSISTENCIA ';
  wSQL = wSQL ||'FROM TMP_VEF_EMP_TMOV'||wAux||'0_TEMP k ';
  wSQL = wSQL ||'WHERE k.bdSESSAO = '||:prSESSAO;
  wSQL = wSQL ||' AND EXISTS ( ';
  wSQL = wSQL ||            ' SELECT FIRST 1 '||wAux||'0.bdCHAVE ';
  wSQL = wSQL ||            ' FROM VEF_EMP_TMOV'||wAux||'0 '||wAux||'0 ';
  wSQL = wSQL ||            ' WHERE '||wAux||'0.bdCODEMP = k.bdCODEMP ';
  IF (UPPER(:prSUFIXO) = 'K290') THEN
    BEGIN
      wSQL = wSQL ||              ' AND '||wAux||'0.bdREFLAN = k.bdREFLAN ';
      wSQL = wSQL ||              ' AND '||wAux||'0.bdDATAINI = k.bdDATAINI ';
      wSQL = wSQL ||              ' AND '||wAux||'0.bdDATAFIN = k.bdDATAFIN ';
      wSQL = wSQL ||              ' AND '||wAux||'0.bdORDEMPROD = K.bdORDEMPROD ';
    END
  ELSE
  IF (UPPER(:prSUFIXO) = 'K300') THEN
    wSQL = wSQL ||              ' AND '||wAux||'0.bdDATA = K.bdDATA ';
  wSQL = wSQL ||            ' ); ';
  EXECUTE STATEMENT wSQL;

  /*87 - Produto não informado ou inconsistente.*/
  wSQL =        'INSERT INTO VEF_INCON_TMOVBLOCOK (bdCODEMP, bdSESSAO, bdCHAVE'||wAux||'0, bdORDEM'||wAux||'1, bdCODINCONSISTENCIA) ';
  wSQL = wSQL ||'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, k.bdORDEM, 87 AS bdCODINCONSISTENCIA ';
  wSQL = wSQL ||'FROM TMP_VEF_EMP_TMOV'||wAux||'1_TEMP k ';
  wSQL = wSQL ||'WHERE k.bdSESSAO = '||:prSESSAO;
  wSQL = wSQL || ' AND ((k.bdALTCODPROD IS NULL) OR (k.bdALTCODPROD = 0)); ';
  EXECUTE STATEMENT wSQL;
  /*87 - Produto não informado ou inconsistente.*/
  wSQL =        'INSERT INTO VEF_INCON_TMOVBLOCOK (bdCODEMP, bdSESSAO, bdCHAVE'||wAux||'0, bdORDEM'||wAux||'2, bdCODINCONSISTENCIA) ';
  wSQL = wSQL ||'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, k.bdORDEM, 87 AS bdCODINCONSISTENCIA ';
  wSQL = wSQL ||'FROM TMP_VEF_EMP_TMOV'||wAux||'2_TEMP k ';
  wSQL = wSQL ||'WHERE k.bdSESSAO = '||:prSESSAO;
  wSQL = wSQL || ' AND ((k.bdALTCODPROD IS NULL) OR (k.bdALTCODPROD = 0)); ';
  EXECUTE STATEMENT wSQL;

  SELECT s.bdSESSAO
  FROM TMP_TSESSAO_IMP s
  WHERE s.bdID_TERMINAL = :prID_TERMINAL
    AND s.bdTABLE = 'TMP_TCADPRO_TEMP'
  INTO :wSessaoPro;

  /*76 - Produto inconsistente*/
  wSQL =        'INSERT INTO VEF_INCON_TMOVBLOCOK (bdCODEMP, bdSESSAO, bdCHAVE'||wAux||'0, bdORDEM'||wAux||'1, bdCODINCONSISTENCIA) ';
  wSQL = wSQL ||'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, k.bdORDEM, 76 AS bdCODINCONSISTENCIA ';
  wSQL = wSQL ||'FROM TMP_VEF_EMP_TMOV'||wAux||'1_TEMP k ';
  wSQL = wSQL ||'LEFT OUTER JOIN VEF_INCON_TCADPRO pro ON (pro.bdSESSAO = '||:wSessaoPro||' AND pro.bdCODEMP = k.bdCODEMP AND pro.bdCODPROD = k.bdALTCODPROD) ';
  wSQL = wSQL ||'WHERE k.bdSESSAO = '||:prSESSAO;
  wSQL = wSQL ||' AND ((k.bdALTCODPROD IS NOT NULL) AND (k.bdALTCODPROD > 0)) ';
  wSQL = wSQL ||' AND pro.bdCODINCONSISTENCIA IS NOT NULL; ';
  EXECUTE STATEMENT wSQL;
  /*76 - Produto inconsistente*/
  wSQL =        'INSERT INTO VEF_INCON_TMOVBLOCOK (bdCODEMP, bdSESSAO, bdCHAVE'||wAux||'0, bdORDEM'||wAux||'2, bdCODINCONSISTENCIA) ';
  wSQL = wSQL ||'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, k.bdORDEM, 76 AS bdCODINCONSISTENCIA ';
  wSQL = wSQL ||'FROM TMP_VEF_EMP_TMOV'||wAux||'2_TEMP k ';
  wSQL = wSQL ||'LEFT OUTER JOIN VEF_INCON_TCADPRO pro ON (pro.bdSESSAO = '||:wSessaoPro||' AND pro.bdCODEMP = k.bdCODEMP AND pro.bdCODPROD = k.bdALTCODPROD) ';
  wSQL = wSQL ||'WHERE k.bdSESSAO = '||:prSESSAO;
  wSQL = wSQL ||' AND ((k.bdALTCODPROD IS NOT NULL) AND (k.bdALTCODPROD > 0)) ';
  wSQL = wSQL ||' AND pro.bdCODINCONSISTENCIA IS NOT NULL; ';
  EXECUTE STATEMENT wSQL;

  /*155 - O produto informado precisa ter o tipo do item no cadastro do produto como 03 - Produto em processo ou 04 - Produto acabado.*/
  wSQL =        'INSERT INTO VEF_INCON_TMOVBLOCOK (bdCODEMP, bdSESSAO, bdCHAVE'||wAux||'0, bdORDEM'||wAux||'1, bdCODINCONSISTENCIA) ';
  wSQL = wSQL ||'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, k.bdORDEM, 155 AS bdCODINCONSISTENCIA ';
  wSQL = wSQL ||'FROM TMP_VEF_EMP_TMOV'||wAux||'1_TEMP k ';
  wSQL = wSQL ||'LEFT OUTER JOIN TMP_TCADPRO_TEMP pro ON (pro.bdSESSAO = '||:wSessaoPro||' AND pro.bdCODEMP = k.bdCODEMP AND pro.bdCODPROD = k.bdALTCODPROD) ';
  wSQL = wSQL ||'WHERE k.bdSESSAO = '||:prSESSAO;
  wSQL = wSQL ||' AND (pro.bdCODTIPOSER NOT IN (4,5)); ';
  EXECUTE STATEMENT wSQL;

  /*156 - Não serão aceitos dois ou mais lançamentos com o mesmo produto vinculados.*/
  wSQL =        'INSERT INTO VEF_INCON_TMOVBLOCOK (bdCODEMP, bdSESSAO, bdCHAVE'||wAux||'0, bdORDEM'||wAux||'1, bdCODINCONSISTENCIA) ';
  wSQL = wSQL ||'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, k.bdORDEM, 156 AS bdCODINCONSISTENCIA ';
  wSQL = wSQL ||'FROM TMP_VEF_EMP_TMOV'||wAux||'1_TEMP k ';
  wSQL = wSQL ||'WHERE k.bdSESSAO = '||:prSESSAO;
  wSQL = wSQL ||'GROUP BY k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, k.bdORDEM ';
  wSQL = wSQL ||'HAVING COUNT(k.bdCODPROD) > 1 ';
  EXECUTE STATEMENT wSQL;

  /*157 - Não são aceitos valores negativos ou iguais a zero para o campo quantidade.*/
  wSQL =        'INSERT INTO VEF_INCON_TMOVBLOCOK (bdCODEMP, bdSESSAO, bdCHAVE'||wAux||'0, bdORDEM'||wAux||'1, bdCODINCONSISTENCIA) ';
  wSQL = wSQL ||'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, k.bdORDEM, 157 AS bdCODINCONSISTENCIA ';
  wSQL = wSQL ||'FROM TMP_VEF_EMP_TMOV'||wAux||'1_TEMP k ';
  wSQL = wSQL ||'WHERE k.bdSESSAO = '||:prSESSAO;
  wSQL = wSQL ||'   AND ((k.bdQTDITEM IS NULL) OR (k.bdQTDITEM <= 0)); ';
  EXECUTE STATEMENT wSQL;
  /*157 - Não são aceitos valores negativos ou iguais a zero para o campo quantidade.*/
  wSQL =        'INSERT INTO VEF_INCON_TMOVBLOCOK (bdCODEMP, bdSESSAO, bdCHAVE'||wAux||'0, bdORDEM'||wAux||'1, bdCODINCONSISTENCIA) ';
  wSQL = wSQL ||'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, k.bdORDEM, 157 AS bdCODINCONSISTENCIA ';
  wSQL = wSQL ||'FROM TMP_VEF_EMP_TMOV'||wAux||'2_TEMP k ';
  wSQL = wSQL ||'WHERE k.bdSESSAO = '||:prSESSAO;
  wSQL = wSQL ||'   AND ((k.bdQTDITEM IS NULL) OR (k.bdQTDITEM <= 0)); ';
  EXECUTE STATEMENT wSQL;

  /*158 - O insumo é obrigatório para importação do registro.*/
  wSQL =        'INSERT INTO VEF_INCON_TMOVBLOCOK (bdCODEMP, bdSESSAO, bdCHAVE'||wAux||'0, bdORDEM'||wAux||'1, bdCODINCONSISTENCIA) ';
  wSQL = wSQL ||'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, k.bdORDEM, 158 AS bdCODINCONSISTENCIA ';
  wSQL = wSQL ||'FROM TMP_VEF_EMP_TMOV'||wAux||'2_TEMP k ';
  wSQL = wSQL ||'WHERE k.bdSESSAO = '||:prSESSAO;
  wSQL = wSQL ||'   AND ((k.bdALTCODPROD IS NULL) OR (k.bdALTCODPROD <= 0)); ';
  EXECUTE STATEMENT wSQL;

  /*159 - O item do registro tem de ser do tipo 00, 01, 02, 03, 04, 05 ou 10 no seu cadastro de produtos. Verifique o cadastro de produtos.*/
  wSQL =        'INSERT INTO VEF_INCON_TMOVBLOCOK (bdCODEMP, bdSESSAO, bdCHAVE'||wAux||'0, bdORDEM'||wAux||'1, bdCODINCONSISTENCIA) ';
  wSQL = wSQL ||'SELECT k.bdCODEMP, k.bdSESSAO, k.bdCHAVE, k.bdORDEM, 159 AS bdCODINCONSISTENCIA ';
  wSQL = wSQL ||'FROM TMP_VEF_EMP_TMOV'||wAux||'2_TEMP k ';
  wSQL = wSQL ||'LEFT OUTER JOIN TMP_TCADPRO_TEMP pro ON (pro.bdSESSAO = '||:wSessaoPro||' AND pro.bdCODEMP = k.bdCODEMP AND pro.bdCODPROD = k.bdALTCODPROD) ';
  wSQL = wSQL ||'WHERE k.bdSESSAO = '||:prSESSAO;
  wSQL = wSQL ||' AND (pro.bdCODTIPOSER NOT IN (1,2,3,4,5,6,11)); ';
  EXECUTE STATEMENT wSQL;

END
^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK290 (
    prSESSAO INTEGER,
    prULTCHAVE INTEGER,
    prID_TERMINAL INTEGER)
AS
DECLARE VARIABLE wSessaoPro INTEGER;
BEGIN
  DELETE FROM VEF_INCON_TMOVBLOCOK k WHERE k.bdSESSAO = :prSESSAO AND k.bdCHAVEK290 IS NOT NULL;

  IF (:PRULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVK290_TEMP k SET k.bdEDITCHAVE = :prULTCHAVE WHERE k.bdSESSAO = :prSESSAO;

  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_BLOCOK290_K300 ('K290', :prSESSAO,  :prID_TERMINAL);

END
^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_BLOCOK300 (
    prSESSAO INTEGER,
    prULTCHAVE INTEGER,
    prID_TERMINAL INTEGER)
AS
DECLARE VARIABLE wSessaoPro INTEGER;
BEGIN
  DELETE FROM VEF_INCON_TMOVBLOCOK k WHERE k.bdSESSAO = :prSESSAO AND k.bdCHAVEK290 IS NOT NULL;

  IF (:prULTCHAVE > 0) THEN
    UPDATE TMP_VEF_EMP_TMOVK300_TEMP k SET k.bdEDITCHAVE = :prULTCHAVE WHERE k.bdSESSAO = :prSESSAO;

  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_BLOCOK290_K300 ('K300', :prSESSAO,  :prID_TERMINAL);

END
^

/* Restore proc. body: SP_VRH_RELATORIOABSENTISMO */
CREATE OR ALTER PROCEDURE SP_VRH_RELATORIOABSENTISMO (
    PREMP VARCHAR(22000),
    PRCOL VARCHAR(32700),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRSITCOL INTEGER,
    PRFILTROCLA VARCHAR(5000) = NULL)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODCENTRO INTEGER,
    BDCODTPCC INTEGER,
    BDREF INTEGER,
    BDCODCLA INTEGER,
    BDDESCCLA VARCHAR(40),
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDNOMTPCC DM_BDNOMEMP,
    BDHORASTRABDIA NUMERIC(18,6),
    BDDIASTRAB INTEGER,
    BDHORASFALTASMES NUMERIC(18,6),
    BDHORASTRABMES NUMERIC(18,6))
AS
DECLARE VARIABLE WSQL VARCHAR(28000);
DECLARE VARIABLE WSQLAUX VARCHAR(10000);
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WDATAADM DATE;
DECLARE VARIABLE WDIASTRAB INTEGER;
DECLARE VARIABLE WREFRESC INTEGER;
DECLARE VARIABLE WDATARESC DATE;
DECLARE VARIABLE WDATAINI DATE;
DECLARE VARIABLE WDATAFIM DATE;
DECLARE VARIABLE WVAL NUMERIC(18,6);
DECLARE VARIABLE WCODVER INTEGER;
DECLARE VARIABLE WCLAVER VARCHAR(20);
DECLARE VARIABLE WTIPOREF INTEGER;
DECLARE VARIABLE WCONVREFEMP DM_BOOLEAN;
DECLARE VARIABLE WTOTFALTAS NUMERIC(18,6);
DECLARE VARIABLE WINTVAL INTEGER;
DECLARE VARIABLE WSQLVER VARCHAR(1500);
DECLARE VARIABLE WCODCENTRO INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WCENTROATU INTEGER;
DECLARE VARIABLE WCODTPCCATU INTEGER;
DECLARE VARIABLE WEMPATU INTEGER;
DECLARE VARIABLE WTIPOCOL INTEGER;
DECLARE VARIABLE WPROPRESC INTEGER;
DECLARE VARIABLE WPROPADM INTEGER;
DECLARE VARIABLE WPROPFER INTEGER;
DECLARE VARIABLE WPROPSIT INTEGER;
DECLARE VARIABLE WDIASDOMES INTEGER;
DECLARE VARIABLE WDIASADM INTEGER;
DECLARE VARIABLE WDIASRESC INTEGER;
DECLARE VARIABLE WDIASSIT INTEGER;
DECLARE VARIABLE WDIASFER INTEGER;
BEGIN
  /* prsitcol
     0 = Somente ativos
     1 = Todos
     2 = Somente os demitidos
     3 = Somente admitidos no mês
     4 = Somente demitidos no mês
     5 = Ativos sem os demitidos no mês
     6 = Ativos sem demitidos com transferência
     7 = Ativos sem afastados o mês inteiro
     8 = Afastados o mês inteiro
   */

  wsql = 'select col.BDCODEMP, col.BDCODCOL, colcad.BDNOMCOL, colcad.BDNOMCOLUPPER, col.BDDATAADMCOL '||
         'from VRH_EMP_TCOLCON col '||
     'left outer join VW_VRH_EMP_TCOLCON_CAD colcad on colcad.BDCODEMP = col.BDCODEMP and colcad.BDCODCOL = col.BDCODCOL ';

  IF (premp IS NOT NULL AND premp <> '') THEN
     BEGIN
       wsql = wsql||' where '||premp;

       IF (prcol IS NOT NULL AND prcol <> '') THEN
          wsql = wsql||' and '||prcol;
     END

  wsql = wsql||' order by col.BDCODEMP, col.BDCODCOL ';
  wrefatu = prrefini;

  WHILE (wrefatu <= prreffim) DO
    BEGIN
      wempatu = 0;
      wconvrefemp = 'FALSE';
      wpropadm = 0;
      wpropfer = 0;
      wpropresc = 0;
      wpropsit = 0;
      wtipocol = 0;
      FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDNOMCOL, :BDNOMCOLUPPER, :wdataadm DO
        BEGIN
          BDREF = wrefatu;
          IF (CAST((SUBSTRING(CAST(wdataadm AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataadm AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= wrefatu) THEN
             BEGIN
               wsqlaux = 'select first 1 COL.BDCODCLA, CLA.BDDESCCLA '||
                         'from VRH_EMP_TCOLCON_VINC COL '||
                         'join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = COL.BDCODCLA) '||
                         'where COL.BDCODEMP = '||BDCODEMP||' and COL.BDCODCOL = '||BDCODCOL||' and COL.BDREFCOL <= '||wrefatu;

               IF (prfiltrocla IS NOT NULL AND prfiltrocla <> '') THEN
                  wsqlaux = wsqlaux||' and '||prfiltrocla;

               wsqlaux = wsqlaux||' order by COL.BDREFCOL DESC ';

               BDCODCLA = 0;
               BDDESCCLA = NULL;
               EXECUTE STATEMENT wsqlaux INTO :BDCODCLA, :BDDESCCLA;

               IF (BDCODCLA IS NOT NULL AND BDCODCLA > 0) THEN
                  BEGIN
                    IF (wempatu <> BDCODEMP) THEN
                       BEGIN 
                         wempatu = BDCODEMP;
                         wsqlaux = 'select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = '||BDCODEMP||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC';
                         EXECUTE STATEMENT wsqlaux INTO :wconvrefemp;

                         wsqlaux = 'select first 1     BDPROPADMEMP, BDPROPRESEMP, BDPROPFEREMP, BDPROPSITEMP from VRHF_BASE_TEMPPROP where BDCODEMP = '||BDCODEMP||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC';
                         EXECUTE STATEMENT wsqlaux INTO :wpropadm, :wpropresc, :wpropfer, :wpropsit;
                       END

                    wdataresc = NULL;
                    wrefresc = 0;
                    SELECT FIRST 1 RESC.BDDATARESCISAO, RESC.BDREFRESCISAO FROM VRH_EMP_TRESCISAO RESC
                    JOIN VRH_BASE_TPREPRESC PRES ON (PRES.BDCODPRES = RESC.BDCODPRES)
                    WHERE RESC.BDCODEMP = :BDCODEMP AND RESC.BDCODCOL = :BDCODCOL AND COALESCE(PRES.BDTIPOMOV, 0) = 0 INTO :wdataresc, :wrefresc;

                    wsqlaux = 'select first 1 BDHORASDIARIASCOL, BDTIPOCOL '||
                              'from VRHF_EMP_TCOL_CALC '||
                              'where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFCOL <= '||wrefatu||
                              'order by BDREFCOL DESC ';
     
                    EXECUTE STATEMENT wsqlaux INTO :BDHORASTRABDIA, :wtipocol;

                    IF ((BDHORASTRABDIA IS NULL) OR (BDHORASTRABDIA = 0)) THEN
                       BDHORASTRABDIA = 7.3333;

                    IF (CAST(SUBSTRING(wrefatu FROM 5 FOR 2) AS INTEGER) IN (1,3,5,7,8,10,12)) THEN
                       wdiasdomes = 31;
                    ELSE
                    IF (CAST(SUBSTRING(wrefatu FROM 5 FOR 2) AS INTEGER) = 2) THEN
                       BEGIN
                         -- Ano bisexto
                         IF ((MOD(CAST(SUBSTRING(wrefatu FROM 1 FOR 4) AS INTEGER), 4) = 0) AND ((MOD(CAST(SUBSTRING(wrefatu FROM 1 FOR 4) AS INTEGER), 100) <> 0) OR (MOD(CAST(SUBSTRING(wrefatu FROM 1 FOR 4) AS INTEGER), 400) = 0))) THEN
                            wdiasdomes = 29;
                         ELSE
                            wdiasdomes = 28;
                       END
                    ELSE
                       wdiasdomes = 30;

                    -- Mês da admissão
                    wdiasadm = 0;
                    IF (wrefatu = CAST((SUBSTRING(CAST(wdataadm AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataadm AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER)) THEN
                       wdiasadm = CAST((SUBSTRING(CAST(wdataadm AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER);

                    -- Mês da rescisão
                    wdiasresc = 0;
                    IF (wrefatu = wrefresc) THEN
                       BEGIN
                         -- Horistas
                         IF (COALESCE(wtipocol,0) IN (2,4)) THEN
                            wdiasresc = (wdiasdomes - CAST((SUBSTRING(CAST(wdataresc AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER));
                         ELSE
                            BEGIN
                              -- Dias do mês
                              IF (COALESCE(wpropresc,0) = 0) THEN
                                 wdiasresc = (wdiasdomes - CAST((SUBSTRING(CAST(wdataresc AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER));
                              ELSE
                                 wdiasresc = (30 - CAST((SUBSTRING(CAST(wdataresc AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER));
                            END
                       END

                    -- Férias
                    wdiasfer = 0;
                    FOR SELECT BDINIPERGOZOFE, BDFIMPERGOZOFE FROM VRH_EMP_TFERIAS
                    WHERE BDCODEMP = :BDCODEMP AND BDCODCOL = :BDCODCOL AND ((BDREFINIFE = :wrefatu) OR (BDREFFIMFE = :wrefatu) OR (BDREFINIFE < :wrefatu AND BDREFFIMFE > :wrefatu)) AND BDINIPERGOZOFE IS NOT NULL INTO :wdataini, :wdatafim DO
                      BEGIN
                        -- férias dentro do mês
                        IF (CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = CAST((SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER)) THEN
                           wdiasfer = wdiasfer + (wdatafim - wdataini) + 1;
                        ELSE
                        -- Início das férias dentro do mês
                        IF (CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = wrefatu) THEN
                           wdiasfer = wdiasfer + (wdiasdomes - CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER)) + 1;
                        ELSE
                        -- Final das férias dentro do mês
                        IF (CAST((SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = wrefatu) THEN
                           wdiasfer = wdiasfer + CAST((SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER);
                        ELSE
                        -- Férias de janeiro a março. No caso de feveireiro estar o mês inteiro de férias
                        IF (CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) < wrefatu AND CAST((SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) > wrefatu) THEN
                           BEGIN
                             IF (COALESCE(wtipocol,0) IN (2,4)) THEN
                                wdiasfer = wdiasdomes;
                             ELSE
                                BEGIN
                                  -- Dias do mês
                                  IF (COALESCE(wpropfer,0) = 0) THEN
                                     wdiasfer = wdiasdomes;
                                  ELSE
                                     wdiasfer = 30;
                                END
                           END
                      END

                    -- Situação
                    wdiassit = 0;
                    FOR SELECT SIT.BDDATAINISIT, SIT.BDDATAFIMSIT FROM VRH_EMP_TSITCOL SIT
                    JOIN VRH_BASE_TPREPSIT PSIT ON (PSIT.BDCODSIT = SIT.BDCODSIT)
                    WHERE SIT.BDCODEMP = :BDCODEMP AND SIT.BDCODCOL = :BDCODCOL AND CAST((SUBSTRING(CAST(SIT.BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(SIT.BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) <= :wrefatu AND
                          ((SIT.BDDATAFIMSIT IS NULL) OR (CAST((SUBSTRING(CAST(SIT.BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(SIT.BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) >= :wrefatu)) AND
                          PSIT.BDGRUPOSIT IN (0,1,2,3,4,6,7,9,10,11)
                     INTO :wdataini, :wdatafim DO
                      BEGIN
                        -- Situação dentro do mês
                        IF (CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = CAST((SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER)) THEN
                           wdiassit = wdiassit + (wdatafim - wdataini) + 1;
                        ELSE
                        -- Início da situação dentro do mês
                        IF (CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = wrefatu) THEN
                           BEGIN
                             -- Horistas
                             IF (COALESCE(wtipocol,0) IN (2,4)) THEN
                                wdiassit = wdiassit + (wdiasdomes - CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER)) + 1;
                             ELSE
                                BEGIN
                                  -- Dias do mês
                                  IF (COALESCE(wpropsit,0) = 0) THEN
                                     wdiassit = wdiassit + (wdiasdomes - CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER)) + 1;
                                  ELSE
                                     wdiassit = wdiassit + (30 - CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER)) + 1;

                                END
                           END
                        ELSE
                        -- Final da situação dentro do mês
                        IF (CAST((SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) = wrefatu) THEN
                           wdiassit = wdiassit + CAST((SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 9 FOR 2)) AS INTEGER);
                        ELSE
                        -- Mês todo em situação
                        IF (CAST((SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdataini AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) < wrefatu AND CAST((SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wdatafim AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) > wrefatu) THEN
                           BEGIN
                             IF (COALESCE(wtipocol,0) IN (2,4)) THEN
                                wdiassit = wdiasdomes;
                             ELSE
                                BEGIN
                                  -- Dias do mês
                                  IF (COALESCE(wpropsit,0) = 0) THEN
                                     wdiassit = wdiasdomes;
                                  ELSE
                                     wdiassit = 30;
                                END
                           END
                      END

                    IF (COALESCE(wtipocol,0) IN (2,4)) THEN
                       wdiastrab = wdiasdomes - wdiasadm - wdiasresc - wdiasfer - wdiassit;
                    ELSE
                       BEGIN
                         IF (wdiasresc > 0 AND COALESCE(wpropresc,0) = 0) THEN
                            wdiastrab = wdiasdomes;
                         ELSE
                         IF (wdiasadm > 0 AND COALESCE(wpropadm,0) IN (0,2)) THEN
                            wdiastrab = wdiasdomes;
                         ELSE
                         IF (wdiasfer > 0 AND COALESCE(wpropfer,0) = 0) THEN
                            wdiastrab = wdiasdomes;
                         ELSE
                         IF (wdiassit > 0 AND COALESCE(wpropsit,0) = 0) THEN
                            wdiastrab = wdiasdomes;
                         ELSE
                            wdiastrab = 30;

                         wdiastrab = wdiastrab - wdiasadm - wdiasresc - wdiasfer - wdiassit;
                       END

                    IF ((wdiastrab IS NULL) OR (wdiastrab < 0)) THEN
                       wdiastrab = 0;

                    bddiastrab = wdiastrab;

                    -- Informações das faltas horas e dias nas folhas.
                    wsqlaux = 'select FN.BDCODVER, FN.BDREFVFN, VER.BDCLAVER, FN.BDCODCENTRO, FN.BDCODTPCC from ('||
                                 'select BDCODVER, BDREFVFN, CAST(null as integer) BDCODCENTRO, CAST(null as integer) BDCODTPCC from VRHF_EMP_TVERBAFN '||
                                 'where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFFN = '||wrefatu||' '||
                                 ' union all '||
                                 'select BDCODVER, BDREFVFC, CAST(null as integer) BDCODCENTRO, CAST(null as integer) BDCODTPCC from VRHF_EMP_TVERBAFC '||
                                 'where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDREFCOMP = '||wrefatu||' '||
                                 ' union all '||
                                 'select FN.BDCODVER, FN.BDREFVFT, PFN.BDCODCENTRO, PFN.BDCODTPCC from VRHF_EMP_TVERBATOMADOR FN '||
                                 'join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FN.BDCODEMP and PFN.BDCODCOL = FN.BDCODCOL and PFN.BDORDEM = FN.BDORDEM) '||
                                 'where FN.BDCODEMP = '||BDCODEMP||' and FN.BDCODCOL = '||BDCODCOL||' and FN.BDREFTOMADOR = '||wrefatu||' '||
                                 ' union all '||
                                 'select FN.BDCODVER, FN.BDREFVFC, PFN.BDCODCENTRO, PFN.BDCODTPCC from VRHF_EMP_TVERBAFCTOMADOR FN '||
                                 'join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FN.BDCODEMP and PFN.BDCODCOL = FN.BDCODCOL and PFN.BDORDEM = FN.BDORDEM) '||
                                 'where FN.BDCODEMP = '||BDCODEMP||' and FN.BDCODCOL = '||BDCODCOL||' and FN.BDREFCOMP = '||wrefatu||
                              ') FN '||
                              'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER) '||
--                              'where ((VER.BDCLAVER starting with ''0.007.0'') or (VER.BDCLAVER starting with ''0.460.0.0'') or ((VER.BDCLAVER starting with ''0.715.0''))) '||
                              'order by FN.BDCODCENTRO, FN.BDCODTPCC, FN.BDCODVER ';

                    wcentroatu = -1;
                    wcodtpccatu = -1;
                    wtotfaltas = 0;

                    FOR EXECUTE STATEMENT wsqlaux INTO :wcodver, :wval, :wclaver, :wcodcentro, :wcodtpcc DO
                      BEGIN
                        IF (wcentroatu = -1) THEN
                           wcentroatu = COALESCE(wcodcentro, 0);

                        IF (wcodtpccatu = -1) THEN
                           wcodtpccatu = COALESCE(wcodtpcc, 0);

                       IF ((wcentroatu <> COALESCE(wcodcentro, 0)) OR (wcodtpccatu <> COALESCE(wcodtpcc, 0))) THEN
                          BEGIN
                            IF (wcentroatu = 0) THEN
                               BDCODCENTRO = NULL;
                            ELSE
                               BDCODCENTRO = wcentroatu;

                            IF (wcodtpccatu = 0) THEN
                               BDCODTPCC = NULL;
                            ELSE
                               BDCODTPCC = wcodtpccatu;

                            BDHORASTRABMES = CAST(bddiastrab * bdhorastrabdia AS NUMERIC(18,2));
                            BDHORASFALTASMES = wtotfaltas;
                            SUSPEND;

                            wcentroatu = COALESCE(wcodcentro, 0);
                            wcodtpccatu = COALESCE(wcodtpcc, 0);
                            wtotfaltas = 0;
                          END


                        wsqlver = 'select first 1 BDTIPOREFVER from VRH_BASE_TVERBAS_REF where BDCODVER = '||wcodver||' and BDREFVER <= '||wrefatu||' order by BDREFVER DESC';
                        EXECUTE STATEMENT wsqlver INTO :wtiporef;

                        IF (wval IS NULL) THEN
                           wval = 0;

                        -- Faltas indevidas
                        IF (SUBSTRING(wclaver FROM 1 FOR 7) = '0.715.0') THEN
                           BEGIN
                             IF (wtiporef = 1 AND COALESCE(UPPER(wconvrefemp), 'FALSE') = 'TRUE') THEN  -- Verba com a referência em horas. Empresa converte referência em horas
                                BEGIN
                                  wintval = CAST(wval - 0.05 AS INTEGER);
                                  wval = wval - wintval;
     
                                  IF (wval > 0) THEN
                                     BEGIN
                                       wval = CAST(wval / 60 * 100 AS NUMERIC(18, 2)) + wintval;
                                     END
                                END
                             ELSE
                             IF (wtiporef = 2) THEN  -- dia
                                wval = CAST(wval * BDHORASTRABDIA AS NUMERIC(18,2));

                             wval = wval * -1;
                           END
                        ELSE
                        IF ((SUBSTRING(wclaver FROM 1 FOR 7) = '0.007.0') OR (SUBSTRING(wclaver FROM 1 FOR 9) = '0.460.0.0') ) THEN
                           BEGIN
                             IF (wtiporef = 1 AND COALESCE(UPPER(wconvrefemp), 'FALSE') = 'TRUE') THEN  -- Verba com a referência em horas. Empresa converte referência em horas
                                BEGIN
                                  wintval = CAST(wval - 0.05 AS INTEGER);
                                  wval = wval - wintval;
     
                                  IF (wval > 0) THEN
                                     BEGIN
                                       wval = CAST(wval / 60 * 100 AS NUMERIC(18, 2)) + wintval;
                                     END
                                END
                             ELSE
                             IF (wtiporef = 2) THEN  -- dia
                                wval = CAST(wval * BDHORASTRABDIA AS NUMERIC(18,2));
                           END
                        ELSE
                        IF (SUBSTRING(wclaver FROM 1 FOR 7) = '0.007.3') THEN --suspensão
                           BEGIN
                             IF (wtiporef = 1 AND COALESCE(UPPER(wconvrefemp), 'FALSE') = 'TRUE') THEN  -- Verba com a referência em horas. Empresa converte referência em horas
                                BEGIN
                                  wintval = CAST(wval - 0.05 AS INTEGER);
                                  wval = wval - wintval;
     
                                  IF (wval > 0) THEN
                                     BEGIN
                                       wval = CAST(wval / 60 * 100 AS NUMERIC(18, 2)) + wintval;
                                     END
                                END
                             ELSE
                             IF (wtiporef = 2) THEN  -- dia
                                wval = CAST(wval * BDHORASTRABDIA AS NUMERIC(18,2));
                           END
                        ELSE
                           wval = 0;

                        wtotfaltas = wtotfaltas + wval;
                      END

                    IF (wcentroatu <> -1 AND wcodtpccatu <> -1) THEN
                       BEGIN
                         IF (wcentroatu = 0) THEN
                            BDCODCENTRO = NULL;
                         ELSE
                            BDCODCENTRO = wcentroatu;

                         IF (wcodtpccatu = 0) THEN
                            BDCODTPCC = NULL;
                         ELSE
                            BDCODTPCC = wcodtpccatu;

                         BDHORASTRABMES = CAST(bddiastrab * bdhorastrabdia AS NUMERIC(18,2));
                         BDHORASFALTASMES = wtotfaltas;
                         SUSPEND;
                       END
                  END
             END
        END

      IF (SUBSTRING(wrefatu FROM 5 FOR 2) = '12' ) THEN
         wrefatu = CAST((CAST((CAST(SUBSTRING(wrefatu FROM 1 FOR 4) AS INTEGER) + 1) AS VARCHAR(4))||'01') AS INTEGER);
      ELSE
         BEGIN
           IF (CAST(SUBSTRING(wrefatu FROM 5 FOR 2) AS INTEGER) < 9) THEN
              wrefatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||'0'||CAST((CAST(SUBSTRING(wrefatu FROM 5 FOR 2) AS INTEGER) + 1) AS VARCHAR(1))) AS INTEGER);
           ELSE
              wrefatu = CAST((SUBSTRING(wrefatu FROM 1 FOR 4)||CAST((CAST(SUBSTRING(wrefatu FROM 5 FOR 2) AS INTEGER) + 1) AS VARCHAR(2))) AS INTEGER);
         END
    END

END^

--Sol. 19692 - Ajuste para não ocorrer erro na comparação do campo da data final com a data de rescisão - Bruno L. R. - 17/07/2017
create or alter procedure SP_APURADOS_VALTRANS (
    PRCODEMP varchar(25000),
    PRCOLABORADOR varchar(32700),
    PRCOMPETENCIA integer,
    PRNRVIAS integer)
returns (
    BDNRVIA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODITI integer,
    BDCOMPETENCIA integer,
    BDQUANTIDADE integer,
    BDTPAPURACAO integer,
    BDDTINICIAL date,
    BDDTFINAL date,
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDRGCOL varchar(20),
    BDCPFCOL varchar(14),
    BDDESCITI varchar(40),
    BDLINHAITI varchar(20),
    BDVALUNI numeric(18,6),
    BDVALCUSTOEMP numeric(18,6),
    BDVALDESCONTO numeric(18,6),
    BDQTDITINERARIOS integer,
    BDFECHAMENTOVT integer,
    BDFECHAMENTO integer,
    BDVALOREMPRESA numeric(18,2),
    BDVALORDESCCOL numeric(18,2))
as
declare variable WVIA integer;
declare variable WBDCODEMP integer;
declare variable WBDCODCOL integer;
declare variable WBDCODITI integer;
declare variable WBDCOMPETENCIA integer;
declare variable WBDQUANTIDADE integer;
declare variable WBDTAPURACAO integer;
declare variable WBDDTINICIAL date;
declare variable WBDDTFINAL date;
declare variable WBDNOMCOL DM_BDNOMCOL;
declare variable WBDNOMCOLUPPER DM_BDNOMCOL;
declare variable WBDRGCOL varchar(20);
declare variable WBDCPFCOL varchar(30);
declare variable WBDDESCITI varchar(50);
declare variable WBDLINHAITI varchar(20);
declare variable WBDVALUNI numeric(18,6);
declare variable WBDVALCUSTOEMP numeric(18,6);
declare variable WBDVALDESCONTO numeric(18,6);
declare variable WBDQTDITINERARIOS integer;
declare variable WSQL varchar(30000);
declare variable WSQLDATA varchar(10000);
declare variable WWHERE varchar(10000);
declare variable WBDDATAADMCOL date;
declare variable WBDDATARESCISAO date;
declare variable WSQLCUSTOEMP varchar(2000);
declare variable WFECHAVTEMP integer;
declare variable WFECHAEMP integer;
declare variable WULTDIA integer;
BEGIN
  WBDQTDITINERARIOS = 0;
  WVIA = 1;

  WSQL = 'select ValeTrans.*, cast (null as Date) BDDTINICIAL, cast(null as Date) BDDTFINAL, COLCAD.BDNOMCOL, COLCAD.BDNOMCOLUPPER, DOCREF.BDRGCOL, ColCon.BDCPFCOL, Iti.BDDESCITI, '||
        'Iti.BDLINHAITI, Iti.BDVALITI BDVALUNI, 0 BDVALCUSTOEMP, 0 BDVALDESCONTO, ColCon.BDDATAADMCOL, Resc.BDDATARESCISAO '||
        'from VRHF_EMP_TAPVALTRANS ValeTrans '||
        'left outer join VRH_EMP_TCOLCON ColCon on (ColCon.BDCODEMP = ValeTrans.BDCODEMP and ColCon.BDCODCOL = ValeTrans.BDCODCOL) '||
        'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = VALETRANS.BDCODEMP and COLCAD.BDCODCOL = VALETRANS.BDCODCOL) '||
        'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = VALETRANS.BDCODEMP and DOCREF.BDCODCOL = VALETRANS.BDCODCOL) '||
        'left outer join VRH_EMP_TCOLCON_DOC ColConDoc on (ColConDoc.BDCODEMP = ValeTrans.BDCODEMP and ColConDoc.BDCODCOL = ValeTrans.BDCODCOL) '||
        'left outer join VW_VRHF_BASE_TITINERARIOS_REF Iti on (Iti.BDCODITI = ValeTrans.BDCODITI) '||
        'left outer join VW_RESCISAO Resc on (Resc.BDCODEMP = ValeTrans.BDCODEMP and Resc.BDCODCOL = ValeTrans.BDCODCOL) ';

  WWHERE = '';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     BEGIN
      WWHERE = ' where '||PRCODEMP||' ';

      IF (PRCOLABORADOR IS NOT NULL AND PRCOLABORADOR <> '') THEN
         WWHERE = WWHERE||' and '||PRCOLABORADOR||' ';
     END

   IF (PRCOMPETENCIA IS NOT NULL AND PRCOMPETENCIA <> 0) THEN
      BEGIN
        IF (WWHERE = '') THEN
           WWHERE = WWHERE||' where ValeTrans.BDCOMPETENCIA = '||PRCOMPETENCIA;
        ELSE
           WWHERE = WWHERE||' and ValeTrans.BDCOMPETENCIA = '||PRCOMPETENCIA;
      END

   WSQL = WSQL||WWHERE||' order by ValeTrans.BDCODEMP, ValeTrans.BDCODCOL, ValeTrans.BDCODITI, ValeTrans.BDCOMPETENCIA';

--   EXECUTE STATEMENT 'select ULTDIA from ULTIMO_DIA_MES('||SUBSTRING(prcompetencia FROM 5 FOR 2)||', '||SUBSTRING(prcompetencia FROM 1 FOR 4)||')' INTO :wultdia;

   FOR EXECUTE STATEMENT WSQL INTO
     WBDCODEMP,
     WBDCODCOL,
     WBDCODITI,
     WBDCOMPETENCIA,
     WBDQUANTIDADE,
     WBDTAPURACAO,
     WBDDTINICIAL,
     WBDDTFINAL,
     WBDNOMCOL,
     WBDNOMCOLUPPER,
     WBDRGCOL,
     WBDCPFCOL,
     WBDDESCITI,
     WBDLINHAITI,
     WBDVALUNI,
     WBDVALCUSTOEMP,
     WBDVALDESCONTO,
     WBDDATAADMCOL,
     WBDDATARESCISAO
   DO
   BEGIN
     WVIA          = 1;
     BDVALCUSTOEMP = 0;

     WHILE (WVIA <= PRNRVIAS) DO
       BEGIN
         BDNRVIA       = WVIA;
         BDCODEMP      = WBDCODEMP;
         BDCODCOL      = WBDCODCOL;
         BDCODITI      = WBDCODITI;
         BDCOMPETENCIA = WBDCOMPETENCIA;
         BDQUANTIDADE  = WBDQUANTIDADE;
         BDTPAPURACAO  = WBDTAPURACAO;

         WSQLDATA    = 'select first 1 BDFECHAVTEMP, BDFECHAMESEMP from VRHF_BASE_TEMPCALC where BDCODEMP = '||BDCODEMP||' and BDREFEMP <= '||prcompetencia||' order by BDREFEMP DESC';
         WFECHAVTEMP = null;
         EXECUTE STATEMENT WSQLDATA INTO :WFECHAVTEMP, :WFECHAEMP;
    
         BDFECHAMENTOVT = wfechavtemp;
         BDFECHAMENTO   = wfechaemp;

         EXECUTE STATEMENT 'select ULTDIA from ULTIMO_DIA_MES('||SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2)||', '||SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4)||')' INTO :wultdia;

         if ((coalesce(wfechavtemp, 0) = 0) or (wfechavtemp > wultdia)) then
            begin
              WBDDTINICIAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/01/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);

              if (coalesce(wfechavtemp, 0) = 0) then
                 WBDDTFINAL = null;
              else
                 begin
--                    if (SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) = '02') then
--                      begin
--                        /*Entra aqui se for no mês de Fevereiro*/
--                        wultdia = 28;
--                      end
--                    else
--                      begin
--                        if (wultdia >= 30) then
--                          begin
--                            wultdia = 30;
--                          end
--                        else
--                          begin
--                            wultdia = wultdia;
--                          end
--                      end

                    WBDDTFINAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/' ||wultdia|| '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
                 end
            end
         else
            begin
                  begin
                    if (WFECHAVTEMP >= 30) then
                      begin
                        if (SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) = '02') then
                          begin
                            WFECHAVTEMP  = 28;
                            WBDDTFINAL   = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2)|| '/' ||WFECHAVTEMP || '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
                            WBDDTINICIAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2)||'/01/' ||SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
                          end
                        else
                          begin
                            /*Quando a data de fechamento for maior que ou >= 30 coloca a data de fechamento como 30 para data final e 01 para data inicial*/
                            if (WFECHAVTEMP >= 30) then
                              begin
--                                wultdia = null;
--                                EXECUTE STATEMENT 'select ULTDIA from ULTIMO_DIA_MES('||SUBSTRING(prcompetencia FROM 5 FOR 2)||', '||SUBSTRING(prcompetencia FROM 1 FOR 4)||')' INTO :wultdia;

                                WFECHAVTEMP  = wultdia;
                              end

                            WBDDTFINAL   = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2)|| '/' ||WFECHAVTEMP || '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
                            WBDDTINICIAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2)||'/01/' ||SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
                          end
                      end
                    else
                      begin
                        /*Quando a data de fechamento for <= 30 e não for janeiro ele pega a data de fechamento e coloca como data final e como data inicial coloca um mês a menos e um dia a mais */
                        WFECHAVTEMP  = WFECHAVTEMP;
                        WBDDTFINAL   = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/' ||WFECHAVTEMP || '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
                        WBDDTINICIAL = DATEADD(DAY, 1, DATEADD(MONTH, -1, WBDDTFINAL));
                      end
                  end
            end

         IF (WBDDTINICIAL < WBDDATAADMCOL) THEN
            BEGIN
              WBDDTINICIAL = WBDDATAADMCOL;
            END
    
         IF (((SUBSTRING(WBDDATARESCISAO FROM 1 FOR 4) || SUBSTRING(WBDDATARESCISAO FROM 6 FOR 2)) = BDCOMPETENCIA) AND (WBDDTFINAL > WBDDATARESCISAO)) THEN
            BEGIN
              WBDDTFINAL = WBDDATARESCISAO;
            END
    
         BDDTINICIAL = WBDDTINICIAL;
         BDDTFINAL = WBDDTFINAL;


         WSQLCUSTOEMP = 'select (ValTrans.BDQUANTIDADE * Iti.BDVALITI) from VRHF_EMP_TAPVALTRANS ValTrans '||
            'left outer join VW_VRHF_BASE_TITINERARIOS_REF Iti on (Iti.BDCODITI = ValTrans.BDCODITI) '||
         'where ValTrans.BDCODEMP='||BDCODEMP||' and ValTrans.BDCODCOL='||BDCODCOL||' and ValTrans.BDCOMPETENCIA='||PRCOMPETENCIA;

         FOR EXECUTE STATEMENT WSQLCUSTOEMP INTO WBDVALCUSTOEMP DO
           BEGIN
             BDVALCUSTOEMP = BDVALCUSTOEMP + WBDVALCUSTOEMP;
           END

         BDNOMCOL = WBDNOMCOL;
         BDNOMCOLUPPER = WBDNOMCOLUPPER;
         BDRGCOL = WBDRGCOL;
         BDCPFCOL = WBDCPFCOL;
         BDDESCITI = WBDDESCITI;
         BDLINHAITI = WBDLINHAITI;
         BDVALUNI = WBDVALUNI;
         BDVALDESCONTO = WBDVALDESCONTO;
         WBDQTDITINERARIOS = WBDQTDITINERARIOS + 1;
         BDQTDITINERARIOS = WBDQTDITINERARIOS;
         BDVALOREMPRESA = BDVALCUSTOEMP;
         BDVALORDESCCOL = 0;

         WSQLCUSTOEMP = 'select FN.BDVALVFN from VRHF_EMP_TVERBAFN FN '||
                        'left outer join VRH_BASE_TVERBAS Ver on (Ver.BDCODVER = FN.BDCODVER) '||
                        'where FN.BDCODEMP = '||BDCODEMP||' and FN.BDCODCOL = '||BDCODCOL||' and FN.BDREFFN = '||prcompetencia||
                           ' and Ver.BDCLAVER starting with ''0.008.0.0'' ';

           FOR EXECUTE STATEMENT WSQLCUSTOEMP INTO WBDVALCUSTOEMP DO
           BEGIN
             BDVALOREMPRESA = BDVALOREMPRESA - WBDVALCUSTOEMP;
             BDVALORDESCCOL = BDVALORDESCCOL + WBDVALCUSTOEMP;
           END

         WSQLCUSTOEMP = 'select FN.BDVALVFN from VRHF_EMP_TVERBAINT FN '||
                        'left outer join VRH_BASE_TVERBAS Ver on (Ver.BDCODVER = FN.BDCODVER) '||
                        'where FN.BDCODEMP = '||BDCODEMP||' and FN.BDCODCOL = '||BDCODCOL||' and FN.BDREFFN = '||prcompetencia||
                           ' and Ver.BDCLAVER starting with ''0.008.0.0'' ';

           FOR EXECUTE STATEMENT WSQLCUSTOEMP INTO WBDVALCUSTOEMP DO
           BEGIN
             BDVALOREMPRESA = BDVALOREMPRESA - WBDVALCUSTOEMP;
             BDVALORDESCCOL = BDVALORDESCCOL + WBDVALCUSTOEMP;
           END

         WSQLCUSTOEMP = 'select FN.BDVALVFT from VRHF_EMP_TVERBATOMADOR FN '||
                        'left outer join VRH_BASE_TVERBAS Ver on (Ver.BDCODVER = FN.BDCODVER) '||
                        'where FN.BDCODEMP = '||BDCODEMP||' and FN.BDCODCOL = '||BDCODCOL||' and FN.BDREFTOMADOR = '||prcompetencia||
                           ' and Ver.BDCLAVER starting with ''0.008.0.0'' ';

           FOR EXECUTE STATEMENT WSQLCUSTOEMP INTO WBDVALCUSTOEMP DO
           BEGIN
             BDVALOREMPRESA = BDVALOREMPRESA - WBDVALCUSTOEMP;
             BDVALORDESCCOL = BDVALORDESCCOL + WBDVALCUSTOEMP;
           END

         WSQLCUSTOEMP = 'select FN.BDVALVFT from VRHF_EMP_TVERBATOMINT FN '||
                        'left outer join VRH_BASE_TVERBAS Ver on (Ver.BDCODVER = FN.BDCODVER) '||
                        'where FN.BDCODEMP = '||BDCODEMP||' and FN.BDCODCOL = '||BDCODCOL||' and FN.BDREFTOMADOR = '||prcompetencia||
                           ' and Ver.BDCLAVER starting with ''0.008.0.0'' ';

           FOR EXECUTE STATEMENT WSQLCUSTOEMP INTO WBDVALCUSTOEMP DO
           BEGIN
             BDVALOREMPRESA = BDVALOREMPRESA - WBDVALCUSTOEMP;
             BDVALORDESCCOL = BDVALORDESCCOL + WBDVALCUSTOEMP;
           END

         if (coalesce(BDVALOREMPRESA, 0) < 0) then
            BDVALOREMPRESA = 0;

         WVIA = WVIA + 1;
         SUSPEND;
         BDVALCUSTOEMP = 0;

       END
   END
END
^

--Sol. 19692 - Ajuste para não ocorrer erro na comparação do campo da data final com a data de rescisão - Bruno L. R. - 17/07/2017
/* Restore proc. body: SP_APURADOS_VALREF */
create or alter procedure SP_APURADOS_VALREF (
    PRCODEMP varchar(6000),
    PRCOLABORADOR varchar(6000),
    PRCOMPETENCIA integer,
    PRNRVIAS integer,
    PRDATAINICIAL date = null,
    PRDATAFINAL date = null)
returns (
    BDNRVIA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODCONVREF integer,
    BDCOMPETENCIA integer,
    BDQUANTIDADE integer,
    BDTPAPURACAO integer,
    BDDTINICIAL date,
    BDDTFINAL date,
    BDDESCCONVREF varchar(50),
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDRGCOL varchar(20),
    BDCPFCOL varchar(14),
    BDVALUNI numeric(18,6),
    BDVALCUSTOEMP numeric(18,6),
    BDVALDESCONTO numeric(18,6),
    BDQTDCONVENIOREF integer,
    BDFECHAMENTOVT integer,
    BDFECHAMENTO integer,
    BDVALOREMPRESA numeric(18,2),
    BDVALORDESCCOL numeric(18,2))
as
declare variable WVIA integer;
declare variable WBDCODEMP integer;
declare variable WBDCODCOL integer;
declare variable WFECHAVTEMP integer;
declare variable WBDCODCONVREF integer;
declare variable WBDCOMPETENCIA integer;
declare variable WBDQUANTIDADE integer;
declare variable WBDTAPURACAO integer;
declare variable WBDDTINICIAL date;
declare variable WBDDTFINAL date;
declare variable WBDDESCCONVREF varchar(50);
declare variable WBDNOMCOL DM_BDNOMCOL;
declare variable WBDNOMCOLUPPER DM_BDNOMCOL;
declare variable WBDRGCOL varchar(20);
declare variable WBDCPFCOL varchar(30);
declare variable WBDVALUNI numeric(18,6);
declare variable WBDVALCUSTOEMP numeric(18,6);
declare variable WBDVALDESCONTO numeric(18,6);
declare variable WBDQTDCONVENIOREF integer;
declare variable WSQL varchar(30000);
declare variable WSQLDATA varchar(10000);
declare variable WSQLCUSTOEMP varchar(20000);
declare variable WWHERE varchar(10000);
declare variable WBDDATAADMCOL date;
declare variable WBDDATARESCISAO date;
declare variable WFECHAEMP integer;
declare variable WULTDIA integer;
declare variable WPERIODO varchar(16);
BEGIN
  WBDQTDCONVENIOREF = 0;
  WVIA = 1;

  WSQL = 'select ValeRef.BDCODEMP,ValeRef.BDCODCOL,ValeRef.BDCODCONVREF,ValeRef.BDCOMPETENCIA,ValeRef.BDQUANTIDADE,ValeRef.BDTPAPURACAO,'||
        'ValeRef.BDINICIOAPURACAO, ValeRef.BDFINALAPURACAO, COLCAD.BDNOMCOL, COLCAD.BDNOMCOLUPPER, DOCREF.BDRGCOL, ColCon.BDCPFCOL, '||
        'Conv.BDVALUNI BDVALUNI, 0 BDVALCUSTOEMP, 0 BDVALDESCONTO, COLCON.BDDATAADMCOL, Resc.BDDATARESCISAO, Conv.BDDESC BDDESCCONVREF, '||
        'ValeRef.BDPERIODO '||
        'from VRHF_EMP_TAPVALREF ValeRef '||
        'left outer join VRH_EMP_TCOLCON ColCon on (ColCon.BDCODEMP = ValeRef.BDCODEMP and ColCon.BDCODCOL = ValeRef.BDCODCOL) '||
        'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = VALEREF.BDCODEMP and COLCAD.BDCODCOL = VALEREF.BDCODCOL) '||
        'left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (DOCREF.BDCODEMP = VALEREF.BDCODEMP and DOCREF.BDCODCOL = VALEREF.BDCODCOL) '||
        'left outer join VRH_EMP_TCOLCON_DOC ColConDoc on (ColConDoc.BDCODEMP = ValeRef.BDCODEMP and ColConDoc.BDCODCOL = ValeRef.BDCODCOL) '||
        'left outer join VW_VRHF_BASE_TCONVREFEICAO_REF Conv on (Conv.BDCODCONVREF = ValeRef.BDCODCONVREF)  '||
        'left outer join VW_RESCISAO Resc on (Resc.BDCODEMP = ValeRef.BDCODEMP and Resc.BDCODCOL = ValeRef.BDCODCOL) ';

  WWHERE = '';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
     BEGIN
      WWHERE = ' where '||PRCODEMP||' ';

      IF (PRCOLABORADOR IS NOT NULL AND PRCOLABORADOR <> '') THEN
         WWHERE = WWHERE||' and '||PRCOLABORADOR||' ';
     END

   if (prdatainicial is not null and prdatafinal is not null) then
      begin
        if (wwhere = '') then
           wwhere = ' where ';
        else
           wwhere = wwhere||' and ';

        wwhere = wwhere||'ValeRef.BDINICIOAPURACAO <= '''||prdatafinal||''' and ValeRef.BDFINALAPURACAO >= '''||prdatainicial||''' ';
      end
   else
   IF (PRCOMPETENCIA IS NOT NULL AND PRCOMPETENCIA <> 0) THEN
      BEGIN
        IF (WWHERE = '') THEN
           WWHERE = WWHERE||' where ValeRef.BDCOMPETENCIA = '||PRCOMPETENCIA;
        ELSE
           WWHERE = WWHERE||' and ValeRef.BDCOMPETENCIA = '||PRCOMPETENCIA;
      END

   WSQL = WSQL||WWHERE||' order by ValeRef.BDCODEMP, ValeRef.BDCODCOL, ValeRef.BDCODCONVREF, ValeRef.BDCOMPETENCIA, ValeRef.BDPERIODO ';

--   EXECUTE STATEMENT 'select ULTDIA from ULTIMO_DIA_MES('||SUBSTRING(prcompetencia FROM 5 FOR 2)||', '||SUBSTRING(prcompetencia FROM 1 FOR 4)||')' INTO :wultdia;

   FOR EXECUTE STATEMENT WSQL INTO
     WBDCODEMP,
     WBDCODCOL,
     WBDCODCONVREF,
     WBDCOMPETENCIA,
     WBDQUANTIDADE,
     WBDTAPURACAO,
     WBDDTINICIAL,
     WBDDTFINAL,
     WBDNOMCOL,
     WBDNOMCOLUPPER,
     WBDRGCOL,
     WBDCPFCOL,
     WBDVALUNI,
     WBDVALCUSTOEMP,
     WBDVALDESCONTO,
     WBDDATAADMCOL,
     WBDDATARESCISAO,
     WBDDESCCONVREF,
     wperiodo
   DO
   BEGIN
     WVIA = 1;
     WHILE (WVIA <= PRNRVIAS) DO
       BEGIN
         BDNRVIA = WVIA;
         BDCODEMP = WBDCODEMP;
         BDCODCOL = WBDCODCOL;
         BDCODCONVREF = WBDCODCONVREF;
         BDCOMPETENCIA = WBDCOMPETENCIA;
         BDQUANTIDADE = WBDQUANTIDADE;
         BDTPAPURACAO = WBDTAPURACAO;

         WSQLDATA = 'select first 1 BDFECHAVTEMP, BDFECHAMESEMP from VRHF_BASE_TEMPCALC where BDCODEMP = '||BDCODEMP||' and BDREFEMP <= '||prcompetencia||' order by BDREFEMP DESC';
         EXECUTE STATEMENT WSQLDATA INTO WFECHAVTEMP, WFECHAEMP;

         BDFECHAMENTOVT = wfechavtemp;
         BDFECHAMENTO   = wfechaemp;

         EXECUTE STATEMENT 'select ULTDIA from ULTIMO_DIA_MES('||SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2)||', '||SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4)||')' INTO :wultdia;

         if ((coalesce(wfechavtemp, 0) = 0) or (wfechavtemp > wultdia)) then
            begin
              WBDDTINICIAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/01/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);

              if (coalesce(wfechavtemp, 0) = 0) then
                 WBDDTFINAL = null;
              else
                 begin
--                    if (SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) = '02') then
--                      begin
--                        /*Entra aqui se for no mês de Fevereiro*/
--                        wultdia = 28;
--                      end
--                    else
--                      begin
--                        if (wultdia >= 30) then
--                          begin
--                            wultdia = 30;
--                          end
--                        else
--                          begin
--                            wultdia = wultdia;
--                          end
--                      end

                    WBDDTFINAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/' ||wultdia|| '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
                 end
            end
         else
            begin
                  begin
                    if (WFECHAVTEMP >= 30) then
                      begin
                        if (SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) = '02') then
                          begin
                            WFECHAVTEMP  = 28;
                            WBDDTFINAL   = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2)|| '/' ||WFECHAVTEMP || '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
                            WBDDTINICIAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2)||'/01/' ||SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
                          end
                        else
                          begin
                            /*Quando a data de fechamento for maior que ou >= 30 coloca a data de fechamento como 30 para data final e 01 para data inicial*/
                            if (WFECHAVTEMP >= 30) then
                              begin
--                                wultdia = null;
--                                EXECUTE STATEMENT 'select ULTDIA from ULTIMO_DIA_MES('||SUBSTRING(prcompetencia FROM 5 FOR 2)||', '||SUBSTRING(prcompetencia FROM 1 FOR 4)||')' INTO :wultdia;

                                WFECHAVTEMP  = wultdia;
                              end

                            WBDDTFINAL   = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2)|| '/' ||WFECHAVTEMP || '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
                            WBDDTINICIAL = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2)||'/01/' ||SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
                          end
                      end
                    else
                      begin
                        /*Quando a data de fechamento for <= 30 e não for janeiro ele pega a data de fechamento e coloca como data final e como data inicial coloca um mês a menos e um dia a mais */
                        WFECHAVTEMP  = WFECHAVTEMP;
                        WBDDTFINAL   = SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2) || '/' ||WFECHAVTEMP || '/' || SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4);
                        WBDDTINICIAL = DATEADD(DAY, 1, DATEADD(MONTH, -1, WBDDTFINAL));
                      end
                  end
            end

         IF (WBDDTINICIAL < WBDDATAADMCOL) THEN
            BEGIN
              WBDDTINICIAL = WBDDATAADMCOL;
            END
    
         IF (((SUBSTRING(WBDDATARESCISAO FROM 1 FOR 4) || SUBSTRING(WBDDATARESCISAO FROM 6 FOR 2)) = BDCOMPETENCIA) AND (WBDDTFINAL > WBDDATARESCISAO)) THEN
            BEGIN
              WBDDTFINAL = WBDDATARESCISAO;
            END
    
         BDDTINICIAL = WBDDTINICIAL;
         BDDTFINAL = WBDDTFINAL;


         WSQLCUSTOEMP = 'select distinct (ValRef.BDQUANTIDADE * Conv.BDVALUNI) from VRHF_EMP_TAPVALREF ValRef '||
            'left outer join VW_VRHF_BASE_TCONVREFEICAO_REF Conv on (Conv.BDCODCONVREF = ValRef.BDCODCONVREF) '||            -- Sol. 134797 | Michel Luciano | 17/03/2020.
         'where ValRef.BDCODEMP='||BDCODEMP||' and ValRef.BDCODCOL='||BDCODCOL||' and ValRef.BDCOMPETENCIA='||BDCOMPETENCIA||' and ValRef.BDCODCONVREF='||WBDCODCONVREF||
            ' and ValRef.BDPERIODO = '''||wperiodo||''' ';

         EXECUTE STATEMENT WSQLCUSTOEMP INTO WBDVALCUSTOEMP;

         BDNOMCOL = WBDNOMCOL;
         BDNOMCOLUPPER = WBDNOMCOLUPPER;
         BDRGCOL = WBDRGCOL;
         BDCPFCOL = WBDCPFCOL;
         BDVALUNI = WBDVALUNI;
         BDVALCUSTOEMP = WBDVALCUSTOEMP;
         BDVALDESCONTO = WBDVALDESCONTO;
         WBDQTDCONVENIOREF = WBDQTDCONVENIOREF + 1;
         BDQTDCONVENIOREF = WBDQTDCONVENIOREF;
         BDDESCCONVREF = WBDDESCCONVREF;

         BDVALOREMPRESA = BDVALCUSTOEMP;
         BDVALORDESCCOL = 0;

         WSQLCUSTOEMP = 'select FN.BDVALVFN from VRHF_EMP_TVERBAFN FN '||
                        'left outer join VRH_BASE_TVERBAS Ver on (Ver.BDCODVER = FN.BDCODVER) '||
                        'where FN.BDCODEMP = '||BDCODEMP||' and FN.BDCODCOL = '||BDCODCOL||' and FN.BDREFFN = '||BDCOMPETENCIA||
                           ' and Ver.BDCLAVER starting with ''0.008.0.2'' ';

           FOR EXECUTE STATEMENT WSQLCUSTOEMP INTO WBDVALCUSTOEMP DO
           BEGIN
             BDVALOREMPRESA = BDVALOREMPRESA - WBDVALCUSTOEMP;
             BDVALORDESCCOL = BDVALORDESCCOL + WBDVALCUSTOEMP;
           END

         WSQLCUSTOEMP = 'select FN.BDVALVFN from VRHF_EMP_TVERBAINT FN '||
                        'left outer join VRH_BASE_TVERBAS Ver on (Ver.BDCODVER = FN.BDCODVER) '||
                        'where FN.BDCODEMP = '||BDCODEMP||' and FN.BDCODCOL = '||BDCODCOL||' and FN.BDREFFN = '||BDCOMPETENCIA||
                           ' and Ver.BDCLAVER starting with ''0.008.0.2'' ';

           FOR EXECUTE STATEMENT WSQLCUSTOEMP INTO WBDVALCUSTOEMP DO
           BEGIN
             BDVALOREMPRESA = BDVALOREMPRESA - WBDVALCUSTOEMP;
             BDVALORDESCCOL = BDVALORDESCCOL + WBDVALCUSTOEMP;
           END

         WSQLCUSTOEMP = 'select FN.BDVALVFT from VRHF_EMP_TVERBATOMADOR FN '||
                        'left outer join VRH_BASE_TVERBAS Ver on (Ver.BDCODVER = FN.BDCODVER) '||
                        'where FN.BDCODEMP = '||BDCODEMP||' and FN.BDCODCOL = '||BDCODCOL||' and FN.BDREFTOMADOR = '||BDCOMPETENCIA||
                           ' and Ver.BDCLAVER starting with ''0.008.0.2'' ';

           FOR EXECUTE STATEMENT WSQLCUSTOEMP INTO WBDVALCUSTOEMP DO
           BEGIN
             BDVALOREMPRESA = BDVALOREMPRESA - WBDVALCUSTOEMP;
             BDVALORDESCCOL = BDVALORDESCCOL + WBDVALCUSTOEMP;
           END

         WSQLCUSTOEMP = 'select FN.BDVALVFT from VRHF_EMP_TVERBATOMINT FN '||
                        'left outer join VRH_BASE_TVERBAS Ver on (Ver.BDCODVER = FN.BDCODVER) '||
                        'where FN.BDCODEMP = '||BDCODEMP||' and FN.BDCODCOL = '||BDCODCOL||' and FN.BDREFTOMADOR = '||BDCOMPETENCIA||
                           ' and Ver.BDCLAVER starting with ''0.008.0.2'' ';

           FOR EXECUTE STATEMENT WSQLCUSTOEMP INTO WBDVALCUSTOEMP DO
           BEGIN
             BDVALOREMPRESA = BDVALOREMPRESA - WBDVALCUSTOEMP;
             BDVALORDESCCOL = BDVALORDESCCOL + WBDVALCUSTOEMP;
           END

         if (coalesce(BDVALOREMPRESA, 0) < 0) then
            BDVALOREMPRESA = 0;

         WVIA = WVIA + 1;
         SUSPEND;
       END
     END
END^

--Sol. 18845 - Bruno L. R. - 10/06/2017 - Procedure para retornar as informações de percentual de gorjeta do cadastro do colaborador.
CREATE OR ALTER procedure SP_PERC_GORJETA (
    PRCODEMP varchar(2000),
    PRCODCOL varchar(2000),
    PRREF integer,
    PRHISTTRANSF integer = 0,
    PRPODE integer = 1)
returns (
    BDREFCOL varchar(10),
    BDPERCGORJ numeric(18,6),
    BDNOMCOL varchar(200),
    BDCODCOL integer,
    BDCODEMP integer,
    BDCODEMPORIG integer,
    BDCODCOLORIG integer)
as
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WNOMCOL varchar(200);
declare variable WPERCGORJ numeric(18,6);
declare variable WREFCOL integer;
declare variable WSQL varchar(20000);
declare variable WSQL2 varchar(20000);
declare variable WCOUNT integer;
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
declare variable WSQL3 varchar(2000);
BEGIN
  if (PRPODE = 1) then
    BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRREF);
    
  WSQL = ' select BDCODEMP, BDCODCOL from VW_VRHF_EMP_TCOL_CALC COL ';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
     BEGIN
       WSQL = WSQL || ' where '||prcodemp;
       IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
          WSQL = WSQL || ' and '||PRCODCOL;
     END
  ELSE
     BEGIN
       IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
          WSQL = WSQL || ' where '||PRCODCOL;
     END
    
  FOR EXECUTE STATEMENT WSQL INTO
    WCODEMP,
    WCODCOL
  DO
  BEGIN
    if (PRHISTTRANSF = 1) then
       BEGIN
         WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = ' || WCODEMP || ' and BDCODCOLDEST = ' || WCODCOL;
         FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
           BEGIN
             IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
               BEGIN
             WSQL3 = 'SELECT * FROM SP_PERC_GORJETA(''BDCODEMP = '||wcodemporig||''', ''BDCODCOL = ' || wcodcolorig || ''',' || PRREF || ',' ||  PRHISTTRANSF || ')';
             FOR EXECUTE STATEMENT wsql3 INTO
               :BDREFCOL,
               :BDPERCGORJ,
               :BDNOMCOL,
               :BDCODCOL,
               :BDCODEMP,
               :BDCODEMPORIG,
               :BDCODCOLORIG DO
                   BEGIN
                 BDCODEMP = WCODEMP;
                 BDCODCOL = WCODCOL;
                 SUSPEND;
           END
       END
           END
       END
    
    WCOUNT = 0;
    WSQL2 = 'select COL.BDCODEMP, COL.BDCODCOL, COL.BDNOMCOL, CALC.BDPERCGORJ, CALC.BDREFCOL '||
                'from VW_VRH_EMP_TCOLCON_CAD COL '||
                'left outer join VRHF_EMP_TCOL_CALC CALC on (CALC.BDCODEMP = COL.BDCODEMP and CALC.BDCODCOL = COL.BDCODCOL) '||
                'where CALC.BDPERCGORJ is not null and COL.BDCODEMP='||WCODEMP||' and COL.BDCODCOL='||WCODCOL||' '||
                'order by COL.BDCODEMP, COL.BDCODCOL, CALC.BDREFCOL ';
    
    FOR EXECUTE STATEMENT WSQL2 INTO
      WCODEMP,
      WCODCOL,
      WNOMCOL,
      WPERCGORJ,
      WREFCOL
    DO
      BEGIN
        IF (WCOUNT = 0) THEN
           BEGIN
             BDCODEMP = WCODEMP;
             BDCODCOL = WCODCOL;
             BDNOMCOL = WNOMCOL;
             BDPERCGORJ = WPERCGORJ;
             BDREFCOL = SUBSTRING(WREFCOL FROM 5 FOR 2)||'/'||SUBSTRING(WREFCOL FROM 1 FOR 4);
             bdcodemporig = bdcodemp;
             bdcodcolorig = bdcodcol;
             SUSPEND;
           END
        ELSE
           BEGIN
             IF (BDPERCGORJ <> WPERCGORJ) THEN
                BEGIN
                  BDCODEMP = WCODEMP;
                  BDCODCOL = WCODCOL;
                  BDNOMCOL = WNOMCOL;
                  BDPERCGORJ = WPERCGORJ;
                  BDREFCOL = SUBSTRING(WREFCOL FROM 5 FOR 2)||'/'||SUBSTRING(WREFCOL FROM 1 FOR 4);
                  bdcodemporig = bdcodemp;
                  bdcodcolorig = bdcodcol;
                  SUSPEND;
                END
           END
    
        WCOUNT = WCOUNT + 1;
      END
  END
    END
  ELSE
     BEGIN
       BDCODEMP = 0;
       BDCODCOL = 0;
       SUSPEND;
     END
END^


CREATE OR ALTER TRIGGER vrh_base_taut_publica_bi0 FOR vrh_base_taut_publica
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF ((NEW.bdcodautpub IS NULL) OR (NEW.bdcodautpub = 0)) THEN
     SELECT COALESCE(MAX(bdcodautpub),0)+1 FROM vrh_base_taut_publica INTO NEW.bdcodautpub;
END
^

CREATE OR ALTER trigger vef_base_tplanoacoestroca_au0 for vef_base_tplanoacoestroca
active after update position 0
AS
declare variable wCFOP INTEGER;
begin
  if (new.bdcodnat is not null) then
    begin
      --sempre deve jogar na tabela de varias cfops
      select bdcodnat from VEF_BASE_TPLANOACOESTROCACFOPS where BDCODPLATROCA = new.bdcodplatroca and bdchave = new.bdchave and bdcodnat = new.bdcodnat into :wCFOP;
      if (:wCFOP = 0) then
        UPDATE OR INSERT INTO VEF_BASE_TPLANOACOESTROCACFOPS (BDCODPLATROCA, BDCHAVE, BDCODNAT)
                                                    VALUES (new.bdcodplatroca, new.bdchave, new.bdcodnat)
                                                  MATCHING (BDCODPLATROCA, BDCHAVE, BDCODNAT);
    end
end^

CREATE OR ALTER trigger VEF_BASE_TPLANOACOESTROCA_BI0 for VEF_BASE_TPLANOACOESTROCA
active before insert position 0
AS
  DECLARE VARIABLE wQtdeFil INTEGER;
  declare variable wCodigo INTEGER;
BEGIN
  IF (NEW.BDQTDFILTRO IS NULL) THEN
    BEGIN
       wQtdeFil = 0;
       IF (NEW.BDTIPOLAN IS NOT NULL) THEN     -- Movimento
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDMODELO IS NOT NULL) THEN      -- Modelo
         wQtdeFil = wQtdeFil+1;
       IF ((NEW.BDESPECIE IS NOT NULL) AND (NEW.BDESPECIE <> '')) THEN -- Espécie
         wQtdeFil = wQtdeFil+1;
       IF ((NEW.BDSERIE IS NOT NULL) AND (NEW.BDSERIE <> '')) THEN     -- Série
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODNAT IS NOT NULL) THEN      -- CFOP
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODTER IS NOT NULL) THEN      -- Participante
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDNCMPROD IS NOT NULL) THEN     -- NBM-NCM/SH
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODPROD IS NOT NULL) THEN     -- Produto
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDVLRIGUALA IS NOT NULL) THEN   -- Valor igual a
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDVLRMENORQUE IS NOT NULL) THEN -- Menor que
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDVLRMAIORQUE IS NOT NULL) THEN -- Maior que
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDALIQICMSFIL IS NOT NULL) THEN -- Alíquota ICMS
         wQtdeFil = wQtdeFil+1;
       /* Entrada */
       IF (NEW.BDCODCSTICMSENTFIL IS NOT NULL) THEN -- CST ICMS
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODCSTIPIENTFIL IS NOT NULL) THEN  -- CST IPI
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODCSTPISENTFIL IS NOT NULL) THEN  -- CST PIS
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODCSTCOFENTFIL IS NOT NULL) THEN  -- CST Cofins
         wQtdeFil = wQtdeFil+1;
       /* Saída */
       IF (NEW.BDCODCSTICMSSAIFIL IS NOT NULL) THEN -- CST ICMS
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODCSTIPISAIFIL IS NOT NULL) THEN  -- CST IPI
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODCSTPISSAIFIL IS NOT NULL) THEN  -- CST PIS
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODCSTCOFSAIFIL IS NOT NULL) THEN  -- CST Cofins
         wQtdeFil = wQtdeFil+1;
       IF ((NEW.BDCONSUFINALFIL IS NOT NULL) or  (new.BDCONSUFINALFIL > -1) ) THEN  -- consumidor final
         wQtdeFil = wQtdeFil+1;

       NEW.BDQTDFILTRO = wQtdeFil;
    END

    wCodigo = 0;
    IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0))  THEN
       BEGIN
         SELECT MAX(BDCHAVE)+1 FROM VEF_BASE_TPLANOACOESTROCA WHERE NEW.BDCODPLATROCA = BDCODPLATROCA INTO WCODIGO;
         NEW.BDCHAVE = WCODIGO;
       END
    ELSE
       BEGIN
         SELECT BDCHAVE FROM VEF_BASE_TPLANOACOESTROCA WHERE NEW.BDCODPLATROCA = BDCODPLATROCA AND BDCHAVE = NEW.BDCHAVE INTO WCODIGO;
         if (WCODIGO > 0) then
            BEGIN
              SELECT MAX(BDCHAVE)+1 FROM VEF_BASE_TPLANOACOESTROCA WHERE NEW.BDCODPLATROCA = BDCODPLATROCA INTO WCODIGO;
              NEW.BDCHAVE = WCODIGO;
            END
       END

  -- Alt: #206609  - Adicionado tratamentos para evitar a configucao "Plano pagamento" informado, em uma chave com a opcao de "Pagamento" diferente de 2-Prazo...
  IF ((NEW.BDCONDPGTOACAO <> 1) and (NEW.BDCODIGOPLAACAO > 0)) THEN
    EXCEPTION EX_PLANOTROCA_CONDPGTO;

END
^

CREATE OR ALTER TRIGGER VEF_BASE_TPLANOACOESTROCA_BU0 FOR VEF_BASE_TPLANOACOESTROCA
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN

  -- Alt: #206609  - Adicionado tratamentos para evitar a configucao "Plano pagamento" informado, em uma chave com a opcao de "Pagamento" diferente de 2-Prazo...
  IF ((NEW.BDCONDPGTOACAO <> 1) and (NEW.BDCODIGOPLAACAO > 0)) THEN
    EXCEPTION EX_PLANOTROCA_CONDPGTO;

END
^


CREATE OR ALTER trigger vef_base_tplanoacoesconf1900_bi for vef_base_tplanoacoesconf1900
active before insert position 0
AS
  DECLARE VARIABLE wQtdeFil INTEGER;
BEGIN
       wQtdeFil = 0;
    IF (NEW.BDQTDFILTRO IS NOT NULL) THEN
          wQtdefil = NEW.BDQTDFILTRO;
       IF (NEW.BDTIPOMOV IS NOT NULL) THEN     -- Movimento
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDMODELO IS NOT NULL) THEN      -- Modelo
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODCSTICMS IS NOT NULL) THEN      -- CST de ICMS
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODNAT IS NOT NULL) THEN      -- Código de Natureza
         wQtdeFil = wQtdeFil+1;
       IF ((NEW.BDCONSUFINAL IS NOT NULL) AND (NEW.BDCONSUFINAL <> -1) ) THEN     -- Consumidor Final
         wQtdeFil = wQtdeFil+1;

       NEW.BDQTDFILTRO = wQtdeFil;   
    
      IF (NEW.bdcodajuicmsst IS NOT NULL) THEN
        NEW.BDCODAJU = NULL;
END^

CREATE OR ALTER trigger vef_tplanoacoesconf1900_bu0 for vef_base_tplanoacoesconf1900
active before update position 0
AS
  DECLARE VARIABLE wQtdeFil INTEGER;
begin
      wQtdeFil = 0;
       IF (NEW.BDQTDFILTRO IS NOT NULL) THEN
          wQtdefil = NEW.BDQTDFILTRO;
       IF (NEW.BDTIPOMOV IS NOT NULL) THEN     -- Movimento
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDMODELO IS NOT NULL) THEN      -- Modelo
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODCSTICMS IS NOT NULL) THEN      -- CST de ICMS
         wQtdeFil = wQtdeFil+1;
       IF (NEW.BDCODNAT IS NOT NULL) THEN      -- Código de Natureza
         wQtdeFil = wQtdeFil+1;
       IF ((NEW.BDCONSUFINAL IS NOT NULL) AND (NEW.BDCONSUFINAL <> -1) ) THEN     -- Consumidor Final
         wQtdeFil = wQtdeFil+1;

       NEW.BDQTDFILTRO = wQtdeFil;   
      
    IF (NEW.BDCODAJUICMSST = 0) then
         NEW.BDCODAJUICMSST = NULL;
    
       IF (NEW.bdcodajuicmsst IS NOT NULL) THEN
         NEW.BDCODAJU = NULL;
end^

CREATE OR ALTER trigger vef_base_tvinccodplano1900_ai0 for vef_base_tvinccodplano1900
active after insert position 0
AS
begin
 DELETE FROM VEF_BASE_TVINCCODPLANO1900 WHERE BDCODNAT IS NULL AND BDCODCSTICMS IS NULL;
end^

CREATE OR ALTER TRIGGER VEF_BASE_TVINCCODPLANO1200_AI0 FOR VEF_BASE_TVINCCODPLANO1250
ACTIVE AFTER INSERT POSITION 0
AS
begin
  DELETE FROM VEF_BASE_TVINCCODPLANO1250 WHERE BDCODNAT IS NULL AND BDCODCSTICMS IS NULL;
end^

CREATE OR ALTER trigger vef_base_tvinccodplano1900_bi0 for vef_base_tvinccodplano1900
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
  IF ((NEW.BDORDEM IS NULL) or (NEW.BDORDEM = 0))  THEN
     BEGIN
       SELECT COALESCE(MAX(BDORDEM)+1,1) FROM VEF_BASE_TVINCCODPLANO1900 where BDCODPLANCONF1900 = NEW.BDCODPLANCONF1900
       INTO vCodigo;
       NEW.BDORDEM = :vCodigo;
     END

end^

CREATE OR ALTER TRIGGER VEF_BASE_TVINCCODPLANO1200_BI0 FOR VEF_BASE_TVINCCODPLANO1250
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
  IF ((NEW.BDORDEM IS NULL) or (NEW.BDORDEM = 0))  THEN
     BEGIN
       SELECT COALESCE(MAX(BDORDEM)+1,1) FROM VEF_BASE_TVINCCODPLANO1250 where BDCODPLANCONF1200 = NEW.BDCODPLANCONF1200
       INTO vCodigo;
       NEW.BDORDEM = :vCodigo;
     END
end^

CREATE OR ALTER procedure SP_ATUALIZAR_VICCODPLANO1900 (
    BDCHAVE integer,
    BDCODPLANCONF1900 integer,
    BDCODCSTICMS integer,
    BDCODNAT integer)
as
begin
  INSERT INTO VEF_BASE_TVINCCODPLANO1900(BDORDEM,BDCHAVE,BDCODPLANCONF1900,BDCODCSTICMS,BDCODNAT) VALUES(0,:bdchave,:bdcodplanconf1900, iif(:bdcodcsticms = 0, null,  :bdcodcsticms),iif(:bdcodnat = 0, null, :bdcodnat));
end^

CREATE OR ALTER PROCEDURE SP_VRHF_RELATORIOFF_VALOR (
    PREMP VARCHAR(20000),
    PRCOL VARCHAR(32700),
    PRAUT VARCHAR(12000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRBASES SMALLINT = 0,
    PRFN SMALLINT = 0,
    PRFC SMALLINT = 0,
    PRADS SMALLINT = 0,
    PRAD13 SMALLINT = 0,
    PR13 SMALLINT = 0,
    PRC13 SMALLINT = 0,
    PRFA SMALLINT = 0,
    PRCODFA INTEGER = 0,
    PRSERV SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODTER INTEGER,
    BDREF INTEGER,
    BDCODVER INTEGER,
    BDVALOR NUMERIC(18,4),
    BDTIPO VARCHAR(5),
    BDDATARESCISAO DATE,
    BDDESCVER VARCHAR(40),
    BDCLAVER VARCHAR(20))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WBFGTS NUMERIC(18,4);
DECLARE VARIABLE WFGTS NUMERIC(18,4);
DECLARE VARIABLE WBFGTS13 NUMERIC(18,4);
DECLARE VARIABLE WFGTS13 NUMERIC(18,4);
DECLARE VARIABLE WBINSS NUMERIC(18,4);
DECLARE VARIABLE WBINSS13 NUMERIC(18,4);
DECLARE VARIABLE WBIR NUMERIC(18,4);
DECLARE VARIABLE WBIR13 NUMERIC(18,4);
DECLARE VARIABLE WDEPFN NUMERIC(18,4);
BEGIN
  BDCODTER = NULL;

  IF (UPPER(COALESCE(prcol, '')) <> 'NENHUM') THEN
     BEGIN
       IF (COALESCE(prfn, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDCODVER, FOL.BDVALVFN, '||
                   'case when COALESCE(RESC.BDREFRESCISAO,0) = FOL.BDREFFN then ''C'' else ''M'' end BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from ('||
                   'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDCODVER, FOL.BDVALVFN '||
                   'from VRHF_EMP_TVERBAFN FOL '||
                   'where FOL.BDREFFN between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            wsql = wsql||' union all '||
                   'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDCODVER, SUM(FOL.BDVALVFT) BDVALVFT '||
                   'from VRHF_EMP_TVERBATOMADOR FOL '||
                   'where FOL.BDREFTOMADOR between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            wsql = wsql||' group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDCODVER) FOL '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) ';

     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;
     
            IF (COALESCE(prbases,0) = 1) THEN
               BEGIN
                 BDCODVER = 999999;
                 BDCLAVER = '99999999999999999999';
                 wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDBFGTSFN, FOL.BDFGTSFN, FOL.BDBFGTS13FN, FOL.BDFGTS13FN, '||
                          'FOL.BDBINSSAPFN, FOL.BDBIRRFFN, FOL.BDBINSS13APFN, FOL.BDBIRRF13FN, FOL.BDDEPFN, '||
                        'case when COALESCE(RESC.BDREFRESCISAO,0) = FOL.BDREFFN then ''C'' else ''M'' end BDTIPO, RESC.BDDATARESCISAO '||
                        'from ('||
                        'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDBFGTSFN + FOL.BDBFGTSFEFN BDBFGTSFN, FOL.BDFGTSFN + FOL.BDFGTSFEFN BDFGTSFN, FOL.BDBFGTS13FN, FOL.BDFGTS13FN, '||
                          'FOL.BDBINSSAPFN, FOL.BDBIRRFFN + FOL.BDBIRRFFEFN BDBIRRFFN, FOL.BDBINSS13APFN, FOL.BDBIRRF13FN, FOL.BDDEPFN '||
                        'from VRHF_EMP_TFOLHANORMAL FOL '||
                        'where FOL.BDREFFN between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 wsql = wsql||' union all '||
                        'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, SUM(FOL.BDBFGTSFT + FOL.BDBFGTSFEFT), SUM(FOL.BDFGTSFT + FOL.BDFGTSFEFT), SUM(FOL.BDBFGTS13FT), SUM(FOL.BDFGTS13FT), '||
                          'SUM(FOL.BDBINSSAPFT), SUM(FOL.BDBIRRFFT + FOL.BDBIRRFFEFT), SUM(FOL.BDBINSS13APFT), SUM(FOL.BDBIRRF13FT), SUM(FOL.BDDEPFT) '||
                        'from VRHF_EMP_TFOLHATOMADOR FOL '||
                        'where FOL.BDREFTOMADOR between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 wsql = wsql||' group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR) FOL '||
                        'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) ';
     
                 FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :wbfgts, :wfgts, :wbfgts13, :wfgts13, :wbinss, :wbir, :wbinss13, :wbir13, :wdepfn, :BDTIPO, :BDDATARESCISAO DO
                   BEGIN
                     BDDESCVER = 'Base de FGTS';
                     BDVALOR = wbfgts;
                     SUSPEND;
     
                     BDDESCVER = 'Valor de FGTS';
                     BDVALOR = wfgts;
                     SUSPEND;
     
                     BDDESCVER = 'Base de INSS';
                     BDVALOR = wbinss;
                     SUSPEND;
     
                     BDDESCVER = 'Base de IR';
                     BDVALOR = wbir;
                     SUSPEND;
     
                     BDDESCVER = 'Dependente de IR';
                     BDVALOR = wdepfn;
                     SUSPEND;

                     IF (BDTIPO = 'C') THEN
                        BEGIN
                          BDDESCVER = 'Base de FGTS 13º';
                          BDVALOR = wbfgts13;
                          SUSPEND;
          
                          BDDESCVER = 'Valor de FGTS 13º';
                          BDVALOR = wfgts13;
                          SUSPEND;
          
                          BDDESCVER = 'Base de INSS 13º';
                          BDVALOR = wbinss13;
                          SUSPEND;
                          BDDESCVER = 'Base de IR 13º';
                          BDVALOR = wbir13;
                          SUSPEND;
                       END
                   END
               END
          END
     
       IF (COALESCE(prfc, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFCOMP, FOL.BDCODVER, FOL.BDVALVFC, '||
                   'case when COALESCE(RESC.BDREFRESCISAO,0) = FOL.BDREFFN then ''C'' else ''F'' end BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from ('||
                   'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FC.BDREFCOMP, FOL.BDCODVER, FOL.BDVALVFC '||
                   'from VRHF_EMP_TVERBAFC FOL '||
                   'join VRHF_EMP_TFOLHACOMP FC on (FC.BDCODEMP = FOL.BDCODEMP and FC.BDCODCOL = FOL.BDCODCOL and FC.BDREFFN = FOL.BDREFFN and FC.BDREFFC = FOL.BDREFFC) '||
                   'where FC.BDREFCOMP between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            wsql = wsql||' union all '||
                   'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FC.BDREFCOMP, FOL.BDCODVER, SUM(FOL.BDVALVFC) BDVALVFC '||
                   'from VRHF_EMP_TVERBAFCTOMADOR FOL '||
                   'join VRHF_EMP_TFOLTOMCOMP FC on (FC.BDCODEMP = FOL.BDCODEMP and FC.BDCODCOL = FOL.BDCODCOL and FC.BDREFTOMADOR = FOL.BDREFTOMADOR and FC.BDREFFC = FOL.BDREFFC and FC.bdordem = FOL.BDORDEM) '||
                   'where FC.BDREFCOMP between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            wsql = wsql||' group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FC.BDREFCOMP, FOL.BDCODVER) FOL '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) ';
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;

            IF (COALESCE(prbases,0) = 1) THEN
               BEGIN
                 BDCODVER = 999999;
                 BDCLAVER = '99999999999999999999';
                 wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFCOMP, FOL.BDBFGTSFC, FOL.BDFGTSFC, FOL.BDBFGTS13FC, FOL.BDFGTS13FC, '||
                          'FOL.BDBINSSAPFC, FOL.BDBIRRFFC, FOL.BDBINSS13APFC, FOL.BDBIRRF13FC, FOL.BDDEPFC, '||
                        'case when COALESCE(RESC.BDREFRESCISAO,0) = FOL.BDREFFN then ''C'' else ''F'' end BDTIPO, RESC.BDDATARESCISAO '||
                        'from ('||
                        'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDREFCOMP, FOL.BDBFGTSFC + FOL.BDBFGTSFEFC BDBFGTSFC, FOL.BDFGTSFC + FOL.BDFGTSFEFC BDFGTSFC, FOL.BDBFGTS13FC, FOL.BDFGTS13FC, '||
                          'FOL.BDBINSSAPFC, FOL.BDBIRRFFC + FOL.BDBIRRFFEFC BDBIRRFFC, FOL.BDBINSS13APFC, FOL.BDBIRRF13FC, FOL.BDDEPFC '||
                        'from VRHF_EMP_TFOLHACOMP FOL '||
                        'where FOL.BDREFCOMP between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 wsql = wsql||' union all '||
                        'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDREFCOMP, SUM(FOL.BDBFGTSFC + FOL.BDBFGTSFEFC), SUM(FOL.BDFGTSFC + FOL.BDFGTSFEFC), SUM(FOL.BDBFGTS13FC), SUM(FOL.BDFGTS13FC), '||
                          'SUM(FOL.BDBINSSAPFC), SUM(FOL.BDBIRRFFC + FOL.BDBIRRFFEFC), SUM(FOL.BDBINSS13APFC), SUM(FOL.BDBIRRF13FC), SUM(FOL.BDDEPFC) '||
                        'from VRHF_EMP_TFOLTOMCOMP FOL '||
                        'where FOL.BDREFCOMP between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 wsql = wsql||' group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDREFCOMP) FOL '||
                        'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) ';
     
                 FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :wbfgts, :wfgts, :wbfgts13, :wfgts13, :wbinss, :wbir, :wbinss13, :wbir13, :wdepfn, :BDTIPO, :BDDATARESCISAO DO
                   BEGIN
                     BDDESCVER = 'Base de FGTS';
                     BDVALOR = wbfgts;
                     SUSPEND;
     
                     BDDESCVER = 'Valor de FGTS';
                     BDVALOR = wfgts;
                     SUSPEND;
     
                     BDDESCVER = 'Base de INSS';
                     BDVALOR = wbinss;
                     SUSPEND;
     
                     BDDESCVER = 'Base de IR';
                     BDVALOR = wbir;
                     SUSPEND;
     
                     BDDESCVER = 'Dependente de IR';
                     BDVALOR = wdepfn;
                     SUSPEND;

                     IF (BDTIPO = 'C') THEN
                        BEGIN
                          BDDESCVER = 'Base de FGTS 13º';
                          BDVALOR = wbfgts13;
                          SUSPEND;
          
                          BDDESCVER = 'Valor de FGTS 13º';
                          BDVALOR = wfgts13;
                          SUSPEND;
          
                          BDDESCVER = 'Base de INSS 13º';
                          BDVALOR = wbinss13;
                          SUSPEND;
          
                          BDDESCVER = 'Base de IR 13º';
                          BDVALOR = wbir13;
                          SUSPEND;
                       END
                   END
               END
          END
     
       IF (COALESCE(prads, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, AD.BDREFAD, FOL.BDCODVER, FOL.BDVALVAD, '||
                   '''A'' BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from VRHF_EMP_TVERBAAD FOL '||
                   'join VRHF_EMP_TADSAL AD on (AD.BDCODEMP = FOL.BDCODEMP and AD.BDCODCOL = FOL.BDCODCOL and AD.BDDATAAD = FOL.BDDATAAD) '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                   'where AD.BDREFAD between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;

            IF (COALESCE(prbases,0) = 1) THEN
               BEGIN
                 BDCODVER = 999999;
                 BDCLAVER = '99999999999999999999';
                 wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFAD, FOL.BDBASEIRAD, FOL.BDDEPIRAD, '||
                        '''A'' BDTIPO, RESC.BDDATARESCISAO '||
                        'from VRHF_EMP_TADSAL FOL '||
                        'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                        'where FOL.BDREFAD between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :wbir, :wdepfn, :BDTIPO, :BDDATARESCISAO DO
                   BEGIN
                     BDDESCVER = 'Base de IR';
                     BDVALOR = wbir;
                     SUSPEND;

                     BDDESCVER = 'Dependente de IR';
                     BDVALOR = wdepfn;
                     SUSPEND;
                   END
               END

          END
     
       IF (COALESCE(prad13, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFA13, FOL.BDCODVER, FOL.BDVALVA13, '||
                   '''1'' BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from VRHF_EMP_TVERBAA13 FOL '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                   'where FOL.BDREFA13 between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;
     
            IF (COALESCE(prbases,0) = 1) THEN
               BEGIN
                 BDCODVER = 999999;
                 BDCLAVER = '99999999999999999999';
                 wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFA13, FOL.BDBASEFGTSA13, FOL.BDFGTSA13, '||
                        '''1'' BDTIPO, RESC.BDDATARESCISAO '||
                        'from VRHF_EMP_TA13SAL FOL '||
                        'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                        'where FOL.BDREFA13 between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :wbfgts13, :wfgts13, :BDTIPO, :BDDATARESCISAO DO
                   BEGIN
                     BDDESCVER = 'Base de FGTS 13º';
                     BDVALOR = :wbfgts13;
                     SUSPEND;

                     BDDESCVER = 'Valor de FGTS 13º';
                     BDVALOR = :wfgts13;
                     SUSPEND;
                   END
               END

          END
     
       IF (COALESCE(pr13, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13, FOL.BDCODVER, FOL.BDVALV13, '||
                   '''2'' BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from VRHF_EMP_TVERBA13 FOL '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                   'where FOL.BDREF13 between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;

            IF (COALESCE(prbases,0) = 1) THEN
               BEGIN
                 BDCODVER = 999999;
                 BDCLAVER = '99999999999999999999';
                 wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13, FOL.BDBASEIR13, FOL.BDBASEFGTS13, FOL.BDFGTS13, FOL.BDBASEINSS13, FOL.BDDEP13, '||
                        '''2'' BDTIPO, RESC.BDDATARESCISAO '||
                        'from VRHF_EMP_T13SAL FOL '||
                        'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                        'where FOL.BDREF13 between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :wbir13, :wbfgts13, :wfgts13, :wbinss13, :wdepfn, :BDTIPO, :BDDATARESCISAO DO
                   BEGIN
                     BDDESCVER = 'Base de IR 13º';
                     BDVALOR = :wbir13;
                     SUSPEND;

                     BDDESCVER = 'Base de FGTS 13º';
                     BDVALOR = :wbfgts13;
                     SUSPEND;

                     BDDESCVER = 'Valor de FGTS 13º';
                     BDVALOR = :wfgts13;
                     SUSPEND;

                     BDDESCVER = 'Base de INSS 13º';
                     BDVALOR = :wbinss13;
                     SUSPEND;

                     BDDESCVER = 'Dependente de IR 13º';
                     BDVALOR = :wdepfn;
                     SUSPEND;
                   END

               END

          END
     
       IF (COALESCE(prc13, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFC13, FOL.BDCODVER, FOL.BDVALVC13, '||
                   '''3'' BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from VRHF_EMP_TVERBAC13 FOL '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                   'where FOL.BDREFC13 between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;

            IF (COALESCE(prbases,0) = 1) THEN
               BEGIN
                 BDCODVER = 999999;
                 BDCLAVER = '99999999999999999999';
                 wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13, FOL.BDBASEIRC13, FOL.BDBASEFGTSC13, FOL.BDFGTSC13, FOL.BDBASEINSSC13, FOL.BDDEPC13, '||
                        '''2'' BDTIPO, RESC.BDDATARESCISAO '||
                        'from VRHF_EMP_TC13SAL FOL '||
                        'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                        'where FOL.BDREFC13 between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :wbir13, :wbfgts13, :wfgts13, :wbinss13, :wdepfn, :BDTIPO, :BDDATARESCISAO DO
                   BEGIN
                     BDDESCVER = 'Base de IR 13º';
                     BDVALOR = :wbir13;
                     SUSPEND;

                     BDDESCVER = 'Base de FGTS 13º';
                     BDVALOR = :wbfgts13;
                     SUSPEND;

                     BDDESCVER = 'Valor de FGTS 13º';
                     BDVALOR = :wfgts13;
                     SUSPEND;

                     BDDESCVER = 'Base de INSS 13º';
                     BDVALOR = :wbinss13;
                     SUSPEND;

                     BDDESCVER = 'Dependente de IR 13º';
                     BDVALOR = :wdepfn;
                     SUSPEND;
                   END
               END
          END
     
       IF (COALESCE(prfa, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FA.BDREF, FOL.BDCODVER, FOL.BDVALVFA, '||
                   '''P'' BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from VRHF_EMP_TVERBAFA FOL '||
                   'join VRHF_EMP_TFOLHAAVULSA FA on (FA.BDCODEMP = FOL.BDCODEMP and FA.BDCODCOL = FOL.BDCODCOL and FA.BDDATAFA = FOL.BDDATAFA and FA.BDCODTCA = FOL.BDCODTCA) '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                   'where FA.BDREF between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            IF (COALESCE(prcodfa, 0) > 0) THEN
               wsql = wsql||' and FOL.BDCODTCA = '||prcodfa;
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;

            IF (COALESCE(prbases,0) = 1) THEN
               BEGIN
                 BDCODVER = 999999;
                 BDCLAVER = '99999999999999999999';
                 wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF, FOL.BDBFGTSFA, FOL.BDFGTSFA, FOL.BDBINSSFA, FOL.BDBIRRFFA, FOL.BDDEPFA, '||
                        '''P'' BDTIPO, RESC.BDDATARESCISAO '||
                        'from VRHF_EMP_TFOLHAAVULSA FOL '||
                        'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                        'where FOL.BDREF between '||prrefini||' and '||prreffim;
               
                 IF (premp IS NOT NULL AND premp <> '') THEN
                    BEGIN
                      wsql = wsql||' and '||premp;
          
                      IF (prcol IS NOT NULL AND prcol <> '') THEN
                         wsql = wsql||' and '||prcol;
                    END
          
                 IF (COALESCE(prcodfa, 0) > 0) THEN
                    wsql = wsql||' and FOL.BDCODTCA = '||prcodfa;
          
                 FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :wbfgts, :wfgts, :wbinss, :wbir, :wdepfn, :BDTIPO, :BDDATARESCISAO DO
                   BEGIN
                     BDDESCVER = 'Base de FGTS';
                     BDVALOR = :wbfgts;
                     SUSPEND;

                     BDDESCVER = 'Valor de FGTS';
                     BDVALOR = :wfgts;
                     SUSPEND;

                     BDDESCVER = 'Base de INSS';
                     BDVALOR = :wbinss;
                     SUSPEND;

                     BDDESCVER = 'Base de IR';
                     BDVALOR = :wbir;
                     SUSPEND;

                     BDDESCVER = 'Dependente de IR';
                     BDVALOR = :wdepfn;
                     SUSPEND;
                   END
               END
          END
     END

  IF (COALESCE(prserv, 0) = 1 AND UPPER(COALESCE(praut, '')) <> 'NENHUM') THEN
     BEGIN
       BDCODCOL = NULL;
       wsql = 'select FOL.BDCODEMP, FOL.BDCODTER, SERV.BDREFINSSSERV, FOL.BDCODVER, FOL.BDVALOR, '||
              '''S'' BDTIPO, cast(null as date) BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
              'from VRHF_BASE_ITEMS_CALCTERC FOL '||
              'join VRHF_BASE_CALC_TERC SERV on (SERV.BDCODEMP = FOL.BDCODEMP and SERV.BDCODTER = FOL.BDCODTER and SERV.BDCODSERV = FOL.BDCODSERV) '||
              'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
              'where SERV.BDREFINSSSERV between '||prrefini||' and '||prreffim;
     
       IF (premp IS NOT NULL AND premp <> '') THEN
          BEGIN
            wsql = wsql||' and '||premp;

            IF (praut IS NOT NULL AND praut <> '') THEN
               wsql = wsql||' and '||praut;
          END

       FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODTER, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
         SUSPEND;

       IF (COALESCE(prbases,0) = 1) THEN
          BEGIN
            BDCODVER = 999999;
            BDCLAVER = '99999999999999999999';
            wsql = 'select FOL.BDCODEMP, FOL.BDCODTER, FOL.BDREFINSSSERV, FOL.BDBASEIR, FOL.BDBASEINSS, FOL.BDVALOUTENTIDADES, FOL.BDVALORDEP, '||
                   '''S'' BDTIPO, cast(null as date) BDDATARESCISAO '||
                   'from VRHF_BASE_CALC_TERC FOL '||
                   'where FOL.BDREFINSSSERV between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (praut IS NOT NULL AND praut <> '') THEN
                    wsql = wsql||' and '||praut;
               END
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODTER, :BDREF, :wbir, :wbinss, :wbfgts13, :wdepfn, :BDTIPO, :BDDATARESCISAO DO
              BEGIN
                BDDESCVER = 'Base de IR';
                BDVALOR = wbir;
                SUSPEND;

                BDDESCVER = 'Base de INSS';
                BDVALOR = wbinss;
                SUSPEND;

                BDDESCVER = 'Valor outras entidades';
                BDVALOR = wbfgts13;
                SUSPEND;

                BDDESCVER = 'Depdendente de IR';
                BDVALOR = wdepfn;
                SUSPEND;
              END
          END
     END
END^


CREATE OR ALTER PROCEDURE SP_VRHF_RELATORIOFF_REF (
    PREMP VARCHAR(20000),
    PRCOL VARCHAR(32700),
    PRAUT VARCHAR(12000),
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRFN SMALLINT = 0,
    PRFC SMALLINT = 0,
    PRADS SMALLINT = 0,
    PRAD13 SMALLINT = 0,
    PR13 SMALLINT = 0,
    PRC13 SMALLINT = 0,
    PRFA SMALLINT = 0,
    PRCODFA INTEGER = 0,
    PRSERV SMALLINT = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDCODTER INTEGER,
    BDREF INTEGER,
    BDCODVER INTEGER,
    BDVALOR NUMERIC(18,4),
    BDTIPO VARCHAR(5),
    BDDATARESCISAO DATE,
    BDDESCVER VARCHAR(40),
    BDCLAVER VARCHAR(20))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  BDCODTER = NULL;

  IF (UPPER(COALESCE(prcol, '')) <> 'NENHUM') THEN
     BEGIN
       IF (COALESCE(prfn, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDCODVER, FOL.BDREFVFN, '||
                   'case when COALESCE(RESC.BDREFRESCISAO,0) = FOL.BDREFFN then ''C'' else ''M'' end BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from ('||
                   'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FOL.BDCODVER, FOL.BDREFVFN '||
                   'from VRHF_EMP_TVERBAFN FOL '||
                   'where FOL.BDREFFN between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            wsql = wsql||' union all '||
                   'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDCODVER, SUM(FOL.BDREFVFT) BDREFVFT '||
                   'from VRHF_EMP_TVERBATOMADOR FOL '||
                   'where FOL.BDREFTOMADOR between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            wsql = wsql||' group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FOL.BDCODVER) FOL '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) ';

     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;
          END
     
       IF (COALESCE(prfc, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFCOMP, FOL.BDCODVER, FOL.BDREFVFC, '||
                   'case when COALESCE(RESC.BDREFRESCISAO,0) = FOL.BDREFFN then ''C'' else ''F'' end BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from ('||
                   'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFFN, FC.BDREFCOMP, FOL.BDCODVER, FOL.BDREFVFC '||
                   'from VRHF_EMP_TVERBAFC FOL '||
                   'join VRHF_EMP_TFOLHACOMP FC on (FC.BDCODEMP = FOL.BDCODEMP and FC.BDCODCOL = FOL.BDCODCOL and FC.BDREFFN = FOL.BDREFFN and FC.BDREFFC = FOL.BDREFFC) '||
                   'where FC.BDREFCOMP between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            wsql = wsql||' union all '||
                   'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FC.BDREFCOMP, FOL.BDCODVER, SUM(FOL.BDREFVFC) BDREFVFC '||
                   'from VRHF_EMP_TVERBAFCTOMADOR FOL '||
                   'join VRHF_EMP_TFOLTOMCOMP FC on (FC.BDCODEMP = FOL.BDCODEMP and FC.BDCODCOL = FOL.BDCODCOL and FC.BDREFTOMADOR = FOL.BDREFTOMADOR and FC.BDREFFC = FOL.BDREFFC and FC.bdordem = FOL.BDORDEM) '||
                   'where FC.BDREFCOMP between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            wsql = wsql||' group by FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFTOMADOR, FC.BDREFCOMP, FOL.BDCODVER) FOL '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) ';
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;
          END
     
       IF (COALESCE(prads, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, AD.BDREFAD, FOL.BDCODVER, FOL.BDREFVAD, '||
                   '''A'' BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from VRHF_EMP_TVERBAAD FOL '||
                   'join VRHF_EMP_TADSAL AD on (AD.BDCODEMP = FOL.BDCODEMP and AD.BDCODCOL = FOL.BDCODCOL and AD.BDDATAAD = FOL.BDDATAAD) '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                   'where AD.BDREFAD between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;
          END
     
       IF (COALESCE(prad13, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFA13, FOL.BDCODVER, FOL.BDREFVA13, '||
                   '''1'' BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from VRHF_EMP_TVERBAA13 FOL '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                   'where FOL.BDREFA13 between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;
          END
     
       IF (COALESCE(pr13, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREF13, FOL.BDCODVER, FOL.BDREFV13, '||
                   '''2'' BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from VRHF_EMP_TVERBA13 FOL '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                   'where FOL.BDREF13 between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;
          END
     
       IF (COALESCE(prc13, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FOL.BDREFC13, FOL.BDCODVER, FOL.BDREFVC13, '||
                   '''3'' BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from VRHF_EMP_TVERBAC13 FOL '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                   'where FOL.BDREFC13 between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;
          END
     
       IF (COALESCE(prfa, 0) = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCODCOL, FA.BDREF, FOL.BDCODVER, FOL.BDREFVFA, '||
                   '''P'' BDTIPO, RESC.BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
                   'from VRHF_EMP_TVERBAFA FOL '||
                   'join VRHF_EMP_TFOLHAAVULSA FA on (FA.BDCODEMP = FOL.BDCODEMP and FA.BDCODCOL = FOL.BDCODCOL and FA.BDDATAFA = FOL.BDDATAFA and FA.BDCODTCA = FOL.BDCODTCA) '||
                   'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
                   'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL) '||
                   'where FA.BDREF between '||prrefini||' and '||prreffim;
          
            IF (premp IS NOT NULL AND premp <> '') THEN
               BEGIN
                 wsql = wsql||' and '||premp;
     
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                    wsql = wsql||' and '||prcol;
               END
     
            IF (COALESCE(prcodfa, 0) > 0) THEN
               wsql = wsql||' and FOL.BDCODTCA = '||prcodfa;
     
            FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODCOL, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
              SUSPEND;
         END
     END

  IF (COALESCE(prserv, 0) = 1 AND UPPER(COALESCE(praut, '')) <> 'NENHUM') THEN
     BEGIN
       BDCODCOL = NULL;
       wsql = 'select FOL.BDCODEMP, FOL.BDCODTER, SERV.BDREFINSSSERV, FOL.BDCODVER, FOL.BDREFERENCIA, '||
              '''S'' BDTIPO, cast(null as date) BDDATARESCISAO, VERBAS.BDDESCVER, VERBAS.BDCLAVER '||
              'from VRHF_BASE_ITEMS_CALCTERC FOL '||
              'join VRHF_BASE_CALC_TERC SERV on (SERV.BDCODEMP = FOL.BDCODEMP and SERV.BDCODTER = FOL.BDCODTER and SERV.BDCODSERV = FOL.BDCODSERV) '||
              'join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOL.BDCODVER) '||
              'where SERV.BDREFINSSSERV between '||prrefini||' and '||prreffim;
     
       IF (premp IS NOT NULL AND premp <> '') THEN
          BEGIN
            wsql = wsql||' and '||premp;

            IF (praut IS NOT NULL AND praut <> '') THEN
               wsql = wsql||' and '||praut;
          END

       FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :BDCODTER, :BDREF, :BDCODVER, :BDVALOR, :BDTIPO, :BDDATARESCISAO, :BDDESCVER, :BDCLAVER DO
         SUSPEND;
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TCONFBLOCOM_BI0 FOR VEF_BASE_TCONFBLOCOM
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCODCONF IS NULL) OR (NEW.BDCODCONF = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(BDCODCONF)+1),1) FROM VEF_BASE_TCONFBLOCOM INTO vcodigo;
        NEW.BDCODCONF = vcodigo;
     END
  ELSE
    BEGIN
       SELECT BDCODCONF FROM VEF_BASE_TCONFBLOCOM WHERE BDCODCONF = NEW.BDCODCONF INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(BDCODCONF)+1),1) FROM VEF_BASE_TCONFBLOCOM INTO vcodigo;
            NEW.BDCODCONF = vcodigo;
         END
    END
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVENTOCOGIASP_AD0 FOR TOL_VEF_EMP_TMOVENTOCO_GIASP
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  /* Trigger text */
  DELETE FROM VEF_EMP_TMOVOCO_GIASP oco WHERE oco.BDCODEMP = OLD.BDCODEMP AND oco.BDCODTIPOOCOGIA = OLD.BDCODTIPOOCOGIA AND oco.BDCHAVEOCOGIASP = OLD.BDCHAVEOCOGIASP
     AND NOT EXISTS(SELECT * FROM TOL_VEF_EMP_TC197IVASP iva WHERE iva.bdCODEMP = oco.bdCODEMP AND iva.bdCODTIPOOCOGIA = oco.bdCODTIPOOCOGIA AND iva.bdCHAVEOCOGIASP = oco.bdCHAVEOCOGIASP); -- Alt.: 232467 - Apenas quando o C195 nao estiver ligado a outro IVA...
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TDIMEQ12_E116_AD0 FOR TOL_VEF_EMP_TDIMEQ12_E116
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  /* TRIGGER TEXT */
  DELETE FROM VEF_EMP_TAJUICMSE116 E116 WHERE E116.BDCODEMP = OLD.BDCODEMP AND E116.BDORDEME116250 = OLD.BDORDEME116250;
END
^

CREATE OR ALTER TRIGGER TOL_VEF_TDIMEGERDEBESP_E116_AD0 FOR TOL_VEF_EMP_TDIMEGERDEBESP_E116
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  /* TRIGGER TEXT */
  DELETE FROM VEF_EMP_TAJUICMSE116 E116 WHERE E116.BDCODEMP = OLD.BDCODEMP AND E116.BDORDEME116250 = OLD.BDORDEME116250;
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TDARF_E116_AD0 FOR TOL_VEF_EMP_TDARF_E116
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  /* TRIGGER TEXT */
  DELETE FROM VEF_EMP_TAJUICMSE116 E116 WHERE E116.BDCODEMP = OLD.BDCODEMP AND E116.BDORDEME116250 = OLD.BDORDEME116250;
END
^

--Sol. 18507 - Criação da trigger para inserir as verbas salariais por empresa ao cadastrar uma empresa nova - Bruno L. R. - 17/07/2017
CREATE OR ALTER TRIGGER tr_af_insert_tempresas FOR tempresas
ACTIVE AFTER INSERT POSITION 0
AS
  DECLARE VARIABLE vCodemp INTEGER;
BEGIN
  /* Trigger text */
  vcodemp = NULL;
  SELECT FIRST 1 BDCODEMP FROM VRHF_BASE_TVERBASEMP WHERE BDCODEMP = NEW.bdcodemp INTO :vcodemp;

  IF (vcodemp IS NULL) THEN
     BEGIN
       EXECUTE PROCEDURE SP_VRH_VERIFICAVERBASEMP_PADRAO(NEW.bdcodemp);
     END
END
^

CREATE OR ALTER trigger tr_af_insert_tdarfpadrao for tdarfpadrao
active after insert or update position 0
AS
  declare variable vCodEsc integer;
  declare variable vCodPlanConc integer;
  declare variable vCodItemConc integer;
  declare variable vCodFor integer;
  declare variable vCodDesp integer;
  declare variable vChaveCtaPag integer;
  declare variable vCodPlanEsc integer;
  declare variable vObsDesp blob;
  declare variable vDescImp varchar(100);
  declare variable vClassImp varchar(40);
  declare variable vEsfImp integer;
  declare variable vPerapu integer;
  declare variable vDocArc integer;
  declare variable vDescRec varchar(150);
  declare variable vStrRef varchar(7);
  declare variable vStrDtVenc varchar(10);
  declare variable vChCtaPagAux integer;
  declare variable vChaveCtaBan integer;
  declare variable vMes smallint;
  declare variable vAno integer;
  declare variable vDia integer;
  declare variable vDataEmi date;
begin
  -- #193309 | Antony R. (30/01/2024) - Processos conciliados financeiro
  select first 1 esc.bdcodesc, esc.bdcodplaconc from tescritorio esc where esc.bdcodempinteg = new.bdcodemp into :vcodesc, vcodplanesc;

  if (vcodesc > 0) then
  begin
    select first 1 x.bdclassimp from timposto x where x.bdcodimp = new.bdcodimp into :vclassimp;

    -- Item plano
    select first 1 conc.bdcodplaconc, conc.bdcoditemconc, conc.bdcodfor, conc.bdcoddesp, coalesce(conc.bdobsitemconc,'')
    from VFIN_BASE_TITENSPLANOCONCI conc
    inner join timposto imp on (imp.bdcodimp = conc.bdcodimp)
    where conc.bdcodplaconc = :vcodplanesc and conc.bdtipoprocconc = 1 and (:vclassimp starting with imp.bdclassimp)
    order by imp.bdclassimp desc
    into :vcodplanconc, vcoditemconc, vcodfor, vcoddesp, vobsdesp;

    if ((vcoditemconc > 0) and (vcodplanconc > 0)) then
    begin

      if (UPDATING) then
      begin
        -- Excluir contas a pagar vinculada ao imposto
        select coalesce(tol.bdchavectapag,0) from TOL_VFIN_DESP_DARF tol where tol.bdcodemp = new.bdcodemp and tol.bdchavedarf = new.bdchavedarf into :vChCtaPagAux;

        if (:vChCtaPagAux > 0) then
        begin
          delete from VFIN_ESC_TCONTASPAGARDESP desp where desp.bdcodesc = :vcodesc and desp.bdchavectapag = :vChCtaPagAux;
        end
      end

      -- Chave contas a pagar
      :vChaveCtaPag = 0;
      select first 1 coalesce(cta.bdchavectapag,0) + 1 from VFIN_ESC_TCONTASAPAGAR cta where cta.bdcodesc = :vcodesc order by bdcodesc, bdchavectapag desc into :vChaveCtaPag;

      if (vchavectapag <= 0) then
      begin
        :vchavectapag = 1;
      end

      -- Conta bancária padrão do escritório
      select first 1 x.bdchavectaban from VFIN_BASE_TESCPARFAT x where x.bdcodesc = :vcodesc into :vChaveCtaBan;

      :vDia = 1;
      :vMes = CAST(SUBSTRING(CAST(new.bdreferencia AS VARCHAR(6)) FROM 5 FOR 2) AS SMALLINT);
      :vAno = CAST(SUBSTRING(CAST(new.bdreferencia AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);


      :vDataEmi = vMes||'-'||vDia||'-'||vAno;

      -- Lançamento contas a pagar
      insert into VFIN_ESC_TCONTASAPAGAR (bdcodesc, bdchavectapag, bdcodfor ,bddataemissao, bddatavenc, bdreferencia, bdreffinparc, bdchavectaban)
      values (:vcodesc, :vchavectapag, :vcodfor, :vDataEmi, new.bddatavcto, new.bdreferencia, new.bdreferencia,:vChaveCtaBan);

      -- Depesa - Imposto
      insert into VFIN_ESC_TCONTASPAGARDESP (BDCODESC, BDCHAVECTAPAG, BDORDEMDESP, BDCODDESP, BDVALORDESP, BDTOTPENDDESP, BDCODCAT)
      values (:vcodesc, :vchavectapag, null, :vcoddesp, new.bdtotal, new.bdtotal, null);

      -- Observação
      select first 1 bddescimp, bdcompetencia, bdperapuracao, bddocarrecadacao from timposto  where bdcodimp = new.bdcodimp into :vdescimp, vesfimp, vperapu, vdocarc;
      select first 1 bddescrec from TCODREC x where bdcodrec = new.bdcodrec into :vdescrec;

      select bddata from SP_PARSE_DATE(new.bddatavcto,'DDMMYYYY') into :vStrDtVenc;
      :vStrDtVenc = SUBSTRING(:vStrDtVenc from 1 for 2) || '/' || SUBSTRING(:vStrDtVenc from 3 for 2) || '/' || SUBSTRING(:vStrDtVenc from 5 for 4);
      :vStrRef = SUBSTRING(new.bdreferencia from 5 for 2) || '/' || SUBSTRING(new.bdreferencia from 1 for 4);

      :vobsdesp = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(:vobsdesp, '*CODIMP', COALESCE(new.BDCODIMP, ' ')), '*DESIMP', COALESCE(:vdescimp, ' ')), '*REFIMP', COALESCE(:vStrRef, ' ')), '*VCTIMP', COALESCE(:vStrDtVenc, ' ')), '*ALQIMP', COALESCE(new.bdaliqimp, ' '));
      :vobsdesp = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(:vobsdesp, '*QTIMP', COALESCE(new.bdquota, ' ')), '*ESFIMP', COALESCE(:vesfimp, ' ')), '*PERAPU', COALESCE(:vperapu, ' ')), '*CODREC', COALESCE(new.bdcodrec, ' ')), '*DESREC', COALESCE(:vdescrec, ' '));
      :vobsdesp = REPLACE(REPLACE(:vobsdesp, '*DOCARC', COALESCE(:vdocarc, ' ')), '*OBSIMP', COALESCE(new.bdobs, ' '));

      if ((new.bdmulta > 0) or (new.bdjuros > 0)) then
      begin
        :vobsdesp = :vobsdesp || ' (valor imposto: ' || REPLACE(new.bdvalor, '.', ',');

        if (new.bdmulta > 0) then
        begin
          :vobsdesp = :vobsdesp || ' - valor multa: ' || REPLACE(new.bdmulta, '.', ',');
        end

        if (new.bdjuros > 0) then
        begin
          :vobsdesp = :vobsdesp || ' - valor juros: ' || REPLACE(new.bdjuros, '.', ',');
        end

        :vobsdesp = :vobsdesp || ')';
      end

      insert into VFIN_ESC_TCONTASPAGARDESPOBS (bdcodesc, bdchavectapag, bdordemdesp, bdobsdesp)
      values (:vcodesc, :vchavectapag, 1, :vobsdesp);

      -- Vínculo entre a DARF e Lançamento de Contas a Pagar
      insert into TOL_VFIN_DESP_DARF (bdcodesc, bdchavectapag, bdordemdesp, bdcodemp, bdchavedarf)
      select desp.bdcodesc, desp.bdchavectapag, desp.bdordemdesp, new.bdcodemp, new.bdchavedarf
      from VFIN_ESC_TCONTASPAGARDESP desp
      where desp.bdcodesc = :vcodesc and desp.bdchavectapag = :vchavectapag;

    end
  end

END
^

CREATE OR ALTER TRIGGER TOL_VFIN_DESP_DARF_AD0 FOR TOL_VFIN_DESP_DARF
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  delete from VFIN_ESC_TCONTASPAGARDESP desp where desp.bdcodesc = old.bdcodesc and desp.bdchavectapag = old.bdchavectapag;
END
^

--Sol. 19704 - Bruno L. R. - 04/08/2017
CREATE OR ALTER TRIGGER VRH_EMP_TCOL_EXAME_TOX_BI0 FOR VRH_EMP_TCOL_EXAME_TOX
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF ((NEW.bdcodigo IS NULL) OR (NEW.bdcodigo = 0)) THEN
     SELECT COALESCE(MAX(bdcodigo),0)+1 FROM VRH_EMP_TCOL_EXAME_TOX WHERE bdcodemp = NEW.bdcodemp AND bdcodcol = NEW.bdcodcol INTO NEW.bdcodigo;

  if (COALESCE(new.bdcodtipo, 0) = 0) then
     new.bdcodtipo = 1;

  if (NEW.bdgeraevento2221 = NULL) then
     SELECT EMP.bdgerareventotoxicologico FROM tempresas EMP WHERE EMP.bdcodemp = NEW.BDCODEMP INTO NEW.bdgeraevento2221;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_EXAME_TOX_AI0 FOR VRH_EMP_TCOL_EXAME_TOX
ACTIVE AFTER INSERT POSITION 0
AS
begin
  IF (NEW.BDDTEXAME >= '08-01-2024') THEN
     UPDATE TEMPRESAS EMP SET EMP.BDGERAREVENTOTOXICOLOGICO = NEW.BDGERAEVENTO2221 WHERE EMP.BDCODEMP = NEW.BDCODEMP AND EMP.BDGERAREVENTOTOXICOLOGICO <> NEW.BDGERAEVENTO2221;
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_EXAME_TOX_AU0 FOR VRH_EMP_TCOL_EXAME_TOX
ACTIVE AFTER UPDATE POSITION 0
AS
begin
  IF (NEW.BDDTEXAME >= '08-01-2024') THEN
     UPDATE TEMPRESAS EMP SET EMP.BDGERAREVENTOTOXICOLOGICO = NEW.BDGERAEVENTO2221 WHERE EMP.BDCODEMP = NEW.BDCODEMP AND EMP.BDGERAREVENTOTOXICOLOGICO <> NEW.BDGERAEVENTO2221;
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_EXAME_TOX_BU0 FOR VRH_EMP_TCOL_EXAME_TOX
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  if (COALESCE(old.bdcodtipo, 0) <> 0) then
     new.bdcodtipo = old.bdcodtipo;

end
^

CREATE OR ALTER TRIGGER VRH_EMP_TREDUCAOCOL_BI0 FOR VRH_EMP_TREDUCAOCOL
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;
BEGIN
  IF ((NEW.bdcodredsal IS NULL) OR (NEW.bdcodredsal = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodredsal) + 1, 1)
       FROM VRH_EMP_TREDUCAOCOL
       INTO :vNovoCod;

       NEW.bdcodredsal = :vNovoCod;
     END

  IF (NEW.BDDIASACORDOINI IS NULL) THEN
    NEW.BDDIASACORDOINI = NEW.BDQTDDIASREDSAL;


  if (new.BDDATAINIREDSAL is not null) then
     new.BDREFINIREDSAL = CAST((SUBSTRING(CAST(new.BDDATAINIREDSAL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(new.BDDATAINIREDSAL AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
  else
     new.BDREFINIREDSAL = null;

  if (new.BDDATAFIMREDSAL is not null) then
     new.BDREFFIMREDSAL = CAST((SUBSTRING(CAST(new.BDDATAFIMREDSAL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(new.BDDATAFIMREDSAL AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
  else
     new.BDREFFIMREDSAL = null;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TREDUCAOCOL_BU0 FOR VRH_EMP_TREDUCAOCOL
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  if (new.BDDATAINIREDSAL is not null) then
     new.BDREFINIREDSAL = CAST((SUBSTRING(CAST(new.BDDATAINIREDSAL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(new.BDDATAINIREDSAL AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
  else
     new.BDREFINIREDSAL = null;

  if (new.BDDATAFIMREDSAL is not null) then
     new.BDREFFIMREDSAL = CAST((SUBSTRING(CAST(new.BDDATAFIMREDSAL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(new.BDDATAFIMREDSAL AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);
  else
     new.BDREFFIMREDSAL = null;
end
^

CREATE OR ALTER trigger vrh_emp_tsitcol_bi0 for vrh_emp_tsitcol
active before insert position 0
AS
begin
  IF (NEW.BDDIASACORDOINI IS NULL) THEN
    NEW.BDDIASACORDOINI = NEW.BDDIASSIT;
end
^

CREATE OR ALTER trigger vrh_emp_tsitcol_ai0 for vrh_emp_tsitcol
active after insert position 0
as
declare variable WS varchar(300);
declare variable WCAT integer;
declare variable WCATES integer;
declare variable WHORA time;
declare variable WDATAINI date;
declare variable WDATAFIM date;
declare variable WDIASIT integer;
declare variable wSQLInt varchar(1000);
declare variable wSQLInt2 varchar(1000);
declare variable wdatafimant date;
declare variable wreffimsit integer;
declare variable wreffimcont integer;
declare variable winisefipstr varchar(10);
declare variable wdataaux date;
declare variable wlastcodcont integer;
declare variable wCodSit integer;
declare variable wDiaUtil integer;
declare variable wDataPagamento date;
declare variable wferiado varchar(5);
declare variable wPagEmp integer;
declare variable wCountContr integer;
declare variable WSS varchar(300);
begin
  WS = 'select first 1 BDCATEGORIACOL, BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS where BDCODEMP = ' || new.BDCODEMP || ' and BDCODCOL = ' || new.BDCODCOL || ' and BDREFCOL <= (select cast(BDDATA as integer) from SP_PARSE_DATE(''' || new.BDDATAINISEFIP || ''', ''YYYYMM'')) order by BDREFCOL DESC';
  WCAT = null;
  WCATES = null;
  execute statement WS into :WCAT, :WCATES;

  WDATAFIM = null;

  WS = 'select BDCODSIT from VRH_BASE_TPREPSIT where BDCODSIT = ' || new.bdcodsit || ' and BDGRUPOSIT in (2, 4) and BDPADRAO = ''TRUE''';
  execute statement WS into :wCodSit;

  WSS = 'select count(*) from VRH_EMP_TINTERMITENTE '||
        'where BDCODEMP = ' || new.BDCODEMP || ' and BDCODCOL = ' || new.BDCODCOL || ' and BDDATACONVTI = ''' || new.BDDATAINISEFIP || ''' and BDLANCSITUACAO = ''TRUE'' ';
  execute statement WSS into :wCountContr;

  -- intermitente. Deve verificar se tem convocação lançada, senão deve gerar uma convocação "fantasma"
  if (coalesce(WCAT, 0) = 4 and coalesce(WCATES, 0) = 111 and coalesce(wCodSit, 0) > 0 and coalesce(wCountContr, 0) <= 0) then
  begin
    WCAT = null;
    wSQLInt = 'select first 1 BDCODCONTTI, BDDATAINISERVTI, BDDATAFIMSERVTI from VRH_EMP_TINTERMITENTE where BDCODEMP = ' || new.bdcodemp || ' and BDCODCOL = ' || new.bdcodcol || ' and '||
              '((''' || new.BDDATAINISEFIP || ''' >= BDDATAINISERVTI and ''' || new.BDDATAINISEFIP || ''' <= BDDATAFIMSERVTI) or (''' || new.BDDATAINISEFIP || ''' <= BDDATAINISERVTI)) and '||
              '((select cast(BDDATA as integer) '||
              '  from SP_PARSE_DATE(''' || new.BDDATAINISEFIP || ''', ''YYYYMM'')) = (select cast(BDDATA as integer) '||
              '                                                 from SP_PARSE_DATE(BDDATAINISERVTI, ''YYYYMM'')))';

    EXECUTE STATEMENT wSQLInt INTO :WCAT, :WDATAINI, :WDATAFIM;

    wSQLInt2 = 'select BDCODCONTTI, BDDATAINISERVTI, BDDATAFIMSERVTI from VRH_EMP_TINTERMITENTE where BDCODEMP = ' || new.bdcodemp || ' and BDCODCOL = ' || new.bdcodcol || ' and '||
              '((''' || new.BDDATAINISEFIP || ''' >= BDDATAINISERVTI and ''' || new.BDDATAINISEFIP || ''' <= BDDATAFIMSERVTI) or (''' || new.BDDATAINISEFIP || ''' <= BDDATAINISERVTI)) and '||
              '((select cast(BDDATA as integer) '||
              '  from SP_PARSE_DATE(''' || new.BDDATAINISEFIP || ''', ''YYYYMM'')) = (select cast(BDDATA as integer) '||
              '                                                 from SP_PARSE_DATE(BDDATAINISERVTI, ''YYYYMM'')))';

    select current_time from RDB$DATABASE into :WHORA;

    -- INICIO data pagamento
    wDiaUtil = 0;
    wDataPagamento = cast(substring(new.BDDATAINISEFIP from 1 for 4) || '-' || substring(new.BDDATAINISEFIP from 6 for 2) || '-01' as date);
    wDataPagamento = dateadd(1 month to :wDataPagamento);

    select first 1 BDPAGEMP from VRHF_BASE_TEMPCALC where BDCODEMP = new.bdcodemp order by BDREFEMP desc into :wPagEmp;

    if (wPagEmp = 0) then
      begin
        while (wDiaUtil < 5) do
          begin
            select bdferiado from sp_feriado_empresa(new.BDCODEMP, :wDataPagamento) into :wferiado;
        
            if (wferiado = 'FALSE' and extract(weekday from wDataPagamento) not in (0,6)) then
              begin
                wDiaUtil = wDiaUtil + 1;
              end
        
            if (wDiaUtil = 5) then
              Break;

            wDataPagamento = dateadd(1 day to :wDataPagamento);
          end
      end
    else
      begin
        select ULTDIA
        from ULTIMO_DIA_MES(cast(substring(new.BDDATAINISEFIP from 6 for 2) as integer), cast(substring(new.BDDATAINISEFIP from 1 for 4) as integer))
        into :WDIASIT;

        wDataPagamento = cast(substring(new.BDDATAINISEFIP from 1 for 4) || '-' || substring(new.BDDATAINISEFIP from 6 for 2) || '-' || cast(WDIASIT as varchar(2)) as date);

        select BDDATA from SP_DATA_UTIL(new.BDCODEMP, :wDataPagamento) into :wDataPagamento;
      end
    -- FIM data pagamento

    -- Não existe contrato no mês
    if (coalesce(:WCAT, 0) <= 0) then
    begin
      WDATAFIM = new.BDDATAFIMSIT;

      select cast(BDDATA as integer) from SP_PARSE_DATE(:WDATAFIM, 'YYYYMM') into :wreffimsit;
      select cast(BDDATA as integer) from SP_PARSE_DATE(new.bddatainisefip, 'YYYYMM') into :wreffimcont;

      if ((WDATAFIM is null) or (wreffimsit > wreffimcont)) then
        begin
          winisefipstr = cast(new.BDDATAINISEFIP as varchar(10));

          select ULTDIA
          from ULTIMO_DIA_MES(cast(substring(:winisefipstr from 6 for 2) as integer), cast(substring(:winisefipstr from 1 for 4) as integer))
          into :WDIASIT;

          WDATAFIM = cast(substring(:winisefipstr from 1 for 4) || '-' || substring(:winisefipstr from 6 for 2) || '-' || cast(WDIASIT as varchar(2)) as date);
        end

      insert into VRH_EMP_TINTERMITENTE (BDCODEMP, BDCODCOL, BDCODCONTTI, BDDESCCONTRATOTI, BDDATACONVTI, BDHORACONVTI, BDCOMUNICCONVTI,
                                         BDDATAINISERVTI, BDDATAFIMSERVTI, BDDATAPAGTI, BDLANCSITUACAO)
      values (new.BDCODEMP, new.BDCODCOL, 0, 'SITUAÇÃO INTERMITENTE', new.BDDATAINISEFIP, :WHORA, 'Gerado automaticamente por motivo de afastamento',
              new.BDDATAINISEFIP, :WDATAFIM, :wDataPagamento, 'TRUE');

      select BDCODCONTTI from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDDATAINISERVTI = new.BDDATAINISEFIP into :wlastcodcont;

      insert into VRH_EMP_TINTERMITENTE_ACEI (BDCODEMP, BDCODCOL, BDCODCONTTI, BDDATAACEITETI, BDHORAACEITETI,
                                              BDCOMUNICACEITETI, BDSTATUSACEITETI)
      values (new.BDCODEMP, new.BDCODCOL, :wlastcodcont, new.BDDATAINISEFIP, :WHORA, 'SITUAÇÃO INTERMITENTE', 2);
    end
    else
    if (new.bddatafimsit is not null) then
      begin
        wdataaux = null;
        FOR EXECUTE STATEMENT wSQLInt2 INTO :WCAT, :WDATAINI, :WDATAFIM DO
          BEGIN
            if (new.BDDATAINISEFIP < :WDATAINI and :wdataaux is null) then
              begin
                wdataaux = dateadd(-1 day to WDATAINI);

                insert into VRH_EMP_TINTERMITENTE (BDCODEMP, BDCODCOL, BDCODCONTTI, BDDESCCONTRATOTI, BDDATACONVTI, BDHORACONVTI, BDCOMUNICCONVTI,
                                                   BDDATAINISERVTI, BDDATAFIMSERVTI, BDDATAPAGTI, BDLANCSITUACAO)
                values (new.BDCODEMP, new.BDCODCOL, 0, 'SITUAÇÃO INTERMITENTE', new.BDDATAINISEFIP, :WHORA, 'Gerado automaticamente por motivo de afastamento',
                        new.BDDATAINISEFIP, :wdataaux, :wDataPagamento, 'TRUE');

                select first 1 BDCODCONTTI from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDDATAINISERVTI = new.BDDATAINISEFIP into :wlastcodcont;

                insert into VRH_EMP_TINTERMITENTE_ACEI (BDCODEMP, BDCODCOL, BDCODCONTTI, BDDATAACEITETI, BDHORAACEITETI,
                                                        BDCOMUNICACEITETI, BDSTATUSACEITETI)
                values (new.BDCODEMP, new.BDCODCOL, :wlastcodcont, new.BDDATAINISEFIP, :WHORA, 'SITUAÇÃO INTERMITENTE', 2);
              end
          END

        select cast(BDDATA as integer) from SP_PARSE_DATE(new.bddatafimsit, 'YYYYMM') into :wreffimsit;
        select cast(BDDATA as integer) from SP_PARSE_DATE(:WDATAFIM, 'YYYYMM') into :wreffimcont;

        if (new.bddatafimsit > :WDATAFIM and wreffimsit = wreffimcont) then
          begin
            wdataaux = dateadd(1 day to WDATAFIM);

            insert into VRH_EMP_TINTERMITENTE (BDCODEMP, BDCODCOL, BDCODCONTTI, BDDESCCONTRATOTI, BDDATACONVTI, BDHORACONVTI, BDCOMUNICCONVTI,
                                               BDDATAINISERVTI, BDDATAFIMSERVTI, BDDATAPAGTI, BDLANCSITUACAO)
            values (new.BDCODEMP, new.BDCODCOL, 0, 'SITUAÇÃO INTERMITENTE', new.BDDATAINISEFIP, :WHORA, 'Gerado automaticamente por motivo de afastamento',
                    :wdataaux, new.bddatafimsit, :wDataPagamento, 'TRUE');

            select first 1 BDCODCONTTI from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDDATAINISERVTI = :wdataaux into :wlastcodcont;

            insert into VRH_EMP_TINTERMITENTE_ACEI (BDCODEMP, BDCODCOL, BDCODCONTTI, BDDATAACEITETI, BDHORAACEITETI,
                                                    BDCOMUNICACEITETI, BDSTATUSACEITETI)
            values (new.BDCODEMP, new.BDCODCOL, :wlastcodcont, :wdataaux, :WHORA, 'SITUAÇÃO INTERMITENTE', 2);
          end
        else
          begin
            wdatafimant = dateadd(1 day to WDATAFIM);
    
            if ((new.bddatafimsit is null) or (wreffimsit > wreffimcont)) then
              begin
                winisefipstr = cast(new.BDDATAINISEFIP as varchar(10));
            
                select ULTDIA
                from ULTIMO_DIA_MES(cast(substring(:winisefipstr from 6 for 2) as integer), cast(substring(:winisefipstr from 1 for 4) as integer))
                into :WDIASIT;
    
                wdataaux = cast(substring(:winisefipstr from 1 for 4) || '-' || substring(:winisefipstr from 6 for 2) || '-' || cast(WDIASIT as varchar(2)) as date);

                insert into VRH_EMP_TINTERMITENTE (BDCODEMP, BDCODCOL, BDCODCONTTI, BDDESCCONTRATOTI, BDDATACONVTI, BDHORACONVTI, BDCOMUNICCONVTI,
                                                   BDDATAINISERVTI, BDDATAFIMSERVTI, BDDATAPAGTI, BDLANCSITUACAO)
                values (new.BDCODEMP, new.BDCODCOL, 0, 'SITUAÇÃO INTERMITENTE', new.BDDATAINISEFIP, :WHORA, 'Gerado automaticamente por motivo de afastamento',
                        :wdatafimant, :wdataaux, :wDataPagamento, 'TRUE');

                select first 1 BDCODCONTTI from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDDATAINISERVTI = :wdatafimant into :wlastcodcont;

                insert into VRH_EMP_TINTERMITENTE_ACEI (BDCODEMP, BDCODCOL, BDCODCONTTI, BDDATAACEITETI, BDHORAACEITETI,
                                                        BDCOMUNICACEITETI, BDSTATUSACEITETI)
                values (new.BDCODEMP, new.BDCODCOL, :wlastcodcont, :wdatafimant, :WHORA, 'SITUAÇÃO INTERMITENTE', 2);
              end
          end
      end
    else
      begin -- Existe contrato no mês.
        FOR EXECUTE STATEMENT wSQLInt2 INTO :WCAT, :WDATAINI, :WDATAFIM DO
          BEGIN
            if (new.BDDATAINISEFIP < :WDATAINI) then
              begin
                if (wdatafimant is not null) then
                  begin
                    wdataaux = dateadd(-1 day to WDATAINI);

                    insert into VRH_EMP_TINTERMITENTE (BDCODEMP, BDCODCOL, BDCODCONTTI, BDDESCCONTRATOTI, BDDATACONVTI, BDHORACONVTI, BDCOMUNICCONVTI,
                                                       BDDATAINISERVTI, BDDATAFIMSERVTI, BDDATAPAGTI, BDLANCSITUACAO)
                    values (new.BDCODEMP, new.BDCODCOL, 0, 'SITUAÇÃO INTERMITENTE', new.BDDATAINISEFIP, :WHORA, 'Gerado automaticamente por motivo de afastamento',
                            :wdatafimant, :wdataaux, :wDataPagamento, 'TRUE');

                    select first 1 BDCODCONTTI from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDDATAINISERVTI = :wdatafimant into :wlastcodcont;

                    insert into VRH_EMP_TINTERMITENTE_ACEI (BDCODEMP, BDCODCOL, BDCODCONTTI, BDDATAACEITETI, BDHORAACEITETI,
                                                            BDCOMUNICACEITETI, BDSTATUSACEITETI)
                    values (new.BDCODEMP, new.BDCODCOL, :wlastcodcont, :wdatafimant, :WHORA, 'SITUAÇÃO INTERMITENTE', 2);
                  end
                else
                  begin
                    wdataaux = dateadd(-1 day to WDATAINI);

                    insert into VRH_EMP_TINTERMITENTE (BDCODEMP, BDCODCOL, BDCODCONTTI, BDDESCCONTRATOTI, BDDATACONVTI, BDHORACONVTI, BDCOMUNICCONVTI,
                                                       BDDATAINISERVTI, BDDATAFIMSERVTI, BDDATAPAGTI, BDLANCSITUACAO)
                    values (new.BDCODEMP, new.BDCODCOL, 0, 'SITUAÇÃO INTERMITENTE', new.BDDATAINISEFIP, :WHORA, 'Gerado automaticamente por motivo de afastamento',
                            new.BDDATAINISEFIP, :wdataaux, :wDataPagamento, 'TRUE');

                    select first 1 BDCODCONTTI from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDDATAINISERVTI = new.BDDATAINISEFIP into :wlastcodcont;

                    insert into VRH_EMP_TINTERMITENTE_ACEI (BDCODEMP, BDCODCOL, BDCODCONTTI, BDDATAACEITETI, BDHORAACEITETI,
                                                            BDCOMUNICACEITETI, BDSTATUSACEITETI)
                    values (new.BDCODEMP, new.BDCODCOL, :wlastcodcont, new.BDDATAINISEFIP, :WHORA, 'SITUAÇÃO INTERMITENTE', 2);

                    wdatafimant = dateadd(1 day to WDATAFIM);
                  end
              end
            else
              begin
                wdatafimant = dateadd(1 day to WDATAFIM);
              end
          END
          wdatafimant = dateadd(1 day to WDATAFIM);

          select cast(BDDATA as integer) from SP_PARSE_DATE(new.bddatafimsit, 'YYYYMM') into :wreffimsit;
          select cast(BDDATA as integer) from SP_PARSE_DATE(:wdatafimant, 'YYYYMM') into :wreffimcont;

          if ((new.bddatafimsit is null) or (wreffimsit > wreffimcont)) then
            begin
              winisefipstr = cast(new.BDDATAINISEFIP as varchar(10));

              select ULTDIA
              from ULTIMO_DIA_MES(cast(substring(:winisefipstr from 6 for 2) as integer), cast(substring(:winisefipstr from 1 for 4) as integer))
              into :WDIASIT;

              wdataaux = cast(substring(:winisefipstr from 1 for 4) || '-' || substring(:winisefipstr from 6 for 2) || '-' || cast(WDIASIT as varchar(2)) as date);

              insert into VRH_EMP_TINTERMITENTE (BDCODEMP, BDCODCOL, BDCODCONTTI, BDDESCCONTRATOTI, BDDATACONVTI, BDHORACONVTI, BDCOMUNICCONVTI,
                                                 BDDATAINISERVTI, BDDATAFIMSERVTI, BDDATAPAGTI, BDLANCSITUACAO)
              values (new.BDCODEMP, new.BDCODCOL, 0, 'SITUAÇÃO INTERMITENTE', new.BDDATAINISEFIP, :WHORA, 'Gerado automaticamente por motivo de afastamento',
                      :wdatafimant, :wdataaux, :wDataPagamento, 'TRUE');

              select first 1 BDCODCONTTI from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDDATAINISERVTI = :wdatafimant into :wlastcodcont;

              insert into VRH_EMP_TINTERMITENTE_ACEI (BDCODEMP, BDCODCOL, BDCODCONTTI, BDDATAACEITETI, BDHORAACEITETI,
                                                      BDCOMUNICACEITETI, BDSTATUSACEITETI)
              values (new.BDCODEMP, new.BDCODCOL, :wlastcodcont, :wdatafimant, :WHORA, 'SITUAÇÃO INTERMITENTE', 2);
            end
      end
  end
end
^

--Sol. 18256 - Bruno L. R. - 02/08/2017 - Criação da trigger para gravar novamente o lançamento da rescisão no momento que o processo de reintegração é excluído
CREATE OR ALTER TRIGGER vrh_emp_trescisao_reintegr_ad0 FOR vrh_emp_trescisao_reintegracao
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  DELETE FROM VRH_EMP_TRESCISAO WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL;

--Sol. 129845 - Paulo Nunes - 29/11/2019 - Criado verificação se existe o colaborador pois quando exclui o colaborador não pode fazer o insert da rescisão.
  if (exists(select C.BDCODCOL
             from VRH_EMP_TCOLCON C
             where C.BDCODEMP = old.BDCODEMP and
                   C.BDCODCOL = old.BDCODCOL)) then
  begin
    update or insert into VRH_EMP_TRESCISAO (BDCODEMP, BDCODCOL, BDDATARESCISAO, BDCODPRES, BDDATAAVPREVIO, BDDATAHOM,
                                             BDDATAPAGRESCISAO, BDSALDOFGTS, BDCALCFGTSMESANT, BDMAIORREMUNERACAO,
                                             BDCHAVEINDENTIFICACAO, BDDATAPAGGRFC, BDREPOSICAOVAGA, BDDISSIDIO,
                                             BDDATADISSIDIO, BDDESCANSOINDENIZADO, BDREFRESCISAO, BDDISPAVPREVRESC,
                                             BDNOVOEMPRESC, BDPERTRCTRESC, BDPERFGTSRESC, BDPROJECAOAVISO,
                                             BDDIASINDENIZADOS, BDDIASTRABALHADOS, BDDATANOTIF, BDTIPOAVPREV,
                                             BDREFPAGRESCISAO, BDREFPROJECAOAVISO, BDENVIADORHNET, BDINDPENALIM,
                                             BDVALFGTSRESC)
    values (old.BDCODEMP, old.BDCODCOL, old.BDDATARESCISAO, old.BDCODPRES, old.BDDATAAVPREVIO, old.BDDATAHOM,
            old.BDDATAPAGRESCISAO, old.BDSALDOFGTS, old.BDCALCFGTSMESANT, old.BDMAIORREMUNERACAO,
            old.BDCHAVEINDENTIFICACAO, old.BDDATAPAGGRFC, old.BDREPOSICAOVAGA, old.BDDISSIDIO, old.BDDATADISSIDIO,
            old.BDDESCANSOINDENIZADO, old.BDREFRESCISAO, old.BDDISPAVPREVRESC, old.BDNOVOEMPRESC, old.BDPERTRCTRESC,
            old.BDPERFGTSRESC, old.BDPROJECAOAVISO, old.BDDIASINDENIZADOS, old.BDDIASTRABALHADOS, old.BDDATANOTIF,
            old.BDTIPOAVPREV, old.BDREFPAGRESCISAO, old.BDREFPROJECAOAVISO, old.BDENVIADORHNET, old.BDINDPENALIM,
            old.BDVALFGTSRESC)
    matching (BDCODEMP, BDCODCOL, BDDATARESCISAO, BDCODPRES);
  end
end
^

CREATE OR ALTER trigger vrh_emp_tcol_reintegracao_ad0 for vrh_emp_tcol_reintegracao
active after delete position 0
AS
BEGIN
  DELETE FROM VRH_EMP_TRESCISAO_REINTEGRACAO WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL;
--Sol. 129845 - Paulo Nunes - 29/11/2019 - Alterado update para verificar se existe o colaborador.
  UPDATE VRH_EMP_TCOL_ADM SET BDTIPOADMCOL = OLD.BDTIPOADMCOLANT 
    where exists(select C.BDCODEMP
               from VRH_EMP_TCOLCON C
               where C.BDCODEMP = old.BDCODEMP and
                     C.BDCODCOL = old.BDCODCOL) and
        BDCODEMP = old.BDCODEMP and
        BDCODCOL = old.BDCODCOL;
END
^

/* Restore proc. body: SP_VRH_MONTAQUADROHORAS */
create or alter procedure SP_VRH_MONTAQUADROHORAS (
    PREMP varchar(25000),
    PRCODPQUA integer,
    PRCODQH integer,
    PREXPINICIAL smallint = 0,
    PRINATIVAR smallint = 0)
returns (
    BDCODEMPRHNET integer,
    BDCODEMP integer,
    BDCODPQUA integer,
    BDCODQH integer,
    BDDESCQH DM_BDDESCQH,
    BDDIASEMQH integer,
    BDHORA1 time,
    BDHORA2 time,
    BDHORA3 time,
    BDHORA4 time,
    BDHORA5 time,
    BDHORA6 time,
    BDHORA7 time,
    BDHORA8 time,
    BDHORFLEX integer,
    BDINATIVO DM_BOOLEAN,
    BDATIVO smallint)
as
declare variable WSQL varchar(32700);
declare variable WCODEMPRHNET integer;
declare variable WEMPRHNETATU integer;
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WCODPQUA integer;
declare variable WCODPQUAATU integer;
declare variable WCODQH integer;
declare variable WCODQHATU integer;
declare variable WDESCQH DM_BDDESCQH;
declare variable WDESCQHATU DM_BDDESCQH;
declare variable WDIASEM integer;
declare variable WDIASEMATU integer;
declare variable WHORA time;
declare variable WFLEXIVEL DM_BOOLEAN;
declare variable WFLEXIVELATU DM_BOOLEAN;
declare variable WSHORA smallint;
declare variable WHORA1 time;
declare variable WHORA2 time;
declare variable WHORA3 time;
declare variable WHORA4 time;
declare variable WHORA5 time;
declare variable WHORA6 time;
declare variable WHORA7 time;
declare variable WHORA8 time;
declare variable WREF integer;
declare variable WDATA date;
declare variable WINATIVO DM_BOOLEAN;
declare variable WINATIVOANT DM_BOOLEAN;
BEGIN
  wref = null;
  wref = RDB$GET_CONTEXT ('USER_SESSION', 'W_ANOMES');
  prinativar = coalesce(prinativar, 0);

  if (wref is null) then
     begin
       select current_date from RDB$DATABASE into :wdata;
       wref = CAST((SUBSTRING(CAST(wdata as VARCHAR(10)) from 1 FOR 4)||SUBSTRING(CAST(wdata as VARCHAR(10)) from 6 FOR 2)) AS INTEGER);
     end

  wsql = 'select BDCODEMPRHNET, BDCODEMP, BDDESCQH, BDCODQH, BDCODPQUA, BDDIASEMQH, BDHORA, BDFLEXIVEL, BDINATIVO '||
         'from (select coalesce(empc.BDCODWEB, empc.BDCODEMP) BDCODEMPRHNET, empc.BDCODEMP, q.BDCODQH, q.BDCODPQUA, q.BDDESCQH, qd.BDDIASEMQH, qhs.BDQHHSENT BDHORA, qhs.BDCODQHH, qhs.BDCODQHHS,'||
                 '''1'' BDCODSEQ, ''FALSE'' BDFLEXIVEL, ''FALSE'' BDCONTROLE, q.BDINATIVO '||
               'from ('||
                 'select EMPC.BDCODEMP, EMPC2.BDCODPQUA '||
                 'from (select EMPC.BDCODEMP, MAX(EMPC.BDREFEMP) BDREFEMP '||
                       'from VRHF_BASE_TEMPVINC EMPC '||
                       'where EMPC.BDREFEMP <= '||wref||' '||
                          'and EMPC.BDCODPQUA is not null ';

                          IF (premp IS NOT NULL AND premp <> '') THEN
                             wsql = wsql||' and '||premp;
           
                          IF (prcodpqua IS NOT NULL AND prcodpqua <> 0) THEN
                             wsql = wsql||' and EMPC.BDCODPQUA = '||prcodpqua;

  wsql = wsql||
                       'group by BDCODEMP'||
                      ') EMPC '||
                 'join VRHF_BASE_TEMPVINC EMPC2 on (EMPC2.BDCODEMP = EMPC.BDCODEMP and EMPC2.BDREFEMP = EMPC.BDREFEMP) '||
               ') EMP '||
               'join (select EMPC.* from TEMPRESAS EMPC '||
                     'where upper(coalesce(empc.BDRHNET, ''FALSE'')) = ''TRUE''';

               if (coalesce(prexpinicial, 0) <> 1) then
                  wsql = wsql||' and upper(coalesce(empc.BDNOVORHNETSOCIAL, ''FALSE'')) = ''TRUE''';

               IF (premp IS NOT NULL AND premp <> '') THEN
                  wsql = wsql||' and '||premp;

  wsql = wsql||') EMPC on (EMPC.BDCODEMP = EMP.BDCODEMP) '||
               'left outer join VRH_BASE_TQH Q on (Q.BDCODPQUA = EMP.BDCODPQUA) '||
               'left outer join VRH_BASE_TQH_DIAS qd on (qd.BDCODQH = q.BDCODQH) and (qd.BDCODPQUA = q.BDCODPQUA) '||
               'left outer join VRH_BASE_TQH_HORARIO qh on (qh.BDCODQHH = qd.BDCODQHH) '||
               'left outer join VRH_BASE_TQH_HORAS qhs on (qhs.BDCODQHH = qh.BDCODQHH) '||
               'where qd.BDCODQH is not null and emp.BDCODPQUA is not null and empc.BDCODEMP is not null ';

               IF (premp IS NOT NULL AND premp <> '') THEN
                  wsql = wsql||' and '||premp;

               IF (prcodpqua IS NOT NULL AND prcodpqua <> 0) THEN
                  wsql = wsql||' and q.BDCODPQUA = '||prcodpqua;

               IF (prcodqh IS NOT NULL AND prcodqh <> 0) THEN
                  wsql = wsql||' and q.BDCODQH = '||prcodqh;

  wsql = wsql||
               ' union all '||
               'select coalesce(empc.BDCODWEB, empc.BDCODEMP) BDCODEMPRHNET, empc.BDCODEMP, q.BDCODQH, q.BDCODPQUA, q.BDDESCQH, qd.BDDIASEMQH, qhs.BDQHHSSAI BDHORA, qhs.BDCODQHH, qhs.BDCODQHHS, '||
                 '''2'' BDCODSEQ, ''FALSE'' BDFLEXIVEL, ''FALSE'' BDCONTROLE, q.BDINATIVO '||
               'from ('||
                 'select EMPC.BDCODEMP, EMPC2.BDCODPQUA '||
                 'from (select EMPC.BDCODEMP, MAX(EMPC.BDREFEMP) BDREFEMP '||
                       'from VRHF_BASE_TEMPVINC EMPC '||
                       'where EMPC.BDREFEMP <= '||wref||' '||
                          'and EMPC.BDCODPQUA is not null ';

                          IF (premp IS NOT NULL AND premp <> '') THEN
                             wsql = wsql||' and '||premp;
           
                          IF (prcodpqua IS NOT NULL AND prcodpqua <> 0) THEN
                             wsql = wsql||' and EMPC.BDCODPQUA = '||prcodpqua;

  wsql = wsql||
                       'group by BDCODEMP'||
                      ') EMPC '||
                 'join VRHF_BASE_TEMPVINC EMPC2 on (EMPC2.BDCODEMP = EMPC.BDCODEMP and EMPC2.BDREFEMP = EMPC.BDREFEMP) '||
               ') EMP '||
               'join (select EMPC.* from TEMPRESAS EMPC '||
                     'where upper(coalesce(empc.BDRHNET, ''FALSE'')) = ''TRUE''';

               if (coalesce(prexpinicial, 0) <> 1) then
                  wsql = wsql||' and upper(coalesce(empc.BDNOVORHNETSOCIAL, ''FALSE'')) = ''TRUE''';

               IF (premp IS NOT NULL AND premp <> '') THEN
                  wsql = wsql||' and '||premp;

  wsql = wsql||') EMPC on (EMPC.BDCODEMP = EMP.BDCODEMP) '||
               'left outer join VRH_BASE_TQH Q on (Q.BDCODPQUA = EMP.BDCODPQUA) '||
               'left outer join VRH_BASE_TQH_DIAS qd on (qd.BDCODQH = q.BDCODQH) and (qd.BDCODPQUA = q.BDCODPQUA) '||
               'left outer join VRH_BASE_TQH_HORARIO qh on (qh.BDCODQHH = qd.BDCODQHH) '||
               'left outer join VRH_BASE_TQH_HORAS qhs on (qhs.BDCODQHH = qh.BDCODQHH) '||
               'where upper(empc.BDRHNET) = ''TRUE'' '||
                    ' and qd.BDCODQH is not null and emp.BDCODPQUA is not null and empc.BDCODEMP is not null ';

               IF (premp IS NOT NULL AND premp <> '') THEN
                  wsql = wsql||' and '||premp;

               IF (prcodpqua IS NOT NULL AND prcodpqua <> 0) THEN
                  wsql = wsql||' and q.BDCODPQUA = '||prcodpqua;

               IF (prcodqh IS NOT NULL AND prcodqh <> 0) THEN
                  wsql = wsql||' and q.BDCODQH = '||prcodqh;

  wsql = wsql||
               ' union all '||
               'select coalesce(EMPC.BDCODWEB, EMPC.BDCODEMP) BDCODEMPRHNET, empc.BDCODEMP, Q.BDCODQH, q.BDCODPQUA, Q.BDDESCQH, 0 BDDIASEMQH, CAST(null as TIME) BDHORA, 0 BDCODQHH, 0 BDCODQHHS, '||
                 '''0'' BDCODSEQ, ''FALSE'' BDFLEXIVEL, ''TRUE'' BDCONTROLE, q.BDINATIVO '||
               'from ('||
                 'select EMPC.BDCODEMP, EMPC2.BDCODPQUA '||
                 'from (select EMPC.BDCODEMP, MAX(EMPC.BDREFEMP) BDREFEMP '||
                       'from VRHF_BASE_TEMPVINC EMPC '||
                       'where EMPC.BDREFEMP <= '||wref||' '||
                          'and EMPC.BDCODPQUA is not null ';

                          IF (premp IS NOT NULL AND premp <> '') THEN
                             wsql = wsql||' and '||premp;
           
                          IF (prcodpqua IS NOT NULL AND prcodpqua <> 0) THEN
                             wsql = wsql||' and EMPC.BDCODPQUA = '||prcodpqua;

  wsql = wsql||
                       'group by BDCODEMP'||
                      ') EMPC '||
                 'join VRHF_BASE_TEMPVINC EMPC2 on (EMPC2.BDCODEMP = EMPC.BDCODEMP and EMPC2.BDREFEMP = EMPC.BDREFEMP) '||
               ') EMP '||
               'join (select EMPC.* from TEMPRESAS EMPC '||
                     'where upper(coalesce(empc.BDRHNET, ''FALSE'')) = ''TRUE''';

               if (coalesce(prexpinicial, 0) <> 1) then
                  wsql = wsql||' and upper(coalesce(empc.BDNOVORHNETSOCIAL, ''FALSE'')) = ''TRUE''';

               IF (premp IS NOT NULL AND premp <> '') THEN
                  wsql = wsql||' and '||premp;

  wsql = wsql||') EMPC on (EMPC.BDCODEMP = EMP.BDCODEMP) '||
               'left outer join VRH_BASE_TQH Q on (Q.BDCODPQUA = EMP.BDCODPQUA) '||
               'where upper(empc.BDRHNET) = ''TRUE'' '||
                 'and EMP.BDCODPQUA is not null and empc.BDCODEMP is not null '||
                 'and not exists(select * from VRH_BASE_TQH_DIAS where BDCODPQUA = Q.BDCODPQUA and BDCODQH = Q.BDCODQH and BDCODQHH > 0) ';

               IF (premp IS NOT NULL AND premp <> '') THEN
                  wsql = wsql||' and '||premp;

               IF (prcodpqua IS NOT NULL AND prcodpqua <> 0) THEN
                  wsql = wsql||' and q.BDCODPQUA = '||prcodpqua;

               IF (prcodqh IS NOT NULL AND prcodqh <> 0) THEN
                  wsql = wsql||' and q.BDCODQH = '||prcodqh;

  wsql = wsql||
         ') '||
         'order by BDCODEMP, BDCODPQUA, BDCODQH, BDDIASEMQH, BDCODQHHS, BDCODSEQ';

  wemprhnetatu = 0;
  wempatu = 0;
  wcodpquaatu = 0;
  wcodqhatu = 0;
  wdiasematu = -1;
  wshora      = 1;
  whora1      = NULL;
  whora2      = NULL;
  whora3      = NULL;
  whora4      = NULL;
  whora5      = NULL;
  whora6      = NULL;
  whora7      = NULL;
  whora8      = NULL;
  winativo    = NULL;
  winativoant = NULL;

  FOR EXECUTE STATEMENT wsql INTO :wcodemprhnet, :wcodemp, :wdescqh, :wcodqh, :wcodpqua, :wdiasem, :whora, :wflexivel, :winativo DO
    BEGIN
      IF (wempatu = 0) THEN
         begin
           wempatu = wcodemp;
           winativoant = winativo;
         end

      IF (wcodpquaatu = 0) THEN
         wcodpquaatu = wcodpqua;

      IF (wcodqhatu = 0) THEN
         wcodqhatu = wcodqh;

      IF (wdiasematu = -1) THEN
         wdiasematu = wdiasem;

      IF ((wempatu <> wcodemp) OR (wcodpquaatu <> wcodpqua) OR (wcodqhatu <> wcodqh) OR (wdiasematu <> wdiasem)) THEN
         BEGIN
           BDCODEMPRHNET = wemprhnetatu;
           BDCODEMP = wempatu;
           BDCODPQUA = wcodpquaatu;
           BDDESCQH = wdescqhatu;

           IF (wdiasematu = 7) THEN
              BDDIASEMQH = 1;
           ELSE
              BDDIASEMQH = wdiasematu + 1;

           BDCODQH = wcodqhatu;
           BDHORA1 = whora1;
           BDHORA2 = whora2;
           BDHORA3 = whora3;
           BDHORA4 = whora4;
           BDHORA5 = whora5;
           BDHORA6 = whora6;
           BDHORA7 = whora7;
           BDHORA8 = whora8;

           if (prinativar > 0) then
              BDINATIVO = 'TRUE';
           else
           BDINATIVO = winativoant;

           if ((prinativar > 0) or (upper(coalesce(winativoant, 'FALSE')) = 'TRUE')) then
              BDATIVO = 0;
           else
              BDATIVO = 1;

           IF (UPPER(wflexivelatu) = 'TRUE') THEN
              BDHORFLEX = 1;
           ELSE
              BDHORFLEX = 0;

           SUSPEND;
           wempatu = wcodemp;
           wcodpquaatu = wcodpqua;
           wdiasematu = wdiasem;
           wcodqhatu = wcodqh;
           whora1 = NULL;
           whora2 = NULL;
           whora3 = NULL;
           whora4 = NULL;
           whora5 = NULL;
           whora6 = NULL;
           whora7 = NULL;
           whora8 = NULL;
           wshora = 1;
           winativoant = winativo;
         END

      wdescqhatu = wdescqh;
      wflexivelatu = wflexivel;
      wemprhnetatu = wcodemprhnet;

      IF (wshora = 1) THEN
         whora1 = whora;
      ELSE
      IF (wshora = 2) THEN
         whora2 = whora;
      ELSE
      IF (wshora = 3) THEN
         whora3 = whora;
      ELSE
      IF (wshora = 4) THEN
         whora4 = whora;
      ELSE
      IF (wshora = 5) THEN
         whora5 = whora;
      ELSE
      IF (wshora = 6) THEN
         whora6 = whora;
      ELSE
      IF (wshora = 7) THEN
         whora7 = whora;
      ELSE
         whora8 = whora;

      wshora = wshora + 1;
    END

  IF ((wempatu <> 0) AND (wcodpquaatu <> 0) AND (wcodqhatu <> 0)) THEN
     BEGIN
       BDCODEMPRHNET = wemprhnetatu;
       BDCODEMP = wempatu;
       BDCODPQUA = wcodpquaatu;
       BDDESCQH = wdescqhatu;

       IF (wdiasematu = 7) THEN
          BDDIASEMQH = 1;
       ELSE
          BDDIASEMQH = wdiasematu + 1;

       BDCODQH = wcodqhatu;
       BDHORA1 = whora1;
       BDHORA2 = whora2;
       BDHORA3 = whora3;
       BDHORA4 = whora4;
       BDHORA5 = whora5;
       BDHORA6 = whora6;
       BDHORA7 = whora7;
       BDHORA8 = whora8;

       if (prinativar > 0) then
          BDINATIVO = 'TRUE';
       else
       BDINATIVO = winativoant;

       if ((prinativar > 0) or (upper(coalesce(winativoant, 'FALSE')) = 'TRUE')) then
          BDATIVO = 0;
       else
          BDATIVO = 1;

       IF (UPPER(wflexivelatu) = 'TRUE') THEN
          BDHORFLEX = 1;
       ELSE
          BDHORFLEX = 0;
       SUSPEND;
     END

END^


CREATE OR ALTER procedure SP_QUADRO_INTERMITENTE_CONTRATO (
    PREMPRESA integer not null,
    PRCOLABORADOR integer not null,
    PRCONTRATO integer not null)
returns (
    QUADRO varchar(1000))
as
declare variable SQL varchar(345);
declare variable EMPRESA integer;
declare variable COLABORADOR integer;
declare variable QUADROREGISTRO varchar(100);
declare variable WAUXBDDESQHH varchar(50);
declare variable WAUXBDCODQHH integer;
declare variable WAUXBDDATADTI date;
declare variable QUADROFINAL varchar(1000);
declare variable CONTRATO integer;
begin
  /*Passo os parâmetros de entrada para as respectivas variáveis*/
  CONTRATO    = PRCONTRATO;
  EMPRESA     = PREMPRESA;
  COLABORADOR = PRCOLABORADOR;
  QUADROFINAL = '';

  -- Sol. 16669 - Criação da trigger para controlar inserção de novos motivos para sáida do eSocial. - Gabriel Z. 31/07/2017
  /*SQL que busca os quadros de horários informados no contrato*/
  SQL = ' SELECT'||
        ' QH_INTERM.BDDATADTI,'||
        ' QH_INTERM.BDCODQHH,'||
        ' QH.bddesqhh'||
        ' FROM VRH_EMP_TINTERMITENTE_QHDIAS QH_INTERM'||
        ' LEFT JOIN VRH_BASE_TQH_HORARIO QH ON (QH_INTERM.BDCODQHH = QH.BDCODQHH)'||
        ' WHERE'||
        ' QH_INTERM.BDCODEMP = '   || CAST(EMPRESA AS VARCHAR(10))    ||' AND '||
        ' QH_INTERM.BDCODCOL = '   || CAST(COLABORADOR AS VARCHAR(10))||' AND '||
        ' QH_INTERM.BDCODCONTTI = '|| CAST(CONTRATO AS VARCHAR(10));

  FOR EXECUTE STATEMENT SQL INTO
    :WAUXBDDATADTI,
    :WAUXBDCODQHH,
    :WAUXBDDESQHH
  DO
    BEGIN
        IF (WAUXBDCODQHH IS NOT NULL) THEN
            BEGIN
                /*Se salvou o quadro de horário*/
                EXECUTE PROCEDURE ddmmaaaa(WAUXBDDATADTI) returning_values :QUADROREGISTRO;
                QUADROREGISTRO =  QUADROREGISTRO ||' - '||WAUXBDDESQHH;
           END
        ELSE
            BEGIN
                /*Se não estiver com o link de registro para o quadro de horário*/
                EXECUTE PROCEDURE ddmmaaaa(WAUXBDDATADTI) returning_values :QUADROREGISTRO ;
                QUADROREGISTRO = QUADROREGISTRO ||' - '||'Quadro não informado para está data';
            END

        /*Passa o quadro de horário encontrado no registro para o quadro de horário final*/
        QUADROFINAL = QUADROFINAL || QUADROREGISTRO||ascii_char(13);
    END

    /*Passa valor de retorno e suspende a função*/
    QUADRO = QUADROFINAL;
    SUSPEND;

end^

CREATE OR ALTER procedure SP_ESTABILIDADE_COL (
    PROPCAOESTAB integer,
    PRBDCODEMP varchar(500),
    PRBDCODCOL varchar(500),
    PRBDREF integer,
    PRTIPOSIT integer,
    PRPRIMDIAMES date,
    PRULTDIAMES date,
    PRCODSINTRAB varchar(500),
    PRCODTPCC varchar(500),
    PRCODCLA varchar(500),
    PRCODFUN varchar(500))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDFIMCIPA date,
    BDINICIPA date,
    BDNOMCOL varchar(150),
    BDCODSINTRAB integer,
    BDDATAINISIT date,
    BDDATAFIMSIT date,
    BDCODSIT integer,
    BDDESCSIT varchar(100),
    BDFIMPERGOZOFE date,
    BDINIPERGOZOFE date,
    BDFIMPERAQUISFE date,
    BDINIPERAQUISFE date,
    BDDATAESTAB date)
as
declare variable WWHERE varchar(2000);
declare variable WORDERBY varchar(100);
declare variable WSQL varchar(6000);
BEGIN
    IF (PROPCAOESTAB = 0) THEN     /*SITUACAO*/
        BEGIN
           /*|BUSCA O ÚLTIMO DIA DO MÊS QUE FOI PASSADO NA REFERÊNCIA|*/
--           WSQL = '';
--           WSQL = 'SELECT * FROM ULTIMO_DIA_MES('||RIGHT(PRBDREF,2)||','||LEFT(PRBDREF,4)||')';
--           EXECUTE STATEMENT WSQL INTO :WULTDIAMES;
        
           /*|MONTA SQL|*/
           WSQL = '';
           WSQL = ' SELECT * FROM '||
                  '( SELECT '||
                  '     SIT.BDCODEMP, '||
                  '     SIT.BDCODCOL, '||
                  '     COLCAD.BDNOMCOL, '||
                  '     COLVINC.BDCODSINTRAB, '||
                  '     SIT.BDDATAINISIT, '||
                  '     SIT.BDDATAFIMSIT, '||
                  '     SIT.BDCODSIT, '||
                  '     PREPSIT.BDDESCSIT, '||
                  '     CASE '||
                  '         WHEN PREPSIT.BDGRUPOSIT IN (4,0) THEN '||  /* sal mat ou sal mat emp */
                  '             CASE '||
                  --'                 WHEN SIT.BDDATAPARTOSIT IS NULL THEN DATEADD(DAY,PREPESTAB.BDDIASETB-1,SIT.BDDATAINISIT)'||
                  '                 WHEN SIT.BDDATAPARTOSIT IS NULL THEN DATEADD(DAY, PREPESTAB.BDDIASETB-1, SIT.BDDATAINISIT) '||
                  '             ELSE '||
                  --'                 DATEADD(DAY, PREPESTAB.BDDIASETB-1,SIT.BDDATAPARTOSIT)  '||
                  '                 DATEADD(DAY, PREPESTAB.BDDIASETB -1, SIT.BDDATAPARTOSIT) '||
                  '             END '||
                  '     ELSE '||
                  --'         DATEADD(DAY,PREPESTAB.BDDIASETB-1,SIT.BDDATAFIMSIT) '||
                  '         DATEADD(DAY, PREPESTAB.BDDIASETB, SIT.BDDATAFIMSIT) '||
                  '     END AS BDDATAESTAB '||
                  ' FROM VRH_EMP_TSITCOL SIT '||
                  ' LEFT JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON(COLCAD.BDCODEMP = SIT.BDCODEMP AND '||
                  '                                            COLCAD.BDCODCOL = SIT.BDCODCOL) '||
                  ' LEFT JOIN SP_VRHF_TCOL_VINC_REF(COLCAD.BDCODEMP, '||
                  '                                 COLCAD.BDCODCOL, '||
                  '                                 '|| PRBDREF ||') COLVINC ON(COLVINC.BDCODEMP = COLCAD.BDCODEMP AND '||
                  '                                                  COLVINC.BDCODCOL = COLCAD.BDCODCOL) '||
                  ' LEFT OUTER JOIN VRH_BASE_TPREPSIT PREPSIT ON (SIT.BDCODSIT = PREPSIT.BDCODSIT) '||
                  ' LEFT OUTER JOIN VRH_BASE_TPREPESTAB PREPESTAB ON(PREPESTAB.BDCODSINTRAB = COLVINC.BDCODSINTRAB AND '||
                  '                                                  PREPESTAB.BDGRUPOSITETB = PREPSIT.BDGRUPOSIT AND '||
                                                                    'PREPESTAB.BDTIPOETB = 0) ';
           /*
           0 - Somente os ativos
           1 - Todos
           2 - Somente os demitidos
           3 - Somente admitidos no mês
           4 - Somente demitidos no mês
           5 - Ativos sem demitidos no mês
           6 - Ativos sem demitidos com transferência no mês
           7 - Ativos sem afastados no mês inteiro
           8 - Afastados o mês inteiro
           */

           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 0) THEN  -- somente ativos
              wsql = wsql || 'join sp_somente_ativos('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 2) THEN  -- somente demitidos
              wsql = wsql || 'join sp_somente_demitidos('''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 3) THEN  -- admitidos no mês
              wsql = wsql || 'join sp_somente_admitidos_mes('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 4) THEN  -- demitidos no mês
              wsql = wsql || 'join sp_somente_demitidos_mes('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 5) THEN  -- ativos sem demitidos no mês
              wsql = wsql || 'join sp_ativos_sem_demitidos_mes('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 6) THEN  -- ativos sem demitidos no mês, com transferidos
              wsql = wsql || 'join sp_ati_sem_dem_com_transf('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 7) THEN  -- ativos sem afastados o mês inteiro
              wsql = wsql || 'join sp_ati_sem_afast_mes_int('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 8) THEN  -- afastados o mês inteiro
              wsql = wsql || 'join sp_afastados_mes_inteiro('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';


            -- Filtro por sindicato
           IF ((prcodsintrab IS NOT NULL) AND (prcodsintrab <> '')) THEN
              WSQL = WSQL || ' join VW_VRH_EMP_TCOL_VINC COL_VINC on (COLCAD.BDCODEMP = COL_VINC.BDCODEMP and COLCAD.BDCODCOL = COL_VINC.BDCODCOL and ' || prcodsintrab || ') ';
        
           -- Filtro por Centro de Custo
           IF ((PRCODTPCC IS NOT NULL) AND (PRCODTPCC <> '')) THEN
              WSQL = WSQL || ' JOIN VRHF_EMP_TPREPFN COLVINC_CC ON (COLCAD.BDCODEMP = COLVINC_CC.BDCODEMP AND COLCAD.BDCODCOL = COLVINC_CC.BDCODCOL AND ' || PRCODTPCC || ') ';
         
           -- Filtro por classe
           IF ((PRCODCLA IS NOT NULL) AND (PRCODCLA <> '')) THEN
              WSQL = WSQL || ' join VW_VRH_EMP_TCOLCON_VINC COLCON_VINC on (COLCAD.BDCODEMP = COLCON_VINC.BDCODEMP and COLCAD.BDCODCOL = COLCON_VINC.BDCODCOL and ' || PRCODCLA || ') ';
         
           -- Filtro por funcao
           IF ((PRCODFUN IS NOT NULL) AND (PRCODFUN <> '')) THEN
              WSQL = WSQL || ' join VW_VRH_EMP_TCOL_VINCDIA COL_VINCDIA on (COLCAD.BDCODEMP = COL_VINCDIA.BDCODEMP and COLCAD.BDCODCOL = COL_VINCDIA.BDCODCOL and ' || PRCODFUN || ') ';

        
           /*|MONTA WHERE|*/
           WWHERE = ' WHERE ';

        
           /*EMPRESA*/
           IF (PRBDCODEMP <> '' AND PRBDCODEMP IS NOT NULL) THEN
             BEGIN
               IF (position('SIT.' IN PRBDCODEMP) = 0) THEN
                  WWHERE = WWHERE || REPLACE(PRBDCODEMP, 'BDCODEMP', 'SIT.BDCODEMP');
               else
                  WWHERE = WWHERE || PRBDCODEMP;
             END
        
           /*COLABORADOR*/
           IF (PRBDCODCOL <> '' AND PRBDCODCOL IS NOT NULL) THEN
              BEGIN
                 IF (position('SIT.' IN PRBDCODCOL) = 0) THEN
                    WWHERE = WWHERE||' AND '|| 'SIT.' ||PRBDCODCOL||' ';
                 else
                    WWHERE = WWHERE||' AND '||PRBDCODCOL||' ';
              END
        
           /*REFERÊNCIA*/
           IF (PRBDREF > 0 AND PRBDREF IS NOT NULL) THEN
              BEGIN
                 /*OBSERVAÇÃO: Cuidado ao mexer no filtro abaixo.
                               Ele faz básicamente a mesma coisa do CASE que busca a informação no corpo do SQL,
                               A diferença é que aqui ele transforma em WHERE
                 */
--                 WDATAMAX = RIGHT(PRBDREF,2) || '/' || WULTDIAMES || '/' || LEFT(PRBDREF,4);
--                 WDATAMIN = RIGHT(PRBDREF,2) || '/' || '01' || '/' || LEFT(PRBDREF,4);
                 WWHERE = WWHERE ||' AND ';
                 WWHERE = WWHERE ||' ( '||
                                   '  ( '||
                                   '   (PREPSIT.BDGRUPOSIT IN (4, 0)) '||
                                   '   AND '||
                                   '   ( '||
                                   '    ((SIT.BDDATAPARTOSIT IS NULL    ) AND (SIT.BDDATAINISIT   <= '''||prultdiames||''')) '||
                                   '    OR '||
                                   '    ((SIT.BDDATAPARTOSIT IS NOT NULL) AND (SIT.BDDATAPARTOSIT <= '''||prprimdiames||''')) '||
                                   '   ) '||
                                   '  ) '||
                                   '  OR '||
                                   '  ( '||
                                   '   (PREPSIT.BDGRUPOSIT NOT IN (4, 0)) '||
                                   '   AND '||
                                   '   ((SIT.BDDATAFIMSIT IS NOT NULL)) '||
                                   '  ) '||
                                   ' ) ';

                  WWHERE = WWHERE || ' AND ';
                  WWHERE = WWHERE || ' ((SIT.BDDATAINISIT <= '''||prultdiames||''') or (SIT.BDDATAFIMSIT <= '''||prultdiames||''')) ';

              END

           /*REFERENCIA ESTABILIDADE*/
           IF (PRBDREF > 0 AND PRBDREF IS NOT NULL) THEN
              BEGIN
                 /*OBSERVAÇÃO: Cuidado ao mexer no filtro abaixo.
                               Ele faz básicamente a mesma coisa do CASE que busca a informação no corpo do SQL,
                               A diferença é que aqui ele transforma em WHERE
                 */

--                 WDATAMIN = '';
--                 WDATAMIN = RIGHT(PRBDREF,2) || '/' || '01' || '/' || LEFT(PRBDREF,4);

                 wWHERE = WWHERE || ' AND '||
                                    ' ( '||
                                    '  ( '||
                                    '   (PREPSIT.BDGRUPOSIT IN (4, 0)) '||
                                    '   AND '||
                                    '   ( '||
                                    --'    ((SIT.BDDATAPARTOSIT IS NULL    ) AND (DATEADD(DAY, PREPESTAB.BDDIASETB - 1, SIT.BDDATAINISIT) >= '''||prprimdiames||''')) '||
                                    '    ((SIT.BDDATAPARTOSIT IS NULL    ) AND (DATEADD(DAY, PREPESTAB.BDDIASETB, SIT.BDDATAINISIT) >= '''||prprimdiames||''')) '||
                                    '    OR'||
                                    --'    ((SIT.BDDATAPARTOSIT IS NOT NULL) AND (DATEADD(DAY, PREPESTAB.BDDIASETB - 1, SIT.BDDATAPARTOSIT) >= '''||prprimdiames||''')) '||
                                    '    ((SIT.BDDATAPARTOSIT IS NOT NULL) AND (DATEADD(DAY, PREPESTAB.BDDIASETB, SIT.BDDATAPARTOSIT) >= '''||prprimdiames||''')) '||
                                    '   ) '||
                                    '  ) '||
                                    '  OR '||
                                    '  ( '||
                                    '   (PREPSIT.BDGRUPOSIT NOT IN (4, 0)) '||
                                    '   AND '||
                                    --'   ((SIT.BDDATAFIMSIT IS NOT NULL  ) AND (DATEADD(DAY, PREPESTAB.BDDIASETB - 1, SIT.BDDATAFIMSIT) >= '''||prprimdiames||''')) '||
                                    '   ((SIT.BDDATAFIMSIT IS NOT NULL  ) AND (DATEADD(DAY, PREPESTAB.BDDIASETB, SIT.BDDATAFIMSIT) >= '''||prprimdiames||''')) '||
                                    '  ) '||
                                    ' ) ';

              END

           /*|UNIÃO DAS VARIAVEIS DO SQL|*/
           WSQL = WSQL || WWHERE;
        
           WSQL = WSQL ||
                  ' UNION ALL '||
                  ' SELECT '||
                  ' SIT.BDCODEMP, '||
                  ' SIT.BDCODCOL, '||
                  ' NOM.BDNOMCOL, '||
                  ' COLVINC.BDCODSINTRAB, '||
                  ' SIT.BDDATAINICIO BDDATAINISIT, '||
                  ' SIT.BDDATAFIM BDDATAFIMSIT, '||
                  ' SIT.bdcodMOTESTAB, '||
                  ' TMOT.bddescricao, '||
                  ' SIT.BDDATAFIM BDDATAESTAB '||
                  ' from VRH_EMP_TESTABILIDADE SIT '||
                  ' left outer join VRH_BASE_TMOTESTAB_ESOCIAL TMOT on (TMOT.BDCODMOTESTAB = SIT.BDCODMOTESTAB) '||
                  ' join VRH_EMP_TCOLCON_CAD NOM on NOM.BDCODEMP = SIT.BDCODEMP and NOM.BDCODCOL = SIT.BDCODCOL '||
                  ' AND NOM.BDREFCOL = (SELECT MAX(BDREFCOL) FROM VRH_EMP_TCOLCON_CAD WHERE BDCODCOL = NOM.BDCODCOL AND BDCODEMP = NOM.BDCODEMP) '||
                  ' join VRH_EMP_TCOLCON_DOC COLD on COLD.BDCODEMP = SIT.BDCODEMP and COLD.BDCODCOL = SIT.BDCODCOL '||
                  ' join VW_VRH_EMP_TCOL_ADM COLADM on COLADM.BDCODEMP = SIT.BDCODEMP and COLADM.BDCODCOL = SIT.BDCODCOL '||
                  ' left join SP_VRHF_TCOL_VINC_REF(SIT.BDCODEMP, SIT.BDCODCOL, '|| PRBDREF ||') COLVINC on (COLVINC.BDCODEMP = SIT.BDCODEMP and COLVINC.BDCODCOL = SIT.BDCODCOL) ';

            WWHERE = '';
            /*EMPRESA*/
            IF (PRBDCODEMP <> '' AND PRBDCODEMP IS NOT NULL) THEN
             BEGIN
                 WWHERE = ' WHERE ';
                 IF (position('SIT.' IN PRBDCODEMP) = 0) THEN
                     WWHERE = WWHERE || REPLACE(PRBDCODEMP, 'BDCODEMP', 'SIT.BDCODEMP');
                 else
                     WWHERE = WWHERE || PRBDCODEMP;
             END

           /*COLABORADOR*/
           IF (PRBDCODCOL <> '' AND PRBDCODCOL IS NOT NULL) THEN
              BEGIN
                 IF (position('SIT.' IN PRBDCODCOL) = 0) THEN
                    WWHERE = WWHERE||' AND '||'SIT.' ||PRBDCODCOL||' ';
                 else
                    WWHERE = WWHERE||' AND '||PRBDCODCOL||' ';
              END

           /*REF*/
           IF (PRBDREF > 0 AND PRBDREF IS NOT NULL) THEN
              BEGIN
--                 WDATAMIN = '';
--                 WDATAMAX = '';
--                 WDATAMIN = RIGHT(PRBDREF,2) || '/' || '01'       || '/' || LEFT(PRBDREF,4);
--                 WDATAMAX = RIGHT(PRBDREF,2) || '/' || WULTDIAMES || '/' || LEFT(PRBDREF,4);


                 WWHERE = WWHERE || ' AND '|| '((SIT.BDDATAINICIO IS NOT NULL  ) AND SIT.BDDATAFIM >= '''||prprimdiames||''')';
                 WWHERE = WWHERE || ' AND '|| ' (SIT.BDDATAFIM IS NOT NULL AND SIT.BDDATAINICIO <= '''||prultdiames||''')';
              END


           /*|MONTA ORDERBY|*/
           WORDERBY = '';
            WORDERBY = 'ORDER BY BDCODEMP, BDCODCOL';
        
            WSQL = WSQL || WWHERE || ' AND SIT.BDCODMOTESTAB IN (1,2,3,4,5)) ' || WORDERBY;
        
           FOR
             EXECUTE STATEMENT WSQL INTO
             :BDCODEMP,
             :BDCODCOL,
             :BDNOMCOL,
             :BDCODSINTRAB,
             :BDDATAINISIT,
             :BDDATAFIMSIT,
             :BDCODSIT,
             :BDDESCSIT,
             :BDDATAESTAB
           DO
           BEGIN
             SUSPEND;
           END


        END

     IF (PROPCAOESTAB = 1) THEN      /*CIPA*/
        BEGIN
--           /*|BUSCA O ÚLTIMO DIA DO MÊS QUE FOI PASSADO NA REFERÊNCIA|*/
--           WSQL = '';
--           WSQL = 'SELECT * FROM ULTIMO_DIA_MES('||RIGHT(PRBDREF,2)||','||LEFT(PRBDREF,4)||')';
--           EXECUTE STATEMENT WSQL INTO :WULTDIAMES;

           /*|MONTA SQL|*/
           WSQL = '';
           WSQL = ' SELECT * FROM ('||
                  ' SELECT '||
                  ' CIPA.BDCODEMP, '||
                  ' CIPA.BDCODCOL, '||
                  ' COLCAD.BDNOMCOL, '||
                  ' COLVINC.BDCODSINTRAB,'||
                  ' CIPA.BDINICIPA, '||
                  ' CIPA.BDFIMCIPA, '||
                  --' DATEADD(DAY, PREPESTAB.BDDIASETB - 1, CIPA.BDFIMCIPA) AS BDDATAESTAB '||
                  ' DATEADD(DAY, PREPESTAB.BDDIASETB, CIPA.BDFIMCIPA) AS BDDATAESTAB '||
                  ' FROM VRH_EMP_TMANDCIPA CIPA '||
                  ' LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON (CIPA.BDCODEMP = COLCAD.BDCODEMP AND '||
                  '                                                   CIPA.BDCODCOL = COLCAD.BDCODCOL) '||
                  ' LEFT JOIN SP_VRHF_TCOL_VINC_REF(COLCAD.BDCODEMP, '||
                  '                                 COLCAD.BDCODCOL, '||
                  '                                 '|| PRBDREF ||') COLVINC ON(COLVINC.BDCODEMP = COLCAD.BDCODEMP AND '||
                  '                                                  COLVINC.BDCODCOL = COLCAD.BDCODCOL) '||
                  ' LEFT OUTER JOIN VRH_BASE_TPREPESTAB PREPESTAB ON (PREPESTAB.BDCODSINTRAB  = COLVINC.BDCODSINTRAB AND '||
                                                                    ' PREPESTAB.BDTIPOETB     = 1) ';

            /*
           0 - Somente os ativos
           1 - Todos
           2 - Somente os demitidos
           3 - Somente admitidos no mês
           4 - Somente demitidos no mês
           5 - Ativos sem demitidos no mês
           6 - Ativos sem demitidos com transferência no mês
           7 - Ativos sem afastados no mês inteiro
           8 - Afastados o mês inteiro
           */

           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 0) THEN  -- somente ativos
              wsql = wsql || 'join sp_somente_ativos('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 2) THEN  -- somente demitidos
              wsql = wsql || 'join sp_somente_demitidos('''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 3) THEN  -- admitidos no mês
              wsql = wsql || 'join sp_somente_admitidos_mes('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 4) THEN  -- demitidos no mês
              wsql = wsql || 'join sp_somente_demitidos_mes('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 5) THEN  -- ativos sem demitidos no mês
              wsql = wsql || 'join sp_ativos_sem_demitidos_mes('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 6) THEN  -- ativos sem demitidos no mês, com transferidos
              wsql = wsql || 'join sp_ati_sem_dem_com_transf('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 7) THEN  -- ativos sem afastados o mês inteiro
              wsql = wsql || 'join sp_ati_sem_afast_mes_int('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 8) THEN  -- afastados o mês inteiro
              wsql = wsql || 'join sp_afastados_mes_inteiro('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';


            -- Filtro por sindicato
           IF ((prcodsintrab IS NOT NULL) AND (prcodsintrab <> '')) THEN
              WSQL = WSQL || ' join VW_VRH_EMP_TCOL_VINC COL_VINC on (COLCAD.BDCODEMP = COL_VINC.BDCODEMP and COLCAD.BDCODCOL = COL_VINC.BDCODCOL and ' || prcodsintrab || ') ';
         
           -- Filtro por Centro de Custo
           IF ((PRCODTPCC IS NOT NULL) AND (PRCODTPCC <> '')) THEN
              WSQL = WSQL || ' JOIN VRHF_EMP_TPREPFN COLVINC_CC ON (COLCAD.BDCODEMP = COLVINC_CC.BDCODEMP AND COLCAD.BDCODCOL = COLVINC_CC.BDCODCOL AND ' || PRCODTPCC || ') ';
         
           -- Filtro por classe
           IF ((PRCODCLA IS NOT NULL) AND (PRCODCLA <> '')) THEN
              WSQL = WSQL || ' join VW_VRH_EMP_TCOLCON_VINC COLCON_VINC on (COLCAD.BDCODEMP = COLCON_VINC.BDCODEMP and COLCAD.BDCODCOL = COLCON_VINC.BDCODCOL and ' || PRCODCLA || ') ';
         
           -- Filtro por funcao
           IF ((PRCODFUN IS NOT NULL) AND (PRCODFUN <> '')) THEN
              WSQL = WSQL || ' join VW_VRH_EMP_TCOL_VINCDIA COL_VINCDIA on (COLCAD.BDCODEMP = COL_VINCDIA.BDCODEMP and COLCAD.BDCODCOL = COL_VINCDIA.BDCODCOL and ' || PRCODFUN || ') ';
        

           /*|MONTA WHERE|*/
           WWHERE = ' WHERE ';
        
           /*EMPRESA*/
           IF (PRBDCODEMP <> '' AND PRBDCODEMP IS NOT NULL) THEN
             BEGIN
               IF (position('CIPA.' IN PRBDCODEMP) = 0) THEN
                  WWHERE = WWHERE || REPLACE(PRBDCODEMP, 'BDCODEMP', 'CIPA.BDCODEMP');
               else
                  WWHERE = WWHERE || PRBDCODEMP;
             END
        
           /*COLABORADOR*/
           IF (PRBDCODCOL <> '' AND PRBDCODCOL IS NOT NULL) THEN
              BEGIN
                 IF (position('CIPA.' IN PRBDCODCOL) = 0) THEN
                    WWHERE = WWHERE||' AND '|| 'CIPA.' ||PRBDCODCOL||' ';
                 else
                    WWHERE = WWHERE||' AND '|| PRBDCODCOL||' ';
              END
        
           /*REFERÊNCIA*/
           IF (PRBDREF > 0 AND PRBDREF IS NOT NULL) THEN
              BEGIN
--                 WDATAMIN = '';
--                 WDATAMAX = '';
--                 WDATAMIN = RIGHT(PRBDREF,2) || '/' || '01'       || '/' || LEFT(PRBDREF,4);
--                 WDATAMAX = RIGHT(PRBDREF,2) || '/' || WULTDIAMES || '/' || LEFT(PRBDREF,4);


                 --WWHERE = WWHERE || ' AND '|| '((CIPA.bdfimcipa IS NOT NULL  ) AND (DATEADD(DAY, PREPESTAB.BDDIASETB - 1, CIPA.bdfimcipa) >= '''||prprimdiames||'''))';
                 WWHERE = WWHERE || ' AND '|| '((CIPA.bdfimcipa IS NOT NULL  ) AND (DATEADD(DAY, PREPESTAB.BDDIASETB, CIPA.bdfimcipa) >= '''||prprimdiames||'''))';
                 WWHERE = WWHERE || ' AND '|| ' (CIPA.BDFIMCIPA IS NOT NULL AND CIPA.BDINICIPA <= '''||prultdiames||''')';
              END
        
           /*|UNIÃO DAS VARIAVEIS DO SQL|*/
           WSQL = WSQL || WWHERE;

           /*|ESTABILIDADE LANÇADA NO LANÇAMENTO DE PERÍODOS DE ESTABILIDADE|*/
           WSQL = WSQL ||
                  ' UNION ALL '||
                  ' SELECT '||
                  ' CIPA.BDCODEMP, '||
                  ' CIPA.BDCODCOL, '||
                  ' NOM.BDNOMCOL, '||
                  ' COLVINC.BDCODSINTRAB, '||
                  ' CIPA.BDDATAINICIO BDINICIPA, '||
                  ' CIPA.BDDATAFIM BDFIMCIPA, '||
                  ' CIPA.BDDATAFIM BDDATAESTAB '||
                  ' FROM VRH_EMP_TESTABILIDADE CIPA '||
                  ' LEFT OUTER JOIN VRH_BASE_TMOTESTAB_ESOCIAL TMOT ON (TMOT.BDCODMOTESTAB = CIPA.BDCODMOTESTAB) '||
                  ' JOIN VRH_EMP_TCOLCON_CAD NOM ON NOM.BDCODEMP = CIPA.BDCODEMP AND NOM.BDCODCOL = CIPA.BDCODCOL AND NOM.BDREFCOL = (SELECT MAX(BDREFCOL) FROM VRH_EMP_TCOLCON_CAD WHERE BDCODCOL = NOM.BDCODCOL AND BDCODEMP = NOM.BDCODEMP)'||
                  ' JOIN VRH_EMP_TCOLCON_DOC COLD ON COLD.BDCODEMP = CIPA.BDCODEMP AND COLD.BDCODCOL = CIPA.BDCODCOL '||
                  ' JOIN VW_VRH_EMP_TCOL_ADM COLADM ON COLADM.BDCODEMP = CIPA.BDCODEMP AND COLADM.BDCODCOL = CIPA.BDCODCOL '||
                  ' LEFT JOIN SP_VRHF_TCOL_VINC_REF(CIPA.BDCODEMP, CIPA.BDCODCOL, '|| PRBDREF ||') COLVINC '||
                  ' ON (COLVINC.BDCODEMP = CIPA.BDCODEMP AND COLVINC.BDCODCOL = CIPA.BDCODCOL) ';

            WWHERE = '';
            /*EMPRESA*/
            IF (PRBDCODEMP <> '' AND PRBDCODEMP IS NOT NULL) THEN
             BEGIN
                 WWHERE = ' WHERE ';
                 IF (position('CIPA.' IN PRBDCODEMP) = 0) THEN
                    WWHERE = WWHERE || REPLACE(PRBDCODEMP, 'BDCODEMP', 'CIPA.BDCODEMP');
                 else
                    WWHERE = WWHERE || PRBDCODEMP;
             END

           /*COLABORADOR*/
           IF (PRBDCODCOL <> '' AND PRBDCODCOL IS NOT NULL) THEN
              BEGIN
                 IF (position('CIPA.' IN PRBDCODCOL) = 0) THEN
                    WWHERE = WWHERE||' AND '|| 'CIPA.' || PRBDCODCOL||' ';
                 else
                    WWHERE = WWHERE||' AND '|| PRBDCODCOL||' ';
              END

           /*REF*/
           IF (PRBDREF > 0 AND PRBDREF IS NOT NULL) THEN
              BEGIN
--                 WDATAMIN = '';
--                 WDATAMAX = '';
--                 WDATAMIN = RIGHT(PRBDREF,2) || '/' || '01'       || '/' || LEFT(PRBDREF,4);
--                 WDATAMAX = RIGHT(PRBDREF,2) || '/' || WULTDIAMES || '/' || LEFT(PRBDREF,4);


                 WWHERE = WWHERE || ' AND '|| '((CIPA.BDDATAINICIO IS NOT NULL  ) AND CIPA.BDDATAFIM >= '''||prprimdiames||''')';
                 WWHERE = WWHERE || ' AND '|| ' (CIPA.BDDATAFIM IS NOT NULL AND CIPA.BDDATAINICIO <= '''||prultdiames||''')';
              END


           /*|MONTA ORDERBY|*/
           WORDERBY = '';
            WORDERBY = 'ORDER BY BDCODEMP, BDCODCOL';
        
            WSQL = WSQL || WWHERE || ' AND CIPA.BDCODMOTESTAB IN (7,8,9)) ' || WORDERBY;
        
           FOR
             EXECUTE STATEMENT WSQL INTO
             :BDCODEMP,
             :BDCODCOL,
             :BDNOMCOL,
             :BDCODSINTRAB,
             :BDINICIPA,
             :BDFIMCIPA,
             :BDDATAESTAB
           DO
           BEGIN
             SUSPEND;
           END
        END


     IF (PROPCAOESTAB = 2) THEN         /*FERIAS*/
        BEGIN
--           /*|BUSCA O ÚLTIMO DIA DO MÊS QUE FOI PASSADO NA REFERÊNCIA|*/
--           WSQL = '';
--           WSQL = 'SELECT * FROM ULTIMO_DIA_MES('||RIGHT(PRBDREF,2)||','||LEFT(PRBDREF,4)||')';
--           EXECUTE STATEMENT WSQL INTO :WULTDIAMES;

           WWHERE = '';

           /*EMPRESA*/
           IF (PRBDCODEMP <> '' AND PRBDCODEMP IS NOT NULL) THEN
             BEGIN
                 WWHERE = ' WHERE ';
                 IF (position('X.' IN PRBDCODEMP) = 0) THEN
                    WWHERE = WWHERE || REPLACE(PRBDCODEMP, 'BDCODEMP', 'X.BDCODEMP');
                 else
                    WWHERE = WWHERE || PRBDCODEMP;
             END
        
           /*COLABORADOR*/
           IF (PRBDCODCOL <> '' AND PRBDCODCOL IS NOT NULL) THEN
              BEGIN
                 IF (position('X.' IN PRBDCODCOL) = 0) THEN
                    WWHERE = WWHERE||' AND '|| 'X.' || PRBDCODCOL||' ';
                 ELSE
                    WWHERE = WWHERE||' AND '|| PRBDCODCOL||' ';
              END

           WSQL = '';
           WSQL = ' SELECT '||
                  ' FERIAS.BDCODEMP, '||
                  ' FERIAS.BDCODCOL, '||
                  ' COLCAD.BDNOMCOL, '||
                  ' FERIAS.BDINIPERAQUISFE, '||
                  ' FERIAS.BDFIMPERAQUISFE, '||
                  ' FERIAS.BDINIPERGOZOFE, '||
                  ' FERIAS.BDFIMPERGOZOFE, '||
                  --' DATEADD(DAY, PREPESTAB.BDDIASETB, FERIAS.BDFIMPERGOZOFE) AS BDDATAESTAB '||
                  'case when (PREPESTAB.BDDIASFERETB = ''TRUE'') then dateadd(day, FERIAS.BDQTDGOZOFE, FERIAS.BDFIMPERGOZOFE) ' || -- Solicitação #202212 - Jackson Nunes - 02/05/2024
                  ' else dateadd(day, PREPESTAB.BDDIASETB, FERIAS.BDFIMPERGOZOFE) end BDDATAESTAB ' ||
                  ' FROM (SELECT '||
                  '       X.BDCODEMP, '||
                  '       X.BDCODCOL, '||
                  '       MAX(X.BDINIPERGOZOFE) BDINIPERGOZOFE '||
                  '       FROM VRH_EMP_TFERIAS X '||
                  WWHERE||
                  '        '||
                  '       GROUP BY X.BDCODEMP, X.BDCODCOL) FER '||
                  ' JOIN VRH_EMP_TFERIAS FERIAS ON (FER.BDCODEMP = FERIAS.BDCODEMP AND '||
                  '                                 FER.BDCODCOL = FERIAS.BDCODCOL AND '||
                  '                                 FERIAS.BDINIPERGOZOFE = FER.BDINIPERGOZOFE) '||
                  ' LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON (COLCAD.BDCODEMP = FERIAS.BDCODEMP AND '||
                  '                                                   COLCAD.BDCODCOL = FERIAS.BDCODCOL) '||
                  ' LEFT JOIN SP_VRHF_TCOL_VINC_REF(COLCAD.BDCODEMP, '||
                  '                                 COLCAD.BDCODCOL, '||
                  '                                 201808) COLVINC ON (COLVINC.BDCODEMP = COLCAD.BDCODEMP AND '||
                  '                                                     COLVINC.BDCODCOL = COLCAD.BDCODCOL) '||
                  ' LEFT OUTER JOIN VRH_BASE_TPREPESTAB PREPESTAB ON (PREPESTAB.BDCODSINTRAB = COLVINC.BDCODSINTRAB AND '||
                  '                                                   PREPESTAB.BDTIPOETB    = 2) ';

             /*
           0 - Somente os ativos
           1 - Todos
           2 - Somente os demitidos
           3 - Somente admitidos no mês
           4 - Somente demitidos no mês
           5 - Ativos sem demitidos no mês
           6 - Ativos sem demitidos com transferência no mês
           7 - Ativos sem afastados no mês inteiro
           8 - Afastados o mês inteiro
           */

           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 0) THEN  -- somente ativos
              wsql = wsql || 'join sp_somente_ativos('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 2) THEN  -- somente demitidos
              wsql = wsql || 'join sp_somente_demitidos('''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 3) THEN  -- admitidos no mês
              wsql = wsql || 'join sp_somente_admitidos_mes('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 4) THEN  -- demitidos no mês
              wsql = wsql || 'join sp_somente_demitidos_mes('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 5) THEN  -- ativos sem demitidos no mês
              wsql = wsql || 'join sp_ativos_sem_demitidos_mes('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 6) THEN  -- ativos sem demitidos no mês, com transferidos
              wsql = wsql || 'join sp_ati_sem_dem_com_transf('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 7) THEN  -- ativos sem afastados o mês inteiro
              wsql = wsql || 'join sp_ati_sem_afast_mes_int('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
           ELSE
           IF (PRTIPOSIT IS NOT NULL AND PRTIPOSIT = 8) THEN  -- afastados o mês inteiro
              wsql = wsql || 'join sp_afastados_mes_inteiro('''||prprimdiames||''','''||prultdiames||''') filtro on (filtro.bdcodemp = COLCAD.bdcodemp and filtro.bdcodcol = COLCAD.bdcodcol) ';
        
            -- Filtro por sindicato
           IF ((prcodsintrab IS NOT NULL) AND (prcodsintrab <> '')) THEN
              WSQL = WSQL || ' join VW_VRH_EMP_TCOL_VINC COL_VINC on (COLCAD.BDCODEMP = COL_VINC.BDCODEMP and COLCAD.BDCODCOL = COL_VINC.BDCODCOL and ' || prcodsintrab || ') ';
         
           -- Filtro por Centro de Custo
           IF ((PRCODTPCC IS NOT NULL) AND (PRCODTPCC <> '')) THEN
              WSQL = WSQL || ' JOIN VRHF_EMP_TPREPFN COLVINC_CC ON (COLCAD.BDCODEMP = COLVINC_CC.BDCODEMP AND COLCAD.BDCODCOL = COLVINC_CC.BDCODCOL AND ' || PRCODTPCC || ') ';
         
           -- Filtro por classe
           IF ((PRCODCLA IS NOT NULL) AND (PRCODCLA <> '')) THEN
              WSQL = WSQL || ' join VW_VRH_EMP_TCOLCON_VINC COLCON_VINC on (COLCAD.BDCODEMP = COLCON_VINC.BDCODEMP and COLCAD.BDCODCOL = COLCON_VINC.BDCODCOL and ' || PRCODCLA || ') ';
         
           -- Filtro por funcao
           IF ((PRCODFUN IS NOT NULL) AND (PRCODFUN <> '')) THEN
              WSQL = WSQL || ' join VW_VRH_EMP_TCOL_VINCDIA COL_VINCDIA on (COLCAD.BDCODEMP = COL_VINCDIA.BDCODEMP and COLCAD.BDCODCOL = COL_VINCDIA.BDCODCOL and ' || PRCODFUN || ') ';

            /*REFERÊNCIA*/
            /*|MONTA WHERE|*/
           WWHERE = ' WHERE ';
        
            IF (PRBDREF > 0 AND PRBDREF IS NOT NULL) THEN
               BEGIN
                  --WDATAMAX = RIGHT(PRBDREF,2) || '/' || WULTDIAMES || '/' || LEFT(PRBDREF,4);
                  WWHERE = WWHERE || ' (FERIAS.BDFIMPERGOZOFE IS NOT NULL AND FERIAS.BDFIMPERGOZOFE IS NOT NULL AND FERIAS.BDFIMPERGOZOFE <= '''||prultdiames||''')';
               END

           /*REFERENCIA ESTABILIDADE*/
           IF (PRBDREF > 0 AND PRBDREF IS NOT NULL) THEN
              BEGIN
--                 WDATAMIN = '';
--                 WDATAMIN = RIGHT(PRBDREF,2) || '/' || '01' || '/' || LEFT(PRBDREF,4);

--                 WWHERE = WWHERE || ' AND '  || ' ((FERIAS.BDFIMPERGOZOFE IS NOT NULL) AND (DATEADD(DAY, PREPESTAB.BDDIASETB - 1, FERIAS.BDFIMPERGOZOFE) >= '||prprimdiames||')) ';
                 WWHERE = WWHERE ||  ' AND '  || ' ((FERIAS.BDFIMPERGOZOFE IS NOT NULL) AND (case when (upper(PREPESTAB.BDDIASFERETB) = ''TRUE'') then dateadd(day, FERIAS.BDQTDGOZOFE, FERIAS.BDFIMPERGOZOFE) ' ||
                                     'else dateadd(day, PREPESTAB.BDDIASETB, FERIAS.BDFIMPERGOZOFE) end) >= '''||prprimdiames||''') ';
              END
           /*|MONTA ORDERBY|*/
           WORDERBY = '';
           WORDERBY = ' ORDER BY FERIAS.BDCODEMP, FERIAS.BDCODCOL ';

           /*|UNIÃO DAS VARIAVEIS DO SQL|*/
           WSQL = WSQL || WWHERE || WORDERBY;

           FOR
             EXECUTE STATEMENT WSQL INTO
             BDCODEMP,
             BDCODCOL,
             BDNOMCOL,
             BDINIPERAQUISFE,
             BDFIMPERAQUISFE,
             BDINIPERGOZOFE,
             BDFIMPERGOZOFE,
             BDDATAESTAB
           DO
           BEGIN
             SUSPEND;
           END

        END
END^

CREATE OR ALTER procedure SP_CARREGAR_TMP_TOBSERVACAO (
    PRINICIALIZANDOSERVIDOR DM_BOOLEAN)
as
declare variable WCODOBS integer;
begin

  IF (:PRINICIALIZANDOSERVIDOR = 'TRUE') THEN
    DELETE FROM TMP_VEF_BASE_TOBSERVACAO WHERE BDSESSAO IS NOT NULL;
  SELECT FIRST 1 BDCODOBS FROM TMP_VEF_BASE_TOBSERVACAO INTO :wCodObs;

  IF ((:wCodObs IS NULL) OR (:wCodObs = 0)) THEN
    BEGIN
      /*Carregando a tabela temporária da observação*/
      INSERT INTO TMP_VEF_BASE_TOBSERVACAO(BDSESSAO, BDCODOBS, BDEDITCHAVE, BDCODEXP, BDNOMEOBS, BDTIPOOBS, BDCODEMP, BDCODTIPO)
      SELECT 0 BDSESSAO, O.BDCODOBS, O.BDCODOBS, O.BDCODEXP, O.BDNOMEOBS, O.BDTIPOOBS, O.BDCODEMP, O.BDCODTIPO
      FROM VEF_BASE_TOBSERVACAO O;
    END
end^

create or alter procedure SP_CARREGAR_TMP_TCADINFCOM (
    PRINICIALIZANDOSERVIDOR DM_BOOLEAN)
as
declare variable WBDORDEMINFCOM integer;
declare variable WNAOCARREGARTMP DM_BOOLEAN;
BEGIN
/*
    -Carregar as temporárias, na TPARAMETRO o parâmetro NAOCARREGARTEMPORARIAS afeta como rotina irá funcionar
    tanto o BDVALORSTR, quanto o BDVALORINT alteram o comportamento da rotina de suas formas

    BDVALORINT (Usado na rotina do uServidorMetodos):
    -Sem parâmetro (Padrão) (0 ou null):
       -No expediente: só carrega diferenças
       -Fora do expediente: carrega tudo
       -Reinício manual: carrega tudo
    -Com parâmetro
       -Se 1 (só diferenças)
          -No expediente: só carrega diferenças
          -Fora do expediente: só carrega diferenças
          -Reinício manual: só carrega diferenças
       -Se 2 (tudo)
          -No expediente: carrega tudo
          -Fora do expediente: carrega tudo
          -Reinício manual: carrega tudo
       -Se 3 (tudo no fim de semana)
         -No expediente: só carrega diferenças
         -Fora do expediente: só carrega diferenças na maioria dos dias, no sábado ele carrega tudo (Na MG é na sexta)
         -Reinício manual: só carrega diferenças na maioria dos dias, no sábado ele carrega tudo (Na MG é na sexta)
       Independente da opção, ele só carrega tudo uma vez a cada 23 horas

    BDVALORSTR (Usado pelas SPs, Exemplo: SP_CARREGAR_TMP_TCADPRO):
    NÃO MEXER NUNCA, NUNQUINHA, O FALSE NÃO FUNCIONA DIREITO, TEM ROTINA QUE CARREGA A MESMA COISA DUAS VEZES
    SEMPRE QUE MEXER AQUI FALAR COM O FISCAL
    -TRUE (Padrão, deve estar sempre com essa opção nos clientes):
      Carrega o que ainda não tem na tabela
    -FALSE:
      Carrega tudo, mesmo que já tenha na tabela
      
    No mundo ideal, esses parâmetros seriam unificados. 
    Nas Sps, deveria ter um parametro para dizer se está carregando tudo ou só as diferenças
    Quando carregar tudo, deveria executar como se o NAOCARREGARTEMPORARIAS estivesse false; e
    Quando carrega só as diferenças deveria executar como se o NAOCARREGARTEMPORARIAS estivesse true.
    Na teoria, mas sinceramente, passar como true sempre é bem melhor, não é lento suficiente pra ser um problema,
    além disso o FALSE é bugado. SE MEXER NISSO FALAR COM O FISCAL.
*/

  wNaoCarregarTMP = 'FALSE';
  select first 1 bdVALORSTR from TPARAMETRO where bdPARAM='NAOCARREGARTEMPORARIAS' into :wNaoCarregarTMP;        

  SELECT FIRST 1 BDORDEMINFCOM FROM TMP_VEF_BASE_TCADINFCOM INTO :wBDORDEMINFCOM;

  IF ((:wBDORDEMINFCOM IS NULL) OR (:wBDORDEMINFCOM = 0) or ((:PRINICIALIZANDOSERVIDOR = 'TRUE') and (:wNaoCarregarTMP = 'TRUE'))) THEN
    BEGIN
      if (:wNaoCarregarTMP = 'TRUE') then
        begin
      INSERT INTO TMP_VEF_BASE_TCADINFCOM(BDSESSAO, BDORDEMINFCOM, BDEDITCHAVE, BDCODINFCOM,
                                          BDDESCINFCOM, BDCODEMP, BDCODTIPO, BDDESCINFCOMHASH)
      SELECT 0 BDSESSAO, I.BDORDEMINFCOM, I.BDORDEMINFCOM, I.BDCODINFCOM, I.BDDESCINFCOM,
             I.BDCODEMP, I.BDCODTIPO, I.BDDESCINFCOMHASH
          FROM VEF_BASE_TCADINFCOM I
          LEFT OUTER JOIN TMP_VEF_BASE_TCADINFCOM TMP ON (TMP.BDSESSAO = 0 AND TMP.BDORDEMINFCOM = I.BDORDEMINFCOM)
          WHERE TMP.BDSESSAO IS NULL;
        END
      else
        BEGIN
          INSERT INTO TMP_VEF_BASE_TCADINFCOM(BDSESSAO, BDORDEMINFCOM, BDEDITCHAVE, BDCODINFCOM,
                                              BDDESCINFCOM, BDCODEMP, BDCODTIPO, BDDESCINFCOMHASH)
          SELECT 0 BDSESSAO, I.BDORDEMINFCOM, I.BDORDEMINFCOM, I.BDCODINFCOM, I.BDDESCINFCOM,
                 I.BDCODEMP, I.BDCODTIPO, I.BDDESCINFCOMHASH
      FROM VEF_BASE_TCADINFCOM I;
    END
    END
END^

CREATE OR ALTER PROCEDURE SP_LOAD_TMP_TABLES (
    PRINICIALIZANDOSERVIDOR DM_BOOLEAN)
AS
BEGIN
  PRINICIALIZANDOSERVIDOR = UPPER(:PRINICIALIZANDOSERVIDOR);

  /*Limpando tabelas TEMP*/
  EXECUTE PROCEDURE CLEAR_ALL_TEMPORARY_TABLE;

  /*Carregando a tabela temporária do participante*/
  EXECUTE PROCEDURE SP_CARREGAR_TMP_TTERCEIRO(:PRINICIALIZANDOSERVIDOR);

  /*Carregando as tabelas temporárias do produto*/
  EXECUTE PROCEDURE SP_CARREGAR_TMP_TCADPRO(:PRINICIALIZANDOSERVIDOR);

  IF (:PRINICIALIZANDOSERVIDOR = 'TRUE') THEN
    DELETE FROM TMP_VEF_BASE_TOBSERVACAO WHERE BDSESSAO IS NOT NULL;  
  
  /*Carregando a tabela temporária da observação*/
  EXECUTE PROCEDURE SP_CARREGAR_TMP_TOBSERVACAO(:PRINICIALIZANDOSERVIDOR);

  /*Carregando a tabela temporária da informação complementar*/
  EXECUTE PROCEDURE SP_CARREGAR_TMP_TCADINFCOM(:PRINICIALIZANDOSERVIDOR);
END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_TOBSERVACAO (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER,
    PRLANCAMENTOMANUAL DM_BOOLEAN)
AS
DECLARE VARIABLE WCODOBS INTEGER;
DECLARE VARIABLE WEDITCHAVE INTEGER;
DECLARE VARIABLE WCODEXP VARCHAR(6);
DECLARE VARIABLE WNOMEOBS VARCHAR(100);
DECLARE VARIABLE WTIPOOBS INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODTIPO INTEGER;
DECLARE VARIABLE WATUOBS DM_BOOLEAN;
BEGIN

  --EXECUTE PROCEDURE SP_CARREGAR_TMP_TOBSERVACAO('FALSE');

  IF (UPPER(:PRLANCAMENTOMANUAL) = 'TRUE') THEN
    BEGIN
      SELECT FIRST 1 O.BDCODOBS, O.BDEDITCHAVE, O.BDCODEXP,
                     O.BDNOMEOBS, O.BDTIPOOBS, O.BDCODEMP,
                     O.BDCODTIPO
      FROM TMP_VEF_BASE_TOBSERVACAO_TEMP O
      WHERE BDSESSAO = 0
      INTO :wCodObs,
           :wEditChave,
           :wCodExp,
           :wNomeObs,
           :wTipoObs,
           :wCodEmp,
           :wCodTipo;

      IF ((:wCodObs IS NOT NULL) AND (:wCodObs > 0)) THEN
        BEGIN
          UPDATE OR INSERT INTO TMP_VEF_BASE_TOBSERVACAO(BDSESSAO, BDCODOBS, BDEDITCHAVE, BDCODEXP, BDNOMEOBS, BDTIPOOBS, BDCODEMP, BDCODTIPO)
          VALUES(0, :wCodObs, :wCodObs, :wCodExp, :wNomeObs, :wTipoObs, :wCodEmp, :wCodTipo) MATCHING(BDEDITCHAVE);
        END

      DELETE FROM TMP_VEF_BASE_TOBSERVACAO_TEMP WHERE BDSESSAO = 0;

      EXIT;
    END

  SELECT SP.BDATUOBS FROM SP_GET_ACOES_INCONSISTENCIA(:PRCODEMP, :PRREF) SP INTO :wAtuObs;

  FOR SELECT COALESCE(O.BDCODOBS, 0),
             COALESCE(O.BDEDITCHAVE, 0),
             REPLACE(COALESCE(O.BDCODEXP, ''), '"', ''),
             REPLACE(COALESCE(O.BDNOMEOBS, ''), '"', ''),
             COALESCE(O.BDTIPOOBS, 0),
             O.BDCODEMP,
             O.BDCODTIPO
      FROM TMP_VEF_BASE_TOBSERVACAO_TEMP O
      WHERE O.BDSESSAO = :PRSESSAO
      AND ((O.BDEDITCHAVE IS NULL) OR (O.BDEDITCHAVE = 0))
      INTO :wCodObs,
           :wEditChave,
           :wCodExp,
           :wNomeObs,
           :wTipoObs,
           :wCodEmp,
           :wCodTipo
  DO
    BEGIN
      /********************************Vínculo*********************************/
        SELECT FIRST 1 O.BDEDITCHAVE
        FROM TMP_VEF_BASE_TOBSERVACAO O
        WHERE ((O.BDCODEXP IS NOT NULL) AND (O.BDCODEXP <> ''))
        AND O.BDCODEMP = :wCodEmp
        AND O.BDCODEXP = :wCodExp
        INTO :wEditChave;

        IF ((:wEditChave IS NULL) OR (:wEditChave = 0)) THEN
          BEGIN
            SELECT FIRST 1 O.BDEDITCHAVE
            FROM TMP_VEF_BASE_TOBSERVACAO O
            WHERE ((O.BDCODEXP IS NOT NULL) AND (O.BDCODEXP <> ''))
            AND O.BDCODEXP = :wCodExp
            AND ((O.BDCODEMP IS NULL) OR (O.BDCODEMP = 0))
            INTO :wEditChave;
          END
        /*103 - Sped Fiscal, 104 - Sped Contribuições
          Não vincula por descrição - Sol: 22888*/
        IF (:wCodTipo NOT IN(103, 104)) THEN
          BEGIN
            IF ((:wEditChave IS NULL) OR (:wEditChave = 0)) THEN
              BEGIN
                SELECT FIRST 1 O.BDEDITCHAVE
                FROM TMP_VEF_BASE_TOBSERVACAO O
                WHERE O.BDCODEMP = :wCodEmp
                AND O.BDNOMEOBS = :wNomeObs
                INTO :wEditChave;
              END
          END
      /************************************************************************/

      /*Existe na base de dados*/
      IF ((:wEditChave IS NOT NULL) AND (:wEditChave > 0)) THEN
        BEGIN
          /*Tem ação de inconsistencia para atualizar a observação*/
          IF (:wAtuObs = 'TRUE') THEN
            BEGIN
              UPDATE TMP_VEF_BASE_TOBSERVACAO TMP
              SET TMP.BDSESSAO = :PRSESSAO,
                  TMP.BDCODEXP = :wCodExp,
                  TMP.BDNOMEOBS = :wNomeObs,
                  TMP.BDTIPOOBS = :wTipoObs,
                  TMP.BDCODEMP =  :wCodEmp,
                  TMP.BDCODTIPO = :wCodTipo,
                  TMP.BDEDITCHAVE = :wEditChave
              WHERE TMP.BDEDITCHAVE = :wEditChave;
            END
          ELSE
            BEGIN
              UPDATE TMP_VEF_BASE_TOBSERVACAO TMP
              SET TMP.BDSESSAO = :PRSESSAO
              WHERE TMP.BDEDITCHAVE = :wEditChave;
            END

          /*Quando não tem ação de inconsistencia para atualizar a observação, é tratado na hora de gravar a observação*/

          UPDATE TMP_VEF_BASE_TOBSERVACAO_TEMP T SET T.BDEDITCHAVE = :wEditChave WHERE T.BDSESSAO = :PRSESSAO AND T.BDCODOBS = :wCodObs;
        END
      ELSE /*Observação nova*/
        BEGIN
          INSERT INTO TMP_VEF_BASE_TOBSERVACAO(BDSESSAO, BDCODOBS, BDEDITCHAVE, BDCODEXP, BDNOMEOBS, BDTIPOOBS, BDCODEMP, BDCODTIPO, BDIMPORTANDO)
          VALUES (:PRSESSAO, :wCodObs, 0, :wCodExp, :wNomeObs, :wTipoObs, :wCodEmp, :wCodTipo, 'TRUE');
        END
    END

END
^

CREATE OR ALTER PROCEDURE SP_GERACODIGOS_OBSERVACAO (
    PRSESSAO INTEGER,
    PRULTCHAVE INTEGER)
AS
DECLARE VARIABLE WCODOBS INTEGER;
BEGIN

  FOR SELECT O.BDCODOBS
      FROM TMP_VEF_BASE_TOBSERVACAO O
      WHERE O.BDSESSAO = :PRSESSAO
      AND O.BDEDITCHAVE = 0
      INTO :wCodObs
  DO
    BEGIN
      UPDATE TMP_VEF_BASE_TOBSERVACAO O SET O.BDEDITCHAVE = :PRULTCHAVE WHERE O.BDSESSAO = :PRSESSAO AND O.BDCODOBS = :wCodObs AND O.BDIMPORTANDO = 'TRUE';

      PRULTCHAVE = PRULTCHAVE - 1;
    END

  UPDATE TMP_VEF_BASE_TOBSERVACAO_TEMP T SET T.BDEDITCHAVE = (SELECT FIRST 1 O.BDEDITCHAVE FROM TMP_VEF_BASE_TOBSERVACAO O WHERE O.BDSESSAO = T.BDSESSAO AND O.BDCODOBS = T.BDCODOBS AND O.BDIMPORTANDO = 'TRUE')
  WHERE T.BDSESSAO = :PRSESSAO
  AND ((T.BDEDITCHAVE IS NULL) OR (T.BDEDITCHAVE = 0));

END^

CREATE OR ALTER PROCEDURE SP_INSERT_OR_UPDATE_TOBSERVACAO (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS
DECLARE VARIABLE WATUOBS DM_BOOLEAN;
DECLARE VARIABLE WEDITCHAVE INTEGER;
DECLARE VARIABLE WCODEXP VARCHAR(6);
DECLARE VARIABLE WNOMEOBS VARCHAR(100);
DECLARE VARIABLE WTIPOOBS INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODTIPO INTEGER;
BEGIN

  SELECT SP.BDATUOBS FROM SP_GET_ACOES_INCONSISTENCIA(:PRCODEMP, :PRREF) SP INTO :wAtuObs;

  IF (:wAtuObs = 'FALSE') THEN
    BEGIN
      INSERT INTO VEF_BASE_TOBSERVACAO(BDCODOBS, BDCODEXP, BDNOMEOBS, BDTIPOOBS, BDCODEMP, BDCODTIPO)
      SELECT O.BDEDITCHAVE, O.BDCODEXP, O.BDNOMEOBS, O.BDTIPOOBS, O.BDCODEMP, O.BDCODTIPO
      FROM TMP_VEF_BASE_TOBSERVACAO_TEMP O
      LEFT OUTER JOIN VEF_BASE_TOBSERVACAO T ON(T.BDCODOBS = O.BDEDITCHAVE)
      WHERE O.BDSESSAO = :PRSESSAO
      AND T.BDCODOBS IS NULL;
    END
  ELSE
    BEGIN
      /*Tem ação de inconsistência para atualizar a observação*/
      FOR SELECT O.BDEDITCHAVE, O.BDCODEXP, O.BDNOMEOBS,
                 O.BDTIPOOBS, O.BDCODEMP, O.BDCODTIPO
          FROM TMP_VEF_BASE_TOBSERVACAO_TEMP O
          WHERE O.BDSESSAO = :PRSESSAO
          INTO :wEditChave, :wCodExp, :wNomeObs, :wTipoObs,
               :wCodEmp, :wCodTipo
      DO
        BEGIN
          UPDATE OR INSERT INTO VEF_BASE_TOBSERVACAO(BDCODOBS, BDCODEXP, BDNOMEOBS, BDTIPOOBS, BDCODEMP, BDCODTIPO)
          VALUES(:wEditChave, :wCodExp, :wNomeObs, :wTipoObs, :wCodEmp, :wCodTipo) MATCHING(BDCODOBS);
        END
    END

END^

CREATE OR ALTER PROCEDURE SP_VINCULAR_OBSERVACAO (
    PRSESSAO INTEGER,
    PRID_TERMINAL INTEGER)
as
declare variable WSQL varchar(500);
declare variable WTABLE varchar(50);
declare variable WSESSAOATU integer;
declare variable wCampo varchar(50);
BEGIN

  FOR SELECT TRIM(UPPER(T.RDB$RELATION_NAME)) BDTABLE
      FROM RDB$RELATION_FIELDS T
      WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
      AND RDB$FIELD_NAME = 'BDCODOBS'
      AND TRIM(UPPER(T.RDB$RELATION_NAME)) <> 'TMP_VEF_BASE_TOBSERVACAO_TEMP'
      INTO :wTable
  DO
    BEGIN

      SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = :wTable INTO :wSessaoAtu;
      IF ((:wSessaoAtu IS NOT NULL) AND (:wSessaoAtu > 0)) THEN
        BEGIN
          SELECT TRIM(UPPER(RDB$FIELD_NAME)) BDCAMPO FROM RDB$RELATION_FIELDS T WHERE RDB$RELATION_NAME = :wTable AND RDB$FIELD_NAME = 'BDALTCODOBS' INTO :wCampo;

          if (:wCampo is not null) then
            begin
          wSql =          'UPDATE '||:wTable||' T ';
          wSql = :wSql || 'SET T.BDALTCODOBS = (';
          wSql = :wSql ||                      'SELECT FIRST 1 O.BDEDITCHAVE ';
          wSql = :wSql ||                      'FROM TMP_VEF_BASE_TOBSERVACAO_TEMP O ';
          wSql = :wSql ||                      'WHERE O.BDSESSAO = '||:PRSESSAO;
          wSql = :wSql ||                      'AND O.BDCODOBS = T.BDCODOBS';
          wSql = :wSql ||                     ')';
          wSql = :wSql || 'WHERE T.BDSESSAO = '||:wSessaoAtu||' ';
          wSql = :wSql || 'AND ((T.BDALTCODOBS IS NULL) OR (T.BDALTCODOBS = 0))';
          EXECUTE STATEMENT :wSql;

          wSql = 'UPDATE '||:wTable||' T SET T.BDCODOBS = T.BDALTCODOBS WHERE T.BDSESSAO = '||:wSessaoAtu||' AND ((T.BDALTCODOBS IS NOT NULL) AND (T.BDALTCODOBS > 0))';
          EXECUTE STATEMENT :wSql;
            end
          else
            begin
              EXECUTE PROCEDURE LANCA_EXCEPTION('Faltou criar o campo BDALTCODOBS na tabela :'||:wTable, null, null);
            end

         wCampo = null;
         wSessaoAtu = null;

        END
    END



  WHEN ANY DO
    BEGIN
      IN AUTONOMOUS TRANSACTION DO
        EXECUTE PROCEDURE LANCA_EXCEPTION('SP_VINCULAR_OBSERVACAO', SQLCODE, GDSCODE);
      EXCEPTION;
    END
END^

create or alter procedure SP_ATUALIZAR_TMP_TCADINFCOM (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer,
    PRLANCAMENTOMANUAL DM_BOOLEAN)
as
declare variable WDESCINFCOMHASH bigint;
declare variable WORDEMINFCOM integer;
declare variable WCODINFCOM varchar(6);
declare variable WDESCINFCOM_ varchar(255);
declare variable WDESCINFCOM blob sub_type 1 segment size 16384;
declare variable WCODEMP integer;
declare variable WCODTIPO integer;
declare variable WCODENCONTRADO integer;
declare variable WATUALIZARDADOS DM_BOOLEAN;
declare variable WCASASNUM integer;
declare variable WCODINFCOMAUX varchar(6);
declare variable WEDITCHAVE integer;
declare variable WINFOCADASTRADA DM_BOOLEAN;
declare variable WCODINFCOMPLE varchar(6);
BEGIN
  PRLANCAMENTOMANUAL = UPPER(:PRLANCAMENTOMANUAL);    

  --EXECUTE PROCEDURE SP_CARREGAR_TMP_TCADINFCOM('FALSE');

  IF (:PRLANCAMENTOMANUAL = 'TRUE') THEN
    BEGIN
      SELECT FIRST 1 BDORDEMINFCOM, BDCODINFCOM, BDDESCINFCOM, BDCODEMP, BDCODTIPO
      FROM TMP_VEF_BASE_TCADINFCOM_TEMP I WHERE I.BDSESSAO = 0
      INTO :wOrdemInfCom, :wCodInfCom, :wDescInfCom, :wCodEmp, :wCodTipo;

      IF ((:wOrdemInfCom IS NOT NULL) AND (:wOrdemInfCom > 0)) THEN
        BEGIN
          UPDATE OR INSERT INTO TMP_VEF_BASE_TCADINFCOM(BDSESSAO, BDORDEMINFCOM, BDEDITCHAVE, BDCODINFCOM, BDDESCINFCOM, BDCODEMP, BDCODTIPO, BDDESCINFCOMHASH)
          VALUES(0, :wOrdemInfCom, :wOrdemInfCom, :wCodInfCom, :wDescInfCom, :wCodEmp, :wCodTipo, HASH(UPPER(:wDescInfCom))) MATCHING(BDEDITCHAVE);
        END

      DELETE FROM TMP_VEF_BASE_TCADINFCOM_TEMP WHERE BDSESSAO = 0;

      EXIT;
    END

  SELECT SP.BDATUINFCOM FROM SP_GET_ACOES_INCONSISTENCIA(:PRCODEMP, :PRREF) SP INTO :wAtualizarDados;

  FOR SELECT BDORDEMINFCOM, BDCODINFCOM, REPLACE(BDDESCINFCOM, '±', '|'), BDDESCINFCOM,
             BDCODEMP, BDCODTIPO, HASH(REPLACE(UPPER(TRIM(BDDESCINFCOM)), '±', '|')) BDDESCINFCOMHASH
      FROM TMP_VEF_BASE_TCADINFCOM_TEMP I
      WHERE I.BDSESSAO = :PRSESSAO
      AND ((I.BDEDITCHAVE = 0) OR (I.BDEDITCHAVE IS NULL))
      INTO :wOrdemInfCom, :wCodInfCom, :wDescInfCom, :wDescInfCom_,
           :wCodEmp, :wCodTipo, :WDESCINFCOMHASH
  DO
    BEGIN
      wCodEncontrado = NULL;
     /************************Vínculo************************/
      if (:wCodTipo in (103, 104)) then  /*No SPED vincula por código*/
        begin
      SELECT FIRST 1 I.BDEDITCHAVE
      FROM TMP_VEF_BASE_TCADINFCOM I
          WHERE BDCODINFCOM = :wCodInfcom
          AND I.BDCODEMP = :PRCODEMP
    --      AND I.BDSESSAO = 0
          INTO :wCodEncontrado;
    
          IF ((:wCodEncontrado IS NULL) OR (:wCodEncontrado = 0)) THEN
            BEGIN
              SELECT FIRST 1 I.BDEDITCHAVE
              FROM TMP_VEF_BASE_TCADINFCOM I
              WHERE BDCODINFCOM = :wCodInfcom
              AND ((I.BDCODEMP IS NULL) OR (I.BDCODEMP = 0))
    --          AND I.BDSESSAO = 0
              INTO :wCodEncontrado;
            END
        end
      ELSE  /*Demais importações vincula por descrição*/
        BEGIN
          SELECT FIRST 1 I.BDEDITCHAVE
          FROM (
                SELECT FIRST 1 I.BDEDITCHAVE
          FROM TMP_VEF_BASE_TCADINFCOM I
      WHERE (BDDESCINFCOMHASH = :WDESCINFCOMHASH)
                AND i.bdDESCINFCOM = :WDESCINFCOM_ -- Alt.: #197801 - Haviam duas informacoes complementares com o mesmo Hash, por isso vai tentar verificar pela descricao tambem...
      AND I.BDCODEMP = :PRCODEMP
                --AND I.BDSESSAO = 0
                UNION ALL
                SELECT FIRST 1 I.BDEDITCHAVE
                FROM TMP_VEF_BASE_TCADINFCOM I
                WHERE (BDDESCINFCOMHASH = :WDESCINFCOMHASH)
                AND I.BDCODEMP = :PRCODEMP
                --AND I.BDSESSAO = 0
                ) I
      INTO :wCodEncontrado;

      IF ((:wCodEncontrado IS NULL) OR (:wCodEncontrado = 0)) THEN
        BEGIN
          SELECT FIRST 1 I.BDEDITCHAVE
          FROM TMP_VEF_BASE_TCADINFCOM I
          WHERE (BDDESCINFCOMHASH = :WDESCINFCOMHASH)
          AND ((I.BDCODEMP IS NULL) OR (I.BDCODEMP = 0))
    --          AND I.BDSESSAO = 0
          INTO :wCodEncontrado;
        END
        END
      /*******************************************************/

      IF ((:wCodEncontrado IS NOT NULL) AND (:wCodEncontrado > 0)) THEN /*Encontrou uma informação complementar igual*/
        BEGIN
          IF (:wAtualizarDados = 'TRUE') THEN
            BEGIN
              UPDATE TMP_VEF_BASE_TCADINFCOM I
              SET I.BDSESSAO = :PRSESSAO,
                  I.BDCODINFCOM = IIF(:wCodtipo IN (106, 107, 132), I.BDCODINFCOM, :wCodInfCom), /*Na NFe não vem esse código, então não deve atualizar*/
                  I.BDDESCINFCOM = :wDescInfCom,
                  I.BDCODEMP = :wCodEmp,
                  I.BDCODTIPO = :wCodTipo,
                  I.BDDESCINFCOMHASH = :WDESCINFCOMHASH
              WHERE I.BDEDITCHAVE = :wCodEncontrado;
            END
          ELSE
            BEGIN
              UPDATE TMP_VEF_BASE_TCADINFCOM I
              SET I.BDSESSAO = :PRSESSAO
              WHERE I.BDEDITCHAVE = :wCodEncontrado;
            END

          UPDATE TMP_VEF_BASE_TCADINFCOM_TEMP I SET I.BDEDITCHAVE = :wCodEncontrado WHERE I.BDSESSAO = :PRSESSAO AND I.BDORDEMINFCOM = :wOrdemInfCom;

          IF (:wAtualizarDados <> 'TRUE') THEN
            BEGIN
              IF (:wCodTipo IN (103, 104)) THEN
                BEGIN
                  UPDATE TMP_VEF_BASE_TCADINFCOM_TEMP I
                  SET I.BDDESCINFCOM = (SELECT FIRST 1 BDDESCINFCOM FROM TMP_VEF_BASE_TCADINFCOM T WHERE T.BDEDITCHAVE = :wCodEncontrado AND T.BDSESSAO = :PRSESSAO)
                  WHERE I.BDEDITCHAVE = :wCodEncontrado AND
                        I.BDSESSAO = :PRSESSAO;
        END
            END
        END
      ELSE
        BEGIN
          INSERT INTO TMP_VEF_BASE_TCADINFCOM(BDSESSAO, BDORDEMINFCOM, BDEDITCHAVE, BDCODINFCOM, BDDESCINFCOM, BDCODEMP, BDCODTIPO, BDDESCINFCOMHASH, BDIMPORTANDO)
          VALUES(:PRSESSAO, :wOrdemInfCom, 0, :wCodInfCom, :wDescInfCom, :wCodEmp, :wCodTipo, :WDESCINFCOMHASH, 'TRUE');
        END
    END
    
  UPDATE TMP_VEF_BASE_TCADINFCOM_TEMP I SET I.BDDESCINFCOMHASH = HASH(UPPER(I.BDDESCINFCOM)) WHERE I.BDSESSAO = :PRSESSAO;    

  /*Informação complementar que não existe vai ser gerado um sequencial para o CODINFCOM* /
  SELECT IIF(INF.BDSONUMERO = 'TRUE', CAST(INF.BDCODINFCOM AS INTEGER)+1, 1) BDNEWCODINFCOM
  FROM (
        SELECT FIRST 1 I.BDCODINFCOM, IIF((SELECT BDRESULT FROM SONUMEROS(I.BDCODINFCOM)) = 1, 'TRUE', 'FALSE') BDSONUMERO
        FROM VEF_BASE_TCADINFCOM I
        WHERE I.BDCODEMP = :PRCODEMP
        ORDER BY I.BDCODINFCOM DESC
       ) INF
  INTO :wCodEncontrado;*/
--  select first 1 I.BDCODINFCOM
--  from VEF_BASE_TCADINFCOM I
--  where I.BDCODEMP = :PRCODEMP and
--        ((STRLEN(I.BDCODINFCOM) = 6) or ((select BDRESULT from SONUMEROS(I.BDCODINFCOM)) = 1))
--  order by I.BDCODINFCOM desc INTO :wCodInfCom;

select first 1 I.BDCODINFCOM from VEF_BASE_TCADINFCOM I
  where I.BDCODEMP = :PRCODEMP
    and
        (
        ( char_length(I.BDCODINFCOM) = 6)
        or
        (i.BDSONUMEROS = 1)
        )
  order by I.BDCODINFCOM desc INTO :wCodInfCom;

  IF (:wCodInfCom IS NULL) THEN -- Alt.: #98202 - Quando a empresa está cadastrando a primeira informacao complementar, traz vazio, por isso leva um zero para cadastrar a primeira...
    wCodInfCom = '0';

  SETCODINFCOM(:wCodInfCom);

  /* Nas importações via XML e chave de acesso não deve atualizar o código quando a info complementar já está cadastrada */
  UPDATE TMP_VEF_BASE_TCADINFCOM_TEMP I
  SET I.BDCODINFCOM = (SELECT A.BDCODINFCOM FROM VEF_BASE_TCADINFCOM A WHERE A.BDORDEMINFCOM = I.BDEDITCHAVE AND A.BDCODTIPO IN (106, 107, 132))
  WHERE I.BDSESSAO = :PRSESSAO
  AND ((I.BDCODINFCOM IS NULL) OR (I.BDCODINFCOM = ''))
  AND (I.BDCODTIPO IN (106, 107, 132) AND (EXISTS (SELECT A.BDORDEMINFCOM FROM VEF_BASE_TCADINFCOM A WHERE A.BDORDEMINFCOM = I.BDEDITCHAVE AND A.BDCODTIPO IN (106, 107, 132))));

  :wCODINFCOMPLE = GETCODINFCOM(1);

  UPDATE TMP_VEF_BASE_TCADINFCOM_TEMP I
  SET I.BDCODINFCOM = :wCODINFCOMPLE
  WHERE I.BDSESSAO = :PRSESSAO
  AND ((I.BDCODINFCOM IS NULL) OR (I.BDCODINFCOM = ''));

  /*#205163 | Título: Importação - Inconsistência na informação complementar - foi feito o update para deixar o BDCODINFCOM igual ao da TMP_VEF_BASE_TCADINFCOM_TEMP pois estava causando erro em alguns clientes porque deixa o campo vazio*/
  UPDATE TMP_VEF_BASE_TCADINFCOM I
  SET I.BDCODINFCOM = :wCODINFCOMPLE
  WHERE I.BDSESSAO = :PRSESSAO
  AND ((I.BDCODINFCOM IS NULL) OR (I.BDCODINFCOM = ''));
END
^


CREATE OR ALTER PROCEDURE SP_GERACODIGOS_INFCOM (
    PRSESSAO INTEGER,
    PRULTCHAVE INTEGER)
AS
DECLARE VARIABLE WORDEMINFCOM INTEGER;
BEGIN

  FOR SELECT I.BDORDEMINFCOM
      FROM TMP_VEF_BASE_TCADINFCOM I
      WHERE I.BDSESSAO = :PRSESSAO
      AND I.BDEDITCHAVE = 0
      INTO :wOrdemInfCom
  DO
    BEGIN
      UPDATE TMP_VEF_BASE_TCADINFCOM I SET I.BDEDITCHAVE = :PRULTCHAVE WHERE I.BDSESSAO = :PRSESSAO AND I.BDORDEMINFCOM = :wOrdemInfCom AND I.BDIMPORTANDO = 'TRUE';

      PRULTCHAVE = PRULTCHAVE - 1;
    END

  UPDATE TMP_VEF_BASE_TCADINFCOM_TEMP T SET T.BDEDITCHAVE = (SELECT first 1 I.BDEDITCHAVE FROM TMP_VEF_BASE_TCADINFCOM I WHERE I.BDSESSAO = T.BDSESSAO AND I.BDORDEMINFCOM = T.BDORDEMINFCOM AND I.BDIMPORTANDO = 'TRUE')
  WHERE T.BDSESSAO = :PRSESSAO
  AND ((T.BDEDITCHAVE IS NULL) OR (T.BDEDITCHAVE = 0));
END^



CREATE OR ALTER PROCEDURE SP_INSERT_OR_UPDATE_TCADINFCOM (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS
DECLARE VARIABLE wAtuInfCom DM_BOOLEAN;
DECLARE VARIABLE wOrdemInfCom INTEGER;
DECLARE VARIABLE wCodInfCom VARCHAR(6);
DECLARE VARIABLE wDescInfCom BLOB SUB_TYPE 1 SEGMENT SIZE 16384;
DECLARE VARIABLE wCodEmp INTEGER;
DECLARE VARIABLE wCodTipo INTEGER;
DECLARE VARIABLE wDescInfComHash BIGINT;
BEGIN
  SELECT SP.BDATUINFCOM FROM SP_GET_ACOES_INCONSISTENCIA(:PRCODEMP, :PRREF) SP INTO :wAtuInfCom;

  IF (:wAtuInfCom = 'FALSE') THEN
    BEGIN
      /*Só importa os novos*/
      INSERT INTO VEF_BASE_TCADINFCOM(BDORDEMINFCOM, BDCODINFCOM, BDDESCINFCOM, BDCODEMP, BDCODTIPO, BDDESCINFCOMHASH)
      SELECT I.BDEDITCHAVE BDORDEMINFCOM, I.BDCODINFCOM, I.BDDESCINFCOM, I.BDCODEMP, I.BDCODTIPO, HASH(UPPER(I.BDDESCINFCOM))
      FROM TMP_VEF_BASE_TCADINFCOM_TEMP I
      LEFT OUTER JOIN VEF_BASE_TCADINFCOM INF ON(INF.BDORDEMINFCOM = I.BDEDITCHAVE)
      WHERE I.BDSESSAO = :PRSESSAO
      AND INF.BDORDEMINFCOM IS NULL;
    END
  ELSE
    BEGIN
      FOR SELECT I.BDEDITCHAVE BDORDEMINFCOM, I.BDCODINFCOM, I.BDDESCINFCOM,
                 I.BDCODEMP, I.BDCODTIPO, HASH(UPPER(I.BDDESCINFCOM)) BDDESCINFCOMHASH
          FROM TMP_VEF_BASE_TCADINFCOM_TEMP I
          WHERE I.BDSESSAO = :PRSESSAO
          INTO :wOrdemInfCom, :wCodInfCom, :wDescInfCom,
               :wCodEmp, :wCodTipo, :wDescInfComHash
      DO
        BEGIN
          UPDATE OR INSERT INTO VEF_BASE_TCADINFCOM(BDORDEMINFCOM, BDCODINFCOM, BDDESCINFCOM, BDCODEMP, BDCODTIPO, BDDESCINFCOMHASH)
          VALUES(:wOrdemInfCom, :wCodInfCom, :wDescInfCom, :wCodEmp, :wCodTipo, :wDescInfComHash) MATCHING(BDORDEMINFCOM);
        END
    END
END^

create or alter procedure SP_UPD_CAM_INTEGRACAO_ARQ_INCO (
    PRCODEMP integer,
    PRCAMINHO varchar(2000),
    PRNOVOCAMINHO varchar(2000))
as
declare variable WSQL varchar(5000);
declare variable WORDEM integer;
begin
  WORDEM = (select first 1 INC.BDORDEM
            from TINTEGRACAO_ARQ_CLIENTE ARQ
            join TINTEGRACAO_ARQ_CLIENTE_INCONS INC on (ARQ.BDCODEMP = INC.BDCODEMP and
                  ARQ.BDORDEM = INC.BDORDEM)
            where ARQ.BDCODEMP = :PRCODEMP and
                  ARQ.BDCAMINHO = :PRCAMINHO);
  if (WORDEM is not null) then
  begin
    WSQL = ' update TINTEGRACAO_ARQ_CLIENTE ';
    WSQL = WSQL || ' set BDCAMINHO = ''' || PRNOVOCAMINHO || '''';
    WSQL = WSQL || ' where (BDCODEMP = ' || PRCODEMP || ') and';
    WSQL = WSQL || '       (BDORDEM = ' || WORDEM || ');';

    execute statement(WSQL);
  end
end^

CREATE OR ALTER procedure SP_VINCULAR_INFCOM (
    PRSESSAO integer,
    PRID_TERMINAL integer,
    PRIMPORTARCADASTRO DM_BOOLEAN)
as
declare variable WSQL varchar(700);
declare variable WTABLE varchar(50);
declare variable WSESSAOATU integer;
declare variable WDESC varchar(20);
declare variable WCODTIPO integer;
BEGIN
  PRIMPORTARCADASTRO = UPPER(:PRIMPORTARCADASTRO);

  SELECT FIRST 1 C.BDCODTIPO FROM TMP_VEF_BASE_TCADINFCOM_TEMP C WHERE C.BDSESSAO = :PRSESSAO INTO :wCodTipo;

  FOR SELECT TRIM(UPPER(T.RDB$RELATION_NAME)) BDTABLE
      FROM RDB$RELATION_FIELDS T
      WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
      AND RDB$FIELD_NAME = 'BDORDEMINFCOM'
      AND TRIM(UPPER(T.RDB$RELATION_NAME)) <> 'TMP_VEF_BASE_TCADINFCOM_TEMP'
      INTO :wTable
  DO
    BEGIN

      wSessaoAtu = NULL;
      SELECT S.BDSESSAO FROM TMP_TSESSAO_IMP S WHERE S.BDID_TERMINAL = :PRID_TERMINAL AND S.BDTABLE = :wTable INTO :wSessaoAtu;
      IF ((:wSessaoAtu IS NOT NULL) AND (:wSessaoAtu > 0)) THEN
        BEGIN               /*103 - Sped Fiscal, 104 - Sped Contribuições*/

          IF (:WTABLE = 'TMP_VEF_EMP_TMOVSAIINFCOM_TEMP') THEN
            wDesc = 'BDDESCINFCOMCAD';
          ELSE
            wDesc = 'BDDESCINFCOM';

          IF (:wCodTipo IN (103, 104)) THEN
            BEGIN
              /*Sped busca por CODINFCOM - VARCHAR(6)*/
              wSql =          'UPDATE '||:wTable||' T ';
              wSql = :wSql || 'SET T.BDALTORDEMINFCOM = (';
              wSql = :wSql ||                           'SELECT FIRST 1 I.BDEDITCHAVE ';
              wSql = :wSql ||                           'FROM TMP_VEF_BASE_TCADINFCOM_TEMP I ';
              wSql = :wSql ||                           'WHERE I.BDSESSAO = '||:PRSESSAO;
              wSql = :wSql ||                           ' AND I.BDCODINFCOM = T.BDCODINFCOM';
              wSql = :wSql ||                          ')';
              wSql = :wSql || 'WHERE T.BDSESSAO = '||:wSessaoAtu||' ';
              wSql = :wSql || ' AND ((T.BDALTORDEMINFCOM IS NULL) OR (T.BDALTORDEMINFCOM = 0)) ';
              wSql = :wSql || ' AND ((T.BDCODINFCOM IS NOT NULL) AND (T.BDCODINFCOM <> ''''))';
              EXECUTE STATEMENT :wSql;
            END

          /*NFe busca pela descrição*/
          wSql =          'UPDATE '||:wTable||' T ';
          wSql = :wSql || 'SET T.BDALTORDEMINFCOM = (';
          wSql = :wSql ||                          'SELECT FIRST 1 I.BDEDITCHAVE ';
          wSql = :wSql ||                          'FROM ( ';
          wSql = :wSql ||                                'SELECT FIRST 1 I.BDEDITCHAVE ';
          wSql = :wSql ||                                'FROM TMP_VEF_BASE_TCADINFCOM I ';
          wSql = :wSql ||                                'WHERE I.BDSESSAO = '||:PRSESSAO;
          wSql = :wSql ||                                '  AND i.bdDESCINFCOM = t.'||:wDesc||' '; -- Alt.: #197801 - Haviam duas informacoes complementares com o mesmo Hash, por isso vai tentar verificar pela descricao tambem...
          wSql = :wSql ||                                '  AND I.BDDESCINFCOMHASH = HASH(UPPER(T.'||:wDesc||')) ';
          wSql = :wSql ||                                'UNION ALL ';
          wSql = :wSql ||                                'SELECT FIRST 1 I.BDEDITCHAVE ';
          wSql = :wSql ||                                'FROM TMP_VEF_BASE_TCADINFCOM I ';
          wSql = :wSql ||                                'WHERE I.BDSESSAO = '||:PRSESSAO;
          wSql = :wSql ||                                '  AND I.BDDESCINFCOMHASH = HASH(UPPER(T.'||:wDesc||')) ';
          wSql = :wSql ||                                ') I ';
          wSql = :wSql ||                          ')';
          wSql = :wSql || 'WHERE T.BDSESSAO = '||:wSessaoAtu||' ';
          wSql = :wSql || ' AND ((T.BDALTORDEMINFCOM IS NULL) OR (T.BDALTORDEMINFCOM = 0))';
          wSql = :wSql || ' AND ((T.'||:wDesc||' IS NOT NULL) OR (T.'||:wDesc||' <> ''''))';
          EXECUTE STATEMENT :wSql;

          wSql =          ' UPDATE '||:wTable||' T SET T.BDORDEMINFCOM = T.BDALTORDEMINFCOM, ';
          wSql = :wSql || '         T.'||:wDesc||' = (SELECT FIRST 1 CAST(SUBSTRING(I.BDDESCINFCOM FROM 1 FOR 1000) AS VARCHAR(1000)) BDDESCINFCOM FROM TMP_VEF_BASE_TCADINFCOM I WHERE I.BDEDITCHAVE = T.BDALTORDEMINFCOM), ';
          wSql = :wSql || '         T.BDCODINFCOM = IIF(COALESCE(T.BDCODINFCOM, '''') = '''', (SELECT FIRST 1 I.BDCODINFCOM BDDESCINFCOM FROM TMP_VEF_BASE_TCADINFCOM I WHERE I.BDEDITCHAVE = T.BDALTORDEMINFCOM), T.BDCODINFCOM) ';
          wSql = :wSql || ' WHERE T.BDSESSAO = '||:wSessaoAtu;
          wSql = :wSql || ' AND ((T.BDALTORDEMINFCOM IS NOT NULL) AND (T.BDALTORDEMINFCOM > 0)) ';
          EXECUTE STATEMENT :wSql;          

          /*Só entra no if importando sped, lançamento de saída e com o parâmetro "Informação Complementar" desmarcado na tela de filtro.*/
          IF ((:wCodTipo IN (103, 104)) AND (:PRIMPORTARCADASTRO = 'FALSE')) THEN
            BEGIN
              wSql =          ' UPDATE '||:wTable||' T SET T.BDORDEMINFCOM = 0, T.BDALTORDEMINFCOM = 0 ';
              wSql = :wSql || ' WHERE T.BDSESSAO = '||:wSessaoAtu;
--              wSql = :wSql || ' AND NOT EXISTS (SELECT BDORDEMINFCOM FROM VEF_BASE_TCADINFCOM C WHERE (C.BDCODINFCOM = T.BDCODINFCOM)  AND (C.BDDESCINFCOM = SUBSTRING(T.BDDESCINFCOM FROM 1 FOR 255)) AND C.BDCODEMP = T.BDCODEMP);';
              wSql = :wSql || ' AND NOT EXISTS (SELECT BDORDEMINFCOM FROM VEF_BASE_TCADINFCOM C WHERE (C.BDCODINFCOM = T.BDCODINFCOM) AND C.BDCODEMP = T.BDCODEMP);';
              EXECUTE STATEMENT :wSql;

              IF ((:WTABLE = 'TMP_VEF_EMP_TD100SAI_TEMP') OR (:WTABLE = 'TMP_VEF_EMP_TD500SAI_TEMP')) THEN
                 BEGIN
                   wsql = '          UPDATE '||:wTable||' T SET T.BDORDEMINFCOM = null, T.BDALTORDEMINFCOM = null';
                   wsql = :wsql || ' WHERE T.BDCODINFCOM = '''';';
                   EXECUTE STATEMENT :wSql;
            END
        END
    END
    END
END
^

CREATE OR ALTER trigger vrh_base_tmotesocial_ent_bi0 for vrh_base_tmotesocial_ent
active before insert position 0
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF ((NEW.BDCODMOTESENT IS NULL) OR (NEW.BDCODMOTESENT = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODMOTESENT), 0) + 1 FROM VRH_BASE_TMOTESOCIAL_ENT INTO :vcod;
       NEW.BDCODMOTESENT = :vcod;
     END
END^

CREATE OR ALTER PROCEDURE SP_RETORNA_REFERENCIAS (
    PRCODEMP INTEGER,
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDREFERENCIA INTEGER)
AS
DECLARE VARIABLE I    INTEGER;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES INTEGER;
BEGIN
  /* Retorna as referências entre a referência inicial e a referência final */
  IF ((PRREFINI <= PRREFFIN) AND
      (CHAR_LENGTH(TRIM(CAST(PRREFINI AS VARCHAR(6)))) = 6) AND -- REFERENCIA DEVE TER 6 CARACTERES
      (CHAR_LENGTH(TRIM(CAST(PRREFFIN AS VARCHAR(6)))) = 6)) THEN
    BEGIN
       WANO = CAST(SUBSTRING(CAST(PRREFINI AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
       WMES = CAST(SUBSTRING(CAST(PRREFINI AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
       I    = PRREFINI;

       WHILE (I <= PRREFFIN) DO
         BEGIN
           BDCODEMP = prCODEMP;
           BDREFERENCIA = CAST(CAST(WANO AS VARCHAR(4))||LPAD(CAST(WMES AS VARCHAR(2)),2,'0') AS INTEGER);
  
           IF (WMES < 12) THEN
             WMES = WMES+1;
           ELSE
             BEGIN
               wMES = 1;
               WANO = WANO+1;
             END
  
           I = BDREFERENCIA;
           IF (I <= PRREFFIN) THEN
             SUSPEND;
         END
    END
END
^

CREATE OR ALTER trigger vrh_esocial_fechamento_bi0 for vrh_esocial_fechamento
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vRefAux INTEGER;
BEGIN
  /* Trigger text */
  vCodigo = 0;
  IF ((NEW.BDCODIGO IS NULL) OR (NEW.BDCODIGO = 0)) THEN
    BEGIN
       SELECT COALESCE((MAX(BDCODIGO) + 1), 1) FROM VRH_ESOCIAL_FECHAMENTO WHERE BDCODEMP = NEW.BDCODEMP AND BDREF = NEW.BDREF INTO vCodigo;
       NEW.BDCODIGO = vCodigo;
    END

  IF (NEW.bdintegrado = 'TRUE') THEN
     BEGIN
       vRefAux = NEW.bdref;
       IF (NEW.bdanual = 'TRUE') THEN
         vRefAux = NEW.bdref + 1;

       IF ((NEW.bddatareab IS NOT NULL) AND
           (NEW.bdhorareab IS NOT NULL) AND
           (NEW.bddatareab + NEW.bdhorareab > NEW.bddata + NEW.bdhora)) THEN
          EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, vRefAux, '5', '', 'TRUE'); -- 5 - Reaberto
       ELSE
       IF (NEW.bdsemmovimento = 'TRUE') THEN
          EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, vRefAux, '6', '', 'TRUE'); -- 6 - Processado sem dados
       ELSE
          EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, vRefAux, '3', '', 'TRUE'); -- 3 - Processado
END
END
^

-- 125979 - Raphael Teodoro - 15/01/2020
CREATE OR ALTER trigger vrh_esocial_fechamento_bu0 for vrh_esocial_fechamento
active before update position 0
AS
    DECLARE VARIABLE vRefAux INTEGER;
BEGIN
  /* Trigger text */
  IF (NEW.bdintegrado = 'TRUE') THEN
     BEGIN
       vRefAux = NEW.bdref;
       IF (NEW.bdanual = 'TRUE') THEN
         vRefAux = NEW.bdref + 1;

       IF ((NEW.bddatareab IS NOT NULL) AND
           (NEW.bdhorareab IS NOT NULL) AND
           (NEW.bddatareab + NEW.bdhorareab > NEW.bddata + NEW.bdhora)) THEN
          EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, vRefAux, '5', '', 'TRUE'); -- 5 - Reaberto
       ELSE
       IF (NEW.bdsemmovimento = 'TRUE') THEN
          EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, vRefAux, '6', '', 'TRUE'); -- 6 - Processado sem dados
       ELSE
          EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, vRefAux, '3', '', 'TRUE'); -- 3 - Processado
     END
END
^

-- 125979 - Raphael Teodoro - 15/01/2020
CREATE OR ALTER TRIGGER VRH_ESOCIAL_FECHAMENTO_AD0 FOR VRH_ESOCIAL_FECHAMENTO
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  /* Trigger text */
  EXECUTE PROCEDURE sp_vrh_painel_update(OLD.bdcodemp, OLD.bdref, '2', '', 'TRUE'); -- 2 - Excluido
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TSEFIPSM_BI0 FOR VRH_BASE_TSEFIPSM
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF ((NEW.bdcodsefip IS NULL) OR (NEW.bdcodsefip = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODSEFIP) + 1, 1) FROM VRH_BASE_TSEFIPSM WHERE BDCODEMP = NEW.bdcodemp INTO :vcod;
       NEW.bdcodsefip = vcod;
     END
END
^

CREATE OR ALTER TRIGGER TPROCESSO_JUDADM_INDSUSP_BI0 FOR TPROCESSO_JUDADM_INDSUSP
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF (COALESCE(NEW.bdcodindprocesso, 0) = 0) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODINDPROCESSO) + 1, 1) FROM TPROCESSO_JUDADM_INDSUSP INTO :vcod;
       NEW.bdcodindprocesso = :vcod;
     END
END
^

CREATE OR ALTER PROCEDURE SP_ALTERA_PROD_GRID (
    PRSESSAO INTEGER,
    PRCODPRODVINC INTEGER,
    PRCODPRODNOVO INTEGER)
AS
DECLARE VARIABLE WCODPROD INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODPRODVINC INTEGER;
DECLARE VARIABLE WCODPRODOUTEMP INTEGER;
DECLARE VARIABLE WCODPRODMSMEMP INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WORIGEM INTEGER;
DECLARE VARIABLE WENTRADA INTEGER;
DECLARE VARIABLE WQTDPRODREL INTEGER;
DECLARE VARIABLE WCODENTRADA VARCHAR(60);
DECLARE VARIABLE WDESCPROD VARCHAR(200);
BEGIN
  /****************************************************************************/
  /*                   Patrick T. Sá   06/09/2017 - 19:40                     */
  /*            Alteração do campo "Produto Único na grid com F4              */
  /****************************************************************************/
  wEntrada = 0;
  /*Dados do produto na grid (Que foi pressionado F4)*/
  SELECT T.BDEDITCHAVE, T.BDCODEMP, T.BDORIGEMPROD,
         T.BDCODENTRADA, T.BDDESCPROD, T.BDCODTERLAYOUT
  FROM TMP_TCADPRO_TEMP T
  WHERE T.BDSESSAO = :PRSESSAO
  AND T.BDCODPRODVINC = :PRCODPRODVINC
  INTO :wCodProd, :wCodEmp, :wOrigem,
       :wCodEntrada, :wDescProd, :wCodTer;

  /*Busca se na importação existe mais de um produto relacionado ao mesmo código.
    Exemplo: Código | Descrição | Código Entrada
               1    |   CAMISA  |   001.001
               1    |   CAMISA  |   001.002
               1    |   CAMISA  |   001.003
    OU banco HHC - Empresa 73 - Chave NFe 41-1708-07.407.774/0001-80-55-001-000.016.396-114.028.665-6
  */
  SELECT COUNT(T.BDEDITCHAVE) BDQTDPRODREL
  FROM TMP_TCADPRO_TEMP T
  WHERE T.BDSESSAO = :PRSESSAO
  AND T.BDEDITCHAVE = :wCodProd
  GROUP BY T.BDEDITCHAVE
  INTO :wQtdProdRel;

  /*Verifica se já tem o produto na empresa*/
  SELECT (SELECT PV.BDCODPROD FROM TCADPRO_VINC PV WHERE PV.BDCODPROD = :PRCODPRODNOVO AND PV.BDCODEMP = :wCodEmp) BDCODPRODVINC, /*Produto na empresa*/
         (SELECT FIRST 1 TMP.BDCODPROD FROM TMP_TCADPRO TMP WHERE TMP.BDEDITCHAVE = :wCodProd AND TMP.BDCODEMP <> :wCodEmp) BDCODPRODOUTEMP, /*Produto em outra empresa*/
         (SELECT PV.BDCODPROD FROM TCADPRO_VINC PV WHERE PV.BDCODPROD = :wCodProd AND PV.BDCODEMP = :wCodEmp) BDCODPRODMSMEMP /*Produto antigo na empresa*/
  FROM RDB$DATABASE
  INTO :wCodProdVinc, :wCodProdOutEmp, :wCodProdMsmEmp;

  /*Produto que o usuário digitou já existe na empresa*/
  IF ((:wCodProdVinc IS NOT NULL) AND (:wCodProdVinc > 0)) THEN
    BEGIN
      /*Somente um produto com o mesmo código na grid*/
      IF (:wQtdProdRel = 1) THEN
        BEGIN
          IF ((:wCodProdMsmEmp IS NULL) OR (:wCodProdMsmEmp = 0)) THEN
            BEGIN
              /*Apaga na TMP_TCADPRO o produto da grid(Somente da empresa)*/
              DELETE FROM TMP_TCADPRO TMP WHERE TMP.BDEDITCHAVE = :wCodprod AND TMP.BDCODEMP = :wCodEmp;

              /*Se for produto de entrada apaga na TMP_TCADPRO_PART também*/
              IF (:wOrigem = :wEntrada) THEN
                BEGIN
                  DELETE FROM TMP_TCADPRO_PART PT
                  WHERE PT.BDEDITCHAVE = :wCodprod
                  AND PT.BDCODENTRADA = :wCodEntrada
                  AND PT.BDDESCPRODBUSCA = :wDescProd
                  AND PT.BDCODTER = :wCodTer;
                END
            END
        END
      ELSE
        BEGIN
          IF (:wOrigem = :wEntrada) THEN
            BEGIN
              UPDATE TMP_TCADPRO_PART PT
              SET PT.BDEDITCHAVE = :PRCODPRODNOVO,
                  PT.BDCODPROD = :PRCODPRODNOVO,
                  PT.BDORDEM = (COALESCE((SELECT MAX(BDORDEM)+1 FROM TMP_TCADPRO_PART WHERE BDEDITCHAVE = :PRCODPRODNOVO), 1))
              WHERE PT.BDEDITCHAVE = :wCodprod
              AND PT.BDCODENTRADA = :wCodEntrada
              AND PT.BDDESCPRODBUSCA = :wDescProd
              AND PT.BDCODTER = :wCodTer;
            END
        END
    END
  ELSE
    BEGIN /*Está relacionando com um produto que não existe na empresa*/
      IF (:wQtdProdRel = 1) THEN
        BEGIN
          UPDATE TMP_TCADPRO TMP SET TMP.BDEDITCHAVE = :PRCODPRODNOVO, TMP.BDCODPROD = :PRCODPRODNOVO WHERE TMP.BDEDITCHAVE = :wCodProd AND TMP.BDCODEMP = :wCodEmp;

          IF (:wOrigem = :wEntrada) THEN
            BEGIN
              UPDATE TMP_TCADPRO_PART PT
              SET PT.BDEDITCHAVE = :PRCODPRODNOVO,
                  PT.BDCODPROD = :PRCODPRODNOVO,
                  PT.BDORDEM = (COALESCE((SELECT MAX(BDORDEM)+1 FROM TMP_TCADPRO_PART WHERE BDEDITCHAVE = :PRCODPRODNOVO), 1))
              WHERE PT.BDEDITCHAVE = :wCodprod
              AND PT.BDCODENTRADA = :wCodEntrada
              AND PT.BDDESCPRODBUSCA = :wDescProd
              AND PT.BDCODTER = :wCodTer;
            END
        END
      ELSE
        BEGIN
          /*Quando tem mais de um produto com o mesmo código, insere um novo na tmp com o código informado pelo usuário*/
          INSERT INTO TMP_TCADPRO(BDSESSAO, BDEDITCHAVE, BDCODPROD, BDORIGEMPROD, BDCODTERLAYOUT, BDCNPJTERLAYOUT, BDCODEMP, BDCODSAIDA,
                                  BDDESCPROD, BDAPELIDOUNICO, BDDESCRICAOUNICA, BDCODIGOEAN, BDCODTER, BDCODENTRADA, BDCODTIPO, BDCODCOMBANP)
          SELECT FIRST 1 :PRSESSAO, :PRCODPRODNOVO, :PRCODPRODNOVO, TMP.BDORIGEMPROD, TMP.BDCODTERLAYOUT, TMP.BDCNPJTERLAYOUT, TMP.BDCODEMP, TMP.BDCODSAIDA,
                         TMP.BDDESCPROD, TMP.BDAPELIDOUNICO, TMP.BDDESCRICAOUNICA, TMP.BDCODIGOEAN, TMP.BDCODTER, TMP.BDCODENTRADA, TMP.BDCODTIPO,
                         TMP.BDCODCOMBANP
          FROM TMP_TCADPRO TMP
          WHERE TMP.BDEDITCHAVE = :wCodProd
          AND TMP.BDCODEMP = :wCodEmp;

          IF (:wOrigem = :wEntrada) THEN
            BEGIN
              UPDATE TMP_TCADPRO_PART PT
              SET PT.BDEDITCHAVE = :PRCODPRODNOVO,
                  PT.BDCODPROD = :PRCODPRODNOVO,
                  PT.BDORDEM = (COALESCE((SELECT MAX(BDORDEM)+1 FROM TMP_TCADPRO_PART WHERE BDEDITCHAVE = :PRCODPRODNOVO), 1))
              WHERE PT.BDEDITCHAVE = :wCodprod
              AND PT.BDCODENTRADA = :wCodEntrada
              AND PT.BDDESCPRODBUSCA = :wDescProd
              AND PT.BDCODTER = :wCodTer;
            END
        END
    END

  IF (((:wCodProdOutEmp IS NULL) OR (:wCodProdOutEmp = 0)) AND ((:wCodProdMsmEmp IS NULL) OR (:wCodProdMsmEmp = 0))) THEN
    DELETE FROM TMP_TCADPRO TMP WHERE TMP.BDEDITCHAVE = :wCodProd AND ((TMP.BDCODEMP IS NULL) OR (TMP.BDCODEMP = 0));

  UPDATE TMP_TCADPRO_TEMP T
  SET T.BDSITUACAO = 1,
      T.BDPRODEXISTEBASE = 'TRUE',
      T.BDEDITCHAVE = :PRCODPRODNOVO
  WHERE T.BDSESSAO = :PRSESSAO
  AND T.BDCODEMP = :wCodEmp
  AND T.BDCODPRODVINC = :PRCODPRODVINC;

  /* ** Produto "Não Relacionado" ou "Cadastro Automático" ** */

  /*1 - OK
    1 - Troca o produto da empresa e apaga o produto unico(verificar na TMP_TCADPRO e TCADPRO) do que está sendo importado
        EX: 1 - 'ABC' - Null
            1 - 'ABC' - 73
        Produto digitado no grid(2), deve trocar o vinculado para 2 e apagar o unico.
        Trocar produtos por participante para o produto novo tambem


    ** Produto "Relacionado" **

    1 - Vários iguais no grid
        Verificar quantos produtos vinculados ao código que está na grid(olhar na TMP_TCADPRO_TEMP),
        se existir mais de um com o mesmo código de produto
        deve fazer um insert select do produto que esta na grid com o código digitado pelo usuário.
        Trocar a TMP_TCADPRO_PART usando como filtro o código de entrada do produto que está sendo trocado no grid.
    
        **Só um igual na grid e troca para um produto unico**
          Se existir só um desse produto na grid deve trocar ele na TMP da empresa para o novo produto e
          tambem verificar se não existe ele em outras empresas na TMP_TCADPRO e não existe na TCADPRO,
          se não existir em outras empresas apaga o produto unico. Trocar o TMP_TCADPRO_PART também através da TMP_TCADPRO_TEMP

    Quando já tem o produto na própria empresa
    2 - Verificar se já tem o produto digitado na empresa, se já existir,
    apaga oque está na grid(sendo alterado) na TMP_TCADPRO e TMP_TCADPRO_PART da EMPRESA.
    Ver se não está cadastrado em outra empresa(TMP_TCADPRO e TCADPRO), se não estiver deve apagar da TMP_TCADPRO.*/

END^

CREATE OR ALTER TRIGGER TPROCESSO_JUDADM_AUTORIA_BI0 FOR TPROCESSO_JUDADM_AUTORIA
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF (COALESCE(NEW.bdcodautproc, 0) = 0) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODAUTPROC) + 1, 1) FROM TPROCESSO_JUDADM_AUTORIA INTO :vcod;
       NEW.bdcodautproc = :vcod;
     END
END
^

CREATE OR ALTER TRIGGER TPROCESSO_JUDADM_INDMAT_BI0 FOR TPROCESSO_JUDADM_INDMAT
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF (COALESCE(NEW.bdcodmatproc, 0) = 0) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODMATPROC) + 1, 1) FROM TPROCESSO_JUDADM_INDMAT INTO :vcod;
       NEW.bdcodmatproc = :vcod;
     END
END
^

CREATE OR ALTER TRIGGER TPROCESSO_JUDADM_BI0 FOR TPROCESSO_JUDADM
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF (COALESCE(NEW.BDCODPROCESSO, 0) = 0) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODPROCESSO) + 1, 1) FROM TPROCESSO_JUDADM WHERE BDCODEMP = NEW.BDCODEMP INTO :vcod;
       NEW.BDCODPROCESSO = :vcod;
     END
END
^

CREATE OR ALTER TRIGGER TPROCESSO_JUDADM_ITEM_BI0 FOR TPROCESSO_JUDADM_ITEM
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF (COALESCE(NEW.BDCODITEMPROC, 0) = 0) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODITEMPROC) + 1, 1) FROM TPROCESSO_JUDADM_ITEM WHERE BDCODEMP = NEW.BDCODEMP and BDCODPROCESSO = NEW.BDCODPROCESSO INTO :vcod;
       NEW.BDCODITEMPROC = :vcod;
     END
END
^

CREATE OR ALTER TRIGGER TPROCESSO_JUDADM_ANEXO_BI0 FOR TPROCESSO_JUDADM_ANEXO
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF (COALESCE(NEW.BDCODPROCANEXO, 0) = 0) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODPROCANEXO) + 1, 1) FROM TPROCESSO_JUDADM_ANEXO WHERE BDCODEMP = NEW.BDCODEMP and BDCODPROCESSO = NEW.BDCODPROCESSO INTO :vcod;
       NEW.BDCODPROCANEXO = :vcod;
     END
END
^

/* Restore proc. body: INC_REFERENCIA */
CREATE OR ALTER PROCEDURE INC_REFERENCIA (
    PRREFERENCIA INTEGER,
    PRMESES INTEGER = 1)
RETURNS (
    BDREFERENCIA INTEGER)
AS
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES INTEGER;
BEGIN
  BDREFERENCIA = NULL;

  IF ((CHAR_LENGTH(CAST(prREFERENCIA as VARCHAR(10))) <> 6) OR (PRMESES < 0)) THEN
    SUSPEND;
  ELSE
  IF (CHAR_LENGTH(CAST(prREFERENCIA as VARCHAR(10))) = 0) THEN
    BDREFERENCIA = prREFERENCIA;
  ELSE
    BEGIN
      wMES = CAST(SUBSTRING(CAST(prREFERENCIA as VARCHAR(6)) FROM 5 FOR 2) as INTEGER);
      wANO = CAST(SUBSTRING(CAST(prREFERENCIA as VARCHAR(6)) FROM 1 FOR 4) as INTEGER);
    
      WHILE (prMESES > 0) DO
        BEGIN
          IF (wMES = 12) THEN
            BEGIN
              wMES = 1;
              wANO = wANO+1;
            END
          ELSE
            wMES = wMES + 1;
    
          prMESES = prMESES-1;
        END
    
      BDREFERENCIA = CAST(wANO||LPAD(CAST(wMES AS VARCHAR(2)), 2, '0') as INTEGER);
    
      SUSPEND;
    END
END
^

CREATE OR ALTER PROCEDURE DEC_REFERENCIA (
    PRREFERENCIA INTEGER,
    PRMESES INTEGER = 1)
RETURNS (
    BDREFERENCIA INTEGER)
AS
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES INTEGER;
BEGIN
  BDREFERENCIA = NULL;

  IF ((CHAR_LENGTH(CAST(prREFERENCIA as VARCHAR(10))) <> 6) OR (PRMESES < 0)) THEN
    SUSPEND;
  ELSE
  IF (CHAR_LENGTH(CAST(prREFERENCIA as VARCHAR(10))) = 0) THEN
    BDREFERENCIA = prREFERENCIA;
  ELSE
    BEGIN
      wMES = CAST(SUBSTRING(CAST(prREFERENCIA as VARCHAR(6)) FROM 5 FOR 2) as INTEGER);
      wANO = CAST(SUBSTRING(CAST(prREFERENCIA as VARCHAR(6)) FROM 1 FOR 4) as INTEGER);
    
      WHILE (prMESES > 0) DO
        BEGIN
          IF (wMES = 1) THEN
            BEGIN
              wMES = 12;
              wANO = wANO-1;
            END
          ELSE
            wMES = wMES-1;
    
          prMESES = prMESES-1;
        END
    
      BDREFERENCIA = CAST(wANO||LPAD(CAST(wMES AS VARCHAR(2)), 2, '0') as INTEGER);
    
      SUSPEND;
    END
END
^

CREATE OR ALTER PROCEDURE SP_TIRATODOSSINAIS (
    STR VARCHAR(32000))
RETURNS (
    RESULT VARCHAR(32000))
AS
BEGIN
  RESULT = STR;
  RESULT = REPLACE(RESULT, '/', '');
  RESULT = REPLACE(RESULT, '(', '');
  RESULT = REPLACE(RESULT, ')', '');
  RESULT = REPLACE(RESULT, '-', '');
  RESULT = REPLACE(RESULT, '_', '');
  RESULT = REPLACE(RESULT, '.', '');
  RESULT = REPLACE(RESULT, ',', '');
  RESULT = REPLACE(RESULT, '\', '');
  RESULT = REPLACE(RESULT, '$', '');
  RESULT = REPLACE(RESULT, '*', '');
  RESULT = REPLACE(RESULT, ':', '');
  RESULT = REPLACE(RESULT, '"', '');
  RESULT = REPLACE(RESULT, 'º', '');
  RESULT = REPLACE(RESULT, 'ª', '');

  SUSPEND;
END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_ISS_CURITIBA_REG_E_R (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRTIPOLANC INTEGER,
    PRRETIFICADORA INTEGER,
    PRARQUIVO VARCHAR(260),
    PRTIPOLANCEXP INTEGER)
AS
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- REGISTRO DOCUMENTOS EMITIDOS DECLARADOS – “E”
  -- REGISTRO DOCUMENTOS RECEBIDOS DECLARADOS – “R”
  INSERT INTO TEXPORTACAO_ISS_CURITIBA (bdID, bdCODEMP, bdORDEMREG, bdORDEM, bdVLREMIT, bdVLRDEDEMIT, bdVLRRECEB, bdVLRDEDRECEB, bdLINHA)
  SELECT :prARQUIVO, s.bdCODEMP, 3+:prTIPOLANCEXP, LPAD(COALESCE((SELECT COUNT(*)
                                                                  FROM TEXPORTACAO_ISS_CURITIBA WHERE bdID = :prARQUIVO),1), 6, '0'),
--SELECT :prARQUIVO, s.bdCODEMP, 3+:prTIPOLANCEXP, i.bdCODEMP||'.'||i.bdCHAVE||'.'||i.bdORDEM,
         CASE WHEN s.bdTIPLAN = 0 THEN COALESCE(i.bdVLRCONTAB, 0)     ELSE 0 END AS bdVLREMIT,
         CASE WHEN s.bdTIPLAN = 0 THEN COALESCE(i.bdACREDEDUIRSER, 0) ELSE 0 END AS bdVLRDEDEMIT,
         CASE WHEN s.bdTIPLAN = 1 THEN COALESCE(i.bdVLRCONTAB, 0)     ELSE 0 END AS bdVLRRECEB,
         CASE WHEN s.bdTIPLAN = 1 THEN COALESCE(i.bdACREDEDUIRSER, 0) ELSE 0 END AS bdVLRDEDRECEB,
--'|E.01|'||
         CASE

           WHEN s.bdTIPLAN = 0 THEN 'E'
           WHEN s.bdTIPLAN = 1 THEN 'R'                                         -- CAMPOS  POSIÇÕES  TIPO/TAMANHO  DESCRIÇÃO                                                                                                                       OBSERVAÇÕES
         ELSE ' ' END||                                                         -- E.01    1 - 1     Caracter(1)   Código do registro “E”                                                                                                          Campo Obrigatório
--'|E.02|'||
         (SUBSTRING(s.bdDATAEMISSAO FROM 9 FOR 2)||
          SUBSTRING(s.bdDATAEMISSAO FROM 6 FOR 2)||
          SUBSTRING(s.bdDATAEMISSAO FROM 1 FOR 4))||                            -- E.02    2 - 9     Numérico(8)   Data de emissão do documento declarado.                                                                                         Campo Obrigatório Formato: DDMMAAAA
--'|E.03|'||
         LPAD(SUBSTRING(COALESCE(s.bdNUMDOCINI,'') FROM 1 FOR 8), 8, '0')||     -- E.03    10 - 17   Numérico(8)   Número do documento inicial emitido                                                                                             Obs.: este campo será obrigatório somente quando o tipo de documento declarado (campo E.05) for nota fiscal ou conhecimento de transporte.
--'|E.04|'||
         RPAD('', 8, ' ')||                                                     -- E.04    18 - 25   Numérico(8)   Número do documento final emitido                                                                                               Obs.: este campo deverá ser informado apenas quando caracterizar agrupamento de notas e quando o serviço não caracterizar subst.tribut/ret.órgãos públ. (campo E.07).
                                                                                --                                                                                                                                                                       Também deverá ser respeitado o valor mínimo de cada documento. Poderão ser agrupados apenas os documentos com valor unitário inferior a R$ 200,00. Limite de 20 documentos por agrupamento.
--'|E.05|'||
         COALESCE(tpnf.bdCODTPNFEXP,'0')||                                      -- E.05    26 - 26   Numérico(1)   Identificação do Tipo de Documento emitido.                                                                                     Campo Obrigatório
                                                                                --                                   Pessoas Jurídicas poderão utilizar os seguintes códigos: 1. Nota Fiscal, 4. Cupom Fiscal, 6. Conhecimento de Transporte
                                                                                --                                   Pessoas Físicas poderão utilizar os seguintes códigos: 2. Recibo Comum, 3. RPA - Recibo Pagamento Autônomo
--'|E.06|'||
         RPAD(SUBSTRING(COALESCE(s.bdSERIE,'') FROM 1 FOR 3), 3, ' ')||         -- E.06    27 - 29   Caracter(3)   Série do Documento emitido quando o campo E.05 = Nota Fiscal                                                                    Obs.: Este nº será obrigatório somente quando o tipo de documento declarado (campo E.05) for nota fiscal.
--'|E.07|'||
         CASE                                                                   -- E.07    30 - 30   Caracter(1)   Identificação do Serviço Prestado caracterizando Substituição Tributária / Retenção Órgão Público ou Doc.Fiscal Normal          Campo Obrigatório
           WHEN ic.bdCODIDNF = 0 THEN 'N'                                       --                                   N – Doc.Fiscal Normal
           WHEN ic.bdCODIDNF = 1 THEN 'S'                                       --                                   S – caracteriza substituição tributária/retenção órgão público
           WHEN ic.bdCODIDNF = 2 THEN 'R'                                       --                                   R - Caracteriza retenção na fonte

         ELSE 'N' END||
--'|E.08|'||
         IIF(s.bdCODCID = 3281, 'D', 'F')||                                     -- E.08    31 - 31   Caracter(1)   Indicador do Local de Prestação do Serviço quando o serviço prestado caracterizar substituição tributária / retenção órgão público, de acordo com o campo E.07.
                                                                                --                                   D – Dentro do Município                                                                                                       Campo obrigatório somente quando o campo E.07 = Substituição tributária / retenção fonte órgão público
                                                                                --                                   F – Fora do Município
--'|E.09|'||
         RPAD(SUBSTRING((SELECT RESULT FROM SP_TIRATODOSSINAIS
                         (COALESCE(atv.bdCODMUNATVM,''))) FROM 1 FOR 2),2,' ')||-- E.09    32 - 33   Caracter(2)   Código do Item da Lista de Serviços (Lei Complementar 116/2003)                                                                 Campo Obrigatório somente quando o serviço prestado caracterizar substituição tributária / retenção órgão público, de acordo com o campo E.07.
--'|E.10|'||
         RPAD(SUBSTRING((SELECT RESULT FROM SP_TIRATODOSSINAIS
                         (COALESCE(atv.bdCODMUNATVM,''))) FROM 3 FOR 2),2,' ')||-- E.10    34 - 35   Caracter(2)   Código do Sub-item da Lista de Serviços (Lei Complementar 116/2003).                                                            Campo Obrigatório somente quando o serviço prestado caracterizar substituição tributária / retenção órgão público, de acordo com o campo E.07
--'|E.11|'||
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                                  (COALESCE(i.bdVLRCONTAB,0))), 15, '0')||      -- E.11    36 - 50   Numérico(15)  Valor do documento emitido.                                                                                                     Campo Obrigatório
--'|E.12|'||
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                                  (COALESCE(i.bdACREDEDUIRSER,0))), 15, '0')||  -- E.12    51 - 65   Numérico(15)  Valor de dedução do documento emitido conforme legislação tributária municipal pertinente.                                      Campo Obrigatório. Obs.: Caso não tenha valor de dedução informar 0 (zero).
--'|E.13|'||
         LPAD(SUBSTRING((SELECT RESULT FROM SP_TIRATODOSSINAIS
                          (COALESCE(ter.bdIMTER,''))) FROM 1 FOR 8),  10, '0')||-- E.13    66 - 75   Numérico(10)  Número da inscrição municipal do tomador de serviço.                                                                            Formato: 9999999999 Ex. 154-3 No arquivo ficará: 0000001543
                                                                                --                                                                                                                                                                 Obs.: quando este campo for informado torna-se desnecessário os dados dos campos E.17 a E.24
                                                                                --                                                                                                                                                                 Este número quando informado, obrigatoriamente deverá ser diferente do campo informado em H.02
--'|E.14|'||
         IIF((CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(ter.bdCGCTER,'')))) >= 14),
              LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                                       (COALESCE(ter.bdCGCTER,''))), 14, '0'),  -- E.14    76 - 89   Numérico(14)  Número do CNPJ do tomador de serviço quando este for Pessoa Jurídica                                                            Obs.: este número quando informado, obrigatoriamente deverá ser diferente do campo informado em H.03.
               LPAD('',14,'0') )||                                              --                                                                                                                                                                 Campo obrigatório somente quando o campo E.07 = Substituição tributária / retenção fonte órgão público
--'|E.15|'||
         IIF((CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(ter.bdCGCTER,'')))) < 14),
              LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                                       (COALESCE(ter.bdCGCTER,''))), 11, '0'),  -- E.15    90 - 100  Numérico(11)  Número do CPF do tomador de serviço quando este for Pessoa Física                                                               Obs.: se os campos E.13 e E.14 não forem informados então este campo torna-se obrigatório, exceto quando o tomador de serviço for uma pessoa física sem identificação.
               LPAD('',11,'0') )||                                              --                                                                                                                                                                 Este número quando informado, obrigatoriamente deverá ser diferente do campo informado em H.04.
--'|E.16|'||
         RPAD(SUBSTRING(COALESCE(ter.bdNOMETER,'') FROM 1 FOR 100), 100, ' ')|| -- E.16   101 - 200  Varchar(100)  Nome ou Razão Social do tomador de serviço                                                                                      Campo Obrigatório, exceto quando o tomador de serviço for uma pessoa física sem identificação.
--'|E.17|'||
         RPAD((CASE                                                             -- E.17   201 - 205  Caracter(5)   Identificação do Tipo do Logradouro do Endereço do tomador de serviço                                                           Ex.: de Siglas a serem utilizadas:
                 WHEN ter.bdLOGRTER = 'Avenida'    THEN 'AV.'                   --                                                                                                                                                                       AV.   Avenida
                 WHEN ter.bdLOGRTER = 'Rótula'     THEN 'ROT.'                  --                                                                                                                                                                       ROT.  Rótula
                 WHEN ter.bdLOGRTER = 'Rua'        THEN 'R.'                    --                                                                                                                                                                       R.    Rua
                 WHEN ter.bdLOGRTER = 'Travessa'   THEN 'TV.'                   --                                                                                                                                                                       TV.   Travessa
                 WHEN ter.bdLOGRTER = 'Alameda'    THEN 'AL.'                   --                                                                                                                                                                       AL.   Alameda
                 WHEN ter.bdLOGRTER = 'Estrada'    THEN 'EST.'                  --                                                                                                                                                                       EST.  Estrada
                 WHEN ter.bdLOGRTER = 'Rodovia'    THEN 'ROD.'                  --                                                                                                                                                                       ROD.  Rodovia
                 WHEN ter.bdLOGRTER = 'Variante'   THEN 'VAR.'                  --                                                                                                                                                                       VAR.  Variante
                 WHEN ter.bdLOGRTER = 'Praça'      THEN 'PC.'                   --                                                                                                                                                                       PC.   Praça
                 WHEN ter.bdLOGRTER = 'Largo'      THEN 'LG.'                   --                                                                                                                                                                       LG.   Largo
                 WHEN ter.bdLOGRTER = 'Jardinete'  THEN 'JDTE.'                 --                                                                                                                                                                       JDTE. Jardinete
                 WHEN ter.bdLOGRTER = 'Parque'     THEN 'PQ.'                   --                                                                                                                                                                       PQ.   Parque
                 WHEN ter.bdLOGRTER = 'Rio'        THEN 'RIO'                   --                                                                                                                                                                       RIO   Rio
                 WHEN ter.bdLOGRTER = 'Terminal'   THEN 'TER.'                  --                                                                                                                                                                       TER.  Terminal
                 WHEN ter.bdLOGRTER = 'Alto'       THEN 'AT.'                   --                                                                                                                                                                       AT.   Alto
                 WHEN ter.bdLOGRTER = 'Beco'       THEN 'BC.'                   --                                                                                                                                                                       BC.   Beco
                 WHEN ter.bdLOGRTER = 'Conjunto'   THEN 'CJTO.'                 --                                                                                                                                                                       CJTO. Conjunto
                 WHEN ter.bdLOGRTER = 'Galeria'    THEN 'GL.'                   --                                                                                                                                                                       GL.   Galeria
                 WHEN ter.bdLOGRTER = 'Granja'     THEN 'GR.'                   --                                                                                                                                                                       GR.   Granja
                 WHEN ter.bdLOGRTER = 'Lagoa'      THEN 'LA'                    --                                                                                                                                                                       LA    Lagoa
                 WHEN ter.bdLOGRTER = 'Ladeira'    THEN 'LD.'                   --                                                                                                                                                                       LD.   Ladeira
                 WHEN ter.bdLOGRTER = 'Loteamento' THEN 'LT.'                   --                                                                                                                                                                       LT.   Loteamento
                 WHEN ter.bdLOGRTER = 'Paço'       THEN 'PÇ'                    --                                                                                                                                                                       PÇ    Paço
                 WHEN ter.bdLOGRTER = 'Vila'       THEN 'VILA'                  --                                                                                                                                                                       VILA  Vila
                 WHEN ter.bdLOGRTER = 'Salina'     THEN 'SL.'                   --                                                                                                                                                                       SL.   Salina
                 WHEN ter.bdLOGRTER = 'Sítio'      THEN 'SIT.'                  --                                                                                                                                                                       SIT.  Sítio
                 WHEN ter.bdLOGRTER = 'Viela'      THEN 'VEL.'                  --                                                                                                                                                                       VEL.  Viela
                 WHEN ter.bdLOGRTER = 'Viaduto'    THEN 'VIAD.'                 --                                                                                                                                                                       VIAD. Viaduto
                 WHEN ter.bdLOGRTER = 'Servidão'   THEN 'SER.'                  --                                                                                                                                                                       SER.  Servidão
                 WHEN ter.bdLOGRTER = 'Jardim'     THEN 'JAR.'                  --                                                                                                                                                                       JAR.  Jardim
               ELSE '' END),5,' ')||
--'|E.18|'||
         RPAD(SUBSTRING(COALESCE(ter.bdENDTER,'') FROM 1 FOR 50), 50, ' ')||    -- E.18   206 - 255  Caracter(50)  Nome do Logradouro do Endereço do tomador de serviço
--'|E.19|'||
         RPAD(SUBSTRING(COALESCE(ter.bdNUMTER,'') FROM 1 FOR 6), 6, ' ')||      -- E.19   256 - 261  Caracter(6)   Número do Endereço do tomador de serviço
--'|E.20|'||
         RPAD(SUBSTRING(COALESCE(ter.bdCOMPTER,'') FROM 1 FOR 20), 20, ' ')||   -- E.20   262 - 281  Caracter(20)  Complemento do Endereço do tomador de serviço
--'|E.21|'||
         RPAD(SUBSTRING(COALESCE(ter.bdBAITER,'') FROM 1 FOR 50), 50, ' ')||    -- E.21   282 - 331  Caracter(50)  Bairro do Endereço do tomador de serviço
--'|E.22|'||
         RPAD(SUBSTRING(COALESCE(terCid.bdNOMCID,'') FROM 1 FOR 44), 44, ' ')|| -- E.22   332 - 375  Caracter(44)  Cidade do Endereço do tomador de serviço
--'|E.23|'||
         RPAD(SUBSTRING(COALESCE(terUF.bdSIGLAUF,'') FROM 1 FOR 2), 2, ' ')||   -- E.23   376 - 377  Caracter(2)   Estado da Cidade do Endereço do tomador de serviço
--'|E.24|'||
         LPAD(SUBSTRING((SELECT RESULT FROM SP_TIRATODOSSINAIS
                           (COALESCE(ter.bdCEPTER,''))) FROM 1 FOR 8), 8, '0')||-- E.24   378 - 385  Numérico(8)   Cep do Endereço do tomador de serviço
--'|E.25|'||
         LPAD(COALESCE((SELECT COUNT(*)
                        FROM TEXPORTACAO_ISS_CURITIBA),1), 6, '0')||            -- E.25   386 - 391  Numérico(6)   Número seqüencial do registro dentro do arquivo                                                                                 Campo Obrigatório Formato: 999999
--'|E.26|'||
         LPAD(SUBSTRING((SELECT RESULT
                         FROM SP_TIRATODOSSINAIS(
                                                 CASE
                                                   WHEN s.bdTIPLAN = 0 THEN -- Emitidos
                                                     CASE WHEN ic.bdCODIDNF = 0 THEN -- N – Doc.Fiscal Normal
                                                       IIF((i.bdALIQREDISSSER < 10), '0'||i.bdALIQREDISSSER, i.bdALIQREDISSSER)
                                                     ELSE '' END
                                                   WHEN s.bdTIPLAN = 1 THEN -- Recebidos
                                                     CASE WHEN ic.bdCODIDNF <> 0 THEN -- N – Doc.Fiscal Normal
                                                       IIF((i.bdALIQREDISSSER < 10), '0'||i.bdALIQREDISSSER, i.bdALIQREDISSSER)
                                                     ELSE '' END
                                                 ELSE '' END))
              FROM 1 FOR 4), 4, '0')||                                          -- E.26   392 - 395  Numérico(4)   Valor percentual da Alíquota                                                                                                    Campo Obrigatório somente quando o serviço tomador NÃO caracterizar Substituição Tributária / Retenção Órgão Público, retenção na fonte conforme item E.07.
                                                                                --                                                                                                                                                                 Caso contrário o campo deve vir preenchido com 0000.
                                                                                --                                                                                                                                                                 Quando esta informação for obrigatória então o valor deve ser maior que 0000.
                                                                                --                                                                                                                                                                 Exemplo quando a alíquota for 5%: 0500
--'|E.27|'||
         '.'                                                                    -- E.27   396 - 396  Caracter(1)   Caracter fixo = . (ponto)                                                                                                       Campo obrigatório que indica o final do registro.
  FROM VEF_EMP_TMOVSER s
  JOIN VEF_EMP_TMOVSERITENS i ON (i.bdCODEMP = s.bdCODEMP AND i.bdCHAVE = s.bdCHAVE)
  LEFT OUTER JOIN TATVMUNICIPAL atv ON (atv.BDCODATVM = i.BDCODATVM)
  LEFT OUTER JOIN VEF_EMP_TMOVSERITENSCUR ic ON (ic.bdCODEMP = s.bdCODEMP AND ic.bdCHAVE = s.bdCHAVE AND ic.bdORDEM = i.bdORDEM)
  LEFT OUTER JOIN VEF_BASE_TTABTPNF tpnf ON (tpnf.bdCODTPNF = s.bdCODTPNF)
  LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.bdCODTER = s.bdCODTER)
  LEFT OUTER JOIN TCIDADE terCid ON (terCid.bdCODCID = ter.bdCODCID)
  LEFT OUTER JOIN TUF terUF ON (terUF.bdCODUF = terCid.bdCODUF)
  WHERE s.bdCODEMP = :prCODEMP
    AND s.bdCODSITNF NOT IN (2,3,4,5) -- Notas canceladas
    AND s.bdTIPLAN = :prTIPOLANCEXP
    AND s.bdDATAEMISSAO BETWEEN :prDTINI AND :prDTFIM
  ORDER BY i.bdCODEMP, i.bdCHAVE, i.bdORDEM;

END
^

CREATE OR ALTER procedure SP_EXPORTA_ISS_RECIFE (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRDTINI date,
    PRDTFIM date,
    PRTIPOLANC integer,
    PRRETIFICADORA integer,
    PRARQUIVO varchar(260))
as
declare variable WORDEM integer;
declare variable WLINHA blob sub_type 1 segment size 200 character set UTF8;
declare variable WQTDE integer;
BEGIN
  IF (:prTIPOLANC = 1) THEN -- Somente emitidos
    EXIT; -- Apenas serviços tomados/recebidos...

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  /******************************************************************************
   *                              TIPO 10 - HEADER                              *
   *****************************************************************************/ 
  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_ISS_RECIFE (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, 10, GETORDEMSEQUENCIAL(:WORDEM),
           '10' ||    -- 1 Tipo de registro
           '003' || -- 2 Versão do Arquivo
           IIF(STRLEN(EMP.BDCNPJEMP) = 18,'2','1') || -- 3 Identificação CPF ou CNPJ do Contribuinte / 1 - CPF, 2 - CNPJ
           RPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS(EMP.BDCNPJEMP)),14,' ') || -- 4 CPF ou CNPJ do Contribuinte
           RPAD(Coalesce((SELECT RESULT FROM SP_TIRATODOSSINAIS(REF.BDIMEMP)),''),15,' ') || -- 5 Inscrição Municipal do Contribuinte
           (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMMDD')) || -- 6 Data de Início do Período Transferido no Arquivo / AAAAMMDD
           (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMMDD')) || -- 7 Data de Fim do Período Transferido no Arquivo / AAAAMMDD
           '' -- 8 Caractere de Fim de Linha
  FROM TEMPRESAS EMP
  LEFT OUTER JOIN VW_TEMPRESAS_REF REF ON (REF.BDCODEMP = EMP.BDCODEMP)
  WHERE EMP.BDCODEMP = :PRCODEMP;


  /*****************************************************************************
   *                                TIPO 40                                    *
   ****************************************************************************/
   IF (:PRTIPOLANC IN (0,2)) THEN
     BEGIN
       SETORDEMSEQUENCIAL(0);
       INSERT INTO TEXPORTACAO_ISS_RECIFE (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDVLRSER, BDVLRDED, BDVLRDESC_COND, BDVLRDESC_INCOND, BDLINHA)
       SELECT :prARQUIVO, MOV.bdCODEMP, 40, GETORDEMSEQUENCIAL(:WORDEM),
              I.BDVLRCONTAB,
              I.BDDESCONTO,
              0,
              0,
              '40'|| -- 1-Tipo de Registro
              '01'|| -- 2 - Tipo de Documento
              RPAD(SUBSTRING(MOV.BDSERIE FROM 1 FOR 5),5,' ')|| -- 3 - Série do Documento
              LPAD(SUBSTRING(MOV.BDNUMDOCINI FROM 1 FOR 15),15,' ')|| -- 4 - Número do Documento
              (SELECT BDDATA FROM SP_PARSE_DATE(MOV.BDDATAEMISSAO, 'YYYYMMDD'))|| -- 5 - Data de Emissão
              IIF(MOV.bdCODSITNF IN (2,3,4,5),'2','1')|| -- 6 -  Status do Documento / 1 - Normal; 2 - Cancelado
              IIF(STRLEN(Coalesce(TER.BDCGCTER,'')) = 18,'2','1')|| -- 7 - Identificação de CPF ou CNPJ do Prestador
              LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS(IIF(TER.BDCODPAIS = 30,TER.BDCGCTER,'99999999050'))),14,'0') || -- 8 - CPF ou CNPJ do Prestador
              /*Apagar*/  --  RPAD(Coalesce((SELECT bdNUMERO FROM SP_RETORNA_NUMEROS(SUBSTRING(TER.BDIMTER FROM 1 FOR 15))),''),15,' ')|| -- 9 - Inscrição Municipal do Prestador
              RPAD(Coalesce((SELECT first 0 bdNUMERO FROM SP_RETORNA_NUMEROS(SUBSTRING(TER.BDIMTER FROM 1 FOR 15))),''),15,' ')||
              RPAD(Coalesce((SELECT bdNUMERO FROM SP_RETORNA_NUMEROS(SUBSTRING(TER.BDIETER FROM 1 FOR 15))),''),15,' ')|| -- 10 - Inscrição Estadual do Prestador
              RPAD(Coalesce(SUBSTRING(TER.BDNOMETER FROM 1 FOR 115),''),115,' ')|| -- 11 - Nome ou Razão Social do Prestador
              RPAD(Coalesce(CASE
                      WHEN ter.bdLOGRTER = 'Avenida'    THEN 'AV'
                      WHEN ter.bdLOGRTER = 'Rótula'     THEN 'ROT'
                      WHEN ter.bdLOGRTER = 'Rua'        THEN 'RUA'
                      WHEN ter.bdLOGRTER = 'Travessa'   THEN 'TV'
                      WHEN ter.bdLOGRTER = 'Alameda'    THEN 'AL'
                      WHEN ter.bdLOGRTER = 'Estrada'    THEN 'EST'
                      WHEN ter.bdLOGRTER = 'Rodovia'    THEN 'ROD'
                      WHEN ter.bdLOGRTER = 'Variante'   THEN 'VAR'
                      WHEN ter.bdLOGRTER = 'Praça'      THEN 'PC'
                      WHEN ter.bdLOGRTER = 'Largo'      THEN 'LG'
                      WHEN ter.bdLOGRTER = 'Jardinete'  THEN 'JDT'
                      WHEN ter.bdLOGRTER = 'Parque'     THEN 'PQ'
                      WHEN ter.bdLOGRTER = 'Rio'        THEN 'RIO'
                      WHEN ter.bdLOGRTER = 'Terminal'   THEN 'TER'
                      WHEN ter.bdLOGRTER = 'Alto'       THEN 'AT'
                      WHEN ter.bdLOGRTER = 'Beco'       THEN 'BC'
                      WHEN ter.bdLOGRTER = 'Conjunto'   THEN 'CJT'
                      WHEN ter.bdLOGRTER = 'Galeria'    THEN 'GL'
                      WHEN ter.bdLOGRTER = 'Granja'     THEN 'GR'
                      WHEN ter.bdLOGRTER = 'Lagoa'      THEN 'LA'
                      WHEN ter.bdLOGRTER = 'Ladeira'    THEN 'LD'
                      WHEN ter.bdLOGRTER = 'Loteamento' THEN 'LT'
                      WHEN ter.bdLOGRTER = 'Paço'       THEN 'PÇ'
                      WHEN ter.bdLOGRTER = 'Vila'       THEN 'VIL'
                      WHEN ter.bdLOGRTER = 'Salina'     THEN 'SL'
                      WHEN ter.bdLOGRTER = 'Sítio'      THEN 'SIT'
                      WHEN ter.bdLOGRTER = 'Viela'      THEN 'VEL'
                      WHEN ter.bdLOGRTER = 'Viaduto'    THEN 'VIA'
                      WHEN ter.bdLOGRTER = 'Servidão'   THEN 'SER'
                      WHEN ter.bdLOGRTER = 'Jardim'     THEN 'JAR'
                    ELSE '' END, ''),3,' ')||  -- 12 - Tipo de endereço
              RPAD(SUBSTRING(COALESCE(ter.bdENDTER,'') FROM 1 FOR 125), 125, ' ')||  -- 13 -  Endereço do Prestador
              RPAD(SUBSTRING(COALESCE(ter.bdNUMTER,'') FROM 1 FOR 10), 10, ' ')||    -- 14 - Número do Endereço do Prestador
              RPAD(SUBSTRING(COALESCE(ter.bdCOMPTER,'') FROM 1 FOR 60), 60, ' ')||   -- 15 - Complemento do Endereço do Prestador
              RPAD(SUBSTRING(COALESCE(ter.bdBAITER,'') FROM 1 FOR 72), 72, ' ')||    -- 16 - Bairro do Prestador
              RPAD(SUBSTRING(COALESCE(terCid.bdNOMCID,'') FROM 1 FOR 50), 50, ' ')|| -- 17 - Cidade do Prestador
              RPAD(SUBSTRING(COALESCE(terUF.bdSIGLAUF,'') FROM 1 FOR 2), 2, ' ')||   -- 18 - UF do Prestador
              LPAD(SUBSTRING((SELECT RESULT FROM SP_TIRATODOSSINAIS
                                (COALESCE(ter.bdCEPTER,''))) FROM 1 FOR 8), 8, '0')||-- 19 - CEP do Prestador   
              RPAD(SUBSTRING(COALESCE(Coalesce(LPAD(ter.BDDDDTER,3,'0'),'')||(SELECT RESULT FROM SP_TIRATODOSSINAIS(ter.BDFONETER)),'') FROM 1 FOR 11),11, ' ')||   -- 20 - Telefone de Contato do Prestador
              RPAD(SUBSTRING(COALESCE(ter.BDEMAILTER,'') FROM 1 FOR 80), 80, ' ')||   -- 21 - E-mail do Prestador
              Coalesce(LPAD(iss.BDCODTPTRIB,2,'0'), '00')||  -- 22 -  Tipo de Tributação de Serviços
              RPAD('',54,' ')|| -- 23 - Reservado
              IIF(COALESCE(TER.BDRECOLHEGUIAMUN,'') = 'TRUE','2',IIF(TER.BDENQSIMPLESFEDTER IN (0,1),'1','0')) || -- 24 - Opção pelo simples
              LPAD(Coalesce((SUBSTRING((SELECT RESULT FROM SP_TIRATODOSSINAIS(ATV.BDCODMUNATVM)) FROM 1 FOR 4)),''),4,'0') || -- 25 - Item da Lista de Serviços-LC 116/03 (Código do Serviço Federal)
              RPAD(Coalesce(SUBSTRING(ATV.BDIDCNAE FROM 1 FOR 20),''),20,' ') || -- 26.C - CNAE -Código da Classificação Nacional de Atividades Econômicas (Código do Serviço Municipal)
              LPAD(Coalesce((SELECT RESULT FROM SP_TIRATODOSSINAIS(Cast(ATV.BDALIQATVM as NUMERIC(15,2)))),''),5,'0') || -- 27 - Alíquota
              LPAD(Coalesce((SELECT RESULT FROM SP_TIRATODOSSINAIS(I.BDVLRCONTAB)),''),15,'0') || -- 28 - Valor dos Serviços
              LPAD(Coalesce((SELECT RESULT FROM SP_TIRATODOSSINAIS(I.BDDESCONTO)),''),15,'0') || -- 29 - Valor das Deduções
              RPAD('',30,' ')|| -- 30 - Reservado 
              LPAD(Coalesce((SELECT RESULT FROM SP_TIRATODOSSINAIS(I.BDVLRISSSER)),''),15,'0') || -- 31 - Valor do ISS
              IIF(Coalesce(ret.BDISSRET,0) > 0,'1','0') || -- 32 - ISS Retido
              IIF(Coalesce(ret.BDISSRET,0) > 0,(SELECT BDDATA FROM SP_PARSE_DATE(MOV.BDDATALAN, 'YYYYMM')) || LPAD((SELECT ULTDIA FROM ULTIMO_DIA_MES(EXTRACT(MONTH FROM MOV.bddatalan),EXTRACT(year FROM MOV.bddatalan))),2,'0'),(SELECT BDDATA FROM SP_PARSE_DATE(MOV.BDDATAEMISSAO, 'YYYYMM')) || LPAD((SELECT ULTDIA FROM ULTIMO_DIA_MES(EXTRACT(MONTH FROM MOV.bddatalan),EXTRACT(year FROM MOV.bddatalan))),2,'0')) || -- 33 - Data de Competência, trás o último dia do mês selecionado
              RPAD('',30,' ') || -- 34 - Reservado
              RPAD('',15,' ') || -- 35 - Código da Obra
              RPAD('',15,' ') || -- 36 - Anotação de Responsabilidade Técnica
              SUBSTRING('' FROM 1 FOR 4000) || -- 37 - Discriminação dos Serviços
              ''  -- 38 - Fim de linha
       FROM VEF_EMP_TMOVSER MOV
       JOIN VEF_EMP_TMOVSERITENS i ON (i.bdCODEMP = MOV.bdCODEMP AND i.bdCHAVE = MOV.bdCHAVE)
       LEFT OUTER JOIN TATVMUNICIPAL atv ON (atv.BDCODATVM = i.BDCODATVM)
       LEFT OUTER JOIN VEF_BASE_TTABTPNF tpnf ON (tpnf.bdCODTPNF = MOV.bdCODTPNF)
       LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.bdCODTER = MOV.bdCODTER)
       LEFT OUTER JOIN TCIDADE terCid ON (terCid.bdCODCID = ter.bdCODCID)
       LEFT OUTER JOIN TUF terUF ON (terUF.bdCODUF = terCid.bdCODUF)
       LEFT OUTER JOIN VEF_EMP_TMOVSERRET ret ON (ret.BDCODEMP = MOV.BDCODEMP AND ret.BDCHAVE = MOV.BDCHAVE)
       LEFT OUTER JOIN VEF_EMP_TMOVSERDED DED ON (DED.BDCODEMP = MOV.BDCODEMP AND DED.BDCHAVE = MOV.BDCHAVE)
       LEFT OUTER JOIN VEF_EMP_TMOVSERRECIFE iss ON (iss.BDCODEMP = MOV.BDCODEMP AND iss.BDCHAVE = MOV.BDCHAVE)
       WHERE MOV.bdCODEMP = :prCODEMP
         AND MOV.bdTIPLAN = 1
         AND MOV.bddataEMISSAO BETWEEN :prDTINI AND :prDTFIM
       ORDER BY i.bdCODEMP, i.bdCHAVE, i.bdORDEM;
     END

  SELECT COUNT(r.bdORDEM)
  FROM TEXPORTACAO_ISS_RECIFE r
  WHERE r.bdID = :prARQUIVO
    AND r.bdCODEMP = :prCODEMP
    AND r.bdORDEMREG = 40
  INTO wQTDE;

  /* Caso não existam registros no grupo 40, não exporta nada...
     O registro 40 segndo o manual é opcional, porém é obrigatório exportar algm registro detalhe, como o único registro detalhe que exportamos é o 40, caso ele não vá no arquivo dá erro no validador.
     "Detalhe 202 Arquivo sem linhas de detalhe. Incluir os registros de detalhe (tipo 20 e/ou 30 e/ou 40) no arquivo. Verifique se os terminadores de linha estão preenchidos corretamente (conjunto de caracteres chr(13) seguido do chr(10)) em todos os registros." */
  IF (wQTDE = 0) THEN
    BEGIN
      DELETE FROM TEXPORTACAO_ISS_RECIFE;

      EXIT;
    END

  /*****************************************************************************
   *                                TIPO 90                                    *
   ****************************************************************************/   
  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_ISS_RECIFE (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, 90, GETORDEMSEQUENCIAL(:WORDEM),
           '90' ||    -- 1 Tipo de registro
           LPAD(EXP.BDCOUNT,8,'0') || -- 2 Número de linhas de detalhe do arquivo
           LPAD(Coalesce((SELECT RESULT FROM SP_TIRATODOSSINAIS(EXP.BDVLRSER)),''),15,'0') || -- 3 Valor total dos serviços contido no arquivo
           LPAD(Coalesce((SELECT RESULT FROM SP_TIRATODOSSINAIS(EXP.BDVLRDED)),''),15,'0') || -- 4 Valor total das deduções contidas no arquivo
           LPAD(Coalesce((SELECT RESULT FROM SP_TIRATODOSSINAIS(EXP.BDVLRDESC_COND)),''),15,'0') || -- 5 Valor total dos descontos condicionados contidos no arquivo
           LPAD(Coalesce((SELECT RESULT FROM SP_TIRATODOSSINAIS(EXP.BDVLRDESC_INCOND)),''),15,'0') || -- 6 Valor total dos descontos incondicionados contidos no arquivo
           '' -- 7 Caractere de Fim de Linha
  FROM (SELECT COUNT(BDCODEMP) BDCOUNT, SUM(Coalesce(BDVLRSER,0)) BDVLRSER, SUM(Coalesce(BDVLRDED,0)) BDVLRDED,
               SUM(Coalesce(BDVLRDESC_COND,0)) BDVLRDESC_COND, SUM(Coalesce(BDVLRDESC_INCOND,0)) BDVLRDESC_INCOND
        FROM TEXPORTACAO_ISS_RECIFE
        WHERE BDORDEMREG = 40) EXP;

  /*****************************************************************************
   *                           EXPORTANDO ARQUIVO                              *
   ****************************************************************************/
  OPENARQ(:prARQUIVO,:PRCODEMP);

  FOR
    SELECT e.bdLINHA
    FROM TEXPORTACAO_ISS_RECIFE E
    WHERE e.bdID = :prARQUIVO
    ORDER BY e.bdORDEMREG, e.bdORDEM
    INTO :wLINHA
  DO
    BEGIN
      WRITELNOA(:WLINHA,:PRCODEMP);
    END

  CLOSEARQ(:prARQUIVO,:PRCODEMP);

  DELETE FROM TEXPORTACAO_ISS_RECIFE;

END^




CREATE OR ALTER procedure SP_EXPORTA_ISS_CURITIBA (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRDTINI date,
    PRDTFIM date,
    PRTIPOLANC integer,
    PRRETIFICADORA integer,
    PRARQUIVO varchar(260))
as
declare variable WLINHA blob sub_type 1 segment size 200 character set UTF8;
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- REGISTRO HEADER – “H”
  INSERT INTO TEXPORTACAO_ISS_CURITIBA (bdID, bdCODEMP, bdORDEMREG, bdORDEM, bdLINHA)
  SELECT :prARQUIVO, r.bdCODEMP, 1, '000000',                                   -- CAMPOS  POSIÇÕES  TIPO/TAMANHO  DESCRIÇÃO                                                                      OBSERVAÇÕES
--SELECT :prARQUIVO, r.bdCODEMP, 1, r.bdCODEMP,                                 -- CAMPOS  POSIÇÕES  TIPO/TAMANHO  DESCRIÇÃO                                                                      OBSERVAÇÕES
         'H'||                                                                  -- H.01     1 -   1  Caracter(1)   Código do registro “H”                                                         Campo Obrigatório
         LPAD(RIGHT((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(r.bdIMEMP,'')))
                     ,8), 10, '0')||         -- H.02     2 -  11  Numérico(10)  Número da Inscrição Municipal do Declarante                                    Formato: 9999999999 Exemplo: 65985-1 No arquivo ficará: 0000659851 Campo Não Obrigatório.
         LPAD(IIF(CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(r.bdCNPJEMP,'')))) >= 14,
                  (SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(r.bdCNPJEMP,''))),
                  ''), 14, '0')||                                               -- H.03    12 -  25  Numérico(14)  Número do CNPJ do Declarante no caso de pessoa jurídica                        Formato: 99999999999999 Campo Obrigatório quando o campo H.02 ou H.04 não for preenchido
         LPAD(IIF(CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(r.bdCNPJEMP,'')))) < 14,
                  (SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(r.bdCNPJEMP,''))),
                  ''), 11, '0')||                                               -- H.04    26 -  36  Numérico(11)  Número do CPF do Declarante no caso de pessoa física                           Obs.: Se o campo H.02 ou H.03 não for informado, então este campo será obrigatório Formato: 99999999999
         RPAD(COALESCE(r.bdNOMEMP,''), 100, ' ')||                              -- H.05    37 - 136  Caracter(100) Nome/Razão Social do Declarante                                                Campo Obrigatório.
         'N'||                                                                  -- H.06   137 - 137  Caracter(1)   Tipo do Arquivo enviado para a Prefeitura, podendo ser: N – normal, T – Teste  Campo Obrigatório.
         SUBSTRING(:prREFERENCIA FROM 5 FOR 2)||                                -- H.07   138 - 139  Numérico (2)  Mês de referência dos documentos declarados                                    Campo Obrigatório.
         SUBSTRING(:prREFERENCIA FROM 1 FOR 4)||                                -- H.08   140 - 143  Numérico(4)   Ano de referência dos documentos declarados                                    Campo Obrigatório.
         RPAD('', 252, ' ')||                                                   -- H.09   144 - 395  Caracter(252) Brancos – reservado para futuro                                                Campo Obrigatório.
         '.'                                                                    -- H.10   396 - 396  Caracter(1)   Caracter fixo = . (ponto)                                                      Campo obrigatório que indica o final do registro.
  FROM VW_EMPRESAS_REF_ATUAL r
  WHERE r.bdCODEMP = :prCODEMP;

  -- REGISTRO DOCUMENTOS EMITIDOS CANCELADOS – “C”
  INSERT INTO TEXPORTACAO_ISS_CURITIBA (bdID, bdCODEMP, bdORDEMREG, bdORDEM, bdLINHA)
  SELECT :prARQUIVO, s.bdCODEMP, 2, LPAD(COALESCE((SELECT COUNT(*)              -- CAMPOS  POSIÇÕES  TIPO/TAMANHO  DESCRIÇÃO                                        OBSERVAÇÕES
                                                   FROM TEXPORTACAO_ISS_CURITIBA WHERE bdID = :prARQUIVO),1), 6, '0'),
--SELECT :prARQUIVO, s.bdCODEMP, 2, s.bdCODEMP||'.'||s.bdCHAVE,                 -- CAMPOS  POSIÇÕES  TIPO/TAMANHO  DESCRIÇÃO                                        OBSERVAÇÕES
         'C'||                                                                  -- C.01     1 -   1  Caracter(1)   Código do registro “C”                           Campo Obrigatório
         COALESCE((SUBSTRING(s.bdDATACANC FROM 9 FOR 2)||
                   SUBSTRING(s.bdDATACANC FROM 6 FOR 2)||
                   SUBSTRING(s.bdDATACANC FROM 1 FOR 4)),'00000000')||          -- C.02     2 -   9  Numérico(8)   Data do cancelamento  da nota fiscal emitida.    Campo Obrigatório Formato: DDMMAAAAA
         LPAD(SUBSTRING(COALESCE(s.bdNUMDOCINI,'') FROM 1 FOR 8), 8, '0')||     -- C.03    10 -  17  Numérico(8)   Número da nota fiscal inicial cancelada          Campo Obrigatório
         LPAD(SUBSTRING(COALESCE(s.bdNUMDOCFIM,'') FROM 1 FOR 8), 8, '0')||     -- C.04    18 -  25  Numérico(8)   Número da nota fiscal final cancelada            Deverá ser informado somente quando houver um agrupamento de notas canceladas.
         RPAD(SUBSTRING(COALESCE(s.bdSERIE,'') FROM 1 FOR 3), 3, ' ')||         -- C.05    26 -  28  Caracter(3)   Série da Nota Fiscal cancelada                   Campo Obrigatório
         RPAD('', 361, ' ')||                                                   -- C.06    29 - 389  Caracter(361) Reservado para futuro
         LPAD(COALESCE((SELECT COUNT(*)
                        FROM TEXPORTACAO_ISS_CURITIBA),1), 6, '0')||            -- C.07   390 - 395  Numérico(6)   Número seqüencial do registro dentro do arquivo. Campo Obrigatório.
         '.'                                                                    -- C.08   396 - 396  Caracter(1)   Caracter fixo = . (ponto)                        Campo obrigatório que indica o final do registro.
  FROM VEF_EMP_TMOVSER s
  WHERE s.bdCODEMP = :prCODEMP
    AND s.bdTIPLAN = 0 -- Apenas serviços Emitidos
    AND s.bdCODSITNF IN (2,3,4,5) -- Notas canceladas
    AND s.bdDATAEMISSAO BETWEEN :prDTINI AND :prDTFIM;

  -- REGISTRO DOCUMENTOS EMITIDOS DECLARADOS – “E”
  IF (:prTIPOLANC IN (0,1)) THEN -- 0 = Ambos (emitidos/recebidos) / 1 = Somente emitidos
    EXECUTE PROCEDURE SP_EXPORTA_ISS_CURITIBA_REG_E_R (:prCODEMP, :prREFERENCIA, :prDTINI, :prDTFIM, :prTIPOLANC, :prRETIFICADORA, :prARQUIVO, 0);

  -- REGISTRO DOCUMENTOS RECEBIDOS DECLARADOS – “R”
  IF (:prTIPOLANC IN (0,2)) THEN -- 0 = Ambos (emitidos/recebidos) / 2 = Somente recebidos
    EXECUTE PROCEDURE SP_EXPORTA_ISS_CURITIBA_REG_E_R (:prCODEMP, :prREFERENCIA, :prDTINI, :prDTFIM, :prTIPOLANC, :prRETIFICADORA, :prARQUIVO, 1);

  -- REGISTRO HEADER – “T”
  INSERT INTO TEXPORTACAO_ISS_CURITIBA (bdID, bdCODEMP, bdORDEMREG, bdORDEM, bdLINHA)
  SELECT :prARQUIVO, c.bdCODEMP, 5, LPAD(COALESCE((SELECT COUNT(*)              -- CAMPOS  POSIÇÕES  TIPO/TAMANHO  DESCRIÇÃO                                                                                                                        OBSERVAÇÕES
                                                   FROM TEXPORTACAO_ISS_CURITIBA WHERE bdID = :prARQUIVO),1), 6, '0'),
--SELECT :prARQUIVO, c.bdCODEMP, 5, c.bdCODEMP,                                 -- CAMPOS  POSIÇÕES  TIPO/TAMANHO  DESCRIÇÃO                                                                                                                        OBSERVAÇÕES
         'T'||                                                                  -- T.01     1 -   1  Caracter(1)   Código do registro “T”                                                                                                           Campo Obrigatório
         LPAD(COUNT(*)+1, 8, '0')||                                             -- T.02     2 -   9  Numérico(8)   Quantidade total de registros do arquivo, incluindo o header (H) e trailler (T)                                                  Campo Obrigatório
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                             (SUM(COALESCE(c.bdVLREMIT,0)))), 15, '0')||        -- T.03    10 -  24  Numérico(15)  Valor Total dos Documentos emitidos  pelo Prestador de Serviços. Soma de todos os valores descritos nos campos E.11              Campo Obrigatório
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                             (SUM(COALESCE(c.bdVLRDEDEMIT,0)))), 15, '0')||     -- T.04    25 -  39  Numérico(15)  Valor Total das Deduções dos Documentos emitidos pelo Prestador de Serviços. Soma de todos os valores descritos nos campos E.12  Campo Obrigatório
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                             (SUM(COALESCE(c.bdVLRRECEB,0)))), 15, '0')||       -- T.05    40 -  54  Numérico(15)  Valor Total dos Documentos recebidos  pelo tomador de Serviços. Soma de todos os valores descritos nos campos R.11               Campo Obrigatório
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS
                             (SUM(COALESCE(c.bdVLRDEDRECEB,0)))), 15, '0')||    -- T.06    55 -  69  Numérico(15)  Valor Total das Deduções dos Documentos recebidos  pelo tomador de Serviços. Soma de todos os valores descritos nos campos R.12  Campo Obrigatório
         RPAD('', 326, ' ')||                                                   -- T.07    70 - 395  Caracter(326) Brancos – reservado para futuro
         '.'                                                                    -- T.08   396 - 396  Caracter(1)   Caracter fixo = . (ponto)                                                                                                        Campo obrigatório que indica o final do registro.
  FROM TEXPORTACAO_ISS_CURITIBA c
  WHERE c.bdCODEMP = :prCODEMP
  GROUP BY c.bdCODEMP;

  -- Exporta arquivo...
  OPENARQ(:prARQUIVO,:prCODEMP);

  FOR
    SELECT e.bdLINHA
    FROM TEXPORTACAO_ISS_CURITIBA E
    WHERE e.bdID = :prARQUIVO
    ORDER BY e.bdORDEMREG, e.bdORDEM
    INTO :wLINHA
  DO
    BEGIN
      WRITELNOA(:WLINHA,:prCODEMP);
    END

  CLOSEARQ(:prARQUIVO,:prCODEMP);

  DELETE FROM TEXPORTACAO_ISS_CURITIBA;

END
^

CREATE OR ALTER PROCEDURE SP_RETORNA_MAIOR_ZERO (
    PRVALOR NUMERIC(15,2))
RETURNS (
    BDVALOR NUMERIC(15,2))
AS
BEGIN
  BDVALOR = 0;
  IF (PRVALOR > 0) THEN
    BDVALOR = PRVALOR;
  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_ATU_ESTRUTURA_TEMP (
    PRTABELA VARCHAR(63))
AS
declare variable W_COLUMNS varchar(10000);
declare variable W_SQL_CREATE varchar(10000);
declare variable W_COUNT integer;
begin
  /* Vamos primeiro descobrir em qual caminho iremos percorrer*/
  select count(*)
  from RDB$RELATIONS
  where trim(upper(RDB$RELATION_NAME)) = trim(upper('TMP_' || :PRTABELA || '_TEMP')) and
        RDB$SYSTEM_FLAG = 0
  into :W_COUNT; -- Exclui tabelas de sistema

  --Tabela tempor?ria n?o existe, ent?o vamos CRIAR uma
  if (W_COUNT = 0) then
  begin
    --primeiro vamos levantar quais as colunas da tabela...
    select list(TBS.FIELDS, ',')
    from (select trim(F.RDB$FIELD_NAME) || ' ' || iif(substring(F.RDB$FIELD_SOURCE from 1 for 3) <> 'DM_',
                 case
                   when FF.RDB$FIELD_TYPE = 7 then 'SMALLINT'
                   when FF.RDB$FIELD_TYPE = 8 then 'INTEGER'
                   when FF.RDB$FIELD_TYPE = 10 then 'FLOAT'
                   when FF.RDB$FIELD_TYPE = 12 then 'DATE'
                   when FF.RDB$FIELD_TYPE = 13 then 'TIME'
                   when FF.RDB$FIELD_TYPE = 14 then 'DOUBLE PRECISION'
                   when FF.RDB$FIELD_TYPE = 16 then 'BIGINT'
                   when FF.RDB$FIELD_TYPE = 23 then 'BOOLEAN'
                   when FF.RDB$FIELD_TYPE = 27 then 'DOUBLE PRECISION'
                   when FF.RDB$FIELD_TYPE = 35 then 'TIMESTAMP'
                   when FF.RDB$FIELD_TYPE = 37 then 'VARCHAR(' || FF.RDB$CHARACTER_LENGTH || ')'
                   when FF.RDB$FIELD_TYPE = 261 then 'BLOB SUB_TYPE ' || FF.RDB$FIELD_SUB_TYPE || ' SEGMENT SIZE ' || FF.RDB$SEGMENT_LENGTH
                   else 'UNKNOWN'
                 end, '') ||
                 case
                   when substring(F.RDB$FIELD_SOURCE from 1 for 3) = 'DM_' then trim(F.RDB$FIELD_SOURCE)
                   else ''
                 end /*||
                 case
                   when F.RDB$NULL_FLAG = 1 then ' NOT NULL'
                   else ''
                 end*/ as FIELDS,
                 F.RDB$FIELD_POSITION
          from RDB$RELATION_FIELDS F
          join RDB$FIELDS FF on F.RDB$FIELD_SOURCE = FF.RDB$FIELD_NAME
          where F.RDB$RELATION_NAME = trim(upper(:PRTABELA))
          order by 2) TBS
    into :W_COLUMNS;

    W_COLUMNS = 'BDSESSAO INTEGER NOT NULL, BDEDITCHAVE INTEGER, BDROW_EXCLUIDA integer,  ' || :W_COLUMNS;

    --Agora vamos montar os SQLs que far?o o paranau? todo

    --Recria??o da tabela tempor?ria
    W_SQL_CREATE = 'CREATE TABLE TMP_' || :PRTABELA || '_TEMP ( ' || :W_COLUMNS || ')';

    --Senta a lenha no SQL....
    execute statement :W_SQL_CREATE;
  end
  else
  begin
    --a tabela j? existe, logo precisa apenas adicionar os campos novos que foram criados...
    select list('ADD ' || trim(F.RDB$FIELD_NAME) || ' ' || iif(substring(F.RDB$FIELD_SOURCE from 1 for 3) <> 'DM_',
           case
             when FF.RDB$FIELD_TYPE = 7 then 'SMALLINT'
             when FF.RDB$FIELD_TYPE = 8 then 'INTEGER'
             when FF.RDB$FIELD_TYPE = 10 then 'FLOAT'
             when FF.RDB$FIELD_TYPE = 12 then 'DATE'
             when FF.RDB$FIELD_TYPE = 13 then 'TIME'
             when FF.RDB$FIELD_TYPE = 14 then 'DOUBLE PRECISION'
             when FF.RDB$FIELD_TYPE = 16 then 'BIGINT'
             when FF.RDB$FIELD_TYPE = 23 then 'BOOLEAN'
             when FF.RDB$FIELD_TYPE = 27 then 'DOUBLE PRECISION'
             when FF.RDB$FIELD_TYPE = 35 then 'TIMESTAMP'
             when FF.RDB$FIELD_TYPE = 37 then 'VARCHAR(' || FF.RDB$CHARACTER_LENGTH || ')'
             when FF.RDB$FIELD_TYPE = 261 then 'BLOB SUB_TYPE ' || FF.RDB$FIELD_SUB_TYPE || ' SEGMENT SIZE ' || FF.RDB$SEGMENT_LENGTH
             else 'UNKNOWN'
           end, '') ||
           case
             when substring(F.RDB$FIELD_SOURCE from 1 for 3) = 'DM_' then trim(F.RDB$FIELD_SOURCE)
             else ''
           end /*||
           case
             when F.RDB$NULL_FLAG = 1 then ' NOT NULL'
             else ''
           end*/, ',')
    from RDB$RELATION_FIELDS F
    join RDB$FIELDS FF on F.RDB$FIELD_SOURCE = FF.RDB$FIELD_NAME
    where F.RDB$RELATION_NAME = trim(upper(:PRTABELA)) and
          not exists(select 1
                     from RDB$RELATION_FIELDS F2
                     where F2.RDB$RELATION_NAME = trim(upper('TMP_' || :PRTABELA || '_TEMP')) and
                           F2.RDB$FIELD_NAME = F.RDB$FIELD_NAME)
    into :W_COLUMNS;

    --verificando se tem os campos pr prios daa tabelas tempor rias
    select count(RDB$FIELD_NAME)
    from RDB$RELATION_FIELDS
    where RDB$RELATION_NAME = trim(upper('TMP_' || :PRTABELA || '_TEMP')) and
          RDB$FIELD_NAME = 'BDEDITCHAVE'
    into :W_COUNT;

    if (W_COUNT = 0) then
    begin
        W_COLUMNS = ' ADD BDEDITCHAVE INTEGER ' || Coalesce(',' || :W_COLUMNS, '');
    end

     select count(RDB$FIELD_NAME)
    from RDB$RELATION_FIELDS
    where RDB$RELATION_NAME = trim(upper('TMP_' || :PRTABELA || '_TEMP')) and
          RDB$FIELD_NAME = 'BDROW_EXCLUIDA'
    into :W_COUNT;

    if (W_COUNT = 0) then
    begin
        W_COLUMNS = ' ADD BDROW_EXCLUIDA INTEGER ' || Coalesce(',' || :W_COLUMNS, '');
    end

    if (coalesce(:W_COLUMNS, '') <> '') then
    begin
      --montando o ALTER TABLE
      W_SQL_CREATE = 'ALTER TABLE TMP_' || :PRTABELA || '_TEMP ' || :W_COLUMNS;

      --Senta a lenha no SQL....
      execute statement :W_SQL_CREATE;
    end
  end
end^

CREATE OR ALTER PROCEDURE SP_ATU_EST_TEMP_RECURSIVO (
    PRTABELA VARCHAR(63),
    PRPREFIXO VARCHAR(10))
AS
DECLARE VARIABLE W_TAB_FILHO VARCHAR(63);
DECLARE VARIABLE WVERSAO VARCHAR(10);
begin
   select GETVERSAO_FB() from rdb$database into :wVersao;

   if (Cast(substring(:WVERSAO FROM 1 FOR 1) AS INTEGER) >= 4) then
      begin
          --Primeiro se atualiza...
          EXECUTE PROCEDURE SP_ATU_ESTRUTURA_TEMP(:PRTABELA);
        
          /* Vamos listar todas as tabelas dependentes, a partir do que veio de par?metro */
          for select Trim(RC.RDB$RELATION_NAME) as CHILD_TABLE
              from RDB$RELATION_CONSTRAINTS RC
                    join RDB$REF_CONSTRAINTS REF on RC.RDB$CONSTRAINT_NAME = REF.RDB$CONSTRAINT_NAME
                    join RDB$RELATION_CONSTRAINTS RP on REF.RDB$CONST_NAME_UQ = RP.RDB$CONSTRAINT_NAME
              where RC.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' and
                    RP.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY' and
                    RP.RDB$RELATION_NAME = trim(upper(:PRTABELA)) and
                    (:PRPREFIXO = '' or (RC.RDB$RELATION_NAME starts with Upper(:PRPREFIXO)))
          into :W_TAB_FILHO
          do
             begin
                 /* recursividade na veia!!! */
                 execute procedure SP_ATU_EST_TEMP_RECURSIVO(:w_tab_filho, :prPrefixo);
             end
      end
end^

CREATE OR ALTER procedure SP_CARREGA_TABTEMP (
    PRTABELA varchar(63),
    PRWHERE varchar(10000) not null,
    PREDITCHAVE varchar(63),
    PRSESSAO integer)
as
declare variable W_COLUMNS varchar(10000);
declare variable W_SQL_INSERT varchar(10000);
declare variable W_COLUMNSTAB varchar(10000);
begin
/*  if (coalesce(:prSessao,0) = 0) then
     begin
        exception EX_SESSAO_ZERADA ('SP_CARREGA_TABTEMP');--, PRTABELA);
     end

  if (coalesce(trim(:prEditChave), '') = '') then
     begin
        exception EX_EDITCHAVE_VAZIO(:PRTABELA);--, 'SP_CARREGA_TABTEMP');
     end

  if (coalesce(trim(:PRWHERE), '') = '') then
     begin
        exception EX_FALTA_CLAUSULA_WHERE('SP_CARREGA_TABTEMP');--, :PRTABELA);
     end */

  --Carregar a lista de campos da tabela quente
  select list(TBS.FIELDS, ',')
  from (select trim(F.RDB$FIELD_NAME) as FIELDS, F.RDB$FIELD_POSITION
        from RDB$RELATION_FIELDS F
        where UPPER(TRIM(F.RDB$RELATION_NAME)) = UPPER(TRIM(:prtabela))
        order by 2) TBS
  into :W_COLUMNS;

  --Carregar a lista de campos da tabela quente
  select list('TAB.' || TBS.FIELDS, ',')
  from (select trim(F.RDB$FIELD_NAME) as FIELDS, F.RDB$FIELD_POSITION
        from RDB$RELATION_FIELDS F
        where UPPER(TRIM(F.RDB$RELATION_NAME)) = UPPER(TRIM(:prtabela))
        order by 2) TBS
  into :W_COLUMNSTAB;

  --Montando o SQL que far? a inser??o
  W_SQL_INSERT = 'INSERT INTO TMP_' || :PRTABELA || '_TEMP (BDEDITCHAVE, BDSESSAO,' || :W_COLUMNS || ') ' ||
                 'SELECT TAB.' || :prEditChave || ',' || :PRSESSAO || ',' || :W_COLUMNSTAB || ' ' ||
                 'FROM ' || :PRTABELA || ' TAB ' || :PRWHERE;

  EXECUTE STATEMENT :W_SQL_INSERT;
end^

create or alter procedure SP_ZERA_CAMPOS_NUMERICOS (
    PRTABELA varchar(31),
    PRFILTROWHERE varchar(255),
    PRPREFIXO varchar(3),
    PRRECURSIVO char(1) = 'S' 
)
as
declare variable WNOME_CAMPO varchar(31);
declare variable WSQL varchar(10000);
declare variable WCAMPOS_UPDATE varchar(10000);
declare variable WTABELAFILHA varchar(31);
begin
  -- Inicializa a string dos campos que serão atualizados
  WCAMPOS_UPDATE = '';

  -- Loop para construir a lista de campos NUMERIC a serem zerados
  for select RF.RDB$FIELD_NAME as CAMPO
      from RDB$RELATION_FIELDS RF
      join RDB$FIELDS F on RF.RDB$FIELD_SOURCE = F.RDB$FIELD_NAME
      where RF.RDB$RELATION_NAME = :PRTABELA and
            F.RDB$FIELD_TYPE = 16 -- Tipo NUMERIC/DECIMAL
      into :WNOME_CAMPO
  do
  begin
    -- Adiciona o campo na string de campos para o comando UPDATE
    if (WCAMPOS_UPDATE = '') then
      WCAMPOS_UPDATE = 'TAB.' || WNOME_CAMPO || ' = 0';
    else
      WCAMPOS_UPDATE = WCAMPOS_UPDATE || ', TAB.' || WNOME_CAMPO || ' = 0';
  end

  -- Se não encontrou nenhum campo NUMERIC, simplesmente sai da procedure
  if (WCAMPOS_UPDATE <> '') then
  begin
    -- Constrói o comando UPDATE completo
    WSQL = 'UPDATE ' || :PRTABELA || ' TAB SET ' || WCAMPOS_UPDATE;

    -- Adiciona a condição WHERE se fornecida
    if (PRFILTROWHERE is not null) then
      WSQL = WSQL || ' WHERE ' || :PRFILTROWHERE;

    -- Executa o comando UPDATE dinamicamente
    execute statement WSQL;
  end

  -- Se a operação for recursiva, busca as tabelas filhas e chama a SP para cada uma delas
  if (PRRECURSIVO = 'S') then
  begin
    -- Identifica as tabelas filhas (tabelas com FK para a tabela atual)
    for select trim(RC.RDB$RELATION_NAME) as CHILD_TABLE
        from RDB$RELATION_CONSTRAINTS RC
        join RDB$REF_CONSTRAINTS REF on RC.RDB$CONSTRAINT_NAME = REF.RDB$CONSTRAINT_NAME
        join RDB$RELATION_CONSTRAINTS RP on REF.RDB$CONST_NAME_UQ = RP.RDB$CONSTRAINT_NAME
        where RC.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' and
              RP.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY' and
              RP.RDB$RELATION_NAME = :PRTABELA and
              ((substring(RC.RDB$RELATION_NAME from 1 for 3) = '') or (substring(RC.RDB$RELATION_NAME from 1 for 3) = :PRPREFIXO))
        into :WTABELAFILHA
    do
    begin
      -- Chama a SP para a tabela filha, de forma recursiva
      execute procedure SP_ZERA_CAMPOS_NUMERICOS(WTABELAFILHA, :PRFILTROWHERE, 'S');
    end
  end
end ^

create or alter procedure SP_CANCELAR_LAN_BASE_SER
as
declare variable WZERARNFCANC DM_BOOLEAN;
BEGIN

  --Vamos obter a configuração que indica se deve zerar os valores da nota ou não
  SELECT UPPER(P.BDVALOR)
  FROM TPARGER P
  WHERE UPPER(P.BDCAMPO) = 'BDZERANFCANCELADA'
  INTO :wZerarNFCanc;

  --Atualizando o Status da Nota
  UPDATE VEF_EMP_TMOVSER S
  SET S.BDCODSITNF = 2,
      S.BDDATACANC = S.BDDATAEMISSAO
  WHERE EXISTS (
                SELECT REP.BDCHAVE
                FROM TMP_TLANC_REPETIDOS REP
                WHERE REP.BDCODEMP = S.BDCODEMP
                  AND REP.BDCHAVE = S.BDCHAVE
               );

  --Nota cancelada não contabiliza
  DELETE FROM TOL_VEF_EMP_TMOVSER TOL
  WHERE EXISTS(
                SELECT REP.BDCHAVE
                FROM TMP_TLANC_REPETIDOS REP
                WHERE REP.BDCODEMP = TOL.BDCODEMP
                  AND REP.BDCHAVE = TOL.bdchaveser
              );

  /************************************** Zerar valores **************************************/
  IF (:wZerarNFCanc = 'TRUE') THEN
    BEGIN
      EXECUTE PROCEDURE SP_ZERA_CAMPOS_NUMERICOS('VEF_EMP_TMOVSER',
                                              'EXISTS ( ' ||
                                              '        SELECT REP.BDCHAVE '||
                                              '        FROM TMP_TLANC_REPETIDOS REP '||
                                              '        WHERE REP.BDCODEMP = TAB.BDCODEMP ' ||
                                              '          AND REP.BDCHAVE = TAB.BDCHAVE' ||
                                              '       )',
                                              'VEF',
                                              'S');
    END

   DELETE FROM TMP_TLANC_REPETIDOS;
END^

CREATE OR ALTER procedure SP_CARREGA_TABTEMP_RECURSIVO (
    PRTABELA varchar(63),
    PRPREFIXO varchar(10),
    PRWHERE varchar(10000),
    PREDITCHAVE varchar(63),
    PRSESSAO integer,
    PRTAB_EXCLUIDAS varchar(10000))
as
declare variable W_TAB_FILHO varchar(63);
declare variable WVERSAO varchar(10);
declare variable W_ROWCOUNT integer;
begin
   select GETVERSAO_FB() from rdb$database into :wVersao;

   if (Cast(substring(:WVERSAO FROM 1 FOR 1) AS INTEGER) >= 4) then
      begin
          --Primeiro se atualiza...
          EXECUTE PROCEDURE SP_CARREGA_TABTEMP(:PRTABELA, :PRWHERE, :PREDITCHAVE, :PRSESSAO);
        
          EXECUTE STATEMENT 'select COUNT(1) from TMP_'||:prTabela||'_TEMP where bdSessao = ' || :prSessao into :W_ROWCOUNT;

          if (W_ROWCOUNT > 0) then
             begin
                /* Vamos listar todas as tabelas dependentes, a partir do que veio de par?metro */
                for select Trim(RC.RDB$RELATION_NAME) as CHILD_TABLE
                    from RDB$RELATION_CONSTRAINTS RC
                          join RDB$REF_CONSTRAINTS REF on RC.RDB$CONSTRAINT_NAME = REF.RDB$CONSTRAINT_NAME
                          join RDB$RELATION_CONSTRAINTS RP on REF.RDB$CONST_NAME_UQ = RP.RDB$CONSTRAINT_NAME
                    where RC.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' and
                          RP.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY' and
                          RP.RDB$RELATION_NAME = :PRTABELA and
                          (:PRPREFIXO = '' or (substring(RC.RDB$RELATION_NAME from 1 for 3) = :PRPREFIXO)) and
                          (POSITION(TRIM(RC.RDB$RELATION_NAME) in coalesce(:PRTAB_EXCLUIDAS, '')) = 0)
                into :W_TAB_FILHO
                do
                   begin
                       /* recursividade na veia!!! */
                       EXECUTE PROCEDURE SP_CARREGA_TABTEMP_RECURSIVO(:w_tab_filho, :prPrefixo, :PRWHERE, :preditchave, :prsessao, :PRTAB_EXCLUIDAS);
                   end
             end
      end
end^

CREATE OR ALTER procedure SPCOMMITA_TEMP (
    PRTABELA varchar(63),
    PRSESSAO integer)
as
declare variable WPK_TABLES varchar(1000);
declare variable WSQL varchar(20000);
declare variable WFIELDS_MATCHED varchar(10000);
declare variable WFIELDS_NOT_MATCHED varchar(10000);
declare variable WFIELDS_NOT_MATCHED_TEMP varchar(10000);
begin
  --Obtendo os campos que foram a chave prim?ria
  select list('TAB.' || trim(RDB$INDEX_SEGMENTS.RDB$FIELD_NAME) || ' = ' || 'TMP.' || trim(RDB$INDEX_SEGMENTS.RDB$FIELD_NAME), ' and ')
  from RDB$INDEX_SEGMENTS
  join RDB$INDICES on RDB$INDEX_SEGMENTS.RDB$INDEX_NAME = RDB$INDICES.RDB$INDEX_NAME
  join RDB$RELATION_CONSTRAINTS on RDB$INDICES.RDB$INDEX_NAME = RDB$RELATION_CONSTRAINTS.RDB$INDEX_NAME
  where RDB$RELATION_CONSTRAINTS.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY' and
        upper(trim(RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME)) = upper(trim(:PRTABELA))
  into :WPK_TABLES;

  --Se n?o tiver chave prim?ria, morre tudo aqui
  --if (:WPK_TABLES is null) then
  --  exception EX_PK_NOT_FOUND(:PRTABELA);

  --Obtendo os campos para a parte do update do comando
  with CAMPOS
  as (select trim(FN.RDB$FIELD_NAME) as FIELD_NAME
      from RDB$RELATION_FIELDS FN
      left join(select trim(RDB$INDEX_SEGMENTS.RDB$FIELD_NAME) as PKNAME
                from RDB$INDEX_SEGMENTS
                join RDB$INDICES on RDB$INDEX_SEGMENTS.RDB$INDEX_NAME = RDB$INDICES.RDB$INDEX_NAME
                join RDB$RELATION_CONSTRAINTS on RDB$INDICES.RDB$INDEX_NAME = RDB$RELATION_CONSTRAINTS.RDB$INDEX_NAME
                where RDB$RELATION_CONSTRAINTS.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY' and
                      upper(trim(RDB$RELATION_CONSTRAINTS.RDB$RELATION_NAME)) = upper(trim(:PRTABELA))) TPK on TPK.PKNAME = FN.RDB$FIELD_NAME
      where upper(trim(FN.RDB$RELATION_NAME)) = upper(trim(:PRTABELA)) and
            TPK.PKNAME is null
      order by FN.RDB$FIELD_POSITION)
  select list('TAB.' || FIELD_NAME || ' = ' || 'TMP.' || FIELD_NAME, ', ')
  from CAMPOS
  into :WFIELDS_MATCHED;

  --agora os campos para a parte do insert
  with CAMPOS
  as (select trim(FF.RDB$FIELD_NAME) as FIELD_NAME
      from RDB$RELATION_FIELDS FF
      where upper(trim(FF.RDB$RELATION_NAME)) = upper(trim(:PRTABELA))
      order by FF.RDB$FIELD_POSITION)
  select list(FIELD_NAME, ', ')
  from CAMPOS
  into :WFIELDS_NOT_MATCHED;

  --os campos que ser?o usados no Insert
  with CAMPOS
  as (select trim(FF.RDB$FIELD_NAME) as FIELD_NAME
      from RDB$RELATION_FIELDS FF
      where upper(trim(FF.RDB$RELATION_NAME)) = upper(trim(:PRTABELA))
      order by FF.RDB$FIELD_POSITION)
  select list('TMP.' || FIELD_NAME, ', ')
  from CAMPOS
  into :WFIELDS_NOT_MATCHED_TEMP;

  --Motando o brut?o aqui
  WSQL = 'merge into ' || :prtabela || ' TAB ' ||
         'using (SELECT * FROM TMP_' || :PRTABELA || '_TEMP WHERE BDSESSAO = ' || :prsessao || ') TMP ' ||
         'on ' || :WPK_TABLES;

   --WSQL = :WSQL ||
   --      '    when matched and TMP.BDROW_EXCLUIDA = 1 then delete ';

  if (WFIELDS_MATCHED IS NOT NULL) then
     begin
        WSQL = :WSQL ||
               '    when matched then' ||
               '        update set ' || :WFIELDS_MATCHED;
     end

  WSQL = :WSQL ||
         '    when not matched then ' ||
         '        insert (' || :WFIELDS_NOT_MATCHED || ')' ||
         '        values(' || :WFIELDS_NOT_MATCHED_TEMP || ')';

  --aquela sentada de lenha b?sica
  EXECUTE STATEMENT :WSQL;
end^

CREATE OR ALTER procedure SPCOMMITA_TEMP_RECURSIVA (
    PRTABELA varchar(63),
    PRPREFIXO varchar(10),
    PRSESSAO integer,
    PRTAB_EXCLUIDAS varchar(10000))
as
declare variable W_TAB_FILHO varchar(10000);
declare variable WVERSAO varchar(10);
declare variable W_ROWCOUNT integer;
begin
    select GETVERSAO_FB() from rdb$database into :wVersao;

   if (Cast(substring(:WVERSAO FROM 1 FOR 1) AS INTEGER) >= 4) then
      begin
          EXECUTE STATEMENT 'select COUNT(1) from TMP_'||:prTabela||'_TEMP where bdSessao = ' || :prSessao into :W_ROWCOUNT;

          if (W_ROWCOUNT > 0) then
              begin
                  --Primeiro comita
                  EXECUTE PROCEDURE SPCOMMITA_TEMP(:PRTABELA, :PRSESSAO);
                
                  /* Vamos listar todas as tabelas dependentes, a partir do que veio de par?metro */
                  for select Trim(RC.RDB$RELATION_NAME) as CHILD_TABLE
                      from RDB$RELATION_CONSTRAINTS RC
                            join RDB$REF_CONSTRAINTS REF on RC.RDB$CONSTRAINT_NAME = REF.RDB$CONSTRAINT_NAME
                            join RDB$RELATION_CONSTRAINTS RP on REF.RDB$CONST_NAME_UQ = RP.RDB$CONSTRAINT_NAME
                      where RC.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' and
                            RP.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY' and
                            TRIM(UPPER(RP.RDB$RELATION_NAME)) = TRIM(UPPER(:PRTABELA)) and
                            (:PRPREFIXO = '' or (upper(substring(RC.RDB$RELATION_NAME from 1 for 3)) = Upper(:PRPREFIXO))) and
                            (POSITION(Trim(RC.RDB$RELATION_NAME) in coalesce(:PRTAB_EXCLUIDAS, '')) = 0)
                  into :W_TAB_FILHO
                  do
                     begin
                         /* recursividade na veia!!! */
                         EXECUTE PROCEDURE SPCOMMITA_TEMP_RECURSIVA(:w_tab_filho, :prPrefixo, :prsessao, :PRTAB_EXCLUIDAS);
                     end
              end
     end
end^


CREATE OR ALTER procedure SPLIMP_TEMP (
    PRTABELA varchar(63),
    PRSESSAO integer)
as
declare variable WSQL varchar(10000);
begin
   --Motando o brut?o aqui
  WSQL = 'DELETE FROM TMP_' ||:prtabela || '_TEMP WHERE BDSESSAO = ' || PRSESSAO;

  --aquela sentada de lenha b?sica
  EXECUTE STATEMENT :WSQL;
end^

create or alter procedure SPLIMP_TEMP_RECURSIVO (
    PRTABELA varchar(63),
    PRPREFIXO varchar(10),
    PRSESSAO integer)
as
declare variable W_TAB_FILHO varchar(63);
declare variable wVERSAO varchar(10);
begin
   select GETVERSAO_FB() from rdb$database into :wVersao;

   if (Cast(substring(:WVERSAO FROM 1 FOR 1) AS INTEGER) >= 4) then
      begin
          EXECUTE PROCEDURE SPLIMP_TEMP(:PRTABELA, :PRSESSAO);
        
          /* Vamos listar todas as tabelas dependentes, a partir do que veio de par?metro */
          for select Trim(RC.RDB$RELATION_NAME) as CHILD_TABLE
              from RDB$RELATION_CONSTRAINTS RC
                    join RDB$REF_CONSTRAINTS REF on RC.RDB$CONSTRAINT_NAME = REF.RDB$CONSTRAINT_NAME
                    join RDB$RELATION_CONSTRAINTS RP on REF.RDB$CONST_NAME_UQ = RP.RDB$CONSTRAINT_NAME
              where RC.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' and
                    RP.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY' and
                    RP.RDB$RELATION_NAME = :PRTABELA and
                    (:PRPREFIXO = '' or (substring(RC.RDB$RELATION_NAME from 1 for 3) = :PRPREFIXO))
          into :W_TAB_FILHO
          do
             begin
                 /* recursividade na veia!!! */
                 EXECUTE PROCEDURE SPLIMP_TEMP_RECURSIVO(:w_tab_filho, :prPrefixo, :prsessao);
             end
     end
end^

create or alter procedure SP_UPDATE_TABTEMP (
    PRTABELA varchar(63),
    PRUSING varchar(10000) not null,
    PRVINCULO varchar(10000) not null,
    PR_MATCHED varchar(10000) not null,
    PR_NOT_MATCHED varchar(10000) not null)
as
declare variable W_SQL_MERGE varchar(10000);
begin
  --Montando o SQL que far? a inser??o
  W_SQL_MERGE = 'MERGE INTO TMP_' || :PRTABELA || '_TEMP FILHO ' || 'USING (' || :PRUSING || ') PAI ' || 'ON ' || :PRVINCULO;

  if (:PR_MATCHED <> '') then
    W_SQL_MERGE = W_SQL_MERGE || ' WHEN MATCHED THEN ' || :PR_MATCHED;

  if (:PR_NOT_MATCHED <> '') then
    W_SQL_MERGE = W_SQL_MERGE || ' WHEN NOT MATCHED THEN ' || :PR_NOT_MATCHED;

  execute statement :W_SQL_MERGE;
end^

create or alter procedure SP_UPDATE_TABTEMP_RECURSIVO (
    PRTABELA varchar(63),
    PRPREFIXO varchar(10),
    PRTAB_EXCLUIDAS varchar(10000),
    PRUSING varchar(10000) not null,
    PRVINCULO varchar(10000) not null,
    PR_MATCHED varchar(10000) not null,
    PR_NOT_MATCHED varchar(10000) not null,
    PR_AUTO_EXECUTE integer,
    PRSESSAO integer)
as
declare variable W_TAB_FILHO varchar(63);
declare variable WVERSAO varchar(10);
declare variable W_ROWCOUNT integer;
begin
  select GETVERSAO_FB()
  from RDB$DATABASE
  into :WVERSAO;

  if (cast(substring(:WVERSAO from 1 for 1) as integer) >= 4) then
  begin
    --Primeiro se atualiza...
    if (:PR_AUTO_EXECUTE = 1) then
      execute procedure SP_UPDATE_TABTEMP(:PRTABELA, :PRUSING, :PRVINCULO, :PR_MATCHED, :PR_NOT_MATCHED);

    execute statement 'select COUNT(1) from TMP_' || :PRTABELA || '_TEMP where bdSessao = ' || :PRSESSAO
        into :W_ROWCOUNT;

    if (W_ROWCOUNT > 0) then
    begin
      /* Vamos listar todas as tabelas dependentes, a partir do que veio de par?metro */
      for select trim(RC.RDB$RELATION_NAME) as CHILD_TABLE
          from RDB$RELATION_CONSTRAINTS RC
          join RDB$REF_CONSTRAINTS REF on RC.RDB$CONSTRAINT_NAME = REF.RDB$CONSTRAINT_NAME
          join RDB$RELATION_CONSTRAINTS RP on REF.RDB$CONST_NAME_UQ = RP.RDB$CONSTRAINT_NAME
          where RC.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' and
                RP.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY' and
                RP.RDB$RELATION_NAME = :PRTABELA and
                (:PRPREFIXO = '' or (substring(RC.RDB$RELATION_NAME from 1 for 3) = :PRPREFIXO)) and
                (position(trim(RC.RDB$RELATION_NAME) in coalesce(:PRTAB_EXCLUIDAS, '')) = 0)
          into :W_TAB_FILHO
      do
      begin
        /* recursividade na veia!!! */
        execute procedure SP_UPDATE_TABTEMP_RECURSIVO(:W_TAB_FILHO, :PRPREFIXO, :PRTAB_EXCLUIDAS, :PRUSING, :PRVINCULO,
            :PR_MATCHED, :PR_NOT_MATCHED, 1, PRSESSAO);
      end
    end
  end
end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_ECREDAC (
    PRSESSAO integer)
as
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WEDITCHAVE integer;
declare variable WVLRSAI numeric(15,2);
declare variable WCREDACU varchar(5);
declare variable WVLRIVA numeric(15,2);
declare variable WVLRCREDEST numeric(15,2);
declare variable WALIQPCM numeric(7,4);
declare variable WVLRCREDGER numeric(15,2);
declare variable WCODENQLEGAL integer;
declare variable WCHAVEENT integer;
declare variable WVLRICMSOUT numeric(15,2);
declare variable WALIQCREDOUT numeric(15,2);
declare variable WORIGEM integer;
declare variable WVLRSAI_AUX numeric(15,2);
declare variable WVLRIVA_AUX numeric(15,2);
declare variable WVLRCREDEST_AUX numeric(15,2);
declare variable WVLRCREDGER_AUX numeric(15,2);
declare variable WVLRICMSOUT_AUX numeric(15,2);
begin
  /* Esta aqui ? um SP de rateio, s?o de tabelas espec?ficas e ent?o o que uma faz as outras copiam, apenas mudando a tabela e os campos */

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  for select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDEDITCHAVE, sum(ATU.BDVLRSAI) as BDVLRSAI,
             ATU.BDCREDACU, sum(ATU.BDVLRIVA) as BDVLRIVA, sum(ATU.BDVLRCREDEST) as BDVLRCREDEST, ATU.BDALIQPCM,
             Sum(ATU.BDVLRCREDGER) as BDVLRCREDGER, ATU.BDCODENQLEGAL, ATU.BDCHAVEENT, SUM(ATU.BDVLRICMSOUT) as BDVLRICMSOUT,
             ATU.BDALIQCREDOUT, ATU.BDORIGEM
      from (select ECREDAC.BDCODEMP, ECREDAC.BDCHAVE, ECREDAC.BDORDEM, ECREDAC.BDEDITCHAVE,
                   ECREDAC.BDVLRSAI * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRSAI, ECREDAC.BDCREDACU,
                   coalesce(ECREDAC.BDVLRIVA, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRIVA,
                   coalesce(ECREDAC.BDVLRCREDEST, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRCREDEST, ECREDAC.BDALIQPCM,
                   coalesce(ECREDAC.BDVLRCREDGER, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRCREDGER, ECREDAC.BDCODENQLEGAL,
                   ECREDAC.BDCHAVEENT, coalesce(ECREDAC.BDVLRICMSOUT, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRICMSOUT,
                   ECREDAC.BDALIQCREDOUT, 1 AS BDORIGEM
            from TMP_VEF_EMP_TMOVSAIECREDAC_TEMP ECREDAC
            inner join TMP_VEF_EMP_TMOVSAIITENS_TEMP IT on IT.BDSESSAO = ECREDAC.BDSESSAO and
                  IT.BDCODEMP = ECREDAC.BDCODEMP and
                  IT.BDCHAVE = ECREDAC.BDCHAVE and
                  IT.BDORDEM = ECREDAC.BDORDEM and
                  IT.BDSESSAO = ECREDAC.BDSESSAO
            where ECREDAC.BDSESSAO = :PRSESSAO and
                  coalesce(IT.BDROW_EXCLUIDA, 0) <> 1
            union all
            select ECREDAC.BDCODEMP, ECREDAC.BDCHAVE, PR.BDORDEM_ATU, ECREDAC.BDEDITCHAVE,
                   ECREDAC.BDVLRSAI * PR.BDRAZAORATEIO as BDVLRSAI, ECREDAC.BDCREDACU,
                   coalesce(ECREDAC.BDVLRIVA, 0) * PR.BDRAZAORATEIO as BDVLRIVA,
                   coalesce(ECREDAC.BDVLRCREDEST, 0) * PR.BDRAZAORATEIO as BDVLRCREDEST, ECREDAC.BDALIQPCM,
                   coalesce(ECREDAC.BDVLRCREDGER, 0) * PR.BDRAZAORATEIO as BDVLRCREDGER, ECREDAC.BDCODENQLEGAL,
                   ECREDAC.BDCHAVEENT, coalesce(ECREDAC.BDVLRICMSOUT, 0) * PR.BDRAZAORATEIO as BDVLRICMSOUT,
                   ECREDAC.BDALIQCREDOUT, 2 AS BDORIGEM
            from TMP_VEF_EMP_TMOVSAIECREDAC_TEMP ECREDAC
            inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on ECREDAC.BDSESSAO = PR.BDSESSAO and
                  ECREDAC.BDCODEMP = PR.BDCODEMP and
                  ECREDAC.BDCHAVE = PR.BDCHAVE and
                  ECREDAC.BDORDEM = PR.BDORDEM_ORIG and
                  ECREDAC.BDSESSAO = PR.BDSESSAO
            where ECREDAC.BDSESSAO = :PRSESSAO) ATU
      group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDEDITCHAVE, ATU.BDCREDACU, ATU.BDALIQPCM, ATU.BDCODENQLEGAL,
               ATU.BDCHAVEENT, ATU.BDALIQCREDOUT, ATU.BDORIGEM
      into :WCODEMP, :WCHAVE, :WORDEM, :WEDITCHAVE, :WVLRSAI, :WCREDACU, :WVLRIVA, :WVLRCREDEST, :WALIQPCM, :WVLRCREDGER, :WCODENQLEGAL,
           :WCHAVEENT, :WVLRICMSOUT, :WALIQCREDOUT, :WORIGEM
  do
  begin
    --Vamos ver se j? n?o existe e fazer a soma neste caso aqui
    if (:WORIGEM = 2) then
    begin
      select first 1 coalesce(BDVLRSAI, 0) AS BDVLRSAI, coalesce(BDVLRIVA, 0) AS BDVLRIVA, coalesce(BDVLRCREDEST, 0) as BDVLRCREDEST,
             coalesce(BDVLRCREDGER, 0) AS BDVLRCREDGER, coalesce(BDVLRICMSOUT, 0) AS BDVLRICMSOUT
      from TMP_VEF_EMP_TMOVSAIECREDAC_TEMP 
      where BDCHAVE = :WCHAVE and
            BDORDEM = :WORDEM and
   BDSESSAO = :PRSESSAO
      into :WVLRSAI_AUX, :WVLRIVA_AUX, :WVLRCREDEST_AUX, :WVLRCREDGER_AUX, :WVLRICMSOUT_AUX;

      WVLRSAI  = coalesce(:WVLRSAI, 0) + coalesce(:WVLRSAI_AUX, 0);
      WVLRIVA = coalesce(:WVLRIVA, 0) + coalesce(:WVLRIVA_AUX, 0);
      WVLRCREDEST  = coalesce(:WVLRCREDEST, 0) + coalesce(:WVLRCREDEST_AUX, 0);
      WVLRCREDGER  = coalesce(:WVLRCREDGER, 0) + coalesce(:WVLRCREDGER_AUX, 0);
      WVLRICMSOUT  = coalesce(:WVLRICMSOUT, 0) + coalesce(:WVLRICMSOUT_AUX, 0);
    end

    --vamos agora fazer o update ou insert do registro
    UPDATE OR INSERT INTO TMP_VEF_EMP_TMOVSAIECREDAC_TEMP
        (BDSESSAO, BDEDITCHAVE, BDCODEMP, BDCHAVE, BDORDEM, BDVLRSAI, BDCREDACU, BDVLRIVA, BDVLRCREDEST, BDALIQPCM, BDVLRCREDGER, BDCODENQLEGAL, BDCHAVEENT, BDVLRICMSOUT, BDALIQCREDOUT)
        values(:PRSESSAO, :WEDITCHAVE, :WCODEMP, :WCHAVE, :WORDEM, :WVLRSAI, :WCREDACU, :WVLRIVA, :WVLRCREDEST, :WALIQPCM, :WVLRCREDGER, :WCODENQLEGAL, :WCHAVEENT, :WVLRICMSOUT, :WALIQCREDOUT)
    MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM);
  end

end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_INF_NF_SP (
    PRSESSAO integer)
as
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WEDITCHAVE integer;
declare variable WORIGEM integer;
declare variable WVLRTOTFRETE numeric(15,2);
declare variable WVLRTOTSEGURO numeric(15,2);
declare variable WBASE_AUX numeric(15,2);
declare variable WVALOR_AUX numeric(15,2);
begin
  /* Esta aqui ? um SP de rateio, s?o de tabelas espec?ficas e ent?o o que uma faz as outras copiam, apenas mudando a tabela e os campos */

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  for select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDEDITCHAVE, sum(ATU.BDVLRTOTFRETE) as BDVLRTOTFRETE,
            sum(ATU.BDVLRTOTSEGURO) as BDVLRTOTSEGURO, ATU.BDORIGEM
      from (select DCIP.BDCODEMP, DCIP.BDCHAVE, DCIP.BDORDEM, DCIP.BDEDITCHAVE,
                   DCIP.BDVLRTOTFRETE * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRTOTFRETE,
                   coalesce(DCIP.BDVLRTOTSEGURO, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRTOTSEGURO, 1 AS BDORIGEM
            from TMP_VEF_EMP_TMOVSAI_INF_NF_SP_TEMP DCIP
            inner join TMP_VEF_EMP_TMOVSAIITENS_TEMP IT on IT.BDSESSAO = DCIP.BDSESSAO and
                  IT.BDCODEMP = DCIP.BDCODEMP and
                  IT.BDCHAVE = DCIP.BDCHAVE and
                  IT.BDORDEM = DCIP.BDORDEM and
                  IT.BDSESSAO = DCIP.BDSESSAO
            where DCIP.BDSESSAO = :PRSESSAO and
                  coalesce(IT.BDROW_EXCLUIDA, 0) <> 1
            union all
            select DCIP.BDCODEMP, DCIP.BDCHAVE, PR.BDORDEM_ATU, DCIP.BDEDITCHAVE,
                   DCIP.BDVLRTOTFRETE * PR.BDRAZAORATEIO as BDVLRTOTFRETE,
                   coalesce(DCIP.BDVLRTOTSEGURO, 0) * PR.BDRAZAORATEIO as BDVLRTOTSEGURO, 2 AS BDORIGEM
            from TMP_VEF_EMP_TMOVSAI_INF_NF_SP_TEMP DCIP
            inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on DCIP.BDSESSAO = PR.BDSESSAO and
                  DCIP.BDCODEMP = PR.BDCODEMP and
                  DCIP.BDCHAVE = PR.BDCHAVE and
                  DCIP.BDORDEM = PR.BDORDEM_ORIG
            where DCIP.BDSESSAO = :PRSESSAO) ATU
      group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDEDITCHAVE, ATU.BDORIGEM
      into :WCODEMP, :WCHAVE, :WORDEM, :WEDITCHAVE, :WVLRTOTFRETE, :WVLRTOTSEGURO, :WORIGEM
  do
  begin
    --Vamos ver se j? n?o existe e fazer a soma neste caso aqui
    if (:WORIGEM = 2) then
    begin
      select first 1 coalesce(BDVLRTOTFRETE, 0) AS BDVLRTOTFRETE, coalesce(BDVLRTOTSEGURO, 0) AS BDVLRTOTSEGURO
      from TMP_VEF_EMP_TMOVSAI_INF_NF_SP_TEMP
      where BDCHAVE = :WCHAVE and
            BDORDEM = :WORDEM and
   BDSESSAO = :PRSESSAO
      into :WBASE_AUX, :WVALOR_AUX;

      WVLRTOTFRETE  = coalesce(:WVLRTOTFRETE, 0) + coalesce(:WBASE_AUX, 0);
      WVLRTOTSEGURO = coalesce(:WVLRTOTSEGURO, 0) + coalesce(:WVALOR_AUX, 0);
    end

    --vamos agora fazer o update ou insert do registro
    UPDATE OR INSERT INTO TMP_VEF_EMP_TMOVSAI_INF_NF_SP_TEMP
        (BDSESSAO, BDEDITCHAVE, BDCODEMP, BDCHAVE, BDORDEM, BDVLRTOTFRETE, BDVLRTOTSEGURO)
        values(:PRSESSAO, :WEDITCHAVE, :WCODEMP, :WCHAVE, :WORDEM, :WVLRTOTFRETE, :WVLRTOTSEGURO)
    MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM);
  end

end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_IVA (
    PRSESSAO integer)
as
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WORDEMIVA integer;
declare variable WORDEM_SALVA integer;
declare variable WEDITCHAVE integer;
declare variable WALIQINTERNA numeric(18,6);
declare variable WVALPROD numeric(18,2);
declare variable WALIQIVA numeric(18,6);
declare variable WBASECALC numeric(18,2);
declare variable WICMSDEST numeric(18,2);
declare variable WICMSRECOLHER numeric(18,2);
declare variable WCODREC integer;
declare variable WDATAREC date;
declare variable WVLRREC integer;
declare variable WCODPROD integer;
declare variable WDESTDA integer;
begin
  /* Esta aqui ? um SP de rateio, s?o de tabelas espec?ficas e ent?o o que uma faz as outras copiam, apenas mudando a tabela e os campos */

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  for select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMIVA, ATU.BDEDITCHAVE,
             ATU.BDALIQINTERNA, SUM(ATU.BDVALPROD) AS BDVALPROD, ATU.BDALIQIVA, SUM(ATU.BDBASECALC) AS BDBASECALC,
             SUM(ATU.BDICMSDEST) AS BDICMSDEST, SUM(ATU.BDICMSRECOLHER) AS BDICMSRECOLHER, ATU.BDCODREC, ATU.BDDATAREC,
             SUM(ATU.BDVLRREC) AS BDVLRREC, ATU.BDCODPROD, ATU.BDDESTDA
      from (select MVA.BDCODEMP, MVA.BDCHAVE, MVA.BDORDEM, MVA.BDORDEMIVA, MVA.BDEDITCHAVE,
                   MVA.BDALIQINTERNA, MVA.BDVALPROD * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDVALPROD, MVA.BDALIQIVA,
                   MVA.BDBASECALC * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDBASECALC,
                   MVA.BDICMSDEST * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDICMSDEST,
                   MVA.BDICMSRECOLHER * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDICMSRECOLHER, MVA.BDCODREC, MVA.BDDATAREC,
                   MVA.BDVLRREC * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDVLRREC, MVA.BDCODPROD, MVA.BDDESTDA
            from TMP_VEF_EMP_TMOVENT_IVA_TEMP MVA
            inner join TMP_VEF_EMP_TMOVENTITENS_TEMP IT on IT.BDSESSAO = MVA.BDSESSAO and
                  IT.BDCODEMP = MVA.BDCODEMP and
                  IT.BDCHAVE = MVA.BDCHAVE and
                  IT.BDORDEM = MVA.BDORDEM and
                  IT.BDSESSAO = MVA.BDSESSAO
            where MVA.BDSESSAO = :PRSESSAO and
                  coalesce(IT.BDROW_EXCLUIDA, 0) <> 1
            union all
            select MVA.BDCODEMP, MVA.BDCHAVE, MVA.BDORDEM, MVA.BDORDEMIVA, MVA.BDEDITCHAVE,
                   MVA.BDALIQINTERNA, MVA.BDVALPROD * PR.BDRAZAORATEIO AS BDVALPROD, MVA.BDALIQIVA,
                   MVA.BDBASECALC * PR.BDRAZAORATEIO AS BDBASECALC,
                   MVA.BDICMSDEST * PR.BDRAZAORATEIO AS BDICMSDEST,
                   MVA.BDICMSRECOLHER * PR.BDRAZAORATEIO AS BDICMSRECOLHER, MVA.BDCODREC, MVA.BDDATAREC,
                   MVA.BDVLRREC * PR.BDRAZAORATEIO AS BDVLRREC, MVA.BDCODPROD, MVA.BDDESTDA
            from TMP_VEF_EMP_TMOVENT_IVA_TEMP MVA
            inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on MVA.BDSESSAO = PR.BDSESSAO and
                  MVA.BDCODEMP = PR.BDCODEMP and
                  MVA.BDCHAVE = PR.BDCHAVE and
                  MVA.BDORDEM = PR.BDORDEM_ORIG
            where MVA.BDSESSAO = :PRSESSAO) ATU
      group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMIVA, ATU.BDEDITCHAVE, ATU.BDALIQINTERNA, ATU.BDALIQIVA, ATU.BDCODREC,
               ATU.BDDATAREC,ATU.BDCODPROD, ATU.BDDESTDA
      into :WCODEMP, :WCHAVE, :WORDEM, :WORDEMIVA, :WEDITCHAVE, :WALIQINTERNA, :WVALPROD, :WALIQIVA, :WBASECALC, :WICMSDEST, :WICMSRECOLHER,
           :WCODREC, :WDATAREC, :WVLRREC, :WCODPROD, :WDESTDA
  do
  begin
    --Se a ordem vier aqui como -1, ent?o ? um lan?amento novo?
    if (:WORDEMIVA = -1) then
    begin
      WORDEM_SALVA = -1;

      --a primeira coisa ? procurar se j? tem algum lan?amento com os dados na chave/ordem
      select first 1 BDORDEMIVA
      from TMP_VEF_EMP_TMOVENT_IVA_TEMP
      where BDCHAVE = :WCHAVE and
            BDORDEM = :WORDEM and
            BDCODPROD = :WCODPROD and
   BDSESSAO = :PRSESSAO
      into :WORDEM_SALVA;

      --Se n?o tiver, vamos pegar a pr?xima
      if (coalesce(:WORDEM_SALVA, -1) = -1) then
      begin
        select max(BDORDEMIVA)
        from TMP_VEF_EMP_TMOVENT_IVA_TEMP
        where BDCHAVE = :WCHAVE and
              BDORDEM = :WORDEM and
     BDSESSAO = :PRSESSAO
        into :WORDEM_SALVA;

        WORDEM_SALVA = coalesce(:WORDEM_SALVA, 0) + 1;
      end

      --atualizamos a ordem ent?o
      WORDEMIVA = :WORDEM_SALVA;
    end

    --vamos agora fazer o update ou insert do registro
    UPDATE OR INSERT INTO TMP_VEF_EMP_TMOVENT_IVA_TEMP
        (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMIVA, BDEDITCHAVE, BDALIQINTERNA, BDVALPROD, BDALIQIVA, BDBASECALC, BDICMSDEST,
         BDICMSRECOLHER, BDCODREC, BDDATAREC, BDVLRREC, BDCODPROD, BDDESTDA)
        values(:PRSESSAO, :WCODEMP, :WCHAVE, :WORDEM, :WORDEMIVA, :WEDITCHAVE, :WALIQINTERNA, :WVALPROD, :WALIQIVA, :WBASECALC, :WICMSDEST,
               :WICMSRECOLHER, :WCODREC, :WDATAREC, :WVLRREC, :WCODPROD, :WDESTDA)
    MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMIVA);
  end

end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_MVASC (
    PRSESSAO integer)
as
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WORDEMMVA integer;
declare variable WEDITCHAVE integer;
declare variable WCODPROD integer;
declare variable WMVA numeric(7,4);
declare variable WALIQINT numeric(7,4);
declare variable WALIQEST numeric(7,4);
declare variable WMVAAJU numeric(7,4);
declare variable WICMS numeric(15,2);
declare variable WICMSNR numeric(15,2);
declare variable WARRECADACAO integer;
declare variable WNARREST varchar(25);
declare variable WORDEM_SALVA integer;
begin
  /* Esta aqui ? um SP de rateio, s?o de tabelas espec?ficas e ent?o o que uma faz as outras copiam, apenas mudando a tabela e os campos */

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  for select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMMVA, ATU.BDEDITCHAVE,
             ATU.BDCODPROD, ATU.BDMVA, ATU.BDALIQINT, ATU.BDALIQEST, ATU.BDMVAAJU,
             SUM(ATU.BDICMS) AS BDICMS, SUM(ATU.BDICMSNR) AS BDICMSNR, ATU.BDARRECADACAO, ATU.BDNARREST
      from (select MVA.BDCODEMP, MVA.BDCHAVE, MVA.BDORDEM, MVA.BDORDEMMVA, MVA.BDEDITCHAVE,
                   MVA.BDCODPROD, MVA.BDMVA, MVA.BDALIQINT, MVA.BDALIQEST, MVA.BDMVAAJU,
                   MVA.BDICMS * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDICMS,
                   MVA.BDICMSNR * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDICMSNR,
                   MVA.BDARRECADACAO, MVA.BDNARREST
            from TMP_VEF_EMP_TMOVMVASC_TEMP MVA
            inner join TMP_VEF_EMP_TMOVENTITENS_TEMP IT on IT.BDSESSAO = MVA.BDSESSAO and
                  IT.BDCODEMP = MVA.BDCODEMP and
                  IT.BDCHAVE = MVA.BDCHAVE and
                  IT.BDORDEM = MVA.BDORDEM and
                  IT.BDSESSAO = MVA.BDSESSAO
            where MVA.BDSESSAO = :PRSESSAO and
                  coalesce(IT.BDROW_EXCLUIDA, 0) <> 1
            union all
            select MVA.BDCODEMP, MVA.BDCHAVE, MVA.BDORDEM, MVA.BDORDEMMVA, MVA.BDEDITCHAVE,
                   MVA.BDCODPROD, MVA.BDMVA, MVA.BDALIQINT, MVA.BDALIQEST, MVA.BDMVAAJU,
                   MVA.BDICMS * PR.BDRAZAORATEIO AS BDICMS,
                   MVA.BDICMSNR * PR.BDRAZAORATEIO AS BDICMSNR,
                   MVA.BDARRECADACAO, MVA.BDNARREST
            from TMP_VEF_EMP_TMOVMVASC_TEMP MVA
            inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on MVA.BDSESSAO = PR.BDSESSAO and
                  MVA.BDCODEMP = PR.BDCODEMP and
                  MVA.BDCHAVE = PR.BDCHAVE and
                  MVA.BDORDEM = PR.BDORDEM_ORIG
            where MVA.BDSESSAO = :PRSESSAO) ATU
      group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMMVA, ATU.BDEDITCHAVE, ATU.BDCODPROD, ATU.BDMVA, ATU.BDALIQINT,
               ATU.BDALIQEST, ATU.BDMVAAJU, ATU.BDARRECADACAO, ATU.BDNARREST
      into :WCODEMP, :WCHAVE, :WORDEM, :WORDEMMVA, :WEDITCHAVE, :WCODPROD, :WMVA, :WALIQINT, :WALIQEST, :WMVAAJU, :WICMS, :WICMSNR, :WARRECADACAO, :WNARREST
  do
  begin
    --Se a ordem vier aqui como -1, ent?o ? um lan?amento novo?
    if (:WORDEMMVA = -1) then
    begin
      WORDEM_SALVA = -1;

      --a primeira coisa ? procurar se j? tem algum lan?amento com os dados na chave/ordem
      select first 1 BDORDEMMVA
      from TMP_VEF_EMP_TMOVMVASC_TEMP
      where BDCHAVE = :WCHAVE and
            BDORDEM = :WORDEM and
            BDCODPROD = :WCODPROD and
   BDSESSAO = :PRSESSAO
      into :WORDEM_SALVA;

      --Se n?o tiver, vamos pegar a pr?xima
      if (coalesce(:WORDEM_SALVA, -1) = -1) then
      begin
        select max(BDORDEMMVA)
        from TMP_VEF_EMP_TMOVMVASC_TEMP
        where BDCHAVE = :WCHAVE and
              BDORDEM = :WORDEM and 
     BDSESSAO = :PRSESSAO
        into :WORDEM_SALVA;

        WORDEM_SALVA = coalesce(:WORDEM_SALVA, 0) + 1;
      end

      --atualizamos a ordem ent?o
      WORDEMMVA = :WORDEM_SALVA;
    end

    --vamos agora fazer o update ou insert do registro
    UPDATE OR INSERT INTO TMP_VEF_EMP_TMOVMVASC_TEMP
        (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMMVA, BDEDITCHAVE, BDCODPROD, BDMVA, BDALIQINT, BDALIQEST, BDMVAAJU,
         BDICMS, BDICMSNR, BDARRECADACAO, BDNARREST)
        values(:PRSESSAO, :WCODEMP, :WCHAVE, :WORDEM, :WORDEMMVA, :WEDITCHAVE, :WCODPROD, :WMVA, :WALIQINT, :WALIQEST, :WMVAAJU,
               :WICMS, :WICMSNR, :WARRECADACAO, :WNARREST)
    MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMMVA);
  end

end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_MVAPR (
    PRSESSAO integer)
as
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WORDEMMVA integer;
declare variable WEDITCHAVE integer;
declare variable WCODPROD integer;
declare variable WVLRICMSST numeric(15,2);
declare variable WVLRICMSSTNAORET numeric(15,2);
declare variable WARRECADACAO integer;
declare variable WNUMARRECEST varchar(25);
declare variable WORDEM_SALVA integer;
begin
  /* Esta aqui ? um SP de rateio, s?o de tabelas espec?ficas e ent?o o que uma faz as outras copiam, apenas mudando a tabela e os campos */

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  for select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMMVA, ATU.BDEDITCHAVE,
             ATU.BDCODPROD, SUM(ATU.BDVLRICMSST) AS BDVLRICMSST, SUM(ATU.BDVLRICMSSTNAORET) AS BDVLRICMSSTNAORET,
             ATU.BDARRECADACAO, ATU.BDNUMARRECEST
      from (select MVA.BDCODEMP, MVA.BDCHAVE, MVA.BDORDEM, MVA.BDORDEMMVA, MVA.BDEDITCHAVE,
                   MVA.BDCODPROD, MVA.BDVLRICMSST * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDVLRICMSST,
                   MVA.BDVLRICMSSTNAORET * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDVLRICMSSTNAORET,
                   MVA.BDARRECADACAO, MVA.BDNUMARRECEST
            from TMP_VEF_EMP_TMOVMVAPR_TEMP MVA
            inner join TMP_VEF_EMP_TMOVENTITENS_TEMP IT on IT.BDSESSAO = MVA.BDSESSAO and
                  IT.BDCODEMP = MVA.BDCODEMP and
                  IT.BDCHAVE = MVA.BDCHAVE and
                  IT.BDORDEM = MVA.BDORDEM and
                  IT.BDSESSAO = MVA.BDSESSAO
            where MVA.BDSESSAO = :PRSESSAO and
                  coalesce(IT.BDROW_EXCLUIDA, 0) <> 1
            union all
            select MVA.BDCODEMP, MVA.BDCHAVE, MVA.BDORDEM, MVA.BDORDEMMVA, MVA.BDEDITCHAVE,
                   MVA.BDCODPROD, MVA.BDVLRICMSST * PR.BDRAZAORATEIO AS BDVLRICMSST,
                   MVA.BDVLRICMSSTNAORET * PR.BDRAZAORATEIO AS BDVLRICMSSTNAORET,
                   MVA.BDARRECADACAO, MVA.BDNUMARRECEST
            from TMP_VEF_EMP_TMOVMVAPR_TEMP MVA
            inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on MVA.BDSESSAO = PR.BDSESSAO and
                  MVA.BDCODEMP = PR.BDCODEMP and
                  MVA.BDCHAVE = PR.BDCHAVE and
                  MVA.BDORDEM = PR.BDORDEM_ORIG
            where MVA.BDSESSAO = :PRSESSAO) ATU
      group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMMVA, ATU.BDEDITCHAVE, ATU.BDCODPROD, ATU.BDARRECADACAO, ATU.BDNUMARRECEST
      into :WCODEMP, :WCHAVE, :WORDEM, :WORDEMMVA, :WEDITCHAVE, :WCODPROD, :WVLRICMSST, :WVLRICMSSTNAORET, :WARRECADACAO, :WNUMARRECEST
  do
  begin
    --Se a ordem vier aqui como -1, ent?o ? um lan?amento novo?
    if (:WORDEMMVA = -1) then
    begin
      WORDEM_SALVA = -1;

      --a primeira coisa ? procurar se j? tem algum lan?amento com os dados na chave/ordem
      select first 1 BDORDEMMVA
      from TMP_VEF_EMP_TMOVMVAPR_TEMP
      where BDCHAVE = :WCHAVE and
            BDORDEM = :WORDEM and
            BDCODPROD = :WCODPROD and
   BDSESSAO = :PRSESSAO
      into :WORDEM_SALVA;

      --Se n?o tiver, vamos pegar a pr?xima
      if (coalesce(:WORDEM_SALVA, -1) = -1) then
      begin
        select max(BDORDEMMVA)
        from TMP_VEF_EMP_TMOVMVAPR_TEMP
        where BDCHAVE = :WCHAVE and
              BDORDEM = :WORDEM and
     BDSESSAO = :PRSESSAO
        into :WORDEM_SALVA;

        WORDEM_SALVA = coalesce(:WORDEM_SALVA, 0) + 1;
      end

      --atualizamos a ordem ent?o
      WORDEMMVA = :WORDEM_SALVA;
    end

    --vamos agora fazer o update ou insert do registro
    UPDATE OR INSERT INTO TMP_VEF_EMP_TMOVMVAPR_TEMP
        (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMMVA, BDEDITCHAVE, BDCODPROD, BDVLRICMSST, BDVLRICMSSTNAORET, BDARRECADACAO, BDNUMARRECEST)
        values(:PRSESSAO, :WCODEMP, :WCHAVE, :WORDEM, :WORDEMMVA, :WEDITCHAVE, :WCODPROD, :WVLRICMSST, :WVLRICMSSTNAORET, :WARRECADACAO, :WNUMARRECEST)
    MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMMVA);
  end

end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_MVA (
    PRSESSAO integer)
as
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WORDEMMVA integer;
declare variable WORDEM_SALVA integer;
declare variable WEDITCHAVE integer;
declare variable WTOTMER numeric(15,2);
declare variable WVLRMERC numeric(15,2);
declare variable WOUTDESP numeric(15,2);
declare variable WVLRIPI numeric(15,2);
declare variable WVLRFRETERAT numeric(15,2);
declare variable WPERCMARGLUCRO numeric(9,4);
declare variable WPERCIMPDEST numeric(9,4);
declare variable WVLRIMPDEST numeric(15,2);
declare variable WALIQINTERNA numeric(7,4);
declare variable WPERCREDBC numeric(7,4);
declare variable WBCRETENCAO numeric(15,2);
declare variable WVLRIMPRET numeric(15,2);
declare variable WREGESP varchar(5);
declare variable WGUIARECOLHIDA numeric(15,2);
declare variable WVLRIMPREC numeric(15,2);
declare variable WPERCFEM numeric(7,4);
declare variable WVLRFEM numeric(15,2);
declare variable WBASESTDESTACADO numeric(15,2);
declare variable WIMPDESTACADONOTA numeric(15,2);
declare variable WTOTFRETE numeric(15,2);
begin
  /* Esta aqui ? um SP de rateio, s?o de tabelas espec?ficas e ent?o o que uma faz as outras copiam, apenas mudando a tabela e os campos */

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  for select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMMVA, ATU.BDEDITCHAVE,
             SUM(ATU.BDTOTMER) AS BDTOTMER, SUM(ATU.BDTOTFRETE) AS BDTOTFRETE, SUM(ATU.BDVLRMERC) AS BDVLRMERC,
             SUM(ATU.BDOUTDESP) AS BDOUTDESP, SUM(ATU.BDVLRIPI) AS BDVLRIPI, SUM(ATU.BDVLRFRETERAT) AS BDVLRFRETERAT,
             ATU.BDPERCMARGLUCRO, ATU.BDPERCIMPDEST, SUM(ATU.BDVLRIMPDEST) AS BDVLRIMPDEST, ATU.BDALIQINTERNA, ATU.BDPERCREDBC,
             SUM(ATU.BDBCRETENCAO) AS BDBCRETENCAO, SUM(ATU.BDVLRIMPRET) AS BDVLRIMPRET, ATU.BDREGESP,
             SUM(ATU.BDGUIARECOLHIDA) AS BDGUIARECOLHIDA, SUM(ATU.BDVLRIMPREC) AS BDVLRIMPREC, ATU.BDPERCFEM,
             SUM(ATU.BDVLRFEM) AS BDVLRFEM, SUM(ATU.BDBASESTDESTACADO) AS BDBASESTDESTACADO, SUM(ATU.BDIMPDESTACADONOTA) AS BDIMPDESTACADONOTA
      from (select MVA.BDCODEMP, MVA.BDCHAVE, MVA.BDORDEM, MVA.BDORDEMMVA, MVA.BDEDITCHAVE,
                   MVA.BDTOTMER * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDTOTMER,
                   MVA.BDTOTFRETE * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDTOTFRETE,
                   MVA.BDVLRMERC * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDVLRMERC,
                   MVA.BDOUTDESP * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDOUTDESP,
                   MVA.BDVLRIPI * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDVLRIPI,
                   MVA.BDVLRFRETERAT * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDVLRFRETERAT,
                   MVA.BDPERCMARGLUCRO, MVA.BDPERCIMPDEST,
                   MVA.BDVLRIMPDEST * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDVLRIMPDEST,
                   MVA.BDALIQINTERNA, MVA.BDPERCREDBC,
                   MVA.BDBCRETENCAO * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDBCRETENCAO,
                   MVA.BDVLRIMPRET * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDVLRIMPRET,
                   MVA.BDREGESP,
                   MVA.BDGUIARECOLHIDA * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDGUIARECOLHIDA,
                   MVA.BDVLRIMPREC * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDVLRIMPREC,
                   MVA.BDPERCFEM,
                   MVA.BDVLRFEM * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDVLRFEM,
                   MVA.BDBASESTDESTACADO * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDBASESTDESTACADO,
                   MVA.BDIMPDESTACADONOTA * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END AS BDIMPDESTACADONOTA
            from TMP_VEF_EMP_TMOVENTMVA_TEMP MVA
            inner join TMP_VEF_EMP_TMOVENTITENS_TEMP IT on IT.BDSESSAO = MVA.BDSESSAO and
                  IT.BDCODEMP = MVA.BDCODEMP and
                  IT.BDCHAVE = MVA.BDCHAVE and
                  IT.BDORDEM = MVA.BDORDEM and
                  IT.BDSESSAO = MVA.BDSESSAO
            where MVA.BDSESSAO = :PRSESSAO and
                  coalesce(IT.BDROW_EXCLUIDA, 0) <> 1
            union all
            select MVA.BDCODEMP, MVA.BDCHAVE, MVA.BDORDEM, MVA.BDORDEMMVA, MVA.BDEDITCHAVE,
                   MVA.BDTOTMER * PR.BDRAZAORATEIO AS BDTOTMER,
                   MVA.BDTOTFRETE * PR.BDRAZAORATEIO AS BDTOTFRETE,
                   MVA.BDVLRMERC * PR.BDRAZAORATEIO AS BDVLRMERC,
                   MVA.BDOUTDESP * PR.BDRAZAORATEIO AS BDOUTDESP,
                   MVA.BDVLRIPI * PR.BDRAZAORATEIO AS BDVLRIPI,
                   MVA.BDVLRFRETERAT * PR.BDRAZAORATEIO AS BDVLRFRETERAT,
                   MVA.BDPERCMARGLUCRO, MVA.BDPERCIMPDEST,
                   MVA.BDVLRIMPDEST * PR.BDRAZAORATEIO AS BDVLRIMPDEST,
                   MVA.BDALIQINTERNA, MVA.BDPERCREDBC,
                   MVA.BDBCRETENCAO * PR.BDRAZAORATEIO AS BDBCRETENCAO,
                   MVA.BDVLRIMPRET * PR.BDRAZAORATEIO AS BDVLRIMPRET,
                   MVA.BDREGESP,
                   MVA.BDGUIARECOLHIDA * PR.BDRAZAORATEIO AS BDGUIARECOLHIDA,
                   MVA.BDVLRIMPREC * PR.BDRAZAORATEIO AS BDVLRIMPREC,
                   MVA.BDPERCFEM,
                   MVA.BDVLRFEM * PR.BDRAZAORATEIO AS BDVLRFEM,
                   MVA.BDBASESTDESTACADO * PR.BDRAZAORATEIO AS BDBASESTDESTACADO,
                   MVA.BDIMPDESTACADONOTA * PR.BDRAZAORATEIO AS BDIMPDESTACADONOTA
            from TMP_VEF_EMP_TMOVENTMVA_TEMP MVA
            inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on MVA.BDSESSAO = PR.BDSESSAO and
                  MVA.BDCODEMP = PR.BDCODEMP and
                  MVA.BDCHAVE = PR.BDCHAVE and
                  MVA.BDORDEM = PR.BDORDEM_ORIG
            where MVA.BDSESSAO = :PRSESSAO) ATU
      group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMMVA, ATU.BDEDITCHAVE, ATU.BDPERCMARGLUCRO, ATU.BDPERCIMPDEST,
               ATU.BDALIQINTERNA, ATU.BDPERCREDBC, ATU.BDREGESP, ATU.BDPERCFEM
      into :WCODEMP, :WCHAVE, :WORDEM, :WORDEMMVA, :WEDITCHAVE, :WTOTMER, :WTOTFRETE, :WVLRMERC, :WOUTDESP, :WVLRIPI, :WVLRFRETERAT,
           :WPERCMARGLUCRO, :WPERCIMPDEST, :WVLRIMPDEST, :WALIQINTERNA, :WPERCREDBC, :WBCRETENCAO, :WVLRIMPRET, :WREGESP, :WGUIARECOLHIDA,
           :WVLRIMPREC, :WPERCFEM, :WVLRFEM, :WBASESTDESTACADO, :WIMPDESTACADONOTA
  do
  begin
    --Se a ordem vier aqui como -1, ent?o ? um lan?amento novo?
    if (:WORDEMMVA = -1) then
    begin
      WORDEM_SALVA = -1;

      --a primeira coisa ? procurar se j? tem algum lan?amento com os dados na chave/ordem
      select first 1 BDORDEMMVA
      from TMP_VEF_EMP_TMOVENTMVA_TEMP
      where BDCHAVE = :WCHAVE and
            BDORDEM = :WORDEM and
            BDPERCIMPDEST = :WPERCIMPDEST and
   BDSESSAO = :PRSESSAO
      into :WORDEM_SALVA;

      --Se n?o tiver, vamos pegar a pr?xima
      if (coalesce(:WORDEM_SALVA, -1) = -1) then
      begin
        select max(BDORDEMMVA)
        from TMP_VEF_EMP_TMOVENTMVA_TEMP
        where BDCHAVE = :WCHAVE and
              BDORDEM = :WORDEM and
     BDSESSAO = :PRSESSAO
        into :WORDEM_SALVA;

        WORDEM_SALVA = coalesce(:WORDEM_SALVA, 0) + 1;
      end

      --atualizamos a ordem ent?o
      WORDEMMVA = :WORDEM_SALVA;
    end

    --vamos agora fazer o update ou insert do registro
    UPDATE OR INSERT INTO TMP_VEF_EMP_TMOVENTMVA_TEMP
        (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMMVA, BDEDITCHAVE, BDTOTMER, BDTOTFRETE, BDVLRMERC, BDOUTDESP, BDVLRIPI, BDVLRFRETERAT,
         BDPERCMARGLUCRO, BDPERCIMPDEST, BDVLRIMPDEST, BDALIQINTERNA, BDPERCREDBC, BDBCRETENCAO, BDVLRIMPRET, BDREGESP, BDGUIARECOLHIDA,
         BDVLRIMPREC, BDPERCFEM, BDVLRFEM,  BDBASESTDESTACADO, BDIMPDESTACADONOTA)
        values(:PRSESSAO, :WCODEMP, :WCHAVE, :WORDEM, :WORDEMMVA, :WEDITCHAVE, :WTOTMER, :WTOTFRETE, :WVLRMERC, :WOUTDESP, :WVLRIPI, :WVLRFRETERAT,
               :WPERCMARGLUCRO, :WPERCIMPDEST, :WVLRIMPDEST, :WALIQINTERNA, :WPERCREDBC, :WBCRETENCAO, :WVLRIMPRET, :WREGESP, :WGUIARECOLHIDA,
               :WVLRIMPREC, :WPERCFEM, :WVLRFEM,  :WBASESTDESTACADO, :WIMPDESTACADONOTA)
    MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMMVA);
  end

end^

create or alter procedure SP_FISCAL_RATEIA_PMPF (
    PRSESSAO integer)
as
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WORDEMPMPF integer;
declare variable WEDITCHAVE integer;
declare variable WORDEM_SALVA integer;
declare variable WVLRTOTALPROD numeric(15,2);
declare variable WALIQIMPDEST numeric(7,4);
declare variable WVLRIMPDEST numeric(15,2);
declare variable WQTDPROD numeric(12,2);
declare variable WPMPFUNID numeric(15,2);
declare variable WALIQINTERNA numeric(7,4);
declare variable WREDBC numeric(7,4);
declare variable WBCRETENCAO numeric(15,2);
declare variable WVLRIMPRET numeric(15,2);
declare variable WALIQFEM numeric(7,4);
declare variable WVLRFEM numeric(15,2);
begin
  /* Esta aqui ? um SP de rateio, s?o de tabelas espec?ficas e ent?o o que uma faz as outras copiam, apenas mudando a tabela e os campos */

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  for select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMPMPF, ATU.BDEDITCHAVE,
             ATU.BDQTDPROD, ATU.BDPMPFUNID, ATU.BDALIQINTERNA, ATU.BDREDBC, ATU.BDALIQFEM, ATU.BDALIQIMPDEST,
             sum(ATU.BDVLRTOTALPROD) as BDVLRTOTALPROD,
             sum(ATU.BDBCRETENCAO) as BDBCRETENCAO,
             sum(ATU.BDVLRIMPRET) as BDVLRIMPRET,
             sum(ATU.BDVLRIMPDEST) as BDVLRIMPDEST,
             sum(ATU.BDVLRFEM) as BDVLRFEM
      from (select pmpf.BDCODEMP, pmpf.BDCHAVE, pmpf.BDORDEM, pmpf.BDORDEMPMPF, pmpf.BDEDITCHAVE,
                   pmpf.BDQTDPROD, pmpf.BDPMPFUNID, pmpf.BDALIQINTERNA, pmpf.BDREDBC, pmpf.BDALIQFEM, pmpf.BDALIQIMPDEST,
                   coalesce(pmpf.BDVLRTOTALPROD, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRTOTALPROD,
                   coalesce(pmpf.BDBCRETENCAO, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDBCRETENCAO,
                   coalesce(pmpf.BDVLRIMPRET, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRIMPRET,
                   coalesce(pmpf.BDVLRIMPDEST, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRIMPDEST,
                   coalesce(pmpf.BDVLRFEM, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRFEM
            from TMP_VEF_EMP_TMOVENTPMPF_TEMP pmpf
            inner join TMP_VEF_EMP_TMOVENTITENS_TEMP IT on IT.BDSESSAO = pmpf.BDSESSAO and
                  IT.BDCODEMP = pmpf.BDCODEMP and
                  IT.BDCHAVE = pmpf.BDCHAVE and
                  IT.BDORDEM = pmpf.BDORDEM and
                  IT.BDSESSAO = pmpf.BDSESSAO
            where pmpf.BDSESSAO = :PRSESSAO and
                  coalesce(IT.BDROW_EXCLUIDA, 0) <> 1
            union all
            select pmpf.BDCODEMP, pmpf.BDCHAVE, PR.BDORDEM_ATU, -1 as BDORDEMPMPF, pmpf.BDEDITCHAVE,
                   pmpf.BDQTDPROD, pmpf.BDPMPFUNID, pmpf.BDALIQINTERNA, pmpf.BDREDBC, pmpf.BDALIQFEM, pmpf.BDALIQIMPDEST,
                   coalesce(pmpf.BDVLRTOTALPROD, 0) * PR.BDRAZAORATEIO as BDVLRTOTALPROD,
                   coalesce(pmpf.BDBCRETENCAO, 0) * PR.BDRAZAORATEIO as BDBCRETENCAO,
                   coalesce(pmpf.BDVLRIMPRET, 0) * PR.BDRAZAORATEIO as BDVLRIMPRET,
                   coalesce(pmpf.BDVLRIMPDEST, 0) * PR.BDRAZAORATEIO as BDVLRIMPDEST,
                   coalesce(pmpf.BDVLRFEM, 0) * PR.BDRAZAORATEIO as BDVLRFEM
            from TMP_VEF_EMP_TMOVENTPMPF_TEMP pmpf
            inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on pmpf.BDSESSAO = PR.BDSESSAO and
                  pmpf.BDCODEMP = PR.BDCODEMP and
                  pmpf.BDCHAVE = PR.BDCHAVE and
                  pmpf.BDORDEM = PR.BDORDEM_ORIG
            where pmpf.BDSESSAO = :PRSESSAO) ATU
      group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMPMPF, ATU.BDEDITCHAVE,
               ATU.BDQTDPROD, ATU.BDPMPFUNID, ATU.BDALIQINTERNA, ATU.BDREDBC, ATU.BDALIQFEM, ATU.BDALIQIMPDEST
      into :WCODEMP, :WCHAVE, :WORDEM, :WORDEMPMPF, :WEDITCHAVE, :WQTDPROD, :WPMPFUNID, :WALIQINTERNA, :WREDBC, :WALIQFEM,
           :WALIQIMPDEST, :WVLRTOTALPROD, :WBCRETENCAO, :WVLRIMPRET, :WVLRIMPDEST, :WVLRFEM
  do
  begin
    --Se a ordem vier aqui como -1, ent?o ? um lan?amento novo?
    if (:WORDEMPMPF = -1) then
    begin
      WORDEM_SALVA = -1;

      --a primeira coisa ? procurar se j? tem algum lan?amento com os dados na chave/ordem
      select first 1 BDORDEMPMPF
      from TMP_VEF_EMP_TMOVENTPMPF_TEMP
      where BDCHAVE = :WCHAVE and
            BDORDEM = :WORDEM and
            BDALIQIMPDEST = :WALIQIMPDEST and
            BDALIQINTERNA = :WALIQINTERNA and
   BDSESSAO = :PRSESSAO
      into :WORDEM_SALVA;

      --Se n?o tiver, vamos pegar a pr?xima
      if (coalesce(:WORDEM_SALVA, -1) = -1) then
      begin
        select max(BDORDEMPMPF)
        from TMP_VEF_EMP_TMOVENTPMPF_TEMP
        where BDCHAVE = :WCHAVE and
              BDORDEM = :WORDEM and
     BDSESSAO = :PRSESSAO
        into :WORDEM_SALVA;

        WORDEM_SALVA = coalesce(:WORDEM_SALVA, 0) + 1;
      end

      --atualizamos a ordem ent?o
      WORDEMPMPF = :WORDEM_SALVA;
    end

    --vamos agora fazer o update ou insert do registro
    UPDATE OR INSERT INTO TMP_VEF_EMP_TMOVENTPMPF_TEMP
        (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPMPF, BDEDITCHAVE, BDVLRTOTALPROD, BDALIQIMPDEST, BDVLRIMPDEST, BDQTDPROD,
         BDPMPFUNID, BDALIQINTERNA, BDREDBC, BDBCRETENCAO, BDVLRIMPRET, BDALIQFEM, BDVLRFEM)
        values(:PRSESSAO, :WCODEMP, :WCHAVE, :WORDEM, :WORDEMPMPF, :WEDITCHAVE, :WVLRTOTALPROD, :WALIQIMPDEST, :WVLRIMPDEST, :WQTDPROD,
               :WPMPFUNID, :WALIQINTERNA, :WREDBC, :WBCRETENCAO, :WVLRIMPRET, :WALIQFEM, :WVLRFEM)
    MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPMPF);
  end

end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_DCIP (
    PRSESSAO integer)
as
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WEDITCHAVE integer;
declare variable WCODTPCREDPRE integer;
declare variable WBASECRED bigint;
declare variable WALIQCRED integer;
declare variable WVALORCRED bigint;
declare variable WBASE_AUX bigint;
declare variable WVALOR_AUX bigint;
declare variable WORIGEM integer;
begin
  /* Esta aqui ? um SP de rateio, s?o de tabelas espec?ficas e ent?o o que uma faz as outras copiam, apenas mudando a tabela e os campos */

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  for select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDEDITCHAVE, ATU.BDCODTPCREDPRE, sum(ATU.BDBASECRED) as BDBASECRED,
             ATU.BDALIQCRED, sum(ATU.BDVALORCRED) as BDVALORCRED, ATU.BDORIGEM
      from (select DCIP.BDCODEMP, DCIP.BDCHAVE, DCIP.BDORDEM, DCIP.BDEDITCHAVE, DCIP.BDCODTPCREDPRE,
                   DCIP.BDBASECRED * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDBASECRED, DCIP.BDALIQCRED,
                   coalesce(DCIP.BDVALORCRED, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVALORCRED, 1 AS BDORIGEM
            from TMP_VEF_EMP_TMOVENTDCIP_TEMP DCIP
            inner join TMP_VEF_EMP_TMOVENTITENS_TEMP IT on IT.BDSESSAO = DCIP.BDSESSAO and
                  IT.BDCODEMP = DCIP.BDCODEMP and
                  IT.BDCHAVE = DCIP.BDCHAVE and
                  IT.BDORDEM = DCIP.BDORDEM and
                  IT.BDSESSAO = DCIP.BDSESSAO
            where DCIP.BDSESSAO = :PRSESSAO and
                  coalesce(IT.BDROW_EXCLUIDA, 0) <> 1
            union all
            select DCIP.BDCODEMP, DCIP.BDCHAVE, PR.BDORDEM_ATU, DCIP.BDEDITCHAVE, DCIP.BDCODTPCREDPRE,
                   DCIP.BDBASECRED * PR.BDRAZAORATEIO as BDBASECRED, DCIP.BDALIQCRED,
                   coalesce(DCIP.BDVALORCRED, 0) * PR.BDRAZAORATEIO as BDVALORCRED, 2 AS BDORIGEM
            from TMP_VEF_EMP_TMOVENTDCIP_TEMP DCIP
            inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on DCIP.BDSESSAO = PR.BDSESSAO and
                  DCIP.BDCODEMP = PR.BDCODEMP and
                  DCIP.BDCHAVE = PR.BDCHAVE and
                  DCIP.BDORDEM = PR.BDORDEM_ORIG
            where DCIP.BDSESSAO = :PRSESSAO) ATU
      group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDEDITCHAVE, ATU.BDCODTPCREDPRE, ATU.BDALIQCRED, ATU.BDORIGEM
      into :WCODEMP, :WCHAVE, :WORDEM, :WEDITCHAVE, :WCODTPCREDPRE, :WBASECRED, :WALIQCRED, :WVALORCRED, :WORIGEM
  do
  begin
    --Vamos ver se j? n?o existe e fazer a soma neste caso aqui
    if (:WORIGEM = 2) then
    begin
      select first 1 coalesce(BDBASECRED, 0) AS BDBASECRED, coalesce(BDVALORCRED, 0) AS BDVALORCRED
      from TMP_VEF_EMP_TMOVENTDCIP_TEMP
      where BDCHAVE = :WCHAVE and
            BDORDEM = :WORDEM and 
   BDSESSAO = :PRSESSAO
      into :WBASE_AUX, :WVALOR_AUX;

      WBASECRED  = coalesce(:WBASECRED, 0) + coalesce(:WBASE_AUX, 0);
      WVALORCRED = coalesce(:WVALORCRED, 0) + coalesce(:WVALOR_AUX, 0);
    end

    --vamos agora fazer o update ou insert do registro
    UPDATE OR INSERT INTO TMP_VEF_EMP_TMOVENTDCIP_TEMP 
        (BDSESSAO, BDEDITCHAVE, BDCODEMP, BDCHAVE, BDORDEM, BDCODTPCREDPRE, BDBASECRED, BDALIQCRED, BDVALORCRED)
        values(:PRSESSAO, :WEDITCHAVE, :WCODEMP, :WCHAVE, :WORDEM, :WCODTPCREDPRE, :WBASECRED, :WALIQCRED, :WVALORCRED)
    MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM);
  end

end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_ANTIMP (
    PRSESSAO integer)
as
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WORDEMANT integer;
declare variable WORDEM_SALVA integer;
declare variable WBASE numeric(18,2);
declare variable WPERCENTUAL numeric(18,6);
declare variable WVALOR numeric(18,2);
declare variable WEDITCHAVE integer;
declare variable WVLRMERC numeric(15,2);
declare variable WVLRIPI numeric(15,2);
declare variable WVLROUTDESP numeric(15,2);
declare variable WVLRFRETE numeric(15,2);
declare variable WALIQORIGEM numeric(7,4);
declare variable WICMSORIGEM numeric(15,2);
declare variable WALIQINTERNA numeric(7,4);
declare variable WEXCLUICMS numeric(15,2);
declare variable WINCLUICMSINTERNO numeric(15,2);
declare variable WDIFINTERNO numeric(15,2);
declare variable WALIQFEM numeric(7,4);
declare variable WVLRFEM numeric(15,2);
declare variable WIMPRECOLHER numeric(15,2);
begin
  /* Esta aqui ? um SP de rateio, s?o de tabelas espec?ficas e ent?o o que uma faz as outras copiam, apenas mudando a tabela e os campos */

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  for select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMANT, ATU.BDEDITCHAVE, sum(ATU.BDBASE) as BDBASE,
             ATU.BDPERCENTUAL, sum(ATU.BDVALOR) as BDVALOR, sum(ATU.BDVLRMERC) as BDVLRMERC, sum(ATU.BDVLRIPI) as BDVLRIPI,
             sum(ATU.BDVLROUTDESP) as BDVLROUTDESP, sum(ATU.BDVLRFRETE) as BDVLRFRETE, ATU.BDALIQORIGEM,
             sum(ATU.BDICMSORIGEM) as BDICMSORIGEM, ATU.BDALIQINTERNA, sum(ATU.BDEXCLUICMS) as BDEXCLUICMS,
             sum(ATU.BDINCLUICMSINTERNO) as BDINCLUICMSINTERNO, sum(ATU.BDDIFINTERNO) as BDDIFINTERNO, ATU.BDALIQFEM,
             sum(ATU.BDVLRFEM) as BDVLRFEM, sum(ATU.BDIMPRECOLHER) as BDIMPRECOLHER
      from (select ANT.BDCODEMP, ANT.BDCHAVE, ANT.BDORDEM, ANT.BDORDEMANT, ANT.BDEDITCHAVE,
                   ANT.BDBASE * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDBASE, ANT.BDPERCENTUAL,
                   coalesce(ANT.BDVALOR, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVALOR,
                   coalesce(ANT.BDVLRMERC, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRMERC,
                   coalesce(ANT.BDVLRIPI, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRIPI,
                   coalesce(ANT.BDVLROUTDESP, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLROUTDESP,
                   coalesce(ANT.BDVLRFRETE, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRFRETE, ANT.BDALIQORIGEM,
                   coalesce(ANT.BDICMSORIGEM, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDICMSORIGEM, ANT.BDALIQINTERNA,
                   coalesce(ANT.BDEXCLUICMS, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDEXCLUICMS,
                   coalesce(ANT.BDINCLUICMSINTERNO, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDINCLUICMSINTERNO,
                   coalesce(ANT.BDDIFINTERNO, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDDIFINTERNO, ANT.BDALIQFEM,
                   coalesce(ANT.BDVLRFEM, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRFEM,
                   coalesce(ANT.BDIMPRECOLHER, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDIMPRECOLHER
            from TMP_VEF_EMP_TMOVENTANTIMP_TEMP ANT
            inner join TMP_VEF_EMP_TMOVENTITENS_TEMP IT on IT.BDSESSAO = ANT.BDSESSAO and
                  IT.BDCODEMP = ANT.BDCODEMP and
                  IT.BDCHAVE = ANT.BDCHAVE and
                  IT.BDORDEM = ANT.BDORDEM and
                  IT.BDSESSAO = ANT.BDSESSAO
            where ANT.BDSESSAO = :PRSESSAO and
                  coalesce(IT.BDROW_EXCLUIDA, 0) <> 1
            union all
            select ANT.BDCODEMP, ANT.BDCHAVE, PR.BDORDEM_ATU, -1 as BDORDEMANT, ANT.BDEDITCHAVE,
                   ANT.BDBASE * PR.BDRAZAORATEIO as BDBASE, ANT.BDPERCENTUAL,
                   coalesce(ANT.BDVALOR, 0) * PR.BDRAZAORATEIO as BDVALOR,
                   coalesce(ANT.BDVLRMERC, 0) * PR.BDRAZAORATEIO as BDVLRMERC,
                   coalesce(ANT.BDVLRIPI, 0) * PR.BDRAZAORATEIO as BDVLRIPI,
                   coalesce(ANT.BDVLROUTDESP, 0) * PR.BDRAZAORATEIO as BDVLROUTDESP,
                   coalesce(ANT.BDVLRFRETE, 0) * PR.BDRAZAORATEIO as BDVLRFRETE, ANT.BDALIQORIGEM,
                   coalesce(ANT.BDICMSORIGEM, 0) * PR.BDRAZAORATEIO as BDICMSORIGEM, ANT.BDALIQINTERNA,
                   coalesce(ANT.BDEXCLUICMS, 0) * PR.BDRAZAORATEIO as BDEXCLUICMS,
                   coalesce(ANT.BDINCLUICMSINTERNO, 0) * PR.BDRAZAORATEIO as BDINCLUICMSINTERNO,
                   coalesce(ANT.BDDIFINTERNO, 0) * PR.BDRAZAORATEIO as BDDIFINTERNO, ANT.BDALIQFEM,
                   coalesce(ANT.BDVLRFEM, 0) * PR.BDRAZAORATEIO as BDVLRFEM,
                   coalesce(ANT.BDIMPRECOLHER, 0) * PR.BDRAZAORATEIO as BDIMPRECOLHER
            from TMP_VEF_EMP_TMOVENTANTIMP_TEMP ANT
            inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on ANT.BDSESSAO = PR.BDSESSAO and
                  ANT.BDCODEMP = PR.BDCODEMP and
                  ANT.BDCHAVE = PR.BDCHAVE and
                  ANT.BDORDEM = PR.BDORDEM_ORIG
            where ANT.BDSESSAO = :PRSESSAO) ATU
      group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMANT, ATU.BDEDITCHAVE, ATU.BDPERCENTUAL, ATU.BDALIQORIGEM,
               ATU.BDALIQINTERNA, ATU.BDALIQFEM
      into :WCODEMP, :WCHAVE, :WORDEM, :WORDEMANT, :WEDITCHAVE, :WBASE, :WPERCENTUAL, :WVALOR, :WVLRMERC, :WVLRIPI, :WVLROUTDESP,
           :WVLRFRETE, :WALIQORIGEM, :WICMSORIGEM, :WALIQINTERNA, :WEXCLUICMS, :WINCLUICMSINTERNO, :WDIFINTERNO, :WALIQFEM,
           :WVLRFEM, :WIMPRECOLHER
  do
  begin
    --Se a ordem vier aqui como -1, ent?o ? um lan?amento novo?
    if (:WORDEMANT = -1) then
    begin
      WORDEM_SALVA = -1;

      --a primeira coisa ? procurar se j? tem algum lan?amento com os dados na chave/ordem
      select first 1 BDORDEMANT
      from TMP_VEF_EMP_TMOVENTANTIMP_TEMP
      where BDCHAVE = :WCHAVE and
            BDORDEM = :WORDEM and
            BDALIQORIGEM = :WALIQORIGEM and
            BDALIQINTERNA = :WALIQINTERNA and
   BDSESSAO = :PRSESSAO
      into :WORDEM_SALVA;

      --Se n?o tiver, vamos pegar a pr?xima
      if (coalesce(:WORDEM_SALVA, -1) = -1) then
      begin
        select max(BDORDEMANT)
        from TMP_VEF_EMP_TMOVENTANTIMP_TEMP
        where BDCHAVE = :WCHAVE and
              BDORDEM = :WORDEM and
     BDSESSAO = :PRSESSAO
        into :WORDEM_SALVA;

        WORDEM_SALVA = coalesce(:WORDEM_SALVA, 0) + 1;
      end

      --atualizamos a ordem ent?o
      WORDEMANT = :WORDEM_SALVA;
    end

    --vamos agora fazer o update ou insert do registro
    UPDATE OR INSERT INTO TMP_VEF_EMP_TMOVENTANTIMP_TEMP
        (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMANT, BDEDITCHAVE, BDBASE, BDPERCENTUAL, BDVALOR, BDVLRMERC,
         BDVLRIPI, BDVLROUTDESP, BDVLRFRETE, BDALIQORIGEM, BDICMSORIGEM, BDALIQINTERNA, BDEXCLUICMS, BDINCLUICMSINTERNO,
         BDDIFINTERNO, BDALIQFEM, BDVLRFEM, BDIMPRECOLHER)
        values(:PRSESSAO, :WCODEMP, :WCHAVE, :WORDEM, :WORDEMANT, :WEDITCHAVE, :WBASE, :WPERCENTUAL, :WVALOR, :WVLRMERC,
               :WVLRIPI, :WVLROUTDESP, :WVLRFRETE, :WALIQORIGEM, :WICMSORIGEM, :WALIQINTERNA, :WEXCLUICMS, :WINCLUICMSINTERNO,
               :WDIFINTERNO, :WALIQFEM, :WVLRFEM, :WIMPRECOLHER)
    MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMANT);
  end
end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_ANTPR (
    PRSESSAO integer)
as
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WORDEMANT integer;
declare variable WEDITCHAVE integer;
declare variable WBASEANT numeric(15,2);
declare variable WVLRANT numeric(15,2);
declare variable WALIQORIGEM numeric(7,4);
declare variable WALIQDESTINO numeric(7,4);
declare variable WORDEM_SALVA integer;
declare variable WBASE_SALVA numeric(15,2);
declare variable WVLR_SALVA numeric(15,2);
begin
  /* Esta aqui ? um SP de rateio, s?o de tabelas espec?ficas e ent?o o que uma faz as outras copiam, apenas mudando a tabela e os campos */

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  for select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMANT, ATU.BDEDITCHAVE, sum(ATU.BDVLRANT) as BDVLRANT,
             ATU.BDALIQORIGEM, ATU.BDALIQDESTINO, sum(ATU.BDBASEANT) as BDBASEANT
      from (select ANT.BDCODEMP, ANT.BDCHAVE, ANT.BDORDEM, ANT.BDORDEMANT, ANT.BDEDITCHAVE,
                   ANT.BDVLRANT * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRANT, ANT.BDALIQORIGEM, ANT.BDALIQDESTINO,
                   coalesce(ANT.BDBASEANT, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDBASEANT
            from TMP_VEF_EMP_TMOVENTANTPR_TEMP ANT
            inner join TMP_VEF_EMP_TMOVENTITENS_TEMP IT on IT.BDSESSAO = ANT.BDSESSAO and
                  IT.BDCODEMP = ANT.BDCODEMP and
                  IT.BDCHAVE = ANT.BDCHAVE and
                  IT.BDORDEM = ANT.BDORDEM and
                  IT.BDSESSAO = ANT.BDSESSAO
            where ANT.BDSESSAO = :PRSESSAO and
                  coalesce(IT.BDROW_EXCLUIDA, 0) <> 1
            union all
            select ANT.BDCODEMP, ANT.BDCHAVE, PR.BDORDEM_ATU, -1 as BDORDEMANT, ANT.BDEDITCHAVE,
                   ANT.BDVLRANT * PR.BDRAZAORATEIO as BDVLRANT, ANT.BDALIQORIGEM, ANT.BDALIQDESTINO,
                   coalesce(ANT.BDBASEANT, 0) * PR.BDRAZAORATEIO as BDBASEANT
            from TMP_VEF_EMP_TMOVENTANTPR_TEMP ANT
            inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on ANT.BDSESSAO = PR.BDSESSAO and
                  ANT.BDCODEMP = PR.BDCODEMP and
                  ANT.BDCHAVE = PR.BDCHAVE and
                  ANT.BDORDEM = PR.BDORDEM_ORIG
            where ANT.BDSESSAO = :PRSESSAO) ATU
      group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMANT, ATU.BDEDITCHAVE, ATU.BDALIQORIGEM, ATU.BDALIQDESTINO
      order by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMANT desc, ATU.BDALIQORIGEM, ATU.BDALIQORIGEM
      into :WCODEMP, :WCHAVE, :WORDEM, :WORDEMANT, :WEDITCHAVE, :WVLRANT, :WALIQORIGEM, :WALIQDESTINO, :WBASEANT
  do
  begin
    --Se a ordem vier aqui como -1, ent?o ? um lan?amento novo?
    if (:WORDEMANT = -1) then
    begin
      WORDEM_SALVA = -1;

      --a primeira coisa ? procurar se j? tem algum lan?amento com os dados na chave/ordem
      select first 1 BDORDEMANT, BDBASEANT, BDVLRANT
      from TMP_VEF_EMP_TMOVENTANTPR_TEMP
      where BDCHAVE = :WCHAVE and
            BDORDEM = :WORDEM and
            BDALIQORIGEM = :WALIQORIGEM and
            BDALIQDESTINO = :WALIQDESTINO and
            BDSESSAO = :PRSESSAO
      into :WORDEM_SALVA, :WBASE_SALVA, WVLR_SALVA;

      --Se n?o tiver, vamos pegar a pr?xima
      if (coalesce(:WORDEM_SALVA, -1) = -1) then
         begin
           select max(BDORDEMANT)
           from TMP_VEF_EMP_TMOVENTANTPR_TEMP
           where BDCHAVE = :WCHAVE and
                 BDORDEM = :WORDEM and
                 BDSESSAO = :PRSESSAO
           into :WORDEM_SALVA;

           WORDEM_SALVA = coalesce(:WORDEM_SALVA, 0) + 1;
         end
      else
         begin
            WBASEANT = :WBASEANT + coalesce(:WBASE_SALVA, 0);
            WVLRANT  = :WVLRANT  + coalesce(:WVLR_SALVA, 0);
         end

      --atualizamos a ordem ent?o
      WORDEMANT = :WORDEM_SALVA;
    end

    --vamos agora fazer o update ou insert do registro
    UPDATE OR INSERT INTO TMP_VEF_EMP_TMOVENTANTPR_TEMP
        (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMANT, BDEDITCHAVE, BDBASEANT, BDALIQORIGEM, BDALIQDESTINO, BDVLRANT)
        values(:PRSESSAO, :WCODEMP, :WCHAVE, :WORDEM, :WORDEMANT, :WEDITCHAVE, :WBASEANT, :WALIQORIGEM, :WALIQDESTINO, :WVLRANT)
    MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMANT);
  end

end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_DAPI (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
declare variable WMOVIMENTO varchar(3);
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WEDITCHAVE integer;
declare variable WTIPOISEOUT integer;
declare variable WVALOR numeric(15,2);
declare variable WORDEMST integer;
declare variable WCODTIPODAPI integer;
declare variable WSQL varchar(10000);
declare variable WSQL_AUX varchar(10000);
declare variable WORDEM_SALVA integer;
begin
  if (prmovimento = 0) then
     begin
        :wmovimento = 'ENT';
     end
  else
     begin
        :wmovimento = 'SAI';
     end

   wSQL = ' select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDEDITCHAVE, ATU.BDTIPOISEOUT, '||
          '       sum(ATU.BDVALOR) as BDVALOR, ATU.BDORDEMST, ATU.BDCODTIPODAPI '||
          'from (select DAPI.BDCODEMP, DAPI.BDCHAVE, DAPI.BDORDEM, DAPI.BDEDITCHAVE, DAPI.BDTIPOISEOUT, '||
          '                   DAPI.BDVALOR * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVALOR, '||
          '                   DAPI.BDORDEMST, DAPI.BDCODTIPODAPI '||
          '            from TMP_VEF_EMP_TMOV' || :wmovimento || 'STDAPI_TEMP DAPI '||
          '            inner join TMP_VEF_EMP_TMOVENTITENS_TEMP IT on IT.BDSESSAO = DAPI.BDSESSAO and '||
          '                  IT.BDCODEMP = DAPI.BDCODEMP and '||
          '                  IT.BDCHAVE = DAPI.BDCHAVE and '||
          '                  IT.BDORDEM = DAPI.BDORDEM and '||
          '                  IT.BDSESSAO = DAPI.BDSESSAO '||
          '            where DAPI.BDSESSAO = ' || :prSessao || ' and '||
          '                  coalesce(IT.BDROW_EXCLUIDA, 0) <> 1 '||
          '            union all '||
          '            select DAPI.BDCODEMP, DAPI.BDCHAVE, PR.BDORDEM_ATU, DAPI.BDEDITCHAVE, DAPI.BDTIPOISEOUT, '||
          '                   DAPI.BDVALOR * PR.BDRAZAORATEIO as BDVALOR, '||
          '                   DAPI.BDORDEMST, DAPI.BDCODTIPODAPI '||
          '            from TMP_VEF_EMP_TMOV' || :wmovimento || 'STDAPI_TEMP DAPI '||
          '            inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on DAPI.BDSESSAO = PR.BDSESSAO and '||
          '                  DAPI.BDCODEMP = PR.BDCODEMP and '||
          '                  DAPI.BDCHAVE = PR.BDCHAVE and '||
          '                  DAPI.BDORDEM = PR.BDORDEM_ORIG '||
          '            where DAPI.BDSESSAO = ' || :prSessao || ') ATU '||
          'group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDEDITCHAVE, ATU.BDTIPOISEOUT, ATU.BDORDEMST, ATU.BDCODTIPODAPI';

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  for execute statement wsql into
         :WCODEMP, :WCHAVE, :WORDEM, :WEDITCHAVE, :WTIPOISEOUT, :WVALOR, :WORDEMST, :WCODTIPODAPI
  do
     begin
        --Se a ordem vier aqui como -1, ent?o ? um lan?amento novo?
        if (:WORDEMST = -1) then
           begin
              wordem_salva = -1;

              --a primeira coisa ? procurar se j? tem algum lan?amento com os dados na chave/ordem
              wSQL_AUX = 'SELECT first 1 BDORDEMST ' ||
                         'FROM TMP_VEF_EMP_TMOV' || :wmovimento || 'STDAPI_TEMP ' ||
                         'WHERE BDCHAVE = ' || :WCHAVE ||
                         '  and BDORDEM = ' || :WORDEM ||
                         '  and BDTIPOISEOUT = ' || :WTIPOISEOUT ||
       '  and BDSESSAO = ' || :prSessao;

              EXECUTE STATEMENT :WSQL_AUX INTO :WORDEM_SALVA;

              --Se n?o tiver, vamos pegar a pr?xima
              if (coalesce(:wordem_salva,-1) = -1) then
                 begin
                    wSQL_AUX = 'SELECT MAX(BDORDEMST) ' ||
                               'FROM TMP_VEF_EMP_TMOV' || :wmovimento || 'STDAPI_TEMP ' ||
                               'WHERE BDCHAVE = ' || :WCHAVE ||
                               '  and BDORDEM = ' || :WORDEM ||
                               '  and BDTIPOISEOUT = ' || :WTIPOISEOUT ||
             '  and BDSESSAO = ' || :prSessao;

                    EXECUTE STATEMENT :WSQL_AUX INTO :WORDEM_SALVA;

                    WORDEM_SALVA = coalesce(:wordem_salva, 0) + 1;
                 end

              --atualizamos a ordem ent?o
              WORDEMST = :wordem_salva;
           end

        --vamos agora fazer o update ou insert do registro
        wsql_aux = 'UPDATE OR INSERT INTO TMP_VEF_EMP_TMOV' || :wmovimento || 'STDAPI_TEMP ' ||
                   '     (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMST, BDEDITCHAVE, ' ||
                   '      BDTIPOISEOUT, BDCODTIPODAPI, BDVALOR) ' ||
                   'values(' || :PRSESSAO || ', ' || :WCODEMP || ', ' || :WCHAVE || ', ' || :WORDEM || ', ' || :WORDEMST || ', ' || :WEDITCHAVE || ', ' ||
                   '      ' || :WTIPOISEOUT || ', ' || :WCODTIPODAPI || ', ' || :WVALOR || ') ' ||
                   ' MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMST)';

        EXECUTE STATEMENT :WSQL_AUX;
     end
end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_SN (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
declare variable WMOVIMENTO varchar(3);
declare variable WORDEM_SALVA integer;
declare variable WSQL varchar(10000);
declare variable WSQL_AUX varchar(10000);
declare variable WEDITCHAVE integer;
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WCHAVESN integer;
declare variable WCODBASESN integer;
declare variable WCODIMPOSTO integer;
declare variable WVLRBASE numeric(18,2);
declare variable WCODTIPOIMPOSTO integer;
declare variable WCODNAT integer;
declare variable WCODATIVSIMPNAC integer;
declare variable WCODCONFSN integer;
declare variable WCODPLANOCONFSN integer;
declare variable WCODTIPOIMPPIS integer;
declare variable WCODTIPOIMPCOFINS integer;
declare variable WCODTIPOIMPCSLL integer;
declare variable WCODTIPOIMPICMS integer;
declare variable WCODTIPOIMPINSSCPP integer;
declare variable WCODTIPOIMPIRPJ integer;
declare variable WCODTIPOIMPIPI integer;
declare variable WCODTIPOIMPISS integer;
declare variable WORDEM integer;
begin
  if (prmovimento = 0) then
     begin
        :wmovimento = 'ENT';
     end
  else
     begin
        :wmovimento = 'SAI';
     end

  wSQL = 'select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDEDITCHAVE, ATU.BDCHAVESN, '||
         '       sum(ATU.BDVLRBASE) as BDVLRBASE, ATU.BDCODBASESN, ATU.BDCODIMPOSTO, ATU.BDCODTIPOIMPOSTO, ATU.BDCODNAT, ATU.BDCODATIVSIMPNAC, '||
         '       ATU.BDCODCONFSN, ATU.BDCODPLANOCONFSN, ATU.BDCODTIPOIMPPIS, ATU.BDCODTIPOIMPCOFINS, ATU.BDCODTIPOIMPCSLL, ATU.BDCODTIPOIMPICMS, '||
         '       ATU.BDCODTIPOIMPINSSCPP, ATU.BDCODTIPOIMPIRPJ, ATU.BDCODTIPOIMPIPI, ATU.BDCODTIPOIMPISS '||
         'from (select SN.BDCODEMP, SN.BDCHAVE, SN.BDORDEM, SN.BDEDITCHAVE, SN.BDCHAVESN, '||
         '                   SN.BDVLRBASE * CASE when coalesce(IT.BDVLRORIGINAL, 0) = 0 then 1 WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRBASE, '||
         '                   SN.BDCODBASESN, SN.BDCODIMPOSTO, SN.BDCODTIPOIMPOSTO, SN.BDCODNAT, SN.BDCODATIVSIMPNAC, SN.BDCODCONFSN, '||
         '                   SN.BDCODPLANOCONFSN, SN.BDCODTIPOIMPPIS, SN.BDCODTIPOIMPCOFINS, SN.BDCODTIPOIMPCSLL, SN.BDCODTIPOIMPICMS, '||
         '                   SN.BDCODTIPOIMPINSSCPP, SN.BDCODTIPOIMPIRPJ, SN.BDCODTIPOIMPIPI, SN.BDCODTIPOIMPISS '||
         '            from TMP_VEF_EMP_TMOV' || :wmovimento || 'SN_TEMP SN '||
         '            inner join TMP_VEF_EMP_TMOV' || :wmovimento || 'ITENS_TEMP IT on IT.BDSESSAO = SN.BDSESSAO and '||
         '                  IT.BDCODEMP = SN.BDCODEMP and '||
         '                  IT.BDCHAVE = SN.BDCHAVE and '||
         '                  IT.BDORDEM = SN.BDORDEM and '||
         '                  IT.BDSESSAO = SN.BDSESSAO '||
         '            where SN.BDSESSAO = ' || :prSessao || ' and '||
         '                  coalesce(IT.BDROW_EXCLUIDA, 0) <> 1 '||
         '            union all '||
         '            select SN.BDCODEMP, SN.BDCHAVE, PR.BDORDEM_ATU, SN.BDEDITCHAVE, -1, '||
         '                   SN.BDVLRBASE * PR.BDRAZAORATEIO as BDVLRBASE, '||
         '                   SN.BDCODBASESN, SN.BDCODIMPOSTO, SN.BDCODTIPOIMPOSTO, SN.BDCODNAT, SN.BDCODATIVSIMPNAC, SN.BDCODCONFSN, '||
         '                   SN.BDCODPLANOCONFSN, SN.BDCODTIPOIMPPIS, SN.BDCODTIPOIMPCOFINS, SN.BDCODTIPOIMPCSLL, SN.BDCODTIPOIMPICMS, '||
         '                   SN.BDCODTIPOIMPINSSCPP, SN.BDCODTIPOIMPIRPJ, SN.BDCODTIPOIMPIPI, SN.BDCODTIPOIMPISS '||
         '            from TMP_VEF_EMP_TMOV' || :wmovimento || 'SN_TEMP SN '||
         '            inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on SN.BDSESSAO = PR.BDSESSAO and '||
         '                  SN.BDCODEMP = PR.BDCODEMP and '||
         '                  SN.BDCHAVE = PR.BDCHAVE and '||
         '                  SN.BDORDEM = PR.BDORDEM_ORIG '||
         '            where SN.BDSESSAO = ' || :prSessao || ') ATU '||
         'group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDEDITCHAVE, ATU.BDCHAVESN, ATU.BDCODBASESN, ATU.BDCODIMPOSTO, ATU.BDCODTIPOIMPOSTO, ATU.BDCODNAT, ATU.BDCODATIVSIMPNAC, '||
         '       ATU.BDCODCONFSN, ATU.BDCODPLANOCONFSN, ATU.BDCODTIPOIMPPIS, ATU.BDCODTIPOIMPCOFINS, ATU.BDCODTIPOIMPCSLL, ATU.BDCODTIPOIMPICMS, '||
         '       ATU.BDCODTIPOIMPINSSCPP, ATU.BDCODTIPOIMPIRPJ, ATU.BDCODTIPOIMPIPI, ATU.BDCODTIPOIMPISS';

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  for execute statement wsql into
         :WCODEMP, :WCHAVE, :WORDEM, :WEDITCHAVE, :WCHAVESN, :WVLRBASE, :WCODBASESN, :WCODIMPOSTO, :WCODTIPOIMPOSTO, :WCODNAT,
         :WCODATIVSIMPNAC, :WCODCONFSN, :WCODPLANOCONFSN, :WCODTIPOIMPPIS, :WCODTIPOIMPCOFINS, :WCODTIPOIMPCSLL, :WCODTIPOIMPICMS,
       :WCODTIPOIMPINSSCPP, :WCODTIPOIMPIRPJ, :WCODTIPOIMPIPI, :WCODTIPOIMPISS
  do
     begin
        --Se a ordem vier aqui como -1, ent?o ? um lan?amento novo?
        if (:WCHAVESN = -1) then
           begin
              wSQL_AUX = 'SELECT MAX(BDCHAVESN) ' ||
                         'FROM TMP_VEF_EMP_TMOV' || :wmovimento || 'SN_TEMP ' ||
                         'WHERE BDCHAVE = ' || :WCHAVE ||
                         '  and BDORDEM = ' || :WORDEM ||
       '  and BDSESSAO = ' || :prSessao;

              EXECUTE STATEMENT :WSQL_AUX INTO :WORDEM_SALVA;

              WORDEM_SALVA = coalesce(:wordem_salva, 0) + 1;

              --atualizamos a ordem ent?o
              WCHAVESN = :wordem_salva;
           end

        --vamos agora fazer o update ou insert do registro
        wsql_aux = 'UPDATE OR INSERT INTO TMP_VEF_EMP_TMOV' || :wmovimento || 'SN_TEMP ' ||
                   '     (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDCHAVESN, BDEDITCHAVE, BDCODBASESN, BDCODIMPOSTO, ' ||
                   '      BDVLRBASE, BDCODTIPOIMPOSTO, BDCODNAT, BDCODATIVSIMPNAC, BDCODCONFSN, BDCODPLANOCONFSN, ' ||
                   '      BDCODTIPOIMPPIS, BDCODTIPOIMPCOFINS, BDCODTIPOIMPCSLL, BDCODTIPOIMPICMS, BDCODTIPOIMPINSSCPP, ' ||
                   '      BDCODTIPOIMPIRPJ, BDCODTIPOIMPIPI, BDCODTIPOIMPISS) ' ||
                   'values(' || :PRSESSAO || ', ' || :WCODEMP || ', ' || :WCHAVE || ', ' || :WORDEM || ', ' || :WCHAVESN || ', ' || :WEDITCHAVE || ', ' ||
                   '      ' || :WCODBASESN || ', ' || coalesce(:WCODIMPOSTO, 'NULL') || ', ' || :WVLRBASE || ', ' || coalesce(:WCODTIPOIMPOSTO, 'NULL') || ', ' || :WCODNAT || ', ' ||
                   '      ' || :WCODATIVSIMPNAC || ', ' || :WCODCONFSN || ', ' || :WCODPLANOCONFSN || ', ' || :WCODTIPOIMPPIS || ', ' || :WCODTIPOIMPCOFINS || ', ' ||
                   '      ' || :WCODTIPOIMPCSLL || ', ' || :WCODTIPOIMPICMS || ', ' || :WCODTIPOIMPINSSCPP || ', ' || :WCODTIPOIMPIRPJ || ', ' ||
                   '      ' || :WCODTIPOIMPIPI || ', ' || :WCODTIPOIMPISS || ') ' ||
                   ' MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDCHAVESN)';

        EXECUTE STATEMENT :WSQL_AUX;
     end
end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_Q48 (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
declare variable WMOVIMENTO varchar(3);
declare variable WSQL_AUX varchar(10000);
declare variable WSQL varchar(10000);
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WEDITCHAVE integer;
declare variable WCODCID integer;
declare variable WORIGEM integer;
declare variable WVLRSAIDA numeric(15,2);
declare variable WVLRSAIDA_AUX numeric(15,2);
declare variable WVLRESTORNOS numeric(15,2);
declare variable WVLRESTORNOS_AUX numeric(15,2);
declare variable WVLRREMESSA numeric(15,2);
declare variable WVLRREMESSA_AUX numeric(15,2);
declare variable WVLRRETORNO numeric(15,2);
declare variable WVLRRETORNO_AUX numeric(15,2);
declare variable WVLRANULACOES numeric(15,2);
declare variable WVLRANULACOES_AUX numeric(15,2);
declare variable WVLRCANCELAMENTOS numeric(15,2);
declare variable WVLRCANCELAMENTOS_AUX numeric(15,2);
declare variable WVLRDEVOLUCOES numeric(15,2);
declare variable WVLRDEVOLUCOES_AUX numeric(15,2);
declare variable WVLRREGDUPLICI numeric(15,2);
declare variable WVLRREGDUPLICI_AUX numeric(15,2);
declare variable WVLROUTRENTRADAS numeric(15,2);
declare variable WVLROUTRENTRADAS_AUX numeric(15,2);
declare variable WVLRTOTALLIQUIDO numeric(15,2);
declare variable WVLRTOTALLIQUIDO_AUX numeric(15,2);
begin
  /* Esta aqui ? um SP de rateio, s?o de tabelas espec?ficas e ent?o o que uma faz as outras copiam, apenas mudando a tabela e os campos */

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  if (prmovimento = 0) then
     begin
        :wmovimento = 'ENT';
     end
  else
     begin
        :wmovimento = 'SAI';
     end

  wSQL = 'select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDEDITCHAVE, ATU.BDCODCID, ATU.BDORIGEM, ' ||
         '       sum(ATU.BDVLRSAIDA) as BDVLRSAIDA, sum(ATU.BDVLRESTORNOS) as BDVLRESTORNOS, sum(ATU.BDVLRREMESSA) as BDVLRREMESSA, ' ||
         '       sum(ATU.BDVLRRETORNO) as BDVLRRETORNO, sum(ATU.BDVLRANULACOES) as BDVLRANULACOES, sum(ATU.BDVLRCANCELAMENTOS) as BDVLRCANCELAMENTOS, ' ||
         '       sum(ATU.BDVLRDEVOLUCOES) as BDVLRDEVOLUCOES, sum(ATU.BDVLRREGDUPLICI) as BDVLRREGDUPLICI, sum(ATU.BDVLROUTRENTRADAS) as BDVLROUTRENTRADAS, ' ||
         '       sum(ATU.BDVLRTOTALLIQUIDO) as BDVLRTOTALLIQUIDO ' ||
         '      from (select Q48.BDCODEMP, Q48.BDCHAVE, Q48.BDORDEM, Q48.BDEDITCHAVE, Q48.BDCODCID, ' ||
         '                   Q48.BDVLRSAIDA * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRSAIDA, ' ||
         '                   Q48.BDVLRESTORNOS * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRESTORNOS, ' ||
         '                   Q48.BDVLRREMESSA * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRREMESSA, ' ||
         '                   Q48.BDVLRRETORNO * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRRETORNO, ' ||
         '                   Q48.BDVLRANULACOES * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRANULACOES, ' ||
         '                   Q48.BDVLRCANCELAMENTOS * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRCANCELAMENTOS, ' ||
         '                   Q48.BDVLRDEVOLUCOES * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRDEVOLUCOES, ' ||
         '                   Q48.BDVLRREGDUPLICI * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRREGDUPLICI, ' ||
         '                   Q48.BDVLROUTRENTRADAS * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLROUTRENTRADAS, ' ||
         '                   Q48.BDVLRTOTALLIQUIDO * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRTOTALLIQUIDO, ' ||
         '                   1 AS BDORIGEM ' ||
         '            from TMP_VEF_EMP_TMOV' || :wmovimento || 'Q48_TEMP Q48 ' ||
         '            inner join TMP_VEF_EMP_TMOVENTITENS_TEMP IT on IT.BDSESSAO = Q48.BDSESSAO and ' ||
         '                  IT.BDCODEMP = Q48.BDCODEMP and ' ||
         '                  IT.BDCHAVE = Q48.BDCHAVE and ' ||
         '                  IT.BDORDEM = Q48.BDORDEM and ' ||
         '                  IT.BDSESSAO = Q48.BDSESSAO ' ||
         '            where Q48.BDSESSAO = ' || :prSessao || ' and ' ||
         '                  coalesce(IT.BDROW_EXCLUIDA, 0) <> 1 ' ||
         '            union all ' ||
         '            select Q48.BDCODEMP, Q48.BDCHAVE, PR.BDORDEM_ATU, Q48.BDEDITCHAVE, Q48.BDCODCID, ' ||
         '                   Q48.BDVLRSAIDA * PR.BDRAZAORATEIO as BDVLRSAIDA, ' ||
         '                   Q48.BDVLRESTORNOS * PR.BDRAZAORATEIO as BDVLRESTORNOS, ' ||
         '                   Q48.BDVLRREMESSA * PR.BDRAZAORATEIO as BDVLRREMESSA, ' ||
         '                   Q48.BDVLRRETORNO * PR.BDRAZAORATEIO as BDVLRRETORNO, ' ||
         '                   Q48.BDVLRANULACOES * PR.BDRAZAORATEIO as BDVLRANULACOES, ' ||
         '                   Q48.BDVLRCANCELAMENTOS * PR.BDRAZAORATEIO as BDVLRCANCELAMENTOS, ' ||
         '                   Q48.BDVLRDEVOLUCOES * PR.BDRAZAORATEIO as BDVLRDEVOLUCOES, ' ||
         '                   Q48.BDVLRREGDUPLICI * PR.BDRAZAORATEIO as BDVLRREGDUPLICI, ' ||
         '                   Q48.BDVLROUTRENTRADAS * PR.BDRAZAORATEIO as BDVLROUTRENTRADAS, ' ||
         '                   Q48.BDVLRTOTALLIQUIDO * PR.BDRAZAORATEIO as BDVLRTOTALLIQUIDO, ' ||
         '                   2 AS BDORIGEM ' ||
         '            from TMP_VEF_EMP_TMOV' || :wmovimento || 'Q48_TEMP Q48 ' ||
         '            inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on Q48.BDSESSAO = PR.BDSESSAO and ' ||
         '                  Q48.BDCODEMP = PR.BDCODEMP and ' ||
         '                  Q48.BDCHAVE = PR.BDCHAVE and ' ||
         '                  Q48.BDORDEM = PR.BDORDEM_ORIG ' ||
         '            where Q48.BDSESSAO = ' || :prSessao || ') ATU ' ||
         '      group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDEDITCHAVE, ATU.BDCODCID, ATU.BDORIGEM';


  for execute statement :wsql into
        :WCODEMP, :WCHAVE, :WORDEM, :WEDITCHAVE, :WCODCID, :WORIGEM,
        :WVLRSAIDA, :WVLRESTORNOS, :WVLRREMESSA, :WVLRRETORNO, :WVLRANULACOES,
        :WVLRCANCELAMENTOS, :WVLRDEVOLUCOES, :WVLRREGDUPLICI, :WVLROUTRENTRADAS,
        :WVLRTOTALLIQUIDO
  do
  begin
     --Vamos ver se j? n?o existe e fazer a soma neste caso aqui
     if (:WORIGEM = 2) then
     begin
        wSQL_AUX = 'select first 1 coalesce(BDVLRSAIDA, 0) AS BDVLRSAIDA, coalesce(BDVLRESTORNOS, 0) AS BDVLRESTORNOS, '||
                   '        coalesce(BDVLRREMESSA, 0) AS BDVLRREMESSA, coalesce(BDVLRRETORNO, 0) AS BDVLRRETORNO, '||
                   '        coalesce(BDVLRANULACOES, 0) AS BDVLRANULACOES, coalesce(BDVLRCANCELAMENTOS, 0) AS BDVLRCANCELAMENTOS, '||
                   '        coalesce(BDVLRDEVOLUCOES, 0) AS BDVLRDEVOLUCOES, coalesce(BDVLRREGDUPLICI, 0) AS BDVLRREGDUPLICI, '||
                   '        coalesce(BDVLROUTRENTRADAS, 0) AS BDVLROUTRENTRADAS, coalesce(BDVLRTOTALLIQUIDO, 0) AS BDVLRTOTALLIQUIDO '||
                   ' from TMP_VEF_EMP_TMOV' || :wmovimento || 'Q48_TEMP '||
                   ' where BDCHAVE = ' || :WCHAVE ||
                   '   and BDORDEM = ' || :WORDEM ||
                   '   and BDCODCID = ' || :WCODCID ||
                   '   and BDSESSAO = ' || :PRSESSAO;

       EXECUTE STATEMENT :WSQL_AUX
       into :WVLRSAIDA_AUX, :WVLRESTORNOS_AUX, :WVLRREMESSA_AUX, :WVLRRETORNO_AUX, :WVLRANULACOES_AUX,
            :WVLRCANCELAMENTOS_AUX, :WVLRDEVOLUCOES_AUX, :WVLRREGDUPLICI_AUX, :WVLROUTRENTRADAS_AUX, :WVLRTOTALLIQUIDO_AUX;

       WVLRSAIDA = coalesce(:WVLRSAIDA, 0) + coalesce(:WVLRSAIDA_AUX, 0);
       WVLRESTORNOS  = coalesce(:WVLRESTORNOS, 0) + coalesce(:WVLRESTORNOS_AUX, 0);
       WVLRREMESSA = coalesce(:WVLRREMESSA, 0) + coalesce(:WVLRREMESSA_AUX, 0);
       WVLRRETORNO = coalesce(:WVLRRETORNO, 0) + coalesce(:WVLRRETORNO_AUX, 0);
       WVLRANULACOES = coalesce(:WVLRANULACOES, 0) + coalesce(:WVLRANULACOES_AUX, 0);
       WVLRCANCELAMENTOS = coalesce(:WVLRCANCELAMENTOS, 0) + coalesce(:WVLRCANCELAMENTOS_AUX, 0);
       WVLRDEVOLUCOES = coalesce(:WVLRDEVOLUCOES, 0) + coalesce(:WVLRDEVOLUCOES_AUX, 0);
       WVLRREGDUPLICI = coalesce(:WVLRREGDUPLICI, 0) + coalesce(:WVLRREGDUPLICI_AUX, 0);
       WVLROUTRENTRADAS = coalesce(:WVLROUTRENTRADAS, 0) + coalesce(:WVLROUTRENTRADAS_AUX, 0);
       WVLRTOTALLIQUIDO = coalesce(:WVLRTOTALLIQUIDO, 0) + coalesce(:WVLRTOTALLIQUIDO_AUX, 0);
     end

     --vamos agora fazer o update ou insert do registro
     wSQL_AUX = 'UPDATE OR INSERT INTO TMP_VEF_EMP_TMOV' || :wmovimento || 'Q48_TEMP ' ||
                '   (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDEDITCHAVE, BDCODCID, BDVLRSAIDA, BDVLRESTORNOS, BDVLRREMESSA, BDVLRRETORNO, ' ||
                '    BDVLRANULACOES, BDVLRCANCELAMENTOS, BDVLRDEVOLUCOES, BDVLRREGDUPLICI, BDVLROUTRENTRADAS, BDVLRTOTALLIQUIDO) ' ||
                'values ' ||
                '   (' || :prSESSAO || ', ' || :WCODEMP || ', ' || :WCHAVE || ', ' || :WORDEM || ', ' || :WEDITCHAVE || ', ' || :WCODCID || ', ' || :WVLRSAIDA || ', ' || :WVLRESTORNOS || ', ' || :WVLRREMESSA || ', ' || :WVLRRETORNO || ', ' || 
                          :WVLRANULACOES || ', ' || :WVLRCANCELAMENTOS || ', ' || :WVLRDEVOLUCOES || ', ' || :WVLRREGDUPLICI || ', ' || :WVLROUTRENTRADAS || ', ' || :WVLRTOTALLIQUIDO || ') ' ||
                'MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM)';

     EXECUTE STATEMENT :WSQL_AUX;
  end
end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_PR (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
declare variable WMOVIMENTO varchar(3);
declare variable WSQL varchar(10000);
begin
  if (prmovimento = 0) then
     begin
        :wmovimento = 'ENT';
     end
  else
     begin
        :wmovimento = 'SAI';
     end

  wSQL = 'merge into TMP_VEF_EMP_TMOV' || :wmovimento || 'PR_TEMP PAI ' ||
         'using (select DIF.BDSESSAO, DIF.BDCODEMP, DIF.BDCHAVE, PR.BDORDEM_ATU, ' ||
         '             max(DIF.BDCODIMOVRUR) as BDCODIMOVRUR, DIF.BDEDITCHAVE, ' ||
         '             DIF.BDTIPMOV, DIF.BDCTACOR, DIF.BDCODTER, DIF.BDTIPDOC, DIF.BDTIPLAN ' ||
         '      from TMP_VEF_EMP_TMOV' || :wmovimento || 'PR_TEMP DIF ' ||
         '      inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on DIF.BDSESSAO = PR.BDSESSAO and ' ||
         '            DIF.BDCODEMP = PR.BDCODEMP and ' ||
         '            DIF.BDCHAVE = PR.BDCHAVE and ' ||
         '            DIF.BDORDEM = PR.BDORDEM_ORIG ' ||
         '      where DIF.BDSESSAO = ' || :prsessao || ' ' ||
         '      group by DIF.BDSESSAO, DIF.BDCODEMP, DIF.BDCHAVE, PR.BDORDEM_ATU, DIF.BDEDITCHAVE, ' ||
         '               DIF.BDTIPMOV, DIF.BDCTACOR, DIF.BDCODTER, DIF.BDTIPDOC, DIF.BDTIPLAN) FILHO ' ||
         'on PAI.BDSESSAO = FILHO.BDSESSAO and ' ||
         '   PAI.BDCHAVE = FILHO.BDCHAVE and ' ||
         '   PAI.BDCODEMP = FILHO.BDCODEMP and ' ||
         '   PAI.BDORDEM = FILHO.BDORDEM_ATU ' ||
         'when not matched then ' ||
         '    insert (BDSESSAO, BDEDITCHAVE, BDCODEMP, BDCHAVE, BDORDEM, BDCODIMOVRUR, BDTIPMOV, BDCTACOR, BDCODTER, BDTIPDOC, BDTIPLAN) ' ||
         '    values (FILHO.BDSESSAO, FILHO.BDEDITCHAVE, FILHO.BDCODEMP, FILHO.BDCHAVE, FILHO.BDORDEM_ATU, ' ||
         '            FILHO.BDCODIMOVRUR, FILHO.BDTIPMOV, FILHO.BDCTACOR, FILHO.BDCODTER, FILHO.BDTIPDOC, FILHO.BDTIPLAN)';

   execute statement :wsql;
end^

create or alter procedure SP_FISCAL_RATEIA_OCOSP (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
declare variable WSQL varchar(10000);
declare variable WMOVIMENTO varchar(3);
begin
  if (prmovimento = 0) then
     begin
        :wmovimento = 'ENT';
     end
  else
     begin
        :wmovimento = 'SAI';
     end

  wSQL = 'merge into TMP_VEF_EMP_TMOV' || :wmovimento || 'OCOSP_TEMP PAI ' ||
         'using (select DIF.BDSESSAO, DIF.BDCODEMP, DIF.BDCHAVE, PR.BDORDEM_ATU, ' ||
         '             max(DIF.BDCODLISOCOGIASP) as BDCODLISOCOGIASP, DIF.BDEDITCHAVE ' ||
         '      from TMP_VEF_EMP_TMOV' || :wmovimento || 'OCOSP_TEMP DIF ' ||
         '      inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on DIF.BDSESSAO = PR.BDSESSAO and ' ||
         '            DIF.BDCODEMP = PR.BDCODEMP and ' ||
         '            DIF.BDCHAVE = PR.BDCHAVE and ' ||
         '            DIF.BDORDEM = PR.BDORDEM_ORIG ' ||
         '      where DIF.BDSESSAO = ' || :prsessao || ' ' ||
         '      group by DIF.BDSESSAO, DIF.BDCODEMP, DIF.BDCHAVE, PR.BDORDEM_ATU, DIF.BDEDITCHAVE) FILHO ' ||
         'on PAI.BDSESSAO = FILHO.BDSESSAO and ' ||
         '   PAI.BDCHAVE = FILHO.BDCHAVE and ' ||
         '   PAI.BDCODEMP = FILHO.BDCODEMP and ' ||
         '   PAI.BDORDEM = FILHO.BDORDEM_ATU ' ||
         'when not matched then ' ||
         '    insert (BDSESSAO, BDEDITCHAVE, BDCODEMP, BDCHAVE, BDORDEM, BDCODLISOCOGIASP) ' ||
         '    values (FILHO.BDSESSAO, FILHO.BDEDITCHAVE, FILHO.BDCODEMP, FILHO.BDCHAVE, FILHO.BDORDEM_ATU, ' ||
         '            FILHO.BDCODLISOCOGIASP)';

   execute statement :wsql;
end^

create or alter procedure SP_FISCAL_RATEIA_IMPRETSP (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
declare variable WCODEMP integer;
declare variable WMOVIMENTO varchar(3);
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WEDITCHAVE integer;
declare variable WORIGEM integer;
declare variable WSUBSTITUTO numeric(18,2);
declare variable WSUBSTITUIDO numeric(18,2);
declare variable WBASE_AUX numeric(18,2);
declare variable WVALOR_AUX numeric(18,2);
declare variable WSQL varchar(10000);
declare variable WSQL_AUX varchar(10000);
begin
  /* Esta aqui ? um SP de rateio, s?o de tabelas espec?ficas e ent?o o que uma faz as outras copiam, apenas mudando a tabela e os campos */
  if (prmovimento = 0) then
     begin
        :wmovimento = 'ENT';
     end
  else
     begin
        :wmovimento = 'SAI';
     end

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  WSQL = 'select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDEDITCHAVE, sum(ATU.BDIMPSUBSTITUTO) as BDIMPSUBSTITUTO, sum(ATU.BDIMPSUBSTITUIDO) as BDIMPSUBSTITUIDO, ATU.BDORIGEM ' ||
         'from (select IMPRET.BDCODEMP, IMPRET.BDCHAVE, IMPRET.BDORDEM, IMPRET.BDEDITCHAVE, ' ||
         '          coalesce(IMPRET.BDIMPSUBSTITUTO, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDIMPSUBSTITUTO, ' ||
         '          coalesce(IMPRET.BDIMPSUBSTITUIDO, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDIMPSUBSTITUIDO, 1 AS BDORIGEM ' ||
         '   from TMP_VEF_EMP_TMOVENTIMPRETSP_TEMP IMPRET ' ||
         '   inner join TMP_VEF_EMP_TMOV' || :wmovimento || 'ITENS_TEMP IT on IT.BDSESSAO = IMPRET.BDSESSAO and ' ||
         '         IT.BDCODEMP = IMPRET.BDCODEMP and ' ||
         '         IT.BDCHAVE = IMPRET.BDCHAVE and ' ||
         '         IT.BDORDEM = IMPRET.BDORDEM and ' ||
         '         IT.BDSESSAO = IMPRET.BDSESSAO ' ||
         '   where IMPRET.BDSESSAO = ' || :prSessao || ' and ' ||
         '         coalesce(IT.BDROW_EXCLUIDA, 0) <> 1 ' ||
         '   union all ' ||
         '   select IMPRET.BDCODEMP, IMPRET.BDCHAVE, PR.BDORDEM_ATU, IMPRET.BDEDITCHAVE, ' ||
         '          coalesce(IMPRET.BDIMPSUBSTITUTO, 0) * PR.BDRAZAORATEIO as BDIMPSUBSTITUTO, ' ||
         '          coalesce(IMPRET.BDIMPSUBSTITUIDO, 0) * PR.BDRAZAORATEIO as BDIMPSUBSTITUIDO, 2 AS BDORIGEM ' ||
         '   from TMP_VEF_EMP_TMOV' || :wmovimento || 'IMPRETSP_TEMP IMPRET ' ||
         '   inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on IMPRET.BDSESSAO = PR.BDSESSAO and ' ||
         '         IMPRET.BDCODEMP = PR.BDCODEMP and ' ||
         '         IMPRET.BDCHAVE = PR.BDCHAVE and ' ||
         '         IMPRET.BDORDEM = PR.BDORDEM_ORIG ' ||
         '   where IMPRET.BDSESSAO = ' || :prSessao || ') ATU ' ||
         'group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDEDITCHAVE, ATU.BDORIGEM';


  for execute statement wsql into :WCODEMP, :WCHAVE, :WORDEM, :WEDITCHAVE, :WSUBSTITUTO, :WSUBSTITUIDO, :WORIGEM do
     begin
        --Vamos ver se j? n?o existe e fazer a soma neste caso aqui
        if (:WORIGEM = 2) then
           begin
              wsql_Aux = 'select first 1 coalesce(BDIMPSUBSTITUTO, 0) AS BDIMPSUBSTITUTO, coalesce(BDIMPSUBSTITUIDO, 0) AS BDIMPSUBSTITUIDO ' ||
                         'from TMP_VEF_EMP_TMOV' || :wmovimento || 'IMPRETSP_TEMP ' ||
                         'where BDCHAVE = ' || :WCHAVE || ' and ' ||
                         '      BDORDEM = ' || :WORDEM || ' and ' ||
       '      BDSESSAO = ' || :prSessao;

              execute statement wsql_Aux into :WBASE_AUX, :WVALOR_AUX;

              WSUBSTITUTO  = coalesce(:WSUBSTITUTO, 0) + coalesce(:WBASE_AUX, 0);
              WSUBSTITUIDO = coalesce(:WSUBSTITUIDO, 0) + coalesce(:WVALOR_AUX, 0);
           end

        --vamos agora fazer o update ou insert do registro
        wsql_Aux = 'UPDATE OR INSERT INTO TMP_VEF_EMP_TMOVENTIMPRETSP_TEMP ' ||
                   '    (BDSESSAO, BDEDITCHAVE, BDCODEMP, BDCHAVE, BDORDEM, BDIMPSUBSTITUTO, BDIMPSUBSTITUIDO)' ||
                   '    values(' || :PRSESSAO || ', ' || :WEDITCHAVE || ', ' || :WCODEMP || ', ' || :WCHAVE || ', ' ||
                                    :WORDEM || ', ' || :WSUBSTITUTO || ', ' || :WSUBSTITUIDO || ')' ||
                   'MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM)';

        execute statement wsql_Aux;
     end

end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_MOVCC (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WORDEMCC integer;
declare variable WEDITCHAVE integer;
declare variable WVALOR numeric(18,2);
declare variable WPERCENTUAL numeric(18,6);
declare variable WCODCENTRO integer;
declare variable WCODTPCC integer;
declare variable WVLRIMP numeric(18,2);
declare variable WDEBCRED integer;
declare variable WORDEM_SALVA integer;
declare variable WMOVIMENTO varchar(3);
declare variable WSQL varchar(20000);
declare variable WSQL_AUX varchar(20000);
declare variable WVALOR_ORIG numeric(15,2);
declare variable WVLRCONTAB numeric(15,2);
begin
    /* Esta aqui ? um SP de rateio, s?o de tabelas espec?ficas e ent?o o que uma faz as outras copiam, apenas mudando a tabela e os campos */
  if (prmovimento = 0) then
     begin
        :wmovimento = 'ENT';
     end
  else
     begin
        :wmovimento = 'SAI';
     end

  wSQL = 'select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMCC, ATU.BDEDITCHAVE, ' ||
         '       sum(ATU.BDVALOR) as BDVALOR, ATU.BDPERCENTUAL, ATU.BDCODCENTRO, ' ||
         '       sum(ATU.BDVLRIMP) as BDVLRIMP, ATU.BDCODTPCC, ATU.BDDEBCRED, ATU.BDVLRCONTAB ' ||
         'from (select CC.BDCODEMP, CC.BDCHAVE, CC.BDORDEM, CC.BDORDEMCC, CC.BDEDITCHAVE, ' ||
         '             CC.BDVALOR * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVALOR, CC.BDPERCENTUAL, ' ||
         '             CC.BDCODCENTRO, Coalesce(CC.BDVLRIMP, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRIMP, ' ||
         '             CC.BDCODTPCC, CC.BDDEBCRED, IT.BDVLRCONTAB ' ||
         '      from TMP_VEF_EMP_TMOVCC' || :wmovimento || '_TEMP CC ' ||
         '      inner join TMP_VEF_EMP_TMOV' || :wmovimento || 'ITENS_TEMP IT on IT.BDSESSAO = CC.BDSESSAO and ' ||
         '            IT.BDCODEMP = CC.BDCODEMP and ' ||
         '            IT.BDCHAVE = CC.BDCHAVE and ' ||
         '            IT.BDORDEM = CC.BDORDEM and ' ||
         '            IT.BDSESSAO = CC.BDSESSAO ' ||
         '        where CC.BDSESSAO = ' || :prSessao || ' and ' ||
         '            coalesce(IT.BDROW_EXCLUIDA, 0) <> 1 ' ||
         '      union all ' ||
         '      select CC.BDCODEMP, CC.BDCHAVE, PR.BDORDEM_ATU, -1 as BDORDEMCC, CC.BDEDITCHAVE, ' ||
         '             CC.BDVALOR * PR.BDRAZAORATEIO as BDVALOR, CC.BDPERCENTUAL, CC.BDCODCENTRO, ' ||
         '             Coalesce(CC.BDVLRIMP, 0) * PR.BDRAZAORATEIO as BDVLRIMP, CC.BDCODTPCC, CC.BDDEBCRED, IT.BDVLRCONTAB ' ||
         '      from TMP_VEF_EMP_TMOVCC' || :wmovimento || '_TEMP CC ' ||
         '      inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on CC.BDSESSAO = PR.BDSESSAO and ' ||
         '            CC.BDCODEMP = PR.BDCODEMP and ' ||
         '            CC.BDCHAVE = PR.BDCHAVE and ' ||
         '            CC.BDORDEM = PR.BDORDEM_ORIG ' ||
         '         inner join TMP_VEF_EMP_TMOVENTITENS_TEMP IT on IT.BDSESSAO = PR.BDSESSAO and ' ||
         '            IT.BDCODEMP = PR.BDCODEMP and ' ||
         '            IT.BDCHAVE = PR.BDCHAVE and ' ||
         '            IT.BDORDEM = PR.BDORDEM_ATU and ' ||
         '            IT.BDSESSAO = PR.BDSESSAO ' ||
         '        where CC.BDSESSAO = ' || :prSessao || ') ATU ' ||
         'group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMCC, ATU.BDEDITCHAVE, ATU.BDPERCENTUAL, ' ||
         '         ATU.BDCODCENTRO, ATU.BDCODTPCC, ATU.BDDEBCRED, ATU.BDVLRCONTAB ' ||
         'order by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMCC DESC';

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  for execute statement wsql into
         :WCODEMP,
         :WCHAVE,
         :WORDEM,
         :WORDEMCC,
         :WEDITCHAVE,
         :WVALOR,
         :WPERCENTUAL,
         :WCODCENTRO,
         :WVLRIMP,
         :WCODTPCC,
         :WDEBCRED,
         :WVLRCONTAB
  do
     begin
        WVALOR_ORIG = 0;

        --Se a ordem vier aqui como -1, ent?o ? um lan?amento novo?
        if (:WORDEMCC = -1) then
           begin
              wordem_salva = -1;

              --a primeira coisa ? procurar se j? tem algum lan?amento com os dados na chave/ordem
              wSQL_AUX = 'SELECT first 1 BDORDEMCC, BDVALOR ' ||
                         'FROM TMP_VEF_EMP_TMOVCC' || :wmovimento || '_TEMP ' ||
                         'WHERE BDCHAVE = ' || :WCHAVE ||
                         '  and BDORDEM = ' || :WORDEM ||
                         '  and BDCODCENTRO = ' || :WCODCENTRO ||
                         '  and BDCODTPCC = ' || :WCODTPCC ||
                         '  and BDSESSAO = ' || :prSessao;

              EXECUTE STATEMENT :WSQL_AUX INTO :WORDEM_SALVA, :WVALOR_ORIG;

              --Se n?o tiver, vamos pegar a pr?xima
              if (coalesce(:wordem_salva,-1) = -1) then
                 begin
                    WVALOR_ORIG = 0;

                    wSQL_AUX = 'SELECT MAX(BDORDEMCC) ' ||
                               'FROM TMP_VEF_EMP_TMOVCC' || :wmovimento || '_TEMP ' ||
                               'WHERE BDCHAVE = ' || :WCHAVE ||
                               '  and BDORDEM = ' || :WORDEM ||
                               '  and BDSESSAO = ' || :prSessao;

                    EXECUTE STATEMENT :WSQL_AUX INTO :WORDEM_SALVA;

                    WORDEM_SALVA = coalesce(:wordem_salva, 0) + 1;
                 end

              --atualizamos a ordem ent?o
              WORDEMCC = :wordem_salva;
           end

        WVALOR = :WVALOR + coalesce(:WVALOR_ORIG,0);

        --Precisamos ajustar o percentual
        wpercentual = CAST(:WVALOR / :WVLRCONTAB * 100 AS NUMERIC(18, 6));

        --Ajustar para chegar nos 100%
        wSQL_AUX = 'SELECT  Coalesce(SUM(BDPERCENTUAL),0) ' ||
                   'FROM  TMP_VEF_EMP_TMOVCC' || :wmovimento || '_TEMP ' ||
                   'WHERE BDCHAVE = ' || :WCHAVE ||
                   '  and BDORDEM = ' || :WORDEM ||
                   '  and BDSESSAO = ' || :prSessao ||
                   '  and BDORDEMCC <> ' || :WORDEMCC;

        --Agora temos o percentual atual... e somaremos a diferença
        EXECUTE STATEMENT :WSQL_AUX INTO :WVALOR_ORIG;

        if ((100 - (:WVALOR_ORIG + :wpercentual)) BETWEEN -2 AND 2) then
           wpercentual = :wpercentual + (100 - (:WVALOR_ORIG + :wpercentual));

        --vamos agora fazer o update ou insert do registro
        wsql_aux = 'UPDATE OR INSERT INTO TMP_VEF_EMP_TMOVCC' || :wmovimento || '_TEMP ' ||
                   '     (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMCC, BDEDITCHAVE, ' ||
                   '      BDVALOR, BDPERCENTUAL, BDCODCENTRO, BDCODTPCC, BDVLRIMP, BDDEBCRED) ' ||
                   'values(' || :PRSESSAO || ', ' || :WCODEMP || ', ' || :WCHAVE || ', ' || :WORDEM || ', ' || :WORDEMCC || ', ' || :WEDITCHAVE || ', ' ||
                   '      ' || :WVALOR || ', ' || :WPERCENTUAL || ', ' || :WCODCENTRO || ', ' || :WCODTPCC || ', ' || :WVLRIMP || ', ' || :WDEBCRED || ') ' ||
                   ' MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMCC)';

        EXECUTE STATEMENT :WSQL_AUX;
     end
end^

CREATE OR ALTER procedure SP_FISCAL_RATEIA_CFOP_MOVRAT (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WORDEMRAT integer;
declare variable WEDITCHAVE integer;
declare variable WVALOR numeric(18,2);
declare variable WCODPLANOONLINE integer;
declare variable WCHAVEONLINE integer;
declare variable WCRED integer;
declare variable WDEB integer;
declare variable WORDEM_SALVA integer;
declare variable WMOVIMENTO varchar(3);
declare variable WSQL varchar(20000);
declare variable WSQL_AUX varchar(20000);
declare variable WHIST integer;
declare variable WCOMP integer;
declare variable WCODNAT integer;
declare variable WCONDPGTO integer;
begin
    /* Esta aqui ? um SP de rateio, s?o de tabelas espec?ficas e ent?o o que uma faz as outras copiam, apenas mudando a tabela e os campos */
  if (prmovimento = 0) then
     begin
        :wmovimento = 'ENT';
     end
  else
     begin
        :wmovimento = 'SAI';
     end

  wSQL = 'select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMRAT, ATU.BDEDITCHAVE, ' ||
         '       sum(ATU.BDVALOR) as BDVALOR, ATU.BDCODPLANOONLINE, ATU.BDCHAVEONLINE, ' ||
         '       ATU.BDCRED, ATU.BDDEB, ATU.BDHIST, ATU.BDCOMP, ATU.BDCODNAT, ATU.BDCONDPGTO ' ||
         'from (select CC.BDCODEMP, CC.BDCHAVE, CC.BDORDEM, CC.BDORDEMRAT, CC.BDEDITCHAVE, ' ||
         '             CC.BDVALOR * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVALOR, CC.BDCODPLANOONLINE, ' ||
         '             CC.BDCHAVEONLINE, CC.BDCRED, CC.BDDEB, CC.BDHIST, CC.BDCOMP, CC.BDCODNAT, CC.BDCONDPGTO ' ||
         '      from TMP_VEF_EMP_TMOVRAT' || :wmovimento || '_TEMP CC ' ||
         '      inner join TMP_VEF_EMP_TMOV' || :wmovimento || 'ITENS_TEMP IT on IT.BDSESSAO = CC.BDSESSAO and ' ||
         '            IT.BDCODEMP = CC.BDCODEMP and ' ||
         '            IT.BDCHAVE = CC.BDCHAVE and ' ||
         '            IT.BDORDEM = CC.BDORDEM and ' ||
         '            IT.BDSESSAO = CC.BDSESSAO ' ||
         '        where CC.BDSESSAO = ' || :prSessao || ' and ' ||
         '            coalesce(IT.BDROW_EXCLUIDA, 0) <> 1 ' ||
         '      union all ' ||
         '      select CC.BDCODEMP, CC.BDCHAVE, PR.BDORDEM_ATU, -1 as BDORDEMRAT, CC.BDEDITCHAVE, ' ||
         '             CC.BDVALOR * PR.BDRAZAORATEIO as BDVALOR, CC.BDCODPLANOONLINE, CC.BDCHAVEONLINE, ' ||
         '            CC.BDCRED, CC.BDDEB, CC.BDHIST, CC.BDCOMP, CC.BDCODNAT, CC.BDCONDPGTO ' ||
         '      from TMP_VEF_EMP_TMOVRAT' || :wmovimento || '_TEMP CC ' ||
         '      inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on CC.BDSESSAO = PR.BDSESSAO and ' ||
         '            CC.BDCODEMP = PR.BDCODEMP and ' ||
         '            CC.BDCHAVE = PR.BDCHAVE and ' ||
         '            CC.BDORDEM = PR.BDORDEM_ORIG ' ||
         '        where CC.BDSESSAO = ' || :prSessao || ') ATU ' ||
         'group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMRAT, ATU.BDEDITCHAVE, ATU.BDCODPLANOONLINE, ' ||
         '         ATU.BDCHAVEONLINE, ATU.BDCRED, ATU.BDDEB, ATU.BDHIST, ATU.BDCOMP, ATU.BDCODNAT, ATU.BDCONDPGTO';

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  for execute statement wsql into
         :WCODEMP,
         :WCHAVE,
         :WORDEM,
         :WORDEMRAT,
         :WEDITCHAVE,
         :WVALOR,
         :WCODPLANOONLINE,
         :WCHAVEONLINE,
         :WCRED,
         :WDEB,
         :WHIST,
         :WCOMP,
         :WCODNAT,
         :WCONDPGTO
  do
     begin
        --Se a ordem vier aqui como -1, ent?o ? um lan?amento novo?
        if (:WORDEMRAT = -1) then
           begin
              wordem_salva = -1;

              --a primeira coisa ? procurar se j? tem algum lan?amento com os dados na chave/ordem
              wSQL_AUX = 'SELECT first 1 BDORDEMRAT ' ||
                         'FROM TMP_VEF_EMP_TMOVRAT' || :wmovimento || '_TEMP ' ||
                         'WHERE BDCHAVE = ' || :WCHAVE ||
                         '  and BDORDEM = ' || :WORDEM ||
                         '  and BDDEB = ' || IIF(:WDEB IS NULL,  'NULL', :WDEB)  ||
                         '  and BDCRED = ' || IIF(:WCRED IS NULL,  'NULL', :WCRED) ||
                         '  and BDSESSAO = ' || :prSessao;

              EXECUTE STATEMENT :WSQL_AUX INTO :WORDEM_SALVA;

              --Se n?o tiver, vamos pegar a pr?xima
              if (coalesce(:wordem_salva,-1) = -1) then
                 begin
                    wSQL_AUX = 'SELECT MAX(BDORDEMRAT) ' ||
                               'FROM TMP_VEF_EMP_TMOVRAT' || :wmovimento || '_TEMP ' ||
                               'WHERE BDCHAVE = ' || :WCHAVE ||
                               '  and BDORDEM = ' || :WORDEM ||
                               '  and BDSESSAO = ' || :prSessao;

                    EXECUTE STATEMENT :WSQL_AUX INTO :WORDEM_SALVA;

                    WORDEM_SALVA = coalesce(:wordem_salva, 0) + 1;
                 end

              --atualizamos a ordem ent?o
              WORDEMRAT = :wordem_salva;
           end

        --vamos agora fazer o update ou insert do registro
        wsql_aux = 'UPDATE OR INSERT INTO TMP_VEF_EMP_TMOVRAT' || :wmovimento || '_TEMP ' ||
                   '     (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMRAT, BDEDITCHAVE, ' ||
                   '      BDVALOR, BDCODPLANOONLINE, BDCHAVEONLINE, BDCRED, BDDEB, ' ||
                   '      BDHIST, BDCOMP, BDCODNAT, BDCONDPGTO) ' ||
                   'values(' || :PRSESSAO || ', ' || :WCODEMP || ', ' || :WCHAVE || ', ' || :WORDEM || ', ' || :WORDEMRAT || ', ' || :WEDITCHAVE || ', ' ||
                   '      ' || :WVALOR || ', ' || :WCODPLANOONLINE || ', ' || :WCHAVEONLINE || ', ' || IIF(:WCRED IS NULL,  'NULL', :WCRED) || ', ' || IIF(:WDEB IS NULL,  'NULL', :WDEB) ||  ', ' ||
                   '      ' || IIF(:WHIST IS NULL,  'NULL', :WHIST) || ', ' || IIF(:WCOMP IS NULL,  'NULL', :WCOMP) || ', ' || :WCODNAT || ', ' || :WCONDPGTO || ') ' ||
                   ' MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMRAT)';

        EXECUTE STATEMENT :WSQL_AUX;
     end
end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_DIFPR (
    PRSESSAO integer,
    PRMOVIMENTO integer)
as
declare variable WMOVIMENTO varchar(3);
declare variable WSQL varchar(10000);
declare variable WSQL_AUX varchar(10000);
declare variable WORDEM_SALVA integer;
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WORDEMDIF integer;
declare variable WEDITCHAVE integer;
declare variable WBASECALCULO numeric(15,2);
declare variable WICMSORIGEM numeric(15,2);
declare variable WPRECINTRA numeric(7,4);
declare variable WBASEESTADO numeric(15,2);
declare variable WALIQINTERNA numeric(7,4);
declare variable WICMSINTERNO numeric(15,2);
declare variable WIMPRECOLHER numeric(15,2);
declare variable WREDUCAOBC numeric(7,4);
declare variable WALIQSN numeric(7,4);
declare variable WALIQSNFIELD varchar(20);
begin
  if (prmovimento = 0) then
     begin
        :wmovimento = 'ENT';
        :WALIQSNFIELD = ', DIF.BDALIQSN ';
     end
  else
     begin
        :wmovimento = 'SAI';
        :WALIQSNFIELD = ', 0 AS BDALIQSN ';
     end

  wSQL = 'select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMDIF, ATU.BDEDITCHAVE, sum(ATU.BDBASECALCULO) as BDBASECALCULO, ' ||
         '       sum(ATU.BDICMSORIGEM) as BDICMSORIGEM, ATU.BDPRECINTRA, sum(ATU.BDBASEESTADO) as BDBASEESTADO, ATU.BDALIQINTERNA, ' ||
         '       sum(ATU.BDICMSINTERNO) as BDICMSINTERNO, sum(ATU.BDIMPRECOLHER) as BDIMPRECOLHER, ATU.BDREDUCAOBC, ATU.BDALIQSN ' ||
         '      from (select DIF.BDCODEMP, DIF.BDCHAVE, DIF.BDORDEM, DIF.BDORDEMDIF, DIF.BDEDITCHAVE, ' ||
         '                   DIF.BDBASECALCULO * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDBASECALCULO, ' ||
         '                   DIF.BDICMSORIGEM * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDICMSORIGEM,DIF.BDPRECINTRA, ' ||
         '                   coalesce(DIF.BDBASEESTADO, 0) * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDBASEESTADO, DIF.BDALIQINTERNA, ' ||
         '                   DIF.BDICMSINTERNO * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDICMSINTERNO, ' ||
         '                   DIF.BDIMPRECOLHER * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDIMPRECOLHER, DIF.BDREDUCAOBC' || :WALIQSNFIELD ||
         '            from TMP_VEF_EMP_TMOV' || :wmovimento || 'DIFPR_TEMP DIF ' ||
         '            inner join TMP_VEF_EMP_TMOV' || :wmovimento || 'ITENS_TEMP IT on IT.BDSESSAO = DIF.BDSESSAO and ' ||
         '                  IT.BDCODEMP = DIF.BDCODEMP and ' ||
         '                  IT.BDCHAVE = DIF.BDCHAVE and ' ||
         '                  IT.BDORDEM = DIF.BDORDEM and ' ||
         '                  IT.BDSESSAO = DIF.BDSESSAO ' ||
         '        where DIF.BDSESSAO = ' || :prSessao || ' ' ||
         '          and coalesce(IT.BDROW_EXCLUIDA, 0) <> 1 ' ||
         '            union all ' ||
         '            select DIF.BDCODEMP, DIF.BDCHAVE, PR.BDORDEM_ATU, DIF.BDORDEMDIF, DIF.BDEDITCHAVE, ' ||
         '                   DIF.BDBASECALCULO * PR.BDRAZAORATEIO as BDBASECALCULO, ' ||
         '                   DIF.BDICMSORIGEM * PR.BDRAZAORATEIO as BDICMSORIGEM, DIF.BDPRECINTRA, ' ||
         '                   coalesce(DIF.BDBASEESTADO, 0) * PR.BDRAZAORATEIO as BDBASEESTADO, DIF.BDALIQINTERNA, ' ||
         '                   DIF.BDICMSINTERNO * PR.BDRAZAORATEIO as BDICMSINTERNO, ' ||
         '                   DIF.BDIMPRECOLHER * PR.BDRAZAORATEIO as BDIMPRECOLHER, DIF.BDREDUCAOBC' || :WALIQSNFIELD ||
         '            from TMP_VEF_EMP_TMOV' || :wmovimento || 'DIFPR_TEMP DIF ' ||
         '            inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on DIF.BDSESSAO = PR.BDSESSAO and ' ||
         '                  DIF.BDCODEMP = PR.BDCODEMP and ' ||
         '                  DIF.BDCHAVE = PR.BDCHAVE and ' ||
         '                  DIF.BDORDEM = PR.BDORDEM_ORIG ' ||
         '        where DIF.BDSESSAO = ' || :prSessao || ') ATU ' ||
         '      group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMDIF, ATU.BDEDITCHAVE, ATU.BDPRECINTRA, ATU.BDALIQINTERNA, ATU.BDREDUCAOBC, ATU.BDALIQSN ';

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  for execute statement wsql into
         :WCODEMP,
         :WCHAVE,
         :WORDEM,
         :WORDEMDIF,
         :WEDITCHAVE,
         :WBASECALCULO,
         :WICMSORIGEM,
         :WPRECINTRA,
         :WBASEESTADO,
         :WALIQINTERNA,
         :WICMSINTERNO,
         :WIMPRECOLHER,
         :WREDUCAOBC,
         :WALIQSN
  do
     begin
        --Se a ordem vier aqui como -1, ent?o ? um lan?amento novo?
        if (:WORDEMDIF = -1) then
           begin
              wordem_salva = -1;

              --a primeira coisa ? procurar se j? tem algum lan?amento com os dados na chave/ordem
              wSQL_AUX = 'SELECT first 1 BDORDEMDIF ' ||
                         'FROM TMP_VEF_EMP_TMOV' || :wmovimento || 'DIFPR_TEMP ' ||
                         'WHERE BDCHAVE = ' || :WCHAVE ||
                         '  and BDORDEM = ' || :WORDEM ||
                         '  and BDALIQINTERNA = ' || :WALIQINTERNA ||
                         '  and BDPRECINTRA = ' || :WPRECINTRA ||
       '  and BDSESSAO = ' || :prsessao;

              EXECUTE STATEMENT :WSQL_AUX INTO :WORDEM_SALVA;

              --Se n?o tiver, vamos pegar a pr?xima
              if (coalesce(:wordem_salva,-1) = -1) then
                 begin
                    wSQL_AUX = 'SELECT MAX(BDORDEMDIF) ' ||
                               'FROM TMP_VEF_EMP_TMOV' || :wmovimento || 'DIFPR_TEMP ' ||
                               'WHERE BDCHAVE = ' || :WCHAVE ||
                               '  and BDORDEM = ' || :WORDEM ||
          '  and BDSESSAO = ' || :prSessao;

                    EXECUTE STATEMENT :WSQL_AUX INTO :WORDEM_SALVA;

                    WORDEM_SALVA = coalesce(:wordem_salva, 0) + 1;
                 end

              --atualizamos a ordem ent?o
              WORDEMDIF = :wordem_salva;
           end

        --vamos agora fazer o update ou insert do registro
        wsql_aux = 'UPDATE OR INSERT INTO TMP_VEF_EMP_TMOV' || :wmovimento || 'DIFPR_TEMP ' ||
                   '     (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMDIF, BDEDITCHAVE, BDBASECALCULO, BDICMSORIGEM, BDPRECINTRA, ' ||
                   '       BDBASEESTADO, BDALIQINTERNA, BDICMSINTERNO, BDIMPRECOLHER, BDREDUCAOBC';

        if (prmovimento = 0) then
           wsql_aux = :wsql_aux || ', BDALIQSN) ';

        wsql_aux = :wsql_aux ||
                   'values(' || :PRSESSAO || ', ' || :WCODEMP || ', ' || :WCHAVE || ', ' || :WORDEM || ', ' || :WORDEMDIF || ', ' || :WEDITCHAVE || ', ' ||
                   '      ' || :WBASECALCULO || ', ' || :WICMSORIGEM || ', ' || :WPRECINTRA || ', ' || :WBASEESTADO || ', ' || :WALIQINTERNA ||  ', ' ||
                   '      ' || :WICMSINTERNO || ', ' || :WIMPRECOLHER || ', ' || :WREDUCAOBC;

        if (prmovimento = 0) then
            wsql_aux = :wsql_aux || ', ' || :WALIQSN;

        wsql_aux = :wsql_aux 
                  ||  ') MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMDIF)';

        EXECUTE STATEMENT :WSQL_AUX;
     end
end^

create or alter procedure SP_FISCAL_RATEIA_CFOP_DIFALIQ (
    PRSESSAO integer not null,
    PRMOVIMENTO integer not null)
as
declare variable WSQL varchar(10000);
declare variable WMOVIMENTO varchar(3);
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WORDEMDIFALIQ integer;
declare variable WBCDIFENTALIQ numeric(15,2);
declare variable WALIQORIDIFENTALIQ numeric(15,2);
declare variable WALIQDESDIFENTALIQ numeric(15,2);
declare variable WVLRDIFENTALIQ numeric(15,2);
declare variable WORDEM_SALVA integer;
declare variable WSQL_AUX varchar(1000);
declare variable WEDITCHAVE integer;
begin
  /* Esta aqui ? um SP de rateio, s?o de tabelas espec?ficas e ent?o o que uma faz as outras copiam, apenas mudando a tabela e os campos */
  if (prmovimento = 0) then
     begin
        :wmovimento = 'ENT';
     end
  else
     begin
        :wmovimento = 'SAI';
     end

  wSQL = 'select ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMDIFALIQ, ATU.BDEDITCHAVE, '||
         '       sum(ATU.BDBCDIFENTALIQ) as BDBCDIFENTALIQ, ATU.BDALIQORIDIFENTALIQ, ATU.BDALIQDESDIFENTALIQ, ' ||
         '       sum(ATU.BDVLRDIFENTALIQ) as BDVLRDIFENTALIQ ' ||
         '  from (select DIF.BDCODEMP, DIF.BDCHAVE, DIF.BDORDEM, DIF.BDORDEMDIFALIQ, DIF.BDEDITCHAVE, ' ||
         '               DIF.BDBCDIFENTALIQ * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDBCDIFENTALIQ, DIF.BDALIQORIDIFENTALIQ, ' ||
         '               DIF.BDALIQDESDIFENTALIQ, DIF.BDVLRDIFENTALIQ * CASE WHEN (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) > 1 THEN 1 ELSE (IT.BDVLRCONTAB / IT.BDVLRORIGINAL) END as BDVLRDIFENTALIQ ' ||
         '        from TMP_VEF_EMP_TMOV' || :wmovimento || 'DIFALIQ_TEMP DIF ' ||
         '        inner join TMP_VEF_EMP_TMOV' || :wmovimento || 'ITENS_TEMP IT on IT.BDSESSAO = DIF.BDSESSAO and ' ||
         '              IT.BDCODEMP = DIF.BDCODEMP and ' ||
         '              IT.BDCHAVE = DIF.BDCHAVE and ' ||
         '              IT.BDORDEM = DIF.BDORDEM and ' ||
         '              IT.BDSESSAO = DIF.BDSESSAO ' ||
         '        where DIF.BDSESSAO = ' || :prSessao || ' ' ||
         '          and coalesce(IT.BDROW_EXCLUIDA, 0) <> 1 ' ||
         '        union all ' ||
         '        select DIF.BDCODEMP, DIF.BDCHAVE, PR.BDORDEM_ATU, -1 as BDORDEMDIFALIQ, ' ||
         '               DIF.BDEDITCHAVE, DIF.BDBCDIFENTALIQ * PR.BDRAZAORATEIO as BDBCDIFENTALIQ, ' ||
         '               DIF.BDALIQORIDIFENTALIQ, DIF.BDALIQDESDIFENTALIQ, ' ||
         '               DIF.BDVLRDIFENTALIQ * PR.BDRAZAORATEIO as BDVLRDIFENTALIQ ' ||
         '        from TMP_VEF_EMP_TMOV' || :wmovimento || 'DIFALIQ_TEMP DIF ' ||
         '        inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on DIF.BDSESSAO = PR.BDSESSAO and ' ||
         '              DIF.BDCODEMP = PR.BDCODEMP and ' ||
         '              DIF.BDCHAVE = PR.BDCHAVE and ' ||
         '              DIF.BDORDEM = PR.BDORDEM_ORIG ' ||
         '        where DIF.BDSESSAO = ' || :prSessao || ') ATU ' ||
         '  group by ATU.BDCODEMP, ATU.BDCHAVE, ATU.BDORDEM, ATU.BDORDEMDIFALIQ, ATU.BDEDITCHAVE, ATU.BDALIQORIDIFENTALIQ, ATU.BDALIQDESDIFENTALIQ';

  --eu tentei, sem sucesso fazer isso aqui diretamente pelo merge.. ent?o vamos pelo cursor...
  -- aqui estar? a diferen?a entre ele e as outras SP, a quantidade de vari?veis no FOR aqui,
  -- o resto, em teoria, segue a mesma receita de bolo
  for execute statement wsql into
         :WCODEMP,
         :WCHAVE,
         :WORDEM,
         :WORDEMDIFALIQ,
         :WEDITCHAVE,
         :WBCDIFENTALIQ,
         :WALIQORIDIFENTALIQ,
         :WALIQDESDIFENTALIQ,
         :WVLRDIFENTALIQ
  do
     begin
        --Se a ordem vier aqui como -1, ent?o ? um lan?amento novo?
        if (:WORDEMDIFALIQ = -1) then
           begin
              wordem_salva = -1;

              --a primeira coisa ? procurar se j? tem algum lan?amento com os dados na chave/ordem
              wSQL_AUX = 'SELECT first 1 BDORDEMDIFALIQ ' ||
                         'FROM TMP_VEF_EMP_TMOV' || :wmovimento || 'DIFALIQ_TEMP ' ||
                         'WHERE BDCHAVE = ' || :WCHAVE ||
                         '  and BDORDEM = ' || :WORDEM ||
                         '  and BDALIQORIDIFENTALIQ = ' || :WALIQORIDIFENTALIQ ||
                         '  and BDALIQDESDIFENTALIQ = ' || :WALIQDESDIFENTALIQ ||
       '  and BDSESSAO = ' || :prSessao;

              EXECUTE STATEMENT :WSQL_AUX INTO :WORDEM_SALVA;

              --Se n?o tiver, vamos pegar a pr?xima
              if (coalesce(:wordem_salva,-1) = -1) then
                 begin
                    wSQL_AUX = 'SELECT MAX(BDORDEMDIFALIQ) ' ||
                               'FROM TMP_VEF_EMP_TMOV' || :wmovimento || 'DIFALIQ_TEMP ' ||
                               'WHERE BDCHAVE = ' || :WCHAVE ||
                               '  and BDORDEM = ' || :WORDEM ||
          '  and BDSESSAO = ' || :prSessao;

                    EXECUTE STATEMENT :WSQL_AUX INTO :WORDEM_SALVA;

                    WORDEM_SALVA = coalesce(:wordem_salva, 0) + 1;
                 end

              --atualizamos a ordem ent?o
              WORDEMDIFALIQ = :wordem_salva;
           end

        --vamos agora fazer o update ou insert do registro
        wsql_aux = 'UPDATE OR INSERT INTO TMP_VEF_EMP_TMOV' || :wmovimento || 'DIFALIQ_TEMP ' ||
                   '     (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMDIFALIQ, BDEDITCHAVE, ' ||
                   '      BDBCDIFENTALIQ, BDALIQORIDIFENTALIQ, BDALIQDESDIFENTALIQ, BDVLRDIFENTALIQ) ' ||
                   'values(' || :PRSESSAO || ', ' || :WCODEMP || ', ' || :WCHAVE || ', ' || :WORDEM || ', ' || :WORDEMDIFALIQ || ', ' || :WEDITCHAVE || ', ' ||
                   '      ' || :WBCDIFENTALIQ || ', ' || :WALIQORIDIFENTALIQ || ', ' || :WALIQDESDIFENTALIQ || ', ' || :WVLRDIFENTALIQ || ') ' ||
                   ' MATCHING (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMDIFALIQ)';

        EXECUTE STATEMENT :WSQL_AUX;
     end
end^

CREATE OR ALTER procedure SP_FISCAL_RATEIA_CFOP (
    PRSESSAO integer not null,
    PRMOVIMENTO integer not null)
as
declare variable WMOV varchar(3);
declare variable WSQL varchar(30000);
begin
  /* prMovimento: 0 - Entrada; 1 - Saídas

     O que esta procedure faz?
         Quando os produtos mudam de CFOP ela vai ratear as tabelas filhas conforme o valor mudou.
         Por exemplo quando temos uma nota com um CFOP, digamos que seja 5.102-000, e desmembramos um produto para a CFOP 5.101-000.
         O valor original da CFOP era 1.000,00 e desmemebramos 200,00. Logo as tabelas dependentes, como diferencial de alíquota, centro de custo,
         são atualizadas neste valor e outros registros são criados se necessário

     Gostei disso! O que eu preciso fazer para usar?
        1 - O fundamental aqui ? primeiro usar as rotinas :
               * SPLIMP_TEMP_RECURSIVO, SP_CARREGA_TABTEMP_RECURSIVO e SPCOMMITA_TEMP_RECURSIVA: estas rotinas se encarregam de carregar todos
                 os dados que você precisa para garantir que ninguém fique de fora, além de automatizar o processo.

        2 - também certifique-se que os campos BDVLRCONTAB e BDVLRORIGINAL nas tabelas TMP_VEF_EMP_TMOVENTITENS_TEMP e TMP_VEF_EMP_TMOVSAIITENS_TEMP
            estejam com os valores corretos antes que chegar aqui

     Bom eu acho que ali em cima já fica bem claro, mas vou deixar isso bem explícito:

                   Esta ROTINA SÓ TRABALHA COM AS TABELAS TEMPORÁRIAS!!!

  */

  /*
                       PREPARANDO O AMBIENTE!!!!


      Neste trecho o que faremos?

      1 - vamos fazer o novo LINK entre os produtos e as CFOPs
      2 - vamos "excluir logicamente" as CFOPs que ficaram sem produtos
      3 - vamos popular a tabela auxiliar de rateio
  */

  if (PRMOVIMENTO = 0) then
     begin
        :WMOV = 'ENT';
     end
  else
     begin
        :WMOV = 'SAI';
     end

  WSQL = 'alter trigger TMP_VEF_EMP_TMOVPRO' || :WMOV || '_TEMP_AU0 active;';

  execute statement :WSQL;

  -- Passo 1: atualizar os produtos conforme a CFOP
  WSQL = 'merge into TMP_VEF_EMP_TMOVPRO' || :WMOV || '_TEMP PROD ' || 'using (select PR.BDCODEMP, PR.BDSESSAO, PR.BDCHAVE, PR.BDORDEM, PR.BDORDEMPRO, ' || '              (select min(IT.BDORDEM) ' || '               from TMP_VEF_EMP_TMOV' || :WMOV || 'ITENS_TEMP IT ' || '               where IT.BDSESSAO = PR.BDSESSAO and ' || '                     IT.BDCODEMP = PR.BDCODEMP and ' || '                     IT.BDCHAVE = PR.BDCHAVE and ' || '                     IT.BDCODNAT = PR.BDCODNAT) as BDORDEMNOVA, ' || '              row_number() over(partition by PR.BDCHAVE) as ORDEMPRONOVA, ' || '              (select coalesce(max(PR2.BDORDEMPRO), 0) ' || '               from TMP_VEF_EMP_TMOVPRO' || :WMOV || '_TEMP PR2 ' || '               where PR2.BDSESSAO = PR.BDSESSAO and ' || '                     PR2.BDCODEMP = PR.BDCODEMP and ' || '                     PR2.BDCHAVE = PR.BDCHAVE and ' || '                     PR2.BDORDEM = (select min(IT.BDORDEM) ' || '                                    from TMP_VEF_EMP_TMOV' || :WMOV || 'ITENS_TEMP IT ' || '                                    where IT.BDSESSAO = PR.BDSESSAO and ' || '                                          IT.BDCODEMP = PR.BDCODEMP and ' || '                                          IT.BDCHAVE = PR.BDCHAVE and ' || '                                          IT.BDCODNAT = PR.BDCODNAT)) as ORDEM_FIN_ATU ' || '       from TMP_VEF_EMP_TMOVPRO' || :WMOV || '_TEMP PR ' || '       where PR.BDSESSAO = ' || :PRSESSAO || ' and ' || '             (select min(IT.BDORDEM) ' || '              from TMP_VEF_EMP_TMOV' || :WMOV || 'ITENS_TEMP IT ' || '              where IT.BDSESSAO = PR.BDSESSAO and ' || '                    IT.BDCODEMP = PR.BDCODEMP and ' || '                    IT.BDCHAVE = PR.BDCHAVE and ' || '                    IT.BDCODNAT = PR.BDCODNAT) <> PR.BDORDEM) ITENS ' || 'on PROD.BDCODEMP = ITENS.BDCODEMP and ' || '   PROD.BDSESSAO = ITENS.BDSESSAO and ' || '   PROD.BDCHAVE = ITENS.BDCHAVE and ' || '   PROD.BDORDEM = ITENS.BDORDEM and ' || '   PROD.BDORDEMPRO = ITENS.BDORDEMPRO and ' || '   PROD.BDSESSAO = ' || :PRSESSAO || ' ' || 'when matched then ' || '    update set PROD.BDORDEM_ORIG = PROD.BDORDEM, ' || '               PROD.BDORDEMPRO_ORIG = PROD.BDORDEMPRO, ' || '               PROD.BDORDEM = ITENS.BDORDEMNOVA, ' || '               PROD.BDORDEMPRO = ITENS.ORDEM_FIN_ATU + ITENS.ORDEMPRONOVA;';

  execute statement :WSQL;

  WSQL = 'alter trigger TMP_VEF_EMP_TMOVPRO' || :WMOV || '_TEMP_AU0 inactive;';

  execute statement :WSQL;

  --Passo 2: APAGAR OS ITENS QUE FICARAM SEM PRODUTOS -- calma pequeno mancebo.. apenas logicamente agora
  WSQL = 'merge into TMP_VEF_EMP_TMOV' || :WMOV || 'ITENS_TEMP IT ' || 'using (select IT.BDCHAVE, IT.BDSESSAO, IT.BDORDEM, IT.BDCODEMP ' || 'from TMP_VEF_EMP_TMOV' || :WMOV || 'ITENS_TEMP IT ' || 'left outer join TMP_VEF_EMP_TMOVPRO' || :WMOV || '_TEMP PR on IT.BDSESSAO = PR.BDSESSAO and ' || '      IT.BDCODEMP = PR.BDCODEMP and ' || '      IT.BDCHAVE = PR.BDCHAVE and ' || '      IT.BDORDEM = PR.BDORDEM ' || 'where IT.BDSESSAO = ' || :PRSESSAO || ' and ' || '      PR.BDORDEMPRO is null) PROV ' || 'on IT.bdsessao = prov.bdsessao and ' || '   it.bdcodemp = prov.bdcodemp and ' || '   it.bdchave  = prov.bdchave and ' || '   it.bdordem  = prov.bdordem ' || 'when matched then ' || '   update set it.BDROW_EXCLUIDA = 1';

  execute statement :WSQL;

  --Passo 3: Limpando a tabela auxiliar de rateios - no fim ele também faz isso, mas por precaução, reforçamos aqui
  delete from TMP_VEF_EMP_AUXRATEIOCFOP_TEMP where BDSESSAO = :PRSESSAO;

  --agora vamos repopular essa tabela, é usada nas procedures a frente
  WSQL = 'insert into TMP_VEF_EMP_AUXRATEIOCFOP_TEMP ' || 'select IT.BDSESSAO, IT.BDCODEMP, IT.BDCHAVE, CFOP.BDVLRORIGINAL, sum(IT.BDVLRITEM) as BDVLRRATEIO, ' || '       IT.BDORDEM as BDORDEM_ATU, IT.BDORDEM_ORIG, sum(IT.BDVLRITEM)/iif(Coalesce(CFOP.BDVLRORIGINAL, 0) = 0, 1, CFOP.BDVLRORIGINAL) ' || 'from TMP_VEF_EMP_TMOVPRO' || :WMOV || '_TEMP IT ' || '   inner join TMP_VEF_EMP_TMOV' || :WMOV || 'ITENS_TEMP CFOP ' || '     on CFOP.BDSESSAO = IT.BDSESSAO and ' || '        CFOP.BDCODEMP = IT.BDCODEMP and ' || '        CFOP.BDCHAVE = IT.BDCHAVE and   ' || '        CFOP.BDORDEM = IT.BDORDEM_ORIG  ' || 'where IT.BDSESSAO = ' || :PRSESSAO || ' ' || 'group by IT.BDSESSAO, IT.BDCODEMP, IT.BDCHAVE, IT.BDORDEM, IT.BDORDEM_ORIG, CFOP.BDVLRORIGINAL';

  execute statement :WSQL;

  /*
                       INÍCIO DO RATEIO PROPRIAMENTE DITO!!!!

       O que vamos fazer aqui:

       1 - algumas tabelas não precisa do rateio em si, mas apenas que sejam realocadas, como a de histórico de importações,
           Isso é sussi e fazer aqui mesmo
       2 - já outras tabelas precisam ratear os valores, nestes casos criamos um SP para cada tabela, afim de tratar de suas particularidades



       DICA DE OURO !!!

       Leia tudo:
       Você precisa inserir uma tabela nova aqui? Se liga nessas inspirações:

          - Se a tabela que vai ser rateada é do tipo 1:1, ou seja não possui um campo ordem próprio, olhe a SP_FISCAL_RATEIA_CFOP_DCIP
          - Se a tabela que vai ser rateada é do tipo 1:N, ou seja possui um campo próprio de ordem, olhe a SP_FISCAL_RATEIA_CFOP_ANTPR
          - Se a tabela que vai ser rateada vale para entrada e saídas, olhe a SP_FISCAL_RATEIA_CFOP_DIFALIQ
  */

  --VEF_EMP_TMOVPROENTIMPORI e VEF_EMP_TMOVPROSAIIMPORI
  /* Neste itens, como são os valores originais, nunca devem ser mexidos....
  WSQL = 'merge into TMP_VEF_EMP_TMOVPRO' || :WMOV || 'IMPORI_TEMP FILHO ' ||
         'using (select PROD.BDORDEM_ORIG, PROD.BDORDEM, PROD.BDORDEMPRO_ORIG, PROD.BDORDEMPRO, PROD.BDCODEMP, ' ||
         '              PROD.BDCHAVE, PROD.BDSESSAO ' ||
         '              from TMP_VEF_EMP_TMOVPRO' || :WMOV || '_TEMP PROD ' ||
         '              where PROD.BDSESSAO = ' || :PRSESSAO || ' and ' ||
         '                    coalesce(PROD.BDORDEM_ORIG, PROD.BDORDEM) <> PROD.BDORDEM) PAI ' ||
         'on FILHO.BDCHAVE = PAI.BDCHAVE and ' ||
         '   FILHO.BDSESSAO = PAI.BDSESSAO and ' ||
         '   FILHO.BDCODEMP = PAI.BDCODEMP and ' ||
         '   FILHO.BDORDEM = PAI.BDORDEM_ORIG and ' ||
         '   FILHO.BDORDEMHIST = PAI.BDORDEMPRO_ORIG ' ||
         'when matched then ' ||
         '    update set FILHO.BDORDEM = PAI.BDORDEM, ' ||
         '               FILHO.BDORDEMHIST = PAI.BDORDEMPRO';

  execute statement :WSQL;
  */

  --Agora aqui vamos chamar as procedures de rateios conforme o que foi passado

  --   VEF_EMP_TMOVENTDIFALIQ e VEF_EMP_TMOVSAIDIFALIQ
  execute procedure SP_FISCAL_RATEIA_CFOP_DIFALIQ(:PRSESSAO, :PRMOVIMENTO);

  --   VEF_EMP_TMOVENTDIFPR e VEF_EMP_TMOVSAIDIFPR
  execute procedure SP_FISCAL_RATEIA_CFOP_DIFPR(:PRSESSAO, :PRMOVIMENTO);

  --   VEF_EMP_TMOVCCENT e VEF_EMP_TMOVCCSAI
  execute procedure SP_FISCAL_RATEIA_CFOP_MOVCC(:PRSESSAO, :PRMOVIMENTO);

  --   VEF_EMP_TMOVRATENT e VEF_EMP_TMOVRATSAI
  execute procedure SP_FISCAL_RATEIA_CFOP_MOVRAT(:PRSESSAO, :PRMOVIMENTO);

  --   TMP_VEF_EMP_TMOVENTIMPRETSP_TEMP e TMP_VEF_EMP_TMOVSAIIMPRETSP_TEMP
  execute procedure SP_FISCAL_RATEIA_IMPRETSP(:PRSESSAO, :PRMOVIMENTO);

  --   VEF_EMP_TMOVENTOCOSP e VEF_EMP_TMOVSAIOCOSP
  execute procedure SP_FISCAL_RATEIA_OCOSP(:PRSESSAO, :PRMOVIMENTO);

  --   TMP_VEF_EMP_TMOVENTPR_TEMP e TMP_VEF_EMP_TMOVSAIPR_TEMP
  execute procedure SP_FISCAL_RATEIA_CFOP_PR(:PRSESSAO, :PRMOVIMENTO);

  --   TMP_VEF_EMP_TMOVENTQ48_TEMP e TMP_VEF_EMP_TMOVSAIQ48_TEMP
  execute procedure SP_FISCAL_RATEIA_CFOP_Q48(:PRSESSAO, :PRMOVIMENTO);

  --   TMP_VEF_EMP_TMOVENTSN_TEMP e TMP_VEF_EMP_TMOVSAISN_TEMP
  execute procedure SP_FISCAL_RATEIA_CFOP_SN(:PRSESSAO, :PRMOVIMENTO);

  --   VEF_EMP_TMOVENTSTDAPI e VEF_EMP_TMOVSAISTDAPI
  execute procedure SP_FISCAL_RATEIA_CFOP_DAPI(:PRSESSAO, :PRMOVIMENTO);

  --   VEF_EMP_TMOVENTVARALIQ e VEF_EMP_TMOVSAIVARALIQ
  -- Neste caso aqui vamos refazer tudo por conta das alterações que possam ter havido
  -- Então primeiro vamos apagar tudo
  wSQL =  'DELETE FROM TMP_VEF_EMP_TMOV' || :WMOV || 'VARALIQ_TEMP WHERE BDSESSAO = ' || :PRSESSAO;
  execute statement :WSQL;

  -- Depois refaremos tudo
  wSQL =  ' insert into TMP_VEF_EMP_TMOV' || :WMOV || 'VARALIQ_TEMP ' ||
          ' with VAR_ALIQ_CALC ' ||
          '   as (select MP.BDSESSAO, MP.BDCODEMP, MP.BDCHAVE, MP.BDORDEM, ' ||
          '            dense_rank() over(partition by MP.BDCODEMP, MP.BDCHAVE, MP.BDORDEM, MP.BDSESSAO order by MP.BDALIQICMS) as BDORDEMICMS, ' ||
          '            MP.BDCHAVE as BDCHAVE2, sum(MP.BDVLRITEM) as BDVLRCONTABIL, 0 as CONST3, sum(MP.BDBCICMS) as BDBASEREDICMS, ' ||
          '            MP.BDALIQICMS, sum(MP.BDVLRICMS) as BDVLRICMS, 0 as CONST, 0 as CONST2, 0 as BDEXCLUIDA, ' ||
          '            sum(1) over(partition by MP.BDCODEMP, MP.BDCHAVE, MP.BDORDEM, MP.BDSESSAO) AS COUNTALIQ ' ||
          '       from TMP_VEF_EMP_TMOVPRO' || :WMOV || '_TEMP MP ' ||
          '       where MP.BDSESSAO = ' || :PRSESSAO ||
          '       group by MP.BDCODEMP, MP.BDCHAVE, MP.BDORDEM, MP.BDSESSAO, MP.BDALIQICMS ' ||
          '      ) ' ||
          ' select BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMICMS, BDCHAVE2, BDVLRCONTABIL, CONST3, BDBASEREDICMS, ' ||
          '        BDALIQICMS, BDVLRICMS, CONST, CONST2, BDEXCLUIDA ' ||
          ' from VAR_ALIQ_CALC ' ||
          ' where COUNTALIQ > 1';
  execute statement :WSQL;

  --   VEF_EMP_TMOVENTVINCBEM e VEF_EMP_TMOVSAIVINCBEM
  wSQL =  'merge into TMP_VEF_EMP_TMOV' || :WMOV || 'VINCBEM_TEMP PAI ' ||
          'using (SELECT IT.BDSESSAO, IT.BDCODEMP, IT.BDCHAVE, IT.BDORDEM, IT.BDORDEM_ORIG ' ||
          '       FROM  TMP_VEF_EMP_TMOVPRO' || :WMOV || '_TEMP IT ' ||
          '       WHERE IT.bdordem <> coalesce(IT.bdordem_orig,IT.bdordem) ' ||
          '         and IT.bdSessao  = ' || :PRSESSAO || ') FILHO ' ||
          'on pai.bdsessao = filho.bdsessao ' ||
          '  and pai.bdcodemp = filho.bdcodemp ' ||
          '  and pai.bdchave = filho.bdchave ' ||
          '  and pai.bdordem = filho.bdordem_orig ' ||
          'when matched then ' ||
          '    update set PAI.BDORDEM = filho.BDORDEM';
  execute statement :WSQL;

  --algumas tabelas são exclusivas por movimento
  --  ENTRADAS
  if (PRMOVIMENTO = 0) then
     begin
        --   TMP_VEF_EMP_TMOVENTANTPR_TEMP
        execute procedure SP_FISCAL_RATEIA_CFOP_ANTPR(:PRSESSAO);

        --   TMP_VEF_EMP_TMOVENTANTIMP_TEMP
        execute procedure SP_FISCAL_RATEIA_CFOP_ANTIMP(:PRSESSAO);

        --   TMP_VEF_EMP_TMOVENTDCIP_TEMP
        execute procedure SP_FISCAL_RATEIA_CFOP_DCIP(:PRSESSAO);

        --   TMP_VEF_EMP_TMOVENTPMPF_TEMP
        execute procedure SP_FISCAL_RATEIA_PMPF(:PRSESSAO);

        --   TMP_VEF_EMP_TMOVENTMVA_TEMP
        execute procedure SP_FISCAL_RATEIA_CFOP_MVA(:PRSESSAO);

        --   TMP_VEF_EMP_TMOVMVAPR_TEMP
        execute procedure SP_FISCAL_RATEIA_CFOP_MVAPR(:PRSESSAO);

        --   TMP_VEF_EMP_TMOVMVASC_TEMP
        execute procedure SP_FISCAL_RATEIA_CFOP_MVASC(:PRSESSAO);

        --   TMP_VEF_EMP_TMOVENT_IVA_TEMP
        execute procedure SP_FISCAL_RATEIA_CFOP_IVA(:PRSESSAO);
     end
  else
     -- SA?DAS
     begin
        --   VEF_EMP_TMOVSAI_INF_NF_SP
        execute procedure SP_FISCAL_RATEIA_CFOP_INF_NF_SP(:prSessao);

        --   VEF_EMP_TMOVSAIEXPSP
        merge into TMP_VEF_EMP_TMOVSAIEXPSP_TEMP PAI
        using (select EXP.BDSESSAO, EXP.BDCODEMP, EXP.BDCHAVE, EXP.BDEDITCHAVE, PR.BDORDEM_ATU, EXP.BDREGEXPORTACAO
               from TMP_VEF_EMP_TMOVSAIEXPSP_TEMP EXP
               inner join TMP_VEF_EMP_AUXRATEIOCFOP_TEMP PR on EXP.BDSESSAO = PR.BDSESSAO and
                     EXP.BDCODEMP = PR.BDCODEMP and
                     EXP.BDCHAVE = PR.BDCHAVE and
                     EXP.BDORDEM = PR.BDORDEM_ORIG and
                     EXP.BDSESSAO = PR.BDSESSAO
               where EXP.BDSESSAO = :PRSESSAO) FILHO
        on PAI.BDCODEMP = FILHO.BDCODEMP and
           PAI.BDCHAVE = FILHO.BDCHAVE and
           PAI.BDORDEM = FILHO.BDORDEM_ATU and
           PAI.BDSESSAO = FILHO.BDSESSAO
        when not matched then
           insert (BDSESSAO, BDCODEMP, BDCHAVE, BDEDITCHAVE, BDORDEM, BDREGEXPORTACAO)
           values (FILHO.BDSESSAO, FILHO.BDCODEMP, FILHO.BDCHAVE, FILHO.BDEDITCHAVE, FILHO.BDORDEM_ATU, FILHO.BDREGEXPORTACAO);

        --   VEF_EMP_TMOVSAIECREDAC
        execute procedure SP_FISCAL_RATEIA_CFOP_ECREDAC(:prSessao);
     end

  /*
                       RESTAURANDO O AMBIENTE!!!!


      Neste trecho o que faremos?

      1 - vamos limpar a tabela auxiliar de rateio
  */

  --Ao final de tudo limpamos a tabela auxiliar e agrademos pelos seus bons serviços
  delete from TMP_VEF_EMP_AUXRATEIOCFOP_TEMP where BDSESSAO = :PRSESSAO;
end
^

CREATE OR ALTER procedure SP_NOTAS_ENVIO_IMENDES (
    PRCODEMP varchar(5000),
    PRDATAINICIAL date,
    PRDATAFIM date,
    PRMOVENT DM_BOOLEAN,
    PRMOVSAI DM_BOOLEAN,
    PRMOVREDZ DM_BOOLEAN,
    PRCODTER varchar(5000),
    PRCODPROD varchar(5000),
    PRCODNAT varchar(5000),
    PRDOCUMENTO varchar(5000))
as
declare variable WREF varchar(6);
declare variable WSQL varchar(25000);
BEGIN
  WREF = (SELECT BDAAAAMM FROM AAAAMM(:PRDATAINICIAL));
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(WREF);

  IF (PRMOVENT = 'TRUE') THEN
     BEGIN
      WSQL =        ' INSERT INTO VEF_EMP_TAUDIMENDES (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDSTATUS, BDMOVIMENTO, BDCODNCM, BDCODCEST, BDCSTPISCOFINSENT, ';
      WSQL = WSQL ||                                '  BDALIQPIS, BDALIQCOFINS, BDCSTIPIENT, BDALIQIPI, BDCODUF, BDCODNATOPE, BDFINALIDADE, BDDATANOTA, BDCODTER, ';
      WSQL = WSQL ||                                '  BDCODPROD, BDCODNAT, BDDOCUMENTO, BDCARACTRIBUTARIATER, BDMODELO,BDSERIE,BDCHAVENFE,BDQTDITEM,BDVLRITEM, BDCSTICMS) ';
      WSQL = WSQL ||' SELECT ENT.BDCODEMP, ENT.BDCHAVE, MPRO.BDORDEM, MPRO.BDORDEMPRO, 0, 0/*ENTRADA*/, ';
      WSQL = WSQL ||'         PRO.BDNCMPROD, PRO.BDCODCEST, MPRO.BDCODCSTPIS,MPRO.BDALIQPIS, MPRO.BDALIQCOFINS, ';
      WSQL = WSQL ||'         MPRO.BDCODCSTIPI, MPRO.BDALIQIPI,CID.BDCODUF, I.BDCODNAT, ';
      WSQL = WSQL ||'         IIF(COALESCE(TT.BDTIPOSER,''00'') = ''00'', 0 /*REVENDA*/, IIF(TT.BDTIPOSER IN (''01'',''02'',''03'',''04'',''05'',''06'',''10''),1,IIF(TT.BDTIPOSER IN (''07'',''08''),2,0) )) BDFINALIDADE, ';
      WSQL = WSQL ||'         ENT.BDDATAENTRADAENT, ENT.BDCODTER, PRO.BDCODPROD, I.BDCODNAT, ENT.BDNUMDOCINI, ';
      WSQL = WSQL ||         'case when coalesce(TER.BDCARACTRIBUTARIATER, -1) >= 5 then TER.BDCARACTRIBUTARIATER + 1 ';
      WSQL = WSQL ||              'when coalesce(TER.BDCARACTRIBUTARIATER, -1) = -1 and position(''/'' in TER.BDCGCTER) = 0 and coalesce(TER.BDPRURALTER, ''FALSE'') = ''TRUE'' then 6 ';
      WSQL = WSQL ||              'when coalesce(TER.BDCARACTRIBUTARIATER, -1) = -1 and position(''/'' in TER.BDCGCTER) = 0 and coalesce(TER.BDPRURALTER, ''FALSE'') = ''FALSE'' then 8 ';
      WSQL = WSQL ||              'else TER.BDCARACTRIBUTARIATER ';
      WSQL = WSQL ||         'end as BDCARACTRIBUTARIATER, ';
      WSQL = WSQL ||'         ENT.BDMODELO, IIF(ENT.BDSERIE = '''', NULL, ENT.BDSERIE) BDSERIE, ENT.BDCHAVENFE, MPRO.BDQTDITEM, MPRO.BDVLRITEM, IIF(ICMS.BDCODCSTICMS IN (34,35,36,37,38,39,40,41,42,43),000,ICMS.BDCSTICMS) BDCSTICMS ';
      WSQL = WSQL ||'  FROM ( ';
      WSQL = WSQL ||'        SELECT * ';
      WSQL = WSQL ||'        FROM VEF_EMP_TMOVENT ENT ';
      WSQL = WSQL ||'        WHERE '|| PRCODEMP ;
--      WSQL = WSQL ||'        AND   ENT.BDREFLAN = '||WREF;
      WSQL = WSQL ||'        AND   ENT.BDDATAENTRADAENT BETWEEN '' '||PRDATAINICIAL||' '' AND '' '||PRDATAFIM||' '' ';
      IF (PRCODTER <> '') THEN
        WSQL = WSQL ||'      AND   '||PRCODTER;
      IF (PRDOCUMENTO <> '') THEN
        WSQL = WSQL ||'      AND   ENT.BDNUMDOCINI IN ('||PRDOCUMENTO||')';
      WSQL = WSQL ||'      ) ENT ';
      WSQL = WSQL ||'  JOIN TTERCEIRO_REF TER ON (TER.BDCODTER = ENT.BDCODTER AND TER.BDREFEMP = COALESCE( ';
      WSQL = WSQL ||                                                                                     ' (SELECT FIRST 1 BDREFEMP FROM TTERCEIRO_REF T ';
      WSQL = WSQL ||                                                                                     '  WHERE T.BDCODTER = TER.BDCODTER AND T.BDREFEMP <= ENT.BDREFLAN ';
      WSQL = WSQL ||                                                                                     '  ORDER BY T.BDCODTER DESC, T.BDREFEMP DESC), ';
      WSQL = WSQL ||                                                                                     ' (SELECT FIRST 1 RF2.BDREFEMP FROM TTERCEIRO_REF RF2 ';
      WSQL = WSQL ||                                                                                     ' WHERE RF2.BDCODTER = TER.BDCODTER ORDER BY RF2.BDCODTER, RF2.BDREFEMP) ';
      WSQL = WSQL ||                                                                                     ' ) ) ';
      WSQL = WSQL ||'  JOIN TCIDADE CID ON (CID.BDCODCID = TER.BDCODCID) ';
      WSQL = WSQL ||'  JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE) ';
      WSQL = WSQL ||'  JOIN VEF_EMP_TMOVPROENT MPRO ON (MPRO.BDCODEMP = I.BDCODEMP AND MPRO.BDCHAVE = I.BDCHAVE AND MPRO.BDORDEM = I.BDORDEM) ';
      WSQL = WSQL ||'  JOIN TCADPRO_VINC PRO ON (PRO.BDCODEMP = MPRO.BDCODEMP AND PRO.BDCODPROD = MPRO.BDCODPROD) ';
      WSQL = WSQL ||'  LEFT OUTER JOIN TTIPO_SERVICO TT ON  (TT.BDCODTIPOSER = PRO.BDCODTIPOSER) ';
      WSQL = WSQL ||'  JOIN TEMPRESAS EMP ON (EMP.BDCODEMP = ENT.BDCODEMP) ';
      WSQL = WSQL ||'  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = MPRO.BDCODCSTICMS) ';
      WSQL = WSQL ||'  WHERE NOT EXISTS (SELECT FIRST 1 AUD.BDCODEMP FROM VEF_EMP_TAUDIMENDES AUD ';
      WSQL = WSQL ||'                    WHERE AUD.BDCODEMP = MPRO.BDCODEMP ';
      WSQL = WSQL ||'                    AND   AUD.BDCHAVE =  MPRO.BDCHAVE ';
      WSQL = WSQL ||'                    AND   AUD.BDORDEM = MPRO.BDORDEM ';
      WSQL = WSQL ||'                    AND   AUD.BDORDEMPRO = MPRO.BDORDEMPRO ';
      WSQL = WSQL ||'                    AND   AUD.BDMOVIMENTO = 0) ';
      WSQL = WSQL ||'  AND UPPER(EMP.BDIMENDES) = ''TRUE'' ';
      IF (PRCODNAT <> '') THEN
          WSQL = WSQL ||' AND '||PRCODNAT;
      IF (PRCODPROD <> '') THEN
         WSQL = WSQL ||'  AND '||PRCODPROD;

      EXECUTE STATEMENT(WSQL);
     END

  IF (PRMOVSAI = 'TRUE') THEN
     BEGIN
      WSQL =        ' INSERT INTO VEF_EMP_TAUDIMENDES (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDSTATUS, BDMOVIMENTO, BDCODNCM, BDCODCEST, BDCSTPISCOFINSSAI, ';
      WSQL = WSQL ||                                '  BDALIQPIS, BDALIQCOFINS, BDCSTIPISAI, BDALIQIPI, BDCODUF, BDCODNATOPE, BDDATANOTA, BDCODTER, ';
      WSQL = WSQL ||                                '  BDCODPROD, BDCODNAT, BDDOCUMENTO, BDCARACTRIBUTARIATER, BDMODELO,BDSERIE,BDCHAVENFE,BDQTDITEM,BDVLRITEM, BDCSTICMS, BDCODNATREC, BDFINALIDADE) ';
      WSQL = WSQL ||' select A.*, iif(coalesce(BDCARACTRIBUTARIATER, 0) < 7, 0, 2) as BDFINALIDADE from ( ';/* 0 - Revenda; 2 - Uso e Cosnumo */ 
      WSQL = WSQL ||' select SAI.BDCODEMP, SAI.BDCHAVE, MPRO.BDORDEM, MPRO.BDORDEMPRO, 0 as BDSTATUS, 1 AS BDMOVIMENTO /*SAIDA*/ , ';
      WSQL = WSQL ||'         PRO.BDNCMPROD, PRO.BDCODCEST, MPRO.BDCODCSTPIS,MPRO.BDALIQPIS, MPRO.BDALIQCOFINS, ';
      WSQL = WSQL ||'         MPRO.BDCODCSTIPI, MPRO.BDALIQIPI,CID.BDCODUF, I.BDCODNAT AS BDCODNATOPE, ';
      WSQL = WSQL ||'         SAI.BDDATAEMISSAO, SAI.BDCODTER, PRO.BDCODPROD, I.BDCODNAT, SAI.BDNUMDOCINI, ';
      WSQL = WSQL ||         'case when coalesce(TER.BDCARACTRIBUTARIATER, -1) >= 5 then TER.BDCARACTRIBUTARIATER + 1 ';
      WSQL = WSQL ||              'when coalesce(TER.BDCARACTRIBUTARIATER, -1) = -1 and position(''/'' in TER.BDCGCTER) = 0 and coalesce(TER.BDPRURALTER, ''FALSE'') = ''TRUE'' then 6 ';
      WSQL = WSQL ||              'when coalesce(TER.BDCARACTRIBUTARIATER, -1) = -1 and position(''/'' in TER.BDCGCTER) = 0 and coalesce(TER.BDPRURALTER, ''FALSE'') = ''FALSE'' then 8 ';
      WSQL = WSQL ||              'else TER.BDCARACTRIBUTARIATER ';
      WSQL = WSQL ||         'end as BDCARACTRIBUTARIATER, ';
      WSQL = WSQL ||'         SAI.BDMODELO, IIF(SAI.BDSERIE = '''', NULL, SAI.BDSERIE) BDSERIE, SAI.BDCHAVENFE, MPRO.BDQTDITEM, MPRO.BDVLRITEM, IIF(ICMS.BDCODCSTICMS IN (34,35,36,37,38,39,40,41,42,43),000,ICMS.BDCSTICMS) BDCSTICMS, MPRO.BDCODNATREC ';
      WSQL = WSQL ||'  FROM ( ';
      WSQL = WSQL ||'        SELECT * ';
      WSQL = WSQL ||'        FROM VEF_EMP_TMOVSAI SAI ';
      WSQL = WSQL ||'        WHERE '|| PRCODEMP ;
--      WSQL = WSQL ||'        AND   SAI.BDREFLAN = '||WREF;
      WSQL = WSQL ||'        AND   SAI.BDDATAEMISSAO BETWEEN '' '||PRDATAINICIAL||' '' AND '' '||PRDATAFIM||' '' ';
      IF (PRCODTER <> '') THEN
        WSQL = WSQL ||'      AND   '||PRCODTER;
      IF (PRDOCUMENTO <> '') THEN
        WSQL = WSQL ||'      AND   SAI.BDNUMDOCINI IN ('||PRDOCUMENTO||')';
      WSQL = WSQL ||'      ) SAI ';
      WSQL = WSQL ||'  JOIN TTERCEIRO_REF TER ON (TER.BDCODTER = SAI.BDCODTER AND TER.BDREFEMP = COALESCE( ';
      WSQL = WSQL ||                                                                                     ' (SELECT FIRST 1 BDREFEMP FROM TTERCEIRO_REF T ';
      WSQL = WSQL ||                                                                                     '  WHERE T.BDCODTER = TER.BDCODTER AND T.BDREFEMP <= SAI.BDREFLAN ';
      WSQL = WSQL ||                                                                                     '  ORDER BY T.BDCODTER DESC, T.BDREFEMP DESC), ';
      WSQL = WSQL ||                                                                                     ' (SELECT FIRST 1 RF2.BDREFEMP FROM TTERCEIRO_REF RF2 ';
      WSQL = WSQL ||                                                                                     ' WHERE RF2.BDCODTER = TER.BDCODTER ORDER BY RF2.BDCODTER, RF2.BDREFEMP) ';
      WSQL = WSQL ||                                                                                     ' ) ) ';
      WSQL = WSQL ||'  JOIN TCIDADE CID ON (CID.BDCODCID = TER.BDCODCID) ';
      WSQL = WSQL ||'  JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE) ';
      WSQL = WSQL ||'  JOIN VEF_EMP_TMOVPROSAI MPRO ON (MPRO.BDCODEMP = I.BDCODEMP AND MPRO.BDCHAVE = I.BDCHAVE AND MPRO.BDORDEM = I.BDORDEM) ';
      WSQL = WSQL ||'  JOIN TCADPRO_VINC PRO ON (PRO.BDCODEMP = MPRO.BDCODEMP AND PRO.BDCODPROD = MPRO.BDCODPROD) ';
      WSQL = WSQL ||'  LEFT OUTER JOIN TTIPO_SERVICO TT ON  (TT.BDCODTIPOSER = PRO.BDCODTIPOSER) ';
      WSQL = WSQL ||'  JOIN TEMPRESAS EMP ON (EMP.BDCODEMP = SAI.BDCODEMP) ';
      WSQL = WSQL ||'  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = MPRO.BDCODCSTICMS) ';
      wsql = WSQL ||'  LEFT OUTER JOIN VEF_BASE_TTAB_NATREC NATREC ON (NATREC.BDCODNATREC = MPRO.BDCODNATREC) ';
      WSQL = WSQL ||'  WHERE NOT EXISTS (SELECT FIRST 1 AUD.BDCODEMP FROM VEF_EMP_TAUDIMENDES AUD ';
      WSQL = WSQL ||'                    WHERE AUD.BDCODEMP = MPRO.BDCODEMP ';
      WSQL = WSQL ||'                    AND   AUD.BDCHAVE =  MPRO.BDCHAVE ';
      WSQL = WSQL ||'                    AND   AUD.BDORDEM = MPRO.BDORDEM ';
      WSQL = WSQL ||'                    AND   AUD.BDORDEMPRO = MPRO.BDORDEMPRO ';
      WSQL = WSQL ||'                    AND   AUD.BDMOVIMENTO = 1) ';
      WSQL = WSQL ||'  AND UPPER(EMP.BDIMENDES) = ''TRUE'' ';
      IF (PRCODNAT <> '') THEN
          WSQL = WSQL ||' AND '||PRCODNAT;
      IF (PRCODPROD <> '') THEN
         WSQL = WSQL ||'  AND '||PRCODPROD;
      WSQL = WSQL ||' ) A ';

      EXECUTE STATEMENT(WSQL);
     END

  IF (PRMOVREDZ = 'TRUE') THEN
     BEGIN
       WSQL = ' INSERT INTO VEF_EMP_TAUDIMENDES (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDSTATUS, BDMOVIMENTO, BDCODNCM, BDCODCEST,  BDCODUF, BDCODNATOPE, BDFINALIDADE, BDDATANOTA,  ';
       WSQL = WSQL ||'                           BDCODPROD, BDCODNAT, BDDOCUMENTO, BDCARACTRIBUTARIATER,BDCSTPISCOFINSSAI,BDALIQPIS,BDALIQCOFINS,BDREGREDZ,BDVLRNOTAREDZ,BDQTDITEM,BDVLRITEM, BDCSTICMS,BDBASEICMS) ';
       WSQL = WSQL ||' SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDORDEMVARCFOP,P.BDORDEM60I, 0 BDSTATUS, 2 /*REDZ*/, PRO.BDNCMPROD,PRO.BDCODCEST, MOV.BDCODUF, MOV.BDCODNAT, ';
       WSQL = WSQL ||' 0 BDFINALIDADE, MOV.BDDATAREDZ, P.BDCODPROD, MOV.BDCODNAT, MOV.BDNUMCUPINI, ';
       WSQL = WSQL ||' 8 BDCARACTRIBUTARIATER, NULL BDCODCSTPIS, NULL BDALIQ_PIS, NULL BDALIQ_COFINS, ''60I'', P.BDVALORUNITARIO, ';
       WSQL = WSQL ||' P.BDQUANTIDADE, P.BDVALORUNITARIO, IIF(ICMS.BDCODCSTICMS IN (34,35,36,37,38,39,40,41,42,43),000,ICMS.BDCSTICMS) BDCSTICMS,P.BDBASECALCICMS ';
       WSQL = WSQL ||' FROM ( ';
       WSQL = WSQL ||       ' SELECT MOV.*, CF.BDORDEMVARCFOP, CF.BDCODNAT, CF.BDCODTER, CID.BDCODUF ';
       WSQL = WSQL ||       ' FROM ( ';
       WSQL = WSQL ||             ' SELECT MOV.* ';
       WSQL = WSQL ||             ' FROM VEF_EMP_TREDZ MOV ';

       WSQL = WSQL ||'        WHERE '|| :PRCODEMP;
       WSQL = WSQL ||'        AND   MOV.BDDATAREDZ BETWEEN '' '||PRDATAINICIAL||' '' AND '' '||PRDATAFIM||' '' ';
--       IF (PRCODTER <> '') THEN
--         WSQL = WSQL ||'      AND   '||PRCODTER;
       IF (PRDOCUMENTO <> '') THEN
         WSQL = WSQL ||'      AND   MOV.BDNUMCUPINI IN ('||PRDOCUMENTO||')';
       WSQL = WSQL ||'             ) MOV ';
       WSQL = WSQL ||'        JOIN TEMPRESAS E ON (E.BDCODEMP = MOV.BDCODEMP) ';
       WSQL = WSQL ||'        JOIN VW_TEMPRESAS_REF_ATUAL REF ON (REF.BDCODEMP = MOV.BDCODEMP) ';
       WSQL = WSQL ||'        JOIN TCIDADE CID ON (CID.BDCODCID = REF.BDCODCID) ';
       WSQL = WSQL ||'        JOIN VW_VEF_BASE_TEMPPARFED EMP ON (EMP.BDCODEMP = MOV.BDCODEMP) ';
       WSQL = WSQL ||'        JOIN VEF_EMP_TREDZVARCFOP CF ON (CF.BDCODEMP = MOV.BDCODEMP AND CF.BDCHAVE = MOV.BDCHAVE AND CF.BDORDEMVARCFOP = ';
       WSQL = WSQL ||'        (SELECT FIRST 1 C.BDORDEMVARCFOP FROM VEF_EMP_TREDZVARCFOP C WHERE C.BDCODEMP = CF.BDCODEMP AND C.BDCHAVE = CF.BDCHAVE ORDER BY C.BDORDEMVARCFOP)) ';
       WSQL = WSQL ||'        WHERE UPPER(E.BDIMENDES) = ''TRUE'' ';
       WSQL = WSQL ||'        AND COALESCE(EMP.BDCODCONFICMSSPED,0) = 0 ';
       WSQL = WSQL ||'       ) MOV ';
       WSQL = WSQL ||' JOIN VEF_EMP_TREDZ60I P ON (P.BDCODEMP = MOV.BDCODEMP AND P.BDCHAVE = MOV.BDCHAVE) ';
       WSQL = WSQL ||' JOIN TCADPRO_VINC PRO ON (PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD) ';
       WSQL = WSQL ||' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = P.BDCODCSTICMS) ';
       WSQL = WSQL ||' WHERE NOT EXISTS(SELECT FIRST 1 AUD.BDCODEMP ';
       WSQL = WSQL ||'                  FROM VEF_EMP_TAUDIMENDES AUD ';
       WSQL = WSQL ||'                  WHERE AUD.BDCODEMP = MOV.BDCODEMP AND ';
       WSQL = WSQL ||'                        AUD.BDCHAVE = MOV.BDCHAVE AND ';
       WSQL = WSQL ||'                        AUD.BDORDEM = MOV.BDORDEMVARCFOP AND ';
       WSQL = WSQL ||'                        AUD.BDORDEMPRO = P.BDORDEM60I AND ';
       WSQL = WSQL ||'                        AUD.BDMOVIMENTO = 2) ';
       WSQL = WSQL ||' UNION ALL ';
--/*EMPRESA DO SPED - PERFIL A - C460/C470*/
       WSQL = WSQL ||' SELECT MOV.BDCODEMP, MOV.BDCHAVE,  D.BDORDEMDOCECF, I.BDORDEMITEM, 0 BDSTATUS, 2 /*REDZ*/,PRO.BDNCMPROD,PRO.BDCODCEST, MOV.BDCODUF, I.BDCODNAT, ';
       WSQL = WSQL ||'        0 BDFINALIDADE, MOV.BDDATAREDZ, I.BDCODPROD, I.BDCODNAT, D.BDNUMDOCCOO, ';
       WSQL = WSQL ||'        8 BDCARACTRIBUTARIATER, NULL BDCODCSTPIS, NULL BDALIQ_PIS, NULL BDALIQ_COFINS, ''C470'', I.BDVLRTOTPRO,  ';
       WSQL = WSQL ||'        I.BDQTDITEM, I.BDVLRTOTPRO, IIF(ICMS.BDCODCSTICMS IN (34,35,36,37,38,39,40,41,42,43),000,ICMS.BDCSTICMS) BDCSTICMS,0  ';
       WSQL = WSQL ||' FROM ( ';
       WSQL = WSQL ||       ' SELECT MOV.*,EMP.BDPERFILSPED, CID.BDCODUF ';
       WSQL = WSQL ||       ' FROM ( ';
       WSQL = WSQL ||             ' SELECT MOV.* ';
       WSQL = WSQL ||             ' FROM VEF_EMP_TREDZ MOV ';

       WSQL = WSQL ||'        WHERE '|| :PRCODEMP;
       WSQL = WSQL ||'        AND   MOV.BDDATAREDZ BETWEEN '' '||PRDATAINICIAL||' '' AND '' '||PRDATAFIM||' '' ';
--       IF (PRCODTER <> '') THEN
--         WSQL = WSQL ||'      AND   '||PRCODTER;
       IF (PRDOCUMENTO <> '') THEN
         WSQL = WSQL ||'      AND   MOV.BDNUMCUPINI IN ('||PRDOCUMENTO||')';
       WSQL = WSQL ||'             ) MOV ';
       WSQL = WSQL ||'        JOIN TEMPRESAS E ON (E.BDCODEMP = MOV.BDCODEMP) ';
       WSQL = WSQL ||'        JOIN VW_TEMPRESAS_REF_ATUAL REF ON (REF.BDCODEMP = MOV.BDCODEMP) ';
       WSQL = WSQL ||'        JOIN TCIDADE CID ON (CID.BDCODCID = REF.BDCODCID) ';
       WSQL = WSQL ||'        JOIN VW_VEF_BASE_TEMPPARFED EMP ON (EMP.BDCODEMP = MOV.BDCODEMP) ';
       WSQL = WSQL ||'        WHERE (COALESCE(EMP.BDCODCONFICMSSPED,0) > 0 ';
       WSQL = WSQL ||'        AND EMP.BDPERFILSPED = 0) '; /*PERFIL A*/
       WSQL = WSQL ||'        AND UPPER(E.BDIMENDES) = ''TRUE'' ';
       WSQL = WSQL ||'       ) MOV ';
       WSQL = WSQL ||' JOIN VEF_EMP_TDOCECF D ON (D.BDCODEMP = MOV.BDCODEMP AND D.BDCHAVE = MOV.BDCHAVE) ';
       WSQL = WSQL ||' JOIN VEF_EMP_TITEMDOCECF I ON (I.BDCODEMP = D.BDCODEMP AND I.BDCHAVE = D.BDCHAVE AND I.BDORDEMDOCECF = D.BDORDEMDOCECF) ';
       WSQL = WSQL ||' JOIN TCADPRO_VINC PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCODPROD = I.BDCODPROD) ';
       WSQL = WSQL ||' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = I.BDCODCSTICMS) ';
       WSQL = WSQL ||' WHERE NOT EXISTS(SELECT FIRST 1 AUD.BDCODEMP ';
       WSQL = WSQL ||'                  FROM VEF_EMP_TAUDIMENDES AUD ';
       WSQL = WSQL ||'                  WHERE AUD.BDCODEMP = MOV.BDCODEMP AND ';
       WSQL = WSQL ||'                        AUD.BDCHAVE = MOV.BDCHAVE AND ';
       WSQL = WSQL ||'                        AUD.BDORDEM = D.BDORDEMDOCECF AND ';
       WSQL = WSQL ||'                        AUD.BDORDEMPRO = I.BDORDEMITEM AND ';
       WSQL = WSQL ||'                        AUD.BDMOVIMENTO = 2) ';
--       IF (PRCODTER <> '') THEN
--         WSQL = WSQL ||'      AND   (D.'|| SUBSTRING(PRCODTER FROM 1 FOR CHAR_LENGTH(PRCODTER)) ||')';

       WSQL = WSQL ||' UNION ALL ';
--/*EMPRESA DO SPED - PERFIL B - C425*/
       WSQL = WSQL ||' SELECT MOV.BDCODEMP, MOV.BDCHAVE,  I.BDORDEMTOT, I.BDORDEMC425, 0 BDSTATUS, 2 /*REDZ*/,PRO.BDNCMPROD,PRO.BDCODCEST, MOV.BDCODUF, I.BDCODNAT, ';
       WSQL = WSQL ||'        0 BDFINALIDADE, MOV.BDDATAREDZ, I.BDCODPROD, I.BDCODNAT, MOV.BDNUMCUPINI, ';
       WSQL = WSQL ||'        8 BDCARACTRIBUTARIATER,I.BDCODCSTPIS, I.BDALIQ_PIS, I.BDALIQ_COFINS, ''C425'', I.BDVLRACU,  ';
       WSQL = WSQL ||'        I.BDQTDACU, I.BDVLRACU, IIF(ICMS.BDCODCSTICMS IN (34,35,36,37,38,39,40,41,42,43),000,ICMS.BDCSTICMS) BDCSTICMS,0    ';
       WSQL = WSQL ||' FROM ( ';
       WSQL = WSQL ||       ' SELECT MOV.*,EMP.BDPERFILSPED, CID.BDCODUF ';
       WSQL = WSQL ||       ' FROM ( ';
       WSQL = WSQL ||             ' SELECT MOV.* ';
       WSQL = WSQL ||             ' FROM VEF_EMP_TREDZ MOV ';

       WSQL = WSQL ||'        WHERE '|| :PRCODEMP;
       WSQL = WSQL ||'        AND   MOV.BDDATAREDZ BETWEEN '' '||PRDATAINICIAL||' '' AND '' '||PRDATAFIM||' '' ';
--       IF (PRCODTER <> '') THEN
--         WSQL = WSQL ||'      AND   '||PRCODTER;
       IF (PRDOCUMENTO <> '') THEN
         WSQL = WSQL ||'      AND   MOV.BDNUMCUPINI IN ('||PRDOCUMENTO||')';
       WSQL = WSQL ||'             ) MOV ';
       WSQL = WSQL ||'        JOIN TEMPRESAS E ON (E.BDCODEMP = MOV.BDCODEMP) ';
       WSQL = WSQL ||'        JOIN VW_TEMPRESAS_REF_ATUAL REF ON (REF.BDCODEMP = MOV.BDCODEMP) ';
       WSQL = WSQL ||'        JOIN TCIDADE CID ON (CID.BDCODCID = REF.BDCODCID) ';
       WSQL = WSQL ||'        JOIN VW_VEF_BASE_TEMPPARFED EMP ON (EMP.BDCODEMP = MOV.BDCODEMP) ';
       WSQL = WSQL ||'        WHERE COALESCE(EMP.BDCODCONFICMSSPED,0) > 0 ';
       WSQL = WSQL ||'        AND EMP.BDPERFILSPED = 1 /*PERFIL B*/  ';
       --WSQL = WSQL ||'        AND EMP.BDGERAC490 = ''FALSE'' ';
       WSQL = WSQL ||'        AND UPPER(E.BDIMENDES) = ''TRUE'' ';
       WSQL = WSQL ||'       ) MOV ';
       WSQL = WSQL ||' JOIN VEF_EMP_TREDZC425 I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE) ';
       WSQL = WSQL ||' JOIN TCADPRO_VINC PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCODPROD = I.BDCODPROD) ';
       WSQL = WSQL ||' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = I.BDCODCSTICMS) ';
       WSQL = WSQL ||' WHERE NOT EXISTS(SELECT FIRST 1 AUD.BDCODEMP ';
       WSQL = WSQL ||'                  FROM VEF_EMP_TAUDIMENDES AUD ';
       WSQL = WSQL ||'                  WHERE AUD.BDCODEMP = MOV.BDCODEMP AND ';
       WSQL = WSQL ||'                        AUD.BDCHAVE = MOV.BDCHAVE AND ';
       WSQL = WSQL ||'                        AUD.BDORDEM = I.BDORDEMTOT AND ';
       WSQL = WSQL ||'                        AUD.BDORDEMPRO = I.BDORDEMC425 AND ';
       WSQL = WSQL ||'                        AUD.BDMOVIMENTO = 2) ';
       WSQL = WSQL ||' UNION ALL ';
--/*EMPRESA DO SPED - PERFIL B - C425 ISS*/
       WSQL = WSQL ||' SELECT MOV.BDCODEMP, MOV.BDCHAVE,  I.BDORDEMICMS, I.BDORDEMC425, 0 BDSTATUS, 2 /*REDZ*/,PRO.BDNCMPROD,PRO.BDCODCEST, MOV.BDCODUF, I.BDCODNAT, ';
       WSQL = WSQL ||'        0 BDFINALIDADE, MOV.BDDATAREDZ, I.BDCODPROD, I.BDCODNAT, MOV.BDNUMCUPINI, ';
       WSQL = WSQL ||'        8 BDCARACTRIBUTARIATER,I.BDCODCSTPIS, I.BDALIQ_PIS, I.BDALIQ_COFINS, ''C425'', I.BDVLRACU,  ';
       WSQL = WSQL ||'        I.BDQTDACU, I.BDVLRACU, IIF(ICMS.BDCODCSTICMS IN (34,35,36,37,38,39,40,41,42,43),000,ICMS.BDCSTICMS) BDCSTICMS,0    ';
       WSQL = WSQL ||' FROM ( ';
       WSQL = WSQL ||       ' SELECT MOV.*,EMP.BDPERFILSPED, CID.BDCODUF ';
       WSQL = WSQL ||       ' FROM ( ';
       WSQL = WSQL ||             ' SELECT MOV.* ';
       WSQL = WSQL ||             ' FROM VEF_EMP_TREDZ MOV ';

       WSQL = WSQL ||'        WHERE '|| :PRCODEMP;
       WSQL = WSQL ||'        AND   MOV.BDDATAREDZ BETWEEN '' '||PRDATAINICIAL||' '' AND '' '||PRDATAFIM||' '' ';
       IF (PRDOCUMENTO <> '') THEN
         WSQL = WSQL ||'      AND   MOV.BDNUMCUPINI IN ('||PRDOCUMENTO||')';
       WSQL = WSQL ||'             ) MOV ';
       WSQL = WSQL ||'        JOIN TEMPRESAS E ON (E.BDCODEMP = MOV.BDCODEMP) ';
       WSQL = WSQL ||'        JOIN VW_TEMPRESAS_REF_ATUAL REF ON (REF.BDCODEMP = MOV.BDCODEMP) ';
       WSQL = WSQL ||'        JOIN TCIDADE CID ON (CID.BDCODCID = REF.BDCODCID) ';
       WSQL = WSQL ||'        JOIN VW_VEF_BASE_TEMPPARFED EMP ON (EMP.BDCODEMP = MOV.BDCODEMP) ';
       WSQL = WSQL ||'        WHERE COALESCE(EMP.BDCODCONFICMSSPED,0) > 0 ';
       WSQL = WSQL ||'        AND EMP.BDPERFILSPED = 1 /*PERFIL B*/  ';
       --WSQL = WSQL ||'        AND EMP.BDGERAC490 = ''FALSE'' ';
       WSQL = WSQL ||'        AND UPPER(E.BDIMENDES) = ''TRUE'' ';
       WSQL = WSQL ||'       ) MOV ';
       WSQL = WSQL ||' JOIN VEF_EMP_TREDZC425ALIQ I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE) ';
       WSQL = WSQL ||' JOIN TCADPRO_VINC PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCODPROD = I.BDCODPROD) ';
       WSQL = WSQL ||' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = I.BDCODCSTICMS) ';
       WSQL = WSQL ||' WHERE NOT EXISTS(SELECT FIRST 1 AUD.BDCODEMP ';
       WSQL = WSQL ||'                  FROM VEF_EMP_TAUDIMENDES AUD ';
       WSQL = WSQL ||'                  WHERE AUD.BDCODEMP = MOV.BDCODEMP AND ';
       WSQL = WSQL ||'                        AUD.BDCHAVE = MOV.BDCHAVE AND ';
       WSQL = WSQL ||'                        AUD.BDORDEM = I.BDORDEMICMS AND ';
       WSQL = WSQL ||'                        AUD.BDORDEMPRO = I.BDORDEMC425 AND ';
       WSQL = WSQL ||'                        AUD.BDMOVIMENTO = 2) ';
--       IF (PRCODTER <> '') THEN
--         WSQL = WSQL ||'      AND   CF.'|| SUBSTRING(PRCODTER FROM 1 FOR CHAR_LENGTH(PRCODTER));
       EXECUTE STATEMENT(WSQL);
     END

  IF ((:PRMOVSAI = 'TRUE') OR (:PRMOVENT = 'TRUE')) THEN
    BEGIN
      WSQL =        'UPDATE VEF_EMP_TAUDIMENDES AUD ';
      WSQL = WSQL ||'SET AUD.BDCARACTRIBUTARIATER = (SELECT FIRST 1 case when coalesce(TER.BDCARACTRIBUTARIATER, -1) >= 5 then TER.BDCARACTRIBUTARIATER + 1 ';
      WSQL = WSQL ||                                                 'when coalesce(TER.BDCARACTRIBUTARIATER, -1) = -1 and position(''/'' in TER.BDCGCTER) = 0 and coalesce(TER.BDPRURALTER, ''FALSE'') = ''TRUE'' then 6 ';
      WSQL = WSQL ||                                                 'when coalesce(TER.BDCARACTRIBUTARIATER, -1) = -1 and position(''/'' in TER.BDCGCTER) = 0 and coalesce(TER.BDPRURALTER, ''FALSE'') = ''FALSE'' then 8 ';
      WSQL = WSQL ||                                                 'else TER.BDCARACTRIBUTARIATER ';
      WSQL = WSQL ||                                               'end as BDCARACTRIBUTARIATER ';
      WSQL = WSQL ||                                'FROM TTERCEIRO_REF TER ';
      WSQL = WSQL ||                                'WHERE (TER.BDCODTER = AUD.BDCODTER AND TER.BDREFEMP = COALESCE((SELECT FIRST 1 BDREFEMP FROM TTERCEIRO_REF T ';
      WSQL = WSQL ||                                                                                                'WHERE T.BDCODTER = TER.BDCODTER AND T.BDREFEMP <= (SUBSTRING(AUD.BDDATANOTA FROM 1 FOR 4)||SUBSTRING(AUD.BDDATANOTA FROM 6 FOR 2)) ';
      WSQL = WSQL ||                                                                                                'ORDER BY T.BDCODTER DESC, T.BDREFEMP DESC), ';
      WSQL = WSQL ||                                                                                                '(SELECT FIRST 1 RF2.BDREFEMP FROM TTERCEIRO_REF RF2 ';
      WSQL = WSQL ||                                                                                                 'WHERE RF2.BDCODTER = TER.BDCODTER ORDER BY RF2.BDCODTER, RF2.BDREFEMP)))) ';
      WSQL = WSQL ||'WHERE '|| :PRCODEMP;
      WSQL = WSQL ||' AND AUD.BDDATANOTA BETWEEN '' '||PRDATAINICIAL||' '' AND '' '||PRDATAFIM||' '' ';

      IF ((PRMOVSAI = 'TRUE') AND (PRMOVENT = 'TRUE')) THEN
         WSQL = WSQL ||' AND AUD.BDMOVIMENTO IN (0,1) ';
      ELSE IF (PRMOVSAI = 'TRUE') THEN
         WSQL = WSQL ||' AND AUD.BDMOVIMENTO = 1 ';
      ELSE IF (PRMOVENT = 'TRUE') THEN
         WSQL = WSQL ||' AND AUD.BDMOVIMENTO = 0 ';

      EXECUTE STATEMENT(WSQL);
    END
END^

create or alter procedure SP_AUDITANOTAS_IMENDES_UPDT (
    PRCODEMP varchar(30000),
    PRDATAINI date,
    PRDATAFIM date,
    PRSESSAO integer)
as
declare variable WSQL varchar(5000);
declare variable WCHAVE integer;
declare variable WMOVIMENTO integer;
declare variable WSTATUS integer;
declare variable WCODEMP integer;
declare variable WCODSTATUS integer;
declare variable WDESCSTATUS varchar(2500);
declare variable WCODSTATUSATUAL integer;
declare variable WDESCSTATUSATUAL varchar(100);
BEGIN

   /****ATENÇÃO.... Se for mudar algo nos valores dos campos da tabela, faça isso aqui, antes de mexer nos status****/
    WSQL =         ' UPDATE TMP_VEF_EMP_RETORNOIMENDES_TEMP T';
    WSQL = WSQL || ' SET T.BDBCPIS = 0, T.BDVLRPIS = 0';
    WSQL = WSQL || ' WHERE T.BDCSTPIS IN (''49'', ''99'') AND T.BDALIQPIS = 0 AND ';
    WSQL = WSQL || '       T.BDSESSAO = ' || :PRSESSAO;
    EXECUTE STATEMENT(WSQL);

    WSQL =         ' UPDATE TMP_VEF_EMP_RETORNOIMENDES_TEMP T';
    WSQL = WSQL || ' SET T.BDBCCOFINS = 0, T.BDVLRCOFINS = 0';
    WSQL = WSQL || ' WHERE T.BDCSTCOF IN (''49'', ''99'') AND T.BDALIQCOFINS = 0 AND ';
    WSQL = WSQL || '       T.BDSESSAO = ' || :PRSESSAO;

    EXECUTE STATEMENT(WSQL);

    WSQL =         ' UPDATE TMP_VEF_EMP_RETORNOIMENDES_TEMP T';
    WSQL = WSQL || ' SET T.BDBCPIS = 0,';
    WSQL = WSQL || '     T.BDVLRPIS = 0';
    WSQL = WSQL || ' WHERE T.BDCSTPIS = ''05'' AND';
    WSQL = WSQL || '       T.BDCODNATOPE IN (''5102000'', ''5106000'', ''5110000'', ''5112000'', ''5114000'', ''5115000'', ''5117000'', ''5119000'', ''5120000'', ''5123000'',';
    WSQL = WSQL || '                         ''5403000'', ''5405000'', ''5406000'', ''5104000'', ''5407000'', ''6102000'', ''6104000'', ''6106000'', ''6110000'', ''6112000'',';
    WSQL = WSQL || '                         ''6114000'', ''6115000'', ''6117000'', ''6119000'', ''6120000'', ''6123000'', ''6403000'', ''6405000'', ''6407000'', ''6406000'') AND ';
    WSQL = WSQL || '       T.BDSESSAO = ' || :PRSESSAO;

    EXECUTE STATEMENT(WSQL);

    WSQL =         ' UPDATE TMP_VEF_EMP_RETORNOIMENDES_TEMP T';
    WSQL = WSQL || ' SET T.BDBCCOFINS = 0,';
    WSQL = WSQL || '     T.BDVLRCOFINS = 0';
    WSQL = WSQL || ' WHERE T.BDCSTCOF = ''05'' AND';
    WSQL = WSQL || '       T.BDCODNATOPE IN (''5102000'', ''5106000'', ''5110000'', ''5112000'', ''5114000'', ''5115000'', ''5117000'', ''5119000'', ''5120000'', ''5123000'',';
    WSQL = WSQL || '                         ''5403000'', ''5405000'', ''5406000'', ''5104000'', ''5407000'', ''6102000'', ''6104000'', ''6106000'', ''6110000'', ''6112000'',';
    WSQL = WSQL || '                         ''6114000'', ''6115000'', ''6117000'', ''6119000'', ''6120000'', ''6123000'', ''6403000'', ''6405000'', ''6407000'', ''6406000'') AND ';
    WSQL = WSQL || '       T.BDSESSAO = ' || :PRSESSAO;

    EXECUTE STATEMENT(WSQL);

    WSQL =         ' UPDATE TMP_VEF_EMP_RETORNOIMENDES_TEMP T';
    WSQL = WSQL || ' SET T.BDBCPIS = 0, T.BDVLRPIS = 0';
    WSQL = WSQL || ' WHERE T.BDCSTPIS in (''98'') AND T.BDALIQPIS = 0 AND ';
    WSQL = WSQL || '       T.BDSESSAO = ' || :PRSESSAO;

    EXECUTE STATEMENT(WSQL);

    WSQL =         ' UPDATE TMP_VEF_EMP_RETORNOIMENDES_TEMP T';
    WSQL = WSQL || ' SET T.BDBCCOFINS = 0, T.BDVLRCOFINS = 0';
    WSQL = WSQL || ' WHERE T.BDCSTCOF in (''98'') AND T.BDALIQCOFINS = 0 AND';   :
    WSQL = WSQL || '       T.BDSESSAO = ' || PRSESSAO;

    EXECUTE STATEMENT(WSQL);

    /*Atualizando a data de retorno*/
    WSQL = '       UPDATE VEF_EMP_TAUDIMENDES AUD SET ';
    WSQL = WSQL || '     AUD.BDDATARETORNO = (SELECT FIRST 1 RO.BDDATARETORNO FROM TMP_VEF_EMP_RETORNOIMENDES_TEMP RO ';
--    WSQL = WSQL || '         WHERE RO.BDCODEMP = AUD.BDCODEMP ';
--    WSQL = WSQL || '         AND   RO.BDDATANOTA = AUD.BDDATANOTA ';
--    WSQL = WSQL || '         AND   RO.BDMOVIMENTO = AUD.BDMOVIMENTO ';
--    WSQL = WSQL || '         AND   COALESCE(RO.BDCODTER,0) = COALESCE(AUD.BDCODTER,0) ';
--    WSQL = WSQL || '         AND   RO.BDCODNATOPE = AUD.BDCODNATOPE ';
--    WSQL = WSQL || '         AND   RO.BDDOCUMENTO = AUD.BDDOCUMENTO ';
--    WSQL = WSQL || '         AND   RO.BDCODPROD = AUD.BDCODPROD ';
--    WSQL = WSQL || '         AND   RO.BDCOMPARATIVO = 1  ';
--    WSQL = WSQL || '         AND   RO.BDCHAVE  = AUD.BDCHAVE ';
--    WSQL = WSQL || '         AND   RO.BDORDEM  = AUD.BDORDEM ';
--    WSQL = WSQL || '         AND   RO.BDORDEMPRO = AUD.BDORDEMPRO ';
--    WSQL = WSQL || '         AND   RO.BDSESSAO = '|| :PRSESSAO ;
    WSQL = WSQL || '         WHERE  ';                            
    WSQL = WSQL || '               RO.BDSESSAO = '|| :PRSESSAO ;
    WSQL = WSQL || '         AND   RO.BDCODEMP = AUD.BDCODEMP ';
    WSQL = WSQL || '         AND   RO.BDDATANOTA = AUD.BDDATANOTA ';
    WSQL = WSQL || '         AND   RO.BDMOVIMENTO = AUD.BDMOVIMENTO ';                   
    WSQL = WSQL || '         AND   RO.BDCODNATOPE = AUD.BDCODNATOPE ';                       
    WSQL = WSQL || '         AND   RO.BDDOCUMENTO = AUD.BDDOCUMENTO ';                     
    WSQL = WSQL || '         AND   RO.BDCODPROD = AUD.BDCODPROD ';                       
    WSQL = WSQL || '         AND   RO.BDCHAVE  = AUD.BDCHAVE ';                   
    WSQL = WSQL || '         AND   RO.BDORDEM  = AUD.BDORDEM ';         
    WSQL = WSQL || '         AND   RO.BDORDEMPRO = AUD.BDORDEMPRO ';
    WSQL = WSQL || '         AND   COALESCE(RO.BDCODTER,0) = COALESCE(AUD.BDCODTER,0) ';
    WSQL = WSQL || '         AND   RO.BDCOMPARATIVO = 1  ';
    WSQL = WSQL || '         ), ';
    WSQL = WSQL || '     AUD.BDHORARETORNO = (SELECT FIRST 1 RO.BDHORARETORNO FROM TMP_VEF_EMP_RETORNOIMENDES_TEMP RO ';
    WSQL = WSQL || '         WHERE  ';                            
    WSQL = WSQL || '               RO.BDSESSAO = '|| :PRSESSAO ;
    WSQL = WSQL || '         AND   RO.BDCODEMP = AUD.BDCODEMP ';
    WSQL = WSQL || '         AND   RO.BDDATANOTA = AUD.BDDATANOTA ';
    WSQL = WSQL || '         AND   RO.BDMOVIMENTO = AUD.BDMOVIMENTO ';                   
    WSQL = WSQL || '         AND   RO.BDCODNATOPE = AUD.BDCODNATOPE ';                       
    WSQL = WSQL || '         AND   RO.BDDOCUMENTO = AUD.BDDOCUMENTO ';                     
    WSQL = WSQL || '         AND   RO.BDCODPROD = AUD.BDCODPROD ';                       
    WSQL = WSQL || '         AND   RO.BDCHAVE  = AUD.BDCHAVE ';                   
    WSQL = WSQL || '         AND   RO.BDORDEM  = AUD.BDORDEM ';         
    WSQL = WSQL || '         AND   RO.BDORDEMPRO = AUD.BDORDEMPRO ';
    WSQL = WSQL || '         AND   COALESCE(RO.BDCODTER,0) = COALESCE(AUD.BDCODTER,0) ';
    WSQL = WSQL || '         AND   RO.BDCOMPARATIVO = 1  ';
    WSQL = WSQL || '         ) ';
    WSQL = WSQL || ' WHERE '||:PRCODEMP||' AND '||'AUD.BDDATANOTA BETWEEN '''|| :PRDATAINI ||''' AND '''|| :PRDATAFIM ||'''';
    WSQL = WSQL || ' AND AUD.BDSTATUS <> 6 '; /*CONFERIDO MANUALMENTE*/
    WSQL = WSQL || ' AND AUD.BDSTATUS <> 7 '; /*CONFERIDO AUTOMATICAMENTE*/

    EXECUTE STATEMENT(WSQL);

    /*Atualizando a data de envio se não houver*/
    WSQL = '       UPDATE VEF_EMP_TAUDIMENDES AUD SET ';
    WSQL = WSQL || '     AUD.BDDATAENVIO = (SELECT FIRST 1 RO.BDDATARETORNO FROM TMP_VEF_EMP_RETORNOIMENDES_TEMP RO ';
    WSQL = WSQL || '         WHERE  ';                            
    WSQL = WSQL || '               RO.BDSESSAO = '|| :PRSESSAO ;
    WSQL = WSQL || '         AND   RO.BDCODEMP = AUD.BDCODEMP ';
    WSQL = WSQL || '         AND   RO.BDDATANOTA = AUD.BDDATANOTA ';
    WSQL = WSQL || '         AND   RO.BDMOVIMENTO = AUD.BDMOVIMENTO ';                   
    WSQL = WSQL || '         AND   RO.BDCODNATOPE = AUD.BDCODNATOPE ';                       
    WSQL = WSQL || '         AND   RO.BDDOCUMENTO = AUD.BDDOCUMENTO ';                     
    WSQL = WSQL || '         AND   RO.BDCODPROD = AUD.BDCODPROD ';                       
    WSQL = WSQL || '         AND   RO.BDCHAVE  = AUD.BDCHAVE ';                   
    WSQL = WSQL || '         AND   RO.BDORDEM  = AUD.BDORDEM ';         
    WSQL = WSQL || '         AND   RO.BDORDEMPRO = AUD.BDORDEMPRO ';
    WSQL = WSQL || '         AND   COALESCE(RO.BDCODTER,0) = COALESCE(AUD.BDCODTER,0) ';
    WSQL = WSQL || '         AND   RO.BDCOMPARATIVO = 1  ';
    WSQL = WSQL || '         ), ';
    WSQL = WSQL || '     AUD.BDHORAENVIO = (SELECT FIRST 1 RO.BDHORARETORNO FROM TMP_VEF_EMP_RETORNOIMENDES_TEMP RO ';
    WSQL = WSQL || '         WHERE  ';                            
    WSQL = WSQL || '               RO.BDSESSAO = '|| :PRSESSAO ;
    WSQL = WSQL || '         AND   RO.BDCODEMP = AUD.BDCODEMP ';
    WSQL = WSQL || '         AND   RO.BDDATANOTA = AUD.BDDATANOTA ';
    WSQL = WSQL || '         AND   RO.BDMOVIMENTO = AUD.BDMOVIMENTO ';                   
    WSQL = WSQL || '         AND   RO.BDCODNATOPE = AUD.BDCODNATOPE ';                       
    WSQL = WSQL || '         AND   RO.BDDOCUMENTO = AUD.BDDOCUMENTO ';                     
    WSQL = WSQL || '         AND   RO.BDCODPROD = AUD.BDCODPROD ';                       
    WSQL = WSQL || '         AND   RO.BDCHAVE  = AUD.BDCHAVE ';                   
    WSQL = WSQL || '         AND   RO.BDORDEM  = AUD.BDORDEM ';         
    WSQL = WSQL || '         AND   RO.BDORDEMPRO = AUD.BDORDEMPRO ';
    WSQL = WSQL || '         AND   COALESCE(RO.BDCODTER,0) = COALESCE(AUD.BDCODTER,0) ';
    WSQL = WSQL || '         AND   RO.BDCOMPARATIVO = 1  ';
    WSQL = WSQL || '         ) ';
    WSQL = WSQL || ' WHERE '||:PRCODEMP||' AND '||'AUD.BDDATANOTA BETWEEN '''|| :PRDATAINI ||''' AND '''|| :PRDATAFIM ||'''';
    WSQL = WSQL || ' AND AUD.BDSTATUS <> 6 AND (AUD.BDDATAENVIO IS NULL) AND (AUD.BDHORAENVIO IS NULL)'; /*CONFERIDO MANUALMENTE*/
    WSQL = WSQL || ' AND AUD.BDSTATUS <> 7 AND (AUD.BDDATAENVIO IS NULL) AND (AUD.BDHORAENVIO IS NULL)'; /*CONFERIDO AUTOMATICAMENTE*/

    EXECUTE STATEMENT(WSQL);

    /*Tag PrcDifer é m caso específico, caso ela esteja diferente, o cliente deve validar ela*/
    WSQL =         ' UPDATE VEF_EMP_TAUDIMENDES AUD SET ';
    WSQL = WSQL || ' AUD.BDSTATUS = 5 ';--Retorno, mas possue um campo específico
    WSQL = WSQL || ' WHERE '||:PRCODEMP||' AND '||'AUD.BDDATANOTA BETWEEN '''|| :PRDATAINI ||''' AND '''|| :PRDATAFIM ||'''';
    WSQL = WSQL || ' AND AUD.BDSTATUS <> 6 '; /*CONFERIDO MANUALMENTE*/
    WSQL = WSQL || ' AND AUD.BDSTATUS <> 7 '; /*CONFERIDO AUTOMATICAMENTE*/
    WSQL = WSQL || ' AND EXISTS ( ';
    WSQL = WSQL || ' SELECT FIRST 1 RO.BDCODEMP ';
    WSQL = WSQL || ' FROM TMP_VEF_EMP_RETORNOIMENDES_TEMP RO ';
    WSQL = WSQL || ' JOIN TMP_VEF_EMP_RETORNOIMENDES_TEMP RA ON (RA.BDCODEMP = RO.BDCODEMP AND RA.BDDATANOTA = RO.BDDATANOTA AND RA.BDMOVIMENTO = RO.BDMOVIMENTO ';
    WSQL = WSQL || '                                                     AND COALESCE(RA.BDCODTER,0) = COALESCE(RO.BDCODTER,0) AND RA.BDCODNATOPE = RO.BDCODNATOPE AND RA.BDDOCUMENTO = RO.BDDOCUMENTO ';
    WSQL = WSQL || '                                                     AND RA.BDCODPROD = RO.BDCODPROD AND RO.BDCHAVE  = RA.BDCHAVE AND RO.BDORDEM = RA.BDORDEM ';
    WSQL = WSQL || '                                                     AND RO.BDORDEMPRO = RA.BDORDEMPRO  AND RA.BDSESSAO = '|| :PRSESSAO ||' AND RA.bdcomparativo = 1 /*AUD*/) ';
    WSQL = WSQL || '         WHERE RO.BDCODEMP = AUD.BDCODEMP AND RO.BDDATANOTA = AUD.BDDATANOTA AND   RO.BDMOVIMENTO = AUD.BDMOVIMENTO ';
    WSQL = WSQL || '         AND   COALESCE(RO.BDCODTER,0) = COALESCE(AUD.BDCODTER,0) AND   RO.BDCODNATOPE = AUD.BDCODNATOPE AND   RO.BDDOCUMENTO = AUD.BDDOCUMENTO ';
    WSQL = WSQL || '         AND   RO.BDCODPROD = AUD.BDCODPROD AND   RO.BDCOMPARATIVO = 0 /*ORI*/ AND   RA.BDPERCDIFER > 0  AND   RO.BDCHAVE  = AUD.BDCHAVE';
    WSQL = WSQL || '         AND   RO.BDORDEM  = AUD.BDORDEM AND   RO.BDORDEMPRO = AUD.BDORDEMPRO ';
    WSQL = WSQL || '         AND   RO.BDSESSAO = '|| :PRSESSAO ;
    WSQL = WSQL || '         ); ';


    EXECUTE STATEMENT(WSQL);

            /*Retornou com sucesso*/
    WSQL =         ' UPDATE VEF_EMP_TAUDIMENDES AUD SET ';
    WSQL = WSQL || ' AUD.BDSTATUS = 2  '; --Retornou com sucesso
    WSQL = WSQL || ' WHERE '||:PRCODEMP||' AND '||'AUD.BDDATANOTA BETWEEN '''|| :PRDATAINI ||''' AND '''|| :PRDATAFIM ||'''';
    WSQL = WSQL || ' AND AUD.BDSTATUS <> 6 '; /*CONFERIDO MANUALMENTE*/
    WSQL = WSQL || ' AND AUD.BDSTATUS <> 7 '; /*CONFERIDO AUTOMATICAMENTE*/
    WSQL = WSQL || ' AND EXISTS ( ';
    WSQL = WSQL || '         SELECT FIRST 1 RO.BDCODEMP ';
    WSQL = WSQL || '         FROM TMP_VEF_EMP_RETORNOIMENDES_TEMP RO ';
    WSQL = WSQL || '         JOIN TMP_VEF_EMP_RETORNOIMENDES_TEMP RA ON (RA.BDCODEMP = RO.BDCODEMP AND RA.BDDATANOTA = RO.BDDATANOTA AND RA.BDMOVIMENTO = RO.BDMOVIMENTO ';
    WSQL = WSQL ||                                                    ' AND COALESCE(RA.BDCODTER,0) = COALESCE(RO.BDCODTER,0) AND RA.BDCODNATOPE = RO.BDCODNATOPE AND RA.BDDOCUMENTO = RO.BDDOCUMENTO ';
    WSQL = WSQL ||                                                    ' AND RA.BDCODPROD = RO.BDCODPROD AND RO.BDCHAVE  = RA.BDCHAVE AND RO.BDORDEM = RA.BDORDEM ';
    WSQL = WSQL ||                                                    ' AND RO.BDORDEMPRO = RA.BDORDEMPRO AND RA.BDSESSAO = '|| :PRSESSAO ||' AND RA.bdcomparativo = 1 /*AUD*/) ';
    WSQL = WSQL || '         WHERE RO.BDCODEMP = AUD.BDCODEMP AND   RO.BDDATANOTA = AUD.BDDATANOTA AND   RO.BDMOVIMENTO = AUD.BDMOVIMENTO AND   COALESCE(RO.BDCODTER,0) = COALESCE(AUD.BDCODTER,0) ';
    WSQL = WSQL || '         AND   RO.BDCODNATOPE = AUD.BDCODNATOPE AND   RO.BDDOCUMENTO = AUD.BDDOCUMENTO AND   RO.BDCODPROD = AUD.BDCODPROD AND   RO.BDCHAVE  = AUD.BDCHAVE ';
    WSQL = WSQL || '         AND   RO.BDORDEM  = AUD.BDORDEM AND   RO.BDORDEMPRO = AUD.BDORDEMPRO AND   RO.BDCOMPARATIVO = 1';
    WSQL = WSQL || '         AND   RO.BDSESSAO = '|| :PRSESSAO ;
    WSQL = WSQL || '         AND   (  COALESCE(RO.bdcsticms,0) =  COALESCE(RA.bdcsticms,0) OR   COALESCE(RO.BDALIQICMS,0) = COALESCE(RA.BDALIQICMS,0) OR COALESCE(RO.BDREDBCICMS,0) = COALESCE(RA.BDREDBCICMS,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDBCICMS,0)   = COALESCE(RA.BDBCICMS,0)   OR COALESCE(RO.BDVLRICMS,0)   = COALESCE(RA.BDVLRICMS,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDALIQFCP,0)  = COALESCE(RA.BDALIQFCP,0)  OR COALESCE(RO.BDBCFCP,0)     = COALESCE(RA.BDBCFCP,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDVLRFCP,0)   = COALESCE(RA.BDVLRFCP,0)   OR COALESCE(RO.BDPERCDIFER,0) = COALESCE(RA.BDPERCDIFER,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDCSTICMSST,0) = COALESCE(RA.BDCSTICMSST,0) OR COALESCE(RO.BDALIQICMSST,0) = COALESCE(RA.BDALIQICMSST,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDBCICMSST,0)  = COALESCE(RA.BDBCICMSST,0)  OR COALESCE(RO.BDVLRICMSST,0)  = COALESCE(RA.BDVLRICMSST,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDALIQFCPST,0) = COALESCE(RA.BDALIQFCPST,0) OR COALESCE(RO.BDBCICMSFCP,0)  = COALESCE(RA.BDBCICMSFCP,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDVLRFCPST,0)  = COALESCE(RA.BDVLRFCPST,0)  OR COALESCE(RO.BDCSTPIS,0)     = COALESCE(RA.BDCSTPIS,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDALIQPIS,0)   = COALESCE(RA.BDALIQPIS,0)   OR COALESCE(RO.BDBCPIS,0)     = COALESCE(RA.BDBCPIS,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDVLRPIS,0)    = COALESCE(RA.BDVLRPIS,0)    OR COALESCE(RO.BDCSTCOF,0)     = COALESCE(RA.BDCSTCOF,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDALIQCOFINS,0) = COALESCE(RA.BDALIQCOFINS,0) OR COALESCE(RO.BDBCCOFINS,0) = COALESCE(RA.BDBCCOFINS,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDVLRCOFINS,0)   = COALESCE(RA.BDVLRCOFINS,0)  OR COALESCE(RO.BDCSTIPI,0)   = COALESCE(RA.BDCSTIPI,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDALIQIPI,0)     = COALESCE(RA.BDALIQIPI,0) OR COALESCE(RO.BDBCIPI,0) = COALESCE(RA.BDBCIPI,0) OR COALESCE(RO.BDVLRIPI,0) = COALESCE(RA.BDVLRIPI,0) ';
    WSQL = WSQL || '         OR   RO.BDCODNAT = IIF(CHAR_LENGTH(RA.BDCODNAT) = 4,RA.BDCODNAT||''000'',RA.BDCODNAT) OR RO.BDISANTECIPACAO = RA.BDISANTECIPACAO ';
    WSQL = WSQL || '         OR RO.BDCODNCM = RA.BDCODNCM   OR   Coalesce(RO.BDCODCEST,0)  = Coalesce(RA.BDCODCEST,0) ) ';
    WSQL = WSQL || '         ); ';

    EXECUTE STATEMENT(WSQL);

            /*Retornou e possue inconsistências*/
    WSQL =         ' UPDATE VEF_EMP_TAUDIMENDES AUD SET ';
    WSQL = WSQL || ' AUD.BDSTATUS = 4  '; --Retornou e possue inconsistências
    WSQL = WSQL || ' WHERE '||:PRCODEMP||' AND '||'AUD.BDDATANOTA BETWEEN '''|| :PRDATAINI ||''' AND '''|| :PRDATAFIM ||'''';
    WSQL = WSQL || ' AND AUD.BDSTATUS <> 6 '; /*CONFERIDO MANUALMENTE*/
    WSQL = WSQL || ' AND AUD.BDSTATUS <> 7 '; /*CONFERIDO AUTOMATICAMENTE*/
    WSQL = WSQL || ' AND EXISTS ( ';
    WSQL = WSQL || '         SELECT FIRST 1 RO.BDCODEMP ';
    WSQL = WSQL || '         FROM TMP_VEF_EMP_RETORNOIMENDES_TEMP RO ';
    WSQL = WSQL || '         JOIN TMP_VEF_EMP_RETORNOIMENDES_TEMP RA ON (RA.BDCODEMP = RO.BDCODEMP AND RA.BDDATANOTA = RO.BDDATANOTA AND RA.BDMOVIMENTO = RO.BDMOVIMENTO ';
    WSQL = WSQL ||                                                    ' AND COALESCE(RA.BDCODTER,0) = COALESCE(RO.BDCODTER,0) AND RA.BDCODNATOPE = RO.BDCODNATOPE AND RA.BDDOCUMENTO = RO.BDDOCUMENTO ';
    WSQL = WSQL ||                                                    ' AND RA.BDCODPROD = RO.BDCODPROD AND RO.BDCHAVE  = RA.BDCHAVE AND RO.BDORDEM = RA.BDORDEM ';
    WSQL = WSQL ||                                                    ' AND RO.BDORDEMPRO = RA.BDORDEMPRO AND RA.BDSESSAO = '|| :PRSESSAO ||' AND RA.bdcomparativo = 1 /*AUD*/) ';
    WSQL = WSQL || '         WHERE RO.BDCODEMP = AUD.BDCODEMP AND   RO.BDDATANOTA = AUD.BDDATANOTA AND   RO.BDMOVIMENTO = AUD.BDMOVIMENTO ';
    WSQL = WSQL || '         AND   COALESCE(RO.BDCODTER,0) = COALESCE(AUD.BDCODTER,0) AND   RO.BDCODNATOPE = AUD.BDCODNATOPE AND   RO.BDDOCUMENTO = AUD.BDDOCUMENTO ';
    WSQL = WSQL || '         AND   RO.BDCODPROD = AUD.BDCODPROD AND   RO.BDCHAVE  = AUD.BDCHAVE AND   RO.BDORDEM  = AUD.BDORDEM  AND   RO.BDORDEMPRO = AUD.BDORDEMPRO ';
    WSQL = WSQL || '         AND   RO.BDCOMPARATIVO = 0 /*ORI*/';
    WSQL = WSQL || '         AND   RO.BDSESSAO = '|| :PRSESSAO ;
    WSQL = WSQL || '         AND   (  COALESCE(RO.bdcsticms,0) <>  COALESCE(RA.bdcsticms,0) OR   COALESCE(RO.BDALIQICMS,0) <> COALESCE(RA.BDALIQICMS,0) OR COALESCE(RO.BDREDBCICMS,0) <> COALESCE(RA.BDREDBCICMS,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDBCICMS,0)   <> COALESCE(RA.BDBCICMS,0)   OR COALESCE(RO.BDVLRICMS,0)   <> COALESCE(RA.BDVLRICMS,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDALIQFCP,0)  <> COALESCE(RA.BDALIQFCP,0)  OR COALESCE(RO.BDBCFCP,0)     <> COALESCE(RA.BDBCFCP,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDVLRFCP,0)   <> COALESCE(RA.BDVLRFCP,0)   OR COALESCE(RO.BDPERCDIFER,0) <> COALESCE(RA.BDPERCDIFER,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDCSTICMSST,0) <> COALESCE(RA.BDCSTICMSST,0) OR COALESCE(RO.BDALIQICMSST,0) <> COALESCE(RA.BDALIQICMSST,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDBCICMSST,0)  <> COALESCE(RA.BDBCICMSST,0)  OR COALESCE(RO.BDVLRICMSST,0)  <> COALESCE(RA.BDVLRICMSST,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDALIQFCPST,0) <> COALESCE(RA.BDALIQFCPST,0) OR COALESCE(RO.BDBCICMSFCP,0)  <> COALESCE(RA.BDBCICMSFCP,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDVLRFCPST,0)  <> COALESCE(RA.BDVLRFCPST,0)  OR COALESCE(RO.BDCSTPIS,0)     <> COALESCE(RA.BDCSTPIS,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDALIQPIS,0)   <> COALESCE(RA.BDALIQPIS,0)   OR COALESCE(RO.BDBCPIS,0)     <> COALESCE(RA.BDBCPIS,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDVLRPIS,0)    <> COALESCE(RA.BDVLRPIS,0)    OR COALESCE(RO.BDCSTCOF,0)     <> COALESCE(RA.BDCSTCOF,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDALIQCOFINS,0) <> COALESCE(RA.BDALIQCOFINS,0) OR COALESCE(RO.BDBCCOFINS,0) <> COALESCE(RA.BDBCCOFINS,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDVLRCOFINS,0)   <> COALESCE(RA.BDVLRCOFINS,0)  OR COALESCE(RO.BDCSTIPI,0)   <> COALESCE(RA.BDCSTIPI,0) ';
    WSQL = WSQL || '         OR   COALESCE(RO.BDALIQIPI,0)     <> COALESCE(RA.BDALIQIPI,0) OR COALESCE(RO.BDBCIPI,0) <> COALESCE(RA.BDBCIPI,0) OR COALESCE(RO.BDVLRIPI,0) <> COALESCE(RA.BDVLRIPI,0) ';
    WSQL = WSQL || '         OR   IIF(CHAR_LENGTH(RO.BDCODNAT) > 4,SUBSTRING(RO.BDCODNAT FROM 1 FOR 4),RO.BDCODNAT) <> IIF(CHAR_LENGTH(RA.BDCODNAT) > 4,SUBSTRING(RA.BDCODNAT FROM 1 FOR 4),RA.BDCODNAT) OR RO.BDISANTECIPACAO <> RA.BDISANTECIPACAO ';
    WSQL = WSQL || '         OR RO.BDCODNCM <> RA.BDCODNCM   OR   Coalesce(RO.BDCODCEST,0)  <> Coalesce(RA.BDCODCEST,0) ) ';
    WSQL = WSQL || '         ); ';

    EXECUTE STATEMENT(WSQL);
        
            /*Quando não teve retorno*/
    WSQL =         ' UPDATE VEF_EMP_TAUDIMENDES AUD SET ';
    WSQL = WSQL || ' AUD.BDSTATUS = 3  '; --Enviado mas ainda não tem retorno
    WSQL = WSQL || ' WHERE '||:PRCODEMP||' AND '||'AUD.BDDATANOTA BETWEEN '''|| :PRDATAINI ||''' AND '''|| :PRDATAFIM ||'''';
    WSQL = WSQL || ' AND AUD.BDSTATUS <> 6 '; /*CONFERIDO MANUALMENTE*/
    WSQL = WSQL || ' AND AUD.BDSTATUS <> 7 '; /*CONFERIDO AUTOMATICAMENTE*/
    WSQL = WSQL || ' AND NOT EXISTS ( ';
    WSQL = WSQL ||                 ' SELECT FIRST 1 R.BDCODEMP ';
    WSQL = WSQL ||                 ' FROM TMP_VEF_EMP_RETORNOIMENDES_TEMP R ';
    WSQL = WSQL ||                 ' WHERE R.BDCODEMP = AUD.BDCODEMP ';
    WSQL = WSQL ||                 ' AND   R.BDDATANOTA = AUD.BDDATANOTA AND   R.BDMOVIMENTO = AUD.BDMOVIMENTO AND   COALESCE(R.BDCODTER,0) = COALESCE(AUD.BDCODTER,0) ';
    WSQL = WSQL ||                 ' AND   R.BDCODNATOPE = AUD.BDCODNATOPE AND   R.BDDOCUMENTO = AUD.BDDOCUMENTO AND   R.BDCODPROD = AUD.BDCODPROD';
    WSQL = WSQL ||                 ' AND   R.BDCHAVE  = AUD.BDCHAVE AND   R.BDORDEM  = AUD.BDORDEM AND   R.BDORDEMPRO = AUD.BDORDEMPRO ';
    WSQL = WSQL ||                 ' AND   R.BDSESSAO = '|| :PRSESSAO ;
    WSQL = WSQL ||                 ' AND   R.BDCOMPARATIVO = 1 /*AUD*/  ';
    WSQL = WSQL ||                 ' ); ';

    EXECUTE STATEMENT(WSQL);


    FOR SELECT S.BDCODEMP, S.BDCHAVE, S.BDMOVIMENTO, S.BDSTATUS
        FROM (
              SELECT R.BDCODEMP, R.BDCHAVE, R.BDMOVIMENTO, MAX(AUD.BDSTATUS) BDSTATUS
              FROM TMP_VEF_EMP_RETORNOIMENDES_TEMP R
              JOIN VEF_EMP_TAUDIMENDES AUD ON (AUD.BDCODEMP = R.BDCODEMP AND AUD.BDCHAVE = R.BDCHAVE AND AUD.BDORDEM = R.BDORDEM AND AUD.BDORDEMPRO = R.BDORDEMPRO AND AUD.BDMOVIMENTO = R.BDMOVIMENTO)
              WHERE R.BDSESSAO = :PRSESSAO AND R.BDCOMPARATIVO = 0
              GROUP BY R.BDCODEMP, R.BDCHAVE, R.BDMOVIMENTO
             ) S
        WHERE S.BDSTATUS IN (2, 4, 6, 7)
        INTO :WCODEMP, :WCHAVE, :WMOVIMENTO,:WSTATUS
    DO
    BEGIN

       IF (WSTATUS = 2) THEN
          BEGIN
            WDESCSTATUS = 'Nota auditada pelo Connection IAT.';
            WCODSTATUS = 1; --CONFERIDO
          END
       ELSE IF (WSTATUS= 4) THEN
          BEGIN
            WDESCSTATUS = 'Nota pendente pelo Connection IAT.';
            WCODSTATUS = 3; --PENDENTE
          END
       ELSE IF (WSTATUS= 6) THEN
          BEGIN
            WDESCSTATUS = 'Nota conferida manualmente no processo de auditoria Connection IAT.';
            WCODSTATUS = 1; --CONFERIDO
          END
       ELSE IF (WSTATUS= 7) THEN
          BEGIN
            WDESCSTATUS = 'Nota ajustada pelo Connection IAT.';
            WCODSTATUS = 1; --CONFERIDO
          END

       WCODSTATUSATUAL = 0;

       IF (:WMOVIMENTO = 0) THEN
          BEGIN
            SELECT S.BDCODSTATUSLAN, SUBSTRING(S.bdjustificativa FROM 1 for 100)
            FROM VEF_EMP_TMOVENTSTATUS S
            WHERE S.BDCODEMP = :WCODEMP
            AND S.BDCHAVE = :WCHAVE
            AND S.BDORDEMSTATUS = (SELECT MAX(S.BDORDEMSTATUS) FROM VEF_EMP_TMOVENTSTATUS S
                                   WHERE S.BDCODEMP = :WCODEMP
                                   AND S.BDCHAVE = :WCHAVE
                                   AND S.BDCODORISTATUS = 7) /*IMENDES*/
            INTO :WCODSTATUSATUAL, :WDESCSTATUSATUAL;

            --168914 senta que lá vem a história, quando a nota foi ajustada automaticamente, se passa de novo de pelo iMendes, deve então, caso esteja como OK, dá a justificativa que foi auditada...
            if ((:wstatus = 2) and (Position('ajustada', :wdescstatusatual) <> 0)) then
               begin
                  :WCODSTATUSATUAL = 2;
               end

            IF (COALESCE(:WCODSTATUSATUAL,0) <> :WCODSTATUS) THEN
               BEGIN
                 INSERT INTO VEF_EMP_TMOVENTSTATUS(BDCODEMP, BDCHAVE, BDORDEMSTATUS, BDCODUSU, BDCODTIPO, BDCODSTATUSLAN, BDJUSTIFICATIVA, BDDATASTATUS, BDHORA, BDREADONLY, BDCODORISTATUS)
                 VALUES (:WCODEMP,:WCHAVE, COALESCE((SELECT MAX(S.BDORDEMSTATUS)+1 FROM VEF_EMP_TMOVENTSTATUS S WHERE S.BDCODEMP = :WCODEMP AND S.BDCHAVE = :WCHAVE),1),
                        (SELECT BDCODUSU FROM VW_VARIAVEIS_SESSAO_BANCO) , 102, :WCODSTATUS,:WDESCSTATUS, CURRENT_DATE, CURRENT_TIME, 'TRUE', 7);

                 UPDATE VEF_EMP_TMOVENT E SET
                 E.BDCODSTATUSLAN = :WCODSTATUS
                 WHERE E.BDCODEMP = :WCODEMP
                 AND   E.BDCHAVE  = :WCHAVE;

               END
          END
       ELSE IF (:WMOVIMENTO = 1) THEN
          BEGIN
            SELECT S.BDCODSTATUSLAN, SUBSTRING(S.bdjustificativa FROM 1 for 100)
            FROM VEF_EMP_TMOVSAISTATUS S
            WHERE S.BDCODEMP = :WCODEMP
            AND S.BDCHAVE = :WCHAVE
            AND S.BDORDEMSTATUS = (SELECT MAX(S.BDORDEMSTATUS) FROM VEF_EMP_TMOVSAISTATUS S
                                   WHERE S.BDCODEMP = :WCODEMP
                                   AND S.BDCHAVE = :WCHAVE
                                   AND S.BDCODORISTATUS = 7) /*IMENDES*/
            INTO :WCODSTATUSATUAL, :WDESCSTATUSATUAL;

            --168914 senta que lá vem a história, quando a nota foi ajustada automaticamente, se passa de novo de pelo iMendes, deve então, caso esteja como OK, dá a justificativa que foi auditada...
            if ((:wstatus = 2) and (Position('ajustada', :wdescstatusatual) <> 0)) then
               begin
                  :WCODSTATUSATUAL = 2;
               end

            IF (COALESCE(:WCODSTATUSATUAL,0) <> :WCODSTATUS) THEN
               BEGIN
                 INSERT INTO VEF_EMP_TMOVSAISTATUS(BDCODEMP, BDCHAVE, BDORDEMSTATUS, BDCODUSU, BDCODTIPO, BDCODSTATUSLAN, BDJUSTIFICATIVA, BDDATASTATUS, BDHORA, BDREADONLY, BDCODORISTATUS)
                 VALUES (:WCODEMP,:WCHAVE, COALESCE((SELECT MAX(S.BDORDEMSTATUS)+1 FROM VEF_EMP_TMOVSAISTATUS S WHERE S.BDCODEMP = :WCODEMP AND S.BDCHAVE = :WCHAVE),1),
                        (SELECT BDCODUSU FROM VW_VARIAVEIS_SESSAO_BANCO) , 102, :WCODSTATUS,:WDESCSTATUS, CURRENT_DATE, CURRENT_TIME, 'TRUE', 7);

                 UPDATE VEF_EMP_TMOVSAI E SET
                 E.BDCODSTATUSLAN = :WCODSTATUS
                 WHERE E.BDCODEMP = :WCODEMP
                 AND   E.BDCHAVE  = :WCHAVE;
               END
          END
       ELSE IF (:WMOVIMENTO = 2) THEN
          BEGIN
            SELECT S.BDCODSTATUSLAN, SUBSTRING(S.bdjustificativa FROM 1 for 100)
            FROM VEF_EMP_TREDZSTATUS S
            WHERE S.BDCODEMP = :WCODEMP
            AND S.BDCHAVE = :WCHAVE
            AND S.BDORDEMSTATUS = (SELECT MAX(S.BDORDEMSTATUS) FROM VEF_EMP_TREDZSTATUS S
                                   WHERE S.BDCODEMP = :WCODEMP
                                   AND S.BDCHAVE = :WCHAVE
                                   AND S.BDCODORISTATUS = 7) /*IMENDES*/
            INTO :WCODSTATUSATUAL, :WDESCSTATUSATUAL;

            --168914 senta que lá vem a história, quando a nota foi ajustada automaticamente, se passa de novo de pelo iMendes, deve então, caso esteja como OK, dá a justificativa que foi auditada...
            if ((:wstatus = 2) and (Position('ajustada', :wdescstatusatual) <> 0)) then
               begin
                  :WCODSTATUSATUAL = 2;
               end

            IF (COALESCE(:WCODSTATUSATUAL,0) <> :WCODSTATUS) THEN
               BEGIN
                 INSERT INTO VEF_EMP_TREDZSTATUS(BDCODEMP, BDCHAVE, BDORDEMSTATUS, BDCODUSU, BDCODTIPO, BDCODSTATUSLAN, BDJUSTIFICATIVA, BDDATASTATUS, BDHORA, BDREADONLY, BDCODORISTATUS)
                 VALUES (:WCODEMP,:WCHAVE, COALESCE((SELECT MAX(S.BDORDEMSTATUS)+1 FROM VEF_EMP_TREDZSTATUS S WHERE S.BDCODEMP = :WCODEMP AND S.BDCHAVE = :WCHAVE),1),
                        (SELECT BDCODUSU FROM VW_VARIAVEIS_SESSAO_BANCO) , 102, :WCODSTATUS,:WDESCSTATUS, CURRENT_DATE, CURRENT_TIME, 'TRUE', 7);

                 UPDATE VEF_EMP_TREDZ E SET
                 E.BDCODSTATUSLAN = :WCODSTATUS
                 WHERE E.BDCODEMP = :WCODEMP
                 AND   E.BDCHAVE  = :WCHAVE;
               END
          END
    END
END^

CREATE OR ALTER procedure SP_AUDITANOTAS_IMENDES_SAI (
    PRCODEMP varchar(30000),
    PRDATAINI date,
    PRDATAFIM date,
    PRSESSAO integer,
    PRREFERENCIA integer)
as
declare variable WSQL varchar(29994);
BEGIN

    WSQL = ' INSERT INTO TMP_VEF_EMP_RETORNOIMENDES_TEMP (BDCOMPARATIVO, BDCODEMP, BDDATANOTA, BDMOVIMENTO, BDCODTER, BDCODNATOPE,
                                                  BDDOCUMENTO, BDCODPROD, BDCSTICMS, BDALIQICMS, BDREDBCICMS, BDBCICMS,
                                                  BDVLRICMS, BDALIQFCP, BDBCFCP, BDVLRFCP, BDAMPLEGAL,
                                                  BDPERCDIFER, BDCSTICMSST, BDALIQICMSST, BDBCICMSST, BDVLRICMSST,
                                                  BDALIQFCPST, BDBCICMSFCP, BDVLRFCPST, BDCSTPIS, BDALIQPIS, BDBCPIS,
                                                  BDVLRPIS, BDCSTCOF, BDALIQCOFINS, BDBCCOFINS, BDVLRCOFINS,
                                                  BDBASELEGALPIS,BDBASELEGALCOF, BDCODNATREC, BDCSTIPI, BDALIQIPI, BDBCIPI, BDVLRIPI, BDCODNAT,
                                                 BDCODNCM, BDCODCEST, BDCLASSCEST, BDCODUF,BDCHAVE,BDORDEM,BDORDEMPRO,BDDATARETORNO,
                                                 BDHORARETORNO,BDCHAVELOG,BDSESSAO,BDSTATUS, BDCSON, BDCLASSIFICACAO)
    with
     AUD_BASICO
     as (select AUD.BDCHAVE, cast(AUD.BDCODPROD as varchar(20)) BDCODPROD, AUD.BDCODUF, AUD.BDCODNATOPE,
                Coalesce(iif(AUD.BDCARACTRIBUTARIATER = -1, 0, AUD.BDCARACTRIBUTARIATER), 0) BDCARACTRIBUTARIATER, AUD.BDFINALIDADE,
                P.BDCODIGOEAN, TRIM(LEADING ''0'' FROM P.BDCODIGOEAN) AS BDEANLIMPO, AUD.BDCODNCM, AUD.BDDATANOTA, AUD.BDMOVIMENTO, AUD.BDCODTER, AUD.BDDOCUMENTO,
                AUD.BDORDEM, AUD.BDORDEMPRO, AUD.BDCODCEST, AUD.BDDATAENVIO, AUD.BDSTATUS, trim(PVINC.BDCODIAT) as BDCODIAT,
                EMP.BDCODEMP, EMP.BDCODCID, EMP.BDIAT_PISCOF_SEM_ICMS, EMP.BDCARACTRIBUTARIA, EMP.BDSUBSTRIB,
                iif(EMP.BDCODENQFED <> 3, 0 /*SN*/ , iif(EMP.BDFORMATRIBUTACAO = 1, 2 /*LP*/ , 1 /*LR*/ )) as BDREGTRIBUTARIO, CID.BDCODUF as BDCODUFEMP
         /*from TEMPRESAS E Alt.: #223280 - Lentidao*/
         from (SELECT * FROM TEMPRESAS e WHERE E.'||:PRCODEMP||') E
         join SP_CONSULTA_EMPRESA_REF(E.BDCODEMP,' || :PRREFERENCIA || ') EMP on (0=0)
         join TCIDADE CID on (CID.BDCODCID = EMP.BDCODCID)
         join VEF_EMP_TAUDIMENDES AUD on EMP.BDCODEMP = AUD.BDCODEMP
         left outer join TCADPRO P on (P.BDCODPROD = AUD.BDCODPROD)
         left outer join TCADPRO_VINC PVINC on (PVINC.BDCODPROD = AUD.BDCODPROD and
               PVINC.BDCODEMP = AUD.BDCODEMP)
      WHERE /*EMP.'||:PRCODEMP||' AND Alt.: #223280 - Lentidao*/ AUD.BDDATANOTA BETWEEN '''|| :PRDATAINI ||''' AND '''|| :PRDATAFIM ||'''
        AND AUD.BDMOVIMENTO = 1 ),
    REGRAS_PROD
    as (select R.BDCODGRUPO,R.BDORDEMREGRA ,AUD_BASICO.BDCHAVE, R.BDSUBSTRIBUTARIO, R.BDCHAVELOG, AUD_BASICO.BDORDEM,
               AUD_BASICO.BDORDEMPRO, AUD_BASICO.BDCODEMP, (G.BDDATARETORNO + G.bdhoraretorno) AS BDDATAHORARETORNO
        from AUD_BASICO
        inner join VEF_EMP_TREGRASPRODUTOS R on R.BDUFNOTA = AUD_BASICO.BDCODUF and
              R.BDCODNAT = substring(AUD_BASICO.BDCODNATOPE from 1 for 4) and
              AUD_BASICO.BDCARACTRIBUTARIATER = R.BDCARACTRIBUTARIATER and
              R.BDFINALIDADE = AUD_BASICO.BDFINALIDADE and
              AUD_BASICO.BDCODPROD = R.BDCODPRODIMEND and
              R.BDCARACTRIBUTARIA = AUD_BASICO.BDCARACTRIBUTARIA and
              R.BDREGTRIBUTARIO = AUD_BASICO.BDREGTRIBUTARIO and
              R.BDCODUF = AUD_BASICO.BDCODUFEMP
        left join VEF_BASE_TGRUPOIMENDES G on (G.BDCODGRUPO = R.BDCODGRUPO) --and (G.bdCODCEST = AUD_BASICO.BDCODCEST)
        where ((AUD_BASICO.BDDATAENVIO is null) or (extract(year from G.BDDATARETORNO) = extract(year from AUD_BASICO.BDDATAENVIO) and
              extract(month from G.BDDATARETORNO) = extract(month from AUD_BASICO.BDDATAENVIO)))),
    REGRAS_PROD_MAX
    as (select BDCHAVE, BDORDEM, BDORDEMPRO, BDCODEMP, MAX(BDDATAHORARETORNO) AS MAXRETORNO
        FROM REGRAS_PROD
        GROUP BY BDCHAVE, BDORDEM, BDORDEMPRO, BDCODEMP),
    REGRAS_EAN
    as (select R.BDCODGRUPO,R.BDORDEMREGRA ,AUD_BASICO.BDCHAVE, R.BDSUBSTRIBUTARIO, R.BDCHAVELOG, AUD_BASICO.BDORDEM,
               AUD_BASICO.BDORDEMPRO, AUD_BASICO.BDCODEMP, (G.BDDATARETORNO + G.bdhoraretorno) AS BDDATAHORARETORNO
        from AUD_BASICO
        inner join VEF_EMP_TREGRASPRODUTOS R on R.BDUFNOTA = AUD_BASICO.BDCODUF and
              R.BDCODNAT = substring(AUD_BASICO.BDCODNATOPE from 1 for 4) and
              AUD_BASICO.BDCARACTRIBUTARIATER = R.BDCARACTRIBUTARIATER and
              R.BDFINALIDADE = AUD_BASICO.BDFINALIDADE and
              AUD_BASICO.BDEANLIMPO = R.BDCODPRODIMEND and
              R.BDCARACTRIBUTARIA = AUD_BASICO.BDCARACTRIBUTARIA and
              R.BDREGTRIBUTARIO = AUD_BASICO.BDREGTRIBUTARIO and
              R.BDCODUF = AUD_BASICO.BDCODUFEMP
          AND r.BDCHAVELOG = (SELECT MAX(x.BDCHAVELOG) /* #222842 */
                              FROM VEF_EMP_TREGRASPRODUTOS x
                              WHERE x.BDUFNOTA = r.BDUFNOTA and
                                    x.BDCODNAT = R.BDCODNAT and
                                    x.BDCARACTRIBUTARIATER = R.BDCARACTRIBUTARIATER and
                                    x.BDFINALIDADE = R.BDFINALIDADE and
                                    x.BDCODPRODIMEND = R.BDCODPRODIMEND and
                                    x.BDCARACTRIBUTARIA = R.BDCARACTRIBUTARIA and
                                    x.BDREGTRIBUTARIO = R.BDREGTRIBUTARIO and
                                    x.BDCODUF = R.BDCODUF)
        inner join VEF_BASE_TGRUPOIMENDES G on (G.BDCODGRUPO = R.BDCODGRUPO) --and (G.bdCODCEST = AUD_BASICO.BDCODCEST)
        where ((AUD_BASICO.BDDATAENVIO is null) or (extract(year from G.BDDATARETORNO) = extract(year from AUD_BASICO.BDDATAENVIO) and
              extract(month from G.BDDATARETORNO) = extract(month from AUD_BASICO.BDDATAENVIO)))),
    /* Alt.: #222842 - Resolve os registros duplicados ali em cima, bsucando o log mais recente.
    REGRAS_EAN_MAX
    as (select BDCHAVE, BDORDEM, BDORDEMPRO, BDCODEMP, MAX(BDDATAHORARETORNO) AS MAXRETORNO
        FROM REGRAS_EAN
        GROUP BY BDCHAVE, BDORDEM, BDORDEMPRO, BDCODEMP),*/
    REGRAS_IAT
    as (select R.BDCODGRUPO,R.BDORDEMREGRA ,AUD_BASICO.BDCHAVE, R.BDSUBSTRIBUTARIO, R.BDCHAVELOG, AUD_BASICO.BDORDEM,
               AUD_BASICO.BDORDEMPRO, AUD_BASICO.BDCODEMP, (G.BDDATARETORNO + G.bdhoraretorno) AS BDDATAHORARETORNO
        from AUD_BASICO
        inner join VEF_EMP_TREGRASPRODUTOS R on R.BDUFNOTA = AUD_BASICO.BDCODUF and
              R.BDCODNAT = substring(AUD_BASICO.BDCODNATOPE from 1 for 4) and
              AUD_BASICO.BDCARACTRIBUTARIATER = R.BDCARACTRIBUTARIATER and
              R.BDFINALIDADE = AUD_BASICO.BDFINALIDADE and
              trim(AUD_BASICO.BDCODIAT) = R.BDCODPRODIMEND and
              R.BDCARACTRIBUTARIA = AUD_BASICO.BDCARACTRIBUTARIA and
              R.BDREGTRIBUTARIO = AUD_BASICO.BDREGTRIBUTARIO and
              R.BDCODUF = AUD_BASICO.BDCODUFEMP
        inner join VEF_BASE_TGRUPOIMENDES G on (G.BDCODGRUPO = R.BDCODGRUPO) --and (G.bdCODCEST = AUD_BASICO.BDCODCEST)
        where ((AUD_BASICO.BDDATAENVIO is null) or (extract(year from G.BDDATARETORNO) = extract(year from AUD_BASICO.BDDATAENVIO) and
              extract(month from G.BDDATARETORNO) = extract(month from AUD_BASICO.BDDATAENVIO)))),
    REGRAS_IAT_MAX
    as (select BDCHAVE, BDORDEM, BDORDEMPRO, BDCODEMP, MAX(BDDATAHORARETORNO) AS MAXRETORNO
        FROM REGRAS_IAT
        GROUP BY BDCHAVE, BDORDEM, BDORDEMPRO, BDCODEMP),
    REGRAS
    as (select AUD_BASICO.BDCHAVE, AUD_BASICO.BDORDEM, AUD_BASICO.BDORDEMPRO,
               coalesce(REGRAS_PROD.BDCODGRUPO, REGRAS_EAN.BDCODGRUPO, REGRAS_IAT.BDCODGRUPO) as BDCODGRUPO,
               coalesce(REGRAS_PROD.BDSUBSTRIBUTARIO, REGRAS_EAN.BDSUBSTRIBUTARIO, REGRAS_IAT.BDSUBSTRIBUTARIO) as BDSUBSTRIBUTARIO,
               coalesce(REGRAS_PROD.BDCHAVELOG, REGRAS_EAN.BDCHAVELOG, REGRAS_IAT.BDCHAVELOG) as BDCHAVELOG
        from AUD_BASICO
        left join REGRAS_PROD_MAX on
              REGRAS_PROD_MAX.BDCODEMP   = AUD_BASICO.BDCODEMP  and
              REGRAS_PROD_MAX.BDCHAVE    = AUD_BASICO.BDCHAVE   and
              REGRAS_PROD_MAX.BDORDEM    = AUD_BASICO.BDORDEM   and
              REGRAS_PROD_MAX.BDORDEMPRO = AUD_BASICO.BDORDEMPRO
        left join REGRAS_PROD on
              REGRAS_PROD_MAX.BDCODEMP   = REGRAS_PROD.BDCODEMP and
              REGRAS_PROD_MAX.BDCHAVE    = REGRAS_PROD.BDCHAVE and
              REGRAS_PROD_MAX.BDORDEM    = REGRAS_PROD.BDORDEM and
              REGRAS_PROD_MAX.BDORDEMPRO = REGRAS_PROD.BDORDEMPRO and
              REGRAS_PROD_MAX.MAXRETORNO = REGRAS_PROD.BDDATAHORARETORNO
        /*left join REGRAS_EAN_MAX on Alt.: #222842
              REGRAS_EAN_MAX.BDCODEMP   = AUD_BASICO.BDCODEMP  and
              REGRAS_EAN_MAX.BDCHAVE    = AUD_BASICO.BDCHAVE   and
              REGRAS_EAN_MAX.BDORDEM    = AUD_BASICO.BDORDEM   and
              REGRAS_EAN_MAX.BDORDEMPRO = AUD_BASICO.BDORDEMPRO
        left join REGRAS_EAN on
              REGRAS_EAN_MAX.BDCODEMP   = REGRAS_EAN.BDCODEMP and
              REGRAS_EAN_MAX.BDCHAVE    = REGRAS_EAN.BDCHAVE and
              REGRAS_EAN_MAX.BDORDEM    = REGRAS_EAN.BDORDEM and
              REGRAS_EAN_MAX.BDORDEMPRO = REGRAS_EAN.BDORDEMPRO and
              REGRAS_EAN_MAX.MAXRETORNO = REGRAS_EAN.BDDATAHORARETORNO*/
        left join REGRAS_EAN on
              REGRAS_EAN.BDCODEMP   = AUD_BASICO.BDCODEMP  and
              REGRAS_EAN.BDCHAVE    = AUD_BASICO.BDCHAVE   and
              REGRAS_EAN.BDORDEM    = AUD_BASICO.BDORDEM   and
              REGRAS_EAN.BDORDEMPRO = AUD_BASICO.BDORDEMPRO
        left join REGRAS_IAT_MAX on
              REGRAS_IAT_MAX.BDCODEMP   = AUD_BASICO.BDCODEMP  and
              REGRAS_IAT_MAX.BDCHAVE    = AUD_BASICO.BDCHAVE   and
              REGRAS_IAT_MAX.BDORDEM    = AUD_BASICO.BDORDEM   and
              REGRAS_IAT_MAX.BDORDEMPRO = AUD_BASICO.BDORDEMPRO
        left join REGRAS_IAT on
              REGRAS_IAT_MAX.BDCODEMP   = REGRAS_IAT.BDCODEMP and
              REGRAS_IAT_MAX.BDCHAVE    = REGRAS_IAT.BDCHAVE and
              REGRAS_IAT_MAX.BDORDEM    = REGRAS_IAT.BDORDEM and
              REGRAS_IAT_MAX.BDORDEMPRO = REGRAS_IAT.BDORDEMPRO and
              REGRAS_IAT_MAX.MAXRETORNO = REGRAS_IAT.BDDATAHORARETORNO)
     SELECT 0 BDCOMPARATIVO /*ORIGINAL*/, AUD.BDCODEMP,AUD.BDDATANOTA,AUD.BDMOVIMENTO,AUD.BDCODTER,AUD.BDCODNATOPE,AUD.BDDOCUMENTO, AUD.BDCODPROD,
           AUD.BDCSTICMS, AUD.BDALIQICMS, AUD.BDREDBCICMS, AUD.BDBCICMS, AUD.BDVLRICMS, AUD.BDALQFCP, AUD.BDBCFCP, AUD.BDVLRFCP, '''' BDAMPLEGAL, 0 BDPERCDIFER,
           IIF(RI.BDALIQICMSST > 0 OR (RI.BDCSTICMS = 60 OR RI.BDCSON = 500),AUD.BDCSTICMS,0) BDCSTICMSST, AUD.BDALIQST BDALIQICMSST , AUD.BDBCST BDBCICMSST, AUD.BDVLRST BDVLRICMSST,
           AUD.BDALIQFCPSTRET BDALIQFCPST ,AUD.BDBCFCPSTRET BDBCICMSFCP, AUD.BDVLRFCPSTRET BDVLRFCPST,
           AUD.BDCSTPIS,AUD.BDALIQPIS,  AUD.BDBCPIS ,AUD.BDVLRPIS,
           AUD.BDCSTCOF, AUD.BDALIQCOFINS, AUD.BDBCCOFINS, AUD.BDVLRCOFINS, '''' BDBASELEGALPISCOFINS, '''' BDBASELEGALCOF, AUD.BDCODNATREC, 
           COALESCE(AUD.BDCODEXPCSTIPI,0) BDCSTIPI, AUD.BDALIQIPI, AUD.BDBCIPI, AUD.BDVLRIPI,
          /*OA*/ AUD.BDCODNAT,AUD.BDCODNCM, AUD.BDCODCEST, C.BDCLASSCEST, AUD.BDCODUF,AUD.BDCHAVE, AUD.BDORDEM, AUD.BDORDEMPRO,G.BDDATARETORNO,G.BDHORARETORNO,
           R.BDCHAVELOG, ' ||:PRSESSAO || ', AUD.BDSTATUS, RI.BDCSON, N.BDCLASSIFICACAO
     from (select AUD.*, I.BDCSTICMS, PRO.BDALIQICMS, PRO.BDREDBCICMS, PRO.BDBCICMS, PRO.BDVLRICMS, PRO.BDALIQFCPRETIDO,
                  PRO.BDBCFCP, PRO.BDVLRFCP, PRO.BDALIQST, PRO.BDBCST, PRO.BDVLRST, PRO.BDALIQFCPSTRET, PRO.BDBCFCPSTRET,
                  PRO.BDVLRFCPSTRET, PIS.BDCSTPIS, PRO.BDALIQPIS, PRO.BDBCPIS, COF.BDCSTCOF, PRO.BDALIQCOFINS,
                  PRO.BDBCCOFINS, PRO.BDVLRPIS, PRO.BDVLRCOFINS, IPI.BDCODEXPCSTIPI, PRO.BDALIQIPI, PRO.BDBCIPI,
                  PRO.BDVLRIPI, PRO.BDALQFCP, IT.BDCODNAT, NATREC.BDNATREC as BDCODNATREC
           from AUD_BASICO AUD
           join VEF_EMP_TMOVSAIITENS IT on (IT.BDCODEMP = AUD.BDCODEMP and
                 IT.BDCHAVE = AUD.BDCHAVE and
                 IT.BDORDEM = AUD.BDORDEM)
           join VEF_EMP_TMOVPROSAI PRO on (PRO.BDCODEMP = AUD.BDCODEMP and
                 PRO.BDCHAVE = AUD.BDCHAVE and
                 PRO.BDORDEM = AUD.BDORDEM and
                 PRO.BDORDEMPRO = AUD.BDORDEMPRO)
           left join VEF_BASE_TTABCSTICMS I on (I.BDCODCSTICMS = PRO.BDCODCSTICMS)
           left join VEF_BASE_TTABCSTPIS PIS on (PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
           left join VEF_BASE_TTABCSTCOF COF on (COF.BDCODCSTCOF = PRO.BDCODCSTCOF)
           left join VEF_BASE_TTABCSTIPI IPI on (IPI.BDCODCSTIPI = PRO.BDCODCSTIPI)
           left join VEF_BASE_TTAB_NATREC NATREC on (NATREC.BDCODNATREC = PRO.BDCODNATREC)) AUD
     join REGRAS R on R.BDCHAVE = AUD.BDCHAVE and R.bdORDEM = AUD.BDORDEM and R.BDORDEMPRO = AUD.BDORDEMPRO
     join VEF_BASE_TGRUPOIMENDES G on (G.BDCODGRUPO = R.BDCODGRUPO)
     join VEF_EMP_TREGRASIMENDES RI on (RI.BDCODGRUPO = G.BDCODGRUPO and
           RI.BDCODUF = AUD.BDCODUF and
           substring(RI.BDCODNATOPE from 1 for 4) = substring(AUD.BDCODNATOPE from 1 for 4) and
           RI.BDFINALIDADE = AUD.BDFINALIDADE and
           AUD.BDCARACTRIBUTARIATER = RI.BDCARACTRIBUTARIATER)
     left join TCEST C on (C.BDCODCEST = AUD.BDCODCEST)
     LEFT OUTER JOIN TNCM N ON (N.BDNCMPROD = AUD.BDCODNCM)
     where ((AUD.BDDATAENVIO is null) or (extract(year from G.BDDATARETORNO) = extract(year from AUD.BDDATAENVIO) and
           extract(month from G.BDDATARETORNO) = extract(month from AUD.BDDATAENVIO))) and
           (iif(coalesce(AUD.BDSUBSTRIB, 0) = 0, R.BDSUBSTRIBUTARIO = 0, R.BDSUBSTRIBUTARIO = 1))
    UNION ALL /*AUDITORIA*/ 
    SELECT AUD.BDCOMPARATIVO /*AUDITORIA*/, AUD.BDCODEMP,AUD.BDDATANOTA,AUD.BDMOVIMENTO,AUD.BDCODTER,AUD.BDCODNATOPE,AUD.BDDOCUMENTO, AUD.BDCODPROD,
           /*ICMS*/ Coalesce(AUD.BDCSON,AUD.BDCSTICMS) BDCSTICMS, AUD.BDALIQICMS,AUD.BDREDBCICMS, IIF(AUD.BDALIQICMS > 0,AUD.BDBCICMS,0) BDBCICMS, (AUD.BDBCICMS*(AUD.BDALIQICMS/100)) BDVLRICMS, AUD.BDALIQFCP, IIF(AUD.BDALIQFCP > 0,AUD.BDBCICMS,0) BDBCFCP,
           (AUD.BDBCICMS*(AUD.BDALIQFCP/100)) BDVLRFCP, AUD.BDAMPLEGAL, AUD.BDPERCDIFER,
           /*ICMSST*/IIF(BDISICMSST = ''TRUE'',  Coalesce(AUD.BDCSON,AUD.BDCSTICMSST),0) BDCSTICMSST,IIF(BDISICMSST = ''TRUE'',AUD.BDALIQICMSST,0) BDALIQICMSST, IIF(AUD.BDREBCICMSST > 0,AUD.BDBCICMSST*(1- (BDREBCICMSST / 100)),AUD.BDBCICMSST) BDBCICMSST,
           CAST(iif(BDISICMSST = ''TRUE'', iif(AUD.BDREBCICMSST > 0,CAST(AUD.BDBCICMSST * (1- (BDREBCICMSST / 100)) AS DM_NUMERIC_15_2), AUD.BDBCICMSST) * (AUD.BDALIQICMSST/100), 0) AS DM_NUMERIC_15_2) BDVLRICMSST,
           IIF(BDISICMSST = ''TRUE'' AND AUD.BDALIQICMS = 0,AUD.BDALIQFCP, 0 ) BDALIQFCPST,
           IIF(IIF(BDISICMSST = ''TRUE'' AND AUD.BDALIQICMS = 0, AUD.BDALIQFCP, 0) > 0, CAST(iif(AUD.BDREBCICMSST > 0, CAST(AUD.BDBCICMSST * (1- (BDREBCICMSST / 100))  AS DM_NUMERIC_15_2), AUD.BDBCICMSST) AS DM_NUMERIC_15_2),0) BDBCICMSFCP,
           CAST(iif(BDISICMSST = ''TRUE'' and AUD.BDALIQICMS = 0, iif(AUD.BDREBCICMSST > 0, CAST(AUD.BDBCICMSST * (BDREBCICMSST / 100) AS DM_NUMERIC_15_2), AUD.BDBCICMSST) * (AUD.BDALIQFCP * 100), 0) AS DM_NUMERIC_15_2) BDVLRFCPST,
           /*PIS*/IIF(CHAR_LENGTH(AUD.BDCSTPISCOFINSSAI) = 1, ''0''||AUD.BDCSTPISCOFINSSAI,AUD.BDCSTPISCOFINSSAI) BDCSTPIS,AUD.BDALIQPIS, SALP(AUD.BDBASEPIS - iif(BDIAT_PISCOF_SEM_ICMS = ''TRUE'', (AUD.BDBCICMS * (AUD.BDALIQICMS / 100)), 0)) AS BDBASEPIS, (SALP(AUD.BDBASEPIS  - iif(BDIAT_PISCOF_SEM_ICMS = ''TRUE'', (AUD.BDBCICMS * (AUD.BDALIQICMS / 100)), 0)) *(AUD.BDALIQPIS/100)) BDVLRPIS,
           /*COFINS*/ IIF(CHAR_LENGTH(AUD.BDCSTPISCOFINSSAI) = 1, ''0''||AUD.BDCSTPISCOFINSSAI,AUD.BDCSTPISCOFINSSAI) BDCSTCOFINS, AUD.BDALIQCOFINS, SALP(AUD.BDBASECOFINS - iif(BDIAT_PISCOF_SEM_ICMS = ''TRUE'', (AUD.BDBCICMS * (AUD.BDALIQICMS / 100)), 0)) AS BDBASECOFINS, (SALP(AUD.BDBASECOFINS  - iif(BDIAT_PISCOF_SEM_ICMS = ''TRUE'', (AUD.BDBCICMS * (AUD.BDALIQICMS / 100)), 0))*(AUD.BDALIQCOFINS/100)) BDVLRCOFINS, AUD.BDBASELEGALPISCOFINS, AUD.BDBASELEGALPISCOFINS BDBASELEGALCOF, AUD.BDCODNATREC,
           /*IPI*/ COALESCE(AUD.BDCSTIPISAI,0) BDCSTIPI, AUD.BDALIQIPI, AUD.BDBASEIPI, (AUD.BDBASEIPI*(AUD.BDALIQIPI/100)) BDVLRIPI,
           /*OA*/  AUD.BDCODNAT, AUD.BDCODNCM, AUD.BDCODCEST, AUD.BDCLASSCEST, AUD.BDCODUF,AUD.BDCHAVE, AUD.BDORDEM, AUD.BDORDEMPRO,AUD.BDDATARETORNO,AUD.BDHORARETORNO,
           AUD.BDCHAVELOG, ' ||:PRSESSAO || ', AUD.BDSTATUS, AUD.BDCSON, AUD.BDCLASSIFICACAO
     from (select 1 BDCOMPARATIVO /*AUDITORIA*/ , AUD.BDCODEMP, AUD.BDDATANOTA, AUD.BDMOVIMENTO, AUD.BDCODTER,
                  AUD.BDCODNATOPE, AUD.BDDOCUMENTO, AUD.BDCODPROD,
                               /*ICMS*/ (substring(I.BDCSTICMS from 1 for 1) || iif(char_length(RI.BDCSTICMS) = 1, ''0'' || RI.BDCSTICMS, RI.BDCSTICMS)) BDCSTICMS, IIF(AUD.BDREGTRIBUTARIO = 0, 0, iif(substring(AUD.BDCODNATOPE from 1 for 1) <> 6, iif(RI.BDALIQFCP > 0, (RI.BDALIQICMSINTERNA - RI.BDALIQFCP), RI.BDALIQICMSINTERNA), RI.BDALIQICMSINTERESTAD)) BDALIQICMS,
                  iif(RI.BDPERCDIFER > 0, RI.BDPERCDIFER, iif(substring(AUD.BDCODNATOPE from 1 for 1) = 6, RI.BDREDBCICMSINTERESTAD, RI.BDREDBCICMS)) BDREDBCICMS,
                  iif(RI.BDISISENTO = ''TRUE'', 0, iif(RI.BDPERCDIFER > 0, iif(RI.BDPERCDIFER = AUD.BDREDBCNOTA, AUD.BDBCICMS, AUD.BDBCICMS - (AUD.BDBCICMS * (RI.BDPERCDIFER / 100))), iif(substring(AUD.BDCODNATOPE from 1 for 1) = 6, iif(RI.BDREDBCICMSINTERESTAD > 0, iif(RI.BDREDBCICMSINTERESTAD = AUD.BDREDBCNOTA, AUD.BDBCICMS, AUD.BDBCICMS - (AUD.BDBCICMS * (RI.BDREDBCICMSINTERESTAD / 100))), AUD.BDBCICMS), iif(RI.BDREDBCICMS > 0, iif(RI.BDREDBCICMS = AUD.BDREDBCNOTA, AUD.BDBCICMS, AUD.BDBCICMS - (AUD.BDBCICMS * (RI.BDREDBCICMS / 100))), AUD.BDBCICMS)))) BDBCICMS,
                  IIF(AUD.BDREGTRIBUTARIO = 0, 0, RI.BDALIQFCP) AS BDALIQFCP, RI.BDAMPLEGAL, RI.BDPERCDIFER, /*ICMSST*/ RI.BDALIQICMSST,
                  iif(char_length(RI.BDCSTICMS) = 1, ''00'' || RI.BDCSTICMS, ''0'' || RI.BDCSTICMS) BDCSTICMSST,
                  iif(RI.BDALIQICMSST > 0 or (RI.BDCSTICMS = 60 or RI.BDCSON = 500), ''TRUE'', ''FALSE'') BDISICMSST, iif(RI.BDIVA = 0, 0,
                  (BDVLROPERACAOST * (1 + (RI.BDIVA / 100)))) BDBCICMSST, RI.BDREBCICMSST,
                  /*PIS/COFINS*/ G.BDCSTPISCOFINSSAI, G.BDALIQPIS, G.BDALIQCOFINS, NATREC.BDNATREC as BDCODNATREC,
                  iif(BDCSTPISCOFINSSAI in (4, 7, 8, 9) and G.BDALIQPIS = 0, 0, BDVLRBASEPISCOF) BDBASEPIS,
                  iif(BDCSTPISCOFINSSAI in (4, 7, 8, 9) and BDALIQCOFINS = 0, 0, BDVLRBASEPISCOF) BDBASECOFINS,
                  G.BDBASELEGALPISCOFINS, /*IPI*/ G.BDCSTIPISAI, G.BDALIQIPI,
                  iif(BDCSTIPISAI in (52, 53, 54, 55) or G.BDALIQIPI = 0, 0, BDVLRBASEIPI) BDBASEIPI,
                  /*OA*/ RI.BDCODNATAUD BDCODNAT, G.BDCODNCM, G.BDCODCEST, C.BDCLASSCEST, AUD.BDCODUF, AUD.BDCHAVE,
                  AUD.BDORDEM, AUD.BDORDEMPRO, G.BDDATARETORNO, G.BDHORARETORNO, R.BDCHAVELOG, AUD.BDSTATUS, RI.BDCSON,
                  AUD.BDIAT_PISCOF_SEM_ICMS, N.BDCLASSIFICACAO
           from (select AUD.*, PRO.BDREDBCICMS BDREDBCNOTA, iif(PRO.BDBCICMS > 0, PRO.BDBCICMS, PRO.BDVLRITEM) BDBCICMS,
                        ((PRO.BDVLRITEM + PRO.BDVLRIPI + PRO.BDVLRDESPACESSORIA + PRO.BDVLRFRETE) - PRO.BDVLRDESC) BDVLROPERACAOST, iif(PRO.BDBCPIS > 0, PRO.BDBCPIS,
                        ((PRO.BDVLRITEM + PRO.BDVLRDESPACESSORIA + PRO.BDVLRFRETE) - (PRO.BDVLRDESC + iif((coalesce(INTEG.BDSOMAIPIPROD, ''TRUE'') = ''TRUE'') or (coalesce(NATOP.BDSOMAIPIPROD, ''TRUE'') = ''TRUE''), ORI.BDVLRIPI, 0) + iif((coalesce(INTEG.BDSOMASTPROD, ''TRUE'') = ''TRUE'') or (coalesce(NATOP.BDSOMASTPROD, ''TRUE'') = ''TRUE''), ORI.BDVLRST, 0)))) BDVLRBASEPISCOF, iif(PRO.BDBCIPI > 0, PRO.BDBCIPI,
                        ((PRO.BDVLRITEM + PRO.BDVLRDESPACESSORIA + PRO.BDVLRFRETE) - (PRO.BDVLRDESC + iif((coalesce(INTEG.BDSOMAIPIPROD, ''TRUE'') = ''TRUE'') or (coalesce(NATOP.BDSOMAIPIPROD, ''TRUE'') = ''TRUE''), ORI.BDVLRIPI, 0) + iif((coalesce(INTEG.BDSOMASTPROD, ''TRUE'') = ''TRUE'') or (coalesce(NATOP.BDSOMASTPROD, ''TRUE'') = ''TRUE''), ORI.BDVLRST, 0)))) BDVLRBASEIPI, PRO.BDCODCSTICMS
                 from AUD_BASICO AUD
                 left outer join VW_VEF_BASE_TEMPPARINTEG INTEG on (AUD.BDCODEMP = INTEG.BDCODEMP)
                 join VEF_EMP_TMOVPROSAI PRO on (PRO.BDCODEMP = AUD.BDCODEMP and
                       PRO.BDCHAVE = AUD.BDCHAVE and
                       PRO.BDORDEM = AUD.BDORDEM and
                       PRO.BDORDEMPRO = AUD.BDORDEMPRO)
                 left outer join VEF_EMP_TMOVPROSAIIMPORI ORI on (ORI.BDCODEMP = PRO.BDCODEMP and
                       ORI.BDCHAVE = PRO.BDCHAVE and
                       ORI.BDORDEM = PRO.BDORDEM and
                       ORI.BDORDEMHIST = PRO.BDORDEMPRO)
                 left outer join VEF_BASE_TNATOP NATOP on (NATOP.BDCODNAT = AUD.BDCODNATOPE)) AUD
           join REGRAS R on R.BDCHAVE = AUD.BDCHAVE and R.bdORDEM = AUD.BDORDEM and R.BDORDEMPRO = AUD.BDORDEMPRO
           join VEF_BASE_TGRUPOIMENDES G on (G.BDCODGRUPO = R.BDCODGRUPO)
           join VEF_EMP_TREGRASIMENDES RI on (RI.BDCODGRUPO = G.BDCODGRUPO and
                 RI.BDCODUF = AUD.BDCODUF and
                 substring(RI.BDCODNATOPE from 1 for 4) = substring(AUD.BDCODNATOPE from 1 for 4) and
                 RI.BDFINALIDADE = AUD.BDFINALIDADE and
                 AUD.BDCARACTRIBUTARIATER = RI.BDCARACTRIBUTARIATER)
           left outer join VEF_BASE_TTABCSTICMS I on (I.BDCODCSTICMS = AUD.BDCODCSTICMS)
           left outer join VEF_BASE_TTAB_NATREC NATREC on (NATREC.BDCODNATREC = G.BDCODNATREC)
           left outer join TCEST C on (C.BDCODCEST = G.BDCODCEST)
           LEFT OUTER JOIN TNCM N ON (N.BDNCMPROD = G.BDCODNCM)
           where ((AUD.BDDATAENVIO is null) or (extract(year from G.BDDATARETORNO) = extract(year from AUD.BDDATAENVIO) and
           extract(month from G.BDDATARETORNO) = extract(month from AUD.BDDATAENVIO))) and
                 (iif(coalesce(AUD.BDSUBSTRIB, 0) = 0, R.BDSUBSTRIBUTARIO = 0, R.BDSUBSTRIBUTARIO = 1))
                 ) AUD;';

    EXECUTE STATEMENT(WSQL);
END^

create or alter procedure SP_AUDITANOTAS_IMENDES_ENT (
    PRCODEMP varchar(30000),
    PRDATAINI date,
    PRDATAFIM date,
    PRSESSAO integer,
    PRREFERENCIA integer)
as
declare variable WSQL varchar(29994);
BEGIN
    
    WSQL =       ' INSERT INTO TMP_VEF_EMP_RETORNOIMENDES_TEMP (BDCOMPARATIVO, BDCODEMP, BDDATANOTA, BDMOVIMENTO, BDCODTER, BDCODNATOPE, 
                    BDDOCUMENTO, BDCODPROD, BDCSTICMS, BDALIQICMS, BDREDBCICMS, BDBCICMS,
                    BDVLRICMS, BDALIQFCP, BDBCFCP, BDVLRFCP, BDAMPLEGAL,
                    BDPERCDIFER, BDCSTICMSST, BDALIQICMSST, BDBCICMSST, BDVLRICMSST,
                    BDALIQFCPST, BDBCICMSFCP, BDVLRFCPST, BDCSTPIS, BDALIQPIS, BDBCPIS,
                    BDVLRPIS, BDCSTCOF, BDALIQCOFINS, BDBCCOFINS, BDVLRCOFINS,
                    BDBASELEGALPIS,BDBASELEGALCOF, BDCSTIPI, BDALIQIPI, BDBCIPI, BDVLRIPI, BDCODNAT,
                    BDISANTECIPACAO, BDCODNCM, BDCODCEST, BDCLASSCEST,BDCODUF,BDCHAVE,BDORDEM,BDORDEMPRO,
                    BDDATARETORNO,BDHORARETORNO,BDCHAVELOG,BDSESSAO,BDSTATUS, BDCSON, BDCLASSIFICACAO)
    with
     AUD_BASICO
     as (select AUD.BDCHAVE, cast(AUD.BDCODPROD as varchar(20)) BDCODPROD, AUD.BDCODUF, AUD.BDCODNATOPE,
                Coalesce(iif(AUD.BDCARACTRIBUTARIATER = -1, 0, AUD.BDCARACTRIBUTARIATER), 0) BDCARACTRIBUTARIATER, AUD.BDFINALIDADE,
                P.BDCODIGOEAN, TRIM(LEADING ''0'' FROM P.BDCODIGOEAN) AS BDEANLIMPO, AUD.BDCODNCM, AUD.BDDATANOTA, AUD.BDMOVIMENTO, AUD.BDCODTER, AUD.BDDOCUMENTO,
                AUD.BDORDEM, AUD.BDORDEMPRO, AUD.BDCODCEST, AUD.BDDATAENVIO, AUD.BDSTATUS, trim(PVINC.BDCODIAT) as BDCODIAT,
                EMP.BDCODEMP, EMP.BDCODCID, EMP.BDIAT_PISCOF_SEM_ICMS, EMP.BDCARACTRIBUTARIA, EMP.BDSUBSTRIB,
                iif(EMP.BDCODENQFED <> 3, 0 /*SN*/ , iif(EMP.BDFORMATRIBUTACAO = 1, 2 /*LP*/ , 1 /*LR*/ )) as BDREGTRIBUTARIO, CID.BDCODUF as BDCODUFEMP
         /*from TEMPRESAS E Alt.: #223280 - Lentidao*/
         from (SELECT * FROM TEMPRESAS e WHERE E.'||:PRCODEMP||') E
         join SP_CONSULTA_EMPRESA_REF(E.BDCODEMP,' || :PRREFERENCIA || ') EMP on (0=0)
         join TCIDADE CID on (CID.BDCODCID = EMP.BDCODCID)
         join VEF_EMP_TAUDIMENDES AUD on EMP.BDCODEMP = AUD.BDCODEMP
         left outer join TCADPRO P on (P.BDCODPROD = AUD.BDCODPROD)
         left outer join TCADPRO_VINC PVINC on (PVINC.BDCODPROD = AUD.BDCODPROD and
               PVINC.BDCODEMP = AUD.BDCODEMP)
      WHERE /*EMP.'||:PRCODEMP||' AND Alt.: #223280 - Lentidao*/ AUD.BDDATANOTA BETWEEN '''|| :PRDATAINI ||''' AND '''|| :PRDATAFIM ||'''
        AND AUD.BDMOVIMENTO = 0 ),
    REGRAS_PROD
    as (select R.BDCODGRUPO,R.BDORDEMREGRA ,AUD_BASICO.BDCHAVE, R.BDSUBSTRIBUTARIO, R.BDCHAVELOG, AUD_BASICO.BDORDEM,
               AUD_BASICO.BDORDEMPRO, AUD_BASICO.BDCODEMP, (G.BDDATARETORNO + G.bdhoraretorno) AS BDDATAHORARETORNO
        from AUD_BASICO
        inner join VEF_EMP_TREGRASPRODUTOS R on R.BDUFNOTA = AUD_BASICO.BDCODUF and
              R.BDCODNAT = substring(AUD_BASICO.BDCODNATOPE from 1 for 4) and
              AUD_BASICO.BDCARACTRIBUTARIATER = R.BDCARACTRIBUTARIATER and
              R.BDFINALIDADE = AUD_BASICO.BDFINALIDADE and
              AUD_BASICO.BDCODPROD = R.BDCODPRODIMEND and
              R.BDCARACTRIBUTARIA = AUD_BASICO.BDCARACTRIBUTARIA and
              R.BDREGTRIBUTARIO = AUD_BASICO.BDREGTRIBUTARIO and
              R.BDCODUF = AUD_BASICO.BDCODUFEMP
        left join VEF_BASE_TGRUPOIMENDES G on (G.BDCODGRUPO = R.BDCODGRUPO) --and (G.bdCODCEST = AUD_BASICO.BDCODCEST)
        where ((AUD_BASICO.BDDATAENVIO is null) or (extract(year from G.BDDATARETORNO) = extract(year from AUD_BASICO.BDDATAENVIO) and
              extract(month from G.BDDATARETORNO) = extract(month from AUD_BASICO.BDDATAENVIO)))),
    REGRAS_PROD_MAX
    as (select BDCHAVE, BDORDEM, BDORDEMPRO, BDCODEMP, MAX(BDDATAHORARETORNO) AS MAXRETORNO
        FROM REGRAS_PROD
        GROUP BY BDCHAVE, BDORDEM, BDORDEMPRO, BDCODEMP),
    REGRAS_EAN
    as (select R.BDCODGRUPO,R.BDORDEMREGRA ,AUD_BASICO.BDCHAVE, R.BDSUBSTRIBUTARIO, R.BDCHAVELOG, AUD_BASICO.BDORDEM,
               AUD_BASICO.BDORDEMPRO, AUD_BASICO.BDCODEMP, (G.BDDATARETORNO + G.bdhoraretorno) AS BDDATAHORARETORNO
        from AUD_BASICO
        inner join VEF_EMP_TREGRASPRODUTOS R on R.BDUFNOTA = AUD_BASICO.BDCODUF and
              R.BDCODNAT = substring(AUD_BASICO.BDCODNATOPE from 1 for 4) and
              AUD_BASICO.BDCARACTRIBUTARIATER = R.BDCARACTRIBUTARIATER and
              R.BDFINALIDADE = AUD_BASICO.BDFINALIDADE and
              AUD_BASICO.BDEANLIMPO = R.BDCODPRODIMEND and
              R.BDCARACTRIBUTARIA = AUD_BASICO.BDCARACTRIBUTARIA and
              R.BDREGTRIBUTARIO = AUD_BASICO.BDREGTRIBUTARIO and
              R.BDCODUF = AUD_BASICO.BDCODUFEMP
          AND r.BDCHAVELOG = (SELECT MAX(x.BDCHAVELOG) /* #222842 */
                              FROM VEF_EMP_TREGRASPRODUTOS x
                              WHERE x.BDUFNOTA = r.BDUFNOTA and
                                    x.BDCODNAT = R.BDCODNAT and
                                    x.BDCARACTRIBUTARIATER = R.BDCARACTRIBUTARIATER and
                                    x.BDFINALIDADE = R.BDFINALIDADE and
                                    x.BDCODPRODIMEND = R.BDCODPRODIMEND and
                                    x.BDCARACTRIBUTARIA = R.BDCARACTRIBUTARIA and
                                    x.BDREGTRIBUTARIO = R.BDREGTRIBUTARIO and
                                    x.BDCODUF = R.BDCODUF)
        inner join VEF_BASE_TGRUPOIMENDES G on (G.BDCODGRUPO = R.BDCODGRUPO) --and (G.bdCODCEST = AUD_BASICO.BDCODCEST)
        where ((AUD_BASICO.BDDATAENVIO is null) or (extract(year from G.BDDATARETORNO) = extract(year from AUD_BASICO.BDDATAENVIO) and
              extract(month from G.BDDATARETORNO) = extract(month from AUD_BASICO.BDDATAENVIO)))),
    /* Alt.: #222842 - Resolve os registros duplicados ali em cima, bsucando o log mais recente.
    REGRAS_EAN_MAX
    as (select BDCHAVE, BDORDEM, BDORDEMPRO, BDCODEMP, MAX(BDDATAHORARETORNO) AS MAXRETORNO
        FROM REGRAS_EAN
        GROUP BY BDCHAVE, BDORDEM, BDORDEMPRO, BDCODEMP),*/
    REGRAS_IAT
    as (select R.BDCODGRUPO,R.BDORDEMREGRA ,AUD_BASICO.BDCHAVE, R.BDSUBSTRIBUTARIO, R.BDCHAVELOG, AUD_BASICO.BDORDEM,
               AUD_BASICO.BDORDEMPRO, AUD_BASICO.BDCODEMP, (G.BDDATARETORNO + G.bdhoraretorno) AS BDDATAHORARETORNO
        from AUD_BASICO
        inner join VEF_EMP_TREGRASPRODUTOS R on R.BDUFNOTA = AUD_BASICO.BDCODUF and
              R.BDCODNAT = substring(AUD_BASICO.BDCODNATOPE from 1 for 4) and
              AUD_BASICO.BDCARACTRIBUTARIATER = R.BDCARACTRIBUTARIATER and
              R.BDFINALIDADE = AUD_BASICO.BDFINALIDADE and
              trim(AUD_BASICO.BDCODIAT) = R.BDCODPRODIMEND and
              R.BDCARACTRIBUTARIA = AUD_BASICO.BDCARACTRIBUTARIA and
              R.BDREGTRIBUTARIO = AUD_BASICO.BDREGTRIBUTARIO and
              R.BDCODUF = AUD_BASICO.BDCODUFEMP
        inner join VEF_BASE_TGRUPOIMENDES G on (G.BDCODGRUPO = R.BDCODGRUPO) --and (G.bdCODCEST = AUD_BASICO.BDCODCEST)
        where ((AUD_BASICO.BDDATAENVIO is null) or (extract(year from G.BDDATARETORNO) = extract(year from AUD_BASICO.BDDATAENVIO) and
              extract(month from G.BDDATARETORNO) = extract(month from AUD_BASICO.BDDATAENVIO)))),
    REGRAS_IAT_MAX
    as (select BDCHAVE, BDORDEM, BDORDEMPRO, BDCODEMP, MAX(BDDATAHORARETORNO) AS MAXRETORNO
        FROM REGRAS_IAT
        GROUP BY BDCHAVE, BDORDEM, BDORDEMPRO, BDCODEMP),
    REGRAS
    as (select AUD_BASICO.BDCHAVE, AUD_BASICO.BDORDEM, AUD_BASICO.BDORDEMPRO,
               coalesce(REGRAS_PROD.BDCODGRUPO, REGRAS_EAN.BDCODGRUPO, REGRAS_IAT.BDCODGRUPO) as BDCODGRUPO,
               coalesce(REGRAS_PROD.BDSUBSTRIBUTARIO, REGRAS_EAN.BDSUBSTRIBUTARIO, REGRAS_IAT.BDSUBSTRIBUTARIO) as BDSUBSTRIBUTARIO,
               coalesce(REGRAS_PROD.BDCHAVELOG, REGRAS_EAN.BDCHAVELOG, REGRAS_IAT.BDCHAVELOG) as BDCHAVELOG
        from AUD_BASICO
        left join REGRAS_PROD_MAX on
              REGRAS_PROD_MAX.BDCODEMP   = AUD_BASICO.BDCODEMP  and
              REGRAS_PROD_MAX.BDCHAVE    = AUD_BASICO.BDCHAVE   and
              REGRAS_PROD_MAX.BDORDEM    = AUD_BASICO.BDORDEM   and
              REGRAS_PROD_MAX.BDORDEMPRO = AUD_BASICO.BDORDEMPRO
        left join REGRAS_PROD on
              REGRAS_PROD_MAX.BDCODEMP   = REGRAS_PROD.BDCODEMP and
              REGRAS_PROD_MAX.BDCHAVE    = REGRAS_PROD.BDCHAVE and
              REGRAS_PROD_MAX.BDORDEM    = REGRAS_PROD.BDORDEM and
              REGRAS_PROD_MAX.BDORDEMPRO = REGRAS_PROD.BDORDEMPRO and
              REGRAS_PROD_MAX.MAXRETORNO = REGRAS_PROD.BDDATAHORARETORNO
        /*left join REGRAS_EAN_MAX on  Alt.: #222842
              REGRAS_EAN_MAX.BDCODEMP   = AUD_BASICO.BDCODEMP  and
              REGRAS_EAN_MAX.BDCHAVE    = AUD_BASICO.BDCHAVE   and
              REGRAS_EAN_MAX.BDORDEM    = AUD_BASICO.BDORDEM   and
              REGRAS_EAN_MAX.BDORDEMPRO = AUD_BASICO.BDORDEMPRO
        left join REGRAS_EAN on
              REGRAS_EAN_MAX.BDCODEMP   = REGRAS_EAN.BDCODEMP and
              REGRAS_EAN_MAX.BDCHAVE    = REGRAS_EAN.BDCHAVE and
              REGRAS_EAN_MAX.BDORDEM    = REGRAS_EAN.BDORDEM and
              REGRAS_EAN_MAX.BDORDEMPRO = REGRAS_EAN.BDORDEMPRO and
              REGRAS_EAN_MAX.MAXRETORNO = REGRAS_EAN.BDDATAHORARETORNO*/
        left join REGRAS_EAN on
              REGRAS_EAN.BDCODEMP   = AUD_BASICO.BDCODEMP  and
              REGRAS_EAN.BDCHAVE    = AUD_BASICO.BDCHAVE   and
              REGRAS_EAN.BDORDEM    = AUD_BASICO.BDORDEM   and
              REGRAS_EAN.BDORDEMPRO = AUD_BASICO.BDORDEMPRO
        left join REGRAS_IAT_MAX on
              REGRAS_IAT_MAX.BDCODEMP   = AUD_BASICO.BDCODEMP  and
              REGRAS_IAT_MAX.BDCHAVE    = AUD_BASICO.BDCHAVE   and
              REGRAS_IAT_MAX.BDORDEM    = AUD_BASICO.BDORDEM   and
              REGRAS_IAT_MAX.BDORDEMPRO = AUD_BASICO.BDORDEMPRO
        left join REGRAS_IAT on
              REGRAS_IAT_MAX.BDCODEMP   = REGRAS_IAT.BDCODEMP and
              REGRAS_IAT_MAX.BDCHAVE    = REGRAS_IAT.BDCHAVE and
              REGRAS_IAT_MAX.BDORDEM    = REGRAS_IAT.BDORDEM and
              REGRAS_IAT_MAX.BDORDEMPRO = REGRAS_IAT.BDORDEMPRO and
              REGRAS_IAT_MAX.MAXRETORNO = REGRAS_IAT.BDDATAHORARETORNO)
  SELECT 0 BDCOMPARATIVO /*ORIGINAL*/, AUD.BDCODEMP,AUD.BDDATANOTA,AUD.BDMOVIMENTO,AUD.BDCODTER,AUD.BDCODNATOPE,AUD.BDDOCUMENTO, AUD.BDCODPROD,
       AUD.BDCSTICMS, IIF(RI.BDCSTICMS = 60 OR RI.BDCSON = 500,0,AUD.BDALIQICMS) BDALIQICMS, IIF(RI.BDCSTICMS = 60 OR RI.BDCSON = 500,0,AUD.BDREDBCICMS) BDREDBCICMS, IIF(RI.BDCSTICMS = 60 OR RI.BDCSON = 500,0,AUD.BDBCICMS) BDBCICMS , IIF(RI.BDCSTICMS = 60 OR RI.BDCSON = 500,0,AUD.BDVLRICMS) BDVLRICMS, AUD.BDALQFCP BDALIQFCP, AUD.BDBCFCP, AUD.BDVLRFCP, '''' BDAMPLEGAL, 0 BDPERCDIFER,
       /*ICMSST*/IIF(RI.BDALIQICMSST > 0 OR (RI.BDCSTICMS = 60 OR RI.BDCSON = 500),AUD.BDCSTICMS,0) BDCSTICMSST, AUD.BDALIQST BDALIQICMSST , AUD.BDBCST BDBCICMSST, AUD.BDVLRST BDVLRICMSST,
       AUD.BDALIQFCPSTRET BDALIQFCPST ,AUD.BDBCFCPSTRET BDBCICMSFCP, AUD.BDVLRFCPSTRET BDVLRFCPST,AUD.BDCSTPIS, AUD.BDALIQPIS, AUD.BDBCPIS, AUD.BDVLRPIS,
       AUD.BDCSTCOF  BDCSTCOFINS, AUD.BDALIQCOFINS, AUD.BDBCCOFINS, AUD.BDVLRCOFINS, '''' BDBASELEGALPISCOFINS,'''' BDBASELEGALCOF,
       COALESCE(AUD.BDCODEXPCSTIPI,0) BDCSTIPI, AUD.BDALIQIPI, AUD.BDBCIPI, AUD.BDVLRIPI,
       /*OA*/  AUD.BDCODNAT, AUD.BDISANTECIPACAO,AUD.BDCODNCM, AUD.BDCODCEST, C.BDCLASSCEST, AUD.BDCODUF,AUD.BDCHAVE, AUD.BDORDEM, AUD.BDORDEMPRO,G.BDDATARETORNO,G.BDHORARETORNO,
       R.BDCHAVELOG, ' ||:PRSESSAO || ', AUD.BDSTATUS, RI.BDCSON, N.BDCLASSIFICACAO
  FROM (
       SELECT AUD.*,I.BDCSTICMS, PRO.BDALIQICMS, PRO.BDREDBCICMS, PRO.BDBCICMS, PRO.BDVLRICMS, PRO.BDALIQFCPRETIDO, PRO.BDBCFCP, PRO.BDVLRFCP,
              PRO.BDALIQST, PRO.BDBCST, PRO.BDVLRST, PRO.BDALIQFCPSTRET, PRO.BDBCFCPSTRET, PRO.BDVLRFCPSTRET,
              PIS.BDCSTPIS, PRO.BDALIQPIS, PRO.BDBCPIS, COF.BDCSTCOF, PRO.BDALIQCOFINS, PRO.BDBCCOFINS,
              PRO.BDVLRPIS, PRO.BDVLRCOFINS, IPI.BDCODEXPCSTIPI, PRO.BDALIQIPI, PRO.BDBCIPI, PRO.BDVLRIPI,PRO.BDALQFCP,
              IT.BDCODNAT, IIF((ANT.BDCODEMP IS NOT NULL) OR (PR.BDCODEMP IS NOT NULL),''TRUE'',''FALSE'') BDISANTECIPACAO
 from AUD_BASICO AUD
       JOIN VEF_EMP_TMOVENTITENS IT ON (IT.BDCODEMP = AUD.BDCODEMP AND IT.BDCHAVE = AUD.BDCHAVE AND IT.BDORDEM = AUD.BDORDEM)
       JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = AUD.BDCODEMP AND PRO.BDCHAVE = AUD.BDCHAVE AND PRO.BDORDEM = AUD.BDORDEM AND PRO.BDORDEMPRO = AUD.BDORDEMPRO)
       LEFT OUTER JOIN VEF_EMP_TMOVENTANTIMP ANT ON (ANT.BDCODEMP = AUD.BDCODEMP AND ANT.BDCHAVE = AUD.BDCHAVE AND ANT.BDORDEM = AUD.BDORDEM)
       LEFT OUTER JOIN VEF_EMP_TMOVENTANTPR  PR  ON (PR.BDCODEMP = AUD.BDCODEMP AND PR.BDCHAVE = AUD.BDCHAVE AND PR.BDORDEM = AUD.BDORDEM)
       LEFT OUTER JOIN VEF_BASE_TTABCSTICMS I ON (I.BDCODCSTICMS = PRO.BDCODCSTICMS)
       LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON (PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
       LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON (COF.BDCODCSTCOF = PRO.BDCODCSTCOF)
       LEFT OUTER JOIN VEF_BASE_TTABCSTIPI IPI ON (IPI.BDCODCSTIPI = PRO.BDCODCSTIPI)
      ) AUD
  join REGRAS R on R.BDCHAVE = AUD.BDCHAVE and R.BDORDEM = AUD.BDORDEM and R.BDORDEMPRO = AUD.BDORDEMPRO
 JOIN VEF_BASE_TGRUPOIMENDES G ON (G.BDCODGRUPO = R.BDCODGRUPO)
 JOIN VEF_EMP_TREGRASIMENDES RI ON (RI.BDCODGRUPO = G.BDCODGRUPO AND RI.BDCODUF = AUD.BDCODUF AND SUBSTRING(RI.BDCODNATOPE FROM 1 FOR 4)= SUBSTRING(AUD.BDCODNATOPE FROM 1 FOR 4) AND COALESCE(AUD.BDCARACTRIBUTARIATER,0) = RI.BDCARACTRIBUTARIATER AND RI.BDFINALIDADE = AUD.BDFINALIDADE )
 LEFT OUTER JOIN TCEST C ON (C.BDCODCEST = AUD.BDCODCEST)
 LEFT OUTER JOIN TNCM N ON (N.BDNCMPROD = AUD.BDCODNCM)
 WHERE ((AUD.BDDATAENVIO IS NULL OR AUD.BDDATAENVIO IS NULL) OR (SUBSTRING(G.BDDATARETORNO FROM 1 FOR 4)||SUBSTRING(G.BDDATARETORNO FROM 6 FOR 2)) = (SUBSTRING(AUD.BDDATAENVIO FROM 1 FOR 4)||SUBSTRING(AUD.BDDATAENVIO FROM 6 FOR 2)))
 and (iif(AUD.BDSUBSTRIB is null or AUD.BDSUBSTRIB = 0, r.bdsubstributario = 0, r.bdsubstributario = 1))
 UNION ALL /*AUDITORIA*/
  SELECT AUD.BDCOMPARATIVO /*AUDITORIA*/, AUD.BDCODEMP,AUD.BDDATANOTA,AUD.BDMOVIMENTO,AUD.BDCODTER,AUD.BDCODNATOPE,AUD.BDDOCUMENTO, AUD.BDCODPROD,
       Coalesce(AUD.BDCSON,AUD.BDCSTICMS) BDCSTICMS, IIF(AUD.BDCSTICMS = 60 OR AUD.BDCSON = 500,0,AUD.BDALIQICMS) BDALIQICMS, IIF(AUD.BDCSTICMS = 60 OR AUD.BDCSON = 500,0,AUD.BDREDBCICMS) BDREDBCICMS, IIF(AUD.BDALIQICMS > 0,IIF(AUD.BDCSTICMS = 60 OR AUD.BDCSON = 500,0,AUD.BDBCICMS),0) BDBCICMS, (IIF(AUD.BDCSTICMS = 60 OR AUD.BDCSON = 500,0,AUD.BDBCICMS)*(AUD.BDALIQICMS/100)) BDVLRICMS, AUD.BDALIQFCP, IIF(AUD.BDALIQFCP > 0,AUD.BDBCICMS,0) BDBCFCP,
        (AUD.BDBCICMS*(AUD.BDALIQFCP/100)) BDVLRFCP, AUD.BDAMPLEGAL, AUD.BDPERCDIFER,
       IIF(BDISICMSST = ''TRUE'',Coalesce(AUD.BDCSON,AUD.BDCSTICMSST),0) BDCSTICMSST,IIF(BDISICMSST = ''TRUE'',AUD.BDALIQICMSST,0) BDALIQICMSST, IIF(AUD.BDREBCICMSST > 0,AUD.BDBCICMSST*(1- (BDREBCICMSST / 100)),AUD.BDBCICMSST) BDBCICMSST,
        CAST(iif(BDISICMSST = ''TRUE'', iif(AUD.BDREBCICMSST > 0,CAST(AUD.BDBCICMSST * (1- (BDREBCICMSST / 100)) AS DM_NUMERIC_15_2), AUD.BDBCICMSST) * (AUD.BDALIQICMSST/100), 0) AS DM_NUMERIC_15_2) BDVLRICMSST,
        IIF(BDISICMSST = ''TRUE'' AND AUD.BDALIQICMS = 0,AUD.BDALIQFCP, 0 ) BDALIQFCPST,
        IIF(IIF(BDISICMSST = ''TRUE'' AND AUD.BDALIQICMS = 0, AUD.BDALIQFCP, 0) > 0, CAST(iif(AUD.BDREBCICMSST > 0, CAST(AUD.BDBCICMSST * (1- (BDREBCICMSST / 100))  AS DM_NUMERIC_15_2), AUD.BDBCICMSST) AS DM_NUMERIC_15_2),0) BDBCICMSFCP,
       CAST(iif(BDISICMSST = ''TRUE'' and AUD.BDALIQICMS = 0, iif(AUD.BDREBCICMSST > 0, CAST(AUD.BDBCICMSST * (1- (BDREBCICMSST / 100)) AS DM_NUMERIC_15_2), AUD.BDBCICMSST) * (AUD.BDALIQFCP * 100), 0) AS DM_NUMERIC_15_2) BDVLRFCPST,
        IIF(CHAR_LENGTH(AUD.BDCSTPISCOFINSENT) = 1, ''0''||AUD.BDCSTPISCOFINSENT,AUD.BDCSTPISCOFINSENT) BDCSTPIS, AUD.BDALIQPIS, AUD.BDBASEPIS, (AUD.BDBASEPIS*(AUD.BDALIQPIS/100)) BDVLRPIS,
        IIF(CHAR_LENGTH(AUD.BDCSTPISCOFINSENT) = 1, ''0''||AUD.BDCSTPISCOFINSENT,AUD.BDCSTPISCOFINSENT)  BDCSTCOFINS, AUD.BDALIQCOFINS, AUD.BDBASECOFINS, (AUD.BDBASECOFINS*(AUD.BDALIQCOFINS/100)) BDVLRCOFINS, BDBASELEGALPISCOFINS,BDBASELEGALPISCOFINS BDBASELEGALCOF,
        COALESCE(AUD.BDCSTIPIENT,0) BDCSTIPI, AUD.BDALIQIPI, AUD.BDBASEIPI, (AUD.BDBASEIPI*(AUD.BDALIQIPI/100)) BDVLRIPI,
        /*OA*/  AUD.BDCODNAT,AUD.BDISANTECIPACAO, AUD.BDCODNCM, AUD.BDCODCEST, AUD.BDCLASSCEST, AUD.BDCODUF,AUD.BDCHAVE, AUD.BDORDEM, AUD.BDORDEMPRO,AUD.BDDATARETORNO,AUD.BDHORARETORNO,
        AUD.BDCHAVELOG,' ||:PRSESSAO || ', AUD.BDSTATUS, AUD.BDCSON, AUD.BDCLASSIFICACAO
  FROM (
       SELECT 1 BDCOMPARATIVO /*AUDITORIA*/, AUD.BDCODEMP,AUD.BDDATANOTA,AUD.BDMOVIMENTO,AUD.BDCODTER,AUD.BDCODNATOPE,AUD.BDDOCUMENTO, AUD.BDCODPROD,
              /*ICMS*/(substring(I.BDCSTICMS FROM 1 FOR 1) || IIF(char_length(RI.BDCSTICMS) = 1, ''0'' || RI.BDCSTICMS, RI.BDCSTICMS)) BDCSTICMS, IIF(AUD.BDREGTRIBUTARIO = 0, 0,IIF(SUBSTRING(AUD.BDCODNATOPE FROM 1 FOR 1) <> 2,IIF(RI.BDALIQFCP > 0,(RI.BDALIQICMSINTERNA-RI.BDALIQFCP), RI.BDALIQICMSINTERNA),RI.BDALIQICMSINTERESTAD)) BDALIQICMS,
              IIF(RI.BDPERCDIFER > 0, RI.BDPERCDIFER, IIF(SUBSTRING(AUD.BDCODNATOPE FROM 1 FOR 1) = 2,RI.BDREDBCICMSINTERESTAD ,RI.BDREDBCICMS)) BDREDBCICMS, IIF(RI.BDISISENTO = ''TRUE'',0,IIF(RI.BDPERCDIFER > 0,IIF(RI.BDPERCDIFER = AUD.BDREDBCNOTA,AUD.BDBCICMS, AUD.BDBCICMS-(AUD.BDBCICMS*(RI.BDPERCDIFER/100))), IIF(SUBSTRING(AUD.BDCODNATOPE FROM 1 FOR 1) = 2, IIF(RI.BDREDBCICMSINTERESTAD > 0, IIF(RI.BDREDBCICMSINTERESTAD = AUD.BDREDBCNOTA,AUD.BDBCICMS, AUD.BDBCICMS-(AUD.BDBCICMS*(RI.BDREDBCICMSINTERESTAD/100))), AUD.BDBCICMS) ,IIF(RI.BDREDBCICMS > 0, IIF(RI.BDREDBCICMS = AUD.BDREDBCNOTA,AUD.BDBCICMS, AUD.BDBCICMS-(AUD.BDBCICMS*(RI.BDREDBCICMS/100))), AUD.BDBCICMS)))) BDBCICMS,
              IIF(AUD.BDREGTRIBUTARIO = 0, 0, RI.BDALIQFCP) AS BDALIQFCP, RI.BDAMPLEGAL, RI.BDPERCDIFER,
              RI.BDALIQICMSST, (substring(I.BDCSTICMS from 1 for 1) || iif(char_length(RI.BDCSTICMS) = 1, ''0'' || RI.BDCSTICMS, RI.BDCSTICMS)) BDCSTICMSST,
              IIF(RI.BDALIQICMSST > 0 OR (RI.BDCSTICMS = 60 OR RI.BDCSON = 500), ''TRUE'', ''FALSE'') BDISICMSST, IIF(RI.BDIVA = 0,0,(BDVLROPERACAOST * (1+(RI.BDIVA/100)))) BDBCICMSST,RI.BDREBCICMSST,
              G.BDCSTPISCOFINSENT, G.BDALIQPIS, G.BDALIQCOFINS,
              IIF(BDCSTPISCOFINSENT IN (70,71,72,74) AND BDALIQPIS = 0, 0, BDVLRBASEPISCOF) BDBASEPIS,
              IIF(BDCSTPISCOFINSENT IN (70,71,72,74) AND BDALIQCOFINS = 0, 0, BDVLRBASEPISCOF) BDBASECOFINS,
              G.BDBASELEGALPISCOFINS,
              G.BDCSTIPIENT, G.BDALIQIPI, IIF(G.BDCSTIPIENT IN (2,3,4,5) OR G.BDALIQIPI = 0, 0, BDVLRBASEIPI) BDBASEIPI,
              /*OA*/  RI.BDCODNATAUD BDCODNAT, RI.BDISANTECIPACAO, G.BDCODNCM, G.BDCODCEST, C.BDCLASSCEST, AUD.BDCODUF,AUD.BDCHAVE, AUD.BDORDEM, AUD.BDORDEMPRO,G.BDDATARETORNO,G.BDHORARETORNO,R.BDCHAVELOG, AUD.BDSTATUS, RI.BDCSON, N.BDCLASSIFICACAO
       FROM (
             SELECT AUD.*, PRO.BDREDBCICMS BDREDBCNOTA, IIF(PRO.BDBCICMS > 0,PRO.BDBCICMS, PRO.BDVLRITEM) BDBCICMS,
             ((PRO.BDVLRITEM+PRO.BDVLRIPI+PRO.BDVLRDESPACESSORIA+PRO.BDVLRFRETE)-PRO.BDVLRDESC) BDVLROPERACAOST,
             iif(PRO.bdbcpis > 0, PRO.bdbcpis, ((PRO.BDVLRITEM+PRO.BDVLRDESPACESSORIA+PRO.BDVLRFRETE)-(PRO.BDVLRDESC+ IIF((Coalesce(INTEG.BDSOMAIPIPROD,''TRUE'') = ''TRUE'') OR (Coalesce(NATOP.BDSOMAIPIPROD,''TRUE'') = ''TRUE''), ORI.BDVLRIPI,0)+IIF((Coalesce(INTEG.BDSOMASTPROD,''TRUE'') = ''TRUE'') OR (Coalesce(NATOP.BDSOMASTPROD,''TRUE'') = ''TRUE''), ORI.BDVLRST,0)))) BDVLRBASEPISCOF,
             iif(PRO.bdbcipi > 0, PRO.bdbcipi, ((PRO.BDVLRITEM+PRO.BDVLRDESPACESSORIA+PRO.BDVLRFRETE)-(PRO.BDVLRDESC+ IIF((Coalesce(INTEG.BDSOMAIPIPROD,''TRUE'') = ''TRUE'') OR (Coalesce(NATOP.BDSOMAIPIPROD,''TRUE'') = ''TRUE''), ORI.BDVLRIPI,0)+IIF((Coalesce(INTEG.BDSOMASTPROD,''TRUE'') = ''TRUE'') OR (Coalesce(NATOP.BDSOMASTPROD,''TRUE'') = ''TRUE''), ORI.BDVLRST,0)))) BDVLRBASEIPI,
             PRO.BDCODCSTICMS
  from AUD_BASICO AUD
                            left outer join VW_VEF_BASE_TEMPPARINTEG INTEG on (AUD.BDCODEMP = INTEG.BDCODEMP)
            JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = AUD.BDCODEMP AND PRO.BDCHAVE = AUD.BDCHAVE AND PRO.BDORDEM = AUD.BDORDEM AND PRO.BDORDEMPRO = AUD.BDORDEMPRO)
            LEFT OUTER JOIN VEF_EMP_TMOVPROENTIMPORI ORI ON (ORI.BDCODEMP = PRO.BDCODEMP AND ORI.BDCHAVE = PRO.BDCHAVE AND ORI.BDORDEM = PRO.BDORDEM AND ORI.BDORDEMHIST = PRO.BDORDEMPRO)
             LEFT OUTER JOIN VEF_BASE_TNATOP NATOP ON (NATOP.BDCODNAT = AUD.BDCODNATOPE)
            ) AUD
   join REGRAS R on R.BDCHAVE = AUD.BDCHAVE and R.BDORDEM = AUD.BDORDEM and R.BDORDEMPRO = AUD.BDORDEMPRO
       JOIN VEF_BASE_TGRUPOIMENDES G ON (G.BDCODGRUPO = R.BDCODGRUPO)
       JOIN VEF_EMP_TREGRASIMENDES RI ON (RI.BDCODGRUPO = G.BDCODGRUPO AND RI.BDCODUF = AUD.BDCODUF AND SUBSTRING(RI.BDCODNATOPE FROM 1 FOR 4)= SUBSTRING(AUD.BDCODNATOPE FROM 1 FOR 4) AND RI.BDFINALIDADE = AUD.BDFINALIDADE AND COALESCE(AUD.BDCARACTRIBUTARIATER,0) = RI.BDCARACTRIBUTARIATER)
       LEFT OUTER JOIN TCEST C ON (C.BDCODCEST = G.BDCODCEST)
       LEFT OUTER JOIN TNCM N ON (N.BDNCMPROD = G.BDCODNCM)
       LEFT OUTER JOIN VEF_BASE_TTABCSTICMS I ON (I.BDCODCSTICMS = AUD.BDCODCSTICMS)
   where ((AUD.BDDATAENVIO is null) or (extract(year from G.BDDATARETORNO) = extract(year from AUD.BDDATAENVIO) and
          extract(month from G.BDDATARETORNO) = extract(month from AUD.BDDATAENVIO))) and
          (iif(coalesce(AUD.BDSUBSTRIB, 0) = 0, R.BDSUBSTRIBUTARIO = 0, R.BDSUBSTRIBUTARIO = 1))) AUD';

    EXECUTE STATEMENT(WSQL);
END^

create or alter procedure SP_AUDITANOTAS_IMENDES_REDZ (
    PRCODEMP varchar(30000),
    PRDATAINI date,
    PRDATAFIM date,
    PRSESSAO integer)
as
declare variable WSQL varchar(29994);
BEGIN

    WSQL =         'INSERT INTO TMP_VEF_EMP_RETORNOIMENDES_TEMP (BDCOMPARATIVO, BDCODEMP, BDDATANOTA, BDMOVIMENTO, BDCODTER, BDCODNATOPE,BDDOCUMENTO, BDCODPROD, BDCSTICMS, BDALIQICMS, BDREDBCICMS, BDBCICMS,  ';
    WSQL = WSQL || '                                             BDVLRICMS, BDALIQFCP, BDBCFCP, BDVLRFCP, BDAMPLEGAL,BDPERCDIFER, BDCSTICMSST, BDALIQICMSST, BDBCICMSST, BDVLRICMSST,  ';
    WSQL = WSQL || '                                             BDALIQFCPST, BDBCICMSFCP, BDVLRFCPST, BDCSTPIS, BDALIQPIS, BDBCPIS,BDVLRPIS, BDCSTCOF, BDALIQCOFINS, BDBCCOFINS, BDVLRCOFINS, ';
    WSQL = WSQL || '                                             BDBASELEGALPIS,BDBASELEGALCOF, BDCODNAT,BDCODNCM, BDCODCEST, BDCLASSCEST, BDCODUF,BDCHAVE,BDORDEM,BDORDEMPRO,BDDATARETORNO,BDHORARETORNO,BDCHAVELOG,BDSESSAO,BDSTATUS, bdCLASSIFICACAO) ';
    WSQL = WSQL || '/*ORIGINAL C425*/ ';
    WSQL = WSQL || 'SELECT 0 BDCOMPARATIVO /*ORIGINAL*/, AUD.BDCODEMP,AUD.BDDATANOTA,AUD.BDMOVIMENTO,AUD.BDCODTER,AUD.BDCODNATOPE,AUD.BDDOCUMENTO, AUD.BDCODPROD, ';
    WSQL = WSQL || '       AUD.BDCSTICMS, AUD.BDALIQICMS, 0 BDREDBCICMS, IIF(AUD.BDALIQICMS > 0,AUD.BDBASEICMS,0) BDBCICMS, AUD.BDVLRICMS, 0 BDALIQFCP, 0 BDBCFCP, 0 BDVLRFCP, '''' BDAMPLEGAL,0 BDPERCDIFER, ';
    WSQL = WSQL || '       /*ICMSST*/ 0 BDALIQICMSST, 0 BDCSTICMSST, 0 BDBCICMSST, 0 BDVLRICMSST, 0 BDALIQFCPST ,0 BDBCICMSFCP, 0 BDVLRFCPST, ';
    WSQL = WSQL || '       /*PIS*/  AUD.BDCODCSTPIS BDCSTPIS, AUD.BDALIQ_PIS BDALIQPIS,AUD.BDVL_BC_PIS BDBASEPIS, AUD.BDVLRPIS, ';
    WSQL = WSQL || '       /*COFINS*/  AUD.BDCODCSTCOF BDCSTCOF, AUD.BDALIQ_COFINS BDALIQCOFINS, AUD.BDVL_BC_COFINS BDBASECOFINS, AUD.BDVLRCOFINS, '''' BDBASELEGALPISCOFINS, '''' BDBASELEGALCOF, ';
    WSQL = WSQL || '       /*OA*/ AUD.BDCODNAT,AUD.BDCODNCM, AUD.BDCODCEST, C.BDCLASSCEST, AUD.BDCODUF,AUD.BDCHAVE, AUD.BDORDEM, AUD.BDORDEMPRO,G.BDDATARETORNO,G.BDHORARETORNO,';
    WSQL = WSQL || '       R.BDCHAVELOG, ' ||:PRSESSAO || ', AUD.BDSTATUS, N.bdCLASSIFICACAO ';
    WSQL = WSQL || 'FROM ( ';
    WSQL = WSQL || '      SELECT AUD.*, IIF(COALESCE(C.BDCSTICMS,'''') = '''',IIF(I.BDORDEMTOT = 7,''041'', IIF(I.BDORDEMTOT = 5,''060'', IIF(I.BDORDEMTOT = 6,''040'',''''))) ,C.BDCSTICMS) BDCSTICMS, IIF(I.BDORDEMTOT IN (7,5,6),0,I.BDALIQTOT) BDALIQICMS, I.BDBASEICMS, I.BDVLRICMS, ';
    WSQL = WSQL || '             PIS.BDCSTPIS BDCODCSTPIS, COF.BDCSTCOF BDCODCSTCOF, I.BDVL_BC_PIS, I.BDALIQ_PIS ,I.BDVLRPIS,I.BDVL_BC_COFINS, I.BDALIQ_COFINS, I.BDVLRCOFINS, I.BDCODNAT, ';
    WSQL = WSQL ||              'CID.BDCODUF BDCODUFEMP, IIF(ENQ.BDCODENQFED <> 3, 0 /*SN*/, IIF(ENQ.BDFORMATRIBUTACAO = 1,2 /*LP*/,1/*LR*/)) BDREGTRIBUTARIO,EMP.BDCARACTRIBUTARIA, VW.BDSUBSTRIB ';
    WSQL = WSQL ||       'from (select EMP.BDCODEMP, EMP.BDCARACTRIBUTARIA, EMP.BDCODCID ';
    WSQL = WSQL ||       '      from VW_TEMPRESAS_REF EMP ';
    WSQL = WSQL ||       '      where '||:PRCODEMP||') EMP ';      
    WSQL = WSQL ||       'left outer join VW_VEF_BASE_TEMPPAREST VW on (VW.BDCODEMP = EMP.BDCODEMP) ';
    WSQL = WSQL ||       'left outer join TCIDADE CID on (CID.BDCODCID = EMP.BDCODCID) ';
    WSQL = WSQL ||       'left outer join VW_TENQFED ENQ on (ENQ.BDCODEMP = EMP.BDCODEMP) ';
    WSQL = WSQL || '      left outer JOIN ( ';
    WSQL = WSQL || '           SELECT AUD.BDCHAVE, CAST(AUD.BDCODPROD AS VARCHAR(20)) BDCODPROD, AUD.BDCODUF, AUD.BDCODNATOPE, IIF(AUD.BDCARACTRIBUTARIATER = -1, 0, AUD.BDCARACTRIBUTARIATER) BDCARACTRIBUTARIATER, AUD.BDFINALIDADE,P.BDCODIGOEAN, AUD.BDCODNCM, ';
    WSQL = WSQL || '                  AUD.BDCODEMP,AUD.BDDATANOTA,AUD.BDMOVIMENTO,AUD.BDCODTER,AUD.BDDOCUMENTO, AUD.BDORDEM, AUD.BDORDEMPRO, AUD.BDCODCEST, AUD.BDDATAENVIO, AUD.BDSTATUS, Trim(PVINC.BDCODIAT) AS BDCODIAT ';
    WSQL = WSQL || '           FROM VEF_EMP_TAUDIMENDES AUD ';
    WSQL = WSQL || '           LEFT OUTER JOIN TCADPRO P ON (P.BDCODPROD = AUD.BDCODPROD) ';       
    WSQL = WSQL ||             'LEFT OUTER JOIN TCADPRO_VINC PVINC ON (PVINC.BDCODPROD = AUD.BDCODPROD AND PVINC.BDCODEMP = AUD.BDCODEMP) ';
    WSQL = WSQL || '           WHERE AUD.'||:PRCODEMP||' AND '||'AUD.BDDATANOTA BETWEEN '''|| :PRDATAINI ||''' AND '''|| :PRDATAFIM ||''' AND AUD.BDMOVIMENTO = 2 AND   AUD.BDREGREDZ = ''C425'' ';
    WSQL = WSQL || '         ) AUD on (AUD.BDCODEMP = EMP.BDCODEMP) ';
    WSQL = WSQL || '      JOIN VEF_EMP_TREDZC425 I ON (I.BDCODEMP = AUD.BDCODEMP AND I.BDCHAVE = AUD.BDCHAVE AND I.BDORDEMTOT = AUD.BDORDEM AND I.BDORDEMC425 = AUD.BDORDEMPRO) ';
    WSQL = WSQL || '      LEFT OUTER JOIN VEF_BASE_TTABCSTICMS C ON (C.BDCODCSTICMS = I.BDCODCSTICMS) ';
    WSQL = WSQL ||       'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON (PIS.BDCODCSTPIS = I.BDCODCSTPIS) ';
    WSQL = WSQL ||       'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON (COF.BDCODCSTCOF = I.BDCODCSTCOF) ';
    WSQL = WSQL || '      ) AUD ';
    WSQL = WSQL || 'JOIN VEF_EMP_TREGRASPRODUTOS R ON (R.BDUFNOTA = AUD.BDCODUF AND R.BDCODNAT = SUBSTRING(AUD.BDCODNATOPE FROM 1 FOR 4) AND COALESCE(AUD.BDCARACTRIBUTARIATER,0) = R.BDCARACTRIBUTARIATER AND R.BDFINALIDADE = AUD.BDFINALIDADE AND (AUD.BDCODPROD = R.BDCODPRODIMEND or AUD.BDCODIGOEAN = R.BDCODPRODIMEND or Trim(AUD.BDCODIAT) = R.BDCODPRODIMEND) ';
    WSQL = WSQL ||                                              ' AND R.BDCODUF = AUD.BDCODUFEMP AND R.BDREGTRIBUTARIO = AUD.BDREGTRIBUTARIO AND R.BDCARACTRIBUTARIA = AUD.BDCARACTRIBUTARIA ) ';
    WSQL = WSQL || 'JOIN VEF_BASE_TGRUPOIMENDES G ON (G.BDCODGRUPO = R.BDCODGRUPO) and (G.bdCODCEST = AUD.BDCODCEST) ';
    WSQL = WSQL || 'LEFT OUTER JOIN TCEST C ON (C.BDCODCEST = AUD.BDCODCEST) ';
    WSQL = WSQL || ' LEFT OUTER JOIN TNCM N ON (N.BDNCMPROD = AUD.BDCODNCM) ';
    WSQL = WSQL || 'WHERE ((AUD.BDDATAENVIO IS NULL OR AUD.BDDATAENVIO IS NULL) OR (SUBSTRING(G.BDDATARETORNO FROM 1 FOR 4)||SUBSTRING(G.BDDATARETORNO FROM 6 FOR 2)) = (SUBSTRING(AUD.BDDATAENVIO FROM 1 FOR 4)||SUBSTRING(AUD.BDDATAENVIO FROM 6 FOR 2))) ';
    WSQL = WSQL || 'and (iif(AUD.BDSUBSTRIB is null or AUD.BDSUBSTRIB = 0, r.bdsubstributario = 0, r.bdsubstributario = 1))';

    WSQL = WSQL || 'UNION ALL ';
    WSQL = WSQL || '/*AL?QUOTA C425*/ ';
    WSQL = WSQL || 'SELECT 0 BDCOMPARATIVO /*ORIGINAL*/, AUD.BDCODEMP,AUD.BDDATANOTA,AUD.BDMOVIMENTO,AUD.BDCODTER,AUD.BDCODNATOPE,AUD.BDDOCUMENTO, AUD.BDCODPROD, ';
    WSQL = WSQL || '       AUD.BDCSTICMS, AUD.BDALIQICMS, 0 BDREDBCICMS, IIF(AUD.BDALIQICMS > 0,AUD.BDBASEICMS,0) BDBCICMS, AUD.BDVLRICMS, 0 BDALIQFCP, 0 BDBCFCP, 0 BDVLRFCP, '''' BDAMPLEGAL,0 BDPERCDIFER, ';
    WSQL = WSQL || '       /*ICMSST*/ 0 BDALIQICMSST, 0 BDCSTICMSST, 0 BDBCICMSST, 0 BDVLRICMSST, 0 BDALIQFCPST ,0 BDBCICMSFCP, 0 BDVLRFCPST, ';
    WSQL = WSQL || '       /*PIS*/  AUD.BDCODCSTPIS BDCSTPIS, AUD.BDALIQ_PIS BDALIQPIS,AUD.BDVL_BC_PIS BDBASEPIS, AUD.BDVLRPIS, ';
    WSQL = WSQL || '       /*COFINS*/  AUD.BDCODCSTCOF BDCSTCOF, AUD.BDALIQ_COFINS BDALIQCOFINS, AUD.BDVL_BC_COFINS BDBASECOFINS, AUD.BDVLRCOFINS, '''' BDBASELEGALPISCOFINS, '''' BDBASELEGALCOF, ';
    WSQL = WSQL || '       /*OA*/ AUD.BDCODNAT,AUD.BDCODNCM, AUD.BDCODCEST, C.BDCLASSCEST, AUD.BDCODUF,AUD.BDCHAVE, AUD.BDORDEM, AUD.BDORDEMPRO,G.BDDATARETORNO,G.BDHORARETORNO, ';
    WSQL = WSQL || '       R.BDCHAVELOG, ' ||:PRSESSAO || ', AUD.BDSTATUS, N.BDCLASSIFICACAO ';
    WSQL = WSQL || 'FROM ( ';
    WSQL = WSQL || '      SELECT AUD.*, IIF(COALESCE(C.BDCSTICMS,'''') = '''',''000'',C.BDCSTICMS) BDCSTICMS, VA.BDALIQICMS BDALIQICMS, I.BDBASEICMS, I.BDVLRICMS, ';
    WSQL = WSQL || '             PIS.BDCSTPIS BDCODCSTPIS, COF.BDCSTCOF BDCODCSTCOF, I.BDVL_BC_PIS, I.BDALIQ_PIS ,I.BDVLRPIS, ';
    WSQL = WSQL || '             I.BDVL_BC_COFINS, I.BDALIQ_COFINS, I.BDVLRCOFINS, I.BDCODNAT, ';
    WSQL = WSQL ||              'CID.BDCODUF BDCODUFEMP, IIF(ENQ.BDCODENQFED <> 3, 0 /*SN*/, IIF(ENQ.BDFORMATRIBUTACAO = 1,2 /*LP*/,1/*LR*/)) BDREGTRIBUTARIO,EMP.BDCARACTRIBUTARIA, VW.BDSUBSTRIB ';
    WSQL = WSQL ||       'from (select EMP.BDCODEMP, EMP.BDCARACTRIBUTARIA, EMP.BDCODCID ';
    WSQL = WSQL ||       '      from VW_TEMPRESAS_REF EMP ';
    WSQL = WSQL ||       '      where '||:PRCODEMP||') EMP ';      
    WSQL = WSQL ||       'left outer join VW_VEF_BASE_TEMPPAREST VW on (VW.BDCODEMP = EMP.BDCODEMP) ';
    WSQL = WSQL ||       'left outer join TCIDADE CID on (CID.BDCODCID = EMP.BDCODCID) ';
    WSQL = WSQL ||       'left outer join VW_TENQFED ENQ on (ENQ.BDCODEMP = EMP.BDCODEMP) ';
    WSQL = WSQL || '      left outer JOIN ( ';
    WSQL = WSQL || '           SELECT AUD.BDCHAVE, CAST(AUD.BDCODPROD AS VARCHAR(20)) BDCODPROD, AUD.BDCODUF, AUD.BDCODNATOPE, IIF(AUD.BDCARACTRIBUTARIATER = -1, 0, AUD.BDCARACTRIBUTARIATER) BDCARACTRIBUTARIATER, AUD.BDFINALIDADE,P.BDCODIGOEAN, AUD.BDCODNCM, ';
    WSQL = WSQL || '                  AUD.BDCODEMP,AUD.BDDATANOTA,AUD.BDMOVIMENTO,AUD.BDCODTER,AUD.BDDOCUMENTO, AUD.BDORDEM, AUD.BDORDEMPRO, AUD.BDCODCEST, AUD.BDDATAENVIO, AUD.BDSTATUS, Trim(PVINC.BDCODIAT) AS BDCODIAT ';
    WSQL = WSQL || '           FROM VEF_EMP_TAUDIMENDES AUD ';
    WSQL = WSQL || '           LEFT OUTER JOIN TCADPRO P ON (P.BDCODPROD = AUD.BDCODPROD) ';      
    WSQL = WSQL ||             'LEFT OUTER JOIN TCADPRO_VINC PVINC ON (PVINC.BDCODPROD = AUD.BDCODPROD AND PVINC.BDCODEMP = AUD.BDCODEMP) ';
    WSQL = WSQL || '           WHERE AUD.'||:PRCODEMP||' AND '||'AUD.BDDATANOTA BETWEEN '''|| :PRDATAINI ||''' AND '''|| :PRDATAFIM ||''' AND AUD.BDMOVIMENTO = 2 AND   AUD.BDREGREDZ = ''C425'' ';
    WSQL = WSQL || '         ) AUD on (AUD.BDCODEMP = EMP.BDCODEMP) ';
    WSQL = WSQL || '      JOIN VEF_EMP_TREDZC425ALIQ I ON (I.BDCODEMP = AUD.BDCODEMP AND I.BDCHAVE = AUD.BDCHAVE AND I.BDORDEMICMS = AUD.BDORDEM AND I.BDORDEMC425 = AUD.BDORDEMPRO) ';
    WSQL = WSQL || '      LEFT OUTER JOIN VEF_EMP_TREDZVARALIQ VA ON (VA.BDCODEMP = I.BDCODEMP AND VA.BDCHAVE = I.BDCHAVE AND VA.BDORDEMICMS = I.BDORDEMICMS) ';
    WSQL = WSQL || '      LEFT OUTER JOIN VEF_BASE_TTABCSTICMS C ON (C.BDCODCSTICMS = I.BDCODCSTICMS) ';
    WSQL = WSQL ||       'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON (PIS.BDCODCSTPIS = I.BDCODCSTPIS) ';
    WSQL = WSQL ||       'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON (COF.BDCODCSTCOF = I.BDCODCSTCOF) ';
    WSQL = WSQL || '      ) AUD ';
    WSQL = WSQL || 'JOIN VEF_EMP_TREGRASPRODUTOS R ON (R.BDUFNOTA = AUD.BDCODUF AND R.BDCODNAT = SUBSTRING(AUD.BDCODNATOPE FROM 1 FOR 4) AND COALESCE(AUD.BDCARACTRIBUTARIATER,0) = R.BDCARACTRIBUTARIATER AND R.BDFINALIDADE = AUD.BDFINALIDADE AND (AUD.BDCODPROD = R.BDCODPRODIMEND or AUD.BDCODIGOEAN = R.BDCODPRODIMEND or Trim(AUD.BDCODIAT) = R.BDCODPRODIMEND) ';
    WSQL = WSQL ||                                              ' AND R.BDCODUF = AUD.BDCODUFEMP AND R.BDREGTRIBUTARIO = AUD.BDREGTRIBUTARIO AND R.BDCARACTRIBUTARIA = AUD.BDCARACTRIBUTARIA ) ';
    WSQL = WSQL || 'JOIN VEF_BASE_TGRUPOIMENDES G ON (G.BDCODGRUPO = R.BDCODGRUPO) and (G.bdCODCEST = AUD.BDCODCEST) ';
    WSQL = WSQL || 'LEFT OUTER JOIN TCEST C ON (C.BDCODCEST = AUD.BDCODCEST) ';
    WSQL = WSQL || ' LEFT OUTER JOIN TNCM N ON (N.BDNCMPROD = AUD.BDCODNCM) ';
    WSQL = WSQL || 'WHERE ((AUD.BDDATAENVIO IS NULL OR AUD.BDDATAENVIO IS NULL) OR (SUBSTRING(G.BDDATARETORNO FROM 1 FOR 4)||SUBSTRING(G.BDDATARETORNO FROM 6 FOR 2)) = (SUBSTRING(AUD.BDDATAENVIO FROM 1 FOR 4)||SUBSTRING(AUD.BDDATAENVIO FROM 6 FOR 2))) ';
    WSQL = WSQL || 'and (iif(AUD.BDSUBSTRIB is null or AUD.BDSUBSTRIB = 0, r.bdsubstributario = 0, r.bdsubstributario = 1))';

    WSQL = WSQL || 'UNION ALL ';
    WSQL = WSQL || '/*ORIGINAL 60I*/ ';
    WSQL = WSQL || 'SELECT 0 BDCOMPARATIVO /*ORIGINAL*/, AUD.BDCODEMP,AUD.BDDATANOTA,AUD.BDMOVIMENTO,AUD.BDCODTER,AUD.BDCODNATOPE,AUD.BDDOCUMENTO, AUD.BDCODPROD, ';
    WSQL = WSQL || '       AUD.BDCSTICMS,AUD.BDALIQICMS, 0 BDREDBCICMS, IIF(AUD.BDALIQICMS > 0,AUD.BDBASECALCICMS,0) BDBCICMS,BDVLRICMS, 0 BDALIQFCP, 0 BDBCFCP , 0 BDVLRFCP, '''' BDAMPLEGAL,0 BDPERCDIFER, ';
    WSQL = WSQL || '       /*ICMSST*/ 0 BDALIQICMSST, 0 BDCSTICMSST, 0 BDBCICMSST, 0 BDVLRICMSST, 0 BDALIQFCPST ,0 BDBCICMSFCP, 0 BDVLRFCPST, ';
    WSQL = WSQL || '       /*PIS*/  '''' BDCSTPIS, 0 BDALIQPIS, 0 BDBASEPIS,0 BDVLRPIS,/*COFINS*/ '''' BDCSTCOF, 0 BDALIQCOFINS, 0 BDBASECOFINS, 0 BDVLRCOFINS, '''' BDBASELEGALPISCOFINS, '''' BDBASELEGALCOF,  ';
    WSQL = WSQL || '       /*OA*/  IIF(RI.BDSIMBPDV = ''F'',5405,5102) BDCODNAT,AUD.BDCODNCM, AUD.BDCODCEST, C.BDCLASSCEST, AUD.BDCODUF,AUD.BDCHAVE, AUD.BDORDEM, AUD.BDORDEMPRO,G.BDDATARETORNO,G.BDHORARETORNO, ';
    WSQL = WSQL || '       R.BDCHAVELOG, ' ||:PRSESSAO || ', AUD.BDSTATUS, N.BDCLASSIFICACAO ';
    WSQL = WSQL || 'FROM ( ';
    WSQL = WSQL || '      SELECT AUD.*, C.BDCSTICMS, ZI.BDALIQICMS, ZI.BDBASECALCICMS, ZI.BDVLRICMS, ';
    WSQL = WSQL ||              'CID.BDCODUF BDCODUFEMP, IIF(ENQ.BDCODENQFED <> 3, 0 /*SN*/, IIF(ENQ.BDFORMATRIBUTACAO = 1,2 /*LP*/,1/*LR*/)) BDREGTRIBUTARIO,EMP.BDCARACTRIBUTARIA, VW.BDSUBSTRIB ';
    WSQL = WSQL ||       'from (select EMP.BDCODEMP, EMP.BDCARACTRIBUTARIA, EMP.BDCODCID ';
    WSQL = WSQL ||       '      from VW_TEMPRESAS_REF EMP ';
    WSQL = WSQL ||       '      where '||:PRCODEMP||') EMP ';      
    WSQL = WSQL ||       'left outer join VW_VEF_BASE_TEMPPAREST VW on (VW.BDCODEMP = EMP.BDCODEMP) ';
    WSQL = WSQL ||       'left outer join TCIDADE CID on (CID.BDCODCID = EMP.BDCODCID) ';
    WSQL = WSQL ||       'left outer join VW_TENQFED ENQ on (ENQ.BDCODEMP = EMP.BDCODEMP) ';
    WSQL = WSQL || '      left outer JOIN ( ';
    WSQL = WSQL || '           SELECT AUD.BDCHAVE, CAST(AUD.BDCODPROD AS VARCHAR(20)) BDCODPROD, AUD.BDCODUF, AUD.BDCODNATOPE, IIF(AUD.BDCARACTRIBUTARIATER = -1, 0, AUD.BDCARACTRIBUTARIATER) BDCARACTRIBUTARIATER, AUD.BDFINALIDADE,P.BDCODIGOEAN, AUD.BDCODNCM, ';
    WSQL = WSQL || '                  AUD.BDCODEMP,AUD.BDDATANOTA,AUD.BDMOVIMENTO,AUD.BDCODTER,AUD.BDDOCUMENTO, AUD.BDORDEM, AUD.BDORDEMPRO, AUD.BDCODCEST, AUD.BDDATAENVIO,AUD.BDCODNAT, AUD.BDSTATUS, Trim(PVINC.BDCODIAT) AS BDCODIAT ';
    WSQL = WSQL || '           FROM VEF_EMP_TAUDIMENDES AUD ';
    WSQL = WSQL || '           LEFT OUTER JOIN TCADPRO P ON (P.BDCODPROD = AUD.BDCODPROD) ';     
    WSQL = WSQL ||            'LEFT OUTER JOIN TCADPRO_VINC PVINC ON (PVINC.BDCODPROD = AUD.BDCODPROD AND PVINC.BDCODEMP = AUD.BDCODEMP) ';
    WSQL = WSQL || '           WHERE AUD.'||:PRCODEMP||' AND '||'AUD.BDDATANOTA BETWEEN '''|| :PRDATAINI ||''' AND '''|| :PRDATAFIM ||'''';
    WSQL = WSQL || '           AND AUD.BDMOVIMENTO = 2 AND AUD.BDREGREDZ = ''60I'' ';
    WSQL = WSQL || '         ) AUD on (AUD.BDCODEMP = EMP.BDCODEMP) ';
    WSQL = WSQL || '      JOIN VEF_EMP_TREDZ60I ZI ON (ZI.BDCODEMP = AUD.BDCODEMP AND ZI.BDCHAVE = AUD.BDCHAVE AND ZI.BDORDEM60I = AUD.BDORDEMPRO) ';
    WSQL = WSQL || '      LEFT OUTER join VEF_BASE_TTABCSTICMS C on (C.BDCODCSTICMS = ZI.BDCODCSTICMS) ';
    WSQL = WSQL || '      ) AUD ';
    WSQL = WSQL || 'JOIN VEF_EMP_TREGRASPRODUTOS R ON (R.BDUFNOTA = AUD.BDCODUF AND R.BDCODNAT = SUBSTRING(AUD.BDCODNATOPE FROM 1 FOR 4) AND COALESCE(AUD.BDCARACTRIBUTARIATER,0) = R.BDCARACTRIBUTARIATER AND R.BDFINALIDADE = AUD.BDFINALIDADE AND (AUD.BDCODPROD = R.BDCODPRODIMEND or AUD.BDCODIGOEAN = R.BDCODPRODIMEND or Trim(AUD.BDCODIAT) = R.BDCODPRODIMEND) ';
    WSQL = WSQL ||                                              ' AND R.BDCODUF = AUD.BDCODUFEMP AND R.BDREGTRIBUTARIO = AUD.BDREGTRIBUTARIO AND R.BDCARACTRIBUTARIA = AUD.BDCARACTRIBUTARIA) ';
    WSQL = WSQL || 'JOIN VEF_BASE_TGRUPOIMENDES G ON (G.BDCODGRUPO = R.BDCODGRUPO) and (G.bdCODCEST = AUD.BDCODCEST) ';
    WSQL = WSQL || 'JOIN VEF_EMP_TREGRASIMENDES RI ON (RI.BDCODGRUPO = G.BDCODGRUPO AND RI.BDCODUF = AUD.BDCODUF AND RI.BDCODNATOPE = AUD.BDCODNATOPE AND RI.BDFINALIDADE = AUD.BDFINALIDADE AND COALESCE(AUD.BDCARACTRIBUTARIATER,0) = RI.BDCARACTRIBUTARIATER) ';
    WSQL = WSQL || 'LEFT OUTER JOIN TCEST C ON (C.BDCODCEST = AUD.BDCODCEST) ';
    WSQL = WSQL || ' LEFT OUTER JOIN TNCM N ON (N.BDNCMPROD = AUD.BDCODNCM) ';
    WSQL = WSQL || 'WHERE ((AUD.BDDATAENVIO IS NULL OR AUD.BDDATAENVIO IS NULL) OR (SUBSTRING(G.BDDATARETORNO FROM 1 FOR 4)||SUBSTRING(G.BDDATARETORNO FROM 6 FOR 2)) = (SUBSTRING(AUD.BDDATAENVIO FROM 1 FOR 4)||SUBSTRING(AUD.BDDATAENVIO FROM 6 FOR 2))) ';
    WSQL = WSQL || 'and (iif(AUD.BDSUBSTRIB is null or AUD.BDSUBSTRIB = 0, r.bdsubstributario = 0, r.bdsubstributario = 1))';

    WSQL = WSQL || 'UNION ALL ';
    WSQL = WSQL || '/*ORIGINAL C470*/ ';
    WSQL = WSQL || 'SELECT 0 BDCOMPARATIVO /*ORIGINAL*/, AUD.BDCODEMP,AUD.BDDATANOTA,AUD.BDMOVIMENTO,AUD.BDCODTER,AUD.BDCODNATOPE,AUD.BDDOCUMENTO, AUD.BDCODPROD, ';
    WSQL = WSQL || '       AUD.BDCSTICMS, AUD.BDALIQICMS, 0 BDREDBCICMS, IIF(AUD.BDALIQICMS > 0,AUD.BDVLRTOTPRO,0) BDBCICMS, AUD.BDVLRICMS, 0 BDALIQFCP, 0 BDBCFCP, 0 BDVLRFCP, '''' BDAMPLEGAL,0 BDPERCDIFER, ';
    WSQL = WSQL || '       /*ICMSST*/ 0 BDALIQICMSST, 0 BDCSTICMSST, 0 BDBCICMSST, 0 BDVLRICMSST, 0 BDALIQFCPST ,0 BDBCICMSFCP, 0 BDVLRFCPST, ';
    WSQL = WSQL || '       /*PIS*/ IIF(CHAR_LENGTH(AUD.BDCODCSTPIS) = 1, ''0''||AUD.BDCODCSTPIS,AUD.BDCODCSTPIS) BDCSTPIS,AUD.BDALIQ_PIS BDALIQPIS, AUD.BDVL_BC_PIS BDBASEPIS, AUD.BDVLRPIS , ';
    WSQL = WSQL || '       /*COFINS*/ IIF(CHAR_LENGTH(AUD.BDCODCSTCOF) = 1, ''0''||AUD.BDCODCSTCOF,AUD.BDCODCSTCOF)  BDCSTCOF,AUD.BDALIQ_COFINS BDALIQCOFINS, AUD.BDVL_BC_COFINS BDBASECOFINS, AUD.BDVLRCOFINS, '''' BDBASELEGALPISCOFINS, '''' BDBASELEGALCOF, ';
    WSQL = WSQL || '       /*OA*/ AUD.BDCODNAT,AUD.BDCODNCM, AUD.BDCODCEST, C.BDCLASSCEST, AUD.BDCODUF,AUD.BDCHAVE, AUD.BDORDEM, AUD.BDORDEMPRO,G.BDDATARETORNO,G.BDHORARETORNO, ';
    WSQL = WSQL || '       R.BDCHAVELOG, ' ||:PRSESSAO || ', AUD.BDSTATUS, N.BDCLASSIFICACAO ';
    WSQL = WSQL || 'FROM ( ';
    WSQL = WSQL || '      SELECT AUD.*, C.BDCSTICMS, IT.BDALIQICMS, IT.BDVLRTOTPRO, IT.BDVLRICMS,PIS.BDCSTPIS BDCODCSTPIS, IT.BDVL_BC_PIS, IT.BDALIQ_PIS, IT.BDVLRPIS,COF.BDCSTCOF BDCODCSTCOF, IT.BDVL_BC_COFINS, IT.BDALIQ_COFINS, IT.BDVLRCOFINS, IT.BDCODNAT, ';
    WSQL = WSQL ||              'CID.BDCODUF BDCODUFEMP, IIF(ENQ.BDCODENQFED <> 3, 0 /*SN*/, IIF(ENQ.BDFORMATRIBUTACAO = 1,2 /*LP*/,1/*LR*/)) BDREGTRIBUTARIO,EMP.BDCARACTRIBUTARIA, VW.BDSUBSTRIB ';
    WSQL = WSQL ||       'from (select EMP.BDCODEMP, EMP.BDCARACTRIBUTARIA, EMP.BDCODCID ';
    WSQL = WSQL ||       '      from VW_TEMPRESAS_REF EMP ';
    WSQL = WSQL ||       '      where '||:PRCODEMP||') EMP ';      
    WSQL = WSQL ||       'left outer join VW_VEF_BASE_TEMPPAREST VW on (VW.BDCODEMP = EMP.BDCODEMP) ';
    WSQL = WSQL ||       'left outer join TCIDADE CID on (CID.BDCODCID = EMP.BDCODCID) ';
    WSQL = WSQL ||       'left outer join VW_TENQFED ENQ on (ENQ.BDCODEMP = EMP.BDCODEMP) ';
    WSQL = WSQL || '      left outer JOIN ( ';
    WSQL = WSQL || '           SELECT AUD.BDCHAVE, CAST(AUD.BDCODPROD AS VARCHAR(20)) BDCODPROD, AUD.BDCODUF, AUD.BDCODNATOPE, IIF(AUD.BDCARACTRIBUTARIATER = -1, 0, AUD.BDCARACTRIBUTARIATER) BDCARACTRIBUTARIATER, AUD.BDFINALIDADE,P.BDCODIGOEAN, AUD.BDCODNCM, ';
    WSQL = WSQL || '                  AUD.BDCODEMP,AUD.BDDATANOTA,AUD.BDMOVIMENTO,AUD.BDCODTER,AUD.BDDOCUMENTO, AUD.BDORDEM, AUD.BDORDEMPRO, AUD.BDCODCEST, AUD.BDDATAENVIO, AUD.BDSTATUS, Trim(PVINC.BDCODIAT) AS BDCODIAT ';
    WSQL = WSQL || '           FROM VEF_EMP_TAUDIMENDES AUD ';
    WSQL = WSQL || '           LEFT OUTER JOIN TCADPRO P ON (P.BDCODPROD = AUD.BDCODPROD) ';     
    WSQL = WSQL ||            'LEFT OUTER JOIN TCADPRO_VINC PVINC ON (PVINC.BDCODPROD = AUD.BDCODPROD AND PVINC.BDCODEMP = AUD.BDCODEMP) ';
    WSQL = WSQL || '           WHERE AUD.'||:PRCODEMP||' AND '||'AUD.BDDATANOTA BETWEEN '''|| :PRDATAINI ||''' AND '''|| :PRDATAFIM ||''' AND AUD.BDMOVIMENTO = 2 AND AUD.BDREGREDZ = ''C470'' ';
    WSQL = WSQL || '         ) AUD on (AUD.BDCODEMP = EMP.BDCODEMP) ';
    WSQL = WSQL || '      JOIN VEF_EMP_TITEMDOCECF IT ON (IT.BDCODEMP = AUD.BDCODEMP AND IT.BDCHAVE = AUD.BDCHAVE AND IT.BDORDEMDOCECF =AUD.BDORDEM AND IT.BDORDEMITEM = AUD.BDORDEMPRO) ';
    WSQL = WSQL || '      LEFT OUTER JOIN VEF_BASE_TTABCSTICMS C ON (C.BDCODCSTICMS = IT.BDCODCSTICMS) ';
    WSQL = WSQL ||       'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON (PIS.BDCODCSTPIS = IT.BDCODCSTPIS) ';
    WSQL = WSQL ||       'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON (COF.BDCODCSTCOF = IT.BDCODCSTCOF) ';
    WSQL = WSQL || '      ) AUD ';
    WSQL = WSQL || 'JOIN VEF_EMP_TREGRASPRODUTOS R ON (R.BDUFNOTA = AUD.BDCODUF AND R.BDCODNAT = SUBSTRING(AUD.BDCODNATOPE FROM 1 FOR 4) AND COALESCE(AUD.BDCARACTRIBUTARIATER,0) = R.BDCARACTRIBUTARIATER AND R.BDFINALIDADE = AUD.BDFINALIDADE AND (AUD.BDCODPROD = R.BDCODPRODIMEND or AUD.BDCODIGOEAN = R.BDCODPRODIMEND or Trim(AUD.BDCODIAT) = R.BDCODPRODIMEND) ';
    WSQL = WSQL ||                                              ' AND R.BDCODUF = AUD.BDCODUFEMP AND R.BDREGTRIBUTARIO = AUD.BDREGTRIBUTARIO AND R.BDCARACTRIBUTARIA = AUD.BDCARACTRIBUTARIA) ';
    WSQL = WSQL || 'JOIN VEF_BASE_TGRUPOIMENDES G ON (G.BDCODGRUPO = R.BDCODGRUPO) and (G.bdCODCEST = AUD.BDCODCEST)';
    WSQL = WSQL || 'LEFT OUTER JOIN TCEST C ON (C.BDCODCEST = AUD.BDCODCEST) ';
    WSQL = WSQL || ' LEFT OUTER JOIN TNCM N ON (N.BDNCMPROD = AUD.BDCODNCM) ';
    WSQL = WSQL || 'WHERE ((AUD.BDDATAENVIO IS NULL OR AUD.BDDATAENVIO IS NULL) OR (SUBSTRING(G.BDDATARETORNO FROM 1 FOR 4)||SUBSTRING(G.BDDATARETORNO FROM 6 FOR 2)) = (SUBSTRING(AUD.BDDATAENVIO FROM 1 FOR 4)||SUBSTRING(AUD.BDDATAENVIO FROM 6 FOR 2))) ';
    WSQL = WSQL || 'and (iif(AUD.BDSUBSTRIB is null or AUD.BDSUBSTRIB = 0, r.bdsubstributario = 0, r.bdsubstributario = 1))';
    WSQL = WSQL || 'UNION ALL /*AUDITORIA*/ ';
    WSQL = WSQL || 'SELECT AUD.BDCOMPARATIVO /*AUDITORIA*/, AUD.BDCODEMP,AUD.BDDATANOTA,AUD.BDMOVIMENTO,AUD.BDCODTER,AUD.BDCODNATOPE,AUD.BDDOCUMENTO, AUD.BDCODPROD, ';
    WSQL = WSQL || '       Coalesce(AUD.BDCSON,AUD.BDCSTICMS) BDCSTICMS,AUD.BDALIQICMS,AUD.BDREDBCICMS, IIF(AUD.BDALIQICMS > 0,AUD.BDBCICMS,0) BDBASEICMS, (AUD.BDBCICMS*(AUD.BDALIQICMS/100)) BDVLRICMS, 0 BDALIQFCP, 0 BDBCFCP, 0 BDVLRFCP, AUD.BDAMPLEGAL, 0 BDPERCDIFER, ';
    WSQL = WSQL || '       /*ICMSST*/IIF(BDISICMSST = ''TRUE'',Coalesce(AUD.BDCSON,AUD.BDCSTICMS),0) BDCSTICMSST, 0 BDALIQICMSST, 0 BDBCICMSST, 0 BDVLRICMSST, 0 BDALIQFCPST ,0 BDBCICMSFCP, 0 BDVLRFCPST, ';
    WSQL = WSQL || '       /*PIS*/ IIF(CHAR_LENGTH(AUD.BDCSTPIS) = 1, ''0''||AUD.BDCSTPIS,AUD.BDCSTPIS) BDCSTPIS, AUD.BDALIQPIS, SALP(AUD.BDBASEPIS - IIF(AUD.BDIAT_PISCOF_SEM_ICMS = ''TRUE'', (AUD.BDBCICMS*(AUD.BDALIQICMS/100)), 0)) AS BDBASEPIS, (SALP(AUD.BDBASEPIS - IIF(AUD.BDIAT_PISCOF_SEM_ICMS = ''TRUE'', (AUD.BDBCICMS*(AUD.BDALIQICMS/100)), 0))*(AUD.BDALIQPIS/100)) BDVLRPIS, ';
    WSQL = WSQL || '       /*COFINS*/ IIF(CHAR_LENGTH(AUD.BDCSTCOF) = 1, ''0''||AUD.BDCSTCOF,AUD.BDCSTCOF) BDCSTCOF, AUD.BDALIQCOFINS, SALP(AUD.BDBASECOFINS - IIF(AUD.BDIAT_PISCOF_SEM_ICMS = ''TRUE'', (AUD.BDBCICMS*(AUD.BDALIQICMS/100)), 0)) AS BDBASECOFINS, (SALP(AUD.BDBASECOFINS - IIF(AUD.BDIAT_PISCOF_SEM_ICMS = ''TRUE'', (AUD.BDBCICMS*(AUD.BDALIQICMS/100)), 0))*(AUD.BDALIQCOFINS/100)) BDVLRCOFINS, '''' BDBASELEGALPISCOFINS, '''' BDBASELEGALCOF, ';
    WSQL = WSQL || '       /*OA*/ AUD.BDCODNAT, AUD.BDCODNCM, AUD.BDCODCEST,AUD.BDCLASSCEST, AUD.BDCODUF,AUD.BDCHAVE, AUD.BDORDEM, AUD.BDORDEMPRO,AUD.BDDATARETORNO,AUD.BDHORARETORNO, ';
    WSQL = WSQL || '       AUD.BDCHAVELOG, ' ||:PRSESSAO || ', AUD.BDSTATUS, AUD.BDCLASSIFICACAO ';
    WSQL = WSQL || ' FROM ( ';
    WSQL = WSQL || '      SELECT 1 BDCOMPARATIVO /*AUDITORIA*/, AUD.BDCODEMP,AUD.BDDATANOTA,AUD.BDMOVIMENTO,AUD.BDCODTER,AUD.BDCODNATOPE,AUD.BDDOCUMENTO, AUD.BDCODPROD, AUD.BDIAT_PISCOF_SEM_ICMS, ';
    WSQL = WSQL || '             /*ICMS*/AUD.BDCSTRED BDCSTICMS, AUD.BDCODGRUPO, ';
    WSQL = WSQL || '             AUD.BDALIQICMSPDV BDALIQICMS, AUD.BDREDBCICMS, IIF(AUD.BDBASECALCICMS > 0,AUD.BDBASECALCICMS,AUD.BDVLRNOTAREDZ) BDBCICMS, AUD.BDAMPLEGAL,/*ICMSST*/ IIF((AUD.BDCSTICMS = 60 OR AUD.BDCSON = 500), ''TRUE'', ''FALSE'') BDISICMSST, ';
    WSQL = WSQL || '              /*PIS*/ IIF(AUD.BDREGREDZ = ''60I'','''',AUD.BDCSTPISCOFINSPDVSAI) BDCSTPIS, IIF(AUD.BDREGREDZ = ''60I'',0,AUD.BDALIPISPDV) BDALIQPIS, IIF(AUD.BDREGREDZ = ''60I'',0,IIF(BDCSTPISCOFINSPDVSAI IN (4,7,8,9) AND BDALIPISPDV = 0, 0, AUD.BDVLRNOTAREDZ)) BDBASEPIS, ';
    WSQL = WSQL || '              /*COFINS*/ IIF(AUD.BDREGREDZ = ''60I'','''',AUD.BDCSTPISCOFINSPDVSAI) BDCSTCOF, IIF(AUD.BDREGREDZ = ''60I'',0,AUD.BDALIQCOFINSPDV) BDALIQCOFINS,IIF(AUD.BDREGREDZ = ''60I'',0,IIF(BDCSTPISCOFINSPDVSAI IN (4,7,8,9) AND BDALIPISPDV = 0, 0, AUD.BDVLRNOTAREDZ)) BDBASECOFINS, ';
    WSQL = WSQL || '              /*OA*/ AUD.BDCODNAT, AUD.BDCODNCMG BDCODNCM, AUD.BDCODCEST, AUD.BDCLASSCEST, AUD.BDCODUF,AUD.BDCHAVE, AUD.BDORDEM, AUD.BDORDEMPRO, AUD.BDDATARETORNO,AUD.BDHORARETORNO, AUD.BDCHAVELOG, AUD.BDSTATUS, AUD.BDCSON, AUD.BDCLASSIFICACAO ';
    WSQL = WSQL || '      FROM ( ';
    WSQL = WSQL || '            SELECT AUD.*, /*ICMS*/coalesce(coalesce(RI.BDCSONICMSPDV,(substring(I.bdcsticms FROM 1 FOR 1) || IIF(char_length(RI.BDCSTICMSPDV) = 1,''0'' || RI.BDCSTICMSPDV, RI.BDCSTICMSPDV))), coalesce(RI.BDCSONICMSPDV,(substring(I.bdcsticms FROM 1 FOR 1) || IIF(char_length(RI.BDCSTICMS) = 1,''0'' || RI.BDCSTICMS, RI.BDCSTICMS)))) BDCSTRED, G.BDCODGRUPO, RI.BDALIQICMSPDV, RI.BDREDBCICMS, RI.BDAMPLEGAL, RI.BDCSTICMS, RI.BDCSON, ';
    WSQL = WSQL || '                   RI.BDCSTPISCOFINSPDVSAI, RI.BDALIQCOFINSPDV, RI.BDALIPISPDV, IIF(RI.BDSIMBPDV = ''F'',5405,5102) BDCODNAT,R.BDCHAVELOG, ';
    WSQL = WSQL || '                   G.BDCODNCM BDCODNCMG, G.BDCODCEST, C.BDCLASSCEST,G.BDDATARETORNO,G.BDHORARETORNO, IIF(AUD.BDREGREDZ = ''60I'',IIF(((AUD.BDBASEICMS - (AUD.BDVLRNOTAREDZ*AUD.BDQTDITEM))*1) > 0.05,(AUD.BDVLRNOTAREDZ*AUD.BDQTDITEM),AUD.BDBASEICMS),0) BDBASECALCICMS, N.BDCLASSIFICACAO ';
    WSQL = WSQL || '            FROM ( ';
    WSQL = WSQL || '                  SELECT AUD.*,CID.BDCODUF BDCODUFEMP, IIF(ENQ.BDCODENQFED <> 3, 0 /*SN*/, IIF(ENQ.BDFORMATRIBUTACAO = 1,2 /*LP*/,1/*LR*/)) BDREGTRIBUTARIO,EMP.BDCARACTRIBUTARIA, VW.BDSUBSTRIB, EMP.BDIAT_PISCOF_SEM_ICMS ';
    WSQL = WSQL ||                   'from (select EMP.BDCODEMP, EMP.BDCARACTRIBUTARIA, EMP.BDCODCID, EMP.BDIAT_PISCOF_SEM_ICMS ';
    WSQL = WSQL ||                   '      from VW_TEMPRESAS_REF EMP ';
    WSQL = WSQL ||                   '      where '||:PRCODEMP||') EMP ';
    WSQL = WSQL ||                   'left outer join VW_VEF_BASE_TEMPPAREST VW on (VW.BDCODEMP = EMP.BDCODEMP) ';
    WSQL = WSQL ||                   'left outer join TCIDADE CID on (CID.BDCODCID = EMP.BDCODCID) ';
    WSQL = WSQL ||                   'left outer join VW_TENQFED ENQ on (ENQ.BDCODEMP = EMP.BDCODEMP) ';
    WSQL = WSQL || '          left outer JOIN ( ';
    WSQL = WSQL || '                  SELECT AUD.BDCHAVE, CAST(AUD.BDCODPROD AS VARCHAR(20)) BDCODPROD, AUD.BDCODUF, AUD.BDCODNATOPE, AUD.BDFINALIDADE, IIF(AUD.BDCARACTRIBUTARIATER = -1, 0, AUD.BDCARACTRIBUTARIATER) BDCARACTRIBUTARIATER,P.BDCODIGOEAN, AUD.BDCODNCM, ';
    WSQL = WSQL || '                         AUD.BDCODEMP,AUD.BDDATANOTA,AUD.BDMOVIMENTO,AUD.BDCODTER,AUD.BDDOCUMENTO, COALESCE(AUD.BDVLRNOTAREDZ,0)  BDVLRNOTAREDZ, AUD.BDORDEM, AUD.BDORDEMPRO, AUD.BDDATAENVIO,AUD.BDREGREDZ, AUD.BDBASEICMS,AUD.BDQTDITEM, AUD.BDSTATUS, Trim(PVINC.BDCODIAT) AS BDCODIAT  ';
    WSQL = WSQL || '                  FROM VEF_EMP_TAUDIMENDES AUD ';
    WSQL = WSQL || '                  LEFT OUTER JOIN TCADPRO P ON (P.BDCODPROD = AUD.BDCODPROD) ';
    WSQL = WSQL ||             'LEFT OUTER JOIN TCADPRO_VINC PVINC ON (PVINC.BDCODPROD = AUD.BDCODPROD AND PVINC.BDCODEMP = AUD.BDCODEMP) ';
    WSQL = WSQL || '           WHERE AUD.'||:PRCODEMP||' AND '||'AUD.BDDATANOTA BETWEEN '''|| :PRDATAINI ||''' AND '''|| :PRDATAFIM ||'''';
    WSQL = WSQL || '                  AND AUD.BDMOVIMENTO = 2 ';
    WSQL = WSQL || '                 ) AUD on (AUD.BDCODEMP = EMP.BDCODEMP) ';
    WSQL = WSQL || '                 ) AUD ';
    WSQL = WSQL || '           JOIN VEF_EMP_TREGRASPRODUTOS R ON (R.BDUFNOTA = AUD.BDCODUF AND R.BDCODNAT = SUBSTRING(AUD.BDCODNATOPE FROM 1 FOR 4) AND COALESCE(AUD.BDCARACTRIBUTARIATER,0) = R.BDCARACTRIBUTARIATER AND R.BDFINALIDADE = AUD.BDFINALIDADE AND (AUD.BDCODPROD = R.BDCODPRODIMEND or AUD.BDCODIGOEAN = R.BDCODPRODIMEND or Trim(AUD.BDCODIAT) = R.BDCODPRODIMEND) ';
    WSQL = WSQL ||                                              ' AND R.BDCODUF = AUD.BDCODUFEMP AND R.BDREGTRIBUTARIO = AUD.BDREGTRIBUTARIO AND R.BDCARACTRIBUTARIA = AUD.BDCARACTRIBUTARIA) ';
    WSQL = WSQL || '           JOIN VEF_BASE_TGRUPOIMENDES G ON (G.BDCODGRUPO = R.BDCODGRUPO) ';
    WSQL = WSQL || '           JOIN VEF_EMP_TREGRASIMENDES RI ON (RI.BDCODGRUPO = G.BDCODGRUPO AND RI.BDCODUF = AUD.BDCODUF AND SUBSTRING(RI.BDCODNATOPE FROM 1 FOR 4)= SUBSTRING(AUD.BDCODNATOPE FROM 1 FOR 4) AND RI.BDFINALIDADE = AUD.BDFINALIDADE AND COALESCE(AUD.BDCARACTRIBUTARIATER,0) = RI.BDCARACTRIBUTARIATER) ';
    WSQL = WSQL || '           LEFT OUTER JOIN TCEST C ON (C.BDCODCEST = G.BDCODCEST) ';
    WSQL = WSQL || '           LEFT OUTER JOIN TNCM N ON (N.BDNCMPROD = G.BDCODNCM) ';
    WSQL = WSQL || '           LEFT OUTER JOIN VEF_EMP_TITEMDOCECF PRODECF ON (PRODECF.BDCODEMP = AUD.BDCODEMP AND PRODECF.BDCHAVE = AUD.BDCHAVE AND PRODECF.BDCODPROD = AUD.BDCODPROD AND PRODECF.BDORDEMITEM = AUD.BDORDEMPRO)';
    WSQL = WSQL || '           LEFT OUTER JOIN VEF_EMP_TREDZC425 PROD425 ON (PROD425.BDCODEMP = AUD.BDCODEMP AND PROD425.BDCHAVE = AUD.BDCHAVE AND PROD425.BDCODPROD = AUD.BDCODPROD AND PROD425.BDORDEMC425 = AUD.BDORDEMPRO)';
    WSQL = WSQL || '           LEFT OUTER JOIN VEF_EMP_TREDZC425ALIQ PROD425A ON (PROD425A.BDCODEMP = AUD.BDCODEMP AND PROD425A.BDCHAVE = AUD.BDCHAVE AND PROD425A.BDCODPROD = AUD.BDCODPROD AND PROD425A.BDORDEMC425 = AUD.BDORDEMPRO)';
    WSQL = WSQL || '           LEFT OUTER JOIN VEF_EMP_TREDZ60I PRODSINT ON (PRODSINT.BDCODEMP = AUD.BDCODEMP AND PRODSINT.BDCHAVE = AUD.BDCHAVE AND PRODSINT.BDCODPROD = AUD.BDCODPROD AND PRODSINT.BDORDEM60I = AUD.BDORDEMPRO)';
    WSQL = WSQL || '           LEFT OUTER JOIN VEF_BASE_TTABCSTICMS I ON (I.BDCODCSTICMS = COALESCE(PRODECF.BDCODCSTICMS,PROD425.BDCODCSTICMS, PRODSINT.BDCODCSTICMS, PROD425A.BDCODCSTICMS))';
    WSQL = WSQL || '           WHERE ((AUD.BDDATAENVIO IS NULL OR AUD.BDDATAENVIO IS NULL) OR (SUBSTRING(G.BDDATARETORNO FROM 1 FOR 4)||SUBSTRING(G.BDDATARETORNO FROM 6 FOR 2)) = (SUBSTRING(AUD.BDDATAENVIO FROM 1 FOR 4)||SUBSTRING(AUD.BDDATAENVIO FROM 6 FOR 2))) ';
    WSQL = WSQL || ' and (iif(AUD.BDSUBSTRIB is null or AUD.BDSUBSTRIB = 0, r.bdsubstributario = 0, r.bdsubstributario = 1))) AUD ';
    WSQL = WSQL || '   ) AUD; ';
    
    EXECUTE STATEMENT(WSQL);
END^


create or alter procedure SP_AUDITANOTAS_IMENDES (
    PRCODEMP varchar(30000),
    PRDATAINI date,
    PRDATAFIM date,
    PRSESSAO integer,
    PRCOMPARATIVO integer = -1,
    PRSOSELECT varchar(5) = 'FALSE',
    PRENTRADA varchar(5) = 'TRUE',
    PRSAIDA varchar(5) = 'TRUE',
    PRREDZ varchar(5) = 'TRUE')
as
declare variable WREF varchar(6);
BEGIN
    DELETE FROM TMP_VEF_EMP_RETORNOIMENDES_TEMP WHERE BDSESSAO = :PRSESSAO;
    
    WREF = (SELECT BDAAAAMM FROM AAAAMM(:PRDATAINI));
    EXECUTE PROCEDURE SP_SETA_COMPETENCIA(WREF); 
    --EXECUTE PROCEDURE sp_seta_competencia(SUBSTRING(prdataini FROM 1 FOR 4)||SUBSTRING(prdataini FROM 6 FOR 2));
    
    if (PRENTRADA = 'TRUE') then
      BEGIN
          EXECUTE PROCEDURE SP_AUDITANOTAS_IMENDES_ENT(:PRCODEMP,:PRDATAINI,:PRDATAFIM,:PRSESSAO, CAST(:WREF AS INTEGER));
      END

    if (PRSAIDA = 'TRUE') then
      BEGIN
          EXECUTE PROCEDURE SP_AUDITANOTAS_IMENDES_SAI(:PRCODEMP,:PRDATAINI,:PRDATAFIM,:PRSESSAO, CAST(:WREF AS INTEGER));
      END

    if (PRREDZ = 'TRUE') then
      BEGIN
          EXECUTE PROCEDURE SP_AUDITANOTAS_IMENDES_REDZ(:PRCODEMP,:PRDATAINI,:PRDATAFIM,:PRSESSAO);
      END

    IF (PRSOSELECT = 'FALSE') THEN
       BEGIN
         EXECUTE PROCEDURE SP_AUDITANOTAS_IMENDES_UPDT(:PRCODEMP,:PRDATAINI,:PRDATAFIM,:PRSESSAO);
       END

  if (:PRSESSAO = 0) then
      DELETE FROM TMP_VEF_EMP_RETORNOIMENDES_TEMP WHERE BDSESSAO = 0;
END^

CREATE OR ALTER procedure SP_CARREGA_SIM_IM_REFTRIB (
    PRSESSAO integer,
    PRNOVO boolean)
as
declare variable WCONTA integer;
declare variable WSQL varchar(30000) collate WIN_PTBR;
declare variable WCONTA2 integer;
begin
   if (:prNOVO) then
      begin
         DELETE FROM TMP_VEF_EMP_IM_SIMULADOR_REF_TRIB_TEMP WHERE BDSESSAO = :prSESSAO;
      end

   SELECT COUNT(*) FROM TMP_VEF_EMP_IM_SIMULADOR_REF_TRIB_TEMP WHERE BDSESSAO = :prSESSAO INTO :WCONTA;

   --Vamos jogar os dados carregados para a tabela de ambiente
   wSQL = 'merge into TMP_VEF_EMP_IM_SIMULADOR_REF_TRIB_TEMP SIM
           using (select ' || :prSessao || ' AS BDSESSAO,
                             REF.BDCHAVE, REF.BDCODEMP, ENV.BDORDEM, ENV.BDCODTER, ENV.BDCODPROD, ENV.BDEMITENTE, ENV.BDMOVIMENTO, ENV.BDCFOP, coalesce(RET.BDANORETORNO,0) AS BDANORETORNO,
                             RET.BDIM_ICMS_ALIQUOTA, RET.BDIM_ICMS_VALOR, RET.BDIM_PIS_COFINS_BASE, RET.BDIM_PIS_VALOR, RET.BDIM_COFINS_VALOR,
                             RET.BDIM_IPI_ALIQUOTA, RET.BDIM_IPI_VALOR, RET.BDIM_ISS_ALIQUOTA, RET.BDIM_ISS_VALOR, RET.BDIM_IS_ALIQ,
                             RET.BDIM_IS_VALOR, RET.BDIM_CBS_ALIQ, RET.BDIM_CBS_VALOR, RET.BDIM_IBS_ALIQ, RET.BDIM_IBS_VALOR, TERC.BDNOMETER,
                             TERC.BDPRURALTER, TERC.BDENQSIMPLESFEDTER, TERC.BDSIGLAUF, PRO.BDNCMPROD, PRO.BDDESCPROD, NCM.BDCLASSIFICACAO,
                             (coalesce(ENV.bdvlricms,0) + coalesce(env.bdvlrpis,0) + coalesce(env.bdvlripi,0) + coalesce(env.bdvlrcofins,0) + coalesce(env.bdvlrissqn,0) + coalesce(env.bdvlr_is,0) + coalesce(env.bdvlr_cbs,0) + coalesce(env.bdvlr_ibs,0)) as BDTOTALIMPOSTOSANTES,
                             (coalesce(RET.bdim_icms_valor,0) + coalesce(ret.bdim_pis_valor,0) + coalesce(ret.bdim_cofins_valor,0) + coalesce(ret.bdim_ipi_valor,0) + coalesce(ret.bdim_iss_valor,0) + coalesce(ret.bdim_is_valor,0) + coalesce(ret.bdim_cbs_valor,0) + coalesce(ret.bdim_ibs_valor,0)) as BDTOTALIMPOSTOAGORA,
                             ENV.BDVLRICMS, ENV.bdvlrissqn, ENV.BDVLRPIS, ENV.BDVLRCOFINS, ENV.BDVLRIPI, ENV.bdvlr_cbs, ENV.BDVLR_IBS, ENV.BDVLR_IS, ENV.BDVLRITEM, BDORIGEM, REF.BDREFERENCIA,
                             RET.BDIM_IBS_RED_ALIQ, RET.BDIM_IBS_MUN_RED_ALIQ, RET.BDIM_CBS_RED_ALIQ
                      from VEF_EMP_IM_SIMULADOR_REF_TRIB REF
                      inner join TMP_EMPRESAS_SELECT SEL on SEL.BDCODEMP = REF.BDCODEMP
                      inner join VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD ENV on REF.BDCHAVE = ENV.BDCHAVE
                        left join SP_CONSULTA_TERCEIROREF(REF.BDREFERENCIA, ENV.BDCODTER) TERC on (1 = 1)
                        left join VEF_EMP_IM_SIMULADOR_REF_TRIB_RETORNO RET on ENV.BDCHAVE = RET.BDCHAVE and ENV.BDORDEM = RET.BDORDEM
                        left join TCADPRO_VINC PRO on PRO.bdcodemp = REF.BDCODEMP and PRO.BDCODPROD = ENV.BDCODPROD
                      left join TNCM NCM on NCM.BDNCMPROD = PRO.BDNCMPROD) AS SEL
           on SIM.bdsessao = SEL.bdsessao and SIM.bdchave = SEL.BDCHAVE and SIM.bdordem = SEL.bdordem and SIM.bdanoretorno = SEL.bdanoretorno
           when matched then
               UPDATE  set
                       SIM.BDIM_ICMS_ALIQUOTA   = SEL.BDIM_ICMS_ALIQUOTA,
                       SIM.BDIM_ICMS_VALOR      = SEL.BDIM_ICMS_VALOR,
                       SIM.BDIM_PIS_COFINS_BASE = SEL.BDIM_PIS_COFINS_BASE,
                       SIM.BDIM_PIS_VALOR       = SEL.BDIM_PIS_VALOR,
                       SIM.BDIM_COFINS_VALOR    = SEL.BDIM_COFINS_VALOR,
                       SIM.BDIM_IPI_ALIQUOTA    = SEL.BDIM_IPI_ALIQUOTA,
                       SIM.BDIM_IPI_VALOR       = SEL.BDIM_IPI_VALOR,
                       SIM.BDIM_ISS_ALIQUOTA    = SEL.BDIM_ISS_ALIQUOTA,
                       SIM.BDIM_ISS_VALOR       = SEL.BDIM_ISS_VALOR,
                       SIM.BDIM_IS_ALIQ         = SEL.BDIM_IS_ALIQ,
                       SIM.BDIM_IS_VALOR        = SEL.BDIM_IS_VALOR,
                       SIM.BDIM_CBS_ALIQ        = SEL.BDIM_CBS_ALIQ,
                       SIM.BDIM_CBS_RED_ALIQ    = SEL.BDIM_CBS_RED_ALIQ,
                       SIM.BDIM_CBS_VALOR       = SEL.BDIM_CBS_VALOR,
                       SIM.BDIM_IBS_ALIQ        = SEL.BDIM_IBS_ALIQ,
                       SIM.BDIM_IBS_VALOR       = SEL.BDIM_IBS_VALOR,
                       SIM.BDIM_IBS_EST_RED_ALIQ= SEL.BDIM_IBS_RED_ALIQ,
                       SIM.BDIM_IBS_MUN_RED_ALIQ= SEL.BDIM_IBS_MUN_RED_ALIQ,
                       SIM.BDTOTALIMPOSTOSANTES = SEL.BDTOTALIMPOSTOSANTES,
                       SIM.BDTOTALIMPOSTOAGORA  = SEL.BDTOTALIMPOSTOAGORA,
                       SIM.BDVLRICMS            = SEL.BDVLRICMS,
                       SIM.BDVLRISS             = SEL.bdvlrissqn,
                       SIM.BDVLRPIS             = SEL.BDVLRPIS,
                       SIM.BDVLRCOFINS          = SEL.BDVLRCOFINS,
                       SIM.BDVLRIPI             = SEL.BDVLRIPI,
                       SIM.BDVLRCBS             = SEL.BDVLR_CBS,
                       SIM.BDVLRIBS             = SEL.BDVLR_IBS,
                       SIM.BDVLRIS              = SEL.BDVLR_IS,
                       SIM.BDVLRCONTABIL        = SEL.BDVLRITEM,
                       SIM.BDREFERENCIA         = SEL.BDREFERENCIA
           when not matched then
               INSERT (BDSESSAO, BDCHAVE, BDCODEMP, BDORDEM, BDCODTER, BDCODPROD, BDEMITENTE, BDMOVIMENTO, BDCFOP, BDANORETORNO,
                       BDIM_ICMS_ALIQUOTA, BDIM_ICMS_VALOR, BDIM_PIS_COFINS_BASE, BDIM_PIS_VALOR, BDIM_COFINS_VALOR, BDIM_IPI_ALIQUOTA,
                       BDIM_IPI_VALOR, BDIM_ISS_ALIQUOTA, BDIM_ISS_VALOR, BDIM_IS_ALIQ, BDIM_IS_VALOR, BDIM_CBS_ALIQ, BDIM_CBS_VALOR,
                       BDIM_IBS_ALIQ, BDIM_IBS_VALOR, BDNOMETER, BDPRURALTER, BDENQSIMPLESFEDTER, BDSIGLAUF, BDNCMPROD, BDDESCPROD,
                       BDCLASSIFICACAO, BDTOTALIMPOSTOSANTES, BDTOTALIMPOSTOAGORA, BDVLRICMS, BDVLRISS, BDVLRPIS, BDVLRCOFINS, BDVLRIPI,
                       BDVLRCBS, BDVLRIBS, BDVLRIS, BDVLRCONTABIL, BDORIGEM, BDREFERENCIA, BDIM_IBS_EST_RED_ALIQ, BDIM_IBS_MUN_RED_ALIQ, BDIM_CBS_RED_ALIQ)

               Values (SEL.BDSESSAO, SEL.BDCHAVE, SEL.BDCODEMP, SEL.BDORDEM, SEL.BDCODTER, SEL.BDCODPROD, SEL.BDEMITENTE, SEL.BDMOVIMENTO, SEL.BDCFOP, SEL.BDANORETORNO,
                       SEL.BDIM_ICMS_ALIQUOTA, SEL.BDIM_ICMS_VALOR, SEL.BDIM_PIS_COFINS_BASE, SEL.BDIM_PIS_VALOR, SEL.BDIM_COFINS_VALOR, SEL.BDIM_IPI_ALIQUOTA,
                       SEL.BDIM_IPI_VALOR, SEL.BDIM_ISS_ALIQUOTA, SEL.BDIM_ISS_VALOR, SEL.BDIM_IS_ALIQ, SEL.BDIM_IS_VALOR, SEL.BDIM_CBS_ALIQ, SEL.BDIM_CBS_VALOR,
                       SEL.BDIM_IBS_ALIQ, SEL.BDIM_IBS_VALOR, SEL.BDNOMETER, SEL.BDPRURALTER, SEL.BDENQSIMPLESFEDTER, SEL.BDSIGLAUF, SEL.BDNCMPROD, SEL.BDDESCPROD,
                       SEL.BDCLASSIFICACAO, SEL.BDTOTALIMPOSTOSANTES, SEL.BDTOTALIMPOSTOAGORA, SEL.BDVLRICMS, SEL.bdvlrissqn, SEL.BDVLRPIS, SEL.BDVLRCOFINS, SEL.BDVLRIPI,
                       SEL.BDVLR_CBS, SEL.BDVLR_IBS, SEL.BDVLR_IS, SEL.BDVLRITEM, SEL.BDORIGEM, SEL.BDREFERENCIA, SEL.BDIM_IBS_RED_ALIQ, SEL.BDIM_IBS_MUN_RED_ALIQ, SEL.BDIM_CBS_RED_ALIQ)';

   execute statement :wSQL;

   SELECT COUNT(*) FROM TMP_VEF_EMP_IM_SIMULADOR_REF_TRIB_TEMP WHERE BDSESSAO = :prSESSAO INTO :WCONTA2;

   if (:WCONTA <> :WCONTA2) then
      begin
         DELETE FROM TMP_VEF_EMP_IM_SIMULADOR_REF_TRIB_TOTAIS_TEMP WHERE BDSESSAO = :prSessao;

            wSQL = 'INSERT INTO TMP_VEF_EMP_IM_SIMULADOR_REF_TRIB_TOTAIS_TEMP
                 select FIL.BDCHAVE, ' || :prSessao || ' AS BDSESSAO, FIL.IMPOSTO, FIL.BDANOATUAL, FIL.BD2026, FIL.BD2027, FIL.BD2028, FIL.BD2029, FIL.BD2030, FIL.BD2031, FIL.BD2032, FIL.BD2033, FIL.BDORDEM
                 from (select SIM.BDCHAVE, ''PIS'' as IMPOSTO,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(SIM.BDVLRPIS, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BDANOATUAL,
                              sum(case when SIM.BDANORETORNO = 2026 then coalesce(SIM.BDIM_PIS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2026,
                              sum(case when SIM.BDANORETORNO = 2027 then coalesce(SIM.BDIM_PIS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2027,
                              sum(case when SIM.BDANORETORNO = 2028 then coalesce(SIM.BDIM_PIS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2028,
                              sum(case when SIM.BDANORETORNO = 2029 then coalesce(SIM.BDIM_PIS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2029,
                              sum(case when SIM.BDANORETORNO = 2030 then coalesce(SIM.BDIM_PIS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2030,
                              sum(case when SIM.BDANORETORNO = 2031 then coalesce(SIM.BDIM_PIS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2031,
                              sum(case when SIM.BDANORETORNO = 2032 then coalesce(SIM.BDIM_PIS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2032,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(SIM.BDIM_PIS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2033,
             1 AS BDORDEM
      from TMP_VEF_EMP_IM_SIMULADOR_REF_TRIB_TEMP SIM
      where SIM.BDSESSAO = ' || :prSessao || '
      group by SIM.BDCHAVE
      union all
      select SIM.BDCHAVE, ''Cofins'' as IMPOSTO,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(SIM.BDVLRCOFINS, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BDANOATUAL,
                              sum(case when SIM.BDANORETORNO = 2026 then coalesce(SIM.BDIM_COFINS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2026,
                              sum(case when SIM.BDANORETORNO = 2027 then coalesce(SIM.BDIM_COFINS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2027,
                              sum(case when SIM.BDANORETORNO = 2028 then coalesce(SIM.BDIM_COFINS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2028,
                              sum(case when SIM.BDANORETORNO = 2029 then coalesce(SIM.BDIM_COFINS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2029,
                              sum(case when SIM.BDANORETORNO = 2030 then coalesce(SIM.BDIM_COFINS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2030,
                              sum(case when SIM.BDANORETORNO = 2031 then coalesce(SIM.BDIM_COFINS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2031,
                              sum(case when SIM.BDANORETORNO = 2032 then coalesce(SIM.BDIM_COFINS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2032,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(SIM.BDIM_COFINS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2033,
             2 AS BDORDEM
      from TMP_VEF_EMP_IM_SIMULADOR_REF_TRIB_TEMP SIM
      where SIM.BDSESSAO = ' || :prSessao || '
      group by SIM.BDCHAVE
      union all
      select SIM.BDCHAVE, ''CBS'' as IMPOSTO,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(SIM.BDVLRCBS, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BDANOATUAL,
                              sum(case when SIM.BDANORETORNO = 2026 then coalesce(SIM.BDIM_CBS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2026,
                              sum(case when SIM.BDANORETORNO = 2027 then coalesce(SIM.BDIM_CBS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2027,
                              sum(case when SIM.BDANORETORNO = 2028 then coalesce(SIM.BDIM_CBS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2028,
                              sum(case when SIM.BDANORETORNO = 2029 then coalesce(SIM.BDIM_CBS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2029,
                              sum(case when SIM.BDANORETORNO = 2030 then coalesce(SIM.BDIM_CBS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2030,
                              sum(case when SIM.BDANORETORNO = 2031 then coalesce(SIM.BDIM_CBS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2031,
                              sum(case when SIM.BDANORETORNO = 2032 then coalesce(SIM.BDIM_CBS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2032,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(SIM.BDIM_CBS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2033,
             6 AS BDORDEM
      from TMP_VEF_EMP_IM_SIMULADOR_REF_TRIB_TEMP SIM
      where SIM.BDSESSAO = ' || :prSessao || '
      group by SIM.BDCHAVE
      union all
      select SIM.BDCHAVE, ''ICMS'' as IMPOSTO,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(SIM.BDVLRICMS, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BDANOATUAL,
                              sum(case when SIM.BDANORETORNO = 2026 then coalesce(SIM.BDIM_ICMS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2026,
                              sum(case when SIM.BDANORETORNO = 2027 then coalesce(SIM.BDIM_ICMS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2027,
                              sum(case when SIM.BDANORETORNO = 2028 then coalesce(SIM.BDIM_ICMS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2028,
                              sum(case when SIM.BDANORETORNO = 2029 then coalesce(SIM.BDIM_ICMS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2029,
                              sum(case when SIM.BDANORETORNO = 2030 then coalesce(SIM.BDIM_ICMS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2030,
                              sum(case when SIM.BDANORETORNO = 2031 then coalesce(SIM.BDIM_ICMS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2031,
                              sum(case when SIM.BDANORETORNO = 2032 then coalesce(SIM.BDIM_ICMS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2032,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(SIM.BDIM_ICMS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2033,
             3 AS BDORDEM
      from TMP_VEF_EMP_IM_SIMULADOR_REF_TRIB_TEMP SIM
      where SIM.BDSESSAO = ' || :prSessao || '
      group by SIM.BDCHAVE
      union all
      select SIM.BDCHAVE, ''ISS'' as IMPOSTO,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(SIM.BDVLRISS, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BDANOATUAL,
                              sum(case when SIM.BDANORETORNO = 2026 then coalesce(SIM.BDIM_ISS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2026,
                              sum(case when SIM.BDANORETORNO = 2027 then coalesce(SIM.BDIM_ISS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2027,
                              sum(case when SIM.BDANORETORNO = 2028 then coalesce(SIM.BDIM_ISS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2028,
                              sum(case when SIM.BDANORETORNO = 2029 then coalesce(SIM.BDIM_ISS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2029,
                              sum(case when SIM.BDANORETORNO = 2030 then coalesce(SIM.BDIM_ISS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2030,
                              sum(case when SIM.BDANORETORNO = 2031 then coalesce(SIM.BDIM_ISS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2031,
                              sum(case when SIM.BDANORETORNO = 2032 then coalesce(SIM.BDIM_ISS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2032,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(SIM.BDIM_ISS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2033,
             4 AS BDORDEM
      from TMP_VEF_EMP_IM_SIMULADOR_REF_TRIB_TEMP SIM
      where SIM.BDSESSAO = ' || :prSessao || '
      group by SIM.BDCHAVE
      union all
      select SIM.BDCHAVE, ''IBS'' as IMPOSTO,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(SIM.BDVLRIBS, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BDANOATUAL,
                              sum(case when SIM.BDANORETORNO = 2026 then coalesce(SIM.BDIM_IBS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2026,
                              sum(case when SIM.BDANORETORNO = 2027 then coalesce(SIM.BDIM_IBS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2027,
                              sum(case when SIM.BDANORETORNO = 2028 then coalesce(SIM.BDIM_IBS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2028,
                              sum(case when SIM.BDANORETORNO = 2029 then coalesce(SIM.BDIM_IBS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2029,
                              sum(case when SIM.BDANORETORNO = 2030 then coalesce(SIM.BDIM_IBS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2030,
                              sum(case when SIM.BDANORETORNO = 2031 then coalesce(SIM.BDIM_IBS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2031,
                              sum(case when SIM.BDANORETORNO = 2032 then coalesce(SIM.BDIM_IBS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2032,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(SIM.BDIM_IBS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2033,
             7 AS BDORDEM
      from TMP_VEF_EMP_IM_SIMULADOR_REF_TRIB_TEMP SIM
      where SIM.BDSESSAO = ' || :prSessao || '
      group by SIM.BDCHAVE
      union all
      select SIM.BDCHAVE, ''IPI'' as IMPOSTO,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(SIM.BDVLRIPI, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BDANOATUAL,
                              sum(case when SIM.BDANORETORNO = 2026 then coalesce(SIM.BDIM_IPI_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2026,
                              sum(case when SIM.BDANORETORNO = 2027 then coalesce(SIM.BDIM_IPI_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2027,
                              sum(case when SIM.BDANORETORNO = 2028 then coalesce(SIM.BDIM_IPI_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2028,
                              sum(case when SIM.BDANORETORNO = 2029 then coalesce(SIM.BDIM_IPI_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2029,
                              sum(case when SIM.BDANORETORNO = 2030 then coalesce(SIM.BDIM_IPI_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2030,
                              sum(case when SIM.BDANORETORNO = 2031 then coalesce(SIM.BDIM_IPI_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2031,
                              sum(case when SIM.BDANORETORNO = 2032 then coalesce(SIM.BDIM_IPI_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2032,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(SIM.BDIM_IPI_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2033,
             5 AS BDORDEM
      from TMP_VEF_EMP_IM_SIMULADOR_REF_TRIB_TEMP SIM
      where SIM.BDSESSAO = ' || :prSessao || '
      group by SIM.BDCHAVE
      union all
      select SIM.BDCHAVE, ''IS'' as IMPOSTO,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(SIM.BDVLRIS, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BDANOATUAL,
                              sum(case when SIM.BDANORETORNO = 2026 then coalesce(SIM.BDIM_IS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2026,
                              sum(case when SIM.BDANORETORNO = 2027 then coalesce(SIM.BDIM_IS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2027,
                              sum(case when SIM.BDANORETORNO = 2028 then coalesce(SIM.BDIM_IS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2028,
                              sum(case when SIM.BDANORETORNO = 2029 then coalesce(SIM.BDIM_IS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2029,
                              sum(case when SIM.BDANORETORNO = 2030 then coalesce(SIM.BDIM_IS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2030,
                              sum(case when SIM.BDANORETORNO = 2031 then coalesce(SIM.BDIM_IS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2031,
                              sum(case when SIM.BDANORETORNO = 2032 then coalesce(SIM.BDIM_IS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2032,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(SIM.BDIM_IS_VALOR, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2033,
             8 AS BDORDEM
      from TMP_VEF_EMP_IM_SIMULADOR_REF_TRIB_TEMP SIM
      where SIM.BDSESSAO = ' || :prSessao || '
      group by SIM.BDCHAVE
      union all
      select SIM.BDCHAVE, ''TOTAL'' as IMPOSTO,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(SIM.BDTOTALIMPOSTOSANTES, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BDANOATUAL,
                              sum(case when SIM.BDANORETORNO = 2026 then coalesce(BDTOTALIMPOSTOAGORA, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2026,
                              sum(case when SIM.BDANORETORNO = 2027 then coalesce(BDTOTALIMPOSTOAGORA, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2027,
                              sum(case when SIM.BDANORETORNO = 2028 then coalesce(BDTOTALIMPOSTOAGORA, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2028,
                              sum(case when SIM.BDANORETORNO = 2029 then coalesce(BDTOTALIMPOSTOAGORA, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2029,
                              sum(case when SIM.BDANORETORNO = 2030 then coalesce(BDTOTALIMPOSTOAGORA, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2030,
                              sum(case when SIM.BDANORETORNO = 2031 then coalesce(BDTOTALIMPOSTOAGORA, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2031,
                              sum(case when SIM.BDANORETORNO = 2032 then coalesce(BDTOTALIMPOSTOAGORA, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2032,
                              sum(case when SIM.BDANORETORNO = 2033 then coalesce(BDTOTALIMPOSTOAGORA, 0) * iif(SIM.BDMOVIMENTO in (2, 3, 6), 1, -1) else 0 end) as BD2033,
             9 AS BDORDEM
      from TMP_VEF_EMP_IM_SIMULADOR_REF_TRIB_TEMP SIM
      where SIM.BDSESSAO = ' || :prSessao || '
      group by SIM.BDCHAVE) FIL';

   execute statement :wSQL;
      end
end^

create or alter procedure SP_SIM_IM_REFTRIB_LOAD_MOVPROD (
    PRCAMPODATA varchar(20),
    PRMOVIMENTO varchar(3),
    PRANO integer,
    PRCODMOV integer,
    PRCHAVE integer,
    PRMESES varchar(30))
as
declare variable WSQL varchar(30000);
begin
   :wsql = 'INSERT INTO VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD (BDCHAVE, BDORDEM, BDCODTER, BDCODPROD, BDEMITENTE, BDMOVIMENTO, BDCFOP, BDCODCSTCOF,' ||
           '                                                BDCODCSTICMS, BDCODCSTPIS, BDCODCSTIPI, BDQTDITEM, BDVLRITEM, BDVLRDESC, BDVLRDESPACESSORIA,' ||
           '                                                                  BDBCICMS, BDBCPIS, BDBCCOFINS, BDBCIPI, BDALIQICMS, BDALIQPIS, BDALIQCOFINS, BDALIQIPI,' ||
           '                                                                  BDVLRICMS, BDVLRPIS, BDVLRIPI, BDVLRCOFINS, BDALIQISSQN, BDVLRISSQN, BDALIQ_IS, BDCST_IS,' ||
           '                                                                  BDVLR_IS, BDALIQ_CBS, BDVLR_CBS, BDALIQ_IBS, BDVLR_IBS, BDORIGEM)' ||
           'with ref as' ||
           '   (SELECT ENV.BDCODEMP, ENV.bdstatus, ENV.bdCHAVE, COALESCE(MAX(TRIB.BDORDEM), 0) AS BDULTORDEM' ||
           '    FROM VEF_EMP_IM_SIMULADOR_REF_TRIB ENV' ||
           '    LEFT join VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD TRIB on ENV.BDCHAVE = TRIB.BDCHAVE' ||
           '    WHERE ENV.BDCHAVE = ' || :prChave ||
           '    GROUP BY ENV.BDCODEMP, ENV.bdstatus, ENV.bdCHAVE'||
           '    ),'||
           'DADOS '||
           'as (select MPRO.BDCODEMP, MPRO.BDCODPROD, SUBSTRING(IT.bdcodnat FROM 1 FOR 4) AS BDCODNAT, iif(CHAR_LENGTH(Ter.BDCGCTER) = 14,-1,MOV.BDCODTER) AS BDCODTER, MOV.BDEMITENTE,'||
           '       MPRO.BDCODCSTCOF, MPRO.BDCODCSTICMS, MPRO.BDCODCSTPIS, MPRO.BDCODCSTIPI,'||
           '      sum(coalesce(MPRO.BDQTDITEM, 0)) as BDQTDITEM, sum(coalesce(MPRO.BDVLRITEM, 0)) as BDVLRITEM,'||
           '       sum(coalesce(MPRO.BDVLRDESC, 0)) as BDVLRDESC, sum(coalesce(MPRO.BDVLRDESPACESSORIA, 0)) as BDVLRDESPACESSORIA,'||
           '       /*MPRO.BDREDBCICMS,*/ sum(coalesce(iif(MPRO.BDVLRICMSMONO <> 0, MPRO.BDBCICMSMONO, MPRO.BDBCICMS), 0)) as BDBCICMS, sum(coalesce(MPRO.BDBCPIS, 0)) as BDBCPIS,'||
           '       sum(coalesce(MPRO.BDBCIPI, 0)) as BDBCIPI, sum(coalesce(MPRO.BDBCCOFINS, 0)) as BDBCCOFINS, iif(MPRO.BDVLRICMSMONO <> 0, MPRO.BDALIQICMSMONO, MPRO.BDALIQICMS) AS BDALIQICMS,'||
           '       MPRO.BDALIQPIS, MPRO.BDALIQIPI, MPRO.BDALIQCOFINS,';

   --#223793 - começamos a complicar aqui as coisas
   --#224299 - se tiver ICMS monofásico, sem precisa olhar os outros campos
   if (:prmovimento = 'ENT') then
      begin
         :wsql = :wsql || 'sum(iif(MPRO.BDVLRICMSMONO <> 0, coalesce(MPRO.BDVLRICMSMONO,0), coalesce(MPRO.BDVLRICMS, 0) + iif(UPPER(CFOP.BDDEVOL) = ''TRUE'', coalesce(MPRO.BDVLRST, 0) + coalesce(MPRO.BDVLRFCP, 0) + coalesce(MPRO.BDFCPRETIDO, 0), 0))) as BDVLRICMS,';
      end
   else
      begin
         :wsql = :wsql || 'sum(iif(MPRO.BDVLRICMSMONO <> 0, coalesce(MPRO.BDVLRICMSMONO,0), coalesce(MPRO.BDVLRICMS, 0) + coalesce(MPRO.BDVLRST, 0) + coalesce(MPRO.BDVLRFCP, 0) + coalesce(MPRO.BDFCPRETIDO, 0))) as BDVLRICMS,';
      end

   :wsql = :wsql ||
           '       sum(coalesce(MPRO.BDVLRPIS, 0)) as BDVLRPIS, sum(coalesce(MPRO.BDVLRIPI, 0)) as BDVLRIPI,'||
           '       sum(coalesce(MPRO.BDVLRCOFINS, 0)) as BDVLRCOFINS, MPRO.BDALIQISSQN,'||
           '       sum(coalesce(MPRO.BDVLRISSQN, 0)) as BDVLRISSQN, null as BDALIQ_IS, null as BDCST_IS,'||
           '       null as BDVLR_IS, null as BDALIQ_CBS, null as BDVLR_CBS, null as BDALIQ_IBS, null as BDVLR_IBS '||
           ' from ref '||
           ' inner join VEF_EMP_TMOV' || :prmovimento ||' MOV on REF.BDCODEMP = MOV.BDCODEMP '||
           ' inner join VEF_EMP_TMOV' || :prmovimento ||'ITENS IT on IT.BDCODEMP = MOV.BDCODEMP and IT.BDCHAVE = MOV.BDCHAVE '||
           ' inner join VEF_EMP_TMOVPRO' || :prmovimento ||' MPRO on MPRO.BDCODEMP = IT.BDCODEMP and MPRO.BDCHAVE = IT.BDCHAVE and MPRO.BDORDEM = IT.BDORDEM '||
           ' inner join tterceiro TER ON TER.bdcodter = mov.bdcodter ';

   if (:prmovimento = 'ENT') then
      begin
         :wsql = :wsql || ' inner join VEF_BASE_TNATOP CFOP ON CFOP.BDCODNAT = IT.BDCODNAT ';
      end


   :wsql = :wsql ||
           ' where MOV.' || :prcampodata || ' between '||''''|| :prano ||'-01-01' || '''' || ' and ' || '''' || :prano ||'-12-31'||''''||
           '   and MOV.BDCODSITNF in (0, 1, 6, 7, 8) and (coalesce(MOV.BDVALORNOTA,0) > 0)'||
           '   and (NOT MOV.BDMODELO in (6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 21, 22, 26, 27, 28, 29, 57, 62, 63, 66, 67))';

   if (:PRMESES <> 'T') then
      begin
         :wsql = :wsql || '  and extract(month from MOV.' || :prcampodata || ') in (13'|| :PRMESES ||'13) ';
      end

   :wsql = :wsql ||
           ' group by MPRO.BDCODEMP, MPRO.BDCODPROD, MPRO.BDCODCSTCOF, MPRO.BDCODCSTICMS, MPRO.BDCODCSTPIS,'||
           '         MPRO.BDCODCSTIPI, SUBSTRING(IT.bdcodnat FROM 1 FOR 4), iif(CHAR_LENGTH(Ter.BDCGCTER) = 14,-1,MOV.BDCODTER), MOV.BDEMITENTE, iif(MPRO.BDVLRICMSMONO <> 0, MPRO.BDALIQICMSMONO, MPRO.BDALIQICMS), MPRO.BDALIQPIS,'||
           '         MPRO.BDALIQIPI, MPRO.BDALIQCOFINS, MPRO.BDALIQISSQN'||
           ')'||
           'Select REF.BDCHAVE,'||
           '       row_number() OVER (PARTITION BY REF.BDCHAVE ORDER BY REF.BDCHAVE) + REF.BDULTORDEM AS BDORDEM,'||
           '       DADOS.BDCODTER,'||
           '       DADOS.BDCODPROD,'||
           '       DADOS.BDEMITENTE,'||
           '       '|| :prcodmov ||' AS BDMOVIMENTO,'||
           '       DADOS.BDCODNAT,'||
           '       DADOS.BDCODCSTCOF,'||
           '       DADOS.BDCODCSTICMS,'||
           '       DADOS.BDCODCSTPIS,'||
           '       DADOS.BDCODCSTIPI,'||
           '       DADOS.BDQTDITEM,'||
           '       DADOS.BDVLRITEM,'||
           '       DADOS.BDVLRDESC,'||
           '       DADOS.BDVLRDESPACESSORIA,'||
           '       DADOS.BDBCICMS,'||
           '       DADOS.BDBCPIS,'||
           '       DADOS.BDBCCOFINS,'||
           '       DADOS.BDBCIPI,'||
           '       DADOS.BDALIQICMS,'||
           '       DADOS.BDALIQPIS,'||
           '       DADOS.BDALIQCOFINS,'||
           '       DADOS.BDALIQIPI,'||
           '       DADOS.BDVLRICMS,'||
           '       DADOS.BDVLRPIS,'||
           '       DADOS.BDVLRIPI,'||
           '       DADOS.BDVLRCOFINS,'||
           '       DADOS.BDALIQISSQN,'||
           '       DADOS.BDVLRISSQN,'||
           '       DADOS.BDALIQ_IS,'||
           '       DADOS.BDCST_IS,'||
           '       DADOS.BDVLR_IS,'||
           '       DADOS.BDALIQ_CBS,'||
           '       DADOS.BDVLR_CBS,'||
           '       DADOS.BDALIQ_IBS,'||
           '       DADOS.BDVLR_IBS, '||
           '       1 '|| --indicando a origem do produto
           'from DADOS'||
           '   inner join REF on DADOS.BDCODEMP = REF.BDCODEMP '||
           'where DADOS.BDVLRITEM > 0;';

   execute statement :wsql;
end^

create or alter procedure SP_SIM_IM_REFTRIB_LOAD_MOVSPROD (
    PRCAMPODATA varchar(20),
    PRMOVIMENTO varchar(3),
    PRANO integer,
    PRCODMOV integer,
    PRCHAVE integer)
as
declare variable WSQL varchar(30000);
begin
  :wsql = 'INSERT INTO VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD (BDCHAVE, BDORDEM, BDCODTER, BDCODPROD, BDEMITENTE, BDMOVIMENTO, BDCFOP, BDCODCSTCOF,' ||
           '                                                BDCODCSTICMS, BDCODCSTPIS, BDCODCSTIPI, BDQTDITEM, BDVLRITEM, BDVLRDESC, BDVLRDESPACESSORIA,' ||
           '                                                                  BDBCICMS, BDBCPIS, BDBCCOFINS, BDBCIPI, BDALIQICMS, BDALIQPIS, BDALIQCOFINS, BDALIQIPI,' ||
           '                                                                  BDVLRICMS, BDVLRPIS, BDVLRIPI, BDVLRCOFINS, BDALIQISSQN, BDVLRISSQN, BDALIQ_IS, BDCST_IS,' ||
           '                                                                  BDVLR_IS, BDALIQ_CBS, BDVLR_CBS, BDALIQ_IBS, BDVLR_IBS)' ||
           'with ref as' ||
           '   (SELECT ENV.BDCODEMP, ENV.bdstatus, ENV.bdCHAVE, COALESCE(MAX(TRIB.BDORDEM), 0) AS BDULTORDEM' ||
           '    FROM VEF_EMP_IM_SIMULADOR_REF_TRIB ENV' ||
           '    LEFT join VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD TRIB on ENV.BDCHAVE = TRIB.BDCHAVE' ||
           '    WHERE ENV.BDCHAVE = ' || :prChave ||
           '    GROUP BY ENV.BDCODEMP, ENV.bdstatus, ENV.bdCHAVE'||
           '    ),'||
           'DADOS '||
           'as (select IT.BDCODEMP, null AS BDCODPROD, substring(IT.BDCODNAT from 1 for 4) as BDCODNAT,'||
           '           iif(char_length(TER.BDCGCTER) = 14, -1, MOV.BDCODTER) as BDCODTER, MOV.BDEMITENTE, null BDCODCSTCOF,'||
           '           null BDCODCSTICMS, null BDCODCSTPIS, null BDCODCSTIPI, null as BDQTDITEM,'||
           '           sum(coalesce(IT.bdvlrcontab, 0)) as BDVLRITEM, sum(coalesce(IT.bddesconto, 0)) as BDVLRDESC,'||
           '           null as BDVLRDESPACESSORIA, sum(coalesce(IT.bdbaseicms, 0)) as BDBCICMS, null as BDBCPIS,'||
           '           null as BDBCIPI, null as BDBCCOFINS, IT.bdaliqicms, null BDALIQPIS, null BDALIQIPI, null BDALIQCOFINS,'||
           '           sum(coalesce(IT.bdvlricms, 0)) as BDVLRICMS, sum(coalesce(IT.bdvlrpis, 0)) as BDVLRPIS,'||
           '           sum(coalesce(IT.BDVLRIPI, 0)) as BDVLRIPI, sum(coalesce(IT.BDVLRCOFINS, 0)) as BDVLRCOFINS, null BDALIQISSQN,'||
           '           null as BDVLRISSQN, null as BDALIQ_IS, null as BDCST_IS, null as BDVLR_IS,'||
           '           null as BDALIQ_CBS, null as BDVLR_CBS, null as BDALIQ_IBS, null as BDVLR_IBS '||
           ' from ref '||
           ' inner join VEF_EMP_TMOV' || :prmovimento ||' MOV on REF.BDCODEMP = MOV.BDCODEMP '||
           ' inner join tterceiro TER ON TER.bdcodter = mov.bdcodter '||

           ' inner join VEF_EMP_TMOV' || :prmovimento ||'ITENS IT on IT.BDCODEMP = MOV.BDCODEMP and IT.BDCHAVE = MOV.BDCHAVE '||

           --tabelas que não podem ter registro
           '  left join VEF_EMP_TMOVPRO' || :prmovimento ||' MPRO on MPRO.BDCODEMP = IT.BDCODEMP and MPRO.BDCHAVE = IT.BDCHAVE and MPRO.BDORDEM = IT.BDORDEM '||
           '  left join VEF_EMP_TC590TOT' || :prmovimento ||' C590 ON C590.bdCODEMP = MOV.BDCODEMP and C590.bdCHAVE = MOV.BDCHAVE '||
           '  left join VEF_EMP_TC500' || :prmovimento ||' C500 on C500.BDCODEMP = MOV.BDCODEMP and C500.BDCHAVE = MOV.BDCHAVE '||
           '  left join VEF_EMP_TD100' || :prmovimento ||' D100 on D100.BDCODEMP = MOV.BDCODEMP and D100.BDCHAVE = MOV.BDCHAVE '||
           '  left join VEF_EMP_TD500' || :prmovimento ||' D500 on D500.BDCODEMP = MOV.BDCODEMP and D500.BDCHAVE = MOV.BDCHAVE ';

  if (:PRCODMOV = 1) then
     begin
        :wsql = :wSQL || '  left join VEF_EMP_TD590TOTENT D590 on D590.BDCODEMP = MOV.BDCODEMP and D590.BDCHAVE = MOV.BDCHAVE ';
     end

  :wsql = :wSQL ||
           ' where MOV.' || :prcampodata || ' between '||''''|| :prano ||'-01-01' || '''' || ' and ' || '''' || :prano ||'-12-31'||''''||
           '   and (not MOV.BDMODELO in (6,7,8,9,10,11,12,13,14,15,16,21,22,26,27,28,29,57,62,63,67,66)) and (coalesce(MOV.BDVALORNOTA,0) > 0) '||
           '   and MOV.BDCODSITNF in (0, 1, 6, 7, 8) and MPRO.bdchave is null and C590.bdchave is null and C500.bdchave is null and D100.bdchave is null and D500.bdchave is null ';

  if (:PRCODMOV = 1) then
     begin
        :wsql = :wSQL || ' and D590.bdchave is null ';
     end

  :wsql = :wSQL ||
           ' group by IT.BDCODEMP, substring(IT.BDCODNAT from 1 for 4), iif(char_length(TER.BDCGCTER) = 14, -1, MOV.BDCODTER), MOV.BDEMITENTE, IT.BDALIQICMS '||
           ')'||
           'Select REF.BDCHAVE,'||
           '       row_number() OVER (PARTITION BY REF.BDCHAVE ORDER BY REF.BDCHAVE) + REF.BDULTORDEM AS BDORDEM,'||
           '       DADOS.BDCODTER,'||
           '       DADOS.BDCODPROD,'||
           '       DADOS.BDEMITENTE,'||
           '       '|| :prcodmov ||' AS BDMOVIMENTO,'||
           '       DADOS.BDCODNAT,'||
           '       DADOS.BDCODCSTCOF,'||
           '       DADOS.BDCODCSTICMS,'||
           '       DADOS.BDCODCSTPIS,'||
           '       DADOS.BDCODCSTIPI,'||
           '       DADOS.BDQTDITEM,'||
           '       DADOS.BDVLRITEM,'||
           '       DADOS.BDVLRDESC,'||
           '       DADOS.BDVLRDESPACESSORIA,'||
           '       DADOS.BDBCICMS,'||
           '       DADOS.BDBCPIS,'||
           '       DADOS.BDBCCOFINS,'||
           '       DADOS.BDBCIPI,'||
           '       DADOS.BDALIQICMS,'||
           '       DADOS.BDALIQPIS,'||
           '       DADOS.BDALIQCOFINS,'||
           '       DADOS.BDALIQIPI,'||
           '       DADOS.BDVLRICMS,'||
           '       DADOS.BDVLRPIS,'||
           '       DADOS.BDVLRIPI,'||
           '       DADOS.BDVLRCOFINS,'||
           '       DADOS.BDALIQISSQN,'||
           '       DADOS.BDVLRISSQN,'||
           '       DADOS.BDALIQ_IS,'||
           '       DADOS.BDCST_IS,'||
           '       DADOS.BDVLR_IS,'||
           '       DADOS.BDALIQ_CBS,'||
           '       DADOS.BDVLR_CBS,'||
           '       DADOS.BDALIQ_IBS,'||
           '       DADOS.BDVLR_IBS '||
           'from DADOS'||
           '   inner join REF on DADOS.BDCODEMP = REF.BDCODEMP '||
           'where DADOS.BDVLRITEM > 0;';

   execute statement :wsql;
end^

create or alter procedure SP_CARREGADADOS_SIM_IM_REFTRIB (
    PRCHAVE integer)
as
declare variable WANO integer;
declare variable WCODEMP integer;
declare variable WCFG_MESES varchar(30);
declare variable WCFG_ENV_PROD varchar(1);
declare variable WCFG_ENV_CFOP_ESP varchar(1);
declare variable WCFG_ENV_SERV varchar(1);
declare variable WCFG_ENV_DEMAIS_DOC varchar(1);
declare variable WCFG_ENV_OP_IMOB varchar(1);
declare variable WCFG_ENV_OP_FIN varchar(1);
declare variable WCFG_TOTAL_LAN integer;
declare variable WCFG_TOTAL_SAIDAS integer;
declare variable WCFG_TOTAL_ENTRADAS integer;
declare variable WCFG_TOTAL_SERVICOS integer;
declare variable WCFG_TOTAL_CFOP_ESP integer;
declare variable WCFG_TOTAL_DDOC_DEB integer;
declare variable WCFG_TOTAL_DDOC_CRED integer;
declare variable WCFG_TOTAL_OP_IMOB integer;
declare variable WCFG_TOTAL_OP_FIN integer;

declare procedure setfeedback(prfeedback varchar(200))
as
declare variable watusql varchar(400);
begin
   :watusql = ' UPDATE VEF_EMP_IM_SIMULADOR_REF_TRIB'||
              ' SET BDFEEDBACK = '||''''||:prfeedback||''''||
              ' WHERE BDSTATUS = 0 and BDCODEMP IN (SELECT BDCODEMP FROM TMP_EMPRESAS_SELECT)';

   execute statement :watusql;
end

begin
  delete from VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD
  where BDCHAVE = :PRCHAVE;

  select BDREFERENCIA, BDCODEMP, coalesce(BD_CFG_CONS_MESES, 'T'), coalesce(BD_CFG_ENV_MOV_PROD, 'T'), coalesce(BD_CFG_ENV_MOV_CFOP_ESPECIAL, 'T'),
         coalesce(BD_CFG_ENV_SERVICOS, 'T'), coalesce(BD_CFG_ENV_DEMAIS_DOC, 'T'), coalesce(BD_CFG_ENV_OPIMOB, 'T'), coalesce(BD_CFG_ENV_OPFIN, 'T'),
         coalesce(BD_CFG_QDADE_LANTOTAL, 0), coalesce(BD_CFG_QDADE_LANSAIDA, -1), coalesce(BD_CFG_QDADE_LANENTRADA, -1), coalesce(BD_CFG_QDADE_LANSERVICO, -1),
         coalesce(BD_CFG_QDADE_LAN_CFOP_ESPECIAL, -1), coalesce(BD_CFG_QDADE_DEMAISDOC_CRED, -1), coalesce(BD_CFG_QDADE_DEMAISDOC_DEB, -1),
         coalesce(BD_CFG_QDADE_OPIMOB, -1), coalesce(BD_CFG_QDADE_OPFIN, -1)
  from VEF_EMP_IM_SIMULADOR_REF_TRIB T
  where BDCHAVE = :PRCHAVE
  into :WANO, :WCODEMP, :WCFG_MESES, :WCFG_ENV_PROD, :WCFG_ENV_CFOP_ESP, :WCFG_ENV_SERV, :WCFG_ENV_DEMAIS_DOC,
       :WCFG_ENV_OP_IMOB, :WCFG_ENV_OP_FIN, :WCFG_TOTAL_LAN, :WCFG_TOTAL_SAIDAS, :WCFG_TOTAL_ENTRADAS, :WCFG_TOTAL_SERVICOS,
       :WCFG_TOTAL_CFOP_ESP, :WCFG_TOTAL_DDOC_CRED, :WCFG_TOTAL_DDOC_DEB, :WCFG_TOTAL_OP_IMOB, :WCFG_TOTAL_OP_FIN;

  if ((TRIM(:WCFG_MESES) <> '') AND (:WCFG_MESES <> 'T')) then
     begin
        :WCFG_MESES = ',' || parse_meses(:WCFG_MESES) || ',';
     end
  -----------------------------------------------------------------------------------------------------------------------
  --=====================               E N T R A D A S               =================================================--
  -----------------------------------------------------------------------------------------------------------------------
  if ((:WCFG_ENV_PROD in ('T', 'E')) and ((:WCFG_TOTAL_ENTRADAS > 0) or (:WCFG_TOTAL_ENTRADAS = -1) )) then
     begin
--         execute procedure SETFEEDBACK('Analisando movimento de entradas - com produtos');
         execute procedure SP_SIM_IM_REFTRIB_LOAD_MOVPROD('BDDATAENTRADAENT', 'ENT', :WANO, 1, :PRCHAVE, :WCFG_MESES);

  --execute procedure SETFEEDBACK('Analisando movimento de entradas - sem produtos');
  --execute procedure SP_SIM_IM_REFTRIB_LOAD_MOVSPROD('BDDATAENTRADAENT', 'ENT', :WANO, 1, :PRCHAVE);

         if (:WCFG_TOTAL_ENTRADAS > 0) then
            begin
               delete from VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD a
               where a.BDCHAVE = :prCHAVE
                 and bdorigem = 1
                 and bdmovimento = 1
                 and not exists (
                   select 1
                   from (
                     select BDCHAVE, BDORDEM
                     from VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD
                     where BDCHAVE = :prCHAVE
                       and bdorigem = 1
                       and bdmovimento = 1
                     order by BDORDEM
                     rows :WCFG_TOTAL_ENTRADAS
                   ) x
                   where x.BDCHAVE = a.BDCHAVE and x.BDORDEM = a.BDORDEM
                 );
            end
     end

  -----------------------------------------------------------------------------------------------------------------------
  --=====================                 S A Í D A S                 =================================================--
  -----------------------------------------------------------------------------------------------------------------------
  if ((:WCFG_ENV_PROD in ('T', 'S')) and ((:WCFG_TOTAL_SAIDAS > 0) or (:WCFG_TOTAL_SAIDAS = -1) )) then
     begin
--         execute procedure SETFEEDBACK('Analisando movimento de saídas - com produtos');
         execute procedure SP_SIM_IM_REFTRIB_LOAD_MOVPROD('bddataemissao', 'SAI', :WANO, 2, :PRCHAVE, :WCFG_MESES);

  --execute procedure SETFEEDBACK('Analisando movimento de saídas - sem produtos');
  --execute procedure SP_SIM_IM_REFTRIB_LOAD_MOVSPROD('bddataemissao', 'SAI', :WANO, 2, :PRCHAVE);

         if (:WCFG_TOTAL_SAIDAS > 0) then
            begin
               delete from VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD a
               where a.BDCHAVE = :prCHAVE
                 and bdorigem = 1
                 and bdmovimento = 2
                 and not exists (
                   select 1
                   from (
                     select BDCHAVE, BDORDEM
                     from VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD
                     where BDCHAVE = :prCHAVE
                       and bdorigem = 1
                       and bdmovimento = 2
                     order by BDORDEM
                     rows :WCFG_TOTAL_SAIDAS
                   ) x
                   where x.BDCHAVE = a.BDCHAVE and x.BDORDEM = a.BDORDEM
                 );
            end
     end


  if ((:WCFG_TOTAL_CFOP_ESP > 0) or (:WCFG_TOTAL_CFOP_ESP = -1)) then
     begin
  --================================Água/Energia elétrica/Gás
  --Entradas
        if (:WCFG_ENV_CFOP_ESP in ('T', 'E')) then
           begin
--              execute procedure SETFEEDBACK('Analisando movimento de entradas - Água/Energia elétrica/Gás');

  insert into VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD (BDCHAVE, BDORDEM, BDCODTER, BDEMITENTE, BDMOVIMENTO, BDCFOP,
                                                  BDCODCSTCOF, BDCODCSTICMS, BDCODCSTPIS, BDQTDITEM, BDVLRITEM,
                                                  BDVLRDESC, BDVLRDESPACESSORIA, BDBCICMS, BDBCPIS, BDBCCOFINS,
                                                  BDALIQICMS, BDALIQPIS, BDALIQCOFINS, BDVLRICMS, BDVLRPIS,
                                                  BDVLRCOFINS, BDORIGEM)
  with REF
  as (select ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE, coalesce(max(TRIB.BDORDEM), 0) as BDULTORDEM
      from VEF_EMP_IM_SIMULADOR_REF_TRIB ENV
      left join VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD TRIB on ENV.BDCHAVE = TRIB.BDCHAVE
      where ENV.BDCHAVE = :PRCHAVE
      group by ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE),
  DADOS
  as (select MOV.BDCODEMP, sum(coalesce(C590.BDVLROPERACAO, IT.BDVLRCONTAB, 0)) as BDVLRITEM, MOV.BDCODTER,
             2 as BDEMITENTE, 1 as BDMOVIMENTO, max(C590.BDCODCSTICMS) as BDCODCSTICMS, C500.BDCODCSTPIS,
             C500.BDCODCSTCOF, 0 as BDQTDITEM,
             sum(coalesce(C500.BDVLRPIS, 0) * (coalesce(IT.BDVLRCONTAB, C590.BDVLROPERACAO, 0) / CAST(MOV.BDVALORNOTA AS NUMERIC(20,8)))) as BDVLRPIS,
             sum(coalesce(C500.BDVLRCOFINS, 0) * (coalesce(IT.BDVLRCONTAB, C590.BDVLROPERACAO, 0) / CAST(MOV.BDVALORNOTA AS NUMERIC(20,8)))) as BDVLRCOFINS,
             sum(coalesce(C500.BDVL_BC_PIS, 0) * (coalesce(IT.BDVLRCONTAB, C590.BDVLROPERACAO, 0) / CAST(MOV.BDVALORNOTA AS NUMERIC(20,8)))) as BDVL_BC_PIS,
             sum(coalesce(C500.BDVL_BC_COF, 0) * (coalesce(IT.BDVLRCONTAB, C590.BDVLROPERACAO, 0) / CAST(MOV.BDVALORNOTA AS NUMERIC(20,8)))) as BDVL_BC_COF,
             C500.BDALIQ_PIS, C500.BDALIQ_COF, max(coalesce(C590.BDALIQICMS, IT.BDALIQICMS)) as BDALIQICMS,
             sum(coalesce(C590.BDBCICMS, IT.BDBASEICMS, 0)) as BDBCICMS,
             sum(coalesce(C590.BDVLRICMS, IT.BDVLRICMS, 0)) as BDVLRICMS,
             sum(coalesce(C500.BDVLRDESPACE, 0) * (coalesce(IT.BDVLRCONTAB, C590.BDVLROPERACAO, 0) / CAST(MOV.BDVALORNOTA AS NUMERIC(20,8)))) as BDVLRDESPACE,
             substring(IT.BDCODNAT from 1 for 4) as BDCODNAT, sum(coalesce(IT.BDDESCONTO, 0)) as BDVLRDESC
      from VEF_EMP_TMOVENT MOV
                    inner join VEF_EMP_TMOVENTITENS IT on IT.BDCODEMP = MOV.BDCODEMP and IT.BDCHAVE = MOV.BDCHAVE
                     left join VEF_EMP_TC500ENT C500 on C500.BDCODEMP = MOV.BDCODEMP and C500.BDCHAVE = MOV.BDCHAVE
                     left join VEF_EMP_TC590TOTENT C590 on C590.BDCODEMP = IT.BDCODEMP and C590.BDCHAVE = IT.BDCHAVE and C590.bdORDEM = IT.BDORDEM
      where MOV.BDCODEMP = :WCODEMP and
            MOV.BDMODELO in (6, 28, 29, 66) and
            MOV.BDCODSITNF in (0, 1, 6, 7, 8) and
            (coalesce(MOV.BDVALORNOTA,0) > 0) and
                        extract(year from MOV.BDDATAENTRADAENT) = :WANO and
                        ((:WCFG_MESES = 'T') or ('' || :WCFG_MESES || '') like cast('%,' || extract(month from MOV.BDDATAENTRADAENT) || ',%' as varchar(30)))
      group by MOV.BDCODEMP, MOV.BDCODTER, C500.BDCODCSTPIS, C500.BDCODCSTCOF, C500.BDALIQ_PIS, C500.BDALIQ_COF, substring(IT.BDCODNAT from 1 for 4))
  select REF.BDCHAVE, row_number() over(partition by REF.BDCHAVE order by REF.BDCHAVE) + REF.BDULTORDEM as BDORDEM,
         DADOS.BDCODTER, DADOS.BDEMITENTE, DADOS.BDMOVIMENTO, DADOS.BDCODNAT, DADOS.BDCODCSTCOF, DADOS.BDCODCSTICMS,
         DADOS.BDCODCSTPIS, DADOS.BDQTDITEM, DADOS.BDVLRITEM, DADOS.BDVLRDESC, DADOS.BDVLRDESPACE, DADOS.BDBCICMS,
         DADOS.BDVL_BC_PIS, DADOS.BDVL_BC_COF, DADOS.BDALIQICMS, DADOS.BDALIQ_PIS, DADOS.BDALIQ_COF, DADOS.BDVLRICMS,
         DADOS.BDVLRPIS, DADOS.BDVLRCOFINS, 2
  from DADOS
  inner join REF on DADOS.BDCODEMP = REF.BDCODEMP
  where DADOS.BDVLRITEM > 0;
           end

  --Saídas
        if (:WCFG_ENV_CFOP_ESP in ('T', 'S')) then
           begin
--              execute procedure SETFEEDBACK('Analisando movimento de saídas - Água/Energia elétrica/Gás');

  insert into VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD (BDCHAVE, BDORDEM, BDCODTER, BDEMITENTE, BDMOVIMENTO, BDCFOP,
                                                  BDCODCSTCOF, BDCODCSTICMS, BDCODCSTPIS, BDQTDITEM, BDVLRITEM,
                                                  BDVLRDESC, BDVLRDESPACESSORIA, BDBCICMS, BDBCPIS, BDBCCOFINS,
                                                  BDALIQICMS, BDALIQPIS, BDALIQCOFINS, BDVLRICMS, BDVLRPIS,
                                                  BDVLRCOFINS, BDORIGEM)
  with
       REF
  as (select ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE, coalesce(max(TRIB.BDORDEM), 0) as BDULTORDEM
      from VEF_EMP_IM_SIMULADOR_REF_TRIB ENV
        left join VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD TRIB on ENV.BDCHAVE = TRIB.BDCHAVE
      where ENV.BDCHAVE = :PRCHAVE
      group by ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE),
       DADOS
  as (select MOV.BDCODEMP, null as BDCODPROD, substring(IT.BDCODNAT from 1 for 4) as BDCODNAT,
             iif(char_length(TER.BDCGCTER) = 14, -1, MOV.BDCODTER) as BDCODTER, 1 as BDEMITENTE,
             sum(coalesce(C590.BDVLROPERACAO, IT.BDVLRCONTAB, 0)) as BDVLRITEM, 2 as BDMOVIMENTO,
             max(C590.BDCODCSTICMS) as BDCODCSTICMS, C500.BDCODCSTPIS, C500.BDCODCSTCOF, 0 as BDQTDITEM,
             sum(coalesce(C500.BDVLRPIS, 0) * (coalesce(IT.BDVLRCONTAB, C590.BDVLROPERACAO, 0) / cast(MOV.BDVALORNOTA as numeric(20,8)))) as BDVLRPIS,
             sum(coalesce(C500.BDVLRCOFINS, 0) * (coalesce(IT.BDVLRCONTAB, C590.BDVLROPERACAO, 0) / cast(MOV.BDVALORNOTA as numeric(20,8)))) as BDVLRCOFINS,
             sum(coalesce(C500.BDVL_BC_PIS, 0) * (coalesce(IT.BDVLRCONTAB, C590.BDVLROPERACAO, 0) / cast(MOV.BDVALORNOTA as numeric(20,8)))) as BDVL_BC_PIS,
             sum(coalesce(C500.BDVL_BC_COF, 0) * (coalesce(IT.BDVLRCONTAB, C590.BDVLROPERACAO, 0) / cast(MOV.BDVALORNOTA as numeric(20,8)))) as BDVL_BC_COF,
             C500.BDALIQ_PIS, C500.BDALIQ_COF, max(coalesce(C590.BDALIQICMS, IT.BDALIQICMS)) as BDALIQICMS,
             sum(coalesce(C590.BDBCICMS, IT.BDBASEICMS, 0)) as BDBCICMS,
             sum(coalesce(C590.BDVLRICMS, IT.BDVLRICMS, 0)) as BDVLRICMS,
             sum(coalesce(C500.BDVLRDESPACE, 0) * (coalesce(IT.BDVLRCONTAB, C590.BDVLROPERACAO, 0) / cast(MOV.BDVALORNOTA as numeric(20,8)))) as BDVLRDESPACE,
             sum(coalesce(IT.BDDESCONTO, 0)) as BDVLRDESC
      from VEF_EMP_TMOVSAI MOV
      inner join VEF_EMP_TMOVSAIITENS IT on IT.BDCODEMP = MOV.BDCODEMP and IT.BDCHAVE = MOV.BDCHAVE
      inner join TTERCEIRO TER on TER.BDCODTER = MOV.BDCODTER
       left join VEF_EMP_TC500SAI C500 on C500.BDCODEMP = MOV.BDCODEMP and C500.BDCHAVE = MOV.BDCHAVE
       left join VEF_EMP_TC590TOTSAI C590 on C590.BDCODEMP = IT.BDCODEMP and C590.BDCHAVE = IT.BDCHAVE and C590.BDORDEM = IT.BDORDEM
    where MOV.BDCODEMP = :WCODEMP and
          MOV.BDMODELO in (6, 28, 29, 66) and
          MOV.BDCODSITNF in (0, 1, 6, 7, 8) and
          extract(year from MOV.BDDATAEMISSAO) = :WANO and
                      ((:WCFG_MESES = 'T') or ('' || :WCFG_MESES || '') like cast('%,' || extract(month from MOV.BDDATAEMISSAO) || ',%' as varchar(30))) and
          not exists (
                      select 1
                      from VEF_EMP_TMOVPROSAI P
                      where P.BDCHAVE = IT.BDCHAVE
                        and P.BDCODEMP = IT.BDCODEMP
                        and P.BDORDEM = IT.BDORDEM
                      )
    group by MOV.BDCODEMP, substring(IT.BDCODNAT from 1 for 4), iif(char_length(TER.BDCGCTER) = 14, -1, MOV.BDCODTER), C500.BDCODCSTPIS, C500.BDCODCSTCOF, C500.BDALIQ_PIS, C500.BDALIQ_COF
    union all
    select MPRO.BDCODEMP, null as BDCODPROD, substring(IT.BDCODNAT from 1 for 4) as BDCODNAT,
           iif(char_length(TER.BDCGCTER) = 14, -1, MOV.BDCODTER) as BDCODTER, 1 as BDEMITENTE,
           sum(coalesce(MPRO.BDVLRITEM, 0)) as BDVLRITEM, 2 as BDMOVIMENTO, MPRO.BDCODCSTICMS, MPRO.BDCODCSTPIS,
           MPRO.BDCODCSTCOF, sum(coalesce(MPRO.BDQTDITEM, 0)) as BDQTDITEM, sum(coalesce(MPRO.BDVLRPIS, 0)) as BDVLRPIS,
           sum(coalesce(MPRO.BDVLRCOFINS, 0)) as BDVLRCOFINS, sum(coalesce(MPRO.BDBCPIS, 0)) as BDBCPIS,
           sum(coalesce(MPRO.BDBCCOFINS, 0)) as BDBCCOFINS, MPRO.BDALIQPIS, MPRO.BDALIQCOFINS, MPRO.BDALIQICMS,
           sum(coalesce(MPRO.BDBCICMS, 0)) as BDBCICMS, sum(coalesce(MPRO.BDVLRICMS, 0)) as BDVLRICMS,
           sum(coalesce(MPRO.BDVLRDESPACESSORIA, 0)) as BDVLRDESPACESSORIA,
           sum(coalesce(MPRO.BDVLRDESC, 0)) as BDVLRDESC
    from VEF_EMP_TMOVSAI MOV
                  inner join VEF_EMP_TMOVSAIITENS IT on IT.BDCODEMP = MOV.BDCODEMP and IT.BDCHAVE = MOV.BDCHAVE
                  inner join VEF_EMP_TMOVPROSAI MPRO on MPRO.BDCODEMP = IT.BDCODEMP and MPRO.BDCHAVE = IT.BDCHAVE and MPRO.BDORDEM = IT.BDORDEM
    inner join TTERCEIRO TER on TER.BDCODTER = MOV.BDCODTER
    where MOV.BDCODEMP = :WCODEMP and
          MOV.BDMODELO in (6, 28, 29, 66) and
          MOV.BDCODSITNF in (0, 1, 6, 7, 8) and
          extract(year from MOV.BDDATAEMISSAO) = :WANO and
          (coalesce(MOV.BDVALORNOTA, 0) > 0)
    group by MPRO.BDCODEMP, substring(IT.BDCODNAT from 1 for 4), iif(char_length(TER.BDCGCTER) = 14, -1, MOV.BDCODTER), MPRO.BDCODCSTICMS, MPRO.BDCODCSTPIS, MPRO.BDCODCSTCOF, MPRO.BDALIQPIS, MPRO.BDALIQCOFINS, MPRO.BDALIQICMS
 )
 select REF.BDCHAVE,
        row_number() over(partition by REF.BDCHAVE order by REF.BDCHAVE) + REF.BDULTORDEM as BDORDEM, DADOS.BDCODTER,
        DADOS.BDEMITENTE, DADOS.BDMOVIMENTO, DADOS.BDCODNAT, DADOS.BDCODCSTCOF, DADOS.BDCODCSTICMS, DADOS.BDCODCSTPIS,
        DADOS.BDQTDITEM, DADOS.BDVLRITEM, DADOS.BDVLRDESC, DADOS.BDVLRDESPACE, DADOS.BDBCICMS, DADOS.BDVL_BC_PIS,
        DADOS.BDVL_BC_COF, DADOS.BDALIQICMS, DADOS.BDALIQ_PIS, DADOS.BDALIQ_COF, DADOS.BDVLRICMS, DADOS.BDVLRPIS,
        DADOS.BDVLRCOFINS, 2
 from DADOS
    inner join REF on DADOS.BDCODEMP = REF.BDCODEMP
 where DADOS.BDVLRITEM > 0;
          end

  --================================Telecom
  --Entradas
        if (:WCFG_ENV_CFOP_ESP in ('T', 'E')) then
           begin
--              execute procedure SETFEEDBACK('Analisando movimento de entradas - Telecomunicações');

  insert into VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD (BDCHAVE, BDORDEM, BDCODTER, BDEMITENTE, BDMOVIMENTO, BDCFOP,
                                                  BDCODCSTCOF, BDCODCSTICMS, BDCODCSTPIS, BDQTDITEM, BDVLRITEM,
                                                  BDVLRDESC, BDBCICMS, BDBCPIS, BDBCCOFINS, BDALIQICMS, BDALIQPIS,
                                                  BDALIQCOFINS, BDVLRICMS, BDVLRPIS, BDVLRCOFINS, BDORIGEM)
  with REF
  as (select ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE, coalesce(max(TRIB.BDORDEM), 0) as BDULTORDEM
      from VEF_EMP_IM_SIMULADOR_REF_TRIB ENV
      left join VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD TRIB on ENV.BDCHAVE = TRIB.BDCHAVE
      where ENV.BDCHAVE = :PRCHAVE
      group by ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE),
  DADOS
  as (select MOV.BDCODEMP, sum(coalesce(IT.BDVLRCONTAB, D590.BDVLROPERACAO, 0)) as BDVLRITEM, MOV.BDCODTER,
             2 as BDEMITENTE, 1 as BDMOVIMENTO, max(D590.BDCODCSTICMS) as BDCODCSTICMS, D500.BDCODCSTPIS,
             D500.BDCODCSTCOF, 0 as BDQTDITEM,
             sum(coalesce(D500.BDVLRPIS, 0) * (coalesce(IT.BDVLRCONTAB, D590.BDVLROPERACAO, 0) / CAST(MOV.BDVALORNOTA AS NUMERIC(20,8)))) as BDVLRPIS,
             sum(coalesce(D500.BDVLRCOFINS, 0) * (coalesce(IT.BDVLRCONTAB, D590.BDVLROPERACAO, 0) / CAST(MOV.BDVALORNOTA AS NUMERIC(20,8)))) as BDVLRCOFINS,
             sum(coalesce(D500.BDVL_BC_PIS, 0) * (coalesce(IT.BDVLRCONTAB, D590.BDVLROPERACAO, 0) / CAST(MOV.BDVALORNOTA AS NUMERIC(20,8)))) as BDVL_BC_PIS,
             D500.BDALIQ_PIS,
             sum(coalesce(D500.BDVL_BC_COF, 0) * (coalesce(IT.BDVLRCONTAB, D590.BDVLROPERACAO, 0) / CAST(MOV.BDVALORNOTA AS NUMERIC(20,8)))) as BDVL_BC_COF,
             D500.BDALIQ_COF, max(coalesce(D590.BDALIQICMS, IT.BDALIQICMS, 0)) as BDALIQICMS,
             sum(coalesce(D590.BDBCICMS, IT.BDBASEICMS, 0)) as BDBCICMS,
             sum(coalesce(D590.BDVLRICMS, IT.BDVLRICMS, 0)) as BDVLRICMS,
             substring(IT.BDCODNAT from 1 for 4) as BDCODNAT, sum(coalesce(IT.BDDESCONTO, 0)) as BDVLRDESC
      from VEF_EMP_TMOVENT MOV
                    inner join VEF_EMP_TMOVENTITENS IT on IT.BDCODEMP = MOV.BDCODEMP and IT.BDCHAVE = MOV.BDCHAVE
                     left join VEF_EMP_TD500ENT D500 on D500.BDCODEMP = MOV.BDCODEMP and D500.BDCHAVE = MOV.BDCHAVE
                     left join VEF_EMP_TD590TOTENT D590 on D590.BDCODEMP = IT.BDCODEMP and D590.BDCHAVE = IT.BDCHAVE and D590.bdORDEM = IT.BDORDEM
      where MOV.BDCODEMP = :WCODEMP and
            MOV.BDMODELO in (21, 22, 62) and
            MOV.BDCODSITNF in (0, 1, 6, 7, 8) and
            (coalesce(MOV.BDVALORNOTA,0) > 0) and
                        extract(year from MOV.BDDATAENTRADAENT) = :WANO and
                        ((:WCFG_MESES = 'T') or ('' || :WCFG_MESES || '') like cast('%,' || extract(month from MOV.BDDATAENTRADAENT) || ',%' as varchar(30)))
      group by MOV.BDCODEMP, MOV.BDCODTER, D500.BDCODCSTPIS, D500.BDCODCSTCOF, D500.BDALIQ_PIS, D500.BDALIQ_COF, substring(IT.BDCODNAT from 1 for 4))
  select REF.BDCHAVE, row_number() over(partition by REF.BDCHAVE order by REF.BDCHAVE) + REF.BDULTORDEM as BDORDEM,
         DADOS.BDCODTER, DADOS.BDEMITENTE, DADOS.BDMOVIMENTO, DADOS.BDCODNAT, DADOS.BDCODCSTCOF, DADOS.BDCODCSTICMS,
         DADOS.BDCODCSTPIS, DADOS.BDQTDITEM, DADOS.BDVLRITEM, DADOS.BDVLRDESC, DADOS.BDBCICMS, DADOS.BDVL_BC_PIS,
         DADOS.BDVL_BC_COF, DADOS.BDALIQICMS, DADOS.BDALIQ_PIS, DADOS.BDALIQ_COF, DADOS.BDVLRICMS, DADOS.BDVLRPIS,
         DADOS.BDVLRCOFINS, 3
  from DADOS
  inner join REF on DADOS.BDCODEMP = REF.BDCODEMP
  where DADOS.BDVLRITEM > 0;
           end

   --Saídas
        if (:WCFG_ENV_CFOP_ESP in ('T', 'S')) then
           begin
--              execute procedure SETFEEDBACK('Analisando movimento de saídas - Telecomunicações');

  insert into VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD (BDCHAVE, BDORDEM, BDCODTER, BDEMITENTE, BDMOVIMENTO, BDCFOP,
                                                  BDCODCSTCOF, BDCODCSTICMS, BDCODCSTPIS, BDQTDITEM, BDVLRITEM,
                                                  BDVLRDESC, BDVLRDESPACESSORIA, BDBCICMS, BDBCPIS, BDBCCOFINS,
                                                  BDALIQICMS, BDALIQPIS, BDALIQCOFINS, BDVLRICMS, BDVLRPIS,
                                                  BDVLRCOFINS, BDORIGEM)
   with
       REF
  as (select ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE, coalesce(max(TRIB.BDORDEM), 0) as BDULTORDEM
      from VEF_EMP_IM_SIMULADOR_REF_TRIB ENV
        left join VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD TRIB on ENV.BDCHAVE = TRIB.BDCHAVE
      where ENV.BDCHAVE = :PRCHAVE
      group by ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE),
       DADOS
  as (select MOV.BDCODEMP, null as BDCODPROD, substring(IT.BDCODNAT from 1 for 4) as BDCODNAT,
             iif(char_length(TER.BDCGCTER) = 14, -1, MOV.BDCODTER) as BDCODTER, 1 as BDEMITENTE,
             sum(coalesce(IT.BDVLRCONTAB, 0)) as BDVLRITEM, 2 as BDMOVIMENTO,
             /*max(C590.BDCODCSTICMS)*/NULL as BDCODCSTICMS, NULL AS BDCODCSTPIS, NULL AS BDCODCSTCOF, 0 as BDQTDITEM,
             NULL as BDVLRPIS,
             NULL as BDVLRCOFINS,
             NULL as BDVL_BC_PIS,
             NULL as BDVL_BC_COF,
             NULL BDALIQ_PIS, NULL BDALIQ_COF, max(coalesce(IT.BDALIQICMS,0)) as BDALIQICMS,
             sum(coalesce(IT.BDBASEICMS, 0)) as BDBCICMS,
             sum(coalesce(IT.BDVLRICMS, 0)) as BDVLRICMS,
             NULL as BDVLRDESPACE,
             sum(coalesce(IT.BDDESCONTO, 0)) as BDVLRDESC
      from VEF_EMP_TMOVSAI MOV
      inner join VEF_EMP_TMOVSAIITENS IT on IT.BDCODEMP = MOV.BDCODEMP and IT.BDCHAVE = MOV.BDCHAVE
      inner join TTERCEIRO TER on TER.BDCODTER = MOV.BDCODTER
    where MOV.BDCODEMP = :WCODEMP and
          MOV.BDMODELO in (21,22,62) and
          MOV.BDCODSITNF in (0, 1, 6, 7, 8) and
          extract(year from MOV.BDDATAEMISSAO) = :WANO and
                      ((:WCFG_MESES = 'T') or ('' || :WCFG_MESES || '') like cast('%,' || extract(month from MOV.BDDATAEMISSAO) || ',%' as varchar(30))) and
          not exists (
                      select 1
                      from VEF_EMP_TMOVPROSAI P
                      where P.BDCHAVE = IT.BDCHAVE
                        and P.BDCODEMP = IT.BDCODEMP
                        and P.BDORDEM = IT.BDORDEM
                      )
    group by MOV.BDCODEMP, substring(IT.BDCODNAT from 1 for 4), iif(char_length(TER.BDCGCTER) = 14, -1, MOV.BDCODTER)
    union all
    select MPRO.BDCODEMP, null as BDCODPROD, substring(IT.BDCODNAT from 1 for 4) as BDCODNAT,
           iif(char_length(TER.BDCGCTER) = 14, -1, MOV.BDCODTER) as BDCODTER, 1 as BDEMITENTE,
           sum(coalesce(MPRO.BDVLRITEM, 0)) as BDVLRITEM, 2 as BDMOVIMENTO, MPRO.BDCODCSTICMS, MPRO.BDCODCSTPIS,
           MPRO.BDCODCSTCOF, sum(coalesce(MPRO.BDQTDITEM, 0)) as BDQTDITEM, sum(coalesce(MPRO.BDVLRPIS, 0)) as BDVLRPIS,
           sum(coalesce(MPRO.BDVLRCOFINS, 0)) as BDVLRCOFINS, sum(coalesce(MPRO.BDBCPIS, 0)) as BDBCPIS,
           sum(coalesce(MPRO.BDBCCOFINS, 0)) as BDBCCOFINS, MPRO.BDALIQPIS, MPRO.BDALIQCOFINS, MPRO.BDALIQICMS,
           sum(coalesce(MPRO.BDBCICMS, 0)) as BDBCICMS, sum(coalesce(MPRO.BDVLRICMS, 0)) as BDVLRICMS,
           sum(coalesce(MPRO.BDVLRDESPACESSORIA, 0)) as BDVLRDESPACESSORIA,
           sum(coalesce(MPRO.BDVLRDESC, 0)) as BDVLRDESC
    from VEF_EMP_TMOVSAI MOV
                  inner join VEF_EMP_TMOVSAIITENS IT on IT.BDCODEMP = MOV.BDCODEMP and IT.BDCHAVE = MOV.BDCHAVE
                  inner join VEF_EMP_TMOVPROSAI MPRO on MPRO.BDCODEMP = IT.BDCODEMP and MPRO.BDCHAVE = IT.BDCHAVE and MPRO.BDORDEM = IT.BDORDEM
    inner join TTERCEIRO TER on TER.BDCODTER = MOV.BDCODTER
    where MOV.BDCODEMP = :WCODEMP and
          MOV.BDMODELO in (21,22,62) and
          MOV.BDCODSITNF in (0, 1, 6, 7, 8) and
          extract(year from MOV.BDDATAEMISSAO) = :WANO and
          (coalesce(MOV.BDVALORNOTA, 0) > 0)
    group by MPRO.BDCODEMP, substring(IT.BDCODNAT from 1 for 4), iif(char_length(TER.BDCGCTER) = 14, -1, MOV.BDCODTER), MPRO.BDCODCSTICMS, MPRO.BDCODCSTPIS, MPRO.BDCODCSTCOF, MPRO.BDALIQPIS, MPRO.BDALIQCOFINS, MPRO.BDALIQICMS
 )
 select REF.BDCHAVE,
        row_number() over(partition by REF.BDCHAVE order by REF.BDCHAVE) + REF.BDULTORDEM as BDORDEM, DADOS.BDCODTER,
        DADOS.BDEMITENTE, DADOS.BDMOVIMENTO, DADOS.BDCODNAT, DADOS.BDCODCSTCOF, DADOS.BDCODCSTICMS, DADOS.BDCODCSTPIS,
        DADOS.BDQTDITEM, DADOS.BDVLRITEM, DADOS.BDVLRDESC, DADOS.BDVLRDESPACE, DADOS.BDBCICMS, DADOS.BDVL_BC_PIS,
        DADOS.BDVL_BC_COF, DADOS.BDALIQICMS, DADOS.BDALIQ_PIS, DADOS.BDALIQ_COF, DADOS.BDVLRICMS, DADOS.BDVLRPIS,
        DADOS.BDVLRCOFINS, 3
 from DADOS
    inner join REF on DADOS.BDCODEMP = REF.BDCODEMP
 where DADOS.BDVLRITEM > 0;
          end

  --================================Transportes
  --Entradas
        if (:WCFG_ENV_CFOP_ESP in ('T', 'E')) then
           begin
--              execute procedure SETFEEDBACK('Analisando movimento de entradas - Transportes');

  insert into VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD (BDCHAVE, BDORDEM, BDCODTER, BDEMITENTE, BDMOVIMENTO, BDCFOP,
                                                  BDCODCSTCOF, BDCODCSTICMS, BDCODCSTPIS, BDQTDITEM, BDVLRITEM,
                                                  BDVLRDESC, BDBCICMS, BDBCPIS, BDBCCOFINS, BDALIQICMS, BDALIQPIS,
                                                  BDALIQCOFINS, BDVLRICMS, BDVLRPIS, BDVLRCOFINS, BDORIGEM)
  with REF
  as (select ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE, coalesce(max(TRIB.BDORDEM), 0) as BDULTORDEM
      from VEF_EMP_IM_SIMULADOR_REF_TRIB ENV
      left join VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD TRIB on ENV.BDCHAVE = TRIB.BDCHAVE
      where ENV.BDCHAVE = :PRCHAVE
      group by ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE),
  DADOS
  as (select MOV.BDCODEMP, sum(coalesce(IT.BDVLRCONTAB, 0)) as BDVLRITEM, MOV.BDCODTER, 2 as BDEMITENTE,
             1 as BDMOVIMENTO, max(IT.BDCODCSTICMS) as BDCODCSTICMS, D100.BDCODCSTPIS, D100.BDCODCSTCOF, 0 as BDQTDITEM,
             sum(coalesce(D100.BDVLRPIS, 0) * (coalesce(IT.BDVLRCONTAB, 0) / CAST(MOV.BDVALORNOTA AS NUMERIC(20,8)))) as BDVLRPIS,
             sum(coalesce(D100.BDVLRCOFINS, 0) * (coalesce(IT.BDVLRCONTAB, 0) / CAST(MOV.BDVALORNOTA AS NUMERIC(20,8)))) as BDVLRCOFINS,
             sum(coalesce(D100.BDVL_BC_PIS, 0) * (coalesce(IT.BDVLRCONTAB, 0) / CAST(MOV.BDVALORNOTA AS NUMERIC(20,8)))) as BDVL_BC_PIS, D100.BDALIQ_PIS,
             sum(coalesce(D100.BDVL_BC_COF, 0) * (coalesce(IT.BDVLRCONTAB, 0) / CAST(MOV.BDVALORNOTA AS NUMERIC(20,8)))) as BDVL_BC_COF, D100.BDALIQ_COF, max(IT.BDALIQICMS) as BDALIQICMS,
             sum(coalesce(IT.BDBASEICMS, 0)) as BDBCICMS, sum(coalesce(IT.BDVLRICMS, 0)) as BDVLRICMS,
             substring(IT.BDCODNAT from 1 for 4) as BDCODNAT, sum(coalesce(IT.BDDESCONTO, 0)) as BDVLRDESC
      from VEF_EMP_TMOVENT MOV
                    inner join VEF_EMP_TMOVENTITENS IT on IT.BDCODEMP = MOV.BDCODEMP and IT.BDCHAVE = MOV.BDCHAVE
                     left join VEF_EMP_TD100ENT D100 on D100.BDCODEMP = MOV.BDCODEMP and D100.BDCHAVE = MOV.BDCHAVE
      where MOV.BDCODEMP = :WCODEMP and
                        MOV.BDMODELO in (7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 26, 27, 57, 63, 67) and
            MOV.BDCODSITNF in (0, 1, 6, 7, 8) and
            (coalesce(MOV.BDVALORNOTA,0) > 0) and
                        extract(year from MOV.BDDATAENTRADAENT) = :WANO and
                        ((:WCFG_MESES = 'T') or ('' || :WCFG_MESES || '') like cast('%,' || extract(month from MOV.BDDATAENTRADAENT) || ',%' as varchar(30)))
      group by MOV.BDCODEMP, MOV.BDCODTER, D100.BDCODCSTPIS, D100.BDCODCSTCOF, D100.BDALIQ_PIS, D100.BDALIQ_COF, substring(IT.BDCODNAT from 1 for 4))
  select REF.BDCHAVE, row_number() over(partition by REF.BDCHAVE order by REF.BDCHAVE) + REF.BDULTORDEM as BDORDEM,
         DADOS.BDCODTER, DADOS.BDEMITENTE, DADOS.BDMOVIMENTO, DADOS.BDCODNAT, DADOS.BDCODCSTCOF, DADOS.BDCODCSTICMS,
         DADOS.BDCODCSTPIS, DADOS.BDQTDITEM, DADOS.BDVLRITEM, DADOS.BDVLRDESC, DADOS.BDBCICMS, DADOS.BDVL_BC_PIS,
         DADOS.BDVL_BC_COF, DADOS.BDALIQICMS, DADOS.BDALIQ_PIS, DADOS.BDALIQ_COF, DADOS.BDVLRICMS, DADOS.BDVLRPIS,
         DADOS.BDVLRCOFINS, 4
  from DADOS
  inner join REF on DADOS.BDCODEMP = REF.BDCODEMP
  where DADOS.BDVLRITEM > 0;
           end

  --Saídas
        if (:WCFG_ENV_CFOP_ESP in ('T', 'S')) then
           begin
--              execute procedure SETFEEDBACK('Analisando movimento de saídas - Transportes');

  insert into VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD (BDCHAVE, BDORDEM, BDCODTER, BDEMITENTE, BDMOVIMENTO, BDCFOP,
                                                  BDCODCSTCOF, BDCODCSTICMS, BDCODCSTPIS, BDQTDITEM, BDVLRITEM,
                                                  BDVLRDESC, BDBCICMS, BDBCPIS, BDBCCOFINS, BDALIQICMS, BDALIQPIS,
                                                  BDALIQCOFINS, BDVLRICMS, BDVLRPIS, BDVLRCOFINS, BDORIGEM)
  with REF
  as (select ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE, coalesce(max(TRIB.BDORDEM), 0) as BDULTORDEM
      from VEF_EMP_IM_SIMULADOR_REF_TRIB ENV
      left join VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD TRIB on ENV.BDCHAVE = TRIB.BDCHAVE
      where ENV.BDCHAVE = :PRCHAVE
      group by ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE),
  DADOS
  as (select MOV.BDCODEMP, sum(coalesce(IT.BDVLRCONTAB, 0)) as BDVLRITEM, MOV.BDCODTER, 1 as BDEMITENTE,
             2 as BDMOVIMENTO, max(IT.BDCODCSTICMS) as BDCODCSTICMS, D100.BDCODCSTPIS, D100.BDCODCSTCOF, 0 as BDQTDITEM,
             sum(coalesce(D100.BDVLRPIS, 0) * (coalesce(IT.BDVLRCONTAB, 0) / CAST(MOV.BDVALORNOTA AS NUMERIC(20,8)))) as BDVLRPIS,
             sum(coalesce(D100.BDVLRCOFINS, 0) * (coalesce(IT.BDVLRCONTAB, 0) / CAST(MOV.BDVALORNOTA AS NUMERIC(20,8)))) as BDVLRCOFINS,
             sum(coalesce(D100.BDVL_BC_PIS, 0) * (coalesce(IT.BDVLRCONTAB, 0) / CAST(MOV.BDVALORNOTA AS NUMERIC(20,8)))) as BDVL_BC_PIS, D100.BDALIQ_PIS,
             sum(coalesce(D100.BDVL_BC_COF, 0) * (coalesce(IT.BDVLRCONTAB, 0) / CAST(MOV.BDVALORNOTA AS NUMERIC(20,8)))) as BDVL_BC_COF, D100.BDALIQ_COF, max(IT.BDALIQICMS) as BDALIQICMS,
             sum(coalesce(IT.BDBASEICMS, 0)) as BDBCICMS, sum(coalesce(IT.BDVLRICMS, 0)) as BDVLRICMS,
             substring(IT.BDCODNAT from 1 for 4) as BDCODNAT, sum(coalesce(IT.BDDESCONTO, 0)) as BDVLRDESC
      from VEF_EMP_TMOVSAI MOV
                    inner join VEF_EMP_TMOVSAIITENS IT on IT.BDCODEMP = MOV.BDCODEMP and IT.BDCHAVE = MOV.BDCHAVE
                     left join VEF_EMP_TD100SAI D100 on D100.BDCODEMP = MOV.BDCODEMP and D100.BDCHAVE = MOV.BDCHAVE
      where MOV.BDCODEMP = :WCODEMP and
            MOV.BDMODELO in (7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 26, 27, 57, 63, 67) and
            (coalesce(MOV.BDVALORNOTA,0) > 0) and
            MOV.BDCODSITNF in (0, 1, 6, 7, 8) and
                        extract(year from MOV.BDDATAEMISSAO) = :WANO and
                        ((:WCFG_MESES = 'T') or ('' || :WCFG_MESES || '') like cast('%,' || extract(month from MOV.BDDATAEMISSAO) || ',%' as varchar(30)))
      group by MOV.BDCODEMP, MOV.BDCODTER, D100.BDCODCSTPIS, D100.BDCODCSTCOF, D100.BDALIQ_PIS, D100.BDALIQ_COF, substring(IT.BDCODNAT from 1 for 4))
  select REF.BDCHAVE, row_number() over(partition by REF.BDCHAVE order by REF.BDCHAVE) + REF.BDULTORDEM as BDORDEM,
         DADOS.BDCODTER, DADOS.BDEMITENTE, DADOS.BDMOVIMENTO, DADOS.BDCODNAT, DADOS.BDCODCSTCOF, DADOS.BDCODCSTICMS,
         DADOS.BDCODCSTPIS, DADOS.BDQTDITEM, DADOS.BDVLRITEM, DADOS.BDVLRDESC, DADOS.BDBCICMS, DADOS.BDVL_BC_PIS,
         DADOS.BDVL_BC_COF, DADOS.BDALIQICMS, DADOS.BDALIQ_PIS, DADOS.BDALIQ_COF, DADOS.BDVLRICMS, DADOS.BDVLRPIS,
         DADOS.BDVLRCOFINS, 4
  from DADOS
  inner join REF on DADOS.BDCODEMP = REF.BDCODEMP
  where DADOS.BDVLRITEM > 0;
           end

        if (:WCFG_TOTAL_CFOP_ESP > 0) then
           begin
              delete from VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD a
              where a.BDCHAVE = :prCHAVE
                and bdorigem in (2,3,4)
                and not exists (
                  select 1
                  from (
                    select BDCHAVE, BDORDEM
                    from VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD
                    where BDCHAVE = :prCHAVE
                      and bdorigem in (2,3,4)
                    order by BDORDEM
                    rows :WCFG_TOTAL_CFOP_ESP
                  ) x
                  where x.BDCHAVE = a.BDCHAVE and x.BDORDEM = a.BDORDEM
                );
           end

     end
  --================================Redução Z
  if (:WCFG_ENV_PROD in ('T', 'S')) then
     begin
--         execute procedure SETFEEDBACK('Analisando movimento de redução Z');

  insert into VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD (BDCHAVE, BDORDEM, BDCODPROD, BDEMITENTE, BDMOVIMENTO, BDCFOP,
                                                  BDCODCSTCOF, BDCODCSTICMS, BDCODCSTPIS, BDQTDITEM, BDVLRITEM,
                                                  BDBCICMS, BDBCPIS, BDBCCOFINS, BDALIQICMS, BDALIQPIS, BDALIQCOFINS,
                                                  BDVLRICMS, BDVLRPIS, BDVLRCOFINS, BDORIGEM)
  with REF
  as (select ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE, coalesce(max(TRIB.BDORDEM), 0) as BDULTORDEM
      from VEF_EMP_IM_SIMULADOR_REF_TRIB ENV
      left join VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD TRIB on ENV.BDCHAVE = TRIB.BDCHAVE
      where ENV.BDCHAVE = :PRCHAVE
      group by ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE),
  DADOS
  as (select MOV.BDCODEMP, 1 as BDEMITENTE, 2 as BDMOVIMENTO, C425.BDCODPROD, C425.BDCODCSTICMS, C425.BDCODCSTPIS,
             C425.BDCODCSTCOF, sum(C425.BDQTDACU) as BDQTDITEM, sum(C425.BDVLRACU) as BDVLRITEM,
             sum(C425.BDVLRCOFINS) as BDVLRCOFINS, sum(C425.BDVLRPIS) as BDVLRPIS, sum(C425.BDVL_BC_PIS) as BDVL_BC_PIS,
             C425.BDALIQ_PIS, sum(C425.BDVL_BC_COFINS) as BDVL_BC_COFINS, C425.BDALIQ_COFINS,
             C425.BDALIQTOT as BDALIQICMS, sum(C425.BDBASEICMS) as BDBCICMS, sum(C425.BDVLRICMS) as BDVLRICMS,
             substring(C425.BDCODNAT from 1 for 4) as BDCODNAT
      from VEF_EMP_TREDZ MOV
               inner join VEF_EMP_TREDZC425 C425 on C425.BDCODEMP = MOV.BDCODEMP and C425.BDCHAVE = MOV.BDCHAVE
      where MOV.BDCODEMP = :WCODEMP and
                   extract(year from MOV.BDDATAREDZ) = :WANO and
                   ((:WCFG_MESES = 'T') or ('' || :WCFG_MESES || '') like cast('%,' || extract(month from MOV.BDDATAREDZ) || ',%' as varchar(30)))
      group by MOV.BDCODEMP, C425.BDCODPROD, C425.BDCODCSTICMS, C425.BDCODCSTPIS, C425.BDCODCSTCOF, C425.BDALIQ_PIS, C425.BDALIQ_COFINS, C425.BDALIQTOT, substring(C425.BDCODNAT from 1 for 4)
      union all
      select MOV.BDCODEMP, 1 as BDEMITENTE, 2 as BDMOVIMENTO, C425.BDCODPROD, C425.BDCODCSTICMS, C425.BDCODCSTPIS,
             C425.BDCODCSTCOF, sum(C425.BDQTDACU) as BDQTDITEM, sum(C425.BDVLRACU) as BDVLRITEM,
             sum(C425.BDVLRCOFINS) as BDVLRCOFINS, sum(C425.BDVLRPIS) as BDVLRPIS, sum(C425.BDVL_BC_PIS) as BDVL_BC_PIS,
             C425.BDALIQ_PIS, sum(C425.BDVL_BC_COFINS) as BDVL_BC_COFINS, C425.BDALIQ_COFINS,
             C425.BDALIQTOT as BDALIQICMS, sum(C425.BDBASEICMS) as BDBCICMS, sum(C425.BDVLRICMS) as BDVLRICMS,
             substring(C425.BDCODNAT from 1 for 4) as BDCODNAT
      from VEF_EMP_TREDZ MOV
               inner join VEF_EMP_TREDZC425ALIQ C425 on C425.BDCODEMP = MOV.BDCODEMP and C425.BDCHAVE = MOV.BDCHAVE
      where MOV.BDCODEMP = :WCODEMP and
                   extract(year from MOV.BDDATAREDZ) = :WANO and
                   ((:WCFG_MESES = 'T') or ('' || :WCFG_MESES || '') like cast('%,' || extract(month from MOV.BDDATAREDZ) || ',%' as varchar(30)))
      group by MOV.BDCODEMP, C425.BDCODPROD, C425.BDCODCSTICMS, C425.BDCODCSTPIS, C425.BDCODCSTCOF, C425.BDALIQ_PIS, C425.BDALIQ_COFINS, C425.BDALIQTOT, substring(C425.BDCODNAT from 1 for 4)
      union all
      select MOV.BDCODEMP, 1 as BDEMITENTE, 2 as BDMOVIMENTO, C470.BDCODPROD, C470.BDCODCSTICMS, C470.BDCODCSTPIS,
             C470.BDCODCSTCOF, sum(C470.BDQTDITEM) as BDQTDITEM, sum(C470.BDVLRTOTPRO) as BDVLRITEM,
             sum(C470.BDVLRCOFINS) as BDVLRCOFINS, sum(C470.BDVLRPIS) as BDVLRPIS, sum(C470.BDVL_BC_PIS) as BDVL_BC_PIS,
             C470.BDALIQ_PIS, sum(C470.BDVL_BC_COFINS) as BDVL_BC_COFINS, C470.BDALIQ_COFINS, C470.BDALIQICMS, sum(
                    case when C470.BDALIQICMS > 0 then C470.BDVLRTOTPRO else 0 end) as BDBCICMS,
             sum(C470.BDVLRICMS) as BDVLRICMS, substring(C470.BDCODNAT from 1 for 4) as BDCODNAT
      from VEF_EMP_TREDZ MOV
               inner join VEF_EMP_TITEMDOCECF C470 on C470.BDCODEMP = MOV.BDCODEMP and C470.BDCHAVE = MOV.BDCHAVE
      where MOV.BDCODEMP = :WCODEMP and
                   extract(year from MOV.BDDATAREDZ) = :WANO and
                   ((:WCFG_MESES = 'T') or ('' || :WCFG_MESES || '') like cast('%,' || extract(month from MOV.BDDATAREDZ) || ',%' as varchar(30)))
      group by MOV.BDCODEMP, C470.BDCODPROD, C470.BDCODCSTICMS, C470.BDCODCSTPIS, C470.BDCODCSTCOF, C470.BDALIQ_PIS, C470.BDALIQ_COFINS, C470.BDALIQICMS, substring(C470.BDCODNAT from 1 for 4))
  select REF.BDCHAVE, row_number() over(partition by REF.BDCHAVE order by REF.BDCHAVE) + REF.BDULTORDEM as BDORDEM,
         DADOS.BDCODPROD, DADOS.BDEMITENTE, DADOS.BDMOVIMENTO, DADOS.BDCODNAT, DADOS.BDCODCSTCOF, DADOS.BDCODCSTICMS,
         DADOS.BDCODCSTPIS, DADOS.BDQTDITEM, DADOS.BDVLRITEM, DADOS.BDBCICMS, DADOS.BDVL_BC_PIS, DADOS.BDVL_BC_COFINS,
         DADOS.BDALIQICMS, DADOS.BDALIQ_PIS, DADOS.BDALIQ_COFINS, DADOS.BDVLRICMS, DADOS.BDVLRPIS, DADOS.BDVLRCOFINS, 5
  from DADOS
  inner join REF on DADOS.BDCODEMP = REF.BDCODEMP
  where DADOS.BDVLRITEM > 0;
      end

  /*
  --Chegou a hora e a vez dos serviços
  execute procedure SETFEEDBACK('Analisando movimento de serviços');
  insert into VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD (BDCHAVE, BDORDEM, BDCODTER, BDEMITENTE, BDMOVIMENTO, BDCODCSTCOF,
                                                  BDCODCSTPIS, BDVLRITEM, BDBCPIS, BDBCCOFINS, BDALIQPIS, BDALIQCOFINS,
                                                  BDVLRPIS, BDVLRCOFINS, BDCFOP, BDCODATVM, BDVLRISSQN, BDBCISSQN, BDORIGEM)
  with REF
  as (select ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE, coalesce(max(TRIB.BDORDEM), 0) as BDULTORDEM
      from VEF_EMP_IM_SIMULADOR_REF_TRIB ENV
        left join VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD TRIB on ENV.BDCHAVE = TRIB.BDCHAVE
      where ENV.BDCHAVE = :PRCHAVE
      group by ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE),
  DADOS
  as (select MOV.BDCODEMP, sum(IT.BDVLRCONTAB) as BDVLRITEM, MOV.BDCODTER,
             case
               when MOV.BDTIPLAN = 0 then 1
               else 2
             end as BDEMITENTE,
             case
               when MOV.BDTIPLAN = 0 then 3
               else 4
             end as BDMOVIMENTO,
             A170.BDCODCSTPIS, A170.BDCODCSTCOF, sum(coalesce(A170.BDVL_PIS, 0)) as BDVLRPIS, sum(coalesce(A170.BDVL_COFINS, 0)) as BDVLRCOFINS,
             sum(coalesce(A170.BDVL_BC_PIS,0)) as BDVL_BC_PIS, A170.BDALIQ_PIS, sum(coalesce(A170.BDVL_BC_COFINS,0)) as BDVL_BC_COF,
             A170.BDALIQ_COFINS, substring(IT.BDCODNAT from 1 for 4) as BDCODNAT, sum(IT.BDDESCONTO) as BDVLRDESC,
             IT.BDCODATVM, sum(IT.BDVLRISSSER) as BDVLRISSSER, sum(IT.BDBCISSSER) as BDBCISSSER
      from VEF_EMP_TMOVSER MOV
        inner join VEF_EMP_TMOVSERITENS IT on IT.BDCODEMP = MOV.BDCODEMP and IT.BDCHAVE = MOV.BDCHAVE
         left join VEF_EMP_TA170 A170 on A170.BDCODEMP = MOV.BDCODEMP and A170.BDCHAVE = MOV.BDCHAVE
      where MOV.BDCODEMP = :WCODEMP
        and extract(year from MOV.BDDATAEMISSAO) = :WANO
      group by MOV.BDCODEMP, MOV.BDCODTER, A170.BDCODCSTPIS, A170.BDCODCSTCOF, A170.BDALIQ_PIS, A170.BDALIQ_COFINS, substring(IT.BDCODNAT from 1 for 4), MOV.BDTIPLAN, IT.BDCODATVM)
  select REF.BDCHAVE, row_number() over(partition by REF.BDCHAVE order by REF.BDCHAVE) + REF.BDULTORDEM as BDORDEM,
         DADOS.BDCODTER, DADOS.BDEMITENTE, DADOS.BDMOVIMENTO, DADOS.BDCODCSTCOF, DADOS.BDCODCSTPIS, DADOS.BDVLRITEM,
         DADOS.BDVL_BC_PIS, DADOS.BDVL_BC_COF, DADOS.BDALIQ_PIS, DADOS.BDALIQ_COFINS, DADOS.BDVLRPIS,
         DADOS.BDVLRCOFINS, DADOS.BDCODNAT, DADOS.BDCODATVM, DADOS.BDVLRISSSER, DADOS.BDBCISSSER, 6
  from DADOS
  inner join REF on DADOS.BDCODEMP = REF.BDCODEMP
  where DADOS.BDVLRITEM > 0;

  --Demais documentos
  execute procedure SETFEEDBACK('Analisando movimento de demais documentos');
  insert into VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD (BDCHAVE, BDORDEM, BDCODTER, BDEMITENTE, BDMOVIMENTO, BDCODCSTCOF,
                                                  BDCODCSTPIS, BDVLRITEM, BDBCPIS, BDBCCOFINS, BDALIQPIS, BDALIQCOFINS,
                                                  BDVLRPIS, BDVLRCOFINS, BDTIPODEMAISDOC, BDTIPOOPERACAO, BDORIGEM)
  with REF
  as (select ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE, coalesce(max(TRIB.BDORDEM), 0) as BDULTORDEM
      from VEF_EMP_IM_SIMULADOR_REF_TRIB ENV
      left join VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD TRIB on ENV.BDCHAVE = TRIB.BDCHAVE
      where ENV.BDCHAVE = :PRCHAVE
      group by ENV.BDCODEMP, ENV.BDSTATUS, ENV.BDCHAVE),
  DADOS
  as (select MOV.BDCODEMP, sum(MOV.BDVL_OPER) as BDVLRITEM, MOV.BDCODTER, 1 as BDEMITENTE,
             case
               when MOV.BDIND_OPER = 1 then 5
               else 6
             end as BDMOVIMENTO,
             MOV.BDCODCSTPIS, MOV.BDCODCSTCOF, sum(MOV.BDVLR_PIS) as BDVLR_PIS, sum(MOV.BDVLR_COFINS) as BDVLR_COFINS,
             sum(MOV.BDVL_BC_PIS) as BDVL_BC_PIS, MOV.BDALIQ_PIS, sum(MOV.BDVL_BC_COFINS) as BDVL_BC_COFINS,
             MOV.BDALIQ_COFINS, MOV.BDCODTIPODOC, MOV.BDIND_OPER
      from VEF_EMP_TMOVDEMAISDOC_F100 MOV
      where MOV.BDCODEMP = :WCODEMP and
            extract(year from MOV.BDDT_OPER) = :WANO
      group by MOV.BDCODEMP, MOV.BDCODTER, MOV.BDCODCSTPIS, MOV.BDCODCSTCOF, MOV.BDALIQ_PIS, MOV.BDALIQ_COFINS, MOV.BDCODTIPODOC, MOV.BDIND_OPER)
  select REF.BDCHAVE, row_number() over(partition by REF.BDCHAVE order by REF.BDCHAVE) + REF.BDULTORDEM as BDORDEM,
         DADOS.BDCODTER, DADOS.BDEMITENTE, DADOS.BDMOVIMENTO, DADOS.BDCODCSTCOF, DADOS.BDCODCSTPIS, DADOS.BDVLRITEM,
         DADOS.BDVL_BC_PIS, DADOS.BDVL_BC_COFINS, DADOS.BDALIQ_PIS, DADOS.BDALIQ_COFINS, DADOS.BDVLR_PIS,
         DADOS.BDVLR_COFINS, DADOS.BDCODTIPODOC, DADOS.BDIND_OPER, 7
  from DADOS
  inner join REF on DADOS.BDCODEMP = REF.BDCODEMP
  where DADOS.BDVLRITEM > 0; */

  --Vamos fazer os cortes aqui....
  if (:WCFG_TOTAL_LAN > 0) then
     begin
        delete from VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD a
        where a.BDCHAVE = :prCHAVE
          and not exists (
            select 1
            from (
              select BDCHAVE, BDORDEM
              from VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD
              where BDCHAVE = :prCHAVE
              order by BDORDEM
              rows :WCFG_TOTAL_LAN
            ) x
            where x.BDCHAVE = a.BDCHAVE and x.BDORDEM = a.BDORDEM
          );
     end

  --Vamos inserir os produtos que estão incompletos....
  insert into VEF_EMP_IM_SIM_RT_PROD_NCAD (BDCODEMP, BDCODPRO)
  select TPROEMP.BDCODEMP, TPROEMP.BDCODPROD
  from VEF_EMP_IM_SIMULADOR_REF_TRIB TRIB
    inner join VEF_EMP_IM_SIMULADOR_REF_TRIB_PROD PROD on TRIB.BDCHAVE = PROD.BDCHAVE
    inner join TCADPRO TPRO on TPRO.BDCODPROD = PROD.BDCODPROD
    inner join TCADPRO_VINC TPROEMP on TPROEMP.BDCODPROD = PROD.BDCODPROD and TPROEMP.BDCODEMP = TRIB.BDCODEMP
  where PROD.BDCHAVE = :prChave and
        (coalesce(trim(TPRO.BDCODIGOEAN), '') = '') and
        (TPROEMP.BDNCMPROD is null) and
        (coalesce(trim(TPROEMP.BDCODIAT), '') = '') and
        not exists(select 1
                   from VEF_EMP_IM_SIM_RT_PROD_NCAD NCAD
                   where NCAD.BDCODEMP = TPROEMP.BDCODEMP and
                         NCAD.BDCODPRO = TPROEMP.BDCODPROD)
  group by TPROEMP.BDCODEMP, TPROEMP.BDCODPROD;
end^

CREATE OR ALTER PROCEDURE SP_BLOCOM_DADOSFINAIS_M400_M800 (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRCODEMPPRINCIPALSCP INTEGER,
    PRRETIFICADORA INTEGER,
    PRAJUSTESCP DM_BOOLEAN)
AS
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WEXPNFCOMVALSAI VARCHAR(5);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCSTCOF INTEGER;
DECLARE VARIABLE WCODCSTPIS INTEGER;
DECLARE VARIABLE WCODNATREC INTEGER;
DECLARE VARIABLE WALIQPIS NUMERIC(8,4);
DECLARE VARIABLE WALIQCOFINS NUMERIC(8,4);
DECLARE VARIABLE WVLRITEM NUMERIC(15,2);
DECLARE VARIABLE WBCPIS NUMERIC(15,2);
DECLARE VARIABLE WBCCOFINS NUMERIC(15,2);
DECLARE VARIABLE WVLRPIS NUMERIC(15,2);
DECLARE VARIABLE WVLRCOFINS NUMERIC(15,2);
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WVLDIF DM_NUMERIC_15_2;
DECLARE VARIABLE WVL_TOT_REC DM_NUMERIC_15_2;
BEGIN
  SELECT BDINCTRIB+1, BDCODCRIT, BDEXPNFCOMVALSAI FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :wINCTRIB, :wCODCRIT, :wEXPNFCOMVALSAI;

  IF ((wINCTRIB IS NOT NULL) AND (wEXPNFCOMVALSAI <> 'TRUE')) THEN
    BEGIN
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidencia tributaria <> de "exclusivamente nao-cumulativo" e criterio de escrituracao = "Regime de caixa"...
        BEGIN
          FOR
            SELECT AUX.BDCODEMP, AUX.BDCODCSTCOF, AUX.BDCODCSTPIS, /*AUX.BDCODNATREC, AUX.BDALIQPIS, AUX.BDALIQCOFINS,*/
                   SUM(AUX.BDVLRITEM) BDVLRITEM/*,
                   SUM(AUX.BDBCPIS) BDBCPIS,
                   SUM(AUX.BDBCCOFINS) BDBCCOFINS,
                   SUM(AUX.BDVLRPIS) BDVLRPIS,
                   SUM(AUX.BDVLRCOFINS) BDVLRCOFINS*/
            FROM (
            SELECT COALESCE(EMPSCP.BDCODEMPSCP, SAI.BDCODEMP) BDCODEMP, SAI.BDCODTER, MOVPRO.BDCODCSTCOF, MOVPRO.BDCODCSTPIS, MOVPRO.BDCODNATREC, MOVPRO.BDALIQPIS, MOVPRO.BDALIQCOFINS, ITENS.BDCODNAT, SAI.BDMODELO,
                   SAI.BDSERIE, SAI.BDSUBSERIE, SAI.BDCODSITNF, SAI.BDNUMDOCINI, SAI.BDNUMDOCFIM, 0 AS BDCODPLAPADRAO, 0 AS BDCREDITO, 0 AS BDREFERENCIA, 
                        CAST(((CAST(SAI.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(IVLR.BDVLRCONTABTOTAL = 0, 1, IVLR.BDVLRCONTABTOTAL) AS NUMERIC(15,4)))* COALESCE(MOVPRO.BDVLRITEM, 0))   AS DM_NUMERIC_15_2) BDVLRITEM, 
                        CAST(((CAST(SAI.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(IVLR.BDVLRCONTABTOTAL = 0, 1, IVLR.BDVLRCONTABTOTAL) AS NUMERIC(15,4)))* COALESCE(MOVPRO.BDBCPIS, 0))     AS DM_NUMERIC_15_2) BDBCPIS, 
                        CAST(((CAST(SAI.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(IVLR.BDVLRCONTABTOTAL = 0, 1, IVLR.BDVLRCONTABTOTAL) AS NUMERIC(15,4)))* COALESCE(MOVPRO.BDBCCOFINS, 0))  AS DM_NUMERIC_15_2) BDBCCOFINS, 
                        CAST(((CAST(SAI.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(IVLR.BDVLRCONTABTOTAL = 0, 1, IVLR.BDVLRCONTABTOTAL) AS NUMERIC(15,4)))* COALESCE(MOVPRO.BDVLRPIS, 0))    AS DM_NUMERIC_15_2) BDVLRPIS, 
                        CAST(((CAST(SAI.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(IVLR.BDVLRCONTABTOTAL = 0, 1, IVLR.BDVLRCONTABTOTAL) AS NUMERIC(15,4)))* COALESCE(MOVPRO.BDVLRCOFINS, 0)) AS DM_NUMERIC_15_2) BDVLRCOFINS, 
                        IIF(COALESCE(EMPSCP.BDCODEMPSCP,0) > 0,SAI.BDCODEMP,NULL) BDCODEMPSOCIA, ITENS.BDVLRICMS 
            FROM ( 
                  SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDCODTER,MOV.BDMODELO,MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM,
                         MOV.BDVALORNOTA, SUM(AUX.BDVALORPGTOPAR) BDVALORPGTOPAR, SUM(AUX.BDVALORPAR) BDVALORPAR
                  FROM (
                        SELECT AUX.BDCODEMP, AUX.BDCHAVE, AUX.BDREFLAN, SUM(COALESCE(AUX.BDVALORPGTOPAR, 0)) BDVALORPGTOPAR, CAST(SUM(COALESCE(CAST(PAR.BDVALORPAR AS DM_NUMERIC_15_2), 0)) + 
                               SUM(COALESCE(PAR.BDVALORRETPIS, 0)) + SUM(COALESCE(PAR.BDVALORRETCOFINS, 0)) + SUM(COALESCE(PAR.BDVALORRETCSLL, 0)) + 
                               SUM(COALESCE(PAR.BDVALORRETIRRF, 0)) + SUM(COALESCE(PAR.BDVALORRETISSQN, 0)) + SUM(COALESCE(PAR.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) - 0.00 BDVALORPAR 
                        FROM( 
                             SELECT M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, P.BDORDEMPAR, 
                                    CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + 
                                     SUM(COALESCE(P.BDVALORRETPIS, 0)) + 
                                     SUM(COALESCE(P.BDVALORRETCOFINS, 0)) + 
                                     SUM(COALESCE(P.BDVALORRETCSLL, 0)) + 
                                     SUM(COALESCE(P.BDVALORRETIRRF, 0)) + 
                                     SUM(COALESCE(P.BDVALORRETISSQN, 0)) + 
                                     SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR 
                             FROM (SELECT * FROM VEF_EMP_TMOVSAI WHERE BDCODEMP = :PRCODEMP) M
                             JOIN VEF_EMP_TMOVSAIPARPGTO P ON (P.BDCODEMP = M.BDCODEMP AND P.BDCHAVE = M.BDCHAVE AND
                                                               EXTRACT(YEAR FROM P.BDDATAPGTOPAR)||LPAD(EXTRACT(MONTH FROM P.BDDATAPGTOPAR),2,'0') = :PRREFERENCIA AND
                                                               P.BDCODTIPOBAIXA = 1)
                             LEFT OUTER JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = P.BDCODEMP AND PAR.BDCHAVE = P.BDCHAVE AND PAR.BDORDEMPAR = P.BDORDEMPAR) 
                             LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = P.BDCODNAT) 
                             WHERE P.BDCODTIPOBAIXA = 1
                               AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) = TRIM('FALSE'))) 
                               AND ((M.BDCODSITNF NOT IN (2,3,4,5) )) 
                               AND (M.BDMODELO NOT IN (7,8,9,10,11,13,14,15,16,26,27,57,67,800,63)) 
                             GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, P.BDORDEMPAR 
                            ) AUX 
                          LEFT OUTER JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = AUX.BDCODEMP AND PAR.BDCHAVE = AUX.BDCHAVE AND PAR.BDORDEMPAR = AUX.BDORDEMPAR) 
                          GROUP BY AUX.BDCODEMP, AUX.BDCHAVE, AUX.BDREFLAN
                          ) AUX 
               LEFT OUTER JOIN  VEF_EMP_TMOVSAI MOV ON (MOV.BDCODEMP = AUX.BDCODEMP AND MOV.BDCHAVE = AUX.BDCHAVE) 
               WHERE AUX.BDVALORPGTOPAR > 0 
               AND ((SELECT FIRST 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER P 
               WHERE P.BDCODEMP = AUX.BDCODEMP AND P.BDREFEMP <= AUX.BDREFLAN ORDER BY BDCODEMP DESC, BDREFEMP DESC) = 1) 
               GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDCODTER,MOV.BDMODELO,MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM, MOV.BDVALORNOTA
            ) SAI 
             JOIN VEF_EMP_TMOVSAIITENS ITENS ON (SAI.BDCODEMP = ITENS.BDCODEMP AND SAI.BDCHAVE = ITENS.BDCHAVE) 
             JOIN VEF_EMP_TMOVPROSAI MOVPRO ON (ITENS.BDCODEMP = MOVPRO.BDCODEMP AND ITENS.BDCHAVE = MOVPRO.BDCHAVE AND ITENS.BDORDEM = MOVPRO.BDORDEM) 
             LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PRAJUSTESCP = TRUE) AND (EMPSCP.BDCODEMP = ITENS.BDCODEMP) AND (EMPSCP.BDREFEMP = ITENS.BDREFSOC) AND (EMPSCP.BDCODSCP = ITENS.BDCODSCP)
             LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = ITENS.BDCODNAT) 
             LEFT OUTER JOIN(SELECT I.BDCODEMP, I.BDCHAVE, SUM(I.BDVLRCONTAB) AS BDVLRCONTABTOTAL FROM VEF_EMP_TMOVSAIITENS I  LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT) WHERE NAT.BDLANCPARCELAMENTO = 'TRUE'  GROUP BY I.BDCODEMP, I.BDCHAVE) IVLR ON (IVLR.BDCODEMP = SAI.BDCODEMP AND IVLR.BDCHAVE = SAI.BDCHAVE) 
             WHERE ((MOVPRO.BDCODCSTPIS IS NOT NULL) OR (MOVPRO.BDCODCSTCOF IS NOT NULL)) 
               AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) = TRIM('FALSE'))) 
             UNION ALL 
             SELECT COALESCE(EMPSCP.BDCODEMPSCP, D100.BDCODEMP), MOV.BDCODTER, D100.BDCODCSTCOF, D100.BDCODCSTPIS, D100.BDCODNATREC, D100.BDALIQ_PIS BDALIQPIS, D100.BDALIQ_COF BDALIQCOFINS, ITENS.BDCODNAT, MOV.BDMODELO, 
                    MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM, 0 AS BDCODPLAPADRAO, 0 AS BDCREDITO, 0 AS BDREFERENCIA , 
                    CAST(COALESCE(ITENS.BDVLRCONTAB, 0) * (MOV.BDVALORPGTOPAR / IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1)) AS DM_NUMERIC_15_2) AS BDVLRITEM, 
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* CAST(((D100.BDVL_BC_PIS * COALESCE(ITENS.BDVLRCONTAB, 0)) / IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1)) AS DM_NUMERIC_15_2)) AS DM_NUMERIC_15_2) BDBCPIS, 
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* CAST(((D100.BDVL_BC_COF * COALESCE(ITENS.BDVLRCONTAB, 0)) / IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1)) AS DM_NUMERIC_15_2)) AS DM_NUMERIC_15_2) BDBCCOFINS, 
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* CAST(((D100.BDVLRPIS * COALESCE(ITENS.BDVLRCONTAB, 0))    / IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1)) AS DM_NUMERIC_15_2)) AS DM_NUMERIC_15_2) BDVLRPIS, 
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* CAST(((D100.BDVLRCOFINS * COALESCE(ITENS.BDVLRCONTAB, 0)) / IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1)) AS DM_NUMERIC_15_2)) AS DM_NUMERIC_15_2) BDVLRCOFINS, 
             IIF(COALESCE(EMPSCP.BDCODEMPSCP,0) > 0,D100.BDCODEMP,NULL) BDCODEMPSOCIA, ITENS.BDVLRICMS 
             FROM ( 
                   SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDCODTER,MOV.BDMODELO,MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM,
                          MOV.BDVALORNOTA, SUM(AUX.BDVALORPGTOPAR) BDVALORPGTOPAR, SUM(AUX.BDVALORPAR) BDVALORPAR
                   FROM ( 
                        SELECT AUX.BDCODEMP, AUX.BDCHAVE, AUX.BDREFLAN, SUM(COALESCE(AUX.BDVALORPGTOPAR, 0)) BDVALORPGTOPAR, CAST(SUM(COALESCE(CAST(PAR.BDVALORPAR AS DM_NUMERIC_15_2), 0)) + 
                               SUM(COALESCE(PAR.BDVALORRETPIS, 0)) + SUM(COALESCE(PAR.BDVALORRETCOFINS, 0)) + SUM(COALESCE(PAR.BDVALORRETCSLL, 0)) + 
                               SUM(COALESCE(PAR.BDVALORRETIRRF, 0)) + SUM(COALESCE(PAR.BDVALORRETISSQN, 0)) + SUM(COALESCE(PAR.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) - 0.00 BDVALORPAR 
                        FROM( 
                             SELECT M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, P.BDORDEMPAR, 
                                    CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + 
                                     SUM(COALESCE(P.BDVALORRETPIS, 0)) + 
                                     SUM(COALESCE(P.BDVALORRETCOFINS, 0)) + 
                                     SUM(COALESCE(P.BDVALORRETCSLL, 0)) + 
                                     SUM(COALESCE(P.BDVALORRETIRRF, 0)) + 
                                     SUM(COALESCE(P.BDVALORRETISSQN, 0)) + 
                                     SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR 
                             FROM (SELECT * FROM VEF_EMP_TMOVSAI WHERE BDCODEMP = :PRCODEMP) M
                             JOIN VEF_EMP_TMOVSAIPARPGTO P ON (P.BDCODEMP = M.BDCODEMP AND P.BDCHAVE = M.BDCHAVE AND
                                                               EXTRACT(YEAR FROM P.BDDATAPGTOPAR)||LPAD(EXTRACT(MONTH FROM P.BDDATAPGTOPAR),2,'0') = :PRREFERENCIA AND
                                                               P.BDCODTIPOBAIXA = 1)
                             LEFT OUTER JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = P.BDCODEMP AND PAR.BDCHAVE = P.BDCHAVE AND PAR.BDORDEMPAR = P.BDORDEMPAR) 
                             LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = P.BDCODNAT) 
                             WHERE P.BDCODTIPOBAIXA = 1
                               AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) = TRIM('FALSE'))) 
                               AND ((M.BDCODSITNF NOT IN (2,3,4,5) )) 
                               AND (M.BDMODELO IN (7,8,9,10,11,13,14,15,16,26,27,57,67,800,63)) 
                             GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, P.BDORDEMPAR 
                            ) AUX 
                          LEFT OUTER JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = AUX.BDCODEMP AND PAR.BDCHAVE = AUX.BDCHAVE AND PAR.BDORDEMPAR = AUX.BDORDEMPAR) 
                          GROUP BY AUX.BDCODEMP, AUX.BDCHAVE, AUX.BDREFLAN) AUX 
                          LEFT OUTER JOIN  VEF_EMP_TMOVSAI MOV ON (MOV.BDCODEMP = AUX.BDCODEMP AND MOV.BDCHAVE = AUX.BDCHAVE) 
                          WHERE AUX.BDVALORPGTOPAR > 0 
                          AND ((SELECT FIRST 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER P 
                          WHERE P.BDCODEMP = AUX.BDCODEMP AND P.BDREFEMP <= AUX.BDREFLAN ORDER BY BDCODEMP DESC, BDREFEMP DESC) = 1) 
                          GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDCODTER,MOV.BDMODELO,MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM, MOV.BDVALORNOTA
                        ) MOV 
             JOIN VEF_EMP_TMOVSAIITENS ITENS ON (MOV.BDCODEMP = ITENS.BDCODEMP AND MOV.BDCHAVE = ITENS.BDCHAVE) 
             JOIN VEF_EMP_TD100SAI D100 ON (MOV.BDCODEMP = D100.BDCODEMP AND MOV.BDCHAVE = D100.BDCHAVE) 
             LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PRAJUSTESCP = TRUE) AND (EMPSCP.BDCODEMP = ITENS.BDCODEMP) AND (EMPSCP.BDREFEMP = ITENS.BDREFSOC) AND (EMPSCP.BDCODSCP = ITENS.BDCODSCP)
             LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = ITENS.BDCODNAT) 
             WHERE ((D100.BDCODCSTPIS IS NOT NULL) OR (D100.BDCODCSTCOF IS NOT NULL)) 
               AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) = TRIM('FALSE'))) 
             UNION ALL 
             SELECT COALESCE(EMPSCP.BDCODEMPSCP, D400.BDCODEMP), MOV.BDCODTER, D400.BDCODCSTCOF, D400.BDCODCSTPIS, D400.BDCODNATREC, D400.BDALIQ_PIS AS BDALIQPIS, D400.BDALIQ_COF AS BDALIQCOFINS, ITENS.BDCODNAT, MOV.BDMODELO, 
                    MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM, 0 AS BDCODPLAPADRAO, 0 AS BDCREDITO, 0 AS BDREFERENCIA,
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(ITENS.BDVLRCONTAB, 0)) AS DM_NUMERIC_15_2) AS BDVLRITEM, 
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* ((D400.BDVL_BC_PIS * COALESCE(ITENS.BDVLRCONTAB, 0))/IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1))) AS DM_NUMERIC_15_2) BDBCPIS, 
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* ((D400.BDVL_BC_COF * COALESCE(ITENS.BDVLRCONTAB, 0))/IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1))) AS DM_NUMERIC_15_2) BDBCCOFINS, 
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* ((D400.BDVL_PIS    * COALESCE(ITENS.BDVLRCONTAB, 0))/IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1))) AS DM_NUMERIC_15_2) BDVLRPIS, 
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* ((D400.BDVL_COF    * COALESCE(ITENS.BDVLRCONTAB, 0))/IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1))) AS DM_NUMERIC_15_2) BDVLRCOFINS, 
                    IIF(COALESCE(EMPSCP.BDCODEMPSCP,0) > 0,D400.BDCODEMP,NULL) BDCODEMPSOCIA, ITENS.BDVLRICMS
                 FROM ( 
                       SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDCODTER,MOV.BDMODELO,MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM,
                              MOV.BDVALORNOTA, SUM(AUX.BDVALORPGTOPAR) BDVALORPGTOPAR, SUM(AUX.BDVALORPAR) BDVALORPAR
                       FROM (
                             SELECT AUX.BDCODEMP, AUX.BDCHAVE, AUX.BDREFLAN, SUM(COALESCE(AUX.BDVALORPGTOPAR, 0)) BDVALORPGTOPAR, CAST(SUM(COALESCE(CAST(PAR.BDVALORPAR AS DM_NUMERIC_15_2), 0)) + 
                                    SUM(COALESCE(PAR.BDVALORRETPIS, 0)) + SUM(COALESCE(PAR.BDVALORRETCOFINS, 0)) + SUM(COALESCE(PAR.BDVALORRETCSLL, 0)) + 
                                    SUM(COALESCE(PAR.BDVALORRETIRRF, 0)) + SUM(COALESCE(PAR.BDVALORRETISSQN, 0)) + SUM(COALESCE(PAR.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) - 0.00 BDVALORPAR 
                             FROM( 
                                  SELECT M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, P.BDORDEMPAR, 
                                         CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + 
                                         SUM(COALESCE(P.BDVALORRETPIS, 0)) +
                                         SUM(COALESCE(P.BDVALORRETCOFINS, 0)) +
                                         SUM(COALESCE(P.BDVALORRETCSLL, 0)) +
                                         SUM(COALESCE(P.BDVALORRETIRRF, 0)) +
                                         SUM(COALESCE(P.BDVALORRETISSQN, 0)) +
                                         SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR
                                  FROM (SELECT * FROM VEF_EMP_TMOVSAI WHERE BDCODEMP = :PRCODEMP) M
                                  JOIN VEF_EMP_TMOVSAIPARPGTO P ON (P.BDCODEMP = M.BDCODEMP AND P.BDCHAVE = M.BDCHAVE AND
                                                                    EXTRACT(YEAR FROM P.BDDATAPGTOPAR)||LPAD(EXTRACT(MONTH FROM P.BDDATAPGTOPAR),2,'0') = :PRREFERENCIA AND
                                                                    P.BDCODTIPOBAIXA = 1) 
                                  LEFT OUTER JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = P.BDCODEMP AND PAR.BDCHAVE = P.BDCHAVE AND PAR.BDORDEMPAR = P.BDORDEMPAR) 
                                  LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = P.BDCODNAT) 
                                  WHERE P.BDCODTIPOBAIXA = 1
                                    AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) = TRIM('FALSE'))) 
                                    AND ((M.BDCODSITNF NOT IN (2,3,4,5) )) 
                                    AND (M.BDMODELO IN (7,8,9,10,11,13,14,15,16,26,27,57,67,800,63)) 
                                  GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, P.BDORDEMPAR 
                                 ) AUX 
                             LEFT OUTER JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = AUX.BDCODEMP AND PAR.BDCHAVE = AUX.BDCHAVE AND PAR.BDORDEMPAR = AUX.BDORDEMPAR) 
                             GROUP BY AUX.BDCODEMP, AUX.BDCHAVE, AUX.BDREFLAN
                             ) AUX 
                   LEFT OUTER JOIN  VEF_EMP_TMOVSAI MOV ON (MOV.BDCODEMP = AUX.BDCODEMP AND MOV.BDCHAVE = AUX.BDCHAVE) 
                   WHERE AUX.BDVALORPGTOPAR > 0 
                   AND ((SELECT FIRST 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER P 
                   WHERE P.BDCODEMP = AUX.BDCODEMP AND P.BDREFEMP <= AUX.BDREFLAN ORDER BY BDCODEMP DESC, BDREFEMP DESC) = 1) 
                   GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDCODTER,MOV.BDMODELO,MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM, MOV.BDVALORNOTA
                 ) MOV 
             JOIN VEF_EMP_TMOVSAIITENS ITENS ON (MOV.BDCODEMP = ITENS.BDCODEMP AND MOV.BDCHAVE = ITENS.BDCHAVE) 
             JOIN VEF_EMP_TD400SAI D400 ON (MOV.BDCODEMP = D400.BDCODEMP AND MOV.BDCHAVE = D400.BDCHAVE) 
             LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PRAJUSTESCP = TRUE) AND (EMPSCP.BDCODEMP = ITENS.BDCODEMP) AND (EMPSCP.BDREFEMP = ITENS.BDREFSOC) AND (EMPSCP.BDCODSCP = ITENS.BDCODSCP)
             LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = ITENS.BDCODNAT) 
             WHERE ((D400.BDCODCSTPIS IS NOT NULL) OR (D400.BDCODCSTCOF IS NOT NULL)) 
               AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) = TRIM('FALSE'))) 
             UNION ALL 
             SELECT COALESCE(EMPSCP.BDCODEMPSCP, D500.BDCODEMP), MOV.BDCODTER, D500.BDCODCSTCOF, D500.BDCODCSTPIS, D500.BDCODNATREC, D500.BDALIQ_PIS BDALIQPIS, D500.BDALIQ_COF BDALIQCOFINS, ITENS.BDCODNAT, MOV.BDMODELO, 
                    MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM, 0 AS BDCODPLAPADRAO, 0 AS BDCREDITO, 0 AS BDREFERENCIA , 
                MOV.BDVALORPGTOPAR BDVLRITEM, 
                CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(D500.BDVL_BC_PIS, 0)) AS DM_NUMERIC_15_2) BDBCPIS, 
                CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(D500.BDVL_BC_COF, 0)) AS DM_NUMERIC_15_2) BDBCCOFINS, 
                CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(D500.BDVLRPIS, 0))    AS DM_NUMERIC_15_2) BDVLRPIS, 
                CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(D500.BDVLRCOFINS, 0)) AS DM_NUMERIC_15_2) BDVLRCOFINS, 
                IIF(COALESCE(EMPSCP.BDCODEMPSCP,0) > 0,D500.BDCODEMP,NULL) BDCODEMPSOCIA, ITENS.BDVLRICMS 
             FROM ( 
                   SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDCODTER,MOV.BDMODELO,MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM,
                          MOV.BDVALORNOTA, SUM(AUX.BDVALORPGTOPAR) BDVALORPGTOPAR, SUM(AUX.BDVALORPAR) BDVALORPAR
                   FROM (
                         SELECT AUX.BDCODEMP, AUX.BDCHAVE, AUX.BDREFLAN, SUM(COALESCE(AUX.BDVALORPGTOPAR, 0)) BDVALORPGTOPAR, CAST(SUM(COALESCE(CAST(PAR.BDVALORPAR AS DM_NUMERIC_15_2), 0)) + 
                                SUM(COALESCE(PAR.BDVALORRETPIS, 0)) + SUM(COALESCE(PAR.BDVALORRETCOFINS, 0)) + SUM(COALESCE(PAR.BDVALORRETCSLL, 0)) + 
                                SUM(COALESCE(PAR.BDVALORRETIRRF, 0)) + SUM(COALESCE(PAR.BDVALORRETISSQN, 0)) + SUM(COALESCE(PAR.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) - 0.00 BDVALORPAR 
                         FROM( 
                              SELECT M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, P.BDORDEMPAR, 
                                     CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + 
                                     SUM(COALESCE(P.BDVALORRETPIS, 0)) +
                                     SUM(COALESCE(P.BDVALORRETCOFINS, 0)) +
                                     SUM(COALESCE(P.BDVALORRETCSLL, 0)) +
                                     SUM(COALESCE(P.BDVALORRETIRRF, 0)) +
                                     SUM(COALESCE(P.BDVALORRETISSQN, 0)) +
                                     SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR
                              FROM (SELECT * FROM VEF_EMP_TMOVSAI WHERE BDCODEMP = :PRCODEMP) M
                              JOIN VEF_EMP_TMOVSAIPARPGTO P ON (P.BDCODEMP = M.BDCODEMP AND P.BDCHAVE = M.BDCHAVE AND
                                                                EXTRACT(YEAR FROM P.BDDATAPGTOPAR)||LPAD(EXTRACT(MONTH FROM P.BDDATAPGTOPAR),2,'0') = :PRREFERENCIA AND
                                                                P.BDCODTIPOBAIXA = 1) 
                              LEFT OUTER JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = P.BDCODEMP AND PAR.BDCHAVE = P.BDCHAVE AND PAR.BDORDEMPAR = P.BDORDEMPAR) 
                              LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = P.BDCODNAT) 
                              WHERE P.BDCODTIPOBAIXA = 1
                                AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) = TRIM('FALSE'))) 
                                AND ((M.BDCODSITNF NOT IN (2,3,4,5) )) 
                                AND (M.BDMODELO NOT IN (7,8,9,10,11,13,14,15,16,26,27,57,67,800,63)) 
                              GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, P.BDORDEMPAR 
                             ) AUX 
                          LEFT OUTER JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = AUX.BDCODEMP AND PAR.BDCHAVE = AUX.BDCHAVE AND PAR.BDORDEMPAR = AUX.BDORDEMPAR) 
                          GROUP BY AUX.BDCODEMP, AUX.BDCHAVE, AUX.BDREFLAN
                          ) AUX 
                     LEFT OUTER JOIN  VEF_EMP_TMOVSAI MOV ON (MOV.BDCODEMP = AUX.BDCODEMP AND MOV.BDCHAVE = AUX.BDCHAVE) 
                     WHERE AUX.BDVALORPGTOPAR > 0 
                     AND ((SELECT FIRST 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER P 
                     WHERE P.BDCODEMP = AUX.BDCODEMP AND P.BDREFEMP <= AUX.BDREFLAN ORDER BY BDCODEMP DESC, BDREFEMP DESC) = 1) 
                     GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDCODTER,MOV.BDMODELO,MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM, MOV.BDVALORNOTA
                   ) MOV 
             JOIN VEF_EMP_TMOVSAIITENS ITENS ON (MOV.BDCODEMP = ITENS.BDCODEMP AND MOV.BDCHAVE = ITENS.BDCHAVE) 
             JOIN (SELECT X.* FROM VEF_EMP_TD500SAI X 
                  WHERE NOT EXISTS(SELECT Y.BDCODEMP, Y.BDCHAVE FROM VEF_EMP_TMOVPROSAI Y WHERE X.BDCODEMP = Y.BDCODEMP AND X.BDCHAVE = Y.BDCHAVE) 
                ) D500 ON (MOV.BDCODEMP = D500.BDCODEMP AND MOV.BDCHAVE = D500.BDCHAVE) 
             LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PRAJUSTESCP = TRUE) AND (EMPSCP.BDCODEMP = ITENS.BDCODEMP) AND (EMPSCP.BDREFEMP = ITENS.BDREFSOC) AND (EMPSCP.BDCODSCP = ITENS.BDCODSCP)
             LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = ITENS.BDCODNAT) 
             WHERE ((D500.BDCODCSTPIS IS NOT NULL) OR (D500.BDCODCSTCOF IS NOT NULL)) 
               AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) = TRIM('FALSE'))) 
             UNION ALL 
             SELECT COALESCE(EMPSCP.BDCODEMPSCP, C500.BDCODEMP), MOV.BDCODTER, C500.BDCODCSTCOF, C500.BDCODCSTPIS, C500.BDCODNATREC, C500.BDALIQ_PIS BDALIQPIS, C500.BDALIQ_COF BDALIQCOFINS, ITENS.BDCODNAT, MOV.BDMODELO, 
                    MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM, 0 AS BDCODPLAPADRAO, 0 AS BDCREDITO, 0 AS BDREFERENCIA, 
                    MOV.BDVALORPGTOPAR BDVLRITEM, 
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(C500.BDVL_BC_PIS, 0)) AS DM_NUMERIC_15_2) BDBCPIS, 
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(C500.BDVL_BC_COF, 0)) AS DM_NUMERIC_15_2) BDBCCOFINS, 
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(C500.BDVLRPIS, 0))    AS DM_NUMERIC_15_2) BDVLRPIS, 
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(C500.BDVLRCOFINS, 0)) AS DM_NUMERIC_15_2) BDVLRCOFINS, 
                    IIF(COALESCE(EMPSCP.BDCODEMPSCP,0) > 0,C500.BDCODEMP,NULL) BDCODEMPSOCIA, ITENS.BDVLRICMS 
              FROM ( 
                    SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDCODTER,MOV.BDMODELO,MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM,
                           MOV.BDVALORNOTA, SUM(AUX.BDVALORPGTOPAR) BDVALORPGTOPAR, SUM(AUX.BDVALORPAR) BDVALORPAR
                    FROM (
                          SELECT AUX.BDCODEMP, AUX.BDCHAVE, AUX.BDREFLAN, SUM(COALESCE(AUX.BDVALORPGTOPAR, 0)) BDVALORPGTOPAR, CAST(SUM(COALESCE(CAST(PAR.BDVALORPAR AS DM_NUMERIC_15_2), 0)) + 
                                 SUM(COALESCE(PAR.BDVALORRETPIS, 0)) + SUM(COALESCE(PAR.BDVALORRETCOFINS, 0)) + SUM(COALESCE(PAR.BDVALORRETCSLL, 0)) + 
                                 SUM(COALESCE(PAR.BDVALORRETIRRF, 0)) + SUM(COALESCE(PAR.BDVALORRETISSQN, 0)) + SUM(COALESCE(PAR.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) - 0.00 BDVALORPAR 
                          FROM( 
                               SELECT M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, P.BDORDEMPAR, 
                                      CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + 
                                      SUM(COALESCE(P.BDVALORRETPIS, 0)) +
                                      SUM(COALESCE(P.BDVALORRETCOFINS, 0)) +
                                      SUM(COALESCE(P.BDVALORRETCSLL, 0)) +
                                      SUM(COALESCE(P.BDVALORRETIRRF, 0)) +
                                      SUM(COALESCE(P.BDVALORRETISSQN, 0)) +
                                      SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR
                               FROM (SELECT * FROM VEF_EMP_TMOVSAI WHERE BDCODEMP = :PRCODEMP) M
                               JOIN VEF_EMP_TMOVSAIPARPGTO P ON (P.BDCODEMP = M.BDCODEMP AND P.BDCHAVE = M.BDCHAVE AND
                                                                 EXTRACT(YEAR FROM P.BDDATAPGTOPAR)||LPAD(EXTRACT(MONTH FROM P.BDDATAPGTOPAR),2,'0') = :PRREFERENCIA AND
                                                                 P.BDCODTIPOBAIXA = 1) 
                               LEFT OUTER JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = P.BDCODEMP AND PAR.BDCHAVE = P.BDCHAVE AND PAR.BDORDEMPAR = P.BDORDEMPAR) 
                               LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = P.BDCODNAT) 
                               WHERE P.BDCODTIPOBAIXA = 1
                                 AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) = TRIM('FALSE'))) 
                                 AND ((M.BDCODSITNF NOT IN (2,3,4,5) )) 
                                 AND (M.BDMODELO NOT IN (7,8,9,10,11,13,14,15,16,26,27,57,67,800,63)) 
                               GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, P.BDORDEMPAR 
                              ) AUX 
                            LEFT OUTER JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = AUX.BDCODEMP AND PAR.BDCHAVE = AUX.BDCHAVE AND PAR.BDORDEMPAR = AUX.BDORDEMPAR) 
                            GROUP BY AUX.BDCODEMP, AUX.BDCHAVE, AUX.BDREFLAN
                            ) AUX 
                       LEFT OUTER JOIN  VEF_EMP_TMOVSAI MOV ON (MOV.BDCODEMP = AUX.BDCODEMP AND MOV.BDCHAVE = AUX.BDCHAVE) 
                       WHERE AUX.BDVALORPGTOPAR > 0 
                       AND ((SELECT FIRST 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER P 
                       WHERE P.BDCODEMP = AUX.BDCODEMP AND P.BDREFEMP <= AUX.BDREFLAN ORDER BY BDCODEMP DESC, BDREFEMP DESC) = 1) 
                       GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDCODTER 
                                 ,MOV.BDMODELO 
                               ,MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM, MOV.BDVALORNOTA 
                      ) MOV 
             JOIN VEF_EMP_TMOVSAIITENS ITENS ON (MOV.BDCODEMP = ITENS.BDCODEMP AND MOV.BDCHAVE = ITENS.BDCHAVE) 
             JOIN (SELECT X.* FROM VEF_EMP_TC500SAI X 
                   WHERE NOT EXISTS(SELECT Y.BDCODEMP, Y.BDCHAVE FROM VEF_EMP_TMOVPROSAI Y WHERE X.BDCODEMP = Y.BDCODEMP AND X.BDCHAVE = Y.BDCHAVE) 
                  ) C500 ON (MOV.BDCODEMP = C500.BDCODEMP AND MOV.BDCHAVE = C500.BDCHAVE) 
             LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PRAJUSTESCP = TRUE) AND (EMPSCP.BDCODEMP = ITENS.BDCODEMP) AND (EMPSCP.BDREFEMP = ITENS.BDREFSOC) AND (EMPSCP.BDCODSCP = ITENS.BDCODSCP)
             LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = ITENS.BDCODNAT) 
             WHERE ((C500.BDCODCSTPIS IS NOT NULL) OR (C500.BDCODCSTCOF IS NOT NULL)) 
               AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) = TRIM('FALSE'))) 
             UNION ALL 
             SELECT COALESCE(EMPSCP.BDCODEMPSCP, F500.BDCODEMP), MOV.BDCODTER, F500.BDCODCSTCOF, F500.BDCODCSTPIS, F500.BDCODNATREC, F500.BDALIQPIS, F500.BDALIQCOF BDALIQCOFINS, ITENS.BDCODNAT, MOV.BDMODELO, 
                    MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM, 0 AS BDCODPLAPADRAO, 0 AS BDCREDITO, 0 AS BDREFERENCIA , 
                    MOV.BDVALORPGTOPAR BDVLRITEM, 
                    CAST(((CAST( MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST( IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4))) * COALESCE(F500.BDBASEPIS, 0)) AS DM_NUMERIC_15_2) BDBCPIS, 
                    CAST(((CAST( MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST( IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4))) * COALESCE(F500.BDBASECOF, 0)) AS DM_NUMERIC_15_2) BDBCCOFINS, 
                    CAST(((CAST( MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST( IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4))) * COALESCE(F500.BDVLRPIS, 0))  AS DM_NUMERIC_15_2) BDVLRPIS, 
                    CAST(((CAST( MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST( IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4))) * COALESCE(F500.BDVLRCOF, 0))  AS DM_NUMERIC_15_2) BDVLRCOFINS, 
                    IIF(COALESCE(EMPSCP.BDCODEMPSCP,0) > 0,F500.BDCODEMP,NULL) BDCODEMPSOCIA, ITENS.BDVLRICMS 
             FROM ( 
                   SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDCODTER 
                  ,MOV.BDMODELO 
                  ,MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM, MOV.BDVALORNOTA 
                          , SUM(AUX.BDVALORPGTOPAR) BDVALORPGTOPAR 
                          , SUM(AUX.BDVALORPAR) BDVALORPAR 
                   FROM ( 
                        SELECT AUX.BDCODEMP, AUX.BDCHAVE, AUX.BDREFLAN, SUM(COALESCE(AUX.BDVALORPGTOPAR, 0)) BDVALORPGTOPAR, CAST(SUM(COALESCE(CAST(PAR.BDVALORPAR AS DM_NUMERIC_15_2), 0)) + 
                               SUM(COALESCE(PAR.BDVALORRETPIS, 0)) + SUM(COALESCE(PAR.BDVALORRETCOFINS, 0)) + SUM(COALESCE(PAR.BDVALORRETCSLL, 0)) + 
                               SUM(COALESCE(PAR.BDVALORRETIRRF, 0)) + SUM(COALESCE(PAR.BDVALORRETISSQN, 0)) + SUM(COALESCE(PAR.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) - 0.00 BDVALORPAR 
                        FROM( 
                             SELECT M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, P.BDORDEMPAR, 
                                    CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + 
                                    SUM(COALESCE(P.BDVALORRETPIS, 0)) +
                                    SUM(COALESCE(P.BDVALORRETCOFINS, 0)) +
                                    SUM(COALESCE(P.BDVALORRETCSLL, 0)) +
                                    SUM(COALESCE(P.BDVALORRETIRRF, 0)) +
                                    SUM(COALESCE(P.BDVALORRETISSQN, 0)) +
                                    SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR
                             FROM (SELECT * FROM VEF_EMP_TMOVSAI WHERE BDCODEMP = :PRCODEMP) M
                             JOIN VEF_EMP_TMOVSAIPARPGTO P ON (P.BDCODEMP = M.BDCODEMP AND P.BDCHAVE = M.BDCHAVE AND
                                                               EXTRACT(YEAR FROM P.BDDATAPGTOPAR)||LPAD(EXTRACT(MONTH FROM P.BDDATAPGTOPAR),2,'0') = :PRREFERENCIA AND
                                                               P.BDCODTIPOBAIXA = 1) 
                             LEFT OUTER JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = P.BDCODEMP AND PAR.BDCHAVE = P.BDCHAVE AND PAR.BDORDEMPAR = P.BDORDEMPAR) 
                             LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = P.BDCODNAT) 
                             WHERE P.BDCODTIPOBAIXA = 1
                               AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) = TRIM('FALSE'))) 
                               AND ((M.BDCODSITNF NOT IN (2,3,4,5) )) 
                               AND (M.BDMODELO NOT IN (7,8,9,10,11,13,14,15,16,26,27,57,67,800,63)) 
                             GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, P.BDORDEMPAR 
                            ) AUX 
                      LEFT OUTER JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = AUX.BDCODEMP AND PAR.BDCHAVE = AUX.BDCHAVE AND PAR.BDORDEMPAR = AUX.BDORDEMPAR) 
                      GROUP BY AUX.BDCODEMP, AUX.BDCHAVE, AUX.BDREFLAN
                      ) AUX 
                      LEFT OUTER JOIN  VEF_EMP_TMOVSAI MOV ON (MOV.BDCODEMP = AUX.BDCODEMP AND MOV.BDCHAVE = AUX.BDCHAVE) 
                      WHERE AUX.BDVALORPGTOPAR > 0 
                      AND ((SELECT FIRST 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER P 
                      WHERE P.BDCODEMP = AUX.BDCODEMP AND P.BDREFEMP <= AUX.BDREFLAN ORDER BY BDCODEMP DESC, BDREFEMP DESC) = 1) 
                      GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDCODTER,MOV.BDMODELO,MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM, MOV.BDVALORNOTA
                    ) MOV 
             JOIN VEF_EMP_TMOVSAIITENS ITENS ON (MOV.BDCODEMP = ITENS.BDCODEMP AND MOV.BDCHAVE = ITENS.BDCHAVE) 
             JOIN (SELECT X.* FROM VEF_EMP_TF500SAI X 
                   WHERE NOT EXISTS(SELECT Y.BDCODEMP, Y.BDCHAVE FROM VEF_EMP_TMOVPROSAI Y WHERE X.BDCODEMP = Y.BDCODEMP AND X.BDCHAVE = Y.BDCHAVE) 
                  ) F500 ON (MOV.BDCODEMP = F500.BDCODEMP AND MOV.BDCHAVE = F500.BDCHAVE) 
             LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PRAJUSTESCP = TRUE) AND (EMPSCP.BDCODEMP = ITENS.BDCODEMP) AND (EMPSCP.BDREFEMP = ITENS.BDREFSOC) AND (EMPSCP.BDCODSCP = ITENS.BDCODSCP)
             LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = ITENS.BDCODNAT) 
             WHERE ((F500.BDCODCSTPIS IS NOT NULL) OR (F500.BDCODCSTCOF IS NOT NULL)) 
               AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) = TRIM('FALSE'))) 
             UNION ALL 
             SELECT COALESCE(EMPSCP.BDCODEMPSCP, C170.BDCODEMP), MOV.BDCODTER, C170.BDCODCSTCOF, C170.BDCODCSTPIS, C170.BDCODNATREC, C170.BDALIQ_PIS BDALIQPIS, C170.BDALIQ_COFINS BDALIQCOFINS, ITENS.BDCODNAT, 98 BDMODELO, 
                    MOV.BDSERIE, MOV.BDSUBSERIE, 
                    CASE WHEN MOV.BDCODSITNF IS NULL THEN NULL ELSE SIT.BDCODSITNF END BDCODSITNF, 
                    MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM, 0 AS BDCODPLAPADRAO, 0 AS BDCREDITO, 0 AS BDREFERENCIA , 
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(C170.BDVL_ITEM, 0))      AS DM_NUMERIC_15_2) BDVLRITEM, 
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(C170.BDVL_BC_PIS, 0))    AS DM_NUMERIC_15_2) BDBCPIS, 
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(C170.BDVL_BC_COFINS, 0)) AS DM_NUMERIC_15_2) BDBCCOFINS, 
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(C170.BDVL_PIS, 0))       AS DM_NUMERIC_15_2) BDVLRPIS, 
                    CAST(((CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(C170.BDVL_COFINS, 0))    AS DM_NUMERIC_15_2) BDVLRCOFINS, 
                    IIF(COALESCE(EMPSCP.BDCODEMPSCP,0) > 0,C170.BDCODEMP,NULL) BDCODEMPSOCIA, 0 BDVLRICMS
             FROM ( 
                   SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDCODTER,MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM,
                          MOV.BDVALORNOTA, SUM(AUX.BDVALORPGTOPAR) BDVALORPGTOPAR, SUM(AUX.BDVALORPAR) BDVALORPAR
                   FROM ( 
                        SELECT AUX.BDCODEMP, AUX.BDCHAVE, AUX.BDREFLAN, SUM(COALESCE(AUX.BDVALORPGTOPAR, 0)) BDVALORPGTOPAR, CAST(SUM(COALESCE(CAST(PAR.BDVALORPAR AS DM_NUMERIC_15_2), 0)) + 
                               SUM(COALESCE(PAR.BDVALORRETPIS, 0)) + SUM(COALESCE(PAR.BDVALORRETCOFINS, 0)) + SUM(COALESCE(PAR.BDVALORRETCSLL, 0)) + 
                               SUM(COALESCE(PAR.BDVALORRETIRRF, 0)) + SUM(COALESCE(PAR.BDVALORRETISSQN, 0)) + SUM(COALESCE(PAR.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) - 0.00 BDVALORPAR 
                        FROM( 
                             SELECT M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, P.BDORDEMPAR, 
                                    CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + 
                                     SUM(COALESCE(P.BDVALORRETPIS, 0)) + 
                                     SUM(COALESCE(P.BDVALORRETCOFINS, 0)) + 
                                     SUM(COALESCE(P.BDVALORRETCSLL, 0)) + 
                                     SUM(COALESCE(P.BDVALORRETIRRF, 0)) + 
                                     SUM(COALESCE(P.BDVALORRETISSQN, 0)) + 
                                     SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR 
                             FROM (SELECT * FROM VEF_EMP_TMOVSER WHERE BDCODEMP = :PRCODEMP) M
                             JOIN VEF_EMP_TMOVSERPARPGTO P ON (P.BDCODEMP = M.BDCODEMP AND P.BDCHAVE = M.BDCHAVE AND
                                                               EXTRACT(YEAR FROM P.BDDATAPGTOPAR)||LPAD(EXTRACT(MONTH FROM P.BDDATAPGTOPAR),2,'0') = :PRREFERENCIA AND
                                                               P.BDCODTIPOBAIXA = 1) 
                             LEFT OUTER JOIN VEF_EMP_TMOVSERPAR PAR ON (PAR.BDCODEMP = P.BDCODEMP AND PAR.BDCHAVE = P.BDCHAVE AND PAR.BDORDEMPAR = P.BDORDEMPAR) 
                             LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = P.BDCODNAT) 
                             WHERE P.BDCODTIPOBAIXA = 1
                               AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) = TRIM('FALSE'))) 
                               AND ((M.BDCODSITNF NOT IN (2,3,4,5) )) 
                               AND (M.BDTIPLAN = 0) 
                             GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, P.BDORDEMPAR 
                         ) AUX
                  LEFT OUTER JOIN VEF_EMP_TMOVSERPAR PAR ON (PAR.BDCODEMP = AUX.BDCODEMP AND PAR.BDCHAVE = AUX.BDCHAVE AND PAR.BDORDEMPAR = AUX.BDORDEMPAR) 
                  GROUP BY AUX.BDCODEMP, AUX.BDCHAVE, AUX.BDREFLAN) AUX 
                  LEFT OUTER JOIN  VEF_EMP_TMOVSER MOV ON (MOV.BDCODEMP = AUX.BDCODEMP AND MOV.BDCHAVE = AUX.BDCHAVE) 
                  WHERE AUX.BDVALORPGTOPAR > 0 
                  AND ((SELECT FIRST 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER P 
                  WHERE P.BDCODEMP = AUX.BDCODEMP AND P.BDREFEMP <= AUX.BDREFLAN ORDER BY BDCODEMP DESC, BDREFEMP DESC) = 1) 
                  GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDCODTER,MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDCODSITNF, MOV.BDNUMDOCINI, MOV.BDNUMDOCFIM, MOV.BDVALORNOTA
                ) MOV 
             JOIN VEF_EMP_TMOVSERITENS ITENS ON (MOV.BDCODEMP = ITENS.BDCODEMP AND MOV.BDCHAVE = ITENS.BDCHAVE) 
             JOIN VEF_EMP_TA170 C170 ON (MOV.BDCODEMP = C170.BDCODEMP AND MOV.BDCHAVE = C170.BDCHAVE AND ITENS.BDORDEM = C170.BDORDEM) 
             LEFT OUTER JOIN VEF_BASE_TTABSITNF SIT ON (MOV.BDCODSITNF = SIT.BDCODSITNF) 
             LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PRAJUSTESCP = TRUE) AND (EMPSCP.BDCODEMP = ITENS.BDCODEMP) AND (EMPSCP.BDREFEMP = ITENS.BDREFSOC) AND (EMPSCP.BDCODSCP = ITENS.BDCODSCP)
             LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = ITENS.BDCODNAT) 
             WHERE (C170.BDCODCSTCOF IS NOT NULL) 
               AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) = TRIM('FALSE'))) 
             UNION ALL 
             SELECT COALESCE(EMPSCP.BDCODEMPSCP,MOV.BDCODEMP) BDCODEMP, MOV.BDCODTER, MOV.BDCODCSTCOF, MOV.BDCODCSTPIS, MOV.BDCODNATREC, MOV.BDALIQ_PIS BDALIQPIS, MOV.BDALIQ_COFINS BDALIQCOFINS, 0 BDCODNAT, 99 BDMODELO, '' BDSERIE, 
                    '' BDSUBSERIE, 0 BDCODSITNF, 1 BDNUMDOCINI, 1 BDNUMDOCFIM, 0 AS BDCODPLAPADRAO, 0 AS BDCREDITO, 0 AS BDREFERENCIA, 
                    AUX.BDVALORPGTOPAR BDVLRITEM, 
                    CAST(((CAST(AUX.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(AUX.BDVALORNOTA > 0, AUX.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(MOV.BDVL_BC_PIS, 0))    AS DM_NUMERIC_15_2) BDBCPIS, 
                    CAST(((CAST(AUX.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(AUX.BDVALORNOTA > 0, AUX.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(MOV.BDVL_BC_COFINS, 0)) AS DM_NUMERIC_15_2) BDBCCOFINS, 
                    CAST(((CAST(AUX.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(AUX.BDVALORNOTA > 0, AUX.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(MOV.BDVLR_PIS, 0))      AS DM_NUMERIC_15_2) BDVLRPIS, 
                    CAST(((CAST(AUX.BDVALORPGTOPAR AS NUMERIC(15,4)) / CAST(IIF(AUX.BDVALORNOTA > 0, AUX.BDVALORNOTA, 1) AS NUMERIC(15,4)))* COALESCE(MOV.BDVLR_COFINS, 0))   AS DM_NUMERIC_15_2) BDVLRCOFINS, 
                    IIF(COALESCE(EMPSCP.BDCODEMPSCP,0) > 0,MOV.BDCODEMP,NULL) BDCODEMPSOCIA, 0 BDVLRICMS 
              FROM ( 
                    SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDCODTER, MOV.BDVL_OPER BDVALORNOTA,
                           SUM(AUX.BDVALORPGTOPAR) BDVALORPGTOPAR, SUM(AUX.BDVALORPAR) BDVALORPAR
                    FROM ( 
                         SELECT AUX.BDCODEMP, AUX.BDCHAVE, AUX.BDREFLAN, SUM(COALESCE(AUX.BDVALORPGTOPAR, 0)) BDVALORPGTOPAR, CAST(SUM(COALESCE(CAST(PAR.BDVALORPAR AS DM_NUMERIC_15_2), 0)) + 
                                SUM(COALESCE(PAR.BDVALORRETPIS, 0)) + SUM(COALESCE(PAR.BDVALORRETCOFINS, 0)) + SUM(COALESCE(PAR.BDVALORRETCSLL, 0)) + 
                                SUM(COALESCE(PAR.BDVALORRETIRRF, 0)) + SUM(COALESCE(PAR.BDVALORRETISSQN, 0)) + SUM(COALESCE(PAR.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) - 0.00 BDVALORPAR 
                         FROM( 
                              SELECT M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, P.BDORDEMPAR, 
                                     CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + 
                                     SUM(COALESCE(P.BDVALORRETPIS, 0)) +
                                     SUM(COALESCE(P.BDVALORRETCOFINS, 0)) +
                                     SUM(COALESCE(P.BDVALORRETCSLL, 0)) +
                                     SUM(COALESCE(P.BDVALORRETIRRF, 0)) +
                                     SUM(COALESCE(P.BDVALORRETISSQN, 0)) +
                                     SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR
                              FROM (SELECT * FROM VEF_EMP_TMOVDEMAISDOC_F100 WHERE BDCODEMP = :PRCODEMP) M
                              JOIN VEF_EMP_TMOVF100PARPGTO P ON (P.BDCODEMP = M.BDCODEMP AND P.BDCHAVE = M.BDCHAVE AND
                                                                 EXTRACT(YEAR FROM P.BDDATAPGTOPAR)||LPAD(EXTRACT(MONTH FROM P.BDDATAPGTOPAR),2,'0') = :PRREFERENCIA AND
                                                                 P.BDCODTIPOBAIXA = 1) 
                              LEFT OUTER JOIN VEF_EMP_TMOVF100PAR PAR ON (PAR.BDCODEMP = P.BDCODEMP AND PAR.BDCHAVE = P.BDCHAVE AND PAR.BDORDEMPAR = P.BDORDEMPAR) 
                              LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = P.BDCODNAT) 
                              WHERE P.BDCODTIPOBAIXA = 1
                                AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) = TRIM('FALSE'))) 
                              GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, P.BDORDEMPAR 
                               ) AUX 
               LEFT OUTER JOIN VEF_EMP_TMOVF100PAR PAR ON (PAR.BDCODEMP = AUX.BDCODEMP AND PAR.BDCHAVE = AUX.BDCHAVE AND PAR.BDORDEMPAR = AUX.BDORDEMPAR) 
               GROUP BY AUX.BDCODEMP, AUX.BDCHAVE, AUX.BDREFLAN
               ) AUX 
               LEFT OUTER JOIN  VEF_EMP_TMOVDEMAISDOC_F100 MOV ON (MOV.BDCODEMP = AUX.BDCODEMP AND MOV.BDCHAVE = AUX.BDCHAVE) 
               WHERE AUX.BDVALORPGTOPAR > 0 
               AND ((SELECT FIRST 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER P 
               WHERE P.BDCODEMP = AUX.BDCODEMP AND P.BDREFEMP <= AUX.BDREFLAN ORDER BY BDCODEMP DESC, BDREFEMP DESC) = 1) 
               GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOV.BDCODTER 
                       , MOV.BDVL_OPER 
             ) AUX 
             LEFT OUTER JOIN VEF_EMP_TMOVDEMAISDOC_F100 MOV ON (MOV.BDCODEMP = AUX.BDCODEMP AND MOV.BDCHAVE = AUX.BDCHAVE) 
             LEFT OUTER JOIN VEF_BASE_TCADTIPODEMDOC CAD ON (MOV.BDCODTIPODOC = CAD.BDCODTIPODOC) 
             LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PRAJUSTESCP = TRUE) AND (EMPSCP.BDCODEMP = MOV.BDCODEMP) AND (EMPSCP.BDREFEMP = MOV.BDREFSOC) AND (EMPSCP.BDCODSCP = MOV.BDCODSCP)
             WHERE ((MOV.BDCODCSTPIS IS NOT NULL) OR (MOV.BDCODCSTCOF IS NOT NULL)) 
               AND ((CAD.BDNAOEXPSPED = 'FALSE') OR (CAD.BDNAOEXPSPED IS NULL)) 

             ) AUX
            GROUP BY AUX.BDCODEMP, AUX.BDCODCSTCOF, AUX.BDCODCSTPIS/*, AUX.BDCODNATREC, AUX.BDALIQPIS, AUX.BDALIQCOFINS*/
            INTO :wCODEMP, :wCODCSTCOF, :wCODCSTPIS, /*:wCODNATREC, :wALIQPIS, :wALIQCOFINS,*/
                 :wVLRITEM/*, :wBCPIS, :wBCCOFINS, :wVLRPIS, :wVLRCOFINS*/
        DO BEGIN
             -- M400
             SELECT SUM(m.BDVL_TOT_REC), MAX(m.BDCHAVE)
             FROM VEF_EMP_TBLOCOM400_M800 m
             WHERE m.BDCODQUADRO = 26
               AND m.BDCODEMP = :wCODEMP
               AND m.BDREFERENCIA = :PRREFERENCIA
               AND m.BDCODCSTPIS = :wCODCSTPIS
               AND m.BDRETIFICADORA = :PRRETIFICADORA
             INTO :wVL_TOT_REC, :wCHAVE;

             IF ((:wVL_TOT_REC IS NOT NULL) AND (:wCHAVE IS NOT NULL)) THEN
               BEGIN
                 :wVLDIF = :wVL_TOT_REC - :wVLRITEM;

                 IF ((:wVLDIF <> 0) AND ((:wVLDIF > 0) OR (:wVLDIF > -0.2))) THEN -- Apenas se for ate R$0,20, numero magico decidido pela qualidade...
                   BEGIN
                     UPDATE VEF_EMP_TBLOCOM400_M800 m
                     SET m.BDVL_TOT_REC = IIF((m.BDVL_TOT_REC - :wVLDIF) > 0, (m.BDVL_TOT_REC - :wVLDIF), m.BDVL_TOT_REC)
                     WHERE m.BDCODQUADRO = 26
                       AND m.BDCODEMP = :wCODEMP
                       AND m.BDREFERENCIA = :PRREFERENCIA
                       AND m.BDCODCSTPIS = :wCODCSTPIS
                       AND m.BDRETIFICADORA = :PRRETIFICADORA
                       AND m.BDCHAVE = :wCHAVE;

                     UPDATE VEF_EMP_TBLOCOM410_M810 m
                     SET m.BDVL_REC = IIF((m.BDVL_REC - :wVLDIF) > 0, (m.BDVL_REC - :wVLDIF), m.BDVL_REC)
                     WHERE m.BDCODQUADRO = 26
                       AND m.BDCODEMP = :wCODEMP
                       AND m.BDREFERENCIA = :PRREFERENCIA
                       --AND m.BDCODCSTPIS = :wCODCSTPIS
                       AND m.BDRETIFICADORA = :PRRETIFICADORA
                       AND m.BDCHAVE = :wCHAVE
                       AND m.BDORDEM = (SELECT MAX(BDORDEM)
                                        FROM VEF_EMP_TBLOCOM410_M810 x
                                        WHERE x.BDCODPERIODO = m.BDCODPERIODO
                                          AND x.BDCODEMP = m.BDCODEMP
                                          AND x.BDCODMATRIZ = m.BDCODMATRIZ
                                          AND x.BDCODQUADRO = m.BDCODQUADRO
                                          AND x.BDREFERENCIA = m.BDREFERENCIA
                                          AND x.BDCHAVE = m.BDCHAVE
                                          AND x.BDRETIFICADORA = m.BDRETIFICADORA);
                   END
               END

             -- M800
             SELECT SUM(m.BDVL_TOT_REC), MAX(m.BDCHAVE)
             FROM VEF_EMP_TBLOCOM400_M800 m
             WHERE m.BDCODQUADRO = 43
               AND m.BDCODEMP = :wCODEMP
               AND m.BDREFERENCIA = :PRREFERENCIA
               AND m.BDCODCSTCOF = :wCODCSTCOF
               AND m.BDRETIFICADORA = :PRRETIFICADORA
             INTO :wVL_TOT_REC, :wCHAVE;

             IF ((:wVL_TOT_REC IS NOT NULL) AND (:wCHAVE IS NOT NULL)) THEN
               BEGIN
                 :wVLDIF = :wVL_TOT_REC - :wVLRITEM;
    
                 IF ((:wVLDIF <> 0) AND ((:wVLDIF > 0) OR (:wVLDIF > -0.2))) THEN -- Apenas se for ate R$0,20, numero magico decidido pela qualidade...
                   BEGIN
                     UPDATE VEF_EMP_TBLOCOM400_M800 m
                     SET m.BDVL_TOT_REC = IIF((m.BDVL_TOT_REC - :wVLDIF > 0), (m.BDVL_TOT_REC - :wVLDIF), m.BDVL_TOT_REC)
                     WHERE m.BDCODQUADRO = 43
                       AND m.BDCODEMP = :wCODEMP
                       AND m.BDREFERENCIA = :PRREFERENCIA
                       AND m.BDCODCSTCOF = :wCODCSTCOF
                       AND m.BDRETIFICADORA = :PRRETIFICADORA
                       AND m.BDCHAVE = :wCHAVE;

                     UPDATE VEF_EMP_TBLOCOM410_M810 m
                     SET m.BDVL_REC = IIF((m.BDVL_REC - :wVLDIF) > 0, (m.BDVL_REC - :wVLDIF), m.BDVL_REC)
                     WHERE m.BDCODQUADRO = 43
                       AND m.BDCODEMP = :wCODEMP
                       AND m.BDREFERENCIA = :PRREFERENCIA
                       --AND m.BDCODCSTCOF = :wCODCSTCOF
                       AND m.BDRETIFICADORA = :PRRETIFICADORA
                       AND m.BDCHAVE = :wCHAVE
                       AND m.BDORDEM = (SELECT MAX(BDORDEM)
                                        FROM VEF_EMP_TBLOCOM410_M810 x
                                        WHERE x.BDCODPERIODO = m.BDCODPERIODO
                                          AND x.BDCODEMP = m.BDCODEMP
                                          AND x.BDCODMATRIZ = m.BDCODMATRIZ
                                          AND x.BDCODQUADRO = m.BDCODQUADRO
                                          AND x.BDREFERENCIA = m.BDREFERENCIA
                                          AND x.BDCHAVE = m.BDCHAVE
                                          AND x.BDRETIFICADORA = m.BDRETIFICADORA);
                   END
               END

           END
        END
    END
END
^

create or alter procedure SP_APURACAO_BLOCOM_DADOSFINAIS (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRRETIFICADORA integer,
    PRAJUSTESCP DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
declare variable WCODPERIODO integer;
declare variable WCREDITOSPERANT DM_BOOLEAN;
declare variable WORDENACRED DM_BOOLEAN;
declare variable WTOTALCREDPIS DM_NUMERIC_15_2;
declare variable WTOTALCREDCOFINS DM_NUMERIC_15_2;
declare variable WNAOUTILIZARCRE DM_BOOLEAN;
declare variable WABATERESSARCIM DM_BOOLEAN;
declare variable WCODEMP integer;
declare variable WCODMATRIZ integer;
declare variable WCODQUADRO integer;
declare variable WREFERENCIA integer;
declare variable WPER_APU_CRED integer;
declare variable WCODCRE_4_3_6 integer;
declare variable WTIPOPROD integer;
declare variable WIND_CRED_ORI integer;
declare variable WALIQ DM_NUMERIC_7_4_ALIQ;
declare variable WVLRCREDPERANT DM_NUMERIC_15_2;
declare variable WVALOR DM_NUMERIC_15_2;
declare variable WVALCREDPISPERATUAL DM_NUMERIC_15_2;
declare variable WVALCREDPISPERANT DM_NUMERIC_15_2;
declare variable WVALCREDCOFPERATUAL DM_NUMERIC_15_2;
declare variable WVALCREDCOFPERANT DM_NUMERIC_15_2;
declare variable WTOTALDEBPIS DM_NUMERIC_15_2;
declare variable WTOTALDEBCOFINS DM_NUMERIC_15_2;
declare variable WCALCCAMPO6 DM_NUMERIC_15_2;
declare variable WNAOUTILIZARCRED_201_208 DM_BOOLEAN;
BEGIN
  /* Alt.: #151858 - Foi criado o parâmetro :PRCODEMPSO, pois ao inserir nas tabelas na "SP_APURACAO_BLOCOM_1100_1500", gera os sequenciais pela empresa principal da apuração e aqui precisa seguir a mesma ordem, caso contrário, vai dar problema de chave na tabela */

  /* Caso tenham "COD_CRED" que tenham sido aproveitados todo crédito e não tenham gerados registros 1100/1500,
     É necessário pois precisa consolidar estes registros na exportação. */
  INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCRE_4_3_6, BDTIPOPROD, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC,BDALIQ, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM, BDRETIFICADORA)
  SELECT m.BDCODQUADRO,m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDREFERENCIA,
         m.bdchave , m.BDCODCRE_4_3_6, m.BDTIPOPROD, m.BDPER_APU_CRED, m.BDIND_CRED_ORI, m.BDCNPJ_SUC,M.BDALIQ, m.BDVL_CRED_DISP, m.BDVL_CRED_DESC, m.BDSLD_CRED, :PRRETIFICADORA BDRETIFICADORA
  FROM (
  SELECT IIF((m.BDCODQUADRO = 11), 52, 53) BDCODQUADRO,
         m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDREFERENCIA,
         GETORDEMSEQUENCIAL_STR('11001500.'||m.BDCODPERIODO||'.'||m.BDCODEMP||'.'||m.BDCODMATRIZ||'.'||IIF((m.BDCODQUADRO = 11), 52, 53)||'.'||m.BDREFERENCIA, :prCODEMP)
         /*(SELECT COALESCE(MAX(x.BDCHAVE+1), 1)
          FROM VEF_EMP_TBLOCOM1100_1500 x
          WHERE x.BDCODQUADRO = IIF((m.BDCODQUADRO = 11), 52, 53)
            AND x.BDCODPERIODO = m.BDCODPERIODO
            AND x.BDCODEMP = m.BDCODEMP
            AND x.BDCODMATRIZ = m.BDCODMATRIZ
            AND x.BDREFERENCIA = m.BDREFERENCIA) */
             bdchave,
           m.BDCODCRE_4_3_6, m.BDTIPOPROD, m.BDREFERENCIA BDPER_APU_CRED, m.BDIND_CRED_ORI, '  .   .   /    -  ' BDCNPJ_SUC,M.BDALIQ, SUM(m.BDVL_CRED_DISP) BDVL_CRED_DISP, SUM(m.BDVL_CRED_DESC) BDVL_CRED_DESC, SUM(m.BDSLD_CRED) BDSLD_CRED
  FROM VEF_EMP_TBLOCOM100_500 m
  WHERE m.BDCODMATRIZ = :prCODEMP
    AND m.BDREFERENCIA = :prREFERENCIA
    AND m.BDVL_CRED_DISP > 0
    AND M.BDRETIFICADORA = :PRRETIFICADORA
    GROUP BY IIF((m.BDCODQUADRO = 11), 52, 53),  m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDREFERENCIA, m.BDCODCRE_4_3_6, m.BDTIPOPROD, m.BDREFERENCIA, m.BDIND_CRED_ORI,M.BDALIQ
  ) m
  WHERE
    NOT EXISTS(SELECT *
                    FROM VEF_EMP_TBLOCOM1100_1500 s
                    WHERE s.BDCODEMP = m.BDCODEMP
                      AND s.BDCODMATRIZ = m.BDCODMATRIZ
                      AND s.BDREFERENCIA = m.BDREFERENCIA
                      AND s.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6
                      AND COALESCE(s.BDTIPOPROD,0) = COALESCE(m.BDTIPOPROD,0)
                      AND s.BDORIG_CRED = m.BDIND_CRED_ORI
                      AND s.BDPER_APU_CRED = :prREFERENCIA
                      AND s.BDCODQUADRO = m.BDCODQUADRO
                      AND S.BDRETIFICADORA = :PRRETIFICADORA
                      --AND s.BDALIQ = m.bdALIQ -- Alt.: #135683 - Deve verificar pela aliquota, pois caso mais de um com o mesmo tipo de credito, nao estava levando no 1100/1500...
                      AND ((s.bdALIQ = m.bdALIQ) OR (s.bdALIQ = 9999)) -- Alt.: #206110 - Por algum motivo que não sabemos e temos raiva de quem sabe, quando geram os créditos, é gerado com uma alíquota 9999, dái deve considerar ela aqui também, para não duplicar os créditos, já faz isso também no M200/600, então deve estar certo, ACHO...
--Elizeu - ajuste tecnico pra gerar todos os registros necessários, pois o caso que só a alíquota era diferente ele não levava o registro: Bloco M - Registro 1100/1500 e M100 e 500 #124906 #124637
                    --  and s.BDVL_CRED_APU = m.BDVL_CRED_DISP
                   );


  /**********
  ********************************************** 189944 - Início *********************************************

  - O que está havendo aqui????
    Bem antes dessa alteração o sistema tinha 2 parãmetros: "Utilizar primeiro créditos não passíveis de Ressarcimento" e "Aproveitar primeiro os créditos de PIS e Cofins de períodos anteriores".
    Eles são usados na SP SP_APURACAO_BLOCOM_M200M600, porém Houston we have a problem: naquele momento o sistema não possui as fichas 1100 e 1500 da referência atual.  Você caro leitor, deve ter 4
    observado que elas são geradas no começo dessa digníssima SP aqui.

    Bem o que isso ocasiona: o sistemna se aproveita de todos os créditos ressarcíveis ou não de períodos anteriores e se no período atual tiver crédito não ressarcível eles não são aproveitados.
    Ao longo do tempo, 5 anos, isso pode fazer com que a empresa não consiga se aproveitar de todos os seus créditos.

    Então aqui vamos obter esses 2 parâmetros. Se ambos estiverem como true, o que o sistema fará:

    1 - vai levantar os créditos consumidos no período
    2 - vai apagar todos os valores usados nas fichas 1100 e 1500
    3 - vai reapurar os créditos levando em conta os parâmetros.

    a gente deixa a outra rotina como estar por que precisamos saber o qto foi utilizado nas fichas 1100 e 1500. Então neste caso lá fica como se fosse um
    "rascunho" e aqui estaremos passando a limpo. Em teoria

  **********/
   -- Insere a competência da apuração...
  execute procedure SP_SETA_COMPETENCIA(:prREFERENCIA);

  select BDCODEMP, COALESCE(BDCREDITOSPERANT, 'FALSE'), COALESCE(BDABATERESSARCIM, 'FALSE'), coalesce(BDORDENACRED, 'FALSE'), coalesce(BDNAOUTILIZARCRE, 'FALSE'), coalesce(BDNAOUTILIZARCRED_201_208, 'FALSE')
  from VW_INT_SPEDPISCOFINS_REF
  where BDCODEMP = :PRCODEMP
  into :WCODEMP, :wCREDITOSPERANT, :wABATERESSARCIM, :wORDENACRED, :WNAOUTILIZARCRE, :WNAOUTILIZARCRED_201_208;

  if (:WCODEMP is null) then
    begin
      select COALESCE(BDCREDITOSPERANT, 'FALSE'), COALESCE(BDABATERESSARCIM, 'FALSE'), coalesce(BDORDENACRED, 'FALSE'), coalesce(BDNAOUTILIZARCRE, 'FALSE'), coalesce(BDNAOUTILIZARCRED_201_208, 'FALSE')
      from VW_INT_SPEDPISCOFINS_REF
      where BDCODEMP = :PRCODEMPSO
      into :wCREDITOSPERANT, :wABATERESSARCIM, :wORDENACRED, :WNAOUTILIZARCRE, :WNAOUTILIZARCRED_201_208;
    end

   IF ((:wCREDITOSPERANT = 'TRUE')  and (:WORDENACRED = 'TRUE')) THEN -- Apenas se estiver configurada a opção "Aproveitar o crédito de PIS e Cofins de períodos anteriores"
        BEGIN
          --1 - levantar os créditos consumidos no período
          Select
             SUM(CASE WHEN BDCODQUADRO = 52 THEN COALESCE(BDVL_CRED_DESC_EFD, 0) ELSE 0 END) AS CREDUSADOPIS,
             SUM(CASE WHEN BDCODQUADRO = 53 THEN COALESCE(BDVL_CRED_DESC_EFD, 0) ELSE 0 END) AS CREDUSADOCOFINS
          from VEF_EMP_TBLOCOM1100_1500
          where bdcodMatriz = :prCODEMP
            and bdreferencia = :prREFERENCIA
            AND BDRETIFICADORA = :PRRETIFICADORA
          into :WTOTALCREDPIS, :WTOTALCREDCOFINS;

          --confirmando que os créditos que serão usados de PIS não sejam superiores aos débitos
          SELECT FIRST 1 BDVALOR
          FROM VEF_EMP_TBLOCOMGERREG
          WHERE BDCODPERIODO = 7 and
                BDCODMATRIZ = :PRCODEMP and
                BDREFERENCIA = :prREFERENCIA and
                BDCODQUADRO = 15 and
                BDNUMCAMPO = 2 and
                BDRETIFICADORA = :PRRETIFICADORA
          into :WTOTALDEBPIS;

--          if (:WTOTALCREDPIS > :WTOTALDEBPIS) then
--             BEGIN
                :WTOTALCREDPIS = :WTOTALDEBPIS;
--             END

          --confirmando que os créditos que serão usados de COFINS não sejam superiores aos débitos
          SELECT FIRST 1 BDVALOR
          FROM VEF_EMP_TBLOCOMGERREG
          WHERE BDCODPERIODO = 7 and
                BDCODMATRIZ = :PRCODEMP and
                BDREFERENCIA = :prREFERENCIA and
                BDCODQUADRO = 33 and
                BDNUMCAMPO = 2 and
                BDRETIFICADORA = :PRRETIFICADORA
          into :WTOTALDEBCOFINS;

--          if (:WTOTALCREDCOFINS > :WTOTALDEBCOFINS) then
--             BEGIN
                :WTOTALCREDCOFINS = :WTOTALDEBCOFINS;
--             END

          if ((wtotalcredcofins + wtotalcredpis) > 0) then
             begin
                --2 - apagar todos os valores usados nas fichas 1100 e 1500
                update VEF_EMP_TBLOCOM1100_1500 m
                set m.BDVL_CRED_DESC_EFD = 0,
                    M.BDSLD_CRED_FIM = M.BDVL_CRED_APU
                where bdcodMatriz = :prCODEMP
                  and bdreferencia = :prREFERENCIA
                  AND M.BDRETIFICADORA = :PRRETIFICADORA;

                --Variáveis para atualizar o registro M200/M600
                WVALCREDPISPERATUAL = 0;
                WVALCREDPISPERANT = 0;
                WVALCREDCOFPERATUAL = 0;
                WVALCREDCOFPERANT = 0;

                FOR
                    SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.BDTIPOPROD, m.BDORIG_CRED,m.bdaliq,
                           SUM(COALESCE(m.BDSLD_CRED_FIM, 0)) as BDVALOR
                    FROM VEF_EMP_TBLOCOM1100_1500 m
                    left outer join VEF_BASE_TTAB_4_3_6 reg on (m.bdcodcre_4_3_6 = reg.bdcodcre_4_3_6)
                    where (m.BDCODMATRIZ = :prCODEMP)
                      and (m.BDREFERENCIA = :prREFERENCIA)
                      AND (M.BDRETIFICADORA = :PRRETIFICADORA)
                      --Larissa - 23/11/2021 - Controle de créditos Bloco M - 1100/1500/Ressarcimento #151311 #153687 #157389
                      AND (((Coalesce(m.bdvl_ressarcimento, 0) > 0) AND (:wABATERESSARCIM <> 'TRUE')) or (Coalesce(m.BDVL_RESSARCIMENTO,0) = 0))
                      and IIF(:WNAOUTILIZARCRE = 'TRUE', M.BDCODCRE_4_3_6 NOT IN (20, 21, 22, 23, 24, 25, 26, 27), TRUE)
                      and IIF(:WNAOUTILIZARCRED_201_208 = 'TRUE', M.BDCODCRE_4_3_6 NOT IN (11, 12, 13, 14, 15, 16, 17, 18), TRUE)
                    group by m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.bdTIPOPROD, m.BDORIG_CRED,m.bdaliq , reg.BDCODEXPCRE
                    order by M.BDCODQUADRO, IIF(:WORDENACRED = 'TRUE', IIF(REG.BDCODEXPCRE in ('108','201','202','203','204','208','301','302','303','304','307','308'), 2, 1), 1), m.BDPER_APU_CRED --Larissa - 30/11/2021 - Bloco M - utilização do crédito no mês da apuração, escolha do tipo de crédito #152907
                    into :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wPER_APU_CRED, :wCODCRE_4_3_6, :wTIPOPROD, :wIND_CRED_ORI,:waliq, :wVLRCREDPERANT
                do
                begin

                  if (CASE when :wCODQUADRO = 52 THEN :WTOTALCREDPIS ELSE :wtotalcredcofins END > 0)  then
                    begin

                       IF (:wCODQUADRO = 52) then
                          BEGIN

                             IF (:wVLRCREDPERANT < :WTOTALCREDPIS) then
                                BEGIN
                                   :WVALOR = :wVLRCREDPERANT;
                                END
                             ELSE
                                BEGIN
                                   :WVALOR = :WTOTALCREDPIS;
                                END

                             :WTOTALCREDPIS = :WTOTALCREDPIS - :WVALOR;

                             if (:wREFERENCIA = :wPER_APU_CRED) then
                                begin
                                   :WVALCREDPISPERATUAL = :WVALCREDPISPERATUAL + :wvalor;
                                end
                             else
                                begin
                                   :WVALCREDPISPERANT = :WVALCREDPISPERANT + :wvalor;
                                end

                          END
                       ELSE
                          BEGIN
                             if (:wVLRCREDPERANT < :wtotalcredcofins) then
                                BEGIN
                                   :WVALOR = :wVLRCREDPERANT;
                                END
                             ELSE
                                BEGIN
                                   :WVALOR = :wtotalcredcofins;
                                END

                             :wtotalcredcofins = :wtotalcredcofins - :WVALOR;

                             if (:wREFERENCIA = :wPER_APU_CRED) then
                                begin
                                   :WVALCREDCOFPERATUAL = :WVALCREDCOFPERATUAL + :wvalor;
                                end
                             else
                                begin
                                   :WVALCREDCOFPERANT = :WVALCREDCOFPERANT + :wvalor;
                                end
                          END

                       update VEF_EMP_TBLOCOM1100_1500 m
                       set m.BDVL_CRED_DESC_EFD = :WVALOR,
                           m.BDSLD_CRED_FIM = m.BDSLD_CRED_FIM - :WVALOR
                       where m.BDCODPERIODO = :wCODPERIODO
                         and m.BDCODQUADRO = :wCODQUADRO
                         and m.BDCODEMP = :wCODEMP
                         and m.BDCODMATRIZ = :wCODMATRIZ
                         and m.BDREFERENCIA = :wREFERENCIA
                         and m.BDPER_APU_CRED = :wPER_APU_CRED
                         and m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                         and COALESCE(m.BDTIPOPROD,0) = COALESCE(:wTIPOPROD,0)
                         and m.BDORIG_CRED = :wIND_CRED_ORI
                         and ((m.bdaliq = :wAliq) or (m.bdaliq = 9999))
                         AND M.BDRETIFICADORA = :PRRETIFICADORA;
                    end
                end

                --Aqui Vamos atualizar o M200/M600
                --Quadro 15 - PIS
                update or insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP,  BDCODMATRIZ, BDREFERENCIA,  BDCODQUADRO,  BDNUMCAMPO, BDVALOR             , BDRETIFICADORA)
                                                     values (7,            :prCODEMP, :prCODEMP,   :prREFERENCIA, 15,           3,          :WVALCREDPISPERATUAL, :PRRETIFICADORA)
                matching (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDRETIFICADORA);

                update or insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP,  BDCODMATRIZ, BDREFERENCIA,  BDCODQUADRO,  BDNUMCAMPO, BDVALOR           , BDRETIFICADORA)
                                                     values (7,            :prCODEMP, :prCODEMP,   :prREFERENCIA, 15,           4,          :WVALCREDPISPERANT, :PRRETIFICADORA)
                matching (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDRETIFICADORA);

                :WCALCCAMPO6 = WTOTALDEBPIS - :WVALCREDPISPERATUAL - :WVALCREDPISPERANT;

                update or insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP,  BDCODMATRIZ, BDREFERENCIA,  BDCODQUADRO,  BDNUMCAMPO, BDVALOR     , BDRETIFICADORA)
                                                     values (7,            :prCODEMP, :prCODEMP,   :prREFERENCIA, 15,           5,          :WCALCCAMPO6, :PRRETIFICADORA)
                matching (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDRETIFICADORA);

                SELECT FIRST 1 BDVALOR
                FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODPERIODO = 7 and
                      BDCODMATRIZ = :PRCODEMP and
                      BDREFERENCIA = :prREFERENCIA and
                      BDCODQUADRO = 15 and
                      BDNUMCAMPO = 7 and
                      BDRETIFICADORA = :PRRETIFICADORA
                into :WVALOR;

                :WCALCCAMPO6 = :WCALCCAMPO6 - coalesce(:WVALOR, 0);

                SELECT FIRST 1 BDVALOR
                FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODPERIODO = 7 and
                      BDCODMATRIZ = :PRCODEMP and
                      BDREFERENCIA = :prREFERENCIA and
                      BDCODQUADRO = 15 and
                      BDNUMCAMPO = 8 and
                      BDRETIFICADORA = :PRRETIFICADORA
                into :WVALOR;

                :WCALCCAMPO6 = :WCALCCAMPO6 - coalesce(:WVALOR, 0);

                update or insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP,  BDCODMATRIZ, BDREFERENCIA,  BDCODQUADRO,  BDNUMCAMPO, BDVALOR     , BDRETIFICADORA)
                                                     values (7,            :prCODEMP, :prCODEMP,   :prREFERENCIA, 15,           6,          :WCALCCAMPO6, :PRRETIFICADORA)
                matching (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDRETIFICADORA);

                --Quadro 33 - Cofins
                update or insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP,  BDCODMATRIZ, BDREFERENCIA,  BDCODQUADRO,  BDNUMCAMPO, BDVALOR             , BDRETIFICADORA)
                                                     values (7,            :prCODEMP, :prCODEMP,   :prREFERENCIA, 33,           3,          :WVALCREDCOFPERATUAL, :PRRETIFICADORA)
                matching (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDRETIFICADORA);

                update or insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP,  BDCODMATRIZ, BDREFERENCIA,  BDCODQUADRO,  BDNUMCAMPO, BDVALOR           , BDRETIFICADORA)
                                                     values (7,            :prCODEMP, :prCODEMP,   :prREFERENCIA, 33,           4,          :WVALCREDCOFPERANT, :PRRETIFICADORA)
                matching (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDRETIFICADORA);

                :WCALCCAMPO6 = WTOTALDEBCOFINS - :WVALCREDCOFPERATUAL - :WVALCREDCOFPERANT;

                update or insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP,  BDCODMATRIZ, BDREFERENCIA,  BDCODQUADRO,  BDNUMCAMPO, BDVALOR     , BDRETIFICADORA)
                                                     values (7,            :prCODEMP, :prCODEMP,   :prREFERENCIA, 33,           5,          :WCALCCAMPO6, :PRRETIFICADORA)
                matching (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDRETIFICADORA);

                SELECT FIRST 1 BDVALOR
                FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODPERIODO = 7 and
                      BDCODMATRIZ = :PRCODEMP and
                      BDREFERENCIA = :prREFERENCIA and
                      BDCODQUADRO = 33 and
                      BDNUMCAMPO = 7 and
                      BDRETIFICADORA = :PRRETIFICADORA
                into :WVALOR;

                :WCALCCAMPO6 = :WCALCCAMPO6 - coalesce(:WVALOR, 0);

                SELECT FIRST 1 BDVALOR
                FROM VEF_EMP_TBLOCOMGERREG
                WHERE BDCODPERIODO = 7 and
                      BDCODMATRIZ = :PRCODEMP and
                      BDREFERENCIA = :prREFERENCIA and
                      BDCODQUADRO = 33 and
                      BDNUMCAMPO = 8 and
                      BDRETIFICADORA = :PRRETIFICADORA
                into :WVALOR;

                :WCALCCAMPO6 = :WCALCCAMPO6 - coalesce(:WVALOR, 0);

                update or insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP,  BDCODMATRIZ, BDREFERENCIA,  BDCODQUADRO,  BDNUMCAMPO, BDVALOR     , BDRETIFICADORA)
                                                     values (7,            :prCODEMP, :prCODEMP,   :prREFERENCIA, 33,           6,          :WCALCCAMPO6, :PRRETIFICADORA)
                matching (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDRETIFICADORA);

                --Acertar os registros M100/M500
                update VEF_EMP_TBLOCOM100_500
                set BDVL_CRED_DESC = 0,
                    BDIND_DESC_CRED = 1,
                    BDSLD_CRED = BDVL_CRED_DISP
                where BDCODMATRIZ = :PRCODEMP and
                      BDREFERENCIA = :prreferencia and
                      BDRETIFICADORA = :prretificadora;

                merge into VEF_EMP_TBLOCOM100_500 M100M500
                using (select BDCODQUADRO, BDCODMATRIZ, BDCODEMP, BDCODCRE_4_3_6, BDCODPERIODO, BDREFERENCIA, BDORIG_CRED,
                              BDRETIFICADORA, sum(BDVL_CRED_DESC_EFD) as VALOR
                       from VEF_EMP_TBLOCOM1100_1500 A
                       where BDCODMATRIZ = :PRCODEMP and
                             BDREFERENCIA = :prreferencia and
                             BDRETIFICADORA = :prretificadora and
                             BDREFERENCIA = BDPER_APU_CRED and
                             BDVL_CRED_DESC_EFD > 0
                       group by BDCODQUADRO, BDCODMATRIZ, BDCODEMP, BDCODCRE_4_3_6, BDCODPERIODO, BDREFERENCIA, BDORIG_CRED, BDRETIFICADORA) SALDOS
                on M100M500.BDCODQUADRO = iif(SALDOS.BDCODQUADRO = 52, 11, 29) and
                   M100M500.BDCODPERIODO = SALDOS.BDCODPERIODO and
                   M100M500.BDCODEMP = SALDOS.BDCODEMP and
                   M100M500.BDCODMATRIZ = SALDOS.BDCODMATRIZ and
                   M100M500.BDREFERENCIA = SALDOS.BDREFERENCIA and
                   M100M500.BDCODCRE_4_3_6 = SALDOS.BDCODCRE_4_3_6 and
                   M100M500.BDIND_CRED_ORI = SALDOS.BDORIG_CRED
                when matched then
                    update set M100M500.BDVL_CRED_DESC = iif(M100M500.BDVL_CRED_DISP < SALDOS.VALOR, M100M500.BDVL_CRED_DISP, SALDOS.VALOR),
--                               M100M500.BDIND_DESC_CRED = iif(/*M100M500.BDVL_CRED_DISP > */SALDOS.VALOR > 0, 1, 0),
                               M100M500.BDSLD_CRED = iif(M100M500.BDVL_CRED_DISP < SALDOS.VALOR, 0, M100M500.BDVL_CRED_DISP - SALDOS.VALOR);

                update VEF_EMP_TBLOCOM100_500
                set BDIND_DESC_CRED = iif(BDSLD_CRED > 0 , 1, 0)
                where BDCODMATRIZ = :PRCODEMP and
                      BDREFERENCIA = :prreferencia and
                      BDRETIFICADORA = :prretificadora;
             end
         end
  /**********
  ********************************************** 189944 - Fim *********************************************
  **********/


  WCODPERIODO = NULL; 

  SELECT First 1 M.BDCODPERIODO
  FROM VEF_EMP_TBLOCOM1100_1500 M
  WHERE M.BDCODMATRIZ = :prCODEMP
    AND M.BDREFERENCIA = :prREFERENCIA  
    AND M.BDRETIFICADORA = :PRRETIFICADORA
    AND M.BDCODQUADRO = 52
    AND M.BDVL_CRED_APU = 0
    AND (m.BDVL_RESSARCIMENTO + m.BDVL_COMPENSACAO + m.BDVL_CISAO + m.BDVL_OUTRAS) > 0
  INTO :WCODPERIODO;

  IF (:WCODPERIODO IS NOT NULL) THEN
      UPDATE OR INSERT INTO VEF_INCON_BLOCOM (bdCODPERIODO, bdCODEMP, bdCODMATRIZ, bdREFERENCIA, bdCODBLOCOM, bdCODINC, BDRETIFICADORA)
      VALUES (:WCODPERIODO, :prCODEMP, :prCODEMP, :prREFERENCIA, GETORDEMSEQUENCIAL_STR(:prCODEMP||'.'||:prCODEMP||'.'||:prREFERENCIA, :PRCODEMPSO), 25, :PRRETIFICADORA)
      MATCHING (bdCODPERIODO, bdCODEMP, bdCODMATRIZ, bdREFERENCIA, bdCODBLOCOM, BDRETIFICADORA);
      

  SELECT First 1 M.BDCODPERIODO
  FROM VEF_EMP_TBLOCOM1100_1500 M
  WHERE M.BDCODMATRIZ = :prCODEMP
    AND M.BDREFERENCIA = :prREFERENCIA
    AND M.BDRETIFICADORA = :PRRETIFICADORA
    AND M.BDCODQUADRO = 53                
    AND M.BDVL_CRED_APU = 0
    AND (m.BDVL_RESSARCIMENTO + m.BDVL_COMPENSACAO + m.BDVL_CISAO + m.BDVL_OUTRAS) > 0
  INTO :WCODPERIODO;

  IF (:WCODPERIODO IS NOT NULL) THEN
      UPDATE OR INSERT INTO VEF_INCON_BLOCOM (bdCODPERIODO, bdCODEMP, bdCODMATRIZ, bdREFERENCIA, bdCODBLOCOM, bdCODINC, BDRETIFICADORA)
      VALUES (:WCODPERIODO, :prCODEMP, :prCODEMP, :prREFERENCIA, GETORDEMSEQUENCIAL_STR(:prCODEMP||'.'||:prCODEMP||'.'||:prREFERENCIA, :PRCODEMPSO), 26, :PRRETIFICADORA)
      MATCHING (bdCODPERIODO, bdCODEMP, bdCODMATRIZ, bdREFERENCIA, bdCODBLOCOM, BDRETIFICADORA);


  DELETE
  FROM VEF_EMP_TBLOCOM1100_1500 M
  WHERE M.BDCODMATRIZ = :prCODEMP
    AND M.BDREFERENCIA = :prREFERENCIA
    AND M.BDRETIFICADORA = :PRRETIFICADORA
    AND M.BDVL_CRED_APU = 0
    AND (m.BDVL_RESSARCIMENTO + m.BDVL_COMPENSACAO + m.BDVL_CISAO + m.BDVL_OUTRAS) > 0;


  SELECT First 1 M.BDCODPERIODO
  FROM VEF_EMP_TBLOCOM1100_1500 M
  WHERE M.BDCODMATRIZ = :prCODEMP
    AND M.BDREFERENCIA = :prREFERENCIA
    AND M.BDRETIFICADORA = :PRRETIFICADORA
    AND M.BDCODQUADRO = 52
    AND (m.BDSLD_CRED_FIM - m.BDVL_RESSARCIMENTO - m.BDVL_COMPENSACAO - m.BDVL_CISAO - m.BDVL_OUTRAS) < 0
  INTO :WCODPERIODO;

  IF (:WCODPERIODO IS NOT NULL) THEN
      UPDATE OR INSERT INTO VEF_INCON_BLOCOM (bdCODPERIODO, bdCODEMP, bdCODMATRIZ, bdREFERENCIA, bdCODBLOCOM, bdCODINC, BDRETIFICADORA)
      VALUES (:WCODPERIODO, :prCODEMP, :prCODEMP, :prREFERENCIA, GETORDEMSEQUENCIAL_STR(:prCODEMP||'.'||:prCODEMP||'.'||:prREFERENCIA, :PRCODEMPSO), 23, :PRRETIFICADORA)
      MATCHING (bdCODPERIODO, bdCODEMP, bdCODMATRIZ, bdREFERENCIA, bdCODBLOCOM, BDRETIFICADORA);
      

  SELECT First 1 M.BDCODPERIODO
  FROM VEF_EMP_TBLOCOM1100_1500 M
  WHERE M.BDCODMATRIZ = :prCODEMP
    AND M.BDREFERENCIA = :prREFERENCIA
    AND M.BDRETIFICADORA = :PRRETIFICADORA
    AND M.BDCODQUADRO = 53
    AND (m.BDSLD_CRED_FIM - m.BDVL_RESSARCIMENTO - m.BDVL_COMPENSACAO - m.BDVL_CISAO - m.BDVL_OUTRAS) < 0
  INTO :WCODPERIODO;

  IF (:WCODPERIODO IS NOT NULL) THEN
      UPDATE OR INSERT INTO VEF_INCON_BLOCOM (bdCODPERIODO, bdCODEMP, bdCODMATRIZ, bdREFERENCIA, bdCODBLOCOM, bdCODINC, BDRETIFICADORA)
      VALUES (:WCODPERIODO, :prCODEMP, :prCODEMP, :prREFERENCIA, GETORDEMSEQUENCIAL_STR(:prCODEMP||'.'||:prCODEMP||'.'||:prREFERENCIA, :PRCODEMPSO), 24, :PRRETIFICADORA)
      MATCHING (bdCODPERIODO, bdCODEMP, bdCODMATRIZ, bdREFERENCIA, bdCODBLOCOM, BDRETIFICADORA);

  UPDATE VEF_EMP_TBLOCOM1100_1500 M
  SET M.BDSLD_CRED_FIM = (SELECT BDVALOR FROM SP_RETORNA_MAIOR_ZERO(m.BDSLD_CRED_FIM - Coalesce(m.BDVL_RESSARCIMENTO,0) - Coalesce(m.BDVL_COMPENSACAO,0) - Coalesce(m.BDVL_CISAO,0) - Coalesce(m.BDVL_OUTRAS,0)))
  WHERE M.BDCODMATRIZ = :prCODEMP
    AND M.BDREFERENCIA = :PRREFERENCIA
    AND M.BDRETIFICADORA = :PRRETIFICADORA;

  EXECUTE PROCEDURE SP_BLOCOM_DADOSFINAIS_M400_M800(:PRCODEMP, :PRREFERENCIA, :PRCODEMPSO, :PRRETIFICADORA, :PRAJUSTESCP); 

END^

create or alter procedure SP_APURACAO_BLOCOM_AJUSTACONTAB (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRTIPO VARCHAR(3))
as
declare variable WVALDEBITO DM_NUMERIC_15_2;
declare variable WVALCREDITO DM_NUMERIC_15_2;
declare variable WCODITEMONLINE INTEGER;
declare variable WVAL DM_NUMERIC_15_2;
declare variable WIND INTEGER;
BEGIN
  -- Alt.: #195506 - Estava acontencendo algumas diferenças nos valores da contabilização do Bloco M, aqui vai somar os valores dos lançamentos contábeis e tentar corrigir as diferenças.

  -- Obtem os totatis de debitos e creditos contabilizados e tambem o tipo da conta, onde deve contabilizar a diferenca...
  SELECT SUM(bdDEBITO)bdDEBITO, SUM(bdCREDITO) bdCREDITO, MIN(bdCODITEMONLINE) bdCODITEMONLINE
  FROM (
        SELECT SUM(t.bdDEBITO) bdDEBITO, SUM(t.bdCREDITO) bdCREDITO, t.bdCODITEMONLINE
        FROM (
              SELECT SUM(COALESCE(t.bdVALOR, 0))bdDEBITO, 0 bdCREDITO, t.bdORDENACAO,
                     MIN(CAST((SELECT bdNUMERO FROM SP_RETORNA_NUMEROS(SUBSTRING(t.bdORDENACAO FROM 1 FOR POSITION('.' IN t.bdORDENACAO)-1))) AS INTEGER)) bdCODITEMONLINE
              FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP T
              WHERE t.bdDEBITO IS NOT NULL
                AND t.bdCODMATRIZ = :prCODEMP
                AND t.bdREFERENCIA = :prREFERENCIA
              GROUP BY t.bdORDENACAO
              ) t
        JOIN TITEMCONFIGONLINE i ON(i.bdCODITEMONLINE = t.bdCODITEMONLINE)
        WHERE I.BDFORMULA CONTAINING :prTIPO
        GROUP BY t.bdCODITEMONLINE
        UNION ALL
        SELECT SUM(t.bdDEBITO) bdDEBITO, SUM(t.bdCREDITO) bdCREDITO, t.bdCODITEMONLINE
        FROM (
              SELECT 0 bdDEBITO, SUM(COALESCE(t.bdVALOR, 0)) bdCREDITO, t.bdORDENACAO,
                     MIN(CAST((SELECT bdNUMERO FROM SP_RETORNA_NUMEROS(SUBSTRING(t.bdORDENACAO FROM 1 FOR POSITION('.' IN t.bdORDENACAO)-1))) AS INTEGER)) bdCODITEMONLINE
              FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP T
              WHERE t.bdCREDITO IS NOT NULL
                AND t.bdCODMATRIZ = :prCODEMP
                AND t.bdREFERENCIA = :prREFERENCIA
              GROUP BY t.bdORDENACAO
              ) t
        JOIN TITEMCONFIGONLINE i ON(i.bdCODITEMONLINE = t.bdCODITEMONLINE)
        WHERE I.BDFORMULA CONTAINING :prTIPO
        GROUP BY t.bdCODITEMONLINE
        )
  INTO :wVALDEBITO, :wVALCREDITO, :wCODITEMONLINE;
  
  -- Verifica se existe difernça nos valores
  IF (:wValDebito <> :wValCredito) THEN
    BEGIN
      IF (:wValDebito > :wValCredito) THEN -- Credito
        BEGIN
          :wVal = :wValDebito - :wValCredito;
          :wInd = 1;
        END
      ELSE
      IF (:wValDebito < :wValCredito) THEN -- Debito
        BEGIN
          :wVal = :wValCredito - :wValDebito;
          :wInd = 0;
        END
      
      -- Atualiza o primeiro tipo Debito/Credito que tiver com a diferença encontrada
      MERGE INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP l
      USING (
             SELECT FIRST 1 t.*
             FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t
             WHERE (((t.bdDEBITO IS NOT NULL)  AND (0 = :wInd)) OR
                    ((t.bdCREDITO IS NOT NULL) AND (1 = :wInd)))
               AND t.bdCODMATRIZ = :prCODEMP
               AND t.bdREFERENCIA = :prREFERENCIA
               AND t.bdORDENACAO CONTAINING :wCODITEMONLINE
             ORDER BY t.bdORDENACAO
             ) t
         ON  l.bdCODMATRIZ           = t.bdCODMATRIZ
         AND l.bdREFERENCIA          = t.bdREFERENCIA
         AND COALESCE(l.bdCHAVE,0)   = COALESCE(t.bdCHAVE,0)
         AND l.bdCODPLAPADRAO        = t.bdCODPLAPADRAO
         AND COALESCE(l.bdCODUSU,0)  = COALESCE(t.bdCODUSU,0)
         AND COALESCE(l.bdDEBITO,0)  = COALESCE(t.bdDEBITO,0)
         AND COALESCE(l.bdCREDITO,0) = COALESCE(t.bdCREDITO,0)
         AND COALESCE(l.bdDATA,'')   = COALESCE(t.bdDATA,'')
         AND l.bdORDENACAO           = t.bdORDENACAO
         AND l.bdCODHIST             = t.bdCODHIST
      WHEN MATCHED THEN
          UPDATE SET l.bdVALOR = l.bdVALOR + :wVal;

    END

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRCODITEMONLINE INTEGER)
AS
DECLARE VARIABLE WCODINC INTEGER;
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCONTDETALHADA VARCHAR(5);
declare variable WTIPOINTPIS integer;
declare variable WTIPOINTCOFINS integer;
declare variable WCODPLANOONLINE integer;
BEGIN
  -- Obtém o plano online
  SELECT r.bdCODPLANOONLINE
  FROM VW_TEMPRESAS_REF r
  WHERE r.bdCODEMP = :PRCODEMP
  INTO :wCODPLANOONLINE;

  -- Verifica se contabiliza normal ou por CFOP
  SELECT bdTIPOINTPIS, bdTIPOINTCOFINS
  FROM TPLANO_CONF_ONLINE
  WHERE bdCODPLANOONLINE = :wCODPLANOONLINE
  INTO :wTIPOINTPIS, :wTIPOINTCOFINS;

  /* Insere os valores do Créditos e Débitos */
  if ((:wTIPOINTPIS = 4) OR (:wTIPOINTCOFINS = 4)) then
    BEGIN
      /* Insere os valores do Créditos e Débitos */
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODHIST, bdCODTPHI, bdORDENACAO)
  SELECT t.bdCODMATRIZ, t.bdREFERENCIA, NULL as bdCHAVE, t.bdCODPLAPADRAO, NULL as bdCODUSU, t.bdCONTADEBPROV as bdDEBITO, t.bdCONTACREDPROV as bdCREDITO,
         CASE WHEN ch.bdCOMPLEMENTO IS NOT NULL THEN REPLACE(
                                                     REPLACE(
                                                         REPLACE(
                                                         REPLACE(
                                                     REPLACE(ch.bdCOMPLEMENTO,
                                                             '*MES', COALESCE(SUBSTRING(t.bdREFERENCIA FROM 5 for 2),'*MES')),
                                                             '*ANO', COALESCE(SUBSTRING(t.bdREFERENCIA FROM 1 for 4),'*ANO')),
                                                                 '*REF', COALESCE(SUBSTRING(t.bdREFERENCIA FROM 5 for 2)||'/'||SUBSTRING(t.bdREFERENCIA FROM 1 for 4),'*REF')),
                                                                 '*CFOP', COALESCE(SUBSTRING(N.BDCODNAT FROM 1 FOR 1)||'.'||SUBSTRING(N.BDCODNAT FROM 2 FOR 3)||'-'||SUBSTRING(N.BDCODNAT FROM 5 FOR 3),'*CFOP')),
                                                                 '*CONDICAO', COALESCE(TRIM(CASE WHEN SUBSTRING(T.BDFORMULA FROM 4 FOR 1) = 'P' THEN 'Prazo'
                                                                                                 WHEN SUBSTRING(T.BDFORMULA FROM 4 FOR 1) = 'V' THEN 'Vista'
                                                                                                 WHEN SUBSTRING(T.BDFORMULA FROM 4 FOR 1) = 'O' THEN 'Outras'
                                                                                           END),'*CONDICAO')
                                                                 )
             ELSE 'Valor de '||
                  TRIM(CASE
                         WHEN t.bdFORMULA LIKE '%PIS%' THEN 'PIS'
                         WHEN t.bdFORMULA LIKE '%COFINS%' THEN 'Cofins'
                       ELSE ''
                       END)||
                  ' '||
                  TRIM(CASE
                         WHEN t.bdCODITEMONLINE IN (247,251) THEN 'Crédito '
                         WHEN t.bdCODITEMONLINE IN (248,252) THEN 'Débito '
                       ELSE ''
                       END)||
                  --' - CFOP: '||SUBSTRING(N.BDCODNAT FROM 1 FOR 1)||'.'||SUBSTRING(N.BDCODNAT FROM 2 FOR 3)||'-'||SUBSTRING(N.BDCODNAT FROM 5 FOR 3)|| Alt.: #197649
                  COALESCE((' - CFOP: '||SUBSTRING(N.BDCODNAT FROM 1 FOR 1)||'.'||SUBSTRING(N.BDCODNAT FROM 2 FOR 3)||'-'||SUBSTRING(N.BDCODNAT FROM 5 FOR 3)),'')||
                  ' - Ref:'||CAST(substring(t.bdREFERENCIA FROM 5 for 2)||'/'||substring(t.bdREFERENCIA FROM 1 for 4) AS VARCHAR(7))
             END as bdCOMPL,
             NULL as bdDATA, t.bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, 'TRUE' bdTRANFECHADA, t.bdCODHIST, t.bdCODTPHI, t.bdORDENACAO
      FROM TMP_TCONF_CONTAS_ONLINE_TEMP t
      LEFT OUTER JOIN TCOMPLEMENTO_HIST ch ON (ch.bdCODCOMPHIST = t.bdCODCOMPHIST)
      --JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = T.BDCODNAT) Alt.: #197649
      LEFT OUTER JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = T.BDCODNAT)
      WHERE t.bdCODITEMONLINE IN (:prCODITEMONLINE)  -- "Créditos" e "Débitos"...
        --AND T.BDFORMULA LIKE '%NAT%' -- Conta de CFOP Alt.: #197649
        AND t.bdFORMULA IS NOT NULL
        AND t.bdVALOR > 0
      ORDER BY t.bdCODMATRIZ, t.bdREFERENCIA, t.bdORDENACAO;  
    END
  ELSE
    BEGIN
      /* Insere os valores do Créditos e Débitos */
      INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODHIST, bdCODTPHI, bdORDENACAO)
      SELECT t.bdCODMATRIZ, t.bdREFERENCIA, NULL as bdCHAVE, t.bdCODPLAPADRAO, NULL as bdCODUSU, t.bdCONTADEBPROV as bdDEBITO, t.bdCONTACREDPROV as bdCREDITO,
             CASE WHEN ch.bdCOMPLEMENTO IS NOT NULL THEN REPLACE(
                                                         REPLACE(
                                                         REPLACE(ch.bdCOMPLEMENTO,
                                                                 '*MES', SUBSTRING(t.bdREFERENCIA FROM 5 for 2)),
                                                                 '*ANO', SUBSTRING(t.bdREFERENCIA FROM 1 for 4)),
                                                             '*REF', SUBSTRING(t.bdREFERENCIA FROM 5 for 2)||'/'||SUBSTRING(t.bdREFERENCIA FROM 1 for 4))
         ELSE 'Valor de '||
              TRIM(CASE
                     WHEN t.bdFORMULA LIKE '%PIS%' THEN 'PIS'
                     WHEN t.bdFORMULA LIKE '%COFINS%' THEN 'Cofins'
                   ELSE ''
                   END)||
              ' '||
              TRIM(CASE
                     WHEN t.bdFORMULA LIKE '%CREDDESC%' THEN 'Crédito '
                     WHEN t.bdFORMULA LIKE '%DEBITO%' THEN 'Débito '
                   ELSE ''
                   END)||
               ' "'||COALESCE(cred.bdREGEXP||' - '||cred.bdDESCRICAO, deb.bdCODCSOCIALEXP||' - '||deb.bdDESCRICAO)||'"'||
               ' - Ref:'||CAST(substring(t.bdREFERENCIA FROM 5 for 2)||'/'||substring(t.bdREFERENCIA FROM 1 for 4) AS VARCHAR(7))
         END as bdCOMPL,
         NULL as bdDATA, t.bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, 'TRUE' bdTRANFECHADA, t.bdCODHIST, t.bdCODTPHI, t.bdORDENACAO
  FROM TMP_TCONF_CONTAS_ONLINE_TEMP t
  LEFT OUTER JOIN TCOMPLEMENTO_HIST ch ON (ch.bdCODCOMPHIST = t.bdCODCOMPHIST)
  LEFT OUTER JOIN VEF_BASE_TNATBCPISCOFINS cred ON (cred.bdREGEXP = CASE
                                                                      WHEN t.bdFORMULA LIKE '%CREDDESC%' THEN SUBSTRING(t.bdFORMULA FROM (POSITION('(', t.bdFORMULA)-2) FOR 2)
                                                                    ELSE '' END)
  LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 deb ON (deb.bdCODCSOCIALEXP = CASE
                                                                             WHEN t.bdFORMULA LIKE '%DEBITO%' THEN SUBSTRING(t.bdFORMULA FROM (POSITION('(', t.bdFORMULA)-2) FOR 2)
                                                                           ELSE '' END)
  WHERE t.bdCODITEMONLINE IN (:prCODITEMONLINE) -- "Créditos" e "Débitos"...
    AND t.bdFORMULA IS NOT NULL
    AND t.bdVALOR > 0
  ORDER BY t.bdCODMATRIZ, t.bdREFERENCIA, t.bdORDENACAO;
    END

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (
    PRCODEMP integer,
    PRCODEMPMATRIZ integer,
    PRREFERENCIA integer,
    PRTIPO varchar(6),
    PRDEBCRED varchar(5) = '',
    PRRETIFICADORA integer = 0,
    PRTIPO2 varchar(20) = '',
    PRCONTABILIZAFILIAL DM_BOOLEAN = 'FALSE')
as
declare variable WCODINC integer;
declare variable WINCTRIB integer;
declare variable WCONTDETALHADA varchar(5);
declare variable WSQL varchar(10000);
declare variable WSQLAUX varchar(10000);
declare variable WCODQUADRO integer;
declare variable WCODQUADROSALDO integer;
declare variable WCODITEMONLINE integer;
declare variable WCODEMP integer;
declare variable WVALOR numeric(18,3);
declare variable WORDENACAO varchar(5000);
declare variable WCODEMPSQL varchar(20);
BEGIN
  IF (UPPER(:prTIPO) = 'PIS') THEN
    BEGIN
      wCODQUADRO      = 15; -- M200 - Consolidação da contribuição para o PIS/PASEP
      wCODQUADROSALDO = 52; -- 1100 - Controle de créditos fiscais PIS/PASEP
      IF (:PRRETIFICADORA = 0) THEN
      BEGIN
      wCODITEMONLINE  = 247;
    END
  ELSE
      IF (:PRRETIFICADORA = 1) THEN
      BEGIN
        wCODITEMONLINE  = 533;
      END
    END
  ELSE
  IF (UPPER(:prTIPO) = 'COFINS') THEN
    BEGIN
      wCODQUADRO      = 33; -- M600 - Consolidação da contribuição para o Cofins
      wCODQUADROSALDO = 53; -- 1500 - Controle de créditos fiscais Cofins
      IF (:PRRETIFICADORA = 0) THEN
      BEGIN
      wCODITEMONLINE  = 251;
    END
      ELSE
      IF (:PRRETIFICADORA = 1) THEN
      BEGIN
        wCODITEMONLINE  = 535;
      END
    END

  IF (PRCONTABILIZAFILIAL = 'TRUE') THEN
  BEGIN
    WCODEMPSQL = 'BDCODEMP';
  END
  ELSE
    WCODEMPSQL = 'BDCODMATRIZ';

  IF (:prDEBCRED <> '') THEN
    BEGIN
      wSQLAUX =                         '(COALESCE((SELECT SUM(COALESCE(t.bdVALOR, 0)) ';
      wSQLAUX = wSQLAUX||                          'FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t ';
      wSQLAUX = wSQLAUX||                          'WHERE t.bdCODMATRIZ = G.'||:WCODEMPSQL||' ';
      wSQLAUX = wSQLAUX||                            'AND t.bdREFERENCIA = g.bdREFERENCIA ';
      wSQLAUX = wSQLAUX||                            'AND t.bdCODPLAPADRAO = c.bdCODPLAPADRAO ';
      wSQLAUX = wSQLAUX||                            'AND POSITION('''||:wCODITEMONLINE||''', t.bdORDENACAO) > 0 ';
      wSQLAUX = wSQLAUX||                            'AND ((POSITION(''.00000'', t.bdORDENACAO) = 0) ';
      IF (UPPER(:prDEBCRED) = 'DEB') THEN
        wSQLAUX = wSQLAUX||                   'AND t.bdDEBITO IS NULL)),0)) ';
      ELSE
      IF (UPPER(:prDEBCRED) = 'CRED') THEN
        wSQLAUX = wSQLAUX||                   'AND t.bdCREDITO IS NULL)),0)) ';
    END
  ELSE
    BEGIN
      if (PRCONTABILIZAFILIAL = 'TRUE') then
      BEGIN
        wSQLAUX =               '(COALESCE(m1100.BDVL_CRED_APU,0)';
      END
      ELSE
      BEGIN
        wSQLAUX =               '(COALESCE(m1100.bdSLD_CRED_FIM,0)+COALESCE(g.bdVALOR,0)';
      END                                                                                                                  
      wSQLAUX = wSQLAUX||                                                                       '-COALESCE((SELECT SUM(o.bdVALOR) ';
      wSQLAUX = wSQLAUX||                                                                       'FROM TMP_TCONF_CONTAS_ONLINE_TEMP o ';
      wSQLAUX = wSQLAUX||                                                                       'WHERE o.bdCODPLAPADRAO = c.bdCODPLAPADRAO ';
      wSQLAUX = wSQLAUX||                                                                        'AND o.bdCODITEMONLINE = '||:wCODITEMONLINE||' ';
      IF (PRCONTABILIZAFILIAL = 'TRUE') THEN
      BEGIN
        wSQLAUX = wSQLAUX||                                                                      'AND o.BDCODMATRIZ = '||:PRCODEMP||' ';
      END
      ELSE
        wSQLAUX = wSQLAUX||                                                                      'AND o.BDCODMATRIZ = G.BDCODMATRIZ ';
      wSQLAUX = wSQLAUX||                                                                        'AND o.bdREFERENCIA = G.BDREFERENCIA ';
      wSQLAUX = wSQLAUX||                                                                        'AND o.bdFORMULA IS NOT NULL '; -- Contabilização detalhada
      wSQLAUX = wSQLAUX||                                                                        'AND o.bdVALOR > 0 ),0) ';
      wSQLAUX = wSQLAUX||                                                                       ') ';
    END

  --  "Crédito Principal"
  wSQL =       'INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODHIST, bdCODTPHI, bdORDENACAO) ';
  wSQL = wSQL||'SELECT IIF('||:PRCONTABILIZAFILIAL||' = ''TRUE'','||:PRCODEMP||',g.'||:WCODEMPSQL||'), g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU,  ';
  IF (:prDEBCRED <> '') THEN
    BEGIN
      IF (UPPER(:prDEBCRED) = 'DEB') THEN
        wSQL = wSQL||'c.bdCONTADEBPROV as bdDEBITO, NULL as bdCREDITO, ';
      ELSE
      IF (UPPER(:prDEBCRED) = 'CRED') THEN
        wSQL = wSQL||'NULL as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO, ';
    END
  ELSE
    wSQL = wSQL||'c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO, ';
  --wSQL = wSQL||      ' ''Valor de '||:prTIPO||' Crédito - Ref:''||substring(g.bdREFERENCIA FROM 5 for 2)||''/''||substring(g.bdREFERENCIA FROM 1 for 4) as bdCOMPL, ';
  wSQL = wSQL||      '       CASE WHEN ch.bdCOMPLEMENTO IS NOT NULL THEN REPLACE( ';
  wSQL = wSQL||      '                                                   REPLACE( ';
  wSQL = wSQL||      '                                                   REPLACE(ch.bdCOMPLEMENTO, ';
  wSQL = wSQL||      '                                                           ''*MES'', SUBSTRING(g.bdREFERENCIA FROM 5 for 2)), ';
  wSQL = wSQL||      '                                                           ''*ANO'', SUBSTRING(g.bdREFERENCIA FROM 1 for 4)), ';
  wSQL = wSQL||      '                                                           ''*REF'', SUBSTRING(g.bdREFERENCIA FROM 5 for 2)||''/''||SUBSTRING(g.bdREFERENCIA FROM 1 for 4)) ';
  wSQL = wSQL||      '         ELSE ''Valor de '||:prTIPO||:PRTIPO2||' - Ref:''||substring(g.bdREFERENCIA FROM 5 for 2)||''/''||substring(g.bdREFERENCIA FROM 1 for 4) ';
  wSQL = wSQL||      '       END as bdCOMPL, ';

  wSQL = wSQL||      'NULL as bdDATA, ';
  wSQL = wSQL||      wSQLAUX||' as bdVALOR, ';
  wSQL = wSQL||      '100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, ''TRUE'' bdTRANFECHADA, c.bdCODHIST, c.bdCODTPHI, c.bdORDENACAO ';
  wSQL = wSQL||'FROM VEF_EMP_TBLOCOMGERREG g ';
  wSQL = wSQL||'JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP) ';
  wSQL = wSQL||'JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = '||:wCODITEMONLINE||') ';
  wSQL = wSQL||'LEFT OUTER JOIN TCOMPLEMENTO_HIST ch ON (ch.bdCODCOMPHIST = c.bdCODCOMPHIST) ';
  wSQL = wSQL||'LEFT OUTER JOIN (';
  wSQL = wSQL||                  'SELECT sld.bdCODPERIODO, sld.bdCODMATRIZ, sld.bdREFERENCIA, sld.bdCODQUADRO, SUM(COALESCE(sld.bdSLD_CRED_FIM,0)) as bdSLD_CRED_FIM, SLD.BDRETIFICADORA,sum(coalesce(SLD.BDVL_CRED_APU, 0)) as BDVL_CRED_APU ';
  wSQL = wSQL||                  'FROM VEF_EMP_TBLOCOM1100_1500 sld ';
  wSQL = wSQL||                  'WHERE sld.'||:WCODEMPSQL||'= '||:prCODEMP||' ';
  wSQL = wSQL||                    'AND sld.bdREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||                    'AND sld.bdPER_APU_CRED = '||:prREFERENCIA||' '; -- Apenas o saldo do mês atual, os per´´iodos anteriores já usou o campo 04 na "Compenção"
  wSQL = wSQL||                    'AND sld.bdCODQUADRO = '||:wCODQUADROSALDO||' ';
  wSQL = wSQL||                    'AND SLD.BDRETIFICADORA = '||:PRRETIFICADORA||' ';
  wSQL = wSQL||                  'GROUP BY sld.bdCODPERIODO, sld.bdCODMATRIZ, sld.bdREFERENCIA, sld.bdCODQUADRO, SLD.BDRETIFICADORA ';
  wSQL = wSQL||                 ') m1100 ON (m1100.bdCODPERIODO = g.bdCODPERIODO and m1100.bdCODMATRIZ = g.bdCODMATRIZ and m1100.bdREFERENCIA = g.bdREFERENCIA AND M1100.BDRETIFICADORA = G.BDRETIFICADORA) ';
  IF (PRCONTABILIZAFILIAL = 'TRUE') THEN
    WSQL = WSQL||'WHERE G.BDCODMATRIZ = '||:PRCODEMPMATRIZ||' ';
  ELSE
    WSQL = WSQL||'WHERE G.BDCODMATRIZ = '||:PRCODEMP||' ';
  wSQL = wSQL||  'AND g.bdREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||  'AND g.bdCODQUADRO = '||:wCODQUADRO||' ';
  wSQL = wSQL||  'AND G.BDRETIFICADORA = '||:PRRETIFICADORA||' ';
  wSQL = wSQL||  'AND g.bdNUMCAMPO  = 03 '; -- VL_TOT_CRED_DESC - Valor do Crédito Descontado
  wSQL = wSQL||  'AND c.bdFORMULA IS NULL '; -- Para não carregar as contas detalhadas
  wSQL = wSQL||  ' AND ('||wSQLAUX||') > 0 ';

  EXECUTE STATEMENT wSQL;


  /*Pegar valores negativos e descontar dos créditos que serão lançados - Contabilização - Bloco M #123847
  Quando separava por tipo de crédito e multiplicava - Ele dava 1739,96
  Mas quando pegava a soma dos tipos de crédito e multiplicava - Ele dava 1739,95
  Isso dava uma diferença de uma centavo na contabilização, para não mexer nos registros
  vamos descontar esse 0,01 centavo do primeiro tipo que encontrar */
  IF (:prDEBCRED = '') THEN
     BEGIN
       FOR
         select G.BDCODMATRIZ, (coalesce(M1100.BDSLD_CRED_FIM, 0) + coalesce(G.BDVALOR, 0) - coalesce((select sum(O.BDVALOR)
                                                                                                            from TMP_TCONF_CONTAS_ONLINE_TEMP O
                                                                                                            where O.BDCODPLAPADRAO = C.BDCODPLAPADRAO and
                                                                                                                  O.BDCODITEMONLINE = :WCODITEMONLINE and
                                                                                                                  O.BDCODMATRIZ = G.BDCODMATRIZ and
                                                                                                                  O.BDREFERENCIA = G.BDREFERENCIA and
                                                                                                                  O.BDFORMULA is not null and
                                                                                                                  O.BDVALOR > 0), 0)) as BDVALOR
         from VEF_EMP_TBLOCOMGERREG G
         join VW_TEMPRESAS_REF R on (R.BDCODEMP = G.BDCODEMP)
         join TMP_TCONF_CONTAS_ONLINE_TEMP C on (C.BDCODPLAPADRAO = R.BDCODPLAPADRAO and C.BDCODITEMONLINE = :WCODITEMONLINE)
         left outer join(select SLD.BDCODPERIODO, SLD.BDCODMATRIZ, SLD.BDREFERENCIA, SLD.BDCODQUADRO,
                                sum(coalesce(SLD.BDSLD_CRED_FIM, 0)) as BDSLD_CRED_FIM, SLD.BDRETIFICADORA
                         from VEF_EMP_TBLOCOM1100_1500 SLD
                         where ((SLD.BDCODMATRIZ = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'FALSE')
                                 OR (SLD.BDCODEMP = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'TRUE')) and
                               SLD.BDREFERENCIA = :PRREFERENCIA and
                               SLD.BDPER_APU_CRED = :PRREFERENCIA and
                               SLD.BDCODQUADRO = :wCODQUADROSALDO AND
                               SLD.BDRETIFICADORA = :PRRETIFICADORA
                         group by SLD.BDCODPERIODO, SLD.BDCODMATRIZ, SLD.BDREFERENCIA, SLD.BDCODQUADRO, SLD.BDRETIFICADORA) M1100 on (M1100.BDCODPERIODO = G.BDCODPERIODO and M1100.BDCODMATRIZ = G.BDCODMATRIZ and M1100.BDREFERENCIA = G.BDREFERENCIA AND M1100.BDRETIFICADORA = G.BDRETIFICADORA)
         where IIF(:PRCONTABILIZAFILIAL = 'FALSE',G.BDCODMATRIZ,G.BDCODEMP) = :PRCODEMPMATRIZ AND
               G.BDREFERENCIA = :PRREFERENCIA and
               G.BDCODQUADRO = :wCODQUADRO and
               G.BDNUMCAMPO = 03 and
               G.BDRETIFICADORA = :PRRETIFICADORA AND
               C.BDFORMULA is null and
               (coalesce(M1100.BDSLD_CRED_FIM, 0) + coalesce(G.BDVALOR, 0) - coalesce((select sum(O.BDVALOR)
                                                                                       from TMP_TCONF_CONTAS_ONLINE_TEMP O
                                                                                       where O.BDCODPLAPADRAO = C.BDCODPLAPADRAO and
                                                                                             O.BDCODITEMONLINE = :WCODITEMONLINE and
                                                                                             O.BDCODMATRIZ = G.BDCODMATRIZ and
                                                                                             O.BDREFERENCIA = G.BDREFERENCIA and
                                                                                             O.BDFORMULA is not null and
                                                                                             O.BDVALOR > 0), 0)) < 0
          INTO :WCODEMP,:WVALOR
    
       DO
        BEGIN
          IF ((:WVALOR < 0) AND (:WVALOR > -0.05)) THEN
            BEGIN
              FOR   /*Pega o primeiro tipo de crédito que encontrar*/
                  SELECT FIRST 1 T.BDORDENACAO
                  FROM TMP_TCONF_CONTAS_ONLINE_TEMP t
                  WHERE t.bdCODITEMONLINE IN (:WCODITEMONLINE) -- "Créditos" e "Débitos"...
                  AND t.bdFORMULA IS NOT NULL
                  AND t.bdVALOR > 0
                  ORDER BY t.bdCODMATRIZ, t.bdREFERENCIA, t.bdORDENACAO
                  INTO :WORDENACAO
              DO
                BEGIN
                  UPDATE TMP_TCONF_CONTAS_ONLINE_TEMP t
                  SET T.BDVALOR = T.BDVALOR + :WVALOR
                  WHERE T.BDCODMATRIZ = :PRCODEMP
                  AND T.BDFORMULA IS NOT NULL
                  AND T.BDVALOR > 0
                  AND T.BDREFERENCIA = :PRREFERENCIA
                  AND T.BDCODITEMONLINE = :WCODITEMONLINE
                  AND T.BDORDENACAO = :WORDENACAO;
                END
            END
        END
     END

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRTIPO VARCHAR(6),
    PRDEBCRED VARCHAR(5) = '',
    PRRETIFICADORA INTEGER = 0,
    PRTIPO2 VARCHAR(20) = '',
    PRCONTABILIZAFILIAL DM_BOOLEAN = FALSE)
AS
DECLARE VARIABLE WCODINC INTEGER;
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCONTDETALHADA VARCHAR(5);
DECLARE VARIABLE WSQL VARCHAR(10000);
DECLARE VARIABLE WSQLAUX VARCHAR(10000);
DECLARE VARIABLE WCODQUADRO INTEGER;
DECLARE VARIABLE WCODITEMONLINE INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WVALOR NUMERIC(15,2);
DECLARE VARIABLE WORDENACAO VARCHAR(5000);
DECLARE VARIABLE WCODITEMONLINERECEITAFIN INTEGER;
declare variable WCODEMPSQL varchar(20);
declare variable WCAMPOVALOR varchar(13);
declare variable WTABLEVALOR varchar(23);
BEGIN
  IF (UPPER(:prTIPO) = 'PIS') THEN
    BEGIN
      WCODQUADRO      = 15; -- M200 - Consolidação da contribuição para o PIS/PASEP
      WCODITEMONLINERECEITAFIN = 638;
      IF (:PRRETIFICADORA = 0) THEN
      BEGIN
      WCODITEMONLINE  = 248;
    END
  ELSE
      IF (:PRRETIFICADORA = 1) THEN
      BEGIN
        IF (:PRTIPO2 = ' a pagar') THEN
            WCODITEMONLINE = 533;
        ELSE
            WCODITEMONLINE  = 534;
      END
    END
  ELSE
  IF (UPPER(:prTIPO) = 'COFINS') THEN
    BEGIN
      WCODQUADRO      = 33; -- M600 - Consolidação da contribuição para o Cofins          
      WCODITEMONLINERECEITAFIN = 639;
      IF (:PRRETIFICADORA = 0) THEN
      BEGIN
      WCODITEMONLINE  = 252;
    END
      ELSE
      IF (:PRRETIFICADORA = 1) THEN
      BEGIN
        IF (:PRTIPO2 = ' a pagar') THEN
            WCODITEMONLINE = 535;
        ELSE
            WCODITEMONLINE  = 536;
      END
    END

  IF (PRCONTABILIZAFILIAL = 'TRUE') THEN
  BEGIN
    WCODEMPSQL = 'BDCODEMP';
    WCAMPOVALOR = 'BDVL_CONT_PER';
    WTABLEVALOR = 'VEF_EMP_TBLOCOM210_M610';
  END
  ELSE
  BEGIN
    WCODEMPSQL  = 'BDCODMATRIZ';
    WCAMPOVALOR = 'BDVALOR';
    WTABLEVALOR = 'VEF_EMP_TBLOCOMGERREG';
  END

  IF (:prDEBCRED <> '') THEN
    BEGIN
      IF (:PRRETIFICADORA = 1) THEN
        wSQLAUX =                         'ABS((COALESCE((SELECT SUM(COALESCE(t.bdVALOR, 0)) ';
      ELSE
      wSQLAUX =                         '(COALESCE((SELECT SUM(COALESCE(t.bdVALOR, 0)) ';
      wSQLAUX = wSQLAUX||                           'FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t ';
      wSQLAUX = wSQLAUX||                           'WHERE t.bdCODMATRIZ = g.'||:WCODEMPSQL||' ';
      wSQLAUX = wSQLAUX||                             'AND t.bdREFERENCIA = g.bdREFERENCIA ';
      wSQLAUX = wSQLAUX||                             'AND t.bdCODPLAPADRAO = c.bdCODPLAPADRAO ';
      wSQLAUX = wSQLAUX||                             'AND POSITION('''||:wCODITEMONLINE||''', t.bdORDENACAO) > 0 ';
      wSQLAUX = wSQLAUX||                             'AND ((POSITION(''.00000'', t.bdORDENACAO) = 0) ';
      IF (UPPER(:prDEBCRED) = 'DEB') THEN
        wSQLAUX = wSQLAUX||                   'AND t.bdDEBITO IS NULL)),0)) ';
      ELSE
      IF (UPPER(:prDEBCRED) = 'CRED') THEN
        wSQLAUX = wSQLAUX||                   'AND t.bdCREDITO IS NULL)),0)) ';
    END
  ELSE
    BEGIN
      IF (:PRRETIFICADORA = 1) THEN
        wSQLAUX =          'ABS(COALESCE(COALESCE(g.bdVALOR,0)-COALESCE((SELECT SUM(o.bdVALOR) ';
      ELSE
      wSQLAUX =          'COALESCE(COALESCE(g.bdVALOR,0)-COALESCE((SELECT SUM(o.bdVALOR) ';
      wSQLAUX = wSQLAUX||                                         'FROM TMP_TCONF_CONTAS_ONLINE_TEMP o ';
      wSQLAUX = wSQLAUX||                                         'WHERE o.bdCODPLAPADRAO = c.bdCODPLAPADRAO ';
      wSQLAUX = wSQLAUX||                                           'AND o.bdCODITEMONLINE = '||:wCODITEMONLINE||' ';
      wSQLAUX = wSQLAUX||                                           'AND o.bdCODMATRIZ = g.'||:WCODEMPSQL||' ';
      wSQLAUX = wSQLAUX||                                           'AND o.bdREFERENCIA = g.bdREFERENCIA ';
      wSQLAUX = wSQLAUX||                                           'AND o.bdFORMULA IS NOT NULL ';
      wSQLAUX = wSQLAUX||                                           'AND o.bdVALOR > 0),0)';
           
      wSQLAUX = wSQLAUX||         ' - COALESCE((SELECT first 1 G.bdvlrreceitafinanceira ';
      wSQLAUX = wSQLAUX||                                         'FROM TMP_TCONF_CONTAS_ONLINE_TEMP o ';
      wSQLAUX = wSQLAUX||                                         'WHERE o.bdCODPLAPADRAO = c.bdCODPLAPADRAO ';
      wSQLAUX = wSQLAUX||                                           'AND o.bdCODITEMONLINE = '||:WCODITEMONLINERECEITAFIN||' ';
      wSQLAUX = wSQLAUX||                                           'AND o.bdCODMATRIZ = g.'||:WCODEMPSQL||' ';
      wSQLAUX = wSQLAUX||                                           'AND o.bdREFERENCIA = g.bdREFERENCIA ';
      wSQLAUX = wSQLAUX||                                           ' ),0),0)';
    END

  wSQL =       'INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODHIST, bdCODTPHI, bdORDENACAO) ';
  wSQL = wSQL||'SELECT g.'||:WCODEMPSQL||', g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, ';
  IF (:prDEBCRED <> '') THEN
    BEGIN
      IF (UPPER(:prDEBCRED) = 'DEB') THEN
        wSQL = wSQL||'c.bdCONTADEBPROV as bdDEBITO, NULL as bdCREDITO, ';
      ELSE
      IF (UPPER(:prDEBCRED) = 'CRED') THEN
        wSQL = wSQL||'NULL as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO, ';
    END
  ELSE
    wSQL = wSQL||'c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO, ';
  --wSQL = wSQL||'      ''Valor de '||:prTIPO||' Débito - Ref:''||substring(g.bdREFERENCIA FROM 5 for 2)||''/''||substring(g.bdREFERENCIA FROM 1 for 4) as bdCOMPL, NULL as bdDATA, ';
  wSQL = wSQL||      '       CASE WHEN ch.bdCOMPLEMENTO IS NOT NULL THEN REPLACE( ';
  wSQL = wSQL||      '                                                   REPLACE( ';
  wSQL = wSQL||      '                                                   REPLACE(ch.bdCOMPLEMENTO, ';
  wSQL = wSQL||      '                                                           ''*MES'', SUBSTRING(g.bdREFERENCIA FROM 5 for 2)), ';
  wSQL = wSQL||      '                                                           ''*ANO'', SUBSTRING(g.bdREFERENCIA FROM 1 for 4)), ';
  wSQL = wSQL||      '                                                           ''*REF'', SUBSTRING(g.bdREFERENCIA FROM 5 for 2)||''/''||SUBSTRING(g.bdREFERENCIA FROM 1 for 4)) ';
  wSQL = wSQL||      '         ELSE ''Valor de '||:prTIPO||PRTIPO2||' - Ref:''||CAST(substring(g.bdREFERENCIA FROM 5 for 2)||''/''||substring(g.bdREFERENCIA FROM 1 for 4) AS VARCHAR(7)) ';
  wSQL = wSQL||      '       END as bdCOMPL, NULL as bdDATA, ';
  wSQL = wSQL||       wSQLAUX;
  IF (:PRRETIFICADORA = 1) THEN
  BEGIN
    wSQL = wSQL||' - COALESCE((SELECT RET.BDVALOR FROM VEF_EMP_TBLOCOMGERREG RET ';
    wSQL = wSQL||'             WHERE RET.BDCODMATRIZ = '||:PRCODEMP||' AND ';
    wSQL = wSQL||'                   RET.BDREFERENCIA = '||:prREFERENCIA||' AND ';
    wSQL = wSQL||'                   RET.BDRETIFICADORA = 0 AND ';
    wSQL = wSQL||'                   RET.BDCODQUADRO = '||wCodQuadro;
    IF ((UPPER(:prTIPO) = 'PIS') OR (UPPER(:prTIPO) = 'COFINS')) THEN
        wSQL = wSQL||'           AND RET.BDNUMCAMPO = 13), 0)) ';
  END
  wSQL = wSQL||'      ,100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, ''TRUE'' bdTRANFECHADA, c.bdCODHIST, c.bdCODTPHI, c.bdORDENACAO ';
    --05/09/2023 - Camilla M. - Contabilização separada para filial
  wSQL = wSQL||      'FROM (';
  wSQL = wSQL||             'SELECT G.BDCODEMP,G.BDCODMATRIZ, G.BDREFERENCIA, SUM('||:WCAMPOVALOR||') BDVALOR, SUM(G.BDVLRRECEITAFINANCEIRA) BDVLRRECEITAFINANCEIRA ';
  wSQL = wSQL||             'FROM '||:WTABLEVALOR||' g ';
  wSQL = wSQL||             'WHERE g.'||:WCODEMPSQL||' = '||:prCODEMP||' ';
  wSQL = wSQL||'  AND g.bdREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||'  AND G.BDRETIFICADORA = '||:PRRETIFICADORA||' ';
  IF (PRCONTABILIZAFILIAL = 'TRUE') THEN
    BEGIN
    wSQL = wSQL||           '  AND g.bdCODQUADRO = IIF('||wCodQuadro||' = 15,19,37)'; -- M200 - Consolidação da contribuição para o PIS/PASEP
    END
  ELSE
    BEGIN
  wSQL = wSQL||'  AND g.bdCODQUADRO = '||wCodQuadro||' '; -- M200 - Consolidação da contribuição para o PIS/PASEP
  IF (:PRRETIFICADORA = 1) THEN
    BEGIN
        IF ((UPPER(:prTIPO) = 'PIS') OR (UPPER(:prTIPO) = 'COFINS')) THEN
            wSQL = wSQL||' AND G.BDNUMCAMPO = 13';
    END
  ELSE
  wSQL = wSQL||'  AND g.bdNUMCAMPO  = 02 '; -- VL_TOT_CONT_NC_PER - Valor Total da Contribuição Não Cumulativa do Período
    END
  wSQL = wSQL||             '   GROUP BY G.BDCODEMP,G.BDCODMATRIZ, G.BDREFERENCIA';
  wSQL = wSQL||           ') G ';
  wSQL = wSQL||'JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP) ';
  wSQL = wSQL||'JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = '||:wCODITEMONLINE||') ';
  wSQL = wSQL||'LEFT OUTER JOIN TCOMPLEMENTO_HIST ch ON (ch.bdCODCOMPHIST = c.bdCODCOMPHIST) ';
  wSQL = wSQL||'  WHERE c.bdFORMULA IS NULL '; -- Para não carregar as contas detalhadas
  IF (:PRRETIFICADORA = 1) THEN
    wSQL = wSQL||'  AND ('||:wSQLAux||')) > 0; ';
  ELSE
  wSQL = wSQL||'  AND ('||:wSQLAux||') > 0; ';

  EXECUTE STATEMENT wSQL;

  /*Pegar valores negativos e descontar dos créditos que serão lançados - Contabilização - Bloco M #123847
  Quando separava por tipo de crédito e multiplicava - Ele dava 1739,96
  Mas quando pegava a soma dos tipos de crédito e multiplicava - Ele dava 1739,95
  Isso dava uma diferença de uma centavo na contabilização, para não mexer nos registros
  vamos descontar esse 0,01 centavo do primeiro tipo que encontrar */
  IF (:prDEBCRED = '') THEN
     BEGIN
       FOR
         select G.BDCODMATRIZ, coalesce(coalesce(G.BDVALOR, 0)- coalesce((select sum(O.BDVALOR)
                                                                   from TMP_TCONF_CONTAS_ONLINE_TEMP O
                                                                   where O.BDCODPLAPADRAO = C.BDCODPLAPADRAO and
                                                                         O.BDCODITEMONLINE = :wCODITEMONLINE and
                                                                         O.BDCODMATRIZ = G.BDCODMATRIZ and
                                                                         O.BDREFERENCIA = G.BDREFERENCIA and
                                                                         O.BDFORMULA is not null and
                                                                         O.BDVALOR > 0), 0), 0) as BDVALOR
         from VEF_EMP_TBLOCOMGERREG G
         join VW_TEMPRESAS_REF R on (R.BDCODEMP = G.BDCODEMP)
         join TMP_TCONF_CONTAS_ONLINE_TEMP C on (C.BDCODPLAPADRAO = R.BDCODPLAPADRAO and C.BDCODITEMONLINE = :wCODITEMONLINE)
         where ((G.BDCODMATRIZ = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'FALSE')
                OR (G.BDCODEMP = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'TRUE')) and
               G.BDREFERENCIA = :prREFERENCIA and
               G.BDCODQUADRO  = :wCodQuadro and
               G.BDNUMCAMPO   = 02 and
               G.BDRETIFICADORA = :PRRETIFICADORA AND
               C.BDFORMULA is null and
               (coalesce(coalesce(G.BDVALOR, 0) - coalesce((select sum(O.BDVALOR)
                                                            from TMP_TCONF_CONTAS_ONLINE_TEMP O
                                                            where O.BDCODPLAPADRAO = C.BDCODPLAPADRAO and
                                                                  O.BDCODITEMONLINE = :wCODITEMONLINE and
                                                                  O.BDCODMATRIZ = G.BDCODMATRIZ and
                                                                  O.BDREFERENCIA = G.BDREFERENCIA and
                                                                  O.BDFORMULA is not null and
                                                                  O.BDVALOR > 0), 0), 0)) > 0
          INTO :WCODEMP,:WVALOR
    
       DO
        BEGIN
          IF ((:WVALOR < 0) AND (:WVALOR > -0.05)) THEN
            BEGIN
              FOR   /*Pega o primeiro tipo de crédito que encontrar*/
                  SELECT FIRST 1 T.BDORDENACAO
                  FROM TMP_TCONF_CONTAS_ONLINE_TEMP t
                  WHERE t.bdCODITEMONLINE IN (:WCODITEMONLINE) -- "Créditos" e "Débitos"...
                  AND t.bdFORMULA IS NOT NULL
                  AND t.bdVALOR > 0
                  ORDER BY t.bdCODMATRIZ, t.bdREFERENCIA, t.bdORDENACAO
                  INTO :WORDENACAO
              DO
                BEGIN
                  UPDATE TMP_TCONF_CONTAS_ONLINE_TEMP t
                  SET T.BDVALOR = T.BDVALOR + :WVALOR
                  WHERE T.BDCODMATRIZ = :PRCODEMP
                  AND T.BDFORMULA IS NOT NULL
                  AND T.BDVALOR > 0
                  AND T.BDREFERENCIA = :PRREFERENCIA
                  AND T.BDCODITEMONLINE = :WCODITEMONLINE
                  AND T.BDORDENACAO = :WORDENACAO;
                END
            END
        END
     END
END^

create or alter procedure SP_APURACAO_BLOCOM_ONLINE_CONSO (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRRETIFICADORA integer,
    PRCONTABILIZAFILIAL DM_BOOLEAN,
    PRCODEMPMATRIZ integer)
as
declare variable WINCTRIB integer;
declare variable WCONTDETALHADA varchar(5);
declare variable WCODINC integer;
declare variable WCODQUADRO integer;
declare variable WNUMCAMPO integer;
declare variable WVALOR DM_NUMERIC_15_2;
declare variable WVALORAUX DM_NUMERIC_15_2;
declare variable WAJUPAGARPIS DM_BOOLEAN;
declare variable WAJURECUPERARPIS DM_BOOLEAN;
declare variable WAJUPAGARCOFINS DM_BOOLEAN;
declare variable WAJURECUPERARCOFINS DM_BOOLEAN;
BEGIN
  :WAJUPAGARPIS = 'FALSE';
  :WAJURECUPERARPIS = 'FALSE';
  :WAJUPAGARCOFINS = 'FALSE';
  :WAJURECUPERARCOFINS = 'FALSE';

  IF (:PRRETIFICADORA = 1) THEN
  BEGIN
    FOR SELECT
          REG.BDCODQUADRO, REG.BDNUMCAMPO, REG.BDVALOR
      FROM
          VEF_EMP_TBLOCOMGERREG REG
      WHERE REG.BDCODPERIODO = 7 AND
            REG.BDCODEMP = :PRCODEMP AND
            REG.BDREFERENCIA = :PRREFERENCIA AND
            REG.BDRETIFICADORA = :PRRETIFICADORA AND
            REG.BDCODQUADRO IN (15, 33) AND
            REG.BDNUMCAMPO = 13
      ORDER BY REG.BDCODEMP, REG.BDREFERENCIA, REG.BDCODQUADRO, REG.BDNUMCAMPO
      INTO WCODQUADRO, WNUMCAMPO, WVALOR
      DO
      BEGIN
        -- PIS -> Valor da contribuição a recolher no período
        IF ((WCODQUADRO = 15) AND (WNUMCAMPO = 13)) THEN
        BEGIN
            SELECT FIRST 1
                BDVALOR
            FROM
                VEF_EMP_TBLOCOMGERREG
            WHERE BDCODPERIODO = 7 AND
                  BDCODEMP = :PRCODEMP AND
                  BDREFERENCIA = :PRREFERENCIA AND
                  BDRETIFICADORA = 0 AND
                  BDCODQUADRO = :WCODQUADRO AND
                  BDNUMCAMPO = :WNUMCAMPO
            INTO WVALORAUX;

            IF (WVALOR > WVALORAUX) THEN
            BEGIN
                :WAJUPAGARPIS = 'TRUE';
            END
            ELSE
            IF (WVALOR < WVALORAUX) THEN
            BEGIN
                :WAJURECUPERARPIS = 'TRUE';
            END
        END
        ELSE
        -- COFINS -> Valor da contribuição a recolher no período
        IF ((WCODQUADRO = 33) AND (WNUMCAMPO = 13)) THEN
        BEGIN
            SELECT FIRST 1
                BDVALOR
            FROM
                VEF_EMP_TBLOCOMGERREG
            WHERE BDCODPERIODO = 7 AND
                  BDCODEMP = :PRCODEMP AND
                  BDREFERENCIA = :PRREFERENCIA AND
                  BDRETIFICADORA = 0 AND
                  BDCODQUADRO = :WCODQUADRO AND
                  BDNUMCAMPO = :WNUMCAMPO
            INTO WVALORAUX;

            IF (WVALOR > WVALORAUX) THEN
            BEGIN
                :WAJUPAGARCOFINS = 'TRUE';
            END
            ELSE
            IF (WVALOR < WVALORAUX) THEN
            BEGIN
                :WAJURECUPERARCOFINS = 'TRUE';
            END
        END
      END
  END

  IF (:PRRETIFICADORA = 0) THEN
  BEGIN
  /* PIS */
  /****************************************************************************/
  /********************************** Créditos ********************************/
    -- "Crédito Principal"
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP,:PRCODEMPMATRIZ, :prREFERENCIA, 'PIS', '', :PRRETIFICADORA, ' Crédito',:PRCONTABILIZAFILIAL);
    -- "Crédito Detalhada"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 247);
    -- "Diferenças de Débito"
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP,:PRCODEMPMATRIZ, :prREFERENCIA, 'PIS', 'DEB', :PRRETIFICADORA, ' Crédito',:PRCONTABILIZAFILIAL);
    -- "Diferenças de Crédito"
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP,:PRCODEMPMATRIZ, :prREFERENCIA, 'PIS', 'CRED', :PRRETIFICADORA, ' Crédito',:PRCONTABILIZAFILIAL);
    /********************************** Débitos *********************************/
    -- "Débito Principal"
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS', '', :PRRETIFICADORA, ' Débito',:PRCONTABILIZAFILIAL);
    -- "Débito Detalhado"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 248);
    -- "Diferenças de Débito"
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS', 'DEB', :PRRETIFICADORA, ' Débito',:PRCONTABILIZAFILIAL);
    -- "Diferenças de Crédito"
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS', 'CRED', :PRRETIFICADORA, ' Débito',:PRCONTABILIZAFILIAL);
  END
  ELSE
  IF (:PRRETIFICADORA = 1) THEN
  BEGIN
      /* PIS */
      /****************************************************************************/
      /********************************** A pagar ********************************/
      IF (WAJUPAGARPIS = 'TRUE') THEN
      BEGIN
        -- Verifica se possui alguma inconsistência de contas online...
        SELECT FIRST 1 I.BDCODINC
        FROM VEF_INCON_BLOCOM I
        WHERE I.BDCODMATRIZ = :PRCODEMP
          AND I.BDREFERENCIA = :PRREFERENCIA
          AND I.BDRETIFICADORA = :PRRETIFICADORA
          AND I.BDCODINC IN (27/*Ajuste a pagar PIS*/, 29/*Ajuste a pagar COFINS*/)
        INTO :WCODINC;

        IF (WCODINC IS NULL) THEN
            BEGIN
              -- "Ajuste a pagar"
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS', '', :PRRETIFICADORA, ' a pagar',:PRCONTABILIZAFILIAL);
              -- "Ajuste a pagar Detalhada"
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 533);
              -- "Diferenças de Débito"
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS', 'DEB', :PRRETIFICADORA, ' a pagar',:PRCONTABILIZAFILIAL);
              -- "Diferenças de Crédito"
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS', 'CRED', :PRRETIFICADORA, ' a pagar',:PRCONTABILIZAFILIAL);
            END
      END
      /********************************** A recuperar *********************************/
      ELSE
      IF (WAJURECUPERARPIS = 'TRUE') THEN
      BEGIN
        -- Verifica se possui alguma inconsistência de contas online...
        SELECT FIRST 1 I.BDCODINC
        FROM VEF_INCON_BLOCOM I
        WHERE I.BDCODMATRIZ = :PRCODEMP
          AND I.BDREFERENCIA = :PRREFERENCIA
          AND I.BDRETIFICADORA = :PRRETIFICADORA
          AND I.BDCODINC IN (28/*Ajuste a recuperar PIS*/, 30 /*Ajuste a recuperar COFINS*/)
        INTO :WCODINC;

        IF (WCODINC IS NULL) THEN
            BEGIN
              -- "Ajuste a recuperar Principal"
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS', '', :PRRETIFICADORA, ' a recuperar',:PRCONTABILIZAFILIAL);
              -- "Ajuste a recuperar Detalhado"
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 534);
              -- "Diferenças de Débito"
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS', 'DEB', :PRRETIFICADORA, ' a recuperar',:PRCONTABILIZAFILIAL);
              -- "Diferenças de Crédito"
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'PIS', 'CRED', :PRRETIFICADORA, ' a recuperar',:PRCONTABILIZAFILIAL);
            END
      END
  END
  -- "Outras Deduções"
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODHIST, bdCODTPHI, bdORDENACAO)
  SELECT IIF(:PRCONTABILIZAFILIAL = 'FALSE',g.bdCODMATRIZ, G.BDCODEMP), g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
         CASE WHEN ch.bdCOMPLEMENTO IS NOT NULL THEN REPLACE(
                                                     REPLACE(
                                                     REPLACE(ch.bdCOMPLEMENTO,
                                                             '*MES', SUBSTRING(g.bdREFERENCIA FROM 5 for 2)),
                                                             '*ANO', SUBSTRING(g.bdREFERENCIA FROM 1 for 4)),
                                                             '*REF', SUBSTRING(g.bdREFERENCIA FROM 5 for 2)||'/'||SUBSTRING(g.bdREFERENCIA FROM 1 for 4))
         ELSE 'Valor de PIS Outras Deduções - Ref:'||CAST(substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) AS VARCHAR(7))
         END as bdCOMPL,
         NULL as bdDATA, g.bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, 'TRUE' bdTRANFECHADA, c.bdCODHIST, c.bdCODTPHI, c.bdORDENACAO
  FROM VEF_EMP_TBLOCOMGERREG g
  JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
  JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 249)
  LEFT OUTER JOIN TCOMPLEMENTO_HIST ch ON (ch.bdCODCOMPHIST = c.bdCODCOMPHIST)
  WHERE ((G.BDCODMATRIZ = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'FALSE')
         OR (G.BDCODEMP = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'TRUE'))
    AND g.bdREFERENCIA = :prREFERENCIA
    AND G.BDRETIFICADORA = :PRRETIFICADORA
    AND g.bdCODQUADRO = 15 -- M200 - Consolidação da contribuição para o PIS/PASEP
    AND g.bdNUMCAMPO  = 07 -- VL_OUT_DED_NC - Outras Deduções no Período
    AND g.bdVALOR > 0;

  -- "Compensação"
  --Compensação de filial separado precisamos buscar os valores e calcular
  IF (:PRCONTABILIZAFILIAL = 'TRUE') THEN
  BEGIN
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODHIST, bdCODTPHI, bdORDENACAO)
     SELECT G.BDCODEMP, :PRREFERENCIA,NULL AS BDCHAVE, C.BDCODPLAPADRAO, NULL AS BDCODUSU, C.BDCONTADEBPROV AS BDDEBITO, C.BDCONTACREDPROV AS BDCREDITO,
     CASE WHEN CH.BDCOMPLEMENTO IS NOT NULL THEN REPLACE(
                                                 REPLACE(
                                                 REPLACE(CH.BDCOMPLEMENTO,
                                                         '*MES', SUBSTRING(:PRREFERENCIA FROM 5 FOR 2)),
                                                         '*ANO', SUBSTRING(:PRREFERENCIA FROM 1 FOR 4)),
                                                         '*REF', SUBSTRING(:PRREFERENCIA FROM 5 FOR 2)||'/'||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4))
     ELSE 'Valor de PIS Compensação - Ref:'||CAST(SUBSTRING(:PRREFERENCIA FROM 5 FOR 2)||'/'||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4) AS VARCHAR(7))
     END AS BDCOMPL,
     NULL AS BDDATA,G.BDVALOR, 100 AS BDTIPOLAN, NULL AS BDDCTO, NULL AS BDTRANSACAO, 'TRUE' BDTRANFECHADA, C.BDCODHIST, C.BDCODTPHI, C.BDORDENACAO
         FROM (
             SELECT BDCODEMP, IIF((SUM(BDVLRDEBITO) - (SUM(BDVLRCREDITO) + SUM(BDVLRRETENCAO))) > 0,SUM(BDVLRCREDITO),SUM(BDVLRDEBITO)) BDVALOR FROM
             (
              SELECT M.BDCODEMP, 0 BDVLRDEBITO, SUM(COALESCE(M.BDVL_CRED_APU, 0)) BDVLRCREDITO, 0 BDVLRRETENCAO
              FROM VEF_EMP_TBLOCOM1100_1500 M
              WHERE (M.BDCODQUADRO = 52) -- 1100 - CONTROLE DE CRÉDITOS FISCAIS PIS/PASEP | 1500 - CONTROLE DE CRÉDITOS FISCAIS COFINS
                AND M.BDCODEMP = :PRCODEMP
                AND (M.BDREFERENCIA = :PRREFERENCIA)
                AND (M.BDRETIFICADORA = :PRRETIFICADORA)
              GROUP BY M.BDCODEMP
              UNION ALL
              SELECT G.BDCODEMP,SUM(BDVL_CONT_PER) BDVLRDEBITO, 0 BDVLRCREDITO, 0 BDVLRRETENCAO
              FROM VEF_EMP_TBLOCOM210_M610 G
              WHERE G.BDCODEMP = :PRCODEMP
                AND G.BDREFERENCIA = :PRREFERENCIA
                AND G.BDRETIFICADORA = :PRRETIFICADORA
                AND G.BDCODQUADRO = 19
              GROUP BY G.BDCODEMP, G.BDREFERENCIA
              UNION ALL
              SELECT BDCODEMP, 0 BDVLRDEBITO, 0 BDVLRCREDITO, SUM(M.BDVLRPIS) BDVLRRETENCAO
              FROM VEF_EMP_TORIDEDF700 M
              WHERE M.BDINDNATDED = 1 -- 0 - DEDUÇÃO DE NATUREZA NÃO CUMULATIVA
              AND M.BDCODEMP = :PRCODEMP
              AND M.BDREFERENCIA = :PRREFERENCIA
              GROUP BY BDCODEMP
              UNION ALL
              SELECT M.BDCODEMP, 0 BDVLRDEBITO, 0 BDVLRCREDITO, COALESCE(M.BDSLD_RET, 0) BDVLRRETENCAO
              FROM VEF_EMP_TBLOCOM1300_1700 M
              WHERE (M.BDCODQUADRO = 49) -- 1300 - FICHA DE RETENÇÃO DO PIS/PASEP | 1700 - FICHA DE RETENÇÃO DO COFINS
                AND M.BDCODEMP = :PRCODEMP
                AND M.BDREFERENCIA = :PRREFERENCIA
                AND M.BDRETIFICADORA = :PRRETIFICADORA
             )
             GROUP BY BDCODEMP
         )  G
       JOIN VW_TEMPRESAS_REF R ON (R.BDCODEMP = G.BDCODEMP)
       JOIN TMP_TCONF_CONTAS_ONLINE_TEMP C ON (C.BDCODPLAPADRAO = R.BDCODPLAPADRAO AND C.BDCODITEMONLINE = 250)
       LEFT OUTER JOIN TCOMPLEMENTO_HIST CH ON (CH.BDCODCOMPHIST = C.BDCODCOMPHIST)
       WHERE G.BDVALOR > 0;
  END
  ELSE
    BEGIN
      INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODHIST, bdCODTPHI, bdORDENACAO)
      SELECT IIF(:PRCONTABILIZAFILIAL = 'FALSE',g.bdCODMATRIZ, G.BDCODEMP), g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
         CASE WHEN ch.bdCOMPLEMENTO IS NOT NULL THEN REPLACE(
                                                     REPLACE(
                                                     REPLACE(ch.bdCOMPLEMENTO,
                                                             '*MES', SUBSTRING(g.bdREFERENCIA FROM 5 for 2)),
                                                             '*ANO', SUBSTRING(g.bdREFERENCIA FROM 1 for 4)),
                                                             '*REF', SUBSTRING(g.bdREFERENCIA FROM 5 for 2)||'/'||SUBSTRING(g.bdREFERENCIA FROM 1 for 4))
             ELSE 'Valor de PIS Compensação - Ref:'||CAST(substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) AS VARCHAR(7))
         END as bdCOMPL,
         NULL as bdDATA, SUM(g.bdVALOR) as bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, 'TRUE' bdTRANFECHADA, c.bdCODHIST, c.bdCODTPHI, c.bdORDENACAO
  FROM VEF_EMP_TBLOCOMGERREG g
  JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
  JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 250)
  LEFT OUTER JOIN TCOMPLEMENTO_HIST ch ON (ch.bdCODCOMPHIST = c.bdCODCOMPHIST)
      WHERE ((G.BDCODMATRIZ = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'FALSE')
             OR (G.BDCODEMP = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'TRUE'))
    AND g.bdREFERENCIA = :prREFERENCIA
    AND G.BDRETIFICADORA = :PRRETIFICADORA
    AND g.bdCODQUADRO = 15 -- M200 - Consolidação da contribuição para o PIS/PASEP
    AND (
         (g.bdNUMCAMPO  = 03) OR -- VL_TOT_CRED_DESC - Valor do Crédito Descontado
                 (g.bdNUMCAMPO  = 04) OR -- VL_TOT_CRED_DESC_ANT - Valor do Crédito Descontado, Apurado em Período de Apuração Anterior
                 (g.bdNUMCAMPO  = 06) OR -- VL_RET_NC - Valor Retido na Fonte Deduzido no Período
                 (g.bdNUMCAMPO  = 07)    -- VL_OUT_DED_NC - Outras Deduções no Período
                 )
            AND g.bdVALOR > 0
      GROUP BY IIF(:PRCONTABILIZAFILIAL = 'FALSE',g.bdCODMATRIZ, G.BDCODEMP), g.bdREFERENCIA, c.bdCODPLAPADRAO, c.bdCONTADEBPROV, c.bdCONTACREDPROV, c.bdCODHIST, c.bdCODTPHI, ch.bdCOMPLEMENTO, c.bdORDENACAO;
    END


  -- "Receita financeira"
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODHIST, bdCODTPHI, bdORDENACAO)
  SELECT IIF(:PRCONTABILIZAFILIAL = 'FALSE',g.bdCODMATRIZ, G.BDCODEMP), g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
         CASE WHEN ch.bdCOMPLEMENTO IS NOT NULL THEN REPLACE(
                                                     REPLACE(
                                                     REPLACE(ch.bdCOMPLEMENTO,
                                                             '*MES', SUBSTRING(g.bdREFERENCIA FROM 5 for 2)),
                                                             '*ANO', SUBSTRING(g.bdREFERENCIA FROM 1 for 4)),
                                                             '*REF', SUBSTRING(g.bdREFERENCIA FROM 5 for 2)||'/'||SUBSTRING(g.bdREFERENCIA FROM 1 for 4))
         ELSE 'Valor de PIS Débito Receita Financeira - Ref:'||CAST(substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) AS VARCHAR(7))
         END as bdCOMPL,
         NULL as bdDATA, SUM(g.bdvlrreceitafinanceira) as bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, 'TRUE' bdTRANFECHADA, c.bdCODHIST, c.bdCODTPHI, c.bdORDENACAO
  FROM VEF_EMP_TBLOCOMGERREG g
  JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
  JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 638)
  LEFT OUTER JOIN TCOMPLEMENTO_HIST ch ON (ch.bdCODCOMPHIST = c.bdCODCOMPHIST)
  WHERE ((G.BDCODMATRIZ = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'FALSE')
         OR (G.BDCODEMP = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'TRUE'))
    AND g.bdREFERENCIA = :prREFERENCIA
    AND G.BDRETIFICADORA = :PRRETIFICADORA
    AND g.bdCODQUADRO = 15 -- M200 - Consolidação da contribuição para o PIS/PASEP
    AND (
         (g.bdNUMCAMPO  = 02)
                 )
            AND g.bdvlrreceitafinanceira > 0
  GROUP BY IIF(:PRCONTABILIZAFILIAL = 'FALSE',g.bdCODMATRIZ, G.BDCODEMP), g.bdREFERENCIA, c.bdCODPLAPADRAO, c.bdCONTADEBPROV, c.bdCONTACREDPROV, c.bdCODHIST, c.bdCODTPHI, ch.bdCOMPLEMENTO, c.bdORDENACAO;
  /****************************************************************************/
  IF (:PRRETIFICADORA = 0) THEN
  BEGIN
  /****************************************************************************/
  /********************************** Créditos ********************************/
  /* Cofins */
    -- "Crédito Principal"
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP,:PRCODEMPMATRIZ, :prREFERENCIA, 'Cofins', '', :PRRETIFICADORA, ' Crédito',:PRCONTABILIZAFILIAL);
    -- "Crédito Detalhada"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 251);
    -- "Diferenças de Débito"
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP,:PRCODEMPMATRIZ, :prREFERENCIA, 'Cofins', 'DEB', :PRRETIFICADORA, ' Crédito',:PRCONTABILIZAFILIAL);
    -- "Diferenças de Crédito"
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CRED (:prCODEMP,:PRCODEMPMATRIZ, :prREFERENCIA, 'Cofins', 'CRED', :PRRETIFICADORA, ' Crédito',:PRCONTABILIZAFILIAL);
    /********************************** Débitos *********************************/
    -- "Débito Principal"
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins', '', :PRRETIFICADORA, ' Débito',:PRCONTABILIZAFILIAL);
    -- "Débito Detalhada"
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 252);
    -- "Diferenças de Débito"
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins', 'DEB', :PRRETIFICADORA, ' Débito',:PRCONTABILIZAFILIAL);
    -- "Diferenças de Crédito"
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins', 'CRED', :PRRETIFICADORA, ' Débito',:PRCONTABILIZAFILIAL);
  END
  ELSE
  IF (:PRRETIFICADORA = 1) THEN
  BEGIN
      /****************************************************************************/
      /********************************** A pagar ********************************/
      /* Cofins */
      IF (WAJUPAGARCOFINS = 'TRUE') THEN
      BEGIN
        -- Verifica se possui alguma inconsistência de contas online...
        SELECT FIRST 1 I.BDCODINC
        FROM VEF_INCON_BLOCOM I
        WHERE I.BDCODMATRIZ = :PRCODEMP
          AND I.BDREFERENCIA = :PRREFERENCIA
          AND I.BDRETIFICADORA = :PRRETIFICADORA
          AND I.BDCODINC IN (27/*Ajuste a pagar PIS*/, 29 /*Ajuste a pagar COFINS*/)
        INTO :WCODINC;

        IF (WCODINC IS NULL) THEN
            BEGIN
              -- "Ajuste a pagar Principal"
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins', '', :PRRETIFICADORA, ' a pagar',:PRCONTABILIZAFILIAL);
              -- "Ajuste a pagar Detalhada"
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 535);
              -- "Diferenças de Débito"
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins', 'DEB', :PRRETIFICADORA, ' a pagar',:PRCONTABILIZAFILIAL);
              -- "Diferenças de Crédito"
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins', 'CRED', :PRRETIFICADORA, ' a pagar',:PRCONTABILIZAFILIAL);
            END
      END
      ELSE
      /********************************** A recuperar *********************************/
      IF (WAJURECUPERARCOFINS = 'TRUE') THEN
      BEGIN
        -- Verifica se possui alguma inconsistência de contas online...
        SELECT FIRST 1 I.BDCODINC
        FROM VEF_INCON_BLOCOM I
        WHERE I.BDCODMATRIZ = :PRCODEMP
          AND I.BDREFERENCIA = :PRREFERENCIA
          AND I.BDRETIFICADORA = :PRRETIFICADORA
          AND I.BDCODINC IN ( 28 /*Ajuste a recuperar PIS*/, 30 /*Ajuste a recuperar COFINS*/)
        INTO :WCODINC;

        IF (WCODINC IS NULL) THEN
            BEGIN
              -- "Ajuste a recuperar Principal"
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins', '', :PRRETIFICADORA, ' a recuperar',:PRCONTABILIZAFILIAL);
              -- "Ajuste a recuperar Detalhada"
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DETAL (:prCODEMP, :prREFERENCIA, 536);
              -- "Diferenças de Débito"
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins', 'DEB', :PRRETIFICADORA, ' a recuperar',:PRCONTABILIZAFILIAL);
              -- "Diferenças de Crédito"
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_DEB (:prCODEMP, :prREFERENCIA, 'Cofins', 'CRED', :PRRETIFICADORA, ' a recuperar',:PRCONTABILIZAFILIAL);
            END
      END
  END
  -- "Outras Deduções"
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODHIST, bdCODTPHI, bdORDENACAO)
  SELECT IIF(:PRCONTABILIZAFILIAL = 'FALSE',g.bdCODMATRIZ, G.BDCODEMP), g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
         CASE WHEN ch.bdCOMPLEMENTO IS NOT NULL THEN REPLACE(
                                                     REPLACE(
                                                     REPLACE(ch.bdCOMPLEMENTO,
                                                             '*MES', SUBSTRING(g.bdREFERENCIA FROM 5 for 2)),
                                                             '*ANO', SUBSTRING(g.bdREFERENCIA FROM 1 for 4)),
                                                             '*REF', SUBSTRING(g.bdREFERENCIA FROM 5 for 2)||'/'||SUBSTRING(g.bdREFERENCIA FROM 1 for 4))
         ELSE 'Valor de Cofins Outras Deduções - Ref:'||CAST(substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) AS VARCHAR(7))
         END as bdCOMPL,
         NULL as bdDATA, g.bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, 'TRUE' bdTRANFECHADA, c.bdCODHIST, c.bdCODTPHI, c.bdORDENACAO
  FROM VEF_EMP_TBLOCOMGERREG g
  JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
  JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 253)
  LEFT OUTER JOIN TCOMPLEMENTO_HIST ch ON (ch.bdCODCOMPHIST = c.bdCODCOMPHIST)
  WHERE ((G.BDCODMATRIZ = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'FALSE')
         OR (G.BDCODEMP = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'TRUE'))
    AND g.bdREFERENCIA = :prREFERENCIA
    AND G.BDRETIFICADORA = :PRRETIFICADORA
    AND g.bdCODQUADRO = 33 -- M600 - Consolidação da contribuição para o Cofins
    AND g.bdNUMCAMPO  = 07 -- VL_OUT_DED_NC - Outras Deduções no Período
    AND g.bdVALOR > 0;

  -- "Compensação"
  IF (:PRCONTABILIZAFILIAL = 'TRUE') THEN
  BEGIN
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODHIST, bdCODTPHI, bdORDENACAO)
    SELECT G.BDCODEMP, :PRREFERENCIA,NULL AS BDCHAVE, C.BDCODPLAPADRAO, NULL AS BDCODUSU, C.BDCONTADEBPROV AS BDDEBITO, C.BDCONTACREDPROV AS BDCREDITO,
    CASE WHEN CH.BDCOMPLEMENTO IS NOT NULL THEN REPLACE(
                                                REPLACE(
                                                REPLACE(CH.BDCOMPLEMENTO,
                                                        '*MES', SUBSTRING(:PRREFERENCIA FROM 5 FOR 2)),
                                                        '*ANO', SUBSTRING(:PRREFERENCIA FROM 1 FOR 4)),
                                                        '*REF', SUBSTRING(:PRREFERENCIA FROM 5 FOR 2)||'/'||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4))
    ELSE 'Valor de Cofins Compensação - Ref:'||CAST(SUBSTRING(:PRREFERENCIA FROM 5 FOR 2)||'/'||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4) AS VARCHAR(7))
    END AS BDCOMPL,
    NULL AS BDDATA,G.BDVALOR, 100 AS BDTIPOLAN, NULL AS BDDCTO, NULL AS BDTRANSACAO, 'TRUE' BDTRANFECHADA, C.BDCODHIST, C.BDCODTPHI, C.BDORDENACAO
        FROM (
            SELECT BDCODEMP, IIF((SUM(BDVLRDEBITO) - (SUM(BDVLRCREDITO) + SUM(BDVLRRETENCAO))) > 0,SUM(BDVLRCREDITO),SUM(BDVLRDEBITO)) BDVALOR FROM
            (
             SELECT M.BDCODEMP, 0 BDVLRDEBITO, SUM(COALESCE(M.BDVL_CRED_APU, 0)) BDVLRCREDITO, 0 BDVLRRETENCAO
             FROM VEF_EMP_TBLOCOM1100_1500 M
             WHERE (M.BDCODQUADRO = 53) -- 1100 - CONTROLE DE CRÉDITOS FISCAIS PIS/PASEP | 1500 - CONTROLE DE CRÉDITOS FISCAIS COFINS
               AND M.BDCODEMP = :PRCODEMP
               AND (M.BDREFERENCIA = :PRREFERENCIA)
               AND (M.BDRETIFICADORA = :PRRETIFICADORA)
             GROUP BY M.BDCODEMP
             UNION ALL
              SELECT G.BDCODEMP,SUM(BDVL_CONT_PER) BDVLRDEBITO, 0 BDVLRCREDITO, 0 BDVLRRETENCAO
              FROM VEF_EMP_TBLOCOM210_M610 G
              WHERE G.BDCODEMP = :PRCODEMP
                AND G.BDREFERENCIA = :PRREFERENCIA
                AND G.BDRETIFICADORA = :PRRETIFICADORA
                AND G.BDCODQUADRO = 37
              GROUP BY G.BDCODEMP, G.BDREFERENCIA
             UNION ALL
             SELECT BDCODEMP, 0 BDVLRDEBITO, 0 BDVLRCREDITO, SUM(M.BDVLRCOFINS) BDVLRRETENCAO
             FROM VEF_EMP_TORIDEDF700 M
             WHERE M.BDINDNATDED = 1 -- 0 - DEDUÇÃO DE NATUREZA NÃO CUMULATIVA
             AND M.BDCODEMP = :PRCODEMP
             AND M.BDREFERENCIA = :PRREFERENCIA
             GROUP BY BDCODEMP
             UNION ALL
             SELECT M.BDCODEMP, 0 BDVLRDEBITO, 0 BDVLRCREDITO, COALESCE(M.BDSLD_RET, 0) BDVLRRETENCAO
             FROM VEF_EMP_TBLOCOM1300_1700 M
             WHERE (M.BDCODQUADRO = 50) -- 1300 - FICHA DE RETENÇÃO DO PIS/PASEP | 1700 - FICHA DE RETENÇÃO DO COFINS
               AND M.BDCODEMP = :PRCODEMP
               AND M.BDREFERENCIA = :PRREFERENCIA
               AND M.BDRETIFICADORA = :PRRETIFICADORA
            )
            GROUP BY BDCODEMP
        )  G
      JOIN VW_TEMPRESAS_REF R ON (R.BDCODEMP = G.BDCODEMP)
      JOIN TMP_TCONF_CONTAS_ONLINE_TEMP C ON (C.BDCODPLAPADRAO = R.BDCODPLAPADRAO AND C.BDCODITEMONLINE = 254)
      LEFT OUTER JOIN TCOMPLEMENTO_HIST CH ON (CH.BDCODCOMPHIST = C.BDCODCOMPHIST)
      WHERE G.BDVALOR > 0;
  END
  ELSE
  BEGIN
    INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODHIST, bdCODTPHI, bdORDENACAO)
    SELECT IIF(:PRCONTABILIZAFILIAL = 'FALSE',g.bdCODMATRIZ, G.BDCODEMP), g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
         CASE WHEN ch.bdCOMPLEMENTO IS NOT NULL THEN REPLACE(
                                                     REPLACE(
                                                     REPLACE(ch.bdCOMPLEMENTO,
                                                             '*MES', SUBSTRING(g.bdREFERENCIA FROM 5 for 2)),
                                                             '*ANO', SUBSTRING(g.bdREFERENCIA FROM 1 for 4)),
                                                             '*REF', SUBSTRING(g.bdREFERENCIA FROM 5 for 2)||'/'||SUBSTRING(g.bdREFERENCIA FROM 1 for 4))
           ELSE 'Valor de Cofins Compensação - Ref:'||CAST(substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) AS VARCHAR(7))
         END as bdCOMPL,
         NULL as bdDATA, SUM(g.bdVALOR) as bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, 'TRUE' bdTRANFECHADA, c.bdCODHIST, c.bdCODTPHI, c.bdORDENACAO
  FROM VEF_EMP_TBLOCOMGERREG g
  JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
  JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 254)
  LEFT OUTER JOIN TCOMPLEMENTO_HIST ch ON (ch.bdCODCOMPHIST = c.bdCODCOMPHIST)
    WHERE ((G.BDCODMATRIZ = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'FALSE')
           OR (G.BDCODEMP = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'TRUE'))
    AND g.bdREFERENCIA = :prREFERENCIA
    AND G.BDRETIFICADORA = :PRRETIFICADORA
    AND g.bdCODQUADRO = 33 -- M600 - Consolidação da contribuição para o Cofins
    AND (
         (g.bdNUMCAMPO  = 03) OR -- VL_TOT_CRED_DESC - Valor do Crédito Descontado
                 (g.bdNUMCAMPO  = 04) OR -- VL_TOT_CRED_DESC_ANT - Valor do Crédito Descontado, Apurado em Período de Apuração Anterior
                 (g.bdNUMCAMPO  = 06) OR -- VL_RET_NC - Valor Retido na Fonte Deduzido no Período
                 (g.bdNUMCAMPO  = 07)   -- VL_OUT_DED_NC - Outras Deduções no Período
                 )
            AND g.bdVALOR > 0
    GROUP BY IIF(:PRCONTABILIZAFILIAL = 'FALSE',g.bdCODMATRIZ, G.BDCODEMP), g.bdREFERENCIA, c.bdCODPLAPADRAO, c.bdCONTADEBPROV, c.bdCONTACREDPROV, c.bdCODHIST, c.bdCODTPHI, ch.bdCOMPLEMENTO, c.bdORDENACAO;
  END


  -- "Receita financeira"
  INSERT INTO TMP_VSUC_EMP_TLAN_BLOCOM_TEMP (bdCODMATRIZ, bdREFERENCIA, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdCODHIST, bdCODTPHI, bdORDENACAO)
  SELECT IIF(:PRCONTABILIZAFILIAL = 'FALSE',g.bdCODMATRIZ, G.BDCODEMP), g.bdREFERENCIA, NULL as bdCHAVE, c.bdCODPLAPADRAO, NULL as bdCODUSU, c.bdCONTADEBPROV as bdDEBITO, c.bdCONTACREDPROV as bdCREDITO,
         CASE WHEN ch.bdCOMPLEMENTO IS NOT NULL THEN REPLACE(
                                                     REPLACE(
                                                     REPLACE(ch.bdCOMPLEMENTO,
                                                             '*MES', SUBSTRING(g.bdREFERENCIA FROM 5 for 2)),
                                                             '*ANO', SUBSTRING(g.bdREFERENCIA FROM 1 for 4)),
                                                             '*REF', SUBSTRING(g.bdREFERENCIA FROM 5 for 2)||'/'||SUBSTRING(g.bdREFERENCIA FROM 1 for 4))
         ELSE 'Valor de Cofins Débito Receita Financeira - Ref:'||CAST(substring(g.bdREFERENCIA FROM 5 for 2)||'/'||substring(g.bdREFERENCIA FROM 1 for 4) AS VARCHAR(7))
         END as bdCOMPL,
         NULL as bdDATA, SUM(g.bdvlrreceitafinanceira) as bdVALOR, 100 as bdTIPOLAN, NULL as bdDCTO, NULL as bdTRANSACAO, 'TRUE' bdTRANFECHADA, c.bdCODHIST, c.bdCODTPHI, c.bdORDENACAO
  FROM VEF_EMP_TBLOCOMGERREG g
  JOIN VW_TEMPRESAS_REF r ON (r.bdCODEMP = g.bdCODEMP)
  JOIN TMP_TCONF_CONTAS_ONLINE_TEMP c ON (c.bdCODPLAPADRAO = r.bdCODPLAPADRAO AND c.bdCODITEMONLINE = 639)
  LEFT OUTER JOIN TCOMPLEMENTO_HIST ch ON (ch.bdCODCOMPHIST = c.bdCODCOMPHIST)
  WHERE ((G.BDCODMATRIZ = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'FALSE')
         OR (G.BDCODEMP = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'TRUE'))
    AND g.bdREFERENCIA = :prREFERENCIA
    AND G.BDRETIFICADORA = :PRRETIFICADORA
    AND g.bdCODQUADRO = 33 -- M600 - Consolidação da contribuição para o Cofins
    AND (
         (g.bdNUMCAMPO  = 02)
                 )
            AND g.bdvlrreceitafinanceira > 0
  GROUP BY IIF(:PRCONTABILIZAFILIAL = 'FALSE',g.bdCODMATRIZ, G.BDCODEMP), g.bdREFERENCIA, c.bdCODPLAPADRAO, c.bdCONTADEBPROV, c.bdCONTACREDPROV, c.bdCODHIST, c.bdCODTPHI, ch.bdCOMPLEMENTO, c.bdORDENACAO;
  /****************************************************************************/

  /*Aqui vou deletar as inconsistências da conta "A Recuperar". A pedido da qualidade devemos apenas mostrar inconsistência da conta
  que será contabilizada no momento.*/
  IF ((WAJUPAGARCOFINS = 'TRUE') OR ((WAJUPAGARCOFINS = 'FALSE') AND (WAJURECUPERARCOFINS = 'FALSE'))) THEN
    BEGIN
        DELETE FROM VEF_INCON_BLOCOM I
        WHERE I.BDCODMATRIZ = :PRCODEMP
          AND I.BDREFERENCIA = :PRREFERENCIA
          AND I.BDRETIFICADORA = :PRRETIFICADORA
          AND I.BDCODINC IN ( 28 /*Ajuste a recuperar PIS*/, 30 /*Ajuste a recuperar COFINS*/);
    END
  /*Aqui vou deletar as inconsistências da conta "A Pagar". A pedido da qualidade devemos apenas mostrar inconsistência da conta
  que será contabilizada no momento.*/
  IF ((WAJURECUPERARCOFINS = 'TRUE') OR ((WAJUPAGARCOFINS = 'FALSE') AND (WAJURECUPERARCOFINS = 'FALSE'))) THEN
    BEGIN
        DELETE FROM VEF_INCON_BLOCOM I
        WHERE I.BDCODMATRIZ = :PRCODEMP
          AND I.BDREFERENCIA = :PRREFERENCIA
          AND I.BDRETIFICADORA = :PRRETIFICADORA
          AND I.BDCODINC IN (27/*Ajuste a pagar PIS*/, 29 /*Ajuste a pagar COFINS*/);
    END

  /* Alt.: #180334 - Quando lança as diferenças de crédito, estava apenas pegando a primeira conta que encontrava, porém deve contabilizar com as mesmas contas da primeira do primeiro lançamento,
     pois nesse caso ficavam algumas contabilização de R$0,01 e uma contas que não eram usadas por outras contabilizações. Como no memomento que contabiliza isso aqui ainda não tem todos
     os lançamentos contabeis, deixa fazer nas contas lá (essas de ordenação "00000") e aqui troca para as primeiras que encontrar, assim garante que sempre vai pegar a primeira conta corretamente. */
  UPDATE TMP_VSUC_EMP_TLAN_BLOCOM_TEMP l
  SET l.bdDEBITO = (SELECT FIRST 1 x.bdDEBITO
                    FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP x
                    WHERE ((POSITION('.00000', x.bdORDENACAO)) = 0)
                      AND  x.bdCODMATRIZ = l.bdCODMATRIZ
                      AND x.bdREFERENCIA = l.bdREFERENCIA
                      AND x.bdCODPLAPADRAO = l.bdCODPLAPADRAO
                      AND SUBSTRING(x.bdORDENACAO FROM 1 FOR (POSITION('.', x.bdORDENACAO))) = SUBSTRING(l.bdORDENACAO FROM 1 FOR (POSITION('.', l.bdORDENACAO)))
                    ORDER BY x.bdORDENACAO),
      l.bdCREDITO = (SELECT FIRST 1 x.bdCREDITO
                    FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP x
                    WHERE ((POSITION('.00000', x.bdORDENACAO)) = 0)
                      AND  x.bdCODMATRIZ = l.bdCODMATRIZ
                      AND x.bdREFERENCIA = l.bdREFERENCIA
                      AND x.bdCODPLAPADRAO = l.bdCODPLAPADRAO
                      AND SUBSTRING(x.bdORDENACAO FROM 1 FOR (POSITION('.', x.bdORDENACAO))) = SUBSTRING(l.bdORDENACAO FROM 1 FOR (POSITION('.', l.bdORDENACAO)))
                    ORDER BY x.bdORDENACAO)
  WHERE ((POSITION('.00000', l.bdORDENACAO)) > 0)
    AND CAST(SUBSTRING(l.bdORDENACAO FROM 1 FOR (POSITION('.', l.bdORDENACAO))) AS INTEGER) IN (247,533,251,535,248,533,534,252,535,536)
    AND l.bdVALOR = 0.01
    AND EXISTS(SELECT x.*
               FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP x
               WHERE ((POSITION('.00000', x.bdORDENACAO)) = 0)
                 AND  x.bdCODMATRIZ = l.bdCODMATRIZ
                 AND x.bdREFERENCIA = l.bdREFERENCIA
                 AND x.bdCODPLAPADRAO = l.bdCODPLAPADRAO
                 AND SUBSTRING(x.bdORDENACAO FROM 1 FOR (POSITION('.', x.bdORDENACAO))) = SUBSTRING(l.bdORDENACAO FROM 1 FOR (POSITION('.', l.bdORDENACAO))) );

END
^

CREATE OR ALTER procedure SP_APURACAO_BLOCOM_VALIDACONTAS (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRCODCONFBLOCOM integer,
    PRCODPLANOONLINE integer,
    PRCODITEMONLINE integer,
    PRCODINC integer,
    PRRETIFICADORA integer,
    PRCODEMPPRINCIPAL integer)
as
declare variable WCODPLAPADRAO integer;
declare variable WCONTADEBPROV integer;
declare variable WCONTACREDPROV integer;
declare variable WCLASSIFICACAO varchar(100);
declare variable WCODITEMONLINE integer;
declare variable WCODHIST integer;
declare variable WCODTPHI integer;
declare variable WCODCOMPHIST integer;
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Busca as contas do lançamento contábi, primeiro a especifica, caso não exista, busca a padrão...
  SELECT FIRST 1 bdCODPLAPADRAO, bdCONTADEBPROV, bdCONTACREDPROV, bdCLASSIFICACAO, bdCODITEMONLINE, bdCODHIST, bdCODTPHI, BDCODCOMPHIST
  FROM (
         SELECT o.bdCODPLAPADRAO, o.bdCODITEMONLINE, o.bdCONTADEBPROV, o.bdCONTACREDPROV, o.bdCLASSIFICACAO, o.BDCODHISTPROV AS BDCODHIST, o.BDCODTPHI, o.BDCODCOMPHISTPROV AS BDCODCOMPHIST
         FROM VW_TCONF_CONTAS_REF o
         WHERE o.bdCODPLANOONLINE = :prCODPLANOONLINE
           AND o.bdCODITEMONLINE = :prCODITEMONLINE -- Busca a conta específíca...
           AND ((o.bdCONTADEBPROV IS NOT NULL) AND (o.bdCONTACREDPROV IS NOT NULL))
           AND (o.bdCODCONFBLOCOM = :prCODCONFBLOCOM) -- Configuração especifica
           AND ((O.BDCLASSIFICACAO LIKE '03.002.000000010.000000002.T0000000%')
           OR   (O.BDCLASSIFICACAO LIKE '03.002.000000010.000000001.T0000000%'))
         UNION ALL
         SELECT o.bdCODPLAPADRAO, o.bdCODITEMONLINE, o.bdCONTADEBPROV, o.bdCONTACREDPROV, o.bdCLASSIFICACAO, o.BDCODHISTPROV AS BDCODHIST, o.BDCODTPHI, o.BDCODCOMPHISTPROV AS BDCODCOMPHIST
         FROM VW_TCONF_CONTAS_REF o
         WHERE o.bdCODPLANOONLINE = :prCODPLANOONLINE
           AND o.bdCODITEMONLINE = :prCODITEMONLINE -- Busca a conta padrão...
           --AND ((o.bdCONTADEBPROV IS NOT NULL) AND (o.bdCONTACREDPROV IS NOT NULL))
           AND (o.bdCODCONFBLOCOM IS NULL) -- Configuração padrão
        ) c
  --WHERE ((c.bdCONTADEBPROV IS NOT NULL) AND (c.bdCONTACREDPROV IS NOT NULL))
  INTO :wCODPLAPADRAO, :wCONTADEBPROV, :wCONTACREDPROV, :wCLASSIFICACAO, :wCODITEMONLINE, :wCODTPHI, :wCODHIST, :wCODCOMPHIST; -- Os campos "bdCODTPHI" e "bdCODHIST" estão invertidos na tabela acima, por isso inverte aqui...

  -- Grava as contas do que acabou de buscar, caso não existam, insere a inconsistência...
  IF ((:wCODPLAPADRAO IS NOT NULL) AND (:wCONTADEBPROV IS NOT NULL) AND (:wCONTACREDPROV IS NOT NULL)) THEN
    BEGIN
      INSERT INTO TMP_TCONF_CONTAS_ONLINE_TEMP (bdCODMATRIZ,  bdREFERENCIA,  bdCODPLANOONLINE, bdCODPLAPADRAO,  bdCODITEMONLINE, bdCONTADEBPROV, bdCONTACREDPROV, bdCODHIST, bdCODTPHI, bdCODCOMPHIST, bdORDENACAO)
                                        VALUES (  :prCODEMP, :prREFERENCIA, :prCODPLANOONLINE, :wCODPLAPADRAO, :prCODITEMONLINE, :wCONTADEBPROV, :wCONTACREDPROV, :wCODHIST, :wCODTPHI, :wCODCOMPHIST, LPAD(:wCODITEMONLINE, 5, '0')||'.'||LPAD('', 5, '0'));
    END
  ELSE
  IF ( --(:wCONTADEBPROV IS NULL) AND (:wCONTACREDPROV IS NULL) AND
       (:prCODINC NOT IN (15,19,31,32)) ) THEN -- Conta "Outras Deduções" não vai obrigar ou lançar inconsistências...
    BEGIN
      INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDREPLACES, BDRETIFICADORA)
                            VALUES (7, IIF(:PRCODEMPPRINCIPAL > 0, :PRCODEMPPRINCIPAL,:prCODEMP), IIF(:PRCODEMPPRINCIPAL > 0, :PRCODEMPPRINCIPAL,:prCODEMP), :prREFERENCIA,
                                    GETORDEMSEQUENCIAL_STR(IIF(:PRCODEMPPRINCIPAL > 0, :PRCODEMPPRINCIPAL,:prCODEMP)||'.'||IIF(:PRCODEMPPRINCIPAL > 0, :PRCODEMPPRINCIPAL,:prCODEMP)||'.'||:prReferencia, IIF(:PRCODEMPPRINCIPAL > 0, :PRCODEMPPRINCIPAL,:prCODEMP)),
                                    NULL, NULL, NULL, NULL, :prCODINC, :prCODPLANOONLINE||'¨'||COALESCE(:wCLASSIFICACAO,'03.002')||'¨'||:prCODPLANOONLINE, :PRRETIFICADORA); -- Caso não tenha conta por não ter atualizado o plano, joga o padrão para abrir a tela e mostrar que não tem comnfiguração das contas...
    END
 
END^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_VALIDA_DETAL (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRCODCONFBLOCOM INTEGER,
    PRCODPLANOONLINE INTEGER,
    PRCODQUADRO INTEGER,
    PRCODNATBC VARCHAR(6),
    PRVALOR NUMERIC(15,2),
    PRVALORRECEITAFIN numeric(15,2))
AS
DECLARE VARIABLE WCODPLAPADRAO INTEGER;
DECLARE VARIABLE WCONTADEBPROV INTEGER;
DECLARE VARIABLE WCONTACREDPROV INTEGER;
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(100);
DECLARE VARIABLE WCODITEMONLINE INTEGER;
DECLARE VARIABLE WFORMULA VARCHAR(100);
DECLARE VARIABLE WREPLACE01 VARCHAR(10);
DECLARE VARIABLE WREPLACE02 VARCHAR(200);
DECLARE VARIABLE WREPLACE03 VARCHAR(10);
DECLARE VARIABLE WORD INTEGER;
DECLARE VARIABLE WCODHIST INTEGER;
DECLARE VARIABLE WCODTPHI INTEGER;
DECLARE VARIABLE WCODCOMPHIST INTEGER;
declare variable WCHAVE integer;
declare variable WRECEITAFINANCEIRA integer;
BEGIN
  -- Busca as contas do lançamento contábi, primeiro a especifica, caso não exista, busca a padrão...
  SELECT FIRST 1 bdCODPLAPADRAO, bdCHAVE, bdCONTADEBPROV, bdCONTACREDPROV, bdCLASSIFICACAO, bdCODITEMONLINE, bdFORMULA, bdCODHIST, bdCODTPHI, bdCODCOMPHIST,
         TRIM(CASE
                WHEN :prCODQUADRO IN (11,29) THEN 'Crédito'
                WHEN :prCODQUADRO IN (19,37) THEN 'Débito'
              END) as bdREPLACE01,
         COALESCE(cred.bdREGEXP||' - '||cred.bdDESCRICAO, deb.bdCODCSOCIALEXP||' - '||deb.bdDESCRICAO) as bdREPLACE02,
         TRIM(CASE
                WHEN :prCODQUADRO IN (11,19) THEN 'PIS'
                WHEN :prCODQUADRO IN (29,37) THEN 'COFINS'
              END) as bdREPLACE03,
         COALESCE(cred.bdREGEXP, deb.bdCODCSOCIALEXP) as bdORD,
         Coalesce((SELECT FIRST 1 O.BDCODITEMONLINE
         FROM vw_tconf_contas_ref o
         WHERE o.bdCODPLANOONLINE = :prCODPLANOONLINE
           AND o.bdcoditemonline = TRIM(CASE
                                   WHEN :prCODQUADRO IN (11,19) THEN 638
                                   WHEN :prCODQUADRO IN (29,37) THEN 639
                                  END)
           AND (O.bdcontadebprov <> 0 and
               o.bdcontacredprov <> 0)
              ),0) BDRECEITAFINANCEIRA
  FROM (
         SELECT o.bdCODPLAPADRAO, o.bdCHAVE, o.bdCODITEMONLINE, o.bdCONTADEBPROV, o.bdCONTACREDPROV, o.bdCLASSIFICACAO, o.bdFORMULA,
                o.BDCODHISTPROV AS BDCODHIST, o.BDCODTPHI, o.BDCODCOMPHISTPROV AS BDCODCOMPHIST
         FROM vw_tconf_contas_ref o
         WHERE o.bdCODPLANOONLINE = :prCODPLANOONLINE
           AND o.bdFORMULA = 'BLOCOM'||
                             TRIM(CASE
                                    WHEN :prCODQUADRO IN (11,29) THEN 'CREDDESC'
                                    WHEN :prCODQUADRO IN (19,37) THEN 'DEBITO'
                                  END)||
                             TRIM(CASE
                                    WHEN :prCODQUADRO IN (11,19) THEN 'PIS'
                                    WHEN :prCODQUADRO IN (29,37) THEN 'COFINS'
                                  END)||
                             '.'||LPAD(:prCODNATBC, 6, '0')||'('||:prCODCONFBLOCOM||')'
--           AND ((o.bdCONTADEBPROV IS NOT NULL) AND (o.bdCONTACREDPROV IS NOT NULL))
         UNION ALL
         SELECT o.bdCODPLAPADRAO, o.bdCHAVE, o.bdCODITEMONLINE, o.bdCONTADEBPROV, o.bdCONTACREDPROV, o.bdCLASSIFICACAO, o.bdFORMULA,
                o.BDCODHISTPROV AS BDCODHIST, o.BDCODTPHI, o.BDCODCOMPHISTPROV AS BDCODCOMPHIST
         FROM vw_tconf_contas_ref o
         WHERE o.bdCODPLANOONLINE = :prCODPLANOONLINE
           AND o.bdFORMULA = 'BLOCOM'||
                             TRIM(CASE
                                    WHEN :prCODQUADRO IN (11,29) THEN 'CREDDESC'
                                    WHEN :prCODQUADRO IN (19,37) THEN 'DEBITO'
                                  END)||
                             TRIM(CASE
                                    WHEN :prCODQUADRO IN (11,19) THEN 'PIS'
                                    WHEN :prCODQUADRO IN (29,37) THEN 'COFINS'
                                  END)||
                             '.T.'||LPAD(:prCODNATBC, 6, '0')||'('||:prCODCONFBLOCOM||')'
        ) c
  LEFT OUTER JOIN VEF_BASE_TNATBCPISCOFINS cred ON (cred.bdREGEXP = CASE
                                                                      WHEN c.bdFORMULA LIKE '%CREDDESC%' THEN SUBSTRING(c.bdFORMULA FROM (POSITION('(', c.bdFORMULA)-2) FOR 2)
                                                                    ELSE '' END)
  LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 deb ON (deb.bdCODCSOCIALEXP = CASE
                                                                             WHEN c.bdFORMULA LIKE '%DEBITO%' THEN SUBSTRING(c.bdFORMULA FROM (POSITION('(', c.bdFORMULA)-2) FOR 2)
                                                                           ELSE '' END)
  INTO :wCODPLAPADRAO, :wCHAVE, :wCONTADEBPROV, :wCONTACREDPROV, :wCLASSIFICACAO, :wCODITEMONLINE, :wFORMULA, :wCODTPHI, :wCODHIST, :wCODCOMPHIST, -- Os campos "bdCODTPHI" e "bdCODHIST" est?o invertidos na tabela acima, por isso inverte aqui...
       :wREPLACE01, :wREPLACE02, :wREPLACE03, wORD, WRECEITAFINANCEIRA;

  -- Grava as contas do que acabou de buscar, caso não existam, insere a inconsistência...
--  IF ((:wCODPLAPADRAO IS NOT NULL) AND (:wCONTADEBPROV IS NOT NULL) AND (:wCONTACREDPROV IS NOT NULL)) THEN
  IF ((:wCODPLAPADRAO IS NOT NULL) AND ((:wCONTADEBPROV IS NOT NULL) OR (:wCONTACREDPROV IS NOT NULL))) THEN
    BEGIN
      INSERT INTO TMP_TCONF_CONTAS_ONLINE_TEMP (bdCODMATRIZ, bdCHAVE,  bdREFERENCIA,  bdCODPLANOONLINE, bdCODPLAPADRAO, bdCODITEMONLINE, bdCONTADEBPROV, bdCONTACREDPROV, bdFORMULA, bdCODHIST, bdCODTPHI, bdCODCOMPHIST,  bdVALOR                                                           , bdORDENACAO)
                                        VALUES (  :prCODEMP, :wCHAVE, :prREFERENCIA, :prCODPLANOONLINE, :wCODPLAPADRAO, :wCODITEMONLINE, :wCONTADEBPROV, :wCONTACREDPROV, :wFORMULA, :wCODHIST, :wCODTPHI, :wCODCOMPHIST, IIF(:WRECEITAFINANCEIRA > 0,:prVALOR - :PRVALORRECEITAFIN,:prVALOR), LPAD(:wCODITEMONLINE, 5, '0')||'.'||LPAD(:wORD, 5, '0'));
    END

END
^

CREATE OR ALTER procedure SP_APUR_BLCM_VALIDA_DETAL_CFOP (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRCODCONFBLOCOM integer,
    PRCODPLANOONLINE integer,
    PRCODQUADRO integer,
    PRCODNAT integer,
    PRCONDPGTO integer,
    PRVALOR numeric(15,2),
    PRCODEMPPRINCIPAL integer,
    PRCODNATBC VARCHAR(6))
as
declare variable WCODPLAPADRAO integer;
declare variable WCONTADEBPROV integer;
declare variable WCONTACREDPROV integer;
declare variable WCLASSIFICACAO varchar(100);
declare variable WCODITEMONLINE integer;
declare variable WFORMULA varchar(100);
declare variable WREPLACE01 varchar(10);
declare variable WREPLACE02 varchar(200);
declare variable WREPLACE03 varchar(10);
declare variable WORD integer;
declare variable WCODHIST integer;
declare variable WCODTPHI integer;
declare variable WCODCOMPHIST integer;
declare variable WRECEITAFINANCEIRA integer;
declare variable WCONTABILIZA DM_BOOLEAN;
declare variable WCHAVE integer;
BEGIN

  IF ((COALESCE(:PRCODNAT,'') = '') AND (:prCODNATBC <> '')) THEN -- Alt.: #197649 - Quando vier sem a CFOP, manda contabilizar pelo modelo detalhado, para continuar funcionando como sempre fez...
    BEGIN
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDA_DETAL (:prCODEMP, :prREFERENCIA, :prCODCONFBLOCOM, :prCODPLANOONLINE, :prCODQUADRO, :prCODNATBC, :prVALOR, 0);
      EXIT;
    END

  --VERIFICA SE A CFOP CONTABILIZA
  SELECT BDCONTABILIZA
  FROM VEF_BASE_TNATOP N
  WHERE N.BDCODNAT = :PRCODNAT
  INTO :WCONTABILIZA;

  IF (:WCONTABILIZA = 'FALSE') THEN
    EXIT;

  -- BUSCA AS CONTAS DO LANÇAMENTO CONTÁBI, PRIMEIRO A ESPECIFICA, CASO NÃO EXISTA, BUSCA A PADRÃO...
 SELECT FIRST 1 O.BDCODPLAPADRAO, O.BDCHAVE, O.BDCONTADEBPROV, O.BDCONTACREDPROV, O.BDCLASSIFICACAO,
         CASE WHEN :PRCODQUADRO = 11 THEN 247
              WHEN :PRCODQUADRO = 19 THEN 248
              WHEN :PRCODQUADRO = 29 THEN 251
              WHEN :PRCODQUADRO = 37 THEN 252
         END  BDCODITEMONLINE, O.BDFORMULA,
         O.BDCODHISTPROV AS BDCODHIST, O.BDCODTPHI, O.BDCODCOMPHISTPROV AS BDCODCOMPHIST,
         TRIM(CASE
                WHEN :PRCODQUADRO IN (11,29) THEN 'CRÉDITO'
                WHEN :PRCODQUADRO IN (19,37) THEN 'DÉBITO'
              END) AS BDREPLACE01,
         'CFOP '||SUBSTRING(:PRCODNAT FROM 1 FOR 1)||'.'||SUBSTRING(:PRCODNAT FROM 2 FOR 3)||'-'||SUBSTRING(:PRCODNAT FROM 5 FOR 3)||' - '||
          CASE
               WHEN :PRCONDPGTO = 0 THEN 'Vista'
               WHEN :PRCONDPGTO = 1 THEN 'Prazo'
               WHEN :PRCONDPGTO = 2 THEN 'Outras'
          END
          AS BDREPLACE02,
         TRIM(CASE
                WHEN :PRCODQUADRO IN (11,19) THEN 'PIS'
                WHEN :PRCODQUADRO IN (29,37) THEN 'COFINS'
              END) AS BDREPLACE03,
         :PRCODNAT||'.'||:PRCONDPGTO AS BDORD
  FROM (
        SELECT O.BDCODPLAPADRAO, O.BDCHAVE, O.BDCONTADEBPROV, O.BDCONTACREDPROV, O.BDCLASSIFICACAO,O.BDFORMULA,
         O.BDCODHISTPROV, O.BDCODTPHI, O.BDCODCOMPHISTPROV
        FROM  VW_TCONF_CONTAS_REF O
        WHERE O.BDCODPLANOONLINE = :PRCODPLANOONLINE
          AND O.BDCODNAT = :PRCODNAT
          AND O.BDFORMULA = 'NAT'||
                          TRIM(CASE
                                WHEN :PRCONDPGTO = 0 THEN 'V'
                                WHEN :PRCONDPGTO = 1 THEN 'P'
                                WHEN :PRCONDPGTO = 2 THEN 'O'
                              END)||
                         TRIM(CASE
                                WHEN :PRCODQUADRO IN (11,19) THEN 'PIS'
                                WHEN :PRCODQUADRO IN (29,37) THEN 'COFINS'
                              END)||
                         '('||:PRCODNAT||')'
           AND O.BDCONTADEBPROV IS NOT NULL AND O.BDCONTACREDPROV IS NOT NULL
        UNION ALL
        SELECT R.BDCODPLAPADRAO, R.BDCHAVE, R.BDCONTADEBPROV, R.BDCONTACREDPROV, R.BDCLASSIFICACAO,R.BDFORMULA,
         R.BDCODHISTPROV, R.BDCODTPHI, R.BDCODCOMPHISTPROV
        FROM (
           SELECT O.BDCODPLANOONLINE, O.BDCHAVE, O.BDCODITEMONLINE,(SELECT * FROM SP_GET_CLASSIFICACAO_NIVEL(O.BDCLASSIFICACAO,7))||'.A00000'||O.BDCODITEMONLINE BDCLASSIFICACAOTITULO
           FROM VW_TCONF_CONTAS_REF O
            WHERE O.BDCODPLANOONLINE = :PRCODPLANOONLINE
            AND O.BDCODNAT = :PRCODNAT
            AND O.BDFORMULA = 'NAT'||
                              TRIM(CASE
                                    WHEN :PRCONDPGTO = 0 THEN 'V'
                                    WHEN :PRCONDPGTO = 1 THEN 'P'
                                    WHEN :PRCONDPGTO = 2 THEN 'O'
                                  END)||
                             TRIM(CASE
                                    WHEN :PRCODQUADRO IN (11,19) THEN 'PIS'
                                    WHEN :PRCODQUADRO IN (29,37) THEN 'COFINS'
                                  END)||
                             '('||:PRCODNAT||')'
               ) O
        LEFT OUTER JOIN VW_TCONF_CONTAS_REF R ON (R.BDCODPLANOONLINE = O.BDCODPLANOONLINE AND R.BDCLASSIFICACAO = BDCLASSIFICACAOTITULO)
  ) O
  INTO :WCODPLAPADRAO, :WCHAVE, :WCONTADEBPROV, :WCONTACREDPROV, :WCLASSIFICACAO, :WCODITEMONLINE, :WFORMULA, :WCODTPHI, :WCODHIST, :WCODCOMPHIST, -- OS CAMPOS "BDCODTPHI" E "BDCODHIST" EST?O INVERTIDOS NA TABELA ACIMA, POR ISSO INVERTE AQUI...
       :WREPLACE01, :WREPLACE02, :WREPLACE03, WORD;

  -- Grava as contas do que acabou de buscar, caso não existam, insere a inconsistência...
  -- Se não tiver conta de alguma CFOP não vai contabilizar nada..
  IF ((:WCODPLAPADRAO IS NOT NULL) AND ((:WCONTADEBPROV IS NOT NULL) OR (:WCONTACREDPROV IS NOT NULL)))  THEN
    BEGIN
      INSERT INTO TMP_TCONF_CONTAS_ONLINE_TEMP (BDCODMATRIZ, BDCHAVE,  BDREFERENCIA,  BDCODPLANOONLINE, BDCODPLAPADRAO, BDCODITEMONLINE, BDCONTADEBPROV, BDCONTACREDPROV, BDFORMULA, BDCODHIST, BDCODTPHI, BDCODCOMPHIST,  BDVALOR,  BDCODNAT, BDORDENACAO)
                                        VALUES (  :PRCODEMP, :wCHAVE, :PRREFERENCIA, :PRCODPLANOONLINE, :WCODPLAPADRAO, :WCODITEMONLINE, :WCONTADEBPROV, :WCONTACREDPROV, :WFORMULA, :WCODHIST, :WCODTPHI, :WCODCOMPHIST, :PRVALOR, :PRCODNAT, LPAD(:WCODITEMONLINE, 5, '0')||'.'||LPAD(:WORD, 5, '0'));
    END
  ELSE if (:WCODPLAPADRAO IS NOT NULL) then -- Ocorria erro quando nao encontrava nada no SQL principal e trazia tudo nulo
    BEGIN
      INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDREPLACES, BDRETIFICADORA)
                            VALUES (7, IIF(:PRCODEMPPRINCIPAL > 0, :PRCODEMPPRINCIPAL,:prCODEMP), IIF(:PRCODEMPPRINCIPAL > 0, :PRCODEMPPRINCIPAL,:prCODEMP), :prREFERENCIA,
                                    GETORDEMSEQUENCIAL_STR(IIF(:PRCODEMPPRINCIPAL > 0, :PRCODEMPPRINCIPAL,:prCODEMP)||'.'||IIF(:PRCODEMPPRINCIPAL > 0, :PRCODEMPPRINCIPAL,:prCODEMP)||'.'||:prReferencia, IIF(:PRCODEMPPRINCIPAL > 0, :PRCODEMPPRINCIPAL,:prCODEMP)),
                                    NULL, NULL, NULL, NULL, 21, :PRCODPLANOONLINE||'¨'||:WREPLACE01||'¨'||:WREPLACE03||'¨'||:WREPLACE02||'¨'||:WREPLACE01||'¨'||:PRCODPLANOONLINE, 0); -- Caso não tenha conta por não ter atualizado o plano, joga o padrão para abrir a tela e mostrar que não tem comnfiguração das contas...
    END

END
^

CREATE OR ALTER procedure SP_APURACAO_BLOCOM_VALIDAONLINE (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRCODEMPPRINCIPALSCP integer,
    PRRETIFICADORA integer,
    PRCONTABILIZAFILIAL DM_BOOLEAN)
as
declare variable WSQL varchar(32000);
declare variable WCODCONFBLOCOM integer;
declare variable WCODPLANOONLINE integer;
declare variable WTIPOINTPIS integer;
declare variable WTIPOINTCOFINS integer;
declare variable WCODQUADRO integer;
declare variable WCODNATBC varchar(6);
declare variable WVALOR numeric(15,2);
declare variable WCODINC integer;
declare variable WVALORRECEITAFINANCEIRA numeric(15,2);
declare variable WCODNAT integer;
declare variable WCONDPGTO integer;
BEGIN
  -- Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Obtém a configuração de Bloco M
  SELECT COALESCE(tot.bdCODCONFBLOCOM, confPadrao.bdCODCONF) AS bdCODCONFBLOCOM
  FROM VW_EMP_REF_TOTAL tot
  LEFT OUTER JOIN (
                    SELECT FIRST 1 x.bdCODCONF, x.bdPLANOPADRAO
                    FROM VEF_BASE_TCONFBLOCOM x
                    WHERE x.bdPLANOPADRAO = 'TRUE'
                   ) confPadrao ON (confPadrao.bdPLANOPADRAO = 'TRUE')
  WHERE  tot.bdCODEMP = :PRCODEMPPRINCIPALSCP
  ORDER BY tot.bdCODCONFBLOCOM, tot.bdCODEMP
  INTO :wCODCONFBLOCOM;

  -- Obtém o plano online
  SELECT r.bdCODPLANOONLINE
  FROM VW_TEMPRESAS_REF r
  WHERE r.bdCODEMP = :PRCODEMPPRINCIPALSCP
  INTO :wCODPLANOONLINE;

  -- Verifica se deve ou não contabilizar o PIS e Cofins...
  SELECT bdTIPOINTPIS, bdTIPOINTCOFINS
  FROM TPLANO_CONF_ONLINE
  WHERE bdCODPLANOONLINE = :wCODPLANOONLINE
  INTO :wTIPOINTPIS, :wTIPOINTCOFINS;

  IF ((:wCODCONFBLOCOM > 0) AND (:wCODPLANOONLINE > 0)) THEN
    BEGIN
      IF (((:wTIPOINTPIS IN (1,4)) OR (:wTIPOINTCOFINS IN (1,4))) OR (:PRRETIFICADORA = 1)) THEN -- Valores da apuração
        BEGIN
          if ((:wTIPOINTPIS = 4) OR (:wTIPOINTCOFINS = 4)) then
            BEGIN
              wSQL = 'SELECT BDCODQUADRO,BDCODNAT, BDCONDPGTO, BDVALOR, bdCODNATBC ';
              wSQL = wSQL || ' FROM ( ';
              wSQL = wSQL || '  SELECT BDCODQUADRO,BDCODNAT, BDCONDPGTO, SUM(BDVALOR) BDVALOR, bdCODNATBC ';
              wSQL = wSQL || '  FROM ( ';
              wSQL = wSQL || '        SELECT BDCODNAT, BDCONDPGTO,BDCODQUADRO, bdCODNATBC, ';
              wSQL = wSQL || '        CAST(M.BDVL_BC AS NUMERIC(15,4))*(CAST(M.bdALIQ AS NUMERIC(15,6))/100) BDVALOR';
              wSQL = wSQL || '        FROM VEF_EMP_TVINCM105_M505 M ';
              wSQL = wSQL || '        WHERE ';

                     if (:PRCONTABILIZAFILIAL = 'FALSE') then
                        wSQL = wSQL || '        M.BDCODMATRIZ = ' || :PRCODEMP;
                      else
                        wSQL = wSQL || '        M.BDCODEMP = ' || :PRCODEMP;

              wSQL = wSQL || ' AND BDREFERENCIA = ' ||:prREFERENCIA;
              wSQL = wSQL || '  AND BDRETIFICADORA = ' || :PRRETIFICADORA;
              wSQL = wSQL || '  AND (M.BDCODQUADRO = 11 or M.BDCODQUADRO = 29) ';
              wSQL = wSQL || '  AND M.BDCODPERIODO = 7 ';
              wSQL = wSQL || '  ) ';
              wSQL = wSQL || 'GROUP BY BDCODNAT, BDCONDPGTO,BDCODQUADRO, bdCODNATBC ';
              wSQL = wSQL || ' UNION ALL ';
              wSQL = wSQL || ' SELECT BDCODQUADRO,BDCODNAT, BDCONDPGTO, SUM(BDVALOR) BDVALOR, bdCODNATBC ';
              wSQL = wSQL || ' FROM ( ';
              wSQL = wSQL || '      SELECT BDCODNAT, BDCONDPGTO,BDCODQUADRO, CS.bdcodcsocialexp bdCODNATBC, ';
              wSQL = wSQL || '      (( IIF(BDVL_BC_CONT > 0,BDVL_BC_CONT,COALESCE(BDQUANT_BC,0)) * IIF(COALESCE(BDALIQ,0) > 0, COALESCE(BDALIQ,0), COALESCE(BDALIQ_QUANT,1)))/IIF(COALESCE(BDALIQ,0) > 0, 100, 1)) BDVALOR ';
              wSQL = wSQL || '      FROM VEF_EMP_TVINC_M210_M610 M ';
              wSQL = wSQL || '      LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 CS ON (CS.bdcodcsocial = M.BDCODCSOCIAL) ';
              wSQL = wSQL || '      WHERE ';

              if (:PRCONTABILIZAFILIAL = 'FALSE') then
                wSQL = wSQL || ' M.BDCODMATRIZ = ' || :PRCODEMP;
              else
                wSQL = wSQL || ' M.BDCODEMP = ' || :PRCODEMP;

              wSQL = wSQL || ' AND BDREFERENCIA = ' || :prREFERENCIA;
              wSQL = wSQL || ' AND BDRETIFICADORA = ' || :PRRETIFICADORA;
              wSQL = wSQL || ' AND (M.BDCODQUADRO = 19 or M.BDCODQUADRO=37) ';
              wSQL = wSQL || ' AND M.BDCODPERIODO = 7 ';
              wSQL = wSQL || ' AND (((' ||:wTIPOINTPIS || '<> 4) AND ('|| :wTIPOINTCOFINS ||' <> 4)) OR ' ;
              wSQL = wSQL || '   (m.bdCODCSOCIAL NOT IN(7,8,9,10,13)) )';
              wSQL = wSQL || ' ) ';
              wSQL = wSQL || ' GROUP BY BDCODNAT, BDCONDPGTO,BDCODQUADRO, bdCODNATBC ';
              wSQL = wSQL || ' ) m ';

              -- Contabiliza detalhadamente nas contas especificas...
              FOR execute statement :wSQL INTO :wCODQUADRO, :WCODNAT,:WCONDPGTO, :wVALOR, :wCODNATBC DO
              BEGIN
                EXECUTE PROCEDURE SP_APUR_BLCM_VALIDA_DETAL_CFOP(:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, :wCODQUADRO, :WCODNAT,:WCONDPGTO,:wVALOR,IIF(:PRCONTABILIZAFILIAL = 'TRUE',:PRCODEMPPRINCIPALSCP,0), :wCODNATBC);
              END
            END
          ELSE
            BEGIN
              /* Contabiliza detalhadamente nas contas especificas... */
              FOR
            SELECT /*m.bdCODMATRIZ, m.bdREFERENCIA,*/ m.bdCODQUADRO, m.bdCODNATBC, m.bdVALOR, m.BDVLRRECEITAFINANCEIRA
            FROM (
                   SELECT /*m.bdCODMATRIZ, m.bdREFERENCIA,*/ m.bdCODQUADRO, m.bdCODNATBC, SUM((COALESCE(m.bdVL_BC,0)*COALESCE(m.bdALIQ,1))/100) AS bdVALOR, 0 BDVLRRECEITAFINANCEIRA
                   FROM VEF_EMP_TBLOCOM105_M505 m
                   WHERE ((M.BDCODMATRIZ = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'FALSE')
                     OR (M.BDCODEMP = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'TRUE'))
                     AND m.bdREFERENCIA = :prREFERENCIA
                     AND M.BDRETIFICADORA = :PRRETIFICADORA
                   GROUP BY M.BDCODMATRIZ, m.bdREFERENCIA, m.bdCODQUADRO, m.bdCODNATBC
                   UNION ALL
                   SELECT /*m.bdCODMATRIZ, m.bdREFERENCIA,*/ m.bdCODQUADRO, m.bdCODCSOCIAL, SUM(COALESCE(m.bdVL_CONT_PER,0)) AS bdVALOR, SUM(COALESCE(m.BDVLRRECEITAFINANCEIRA,0)) BDVLRRECEITAFINANCEIRA
                   FROM VEF_EMP_TBLOCOM210_M610 m
                   WHERE ((M.BDCODMATRIZ = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'FALSE')
                     OR (M.BDCODEMP = :PRCODEMP AND :PRCONTABILIZAFILIAL = 'TRUE'))
                     AND m.bdREFERENCIA = :prREFERENCIA
                     AND M.BDRETIFICADORA = :PRRETIFICADORA
                     AND (((:wTIPOINTPIS <> 4) AND (:wTIPOINTCOFINS <> 4)) OR /* Alt.: 209240 - Se a empresa contabiliza PIS e Cofins(LR) como "Valores da apuração + total por CFOP", não deve levar as contribuições sociais que caracterizam valores cumulativos 51,52,53,54,72. */
                          (m.bdCODCSOCIAL NOT IN(7,8,9,10,13)) )

                   GROUP BY M.BDCODMATRIZ, m.bdREFERENCIA, m.bdCODQUADRO, m.bdCODCSOCIAL
                  ) m
            INTO /*:wCODMATRIZ, :wREFERENCIA,*/ :wCODQUADRO, :wCODNATBC, :wVALOR, :wValorReceitaFinanceira
          DO
            BEGIN
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDA_DETAL (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, :wCODQUADRO, :wCODNATBC, :wVALOR, :wValorReceitaFinanceira);
            END
            END
          /********************************************************/
          /*Não é uma apuração complementar*/
          IF (:PRRETIFICADORA = 0) THEN
          BEGIN
            /* Contabiliza nas contas principais... */
          IF (:wTIPOINTPIS IN (1,4)) THEN -- Valores da apuração
                BEGIN
                  -- 247 - Crédito - PIS
                  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 247, 13, :PRRETIFICADORA,IIF(:PRCONTABILIZAFILIAL = 'TRUE',:PRCODEMPPRINCIPALSCP,0));
                  -- 248 - Débito - PIS
                  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 248, 14, :PRRETIFICADORA,IIF(:PRCONTABILIZAFILIAL = 'TRUE',:PRCODEMPPRINCIPALSCP,0));
                  -- 249 - Outras Deduções - PIS
                  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 249, 15, :PRRETIFICADORA,IIF(:PRCONTABILIZAFILIAL = 'TRUE',:PRCODEMPPRINCIPALSCP,0));
                  -- 250 - Compensação - PIS
                  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 250, 16, :PRRETIFICADORA,IIF(:PRCONTABILIZAFILIAL = 'TRUE',:PRCODEMPPRINCIPALSCP,0));
                  -- 638 - Receita Financeira - PIS
                  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 638, 31, :PRRETIFICADORA,IIF(:PRCONTABILIZAFILIAL = 'TRUE',:PRCODEMPPRINCIPALSCP,0));
                END
        
          IF (:wTIPOINTCOFINS IN (1,4)) THEN -- Valores da apuração
                BEGIN
                  -- 251 - Crédito - Cofins
                  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 251, 17, :PRRETIFICADORA,IIF(:PRCONTABILIZAFILIAL = 'TRUE',:PRCODEMPPRINCIPALSCP,0));
                  -- 252 - Débito - Cofins
                  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 252, 18, :PRRETIFICADORA,IIF(:PRCONTABILIZAFILIAL = 'TRUE',:PRCODEMPPRINCIPALSCP,0));
                  -- 253 - Outras Deduções - Cofins
                  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 253, 19, :PRRETIFICADORA,IIF(:PRCONTABILIZAFILIAL = 'TRUE',:PRCODEMPPRINCIPALSCP,0));
                  -- 254 - Compensação - Cofins
                  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 254, 20, :PRRETIFICADORA,IIF(:PRCONTABILIZAFILIAL = 'TRUE',:PRCODEMPPRINCIPALSCP,0));   
                  -- 639 - Receita Financeira - Cofins
                  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 639, 32, :PRRETIFICADORA,IIF(:PRCONTABILIZAFILIAL = 'TRUE',:PRCODEMPPRINCIPALSCP,0));
                END
          /****************************************/
          END
          ELSE
          IF (:PRRETIFICADORA = 1) THEN
          BEGIN
            -- 533 - Ajuste a pagar - PIS
            EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 533, 27, :PRRETIFICADORA,IIF(:PRCONTABILIZAFILIAL = 'TRUE',:PRCODEMPPRINCIPALSCP,0));
            -- 534 - Ajuste a recuperar - PIS
            EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 534, 28, :PRRETIFICADORA,IIF(:PRCONTABILIZAFILIAL = 'TRUE',:PRCODEMPPRINCIPALSCP,0));
            -- 535 - Ajuste a pagar Crédito - COFINS
            EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 535, 29, :PRRETIFICADORA,IIF(:PRCONTABILIZAFILIAL = 'TRUE',:PRCODEMPPRINCIPALSCP,0));
            -- 536 - Ajuste a recuperar Débito - COFINS
            EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDACONTAS (:prCODEMP, :prREFERENCIA, :wCODCONFBLOCOM, :wCODPLANOONLINE, 536, 30, :PRRETIFICADORA,IIF(:PRCONTABILIZAFILIAL = 'TRUE',:PRCODEMPPRINCIPALSCP,0));
          END
        END
    END

END^


CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_ONLINE (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRCODEMPPRINCIPALSCP INTEGER,
    PRRETIFICADORA integer,
    PRCONTABILIZAFILIAL DM_BOOLEAN,
    PRRECONTABILIZA boolean = false)
as
DECLARE VARIABLE WDATAINICONTABILIZACAO integer;
DECLARE VARIABLE WCODINC integer;
DECLARE VARIABLE WINCTRIB integer;
BEGIN
  -- Limpa a tabela de contabilização do Bloco M
  DELETE FROM TMP_TCONF_CONTAS_ONLINE_TEMP WHERE ((bdCODMATRIZ = :prCODEMP) OR (BDCODMATRIZ = :PRCODEMPPRINCIPALSCP) ) AND bdREFERENCIA = :prREFERENCIA;

  if (PRRECONTABILIZA = TRUE) then
   DELETE FROM VEF_INCON_BLOCOM WHERE ((bdCODMATRIZ = :prCODEMP) OR (BDCODMATRIZ = :PRCODEMPPRINCIPALSCP)) AND (bdREFERENCIA = :prREFERENCIA) AND (BDRETIFICADORA = :PRRETIFICADORA);

  -- Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Incidência tributária
  SELECT BDINCTRIB+1 FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMPPRINCIPALSCP INTO :wINCTRIB;

  SELECT SUBSTRING(REPLACE(CAST(BDDATA AS VARCHAR(11)),'-','')FROM 1 FOR 6)  FROM TINICIO_CONTABILIZACAO WHERE BDCODEMP = :prcodemp AND BDCODSIS = 3 INTO :wdatainicontabilizacao;

  IF ((:wINCTRIB IN (1,3)) OR (:PRRETIFICADORA = 1)) THEN -- 1 - Exclusivamente no regime não-cumulativo e 3 - Regimes não-cumulativo e cumulativo
    BEGIN

      if (:wdatainicontabilizacao IS NOT NULL) then      --Quando a data de inicio de contabilização for diferente de nula deve-se ser verificada
         if (:prreferencia < CAST(:wdatainicontabilizacao AS INTEGER)) then -- Só contabiliza os períodos superiores a data de ínicio de contabilização
            EXIT;


      -- Valida as contas da contabilização da apuração do Bloco M...
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_VALIDAONLINE (:prCODEMP, :prREFERENCIA, :PRCODEMPPRINCIPALSCP, :PRRETIFICADORA,:PRCONTABILIZAFILIAL);
    
      -- Verifica se possui alguma inconsistência de contas online...
      SELECT FIRST 1 i.bdCODINC
      FROM VEF_INCON_BLOCOM i
      WHERE i.bdCODMATRIZ = :prCODEMP
        AND i.bdREFERENCIA = :prREFERENCIA
        AND I.BDRETIFICADORA = :PRRETIFICADORA
        -- "Outras Deduções" não é um campo obrigatório
            AND i.bdCODINC IN (13,/*"Crédito" do PIS*/    14,/*"Débito" do PIS*/    /*15,*/ /*"Outras Deduções" do PIS*/    16,/*"Compensação" do PIS*/
                               17,/*"Crédito" do Cofins*/ 18,/*"Débito" do Cofins*/ /*19,*/ /*"Outras Deduções" do Cofins*/ 20,/*"Compensação" do Cofins*/
                               21/*Inconsistências genérica da contabilização detalhada*/)
      INTO :wCODINC;
        
      -- Deleta os registros da tabela da contabilização, caso exista algum lançamento
      DELETE FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t
      WHERE t.bdCODMATRIZ = :prCODEMP
        AND t.bdREFERENCIA = :prREFERENCIA;

      IF (:wCODINC IS NULL) THEN
        EXECUTE PROCEDURE SP_APURACAO_BLOCOM_ONLINE_CONSO (:prCODEMP, :prREFERENCIA, :PRRETIFICADORA,:PRCONTABILIZAFILIAL,:PRCODEMPPRINCIPALSCP);
    END
 
  DELETE FROM TMP_TCONF_CONTAS_ONLINE_TEMP WHERE ((bdCODMATRIZ = :prCODEMP) OR (BDCODMATRIZ = :PRCODEMPPRINCIPALSCP) ) AND bdREFERENCIA = :prREFERENCIA;
 
END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_CONTABILIZAR (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRULTCHAVE INTEGER,
    PRUSUARIO INTEGER,
    PRULTTRANSACAO INTEGER,
    PRRETIFICADORA INTEGER,
    PRDATACONTAB date = null,
    PRCODMATRIZ INTEGER = 0)
as
BEGIN
  -- Atualiza as chaves da contabilização...
  /*UPDATE TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t
  SET t.bdCHAVE = :prULTCHAVE-COALESCE((SELECT COUNT(1)
                                        FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP x
                                        WHERE x.bdCHAVE IS NULL
                                          AND x.bdCODMATRIZ = :prCODEMP
                                          AND x.bdREFERENCIA = :prREFERENCIA), 1)+1,
      t.bdTRANSACAO = :prULTTRANSACAO-COALESCE((SELECT COUNT(1)
                                                FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP x
                                                WHERE x.bdTRANSACAO IS NULL
                                                  AND x.bdCODMATRIZ = :prCODEMP
                                                  AND x.bdREFERENCIA = :prREFERENCIA), 1)+1
  WHERE t.bdCODMATRIZ = :prCODEMP
    AND t.bdREFERENCIA = :prREFERENCIA;*/

  SETORDEMSEQUENCIAL_STR(:prCODEMP);
  UPDATE TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t
  SET t.bdCHAVE = :prULTCHAVE-GETORDEMSEQUENCIAL_STR('CHAVE.'||:prCODEMP||'.'||:prREFERENCIA, :prCODEMP)+1,
      t.bdTRANSACAO = :prULTTRANSACAO-GETORDEMSEQUENCIAL_STR('TRANS.'||:prCODEMP||'.'||:prREFERENCIA, :prCODEMP)+1
  WHERE t.bdCODMATRIZ = :prCODEMP
    AND t.bdREFERENCIA = :prREFERENCIA;

  -- Caso a data esteja "NULL", poem ela no primeiro dia da referência...
  UPDATE TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t
  SET t.bdDATA = CAST(SUBSTRING(t.bdREFERENCIA FROM 5 FOR 2)||'-'||-- Mês
                 CASE -- Dia
                   WHEN (CAST(SUBSTRING(t.bdREFERENCIA FROM 5 FOR 2) as INTEGER) IN (1,3,5,7,8,10,12)) THEN '31-'
                   WHEN (CAST(SUBSTRING(t.bdREFERENCIA FROM 5 FOR 2) as INTEGER) IN (2)) THEN IIF((MOD(CAST(SUBSTRING(t.bdREFERENCIA FROM 1 FOR 4) as INTEGER), 4) = 0),'29-','28-') -- Anos bissexto
                 ELSE '30-'
                 END||
                 SUBSTRING(t.bdREFERENCIA FROM 1 FOR 4) AS DATE) -- Ano
  WHERE t.bdDATA IS NULL
    AND t.bdCODMATRIZ = :prCODEMP
    AND t.bdREFERENCIA = :prREFERENCIA;

  -- Grava a contabilização...
  INSERT INTO VSUC_EMPRESAS_TLAN(bdCODEMP, bdCHAVE, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdcodhist, bdCODTPHI, BDDATALANINICIAL, BDHORALANINICIAL)
  SELECT t.bdCODMATRIZ, t.bdCHAVE, t.bdCODPLAPADRAO, :prUSUARIO, t.bdDEBITO, t.bdCREDITO, t.bdCOMPL, IIF(:PRDATACONTAB IS NULL, t.bdDATA, :PRDATACONTAB), t.bdVALOR, t.bdTIPOLAN, t.bdDCTO, t.bdTRANSACAO, t.bdTRANFECHADA, t.bdcodhist, t.bdCODTPHI, CURRENT_DATE, CURRENT_TIME
  FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t
  WHERE t.bdCODMATRIZ = :prCODEMP
    AND t.bdREFERENCIA = :prREFERENCIA
  ORDER BY t.bdCODMATRIZ, t.bdCHAVE, t.bdTRANSACAO;

  -- Grava a contabilização...
  INSERT INTO TOL_VEF_EMP_TBLOCOMGER (bdCHAVE, bdCODPERIODO, bdCODEMP, bdCODMATRIZ, bdREFERENCIA, BDRETIFICADORA)
  SELECT t.bdCHAVE, 7 as bdCODPERIODO, t.bdCODMATRIZ as bdCODEMP, IIF(:PRCODMATRIZ > 0, :PRCODMATRIZ,t.bdCODMATRIZ) bdCODMATRIZ, t.bdREFERENCIA, :PRRETIFICADORA
  FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t
  WHERE t.bdCODMATRIZ = :prCODEMP
    AND t.bdREFERENCIA = :prREFERENCIA
  ORDER BY t.bdCODMATRIZ, t.bdCHAVE, t.bdTRANSACAO;

  -- Deleta os registros da tabela da contabilização...
  DELETE FROM TMP_VSUC_EMP_TLAN_BLOCOM_TEMP t
  WHERE t.bdCODMATRIZ = :prCODEMP
    AND t.bdREFERENCIA = :prREFERENCIA;

END^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_GERA_AJUSTES_M220 (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRWHEREEMPRESAS VARCHAR(10000),
    PRRETIFICADORA INTEGER,
    PRAJUSTESCP DM_BOOLEAN,
    PRCODEMPSO INTEGER = 0)
AS
DECLARE VARIABLE WCODIGO INTEGER;
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WGERARM220AUTO DM_BOOLEAN;
DECLARE VARIABLE WGERARM220TODOSPROD DM_BOOLEAN;
DECLARE VARIABLE WM220CODCSTFIL INTEGER;
DECLARE VARIABLE WM220CODNATRECFIL INTEGER;
DECLARE VARIABLE WM220NCMPRODFIL INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WCODCSOCIAL INTEGER;
DECLARE VARIABLE WVLRAJUPIS DM_NUMERIC_20MILHOES_2CASAS;
DECLARE VARIABLE WALIQPIS DM_NUMERIC_7_4_ALIQ;
DECLARE VARIABLE WVLRAJUCOF DM_NUMERIC_20MILHOES_2CASAS;
DECLARE VARIABLE WALIQCOF DM_NUMERIC_7_4_ALIQ;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WSQL VARCHAR(32750);
DECLARE VARIABLE WVLRAJUACRESPIS DM_NUMERIC_20MILHOES_2CASAS;
DECLARE VARIABLE WVLRAJUACRESCOF DM_NUMERIC_20MILHOES_2CASAS;
DECLARE VARIABLE WVLRAJUREDUPIS DM_NUMERIC_20MILHOES_2CASAS;
DECLARE VARIABLE WVLRAJUREDUCOF DM_NUMERIC_20MILHOES_2CASAS;
DECLARE VARIABLE WVLCONTDIFERPIS DM_NUMERIC_20MILHOES_2CASAS;
DECLARE VARIABLE WVLCONTDIFERCOF DM_NUMERIC_20MILHOES_2CASAS;
DECLARE VARIABLE WCONTRIRECPIS DM_NUMERIC_20MILHOES_2CASAS;
DECLARE VARIABLE WCONTRIRECCOF DM_NUMERIC_20MILHOES_2CASAS;
BEGIN

  /* Alt.: #242771 - Cria os lancamentos automaticos do M220/620 */
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDCODIGO, BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP INTO :wCODIGO, :wINCTRIB, :wCODCRIT;

  SELECT COALESCE(BDGERARM220TODOSPROD,'FALSE'), COALESCE(BDGERARM220AUTO,'FALSE'), BDM220CODCSTFIL
  FROM VEF_INT_TSPED_PIS_COFINS WHERE BDCODEMP = :prCODEMP AND BDCODIGO = :wCODIGO
  INTO :WGERARM220TODOSPROD, :WGERARM220AUTO, :WM220CODCSTFIL;

  IF ((:WGERARM220AUTO IS NULL) OR (:WGERARM220AUTO <> 'TRUE')) THEN
    EXIT;

  SELECT FIRST 1 BDM220CODNATRECFIL
  FROM VEF_INT_TSPED_PIS_COFINS_NATREC WHERE BDCODEMP = :prCODEMP AND BDCODIGO = :wCODIGO
  INTO :wM220CODNATRECFIL;

  SELECT FIRST 1 BDM220NCMPRODFIL
  FROM VEF_INT_TSPED_PIS_COFINS_NCM WHERE BDCODEMP = :prCODEMP AND BDCODIGO = :wCODIGO
  INTO :wM220NCMPRODFIL;

  DELETE FROM TMP_TAJUAPUPCM220620_BLOCOM_PROD;
  IF ((:wM220NCMPRODFIL IS NOT NULL) AND (:wM220NCMPRODFIL > 0)) THEN
    BEGIN
      -- Alt.: #244877 - Essa consulta pode ficar lenta, por isso filtra primeiro todos os produtos por NCMs e depois so usa esses produtos no filtro...
      wSQL =         'INSERT INTO TMP_TAJUAPUPCM220620_BLOCOM_PROD(bdCODEMP,bdCODPROD) ';
      wSQL = wSQL || 'SELECT DISTINCT prod.bdCODEMP, prod.bdCODPROD ';
      wSQL = wSQL || 'FROM TCADPRO_VINC prod ';
      wSQL = wSQL || 'JOIN(SELECT ncm.bdNCMPROD ';
      wSQL = wSQL || '     FROM (SELECT ncm.bdCLASSIFICACAO ';
      wSQL = wSQL || '           FROM TNCM ncm ';
      wSQL = wSQL || '           JOIN VEF_INT_TSPED_PIS_COFINS_NCM f11 ON(f11.bdM220NCMPRODFIL = ncm.bdNCMPROD) ';
      wSQL = wSQL || '           WHERE f11.bdCODEMP = '||:prCODEMP||' ';
      wSQL = wSQL || '             AND f11.bdCODIGO = '||:wCODIGO||' ) F11 ';
      wSQL = wSQL || '     JOIN TNCM ncm ON(ncm.bdCLASSIFICACAO STARTING WITH f11.bdCLASSIFICACAO) ) ncm ON (ncm.bdNCMPROD = prod.bdNCMPROD) ';
      wSQL = wSQL || 'WHERE '||:PRWHEREEMPRESAS||'; ';

      EXECUTE STATEMENT ( :wSQL );
    END

  DELETE FROM TMP_VEF_EMP_TAJUAPUPCM220620_BLOCOM ;

  wSQL =         'INSERT INTO TMP_VEF_EMP_TAJUAPUPCM220620_BLOCOM (bdCODMATRIZ,bdCODEMP, bdREFERENCIA, bdCHAVE, bdCODAJUEFDC, bdTIPOAJUSTE, bdNUMERODOC, bdDATAREF, ';
  wSQL = wSQL || '                                                 bdCODTIPO, bdTIPOPROD, bdCODSCP, bdREFSOC, bdCODCSOCIAL, bdDESCRICAO, ';
  wSQL = wSQL || '                                                 bdALIQPIS, bdALIQCOFINS, bdVLRAJUPIS, bdVLRAJUCOFINS) ';
  wSQL = wSQL || 'SELECT '||:prCODEMP||',s.bdCODEMP, s.bdREFLAN, GETORDEMSEQUENCIAL_STR(''M220.''||''.''||s.bdCODEMP||''.''||'||:PRREFERENCIA||'/*||''.''||s.bdCHAVENFE*/, '||:PRCODEMP||'), ';
  wSQL = wSQL || '       CASE WHEN p.bdCODCSTPIS = 6 THEN 11 '; -- 11 - Ajuste redução linear dos incentivos e benef. da nat. tributária - alíquota zero
  wSQL = wSQL || '       ELSE 10 END AS bdCODAJUEFDC, ';        -- 10 - Ajuste redução linear dos incentivos e benef. de nat. tributária - isenção
  wSQL = wSQL || '       1 AS bdTIPOAJUSTE, s.bdCHAVENFE AS bdNUMERODOC, s.bdDATAEMISSAO AS bdDATAREF, ';
  wSQL = wSQL || '       150 AS bdCODTIPO, 0 AS bdTIPOPROD, i.bdCODSCP, i.bdREFSOC, ';
  wSQL = wSQL || '       CASE WHEN '||:wINCTRIB||' = 2 THEN 7  '; -- 51 - Contribuição cumulativa apurada a alíquota básica
  wSQL = wSQL || '       ELSE 1 END AS bdCODCSOCIAL,  ';          -- 01 - Contribuição não-cumulativa apurada a alíquota básica
  wSQL = wSQL || '       ''Redução linear de benefícios fiscais - LC 224/2025'' AS bdDESCRICAO, ';
                         -- Alt.: #242771 - As alíquotas são geradas "cheias" para vincular corretamente na apuração, mas o calculo é feito com 10% dela...
  wSQL = wSQL || '       CASE WHEN '||:wINCTRIB||' = 2 THEN 0.65 '; -- 51 - Regime cumulativo    : a alíquota do PIS será 0,065 e do Cofins 0,30
  wSQL = wSQL || '       ELSE 1.65 END AS bdALIQPIS, ';             -- 01 - Regime não cumulativo: a alíquota do PIS será 0,165 e do Cofins 0,7600
  wSQL = wSQL || '       CASE WHEN '||:wINCTRIB||' = 2 THEN 3.0 ';  -- 51 - Regime cumulativo    : a alíquota do PIS será 0,065 e do Cofins 0,30
  wSQL = wSQL || '       ELSE 7.6 END AS bdALIQCOFINS, ';           -- 01 - Regime não cumulativo: a alíquota do PIS será 0,165 e do Cofins 0,7600
  wSQL = wSQL || '       CASE WHEN '||:wINCTRIB||' = 2 THEN 0.00065 ';
  wSQL = wSQL || '       ELSE 0.00165 END * SUM(COALESCE(IIF(p.bdBCPIS    > 0, p.bdBCPIS   , NULL), p.bdVLRITEM,0)) AS bdVLRAJUPIS, ';
  wSQL = wSQL || '       CASE WHEN '||:wINCTRIB||' = 2 THEN 0.003 ';
  wSQL = wSQL || '       ELSE 0.0076 END  * SUM(COALESCE(IIF(p.bdBCCOFINS > 0, p.bdBCCOFINS, NULL), p.bdVLRITEM,0)) AS bdVLRAJUCOFINS ';
  wSQL = wSQL || 'FROM (SELECT s.bdCODEMP, s.bdCHAVE, s.bdREFLAN, s.bdCHAVENFE, s.bdDATAEMISSAO ';
  wSQL = wSQL || '      FROM VEF_EMP_TMOVSAI s ';
  wSQL = wSQL || '      WHERE ' || :PRWHEREEMPRESAS;
  wSQL = wSQL || '        AND s.bdREFLAN = ' || :prREFERENCIA;
  wSQL = wSQL || '        AND s.bdCODSITNF NOT IN(2,3,4,5) ';
  IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
    wSQL = wSQL || '        AND s.bdCONDPGTO <> 1 ';
  wSQL = wSQL || '        AND s.bdMODELO IN(55,65) ) s ';
  wSQL = wSQL || 'JOIN VEF_EMP_TMOVSAIITENS i ON(i.bdCODEMP = s.bdCODEMP AND i.bdCHAVE = s.bdCHAVE) ';
  wSQL = wSQL || 'JOIN VEF_EMP_TMOVPROSAI p ON(p.bdCODEMP = i.bdCODEMP AND p.bdCHAVE = i.bdCHAVE AND p.bdORDEM = i.bdORDEM) ';
  wSQL = wSQL || 'JOIN TCADPRO_VINC vinc ON (vinc.bdCODEMP = p.bdCODEMP AND vinc.bdCODPROD = p.bdCODPROD) ';
  wSQL = wSQL || 'WHERE ((p.bdCODCSTPIS IN(6,7)) OR (p.bdCODCSTCOF IN(6,7))) ';

  IF (:WGERARM220TODOSPROD <> 'TRUE') THEN -- Aplicar para todos os produtos CST 06 e 07
    BEGIN
      IF ((:WM220CODCSTFIL IS NOT NULL) AND (:WM220CODCSTFIL > 0)) THEN
        wSQL = wSQL || '  AND ((p.bdCODCSTPIS IN('||:WM220CODCSTFIL||')) OR (p.bdCODCSTCOF IN('||:WM220CODCSTFIL||'))) '; -- Filtro CST

      IF ((:wM220CODNATRECFIL IS NOT NULL) AND (:wM220CODNATRECFIL > 0)) THEN
        wSQL = wSQL || '  AND ((SELECT FIRST 1 BDM220CODNATRECFIL FROM VEF_INT_TSPED_PIS_COFINS_NATREC n '||
                              ' WHERE n.bdCODEMP = '||:prCODEMP||' AND n.bdCODIGO = '||:wCODIGO||' AND n.bdM220CODNATRECFIL = p.bdCODNATREC) IS NOT NULL) '; -- Filtro Natureza de receitas

      IF ((:wM220NCMPRODFIL IS NOT NULL) AND (:wM220NCMPRODFIL > 0)) THEN
        wSQL = wSQL || '  AND p.bdCODPROD IN(SELECT bdCODPROD FROM TMP_TAJUAPUPCM220620_BLOCOM_PROD WHERE bdCODEMP = s.bdCODEMP) '; -- Filtro NCMs

    END

  wSQL = wSQL || 'GROUP BY s.bdCODEMP, s.bdREFLAN, s.bdCHAVENFE, s.bdDATAEMISSAO, i.bdCODSCP, i.bdREFSOC, p.bdCODCSTPIS; ';

  EXECUTE STATEMENT ( :wSQL );

  IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
    BEGIN
      wSQL =         'INSERT INTO TMP_VEF_EMP_TAJUAPUPCM220620_BLOCOM (bdCODMATRIZ,bdCODEMP, bdREFERENCIA, bdCHAVE, bdCODAJUEFDC, bdTIPOAJUSTE, bdNUMERODOC, bdDATAREF, ';
      wSQL = wSQL || '                                                 bdCODTIPO, bdTIPOPROD, bdCODSCP, bdREFSOC, bdCODCSOCIAL, bdDESCRICAO, ';
      wSQL = wSQL || '                                                 bdALIQPIS, bdALIQCOFINS, bdVLRAJUPIS, bdVLRAJUCOFINS) ';
      wSQL = wSQL || 'SELECT '||:prCODEMP||',s.bdCODEMP, (SELECT bdDATA FROM SP_PARSE_DATE(par.bdDATAPGTOPAR, ''YYYYMM'')) bdREFLAN, ';
      wSQL = wSQL || '       GETORDEMSEQUENCIAL_STR(''M220.''||''.''||s.bdCODEMP||''.''||'||:PRREFERENCIA||'/*||''.''||s.bdCHAVENFE*/, '||:PRCODEMP||'), ';
      wSQL = wSQL || '       CASE WHEN p.bdCODCSTPIS = 6 THEN 11 '; -- 11 - Ajuste redução linear dos incentivos e benef. da nat. tributária - alíquota zero
      wSQL = wSQL || '       ELSE 10 END AS bdCODAJUEFDC, ';        -- 10 - Ajuste redução linear dos incentivos e benef. de nat. tributária - isenção
      wSQL = wSQL || '       1 AS bdTIPOAJUSTE, s.bdCHAVENFE AS bdNUMERODOC, s.bdDATAEMISSAO AS bdDATAREF, ';
      wSQL = wSQL || '       150 AS bdCODTIPO, 0 AS bdTIPOPROD, i.bdCODSCP, i.bdREFSOC, ';
      wSQL = wSQL || '       CASE WHEN '||:wINCTRIB||' = 2 THEN 7  '; -- 51 - Contribuição cumulativa apurada a alíquota básica
      wSQL = wSQL || '       ELSE 1 END AS bdCODCSOCIAL,  ';          -- 01 - Contribuição não-cumulativa apurada a alíquota básica
      wSQL = wSQL || '       ''Redução linear de benefícios fiscais - LC 224/2025'' AS bdDESCRICAO, ';
                             -- Alt.: #242771 - As alíquotas são geradas "cheias" para vincular corretamente na apuração, mas o calculo é feito com 10% dela...
      wSQL = wSQL || '       CASE WHEN '||:wINCTRIB||' = 2 THEN 0.65 '; -- 51 - Regime cumulativo    : a alíquota do PIS será 0,065 e do Cofins 0,30
      wSQL = wSQL || '       ELSE 1.65 END AS bdALIQPIS, ';             -- 01 - Regime não cumulativo: a alíquota do PIS será 0,165 e do Cofins 0,7600
      wSQL = wSQL || '       CASE WHEN '||:wINCTRIB||' = 2 THEN 3.0 ';  -- 51 - Regime cumulativo    : a alíquota do PIS será 0,065 e do Cofins 0,30
      wSQL = wSQL || '       ELSE 7.6 END AS bdALIQCOFINS, ';           -- 01 - Regime não cumulativo: a alíquota do PIS será 0,165 e do Cofins 0,7600
      wSQL = wSQL || '       CASE WHEN '||:wINCTRIB||' = 2 THEN 0.00065 ';
      wSQL = wSQL || '       ELSE 0.00165 END * SUM(CAST(CAST(COALESCE(IIF(p.bdBCPIS    > 0, p.bdBCPIS   , NULL), p.bdVLRITEM, 0) AS NUMERIC(15,4)) * '||
                                                  '(CAST(par.bdVALORPGTOPAR AS NUMERIC(15,6)) / IIF(i.bdVLRCONTABTOTAL = 0, 1, i.bdVLRCONTABTOTAL)) AS DM_NUMERIC_15_2)) AS BDVLRAJUPIS, ';
      wSQL = wSQL || '       CASE WHEN '||:wINCTRIB||' = 2 THEN 0.003 ';
      wSQL = wSQL || '       ELSE 0.0076 END  * SUM(CAST(CAST(COALESCE(IIF(p.bdBCCOFINS > 0, p.bdBCCOFINS, NULL), p.bdVLRITEM,0) AS NUMERIC(15,4)) * '||
                                                  '(CAST(par.bdVALORPGTOPAR AS NUMERIC(15,6)) / IIF(i.bdVLRCONTABTOTAL = 0, 1, i.bdVLRCONTABTOTAL)) AS DM_NUMERIC_15_2)) AS bdVLRAJUCOFINS ';
      wSQL = wSQL || 'FROM (SELECT s.bdCODEMP, s.bdCHAVE, s.bdREFLAN, s.bdCHAVENFE, s.bdDATAEMISSAO ';
      wSQL = wSQL || '      FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL || '      WHERE ' || :PRWHEREEMPRESAS;
      wSQL = wSQL || '        AND s.bdCODSITNF NOT IN(2,3,4,5) ';
      wSQL = wSQL || '        AND s.bdCONDPGTO = 1 ';
      wSQL = wSQL || '        AND s.bdMODELO IN(55,65) ) s ';
      wSQL = wSQL || 'JOIN (SELECT i.bdCODEMP, i.bdCHAVE, i.bdORDEM,i.bdCODSCP, i.bdREFSOC, SUM(i.bdVLRCONTAB) AS bdVLRCONTABTOTAL '||
                     '      FROM VEF_EMP_TMOVSAIITENS i '||
                     '      LEFT OUTER JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT) '||
                     '      WHERE nat.bdLANCPARCELAMENTO = ''TRUE'' '|| -- Deve considerar apenas o valor contabil de CFOPS que gerem as parcelas, nesses casos o valor contábil e menor que o da nota...
                     '      GROUP BY i.bdCODEMP, i.bdCHAVE, i.bdORDEM,i.bdCODSCP, i.bdREFSOC) i on (i.bdCODEMP = s.bdCODEMP AND i.bdCHAVE = s.bdCHAVE) ';
      wSQL = wSQL || 'JOIN VEF_EMP_TMOVPROSAI p ON(p.bdCODEMP = i.bdCODEMP AND p.bdCHAVE = i.bdCHAVE AND p.bdORDEM = i.bdORDEM) ';
      wSQL = wSQL || 'JOIN TCADPRO_VINC vinc ON (vinc.bdCODEMP = p.bdCODEMP AND vinc.bdCODPROD = p.bdCODPROD) ';
      wSQL = wSQL || 'JOIN VEF_EMP_TMOVSAIPARPGTO PAR ON(PAR.BDCODEMP = S.BDCODEMP AND PAR.BDCHAVE = S.BDCHAVE AND PAR.BDCODTIPOBAIXA = 1 AND '|| -- Apenas Pagamento/Recebimento
                                                        '(CAST((SELECT bdDATA FROM SP_PARSE_DATE(par.bdDATAPGTOPAR, ''YYYYMM'')) AS INTEGER) = '||:prREFERENCIA||') ) ';
      wSQL = wSQL || 'WHERE ((p.bdCODCSTPIS IN(6,7)) OR (p.bdCODCSTCOF IN(6,7))) ';

      IF (:WGERARM220TODOSPROD <> 'TRUE') THEN -- Aplicar para todos os produtos CST 06 e 07
        BEGIN
          IF ((:WM220CODCSTFIL IS NOT NULL) AND (:WM220CODCSTFIL > 0)) THEN
            wSQL = wSQL || '  AND ((p.bdCODCSTPIS IN('||:WM220CODCSTFIL||')) OR (p.bdCODCSTCOF IN('||:WM220CODCSTFIL||'))) '; -- Filtro CST

          IF ((:wM220CODNATRECFIL IS NOT NULL) AND (:wM220CODNATRECFIL > 0)) THEN
            wSQL = wSQL || '  AND ((SELECT FIRST 1 BDM220CODNATRECFIL FROM VEF_INT_TSPED_PIS_COFINS_NATREC n '||
                                  ' WHERE n.bdCODEMP = '||:prCODEMP||' AND n.bdCODIGO = '||:wCODIGO||' AND n.bdM220CODNATRECFIL = p.bdCODNATREC) IS NOT NULL) '; -- Filtro Natureza de receitas

          IF ((:wM220NCMPRODFIL IS NOT NULL) AND (:wM220NCMPRODFIL > 0)) THEN
            wSQL = wSQL || '  AND p.bdCODPROD IN(SELECT bdCODPROD FROM TMP_TAJUAPUPCM220620_BLOCOM_PROD WHERE bdCODEMP = s.bdCODEMP) '; -- Filtro NCMs

        END

      wSQL = wSQL || 'GROUP BY s.bdCODEMP, s.bdREFLAN, s.bdCHAVENFE, s.bdDATAEMISSAO, i.bdCODSCP, i.bdREFSOC, p.bdCODCSTPIS, par.bdDATAPGTOPAR; ';

      EXECUTE STATEMENT ( :wSQL );

    END

  /* Esses regsitros são filhos do M210/610, caso eles não existam na apuracao, insere eles...
  Aqui a regra é clara Arnaldo, vai buscar a mesma aliquota nos registros M210/610, se não existir vai inserir um registro, se existir, deve atualizar... */

  wSQL =         'SELECT m.bdCODEMP, m.bdREFERENCIA, ';
  wSQL = wSQL || '       CASE WHEN '||:wINCTRIB||' = 2 THEN 7 '; -- 51 - Contribuição cumulativa apurada a alíquota básica
  wSQL = wSQL || '       ELSE 1 END AS bdCODCSOCIAL, ';          -- 01 - Contribuição não-cumulativa apurada a alíquota básica
  wSQL = wSQL || '       SUM(COALESCE(m.bdVLRAJUPIS,0)), m.bdALIQPIS, SUM(COALESCE(m.bdVLRAJUCOFINS,0)), m.bdALIQCOFINS ';
  wSQL = wSQL || 'FROM TMP_VEF_EMP_TAJUAPUPCM220620_BLOCOM m ';
  wSQL = wSQL || 'WHERE ' || :PRWHEREEMPRESAS;
  wSQL = wSQL || '  AND m.bdREFERENCIA = ' || :prREFERENCIA;
  wSQL = wSQL || '  AND ((m.bdVLRAJUPIS > 0) OR (m.bdVLRAJUCOFINS > 0)) ';
  wSQL = wSQL || 'GROUP BY m.bdCODEMP, m.bdCODEMP, m.bdREFERENCIA, m.bdALIQPIS, m.bdALIQPIS, m.bdALIQCOFINS ';

  FOR
    EXECUTE STATEMENT ( :wSQL )
    INTO :wCODEMP, :wREFERENCIA, :wCODCSOCIAL, :wVLRAJUPIS, :wALIQPIS, :wVLRAJUCOF, :wALIQCOF
  DO
    BEGIN
      IF (:wVLRAJUPIS > 0) THEN
        BEGIN
          wCHAVE = NULL;

          -- Alt.: #245644 - Se inserir, deve jogar o valor dos acrésimos e reduções dos lançamentos que já existem...
          SELECT SUM(COALESCE(IIF(x.bdTIPOAJUSTE = 0 AND x.bdALIQPIS = :wALIQPIS,x.bdVLRAJUPIS,0),0)), SUM(COALESCE(IIF(x.bdTIPOAJUSTE = 0 AND x.bdALIQCOFINS = :wALIQCOF,x.bdVLRAJUCOFINS,0),0)),
                 SUM(COALESCE(IIF(x.bdTIPOAJUSTE = 1 AND x.bdALIQPIS = :wALIQPIS,x.bdVLRAJUPIS,0),0)), SUM(COALESCE(IIF(x.bdTIPOAJUSTE = 1 AND x.bdALIQCOFINS = :wALIQCOF,x.bdVLRAJUCOFINS,0),0))
          FROM VEF_EMP_TAJUAPUPCM220620 x
          WHERE x.bdCODEMP     = :wCODEMP     AND x.bdREFERENCIA = :prREFERENCIA
            AND x.bdCODCSOCIAL = :wCODCSOCIAL
            AND (x.bdALIQPIS = :wALIQPIS OR x.bdALIQCOFINS = :wALIQCOF)
          INTO :WVLRAJUREDUPIS,:WVLRAJUREDUCOF,:WVLRAJUACRESPIS,:WVLRAJUACRESCOF;

          -- Alt.: #245644 - Se inserir, deve Buscar os valores do M230 também...
          SELECT SUM(COALESCE(IIF(x.bdALIQPIS = :wALIQPIS,x.bdVLRCONDEFPIS,0),0)), -- "Valor contribuição diferida"
                 SUM(COALESCE(IIF(x.bdALIQCOFINS = :wALIQCOF,x.bdVLRCONDEFCOFINS,0),0)) 
          FROM VEF_EMP_TINFADIDEFM230630 x
          WHERE x.bdCODEMP     = :wCODEMP     AND x.bdREFERENCIA = :prREFERENCIA
            AND x.bdCODCSOCIAL = :wCODCSOCIAL
            AND (x.bdALIQPIS = :wALIQPIS OR x.bdALIQCOFINS = :wALIQCOF)
          INTO :WVLCONTDIFERPIS, :WVLCONTDIFERCOF;

          -- Alt.: #245644 - Se inserir, deve Buscar os valores do M300 também, Deus do céu...
          SELECT SUM(COALESCE(IIF(x.bdALIQPIS    = :wALIQPIS,COALESCE(x.bdVLRCONTRIPIS,0)    - COALESCE(x.bdVLRCREPIS,0),0),0)), -- "Contribuição a recolher:" não grava o campo, só aparece na tela...
                 SUM(COALESCE(IIF(x.bdALIQCOFINS = :wALIQCOF,COALESCE(x.bdVLRCONTRICOFINS,0) - COALESCE(x.bdVLRCRECOFINS,0),0),0))
          FROM VEF_EMP_TINFADIDEFM300M700 x
          WHERE x.bdCODEMP     = :wCODEMP     AND x.bdREFERENCIA = (SELECT BDREF FROM DEC_REF(:prREFERENCIA))
            AND x.bdCODCSOCIAL = :wCODCSOCIAL
            AND (x.bdALIQPIS = :wALIQPIS OR x.bdALIQCOFINS = :wALIQCOF)
          INTO :WCONTRIRECPIS, :WCONTRIRECCOF;

          SELECT FIRST 1 x.bdCHAVE FROM VEF_EMP_TBLOCOM210_M610 x
          WHERE x.bdCODQUADRO = 19             AND x.bdCODPERIODO = 7
            AND x.bdCODEMP = :wCODEMP          AND x.bdCODMATRIZ = :prCODEMP
            AND x.bdREFERENCIA = :prREFERENCIA AND x.bdRETIFICADORA = :PRRETIFICADORA
            AND x.bdCODCSOCIAL = :wCODCSOCIAL  AND x.bdALIQ = :wALIQPIS
          INTO :wCHAVE;

          IF (:wCHAVE IS NULL) THEN
            BEGIN
              INSERT INTO VEF_EMP_TBLOCOM210_M610(bdCODQUADRO, bdCODPERIODO, bdCODEMP, bdCODMATRIZ, bdREFERENCIA, bdRETIFICADORA, bdTIPOPROD, bdALIQ_QUANT, bdCHAVE, bdCODCSOCIAL, /*bdVL_CONT_APUR,*/ bdALIQ, bdVL_AJUS_ACRES, bdVL_AJUS_REDUC, bdVL_CONT_PER,
                                                  bdVL_CONT_DIFER,bdVL_CONT_DIFER_ANT)
              VALUES (19, 7, :wCODEMP, :prCODEMP, :wREFERENCIA, :PRRETIFICADORA, 0, 0,
                      GETORDEMSEQUENCIAL_STR('M210.'||7||'.'||:wCODEMP||'.'||:wCODEMP||'.19.'||:prREFERENCIA||'.'||:PRCODEMPSO, :prCODEMP),
                      :wCODCSOCIAL, /*:wVLRAJUPIS,*/ :wALIQPIS, :wVLRAJUPIS+COALESCE(:WVLRAJUACRESPIS,0),COALESCE(:WVLRAJUREDUPIS,0),
                      :wVLRAJUPIS+(COALESCE(:WVLRAJUACRESPIS,0)-COALESCE(:WVLRAJUREDUPIS,0))+(COALESCE(:WCONTRIRECPIS,0)-COALESCE(:WVLCONTDIFERPIS,0)),
                      :WVLCONTDIFERPIS, :WCONTRIRECPIS);
            END
          ELSE
            BEGIN
              UPDATE VEF_EMP_TBLOCOM210_M610 x
              SET x.BDVL_AJUS_ACRES = COALESCE(x.BDVL_AJUS_ACRES,0) + :wVLRAJUPIS, -- Total dos ajustes de acréscimo
                  x.BDVL_CONT_PER   = COALESCE(x.BDVL_CONT_PER,0)   + :wVLRAJUPIS  -- Total da contribuição
              WHERE (x.bdCODQUADRO = 19) AND (x.bdCODPERIODO = 7)
                AND (x.bdCODEMP = :wCODEMP) AND (x.bdCODMATRIZ = :prCODEMP)
                AND (x.bdREFERENCIA = :wREFERENCIA) AND (x.bdRETIFICADORA = :PRRETIFICADORA)
                AND (x.bdCHAVE = :wCHAVE);
            END
        END

      IF (:wVLRAJUCOF > 0) THEN
        BEGIN
          wCHAVE = NULL;

          SELECT FIRST 1 x.bdCHAVE FROM VEF_EMP_TBLOCOM210_M610 x
          WHERE x.bdCODQUADRO = 37             AND x.bdCODPERIODO = 7
            AND x.bdCODEMP = :wCODEMP          AND x.bdCODMATRIZ = :prCODEMP
            AND x.bdREFERENCIA = :prREFERENCIA AND x.bdRETIFICADORA = :PRRETIFICADORA
            AND x.bdCODCSOCIAL = :wCODCSOCIAL  AND x.bdALIQ = :wALIQCOF
          INTO :wCHAVE;
    
          IF (:wCHAVE IS NULL) THEN
            BEGIN
              INSERT INTO VEF_EMP_TBLOCOM210_M610(bdCODQUADRO, bdCODPERIODO, bdCODEMP, bdCODMATRIZ, bdREFERENCIA, bdRETIFICADORA, bdTIPOPROD, bdALIQ_QUANT, bdCHAVE, bdCODCSOCIAL, /*bdVL_CONT_APUR,*/ bdALIQ, bdVL_AJUS_ACRES, bdVL_AJUS_REDUC, bdVL_CONT_PER,
                                                 bdVL_CONT_DIFER,bdVL_CONT_DIFER_ANT)
              VALUES (37, 7, :wCODEMP, :prCODEMP, :wREFERENCIA, :PRRETIFICADORA, 0, 0,
                      GETORDEMSEQUENCIAL_STR('M610.'||7||'.'||:wCODEMP||'.'||:wCODEMP||'.37.'||:prREFERENCIA||'.'||:PRCODEMPSO, :prCODEMP),
                      :wCODCSOCIAL, /*:wVLRAJUCOF,*/ :wALIQCOF, :wVLRAJUCOF+COALESCE(:WVLRAJUACRESCOF,0),COALESCE(:WVLRAJUREDUCOF,0),
                      :wVLRAJUCOF+(COALESCE(:WVLRAJUACRESCOF,0)-COALESCE(:WVLRAJUREDUCOF,0))+(COALESCE(:WCONTRIRECCOF,0)-COALESCE(:WVLCONTDIFERCOF,0)),
                      :WVLCONTDIFERCOF, :WCONTRIRECCOF);
            END
          ELSE
            BEGIN
              UPDATE VEF_EMP_TBLOCOM210_M610 x
              SET x.BDVL_AJUS_ACRES = COALESCE(x.BDVL_AJUS_ACRES,0) + :wVLRAJUCOF, -- Total dos ajustes de acréscimo
                  x.BDVL_CONT_PER   = COALESCE(x.BDVL_CONT_PER,0)   + :wVLRAJUCOF  -- Total da contribuição
              WHERE (x.bdCODQUADRO = 37) AND (x.bdCODPERIODO = 7)
                AND (x.bdCODEMP = :wCODEMP) AND (x.bdCODMATRIZ = :prCODEMP)
                AND (x.bdREFERENCIA = :wREFERENCIA) AND (x.bdRETIFICADORA = :PRRETIFICADORA)
                AND (x.bdCHAVE = :wCHAVE);
            END
        END
    END

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_REGAUTO (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRRETIFICADORA INTEGER,
    PRULTCHAVEM220 INTEGER)
AS
BEGIN

  SETORDEMSEQUENCIAL_STR(:prCODEMP);

  -- Atualiza as chaves da tabela
  UPDATE TMP_VEF_EMP_TAJUAPUPCM220620_BLOCOM m
  SET m.bdCHAVE = :PRULTCHAVEM220-GETORDEMSEQUENCIAL_STR('CHAVE.M220.'||:prCODEMP||'.'||:prREFERENCIA, :prCODEMP)+1
  WHERE m.bdCODEMP = :prCODEMP
    AND m.bdREFERENCIA = :prREFERENCIA;

  -- Grava o registro na tabela do M220/620
  INSERT INTO VEF_EMP_TAJUAPUPCM220620(bdCODEMP,bdREFERENCIA,bdCHAVE,bdCODAJUEFDC,bdCODCSOCIAL,bdALIQPIS,bdALIQCOFINS,
                                       bdTIPOAJUSTE,bdNUMERODOC,bdDATAREF,bdDESCRICAO,bdVLRAJUPIS,bdVLRAJUCOFINS,bdCODTIPO,bdCODSCP,bdREFSOC,bdTIPOPROD)
  SELECT m.bdCODEMP,m.bdREFERENCIA,m.bdCHAVE,m.bdCODAJUEFDC,m.bdCODCSOCIAL,(m.bdALIQPIS/10),(m.bdALIQCOFINS/10), -- Alt.: #242771 - No lancamento do M220/620, grava a aliquota com apenas 10% dela...
         m.bdTIPOAJUSTE,m.bdNUMERODOC,m.bdDATAREF,m.bdDESCRICAO,m.bdVLRAJUPIS,m.bdVLRAJUCOFINS,m.bdCODTIPO,m.bdCODSCP,m.bdREFSOC,m.bdTIPOPROD
  FROM TMP_VEF_EMP_TAJUAPUPCM220620_BLOCOM m
  WHERE m.bdCODEMP = :prCODEMP
    AND m.bdREFERENCIA = :prREFERENCIA;

  -- Grava a TOL entre apuracao e lancamento do M220/620
  INSERT INTO TOL_VEF_EMP_TBLOCOMGER_M220(bdCODEMP,bdCODMATRIZ,bdCODPERIODO,bdREFERENCIA,bdRETIFICADORA,bdCODEMPM220,bdCHAVE)
  SELECT m.bdCODEMP,m.bdCODMATRIZ,7 AS bdCODPERIODO,m.bdREFERENCIA, :PRRETIFICADORA,m.bdCODEMP,m.bdCHAVE
  FROM TMP_VEF_EMP_TAJUAPUPCM220620_BLOCOM m
  WHERE m.bdCODEMP = :prCODEMP
    AND m.bdREFERENCIA = :prREFERENCIA;

  -- Deleta os registros da tabela temporaria
  DELETE FROM TMP_VEF_EMP_TAJUAPUPCM220620_BLOCOM t
  WHERE t.bdCODEMP = :prCODEMP
    AND t.bdREFERENCIA = :prREFERENCIA;

END
^

create or alter procedure SP_APURACAO_BLOCOM_0110 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer)
as
declare variable WINCTRIB integer;
declare variable WSQL varchar(32750);
declare variable WRBNCUMTRIBMI numeric(15,2);
declare variable WRBNCUMNTMI numeric(15,2);
declare variable WRBNCUMEXP numeric(15,2);
declare variable WRBCUM numeric(15,2);
declare variable WCODEMPSCP integer;
BEGIN
  -- Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  if (:PRAJUSTESCP = 'FALSE') then
    begin
      -- Incidência tributária
      SELECT BDINCTRIB+1 FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP INTO :wINCTRIB;
    
      -- Obtém os valores das formulas apuradas
      wSQL =       'SELECT ';
      IF (:wINCTRIB IN (1,3)) THEN
        wSQL = wSQL||'       COALESCE(BDRBNCUMTRIBMI, 0) as BDRBNCUMTRIBMI, COALESCE(BDRBNCUMNTMI, 0) as BDRBNCUMNTMI, COALESCE(BDRBNCUMEXP, 0) as BDRBNCUMEXP, ';
      ELSE
        wSQL = wSQL||'       0 as BDRBNCUMTRIBMI, 0 as BDRBNCUMNTMI, 0 as BDRBNCUMEXP, ';
    
      IF (:wINCTRIB IN (2,3)) THEN
        wSQL = wSQL||'       COALESCE(BDRBCUM, 0) as BDRBCUM ';
      ELSE
        wSQL = wSQL||'       0 as BDRBCUM ';
    
      wSQL = wSQL||'FROM TMP_VEF_EMP_TBLOCOM_0110_TEMP aux ';
      wSQL = wSQL||'WHERE aux.BDCODEMP = '||:prCODEMP;
      wSQL = wSQL||'  AND aux.BDREFERENCIA = '||:prREFERENCIA;
    
      EXECUTE STATEMENT ( wSQL )
      INTO :wRBNCUMTRIBMI, :wRBNCUMNTMI, :wRBNCUMEXP, :wRBCUM;
    
      /* 34 - Contribuição não cumulativa
         Tributada no mercado interno */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 34, 1, COALESCE(:wRBNCUMTRIBMI,0), :PRRETIFICADORA);
    
      /* 34 - Contribuição não cumulativa
         Não Tributada no mercado interno */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 34, 2, COALESCE(:wRBNCUMNTMI,0), :PRRETIFICADORA);
    
      /* 34 - Contribuição não cumulativa
         Exportação */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 34, 3, COALESCE(:wRBNCUMEXP,0), :PRRETIFICADORA);
    
      /* 35 - Contribuição cumulativa */
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 35, 1, COALESCE(:wRBCUM,0), :PRRETIFICADORA);
    
      /* 36 - Contribuição Total (Valores não cumulativos + cumulativos) */
      -- Obtém os valores das formulas apuradas
      SELECT SUM(BDVALOR)
      FROM VEF_EMP_TBLOCOMGERREG aux
      WHERE (aux.BDCODQUADRO IN (34,35)) /* 34 - Contribuição não cumulativa / 35 - Contribuição cumulativa */
        AND aux.BDCODEMP = :prCODEMP
        AND aux.BDREFERENCIA = :prREFERENCIA
        AND AUX.BDRETIFICADORA = :PRRETIFICADORA
      INTO :wRBNCUMTRIBMI;
    
      INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                 VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 36, 1, COALESCE(:wRBNCUMTRIBMI,0), :PRRETIFICADORA);
    end
  else
    BEGIN
      /* Camilla M. SCP - Sociedade em conta de participação
         Nas SCPs não vai ter valor de contribuição, então fazer registros zerados */
      FOR SELECT SCP.BDCODEMPSCP BDCODEMP FROM TEMPRESAS_SCP SCP
          --WHERE SCP.BDCODEMP = :prCODEMP
          WHERE scp.BDCODEMP in (SELECT ex.BDCODEMP
                                 FROM TEMPRESAS ex
                                 WHERE ex.BDCODEMP = :prCODEMP
                                    OR ex.BDCODMATRIZ = :prCODEMP)
            AND (SCP.BDCODEMPSCP IS NOT NULL AND SCP.BDCODEMPSCP > 0)
            AND (SCP.BDDATAFINAL IS NULL OR (SELECT bdAAAAMM FROM AAAAMM(SCP.BDDATAFINAL)) >= :prREFERENCIA)
            AND ((SELECT bdAAAAMM FROM AAAAMM(SCP.BDDATAINICIAL)) <= :prREFERENCIA)
          GROUP BY SCP.BDCODEMPSCP
          INTO :WCODEMPSCP
      DO
        BEGIN
          /* 34 - Contribuição não cumulativa
             Tributada no mercado interno */
          INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                     VALUES (7, :WCODEMPSCP, :WCODEMPSCP, :prREFERENCIA, 34, 1, 0, :PRRETIFICADORA);
          /* 34 - Contribuição não cumulativa
             Não Tributada no mercado interno */
          INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                     VALUES (7, :WCODEMPSCP, :WCODEMPSCP, :prREFERENCIA, 34, 2, 0, :PRRETIFICADORA);
          /* 34 - Contribuição não cumulativa
             Exportação */
          INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                     VALUES (7, :WCODEMPSCP, :WCODEMPSCP, :prREFERENCIA, 34, 3, 0, :PRRETIFICADORA);
          /* 35 - Contribuição cumulativa */
          INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                     VALUES (7, :WCODEMPSCP, :WCODEMPSCP, :prREFERENCIA, 35, 1, 0, :PRRETIFICADORA);
          /* 36 - Contribuição Total (Valores não cumulativos + cumulativos) */
          -- Obtém os valores das formulas apuradas
          INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                     VALUES (7, :WCODEMPSCP, :WCODEMPSCP, :prREFERENCIA, 36, 1, 0, :PRRETIFICADORA);
    
        END
    END
END
^

CREATE OR ALTER procedure SP_APURACAO_INSERT_M210_M610AUX (
    PRINCTRIB integer,
    PRRETIFICADORA integer,
    PRCODEMP integer,
    PRTABELAREL integer)
as
declare variable WSQL varchar(32500);
begin
  IF (:PRTABELAREL = 1) THEN
    wSQL =       'INSERT INTO VEF_EMP_TVINC_M210_M610 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL, BDTIPOPROD, BDVL_REC_BRT, BDVL_BC_CONT, BDALIQ, BDQUANT_BC, BDALIQ_QUANT, BDVL_CONT_APUR, BDVL_AJUS_ACRES, BDVL_AJUS_REDUC, BDVL_CONT_DIFER, BDVL_CONT_DIFER_ANT, BDVL_CONT_PER, BDRETIFICADORA , BDVLRRECEITAFINANCEIRA,BDCODTP, BDCODCSTPIS, BDCODCSTCOF, BDCOD_CONT_PIS, BDCOD_CONT_COF, BDCODEMPSCP,BDVL_AJUS_ACRES_BC, BDVL_AJUS_REDUC_BC, BDVL_BC_CONT_AJUS, BDCHAVELAN,BDCODNAT, BDTIPOREDZ, BDDESCPEREXP, BDDESCNATREC, BDDESCTIPODOC, BDDATANOTA, BDNUMDOC, BDVLRPIS, BDVLRCOFINS,BDCONDPGTO) ';
  ELSE
    wSQL =       'INSERT INTO VEF_EMP_TBLOCOM210_M610 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL, BDTIPOPROD, BDVL_REC_BRT, BDVL_BC_CONT, BDALIQ, BDQUANT_BC, BDALIQ_QUANT, BDVL_CONT_APUR, BDVL_AJUS_ACRES, BDVL_AJUS_REDUC, BDVL_CONT_DIFER, BDVL_CONT_DIFER_ANT, BDVL_CONT_PER, BDRETIFICADORA, BDVLRRECEITAFINANCEIRA) ';

  wSQL = wSQL||'SELECT 19 as BDCODQUADRO, 7 as BDCODPERIODO, IIF(TMP.BDCODEMPSCP > 0,TMP.BDCODEMPSCP,TMP.BDCODEMP) BDCODEMP,IIF(TMP.BDCODEMPSCP > 0,TMP.BDCODEMPSCP,coalesce(EMP.BDCODMATRIZ, TMP.BDCODEMP)) as BDCODMATRIZ, tmp.BDREFERENCIA, ';
  wSQL = wSQL||'GETORDEMSEQUENCIAL_STR(''M210.''||7||''.''||tmp.BDCODEMP||''.''||COALESCE(emp.BDCODMATRIZ, tmp.BDCODEMP)||''.''||19||''.''||tmp.BDREFERENCIA||''.''||TMP.BDCODEMPSCP, '||:prCODEMP||') AS BDCHAVE,';
  /*wSQL = wSQL||'       (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 19 AND x.BDCODPERIODO = 7) as BDCHAVE, ';*/
  wSQL = wSQL||'       t435.BDCODCSOCIAL, tmp.BDTIPOPROD, ';
  wSQL = wSQL||'       SUM(COALESCE(tmp.BDVL_REC_BRT,0)) as BDVL_REC_BRT, ';
  wSQL = wSQL||'       SUM(COALESCE(tmp.BDVL_BC_CONT_PIS,0)) as BDVL_BC_CONT, tmp.BDALIQ_PIS as BDALIQ, ';
  wSQL = wSQL||'       SUM(COALESCE(tmp.BDQUANT_BC_PIS,0)) as BDQUANT_BC, tmp.BDALIQ_QUANT_PIS as BDALIQ_QUANT, ';
  wSQL = wSQL||'       (SUM(IIF(COALESCE(tmp.BDVL_BC_CONT_PIS,0) > 0, tmp.BDVL_BC_CONT_PIS, COALESCE(tmp.BDQUANT_BC_PIS, 0))*IIF(COALESCE(tmp.BDALIQ_PIS,0) > 0, tmp.BDALIQ_PIS, COALESCE(tmp.BDALIQ_QUANT_PIS,1))) ';
    IF (:PRTABELAREL = 1)  then
    wSQL = wSQL||' /100 ';
  wSQL = wSQL||') as BDVL_CONT_APUR, ';
  wSQL = wSQL||'       0 as BDVL_AJUS_ACRES, ';
  wSQL = wSQL||'       0 as BDVL_AJUS_REDUC, ';
  wSQL = wSQL||'       0 as BDVL_CONT_DIFER, ';
  wSQL = wSQL||'       0 as BDVL_CONT_DIFER_ANT, ';
  wSQL = wSQL||'       0 as BDVL_CONT_PER, ';
  wSQL = wSQL||        :PRRETIFICADORA||' BDRETIFICADORA, ';
  wSQL = wSQL||'       (SUM(IIF(tmp.BDRECEITAFINANCEIRA=''TRUE'',IIF(COALESCE(tmp.BDVL_BC_CONT_PIS,0) > 0, tmp.BDVL_BC_CONT_PIS, COALESCE(tmp.BDQUANT_BC_PIS, 0))*IIF(COALESCE(tmp.BDALIQ_PIS,0) > 0, tmp.BDALIQ_PIS, COALESCE(tmp.BDALIQ_QUANT_PIS,1))/100,0))) as BDVLRRECEITAFINANCEIRA ';
  IF (:PRTABELAREL = 1) THEN
    BEGIN
      wSQL = wSQL||',  TMP.BDCODTP, TMP.BDCODCSTPIS, NULL BDCODCSTCOF, TMP.BDCOD_CONT_PIS, ';
      wSQL = wSQL||'NULL BDCOD_CONT_COF, TMP.BDCODEMPSCP, 0 BDVL_AJUS_ACRES_BC, 0 BDVL_AJUS_REDUC_BC, 0 BDVL_BC_CONT_AJUS, ';
      WSQL = WSQL||'TMP.BDCHAVE BDCHAVELAN, BDCODNAT,BDTIPOREDZ, BDDESCPEREXP,  BDDESCNATREC, BDDESCTIPODOC, BDDATANOTA, BDNUMDOC, BDVLRPIS, 0 BDVLRCOFINS,BDCONDPGTO ';
    END

  wSQL = wSQL||'FROM TMP_VEF_EMP_TBLOCOM_M210_M610 tmp ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = tmp.BDCODEMP) ';
  wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (cast(t435.BDCODCSOCIALEXP as integer)= tmp.BDCOD_CONT_PIS) ';
  wSQL = wSQL||'WHERE (((tmp.BDVL_BC_CONT_PIS > 0) or (tmp.BDALIQ_PIS > 0)) or ';
  wSQL = wSQL||'       ((tmp.BDQUANT_BC_PIS > 0) or (tmp.BDALIQ_QUANT_PIS > 0))) ';
  wSQL = wSQL||'  AND (tmp.BDCODCSTPIS in (1,2,3,5)) '; -- CSTs que geram regitros M200/600...
  wSQL = wSQL||'  AND ((tmp.BDCODCSTPIS <> 5) OR ((tmp.BDCODCSTPIS = 5) and ((tmp.BDALIQ_PIS > 0) or (tmp.BDALIQ_QUANT_PIS > 0)))) '; -- CST 05 com alíquota zerada vai no M400/M800...
  wSQL = wSQL||'  AND ((tmp.BDCODTP NOT IN (3,10,11,16)) OR '; -- Lançamentos de transporte com CST inválida, tem inconsistência...
  wSQL = wSQL||'       ((tmp.BDCODTP IN (3,10,11,16)) AND (tmp.BDCODCSTPIS <> (03))) ) ';
  wSQL = wSQL||'  AND (tmp.BDCOD_CONT_PIS IS NOT NULL) ';
  wSQL = wSQL||'  AND (t435.BDCODCSOCIAL IS NOT NULL) ';
  IF (:PRINCTRIB = 1) THEN /* Incidência tributária 1 - Exclusivamente no regime não-cumulativo */
    BEGIN
       wSQL = wSQL||'  AND ((tmp.BDCODCSTPIS in (02,03,05)) OR '; -- CSTs que aceitam qualquer alíquota
       wSQL = wSQL||'       (CAST(tmp.BDALIQ_PIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))) ) ';
     END
   ELSE
   IF (:PRINCTRIB = 2) THEN /* Incidência tributária 2 - Exclusivamente no regime cumulativo */
     BEGIN
       wSQL = wSQL||'  AND ((tmp.BDCODCSTPIS in (02,03,05)) OR '; -- CSTs que aceitam qualquer alíquota
       wSQL = wSQL||'       (CAST(tmp.BDALIQ_PIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) ) ';
     END
   ELSE
   IF (:PRINCTRIB = 3) THEN /* Incidência tributária 3 - Exclusivamente no regime não-cumulativo / Exclusivamente no regime cumulativo */
     BEGIN
       wSQL = wSQL||'  AND ((tmp.BDCODCSTPIS in (02,03,05)) OR '; -- CSTs que aceitam qualquer alíquota
       wSQL = wSQL||'       ((CAST(tmp.BDALIQ_PIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))) OR (CAST(tmp.BDALIQ_PIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4)))) ) ';
     END
   wSQL = wSQL||'GROUP BY tmp.BDCODEMP, emp.BDCODMATRIZ, tmp.BDREFERENCIA, t435.BDCODCSOCIAL, tmp.BDTIPOPROD, tmp.BDALIQ_PIS, tmp.BDALIQ_QUANT_PIS,TMP.BDCODEMPSCP ';
   IF (:PRTABELAREL = 1) THEN
   wSQL = wSQL||', BDCHAVE,  TMP.BDCODTP, TMP.BDCODCSTPIS, TMP.BDCOD_CONT_PIS, BDCHAVELAN, BDCODNAT,BDTIPOREDZ, BDDESCPEREXP,  BDDESCNATREC, BDDESCTIPODOC, BDDATANOTA, BDNUMDOC, BDVLRPIS,BDCONDPGTO ';

   EXECUTE STATEMENT ( wSQL );

  /* REGISTRO M610: DETALHAMENTO DA CONTRIBUIÇÃO PARA A SEGURIDADE SOCIAL - COFINS DO PERÍODO */
  IF (:PRTABELAREL = 1) THEN
    wSQL =       'INSERT INTO VEF_EMP_TVINC_M210_M610 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL, BDTIPOPROD, BDVL_REC_BRT, BDVL_BC_CONT, BDALIQ, BDQUANT_BC, BDALIQ_QUANT, BDVL_CONT_APUR, BDVL_AJUS_ACRES, BDVL_AJUS_REDUC, BDVL_CONT_DIFER, BDVL_CONT_DIFER_ANT, BDVL_CONT_PER, BDRETIFICADORA, BDVLRRECEITAFINANCEIRA,BDCODTP, BDCODCSTPIS, BDCODCSTCOF, BDCOD_CONT_PIS, BDCOD_CONT_COF, BDCODEMPSCP,BDVL_AJUS_ACRES_BC, BDVL_AJUS_REDUC_BC, BDVL_BC_CONT_AJUS, BDCHAVELAN, BDCODNAT,BDTIPOREDZ, BDDESCPEREXP,  BDDESCNATREC, BDDESCTIPODOC, BDDATANOTA, BDNUMDOC, BDVLRPIS, BDVLRCOFINS,BDCONDPGTO) ';
  ELSE
    wSQL =       'INSERT INTO VEF_EMP_TBLOCOM210_M610 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL, BDTIPOPROD, BDVL_REC_BRT, BDVL_BC_CONT, BDALIQ, BDQUANT_BC, BDALIQ_QUANT, BDVL_CONT_APUR, BDVL_AJUS_ACRES, BDVL_AJUS_REDUC, BDVL_CONT_DIFER, BDVL_CONT_DIFER_ANT, BDVL_CONT_PER, BDRETIFICADORA, BDVLRRECEITAFINANCEIRA) ';

  wSQL = wSQL||'SELECT 37 as BDCODQUADRO, 7 as BDCODPERIODO, IIF(TMP.BDCODEMPSCP > 0,TMP.BDCODEMPSCP,TMP.BDCODEMP) BDCODEMP,IIF(TMP.BDCODEMPSCP > 0,TMP.BDCODEMPSCP,coalesce(EMP.BDCODMATRIZ, TMP.BDCODEMP)) as BDCODMATRIZ, tmp.BDREFERENCIA, ';
  wSQL = wSQL||'GETORDEMSEQUENCIAL_STR(''M610.''||7||''.''||tmp.BDCODEMP||''.''||COALESCE(emp.BDCODMATRIZ, tmp.BDCODEMP)||''.''||37||''.''||tmp.BDREFERENCIA||''.''||TMP.BDCODEMPSCP, '||:prCODEMP||') AS BDCHAVE,';
/*  wSQL = wSQL||'      (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 37 AND x.BDCODPERIODO = 7) as BDCHAVE, ';*/
  wSQL = wSQL||'      t435.BDCODCSOCIAL, tmp.BDTIPOPROD, ';
  wSQL = wSQL||'      SUM(COALESCE(tmp.BDVL_REC_BRT,0)) as BDVL_REC_BRT, ';
  wSQL = wSQL||'      SUM(COALESCE(tmp.BDVL_BC_CONT_COF,0)) as BDVL_BC_CONT, tmp.BDALIQ_COF as BDALIQ, ';
  wSQL = wSQL||'      SUM(COALESCE(tmp.BDQUANT_BC_COF,0)) as BDQUANT_BC, tmp.BDALIQ_QUANT_COF as BDALIQ_QUANT, ';
  wSQL = wSQL||'      (SUM(IIF(COALESCE(tmp.BDVL_BC_CONT_COF,0) > 0, tmp.BDVL_BC_CONT_COF, COALESCE(tmp.BDQUANT_BC_COF, 0))*IIF(COALESCE(tmp.BDALIQ_COF,0) > 0, tmp.BDALIQ_COF, COALESCE(tmp.BDALIQ_QUANT_COF,1))) ';
  IF (:PRTABELAREL = 1)  then
    wSQL = wSQL||' /100 ';
  wSQL = wSQL||') as BDVL_CONT_APUR, ';
  wSQL = wSQL||'      0 as BDVL_AJUS_ACRES, ';
  wSQL = wSQL||'      0 as BDVL_AJUS_REDUC, ';
  wSQL = wSQL||'      0 as BDVL_CONT_DIFER, ';
  wSQL = wSQL||'      0 as BDVL_CONT_DIFER_ANT, ';
  wSQL = wSQL||'      0 as BDVL_CONT_PER, ';
  wSQL = wSQL||       :PRRETIFICADORA||' BDRETIFICADORA, ';
  wSQL = wSQL||'      (SUM(IIF(tmp.BDRECEITAFINANCEIRA=''TRUE'',IIF(COALESCE(tmp.BDVL_BC_CONT_COF,0) > 0, tmp.BDVL_BC_CONT_COF, COALESCE(tmp.BDQUANT_BC_COF, 0))*IIF(COALESCE(tmp.BDALIQ_COF,0) > 0, tmp.BDALIQ_COF, COALESCE(tmp.BDALIQ_QUANT_COF,1))/100,0))) as BDVLRRECEITAFINANCEIRA ';
  IF (:PRTABELAREL = 1) THEN
    BEGIN
      wSQL = wSQL||',  TMP.BDCODTP, NULL BDCODCSTPIS, TMP.BDCODCSTCOF, NULL BDCOD_CONT_PIS, ';
      wSQL = wSQL||'TMP.BDCOD_CONT_COF, TMP.BDCODEMPSCP, 0 BDVL_AJUS_ACRES_BC, 0 BDVL_AJUS_REDUC_BC, 0 BDVL_BC_CONT_AJUS, ';
      wSQL = wSQL||'TMP.BDCHAVE BDCHAVELAN, BDCODNAT,BDTIPOREDZ, BDDESCPEREXP,  BDDESCNATREC, BDDESCTIPODOC, BDDATANOTA, BDNUMDOC, 0 BDVLRPIS, BDVLRCOFINS,BDCONDPGTO ';
    END
  wSQL = wSQL||'FROM TMP_VEF_EMP_TBLOCOM_M210_M610 tmp ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = tmp.BDCODEMP) ';
  wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (cast(t435.BDCODCSOCIALEXP as integer)= tmp.BDCOD_CONT_COF) ';
  wSQL = wSQL||'WHERE (((tmp.BDVL_BC_CONT_COF > 0) or (tmp.BDALIQ_COF > 0)) or ';
  wSQL = wSQL||'       ((tmp.BDQUANT_BC_COF > 0) or (tmp.BDALIQ_QUANT_COF > 0))) ';
  wSQL = wSQL||'  AND (tmp.BDCODCSTCOF in (1,2,3,5)) '; -- CSTs que geram regitros M200/600...
  wSQL = wSQL||'  AND ((tmp.BDCODCSTCOF <> 5) OR ((tmp.BDCODCSTCOF = 5) and ((tmp.BDALIQ_COF > 0) or (tmp.BDALIQ_QUANT_COF > 0)))) '; -- CST 05 com alíquota zerada vai no M400/M800...
  wSQL = wSQL||'  AND ((tmp.BDCODTP NOT IN (3,10,11,16)) OR '; -- Lançamentos de transporte com CST inválida, tem inconsistência...
  wSQL = wSQL||'       ((tmp.BDCODTP IN (3,10,11,16)) AND (tmp.BDCODCSTCOF <> (03))) ) ';
  wSQL = wSQL||'  AND (tmp.BDCOD_CONT_COF IS NOT NULL) ';
  wSQL = wSQL||'  AND (t435.BDCODCSOCIAL IS NOT NULL) ';
  IF (:PRINCTRIB = 1) THEN /* Incidência tributária 1 - Exclusivamente no regime não-cumulativo */
    BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTCOF in (02,03,05)) OR '; -- CSTs que aceitam qualquer alíquota
      wSQL = wSQL||'       (CAST(tmp.BDALIQ_COF as NUMERIC(7,4)) = CAST(7.60 as NUMERIC(7,4))) ) ';
    END
   ELSE
   IF (:PRINCTRIB = 2) THEN /* Incidência tributária 2 - Exclusivamente no regime cumulativo */
    BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTCOF in (02,03,05)) OR '; -- CSTs que aceitam qualquer alíquota
      wSQL = wSQL||'       (CAST(tmp.BDALIQ_COF as NUMERIC(7,4)) = CAST(3.00 as NUMERIC(7,4))) ) ';
    END
   ELSE
   IF (:PRINCTRIB = 3) THEN /* Incidência tributária 3 - Exclusivamente no regime não-cumulativo / Exclusivamente no regime cumulativo */
    BEGIN
      wSQL = wSQL||'  AND ((tmp.BDCODCSTCOF in (02,03,05)) OR '; -- CSTs que aceitam qualquer alíquota
      wSQL = wSQL||'       ((CAST(tmp.BDALIQ_COF as NUMERIC(7,4)) = CAST(7.60 as NUMERIC(7,4))) OR (CAST(tmp.BDALIQ_COF as NUMERIC(7,4)) = CAST(3.00 as NUMERIC(7,4)))) ) ';
    END
   wSQL = wSQL||'GROUP BY tmp.BDCODEMP, emp.BDCODMATRIZ, tmp.BDREFERENCIA, t435.BDCODCSOCIAL, tmp.BDTIPOPROD, tmp.BDALIQ_COF, tmp.BDALIQ_QUANT_COF,TMP.BDCODEMPSCP ';
   IF (:PRTABELAREL = 1) THEN
   wSQL = wSQL||', BDCHAVE,  TMP.BDCODTP, TMP.BDCODCSTCOF, TMP.BDCOD_CONT_COF, BDCHAVELAN, BDCODNAT,BDTIPOREDZ, BDDESCPEREXP,  BDDESCNATREC, BDDESCTIPODOC, BDDATANOTA, BDNUMDOC, BDVLRCOFINS,BDCONDPGTO ';

  EXECUTE STATEMENT ( wSQL );

end^

create or alter procedure SP_APURACAO_BLOCOM_M210_M610AUX (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PREXECREL DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
declare variable WTABELAFISICA varchar(500);
declare variable WJ integer;
declare variable WSQLPREFIXO varchar(32750);
declare variable WI integer;
declare variable WINCTRIB integer;
declare variable WSQL varchar(32750);
declare variable WCODPERIODO integer;
declare variable WCODEMP integer;
declare variable WCODMATRIZ integer;
declare variable WCODQUADRO integer;
declare variable WREFERENCIA integer;
declare variable WCHAVE integer;
declare variable WCODCSOCIAL integer;
declare variable WTIPOPROD integer;
declare variable WINDNATPJ integer;
declare variable WALIQ_PIS_IT_1 varchar(5);
declare variable WALIQ_COF_IT_1 varchar(5);
declare variable WALIQ_PIS_IT_2 varchar(5);
declare variable WALIQ_COF_IT_2 varchar(5);
declare variable WCONTROLCRED DM_BOOLEAN;
declare variable WCODPLANOONLINE integer;
declare variable WTIPOINTPIS integer;
declare variable WTIPOINTCOFINS integer;
BEGIN
  /* Incidência tributária 1 - Exclusivamente no regime não-cumulativo */
  wALIQ_PIS_IT_1 = '1.65';
  wALIQ_COF_IT_1 = '7.60';
  /* Incidência tributária 2 - Exclusivamente no regime cumulativo */
  wALIQ_PIS_IT_2 = '0.65';
  wALIQ_COF_IT_2 = '3.00';
  wI = 0;
  wj = 1;

  -- Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  select coalesce((select BDINCTRIB + 1 from VW_INT_SPEDPISCOFINS_REF where BDCODEMP = :PRCODEMP),
                  (select BDINCTRIB + 1 from VW_INT_SPEDPISCOFINS_REF where BDCODEMP = :PRCODEMPSO)) as BDINCTRIB
  from RDB$DATABASE
  into :wINCTRIB;

  select coalesce((select BDINDNATPJ from VW_VEF_BASE_TEMPPARFED where BDCODEMP = :PRCODEMP),
                  (select BDINDNATPJ from VW_VEF_BASE_TEMPPARFED where BDCODEMP = :PRCODEMPSO)) as BDINDNATPJ
  from RDB$DATABASE
  into :wINDNATPJ;

  -- Obtém o plano online
  SELECT r.bdCODPLANOONLINE
  FROM VW_TEMPRESAS_REF r
  WHERE r.bdCODEMP = :PRCODEMP
  INTO :wCODPLANOONLINE;

  -- Verifica se contabiliza normal ou por CFOP
  SELECT bdTIPOINTPIS, bdTIPOINTCOFINS
  FROM TPLANO_CONF_ONLINE
  WHERE bdCODPLANOONLINE = :wCODPLANOONLINE
  INTO :wTIPOINTPIS, :wTIPOINTCOFINS;

  /* REGISTRO M210: DETALHAMENTO DA CONTRIBUIÇÃO PARA O PIS/PASEP DO PERÍODO */
  IF (:PREXECREL = 'TRUE') THEN
    EXECUTE PROCEDURE SP_APURACAO_INSERT_M210_M610AUX(:wINCTRIB,:PRRETIFICADORA,:PRCODEMP, wj);
  ELSE
    BEGIN
      EXECUTE PROCEDURE SP_APURACAO_INSERT_M210_M610AUX(:wINCTRIB,:PRRETIFICADORA,:PRCODEMP, wI);

      IF ((:WTIPOINTPIS = 4) OR (:WTIPOINTCOFINS = 4)) THEN
        EXECUTE PROCEDURE SP_APURACAO_INSERT_M210_M610AUX(:wINCTRIB,:PRRETIFICADORA,:PRCODEMP, wj);
    END

  IF (:PREXECREL = 'FALSE') THEN
    begin
      WTABELAFISICA = 'VEF_EMP_TBLOCOM210_M610';
      wSQL = 'SELECT DISTINCT BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA,BDCHAVE, BDCODCSOCIAL, BDTIPOPROD ';
      WSQL = WSQL|| 'FROM '||:WTABELAFISICA||' x ';
      WSQL = WSQL||'WHERE x.BDCODMATRIZ = '||:prCODEMP||' ';
      WSQL = WSQL||'AND x.BDREFERENCIA = '||:prREFERENCIA||' ';
      WSQL = WSQL||'AND X.BDRETIFICADORA = '||:PRRETIFICADORA||' ';
      WSQL = WSQL||'UNION ALL ';
      WSQL = WSQL||'SELECT BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL, BDTIPOPROD ';
      WSQL = WSQL||'FROM ( ';
      WSQL = WSQL||    'SELECT SCP.BDCODEMPSCP ';
      WSQL = WSQL||    'FROM TEMPRESAS_SCP SCP ';
      --WSQL = WSQL||    'WHERE SCP.BDCODEMP = '||:prCODEMP||' ';
      WSQL = WSQL||    'WHERE scp.BDCODEMP in(SELECT ex.BDCODEMP ';
      WSQL = WSQL||                          'FROM TEMPRESAS ex ';
      WSQL = WSQL||                          'WHERE ex.BDCODEMP = '||:prCODEMP||' ';
      WSQL = WSQL||                             'OR ex.BDCODMATRIZ = '||:prCODEMP||')';

      WSQL = WSQL||    'AND (SCP.BDCODEMPSCP IS NOT NULL AND SCP.BDCODEMPSCP > 0) ';
      WSQL = WSQL||    'AND (SCP.BDDATAFINAL IS NULL OR (SELECT bdAAAAMM FROM AAAAMM(SCP.BDDATAFINAL)) >= '||:prREFERENCIA||') ';
      WSQL = WSQL||    'AND (SCP.BDDATAINICIAL IS NULL OR (SELECT bdAAAAMM FROM AAAAMM(SCP.BDDATAINICIAL)) <= '||:prREFERENCIA||')  ';

      WSQL = WSQL||    'AND '||:PRAJUSTESCP||' = ''TRUE'' ';
      WSQL = WSQL||    'GROUP BY SCP.BDCODEMPSCP ';
      WSQL = WSQL||   ') SCP ';
      WSQL = WSQL||'JOIN '||:WTABELAFISICA||' x ON (x.BDCODMATRIZ = SCP.BDCODEMPSCP AND ';
      WSQL = WSQL||'x.BDREFERENCIA = '||:prREFERENCIA||' AND ';
      WSQL = WSQL|| 'X.BDRETIFICADORA = '||:PRRETIFICADORA||' ';
      WSQL = WSQL|| ' )';

      FOR EXECUTE STATEMENT ( WSQL )
      INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCODCSOCIAL, :wTIPOPROD
      DO
        BEGIN
          :WCONTROLCRED = False;
          --- novos campos para 01/2019  Apuração Bloco M - M210/M610 #82005 campos novos do 05 ao 07
          WSQLPREFIXO = 'UPDATE '||:WTABELAFISICA||' x ';
          WSQLPREFIXO = WSQLPREFIXO||'SET ';
          -- Se a empresa for sociedade cooperativa, vai descontar os lançamentos de ajuste do M211...
          WSQLPREFIXO = WSQLPREFIXO||'X.BDVL_BC_CONT = iif('||:WINDNATPJ||' in (1, 4), (X.BDVL_BC_CONT - coalesce((select sum(iif((X.BDCODQUADRO = 19), coalesce(M211.BDVLREXCLUGERPIS, 0) + coalesce(M211.BDVLREXCLUBCPIS, 0), coalesce(M211.BDVLREXCLUGERCOFINS, 0) + coalesce(M211.BDVLREXCLUBCCOFINS, 0))) ';
          WSQLPREFIXO = WSQLPREFIXO||                                                                     'from VEF_EMP_TSOCCOOPM211M611 M211 ';
          WSQLPREFIXO = WSQLPREFIXO||                                                                     'left outer join TEMPRESAS_SCP SCP on (SCP.BDCODEMP = M211.BDCODEMP and ';
          WSQLPREFIXO = WSQLPREFIXO||                                                                           'SCP.BDCODSCP = M211.BDCODSCP and ';
          WSQLPREFIXO = WSQLPREFIXO||                                                                           'SCP.BDREFEMP = M211.BDREFSOC) ';
          WSQLPREFIXO = WSQLPREFIXO||                                                                     'where ((('||:PRAJUSTESCP||' = ''TRUE'') and ';
          WSQLPREFIXO = WSQLPREFIXO||                                                                           '(M211.BDCODEMP = X.BDCODEMP and ';
          WSQLPREFIXO = WSQLPREFIXO||                                                                           '(M211.BDCODSCP is null or M211.BDCODSCP = 0) or (SCP.BDCODEMPSCP = X.BDCODEMP))) or ('||:PRAJUSTESCP||' = ''FALSE'' and ';
          WSQLPREFIXO = WSQLPREFIXO||                                                                           'M211.BDCODEMP = X.BDCODEMP)) and ';
          WSQLPREFIXO = WSQLPREFIXO||                                                                           'M211.BDREFERENCIA = X.BDREFERENCIA and ';
          WSQLPREFIXO = WSQLPREFIXO||                                                                           'M211.BDCODCSOCIAL = X.BDCODCSOCIAL and ';
          WSQLPREFIXO = WSQLPREFIXO||                                                                           'COALESCE(M211.BDTIPOPROD,0) = COALESCE(X.BDTIPOPROD,0) and ';
          WSQLPREFIXO = WSQLPREFIXO||                                                                           '(((X.BDCODQUADRO = 19) and ';
          WSQLPREFIXO = WSQLPREFIXO||                                                                           '(M211.BDALIQPIS = X.BDALIQ)) or ((X.BDCODQUADRO = 37) and ';
          WSQLPREFIXO = WSQLPREFIXO||                                                                           '(M211.BDALIQCOFINS = X.BDALIQ)))), 0)), X.BDVL_BC_CONT), ';
    
          --- novos campos para 01/2019  Apuração Bloco M - M210/M610 #82005 campos novos do 05 ao 07
          --05 VL_AJUS_ACRES_BC Valor do total dos ajustes de acréscimo da base de cálculo da contribuição a que se refere o Campo 04
          WSQLPREFIXO = WSQLPREFIXO||  'x.BDVL_AJUS_ACRES_BC  = (SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m215_M615.bdvl_aj_bc_pis,0), COALESCE(m215_M615.bdvl_aj_bc_cofins,0))) ';
          WSQLPREFIXO = WSQLPREFIXO||                                    'FROM VEF_EMP_TLANAJUM215_M615 m215_M615 ';
          WSQLPREFIXO = WSQLPREFIXO||                                    'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = m215_M615.BDCODEMP AND SCP.BDCODSCP = m215_M615.BDCODSCP AND SCP.BDREFEMP = m215_M615.BDREFSOC) ';
          WSQLPREFIXO = WSQLPREFIXO||                                    'WHERE ((('||:PRAJUSTESCP||' = ''TRUE'') AND (m215_M615.BDCODEMP = x.BDCODEMP AND (m215_M615.BDCODSCP IS NULL OR m215_M615.BDCODSCP = 0) OR (SCP.BDCODEMPSCP = x.BDCODEMP))) ';
          WSQLPREFIXO = WSQLPREFIXO||                                    'OR ('||:PRAJUSTESCP||' = ''FALSE'' AND m215_M615.BDCODEMP = x.BDCODEMP)) ';
          WSQLPREFIXO = WSQLPREFIXO||                                      'AND m215_M615.BDREFERENCIA = x.BDREFERENCIA ';
          WSQLPREFIXO = WSQLPREFIXO||                                      'AND m215_M615.BDCODCSOCIAL = x.BDCODCSOCIAL ';
          WSQLPREFIXO = WSQLPREFIXO||                                      'AND COALESCE(m215_M615.BDTIPOPROD,0) = COALESCE(x.BDTIPOPROD,0) ';
          WSQLPREFIXO = WSQLPREFIXO||                                      'and m215_m615.bdind_aj_bc = 1 ';
          WSQLPREFIXO = WSQLPREFIXO||                                      'AND (((x.BDCODQUADRO = 19) AND (m215_M615.BDALIQPIS = x.BDALIQ)) OR ';
          WSQLPREFIXO = WSQLPREFIXO||                                           '((x.BDCODQUADRO = 37) AND (m215_M615.BDALIQCOFINS = x.BDALIQ)))), ';
          --06 VL_AJUS_REDUC_BC_COFINS Valor do total dos ajustes de redução da base de cálculo da contribuição a que se refere o Campo 04
          WSQLPREFIXO = WSQLPREFIXO||   'x.BDVL_AJUS_REDUC_BC  = (SELECT coalesce(SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m215_M615.bdvl_aj_bc_pis,0), COALESCE(m215_M615.bdvl_aj_bc_cofins,0))),0) ';
          WSQLPREFIXO = WSQLPREFIXO||                                    'FROM VEF_EMP_TLANAJUM215_M615 m215_M615 ';
          WSQLPREFIXO = WSQLPREFIXO||                                   'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = m215_M615.BDCODEMP AND SCP.BDCODSCP = m215_M615.BDCODSCP AND SCP.BDREFEMP = m215_M615.BDREFSOC) ';
          WSQLPREFIXO = WSQLPREFIXO||                                    'WHERE ((('||:PRAJUSTESCP||' = ''TRUE'') AND (m215_M615.BDCODEMP = x.BDCODEMP AND (m215_M615.BDCODSCP IS NULL OR m215_M615.BDCODSCP = 0) OR (SCP.BDCODEMPSCP = x.BDCODEMP))) ';
          WSQLPREFIXO = WSQLPREFIXO||                                    'OR ('||:PRAJUSTESCP||' = ''FALSE'' AND m215_M615.BDCODEMP = x.BDCODEMP)) ';
          WSQLPREFIXO = WSQLPREFIXO||                                      'AND m215_M615.BDREFERENCIA = x.BDREFERENCIA ';
          WSQLPREFIXO = WSQLPREFIXO||                                      'AND m215_M615.BDCODCSOCIAL = x.BDCODCSOCIAL ';
          WSQLPREFIXO = WSQLPREFIXO||                                      'AND COALESCE(m215_M615.BDTIPOPROD,0) = COALESCE(x.BDTIPOPROD,0) ';
          WSQLPREFIXO = WSQLPREFIXO||                                      'and m215_m615.bdind_aj_bc = 0 ';
          WSQLPREFIXO = WSQLPREFIXO||                                      'AND (((x.BDCODQUADRO = 19) AND (m215_M615.BDALIQPIS = x.BDALIQ)) OR ';
          WSQLPREFIXO = WSQLPREFIXO||                                           '((x.BDCODQUADRO = 37) AND (m215_M615.BDALIQCOFINS = x.BDALIQ)))) ';
    
          WSQLPREFIXO = WSQLPREFIXO||'WHERE x.BDCODPERIODO = '||:WCODPERIODO||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND X.BDRETIFICADORA = '||:PRRETIFICADORA||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND x.BDCODEMP = '||:WCODEMP||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND x.BDCODMATRIZ = '||:WCODMATRIZ||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND x.BDCODQUADRO = '||:WCODQUADRO||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND x.BDREFERENCIA = '||:WREFERENCIA||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND x.BDCHAVE = '||:WCHAVE||' ';
          execute statement ( WSQLPREFIXO );
    
          WSQLPREFIXO = 'UPDATE '||:WTABELAFISICA||' x ';
          WSQLPREFIXO = WSQLPREFIXO||'set ';
          --07 VL_BC_CONT_AJUS Valor da Base de Cálculo da Contribuição, após os ajustes. (Campo 07 = Campo 04 + Campo 05 - Campo 06) ';
          WSQLPREFIXO = WSQLPREFIXO||   'x.BDVL_BC_CONT_AJUS   = (( coalesce(x.BDVL_BC_CONT,0) + coalesce(x.BDVL_AJUS_ACRES_BC,0)) - coalesce(x.BDVL_AJUS_REDUC_BC,0)) ';
          --Deve verificar a BC por Quantidade quando a Base principal for zerada ';
          WSQLPREFIXO = WSQLPREFIXO||'WHERE x.BDCODPERIODO = '||:WCODPERIODO||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND X.BDRETIFICADORA = '||:PRRETIFICADORA||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND x.BDCODEMP = '||:WCODEMP||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND x.BDCODMATRIZ = '||:WCODMATRIZ||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND x.BDCODQUADRO = '||:WCODQUADRO||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND x.BDREFERENCIA = '||:WREFERENCIA||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND x.BDCHAVE = '||:WCHAVE||' ';
          execute statement ( WSQLPREFIXO );
    
          /* Verifica o quadros para pegar os campos corretos, PIS ou Cofins */
          /* Quando alterar os Selects dos campos, não esquecer de atualizar os Selects do campos 13... */
          WSQLPREFIXO = 'UPDATE '||:WTABELAFISICA||' x ';
          WSQLPREFIXO = WSQLPREFIXO||'SET ';-- 04 - VL_BC_CONT - Valor da Base de Cálculo da Contribuição ';
          -- Se a empresa for sociedade cooperativa, vai descontar os lançamentos de ajuste do M211...
    --          x.BDVL_BC_CONT = IIF('||:WINDNATPJ||' IN (1,4),
    ----                               (IIF(((COALESCE(x.BDVL_BC_CONT,0) > 0) OR (x.BDCODCSOCIAL = 3)), COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0))- -- Contribuição social 3 é base de cálculo por quantidade sempre
    --                               (x.BDVL_BC_CONT-
    --                                COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m211.BDVLREXCLUGERPIS,0)+COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUGERCOFINS,0)+COALESCE(m211.BDVLREXCLUBCCOFINS,0) ))
    --                                          FROM VEF_EMP_TSOCCOOPM211M611 m211
    --                                          WHERE m211.BDCODEMP = x.BDCODEMP
    --                                            AND m211.BDREFERENCIA = x.BDREFERENCIA
    --                                            AND m211.BDCODCSOCIAL = x.BDCODCSOCIAL
    --                                            AND (((x.BDCODQUADRO = 19) AND (m211.BDALIQPIS = x.BDALIQ)) OR
    --                                                 ((x.BDCODQUADRO = 37) AND (m211.BDALIQCOFINS = x.BDALIQ)))),0)
    --                                        ),
    ----                               IIF(((COALESCE(x.BDVL_BC_CONT,0) > 0) OR (x.BDCODCSOCIAL = 3)), COALESCE(x.BDVL_BC_CONT,0), COALESCE(x.BDQUANT_BC, 0))), -- Contribuição social 3 é base de cálculo por quantidade sempre
    --                               x.BDVL_BC_CONT), -- Contribuição social 3 é base de cálculo por quantidade sempre
          -- 08 - VL_CONT_APUR - Valor total da contribuição social apurada
          WSQLPREFIXO = WSQLPREFIXO||'x.BDVL_CONT_APUR = (( iif(x.BDVL_BC_CONT_AJUS > 0,x.BDVL_BC_CONT_AJUS,coalesce(x.BDQUANT_BC,0)) * IIF(COALESCE(x.BDALIQ,0) > 0, COALESCE(x.BDALIQ,0), COALESCE(x.BDALIQ_QUANT,1)))/IIF(COALESCE(x.BDALIQ,0) > 0, 100, 1)) '; -- Caso seja por quantidade, multiplica sem alíquota....
          -- 09 - VL_AJUS_ACRES - Valor total dos ajustes de acréscimo
          WSQLPREFIXO = WSQLPREFIXO||', x.BDVL_AJUS_ACRES = (COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m220.BDVLRAJUPIS,0), COALESCE(m220.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TAJUAPUPCM220620 m220 LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = M220.BDCODEMP AND SCP.BDCODSCP = M220.BDCODSCP AND SCP.BDREFEMP = M220.BDREFSOC) WHERE ((('||:PRAJUSTESCP||' = ''TRUE'') AND (M220.BDCODEMP = x.BDCODEMP AND (M220.BDCODSCP IS NULL OR M220.BDCODSCP = 0) OR (SCP.BDCODEMPSCP = x.BDCODEMP))) OR ('||:PRAJUSTESCP||' = ''FALSE'' AND M220.BDCODEMP = x.BDCODEMP)) AND m220.BDREFERENCIA = x.BDREFERENCIA AND m220.BDTIPOAJUSTE = 1 AND (((x.BDCODQUADRO = 19) AND (m220.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m220.BDALIQCOFINS = x.BDALIQ))) AND (m220.BDCODCSOCIAL = x.BDCODCSOCIAL) AND (COALESCE(m220.BDTIPOPROD,0) = COALESCE(x.BDTIPOPROD,0))),0)), ';
          -- 10 - VL_AJUS_REDUC - Valor total dos ajustes de redução
          WSQLPREFIXO = WSQLPREFIXO||'x.BDVL_AJUS_REDUC = (COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m220.BDVLRAJUPIS,0), COALESCE(m220.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TAJUAPUPCM220620 m220 LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = M220.BDCODEMP AND SCP.BDCODSCP = M220.BDCODSCP AND SCP.BDREFEMP = M220.BDREFSOC) WHERE ((('||:PRAJUSTESCP||' = ''TRUE'') AND (M220.BDCODEMP = x.BDCODEMP AND (M220.BDCODSCP IS NULL OR M220.BDCODSCP = 0) OR (SCP.BDCODEMPSCP = x.BDCODEMP))) OR ('||:PRAJUSTESCP||' = ''FALSE'' AND M220.BDCODEMP = x.BDCODEMP)) AND m220.BDREFERENCIA = x.BDREFERENCIA AND m220.BDTIPOAJUSTE = 0 AND (((x.BDCODQUADRO = 19) AND (m220.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m220.BDALIQCOFINS = x.BDALIQ) )) AND (m220.BDCODCSOCIAL = x.BDCODCSOCIAL) AND (COALESCE(m220.BDTIPOPROD,0) = COALESCE(x.BDTIPOPROD,0))),0)), ';
          -- 11 - VL_CONT_DIFER - Valor da contribuição a diferir no período
          WSQLPREFIXO = WSQLPREFIXO||'x.BDVL_CONT_DIFER = (COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m230.BDVLRCONDEFPIS,0), COALESCE(m230.BDVLRCONDEFCOFINS,0))) FROM VEF_EMP_TINFADIDEFM230630 m230 LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = m230.BDCODEMP AND SCP.BDCODSCP = m230.BDCODSCP AND SCP.BDREFEMP = m230.BDREFSOC) WHERE ((('||:PRAJUSTESCP||' = ''TRUE'') AND (m230.BDCODEMP = x.BDCODEMP AND (m230.BDCODSCP IS NULL OR m230.BDCODSCP = 0) OR (SCP.BDCODEMPSCP = x.BDCODEMP))) OR ('||:PRAJUSTESCP||' = ''FALSE'' AND m230.BDCODEMP = x.BDCODEMP)) AND m230.BDREFERENCIA = x.BDREFERENCIA AND m230.BDCODCSOCIAL = x.BDCODCSOCIAL AND COALESCE(m230.BDTIPOPROD,0) = COALESCE(x.BDTIPOPROD,0) AND (((x.BDCODQUADRO = 19) AND (m230.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m230.BDALIQCOFINS = x.BDALIQ))) ),0)), ';
          -- 12 - VL_CONT_DIFER_ANT - Valor da contribuição diferida em períodos anteriores
          WSQLPREFIXO = WSQLPREFIXO||'x.BDVL_CONT_DIFER_ANT = (COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), (COALESCE(m300.BDVLRCONTRIPIS,0)-COALESCE(m300.BDVLRCREPIS,0)), (COALESCE(m300.BDVLRCONTRICOFINS,0)-COALESCE(m300.BDVLRCRECOFINS,0)))) FROM VEF_EMP_TINFADIDEFM300M700 m300 LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = m300.BDCODEMP AND SCP.BDCODSCP = m300.BDCODSCP AND SCP.BDREFEMP = m300.BDREFSOC) WHERE ((('||:PRAJUSTESCP||' = ''TRUE'') AND (m300.BDCODEMP = x.BDCODEMP AND (m300.BDCODSCP IS NULL OR m300.BDCODSCP = 0) OR (SCP.BDCODEMPSCP = x.BDCODEMP))) OR ('||:PRAJUSTESCP||' = ''FALSE'' AND m300.BDCODEMP = x.BDCODEMP)) AND m300.BDDATAREC IS NOT NULL AND (select BDAAAAMM from AAAAMM(m300.bddatarec)) = x.BDREFERENCIA AND m300.BDCODCSOCIAL = x.BDCODCSOCIAL AND (((x.BDCODQUADRO = 19) AND (m300.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m300.BDALIQCOFINS = x.BDALIQ))) ),0)), ';
          -- 13 - VL_CONT_PER - Valor Total da Contribuição do Período (08 + 09 - 10 - 11 + 12)
          WSQLPREFIXO = WSQLPREFIXO||'x.BDVL_CONT_PER = ( ';
          WSQLPREFIXO = WSQLPREFIXO||    /*   08 - VL_CONT_APUR */       'CAST(((iif(x.BDVL_BC_CONT_AJUS > 0,x.BDVL_BC_CONT_AJUS,coalesce(x.BDQUANT_BC,0))*IIF(COALESCE(x.BDALIQ,0) > 0, COALESCE(x.BDALIQ,0), COALESCE(x.BDALIQ_QUANT,1)))/IIF(COALESCE(x.BDALIQ,0) > 0, 100, 1)) AS dm_numeric_15_2) '; -- Caso seja por quantidade, multiplica sem alíquota....
          WSQLPREFIXO = WSQLPREFIXO||    /* + 09 - VL_AJUS_ACRES */     '+(IIF('||:WCONTROLCRED||' = ''TRUE'', 0, COALESCE((SELECT SUM(IIF((X.BDCODQUADRO = 19), COALESCE(M220.BDVLRAJUPIS,0), COALESCE(M220.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TAJUAPUPCM220620 M220 LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = M220.BDCODEMP AND SCP.BDCODSCP = M220.BDCODSCP AND SCP.BDREFEMP = M220.BDREFSOC) WHERE ((('||:PRAJUSTESCP||' = ''TRUE'') AND (M220.BDCODEMP = X.BDCODEMP AND (M220.BDCODSCP IS NULL OR M220.BDCODSCP = 0) OR (SCP.BDCODEMPSCP = X.BDCODEMP))) OR ('||:PRAJUSTESCP||' = ''FALSE'' AND M220.BDCODEMP = X.BDCODEMP)) AND M220.BDREFERENCIA = X.BDREFERENCIA AND M220.BDTIPOAJUSTE = 1 AND M220.BDCODCSOCIAL = X.BDCODCSOCIAL AND COALESCE(M220.BDTIPOPROD,0) = COALESCE(X.BDTIPOPROD,0) AND (((X.BDCODQUADRO = 19) AND (M220.BDALIQPIS = X.BDALIQ)) OR ((X.BDCODQUADRO = 37) AND (M220.BDALIQCOFINS = X.BDALIQ))) ),0))) ';
          WSQLPREFIXO = WSQLPREFIXO||    /* - 10 - VL_AJUS_REDUC */     '-(IIF('||:WCONTROLCRED||' = ''TRUE'', 0, COALESCE((SELECT SUM(IIF((X.BDCODQUADRO = 19), COALESCE(M220.BDVLRAJUPIS,0), COALESCE(M220.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TAJUAPUPCM220620 M220 LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = M220.BDCODEMP AND SCP.BDCODSCP = M220.BDCODSCP AND SCP.BDREFEMP = M220.BDREFSOC) WHERE ((('||:PRAJUSTESCP||' = ''TRUE'') AND (M220.BDCODEMP = X.BDCODEMP AND (M220.BDCODSCP IS NULL OR M220.BDCODSCP = 0) OR (SCP.BDCODEMPSCP = X.BDCODEMP))) OR ('||:PRAJUSTESCP||' = ''FALSE'' AND M220.BDCODEMP = X.BDCODEMP)) AND M220.BDREFERENCIA = X.BDREFERENCIA AND M220.BDTIPOAJUSTE = 0 AND M220.BDCODCSOCIAL = X.BDCODCSOCIAL AND COALESCE(M220.BDTIPOPROD,0) = COALESCE(X.BDTIPOPROD,0) AND (((X.BDCODQUADRO = 19) AND (M220.BDALIQPIS = X.BDALIQ)) OR ((X.BDCODQUADRO = 37) AND (M220.BDALIQCOFINS = X.BDALIQ))) ),0)))/* - 11 - VL_CONT_DIFER */     -(COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), COALESCE(m230.BDVLRCONDEFPIS,0), COALESCE(m230.BDVLRCONDEFCOFINS,0))) FROM VEF_EMP_TINFADIDEFM230630 m230 LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = m230.BDCODEMP AND SCP.BDCODSCP = m230.BDCODSCP AND SCP.BDREFEMP = m230.BDREFSOC) WHERE ((('||:PRAJUSTESCP||' = ''TRUE'') AND (m230.BDCODEMP = x.BDCODEMP AND (m230.BDCODSCP IS NULL OR m230.BDCODSCP = 0) OR (SCP.BDCODEMPSCP = x.BDCODEMP))) OR ('||:PRAJUSTESCP||' = ''FALSE'' AND m230.BDCODEMP = x.BDCODEMP)) AND m230.BDREFERENCIA = x.BDREFERENCIA AND m230.BDCODCSOCIAL = x.BDCODCSOCIAL AND COALESCE(m230.BDTIPOPROD,0) = COALESCE(x.BDTIPOPROD,0) AND (((x.BDCODQUADRO = 19) AND (m230.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m230.BDALIQCOFINS = x.BDALIQ))) ),0)) ';
          WSQLPREFIXO = WSQLPREFIXO||    /* + 12 - VL_CONT_DIFER_ANT */ '+(COALESCE((SELECT SUM(IIF((x.BDCODQUADRO = 19), (COALESCE(m300.BDVLRCONTRIPIS,0)-COALESCE(m300.BDVLRCREPIS,0)), (COALESCE(m300.BDVLRCONTRICOFINS,0)-COALESCE(m300.BDVLRCRECOFINS,0)))) FROM VEF_EMP_TINFADIDEFM300M700 m300 LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = m300.BDCODEMP AND SCP.BDCODSCP = m300.BDCODSCP AND SCP.BDREFEMP = m300.BDREFSOC) WHERE ((('||:PRAJUSTESCP||' = ''TRUE'') AND (m300.BDCODEMP = x.BDCODEMP AND (m300.BDCODSCP IS NULL OR m300.BDCODSCP = 0) OR (SCP.BDCODEMPSCP = x.BDCODEMP))) OR ('||:PRAJUSTESCP||' = ''FALSE'' AND m300.BDCODEMP = x.BDCODEMP)) AND m300.BDDATAREC IS NOT NULL AND (select BDAAAAMM from AAAAMM(m300.bddatarec)) = x.BDREFERENCIA AND m300.BDCODCSOCIAL = x.BDCODCSOCIAL AND (((x.BDCODQUADRO = 19) AND (m300.BDALIQPIS = x.BDALIQ)) OR ((x.BDCODQUADRO = 37) AND (m300.BDALIQCOFINS = x.BDALIQ))) ),0)))';
          WSQLPREFIXO = WSQLPREFIXO||'WHERE x.BDCODPERIODO = '||:WCODPERIODO||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND X.BDRETIFICADORA = '||:PRRETIFICADORA||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND x.BDCODEMP = '||:WCODEMP||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND x.BDCODMATRIZ = '||:WCODMATRIZ||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND x.BDCODQUADRO = '||:WCODQUADRO||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND x.BDREFERENCIA = '||:WREFERENCIA||' ';
          WSQLPREFIXO = WSQLPREFIXO||  'AND x.BDCHAVE = '||:WCHAVE||' ';
          execute statement ( WSQLPREFIXO );

          IF (:WINDNATPJ IN (1,4)) THEN -- Apenas se a empresa for "01 - Sociedade cooperativa" ou "04 - Sociedade cooperativa participante de SCP como sócia ostensiva"
            BEGIN
              /* REGISTRO M211: SOCIEDADES COOPERATIVAS - COMPOSIÇÃO DA BASE DE CALCULO - PIS/PASEP */
              WSQLPREFIXO = 'INSERT INTO VEF_EMP_TBLOCOM211_M611 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDTIPOSOCCOOP, BDVL_BC_CONT_ANT_EXC, BDVL_EXC_COOP_GER, BDVL_EXC_ESP_COOP, BDVL_BC_CONT, BDRETIFICADORA) ';
              WSQLPREFIXO = WSQLPREFIXO||'SELECT '||:WCODPERIODO||' AS BDCODPERIODO, COALESCE(SCP.BDCODEMPSCP,m211.BDCODEMP) BDCODEMP, COALESCE(SCP.BDCODEMPSCP,COALESCE(emp.BDCODMATRIZ, m211.BDCODEMP)) AS BDCODMATRIZ, '||:WCODQUADRO||' AS BDCODQUADRO, m211.BDREFERENCIA, '||:WCHAVE||' AS BDCHAVE, ';
                     /*(SELECT COALESCE(MAX(x.BDORDEM)+1, 1)
                      FROM VEF_EMP_TBLOCOM211_M611 x
                          WHERE x.BDCODPERIODO = '||:WCODPERIODO||'
                            AND x.BDCODEMP = '||:WCODEMP||'
                            AND x.BDCODMATRIZ = '||:WCODMATRIZ||'
                            AND x.BDCODQUADRO = '||:WCODQUADRO||'
                            AND x.BDREFERENCIA = '||:WREFERENCIA||'
                            AND x.BDCHAVE = '||:WCHAVE||')  */
        --              GETORDEMSEQUENCIAL_STR(''M211.''||'||:WCODPERIODO||'||''.''||'||:WCODEMP||'||''.''||'||:WCODMATRIZ||'||''.''||'||:WCODQUADRO||'||''.''||'||:WREFERENCIA||'||''.''||'||:WCHAVE||', '||:WCODEMP||') AS BDORDEM,
              WSQLPREFIXO = WSQLPREFIXO||        'GETORDEMSEQUENCIAL_STR(''M211.''||'||:WCODPERIODO||'||''.''||'||:WCODEMP||'||''.''||'||:WCODMATRIZ||'||''.''||'||:WCODQUADRO||'||''.''||'||:WREFERENCIA||'||''.''||'||:WCHAVE||', '||:PRCODEMP||') AS BDORDEM,   ';
              WSQLPREFIXO = WSQLPREFIXO||       'm211.BDTIPOSOCCOOP, ';
              -- 03 - VL_BC_CONT_ANT_EXC_COOP - Valor da Base de Cálculo da Contribuição, conforme Registros escriturados nos Blocos A, C, D e F, antes das Exclusões das Cooperativas. ';
              WSQLPREFIXO = WSQLPREFIXO||           '(SELECT ( SUM(x.BDVL_BC_CONT)+ ';
              -- Como já abateu as exclusões no select complementar acima, adiciona esses valores aqui...
              WSQLPREFIXO = WSQLPREFIXO||                     'SUM(IIF((x.BDCODQUADRO = 19), COALESCE(SUM(m211.BDVLREXCLUGERPIS),0)+COALESCE(SUM(m211.BDVLREXCLUBCPIS),0), ';
              WSQLPREFIXO = WSQLPREFIXO||                                                   'COALESCE(SUM(m211.BDVLREXCLUGERCOFINS),0)+COALESCE(SUM(m211.BDVLREXCLUBCCOFINS),0) )) ) AS BDVL_BC_CONT ';
              WSQLPREFIXO = WSQLPREFIXO||            'FROM '||:WTABELAFISICA||' x ';
              WSQLPREFIXO = WSQLPREFIXO||            'WHERE x.BDCODPERIODO = '||:WCODPERIODO||' ';
              WSQLPREFIXO = WSQLPREFIXO||              'AND X.BDRETIFICADORA = '||:PRRETIFICADORA||' ';
              WSQLPREFIXO = WSQLPREFIXO||              'AND x.BDCODEMP = '||:WCODEMP||' ';
              WSQLPREFIXO = WSQLPREFIXO||              'AND x.BDCODMATRIZ = '||:WCODMATRIZ||' ';
              WSQLPREFIXO = WSQLPREFIXO||              'AND x.BDCODQUADRO = '||:WCODQUADRO||' ';
              WSQLPREFIXO = WSQLPREFIXO||              'AND x.BDREFERENCIA = '||:WREFERENCIA||' ';
              WSQLPREFIXO = WSQLPREFIXO||              'AND x.BDCHAVE = '||:WCHAVE||' ';
              WSQLPREFIXO = WSQLPREFIXO||              'AND x.BDCODCSOCIAL = '||:WCODCSOCIAL||' ';
              WSQLPREFIXO = WSQLPREFIXO||              'AND (((x.BDCODQUADRO = 19) AND ((m211.BDALIQPIS = x.BDALIQ) OR (m211.BDALIQPIS = x.BDALIQ_QUANT)) ) OR ';
              WSQLPREFIXO = WSQLPREFIXO||                   '((x.BDCODQUADRO = 37) AND ((m211.BDALIQCOFINS = x.BDALIQ) OR (m211.BDALIQCOFINS = x.BDALIQ_QUANT))) ) ) AS BDVL_BC_CONT_ANT_EXC, ';
              -- 04 - VL_EXC_COOP_GER - Valor de Exclusão Especifica das Cooperativas em Geral, decorrente das Sobras Apuradas na DRE, destinadas a constituição do Fundo de Reserva e do FATES. ';
              WSQLPREFIXO = WSQLPREFIXO||       'SUM(IIF(('||:WCODQUADRO||' = 19), COALESCE(m211.BDVLREXCLUGERPIS,0), COALESCE(m211.BDVLREXCLUGERCOFINS,0))) AS BDVL_EXC_COOP_GER, ';
              -- 05 - VL_EXC_ESP_COOP - Valor das Exclusões da Base de Cálculo Especifica do Tipo da Sociedade Cooperativa, conforme Campo 02 (IND_TIP_COOP). ';
              WSQLPREFIXO = WSQLPREFIXO||       'SUM(IIF(('||:WCODQUADRO||' = 19), COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUBCCOFINS,0))) AS BDVL_EXC_ESP_COOP, ';
              -- 06 - VL_BC_CONT - Valor da Base de Cálculo, Após as Exclusões Especificas da Sociedade Cooperativa (04 - 05 - 06) - Transportar para M210. ';
              WSQLPREFIXO = WSQLPREFIXO||           /* 03 - VL_BC_CONT_ANT_EXC_COOP */ '( (SELECT SUM(x.BDVL_BC_CONT) AS BDVL_BC_CONT ';
              WSQLPREFIXO = WSQLPREFIXO||                                                 'FROM '||:WTABELAFISICA||' x ';
              WSQLPREFIXO = WSQLPREFIXO||                                                 'WHERE x.BDCODPERIODO = '||:WCODPERIODO||' ';
              WSQLPREFIXO = WSQLPREFIXO||                                                  'AND X.BDRETIFICADORA = '||:PRRETIFICADORA||' ';
              WSQLPREFIXO = WSQLPREFIXO||                                                  'AND x.BDCODEMP = '||:WCODEMP||' ';
              WSQLPREFIXO = WSQLPREFIXO||                                                   'AND x.BDCODMATRIZ = '||:WCODMATRIZ||' ';
              WSQLPREFIXO = WSQLPREFIXO||                                                   'AND x.BDCODQUADRO = '||:WCODQUADRO||' ';
              WSQLPREFIXO = WSQLPREFIXO||                                                   'AND x.BDREFERENCIA = '||:WREFERENCIA||' ';
              WSQLPREFIXO = WSQLPREFIXO||                                                   'AND x.BDCHAVE = '||:WCHAVE||' ';
              WSQLPREFIXO = WSQLPREFIXO||                                                   'AND x.BDCODCSOCIAL = '||:WCODCSOCIAL||') ';
              -- Já abateu as exclusões no select complementar acima... ';
                         --/* 04 - VL_EXC_COOP_GER */          -SUM(IIF(('||:WCODQUADRO||' = 19), COALESCE(m211.BDVLREXCLUGERPIS,0), COALESCE(m211.BDVLREXCLUGERCOFINS,0)))
                         --/* 05 - VL_EXC_ESP_COOP */          -SUM(IIF(('||:WCODQUADRO||' = 19), COALESCE(m211.BDVLREXCLUBCPIS,0), COALESCE(m211.BDVLREXCLUBCCOFINS,0)))
              WSQLPREFIXO = WSQLPREFIXO||                                                ') AS BDVL_BC_CONT, ';
              WSQLPREFIXO = WSQLPREFIXO||''||:PRRETIFICADORA||' BDRETIFICADORA ';
              WSQLPREFIXO = WSQLPREFIXO||'FROM VEF_EMP_TSOCCOOPM211M611 m211 ';
              WSQLPREFIXO = WSQLPREFIXO||'LEFT OUTER JOIN TEMPRESAS emp ON (emp.BDCODEMP = m211.BDCODEMP) ';
              WSQLPREFIXO = WSQLPREFIXO||'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = M211.BDCODEMP AND SCP.BDCODSCP = M211.BDCODSCP AND SCP.BDREFEMP = M211.BDREFSOC AND '||:PRAJUSTESCP||' = ''TRUE'') ';
              WSQLPREFIXO = WSQLPREFIXO||'WHERE ((('||:PRAJUSTESCP||' = ''TRUE'') AND (m211.BDCODEMP = '||:WCODEMP||' AND (M211.BDCODSCP IS NULL OR M211.BDCODSCP = 0) OR (SCP.BDCODEMPSCP = '||:WCODEMP||'))) ';
              WSQLPREFIXO = WSQLPREFIXO||'OR ('||:PRAJUSTESCP||' = ''FALSE'' AND m211.BDCODEMP = '||:WCODEMP||')) ';
              WSQLPREFIXO = WSQLPREFIXO||  'AND m211.BDREFERENCIA = '||:WREFERENCIA||' ';
              WSQLPREFIXO = WSQLPREFIXO||      'AND m211.BDCODCSOCIAL = '||:WCODCSOCIAL||' ';
              WSQLPREFIXO = WSQLPREFIXO||      'AND ( (('||:WCODQUADRO||' = 19) AND ((m211.BDALIQPIS > 0) OR (m211.BDVLREXCLUGERPIS > 0) OR (m211.BDVLREXCLUBCPIS > 0))) OR ';
              WSQLPREFIXO = WSQLPREFIXO||            '(('||:WCODQUADRO||' = 37) AND ((m211.BDALIQCOFINS > 0) OR (m211.BDVLREXCLUGERCOFINS > 0) OR (m211.BDVLREXCLUBCCOFINS > 0))) ) ';
              WSQLPREFIXO = WSQLPREFIXO||      'AND (EXISTS(SELECT * ';
              WSQLPREFIXO = WSQLPREFIXO||                  'FROM '||:WTABELAFISICA||' x ';
              WSQLPREFIXO = WSQLPREFIXO||                  'WHERE x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,m211.BDCODEMP) ';
              WSQLPREFIXO = WSQLPREFIXO||                    'AND X.BDRETIFICADORA = '||:PRRETIFICADORA||' ';
              WSQLPREFIXO = WSQLPREFIXO||                    'AND x.BDREFERENCIA = m211.BDREFERENCIA ';
              WSQLPREFIXO = WSQLPREFIXO||                    'AND x.BDCODCSOCIAL = m211.BDCODCSOCIAL ';
              WSQLPREFIXO = WSQLPREFIXO||                    'AND COALESCE(x.BDTIPOPROD,0) = COALESCE(m211.BDTIPOPROD,0) ';
              WSQLPREFIXO = WSQLPREFIXO||                    'AND (((x.BDCODQUADRO = 19) AND ((m211.BDALIQPIS = x.BDALIQ) OR (m211.BDALIQPIS = x.BDALIQ_QUANT)) ) OR ';
              WSQLPREFIXO = WSQLPREFIXO||                         '((x.BDCODQUADRO = 37) AND ((m211.BDALIQCOFINS = x.BDALIQ) OR (m211.BDALIQCOFINS = x.BDALIQ_QUANT))) ) ';
              WSQLPREFIXO = WSQLPREFIXO||                  ')) ';
              WSQLPREFIXO = WSQLPREFIXO||    'GROUP BY m211.BDCODEMP, emp.BDCODMATRIZ, m211.BDREFERENCIA, m211.BDTIPOSOCCOOP, m211.BDALIQPIS, m211.BDALIQCOFINS, SCP.BDCODEMPSCP ';
              execute statement ( WSQLPREFIXO );
            END
        END
    end

  IF (prverificarinconsistencias = 'TRUE') then
    begin
      /* Aliquota diferente do padrão nos lançamentos do M210 e M610 #Inconsistência# */
      wSQL =       'INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDREPLACES, BDRETIFICADORA) ';
      wSQL = wSQL||'SELECT aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, ';
    --  wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = aux.BDCODEMP AND x.BDCODMATRIZ = aux.BDCODMATRIZ AND x.BDREFERENCIA = '||:prREFERENCIA||') AS BDCODBLOCOM, ';
      wSQL = wSQL||' GETORDEMSEQUENCIAL_STR(aux.bdcodmatriz||''.''||aux.bdcodemp||''.''||aux.bdreferencia, '||:prCODEMP||'), ';
      wSQL = wSQL||       'aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODINC, '||iif(:PRAJUSTESCP = 'TRUE' and :PRCODEMPSO > 0, '''@SCP@'||:PRCODEMP||'''', 'null')||', ';
      wSQL = wSQL||:PRRETIFICADORA||' BDRETIFICADORA ';
      wSQL = wSQL||'FROM ( ';
      -- PIS/PASEP
      wSQL = wSQL||       'SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, ';
      wSQL = wSQL||       '       aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, 6 AS BDCODINC ';
      wSQL = wSQL||       'FROM TMP_VEF_EMP_TBLOCOM_M210_M610 aux ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = aux.BDCODEMP) ';
      wSQL = wSQL||       'left join TEMPRESAS SCP on (SCP.BDCODEMP = AUX.BDCODEMPSCP) ';
      wSQL = wSQL||       'left join VW_INT_SPEDPISCOFINS_REF SPED on (SPED.BDCODEMP = SCP.BDCODEMP) ';
      --wSQL = wSQL||       'WHERE (aux.BDCODCSTPIS NOT IN (02,03,05)) '; -- Para esses CSTs pode ser qualquer alíquota...
      wSQL = wSQL||       'WHERE (aux.BDCODCSTPIS IN (01)) '; -- Para esses CSTs pode ser qualquer alíquota...
      wSQL = wSQL||         'AND aux.BDCODEMP in (SELECT ex.BDCODEMP ';
      wSQL = wSQL||                              'FROM TEMPRESAS ex ';
      wSQL = wSQL||                              'WHERE ex.BDCODEMP = '||iif(:PRAJUSTESCP = 'TRUE' and :PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)||' ';
      wSQL = wSQL||                                 'OR ex.BDCODMATRIZ = '||iif(:PRAJUSTESCP = 'TRUE' and :PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)||') ';
      wSQL = wSQL||         'AND (aux.BDREFERENCIA = '||:prREFERENCIA||') ';

      IF (wINCTRIB = 1) THEN /* Incidência tributária 1 - Exclusivamente no regime não-cumulativo */
        BEGIN
          wSQL = wSQL||         'AND ((CAST(aux.BDALIQ_PIS as NUMERIC(7,4)) <> CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4)) ';
        END
      ELSE
      IF (wINCTRIB = 2) THEN /* Incidência tributária 2 - Exclusivamente no regime cumulativo */
        BEGIN
          wSQL = wSQL||         'AND ((CAST(aux.BDALIQ_PIS as NUMERIC(7,4)) <> CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)) ';
        END
      ELSE
      IF (wINCTRIB = 3) THEN /* Incidência tributária 3 - Regimes não-cumulativo e cumulativo */
        BEGIN
          wSQL = wSQL||         'AND ((((CAST(aux.BDALIQ_PIS as NUMERIC(7,4)) <> CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4))) AND (CAST(aux.BDALIQ_PIS as NUMERIC(7,4)) <> CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)))) ';
        END

      wSQL = wSQL|| ' and (AUX.BDCODEMPSCP = 0 or ' || :wINCTRIB || ' = SPED.BDINCTRIB + 1 or SPED.BDINCTRIB is null)) or ';
      wSQL = wSQL||      '(AUX.BDCODEMPSCP <> 0 and case ';
      wSQL = wSQL||                                  'when SPED.BDINCTRIB + 1 = 1 then (cast(aux.BDALIQ_PIS as NUMERIC(7,4)) <> cast(' || wALIQ_PIS_IT_1 || ' as NUMERIC(7,4))) ';
      wSQL = wSQL||                                  'when SPED.BDINCTRIB + 1 = 2 then (cast(aux.BDALIQ_PIS as NUMERIC(7,4)) <> cast(' || wALIQ_PIS_IT_2 || ' as NUMERIC(7,4))) ';
      wSQL = wSQL||                                  'when SPED.BDINCTRIB + 1 = 3 then ((cast(aux.BDALIQ_PIS as NUMERIC(7,4)) <> cast(' || wALIQ_PIS_IT_1 || ' as NUMERIC(7,4))) and (cast(aux.BDALIQ_PIS as NUMERIC(7,4)) <> cast(' || wALIQ_PIS_IT_2 || ' as NUMERIC(7,4)))) ';
      wSQL = wSQL||                                'end)) ';
    
      wSQL = wSQL||       'UNION ALL ';
      -- Cofins
      wSQL = wSQL||       'SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, ';
      wSQL = wSQL||       '       aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, 7 AS BDCODINC ';
      wSQL = wSQL||       'FROM TMP_VEF_EMP_TBLOCOM_M210_M610 aux ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = aux.BDCODEMP) ';
      wSQL = wSQL||       'left join TEMPRESAS SCP on (SCP.BDCODEMP = AUX.BDCODEMPSCP) ';
      wSQL = wSQL||       'left join VW_INT_SPEDPISCOFINS_REF SPED on (SPED.BDCODEMP = SCP.BDCODEMP) ';
      --wSQL = wSQL||       'WHERE (aux.BDCODCSTCOF NOT IN (02,03,05)) '; -- Para esses CSTs pode ser qualquer alíquota...
      wSQL = wSQL||       'WHERE (aux.BDCODCSTCOF IN (01)) '; -- Para esses CSTs pode ser qualquer alíquota...
      wSQL = wSQL||         'AND aux.BDCODEMP in (SELECT ex.BDCODEMP ';
      wSQL = wSQL||                              'FROM TEMPRESAS ex ';
      wSQL = wSQL||                              'WHERE ex.BDCODEMP = '||iif(:PRAJUSTESCP = 'TRUE' and :PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)||' ';
      wSQL = wSQL||                                 'OR ex.BDCODMATRIZ = '||iif(:PRAJUSTESCP = 'TRUE' and :PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)||') ';
      wSQL = wSQL||         'AND (aux.BDREFERENCIA = '||:prREFERENCIA||') ';

      IF (wINCTRIB = 1) THEN /* Incidência tributária 1 - Exclusivamente no regime não-cumulativo */
        BEGIN
          wSQL = wSQL||         'AND ((CAST(aux.BDALIQ_COF as NUMERIC(7,4)) <> CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4)) ';
        END
      ELSE
      IF (wINCTRIB = 2) THEN /* Incidência tributária 2 - Exclusivamente no regime cumulativo */
        BEGIN
          wSQL = wSQL||         'AND ((CAST(aux.BDALIQ_COF as NUMERIC(7,4)) <> CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)) ';
        END
      ELSE
      IF (wINCTRIB = 3) THEN /* Incidência tributária 3 - Regimes não-cumulativo e cumulativo */
        BEGIN
          wSQL = wSQL||         'AND ((((CAST(aux.BDALIQ_COF as NUMERIC(7,4)) <> CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4))) AND (CAST(aux.BDALIQ_COF as NUMERIC(7,4)) <> CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)))) ';
        END
    
      wSQL = wSQL|| ' and (AUX.BDCODEMPSCP = 0 or ' || :wINCTRIB || ' = SPED.BDINCTRIB + 1 or SPED.BDINCTRIB is null)) or ';
      wSQL = wSQL||      '(AUX.BDCODEMPSCP <> 0 and case ';
      wSQL = wSQL||                                  'when SPED.BDINCTRIB + 1 = 1 then (cast(aux.BDALIQ_COF as NUMERIC(7,4)) <> cast(' || wALIQ_COF_IT_1 || ' as NUMERIC(7,4))) ';
      wSQL = wSQL||                                  'when SPED.BDINCTRIB + 1 = 2 then (cast(aux.BDALIQ_COF as NUMERIC(7,4)) <> cast(' || wALIQ_COF_IT_2 || ' as NUMERIC(7,4))) ';
      wSQL = wSQL||                                  'when SPED.BDINCTRIB + 1 = 3 then ((cast(aux.BDALIQ_COF as NUMERIC(7,4)) <> cast(' || wALIQ_COF_IT_1 || ' as NUMERIC(7,4))) and (cast(aux.BDALIQ_COF as NUMERIC(7,4)) <> cast(' || wALIQ_COF_IT_2 || ' as NUMERIC(7,4)))) ';
      wSQL = wSQL||                                'end)) ';
      wSQL = wSQL||      ') aux ';
    
      EXECUTE STATEMENT ( wSQL );
    
      /*Sol: 87942 Patrick T. Sá 06/08/2018. As inconsistências são geradas por matriz, não deve buscar o código por empresa.*/
      /* CST 03 não permitida nos lançamentos "A100/A170, C600/C601,D200/D201,D300,D600/D601" #Inconsistência# */
      INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDRETIFICADORA)
      SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA,
    --         (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 /*AND x.BDCODEMP = :prCODEMP*/ AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA) AS BDCODBLOCOM,
             GETORDEMSEQUENCIAL_STR(aux.bdcodmatriz||'.'||aux.bdcodemp||'.'||aux.bdreferencia, :prCODEMP),
             aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, 4 AS BDCODINC,
             :PRRETIFICADORA BDRETIFICADORA
      FROM TMP_VEF_EMP_TBLOCOM_M210_M610 aux
      WHERE ((aux.BDCODCSTPIS IN (03)) OR (aux.BDCODCSTCOF IN (03)))
        AND (aux.BDCODTP IN (3,10,11,16))
        AND (aux.BDCODMATRIZ = :prCODEMP)
        AND (aux.BDREFERENCIA = :prREFERENCIA);
    
    INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDRETIFICADORA, BDREPLACES)
    SELECT 7 AS BDCODPERIODO, AUX.BDCODEMP, AUX.BDCODMATRIZ, AUX.BDREFERENCIA,
           GETORDEMSEQUENCIAL_STR(AUX.BDCODMATRIZ || '.' || AUX.BDCODEMP || '.' || AUX.BDREFERENCIA, :PRCODEMP) AS BDCODBLOCOM,
           AUX.BDCODTP, AUX.BDCHAVE, AUX.BDORDEM, AUX.BDORDEMPRO,
           CASE
             WHEN ((COALESCE(AUX.BDVL_BC_CONT_PIS, 0) = 0 AND COALESCE (BDQUANT_BC_PIS, 0) = 0) AND COALESCE(AUX.BDVLRPIS, 0) = 0) THEN 35
             WHEN ((COALESCE(AUX.BDVL_BC_CONT_PIS, 0) = 0 AND COALESCE (BDQUANT_BC_PIS, 0) = 0) AND COALESCE(AUX.BDVLRPIS, 0) > 0) THEN 36
             WHEN ((COALESCE(AUX.BDVL_BC_CONT_PIS, 0) > 0 OR COALESCE (BDQUANT_BC_PIS, 0) > 0) AND COALESCE(AUX.BDVLRPIS, 0) = 0) THEN 37
             ELSE 35 -- PADRÃO SE NENHUMA DAS CONDIÇÕES ESPECÍFICAS FOR ATENDIDA
           END AS BDCODINC, :PRRETIFICADORA AS BDRETIFICADORA, LPAD(CAST(AUX.BDCODCSTPIS AS VARCHAR(2)), 2, '0') AS BDREPLACES
    FROM TMP_VEF_EMP_TBLOCOM_M210_M610 AUX
    WHERE AUX.BDCODTP IN (1, 2, 3, 4) AND
          AUX.BDCODMATRIZ = :PRCODEMP AND
          AUX.BDREFERENCIA = :PRREFERENCIA AND
          AUX.BDCODCSTPIS IS NOT NULL AND
          ((AUX.BDCODCSTPIS IN (1, 2, 3, 50, 51, 52, 53, 54, 56) AND ((COALESCE(AUX.BDVL_BC_CONT_PIS, 0) = 0 AND COALESCE (BDQUANT_BC_PIS, 0) = 0) OR COALESCE(AUX.BDVLRPIS, 0) = 0)) OR
          ((AUX.BDCODCSTPIS NOT IN (4, 5, 6, 49, 55, 65, 70, 71, 72, 73, 74, 75, 98, 99)) AND (COALESCE(AUX.BDVL_BC_CONT_PIS, 0) > 0 OR COALESCE(BDQUANT_BC_PIS, 0) > 0) AND (COALESCE(AUX.BDVLRPIS, 0) = 0)) OR
          (((COALESCE(AUX.BDALIQ_PIS, 0) > 0) OR COALESCE(AUX.BDALIQ_QUANT_PIS, 0) > 0) AND ((COALESCE(AUX.BDVL_BC_CONT_PIS, 0) > 0 OR COALESCE(BDQUANT_BC_PIS, 0) > 0) AND (COALESCE(AUX.BDVLRPIS, 0) = 0))));


    INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDRETIFICADORA, BDREPLACES)
    SELECT 7 AS BDCODPERIODO, AUX.BDCODEMP, AUX.BDCODMATRIZ, AUX.BDREFERENCIA,
           GETORDEMSEQUENCIAL_STR(AUX.BDCODMATRIZ || '.' || AUX.BDCODEMP || '.' || AUX.BDREFERENCIA, :PRCODEMP) AS BDCODBLOCOM,
           AUX.BDCODTP, AUX.BDCHAVE, AUX.BDORDEM, AUX.BDORDEMPRO,
           CASE
             WHEN ((COALESCE(AUX.BDVL_BC_CONT_COF, 0) = 0 AND COALESCE (BDQUANT_BC_COF, 0) = 0) AND COALESCE(AUX.BDVLRCOFINS, 0) = 0) THEN 32
             WHEN ((COALESCE(AUX.BDVL_BC_CONT_COF, 0) = 0 AND COALESCE (BDQUANT_BC_COF, 0) = 0) AND COALESCE(AUX.BDVLRCOFINS, 0) > 0) THEN 33
             WHEN ((COALESCE(AUX.BDVL_BC_CONT_COF, 0) > 0 OR COALESCE (BDQUANT_BC_COF, 0) > 0) AND COALESCE(AUX.BDVLRCOFINS, 0) = 0) THEN 34
             ELSE 32 -- PADRÃO SE NENHUMA DAS CONDIÇÕES ESPECÍFICAS FOR ATENDIDA
           END AS BDCODINC, :PRRETIFICADORA AS BDRETIFICADORA, LPAD(CAST(AUX.BDCODCSTCOF AS VARCHAR(2)), 2, '0') AS BDREPLACES
    FROM TMP_VEF_EMP_TBLOCOM_M210_M610 AUX
    WHERE AUX.BDCODTP IN (1, 2, 3, 4) AND
          AUX.BDCODMATRIZ = :PRCODEMP AND
          AUX.BDREFERENCIA = :PRREFERENCIA AND
          AUX.BDCODCSTCOF IS NOT NULL AND
          ((AUX.BDCODCSTCOF IN (1, 2, 3, 50, 51, 52, 53, 54, 56) AND ((COALESCE(AUX.BDVL_BC_CONT_COF, 0) = 0 AND COALESCE (BDQUANT_BC_COF, 0) = 0) OR COALESCE(AUX.BDVLRCOFINS, 0) = 0)) OR
          ((AUX.BDCODCSTCOF NOT IN (4, 5, 6, 49, 55, 65, 70, 71, 72, 73, 74, 75, 98, 99)) AND (COALESCE(AUX.BDVL_BC_CONT_COF, 0) > 0 OR COALESCE(BDQUANT_BC_COF, 0) > 0) AND (COALESCE(AUX.BDVLRCOFINS, 0) = 0)) OR
          (((COALESCE(AUX.BDALIQ_COF, 0) > 0) OR COALESCE(AUX.BDALIQ_QUANT_COF, 0) > 0) AND ((COALESCE(AUX.BDVL_BC_CONT_COF, 0) > 0 OR COALESCE(BDQUANT_BC_COF, 0) > 0) AND (COALESCE(AUX.BDVLRCOFINS, 0) = 0))));



    INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDRETIFICADORA, BDREPLACES)
    SELECT 7 AS BDCODPERIODO, AUX.BDCODEMP, AUX.BDCODMATRIZ, AUX.BDREFERENCIA,
           GETORDEMSEQUENCIAL_STR(AUX.BDCODMATRIZ || '.' || AUX.BDCODEMP || '.' || AUX.BDREFERENCIA, :PRCODEMP) AS BDCODBLOCOM,
           AUX.BDCODTP, AUX.BDCHAVE, AUX.BDORDEM, AUX.BDORDEMPRO, 39 AS BDCODINC, :PRRETIFICADORA AS BDRETIFICADORA, LPAD(CAST(AUX.BDCODCSTPIS AS VARCHAR(2)), 2, '0') AS BDREPLACES
    FROM TMP_VEF_EMP_TBLOCOM_M210_M610 AUX
    WHERE AUX.BDCODTP IN (1, 2, 3, 4) AND
          AUX.BDCODMATRIZ = :PRCODEMP AND
          AUX.BDREFERENCIA = :PRREFERENCIA AND
          ((AUX.BDCODCSTPIS NOT IN (4, 5, 6, 49, 55, 65, 70, 71, 72, 73, 74, 75, 98, 99) AND AUX.BDCODCSTPIS IS NOT NULL AND (coalesce(AUX.BDQUANT_BC_PIS, 0) > 0 or coalesce(AUX.BDVL_BC_CONT_PIS, 0) > 0)) OR
          (AUX.BDCODCSTPIS in (1, 2, 3, 50, 51, 52, 53, 54, 56))) AND
          (COALESCE(AUX.BDALIQ_QUANT_PIS, 0) = 0 AND COALESCE(AUX.BDALIQ_PIS, 0) = 0);


    INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE,
                                  BDORDEM, BDORDEMPRO, BDCODINC, BDRETIFICADORA, BDREPLACES)
    SELECT 7 AS BDCODPERIODO, AUX.BDCODEMP, AUX.BDCODMATRIZ, AUX.BDREFERENCIA,
           GETORDEMSEQUENCIAL_STR(AUX.BDCODMATRIZ || '.' || AUX.BDCODEMP || '.' || AUX.BDREFERENCIA, :PRCODEMP) AS BDCODBLOCOM,
           AUX.BDCODTP, AUX.BDCHAVE, AUX.BDORDEM, AUX.BDORDEMPRO, 38 AS BDCODINC, :PRRETIFICADORA AS BDRETIFICADORA, LPAD(CAST(AUX.BDCODCSTCOF AS VARCHAR(2)), 2, '0') AS BDREPLACES
    FROM TMP_VEF_EMP_TBLOCOM_M210_M610 AUX
    WHERE AUX.BDCODTP IN (1, 2, 3, 4) AND
          AUX.BDCODMATRIZ = :PRCODEMP AND
          AUX.BDREFERENCIA = :PRREFERENCIA AND
          ((AUX.BDCODCSTCOF NOT IN (4, 5, 6, 49, 55, 65, 70, 71, 72, 73, 74, 75, 98, 99) AND AUX.BDCODCSTCOF IS NOT NULL AND (coalesce(AUX.BDQUANT_BC_COF, 0) > 0 or coalesce(AUX.BDVL_BC_CONT_COF, 0) > 0)) OR
          (AUX.BDCODCSTCOF in (1, 2, 3, 50, 51, 52, 53, 54, 56))) AND
          (COALESCE(AUX.BDALIQ_QUANT_COF, 0) = 0 AND COALESCE(AUX.BDALIQ_COF, 0) = 0);

      /*Sol: 87942 Patrick T. Sá 06/08/2018. As inconsistências são geradas por matriz, não deve buscar o código por empresa.*/
      /* CST diferente de 01, a única permitida nos lançamentos de operações imobiliárias  #Inconsistência# */
      INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDRETIFICADORA)
      SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA,
    --         (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 /*AND x.BDCODEMP = :prCODEMP*/ AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA) AS BDCODBLOCOM,
             GETORDEMSEQUENCIAL_STR(aux.bdcodmatriz||'.'||aux.bdcodemp||'.'||aux.bdreferencia, :prCODEMP),
             aux.BDCODTP, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, 10 AS BDCODINC,
             :PRRETIFICADORA BDRETIFICADORA
      FROM TMP_VEF_EMP_TBLOCOM_M210_M610 aux
      WHERE ((aux.BDCODCSTPIS <> 01) OR (aux.BDCODCSTCOF <> 01))
        AND (aux.BDCODTP IN (14))
        AND (aux.BDCODMATRIZ = :prCODEMP)
        AND (aux.BDREFERENCIA = :prREFERENCIA);
    
      /*Sol: 87942 Patrick T. Sá 06/08/2018. As inconsistências são geradas por matriz, não deve buscar o código por empresa.*/
      IF (:wINDNATPJ IN (1,4)) THEN -- Apenas se a empresa for "01 - Sociedade cooperativa" ou "04 - Sociedade cooperativa participante de SCP como sócia ostensiva"
        BEGIN
          /* Registros de M210/M610 sem M211/M611 respectivo #Inconsistência# */
          INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDREPLACES, BDRETIFICADORA)
          SELECT 7 AS BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA,
    --             (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 /*AND x.BDCODEMP = :prCODEMP*/ AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA) AS BDCODBLOCOM,
                 GETORDEMSEQUENCIAL_STR(aux.bdcodmatriz||'.'||aux.bdcodemp||'.'||aux.bdreferencia, :prCODEMP),
                 NULL AS BDCODTP, NULL AS BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 11 AS BDCODINC,
                 aux.BDCODCSOCIAL||'¨'||CASE WHEN aux.BDCODQUADRO = 19 THEN 'PIS' ELSE 'Cofins' END||'¨'||IIF(aux.BDALIQ > 0, aux.BDALIQ, aux.BDALIQ_QUANT) AS BDREPLACES,
                 :PRRETIFICADORA BDRETIFICADORA
          FROM VEF_EMP_TBLOCOM210_M610 aux
          WHERE (aux.BDCODMATRIZ = :prCODEMP)
            AND (aux.BDREFERENCIA = :prREFERENCIA)
            AND (NOT EXISTS(SELECT *
                            FROM VEF_EMP_TBLOCOM211_M611 m211
                            WHERE m211.BDCODPERIODO = aux.BDCODPERIODO
                              AND m211.BDCODEMP = aux.BDCODEMP
                              AND m211.BDCODMATRIZ = aux.BDCODMATRIZ
                              AND m211.BDCODQUADRO = aux.BDCODQUADRO
                              AND m211.BDREFERENCIA = aux.BDREFERENCIA
                              AND m211.BDCHAVE = aux.BDCHAVE ));
        END
    end
END
^

create or alter procedure SP_APURACAO_BLOCOM_M210_M610_P2 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRAJUSTESCP DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
declare variable WINCTRIB integer;
declare variable WCODCRIT integer;
declare variable WSQL varchar(32750);
declare variable WSQLPREFIXO varchar(8000);
declare variable WSQLSUFIXO varchar(100);
declare variable WMOD_TRANSPORTE varchar(50);
declare variable WMOD_PROD varchar(50);
declare variable WALIQ_PIS_IT_1 varchar(5);
declare variable WALIQ_COF_IT_1 varchar(5);
declare variable WALIQ_PIS_IT_2 varchar(5);
declare variable WALIQ_COF_IT_2 varchar(5);
BEGIN
/* ***** Constantes das CFOPs que geram "NAT_BC_CRED" da tabela 4.3.7. ***** */
-- Modelos para lançamento de entrada, faz isso para não carregar dados de movimentos errados.
-- Por exemplo: Não carregar dados dos produtos em notas de transporte, caso tenham produtos lançados...
--wMOD_COMTELE = '21,22'; -- Lançamento de serviço de comunicação e telecomunicação D500/^D600 (modelo 21 e 22)
--wMOD_ENERGAS = '6,28,29'; -- Nota fiscal de conta de energia elétrica, água ou gás (C500)
wMOD_TRANSPORTE = '7,8,9,10,11,13,14,15,16,26,27,57,67,800,63'; -- Transporte
--wMOD_CFe = '59'; -- CF-e
-- Concatena todos os modelos anteriores, usar "NOT IN"...
--wMOD_PROD = wMOD_COMTELE||','||wMOD_ENERGAS||','||wMOD_TRANSPORTE;--||','||wMOD_CFe;
wMOD_PROD = wMOD_TRANSPORTE;--||','||wMOD_CFe;

--wCST_NAO_CUM = '1,2,3,4,32,71'; -- CSTs do regime não cumulativo
--wCST_CUM = '31,32,51,52,53,54,72'; -- CSTs do regime cumulativo

/* Incidência tributária 1 - Exclusivamente no regime não-cumulativo */
wALIQ_PIS_IT_1 = '1.65';
wALIQ_COF_IT_1 = '7.60';
/* Incidência tributária 2 - Exclusivamente no regime cumulativo */
wALIQ_PIS_IT_2 = '0.65';
wALIQ_COF_IT_2 = '3.00';
/*****************************************************************************/
  -- Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCODCRIT;

  if ((:PRCODEMPSO > 0) and ((wINCTRIB is null) or (wCODCRIT is null))) then
    begin
      SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMPSO
      INTO :wINCTRIB, :wCODCRIT;
    end
  
  IF ((wINCTRIB IS NOT NULL) AND (wCODCRIT IS NOT NULL)) THEN
    BEGIN
--      IF (wINCTRIB = 1) THEN /* Incidência tributária 1 - Exclusivamente no regime não-cumulativo */
--        wCST = wCST_NAO_CUM; -- CSTs do regime não cumulativo
--      ELSE
--      IF (wINCTRIB = 2) THEN /* Incidência tributária 2 - Exclusivamente no regime cumulativo */
--        wCST = wCST_CUM; -- CSTs do regime cumulativo
--      ELSE
--      IF (wINCTRIB = 3) THEN /* Incidência tributária 3 - Regimes não-cumulativo e cumulativo */
--        wCST = wCST_NAO_CUM||','||wCST_CUM; -- CSTs do regime não cumulativo e cumulativo

      wSQLPREFIXO =        'INSERT INTO TMP_VEF_EMP_TBLOCOM_M210_M610 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDCODCSTPIS, BDCODCSTCOF, BDTIPOPROD, BDCOD_CONT_PIS, BDCOD_CONT_COF, BDVL_REC_BRT, BDVL_BC_CONT_PIS, BDVL_BC_CONT_COF, BDALIQ_PIS, BDALIQ_COF, BDQUANT_BC_PIS, BDQUANT_BC_COF, BDALIQ_QUANT_PIS, BDALIQ_QUANT_COF,BDCODEMPSCP, BDCODNAT, BDTIPOREDZ, BDDESCPEREXP, BDDESCNATREC, BDDATANOTA, BDNUMDOC, BDVLRPIS, BDVLRCOFINS,BDCONDPGTO) ';

      wSQLPREFIXO = wSQLPREFIXO|| 'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, aux.BDCODCSTPIS, aux.BDCODCSTCOF, aux.BDTIPOPROD, ';
      IF (wINCTRIB = 1) THEN /* Incidência tributária 1 - Exclusivamente no regime não-cumulativo */
        BEGIN
          wSQLPREFIXO = wSQLPREFIXO||        'COALESCE(aux.BDCOD_CONT_PIS,(CASE aux.BDCODCSTPIS ';
          wSQLPREFIXO = wSQLPREFIXO||                                        'WHEN 1 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = Cast('||wALIQ_PIS_IT_1||' as NUMERIC(7,4))), 01, null) ';
          wSQLPREFIXO = wSQLPREFIXO||                                        'WHEN 2 THEN 02 ';
          wSQLPREFIXO = wSQLPREFIXO||                                        'WHEN 3 THEN 03 ';
          wSQLPREFIXO = wSQLPREFIXO||                                        'WHEN 5 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = Cast('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQLPREFIXO = wSQLPREFIXO||                                     'ELSE null ';
          wSQLPREFIXO = wSQLPREFIXO||                                     'end)) AS BDCOD_CONT_PIS,';

          wSQLPREFIXO = wSQLPREFIXO||        'COALESCE(aux.BDCOD_CONT_COF,(CASE aux.BDCODCSTCOF ';
          wSQLPREFIXO = wSQLPREFIXO||                                        'WHEN 1 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4))), 01, null) ';
          wSQLPREFIXO = wSQLPREFIXO||                                        'WHEN 2 THEN 02 ';
          wSQLPREFIXO = wSQLPREFIXO||                                        'WHEN 3 THEN 03 ';
          wSQLPREFIXO = wSQLPREFIXO||                                        'WHEN 5 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = Cast('||wALIQ_COF_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQLPREFIXO = wSQLPREFIXO||                                     'ELSE null ';
          wSQLPREFIXO = wSQLPREFIXO||                                     'end)) AS BDCOD_CONT_COF,';
        END
      ELSE
      IF (wINCTRIB = 2) THEN /* Incidência tributária 2 - Exclusivamente no regime cumulativo */
        BEGIN
          wSQLPREFIXO = wSQLPREFIXO||        'COALESCE(aux.BDCOD_CONT_PIS,(CASE aux.BDCODCSTPIS ';
          wSQLPREFIXO = wSQLPREFIXO||                                       'WHEN 1 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))), 51, null) ';
          wSQLPREFIXO = wSQLPREFIXO||                                       'WHEN 2 THEN 52 ';
          wSQLPREFIXO = wSQLPREFIXO||                                       'WHEN 3 THEN 53 ';
          wSQLPREFIXO = wSQLPREFIXO||                                       'WHEN 5 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = Cast('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQLPREFIXO = wSQLPREFIXO||                                     'ELSE null ';
          wSQLPREFIXO = wSQLPREFIXO||                                     'end)) AS BDCOD_CONT_PIS,';

          wSQLPREFIXO = wSQLPREFIXO||        'COALESCE(aux.BDCOD_CONT_COF,(CASE aux.BDCODCSTCOF ';
          wSQLPREFIXO = wSQLPREFIXO||                                       'WHEN 1 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4))), 51, null) ';
          wSQLPREFIXO = wSQLPREFIXO||                                       'WHEN 2 THEN 52 ';
          wSQLPREFIXO = wSQLPREFIXO||                                       'WHEN 3 THEN 53 ';
          wSQLPREFIXO = wSQLPREFIXO||                                       'WHEN 5 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = Cast('||wALIQ_COF_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQLPREFIXO = wSQLPREFIXO||                                     'ELSE null ';
          wSQLPREFIXO = wSQLPREFIXO||                                     'end)) AS BDCOD_CONT_COF,';
        END
      ELSE
      IF (wINCTRIB = 3) THEN /* Incidência tributária 3 - Regimes não-cumulativo e cumulativo */
        BEGIN
          wSQLPREFIXO = wSQLPREFIXO||        'COALESCE(aux.BDCOD_CONT_PIS,(CASE aux.BDCODCSTPIS ';
          wSQLPREFIXO = wSQLPREFIXO||                                        'WHEN 1 THEN ';
          wSQLPREFIXO = wSQLPREFIXO||                                           'CASE CAST(aux.BDALIQPIS as NUMERIC(7,4)) ';
          wSQLPREFIXO = wSQLPREFIXO||                                              'WHEN CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4)) THEN 01 ';
          wSQLPREFIXO = wSQLPREFIXO||                                              'WHEN CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)) THEN 51 ';
          wSQLPREFIXO = wSQLPREFIXO||                                           'END ';
          wSQLPREFIXO = wSQLPREFIXO||                                        'WHEN 2 THEN 02 ';
          wSQLPREFIXO = wSQLPREFIXO||                                        'WHEN 3 THEN 03 ';
          wSQLPREFIXO = wSQLPREFIXO||                                        'WHEN 5 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQLPREFIXO = wSQLPREFIXO||                                     'ELSE null ';
          wSQLPREFIXO = wSQLPREFIXO||                                     'end)) AS BDCOD_CONT_PIS,';

          wSQLPREFIXO = wSQLPREFIXO||        'COALESCE(aux.BDCOD_CONT_COF,(CASE aux.BDCODCSTCOF ';
          wSQLPREFIXO = wSQLPREFIXO||                                        'WHEN 1 THEN ';
          wSQLPREFIXO = wSQLPREFIXO||                                           'CASE CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) ';
          wSQLPREFIXO = wSQLPREFIXO||                                              'WHEN CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4)) THEN 01 ';
          wSQLPREFIXO = wSQLPREFIXO||                                              'WHEN CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)) THEN 51 ';
          wSQLPREFIXO = wSQLPREFIXO||                                           'END ';
          wSQLPREFIXO = wSQLPREFIXO||                                        'WHEN 2 THEN 02 ';
          wSQLPREFIXO = wSQLPREFIXO||                                        'WHEN 3 THEN 03 ';
          wSQLPREFIXO = wSQLPREFIXO||                                        'WHEN 5 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4))), 31, 32) ';
          wSQLPREFIXO = wSQLPREFIXO||                                     'ELSE null ';
          wSQLPREFIXO = wSQLPREFIXO||                                     'end)) AS BDCOD_CONT_COF,';
        END
      wSQLPREFIXO = wSQLPREFIXO||        'aux.BDVL_ITEM AS BDVL_REC_BRT,';
      /* Se tiver campo de valor da base de calculo por quandtidade e alíquota em R$, leva os mesmo, caso contrário, verifica pela CST, se for = 3, vai nas quantidades e alíquotas em R$... */
      wSQLPREFIXO = wSQLPREFIXO||        'iif(((aux.BDQUANT_BC_PIS is null) AND (AUX.BDCODCSTPIS = 3)), 0, AUX.BDBCPIS) AS BDVL_BC_CONT_PIS,';
      wSQLPREFIXO = wSQLPREFIXO||        'iif(((aux.BDQUANT_BC_COF is null) AND (AUX.BDCODCSTCOF = 3)), 0, AUX.BDBCCOFINS) AS BDVL_BC_CONT_COF,';
      wSQLPREFIXO = wSQLPREFIXO||        'iif(((aux.BDALIQ_PIS_QUANT is null) AND (aux.BDCODCSTPIS = 3)), 0, aux.BDALIQPIS) AS BDALIQ_PIS,';
      wSQLPREFIXO = wSQLPREFIXO||        'iif(((aux.BDALIQ_COF_QUANT is null) AND (aux.BDCODCSTPIS = 3)), 0, aux.BDALIQCOFINS) AS BDALIQ_COF,';
      wSQLPREFIXO = wSQLPREFIXO||        'COALESCE(aux.BDQUANT_BC_PIS, iif(aux.BDCODCSTPIS = 3, aux.BDBCPIS, 0)) AS BDQUANT_BC_PIS,';
      wSQLPREFIXO = wSQLPREFIXO||        'COALESCE(aux.BDQUANT_BC_COF, iif(AUX.BDCODCSTCOF = 3, AUX.BDBCCOFINS, 0)) AS BDQUANT_BC_COF,';
      wSQLPREFIXO = wSQLPREFIXO||        'COALESCE(aux.BDALIQ_PIS_QUANT, iif(AUX.BDCODCSTPIS = 3, AUX.BDALIQPIS, 0)) AS BDALIQ_QUANT_PIS,';
      wSQLPREFIXO = wSQLPREFIXO||        'COALESCE(aux.BDALIQ_COF_QUANT, iif(AUX.BDCODCSTPIS = 3, AUX.BDALIQCOFINS, 0)) AS BDALIQ_QUANT_COF, ';
      /*Camilla M. SCP*/
      wSQLPREFIXO = wSQLPREFIXO||        IIF(:PRAJUSTESCP = 'TRUE',' COALESCE(aux.BDCODEMPSCP,0) ',' 0')||' BDCODEMPSCP, bdcodnat,BDTIPOREDZ, BDDESCPEREXP,  BDDESCNATREC, BDDATANOTA, BDNUMDOC, BDVLRPIS, BDVLRCOFINS, BDCONDPGTO ';
      wSQLPREFIXO = wSQLPREFIXO|| 'FROM ( ';
      
      wSQLSUFIXO =                      ') aux ';

      if ((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0)) then
        WSQLSUFIXO = WSQLSUFIXO || ' where (coalesce(AUX.BDCODEMPSCP, 0) = '|| :PRCODEMP || ') ';
      else
      if (:PRAJUSTESCP = 'TRUE') then
        wSQLSUFIXO = wSQLSUFIXO || ' where (coalesce(AUX.BDCODEMPSCP, 0) = 0) ';

                           /* C425 - Varias alíquotas */
      wSQL =               'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, c425.BDCHAVE, c425.BDORDEMICMS AS BDORDEM, c425.BDORDEMC425 AS BDORDEMPRO, 7 AS BDCODTP, 0 AS BDTIPOPROD, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'c425.BDVLRACU AS BDVL_ITEM,';
      wSQL = wSQL||               'c425.BDCODCSTPIS, c425.BDVL_BC_PIS AS BDBCPIS, c425.BDALIQ_PIS AS BDALIQPIS, c425.BDVLRPIS,';
      wSQL = wSQL||               'c425.BDCODCSTCOF, c425.BDVL_BC_COFINS AS BDBCCOFINS, c425.BDALIQ_COFINS AS BDALIQCOFINS, c425.BDVLRCOFINS,';
      wSQL = wSQL||               'c425.BDALIQ_PIS_QUANT AS BDQUANT_BC_PIS, c425.BDQUANT_BC_PIS AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'c425.BDALIQ_COFINS_QUANT AS BDQUANT_BC_COF, c425.BDQUANT_BC_COFINS AS BDALIQ_COF_QUANT, SCP.BDCODEMPSCP,  C425.bdcodnat ,TOT.BDNOMETOT || '' - '' || IIF(SUBSTRING(CAST(ALIQ.BDALIQICMS AS NUMERIC(15,2)) FROM 3 FOR 4) > 0, CAST(ALIQ.BDALIQICMS AS NUMERIC(15,2)), CAST(CAST(ALIQ.BDALIQICMS AS NUMERIC(15,0)) AS VARCHAR(10)))  || ''%'' BDTIPOREDZ, null BDDESCPEREXP, null BDDESCNATREC, mov.BDDATAREDZ AS BDDATANOTA, MOV.BDNUMCUPINI BDNUMDOC, ';
      wSQL = wSQL||               '(SELECT FIRST 1 BDCONDPGTO FROM VEF_EMP_TREDZVARCFOP V WHERE V.BDCODEMP = MOV.BDCODEMP AND V.BDCHAVE = MOV.BDCHAVE AND V.BDCODNAT = C425.BDCODNAT) ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||              'SELECT r.BDCODEMP, r.BDCHAVE,  r.BDREFLAN, R.BDDATAREDZ, r.BDNUMCUPINI ';
      wSQL = wSQL||              'FROM VEF_EMP_TREDZ r ';
      wSQL = wSQL||              'WHERE R.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               ' AND r.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TREDZVARALIQ aliq on (aliq.BDCODEMP = mov.BDCODEMP AND aliq.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TREDZC425ALIQ c425 on (c425.BDCODEMP = mov.BDCODEMP AND c425.BDCHAVE = mov.BDCHAVE AND c425.BDORDEMICMS = aliq.BDORDEMICMS) ';
      wSQL = wSQL||        'LEFT OUTER JOIN( ';
      wSQL = wSQL||        '    SELECT COUNT(*) QUANT, VAR.BDCODEMP, VAR.BDCHAVE, SCP.BDCODEMPSCP ';
      wSQL = wSQL||        '    FROM VEF_EMP_TREDZVARCFOP VAR ';
      wSQL = wSQL||        '    LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = VAR.BDCODEMP AND SCP.BDCODSCP = VAR.BDCODSCP AND SCP.BDREFEMP = VAR.BDREFSOC) ';
      wSQL = wSQL||        '    WHERE VAR.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||        '    GROUP BY VAR.BDCODEMP, VAR.BDCHAVE, SCP.BDCODEMPSCP ';
      wSQL = wSQL||        '    HAVING COUNT(*) = (SELECT COUNT(*) FROM VEF_EMP_TREDZVARCFOP VARC WHERE VARC.BDCODEMP = VAR.BDCODEMP AND VARC.BDCHAVE = VAR.BDCHAVE) ';
      wSQL = wSQL||        ') SCP ON (SCP.BDCODEMP = MOV.BDCODEMP AND SCP.BDCHAVE = MOV.BDCHAVE) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_BASE_TTABTOTPAR TOT ON (TOT.BDORDEMTOT = C425.BDORDEMTOT) ';
      wSQL = wSQL||        'union all ';
                           /* C425 - Varias alíquotas - ISS */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, c425.BDCHAVE, c425.BDORDEMISS AS BDORDEM, c425.BDORDEMC425 AS BDORDEMPRO, 7 AS BDCODTP, 0 AS BDTIPOPROD, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'c425.BDVLRACU AS BDVL_ITEM,';
      wSQL = wSQL||               'c425.BDCODCSTPIS, c425.BDVL_BC_PIS AS BDBCPIS, c425.BDALIQ_PIS AS BDALIQPIS, c425.BDVLRPIS,';
      wSQL = wSQL||               'c425.BDCODCSTCOF, c425.BDVL_BC_COFINS AS BDBCCOFINS, c425.BDALIQ_COFINS AS BDALIQCOFINS, c425.BDVLRCOFINS,';
      wSQL = wSQL||               'c425.BDALIQ_PIS_QUANT AS BDQUANT_BC_PIS, c425.BDQUANT_BC_PIS AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'c425.BDALIQ_COFINS_QUANT AS BDQUANT_BC_COF, c425.BDQUANT_BC_COFINS AS BDALIQ_COF_QUANT, SCP.BDCODEMPSCP,  C425.bdcodnat ,TOT.BDNOMETOT || '' - '' || IIF(SUBSTRING(CAST(ALIQ.BDALIQISS AS NUMERIC(15,2)) FROM 3 FOR 4) > 0, CAST(ALIQ.BDALIQISS AS NUMERIC(15,2)), CAST(CAST(ALIQ.BDALIQISS AS NUMERIC(15,0)) AS VARCHAR(10)))  || ''%'' BDTIPOREDZ, null BDDESCPEREXP, null BDDESCNATREC, mov.BDDATAREDZ AS BDDATANOTA, MOV.BDNUMCUPINI BDNUMDOC, ';
      wSQL = wSQL||               '(SELECT FIRST 1 BDCONDPGTO FROM VEF_EMP_TREDZVARCFOP V WHERE V.BDCODEMP = MOV.BDCODEMP AND V.BDCHAVE = MOV.BDCHAVE AND V.BDCODNAT = C425.BDCODNAT) ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||              'SELECT r.BDCODEMP, r.BDCHAVE,  r.BDREFLAN, R.BDDATAREDZ, R.BDNUMCUPINI ';
      wSQL = wSQL||              'FROM VEF_EMP_TREDZ r ';
      wSQL = wSQL||              'WHERE R.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               ' AND r.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TREDZVARALIQISS aliq on (aliq.BDCODEMP = mov.BDCODEMP AND aliq.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TREDZC425ALIQISS c425 on (c425.BDCODEMP = mov.BDCODEMP AND c425.BDCHAVE = mov.BDCHAVE AND c425.BDORDEMISS = aliq.BDORDEMISS) ';
      wSQL = wSQL||        'LEFT OUTER JOIN( ';
      wSQL = wSQL||        '    SELECT COUNT(*) QUANT, VAR.BDCODEMP, VAR.BDCHAVE, SCP.BDCODEMPSCP, VAR.BDCONDPGTO ';
      wSQL = wSQL||        '    FROM VEF_EMP_TREDZVARCFOP VAR ';
      wSQL = wSQL||        '    LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = VAR.BDCODEMP AND SCP.BDCODSCP = VAR.BDCODSCP AND SCP.BDREFEMP = VAR.BDREFSOC) ';
      wSQL = wSQL||        '    WHERE VAR.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||        '    GROUP BY VAR.BDCODEMP, VAR.BDCHAVE, SCP.BDCODEMPSCP, VAR.BDCONDPGTO ';
      wSQL = wSQL||        '    HAVING COUNT(*) = (SELECT COUNT(*) FROM VEF_EMP_TREDZVARCFOP VARC WHERE VARC.BDCODEMP = VAR.BDCODEMP AND VARC.BDCHAVE = VAR.BDCHAVE) ';
      wSQL = wSQL||        ') SCP ON (SCP.BDCODEMP = MOV.BDCODEMP AND SCP.BDCHAVE = MOV.BDCHAVE) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_BASE_TTABTOTPAR TOT ON (TOT.BDORDEMTOT = C425.BDORDEMTOT) ';
      wSQL = wSQL||        'union all ';
                           /* C425 */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, c425.BDCHAVE, c425.BDORDEMTOT AS BDORDEM, c425.BDORDEMC425 AS BDORDEMPRO, 6 AS BDCODTP, 0 AS BDTIPOPROD, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'c425.BDVLRACU AS BDVL_ITEM,';
      wSQL = wSQL||               'c425.BDCODCSTPIS, c425.BDVL_BC_PIS AS BDBCPIS, c425.BDALIQ_PIS AS BDALIQPIS, c425.BDVLRPIS,';
      wSQL = wSQL||               'c425.BDCODCSTCOF, c425.BDVL_BC_COFINS AS BDBCCOFINS, c425.BDALIQ_COFINS AS BDALIQCOFINS, c425.BDVLRCOFINS,';
      wSQL = wSQL||               'c425.BDALIQ_PIS_QUANT AS BDQUANT_BC_PIS, c425.BDQUANT_BC_PIS AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'c425.BDALIQ_COFINS_QUANT AS BDQUANT_BC_COF, c425.BDQUANT_BC_COFINS AS BDALIQ_COF_QUANT, SCP.BDCODEMPSCP,  C425.bdcodnat ,TOT.BDNOMETOT BDTIPOREDZ, null BDDESCPEREXP, null BDDESCNATREC, mov.BDDATAREDZ AS BDDATANOTA, MOV.BDNUMCUPINI BDNUMDOC,  ';
      wSQL = wSQL||               '(SELECT FIRST 1 BDCONDPGTO FROM VEF_EMP_TREDZVARCFOP V WHERE V.BDCODEMP = MOV.BDCODEMP AND V.BDCHAVE = MOV.BDCHAVE AND V.BDCODNAT = C425.BDCODNAT) ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||              'SELECT r.BDCODEMP, r.BDCHAVE, r.BDREFLAN, R.BDDATAREDZ, r.BDNUMCUPINI ';
      wSQL = wSQL||              'FROM VEF_EMP_TREDZ r ';
      wSQL = wSQL||              'WHERE R.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               ' AND r.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TREDZC425 c425 on (c425.BDCODEMP = mov.BDCODEMP AND c425.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'LEFT OUTER JOIN( ';
      wSQL = wSQL||        '    SELECT COUNT(*) QUANT, VAR.BDCODEMP, VAR.BDCHAVE, SCP.BDCODEMPSCP ';
      wSQL = wSQL||        '    FROM VEF_EMP_TREDZVARCFOP VAR ';
      wSQL = wSQL||        '    LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = VAR.BDCODEMP AND SCP.BDCODSCP = VAR.BDCODSCP AND SCP.BDREFEMP = VAR.BDREFSOC) ';
      wSQL = wSQL||        '    WHERE VAR.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||        '    GROUP BY VAR.BDCODEMP, VAR.BDCHAVE, SCP.BDCODEMPSCP ';
      wSQL = wSQL||        '    HAVING COUNT(*) = (SELECT COUNT(*) FROM VEF_EMP_TREDZVARCFOP VARC WHERE VARC.BDCODEMP = VAR.BDCODEMP AND VARC.BDCHAVE = VAR.BDCHAVE) ';
      wSQL = wSQL||        ') SCP ON (SCP.BDCODEMP = MOV.BDCODEMP AND SCP.BDCHAVE = MOV.BDCHAVE) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_BASE_TTABTOTPAR TOT ON (TOT.BDORDEMTOT = C425.BDORDEMTOT) ';

      wSQL = wSQL||        'union all ';
                           /* C470 */
      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, c470.BDCHAVE, c470.BDORDEMDOCECF AS BDORDEM, c470.BDORDEMITEM AS BDORDEMPRO, 8 AS BDCODTP, 0 AS BDTIPOPROD, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
      wSQL = wSQL||               'c470.BDVLRTOTPRO AS BDVL_ITEM,';
      wSQL = wSQL||               'c470.BDCODCSTPIS, c470.BDVL_BC_PIS AS BDBCPIS, c470.BDALIQ_PIS AS BDALIQPIS, c470.BDVLRPIS,';
      wSQL = wSQL||               'c470.BDCODCSTCOF, c470.BDVL_BC_COFINS AS BDBCCOFINS, c470.BDALIQ_COFINS AS BDALIQCOFINS, c470.BDVLRCOFINS,';
      wSQL = wSQL||               'c470.BDALIQ_PIS_QUANT AS BDQUANT_BC_PIS, c470.BDQUANT_BC_PIS AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'c470.BDALIQ_COFINS_QUANT AS BDQUANT_BC_COF, c470.BDQUANT_BC_COFINS AS BDALIQ_COF_QUANT, SCP.BDCODEMPSCP,c470.bdcodnat,''DOC EMITIDOS POR ECF'' BDTIPOREDZ, null BDDESCPEREXP, null BDDESCNATREC, mov.BDDATAREDZ AS BDDATANOTA, MOV.BDNUMCUPINI BDNUMDOC, ';
      wSQL = wSQL||               '(SELECT FIRST 1 BDCONDPGTO FROM VEF_EMP_TREDZVARCFOP V WHERE V.BDCODEMP = MOV.BDCODEMP AND V.BDCHAVE = MOV.BDCHAVE AND V.BDCODNAT = c470.BDCODNAT) ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||              'SELECT r.BDCODEMP, r.BDCHAVE, r.BDREFLAN, R.BDDATAREDZ, r.BDNUMCUPINI ';
      wSQL = wSQL||              'FROM VEF_EMP_TREDZ r ';
      wSQL = wSQL||              'WHERE R.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               ' AND r.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TDOCECF c460 on (c460.BDCODEMP = mov.BDCODEMP AND c460.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'JOIN VEF_EMP_TITEMDOCECF c470 on (c470.BDCODEMP = c460.BDCODEMP AND c470.BDCHAVE = c460.BDCHAVE AND c470.BDORDEMDOCECF = c460.BDORDEMDOCECF) ';
      wSQL = wSQL||        'LEFT OUTER JOIN( ';
      wSQL = wSQL||        '    SELECT COUNT(*) QUANT, VAR.BDCODEMP, VAR.BDCHAVE, SCP.BDCODEMPSCP ';
      wSQL = wSQL||        '    FROM VEF_EMP_TREDZVARCFOP VAR ';
      wSQL = wSQL||        '    LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = VAR.BDCODEMP AND SCP.BDCODSCP = VAR.BDCODSCP AND SCP.BDREFEMP = VAR.BDREFSOC) ';
      wSQL = wSQL||        '    WHERE VAR.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||        '    GROUP BY VAR.BDCODEMP, VAR.BDCHAVE, SCP.BDCODEMPSCP ';
      wSQL = wSQL||        '    HAVING COUNT(*) = (SELECT COUNT(*) FROM VEF_EMP_TREDZVARCFOP VARC WHERE VARC.BDCODEMP = VAR.BDCODEMP AND VARC.BDCHAVE = VAR.BDCHAVE) ';
      wSQL = wSQL||        ') SCP ON (SCP.BDCODEMP = MOV.BDCODEMP AND SCP.BDCHAVE = MOV.BDCHAVE) ';
      wSQL = wSQL||        'WHERE c460.bdCODSITNF NOT IN (2,3,4,5) '; -- Alt.: #100520 #100827 - Não considerar documentos cancelados...

      wSQL = wSQL||        'union all ';
                           /* F500 no lançamento da Redução Z */
      wSQL = wSQL||        'SELECT mov.bdCODEMP, COALESCE(emp.bdCODMATRIZ, mov.bdCODEMP) AS bdCODMATRIZ, mov.bdREFLAN AS bdREFERENCIA, f500.bdCHAVE, f500.bdORDEMF500 AS BDORDEM, NULL AS bdORDEMPRO, 17 AS BDCODTP, 0 AS BDTIPOPROD, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF,';
      wSQL = wSQL||               'f500.bdVLRREC AS bdVL_ITEM,';
      wSQL = wSQL||               'f500.bdCODCSTPIS, f500.bdBASEPIS AS bdBCPIS, f500.bdALIQPIS AS bdALIQPIS, f500.bdVLRPIS,';
      wSQL = wSQL||               'f500.bdCODCSTCOF, f500.bdBASECOF AS BDBCCOFINS, f500.bdALIQCOF AS bdALIQCOFINS, f500.bdVLRCOF,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT, NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT, SCP.BDCODEMPSCP, scp.bdcodnat, ''F500 - Redução Z'' bdtiporedz, null BDDESCPEREXP, null BDDESCNATREC, mov.BDDATAREDZ AS BDDATANOTA, MOV.BDNUMCUPINI BDNUMDOC, SCP.BDCONDPGTO ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||              'SELECT z.bdCODEMP, z.bdCHAVE, z.bdREFLAN, Z.BDDATAREDZ, z.BDNUMCUPINI ';
      wSQL = wSQL||              'FROM VEF_EMP_TREDZ z ';
      wSQL = wSQL||              'WHERE z.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND z.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                'AND (NOT EXISTS(SELECT * FROM VEF_EMP_TREDZC425 c WHERE c.bdCODEMP = z.BDCODEMP AND c.bdCHAVE = z.bdCHAVE)) ';
      wSQL = wSQL||                'AND (NOT EXISTS(SELECT * FROM VEF_EMP_TREDZC425ALIQ c WHERE c.bdCODEMP = z.bdCODEMP AND c.bdCHAVE = z.bdCHAVE)) ';
      wSQL = wSQL||                'AND (NOT EXISTS(SELECT * FROM VEF_EMP_TREDZC425ALIQISS i WHERE i.bdCODEMP = z.bdCODEMP AND i.bdCHAVE = z.bdCHAVE)) ';
      wSQL = wSQL||                'AND (NOT EXISTS(SELECT * FROM VEF_EMP_TITEMDOCECF i WHERE i.bdCODEMP = z.bdCODEMP AND i.bdCHAVE = z.bdCHAVE)) ';
      wSQL = wSQL||              ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TF500REDZ f500 ON (f500.BDCODEMP = mov.BDCODEMP AND f500.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||        'LEFT OUTER JOIN( ';
      WSQL = WSQL||        '    SELECT COUNT(*) QUANT, VAR.BDCODEMP, VAR.BDCHAVE, SCP.BDCODEMPSCP, VAR.BDCODNAT, VAR.BDCONDPGTO ';
      wSQL = wSQL||        '    FROM VEF_EMP_TREDZVARCFOP VAR ';
      wSQL = wSQL||        '    LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = VAR.BDCODEMP AND SCP.BDCODSCP = VAR.BDCODSCP AND SCP.BDREFEMP = VAR.BDREFSOC) ';
      wSQL = wSQL||        '    WHERE VAR.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||        '    GROUP BY VAR.BDCODEMP, VAR.BDCHAVE, SCP.BDCODEMPSCP, VAR.BDCODNAT, VAR.BDCONDPGTO ';
      wSQL = wSQL||        '    HAVING COUNT(*) = (SELECT COUNT(*) FROM VEF_EMP_TREDZVARCFOP VARC WHERE VARC.BDCODEMP = VAR.BDCODEMP AND VARC.BDCHAVE = VAR.BDCHAVE) ';
      wSQL = wSQL||        ') SCP ON (SCP.BDCODEMP = MOV.BDCODEMP AND SCP.BDCHAVE = MOV.BDCHAVE) ';

      wSQL = wSQL||        'union all ';
      
                           /* Lançamento de operações imobiliárias(F200) */

      wSQL = wSQL||        'select MOV.BDCODEMP, MOV.BDCODMATRIZ, MOV.BDREFERENCIA, MOV.BDCHAVE, MOV.BDORDEM, MOV.BDORDEMPRO, MOV.BDCODTP, 0 AS BDTIPOPROD, MOV.BDCOD_CONT_PIS, ';
      wSQL = wSQL||        'MOV.BDCOD_CONT_COF, MOV.BDVL_ITEM, MOV.BDCODCSTPIS, MOV.BDBCPIS, MOV.BDALIQPIS, MOV.BDVLRPIS, MOV.BDCODCSTCOF, MOV.BDBCCOFINS, MOV.BDALIQCOFINS, ';
      wSQL = wSQL||        'MOV.BDVLRCOFINS, MOV.BDQUANT_BC_PIS, MOV.BDALIQ_PIS_QUANT, MOV.BDQUANT_BC_COF, MOV.BDALIQ_COF_QUANT, MOV.BDCODEMPSCP, MOV.BDCODNAT, ';
      wSQL = wSQL||        'MOV.BDTIPOREDZ, OPF200.BDTIPOOPEREXP || '' - '' || OPF200.BDDESCRICAO BDDESCPEREXP, MOV.BDDESCNATREC, ';
      wSQL = wSQL||        'MOV.BDDATANOTA, MOV.BDNUMDOC, -1 BDCONDPGTO ';
      wSQL = wSQL||        'from ( ';

      wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, Cast((SubString(i.BDDATAPGTO FROM 1 for 4)||SubString(i.BDDATAPGTO FROM 6 for 2)) AS Integer) AS BDREFERENCIA, ';
      wSQL = wSQL||               'i.BDCHAVE, i.BDORDEMPGTO AS BDORDEM, NULL AS BDORDEMPRO, 14 AS BDCODTP, ';
      IF (wINCTRIB = 1) THEN
        BEGIN
          wSQL = wSQL||             'iif(((i.BDCODCSTPIS = 1) AND (CAST(i.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4)))), 4, null) AS BDCOD_CONT_PIS, ';
          wSQL = wSQL||             'iif(((i.BDCODCSTCOF = 1) AND (CAST(i.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4)))), 4, null) AS BDCOD_CONT_COF, ';
        END
      ELSE
      IF (wINCTRIB = 2) THEN
        BEGIN
          wSQL = wSQL||             'iif(((i.BDCODCSTPIS = 1) AND (CAST(i.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)))), 54, null) AS BDCOD_CONT_PIS, ';
          wSQL = wSQL||             'iif(((i.BDCODCSTCOF = 1) AND (CAST(i.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)))), 54, null) AS BDCOD_CONT_COF, ';
        END
      ELSE
      IF (wINCTRIB = 3) THEN
        BEGIN
          wSQL = wSQL||           'CASE i.BDCODCSTPIS ';
          wSQL = wSQL||             'WHEN 1 THEN CASE CAST(i.BDALIQPIS as NUMERIC(7,4)) ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4)) THEN 04 ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)) THEN 54 ';
          wSQL = wSQL||                           'ELSE null ';
          wSQL = wSQL||                         'END ';
          wSQL = wSQL||             'WHEN 5 THEN CASE CAST(i.BDALIQPIS as NUMERIC(7,4)) ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)) THEN 54 ';
          wSQL = wSQL||                           'ELSE 32 ';
          wSQL = wSQL||                         'END ';
          wSQL = wSQL||             'ELSE null ';
          wSQL = wSQL||           'END AS BDCOD_CONT_PIS, ';

          wSQL = wSQL||           'CASE i.BDCODCSTCOF ';
          wSQL = wSQL||             'WHEN 1 THEN CASE CAST(i.BDALIQCOFINS as NUMERIC(7,4)) ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4)) THEN 04 ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)) THEN 54 ';
          wSQL = wSQL||                           'ELSE null ';
          wSQL = wSQL||                         'END ';
          wSQL = wSQL||             'WHEN 5 THEN CASE CAST(i.BDALIQCOFINS as NUMERIC(7,4)) ';
          wSQL = wSQL||                           'WHEN CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)) THEN 54 ';
          wSQL = wSQL||                           'ELSE 32 ';
          wSQL = wSQL||                         'END ';
          wSQL = wSQL||             'ELSE null ';
          wSQL = wSQL||           'END AS BDCOD_CONT_COF, ';
        END
      wSQL = wSQL||               'i.BDVLRTOTRECPAR AS BDVL_ITEM,';
      wSQL = wSQL||               'i.BDCODCSTPIS, i.BDBASEPIS AS BDBCPIS, i.BDALIQPIS, i.BDVLRPIS,';
      wSQL = wSQL||               'i.BDCODCSTCOF, i.BDBASECOFINS AS BDBCCOFINS, i.BDALIQCOFINS, i.BDVLRCOFINS,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
      wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT, MOV.BDCODEMPSCP, null bdcodnat, null bdtiporedz, null BDDESCNATREC, I.BDDATAPGTO BDDATANOTA, mov.BDNRCONTRATO BDNUMDOC, MOV.BDTIPOOPERIMOB ';
      wSQL = wSQL||        'FROM (';
      wSQL = wSQL||               'SELECT f.BDCODEMP, f.BDCHAVE,F.BDCODEMPREENDIMENTO,F.BDCODIGOUNIIMOB, SCP.BDCODEMPSCP, F.BDTIPOOPERIMOB, F.BDNRCONTRATO ';
      wSQL = wSQL||               'FROM VEF_EMP_TMOVOPIMOBILIARIA_F200 f ';
      wSQL = wSQL||               'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = F.BDCODEMP AND SCP.BDCODSCP = F.BDCODSCP AND SCP.BDREFEMP = F.BDREFSOC) ';
      wSQL = wSQL||               'WHERE F.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               ') mov ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVOPIMOBI_F200_PGTO i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      /* RET 1800 - Se a Unidade Imobiliária do Lançamento for optante do RET, ela será considerada na apuração do 1800  */
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_BASE_TCADUNIDIMOBILIARIA UNI ON (UNI.BDCODEMP = MOV.BDCODEMP AND UNI.BDCODEMPREENDIMENTO = MOV.BDCODEMPREENDIMENTO AND UNI.BDCODIGOUNIIMOB = MOV.BDCODIGOUNIIMOB)';
      wSQL = wSQL||        'WHERE (i.BDDATAPGTO is not null) AND IIF(((UNI.BDOPTANTERET = ''TRUE'') and ((UNI.BDDATADORET <= '||:PRREFERENCIA||') or (UNI.BDDATADORET is null))), ''TRUE'', ''FALSE'') = ''FALSE'' ';
      wSQL = wSQL||          'AND (Cast((SubString(i.BDDATAPGTO FROM 1 for 4)||SubString(i.BDDATAPGTO FROM 6 for 2)) AS Integer) = '||:prREFERENCIA||') ';

      wSQL = wSQL||        ' ) MOV ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_BASE_TTABTIPOOPF200 OPF200 ON (OPF200.BDTIPOOPERIMOB = MOV.BDTIPOOPERIMOB) ';
      wSQL = wSQL||        'union all ';
                           /* I100 */
      wSQL = wSQL||        'SELECT i100.BDCODEMP, COALESCE(emp.BDCODMATRIZ, i100.BDCODEMP) as BDCODMATRIZ, i100.BDREFERENCIA, i100.BDCHAVE, NULL as BDORDEM,';
--      wSQL = wSQL||               'NULL as BDORDEMPRO, 9 as BDCODTP, NULL as BDCOD_CONT_PIS, NULL as BDCOD_CONT_COF, (i100.BDVLRREC-i100.BDVLRTOTDEDGER-i100.BDVLRTOTDEDESP) as BDVL_ITEM,';
      wSQL = wSQL||               'NULL as BDORDEMPRO, 9 as BDCODTP, 0 AS BDTIPOPROD, NULL as BDCOD_CONT_PIS, NULL as BDCOD_CONT_COF, i100.BDVLRREC as BDVL_ITEM,';
      wSQL = wSQL||               'i100.BDCODCSTPISCOF as BDCODCSTPIS, i100.BDBASEPIS as BDBCPIS, i100.BDALIQPIS, i100.BDVLRPIS,';
      wSQL = wSQL||               'i100.BDCODCSTPISCOF as BDCODCSTCOF, i100.BDBASECOFINS as BDBCCOFINS, i100.BDALIQCOFINS, i100.BDVLRCOFINS,';
      wSQL = wSQL||               'NULL as BDQUANT_BC_PIS, NULL as BDALIQ_PIS_QUANT, NULL as BDQUANT_BC_COF, NULL as BDALIQ_COF_QUANT, SCP.BDCODEMPSCP,null bdcodnat, null bdtiporedz, null BDDESCPEREXP, IIF(REC.BDNATREC is not null, REC.BDNATREC  || '' - '' || REC.BDDESCRICAO, ''Movimentação Financeira'') BDDESCNATREC, CAST(I100.BDREFERENCIA as VARCHAR(200)) as BDDATANOTA, null as BDNUMDOC, -1 BDCONDPGTO ';
      wSQL = wSQL||        'FROM VEF_EMP_TMOVFINI100 i100 ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = i100.BDCODEMP) ';
      wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = i100.BDCODEMP AND SCP.BDCODSCP = i100.BDCODSCP AND SCP.BDREFEMP = i100.BDREFSOC) ';
      wSQL = wSQL||        'LEFT OUTER JOIN VEF_BASE_TTAB_NATREC REC ON (I100.BDCODNATREC = REC.BDCODNATREC) ';
      wSQL = wSQL||        'WHERE i100.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||         ' AND i100.BDREFERENCIA = '||:prREFERENCIA||' ';
      EXECUTE STATEMENT ( wSQLPREFIXO || wSQL || wSQLSUFIXO );
    END
END
^

create or alter procedure SP_APURACAO_BLOCOM_M210_M610 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PREXECREL DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
declare variable WINCTRIB integer;
declare variable WCODCRIT integer;
declare variable WSQL varchar(32750);
declare variable WSQLPREFIXO varchar(8000);
declare variable WSQLSUFIXO varchar(100);
declare variable WMOD_TRANSPORTE varchar(50);
declare variable WMOD_PROD varchar(50);
declare variable WALIQ_PIS_IT_1 varchar(5);
declare variable WALIQ_COF_IT_1 varchar(5);
declare variable WALIQ_PIS_IT_2 varchar(5);
declare variable WALIQ_COF_IT_2 varchar(5);
BEGIN
wMOD_TRANSPORTE = '7,8,9,10,11,13,14,15,16,26,27,57,67,800,63'; -- Transporte
wMOD_PROD = wMOD_TRANSPORTE;--||','||wMOD_CFe;
wALIQ_PIS_IT_1 = '1.65';
wALIQ_COF_IT_1 = '7.60';
wALIQ_PIS_IT_2 = '0.65';
wALIQ_COF_IT_2 = '3.00';
EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);
SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
INTO :wINCTRIB, :wCODCRIT;

IF ((:PRCODEMPSO > 0) and ((wINCTRIB is null) or (wCODCRIT is null))) THEN
begin
SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMPSO
INTO :wINCTRIB, :wCODCRIT;
end

IF ((wINCTRIB IS NOT NULL) AND (wCODCRIT IS NOT NULL)) THEN
BEGIN
wSQLPREFIXO = 'INSERT INTO TMP_VEF_EMP_TBLOCOM_M210_M610 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDCODCSTPIS, BDCODCSTCOF, BDTIPOPROD, BDCOD_CONT_PIS, BDCOD_CONT_COF, BDVL_REC_BRT, BDVL_BC_CONT_PIS, BDVL_BC_CONT_COF, BDALIQ_PIS, BDALIQ_COF, BDQUANT_BC_PIS, BDQUANT_BC_COF, BDALIQ_QUANT_PIS, BDALIQ_QUANT_COF, BDCODEMPSCP, BDRECEITAFINANCEIRA, BDCODNAT, BDDESCTIPODOC,BDTIPOREDZ, BDDESCPEREXP,  BDDESCNATREC, BDDATANOTA, BDNUMDOC, BDVLRPIS, BDVLRCOFINS,BDCONDPGTO) ';
wSQLPREFIXO = wSQLPREFIXO|| 'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, aux.BDCODCSTPIS, aux.BDCODCSTCOF, aux.BDTIPOPROD, ';
IF (wINCTRIB = 1) THEN /* Incidência tributária 1 - Exclusivamente no regime não-cumulativo */
BEGIN
wSQLPREFIXO = wSQLPREFIXO|| 'COALESCE(aux.BDCOD_CONT_PIS,(CASE aux.BDCODCSTPIS ';
wSQLPREFIXO = wSQLPREFIXO||                                 'WHEN 1 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = Cast('||wALIQ_PIS_IT_1||' as NUMERIC(7,4))), 01, null) ';
wSQLPREFIXO = wSQLPREFIXO||                                 'WHEN 2 THEN 02 ';
wSQLPREFIXO = wSQLPREFIXO||                                 'WHEN 3 THEN 03 ';
wSQLPREFIXO = wSQLPREFIXO||                                 'WHEN 5 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = Cast('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))), 31, 32) ';
wSQLPREFIXO = wSQLPREFIXO||                              'ELSE null ';
wSQLPREFIXO = wSQLPREFIXO||                              'end)) AS BDCOD_CONT_PIS,';
wSQLPREFIXO = wSQLPREFIXO|| 'COALESCE(aux.BDCOD_CONT_COF,(CASE aux.BDCODCSTCOF ';
wSQLPREFIXO = wSQLPREFIXO||                                 'WHEN 1 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4))), 01, null) ';
wSQLPREFIXO = wSQLPREFIXO||                                 'WHEN 2 THEN 02 ';
wSQLPREFIXO = wSQLPREFIXO||                                 'WHEN 3 THEN 03 ';
wSQLPREFIXO = wSQLPREFIXO||                                 'WHEN 5 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = Cast('||wALIQ_COF_IT_2||' as NUMERIC(7,4))), 31, 32) ';
wSQLPREFIXO = wSQLPREFIXO||                              'ELSE null ';
wSQLPREFIXO = wSQLPREFIXO||                              'end)) AS BDCOD_CONT_COF,';
END
ELSE
IF (wINCTRIB = 2) THEN /* Incidência tributária 2 - Exclusivamente no regime cumulativo */
BEGIN
wSQLPREFIXO = wSQLPREFIXO|| 'COALESCE(aux.BDCOD_CONT_PIS,(CASE aux.BDCODCSTPIS ';
wSQLPREFIXO = wSQLPREFIXO||                                'WHEN 1 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))), 51, null) ';
wSQLPREFIXO = wSQLPREFIXO||                                'WHEN 2 THEN 52 ';
wSQLPREFIXO = wSQLPREFIXO||                                'WHEN 3 THEN 53 ';
wSQLPREFIXO = wSQLPREFIXO||                                'WHEN 5 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = Cast('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))), 31, 32) ';
wSQLPREFIXO = wSQLPREFIXO||                              'ELSE null ';
wSQLPREFIXO = wSQLPREFIXO||                              'end)) AS BDCOD_CONT_PIS,';
wSQLPREFIXO = wSQLPREFIXO|| 'COALESCE(aux.BDCOD_CONT_COF,(CASE aux.BDCODCSTCOF ';
wSQLPREFIXO = wSQLPREFIXO||                                'WHEN 1 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4))), 51, null) ';
wSQLPREFIXO = wSQLPREFIXO||                                'WHEN 2 THEN 52 ';
wSQLPREFIXO = wSQLPREFIXO||                                'WHEN 3 THEN 53 ';
wSQLPREFIXO = wSQLPREFIXO||                                'WHEN 5 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = Cast('||wALIQ_COF_IT_2||' as NUMERIC(7,4))), 31, 32) ';
wSQLPREFIXO = wSQLPREFIXO||                              'ELSE null ';
wSQLPREFIXO = wSQLPREFIXO||                              'end)) AS BDCOD_CONT_COF,';
END
ELSE
IF (wINCTRIB = 3) THEN /* Incidência tributária 3 - Regimes não-cumulativo e cumulativo */
BEGIN
wSQLPREFIXO = wSQLPREFIXO|| 'COALESCE(aux.BDCOD_CONT_PIS,(CASE aux.BDCODCSTPIS ';
wSQLPREFIXO = wSQLPREFIXO||                                 'WHEN 1 THEN ';
wSQLPREFIXO = wSQLPREFIXO||                                    'CASE CAST(aux.BDALIQPIS as NUMERIC(7,4)) ';
wSQLPREFIXO = wSQLPREFIXO||                                       'WHEN CAST('||wALIQ_PIS_IT_1||' as NUMERIC(7,4)) THEN 01 ';
wSQLPREFIXO = wSQLPREFIXO||                                       'WHEN CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4)) THEN 51 ';
wSQLPREFIXO = wSQLPREFIXO||                                    'END ';
wSQLPREFIXO = wSQLPREFIXO||                                 'WHEN 2 THEN 02 ';
wSQLPREFIXO = wSQLPREFIXO||                                 'WHEN 3 THEN 03 ';
wSQLPREFIXO = wSQLPREFIXO||                                 'WHEN 5 THEN iif((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST('||wALIQ_PIS_IT_2||' as NUMERIC(7,4))), 31, 32) ';
wSQLPREFIXO = wSQLPREFIXO||                              'ELSE null ';
wSQLPREFIXO = wSQLPREFIXO||                              'end)) AS BDCOD_CONT_PIS,';
wSQLPREFIXO = wSQLPREFIXO|| 'COALESCE(aux.BDCOD_CONT_COF,(CASE aux.BDCODCSTCOF ';
wSQLPREFIXO = wSQLPREFIXO||                                 'WHEN 1 THEN ';
wSQLPREFIXO = wSQLPREFIXO||                                    'CASE CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) ';
wSQLPREFIXO = wSQLPREFIXO||                                       'WHEN CAST('||wALIQ_COF_IT_1||' as NUMERIC(7,4)) THEN 01 ';
wSQLPREFIXO = wSQLPREFIXO||                                       'WHEN CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4)) THEN 51 ';
wSQLPREFIXO = wSQLPREFIXO||                                    'END ';
wSQLPREFIXO = wSQLPREFIXO||                                 'WHEN 2 THEN 02 ';
wSQLPREFIXO = wSQLPREFIXO||                                 'WHEN 3 THEN 03 ';
wSQLPREFIXO = wSQLPREFIXO||                                 'WHEN 5 THEN iif((CAST(aux.BDALIQCOFINS as NUMERIC(7,4)) = CAST('||wALIQ_COF_IT_2||' as NUMERIC(7,4))), 31, 32) ';
wSQLPREFIXO = wSQLPREFIXO||                              'ELSE null ';
wSQLPREFIXO = wSQLPREFIXO||                              'end)) AS BDCOD_CONT_COF,';
END
wSQLPREFIXO = wSQLPREFIXO|| 'aux.BDVL_ITEM AS BDVL_REC_BRT,';
/* Se tiver campo de valor da base de calculo por quandtidade e alíquota em R$, leva os mesmo, caso contrário, verifica pela CST, se for = 3, vai nas quantidades e alíquotas em R$... */
wSQLPREFIXO = wSQLPREFIXO|| 'iif(((aux.BDQUANT_BC_PIS is null) AND (AUX.BDCODCSTPIS = 3)), 0, AUX.BDBCPIS) AS BDVL_BC_CONT_PIS,';
wSQLPREFIXO = wSQLPREFIXO|| 'iif(((aux.BDQUANT_BC_COF is null) AND (AUX.BDCODCSTCOF = 3)), 0, AUX.BDBCCOFINS) AS BDVL_BC_CONT_COF,';
wSQLPREFIXO = wSQLPREFIXO|| 'iif(((aux.BDALIQ_PIS_QUANT is null) AND (aux.BDCODCSTPIS = 3)), 0, aux.BDALIQPIS) AS BDALIQ_PIS,';
wSQLPREFIXO = wSQLPREFIXO|| 'iif(((aux.BDALIQ_COF_QUANT is null) AND (aux.BDCODCSTPIS = 3)), 0, aux.BDALIQCOFINS) AS BDALIQ_COF,';
wSQLPREFIXO = wSQLPREFIXO|| 'COALESCE(aux.BDQUANT_BC_PIS, iif(aux.BDCODCSTPIS = 3, aux.BDBCPIS, 0)) AS BDQUANT_BC_PIS,';
wSQLPREFIXO = wSQLPREFIXO|| 'COALESCE(aux.BDQUANT_BC_COF, iif(AUX.BDCODCSTCOF = 3, AUX.BDBCCOFINS, 0)) AS BDQUANT_BC_COF,';
wSQLPREFIXO = wSQLPREFIXO|| 'COALESCE(aux.BDALIQ_PIS_QUANT, iif(AUX.BDCODCSTPIS = 3, AUX.BDALIQPIS, 0)) AS BDALIQ_QUANT_PIS,';
wSQLPREFIXO = wSQLPREFIXO|| 'COALESCE(aux.BDALIQ_COF_QUANT, iif(AUX.BDCODCSTPIS = 3, AUX.BDALIQCOFINS, 0)) AS BDALIQ_QUANT_COF, ';
wSQLPREFIXO = wSQLPREFIXO|| IIF(:PRAJUSTESCP = 'TRUE',' COALESCE(aux.BDCODEMPSCP,0) ',' 0')||' BDCODEMPSCP, AUX.BDRECEITAFINANCEIRA, BDCODNAT, BDDESCTIPODOC, NULL BDTIPOREDZ, NULL BDDESCPEREXP,  NULL BDDESCNATREC, BDDATANOTA, BDNUMDOC, BDVLRPIS, BDVLRCOFINS,BDCONDPGTO ';  /*Camilla M. SCP*/
wSQLPREFIXO = wSQLPREFIXO|| 'FROM ( ';
wSQLSUFIXO = ') aux ';
if ((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0)) then
WSQLSUFIXO = WSQLSUFIXO||' where (coalesce(AUX.BDCODEMPSCP, 0) = '|| :PRCODEMP || ') ';
else
if (:PRAJUSTESCP = 'TRUE') then
WSQLSUFIXO = WSQLSUFIXO||' where (coalesce(AUX.BDCODEMPSCP, 0) = 0) ';
IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
begin /* Saídas - Produtos */
wSQL = 'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, movpro.BDCHAVE, movpro.BDORDEM, movpro.BDORDEMPRO, 2 AS BDCODTP, COALESCE(vinc.BDTIPOPROD,0) BDTIPOPROD, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
wSQL = wSQL|| 'SUM(CAST(CAST(COALESCE(MOVPRO.BDVLRITEM,0)AS NUMERIC(15,4))*(CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,6))/ IVLR.BDVLRCONTABTOTAL)AS DM_NUMERIC_15_2)) BDVL_ITEM,';
wSQL = wSQL|| 'movpro.BDCODCSTPIS, ';
wSQL = wSQL|| 'SUM(CAST(CAST(COALESCE(MOVPRO.BDBCPIS,0)AS NUMERIC(15,4))*(CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,6))/IIF(IVLR.BDVLRCONTABTOTAL = 0,1,IVLR.BDVLRCONTABTOTAL))AS DM_NUMERIC_15_2)) BDBCPIS,';
wSQL = wSQL|| 'movpro.BDALIQPIS, ';
wSQL = wSQL|| 'SUM(CAST(CAST(COALESCE(MOVPRO.BDVLRPIS,0)AS NUMERIC(15,4))*(CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,6))/IIF(IVLR.BDVLRCONTABTOTAL = 0,1,IVLR.BDVLRCONTABTOTAL))AS DM_NUMERIC_15_2)) BDVLRPIS,';
wSQL = wSQL|| 'movpro.BDCODCSTCOF, ';
wSQL = wSQL|| 'SUM(CAST(CAST(COALESCE(MOVPRO.BDBCCOFINS,0)AS NUMERIC(15,4))*(CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,6))/IIF(IVLR.BDVLRCONTABTOTAL = 0,1,IVLR.BDVLRCONTABTOTAL))AS DM_NUMERIC_15_2)) BDBCCOFINS,';
wSQL = wSQL|| 'movpro.BDALIQCOFINS, ';
wSQL = wSQL|| 'SUM(CAST(CAST(COALESCE(MOVPRO.BDVLRCOFINS,0)AS NUMERIC(15,4))*(CAST(MOV.BDVALORPGTOPAR AS NUMERIC(15,6))/IIF(IVLR.BDVLRCONTABTOTAL = 0,1,IVLR.BDVLRCONTABTOTAL))AS DM_NUMERIC_15_2)) BDVLRCOFINS,';
wSQL = wSQL|| 'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT, ';
WSQL = WSQL|| 'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT,SCP.BDCODEMPSCP, ''FALSE'' BDRECEITAFINANCEIRA, I.BDCODNAT, null BDDESCTIPODOC, BDDATAEMISSAO as BDDATANOTA, MOV.BDNUMDOCINI as BDNUMDOC, MOV.BDCONDPGTO ';
wSQL = wSQL|| 'FROM (SELECT aux.BDCODEMP, aux.BDCHAVE, aux.BDREFLAN, SUM(AUX.BDVALORPGTOPAR) BDVALORPGTOPAR, S.BDVALORNOTA, S.BDDATAEMISSAO, S.BDNUMDOCINI, S.BDCONDPGTO ';
wSQL = wSQL||       'FROM (SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, ';
wSQL = wSQL||                     'CAST(SUM(COALESCE(CAST(PAR.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + ';
wSQL = wSQL||                          'SUM(COALESCE(PAR.BDVALORRETPIS, 0)) + ';
wSQL = wSQL||                          'SUM(COALESCE(PAR.BDVALORRETCOFINS, 0)) + ';
wSQL = wSQL||                          'SUM(COALESCE(PAR.BDVALORRETCSLL, 0)) + ';
wSQL = wSQL||                          'SUM(COALESCE(PAR.BDVALORRETIRRF, 0)) + ';
wSQL = wSQL||                          'SUM(COALESCE(PAR.BDVALORRETISSQN, 0)) + ';
wSQL = wSQL||                          'SUM(COALESCE(PAR.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR ';
wSQL = wSQL||             'FROM VEF_EMP_TMOVSAI s ';
wSQL = wSQL||             'JOIN VEF_EMP_TMOVSAIPARPGTO par ON (par.bdCODEMP = s.bdCODEMP AND par.bdCHAVE = s.bdCHAVE AND ';
wSQL = wSQL||                                                 '(CAST((SELECT BDDATA FROM SP_PARSE_DATE(PAR.BDDATAPGTOPAR, ''YYYYMM'')) AS INTEGER) = '||:PRREFERENCIA||') AND ';
wSQL = wSQL||                                                 'par.bdCODTIPOBAIXA = 1) '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
wSQL = wSQL||             'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
wSQL = wSQL||               'AND (s.'||TRIM(:prWHEREEMPRESAS)||') ';
wSQL = wSQL||               'AND (s.BDMODELO not in ('||wMOD_PROD||')) '; -- Modelos que não são produtos...
wSQL = wSQL||               'AND exists(select * ';
wSQL = wSQL||                          'from VEF_EMP_TMOVSAIITENS SI ';
wSQL = wSQL||                          'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
wSQL = wSQL||                          'where SI.BDCODEMP = S.BDCODEMP and ';
wSQL = wSQL||                                'SI.BDCHAVE = S.BDCHAVE) ';
wSQL = wSQL||             'GROUP BY s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
wSQL = wSQL||            ') aux ';
wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = AUX.BDCODEMP AND S.BDCHAVE = AUX.BDCHAVE) ';
wSQL = wSQL||       'WHERE AUX.BDVALORPGTOPAR > 0 ';
IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
wSQL = wSQL||         'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p WHERE p.BDCODEMP = aux.BDCODEMP AND p.BDREFEMP <= aux.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
wSQL = wSQL||       'GROUP BY aux.BDCODEMP, aux.BDCHAVE, aux.BDREFLAN, S.BDVALORNOTA, S.bddataemissao, S.BDNUMDOCINI,S.BDCONDPGTO ';
wSQL = wSQL||       ') mov ';
wSQL = wSQL|| 'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
wSQL = wSQL|| 'JOIN VEF_EMP_TMOVSAIITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
wSQL = wSQL|| 'left outer join TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = I.BDCODEMP AND SCP.BDCODSCP = I.BDCODSCP AND SCP.BDREFEMP = I.BDREFSOC) ';
wSQL = wSQL|| 'LEFT OUTER JOIN (SELECT i.bdCODEMP, i.bdCHAVE, SUM(i.bdVLRCONTAB) AS bdVLRCONTABTOTAL '; -- Alt.: #135727 - Deve considerar apenas o valor contábil que gera as parcelas, caso contrario o valor das parcelas eh menor que o total da nota(sustitui o bdVALORNOTA)...
wSQL = wSQL||                  'FROM VEF_EMP_TMOVSAIITENS i ';
wSQL = wSQL||                  'LEFT OUTER JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT) ';
wSQL = wSQL||                  'WHERE nat.bdLANCPARCELAMENTO = ''TRUE'' ';
wSQL = wSQL||                  'GROUP BY i.bdCODEMP, i.bdCHAVE) iVlr on (iVlr.bdCODEMP = mov.bdCODEMP AND iVlr.bdCHAVE = mov.bdCHAVE) ';
wSQL = wSQL|| 'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, p.BDCODCSTCOF, p.BDCODCSTPIS, p.BDCODCTA, p.BDALIQPIS, p.BDALIQCOFINS,p.BDVLRITEM, ';
wSQL = wSQL||              'p.BDBCPIS, p.BDBCCOFINS, p.BDVLRPIS, p.BDVLRCOFINS, p.bdCODPROD ';
wSQL = wSQL||       'FROM VEF_EMP_TMOVPROSAI p ';
wSQL = wSQL||       'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
wSQL = wSQL||       ') movpro on (i.BDCODEMP = movpro.BDCODEMP AND i.BDCHAVE = movpro.BDCHAVE AND i.BDORDEM = movpro.BDORDEM) ';
wSQL = wSQL|| 'LEFT OUTER JOIN TCADPRO_VINC vinc ON(vinc.bdCODEMP = movpro.bdCODEMP AND vinc.bdCODPROD = movpro.bdCODPROD) ';
wSQL = wSQL|| 'GROUP BY mov.bdCODEMP,EMP.BDCODMATRIZ,MOVPRO.BDCHAVE,MOVPRO.BDORDEM,MOVPRO.BDORDEMPRO,MOVPRO.BDCODCSTPIS,MOV.BDVALORPGTOPAR,MOVPRO.BDBCPIS,vinc.BDTIPOPROD,';
wSQL = wSQL|| 'ivlr.bdVLRCONTABTOTAL,movpro.bdALIQPIS,movpro.bdVLRPIS,movpro.bdCODCSTCOF,movpro.bdBCCOFINS,movpro.bdALIQCOFINS,movpro.bdVLRCOFINS,scp.bdCODEMPSCP, BDCODNAT, BDDATANOTA, BDNUMDOC,MOV.BDCONDPGTO ';

wSQL = wSQL||        'union all ';
/* Saídas - Transporte (D100) */
wSQL = wSQL||        'SELECT mov.BDCODEMP, mov.BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, mov.BDCHAVE, mov.BDORDEM, mov.BDORDEMPRO, mov.BDCODTP, 0 AS BDTIPOPROD, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
wSQL = wSQL||                'SUM((COALESCE(PGTO.BDVALORPGTOPAR,0)*(CAST((CAST(COALESCE(I.BDVLRCONTAB,0)AS NUMERIC(15,4))/IIF(IVLR.BDVLRCONTABTOTAL = 0,1,COALESCE(IVLR.BDVLRCONTABTOTAL, 1))) AS DM_NUMERIC_15_2)))) AS BDVL_ITEM,';
wSQL = wSQL||                'mov.BDCODCSTPIS,';
wSQL = wSQL||                'SUM(CAST((PGTO.BDVALORPGTOPAR * CAST(COALESCE(((MOV.BDBCPIS * COALESCE(I.BDVLRCONTAB, 0)) / IIF(IVLR.BDVLRCONTABTOTAL = 0, 1, IVLR.BDVLRCONTABTOTAL)), 0) AS DM_NUMERIC_15_2)) / IIF(IVLR.BDVLRCONTABTOTAL = 0, 1, IVLR.BDVLRCONTABTOTAL) AS DM_NUMERIC_15_2)) AS BDBCPIS, ';
wSQL = wSQL||                'mov.BDALIQPIS,';
wSQL = wSQL||                'SUM(CAST((PGTO.BDVALORPGTOPAR * CAST(COALESCE(((cast(MOV.BDVLRPIS as DM_NUMERIC_15_2) * COALESCE(I.BDVLRCONTAB, 0)) / IIF(IVLR.BDVLRCONTABTOTAL = 0, 1, IVLR.BDVLRCONTABTOTAL)), 0) AS DM_NUMERIC_15_2)) / IIF(IVLR.BDVLRCONTABTOTAL = 0, 1, IVLR.BDVLRCONTABTOTAL) AS DM_NUMERIC_15_2)) AS BDVLRPIS, ';
wSQL = wSQL||                'mov.BDCODCSTCOF,';
wSQL = wSQL||                'SUM(CAST((PGTO.BDVALORPGTOPAR * CAST(COALESCE(((MOV.BDBCCOFINS * COALESCE(I.BDVLRCONTAB, 0)) / IIF(IVLR.BDVLRCONTABTOTAL = 0, 1, IVLR.BDVLRCONTABTOTAL)), 0) AS DM_NUMERIC_15_2)) / IIF(IVLR.BDVLRCONTABTOTAL = 0, 1, IVLR.BDVLRCONTABTOTAL) AS DM_NUMERIC_15_2)) AS BDBCCOFINS, ';
wSQL = wSQL||                'mov.BDALIQCOFINS,';
wSQL = wSQL||                'SUM(CAST((PGTO.BDVALORPGTOPAR * CAST(COALESCE(((CAST(MOV.BDVLRCOFINS AS NUMERIC(15,2)) * COALESCE(I.BDVLRCONTAB, 0)) / IIF(IVLR.BDVLRCONTABTOTAL = 0, 1, IVLR.BDVLRCONTABTOTAL)), 0) AS DM_NUMERIC_15_2)) / IIF(IVLR.BDVLRCONTABTOTAL = 0, 1, IVLR.BDVLRCONTABTOTAL) AS DM_NUMERIC_15_2)) AS BDVLRCOFINS, ';
wSQL = wSQL||                'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
wSQL = wSQL||   'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT, MOV.BDCODEMPSCP, ''FALSE'' BDRECEITAFINANCEIRA, MOV.BDCODNAT, NULL BDDESCTIPODOC, BDDATAEMISSAO AS BDDATANOTA, BDNUMDOCINI as BDNUMDOC,MOV.BDCONDPGTO ';
/* Saídas - Transporte (D100) */
wSQL = wSQL||        'FROM (SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 16 AS BDCODTP,';
wSQL = wSQL||                      'SUM(I.BDVLRCONTAB) AS BDVL_ITEM,d100.BDCODCSTPIS, SUM(((D100.BDVL_BC_PIS*I.BDVLRCONTAB )/IIF(BDVALORNOTA = 0,1,BDVALORNOTA))) AS BDBCPIS, d100.BDALIQ_PIS AS BDALIQPIS, SUM(((D100.BDVLRPIS*I.BDVLRCONTAB )/IIF(BDVALORNOTA = 0,1,BDVALORNOTA))) BDVLRPIS,';
wSQL = wSQL||                      'd100.BDCODCSTCOF, SUM(((D100.BDVL_BC_COF*I.BDVLRCONTAB )/IIF(BDVALORNOTA = 0,1,BDVALORNOTA))) AS BDBCCOFINS, d100.BDALIQ_COF AS BDALIQCOFINS, SUM(((D100.BDVLRCOFINS*I.BDVLRCONTAB )/IIF(BDVALORNOTA = 0,1,BDVALORNOTA))) BDVLRCOFINS, SCP.BDCODEMPSCP, I.BDCODNAT, MOV.BDDATAEMISSAO AS BDDATANOTA, MOV.BDNUMDOCINI as BDNUMDOC, MOV.BDCONDPGTO ';
wSQL = wSQL||               'FROM (SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDVALORNOTA, S.BDDATAEMISSAO, S.BDNUMDOCINI,S.BDCONDPGTO ';
wSQL = wSQL||                      'FROM VEF_EMP_TMOVSAI s ';
wSQL = wSQL||                      'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
wSQL = wSQL||                        'AND (s.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Transporte
wSQL = wSQL||                        'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
wSQL = wSQL||                        'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p WHERE p.BDCODEMP = s.BDCODEMP AND p.BDREFEMP <= s.BDREFLAN ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
wSQL = wSQL||                        'AND exists(select * ';
wSQL = wSQL||                                   'from VEF_EMP_TMOVSAIITENS SI ';
wSQL = wSQL||                                   'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
wSQL = wSQL||                                   'where SI.BDCODEMP = S.BDCODEMP and ';
wSQL = wSQL||                                   'SI.BDCHAVE = S.BDCHAVE)';
wSQL = wSQL||                      ') mov ';
wSQL = wSQL||               'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
wSQL = wSQL||               'left outer join VEF_EMP_TMOVSAIITENS I on (I.BDCODEMP = MOV.BDCODEMP and I.BDCHAVE = MOV.BDCHAVE) ';
wSQL = wSQL||               'left outer join TEMPRESAS_SCP SCP on (SCP.BDCODEMP = I.BDCODEMP and SCP.BDCODSCP = I.BDCODSCP and SCP.BDREFEMP = I.BDREFSOC) ';
wSQL = wSQL||               'LEFT OUTER JOIN VEF_EMP_TD100SAI d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
wSQL = wSQL||               'WHERE d100.BDCHAVE is not null ';
wSQL = wSQL||  'GROUP BY MOV.BDCODEMP, BDCODMATRIZ, MOV.BDREFLAN, MOV.BDCHAVE,BDORDEM, BDORDEMPRO, BDCODTP, BDCODCSTPIS, BDALIQPIS,D100.BDCODCSTCOF,BDALIQCOFINS,SCP.BDCODEMPSCP, I.BDCODNAT, BDDATANOTA, BDNUMDOC, MOV.BDCONDPGTO  ';
wSQL = wSQL||               'union all ';
wSQL = wSQL||               'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 18 AS BDCODTP, ';
wSQL = wSQL||                      'SUM(I.BDVLRCONTAB) AS BDVL_ITEM,d400.BDCODCSTPIS, SUM(IIF(BDVALORNOTA > 0,((D400.BDVL_BC_PIS*I.BDVLRCONTAB )/IIF(BDVALORNOTA = 0,1,BDVALORNOTA)),D400.BDVL_BC_PIS)) AS BDBCPIS, d400.BDALIQ_PIS AS BDALIQPIS, SUM(IIF(BDVALORNOTA > 0,((D400.BDVL_PIS*I.BDVLRCONTAB )/IIF(BDVALORNOTA = 0,1,BDVALORNOTA)),D400.BDVL_PIS)) bdVL_PIS, ';
wSQL = wSQL||                      'd400.BDCODCSTCOF, SUM(IIF(BDVALORNOTA > 0,((D400.BDVL_BC_COF*I.BDVLRCONTAB )/IIF(BDVALORNOTA = 0,1,BDVALORNOTA)),D400.BDVL_BC_COF)) AS BDBCCOFINS, d400.BDALIQ_COF AS BDALIQCOFINS, SUM(IIF(BDVALORNOTA > 0,((D400.BDVL_COF*I.BDVLRCONTAB )/IIF(BDVALORNOTA = 0,1,BDVALORNOTA)),D400.BDVL_COF)) BDVL_COF, SCP.BDCODEMPSCP, I.BDCODNAT, MOV.BDDATAEMISSAO BDDATANOTA, mov.bdnumdocini BDNUMDOC, MOV.BDCONDPGTO ';
wSQL = wSQL||               'FROM (SELECT S.BDCODEMP, S.BDCHAVE, S.BDREFLAN, S.BDVALORNOTA, S.BDDATAEMISSAO, S.BDNUMDOCINI,S.BDCONDPGTO ';
wSQL = wSQL||                      'FROM VEF_EMP_TMOVSAI s ';
wSQL = wSQL||                      'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';  -- Notas canceladas...
wSQL = wSQL||                        'AND (s.BDMODELO in ('||wMOD_TRANSPORTE||')) ';  -- Transporte
wSQL = wSQL||                        'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
wSQL = wSQL||                        'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p WHERE p.BDCODEMP = s.BDCODEMP AND p.BDREFEMP <= s.BDREFLAN ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
wSQL = wSQL||                        'AND exists(select * ';
wSQL = wSQL||                                   'from VEF_EMP_TMOVSAIITENS SI ';
wSQL = wSQL||                                   'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
wSQL = wSQL||                                   'where SI.BDCODEMP = S.BDCODEMP and ';
wSQL = wSQL||                                   'SI.BDCHAVE = S.BDCHAVE) ';
wSQL = wSQL||                      ') mov ';
wSQL = wSQL||               'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
wSQL = wSQL||               'left outer join VEF_EMP_TMOVSAIITENS I on (I.BDCODEMP = MOV.BDCODEMP and I.BDCHAVE = MOV.BDCHAVE) ';
wSQL = wSQL||               'left outer join TEMPRESAS_SCP SCP on (SCP.BDCODEMP = I.BDCODEMP and SCP.BDCODSCP = I.BDCODSCP and SCP.BDREFEMP = I.BDREFSOC) ';
wSQL = wSQL||               'LEFT OUTER JOIN VEF_EMP_TD400SAI d400 on (d400.BDCODEMP = mov.BDCODEMP AND d400.BDCHAVE = mov.BDCHAVE) ';
wSQL = wSQL||               'WHERE d400.BDCHAVE is not null ';
WSQL = WSQL||  'GROUP BY MOV.BDCODEMP, BDCODMATRIZ, MOV.BDREFLAN, MOV.BDCHAVE,BDORDEM, BDORDEMPRO, BDCODTP, D400.BDCODCSTPIS, BDALIQPIS,D400.BDCODCSTCOF,BDALIQCOFINS,SCP.BDCODEMPSCP, I.BDCODNAT, BDDATANOTA, BDNUMDOC, MOV.BDCONDPGTO ';
wSQL = wSQL||               'union all ';
/* Saídas - F500 */
wSQL = wSQL||               'SELECT mov.bdCODEMP, COALESCE(emp.bdCODMATRIZ, mov.bdCODEMP) AS bdCODMATRIZ, mov.bdREFLAN, mov.bdCHAVE, NULL AS bdORDEM, NULL AS bdORDEMPRO, 17 AS bdCODTP, ';
wSQL = wSQL||                      'SUM(I.BDVLRCONTAB) bdVL_ITEM,f500.bdCODCSTPIS, SUM(IIF(BDVALORNOTA > 0,((F500.BDBASEPIS*I.BDVLRCONTAB )/IIF(BDVALORNOTA = 0,1,BDVALORNOTA)),F500.BDBASEPIS)) BDBCPIS, f500.bdALIQPIS AS bdALIQPIS, SUM(IIF(BDVALORNOTA > 0,((F500.BDVLRPIS*I.BDVLRCONTAB )/IIF(BDVALORNOTA = 0,1,BDVALORNOTA)),F500.BDVLRPIS)) bdVLRPIS, ';
wSQL = wSQL||               'f500.bdCODCSTCOF, SUM(IIF(BDVALORNOTA > 0,((F500.BDBASECOF*I.BDVLRCONTAB )/IIF(BDVALORNOTA = 0,1,BDVALORNOTA)),F500.BDBASECOF)) bdBCCOFINS, f500.bdALIQCOF AS bdALIQCOFINS, SUM(IIF(BDVALORNOTA > 0,((F500.BDVLRCOF*I.BDVLRCONTAB )/IIF(BDVALORNOTA = 0,1,BDVALORNOTA)),F500.BDVLRCOF)) bdVLRCOFINS, SCP.BDCODEMPSCP, I.BDCODNAT, MOV.BDDATAEMISSAO BDDATANOTA, MOV.BDNUMDOCINI BDNUMDOC, MOV.BDCONDPGTO ';
wSQL = wSQL||               'FROM (SELECT s.bdCODEMP, s.bdCHAVE, s.bdREFLAN, s.bdVALORNOTA, S.BDDATAEMISSAO, S.BDNUMDOCINI, S.BDCONDPGTO ';
wSQL = wSQL||                     'FROM VEF_EMP_TMOVSAI s ';
wSQL = wSQL||                     'WHERE (s.bdCODSITNF NOT IN (2,3,4,5)) ';  -- NOTAS CANCELADAS...
wSQL = wSQL||                       'AND s.'||TRIM(:PRWHEREEMPRESAS)||' ';
IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
wSQL = wSQL||                       'AND ((SELECT FIRST 1 bdTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p WHERE p.bdCODEMP = s.bdCODEMP AND p.bdREFEMP <= s.bdREFLAN ORDER BY bdCODEMP DESC, bdREFEMP DESC) = 1) ';
wSQL = wSQL||                       'AND EXISTS(SELECT * ';
wSQL = wSQL||                                  'FROM VEF_EMP_TMOVSAIITENS si ';
wSQL = wSQL||                                  'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = si.bdCODNAT AND ((nat.bdNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.bdNAOEXPEFDCONT)) = TRIM(''FALSE'')))) ';
wSQL = wSQL||                                  'WHERE si.bdCODEMP = s.bdCODEMP ';
wSQL = wSQL||                                    'AND si.bdCHAVE = s.bdCHAVE) ';
wSQL = wSQL||                      'AND (NOT EXISTS(SELECT * FROM VEF_EMP_TMOVSAI x ';
wSQL = wSQL||                                      'JOIN VEF_EMP_TMOVPROSAI xp ON (xp.bdCODEMP = x.bdCODEMP AND xp.bdCHAVE = x.bdCHAVE) ';
wSQL = wSQL||                                      'WHERE x.bdMODELO NOT IN ('||wMOD_PROD||') AND x.bdCODEMP = s.bdCODEMP AND x.bdCHAVE = s.bdCHAVE)) ';
wSQL = wSQL||                      'AND (NOT EXISTS(SELECT * FROM VEF_EMP_TMOVSAI x ';
wSQL = wSQL||                                      'JOIN VEF_EMP_TD100SAI xp ON (xp.bdCODEMP = x.bdCODEMP AND xp.bdCHAVE = x.bdCHAVE) ';
wSQL = wSQL||                                      'WHERE x.bdMODELO NOT IN ('||wMOD_TRANSPORTE||') AND x.bdCODEMP = s.bdCODEMP AND x.bdCHAVE = s.bdCHAVE)) ';
wSQL = wSQL||                      ') mov ';
wSQL = wSQL||               'LEFT OUTER JOIN TEMPRESAS emp ON (emp.bdCODEMP = mov.bdCODEMP) ';
wSQL = wSQL||               'left outer join VEF_EMP_TMOVSAIITENS I on (I.BDCODEMP = MOV.BDCODEMP and I.BDCHAVE = MOV.BDCHAVE) ';
wSQL = wSQL||               'left outer join TEMPRESAS_SCP SCP on (SCP.BDCODEMP = I.BDCODEMP and SCP.BDCODSCP = I.BDCODSCP and SCP.BDREFEMP = I.BDREFSOC) ';
wSQL = wSQL||               'LEFT OUTER JOIN VEF_EMP_TF500SAI f500 ON (f500.bdCODEMP = mov.bdCODEMP AND f500.bdCHAVE = mov.bdCHAVE) ';
wSQL = wSQL||               'WHERE F500.BDCHAVE IS NOT NULL ';
wSQL = wSQL||  'GROUP BY MOV.BDCODEMP, BDCODMATRIZ, MOV.BDREFLAN, MOV.BDCHAVE,BDORDEM, BDORDEMPRO, BDCODTP, F500.BDCODCSTPIS, BDALIQPIS,F500.BDCODCSTCOF,BDALIQCOFINS,SCP.BDCODEMPSCP, I.BDCODNAT, BDDATANOTA, BDNUMDOC, MOV.BDCONDPGTO ';
wSQL = wSQL||             ') mov ';
wSQL = wSQL||        'JOIN (SELECT COALESCE(SCP.BDCODEMPSCP,P.BDCODEMP) BDCODEMP, P.BDCHAVE,SCP.BDCODEMPSCP,P.BDCODNAT, ';
wSQL = wSQL||                     'CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETPIS, 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETCOFINS, 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETCSLL, 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETIRRF, 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETISSQN, 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR ';
wSQL = wSQL||              'FROM VEF_EMP_TMOVSAIPARPGTO P ';
wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = P.BDCODEMP AND I.BDCHAVE = P.BDCHAVE AND I.BDCODNAT = P.BDCODNAT) ';
wSQL = wSQL||              'left outer join TEMPRESAS_SCP SCP on (SCP.BDCODEMP = I.BDCODEMP and SCP.BDCODSCP = I.BDCODSCP and SCP.BDREFEMP = I.BDREFSOC) ';
wSQL = wSQL||              'WHERE P.'||TRIM(:PRWHEREEMPRESAS)||' ';
wSQL = wSQL||                'AND (CAST(SUBSTRING(P.BDDATAPGTOPAR FROM 1 FOR 4) || SUBSTRING(P.BDDATAPGTOPAR FROM 6 FOR 2) AS INTEGER) = '||:PRREFERENCIA||') ';
wSQL = wSQL||                'AND p.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
wSQL = wSQL||              'GROUP BY P.BDCODEMP, P.BDCHAVE, SCP.BDCODEMPSCP,P.BDCODNAT ';
wSQL = wSQL||             ') PGTO ON (PGTO.BDCODEMP = COALESCE(MOV.BDCODEMPSCP,MOV.BDCODEMP)  AND PGTO.BDCHAVE = MOV.BDCHAVE AND PGTO.BDCODNAT = MOV.BDCODNAT) ';
wSQL = wSQL||        'JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = MOV.BDCODEMP AND S.BDCHAVE = MOV.BDCHAVE) ';
wSQL = wSQL||        'JOIN VEF_EMP_TMOVSAIITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE AND I.BDCODNAT = MOV.BDCODNAT) ';
wSQL = wSQL||        'LEFT OUTER JOIN (SELECT i.bdCODEMP, i.bdCHAVE,I.BDCODNAT, SUM(i.bdVLRCONTAB) AS bdVLRCONTABTOTAL '; -- Alt.: #135727 - Deve considerar apenas o valor contábil que gera as parcelas, caso contrario o valor das parcelas eh menor que o total da nota(sustitui o bdVALORNOTA)...
wSQL = wSQL||                         'FROM VEF_EMP_TMOVSAIITENS i ';
wSQL = wSQL||                         'LEFT OUTER JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT) ';
wSQL = wSQL||                         'WHERE nat.bdLANCPARCELAMENTO = ''TRUE'' ';
wSQL = wSQL||                         'GROUP BY i.bdCODEMP, i.bdCHAVE,I.BDCODNAT) iVlr on (iVlr.bdCODEMP = mov.bdCODEMP AND iVlr.bdCHAVE = mov.bdCHAVE AND IVLR.BDCODNAT = MOV.BDCODNAT) ';
wSQL = wSQL||        'GROUP BY mov.bdCODEMP,mov.bdCODMATRIZ,mov.bdCHAVE,mov.bdORDEM,mov.bdORDEMPRO,mov.bdCODTP,mov.bdCODCSTPIS,mov.bdALIQPIS,mov.bdCODCSTCOF,mov.bdALIQCOFINS,mov.bdCODEMPSCP, MOV.BDCODNAT, BDDATANOTA, BDNUMDOC, MOV.BDCONDPGTO ';
wSQL = wSQL||        'union all ';
wSQL = wSQL||        'SELECT mov.BDCODEMP, mov.BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, a170.BDCHAVE, a170.BDORDEM, a170.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, COALESCE(vinc.bdTIPOPROD,0) bdTIPOPROD, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
wSQL = wSQL||              'SUM(CAST((CAST(PGTO.BDVALORPGTOPAR AS NUMERIC(15,4))/CAST(IVLR.BDVLRCONTABTOTAL AS NUMERIC(15,6)))*COALESCE(A170.BDVL_ITEM,0) AS DM_NUMERIC_15_2)) BDVL_ITEM,';
wSQL = wSQL||              'a170.BDCODCSTPIS,';
wSQL = wSQL||              'SUM(CAST(CAST(COALESCE(A170.BDVL_BC_PIS,0)AS NUMERIC(15,4))*(CAST(PGTO.BDVALORPGTOPAR AS NUMERIC(15,6))/IIF(IVLR.BDVLRCONTABTOTAL = 0,1,IVLR.BDVLRCONTABTOTAL))AS DM_NUMERIC_15_2)) BDBCPIS,';
wSQL = wSQL||              'a170.BDALIQ_PIS AS BDALIQPIS,';
wSQL = wSQL||              'SUM(CAST(CAST(COALESCE(A170.BDVL_PIS,0)AS NUMERIC(15,4))*(CAST(PGTO.BDVALORPGTOPAR AS NUMERIC(15,6))/IIF(IVLR.BDVLRCONTABTOTAL = 0,1,IVLR.BDVLRCONTABTOTAL))AS DM_NUMERIC_15_2)) BDVLRPIS,';
wSQL = wSQL||              'a170.BDCODCSTCOF,';
wSQL = wSQL||              'SUM(CAST(CAST(COALESCE(A170.BDVL_BC_COFINS,0)AS NUMERIC(15,4))*(CAST(PGTO.BDVALORPGTOPAR AS NUMERIC(15,6))/IIF(IVLR.BDVLRCONTABTOTAL = 0,1,IVLR.BDVLRCONTABTOTAL))AS DM_NUMERIC_15_2)) BDBCCOFINS,';
wSQL = wSQL||              'a170.BDALIQ_COFINS AS BDALIQCOFINS,';
wSQL = wSQL||              'SUM(CAST(CAST(COALESCE(A170.BDVL_COFINS,0)AS NUMERIC(15,4))*(CAST(PGTO.BDVALORPGTOPAR AS NUMERIC(15,6))/IIF(IVLR.BDVLRCONTABTOTAL = 0,1,IVLR.BDVLRCONTABTOTAL))AS DM_NUMERIC_15_2)) BDVLRCOFINS,';
wSQL = wSQL||              'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
wSQL = wSQL|| 'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT, SCP.BDCODEMPSCP, ''FALSE'' BDRECEITAFINANCEIRA, BDCODNAT, NULL BDDESCTIPODOC, MOV.BDDATAEMISSAO AS BDDATANOTA, MOV.BDNUMDOCINI  BDNUMDOC, MOV.BDCONDPGTO ';
wSQL = wSQL||        'FROM (SELECT s.BDCODEMP, COALESCE(emp.BDCODMATRIZ, s.BDCODEMP) as BDCODMATRIZ, s.BDCHAVE, s.BDREFLAN, s.BDCODSITNF, S.bddataemissao, S.BDNUMDOCINI, S.BDCONDPGTO ';
wSQL = wSQL||              'FROM VEF_EMP_TMOVSER s ';
wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
IF (wINCTRIB = 2) THEN
wSQL = wSQL||             'AND (s.BDTIPLAN = 0) ';
wSQL = wSQL||               'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
wSQL = wSQL||               'AND ((SELECT FIRST 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
wSQL = wSQL||               'AND EXISTS(SELECT * '; -- Alt.: #88586 - Ajustes para não exportar lançamentos quando tenham alguma CFOP com a opção "Não levar Sped Contribuições"
wSQL = wSQL||                          'FROM VEF_EMP_TMOVSERITENS si ';
wSQL = wSQL||                          'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = si.bdCODNAT AND ((nat.bdNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.bdNAOEXPEFDCONT)) = TRIM(''FALSE''))) )  ';
wSQL = wSQL||                          'WHERE si.bdCODEMP = s.bdCODEMP ';
wSQL = wSQL||                            'AND si.bdCHAVE  = s.bdCHAVE) ';
wSQL = wSQL||             ') mov ';
wSQL = wSQL||        'JOIN (SELECT P.BDCODEMP, P.BDCHAVE, ';
wSQL = wSQL||                     'CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETPIS, 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETCOFINS, 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETCSLL, 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETIRRF, 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETISSQN, 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR ';
wSQL = wSQL||              'FROM VEF_EMP_TMOVSERPARPGTO P ';
wSQL = wSQL||              'WHERE P.'||TRIM(:PRWHEREEMPRESAS)||' ';
wSQL = wSQL||                'AND (CAST(SUBSTRING(P.BDDATAPGTOPAR FROM 1 FOR 4) || SUBSTRING(P.BDDATAPGTOPAR FROM 6 FOR 2) AS INTEGER) = '||:PRREFERENCIA||') ';
wSQL = wSQL||                'AND p.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
wSQL = wSQL||              'GROUP BY P.BDCODEMP, P.BDCHAVE ';
wSQL = wSQL||             ') PGTO ON (PGTO.BDCODEMP = MOV.BDCODEMP AND PGTO.BDCHAVE = MOV.BDCHAVE) ';
wSQL = wSQL||        'JOIN VEF_EMP_TMOVSER S ON(S.BDCODEMP = MOV.BDCODEMP AND S.BDCHAVE = MOV.BDCHAVE) ';
wSQL = wSQL||        'JOIN VEF_EMP_TMOVSERITENS i on (mov.BDCODEMP = i.BDCODEMP AND mov.BDCHAVE = i.BDCHAVE) ';
wSQL = wSQL||        'left outer join TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = I.BDCODEMP AND SCP.BDCODSCP = I.BDCODSCP AND SCP.BDREFEMP = I.BDREFSOC) ';
wSQL = wSQL||        'LEFT OUTER JOIN (SELECT i.bdCODEMP, i.bdCHAVE, SUM(i.bdVLRCONTAB) AS bdVLRCONTABTOTAL '; -- Alt.: #135727 - Deve considerar apenas o valor contábil que gera as parcelas, caso contrario o valor das parcelas eh menor que o total da nota(sustitui o bdVALORNOTA)...
wSQL = wSQL||                         'FROM VEF_EMP_TMOVSERITENS i ';
wSQL = wSQL||                         'LEFT OUTER JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT) ';
wSQL = wSQL||                         'WHERE nat.bdLANCPARCELAMENTO = ''TRUE'' ';
wSQL = wSQL||                         'GROUP BY i.bdCODEMP, i.bdCHAVE) iVlr on (iVlr.bdCODEMP = mov.bdCODEMP AND iVlr.bdCHAVE = mov.bdCHAVE) ';
wSQL = wSQL||        'JOIN VEF_EMP_TA170 a170 on (mov.BDCODEMP = a170.BDCODEMP AND mov.BDCHAVE = a170.BDCHAVE AND i.BDORDEM = a170.BDORDEM) ';
wSQL = wSQL||        'LEFT OUTER JOIN TCADPRO_VINC vinc ON (vinc.bdCODEMP = a170.bdCODEMP and vinc.bdCODPROD = a170.bdCODPROD) ';
wSQL = wSQL||        'WHERE (a170.BDCODCSTCOF is not null) ';
wSQL = wSQL||        'GROUP BY mov.bdCODEMP,mov.bdCODMATRIZ,a170.bdCHAVE,a170.bdORDEM,a170.bdNUM_ITEM,vinc.bdTIPOPROD,a170.bdCODCSTPIS,a170.bdALIQ_PIS,a170.bdCODCSTCOF,a170.bdALIQ_COFINS,scp.bdCODEMPSCP, BDCODNAT, BDDATANOTA, BDNUMDOC, MOV.BDCONDPGTO ';
wSQL = wSQL||        'union all ';
wSQL = wSQL||        'SELECT mov.BDCODEMP, mov.BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, 0 AS BDTIPOPROD, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
wSQL = wSQL||               'pgto.bdvalorpgtopar BDVL_ITEM, ';
wSQL = wSQL||               'mov.BDCODCSTPIS,';
wSQL = wSQL||               'SUM(CAST(MOV.BDVL_BC_PIS_ AS NUMERIC(15,6)) * CAST(PGTO.BDVALORPGTOPAR AS NUMERIC(15,6))) BDBCCOFINS, ';
wSQL = wSQL||               'mov.BDALIQ_PIS AS BDALIQPIS,';
wSQL = wSQL||               'SUM(CAST(COALESCE(MOV.BDVLR_PIS,0)*((PGTO.BDVALORPGTOPAR/CAST(MOV.BDVL_OPER AS NUMERIC(15,6))))AS DM_NUMERIC_15_2)) BDVLRPIS, ';
wSQL = wSQL||               'mov.BDCODCSTCOF,';
wSQL = wSQL||               'SUM(CAST(MOV.BDVL_BC_COFINS_ AS NUMERIC(15,6)) * CAST(PGTO.BDVALORPGTOPAR AS NUMERIC(15,6))) BDBCCOFINS,';
wSQL = wSQL||               'mov.BDALIQ_COFINS AS BDALIQCOFINS,';
wSQL = wSQL||               'SUM((CAST(COALESCE(MOV.BDVLR_COFINS,0)*((PGTO.BDVALORPGTOPAR/CAST(MOV.BDVL_OPER AS NUMERIC(15,6))))AS DM_NUMERIC_15_2))) BDVLRCOFINS, ';
wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
wSQL = wSQL||               'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT, MOV.BDCODEMPSCP, MOV.BDRECEITAFINANCEIRA, NULL BDCODNAT, MOV.BDCODTIPODOC ||'' - ''|| MOV.BDDESCRICAO BDDESCTIPODOC, MOV.bddt_oper  AS BDDATANOTA, mov.bdnumdoc as BDNUMDOC, MOV.BDCONDPGTO ';
wSQL = wSQL||        'FROM (SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDCHAVE, dem.BDREFLAN, dem.BDCODCSTPIS, dem.BDCODCSTCOF, dem.BDCODNATREC, dem.BDNAT_BC_CRED,';
wSQL = wSQL||                     'dem.BDVL_BC_PIS, dem.BDALIQ_PIS, dem.BDVLR_PIS,';
wSQL = wSQL||        'dem.BDVL_BC_COFINS, dem.BDALIQ_COFINS, dem.BDVLR_COFINS, DEM.BDVL_OPER, DEM.BDCODSCP,DEM.BDREFSOC, CAD.BDRECEITAFINANCEIRA, DEM.bddt_oper, dem.bdnumdoc, CAD.bddescricao, CAD.BDCODTIPODOC ';
wSQL = wSQL||                     ', CAST(COALESCE(DEM.BDVL_BC_PIS,0) AS NUMERIC(15,6)) / CAST(COALESCE(DEM.BDVL_OPER,0) AS NUMERIC(15,6)) AS BDVL_BC_PIS_ ';
wSQL = wSQL||                     ', CAST(COALESCE(DEM.BDVL_BC_COFINS,0) AS NUMERIC(15,6)) / CAST(COALESCE(DEM.BDVL_OPER,0) AS NUMERIC(15,6)) AS BDVL_BC_COFINS_ , DEM.BDCONDPGTO, SCP.BDCODEMPSCP ';
wSQL = wSQL||              'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
wSQL = wSQL||              'left outer join VEF_BASE_TCADTIPODEMDOC CAD on (dem.BDCODTIPODOC = CAD.BDCODTIPODOC)';
wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
wSQL = wSQL||              'left outer join TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = DEM.BDCODEMP AND SCP.BDCODSCP = DEM.BDCODSCP AND SCP.BDREFEMP = DEM.BDREFSOC) ';
wSQL = wSQL||              ' WHERE DEM.'||TRIM(:prWHEREEMPRESAS)||' ';
IF (wINCTRIB = 2) THEN
wSQL = wSQL||              ' AND (dem.BDIND_OPER <> 1) '; -- Operação de Aquisição...
wSQL = wSQL||                'AND ((CAD.BDNAOEXPSPED = ''FALSE'') or (CAD.BDNAOEXPSPED is null))';
IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e WHERE e.BDCODEMP = coalesce(SCP.BDCODEMPSCP, DEM.BDCODEMP) AND e.BDREFEMP <= dem.BDREFLAN ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
wSQL = wSQL||             ') mov ';
wSQL = wSQL||        'JOIN (SELECT P.BDCODEMP, P.BDCHAVE, ';
wSQL = wSQL||                     'CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETPIS, 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETCOFINS, 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETCSLL, 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETIRRF, 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETISSQN, 0)) + ';
wSQL = wSQL||                      'SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR ';
wSQL = wSQL||              'FROM VEF_EMP_TMOVF100PARPGTO P ';
wSQL = wSQL||              'WHERE P.'||TRIM(:PRWHEREEMPRESAS)||' ';
wSQL = wSQL||                'AND (CAST(SUBSTRING(P.BDDATAPGTOPAR FROM 1 FOR 4) || SUBSTRING(P.BDDATAPGTOPAR FROM 6 FOR 2) AS INTEGER) = '||:PRREFERENCIA||') ';
wSQL = wSQL||                'AND p.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
wSQL = wSQL||              'GROUP BY P.BDCODEMP, P.BDCHAVE ';
wSQL = wSQL||             ') PGTO ON (PGTO.BDCODEMP = MOV.BDCODEMP AND PGTO.BDCHAVE = MOV.BDCHAVE) ';
--wSQL = wSQL||        'left outer join TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = mov.BDCODEMP AND SCP.BDCODSCP = mov.BDCODSCP AND SCP.BDREFEMP = mov.BDREFSOC) ';
wSQL = wSQL||        'WHERE ((mov.BDCODCSTPIS is not null) or (mov.BDCODCSTCOF is not null)) ';
wSQL = wSQL||        'GROUP BY mov.bdCODEMP,mov.bdCODMATRIZ,mov.bdCHAVE,pgto.bdVALORPGTOPAR,mov.bdCODCSTPIS,mov.bdALIQ_PIS,mov.bdCODCSTCOF,mov.bdALIQ_COFINS,mov.bdCODEMPSCP,MOV.BDRECEITAFINANCEIRA,  BDDESCTIPODOC, BDDATANOTA, BDNUMDOC, MOV.BDCONDPGTO ';
EXECUTE STATEMENT ( wSQLPREFIXO || wSQL || wSQLSUFIXO );
END
/* Saídas - F500 */
wSQL =               'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 17 AS BDCODTP, ';
wSQL = wSQL||               '0 AS BDTIPOPROD, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
wSQL = wSQL||               'SUM(IIF(BDVALORNOTA > 0,((F500.BDVLRREC*I.BDVLRCONTAB )/IIF(BDVALORNOTA = 0,1,BDVALORNOTA)),F500.BDVLRREC)) AS BDVL_ITEM, ';
wSQL = wSQL||               'f500.bdCODCSTPIS, SUM(IIF(BDVALORNOTA > 0,((F500.BDBASEPIS*I.BDVLRCONTAB )/IIF(BDVALORNOTA = 0,1,BDVALORNOTA)),F500.BDBASEPIS)) AS BDBCPIS, f500.BDALIQPIS, SUM(IIF(BDVALORNOTA > 0,((F500.BDVLRPIS*I.BDVLRCONTAB )/IIF(BDVALORNOTA = 0,1,BDVALORNOTA)),F500.BDVLRPIS)) BDVLRPIS, ';
wSQL = wSQL||               'f500.BDCODCSTCOF, SUM(IIF(BDVALORNOTA > 0,((F500.BDBASECOF*I.BDVLRCONTAB )/IIF(BDVALORNOTA = 0,1,BDVALORNOTA)),F500.BDBASECOF)) AS BDBCCOFINS, f500.BDALIQCOF AS BDALIQCOFINS, SUM(IIF(BDVALORNOTA > 0,((F500.BDVLRCOF*I.BDVLRCONTAB )/IIF(BDVALORNOTA = 0,1,BDVALORNOTA)),F500.BDVLRCOF)) AS BDVLRCOFINS, ';
wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT, ';
WSQL = WSQL||  'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT,SCP.BDCODEMPSCP, ''FALSE'' BDRECEITAFINANCEIRA, I.BDCODNAT, NULL BDDESCTIPODOC, NULL BDTIPOREDZ, NULL BDDESCPEREXP,  NULL BDDESCNATREC, BDDATAEMISSAO AS BDDATANOTA, BDNUMDOCINI as BDNUMDOC, BDCONDPGTO ';
wSQL = wSQL||        'FROM (SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, S.BDVALORNOTA, S.BDDATAEMISSAO, S.BDNUMDOCINI,S.BDCONDPGTO ';
wSQL = wSQL||               'FROM VEF_EMP_TMOVSAI s ';
wSQL = wSQL||               'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';  -- Notas canceladas...
IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
wSQL = wSQL||               'AND (s.BDCONDPGTO <> 1) ';
wSQL = wSQL||                'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
wSQL = wSQL||                'AND EXISTS(SELECT * ';
wSQL = wSQL||                           'FROM VEF_EMP_TMOVSAIITENS si ';
wSQL = wSQL||                           'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = si.bdCODNAT AND ((nat.bdNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.bdNAOEXPEFDCONT)) = TRIM(''FALSE'')))) ';
wSQL = wSQL||                           'WHERE si.bdCODEMP = s.bdCODEMP ';
wSQL = wSQL||                             'AND si.bdCHAVE = s.bdCHAVE) ';
wSQL = wSQL||                'AND (NOT EXISTS(SELECT * FROM VEF_EMP_TMOVSAI x ';
wSQL = wSQL||                                'JOIN VEF_EMP_TMOVPROSAI xp ON (xp.bdCODEMP = x.bdCODEMP AND xp.bdCHAVE = x.bdCHAVE) ';
wSQL = wSQL||                                'WHERE x.bdMODELO not in ('||wMOD_PROD||') AND x.bdCODEMP = s.bdCODEMP AND x.bdCHAVE = s.bdCHAVE)) ';
wSQL = wSQL||                'AND (NOT EXISTS(SELECT * FROM VEF_EMP_TMOVSAI x ';
wSQL = wSQL||                                'JOIN VEF_EMP_TD100SAI xp ON (xp.bdCODEMP = x.bdCODEMP AND xp.bdCHAVE = x.bdCHAVE) ';
wSQL = wSQL||                                'WHERE x.bdMODELO not in ('||wMOD_TRANSPORTE||') AND x.bdCODEMP = s.bdCODEMP AND x.bdCHAVE = s.bdCHAVE)) ';
wSQL = wSQL||              ') mov ';
wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE) ';
wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = I.BDCODEMP AND SCP.BDCODSCP = I.BDCODSCP AND SCP.BDREFEMP = I.BDREFSOC) ';
wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TF500SAI f500 on (f500.BDCODEMP = mov.BDCODEMP AND f500.BDCHAVE = mov.BDCHAVE) ';
wSQL = wSQL||        'GROUP BY MOV.BDCODEMP, BDCODMATRIZ,BDREFERENCIA, MOV.BDCHAVE,BDORDEM, BDORDEMPRO, BDCODTP, BDCOD_CONT_PIS,BDCOD_CONT_COF, ';
wSQL = wSQL||        'F500.BDCODCSTPIS, F500.BDALIQPIS,F500.BDCODCSTCOF,BDALIQCOFINS,BDQUANT_BC_PIS,BDALIQ_PIS_QUANT, BDQUANT_BC_COF,BDALIQ_COF_QUANT,SCP.BDCODEMPSCP, I.BDCODNAT, BDDATANOTA, BDNUMDOC, MOV.BDCONDPGTO ';
wSQL = wSQL||        'union all ';        
/* Saídas - Produtos */
wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, mov.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, 2 AS BDCODTP, COALESCE(vinc.BDTIPOPROD, 0) BDTIPOPROD, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
IF ((wINCTRIB = 2) AND (wCODCRIT = 2)) THEN
wSQL = wSQL||               'COALESCE(p.BDVLRITEM, 0) + COALESCE(P.BDVLRFRETE, 0) AS BDVL_ITEM,';  --Matheus Amaral - 01/07/2020 - F550 - Valor da Receita #129883 - alterado para trazer o valor do frete no valor total do produto
else
wSQL = wSQL||               'COALESCE(p.BDVLRITEM, 0) AS BDVL_ITEM,';  --Matheus Amaral - 01/07/2020 - F550 - Valor da Receita #129883 - alterado para trazer o valor do frete no valor total do produto
wSQL = wSQL||               'p.BDCODCSTPIS, p.BDBCPIS, p.BDALIQPIS, p.BDVLRPIS,';
wSQL = wSQL||               'p.BDCODCSTCOF, p.BDBCCOFINS, p.BDALIQCOFINS, p.BDVLRCOFINS,';
wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
wSQL = wSQL||  'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT, SCP.BDCODEMPSCP, ''FALSE'' BDRECEITAFINANCEIRA, I.BDCODNAT, NULL BDDESCTIPODOC, NULL BDTIPOREDZ,  NULL BDDESCPEREXP,  NULL BDDESCNATREC, MOV.bddataemissao BDDATANOTA, MOV.BDNUMDOCINI as BDNUMDOC, MOV.BDCONDPGTO ';
wSQL = wSQL||        'FROM (SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDDATAEMISSAO, S.BDNUMDOCINI,S.BDCONDPGTO ';
wSQL = wSQL||               'FROM VEF_EMP_TMOVSAI s ';
wSQL = wSQL||               'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
wSQL = wSQL||                 'AND (s.BDMODELO not in ('||wMOD_PROD||')) '; -- Modelos que não são produtos...
IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
wSQL = wSQL||               'AND (s.BDCONDPGTO <> 1) ';
wSQL = wSQL||                'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
wSQL = wSQL||                 'AND s.BDREFLAN = '||:prREFERENCIA;
wSQL = wSQL||                 'AND exists(select * ';
wSQL = wSQL||                            'from VEF_EMP_TMOVSAIITENS SI ';
wSQL = wSQL||                            'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
wSQL = wSQL||                            'where SI.BDCODEMP = S.BDCODEMP and ';
wSQL = wSQL||                            'SI.BDCHAVE = S.BDCHAVE)';
wSQL = wSQL||              ') mov ';
wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
wSQL = wSQL||        'left outer join TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = I.BDCODEMP AND SCP.BDCODSCP = I.BDCODSCP AND SCP.BDREFEMP = I.BDREFSOC) ';
wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVPROSAI p on (p.BDCODEMP = i.BDCODEMP AND p.BDCHAVE = i.BDCHAVE AND p.BDORDEM = i.BDORDEM) ';
wSQL = wSQL||        'LEFT OUTER JOIN TCADPRO_VINC vinc ON(vinc.bdCODEMP = p.bdCODEMP AND vinc.bdCODPROD = p.bdCODPROD) ';
wSQL = wSQL||        'WHERE (p.BDCODPROD is not null) ';
wSQL = wSQL||        'union all ';
/* Saídas - Transporte (D100) */
wSQL = wSQL||       'SELECT mov.bdCODEMP, COALESCE(emp.bdCODMATRIZ, mov.bdCODEMP) AS bdCODMATRIZ, mov.bdREFLAN AS bdREFERENCIA, mov.bdCHAVE,';
wSQL = wSQL||              'NULL AS BDORDEM, NULL AS BDORDEMPRO, 16 AS BDCODTP, 0 AS BDTIPOPROD, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF,';
wSQL = wSQL||              'i.bdVLRCONTAB AS bdVL_ITEM, d100.bdCODCSTPIS,'; -- Alt.: #123939 - Deve proporcionalizar o valor...
wSQL = wSQL||              '((D100.BDVL_BC_PIS*I.BDVLRCONTAB) / iif(MOV.BDVALORNOTA = 0, 1, MOV.BDVALORNOTA)) AS bdBCPIS,';
wSQL = wSQL||              'd100.bdALIQ_PIS AS bdALIQPIS,';
wSQL = wSQL||              '((d100.bdVLRPIS*I.BDVLRCONTAB) / iif(MOV.BDVALORNOTA = 0, 1, MOV.BDVALORNOTA)) AS bdVLRPIS,';
wSQL = wSQL||              'd100.bdCODCSTCOF,';
wSQL = wSQL||              '((d100.bdVL_BC_COF*I.BDVLRCONTAB) / iif(MOV.BDVALORNOTA = 0, 1, MOV.BDVALORNOTA)) AS BDBCCOFINS,';
wSQL = wSQL||              'd100.bdALIQ_COF AS bdALIQCOFINS,';
wSQL = wSQL||              '((d100.bdVLRCOFINS*I.BDVLRCONTAB) / iif(MOV.BDVALORNOTA = 0, 1, MOV.BDVALORNOTA)) AS bdVLRCOFINS,';
wSQL = wSQL|| 'NULL AS bdQUANT_BC_PIS, NULL AS bdALIQ_PIS_QUANT, NULL AS bdQUANT_BC_COF, NULL AS bdALIQ_COF_QUANT, SCP.BDCODEMPSCP, ''FALSE'' BDRECEITAFINANCEIRA, I.BDCODNAT, NULL BDDESCTIPODOC, NULL BDTIPOREDZ,  NULL BDDESCPEREXP,  NULL BDDESCNATREC, MOV.BDDATAEMISSAO BDDATANOTA, MOV.BDNUMDOCINI as BDNUMDOC, MOV.BDCONDPGTO ';
wSQL = wSQL||        'FROM (SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDVALORNOTA, S.BDDATAEMISSAO, S.BDNUMDOCINI,S.BDCONDPGTO ';
wSQL = wSQL||               'FROM VEF_EMP_TMOVSAI s ';
wSQL = wSQL||               'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
wSQL = wSQL||                 'AND (s.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Transporte
IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
wSQL = wSQL||                 'AND (s.BDCONDPGTO <> 1) ';
wSQL = wSQL||                   'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
wSQL = wSQL||                 ' AND s.BDREFLAN = '||:prREFERENCIA;
wSQL = wSQL||              ') mov ';
wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
wSQL = wSQL||        'left outer join TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = I.BDCODEMP AND SCP.BDCODSCP = I.BDCODSCP AND SCP.BDREFEMP = I.BDREFSOC) ';
wSQL = wSQL||        'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = I.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TD100SAI d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
wSQL = wSQL||        'WHERE (d100.BDCHAVE is not null) ';

wSQL = wSQL||        'union all ';
/*SAÍDAS - D400*/
wSQL = wSQL||       'SELECT mov.bdCODEMP, COALESCE(emp.bdCODMATRIZ, mov.bdCODEMP) AS bdCODMATRIZ, mov.bdREFLAN AS bdREFERENCIA, mov.bdCHAVE, ';
wSQL = wSQL||              'NULL AS BDORDEM, NULL AS BDORDEMPRO, 18 AS BDCODTP, 0 AS BDTIPOPROD, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
wSQL = wSQL||              'i.bdVLRCONTAB AS bdVL_ITEM, d400.bdCODCSTPIS, '; -- Alt.: #123939 - Deve proporcionalizar o valor...
wSQL = wSQL||              '((D400.BDVL_BC_PIS * I.BDVLRCONTAB) / iif(MOV.BDVALORNOTA = 0, 1, MOV.BDVALORNOTA)) AS bdBCPIS, ';
wSQL = wSQL||              'd400.bdALIQ_PIS AS bdALIQPIS, ';
wSQL = wSQL||              '((D400.bdVL_PIS * I.BDVLRCONTAB) / iif(MOV.BDVALORNOTA = 0, 1, MOV.BDVALORNOTA)) AS bdVLRPIS, ';
wSQL = wSQL||              'd400.bdCODCSTCOF, ';
wSQL = wSQL||              '((D400.bdVL_BC_COF * I.BDVLRCONTAB) / iif(MOV.BDVALORNOTA = 0, 1, MOV.BDVALORNOTA)) AS BDBCCOFINS, ';
wSQL = wSQL||              'd400.bdALIQ_COF AS bdALIQCOFINS, ';
wSQL = wSQL||              '((D400.bdVL_COF * I.BDVLRCONTAB) / iif(MOV.BDVALORNOTA = 0, 1, MOV.BDVALORNOTA)) AS bdVLRCOFINS, ';
wSQL = wSQL|| 'NULL AS bdQUANT_BC_PIS, NULL AS bdALIQ_PIS_QUANT, NULL AS bdQUANT_BC_COF, NULL AS bdALIQ_COF_QUANT, SCP.BDCODEMPSCP, ''FALSE'' BDRECEITAFINANCEIRA, I.BDCODNAT, NULL BDDESCTIPODOC, NULL BDTIPOREDZ,  NULL BDDESCPEREXP,  NULL BDDESCNATREC, MOV.BDDATAEMISSAO BDDATANOTA, MOV.BDNUMDOCINI as BDNUMDOC, MOV.BDCONDPGTO ';
wSQL = wSQL||        'FROM (SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDVALORNOTA, s.BDDATAEMISSAO, S.BDNUMDOCINI, S.BDCONDPGTO ';
wSQL = wSQL||               'FROM VEF_EMP_TMOVSAI s ';
wSQL = wSQL||               'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';  -- Notas canceladas...
wSQL = wSQL||                 'AND (s.BDMODELO in ('||wMOD_TRANSPORTE||')) ';  -- Transporte
IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
wSQL = wSQL||                 'AND (s.BDCONDPGTO <> 1) ';
wSQL = wSQL||                   'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
wSQL = wSQL||                  'AND s.BDREFLAN = '||:prREFERENCIA;
wSQL = wSQL||              ') mov ';
wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
wSQL = wSQL||        'left outer join TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = I.BDCODEMP AND SCP.BDCODSCP = I.BDCODSCP AND SCP.BDREFEMP = I.BDREFSOC) ';
wSQL = wSQL||        'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = I.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TD400SAI d400 on (d400.BDCODEMP = mov.BDCODEMP AND d400.BDCHAVE = mov.BDCHAVE) ';
wSQL = wSQL||        'WHERE (d400.BDCHAVE is not null) ';
wSQL = wSQL||        'union all ';
/* Demais documentos - Receita */
wSQL = wSQL||        'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDREFLAN AS BDREFERENCIA, dem.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, 0 AS BDTIPOPROD, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
wSQL = wSQL||               'dem.BDVL_OPER AS BDVL_ITEM,';
wSQL = wSQL||               'dem.BDCODCSTPIS, dem.BDVL_BC_PIS AS BDBCPIS, dem.BDALIQ_PIS AS BDALIQPIS, dem.BDVLR_PIS AS BDVLRPIS,';
wSQL = wSQL||               'dem.BDCODCSTCOF, dem.BDVL_BC_COFINS AS BDBCCOFINS, dem.BDALIQ_COFINS AS BDALIQCOFINS, dem.BDVLR_COFINS AS BDVLRCOFINS,';
wSQL = wSQL||               'NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
wSQL = wSQL||  'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT, SCP.BDCODEMPSCP, CAD.BDRECEITAFINANCEIRA, NULL AS BDCODNAT, CAD.BDCODTIPODOC || '' - '' || CAD.BDDESCRICAO BDDESCTIPODOC, NULL BDTIPOREDZ,  NULL BDDESCPEREXP,  NULL BDDESCNATREC, BDDT_OPER AS BDDATANOTA, BDNUMDOC as BDNUMDOC, DEM.BDCONDPGTO ';
wSQL = wSQL||        'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
wSQL = wSQL||        'left outer join VEF_BASE_TCADTIPODEMDOC CAD on (dem.BDCODTIPODOC = CAD.BDCODTIPODOC)';
wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
wSQL = wSQL||        'left outer join TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = dem.BDCODEMP AND SCP.BDCODSCP = dem.BDCODSCP AND SCP.BDREFEMP = dem.BDREFSOC) ';
wSQL = wSQL||        'WHERE DEM.'||TRIM(:prWHEREEMPRESAS)||' ';
wSQL = wSQL||         'AND ((CAD.BDNAOEXPSPED = ''FALSE'') or (CAD.BDNAOEXPSPED is null))';
wSQL = wSQL||         ' AND dem.BDREFLAN = '||:prREFERENCIA;
IF (wINCTRIB = 2) THEN
wSQL = wSQL||        'AND (dem.BDIND_OPER <> 1) '; -- Operação de Aquisição...
IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
wSQL = wSQL||          'AND (dem.BDCONDPGTO <> 1) ';
wSQL = wSQL||        ' union all ';
/* Serviços tomados(Emitidos) */
wSQL = wSQL||        'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, a.BDCHAVE, a.BDORDEM, a.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, COALESCE(vinc.bdTIPOPROD,0) bdTIPOPROD, NULL AS BDCOD_CONT_PIS, NULL AS BDCOD_CONT_COF, ';
wSQL = wSQL||               'a.BDVL_ITEM, a.BDCODCSTPIS, a.BDVL_BC_PIS AS BDBCPIS, a.BDALIQ_PIS AS BDALIQPIS, a.BDVL_PIS AS BDVLRPIS,';
wSQL = wSQL||               'a.BDCODCSTCOF, a.BDVL_BC_COFINS AS BDBCCOFINS, a.BDALIQ_COFINS AS BDALIQCOFINS, a.BDVL_COFINS AS BDVLRCOFINS,NULL AS BDQUANT_BC_PIS, NULL AS BDALIQ_PIS_QUANT,';
WSQL = WSQL||  'NULL AS BDQUANT_BC_COF, NULL AS BDALIQ_COF_QUANT, SCP.BDCODEMPSCP, ''FALSE'' BDRECEITAFINANCEIRA, I.BDCODNAT, NULL BDDESCTIPODOC, NULL BDTIPOREDZ,  NULL BDDESCPEREXP,  NULL BDDESCNATREC, MOV.BDDATAEMISSAO BDDATANOTA, MOV.BDNUMDOCINI as BDNUMDOC, MOV.BDCONDPGTO  ';
wSQL = wSQL||        'FROM (SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDDATAEMISSAO, S.BDNUMDOCINI, S.BDCONDPGTO  ';
wSQL = wSQL||               'FROM VEF_EMP_TMOVSER s ';
wSQL = wSQL||               'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
IF (wINCTRIB = 2) THEN
wSQL = wSQL||                 'AND (s.BDTIPLAN = 0) ';
IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
wSQL = wSQL||                 'AND (s.BDCONDPGTO <> 1) ';
wSQL = wSQL||                 'AND S.'||TRIM(:prWHEREEMPRESAS)||' ';
wSQL = wSQL||                 ' AND s.BDREFLAN = '||:prREFERENCIA;
wSQL = wSQL||    'AND EXISTS(SELECT * '; -- Alt.: #88586 - Ajustes para não exportar lançamentos quando tenham alguma CFOP com a opção "Não levar Sped Contribuições"
wSQL = wSQL||                            'FROM VEF_EMP_TMOVSERITENS si ';
wSQL = wSQL||                            'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = si.bdCODNAT AND ((nat.bdNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.bdNAOEXPEFDCONT)) = TRIM(''FALSE''))) ) ';
wSQL = wSQL||                            'WHERE si.bdCODEMP = s.bdCODEMP ';
wSQL = wSQL||                              'AND si.bdCHAVE  = s.bdCHAVE) ';
wSQL = wSQL||              ') mov ';
wSQL = wSQL||        'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TMOVSERITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
wSQL = wSQL||        'left outer join TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = I.BDCODEMP AND SCP.BDCODSCP = I.BDCODSCP AND SCP.BDREFEMP = I.BDREFSOC) ';
wSQL = wSQL||        'LEFT OUTER JOIN VEF_EMP_TA170 a on (a.BDCODEMP = i.BDCODEMP AND a.BDCHAVE = i.BDCHAVE AND a.BDORDEM = i.BDORDEM) ';
wSQL = wSQL||        'LEFT OUTER JOIN TCADPRO_VINC vinc ON (vinc.bdCODEMP = a.bdCODEMP and vinc.bdCODPROD = a.bdCODPROD) ';
wSQL = wSQL||        'WHERE (a.BDCODPROD is not null) ';
EXECUTE STATEMENT ( wSQLPREFIXO || wSQL || wSQLSUFIXO );

/* Continucao dessa SP que atingiu os 64k de tamanho das SP */
execute procedure SP_APURACAO_BLOCOM_M210_M610_P2(:PRCODEMP, :PRREFERENCIA, :PRWHEREEMPRESAS, :PRVERIFICARINCONSISTENCIAS, :PRAJUSTESCP, :PRCODEMPSO);
/* Insere os valores no nas tabelas do M210 e M610, pois já atingiu o tamanho máximo da SP */
EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M210_M610AUX(:prCODEMP, :prREFERENCIA, :prverificarinconsistencias, :PRAJUSTESCP, :PRRETIFICADORA, :PREXECREL, :PRCODEMPSO);
END
END
^


/*
  Elizeu - 12-09-18 - Apuração Bloco M215/M615 #82005
*/

create or alter procedure SP_APURACAO_BLOCOM_M215_M615 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRRETIFICADORA integer,
    PRAJUSTESCP DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
declare variable WINCTRIB integer;
declare variable WCODCRIT integer;
BEGIN
  -- INSERE A COMPETÊNCIA DA APURAÇÃO...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :WINCTRIB, :WCODCRIT;

  if ((:WINCTRIB is null) and (:PRCODEMPSO > 0)) then
    begin
      SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMPSO
      INTO :WINCTRIB, :WCODCRIT;
    end

  IF ((WINCTRIB IS NOT NULL) AND (WCODCRIT IS NOT NULL)) THEN
    BEGIN
      /* Registro M215: Ajustes da Base de Cálculo da Contribuição para o PIS/Pasep Apurada */
            INSERT INTO VEF_EMP_TBLOCOM215_M615 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA,BDCHAVE, BDORDEM,
                                           BDTIPOPROD,BDCOD_AJ_BC,BDIND_AJ_BC,BDVL_AJ_BC,BDNUMDOC,BDDESCR_AJ_BC,BDDT_REF_AJU,BDCNPJ_ESTAB,BDINFO_COMPL,bdcodplapadrao,bdcodtpla, BDRETIFICADORA)
      SELECT 7 as BDCODPERIODO, COALESCE(SCP.BDCODEMPSCP,m215.BDCODEMP) BDCODEMP, COALESCE(SCP.BDCODEMPSCP,COALESCE(emp.BDCODMATRIZ, m215.BDCODEMP)) as BDCODMATRIZ,19 as BDCODQUADRO, m215.BDREFERENCIA,
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,m215.BDCODEMP) AND x.BDREFERENCIA = m215.BDREFERENCIA AND X.BDRETIFICADORA = :PRRETIFICADORA AND x.BDCODQUADRO = 19 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m215.BDCODCSOCIAL and COALESCE(x.BDTIPOPROD,0) = COALESCE(m215.BDTIPOPROD,0) and x.BDALIQ = m215.BDALIQPIS) as BDCHAVE,
             GETORDEMSEQUENCIAL_STR('M215.'||7||'.'||m215.BDCODEMP||'.'||COALESCE(emp.BDCODMATRIZ, m215.BDCODEMP)||'.'||19||'.'||m215.BDREFERENCIA||'.'||SCP.BDCODEMPSCP||'.'||
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,m215.BDCODEMP) AND x.BDREFERENCIA = m215.BDREFERENCIA
             AND x.BDCODQUADRO = 19 AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m215.BDCODCSOCIAL and COALESCE(x.BDTIPOPROD,0) = COALESCE(m215.BDTIPOPROD,0) AND x.BDALIQ = m215.BDALIQPIS), :prCODEMP) as BDORDEM,
         /*   (SELECT COALESCE(MAX(x.BDORDEM)+1, 1) FROM VEF_EMP_TBLOCOM215_M615 x WHERE x.BDCODEMP = m215.BDCODEMP AND x.BDREFERENCIA = m215.BDREFERENCIA
                                                                                    AND x.BDCODQUADRO = 19         AND x.BDCODPERIODO = 7
                                                                                    AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE
                                                                                                     FROM VEF_EMP_TBLOCOM210_M610 x
                                                                                                     WHERE x.BDCODEMP = m215.BDCODEMP
                                                                                                       AND x.BDREFERENCIA = m215.BDREFERENCIA
                                                                                                       AND x.BDCODQUADRO = 19
                                                                                                       AND x.BDCODPERIODO = 7
                                                                                                       AND x.BDCODCSOCIAL = m215.BDCODCSOCIAL
                                                                                                       AND x.BDALIQ = m215.BDALIQPIS
                                                                                                       )) as BDORDEM, */
      m215.BDTIPOPROD, m215.BDCOD_AJ_BC  ,m215.BDIND_AJ_BC,m215.bdvl_aj_bc_pis,m215.BDNUMDOC,m215.BDDESCR_AJ_BC,m215.BDDT_REF_AJU,emp.BDCNPJEMP,m215.BDINFO_COMPL,m215.bdcodplapadrao,m215.bdcodtpla,
      :PRRETIFICADORA BDRETIFICADORA
      FROM VEF_EMP_TLANAJUM215_M615 m215
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m215.BDCODEMP)
      LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (M215.BDCODEMP = SCP.BDCODEMP AND M215.BDCODSCP = SCP.BDCODSCP AND M215.BDREFSOC = SCP.BDREFEMP)
      WHERE m215.bdvl_aj_bc_pis > 0
        AND m215.BDCODEMP in (SELECT ex.BDCODEMP
                             FROM TEMPRESAS ex
                             WHERE ex.BDCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)
                                OR ex.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP))
        AND (((iif(:PRAJUSTESCP = true and :PRCODEMPSO > 0, true, false) = true) and (coalesce(SCP.BDCODEMPSCP, 0) = :PRCODEMP)) or
             ((iif(:PRAJUSTESCP = true and :PRCODEMPSO = 0, true, false) = true) and (coalesce(SCP.BDCODEMPSCP, 0) = 0)) or (:PRAJUSTESCP = false))
        AND m215.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,m215.BDCODEMP)
                      AND X.BDRETIFICADORA = :PRRETIFICADORA
                      AND x.BDREFERENCIA = m215.BDREFERENCIA
                      AND x.BDCODQUADRO = 19
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m215.BDCODCSOCIAL
                      AND COALESCE(x.bdTIPOPROD,0) = COALESCE(m215.bdTIPOPROD,0)
                      AND x.BDALIQ = m215.BDALIQPIS));

      /* REGISTRO M620: AJUSTES DA COFINS APURADA */
      INSERT INTO VEF_EMP_TBLOCOM215_M615 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA,BDCHAVE, BDORDEM,
                                           BDTIPOPROD,BDCOD_AJ_BC,BDIND_AJ_BC,BDVL_AJ_BC,BDNUMDOC,BDDESCR_AJ_BC,BDDT_REF_AJU,BDCNPJ_ESTAB,BDINFO_COMPL,bdcodplapadrao,bdcodtpla, BDRETIFICADORA)
      SELECT 7 as BDCODPERIODO, COALESCE(SCP.BDCODEMPSCP,M615.BDCODEMP) BDCODEMP, COALESCE(SCP.BDCODEMPSCP,COALESCE(emp.BDCODMATRIZ, M615.BDCODEMP)) as BDCODMATRIZ,37 as BDCODQUADRO, M615.BDREFERENCIA,
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M615.BDCODEMP) AND x.BDREFERENCIA = M615.BDREFERENCIA AND x.BDCODQUADRO = 37 AND x.BDCODPERIODO = 7 AND X.BDRETIFICADORA = :PRRETIFICADORA AND x.BDCODCSOCIAL = M615.BDCODCSOCIAL and COALESCE(x.BDTIPOPROD,0) = COALESCE(m615.BDTIPOPROD,0) AND x.BDALIQ = M615.BDALIQCOFINS) as BDCHAVE,
             GETORDEMSEQUENCIAL_STR('M615.'||7||'.'||M615.BDCODEMP||'.'||COALESCE(emp.BDCODMATRIZ, M615.BDCODEMP)||'.'||37||'.'||M615.BDREFERENCIA||'.'||SCP.BDCODEMPSCP||'.'||
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = M615.BDCODEMP AND x.BDREFERENCIA = M615.BDREFERENCIA AND x.BDCODQUADRO = 37
             AND x.BDCODPERIODO = 7 AND X.BDRETIFICADORA = :PRRETIFICADORA AND x.BDCODCSOCIAL = M615.BDCODCSOCIAL and COALESCE(x.BDTIPOPROD,0) = COALESCE(m615.BDTIPOPROD,0) AND x.BDALIQ = M615.BDALIQCOFINS), :prCODEMP) as BDORDEM,
            /*(SELECT COALESCE(MAX(x.BDORDEM)+1, 1) FROM VEF_EMP_TBLOCOM215_M615 x WHERE x.BDCODEMP = M615.BDCODEMP AND x.BDREFERENCIA = M615.BDREFERENCIA
                                                                                    AND x.BDCODQUADRO = 37         AND x.BDCODPERIODO = 7
                                                                                    AND x.BDCHAVE = ) as BDORDEM, */
      m615.BDTIPOPROD, M615.BDCOD_AJ_BC  ,M615.BDIND_AJ_BC,M615.bdvl_aj_bc_cofins,M615.BDNUMDOC,M615.BDDESCR_AJ_BC,M615.BDDT_REF_AJU,emp.BDCNPJEMP,M615.BDINFO_COMPL,m615.bdcodplapadrao,m615.bdcodtpla,
      :PRRETIFICADORA BDRETIFICADORA
      FROM VEF_EMP_TLANAJUM215_M615 M615
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = M615.BDCODEMP)
      LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (M615.BDCODEMP = SCP.BDCODEMP AND M615.BDCODSCP = SCP.BDCODSCP AND M615.BDREFSOC = SCP.BDREFEMP)
      WHERE M615.bdvl_aj_bc_cofins > 0
        AND M615.BDCODEMP in (SELECT ex.BDCODEMP
                             FROM TEMPRESAS ex
                             WHERE ex.BDCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)
                                OR ex.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP))
        AND (((iif(:PRAJUSTESCP = true and :PRCODEMPSO > 0, true, false) = true) and (coalesce(SCP.BDCODEMPSCP, 0) = :PRCODEMP)) or
             ((iif(:PRAJUSTESCP = true and :PRCODEMPSO = 0, true, false) = true) and (coalesce(SCP.BDCODEMPSCP, 0) = 0)) or (:PRAJUSTESCP = false))
        AND M615.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M615.BDCODEMP)
                      AND X.BDRETIFICADORA = :PRRETIFICADORA
                      AND x.BDREFERENCIA = M615.BDREFERENCIA
                      AND x.BDCODQUADRO = 37
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = M615.BDCODCSOCIAL
                      AND COALESCE(x.BDTIPOPROD,0) = COALESCE(m615.BDTIPOPROD,0)
                      AND x.BDALIQ = M615.BDALIQCOFINS));

    END
END
^

create or alter procedure SP_APURACAO_BLOCOM_M220_M620 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PRCODEMPSO integer = 0)
as
declare variable WINCTRIB integer;
declare variable WCODCRIT integer;
declare variable WCONTROLCRED DM_BOOLEAN;
declare variable WCREDANTERIOR DM_BOOLEAN;
declare variable WVALORCONT_PIS numeric(15,2);
declare variable WVALORCONT_COFINS numeric(15,2);
declare variable WBDVL_AJUS_ACRES numeric(15,2);
declare variable WBDVL_AJUS_REDUC numeric(15,2);
declare variable WBDVL_CONT_DIFER_ANT numeric(15,2);
declare variable WBDVL_CONT_DIFER numeric(15,2);
declare variable WBDVL_AJ_SALDO numeric(15,2);
declare variable WBDLV_AJ_UTILIZADO numeric(15,2);
declare variable WORDEM_AJ integer;
declare variable WSQL_AJ varchar(32750);
declare variable WSQL_AJ_2 varchar(32750);
declare variable WBDCODQUADRO integer;
declare variable WBDCHAVE integer;
declare variable WBDCODPERIODO integer;
declare variable WBDCODMATRIZ integer;
declare variable BDVL_AJ_REF integer;
declare variable WBDREFLAN220 integer;
declare variable WBDDT_REF date;
declare variable WBDALIQ numeric(7,4);
declare variable WBDCODCSOCIAL integer;
declare variable WBDTIPOPROD integer;
declare variable WBDALIQ_220 numeric(7,4);
declare variable WBDCODCSOCIAL_220 integer;
declare variable WBDTIPOPROD_220 integer;
declare variable WBDCHAVE210 integer;
declare variable WBDCODEMP210 integer;
declare variable WBDCODMATRIZ210 integer;
declare variable WBDCODSCP integer;
declare variable WBDREFEMP integer;
BEGIN
  /* INSERE A COMPETÊNCIA DA APURAÇÃO... */
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT, BDCONTROLCRED, BDCREDANTERIOR FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :WINCTRIB, :WCODCRIT, :WCONTROLCRED, :WCREDANTERIOR;

  if ((:WINCTRIB is null) and (:PRCODEMPSO > 0)) then
    begin
      SELECT BDINCTRIB+1, BDCODCRIT, BDCONTROLCRED, BDCREDANTERIOR FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMPSO
      INTO :WINCTRIB, :WCODCRIT, :WCONTROLCRED, :WCREDANTERIOR;
    end

  IF ((WINCTRIB IS NOT NULL) AND (WCODCRIT IS NOT NULL)) THEN
    BEGIN
      /* REGISTRO M220: AJUSTES DA CONTRIBUIÇÃO PARA O PIS/PASEP APURADA */
      INSERT INTO VEF_EMP_TBLOCOM220_M620 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODAJUEFDC, BDIND_AJ, BDVL_AJ, BDNUM_DOC, DESCR_AJ, BDDT_REF, BDVL_AJ_SALDO, BDVL_AJ_UTILIZADO, BDVL_AJ_REF, BDRETIFICADORA)
      SELECT 7 AS BDCODPERIODO, COALESCE(SCP.BDCODEMPSCP,M220.BDCODEMP) BDCODEMP, COALESCE(SCP.BDCODEMPSCP,COALESCE(EMP.BDCODMATRIZ, M220.BDCODEMP)) AS BDCODMATRIZ, 19 AS BDCODQUADRO, M220.BDREFERENCIA,
             (SELECT FIRST 1 X.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 X WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M220.BDCODEMP) AND X.BDREFERENCIA = M220.BDREFERENCIA AND X.BDCODQUADRO = 19 AND X.BDCODPERIODO = 7 AND X.BDCODCSOCIAL = M220.BDCODCSOCIAL AND COALESCE(X.BDTIPOPROD,0) = COALESCE(M220.BDTIPOPROD,0) AND X.BDALIQ = M220.BDALIQPIS AND X.BDRETIFICADORA = :PRRETIFICADORA) AS BDCHAVE,
             GETORDEMSEQUENCIAL_STR('M220.'||7||'.'||M220.BDCODEMP||'.'||COALESCE(EMP.BDCODMATRIZ, M220.BDCODEMP)||'.'||19||'.'||M220.BDREFERENCIA||'.'||SCP.BDCODEMPSCP||'.'||
             (SELECT FIRST 1 X.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 X WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M220.BDCODEMP) AND X.BDREFERENCIA = M220.BDREFERENCIA
             AND X.BDCODQUADRO = 19 AND X.BDCODPERIODO = 7 AND X.BDCODCSOCIAL = M220.BDCODCSOCIAL AND COALESCE(X.BDTIPOPROD,0) = COALESCE(M220.BDTIPOPROD,0) AND X.BDALIQ = M220.BDALIQPIS AND X.BDRETIFICADORA = :PRRETIFICADORA), :PRCODEMP) AS BDORDEM,
 /*            (SELECT COALESCE(MAX(X.BDORDEM)+1, 1)
              FROM VEF_EMP_TBLOCOM220_M620 X
              WHERE X.BDCODEMP = M220.BDCODEMP
                AND X.BDREFERENCIA = M220.BDREFERENCIA
                AND X.BDCODQUADRO = 19
                AND X.BDCODPERIODO = 7
                AND X.BDCHAVE = (SELECT FIRST 1 X.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 X
                                 WHERE X.BDCODEMP = M220.BDCODEMP
                                   AND X.BDREFERENCIA = M220.BDREFERENCIA
                                   AND X.BDCODQUADRO = 19
                                   AND X.BDCODPERIODO = 7
                                   AND X.BDCODCSOCIAL = M220.BDCODCSOCIAL
                                   AND X.BDALIQ = M220.BDALIQPIS) ) AS BDORDEM,*/
             M220.BDCODAJUEFDC, M220.BDTIPOAJUSTE AS BDIND_AJ, M220.BDVLRAJUPIS AS BDVL_AJ, M220.BDNUMERODOC AS BDNUM_DOC, M220.BDDESCRICAO AS DESCR_AJ, M220.BDDATAREF AS BDDT_REF, IIF(M220.BDTIPOAJUSTE = 0, M220.BDVLRAJUPIS, 0), IIF(M220.BDTIPOAJUSTE = 1, M220.BDVLRAJUPIS, 0), IIF(M220.BDTIPOAJUSTE = 1, M220.BDREFERENCIA, NULL),
             :PRRETIFICADORA
      --FROM VEF_EMP_TAJUAPUPCM220620 M220 Alt.: #242771 - Busca os lancamentos e os registros que foram gerados...
      FROM (SELECT M220.BDCODEMP, M220.BDREFERENCIA, M220.BDCODCSOCIAL, M220.BDTIPOPROD, M220.BDALIQPIS, M220.BDCODAJUEFDC, M220.BDTIPOAJUSTE,
                   M220.BDVLRAJUPIS, M220.BDNUMERODOC, M220.BDDESCRICAO, M220.BDDATAREF, M220.BDCODSCP, M220.BDREFSOC
            FROM VEF_EMP_TAJUAPUPCM220620 M220
            WHERE M220.BDCODEMP IN (SELECT EX.BDCODEMP
                                    FROM TEMPRESAS EX
                                    WHERE EX.BDCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
                                       OR EX.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP))
              AND M220.BDREFERENCIA = :PRREFERENCIA
            UNION ALL
            SELECT M220.BDCODEMP, M220.BDREFERENCIA, M220.BDCODCSOCIAL, M220.BDTIPOPROD, M220.BDALIQPIS, M220.BDCODAJUEFDC, M220.BDTIPOAJUSTE,
                   M220.BDVLRAJUPIS, M220.BDNUMERODOC, M220.BDDESCRICAO, M220.BDDATAREF, M220.BDCODSCP, M220.BDREFSOC
            FROM TMP_VEF_EMP_TAJUAPUPCM220620_BLOCOM M220 -- Alt.: #242771 -- Registros automaticos do M220/620
            WHERE M220.BDCODEMP IN (SELECT EX.BDCODEMP
                                    FROM TEMPRESAS EX
                                    WHERE EX.BDCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
                                       OR EX.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP))
              AND M220.BDREFERENCIA = :PRREFERENCIA) M220
      LEFT OUTER JOIN TEMPRESAS EMP ON (EMP.BDCODEMP = M220.BDCODEMP)
      LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = M220.BDCODEMP AND SCP.BDCODSCP = M220.BDCODSCP AND SCP.BDREFEMP = M220.BDREFSOC)
      WHERE M220.BDVLRAJUPIS > 0
        --AND M220.BDCODEMP IN (SELECT EX.BDCODEMP
        --                     FROM TEMPRESAS EX
        --                     WHERE EX.BDCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
        --                        OR EX.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP))
        AND (((iif(:PRAJUSTESCP = true and :PRCODEMPSO > 0, true, false) = true) and (coalesce(SCP.BDCODEMPSCP, 0) = :PRCODEMP)) or
             ((iif(:PRAJUSTESCP = true and :PRCODEMPSO = 0, true, false) = true) and (coalesce(SCP.BDCODEMPSCP, 0) = 0)) or (:PRAJUSTESCP = false))
        --AND M220.BDREFERENCIA = :PRREFERENCIA
        AND (EXISTS(SELECT FIRST 1 X.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 X
                    WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M220.BDCODEMP)
                      AND X.BDREFERENCIA = M220.BDREFERENCIA
                      AND X.BDCODQUADRO = 19
                      AND X.BDCODPERIODO = 7
                      AND X.BDCODCSOCIAL = M220.BDCODCSOCIAL
                      AND COALESCE(X.BDTIPOPROD,0) = COALESCE(M220.BDTIPOPROD,0)
                      AND X.BDALIQ = M220.BDALIQPIS
                      AND X.BDRETIFICADORA = :PRRETIFICADORA));

      /* REGISTRO M225: DETALHAMENTO DOS AJUSTES DA CONTRIBUIÇÃO PARA O PIS/PASEP APURADA */
      INSERT INTO VEF_EMP_TBLOCOM225_M625 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEM25, BDCODCSTCOF, BDCODPLAPADRAO, BDCODTPLA, BDCODCSTPIS, BDDET_VALOR_AJ, BDDET_BC_CRED, BDDET_ALIQ, BDDT_OPER_AJ, BDDESC_AJ, BDINFO_COMPL, BDRETIFICADORA)
      SELECT 7 AS BDCODPERIODO, COALESCE(SCP.BDCODEMPSCP,M220.BDCODEMP) BDCODEMP, COALESCE(SCP.BDCODEMPSCP,COALESCE(EMP.BDCODMATRIZ, M220.BDCODEMP)) AS BDCODMATRIZ, 19 AS BDCODQUADRO, M220.BDREFERENCIA,
             (SELECT FIRST 1 X.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 X WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M220.BDCODEMP) AND X.BDREFERENCIA = M220.BDREFERENCIA AND X.BDCODQUADRO = 19 AND X.BDCODPERIODO = 7 AND X.BDCODCSOCIAL = M220.BDCODCSOCIAL AND COALESCE(X.BDTIPOPROD,0) = COALESCE(M220.BDTIPOPROD,0) AND X.BDALIQ = M220.BDALIQPIS AND X.BDRETIFICADORA = :PRRETIFICADORA) AS BDCHAVE,
             (SELECT FIRST 1 X.BDORDEM
              FROM VEF_EMP_TBLOCOM220_M620 X
              WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M220.BDCODEMP)
                AND X.BDREFERENCIA = M220.BDREFERENCIA
                AND X.BDCODQUADRO = 19
                AND X.BDCODPERIODO = 7
                AND X.BDRETIFICADORA = :PRRETIFICADORA
                AND X.BDNUM_DOC = M220.BDNUMERODOC
                AND X.DESCR_AJ  = M220.BDDESCRICAO
                AND X.BDDT_REF  = M220.BDDATAREF
                AND X.BDCHAVE = (SELECT FIRST 1 X.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 X
                                 WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M220.BDCODEMP)
                                   AND X.BDREFERENCIA = M220.BDREFERENCIA
                                   AND X.BDCODQUADRO = 19
                                   AND X.BDCODPERIODO = 7
                                   AND X.BDRETIFICADORA = :PRRETIFICADORA
                                   AND X.BDCODCSOCIAL = M220.BDCODCSOCIAL
                                   AND COALESCE(X.BDTIPOPROD,0) = COALESCE(M220.BDTIPOPROD,0)
                                   AND X.BDALIQ = M220.BDALIQPIS) ) AS BDORDEM,
             GETORDEMSEQUENCIAL_STR('M225.'||7||'.'||M220.BDCODEMP||'.'||COALESCE(EMP.BDCODMATRIZ, M220.BDCODEMP)||'.'||19||'.'||M220.BDREFERENCIA||'.'||SCP.BDCODEMPSCP||'.'||
             (SELECT FIRST 1 X.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 X WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M220.BDCODEMP) AND X.BDREFERENCIA = M220.BDREFERENCIA AND X.BDCODQUADRO = 19
             AND X.BDCODPERIODO = 7 AND X.BDCODCSOCIAL = M220.BDCODCSOCIAL AND COALESCE(X.BDTIPOPROD,0) = COALESCE(M220.BDTIPOPROD,0) AND X.BDALIQ = M220.BDALIQPIS AND X.BDRETIFICADORA = :PRRETIFICADORA)||'.'||
             (SELECT FIRST 1 X.BDORDEM FROM VEF_EMP_TBLOCOM220_M620 X WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M220.BDCODEMP) AND X.BDREFERENCIA = M220.BDREFERENCIA AND X.BDCODQUADRO = 19
             AND X.BDCODPERIODO = 7 AND X.BDRETIFICADORA = :PRRETIFICADORA AND X.BDNUM_DOC = M220.BDNUMERODOC AND X.DESCR_AJ  = M220.BDDESCRICAO AND X.BDDT_REF  = M220.BDDATAREF
             AND X.BDCHAVE = (SELECT FIRST 1 X.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 X WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M220.BDCODEMP) AND X.BDREFERENCIA = M220.BDREFERENCIA AND X.BDCODQUADRO = 19
                              AND X.BDCODPERIODO = 7
                              AND X.BDCODCSOCIAL = M220.BDCODCSOCIAL
                              AND COALESCE(X.BDTIPOPROD,0) = COALESCE(M220.BDTIPOPROD,0)
                              AND X.BDALIQ = M220.BDALIQPIS
                              AND X.BDRETIFICADORA = :PRRETIFICADORA)), :PRCODEMP)  AS BDORDEM25,

       /*      (SELECT COALESCE(MAX(X.BDORDEM25)+1, 1)
              FROM VEF_EMP_TBLOCOM225_M625 X
              WHERE X.BDCODEMP = M220.BDCODEMP
                AND X.BDREFERENCIA = M220.BDREFERENCIA
                AND X.BDCODQUADRO = 19
                AND X.BDCODPERIODO = 7
                AND X.BDCHAVE = (SELECT FIRST 1 X.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 X
                                 WHERE X.BDCODEMP = M220.BDCODEMP
                                   AND X.BDREFERENCIA = M220.BDREFERENCIA
                                   AND X.BDCODQUADRO = 19
                                   AND X.BDCODPERIODO = 7
                                   AND X.BDCODCSOCIAL = M220.BDCODCSOCIAL
                                   AND X.BDALIQ = M220.BDALIQPIS)
                AND X.BDORDEM = (SELECT FIRST 1 X.BDORDEM
                                 FROM VEF_EMP_TBLOCOM220_M620 X
                                 WHERE X.BDCODEMP = M220.BDCODEMP
                                   AND X.BDREFERENCIA = M220.BDREFERENCIA
                                   AND X.BDCODQUADRO = 19
                                   AND X.BDCODPERIODO = 7
                                   AND X.BDNUM_DOC = M220.BDNUMERODOC
                                   AND X.DESCR_AJ  = M220.BDDESCRICAO
                                   AND X.BDDT_REF  = M220.BDDATAREF
                                   AND X.BDCHAVE = (SELECT FIRST 1 X.BDCHAVE
                                                    FROM VEF_EMP_TBLOCOM210_M610 X
                                                    WHERE X.BDCODEMP = M220.BDCODEMP
                                                      AND X.BDREFERENCIA = M220.BDREFERENCIA
                                                      AND X.BDCODQUADRO = 19
                                                      AND X.BDCODPERIODO = 7
                                                      AND X.BDCODCSOCIAL = M220.BDCODCSOCIAL
                                                      AND X.BDALIQ = M220.BDALIQPIS)) ) AS BDORDEM25,*/

             M625.BDCODCSTCOF, M625.BDCODPLAPADRAO, M625.BDCODTPLA, M625.BDCODCSTPIS, M625.BDVALORPIS AS BDDET_VALOR_AJ, M625.BDBCPIS AS BDDET_BC_CRED, M625.BDALIQPIS AS BDDET_ALIQ,
             M625.BDDATAOPEPIS AS BDDT_OPER_AJ, M625.BDDESCRICAOAJU AS BDDESC_AJ, M625.BDINFCOMP AS BDINFO_COMPL,
             :PRRETIFICADORA
      FROM VEF_EMP_TAJUAPUPCM220620 M220
      JOIN VEF_EMP_TDETAJUM225625 M625 ON (M220.BDCODEMP = M625.BDCODEMP AND M220.BDCHAVE = M625.BDCHAVE)
      LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = M220.BDCODEMP AND SCP.BDCODSCP = M220.BDCODSCP AND SCP.BDREFEMP = M220.BDREFSOC)
      LEFT OUTER JOIN TEMPRESAS EMP ON (EMP.BDCODEMP = M220.BDCODEMP)
      WHERE M220.BDVLRAJUPIS > 0
        AND M220.BDCODEMP IN (SELECT EX.BDCODEMP
                             FROM TEMPRESAS EX
                             WHERE EX.BDCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
                                OR EX.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP))
        AND (((iif(:PRAJUSTESCP = true and :PRCODEMPSO > 0, true, false) = true) and (coalesce(SCP.BDCODEMPSCP, 0) = :PRCODEMP)) or
             ((iif(:PRAJUSTESCP = true and :PRCODEMPSO = 0, true, false) = true) and (coalesce(SCP.BDCODEMPSCP, 0) = 0)) or (:PRAJUSTESCP = false))
        AND M220.BDREFERENCIA = :PRREFERENCIA
        AND (EXISTS(SELECT FIRST 1 X.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 X
                    WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M220.BDCODEMP)
                      AND X.BDREFERENCIA = M220.BDREFERENCIA
                      AND X.BDCODQUADRO = 19
                      AND X.BDCODPERIODO = 7
                      AND X.BDCODCSOCIAL = M220.BDCODCSOCIAL
                      AND COALESCE(X.BDTIPOPROD,0) = COALESCE(M220.BDTIPOPROD,0)
                      AND X.BDALIQ = M220.BDALIQPIS
                      AND X.BDRETIFICADORA = :PRRETIFICADORA));

      /* REGISTRO M620: AJUSTES DA COFINS APURADA */
      INSERT INTO VEF_EMP_TBLOCOM220_M620 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODAJUEFDC, BDIND_AJ, BDVL_AJ, BDNUM_DOC, DESCR_AJ, BDDT_REF, BDVL_AJ_SALDO, BDVL_AJ_UTILIZADO, BDVL_AJ_REF, BDRETIFICADORA)
      SELECT 7 AS BDCODPERIODO, COALESCE(SCP.BDCODEMPSCP,M620.BDCODEMP) BDCODEMP, COALESCE(SCP.BDCODEMPSCP,COALESCE(EMP.BDCODMATRIZ, M620.BDCODEMP)) AS BDCODMATRIZ, 37 AS BDCODQUADRO, M620.BDREFERENCIA,
             (SELECT FIRST 1 X.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 X WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M620.BDCODEMP) AND X.BDREFERENCIA = M620.BDREFERENCIA AND X.BDCODQUADRO = 37 AND X.BDCODPERIODO = 7 AND X.BDCODCSOCIAL = M620.BDCODCSOCIAL AND COALESCE(X.BDTIPOPROD,0) = COALESCE(M620.BDTIPOPROD,0) AND X.BDALIQ = M620.BDALIQCOFINS AND X.BDRETIFICADORA = :PRRETIFICADORA) AS BDCHAVE,
              GETORDEMSEQUENCIAL_STR('M620.'||7||'.'||M620.BDCODEMP||'.'||COALESCE(EMP.BDCODMATRIZ, M620.BDCODEMP)||'.'||37||'.'||M620.BDREFERENCIA||'.'||SCP.BDCODEMPSCP||'.'||
              (SELECT FIRST 1 X.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 X WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M620.BDCODEMP) AND X.BDREFERENCIA = M620.BDREFERENCIA AND X.BDCODQUADRO = 37
              AND X.BDCODPERIODO = 7 AND X.BDCODCSOCIAL = M620.BDCODCSOCIAL AND COALESCE(X.BDTIPOPROD,0) = COALESCE(M620.BDTIPOPROD,0) AND X.BDALIQ = M620.BDALIQCOFINS AND X.BDRETIFICADORA = :PRRETIFICADORA), :PRCODEMP) AS BDORDEM,

             /*(SELECT COALESCE(MAX(X.BDORDEM)+1, 1) FROM VEF_EMP_TBLOCOM220_M620 X WHERE X.BDCODEMP = M620.BDCODEMP AND X.BDREFERENCIA = M620.BDREFERENCIA AND X.BDCODQUADRO = 37
             AND X.BDCODPERIODO = 7 AND X.BDCHAVE = (SELECT X.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 X WHERE X.BDCODEMP = M620.BDCODEMP AND X.BDREFERENCIA = M620.BDREFERENCIA AND X.BDCODQUADRO = 37
             AND X.BDCODPERIODO = 7 AND X.BDCODCSOCIAL = M620.BDCODCSOCIAL AND X.BDALIQ = M620.BDALIQCOFINS) ) AS BDORDEM,*/

             M620.BDCODAJUEFDC, M620.BDTIPOAJUSTE AS BDIND_AJ, M620.BDVLRAJUCOFINS AS BDVL_AJ, M620.BDNUMERODOC AS BDNUM_DOC, M620.BDDESCRICAO AS DESCR_AJ, M620.BDDATAREF AS BDDT_REF, IIF(M620.BDTIPOAJUSTE = 0, M620.BDVLRAJUCOFINS, 0), IIF(M620.BDTIPOAJUSTE = 1, M620.BDVLRAJUCOFINS, 0), IIF(M620.BDTIPOAJUSTE = 1, M620.BDREFERENCIA, NULL),
             :PRRETIFICADORA
      --FROM VEF_EMP_TAJUAPUPCM220620 M620 Alt.: #242771 - Busca os lancamentos e os registros que foram gerados...
      FROM (SELECT M620.BDCODEMP, M620.BDREFERENCIA, M620.BDCODCSOCIAL, M620.BDTIPOPROD, M620.BDALIQCOFINS, M620.BDCODAJUEFDC, M620.BDTIPOAJUSTE,
                   M620.BDVLRAJUCOFINS, M620.BDNUMERODOC, M620.BDDESCRICAO, M620.BDDATAREF, M620.BDCODSCP, M620.BDREFSOC
            FROM VEF_EMP_TAJUAPUPCM220620 M620
            WHERE M620.BDCODEMP IN (SELECT EX.BDCODEMP
                                    FROM TEMPRESAS EX
                                    WHERE EX.BDCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
                                       OR EX.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP))
              AND M620.BDREFERENCIA = :PRREFERENCIA
            UNION ALL
            SELECT M620.BDCODEMP, M620.BDREFERENCIA, M620.BDCODCSOCIAL, M620.BDTIPOPROD, M620.BDALIQCOFINS, M620.BDCODAJUEFDC, M620.BDTIPOAJUSTE,
                   M620.BDVLRAJUCOFINS, M620.BDNUMERODOC, M620.BDDESCRICAO, M620.BDDATAREF, M620.BDCODSCP, M620.BDREFSOC
            FROM TMP_VEF_EMP_TAJUAPUPCM220620_BLOCOM M620 -- Alt.: #242771 -- Registros automaticos do M220/620
            WHERE M620.BDCODEMP IN (SELECT EX.BDCODEMP
                                    FROM TEMPRESAS EX
                                    WHERE EX.BDCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
                                       OR EX.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP))
              AND M620.BDREFERENCIA = :PRREFERENCIA) M620
      LEFT OUTER JOIN TEMPRESAS EMP ON (EMP.BDCODEMP = M620.BDCODEMP)
      LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = M620.BDCODEMP AND SCP.BDCODSCP = M620.BDCODSCP AND SCP.BDREFEMP = M620.BDREFSOC)
      WHERE M620.BDVLRAJUCOFINS > 0
        --AND M620.BDCODEMP IN (SELECT EX.BDCODEMP
        --                     FROM TEMPRESAS EX
        --                     WHERE EX.BDCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
        --                        OR EX.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP))
        AND (((iif(:PRAJUSTESCP = true and :PRCODEMPSO > 0, true, false) = true) and (coalesce(SCP.BDCODEMPSCP, 0) = :PRCODEMP)) or
             ((iif(:PRAJUSTESCP = true and :PRCODEMPSO = 0, true, false) = true) and (coalesce(SCP.BDCODEMPSCP, 0) = 0)) or (:PRAJUSTESCP = false))
        --AND M620.BDREFERENCIA = :PRREFERENCIA
        AND (EXISTS(SELECT X.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 X
                    WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M620.BDCODEMP)
                      AND X.BDREFERENCIA = M620.BDREFERENCIA
                      AND X.BDCODQUADRO = 37
                      AND X.BDCODPERIODO = 7
                      AND X.BDCODCSOCIAL = M620.BDCODCSOCIAL
                      AND COALESCE(X.BDTIPOPROD,0) = COALESCE(M620.BDTIPOPROD,0)
                      AND X.BDALIQ = M620.BDALIQCOFINS
                      AND X.BDRETIFICADORA = :PRRETIFICADORA));

      /* REGISTRO M625: DETALHAMENTO DOS AJUSTES DA COFINS APURADA */
      INSERT INTO VEF_EMP_TBLOCOM225_M625 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEM25, BDCODCSTCOF, BDCODPLAPADRAO, BDCODTPLA, BDCODCSTPIS, BDDET_VALOR_AJ, BDDET_BC_CRED, BDDET_ALIQ, BDDT_OPER_AJ, BDDESC_AJ, BDINFO_COMPL, BDRETIFICADORA)
      SELECT 7 AS BDCODPERIODO, COALESCE(SCP.BDCODEMPSCP,M620.BDCODEMP) BDCODEMP , COALESCE(SCP.BDCODEMPSCP,COALESCE(EMP.BDCODMATRIZ, M620.BDCODEMP)) AS BDCODMATRIZ, 37 AS BDCODQUADRO, M620.BDREFERENCIA,
             (SELECT X.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 X WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M620.BDCODEMP) AND X.BDREFERENCIA = M620.BDREFERENCIA AND X.BDCODQUADRO = 37 AND X.BDCODPERIODO = 7 AND X.BDCODCSOCIAL = M620.BDCODCSOCIAL AND COALESCE(X.BDTIPOPROD,0) = COALESCE(M620.BDTIPOPROD,0) AND X.BDALIQ = M620.BDALIQCOFINS AND X.BDRETIFICADORA = :PRRETIFICADORA) AS BDCHAVE,
             (SELECT FIRST 1 X.BDORDEM
              FROM VEF_EMP_TBLOCOM220_M620 X
              WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M620.BDCODEMP)
                AND X.BDREFERENCIA = M620.BDREFERENCIA
                AND X.BDCODQUADRO = 37
                AND X.BDCODPERIODO = 7
                AND X.BDRETIFICADORA = :PRRETIFICADORA
                AND X.BDNUM_DOC = M620.BDNUMERODOC
                AND X.DESCR_AJ  = M620.BDDESCRICAO
                AND X.BDDT_REF  = M620.BDDATAREF
                AND X.BDCHAVE = (SELECT X.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 X
                                 WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M620.BDCODEMP)
                                   AND X.BDREFERENCIA = M620.BDREFERENCIA
                                   AND X.BDCODQUADRO = 37
                                   AND X.BDCODPERIODO = 7
                                   AND X.BDRETIFICADORA = :PRRETIFICADORA
                                   AND X.BDCODCSOCIAL = M620.BDCODCSOCIAL
                                   AND COALESCE(X.BDTIPOPROD,0) = COALESCE(M620.BDTIPOPROD,0)
                                   AND X.BDALIQ = M620.BDALIQCOFINS) ) AS BDORDEM,
             GETORDEMSEQUENCIAL_STR('M625.'||7||'.'||M620.BDCODEMP||'.'||COALESCE(EMP.BDCODMATRIZ, M620.BDCODEMP)||'.'||37||'.'||M620.BDREFERENCIA||'.'||SCP.BDCODEMPSCP||'.'||
            (SELECT X.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 X WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M620.BDCODEMP) AND X.BDREFERENCIA = M620.BDREFERENCIA AND X.BDCODQUADRO = 37
            AND X.BDCODPERIODO = 7 AND X.BDCODCSOCIAL = M620.BDCODCSOCIAL AND COALESCE(X.BDTIPOPROD,0) = COALESCE(M620.BDTIPOPROD,0) AND X.BDALIQ = M620.BDALIQCOFINS AND X.BDRETIFICADORA = :PRRETIFICADORA)||'.'||
            (SELECT FIRST 1 X.BDORDEM FROM VEF_EMP_TBLOCOM220_M620 X WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M620.BDCODEMP) AND X.BDREFERENCIA = M620.BDREFERENCIA AND X.BDCODQUADRO = 37
            AND X.BDCODPERIODO = 7 AND X.BDRETIFICADORA = :PRRETIFICADORA AND X.BDNUM_DOC = M620.BDNUMERODOC AND X.DESCR_AJ  = M620.BDDESCRICAO AND X.BDDT_REF  = M620.BDDATAREF
            AND X.BDCHAVE = (SELECT X.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 X WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M620.BDCODEMP) AND X.BDREFERENCIA = M620.BDREFERENCIA
                           AND X.BDCODQUADRO = 37 AND X.BDCODPERIODO = 7 AND X.BDCODCSOCIAL = M620.BDCODCSOCIAL AND COALESCE(X.BDTIPOPROD,0) = COALESCE(M620.BDTIPOPROD,0) AND X.BDALIQ = M620.BDALIQCOFINS AND X.BDRETIFICADORA = :PRRETIFICADORA)), :PRCODEMP)  AS BDORDEM25,

           /*  (SELECT COALESCE(MAX(X.BDORDEM25)+1, 1)
              FROM VEF_EMP_TBLOCOM225_M625 X
              WHERE X.BDCODEMP = M620.BDCODEMP
                AND X.BDREFERENCIA = M620.BDREFERENCIA
                AND X.BDCODQUADRO = 37
                AND X.BDCODPERIODO = 7
                AND X.BDCHAVE = (SELECT X.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM210_M610 X
                                 WHERE X.BDCODEMP = M620.BDCODEMP
                                   AND X.BDREFERENCIA = M620.BDREFERENCIA
                                   AND X.BDCODQUADRO = 37
                                   AND X.BDCODPERIODO = 7
                                   AND X.BDCODCSOCIAL = M620.BDCODCSOCIAL
                                   AND X.BDALIQ = M620.BDALIQCOFINS)
                AND X.BDORDEM = (SELECT FIRST 1 X.BDORDEM
                                 FROM VEF_EMP_TBLOCOM220_M620 X
                                 WHERE X.BDCODEMP = M620.BDCODEMP
                                   AND X.BDREFERENCIA = M620.BDREFERENCIA
                                   AND X.BDCODQUADRO = 37
                                   AND X.BDCODPERIODO = 7
                                   AND X.BDNUM_DOC = M620.BDNUMERODOC
                                   AND X.DESCR_AJ  = M620.BDDESCRICAO
                                   AND X.BDDT_REF  = M620.BDDATAREF
                                   AND X.BDCHAVE = (SELECT X.BDCHAVE
                                                    FROM VEF_EMP_TBLOCOM210_M610 X
                                                    WHERE X.BDCODEMP = M620.BDCODEMP
                                                      AND X.BDREFERENCIA = M620.BDREFERENCIA
                                                      AND X.BDCODQUADRO = 37
                                                      AND X.BDCODPERIODO = 7
                                                      AND X.BDCODCSOCIAL = M620.BDCODCSOCIAL
                                                      AND X.BDALIQ = M620.BDALIQCOFINS)) ) AS BDORDEM25,   */
             M625.BDCODCSTCOF, M625.BDCODPLAPADRAO, M625.BDCODTPLA, M625.BDCODCSTPIS, M625.BDVALORCOFINS AS BDDET_VALOR_AJ, M625.BDBCCOFINS AS BDDET_BC_CRED, M625.BDALIQCOFINS AS BDDET_ALIQ,
             M625.BDDATAOPECOFINS AS BDDT_OPER_AJ, M625.BDDESCRICAOAJU AS BDDESC_AJ, M625.BDINFCOMP AS BDINFO_COMPL, :PRRETIFICADORA
      FROM VEF_EMP_TAJUAPUPCM220620 M620
      JOIN VEF_EMP_TDETAJUM225625 M625 ON (M620.BDCODEMP = M625.BDCODEMP AND M620.BDCHAVE = M625.BDCHAVE)
      LEFT OUTER JOIN TEMPRESAS EMP ON (EMP.BDCODEMP = M620.BDCODEMP)
      LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = M620.BDCODEMP AND SCP.BDCODSCP = M620.BDCODSCP AND SCP.BDREFEMP = M620.BDREFSOC)
      WHERE M620.BDVLRAJUCOFINS > 0
        AND M620.BDCODEMP IN (SELECT EX.BDCODEMP
                             FROM TEMPRESAS EX
                             WHERE EX.BDCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
                                OR EX.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP))
        AND (((iif(:PRAJUSTESCP = true and :PRCODEMPSO > 0, true, false) = true) and (coalesce(SCP.BDCODEMPSCP, 0) = :PRCODEMP)) or
             ((iif(:PRAJUSTESCP = true and :PRCODEMPSO = 0, true, false) = true) and (coalesce(SCP.BDCODEMPSCP, 0) = 0)) or (:PRAJUSTESCP = false))
        AND M620.BDREFERENCIA = :PRREFERENCIA
        AND (EXISTS(SELECT X.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 X
                    WHERE X.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,M620.BDCODEMP)
                      AND X.BDREFERENCIA = M620.BDREFERENCIA
                      AND X.BDCODQUADRO = 37
                      AND X.BDCODPERIODO = 7
                      AND X.BDRETIFICADORA = :PRRETIFICADORA
                      AND X.BDCODCSOCIAL = M620.BDCODCSOCIAL
                      AND COALESCE(X.BDTIPOPROD,0) = COALESCE(M620.BDTIPOPROD,0)
                      AND X.BDALIQ = M620.BDALIQCOFINS));
    END

    /* BLOCO M - M220/620 - CONTROLE DE CRÉDITOS #149138 #155482 - CARLOS XAVIER 10/11/21 */
    IF (:WCONTROLCRED = 'TRUE') THEN
      BEGIN
        :WBDCODEMP210 = null;
        :WSQL_AJ = '';
        if (:PRAJUSTESCP = 'TRUE') then
          begin
           :WSQL_AJ = 'SELECT COALESCE(X.BDVL_CONT_APUR,0), COALESCE(X.BDVL_AJUS_ACRES,0), COALESCE(X.BDVL_AJUS_REDUC,0),';
           :WSQL_AJ = :WSQL_AJ||' COALESCE(X.BDVL_CONT_DIFER_ANT,0), COALESCE(X.BDVL_CONT_DIFER,0), X.BDALIQ, X.BDCODCSOCIAL, X.BDTIPOPROD, X.BDCHAVE,';
           :WSQL_AJ = :WSQL_AJ||' COALESCE(SCP.BDCODEMPSCP, X.BDCODEMP) BDCODEMP, X.BDCODMATRIZ, SCP.BDCODSCP, SCP.BDREFEMP FROM VEF_EMP_TBLOCOM210_M610 X';
           --:WSQL_AJ = :WSQL_AJ||' LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP ='||:PRCODEMP||')';
           :WSQL_AJ = :WSQL_AJ||' LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP in(SELECT ex.BDCODEMP FROM TEMPRESAS ex WHERE ex.BDCODEMP = '||:prCODEMP||' OR ex.BDCODMATRIZ = '||:prCODEMP||'))';
           :WSQL_AJ = :WSQL_AJ||' LEFT OUTER JOIN TEMPRESAS EMP ON (EMP.BDCODEMP = X.BDCODEMP)';
           :WSQL_AJ = :WSQL_AJ||' WHERE X.BDCODEMP IN (SELECT EX.BDCODEMP FROM TEMPRESAS EX WHERE EX.BDCODEMP = SCP.bdcodempscp OR EX.BDCODMATRIZ = SCP.bdcodempscp) AND X.BDCODQUADRO = 19 AND ';
           :WSQL_AJ = :WSQL_AJ||' X.BDREFERENCIA ='||:PRREFERENCIA||' AND X.BDRETIFICADORA = '||:PRRETIFICADORA;

           :WSQL_AJ = :WSQL_AJ||' UNION ALL';
          end

           :WSQL_AJ = :WSQL_AJ||' SELECT COALESCE(X.BDVL_CONT_APUR,0), COALESCE(X.BDVL_AJUS_ACRES,0), COALESCE(X.BDVL_AJUS_REDUC,0), ';
           :WSQL_AJ = :WSQL_AJ||'COALESCE(X.BDVL_CONT_DIFER_ANT,0), COALESCE(X.BDVL_CONT_DIFER,0), X.BDALIQ, X.BDCODCSOCIAL, X.BDTIPOPROD, X.BDCHAVE, X.BDCODEMP,';
           :WSQL_AJ = :WSQL_AJ||'X.BDCODMATRIZ, null BDCODSCP, null BDREFEMP FROM VEF_EMP_TBLOCOM210_M610 X WHERE ';
           :WSQL_AJ = :WSQL_AJ||'(X.BDCODEMP ='||:PRCODEMP||' OR X.BDCODMATRIZ ='||:PRCODEMP||') AND X.BDCODQUADRO = 19 AND ';
           :WSQL_AJ = :WSQL_AJ||'X.BDREFERENCIA ='||:PRREFERENCIA||' AND X.BDRETIFICADORA = '||:PRRETIFICADORA;

         LOOPA:   /* PIS */
        FOR EXECUTE STATEMENT :WSQL_AJ INTO :WVALORCONT_PIS, :WBDVL_AJUS_ACRES, :WBDVL_AJUS_REDUC, :WBDVL_CONT_DIFER_ANT,
          :WBDVL_CONT_DIFER, :WBDALIQ, :WBDCODCSOCIAL, :WBDTIPOPROD, :WBDCHAVE210, :WBDCODEMP210, :WBDCODMATRIZ210, :WBDCODSCP, :WBDREFEMP
          DO
            BEGIN

            IF (:WBDCODEMP210 is null) then
              :WBDCODEMP210 = :PRCODEMP;

           :WSQL_AJ_2 = 'SELECT M220.BDORDEM, M220.BDCODMATRIZ, M220.BDVL_AJ_SALDO, M220.BDCODPERIODO, M220.BDCODQUADRO, M220.BDCHAVE, M220.BDVL_AJ_REF, ';
           :WSQL_AJ_2 = :WSQL_AJ_2||'M220.BDREFERENCIA, M220.BDDT_REF, M220.BDVL_AJ_UTILIZADO, M210.BDALIQ, M210.BDCODCSOCIAL, M210.BDTIPOPROD FROM VEF_EMP_TBLOCOM220_M620 M220 ';
           :WSQL_AJ_2 = :WSQL_AJ_2||'left outer join VEF_EMP_TBLOCOM210_M610 M210 on';
           :WSQL_AJ_2 = :WSQL_AJ_2||'(m210.bdcodquadro = m220.bdcodquadro and m210.bdcodperiodo = m220.bdcodperiodo and m210.bdcodemp = m220.bdcodemp ';
           :WSQL_AJ_2 = :WSQL_AJ_2||'and m210.bdcodmatriz = m220.bdcodmatriz and m210.bdreferencia = m220.bdreferencia and M210.bdchave = m220.bdchave AND M220.BDRETIFICADORA = M210.BDRETIFICADORA)';
           :WSQL_AJ_2 = :WSQL_AJ_2||'WHERE (M220.BDCODEMP = '||:WBDCODEMP210||') AND M220.BDIND_AJ = 0 AND M220.BDCODQUADRO = 19 AND M220.BDVL_AJ_SALDO > 0 AND ';
           :WSQL_AJ_2 = :WSQL_AJ_2||'M220.BDREFERENCIA <='||:PRREFERENCIA||' AND M220.BDRETIFICADORA = '||:PRRETIFICADORA;
           :WSQL_AJ_2 = :WSQL_AJ_2||' AND M210.BDALIQ ='||:WBDALIQ||' AND M210.BDCODCSOCIAL = '||:WBDCODCSOCIAL||' AND COALESCE(M210.BDTIPOPROD,0) = '||:WBDTIPOPROD||' AND M210.BDCHAVE = '||:WBDCHAVE210;
           :WSQL_AJ_2 = IIF(:WCREDANTERIOR = 'TRUE', WSQL_AJ_2||' ORDER BY BDREFERENCIA ASC', WSQL_AJ_2||' ORDER BY BDREFERENCIA DESC');

          LOOPB:
          FOR EXECUTE STATEMENT :WSQL_AJ_2 INTO :WORDEM_AJ, :WBDCODMATRIZ, :WBDVL_AJ_SALDO, :WBDCODPERIODO, :WBDCODQUADRO, :WBDCHAVE, :BDVL_AJ_REF, :WBDREFLAN220, :WBDDT_REF, :WBDLV_AJ_UTILIZADO, :WBDALIQ_220, :WBDCODCSOCIAL_220, :WBDTIPOPROD_220
              DO
                BEGIN
                   :WVALORCONT_PIS = ((:WVALORCONT_PIS + :WBDVL_AJUS_ACRES + WBDVL_CONT_DIFER_ANT) - WBDVL_CONT_DIFER);
                   IF ((:WBDVL_AJ_SALDO > :WVALORCONT_PIS) AND (:WVALORCONT_PIS > 0) AND (:WBDVL_AJ_SALDO > 0)) THEN
                      BEGIN
                         /* SE O SALDO JÁ FOI USADO OU SUA REFERÊNCIA É DIFERENTE DA APURAÇÃO, ATUALIZA PARA O PRIMEIRO DIA DO MÊS REF*/
                        IF ((:WBDLV_AJ_UTILIZADO > 0) OR (:WBDREFLAN220 <> :PRREFERENCIA))  THEN
                            BEGIN
                                :WBDDT_REF = SUBSTRING(:PRREFERENCIA FROM 5 FOR 6)||'/01/'||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4);
                            END 

                         UPDATE VEF_EMP_TBLOCOM210_M610 X
                            SET X.BDVL_CONT_PER = 0 WHERE
                            X.BDCODEMP = :WBDCODEMP210 AND
                            X.BDCODQUADRO = 19 AND
                            X.BDREFERENCIA = :PRREFERENCIA and
                            x.bdchave = :WBDCHAVE210 and
                            X.bdaliq = :WBDALIQ and
                            X.bdcodcsocial = :WBDCODCSOCIAL AND
                            COALESCE(X.BDTIPOPROD,0) = COALESCE(:WBDTIPOPROD,0) AND
                            X.BDRETIFICADORA = :PRRETIFICADORA;
    
                         UPDATE VEF_EMP_TBLOCOM220_M620 X
                            SET X.BDVL_AJ_SALDO = (X.BDVL_AJ_SALDO - :WVALORCONT_PIS),
                            X.BDVL_AJ_UTILIZADO = (:WVALORCONT_PIS),
                            X.BDVL_AJ_REF = (:PRREFERENCIA)
                            WHERE
                            X.BDCODEMP = :WBDCODEMP210
                            AND X.BDCODQUADRO = 19
                            AND X.BDORDEM = :WORDEM_AJ
                            AND X.BDREFERENCIA = :WBDREFLAN220
                            AND X.BDVL_AJ_SALDO > 0
                            AND X.BDRETIFICADORA = :PRRETIFICADORA;

                            /* PREENCHE TABELA DE CONTROLE DE CRÉDITO, USADO NAS EXPORTAÇÕES E TREEVIEW */
                       UPDATE OR INSERT INTO VEF_EMP_TCREDITO_M220_M620 (BDCODPERIODO, BDCODMATRIZ, BDCODEMP, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDREFLANM220, BDVL_AJ_UTILIZADO, BDDT_REF, BDVL_AJ_SALDO_REF, BDALIQ, BDCODCSOCIAL, BDTIPOPROD, BDCODSCP, BDRETIFICADORA)
                       VALUES (:WBDCODPERIODO, :WBDCODMATRIZ210, :WBDCODEMP210, 19, :PRREFERENCIA, :WBDCHAVE, :WORDEM_AJ, :WBDREFLAN220, :WVALORCONT_PIS, :WBDDT_REF, :WBDVL_AJ_SALDO, :WBDALIQ, :WBDCODCSOCIAL,  :WBDTIPOPROD, :WBDCODSCP, :PRRETIFICADORA)
                       MATCHING (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDCHAVE, BDORDEM, BDVL_AJ_SALDO_REF, BDRETIFICADORA);

    
                            :WVALORCONT_PIS = :WVALORCONT_PIS - :WBDVL_AJ_SALDO;
    
                         UPDATE VEF_EMP_TBLOCOM210_M610 X
                            SET X.BDVL_AJUS_REDUC = (X.BDVL_AJUS_REDUC - ABS(:WVALORCONT_PIS)) WHERE
                            X.BDCODEMP = :WBDCODEMP210 AND
                            X.BDCODQUADRO = 19 AND
                            X.BDREFERENCIA = :PRREFERENCIA AND
                            X.bdchave = :WBDCHAVE210 and
                            X.bdaliq = :WBDALIQ and
                            X.bdcodcsocial = :WBDCODCSOCIAL AND
                            COALESCE(X.BDTIPOPROD,0) = COALESCE(:WBDTIPOPROD,0) AND
                            X.BDRETIFICADORA = :PRRETIFICADORA;
                           CONTINUE LOOPB;

                END

                   IF ((:WVALORCONT_PIS >= :WBDVL_AJ_SALDO) AND (:WVALORCONT_PIS > 0) AND (:WBDVL_AJ_SALDO > 0)) THEN
                      BEGIN
                         /* SE O SALDO JÁ FOI USADO OU SUA REFERÊNCIA É DIFERENTE DA APURAÇÃO, ATUALIZA PARA O PRIMEIRO DIA DO MÊS REF*/
                        IF ((:WBDLV_AJ_UTILIZADO > 0) OR (:WBDREFLAN220 <> :PRREFERENCIA)) THEN
                            BEGIN
                                :WBDDT_REF = SUBSTRING(:PRREFERENCIA FROM 5 FOR 6)||'/01/'||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4);
                            END

                        :WVALORCONT_PIS = :WVALORCONT_PIS - :WBDVL_AJ_SALDO;

                        UPDATE VEF_EMP_TBLOCOM220_M620 X
                            SET X.BDVL_AJ_UTILIZADO = (:WBDVL_AJ_SALDO),
                            X.BDVL_AJ_SALDO = (0)
                            WHERE X.BDCODEMP = :WBDCODEMP210
                            AND X.BDCODQUADRO = 19
                            AND X.BDORDEM = :WORDEM_AJ
                            AND X.BDREFERENCIA = :WBDREFLAN220
                            AND X.BDVL_AJ_SALDO > 0
                            AND X.BDRETIFICADORA = :PRRETIFICADORA;

                     UPDATE OR INSERT INTO VEF_EMP_TCREDITO_M220_M620
                     (BDCODPERIODO, BDCODMATRIZ, BDCODEMP, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDREFLANM220, BDVL_AJ_UTILIZADO, BDDT_REF, BDVL_AJ_SALDO_REF, BDALIQ, BDCODCSOCIAL, BDTIPOPROD, BDCODSCP, BDRETIFICADORA)
                     VALUES(:WBDCODPERIODO, :WBDCODMATRIZ210, :WBDCODEMP210, 19, :PRREFERENCIA, :WBDCHAVE, :WORDEM_AJ, :WBDREFLAN220, :WBDVL_AJ_SALDO, :WBDDT_REF, :WBDVL_AJ_SALDO, :WBDALIQ, :WBDCODCSOCIAL, :WBDTIPOPROD, :WBDCODSCP, :PRRETIFICADORA)
                     MATCHING (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDCHAVE, BDORDEM, BDVL_AJ_SALDO_REF, BDRETIFICADORA);

                        UPDATE VEF_EMP_TBLOCOM210_M610 X
                            SET X.BDVL_CONT_PER = (:WVALORCONT_PIS) WHERE
                            X.BDCODEMP = :WBDCODEMP210 AND
                            X.BDCODQUADRO = 19 AND
                            X.BDREFERENCIA = :PRREFERENCIA AND
                            X.bdchave = :WBDCHAVE210 and
                            X.bdaliq = :WBDALIQ and
                            X.bdcodcsocial = :WBDCODCSOCIAL AND
                            COALESCE(X.BDTIPOPROD,0) = COALESCE(:WBDTIPOPROD,0) AND
                            X.BDRETIFICADORA = :PRRETIFICADORA;

                        CONTINUE LOOPB;
                      END
                END


          IF ((SELECT X.BDVL_CONT_PER FROM VEF_EMP_TBLOCOM210_M610 X WHERE X.BDRETIFICADORA = :PRRETIFICADORA AND
            X.BDCODEMP = :WBDCODEMP210 AND X.bdcodmatriz = :WBDCODMATRIZ AND X.BDCODQUADRO = 19 AND X.BDREFERENCIA = :PRREFERENCIA and X.bdchave = :WBDCHAVE210 and
                            X.bdaliq = :WBDALIQ and
                            X.bdcodcsocial = :WBDCODCSOCIAL and
                            COALESCE(X.BDTIPOPROD,0) = COALESCE(:WBDTIPOPROD,0)) >= 0) THEN
            BEGIN

                SELECT SUM(BDVL_AJ_UTILIZADO) FROM VEF_EMP_TCREDITO_M220_M620
                    WHERE BDCODEMP = :WBDCODEMP210 AND BDCODQUADRO = 19 AND BDREFERENCIA = :PRREFERENCIA AND BDALIQ = :WBDALIQ AND BDCODCSOCIAL = :WBDCODCSOCIAL AND COALESCE(BDTIPOPROD,0) = COALESCE(:WBDTIPOPROD,0) AND BDRETIFICADORA = :PRRETIFICADORA
                    INTO :WBDLV_AJ_UTILIZADO;

                UPDATE VEF_EMP_TBLOCOM210_M610 X
                    SET X.BDVL_AJUS_REDUC = (:WBDLV_AJ_UTILIZADO) WHERE
                    X.BDCODEMP = :WBDCODEMP210 AND
                    X.BDCODQUADRO = 19 AND
                    X.BDREFERENCIA = :PRREFERENCIA AND
                    x.bdchave = :WBDCHAVE210 and
                    X.bdaliq = :WBDALIQ and
                    X.bdcodcsocial = :WBDCODCSOCIAL AND
                    COALESCE(X.BDTIPOPROD,0) = COALESCE(:WBDTIPOPROD,0) AND
                    X.BDRETIFICADORA = :PRRETIFICADORA;

                UPDATE VEF_EMP_TBLOCOM210_M610 X
                   SET BDVL_CONT_PER = (COALESCE(X.BDVL_CONT_APUR,0) + COALESCE(X.BDVL_AJUS_ACRES,0) - COALESCE(X.BDVL_AJUS_REDUC,0) + COALESCE(X.BDVL_CONT_DIFER_ANT,0) - COALESCE(X.BDVL_CONT_DIFER,0)) WHERE
                    X.BDCODEMP = :WBDCODEMP210 AND
                    X.BDCODQUADRO = 19 AND
                    X.BDREFERENCIA = :PRREFERENCIA and
                    x.bdchave = :WBDCHAVE210 and
                    X.bdaliq = :WBDALIQ and
                    X.bdcodcsocial = :WBDCODCSOCIAL AND
                    COALESCE(X.BDTIPOPROD,0) = COALESCE(:WBDTIPOPROD,0) AND
                    X.BDRETIFICADORA = :PRRETIFICADORA;
            END


              END

                /* COFINS - EXECUTA A MESMA ROTINA DO PIS, PORÉM PARA O QUADRO 37 */
        :WBDCODEMP210 = null;
        :WSQL_AJ = '';
        :WSQL_AJ_2 = '';
        if (:PRAJUSTESCP = 'TRUE') then
          begin
           :WSQL_AJ = 'SELECT COALESCE(X.BDVL_CONT_APUR,0), COALESCE(X.BDVL_AJUS_ACRES,0), COALESCE(X.BDVL_AJUS_REDUC,0),';
           :WSQL_AJ = :WSQL_AJ||' COALESCE(X.BDVL_CONT_DIFER_ANT,0), COALESCE(X.BDVL_CONT_DIFER,0), X.BDALIQ, X.BDCODCSOCIAL, X.BDTIPOPROD, X.BDCHAVE,';
           :WSQL_AJ = :WSQL_AJ||' COALESCE(SCP.BDCODEMPSCP, X.BDCODEMP) BDCODEMP, X.BDCODMATRIZ, SCP.BDCODSCP, SCP.BDREFEMP FROM VEF_EMP_TBLOCOM210_M610 X';
           --:WSQL_AJ = :WSQL_AJ||' LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP ='||:PRCODEMP||')';
           :WSQL_AJ = :WSQL_AJ||' LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP in(SELECT ex.BDCODEMP FROM TEMPRESAS ex WHERE ex.BDCODEMP = '||:prCODEMP||' OR ex.BDCODMATRIZ = '||:prCODEMP||'))';
           :WSQL_AJ = :WSQL_AJ||' LEFT OUTER JOIN TEMPRESAS EMP ON (EMP.BDCODEMP = X.BDCODEMP)';
           :WSQL_AJ = :WSQL_AJ||' WHERE X.BDCODEMP IN (SELECT EX.BDCODEMP FROM TEMPRESAS EX WHERE EX.BDCODEMP = SCP.bdcodempscp OR EX.BDCODMATRIZ = SCP.bdcodempscp) AND X.BDCODQUADRO = 37 AND ';
           :WSQL_AJ = :WSQL_AJ||' X.BDREFERENCIA ='||:PRREFERENCIA||' AND X.BDRETIFICADORA = '||:PRRETIFICADORA;

           :WSQL_AJ = :WSQL_AJ||' UNION ALL';
          end

           :WSQL_AJ = :WSQL_AJ||' SELECT COALESCE(X.BDVL_CONT_APUR,0), COALESCE(X.BDVL_AJUS_ACRES,0), COALESCE(X.BDVL_AJUS_REDUC,0), ';
           :WSQL_AJ = :WSQL_AJ||'COALESCE(X.BDVL_CONT_DIFER_ANT,0), COALESCE(X.BDVL_CONT_DIFER,0), X.BDALIQ, X.BDCODCSOCIAL, X.BDTIPOPROD, X.BDCHAVE, X.BDCODEMP,';
           :WSQL_AJ = :WSQL_AJ||'X.BDCODMATRIZ, null BDCODSCP, null BDREFEMP FROM VEF_EMP_TBLOCOM210_M610 X WHERE ';
           :WSQL_AJ = :WSQL_AJ||'(X.BDCODEMP ='||:PRCODEMP||' OR X.BDCODMATRIZ ='||:PRCODEMP||') AND X.BDCODQUADRO = 37 AND ';
           :WSQL_AJ = :WSQL_AJ||'X.BDREFERENCIA ='||:PRREFERENCIA||' AND X.BDRETIFICADORA = '||:PRRETIFICADORA;

         LOOPC:   /* COFINS */
        FOR EXECUTE STATEMENT :WSQL_AJ INTO :WVALORCONT_COFINS, :WBDVL_AJUS_ACRES, :WBDVL_AJUS_REDUC, :WBDVL_CONT_DIFER_ANT,
          :WBDVL_CONT_DIFER, :WBDALIQ, :WBDCODCSOCIAL, :wBDTIPOPROD, :WBDCHAVE210, :WBDCODEMP210, :WBDCODMATRIZ210, :WBDCODSCP, :WBDREFEMP
          DO
            BEGIN

            IF (:WBDCODEMP210 is null) then
              :WBDCODEMP210 = :PRCODEMP;

           :WSQL_AJ_2 = ' SELECT M220.BDORDEM, M220.BDCODMATRIZ, M220.BDVL_AJ_SALDO, M220.BDCODPERIODO, M220.BDCODQUADRO, M220.BDCHAVE, M220.BDVL_AJ_REF, ';
           :WSQL_AJ_2 = :WSQL_AJ_2||'M220.BDREFERENCIA, M220.BDDT_REF, M220.BDVL_AJ_UTILIZADO, M210.BDALIQ, M210.BDCODCSOCIAL, M210.BDTIPOPROD FROM VEF_EMP_TBLOCOM220_M620 M220 ';
           :WSQL_AJ_2 = :WSQL_AJ_2||'left outer join VEF_EMP_TBLOCOM210_M610 M210 on';
           :WSQL_AJ_2 = :WSQL_AJ_2||'(m210.bdcodquadro = m220.bdcodquadro and m210.bdcodperiodo = m220.bdcodperiodo and m210.bdcodemp = m220.bdcodemp ';
           :WSQL_AJ_2 = :WSQL_AJ_2||'and m210.bdcodmatriz = m220.bdcodmatriz and m210.bdreferencia = m220.bdreferencia and M210.bdchave = m220.bdchave AND M220.BDRETIFICADORA = M210.BDRETIFICADORA)';
           :WSQL_AJ_2 = :WSQL_AJ_2||'WHERE (M220.BDCODEMP = '||:WBDCODEMP210||') AND M220.BDIND_AJ = 0 AND M220.BDCODQUADRO = 37 AND M220.BDVL_AJ_SALDO > 0 AND ';
           :WSQL_AJ_2 = :WSQL_AJ_2||'M220.BDREFERENCIA <='||:PRREFERENCIA||' AND M220.BDRETIFICADORA = '||:PRRETIFICADORA;
           :WSQL_AJ_2 = :WSQL_AJ_2||' AND M210.BDALIQ ='||:WBDALIQ||' AND M210.BDCODCSOCIAL = '||:WBDCODCSOCIAL||' AND M210.BDTIPOPROD = '||:WBDTIPOPROD||' AND M210.BDCHAVE = '||:WBDCHAVE210;
           :WSQL_AJ_2 = IIF(:WCREDANTERIOR = 'TRUE', WSQL_AJ_2||' ORDER BY BDREFERENCIA ASC', WSQL_AJ_2||' ORDER BY BDREFERENCIA DESC');

          LOOPD:
          FOR EXECUTE STATEMENT :WSQL_AJ_2 INTO :WORDEM_AJ, :WBDCODMATRIZ, :WBDVL_AJ_SALDO, :WBDCODPERIODO, :WBDCODQUADRO, :WBDCHAVE, :BDVL_AJ_REF, :WBDREFLAN220, :WBDDT_REF, :WBDLV_AJ_UTILIZADO, :WBDALIQ_220, :WBDCODCSOCIAL_220, :WBDTIPOPROD_220
              DO
                BEGIN
                   :WVALORCONT_COFINS = ((:WVALORCONT_COFINS + :WBDVL_AJUS_ACRES + WBDVL_CONT_DIFER_ANT) - WBDVL_CONT_DIFER);
                   IF ((:WBDVL_AJ_SALDO > :WVALORCONT_COFINS) AND (:WVALORCONT_COFINS > 0) AND (:WBDVL_AJ_SALDO > 0)) THEN
                      BEGIN
                         /* SE O SALDO JÁ FOI USADO OU SUA REFERÊNCIA É DIFERENTE DA APURAÇÃO, ATUALIZA PARA O PRIMEIRO DIA DO MÊS REF*/
                        IF ((:WBDLV_AJ_UTILIZADO > 0) OR (:WBDREFLAN220 <> :PRREFERENCIA))  THEN
                            BEGIN
                                :WBDDT_REF = SUBSTRING(:PRREFERENCIA FROM 5 FOR 6)||'/01/'||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4);
                            END

                         UPDATE VEF_EMP_TBLOCOM210_M610 X
                            SET X.BDVL_CONT_PER = 0 WHERE
                            X.BDCODEMP = :WBDCODEMP210 AND
                            X.BDCODQUADRO = 37 AND
                            X.BDREFERENCIA = :PRREFERENCIA and
                            x.bdchave = :WBDCHAVE210 and
                            X.bdaliq = :WBDALIQ and
                            X.bdcodcsocial = :WBDCODCSOCIAL AND
                            COALESCE(X.BDTIPOPROD,0) = COALESCE(:WBDTIPOPROD,0) AND
                            X.BDRETIFICADORA = :PRRETIFICADORA;

                         UPDATE VEF_EMP_TBLOCOM220_M620 X
                            SET X.BDVL_AJ_SALDO = (X.BDVL_AJ_SALDO - :WVALORCONT_COFINS),
                            X.BDVL_AJ_UTILIZADO = (:WVALORCONT_COFINS),
                            X.BDVL_AJ_REF = (:PRREFERENCIA)
                            WHERE
                            X.BDCODEMP = :WBDCODEMP210
                            AND X.BDCODQUADRO = 37
                            AND X.BDORDEM = :WORDEM_AJ
                            AND X.BDREFERENCIA = :WBDREFLAN220
                            AND X.BDVL_AJ_SALDO > 0
                            AND X.BDRETIFICADORA = :PRRETIFICADORA;

                            /* PREENCHE TABELA DE CONTROLE DE CRÉDITO, USADO NAS EXPORTAÇÕES E TREEVIEW */
                       UPDATE OR INSERT INTO VEF_EMP_TCREDITO_M220_M620 (BDCODPERIODO, BDCODMATRIZ, BDCODEMP, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDREFLANM220, BDVL_AJ_UTILIZADO, BDDT_REF, BDVL_AJ_SALDO_REF, BDALIQ, BDCODCSOCIAL, BDTIPOPROD, BDCODSCP, BDRETIFICADORA)
                       VALUES (:WBDCODPERIODO, :WBDCODMATRIZ210, :WBDCODEMP210, 37, :PRREFERENCIA, :WBDCHAVE, :WORDEM_AJ, :WBDREFLAN220, :WVALORCONT_COFINS, :WBDDT_REF, :WBDVL_AJ_SALDO, :WBDALIQ, :WBDCODCSOCIAL, :WBDTIPOPROD, :WBDCODSCP, :PRRETIFICADORA)
                       MATCHING (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDCHAVE, BDORDEM, BDVL_AJ_SALDO_REF, BDRETIFICADORA);


                            :WVALORCONT_COFINS = :WVALORCONT_COFINS - :WBDVL_AJ_SALDO;

                         UPDATE VEF_EMP_TBLOCOM210_M610 X
                           SET X.BDVL_AJUS_REDUC = (X.BDVL_AJUS_REDUC - ABS(:WVALORCONT_COFINS)) WHERE
                            X.BDCODEMP = :WBDCODEMP210 AND
                            X.BDCODQUADRO = 37 AND
                            X.BDREFERENCIA = :PRREFERENCIA AND
                            X.bdchave = :WBDCHAVE210 and
                            X.bdaliq = :WBDALIQ and
                            X.bdcodcsocial = :WBDCODCSOCIAL AND
                            COALESCE(X.BDTIPOPROD,0) = COALESCE(:WBDTIPOPROD,0) AND
                            X.BDRETIFICADORA = :PRRETIFICADORA;
                           CONTINUE LOOPD;

                END

                   IF ((:WVALORCONT_COFINS >= :WBDVL_AJ_SALDO) AND (:WVALORCONT_COFINS > 0) AND (:WBDVL_AJ_SALDO > 0)) THEN
                      BEGIN
                         /* SE O SALDO JÁ FOI USADO OU SUA REFERÊNCIA É DIFERENTE DA APURAÇÃO, ATUALIZA PARA O PRIMEIRO DIA DO MÊS REF*/
                        IF ((:WBDLV_AJ_UTILIZADO > 0) OR (:WBDREFLAN220 <> :PRREFERENCIA)) THEN
                            BEGIN
                                :WBDDT_REF = SUBSTRING(:PRREFERENCIA FROM 5 FOR 6)||'/01/'||SUBSTRING(:PRREFERENCIA FROM 1 FOR 4);
                            END

                        :WVALORCONT_COFINS = :WVALORCONT_COFINS - :WBDVL_AJ_SALDO;

                        UPDATE VEF_EMP_TBLOCOM220_M620 X
                            SET X.BDVL_AJ_UTILIZADO = (:WBDVL_AJ_SALDO),
                            X.BDVL_AJ_SALDO = (0)
                            WHERE X.BDCODEMP = :WBDCODEMP210
                            AND X.BDCODQUADRO = 37
                            AND X.BDORDEM = :WORDEM_AJ
                            AND X.BDREFERENCIA = :WBDREFLAN220
                            AND X.BDVL_AJ_SALDO > 0
                            AND X.BDRETIFICADORA = :PRRETIFICADORA;

                     UPDATE OR INSERT INTO VEF_EMP_TCREDITO_M220_M620
                     (BDCODPERIODO, BDCODMATRIZ, BDCODEMP, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDREFLANM220, BDVL_AJ_UTILIZADO, BDDT_REF, BDVL_AJ_SALDO_REF, BDALIQ, BDCODCSOCIAL, BDTIPOPROD, BDCODSCP, BDRETIFICADORA)
                     VALUES(:WBDCODPERIODO, :WBDCODMATRIZ210, :WBDCODEMP210, 37, :PRREFERENCIA, :WBDCHAVE, :WORDEM_AJ, :WBDREFLAN220, :WBDVL_AJ_SALDO, :WBDDT_REF, :WBDVL_AJ_SALDO, :WBDALIQ, :WBDCODCSOCIAL, :WBDTIPOPROD, :WBDCODSCP, :PRRETIFICADORA)
                     MATCHING (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDCHAVE, BDORDEM, BDVL_AJ_SALDO_REF, BDRETIFICADORA);

                        UPDATE VEF_EMP_TBLOCOM210_M610 X
                            SET X.BDVL_CONT_PER = (:WVALORCONT_COFINS) WHERE
                            X.BDCODEMP = :WBDCODEMP210 AND
                            X.BDCODQUADRO = 37 AND
                            X.BDREFERENCIA = :PRREFERENCIA AND
                            X.bdchave = :WBDCHAVE210 and
                            X.bdaliq = :WBDALIQ and
                            X.bdcodcsocial = :WBDCODCSOCIAL AND
                            COALESCE(X.BDTIPOPROD,0) = COALESCE(:WBDTIPOPROD,0) AND
                            X.BDRETIFICADORA = :PRRETIFICADORA;

                        CONTINUE LOOPD;
                      END
                END


          IF ((SELECT X.BDVL_CONT_PER FROM VEF_EMP_TBLOCOM210_M610 X WHERE X.BDRETIFICADORA = :PRRETIFICADORA AND
            X.BDCODEMP = :WBDCODEMP210 AND X.bdcodmatriz = :WBDCODMATRIZ AND X.BDCODQUADRO = 37 AND X.BDREFERENCIA = :PRREFERENCIA and X.bdchave = :WBDCHAVE210 and
                            X.bdaliq = :WBDALIQ and
                            X.bdcodcsocial = :WBDCODCSOCIAL and
                            COALESCE(X.BDTIPOPROD,0) = COALESCE(:WBDTIPOPROD,0)) >= 0) THEN
            BEGIN

                SELECT SUM(BDVL_AJ_UTILIZADO) FROM VEF_EMP_TCREDITO_M220_M620
                    WHERE BDCODEMP = :WBDCODEMP210 AND BDCODQUADRO = 37 AND BDREFERENCIA = :PRREFERENCIA AND BDALIQ = :WBDALIQ AND BDCODCSOCIAL = :WBDCODCSOCIAL AND COALESCE(BDTIPOPROD,0) = COALESCE(:WBDTIPOPROD,0) AND BDRETIFICADORA = :PRRETIFICADORA
                    INTO :WBDLV_AJ_UTILIZADO;

                UPDATE VEF_EMP_TBLOCOM210_M610 X
                    SET X.BDVL_AJUS_REDUC = (:WBDLV_AJ_UTILIZADO) WHERE
                    X.BDCODEMP = :WBDCODEMP210 AND
                    X.BDCODQUADRO = 37 AND
                    X.BDREFERENCIA = :PRREFERENCIA AND
                    x.bdchave = :WBDCHAVE210 and
                    X.bdaliq = :WBDALIQ and
                    X.bdcodcsocial = :WBDCODCSOCIAL AND
                    COALESCE(X.BDTIPOPROD,0) = COALESCE(:WBDTIPOPROD,0) AND
                    X.BDRETIFICADORA = :PRRETIFICADORA;

                UPDATE VEF_EMP_TBLOCOM210_M610 X
                   SET BDVL_CONT_PER = (COALESCE(X.BDVL_CONT_APUR,0) + COALESCE(X.BDVL_AJUS_ACRES,0) - COALESCE(X.BDVL_AJUS_REDUC,0) + COALESCE(X.BDVL_CONT_DIFER_ANT,0) - COALESCE(X.BDVL_CONT_DIFER,0)) WHERE
                    X.BDCODEMP = :WBDCODEMP210 AND
                    X.BDCODQUADRO = 37 AND
                    X.BDREFERENCIA = :PRREFERENCIA and
                    x.bdchave = :WBDCHAVE210 and
                    X.bdaliq = :WBDALIQ and
                    X.bdcodcsocial = :WBDCODCSOCIAL AND
                    COALESCE(X.BDTIPOPROD,0) = COALESCE(:WBDTIPOPROD,0) AND
                    X.BDRETIFICADORA = :PRRETIFICADORA;
            END

              END

              END

END
^

create or alter procedure SP_APURACAO_BLOCOM_M230_M630 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRRETIFICADORA integer,
    PRAJUSTESCP DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
declare variable WINCTRIB integer;
declare variable WCODCRIT integer;
BEGIN
  -- INSERE A COMPETÊNCIA DA APURAÇÃO...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :WINCTRIB, :WCODCRIT;

  if ((:WINCTRIB is null) and (:PRCODEMPSO > 0)) then
    begin
      SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMPSO
      INTO :WINCTRIB, :WCODCRIT;
    end

  IF ((WINCTRIB IS NOT NULL) AND (WCODCRIT IS NOT NULL)) THEN
    BEGIN
      /* REGISTRO M230: INFORMAÇÕES ADICIONAIS DE DIFERIMENTO */
      INSERT INTO VEF_EMP_TBLOCOM230_M630 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODCRE_4_3_6, BDCNPJ, BDVL_VEND, BDVL_NAO_RECEB, BDVL_CONT_DIF, BDVL_CRED_DIF, BDRETIFICADORA)
      SELECT 7 as BDCODPERIODO, COALESCE(SCP.BDCODEMPSCP,m230.BDCODEMP) BDCODEMP, COALESCE(SCP.BDCODEMPSCP,COALESCE(emp.BDCODMATRIZ, m230.BDCODEMP)) as BDCODMATRIZ, 19 as BDCODQUADRO, m230.BDREFERENCIA,
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,m230.BDCODEMP) AND x.BDREFERENCIA = m230.BDREFERENCIA AND x.BDCODQUADRO = 19 AND x.BDCODPERIODO = 7 AND X.BDRETIFICADORA = :PRRETIFICADORA AND x.BDCODCSOCIAL = m230.BDCODCSOCIAL AND COALESCE(x.BDTIPOPROD,0) = COALESCE(m230.BDTIPOPROD,0) AND x.BDALIQ = m230.BDALIQPIS) as BDCHAVE,
             GETORDEMSEQUENCIAL_STR('M230.'||7||'.'||m230.BDCODEMP||'.'||COALESCE(emp.BDCODMATRIZ, m230.BDCODEMP)||'.'||19||'.'||m230.BDREFERENCIA||'.'||SCP.BDCODEMPSCP||'.'||
            (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,m230.BDCODEMP) AND x.BDREFERENCIA = m230.BDREFERENCIA AND x.BDCODQUADRO = 19
            AND x.BDCODPERIODO = 7 AND X.BDRETIFICADORA = :PRRETIFICADORA AND x.BDCODCSOCIAL = m230.BDCODCSOCIAL AND COALESCE(x.BDTIPOPROD,0) = COALESCE(m230.BDTIPOPROD,0) AND x.BDALIQ = m230.BDALIQPIS), :prCODEMP) as BDORDEM,

/*(SELECT COALESCE(MAX(x.BDORDEM)+1, 1) FROM VEF_EMP_TBLOCOM230_M630 x WHERE x.BDCODEMP = m230.BDCODEMP AND x.BDREFERENCIA = m230.BDREFERENCIA AND x.BDCODQUADRO = 19 AND x.BDCODPERIODO = 7
  AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE   FROM VEF_EMP_TBLOCOM210_M610 x  WHERE x.BDCODEMP = m230.BDCODEMP AND x.BDREFERENCIA = m230.BDREFERENCIA AND x.BDCODQUADRO = 19
   AND x.BDCODPERIODO = 7 AND x.BDCODCSOCIAL = m230.BDCODCSOCIAL AND x.BDALIQ = m230.BDALIQPIS) ) as BDORDEM, */

             m230.BDCODCRE_4_3_6, m230.BDCNPJPJRELACIONADA as BDCNPJ,
             m230.BDVLRVENDAPIS as BDVL_VEND, m230.BDVLRNRECPIS as BDVL_NAO_RECEB, m230.BDVLRCONDEFPIS as BDVL_CONT_DIF, m230.BDVLRCREDEFPIS as BDVL_CRED_DIF,
             :PRRETIFICADORA
      FROM VEF_EMP_TINFADIDEFM230630 m230
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m230.BDCODEMP)
      LEFT outer JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = m230.BDCODEMP AND SCP.BDCODSCP = m230.BDCODSCP AND SCP.BDREFEMP = m230.BDREFSOC)
      WHERE m230.BDALIQPIS > 0
        AND m230.BDCODEMP in (SELECT ex.BDCODEMP
                              FROM TEMPRESAS ex
                              WHERE ex.BDCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
                                OR EX.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP))
        AND (((iif(:PRAJUSTESCP = true and :PRCODEMPSO > 0, true, false) = true) and (coalesce(SCP.BDCODEMPSCP, 0) = :PRCODEMP)) or
             ((iif(:PRAJUSTESCP = true and :PRCODEMPSO = 0, true, false) = true) and (coalesce(SCP.BDCODEMPSCP, 0) = 0)) or (:PRAJUSTESCP = false))
        AND m230.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,m230.BDCODEMP)
                      AND x.BDREFERENCIA = m230.BDREFERENCIA
                      AND x.BDCODQUADRO = 19
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m230.BDCODCSOCIAL
                      AND COALESCE(x.BDTIPOPROD,0) = COALESCE(m230.BDTIPOPROD,0)
                      AND x.BDALIQ = m230.BDALIQPIS
                      AND X.BDRETIFICADORA = :PRRETIFICADORA));

      /* REGISTRO M630: INFORMAÇÕES ADICIONAIS DE DIFERIMENTO */
      INSERT INTO VEF_EMP_TBLOCOM230_M630 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODCRE_4_3_6, BDCNPJ, BDVL_VEND, BDVL_NAO_RECEB, BDVL_CONT_DIF, BDVL_CRED_DIF, BDRETIFICADORA)
      SELECT 7 as BDCODPERIODO, COALESCE(SCP.BDCODEMPSCP,m630.BDCODEMP) BDCODEMP, COALESCE(SCP.BDCODEMPSCP,COALESCE(emp.BDCODMATRIZ, m630.BDCODEMP)) as BDCODMATRIZ, 37 as BDCODQUADRO, m630.BDREFERENCIA,
             (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,m630.BDCODEMP) AND x.BDREFERENCIA = m630.BDREFERENCIA AND x.BDCODQUADRO = 37 AND x.BDCODPERIODO = 7 AND X.BDRETIFICADORA = :PRRETIFICADORA AND x.BDCODCSOCIAL = m630.BDCODCSOCIAL AND COALESCE(x.BDTIPOPROD,0) = COALESCE(m630.BDTIPOPROD,0) AND x.BDALIQ = m630.BDALIQCOFINS) as BDCHAVE,
              GETORDEMSEQUENCIAL_STR('M630.'||7||'.'||m630.BDCODEMP||'.'||COALESCE(emp.BDCODMATRIZ, m630.BDCODEMP)||'.'||37||'.'||m630.BDREFERENCIA||'.'||SCP.BDCODEMPSCP||'.'||
              (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,m630.BDCODEMP) AND x.BDREFERENCIA = m630.BDREFERENCIA AND x.BDCODQUADRO = 37
              AND x.BDCODPERIODO = 7 AND X.BDRETIFICADORA = :PRRETIFICADORA AND x.BDCODCSOCIAL = m630.BDCODCSOCIAL AND COALESCE(x.BDTIPOPROD,0) = COALESCE(m630.BDTIPOPROD,0) AND x.BDALIQ = m630.BDALIQCOFINS), :prCODEMP) as BDORDEM,
/*(SELECT COALESCE(MAX(x.BDORDEM)+1, 1) FROM VEF_EMP_TBLOCOM230_M630 x WHERE x.BDCODEMP = m630.BDCODEMP AND x.BDREFERENCIA = m630.BDREFERENCIA
AND x.BDCODQUADRO = 37 AND x.BDCODPERIODO = 7 AND x.BDCHAVE = (SELECT FIRST 1 x.BDCHAVE FROM VEF_EMP_TBLOCOM210_M610 x WHERE x.BDCODEMP = m630.BDCODEMP AND x.BDREFERENCIA = m630.BDREFERENCIA AND x.BDCODQUADRO = 37 AND x.BDCODPERIODO = 7
AND x.BDCODCSOCIAL = m630.BDCODCSOCIAL AND x.BDALIQ = m630.BDALIQCOFINS) ) as BDORDEM,  */
             m630.BDCODCRE_4_3_6, m630.BDCNPJPJRELACIONADA as BDCNPJ,
             m630.BDVLRVENDACOFINS as BDVL_VEND, m630.BDVLRNRECCOFINS as BDVL_NAO_RECEB, m630.BDVLRCONDEFCOFINS as BDVL_CONT_DIF, m630.BDVLRCREDEPCOFINS as BDVL_CRED_DIF,
             :PRRETIFICADORA
      FROM VEF_EMP_TINFADIDEFM230630 m630
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m630.BDCODEMP)
      LEFT outer JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = m630.BDCODEMP AND SCP.BDCODSCP = m630.BDCODSCP AND SCP.BDREFEMP = m630.BDREFSOC)
      WHERE m630.BDALIQCOFINS > 0
        AND m630.BDCODEMP in (SELECT ex.BDCODEMP
                              FROM TEMPRESAS ex
                              WHERE ex.BDCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
                                OR EX.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP))
        AND (((iif(:PRAJUSTESCP = true and :PRCODEMPSO > 0, true, false) = true) and (coalesce(SCP.BDCODEMPSCP, 0) = :PRCODEMP)) or
             ((iif(:PRAJUSTESCP = true and :PRCODEMPSO = 0, true, false) = true) and (coalesce(SCP.BDCODEMPSCP, 0) = 0)) or (:PRAJUSTESCP = false))
        AND m630.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM210_M610 x
                    WHERE x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,m630.BDCODEMP)
                      AND x.BDREFERENCIA = m630.BDREFERENCIA
                      AND x.BDCODQUADRO = 37
                      AND x.BDCODPERIODO = 7
                      AND x.BDCODCSOCIAL = m630.BDCODCSOCIAL
                      AND COALESCE(x.BDTIPOPROD,0) = COALESCE(m630.BDTIPOPROD,0)
                      AND x.BDALIQ = m630.BDALIQCOFINS
                      AND X.BDRETIFICADORA = :PRRETIFICADORA));

    END

END
^

CREATE OR ALTER procedure SP_APURACAO_BLOCOM_M200 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRCODEMPPRINCIPALSCP integer,
    PRRETIFICADORA INTEGER)
as
begin
-- Alterado para a SP_APURACAO_BLOCOM_M200M600 e será removida depois, confia...
end
^

CREATE OR ALTER procedure SP_APURACAO_BLOCOM_M600 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRCODEMPPRINCIPALSCP integer,
    PRRETIFICADORA INTEGER)
as
begin
-- Alterado para a SP_APURACAO_BLOCOM_M200M600 e será removida depois, confia...
end
^

create or alter procedure SP_APURACAO_BLOCOM_M200M600_P2 (
    PRCODQUADRO integer,
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRCODEMPSO integer,
    PRRETIFICADORA integer,
    PRVLRSLD numeric(15,2))
as
declare variable WSQL varchar(32750);
declare variable WINCTRIB integer;
declare variable WRETPISCOFPERANT varchar(5);
declare variable WVLR numeric(15,2);
declare variable WVLRAUX numeric(15,2);
declare variable WVLRSLD numeric(15,2);
declare variable WVLRTOTCONT numeric(15,2);
declare variable WQTD integer;
declare variable WCODPERIODO integer;
declare variable WCODEMP integer;
declare variable WCODMATRIZ integer;
declare variable WCODQUADRO integer;
declare variable WREFERENCIA integer;
declare variable WCHAVE integer;
declare variable WCOD_NAT_REC integer;
declare variable WORDENACAO integer;
declare variable WVLRRECEITAFINANCEIRA DM_NUMERIC_15_2;
declare variable WNAOUTILIZARCRE DM_BOOLEAN;
declare variable WNAOUTILIZARCRED_201_208 DM_BOOLEAN;
BEGIN
   -- Alt.: #214876 - Movido para aqui, pois a "SP_APURACAO_BLOCOM_M200M600" já bateu no limite.
   -- Se não tiver gerados valores nos campos dos quadros, vai gerar zerado...
    SELECT FIRST 1 BDVALOR FROM VEF_EMP_TBLOCOMGERREG
    WHERE BDCODPERIODO = 7 AND BDCODEMP = :prCODEMP AND BDCODMATRIZ = :prCODEMP AND BDREFERENCIA = :prREFERENCIA AND BDCODQUADRO = :prCODQUADRO
      AND BDNUMCAMPO = 2 AND BDRETIFICADORA = :PRRETIFICADORA INTO :WVLR;
    IF (ROW_COUNT = 0) THEN
    insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                               values (7, :prCODEMP, :prCODEMP, :prREFERENCIA, :prCODQUADRO, 2, 0, :PRRETIFICADORA);
    SELECT FIRST 1 BDVALOR FROM VEF_EMP_TBLOCOMGERREG
    WHERE BDCODPERIODO = 7 AND BDCODEMP = :prCODEMP AND BDCODMATRIZ = :prCODEMP AND BDREFERENCIA = :prREFERENCIA AND BDCODQUADRO = :prCODQUADRO
      AND BDNUMCAMPO = 3 AND BDRETIFICADORA = :PRRETIFICADORA INTO :WVLR;
    IF (ROW_COUNT = 0) THEN
    insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                               values (7, :prCODEMP, :prCODEMP, :prREFERENCIA, :prCODQUADRO, 3, 0, :PRRETIFICADORA);
    SELECT FIRST 1 BDVALOR FROM VEF_EMP_TBLOCOMGERREG
    WHERE BDCODPERIODO = 7 AND BDCODEMP = :prCODEMP AND BDCODMATRIZ = :prCODEMP AND BDREFERENCIA = :prREFERENCIA AND BDCODQUADRO = :prCODQUADRO
      AND BDNUMCAMPO = 4 AND BDRETIFICADORA = :PRRETIFICADORA INTO :WVLR;
    IF (ROW_COUNT = 0) THEN
    insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                               values (7, :prCODEMP, :prCODEMP, :prREFERENCIA, :prCODQUADRO, 4, 0, :PRRETIFICADORA);
    SELECT FIRST 1 BDVALOR FROM VEF_EMP_TBLOCOMGERREG
    WHERE BDCODPERIODO = 7 AND BDCODEMP = :prCODEMP AND BDCODMATRIZ = :prCODEMP AND BDREFERENCIA = :prREFERENCIA AND BDCODQUADRO = :prCODQUADRO
      AND BDNUMCAMPO = 5 AND BDRETIFICADORA = :PRRETIFICADORA INTO :WVLR;
    IF (ROW_COUNT = 0) THEN
    insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                               values (7, :prCODEMP, :prCODEMP, :prREFERENCIA, :prCODQUADRO, 5, 0, :PRRETIFICADORA);
    SELECT FIRST 1 BDVALOR FROM VEF_EMP_TBLOCOMGERREG
    WHERE BDCODPERIODO = 7 AND BDCODEMP = :prCODEMP AND BDCODMATRIZ = :prCODEMP AND BDREFERENCIA = :prREFERENCIA AND BDCODQUADRO = :prCODQUADRO
      AND BDNUMCAMPO = 6 AND BDRETIFICADORA = :PRRETIFICADORA INTO :WVLR;
    IF (ROW_COUNT = 0) THEN
    insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                               values (7, :prCODEMP, :prCODEMP, :prREFERENCIA, :prCODQUADRO, 6, 0, :PRRETIFICADORA);
    SELECT FIRST 1 BDVALOR FROM VEF_EMP_TBLOCOMGERREG
    WHERE BDCODPERIODO = 7 AND BDCODEMP = :prCODEMP AND BDCODMATRIZ = :prCODEMP AND BDREFERENCIA = :prREFERENCIA AND BDCODQUADRO = :prCODQUADRO
      AND BDNUMCAMPO = 7 AND BDRETIFICADORA = :PRRETIFICADORA INTO :WVLR;
    IF (ROW_COUNT = 0) THEN
    insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                               values (7, :prCODEMP, :prCODEMP, :prREFERENCIA, :prCODQUADRO, 7, 0, :PRRETIFICADORA);
    SELECT FIRST 1 BDVALOR FROM VEF_EMP_TBLOCOMGERREG
    WHERE BDCODPERIODO = 7 AND BDCODEMP = :prCODEMP AND BDCODMATRIZ = :prCODEMP AND BDREFERENCIA = :prREFERENCIA AND BDCODQUADRO = :prCODQUADRO
      AND BDNUMCAMPO = 8 AND BDRETIFICADORA = :PRRETIFICADORA INTO :WVLR;
    IF (ROW_COUNT = 0) THEN
    insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                               values (7, :prCODEMP, :prCODEMP, :prREFERENCIA, :prCODQUADRO, 8, 0, :PRRETIFICADORA);
   /*********************************************************************************************************************************************/

  :wVLRSLD     = :prVLRSLD;

  select BDINCTRIB+1, /*BDCREDITOSPERANT,*/ BDRETPISCOFPERANT/*, COALESCE(BDABATERESSARCIM, 'FALSE'), coalesce(BDORDENACRED, 'FALSE')*/, coalesce(BDNAOUTILIZARCRE, 'FALSE'), coalesce(BDNAOUTILIZARCRED_201_208, 'FALSE')
  from VW_INT_SPEDPISCOFINS_REF where BDCODEMP = :PRCODEMP
  into :wINCTRIB, /*:wCREDITOSPERANT,*/ :wRETPISCOFPERANT/*, :wABATERESSARCIM, :wORDENACRED*/, :WNAOUTILIZARCRE, :WNAOUTILIZARCRED_201_208;

  if ((:PRCODEMPSO > 0) and (:WINCTRIB is null)) then
    begin
      select BDINCTRIB+1, /*BDCREDITOSPERANT,*/ BDRETPISCOFPERANT/*, COALESCE(BDABATERESSARCIM, 'FALSE'), coalesce(BDORDENACRED, 'FALSE')*/, coalesce(BDNAOUTILIZARCRE, 'FALSE'), coalesce(BDNAOUTILIZARCRED_201_208, 'FALSE')
      from VW_INT_SPEDPISCOFINS_REF where BDCODEMP = :PRCODEMPSO
      into :wINCTRIB, /*:wCREDITOSPERANT,*/ :wRETPISCOFPERANT/*, :wABATERESSARCIM, :wORDENACRED*/, :WNAOUTILIZARCRE, :WNAOUTILIZARCRED_201_208;
    end

  /* 2 - Exclusivamente no regime cumulativo */
  if (wINCTRIB in (2,3)) then
    begin
      /* 09 - VL_TOT_CONT_CUM_PER - Valor Total da Contribuição Cumulativa do Período (recuperado do campo 13 do Registro M210, quando o campo "COD_CONT" = 31, 32, 51, 52, 53, 54 e 72) */
      wVLRTOTCONT = 0;
      select sum(coalesce(m.bdVL_CONT_PER, 0)) as bdVALOR, sum(coalesce(m.bdvlrreceitafinanceira, 0)) as bdVLRRECEITAFINANCEIRA
      from VEF_EMP_TBLOCOM210_M610 m 
      left outer join  VEF_BASE_TTABCSOCIAL_4_3_5 t435 on (t435.bdCODCSOCIAL =  m.bdCODCSOCIAL) 
      where ((3 = 3) and (t435.bdCODCSOCIALEXP in (31,51,52,53,54,72)) or -- Quando é regime não-cumulativo e cumulativo, já considerou algumas contribuições no campo 2...
             (3 <> 3) and (t435.bdCODCSOCIALEXP in (31,32,51,52,53,54,72)))
        and (m.bdCODQUADRO = IIF(:prCODQUADRO = 15,19,37)) -- M210 - Detalhamento da contribuição para o PIS/PASEP | M610 - Detalhamento da contribuição para o Cofins
        and m.bdCODMATRIZ = :prCODEMP
        and m.bdREFERENCIA = :prREFERENCIA
        AND M.BDRETIFICADORA = :PRRETIFICADORA
      into :wVLRTOTCONT, :wVLRRECEITAFINANCEIRA;

      insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA, BDVLRRECEITAFINANCEIRA)
                                 values (7, :prCODEMP, :prCODEMP, :prREFERENCIA, :prCODQUADRO, 9, coalesce(:wVLRTOTCONT,0), :PRRETIFICADORA, COALESCE(:wVLRRECEITAFINANCEIRA,0));

      /* 22 O valor total da da contribuição social apurada, deve ser igual ou superior ao somatório total dos ajustes de redução dos registros M220, para PIS/PASEP ou M620, para Cofins, onde o tipo de ajuste seja igual a 0(Ajustes de redução). #Inconsistência# */
      if ((:wVLRTOTCONT < 0) and (:prVerificarInconsistencias = 'TRUE')) then
        update or insert into VEF_INCON_BLOCOM (bdCODPERIODO, bdCODEMP, bdCODMATRIZ, bdREFERENCIA, bdCODBLOCOM, bdCODINC, BDRETIFICADORA)
                                        values (7, :prCODEMP, :prCODEMP, :prREFERENCIA, GETORDEMSEQUENCIAL_STR(:prCODEMP||'.'||:prCODEMP||'.'||:prREFERENCIA, :PRCODEMPSO), 22, :PRRETIFICADORA)
                                      matching (bdCODPERIODO, bdCODEMP, bdCODMATRIZ, bdREFERENCIA, bdCODBLOCOM, BDRETIFICADORA);

      /* 10 - VL_RET_CUM - Valor Retido na Fonte Deduzido no Período */
      wVLR = 0;

      wSQL =        'SELECT COUNT(*) as BDQTD ';
      wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
      IF (:prCODQUADRO = 15) THEN
        wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 49) '; -- 1300 - Ficha de retenção do PIS/PASEP
      ELSE
        wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 50) '; -- 1700 - Ficha de retenção do Cofins
      if (wINCTRIB in (3)) then -- Apenas vai considerar o tipo de incidência tributária quando for ambas as incidencias...
      wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 1 '; -- Cumulativa
      wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL|| '  AND m.BDRETIFICADORA = '||:PRRETIFICADORA||' ';
      execute statement ( wSQL )
      into :WQTD;

      if ((WQTD = 0) or ((:wVLRTOTCONT is null) or (:wVLRTOTCONT = 0)))  then
        begin
          insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                     values (7, :prCODEMP, :prCODEMP, :prREFERENCIA, :prCODQUADRO, 10, coalesce(:wVLR,0), :PRRETIFICADORA);
        end
      else
        begin
          wSQL =        'SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, ';
          wSQL = wSQL|| '      SUM(COALESCE(m.BDSLD_RET, 0)) as BDVALOR, ';
          wSQL = wSQL|| '      IIF((m.BDREFERENCIA = m.BDPR_REC_RET), 0, 1) as BDORDENACAO ';
          wSQL = wSQL|| 'FROM VEF_EMP_TBLOCOM1300_1700 m ';
          IF (:prCODQUADRO = 15) THEN
            wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 49) '; -- 1300 - Ficha de retenção do PIS/PASEP
          ELSE
            wSQL = wSQL|| 'WHERE (m.BDCODQUADRO = 50) '; -- 1700 - Ficha de retenção do Cofins
          if (wINCTRIB in (3)) then -- Apenas vai considerar o tipo de incidência tributária quando for ambas as incidencias...
            wSQL = wSQL|| '  AND m.BDCOD_NAT_REC = 1 '; -- Cumulativa
          wSQL = wSQL|| '  AND m.BDCODMATRIZ = '||:prCODEMP||' ';
          wSQL = wSQL|| '  AND m.BDREFERENCIA = '||:prREFERENCIA||' ';
          wSQL = wSQL|| '  AND m.BDRETIFICADORA = '||:PRRETIFICADORA||' ';
          wSQL = wSQL|| 'GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, m.BDPR_REC_RET ';
          if (:wRETPISCOFPERANT = 'TRUE') then -- Quando estiver configurada a opção "Aproveitar as retenções de PIS e Cofins de períodos anteriores" vai aproveitar sempre os períodos anteriores primeiro...
            wSQL = wSQL|| 'ORDER BY m.BDPR_REC_RET ';
          else -- Caso conterário, vai primeiro abater o mês atual e depois os meses anteriores....
            wSQL = wSQL|| 'ORDER BY BDORDENACAO, m.BDPR_REC_RET ';

          for
              execute statement ( wSQL )
                  into :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCOD_NAT_REC, :wVLR, :wORDENACAO
          do
          begin
            if (:wVLRTOTCONT > 0) then
              begin
                /* Se o valor do crédito for maior que o valor do débito então este valor deve ser levado como saldo credor no registro 1300. */
                if (:wVLR < :wVLRTOTCONT) then
                  begin
                    wVLRSLD     = 0;
                    wVLRTOTCONT = wVLRTOTCONT - wVLR;
                  end
                else
                  begin
                /* Caso tenha mais débitos que créditos, abate apenas apenas os créditos possíveis do lançamento... */
                    wVLRSLD     = :wVLR - :wVLRTOTCONT;
                    wVLR        = :wVLR - :wVLRSLD;
                    wVLRTOTCONT = 0;
                  end
        
                /* Caso tenha registros atualiza */
                update VEF_EMP_TBLOCOM1300_1700 m
                set m.BDVL_RET_DED = :wVLR,
                    m.BDSLD_RET    = :wVLRSLD
                where m.BDCODPERIODO = :wCODPERIODO
                  and m.BDCODEMP = :wCODEMP
                  and m.BDCODMATRIZ = :wCODMATRIZ
                  and m.BDCODQUADRO = :wCODQUADRO
                  and m.BDREFERENCIA = :wREFERENCIA
                  and m.BDCHAVE = :wCHAVE
                  and m.BDCOD_NAT_REC = :wCOD_NAT_REC
                  AND M.BDRETIFICADORA = :PRRETIFICADORA;
        
                wVLRAUX = 0;
                select coalesce(BDVALOR, 0)
                from VEF_EMP_TBLOCOMGERREG
                where BDCODMATRIZ  = :prCODEMP
                  and BDREFERENCIA = :prREFERENCIA
                  AND BDRETIFICADORA = :PRRETIFICADORA
                  and BDCODQUADRO  = :prCODQUADRO -- M200 - Consolidação da contribuição para o PIS/PASEP
                  and BDNUMCAMPO   = 10
                into wVLRAUX;
          
                if (wVLRAUX is null) then
                  wVLRAUX = 0;
          
                update or insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                                             values (7, :prCODEMP, :prCODEMP, :prREFERENCIA, :prCODQUADRO, 10, coalesce(:wVLR+:wVLRAUX,0), :PRRETIFICADORA)
                                                   matching (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDRETIFICADORA);
              end
          end
        end

      /* 11 - VL_OUT_DED_CUM - Outras Deduções no Período */
      wVLR = 0;
      select sum(coalesce(IIF(:prCODQUADRO = 15,m.BDVLRPIS,m.BDVLRCOFINS), 0)) as BDVALOR -- M300: Contribuição de PIS/PASEP diferida em períodos anteriores - Valores a pagar no período. | M700: Cofins diferida em períodos anteriores - Valores a pagar no período
      from VEF_EMP_TORIDEDF700 m
      where m.BDINDNATDED = 2 -- 1 - Dedução de Natureza Cumulativa
        and m.BDCODEMP in (select ex.BDCODEMP
                           from TEMPRESAS ex
                           where ex.BDCODEMP = :prCODEMP
                              or ex.BDCODMATRIZ = :prCODEMP)
        and m.BDREFERENCIA = :prREFERENCIA
      into :wVLR;

      insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                 values (7, :prCODEMP, :prCODEMP, :prREFERENCIA, :prCODQUADRO, 11, coalesce(:wVLR,0), :PRRETIFICADORA);

      /* 12 - VL_CONT_CUM_REC - Valor da Contribuição Cumulativa a Recolher/Pagar (09 - 10 - 11) */
      wVLR = 0;
      select sum(aux.BDVLRSOMAR-aux.BDVLRSUB) as BDVALOR
      from (/* Campo a somar */
            select m.BDCODEMP, m.BDREFERENCIA, coalesce(m.BDVALOR,0) as BDVLRSOMAR, 0 as BDVLRSUB
            from VEF_EMP_TBLOCOMGERREG m
            where (m.BDCODQUADRO = :prCODQUADRO)
              and (m.BDNUMCAMPO in (9))
              and m.BDCODMATRIZ = :prCODEMP
              and m.BDREFERENCIA = :prREFERENCIA
              AND M.BDRETIFICADORA = :PRRETIFICADORA
            union all
            /* Campo a subtrair */
            select m.BDCODEMP, m.BDREFERENCIA, 0 as BDVLRSOMAR, coalesce(m.BDVALOR,0) as BDVLRSUB
            from VEF_EMP_TBLOCOMGERREG m
            where (m.BDCODQUADRO = :prCODQUADRO)
              and (m.BDNUMCAMPO in (10,11))
              and m.BDCODMATRIZ = :prCODEMP
              and m.BDREFERENCIA = :prREFERENCIA
              AND M.BDRETIFICADORA = :PRRETIFICADORA
            ) aux
      into :wVLR;

      insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                 values (7, :prCODEMP, :prCODEMP, :prREFERENCIA, :prCODQUADRO, 12, coalesce(:wVLR,0), :PRRETIFICADORA);
    end
  else
    begin -- Joga os valores zerados...
      /* 09 - VL_TOT_CONT_CUM_PER - Valor Total da Contribuição Cumulativa do Período (recuperado do campo 13 do Registro M210, quando o campo "COD_CONT" = 31, 32, 51, 52, 53, 54 e 72) */
      insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                 values (7, :prCODEMP, :prCODEMP, :prREFERENCIA, :prCODQUADRO, 9, 0, :PRRETIFICADORA);

      /* 10 - VL_RET_CUM - Valor Retido na Fonte Deduzido no Período */
      insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                 values (7, :prCODEMP, :prCODEMP, :prREFERENCIA, :prCODQUADRO, 10, 0, :PRRETIFICADORA);

      /* 11 - VL_OUT_DED_CUM - Outras Deduções no Período */
      insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                 values (7, :prCODEMP, :prCODEMP, :prREFERENCIA, :prCODQUADRO, 11, 0, :PRRETIFICADORA);

      /* 12 - VL_CONT_CUM_REC - Valor da Contribuição Cumulativa a Recolher/Pagar (09 - 10 - 11) */
      insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                                 values (7, :prCODEMP, :prCODEMP, :prREFERENCIA, :prCODQUADRO, 12, 0, :PRRETIFICADORA);
    end

  /* 3 - Regimes não-cumulativo e cumulativo */
  /* 13 - VL_TOT_CONT_REC - VALOR TOTAL DA CONTRIBUIÇÃO A RECOLHER/PAGAR NO PERÍODO (08 + 12) */
  WVLR = 0;
  select sum(coalesce(M.BDVALOR,0)) as BDVALOR
  from VEF_EMP_TBLOCOMGERREG M
  where (M.BDCODQUADRO = :prCODQUADRO)
    and (M.BDNUMCAMPO in (8,12))
    and M.BDCODMATRIZ = :PRCODEMP
    and M.BDREFERENCIA = :PRREFERENCIA
    AND M.BDRETIFICADORA = :PRRETIFICADORA
  into :WVLR;
 
  insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
                             values (7, :PRCODEMP, :PRCODEMP, :PRREFERENCIA, :prCODQUADRO, 13, coalesce(:WVLR,0), :PRRETIFICADORA);

    /* Solicitação #164829 - Se tiver paramentro de não utilizar credito marcado vai zerar valor de desconto e passar para saldo */
    IF (WNAOUTILIZARCRE = 'TRUE') THEN
        BEGIN
            UPDATE VEF_EMP_TBLOCOM1100_1500 M
            SET M.BDSLD_CRED_FIM = (M.BDSLD_CRED_FIM + M.BDVL_CRED_DESC_EFD),
                M.BDVL_CRED_DESC_EFD = 0
            WHERE ((M.BDCODEMP = :PRCODEMP) OR (M.BDCODMATRIZ = :PRCODEMP)) AND
                    M.BDREFERENCIA = :PRREFERENCIA AND
                    M.BDRETIFICADORA = :PRRETIFICADORA AND
                    M.BDCODCRE_4_3_6 IN (20, 21, 22, 23, 24, 25, 26, 27); -- DE 301 AT? 308

            UPDATE VEF_EMP_TBLOCOM100_500 M
            SET M.BDIND_DESC_CRED = 1,
                M.BDVL_CRED_DESC = 0,
                M.BDSLD_CRED = M.BDVL_CRED_DISP
            WHERE ((M.BDCODEMP = :PRCODEMP) OR (M.BDCODMATRIZ = :PRCODEMP))
            AND     M.BDREFERENCIA = :PRREFERENCIA
            AND     M.BDRETIFICADORA = :PRRETIFICADORA
            AND     M.BDCODCRE_4_3_6 IN (20, 21, 22, 23, 24, 25, 26, 27); -- DE 301 AT? 308
        END

    IF (WNAOUTILIZARCRED_201_208 = 'TRUE') THEN
        BEGIN
            UPDATE VEF_EMP_TBLOCOM1100_1500 M
            SET M.BDSLD_CRED_FIM = (M.BDSLD_CRED_FIM + M.BDVL_CRED_DESC_EFD),
                M.BDVL_CRED_DESC_EFD = 0
            WHERE ((M.BDCODEMP = :PRCODEMP) OR (M.BDCODMATRIZ = :PRCODEMP)) AND
                    M.BDREFERENCIA = :PRREFERENCIA AND
                    M.BDRETIFICADORA = :PRRETIFICADORA AND
                    M.BDCODCRE_4_3_6 IN (11, 12, 13, 14, 15, 16, 17, 18);

            UPDATE VEF_EMP_TBLOCOM100_500 M
            SET M.BDIND_DESC_CRED = 1,
                M.BDVL_CRED_DESC = 0,
                M.BDSLD_CRED = M.BDVL_CRED_DISP
            WHERE ((M.BDCODEMP = :PRCODEMP) OR (M.BDCODMATRIZ = :PRCODEMP))
            AND     M.BDREFERENCIA = :PRREFERENCIA
            AND     M.BDRETIFICADORA = :PRRETIFICADORA
            AND     M.BDCODCRE_4_3_6 IN (11, 12, 13, 14, 15, 16, 17, 18);
END

END
^

create or alter procedure SP_APURACAO_BLOCOM_M200M600 (
    PRCODQUADRO integer,
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRCODEMPSO integer,
    PRRETIFICADORA integer)
as
declare variable WSQL varchar(32750);
declare variable WINCTRIB integer;
declare variable WCREDITOSPERANT varchar(5);
declare variable WRETPISCOFPERANT varchar(5);
declare variable WVLR numeric(15,2);
declare variable WVLRAUX numeric(15,2);
declare variable WVLRUP numeric(15,2);
declare variable WVLRUPAUX numeric(15,2);
declare variable WVLRSLD numeric(15,2);
declare variable WVLRTOTCONT numeric(15,2);
declare variable WVLRCREDPERANT numeric(15,2);
declare variable WVLRCREDPERANT_TOTAL numeric(15,2);
declare variable WINTAUX integer;
declare variable WQTD integer;
declare variable WCODPERIODO integer;
declare variable WCODEMP integer;
declare variable WCODMATRIZ integer;
declare variable WCODQUADRO integer;
declare variable WREFERENCIA integer;
declare variable WPER_APU_CRED integer;
declare variable WCHAVE integer;
declare variable WCODCRE_4_3_6 integer;
declare variable WTIPOPROD integer;
declare variable WIND_CRED_ORI integer;
declare variable WCOD_NAT_REC integer;
declare variable WCHAVEAUX integer;
declare variable WORDENACAO integer;
declare variable WIND_DESC_CRED integer;
declare variable WALIQ DM_NUMERIC_7_4_ALIQ;
declare variable WABATERESSARCIM varchar(5);
declare variable WORDENACRED varchar(5);
declare variable WBDCODEXPCRE varchar(3);
declare variable WVL_CRED_DISP numeric(15,2);
declare variable WVL_CRED_DESC numeric(15,2);
declare variable WVL_CRED_SLD numeric(15,2);
declare variable WVLR_CRED_TOTAL_DESC_PERIODO numeric(15,2);
declare variable WVLRRECEITAFINANCEIRA DM_NUMERIC_15_2;
declare variable WNAOUTILIZARCRE DM_BOOLEAN;
declare variable WCONTABILIZAFILIALORIGINAL DM_BOOLEAN;
declare variable WNAOUTILIZARCRED_201_208 DM_BOOLEAN;
BEGIN
  execute procedure SP_SETA_COMPETENCIA(:prREFERENCIA);

  select BDINCTRIB+1, BDCREDITOSPERANT, BDRETPISCOFPERANT, COALESCE(BDABATERESSARCIM, 'FALSE'), coalesce(BDORDENACRED, 'FALSE'), coalesce(BDNAOUTILIZARCRE, 'FALSE'), coalesce(BDNAOUTILIZARCRED_201_208, 'FALSE')
  from VW_INT_SPEDPISCOFINS_REF
  where BDCODEMP = :PRCODEMP
  into :wINCTRIB, :wCREDITOSPERANT, :wRETPISCOFPERANT, :wABATERESSARCIM, :wORDENACRED, :WNAOUTILIZARCRE, :WNAOUTILIZARCRED_201_208;

  if ((:WINCTRIB is null) and (:PRCODEMPSO > 0)) then
    begin
      select BDINCTRIB+1, BDCREDITOSPERANT, BDRETPISCOFPERANT, COALESCE(BDABATERESSARCIM, 'FALSE'), coalesce(BDORDENACRED, 'FALSE'), coalesce(BDNAOUTILIZARCRE, 'FALSE'), coalesce(BDNAOUTILIZARCRED_201_208, 'FALSE')
      from VW_INT_SPEDPISCOFINS_REF
      where BDCODEMP = :PRCODEMPSO
      into :wINCTRIB, :wCREDITOSPERANT, :wRETPISCOFPERANT, :wABATERESSARCIM, :wORDENACRED, :WNAOUTILIZARCRE, :WNAOUTILIZARCRED_201_208;
    end

  /* REGISTRO M200: CONSOLIDAÇÃO DA CONTRIBUIÇÃO PARA O PIS/PASEP DO PERÍODO */
  /* 1 - Exclusivamente no regime não-cumulativo */
  if (WINCTRIB in (1, 3)) then
  begin
    /* 02 - VL_TOT_CONT_NC_PER - Valor Total da Contribuição Não Cumulativa do Período (recuperado do campo 13 do Registro M210, quando o campo "COD_CONT" = 01, 02, 03, 04, 32 e 71) */
    WVLRTOTCONT = 0;
    select sum(coalesce(M.BDVL_CONT_PER, 0)) as BDVALOR, sum(coalesce(M.BDVLRRECEITAFINANCEIRA, 0)) as BDVLRRECEITAFINANCEIRA
    from VEF_EMP_TBLOCOM210_M610 M
    left outer join VEF_BASE_TTABCSOCIAL_4_3_5 T435 on (T435.BDCODCSOCIAL = M.BDCODCSOCIAL)
    where (T435.BDCODCSOCIALEXP in (01, 02, 03, 04, 32, 71)) and
          (M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 19, 37)) and --M210 - Detalhamento da contribuição para o PIS/PASEP | M610 - Detalhamento da contribuição para o Cofins
          M.BDCODMATRIZ = :PRCODEMP and
          M.BDREFERENCIA = :PRREFERENCIA and
          M.BDRETIFICADORA = :PRRETIFICADORA
    into :WVLRTOTCONT, :WVLRRECEITAFINANCEIRA;

    delete from TMP_TBLOCOM_CONTR_TEMP;
    --Guarda os valores totais das contribuições por tipo de produto, para descontar apenas desse mesmo tipo de produto posteriormente...
    insert into TMP_TBLOCOM_CONTR_TEMP (BDTIPOPROD, BDVL_CONT_PER)
    select M.BDTIPOPROD, sum(coalesce(M.BDVL_CONT_PER, 0)) as BDVALOR
    from VEF_EMP_TBLOCOM210_M610 M
    left outer join VEF_BASE_TTABCSOCIAL_4_3_5 T435 on (T435.BDCODCSOCIAL = M.BDCODCSOCIAL)
    where (T435.BDCODCSOCIALEXP in (01, 02, 03, 04, 32, 71)) and
          (M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 19, 37)) and --M210 - DETALHAMENTO DA CONTRIBUI????O PARA O PIS/PASEP | M610 - DETALHAMENTO DA CONTRIBUI????O PARA O COFINS
          M.BDCODMATRIZ = :PRCODEMP and
          M.BDREFERENCIA = :PRREFERENCIA and
          M.BDRETIFICADORA = :PRRETIFICADORA
    group by M.BDTIPOPROD;

    insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA, BDVLRRECEITAFINANCEIRA)
    values (7, :PRCODEMP, :PRCODEMP, :PRREFERENCIA, :PRCODQUADRO, 2, coalesce(:WVLRTOTCONT, 0), :PRRETIFICADORA, coalesce(:WVLRRECEITAFINANCEIRA, 0));

    WVLRCREDPERANT = 0;
    WVLRCREDPERANT_TOTAL = 0;
    if (:WCREDITOSPERANT = 'TRUE') then /* Apenas se estiver configurada a opção "Aproveitar o crédito de PIS e Cofins de períodos anteriores" */
    begin
      for select M.BDCODPERIODO, M.BDCODEMP, M.BDCODMATRIZ, M.BDCODQUADRO, M.BDREFERENCIA, M.BDPER_APU_CRED, M.BDCODCRE_4_3_6, M.BDTIPOPROD, M.BDORIG_CRED, M.BDALIQ, sum(coalesce(M.BDSLD_CRED_FIM, 0)) as BDVALOR, REG.BDCODEXPCRE
          from VEF_EMP_TBLOCOM1100_1500 M
          left outer join VEF_BASE_TTAB_4_3_6 REG on (M.BDCODCRE_4_3_6 = REG.BDCODCRE_4_3_6)
          where (M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 52, 53)) and --1100 - Controle de créditos fiscais PIS/PASEP | 1500 - Controle de créditos fiscais Cofins
                (M.BDCODMATRIZ = :PRCODEMP) and
                (M.BDREFERENCIA = :PRREFERENCIA) and
                (M.BDRETIFICADORA = :PRRETIFICADORA)
                --Larissa - 23/11/2021 - Controle de créditos Bloco M - 1100/1500/Ressarcimento #151311 #153687 #157389
                AND (((m.bdvl_ressarcimento > 0) AND (:wABATERESSARCIM <> 'TRUE')) or (m.BDVL_RESSARCIMENTO = 0))
                and IIF(:WNAOUTILIZARCRE = 'TRUE', M.BDCODCRE_4_3_6 NOT IN (20, 21, 22, 23, 24, 25, 26, 27), TRUE)
                and IIF(:WNAOUTILIZARCRED_201_208 = 'TRUE', M.BDCODCRE_4_3_6 NOT IN (11, 12, 13, 14, 15, 16, 17, 18), TRUE)
              group by m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDPER_APU_CRED, m.BDCODCRE_4_3_6, m.bdTIPOPROD, m.BDORIG_CRED,m.bdaliq , reg.BDCODEXPCRE
              order by IIF(:WORDENACRED = 'TRUE', reg.BDCODEXPCRE, m.bdcodmatriz), m.BDPER_APU_CRED --Larissa - 30/11/2021 - Bloco M - utilização do crédito no mês da apuração, escolha do tipo de crédito #152907
              into :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wPER_APU_CRED, :wCODCRE_4_3_6, :wTIPOPROD, wIND_CRED_ORI,:waliq, :wVLRCREDPERANT, :WBDCODEXPCRE
      do
      begin
        if (((select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD) > 0) and (:WVLRCREDPERANT > 0)) then
        begin
          if ((select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD) < :WVLRCREDPERANT) then --Caso o valor da contribuição seja menor que o crédito anterior, apenas abate esse valor...
          begin
            WVLR = (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD);
            update TMP_TBLOCOM_CONTR_TEMP
            set BDVL_CONT_PER = 0
            where BDTIPOPROD = :WTIPOPROD;
          end
          else
          begin --Caso o valor da contribução seja maior que o crédito, pode abater totalmente...
            WVLR = :WVLRCREDPERANT;
            update TMP_TBLOCOM_CONTR_TEMP
            set BDVL_CONT_PER = (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD) - :WVLRCREDPERANT
            where BDTIPOPROD = :WTIPOPROD;
          end

          WVLRCREDPERANT_TOTAL = WVLRCREDPERANT_TOTAL + WVLR;

          update VEF_EMP_TBLOCOM1100_1500 M
          set M.BDVL_CRED_DESC_EFD = :WVLR,
              M.BDSLD_CRED_FIM = M.BDSLD_CRED_FIM - :WVLR
          where M.BDCODPERIODO = :WCODPERIODO and
                M.BDCODQUADRO = :WCODQUADRO and
                M.BDCODEMP = :WCODEMP and
                M.BDCODMATRIZ = :WCODMATRIZ and
                M.BDREFERENCIA = :WREFERENCIA and
                M.BDPER_APU_CRED = :WPER_APU_CRED and
                M.BDCODCRE_4_3_6 = :WCODCRE_4_3_6 and
                coalesce(M.BDTIPOPROD, 0) = coalesce(:WTIPOPROD, 0) and
                M.BDORIG_CRED = :WIND_CRED_ORI and
                ((M.BDALIQ = :WALIQ) or (M.BDALIQ = 9999)) and
                M.BDRETIFICADORA = :PRRETIFICADORA;
        end
      end
    end

    /* 03 - VL_TOT_CRED_DESC - Valor do Crédito Descontado, Apurado no Próprio Período da Escrituração (recuperado do campo 14 do Registro M100) */
      select count(m.BDCHAVE) as BDQTD
      from VEF_EMP_TBLOCOM100_500 m
      where (m.BDCODQUADRO = IIF(:prCODQUADRO = 15,11,29)) -- M100 - Crédito de PIS/PASEP | M500 - Crédito de Cofins
        and m.BDCODMATRIZ = :prCODEMP
        and m.BDREFERENCIA = :prREFERENCIA
        AND M.BDRETIFICADORA = :PRRETIFICADORA
        and IIF(:WNAOUTILIZARCRE = 'TRUE', M.BDCODCRE_4_3_6 NOT IN (20, 21, 22, 23, 24, 25, 26, 27), TRUE)
        and IIF(:WNAOUTILIZARCRED_201_208 = 'TRUE', M.BDCODCRE_4_3_6 NOT IN (11, 12, 13, 14, 15, 16, 17, 18), TRUE)
      into wQTD;

    if ((WQTD = 0) or ((select sum(BDVL_CONT_PER) from TMP_TBLOCOM_CONTR_TEMP) = 0) or ((select sum(BDVL_CONT_PER) from TMP_TBLOCOM_CONTR_TEMP) is null)) then --Caso não tenha dados no M100/M500 ou o valor do crédito seja zerado...
    begin
      update or insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
      values (7, :PRCODEMP, :prCODEMP, :PRREFERENCIA, :PRCODQUADRO, 3, 0, :PRRETIFICADORA)
      matching (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDRETIFICADORA);

          for
              select m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDTIPOPROD, m.BDIND_CRED_ORI,m.bdaliq,
                     sum(coalesce(m.BDVL_CRED_DESC, 0)) as BDVALOR
              from VEF_EMP_TBLOCOM100_500 m
              where (m.BDCODQUADRO = IIF(:prCODQUADRO = 15,11,29))
                and m.BDCODMATRIZ = :prCODEMP
                and m.BDREFERENCIA = :prREFERENCIA
                AND M.BDRETIFICADORA = :PRRETIFICADORA
                and m.BDVL_CRED_DESC > 0
                AND IIF(:WNAOUTILIZARCRE = 'TRUE', m.BDCODCRE_4_3_6 NOT IN (20, 21, 22, 23, 24, 25, 26, 27), TRUE)
                AND IIF(:WNAOUTILIZARCRED_201_208 = 'TRUE', M.BDCODCRE_4_3_6 NOT IN (11, 12, 13, 14, 15, 16, 17, 18), TRUE)
              group by m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDTIPOPROD, m.BDIND_CRED_ORI,m.bdaliq
              into :wCODEMP, :wCODMATRIZ, :wCHAVE, :wCODCRE_4_3_6, :wTIPOPROD, :wIND_CRED_ORI,:waliq, :wVLR
      do
      begin
        --Zera os créditos descontados do M100 e joga tudo pra saldo...
        update VEF_EMP_TBLOCOM100_500 M
        set M.BDIND_DESC_CRED = 1,
            M.BDVL_CRED_DESC = 0,
            M.BDSLD_CRED = M.BDVL_CRED_DISP
        where (M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 11, 29)) and
              M.BDCODCRE_4_3_6 = :WCODCRE_4_3_6 and
              coalesce(M.BDTIPOPROD, 0) = coalesce(:WTIPOPROD, 0) and
              M.BDIND_CRED_ORI = :WIND_CRED_ORI and
              M.BDCODEMP = :WCODEMP and
              M.BDCODMATRIZ = :WCODMATRIZ and
              M.BDREFERENCIA = :PRREFERENCIA and
              M.BDRETIFICADORA = :PRRETIFICADORA;

        /* Cria lançamento de implantação de saldos, aqui verifica se já existem lançamentos de Saldos */
        select count(*)
        from VEF_EMP_TBLOCOM1100_1500 M
        where M.BDCODPERIODO = 7 and
              M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 52, 53) and
              M.BDCODEMP = :WCODEMP and
              M.BDCODMATRIZ = :WCODMATRIZ and
              M.BDREFERENCIA = :PRREFERENCIA and
              M.BDPER_APU_CRED = :PRREFERENCIA and
              M.BDCODCRE_4_3_6 = :WCODCRE_4_3_6 and
              coalesce(M.BDTIPOPROD, 0) = coalesce(:WTIPOPROD, 0) and
              M.BDORIG_CRED = :WIND_CRED_ORI and
              ((M.BDALIQ = :WALIQ) or (M.BDALIQ = 9999)) and
              M.BDRETIFICADORA = :PRRETIFICADORA
        into :WQTD;

        if (:WQTD > 0) then
        begin
          update VEF_EMP_TBLOCOM1100_1500 M
          set M.BDVL_CRED_APU = M.BDVL_CRED_APU + :WVLR,
              M.BDVL_CRED_DESC_EFD = M.BDVL_CRED_DESC_EFD,
              M.BDSLD_CRED_FIM = M.BDSLD_CRED_FIM + :WVLR
          where M.BDCODPERIODO = 7 and
                M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 52, 53) and
                M.BDCODEMP = :WCODEMP and
                M.BDCODMATRIZ = :WCODMATRIZ and
                M.BDREFERENCIA = :PRREFERENCIA and
                M.BDPER_APU_CRED = :PRREFERENCIA and
                M.BDCODCRE_4_3_6 = :WCODCRE_4_3_6 and
                coalesce(M.BDTIPOPROD, 0) = coalesce(:WTIPOPROD, 0) and
                M.BDORIG_CRED = :WIND_CRED_ORI and
                ((M.BDALIQ = :WALIQ) or (M.BDALIQ = 9999)) and
                M.BDRETIFICADORA = :PRRETIFICADORA;
        end
        else
        begin
                insert into VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDTIPOPROD, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC,bdaliq, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM, BDRETIFICADORA)
                                              values (IIF(:prCODQUADRO = 15,52,53), -- 1100 - Controle de créditos fiscais PIS/PASEP | 1500 - Controle de créditos fiscais Cofins
                                                      GETORDEMSEQUENCIAL_STR('11001500.'||7||'.'||:wCODEMP||'.'||:wCODMATRIZ||'.'||IIF(:prCODQUADRO = 15,52,53)||'.'||:prREFERENCIA, :PRCODEMP),
                                                      7, :wCODEMP, :wCODMATRIZ, :prREFERENCIA, :wCODCRE_4_3_6, :wTIPOPROD, :prREFERENCIA, :wIND_CRED_ORI, '  .   .   /    -',:waliq, :wVLR, 0, :wVLR, :PRRETIFICADORA);
              END
     END
  END
      ELSE
        BEGIN
          FOR
              SELECT m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDTIPOPROD, m.BDIND_CRED_ORI,m.bdaliq,
                     SUM(COALESCE(m.BDVL_CRED_DESC, 0)) as BDVALOR
              FROM VEF_EMP_TBLOCOM100_500 m
              WHERE (m.BDCODQUADRO = IIF(:prCODQUADRO = 15,11,29))
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
                AND m.BDVL_CRED_DESC > 0
                AND M.BDRETIFICADORA = :PRRETIFICADORA
                and (:wordenacred <> 'TRUE')
                and IIF(:WNAOUTILIZARCRE = 'TRUE', M.BDCODCRE_4_3_6 NOT IN (20, 21, 22, 23, 24, 25, 26, 27), TRUE)
                and IIF(:WNAOUTILIZARCRED_201_208 = 'TRUE', M.BDCODCRE_4_3_6 NOT IN (11, 12, 13, 14, 15, 16, 17, 18), TRUE)
              group by m.BDCODEMP, m.BDCODMATRIZ, m.BDCHAVE, m.BDCODCRE_4_3_6, m.BDTIPOPROD, m.BDIND_CRED_ORI,m.bdaliq
              into :wCODEMP, :wCODMATRIZ, :wCHAVE, :wCODCRE_4_3_6, :wTIPOPROD, :wIND_CRED_ORI,:waliq, :wVLR
      do
      begin
        if ((select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD) > 0) then
        begin
          /* Se o valor do crédito for maior que o valor do débito então este valor deve ser levado como saldo credor no registro 1300. */
          if (:WVLR < (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD)) then
          begin
            WVLRSLD = 0;
            update TMP_TBLOCOM_CONTR_TEMP
            set BDVL_CONT_PER = (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD) - :WVLR
            where BDTIPOPROD = :WTIPOPROD;
            WIND_DESC_CRED = 0; --0 - Utilização do valor total para desconto da contribuição apurada no período, no Registro M200;
          end
          else
          begin
            /* Caso tenha mais débitos que créditos, abate apenas apenas os créditos possíveis do lançamento... */
            WVLRSLD = :WVLR - (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD);
            WVLR = :WVLR - :WVLRSLD;
            update TMP_TBLOCOM_CONTR_TEMP
            set BDVL_CONT_PER = 0
            where BDTIPOPROD = :WTIPOPROD;
            WIND_DESC_CRED = 1; --1 - Utilização de valor parcial para desconto da contribuição apurada no período, no Registro M200.
          end

                update VEF_EMP_TBLOCOM100_500 m
                set m.BDIND_DESC_CRED = :wIND_DESC_CRED,
                    m.BDVL_CRED_DESC  = :wvlr,
                    m.BDSLD_CRED      = :wVLRSLD
                where (m.BDCODQUADRO = IIF(:prCODQUADRO = 15,11,29))
                  and m.BDCODEMP = :wCODEMP
                  and m.BDCODMATRIZ = :wCODMATRIZ
                  and m.BDCHAVE = :wCHAVE
                  and m.BDREFERENCIA = :prREFERENCIA
                  and m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  and COALESCE(m.BDTIPOPROD,0) = COALESCE(:wTIPOPROD,0)
                  and m.BDIND_CRED_ORI = :wIND_CRED_ORI
                  AND M.BDRETIFICADORA = :PRRETIFICADORA;

          if (WVLRSLD > 0) then
          begin
            select count(*)
            from VEF_EMP_TBLOCOM1100_1500 M
            where M.BDCODPERIODO = 7 and
                  M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 52, 53) and
                  M.BDCODEMP = :WCODEMP and
                  M.BDCODMATRIZ = :WCODMATRIZ and
                  M.BDREFERENCIA = :PRREFERENCIA and
                  M.BDPER_APU_CRED = :PRREFERENCIA and
                  M.BDCODCRE_4_3_6 = :WCODCRE_4_3_6 and
                  coalesce(M.BDTIPOPROD, 0) = coalesce(:WTIPOPROD, 0) and
                  M.BDORIG_CRED = :WIND_CRED_ORI and
                  ((M.BDALIQ = :WALIQ) or (M.BDALIQ = 9999)) and
                  M.BDRETIFICADORA = :PRRETIFICADORA
            into :WQTD;

            if (:WQTD > 0) then
            begin
              update VEF_EMP_TBLOCOM1100_1500 M
              set M.BDVL_CRED_APU = M.BDVL_CRED_APU + :WVLR,
                  M.BDVL_CRED_DESC_EFD = M.BDVL_CRED_DESC_EFD,
                  M.BDSLD_CRED_FIM = M.BDSLD_CRED_FIM + :WVLR
              where M.BDCODPERIODO = 7 and
                    M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 52, 53) and
                    M.BDCODEMP = :WCODEMP and
                    M.BDCODMATRIZ = :WCODMATRIZ and
                    M.BDREFERENCIA = :PRREFERENCIA and
                    M.BDPER_APU_CRED = :PRREFERENCIA and
                    M.BDCODCRE_4_3_6 = :WCODCRE_4_3_6 and
                    coalesce(M.BDTIPOPROD, 0) = coalesce(:WTIPOPROD, 0) and
                    M.BDORIG_CRED = :WIND_CRED_ORI and
                    ((M.BDALIQ = :WALIQ) or (M.BDALIQ = 9999)) and
                    M.BDRETIFICADORA = :PRRETIFICADORA;
            end
            else
            begin
              insert into VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDTIPOPROD, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDALIQ, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM, BDRETIFICADORA)
              values (iif(:PRCODQUADRO = 15, 52, 53), GETORDEMSEQUENCIAL_STR('11001500.' || 7 || '.' || :WCODEMP || '.' || :WCODMATRIZ || '.' || iif(:PRCODQUADRO = 15, 52, 53) || '.' || :PRREFERENCIA, :PRCODEMP),
                      7, :WCODEMP, :WCODMATRIZ, :PRREFERENCIA, :WCODCRE_4_3_6, :WTIPOPROD, :PRREFERENCIA, :WIND_CRED_ORI, '  .   .   /    -', :WALIQ, (:WVLR + :WVLRSLD), :WVLR, :WVLRSLD, :PRRETIFICADORA);
            end
          end

          WVLRAUX = 0;
          select coalesce(BDVALOR, 0)
          from VEF_EMP_TBLOCOMGERREG
          where BDCODMATRIZ = :PRCODEMP and
                BDREFERENCIA = :PRREFERENCIA and
                BDRETIFICADORA = :PRRETIFICADORA and
                BDCODQUADRO = :PRCODQUADRO and
                BDNUMCAMPO = 3
          into WVLRAUX;

          if (WVLRAUX is null) then
            WVLRAUX = 0;

          update or insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
          values (7, :PRCODEMP, :PRCODEMP, :PRREFERENCIA, :PRCODQUADRO, 3, coalesce(:WVLR + :WVLRAUX, 0), :PRRETIFICADORA)
          matching (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDRETIFICADORA);
        end
        else
        begin
                update VEF_EMP_TBLOCOM100_500 m
                set m.BDIND_DESC_CRED = 1,
                    m.BDVL_CRED_DESC  = 0,
                    m.BDSLD_CRED      = m.BDVL_CRED_DISP
                where (m.BDCODQUADRO = IIF(:prCODQUADRO = 15,11,29))
                  and m.BDCODCRE_4_3_6 = :wCODCRE_4_3_6
                  and COALESCE(m.BDTIPOPROD,0) = COALESCE(:wTIPOPROD,0)
                  and m.BDIND_CRED_ORI = :wIND_CRED_ORI
                  and m.BDCODEMP = :wCODEMP
                  and m.BDCODMATRIZ = :wCODMATRIZ
                  and m.BDREFERENCIA = :prREFERENCIA
                  and m.BDCHAVE = :wCHAVE
                  AND M.BDRETIFICADORA = :PRRETIFICADORA;
          
          /* Cria lançamento de implantação de saldos, aqui verifica se já existem lançamentos de Saldos */
          select count(*)
          from VEF_EMP_TBLOCOM1100_1500 M
          where M.BDCODPERIODO = 7 and
                M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 52, 53) and
                M.BDCODEMP = :WCODEMP and
                M.BDCODMATRIZ = :WCODMATRIZ and
                M.BDREFERENCIA = :PRREFERENCIA and
                M.BDPER_APU_CRED = :PRREFERENCIA and
                M.BDCODCRE_4_3_6 = :WCODCRE_4_3_6 and
                coalesce(M.BDTIPOPROD, 0) = coalesce(:WTIPOPROD, 0) and
                M.BDORIG_CRED = :WIND_CRED_ORI and
                ((M.BDALIQ = :WALIQ) or (M.BDALIQ = 9999)) and
                M.BDRETIFICADORA = :PRRETIFICADORA
          into :WQTD;

          if (:WQTD > 0) then
          begin
            /* Caso tenha registros atualiza */
            update VEF_EMP_TBLOCOM1100_1500 M
            set M.BDVL_CRED_APU = M.BDVL_CRED_APU + :WVLR,
                M.BDVL_CRED_DESC_EFD = M.BDVL_CRED_DESC_EFD,
                M.BDSLD_CRED_FIM = M.BDSLD_CRED_FIM + :WVLR
            where M.BDCODPERIODO = 7 and
                  M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 52, 53) and
                  M.BDCODEMP = :WCODEMP and
                  M.BDCODMATRIZ = :WCODMATRIZ and
                  M.BDREFERENCIA = :PRREFERENCIA and
                  M.BDPER_APU_CRED = :PRREFERENCIA and
                  M.BDCODCRE_4_3_6 = :WCODCRE_4_3_6 and
                  coalesce(M.BDTIPOPROD, 0) = coalesce(:WTIPOPROD, 0) and
                  M.BDORIG_CRED = :WIND_CRED_ORI and
                  ((M.BDALIQ = :WALIQ) or (M.BDALIQ = 9999)) and
                  M.BDRETIFICADORA = :PRRETIFICADORA;
          end
          else
          begin
            /* Caso não tenha lançamento de saldos insere */
            insert into VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDTIPOPROD, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDALIQ, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM, BDRETIFICADORA)
            values (iif(:PRCODQUADRO = 15, 52, 53), GETORDEMSEQUENCIAL_STR('11001500.' || 7 || '.' || :WCODEMP || '.' || :WCODMATRIZ || '.' || iif(:PRCODQUADRO = 15, 52, 53) || '.' || :PRREFERENCIA, :PRCODEMP),
                    7, :WCODEMP, :WCODMATRIZ, :PRREFERENCIA, :WCODCRE_4_3_6, :WTIPOPROD, :PRREFERENCIA, :WIND_CRED_ORI, '  .   .   /    -', :WALIQ, :WVLR, 0, :WVLR, :PRRETIFICADORA);
          end
        end
      end
    end

    /* 04 - VL_TOT_CRED_DESC_ANT - Valor do Crédito Descontado, Apurado em Período de Apuração Anterior (recuperado do campo 13 do Registro 1100) */
    WVLR = 0;
    if (:WCREDITOSPERANT = 'TRUE') then /* Apenas se estiver configurada a opção "Aproveitar o crédito de PIS e Cofins de períodos anteriores" */
    begin
      WVLR = WVLRCREDPERANT_TOTAL;
          IF ((:WVLR = 0) AND (:WCREDITOSPERANT = 'TRUE') AND (:WORDENACRED = 'TRUE')) THEN
          BEGIN
            SELECT SUM(BDVL_CRED_DISP) BDVL_CRED_DISP, SUM(BDVL_CRED_DESC) BDVL_CRED_DESC
            FROM VEF_EMP_TBLOCOM100_500 m
            WHERE (m.BDCODQUADRO = IIF(:prCODQUADRO = 15,11,29))
                AND m.BDCODMATRIZ = :prCODEMP
                AND m.BDREFERENCIA = :prREFERENCIA
                AND M.BDRETIFICADORA = :PRRETIFICADORA
                and IIF(:WNAOUTILIZARCRE = 'TRUE', M.BDCODCRE_4_3_6 NOT IN (20, 21, 22, 23, 24, 25, 26, 27), TRUE)
                and IIF(:WNAOUTILIZARCRED_201_208 = 'TRUE', M.BDCODCRE_4_3_6 NOT IN (11, 12, 13, 14, 15, 16, 17, 18), TRUE)
            INTO :WVL_CRED_DISP, :WVL_CRED_DESC;

        if (:WVL_CRED_DISP > (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD)) then
        begin
          :WVL_CRED_SLD = :WVL_CRED_DISP - (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD);

          update VEF_EMP_TBLOCOM100_500 M
          set M.BDVL_CRED_DESC = (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD),
              M.BDSLD_CRED = :WVL_CRED_SLD
          where (M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 11, 29)) and
                M.BDCODEMP = :PRCODEMP and
                M.BDCODMATRIZ = :PRCODEMP and
                M.BDREFERENCIA = :PRREFERENCIA and
                M.BDRETIFICADORA = :PRRETIFICADORA;
        end
        else
        begin
          :WVL_CRED_SLD = 0;
          update VEF_EMP_TBLOCOM100_500 M
          set M.BDVL_CRED_DESC = :WVL_CRED_DISP,
              M.BDSLD_CRED = 0
          where (M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 11, 29)) and
                M.BDCODEMP = :PRCODEMP and
                M.BDCODMATRIZ = :PRCODEMP and
                M.BDREFERENCIA = :PRREFERENCIA and
                M.BDRETIFICADORA = :PRRETIFICADORA;
        end
      end
    end
    else
    begin
      WVLRCREDPERANT_TOTAL = 0;
      for select M.BDCODPERIODO, M.BDCODEMP, M.BDCODMATRIZ, M.BDCODQUADRO, M.BDCHAVE, M.BDREFERENCIA, M.BDPER_APU_CRED, M.BDCODCRE_4_3_6, M.BDTIPOPROD, M.BDIND_CRED_ORI, M.BDALIQ, M.BDVALOR
          from (select M.BDCODPERIODO, M.BDCODEMP, M.BDCODMATRIZ, M.BDCODQUADRO, 0 BDCHAVE, M.BDREFERENCIA, M.BDPER_APU_CRED, M.BDCODCRE_4_3_6, M.BDTIPOPROD, M.BDORIG_CRED as BDIND_CRED_ORI, M.BDALIQ,
                       sum(coalesce(M.BDSLD_CRED_FIM, 0)) as BDVALOR, REG.BDCODEXPCRE, iif(REG.BDCODEXPCRE in ('108', '201', '202', '203', '204', '208', '301', '302', '303', '304', '307', '308'), 2, 1) as BDORG
                from VEF_EMP_TBLOCOM1100_1500 M
                left outer join VEF_BASE_TTAB_4_3_6 REG on (M.BDCODCRE_4_3_6 = REG.BDCODCRE_4_3_6)
                where (M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 52, 53)) and
                      (M.BDCODMATRIZ = :PRCODEMP) and
                      (M.BDREFERENCIA = :PRREFERENCIA) and
                      (M.BDRETIFICADORA = :PRRETIFICADORA)
                      and (((M.BDVL_RESSARCIMENTO > 0)
                      and (:WABATERESSARCIM <> 'TRUE')) or (M.BDVL_RESSARCIMENTO = 0))
                      and IIF(:WNAOUTILIZARCRE = 'TRUE', m.BDCODCRE_4_3_6 NOT IN (20, 21, 22, 23, 24, 25, 26, 27), TRUE)
                      and IIF(:WNAOUTILIZARCRED_201_208 = 'TRUE', M.BDCODCRE_4_3_6 NOT IN (11, 12, 13, 14, 15, 16, 17, 18), TRUE)
                group by M.BDCODPERIODO, M.BDCODEMP, M.BDCODMATRIZ, M.BDCODQUADRO, BDCHAVE, M.BDREFERENCIA, M.BDPER_APU_CRED, M.BDCODCRE_4_3_6, M.BDTIPOPROD,
                       BDIND_CRED_ORI, M.BDALIQ, REG.BDCODEXPCRE
                union all
                select 7 BDCODPERIODO, CRED.BDCODEMP, CRED.BDCODMATRIZ, CRED.BDCODQUADRO, CRED.BDCHAVE, CRED.BDREFERENCIA, CRED.BDREFERENCIA as BDPER_APU_CRED, CRED.BDCODCRE_4_3_6, CRED.BDTIPOPROD,
                       CRED.BDIND_CRED_ORI, CRED.BDALIQ, sum(coalesce(CRED.BDVL_CRED_DESC, 0)) as BDVALOR, REG.BDCODEXPCRE, iif(REG.BDCODEXPCRE in ('108', '201', '202', '203', '204', '208', '301', '302', '303', '304', '307', '308'), 2, 1) as BDORG
                from VEF_EMP_TBLOCOM100_500 CRED
                left outer join VEF_BASE_TTAB_4_3_6 REG on (cred.BDCODCRE_4_3_6 = REG.BDCODCRE_4_3_6)
                where (cred.BDCODQUADRO = IIF(:prCODQUADRO = 15,11,29))
                      and cred.BDCODMATRIZ = :prCodEmp
                      and cred.BDREFERENCIA = :PRREFERENCIA
                      AND (cred.BDRETIFICADORA = :PRRETIFICADORA)
                      and (:WORDENACRED = 'TRUE')
                      and IIF(:WNAOUTILIZARCRE = 'TRUE', CRED.BDCODCRE_4_3_6 NOT IN (20, 21, 22, 23, 24, 25, 26, 27), TRUE)
                      and IIF(:WNAOUTILIZARCRED_201_208 = 'TRUE', CRED.BDCODCRE_4_3_6 NOT IN (11, 12, 13, 14, 15, 16, 17, 18), TRUE)
                group by BDCODPERIODO, CRED.BDCODEMP, CRED.BDCODMATRIZ, CRED.BDCODQUADRO, CRED.BDCHAVE, CRED.BDREFERENCIA, BDPER_APU_CRED, CRED.BDCODCRE_4_3_6, CRED.BDTIPOPROD,
                       CRED.BDIND_CRED_ORI, CRED.BDALIQ, REG.BDCODEXPCRE
                
              ) m
              order by iif(:WORDENACRED = 'TRUE', m.BDORG, M.BDCODMATRIZ),  M.BDPER_APU_CRED desc
            into :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wchave, :wREFERENCIA, :wPER_APU_CRED, :wCODCRE_4_3_6, :wTIPOPROD, :wIND_CRED_ORI, :waliq, :wVLRCREDPERANT
      do
      begin
        if (((select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD) > 0) and (:WVLRCREDPERANT > 0)) then
        begin
          if ((select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD) < :WVLRCREDPERANT) then --Caso o valor da contribuição seja menor que o crédito anterior, apenas abate esse valor...
          begin
            WVLRSLD = :WVLRCREDPERANT - (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD);
            WVLR = (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD);
            update TMP_TBLOCOM_CONTR_TEMP
            set BDVL_CONT_PER = 0
            where BDTIPOPROD = :WTIPOPROD;
            WIND_DESC_CRED = 1;
          end
          else
                  begin
                    wVLR = :wVLRCREDPERANT;
                    UPDATE TMP_TBLOCOM_CONTR_TEMP
                    SET BDVL_CONT_PER = (SELECT BDVL_CONT_PER FROM TMP_TBLOCOM_CONTR_TEMP WHERE BDTIPOPROD = :wTIPOPROD) - :wVLRCREDPERANT
                    WHERE BDTIPOPROD = :wTIPOPROD;
                    wind_desc_cred = 0;
                    wvlrsld = 0;
          end

          if (:WPER_APU_CRED <> PRREFERENCIA) then
            WVLRCREDPERANT_TOTAL = WVLRCREDPERANT_TOTAL + WVLR;

          if ((:WPER_APU_CRED = PRREFERENCIA) and (:WORDENACRED = 'TRUE')) then
          begin
            update VEF_EMP_TBLOCOM100_500 M
            set M.BDIND_DESC_CRED = :WIND_DESC_CRED,
                M.BDVL_CRED_DESC = :WVLR,
                M.BDSLD_CRED = :WVLRSLD
            where (M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 11, 29)) and
                  M.BDCODEMP = :WCODEMP and
                  M.BDCODMATRIZ = :WCODMATRIZ and
                  M.BDCHAVE = :WCHAVE and
                  M.BDREFERENCIA = :PRREFERENCIA and
                  M.BDRETIFICADORA = :PRRETIFICADORA and
                  M.BDCODCRE_4_3_6 = :WCODCRE_4_3_6 and
                  coalesce(M.BDTIPOPROD, 0) = coalesce(:WTIPOPROD, 0) and
                  M.BDIND_CRED_ORI = :WIND_CRED_ORI;

            if (WVLRSLD > 0) then
            begin
              select count(*)
              from VEF_EMP_TBLOCOM1100_1500 M
              where M.BDCODPERIODO = 7 and
                    M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 52, 53) and
                    M.BDCODEMP = :WCODEMP and
                    M.BDCODMATRIZ = :WCODMATRIZ and
                    M.BDREFERENCIA = :PRREFERENCIA and
                    M.BDRETIFICADORA = :PRRETIFICADORA and
                    M.BDPER_APU_CRED = :PRREFERENCIA and
                    M.BDCODCRE_4_3_6 = :WCODCRE_4_3_6 and
                    coalesce(M.BDTIPOPROD, 0) = coalesce(:WTIPOPROD, 0) and
                    M.BDORIG_CRED = :WIND_CRED_ORI and
                    ((M.BDALIQ = :WALIQ) or (M.BDALIQ = 9999))
              into :WQTD;

              if (:WQTD > 0) then
              begin
                update VEF_EMP_TBLOCOM1100_1500 M
                set M.BDVL_CRED_APU = M.BDVL_CRED_APU + :WVLRCREDPERANT,
                    M.BDVL_CRED_DESC_EFD = M.BDVL_CRED_DESC_EFD,
                    M.BDSLD_CRED_FIM = M.BDSLD_CRED_FIM + :WVLR
                where M.BDCODPERIODO = 7 and
                      M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 52, 53) and
                      M.BDCODEMP = :WCODEMP and
                      M.BDCODMATRIZ = :WCODMATRIZ and
                      M.BDREFERENCIA = :PRREFERENCIA and
                      M.BDPER_APU_CRED = :PRREFERENCIA and
                      M.BDRETIFICADORA = :PRRETIFICADORA and
                      M.BDCODCRE_4_3_6 = :WCODCRE_4_3_6 and
                      coalesce(M.BDTIPOPROD, 0) = coalesce(:WTIPOPROD, 0) and
                      M.BDORIG_CRED = :WIND_CRED_ORI and
                      ((M.BDALIQ = :WALIQ) or (M.BDALIQ = 9999));
              end
              else
              begin
                insert into VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDTIPOPROD, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDALIQ, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM, BDRETIFICADORA)
                values (iif(:PRCODQUADRO = 15, 52, 53), GETORDEMSEQUENCIAL_STR('11001500.' || 7 || '.' || :WCODEMP || '.' || :WCODMATRIZ || '.' || iif(:PRCODQUADRO = 15, 52, 53) || '.' || :PRREFERENCIA, :PRCODEMP),
                        7, :WCODEMP, :WCODMATRIZ, :PRREFERENCIA, :WCODCRE_4_3_6, :WTIPOPROD, :PRREFERENCIA, :WIND_CRED_ORI, '  .   .   /    -', :WALIQ, (:WVLR + :WVLRSLD), :WVLR, :WVLRSLD, :PRRETIFICADORA);
              end
            end

            WVLRAUX = 0;
            select coalesce(BDVALOR, 0)
            from VEF_EMP_TBLOCOMGERREG
            where BDCODMATRIZ = :PRCODEMP and
                  BDREFERENCIA = :PRREFERENCIA and
                  BDRETIFICADORA = :PRRETIFICADORA and
                  BDCODQUADRO = :PRCODQUADRO and
                  BDNUMCAMPO = 3
            into WVLRAUX;

            if (WVLRAUX is null) then
              WVLRAUX = 0;

            update or insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
            values (7, :PRCODEMP, :PRCODEMP, :PRREFERENCIA, :PRCODQUADRO, 3, coalesce(:WVLR + :WVLRAUX, 0), :PRRETIFICADORA)
            matching (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDRETIFICADORA);
          end
          else
          begin
            update VEF_EMP_TBLOCOM1100_1500 M
            set M.BDVL_CRED_DESC_EFD = :WVLR,
                M.BDSLD_CRED_FIM = M.BDSLD_CRED_FIM - :WVLR
            where M.BDCODPERIODO = :WCODPERIODO and
                  M.BDCODQUADRO = :WCODQUADRO and
                  M.BDCODEMP = :WCODEMP and
                  M.BDCODMATRIZ = :WCODMATRIZ and
                  M.BDREFERENCIA = :WREFERENCIA and
                  M.BDPER_APU_CRED = :WPER_APU_CRED and
                  M.BDCODCRE_4_3_6 = :WCODCRE_4_3_6 and
                  coalesce(M.BDTIPOPROD, 0) = coalesce(:WTIPOPROD, 0) and
                  M.BDORIG_CRED = :WIND_CRED_ORI and
                  ((M.BDALIQ = :WALIQ) or (M.BDALIQ = 9999)) and
                  M.BDRETIFICADORA = :PRRETIFICADORA;
          end
        end
        else
        begin
          if ((:WPER_APU_CRED = PRREFERENCIA) and (:WORDENACRED = 'TRUE')) then
          begin
            --Zera os créditos descontados do M100 e joga tudo pra saldo...
            update VEF_EMP_TBLOCOM100_500 M
            set M.BDIND_DESC_CRED = 1,
                M.BDVL_CRED_DESC = 0,
                M.BDSLD_CRED = M.BDVL_CRED_DISP
            where (M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 11, 29)) and
                  M.BDCODCRE_4_3_6 = :WCODCRE_4_3_6 and
                  coalesce(M.BDTIPOPROD, 0) = coalesce(:WTIPOPROD, 0) and
                  M.BDIND_CRED_ORI = :WIND_CRED_ORI and
                  M.BDCODEMP = :WCODEMP and
                  M.BDCODMATRIZ = :WCODMATRIZ and
                  M.BDREFERENCIA = :PRREFERENCIA and
                  M.BDRETIFICADORA = :PRRETIFICADORA and
                  M.BDCHAVE = :WCHAVE;

            /* Cria lançamento de implantação de saldos, aqui verifica se já existem lançamentos de Saldos */
            select count(*)
            from VEF_EMP_TBLOCOM1100_1500 M
            where M.BDCODPERIODO = 7 and
                  M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 52, 53) and
                  M.BDCODEMP = :WCODEMP and
                  M.BDCODMATRIZ = :WCODMATRIZ and
                  M.BDREFERENCIA = :PRREFERENCIA and
                  M.BDPER_APU_CRED = :PRREFERENCIA and
                  M.BDRETIFICADORA = :PRRETIFICADORA and
                  M.BDCODCRE_4_3_6 = :WCODCRE_4_3_6 and
                  coalesce(M.BDTIPOPROD, 0) = coalesce(:WTIPOPROD, 0) and
                  M.BDORIG_CRED = :WIND_CRED_ORI and
                  ((M.BDALIQ = :WALIQ) or (M.BDALIQ = 9999))
            into :WQTD;

            if (:WQTD > 0) then
            begin
              /* Caso tenha registros atualiza */
              update VEF_EMP_TBLOCOM1100_1500 M
              set M.BDVL_CRED_APU = M.BDVL_CRED_APU + :WVLRCREDPERANT,
                  M.BDVL_CRED_DESC_EFD = M.BDVL_CRED_DESC_EFD,
                  M.BDSLD_CRED_FIM = M.BDSLD_CRED_FIM + :WVLRCREDPERANT
              where M.BDCODPERIODO = 7 and
                    M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 52, 53) and
                    M.BDCODEMP = :WCODEMP and
                    M.BDCODMATRIZ = :WCODMATRIZ and
                    M.BDREFERENCIA = :PRREFERENCIA and
                    M.BDPER_APU_CRED = :PRREFERENCIA and
                    M.BDRETIFICADORA = :PRRETIFICADORA and
                    M.BDCODCRE_4_3_6 = :WCODCRE_4_3_6 and
                    coalesce(M.BDTIPOPROD, 0) = coalesce(:WTIPOPROD, 0) and
                    M.BDORIG_CRED = :WIND_CRED_ORI and
                    ((M.BDALIQ = :WALIQ) or (M.BDALIQ = 9999));
            end
            else
            begin
              /* Caso não tenha lançamento de saldos insere */
              insert into VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCHAVE, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCRE_4_3_6, BDTIPOPROD, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC, BDALIQ, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM, BDRETIFICADORA)
              values (iif(:PRCODQUADRO = 15, 52, 53), GETORDEMSEQUENCIAL_STR('11001500.' || 7 || '.' || :WCODEMP || '.' || :WCODMATRIZ || '.' || iif(:PRCODQUADRO = 15, 52, 53) || '.' || :PRREFERENCIA, :PRCODEMP),
                      7, :WCODEMP, :WCODMATRIZ, :PRREFERENCIA, :WCODCRE_4_3_6, :WTIPOPROD, :PRREFERENCIA, :WIND_CRED_ORI, '  .   .   /    -', :WALIQ, :WVLRCREDPERANT, 0, :WVLRCREDPERANT, :PRRETIFICADORA);
            end
          end
        end
      end
      WVLR = WVLRCREDPERANT_TOTAL;
    end

    insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
    values (7, :PRCODEMP, :PRCODEMP, :PRREFERENCIA, :PRCODQUADRO, 4, coalesce(:WVLR, 0), :PRRETIFICADORA);

      if ((:wCREDITOSPERANT = 'TRUE') and
          (:wORDENACRED = 'TRUE')) then
        begin
          :wQTD = 0;
          select COUNT(BDCODEMP)
      from VEF_EMP_TBLOCOMGERREG
      where BDCODMATRIZ = :PRCODEMP and
            BDREFERENCIA = :PRREFERENCIA and
            BDRETIFICADORA = :PRRETIFICADORA and
            BDCODQUADRO = :PRCODQUADRO and
            BDNUMCAMPO = 3
      into :WQTD;

      if ((:WQTD = 0) or (:WQTD is null)) then
      begin
        :WVLR = 0;
        :WVLR_CRED_TOTAL_DESC_PERIODO = 0;
                FOR
                    SELECT BDCODEMP, BDCHAVE, BDCODCRE_4_3_6, BDTIPOPROD, BDIND_CRED_ORI, SUM(BDVL_CRED_DISP) BDVL_CRED_DISP, SUM(BDVL_CRED_DESC) BDVL_CRED_DESC
                    FROM VEF_EMP_TBLOCOM100_500 m
                    WHERE (m.BDCODQUADRO = IIF(:prCODQUADRO = 15,11,29))
                        AND m.BDCODMATRIZ = :prCODEMP
                        AND m.BDREFERENCIA = :prREFERENCIA
                        AND M.BDRETIFICADORA = :PRRETIFICADORA
                        AND IIF(:WNAOUTILIZARCRE = 'TRUE', m.BDCODCRE_4_3_6 NOT IN (20, 21, 22, 23, 24, 25, 26, 27), TRUE)
                        AND IIF(:WNAOUTILIZARCRED_201_208 = 'TRUE', M.BDCODCRE_4_3_6 NOT IN (11, 12, 13, 14, 15, 16, 17, 18), TRUE)
                    GROUP BY BDCODEMP, BDCHAVE, BDCODCRE_4_3_6, BDTIPOPROD, BDIND_CRED_ORI
                    INTO :wCODEMP, :WCHAVE, :WCODCRE_4_3_6, :wTIPOPROD, :WIND_CRED_ORI, :WVL_CRED_DISP, :WVL_CRED_DESC
                DO
                BEGIN
          --Matheus Amaral - Vê o quanto de crédito foi descontado e atualiza o m100 alterando o crédito disponível. XXX
          if ((select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD) > :WVL_CRED_DISP) then
          begin
            :WVLR = (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD) - ((select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD) - :WVL_CRED_DISP);
            :WVLR_CRED_TOTAL_DESC_PERIODO = :WVLR_CRED_TOTAL_DESC_PERIODO + :WVLR;

            if (:WVLR_CRED_TOTAL_DESC_PERIODO > (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD)) then --Alt.: #170034 - Deve se apropriar de no maximos os creditos que tiver no mes, caso contr??rio pode gerar um valor negativo nos campos 5 e 6
            begin
              :WVLR = :WVLR - (:WVLR_CRED_TOTAL_DESC_PERIODO - (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD));
              :WVLR_CRED_TOTAL_DESC_PERIODO = :WVLR_CRED_TOTAL_DESC_PERIODO - (:WVLR_CRED_TOTAL_DESC_PERIODO - (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD));
              update TMP_TBLOCOM_CONTR_TEMP
              set BDVL_CONT_PER = 0 --Deve zerar para não descontar do 1300/1700
              where BDTIPOPROD = :WTIPOPROD;
            end

            update VEF_EMP_TBLOCOM100_500 M
            set M.BDVL_CRED_DESC = :WVLR,
                M.BDSLD_CRED = iif((select BDVL_CONT_PER
                                    from TMP_TBLOCOM_CONTR_TEMP
                                    where BDTIPOPROD = :WTIPOPROD) <> 0, 0, (M.BDVL_CRED_DISP - :WVLR))
            where (M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 11, 29)) and
                  M.BDCODEMP = :PRCODEMP and
                  M.BDCODMATRIZ = :PRCODEMP and
                  M.BDREFERENCIA = :PRREFERENCIA and
                  M.BDRETIFICADORA = :PRRETIFICADORA and
                  M.BDCHAVE = :WCHAVE and
                  M.BDCODCRE_4_3_6 = :WCODCRE_4_3_6 and
                  coalesce(M.BDTIPOPROD, 0) = coalesce(:WTIPOPROD, 0) and
                  M.BDIND_CRED_ORI = :WIND_CRED_ORI;
          end
          else
          begin
            :WVLR = (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD);
            :WVLR_CRED_TOTAL_DESC_PERIODO = :WVLR_CRED_TOTAL_DESC_PERIODO + :WVLR;

            update VEF_EMP_TBLOCOM100_500 M
            set M.BDVL_CRED_DESC = :WVLR,
                M.BDSLD_CRED = :WVL_CRED_DISP - :WVLR
            where (M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 11, 29)) and
                  M.BDCODEMP = :WCODEMP and
                  M.BDCODMATRIZ = :PRCODEMP and
                  M.BDREFERENCIA = :PRREFERENCIA and
                  M.BDRETIFICADORA = :PRRETIFICADORA and
                  M.BDCHAVE = :WCHAVE and
                  M.BDCODCRE_4_3_6 = :WCODCRE_4_3_6 and
                  coalesce(M.BDTIPOPROD, 0) = coalesce(:WTIPOPROD, 0) and
                  M.BDIND_CRED_ORI = :WIND_CRED_ORI;

            update TMP_TBLOCOM_CONTR_TEMP
            set BDVL_CONT_PER = 0 --Deve zerar para não descontar do 1300/1700
            where BDTIPOPROD = :WTIPOPROD;
          end
        end

        update or insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
        values (7, :PRCODEMP, :PRCODEMP, :PRREFERENCIA, :PRCODQUADRO, 3, coalesce(:WVLR_CRED_TOTAL_DESC_PERIODO, 0), :PRRETIFICADORA)
        matching (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDRETIFICADORA);

              UPDATE TMP_TBLOCOM_CONTR_TEMP
              SET BDVL_CONT_PER = (SELECT BDVL_CONT_PER FROM TMP_TBLOCOM_CONTR_TEMP WHERE BDTIPOPROD = :wTIPOPROD) - :WVLR_CRED_TOTAL_DESC_PERIODO
              WHERE BDTIPOPROD = :wTIPOPROD;
      end
    end

    /* 05 - VL_TOT_CONT_NC_DEV - Valor Total da Contribuição Não Cumulativa Devida (02 - 03 - 04) */
    WVLR = 0;
    select sum(AUX.BDVLRSOMAR - AUX.BDVLRSUB) as BDVALOR
    from (select M.BDCODEMP, M.BDREFERENCIA, coalesce(M.BDVALOR, 0) as BDVLRSOMAR, 0 as BDVLRSUB
          from VEF_EMP_TBLOCOMGERREG M
          where (M.BDCODQUADRO = :PRCODQUADRO) and
                (M.BDNUMCAMPO in (2)) and
                M.BDCODMATRIZ = :PRCODEMP and
                M.BDREFERENCIA = :PRREFERENCIA and
                M.BDRETIFICADORA = :PRRETIFICADORA
          union all
          select M.BDCODEMP, M.BDREFERENCIA, 0 as BDVLRSOMAR, coalesce(M.BDVALOR, 0) as BDVLRSUB
          from VEF_EMP_TBLOCOMGERREG M
          where (M.BDCODQUADRO = :PRCODQUADRO) and
                (M.BDNUMCAMPO in (3, 4)) and
                M.BDCODMATRIZ = :PRCODEMP and
                M.BDREFERENCIA = :PRREFERENCIA and
                M.BDRETIFICADORA = :PRRETIFICADORA) AUX
    into :WVLR;

    insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
    values (7, :PRCODEMP, :PRCODEMP, :PRREFERENCIA, :PRCODQUADRO, 5, coalesce(:WVLR, 0), :PRRETIFICADORA);

    /* 06 - VL_RET_NC - Valor Retido na Fonte Deduzido no Período */
    WVLR = 0;
    WSQL = 'SELECT COUNT(*) as BDQTD ';
    WSQL = WSQL || 'FROM VEF_EMP_TBLOCOM1300_1700 m ';

    if (:PRCODQUADRO = 15) then
      WSQL = WSQL || 'WHERE (m.BDCODQUADRO = 49) ';
    else
      WSQL = WSQL || 'WHERE (m.BDCODQUADRO = 50) ';

    if (WINCTRIB in (3)) then
      WSQL = WSQL || '  AND m.BDCOD_NAT_REC = 0 ';

    WSQL = WSQL || '  AND m.BDCODMATRIZ = ' || :PRCODEMP || ' ';
    WSQL = WSQL || '  AND m.BDREFERENCIA = ' || :PRREFERENCIA || ' ';
    WSQL = WSQL || '  AND m.BDRETIFICADORA = ' || :PRRETIFICADORA || ' ';

    execute statement(WSQL)
    into :WQTD;

    if ((WQTD = 0) or (((select sum(BDVL_CONT_PER) from TMP_TBLOCOM_CONTR_TEMP) is null) or ((select sum(BDVL_CONT_PER) from TMP_TBLOCOM_CONTR_TEMP) = 0))) then
    begin
      insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
      values (7, :PRCODEMP, :PRCODEMP, :PRREFERENCIA, :PRCODQUADRO, 6, coalesce(:WVLR, 0), :PRRETIFICADORA);
    end
    else
    begin
      WSQL = 'SELECT m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, ';
      WSQL = WSQL || ' SUM(COALESCE(m.BDSLD_RET, 0)) as BDVALOR, ';
      WSQL = WSQL || ' IIF((m.BDREFERENCIA = m.BDPR_REC_RET), 0, 1) as BDORDENACAO ';
      WSQL = WSQL || 'FROM VEF_EMP_TBLOCOM1300_1700 m ';

      if (:PRCODQUADRO = 15) then
        WSQL = WSQL || 'WHERE (m.BDCODQUADRO = 49) ';
      else
        WSQL = WSQL || 'WHERE (m.BDCODQUADRO = 50) ';

      if (WINCTRIB in (3)) then
        WSQL = WSQL || '  AND m.BDCOD_NAT_REC = 0 ';

      WSQL = WSQL || '  AND m.BDCODMATRIZ = ' || :PRCODEMP || ' ';
      WSQL = WSQL || '  AND m.BDREFERENCIA = ' || :PRREFERENCIA || ' ';
      WSQL = WSQL || '  AND m.BDRETIFICADORA = ' || :PRRETIFICADORA || ' ';
      WSQL = WSQL || 'GROUP BY m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, m.BDCODQUADRO, m.BDREFERENCIA, m.BDCHAVE, m.BDCOD_NAT_REC, m.BDPR_REC_RET ';

      if (:WRETPISCOFPERANT = 'TRUE') then
        WSQL = WSQL || 'ORDER BY m.BDPR_REC_RET ';
      else --Caso contrário, vai primeiro abater o mês atual e depois os meses anteriores....
        WSQL = WSQL || 'ORDER BY BDORDENACAO, m.BDPR_REC_RET ';

      for execute statement(WSQL)
      into :WCODPERIODO, :WCODEMP, :WCODMATRIZ, :WCODQUADRO, :WREFERENCIA, :WCHAVE, :WCOD_NAT_REC, :WVLR, :WORDENACAO
      do
      begin
        for select BDTIPOPROD
            from TMP_TBLOCOM_CONTR_TEMP
            where BDVL_CONT_PER > 0 and
                  BDTIPOPROD = 0
            order by BDTIPOPROD
            into :WTIPOPROD
        do
        begin
          if (((select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD) > 0) and (:WVLR > 0)) then
          begin
            /* Se o valor do crédito for maior que o valor do débito então este valor deve ser levado como saldo credor no registro 1300. */
            if (:WVLR < (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD)) then
            begin
              WVLRSLD = 0;
              update TMP_TBLOCOM_CONTR_TEMP
              set BDVL_CONT_PER = (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD) - :WVLR
              where BDTIPOPROD = :WTIPOPROD;
            end
            else
            begin
              /* Caso tenha mais débitos que créditos, abate apenas apenas os créditos possíveis do lançamento... */
              WVLRSLD = :WVLR - (select BDVL_CONT_PER from TMP_TBLOCOM_CONTR_TEMP where BDTIPOPROD = :WTIPOPROD);
              WVLR = :WVLR - :WVLRSLD;
              update TMP_TBLOCOM_CONTR_TEMP
              set BDVL_CONT_PER = 0
              where BDTIPOPROD = :WTIPOPROD;
            end

            update VEF_EMP_TBLOCOM1300_1700 M
            set M.BDVL_RET_DED = :WVLR + coalesce((select M.BDVL_RET_DED
                                                   from VEF_EMP_TBLOCOM1300_1700 M
                                                   where M.BDCODPERIODO = :WCODPERIODO and
                                                         M.BDCODEMP = :WCODEMP and
                                                         M.BDCODMATRIZ = :WCODMATRIZ and
                                                         M.BDCODQUADRO = :WCODQUADRO and
                                                         M.BDREFERENCIA = :WREFERENCIA and
                                                         M.BDCHAVE = :WCHAVE and
                                                         M.BDCOD_NAT_REC = :WCOD_NAT_REC and
                                                         M.BDRETIFICADORA = :PRRETIFICADORA), 0),
                M.BDSLD_RET = :WVLRSLD
            where M.BDCODPERIODO = :WCODPERIODO and
                  M.BDCODEMP = :WCODEMP and
                  M.BDCODMATRIZ = :WCODMATRIZ and
                  M.BDCODQUADRO = :WCODQUADRO and
                  M.BDREFERENCIA = :WREFERENCIA and
                  M.BDCHAVE = :WCHAVE and
                  M.BDCOD_NAT_REC = :WCOD_NAT_REC and
                  M.BDRETIFICADORA = :PRRETIFICADORA;

            WVLRAUX = 0;
            select coalesce(BDVALOR, 0)
            from VEF_EMP_TBLOCOMGERREG
            where BDCODMATRIZ = :PRCODEMP and
                  BDREFERENCIA = :PRREFERENCIA and
                  BDRETIFICADORA = :PRRETIFICADORA and
                  BDCODQUADRO = :PRCODQUADRO and
                  BDNUMCAMPO = 6
            into WVLRAUX;

            if (WVLRAUX is null) then
              WVLRAUX = 0;

            update or insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
            values (7, :PRCODEMP, :PRCODEMP, :PRREFERENCIA, :PRCODQUADRO, 6, coalesce(:WVLR + :WVLRAUX, 0), :PRRETIFICADORA)
            matching (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDRETIFICADORA);

            :WVLR = :WVLRSLD;
          end
        end
      end
    end

    /* 07 - VL_OUT_DED_NC - Outras Deduções no Período */
    WVLR = 0;
    select sum(coalesce(iif(:PRCODQUADRO = 15, M.BDVLRPIS, M.BDVLRCOFINS), 0)) as BDVALOR
    from VEF_EMP_TORIDEDF700 M
    where M.BDINDNATDED = 1 and --0 - Dedução de Natureza Não Cumulativa
          M.BDCODEMP in (select EX.BDCODEMP
                         from TEMPRESAS EX
                         where EX.BDCODEMP = :PRCODEMP or EX.BDCODMATRIZ = :PRCODEMP) and
          M.BDREFERENCIA = :PRREFERENCIA
    into :WVLR;

    insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
    values (7, :PRCODEMP, :PRCODEMP, :PRREFERENCIA, :PRCODQUADRO, 7, coalesce(:WVLR, 0), :PRRETIFICADORA);

    /* 08 - VL_CONT_NC_REC - Valor da Contribuição Não Cumulativa a Recolher/Pagar (05 - 06 - 07) */
    WVLR = 0;
    select sum(AUX.BDVLRSOMAR) as BDVALOR, sum(AUX.BDVLRSUB) as BDVALORSUB
    from (select M.BDCODEMP, M.BDREFERENCIA, coalesce(M.BDVALOR, 0) as BDVLRSOMAR, 0 as BDVLRSUB
          from VEF_EMP_TBLOCOMGERREG M
          where (M.BDCODQUADRO = :PRCODQUADRO) and
                (M.BDNUMCAMPO in (5)) and
                M.BDCODMATRIZ = :PRCODEMP and
                M.BDREFERENCIA = :PRREFERENCIA and
                M.BDRETIFICADORA = :PRRETIFICADORA
          union all
          select M.BDCODEMP, M.BDREFERENCIA, 0 as BDVLRSOMAR, coalesce(M.BDVALOR, 0) as BDVLRSUB
          from VEF_EMP_TBLOCOMGERREG M
          where (M.BDCODQUADRO = :PRCODQUADRO) and
                (M.BDNUMCAMPO in (6, 7)) and
                M.BDCODMATRIZ = :PRCODEMP and
                M.BDREFERENCIA = :PRREFERENCIA and
                M.BDRETIFICADORA = :PRRETIFICADORA) AUX
    into :WVLR, :WVLRAUX;

      if ((wVLR - wVLRAUX) >= 0) then -- Se tiver valor de contribuição, calcula os campos a somar e subtrair...
        wVLR = (wVLR - wVLRAUX);
      else
      /* Se o valor do campo 5(Valor Total da Contribuição) menos o valor do campo 6(Valor Retido na Fonte) for menor que zero, então este valor deve ser levado como saldo no registro 1300. */
      if ((wVLR - wVLRAUX) < 0) then
    begin
      update VEF_EMP_TBLOCOMGERREG
      set BDVALOR = :WVLR
      where BDCODMATRIZ = :PRCODEMP and
            BDREFERENCIA = :PRREFERENCIA and
            BDRETIFICADORA = :PRRETIFICADORA and
            BDCODQUADRO = :PRCODQUADRO and
            BDNUMCAMPO = 6;

      /* Caso tenha lançamentos, desconta o valor da contribuição deles */
      for select M.BDCODPERIODO, M.BDCODEMP, M.BDCODMATRIZ, M.BDCODQUADRO, M.BDREFERENCIA, M.BDCHAVE, coalesce(M.BDVL_RET_APU, 0)
          from VEF_EMP_TBLOCOM1300_1700 M
          where (M.BDCODQUADRO = iif(:PRCODQUADRO = 15, 49, 50)) and
                M.BDCODMATRIZ = :PRCODEMP and
                M.BDREFERENCIA = :PRREFERENCIA and
                M.BDRETIFICADORA = :PRRETIFICADORA
          into :WCODPERIODO, :WCODEMP, :WCODMATRIZ, :WCODQUADRO, :WREFERENCIA, :WCHAVE, :WVLRUP
      do
      begin
        if (WVLR > 0) then
        begin
          /* Caso tenha mais débitos que créditos, abate apenas apenas os créditos possíveis do lançamento... */
          if (:WVLRUP < :WVLR) then
          begin
            WVLRUPAUX = :WVLRUP;
            WVLRSLD = 0;
            WVLR = :WVLR - :WVLRUP;/* Crédito já descontado vai ser abatido... */
          end
          else
          begin
            WVLRUPAUX = :WVLR;
            WVLRSLD = :WVLRUP - :WVLR;
          end

          update or insert into VEF_EMP_TBLOCOM1300_1700 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDVL_RET_DED, BDSLD_RET, BDRETIFICADORA)
          values (:WCODPERIODO, :WCODEMP, :WCODMATRIZ, :WCODQUADRO, :WREFERENCIA, :WCHAVE, :WVLRUPAUX, :WVLRSLD, :PRRETIFICADORA)
          matching (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDRETIFICADORA);
        end
      end
      WVLR = 0; --Se não tiver valor de contribbuição, leva zerado...
    end

    insert into VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
    values (7, :PRCODEMP, :PRCODEMP, :PRREFERENCIA, :PRCODQUADRO, 8, coalesce(:WVLR, 0), :PRRETIFICADORA);
  end

  /* Continucao dessa SP que atingiu os 64k de tamanho das SP */
  execute procedure SP_APURACAO_BLOCOM_M200M600_P2(:PRCODQUADRO, :PRCODEMP, :PRREFERENCIA, :PRVERIFICARINCONSISTENCIAS, :PRCODEMPSO, :PRRETIFICADORA, :WVLRSLD);
end
^

create or alter procedure SP_APURACAO_BLOCOM_M200_M600 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PRCONTABILIZAFILIAL DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
declare variable WCODEMPAUX integer;
BEGIN
  -- Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  :WCODEMPAUX = :PRCODEMP;

  if (:PRCODEMPSO > 0) then
    :WCODEMPAUX = :PRCODEMPSO;

  /* REGISTRO M210: DETALHAMENTO DA CONTRIBUIÇÃO PARA O PIS/PASEP DO PERÍODO
     REGISTRO M610: DETALHAMENTO DA CONTRIBUIÇÃO PARA A SEGURIDADE SOCIAL - COFINS DO PERÍODO */
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M210_M610 (:prCODEMP, :prREFERENCIA, :prWhereEmpresas, :prverificarinconsistencias, :PRAJUSTESCP, :PRRETIFICADORA, 'FALSE', :PRCODEMPSO);

  /*  Elizeu - 12-09-18 - Apuração Bloco M215/M615 #82005 */
  /* Registro M215: Ajustes da Base de Cálculo da Contribuição para o PIS/Pasep Apurada
     Registro M615: Ajustes da Base de Cálculo da COFINS Apurada */
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M215_M615 (:prCODEMP, :prREFERENCIA, :PRRETIFICADORA, :PRAJUSTESCP, :PRCODEMPSO);
  
  /* Alt.: #242771 - Cria os ajustes automaticos de M220/620 conforme configuracao */  
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_GERA_AJUSTES_M220 (:PRCODEMP, :PRREFERENCIA, :PRWHEREEMPRESAS, :PRRETIFICADORA, :PRAJUSTESCP, :PRCODEMPSO);
  
  /* REGISTRO M220: AJUSTES DA CONTRIBUIÇÃO PARA O PIS/PASEP APURADA
     REGISTRO M620: AJUSTES DA COFINS APURADA */
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M220_M620 (:prCODEMP, :prREFERENCIA, :PRAJUSTESCP, :PRRETIFICADORA, :PRCODEMPSO);

  /* REGISTRO M230: INFORMAÇÕES ADICIONAIS DE DIFERIMENTO
     REGISTRO M630: INFORMAÇÕES ADICIONAIS DE DIFERIMENTO */
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M230_M630 (:prCODEMP, :prREFERENCIA, :PRRETIFICADORA, :PRAJUSTESCP, :PRCODEMPSO);

  /* REGISTRO M200: CONSOLIDAÇÃO DA CONTRIBUIÇÃO PARA O PIS/PASEP DO PERÍODO */
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M200M600(15, :prCODEMP, :prREFERENCIA, :prVerificarInconsistencias, :WCODEMPAUX, :PRRETIFICADORA);

  /* REGISTRO M600: CONSOLIDAÇÃO DA CONTRIBUIÇÃO PARA A SEGURIDADE SOCIAL - COFINS DO PERÍODO */
  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M200M600(33, :prCODEMP, :prREFERENCIA, :prVerificarInconsistencias, :WCODEMPAUX, :PRRETIFICADORA);

  /*Camilla M. SCP - Se tiver que realizar os ajustes por SCP, vai executar as procedures do M200 e M600 para casa SCP
  É mais viável chamar a procedure para cada SCP, do que colocar um monte de FOR SELECT la dentro, para pegar as SCPs também
  Mandando o código de empresa SCP direto na procedure, não é necessário nenhuma alteração lá dentro*/

  /*IF (:PRAJUSTESCP = 'TRUE') THEN
    BEGIN
      FOR
        SELECT SCP.BDCODEMPSCP
        FROM TEMPRESAS_SCP SCP
        --WHERE SCP.BDCODEMP = :prCODEMP
        WHERE scp.BDCODEMP in(SELECT ex.BDCODEMP
                              FROM TEMPRESAS ex
                              WHERE ex.BDCODEMP = :prCODEMP
                                 OR ex.BDCODMATRIZ = :prCODEMP)
          AND (SCP.BDCODEMPSCP IS NOT NULL AND SCP.BDCODEMPSCP > 0)
          AND (SCP.BDDATAFINAL IS NULL OR (SELECT bdAAAAMM FROM AAAAMM(SCP.BDDATAFINAL)) >= :prREFERENCIA)
          AND ((SELECT bdAAAAMM FROM AAAAMM(SCP.BDDATAINICIAL)) <= :prREFERENCIA)
        GROUP BY SCP.BDCODEMPSCP
        INTO :WCODEMPAUX
      DO
      BEGIN
        -- REGISTRO M200: CONSOLIDAÇÃO DA CONTRIBUIÇÃO PARA O PIS/PASEP DO PERÍODO
        EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M200M600(15, :WCODEMPAUX, :prREFERENCIA, :prVerificarInconsistencias, :prCODEMP, :PRRETIFICADORA);

        -- REGISTRO M600: CONSOLIDAÇÃO DA CONTRIBUIÇÃO PARA A SEGURIDADE SOCIAL - COFINS DO PERÍODO
        EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M200M600(33, :WCODEMPAUX, :prREFERENCIA, :prVerificarInconsistencias, :PRCODEMP, :PRRETIFICADORA);
      END
    END*/
END
^

create or alter procedure SP_APURACAO_BLOCOM_M400_M800P_2 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRAJUSTESCP varchar(5),
    PRCODEMPSO integer = 0)
as
declare variable WSQL varchar(32750);
declare variable WSQLPREFIXO varchar(800);
declare variable WSQLSUFIXO varchar(800);
declare variable WMOD_TRANSPORTE varchar(50);
BEGIN
-- Modelos para lançamento de entrada, faz isso para não carregar dados de movimentos errados.
-- Por exemplo: Não carregar dados dos produtos em notas de transporte, caso tenham produtos lançados...
wMOD_TRANSPORTE = '7,8,9,10,11,13,14,15,16,26,27,57,67,800,63'; -- Transporte

  -- Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

   wSQLPREFIXO =              'INSERT INTO TMP_VEF_EMP_TBLOCOM_M400_M800 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDVL_ITEM, BDCODNATREC, BDCODCTA, BDCODCSTPIS, BDBCPIS, BDALIQPIS, BDVLRPIS, BDCODCSTCOF, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDCODPLAPADRAO, BDCODTPLA,BDCODEMPSCP) ';
   wSQLPREFIXO = wSQLPREFIXO||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFLAN, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, ';
   wSQLPREFIXO = wSQLPREFIXO||       'aux.BDVL_ITEM, aux.BDCODNATREC, aux.BDCODCTA,';
   wSQLPREFIXO = wSQLPREFIXO||       'IIF(AUX.BDCODCSTPIS IN (''04'',''06'',''07'',''08'',''09''),AUX.BDCODCSTPIS,null) BDCODCSTPIS, ';
   wSQLPREFIXO = wSQLPREFIXO||       'aux.BDBCPIS, aux.BDALIQPIS, aux.BDVLRPIS,';
   wSQLPREFIXO = wSQLPREFIXO||       'IIF(AUX.BDCODCSTCOF IN (''04'',''06'',''07'',''08'',''09''),AUX.BDCODCSTCOF,null) BDCODCSTCOF, ';
   wSQLPREFIXO = wSQLPREFIXO||       'aux.BDBCCOFINS, aux.BDALIQCOFINS, aux.BDVLRCOFINS, ';
   wSQLPREFIXO = wSQLPREFIXO||       'aux.BDCODPLAPADRAO, aux.BDCODTPLA, '||IIF(:PRAJUSTESCP = 'TRUE',' COALESCE(SCP.BDCODEMPSCP,0) ',' 0')||' BDCODEMPSCP ';
   wSQLPREFIXO = wSQLPREFIXO||'FROM (';
   
   wSQLSUFIXO =                     ') aux ';
   wSQLSUFIXO = wSQLSUFIXO||'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = AUX.BDCODEMP AND SCP.BDCODSCP = AUX.BDCODSCP AND SCP.BDREFEMP = AUX.BDREFSOC) ';
   wSQLSUFIXO = wSQLSUFIXO||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstPIS ON (cstPIS.BDCODCSTPIS = aux.BDCODCSTPIS) ';
   wSQLSUFIXO = wSQLSUFIXO||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstCOF ON (cstCOF.BDCODCSTCOF = aux.BDCODCSTCOF) ';
   wSQLSUFIXO = wSQLSUFIXO||'WHERE ((cstPIS.BDCSTPIS in (''04'',''06'',''07'',''08'',''09'')) OR ((cstPIS.BDCSTPIS = ''05'') AND (aux.BDALIQPIS = 0)) OR ';
   wSQLSUFIXO = wSQLSUFIXO||       '(cstCOF.BDCSTCOF in (''04'',''06'',''07'',''08'',''09'')) OR ((cstCOF.BDCSTCOF = ''05'') AND (aux.BDALIQCOFINS = 0))) ';

   if ((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0)) then
     wSQLSUFIXO = wSQLSUFIXO||' and coalesce(SCP.BDCODEMPSCP, 0) = ' || :PRCODEMP;
   else
   if (:PRAJUSTESCP = 'TRUE') then
     wSQLSUFIXO = wSQLSUFIXO||' and coalesce(SCP.BDCODEMPSCP, 0) = 0';
    
   wSQL =             'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, ';
--   wSQL = wSQL||              '(pgto.bdvalorpgtopar +(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
   wSQL = wSQL||              'PGTO.BDVALORPGTOPAR BDVL_ITEM,';
   wSQL = wSQL||              'mov.BDCODNATREC, NULL AS BDCODCTA, mov.BDCODCSTPIS,';
   wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(MOV.BDVL_BC_PIS, 0)) / MOV.BDVL_OPER AS DM_NUMERIC_15_2) BDBCPIS, ';
   wSQL = wSQL||              'mov.BDALIQ_PIS AS BDALIQPIS,';
   wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(MOV.BDVLR_PIS, 0)) / MOV.BDVL_OPER AS DM_NUMERIC_15_2) BDVLRPIS, ';
   wSQL = wSQL||              'mov.BDCODCSTCOF,';
   wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(MOV.BDVL_BC_COFINS, 0)) / MOV.BDVL_OPER AS DM_NUMERIC_15_2) BDBCCOFINS, ';
   wSQL = wSQL||              'mov.BDALIQ_COFINS AS BDALIQCOFINS,';
   wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(MOV.BDVLR_COFINS, 0)) / MOV.BDVL_OPER AS DM_NUMERIC_15_2) BDVLRCOFINS, ';
   wSQL = wSQL||              'ccl.BDCODPLAPADRAO, COALESCE(mov.bdCODTPLA, ccl.bdCODTPLA) as bdCODTPLA,MOV.BDCODSCP, MOV.BDREFSOC ';
   wSQL = wSQL||       'FROM (';
   wSQL = wSQL||             'SELECT dem.BDCODEMP, dem.BDCHAVE, dem.BDREFLAN, dem.BDCODCSTPIS, dem.BDCODCSTCOF, dem.BDCODNATREC, dem.bdCODTPLA, ';
   wSQL = wSQL||                    'dem.BDVL_BC_PIS, dem.BDALIQ_PIS, dem.BDVLR_PIS,';
   wSQL = wSQL||                    'dem.BDVL_BC_COFINS, dem.BDALIQ_COFINS, dem.BDVLR_COFINS, dem.BDVL_OPER,DEM.BDCODSCP, DEM.BDREFSOC, SCP.BDCODEMPSCP ';
   wSQL = wSQL||             'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
   wSQL = wSQL||             'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = dem.BDCODEMP AND SCP.BDCODSCP = dem.BDCODSCP AND SCP.BDREFEMP = dem.BDREFSOC) ';
   wSQL = wSQL||             'left outer join VEF_BASE_TCADTIPODEMDOC CAD on (dem.BDCODTIPODOC = CAD.BDCODTIPODOC)';
   wSQL = wSQL||             'WHERE dem.'||TRIM(:prWHEREEMPRESAS)||' ';
   wSQL = wSQL||                'AND ((CAD.BDNAOEXPSPED = ''FALSE'') or (CAD.BDNAOEXPSPED is null))';
   IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
     wSQL = wSQL||               'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e WHERE e.BDCODEMP = coalesce(SCP.BDCODEMPSCP, DEM.BDCODEMP) AND e.BDREFEMP <= dem.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
   wSQL = wSQL||            ') mov ';
   wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
--   wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = mov.BDCODEMP AND SCP.BDCODSCP = mov.BDCODSCP AND SCP.BDREFEMP = mov.BDREFSOC) ';
   wSQL = wSQL||       'JOIN (';
   wSQL = wSQL||             'SELECT P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR, ';
   wSQL = wSQL||                    'CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + ';
   wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETPIS, 0)) + ';
   wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETCOFINS, 0)) + ';
   wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETCSLL, 0)) + ';
   wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETIRRF, 0)) + ';
   wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETISSQN, 0)) + ';
   wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR ';
   wSQL = wSQL||             'FROM VEF_EMP_TMOVF100PARPGTO P ';
   wSQL = wSQL||             'WHERE P.'||TRIM(:PRWHEREEMPRESAS)||' ';
   wSQL = wSQL||               'AND (CAST(SUBSTRING(P.BDDATAPGTOPAR FROM 1 FOR 4) || SUBSTRING(P.BDDATAPGTOPAR FROM 6 FOR 2) AS INTEGER) = '||:PRREFERENCIA||') ';
   --wSQL = wSQL||               'AND P.BDCODTIPOBAIXA <> 2 ';
   wSQL = wSQL||               'AND p.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
   wSQL = wSQL||             'GROUP BY P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR ';
   wSQL = wSQL||            ') PGTO ON (PGTO.BDCODEMP = MOV.BDCODEMP AND PGTO.BDCHAVE = MOV.BDCHAVE) ';
   wSQL = wSQL||       'LEFT OUTER JOIN( ';
   wSQL = wSQL||                       'SELECT aux.BDCODEMP, aux.BDCHAVELAN, aux.BDORDEMPAR, min(aux.BDORD) as BDORD, min(aux.BDCHAVE) as BDCHAVE, AUX.BDCODEMPSUC ';
   wSQL = wSQL||                       'FROM ( ';
   wSQL = wSQL||                             'SELECT t.BDCODEMP, t.BDCHAVELAN, t.BDORDEMPAR, MIN(t.BDCHAVE) as BDCHAVE, 1 as BDORD, T.BDCODEMPSUC ';
   wSQL = wSQL||                             'FROM TOL_VEF_EMP_TMOVF100PARPGTO t ';
   wSQL = wSQL||                             'JOIN VSUC_EMPRESAS_TLAN l ON (l.BDCODEMP = t.BDCODEMPSUC and l.BDCHAVE = t.BDCHAVE and l.BDVALOR = (SELECT COALESCE(MAX(d.bdVL_OPER), 0) '; -- Alt.: 80135 - Apenas contas de valor contábil...
   wSQL = wSQL||                                                                                                                              'FROM VEF_EMP_TMOVDEMAISDOC_F100 d ';
   wSQL = wSQL||                                                                                                                              'WHERE d.BDCODEMP = t.BDCODEMP ';
   wSQL = wSQL||                                                                                                                                'AND d.BDCHAVE = t.BDCHAVELAN)) ';
   wSQL = wSQL||                             'GROUP BY t.BDCODEMP, t.BDCHAVELAN, t.BDORDEMPAR, T.BDCODEMPSUC ';
   wSQL = wSQL||                             'UNION ALL ';
   wSQL = wSQL||                             'SELECT t.BDCODEMP, t.BDCHAVELAN, t.BDORDEMPAR, MIN(t.BDCHAVE) as BDCHAVE, 2 as BDORD, T.BDCODEMPSUC ';
   wSQL = wSQL||                             'FROM TOL_VEF_EMP_TMOVF100PARPGTO t ';
   wSQL = wSQL||                             'JOIN VSUC_EMPRESAS_TLAN l ON (l.BDCODEMP = t.BDCODEMPSUC and l.BDCHAVE = t.BDCHAVE) ';
   wSQL = wSQL||                             'GROUP BY t.BDCODEMP, t.BDCHAVELAN, t.BDORDEMPAR, T.BDCODEMPSUC ';
   wSQL = wSQL||                            ') aux ';
   wSQL = wSQL||                       'GROUP BY AUX.BDCODEMP, AUX.BDCHAVELAN, AUX.BDORDEMPAR, AUX.BDCODEMPSUC ';
   wSQL = wSQL||                       ') TOL on (TOL.BDCODEMPSUC = COALESCE(MOV.BDCODEMPSCP,PGTO.BDCODEMP) and TOL.BDCHAVELAN = pgto.BDCHAVE and TOL.BDORDEMPAR = pgto.BDORDEMPAR) ';
   wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN LAN on (LAN.BDCODEMP = TOL.BDCODEMPSUC and LAN.bdchave = TOL.BDCHAVE) ';

   wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
   wSQL = wSQL||       'WHERE ((mov.BDCODCSTPIS is not null) OR (mov.BDCODCSTCOF is not null)) ';

   wSQL = wSQL||       'UNION ALL ';

   wSQL = wSQL||      'SELECT mov.bdCODEMP, COALESCE(emp.bdCODMATRIZ, mov.bdCODEMP) AS bdCODMATRIZ, '||:prREFERENCIA||' bdREFLAN, d400.bdCHAVE, NULL AS bdORDEM, NULL AS bdORDEMPRO, 18 AS BDCODTP, ';
--   wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
   wSQL = wSQL||              'PGTO.BDVALORPGTOPAR BDVL_ITEM,';
   wSQL = wSQL||              'd400.bdCODNATREC, NULL AS BDCODCTA, d400.bdCODCSTPIS,';
   wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(d400.BDVL_BC_PIS, 0)) / iVlr.bdVLRCONTABTOTAL AS DM_NUMERIC_15_2) BDBCPIS,';
   wSQL = wSQL||              'd400.BDALIQ_PIS AS BDALIQPIS,';
   wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(d400.bdVL_PIS, 0)) / iVlr.bdVLRCONTABTOTAL AS DM_NUMERIC_15_2) BDVLRPIS,';
   wSQL = wSQL||              'd400.BDCODCSTCOF,';
   wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(d400.BDVL_BC_COF, 0)) / iVlr.bdVLRCONTABTOTAL AS DM_NUMERIC_15_2) BDBCCOFINS,';
   wSQL = wSQL||              'd400.BDALIQ_COF AS BDALIQCOFINS,';
   wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(d400.BDVL_COF, 0)) / iVlr.bdVLRCONTABTOTAL AS DM_NUMERIC_15_2) BDVLRCOFINS,';
   wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA,itens.BDCODSCP, itens.BDREFSOC ';
   wSQL = wSQL||      'FROM (';
   wSQL = wSQL||             'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, S.BDVALORNOTA ';
   wSQL = wSQL||             'FROM VEF_EMP_TMOVSAI s ';
   wSQL = wSQL||             'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
   wSQL = wSQL||               'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
   IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
     wSQL = wSQL||               'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
   wSQL = wSQL||              'AND exists(select * ';
   wSQL = wSQL||              'from VEF_EMP_TMOVSAIITENS SI ';
   wSQL = wSQL||              'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
   wSQL = wSQL||              'where SI.BDCODEMP = S.BDCODEMP and ';
   wSQL = wSQL||              'SI.BDCHAVE = S.BDCHAVE) ';
   wSQL = wSQL||             ') mov ';
   wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
   wSQL = wSQL||       'JOIN ( ';
   wSQL = wSQL||             'SELECT P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR, ';
   wSQL = wSQL||                    'CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + ';
   wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETPIS, 0)) + ';
   wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETCOFINS, 0)) + ';
   wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETCSLL, 0)) + ';
   wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETIRRF, 0)) + ';
   wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETISSQN, 0)) + ';
   wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR, P.BDCODNAT ';
   wSQL = wSQL||             'FROM VEF_EMP_TMOVSAIPARPGTO P ';
   wSQL = wSQL||             'WHERE P.'||TRIM(:PRWHEREEMPRESAS)||' ';
   wSQL = wSQL||               'AND (CAST(SUBSTRING(P.BDDATAPGTOPAR FROM 1 FOR 4) || SUBSTRING(P.BDDATAPGTOPAR FROM 6 FOR 2) AS INTEGER) = '||:PRREFERENCIA||') ';
   --wSQL = wSQL||               'AND P.BDCODTIPOBAIXA <> 2 ';
   wSQL = wSQL||               'AND p.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
   wSQL = wSQL||             'GROUP BY P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR, P.BDCODNAT ';
   wSQL = wSQL||            ') PGTO ON (PGTO.BDCODEMP = mov.BDCODEMP AND PGTO.BDCHAVE = mov.BDCHAVE) ';
   --wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (PGTO.BDCODEMP = itens.BDCODEMP AND PGTO.BDCHAVE = itens.BDCHAVE AND ITENS.BDCODNAT = PGTO.BDCODNAT) '; Alt.: #227786
   wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (PGTO.BDCODEMP = itens.BDCODEMP AND PGTO.BDCHAVE = itens.BDCHAVE) ';
   wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = ITENS.BDCODEMP AND SCP.BDCODSCP = ITENS.BDCODSCP AND SCP.BDREFEMP = ITENS.BDREFSOC) ';
   wSQL = wSQL||       'LEFT OUTER JOIN (SELECT i.bdCODEMP, i.bdCHAVE, SUM(i.bdVLRCONTAB) AS bdVLRCONTABTOTAL ';  -- Alt.: #135727 - Deve considerar apenas o valor contábil que gera as parcelas, caso contrario o valor das parcelas eh menor que o total da nota(sustitui o bdVALORNOTA)...
   wSQL = wSQL||                        'FROM VEF_EMP_TMOVSAIITENS i ';
   wSQL = wSQL||                        'LEFT OUTER JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT) ';
   wSQL = wSQL||                        'WHERE nat.bdLANCPARCELAMENTO = ''TRUE'' ';
   wSQL = wSQL||                        'GROUP BY i.bdCODEMP, i.bdCHAVE) iVlr on (iVlr.bdCODEMP = pgto.bdCODEMP AND iVlr.bdCHAVE = pgto.bdCHAVE) ';
   wSQL = wSQL||       'JOIN (SELECT x.* FROM VEF_EMP_TD400SAI x ';
   wSQL = wSQL||             'WHERE NOT EXISTS(SELECT p.BDCODEMP, p.BDCHAVE FROM VEF_EMP_TMOVPROSAI p WHERE p.BDCODEMP = x.BDCODEMP AND p.BDCHAVE = x.BDCHAVE) ';
   wSQL = wSQL||             ') d400 ON (d400.BDCODEMP = mov.bdCODEMP AND d400.bdCHAVE = MOV.BDCHAVE) ';
   wSQL = wSQL||       'LEFT OUTER JOIN(SELECT PGTO.BDCODEMP, PGTO.BDCHAVELAN, PGTO.BDORDEMPAR, MIN(PGTO.BDCHAVE) as BDCHAVE, PGTO.BDCODEMPSUC ';
   wSQL = wSQL||                       'FROM TOL_VEF_EMP_TMOVSAIPARPGTO PGTO ';
--   wSQL = wSQL||                       'WHERE bdFORMULA LIKE ''%NAT%LAN(%)'' '; -- Alt.: 80135 - Apenas contas de valor contábil...
   wSQL = wSQL||                       'GROUP BY PGTO.BDCODEMP, PGTO.BDCHAVELAN, PGTO.BDORDEMPAR, PGTO.BDCODEMPSUC) tol on (TOL.BDCODEMPSUC = COALESCE(SCP.BDCODEMPSCP,PGTO.BDCODEMP) and tol.BDCHAVELAN = PGTO.BDCHAVE and tol.BDORDEMPAR = pgto.BDORDEMPAR) ';
   wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMPSUC and lan.BDCHAVE = tol.BDCHAVE) ';
   wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
   wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE,BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM,BDCODEMPSUC) TOLRAT on (TOLRAT.BDCODEMPSUC = COALESCE(SCP.BDCODEMPSCP,itens.BDCODEMP) and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
   wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMPSUC and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
   wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
   wSQL = wSQL||       'WHERE ((d400.bdCODCSTPIS IS NOT NULL) OR (d400.bdCODCSTCOF IS NOT NULL)) ';

   EXECUTE STATEMENT ( wSQLPREFIXO || wSQL || wSQLSUFIXO ); 
END
^

create or alter procedure SP_APURACAO_BLOCOM_M400_M800PAR (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRAJUSTESCP varchar(5),
    PRCODEMPSO integer = 0)
as
declare variable WINCTRIB integer;
declare variable WCODCRIT integer;
declare variable WSQL varchar(32750);
declare variable WSQLPREFIXO varchar(800);
declare variable WSQLSUFIXO varchar(800);
declare variable WEXPNFCOMVALSAI varchar(5);
declare variable WMOD_TRANSPORTE varchar(50);
BEGIN
-- Modelos para lançamento de entrada, faz isso para não carregar dados de movimentos errados.
-- Por exemplo: Não carregar dados dos produtos em notas de transporte, caso tenham produtos lançados...
wMOD_TRANSPORTE = '7,8,9,10,11,13,14,15,16,26,27,57,67,800,63'; -- Transporte

  -- Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT, BDEXPNFCOMVALSAI FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :wINCTRIB, :wCODCRIT, :wEXPNFCOMVALSAI;

  if ((:WINCTRIB is null) and (:PRCODEMPSO > 0)) then
    begin
      SELECT BDINCTRIB+1, BDCODCRIT, BDEXPNFCOMVALSAI FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMPSO
      INTO :wINCTRIB, :wCODCRIT, :wEXPNFCOMVALSAI;
    end

  IF ((wINCTRIB IS NOT NULL) AND (wEXPNFCOMVALSAI <> 'TRUE') and (wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
    BEGIN
      wSQLPREFIXO =              'INSERT INTO TMP_VEF_EMP_TBLOCOM_M400_M800 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDVL_ITEM, BDCODNATREC, BDCODCTA, BDCODCSTPIS, BDBCPIS, BDALIQPIS, BDVLRPIS, BDCODCSTCOF, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDCODPLAPADRAO, BDCODTPLA,BDCODEMPSCP) ';
      wSQLPREFIXO = wSQLPREFIXO||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFLAN, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, ';
      wSQLPREFIXO = wSQLPREFIXO||       'aux.BDVL_ITEM, aux.BDCODNATREC, aux.BDCODCTA,';
      wSQLPREFIXO = wSQLPREFIXO||       'IIF(AUX.BDCODCSTPIS IN (''04'',''06'',''07'',''08'',''09''),AUX.BDCODCSTPIS,null) BDCODCSTPIS, ';
      wSQLPREFIXO = wSQLPREFIXO||       'aux.BDBCPIS, aux.BDALIQPIS, aux.BDVLRPIS,';
      wSQLPREFIXO = wSQLPREFIXO||       'IIF(AUX.BDCODCSTCOF IN (''04'',''06'',''07'',''08'',''09''),AUX.BDCODCSTCOF,null) BDCODCSTCOF, ';
      wSQLPREFIXO = wSQLPREFIXO||       'aux.BDBCCOFINS, aux.BDALIQCOFINS, aux.BDVLRCOFINS, ';
      wSQLPREFIXO = wSQLPREFIXO||       'aux.BDCODPLAPADRAO, aux.BDCODTPLA, '||IIF(:PRAJUSTESCP = 'TRUE',' COALESCE(SCP.BDCODEMPSCP,0) ',' 0')||' BDCODEMPSCP ';
      wSQLPREFIXO = wSQLPREFIXO||'FROM (';
      
      wSQLSUFIXO =                     ') aux ';
      wSQLSUFIXO = wSQLSUFIXO||'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = AUX.BDCODEMP AND SCP.BDCODSCP = AUX.BDCODSCP AND SCP.BDREFEMP = AUX.BDREFSOC) ';
      wSQLSUFIXO = wSQLSUFIXO||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstPIS ON (cstPIS.BDCODCSTPIS = aux.BDCODCSTPIS) ';
      wSQLSUFIXO = wSQLSUFIXO||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstCOF ON (cstCOF.BDCODCSTCOF = aux.BDCODCSTCOF) ';
      wSQLSUFIXO = wSQLSUFIXO||'WHERE ((cstPIS.BDCSTPIS in (''04'',''06'',''07'',''08'',''09'')) OR ((cstPIS.BDCSTPIS = ''05'') AND (aux.BDALIQPIS = 0)) OR ';
      wSQLSUFIXO = wSQLSUFIXO||       '(cstCOF.BDCSTCOF in (''04'',''06'',''07'',''08'',''09'')) OR ((cstCOF.BDCSTCOF = ''05'') AND (aux.BDALIQCOFINS = 0))) ';

      if ((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0)) then
         wSQLSUFIXO = wSQLSUFIXO||' and coalesce(SCP.BDCODEMPSCP, 0) = ' || :PRCODEMP;
      else
      if (:PRAJUSTESCP = 'TRUE') then
         wSQLSUFIXO = wSQLSUFIXO||' and coalesce(SCP.BDCODEMPSCP, 0) = 0';
       
      /* Saídas - Produtos */
      wSQL =              'SELECT sai.BDCODEMP, COALESCE(emp.BDCODMATRIZ, sai.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' BDREFLAN, movpro.BDCHAVE, movpro.BDORDEM, movpro.BDORDEMPRO, 2 AS BDCODTP, ';
          wSQL = wSQL||              'CAST(SUM((PGTO.BDVALORPGTOPAR * coalesce(MOVPRO.BDVLRITEM, 0)) / iif(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1)) AS NUMERIC(15,2)) BDVL_ITEM, ';
      wSQL = wSQL||              'movpro.BDCODNATREC, movpro.BDCODCTA, movpro.BDCODCSTPIS,';
          wSQL = wSQL||              'CAST((SUM(PGTO.BDVALORPGTOPAR) * COALESCE(MOVPRO.BDBCPIS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDBCPIS, ';
      wSQL = wSQL||              'movpro.BDALIQPIS,';
          wSQL = wSQL||              'CAST((SUM(PGTO.BDVALORPGTOPAR) * COALESCE(MOVPRO.BDVLRPIS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDVLRPIS, ';
      wSQL = wSQL||              'movpro.BDCODCSTCOF,';
          wSQL = wSQL||              'CAST((SUM(PGTO.BDVALORPGTOPAR) * COALESCE(MOVPRO.BDBCCOFINS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDBCCOFINS, ';
      wSQL = wSQL||              'movpro.BDALIQCOFINS, ';
          wSQL = wSQL||              'CAST((SUM(PGTO.BDVALORPGTOPAR) * COALESCE(MOVPRO.BDVLRCOFINS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA, ITENS.BDCODSCP, ITENS.BDREFSOC ';
      wSQL = wSQL||       'FROM (SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, S.BDVALORNOTA ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
      wSQL = wSQL||              'AND (s.BDMODELO not in ('||wMOD_TRANSPORTE||')) '; -- Modelos que não são produtos...
      wSQL = wSQL||              'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
        wSQL = wSQL||              'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||              'AND exists(select * ';
      wSQL = wSQL||                         'from VEF_EMP_TMOVSAIITENS SI ';
      wSQL = wSQL||                         'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
      wSQL = wSQL||                         'where SI.BDCODEMP = S.BDCODEMP and ';
      wSQL = wSQL||                         'SI.BDCHAVE = S.BDCHAVE)) SAI ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = sai.BDCODEMP) ';
    --  wSQL = wSQL||       'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,CAST(COUNT(aux.BDCHAVE) AS NUMERIC(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVSAIPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x ON (sai.BDCODEMP = x.BDCODEMP AND sai.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||       'JOIN (';
          wSQL = wSQL||             'SELECT P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR, ';
          wSQL = wSQL||                    'CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS NUMERIC(15,4)), 0)) + ';
          wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETPIS, 0)) + ';
          wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETCOFINS, 0)) + ';
          wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETCSLL, 0)) + ';
          wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETIRRF, 0)) + ';
          wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETISSQN, 0)) + ';
          wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETINSS, 0)) AS NUMERIC(15,4)) BDVALORPGTOPAR, P.BDCODNAT ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVSAIPARPGTO P ';
      wSQL = wSQL||             'WHERE P.'||TRIM(:PRWHEREEMPRESAS)||' ';
      wSQL = wSQL||               'AND (CAST(SUBSTRING(P.BDDATAPGTOPAR FROM 1 FOR 4) || SUBSTRING(P.BDDATAPGTOPAR FROM 6 FOR 2) AS INTEGER) = '||:PRREFERENCIA||') ';
          wSQL = wSQL||               'AND p.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para c??lculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
      wSQL = wSQL||             'GROUP BY P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR, P.BDCODNAT ';
      wSQL = wSQL||            ') PGTO ON (PGTO.BDCODEMP = SAI.BDCODEMP AND PGTO.BDCHAVE = SAI.BDCHAVE) ';
          --wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (PGTO.BDCODEMP = itens.BDCODEMP AND PGTO.BDCHAVE = itens.BDCHAVE AND ITENS.BDCODNAT = PGTO.BDCODNAT) '; Alt.: #227786
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (PGTO.BDCODEMP = itens.BDCODEMP AND PGTO.BDCHAVE = itens.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = itens.BDCODEMP AND SCP.BDCODSCP = itens.BDCODSCP AND SCP.BDREFEMP = itens.BDREFSOC AND '''||:PRAJUSTESCP||''' = ''TRUE'') ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT i.bdCODEMP, i.bdCHAVE, SUM(i.bdVLRCONTAB) AS bdVLRCONTABTOTAL '; -- Alt.: #135727 - Deve considerar apenas o valor contábil que gera as parcelas, caso contrario o valor das parcelas eh menor que o total da nota(sustitui o bdVALORNOTA)...
      wSQL = wSQL||                        'FROM VEF_EMP_TMOVSAIITENS i ';
      wSQL = wSQL||                        'LEFT OUTER JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT) ';
      wSQL = wSQL||                        'WHERE nat.bdLANCPARCELAMENTO = ''TRUE'' ';
      wSQL = wSQL||                        'GROUP BY i.bdCODEMP, i.bdCHAVE) iVlr on (iVlr.bdCODEMP = pgto.bdCODEMP AND iVlr.bdCHAVE = pgto.bdCHAVE) ';
      wSQL = wSQL||       'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, p.BDCODCSTCOF, p.BDCODCSTPIS, p.BDCODNATREC, p.BDCODCTA, p.BDALIQPIS, p.BDALIQCOFINS, ';
      IF ((wINCTRIB = 2) AND (wCODCRIT = 2)) THEN
        wSQL = wSQL||                  'COALESCE(p.bdVLRITEM, 0) + COALESCE(p.bdVLRFRETE, 0) AS bdVLRITEM,'; -- Alt.: #140820 #141746 #141860 #142059 #142721 #142727 #144499 #144764 #144765 #146779 - Ajustado para respeitar a mesma regra da solicitação do F550 "#129883"
      else
        wSQL = wSQL||                  'COALESCE(p.bdVLRITEM, 0) AS bdVLRITEM,';
      wSQL = wSQL||                    'p.BDBCPIS, p.BDBCCOFINS, p.BDVLRPIS, p.BDVLRCOFINS, p.BDCODPLAPADRAO, p.BDCODTPLA ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVPROSAI p) movpro ON (itens.BDCODEMP = movpro.BDCODEMP AND itens.BDCHAVE = movpro.BDCHAVE AND itens.BDORDEM = movpro.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstPIS ON (cstPIS.BDCODCSTPIS = movpro.BDCODCSTPIS) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstCOF ON (cstCOF.BDCODCSTCOF = movpro.BDCODCSTCOF) ';
      wSQL = wSQL||       'LEFT OUTER JOIN(SELECT PGTO.BDCODEMP, PGTO.BDCHAVELAN, PGTO.BDORDEMPAR, MIN(PGTO.BDCHAVE) as BDCHAVE, PGTO.BDCODEMPSUC ';
      wSQL = wSQL||                       'FROM TOL_VEF_EMP_TMOVSAIPARPGTO PGTO ';
--          wSQL = wSQL||                       'WHERE bdFORMULA LIKE ''%NAT%LAN(%)'' '; -- Alt.: 80135 - Apenas contas de valor contábil...
      wSQL = wSQL||                       'GROUP BY PGTO.BDCODEMP, PGTO.BDCHAVELAN, PGTO.BDORDEMPAR, PGTO.BDCODEMPSUC) tol on (TOL.BDCODEMPSUC = COALESCE(SCP.BDCODEMPSCP,PGTO.BDCODEMP) and tol.BDCHAVELAN = PGTO.BDCHAVE and tol.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMPSUC and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = COALESCE(movpro.BDCODPLAPADRAO, lan.BDCODPLAPADRAO) and ccl.BDCODTPLA = COALESCE(movpro.BDCODTPLA, lan.BDCREDITO)) ';
      wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE,BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM,BDCODEMPSUC) TOLRAT on (TOLRAT.BDCODEMPSUC = COALESCE(SCP.BDCODEMPSCP,itens.BDCODEMP) and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMPSUC and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = COALESCE(movpro.BDCODPLAPADRAO, lanrat.BDCODPLAPADRAO) and cclrat.BDCODTPLA = COALESCE(movpro.BDCODTPLA, lanrat.BDCREDITO)) ';
      wSQL = wSQL||       'WHERE ((movpro.BDCODCSTPIS is not null) OR (movpro.bdcodcstcof is not null)) ';
      wSQL = wSQL||       'AND ((cstPIS.BDCSTPIS in (''04'',''06'',''07'',''08'',''09'')) OR ((cstPIS.BDCSTPIS = ''05'') AND (movpro.BDALIQPIS = 0)) OR ';
      wSQL = wSQL||            '(cstCOF.BDCSTCOF in (''04'',''06'',''07'',''08'',''09'')) OR ((cstCOF.BDCSTCOF = ''05'') AND (movpro.BDALIQCOFINS = 0))) ';
          wSQL = wSQL||       'GROUP BY SAI.BDCODEMP, EMP.BDCODMATRIZ, MOVPRO.BDCHAVE,MOVPRO.BDORDEM, MOVPRO.BDORDEMPRO,MOVPRO.BDCODNATREC, MOVPRO.BDCODCTA, MOVPRO.BDCODCSTPIS,/*PGTO.BDVALORPGTOPAR,*/ MOVPRO.BDBCPIS, IVLR.BDVLRCONTABTOTAL,';
          wSQL = wSQL||       'MOVPRO.BDALIQPIS,MOVPRO.BDVLRPIS,MOVPRO.BDCODCSTCOF,MOVPRO.BDBCCOFINS,MOVPRO.BDALIQCOFINS,MOVPRO.BDVLRCOFINS,CCL.BDCODPLAPADRAO, CCLRAT.BDCODPLAPADRAO,CCL.BDCODTPLA, CCLRAT.BDCODTPLA, ITENS.BDCODSCP, ITENS.BDREFSOC ';


      wSQL = wSQL||       'UNION ALL ';
      /* Saídas - Transporte (D100) */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' BDREFLAN, d100.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 10 AS BDCODTP, ';
--          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
      wSQL = wSQL||              'PGTO.BDVALORPGTOPAR BDVL_ITEM,';
      wSQL = wSQL||              'd100.BDCODNATREC, d100.BDCODCTA, d100.BDCODCSTPIS,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(D100.BDVL_BC_PIS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDBCPIS, ';
      wSQL = wSQL||              'd100.BDALIQ_PIS AS BDALIQPIS,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(D100.BDVLRPIS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDVLRPIS, ';
      wSQL = wSQL||              'd100.BDCODCSTCOF,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(D100.BDVL_BC_COF, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDBCCOFINS, ';
      wSQL = wSQL||              'd100.BDALIQ_COF AS BDALIQCOFINS,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(D100.BDVLRCOFINS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA, ITENS.BDCODSCP, ITENS.BDREFSOC ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, S.BDVALORNOTA ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
      wSQL = wSQL||                'AND (s.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Modelos que não são produtos...
      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
        wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||              'AND exists(select * ';
      wSQL = wSQL||                         'from VEF_EMP_TMOVSAIITENS SI ';
      wSQL = wSQL||                         'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
      wSQL = wSQL||                         'where SI.BDCODEMP = S.BDCODEMP and ';
      wSQL = wSQL||                         'SI.BDCHAVE = S.BDCHAVE)';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'JOIN (';
      wSQL = wSQL||             'SELECT P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR, ';
      wSQL = wSQL||                    'CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETPIS, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETCOFINS, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETCSLL, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETIRRF, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETISSQN, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR,P.BDCODNAT ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVSAIPARPGTO P ';
      wSQL = wSQL||             'WHERE P.'||TRIM(:PRWHEREEMPRESAS)||' ';
      wSQL = wSQL||               'AND (CAST(SUBSTRING(P.BDDATAPGTOPAR FROM 1 FOR 4) || SUBSTRING(P.BDDATAPGTOPAR FROM 6 FOR 2) AS INTEGER) = '||:PRREFERENCIA||') ';
      --wSQL = wSQL||               'AND P.BDCODTIPOBAIXA <> 2 ';
      wSQL = wSQL||               'AND p.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
      wSQL = wSQL||             'GROUP BY P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR,P.BDCODNAT ';
      wSQL = wSQL||            ') PGTO ON (PGTO.BDCODEMP = mov.BDCODEMP AND PGTO.BDCHAVE = mov.BDCHAVE) ';
          --wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (PGTO.BDCODEMP = itens.BDCODEMP AND PGTO.BDCHAVE = itens.BDCHAVE AND PGTO.BDCODNAT = ITENS.BDCODNAT) '; Alt.: #227786
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (PGTO.BDCODEMP = itens.BDCODEMP AND PGTO.BDCHAVE = itens.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = itens.BDCODEMP AND SCP.BDCODSCP = itens.BDCODSCP AND SCP.BDREFEMP = itens.BDREFSOC AND '''||:PRAJUSTESCP||''' = ''TRUE'') ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT i.bdCODEMP, i.bdCHAVE, SUM(i.bdVLRCONTAB) AS bdVLRCONTABTOTAL '; -- Alt.: #135727 - Deve considerar apenas o valor contábil que gera as parcelas, caso contrario o valor das parcelas eh menor que o total da nota(sustitui o bdVALORNOTA)...
      wSQL = wSQL||                        'FROM VEF_EMP_TMOVSAIITENS i ';
      wSQL = wSQL||                        'LEFT OUTER JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT) ';
      wSQL = wSQL||                        'WHERE nat.bdLANCPARCELAMENTO = ''TRUE'' ';
      wSQL = wSQL||                        'GROUP BY i.bdCODEMP, i.bdCHAVE) iVlr on (iVlr.bdCODEMP = pgto.bdCODEMP AND iVlr.bdCHAVE = pgto.bdCHAVE) ';
      wSQL = wSQL||       'JOIN VEF_EMP_TD100SAI d100 ON (mov.BDCODEMP = d100.BDCODEMP AND mov.BDCHAVE = d100.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN(SELECT PGTO.BDCODEMP, PGTO.BDCHAVELAN, PGTO.BDORDEMPAR, MIN(PGTO.BDCHAVE) as BDCHAVE, PGTO.BDCODEMPSUC ';
      wSQL = wSQL||                       'FROM TOL_VEF_EMP_TMOVSAIPARPGTO PGTO ';
--          wSQL = wSQL||                       'WHERE bdFORMULA LIKE ''%NAT%LAN(%)'' '; -- Alt.: 80135 - Apenas contas de valor contábil...
      wSQL = wSQL||                       'GROUP BY PGTO.BDCODEMP, PGTO.BDCHAVELAN, PGTO.BDORDEMPAR, PGTO.BDCODEMPSUC) tol on (TOL.BDCODEMPSUC = COALESCE(SCP.BDCODEMPSCP,PGTO.BDCODEMP) and tol.BDCHAVELAN = PGTO.BDCHAVE and tol.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMPSUC and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE,BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM,BDCODEMPSUC) TOLRAT on (tolrat.BDCODEMPSUC = COALESCE(SCP.BDCODEMPSCP,itens.BDCODEMP) and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMPSUC and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
      wSQL = wSQL||       'WHERE ((d100.BDCODCSTPIS is not null) OR (d100.BDCODCSTCOF is not null)) ';

      wSQL = wSQL||       'UNION ALL ';
      /* Saídas - F500 */
      wSQL = wSQL||       'SELECT mov.bdCODEMP, COALESCE(emp.bdCODMATRIZ, mov.bdCODEMP) AS bdCODMATRIZ, '||:prREFERENCIA||' AS bdREFLAN, f500.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 17 AS BDCODTP, ';
      wSQL = wSQL||              'pgto.bdVALORPGTOPAR AS bdVL_ITEM, ';
      wSQL = wSQL||              'f500.BDCODNATREC, NULL AS bdCODCTA, f500.bdCODCSTPIS, ';
      wSQL = wSQL||              'CAST((pgto.bdVALORPGTOPAR * COALESCE(f500.bdBASEPIS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) AS bdBCPIS, ';
      wSQL = wSQL||              'f500.bdALIQPIS, ';
      wSQL = wSQL||              'CAST((pgto.bdVALORPGTOPAR * COALESCE(f500.bdVLRPIS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) AS bdVLRPIS, ';
      wSQL = wSQL||              'f500.bdCODCSTCOF, ';
      wSQL = wSQL||              'CAST((pgto.bdVALORPGTOPAR * COALESCE(f500.bdBASECOF, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) AS bdBCCOFINS, ';
      wSQL = wSQL||              'f500.bdALIQCOF AS bdALIQCOFINS, ';
      wSQL = wSQL||              'CAST((pgto.bdVALORPGTOPAR * COALESCE(f500.bdVLRCOF, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) AS bdVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(ccl.bdCODPLAPADRAO,cclrat.bdCODPLAPADRAO) AS bdCODPLAPADRAO, COALESCE(ccl.bdCODTPLA,cclrat.bdCODTPLA) AS bdCODTPLA, ITENS.BDCODSCP, ITENS.BDREFSOC ';
      wSQL = wSQL||       'FROM (SELECT s.bdCODEMP, s.bdCHAVE, s.bdREFLAN, s.bdVALORNOTA ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||              'WHERE (s.bdCODSITNF NOT IN (2,3,4,5)) ';
      wSQL = wSQL||                'AND s.'||TRIM(:PRWHEREEMPRESAS)||' ';
      IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
        wSQL = wSQL||                'AND ((SELECT FIRST 1 bdTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e WHERE e.bdCODEMP = s.bdCODEMP AND e.bdREFEMP <= s.bdREFLAN ORDER BY bdCODEMP DESC, bdREFEMP DESC) = 1) ';
      wSQL = wSQL||                'AND EXISTS(SELECT * ';
      wSQL = wSQL||                           'FROM VEF_EMP_TMOVSAIITENS si ';
      wSQL = wSQL||                           'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = si.bdCODNAT AND ((nat.bdNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.bdNAOEXPEFDCONT)) = TRIM(''FALSE'')))) ';
      wSQL = wSQL||                           'WHERE si.bdCODEMP = s.bdCODEMP ';
      wSQL = wSQL||                             'AND si.bdCHAVE = s.bdCHAVE) ';
      wSQL = wSQL||               'AND (NOT EXISTS(SELECT * FROM VEF_EMP_TMOVSAI x ';
      wSQL = wSQL||                               'JOIN VEF_EMP_TMOVPROSAI xp ON (xp.bdCODEMP = x.bdCODEMP AND xp.bdCHAVE = x.bdCHAVE) ';
      wSQL = wSQL||                               'WHERE x.bdMODELO NOT IN ('||wMOD_TRANSPORTE||') AND x.bdCODEMP = s.bdCODEMP AND x.bdCHAVE = s.bdCHAVE)) ';
      wSQL = wSQL||               'AND (NOT EXISTS(SELECT * FROM VEF_EMP_TMOVSAI x ';
      wSQL = wSQL||                               'JOIN VEF_EMP_TD100SAI xp ON (xp.bdCODEMP = x.bdCODEMP AND xp.bdCHAVE = x.bdCHAVE) ';
      wSQL = wSQL||                               'WHERE x.bdMODELO IN ('||wMOD_TRANSPORTE||') AND x.bdCODEMP = s.bdCODEMP AND x.bdCHAVE = s.bdCHAVE))) mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp ON (emp.bdCODEMP = mov.bdCODEMP) ';
      wSQL = wSQL||       'JOIN (SELECT p.bdCODEMP, p.bdCHAVE, p.bdORDEMPAR, ';
      wSQL = wSQL||                    'CAST(SUM(COALESCE(CAST(p.bdVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + SUM(COALESCE(p.bdVALORRETPIS, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(p.bdVALORRETCOFINS, 0)) + SUM(COALESCE(p.bdVALORRETCSLL, 0)) + SUM(COALESCE(p.bdVALORRETIRRF, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(p.bdVALORRETISSQN, 0)) + SUM(COALESCE(p.bdVALORRETINSS, 0)) AS DM_NUMERIC_15_2) AS bdVALORPGTOPAR,P.BDCODNAT  ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVSAIPARPGTO p ';
      wSQL = wSQL||             'WHERE p.'||TRIM(:PRWHEREEMPRESAS)||' ';
      wSQL = wSQL||               'AND (CAST(SUBSTRING(p.bdDATAPGTOPAR FROM 1 FOR 4) || SUBSTRING(p.bdDATAPGTOPAR FROM 6 FOR 2) AS INTEGER) = '||:PRREFERENCIA||') ';
      wSQL = wSQL||               'AND p.bdCODTIPOBAIXA = 1 ';  -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
      wSQL = wSQL||             'GROUP BY p.bdCODEMP, p.bdCHAVE, p.bdORDEMPAR, P.BDCODNAT ';
      wSQL = wSQL||            ') pgto ON (pgto.bdCODEMP = mov.bdCODEMP AND pgto.bdCHAVE = mov.bdCHAVE) ';
          --wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (itens.bdCODEMP = pgto.bdCODEMP AND itens.bdCHAVE = pgto.bdCHAVE AND PGTO.BDCODNAT = ITENS.BDCODNAT) '; Alt.: #227786
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (itens.bdCODEMP = pgto.bdCODEMP AND itens.bdCHAVE = pgto.bdCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = itens.BDCODEMP AND SCP.BDCODSCP = itens.BDCODSCP AND SCP.BDREFEMP = itens.BDREFSOC AND '''||:PRAJUSTESCP||''' = ''TRUE'') ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT i.bdCODEMP, i.bdCHAVE, SUM(i.bdVLRCONTAB) AS bdVLRCONTABTOTAL '; -- Alt.: #135727 - Deve considerar apenas o valor contábil que gera as parcelas, caso contrario o valor das parcelas eh menor que o total da nota(sustitui o bdVALORNOTA)...
      wSQL = wSQL||                        'FROM VEF_EMP_TMOVSAIITENS i ';
      wSQL = wSQL||                        'LEFT OUTER JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT) ';
      wSQL = wSQL||                        'WHERE nat.bdLANCPARCELAMENTO = ''TRUE'' ';
      wSQL = wSQL||                        'GROUP BY i.bdCODEMP, i.bdCHAVE) iVlr on (iVlr.bdCODEMP = pgto.bdCODEMP AND iVlr.bdCHAVE = pgto.bdCHAVE) ';
      wSQL = wSQL||       'JOIN VEF_EMP_TF500SAI f500 ON (mov.bdCODEMP = f500.bdCODEMP AND mov.bdCHAVE = f500.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN(SELECT pgto.bdCODEMP, pgto.bdCHAVELAN, pgto.bdORDEMPAR, MIN(pgto.bdCHAVE) AS bdCHAVE, PGTO.BDCODEMPSUC ';
      wSQL = wSQL||                       'FROM TOL_VEF_EMP_TMOVSAIPARPGTO pgto ';
      wSQL = wSQL||                       'GROUP BY pgto.bdCODEMP, pgto.bdCHAVELAN, pgto.bdORDEMPAR, PGTO.BDCODEMPSUC) tol ON (TOL.BDCODEMPSUC = COALESCE(SCP.BDCODEMPSCP,PGTO.BDCODEMP) AND tol.bdCHAVELAN = pgto.bdCHAVE and tol.bdORDEMPAR = pgto.bdORDEMPAR) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.bdCODEMP = tol.BDCODEMPSUC AND lan.bdCHAVE = tol.bdCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.bdCODPLAPADRAO = lan.bdCODPLAPADRAO AND ccl.bdCODTPLA = lan.bdCREDITO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN(SELECT bdCODEMP, bdCHAVELAN, bdORDEM, MIN(bdCHAVE) AS bdCHAVE,BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY bdCODEMP, bdCHAVELAN, bdORDEM,BDCODEMPSUC) tolrat ON (tolrat.BDCODEMPSUC = COALESCE(SCP.BDCODEMPSCP,itens.BDCODEMP) and tolrat.bdCHAVELAN = itens.bdCHAVE and tolrat.bdORDEM = itens.bdORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat ON (lanrat.bdCODEMP = tolrat.BDCODEMPSUC AND lanrat.bdCHAVE = tolrat.bdCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat ON (cclrat.bdCODPLAPADRAO = lanrat.bdCODPLAPADRAO AND cclrat.bdCODTPLA = lanrat.bdCREDITO) ';

      wSQL = wSQL||       'UNION ALL ';

      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' BDREFLAN, d500.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 11 AS BDCODTP, ';
--          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
      wSQL = wSQL||              'PGTO.BDVALORPGTOPAR BDVL_ITEM,';
      wSQL = wSQL||              'd500.BDCODNATREC,d500.BDCODCTA,d500.BDCODCSTPIS,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(D500.BDVL_BC_PIS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDBCPIS, ';
      wSQL = wSQL||              'd500.BDALIQ_PIS AS BDALIQPIS,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(D500.BDVLRPIS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDVLRPIS, ';
      wSQL = wSQL||              'd500.BDCODCSTCOF,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(D500.BDVL_BC_COF, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDBCCOFINS, ';
      wSQL = wSQL||              'd500.BDALIQ_COF AS BDALIQCOFINS, ';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(D500.BDVLRCOFINS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA, ITENS.BDCODSCP, ITENS.BDREFSOC ';
      wSQL = wSQL||       'FROM (SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, S.BDVALORNOTA ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5))';
      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
        wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||              'AND exists(select * ';
      wSQL = wSQL||                         'from VEF_EMP_TMOVSAIITENS SI ';
      wSQL = wSQL||                         'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
      wSQL = wSQL||                         'where SI.BDCODEMP = S.BDCODEMP and ';
      wSQL = wSQL||                         'SI.BDCHAVE = S.BDCHAVE)) mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'JOIN (SELECT P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR, ';
      wSQL = wSQL||                    'CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETPIS, 0)) + SUM(COALESCE(P.BDVALORRETCOFINS, 0)) + SUM(COALESCE(P.BDVALORRETCSLL, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETIRRF, 0)) + SUM(COALESCE(P.BDVALORRETISSQN, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR, P.BDCODNAT ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVSAIPARPGTO P ';
      wSQL = wSQL||             'WHERE P.'||TRIM(:PRWHEREEMPRESAS)||' ';
      wSQL = wSQL||               'AND (CAST(SUBSTRING(P.BDDATAPGTOPAR FROM 1 FOR 4) || SUBSTRING(P.BDDATAPGTOPAR FROM 6 FOR 2) AS INTEGER) = '||:PRREFERENCIA||') ';
      wSQL = wSQL||               'AND p.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
      wSQL = wSQL||             'GROUP BY P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR, P.BDCODNAT ';
      wSQL = wSQL||            ') PGTO ON (PGTO.BDCODEMP = mov.BDCODEMP AND PGTO.BDCHAVE = mov.BDCHAVE) ';
          --wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (PGTO.BDCODEMP = itens.BDCODEMP AND PGTO.BDCHAVE = itens.BDCHAVE AND PGTO.BDCODNAT = ITENS.BDCODNAT) '; Alt.: #227786
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (PGTO.BDCODEMP = itens.BDCODEMP AND PGTO.BDCHAVE = itens.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = itens.BDCODEMP AND SCP.BDCODSCP = itens.BDCODSCP AND SCP.BDREFEMP = itens.BDREFSOC AND '''||:PRAJUSTESCP||''' = ''TRUE'') ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT i.bdCODEMP, i.bdCHAVE, SUM(i.bdVLRCONTAB) AS bdVLRCONTABTOTAL '; -- Alt.: #135727 - Deve considerar apenas o valor contábil que gera as parcelas, caso contrario o valor das parcelas eh menor que o total da nota(sustitui o bdVALORNOTA)...
      wSQL = wSQL||                        'FROM VEF_EMP_TMOVSAIITENS i ';
      wSQL = wSQL||                        'LEFT OUTER JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT) ';
      wSQL = wSQL||                        'WHERE nat.bdLANCPARCELAMENTO = ''TRUE'' ';
      wSQL = wSQL||                        'GROUP BY i.bdCODEMP, i.bdCHAVE) iVlr on (iVlr.bdCODEMP = pgto.bdCODEMP AND iVlr.bdCHAVE = pgto.bdCHAVE) ';
      wSQL = wSQL||       'JOIN (SELECT x.* FROM VEF_EMP_TD500SAI x ';
      wSQL = wSQL||             'WHERE not exists(SELECT p.BDCODEMP, p.BDCHAVE FROM VEF_EMP_TMOVPROSAI p WHERE p.BDCODEMP = x.BDCODEMP AND p.BDCHAVE = x.BDCHAVE) ';
      wSQL = wSQL||             ') d500 ON (mov.BDCODEMP = d500.BDCODEMP AND mov.BDCHAVE = d500.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN(SELECT PGTO.BDCODEMP, PGTO.BDCHAVELAN, PGTO.BDORDEMPAR, MIN(PGTO.BDCHAVE) as BDCHAVE, PGTO.BDCODEMPSUC ';
      wSQL = wSQL||                       'FROM TOL_VEF_EMP_TMOVSAIPARPGTO PGTO ';
--          wSQL = wSQL||                       'WHERE bdFORMULA LIKE ''%NAT%LAN(%)'' '; -- Alt.: 80135 - Apenas contas de valor contábil...
      wSQL = wSQL||                       'GROUP BY PGTO.BDCODEMP, PGTO.BDCHAVELAN, PGTO.BDORDEMPAR, PGTO.BDCODEMPSUC) tol on (TOL.BDCODEMPSUC = COALESCE(SCP.BDCODEMPSCP,PGTO.BDCODEMP) and tol.BDCHAVELAN = PGTO.BDCHAVE and tol.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMPSUC and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE,BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM,BDCODEMPSUC) TOLRAT on (tolrat.BDCODEMPSUC = COALESCE(SCP.BDCODEMPSCP,itens.BDCODEMP) and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMPSUC and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
      wSQL = wSQL||       'WHERE ((d500.BDCODCSTPIS is not null) OR (d500.bdcodcstcof is not null)) ';

      EXECUTE STATEMENT ( wSQLPREFIXO || wSQL || wSQLSUFIXO );

      wSQL =             'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' BDREFLAN, c500.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 12 AS BDCODTP, ';
--          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
      wSQL = wSQL||              'PGTO.BDVALORPGTOPAR BDVL_ITEM,';
      wSQL = wSQL||              'c500.BDCODNATREC, NULL AS BDCODCTA, c500.BDCODCSTPIS,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(C500.BDVL_BC_PIS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDBCPIS, ';
      wSQL = wSQL||              'c500.BDALIQ_PIS AS BDALIQPIS,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(C500.BDVLRPIS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDVLRPIS, ';
      wSQL = wSQL||              'c500.BDCODCSTCOF,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(C500.BDVL_BC_COF, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDBCCOFINS, ';
      wSQL = wSQL||              'c500.BDALIQ_COF AS BDALIQCOFINS,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(C500.BDVLRCOFINS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA,ITENS.BDCODSCP, ITENS.BDREFSOC ';
      wSQL = wSQL||       'FROM (SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, S.BDVALORNOTA ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||             'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
      wSQL = wSQL||               'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
        wSQL = wSQL||               'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||              'AND exists(select * ';
      wSQL = wSQL||              'from VEF_EMP_TMOVSAIITENS SI ';
      wSQL = wSQL||              'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
      wSQL = wSQL||              'where SI.BDCODEMP = S.BDCODEMP and ';
      wSQL = wSQL||              'SI.BDCHAVE = S.BDCHAVE)) mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'JOIN (SELECT P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR, ';
      wSQL = wSQL||                    'CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETPIS, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETCOFINS, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETCSLL, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETIRRF, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETISSQN, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR, P.BDCODNAT ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVSAIPARPGTO P ';
      wSQL = wSQL||             'WHERE P.'||TRIM(:PRWHEREEMPRESAS)||' ';
      wSQL = wSQL||               'AND (CAST(SUBSTRING(P.BDDATAPGTOPAR FROM 1 FOR 4) || SUBSTRING(P.BDDATAPGTOPAR FROM 6 FOR 2) AS INTEGER) = '||:PRREFERENCIA||') ';
      --wSQL = wSQL||               'AND P.BDCODTIPOBAIXA <> 2 ';
      wSQL = wSQL||               'AND p.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
      wSQL = wSQL||             'GROUP BY P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR, P.BDCODNAT ';
      wSQL = wSQL||            ') PGTO ON (PGTO.BDCODEMP = mov.BDCODEMP AND PGTO.BDCHAVE = mov.BDCHAVE) ';
          --wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (PGTO.BDCODEMP = itens.BDCODEMP AND PGTO.BDCHAVE = itens.BDCHAVE AND PGTO.BDCODNAT = ITENS.BDCODNAT) '; Alt.: #227786
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (PGTO.BDCODEMP = itens.BDCODEMP AND PGTO.BDCHAVE = itens.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = itens.BDCODEMP AND SCP.BDCODSCP = itens.BDCODSCP AND SCP.BDREFEMP = itens.BDREFSOC AND '''||:PRAJUSTESCP||''' = ''TRUE'') ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT i.bdCODEMP, i.bdCHAVE, SUM(i.bdVLRCONTAB) AS bdVLRCONTABTOTAL '; -- Alt.: #135727 - Deve considerar apenas o valor contábil que gera as parcelas, caso contrario o valor das parcelas eh menor que o total da nota(sustitui o bdVALORNOTA)...
      wSQL = wSQL||                        'FROM VEF_EMP_TMOVSAIITENS i ';
      wSQL = wSQL||                        'LEFT OUTER JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT) ';
      wSQL = wSQL||                        'WHERE nat.bdLANCPARCELAMENTO = ''TRUE'' ';
      wSQL = wSQL||                        'GROUP BY i.bdCODEMP, i.bdCHAVE) iVlr on (iVlr.bdCODEMP = pgto.bdCODEMP AND iVlr.bdCHAVE = pgto.bdCHAVE) ';
      wSQL = wSQL||       'JOIN (SELECT x.* FROM VEF_EMP_TC500SAI x ';
      wSQL = wSQL||             'WHERE not exists(SELECT p.BDCODEMP, p.BDCHAVE FROM VEF_EMP_TMOVPROSAI p WHERE p.BDCODEMP = x.BDCODEMP AND p.BDCHAVE = x.BDCHAVE) ';
      wSQL = wSQL||             ') c500 ON (mov.BDCODEMP = C500.BDCODEMP AND mov.BDCHAVE = C500.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN(SELECT PGTO.BDCODEMP, PGTO.BDCHAVELAN, PGTO.BDORDEMPAR, MIN(PGTO.BDCHAVE) as BDCHAVE, PGTO.BDCODEMPSUC ';
      wSQL = wSQL||                       'FROM TOL_VEF_EMP_TMOVSAIPARPGTO PGTO ';
--          wSQL = wSQL||                       'WHERE bdFORMULA LIKE ''%NAT%LAN(%)'' '; -- Alt.: 80135 - Apenas contas de valor contábil...
      wSQL = wSQL||                       'GROUP BY PGTO.BDCODEMP, PGTO.BDCHAVELAN, PGTO.BDORDEMPAR, PGTO.BDCODEMPSUC) tol on (TOL.BDCODEMPSUC = COALESCE(SCP.BDCODEMPSCP,PGTO.BDCODEMP) and tol.BDCHAVELAN = PGTO.BDCHAVE and tol.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMPSUC and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE,BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM,BDCODEMPSUC) TOLRAT on (tolrat.BDCODEMPSUC = COALESCE(SCP.BDCODEMPSCP,itens.BDCODEMP) and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMPSUC and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
      wSQL = wSQL||       'WHERE ((C500.BDCODCSTPIS is not null) OR (C500.bdcodcstcof is not null)) ';

      wSQL = wSQL||       'UNION ALL ';

      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' BDREFLAN, f500.BDCHAVE, f500.BDORDEM, f500.BDORDEMF500 AS BDORDEMPRO, 13 AS BDCODTP, ';
--          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
      wSQL = wSQL||              'PGTO.BDVALORPGTOPAR BDVL_ITEM,';
      wSQL = wSQL||              'f500.BDCODNATREC, NULL AS BDCODCTA, f500.BDCODCSTPIS, ';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(F500.BDBASEPIS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDBCPIS, ';
      wSQL = wSQL||              'f500.BDALIQPIS,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(F500.BDVLRPIS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDVLRPIS, ';
      wSQL = wSQL||              'f500.BDCODCSTCOF,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(F500.BDBASECOF, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDBCCOFINS, ';
      wSQL = wSQL||              'f500.BDALIQCOF AS BDALIQCOFINS,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(F500.BDVLRCOF, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA, ITENS.BDCODSCP, ITENS.BDREFSOC ';
      wSQL = wSQL||       'FROM (SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, S.BDVALORNOTA ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
        wSQL = wSQL||                'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||              'AND exists(select * ';
      wSQL = wSQL||              'from VEF_EMP_TMOVSAIITENS SI ';
      wSQL = wSQL||              'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
      wSQL = wSQL||              'where SI.BDCODEMP = S.BDCODEMP and ';
      wSQL = wSQL||              'SI.BDCHAVE = S.BDCHAVE)) mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'JOIN (SELECT P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR, ';
      wSQL = wSQL||                    'CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + SUM(COALESCE(P.BDVALORRETPIS, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETCOFINS, 0)) + SUM(COALESCE(P.BDVALORRETCSLL, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETIRRF, 0)) + SUM(COALESCE(P.BDVALORRETISSQN, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR, P.BDCODNAT ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVSAIPARPGTO P ';
      wSQL = wSQL||             'WHERE P.'||TRIM(:PRWHEREEMPRESAS)||' ';
      wSQL = wSQL||               'AND (CAST(SUBSTRING(P.BDDATAPGTOPAR FROM 1 FOR 4) || SUBSTRING(P.BDDATAPGTOPAR FROM 6 FOR 2) AS INTEGER) = '||:PRREFERENCIA||') ';
      --wSQL = wSQL||               'AND P.BDCODTIPOBAIXA <> 2 ';
      wSQL = wSQL||               'AND p.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
      wSQL = wSQL||             'GROUP BY P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR, P.BDCODNAT ';
      wSQL = wSQL||            ') PGTO ON (PGTO.BDCODEMP = mov.BDCODEMP AND PGTO.BDCHAVE = mov.BDCHAVE) ';
          --wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (PGTO.BDCODEMP = itens.BDCODEMP AND PGTO.BDCHAVE = itens.BDCHAVE AND PGTO.BDCODNAT = ITENS.BDCODNAT) '; Alt.: #227786
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSAIITENS itens ON (PGTO.BDCODEMP = itens.BDCODEMP AND PGTO.BDCHAVE = itens.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = itens.BDCODEMP AND SCP.BDCODSCP = itens.BDCODSCP AND SCP.BDREFEMP = itens.BDREFSOC AND '''||:PRAJUSTESCP||''' = ''TRUE'') ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT i.bdCODEMP, i.bdCHAVE, SUM(i.bdVLRCONTAB) AS bdVLRCONTABTOTAL '; -- Alt.: #135727 - Deve considerar apenas o valor contábil que gera as parcelas, caso contrario o valor das parcelas eh menor que o total da nota(sustitui o bdVALORNOTA)...
      wSQL = wSQL||                        'FROM VEF_EMP_TMOVSAIITENS i ';
      wSQL = wSQL||                        'LEFT OUTER JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT) ';
      wSQL = wSQL||                        'WHERE nat.bdLANCPARCELAMENTO = ''TRUE'' ';
      wSQL = wSQL||                        'GROUP BY i.bdCODEMP, i.bdCHAVE) iVlr on (iVlr.bdCODEMP = pgto.bdCODEMP AND iVlr.bdCHAVE = pgto.bdCHAVE) ';
      wSQL = wSQL||       'JOIN (SELECT X.* FROM VEF_EMP_TF500SAI X ';
      wSQL = wSQL||             'WHERE not exists(SELECT Y.BDCODEMP, Y.BDCHAVE FROM VEF_EMP_TMOVPROSAI Y WHERE X.BDCODEMP = Y.BDCODEMP AND X.BDCHAVE = Y.BDCHAVE) ';
      wSQL = wSQL||             ') F500 ON (mov.BDCODEMP = F500.BDCODEMP AND mov.BDCHAVE = F500.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN(SELECT PGTO.BDCODEMP, PGTO.BDCHAVELAN, PGTO.BDORDEMPAR, MIN(PGTO.BDCHAVE) as BDCHAVE, PGTO.BDCODEMPSUC ';
      wSQL = wSQL||                       'FROM TOL_VEF_EMP_TMOVSAIPARPGTO PGTO ';
--          wSQL = wSQL||                       'WHERE bdFORMULA LIKE ''%NAT%LAN(%)'' '; -- Alt.: 80135 - Apenas contas de valor contábil...
      wSQL = wSQL||                       'GROUP BY PGTO.BDCODEMP, PGTO.BDCHAVELAN, PGTO.BDORDEMPAR, PGTO.BDCODEMPSUC) tol on (TOL.BDCODEMPSUC = COALESCE(SCP.BDCODEMPSCP,PGTO.BDCODEMP) and tol.BDCHAVELAN = PGTO.BDCHAVE and tol.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMPSUC and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE,BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM,BDCODEMPSUC) TOLRAT on (tolrat.BDCODEMPSUC = COALESCE(SCP.BDCODEMPSCP,itens.BDCODEMP) and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMPSUC and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
      wSQL = wSQL||       'WHERE ((F500.BDCODCSTPIS is not null) OR (F500.bdcodcstcof is not null)) ';

      wSQL = wSQL||       'UNION ALL ';

      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' BDREFLAN, a170.BDCHAVE, a170.BDORDEM, a170.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, ';
--          wSQL = wSQL||              '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          --wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(A170.BDVL_ITEM, 0)) / ITENS.BDVLRCONTAB AS DM_NUMERIC_15_2) BDVL_ITEM,'; Alt.: #227786 
          wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(A170.BDVL_ITEM, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDVL_ITEM,';
      wSQL = wSQL||              'a170.BDCODNATREC, NULL AS BDCODCTA, a170.BDCODCSTPIS,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(A170.BDVL_BC_PIS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDBCPIS, ';
      wSQL = wSQL||              'a170.BDALIQ_PIS AS BDALIQPIS,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(A170.BDVL_PIS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDVLRPIS, ';
      wSQL = wSQL||              'a170.BDCODCSTCOF,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(A170.BDVL_BC_COFINS, 0)) / IIF(IVLR.BDVLRCONTABTOTAL > 0, IVLR.BDVLRCONTABTOTAL, 1) AS DM_NUMERIC_15_2) BDBCCOFINS, ';
      wSQL = wSQL||              'a170.BDALIQ_COFINS AS BDALIQCOFINS,';
      wSQL = wSQL||              'CAST((PGTO.BDVALORPGTOPAR * COALESCE(A170.BDVL_COFINS, 0)) / IIF(MOV.BDVALORNOTA > 0, MOV.BDVALORNOTA, 1) AS DM_NUMERIC_15_2) BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA, ITENS.BDCODSCP, ITENS.BDREFSOC ';
      wSQL = wSQL||       'FROM (SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDCODSITNF, S.BDVALORNOTA ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVSER s ';
      wSQL = wSQL||             'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
      wSQL = wSQL||               'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
        wSQL = wSQL||               'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||               'AND EXISTS(SELECT * '; -- Alt.: #88586 - Ajustes para não exportar lançamentos quando tenham alguma CFOP com a opção "Não levar Sped Contribuições"
      wSQL = wSQL||                          'FROM VEF_EMP_TMOVSERITENS si ';
      wSQL = wSQL||                          'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = si.bdCODNAT AND ((nat.bdNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.bdNAOEXPEFDCONT)) = TRIM(''FALSE''))) ) ';
      wSQL = wSQL||                          'WHERE si.bdCODEMP = s.bdCODEMP ';
      wSQL = wSQL||                            'AND si.bdCHAVE  = s.bdCHAVE)) mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'JOIN (SELECT P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR, ';
      wSQL = wSQL||                    'CAST(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + SUM(COALESCE(P.BDVALORRETPIS, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETCOFINS, 0)) + SUM(COALESCE(P.BDVALORRETCSLL, 0)) + SUM(COALESCE(P.BDVALORRETIRRF, 0)) + ';
      wSQL = wSQL||                     'SUM(COALESCE(P.BDVALORRETISSQN, 0)) + SUM(COALESCE(P.BDVALORRETINSS, 0)) AS DM_NUMERIC_15_2) BDVALORPGTOPAR, P.BDCODNAT ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVSERPARPGTO P ';
      wSQL = wSQL||             'WHERE P.'||TRIM(:PRWHEREEMPRESAS)||' ';
      wSQL = wSQL||               'AND (CAST(SUBSTRING(P.BDDATAPGTOPAR FROM 1 FOR 4) || SUBSTRING(P.BDDATAPGTOPAR FROM 6 FOR 2) AS INTEGER) = '||:PRREFERENCIA||') ';
      --wSQL = wSQL||               'AND P.BDCODTIPOBAIXA <> 2 ';
      wSQL = wSQL||               'AND p.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
      wSQL = wSQL||             'GROUP BY P.BDCODEMP, P.BDCHAVE, P.BDORDEMPAR, P.BDCODNAT ';
      wSQL = wSQL||            ') PGTO ON (PGTO.BDCODEMP = mov.BDCODEMP AND PGTO.BDCHAVE = mov.BDCHAVE) ';
          --wSQL = wSQL||       'JOIN VEF_EMP_TMOVSERITENS itens ON (PGTO.BDCODEMP = itens.BDCODEMP AND PGTO.BDCHAVE = itens.BDCHAVE AND PGTO.BDCODNAT = ITENS.BDCODNAT) '; Alt.: #227786
          wSQL = wSQL||       'JOIN VEF_EMP_TMOVSERITENS itens ON (PGTO.BDCODEMP = itens.BDCODEMP AND PGTO.BDCHAVE = itens.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = itens.BDCODEMP AND SCP.BDCODSCP = itens.BDCODSCP AND SCP.BDREFEMP = itens.BDREFSOC AND '''||:PRAJUSTESCP||''' = ''TRUE'') ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT i.bdCODEMP, i.bdCHAVE, SUM(i.bdVLRCONTAB) AS bdVLRCONTABTOTAL '; -- Alt.: #135727 - Deve considerar apenas o valor contábil que gera as parcelas, caso contrario o valor das parcelas eh menor que o total da nota(sustitui o bdVALORNOTA)...
      wSQL = wSQL||                        'FROM VEF_EMP_TMOVSERITENS i ';
      wSQL = wSQL||                        'LEFT OUTER JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT) ';
      wSQL = wSQL||                        'WHERE nat.bdLANCPARCELAMENTO = ''TRUE'' ';
      wSQL = wSQL||                        'GROUP BY i.bdCODEMP, i.bdCHAVE) iVlr on (iVlr.bdCODEMP = pgto.bdCODEMP AND iVlr.bdCHAVE = pgto.bdCHAVE) ';
      wSQL = wSQL||       'JOIN VEF_EMP_TA170 a170 ON (mov.BDCODEMP = a170.BDCODEMP AND mov.BDCHAVE = a170.BDCHAVE AND itens.BDORDEM = a170.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_BASE_TTABSITNFISS sit ON (mov.BDCODSITNF = sit.BDCODSITNF) ';
      wSQL = wSQL||       'LEFT OUTER JOIN(SELECT PGTO.BDCODEMP, PGTO.BDCHAVELAN, PGTO.BDORDEMPAR, MIN(PGTO.BDCHAVE) as BDCHAVE, PGTO.BDCODEMPSUC ';
      wSQL = wSQL||                       'FROM TOL_VEF_EMP_TMOVSERPARPGTO PGTO ';
--          wSQL = wSQL||                       'WHERE bdFORMULA LIKE ''%NAT%LAN(%)'' '; -- Alt.: 80135 - Apenas contas de valor contábil...
      wSQL = wSQL||                       'GROUP BY PGTO.BDCODEMP, PGTO.BDCHAVELAN, PGTO.BDORDEMPAR, PGTO.BDCODEMPSUC) tol on (TOL.BDCODEMPSUC = COALESCE(SCP.BDCODEMPSCP,PGTO.BDCODEMP) and tol.BDCHAVELAN = PGTO.BDCHAVE and tol.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMPSUC and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE,BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATSER GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM,BDCODEMPSUC) tolrat on (tolrat.BDCODEMPSUC = COALESCE(SCP.BDCODEMPSCP,itens.BDCODEMP) and tolrat.BDCHAVELAN = itens.BDCHAVE and tolrat.BDORDEM = itens.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMPSUC and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
      wSQL = wSQL||       'WHERE (a170.BDCODCSTCOF is not null) ';

      EXECUTE STATEMENT ( wSQLPREFIXO || wSQL || wSQLSUFIXO );

      /* Continuação dessa procedure, pois excedeu o tamanho */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M400_M800P_2 (:prCODEMP, :prREFERENCIA, :prWHEREEMPRESAS, :PRAJUSTESCP, :PRCODEMPSO);
    END
END
^

create or alter procedure SP_APURACAO_BLOCOM_M400_M800AUX (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRAJUSTESCP DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
declare variable WINCTRIB integer;
declare variable WCODCRIT integer;
declare variable WSQL varchar(32750);
declare variable WSQLPREFIXO varchar(800);
declare variable WSQLSUFIXO varchar(800);
declare variable WEXPNFCOMVALSAI varchar(5);
declare variable WMOD_TRANSPORTE varchar(50);
BEGIN
-- Modelos para lançamento de entrada, faz isso para não carregar dados de movimentos errados.
-- Por exemplo: Não carregar dados dos produtos em notas de transporte, caso tenham produtos lançados...
wMOD_TRANSPORTE = '7,8,9,10,11,13,14,15,16,26,27,57,67,800,63'; -- Transporte

  -- Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDCODCRIT, BDEXPNFCOMVALSAI FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :wINCTRIB, :wCODCRIT, :wEXPNFCOMVALSAI;

  if ((:WINCTRIB is null) and (:PRCODEMPSO > 0)) then
    begin
      SELECT BDINCTRIB+1, BDCODCRIT, BDEXPNFCOMVALSAI FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMPSO
      INTO :wINCTRIB, :wCODCRIT, :wEXPNFCOMVALSAI;
    end

  IF ((wINCTRIB IS NOT NULL) AND (wEXPNFCOMVALSAI <> 'TRUE')) THEN
    BEGIN
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
        /* REGISTRO M400: RECEITAS ISENTAS, NÃO ALCANÇADAS PELA INCIDÊNCIA DA CONTRIBUIÇÃO, SUJEITAS A ALÍQUOTA ZERO OU DE VENDAS COM SUSPENSÃO - PIS/PASEP
           REGISTRO M800: RECEITAS ISENTAS, NÃO ALCANÇADAS PELA INCIDÊNCIA DA CONTRIBUIÇÃO, SUJEITAS A ALÍQUOTA ZERO OU DE VENDAS COM SUSPENSÃO - COFINS */
        EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M400_M800PAR (:prcodemp,  :prREFERENCIA, :prWHEREEMPRESAS, :PRAJUSTESCP, :PRCODEMPSO);

      wSQLPREFIXO =              'INSERT INTO TMP_VEF_EMP_TBLOCOM_M400_M800 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDVL_ITEM, BDCODNATREC, BDCODCTA, BDCODCSTPIS, BDBCPIS, BDALIQPIS, BDVLRPIS, BDCODCSTCOF, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDCODPLAPADRAO, BDCODTPLA, BDCODEMPSCP) ';

      wSQLPREFIXO = wSQLPREFIXO||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFLAN, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, ';
      wSQLPREFIXO = wSQLPREFIXO||       'aux.BDVL_ITEM, aux.BDCODNATREC, aux.BDCODCTA,';
      wSQLPREFIXO = wSQLPREFIXO||       'IIF(AUX.BDCODCSTPIS IN (''04'',''06'',''07'',''08'',''09''),AUX.BDCODCSTPIS,null) BDCODCSTPIS, ';
      wSQLPREFIXO = wSQLPREFIXO||       'aux.BDBCPIS, aux.BDALIQPIS, aux.BDVLRPIS,';
      wSQLPREFIXO = wSQLPREFIXO||       'IIF(AUX.BDCODCSTCOF IN (''04'',''06'',''07'',''08'',''09''),AUX.BDCODCSTCOF,null) BDCODCSTCOF, ';
      wSQLPREFIXO = wSQLPREFIXO||       'aux.BDBCCOFINS, aux.BDALIQCOFINS, aux.BDVLRCOFINS, ';
      wSQLPREFIXO = wSQLPREFIXO||       'aux.BDCODPLAPADRAO, aux.BDCODTPLA, '||IIF(:PRAJUSTESCP = 'TRUE',' COALESCE(SCP.BDCODEMPSCP,0) ',' 0')||' BDCODEMPSCP ';
      wSQLPREFIXO = wSQLPREFIXO||'FROM (';

      wSQLSUFIXO =                     ') aux ';
      wSQLSUFIXO = wSQLSUFIXO||'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = AUX.BDCODEMP AND SCP.BDCODSCP = AUX.BDCODSCP AND SCP.BDREFEMP = AUX.BDREFSOC) ';
      wSQLSUFIXO = wSQLSUFIXO||'LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstPIS ON (cstPIS.BDCODCSTPIS = aux.BDCODCSTPIS) ';
      wSQLSUFIXO = wSQLSUFIXO||'LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstCOF ON (cstCOF.BDCODCSTCOF = aux.BDCODCSTCOF) ';
      wSQLSUFIXO = wSQLSUFIXO||'WHERE ((cstPIS.BDCSTPIS in (''04'',''06'',''07'',''08'',''09'')) OR ((cstPIS.BDCSTPIS = ''05'') AND (aux.BDALIQPIS = 0)) OR ';
      wSQLSUFIXO = wSQLSUFIXO||       '(cstCOF.BDCSTCOF in (''04'',''06'',''07'',''08'',''09'')) OR ((cstCOF.BDCSTCOF = ''05'') AND (aux.BDALIQCOFINS = 0))) ';
      
      if ((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0)) then
         wSQLSUFIXO = wSQLSUFIXO||' and coalesce(SCP.BDCODEMPSCP, 0) = ' || :PRCODEMP;
      else
      if (:PRAJUSTESCP = 'TRUE') then
         wSQLSUFIXO = wSQLSUFIXO||' and coalesce(SCP.BDCODEMPSCP, 0) = 0';

      /* Saídas - Produtos */
      wSQL =              'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, 2 AS BDCODTP, ';

      IF ((wINCTRIB = 2) AND (wCODCRIT = 2)) THEN
        wSQL = wSQL||            'COALESCE(p.bdVLRITEM, 0) + COALESCE(p.bdVLRFRETE, 0) AS BDVL_ITEM,'; -- Alt.: #140820 #141746 #141860 #142059 #142721 #142727 #144499 #144764 #144765 #146779 - Ajustado para respeitar a mesma regra da solicitação do F550 "#129883"
      else
        wSQL = wSQL||            'COALESCE(p.bdVLRITEM, 0) AS BDVL_ITEM,';

      wSQL = wSQL||              'p.BDCODNATREC, p.BDCODCTA, ';
      wSQL = wSQL||              'p.BDCODCSTPIS, p.BDBCPIS, p.BDALIQPIS, p.BDVLRPIS,';
      wSQL = wSQL||              'p.BDCODCSTCOF, p.BDBCCOFINS, p.BDALIQCOFINS, p.BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA,I.BDCODSCP, I.BDREFSOC ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
      wSQL = wSQL||                'AND (s.BDMODELO not in ('||wMOD_TRANSPORTE||')) '; -- Modelos que não são produtos...

      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
        wSQL = wSQL||              'AND (s.BDCONDPGTO <> 1) ';

      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                'AND exists(select * ';
      wSQL = wSQL||                           'from VEF_EMP_TMOVSAIITENS SI ';
      wSQL = wSQL||                           'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
      wSQL = wSQL||                           'where SI.BDCODEMP = S.BDCODEMP and ';
      wSQL = wSQL||                           'SI.BDCHAVE = S.BDCHAVE)';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i ON (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVPROSAI p ON (p.BDCODEMP = i.BDCODEMP AND p.BDCHAVE = i.BDCHAVE AND p.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, MIN(t.bdCHAVE) as BDCHAVE, T.BDCODEMPSUC ';
      wSQL = wSQL||                        'FROM TOL_VEF_EMP_TMOVSAI t ';
      wSQL = wSQL||                        'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.bdCODEMP = t.BDCODEMPSUC and lan.bdCHAVE = t.bdCHAVE) '; -- Alt.: #126303 - Quando exportava contas com desconto, a conta do valor contabil do credito era a segunda conta, pois isso levava a conta em branco...
      wSQL = wSQL||                        'WHERE t.bdFORMULA LIKE ''%NAT%LAN(%)'' '; -- Alt.: 80135 - Apenas contas de valor contábil...
      wSQL = wSQL||                          'AND lan.bdCREDITO IS NOT NULL '; -- Alt.: #126303 - Quando exportava contas com desconto, a conta do valor contabil do credito era a segunda conta, pois isso levava a conta em branco...
      wSQL = wSQL||                        'GROUP BY t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, T.BDCODEMPSUC) tol on (tol.BDCODEMP = i.BDCODEMP and tol.BDCHAVESAI = i.BDCHAVE and tol.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMPSUC and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = COALESCE(p.BDCODPLAPADRAO,lan.BDCODPLAPADRAO) and ccl.BDCODTPLA = COALESCE(p.BDCODTPLA,lan.BDCREDITO)) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE, BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM,BDCODEMPSUC) tolrat on (tolrat.BDCODEMP = i.BDCODEMP and tolrat.BDCHAVELAN = i.BDCHAVE and tolrat.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMPSUC and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = COALESCE(p.BDCODPLAPADRAO,lanrat.BDCODPLAPADRAO) and cclrat.BDCODTPLA = COALESCE(p.BDCODTPLA,lanrat.BDCREDITO)) ';

      wSQL = wSQL||       'UNION ALL ';
      /* Saídas - Transporte (D100) */
      wSQL = wSQL||       'select mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL as BDORDEM,';
      wSQL = wSQL||              'NULL as BDORDEMPRO, 16 as BDCODTP, I.BDVLRCONTAB as BDVL_ITEM, d100.BDCODNATREC, NULL as BDCODCTA,';
      wSQL = wSQL||              'd100.BDCODCSTPIS, d100.BDVL_BC_PIS as BDBCPIS, d100.BDALIQ_PIS as BDALIQPIS, d100.BDVLRPIS,';
      wSQL = wSQL||              'd100.BDCODCSTCOF, d100.BDVL_BC_COF as BDBCCOFINS, d100.BDALIQ_COF as BDALIQCOFINS, d100.BDVLRCOFINS,';
      wSQL = wSQL||              'COALESCE(CCL.BDCODPLAPADRAO, CCLRAT.BDCODPLAPADRAO) as BDCODPLAPADRAO,';
      wSQL = wSQL||              'COALESCE(CCL.BDCODTPLA, CCLRAT.BDCODTPLA) as BDCODTPLA,I.BDCODSCP, I.BDREFSOC ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDVALORNOTA ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
      wSQL = wSQL||                'AND (s.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Modelos que não são produtos...

      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
        wSQL = wSQL||              'AND (s.BDCONDPGTO <> 1) ';

      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                'AND exists(select * ';
      wSQL = wSQL||                           'from VEF_EMP_TMOVSAIITENS SI ';
      wSQL = wSQL||                           'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
      wSQL = wSQL||                           'where SI.BDCODEMP = S.BDCODEMP and ';
      wSQL = wSQL||                           'SI.BDCHAVE = S.BDCHAVE)';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i ON (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TD100SAI d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, MIN(t.bdCHAVE) as BDCHAVE, T.BDCODEMPSUC ';
      wSQL = wSQL||                        'FROM TOL_VEF_EMP_TMOVSAI t ';
      wSQL = wSQL||                        'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.bdCODEMP = t.BDCODEMPSUC and lan.bdCHAVE = t.bdCHAVE) '; -- Alt.: #126303 - Quando exportava contas com desconto, a conta do valor contabil do credito era a segunda conta, pois isso levava a conta em branco...
      wSQL = wSQL||                        'WHERE t.bdFORMULA LIKE ''%NAT%LAN(%)'' '; -- Alt.: 80135 - Apenas contas de valor contábil...
      wSQL = wSQL||                          'AND lan.bdCREDITO IS NOT NULL '; -- Alt.: #126303 - Quando exportava contas com desconto, a conta do valor contabil do credito era a segunda conta, pois isso levava a conta em branco...
      wSQL = wSQL||                        'GROUP BY t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, T.BDCODEMPSUC) tol on (tol.BDCODEMP = i.BDCODEMP and tol.BDCHAVESAI = i.BDCHAVE and tol.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMPSUC and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE,BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM,BDCODEMPSUC) tolrat on (tolrat.BDCODEMP = i.BDCODEMP and tolrat.BDCHAVELAN = i.BDCHAVE and tolrat.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMPSUC and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
      wSQL = wSQL||       'WHERE d100.bdCODEMP IS NOT NULL ';

      wSQL = wSQL||       'UNION ALL ';
      
      wSQL = wSQL||       'select mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL as BDORDEM, ';
      wSQL = wSQL||              'NULL as BDORDEMPRO, 18 as BDCODTP, mov.BDVALORNOTA as BDVL_ITEM, d400.BDCODNATREC, NULL as BDCODCTA, ';
      wSQL = wSQL||              'd400.BDCODCSTPIS, d400.BDVL_BC_PIS as BDBCPIS, d400.BDALIQ_PIS as BDALIQPIS, d400.BDVL_PIS, ';
      wSQL = wSQL||              'd400.BDCODCSTCOF, d400.BDVL_BC_COF as BDBCCOFINS, d400.BDALIQ_COF as BDALIQCOFINS, d400.BDVL_COF, ';
      wSQL = wSQL||              'COALESCE(CCL.BDCODPLAPADRAO, CCLRAT.BDCODPLAPADRAO) as BDCODPLAPADRAO, ';
      wSQL = wSQL||              'COALESCE(CCL.BDCODTPLA, CCLRAT.BDCODTPLA) as BDCODTPLA,I.BDCODSCP, I.BDREFSOC  ';
      wSQL = wSQL||       'FROM ( ';
      wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDVALORNOTA ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
      wSQL = wSQL||                'AND (s.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Modelos que não são produtos...

      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
        wSQL = wSQL||              'AND (s.BDCONDPGTO <> 1) ';

      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                'AND exists(select * ';
      wSQL = wSQL||                           'from VEF_EMP_TMOVSAIITENS SI ';
      wSQL = wSQL||                           'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
      wSQL = wSQL||                           'where SI.BDCODEMP = S.BDCODEMP and ';
      wSQL = wSQL||                           'SI.BDCHAVE = S.BDCHAVE) ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i ON (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TD400SAI d400 on (d400.BDCODEMP = mov.BDCODEMP AND d400.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, MIN(t.bdCHAVE) as BDCHAVE, T.BDCODEMPSUC ';
      wSQL = wSQL||                        'FROM TOL_VEF_EMP_TMOVSAI t ';
      wSQL = wSQL||                        'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.bdCODEMP = t.BDCODEMPSUC and lan.bdCHAVE = t.bdCHAVE) '; -- Alt.: #126303 - Quando exportava contas com desconto, a conta do valor contabil do credito era a segunda conta, pois isso levava a conta em branco...
      wSQL = wSQL||                        'WHERE t.bdFORMULA LIKE ''%NAT%LAN(%)'' ';  -- Alt.: 80135 - Apenas contas de valor contábil...
      wSQL = wSQL||                          'AND lan.bdCREDITO IS NOT NULL ';   -- Alt.: #126303 - Quando exportava contas com desconto, a conta do valor contabil do credito era a segunda conta, pois isso levava a conta em branco...
      wSQL = wSQL||                        'GROUP BY t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, T.BDCODEMPSUC) tol on (tol.BDCODEMP = i.BDCODEMP and tol.BDCHAVESAI = i.BDCHAVE and tol.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMPSUC and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE,BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM,BDCODEMPSUC) tolrat on (tolrat.BDCODEMP = i.BDCODEMP and tolrat.BDCHAVELAN = i.BDCHAVE and tolrat.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMPSUC and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';
      wSQL = wSQL||       'WHERE d400.bdCODEMP IS NOT NULL ';

      wSQL = wSQL||       'UNION ALL ';
      /* Saídas - F500 */
      wSQL = wSQL||       'SELECT mov.bdCODEMP, COALESCE(emp.bdCODMATRIZ, mov.bdCODEMP) AS bdCODMATRIZ, mov.bdREFLAN, mov.bdCHAVE, NULL AS bdORDEM, ';
      wSQL = wSQL||              'NULL AS BDORDEMPRO, 17 AS BDCODTP, I.BDVLRCONTAB AS bdVL_ITEM, f500.bdCODNATREC, NULL AS bdCODCTA, ';
      wSQL = wSQL||              'f500.bdCODCSTPIS, f500.bdBASEPIS AS bdBCPIS, f500.bdALIQPIS AS bdALIQPIS, f500.bdVLRPIS, ';
      wSQL = wSQL||              'f500.bdCODCSTCOF, f500.bdBASECOF AS bdBCCOFINS, f500.bdALIQCOF AS bdALIQCOFINS, f500.bdVLRCOF AS bdVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(ccl.bdCODPLAPADRAO, cclrat.bdCODPLAPADRAO) AS bdCODPLAPADRAO, ';
      wSQL = wSQL||              'COALESCE(ccl.bdCODTPLA, cclrat.bdCODTPLA) AS bdCODTPLA,I.BDCODSCP, I.BDREFSOC  ';
      wSQL = wSQL||       'FROM ( ';
      wSQL = wSQL||              'SELECT s.bdCODEMP, s.bdCHAVE, s.bdREFLAN, s.bdVALORNOTA ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSAI s ';
      wSQL = wSQL||              'WHERE (s.bdCODSITNF NOT IN (2,3,4,5)) ';

      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
        wSQL = wSQL||              'AND (s.BDCONDPGTO <> 1) ';

      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                'AND EXISTS(SELECT * ';
      wSQL = wSQL||                           'FROM VEF_EMP_TMOVSAIITENS si ';
      wSQL = wSQL||                           'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = si.bdCODNAT AND ((nat.bdNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.bdNAOEXPEFDCONT)) = TRIM(''FALSE'')))) ';
      wSQL = wSQL||                           'WHERE si.bdCODEMP = s.bdCODEMP ';
      wSQL = wSQL||                             'AND si.bdCHAVE = s.bdCHAVE) ';
      wSQL = wSQL||                'AND (NOT EXISTS(SELECT * FROM VEF_EMP_TMOVSAI x ';
      wSQL = wSQL||                                'JOIN VEF_EMP_TMOVPROSAI xp ON (xp.bdCODEMP = x.bdCODEMP AND xp.bdCHAVE = x.bdCHAVE) ';
      wSQL = wSQL||                                'WHERE x.bdMODELO NOT IN ('||wMOD_TRANSPORTE||') AND x.bdCODEMP = s.bdCODEMP AND x.bdCHAVE = s.bdCHAVE)) ';
      wSQL = wSQL||                'AND (NOT EXISTS(SELECT * FROM VEF_EMP_TMOVSAI x ';
      wSQL = wSQL||                                'JOIN VEF_EMP_TD100SAI xp ON (xp.bdCODEMP = x.bdCODEMP AND xp.bdCHAVE = x.bdCHAVE) ';
      wSQL = wSQL||                                'WHERE x.bdMODELO IN ('||wMOD_TRANSPORTE||') AND x.bdCODEMP = s.bdCODEMP AND x.bdCHAVE = s.bdCHAVE)) ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.bdCODEMP = mov.bdCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i ON (i.bdCODEMP = mov.bdCODEMP AND i.bdCHAVE = mov.bdCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TF500SAI f500 on (f500.bdCODEMP = mov.bdCODEMP AND f500.bdCHAVE = mov.bdCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, MIN(t.bdCHAVE) AS bdCHAVE, T.BDCODEMPSUC ';
      wSQL = wSQL||                        'FROM TOL_VEF_EMP_TMOVSAI t ';
      wSQL = wSQL||                        'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.bdCODEMP = t.BDCODEMPSUC and lan.bdCHAVE = t.bdCHAVE) ';  -- Alt.: #126303 - Quando exportava contas com desconto, a conta do valor contabil do credito era a segunda conta, pois isso levava a conta em branco...
      wSQL = wSQL||                        'WHERE t.bdFORMULA LIKE ''%NAT%LAN(%)'' ';  -- Alt.: 80135 - Apenas contas de valor contábil...
      wSQL = wSQL||                          'AND lan.bdCREDITO IS NOT NULL ';  -- Alt.: #126303 - Quando exportava contas com desconto, a conta do valor contabil do credito era a segunda conta, pois isso levava a conta em branco...
      wSQL = wSQL||                        'GROUP BY t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, T.BDCODEMPSUC) tol on (tol.bdCODEMP = i.bdCODEMP and tol.bdCHAVESAI = i.bdCHAVE and tol.bdORDEM = i.bdORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.bdCODEMP = tol.BDCODEMPSUC and lan.bdCHAVE = tol.bdCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.bdCODPLAPADRAO = lan.bdCODPLAPADRAO and ccl.bdCODTPLA = lan.bdCREDITO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT bdCODEMP, bdCHAVELAN, bdORDEM, MIN(bdCHAVE) AS bdCHAVE,BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY bdCODEMP, bdCHAVELAN, bdORDEM,BDCODEMPSUC) tolrat on (tolrat.bdCODEMP = i.bdCODEMP and tolrat.bdCHAVELAN = i.bdCHAVE and tolrat.bdORDEM = i.bdORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.bdCODEMP = tolrat.BDCODEMPSUC and lanrat.bdCHAVE = tolrat.bdCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.bdCODPLAPADRAO = lanrat.bdCODPLAPADRAO and cclrat.bdCODTPLA = lanrat.bdCREDITO) ';
      wSQL = wSQL||       'WHERE F500.bdCODEMP IS NOT NULL ';

      wSQL = wSQL||       'UNION ALL ';
      /* Serviço */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, a.BDCHAVE, a.BDORDEM, a.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, ';
      wSQL = wSQL||              'a.BDVL_ITEM, a.BDCODNATREC, NULL AS BDCODCTA, ';
      wSQL = wSQL||              'a.BDCODCSTPIS, a.BDVL_BC_PIS AS BDBCPIS, a.BDALIQ_PIS AS BDALIQPIS, a.BDVL_PIS AS BDVLRPIS,';
      wSQL = wSQL||              'a.BDCODCSTCOF, a.BDVL_BC_COFINS AS BDBCCOFINS, a.BDALIQ_COFINS AS BDALIQCOFINS, a.BDVL_COFINS AS BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(ccl.BDCODPLAPADRAO,cclrat.BDCODPLAPADRAO) as BDCODPLAPADRAO, COALESCE(ccl.BDCODTPLA,cclrat.BDCODTPLA) as BDCODTPLA,I.BDCODSCP, I.BDREFSOC  ';
      wSQL = wSQL||       'FROM (';
      wSQL = wSQL||              'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSER s ';
      wSQL = wSQL||              'WHERE s.BDTIPLAN = 0 '; -- Serviços Emitidos
      wSQL = wSQL||                'AND (s.BDCODSITNF not in (2,3,4,5)) ';

      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
        wSQL = wSQL||              'AND (s.BDCONDPGTO <> 1) ';

      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                'AND EXISTS(SELECT * '; -- Alt.: #88586 - Ajustes para não exportar lançamentos quando tenham alguma CFOP com a opção "Não levar Sped Contribuições"
      wSQL = wSQL||                           'FROM VEF_EMP_TMOVSERITENS si ';
      wSQL = wSQL||                           'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = si.bdCODNAT AND ((nat.bdNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.bdNAOEXPEFDCONT)) = TRIM(''FALSE''))) ) ';
      wSQL = wSQL||                           'WHERE si.bdCODEMP = s.bdCODEMP ';
      wSQL = wSQL||                             'AND si.bdCHAVE  = s.bdCHAVE) ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSERITENS i ON (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TA170 a ON (a.BDCODEMP = i.BDCODEMP AND a.BDCHAVE = i.BDCHAVE AND a.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVESER, t.bdORDEM, MIN(t.bdCHAVE) as BDCHAVE, T.BDCODEMPSUC ';
      wSQL = wSQL||                        'FROM TOL_VEF_EMP_TMOVSER t ';
      wSQL = wSQL||                        'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.bdCODEMP = t.BDCODEMPSUC and lan.bdCHAVE = t.bdCHAVE) '; -- Alt.: #126303 - Quando exportava contas com desconto, a conta do valor contabil do credito era a segunda conta, pois isso levava a conta em branco...
      wSQL = wSQL||                        'WHERE t.bdFORMULA LIKE ''%NAT%LAN(%)'' '; -- Alt.: 80135 - Apenas contas de valor contábil...
      wSQL = wSQL||                          'AND lan.bdCREDITO IS NOT NULL '; -- Alt.: #126303 - Quando exportava contas com desconto, a conta do valor contabil do credito era a segunda conta, pois isso levava a conta em branco...
      wSQL = wSQL||                        'GROUP BY t.bdCODEMP, t.bdCHAVESER, t.bdORDEM, T.BDCODEMPSUC) tol on (tol.BDCODEMP = i.BDCODEMP and tol.BDCHAVESER = i.BDCHAVE and tol.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMPSUC and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) as BDCHAVE,BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATSER GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM,BDCODEMPSUC) tolrat on (tolrat.BDCODEMP = i.BDCODEMP and tolrat.BDCHAVELAN = i.BDCHAVE and tolrat.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat on (lanrat.BDCODEMP = tolrat.BDCODEMPSUC and lanrat.BDCHAVE = tolrat.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA cclrat on (cclrat.BDCODPLAPADRAO = lanrat.BDCODPLAPADRAO and cclrat.BDCODTPLA = lanrat.BDCREDITO) ';

      EXECUTE STATEMENT ( wSQLPREFIXO || wSQL || wSQLSUFIXO );
      
      /* Demais documentos */
      wSQL =              'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDREFLAN, dem.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, ';
      wSQL = wSQL||              'dem.BDVL_OPER AS BDVL_ITEM, dem.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||              'dem.BDCODCSTPIS, dem.BDVL_BC_PIS AS BDBCPIS, dem.BDALIQ_PIS AS BDALIQPIS, dem.BDVLR_PIS AS BDVLRPIS,';
      wSQL = wSQL||              'dem.BDCODCSTCOF, dem.BDVL_BC_COFINS AS BDBCCOFINS, dem.BDALIQ_COFINS AS BDALIQCOFINS, dem.BDVLR_COFINS AS BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(dem.bdCODPLAPADRAO, lan.bdCODPLAPADRAO) AS bdCODPLAPADRAO, COALESCE(dem.bdCODTPLA, lan.bdCREDITO) AS bdCODTPLA,DEM.BDCODSCP, DEM.BDREFSOC  ';
      wSQL = wSQL||       'FROM ( ';
      wSQL = wSQL||               'SELECT dem.BDCODEMP, dem.BDREFLAN, dem.BDCHAVE, dem.bdIND_OPER, dem.BDVL_OPER, dem.BDCODNATREC, dem.bdCODPLAPADRAO, dem.bdCODTPLA, '; -- Caso tenha vários lançamentos na contabilização, vai buscar apenas a primeira conta...
      wSQL = wSQL||                      'dem.BDCODCSTPIS, dem.BDVL_BC_PIS, dem.BDALIQ_PIS, dem.BDVLR_PIS, ';
      wSQL = wSQL||                      'dem.BDCODCSTCOF, dem.BDVL_BC_COFINS, dem.BDALIQ_COFINS, dem.BDVLR_COFINS,DEM.BDCODSCP, DEM.BDREFSOC ';
      wSQL = wSQL||               'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
      wSQL = wSQL||              'left outer join VEF_BASE_TCADTIPODEMDOC CAD on (dem.BDCODTIPODOC = CAD.BDCODTIPODOC)';
      wSQL = wSQL||               'WHERE dem.bdIND_OPER IN (2,3) '; -- Operação Representativa de Receita

      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
        wSQL = wSQL||                'AND (dem.BDCONDPGTO <> 1) ';

      wSQL = wSQL||                'AND ((CAD.BDNAOEXPSPED = ''FALSE'') or (CAD.BDNAOEXPSPED is null))';
      wSQL = wSQL||                'AND dem.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND dem.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||       ' ) dem ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN( ';
      wSQL = wSQL||                       'SELECT aux.BDCODEMP, aux.BDCHAVEDEMDOC, min(aux.BDORD) as BDORD, min(aux.BDCHAVE) as BDCHAVE, AUX.BDCODEMPSUC ';
      wSQL = wSQL||                       'FROM ( ';
      wSQL = wSQL||                             'SELECT t.BDCODEMP, t.BDCHAVEDEMDOC, MIN(t.BDCHAVE) as BDCHAVE, 0 as BDORD, T.BDCODEMPSUC ';
      wSQL = wSQL||                             'FROM TOL_VEF_EMP_TMOVDEMAISDOC t ';
      wSQL = wSQL||                             'JOIN VSUC_EMPRESAS_TLAN l ON (l.BDCODEMP = t.BDCODEMPSUC and l.BDCHAVE = t.BDCHAVE) ';
      wSQL = wSQL||                             'WHERE bdFORMULA LIKE ''DEMDOC%OP%OPE%'' '; -- Alt.: 80135 - Apenas contas de valor contábil... | Alt.: #92219 -  Atualização da variável
      wSQL = wSQL||                             'GROUP BY t.BDCODEMP, t.BDCHAVEDEMDOC, T.BDCODEMPSUC ';
      wSQL = wSQL||                             'UNION ALL ';
      wSQL = wSQL||                             'SELECT t.BDCODEMP, t.BDCHAVEDEMDOC, MIN(t.BDCHAVE) as BDCHAVE, 1 as BDORD, T.BDCODEMPSUC ';
      wSQL = wSQL||                             'FROM TOL_VEF_EMP_TMOVDEMAISDOC t ';
      wSQL = wSQL||                             'JOIN VSUC_EMPRESAS_TLAN l ON (l.BDCODEMP = t.BDCODEMPSUC and l.BDCHAVE = t.BDCHAVE and l.BDVALOR = (SELECT COALESCE(MAX(d.bdVL_OPER), 0) '; -- Alt.: 80135 - Apenas contas de valor contábil...
      wSQL = wSQL||                                                                                                                              'FROM VEF_EMP_TMOVDEMAISDOC_F100 d ';
      wSQL = wSQL||                                                                                                                              'WHERE d.BDCODEMP = t.BDCODEMP ';
      wSQL = wSQL||                                                                                                                                'AND d.BDCHAVE = t.BDCHAVEDEMDOC)) ';
      wSQL = wSQL||                             'WHERE NOT EXISTS(SELECT sub.BDCODEMP, sub.BDCHAVEDEMDOC, SUB.BDCODEMPSUC ';
      wSQL = wSQL||                                              'FROM TOL_VEF_EMP_TMOVDEMAISDOC sub ';
      wSQL = wSQL||                                              'WHERE sub.bdFORMULA LIKE ''DEMDOC%OP%OPE%'' ';
      wSQL = wSQL||                                                'AND sub.BDCODEMP      = t.BDCODEMP ';
      wSQL = wSQL||                                                'AND sub.BDCHAVEDEMDOC = t.BDCHAVEDEMDOC AND SUB.BDCODEMPSUC = T.BDCODEMPSUC) ';
      wSQL = wSQL||                             'GROUP BY t.BDCODEMP, t.BDCHAVEDEMDOC, T.BDCODEMPSUC ';
      wSQL = wSQL||                             'UNION ALL ';
      wSQL = wSQL||                             'SELECT t.BDCODEMP, t.BDCHAVEDEMDOC, MIN(t.BDCHAVE) as BDCHAVE, 2 as BDORD, T.BDCODEMPSUC ';
      wSQL = wSQL||                             'FROM TOL_VEF_EMP_TMOVDEMAISDOC t ';
      wSQL = wSQL||                             'JOIN VSUC_EMPRESAS_TLAN l ON (l.BDCODEMP = t.BDCODEMPSUC and l.BDCHAVE = t.BDCHAVE) ';
      wSQL = wSQL||                             'WHERE NOT EXISTS(SELECT sub.BDCODEMP, sub.BDCHAVEDEMDOC, SUB.BDCODEMPSUC ';
      wSQL = wSQL||                                              'FROM TOL_VEF_EMP_TMOVDEMAISDOC sub ';
      wSQL = wSQL||                                              'WHERE sub.bdFORMULA LIKE ''DEMDOC%OP%OPE%'' ';
      wSQL = wSQL||                                                'AND sub.BDCODEMP      = t.BDCODEMP ';
      wSQL = wSQL||                                                'AND sub.BDCHAVEDEMDOC = t.BDCHAVEDEMDOC AND SUB.BDCODEMPSUC = T.BDCODEMPSUC) ';
      wSQL = wSQL||                             'GROUP BY t.BDCODEMP, t.BDCHAVEDEMDOC, T.BDCODEMPSUC ';
      wSQL = wSQL||                            ') aux ';
      wSQL = wSQL||                       'GROUP BY AUX.BDCODEMP, AUX.BDCHAVEDEMDOC, AUX.BDCODEMPSUC ';
      wSQL = wSQL||                       ') TOL on (TOL.BDCODEMP = DEM.BDCODEMP and TOL.BDCHAVEDEMDOC = DEM.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN LAN on (LAN.BDCODEMP = TOL.BDCODEMPSUC and LAN.bdchave = TOL.BDCHAVE) ';

      wSQL = wSQL||       'UNION ALL ';
      /* Redução Z */
      wSQL = wSQL||       'SELECT redz.BDCODEMP, redz.BDCODMATRIZ, redz.BDREFLAN, redz.BDCHAVE, redz.BDORDEM, redz.BDORDEMPRO, redz.BDCODTP,  ';
      wSQL = wSQL||              'redz.BDVL_ITEM, redz.BDCODNATREC, redz.BDCODCTA,';
      wSQL = wSQL||              'redz.BDCODCSTPIS, redz.BDBCPIS, redz.BDALIQPIS, redz.BDVLRPIS,';
      wSQL = wSQL||              'redz.BDCODCSTCOF, redz.BDBCCOFINS, redz.BDALIQCOFINS, redz.BDVLRCOFINS, ';
      wSQL = wSQL||              'COALESCE(CclCFOP.bdCODPLAPADRAO,CCL.bdCODPLAPADRAO) AS bdCODPLAPADRAO, ';
      wSQL = wSQL||              'COALESCE(CclCFOP.bdCODTPLA,CCL.bdCODTPLA) AS bdCODTPLA, REDZ.BDCODSCP, REDZ.BDREFSOC ';
      wSQL = wSQL||       'FROM (';
      /* F500 no lançamento da Redução Z */
      wSQL = wSQL||              'SELECT mov.bdCODEMP, COALESCE(emp.bdCODMATRIZ, mov.bdCODEMP) AS bdCODMATRIZ, mov.bdREFLAN, f500.bdCHAVE, f500.bdORDEMF500 AS BDORDEM, NULL AS bdORDEMPRO, 17 AS bdCODTP,';
      wSQL = wSQL||                     'f500.bdVLRREC AS bdVL_ITEM, f500.bdCODNATREC, NULL AS bdCODCTA,';
      wSQL = wSQL||                     'f500.bdCODCSTPIS, f500.bdBASEPIS AS bdBCPIS, f500.bdALIQPIS AS bdALIQPIS, f500.bdVLRPIS,';
      wSQL = wSQL||                     'f500.bdCODCSTCOF, f500.bdVLRCOF AS bdBCCOFINS, f500.bdALIQCOF AS bdALIQCOFINS, f500.bdVLRCOF AS bdVLRCOFINS, NULL AS bdCODNAT, mov.bdGERAC490,SCP.BDCODSCP, SCP.BDREFSOC ';
      wSQL = wSQL||              'FROM (';
      wSQL = wSQL||                     'SELECT z.BDCODEMP, z.BDCHAVE, z.BDREFLAN,';
      wSQL = wSQL||                            '(SELECT x.bdGERAC490 ';
      wSQL = wSQL||                             'FROM VEF_BASE_TEMPPARFED X ';
      wSQL = wSQL||                             'WHERE X.BDCODEMP = z.BDCODEMP ';
      wSQL = wSQL||                             'AND X.BDREFEMP = (SELECT MAX(Y.BDREFEMP) ';
      wSQL = wSQL||                                               'FROM VEF_BASE_TEMPPARFED Y ';
      wSQL = wSQL||                                               'WHERE Y.BDCODEMP = z.BDCODEMP ';
      wSQL = wSQL||                                                 'AND Y.BDREFEMP <= z.BDREFLAN)) AS bdGERAC490 ';
      wSQL = wSQL||                     'FROM VEF_EMP_TREDZ z ';
      wSQL = wSQL||                     'WHERE z.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                       'AND z.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                       'AND (NOT EXISTS(SELECT * FROM VEF_EMP_TREDZC425 c WHERE c.bdCODEMP = z.BDCODEMP AND c.bdCHAVE = z.bdCHAVE)) ';
      wSQL = wSQL||                       'AND (NOT EXISTS(SELECT * FROM VEF_EMP_TREDZC425ALIQ c WHERE c.bdCODEMP = z.bdCODEMP AND c.bdCHAVE = z.bdCHAVE)) ';
      wSQL = wSQL||                       'AND (NOT EXISTS(SELECT * FROM VEF_EMP_TREDZC425ALIQISS i WHERE i.bdCODEMP = z.bdCODEMP AND i.bdCHAVE = z.bdCHAVE)) ';
      wSQL = wSQL||                       'AND (NOT EXISTS(SELECT * FROM VEF_EMP_TITEMDOCECF i WHERE i.bdCODEMP = z.bdCODEMP AND i.bdCHAVE = z.bdCHAVE)) ';
      wSQL = wSQL||                    ') mov ';
      wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TF500REDZ f500 ON (f500.BDCODEMP = mov.BDCODEMP AND f500.BDCHAVE = mov.BDCHAVE) ';
      /*Camilla M. Só vai levar a redução z se todas as CFOPs do lançamento for da mesma SCP, se não vai levar os valores para a sócia ostensiva */
      wSQL = wSQL||              'LEFT OUTER JOIN( ';
      wSQL = wSQL||              '      SELECT COUNT(*) QUANT, VAR.BDCODEMP, VAR.BDCHAVE,VAR.BDCODSCP, VAR.BDREFSOC ';
      wSQL = wSQL||              '      FROM VEF_EMP_TREDZVARCFOP VAR ';
      wSQL = wSQL||              '      WHERE VAR.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||              '      GROUP BY VAR.BDCODEMP, VAR.BDCHAVE,VAR.BDCODSCP, VAR.BDREFSOC ';
      wSQL = wSQL||              '      HAVING COUNT(*) = (SELECT COUNT(*) FROM VEF_EMP_TREDZVARCFOP VARC WHERE VARC.BDCODEMP = VAR.BDCODEMP AND VARC.BDCHAVE = VAR.BDCHAVE) ';
      wSQL = wSQL||              ') SCP ON (SCP.BDCODEMP = MOV.BDCODEMP AND SCP.BDCHAVE = MOV.BDCHAVE) ';
      
      wSQL = wSQL||              'UNION ALL ';      
      
      wSQL = wSQL||              'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, c425.BDCHAVE, c425.BDORDEMTOT AS BDORDEM, c425.BDORDEMC425 AS BDORDEMPRO, 6 AS BDCODTP, ';
      wSQL = wSQL||                     'c425.BDVLRACU AS BDVL_ITEM, c425.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||                     'c425.BDCODCSTPIS, c425.BDVL_BC_PIS AS BDBCPIS, c425.BDALIQ_PIS AS BDALIQPIS, c425.BDVLRPIS,';
      wSQL = wSQL||                     'c425.BDCODCSTCOF, c425.BDVL_BC_COFINS AS BDBCCOFINS, c425.BDALIQ_COFINS AS BDALIQCOFINS, c425.BDVLRCOFINS, c425.bdCODNAT, mov.bdGERAC490,SCP.BDCODSCP, SCP.BDREFSOC ';
      wSQL = wSQL||              'FROM (';
      wSQL = wSQL||                     'SELECT z.BDCODEMP, z.BDCHAVE, z.BDREFLAN, ';
      wSQL = wSQL||                            '(SELECT x.bdGERAC490 ';
      wSQL = wSQL||                             'FROM VEF_BASE_TEMPPARFED X ';
      wSQL = wSQL||                             'WHERE X.BDCODEMP = z.BDCODEMP ';
      wSQL = wSQL||                             'AND X.BDREFEMP = (SELECT MAX(Y.BDREFEMP) ';
      wSQL = wSQL||                                                'FROM VEF_BASE_TEMPPARFED Y ';
      wSQL = wSQL||                                                'WHERE Y.BDCODEMP = z.BDCODEMP ';
      wSQL = wSQL||                                                  'AND Y.BDREFEMP <= z.BDREFLAN)) AS bdGERAC490 ';
      wSQL = wSQL||                     'FROM VEF_EMP_TREDZ z ';
      wSQL = wSQL||                     'WHERE z.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                       'AND z.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                    ') mov ';
      wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TREDZC425 c425 ON (c425.BDCODEMP = mov.BDCODEMP AND c425.BDCHAVE = mov.BDCHAVE) ';
      /*Camilla M. Só vai levar a redução z se todas as CFOPs do lançamento for da mesma SCP, se não vai levar os valores para a sócia ostensiva */
      wSQL = wSQL||              'LEFT OUTER JOIN( ';
      wSQL = wSQL||              '      SELECT COUNT(*) QUANT, VAR.BDCODEMP, VAR.BDCHAVE,VAR.BDCODSCP, VAR.BDREFSOC ';
      wSQL = wSQL||              '      FROM VEF_EMP_TREDZVARCFOP VAR ';
      wSQL = wSQL||              '      WHERE VAR.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||              '      GROUP BY VAR.BDCODEMP, VAR.BDCHAVE,VAR.BDCODSCP, VAR.BDREFSOC ';
      wSQL = wSQL||              '      HAVING COUNT(*) = (SELECT COUNT(*) FROM VEF_EMP_TREDZVARCFOP VARC WHERE VARC.BDCODEMP = VAR.BDCODEMP AND VARC.BDCHAVE = VAR.BDCHAVE) ';
      wSQL = wSQL||              ') SCP ON (SCP.BDCODEMP = MOV.BDCODEMP AND SCP.BDCHAVE = MOV.BDCHAVE) ';

      wSQL = wSQL||              'UNION ALL ';

      wSQL = wSQL||              'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, aliq.BDCHAVE, aliq.BDORDEMICMS AS BDORDEM, aliq.BDORDEMC425 AS BDORDEMPRO, 7 AS BDCODTP, ';
      wSQL = wSQL||                     'aliq.BDVLRACU AS BDVL_ITEM, aliq.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||                     'aliq.BDCODCSTPIS, aliq.BDVL_BC_PIS AS BDBCPIS, aliq.BDALIQ_PIS AS BDALIQPIS, aliq.BDVLRPIS,';
      wSQL = wSQL||                     'aliq.BDCODCSTCOF, aliq.BDVL_BC_COFINS AS BDBCCOFINS, aliq.BDALIQ_COFINS AS BDALIQCOFINS, aliq.BDVLRCOFINS, aliq.bdCODNAT, mov.bdGERAC490,SCP.BDCODSCP, SCP.BDREFSOC ';
      wSQL = wSQL||              'FROM (';
      wSQL = wSQL||                     'SELECT z.BDCODEMP, z.BDCHAVE, z.BDREFLAN, ';
      wSQL = wSQL||                            '(SELECT x.bdGERAC490 ';
      wSQL = wSQL||                             'FROM VEF_BASE_TEMPPARFED X ';
      wSQL = wSQL||                             'WHERE X.BDCODEMP = z.BDCODEMP ';
      wSQL = wSQL||                             'AND X.BDREFEMP = (SELECT MAX(Y.BDREFEMP) ';
      wSQL = wSQL||                                               'FROM VEF_BASE_TEMPPARFED Y ';
      wSQL = wSQL||                                               'WHERE Y.BDCODEMP = z.BDCODEMP ';
      wSQL = wSQL||                                                 'AND Y.BDREFEMP <= z.BDREFLAN)) AS bdGERAC490 ';
      wSQL = wSQL||                     'FROM VEF_EMP_TREDZ z ';
      wSQL = wSQL||                     'WHERE z.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                       'AND z.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                    ') mov ';
      wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TREDZC425ALIQ aliq ON (aliq.BDCODEMP = mov.BDCODEMP AND aliq.BDCHAVE = mov.BDCHAVE) ';
      /*Camilla M. Só vai levar a redução z se todas as CFOPs do lançamento for da mesma SCP, se não vai levar os valores para a sócia ostensiva */
      wSQL = wSQL||              'LEFT OUTER JOIN( ';
      wSQL = wSQL||              '      SELECT COUNT(*) QUANT, VAR.BDCODEMP, VAR.BDCHAVE,VAR.BDCODSCP, VAR.BDREFSOC ';
      wSQL = wSQL||              '      FROM VEF_EMP_TREDZVARCFOP VAR ';
      wSQL = wSQL||              '      WHERE VAR.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||              '      GROUP BY VAR.BDCODEMP, VAR.BDCHAVE,VAR.BDCODSCP, VAR.BDREFSOC ';
      wSQL = wSQL||              '      HAVING COUNT(*) = (SELECT COUNT(*) FROM VEF_EMP_TREDZVARCFOP VARC WHERE VARC.BDCODEMP = VAR.BDCODEMP AND VARC.BDCHAVE = VAR.BDCHAVE) ';
      wSQL = wSQL||              ') SCP ON (SCP.BDCODEMP = MOV.BDCODEMP AND SCP.BDCHAVE = MOV.BDCHAVE) ';

      wSQL = wSQL||              'UNION ALL '; /*C425 - VARIAS ALÍQUOTAS - ISS*/

      wSQL = wSQL||              'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, aliq.BDCHAVE, aliq.BDORDEMISS AS BDORDEM, aliq.BDORDEMC425 AS BDORDEMPRO, 7 AS BDCODTP, ';
      wSQL = wSQL||                     'aliq.BDVLRACU AS BDVL_ITEM, aliq.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||                     'aliq.BDCODCSTPIS, aliq.BDVL_BC_PIS AS BDBCPIS, aliq.BDALIQ_PIS AS BDALIQPIS, aliq.BDVLRPIS,';
      wSQL = wSQL||                     'aliq.BDCODCSTCOF, aliq.BDVL_BC_COFINS AS BDBCCOFINS, aliq.BDALIQ_COFINS AS BDALIQCOFINS, aliq.BDVLRCOFINS, aliq.bdCODNAT, mov.bdGERAC490,SCP.BDCODSCP, SCP.BDREFSOC ';
      wSQL = wSQL||              'FROM (';
      wSQL = wSQL||                     'SELECT z.BDCODEMP, z.BDCHAVE, z.BDREFLAN, ';
      wSQL = wSQL||                            '(SELECT x.bdGERAC490 ';
      wSQL = wSQL||                             'FROM VEF_BASE_TEMPPARFED X ';
      wSQL = wSQL||                             'WHERE X.BDCODEMP = z.BDCODEMP ';
      wSQL = wSQL||                             'AND X.BDREFEMP = (SELECT MAX(Y.BDREFEMP) ';
      wSQL = wSQL||                                               'FROM VEF_BASE_TEMPPARFED Y ';
      wSQL = wSQL||                                               'WHERE Y.BDCODEMP = z.BDCODEMP ';
      wSQL = wSQL||                                                 'AND Y.BDREFEMP <= z.BDREFLAN)) AS bdGERAC490 ';
      wSQL = wSQL||                     'FROM VEF_EMP_TREDZ z ';
      wSQL = wSQL||                     'WHERE z.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                       'AND z.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                    ') mov ';
      wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TREDZC425ALIQISS aliq ON (aliq.BDCODEMP = mov.BDCODEMP AND aliq.BDCHAVE = mov.BDCHAVE) ';
      /*Camilla M. Só vai levar a redução z se todas as CFOPs do lançamento for da mesma SCP, se não vai levar os valores para a sócia ostensiva */
      wSQL = wSQL||              'LEFT OUTER JOIN( ';
      wSQL = wSQL||              '      SELECT COUNT(*) QUANT, VAR.BDCODEMP, VAR.BDCHAVE,VAR.BDCODSCP, VAR.BDREFSOC ';
      wSQL = wSQL||              '      FROM VEF_EMP_TREDZVARCFOP VAR ';
      wSQL = wSQL||              '      WHERE VAR.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||              '      GROUP BY VAR.BDCODEMP, VAR.BDCHAVE,VAR.BDCODSCP, VAR.BDREFSOC ';
      wSQL = wSQL||              '      HAVING COUNT(*) = (SELECT COUNT(*) FROM VEF_EMP_TREDZVARCFOP VARC WHERE VARC.BDCODEMP = VAR.BDCODEMP AND VARC.BDCHAVE = VAR.BDCHAVE) ';
      wSQL = wSQL||              ') SCP ON (SCP.BDCODEMP = MOV.BDCODEMP AND SCP.BDCHAVE = MOV.BDCHAVE) ';

      wSQL = wSQL||              'UNION ALL ';

      wSQL = wSQL||              'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, i.BDCHAVE, i.BDORDEMDOCECF AS BDORDEM, i.BDORDEMITEM AS BDORDEMPRO, 8 AS BDCODTP, ';
      wSQL = wSQL||                     'i.BDVLRTOTPRO AS BDVL_ITEM, i.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||                     'i.BDCODCSTPIS, i.BDVL_BC_PIS AS BDBCPIS, i.BDALIQ_PIS AS BDALIQPIS, i.BDVLRPIS AS BDVLRPIS,';
      wSQL = wSQL||                     'i.BDCODCSTCOF, i.BDVL_BC_COFINS AS BDBCCOFINS, i.BDALIQ_COFINS AS BDALIQCOFINS, i.BDVLRCOFINS, NULL AS bdCODNAT, mov.bdGERAC490,SCP.BDCODSCP, SCP.BDREFSOC ';
      wSQL = wSQL||              'FROM (';
      wSQL = wSQL||                     'SELECT z.BDCODEMP, z.BDCHAVE, z.BDREFLAN, ';
      wSQL = wSQL||                            '(SELECT x.bdGERAC490 ';
      wSQL = wSQL||                             'FROM VEF_BASE_TEMPPARFED X ';
      wSQL = wSQL||                             'WHERE X.BDCODEMP = z.BDCODEMP ';
      wSQL = wSQL||                             'AND X.BDREFEMP = (SELECT MAX(Y.BDREFEMP) ';
      wSQL = wSQL||                                               'FROM VEF_BASE_TEMPPARFED Y ';
      wSQL = wSQL||                                               'WHERE Y.BDCODEMP = z.BDCODEMP ';
      wSQL = wSQL||                                                 'AND Y.BDREFEMP <= z.BDREFLAN)) AS bdGERAC490 ';
      wSQL = wSQL||                     'FROM VEF_EMP_TREDZ z ';
      wSQL = wSQL||                     'WHERE z.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                       'AND z.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                    ') mov ';
      wSQL = wSQL||              'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TDOCECF doc ON (doc.BDCODEMP = mov.BDCODEMP AND doc.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||              'LEFT OUTER JOIN VEF_EMP_TITEMDOCECF i ON (i.BDCODEMP = doc.BDCODEMP AND i.BDCHAVE = doc.BDCHAVE AND i.BDORDEMDOCECF = doc.BDORDEMDOCECF) ';
      /*Camilla M. Só vai levar a redução z se todas as CFOPs do lançamento for da mesma SCP, se não vai levar os valores para a sócia ostensiva */
      wSQL = wSQL||              'LEFT OUTER JOIN( ';
      wSQL = wSQL||              '      SELECT COUNT(*) QUANT, VAR.BDCODEMP, VAR.BDCHAVE,VAR.BDCODSCP, VAR.BDREFSOC ';
      wSQL = wSQL||              '      FROM VEF_EMP_TREDZVARCFOP VAR ';
      wSQL = wSQL||              '      WHERE VAR.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||              '      GROUP BY VAR.BDCODEMP, VAR.BDCHAVE,VAR.BDCODSCP, VAR.BDREFSOC ';
      wSQL = wSQL||              '      HAVING COUNT(*) = (SELECT COUNT(*) FROM VEF_EMP_TREDZVARCFOP VARC WHERE VARC.BDCODEMP = VAR.BDCODEMP AND VARC.BDCHAVE = VAR.BDCHAVE) ';
      wSQL = wSQL||              ') SCP ON (SCP.BDCODEMP = MOV.BDCODEMP AND SCP.BDCHAVE = MOV.BDCHAVE) ';
      wSQL = wSQL||              'WHERE doc.bdCODSITNF NOT IN (2,3,4,5) '; -- Alt.: #100520 #100827 - Não considerar documentos cancelados...
      wSQL = wSQL||            ') redz ';
      /* Alt.: #79665 - Nas contas das várias CFOPs, quando tiver o parametro do C425 marcado, vai buscar as contas da própria CFOP, caso contrario continua como antes */
      --wSQL = wSQL||       'LEFT OUTER JOIN SP_CONSULTAEMPRESAS_SIS(redz.BDREFLAN, redz.bdCODEMP, 0) sis ON (sis.bdCODEMP = redz.bdCODEMP) '; Alt.: #100941 - Alterado para fazer direto no sql da tabela da reducao z...
      wSQL = wSQL||       'LEFT OUTER JOIN (SELECT v.bdCODEMP, v.bdCHAVECFOP, v.bdFORMULA, MIN(v.bdCHAVE) AS bdCHAVE, 0 AS bdORD, V.BDCODEMPSUC ';
      wSQL = wSQL||                        'FROM TOL_VEF_EMP_TREDZVARCFOP v ';
      wSQL = wSQL||                        'JOIN VSUC_EMPRESAS_TLAN l ON (l.bdCODEMP = v.BDCODEMPSUC AND l.bdCHAVE = v.bdCHAVE) ';
      wSQL = wSQL||                        'WHERE v.bdFORMULA LIKE ''NAT%LAN(%)'' ';
      wSQL = wSQL||                        'GROUP BY v.bdCODEMP, v.bdCHAVECFOP, v.bdFORMULA, V.BDCODEMPSUC) TolCFOP on (TolCFOP.BDCODEMP = REDZ.BDCODEMP and TolCFOP.BDCHAVECFOP = REDZ.BDCHAVE AND ';
      --wSQL = wSQL||                                                                                     '(POSITION(redz.bdCODNAT IN TolCFOP.bdFORMULA) > 0) AND sis.bdGERAC490 = ''TRUE'') ';
      wSQL = wSQL||                                                                                     '(POSITION(redz.bdCODNAT IN TolCFOP.bdFORMULA) > 0) AND redz.bdGERAC490 = ''TRUE'') ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN LanCFOP ON (LanCFOP.bdCODEMP = TolCFOP.BDCODEMPSUC AND LanCFOP.bdCHAVE = TolCFOP.bdCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA CclCFOP ON (CclCFOP.bdCODPLAPADRAO = LanCFOP.bdCODPLAPADRAO AND CclCFOP.bdCODTPLA = LanCFOP.bdCREDITO) ';
      /* Alt.: #79665 - Fim */
      wSQL = wSQL||       'LEFT OUTER JOIN (';
      wSQL = wSQL||                          'SELECT aux.BDCODEMP, aux.BDCHAVECFOP, min(aux.BDCHAVE) as BDCHAVE, min(aux.BDORD) as BDORD, AUX.BDCODEMPSUC ';
      wSQL = wSQL||                          'FROM ( ';
      wSQL = wSQL||                                 'SELECT v.bdCODEMP, v.bdCHAVECFOP, MIN(v.bdCHAVE) AS bdCHAVE, 0 as BDORD, V.BDCODEMPSUC ';
      wSQL = wSQL||                         'FROM TOL_VEF_EMP_TREDZVARCFOP v ';
      wSQL = wSQL||                                 'JOIN VSUC_EMPRESAS_TLAN l ON (l.bdCODEMP = v.BDCODEMPSUC AND l.bdCHAVE = v.bdCHAVE) ';
      wSQL = wSQL||                                 'WHERE bdFORMULA LIKE ''NAT%LAN(%)'' '; -- Alt.: 80135 - Apenas contas de valor contábil...
      wSQL = wSQL||                                 'GROUP BY v.bdCODEMP, v.bdCHAVECFOP, V.BDCODEMPSUC ';
      wSQL = wSQL||                                 'UNION ALL ';
      /* Alt.: #100941 - Removido esse critério para buscar as contas da contabilização pelo valor contábil...
      wSQL = wSQL||                                 'SELECT v.bdCODEMP, v.bdCHAVECFOP, MIN(v.bdCHAVE) AS bdCHAVE, 1 as BDORD  ';
      wSQL = wSQL||                                 'FROM TOL_VEF_EMP_TREDZVARCFOP v ';
      wSQL = wSQL||                                 'JOIN VSUC_EMPRESAS_TLAN l ON (l.bdCODEMP = v.bdCODEMP AND l.bdCHAVE = v.bdCHAVE AND l.bdVALOR = (SELECT COALESCE(MAX(c.bdVLRCONTAB), 0) ';
      wSQL = wSQL||                                                                                                                                  'FROM VEF_EMP_TREDZVARCFOP c ';
      wSQL = wSQL||                                                                                                                                  'WHERE c.bdCODEMP = v.bdCODEMP ';
      wSQL = wSQL||                                                                                                                                    'AND c.bdCHAVE = v.bdCHAVECFOP)) ';
      wSQL = wSQL||                                 'WHERE v.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                                 'GROUP BY v.bdCODEMP, v.bdCHAVECFOP ';
      wSQL = wSQL||                                 'UNION ALL '; */
      wSQL = wSQL||                                 'SELECT v.bdCODEMP, v.bdCHAVECFOP, MIN(v.bdCHAVE) AS bdCHAVE, 2 as BDORD, V.BDCODEMPSUC  ';
      wSQL = wSQL||                                 'FROM TOL_VEF_EMP_TREDZVARCFOP v ';
      wSQL = wSQL||                                 'JOIN VSUC_EMPRESAS_TLAN l ON (l.bdCODEMP = v.BDCODEMPSUC AND l.bdCHAVE = v.bdCHAVE) ';
      wSQL = wSQL||                                 'WHERE v.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                                 'GROUP BY v.bdCODEMP, v.bdCHAVECFOP, V.BDCODEMPSUC ';
      wSQL = wSQL||                                 ') aux ';
      wSQL = wSQL||                          'GROUP BY aux.bdCODEMP, aux.bdCHAVECFOP, AUX.BDCODEMPSUC ';
      wSQL = wSQL||                         ') tol on (tol.BDCODEMP = redz.BDCODEMP and tol.BDCHAVECFOP = redz.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tol.BDCODEMPSUC and lan.BDCHAVE = tol.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN PLANOS_TPLA ccl on (ccl.BDCODPLAPADRAO = lan.BDCODPLAPADRAO and ccl.BDCODTPLA = lan.BDCREDITO) ';

      wSQL = wSQL||       'UNION ALL ';
      /* I100 */
      wSQL = wSQL||       'SELECT i100.BDCODEMP, COALESCE(emp.BDCODMATRIZ, i100.BDCODEMP) as BDCODMATRIZ, i100.BDREFERENCIA AS BDREFLAN, i100.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 9 AS BDCODTP, ';
      --wSQL = wSQL||              '(i100.BDVLRREC-i100.BDVLRTOTDEDGER-i100.BDVLRTOTDEDESP) AS BDVL_ITEM, i100.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||              'i100.BDVLRREC AS BDVL_ITEM, i100.BDCODNATREC, NULL AS BDCODCTA,';
      wSQL = wSQL||              'i100.BDCODCSTPISCOF AS BDCODCSTPIS, i100.BDBASEPIS AS BDBCPIS, i100.BDALIQPIS, i100.BDVLRPIS,';
      wSQL = wSQL||              'i100.BDCODCSTPISCOF AS BDCODCSTCOF, i100.BDBASECOFINS AS BDBCCOFINS, i100.BDALIQCOFINS, i100.BDVLRCOFINS, ';
      wSQL = wSQL||              'i200.BDCODPLAPADRAO, i200.BDCODTPLA,I100.BDCODSCP, I100.BDREFSOC ';
      wSQL = wSQL||       'FROM VEF_EMP_TMOVFINI100 i100 ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = i100.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN ( SELECT i.BDCODEMP, i.BDCHAVE, i.BDORDEMI200 as BDORDEMI200, i.BDCODPLAPADRAO, i.BDCODTPLA ';
      wSQL = wSQL||                         'FROM VEF_EMP_TMOVFIN_I200 i ';
      wSQL = wSQL||                         'WHERE i.BDORDEMI200 = (SELECT FIRST 1 x.BDORDEMI200 ';
      wSQL = wSQL||                                                'FROM VEF_EMP_TMOVFIN_I200 x ';
      wSQL = wSQL||                                                'WHERE x.BDCODEMP = i.BDCODEMP ';
      wSQL = wSQL||                                                  'AND x.BDCHAVE = i.BDCHAVE ';
      wSQL = wSQL||                                                  'AND x.BDCODPLAPADRAO IS NOT NULL ';
      wSQL = wSQL||                                                  'AND x.BDCODTPLA IS NOT NULL) ) i200 on (i200.BDCODEMP = i100.BDCODEMP and i200.BDCHAVE = i100.BDCHAVE) ';
      wSQL = wSQL||       'WHERE i100.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||         'AND i100.BDREFERENCIA = '||:prREFERENCIA||' ';

      EXECUTE STATEMENT ( wSQLPREFIXO || wSQL || wSQLSUFIXO );
    END
END
^

create or alter procedure SP_APURACAO_BLOCOM_M400_M800 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PRCODEMPSO integer = 0)
as
declare variable WINCTRIB integer;
declare variable WEXPNFCOMVALSAI varchar(5);
BEGIN
  -- Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDEXPNFCOMVALSAI FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMP
  INTO :wINCTRIB, :wEXPNFCOMVALSAI;

  if ((:WINCTRIB is null) and (:PRCODEMPSO > 0)) then
    begin
      SELECT BDINCTRIB+1, BDEXPNFCOMVALSAI FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMPSO
      INTO :wINCTRIB, :wEXPNFCOMVALSAI;
    end

  IF ((wINCTRIB IS NOT NULL) AND (wEXPNFCOMVALSAI <> 'TRUE')) THEN
    BEGIN
      /* Insert na tabela temporária TMP_VEF_EMP_TBLOCOM_M400_M800 */
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M400_M800AUX (:prCODEMP, :prREFERENCIA, :prWHEREEMPRESAS, :PRAJUSTESCP, :PRCODEMPSO);

      /* REGISTRO M400: RECEITAS ISENTAS, NÃO ALCANÇADAS PELA INCIDÊNCIA DA CONTRIBUIÇÃO, SUJEITAS A ALÍQUOTA ZERO OU DE VENDAS COM SUSPENSÃO - PIS/PASEP */
      INSERT INTO VEF_EMP_TBLOCOM400_M800 (BDCODQUADRO, BDCODPERIODO, BDCODEMP,  BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSTCOF, BDCODPLAPADRAO, BDCODTPLA, BDCODCTA, BDCODCSTPIS, BDVL_TOT_REC, BDDESC_COMPL, BDRETIFICADORA)
      SELECT 26 AS BDCODQUADRO, 7 AS BDCODPERIODO, IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODEMP) BDCODEMP, IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODMATRIZ) BDCODMATRIZ, tmp.BDREFERENCIA,
             GETORDEMSEQUENCIAL_STR('M400.'||7||'.'||tmp.BDCODEMP||'.'||tmp.BDCODMATRIZ||'.'||26||'.'||tmp.BDREFERENCIA||'.'||TMP.BDCODEMPSCP, :prCODEMP) AS BDCHAVE,
/*             (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM400_M800 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 26) AS BDCHAVE, */
             tmp.BDCODCSTCOF, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTPIS, SUM(COALESCE(tmp.BDVL_ITEM,0)) AS BDVL_TOT_REC, NULL AS BDDESC_COMPL,
             :PRRETIFICADORA BDRETIFICADORA
      FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
      WHERE (tmp.BDCODCSTPIS > 0)
        AND (tmp.BDCODNATREC IS NOT NULL)
        AND tmp.BDCODMATRIZ = iif(:PRAJUSTESCP = 'TRUE' and :PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
        AND tmp.BDREFERENCIA = :prREFERENCIA and tmp.BDVL_ITEM > 0
      GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTCOF, tmp.BDCODCSTPIS,tmp.BDCODEMPSCP;

      /* REGISTRO M410: DETALHAMENTO DAS RECEITAS ISENTAS, NÃO ALCANÇADAS PELA INCIDÊNCIA DA CONTRIBUIÇÃO, SUJEITAS A ALÍQUOTA ZERO OU DE VENDAS COM SUSPENSÃO - PIS/PASEP */
      INSERT INTO VEF_EMP_TBLOCOM410_M810 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODPLAPADRAO, BDCODTPLA, BDCODCTA, BDCODNATREC, BDVL_REC, BDDESC_COMPL, BDRETIFICADORA)
      SELECT 7 AS BDCODPERIODO, IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODEMP) BDCODEMP, IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODMATRIZ) BDCODMATRIZ, 26 AS BDCODQUADRO, tmp.BDREFERENCIA,
             (SELECT x.BDCHAVE
              FROM VEF_EMP_TBLOCOM400_M800 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODEMP = IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODEMP)
                AND x.BDCODMATRIZ = IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODMATRIZ)
                AND x.BDREFERENCIA = tmp.BDREFERENCIA
                AND IIF(TMP.BDCODCSTCOF IN ('04','06','07','08','09'), X.BDCODCSTCOF = TMP.BDCODCSTCOF, x.BDCODCSTCOF IS NULL)
                AND IIF(tmp.BDCODCSTPIS in ('04','06','07','08','09'), x.BDCODCSTPIS = tmp.BDCODCSTPIS, x.BDCODCSTPIS is null)
                AND X.BDRETIFICADORA = :PRRETIFICADORA
                AND x.BDCODQUADRO = 26
                AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL)))
                ) AS BDCHAVE,
             GETORDEMSEQUENCIAL_STR('M410.'||7||'.'||tmp.BDCODEMP||'.'||tmp.BDCODMATRIZ||'.'||26||'.'||tmp.BDREFERENCIA||'.'||tmp.BDCODEMPSCP||'.'||
             (SELECT z.BDCHAVE FROM VEF_EMP_TBLOCOM400_M800 z WHERE z.BDCODPERIODO = 7 AND z.BDCODEMP = IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODEMP) AND z.BDCODMATRIZ = IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODMATRIZ)
              AND z.BDREFERENCIA = tmp.BDREFERENCIA AND Z.BDRETIFICADORA = :PRRETIFICADORA AND z.BDCODCSTCOF = tmp.BDCODCSTCOF AND z.BDCODCSTPIS = tmp.BDCODCSTPIS
              AND z.BDCODQUADRO = 26 AND ((z.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((z.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL))) AND ((z.BDCODTPLA = tmp.BDCODTPLA) OR ((z.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL))))
             , :prCODEMP) AS BDORDEM,
            /* (SELECT COALESCE(MAX(x.BDORDEM)+1,1) FROM VEF_EMP_TBLOCOM410_M810 x
              WHERE x.BDCODEMP = tmp.BDCODEMP
                AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                AND x.BDREFERENCIA = tmp.BDREFERENCIA
                AND x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 26
                AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL)))
                AND x.BDCHAVE = (SELECT z.BDCHAVE
                                 FROM VEF_EMP_TBLOCOM400_M800 z
                                 WHERE z.BDCODEMP = tmp.BDCODEMP
                                   AND z.BDCODMATRIZ = tmp.BDCODMATRIZ
                                   AND z.BDREFERENCIA = tmp.BDREFERENCIA
                                   AND z.BDCODCSTCOF = tmp.BDCODCSTCOF
                                   AND z.BDCODCSTPIS = tmp.BDCODCSTPIS
                                   AND z.BDCODQUADRO = 26
                                   AND ((z.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((z.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                                   AND ((z.BDCODTPLA = tmp.BDCODTPLA) OR ((z.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL))))
                                   ) AS BDORDEM, */
             tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODNATREC, SUM(tmp.BDVL_ITEM) AS BDVL_REC, NULL AS BDDESC_COMPL,
             :PRRETIFICADORA BDRETIFICADORA
      FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
      WHERE (tmp.BDCODCSTPIS > 0)
        AND (tmp.BDCODNATREC IS NOT NULL)
        AND tmp.BDCODMATRIZ = iif(:PRAJUSTESCP = 'TRUE' and :PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
        AND tmp.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM400_M800 x
                    WHERE x.BDCODPERIODO = 7
                      AND x.BDCODEMP = IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODEMP)
                      AND x.BDCODMATRIZ = IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODMATRIZ)
                      AND x.BDREFERENCIA = tmp.BDREFERENCIA
                      AND IIF(TMP.BDCODCSTCOF IN ('04','06','07','08','09'), X.BDCODCSTCOF = TMP.BDCODCSTCOF, x.BDCODCSTCOF IS NULL)
                      AND IIF(tmp.BDCODCSTPIS in ('04','06','07','08','09'), x.BDCODCSTPIS = tmp.BDCODCSTPIS, x.BDCODCSTPIS is null)
                      AND X.BDRETIFICADORA = :PRRETIFICADORA
                      AND x.BDCODQUADRO = 26
                      AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                      AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL))) ))
      GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODNATREC, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTCOF, tmp.BDCODCSTPIS,tmp.BDCODEMPSCP;

      /* REGISTRO M800: RECEITAS ISENTAS, NÃO ALCANÇADAS PELA INCIDÊNCIA DA CONTRIBUIÇÃO, SUJEITAS A ALÍQUOTA ZERO OU DE VENDAS COM SUSPENSÃO - COFINS */
      INSERT INTO VEF_EMP_TBLOCOM400_M800 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSTPIS, BDCODPLAPADRAO, BDCODTPLA, BDCODCTA, BDCODCSTCOF, BDVL_TOT_REC, BDDESC_COMPL, BDRETIFICADORA)
      SELECT 43 AS BDCODQUADRO, 7 AS BDCODPERIODO, IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODEMP) BDCODEMP, IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODMATRIZ) BDCODMATRIZ, tmp.BDREFERENCIA,
             GETORDEMSEQUENCIAL_STR('M800.'||7||'.'||tmp.BDCODEMP||'.'||tmp.BDCODMATRIZ||'.'||43||'.'||tmp.BDREFERENCIA||'.'||tmp.BDCODEMPSCP, :prCODEMP) AS BDCHAVE,
/*             (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM400_M800 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = 43) AS BDCHAVE,*/
             tmp.BDCODCSTPIS, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTCOF, SUM(COALESCE(tmp.BDVL_ITEM,0)) AS BDVL_TOT_REC, NULL AS BDDESC_COMPL,
             :PRRETIFICADORA BDRETIFICADORA
      FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
      WHERE (tmp.BDCODCSTCOF > 0)
        AND (tmp.BDCODNATREC IS NOT NULL)
        AND tmp.BDCODMATRIZ = iif(:PRAJUSTESCP = 'TRUE' and :PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
        AND tmp.BDREFERENCIA = :prREFERENCIA and tmp.BDVL_ITEM > 0
      GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTPIS, tmp.BDCODCSTCOF,tmp.BDCODEMPSCP;

      /* REGISTRO M810: DETALHAMENTO DAS RECEITAS ISENTAS, NÃO ALCANÇADAS PELA INCIDÊNCIA DA CONTRIBUIÇÃO, SUJEITAS A ALÍQUOTA ZERO OU DE VENDAS COM SUSPENSÃO - COFINS */
      INSERT INTO VEF_EMP_TBLOCOM410_M810 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODPLAPADRAO, BDCODTPLA, BDCODCTA, BDCODNATREC, BDVL_REC, BDDESC_COMPL, BDRETIFICADORA)
      SELECT 7 AS BDCODPERIODO, IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODEMP) BDCODEMP, IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODMATRIZ) BDCODMATRIZ, 43 AS BDCODQUADRO, tmp.BDREFERENCIA,
             (SELECT x.BDCHAVE
              FROM VEF_EMP_TBLOCOM400_M800 x
              WHERE x.BDCODPERIODO = 7
                AND x.BDCODEMP = IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODEMP)
                AND x.BDCODMATRIZ = IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODMATRIZ)
                AND x.BDREFERENCIA = tmp.BDREFERENCIA
                AND IIF(TMP.BDCODCSTCOF IN ('04','06','07','08','09'), X.BDCODCSTCOF = TMP.BDCODCSTCOF, x.BDCODCSTCOF IS NULL)
                AND IIF(tmp.BDCODCSTPIS in ('04','06','07','08','09'), x.BDCODCSTPIS = tmp.BDCODCSTPIS, x.BDCODCSTPIS is null)
                AND X.BDRETIFICADORA = :PRRETIFICADORA
                AND x.BDCODQUADRO = 43
                AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL)))
                ) AS BDCHAVE,

                GETORDEMSEQUENCIAL_STR('M800.'||7||'.'||tmp.BDCODEMP||'.'||tmp.BDCODMATRIZ||'.'||43||'.'||tmp.BDREFERENCIA||'.'||tmp.BDCODEMPSCP||'.'||
                (SELECT z.BDCHAVE FROM VEF_EMP_TBLOCOM400_M800 z WHERE z.BDCODPERIODO = 7 AND z.BDCODEMP = IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODEMP) AND z.BDCODMATRIZ = IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODMATRIZ)
                AND z.BDREFERENCIA = tmp.BDREFERENCIA AND Z.BDRETIFICADORA = :PRRETIFICADORA AND z.BDCODCSTPIS = tmp.BDCODCSTPIS AND z.BDCODCSTCOF = tmp.BDCODCSTCOF  AND z.BDCODQUADRO = 43
                AND ((z.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((z.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL))) AND ((z.BDCODTPLA = tmp.BDCODTPLA) OR ((z.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL))))
                , :prCODEMP) AS BDORDEM,
           /*  (SELECT COALESCE(MAX(x.BDORDEM)+1,1) FROM VEF_EMP_TBLOCOM410_M810 x
              WHERE x.BDCODEMP = tmp.BDCODEMP
                AND x.BDCODMATRIZ = tmp.BDCODMATRIZ
                AND x.BDREFERENCIA = tmp.BDREFERENCIA
                AND x.BDCODPERIODO = 7
                AND x.BDCODQUADRO = 43
                AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL)))
                AND x.BDCHAVE =  ) AS BDORDEM,*/

       tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODNATREC, SUM(tmp.BDVL_ITEM) AS BDVL_REC, NULL AS BDDESC_COMPL,
       :PRRETIFICADORA BDRETIFICADORA
      FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
      WHERE (tmp.BDCODCSTCOF > 0)
        AND (tmp.BDCODNATREC IS NOT NULL)
        AND tmp.BDCODMATRIZ = iif(:PRAJUSTESCP = 'TRUE' and :PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
        AND tmp.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT FIRST 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM400_M800 x
                    WHERE x.BDCODPERIODO = 7
                      AND x.BDCODEMP = IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODEMP)
                      AND x.BDCODMATRIZ = IIF(tmp.BDCODEMPSCP > 0,tmp.BDCODEMPSCP,tmp.BDCODMATRIZ)
                      AND x.BDREFERENCIA = tmp.BDREFERENCIA
                      AND IIF(TMP.BDCODCSTCOF IN ('04','06','07','08','09'), X.BDCODCSTCOF = TMP.BDCODCSTCOF, x.BDCODCSTCOF IS NULL)
                      AND IIF(tmp.BDCODCSTPIS in ('04','06','07','08','09'), x.BDCODCSTPIS = tmp.BDCODCSTPIS, x.BDCODCSTPIS is null)
                      AND x.BDCODQUADRO = 43
                      AND X.BDRETIFICADORA = :PRRETIFICADORA
                      AND ((x.BDCODPLAPADRAO = tmp.BDCODPLAPADRAO) OR ((x.BDCODPLAPADRAO IS NULL) AND (tmp.BDCODPLAPADRAO IS NULL)))
                      AND ((x.BDCODTPLA = tmp.BDCODTPLA) OR ((x.BDCODTPLA IS NULL) AND (tmp.BDCODTPLA IS NULL))) ))
      GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODNATREC, tmp.BDCODPLAPADRAO, tmp.BDCODTPLA, tmp.BDCODCTA, tmp.BDCODCSTCOF, tmp.BDCODCSTPIS,tmp.BDCODEMPSCP;

    END

   IF ((prverificarinconsistencias = 'TRUE' )) then
     BEGIN
       /* Lançamentos sem natureza da base de cálculo  #Inconsistência# */
       INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP,  BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDRETIFICADORA)
       SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA,  GETORDEMSEQUENCIAL_STR(tmp.bdcodmatriz||'.'||tmp.bdcodemp||'.'||tmp.bdreferencia, :prCODEMP) AS BDCODBLOCOM, tmp.BDCODTP, tmp.BDCHAVE, tmp.BDORDEM, tmp.BDORDEMPRO, 2 AS BDCODINC,
              :PRRETIFICADORA BDRETIFICADORA
       FROM TMP_VEF_EMP_TBLOCOM_M400_M800 tmp
       WHERE tmp.BDCODNATREC IS NULL
         AND tmp.BDCODMATRIZ = iif(:PRAJUSTESCP = 'TRUE' and :PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
         AND tmp.BDREFERENCIA = :prREFERENCIA;
     END
END^

CREATE OR ALTER PROCEDURE SP_APURACAO_BLOCOM_M350 (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRRETIFICADORA INTEGER)
AS
DECLARE VARIABLE WALIQ NUMERIC(15,6);
DECLARE VARIABLE WCODIMP INTEGER;
DECLARE VARIABLE WVLRBRUTO NUMERIC(15,2);
DECLARE VARIABLE WVLRPIS NUMERIC(15,2);
BEGIN
  -- Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT FIRST 1 i.BDCODIMP, i.BDALIQIMPOSTO
  FROM VW_TEMPRESAIMPOSTO e
  LEFT OUTER JOIN TIMPOSTO i ON (i.BDCODIMP = e.BDCODIMP)
  WHERE e.BDCODEMP = :prCODEMP
    AND i.BDCLASSIMP LIKE '01.01.01.04.%' -- "Classificação" PIS - Programa integração social
    AND i.BDCODSIS = 2 -- "Sistema" Folha
    AND i.BDDOCARRECADACAO = 1 -- "Documento arrecadação" DARF
    AND i.BDCODTIPIMP = 6 -- "Tipo de imposto" PIS/Pasep
    AND i.BDTIPOIMPDOC = 2 -- "Tipo cálculo imposto" PIS
    AND i.BDTIPORETENCAO = 1 -- "Retenção" PIS
  INTO :wCODIMP, :wALIQ;

  IF (wALIQ IS NOT NULL) THEN -- A empresa deve ter o imposto cadastrado na empresa, caso contrário, não obriga...
    BEGIN
      SELECT --calc.BDCODEMP,calc.BDREFFN,
             SUM(CASE WHEN vr.BDTIPOCODVER = 0 THEN COALESCE(calc.BDVALVFN,0) ELSE 0 END) AS BDVLRBRUTO
             --SUM(CASE WHEN vr.BDPISVER = 'TRUE' THEN calc.BDVALVFN ELSE 0 END) AS BDVLRPIS -- Apenas verbas cadastradas como PIS
      FROM (
            SELECT fn.BDCODEMP, fn.BDCODCOL, fn.BDREFFN, fn.BDCODVER, fn.BDVALVFN
            FROM VRHF_EMP_TVERBAFN fn -- Folha normal
            WHERE fn.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND fn.BDREFFN = :prREFERENCIA
      
            UNION ALL
      
            SELECT rh.BDCODEMP, ad.BDCODCOL, ad.BDREFCOMP, ad.BDCODVER, ad.BDVALVFC
            FROM VRHF_EMP_TVERBAFC ad -- Folha normal complementar
            JOIN VW_VRHF_EMPRESAS_REF_ATUAL rh ON (ad.BDCODEMP = rh.BDCODEMP)
            WHERE (rh.BDCALCFCNAFNEMP <> 'TRUE')
              AND ad.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND ad.BDREFCOMP = :prREFERENCIA
      
            UNION ALL
      
            SELECT ft.BDCODEMP, ft.BDCODCOL, ft.BDREFTOMADOR, ft.BDCODVER, ft.BDVALVFT
            FROM VRHF_EMP_TVERBATOMADOR ft -- Folha por tomador
            WHERE ft.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND ft.BDREFTOMADOR = :prREFERENCIA
      
            UNION ALL
      
            SELECT ad.BDCODEMP, ad.BDCODCOL, ad.BDREFCOMP, ad.BDCODVER, ad.BDVALVFC
            FROM VRHF_EMP_TVERBAFCTOMADOR ad -- Folha por tomador complementar
            JOIN VW_VRHF_EMPRESAS_REF_ATUAL rh ON (ad.BDCODEMP = rh.BDCODEMP)
            WHERE (rh.BDCALCFCNAFNEMP <> 'TRUE')
              AND ad.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND ad.BDREFCOMP = :prREFERENCIA
      
            UNION ALL
      
            SELECT dt.BDCODEMP, dt.BDCODCOL, dt.BDREF13, dt.BDCODVER, dt.BDVALV13
            FROM VRHF_EMP_TVERBA13 dt -- 13º
            WHERE dt.BDCODEMP in (SELECT ex.BDCODEMP
                                  FROM TEMPRESAS ex
                                  WHERE ex.BDCODEMP = :prCODEMP
                                     OR ex.BDCODMATRIZ = :prCODEMP)
              AND dt.BDREF13 = :prREFERENCIA
      
            UNION ALL

            SELECT ADT.BDCODEMP, ADT.BDCODCOL, ADT.BDREFA13, ADT.BDCODVER, ADT.BDVALVA13
            FROM vrhf_emp_tverbaa13 ADT -- Adiantamento 13o
            WHERE ADT.BDCODEMP in (SELECT ex.BDCODEMP
                                   FROM TEMPRESAS ex
                                   WHERE ex.BDCODEMP = :prCODEMP
                                      OR ex.BDCODMATRIZ = :prCODEMP)
              AND ADT.BDREFA13 = :prREFERENCIA

            UNION ALL
      
            SELECT cdt.BDCODEMP, cdt.BDCODCOL, cdt.BDREFC13, cdt.BDCODVER, cdt.BDVALVC13
            FROM VRHF_EMP_TVERBAC13 cdt -- Complemento 13o
            WHERE cdt.BDCODEMP in (SELECT ex.BDCODEMP
                                   FROM TEMPRESAS ex
                                   WHERE ex.BDCODEMP = :prCODEMP
                                      OR ex.BDCODMATRIZ = :prCODEMP)
              AND cdt.BDREF13 = :prREFERENCIA
            ) calc
      JOIN VW_VRH_EMP_TCOLCON_VINC col ON (col.BDCODEMP = calc.BDCODEMP AND col.BDCODCOL = calc.BDCODCOL)
      JOIN VRH_BASE_TCLASSE cla ON (col.BDCODCLA = cla.BDCODCLA)
      JOIN VW_VERBAS_REF_ATUAL vr ON (vr.BDCODVER = calc.BDCODVER)
      --GROUP BY calc.BDCODEMP, calc.BDREFFN
      INTO :wVLRBRUTO;--, :wVLRPIS;

      /* Caso não tenha apuração da folha #Inconsistência# */
      --IF (:wVLRBRUTO IS NULL) THEN
      --  INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC)
      --                        VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, (SELECT COALESCE(MAX(x.BDCODBLOCOM)+1,1) FROM VEF_INCON_BLOCOM x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = :prCODEMP AND x.BDCODMATRIZ = :prCODEMP AND x.BDREFERENCIA = :prREFERENCIA), NULL, NULL, NULL, NULL, 3);

      SELECT SUM(COALESCE(d.BDBASEIMP,0)) as BDBASEIMP
      FROM TDARFPADRAO d
      WHERE d.BDCODIMP = :wCODIMP
        AND d.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = :prCODEMP
                              OR ex.BDCODMATRIZ = :prCODEMP)
        AND d.BDREFERENCIA = :prREFERENCIA
      INTO :wVLRPIS;

      /* Caso não tenha apuração do Darf PIS #Inconsistência# */
      IF ((:wVLRPIS IS NULL) and (prverificarinconsistencias = 'TRUE' )) then
        INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDRETIFICADORA)
                              VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, GETORDEMSEQUENCIAL_STR(:prCODEMP||'.'||:prCODEMP||'.'||:prREFERENCIA, :prCODEMP), NULL, NULL, NULL, NULL, 12, :PRRETIFICADORA);

    END

  IF ((wALIQ IS NULL) OR (wVLRBRUTO IS NULL) OR (wVLRPIS IS NULL)) THEN
    EXIT;

  /* 02 - VL_TOT_FOL - Valor Total da Folha de Salários */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 2, :wVLRBRUTO, :PRRETIFICADORA);

  /* 03 - VL_EXC_BC - Valor Total das Exclusões à Base de Cálculo */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 3, (:wVLRBRUTO - :wVLRPIS), :PRRETIFICADORA);

  /* 04 - VL_TOT_BC - Valor Total da Base de Cálculo */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 4, :wVLRPIS, :PRRETIFICADORA);

  IF ((wVLRBRUTO = 0) AND (wVLRPIS = 0)) THEN -- Caso venham valores zerados, leva tudo zerado...
    wALIQ = 0;

  /* 05 - ALIQ_PIS_FOL - Alíquota do PIS/PASEP – Folha de Salários */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 5, :wALIQ, :PRRETIFICADORA);

  /* 06 - VL_TOT_CONT_FOL - Valor Total da Contribuição Social sobre a Folha de Salários */
  INSERT INTO VEF_EMP_TBLOCOMGERREG (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODQUADRO, BDNUMCAMPO, BDVALOR, BDRETIFICADORA)
  VALUES (7, :prCODEMP, :prCODEMP, :prREFERENCIA, 25, 6, ((:wVLRPIS*:wALIQ)/100), :PRRETIFICADORA);

END^

create or alter procedure SP_APURACAO_BLOCOM_M300_M700 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PRCODEMPSO integer = 0)
as
declare variable WSQL varchar(32750);
declare variable WULTDIA integer;
declare variable WWHEREDADATA varchar(50);
BEGIN
  /*
    REGISTRO M300: CONTRIBUIÇÃO DE PIS/PASEP DIFERIDA EM PERÍODOS ANTERIORES - VALORES A PAGAR NO PERÍODO.
    REGISTRO M700: COFINS DIFERIDA EM PERÍODOS ANTERIORES - VALORES A PAGAR NO PERÍODO
  */
  --elizeu - 25-10-19 - Bloco M - Lançamento M300/M700 - EFD Contribuições #125762
  EXECUTE STATEMENT 'select ULTDIA from ULTIMO_DIA_MES('||SUBSTRING(PRREFERENCIA FROM 5 FOR 2)||', '||SUBSTRING(PRREFERENCIA FROM 1 FOR 4)||')' INTO :wultdia;
  --MMDDYYYY_SEP
  wWhereDaData = ' between '''||SUBSTRING(PRREFERENCIA FROM 5 FOR 2)||'/01/'||SUBSTRING(PRREFERENCIA FROM 1 FOR 4);
  wWhereDaData = wWhereDaData ||''' and '''||SUBSTRING(PRREFERENCIA FROM 5 FOR 2)||'/'||:wultdia||'/'||SUBSTRING(PRREFERENCIA FROM 1 FOR 4) ||'''';

  wSQL =       'INSERT INTO VEF_EMP_TBLOCOM300_M700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCSOCIAL, BDVL_CONT_APUR_DIFER, BDNAT_CRED_DESC, BDVL_CRED_DESC_DIFER, BDVL_CONT_DIFER_ANT, BDALIQ, BDPER_APUR, BDDT_RECEB, BDRETIFICADORA) ';
  wSQL = wSQL||'SELECT aux.BDCODQUADRO, aux.BDCODPERIODO, '||IIF(:PRAJUSTESCP = 'TRUE','COALESCE(SCP.BDCODEMPSCP,AUX.BDCODEMP)', 'AUX.BDCODEMP')||' BDCODEMP, '||IIF(:PRAJUSTESCP = 'TRUE','COALESCE(SCP.BDCODEMPSCP,coalesce(EMP.BDCODMATRIZ, AUX.BDCODEMP))','coalesce(EMP.BDCODMATRIZ, AUX.BDCODEMP)')||' as BDCODMATRIZ, (select BDAAAAMM from AAAAMM(aux.BDDT_RECEB)) BDREFERENCIA, ';
--  wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCHAVE+1),1) FROM VEF_EMP_TBLOCOM300_M700 x WHERE x.BDCODPERIODO = aux.BDCODPERIODO AND x.BDCODEMP = aux.BDCODEMP AND x.BDCODMATRIZ = COALESCE(emp.BDCODMATRIZ, aux.BDCODEMP) AND x.BDCODQUADRO = aux.BDCODQUADRO AND x.BDREFERENCIA = aux.BDREFERENCIA) AS BDCHAVE, ';
  wSQL = wSQL||       'aux.BDCHAVE, ';
  wSQL = wSQL||       'aux.BDCODCSOCIAL, aux.BDVL_CONT_APUR_DIFER, aux.BDNAT_CRED_DESC, aux.BDVL_CRED_DESC_DIFER, aux.BDVL_CONT_DIFER_ANT, aux.BDALIQ, aux.BDPER_APUR, aux.BDDT_RECEB, ';
  wSQL = wSQL||       :PRRETIFICADORA||' BDRETIFICADORA ';
  wSQL = wSQL||'FROM ( ';
  wSQL = wSQL||      'SELECT 24 as BDCODQUADRO, '; -- M300 - Diferimentos Períodos Anteriores de PIS/PASEP
  wSQL = wSQL||             '7 as BDCODPERIODO, m300.BDCODEMP, m300.BDCHAVE, m300.BDREFERENCIA, m300.BDCODCSOCIAL, m300.BDVLRCONTRIPIS as BDVL_CONT_APUR_DIFER, ';
  wSQL = wSQL||             'm300.BDCODNATDEF as BDNAT_CRED_DESC, m300.BDVLRCREPIS as BDVL_CRED_DESC_DIFER, (m300.BDVLRCONTRIPIS-m300.BDVLRCREPIS) as BDVL_CONT_DIFER_ANT, ';
  wSQL = wSQL||             'm300.BDALIQPIS as BDALIQ, m300.BDREFERENCIA as BDPER_APUR, m300.BDDATAREC as BDDT_RECEB, M300.BDCODSCP, M300.BDREFSOC ';
  wSQL = wSQL||      'FROM VEF_EMP_TINFADIDEFM300M700 m300 ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 soc ON (soc.BDCODCSOCIAL = m300.BDCODCSOCIAL) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_TTABNATCREDEF nat ON (nat.BDCODNATDEF = m300.BDCODNATDEF) ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = M300.BDCODEMP AND SCP.BDCODSCP = M300.BDCODSCP AND SCP.BDREFEMP = M300.BDREFSOC) ';
  wSQL = wSQL||      'WHERE m300.'||TRIM(:prWHEREEMPRESAS)||' ';
  --elizeu - 25-10-19 - Bloco M - Lançamento M300/M700 - EFD Contribuições #125762
  --  wSQL = wSQL||        'AND m300.BDREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||        'AND m300.BDDATAREC '||:wWhereDaData||' ';
  
  wSQL = wSQL||      ' UNION ALL ';
  
  wSQL = wSQL||      'SELECT 42 as BDCODQUADRO, '; -- M700 - Diferimentos Períodos Anteriores de Cofins
  wSQL = wSQL||             '7 as BDCODPERIODO, m700.BDCODEMP, m700.BDCHAVE, m700.BDREFERENCIA, m700.BDCODCSOCIAL, m700.BDVLRCONTRICOFINS as BDVL_CONT_APUR_DIFER, ';
  wSQL = wSQL||             'm700.BDCODNATDEF as BDNAT_CRED_DESC, m700.BDVLRCRECOFINS as BDVL_CRED_DESC_DIFER, (m700.BDVLRCONTRICOFINS-m700.BDVLRCRECOFINS) as BDVL_CONT_DIFER_ANT, ';
  wSQL = wSQL||             'm700.BDALIQCOFINS as BDALIQ, m700.BDREFERENCIA as BDPER_APUR, m700.BDDATAREC as BDDT_RECEB, M700.BDCODSCP, M700.BDREFSOC ';
  wSQL = wSQL||      'FROM VEF_EMP_TINFADIDEFM300M700 m700 ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_TTABCSOCIAL_4_3_5 soc ON (soc.BDCODCSOCIAL = m700.BDCODCSOCIAL) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_TTABNATCREDEF nat ON (nat.BDCODNATDEF = m700.BDCODNATDEF) ';
  wSQL = wSQL||      'WHERE m700.'||TRIM(:prWHEREEMPRESAS)||' ';
--  wSQL = wSQL||        'AND m700.BDREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||        'AND m700.BDDATAREC '||:wWhereDaData||' ';
  wSQL = wSQL||      ') aux ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = aux.BDCODEMP) ';
  wSQL = wSQL||'left outer join TEMPRESAS_SCP SCP on (SCP.BDCODEMP = AUX.BDCODEMP and SCP.BDCODSCP = AUX.BDCODSCP and SCP.BDREFEMP = AUX.BDREFSOC) ';

  if ((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0)) then
    wSQL = wSQL||' where coalesce(SCP.BDCODEMPSCP, 0) = '||:PRCODEMP;
  else
  if (:PRAJUSTESCP = 'TRUE') then
    wSQL = wSQL||' where coalesce(SCP.BDCODEMPSCP, 0) = 0 ';


  EXECUTE STATEMENT wSQL;

  /* REGISTRO M350: PIS/PASEP - FOLHA DE SALÁRIOS */
  if (prReferencia < 202401) then --Conforme Nota Técnica nº 08_2023 - Migração contribuintes PIS_Pasep sobre Folha para eSocial
    begin
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M350 (:prCODEMP, :prREFERENCIA,:prverificarinconsistencias, :PRRETIFICADORA);
    end
END^

create or alter procedure SP_APURACAO_BLOCOM_F60013001700 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PRCODEMPSO integer = 0)
as
declare variable WSQL varchar(32750);
declare variable WINCTRIB integer;
declare variable WTIPOAPURACAORET integer;
declare variable WINDNATPJ integer;
declare variable WRETPISCOFPERANT varchar(5);
BEGIN
  -- Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, BDRETPISCOFPERANT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wRETPISCOFPERANT;

  if ((:wINCTRIB is null) and (:PRCODEMPSO > 0)) then
    begin
      SELECT BDINCTRIB+1, BDRETPISCOFPERANT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMPSO
      INTO :wINCTRIB, :wRETPISCOFPERANT;
    end

  SELECT BDTIPOAPURACAORET FROM VW_VEF_BASE_TEMPPARGER WHERE BDCODEMP = :prCODEMP
  INTO :wTIPOAPURACAORET;

  SELECT BDINDNATPJ FROM VW_VEF_BASE_TEMPPARFED WHERE BDCODEMP = :prCODEMP
  INTO :wINDNATPJ;

  wSQL =       'INSERT INTO TMP_VEF_EMP_TBLOCOM_F600_1300 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDREFAPUSALDO, BDCODTER, BDCNPJEMP, BDDATAEMISSAO, BDVLRCONTAB, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDIND_DEC, BDCODRECPIS, BDCODRECCOFINS, BDVLRPISRET, BDVLRCOFINSRET,BDCODEMPSCP) ';
  /* Saldos de PIS e/ou Cofins lançados */
  wSQL = wSQL||'select GYATT.* ';
  wSQL = wSQL||'from (';
  wSQL = wSQL||'SELECT S.BDCODEMP, coalesce(EMP.BDCODMATRIZ, S.BDCODEMP) as BDCODMATRIZ,';
  wSQL = wSQL||       's.BDREFERENCIA, s.BDREFAPUSALDO, 0 as BDCODTER, emp.BDCNPJEMP, ';
  wSQL = wSQL||       'CAST(SUBSTRING(s.BDREFERENCIA from 1 for 4)||''-''|| SUBSTRING(s.BDREFERENCIA from 5 for 2)||''-01'' as date) as BDDATAEMISSAO, ';
  wSQL = wSQL||       '0 as BDVLRCONTAB, s.BDCODIND_NAT_RET, s.BDTIPONATREC, 0 as BDIND_DEC, ';
  wSQL = wSQL||       'null as BDCODRECPIS, null as BDCODRECCOFINS, ';
  wSQL = wSQL||       'COALESCE(s.BDVLRRETPIS, 0) as BDVLRPISRET, COALESCE(s.BDVLRRETCOFINS, 0) as BDVLRCOFINSRET, '||IIF(:PRAJUSTESCP = 'TRUE', 'COALESCE(SCP.BDCODEMPSCP,0)','0')||' BDCODEMPSCP ';
  wSQL = wSQL||'FROM VEF_EMP_TSALDOSBLOCOM s ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = S.BDCODEMP AND SCP.BDCODSCP = S.BDCODSCP AND SCP.BDREFEMP = S.BDREFSOC) ';
  wSQL = wSQL||'WHERE ((s.BDVLRRETPIS > 0) or (s.BDVLRRETCOFINS > 0)) ';
  wSQL = wSQL||        'AND (s.BDCREDRETIDOS = ''TRUE'') ';
  wSQL = wSQL||        'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND s.BDREFERENCIA = '||:prREFERENCIA||' ';

  wSQL = wSQL||'UNION ALL ';

  -- Solicitação 4962
  -- Demais documentos
  wSQL = wSQL||'SELECT aux.BDCODEMP,aux.BDCODMATRIZ  as BDCODMATRIZ, ';
  wSQL = wSQL||' aux.BDREFERENCIA, aux.BDREFAPUSALDO, aux.BDCODTER, emp.BDCNPJEMP,  ';
  wSQL = wSQL||       'aux.BDDATAEMISSAO, aux.BDVLRCONTAB, nat.BDCODIND_NAT_RET, aux.BDTIPONATREC, aux.BDIND_DEC, ';
  wSQL = wSQL||       'aux.BDCODRECPIS, aux.BDCODRECCOFINS, aux.BDVLRPISRET, aux.BDVLRCOFINSRET,'||IIF(:PRAJUSTESCP = 'TRUE', 'COALESCE(SCP.BDCODEMPSCP,0)','0')||' BDCODEMPSCP ';
  wSQL = wSQL||'FROM ( ';
  wSQL = wSQL||      'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDREFLAN as BDREFERENCIA, dem.BDREFLAN as BDREFAPUSALDO, dem.BDCODTER, indoper.BDINDICADOR,';
  wSQL = wSQL||             'dem.BDDT_OPER as BDDATAEMISSAO, dem.BDVL_OPER as BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ret.BDCODRECPIS, ret.BDCODRECCOFINS,';
  wSQL = wSQL||             'ret.BDVLRPIS as BDVLRPISRET, ret.BDVLRCOFINS as BDVLRCOFINSRET,';
  wSQL = wSQL||             'case when dem.BDIND_OPER = 1 then 1 else 0 end as BDIND_DEC, DEM.BDCODSCP, DEM.BDREFSOC, DEM.BDCHAVE '; -- Aquisição
  wSQL = wSQL||      'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_TCADTIPODEMDOC CAD on (dem.BDCODTIPODOC = CAD.BDCODTIPODOC)';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
  wSQL = wSQL||      'JOIN VEF_BASE_TAB_TIPO_OPERACAO indoper on (indoper.BDIND_OPER = dem.BDIND_OPER) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TMOVDEMRET ret on (ret.BDCODEMP = dem.BDCODEMP and ret.BDCHAVE = dem.BDCHAVE) ';
  wSQL = wSQL||      'WHERE ( (dem.'||TRIM(:prWHEREEMPRESAS)||') ';
  wSQL = wSQL||      'AND ((CAD.BDNAOEXPSPED = ''FALSE'') or (CAD.BDNAOEXPSPED is null))';
  wSQL = wSQL||        'AND (CAST(SUBSTRING(dem.BDDT_OPER FROM 1 for 4)||SUBSTRING(dem.BDDT_OPER FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
    
  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo parêmetro de tipo de apuração da empresa
    wSQL = wSQL||        'AND (dem.BDCONDPGTO <> 1) ';
    
  -- Caso incidência tributária 2 = regime cumulativo. Sped lucro presumido somente os lançamentos de saidas(receitas) então somente os lançamentos com tipos 1 e 2.
  IF (:wINDNATPJ NOT IN (1,4)) THEN -- Alt.: 12342 - Caso a natureza jurídica não seja 1 e 4(Sociedade cooperativa), leva somente aquisição e receita não sujeita ao pagamento de contribuição
    wSQL = wSQL||        'AND (dem.BDIND_OPER IN(2,3)) ';
  
  wSQL = wSQL|| ' ) ';

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo parêmetro de tipo de apuração da empresa
    BEGIN
      wSQL = wSQL||      'UNION ALL ';
      -- Demais documentos - Pagamentos
      wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(EMP.BDCODMATRIZ, MOV.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' as BDREFERENCIA, '||:prREFERENCIA||' as BDREFAPUSALDO, mov.BDCODTER, indoper.BDINDICADOR,';
      wSQL = wSQL||             'pgto.BDDATAPGTOPAR as BDDATAEMISSAO,';
      wSQL = wSQL||             'SUM((pgto.BDVALORPGTOPAR)+';
      wSQL = wSQL||              '(COALESCE(pgto.BDVALORRETPIS, 0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETCOFINS,0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETCSLL, 0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETIRRF, 0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETISSQN, 0)+';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETINSS, 0))) as BDVLRCONTAB,';
      wSQL = wSQL||             'ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ret.BDCODRECPIS, ret.BDCODRECCOFINS,';
      wSQL = wSQL||             'SUM(pgto.BDVALORRETPIS) as BDVLRPISRET, SUM(pgto.BDVALORRETCOFINS) as BDVLRCOFINSRET,';
      wSQL = wSQL||             'case when mov.BDIND_OPER = 1 then 1 else 0 end as BDIND_DEC, mov.BDCODSCP, mov.BDREFSOC,mov.BDCHAVE '; -- Aquisição
      wSQL = wSQL||      'FROM (';
      wSQL = wSQL||            'SELECT * ';
      wSQL = wSQL||            'FROM ( ';
      wSQL = wSQL||                  'SELECT x.BDCODEMP, x.BDCHAVE, x.BDREFLAN, x.BDCODTER, x.BDIND_OPER, x.BDCODCSTPIS, x.BDCODCSTCOF,x.BDCODSCP, x.BDREFSOC ';
      wSQL = wSQL||                  'FROM VEF_EMP_TMOVDEMAISDOC_F100 x ';
      wSQL = wSQL||              'left outer join VEF_BASE_TCADTIPODEMDOC CAD on (x.BDCODTIPODOC = CAD.BDCODTIPODOC)';
      wSQL = wSQL||                  'WHERE x.'||TRIM(:prWHEREEMPRESAS)||' ';

      IF (:wINDNATPJ NOT IN (1,4)) THEN -- Alt.: 12342 - Caso a natureza jurídica não seja 1 e 4(Sociedade cooperativa), leva somente aquisição e receita não sujeita ao pagamento de contribuição
        wSQL = wSQL||                   'AND (x.BDIND_OPER IN(2,3)) ';

      wSQL = wSQL||                'AND ((CAD.BDNAOEXPSPED = ''FALSE'') or (CAD.BDNAOEXPSPED is null))';
      wSQL = wSQL||                  ') aux ';
      IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
        wSQL = wSQL||            'WHERE ((SELECT first 1 BDTIPOAPURACAORET FROM VEF_BASE_TEMPPARGER e WHERE e.BDCODEMP = aux.BDCODEMP AND e.BDREFEMP <= aux.BDREFLAN ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||            ') mov ';
      wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVF100PAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVF100PARPGTO pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||      'JOIN VEF_BASE_TAB_TIPO_OPERACAO INDOPER on (indoper.BDIND_OPER = mov.BDIND_OPER) ';
      wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TMOVDEMRET ret on (ret.BDCODEMP = mov.BDCODEMP and ret.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||      'WHERE ((mov.BDCODCSTPIS is not null) or (mov.BDCODCSTCOF is not null)) ';
      wSQL = wSQL||        'AND (CAST(SUBSTRING(pgto.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(pgto.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
      --wSQL = wSQL||        'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - Não levar no faturamento caso o tipo seja "Desconto"
      wSQL = wSQL||        'AND pgto.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
      wSQL = wSQL||      'GROUP BY MOV.BDCODEMP,EMP.BDCODMATRIZ,MOV.BDCODTER,INDOPER.BDINDICADOR,PGTO.BDDATAPGTOPAR,RET.BDCODIND_NAT_RET,RET.BDTIPONATREC,RET.BDCODRECPIS,RET.BDCODRECCOFINS,MOV.BDIND_OPER,MOV.BDCODSCP, MOV.BDREFSOC, MOV.BDCHAVE ';
    END

  wSQL = wSQL||      'UNION ALL ';
  -- Lançamentos de compensação de retenções de serviços emitidos
  wSQL = wSQL||      'SELECT ret.BDCODEMP, COALESCE(emp.BDCODMATRIZ, ret.BDCODEMP) as BDCODMATRIZ, ret.BDREFERENCIA, ret.BDREFERENCIA as BDREFAPUSALDO, ret.BDCODTER, ';
  wSQL = wSQL||             '0 AS BDINDICADOR, ret.BDDATALAN AS BDDATAEMISSAO, ret.BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
  wSQL = wSQL||             'ret.BDCODRECPIS, ret.BDCODRECCOFINS, ret.BDVLRPIS AS BDVLRPISRET, ret.BDVLRCOFINS AS BDVLRCOFINSRET, ';
  wSQL = wSQL||             '0 as BDIND_DEC, NULL BDCODSCP, NULL BDREFSOC, ret.BDCHAVE ';
  wSQL = wSQL||      'FROM ( ';
  wSQL = wSQL||            'SELECT r.BDCODEMP, r.BDCODTER, r.BDREFLAN AS BDREFERENCIA, r.BDDATALAN, r.BDVLRCONTAB, r.BDCODIND_NAT_RET, r.BDCODRECPIS, ';
  wSQL = wSQL||                   'r.BDCODRECCOFINS, r.BDVLRPIS, r.BDVLRCOFINS, r.BDTIPONATREC, R.BDCHAVE ';
  wSQL = wSQL||            'FROM VEF_EMP_TMOVCOMPRET r ';
  wSQL = wSQL||            'WHERE r.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||              'AND (CAST(SUBSTRING(r.BDDATALAN FROM 1 for 4)||SUBSTRING(r.BDDATALAN FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
  wSQL = wSQL||            ') ret ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = ret.BDCODEMP) ';

  wSQL = wSQL||      'UNION ALL ';
  -- Serviço
  wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFERENCIA, mov.BDREFERENCIA as BDREFAPUSALDO, mov.BDCODTER, ';
  wSQL = wSQL||             'mov.BDTIPLAN AS BDINDICADOR, mov.BDDATAEMISSAO, mov.BDVALORNOTA AS BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
  wSQL = wSQL||             'ret.BDCODRECPIS, ret.BDCODRECCOFINS, IIF(MOV.BDVALORNOTA > 0,((SUM(I.BDVLRCONTAB)/MOV.BDVALORNOTA)* RET.BDVLRPIS),RET.BDVLRPIS) AS BDVLRPISRET, IIF(MOV.BDVALORNOTA > 0,((SUM(I.BDVLRCONTAB)/MOV.BDVALORNOTA)*RET.BDVLRCOFINS),RET.BDVLRCOFINS) AS BDVLRCOFINSRET, ';
  wSQL = wSQL||             'case when mov.BDTIPLAN = 1 then 1 else 0 end as BDIND_DEC, I.BDCODSCP, I.BDREFSOC, MOV.BDCHAVE '; -- Recebidos
  wSQL = wSQL||      'FROM ( ';
  wSQL = wSQL||            'SELECT ser.BDCODEMP, ser.BDCHAVE, ser.BDCODTER, ser.BDDATAEMISSAO, ser.BDVALORNOTA, ser.BDTIPLAN, ser.BDREFLAN AS BDREFERENCIA ';
  wSQL = wSQL||            'FROM VEF_EMP_TMOVSER ser ';
  wSQL = wSQL||            'WHERE ser.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||              'AND (ser.BDREFLAN = '||:prREFERENCIA||') ';
  wSQL = wSQL||              'AND (ser.BDCODSITNF not in (2,3,4,5)) '; -- Alt.: 16516 - Ajustes para não exportar documentos cancelados...
  wSQL = wSQL||              'AND EXISTS(SELECT * '; -- Alt.: #88586 - Ajustes para não exportar lançamentos quando tenham alguma CFOP com a opção "Não levar Sped Contribuições"
  wSQL = wSQL||                         'FROM VEF_EMP_TMOVSERITENS si ';
  wSQL = wSQL||                         'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = si.bdCODNAT AND ((nat.bdNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.bdNAOEXPEFDCONT)) = TRIM(''FALSE''))) ) ';
  wSQL = wSQL||                         'WHERE si.bdCODEMP = ser.bdCODEMP ';
  wSQL = wSQL||                           'AND si.bdCHAVE  = ser.bdCHAVE) ';

  -- caso incidência tributária 2 = regime cumulativo, exportar somente emitidos
  IF (:wINDNATPJ NOT IN (1,4)) THEN -- Alt.: 12342 - Caso a natureza jurídica não seja 1 e 4(Sociedade cooperativa), leva somente serviços emitidos
    wSQL = wSQL||              'AND (ser.BDTIPLAN = 0) ';

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo parêmetro de tipo de apuração da empresa
    wSQL = wSQL||              'AND (ser.BDCONDPGTO <> 1) ';

  wSQL = wSQL||            ') mov ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TMOVSERRET ret on (mov.BDCODEMP = ret.BDCODEMP AND mov.BDCHAVE = ret.BDCHAVE) ';
  wSQL = wSQL||      '      left outer join VEF_EMP_TMOVSERITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE) ';
  wSQL = wSQL||      'GROUP BY EMP.BDCODMATRIZ, MOV.BDCODEMP, MOV.BDREFERENCIA, MOV.BDCODTER, MOV.BDTIPLAN, MOV.BDDATAEMISSAO, MOV.BDVALORNOTA, MOV.BDCHAVE,';
  wSQL = wSQL||               'RET.BDCODIND_NAT_RET, RET.BDTIPONATREC, RET.BDCODRECPIS, RET.BDCODRECCOFINS, RET.BDVLRPIS, RET.BDVLRCOFINS, I.BDCODSCP, I.BDREFSOC ';

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo parêmetro de tipo de apuração da empresa
    BEGIN
      wSQL = wSQL||      'UNION ALL ';
     
      wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' BDREFERENCIA, '||:prREFERENCIA||' as BDREFAPUSALDO, mov.BDCODTER, ';
      wSQL = wSQL||             'mov.BDTIPLAN AS BDINDICADOR, pgto.BDDATAPGTOPAR as BDDATAEMISSAO, ';
      wSQL = wSQL||             'SUM((pgto.BDVALORPGTOPAR)+ ';
      wSQL = wSQL||              '(COALESCE(pgto.BDVALORRETPIS,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETCOFINS,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETCSLL,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETIRRF,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETISSQN,0)+ ';
      wSQL = wSQL||               'COALESCE(pgto.BDVALORRETINSS,0))) AS BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
      wSQL = wSQL||             'ret.BDCODRECPIS, ret.BDCODRECCOFINS, ';
      wSQL = wSQL||             'SUM(pgto.BDVALORRETPIS) as BDVLRPISRET,';
      wSQL = wSQL||             'SUM(pgto.BDVALORRETCOFINS) as BDVLRCOFINSRET,';
      wSQL = wSQL||             'case when mov.BDTIPLAN = 1 then 1 else 0 end as BDIND_DEC, '; -- Recebidos
      wSQL = wSQL||             '(SELECT FIRST 1 i.bdCODSCP FROM VEF_EMP_TMOVSERITENS I WHERE i.bdCODEMP = mov.bdCODEMP AND i.bdCHAVE = mov.bdCHAVE AND i.bdCODNAT = pgto.bdCODNAT ORDER BY i.bdORDEM), ';
      wSQL = wSQL||             '(SELECT FIRST 1 i.bdREFSOC FROM VEF_EMP_TMOVSERITENS I WHERE i.bdCODEMP = mov.bdCODEMP AND i.bdCHAVE = mov.bdCHAVE AND i.bdCODNAT = pgto.bdCODNAT ORDER BY i.bdORDEM), ';
      wSQL = wSQL||             'MOV.BDCHAVE '; -- Recebidos

      wSQL = wSQL||      'FROM ( ';
      wSQL = wSQL||            'SELECT * ';
      wSQL = wSQL||            'FROM ( ';
      wSQL = wSQL||                  'SELECT x.BDCODEMP, x.BDCHAVE, x.BDREFLAN, x.BDCODTER, x.BDTIPLAN, x.BDCODSITNF, x.BDDATAEMISSAO ';
      wSQL = wSQL||                  'FROM VEF_EMP_TMOVSER x ';
      wSQL = wSQL||                  'WHERE x.'||TRIM(:prWHEREEMPRESAS)||' ';

      IF (:wINDNATPJ NOT IN (1,4)) THEN -- Alt.: 12342 - Caso a natureza jurídica não seja 1 e 4(Sociedade cooperativa), leva somente serviços emitidos
        wSQL = wSQL||                    'AND (x.BDTIPLAN = 0) ';

      wSQL = wSQL||                  ') aux ';

      wSQL = wSQL||            'WHERE aux.BDCODSITNF not in (2,3,4,5) '; -- Alt.: 16516 - Ajustes para nÃ£o exportar documentos cancelados...
      IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
        wSQL = wSQL||              'AND ((SELECT first 1 BDTIPOAPURACAORET FROM VEF_BASE_TEMPPARGER e WHERE e.BDCODEMP = aux.BDCODEMP AND e.BDREFEMP <= aux.BDREFLAN ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||              'AND EXISTS(SELECT * '; -- Alt.: #88586 - Ajustes para não exportar lançamentos quando tenham alguma CFOP com a opção "Não levar Sped Contribuições"
      wSQL = wSQL||                         'FROM VEF_EMP_TMOVSERITENS si ';
      wSQL = wSQL||                         'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = si.bdCODNAT AND ((nat.bdNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.bdNAOEXPEFDCONT)) = TRIM(''FALSE''))) ) ';
      wSQL = wSQL||                         'WHERE si.bdCODEMP = aux.bdCODEMP ';
      wSQL = wSQL||                           'AND si.bdCHAVE  = aux.bdCHAVE) ';
      wSQL = wSQL||           ') mov ';
      wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVSERRET ret on (mov.BDCODEMP = ret.BDCODEMP AND mov.BDCHAVE = ret.BDCHAVE) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVSERPAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
      wSQL = wSQL||      'JOIN VEF_EMP_TMOVSERPARPGTO pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||      'WHERE (CAST(SUBSTRING(pgto.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(pgto.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
      --wSQL = wSQL||        'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - Não levar no faturamento caso o tipo seja "Desconto"
      wSQL = wSQL||        'AND pgto.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
      wSQL = wSQL||        'GROUP BY MOV.BDCODEMP,EMP.BDCODMATRIZ,MOV.BDCODTER,MOV.BDTIPLAN,PGTO.BDDATAPGTOPAR,RET.BDCODIND_NAT_RET,RET.BDTIPONATREC,RET.BDCODRECPIS,RET.BDCODRECCOFINS,pgto.bdCODNAT,MOV.BDCHAVE ';
    END

  wSQL = wSQL||      'UNION ALL ';
  -- Saídas
  wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFERENCIA, mov.BDREFERENCIA as BDREFAPUSALDO, mov.BDCODTER, ';
  wSQL = wSQL||             'mov.BDTIPLAN AS BDINDICADOR, mov.BDDATAEMISSAO, mov.BDVALORNOTA AS BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
  wSQL = wSQL||             'ret.BDCODRECPIS, ret.BDCODRECCOFINS, IIF(MOV.BDVALORNOTA > 0,((SUM(I.BDVLRCONTAB)/MOV.BDVALORNOTA)*RET.BDVLRPIS),RET.BDVLRPIS) AS BDVLRPISRET, IIF(MOV.BDVALORNOTA > 0,((SUM(I.BDVLRCONTAB)/MOV.BDVALORNOTA)*RET.BDVLRCOFINS),RET.BDVLRCOFINS) AS BDVLRCOFINSRET, ';
  wSQL = wSQL||             '0 as BDIND_DEC,I.BDCODSCP, I.BDREFSOC, MOV.BDCHAVE ';
  wSQL = wSQL||      'FROM ( ';
  wSQL = wSQL||            'SELECT sai.BDCODEMP, sai.BDCHAVE, sai.BDCODTER, sai.BDDATAEMISSAO, sai.BDVALORNOTA, COALESCE(SAI.BDTIPLAN,0) AS BDTIPLAN, sai.BDREFLAN AS BDREFERENCIA ';
  wSQL = wSQL||            'FROM VEF_EMP_TMOVSAI sai ';
  wSQL = wSQL||            'WHERE sai.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||              'AND (CAST(SUBSTRING(sai.BDDATAEMISSAO FROM 1 for 4)||SUBSTRING(sai.BDDATAEMISSAO FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
  wSQL = wSQL||              'AND sai.BDCODSITNF not in (2,3,4,5) '; -- Alt.: 16516 - Ajustes para não exportar documentos cancelados...

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo parêmetro de tipo de apuração da empresa
    wSQL = wSQL||              'AND (sai.BDCONDPGTO <> 1) ';

  wSQL = wSQL||            ') mov ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TMOVSAIRET ret on (mov.BDCODEMP = ret.BDCODEMP AND mov.BDCHAVE = ret.BDCHAVE) ';
  wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE) ';
  wSQL = wSQL||      'GROUP BY EMP.BDCODMATRIZ, MOV.BDCODEMP, MOV.BDREFERENCIA, MOV.BDCODTER, MOV.BDTIPLAN, MOV.BDDATAEMISSAO, MOV.BDVALORNOTA, MOV.BDCHAVE,';
  wSQL = wSQL||               'RET.BDCODIND_NAT_RET, RET.BDTIPONATREC, RET.BDCODRECPIS, RET.BDCODRECCOFINS, RET.BDVLRPIS, RET.BDVLRCOFINS, I.BDCODSCP, I.BDREFSOC ';

  IF (:wTIPOAPURACAORET = 1) THEN -- Alt.: 12730 - Deve verificar pelo parêmetro de tipo de apuração da empresa
    BEGIN
      wSQL = wSQL||            'UNION ALL ';
    
      wSQL = wSQL||            'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' BDREFERENCIA, '||:prREFERENCIA||' as BDREFAPUSALDO, mov.BDCODTER, ';
      wSQL = wSQL||                   'mov.BDTIPLAN AS BDINDICADOR, pgto.BDDATAPGTOPAR as BDDATAEMISSAO, ';
      wSQL = wSQL||                   'SUM((pgto.BDVALORPGTOPAR)+ ';
      wSQL = wSQL||                    '(COALESCE(pgto.BDVALORRETPIS,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETCOFINS,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETCSLL,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETIRRF,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETISSQN,0)+ ';
      wSQL = wSQL||                     'COALESCE(pgto.BDVALORRETINSS,0))) AS BDVLRCONTAB, ret.BDCODIND_NAT_RET, ret.BDTIPONATREC, ';
      wSQL = wSQL||                   'ret.BDCODRECPIS, ret.BDCODRECCOFINS,';
      wSQL = wSQL||                   'SUM(pgto.BDVALORRETPIS) as BDVLRPISRET,';
      wSQL = wSQL||                   'SUM(pgto.BDVALORRETCOFINS) as BDVLRCOFINSRET,';
      wSQL = wSQL||                   '0 as BDIND_DEC,';
      wSQL = wSQL||                   '(SELECT FIRST 1 i.bdCODSCP FROM VEF_EMP_TMOVSAIITENS I WHERE i.bdCODEMP = mov.bdCODEMP AND i.bdCHAVE = mov.bdCHAVE AND i.bdCODNAT = pgto.bdCODNAT ORDER BY i.bdORDEM), ';
      wSQL = wSQL||                   '(SELECT FIRST 1 i.bdREFSOC FROM VEF_EMP_TMOVSAIITENS I WHERE i.bdCODEMP = mov.bdCODEMP AND i.bdCHAVE = mov.bdCHAVE AND i.bdCODNAT = pgto.bdCODNAT ORDER BY i.bdORDEM), ';
      wSQL = wSQL||                   'MOV.BDCHAVE ';
      wSQL = wSQL||             'FROM ( ';
      wSQL = wSQL||                   'SELECT * ';
      wSQL = wSQL||                   'FROM ( ';
      wSQL = wSQL||                          'SELECT x.BDCODEMP, x.BDCHAVE, x.BDREFLAN, x.BDCODTER, COALESCE(x.BDTIPLAN,0) AS BDTIPLAN, x.BDCODSITNF, x.BDDATAEMISSAO ';
      wSQL = wSQL||                          'FROM VEF_EMP_TMOVSAI x ';
      wSQL = wSQL||                          'WHERE x.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                         ') aux ';
      wSQL = wSQL||                   'WHERE aux.BDCODSITNF not in (2,3,4,5) '; -- Alt.: 16516 - Ajustes para nÃ£o exportar documentos cancelados...
      IF (NOT((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0))) THEN -- Alt.: #240524 - Deve ignorar nas SCPs, pois pode ter uma configuracao diferente nas empresas...
        wSQL = wSQL||                   'AND ((SELECT first 1 BDTIPOAPURACAORET FROM VEF_BASE_TEMPPARGER e WHERE e.BDCODEMP = aux.BDCODEMP AND e.BDREFEMP <= aux.BDREFLAN ORDER BY BDCODEMP desc, BDREFEMP desc) = 1) ';
      wSQL = wSQL||                 ') mov ';
      wSQL = wSQL||            'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||            'JOIN VEF_EMP_TMOVSAIRET ret on (mov.BDCODEMP = ret.BDCODEMP AND mov.BDCHAVE = ret.BDCHAVE) ';
      wSQL = wSQL||            'JOIN VEF_EMP_TMOVSAIPAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
      wSQL = wSQL||            'JOIN VEF_EMP_TMOVSAIPARPGTO pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
      wSQL = wSQL||            'WHERE (CAST(SUBSTRING(pgto.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(pgto.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ';
      --wSQL = wSQL||              'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - Não levar no faturamento caso o tipo seja "Desconto"
      wSQL = wSQL||              'AND pgto.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
      wSQL = wSQL||              'GROUP BY MOV.BDCODEMP,EMP.BDCODMATRIZ,MOV.BDCODTER,MOV.BDTIPLAN,PGTO.BDDATAPGTOPAR,RET.BDCODIND_NAT_RET,RET.BDTIPONATREC,RET.BDCODRECPIS,RET.BDCODRECCOFINS,pgto.bdCODNAT,MOV.BDCHAVE ';
    END

  wSQL = wSQL||    ') aux ';
  wSQL = wSQL||'JOIN TEMPRESAS emp on (aux.BDCODEMP = emp.BDCODEMP) ';
  wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TIND_NAT_RET nat on (nat.BDCODIND_NAT_RET = aux.BDCODIND_NAT_RET) ';
  wSQL = wSQL||'LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES ter ON (ter.BDCODTER = aux.BDCODTER) ';
  wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = AUX.BDCODEMP AND SCP.BDCODSCP = AUX.BDCODSCP AND SCP.BDREFEMP = AUX.BDREFSOC)';
  wSQL = wSQL||'WHERE (nat.BDREGEXP in (''01'',''02'',''03'',''04'',''05'',''99'')) ';
  wSQL = wSQL||' AND (CHAR_LENGTH(ter.BDCGCTER) >= 18) ';
  
  IF (:wINDNATPJ IN (1,4)) THEN
    wSQL = wSQL||        ' AND NOT (AUX.BDINDICADOR = 1 AND AUX.BDCODIND_NAT_RET <> 4) ';
  --wSQL = wSQL||'ORDER BY aux.BDCODMATRIZ, aux.BDCODEMP ';

  wSQL = wSQL||') GYATT ';

  if ((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0)) then
    wSQL = wSQL||' where coalesce(GYATT.BDCODEMPSCP, 0) = '||:PRCODEMP;
  else
  if (:PRAJUSTESCP = 'TRUE') then
    wSQL = wSQL||' where coalesce(GYATT.BDCODEMPSCP, 0) = 0 ';

  EXECUTE STATEMENT ( wSQL );

  -- REGISTRO F600: CONTRIBUIÇÃO RETIDA NA FONTE
  INSERT INTO VEF_EMP_TBLOCOMF600 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODREC, BDCODIND_NAT_RET, BDDT_RET, BDVL_BC_RET, BDVL_RET, BDCNPJPART, BDNOMEPART, BDVL_RET_PIS, BDVL_RET_COFINS, BDIND_DEC, BDIND_NAT_REC, BDRETIFICADORA)
  SELECT aux.BDCODQUADRO, aux.BDCODPERIODO, iif(aux.bdcodempscp > 0,aux.bdcodempscp,aux.BDCODEMP) BDCODEMP, iif(aux.bdcodempscp > 0,aux.bdcodempscp,aux.BDCODMATRIZ) BDCODMATRIZ, aux.BDREFERENCIA,
          GETORDEMSEQUENCIAL_STR('F600.'||aux.BDCODPERIODO||'.'||aux.BDCODEMP||'.'||aux.BDCODMATRIZ||'.'||AUX.BDCODQUADRO||'.'||aux.BDREFERENCIA||'.'||aux.bdcodempscp, :prCODEMP),
         --(SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOMF600 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = aux.BDCODEMP AND x.BDCODMATRIZ = aux.BDCODMATRIZ AND x.BDCODQUADRO = 48 AND x.BDREFERENCIA = aux.BDREFERENCIA) AS BDCHAVE,
         aux.BDCODREC,
--         CASE
--           WHEN :wINCTRIB in (1,2) THEN aux.BDCODIND_NAT_RET
--           WHEN :wINCTRIB in (3) THEN
             -- Caso seja Incidencia tribitária 3, faz a troca da natureza da retenção...
--             CASE aux.BDCODIND_NAT_RET
--                WHEN 1 -- 01 - Retenção por Órgãos, Autarquias e Fundações Federais
--                  THEN 7  -- 51 - Retenção por Órgãos, Autarquias e Fundações Federais
--                WHEN 2 -- 02 - Retenção por outras Entidades da Administração Pública Federal
--                  THEN 8  -- 52 - Retenção por outras Entidades da Administração Pública Federal
--                WHEN 3 -- 03 - Retenção por Pessoas Jurídicas de Direito Privado
--                  THEN 9  -- 53 - Retenção por Pessoas Jurídicas de Direito Privado
--                WHEN 4 -- 04 - Recolhimento por Sociedade Cooperativa
--                  THEN 10 -- 54 - Recolhimento por Sociedade Cooperativa
--                WHEN 5 -- 05 - Retenção por Fabricante de Máquinas e Veículos
--                  THEN 11 -- 55 - Retenção por Fabricante de Máquinas e Veículos
--                WHEN 6 -- 99 - Outras Retenções - Rendimentos sujeitos à regra geral de incidência (não cumulativa ou cumulativa)
--                  THEN 12 -- 59 - Outras Retenções - Rendimentos sujeitos à regra específica de incidência cumulativa (art. 8º da Lei nº 10.637/2002 e art. 10 da Lei nº 10.833/2003)
--             end
--         end as BDCODIND_NAT_RET,
         aux.BDCODIND_NAT_RET,
         aux.BDDT_RET,
         SUM(aux.BDVL_BC_RET) AS BDVL_BC_RET, SUM(aux.BDVL_RET) AS BDVL_RET,
         ter.BDCGCTER AS BDCNPJPART, ter.BDNOME AS BDNOMEPART,
         SUM(aux.BDVL_RET_PIS) AS BDVL_RET_PIS, SUM(aux.BDVL_RET_COFINS) AS BDVL_RET_COFINS,
         aux.BDIND_DEC, aux.BDCOD_NAT_REC AS BDIND_NAT_REC, :PRRETIFICADORA
  FROM (-- PIS
        SELECT 48 AS BDCODQUADRO, 7 AS BDCODPERIODO,
               tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODTER, tmp.BDCODRECPIS AS BDCODREC, tmp.BDCODIND_NAT_RET, tmp.BDDATAEMISSAO AS BDDT_RET,
               tmp.BDVLRCONTAB AS BDVL_BC_RET, tmp.BDVLRPISRET AS BDVL_RET, tmp.BDVLRPISRET AS BDVL_RET_PIS, 0 AS BDVL_RET_COFINS, tmp.BDIND_DEC, tmp.BDCOD_NAT_REC, tmp.BDCODEMPSCP
        FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp
        WHERE tmp.BDCODRECPIS IS NOT NULL
          AND tmp.BDVLRPISRET IS NOT NULL
          AND tmp.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)
          AND tmp.BDREFERENCIA = :prREFERENCIA
        UNION ALL
        -- COFINS
        SELECT 48 AS BDCODQUADRO, 7 AS BDCODPERIODO,
               tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODTER, tmp.BDCODRECCOFINS AS BDCODREC, tmp.BDCODIND_NAT_RET, tmp.BDDATAEMISSAO AS BDDT_RET,
               IIF((tmp.BDCODRECPIS = tmp.BDCODRECCOFINS), 0, tmp.BDVLRCONTAB) AS BDVL_BC_RET, -- Caso seja mesmo código de receita, já trouxe o valor no PIS, daí não soma novamente aqui...
               tmp.BDVLRCOFINSRET AS BDVL_RET, 0 AS BDVL_RET_PIS, tmp.BDVLRCOFINSRET AS BDVL_RET_COFINS, tmp.BDIND_DEC, tmp.BDCOD_NAT_REC, tmp.BDCODEMPSCP
        FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp
        WHERE tmp.BDCODRECCOFINS IS NOT NULL
          AND tmp.BDVLRCOFINSRET IS NOT NULL
          AND tmp.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)
          AND tmp.BDREFERENCIA = :prREFERENCIA
        ) aux
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES ter ON (ter.BDCODTER = aux.BDCODTER)
  WHERE aux.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)
    AND aux.BDREFERENCIA = :prREFERENCIA
    AND ((aux.BDVL_RET_PIS > 0) or (aux.BDVL_RET_COFINS > 0)) --Larissa - 02/2021 - Quando valores de Pis e Cofins fossem zerados ainda retornava registro do F600 - Bloco M - Sped Contribuições - F600 notas sem valor de retenção #135125 
    AND (((iif(:PRAJUSTESCP = true and :PRCODEMPSO > 0, true, false) = true) and (coalesce(AUX.BDCODEMPSCP, 0) = :PRCODEMP)) or
         ((iif(:PRAJUSTESCP = true and :PRCODEMPSO = 0, true, false) = true) and (coalesce(AUX.BDCODEMPSCP, 0) = 0)) or (:PRAJUSTESCP = false))
  GROUP BY aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCODREC,
           aux.BDCODIND_NAT_RET, aux.BDDT_RET, aux.BDIND_DEC, aux.BDCOD_NAT_REC, ter.BDCGCTER, ter.BDNOME, aux.BDCODEMPSCP;

  /* Saldos de retenções de períodos anteriores */
  --IF (:wRETPISCOFPERANT = 'TRUE') THEN -- Verifica o parâmetro "Aproveitar AS retenções de PIS e Cofins de períodos anteriores", caso não esteja habilita, apenas busca a retenção atual...
    --BEGIN
      -- REGISTRO 1300: CONTROLE DOS VALORES RETIDOS NA FONTE - PIS/PASEP
      -- REGISTRO 1700: CONTROLE DOS VALORES RETIDOS NA FONTE - COFINS
      INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDPR_REC_RET, BDVL_RET_APU, BDVL_RET_DED, BDVL_RET_PER, BDVL_RET_DCOMP, BDSLD_RET, BDRETIFICADORA)
      SELECT ant.BDCODQUADRO, ant.BDCODPERIODO, ant.BDCODEMP, ant.BDCODMATRIZ, :prREFERENCIA as BDREFERENCIA,
             GETORDEMSEQUENCIAL_STR('1300.'||ant.BDCODPERIODO||'.'||ant.BDCODEMP||'.'||ant.BDCODMATRIZ||'.'||ant.BDCODQUADRO||'.'||:prREFERENCIA, :prCODEMP),
--             (SELECT COALESCE(MAX(x.BDCHAVE)+1, 1)
--              FROM VEF_EMP_TBLOCOM1300_1700 x
--              WHERE x.BDCODPERIODO = ant.BDCODPERIODO
--                AND x.BDCODEMP = ant.BDCODEMP
--                AND x.BDCODMATRIZ = ant.BDCODMATRIZ
--                AND x.BDCODQUADRO = ant.BDCODQUADRO
--                AND x.BDREFERENCIA = :prREFERENCIA ) AS BDCHAVE,
             ant.BDCODIND_NAT_RET, ant.BDCOD_NAT_REC, ant.BDPR_REC_RET, ant.BDSLD_RET as BDVL_RET_APU, 0 as BDVL_RET_DED, 0 as BDVL_RET_PER, 0 as BDVL_RET_DCOMP, ant.BDSLD_RET as BDSLD_RET,
             :PRRETIFICADORA BDRETIFICADORA
      FROM VEF_EMP_TBLOCOM1300_1700 ant
      WHERE ant.BDSLD_RET > 0
        AND ant.BDCODMATRIZ = :prCODEMP
        AND ant.BDREFERENCIA = (SELECT FIRST 1 x.BDREFERENCIA
                                FROM VEF_EMP_TBLOCOM1300_1700 x
                                WHERE x.BDCODMATRIZ = :prCODEMP
                                  AND x.BDREFERENCIA < :prREFERENCIA
                                  AND x.BDCODPERIODO = 7
                                ORDER BY x.BDREFERENCIA DESC)
        /*AND ANT.BDRETIFICADORA = :PRRETIFICADORA*/; -- Alt.: #180115 - Quando for buscar os saldos, busca todos, pois se a apuração do mês anterior, não tinha uma apuração "retificadora", sempre vinha zerado e se tiver, deve trazer somado...

      --if (:PRAJUSTESCP = 'TRUE') then
        --BEGIN
          --INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDPR_REC_RET, BDVL_RET_APU, BDVL_RET_DED, BDVL_RET_PER, BDVL_RET_DCOMP, BDSLD_RET, BDRETIFICADORA)
          --SELECT ant.BDCODQUADRO, ant.BDCODPERIODO, ant.BDCODEMP, ant.BDCODMATRIZ, :prREFERENCIA as BDREFERENCIA,
          --       GETORDEMSEQUENCIAL_STR('1300.'||ant.BDCODPERIODO||'.'||ant.BDCODEMP||'.'||ant.BDCODMATRIZ||'.'||ant.BDCODQUADRO||'.'||:prREFERENCIA, :prCODEMP),
          --       ant.BDCODIND_NAT_RET, ant.BDCOD_NAT_REC, ant.BDPR_REC_RET, ant.BDSLD_RET as BDVL_RET_APU, 0 as BDVL_RET_DED, 0 as BDVL_RET_PER, 0 as BDVL_RET_DCOMP, ant.BDSLD_RET as BDSLD_RET,
          --       :PRRETIFICADORA BDRETIFICADORA
          --FROM ( SELECT SCP.BDCODEMPSCP
          --       FROM TEMPRESAS_SCP SCP
          --       --WHERE SCP.BDCODEMP = :prCODEMP
          --       WHERE scp.BDCODEMP in(SELECT ex.BDCODEMP
          --                             FROM TEMPRESAS ex
          --                             WHERE ex.BDCODEMP = :prCODEMP
          --                                OR ex.BDCODMATRIZ = :prCODEMP)
          --       ) SCP
          --LEFT OUTER JOIN VEF_EMP_TBLOCOM1300_1700 ant ON(ant.BDCODMATRIZ = SCP.BDCODEMPSCP)
          --WHERE ant.BDSLD_RET > 0
          --  AND ant.BDCODMATRIZ = SCP.BDCODEMPSCP
          --  AND ant.BDREFERENCIA = (SELECT FIRST 1 x.BDREFERENCIA
          --                          FROM VEF_EMP_TBLOCOM1300_1700 x
          --                          WHERE x.BDCODMATRIZ = SCP.BDCODEMPSCP
          --                            AND x.BDREFERENCIA < :prREFERENCIA
          --                            AND x.BDCODPERIODO = 7
          --                          ORDER BY x.BDREFERENCIA DESC)
          --  /*AND ANT.BDRETIFICADORA = :PRRETIFICADORA*/; -- Alt.: #180115 - Quando for buscar os saldos, busca todos, pois se a apuração do mês anterior, não tinha uma apuração "retificadora", sempre vinha zerado e se tiver, deve trazer somado...
  
           -- #211121 - Removido o select anterior, pois estava causando lentidão...
          /*FOR SELECT SCP.BDCODEMPSCP
              FROM TEMPRESAS_SCP SCP
              WHERE scp.BDCODEMP in (SELECT ex.BDCODEMP
                                     FROM TEMPRESAS ex
                                     WHERE ex.BDCODEMP = :prCODEMP
                                        OR ex.BDCODMATRIZ = :prCODEMP)
          INTO :WCODEMPSCP DO
          BEGIN
            INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDPR_REC_RET, BDVL_RET_APU, BDVL_RET_DED, BDVL_RET_PER, BDVL_RET_DCOMP, BDSLD_RET, BDRETIFICADORA)
            SELECT ant.BDCODQUADRO, ant.BDCODPERIODO, ant.BDCODEMP, ant.BDCODMATRIZ, :prREFERENCIA as BDREFERENCIA,
                   GETORDEMSEQUENCIAL_STR('1300.'||ant.BDCODPERIODO||'.'||ant.BDCODEMP||'.'||ant.BDCODMATRIZ||'.'||ant.BDCODQUADRO||'.'||:prREFERENCIA, :prCODEMP),
                   ant.BDCODIND_NAT_RET, ant.BDCOD_NAT_REC, ant.BDPR_REC_RET, ant.BDSLD_RET as BDVL_RET_APU, 0 as BDVL_RET_DED, 0 as BDVL_RET_PER, 0 as BDVL_RET_DCOMP, ant.BDSLD_RET as BDSLD_RET,
                   :PRRETIFICADORA BDRETIFICADORA
            FROM VEF_EMP_TBLOCOM1300_1700 ant
            WHERE ant.BDSLD_RET > 0
              AND ant.BDCODMATRIZ = :WCODEMPSCP
              AND ant.BDREFERENCIA = (SELECT FIRST 1 x.BDREFERENCIA
                                      FROM VEF_EMP_TBLOCOM1300_1700 x
                                      WHERE x.BDCODMATRIZ = :WCODEMPSCP
                                        AND x.BDREFERENCIA < :prREFERENCIA
                                        AND x.BDCODPERIODO = 7
                                      ORDER BY x.BDREFERENCIA DESC)*/
           /*AND ANT.BDRETIFICADORA = :PRRETIFICADORA;*/ -- Alt.: #180115 - Quando for buscar os saldos, busca todos, pois se a apuração do mês anterior, não tinha uma apuração "retificadora", sempre vinha zerado e se tiver, deve trazer somado...
          --END
        --END
    --END

  -- REGISTRO 1300: CONTROLE DOS VALORES RETIDOS NA FONTE - PIS/PASEP
  INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDPR_REC_RET, BDVL_RET_APU, BDVL_RET_DED, BDVL_RET_PER, BDVL_RET_DCOMP, BDSLD_RET, BDRETIFICADORA)
  SELECT 49 AS BDCODQUADRO, 7 AS BDCODPERIODO,iif(tmp.bdcodempscp > 0,tmp.bdcodempscp,tmp.BDCODEMP) BDCODEMP,
          iif(tmp.bdcodempscp > 0,tmp.bdcodempscp,tmp.BDCODMATRIZ) BDCODMATRIZ, tmp.BDREFERENCIA,
--         GETORDEMSEQUENCIAL_STR('1300.'||7/*Periodo*/||'.'||IIF(tmp.bdcodempscp > 0,tmp.bdcodempscp,tmp.BDCODEMP)||'.'||IIF(tmp.bdcodempscp > 0,tmp.bdcodempscp,tmp.BDCODMATRIZ)||'.'||49/*Quadro*/||'.'||tmp.BDREFERENCIA, IIF(tmp.bdcodempscp > 0,tmp.bdcodempscp,tmp.BDCODEMP)),
         GETORDEMSEQUENCIAL_STR('1300.'||7/*Periodo*/||'.'||IIF(tmp.bdcodempscp > 0,tmp.bdcodempscp,tmp.BDCODEMP)||'.'||IIF(tmp.bdcodempscp > 0,tmp.bdcodempscp,tmp.BDCODMATRIZ)||'.'||49/*Quadro*/||'.'||tmp.BDREFERENCIA, :prCODEMP),   
         --(SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM1300_1700 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDCODQUADRO = 49 AND x.BDREFERENCIA = tmp.BDREFERENCIA) AS BDCHAVE,
--         CASE
--           WHEN :wINCTRIB in (1,2) THEN tmp.BDCODIND_NAT_RET
--           WHEN :wINCTRIB in (3) THEN
             -- Caso seja Incidencia tribitária 3, faz a troca da natureza da retenção...
--             CASE tmp.BDCODIND_NAT_RET
--                WHEN 1 -- 01 - Retenção por Órgãos, Autarquias e Fundações Federais
--                  THEN 7  -- 51 - Retenção por Órgãos, Autarquias e Fundações Federais
--                WHEN 2 -- 02 - Retenção por outras Entidades da Administração Pública Federal
--                  THEN 8  -- 52 - Retenção por outras Entidades da Administração Pública Federal
--                WHEN 3 -- 03 - Retenção por Pessoas Jurídicas de Direito Privado
--                  THEN 9  -- 53 - Retenção por Pessoas Jurídicas de Direito Privado
--                WHEN 4 -- 04 - Recolhimento por Sociedade Cooperativa
--                  THEN 10 -- 54 - Recolhimento por Sociedade Cooperativa
--                WHEN 5 -- 05 - Retenção por Fabricante de Máquinas e Veículos
--                  THEN 11 -- 55 - Retenção por Fabricante de Máquinas e Veículos
--                WHEN 6 -- 99 - Outras Retenções - Rendimentos sujeitos à regra geral de incidência (não cumulativa ou cumulativa)
--                  THEN 12 -- 59 - Outras Retenções - Rendimentos sujeitos à regra específica de incidência cumulativa (art. 8º da Lei nº 10.637/2002 e art. 10 da Lei nº 10.833/2003)
--             end
--         end as BDCODIND_NAT_RET,
         tmp.BDCODIND_NAT_RET,
         tmp.BDCOD_NAT_REC,
         --(CAST(SUBSTRING(tmp.BDDATAEMISSAO FROM 1 for 4)||SUBSTRING(tmp.BDDATAEMISSAO FROM 6 for 2) AS INTEGER)) AS BDPR_REC_RET,
         tmp.BDREFAPUSALDO AS BDPR_REC_RET,
         SUM(COALESCE(tmp.BDVLRPISRET, 0)) AS BDVL_RET_APU,
         0 AS BDVL_RET_DED,
         0 AS BDVL_RET_PER, 0 AS BDVL_RET_DCOMP, SUM(COALESCE(tmp.BDVLRPISRET,0)) AS BDSLD_RET,
         :PRRETIFICADORA BDRETIFICADORA
  FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp
  WHERE tmp.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)
    AND tmp.BDREFERENCIA = :prREFERENCIA
    AND tmp.BDVLRPISRET > 0
  GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODIND_NAT_RET, tmp.BDCOD_NAT_REC, tmp.BDDATAEMISSAO, tmp.BDREFAPUSALDO,tmp.BDCODEMPSCP;

  -- REGISTRO 1700: CONTROLE DOS VALORES RETIDOS NA FONTE - COFINS
  INSERT INTO VEF_EMP_TBLOCOM1300_1700 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODIND_NAT_RET, BDCOD_NAT_REC, BDPR_REC_RET, BDVL_RET_APU, BDVL_RET_DED, BDVL_RET_PER, BDVL_RET_DCOMP, BDSLD_RET, BDRETIFICADORA)
  SELECT 50 AS BDCODQUADRO, 7 AS BDCODPERIODO,iif(tmp.bdcodempscp > 0,tmp.bdcodempscp,tmp.BDCODEMP) BDCODEMP,
         iif(tmp.bdcodempscp > 0,tmp.bdcodempscp,tmp.BDCODMATRIZ) BDCODMATRIZ, tmp.BDREFERENCIA,
--         GETORDEMSEQUENCIAL_STR('1300.'||7/*Periodo*/||'.'||IIF(tmp.bdcodempscp > 0,tmp.bdcodempscp,tmp.BDCODEMP)||'.'||IIF(tmp.bdcodempscp > 0,tmp.bdcodempscp,tmp.BDCODMATRIZ)||'.'||50/*Quadro*/||'.'||tmp.BDREFERENCIA, IIF(tmp.bdcodempscp > 0,tmp.bdcodempscp,tmp.BDCODEMP)),
         GETORDEMSEQUENCIAL_STR('1300.'||7/*Periodo*/||'.'||IIF(tmp.bdcodempscp > 0,tmp.bdcodempscp,tmp.BDCODEMP)||'.'||IIF(tmp.bdcodempscp > 0,tmp.bdcodempscp,tmp.BDCODMATRIZ)||'.'||50/*Quadro*/||'.'||tmp.BDREFERENCIA, :prCODEMP),   
         --(SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM1300_1700 x WHERE x.BDCODPERIODO = 7 AND x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDCODQUADRO = 50 AND x.BDREFERENCIA = tmp.BDREFERENCIA) AS BDCHAVE,
--         CASE
--           WHEN :wINCTRIB in (1,2) THEN tmp.BDCODIND_NAT_RET
--           WHEN :wINCTRIB in (3) THEN
             -- Caso seja Incidencia tribitária 3, faz a troca da natureza da retenção...
--             CASE tmp.BDCODIND_NAT_RET
--                WHEN 1 -- 01 - Retenção por Órgãos, Autarquias e Fundações Federais
--                  THEN 7  -- 51 - Retenção por Órgãos, Autarquias e Fundações Federais
--                WHEN 2 -- 02 - Retenção por outras Entidades da Administração Pública Federal
--                  THEN 8  -- 52 - Retenção por outras Entidades da Administração Pública Federal
--                WHEN 3 -- 03 - Retenção por Pessoas Jurídicas de Direito Privado
--                  THEN 9  -- 53 - Retenção por Pessoas Jurídicas de Direito Privado
--                WHEN 4 -- 04 - Recolhimento por Sociedade Cooperativa
--                  THEN 10 -- 54 - Recolhimento por Sociedade Cooperativa
--                WHEN 5 -- 05 - Retenção por Fabricante de Máquinas e Veículos
--                  THEN 11 -- 55 - Retenção por Fabricante de Máquinas e Veículos
--                WHEN 6 -- 99 - Outras Retenções - Rendimentos sujeitos à regra geral de incidência (não cumulativa ou cumulativa)
--                  THEN 12 -- 59 - Outras Retenções - Rendimentos sujeitos à regra específica de incidência cumulativa (art. 8º da Lei nº 10.637/2002 e art. 10 da Lei nº 10.833/2003)
--             end
--         end as BDCODIND_NAT_RET,
         tmp.BDCODIND_NAT_RET,
         tmp.BDCOD_NAT_REC,
         --(CAST(SUBSTRING(tmp.BDDATAEMISSAO FROM 1 for 4)||SUBSTRING(tmp.BDDATAEMISSAO FROM 6 for 2) AS INTEGER)) AS BDPR_REC_RET,
         tmp.BDREFAPUSALDO AS BDPR_REC_RET,
         SUM(COALESCE(tmp.BDVLRCOFINSRET,0)) AS BDVL_RET_APU,
         0 AS BDVL_RET_DED,
         0 AS BDVL_RET_PER, 0 AS BDVL_RET_DCOMP, SUM(COALESCE(tmp.BDVLRCOFINSRET,0)) AS BDSLD_RET,
         :PRRETIFICADORA BDRETIFICADORA
  FROM TMP_VEF_EMP_TBLOCOM_F600_1300 tmp
  WHERE tmp.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)
    AND tmp.BDREFERENCIA = :prREFERENCIA
    AND tmp.BDVLRCOFINSRET > 0
  GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODIND_NAT_RET, tmp.BDCOD_NAT_REC, tmp.BDDATAEMISSAO, tmp.BDREFAPUSALDO,tmp.BDCODEMPSCP;
END
^

create or alter procedure SP_APURACAO_BLOCOM_1100_1500 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PRCODEMPSO integer = 0)
as
declare variable WIFSCP varchar(100);
declare variable WSQL varchar(32750);
declare variable WREFCRED varchar(10);
declare variable WNAOUTILCRED5ANOS DM_BOOLEAN;
BEGIN
  -- Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

--  SELECT BDCREDITOSPERANT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
--  INTO :wCREDITOSPERANT;

  SELECT BDNAOCRED5ANOS FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :WNAOUTILCRED5ANOS;

  if ((:WNAOUTILCRED5ANOS is null) and (:PRCODEMPSO > 0)) then
    begin
      SELECT BDNAOCRED5ANOS FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMPSO
      INTO :WNAOUTILCRED5ANOS;
    end

  if (:WNAOUTILCRED5ANOS = 'TRUE') then
     begin
       WREFCRED = SUBSTRING(prREFERENCIA FROM 5 FOR 2) || '/01/' || SUBSTRING(prREFERENCIA FROM 1 FOR 4);
       WREFCRED = dateadd(-5 YEAR TO CAST(:WREFCRED AS DATE));
       WREFCRED = SUBSTRING(WREFCRED FROM 1 FOR 4) || SUBSTRING(prREFERENCIA FROM 5 FOR 2);
     end

  WIFSCP = ' ';

  if ((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0)) then
     WIFSCP = 'and coalesce(SCP.BDCODEMPSCP, 0) = '||:PRCODEMP||' ';
  else
  if (:PRAJUSTESCP = 'TRUE') then
     WIFSCP = 'and coalesce(SCP.BDCODEMPSCP, 0) = 0 ';

  /* Caso tenha saldos no período anterior a apuração, vai carregar estes valores para a apuração atual */
  wSQL =       'INSERT INTO VEF_EMP_TBLOCOM1100_1500 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCRE_4_3_6, BDTIPOPROD, BDPER_APU_CRED, BDORIG_CRED, BDCNPJ_SUC,BDALIQ, BDVL_CRED_APU, BDVL_CRED_DESC_EFD, BDSLD_CRED_FIM, BDVL_RESSARCIMENTO, BDVL_COMPENSACAO, BDVL_CISAO, BDVL_OUTRAS, BDRETIFICADORA) ';
  wSQL = wSQL||'SELECT aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, ';
  wSQL = wSQL||'GETORDEMSEQUENCIAL_STR(''11001500.''||aux.BDCODPERIODO||''.''||aux.BDCODEMP||''.''||aux.BDCODMATRIZ||''.''||aux.BDCODQUADRO||''.''||aux.BDREFERENCIA, '||:prCODEMP||'),';
  --wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCHAVE+1), 1) FROM VEF_EMP_TBLOCOM1100_1500 x WHERE x.BDCODQUADRO = aux.BDCODQUADRO AND x.BDCODPERIODO = aux.BDCODPERIODO AND x.BDCODEMP = aux.BDCODEMP AND x.BDREFERENCIA = aux.BDREFERENCIA), ';

  wSQL = wSQL||       'aux.BDCODCRE_4_3_6, aux.BDTIPOPROD, aux.BDPER_APU_CRED, aux.BDORIG_CRED, aux.BDCNPJ_SUC, min(aux.BDALIQ), ';
  wSQL = wSQL||       'SUM(COALESCE(aux.BDVL_CRED_APU,0)) as BDVL_CRED_APU, SUM(COALESCE(aux.BDVL_CRED_DESC_EFD,0)) as BDVL_CRED_DESC_EFD, SUM(COALESCE(aux.BDSLD_CRED_FIM,0)) as BDSLD_CRED_FIM, ';
  wSQL = wSQL||       'SUM(COALESCE(aux.BDVL_RESSARCIMENTO,0)) as BDVL_RESSARCIMENTO, SUM(COALESCE(aux.BDVL_COMPENSACAO,0)) as BDVL_COMPENSACAO, SUM(COALESCE(aux.BDVL_CISAO,0)) as BDVL_CISAO, SUM(COALESCE(aux.BDVL_OUTRAS,0)) as BDVL_OUTRAS, ';
  wSQL = wSQL||       :PRRETIFICADORA||' BDRETIFICADORA ';
  wSQL = wSQL||'FROM ( ';
  --IF (:wCREDITOSPERANT = 'TRUE') THEN /* Apenas se estiver configurada a opção "Aproveitar o crédito de PIS e Cofins de períodos anteriores" */
    BEGIN
                         /* Saldos periodos anteriores a apuração */
      wSQL = wSQL||      'SELECT m.BDCODQUADRO, m.BDCODPERIODO, m.BDCODEMP, m.BDCODMATRIZ, '||:prREFERENCIA||' as BDREFERENCIA, m.BDCODCRE_4_3_6, COALESCE(m.BDTIPOPROD,0) BDTIPOPROD, m.BDPER_APU_CRED, m.BDORIG_CRED, ';
      wSQL = wSQL||             'm.BDCNPJ_SUC,m.BDALIQ, m.BDSLD_CRED_FIM AS BDVL_CRED_APU, 0 AS BDVL_CRED_DESC_EFD, m.BDSLD_CRED_FIM, 0 BDVL_RESSARCIMENTO, 0 BDVL_COMPENSACAO, 0 BDVL_CISAO, 0 BDVL_OUTRAS ';
      wSQL = wSQL||      'FROM VEF_EMP_TBLOCOM1100_1500 m ';
      wSQL = wSQL||      'WHERE (m.BDCODMATRIZ = '||:prCODEMP||') ';
      wSQL = wSQL||        'AND (m.BDREFERENCIA = (SELECT FIRST 1 x.BDREFERENCIA ';
      wSQL = wSQL||                               'FROM VEF_EMP_TBLOCOM1100_1500 x ';
      wSQL = wSQL||                               'WHERE x.BDCODMATRIZ = '||:prCODEMP||' ';
      wSQL = wSQL||                                 'AND x.BDREFERENCIA < '||:prREFERENCIA||' ';
      wSQL = wSQL||                                'ORDER BY x.BDREFERENCIA DESC)) ';
      wSQL = wSQL||        'AND m.BDSLD_CRED_FIM > 0 ';
      --wSQL = wSQL||        'AND BDRETIFICADORA = '||:PRRETIFICADORA||' '; -- Alt.: #180115 - Quando for buscar os saldos, busca todos, pois se a apuração do mês anterior, não tinha uma apuração "retificadora", sempre vinha zerado e se tiver, deve trazer somado...
      if (:WNAOUTILCRED5ANOS = 'TRUE') then
        wSQL = wSQL||        'AND M.BDPER_APU_CRED > '||WREFCRED||' ';
      wSQL = wSQL||      'UNION ALL ';

      if (:PRAJUSTESCP = 'TRUE') then
         begin
            wSQL = wSQL||'  select M.BDCODQUADRO, M.BDCODPERIODO, M.BDCODEMP, M.BDCODMATRIZ, '||:prREFERENCIA||' as BDREFERENCIA, M.BDCODCRE_4_3_6, COALESCE(m.BDTIPOPROD,0) BDTIPOPROD, ';
            wSQL = wSQL||'       M.BDPER_APU_CRED, M.BDORIG_CRED, M.BDCNPJ_SUC, M.BDALIQ, M.BDSLD_CRED_FIM as BDVL_CRED_APU, ';
            wSQL = wSQL||'       0 as BDVL_CRED_DESC_EFD, M.BDSLD_CRED_FIM, 0 BDVL_RESSARCIMENTO, 0 BDVL_COMPENSACAO, 0 BDVL_CISAO,0 BDVL_OUTRAS ';
            wSQL = wSQL||'  from VEF_EMP_TBLOCOM1100_1500 M ';
            wSQL = wSQL||'  LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = '||:PRCODEMP||' AND (SCP.BDDATAFINAL IS NULL OR (SELECT bdAAAAMM FROM AAAAMM(SCP.BDDATAFINAL)) >= '||:prREFERENCIA||') AND (SELECT bdAAAAMM FROM AAAAMM(SCP.BDDATAINICIAL)) <= '||:prREFERENCIA||') ';
            wSQL = wSQL||'  where (M.BDCODMATRIZ = SCP.BDCODEMPSCP) and  ';
            wSQL = wSQL||'      (M.BDREFERENCIA = (select first 1 X.BDREFERENCIA ';
            wSQL = wSQL||'                         from VEF_EMP_TBLOCOM1100_1500 X ';
            wSQL = wSQL||'                         where X.BDCODMATRIZ = SCP.BDCODEMPSCP and ';
            wSQL = wSQL||'                               X.BDREFERENCIA < '||:prREFERENCIA||' ';
            wSQL = wSQL||'                         order by X.BDREFERENCIA desc)) and ';
            wSQL = wSQL||'      M.BDSLD_CRED_FIM > 0 ';
            if (:WNAOUTILCRED5ANOS = 'TRUE') then
              wSQL = wSQL||'      AND M.BDPER_APU_CRED > '||WREFCRED||' ';

            wSQL = wSQL||WIFSCP;
            wSQL = wSQL||      'UNION ALL ';
         END
    END
                     /* Saldos de PIS lançados */
  wSQL = wSQL||      'SELECT 52 as BDCODQUADRO, 7 as BDCODPERIODO, ';
  wSQL = wSQL|| IIF(:PRAJUSTESCP = 'TRUE', 'COALESCE(SCP.BDCODEMPSCP,S.BDCODEMP)','S.BDCODEMP')||' BDCODEMP, ';
  wSQL = wSQL|| IIF(:PRAJUSTESCP = 'TRUE', 'COALESCE(SCP.BDCODEMPSCP,coalesce(EMP.BDCODMATRIZ, S.BDCODEMP))' ,'coalesce(EMP.BDCODMATRIZ, S.BDCODEMP)')||' as BDCODMATRIZ, ';
  wSQL = wSQL||             's.BDREFERENCIA, s.BDCODCRE_4_3_6, COALESCE(s.BDTIPOPROD,0) BDTIPOPROD, s.BDREFAPUSALDO as BDPER_APU_CRED, s.BDORIGEMCRED as BDORIG_CRED, ';
  wSQL = wSQL||             's.BDCNPJCEDENTE as BDCNPJ_SUC, 9999 AS bdALIQ, s.BDVLRCREPIS as BDVL_CRED_APU, 0 as BDVL_CRED_DESC_EFD, s.BDVLRCREPIS as BDSLD_CRED_FIM, 0 BDVL_RESSARCIMENTO, 0 BDVL_COMPENSACAO, 0 BDVL_CISAO, 0 BDVL_OUTRAS ';
  wSQL = wSQL||      'FROM VEF_EMP_TSALDOSBLOCOM s ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = S.BDCODEMP AND SCP.BDCODSCP = S.BDCODSCP AND SCP.BDREFEMP = S.BDREFSOC) ';
  wSQL = wSQL||      'WHERE s.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND s.BDREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||        'AND s.BDVLRCREPIS > 0 ';
  wSQL = wSQL||WIFSCP;

  if (:WNAOUTILCRED5ANOS = 'TRUE') then
      wSQL = wSQL||        'AND S.BDREFAPUSALDO > '||WREFCRED;

  wSQL = wSQL||      'UNION ALL ';
                     /* Saldos de Cofins lançados */
  wSQL = wSQL||      'SELECT 53 as BDCODQUADRO, 7 as BDCODPERIODO, ';
  wSQL = wSQL|| IIF(:PRAJUSTESCP = 'TRUE', 'COALESCE(SCP.BDCODEMPSCP,S.BDCODEMP)','S.BDCODEMP')||' BDCODEMP, ';
  wSQL = wSQL|| IIF(:PRAJUSTESCP = 'TRUE', 'COALESCE(SCP.BDCODEMPSCP,coalesce(EMP.BDCODMATRIZ, S.BDCODEMP))' ,'coalesce(EMP.BDCODMATRIZ, S.BDCODEMP)')||' as BDCODMATRIZ, ';
  wSQL = wSQL||             's.BDREFERENCIA, s.BDCODCRE_4_3_6, COALESCE(s.BDTIPOPROD,0) BDTIPOPROD, s.BDREFAPUSALDO as BDPER_APU_CRED, s.BDORIGEMCRED as BDORIG_CRED, ';
  wSQL = wSQL||             's.BDCNPJCEDENTE as BDCNPJ_SUC, 9999 AS bdALIQ, s.BDVLRCRECOFINS as BDVL_CRED_APU, 0 as BDVL_CRED_DESC_EFD, s.BDVLRCRECOFINS as BDSLD_CRED_FIM, 0 BDVL_RESSARCIMENTO, 0 BDVL_COMPENSACAO, 0 BDVL_CISAO, 0 BDVL_OUTRAS ';
  wSQL = wSQL||      'FROM VEF_EMP_TSALDOSBLOCOM s ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = S.BDCODEMP AND SCP.BDCODSCP = S.BDCODSCP AND SCP.BDREFEMP = S.BDREFSOC) ';
  wSQL = wSQL||      'WHERE s.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND s.BDREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||        'AND s.BDVLRCRECOFINS > 0 ';
  wSQL = wSQL||WIFSCP;

  if (:WNAOUTILCRED5ANOS = 'TRUE') then
      wSQL = wSQL||        'AND S.BDREFAPUSALDO > '||WREFCRED;

  wSQL = wSQL||      'UNION ALL ';
                     /* Controle de créditos fiscais PIS */
  wSQL = wSQL||      'SELECT 52 as BDCODQUADRO, 7 as BDCODPERIODO, ';
  wSQL = wSQL|| IIF(:PRAJUSTESCP = 'TRUE', 'COALESCE(SCP.BDCODEMPSCP,S.BDCODEMP)','S.BDCODEMP')||' BDCODEMP, ';
  wSQL = wSQL|| IIF(:PRAJUSTESCP = 'TRUE', 'COALESCE(SCP.BDCODEMPSCP,coalesce(EMP.BDCODMATRIZ, S.BDCODEMP))' ,'coalesce(EMP.BDCODMATRIZ, S.BDCODEMP)')||' as BDCODMATRIZ, ';
  wSQL = wSQL||             's.BDREFERENCIA, s.BDCODCRE_4_3_6, COALESCE(s.BDTIPOPROD,0) BDTIPOPROD, Coalesce(s.BDREFORIGEM, S.BDREFERENCIA) as BDPER_APU_CRED, s.BDORIGEMCRED as BDORIG_CRED, ';
  wSQL = wSQL||             '''  .   .   /    -  '' BDCNPJ_SUC, 9999 AS bdALIQ, 0 as BDVL_CRED_APU, 0 as BDVL_CRED_DESC_EFD, 0 as BDSLD_CRED_FIM, ';
  wSQL = wSQL||             'IIF(S.BDTIPCREDFISCAL = 0,s.BDVLRCREPIS,0) BDVL_RESSARCIMENTO, IIF(S.BDTIPCREDFISCAL = 1,s.BDVLRCREPIS,0) BDVL_COMPENSACAO, ';
  wSQL = wSQL||             'IIF(S.BDTIPCREDFISCAL = 2,s.BDVLRCREPIS,0) BDVL_CISAO, IIF(S.BDTIPCREDFISCAL = 3,s.BDVLRCREPIS,0) BDVL_OUTRAS ';
  wSQL = wSQL||      'FROM VEF_EMP_TCONTROLE_CREDITO s ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = S.BDCODEMP AND SCP.BDCODSCP = S.BDCODSCP AND SCP.BDREFEMP = S.BDREFSOC) ';
  wSQL = wSQL||      'WHERE s.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND s.BDREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||        'AND s.BDVLRCREPIS > 0 ';
  wSQL = wSQL||WIFSCP;

  wSQL = wSQL||      'UNION ALL ';
                     /* Controle de créditos fiscais COFINS */
  wSQL = wSQL||      'SELECT 53 as BDCODQUADRO, 7 as BDCODPERIODO, ';
  wSQL = wSQL|| IIF(:PRAJUSTESCP = 'TRUE', 'COALESCE(SCP.BDCODEMPSCP,S.BDCODEMP)','S.BDCODEMP')||' BDCODEMP, ';
  wSQL = wSQL|| IIF(:PRAJUSTESCP = 'TRUE', 'COALESCE(SCP.BDCODEMPSCP,coalesce(EMP.BDCODMATRIZ, S.BDCODEMP))' ,'coalesce(EMP.BDCODMATRIZ, S.BDCODEMP)')||' as BDCODMATRIZ, ';
  wSQL = wSQL||             's.BDREFERENCIA, s.BDCODCRE_4_3_6, COALESCE(s.BDTIPOPROD,0) BDTIPOPROD, Coalesce(s.BDREFORIGEM, S.BDREFERENCIA) as BDPER_APU_CRED, s.BDORIGEMCRED as BDORIG_CRED, ';
  wSQL = wSQL||             '''  .   .   /    -  '' as BDCNPJ_SUC, 9999 AS bdALIQ, 0 as BDVL_CRED_APU, 0 as BDVL_CRED_DESC_EFD, 0 as BDSLD_CRED_FIM, ';
  wSQL = wSQL||             'IIF(S.BDTIPCREDFISCAL = 0,s.BDVLRCRECOFINS,0) BDVL_RESSARCIMENTO, IIF(S.BDTIPCREDFISCAL = 1,s.BDVLRCRECOFINS,0) BDVL_COMPENSACAO, ';
  wSQL = wSQL||             'IIF(S.BDTIPCREDFISCAL = 2,s.BDVLRCRECOFINS,0) BDVL_CISAO, IIF(S.BDTIPCREDFISCAL = 3,s.BDVLRCRECOFINS,0) BDVL_OUTRAS ';
  wSQL = wSQL||      'FROM VEF_EMP_TCONTROLE_CREDITO s ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = s.BDCODEMP) ';
  wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = S.BDCODEMP AND SCP.BDCODSCP = S.BDCODSCP AND SCP.BDREFEMP = S.BDREFSOC) ';
  wSQL = wSQL||      'WHERE s.'||TRIM(:prWHEREEMPRESAS)||' ';
  wSQL = wSQL||        'AND s.BDREFERENCIA = '||:prREFERENCIA||' ';
  wSQL = wSQL||        'AND s.BDVLRCRECOFINS > 0 ';
  wSQL = wSQL||WIFSCP;

  wSQL = wSQL||      ') aux ';
  wSQL = wSQL||'GROUP BY aux.BDCODQUADRO, aux.BDCODPERIODO, aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCODCRE_4_3_6, aux.BDTIPOPROD, ';
  wSQL = wSQL||         'aux.BDPER_APU_CRED, aux.BDORIG_CRED, aux.BDCNPJ_SUC ';

  EXECUTE STATEMENT ( wSQL );

END
^

create or alter procedure SP_APURACAO_BLOCOM_M100_M500PAR (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000))
as
declare variable WINCTRIB integer;
declare variable WCODCRIT integer;
declare variable WSQL varchar(32750);
declare variable WSQLPREFIXO varchar(8000);
declare variable WSQLSUFIXO varchar(200);
declare variable WMOD_COMTELE varchar(10);
declare variable WMOD_ENERGAS varchar(10);
declare variable WMOD_TRANSPORTE varchar(30);
declare variable WMOD_PROD varchar(50);
declare variable WMOD_COD_CRED_8 varchar(30);
BEGIN
-- Modelos para lançamento de entrada, faz isso para não carregar dados de movimentos errados.
-- Por exemplo: Não carregar dados dos produtos em notas de transporte, caso tenham produtos lançados...
wMOD_COMTELE = '21,22'; -- Lançamento de serviço de comunicação e telecomunicação D500/^D600 (modelo 21 e 22)
wMOD_ENERGAS = '6,28,29,66'; -- Nota fiscal de conta de energia elétrica, água ou gás (C500)
wMOD_TRANSPORTE = '7,8,9,10,11,26,27,57,67,800'; -- Transporte
-- Concatena todos os modelos anteriores, usar "NOT IN"...
wMOD_PROD = wMOD_COMTELE||','||wMOD_ENERGAS||','||wMOD_TRANSPORTE;
-- Modelos que geram "Tipo de Crédito" com final 8, exportação...
wMOD_COD_CRED_8 = '1,100,4,55,65';

  -- Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  SELECT BDINCTRIB+1, -- Incidência tributária
         BDCODCRIT    -- Critério de escrituração (cumulativo)
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCODCRIT;

  IF ((wINCTRIB IS NOT NULL) AND (wCODCRIT IS NOT NULL)) THEN
    BEGIN
      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN -- Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
        BEGIN
          wSQLPREFIXO =       'INSERT INTO TMP_VEF_EMP_TBLOCOM_M100_M500 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDPREFIXONAT, BDVL_ITEM, BDCODCTA, BDCODCSTPIS, BDBCPIS, BDALIQPIS, BDVLRPIS, BDBCPIS_QUANT, BDALIQPIS_QUANT, BDCODCSTCOF, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDBCCOFINS_QUANT, BDALIQCOFINS_QUANT, BDNAT_BC_CRED, BDCOD_CRED) ';
    
          wSQLPREFIXO = wSQLPREFIXO||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, aux.BDPREFIXONAT, aux.BDVL_ITEM, aux.BDCODCTA, aux.BDCODCSTPIS, aux.BDBCPIS,';
          wSQLPREFIXO = wSQLPREFIXO||       'aux.BDALIQPIS, aux.BDVLRPIS, aux.BDBCPIS_QUANT, aux.BDALIQPIS_QUANT, aux.BDCODCSTCOF, aux.BDBCCOFINS, aux.BDALIQCOFINS, aux.BDVLRCOFINS, aux.BDBCCOFINS_QUANT, aux.BDALIQCOFINS_QUANT, ';
          wSQLPREFIXO = wSQLPREFIXO||       'aux.BDNAT_BC_CRED,';

          wSQLPREFIXO = wSQLPREFIXO||       'Coalesce(aux.BDCOD_CRED,';
          wSQLPREFIXO = wSQLPREFIXO||                '(CASE WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 108 '; -- 108 - Quando é usado CFOP do exterior que seja geradora de crédito.
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Vai gerar o campo 2 do M100 com este código quando: A alíquota de PIS e COFINS da nota for de 1,65 ou 0,65.
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Se a alíquota constante da CFOP na nota for diferente de 1,65 ou 0,65.
    
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 208 '; -- 208 - Quando é usado CFOP do exterior que seja geradora de crédito.
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 201 '; -- 201 - Vai gerar o campo 2 do M100 com este código quando: A alíquota de PIS e COFINS da nota for de 1,65 ou 0,65.
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 202 '; -- 202 - Se a alíquota constante da CFOP na nota for diferente de 1,65 ou 0,65.
     
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7))) THEN 308 '; -- 308 - Quando é usado CFOP do exterior que seja geradora de crédito.
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 301 '; -- 301 - Vai gerar o campo 2 do M100 com este código quando: A alíquota de PIS e COFINS da nota for de 1,65 ou 0,65.
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 302 '; -- 302 - Se a alíquota constante da CFOP na nota for diferente de 1,65 ou 0,65.
     
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da primeira linhar e calcular somente o credito referente a este percentual
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 201 '; -- 201 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Não Tributada no mercado interno
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Tributada no mercado interno
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 202 '; -- 202 - Quando for alíquota diferente da básica. Aqui será aplicado o percentual de rateio da linha da receita bruta não cumulativa - Não Tributada no mercado interno.
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for aliquota diferente da basica. Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Tributada no mercado interno
    
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da primeira linhar e calcular somente o credito referente a este percentual
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 301 '; -- 301 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa – Exportação
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for alíquota básica de PIS (1,65 e 0,65). Aqui será aplicado o percentual de rateio da linha da receita bruta não cumulativa - Tributada no mercado interno do 0111 com relação ao percentual total do 0111.
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 302 '; -- 302 - Quando for aliquota for diferente da basica.  Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa – Exportação
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for alíquota for diferente da  básica. Aqui será aplicado o percentual de rateio da linha da receita bruta não cumulativa - Tributada no mercado interno do 0111 com relação ao percentual total do 0111.
    
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 208 '; -- Quando for CFOP do exterior tributada ver o percentual do 0111 e da segunda linhar e calcular somente o credito referente a este percentual
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(1.65 AS NUMERIC(7,4))))) THEN 201 '; -- 201 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Não Tributada no mercado interno
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(1.65 AS NUMERIC(7,4))))) THEN 202 '; -- 202 - Quando for aliquota diferente da basica. Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Não Tributada no mercado interno
    
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) AND (SUBSTRING(aux.BDPREFIXONAT from 1 for 1) IN (3,7))) THEN 108 '; -- Quando é usado CFOP do exterior que tem crédito. E a empresa usa rateio para este código deve ser verificado o percentual relativo a primeira linha do 0111 com relação a ultima e calcular o montante do crédito da CFOP do exterior com CST 56 para este código.
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(1.65 AS NUMERIC(7,4))))) THEN 101 '; -- 101 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Tributada no mercado interno
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(1.65 AS NUMERIC(7,4))))) THEN 102 '; -- 102 - Quando for aliquota diferente da basica. Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Não Tributada no mercado interno

          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN ((aux.BDCODCSTPIS = 60) OR (aux.BDCODCSTCOF = 60)) THEN 106 '; -- Se a empresa usa rateio então soma-se as tres primeiras linhas do 0111 e depois calcula o crédito da soma desse percentual com relação ao faturamento. Se ela não tem 0111 usa-se o valor total da bc e valor do crédito de PIS .
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN ((aux.BDCODCSTPIS = 61) OR (aux.BDCODCSTCOF = 61)) THEN 206 '; -- Se a empresa usa rateio então soma-se as tres primeiras linhas do 0111 e depois calcula o crédito da soma desse percentual com relação ao faturamento. Se ela não tem 0111 usa-se o valor total da bc e valor do crédito de PIS .
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN ((aux.BDCODCSTPIS = 62) OR (aux.BDCODCSTCOF = 62)) THEN 306 '; -- Se a empresa usa rateio então soma-se as tres primeiras linhas do 0111 e depois calcula o crédito da soma desse percentual com relação ao faturamento. Se ela não tem 0111 usa-se o valor total da bc e valor do crédito de PIS .
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN ((aux.BDCODCSTPIS = 63) OR (aux.BDCODCSTCOF = 63)) THEN 106 '; -- Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Tributada no mercado interno
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN ((aux.BDCODCSTPIS = 64) OR (aux.BDCODCSTCOF = 64)) THEN 106 '; -- Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Tributada no mercado interno
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN ((aux.BDCODCSTPIS = 65) OR (aux.BDCODCSTCOF = 65)) THEN 206 '; -- Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Não Tributada no mercado interno
          wSQLPREFIXO = wSQLPREFIXO||                      'WHEN ((aux.BDCODCSTPIS = 66) OR (aux.BDCODCSTCOF = 66)) THEN 106 '; -- Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Não Tributada no mercado interno

          wSQLPREFIXO = wSQLPREFIXO||                 'else NULL end)';
          wSQLPREFIXO = wSQLPREFIXO||               ') AS BDCOD_CRED ';
          wSQLPREFIXO = wSQLPREFIXO||'FROM ( ';
          
          
          wSQLSUFIXO =                     ') aux ';
          wSQLSUFIXO = wSQLSUFIXO||'WHERE ((aux.BDCODCSTPIS not in (4,6,7,8,9)) or ((aux.BDCODCSTPIS = 5) and ((aux.BDALIQPIS = 0) or (aux.BDALIQCOFINS = 0)))) '; -- CSTs que não geram regitros M100/500...
          
          

          wSQL =       'SELECT ent.BDCODEMP, COALESCE(emp.BDCODMATRIZ, ent.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, movpro.BDCHAVE, movpro.BDORDEM, movpro.BDORDEMPRO, 1 AS BDCODTP, ent.BDMODELO, i.BDPREFIXONAT,';
          wSQL = wSQL||      '(CAST(ROUND(('; -- Alt.: 12468 - Estava multiplicando os valores das parcelas x quantidade de produtos que possuem nos itens, por isso divide o valor das parcelas pela quantidade de produtos nos itens...
          wSQL = wSQL||                   '(IIF(qtdepro.BDQTDEPRO < 1, pgto.bdvalorpgtopar,'; -- Caso não tenha produtos integral
          wSQL = wSQL||                                              '((COALESCE(pgto.bdvalorpgtopar,0)*(( COALESCE(movpro.BDVLRITEM,0)/i.BDVLRCONTAB)))) ))+';
          wSQL = wSQL||                   '(IIF(qtdepro.BDQTDEPRO < 1, ( COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||                                                 'COALESCE(pgto.BDVALORRETINSS,0) ),+';
          wSQL = wSQL||                                             '( ((COALESCE(pgto.BDVALORRETPIS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETCOFINS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETCSLL,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETIRRF,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETISSQN,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) +';
          wSQL = wSQL||                                               '((COALESCE(pgto.BDVALORRETINSS,0)*((COALESCE(movpro.BDVLRITEM,1)/i.BDVLRCONTAB)))) )))';
          wSQL = wSQL||                   ') *100) AS NUMERIC(15,2)) /100) AS BDVL_ITEM,';
          wSQL = wSQL||      'movpro.BDCODCTA, movpro.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||      'movpro.BDCODCSTPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(movpro.BDBCPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||      'movpro.BDALIQPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(movpro.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||      'NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
          wSQL = wSQL||      'movpro.BDCODCSTCOF,';
          wSQL = wSQL||      '(CAST((COALESCE(movpro.BDBCCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||      'movpro.BDALIQCOFINS,';
          wSQL = wSQL||      '(CAST((COALESCE(movpro.BDVLRCOFINS,0.00)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||      'NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
          wSQL = wSQL||'FROM (';
          wSQL = wSQL||      'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
          wSQL = wSQL||      'FROM VEF_EMP_TMOVENT e ';
          wSQL = wSQL||      'WHERE (e.BDCODSITNF not in (2,3,4,5)) ';
          wSQL = wSQL||        'AND (e.BDMODELO not in ('||wMOD_PROD||')) '; -- Modelos que não são produtos...
          wSQL = wSQL||        'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||              'WHERE p.BDCODEMP = e.BDCODEMP AND p.BDREFEMP <= e.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||     ') ent ';
          wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = ent.BDCODEMP) ';
          wSQL = wSQL||'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,CAST(COUNT(aux.BDCHAVE) AS NUMERIC(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVENTPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x on (x.BDCODEMP = ent.BDCODEMP AND x.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVENTPAR par on (par.BDCODEMP = ent.BDCODEMP AND par.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN (SELECT * FROM VEF_EMP_TMOVENTPARPGTO p ';
          wSQL = wSQL||      'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND p.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
          wSQL = wSQL||        'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = ent.BDCODEMP AND i.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, Count(*) AS BDQTDEPRO FROM VEF_EMP_TMOVPROENT p group by p.BDCODEMP, p.BDCHAVE, p.BDORDEM) qtdepro on ';
          wSQL = wSQL||                                             '(qtdepro.BDCODEMP = i.BDCODEMP AND qtdepro.BDCHAVE = i.BDCHAVE AND qtdepro.BDORDEM = i.BDORDEM) ';
          wSQL = wSQL||'JOIN (SELECT p.BDCODEMP, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, p.BDCODCSTCOF, p.BDCODCSTPIS, p.BDCODNATBC, p.BDCODCTA, p.BDALIQPIS, p.BDALIQCOFINS,p.BDVLRITEM, ';
          wSQL = wSQL||             'p.BDBCPIS, p.BDBCCOFINS, p.BDVLRPIS, p.BDVLRCOFINS ';
          wSQL = wSQL||      'FROM VEF_EMP_TMOVPROENT p) movpro on (i.BDCODEMP = movpro.BDCODEMP AND i.BDCHAVE = movpro.BDCHAVE AND i.BDORDEM = movpro.BDORDEM) ';
          wSQL = wSQL||'WHERE ((movpro.BDCODCSTPIS is not null) OR (movpro.BDCODCSTCOF is not null)) ';
          wSQL = wSQL|| 'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - Não levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||'union all ';

          wSQL = wSQL||'SELECT ent.BDCODEMP, ent.BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, ent.BDCHAVE, ent.BDORDEM, ent.BDORDEMPRO, ent.BDCODTP, ent.BDMODELO, i.BDPREFIXONAT,';
          wSQL = wSQL||         '(pgto.BDVALORPGTOPAR+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETPIS,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETCOFINS,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETCSLL,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETIRRF,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETISSQN,0)+';
          wSQL = wSQL||           'COALESCE(pgto.BDVALORRETINSS,0) ) AS BDVL_ITEM,';

          wSQL = wSQL||      'ent.BDCODCTA, ent.BDNAT_BC_CRED, ent.BDCOD_CRED,';
          wSQL = wSQL||      'ent.BDCODCSTPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(ent.BDBCPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||      'ent.BDALIQPIS,';
          wSQL = wSQL||      '(CAST((COALESCE(ent.BDVLRPIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||      'NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
          wSQL = wSQL||      'ent.BDCODCSTCOF,';
          wSQL = wSQL||      '(CAST((COALESCE(ent.BDBCCOFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100.00)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||      'ent.BDALIQCOFINS,';
          wSQL = wSQL||      '(CAST((COALESCE(ent.BDVLRCOFINS,0.00)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0.00)*100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||      'NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
          wSQL = wSQL||'FROM (';
                             /* Entradas - Serviço de comunicação e telecomunicação (D500) */
          wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 11 AS BDCODTP, mov.BDMODELO, null AS BDPREFIXONAT,';
          wSQL = wSQL||             'd500.BDVLRSER AS BDVL_ITEM, d500.BDCODCTA, d500.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||             'd500.BDCODCSTPIS, d500.BDVL_BC_PIS AS BDBCPIS, d500.BDALIQ_PIS AS BDALIQPIS, d500.BDVLRPIS,';
          wSQL = wSQL||             'd500.BDCODCSTCOF, d500.BDVL_BC_COF AS BDBCCOFINS, d500.BDALIQ_COF AS BDALIQCOFINS, d500.BDVLRCOFINS ';
          wSQL = wSQL||      'FROM (';
          wSQL = wSQL||            'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
          wSQL = wSQL||            'FROM VEF_EMP_TMOVENT e ';
          wSQL = wSQL||            'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
          wSQL = wSQL||              'AND (e.BDMODELO in ('||wMOD_COMTELE||' )) '; -- Serviço de comunicação e telecomunicação
          wSQL = wSQL||              'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||              'AND e.BDREFLAN = '||:prREFERENCIA||' ';
          wSQL = wSQL||              'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                    'WHERE p.BDCODEMP = e.BDCODEMP AND p.BDREFEMP <= e.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TD500ENT d500 on (d500.BDCODEMP = mov.BDCODEMP AND d500.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||      'WHERE d500.BDCHAVE is not null ';
          wSQL = wSQL||                'AND exists(select * ';
          wSQL = wSQL||                           'from VEF_EMP_TMOVENTITENS SI ';
          wSQL = wSQL||                           'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
          wSQL = wSQL||                           'where SI.BDCODEMP = d500.BDCODEMP and ';
          wSQL = wSQL||                           'SI.BDCHAVE = d500.BDCHAVE)';
      
          wSQL = wSQL||      'union all ';
                             /* Entradas - Nota fiscal de conta de energia elétrica, água ou gás (C500) */
          wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 12 AS BDCODTP, mov.BDMODELO, null AS BDPREFIXONAT,';
          wSQL = wSQL||             'c500.BDVLRCONSFOR AS BDVL_ITEM, NULL AS BDCODCTA, c500.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||             'c500.BDCODCSTPIS, c500.BDVL_BC_PIS AS BDBCPIS, c500.BDALIQ_PIS AS BDALIQPIS, c500.BDVLRPIS,';
          wSQL = wSQL||             'c500.BDCODCSTCOF, c500.BDVL_BC_COF AS BDBCCOFINS, c500.BDALIQ_COF AS BDALIQCOFINS, c500.BDVLRCOFINS ';
          wSQL = wSQL||      'FROM ( ';
          wSQL = wSQL||            'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
          wSQL = wSQL||            'FROM VEF_EMP_TMOVENT e ';
          wSQL = wSQL||            'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
          wSQL = wSQL||              'AND (e.BDMODELO in ('||wMOD_ENERGAS||')) '; -- Nota fiscal de conta de energia elétrica, água ou gás
          wSQL = wSQL||              'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||              'AND e.BDREFLAN = '||:prREFERENCIA||' ';
          wSQL = wSQL||             'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                   'WHERE p.BDCODEMP = e.BDCODEMP AND p.BDREFEMP <= e.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TC500ENT c500 on (c500.BDCODEMP = mov.BDCODEMP AND c500.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||      'WHERE c500.BDCHAVE is not null ';
          wSQL = wSQL||                'AND exists(select * ';
          wSQL = wSQL||                           'from VEF_EMP_TMOVENTITENS SI ';
          wSQL = wSQL||                           'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
          wSQL = wSQL||                           'where SI.BDCODEMP = c500.BDCODEMP and ';
          wSQL = wSQL||                           'SI.BDCHAVE = c500.BDCHAVE)';
          wSQL = wSQL||      'union all ';
                             /* Entradas - Transporte (D100) */
          wSQL = wSQL||      'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 10 AS BDCODTP, mov.BDMODELO, null AS BDPREFIXONAT,';
          wSQL = wSQL||             'd100.BDVLR_FCP_UF_DEST AS BDVL_ITEM, d100.BDCODCTA, d100.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||             'd100.BDCODCSTPIS, d100.BDVL_BC_PIS AS BDBCPIS, d100.BDALIQ_PIS AS BDALIQPIS, d100.BDVLRPIS,';
          wSQL = wSQL||             'd100.BDCODCSTCOF, d100.BDVL_BC_COF AS BDBCCOFINS, d100.BDALIQ_COF AS BDALIQCOFINS, d100.BDVLRCOFINS ';
          wSQL = wSQL||      'FROM ( ';
          wSQL = wSQL||            'SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO ';
          wSQL = wSQL||            'FROM VEF_EMP_TMOVENT e ';
          wSQL = wSQL||            'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; -- Notas canceladas...
          wSQL = wSQL||              'AND (e.BDMODELO in ('||wMOD_TRANSPORTE||')) '; -- Transporte
          wSQL = wSQL||              'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||              'AND e.BDREFLAN = '||:prREFERENCIA||' ';
          wSQL = wSQL||             'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER p ';
          wSQL = wSQL||                   'WHERE p.BDCODEMP = e.BDCODEMP AND p.BDREFEMP <= e.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||            ') mov ';
          wSQL = wSQL||      'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||      'LEFT OUTER JOIN VEF_EMP_TD100ENT d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
          wSQL = wSQL||      'WHERE d100.BDCHAVE is not null ';
          wSQL = wSQL||                'AND exists(select * ';
          wSQL = wSQL||                           'from VEF_EMP_TMOVENTITENS SI ';
          wSQL = wSQL||                           'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
          wSQL = wSQL||                           'where SI.BDCODEMP = d100.BDCODEMP and ';
          wSQL = wSQL||                           'SI.BDCHAVE = d100.BDCHAVE)';

          wSQL = wSQL||    ') ent ';
          wSQL = wSQL||'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,CAST(COUNT(aux.BDCHAVE) AS NUMERIC(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVENTPAR aux group by aux.BDCODEMP,aux.BDCHAVE) x on (x.BDCODEMP = ent.BDCODEMP AND x.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVENTPAR par on (par.BDCODEMP = ent.BDCODEMP AND par.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN (SELECT * FROM VEF_EMP_TMOVENTPARPGTO p ';
          wSQL = wSQL||      'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND p.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
          wSQL = wSQL||        'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||') ) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = ent.BDCODEMP AND i.BDCHAVE = ent.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_BASE_TNATOP nat on (nat.BDCODNAT = i.BDCODNAT AND ((nat.BDNAOEXPEFDCONT is null) OR (TRIM(upper(nat.BDNAOEXPEFDCONT)) <> TRIM(''TRUE''))) ) ';
          wSQL = wSQL||'WHERE ((ent.BDCODCSTPIS is not null) OR (ent.BDCODCSTCOF is not null)) ';
          wSQL = wSQL|| 'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - Não levar no faturamento caso o tipo seja "Desconto"

          EXECUTE STATEMENT ( wSQLPREFIXO || wSQL || wSQLSUFIXO );

          wSQL =     'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, a170.BDCHAVE, a170.BDORDEM, a170.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, NULL as BDMODELO, i.BDPREFIXONAT,';
--          wSQL = wSQL||      '(pgto.BDVALORPGTOPAR+(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||      'PGTO.BDVALORPGTOPAR BDVL_ITEM,';
          wSQL = wSQL||      'NULL AS BDCODCTA, a170.BDNAT_BC_CRED, NULL AS BDCOD_CRED,';
          wSQL = wSQL||      'a170.BDCODCSTPIS,';
          wSQL = wSQL||      'CAST((PGTO.BDVALORPGTOPAR * COALESCE(A170.BDVL_BC_PIS, 0)) / MOV.BDVALORNOTA AS DM_NUMERIC_15_2) BDBCPIS, ';
          wSQL = wSQL||      'a170.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||      'CAST((PGTO.BDVALORPGTOPAR * COALESCE(A170.BDVL_PIS, 0)) / MOV.BDVALORNOTA AS DM_NUMERIC_15_2) BDVLRPIS, ';
          wSQL = wSQL||      'NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
          wSQL = wSQL||      'a170.BDCODCSTCOF,';
          wSQL = wSQL||      'CAST((PGTO.BDVALORPGTOPAR * COALESCE(A170.BDVL_BC_COFINS, 0)) / MOV.BDVALORNOTA AS DM_NUMERIC_15_2) BDBCCOFINS, ';
          wSQL = wSQL||      'a170.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||      'CAST((PGTO.BDVALORPGTOPAR * COALESCE(A170.BDVL_COFINS, 0)) / MOV.BDVALORNOTA AS DM_NUMERIC_15_2) BDVLRCOFINS, ';
          wSQL = wSQL||      'NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
          wSQL = wSQL||'FROM (';
          wSQL = wSQL||      'SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, s.BDCODSITNF, S.BDVALORNOTA ';
          wSQL = wSQL||      'FROM VEF_EMP_TMOVSER s ';
          wSQL = wSQL||      'WHERE (s.BDCODSITNF not in (2,3,4,5)) ';
          IF (wINCTRIB = 2) THEN
            wSQL = wSQL||        'AND (s.BDTIPLAN = 0) ';
          wSQL = wSQL||        'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||              'WHERE e.BDCODEMP = s.BDCODEMP AND e.BDREFEMP <= s.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||        'AND EXISTS(SELECT * '; -- Alt.: #88586 - Ajustes para não exportar lançamentos quando tenham alguma CFOP com a opção "Não levar Sped Contribuições"
          wSQL = wSQL||                   'FROM VEF_EMP_TMOVSERITENS si ';
          wSQL = wSQL||                   'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = si.bdCODNAT AND ((nat.bdNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.bdNAOEXPEFDCONT)) = TRIM(''FALSE''))) ) ';
          wSQL = wSQL||                   'WHERE si.bdCODEMP = s.bdCODEMP ';
          wSQL = wSQL||                     'AND si.bdCHAVE  = s.bdCHAVE) ';
          wSQL = wSQL||     ') mov ';
          wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||'JOIN (';
          wSQL = wSQL||      'SELECT P.BDCODEMP, P.BDCHAVE, P.BDCODTIPOBAIXA, ';
          wSQL = wSQL||             '(SUM(COALESCE(CAST(P.BDVALORPGTOPAR AS DM_NUMERIC_15_2), 0)) + ';
          wSQL = wSQL||              'SUM(COALESCE(P.BDVALORRETPIS, 0)) + ';
          wSQL = wSQL||              'SUM(COALESCE(P.BDVALORRETCOFINS, 0)) + ';
          wSQL = wSQL||              'SUM(COALESCE(P.BDVALORRETCSLL, 0)) + ';
          wSQL = wSQL||              'SUM(COALESCE(P.BDVALORRETIRRF, 0)) + ';
          wSQL = wSQL||              'SUM(COALESCE(P.BDVALORRETISSQN, 0)) + ';
          wSQL = wSQL||              'SUM(COALESCE(P.BDVALORRETINSS, 0))) BDVALORPGTOPAR ';
          wSQL = wSQL||      'FROM VEF_EMP_TMOVSERPARPGTO P ';
          wSQL = wSQL||      'WHERE P.'||TRIM(:PRWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND p.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
          wSQL = wSQL||        'AND (CAST(SUBSTRING(P.BDDATAPGTOPAR FROM 1 FOR 4) || SUBSTRING(P.BDDATAPGTOPAR FROM 6 FOR 2) AS INTEGER) = '||:PRREFERENCIA||') ';
          wSQL = wSQL||        'AND P.BDCODTIPOBAIXA <> 2 ';
          wSQL = wSQL||      'GROUP BY P.BDCODEMP, P.BDCHAVE, P.BDCODTIPOBAIXA ';
          wSQL = wSQL||     ') PGTO ON (PGTO.BDCODEMP = MOV.BDCODEMP AND PGTO.BDCHAVE = MOV.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVSERITENS i on (mov.BDCODEMP = i.BDCODEMP AND mov.BDCHAVE = i.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TA170 a170 on (mov.BDCODEMP = a170.BDCODEMP AND mov.BDCHAVE = a170.BDCHAVE AND i.BDORDEM = a170.BDORDEM) ';
          wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABSITNFISS sit on (mov.BDCODSITNF = sit.BDCODSITNF) ';
          wSQL = wSQL||'WHERE (a170.BDCODCSTCOF is not null) ';
          wSQL = wSQL|| 'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- Sol:16518 - Não levar no faturamento caso o tipo seja "Desconto"

          wSQL = wSQL||'union all ';

          wSQL = wSQL||'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, mov.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT,';
          wSQL = wSQL||       '(pgto.bdvalorpgtopar +(COALESCE(pgto.BDVALORRETPIS,0)+COALESCE(pgto.BDVALORRETCOFINS,0)+COALESCE(pgto.BDVALORRETCSLL,0)+COALESCE(pgto.BDVALORRETIRRF,0)+COALESCE(pgto.BDVALORRETISSQN,0)+COALESCE(pgto.BDVALORRETINSS,0))) AS BDVL_ITEM,';
          wSQL = wSQL||       'NULL AS BDCODCTA, mov.BDNAT_BC_CRED, ';
          wSQL = wSQL||       'CASE WHEN ((mov.BDCODCSTPIS = 60) or (mov.BDCODCSTCOF = 60)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED IN (13,14)) THEN 107 '; -- 1 - Operação no Mercado Interno / 13 - Outras Operações com Direito a Crédito / 14 - Atividade de Transporte de Cargas Subcontratação
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 61) or (mov.BDCODCSTCOF = 61)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED IN (13,14)) THEN 207 '; -- 1 - Operação no Mercado Interno / 13 - Outras Operações com Direito a Crédito / 14 - Atividade de Transporte de Cargas Subcontratação
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 62) or (mov.BDCODCSTCOF = 62)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED IN (13,14)) THEN 307 '; -- 1 - Operação no Mercado Interno / 13 - Outras Operações com Direito a Crédito / 14 - Atividade de Transporte de Cargas Subcontratação
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 63) or (mov.BDCODCSTCOF = 63)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED IN (13,14)) THEN 107 '; -- 1 - Operação no Mercado Interno / 13 - Outras Operações com Direito a Crédito / 14 - Atividade de Transporte de Cargas Subcontratação
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 64) or (mov.BDCODCSTCOF = 64)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED IN (13,14)) THEN 107 '; -- 1 - Operação no Mercado Interno / 13 - Outras Operações com Direito a Crédito / 14 - Atividade de Transporte de Cargas Subcontratação
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 65) or (mov.BDCODCSTCOF = 65)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED IN (13,14)) THEN 207 '; -- 1 - Operação no Mercado Interno / 13 - Outras Operações com Direito a Crédito / 14 - Atividade de Transporte de Cargas Subcontratação
          wSQL = wSQL||            'WHEN ((mov.BDCODCSTPIS = 66) or (mov.BDCODCSTCOF = 66)) AND (mov.BDIND_ORIG_CRED = 1) AND (mov.BDNAT_BC_CRED IN (13,14)) THEN 107 '; -- 1 - Operação no Mercado Interno / 13 - Outras Operações com Direito a Crédito / 14 - Atividade de Transporte de Cargas Subcontratação
          wSQL = wSQL||       'ELSE NULL ';
          wSQL = wSQL||       'END AS BDCOD_CRED,';
          wSQL = wSQL||       'mov.BDCODCSTPIS,';
          wSQL = wSQL||       '(CAST((COALESCE(mov.BDVL_BC_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCPIS,';
          wSQL = wSQL||       'mov.BDALIQ_PIS AS BDALIQPIS,';
          wSQL = wSQL||       '(CAST((COALESCE(mov.BDVLR_PIS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRPIS,';
          wSQL = wSQL||       'NULL as BDBCPIS_QUANT, 0 as BDALIQPIS_QUANT,';
          wSQL = wSQL||       'mov.BDCODCSTCOF,';
          wSQL = wSQL||       '(CAST((COALESCE(mov.BDVL_BC_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDBCCOFINS,';
          wSQL = wSQL||       'mov.BDALIQ_COFINS AS BDALIQCOFINS,';
          wSQL = wSQL||       '(CAST((COALESCE(mov.BDVLR_COFINS,0)/COALESCE(x.BDQTDEPARC,1)) AS NUMERIC(15,2)) * CAST((((COALESCE(pgto.BDVALORPGTOPAR,0) * 100)/COALESCE(par.BDVALORPAR,1))/100) AS NUMERIC(15,8))) AS BDVLRCOFINS, ';
          wSQL = wSQL||       'NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT ';
          wSQL = wSQL||'FROM (';
          wSQL = wSQL||      'SELECT dem.BDCODEMP, dem.BDCHAVE, dem.BDREFLAN, dem.BDCODCSTPIS, dem.BDCODCSTCOF, dem.BDCODNATREC, dem.BDIND_ORIG_CRED, dem.BDNAT_BC_CRED,';
          wSQL = wSQL||             'dem.BDVL_BC_PIS, dem.BDALIQ_PIS, dem.BDVLR_PIS,';
          wSQL = wSQL||             'dem.BDVL_BC_COFINS, dem.BDALIQ_COFINS, dem.BDVLR_COFINS ';
          wSQL = wSQL||      'FROM VEF_EMP_TMOVDEMAISDOC_F100 dem ';
          wSQL = wSQL||              'left outer join VEF_BASE_TCADTIPODEMDOC CAD on (x.BDCODTIPODOC = CAD.BDCODTIPODOC)';
          wSQL = wSQL||      'WHERE ((dem.BDCODCSTPIS is not null) OR (dem.BDCODCSTCOF is not null)) ';
          IF (wINCTRIB = 2) THEN
            wSQL = wSQL||        'AND (dem.BDIND_OPER <> 1) '; -- Operação Representativa de Aquisição...
            wSQL = wSQL||                'AND ((CAD.BDNAOEXPSPED = ''FALSE'') or (CAD.BDNAOEXPSPED is null))';
          wSQL = wSQL||        'AND dem.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND ((SELECT first 1 BDTIPOAPURACAO FROM VEF_BASE_TEMPPARGER e ';
          wSQL = wSQL||             ' WHERE e.BDCODEMP = dem.BDCODEMP AND e.BDREFEMP <= dem.BDREFLAN order by BDCODEMP desc, BDREFEMP desc) = 1) ';
          wSQL = wSQL||     ') mov ';
          wSQL = wSQL||'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
          wSQL = wSQL||'JOIN (SELECT aux.BDCODEMP,aux.BDCHAVE,cast(count(aux.BDCHAVE) AS numeric(15,2)) BDQTDEPARC FROM VEF_EMP_TMOVF100PAR aux group by aux.BDCODEMP,aux.BDCHAVE) X on (mov.BDCODEMP = x.BDCODEMP AND mov.BDCHAVE = x.BDCHAVE) ';
          wSQL = wSQL||'JOIN VEF_EMP_TMOVF100PAR par on (mov.BDCODEMP = par.BDCODEMP AND mov.BDCHAVE = par.BDCHAVE) ';
          wSQL = wSQL||'JOIN (SELECT * FROM VEF_EMP_TMOVF100PARPGTO p ';
          wSQL = wSQL||      'WHERE p.'||TRIM(:prWHEREEMPRESAS)||' ';
          wSQL = wSQL||        'AND p.bdCODTIPOBAIXA = 1 '; -- Alt.: #97533 #92619 #123851 #124179 - Para cálculo do valor proporcional dos impostos, deve apenas considerar as parcelas do tipo "Pagamento/Recebimento"
          wSQL = wSQL||        'AND (CAST(SUBSTRING(p.BDDATAPGTOPAR FROM 1 for 4)||SUBSTRING(p.BDDATAPGTOPAR FROM 6 for 2) AS INTEGER) = '||:prREFERENCIA||')) pgto on (par.BDCODEMP = pgto.BDCODEMP AND par.BDCHAVE = pgto.BDCHAVE AND par.BDORDEMPAR = pgto.BDORDEMPAR) ';
          wSQL = wSQL||'WHERE ((mov.BDCODCSTPIS is not null) OR (mov.BDCODCSTCOF is not null)) ';
          wSQL = wSQL||  'AND (pgto.BDCODTIPOBAIXA <> 2) '; -- sol:16518 - Não levar no faturamento caso o tipo seja "Desconto"

          EXECUTE STATEMENT ( wSQLPREFIXO || wSQL || wSQLSUFIXO );
          
        END
    END

END^

create or alter procedure SP_APURACAO_BLOCOM_M100_M500AUX (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRAJUSTESCP DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
declare variable WINCTRIB integer;
declare variable WCODCRIT integer;
declare variable WSQL varchar(32750);
declare variable WSQLPREFIXO varchar(9000);
declare variable WSQLSUFIXO varchar(300);
declare variable WMOD_COMTELE varchar(10);
declare variable WMOD_ENERGAS varchar(13);
declare variable WMOD_TRANSPORTE varchar(30);
declare variable WMOD_PROD varchar(50);
declare variable WMOD_COD_CRED_8 varchar(30);
declare variable WWHERE_EXTERIOR varchar(200);
BEGIN
  --Modelos para lançamento de entrada, faz isso para não carregar dados de movimentos errados.
  --Por exemplo: Não carregar dados dos produtos em notas de transporte, caso tenham produtos lançados...
  wMOD_COMTELE = '21,22,62'; --Lançamento de serviço de comunicação e telecomunicação D500/^D600 (modelo 21 e 22)
  wMOD_ENERGAS = '6,28,29,66,75'; --Nota fiscal de conta de energia elétrica, água ou gás (C500)
  wMOD_TRANSPORTE = '7,8,9,10,11,26,27,57,67,800'; --Transporte
  wMOD_PROD = wMOD_COMTELE||','||wMOD_ENERGAS||','||wMOD_TRANSPORTE; --Concatena todos os modelos anteriores, usar "NOT IN"...
  wMOD_COD_CRED_8 = '1,100,4,55,65'; --Modelos que geram "Tipo de Crédito" com final 8, exportação...
  
  --Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);
  SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wCODCRIT;

  IF ((:PRCODEMPSO > 0) and ((wINCTRIB is null) or (wCODCRIT is null))) THEN
    begin
      SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMPSO
      INTO :wINCTRIB, :wCODCRIT;
    end
  
  IF ((wINCTRIB IS NOT NULL) AND (wCODCRIT IS NOT NULL)) THEN
    BEGIN
      wSQLPREFIXO = 'INSERT INTO TMP_VEF_EMP_TBLOCOM_M100_M500 (BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODTP, BDPREFIXONAT, BDVL_ITEM, BDCODCTA, BDCODCSTPIS, BDBCPIS, BDALIQPIS, BDVLRPIS, BDBCPIS_QUANT, BDALIQPIS_QUANT, BDCODCSTCOF, BDBCCOFINS, BDALIQCOFINS, BDVLRCOFINS, BDBCCOFINS_QUANT, BDALIQCOFINS_QUANT, BDNAT_BC_CRED, BDCOD_CRED, BDTIPOPROD, BDCODEMPSCP, BDCODNAT,BDDESCTIPODOC,BDDESCPEREXP,BDDESCNATREC,BDDATANOTA, BDNUMDOC, BDCONDPGTO) ';
      wSQLPREFIXO = wSQLPREFIXO||'SELECT aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCHAVE, aux.BDORDEM, aux.BDORDEMPRO, aux.BDCODTP, aux.BDPREFIXONAT, aux.BDVL_ITEM, aux.BDCODCTA, aux.BDCODCSTPIS, aux.BDBCPIS,';
      wSQLPREFIXO = wSQLPREFIXO||       'aux.BDALIQPIS, aux.BDVLRPIS, aux.BDBCPIS_QUANT, aux.BDALIQPIS_QUANT, aux.BDCODCSTCOF, aux.BDBCCOFINS, aux.BDALIQCOFINS, aux.BDVLRCOFINS, aux.BDBCCOFINS_QUANT, aux.BDALIQCOFINS_QUANT, ';
      wSQLPREFIXO = wSQLPREFIXO||       'aux.BDNAT_BC_CRED,';
      wSQLPREFIXO = wSQLPREFIXO||       'Coalesce(aux.BDCOD_CRED,';
  
      wWHERE_EXTERIOR = '((((aux.BDMODELO IS NOT NULL) and (aux.BDMODELO IN ('||wMOD_COD_CRED_8||'))) OR (AUX.BDCODTP IN(3))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) in (3,7)) or (aux.BDIND_ORIG_CRED = 2))';
      
      wSQLPREFIXO = wSQLPREFIXO|| '(CASE WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND '||wWHERE_EXTERIOR||') THEN 108 '; --108 - Quando é usado CFOP do exterior que seja geradora de crédito.
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; --101 - Vai gerar o campo 2 do M100 com este código quando: A alíquota de PIS e COFINS da nota for de 1,65 ou 0,65.
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND (aux.BDPISCOFQTD = ''TRUE'')) THEN 103 ';
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 50) OR (aux.BDCODCSTCOF = 50)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; --102 - Se a alíquota constante da CFOP na nota for diferente de 1,65 ou 0,65.
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND '||wWHERE_EXTERIOR||') THEN 208 '; --208 - Quando é usado CFOP do exterior que seja geradora de crédito.
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 201 '; --201 - Vai gerar o campo 2 do M100 com este código quando: A alíquota de PIS e COFINS da nota for de 1,65 ou 0,65.
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND (aux.BDPISCOFQTD = ''TRUE'')) THEN 203 ';
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 51) OR (aux.BDCODCSTCOF = 51)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 202 '; --202 - Se a alíquota constante da CFOP na nota for diferente de 1,65 ou 0,65.
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND '||wWHERE_EXTERIOR||') THEN 308 '; --308 - Quando é usado CFOP do exterior que seja geradora de crédito.
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 301 '; --301 - Vai gerar o campo 2 do M100 com este código quando: A alíquota de PIS e COFINS da nota for de 1,65 ou 0,65.
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND (aux.BDPISCOFQTD = ''TRUE'')) THEN 303 ';
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 52) OR (aux.BDCODCSTCOF = 52)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 302 '; --302 - Se a alíquota constante da CFOP na nota for diferente de 1,65 ou 0,65.
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND '||wWHERE_EXTERIOR||') THEN 108 '; --Quando for CFOP do exterior tributada ver o percentual do 0111 e da primeira linhar e calcular somente o credito referente a este percentual
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 201 '; --201 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Não Tributada no mercado interno
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; --101 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Tributada no mercado interno
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND (aux.BDPISCOFQTD = ''TRUE'')) THEN 103 ';
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 202 '; --202 - Quando for alíquota diferente da básica. Aqui será aplicado o percentual de rateio da linha da receita bruta não cumulativa - Não Tributada no mercado interno.
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 53) OR (aux.BDCODCSTCOF = 53)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; --102 - Quando for aliquota diferente da basica. Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Tributada no mercado interno
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND '||wWHERE_EXTERIOR||') THEN 108 '; --Quando for CFOP do exterior tributada ver o percentual do 0111 e da primeira linhar e calcular somente o credito referente a este percentual
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 301 '; --301 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Exportação
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) = CAST(1.65 as NUMERIC(7,4))))) THEN 101 '; --101 - Quando for alíquota básica de PIS (1,65 e 0,65). Aqui será aplicado o percentual de rateio da linha da receita bruta não cumulativa - Tributada no mercado interno do 0111 com relação ao percentual total do 0111.
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND (aux.BDPISCOFQTD = ''TRUE'')) THEN 103 ';
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4)))) AND (SubString(aux.BDPREFIXONAT FROM 1 for 1) = ''3'')) THEN 302 '; --302 - Quando for aliquota for diferente da basica.  Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Exportação
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 54) OR (aux.BDCODCSTCOF = 54)) AND ((CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(0.65 as NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS as NUMERIC(7,4)) <> CAST(1.65 as NUMERIC(7,4))))) THEN 102 '; --102 - Quando for alíquota for diferente da  básica. Aqui será aplicado o percentual de rateio da linha da receita bruta não cumulativa - Tributada no mercado interno do 0111 com relação ao percentual total do 0111.
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND '||wWHERE_EXTERIOR||') THEN 208 '; --Quando for CFOP do exterior tributada ver o percentual do 0111 e da segunda linhar e calcular somente o credito referente a este percentual
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(1.65 AS NUMERIC(7,4))))) THEN 201 '; --201 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Não Tributada no mercado interno
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND (aux.BDPISCOFQTD = ''TRUE'')) THEN 203 ';
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 55) OR (aux.BDCODCSTCOF = 55)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(1.65 AS NUMERIC(7,4))))) THEN 202 '; --202 - Quando for aliquota diferente da basica. Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Não Tributada no mercado interno
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND '||wWHERE_EXTERIOR||') THEN 108 '; --Quando é usado CFOP do exterior que tem crédito. E a empresa usa rateio para este código deve ser verificado o percentual relativo a primeira linha do 0111 com relação a ultima e calcular o montante do crédito da CFOP do exterior com CST 56 para este código.
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND (aux.BDPISCOFQTD = ''TRUE'')) THEN 103 ';
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) = CAST(1.65 AS NUMERIC(7,4))))) THEN 101 '; --101 - Quando for aliquota basica de PIS (1,65 e 0,65). Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Tributada no mercado interno
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN (((aux.BDCODCSTPIS = 56) OR (aux.BDCODCSTCOF = 56)) AND ((CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(0.65 AS NUMERIC(7,4))) OR (CAST(aux.BDALIQPIS AS NUMERIC(7,4)) <> CAST(1.65 AS NUMERIC(7,4))))) THEN 102 '; --102 - Quando for aliquota diferente da basica. Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Não Tributada no mercado interno
--#100928 - Movido do select de demais documentos para o padrão, tratando a natureza 14 para todos movimentos
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN ((aux.BDCODCSTPIS = 60) or (aux.BDCODCSTCOF = 60)) AND (aux.BDNAT_BC_CRED IN (14)) THEN 107 '; --1 - Operação no Mercado Interno / 14 - Atividade de Transporte de Cargas Subcontratação
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN ((aux.BDCODCSTPIS = 61) or (aux.BDCODCSTCOF = 61)) AND (aux.BDNAT_BC_CRED IN (14)) THEN 207 '; 
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN ((aux.BDCODCSTPIS = 62) or (aux.BDCODCSTCOF = 62)) AND (aux.BDNAT_BC_CRED IN (14)) THEN 307 '; 
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN ((aux.BDCODCSTPIS = 63) or (aux.BDCODCSTCOF = 63)) AND (aux.BDNAT_BC_CRED IN (14)) THEN 107 '; 
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN ((aux.BDCODCSTPIS = 64) or (aux.BDCODCSTCOF = 64)) AND (aux.BDNAT_BC_CRED IN (14)) THEN 107 '; 
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN ((aux.BDCODCSTPIS = 65) or (aux.BDCODCSTCOF = 65)) AND (aux.BDNAT_BC_CRED IN (14)) THEN 207 '; 
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN ((aux.BDCODCSTPIS = 66) or (aux.BDCODCSTCOF = 66)) AND (aux.BDNAT_BC_CRED IN (14)) THEN 107 '; 
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN ((aux.BDCODCSTPIS = 60) OR (aux.BDCODCSTCOF = 60)) THEN 106 '; --Se a empresa usa rateio então soma-se as tres primeiras linhas do 0111 e depois calcula o crédito da soma desse percentual com relação ao faturamento. Se ela não tem 0111 usa-se o valor total da bc e valor do crédito de PIS.
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN ((aux.BDCODCSTPIS = 61) OR (aux.BDCODCSTCOF = 61)) THEN 206 ';
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN ((aux.BDCODCSTPIS = 62) OR (aux.BDCODCSTCOF = 62)) THEN 306 ';
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN ((aux.BDCODCSTPIS = 63) OR (aux.BDCODCSTCOF = 63)) THEN 106 '; --Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Tributada no mercado interno
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN ((aux.BDCODCSTPIS = 64) OR (aux.BDCODCSTCOF = 64)) THEN 106 ';
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN ((aux.BDCODCSTPIS = 65) OR (aux.BDCODCSTCOF = 65)) THEN 206 '; --Aqui será aplicado o percentual de rateiro da linha da receita bruta não cumulativa - Não Tributada no mercado interno
      wSQLPREFIXO = wSQLPREFIXO||     'WHEN ((aux.BDCODCSTPIS = 66) OR (aux.BDCODCSTCOF = 66)) THEN 106 ';
      wSQLPREFIXO = wSQLPREFIXO||     'else NULL end)';
      wSQLPREFIXO = wSQLPREFIXO|| ') AS BDCOD_CRED, aux.BDTIPOPROD, '||IIF(:PRAJUSTESCP = 'TRUE',' COALESCE(aux.BDCODEMPSCP,0) ',' 0')||' BDCODEMPSCP, BDCODNAT,BDDESCTIPODOC,BDDESCPEREXP,BDDESCNATREC,BDDATANOTA, BDNUMDOC,BDCONDPGTO ';
      wSQLPREFIXO = wSQLPREFIXO||'FROM ( ';
      
      wSQLSUFIXO = ') aux ';
      wSQLSUFIXO = wSQLSUFIXO||'WHERE ((aux.BDCODCSTPIS not in (4,6,7,8,9)) or ((aux.BDCODCSTPIS = 5) and (((aux.BDALIQPIS = 0) and (aux.BDALIQPIS_QUANT = 0)) or ((aux.BDALIQCOFINS = 0) and (aux.BDALIQCOFINS_QUANT = 0))))) '; --CSTs que não geram regitros M100/500...

      if ((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0)) then
        wSQLSUFIXO = wSQLSUFIXO||' and (coalesce(AUX.BDCODEMPSCP, 0) = '||:PRCODEMP||') ';
      else
      if (:PRAJUSTESCP = 'TRUE') then
        wSQLSUFIXO = wSQLSUFIXO||' and (coalesce(AUX.BDCODEMPSCP, 0) = 0) ';

/* Entradas - Produtos */
      wSQL = 'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, p.BDCHAVE, p.BDORDEM, p.BDORDEMPRO, 1 AS BDCODTP, mov.BDMODELO, i.BDPREFIXONAT,';
      wSQL = wSQL|| 'p.BDVLRITEM AS BDVL_ITEM, p.BDCODCTA, p.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED, COALESCE(vinc.bdTIPOPROD,0) bdTIPOPROD,';
      wSQL = wSQL|| 'p.BDCODCSTPIS, IIF(COALESCE(P.BDPISCOFQTD,''FALSE'') = ''TRUE'',NULL,p.BDBCPIS) BDBCPIS, IIF(COALESCE(P.BDPISCOFQTD,''FALSE'') = ''TRUE'',0, p.BDALIQPIS) BDALIQPIS, ';
      wSQL = wSQL|| 'p.BDVLRPIS, IIF(COALESCE(P.BDPISCOFQTD,''FALSE'') = ''TRUE'',p.BDBCPIS,NULL) as BDBCPIS_QUANT, IIF(COALESCE(P.BDPISCOFQTD,''FALSE'') = ''TRUE'',p.BDALIQPIS,NULL) as BDALIQPIS_QUANT, ';
      wSQL = wSQL|| 'p.BDCODCSTCOF, IIF(COALESCE(P.BDPISCOFQTD,''FALSE'') = ''TRUE'',NULL,p.BDBCCOFINS) BDBCCOFINS, IIF(COALESCE(P.BDPISCOFQTD,''FALSE'') = ''TRUE'',0,p.BDALIQCOFINS) BDALIQCOFINS, ';
      WSQL = WSQL|| 'P.BDVLRCOFINS, IIF(COALESCE(P.BDPISCOFQTD,''FALSE'') = ''TRUE'',P.BDBCCOFINS,NULL) BDBCCOFINS_QUANT, IIF(COALESCE(P.BDPISCOFQTD,''FALSE'') = ''TRUE'',P.BDALIQCOFINS,NULL) BDALIQCOFINS_QUANT, 0 BDIND_ORIG_CRED, SCP.BDCODEMPSCP, COALESCE(P.BDPISCOFQTD,''FALSE'') BDPISCOFQTD, I.BDCODNAT, MOV.BDDATAEMISSAO BDDATANOTA, NULL AS BDDESCTIPODOC,NULL AS BDDESCPEREXP,NULL AS BDDESCNATREC, BDNUMDOCINI BDNUMDOC, MOV.BDCONDPGTO ';
      wSQL = wSQL|| 'FROM (SELECT E.BDCODEMP, E.BDCHAVE, E.BDREFLAN, E.BDMODELO, E.BDDATAEMISSAO, E.BDNUMDOCINI, E.BDCONDPGTO ';
      wSQL = wSQL||       'FROM VEF_EMP_TMOVENT e ';
      wSQL = wSQL||       'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; --Notas canceladas...
      wSQL = wSQL||         'AND (e.BDMODELO not in ('||wMOD_PROD||')) '; --Modelos que não são produtos...

      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN --Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
        wSQL = wSQL|| 'AND (e.BDCONDPGTO <> 1) ';

      wSQL = wSQL||         'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||         'AND e.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||         'AND exists(select * ';
      wSQL = wSQL||                    'from VEF_EMP_TMOVENTITENS SI ';
      wSQL = wSQL||                    'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
      wSQL = wSQL||                    'where SI.BDCODEMP = e.BDCODEMP and ';
      wSQL = wSQL||                          'SI.BDCHAVE = e.BDCHAVE)';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVPROENT p on (p.BDCODEMP = i.BDCODEMP AND p.BDCHAVE = i.BDCHAVE AND p.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN TCADPRO_VINC vinc ON(vinc.bdCODEMP = p.bdCODEMP AND vinc.bdCODPROD = p.bdCODPROD) ';
      wSQL = wSQL||       'left outer join TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = I.BDCODEMP AND SCP.BDCODSCP = I.BDCODSCP AND SCP.BDREFEMP = I.BDREFSOC) ';
      wSQL = wSQL||       'WHERE p.BDCODPROD is not null ';
      wSQL = wSQL||         'AND ((p.BDCODCSTPIS is not null) OR (p.BDCODCSTCOF is not null)) ';
      wSQL = wSQL||       'union all ';
/* Entradas - Serviço de comunicação e telecomunicação (D500) */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, d500.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 11 AS BDCODTP, mov.BDMODELO, /*i.*/ 0 BDPREFIXONAT,';
      wSQL = wSQL||              'SUM(IIF(BDVALORNOTA > 0,((D500.BDVLRSER*I.BDVLRCONTAB )/BDVALORNOTA),D500.BDVLRSER)) AS BDVL_ITEM, d500.BDCODCTA, d500.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED, 0 AS BDTIPOPROD,';
      wSQL = wSQL||              'd500.BDCODCSTPIS, SUM(IIF(BDVALORNOTA > 0,((D500.BDVL_BC_PIS*I.BDVLRCONTAB )/BDVALORNOTA),D500.BDVL_BC_PIS)) AS BDBCPIS, d500.BDALIQ_PIS AS BDALIQPIS, SUM(IIF(BDVALORNOTA > 0,((D500.BDVLRPIS*I.BDVLRCONTAB )/BDVALORNOTA),D500.BDVLRPIS)) BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT, ';
      WSQL = WSQL||              'D500.BDCODCSTCOF, SUM(IIF(BDVALORNOTA > 0,((D500.BDVL_BC_COF*I.BDVLRCONTAB )/BDVALORNOTA),D500.BDVL_BC_COF)) AS BDBCCOFINS, D500.BDALIQ_COF AS BDALIQCOFINS, SUM(IIF(BDVALORNOTA > 0,((D500.BDVLRCOFINS*I.BDVLRCONTAB )/BDVALORNOTA),D500.BDVLRCOFINS)) BDVLRCOFINS, NULL AS BDBCCOFINS_QUANT, NULL AS BDALIQCOFINS_QUANT, 0 BDIND_ORIG_CRED,SCP.BDCODEMPSCP, ''FALSE'' BDPISCOFQTD, I.BDCODNAT, MOV.BDDATAEMISSAO BDDATANOTA, NULL AS BDDESCTIPODOC,NULL AS BDDESCPEREXP,NULL AS BDDESCNATREC, BDNUMDOCINI BDNUMDOC, MOV.BDCONDPGTO ';
      wSQL = wSQL||       'FROM (SELECT E.BDCODEMP, E.BDCHAVE, E.BDREFLAN, E.BDMODELO,E.BDVALORNOTA, E.BDDATAEMISSAO, E.BDNUMDOCINI, E.BDCONDPGTO ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVENT e ';
      wSQL = wSQL||             'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; --Notas canceladas...
      wSQL = wSQL||               'AND (e.BDMODELO in ('||wMOD_COMTELE||')) '; --Serviço de comunicação e telecomunicação

      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN --Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
        wSQL = wSQL|| 'AND (e.BDCONDPGTO <> 1) ';

      wSQL = wSQL||               'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||               'AND e.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||               'AND exists(select * ';
      wSQL = wSQL||                           'from VEF_EMP_TMOVENTITENS SI ';
      wSQL = wSQL||                           'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
      wSQL = wSQL||                           'where SI.BDCODEMP = e.BDCODEMP and ';
      wSQL = wSQL||                           'SI.BDCHAVE = e.BDCHAVE)';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = I.BDCODEMP AND SCP.BDCODSCP = I.BDCODSCP AND SCP.BDREFEMP = I.BDREFSOC) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TD500ENT d500 on (d500.BDCODEMP = mov.BDCODEMP AND d500.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'WHERE d500.BDCHAVE is not null ';
      wSQL = wSQL||         'AND ((d500.BDCODCSTPIS is not null) OR (d500.BDCODCSTCOF is not null)) ';
      wSQL = wSQL||         'GROUP BY MOV.BDCODEMP,BDCODMATRIZ, BDREFERENCIA, D500.BDCHAVE,  ';
      wSQL = wSQL||         'BDORDEM, BDORDEMPRO,BDCODTP, MOV.BDMODELO,BDPREFIXONAT,D500.BDCODCTA,BDNAT_BC_CRED,BDCOD_CRED,D500.BDCODCSTPIS,BDALIQPIS, ';
      wSQL = wSQL||         'BDBCPIS_QUANT,BDALIQPIS_QUANT,D500.BDCODCSTCOF,BDALIQCOFINS,BDBCCOFINS_QUANT, BDALIQCOFINS_QUANT,BDIND_ORIG_CRED,BDCODEMPSCP, I.BDCODNAT,  BDDATANOTA, BDNUMDOCINI, MOV.BDCONDPGTO ';
      wSQL = wSQL||       'union all ';
/* Entradas - Nota fiscal de conta de energia elétrica, água ou gás (C500) */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, c500.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 12 AS BDCODTP, mov.BDMODELO, /*i.*/0 BDPREFIXONAT,';
      wSQL = wSQL||              'SUM(IIF(BDVALORNOTA > 0,((C500.BDVLRCONSFOR*I.BDVLRCONTAB )/BDVALORNOTA),C500.BDVLRCONSFOR)) AS BDVL_ITEM, NULL AS BDCODCTA, c500.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED, 0 AS BDTIPOPROD,';
      wSQL = wSQL||              'c500.BDCODCSTPIS, SUM(IIF(BDVALORNOTA > 0,((C500.BDVL_BC_PIS*I.BDVLRCONTAB )/BDVALORNOTA),C500.BDVL_BC_PIS)) AS BDBCPIS, c500.BDALIQ_PIS AS BDALIQPIS, SUM(IIF(BDVALORNOTA > 0,((C500.BDVLRPIS*I.BDVLRCONTAB )/BDVALORNOTA),C500.BDVLRPIS)) BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT, ';
      wSQL = wSQL||              'c500.BDCODCSTCOF, SUM(IIF(BDVALORNOTA > 0,((C500.BDVL_BC_COF*I.BDVLRCONTAB )/BDVALORNOTA),C500.BDVL_BC_COF)) AS BDBCCOFINS, c500.BDALIQ_COF AS BDALIQCOFINS, SUM(IIF(BDVALORNOTA > 0,((C500.BDVLRCOFINS*I.BDVLRCONTAB )/BDVALORNOTA),C500.BDVLRCOFINS)) BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT, 0 BDIND_ORIG_CRED, SCP.BDCODEMPSCP, ''FALSE'' BDPISCOFQTD, I.BDCODNAT, MOV.BDDATAEMISSAO BDDATANOTA, NULL AS BDDESCTIPODOC,NULL AS BDDESCPEREXP,NULL AS BDDESCNATREC, BDNUMDOCINI BDNUMDOC, MOV.BDCONDPGTO ';
      wSQL = wSQL||       'FROM (SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDMODELO, E.BDVALORNOTA, E.BDDATAEMISSAO, E.BDNUMDOCINI, E.BDCONDPGTO ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVENT e ';
      wSQL = wSQL||             'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; --Notas canceladas...
      wSQL = wSQL||               'AND (e.BDMODELO in ('||wMOD_ENERGAS||')) '; --Nota fiscal de conta de energia elétrica, água ou gás

      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN --Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
        wSQL = wSQL|| 'AND (e.BDCONDPGTO <> 1) ';

      wSQL = wSQL||                'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND e.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||                'AND exists(select * ';
      wSQL = wSQL||                           'from VEF_EMP_TMOVENTITENS SI ';
      wSQL = wSQL||                           'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
      wSQL = wSQL||                           'where SI.BDCODEMP = e.BDCODEMP and ';
      wSQL = wSQL||                           'SI.BDCHAVE = e.BDCHAVE)';
      wSQL = wSQL||            ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = I.BDCODEMP AND SCP.BDCODSCP = I.BDCODSCP AND SCP.BDREFEMP = I.BDREFSOC) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TC500ENT c500 on (c500.BDCODEMP = mov.BDCODEMP AND c500.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'WHERE c500.BDCHAVE is not null ';
      wSQL = wSQL||         'AND ((c500.BDCODCSTPIS is not null) OR (c500.BDCODCSTCOF is not null)) ';
      wSQL = wSQL||       'GROUP BY MOV.BDCODEMP,BDCODMATRIZ, BDREFERENCIA, C500.BDCHAVE, ';
      wSQL = wSQL||       'BDORDEM, BDORDEMPRO,BDCODTP, MOV.BDMODELO,BDPREFIXONAT,BDCODCTA,BDNAT_BC_CRED,BDCOD_CRED,C500.BDCODCSTPIS,BDALIQPIS, ';
      wSQL = wSQL||       'BDBCPIS_QUANT,BDALIQPIS_QUANT,C500.BDCODCSTCOF,BDALIQCOFINS,BDBCCOFINS_QUANT, BDALIQCOFINS_QUANT,BDIND_ORIG_CRED,BDCODEMPSCP, I.BDCODNAT,  BDDATANOTA, BDNUMDOCINI, MOV.BDCONDPGTO ';
      wSQL = wSQL||       'union all ';
/*Entrada - Nota Fiscal de conta de energia elética, água ou gás para notas lançadas com o modelo 55 e CFOP de energia Sol: 99928/99929 Camilla M. 18/04/19 */
      wSQL = wSQL|| 'select MOV.BDCODEMP, coalesce(EMP.BDCODMATRIZ, MOV.BDCODEMP) as BDCODMATRIZ,  MOV.BDREFLAN as BDREFERENCIA, MOV.BDCHAVE, ';
      wSQL = wSQL||       'null as BDORDEM, null as BDORDEMPRO, 12 as BDCODTP, MOV.BDMODELO, /*i.*/ 0 BDPREFIXONAT, ';
      wSQL = wSQL||       'PE.bdvlritem as BDVL_ITEM, null as BDCODCTA, PE.bdcodnatbc as BDNAT_BC_CRED, null as BDCOD_CRED, 0 AS BDTIPOPROD, ';
      wSQL = wSQL||       'PE.BDCODCSTPIS, PE.bdbcpis as BDBCPIS, PE.bdaliqpis as BDALIQPIS, PE.BDVLRPIS, null as BDBCPIS_QUANT, null as BDALIQPIS_QUANT, ';
      wSQL = wSQL||       'PE.BDCODCSTCOF, PE.bdbccofins as BDBCCOFINS, PE.bdaliqcofins as BDALIQCOFINS, PE.BDVLRCOFINS, null as BDBCCOFINS_QUANT, null as BDALIQCOFINS_QUANT, 0 BDIND_ORIG_CRED, MOV.BDCODEMPSCP, ''FALSE'' BDPISCOFQTD, mov.bdcodnat, MOV.BDDATAEMISSAO BDDATANOTA, NULL AS BDDESCTIPODOC,NULL AS BDDESCPEREXP,NULL AS BDDESCNATREC, BDNUMDOCINI BDNUMDOC, MOV.BDCONDPGTO ';
      wSQL = wSQL|| 'from( select LAN.BDCODEMP, LAN.BDCHAVE, LAN.BDREFLAN, LAN.BDMODELO, LAN.BDCODEMPSCP, LAN.BDCODNAT, LAN.BDDATAEMISSAO, LAN.BDNUMDOCINI, LAN.BDCONDPGTO ';
      wSQL = wSQL||       'from(select E.BDCODEMP, E.BDREFLAN, E.BDMODELO, I.BDCHAVE, SCP.BDCODEMPSCP, I.BDCODNAT, E.BDDATAEMISSAO, E.BDNUMDOCINI, E.BDCONDPGTO ';
      wSQL = wSQL||            'from VEF_EMP_TMOVENT E ';
      wSQL = wSQL||            'left outer join VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = E.BDCODEMP AND E.BDCHAVE = I.BDCHAVE) ';
      wSQL = wSQL||            'left outer join TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = I.BDCODEMP AND SCP.BDCODSCP = I.BDCODSCP AND SCP.BDREFEMP = I.BDREFSOC) ';
      wSQL = wSQL||            'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = I.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
      wSQL = wSQL||            'where (E.BDCODSITNF not in (2, 3, 4, 5)) '; --Notas canceladas...
      wSQL = wSQL||               'AND E.BDMODELO = 55 ';  --Modelo utilizado para lançar aquisição de energia elétrica em ambiente de contratação livre

      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN --Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
        wSQL = wSQL|| 'AND (e.BDCONDPGTO <> 1) ';

      wSQL = wSQL||       'AND E.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||       'AND E.BDREFLAN = '||:prREFERENCIA||'';
      wSQL = wSQL||       'AND (I.bdprefixonat IN (1251, 1252, 1253, 1254, 1255, 1256, 1257, 1305, 1355, 2251, 2252, 2253, 2254, 2255, 2256, 2257, 2305, 2355, 3251, 3355)) '; --CFOP's de energia
      wSQL = wSQL||            ') LAN ) MOV ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVPROENT PE ON (PE.bdcodemp = MOV.BDCODEMP AND PE.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'WHERE ((pe.BDVLRPIS IS NOT NULL) or (pe.BDVLRCOFINS IS NOT NULL)) ';
      wSQL = wSQL||       'AND ((PE.bdcodcstpis IS NOT NULL) or (PE.bdcodcstcof IS NOT NULL)) ';
      wSQL = wSQL||       'AND pe.bdcodnatbc = 4 ';
      wSQL = wSQL||       'union all ';
/* Entradas - Transporte (D100) */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, d100.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 10 AS BDCODTP, mov.BDMODELO, /*i.*/ 0 BDPREFIXONAT,';
      wSQL = wSQL||              'SUM(I.BDVLRCONTAB) AS BDVL_ITEM, d100.BDCODCTA, d100.BDCODNATBC AS BDNAT_BC_CRED, NULL AS BDCOD_CRED, 0 AS BDTIPOPROD,';
      wSQL = wSQL||              'd100.BDCODCSTPIS, SUM(IIF(BDVALORNOTA > 0,((D100.BDVL_BC_PIS*I.BDVLRCONTAB )/MOV.BDVALORNOTA),D100.BDVL_BC_PIS)) AS BDBCPIS, d100.BDALIQ_PIS AS BDALIQPIS, SUM(IIF(BDVALORNOTA > 0,((D100.BDVLRPIS*I.BDVLRCONTAB )/MOV.BDVALORNOTA),D100.BDVLRPIS)) BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'd100.BDCODCSTCOF, SUM(IIF(BDVALORNOTA > 0,((D100.BDVL_BC_COF*I.BDVLRCONTAB )/MOV.BDVALORNOTA),D100.BDVL_BC_COF)) AS BDBCCOFINS, d100.BDALIQ_COF AS BDALIQCOFINS, SUM(IIF(BDVALORNOTA > 0,((D100.BDVLRCOFINS*I.BDVLRCONTAB )/MOV.BDVALORNOTA),D100.BDVLRCOFINS)) BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT, 0 BDIND_ORIG_CRED, SCP.BDCODEMPSCP, ''FALSE'' BDPISCOFQTD, I.BDCODNAT,MOV.BDDATAEMISSAO BDDATANOTA, NULL AS BDDESCTIPODOC,NULL AS BDDESCPEREXP,NULL AS BDDESCNATREC, BDNUMDOCINI BDNUMDOC, MOV.BDCONDPGTO ';
      wSQL = wSQL||       'FROM (SELECT e.BDCODEMP, e.BDCHAVE, e.BDREFLAN, e.BDVALORNOTA, e.BDMODELO, E.BDDATAEMISSAO, E.BDNUMDOCINI, E.BDCONDPGTO ';
      wSQL = wSQL||             'FROM VEF_EMP_TMOVENT e ';
      wSQL = wSQL||             'WHERE (e.BDCODSITNF not in (2,3,4,5)) '; --Notas canceladas...
      wSQL = wSQL||               'AND (e.BDMODELO in ('||wMOD_TRANSPORTE||')) '; --Transporte

      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN --Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
        wSQL = wSQL||                'AND (e.BDCONDPGTO <> 1) ';

      wSQL = wSQL||                'AND e.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND e.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVENTITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = I.BDCODEMP AND SCP.BDCODSCP = I.BDCODSCP AND SCP.BDREFEMP = I.BDREFSOC) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TD100ENT d100 on (d100.BDCODEMP = mov.BDCODEMP AND d100.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'WHERE d100.BDCHAVE is not null ';
      wSQL = wSQL||                'AND exists(select * ';
      wSQL = wSQL||                           'from VEF_EMP_TMOVENTITENS SI ';
      wSQL = wSQL||                           'join VEF_BASE_TNATOP NAT on (NAT.BDCODNAT = SI.BDCODNAT and ((NAT.BDNAOEXPEFDCONT is null) or (trim(upper(NAT.BDNAOEXPEFDCONT)) = trim(''FALSE'')))) ';
      wSQL = wSQL||                           'where SI.BDCODEMP = d100.BDCODEMP and ';
      wSQL = wSQL||                           'SI.BDCHAVE = d100.BDCHAVE)';
      wSQL = wSQL||         'AND ((d100.BDCODCSTPIS is not null) OR (d100.BDCODCSTCOF is not null)) ';
      wSQL = wSQL||       'GROUP BY MOV.BDCODEMP,BDCODMATRIZ, BDREFERENCIA, D100.BDCHAVE, ';
      wSQL = wSQL||       ' BDORDEM, BDORDEMPRO,BDCODTP, MOV.BDMODELO,BDPREFIXONAT,BDCODCTA,BDNAT_BC_CRED,BDCOD_CRED,D100.BDCODCSTPIS,BDALIQPIS, ';
      wSQL = wSQL||       ' BDBCPIS_QUANT,BDALIQPIS_QUANT,D100.BDCODCSTCOF,BDALIQCOFINS,BDBCCOFINS_QUANT, BDALIQCOFINS_QUANT,BDIND_ORIG_CRED,BDCODEMPSCP, BDDATANOTA, I.BDCODNAT, BDNUMDOCINI, MOV.BDCONDPGTO ';
      EXECUTE STATEMENT ( wSQLPREFIXO || wSQL || wSQLSUFIXO );
/* Demais documentos */
      wSQL = 'SELECT dem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, dem.BDCODEMP) as BDCODMATRIZ, dem.BDREFLAN AS BDREFERENCIA, dem.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 4 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT,';
      wSQL = wSQL|| 'dem.BDVL_OPER AS BDVL_ITEM, NULL AS BDCODCTA, dem.BDNAT_BC_CRED, ';
--#100928 - Movido do select de demais documentos para o padrão, tratando a natureza 14 para todos movimentos
      wSQL = wSQL|| 'CASE WHEN ((dem.BDCODCSTPIS = 60) or (dem.BDCODCSTCOF = 60)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED IN (13)) THEN 107 '; --1 - Operação no Mercado Interno / 13 - Outras Operações com Direito a Crédito
      wSQL = wSQL||      'WHEN ((dem.BDCODCSTPIS = 61) or (dem.BDCODCSTCOF = 61)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED IN (13)) THEN 207 '; 
      wSQL = wSQL||      'WHEN ((dem.BDCODCSTPIS = 62) or (dem.BDCODCSTCOF = 62)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED IN (13)) THEN 307 '; 
      wSQL = wSQL||      'WHEN ((dem.BDCODCSTPIS = 63) or (dem.BDCODCSTCOF = 63)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED IN (13)) THEN 107 '; 
      wSQL = wSQL||      'WHEN ((dem.BDCODCSTPIS = 64) or (dem.BDCODCSTCOF = 64)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED IN (13)) THEN 107 '; 
      wSQL = wSQL||      'WHEN ((dem.BDCODCSTPIS = 65) or (dem.BDCODCSTCOF = 65)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED IN (13)) THEN 207 '; 
      wSQL = wSQL||      'WHEN ((dem.BDCODCSTPIS = 66) or (dem.BDCODCSTCOF = 66)) AND (dem.BDIND_ORIG_CRED = 1) AND (dem.BDNAT_BC_CRED IN (13)) THEN 107 ';
      wSQL = wSQL||      'ELSE NULL ';
      wSQL = wSQL||    'END AS BDCOD_CRED, 0 AS BDTIPOPROD,';
      wSQL = wSQL|| 'dem.BDCODCSTPIS, dem.BDVL_BC_PIS AS BDBCPIS, dem.BDALIQ_PIS AS BDALIQPIS, dem.BDVLR_PIS AS BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL|| 'dem.BDCODCSTCOF, dem.BDVL_BC_COFINS AS BDBCCOFINS, dem.BDALIQ_COFINS AS BDALIQCOFINS, dem.BDVLR_COFINS AS BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT, dem.BDIND_ORIG_CRED, SCP.BDCODEMPSCP, ''FALSE'' BDPISCOFQTD,  NULL AS BDCODNAT, BDDT_OPER AS BDDATANOTA, TIPF100.BDCODTIPODOC || '' - '' || TIPF100.BDDESCRICAO BDDESCTIPODOC, NULL BDDESCPEREXP, NULL BDDESCNATREC, BDNUMDOC, -1 BDCONDPGTO ';
      wSQL = wSQL|| 'FROM  VEF_EMP_TMOVDEMAISDOC_F100 dem ';
      wSQL = wSQL|| 'LEFT OUTER JOIN VEF_BASE_TCADTIPODEMDOC TIPF100 ON (TIPF100.BDCODTIPODOC = DEM.BDCODTIPODOC) ';
      wSQL = wSQL|| 'left outer join VEF_BASE_TCADTIPODEMDOC CAD on (dem.BDCODTIPODOC = CAD.BDCODTIPODOC) ';
      wSQL = wSQL|| 'left outer join TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = dem.BDCODEMP AND SCP.BDCODSCP = dem.BDCODSCP AND SCP.BDREFEMP = dem.BDREFSOC) ';
      wSQL = wSQL|| 'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = dem.BDCODEMP) ';
      wSQL = wSQL|| 'WHERE ((dem.BDCODCSTPIS is not null) OR (dem.BDCODCSTCOF is not null)) ';

      IF (wINCTRIB = 2) THEN
        wSQL = wSQL|| 'AND (dem.BDIND_OPER <> 1) '; --Operação Representativa de Aquisição...

      wSQL = wSQL|| 'AND ((CAD.BDNAOEXPSPED = ''FALSE'') or (CAD.BDNAOEXPSPED is null))';

      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN --Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
        wSQL = wSQL|| 'AND (dem.BDCONDPGTO <> 1) ';

      wSQL = wSQL||           'AND dem.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||         'AND dem.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||       'union all ';

/* Serviços tomados(Recebidos), tipolan = 1 */
      wSQL = wSQL||       'SELECT mov.BDCODEMP, COALESCE(emp.BDCODMATRIZ, mov.BDCODEMP) as BDCODMATRIZ, mov.BDREFLAN AS BDREFERENCIA, a.BDCHAVE, a.BDORDEM, a.BDNUM_ITEM AS BDORDEMPRO, 3 AS BDCODTP, NULL as BDMODELO, i.BDPREFIXONAT,';
      wSQL = wSQL||              'a.BDVL_ITEM, NULL AS BDCODCTA, a.BDNAT_BC_CRED, NULL AS BDCOD_CRED, COALESCE(vinc.bdTIPOPROD,0) bdTIPOPROD,';
      wSQL = wSQL||              'a.BDCODCSTPIS, a.BDVL_BC_PIS AS BDBCPIS, a.BDALIQ_PIS AS BDALIQPIS, a.BDVL_PIS AS BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'a.BDCODCSTCOF, a.BDVL_BC_COFINS AS BDBCCOFINS, a.BDALIQ_COFINS AS BDALIQCOFINS, a.BDVL_COFINS AS BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT, 0 BDIND_ORIG_CRED, SCP.BDCODEMPSCP, ''FALSE'' BDPISCOFQTD, BDCODNAT, BDDATAEMISSAO AS BDDATANOTA, NULL BDDESCTIPODOC, NULL BDDESCPEREXP, NULL BDDESCNATREC, BDNUMDOCINI BDNUMDOC, MOV.BDCONDPGTO ';
      wSQL = wSQL||       'FROM (SELECT s.BDCODEMP, s.BDCHAVE, s.BDREFLAN, S.bddataemissao, S.BDNUMDOCINI, S.BDCONDPGTO ';
      wSQL = wSQL||              'FROM VEF_EMP_TMOVSER s ';
      wSQL = wSQL||              'WHERE (s.BDCODSITNF not in (2,3,4,5)) '; --Notas canceladas...

      IF (wINCTRIB = 2) THEN
        wSQL = wSQL|| 'AND (s.BDTIPLAN = 0) ';

      IF ((wINCTRIB <> 1) AND (wCODCRIT = 1)) THEN --Incidência tributária <> de exclusivamente não-cumulativo e critério de escrituração = Regime de caixa...
        wSQL = wSQL|| 'AND (s.BDCONDPGTO <> 1) ';

      wSQL = wSQL||                'AND s.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND s.BDREFLAN = '||:prREFERENCIA||' ';
      wSQL = wSQL||             ') mov ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = mov.BDCODEMP) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVSERITENS i on (i.BDCODEMP = mov.BDCODEMP AND i.BDCHAVE = mov.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TA170 a on (a.BDCODEMP = i.BDCODEMP AND a.BDCHAVE = i.BDCHAVE AND a.BDORDEM = i.BDORDEM) ';
      wSQL = wSQL||       'LEFT OUTER JOIN TCADPRO_VINC vinc ON (vinc.bdCODEMP = a.bdCODEMP and vinc.bdCODPROD = a.bdCODPROD) ';
      wSQL = wSQL||       ' left outer join TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = i.BDCODEMP AND SCP.BDCODSCP = i.BDCODSCP AND SCP.BDREFEMP = i.BDREFSOC) ';
      wSQL = wSQL||       'WHERE a.BDCODPROD is not null ';
      wSQL = wSQL||         'AND ((a.BDCODCSTPIS is not null) OR (a.BDCODCSTCOF is not null)) ';
      wSQL = wSQL||         'AND EXISTS(SELECT * '; --Alt.: #88586 - Ajustes para não exportar lançamentos quando tenham alguma CFOP com a opção "Não levar Sped Contribuições"
      wSQL = wSQL||                    'FROM VEF_EMP_TMOVSERITENS si ';
      wSQL = wSQL||                    'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = si.bdCODNAT AND ((nat.bdNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.bdNAOEXPEFDCONT)) = TRIM(''FALSE''))) ) ';
      wSQL = wSQL||                    'WHERE si.bdCODEMP = i.bdCODEMP ';
      wSQL = wSQL||                      'AND si.bdCHAVE  = i.bdCHAVE) ';
      wSQL = wSQL||       'union all ';
      wSQL = wSQL||       'SELECT bem.BDCODEMP, COALESCE(emp.BDCODMATRIZ, bem.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA,';
      wSQL = wSQL||               'bem.BDCODBEM AS BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 14 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT,';
--Sol. 22905 Gabriel Ariel (27/02/2018) - Buscar primeiro o valor da depreciacao
      wSQL = wSQL||                'bem.BDVL_ITEM, ';
      wSQL = wSQL||                'bem.BDCODTPLA AS BDCODCTA,';
      wSQL = wSQL||               'CASE bem.BDTIPOAPROCRED ';
      wSQL = wSQL||                 'WHEN 0 THEN ''10'' ';
      wSQL = wSQL||                 'WHEN 1 THEN ''09'' ';
      wSQL = wSQL||                 'WHEN 2 THEN ''11'' ';
      wSQL = wSQL||               'end AS BDNAT_BC_CRED, ';
      wSQL = wSQL||               'case ';
      wSQL = wSQL||                 'when (COALESCE(bem.BDCODPAIS,30) <> 30) then 108';
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 50) or (bem.BDCODCSTCOF = 50)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 103 ';  --Tipo de apropriação: 1 - Valor de aquisição / Numero de parcelas: "5 - 6 Meses (Embalagens de bebidas frias)"
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 51) or (bem.BDCODCSTCOF = 51)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 203 ';  
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 52) or (bem.BDCODCSTCOF = 52)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 303 ';  
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 53) or (bem.BDCODCSTCOF = 53)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 103 ';  
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 54) or (bem.BDCODCSTCOF = 54)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 103 ';  
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 55) or (bem.BDCODCSTCOF = 55)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 203 ';  
      wSQL = wSQL||                 'when (((bem.BDCODCSTPIS = 56) or (bem.BDCODCSTCOF = 56)) and (bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)) then 103 ';
      wSQL = wSQL||               'else null '; --Não levar sempre 101, deve seguir a regra dos demais
      wSQL = wSQL||               'end as BDCOD_CRED, 0 AS BDTIPOPROD, bem.BDCODCSTPIS,';
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, '; --F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM))) as BDBCPIS,';
      wSQL = wSQL||               'IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, bem.BDALIQPIS) AS BDALIQPIS,'; --F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, '; --F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM))) as BDVLRPIS, ';
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), '; --F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM), NULL)) AS BDBCPIS_QUANT, ';
      wSQL = wSQL||               'IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), bem.BDALIQPIS, NULL) AS BDALIQPIS_QUANT,';
      wSQL = wSQL||               'bem.BDCODCSTCOF,';
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, '; --F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM))) AS BDBCCOFINS,';
      wSQL = wSQL||               'IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, bem.BDALIQCOFINS) AS BDALIQCOFINS,'; --F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), NULL, '; --F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM))) as BDVLRCOFINS, ';
      wSQL = wSQL||               '(IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), '; --F130 / 5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                     '(bem.BDVL_ITEM), NULL)) as BDBCCOFINS_QUANT, ';
      wSQL = wSQL||               'IIF(((bem.BDTIPOAPROCRED = 0) and (bem.BDCODNRPARC = 4)), bem.BDALIQCOFINS, NULL) AS BDALIQCOFINS_QUANT, 0 BDIND_ORIG_CRED, SCP.BDCODEMPSCP, ''FALSE'' BDPISCOFQTD, NULL BDCODNAT, BDDATORIAQUIBEM BDDATANOTA, iif((BDCODINDIVIBEM is not null) and (BDCODINDIVIBEM <> ''''), BDCODINDIVIBEM ||'' - ''|| BDNOMBEM, BDNOMBEM) BDDESCTIPODOC, NULL BDDESCPEREXP, NULL BDDESCNATREC, TBEM.BDNRDOCBEM BDNUMDOC, -1 BDCONDPGTO ';
      wSQL = wSQL||       'FROM (SELECT tbem.*, coalesce((select cast(coalesce(PRDEPRECIACAOPERIODO, 0) as numeric(15,2)) PRDEPRECIACAOPERIODO ';
      wSQL = wSQL||             'from SP_CONS_CALC_DEP(tbem.bdCODEMP, TBEM.BDCODBEM, (substring('||:prREFERENCIA||' from 5 for 2) || ''/01/'' || substring('||:prREFERENCIA||' from 1 for 4)), (substring('||:prREFERENCIA||' from 5 for 2) || ''/'' ||(select ULTDIA ';
      wSQL = wSQL||                                                                                                                                                                                                ' from ULTIMO_DIA_MES(cast(substring('||:prREFERENCIA||' from 5 for 2) as integer), cast(substring('||:prREFERENCIA||' from 1 for 4) as integer))) || ''/'' || substring('||:prREFERENCIA||' from 1 for 4)), 0, 0) ';
      wSQL = wSQL||                           'where exists (select dep.bdcodemp from EMPRESAS_TDEPRECIACAO dep where dep.bdcodemp = TBEM.BDCODEMP and dep.bdcodbem = TBEM.BDCODBEM) and TBEM.BDTIPOAPROCRED <> 0), ';
      wSQL = wSQL||               '(case TBEM.BDTIPOAPROCRED ';
      wSQL = wSQL||                  'when 0 then (TBEM.BDBCCALC/COALESCE(case Tbem.BDCODNRPARC '; --F130 não deve abater a exclusão
      wSQL = wSQL||                                                               'when 0 then 1 ';  --1 - Integral
      wSQL = wSQL||                                                               'when 1 then 12 '; --2 - 12 Meses
      wSQL = wSQL||                                                               'when 2 then 24 '; --3 - 24 Meses
      wSQL = wSQL||                                                               'when 3 then 48 '; --4 - 48 Meses
      wSQL = wSQL||                                                               'when 4 then 6 ';  --5 - 6 Meses (Embalagens de bebidas frias)
      wSQL = wSQL||                                                         'when 5 then COALESCE(Tbem.BDNUMPARC, 1) '; --9 - Outra periodicidade definida em Lei. #OBS.: Nesses casos pega o número de parcelas do campo "Quantidade" da aba EFD - PIS/Cofins
      wSQL = wSQL||                                                             'end, 1)) ';
      wSQL = wSQL||                  'else (TBEM.BDBCCALC)-(Tbem.BDEXCBASE/COALESCE(Tbem.BDNUMPARC,1)) '; --F120 deve abater a exclusão
      wSQL = wSQL||                  'end)) as BDVL_ITEM ';
      wSQL = wSQL||              'FROM (SELECT TBEM.*, ';
--Sol. 22905 - Faz a proporcao para o primeiro e ultimo mes, que dependerá dos parâmetros do bem
      wSQL = wSQL||               'CASE WHEN ((BDDEPDIARIA = ''TRUE'') and (TBEM.BDTIPOAPROCRED <> 0)) THEN CASE WHEN ('||:PRREFERENCIA||' = extract(year from BDDTINI) || LPAD(extract(month from BDDTINI),2,''0'')) then cast(cast(TBEM.BDBASECALC * (iif(BDNUMDIAS <= 1, 30, (select ULTDIA  from ULTIMO_DIA_MES(extract(month from BDDTINI), extract(year from BDDTINI)))) - iif((BDNUMDIAS <= 1) and ((extract(day from BDDTINI) ) > 30), 30, (extract(day from BDDTINI) ))) as numeric(15,3)) / iif(BDNUMDIAS <= 1, 30, (select ULTDIA from ULTIMO_DIA_MES(extract(month from BDDTINI), extract(year from BDDTINI)))) as numeric(15,2))';
      wSQL = wSQL||               '                                             WHEN ('||:PRREFERENCIA||' = extract(year from BDDTFIM) || LPAD(extract(month from BDDTFIM),2,''0'')) then cast(cast(TBEM.BDBASECALC * (iif((BDNUMDIAS <= 1) and (extract(day from BDDTFIM) > 30), 30, extract(day from BDDTFIM) )) as numeric(15,3)) / iif(BDNUMDIAS <= 1, 30, (select ULTDIA from ULTIMO_DIA_MES(extract(month from BDDTFIM), extract(year from BDDTFIM)))) as numeric(15,2))';
      wSQL = wSQL||               '                                             ELSE TBEM.BDBASECALC ';
      wSQL = wSQL||               '                                         END ';
      wSQL = wSQL||               '     ELSE TBEM.BDBASECALC ';
      wSQL = wSQL||               'END BDBCCALC ';
      wSQL = wSQL||                'FROM (SELECT TBEM.*, ';
--Sol. 22905 - Pega a data da primeira e ultima parcela, para verificar se o bem está no primeiro ou último mês, onde o cálculo é diferente
      wSQL = wSQL||                    'dateadd(iif(TBEM.BDDEPDIADATA = 2, 0, -1) day to (CASE ';
      wSQL = wSQL||                                      'WHEN ((BDDEPMESAQUIBEM = ''TRUE'') and (BDDEPDIARIA <> ''TRUE'')) OR (tbem.BDTIPOAPROCRED = 0) THEN dateadd(tbem.BDNUMPARC - 1 month to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'else DATEADD(tbem.BDNUMPARC MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'end))BDDTFIM,';
      wSQL = wSQL||                    'dateadd(iif(TBEM.BDDEPDIADATA = 2, 0, -1) day to (CASE ';
      wSQL = wSQL||                                       'WHEN (BDDEPMESAQUIBEM = ''TRUE'') OR (tbem.BDTIPOAPROCRED = 0) THEN tbem.BDDATORIAQUIBEM ';
      wSQL = wSQL||                                       'else DATEADD(1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                       'end))BDDTINI ';
      Wsql = wSQL||                 'FROM EMPRESAS_TBEM tbem ';
      wSQL = wSQL||                'WHERE tbem.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND ((tbem.BDCODCSTPIS is not null) OR (tbem.BDCODCSTCOF is not null)) ';
--sol:15691 - deve trazer os registros sem data de baixa OU (se tiver baixa) todos que a baixa seja posterior ao periodo de apuração OU
--(se a baixa for menor que a data final da apuração) os registros em que o mes da baixa seja igual ao da apuração E estiver parametrizado para depreciar no mes da baixa
      wSQL = wSQL||                'AND ((tbem.BDDATABAIXA is null) OR ';
      wSQL = wSQL||                     '(Cast(SubString(tbem.BDDATABAIXA FROM 1 for 4)||SubString(tbem.BDDATABAIXA FROM 6 for 2) AS Integer) > '||:prREFERENCIA||') OR ';
      wSQL = wSQL||                     '((tbem.BDDEPMESBAIXABEM = ''TRUE'') AND (LPAD(EXTRACT(MONTH FROM tbem.BDDATABAIXA), 2, ''0'') = SubString('||:prREFERENCIA||' FROM 5 for 2)) ';
      wSQL = wSQL||                     '                                    AND (LPAD(EXTRACT(YEAR FROM tbem.BDDATABAIXA), 4, ''0'') = SubString('||:prREFERENCIA||' FROM 1 for 4)) AND ';
      wSQL = wSQL||                      '(tbem.BDTIPOAPROCRED <> 0))) '; --sol:15691 - não levar no mes da baixa se for bdtipoaprocred = 0(10), que é do F130
--sol:15691 - obedecer o parametro BDDEPMESAQUIBEM que diz se deve depreciar no mes da aquisição ou no próximo
      wSQL = wSQL||                'AND (';
      wSQL = wSQL||                     '(Cast(SubString((CASE ';
      wSQL = wSQL||                                      'WHEN ((BDDEPMESAQUIBEM = ''TRUE'') and (BDDEPDIARIA <> ''TRUE'')) OR (tbem.BDTIPOAPROCRED = 0) THEN dateadd(tbem.BDNUMPARC - 1 month to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'else DATEADD(tbem.BDNUMPARC - 1 + 1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'end) FROM 1 for 4)||';
      wSQL = wSQL||                           'SubString((CASE ';
      wSQL = wSQL||                                      'WHEN ((BDDEPMESAQUIBEM = ''TRUE'') and (BDDEPDIARIA <> ''TRUE'')) OR (tbem.BDTIPOAPROCRED = 0) THEN dateadd(tbem.BDNUMPARC - 1 month to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'else DATEADD(tbem.BDNUMPARC - 1 + 1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                      'end) FROM 6 for 2) AS Integer) >= '||:prREFERENCIA||') AND ';
      wSQL = wSQL||                     '((Cast(SubString((CASE ';
      wSQL = wSQL||                                       'WHEN (BDDEPMESAQUIBEM = ''TRUE'') OR (tbem.BDTIPOAPROCRED = 0) THEN tbem.BDDATORIAQUIBEM ';
      wSQL = wSQL||                                       'else DATEADD(1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                       'end) FROM 1 for 4)||';
      wSQL = wSQL||                            'SubString((CASE ';
      wSQL = wSQL||                                       'WHEN (BDDEPMESAQUIBEM = ''TRUE'') OR (tbem.BDTIPOAPROCRED = 0) THEN tbem.BDDATORIAQUIBEM ';
      wSQL = wSQL||                                       'else DATEADD(1 MONTH to tbem.BDDATORIAQUIBEM) ';
      wSQL = wSQL||                                       'end) FROM 6 for 2) AS Integer) <= '||:prREFERENCIA||')) ';
      wSQL = wSQL||                     ') ';
--sol:15653 - somente se cst for diferente de 70
      wSQL = wSQL||                'AND (tbem.BDCODCSTPIS <> 70) AND (tbem.BDCODCSTCOF <> 70) ';
      wSQL = wSQL||              ')TBEM ';
      wSQL = wSQL||           ')TBEM ';
      wSQL = wSQL||             ') bem ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = bem.BDCODEMP) ';
      wSQL = wSQL||       ' left outer join TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = BEM.BDCODEMP AND SCP.BDCODSCP = BEM.BDCODSCP AND SCP.BDREFEMP = BEM.BDREFSOC) ';
      wSQL = wSQL||       ' LEFT OUTER JOIN VEF_EMP_TBEM TBEM ON (TBEM.BDCODEMP = BEM.BDCODEMP AND TBEM.BDCODBEM = BEM.BDCODBEM) ';
      wSQL = wSQL||       'union all ';
      wSQL = wSQL||       'SELECT pgto.BDCODEMP, COALESCE(emp.BDCODMATRIZ, pgto.BDCODEMP) as BDCODMATRIZ, (cast(substring(pgto.BDDATAPGTO FROM 1 for 4)||substring(pgto.BDDATAPGTO FROM 6 for 2) AS integer)) AS BDREFERENCIA, ';
      wSQL = wSQL||              'pgto.BDCHAVE, pgto.BDORDEMPGTO AS BDORDEM, NULL AS BDORDEMPRO, 14 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT, ';
      wSQL = wSQL||              'pgto.BDVLRTOTRECPAR AS BDVL_ITEM, NULL AS BDCODCTA, 109 AS BDNAT_BC_CRED, 109 AS BDCOD_CRED, 0 AS BDTIPOPROD,';
      wSQL = wSQL||              'f205.BDCODCSTPIS, f205.BDBASEPIS AS BDBCPIS, f205.BDALIQPIS, f205.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'f205.BDCODCSTCOF, f205.BDBASECOFINS AS BDBCCOFINS, f205.BDALIQCOFINS, f205.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT, 0 BDIND_ORIG_CRED, 0 BDCODEMPSCP, ''FALSE'' BDPISCOFQTD, NULL AS BDCODNAT, BDDATAPGTO AS BDDATANOTA, NULL BDDESCTIPODOC, OPF200.BDTIPOOPEREXP || '' - '' || OPF200.BDDESCRICAO BDDESCPEREXP,  NULL BDDESCNATREC, BDNRCONTRATO BDNUMDOC, -1 BDCONDPGTO ';
      wSQL = wSQL||       'FROM (SELECT f.* FROM VEF_EMP_TMOVOPIMOBI_F200_PGTO f ';
      wSQL = wSQL||              'WHERE f.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND (cast(substring(f.BDDATAPGTO FROM 1 for 4)||substring(f.BDDATAPGTO FROM 6 for 2) AS integer) = '||:prREFERENCIA||') ';
      wSQL = wSQL||             ') pgto ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = pgto.BDCODEMP) ';
      wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVOPIMOBCUSINCOR f205) f205 on (f205.BDCODEMP = pgto.BDCODEMP AND f205.BDCHAVE = pgto.BDCHAVE AND f205.BDORDEMPGTO = pgto.BDORDEMPGTO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVOPIMOBILIARIA_F200 F200 ON  (PGTO.BDCODEMP = F200.BDCODEMP AND PGTO.BDCHAVE = F200.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_BASE_TTABTIPOOPF200 OPF200 ON (OPF200.BDTIPOOPERIMOB = F200.BDTIPOOPERIMOB) ';
      wSQL = wSQL||       'union all ';
      wSQL = wSQL||       'SELECT pgto.BDCODEMP, COALESCE(emp.BDCODMATRIZ, pgto.BDCODEMP) as BDCODMATRIZ, (cast(substring(pgto.BDDATAPGTO FROM 1 for 4)||substring(pgto.BDDATAPGTO FROM 6 for 2) AS integer)) AS BDREFERENCIA, ';
      wSQL = wSQL||              'pgto.BDCHAVE, pgto.BDORDEMPGTO AS BDORDEM, NULL AS BDORDEMPRO, 14 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT, ';
      wSQL = wSQL||              'pgto.BDVLRTOTRECPAR AS BDVL_ITEM, NULL AS BDCODCTA, 109 AS BDNAT_BC_CRED, 109 AS BDCOD_CRED, 0 AS BDTIPOPROD,';
      wSQL = wSQL||              'f210.BDCODCSTPIS, f210.BDBASEPIS AS BDBCPIS, f210.BDALIQPIS, f210.BDVLRPIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'f210.BDCODCSTCOF, f210.BDBASECOFINS AS BDBCCOFINS, f210.BDALIQCOFINS, f210.BDVLRCOFINS, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT, 0 BDIND_ORIG_CRED, 0 BDCODEMPSCP, ''FALSE'' BDPISCOFQTD, NULL AS BDCODNAT, BDDATAPGTO AS BDDATANOTA, NULL BDDESCTIPODOC, OPF200.BDTIPOOPEREXP || '' - '' || OPF200.BDDESCRICAO BDDESCPEREXP,  NULL BDDESCNATREC, BDNRCONTRATO BDNUMDOC, -1 BDCONDPGTO ';
      wSQL = wSQL||       'FROM (SELECT f.* FROM VEF_EMP_TMOVOPIMOBI_F200_PGTO f ';
      wSQL = wSQL||              'WHERE f.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND (cast(substring(f.BDDATAPGTO FROM 1 for 4)||substring(f.BDDATAPGTO FROM 6 for 2) AS integer) = '||:prREFERENCIA||') ';
      wSQL = wSQL||             ') pgto ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = pgto.BDCODEMP) ';
      wSQL = wSQL||       'JOIN (SELECT * FROM VEF_EMP_TMOVOPIMOBCUSORCA f210) f210 on (f210.BDCODEMP = pgto.BDCODEMP AND f210.BDCHAVE = pgto.BDCHAVE AND f210.BDORDEMPGTO = pgto.BDORDEMPGTO) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_EMP_TMOVOPIMOBILIARIA_F200 F200 ON  (PGTO.BDCODEMP = F200.BDCODEMP AND PGTO.BDCHAVE = F200.BDCHAVE) ';
      wSQL = wSQL||       'LEFT OUTER JOIN VEF_BASE_TTABTIPOOPF200 OPF200 ON (OPF200.BDTIPOOPERIMOB = F200.BDTIPOOPERIMOB) ';
      wSQL = wSQL||       'union all ';
      wSQL = wSQL||       'SELECT pgto.BDCODEMP, COALESCE(emp.BDCODMATRIZ, pgto.BDCODEMP) as BDCODMATRIZ, '||:prREFERENCIA||' AS BDREFERENCIA, ';
      wSQL = wSQL||              'pgto.BDCHAVE, NULL AS BDORDEM, NULL AS BDORDEMPRO, 18 AS BDCODTP, NULL as BDMODELO, NULL AS BDPREFIXONAT, ';
      wSQL = wSQL||              'pgto.BDVL_TOT_EST, pgto.BDCODTPLA AS BDCODCTA, pgto.BDNAT_BC_CRED, ';
      wSQL = wSQL||               'case ';
      wSQL = wSQL||                 'when (((pgto.BDCODCSTPIS = 50) or (pgto.BDCODCSTCOF = 50))) then 104 ';
      wSQL = wSQL||                 'when (((pgto.BDCODCSTPIS = 51) or (pgto.BDCODCSTCOF = 51))) then 204 ';
      wSQL = wSQL||                 'when (((pgto.BDCODCSTPIS = 52) or (pgto.BDCODCSTCOF = 52))) then 304 ';
      wSQL = wSQL||                 'when (((pgto.BDCODCSTPIS = 53) or (pgto.BDCODCSTCOF = 53))) then 104 ';
      wSQL = wSQL||                 'when (((pgto.BDCODCSTPIS = 54) or (pgto.BDCODCSTCOF = 54))) then 104 ';
      wSQL = wSQL||                 'when (((pgto.BDCODCSTPIS = 55) or (pgto.BDCODCSTCOF = 55))) then 204 ';
      wSQL = wSQL||                 'when (((pgto.BDCODCSTPIS = 56) or (pgto.BDCODCSTCOF = 56))) then 104 ';
      wSQL = wSQL||               'else 104 ';
      wSQL = wSQL||               'end as BDCOD_CRED, 0 AS BDTIPOPROD, ';
      wSQL = wSQL||              'pgto.BDCODCSTPIS, pgto.BDVL_BC_MEN_EST, pgto.BDALIQ_PIS, pgto.BDVL_CRED_PIS, NULL as BDBCPIS_QUANT, NULL as BDALIQPIS_QUANT,';
      wSQL = wSQL||              'pgto.BDCODCSTCOF, pgto.BDVL_BC_MEN_EST, pgto.BDALIQ_COF, pgto.BDVL_CRED_COF, NULL as BDBCCOFINS_QUANT, NULL as BDALIQCOFINS_QUANT, 0 BDIND_ORIG_CRED, 0 BDCODEMPSCP, ''FALSE'' BDPISCOFQTD, NULL BDCODNAT , ';
      wSQL = wSQL||              '(select (''01'' || ''/'' || substring(PGTO.BDREFINI from 5 for 2) || ''/'' || substring(PGTO.BDREFINI from 1 for 4)) || '' - '' ||(ULTDIA || ''/'' || substring(PGTO.BDREFFIN from 5 for 2) || ''/'' || substring(PGTO.BDREFFIN from 1 for 4)) as BDDATANOTA ';
      wSQL = wSQL||              '  from ULTIMO_DIA_MES(substring(PGTO.BDREFFIN from 5 for 2), substring(PGTO.BDREFFIN from 1 for 4))) BDDATANOTA, ';
      wSQL = wSQL||              'NULL BDDESCTIPODOC, NULL BDDESCPEREXP, NAT.BDCODNATBC ||'' - ''|| NAT.BDDESCRICAO BDDESCNATREC, null BDNUMDOC, -1 BDCONDPGTO ';
      wSQL = wSQL||       'FROM (SELECT f.* FROM VEF_EMP_TCREDESTOQF150 f ';
      wSQL = wSQL||              'WHERE f.'||TRIM(:prWHEREEMPRESAS)||' ';
      wSQL = wSQL||                'AND ('||:prREFERENCIA||' BETWEEN F.BDREFINI AND F.BDREFFIN)) pgto ';
      WSQL = WSQL||             'LEFT OUTER JOIN VEF_BASE_TNATBCPISCOFINS NAT ON (PGTO.BDNAT_BC_CRED = NAT.BDCODNATBC) ';
      wSQL = wSQL||       'LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = pgto.BDCODEMP) ';
      EXECUTE STATEMENT(wSQLPREFIXO||wSQL||wSQLSUFIXO);
  END
END
^

create or alter procedure SP_APURACAO_BLOCOM_M100M500 (
    PRCODQUADRO integer,
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRRETIFICADORA integer,
    PRTABELAREL integer,
    PRAJUSTESCP DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
declare variable WSQL varchar(32750);
declare variable WINCTRIB integer;
declare variable WMETODOAPRO integer;
declare variable WRBNCUMTRIBMI numeric(15,4);
declare variable WRBNCUMNTMI numeric(15,4);
declare variable WRBNCUMEXP numeric(15,4);
declare variable WRBCUM numeric(15,4);
declare variable WBCPISCOF varchar(400);
declare variable WBCPISCOF_QUANT varchar(400);
declare variable WPISCOFINS varchar(6);
declare variable WPISCOF varchar(3);
declare variable WUSARSO DM_BOOLEAN;
BEGIN
  IF (:prCODQUADRO = 11) THEN
    BEGIN
      :wPISCOF = 'PIS';
      :wPISCOFINS = 'PIS';
    END
  ELSE
    BEGIN
      :wPISCOF = 'COF';
      :wPISCOFINS = 'COFINS';
    END

  :WUSARSO = 'FALSE';

  -- Insere a compet?ncia da apura??o...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Carrega configuração da empresa na referência da apuração...
  SELECT BDINCTRIB+1, -- Incidência tributária
         BDMETODOAPRO+1 -- Método de apropriação
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wMETODOAPRO;

  if ((:WINCTRIB is null) and (:PRCODEMPSO > 0)) then
    begin
      SELECT BDINCTRIB+1, BDMETODOAPRO+1
      FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMPSO
      INTO :wINCTRIB, :wMETODOAPRO;

      :WUSARSO = 'TRUE';
    end

  /* 34 - Contribuição não cumulativa
     Tributada no mercado interno */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribuição não cumulativa
    AND BDNUMCAMPO = 1
    AND BDCODEMP = iif(:WUSARSO = 'TRUE', :PRCODEMPSO, :prCODEMP)
    AND BDREFERENCIA = :prREFERENCIA
    AND BDRETIFICADORA = :PRRETIFICADORA
  INTO :wRBNCUMTRIBMI;

  /* 34 - Contribuição não cumulativa
     Não Tributada no mercado interno */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribuição não cumulativa
    AND BDNUMCAMPO = 2
    AND BDCODEMP = iif(:WUSARSO = 'TRUE', :PRCODEMPSO, :prCODEMP)
    AND BDREFERENCIA = :prREFERENCIA
    AND BDRETIFICADORA = :PRRETIFICADORA
  INTO :wRBNCUMNTMI;

  /* 34 - Contribuição não cumulativa
     Exportação */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 34 -- Contribuição não cumulativa
    AND BDNUMCAMPO = 3
    AND BDCODEMP = iif(:WUSARSO = 'TRUE', :PRCODEMPSO, :prCODEMP)
    AND BDREFERENCIA = :prREFERENCIA
    AND BDRETIFICADORA = :PRRETIFICADORA
  INTO :wRBNCUMEXP;

  /* 35 - Contribuição cumulativa */
  SELECT BDVALOR
  FROM VEF_EMP_TBLOCOMGERREG
  WHERE BDCODQUADRO = 35 -- Contribuição não cumulativa
    AND BDNUMCAMPO = 1
    AND BDCODEMP = iif(:WUSARSO = 'TRUE', :PRCODEMPSO, :prCODEMP)
    AND BDREFERENCIA = :prREFERENCIA
    AND BDRETIFICADORA = :PRRETIFICADORA
  INTO :WRBCUM;

  IF ((wINCTRIB IS NOT NULL) AND (wINCTRIB <> 2)) THEN -- Diferente de "2 - Exclusivamente no regime cumulativo"
    BEGIN
      WBCPISCOF = 'SUM(COALESCE(TMP.BDBC'||:wPISCOFINS||',0))';
      WBCPISCOF_QUANT = 'SUM(COALESCE(TMP.BDBC'||:wPISCOFINS||'_QUANT,0))';

      IF (:wINCTRIB = 3) THEN -- 3 - Regimes n?o-cumulativo e cumulativo - Deve considerar os valores de "N?o cumulativo" e "Cumulativo" para o total e achar os percentuais...
        BEGIN
          WBCPISCOF = 'CAST(('||WBCPISCOF||' * (('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') / IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||'+'||:wRBCUM||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||'+'||:wRBCUM||')))) AS NUMERIC(15,2)) ';
          WBCPISCOF_QUANT = 'CAST(('||WBCPISCOF_QUANT||' * (('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') / IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||'+'||:wRBCUM||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||'+'||:wRBCUM||')))) AS NUMERIC(15,2)) ';
        END
      IF (:PRTABELAREL = 0) THEN
        BEGIN
      /* REGISTRO M100: CRÉDITO DE PIS/PASEP RELATIVO AO PERÍODO */
      wSQL =       'INSERT INTO VEF_EMP_TBLOCOM100_500 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCODCRE_4_3_6, BDTIPOPROD, BDIND_CRED_ORI, BDVL_BC, BDALIQ, BDQUANT_BC, BDALIQ_QUANT, BDVL_CRED,';
      wSQL = wSQL||                                    'BDVL_AJUS_ACRES, BDVL_AJUS_REDUC, BDVL_CRED_DIF, BDVL_CRED_DISP, BDIND_DESC_CRED, BDVL_CRED_DESC, BDSLD_CRED, BDRETIFICADORA) ';
      wSQL = wSQL||'SELECT '||:prCODQUADRO||' AS BDCODQUADRO, 7 AS BDCODPERIODO, IIF(TMP.BDCODEMPSCP > 0,TMP.BDCODEMPSCP,tmp.BDCODEMP) BDCODEMP, IIF(TMP.BDCODEMPSCP > 0,TMP.BDCODEMPSCP,tmp.BDCODMATRIZ) BDCODMATRIZ, tmp.BDREFERENCIA,';

      wSQL = wSQL||'GETORDEMSEQUENCIAL_STR('||IIF(:prCODQUADRO = 11, '''M100.''', '''M500.''')||'||7||''.''||tmp.BDCODEMP||''.''||tmp.BDCODMATRIZ||''.'||:prCODQUADRO||'.''||tmp.BDREFERENCIA||''.''||TMP.BDCODEMPSCP, '||iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)||') AS BDCHAVE,';
      --wSQL = wSQL||'GETORDEMSEQUENCIAL_STR('''||:wRegMX000||'''.7.''||tmp.BDCODEMP||''.''||tmp.BDCODMATRIZ||''.'''||:prCODQUADRO||'.''||tmp.BDREFERENCIA||''.''||TMP.BDCODEMPSCP, '||:prCODEMP||') AS BDCHAVE,';
      --wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDCHAVE)+1, 1) FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = '||:prCODQUADRO||' AND x.BDCODPERIODO = 7) AS BDCHAVE,';
      wSQL = wSQL||       'tmp.BDCODCRE_4_3_6, tmp.BDTIPOPROD, 0 AS BDIND_CRED_ORI, sum(IIF(tmp.BDBC'||:wPISCOFINS||' > 0, tmp.BDVL_BCSOMA,0)), COALESCE(tmp.BDALIQ'||:wPISCOFINS||',0) AS BDALIQ,';
      wSQL = wSQL||       'sum(IIF(tmp.BDBC'||:wPISCOFINS||'_QUANT > 0, tmp.BDVL_BCSOMA,0)) BDBC'||:wPISCOFINS||'_QUANT, COALESCE(tmp.BDALIQ'||:wPISCOFINS||'_QUANT,0) AS BDALIQ_QUANT,';
      wSQL = wSQL||       '(((sum(IIF(tmp.BDBC'||:wPISCOFINS||' > 0, tmp.BDVL_BCSOMA,0))*COALESCE(tmp.BDALIQ'||:wPISCOFINS||',1))/100)+(sum(IIF(tmp.BDBC'||:wPISCOFINS||'_QUANT > 0, tmp.BDVL_BCSOMA,0))*COALESCE(tmp.BDALIQ'||:wPISCOFINS||'_QUANT,1))) AS BDVL_CRED,';
      wSQL = wSQL||       '0 AS BDVL_AJUS_ACRES, 0 AS BDVL_AJUS_REDUC, 0 AS BDVL_CRED_DIF, 0 AS BDVL_CRED_DISP,';
      wSQL = wSQL||       'NULL AS BDIND_DESC_CRED, 0 AS BDVL_CRED_DESC, 0 AS BDSLD_CRED, '|| :PRRETIFICADORA ||' BDRETIFICADORA ';
      wSQL = wSQL||'FROM (SELECT tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDALIQ'||:wPISCOFINS||',';
      wSQL = wSQL||             'tmp.BDALIQ'||:wPISCOFINS||'_QUANT, t436.BDCODCRE_4_3_6, tmp.BDTIPOPROD,';

      -- Verifica se usa rateio ou leva valor cheio...
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime não-cumulativo / 2 - Método de rateio proporcional
        BEGIN
                                   -- Rateio
                                   -- Caso faça rateio na CST com código de crédito, aqui pega os códigos de crédito dos rateios...
          wSQL = wSQL||            'COALESCE(rat.BDCOD_CRED_MATRIZ, tmp.BDCOD_CRED) as BDCOD_CRED, TMP.BDCODEMPSCP,';
                                   -- Caso faça rateio na CST com código de crédito, faz os rateios das base de cálculos pelas formulas do registro 0111...
          wSQL = wSQL||            'CASE tmp.BDCODCST'||:wPISCOF||' ';
          wSQL = wSQL||               'WHEN 53 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,104,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMTRIBMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, cast(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')as NUMERIC(15,2))) ))/100  AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,204,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMNTMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, cast(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')as NUMERIC(15,2))) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 54 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,104,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMTRIBMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, cast(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')as NUMERIC(15,2))) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,304,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMEXP||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, cast(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')as NUMERIC(15,2))) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 55 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,204,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMNTMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,304,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMEXP||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 56 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (101,102,103,104,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMTRIBMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (201,202,203,204,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMNTMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (301,302,303,304,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMEXP||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||              'WHEN 63 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMTRIBMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMNTMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 64 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMTRIBMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMEXP||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 65 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMNTMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMEXP||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 66 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMTRIBMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMNTMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (rat.BDCOD_CRED_MATRIZ IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMEXP||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||             'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||             'END BDVL_BCSOMA, '||WBCPISCOF||' BDBC'||:wPISCOFINS||', ';
          wSQL = wSQL||             WBCPISCOF_QUANT||' BDBC'||:wPISCOFINS||'_QUANT ';

        END
      ELSE
        BEGIN
          wSQL = wSQL||             'tmp.BDCOD_CRED as BDCOD_CRED, TMP.BDCODEMPSCP,';
          wSQL = wSQL||             'Sum(Coalesce(tmp.BDBC'||:wPISCOFINS||',0)+Coalesce(tmp.BDBC'||:wPISCOFINS||'_QUANT,0)) BDVL_BCSOMA, Sum(tmp.BDBC'||:wPISCOFINS||')BDBC'||:wPISCOFINS||', sum(tmp.BDBC'||:wPISCOFINS||'_QUANT) BDBC'||:wPISCOFINS||'_QUANT ';
        END

      wSQL = wSQL||      'FROM TMP_VEF_EMP_TBLOCOM_M100_M500 tmp ';
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime não-cumulativo / 2 - Método de rateio proporcional
        BEGIN
          wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_CST_RATEIO_BLOCOM rat ON (rat.BDCODCSTPIS = tmp.BDCODCST'||:wPISCOF||' and rat.BDCOD_CRED_ORIGINAL = tmp.BDCOD_CRED) ';
          wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTAB_4_3_6 t436 ON (t436.BDCODEXPCRE = COALESCE(rat.BDCOD_CRED_MATRIZ, tmp.BDCOD_CRED)) ';
        END
      ELSE
        wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTAB_4_3_6 t436 ON (t436.BDCODEXPCRE = tmp.BDCOD_CRED) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCST'||:wPISCOF||' cstpis ON (cstpis.BDCODCST'||:wPISCOF||' = tmp.BDCODCST'||:wPISCOF||') ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_EMP_TMOVENT ent ON (ent.BDCODEMP = tmp.BDCODEMP AND ent.BDCHAVE = tmp.BDCHAVE AND 1 = tmp.BDCODTP) '; -- Lan?amentos de entrada com produtos...

      wSQL = wSQL||      'WHERE tmp.BDCODMATRIZ = '||iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)||' ';
      wSQL = wSQL||        'AND tmp.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||        'AND ((tmp.BDBC'||:wPISCOFINS||' > 0) OR (tmp.BDBC'||:wPISCOFINS||'_QUANT > 0)) ';
      wSQL = wSQL||        'AND ((tmp.BDALIQ'||:wPISCOFINS||' > 0) OR (tmp.BDALIQ'||:wPISCOFINS||'_QUANT > 0)) ';
      wSQL = wSQL||        'AND (cstpis.BDCODCST'||:wPISCOF||' IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) ';
      wSQL = wSQL||        'AND (tmp.BDNAT_BC_CRED IS NOT NULL) ';
      wSQL = wSQL||        'AND (tmp.BDCOD_CRED IS NOT NULL) ';
      wSQL = wSQL||        'AND ((tmp.BDCODTP <> 1) OR '; -- Apenas deve filtrar os lançamentos de produtos...
      wSQL = wSQL||       '(';-- Fiiltro dos código da base de cálculo de crétido...
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 01) AND '; -- Aquisição de Bens para Revenda
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1102,1113,1117,1118,1121,1251,1403,1652,2102,2113,2117,2118,2121,2251,2403,2652,3102,3251,3652))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 02) AND '; -- Aquisição de Bens Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1101,1111,1116,1120,1122,1126,1128,1135,1401,1407,1556,1651,1653,2101,2111,2116,2120,2122,2126,2128,2135,2401,2407,2556,2651,2653,3101,3126,3128,3556,3651,3653))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 03) AND '; -- Aquisição de Serviços Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1124,1125,1933,2124,2125,2933))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 12) AND '; -- Devolução de Vendas Sujeitas à Incidência Não-Cumulativa
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1201,1202,1203,1204,1206,1207,1410,1411,1660,1661,1662,2201,2202,2206,2207,2410,2411,2660,2661,2662))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 13) AND '; -- Outras Operações com Direito a Crédito
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1922,2922))) ';
      wSQL = wSQL||        ')';
      wSQL = wSQL||       ') ';       
      wSQL = wSQL||'GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, t436.BDCODCRE_4_3_6, TMP.BDTIPOPROD, tmp.BDALIQ'||:wPISCOFINS||', tmp.BDALIQ'||:wPISCOFINS||'_QUANT, tmp.BDCODCST'||:wPISCOF||', tmp.BDCOD_CRED, TMP.BDCODEMPSCP ';
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime não-cumulativo / 2 - Método de rateio proporcional
        wSQL = wSQL||      ',rat.BDCOD_CRED_MATRIZ';
      wSQL = wSQL||') tmp ';

      if ((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0)) then
        wSQL = wSQL||'where (coalesce(tmp.BDCODEMPSCP, 0) = '||:PRCODEMP||') ';
      else
      if (:PRAJUSTESCP = 'TRUE') then
        wSQL = wSQL||'where (coalesce(tmp.BDCODEMPSCP, 0) = 0) ';

      wSQL = wSQL||'GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODCRE_4_3_6, tmp.BDTIPOPROD, tmp.BDALIQ'||:wPISCOFINS||', tmp.BDALIQ'||:wPISCOFINS||'_QUANT, TMP.BDCODEMPSCP; ';
      EXECUTE STATEMENT ( wSQL );

       END


      /* REGISTRO M105: DETALHAMENTO DA BASE DE CALCULO DO CRÉDITO APURADO NO PERÍODO - PIS/PASEP */
      IF (:PRTABELAREL = 1) THEN
        BEGIN
          wSQL =       'INSERT INTO VEF_EMP_TVINCM105_M505 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODCSTPIS, BDCODCSTCOF, BDCODNATBC, BDCODCRE_4_3_6, BDTIPOPROD, ';
          wSQL = wSQL||                                     'BDVL_BC_TOT, BDVL_BC_CUM, BDVL_BC_NC, BDVL_BC, BDQUANT_BC_TOT, BDQUANT_BC, BDDESC_CRED, BDALIQ, BDRETIFICADORA, BDORDEMPRO,BDCODTP,BDCODNAT,BDDESCTIPODOC,BDDESCPEREXP,BDDESCNATREC,BDDATANOTA, BDCHAVELAN, BDVL_REC_BRT, BDVL_BC_CONT_AJUS, BDVL_CONT_APUR, BDNUMDOC, BDCONDPGTO) ';
        END
      ELSE
        BEGIN
      wSQL =       'INSERT INTO VEF_EMP_TBLOCOM105_M505 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODCSTPIS, BDCODCSTCOF, BDCODNATBC, BDCODCRE_4_3_6, BDTIPOPROD,';
      wSQL = wSQL||                                     'BDVL_BC_TOT, BDVL_BC_CUM, BDVL_BC_NC, BDVL_BC, BDQUANT_BC_TOT, BDQUANT_BC, BDDESC_CRED, BDALIQ, BDRETIFICADORA) ';
        END
      wSQL = wSQL||'SELECT 7 AS BDCODPERIODO, IIF(TMP.BDCODEMPSCP > 0,TMP.BDCODEMPSCP,TMP.BDCODEMP) BDCODEMP, IIF(TMP.BDCODEMPSCP > 0,TMP.BDCODEMPSCP,TMP.BDCODMATRIZ) BDCODMATRIZ, '||:prCODQUADRO||' AS BDCODQUADRO, tmp.BDREFERENCIA,';
      wSQL = wSQL||       '(SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = IIF(TMP.BDCODEMPSCP > 0,TMP.BDCODEMPSCP,TMP.BDCODEMP) AND x.BDCODMATRIZ = IIF(TMP.BDCODEMPSCP > 0,TMP.BDCODEMPSCP,TMP.BDCODMATRIZ) ';
      wSQL = wSQL||'       AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = '||:prCODQUADRO||' AND x.BDCODPERIODO = 7 AND X.BDRETIFICADORA = '|| :PRRETIFICADORA ||' AND x.BDCODCRE_4_3_6 = TMP.BDCODCRE_4_3_6 AND COALESCE(X.BDTIPOPROD,0) = COALESCE(TMP.BDTIPOPROD,0) AND ((x.BDALIQ = tmp.BDALIQ'||:wPISCOFINS||' and x.BDALIQ > 0) OR (x.BDALIQ_QUANT = tmp.BDALIQ'||:wPISCOFINS||'_QUANT and x.BDALIQ_QUANT > 0))) AS BDCHAVE,';

      wSQL = wSQL||'GETORDEMSEQUENCIAL_STR('||IIF(:prCODQUADRO = 11, '''M105.''', '''M505.''')||'||7||''.''||tmp.BDCODEMP||''.''||tmp.BDCODMATRIZ||''.''||11||''.''||tmp.BDREFERENCIA||''.''||TMP.BDCODEMPSCP ';
      wSQL = wSQL||'||''.''||(SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = '||:prCODQUADRO||' AND x.BDCODPERIODO = 7 AND X.BDRETIFICADORA = '|| :PRRETIFICADORA ||' AND x.BDCODCRE_4_3_6 = TMP.BDCODCRE_4_3_6 AND COALESCE(X.BDTIPOPROD,0) = COALESCE(TMP.BDTIPOPROD,0) AND ((x.BDALIQ = tmp.BDALIQ'||:wPISCOFINS||' and x.BDALIQ > 0) OR (x.BDALIQ_QUANT = tmp.BDALIQ'||:wPISCOFINS||'_QUANT and x.BDALIQ_QUANT > 0))), '||iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)||') AS BDORDEM,';
      /*wSQL = wSQL||       '(SELECT COALESCE(MAX(x.BDORDEM)+1,1)';
      wSQL = wSQL||        'FROM VEF_EMP_TBLOCOM105_M505 x ';
      wSQL = wSQL||        'WHERE x.BDCODPERIODO = 7 ';
      wSQL = wSQL||          'AND x.BDCODEMP = tmp.BDCODEMP ';
      wSQL = wSQL||          'AND x.BDCODMATRIZ = tmp.BDCODMATRIZ ';
      wSQL = wSQL||          'AND x.BDCODQUADRO = '||:prCODQUADRO||' ';
      wSQL = wSQL||          'AND x.BDREFERENCIA = tmp.BDREFERENCIA ';
      wSQL = wSQL||          'AND x.BDCODCRE_4_3_6 = t436.BDCODCRE_4_3_6 ';
      wSQL = wSQL||          'AND x.BDALIQ = COALESCE(tmp.BDALIQ'||:wPISCOFINS||',tmp.BDALIQ'||:wPISCOFINS||'_QUANT) ';
      wSQL = wSQL||          'AND x.BDCHAVE = (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODEMP = tmp.BDCODEMP AND x.BDCODMATRIZ = tmp.BDCODMATRIZ AND x.BDREFERENCIA = tmp.BDREFERENCIA AND x.BDCODQUADRO = '||:prCODQUADRO||' AND x.BDCODPERIODO = 7 AND x.BDCODCRE_4_3_6 = t436.BDCODCRE_4_3_6 AND ((x.BDALIQ = tmp.BDALIQ'||:wPISCOFINS||') OR (x.BDALIQ_QUANT = tmp.BDALIQ'||:wPISCOFINS||'_QUANT))) ';
      wSQL = wSQL||        ') AS BDORDEM, '; */

      wSQL = wSQL||       'tmp.BDCODCSTPIS, tmp.BDCODCSTCOF, tmp.BDNAT_BC_CRED AS BDCODNATBC, TMP.BDCODCRE_4_3_6, tmp.BDTIPOPROD, ';
      wSQL = wSQL||       'TMP.BDVL_BC_TOT, ';
      wSQL = wSQL||       ' TMP.BDVL_BC_CUM, TMP.BDVL_BC_NC, ';
                                                    
      wSQL = wSQL||       'IIF(tmp.BDVL_BC > 0, tmp.BDVL_BCSOMA,0) BDVL_BC, ';
      wSQL = wSQL||       'TMP.BDQUANT_BC_TOT,  IIF(tmp.BDBC'||:wPISCOFINS||'_QUANT > 0, tmp.BDVL_BCSOMA,0) AS BDQUANT_BC, NULL AS BDDESC_CRED, IIF(tmp.BDALIQ'||:wPISCOFINS||' > 0,tmp.BDALIQ'||:wPISCOFINS||',tmp.BDALIQ'||:wPISCOFINS||'_QUANT) AS BDALIQ, ';
      wSQL = wSQL||       :PRRETIFICADORA||' BDRETIFICADORA ';
      IF (:PRTABELAREL = 1) THEN
      wSQL = wSQL||       ',BDORDEMPRO,BDCODTP,BDCODNAT,BDDESCTIPODOC,BDDESCPEREXP,BDDESCNATREC,BDDATANOTA, BDCHAVELAN, BDVL_ITEM AS BDVL_REC_BRT, BDBC'||:wPISCOFINS||' AS BDVL_BC_CONT_AJUS, iif(bdcodtp = 14, ((BDALIQ'||:wPISCOFINS||' / 100) *  BDVLR'||:wPISCOFINS||'), BDVLR'||:wPISCOFINS||') AS BDVL_CONT_APUR, BDNUMDOC,BDCONDPGTO ';

                  
      wSQL = wSQL|| ' FROM( ';              
      wSQL = wSQL|| ' SELECT TMP.BDCODEMP, TMP.BDCODMATRIZ, TMP.BDREFERENCIA,';
      wSQL = wSQL||             'TMP.BDCODCSTPIS, TMP.BDCODCSTCOF, TMP.BDNAT_BC_CRED, ';
      wSQL = wSQL||             'TMP.BDALIQ'||:wPISCOFINS||', SUM(COALESCE(tmp.BDBC'||:wPISCOFINS||'TOTAL,0)) AS BDVL_BC_TOT, SUM(COALESCE(tmp.BDBC'||:wPISCOFINS||'QTDTOTAL,0)) BDQUANT_BC_TOT, ';
      wSQL = wSQL||             'TMP.BDALIQ'||:wPISCOFINS||'_QUANT, ';
      wSQL = wSQL||             'TMP.BDCOD_CRED, TMP.BDCODEMPSCP, t436.BDCODCRE_4_3_6, tmp.BDTIPOPROD, ';
      
      IF ((:wINCTRIB = 3) AND (:wMETODOAPRO = 2)) THEN -- 3 - Regimes não-cumulativo e cumulativo - Deve considerar os valores de "Não cumulativo" e "Cumulativo" para o total e achar os percentuais...
        BEGIN
          wSQL = wSQL||       ' CAST( (SUM(COALESCE(tmp.BDBC'||:wPISCOFINS||'TOTAL, 0))*((('||:wRBCUM||')*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||'+'||:wRBCUM||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||'+'||:wRBCUM||')) ))/100 AS NUMERIC(15,2)) AS BDVL_BC_CUM, ';
          wSQL = wSQL||       ' CAST( (SUM(COALESCE(tmp.BDBC'||:wPISCOFINS||'TOTAL, 0))*((('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')*100)/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||'+'||:wRBCUM||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||'+'||:wRBCUM||')) ))/100 AS NUMERIC(15,2)) AS BDVL_BC_NC, ';
        END
      ELSE
        wSQL = wSQL||       ' 0 AS BDVL_BC_CUM, /*(Campo 04 - Campo 05)*/SUM(COALESCE(tmp.BDBC'||:wPISCOFINS||'TOTAL,0)-0) AS BDVL_BC_NC, ';

      -- Verifica se usa rateio ou leva valor cheio...
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime não-cumulativo / 2 - Método de rateio proporcional
        BEGIN
          wSQL = wSQL||            'Coalesce( ';
          wSQL = wSQL||            'CASE tmp.BDCODCST'||:wPISCOF||' ';
          wSQL = wSQL||               'WHEN 53 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (101,102,103,104,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMTRIBMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100  AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (201,202,203,204,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMNTMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 54 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (101,102,103,104,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMTRIBMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (301,302,303,304,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMEXP||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 55 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (201,202,203,204,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMNTMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (301,302,303,304,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMEXP||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 56 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (101,102,103,104,108)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMTRIBMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (201,202,203,204,208)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMNTMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (301,302,303,304,308)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMEXP||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||              'WHEN 63 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMTRIBMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMNTMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 64 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMTRIBMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMEXP||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 65 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMNTMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMEXP||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||               'WHEN 66 THEN ';
          wSQL = wSQL||                 'CASE ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (106,107)) THEN '; -- Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMTRIBMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (206,207)) THEN '; -- N?o Tributada no mercado interno
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMNTMI||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'WHEN (tmp.BDCOD_CRED IN (306,307)) THEN '; -- Exporta??o
          wSQL = wSQL||                     'CAST( (('||WBCPISCOF||'+'||WBCPISCOF_QUANT||')*(Cast('||:wRBNCUMEXP||'*100 AS NUMERIC(18,3))/IIF(('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||') = 0, 1, ('||:wRBNCUMTRIBMI||'+'||:wRBNCUMNTMI||'+'||:wRBNCUMEXP||')) ))/100 AS NUMERIC(15,2)) ';
          wSQL = wSQL||                   'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||                 'END ';
          wSQL = wSQL||             'ELSE ('||WBCPISCOF||'+'||WBCPISCOF_QUANT||') ';
          wSQL = wSQL||             'END,0) BDVL_BCSOMA, ';
          wSQL = wSQL||             WBCPISCOF||' BDVL_BC, ';
          wSQL = wSQL||             WBCPISCOF_QUANT||' BDBC'||:wPISCOFINS||'_QUANT ';
        END
      ELSE
        BEGIN
          wSQL = wSQL||             'Sum(Coalesce(tmp.BDBC'||:wPISCOFINS||',0)+Coalesce(tmp.BDBC'||:wPISCOFINS||'_QUANT,0)) BDVL_BCSOMA, ';
          wSQL = wSQL||             'Sum(Coalesce(tmp.BDBC'||:wPISCOFINS||',0)) BDVL_BC, ';
          wSQL = wSQL||             'Sum(Coalesce(tmp.BDBC'||:wPISCOFINS||'_QUANT,0)) BDBC'||:wPISCOFINS||'_QUANT ';
        END
      IF (:PRTABELAREL = 1) THEN
       wSQL = wSQL||             ',BDORDEMPRO,BDCODTP,BDCODNAT,BDDESCTIPODOC,BDDESCPEREXP,BDDESCNATREC,BDDATANOTA, BDNUMDOC , BDCHAVE AS BDCHAVELAN,  BDBC'||:wPISCOFINS||' ,BDVL_ITEM, BDVLR'||:wPISCOFINS||', BDCONDPGTO ';
      wSQL = wSQL||'FROM (SELECT x.BDCODEMP, x.BDCODMATRIZ, x.BDCHAVE, x.BDREFERENCIA, x.BDPREFIXONAT, x.BDTIPOPROD,';
      wSQL = wSQL||             'x.BDCODCSTPIS, x.BDCODCSTCOF, x.BDCODTP, x.BDNAT_BC_CRED, ';
      wSQL = wSQL||             'x.BDALIQ'||:wPISCOFINS||', (Coalesce(x.BDBC'||:wPISCOFINS||',0)) as BDBC'||:wPISCOFINS||'TOTAL, Coalesce(x.BDBC'||:wPISCOFINS||'_QUANT,0) BDBC'||:wPISCOFINS||'QTDTOTAL,';
      wSQL = wSQL||             'x.BDBCPIS_QUANT, x.BDALIQPIS_QUANT, ';
      wSQL = wSQL||             'x.BDBCCOFINS_QUANT, x.BDALIQCOFINS_QUANT, ';
      -- Verifica se usa rateio ou leva valor cheio...
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime não-cumulativo / 2 - Método de rateio proporcional
        BEGIN
          wSQL = wSQL||            'COALESCE(rat.BDCOD_CRED_MATRIZ, x.BDCOD_CRED) as BDCOD_CRED, ';
        END
      ELSE
        BEGIN
          wSQL = wSQL||            'x.BDCOD_CRED as BDCOD_CRED,';
        END
      wSQL = wSQL||             'x.BDBC'||:wPISCOFINS||', X.BDCODEMPSCP ';
      IF (:PRTABELAREL = 1) THEN
        wSQL = wSQL||            ',X.BDORDEMPRO,X.BDCODNAT,X.BDDESCTIPODOC,X.BDDESCPEREXP,X.BDDESCNATREC,X.BDDATANOTA, x.BDNUMDOC, X.BDVL_ITEM, X.BDVLR'||:wPISCOFINS||', X.BDCONDPGTO ';
      wSQL = wSQL||      'FROM TMP_VEF_EMP_TBLOCOM_M100_M500 x ';
      IF ((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) THEN -- 1 - Exclusivamente no regime não-cumulativo / 2 - Método de rateio proporcional
        wSQL = wSQL||      'LEFT OUTER JOIN VEF_BASE_CST_RATEIO_BLOCOM rat ON (rat.BDCODCSTPIS = x.BDCODCST'||:wPISCOF||' and rat.BDCOD_CRED_ORIGINAL = x.BDCOD_CRED) ';
      wSQL = wSQL||      'WHERE x.BDCODMATRIZ = '||iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)||' ';
      wSQL = wSQL||        'AND x.BDREFERENCIA = '||:prREFERENCIA||' ';
      wSQL = wSQL||      ') tmp ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTAB_4_3_6 t436 ON (t436.BDCODEXPCRE = tmp.BDCOD_CRED) ';
      wSQL = wSQL||'LEFT OUTER JOIN VEF_BASE_TTABCST'||:wPISCOF||' cstpis ON (cstpis.BDCODCST'||:wPISCOF||' = tmp.BDCODCST'||:wPISCOF||') ';
      wSQL = wSQL||'WHERE ((tmp.BDBC'||:wPISCOFINS||' > 0) OR (tmp.BDBC'||:wPISCOFINS||'_QUANT > 0)) ';
      wSQL = wSQL||  'AND ((tmp.BDALIQ'||:wPISCOFINS||' > 0) OR (tmp.BDALIQ'||:wPISCOFINS||'_QUANT > 0)) ';
      wSQL = wSQL||  'AND (cstpis.BDCODCST'||:wPISCOF||' IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND (tmp.BDCOD_CRED IS NOT NULL) ';
      wSQL = wSQL||  'AND ((tmp.BDCODTP <> 1) OR '; -- Apenas deve filtrar os lançamentos de produtos...
      wSQL = wSQL||       '(';-- Fiiltro dos código da base de cálculo de crétido...
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 01) AND '; -- Aquisição de Bens para Revenda
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1102,1113,1117,1118,1121,1251,1403,1652,2102,2113,2117,2118,2121,2251,2403,2652,3102,3251,3652))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 02) AND '; -- Aquisição de Bens Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1101,1111,1116,1120,1122,1126,1128,1135,1401,1407,1556,1651,1653,2101,2111,2116,2120,2122,2126,2128,2135,2401,2407,2556,2651,2653,3101,3126,3128,3556,3651,3653))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 03) AND '; -- Aquisição de Serviços Utilizados como Insumo
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1124,1125,1933,2124,2125,2933))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 12) AND '; -- Devolução de Vendas Sujeitas à Incidência Não-Cumulativa
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1201,1202,1203,1204,1206,1207,1410,1411,1660,1661,1662,2201,2202,2206,2207,2410,2411,2660,2661,2662))) OR ';
      wSQL = wSQL||        '((tmp.BDNAT_BC_CRED = 13) AND '; -- Outras Operações com Direito a Crédito
      wSQL = wSQL||         '(tmp.BDPREFIXONAT IN (1922,2922))) ';
      wSQL = wSQL||        ') ';
      wSQL = wSQL||       ') ';
      wSQL = wSQL||  'AND (tmp.BDNAT_BC_CRED <> 109) '; -- Não pode levar movimentação imobiliária...
      wSQL = wSQL||  'AND tmp.BDCODMATRIZ = '||iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)||' ';
      wSQL = wSQL||  'AND tmp.BDREFERENCIA = '||:prREFERENCIA||' ';

      wSQL = wSQL|| ' GROUP BY tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, tmp.BDCODCSTPIS, tmp.BDCODCSTCOF, tmp.BDNAT_BC_CRED, tmp.BDALIQ'||:wPISCOFINS||', tmp.BDALIQ'||:wPISCOFINS||'_QUANT, tmp.BDCOD_CRED, TMP.BDCODEMPSCP, t436.BDCODCRE_4_3_6, tmp.BDTIPOPROD ';
      IF (:PRTABELAREL = 1) THEN
        wSQL = wSQL|| ', BDORDEMPRO,BDCODTP,BDCODNAT,BDDESCTIPODOC,BDDESCPEREXP,BDDESCNATREC,BDDATANOTA, BDNUMDOC, BDCHAVELAN,  BDBC'||:wPISCOFINS||', BDVL_ITEM,  BDVLR'||:wPISCOFINS||',BDCONDPGTO ';
      wSQL = wSQL|| ') tmp ';

      if ((:PRAJUSTESCP = 'TRUE') and (:PRCODEMPSO > 0)) then
        wSQL = wSQL||'where (coalesce(tmp.BDCODEMPSCP, 0) = '||:PRCODEMP||'); ';
      else
      if (:PRAJUSTESCP = 'TRUE') then
        wSQL = wSQL||'where (coalesce(tmp.BDCODEMPSCP, 0) = 0); ';

      EXECUTE STATEMENT ( wSQL );


      IF (:PRTABELAREL = 0) THEN
        BEGIN
      /* REGISTRO M110: AJUSTES DO CRÉDITO DE PIS/PASEP APURADO */
      INSERT INTO VEF_EMP_TBLOCOM110_M510 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDCODAJUEFDC, BDIND_AJ, BDVL_AJ, BDNUM_DOC, BDDESCR_AJ, BDDT_REF, BDRETIFICADORA, BDTIPOPROD)
      SELECT 7 as BDCODPERIODO, COALESCE(SCP.BDCODEMPSCP,m.BDCODEMP) BDCODEMP, COALESCE(SCP.BDCODEMPSCP,COALESCE(emp.BDCODMATRIZ, m.BDCODEMP)) as BDCODMATRIZ, :prCODQUADRO as BDCODQUADRO, m.BDREFERENCIA,
             (SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODPERIODO = 7 AND X.BDRETIFICADORA = :PRRETIFICADORA AND x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,m.BDCODEMP) AND x.BDCODMATRIZ = COALESCE(SCP.BDCODEMPSCP,COALESCE(emp.BDCODMATRIZ, m.BDCODEMP)) AND x.BDCODQUADRO = :prCODQUADRO AND x.BDREFERENCIA = m.BDREFERENCIA AND x.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6 AND COALESCE(x.BDTIPOPROD,0) = COALESCE(m.BDTIPOPROD,0) AND ((x.BDALIQ = IIF(:prCODQUADRO = 11, m.BDALIQPIS, m.BDALIQCOFINS) and x.BDALIQ > 0) OR (x.BDALIQ_QUANT = IIF(:prCODQUADRO = 11, m.BDALIQPIS, m.BDALIQCOFINS) and x.BDALIQ_QUANT > 0))) as BDCHAVE,
             GETORDEMSEQUENCIAL_STR(IIF(:prCODQUADRO = 11, 'M110.', 'M510.')||7||'.'||m.BDCODEMP||'.'||COALESCE(emp.BDCODMATRIZ, m.BDCODEMP)||'.'||:prCODQUADRO||'.'||m.BDREFERENCIA||'.'||SCP.BDCODEMPSCP
             ||'.'||(SELECT x.BDCHAVE FROM VEF_EMP_TBLOCOM100_500 x WHERE x.BDCODPERIODO = 7 AND X.BDRETIFICADORA = :PRRETIFICADORA AND x.BDCODQUADRO = :prCODQUADRO AND x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,m.BDCODEMP)
             AND x.BDCODMATRIZ = COALESCE(SCP.BDCODEMPSCP,COALESCE(emp.BDCODMATRIZ, m.BDCODEMP)) AND x.BDREFERENCIA = m.BDREFERENCIA AND x.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6 AND COALESCE(x.BDTIPOPROD,0) = COALESCE(m.BDTIPOPROD,0)
             AND ((x.BDALIQ = IIF(:prCODQUADRO = 11, m.BDALIQPIS, m.BDALIQCOFINS) and x.BDALIQ > 0) OR (x.BDALIQ_QUANT = IIF(:prCODQUADRO = 11, m.BDALIQPIS, m.BDALIQCOFINS) and x.BDALIQ_QUANT > 0))), iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP))  as BDORDEM,
             m.BDCODAJUEFDC, m.BDTIPOAJUSTE as BDIND_AJ, SUM(IIF(:prCODQUADRO = 11, m.BDVLRAJUPIS, m.BDVLRAJUCOFINS)) as BDVL_AJ, m.BDNUMERODOC as BDNUM_DOC, m.BDDESCRICAO as BDDESCR_AJ, m.BDDATAREF as BDDT_REF, :PRRETIFICADORA BDRETIFICADORA, COALESCE(m.BDTIPOPROD,0) BDTIPOPROD
      FROM VEF_EMP_TCREDAJU_M110_M510 m
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m.BDCODEMP)
      LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = M.BDCODEMP AND SCP.BDCODSCP = M.BDCODSCP AND SCP.BDREFEMP = M.BDREFSOC)
      WHERE m.BDCODEMP in (SELECT ex.BDCODEMP
                           FROM TEMPRESAS ex
                           WHERE ex.BDCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)
                              OR ex.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)
                              )
        AND (((iif(:PRAJUSTESCP = 'TRUE' and :PRCODEMPSO > 0, 'TRUE', 'FALSE') = 'TRUE') and (coalesce(SCP.BDCODEMPSCP, 0) = :PRCODEMP)) or
             ((iif(:PRAJUSTESCP = 'TRUE' and :PRCODEMPSO = 0, 'TRUE', 'FALSE') = 'TRUE') and (coalesce(SCP.BDCODEMPSCP, 0) = 0)) or
             (:PRAJUSTESCP <> 'TRUE'))
        AND m.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT *
                    FROM VEF_EMP_TBLOCOM100_500 m100
                    WHERE m100.BDCODPERIODO = 7
                      AND M100.BDRETIFICADORA = :PRRETIFICADORA
                      AND m100.BDCODQUADRO = :prCODQUADRO
                      AND m100.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,m.BDCODEMP)
                      AND m100.BDREFERENCIA = m.BDREFERENCIA
                      AND m100.BDCODCRE_4_3_6 = m.BDCODCRE_4_3_6
                      AND COALESCE(m100.BDTIPOPROD,0) = COALESCE(m.BDTIPOPROD,0)
                      AND ((m100.BDALIQ = IIF(:prCODQUADRO = 11, m.BDALIQPIS, m.BDALIQCOFINS) and m100.BDALIQ > 0) OR (m100.BDALIQ_QUANT = IIF(:prCODQUADRO = 11, m.BDALIQPIS, m.BDALIQCOFINS) and m100.BDALIQ_QUANT > 0)) ))
      GROUP BY m.BDCODEMP, emp.BDCODMATRIZ, m.BDREFERENCIA, m.BDCODAJUEFDC, m.BDTIPOAJUSTE, m.BDNUMERODOC, m.BDDESCRICAO, m.BDDATAREF, m.BDCODCRE_4_3_6, m.BDTIPOPROD, IIF(:prCODQUADRO = 11, m.BDALIQPIS, m.BDALIQCOFINS),SCP.BDCODEMPSCP;
   
      /* REGISTRO M115: DETALHAMENTO DOS AJUSTES DO CRÉDITO DE PIS/PASEP APURADO */
      INSERT INTO VEF_EMP_TBLOCOM115_M515 (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDCODQUADRO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEM15, BDCODCSTCOF, BDCODCSTPIS, BDCODPLAPADRAO, BDCODTPLA, BDDET_VALOR_AJ, BDDET_BC_CRED, BDDET_ALIQ, BDDT_OPER_AJ, BDDESC_AJ, BDINFO_COMPL, BDRETIFICADORA)
      SELECT 7 as BDCODPERIODO, COALESCE(SCP.BDCODEMPSCP,m115.BDCODEMP) BDCODEMP, COALESCE(SCP.BDCODEMPSCP,COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)) as BDCODMATRIZ, :prCODQUADRO as BDCODQUADRO, m110.BDREFERENCIA,
             (SELECT First 1 x.BDCHAVE
              FROM VEF_EMP_TBLOCOM110_M510 x
              LEFT OUTER JOIN VEF_EMP_TBLOCOM100_500 M100 ON (M100.BDCODPERIODO = x.BDCODPERIODO AND M100.BDRETIFICADORA = X.BDRETIFICADORA AND
                                                              M100.BDCODEMP = X.BDCODEMP AND
                                                              M100.BDCODMATRIZ = X.BDCODMATRIZ AND M100.BDCODQUADRO = X.BDCODQUADRO AND
                                                              M100.BDREFERENCIA = X.BDREFERENCIA AND M100.BDCHAVE = X.BDCHAVE)
              WHERE x.BDCODPERIODO = 7
                AND X.BDRETIFICADORA = :PRRETIFICADORA
                AND x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,m115.BDCODEMP)
                AND x.BDCODMATRIZ = COALESCE(SCP.BDCODEMPSCP,COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP))
                AND x.BDCODQUADRO = :prCODQUADRO
                AND x.BDREFERENCIA = m110.BDREFERENCIA
                AND x.BDNUM_DOC = m110.BDNUMERODOC
                AND x.BDDESCR_AJ = m110.BDDESCRICAO
                AND x.BDDT_REF = m110.BDDATAREF
                AND ((M100.BDALIQ = IIF(:prCODQUADRO = 11, m115.BDALIQPIS, m115.BDALIQCOFINS) and m100.BDALIQ > 0) OR (M100.BDALIQ_QUANT = IIF(:prCODQUADRO = 11, m115.BDALIQPIS, m115.BDALIQCOFINS) and m100.BDALIQ_QUANT > 0))) as BDCHAVE,
             (SELECT First 1 x.BDORDEM
              FROM VEF_EMP_TBLOCOM110_M510 x
              LEFT OUTER JOIN VEF_EMP_TBLOCOM100_500 M100 ON (M100.BDCODPERIODO = x.BDCODPERIODO AND M100.BDRETIFICADORA = X.BDRETIFICADORA AND
                                                              M100.BDCODEMP = X.BDCODEMP AND
                                                              M100.BDCODMATRIZ = X.BDCODMATRIZ AND M100.BDCODQUADRO = X.BDCODQUADRO AND
                                                              M100.BDREFERENCIA = X.BDREFERENCIA AND M100.BDCHAVE = X.BDCHAVE)
              WHERE x.BDCODPERIODO = 7
                AND X.BDRETIFICADORA = :PRRETIFICADORA
                AND x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,m115.BDCODEMP)
                AND x.BDCODMATRIZ = COALESCE(SCP.BDCODEMPSCP,COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP))
                AND x.BDCODQUADRO = :prCODQUADRO
                AND x.BDREFERENCIA = m110.BDREFERENCIA
                AND x.BDNUM_DOC = m110.BDNUMERODOC
                AND x.BDDESCR_AJ = m110.BDDESCRICAO
                AND x.BDDT_REF = m110.BDDATAREF
                AND ((M100.BDALIQ = IIF(:prCODQUADRO = 11, m115.BDALIQPIS, m115.BDALIQCOFINS) and m100.BDALIQ > 0) OR (M100.BDALIQ_QUANT = IIF(:prCODQUADRO = 11, m115.BDALIQPIS, m115.BDALIQCOFINS) and m100.BDALIQ_QUANT > 0))) as BDORDEM,
             GETORDEMSEQUENCIAL_STR(IIF(:prCODQUADRO = 11, 'M115.', 'M515.')||7||'.'||m115.BDCODEMP||'.'||COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)||'.'||:prCODQUADRO||'.'||m110.BDREFERENCIA||'.'||SCP.BDCODEMPSCP
             ||'.'||(SELECT FIRST 1 x.BDCHAVE || '.' || x.BDORDEM FROM VEF_EMP_TBLOCOM110_M510 x LEFT OUTER JOIN VEF_EMP_TBLOCOM100_500 M100 ON (M100.BDCODPERIODO = x.BDCODPERIODO AND M100.BDRETIFICADORA = X.BDRETIFICADORA AND M100.BDCODEMP = X.BDCODEMP AND M100.BDCODMATRIZ = X.BDCODMATRIZ AND
                     M100.BDCODQUADRO = X.BDCODQUADRO AND M100.BDREFERENCIA = X.BDREFERENCIA AND M100.BDCHAVE = X.BDCHAVE) WHERE x.BDCODPERIODO = 7 AND X.BDRETIFICADORA = :PRRETIFICADORA AND x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,m115.BDCODEMP) AND
                     x.BDCODMATRIZ = COALESCE(SCP.BDCODEMPSCP,COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP)) AND x.BDCODQUADRO = :prCODQUADRO AND x.BDREFERENCIA = m110.BDREFERENCIA AND x.BDNUM_DOC = m110.BDNUMERODOC AND
                     x.BDDESCR_AJ = m110.BDDESCRICAO AND x.BDDT_REF = m110.BDDATAREF AND ((M100.BDALIQ = IIF(:prCODQUADRO = 11, m115.BDALIQPIS, m115.BDALIQCOFINS) and m100.BDALIQ > 0) OR (M100.BDALIQ_QUANT = IIF(:prCODQUADRO = 11, m115.BDALIQPIS, m115.BDALIQCOFINS) and m100.BDALIQ_QUANT > 0)))
             ,  iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP))  as BDORDEM15,
             m115.BDCODCSTCOF, m115.BDCODCSTPIS, m115.BDCODPLAPADRAO, m115.BDCODTPLA, SUM(IIF(:prCODQUADRO = 11, m110.BDVLRAJUPIS, m110.BDVLRAJUCOFINS)) as BDDET_VALOR_AJ, SUM(IIF(:prCODQUADRO = 11, m115.BDBCPIS,m115.BDBCCOFINS)) as BDDET_BC_CRED,
             IIF(:prCODQUADRO = 11, m115.BDALIQPIS, m115.BDALIQCOFINS) as BDDET_ALIQ, IIF(:prCODQUADRO = 11, m115.BDDATAOPEPIS, m115.BDDATAOPECOFINS) as BDDT_OPER_AJ, m115.BDDESCRICAOAJU as BDDESC_AJ, m115.BDINFCOMP as BDINFO_COMPL, :PRRETIFICADORA BDRETIFICADORA
      FROM VEF_EMP_TCREDAJU_M110_M510 m110
      JOIN VEF_EMP_TDETAJU_M115_M515 m115 on (m115.BDCODEMP = m110.BDCODEMP AND m115.BDCHAVE = m110.BDCHAVE)
      LEFT OUTER JOIN TEMPRESAS emp on (emp.BDCODEMP = m110.BDCODEMP)
      LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = m110.BDCODEMP AND SCP.BDCODSCP = m110.BDCODSCP AND SCP.BDREFEMP = m110.BDREFSOC)
      WHERE m115.BDCODEMP IS NOT NULL
        AND IIF(:prCODQUADRO = 11, m115.BDBCPIS,m115.BDBCCOFINS) > 0
        AND m110.BDCODEMP in (SELECT ex.BDCODEMP
                              FROM TEMPRESAS ex
                              WHERE ex.BDCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)
                                 OR ex.BDCODMATRIZ = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :prCODEMP)
                                 )
        AND (((iif(:PRAJUSTESCP = 'TRUE' and :PRCODEMPSO > 0, 'TRUE', 'FALSE') = 'TRUE') and (coalesce(SCP.BDCODEMPSCP, 0) = :PRCODEMP)) or
             ((iif(:PRAJUSTESCP = 'TRUE' and :PRCODEMPSO = 0, 'TRUE', 'FALSE') = 'TRUE') and (coalesce(SCP.BDCODEMPSCP, 0) = 0)) or
             (:PRAJUSTESCP <> 'TRUE'))
        AND m110.BDREFERENCIA = :prREFERENCIA
        AND (EXISTS(SELECT First 1 x.BDCHAVE
                    FROM VEF_EMP_TBLOCOM110_M510 x
                    LEFT OUTER JOIN VEF_EMP_TBLOCOM100_500 M100 ON (M100.BDCODPERIODO = x.BDCODPERIODO AND M100.BDRETIFICADORA = X.BDRETIFICADORA AND
                                                                    M100.BDCODEMP = X.BDCODEMP AND
                                                                    M100.BDCODMATRIZ = X.BDCODMATRIZ AND M100.BDCODQUADRO = X.BDCODQUADRO AND
                                                                    M100.BDREFERENCIA = X.BDREFERENCIA AND M100.BDCHAVE = X.BDCHAVE)
                    WHERE x.BDCODPERIODO = 7
                      AND X.BDRETIFICADORA = :PRRETIFICADORA
                      AND x.BDCODEMP = COALESCE(SCP.BDCODEMPSCP,m115.BDCODEMP)
                      AND x.BDCODMATRIZ = COALESCE(SCP.BDCODEMPSCP,COALESCE(emp.BDCODMATRIZ, m115.BDCODEMP))
                      AND x.BDCODQUADRO = :prCODQUADRO
                      AND x.BDREFERENCIA = m110.BDREFERENCIA
                      AND x.BDNUM_DOC = m110.BDNUMERODOC
                      AND x.BDDESCR_AJ = m110.BDDESCRICAO
                        AND x.BDDT_REF = m110.BDDATAREF
                        AND ((M100.BDALIQ = IIF(:prCODQUADRO = 11, m115.BDALIQPIS, m115.BDALIQCOFINS) and m100.BDALIQ > 0) OR (M100.BDALIQ_QUANT = IIF(:prCODQUADRO = 11, m115.BDALIQPIS, m115.BDALIQCOFINS) and m100.BDALIQ_QUANT > 0))))
      GROUP BY m115.BDCODEMP, emp.BDCODMATRIZ, m110.BDREFERENCIA, m110.BDCODCRE_4_3_6, m110.BDTIPOPROD, m115.BDCODCSTCOF, m115.BDCODCSTPIS, m115.BDCODPLAPADRAO, m115.BDCODTPLA,
               IIF(:prCODQUADRO = 11, m115.BDALIQPIS, m115.BDALIQCOFINS), IIF(:prCODQUADRO = 11, m115.BDDATAOPEPIS, m115.BDDATAOPECOFINS), m115.BDDESCRICAOAJU, m115.BDINFCOMP,
               m110.BDNUMERODOC, m110.BDDESCRICAO, m110.BDDATAREF,SCP.BDCODEMPSCP;
    END
    END
END
^

create or alter procedure SP_APURACAO_BLOCOM_M100 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRRETIFICADORA integer,
    PRTABELAREL integer)
as
BEGIN
-- Alterado para a SP_APURACAO_BLOCOM_M100M500 e será removida depois, confia...
END^

create or alter procedure SP_APURACAO_BLOCOM_M500 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRRETIFICADORA integer,
    PRTABELAREL integer)
as
BEGIN
-- Alterado para a SP_APURACAO_BLOCOM_M100M500 e será removida depois, confia...
END^

create or alter procedure SP_APURACAO_BLOCOM_M100_M500 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PREXECREL DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
declare variable WINCTRIB integer;
declare variable WMETODOAPRO integer;
declare variable WRBNCUMTRIBMI varchar(10000);
declare variable WRBNCUMNTMI varchar(10000);
declare variable WRBNCUMEXP varchar(10000);
declare variable WCODPERIODO integer;
declare variable WCODEMP integer;
declare variable WCODMATRIZ integer;
declare variable WCODQUADRO integer;
declare variable WREFERENCIA integer;
declare variable WCHAVE integer;
declare variable WCODCRE_4_3_6 integer;
declare variable WTIPOPROD integer;
declare variable WALIQ numeric(7,4);
declare variable WQTD integer;
declare variable WVL_BC numeric(15,2);
declare variable WCODPLANOONLINE integer;
declare variable WTIPOINTPIS integer;
declare variable WTIPOINTCOFINS integer;
BEGIN
  -- Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Carrega configuração da empresa na referência da apuração...
  SELECT BDINCTRIB+1, -- Incidência tributária
         BDMETODOAPRO+1 -- Método de apropriação
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wINCTRIB, :wMETODOAPRO;

  if ((:wINCTRIB is null) and (:PRCODEMPSO > 0)) then
    begin
      SELECT BDINCTRIB+1, BDMETODOAPRO+1
      FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMPSO
      INTO :wINCTRIB, :wMETODOAPRO;
    end

  /* 34 - Contribuição não cumulativa */
  SELECT BDRBNCUMTRIBMI, /* Tributada no mercado interno */
         BDRBNCUMNTMI,   /* Não Tributada no mercado interno */
         BDRBNCUMEXP     /* Exportação */
  FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :prCODEMP
  INTO :wRBNCUMTRIBMI, :wRBNCUMNTMI, :wRBNCUMEXP;

  -- Obtém o plano online
  SELECT r.bdCODPLANOONLINE
  FROM VW_TEMPRESAS_REF r
  WHERE r.bdCODEMP = :PRCODEMP
  INTO :wCODPLANOONLINE;

  -- Verifica se contabiliza normal ou por CFOP
  SELECT bdTIPOINTPIS, bdTIPOINTCOFINS
  FROM TPLANO_CONF_ONLINE
  WHERE bdCODPLANOONLINE = :wCODPLANOONLINE
  INTO :wTIPOINTPIS, :wTIPOINTCOFINS;

  IF ((wINCTRIB IS NOT NULL) AND (wINCTRIB <> 2)) THEN -- Diferente de "2 - Exclusivamente no regime cumulativo"
    BEGIN
      -- Preenche a tabela temporária numa SP auxiliar...
      EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M100_M500AUX(:prCODEMP, :prREFERENCIA,:prWHEREEMPRESAS,:PRAJUSTESCP, :PRCODEMPSO);

      /* Lançamentos com CSTs de rateio sem tem cofinguração de rateio preparada. #Inconsistências# */
      SELECT COUNT(*)
      FROM TMP_VEF_EMP_TBLOCOM_M100_M500 tmp
      LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS)
      LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF)
      WHERE ((cstpis.BDCSTPIS IN ('53','54','55','56','63','64','65','66')) OR
             (cstcof.BDCSTCOF IN ('53','54','55','56','63','64','65','66')))
      INTO :wQTD;

      IF (((:wINCTRIB IN (1,3)) AND (:wMETODOAPRO = 2)) AND -- 1 - Exclusivamente no regime não-cumulativo / 2 - Método de rateio proporcional
          (:wQTD >= 1) AND -- Existem lançamentos com AS CSTs de rateio, mas não tem as configurações de rateio preparadas...
          (((:wRBNCUMTRIBMI IS NULL) OR (:wRBNCUMTRIBMI = '')) OR  -- Tributada no Mercado Interno
           ((:wRBNCUMNTMI IS NULL) OR (:wRBNCUMNTMI = '')) OR    -- Não Tributada no Mercado Interno
           ((:wRBNCUMEXP IS NULL) OR (:wRBNCUMEXP = '')) )) THEN -- Exportação
        BEGIN
          IF ((prverificarinconsistencias = 'TRUE' )) then
            INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDRETIFICADORA) VALUES
                   (7, :prCODEMP, :prCODEMP, :prREFERENCIA, GETORDEMSEQUENCIAL_STR(:prCODEMP||'.'||:prCODEMP||'.'||:prREFERENCIA, :prCODEMP), NULL, NULL, NULL, NULL, 1, :PRRETIFICADORA);
        END
      ELSE
        BEGIN
          IF (:PREXECREL = 'FALSE') THEN
            Begin
              /* REGISTRO M100: CRÉDITO DE PIS/PASEP RELATIVO AO PERÍODO (Insere na tabela da apuração)*/
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M100M500 (11, :prCODEMP, :prREFERENCIA, :PRRETIFICADORA, 0, :PRAJUSTESCP, :PRCODEMPSO);
    
              /* REGISTRO M500: CRÉDITO DE COFINS RELATIVO AO PERÍODO (Insere na tabela da apuração)*/
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M100M500 (29, :prCODEMP, :prREFERENCIA, :PRRETIFICADORA, 0, :PRAJUSTESCP, :PRCODEMPSO);

              IF ((:WTIPOINTPIS = 4) OR (:WTIPOINTCOFINS = 4)) THEN
                BEGIN
                  /* REGISTRO M100: CRÉDITO DE PIS/PASEP RELATIVO AO PERÍODO (Insere na tabela de vínculo que é usada no relatório do bloco M)*/
                  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M100M500 (11, :prCODEMP, :prREFERENCIA, :PRRETIFICADORA, 1, :PRAJUSTESCP, :PRCODEMPSO);
                                 
                  /* REGISTRO M500: CRÉDITO DE COFINS RELATIVO AO PERÍODO (Insere na tabela de vínculo que é usada no relatório do bloco M)*/
                  EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M100M500 (29, :prCODEMP, :prREFERENCIA, :PRRETIFICADORA, 1, :PRAJUSTESCP, :PRCODEMPSO);
                END
            End
          Else
            Begin
              /* REGISTRO M100: CRÉDITO DE PIS/PASEP RELATIVO AO PERÍODO (Insere na tabela de vínculo que é usada no relatório do bloco M)*/
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M100M500 (11, :prCODEMP, :prREFERENCIA, :PRRETIFICADORA, 1, :PRAJUSTESCP, :PRCODEMPSO);
    
              /* REGISTRO M500: CRÉDITO DE COFINS RELATIVO AO PERÍODO (Insere na tabela de vínculo que é usada no relatório do bloco M)*/
              EXECUTE PROCEDURE SP_APURACAO_BLOCOM_M100M500 (29, :prCODEMP, :prREFERENCIA, :PRRETIFICADORA, 1, :PRAJUSTESCP, :PRCODEMPSO);
            End
        END
  IF (:PREXECREL = 'FALSE') THEN
    Begin
      /* Alt.: #141965 - Estava ficando com diferença entre os valores do M105/505 e os totalizadores nos M100/500, como faz alguns arredondamentos, acabava dando diferença de alguns centavos em valores muito grandes,
         por tanto foi ajustado para deixar preencher normalmente e ao final ajustar os totais do M100/500 com os valores dos registros M105/505, assim evitamos ter essas diferenças... */
      FOR
          SELECT m105.bdCODPERIODO, m105.bdCODEMP, m105.bdCODMATRIZ, m105.bdCODQUADRO, m105.bdREFERENCIA, m105.bdCHAVE, (SUM(Coalesce(m105.bdVL_BC,0)) + SUM(Coalesce(m105.bdquant_bc,0))) AS bdVL_BC
          FROM VEF_EMP_TBLOCOM105_M505 m105
          WHERE m105.bdCODMATRIZ = :prCODEMP
            AND m105.bdREFERENCIA = :prREFERENCIA
            AND M105.BDRETIFICADORA = :PRRETIFICADORA
          GROUP BY m105.bdCODPERIODO, m105.bdCODEMP, m105.bdCODMATRIZ, m105.bdCODQUADRO, m105.bdREFERENCIA, m105.bdCHAVE
          INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wVL_BC
      DO
        BEGIN
          UPDATE VEF_EMP_TBLOCOM100_500 m100
          SET m100.bdVL_BC = IIF(Coalesce(m100.bdALIQ,0) > 0,:wVL_BC,0),
              m100.bdquant_bc = IIF(Coalesce(m100.bdALIQ,0) > 0,0,:wVL_BC),
              m100.bdVL_CRED = IIF(Coalesce(m100.bdALIQ,0) > 0,(:wVL_BC*m100.bdALIQ)/100, (:wVL_BC*m100.bdALIQ_QUANT))
          WHERE m100.bdCODPERIODO = :wCODPERIODO
            AND m100.bdCODEMP = :wCODEMP
            AND m100.bdCODMATRIZ = :wCODMATRIZ
            AND m100.bdCODQUADRO = :wCODQUADRO
            AND m100.bdREFERENCIA = :wREFERENCIA
            AND m100.bdCHAVE = :wCHAVE
            AND M100.BDRETIFICADORA = :PRRETIFICADORA;
        END

      /* Atualiza os valores após inserir, não faz no INSERT/SELECT acima para não matriciar */
      FOR
          SELECT x.BDCODPERIODO, x.BDCODEMP, x.BDCODMATRIZ, x.BDCODQUADRO, x.BDREFERENCIA, x.BDCHAVE, x.BDCODCRE_4_3_6, x.BDTIPOPROD, x.BDALIQ
          FROM VEF_EMP_TBLOCOM100_500 x
          WHERE x.BDCODMATRIZ = :prCODEMP
            AND x.BDREFERENCIA = :prREFERENCIA
            AND X.BDRETIFICADORA = :PRRETIFICADORA
          UNION ALL
          SELECT x.BDCODPERIODO, x.BDCODEMP, x.BDCODMATRIZ, x.BDCODQUADRO, x.BDREFERENCIA, x.BDCHAVE, x.BDCODCRE_4_3_6, x.BDTIPOPROD, x.BDALIQ
          FROM (
                SELECT SCP.BDCODEMPSCP
                FROM TEMPRESAS_SCP SCP
                --WHERE SCP.BDCODEMP = :prCODEMP
                WHERE scp.BDCODEMP in(SELECT ex.BDCODEMP
                                      FROM TEMPRESAS ex
                                      WHERE ex.BDCODEMP = :prCODEMP
                                         OR ex.BDCODMATRIZ = :prCODEMP)
               ) SCP
          JOIN VEF_EMP_TBLOCOM100_500 x ON (x.BDCODMATRIZ = SCP.BDCODEMPSCP AND x.BDREFERENCIA = :prREFERENCIA AND X.BDRETIFICADORA = :PRRETIFICADORA)
          INTO :wCODPERIODO, :wCODEMP, :wCODMATRIZ, :wCODQUADRO, :wREFERENCIA, :wCHAVE, :wCODCRE_4_3_6, :wTIPOPROD, :wALIQ
      DO
        BEGIN
          /* Verifica o quadros para pegar os campos corretos, PIS ou Cofins */
          /* Quando alterar os SELECTs dos campos, não esquecer de atualizar os SELECTs dos campos 12 e 14... */
          UPDATE VEF_EMP_TBLOCOM100_500 x
          SET -- 09 - VL_AJUS_ACRES - Valor total dos ajustes de acréscimo
              x.BDVL_AJUS_ACRES = (COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRAJUPIS,0), COALESCE(x.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TCREDAJU_M110_M510 x WHERE x.BDTIPOAJUSTE = 1 AND x.BDCODEMP = :wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6 AND COALESCE(x.BDTIPOPROD,0) = COALESCE(:wTIPOPROD,0) AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0)),
              -- 10 - VL_AJUS_REDUC - Valor total dos ajustes de redução
              x.BDVL_AJUS_REDUC = (COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRAJUPIS,0), COALESCE(x.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TCREDAJU_M110_M510 x WHERE x.BDTIPOAJUSTE = 0 AND x.BDCODEMP = :wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6 AND COALESCE(x.BDTIPOPROD,0) = COALESCE(:wTIPOPROD,0) AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0)),
              -- 11 - VL_CRED_DIF - Valor total do crédito diferido no períod
              x.BDVL_CRED_DIF   = (COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRCREDEFPIS,0), COALESCE(x.BDVLRCREDEPCOFINS,0))) FROM VEF_EMP_TINFADIDEFM230630 x WHERE x.BDCODEMP =:wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6 AND COALESCE(x.BDTIPOPROD,0) = COALESCE(:wTIPOPROD,0) AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0)),
              -- 12 - VL_CRED_DISP - Valor Total do Crédito Disponível relativo ao Período (08 + 09 - 10 - 11)
              x.BDVL_CRED_DISP  = ( /*08*/COALESCE(x.BDVL_CRED,0)
                                   +/*09*/(COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRAJUPIS,0), COALESCE(x.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TCREDAJU_M110_M510 x WHERE x.BDTIPOAJUSTE = 1 AND x.BDCODEMP = :wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6 AND COALESCE(x.BDTIPOPROD,0) = COALESCE(:wTIPOPROD,0) AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0))
                                   -/*10*/(COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRAJUPIS,0), COALESCE(x.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TCREDAJU_M110_M510 x WHERE x.BDTIPOAJUSTE = 0 AND x.BDCODEMP = :wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6 AND COALESCE(x.BDTIPOPROD,0) = COALESCE(:wTIPOPROD,0) AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0))
                                   -/*11*/(COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRCREDEFPIS,0), COALESCE(x.BDVLRCREDEPCOFINS,0))) FROM VEF_EMP_TINFADIDEFM230630 x WHERE x.BDCODEMP =:wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6 AND COALESCE(x.BDTIPOPROD,0) = COALESCE(:wTIPOPROD,0) AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0))
                                   ),
              -- 13 - IND_DESC_CRED - Indicador de opção de utilização do crédito disponível no período: 0 - Utilização do valor total para desconto da contribuição apurada no período, no Registro M200; 1 - Utilização de valor parcial para desconto da contribuição apurada no período, no Registro M200.
              x.BDIND_DESC_CRED = 0, -- Por padr?o vai levar sempre como "0", por?m caso utilize parcialmente, vai atualizar na apura??o do M200/M600.
              -- 14 - VL_CRED_DESC - Valor do Crédito disponível, descontado da contribuição apurada no próprio período.
              --    Se IND_DESC_CRED=0, informar o valor total do Campo 12;
              --    Se IND_DESC_CRED=1, informar o valor parcial do Campo 12.
              x.BDVL_CRED_DESC  = ( /*08*/COALESCE(x.BDVL_CRED,0)
                                   +/*09*/(COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRAJUPIS,0), COALESCE(x.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TCREDAJU_M110_M510 x WHERE x.BDTIPOAJUSTE = 1 AND x.BDCODEMP = :wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6 AND COALESCE(x.BDTIPOPROD,0) = COALESCE(:wTIPOPROD,0) AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0))
                                   -/*10*/(COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRAJUPIS,0), COALESCE(x.BDVLRAJUCOFINS,0))) FROM VEF_EMP_TCREDAJU_M110_M510 x WHERE x.BDTIPOAJUSTE = 0 AND x.BDCODEMP = :wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6 AND COALESCE(x.BDTIPOPROD,0) = COALESCE(:wTIPOPROD,0) AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0))
                                   -/*11*/(COALESCE((SELECT SUM(IIF((:wCODQUADRO = 11), COALESCE(x.BDVLRCREDEFPIS,0), COALESCE(x.BDVLRCREDEPCOFINS,0))) FROM VEF_EMP_TINFADIDEFM230630 x WHERE x.BDCODEMP =:wCODEMP AND x.BDREFERENCIA = :wREFERENCIA AND x.BDCODCRE_4_3_6 = :wCODCRE_4_3_6 AND COALESCE(x.BDTIPOPROD,0) = COALESCE(:wTIPOPROD,0) AND ((:wCODQUADRO = 11 AND x.BDALIQPIS = :wALIQ) OR (:wCODQUADRO = 29 AND x.BDALIQCOFINS = :wALIQ))),0))
                                   ),
              -- 15 - SLD_CRED - Saldo de créditos a utilizar em períodos futuros (12 - 14)
              x.BDSLD_CRED      = 0
          WHERE x.BDCODPERIODO = :wCODPERIODO
            AND x.BDCODEMP = :wCODEMP
            AND x.BDCODMATRIZ = :wCODMATRIZ
            AND x.BDCODQUADRO = :wCODQUADRO
            AND x.BDREFERENCIA = :wREFERENCIA
            AND x.BDCHAVE = :wCHAVE
            AND X.BDRETIFICADORA = :PRRETIFICADORA;
        END

      /* 08 - Lançamento sem natureza do crédito informada.  #Inconsistência# */
      IF ((prverificarinconsistencias = 'TRUE' )) then
        BEGIN
          INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDRETIFICADORA)
          SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(tmp.bdcodmatriz||'.'||tmp.bdcodemp||'.'||tmp.bdreferencia, :prCODEMP) AS BDCODBLOCOM, tmp.BDCODTP, tmp.BDCHAVE, tmp.BDORDEM, tmp.BDORDEMPRO, 8 AS BDCODINC,
                 :PRRETIFICADORA BDRETIFICADORA
          FROM TMP_VEF_EMP_TBLOCOM_M100_M500 tmp
          LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS)
          LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF)
          LEFT OUTER JOIN VEF_EMP_TMOVPROENT ent on (ent.BDCODEMP = tmp.BDCODEMP and ent.BDCHAVE = tmp.BDCHAVE and ent.BDORDEM = tmp.BDORDEM and ent.BDORDEMPRO = tmp.BDORDEMPRO and 1 = tmp.BDCODTP)
          LEFT OUTER JOIN VEF_EMP_TMOVSER ser on (ser.BDCODEMP = tmp.BDCODEMP and ser.BDCHAVE = tmp.BDCHAVE and 3 = tmp.BDCODTP)
          LEFT OUTER JOIN VEF_EMP_TA170 a170 on (a170.BDCODEMP = tmp.BDCODEMP AND a170.BDCHAVE = tmp.BDCHAVE AND a170.BDORDEM = tmp.BDORDEM and a170.BDNUM_ITEM = tmp.BDORDEMPRO and 3 = tmp.BDCODTP)
          LEFT OUTER JOIN VEF_EMP_TMOVDEMAISDOC_F100 dem on (dem.BDCODEMP = tmp.BDCODEMP and dem.BDCHAVE = tmp.BDCHAVE and 4 = tmp.BDCODTP)
          LEFT OUTER JOIN VEF_EMP_TD100ENT d100 on (d100.BDCODEMP = tmp.BDCODEMP and d100.BDCHAVE = tmp.BDCHAVE and 10 = tmp.BDCODTP)
          LEFT OUTER JOIN VEF_BASE_TCADTIPODEMDOC CAD on (dem.BDCODTIPODOC = CAD.BDCODTIPODOC)
          LEFT OUTER JOIN VEF_EMP_TD500ENT d500 on (d500.BDCODEMP = tmp.BDCODEMP and d500.BDCHAVE = tmp.BDCHAVE and 11 = tmp.BDCODTP)
          LEFT OUTER JOIN VEF_EMP_TC500ENT c500 on (c500.BDCODEMP = tmp.BDCODEMP and c500.BDCHAVE = tmp.BDCHAVE and 12 = tmp.BDCODTP)
          --LEFT OUTER JOIN VEF_EMP_TMOVOPIMOBI_F200_PGTO f200 on (f200.BDCODEMP = tmp.BDCODEMP and f200.BDCODBEM = tmp.BDCHAVE and 14 = tmp.BDCODTP)
          LEFT OUTER JOIN EMPRESAS_TBEM bem on (bem.BDCODEMP = tmp.BDCODEMP and bem.BDCODBEM = tmp.BDCHAVE and 15 = tmp.BDCODTP)
          WHERE ((cstpis.BDCODCSTPIS IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) OR (cstcof.BDCODCSTCOF IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)))
            AND tmp.BDCODMATRIZ = :prCODEMP
            AND ((CAD.BDNAOEXPSPED = 'FALSE') or (CAD.BDNAOEXPSPED is null))
            AND tmp.BDREFERENCIA = :prREFERENCIA
            AND (((tmp.BDCODTP = 1) and (ent.BDCODNATBC IS NULL)) or -- Entradas
                 ((tmp.BDCODTP = 3) and (ser.BDTIPLAN = 1) and (a170.BDNAT_BC_CRED IS NULL)) or -- Serviços Recebidos
                 ((tmp.BDCODTP = 4) and (dem.BDIND_OPER = 1) and (dem.BDNAT_BC_CRED IS NULL)) or -- Demais documentos, Operação Representativa de Aquisição...
                 ((tmp.BDCODTP = 10) and (d100.BDCODNATBC IS NULL)) or -- Entradas - Transporte (D100)
                 ((tmp.BDCODTP = 11) and (d500.BDCODNATBC IS NULL)) or -- Entradas - Serviço de comunicação e telecomunicação (D500)
                 ((tmp.BDCODTP = 12) and ((c500.bdcodnatbc IS NULL) and (tmp.bdnat_bc_cred IS NULL))) or -- Entradas - Nota fiscal de conta de energia elétrica, água ou gás (C500)
                 --((tmp.BDCODTP = 14) and (f200.BDCODNATBC IS NULL)) or -- Baixa do F200, aqui joga fixo...
                 ((tmp.BDCODTP = 15) and (bem.BDTIPOAPROCRED IS NULL)) ); -- Bens
    
          /* 09 - Natureza da base de calculo do crédito inválida para CFOP lançada.  #Inconsistência# */
          INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDRETIFICADORA)
          SELECT 7 AS BDCODPERIODO, tmp.BDCODEMP, tmp.BDCODMATRIZ, tmp.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(tmp.bdcodmatriz||'.'||tmp.bdcodemp||'.'||tmp.bdreferencia, :prCODEMP) AS BDCODBLOCOM, tmp.BDCODTP, tmp.BDCHAVE, tmp.BDORDEM, tmp.BDORDEMPRO, 9 AS BDCODINC,
                 :PRRETIFICADORA BDRETIFICADORA
          FROM TMP_VEF_EMP_TBLOCOM_M100_M500 tmp
          LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON (cstpis.BDCODCSTPIS = tmp.BDCODCSTPIS)
          LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON (cstcof.BDCODCSTCOF = tmp.BDCODCSTCOF)
          LEFT OUTER JOIN VEF_EMP_TMOVSER ser ON (ser.BDCODEMP = tmp.BDCODEMP AND ser.BDCHAVE = tmp.BDCHAVE AND 3 = tmp.BDCODTP)
          WHERE ((cstpis.BDCODCSTPIS IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)) OR (cstcof.BDCODCSTCOF IN (50,51,52,53,54,55,56,60,61,62,63,64,65,66)))
            AND (tmp.BDNAT_BC_CRED IS NOT NULL)
            AND (tmp.BDCODTP = 1) -- Apenas deve filtrar os lançamentos de produtos...
            AND (-- Fiiltro dos código da base de cálculo de crétido...
                 ((tmp.BDNAT_BC_CRED <> 01) AND -- Aquisição de Bens para Revenda
                  (tmp.BDPREFIXONAT IN (1102,1113,1117,1118,1121,1251,1403,1652,2102,2113,2117,2118,2121,2251,2403,2652,3102,3251,3652))) OR
                 ((tmp.BDNAT_BC_CRED <> 02) AND -- Aquisição de Bens Utilizados como Insumo
                  (tmp.BDPREFIXONAT IN (1101,1111,1116,1120,1122,1126,1128,1401,1407,1556,1651,1653,2101,2111,2116,2120,2122,2126,2128,2401,2407,2556,2651,2653,3101,3126,3128,3556,3651,3653))) OR
                 ((tmp.BDNAT_BC_CRED <> 03) AND -- Aquisição de Serviços Utilizados como Insumo
                  (tmp.BDPREFIXONAT IN (1124,1125,1933,2124,2125,2933))) OR
                 ((tmp.BDNAT_BC_CRED <> 12) AND -- Devolução de Vendas Sujeitas à Incidência Não-Cumulativa
                  (tmp.BDPREFIXONAT IN (1201,1202,1203,1204,1410,1411,1660,1661,1662,2201,2202,2410,2411,2660,2661,2662))) OR
                 ((tmp.BDNAT_BC_CRED <> 13) AND -- Outras Operações com Direito a Crédito
                  (tmp.BDPREFIXONAT IN (1922,2922)))
                 )
            AND tmp.BDCODEMP = :prCODEMP
            AND tmp.BDCODMATRIZ = :prCODEMP
            AND tmp.BDREFERENCIA = :prREFERENCIA;

        
            INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDRETIFICADORA, BDREPLACES)
            SELECT 7 AS BDCODPERIODO, AUX.BDCODEMP, AUX.BDCODMATRIZ, AUX.BDREFERENCIA,
                   GETORDEMSEQUENCIAL_STR(AUX.BDCODMATRIZ || '.' || AUX.BDCODEMP || '.' || AUX.BDREFERENCIA, :PRCODEMP) AS BDCODBLOCOM,
                   AUX.BDCODTP, AUX.BDCHAVE, AUX.BDORDEM, AUX.BDORDEMPRO,
                   CASE
                     WHEN ((COALESCE(AUX.BDBCPIS, 0) = 0 AND COALESCE (BDBCPIS_QUANT, 0) = 0) AND COALESCE(AUX.BDVLRPIS, 0) = 0) THEN 35
                     WHEN ((COALESCE(AUX.BDBCPIS, 0) = 0 AND COALESCE (BDBCPIS_QUANT, 0) = 0) AND COALESCE(AUX.BDVLRPIS, 0) > 0) THEN 36
                     WHEN ((COALESCE(AUX.BDBCPIS, 0) > 0 OR COALESCE (BDBCPIS_QUANT, 0) > 0) AND  COALESCE(AUX.BDVLRPIS, 0) = 0) THEN 37
                     ELSE 35
                   END AS BDCODINC, :PRRETIFICADORA AS BDRETIFICADORA, LPAD(CAST(AUX.BDCODCSTPIS AS VARCHAR(2)), 2, '0') AS BDREPLACES
            FROM TMP_VEF_EMP_TBLOCOM_M100_M500 AUX
            WHERE AUX.BDCODTP IN (1, 2, 3, 4) AND
                  AUX.BDCODMATRIZ = :PRCODEMP AND
                  AUX.BDREFERENCIA = :PRREFERENCIA AND
                  AUX.BDCODCSTPIS IS NOT NULL AND
                  ((AUX.BDCODCSTPIS in (1, 2, 3, 50, 51, 52, 53, 54, 56) and ((coalesce(AUX.BDBCPIS, 0) = 0 and coalesce(AUX.BDBCPIS_QUANT, 0) = 0) or coalesce(AUX.BDVLRPIS, 0) = 0)) or
                  ((AUX.BDCODCSTPIS not in (4, 5, 6, 49, 55, 65, 70, 71, 72, 73, 74, 75, 98, 99)) and (coalesce(AUX.BDBCPIS, 0) > 0 or coalesce(AUX.BDBCPIS_QUANT, 0) > 0) and (coalesce(AUX.BDVLRPIS, 0) = 0)) or
                  (((coalesce(AUX.BDALIQPIS, 0) > 0) OR COALESCE(AUX.BDALIQPIS_QUANT, 0) > 0) and ((coalesce(AUX.BDBCPIS, 0) > 0 or coalesce(AUX.BDBCPIS_QUANT, 0) > 0) and (coalesce(AUX.BDVLRPIS, 0) = 0))));
        
            INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDRETIFICADORA, BDREPLACES)
            SELECT 7 AS BDCODPERIODO, AUX.BDCODEMP, AUX.BDCODMATRIZ, AUX.BDREFERENCIA,
                   GETORDEMSEQUENCIAL_STR(AUX.BDCODMATRIZ || '.' || AUX.BDCODEMP || '.' || AUX.BDREFERENCIA, :PRCODEMP) AS BDCODBLOCOM,
                   AUX.BDCODTP, AUX.BDCHAVE, AUX.BDORDEM, AUX.BDORDEMPRO,
                   CASE
                     WHEN ((COALESCE(AUX.BDBCCOFINS, 0) = 0 AND COALESCE (AUX.BDBCCOFINS_QUANT, 0) = 0) AND COALESCE(AUX.BDVLRCOFINS, 0) = 0) THEN 32
                     WHEN ((COALESCE(AUX.BDBCCOFINS, 0) = 0 AND COALESCE (AUX.BDBCCOFINS_QUANT, 0) = 0) AND COALESCE(AUX.BDVLRCOFINS, 0) > 0) THEN 33
                     WHEN ((COALESCE(AUX.BDBCCOFINS, 0) > 0 OR COALESCE (BDBCCOFINS_QUANT, 0) > 0) AND NOT COALESCE(AUX.BDVLRCOFINS, 0) > 0) THEN 34
                     ELSE 32 -- PADRÃO SE NENHUMA DAS CONDIÇÕES ESPECÍFICAS FOR ATENDIDA
                   END AS BDCODINC, :PRRETIFICADORA AS BDRETIFICADORA, LPAD(CAST(AUX.BDCODCSTCOF AS VARCHAR(2)), 2, '0') AS BDREPLACES
            FROM TMP_VEF_EMP_TBLOCOM_M100_M500 AUX
            WHERE AUX.BDCODTP IN (1, 2, 3, 4) AND
                  AUX.BDCODMATRIZ = :PRCODEMP AND
                  AUX.BDREFERENCIA = :PRREFERENCIA AND
                  AUX.BDCODCSTCOF IS NOT NULL AND
                  ((AUX.BDCODCSTCOF in (1, 2, 3, 50, 51, 52, 53, 54, 56) and ((coalesce(AUX.BDBCCOFINS, 0) = 0 and coalesce(AUX.BDBCCOFINS_QUANT, 0) = 0) or coalesce(AUX.BDVLRCOFINS, 0) = 0)) or
                  ((AUX.BDCODCSTCOF not in (4, 5, 6, 49, 55, 65, 70, 71, 72, 73, 74, 75, 98, 99)) and (coalesce(AUX.BDBCCOFINS, 0) > 0 or coalesce(AUX.BDBCCOFINS_QUANT, 0) > 0) and (coalesce(AUX.BDVLRCOFINS, 0) = 0)) or
                  (((coalesce(AUX.BDALIQCOFINS, 0) > 0) OR COALESCE(AUX.BDALIQCOFINS_QUANT, 0) > 0) and ((coalesce(AUX.BDBCCOFINS, 0) > 0 or coalesce(AUX.BDBCCOFINS_QUANT, 0) > 0) and (coalesce(AUX.BDVLRCOFINS, 0) = 0))));
        
        
            INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDRETIFICADORA, BDREPLACES)
            SELECT 7 AS BDCODPERIODO, AUX.BDCODEMP, AUX.BDCODMATRIZ, AUX.BDREFERENCIA,
                   GETORDEMSEQUENCIAL_STR(AUX.BDCODMATRIZ || '.' || AUX.BDCODEMP || '.' || AUX.BDREFERENCIA, :PRCODEMP) AS BDCODBLOCOM,
                   AUX.BDCODTP, AUX.BDCHAVE, AUX.BDORDEM, AUX.BDORDEMPRO, 39 AS BDCODINC, :PRRETIFICADORA AS BDRETIFICADORA, LPAD(CAST(AUX.BDCODCSTPIS AS VARCHAR(2)), 2, '0') AS BDREPLACES
            FROM TMP_VEF_EMP_TBLOCOM_M100_M500 AUX
            WHERE AUX.BDCODTP IN (1, 2, 3, 4) AND
                  AUX.BDCODMATRIZ = :PRCODEMP AND
                  AUX.BDREFERENCIA = :PRREFERENCIA AND
                  ((AUX.BDCODCSTPIS NOT IN (4, 5, 6, 49, 55, 65, 70, 71, 72, 73, 74, 75, 98, 99) AND AUX.BDCODCSTPIS IS NOT NULL AND (coalesce(AUX.BDBCPIS, 0) > 0 or coalesce(AUX.BDBCPIS_QUANT, 0) > 0)) OR
                  (AUX.BDCODCSTPIS in (1, 2, 3, 50, 51, 52, 53, 54, 56))) AND
                  (COALESCE(AUX.BDALIQPIS, 0) = 0 AND COALESCE(AUX.BDALIQPIS_QUANT, 0) = 0);

        
            INSERT INTO VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE,
                                          BDORDEM, BDORDEMPRO, BDCODINC, BDRETIFICADORA, BDREPLACES)
            SELECT 7 AS BDCODPERIODO, AUX.BDCODEMP, AUX.BDCODMATRIZ, AUX.BDREFERENCIA,
                   GETORDEMSEQUENCIAL_STR(AUX.BDCODMATRIZ || '.' || AUX.BDCODEMP || '.' || AUX.BDREFERENCIA, :PRCODEMP) AS BDCODBLOCOM,
                   AUX.BDCODTP, AUX.BDCHAVE, AUX.BDORDEM, AUX.BDORDEMPRO, 38 AS BDCODINC, :PRRETIFICADORA AS BDRETIFICADORA, LPAD(CAST(AUX.BDCODCSTCOF AS VARCHAR(2)), 2, '0') AS BDREPLACES
            FROM TMP_VEF_EMP_TBLOCOM_M100_M500 AUX
            WHERE AUX.BDCODTP IN (1, 2, 3, 4) AND
                  AUX.BDCODMATRIZ = :PRCODEMP AND
                  AUX.BDREFERENCIA = :PRREFERENCIA AND
                  ((AUX.BDCODCSTCOF NOT IN (4, 5, 6, 49, 55, 65, 70, 71, 72, 73, 74, 75, 98, 99) AND AUX.BDCODCSTCOF IS NOT NULL AND (coalesce(AUX.BDBCCOFINS, 0) > 0 or coalesce(AUX.BDBCCOFINS_QUANT, 0) > 0)) OR
                  (AUX.BDCODCSTCOF in (1, 2, 3, 50, 51, 52, 53, 54, 56))) AND
                  (COALESCE(AUX.BDALIQCOFINS, 0) = 0 AND COALESCE(AUX.BDALIQCOFINS_QUANT, 0) = 0);
        END
    END
    End
END
^

create or alter procedure SP_APURACAO_RET1800AUX (
    PRCODEMP integer,
    PRREFERENCIA integer,
    BDCODREC varchar(10),
    BDCAMPOREC varchar(25))
as
declare variable WSQL varchar(32750);
begin

 /****************************************************************************************************************************
 **   DADOS AGRUPADOS - SEPARADO NUMA PROCEDURE POIS DEVE SER EXECUTADO PARA CADA CÓDIGO DE RECEITA(EXIGIBILIDADE SUSPENSA) **
 *****************************************************************************************************************************/


  WSQL = ' INSERT INTO VEF_EMP_TRET1800TOT(BDCNPJINCORP,BDCODMATRIZ,BDCODEMP, BDREFERENCIA,BDCHAVETOT,BDCHAVEUNI,BDCODREC,BDCODINCORP,BDVLRRECORIGINAL, BDVLRRECFIN,BDVLRDESCONTO,BDVLRDISTRADO,BDBASECALCULO,BDALIQUOTA,BDVALOR,BDVARIACAO) ';
  WSQL = WSQL||' SELECT TMP.BDCNPJINCORP,TMP.BDCODMATRIZ, TMP.BDCODEMP,'||:PRREFERENCIA||', GETORDEMSEQUENCIAL_STR(TMP.BDCODEMP||''.''||TMP.BDCODMATRIZ||''.''||'||:PRREFERENCIA||', '||:prCODEMP||') ,TMP.BDCHAVE, TMP.BDCHAVEREC BDCODREC, ';
  WSQL = WSQL||' (SELECT BDCODINCORP FROM VEF_EMP_TCADINCORPORADORA WHERE BDCODEMP = TMP.BDCODMATRIZ AND BDCNPJINCORP = TMP.BDCNPJINCORP), ';
  WSQL = WSQL||' TMP.BDVLRRECORIGINAL,TMP.BDVLRRECFIN,TMP.BDVLRDESCONTO,TMP.BDVLRDISTRATO, ';
  WSQL = WSQL||' TMP.BDBASECALCULO,TMP.BDALIQUOTA,0 BDVALOR, ';
  WSQL = WSQL||' TMP.BDVARIACAOREC ';
  WSQL = WSQL||' FROM( ';
  WSQL = WSQL||'     SELECT TMP.BDCNPJINCORP, TMP.BDCODEMP, TMP.BDCODMATRIZ, TMP.BDCHAVE, TMP.BDCODREC, ';
  WSQL = WSQL||'     TMP.BDVLRRECORIGINAL,TMP.BDVLRRECFIN,TMP.BDVLRDESCONTO,TMP.BDVLRDISTRATO, TMP.BDALIQUOTA,0 BDBASECALCULO , ';
  WSQL = WSQL||'     TMP.BDVARIACAOREC,TMP.BDVLRREC,TMP.BDCHAVEREC ';
  WSQL = WSQL||'     FROM( ';
 -- WSQL = WSQL||'          SELECT IIF((TMP.BDCODREC = ''1068'' AND TMP.BDVARIACAOREC = 2) OR (TMP.BDCODREC = ''1068'' AND TMP.BDVARIACAOREC = 6),coalesce(TMP.BDCNPJMATRIZ, TMP.BDCNPJEMP),TMP.BDCNPJINCORP) BDCNPJINCORP, ';
  WSQL = WSQL||'          SELECT COALESCE(TMP.BDCNPJINCORP,COALESCE(TMP.BDCNPJMATRIZ, TMP.BDCNPJEMP)) BDCNPJINCORP,  ';
  WSQL = WSQL||'          BDCODMATRIZ BDCODEMP, TMP.BDCODMATRIZ,TMP.BDCHAVE, TMP.BDCODREC,SUM(TMP.BDVLRRECORIGINAL) BDVLRRECORIGINAL,SUM(TMP.BDVLRRECFIN) BDVLRRECFIN, SUM(TMP.BDVLRDESCONTO) BDVLRDESCONTO, SUM(TMP.BDVLRDISTRATO) BDVLRDISTRATO, ';
  WSQL = WSQL||'          TMP.BDALIQUOTA, SUM(TMP.BDVLRREC) BDVLRREC, TMP.BDVARIACAOREC,(SELECT FIRST 1 BDCODREC FROM TCODREC WHERE BDCODRECOF = TMP.BDCODREC) BDCHAVEREC';
  WSQL = WSQL||'          FROM( ';
  WSQL = WSQL||'               SELECT TMP.BDCODEMP, COALESCE(TMP.BDCODMATRIZ,TMP.BDCODEMP) BDCODMATRIZ,TMP.BDCHAVE,TMP.BDCHAVELAN, SUBSTRING('||:BDCAMPOREC||' FROM 1 FOR 4) BDCODREC, ';
  WSQL = WSQL||'               CAST(SUBSTRING('||:BDCAMPOREC||' FROM 6 FOR 6) AS INTEGER) BDVARIACAOREC, TMP.BDCNPJINCORP, ';
  WSQL = WSQL||'               TMP.BDVLRORIGPARCELA BDVLRRECORIGINAL, TMP.BDVLRRECFIN, TMP.BDDESCONTOPAR BDVLRDESCONTO, COALESCE(TMP.BDVLRCONSUDIST,0) BDVLRDISTRATO, EMP.BDCNPJEMP BDCNPJMATRIZ, ';
  WSQL = WSQL||'               CASE '||:BDCAMPOREC;
  WSQL = WSQL||'               WHEN ''1068-1'' THEN 1 WHEN ''1068-2'' THEN 1 WHEN ''1068-6'' THEN 1    WHEN ''1068-7'' THEN 1 ';
  WSQL = WSQL||'               WHEN ''4095-1'' THEN 4 WHEN ''4095-2'' THEN 4 WHEN ''4112-1'' THEN 1.26 WHEN ''4112-2'' THEN 0.31 WHEN ''4112-3'' THEN 0.31 ' ;
  WSQL = WSQL||'               WHEN ''4112-6'' THEN 0.31 WHEN ''4112-7'' THEN 1.26 WHEN ''4112-8'' THEN 0.31 WHEN ''4138-1'' THEN 0.37 WHEN ''4138-2'' THEN 0.09 ';
  WSQL = WSQL||'               WHEN ''4138-3'' THEN 0.09 WHEN ''4138-6'' THEN 0.09 WHEN ''4138-7'' THEN 0.37 WHEN ''4138-8'' THEN 0.09 WHEN ''4153-1'' THEN 0.66 ';
  WSQL = WSQL||'               WHEN ''4153-2'' THEN 0.16 WHEN ''4153-3'' THEN 0.16 WHEN ''4153-6'' THEN 0.16 WHEN ''4153-7'' THEN 0.66 WHEN ''4153-8'' THEN 0.16 ';
  WSQL = WSQL||'               WHEN ''4166-1'' THEN 1.71 WHEN ''4166-2'' THEN 0.44 WHEN ''4166-3'' THEN 0.44 WHEN ''4166-6'' THEN 0.44 WHEN ''4166-7'' THEN 1.71 ';
  WSQL = WSQL||'               WHEN ''4166-8'' THEN 0.44 ELSE NULL END BDALIQUOTA, COALESCE(TMP.BDVLRREC,0) BDVLRREC, TMP.BDIDENTIFICACAOSCP, TMP.BDCNPJEMP ';
  WSQL = WSQL||'               FROM TMP_VEF_EMP_APURET1800_TEMP TMP ';
  WSQL = WSQL||'               LEFT OUTER JOIN TEMPRESAS EMP ON (EMP.BDCODEMP = TMP.BDCODMATRIZ) ';
  WSQL = WSQL||'               WHERE (TMP.BDCODEMP = '||:PRCODEMP||' OR TMP.BDCODMATRIZ = '||:PRCODEMP||') AND '||:BDCAMPOREC||' = '''||:BDCODREC||'''';
  WSQL = WSQL||'             ) TMP ';
  WSQL = WSQL||'         GROUP BY BDCNPJINCORP, BDCODEMP, TMP.BDCODMATRIZ, TMP.BDCHAVE, TMP.BDCODREC,TMP.BDVARIACAOREC,TMP.BDALIQUOTA ';
  WSQL = WSQL||'        ) TMP ';
  WSQL = WSQL||'  ) TMP; ';

  EXECUTE STATEMENT(WSQL);

end
^


create or alter procedure SP_APURACAO_RET1800 (
    PRCODEMP integer,
    PRREFERENCIA integer)
as
declare variable WCODEMP integer;
declare variable BDCODREC varchar(10);
declare variable BDTIPOIMPREC integer;
declare variable PRREFSALDO integer;
declare variable BDVLRABATER DM_NUMERIC_15_2;
declare variable PRCODREC integer;
declare variable PRVARIACAO integer;
declare variable BDVLRABATERUNI DM_NUMERIC_15_2;
declare variable PRVLRSALDO DM_NUMERIC_15_2;
declare variable PRVLRSALDOORIGINAL DM_NUMERIC_15_2;
declare variable PRCHAVELAN integer;
declare variable PRCHAVEUNI integer;
declare variable PRCODMATRIZ integer;
declare variable PRCHAVETOT integer;
declare variable PRVLRDISTCONS DM_NUMERIC_15_2;
declare variable PRCODEMPS integer;
declare variable BDCODMATRIZ_ integer;
declare variable BDREFERENCIA_ integer;
declare variable BDCHAVETOT_ integer;
declare variable BDCODEMP_ integer;
declare variable BDCHAVE_ integer;
declare variable BDVLRINIVENDIDO_ DM_NUMERIC_15_2;
declare variable BDVLRRECORIG_ DM_NUMERIC_15_2;
declare variable BDVLRRECFIN_ DM_NUMERIC_15_2;
declare variable BDVLRDESC_ DM_NUMERIC_15_2;
declare variable BDVLRDISTCONS_ DM_NUMERIC_15_2;
declare variable PRVLRUTILIZADO DM_NUMERIC_15_2;
declare variable BDCODREC_ integer;
declare variable BDVARIACAO_ integer;
declare variable BDORDEM_ integer;
declare variable WCNPJINCORP varchar(18);
declare variable WATUALIZASALDOS integer;
declare variable BDVLRABATIDO DM_NUMERIC_15_2;
declare variable BDVLRSALDODISTRATO DM_NUMERIC_15_2;
declare variable BDVLRSALDOORIGINAL DM_NUMERIC_15_2;
begin

  -- Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  DELETE FROM TMP_VEF_EMP_APURET1800_TEMP WHERE BDCODEMP = :PRCODEMP OR BDCODMATRIZ = :PRCODEMP;

   /* Cria apuração do RET 1800, necessário para os registros abaixo... */
  FOR
      SELECT ex.BDCODEMP
      FROM TEMPRESAS ex
      LEFT OUTER JOIN VWEF_EMPMENSAL_ABA_FEDE_REF FED ON (FED.BDCODEMP = ex.BDCODEMP)
      WHERE (ex.BDCODEMP = :prCODEMP
         OR ex.BDCODMATRIZ = :prCODEMP)
         AND FED.BDOPTANTERET = 'TRUE'
      INTO :wCODEMP
  DO
   BEGIN
     INSERT INTO VEF_EMP_TRET1800GER(BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA) VALUES (7, :wCODEMP, :prCODEMP, :prREFERENCIA);
   END

   /********************************************
   **   Dados principais na tabela temporária **
   ********************************************/
                                                                                                                                                                                                                                                                                                                                                                                                                                                                         /* ADICIONADO O CAMPO DE EXIGSUSP, POIS ELE NÃO ESTAVA AGRUPANDO QUANDO OS CÓDIGOS DE RECEITAS ERAM IGUAIS, POIS GERAVAM UMA CHAVE DIFERENTE */
  INSERT INTO TMP_VEF_EMP_APURET1800_TEMP(BDCODEMP, BDCODMATRIZ, BDCNPJEMP, BDCHAVE, BDORDEMPGTO, BDEMPOPTANTERET, BDCODEMPREENDIMENTO, BDNOMEEMPRE, BDCODIGOUNIIMOB, BDNOMEUNIIMOB, BDNRCONTRATO, BDVLRINCIALVENDA, BDVLRORIGPARCELA, BDVLRRECFIN, BDDESCONTOPAR, BDVLRCONSUDIST, BDCNPJINCORP, BDNOMEINCORP, BDUNIOPTANTERET, BDUNIBDENQPMCMV, BDUNICONTRATOALIEN,BDDATADISTRATO,BDVLRREC, BDCODREC, BDCODRECIRPJ, BDCODRECPIS, BDCODRECCSLL, BDCODRECCOFINS,BDCODINCORP,BDCODSCP,BDREFSCP,BDIDENTIFICACAOSCP,BDCHAVELAN,BDEXIGSUSP)
  SELECT EMP.BDCODEMP, EMP.BDCODMATRIZ, EMP.BDCNPJEMP,NULL,EMP.bdordempgto, EMP.BDOPTANTERET BDEMPOPTANTERET, EMP.BDCODEMPREENDIMENTO, EMP.BDNOMEEMPRE,
         EMP.BDCODIGOUNIIMOB,EMP.BDNOMEUNIIMOB, EMP.BDNRCONTRATO, EMP.BDVLRINCIALVENDA, EMP.BDVLRORIGPARCELA,
         EMP.BDVLRRECFIN, EMP.BDDESCONTOPAR, EMP.BDVLRCONSUDIST, /*VALOR QUE PODE SER ABATIDO */
         INCORP.BDCNPJINCORP, INCORP.BDNOMEINCORP, EMP.UNIOPTANTERET, EMP.UNIBDENQPMCMV, EMP.BDUNICONTRATOALIEN,
         EMP.BDDATADISTRATO,EMP.BDVLRREC,BDCODREC,
         IIF(EMP.BDIRPJEXIGSUSP = 'FALSE' AND (EMP.BDPISEXIGSUSP = 'TRUE' OR EMP.BDCSLLEXIGSUSP = 'TRUE' OR EMP.BDCOFINSEXIGSUSP = 'TRUE'),
         CASE EMP.BDCODREC WHEN '1068-1' THEN '4112-2' WHEN '1068-2' THEN '4112-3' WHEN '1068-6' THEN '4112-6' WHEN '1068-7' THEN '4112-8' WHEN '4095-1' THEN '4112-1'
         WHEN '4095-2' THEN '4112-7' END, NULL) BDCODRECIRPJ,  --O código que tem exigibilidade suspensa não terá valor somente os demais
         IIF(EMP.BDPISEXIGSUSP = 'FALSE' AND (EMP.BDIRPJEXIGSUSP = 'TRUE' OR EMP.BDCSLLEXIGSUSP = 'TRUE' OR EMP.BDCOFINSEXIGSUSP = 'TRUE'),
         CASE EMP.BDCODREC WHEN '1068-1' THEN '4138-2' WHEN '1068-2' THEN '4138-3' WHEN '1068-6' THEN '4138-6' WHEN '1068-7' THEN '4138-8' WHEN '4095-1' THEN '4138-1'
         WHEN '4095-2' THEN '4138-7' END, NULL) BDCODRECPIS,
         IIF(EMP.BDCSLLEXIGSUSP = 'FALSE' AND (EMP.BDIRPJEXIGSUSP = 'TRUE' OR EMP.BDPISEXIGSUSP = 'TRUE' OR EMP.BDCOFINSEXIGSUSP = 'TRUE'),
         CASE EMP.BDCODREC WHEN '1068-1' THEN '4153-2' WHEN '1068-2' THEN '4153-3' WHEN '1068-6' THEN '4153-6' WHEN '1068-7' THEN '4153-8' WHEN '4095-1' THEN '4153-1'
         WHEN '4095-2' THEN '4153-7' END, NULL) BDCODRECCSLL,
         IIF(EMP.BDCOFINSEXIGSUSP = 'FALSE' AND (EMP.BDIRPJEXIGSUSP = 'TRUE' OR EMP.BDPISEXIGSUSP = 'TRUE' OR EMP.BDCSLLEXIGSUSP = 'TRUE'),
         CASE EMP.BDCODREC WHEN '1068-1' THEN '4166-2' WHEN '1068-2' THEN '4166-3' WHEN '1068-6' THEN '4166-6' WHEN '1068-7' THEN '4166-8' WHEN '4095-1' THEN '4166-1'
         WHEN '4095-2' THEN '4166-7' END, NULL) BDCODRECCOFIS, EMP.BDCODINCORP,
         EMP.BDCODSCP,EMP.BDREFSOC,SCP.BDIDENTIFICACAOSCP,EMP.BDCHAVELAN,
         IIF(EMP.BDIRPJEXIGSUSP = 'TRUE' OR EMP.BDPISEXIGSUSP = 'TRUE' OR EMP.BDCSLLEXIGSUSP = 'TRUE' OR EMP.BDCOFINSEXIGSUSP = 'TRUE','TRUE','FALSE') BDEXIGSUSP
  from (
        SELECT F200.BDCODEMP, F200.BDCODMATRIZ, F200.BDCNPJEMP, F200.BDOPTANTERET,F200.BDCODEMPREENDIMENTO,F200.BDCODIGOUNIIMOB,F200.BDNRCONTRATO,F200.BDVLRINCIALVENDA,
        F200.BDCODTER,UNI.BDDESCRICAO BDNOMEUNIIMOB,UNI.BDOPTANTERET UNIOPTANTERET,UNI.BDENQPMCMV UNIBDENQPMCMV, UNI.BDCONTRATOALIEN BDUNICONTRATOALIEN,
        EMPR.BDCODINCORP,EMPR.BDNOMEEMPRE,F200.BDCODSCP,F200.BDREFSOC,
        IIF(EMPR.BDCODINCORP IS NULL AND IIF(((UNI.BDOPTANTERET = 'TRUE') and ((UNI.BDDATADORET <= :PRREFERENCIA) or  (UNI.BDDATADORET is null))), (UNI.BDOPTANTERET = 'TRUE'), null) AND UNI.BDENQPMCMV = 'TRUE' AND UNI.BDCONTRATOALIEN = 'TRUE','1068-6', --Incorp Não Vinculada,Unidade do Ret,PMCMV e Contr Alien
        IIF(EMPR.BDCODINCORP IS NULL AND IIF(((UNI.BDOPTANTERET = 'TRUE') and ((UNI.BDDATADORET <= :PRREFERENCIA) or  (UNI.BDDATADORET is null))), (UNI.BDOPTANTERET = 'TRUE'), null) AND UNI.BDENQPMCMV = 'TRUE','1068-2',     --Incorp Não Vinculada,Unidade Optante do Ret e Enq no PMCMV
        IIF(EMPR.BDCODINCORP IS NOT null AND IIF(((UNI.BDOPTANTERET = 'TRUE') and ((UNI.BDDATADORET <= :PRREFERENCIA) or  (UNI.BDDATADORET is null))), (UNI.BDOPTANTERET = 'TRUE'), null) AND UNI.BDENQPMCMV = 'TRUE' AND F200.BDCODSCP IS NOT NULL,'1068-7', --Empresa com SCP
        IIF(EMPR.BDCODINCORP IS NOT null AND IIF(((UNI.BDOPTANTERET = 'TRUE') and ((UNI.BDDATADORET <= :PRREFERENCIA) or  (UNI.BDDATADORET is null))), (UNI.BDOPTANTERET = 'TRUE'), null) AND F200.BDCODSCP IS NOT NULL, '4095-2',   --Incorp Vinculada,Unidade Optante e SCP
        IIF(EMPR.BDCODINCORP IS NOT null AND IIF(((UNI.BDOPTANTERET = 'TRUE') and ((UNI.BDDATADORET <= :PRREFERENCIA) or  (UNI.BDDATADORET is null))), (UNI.BDOPTANTERET = 'TRUE'), null) AND UNI.BDENQPMCMV = 'TRUE','1068-1', --Incorp Vinculada,Unidade Optante do Ret e Enq no PMCMV
        IIF(EMPR.BDCODINCORP IS NOT null AND IIF(((UNI.BDOPTANTERET = 'TRUE') and ((UNI.BDDATADORET <= :PRREFERENCIA) or  (UNI.BDDATADORET is null))), (UNI.BDOPTANTERET = 'TRUE'), null), '4095-1',NULL --Incorp Vinculada e Unidade Optante
        )))))) BDCODREC,
        IIF(UPPER(F200.BDIRPJEXIGSUSP)   = 'TRUE',IIF(F200.BDDATAFIMIRPJ IS NOT NULL,IIF(F200PG.BDDATAPGTO BETWEEN F200.BDDATAINIIRPJ AND F200.BDDATAFIMIRPJ,'TRUE','FALSE'),IIF(F200PG.BDDATAPGTO >= F200.BDDATAINIIRPJ,'TRUE','FALSE')),'FALSE') BDIRPJEXIGSUSP,
        IIF(UPPER(F200.BDPISEXIGSUSP)    = 'TRUE',IIF(F200.BDDATAFIMPIS IS NOT NULL,IIF(F200PG.BDDATAPGTO BETWEEN F200.BDDATAINIPIS AND F200.BDDATAFIMPIS,'TRUE','FALSE'),IIF(F200PG.BDDATAPGTO >= F200.BDDATAINIPIS,'TRUE','FALSE')),'FALSE') BDPISEXIGSUSP,
        IIF(UPPER(F200.BDCSLLEXIGSUSP)   = 'TRUE',IIF(F200.BDDATAFIMCSLL IS NOT NULL,IIF(F200PG.BDDATAPGTO BETWEEN F200.BDDATAINICSLL AND F200.BDDATAFIMCSLL,'TRUE','FALSE'),IIF(F200PG.BDDATAPGTO >= F200.BDDATAINICSLL,'TRUE','FALSE')),'FALSE') BDCSLLEXIGSUSP,
        IIF(UPPER(F200.BDCOFINSEXIGSUSP) = 'TRUE',IIF(F200.BDDATAFIMCOFINS IS NOT NULL,IIF(F200PG.BDDATAPGTO BETWEEN F200.BDDATAINICOFINS AND F200.BDDATAFIMCOFINS,'TRUE','FALSE'),IIF(F200PG.BDDATAPGTO >= F200.BDDATAINICOFINS,'TRUE','FALSE')),'FALSE') BDCOFINSEXIGSUSP,
        (F200PG.BDMULTAPAR + F200PG.BDJUROSPAR + F200PG.BDACRESCIMOPAR) BDVLRRECFIN,F200PG.BDDESCONTOPAR,F200PG.bdordempgto,F200PG.BDVLRORIGPARCELA, F200.BDDATADISTRATO ,
         IIF((F_AAAAMM(F200.BDDATADISTRATO) = CAST(:PRREFERENCIA AS VARCHAR(6))) AND  (F200.bddistratoparc <> 'TRUE'),COALESCE(F200.BDVLRREC,0),0) BDVLRREC,
         COALESCE(((F200PG.BDVLRORIGPARCELA + (F200PG.BDMULTAPAR + F200PG.BDJUROSPAR + F200PG.BDACRESCIMOPAR)) - F200PG.BDDESCONTOPAR),0) BDVLRCONSUDIST,F200.BDCHAVE BDCHAVELAN
        FROM(
             SELECT  EMP.BDCODEMP, EMP.BDCODMATRIZ, EMP.BDCNPJEMP,F200.BDCHAVE,F200.BDCODEMPREENDIMENTO,F200.BDCODIGOUNIIMOB,F200.BDNRCONTRATO,F200.BDVLRINCIALVENDA,
             F200.BDCODTER,F200.BDCODSCP,F200.BDREFSOC,F200.BDDATADISTRATO,F200.BDVLRREC,F200.BDIRPJEXIGSUSP,F200.BDPISEXIGSUSP,F200.BDCSLLEXIGSUSP,
             F200.BDCOFINSEXIGSUSP,F200.BDDATAINIIRPJ,F200.BDDATAFIMIRPJ,F200.BDDATAINIPIS,F200.BDDATAFIMPIS,
             F200.BDDATAINICSLL,F200.BDDATAFIMCSLL,F200.BDDATAINICOFINS,F200.BDDATAFIMCOFINS,FED.BDOPTANTERET, F200.bddistratoparc
             FROM TEMPRESAS EMP
             LEFT OUTER JOIN VEF_EMP_TMOVOPIMOBILIARIA_F200 F200 ON (F200.BDCODEMP = EMP.BDCODEMP)
             LEFT OUTER JOIN VWEF_EMPMENSAL_ABA_FEDE_REF FED ON (FED.BDCODEMP = F200.BDCODEMP)
             WHERE ((EMP.BDCODEMP = :PRCODEMP or EMP.BDCODMATRIZ = :PRCODEMP) AND FED.BDOPTANTERET = 'TRUE')
        ) F200
        LEFT OUTER JOIN VEF_BASE_TCADUNIDIMOBILIARIA UNI ON (UNI.bdcodemp = F200.BDCODEMP AND UNI.BDCODEMPREENDIMENTO = F200.BDCODEMPREENDIMENTO AND UNI.bdcodigouniimob = F200.bdcodigouniimob)
        LEFT OUTER JOIN VEF_EMP_TMOVOPIMOBI_F200_PGTO  F200PG ON (F200PG.BDCODEMP = F200.BDCODEMP AND F200PG.BDCHAVE = F200.BDCHAVE AND iif(F200PG.BDDATAPGTO IS NOT NULL,(SELECT bdAAAAMM FROM AAAAMM(F200PG.BDDATAPGTO)),000000) = :PRREFERENCIA)    --Colocar a referência aqui
        LEFT OUTER JOIN VEF_EMP_TCADEMPREENDIMENTO EMPR  ON (EMPR.BDCODEMP = F200.BDCODEMP AND EMPR.BDCODEMPREENDIMENTO = F200.BDCODEMPREENDIMENTO)
        WHERE (IIF(((UNI.BDOPTANTERET = 'TRUE') and ((UNI.BDDATADORET <= :PRREFERENCIA) or  (UNI.BDDATADORET is null))), (UNI.BDOPTANTERET = 'TRUE'), null) OR UNI.BDENQPMCMV = 'TRUE') AND (F200PG.BDCODEMPREENDPERMUTA IS NULL OR (F200PG.BDCODEMPREENDPERMUTA = 0))
       )EMP
  LEFT OUTER JOIN VEF_EMP_TCADINCORPORADORA INCORP ON (EMP.BDCODEMP = INCORP.BDCODEMP AND EMP.BDCODINCORP = INCORP.BDCODINCORP)
  LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = EMP.BDCODEMP AND SCP.BDCODSCP = EMP.BDCODSCP AND SCP.BDREFEMP = EMP.BDREFSOC)
  WHERE EMP.BDORDEMPGTO IS NOT NULL; -- Apenas trazer os dados quando houver um lançamento de pagamento da uma unidade

    /* ********************************************************************************************************
   **  DEPOIS DE ADICIONADO OS VALORES NA TPM COM AS CHAVES CORRETAS, APAGA O CODREC PARA BDEXIGSUSP = TRUE **
   ********************************************************************************************************* */

   UPDATE TMP_VEF_EMP_APURET1800_TEMP
   SET BDCODREC = NULL
   WHERE BDEXIGSUSP = 'TRUE';

  /****************************************************************************************************************************
 **   DADOS AGRUPADOS - SEPARADO NUMA PROCEDURE POIS DEVE SER EXECUTADO PARA CADA CÓDIGO DE RECEITA(EXIGIBILIDADE SUSPENSA) **
 *****************************************************************************************************************************/

  FOR    --TRAZER OS CÓDIGOS DIFERENTES POIS VAI AGRUPAR ELES NA PROCEDURE AUX - COD IMP - 0 REC, 1 IRPJ, 2 PIS, 3 COFINS E 4 CSLL
         --FOI FEITO VARIOS SELECTS PARA GARANTIR QUE N VAI SER PEGO VARIAS VEZES O MESMO CÓDIGO
        SELECT BDCODREC, BDCODIMP
        FROM(
             SELECT DISTINCT BDCODREC, 0 BDCODIMP
             FROM TMP_VEF_EMP_APURET1800_TEMP WHERE (BDCODEMP = :PRCODEMP OR BDCODMATRIZ = :PRCODEMP)
             AND BDEXIGSUSP = 'FALSE'
             UNION ALL
             SELECT DISTINCT BDCODRECIRPJ, 1 BDCODIMP
             FROM TMP_VEF_EMP_APURET1800_TEMP WHERE BDCODEMP = :PRCODEMP OR BDCODMATRIZ = :PRCODEMP
             UNION ALL
             SELECT DISTINCT BDCODRECPIS, 2 BDCODIMP
             FROM TMP_VEF_EMP_APURET1800_TEMP WHERE BDCODEMP = :PRCODEMP OR BDCODMATRIZ = :PRCODEMP
              UNION ALL
             SELECT DISTINCT BDCODRECCOFINS, 3 BDCODIMP
             FROM TMP_VEF_EMP_APURET1800_TEMP WHERE BDCODEMP = :PRCODEMP OR BDCODMATRIZ = :PRCODEMP
              UNION ALL
             SELECT DISTINCT BDCODRECCSLL, 4 BDCODIMP
             FROM TMP_VEF_EMP_APURET1800_TEMP WHERE BDCODEMP = :PRCODEMP OR BDCODMATRIZ = :PRCODEMP
         )
         WHERE BDCODREC IS NOT NULL
         GROUP BY BDCODREC, BDCODIMP
         INTO  :BDCODREC,:BDTIPOIMPREC
  DO
    BEGIN /*Inserção dos dados na tabela de totalizadores, separados por código de receita, cada um terá sua respectiva linha com valores*/
       if (:BDTIPOIMPREC = 0) then
          EXECUTE PROCEDURE SP_APURACAO_RET1800AUX(:PRCODEMP,:PRREFERENCIA,:BDCODREC,'BDCODREC');
       else if (:BDTIPOIMPREC = 1) then
          EXECUTE PROCEDURE SP_APURACAO_RET1800AUX(:PRCODEMP,:PRREFERENCIA,:BDCODREC,'BDCODRECIRPJ');
       else if (:BDTIPOIMPREC = 2) then
          EXECUTE PROCEDURE SP_APURACAO_RET1800AUX(:PRCODEMP,:PRREFERENCIA,:BDCODREC,'BDCODRECPIS');
       else if (:BDTIPOIMPREC = 3) then
          EXECUTE PROCEDURE SP_APURACAO_RET1800AUX(:PRCODEMP,:PRREFERENCIA,:BDCODREC,'BDCODRECCOFINS');
       else if (:BDTIPOIMPREC = 4) then
          EXECUTE PROCEDURE SP_APURACAO_RET1800AUX(:PRCODEMP,:PRREFERENCIA,:BDCODREC,'BDCODRECCSLL');
    END

   /* *********************************************************************************
   **  INSERE O LANÇAMENTO QUE TEVE DISTRADO NO PERÍODO APURADO NA TABELA DE SALDOS **
   ******************************************************************************* */

   INSERT INTO VEF_EMP_TRET1800SALDOS (BDCODEMP, BDCHAVELAN, BDCHAVE, BDREFERENCIA, BDVLRABATIDO, BDVLRSALDODISTRATO, BDCODREC, BDVARIACAO, BDVLRSALDOORIGINAL,BDCODMATRIZ)
   SELECT F200.BDCODEMP,F200.BDCHAVE,GETORDEMSEQUENCIAL_STR('1800SALDOS.'||F200.BDCODEMP||'.'||F200.BDCHAVE||'.'||F200.BDCODMATRIZ, :prCODEMP),
          F200.BDREFERENCIA, 0, F200.BDVLRABATIDO,F200.BDCODREC,F200.BDVARIACAO,F200.BDVLRREC,F200.BDCODMATRIZ
   FROM(
        SELECT /*COALESCE(TMP.BDCODMATRIZ,*/TMP.BDCODEMP, TMP.BDCHAVE,
        TMP.BDREFERENCIA, TMP.BDVLRABATIDO, (SELECT FIRST 1 BDCODREC FROM TCODREC WHERE BDCODRECOF = (SUBSTRING(TMP.BDCODREC FROM 1 FOR 4))) BDCODREC,
        CAST(SUBSTRING(TMP.BDCODREC FROM 6 FOR 6) AS INTEGER) BDVARIACAO,TMP.BDVLRREC, TMP.BDCODMATRIZ
        FROM(
            SELECT TMP.BDCODEMP BDCODEMP, TMP.BDCHAVELAN BDCHAVE,
            :PRREFERENCIA BDREFERENCIA, TMP.BDVLRREC BDVLRABATIDO,
            IIF(TMP.BDCODREC IS NULL,  /* Quando for um código que tem exigibilidade, deve pegar ocódigo de receita principal para aplicação dos saldos */
            CASE COALESCE(TMP.BDCODRECIRPJ,COALESCE(TMP.BDCODRECPIS,COALESCE(TMP.BDCODRECCSLL,TMP.BDCODRECCOFINS)))
            WHEN '4112-2' THEN '1068-1' WHEN '4138-2' THEN '1068-1' WHEN '4153-2' THEN '1068-1' WHEN '4166-2' THEN '1068-1' /*1068-1*/
            WHEN '4112-1' THEN '4095-1' WHEN '4138-1' THEN '4095-1' WHEN '4153-1' THEN '4095-1' WHEN '4166-1' THEN '4095-1' /*4095-1*/
            WHEN '4112-2' THEN '1068-2' WHEN '4138-3' THEN '1068-2' WHEN '4153-2' THEN '1068-2' WHEN '4166-3' THEN '1068-2' /*1068-2*/
            WHEN '4112-6' THEN '1068-6' WHEN '4138-6' THEN '1068-6' WHEN '4153-6' THEN '1068-6' WHEN '4166-6' THEN '1068-6' /*1068-6*/
            WHEN '4112-8' THEN '1068-7' WHEN '4138-8' THEN '1068-7' WHEN '4153-8' THEN '1068-7' WHEN '4166-8' THEN '1068-7' /*1068-7*/
            WHEN '4112-7' THEN '4095-2' WHEN '4138-7' THEN '4095-2' WHEN '4153-7' THEN '4095-2' WHEN '4166-7' THEN '4095-2' /*4095-2*/
            END,TMP.BDCODREC) BDCODREC,
            TMP.BDVLRREC, COALESCE(TMP.BDCODMATRIZ,TMP.BDCODEMP) BDCODMATRIZ
            FROM TMP_VEF_EMP_APURET1800_TEMP TMP
            WHERE (TMP.BDCODEMP = :PRCODEMP OR TMP.BDCODMATRIZ = :PRCODEMP) AND TMP.BDVLRREC > 0
            ) TMP
        UNION ALL      --PEGAR OS SALDOS DOS LANÇAMENTOS QUE TIVERAM DISTRATO NO PERÍODO, MAS N TIVERAM PAGAMENTO
        SELECT F200.BDCODEMP,F200.BDCHAVE,
              :PRREFERENCIA BDREFERENCIA, F200.BDVLRREC BDVLRABATIDO, (SELECT FIRST 1 BDCODREC FROM TCODREC WHERE BDCODRECOF = (SUBSTRING(COALESCE(F200.BDCODREC,COALESCE(BDCODRECIRPJ,COALESCE(BDCODRECPIS,COALESCE(BDCODRECCSLL, BDCODRECCOFIS)))) FROM 1 FOR 4))) BDCODREC,
              CAST(SUBSTRING(COALESCE(F200.BDCODREC,COALESCE(BDCODRECIRPJ,COALESCE(BDCODRECPIS,COALESCE(BDCODRECCSLL, BDCODRECCOFIS)))) FROM 6 FOR 6) AS INTEGER) BDVARIACAO,
              F200.BDVLRREC, COALESCE(F200.BDCODMATRIZ,F200.BDCODEMP) BDCODMATRIZ
        FROM(
            SELECT F200.BDCODEMP,F200.BDCHAVE,F200.BDVLRREC, F200.BDCODMATRIZ,
             IIF(F200.BDIRPJEXIGSUSP = 'TRUE' OR F200.BDPISEXIGSUSP = 'TRUE' OR F200.BDCSLLEXIGSUSP = 'TRUE' OR F200.BDCOFINSEXIGSUSP = 'TRUE',NULL,BDCODREC) BDCODREC,
             IIF(F200.BDIRPJEXIGSUSP = 'FALSE' AND (F200.BDPISEXIGSUSP = 'TRUE' OR F200.BDCSLLEXIGSUSP = 'TRUE' OR F200.BDCOFINSEXIGSUSP = 'TRUE'),
             CASE F200.BDCODREC WHEN '1068-1' THEN '4112-2' WHEN '1068-2' THEN '4112-3' WHEN '1068-6' THEN '4112-6' WHEN '1068-7' THEN '4112-8' WHEN '4095-1' THEN '4112-1'
             WHEN '4095-2' THEN '4112-7' END, NULL) BDCODRECIRPJ,  --O código que tem exigibilidade suspensa não terá valor somente os demais
             IIF(F200.BDPISEXIGSUSP = 'FALSE' AND (F200.BDIRPJEXIGSUSP = 'TRUE' OR F200.BDCSLLEXIGSUSP = 'TRUE' OR F200.BDCOFINSEXIGSUSP = 'TRUE'),
             CASE F200.BDCODREC WHEN '1068-1' THEN '4138-2' WHEN '1068-2' THEN '4138-3' WHEN '1068-6' THEN '4138-6' WHEN '1068-7' THEN '4138-8' WHEN '4095-1' THEN '4138-1'
             WHEN '4095-2' THEN '4138-7' END, NULL) BDCODRECPIS,
             IIF(F200.BDCSLLEXIGSUSP = 'FALSE' AND (F200.BDIRPJEXIGSUSP = 'TRUE' OR F200.BDPISEXIGSUSP = 'TRUE' OR F200.BDCOFINSEXIGSUSP = 'TRUE'),
             CASE F200.BDCODREC WHEN '1068-1' THEN '4153-2' WHEN '1068-2' THEN '4153-3' WHEN '1068-6' THEN '4153-6' WHEN '1068-7' THEN '4153-8' WHEN '4095-1' THEN '4153-1'
             WHEN '4095-2' THEN '4153-7' END, NULL) BDCODRECCSLL,
             IIF(F200.BDCOFINSEXIGSUSP = 'FALSE' AND (F200.BDIRPJEXIGSUSP = 'TRUE' OR F200.BDPISEXIGSUSP = 'TRUE' OR F200.BDCSLLEXIGSUSP = 'TRUE'),
             CASE F200.BDCODREC WHEN '1068-1' THEN '4166-2' WHEN '1068-2' THEN '4166-3' WHEN '1068-6' THEN '4166-6' WHEN '1068-7' THEN '4166-8' WHEN '4095-1' THEN '4166-1'
             WHEN '4095-2' THEN '4166-7' END, NULL) BDCODRECCOFIS
             FROM (
                   SELECT  F200.BDCODEMP, F200.BDCHAVE, F200.BDVLRREC,
                   IIF(EMPR.BDCODINCORP IS NULL AND IIF(((UNI.BDOPTANTERET = 'TRUE') and ((UNI.BDDATADORET <= :PRREFERENCIA) or  (UNI.BDDATADORET is null))), (UNI.BDOPTANTERET = 'TRUE'), null) AND UNI.BDENQPMCMV = 'TRUE' AND UNI.BDCONTRATOALIEN = 'TRUE','1068-6', --Incorp Não Vinculada,Unidade do Ret,PMCMV e Contr Alien
                   IIF(EMPR.BDCODINCORP IS NULL AND IIF(((UNI.BDOPTANTERET = 'TRUE') and ((UNI.BDDATADORET <= :PRREFERENCIA) or  (UNI.BDDATADORET is null))), (UNI.BDOPTANTERET = 'TRUE'), null) AND UNI.BDENQPMCMV = 'TRUE','1068-2',     --Incorp Não Vinculada,Unidade Optante do Ret e Enq no PMCMV
                   IIF(EMPR.BDCODINCORP IS NOT null AND IIF(((UNI.BDOPTANTERET = 'TRUE') and ((UNI.BDDATADORET <= :PRREFERENCIA) or  (UNI.BDDATADORET is null))), (UNI.BDOPTANTERET = 'TRUE'), null) AND UNI.BDENQPMCMV = 'TRUE' AND F200.BDCODSCP IS NOT NULL,'1068-7', --Empresa com SCP
                   IIF(EMPR.BDCODINCORP IS NOT null AND IIF(((UNI.BDOPTANTERET = 'TRUE') and ((UNI.BDDATADORET <= :PRREFERENCIA) or  (UNI.BDDATADORET is null))), (UNI.BDOPTANTERET = 'TRUE'), null) AND F200.BDCODSCP IS NOT NULL, '4095-2',   --Incorp Vinculada,Unidade Optante e SCP
                   IIF(EMPR.BDCODINCORP IS NOT null AND IIF(((UNI.BDOPTANTERET = 'TRUE') and ((UNI.BDDATADORET <= :PRREFERENCIA) or  (UNI.BDDATADORET is null))), (UNI.BDOPTANTERET = 'TRUE'), null) AND UNI.BDENQPMCMV = 'TRUE','1068-1', --Incorp Vinculada,Unidade Optante do Ret e Enq no PMCMV
                   IIF(EMPR.BDCODINCORP IS NOT null AND IIF(((UNI.BDOPTANTERET = 'TRUE') and ((UNI.BDDATADORET <= :PRREFERENCIA) or  (UNI.BDDATADORET is null))), (UNI.BDOPTANTERET = 'TRUE'), null), '4095-1',NULL --Incorp Vinculada e Unidade Optante
                   ))))))BDCODREC, F200.BDIRPJEXIGSUSP,F200.BDPISEXIGSUSP,F200.BDCSLLEXIGSUSP,F200.BDCOFINSEXIGSUSP,F200.BDCODMATRIZ
                   FROM(
                       SELECT EMP.BDCODMATRIZ,F200.BDCODEMP, F200.BDCHAVE,F200.BDCODEMPREENDIMENTO,F200.BDCODIGOUNIIMOB,F200.BDDATADISTRATO,F200.BDVLRREC,F200.BDCODSCP,
                       F200.BDIRPJEXIGSUSP,F200.BDPISEXIGSUSP,F200.BDCSLLEXIGSUSP,F200.BDCOFINSEXIGSUSP
                       FROM VEF_EMP_TMOVOPIMOBILIARIA_F200 F200
                       LEFT OUTER JOIN TEMPRESAS EMP ON (EMP.BDCODEMP = F200.BDCODEMP)
                       JOIN VWEF_EMPMENSAL_ABA_FEDE_REF FED ON (FED.BDCODEMP = F200.BDCODEMP)
                       WHERE ((EMP.BDCODEMP = :PRCODEMP) OR (EMP.BDCODMATRIZ = :PRCODEMP)) AND FED.BDOPTANTERET = 'TRUE' AND (F200.bddistratoparc <> 'TRUE')
                       AND F200.BDVLRREC > 0 AND (iif(F200.BDDATADISTRATO IS NOT NULL,(SELECT bdAAAAMM FROM AAAAMM(F200.BDDATADISTRATO)),000000) = :PRREFERENCIA)
                       union all
                       SELECT EMP.BDCODMATRIZ,F200.BDCODEMP, F200.BDCHAVE,F200.BDCODEMPREENDIMENTO,F200.BDCODIGOUNIIMOB,MAX(PGTO.bddatapgto),SUM(PGTO.bdvalorpgto),F200.BDCODSCP,
                       F200.BDIRPJEXIGSUSP,F200.BDPISEXIGSUSP,F200.BDCSLLEXIGSUSP,F200.BDCOFINSEXIGSUSP
                       FROM VEF_EMP_TMOVOPIMOBILIARIA_F200 F200
                         INNER JOIN VEF_EMP_TMOV_OP_IMOB_DISTRATO_PGTO PGTO ON F200.bdCODEMP = PGTO.BDCODEMP AND F200.bdchave = PGTO.bdchave
                       LEFT OUTER JOIN TEMPRESAS EMP ON (EMP.BDCODEMP = F200.BDCODEMP)
                       JOIN VWEF_EMPMENSAL_ABA_FEDE_REF FED ON (FED.BDCODEMP = F200.BDCODEMP)
                       WHERE ((EMP.BDCODEMP = :PRCODEMP) OR (EMP.BDCODMATRIZ = :PRCODEMP)) AND FED.BDOPTANTERET = 'TRUE' AND (F200.bddistratoparc = 'TRUE')
                       AND F200.BDVLRREC > 0 AND (iif(PGTO.bddatapgto IS NOT NULL,F_AAAAMM(PGTO.bddatapgto),000000) = :PRREFERENCIA)
                       GROUP BY EMP.BDCODMATRIZ,F200.BDCODEMP, F200.BDCHAVE,F200.BDCODEMPREENDIMENTO,F200.BDCODIGOUNIIMOB, F200.BDCODSCP, F200.BDIRPJEXIGSUSP,F200.BDPISEXIGSUSP,F200.BDCSLLEXIGSUSP,F200.BDCOFINSEXIGSUSP
                   ) F200
                   LEFT OUTER JOIN VEF_BASE_TCADUNIDIMOBILIARIA UNI ON (UNI.bdcodemp = F200.BDCODEMP AND UNI.BDCODEMPREENDIMENTO = F200.BDCODEMPREENDIMENTO AND UNI.bdcodigouniimob = F200.bdcodigouniimob)
                   LEFT OUTER JOIN VEF_EMP_TCADEMPREENDIMENTO EMPR  ON (EMPR.BDCODEMP = F200.BDCODEMP AND EMPR.BDCODEMPREENDIMENTO = F200.BDCODEMPREENDIMENTO)
                   WHERE (IIF(((UNI.BDOPTANTERET = 'TRUE') and ((UNI.BDDATADORET <= :PRREFERENCIA) or  (UNI.BDDATADORET is null))), (UNI.BDOPTANTERET = 'TRUE'), null) OR UNI.BDENQPMCMV = 'TRUE')
                  )F200
           ) F200
        ) F200
   GROUP BY F200.BDCODEMP,F200.BDCHAVE,F200.BDREFERENCIA,F200.BDVLRABATIDO,F200.BDCODREC,F200.BDVARIACAO,F200.BDVLRREC,F200.BDCODMATRIZ;

   wATUALIZASALDOS = 0;

   /****************************************************************************
   **  INSERÇÃO NA TABELA DE UNIDADE - DESCONTA O SALDO POR CÓDIGO DE RECEITA **
   ****************************************************************************/

   /*PEGA OS SALDOS DA TABELA DE SALDOS E ABATE O VALOR DAS UNIDADE DO PERÍODO, DEPOIS ATUALIZA A TABELA DE SALDOS E A TABELA DE UNIDADES*/

   FOR
      SELECT TOT.BDCODEMP,TOT.BDCODREC, ((SELECT BDCODRECOF FROM TCODREC WHERE BDCODREC = TOT.BDCODREC)||'-'||TOT.BDVARIACAO) BDCODRECOF,TOT.BDVARIACAO, TOT.BDCNPJINCORP
      FROM VEF_EMP_TRET1800TOT TOT
      WHERE ((TOT.BDCODEMP = :PRCODEMP OR TOT.BDCODMATRIZ = :PRCODEMP) AND TOT.BDREFERENCIA = :PRREFERENCIA)
      GROUP BY TOT.BDCODEMP,TOT.BDCODREC,BDCODRECOF,TOT.BDVARIACAO, TOT.BDCNPJINCORP
      ORDER BY TOT.BDCODEMP
      INTO :WCODEMP,:PRCODREC,:BDCODREC,:PRVARIACAO, :WCNPJINCORP
   DO
     BEGIN /*1*/
       wATUALIZASALDOS = 1;
       FOR
        SELECT IIF(S.BDVLRSALDODISTRATO > 0,IIF(S.BDVLRSALDODISTRATO >  S.BDVLRABATER,COALESCE(S.BDVLRABATER,0.00), COALESCE(S.BDVLRABATER - (S.BDVLRABATER - S.BDVLRSALDODISTRATO),0.00)),0.00) BDVLRABATER,
               IIF(S.BDVLRSALDODISTRATO > 0,IIF(S.BDVLRSALDODISTRATO >  S.BDVLRABATERUNI,COALESCE(S.BDVLRABATERUNI,0.00), COALESCE(S.BDVLRABATERUNI - (S.BDVLRABATERUNI - S.BDVLRSALDODISTRATO),0.00)),0.00) BDVLRABATERUNI     --Tem que fazer verificação se ficar negativo
        FROM (
             SELECT S.BDCODEMP, SUM(S.BDVLRSALDODISTRATO) BDVLRSALDODISTRATO, SUM(S.BDVLRABATER) BDVLRABATER,SUM(S.BDVLRABATER) BDVLRABATERUNI
             FROM(
                  SELECT S.BDCODEMP,S.BDCODREC,S.BDVARIACAO,S.BDVLRSALDODISTRATO, BDVLRABATER
                  FROM (
                       SELECT COALESCE(S.BDCODMATRIZ,S.BDCODEMP) BDCODEMP,S.BDCHAVELAN,S.BDCODREC,S.BDVARIACAO,SUM(S.BDVLRSALDODISTRATO) BDVLRSALDODISTRATO, 0 BDVLRABATER
                       FROM VEF_EMP_TRET1800SALDOS S
                       LEFT OUTER JOIN VEF_EMP_TMOVOPIMOBILIARIA_F200 F200 ON (F200.BDCHAVE = S.BDCHAVELAN AND F200.BDCODEMP = S.BDCODEMP)
                       LEFT OUTER JOIN VEF_EMP_TCADEMPREENDIMENTO EMPR  ON (EMPR.BDCODEMP = F200.BDCODEMP AND EMPR.BDCODEMPREENDIMENTO = F200.BDCODEMPREENDIMENTO)
                       LEFT OUTER JOIN VEF_EMP_TCADINCORPORADORA INCORP ON (EMPR.BDCODEMP = INCORP.BDCODEMP AND EMPR.BDCODINCORP = INCORP.BDCODINCORP)
                       WHERE S.BDCODMATRIZ = :PRCODEMP AND S.BDCODREC = :PRCODREC AND S.BDVARIACAO = :PRVARIACAO
                       AND ((INCORP.BDCNPJINCORP IS NULL) OR (INCORP.BDCNPJINCORP = :WCNPJINCORP))
                       AND ((s.BDREFERENCIA = COALESCE((SELECT FIRST 1 x.BDREFERENCIA FROM VEF_EMP_TRET1800SALDOS x
                                                        WHERE x.bdCODMATRIZ = s.bdCODMATRIZ AND x.bdCODEMP = s.bdCODEMP AND x.bdCHAVELAN = s.bdCHAVELAN
                                                        AND x.BDREFERENCIA < :PRREFERENCIA ORDER BY x.BDREFERENCIA DESC),
                                                        :PRREFERENCIA)) OR
                            (s.BDREFERENCIA = :PRREFERENCIA))
                       GROUP BY BDCODEMP,S.BDCHAVELAN,S.BDCODREC,S.BDVARIACAO,BDVLRABATER
                       ) S
                  UNION ALL
                  SELECT COALESCE(TMP.BDCODMATRIZ,TMP.BDCODEMP) BDCODEMP, TMP.BDCODREC,2, 0 BDVLRSALDDISTRATO, SUM(TMP.BDVLRCONSUDIST) BDVLRABATER
                  FROM TMP_VEF_EMP_APURET1800_TEMP TMP
                  WHERE (TMP.BDCODEMP = :PRCODEMP OR TMP.BDCODMATRIZ = :PRCODEMP) AND (TMP.BDCODREC = :BDCODREC OR
                  TMP.BDCODRECIRPJ = :BDCODREC OR TMP.BDCODRECPIS = :BDCODREC OR TMP.BDCODRECCSLL = :BDCODREC OR TMP.BDCODRECCOFINS = :BDCODREC)
                    AND ((TMP.BDCNPJINCORP IS NULL) OR (TMP.BDCNPJINCORP = :WCNPJINCORP))
                    AND ((TMP.BDCNPJINCORP IS NULL) OR (TMP.BDCNPJINCORP = :WCNPJINCORP))
                  GROUP BY BDCODEMP,BDCHAVE,BDCODREC
                ) S
            GROUP BY S.BDCODEMP
            ) S
        WHERE BDVLRABATER > 0 AND BDVLRABATERUNI > 0
        INTO :BDVLRABATER, :BDVLRABATERUNI
       DO
         BEGIN /*2*/

           /* *****************************************************
           **  INSERE O SALDO ATUALIZADO NA TABELA DE SALDOS    **
           **************************************************** */
           FOR
             SELECT S.BDCODEMP,S.BDCHAVELAN,SUM(S.BDVLRSALDODISTRATO),SUM(S.BDVLRSALDOORIGINAL),MAX(S.BDREFERENCIA),S.BDCODMATRIZ
             FROM (
                    SELECT S.BDCODEMP,S.BDCODMATRIZ, S.BDCHAVELAN,SUM(COALESCE(S.BDVLRSALDODISTRATO,0)) BDVLRSALDODISTRATO,S.BDVLRSALDOORIGINAL,MAX(S.BDREFERENCIA) BDREFERENCIA,F200.BDDATADISTRATO
                    FROM VEF_EMP_TRET1800SALDOS S
                    LEFT OUTER JOIN VEF_EMP_TMOVOPIMOBILIARIA_F200 F200 ON (F200.BDCODEMP = S.BDCODEMP AND F200.BDCHAVE = S.BDCHAVELAN)
                    LEFT OUTER JOIN VEF_EMP_TCADEMPREENDIMENTO EMPR  ON (EMPR.BDCODEMP = F200.BDCODEMP AND EMPR.BDCODEMPREENDIMENTO = F200.BDCODEMPREENDIMENTO)
                    LEFT OUTER JOIN VEF_EMP_TCADINCORPORADORA INCORP ON (EMPR.BDCODEMP = INCORP.BDCODEMP AND EMPR.BDCODINCORP = INCORP.BDCODINCORP)
                    WHERE S.BDCODMATRIZ = :PRCODEMP AND S.BDCODREC = :PRCODREC AND S.BDVARIACAO = :PRVARIACAO
                    AND ((INCORP.BDCNPJINCORP IS NULL) OR (INCORP.BDCNPJINCORP = :WCNPJINCORP))
                    AND ((s.BDREFERENCIA = COALESCE((SELECT FIRST 1 x.BDREFERENCIA FROM VEF_EMP_TRET1800SALDOS x
                                                     WHERE x.bdCODMATRIZ = s.bdCODMATRIZ AND x.bdCODEMP = s.bdCODEMP AND x.bdCHAVELAN = s.bdCHAVELAN
                                                     AND x.BDREFERENCIA < :PRREFERENCIA ORDER BY x.BDREFERENCIA DESC),
                                                     :PRREFERENCIA)) OR
                         (s.BDREFERENCIA = :PRREFERENCIA))
                    GROUP BY S.BDCODEMP,S.BDCODMATRIZ,S.BDCHAVELAN,S.BDVLRSALDOORIGINAL, F200.BDDATADISTRATO
                    ORDER BY F200.BDDATADISTRATO
                  ) S
             --WHERE S.BDVLRSALDODISTRATO > 0
             GROUP BY S.BDCODEMP,S.BDCHAVELAN,S.BDCODMATRIZ
             INTO :PRCODEMPS, :PRCHAVELAN,:PRVLRSALDO,:PRVLRSALDOORIGINAL,:PRREFSALDO, :PRCODMATRIZ

           DO
             BEGIN
               if (BDVLRABATER > 0) then  --Tem que ver como fazer para inserir os saldos da filial
                  BEGIN

                   if (:PRREFSALDO <> :PRREFERENCIA) then --O SALDO FOI INSERIDO E UTILIZADO NO MÊS APURADO, SOMENTE ATUALIZAR O VALOR ABATIDO E O SALDO RESTANTE
                      begin
                       INSERT INTO VEF_EMP_TRET1800SALDOS (BDCODEMP, BDCHAVELAN, BDCHAVE, BDREFERENCIA, BDVLRABATIDO, BDVLRSALDODISTRATO, BDCODREC, BDVARIACAO, BDVLRSALDOORIGINAL,BDCODMATRIZ)
                       VALUES(:PRCODEMPS,:PRCHAVELAN,GETORDEMSEQUENCIAL_STR('1800SALDOS.'||:PRCODEMPS||'.'||:PRCHAVELAN||'.'||:PRCODMATRIZ, :prCODEMP),:PRREFERENCIA,
                       IIF(:PRVLRSALDO > :BDVLRABATER, :BDVLRABATER, :PRVLRSALDO),IIF(:PRVLRSALDO > :BDVLRABATER, (:PRVLRSALDO - :BDVLRABATER), 0), :PRCODREC,:PRVARIACAO,:PRVLRSALDOORIGINAL,:PRCODMATRIZ);

                       IF(:PRVLRSALDO < :BDVLRABATER) THEN
                         BEGIN
                           UPDATE VEF_EMP_TRET1800TOT TOT -- Atualiza o valor do saldo utilizado do distrato, pois estava vindo como o valor total
                           SET TOT.BDVLRDISTRADO = :PRVLRSALDO
                           WHERE ((TOT.BDCODEMP = :PRCODEMP OR TOT.BDCODMATRIZ = :PRCODEMP) AND TOT.BDREFERENCIA = :PRREFERENCIA)
                           AND TOT.BDCODEMP = :WCODEMP
                           AND TOT.BDCODREC = :PRCODREC
                           AND TOT.BDVARIACAO = :PRVARIACAO
                           AND TOT.BDCNPJINCORP = :WCNPJINCORP;
                         END
                      end
                   else
                      begin
                        UPDATE VEF_EMP_TRET1800SALDOS S
                        SET S.BDVLRABATIDO = S.BDVLRABATIDO + IIF(:PRVLRSALDO > :BDVLRABATER, :BDVLRABATER, :PRVLRSALDO),
                            S.BDVLRSALDODISTRATO =  IIF(:PRVLRSALDO > :BDVLRABATER, (:PRVLRSALDO - :BDVLRABATER), 0),
                            S.BDVLRSALDOORIGINAL = :PRVLRSALDOORIGINAL
                        WHERE S.BDCODEMP = :PRCODEMPS AND S.BDCHAVELAN = :PRCHAVELAN AND S.BDREFERENCIA = :PRREFERENCIA
                        AND   S.BDCODREC = :PRCODREC AND S.BDVARIACAO = :PRVARIACAO AND S.BDCODMATRIZ = :PRCODMATRIZ;
                      end

                   BDVLRABATER = (BDVLRABATER - (SELECT SUM(BDVLRABATIDO) FROM VEF_EMP_TRET1800SALDOS SA WHERE SA.BDCODEMP = :PRCODEMPS AND SA.BDCHAVELAN = :PRCHAVELAN AND
                                                 SA.BDREFERENCIA = :PRREFERENCIA AND SA.BDCODREC = :PRCODREC AND SA.BDVARIACAO = :PRVARIACAO AND SA.BDCODMATRIZ = :PRCODMATRIZ));


                  END

             END

           /*****************************************************
           ** INSERE OS EMPREENDIMENTOS COM OS SALDOS CORRETOS **
           ****************************************************/

           FOR
              SELECT COALESCE(TMP.BDCODMATRIZ,TMP.BDCODEMP) BDCODMATRIZ, TMP.BDCHAVE,TMP.BDCHAVELAN
              FROM TMP_VEF_EMP_APURET1800_TEMP TMP
              WHERE (TMP.BDCODEMP = :WCODEMP or TMP.BDCODMATRIZ = :WCODEMP ) AND (TMP.BDCODREC = :BDCODREC OR
              TMP.BDCODRECIRPJ = :BDCODREC OR TMP.BDCODRECPIS = :BDCODREC
              OR TMP.BDCODRECCSLL = :BDCODREC OR TMP.BDCODRECCOFINS = :BDCODREC)
              AND ((TMP.BDCNPJINCORP IS NULL) OR (TMP.BDCNPJINCORP = :WCNPJINCORP))
              GROUP BY  BDCODMATRIZ, TMP.BDCHAVE,TMP.BDCHAVELAN
              INTO :PRCODMATRIZ,:PRCHAVEUNI,:PRCHAVELAN
           DO
             BEGIN

             if (BDVLRABATERUNI > 0) then
                begin      --INSERINDO UNIDADE QUE TEM VALOR DE SALDO PARA ABATER
                  /* Alt.: #151565 #151881 - Quando tinham vários pagamentos, inseria todos ao mesmo tempo e não descontava os valores do distrato de cada pagamento, apenas do primeiro...
                   INSERT INTO VEF_EMP_TRET1800UNID (BDCODMATRIZ, BDREFERENCIA, BDCHAVETOT, BDCODEMP, BDCHAVE,BDORDEM,BDVLRINIVENDIDO, BDVLRRECORIG, BDVLRRECFIN, BDVLRDESC, BDVLRDISTCONS,BDCODREC,BDVARIACAO)
                   SELECT TOT.BDCODMATRIZ,TOT.BDREFERENCIA,TOT.BDCHAVETOT,TMP.BDCODEMP,TMP.BDCHAVELAN, GETORDEMSEQUENCIAL_STR(substring(TOT.BDCODMATRIZ||'|'||TOT.BDREFERENCIA||'|'||TOT.BDCHAVETOT||'|'||TMP.BDCODEMP||'|'||TMP.BDCHAVELAN from 1  for 200), :prCODEMP),
                   TMP.BDVLRINCIALVENDA, TMP.BDVLRORIGPARCELA, TMP.BDVLRRECFIN, TMP.BDDESCONTOPAR,
                   COALESCE(IIF(TMP.BDVLRCONSUDIST < :BDVLRABATERUNI, TMP.BDVLRCONSUDIST, :BDVLRABATERUNI),0.00),TOT.BDCODREC, TOT.BDVARIACAO
                   FROM VEF_EMP_TRET1800TOT TOT
                   LEFT OUTER JOIN TMP_VEF_EMP_APURET1800_TEMP TMP ON  ((TMP.BDCODEMP = TOT.BDCODEMP OR TMP.BDCODMATRIZ = TOT.BDCODEMP) AND TMP.BDCHAVE = TOT.BDCHAVEUNI AND TMP.BDCHAVELAN = :PRCHAVELAN
                   AND (TMP.BDCODREC = :BDCODREC OR TMP.BDCODRECIRPJ = :BDCODREC OR TMP.BDCODRECPIS = :BDCODREC OR TMP.BDCODRECCSLL = :BDCODREC OR TMP.BDCODRECCOFINS = :BDCODREC))
                   WHERE (TOT.BDCODEMP = :WCODEMP AND TOT.BDCHAVEUNI = :PRCHAVEUNI AND TOT.BDREFERENCIA = :PRREFERENCIA
                   AND TOT.BDCODREC = :PRCODREC AND TOT.BDVARIACAO = :PRVARIACAO); */

                  FOR
                     SELECT TOT.BDCODMATRIZ,TOT.BDREFERENCIA,TOT.BDCHAVETOT,TMP.BDCODEMP,TMP.BDCHAVELAN, GETORDEMSEQUENCIAL_STR(substring(TOT.BDCODMATRIZ||'|'||TOT.BDREFERENCIA||'|'||TOT.BDCHAVETOT||'|'||TMP.BDCODEMP||'|'||TMP.BDCHAVELAN from 1  for 200), :prCODEMP),
                            TMP.BDVLRINCIALVENDA, TMP.BDVLRORIGPARCELA, TMP.BDVLRRECFIN, TMP.BDDESCONTOPAR,TMP.BDVLRCONSUDIST,TOT.BDCODREC, TOT.BDVARIACAO
                     FROM VEF_EMP_TRET1800TOT TOT
                     LEFT OUTER JOIN TMP_VEF_EMP_APURET1800_TEMP TMP ON  ((TMP.BDCODEMP = TOT.BDCODEMP OR TMP.BDCODMATRIZ = TOT.BDCODEMP) AND TMP.BDCHAVE = TOT.BDCHAVEUNI AND TMP.BDCHAVELAN = :PRCHAVELAN AND
                                                                          (TMP.BDCODREC = :BDCODREC OR TMP.BDCODRECIRPJ = :BDCODREC OR TMP.BDCODRECPIS = :BDCODREC OR TMP.BDCODRECCSLL = :BDCODREC OR TMP.BDCODRECCOFINS = :BDCODREC))
                     WHERE (TOT.BDCODEMP = :WCODEMP AND TOT.BDCHAVEUNI = :PRCHAVEUNI AND TOT.BDREFERENCIA = :PRREFERENCIA
                     AND TOT.BDCODREC = :PRCODREC AND TOT.BDVARIACAO = :PRVARIACAO)
                     AND ((TOT.BDCNPJINCORP IS NULL) OR (TOT.BDCNPJINCORP = :WCNPJINCORP))
                     INTO :BDCODMATRIZ_,:BDREFERENCIA_,:BDCHAVETOT_,:BDCODEMP_,:BDCHAVE_,:BDORDEM_,:BDVLRINIVENDIDO_,:BDVLRRECORIG_,:BDVLRRECFIN_,:BDVLRDESC_,:BDVLRDISTCONS_,:BDCODREC_,:BDVARIACAO_
                  DO
                   BEGIN
                     INSERT INTO VEF_EMP_TRET1800UNID (BDCODMATRIZ, BDREFERENCIA, BDCHAVETOT, BDCODEMP, BDCHAVE,BDORDEM,BDVLRINIVENDIDO, BDVLRRECORIG, BDVLRRECFIN, BDVLRDESC, BDVLRDISTCONS,BDCODREC,BDVARIACAO)
                                               VALUES (:BDCODMATRIZ_,:BDREFERENCIA_,:BDCHAVETOT_,:BDCODEMP_,:BDCHAVE_,:BDORDEM_,:BDVLRINIVENDIDO_,:BDVLRRECORIG_,:BDVLRRECFIN_,:BDVLRDESC_,COALESCE(IIF(:BDVLRDISTCONS_ < :BDVLRABATERUNI, :BDVLRDISTCONS_, :BDVLRABATERUNI),0.00),:BDCODREC_,:BDVARIACAO_);

                     BDVLRABATERUNI = BDVLRABATERUNI - :BDVLRDISTCONS_; -- Alt.: #151565 #151881 - Desconta de cada pagamento sendo inserido...
                     IF (BDVLRABATERUNI < 0) THEN -- Alt.: #157624 - Se descontou tudo na ultima, apenas zera, para nao continuar descontando na proxima e gerar um valor negativo...
                       BDVLRABATERUNI = 0;
                   END

                   FOR
                     SELECT COALESCE(UNI.BDVLRDISTCONS,0.00) FROM VEF_EMP_TRET1800UNID UNI WHERE (UNI.BDCODEMP = :WCODEMP OR UNI.BDCODMATRIZ = :WCODEMP) AND UNI.BDCHAVE = :PRCHAVELAN
                     AND UNI.BDREFERENCIA = :PRREFERENCIA AND UNI.BDVLRDISTCONS <= :BDVLRABATERUNI
                     INTO :PRVLRUTILIZADO
                   DO
                   BEGIN
                     --BDVLRABATERUNI = BDVLRABATERUNI - :PRVLRUTILIZADO;

                     if (BDVLRABATERUNI < 0) then
                        BEGIN
                            UPDATE VEF_EMP_TRET1800UNID U SET
                            U.BDVLRDISTCONS = U.BDVLRDISTCONS + (:BDVLRABATERUNI)
                            WHERE U.BDCODEMP = :WCODEMP
                            AND U.BDCODREC =  :PRCODREC
                            AND U.BDVARIACAO = :PRVARIACAO
                            AND U.BDREFERENCIA = :PRREFERENCIA
                            AND U.BDCHAVE = (SELECT FIRST 1 UNI.BDCHAVE FROM VEF_EMP_TRET1800UNID UNI WHERE UNI.BDCODEMP = :WCODEMP AND UNI.BDCODREC = :PRCODREC
                            AND UNI.BDVARIACAO = :PRVARIACAO AND U.BDREFERENCIA = :PRREFERENCIA AND UNI.BDVLRDISTCONS > 0);
                        END
                   END
                 end
             else
                begin  --INSERINDO UNIDADE SEM VALOR DE SALDO PARA ABATER

                   INSERT INTO VEF_EMP_TRET1800UNID (BDCODMATRIZ, BDREFERENCIA, BDCHAVETOT, BDCODEMP, BDCHAVE,BDORDEM, BDVLRINIVENDIDO, BDVLRRECORIG, BDVLRRECFIN, BDVLRDESC, BDVLRDISTCONS,BDCODREC,BDVARIACAO)
                   SELECT TOT.BDCODMATRIZ,TOT.BDREFERENCIA,TOT.BDCHAVETOT,TMP.BDCODEMP,TMP.BDCHAVELAN,GETORDEMSEQUENCIAL_STR(substring(TOT.BDCODMATRIZ||'|'||TOT.BDREFERENCIA||'|'||TOT.BDCHAVETOT||'|'||TMP.BDCODEMP||'|'||TMP.BDCHAVELAN from 1  for 200), :prCODEMP),
                   TMP.BDVLRINCIALVENDA, TMP.BDVLRORIGPARCELA, TMP.BDVLRRECFIN, TMP.BDDESCONTOPAR,0, TOT.BDCODREC, TOT.BDVARIACAO
                   FROM VEF_EMP_TRET1800TOT TOT
                   LEFT OUTER JOIN TMP_VEF_EMP_APURET1800_TEMP TMP ON ((TMP.BDCODEMP = TOT.BDCODEMP OR TMP.BDCODMATRIZ = TOT.BDCODEMP) AND TMP.BDCHAVE = TOT.BDCHAVEUNI AND TMP.BDCHAVELAN = :PRCHAVELAN
                   AND   (TMP.BDCODREC = :BDCODREC OR TMP.BDCODRECIRPJ = :BDCODREC OR TMP.BDCODRECPIS = :BDCODREC OR TMP.BDCODRECCSLL = :BDCODREC OR TMP.BDCODRECCOFINS = :BDCODREC))
                   WHERE  TOT.BDCODEMP = :WCODEMP AND TOT.BDCHAVEUNI = :PRCHAVEUNI AND TOT.BDREFERENCIA = :PRREFERENCIA
                   AND TOT.BDCODREC = :PRCODREC AND TOT.BDVARIACAO = :PRVARIACAO;
                end
             END
             BDVLRABATER = 0;
             BDVLRABATERUNI = 0;
         END /*2*/
     END /*1*/

 IF (wATUALIZASALDOS = 0) THEN -- Alt.: #224747 - Se Chegou aqui, sem utilizar os saldos, precisa atualizar o que tem de saldos do mes atual, com as sobras do mes anterior...
   BEGIN
     FOR
      SELECT s.bdCODEMP, s.bdCHAVELAN, s.bdCHAVE, s.bdCODMATRIZ
      FROM VEF_EMP_TRET1800SALDOS s
      WHERE s.bdCODMATRIZ = :PRCODEMP AND s.bdREFERENCIA = :PRREFERENCIA
      INTO :PRCODEMP, :PRCHAVELAN, :BDCHAVE_, :PRCODMATRIZ
     DO
       BEGIN
         SELECT s.bdVLRABATIDO, s.bdVLRSALDODISTRATO, s.bdVLRSALDOORIGINAL
         FROM VEF_EMP_TRET1800SALDOS s
         WHERE s.bdCODEMP = :PRCODEMP AND s.bdCHAVELAN = :PRCHAVELAN AND /*s.bdCHAVE = :BDCHAVE_ AND*/ s.bdCODMATRIZ = :PRCODMATRIZ
         AND s.BDREFERENCIA = (SELECT FIRST 1 x.BDREFERENCIA FROM VEF_EMP_TRET1800SALDOS x
                               WHERE x.bdCODMATRIZ = s.bdCODMATRIZ AND x.bdCODEMP = s.bdCODEMP AND x.bdCHAVELAN = s.bdCHAVELAN
                               AND x.BDREFERENCIA < :PRREFERENCIA ORDER BY x.BDREFERENCIA DESC)
         INTO :bdVLRABATIDO, :bdVLRSALDODISTRATO, :bdVLRSALDOORIGINAL;

         UPDATE VEF_EMP_TRET1800SALDOS s
         SET /*s.bdVLRABATIDO       = s.bdVLRABATIDO + COALESCE(:bdVLRABATIDO,0),*/
             s.bdVLRSALDODISTRATO = s.bdVLRSALDODISTRATO + COALESCE(:bdVLRSALDODISTRATO,0)/* - COALESCE(:bdVLRABATIDO,0)*/,
             s.bdVLRSALDOORIGINAL = s.bdVLRSALDOORIGINAL + COALESCE(:bdVLRSALDOORIGINAL,0)
         WHERE (s.bdCODEMP = :PRCODEMP) AND (s.bdCHAVELAN = :PRCHAVELAN) AND (s.bdCHAVE = :BDCHAVE_) AND (s.bdREFERENCIA = :PRREFERENCIA) AND (s.bdCODMATRIZ = :PRCODMATRIZ);
       END
   END

  /*ATUALIZADO OS SALDOS NA TABELA DE TOTAIS CONFORME O INSERIDO NA TABELA DE UNIDADES ACIMA*/

 FOR
  SELECT UNI.BDCODMATRIZ BDCODEMP,UNI.BDCODMATRIZ, UNI.BDCHAVETOT, SUM(COALESCE(UNI.BDVLRDISTCONS,0)) BDVLRDISTCONS
  FROM VEF_EMP_TRET1800UNID UNI
  WHERE (UNI.BDCODEMP = :PRCODEMP OR UNI.BDCODMATRIZ = :PRCODEMP) AND UNI.BDREFERENCIA = :PRREFERENCIA
  GROUP BY BDCODEMP,BDCODMATRIZ,BDCHAVETOT
  INTO :PRCODEMP, :PRCODMATRIZ,:PRCHAVETOT, :PRVLRDISTCONS
 DO
   BEGIN
     UPDATE VEF_EMP_TRET1800TOT TOT
     SET TOT.BDBASECALCULO = ((TOT.BDVLRRECORIGINAL + TOT.BDVLRRECFIN) -  (TOT.BDVLRDESCONTO + :PRVLRDISTCONS)),
         TOT.BDVLRDISTRADO = :PRVLRDISTCONS,
         TOT.BDVALOR = ((TOT.BDVLRRECORIGINAL + TOT.BDVLRRECFIN) -  (TOT.BDVLRDESCONTO + :PRVLRDISTCONS)) * (TOT.BDALIQUOTA /100)
     WHERE TOT.BDCODMATRIZ = :PRCODMATRIZ AND TOT.BDCODEMP = :PRCODEMP
     AND   TOT.BDCHAVETOT = :PRCHAVETOT
     AND   TOT.BDREFERENCIA = :PRREFERENCIA;


   END

   DELETE FROM TMP_VEF_EMP_APURET1800_TEMP WHERE BDCODEMP = :PRCODEMP OR BDCODMATRIZ = :PRCODEMP;

end
^

CREATE OR ALTER procedure SP_APURACAO_BLOCOM_RET1800 (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRWHEREEMPRESAS varchar(10000),
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN)
as
declare variable WOPTANTERET DM_BOOLEAN;
declare variable WEXISTEAPUR varchar(50);
declare variable WSQL varchar(32751);
BEGIN

  /*
    REGISTRO 1800: INCORPORAÇÕES IMOBILIÁRIAS - RET
    QUADRO DO RET - 55
  */

 -- Insere a competência da apuração...
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Verifica se a empresa é Optante do RET

  SELECT BDOPTANTERET FROM VWEF_EMPMENSAL_ABA_FEDE_REF WHERE BDCODEMP = :PRCODEMP INTO WOPTANTERET;

  if (WOPTANTERET = 'TRUE' ) then
     BEGIN

       -- Verifica se já tem uma apuração do RET para o período
       SELECT FIRST 1 BDCODEMP FROM VEF_EMP_TRET1800GER WHERE BDCODMATRIZ = :PRCODEMP AND BDREFERENCIA = :PRREFERENCIA
       INTO WEXISTEAPUR;

       -- Se não tiver, executa a apuração do RET, os valores no 1800 serão todos retirados da apuração
       if (WEXISTEAPUR IS NULL) then
          BEGIN
            EXECUTE PROCEDURE SP_APURACAO_RET1800(:PRCODEMP,:PRREFERENCIA);
          END

       wSQL =       ' INSERT INTO VEF_EMP_TBLOCOMRET1800 (BDCODQUADRO, BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCHAVE, BDCNPJ, BDCODEMPREENDIMENTO, BDVLRRECORIGINAL, ';
       wSQL = wSQL||'                                    BDVLRDESCONTO, BDVLRDISTRATOS, BDBASECALCULO, BDALIQUOTA, BDVALOR, BDDATAPGTO, BDCODREC, BDVARIACAO)';
       wSQL = wSQL||' SELECT RET.BDCODQUADRO,RET.BDCODPERIODO, RET.BDCODEMP,RET.BDCODMATRIZ,RET.BDREFERENCIA, ';
       wSQL = wSQL||'GETORDEMSEQUENCIAL_STR(''1800.''||RET.BDCODPERIODO||''.''||RET.BDCODEMP||''.''||RET.BDCODMATRIZ||''.''||RET.BDCODQUADRO||''.''||RET.BDREFERENCIA, '||:prCODEMP||') AS BDCHAVE,';
/*       wSQL = wSQL||' (SELECT COALESCE(MAX(x.BDCHAVE+1),1) FROM VEF_EMP_TBLOCOMRET1800 x WHERE x.BDCODPERIODO = RET.BDCODPERIODO AND x.BDCODEMP = RET.BDCODEMP and x.BDCODMATRIZ = RET.BDCODMATRIZ AND x.BDCODQUADRO = RET.BDCODQUADRO AND x.BDREFERENCIA = RET.BDREFERENCIA) AS BDCHAVE, ';*/
       wSQL = wSQL||' RET.BDCNPJ,RET.BDCODEMPREENDIMENTO,SUM(RET.BDVLRRECORIGINAL) BDVLRRECORIGINAL, SUM(RET.BDVLRDESCONTO) BDVLRDESCONTO,SUM(RET.BDVLRDISTRADO) BDVLRDISTRADO, ';
       wSQL = wSQL||' SUM(RET.BDBASECALCULO) BDBASECALCULO, RET.BDALIQUOTA , CAST((SUM(RET.BDBASECALCULO) * (BDALIQUOTA/100))AS DM_NUMERIC_15_2) BDVALOR,RET.BDDATAPGTO ,RET.BDCODREC, RET.BDVARIACAO ';
       wSQL = wSQL||' FROM(';
       wSQL = wSQL||'      SELECT 55 AS BDCODQUADRO, 7 AS BDCODPERIODO, UNI.BDCODEMP BDCODEMP, RET.BDCODMATRIZ, RET.BDREFERENCIA, RET.BDCNPJINCORP BDCNPJ,F200.BDCODEMPREENDIMENTO, ';
       wSQL = wSQL||'      UNI.BDVLRRECORIG BDVLRRECORIGINAL , UNI.BDVLRDESC BDVLRDESCONTO, UNI.BDVLRDISTCONS BDVLRDISTRADO, RET.BDALIQUOTA,RET.BDCODREC, RET.BDVARIACAO, UNI.BDVLRRECFIN, ';
       wSQL = wSQL||'      ((UNI.BDVLRRECORIG + UNI.BDVLRRECFIN) -  (UNI.BDVLRDESC + UNI.BDVLRDISTCONS)) BDBASECALCULO, PGTO.BDDATAPGTO ';
       wSQL = wSQL||'      FROM(';
       wSQL = wSQL||'           SELECT RET.BDCODEMP, RET.BDCODMATRIZ, RET.BDREFERENCIA, RET.BDCNPJINCORP,RET.BDALIQUOTA,RET.BDCODREC, RET.BDVARIACAO,RET.BDCHAVETOT ';
       wSQL = wSQL||'           FROM VEF_EMP_TRET1800TOT RET ';
       wSQL = wSQL||'           WHERE RET.'||TRIM(:prWHEREEMPRESAS)||' ';
       wSQL = wSQL||'           AND RET.BDREFERENCIA = '||:prREFERENCIA||' ';
       wSQL = wSQL||'          ) RET';
       wSQL = wSQL||'     LEFT OUTER JOIN VEF_EMP_TRET1800UNID UNI ON (UNI.BDCODMATRIZ = RET.BDCODEMP AND UNI.BDCHAVETOT = RET.BDCHAVETOT AND UNI.BDREFERENCIA = RET.BDREFERENCIA) ';
       wSQL = wSQL||'     LEFT OUTER JOIN VEF_EMP_TMOVOPIMOBILIARIA_F200 F200 ON (F200.BDCODEMP = UNI.BDCODEMP AND F200.BDCHAVE = UNI.BDCHAVE) ';
       /* Alt.: #186868 - Quando tinham vários impostos com o mesmo código de receita e variação, estava multiplicando o valor do RET, por isso vai buscar direto do DARF, do impostos que tenha apurado... */
       --wSQL = wSQL||'     LEFT OUTER JOIN TIMPOSTO IMP ON (IMP.BDCODRECVAR = RET.BDCODREC AND IMP.BDVARIACAO = RET.BDVARIACAO) ';
       --wSQL = wSQL||'     LEFT OUTER JOIN TDARFPADRAO DARF ON (DARF.BDCODEMP = RET.BDCODEMP AND DARF.BDREFERENCIA = RET.BDREFERENCIA AND DARF.BDCODIMP = IMP.BDCODIMP AND DARF.BDCODREC = IMP.BDCODREC AND DARF.BDCNPJDARF = RET.BDCNPJINCORP) ';
       wSQL = wSQL||'     LEFT OUTER JOIN TDARFPADRAO DARF ON (DARF.BDCODEMP = RET.BDCODEMP AND DARF.BDREFERENCIA = RET.BDREFERENCIA AND DARF.BDCODREC = RET.BDCODREC AND DARF.BDCNPJDARF = RET.BDCNPJINCORP) ';
       --wSQL = wSQL||'     LEFT OUTER JOIN TDARFGERPGTO PGTO ON (PGTO.BDCODEMP = RET.BDCODEMP AND PGTO.BDCHAVEDARF = DARF.BDCHAVEDARF) '; Alt.: #186868 - Quando tinham varios pagamentos, estava multiplicando o valor do RET pela quantidade de pagamentos...
       wSQL = wSQL||'     LEFT OUTER JOIN (SELECT pgto.bdCODEMP, pgto.bdCHAVEDARF, MIN(pgto.bdDATAPGTO) bdDATAPGTO ';
       wSQL = wSQL||'                      FROM TDARFGERPGTO pgto ';
       wSQL = wSQL||'                      WHERE pgto.'||TRIM(:prWHEREEMPRESAS)||' ';
       wSQL = wSQL||'                      GROUP BY pgto.bdCODEMP, pgto.bdCHAVEDARF) pgto ON (pgto.bdCODEMP = ret.bdCODEMP AND pgto.bdCHAVEDARF = darf.bdCHAVEDARF) ';
       wSQL = wSQL||'     ) RET ';
       wSQL = wSQL||' GROUP BY  RET.BDCODQUADRO,RET.BDCODPERIODO, RET.BDCODEMP,RET.BDCODMATRIZ,RET.BDREFERENCIA, RET.BDCNPJ, RET.BDCODEMPREENDIMENTO,RET.BDALIQUOTA,RET.BDDATAPGTO ,RET.BDCODREC, RET.BDVARIACAO ';

       EXECUTE STATEMENT wSQL;

     END


END
^

create or alter procedure SP_APURACAO_BLOCOM (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRVERIFICARINCONSISTENCIAS DM_BOOLEAN,
    PRAJUSTESCP DM_BOOLEAN,
    PRRETIFICADORA integer,
    PRCONTABILIZAFILIAL DM_BOOLEAN = 'FALSE')
as
declare variable WCODCONFBLOCOM integer;
declare variable WCODEMP integer;
declare variable WWHEREEMPRESAS varchar(10000);
declare variable WWHEREEMPRESASSCP varchar(10000);
declare variable WCODEMPSCP integer;
declare variable WCODQUADRO integer;
declare variable WNUMCAMPO integer;
declare variable WVALOR DM_NUMERIC_15_2;
declare variable WDELETARETIFICADORA DM_BOOLEAN;
declare variable WVALORAUX DM_NUMERIC_15_2;
declare variable WCODEMPFILIAL integer;
begin
  delete from VEF_INCON_BLOCOM M
  where M.BDCODEMP = :PRCODEMP and
        M.BDREFERENCIA = :PRREFERENCIA and
        M.BDCODPERIODO = 7;

  -- Insere a competência da apuração...
  execute procedure SP_SETA_COMPETENCIA(:PRREFERENCIA);

  -- Obtém a configuração do Bloco M...
  select BDCODCONFBLOCOM
  from VW_VEF_BASE_TEMPPARGER
  where BDCODEMP = :PRCODEMP
  into :WCODCONFBLOCOM;

  -- Quando não tiver configuração de Blooo M na empresa, vai buscar uma configuração padrão...
  if (WCODCONFBLOCOM is null) then
    begin
      select first 1 BDCODCONF
      from VEF_BASE_TCONFBLOCOM
      where BDPLANOPADRAO = 'TRUE'
      into :WCODCONFBLOCOM;
    end

  --Garantir que não precisa mexer na contabilização quando não tem filial cadastrada
  if ((:PRCONTABILIZAFILIAL = 'TRUE') and (coalesce((select first 1 BDCODEMP from TEMPRESAS EX where EX.BDCODMATRIZ = :PRCODEMP), 0) = 0)) then
    :PRCONTABILIZAFILIAL = 'FALSE';

  WWHEREEMPRESAS = '';
  --WWHEREEMPRESASSCP = ' BDCODEMP in (' || :PRCODEMP || ')'; Alt.: #236818

  /* Cria apuração do Bloco M, necessário para os registros abaixo... */
  for select EX.BDCODEMP, null BDCODEMPSCP
      from TEMPRESAS EX
      where EX.BDCODEMP = :PRCODEMP or EX.BDCODMATRIZ = :PRCODEMP
      union all
      select SCP.BDCODEMPSCP BDCODEMP, SCP.BDCODEMPSCP
      from TEMPRESAS_SCP SCP
      where SCP.BDCODEMP in (select EX.BDCODEMP
                             from TEMPRESAS EX
                             where EX.BDCODEMP = :PRCODEMP or EX.BDCODMATRIZ = :PRCODEMP) and
            (SCP.BDCODEMPSCP is not null and
            SCP.BDCODEMPSCP > 0) and
            (SCP.BDDATAFINAL is null or (select BDAAAAMM
                                         from AAAAMM(SCP.BDDATAFINAL)) >= :PRREFERENCIA) and
            :PRAJUSTESCP = 'TRUE'
      group by SCP.BDCODEMPSCP
      into :WCODEMP, :WCODEMPSCP
  do
  begin
    insert into VEF_EMP_TBLOCOMGER (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCONF, BDRETIFICADORA)
    values (7, :WCODEMP, coalesce(:WCODEMPSCP, :PRCODEMP), :PRREFERENCIA, :WCODCONFBLOCOM, :PRRETIFICADORA);

    if (:WCODEMPSCP is null) then
      WWHEREEMPRESAS = WWHEREEMPRESAS || WCODEMP || ',';
  end

  WWHEREEMPRESASSCP = ' BDCODEMP in (' || substring(WWHEREEMPRESAS from 1 for character_length(WWHEREEMPRESAS) - 1) || ')'; -- Alt.: #236818 - Quando for buscar os valores das SCPs, deve buscar também das filiais, pois as SCPs tambem pode estar vinculadas nessas empresas filais...
  WWHEREEMPRESAS = ' bdCODEMP IN(' || substring(WWHEREEMPRESAS from 1 for character_length(WWHEREEMPRESAS) - 1) || ') ';

  --  SETORDEMSEQUENCIAL_STR(:prCODEMP);
  if (:WCODCONFBLOCOM is not null) then
  begin
    /* REGISTRO 0111: TABELA DE RECEITA BRUTA MENSAL PARA FINS DE RATEIO DE CRÉDITOS COMUNS */
    execute procedure SP_APURACAO_BLOCOM_0110(:PRCODEMP, :PRREFERENCIA, 'FALSE', :PRRETIFICADORA);

    /* REGISTRO M100: CRÉDITO DE PIS/PASEP RELATIVO AO PERÍODO
       REGISTRO M500: CRÉDITO DE COFINS RELATIVO AO PERÍODO */
    execute procedure SP_APURACAO_BLOCOM_M100_M500(:PRCODEMP, :PRREFERENCIA, :WWHEREEMPRESAS, :PRVERIFICARINCONSISTENCIAS, :PRAJUSTESCP, :PRRETIFICADORA, false, 0);

    /* REGISTRO 1100: CONTROLE DE CRÉDITOS FISCAIS - PIS/PASEP
       REGISTRO 1500: CONTROLE DE CRÉDITOS FISCAIS - COFINS */
    execute procedure SP_APURACAO_BLOCOM_1100_1500(:PRCODEMP, :PRREFERENCIA, :WWHEREEMPRESAS, :PRAJUSTESCP, :PRRETIFICADORA, 0);

    /* REGISTRO F600: CONTRIBUIÇÃO RETIDA NA FONTE
       REGISTRO 1300: CONTROLE DOS VALORES RETIDOS NA FONTE - PIS/PASEP
       REGISTRO 1700: CONTROLE DOS VALORES RETIDOS NA FONTE - COFINS */
    execute procedure SP_APURACAO_BLOCOM_F60013001700(:PRCODEMP, :PRREFERENCIA, :WWHEREEMPRESAS, :PRAJUSTESCP, :PRRETIFICADORA, 0);

    /* REGISTRO M300: CONTRIBUIÇÃO DE PIS/PASEP DIFERIDA EM PERÍODOS ANTERIORES - VALORES A PAGAR NO PERÍODO.
       REGISTRO M700: COFINS DIFERIDA EM PERÍODOS ANTERIORES - VALORES A PAGAR NO PERÍODO */
    execute procedure SP_APURACAO_BLOCOM_M300_M700(:PRCODEMP, :PRREFERENCIA, :WWHEREEMPRESAS, :PRVERIFICARINCONSISTENCIAS, :PRAJUSTESCP, :PRRETIFICADORA, 0);

    /* REGISTRO M400: RECEITAS ISENTAS, NÃO ALCANÇADAS PELA INCIDÊNCIA DA CONTRIBUIÇÃO, SUJEITAS A ALÍQUOTA ZERO OU DE VENDAS COM SUSPENSÃO - PIS/PASEP
       REGISTRO M800: RECEITAS ISENTAS, NÃO ALCANÇADAS PELA INCIDÊNCIA DA CONTRIBUIÇÃO, SUJEITAS A ALÍQUOTA ZERO OU DE VENDAS COM SUSPENSÃO - COFINS */
    execute procedure SP_APURACAO_BLOCOM_M400_M800(:PRCODEMP, :PRREFERENCIA, :WWHEREEMPRESAS, :PRVERIFICARINCONSISTENCIAS, :PRAJUSTESCP, :PRRETIFICADORA);

    /* REGISTRO M200: CONSOLIDAÇÃO DA CONTRIBUIÇÃO PARA O PIS/PASEP DO PERÍODO
       REGISTRO M600: CONSOLIDAÇÃO DA CONTRIBUIÇÃO PARA A SEGURIDADE SOCIAL - COFINS DO PERÍODO */
    execute procedure SP_APURACAO_BLOCOM_M200_M600(:PRCODEMP, :PRREFERENCIA, :WWHEREEMPRESAS, :PRVERIFICARINCONSISTENCIAS, :PRAJUSTESCP, :PRRETIFICADORA, :PRCONTABILIZAFILIAL, 0);

    /* REGISTRO 1800: CONTROLE RET - Incorporação Imobiliária RET*/
    execute procedure SP_APURACAO_BLOCOM_RET1800(:PRCODEMP, :PRREFERENCIA, :WWHEREEMPRESAS, :PRVERIFICARINCONSISTENCIAS);

    /* Gera últimos ajustes da apuração */
    EXECUTE PROCEDURE SP_APURACAO_BLOCOM_DADOSFINAIS (:prCODEMP, :prREFERENCIA, :PRRETIFICADORA, :PRAJUSTESCP, :prCODEMP);

    /* Cria a contabilização */
    execute procedure SP_APURACAO_BLOCOM_ONLINE(:PRCODEMP, :PRREFERENCIA, :PRCODEMP, :PRRETIFICADORA, :PRCONTABILIZAFILIAL);

    /* Cria a contabilização */
    if (:PRCONTABILIZAFILIAL = 'TRUE') then
    begin
      for select EX.BDCODEMP
          from TEMPRESAS EX
          where EX.BDCODMATRIZ = :PRCODEMP
          into :WCODEMPFILIAL
      do
      begin
        /* Cria a contabilização */
        execute procedure SP_APURACAO_BLOCOM_ONLINE(:WCODEMPFILIAL, :PRREFERENCIA, :PRCODEMP, :PRRETIFICADORA, :PRCONTABILIZAFILIAL);
      end
    end

    /*Camilla M. SCP - Vai atualizar os dados para as SCPs
      É mais viável chamar a procedure para cada SCP, do que colocar um monte de FOR SELECT la dentro, para pegar as SCPs também
      Mandando o código de empresa SCP direto na procedure, não é necessário nenhuma alteração lá dentro*/
    if (:PRAJUSTESCP = 'TRUE') then
    begin
      for select SCP.BDCODEMPSCP
          from TEMPRESAS_SCP SCP
          where SCP.BDCODEMP in (select EX.BDCODEMP
                                 from TEMPRESAS EX
                                 where EX.BDCODEMP = :PRCODEMP or EX.BDCODMATRIZ = :PRCODEMP) and
                (SCP.BDCODEMPSCP is not null and
                SCP.BDCODEMPSCP > 0) and
                (SCP.BDDATAFINAL is null or (select BDAAAAMM
                                             from AAAAMM(SCP.BDDATAFINAL)) >= :PRREFERENCIA) and
                ((select BDAAAAMM
                  from AAAAMM(SCP.BDDATAINICIAL)) <= :PRREFERENCIA)
          group by SCP.BDCODEMPSCP
          into :WCODEMPSCP
      do
      begin
        delete from TMP_VEF_EMP_TBLOCOM_M100_M500 TMP where ((TMP.BDCODMATRIZ = :PRCODEMP) or (TMP.BDCODMATRIZ in (select SCP.BDCODEMPSCP from TEMPRESAS_SCP SCP where SCP.BDCODEMP = :PRCODEMP))) and TMP.BDREFERENCIA = :PRREFERENCIA;
        delete from TMP_VEF_EMP_TBLOCOM_F600_1300 TMP where ((TMP.BDCODMATRIZ = :PRCODEMP) or (TMP.BDCODMATRIZ in (select SCP.BDCODEMPSCP from TEMPRESAS_SCP SCP where SCP.BDCODEMP = :PRCODEMP))) and TMP.BDREFERENCIA = :PRREFERENCIA;
        delete from TMP_VEF_EMP_TBLOCOM_M400_M800 TMP where ((TMP.BDCODMATRIZ = :PRCODEMP) or (TMP.BDCODMATRIZ in (select SCP.BDCODEMPSCP from TEMPRESAS_SCP SCP where SCP.BDCODEMP = :PRCODEMP))) and TMP.BDREFERENCIA = :PRREFERENCIA;
        delete from TMP_VEF_EMP_TBLOCOM_M210_M610 TMP where ((TMP.BDCODMATRIZ = :PRCODEMP) or (TMP.BDCODMATRIZ in (select SCP.BDCODEMPSCP from TEMPRESAS_SCP SCP where SCP.BDCODEMP = :PRCODEMP))) and TMP.BDREFERENCIA = :PRREFERENCIA;
        delete from TMP_VEF_EMP_TBLOCOM_0110_TEMP TMP where ((TMP.BDCODMATRIZ = :PRCODEMP) or (TMP.BDCODMATRIZ in (select SCP.BDCODEMPSCP from TEMPRESAS_SCP SCP where SCP.BDCODEMP = :PRCODEMP))) and TMP.BDREFERENCIA = :PRREFERENCIA;
        delete from TMP_VEF_EMP_TBLOCOM_0111_TEMP TMP where ((TMP.BDCODMATRIZ = :PRCODEMP) or (TMP.BDCODMATRIZ in (select SCP.BDCODEMPSCP from TEMPRESAS_SCP SCP where SCP.BDCODEMP = :PRCODEMP))) and TMP.BDREFERENCIA = :PRREFERENCIA;
        delete from TMP_TCONF_CONTAS_ONLINE_TEMP TMP where ((TMP.BDCODMATRIZ = :PRCODEMP) or (TMP.BDCODMATRIZ in (select SCP.BDCODEMPSCP from TEMPRESAS_SCP SCP where SCP.BDCODEMP = :PRCODEMP))) and TMP.BDREFERENCIA = :PRREFERENCIA;

        /* REGISTRO 0111: TABELA DE RECEITA BRUTA MENSAL PARA FINS DE RATEIO DE CRÉDITOS COMUNS */
        execute procedure SP_APURACAO_BLOCOM_0110(:WCODEMPSCP, :PRREFERENCIA, 'FALSE', :PRRETIFICADORA);

        /* REGISTRO M100: CRÉDITO DE PIS/PASEP RELATIVO AO PERÍODO
           REGISTRO M500: CRÉDITO DE COFINS RELATIVO AO PERÍODO */
        execute procedure SP_APURACAO_BLOCOM_M100_M500(:WCODEMPSCP, :PRREFERENCIA, :WWHEREEMPRESASSCP, :PRVERIFICARINCONSISTENCIAS, :PRAJUSTESCP, :PRRETIFICADORA, false, :PRCODEMP);

        /* REGISTRO 1100: CONTROLE DE CRÉDITOS FISCAIS - PIS/PASEP
           REGISTRO 1500: CONTROLE DE CRÉDITOS FISCAIS - COFINS */
        execute procedure SP_APURACAO_BLOCOM_1100_1500(:WCODEMPSCP, :PRREFERENCIA, :WWHEREEMPRESASSCP, :PRAJUSTESCP, :PRRETIFICADORA, :PRCODEMP);

        /* REGISTRO F600: CONTRIBUIÇÃO RETIDA NA FONTE
           REGISTRO 1300: CONTROLE DOS VALORES RETIDOS NA FONTE - PIS/PASEP
           REGISTRO 1700: CONTROLE DOS VALORES RETIDOS NA FONTE - COFINS */
        execute procedure SP_APURACAO_BLOCOM_F60013001700(:WCODEMPSCP, :PRREFERENCIA, :WWHEREEMPRESASSCP, :PRAJUSTESCP, :PRRETIFICADORA, :PRCODEMP);

        /* REGISTRO M300: CONTRIBUIÇÃO DE PIS/PASEP DIFERIDA EM PERÍODOS ANTERIORES - VALORES A PAGAR NO PERÍODO.
           REGISTRO M700: COFINS DIFERIDA EM PERÍODOS ANTERIORES - VALORES A PAGAR NO PERÍODO */
        execute procedure SP_APURACAO_BLOCOM_M300_M700(:WCODEMPSCP, :PRREFERENCIA, :WWHEREEMPRESASSCP, :PRVERIFICARINCONSISTENCIAS, :PRAJUSTESCP, :PRRETIFICADORA, :PRCODEMP);

        /* REGISTRO M400: RECEITAS ISENTAS, NÃO ALCANÇADAS PELA INCIDÊNCIA DA CONTRIBUIÇÃO, SUJEITAS A ALÍQUOTA ZERO OU DE VENDAS COM SUSPENSÃO - PIS/PASEP
           REGISTRO M800: RECEITAS ISENTAS, NÃO ALCANÇADAS PELA INCIDÊNCIA DA CONTRIBUIÇÃO, SUJEITAS A ALÍQUOTA ZERO OU DE VENDAS COM SUSPENSÃO - COFINS */
        execute procedure SP_APURACAO_BLOCOM_M400_M800(:WCODEMPSCP, :PRREFERENCIA, :WWHEREEMPRESASSCP, :PRVERIFICARINCONSISTENCIAS, :PRAJUSTESCP, :PRRETIFICADORA, :PRCODEMP);

        /* REGISTRO M200: CONSOLIDAÇÃO DA CONTRIBUIÇÃO PARA O PIS/PASEP DO PERÍODO
           REGISTRO M600: CONSOLIDAÇÃO DA CONTRIBUIÇÃO PARA A SEGURIDADE SOCIAL - COFINS DO PERÍODO */
        execute procedure SP_APURACAO_BLOCOM_M200_M600(:WCODEMPSCP, :PRREFERENCIA, :WWHEREEMPRESASSCP, :PRVERIFICARINCONSISTENCIAS, :PRAJUSTESCP, :PRRETIFICADORA, :PRCONTABILIZAFILIAL, :PRCODEMP);

        /* REGISTRO 1800: CONTROLE RET - Incorporação Imobiliária RET*/
        execute procedure SP_APURACAO_BLOCOM_RET1800(:WCODEMPSCP, :PRREFERENCIA, :WWHEREEMPRESASSCP, :PRVERIFICARINCONSISTENCIAS);

        /* Gera últimos ajustes da apuração */
        EXECUTE PROCEDURE SP_APURACAO_BLOCOM_DADOSFINAIS (:WCODEMPSCP, :prREFERENCIA, :PRRETIFICADORA, :PRAJUSTESCP, :prCODEMP);

        /* Cria a contabilização */
        execute procedure SP_APURACAO_BLOCOM_ONLINE(:WCODEMPSCP, :PRREFERENCIA, :PRCODEMP, :PRRETIFICADORA, 'FALSE');
      end
    end

    execute procedure SP_APURACAO_BLOCOM_AJUSTACONTAB(:PRCODEMP, :PRREFERENCIA, 'PIS');
    execute procedure SP_APURACAO_BLOCOM_AJUSTACONTAB(:PRCODEMP, :PRREFERENCIA, 'COF');

    /*Verifica se teve mudança de valores da apuração normal para a retificadora, se não tiver deleta a retificadora.*/
    if (:PRRETIFICADORA = 1) then
    begin
      WDELETARETIFICADORA = 'TRUE';

      for select REG.BDCODQUADRO, REG.BDNUMCAMPO, REG.BDVALOR
          from VEF_EMP_TBLOCOMGERREG REG
          where REG.BDCODPERIODO = 7 and
                REG.BDCODEMP = :PRCODEMP and
                REG.BDREFERENCIA = :PRREFERENCIA and
                REG.BDRETIFICADORA = :PRRETIFICADORA and
                REG.BDCODQUADRO in (15, 33) and
                REG.BDNUMCAMPO = 13
          order by REG.BDCODEMP, REG.BDREFERENCIA, REG.BDCODQUADRO, REG.BDNUMCAMPO
          into WCODQUADRO, WNUMCAMPO, WVALOR
      do
      begin
        --PIS -> Valor da contribuição a recolher no período
        if ((WCODQUADRO = 15) and (WNUMCAMPO = 13)) then
        begin
          select first 1 BDVALOR
          from VEF_EMP_TBLOCOMGERREG
          where BDCODPERIODO = 7 and
                BDCODEMP = :PRCODEMP and
                BDREFERENCIA = :PRREFERENCIA and
                BDRETIFICADORA = 0 and
                BDCODQUADRO = :WCODQUADRO and
                BDNUMCAMPO = :WNUMCAMPO
          into WVALORAUX;

          if (WVALOR <> WVALORAUX) then
            WDELETARETIFICADORA = 'FALSE';
        end
        else

        -- COFINS -> Valor da contribuição a recolher no período.
        if ((WCODQUADRO = 33) and (WNUMCAMPO = 13)) then
        begin
          select first 1 BDVALOR
          from VEF_EMP_TBLOCOMGERREG
          where BDCODPERIODO = 7 and
                BDCODEMP = :PRCODEMP and
                BDREFERENCIA = :PRREFERENCIA and
                BDRETIFICADORA = 0 and
                BDCODQUADRO = :WCODQUADRO and
                BDNUMCAMPO = :WNUMCAMPO
          into WVALORAUX;

          if (WVALOR <> WVALORAUX) then
            WDELETARETIFICADORA = 'FALSE';
        end
      end

      if (:WDELETARETIFICADORA = 'TRUE') then
      begin
        /* Alt.: 183336 - Estava deletando de forma errada as apurações retificadoras, deletava apenas os valores dos quadro, mas mantinha valores dos os saldos e alguns quadros,
           Ajustado para deletar toda a apuração, assim vai apagar todos esses valores que apresentavam problemas nas apurações porteriores e vai gerar uma nova, apenas com a inconsistência...  */
        delete from VEF_EMP_TBLOCOMGER
        where BDCODEMP = :PRCODEMP and
              BDREFERENCIA = :PRREFERENCIA and
              BDCODPERIODO = 7 and
              BDRETIFICADORA = :PRRETIFICADORA;

        insert into VEF_EMP_TBLOCOMGER (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODCONF, BDRETIFICADORA)
        values (7, :PRCODEMP, :PRCODEMP, :PRREFERENCIA, :WCODCONFBLOCOM, :PRRETIFICADORA);

        insert into VEF_INCON_BLOCOM (BDCODEMP, BDREFERENCIA, BDCODPERIODO, BDRETIFICADORA, BDCODINC, BDCODBLOCOM, BDCODMATRIZ)
        values (:PRCODEMP, :PRREFERENCIA, 7, :PRRETIFICADORA, 31, GETORDEMSEQUENCIAL_STR(:PRCODEMP || '.' || :PRCODEMP || '.' || :PRREFERENCIA, :PRCODEMP), :PRCODEMP);
      end
    end

    /* Apaga os dados das tabelas temporárias, faz isso pq se apura-se mais de uma vez, somava todos os valores */
    delete from TMP_VEF_EMP_TBLOCOM_M100_M500 TMP where ((TMP.BDCODMATRIZ = :PRCODEMP) or (TMP.BDCODMATRIZ in (select SCP.BDCODEMPSCP from TEMPRESAS_SCP SCP where SCP.BDCODEMP = :PRCODEMP))) and TMP.BDREFERENCIA = :PRREFERENCIA;
    delete from TMP_VEF_EMP_TBLOCOM_F600_1300 TMP where ((TMP.BDCODMATRIZ = :PRCODEMP) or (TMP.BDCODMATRIZ in (select SCP.BDCODEMPSCP from TEMPRESAS_SCP SCP where SCP.BDCODEMP = :PRCODEMP))) and TMP.BDREFERENCIA = :PRREFERENCIA;
    delete from TMP_VEF_EMP_TBLOCOM_M400_M800 TMP where ((TMP.BDCODMATRIZ = :PRCODEMP) or (TMP.BDCODMATRIZ in (select SCP.BDCODEMPSCP from TEMPRESAS_SCP SCP where SCP.BDCODEMP = :PRCODEMP))) and TMP.BDREFERENCIA = :PRREFERENCIA;
    delete from TMP_VEF_EMP_TBLOCOM_M210_M610 TMP where ((TMP.BDCODMATRIZ = :PRCODEMP) or (TMP.BDCODMATRIZ in (select SCP.BDCODEMPSCP from TEMPRESAS_SCP SCP where SCP.BDCODEMP = :PRCODEMP))) and TMP.BDREFERENCIA = :PRREFERENCIA;
    delete from TMP_VEF_EMP_TBLOCOM_0110_TEMP TMP where ((TMP.BDCODMATRIZ = :PRCODEMP) or (TMP.BDCODMATRIZ in (select SCP.BDCODEMPSCP from TEMPRESAS_SCP SCP where SCP.BDCODEMP = :PRCODEMP))) and TMP.BDREFERENCIA = :PRREFERENCIA;
    delete from TMP_VEF_EMP_TBLOCOM_0111_TEMP TMP where ((TMP.BDCODMATRIZ = :PRCODEMP) or (TMP.BDCODMATRIZ in (select SCP.BDCODEMPSCP from TEMPRESAS_SCP SCP where SCP.BDCODEMP = :PRCODEMP))) and TMP.BDREFERENCIA = :PRREFERENCIA;
    delete from TMP_TCONF_CONTAS_ONLINE_TEMP TMP where ((TMP.BDCODMATRIZ = :PRCODEMP) or (TMP.BDCODMATRIZ in (select SCP.BDCODEMPSCP from TEMPRESAS_SCP SCP where SCP.BDCODEMP = :PRCODEMP))) and TMP.BDREFERENCIA = :PRREFERENCIA;
  end
  else
  begin
    insert into VEF_INCON_BLOCOM (BDCODPERIODO, BDCODEMP, BDCODMATRIZ, BDREFERENCIA, BDCODBLOCOM, BDCODTP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDRETIFICADORA)
    values (7, :PRCODEMP, :PRCODEMP, :PRREFERENCIA, GETORDEMSEQUENCIAL_STR(:PRCODEMP || '.' || :PRCODEMP || '.' || :PRREFERENCIA, :PRCODEMP), null, null, null, null, 5, :PRRETIFICADORA);
  end

  SETORDEMSEQUENCIAL_STR(:PRCODEMP);
end
^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_BLOCOM (
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRCLASSIFICACAO VARCHAR(11) = NULL,
    PRCODQUADRO INTEGER = NULL,
    PRRETIFICADORA integer = 0,
    PRREFFINAL integer = 0)
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDREFERENCIA integer,
    BDCODQUADRO integer,
    BDNUMCAMPO integer,
    BDCLASSIFICACAO varchar(11),
    BDDESCRICAO varchar(80),
    BDVALOR numeric(15,2),
    BDTIPO integer)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WCODEMP integer;
declare variable WCODMATRIZ integer;
declare variable WREFERENCIA integer;
declare variable WCODQUADRO integer;
declare variable WNUMCAMPO integer;
declare variable WCLASSIFICACAO varchar(11);
declare variable WDESCRICAO varchar(80);
declare variable WVALOR numeric(15,2);
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA, NULL, NULL);

  wSQL =       'select reg.BDCODEMP, reg.BDCODMATRIZ, reg.BDREFERENCIA, reg.BDCODQUADRO, reg.BDNUMCAMPO, reg.BDVALOR, ';
  wSQL = wSQL||       'q.BDCLASSIFICACAO, ';
  wSQL = wSQL||       'case ';
  wSQL = wSQL||         'when reg.BDCODQUADRO in (15,33) then '; -- 15 - M200 - Consolidação da contribuição para o PIS/PASEP / 33 - M600 - Consolidação da contribuição para o Cofins
  wSQL = wSQL||            'case reg.BDNUMCAMPO ';
  wSQL = wSQL||               'when  2 then ''Valor total do período'' ';
  wSQL = wSQL||               'when  3 then ''Valor do crédito descontado, apurado no período'' ';
  wSQL = wSQL||               'when  4 then ''Valor do crédito descontado, apurado em período anterior'' ';
  wSQL = wSQL||               'when  5 then ''Valor total da contribuição não cumulativa devida'' ';
  wSQL = wSQL||               'when  6 then ''Valor retido na fonte deduzido'' ';
  wSQL = wSQL||               'when  7 then ''Outras deduções no período'' ';
  wSQL = wSQL||               'when  8 then ''Valor da contribuição não cumulativa a recolher/pagar'' ';
  wSQL = wSQL||               'when  9 then ''Valor Total da Contribuição Cumulativa'' ';
  wSQL = wSQL||               'when 10 then ''Valor retido na fonte deduzido'' ';
  wSQL = wSQL||               'when 11 then ''Outras deduções do período'' ';
  wSQL = wSQL||               'when 12 then ''Valor da contribuição cumulativa a recolher/pagar'' ';
  wSQL = wSQL||               'when 13 then ''Valor total da contribuição a recolher/pagar no período'' ';
  wSQL = wSQL||            'end ';
  wSQL = wSQL||         'when reg.BDCODQUADRO in (34) then '; -- 34 - Contribuição não cumulativa
  wSQL = wSQL||            'case reg.BDNUMCAMPO ';
  wSQL = wSQL||               'when 1 then ''Tributada no mercado interno'' ';
  wSQL = wSQL||               'when 2 then ''Não tributada no mercado interno'' ';
  wSQL = wSQL||               'when 3 then ''Exportação'' ';
  wSQL = wSQL||            'end ';
  wSQL = wSQL||         'when reg.BDCODQUADRO in (35) then '; -- 35 - Contribuição cumulativa
  wSQL = wSQL||               ' ''Receita bruta cumulativa'' ';
  wSQL = wSQL||         'when reg.BDCODQUADRO in (36) then '; -- 36 - Contribuição Total (Valores não cumulativos + cumulativos)
  wSQL = wSQL||               ' ''Receita bruta total'' ';
  wSQL = wSQL||       'end as BDDESCRICAO ';
  wSQL = wSQL||'from VEF_EMP_TBLOCOMGERREG reg ';
  wSQL = wSQL||'left outer join VEF_BASE_TCONFBLOCOMQ q on (q.BDCODQUADRO = reg.BDCODQUADRO) ';

  wWhere = '';

  IF (:prCODEMP IS NOT NULL) THEN
    wWhere = ' where reg.BDCODMATRIZ = '||:PRCODEMP;

  IF (:prREFERENCIA IS NOT NULL) THEN
    BEGIN
      IF (wWhere <> '') THEN
        wWhere = wWhere || ' and ';
      ELSE
        wWhere = ' where ';

       if (:PRREFFINAL > 0) then                                
         wWhere = wWhere||' reg.BDREFERENCIA between ' || :prREFERENCIA || ' AND ' ||:PRREFFINAL;
       else
         wWhere = wWhere||' reg.BDREFERENCIA = '||:prREFERENCIA;
    END

  IF (:prCLASSIFICACAO IS NOT NULL) THEN
    BEGIN
      IF (wWhere <> '') THEN
        wWhere = wWhere || ' and ';
      ELSE
        wWhere = ' where ';

      wWhere = wWhere||' q.BDCLASSIFICACAO LIKE '''||:prCLASSIFICACAO||'%''';
    END

  IF (:prCODQUADRO IS NOT NULL) THEN
    BEGIN
      IF (wWhere <> '') THEN
        wWhere = wWhere || ' and ';
      ELSE
        wWhere = ' where ';

      wWhere = wWhere||' reg.BDCODQUADRO'||' = '||:prCODQUADRO;
    END

   IF (wWhere <> '') THEN
      wWhere = wWhere || ' AND ';
   ELSE
      wWhere = ' WHERE ';

   wWhere = wWhere||' REG.BDRETIFICADORA'||' = '||:PRRETIFICADORA;

   wSQL = wSQL||wWhere||' order by reg.BDCODEMP, reg.BDCODMATRIZ, reg.BDREFERENCIA, reg.BDCODQUADRO, reg.BDNUMCAMPO, q.BDCLASSIFICACAO ';

   IF (prCODQUADRO = 1) THEN -- Resumo
     BEGIN
       wSQL =       'select aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCODQUADRO, aux.BDNUMCAMPO, ';
       wSQL = wSQL||       'SUM(aux.BDVALOR) as BDVALOR, ';
       wSQL = wSQL||       '0 as BDCLASSIFICACAO, ';
       wSQL = wSQL||       'case when (aux.BDNUMCAMPO = 1) then ''Valor total da contribuição não cumulativa'' ';
       wSQL = wSQL||            'when (aux.BDNUMCAMPO = 2) then ''Valor do crédito descontado, retida na fonte e outras deduções'' ';
       wSQL = wSQL||            'when (aux.BDNUMCAMPO = 3) then ''Valor da contribuição não cumulativa a recolher/pagar'' ';
       wSQL = wSQL||            'when (aux.BDNUMCAMPO = 4) then ''Valor total da contribuição cumulativa'' ';
       wSQL = wSQL||            'when (aux.BDNUMCAMPO = 5) then ''Valor da contribuição retida na fonte e outras deduções'' ';
       wSQL = wSQL||            'when (aux.BDNUMCAMPO = 6) then ''Valor da contribuição cumulativa a recolher/pagar'' ';
       wSQL = wSQL||            'when (aux.BDNUMCAMPO = 7) then ''Valor da contribuição a recolher no período'' ';
       wSQL = wSQL||       'end as BDDESCRICAO ';
       wSQL = wSQL||'from ( ';
       wSQL = wSQL||      'select reg.BDCODEMP, reg.BDCODMATRIZ, reg.BDREFERENCIA, reg.BDCODQUADRO, reg.BDVALOR, ';
       wSQL = wSQL||             'case when (reg.BDNUMCAMPO = 2) then 1 ';
       wSQL = wSQL||                  'when (reg.BDNUMCAMPO in (3,4,6,7)) then 2 ';
       wSQL = wSQL||                  'when (reg.BDNUMCAMPO = 8) then 3 ';
       wSQL = wSQL||                  'when (reg.BDNUMCAMPO = 9) then 4 ';
       wSQL = wSQL||                  'when (reg.BDNUMCAMPO in (10,11)) then 5 ';
       wSQL = wSQL||                  'when (reg.BDNUMCAMPO = 12) then 6 ';
       wSQL = wSQL||                  'when (reg.BDNUMCAMPO = 13) then 7 ';
       wSQL = wSQL||             'end as BDNUMCAMPO ';
       wSQL = wSQL||      'from VEF_EMP_TBLOCOMGERREG reg ';
       wSQL = wSQL||      'where reg.BDCODQUADRO in (15,33) ';

       IF (:prCODEMP IS NOT NULL) THEN
         wSQL = wSQL||      ' and reg.BDCODMATRIZ = '||:PRCODEMP;
                                                        
       if (:PRREFFINAL > 0) then                                
         wSQL = wSQL||      ' and reg.BDREFERENCIA between ' || :prREFERENCIA || ' AND ' ||:PRREFFINAL;
       else
       IF (:prREFERENCIA IS NOT NULL) THEN
         wSQL = wSQL||      ' and reg.BDREFERENCIA = '||:prREFERENCIA;

       wSQL = wSQL||        ' AND REG.BDRETIFICADORA = '||:PRRETIFICADORA;
       wSQL = wSQL||      ') aux ';
       wSQL = wSQL||'where aux.BDNUMCAMPO is not null ';
       wSQL = wSQL||'group by aux.BDCODEMP, aux.BDCODMATRIZ, aux.BDREFERENCIA, aux.BDCODQUADRO, aux.BDNUMCAMPO ';
       wSQL = wSQL||'order by aux.BDCODMATRIZ, aux.BDCODEMP, aux.BDREFERENCIA, aux.BDCODQUADRO ';
     END

   FOR
       EXECUTE STATEMENT wSQL
   INTO
     :wCODEMP,
     :wCODMATRIZ,
     :wREFERENCIA,
     :wCODQUADRO,
     :wNUMCAMPO,
     :wVALOR,
     :wCLASSIFICACAO,
     :wDESCRICAO
   DO
     BEGIN
       BDCODEMP        = :wCODEMP;
       BDCODMATRIZ     = :wCODMATRIZ;
       BDREFERENCIA    = :wREFERENCIA;
       BDCODQUADRO     = :wCODQUADRO;
       BDCLASSIFICACAO = :wCLASSIFICACAO;

       IF (prCODQUADRO = 1) THEN -- Resumo
         BEGIN
           IF ((:wCODQUADRO IN (15,33)) AND (:wNUMCAMPO = 1)) THEN
             BEGIN
               BDTIPO     = 0; -- Título
               BDVALOR    = NULL;
               BDNUMCAMPO = NULL;
               IF (:wCODQUADRO = 15) THEN
                 BDDESCRICAO = 'PIS';
               ELSE
               IF (:wCODQUADRO = 33) THEN
                 BDDESCRICAO = 'Cofins';

               SUSPEND;
             END

           /* 15 - M200 - Consolidação da contribuição para o PIS/PASEP
              33 - M600 - Consolidação da contribuição para o Cofins */
           IF ((:wCODQUADRO IN (15,33)) AND (:wNUMCAMPO IN (1,4,7))) THEN
             BEGIN
               BDTIPO     = 0; -- Título
               BDVALOR    = NULL;
               BDNUMCAMPO = NULL;
               IF (:wNUMCAMPO = 1) THEN
                 BDDESCRICAO = 'Contribuição não cumulativa';
               ELSE
               IF (:wNUMCAMPO = 4) THEN
                 BDDESCRICAO = 'Contribuição cumulativa';
               ELSE
               IF (:wNUMCAMPO = 7) THEN
                 BDDESCRICAO = 'Contribuição total(cumulativa + não cumulativa)';
    
               SUSPEND;
             END
         END
       ELSE
       /* 15 - M200 - Consolidação da contribuição para o PIS/PASEP
          33 - M600 - Consolidação da contribuição para o Cofins */
       IF ((:wCODQUADRO IN (15,33)) AND (:wNUMCAMPO IN (2,9,13))) THEN
         BEGIN
           BDTIPO     = 0; -- Título
           BDVALOR    = NULL;
           BDNUMCAMPO = NULL;
           IF (:wNUMCAMPO = 2) THEN
             BDDESCRICAO = 'Contribuição não cumulativa';
           ELSE
           IF (:wNUMCAMPO = 9) THEN
             BDDESCRICAO = 'Contribuição cumulativa';
           ELSE
           IF (:wNUMCAMPO = 13) THEN
             BDDESCRICAO = 'Contribuição total(cumulativa + não cumulativa)';

           SUSPEND;
         END

       /* 34 - Contribuição não cumulativa
          35 - Contribuição cumulativa
          36 - Contribuição Total (Valores não cumulativos + cumulativos) */
       IF ((:wCODQUADRO IN (34,35,36)) AND (:wNUMCAMPO IN (1))) THEN
         BEGIN
           BDTIPO     = 0; -- Título
           BDVALOR    = NULL;
           BDNUMCAMPO = NULL;
           IF (:wCODQUADRO = 34) THEN
             BDDESCRICAO = 'Contribuição não cumulativa';
           ELSE
           IF (:wCODQUADRO = 35) THEN
             BDDESCRICAO = 'Contribuição cumulativa';
           ELSE
           IF (:wCODQUADRO = 36) THEN
             BDDESCRICAO = 'Contribuição Total (Valores não cumulativos + cumulativos)';

           SUSPEND;
         END

       BDTIPO          = 1; -- Analitíca
       BDNUMCAMPO      = :wNUMCAMPO;
       BDVALOR         = :wVALOR;
       BDCLASSIFICACAO = :wCLASSIFICACAO;
       BDDESCRICAO     = :wDESCRICAO;

       SUSPEND;
     END
     
END
^

CREATE OR ALTER TRIGGER vrh_esocial_tocorrencia_l_bi0 FOR vrh_esocial_tocorrencia_lote
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vCodigo = 0;
  IF ((NEW.BDCODOCO IS NULL) OR (NEW.BDCODOCO = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODOCO) + 1), 1) FROM VRH_ESOCIAL_TOCORRENCIA_LOTE INTO vCodigo;
      NEW.BDCODOCO = vCodigo;
    END
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TGRUPOIMENDES_BI0 FOR VEF_BASE_TGRUPOIMENDES
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  NEW.BDCODGRUPO = (SELECT COALESCE(MAX(G.BDCODGRUPO),0)+1 FROM VEF_BASE_TGRUPOIMENDES G);
END
^

CREATE OR ALTER TRIGGER VEF_EMP_TREGRASPRODUTOS_BI0 FOR VEF_EMP_TREGRASPRODUTOS
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  NEW.BDORDEMREGRA = (SELECT COALESCE(MAX(R.BDORDEMREGRA),0)+1 FROM VEF_EMP_TREGRASPRODUTOS R WHERE R.BDCODGRUPO = NEW.BDCODGRUPO);
END
^


CREATE OR ALTER TRIGGER vrh_esocial_tocorrencia_e_bi0 FOR vrh_esocial_tocorrencia_evt
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vCodigo = 0;
  IF ((NEW.BDCODOCO IS NULL) OR (NEW.BDCODOCO = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODOCO) + 1), 1) FROM VRH_ESOCIAL_TOCORRENCIA_evt INTO vCodigo;
      NEW.BDCODOCO = vCodigo;
    END

  if (new.BDCODIGO = 1505) then
     begin
       update VRH_ESOCIAL_TARQUIVO set bdstatus = 5 where bdstatus = 4 and bdcodemp = new.bdcodemp and bdcodigo = new.bdcodevt;
     end
END
^

CREATE OR ALTER TRIGGER vrh_esocial_tlote_bi0 FOR vrh_esocial_tlote_arquivos
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vCodigo = 0;
  IF ((NEW.BDCODLOTE IS NULL) OR (NEW.BDCODLOTE = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODLOTE) + 1), 1) FROM vrh_esocial_tlote_arquivos INTO vCodigo;
      NEW.BDCODLOTE = vCodigo;
    END
END
^

-- Sol 17110 | Marcelo B. M. | Alt:26/09/2017

CREATE OR ALTER TRIGGER VRH_BASE_TCADPREVCOMP_BI0 FOR VRH_BASE_TCADPREVCOMP
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE WCODIGO INTEGER;
BEGIN
  IF ((NEW.BDCODCADPREV IS NULL) OR (NEW.BDCODCADPREV = 0))  THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODCADPREV)+1,1) FROM VRH_BASE_TCADPREVCOMP INTO :WCODIGO;
       NEW.BDCODCADPREV = WCODIGO;
     END
END
^

-- Sol 17110 | Marcelo B. M. | Alt:26/09/2017

CREATE OR ALTER TRIGGER VRH_EMP_TLANCPREVCOMP_BI0 FOR VRH_EMP_TLANCPREVCOMP
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  IF ((NEW.bdcodlancprev IS NULL) OR (NEW.bdcodlancprev = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodlancprev)+1),1) FROM vrh_emp_tlancprevcomp
        WHERE vrh_emp_tlancprevcomp.bdcodemp = NEW.bdcodemp AND
              vrh_emp_tlancprevcomp.bdcodcol = NEW.bdcodcol
        INTO :vcodigo;
        NEW.bdcodlancprev = vcodigo;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_CAD_BI0 FOR VRH_EMP_TCOLCON_CAD
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM VRH_EMP_TCOLCON WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;
       NEW.BDCODCOL = :vNovoCod;
     END

  NEW.bdnomcolupper = UPPER(NEW.bdnomcol);
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_CAD_BU0 FOR VRH_EMP_TCOLCON_CAD
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  NEW.bdnomcolupper = UPPER(NEW.bdnomcol);
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_DOCREF_BI0 FOR VRH_EMP_TCOLCON_DOCREF
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM VRH_EMP_TCOLCON WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;
       NEW.BDCODCOL = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_ADMREF_BI0 FOR VRH_EMP_TCOL_ADMREF
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM VRH_EMP_TCOLCON WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;
       NEW.BDCODCOL = :vNovoCod;
     END

  if (new.bdvincempcol is null) then
     new.bdvincempcol = 0;
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TEMPRESASSST_BI0 FOR VRH_EMP_TEMPRESASSST
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODEMPSST IS NULL) OR (NEW.BDCODEMPSST = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(X.BDCODEMPSST) + 1, 1)
      FROM VRH_EMP_TEMPRESASSST X
      INTO :vNovoCod;
   NEW.BDCODEMPSST = :vNovoCod;
   END
END
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_ADMREF_BU0 FOR VRH_EMP_TCOL_ADMREF
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  if (new.bdvincempcol is null) then
     new.bdvincempcol = 0;
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_FIS_BI0 FOR VRH_EMP_TCOLCON_FIS
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
     BEGIN
       SELECT MAX(BDCODCOL) FROM VRH_EMP_TCOLCON WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCONTRCOL = BDCONTRCOL INTO :vNovoCod;
       NEW.BDCODCOL = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_TCATEGORIA_BI0 FOR VRH_ESOCIAL_TCATEGORIA
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF (COALESCE(NEW.bdcodigo, 0) = 0) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODIGO) + 1, 1) FROM VRH_ESOCIAL_TCATEGORIA INTO :vcod;
       NEW.bdcodigo = :vcod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_RHNET_TARQUIVO_EXP_BI0 FOR VRH_RHNET_TARQUIVO_EXP
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wcodperc INTEGER;
BEGIN
  NEW.bdcodarq = gen_id(GEN_RHNETSOCIAL_EXP, 1);

  select localtimestamp from rdb$database into new.bddatahora;

  new.BDSTATUS = coalesce(new.BDSTATUS, 0);
  new.BDSTATUSENVIO = coalesce(new.BDSTATUSENVIO, 0);

  if (coalesce(new.bdcodemp, 0) <= 0) then
     new.bdcodemp = null;

  wcodperc = null;
  select first 1 BDCODIGO from TPERSONALIZACAO into :wcodperc;
  wcodperc = coalesce(wcodperc, 0);

  if (new.bdchavearqind starting with 'COL.' and wcodperc = 1) then
     begin
       new.bdjsonvalue = replace(new.bdjsonvalue, '"funcionarioId":', '"vFuncionarioContribuinteId":');
       new.bdjsonvalue = replace(new.bdjsonvalue, ':""', ':"NULL"');
     end
END
^

CREATE OR ALTER TRIGGER VRH_DASHBOARD_TARQUIVO_BI0 FOR VRH_DASHBOARD_TARQUIVO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (COALESCE(NEW.BDCODARQ,0) = 0) THEN
     BEGIN
       SELECT MAX(BDCODARQ) + 1 FROM VRH_DASHBOARD_TARQUIVO INTO NEW.BDCODARQ;

       NEW.BDCODARQ = COALESCE(NEW.BDCODARQ, 1);
     END

  NEW.BDDATAHORA = localtimestamp;
END
^

CREATE OR ALTER TRIGGER VRH_DASHBOARD_INFO_ENVIADOS_BI0 FOR VRH_DASHBOARD_INFO_ENVIADOS
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (COALESCE(NEW.BDCODARQ,0) = 0) THEN
     BEGIN
       SELECT MAX(BDCODARQ) + 1 FROM VRH_DASHBOARD_INFO_ENVIADOS INTO NEW.BDCODARQ;

       NEW.BDCODARQ = COALESCE(NEW.BDCODARQ, 1);
     END
END
^

CREATE OR ALTER TRIGGER vef_emp_tmovsaifunrural_bi0 FOR vef_emp_tmovsaifunrural
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END
END
^
CREATE OR ALTER TRIGGER trg_after_del_tpbm_rec FOR vrh_emp_tpbm
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  --Elizeu - 17-08-2018 - Bloco P/Reinf - Integração com a folha #88354
--  IF (OLD.BDCODCONFBLOCOP IS NOT NULL) THEN
--    DELETE FROM VRH_EMP_TPBM_REC R WHERE R.BDCODEMP = OLD.BDCODEMP AND R.BDREF = OLD.BDREF AND R.BDCODCONFBLOCOP = OLD.BDCODCONFBLOCOP;
--  ELSE
  DELETE FROM VRH_EMP_TPBM_REC R WHERE R.BDCODEMP = OLD.BDCODEMP AND R.BDREF = OLD.BDREF;
END^
CREATE OR ALTER TRIGGER VEF_REINF_OCORRENCIA_EVT_BI0 FOR VEF_REINF_OCORRENCIA_EVT
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vCodigo = 0;
  IF ((NEW.BDCODOCO IS NULL) OR (NEW.BDCODOCO = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODOCO) + 1), 1) FROM VEF_REINF_OCORRENCIA_EVT INTO vCodigo;
      NEW.BDCODOCO = vCodigo;
    END
END
^

CREATE OR ALTER PROCEDURE SP_VRHF_EXPORTACAO_CONTABIL (
    PREMP VARCHAR(25000),
    PRREF INTEGER,
    PRAGRUPACOL INTEGER = 0,
    PRFOLHANORMAL INTEGER = 0,
    PRFOLHACOMP INTEGER = 0,
    PRFERIAS INTEGER = 0,
    PRADTOSAL INTEGER = 0,
    PRADTO13 INTEGER = 0,
    PR13SAL INTEGER = 0,
    PRC13SAL INTEGER = 0,
    PRFOLHAAVULSA INTEGER = 0,
    PRPROVFER INTEGER = 0,
    PRPROV13 INTEGER = 0)
RETURNS (
    BDCODEMP INTEGER,
    BDDATALAN DATE,
    BDCTADEB INTEGER,
    BDCODTPCCDEB INTEGER,
    BDCTACCDEB INTEGER,
    BDAPECCDEB VARCHAR(20),
    BDNOMCTACCDEB VARCHAR(40),
    BDCTACRED INTEGER,
    BDCODTPCCCRED INTEGER,
    BDCTACCCRED INTEGER,
    BDAPECCCRED VARCHAR(20),
    BDNOMCTACCCRED VARCHAR(40),
    BDVALORLANC NUMERIC(15,2),
    BDCOMPLHIST VARCHAR(200))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
DECLARE VARIABLE WSQLA VARCHAR(5000);
DECLARE VARIABLE WCODPLACC INTEGER;
DECLARE VARIABLE WCODTPCC INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WVALOR NUMERIC(18,2);
DECLARE VARIABLE WDEBCRE INTEGER;
DECLARE VARIABLE WAPECTACC VARCHAR(20);
DECLARE VARIABLE WNOMCTACC VARCHAR(40);
BEGIN
  wsql = '';

  -- Folha normal
  IF (COALESCE(prfolhanormal, 0) = 1) THEN
     BEGIN
       -- Verbas
       wsql = wsql||'select BDCODEMP, CAST(null as integer) BDORDEM, BDCODCOL, BDCHAVE, BDCODVER '||
                    'from tol_vrhf_emp_tverba_fn '||
                    'where BDREFFN = '||prref||' ';

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||' union all '||
                    'select BDCODEMP, BDORDEM, BDCODCOL, BDCHAVE, BDCODVER '||
                    'from tol_vrhf_emp_tverba_ft '||
                    'where BDREFTOMADOR = '||prref||' ';

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       -- Líquido
       wsql = wsql||' union all '||
                    'select BDCODEMP, CAST(null as integer) BDORDEM, BDCODCOL, BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from tol_vrhf_emp_tcalc_fn '||
                    'where BDREFFN = '||prref||' ';

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||' union all '||
                    'select BDCODEMP, BDORDEM, BDCODCOL, BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from tol_vrhf_emp_tcalc_ft '||
                    'where BDREFTOMADOR = '||prref||' ';

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
     END

  -- Folha complementar
  IF (COALESCE(prfolhacomp, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Verbas
       wsql = wsql||'select BDCODEMP, CAST(null as integer) BDORDEM, BDCODCOL, BDCHAVE, BDCODVER '||
                    'from tol_vrhf_emp_tverba_fn_fc '||
                    'where SUBSTRING(BDREFFC FROM 1 FOR 6) = '||prref||' ';

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||' union all '||
                    'select BDCODEMP, BDORDEM, BDCODCOL, BDCHAVE, BDCODVER '||
                    'from tol_vrhf_emp_tverba_ft_fc '||
                    'where SUBSTRING(BDREFFC FROM 1 FOR 6) = '||prref||' ';

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       -- Líquido
       wsql = wsql||' union all '||
                    'select BDCODEMP, CAST(null as integer) BDORDEM, BDCODCOL, BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from tol_vrhf_emp_tcalc_fn_fc '||
                    'where SUBSTRING(BDREFFC FROM 1 FOR 6) = '||prref||' ';

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||' union all '||
                    'select BDCODEMP, BDORDEM, BDCODCOL, BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from tol_vrhf_emp_tcalc_ft_fc '||
                    'where SUBSTRING(BDREFFC FROM 1 FOR 6) = '||prref||' ';

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
     END

  -- Férias
  IF (COALESCE(prferias, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Verbas
       wsql = wsql||'select L.BDCODEMP, fer.BDORDEM, L.BDCODCOL, L.BDCHAVE, L.BDCODVER '||
                    'from (select *  from vrh_emp_tferias where SUBSTRING(CAST(BDDATAPAGFE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAPAGFE AS VARCHAR(10)) FROM 6 FOR 2) = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||') fer '||
                     'join tol_vrhf_emp_tverba_fer L on (fer.bdcodemp = L.BDCODEMP and fer.BDCODCOL = L.BDCODCOL and fer.BDINIPERAQUISFE = L.BDINIPERAQUISFE and fer.BDCODFE = L.BDCODFE) ';

       -- Líquido
       wsql = wsql||' union all '||
                    'select L.BDCODEMP, fer.BDORDEM, L.BDCODCOL, L.BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from (select *  from vrh_emp_tferias where SUBSTRING(CAST(BDDATAPAGFE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAPAGFE AS VARCHAR(10)) FROM 6 FOR 2) = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||') fer '||
                    'join tol_vrhf_emp_tcalc_fer L on (fer.bdcodemp = L.BDCODEMP and fer.BDCODCOL = L.BDCODCOL and fer.BDINIPERAQUISFE = L.BDINIPERAQUISFE and fer.BDCODFE = L.BDCODFE) ';
     END

  -- Adiantamento salarial
  IF (COALESCE(pradtosal, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Verbas
       wsql = wsql||'select L.BDCODEMP, ad.BDORDEM, L.BDCODCOL, L.BDCHAVE, L.BDCODVER '||
                    'from (select *  from vrhf_emp_tadsal where SUBSTRING(CAST(BDDATAAD AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAAD AS VARCHAR(10)) FROM 6 FOR 2) = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||') ad '||
              'join tol_vrhf_emp_tverba_ad L on (ad.bdcodemp = L.BDCODEMP and ad.BDCODCOL = L.BDCODCOL and ad.BDDATAAD = L.BDDATAAD) ';

       -- Líquido
       wsql = wsql||' union all '||
                    'select L.BDCODEMP, ad.BDORDEM, L.BDCODCOL, L.BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from (select *  from vrhf_emp_tadsal where SUBSTRING(CAST(BDDATAAD AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAAD AS VARCHAR(10)) FROM 6 FOR 2) = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
       wsql = wsql||') ad '||
              'join tol_vrhf_emp_tcalc_ad L on (ad.bdcodemp = L.BDCODEMP and ad.BDCODCOL = L.BDCODCOL and ad.BDDATAAD = L.BDDATAAD) ';
     END

  -- Folha avulsa
  IF (COALESCE(prfolhaavulsa, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Verbas
       wsql = wsql||'select BDCODEMP, CAST(null as integer) BDORDEM, BDCODCOL, BDCHAVE, BDCODVER '||
                    'from tol_vrhf_emp_tverba_fa where SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2) = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       -- Líquido
       wsql = wsql||' union all '||
                    'select BDCODEMP, CAST(null as integer) BDORDEM, BDCODCOL, BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from tol_vrhf_emp_tcalc_fa where SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2) = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
     END

  -- Adiantamento de 13º salário
  IF (COALESCE(pradto13, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Verbas
       wsql = wsql||'select L.BDCODEMP, ad13.BDORDEM, L.BDCODCOL, L.BDCHAVE, L.BDCODVER '||
                    'from (select *  from vrhf_emp_ta13sal where BDREFA13 = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||') ad13 '||
              'join tol_vrhf_emp_tverba_a13 L on (ad13.bdcodemp = L.BDCODEMP and ad13.BDCODCOL = L.BDCODCOL and ad13.BDREFA13 = L.BDREFA13) ';

       -- Líquido
       wsql = wsql||' union all '||
                    'select L.BDCODEMP, ad13.BDORDEM, L.BDCODCOL, L.BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from (select *  from vrhf_emp_ta13sal where BDREFA13 = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
       wsql = wsql||') ad13 '||
              'join tol_vrhf_emp_tcalc_a13 L on (ad13.bdcodemp = L.BDCODEMP and ad13.BDCODCOL = L.BDCODCOL and ad13.BDREFA13 = L.BDREFA13) ';
     END


  -- 13º salário
  IF (COALESCE(pr13sal, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Verbas
       wsql = wsql||'select L.BDCODEMP, s13.BDORDEM, L.BDCODCOL, L.BDCHAVE, L.BDCODVER '||
                    'from (select *  from vrhf_emp_t13sal where BDREF13 = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||') s13 '||
              'join tol_vrhf_emp_tverba_13 L on (s13.bdcodemp = L.BDCODEMP and s13.BDCODCOL = L.BDCODCOL and s13.BDREF13 = L.BDREF13) ';

       -- Líquido
       wsql = wsql||' union all '||
                    'select L.BDCODEMP, s13.BDORDEM, L.BDCODCOL, L.BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from (select *  from vrhf_emp_t13sal where BDREF13 = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
       wsql = wsql||') s13 '||
              'join tol_vrhf_emp_tcalc_13 L on (s13.bdcodemp = L.BDCODEMP and s13.BDCODCOL = L.BDCODCOL and s13.BDREF13 = L.BDREF13) ';
     END


  -- Complemento de 13º salário
  IF (COALESCE(prc13sal, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Verbas
       wsql = wsql||'select L.BDCODEMP, c13.BDORDEM, L.BDCODCOL, L.BDCHAVE, L.BDCODVER '||
                    'from (select *  from vrhf_emp_tc13sal where BDREFC13 = '||prref||' and UPPER(COALESCE(BDPAGOFNC13, ''FALSE'')) = ''FALSE''' ;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;

       wsql = wsql||') c13 '||
              'join tol_vrhf_emp_tverba_c13 L on (c13.bdcodemp = L.BDCODEMP and c13.BDCODCOL = L.BDCODCOL and c13.BDREF13 = L.BDREF13 and c13.BDREFC13 = L.BDREFC13) ';

       -- Líquido
       wsql = wsql||' union all '||
                    'select L.BDCODEMP, c13.BDORDEM, L.BDCODCOL, L.BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from (select *  from vrhf_emp_tc13sal where BDREF13 = '||prref||' and UPPER(COALESCE(BDPAGOFNC13, ''FALSE'')) = ''FALSE''' ;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
       wsql = wsql||') c13 '||
              'join tol_vrhf_emp_tcalc_c13 L on (c13.bdcodemp = L.BDCODEMP and c13.BDCODCOL = L.BDCODCOL and c13.BDREF13 = L.BDREF13 and c13.BDREFC13 = L.BDREFC13) ';
     END

  -- Provisão de férias
  IF (COALESCE(prprovfer, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Provisão
       wsql = wsql||'select BDCODEMP, BDORDEM, BDCODCOL, BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from tol_vrhf_emp_tprovfer_det where BDREFPFER = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
     END

  -- Provisão de 13º salário
  IF (COALESCE(prprov13, 0) = 1) THEN
     BEGIN
       IF (wsql <> '') THEN
          wsql = wsql||' union all ';

       -- Provisão
       wsql = wsql||'select BDCODEMP, BDORDEM, BDCODCOL, BDCHAVE, CAST(null as integer) BDCODVER '||
                    'from tol_vrhf_emp_tprov13_det where BDREFP13 = '||prref;

                    IF (COALESCE(premp, '') <> '') THEN
                       wsql = wsql||' and '||premp;
     END


  IF (wsql <> '') THEN
     BEGIN
       IF (pragrupacol = 1) THEN
          BEGIN
            wsql = 'select FOL.BDCODEMP, CAST(null as integer) BDCHAVE, LAN.BDDATA, TPCC.BDCODCENTRO, TPCC.BDCODTPCC, LAN.BDDEBITO, LAN.BDCREDITO, SUM(COALESCE(LAN.BDVALOR,0)), '||
                          'iif(position(''COL.'', UPPER(lan.bdcompl)) > 0, SUBSTRING(lan.bdcompl FROM 1 FOR position(''COL.'', UPPER(lan.bdcompl)) - 1), lan.bdcompl) BDCOMPL, '||
                          'TPCC.BDAPECTA, TPCC.BDNOMCTA from ('||
                   wsql||') FOL ' ||
                   ' left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                   ' left outer join VSUC_EMPRESAS_TLAN LAN on (LAN.BDCODEMP = FOL.BDCODEMP and LAN.BDCHAVE = FOL.BDCHAVE) '||
                   ' left outer join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FOL.BDCODEMP and PFN.BDCODCOL = FOL.BDCODCOL and PFN.BDORDEM = FOL.BDORDEM) '||
                   ' left outer join CENTROS_TPCC TPCC on (TPCC.BDCODCENTRO = PFN.BDCODCENTRO and TPCC.BDCODTPCC = PFN.BDCODTPCC) '||
                   ' group by FOL.BDCODEMP, LAN.BDDATA, TPCC.BDCODCENTRO, TPCC.BDCODTPCC, LAN.BDDEBITO, LAN.BDCREDITO, BDCOMPL, TPCC.BDAPECTA, TPCC.BDNOMCTA'||
                   ' order by FOL.BDCODEMP, LAN.BDDATA, TPCC.BDCODCENTRO, TPCC.BDCODTPCC ';
          END
       ELSE
          BEGIN
            wsql = 'select FOL.BDCODEMP, FOL.BDCHAVE, LAN.BDDATA, TPCC.BDCODCENTRO, TPCC.BDCODTPCC, LAN.BDDEBITO, LAN.BDCREDITO, LAN.BDVALOR, LAN.BDCOMPL, TPCC.BDAPECTA, TPCC.BDNOMCTA from ('||
                   wsql||') FOL ' ||
                   ' left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                   ' left outer join VSUC_EMPRESAS_TLAN LAN on (LAN.BDCODEMP = FOL.BDCODEMP and LAN.BDCHAVE = FOL.BDCHAVE) '||
                   ' left outer join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FOL.BDCODEMP and PFN.BDCODCOL = FOL.BDCODCOL and PFN.BDORDEM = FOL.BDORDEM) '||
                   ' left outer join CENTROS_TPCC TPCC on (TPCC.BDCODCENTRO = PFN.BDCODCENTRO and TPCC.BDCODTPCC = PFN.BDCODTPCC) '||
                   'order by FOL.BDCODEMP, LAN.BDDATA, TPCC.BDCODCENTRO, TPCC.BDCODTPCC, FOL.BDCHAVE ';

          END

       FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :wchave, :bddatalan, :wcodplacc, :wcodtpcc, :bdctadeb, :bdctacred, :bdvalorlanc, :bdcomplhist, :wapectacc, :wnomctacc DO
         BEGIN
           wdebcre = NULL;
           wvalor = NULL;
           IF (COALESCE(pragrupacol,0) = 1) THEN
              wsqla = 'select SUM(tlcc.BDVALOR), tlcc.BDDEBCRE from VSUC_EMPRESAS_TLCC tlcc '||
                      'join VSUC_EMPRESAS_TLAN lan on (lan.BDCODEMP = tlcc.BDCODEMP and lan.BDCHAVE = tlcc.BDCHAVE) '||
                      'where tlcc.BDCODEMP = '||bdcodemp||' and COALESCE(tlcc.BDCODCENTRO,0) = '||COALESCE(wcodplacc,0)||' and COALESCE(tlcc.BDCODTPCC,0) = '||COALESCE(wcodtpcc,0)||
                         ' and lan.BDDATA = '''||bddatalan||''' and COALESCE(lan.BDDEBITO,0) = '||COALESCE(bdctadeb, 0)||' and COALESCE(lan.BDCREDITO, 0) = '||COALESCE(bdctacred, 0)||
                         ' and iif(position(''COL.'', UPPER(lan.bdcompl)) > 0, SUBSTRING(lan.bdcompl FROM 1 FOR position(''COL.'', UPPER(lan.bdcompl)) - 1), lan.bdcompl) = '''||bdcomplhist||''''||
                         ' group by tlcc.BDDEBCRE ';
           ELSE
              wsqla = 'select BDVALOR, BDDEBCRE from VSUC_EMPRESAS_TLCC where BDCODEMP = '||bdcodemp||' and BDCHAVE = '||wchave||' and COALESCE(BDCODCENTRO,0) = '||COALESCE(wcodplacc,0)||' and COALESCE(BDCODTPCC,0) = '||COALESCE(wcodtpcc,0);

           FOR EXECUTE STATEMENT wsqla INTO :wvalor, :wdebcre DO
             BEGIN
               IF (wdebcre = 1) THEN
                  BEGIN
                    bdapecccred = wapectacc;
                    bdctacccred = bdctacred;
                    bdnomctacccred = wnomctacc;
                    bdcodtpcccred = wcodtpcc;
                    bdapeccdeb = NULL;
                    bdctaccdeb = NULL;
                    bdnomctaccdeb = NULL;
                    bdcodtpccdeb = NULL;
                    bdvalorlanc = wvalor;
                    SUSPEND;
                  END
               ELSE
                  BEGIN
                    bdapecccred = NULL;
                    bdctacccred = NULL;
                    bdnomctacccred = NULL;
                    bdcodtpcccred = NULL;
                    bdapeccdeb = wapectacc;
                    bdctaccdeb = bdctadeb;
                    bdnomctaccdeb = wnomctacc;
                    bdcodtpccdeb = wcodtpcc;
                    bdvalorlanc = wvalor;
                    SUSPEND;
                  END
             END

           IF (wdebcre IS NULL) THEN
              BEGIN
                bdctacccred = NULL;
                bdctaccdeb  = NULL;
                bdnomctacccred = NULL;
                bdnomctaccdeb = NULL;
                bdapecccred = NULL;
                bdapeccdeb = NULL;
                SUSPEND;
              END
         END
     END
END^

--#alt:16965. Ana - 05/12/2017
CREATE OR ALTER PROCEDURE SP_COPIA_DADOS_EMPRESA (
    PRTABELA VARCHAR(64),
    PRCODEMP INTEGER,
    PRCODEMPBACKUP VARCHAR(10),
    PRREFEMP INTEGER)
RETURNS (
    BDINSERIU DM_BOOLEAN)
AS
DECLARE VARIABLE WSQLINSERT VARCHAR(30000);
DECLARE VARIABLE WSQLINSERTCAMPOS VARCHAR(30000);
DECLARE VARIABLE WSQLJOIN VARCHAR(10000);
DECLARE VARIABLE WSQLUNIONJOIN VARCHAR(30000);
DECLARE VARIABLE WSQLREF VARCHAR(100);
DECLARE VARIABLE WSQLDATA VARCHAR(30000);
DECLARE VARIABLE WSQLWHEREJOINS VARCHAR(30000);
DECLARE VARIABLE WSQLWHERE VARCHAR(30000);
DECLARE VARIABLE WPOSSUICAMPOEMP VARCHAR(5);
DECLARE VARIABLE WPOSSUICAMPOREF VARCHAR(5);
DECLARE VARIABLE WPOSSUICAMPODATA VARCHAR(5);
DECLARE VARIABLE WPOSSUICAMPOOBRIGATORIO VARCHAR(5);
DECLARE VARIABLE WEXISTEREG VARCHAR(5);
DECLARE VARIABLE WTABELAAUX VARCHAR(64);
DECLARE VARIABLE WCODEMPAUX VARCHAR(10);
DECLARE VARIABLE WCAMPOTABELA VARCHAR(300);
DECLARE VARIABLE WCAMPOTABELADESTINO VARCHAR(300);
DECLARE VARIABLE WFKANTERIOR VARCHAR(300);
DECLARE VARIABLE WFKATUAL VARCHAR(300);
DECLARE VARIABLE WCAMPODATA VARCHAR(64);
DECLARE VARIABLE WULTIMODIA INTEGER;
DECLARE VARIABLE WINSERIU VARCHAR(5);
DECLARE VARIABLE WAPELIDOORIGEM VARCHAR(10);
DECLARE VARIABLE WAPELIDODESTINO VARCHAR(10);
DECLARE VARIABLE WAPELIDODESTINOAUX VARCHAR(10);
DECLARE VARIABLE WNOTNULL INTEGER;
DECLARE VARIABLE WCOUNT INTEGER;
DECLARE VARIABLE WDATA DATE;
DECLARE VARIABLE WFIELDTYPE INTEGER;
begin
  WPOSSUICAMPOOBRIGATORIO = 'FALSE';
  WPOSSUICAMPOEMP  = 'FALSE';
  WPOSSUICAMPOREF  = 'FALSE';
  WPOSSUICAMPODATA = 'FALSE';
  WSQLDATA         = '';
  WSQLREF          = '';
  WSQLJOIN         = '';
  WSQLUNIONJOIN    = '';
  WSQLWHEREJOINS   = '';
  WSQLWHERE        = '';
  WEXISTEREG       = 'FALSE';
  WINSERIU         = 'FALSE';
  WAPELIDOORIGEM   = 'ORG';
  WAPELIDODESTINO  = 'DEST';
  WAPELIDODESTINOAUX  = WAPELIDODESTINO;
  WCOUNT              = 1;
  WCAMPOTABELA        = '';
  WCAMPOTABELADESTINO = '';
  WFKANTERIOR         = '';
  WFKATUAL            = '';

  BDINSERIU = 'FALSE';

  --Faz a verificação se é alguma das tabelas da online ou suas agregadas, pois ai não deve inserir nada
  --A tabela VLAL_EMPRESAS_APURACAO tem que copiar.
  select TABELA
  from (select distinct(CD.RDB$RELATION_NAME) as TABELA
        from RDB$RELATION_CONSTRAINTS CO
        inner join RDB$INDEX_SEGMENTS ID on (CO.RDB$INDEX_NAME = ID.RDB$INDEX_NAME)
        inner join RDB$REF_CONSTRAINTS RE on (CO.RDB$CONSTRAINT_NAME = RE.RDB$CONSTRAINT_NAME)
        inner join RDB$RELATION_CONSTRAINTS CD on (RE.RDB$CONST_NAME_UQ = CD.RDB$CONSTRAINT_NAME)
        inner join(select distinct trim(CONSTRAINTSORIGEM.RDB$RELATION_NAME) as CAMPO
                   from RDB$RELATION_CONSTRAINTS CONSTRAINTSORIGEM
                   where CONSTRAINTSORIGEM.RDB$RELATION_NAME like('TOL_%')) TE on (TE.CAMPO = CO.RDB$RELATION_NAME)
        where CD.RDB$RELATION_NAME <> 'VSUC_EMPRESAS_TLAN' and CD.RDB$RELATION_NAME <> 'VLAL_EMPRESAS_APURACAO' and CD.RDB$RELATION_NAME <> 'EMPRESAS_TSOC'
        and CD.RDB$RELATION_NAME not in ('VATI_EMPRESAS_IMP_ATIVACONTAB', 'VSUC_EMPRESAS_TPROCEVOLUCOBRA', 'VSUC_EMPRESAS_TTRANSFCUSTOINCOR', 'VSUC_EMPRESAS_VALORPRESENTE', 'EMPRESAS_TBEM_TRANSFERENCIA', 'EMPRESAS_TBEM_TRANSF_CONTA')
  )
  where TABELA = :PRTABELA into :WTABELAAUX;

  if ((trim(WTABELAAUX) <> '') or not (WTABELAAUX is null)) then
    exit;

  if (prtabela = 'EMPRESAS_TBEM_TRANSFERENCIA' or prtabela = 'EMPRESAS_TBEM_TRANSF_CONTA') then --Essas tabelas não tem a empresa como PK, daí ele da erro, mas não é problemático usar a mesma chave para a backup - Machado - 31/03/2025 - #242515
    exit;

  select ULTDIA from ULTIMO_DIA_MES(cast(substring(cast(:PRREFEMP as varchar(8)) from 5 for 2) as integer), cast(substring(cast(:PRREFEMP as varchar(8)) from 1 for 4) as integer))
  into :WULTIMODIA;
  WDATA = substring(cast(PRREFEMP as varchar(8)) from 5 for 2)||'-'||WULTIMODIA||'-'||substring(cast(PRREFEMP as varchar(8)) from 1 for 4);

  if (trim(PRTABELA) <> 'TLIVRO' and
      trim(PRTABELA) <> 'TEMPRESAS' and
      trim(PRTABELA) <> 'PLANOS_TPLA' and
      trim(PRTABELA) <> 'TEMPRESAS_REF' and
      trim(PRTABELA) <> 'TBLOQLAN_EMPRESA' and
      trim(PRTABELA) <> 'TBLOQLAN_USUARIO' and
      trim(PRTABELA) <> 'TEMPRESAS_BACKUP_ONLINE' and
      trim(PRTABELA) <> 'VSUC_PREPARACAO_GRUPOECONOMICO') then
  begin
    --Verifica se os dados das dependencias da tabela ja foram setadas
    for select distinct(CD.RDB$RELATION_NAME)
        from RDB$RELATION_CONSTRAINTS CO
        inner join RDB$INDEX_SEGMENTS ID on (CO.RDB$INDEX_NAME = ID.RDB$INDEX_NAME)
        inner join RDB$REF_CONSTRAINTS RE on (CO.RDB$CONSTRAINT_NAME = RE.RDB$CONSTRAINT_NAME)
        inner join RDB$RELATION_CONSTRAINTS CD on (RE.RDB$CONST_NAME_UQ = CD.RDB$CONSTRAINT_NAME)
        where CO.RDB$RELATION_NAME = :PRTABELA and
              RDB$FIELD_NAME = 'BDCODEMP'
        union select 'VSUC_EMPRESAS_TPROCEVOLUCOBRA' from RDB$DATABASE where trim(upper(:prtabela)) = 'VSUC_EMPRESAS_TLAN'
        union select 'VATI_EMPRESAS_IMP_ATIVACONTAB' from RDB$DATABASE where trim(upper(:prtabela)) = 'VSUC_EMPRESAS_TLAN'
        union select 'VSUC_EMPRESAS_TTRANSFCUSTOINCOR' from RDB$DATABASE where trim(upper(:prtabela)) = 'VSUC_EMPRESAS_TLAN'
        union select 'VSUC_EMPRESAS_VALORPRESENTE' from RDB$DATABASE where trim(upper(:prtabela)) = 'VSUC_EMPRESAS_TLAN'    
        union select 'EMPRESAS_TBEM_TRANSFERENCIA' from RDB$DATABASE where trim(upper(:prtabela)) = 'VSUC_EMPRESAS_TLAN'
        union select 'EMPRESAS_TBEM_TRANSF_CONTA' from RDB$DATABASE where trim(upper(:prtabela)) = 'VSUC_EMPRESAS_TLAN'
        into :WTABELAAUX
    do
    begin
      WTABELAAUX = trim(WTABELAAUX);

      if (WTABELAAUX <> PRTABELA) then
        select BDINSERIU from SP_COPIA_DADOS_EMPRESA(trim(:WTABELAAUX),:PRCODEMP,:PRCODEMPBACKUP,:PRREFEMP) into :WINSERIU;

      WAPELIDODESTINO = WAPELIDODESTINOAUX || WCOUNT;

      WSQLDATA     = '';
      WSQLREF      = '';
      WCAMPOTABELA = '';
      WSQLWHEREJOINS = '';

      --Verifica se a empresa dependente possui os campos de data ou referencia, para adicionar no join
      select first 1 trim(A.RDB$FIELD_NAME) as BDCAMPO
      from RDB$RELATION_FIELDS A
      LEFT JOIN RDB$FIELDS f ON A.RDB$FIELD_SOURCE = f.RDB$FIELD_NAME
      where (A.RDB$RELATION_NAME = :WTABELAAUX) and
            (((trim(A.RDB$FIELD_NAME) like 'BDDATA%') and
               not(trim(A.RDB$FIELD_NAME) like 'BDDATANASC%') and
               not(trim(A.RDB$FIELD_NAME) like 'BDDATAINI%') and
               not(trim(A.RDB$FIELD_NAME) like 'BDDATABASE%')) or
             ((trim(A.RDB$FIELD_NAME) like 'BDDT%') and
               not(trim(A.RDB$FIELD_NAME) like 'BDDTINI%') and
               not(trim(A.RDB$FIELD_NAME) like 'BDDTNASC%')) or
             ((trim(A.RDB$FIELD_NAME) like 'BDDAT%') and
               not(trim(A.RDB$FIELD_NAME) like 'BDDATINI%') and
               not(trim(A.RDB$FIELD_NAME) like 'BDDATNASC%') and
               not(trim(A.RDB$FIELD_NAME) like 'BDDATANASC%'))) and coalesce(f.RDB$FIELD_TYPE, 0) <> 8
      order by RDB$FIELD_POSITION
      into :WCAMPOTABELA;

      if ((WCAMPOTABELA <> '') and not(WCAMPOTABELA is null)) then
        WSQLWHEREJOINS = WSQLWHEREJOINS || ' and '||WAPELIDODESTINO||'.'||WCAMPOTABELA||' <= '''||WDATA||'''' ;

      WCAMPOTABELA = '';
      select first 1 trim(A.RDB$FIELD_NAME) as BDCAMPO
      from RDB$RELATION_FIELDS A
      where (A.RDB$RELATION_NAME = :WTABELAAUX) and
            (trim(A.RDB$FIELD_NAME) like 'BDREFEMP')
      order by RDB$FIELD_POSITION
      into :WCAMPOTABELA;

      if ((WCAMPOTABELA <> '') and not(WCAMPOTABELA is null)) then
        WSQLWHEREJOINS = WSQLWHEREJOINS || ' and '||WAPELIDODESTINO||'.'||WCAMPOTABELA||' <= ' || PRREFEMP;

      --Monta os Joins
      WSQLJOIN = ' join ' || WTABELAAUX || ' ' || WAPELIDODESTINO || ' on(' || WAPELIDODESTINO || '.BDCODEMP = ' || PRCODEMPBACKUP;
      for select IO.RDB$INDEX_NAME, IO.RDB$FIELD_NAME AS CAMPOORIGEM, FO.RDB$NULL_FLAG , ID.RDB$FIELD_NAME as CAMPODESTINO
          from RDB$RELATION_CONSTRAINTS CO
          inner join RDB$INDEX_SEGMENTS IO on (CO.RDB$INDEX_NAME = IO.RDB$INDEX_NAME)
          inner join RDB$REF_CONSTRAINTS RE on (CO.RDB$CONSTRAINT_NAME = RE.RDB$CONSTRAINT_NAME)
          inner join RDB$RELATION_FIELDS FO on (CO.RDB$RELATION_NAME = FO.RDB$RELATION_NAME and IO.RDB$FIELD_NAME = FO.RDB$FIELD_NAME)
          inner join RDB$RELATION_CONSTRAINTS CD on (RE.RDB$CONST_NAME_UQ = CD.RDB$CONSTRAINT_NAME)
          inner join RDB$INDEX_SEGMENTS ID on (CD.RDB$INDEX_NAME = ID.RDB$INDEX_NAME)
          where CO.RDB$RELATION_NAME = :PRTABELA and
                CD.RDB$RELATION_NAME = :WTABELAAUX and
                IO.RDB$FIELD_POSITION = ID.RDB$FIELD_POSITION
      into :WFKATUAL, :WCAMPOTABELA, :WNOTNULL, :WCAMPOTABELADESTINO
      do
      begin
        WCAMPOTABELA = trim(WCAMPOTABELA);
        WCAMPOTABELADESTINO = trim(WCAMPOTABELADESTINO);

        --Verifica se as FKs são diferentes, pois se forem significa que existe mais de uma fk pra mesma tabela e precisamos de dois joins diferentes
        if ((WFKATUAL <> WFKANTERIOR) and (WFKANTERIOR <> ''))then
        begin
          WCOUNT = WCOUNT + 1;

          WSQLJOIN = WSQLJOIN || ') ';

          WAPELIDODESTINO = WAPELIDODESTINOAUX || WCOUNT;

          if (WPOSSUICAMPOOBRIGATORIO = 'TRUE') then
            WSQLUNIONJOIN = WSQLUNIONJOIN || ' left ' || WSQLJOIN;
          else
            WSQLUNIONJOIN = WSQLUNIONJOIN || ' inner ' || WSQLJOIN;

          WSQLJOIN = ' join ' || WTABELAAUX || ' ' || WAPELIDODESTINO || ' on(' || WAPELIDODESTINO || '.BDCODEMP = ' || PRCODEMPBACKUP;
        end

        if ((WCAMPOTABELA <> 'BDCODEMP') and (WCAMPOTABELA <> 'BDFILIAL')) then
        begin
          --Verifica se possui algum campo dependente que não pode ficar vazio na tabela
          if (not (WNOTNULL is null))  then
            WPOSSUICAMPOOBRIGATORIO = 'TRUE';

          WSQLJOIN = WSQLJOIN || ' and ' || WAPELIDODESTINO || '.' || WCAMPOTABELADESTINO|| ' = ' || WAPELIDOORIGEM || '.' || WCAMPOTABELA;

          --Adiciona o campo de FK que não é obrigatório no where pois não estava funcionando corretamente com o inner/left join
          if (WPOSSUICAMPOOBRIGATORIO = 'FALSE') then
             begin ---Leonardo Pereira - 24/03/2021 - Melhorar performace nos inserts
               WSQLWHERE= WSQLWHERE||' and (('||WAPELIDOORIGEM||'.'||WCAMPOTABELA||' is null) or exists (select '||WAPELIDODESTINO||'.'||WCAMPOTABELADESTINO||' from '||WTABELAAUX||' '||WAPELIDODESTINO||
               ' where '||WAPELIDODESTINO||'.'||'BDCODEMP = '||PRCODEMPBACKUP||WSQLWHEREJOINS||' and '||WAPELIDOORIGEM||'.'||WCAMPOTABELA||' = '||WAPELIDODESTINO||'.'||WCAMPOTABELADESTINO||'))';

--            WSQLWHERE= WSQLWHERE||' and (('||WAPELIDOORIGEM||'.'||WCAMPOTABELA||' in (select '||WAPELIDODESTINO||'.'||WCAMPOTABELADESTINO||' from '||WTABELAAUX||' '||WAPELIDODESTINO||
--                                          ' where '||WAPELIDODESTINO||'.'||'BDCODEMP = '||PRCODEMPBACKUP||WSQLWHEREJOINS||')) or ('||WAPELIDOORIGEM||'.'||WCAMPOTABELA||' is null))';
             end
        end

        WFKANTERIOR = WFKATUAL;
      end
      WSQLJOIN = WSQLJOIN||WSQLDATA||WSQLREF||') ';

      if (WPOSSUICAMPOOBRIGATORIO = 'FALSE') then
      begin
        if (WINSERIU = 'FALSE') then
          WINSERIU = 'TRUE';

        WSQLJOIN = '';
      end
      else
        WSQLUNIONJOIN = WSQLUNIONJOIN || ' inner ' || WSQLJOIN;

      WCOUNT = WCOUNT + 1;
      WFKANTERIOR = '';

      if (WINSERIU = 'FALSE') then
        exit;
    end

    WSQLDATA = '';
    WSQLREF  = '';

    --Monta o insert
    WSQLINSERT = 'insert into ' || PRTABELA || ' (BDCODEMP';
    WSQLINSERTCAMPOS = 'select ' || PRCODEMPBACKUP;
    for select trim(A.RDB$FIELD_NAME), f.RDB$FIELD_TYPE
        from RDB$RELATION_FIELDS A
        inner join RDB$FIELDS f on (f.RDB$FIELD_NAME = A.RDB$FIELD_SOURCE)
        where (A.RDB$RELATION_NAME = :PRTABELA) and F.RDB$COMPUTED_BLR is NULL
        order by RDB$FIELD_POSITION
    into :WCAMPOTABELA, :wfieldtype
    do
    begin
      if (WCAMPOTABELA = 'BDREFEMP') then
        WPOSSUICAMPOREF = 'TRUE';

      --Tratamento para filtro pela data
      if (WPOSSUICAMPODATA = 'FALSE' and PRTABELA <> 'VLAL_EMPRESA_APA')  then
      begin
        if((coalesce(wfieldtype, 0) <> 8) and
           (((position('BDDATA', :WCAMPOTABELA) > 0) and
             (position('BDDATAINI', :WCAMPOTABELA) = 0) and
             (position('BDDATABASE', :WCAMPOTABELA) = 0) and
             (position('BDDATANASC', :WCAMPOTABELA) = 0)) or
            ((position('BDDT', :WCAMPOTABELA) > 0) and
             (position('BDDTINI', :WCAMPOTABELA) = 0) and
             (position('BDDTNASC', :WCAMPOTABELA) = 0)) or
            ((position('BDDAT', :WCAMPOTABELA) > 0) and
             (position('BDDATINI', :WCAMPOTABELA) = 0) and
             (position('BDDATABASE', :WCAMPOTABELA) = 0) and
             (position('BDDATNASC', :WCAMPOTABELA) = 0) and
             (position('BDDATANASC', :WCAMPOTABELA) = 0)))) then
        begin
          WPOSSUICAMPODATA = 'TRUE';
          WCAMPODATA = WCAMPOTABELA;
        end
      end

      if (WCAMPOTABELA <> 'BDCODEMP') then
      begin
        WSQLINSERT = WSQLINSERT || ',' || WCAMPOTABELA;
        WSQLINSERTCAMPOS = WSQLINSERTCAMPOS || ',' || WAPELIDOORIGEM ||'.'|| WCAMPOTABELA;
      end
      else
        WPOSSUICAMPOEMP = 'TRUE';
    end
    WSQLINSERT = WSQLINSERT || ') ';

    --Cria filtro pela data
    if (WPOSSUICAMPODATA = 'TRUE') then
      WSQLDATA = ' and ' || WAPELIDOORIGEM ||'.'|| WCAMPODATA || ' <= ''' ||WDATA||'''' ;

    --Cria filtro pela referência
    if (WPOSSUICAMPOREF = 'TRUE') then
      WSQLREF = ' and '|| WAPELIDOORIGEM ||'.BDREFEMP <= ' || PRREFEMP;

    WSQLINSERTCAMPOS = WSQLINSERTCAMPOS || ' from ' || PRTABELA || ' ' || WAPELIDOORIGEM ||' '|| WSQLUNIONJOIN || ' where '||WAPELIDOORIGEM || '.BDCODEMP = ' || PRCODEMP ||
                       WSQLREF || WSQLDATA || WSQLWHERE;

    if (WPOSSUICAMPOEMP = 'TRUE') then
    begin
      --Verifica se ja possui algo cadastrado para a empresa nova na tabela, pois há alguns registros que são setados pelas triggers das tabelas TEMPRESAS e TEMPRESAS_REF
      execute statement 'select first 1 BDCODEMP from ' || PRTABELA || ' where BDCODEMP = ' || PRCODEMPBACKUP into :WCODEMPAUX;
      if ((WCODEMPAUX = '') or (WCODEMPAUX is null) or (WCODEMPAUX = '0')) then
        WEXISTEREG = 'FALSE';
      else
        WEXISTEREG = 'TRUE';

      --Insere os registros
      if (WEXISTEREG = 'FALSE') then
        execute statement WSQLINSERT || WSQLINSERTCAMPOS;

      --Precisa verificar se foi inserido algum registro, pois no caso da recursividade, preciso que as tabelas dependentes tenham esse registro
      execute statement 'select first 1 BDCODEMP from ' || PRTABELA || ' where BDCODEMP = ' || PRCODEMPBACKUP into :WCODEMPAUX;
      if ((WCODEMPAUX = '') or (WCODEMPAUX is null) or (WCODEMPAUX = '0')) then
        BDINSERIU = 'FALSE';
      else
        BDINSERIU = 'TRUE';
    end
  end
  else
    BDINSERIU = 'TRUE';

  suspend;
end^

CREATE OR ALTER procedure SP_COPIA_PLANOCONF1900 (
    PRCODIGOCOPIADO integer,
    PRCODIGONOVO integer)
as
begin
  DELETE FROM VEF_BASE_TPLANOACOESCONF1900 WHERE BDCODPLANCONF1900 = :prcodigonovo;
  DELETE FROM VEF_BASE_TVINCCODPLANO1900 WHERE BDCODPLANCONF1900 = :prcodigonovo;
  SETORDEMSEQUENCIAL_STR(0);

  INSERT INTO VEF_BASE_TPLANOACOESCONF1900 (BDCODPLANCONF1900,BDCHAVE,BDTIPOMOV,BDMODELO,BDCODCSTICMS,BDCODNAT,BDCONSUFINAL,BDCODAJU,BDDESCCOMP, BDQTDFILTRO, BDCODUF, BDVLRAJU, BDCODAJUICMSST)
  SELECT :prcodigonovo, C.BDCHAVE, C.BDTIPOMOV, C.BDMODELO, C.BDCODCSTICMS, C.BDCODNAT, C.BDCONSUFINAL, C.BDCODAJU, C.BDDESCCOMP, C.BDQTDFILTRO, C.BDCODUF, C.BDVLRAJU, C.BDCODAJUICMSST
  FROM VEF_BASE_TPLANOACOESCONF1900 C WHERE C.BDCODPLANCONF1900 = :prcodigocopiado;

  INSERT INTO VEF_BASE_TVINCCODPLANO1900 (BDORDEM,BDCHAVE,BDCODPLANCONF1900,BDCODCSTICMS,BDCODNAT)
  SELECT GETORDEMSEQUENCIAL_STR('1900.'||:prcodigonovo, 0),/*(COALESCE((SELECT MAX(BDORDEM)+ 1 FROM VEF_BASE_TVINCCODPLANO1900 WHERE BDCODPLANCONF1900 = :prcodigonovo),1))*/
  C.BDCHAVE , :prcodigonovo,C.BDCODCSTICMS, C.BDCODNAT
  FROM VEF_BASE_TVINCCODPLANO1900 C WHERE C.BDCODPLANCONF1900 = :prcodigocopiado;

end^

create or alter procedure SP_COPIA_PLANOCONF1250 (
    PRCODIGOCOPIADO integer,
    PRCODIGONOVO integer)
as
begin
  DELETE FROM VEF_BASE_TPLANOACOESCONF1250 WHERE BDCODPLANCONF1200 = :prcodigonovo;
  DELETE FROM VEF_BASE_TVINCCODPLANO1250 WHERE BDCODPLANCONF1200 = :prcodigonovo;
  SETORDEMSEQUENCIAL_STR(0);

  insert into VEF_BASE_TPLANOACOESCONF1250 (BDCODPLANCONF1200, BDCHAVE, BDMODELO, BDCONSUFINAL, BDTABELA57)
  select :PRCODIGONOVO, C.BDCHAVE, C.BDMODELO, C.BDCONSUFINAL, C.BDTABELA57
  from VEF_BASE_TPLANOACOESCONF1250 C
  where C.BDCODPLANCONF1200 = :PRCODIGOCOPIADO;

  insert into VEF_BASE_TVINCCODPLANO1250 (BDORDEM, BDCHAVE, BDCODPLANCONF1200, BDCODCSTICMS, BDCODNAT)
  select GETORDEMSEQUENCIAL_STR('1200.'||:prcodigonovo, 0), C.BDCHAVE, :PRCODIGONOVO, C.BDCODCSTICMS, C.BDCODNAT
  from VEF_BASE_TVINCCODPLANO1250 C
  where C.BDCODPLANCONF1200 = :PRCODIGOCOPIADO;
end^

CREATE OR ALTER PROCEDURE GET_TRATA_VALOR_NEGATIVO (
    PRVALOR DM_NUMERIC_15_2 NOT NULL,
    PRRETORNAZERO DM_BOOLEAN = 'TRUE')
RETURNS (
    BDVALOR VARCHAR(20))
AS
BEGIN
  BDVALOR = REPLACE(:PRVALOR, '.', ',');
  /*Usado para o Sped Fiscal*/
  IF (:PRVALOR < 0) THEN
    BEGIN
      IF(:PRRETORNAZERO = 'TRUE') THEN
        BDVALOR = '0,00';
      ELSE
        BDVALOR = REPLACE(CAST((:PRVALOR * -1) AS VARCHAR(20)), '.', ',');
    END

  SUSPEND;
END^

CREATE OR ALTER procedure SP_CRIA_BACKUP_EMPRESA (
    PRCODEMP integer,
    PRREFEMP integer,
    PRCODPLANOONLINEDE integer,
    PRCODPLANOONLINEPARA integer,
    PRCODUSU integer,
    PRCODUSUINTRANET integer,
    PRNOMUSUINTRANET varchar(80),
    PRCODCONTABLALUR integer)
as
declare variable WSQL varchar(30000);
declare variable WSQLINSERT varchar(30000);
declare variable WSQLINSERTCAMPOS varchar(30000);
declare variable WTABELA varchar(50);
declare variable WCAMPOTABELA varchar(300);
declare variable WCODEMP integer;
declare variable WCODMATRIZ integer;
declare variable WQTDBACKUPEMP integer;
declare variable WCODEMPBACKUP char(10);
declare variable WCODEMPBACKUPMATRIZ char(10);
declare variable WCODEMPAUX char(6);
declare variable WINSERIU varchar(50);
declare variable WCHAVE integer;
declare variable WTIPOLAN integer;
declare variable WULTIMODIA integer;
declare variable WDATA date;
declare variable WTEMPOINI time;
begin
  /*
    Foram utilizadas várias System Tables para efetuar o backup da empresa. Para facilitar a manutenção destes SQLs é interessante utilizar documentação do firebird:
    https://firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-appx04-systables.html
  */

  WSQL            = '';
  WCODEMPBACKUP   = '';

  --Laço das empresas
  WSQL = WSQL || 'select BDCODMATRIZ, BDCODEMP, BDQTDBACKUPEMP ';
  WSQL = WSQL || 'from TEMPRESAS ';
  WSQL = WSQL || 'where BDCODEMP = ' || PRCODEMP ||' or (BDCODMATRIZ = ' || PRCODEMP || ') order by BDCODMATRIZ, BDCODEMP';

  for execute statement WSQL
          into :WCODMATRIZ, :WCODEMP, :WQTDBACKUPEMP
  do
  begin
    --#alt:99618. Empresas novas vem com este campo null. Ana - 09/04/2019
    if (WQTDBACKUPEMP is null) then
      WQTDBACKUPEMP = 0;

    --Incrementa a quantidade de backup da empresa
    WQTDBACKUPEMP = WQTDBACKUPEMP + 1;
    WTEMPOINI = current_time;

    --Cria a chave da empresa backup
    WCODEMPAUX = LPAD(cast(:WCODEMP as varchar(6)), 6, '0');

    if (WQTDBACKUPEMP <= 9) then
      WCODEMPBACKUP = '10' || WQTDBACKUPEMP || WCODEMPAUX;
    else
      WCODEMPBACKUP = '1' || WQTDBACKUPEMP || WCODEMPAUX;

    --Cadastra a empresa backup com o status 1(backup) e quantidade de backup
    WTABELA = 'TEMPRESAS';

    if ((WCODMATRIZ is null) or (WCODMATRIZ = 0)) then
    begin
      WCODEMPBACKUPMATRIZ = WCODEMPBACKUP;
      WSQLINSERT = 'insert into ' || WTABELA || ' (BDCODEMP,BDSTATUSEMP,BDQTDBACKUPEMP';
      WSQLINSERTCAMPOS = 'select ' || WCODEMPBACKUP || ',1,0';
    end
    else
    begin
      WSQLINSERT = 'insert into ' || WTABELA || ' (BDCODEMP,BDSTATUSEMP,BDQTDBACKUPEMP,BDCODMATRIZ';
      WSQLINSERTCAMPOS = 'select ' || WCODEMPBACKUP || ',1,0,' || WCODEMPBACKUPMATRIZ ;
    end

    for execute statement 'SELECT TRIM(A.RDB$FIELD_NAME) FROM RDB$RELATION_FIELDS A, RDB$FIELDS B, RDB$TYPES C WHERE (A.RDB$RELATION_NAME = ''' || WTABELA || ''') AND ' || ' (B.RDB$FIELD_NAME = A.RDB$FIELD_SOURCE) AND (C.RDB$TYPE = B.RDB$FIELD_TYPE) AND (C.RDB$FIELD_NAME = ''' || 'RDB$FIELD_TYPE' || ''') ORDER BY RDB$FIELD_POSITION'
            into :WCAMPOTABELA
    do
    begin
      if (((WCAMPOTABELA = 'BDCODMATRIZ') and ((WCODMATRIZ is null) or (WCODMATRIZ = 0))) or
          (WCAMPOTABELA <> 'BDCODMATRIZ') and (WCAMPOTABELA <> 'BDCODEMP') and
          (WCAMPOTABELA <> 'BDSTATUSEMP') and (WCAMPOTABELA <> 'BDQTDBACKUPEMP')) then
      begin
        WSQLINSERT = WSQLINSERT || ',' || WCAMPOTABELA;
        WSQLINSERTCAMPOS = WSQLINSERTCAMPOS || ',' || WCAMPOTABELA;
      end
    end
    WSQLINSERT = WSQLINSERT || ') ';
    WSQLINSERTCAMPOS = WSQLINSERTCAMPOS || ' from ' || WTABELA || ' where BDCODEMP = ' || WCODEMP;
    execute statement WSQLINSERT || WSQLINSERTCAMPOS;

    --Copia as referencias da empresa
    WTABELA = 'TEMPRESAS_REF';

    WSQLINSERT = 'insert into ' || WTABELA || ' (BDCODEMP,BDAPEEMP';
    WSQLINSERTCAMPOS = 'select ' || WCODEMPBACKUP ||',''Backup - '||WCODEMPBACKUP||'''';
    for execute statement 'SELECT TRIM(A.RDB$FIELD_NAME) FROM RDB$RELATION_FIELDS A, RDB$FIELDS B, RDB$TYPES C WHERE (A.RDB$RELATION_NAME = ''' || WTABELA || ''') AND ' || ' (B.RDB$FIELD_NAME = A.RDB$FIELD_SOURCE) AND (C.RDB$TYPE = B.RDB$FIELD_TYPE) AND (C.RDB$FIELD_NAME = ''' || 'RDB$FIELD_TYPE' || ''') ORDER BY RDB$FIELD_POSITION'
        into :WCAMPOTABELA
    do
    begin
      if ((WCAMPOTABELA <> 'BDCODEMP') and (WCAMPOTABELA <> 'BDAPEEMP')) then
      begin
        WSQLINSERT = WSQLINSERT || ',' || WCAMPOTABELA;
        WSQLINSERTCAMPOS = WSQLINSERTCAMPOS || ',' || WCAMPOTABELA;
      end
    end
    WSQLINSERT = WSQLINSERT || ') ';
    WSQLINSERTCAMPOS = WSQLINSERTCAMPOS || ' from ' || WTABELA || ' where BDCODEMP = ' || WCODEMP || ' and BDREFEMP <= ' || PRREFEMP;
    execute statement WSQLINSERT || WSQLINSERTCAMPOS;

    --Gera a data com o ultimo dia da referência selecionada
    select ULTDIA from ULTIMO_DIA_MES(cast(substring(cast(:PRREFEMP as varchar(8)) from 5 for 2) as integer), cast(substring(cast(:PRREFEMP as varchar(8)) from 1 for 4) as integer))
    into :WULTIMODIA;
    WDATA = substring(cast(PRREFEMP as varchar(8)) from 5 for 2)||'-'||WULTIMODIA||'-'||substring(cast(PRREFEMP as varchar(8)) from 1 for 4);

    --#alt:24127. Tive que adicionar tratamento para pegar só as tabelas que o BDCODEMP seja PK. Ana - 03/05/2018
    --Laço com as tabelas que são dependentes da tabela TEMPRESAS para inserção dos valores
    for select BDCAMPO
        from (select distinct trim(CONSTRAINTSORIGEM.RDB$RELATION_NAME) as BDCAMPO
              from RDB$RELATION_CONSTRAINTS CONSTRAINTSORIGEM
              inner join RDB$INDEX_SEGMENTS INDICES on (CONSTRAINTSORIGEM.RDB$INDEX_NAME = INDICES.RDB$INDEX_NAME)
              inner join RDB$REF_CONSTRAINTS RELACIONAMENTOS on (CONSTRAINTSORIGEM.RDB$CONSTRAINT_NAME = RELACIONAMENTOS.RDB$CONSTRAINT_NAME)
              inner join RDB$RELATION_CONSTRAINTS CONSTRAINTSDESTINO on (RELACIONAMENTOS.RDB$CONST_NAME_UQ = CONSTRAINTSDESTINO.RDB$CONSTRAINT_NAME)
              where (RELACIONAMENTOS.RDB$CONST_NAME_UQ = 'PK_TEMPRESAS' or RELACIONAMENTOS.RDB$CONST_NAME_UQ = 'PK_TEMPRESAS_REF' or INDICES.RDB$FIELD_NAME = 'BDCODEMP')) ALLTABLES
        inner join(select CONSTRAINTS.RDB$RELATION_NAME
                   from RDB$RELATION_CONSTRAINTS CONSTRAINTS
                   inner join RDB$INDEX_SEGMENTS IND on (CONSTRAINTS.RDB$INDEX_NAME = IND.RDB$INDEX_NAME)
                   where IND.RDB$FIELD_NAME = 'BDCODEMP' and
                         CONSTRAINTS.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY') PKTABLES on (PKTABLES.RDB$RELATION_NAME = ALLTABLES.BDCAMPO)
        into :WTABELA
    do
    begin
      select BDINSERIU from SP_COPIA_DADOS_EMPRESA(trim(:WTABELA), :WCODEMP, :WCODEMPBACKUP, :PRREFEMP) into :WINSERIU;

      --Altero os campos bdfilial das tabelas na empresa backup
      if ((:WINSERIU = 'TRUE') and (trim(:WTABELA) = 'VSUC_EMPRESAS_TLAN')) then
        begin
          if ((WCODMATRIZ is not null) and (WCODMATRIZ > 0)) then
            begin
              execute statement 'update VSUC_EMPRESAS_TLAN set BDFILIAL = '||:WCODEMPBACKUP||' where BDCODEMP = '||:WCODEMPBACKUPMATRIZ||' and BDFILIAL = '||:WCODEMP||' and BDDATA <= '''||:WDATA||'''';
              --#alt:91920. Ana - 26/10/2018
              execute statement 'update VSUC_EMPRESAS_TLAN set BDFILIAL = '||:WCODEMPBACKUPMATRIZ||' where BDCODEMP = '||:WCODEMPBACKUP||' and BDFILIAL = '||:WCODMATRIZ||' and BDDATA <= '''||:WDATA||'''';
            end
        end
    end

    UPDATE TEMPRESAS set bdcodcli = null where bdcodemp = :WCODEMPBACKUP;

    --#alt:91920. Ana - 26/10/2018
    --Altera a nova tabela de vínculo do Lançar A
    execute statement ' update VSUC_EMPRESAS_TLANCARA set BDCODEMPORIGEM = '||:WCODEMPBACKUP||' where BDCODEMPORIGEM = '||:WCODEMP||
                      ' and BDCHAVELANORIGEM in (select BDCHAVE from VSUC_EMPRESAS_TLAN where BDCODEMP = '||:WCODEMP||' and BDDATA <= '''||:WDATA||''')';

    execute statement ' update VSUC_EMPRESAS_TLANCARA set BDCODEMPDESTINO = '||:WCODEMPBACKUP||' where BDCODEMPDESTINO = '||:WCODEMP||
                      ' and BDCHAVELANDESTINO in (select BDCHAVE from VSUC_EMPRESAS_TLAN where BDCODEMP = '||:WCODEMP||' and BDDATA <= '''||:WDATA||''')';
    --#alt:91920. fim

    --#135093. Leonardo Pereira - 24/03/2020 - Atualizar as filiais, para não perder os vinculos
    if (coalesce(WCODMATRIZ,0) > 0) then
       execute statement ' update VLAL_VINCULO_CONTABIL_LALUR set BDCODEMPFILIAL = '||:WCODEMPBACKUP||' where BDCODEMP = '||:WCODEMPBACKUPMATRIZ||' and BDCODEMPFILIAL = '||:WCODEMP;
    else
       execute statement ' update VLAL_VINCULO_CONTABIL_LALUR set BDCODEMPFILIAL = '||:WCODEMPBACKUP||' where BDCODEMP = '||:WCODEMPBACKUP||' and BDCODEMPFILIAL = '||:WCODEMP;
    --#135093. Fim
    --Altera tipo dos lançamentos da on-line
--    for select BDCHAVE, BDTIPOLAN
--        from VSUC_EMPRESAS_TLAN
--        where BDCODEMP = :WCODEMPBACKUP and
--              BDTIPOLAN in (100, 200, 3000)
--        into :WCHAVE, :WTIPOLAN
--    do
--    begin
--      --"Lançamento on-line ÚNICO fiscal" para "Copia lançamento on-line ÚNICO fiscal"
--      if (WTIPOLAN = 100) then
--      begin
        update VSUC_EMPRESAS_TLAN set BDTIPOLAN = 31
        where BDCODEMP = :WCODEMPBACKUP and
              --BDCHAVE = :WCHAVE and
              BDTIPOLAN = 100;
--      end
      --"Lançamento on-line ÚNICO folha" para "Copia lançamento on-line ÚNICO folha"
--      else if (WTIPOLAN = 200) then
--        begin
          update VSUC_EMPRESAS_TLAN set BDTIPOLAN = 33
          where BDCODEMP = :WCODEMPBACKUP and
                --BDCHAVE = :WCHAVE and
                BDTIPOLAN = 200;
--        end
     --"Lançamento on-line ÚNICO financeiro" para "Copia lançamento on-line ÚNICO financeiro"
--        else if (WTIPOLAN = 3000) then
--          begin
            update VSUC_EMPRESAS_TLAN set BDTIPOLAN = 35
            where BDCODEMP = :WCODEMPBACKUP and
                  --BDCHAVE = :WCHAVE and
                  BDTIPOLAN = 3000;
--          end
--    end

    --Leva os zeramentos da empresa original para a backup, pois na original não faz sentido ter mais
    execute statement 'update VSUC_EMPRESAS_TENCEXE set BDCODEMP = '||:WCODEMPBACKUP||' where BDCODEMP = '||:WCODEMP||' and BDDATAFIMZER <= '''||:WDATA||'''';

    --Incrementa a quantidade de backups na empresa original
    execute statement 'update TEMPRESAS set BDQTDBACKUPEMP = (BDQTDBACKUPEMP + 1) where BDCODEMP = ' || :WCODEMP;

    --Se a empresa usar o lalur, o código do lalur deve ser alterado na empresa original a partir do período da recontabilização em diante
    if ((PRCODCONTABLALUR <> 0) and not(PRCODCONTABLALUR is null)) then
      execute statement 'update TEMPRESAS_REF set BDCODCONTABLALUR = '||:PRCODCONTABLALUR||' where BDCODEMP = '||:WCODEMP||' and BDREFEMP > '||:PRREFEMP;

    --Adiciona na tabela os processos de backup efetuados
    execute statement 'update or insert into TEMPRESAS_BACKUP_ONLINE (BDCODEMP, BDCODPLANOONLINEDE, BDCODEMPBKP, BDCODPLANOONLINEPARA, '||
                                             'BDCODUSU, BDREFPROCESSO, BDDATA, BDHORA, BDCODUSUINTRANET, BDNOMUSUINTRANET) '||
                      'values('||:WCODEMP||','||:PRCODPLANOONLINEDE||','||:WCODEMPBACKUP||','||:PRCODPLANOONLINEPARA||','||:PRCODUSU||','
                               ||:PRREFEMP||','''||current_date||''','''||current_time||''','||:PRCODUSUINTRANET||','''||PRNOMUSUINTRANET||''')'||
                      'matching (BDCODEMP)';
    --Excluir a apuração da empresa original, porque agora foi copiado para o backup
    delete from VLAL_EMPRESAS_APURACAO where BDCODEMP = :WCODEMP and BDDATFINAPU <= :WDATA;

    delete from tol_vsuc_tdist_lucro dist where dist.bdcodemp = :wcodemp and (select bddata from vsuc_empresas_tlan where bdcodemp = dist.bdcodemp and bdchave = dist.bdchave) <= :wdata;
    delete from tol_vsuc_emp_tvarcambial var where var.bdcodemp = :wcodemp and (select bddata from vsuc_empresas_tlan where bdcodemp = var.bdcodemp and bdchave = var.bdchave) <= :wdata;

    delete from tol_vsuc_emp_tlan_auto dist where dist.bdcodempsuc = :wcodemp and (select bddata from vsuc_empresas_tlan where bdcodemp = dist.bdcodemp and bdchave = dist.bdchave) <= :wdata;
    delete from tol_vsuc_emp_tlan_autoparpgto dist where dist.bdcodempsuc = :wcodemp and (select bddata from vsuc_empresas_tlan where bdcodemp = dist.bdcodempsuc and bdchave = dist.bdchave) <= :wdata;

    --Adiciona no log a cópia efetuada
    WSQLINSERT = 'Efetuada cópia da empresa: '||:WCODEMP||'.
'              ||'Empresa gerada: '||:WCODEMPBACKUP||'.
'              ||'Lançamentos até o período: '||:PRREFEMP;

    execute procedure SP_INSERIR_LOG(WCODEMP, NULL, PRCODUSU, NULL, 4, NULL, cast(addday(:wdata, 1) as date), WTEMPOINI, WSQLINSERT, 0, 0,
                                     CURRENT_USER, 'SERVIDOR', 'TfrProcessoTrocaPlanoContabilizacao', 'Processo de troca de contabilização',
                                     NULL, 'TEMPRESAS', NULL, 'FALSE', cast(addday(:wdata, 1) as date));
  end
end^

CREATE OR ALTER trigger tempresas_backup_online_bi0 for tempresas_backup_online
active before insert position 0
as
  DECLARE VARIABLE vcodigo INTEGER;
begin
  if ((new.BDCODIGO is null) or (new.BDCODIGO = 0)) then
    select BDRESULT from maxsci('BDCODIGO', 'BDCODEMP, BDCODIGO', 'BDCODEMP = '||new.BDCODEMP, 'TEMPRESAS_BACKUP_ONLINE') into  vcodigo;
  else
    begin
      select BDCODIGO from TEMPRESAS_BACKUP_ONLINE where BDCODEMP = new.BDCODEMP and BDCODIGO = new.BDCODIGO into vcodigo;
      if ((not vcodigo is null) and (vcodigo <> 0)) then
        select BDRESULT from maxsci('BDCODIGO', 'BDCODEMP, BDCODIGO', 'BDCODEMP = '||new.BDCODEMP, 'TEMPRESAS_BACKUP_ONLINE') into  vcodigo;
    end

  new.BDCODIGO = vcodigo;
end^
--#alt:16965. fim


CREATE OR ALTER TRIGGER tr_bf_insert_EMPRESAS_ECD_I157 FOR EMPRESAS_ECD_I157
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF ((NEW.bdcodplapadraoi157 IS NULL) OR (NEW.bdcodplapadraoi157 = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodplapadraoi157)+1),1) FROM EMPRESAS_ECD_I157
        WHERE BDCODEMP = NEW.BDCODEMP
        INTO vcodigo;
        NEW.bdcodplapadraoi157 = vcodigo;
     END
END
^

CREATE OR ALTER trigger tr_bfin_EMP_CONTAS_ECD_I157 for EMPRESAS_CONTAS_ECD_I157
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF ((NEW.bdcodplapadraoi157 IS NULL) OR (NEW.bdcodplapadraoi157 = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodplapadraoi157)+1),1) FROM EMPRESAS_CONTAS_ECD_I157
        WHERE BDCODEMP = NEW.BDCODEMP
        INTO vcodigo;
        NEW.bdcodplapadraoi157 = vcodigo;
     END
END
^

create or alter procedure VSUC_SP_CONTAS_CONC_EMP (
    PREMPRESAS varchar(3048),
    PRDATAINI date,
    PRDATAFIN date,
    PRCONTABILIZACAO integer)
returns (
    BDCODEMP integer,
    BDREF integer,
    BDCODUSU integer,
    BDNOMCOMPLUSU varchar(40),
    BDCODTPLA integer,
    BDCONCILIADO integer,
    BDENCPERIODO varchar(5),
    BDCODPLAPADRAO integer)
as
declare variable WSQL varchar(30000);
declare variable WDEBITO integer;
declare variable WCREDITO integer;
declare variable WCONCD varchar(5);
declare variable WCONCC varchar(5);
declare variable WCODEMP integer;
declare variable WREF integer;
declare variable WENCERRAMENTO integer;
begin
  WSQL = 'select  LAN.BDCODEMP, cast(extract(year from LAN.BDDATA) || lpad(extract(month from LAN.BDDATA), 2, ''0'') as varchar(6)) as BDREF,';
  WSQL = WSQL ||' LAN.BDCODUSU, USU.BDNOMCOMPLUSU, LAN.BDCODPLAPADRAO, LAN.BDDEBITO, LAN.BDCREDITO, LAN.BDCONCD, LAN.BDCONCC ';
  WSQL = WSQL ||' from VSUC_EMPRESAS_TLAN LAN ';
  WSQL = WSQL ||' inner join TUSUARIO USU on (USU.BDCODUSU = LAN.BDCODUSU) ';
  WSQL = WSQL ||' where (BDDATA between '''||:PRDATAINI||''' and '''||:PRDATAFIN||''') ';
  WSQL = WSQL ||'   and (BDCONTABILIZACAO in (0, '||:PRCONTABILIZACAO||')) ';
  if ((PREMPRESAS <> '') and (PREMPRESAS is not null)) then
    WSQL = WSQL ||' and (BDCODEMP in ('||:PREMPRESAS||')) ';
  WSQL = WSQL ||' group by LAN.BDCODEMP, BDREF, LAN.BDCODUSU,USU.BDNOMCOMPLUSU, LAN.BDCODPLAPADRAO, LAN.BDDEBITO, LAN.BDCREDITO, LAN.BDCONCD, LAN.BDCONCC ';

  for execute statement WSQL
  into :WCODEMP, :WREF, :BDCODUSU, :BDNOMCOMPLUSU, :BDCODPLAPADRAO, :WDEBITO, :WCREDITO, :WCONCD, :WCONCC DO
   begin
     BDCODTPLA = 0;

     if ((BDCODEMP is null) or (WCODEMP <> BDCODEMP) or (WREF <> BDREF))then
       begin
         BDCODEMP = WCODEMP;
         BDREF    = WREF;

         WENCERRAMENTO = 0;

         select first 1 ENC.BDCHAVEZER
         from VSUC_EMPRESAS_TENCEXE ENC
         where ENC.BDCODEMP = :WCODEMP and
               cast(extract(year from ENC.BDDATAINIZER) || lpad(extract(month from ENC.BDDATAINIZER), 2, '0') as varchar(6)) <= :WREF and
               cast(extract(year from ENC.BDDATAFIMZER) || lpad(extract(month from ENC.BDDATAFIMZER), 2, '0') as varchar(6)) >= :WREF
         into :WENCERRAMENTO;
       end

     if ((WDEBITO is not null) and (WDEBITO > 0)) then
       begin
         BDCODTPLA = WDEBITO;
         if ((WCONCD is not null) and (upper(WCONCD) = 'TRUE')) then
           BDCONCILIADO = 1;
         else
           BDCONCILIADO = null;

         if ((WENCERRAMENTO is not null) and (WENCERRAMENTO > 0)) then
           BDENCPERIODO = 'TRUE';
         else
           BDENCPERIODO = 'FALSE';

         suspend;

         --Se todos os lançamentos desta conta estiverem conciliados, não irá considerar no count de contas movimentadas. Se ocorrer de ter esta conta conciliada e não conciliada
         --irá agrupar e desconsiderar a duplicidade
         if (BDCONCILIADO = 1) then
           begin
             BDCONCILIADO = null;
             suspend;
           end
       end

     if ((WCREDITO is not null) and (WCREDITO > 0)) then
       begin
         BDCODTPLA = WCREDITO;
         if ((WCONCC is not null) and (upper(WCONCC) = 'TRUE')) then
           BDCONCILIADO = 1;
         else
           BDCONCILIADO = null;

         if ((WENCERRAMENTO is not null) and (WENCERRAMENTO > 0)) then
           BDENCPERIODO = 'TRUE';
         else
           BDENCPERIODO = 'FALSE';

         suspend;

         --Se todos os lançamentos desta conta estiverem conciliados, não irá considerar no count de contas movimentadas. Se ocorrer de ter esta conta conciliada e não conciliada
         --irá agrupar e desconsiderar a duplicidade
         if (BDCONCILIADO = 1) then
           begin
             BDCONCILIADO = null;
             suspend;
           end
       end
   end
end^

CREATE OR ALTER TRIGGER VEF_REINF_OCORRENCIA_LOTE_BI0 FOR VEF_REINF_OCORRENCIA_LOTE
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vCodigo = 0;
  IF ((NEW.BDCODOCO IS NULL) OR (NEW.BDCODOCO = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODOCO) + 1), 1) FROM VEF_REINF_OCORRENCIA_LOTE INTO vCodigo;
      NEW.BDCODOCO = vCodigo;
    END
END
^

CREATE OR ALTER TRIGGER VEF_REINF_EVT_BU0 FOR VEF_REINF_EVT
ACTIVE BEFORE UPDATE POSITION 0
AS
  DECLARE VARIABLE wcodevt INTEGER;  
  DECLARE VARIABLE wcodretif INTEGER;
  declare variable evtServTm boolean;
  declare variable evtServPr boolean;
  declare variable evtAssDespRec boolean;
  declare variable evtAssDespRep boolean;
  declare variable evtComProd boolean;
  declare variable evtCPRB boolean;
  declare variable wSQL varchar(600);
BEGIN
END
^

CREATE OR ALTER trigger vef_reinf_evt_ai0 for vef_reinf_evt
active after insert position 0
AS
begin
  IF (NEW.bdcodtipo in (11, 15)) THEN
    BEGIN   ---- Painel eSocial/Reinf/DCTFWeb - Carlos Xavier 20/06/22 - Update apenas para acionar a trigger BU0
      UPDATE VEF_REINF_EVT EVT SET EVT.bdintegrado = EVT.bdintegrado
      WHERE (EVT.BDCODEMP = NEW.bdcodemp AND EVT.bdcodevt = NEW.bdcodevt);
    END
end
^

CREATE OR ALTER TRIGGER VEF_REINF_EVT_AI1 FOR VEF_REINF_EVT
ACTIVE AFTER INSERT POSITION 1
AS
  declare variable vcodobr integer;
  declare variable vcod_2099 integer;
  declare variable vcod_4099 integer;
  declare variable vcodst integer;
begin
  select obr.bdcodobrser from VEF_REINF_TIPO_EVT REINF
  inner join VCT_BASE_OBRIGACAO OBR on(obr.bdcodevtreinf=reinf.bdcodtipo)
  where(BDCODTIPO=New.bdcodtipo)
  and((BDTITULO='R-1000')or(BDTITULO='R-2098')or(BDTITULO='R-9000')or(BDTITULO='R-9001')or
      (BDTITULO='R-9005')or(BDTITULO='R-9011')or(BDTITULO='R-9015'))
  into :vcodobr;

  if (vcodobr is not null) then
  begin
    insert into VCT_EMPRESA_TSOLICITATAREFA (BDCODEMP, BDCODST, BDCODOBRIGACAO, BDCODTIPO,
                                             BDDATASOL, BDDATASOLICITADA, BDDATAPREVISAO,
                                             BDREFSOL, BDTIPOSOLICITACAO)
    select new.bdcodemp, null as bdcodst, OBR.BDCODOBRSER, 501 as BDCODTIPO,
           current_date, venc.bdalerta, venc.bdentrega,
           new.bdreferencia, 1 as BDTIPOSOLICITACAO
    from VCT_BASE_OBRIGACAO OBR
    left join get_vencimento_tarefas(current_date, 15, obr.bdantecipar, obr.bdvence, obr.bdperiodicidade, coalesce(obr.bdalerta, 0), coalesce(obr.bdentrega, 0)) VENC on (VENC.bddata is not null)
    where obr.bdcodobrser = :vcodobr;
  end

    -- Buscar códigos REINF R-2099 e R-4099
    select obr.bdcodobrser from VEF_REINF_TIPO_EVT evt
    join VCT_BASE_OBRIGACAO obr on obr.bdcodevtreinf = evt.bdcodtipo
    where evt.bdtitulo = 'R-2099'
    into :vcod_2099;

    select obr.bdcodobrser from VEF_REINF_TIPO_EVT evt
    join VCT_BASE_OBRIGACAO obr on obr.bdcodevtreinf = evt.bdcodtipo
    where evt.bdtitulo = 'R-4099'
    into :vcod_4099;

    -- Atualizar tarefas R-2099
    if (vcod_2099 is not null) then
    begin
      for select tsol.bdcodst
          from VCT_EMPRESA_TSOLICITATAREFA tsol
          where tsol.bdcodemp = new.bdcodemp
            and tsol.bdcodobrigacao = :vcod_2099
            and tsol.bdrefsol = new.bdreferencia
          into :vcodst
      do
      begin
        update VCT_EMPRESA_TSOLICITATAREFA
        set bddatafim = null, bdaguard = 1
        where bdcodst = :vcodst
          and bdcodemp = new.bdcodemp;

        -- Inserir histórico
        execute procedure VCT_EMPRESA_THISTORICO_STATUS(new.bdcodemp, :vcodst, 2, :vcod_2099, null, null);
      end
    end

    -- Atualizar tarefas R-4099
    if (vcod_4099 is not null) then
    begin
      for select tsol.bdcodst
          from VCT_EMPRESA_TSOLICITATAREFA tsol
          where tsol.bdcodemp = new.bdcodemp
            and tsol.bdcodobrigacao = :vcod_4099
            and tsol.bdrefsol = new.bdreferencia
          into :vcodst
      do
      begin
        update VCT_EMPRESA_TSOLICITATAREFA
        set bddatafim = null, bdaguard = 1
        where bdcodst = :vcodst
          and bdcodemp = new.bdcodemp;

        -- Inserir histórico
        execute procedure VCT_EMPRESA_THISTORICO_STATUS(new.bdcodemp, :vcodst, 2, :vcod_4099, null, null);
    end
  end
end
^

CREATE OR ALTER TRIGGER TOL_VEF_REINF_EVT_SER_AD0 FOR TOL_VEF_REINF_EVT_SER
ACTIVE AFTER DELETE POSITION 0
AS
begin
/* Alt.: #165728 - Não pode deletar os eventos da Reinf e caso o status seja '1 - Aguardando', deve trocar para '8 - Excluido'...
  DELETE FROM VEF_REINF_EVT WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND (BDCODSTATUS IN (1,4,5));*/
  UPDATE VEF_REINF_EVT SET BDCODSTATUS = 8 WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND BDCODSTATUS = 1;
end
^

CREATE OR ALTER trigger tol_vef_reinf_evt_saude_ad0 for tol_vef_reinf_evt_saude
active after delete position 0
AS
begin
  UPDATE VEF_REINF_EVT SET BDCODSTATUS = 8 WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND BDCODSTATUS = 1;
end 
^

CREATE OR ALTER TRIGGER TOL_VEF_REINF_EVT_ENT_AD0 FOR TOL_VEF_REINF_EVT_ENT
ACTIVE AFTER DELETE POSITION 0
AS
begin
/* Alt.: #165728 - Não pode deletar os eventos da Reinf e caso o status seja '1 - Aguardando', deve trocar para '8 - Excluido'...
  DELETE FROM VEF_REINF_EVT WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND (BDCODSTATUS IN (1,4,5));*/
  UPDATE VEF_REINF_EVT SET BDCODSTATUS = 8 WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND BDCODSTATUS = 1;
end
^

CREATE OR ALTER TRIGGER TOL_VEF_REINF_EVT_DEMAISDOC_AD0 FOR TOL_VEF_REINF_EVT_DEMAISDOC
ACTIVE AFTER DELETE POSITION 0
AS
begin
/* Alt.: #165728 - Não pode deletar os eventos da Reinf e caso o status seja '1 - Aguardando', deve trocar para '8 - Excluido'...
  DELETE FROM VEF_REINF_EVT WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND (BDCODSTATUS IN (1,4,5));*/
  UPDATE VEF_REINF_EVT SET BDCODSTATUS = 8 WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND BDCODSTATUS = 1;
end
^

CREATE OR ALTER TRIGGER TOL_VEF_REINF_EVT_DIRF_AD0 FOR TOL_VEF_REINF_EVT_DIRF
ACTIVE AFTER DELETE POSITION 0
AS
begin
  UPDATE VEF_REINF_EVT SET BDCODSTATUS = 8 WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND BDCODSTATUS = 1;
end
^
CREATE OR ALTER TRIGGER TOL_VEF_REINF_EVT_DEMAISDOC_AD0 FOR TOL_VEF_REINF_EVT_DEMAISDOC
ACTIVE AFTER DELETE POSITION 0
AS
begin
/* Alt.: #165728 - não pode deletar os eventos da Reinf e caso o status seja '1 - Aguardando', deve trocar para '8 - Excluido'...
  DELETE FROM VEF_REINF_EVT WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND (BDCODSTATUS IN (1,4,5));*/
  UPDATE VEF_REINF_EVT SET BDCODSTATUS = 8 WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND BDCODSTATUS = 1;
end
^


CREATE OR ALTER TRIGGER TOL_VEF_EMP_TMOVDCOMP_AD0 FOR TOL_VEF_EMP_TMOVDCOMP
ACTIVE AFTER DELETE POSITION 0
AS
begin
--  DELETE FROM TDARFGERPGTO D
--  WHERE D.BDCODEMP = OLD.BDCODEMP AND
--        D.BDCHAVEPGTODARF = OLD.BDCHAVEPGTODARF;
end
^

CREATE OR ALTER TRIGGER TOL_VEF_REINF_EVT_SAI_AD0 FOR TOL_VEF_REINF_EVT_SAI
ACTIVE AFTER DELETE POSITION 0
AS
begin
/* Alt.: #165728 - Não pode deletar os eventos da Reinf e caso o status seja '1 - Aguardando', deve trocar para '8 - Excluido'...
  DELETE FROM VEF_REINF_EVT WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND (BDCODSTATUS IN (1,4,5));*/
  UPDATE VEF_REINF_EVT SET BDCODSTATUS = 8 WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND BDCODSTATUS = 1;
end
^
CREATE OR ALTER TRIGGER TOL_VEF_REINF_EVT_ASSDESP_AD0 FOR TOL_VEF_REINF_EVT_ASSDESP
ACTIVE AFTER DELETE POSITION 0
AS
begin
/* Alt.: #165728 - Não pode deletar os eventos da Reinf e caso o status seja '1 - Aguardando', deve trocar para '8 - Excluido'...
  DELETE FROM VEF_REINF_EVT WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND (BDCODSTATUS IN (1,4,5));*/
  UPDATE VEF_REINF_EVT SET BDCODSTATUS = 8 WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND BDCODSTATUS = 1;
end
^

CREATE OR ALTER TRIGGER TOL_VEF_REINF_EVT_CPRB_AD0 FOR TOL_VEF_REINF_EVT_CPRB
ACTIVE AFTER DELETE POSITION 0
AS
begin
/* Alt.: #165728 - Não pode deletar os eventos da Reinf e caso o status seja '1 - Aguardando', deve trocar para '8 - Excluido'...
  DELETE FROM VEF_REINF_EVT WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND (BDCODSTATUS IN (1,4,5));*/
  UPDATE VEF_REINF_EVT SET BDCODSTATUS = 8 WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND BDCODSTATUS = 1;
end
^

CREATE OR ALTER TRIGGER TOL_VEF_REINF_EVT_ESPDESP_AD0 FOR TOL_VEF_REINF_EVT_ESPDESP
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
/* Alt.: #165728 - Não pode deletar os eventos da Reinf e caso o status seja '1 - Aguardando', deve trocar para '8 - Excluido'...
  DELETE FROM VEF_REINF_EVT WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND (BDCODSTATUS IN (1,4,5));*/
  UPDATE VEF_REINF_EVT SET BDCODSTATUS = 8 WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT AND BDCODSTATUS = 1;
END
^

CREATE OR ALTER TRIGGER VEF_REINF_EVT_AD0 FOR VEF_REINF_EVT
ACTIVE AFTER DELETE POSITION 0
AS
  DECLARE VARIABLE wcodtipoevt INTEGER;
BEGIN
            DELETE from tol_vef_reinf_evt_ser WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.bdcodevt;
            DELETE from tol_vef_reinf_evt_ent WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.bdcodevt;
            DELETE from tol_vef_reinf_evt_SAI WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.bdcodevt;
            DELETE from tol_vef_reinf_evt_demaisdoc WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.bdcodevt;
            DELETE from tol_vef_reinf_evt_assdesp WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.bdcodevt;
            DELETE from TOL_VEF_REINF_EVT_CPRB WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.bdcodevt;
            DELETE FROM TOL_VEF_REINF_EVT_ESPDESP WHERE bdCODEMP = old.bdCODEMP AND bdCODEVT = old.bdCODEVT;
            DELETE FROM TOL_VEF_REINF_EVT_DIRF WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.BDCODEVT;
            DELETE FROM TOL_VEF_REINF_EVT_SOC WHERE bdCODMP = old.bdCODEMP AND bdCODEVT = old.bdCODEVT;
            DELETE FROM TOL_VEF_REINF_EVT_SAUDE WHERE bdCODEMP = old.bdCODEMP AND bdCODEVT = old.bdCODEVT;
            DELETE from TOL_VEF_EMP_TLANDEMCRENDPAGOS WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.bdcodevt;
                                                                                         
     -- wcodtipoevt =  OLD.bdcodtipo;
--      IF (wcodtipoevt in (3,4,19)) THEN
--        BEGIN
--            DELETE from tol_vef_reinf_evt_ser WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.bdcodevt;
--        END
--      IF (wcodtipoevt in (3,16)) THEN
--        BEGIN
--            DELETE from tol_vef_reinf_evt_ent WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.bdcodevt;
--        END
--      IF (wcodtipoevt in (4,7,19)) THEN
--        BEGIN
--            DELETE from tol_vef_reinf_evt_SAI WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.bdcodevt;
--        END
--      IF (wcodtipoevt in (5,6)) THEN
--        BEGIN
--            DELETE from tol_vef_reinf_evt_assdesp WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.bdcodevt;
--        END         
--      IF (wcodtipoevt in (18)) THEN
--        BEGIN
--            DELETE from tol_vef_reinf_evt_assdesp WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.bdcodevt;
--        END         
--      IF (wcodtipoevt = 8) THEN
--        BEGIN
--            DELETE from TOL_VEF_REINF_EVT_CPRB WHERE BDCODEMP = OLD.BDCODEMP AND BDCODEVT = OLD.bdcodevt;
--        END
--      IF (wcodtipoevt = 12) THEN -- R-3010 Receita de Espetáculo Desportivo
--        BEGIN
--            DELETE FROM TOL_VEF_REINF_EVT_ESPDESP WHERE bdCODEMP = old.bdCODEMP AND bdCODEVT = old.bdCODEVT;
--        END
END
^

CREATE OR ALTER TRIGGER VEF_REINF_EVT_BU0 FOR VEF_REINF_EVT
ACTIVE BEFORE UPDATE POSITION 0
AS
  DECLARE VARIABLE wcodevt INTEGER;
  declare variable evtServTm boolean;
  declare variable evtServPr boolean;
  declare variable evtAssDespRec boolean;
  declare variable evtAssDespRep boolean;
  declare variable evtComProd boolean;
  declare variable evtCPRB boolean;
  declare variable wSQL varchar(600);
BEGIN
  -- Matheus Amaral - 25/02/2021 -REINF - exclusão de eventos - Não pode mudar status para 8(Excluido) se tiver recibo
  --IF ((OLD.bdcodstatus <> 8) AND (NEW.bdcodstatus = 8) AND (OLD.bdrecibo is not null) AND (TRIM(OLD.bdrecibo) <> '')) THEN
  --  EXCEPTION EX_REINF_RCB_VINC;

  IF (OLD.bdcodtipo = 14 AND (OLD.BDCODSTATUS <> 3 AND NEW.bdcodstatus = 3)) THEN --Evento de exlusão indo para o status de sucesso
    BEGIN
      wcodevt = 0;
      EXECUTE STATEMENT 'select bdcodevt from vef_reinf_evt where bdrecibo = ''' || OLD.bdparametros || '''' INTO :wcodevt;  --Parametro do R9000 é o recibo do registro que deve ser removido
      IF (wcodevt > 0) THEN
        BEGIN                                                                                  
          UPDATE VEF_REINF_EVT SET BDCODRETIF = null WHERE (BDCODEMP = NEW.bdcodemp AND BDCODEVT = :wcodevt);
          --DELETE FROM VEF_REINF_EVT WHERE BDCODEMP = OLD.bdcodemp AND BDCODRETIF = :wcodevt;
          --DELETE FROM VEF_REINF_EVT WHERE BDCODEMP = OLD.bdcodemp AND BDCODEVT = :wcodevt;
          UPDATE VEF_REINF_EVT SET BDCODSTATUS = 8 WHERE BDCODEMP = OLD.bdcodemp AND BDCODRETIF = :wcodevt;
          UPDATE VEF_REINF_EVT SET BDCODSTATUS = 8 WHERE BDCODEMP = OLD.bdcodemp AND BDCODEVT = :wcodevt;
        END
    END
   ELSE if ((OLD.bdcodstatus <> 3) AND (NEW.bdcodstatus = 3) AND (NEW.bdcodretif IS NOT NULL)) then
     BEGIN
       UPDATE VEF_REINF_EVT SET BDCODRETIF = NEW.BDCODEVT WHERE (BDCODEMP = NEW.bdcodemp AND BDCODRETIF = NEW.BDCODRETIF);
       update VEF_REINF_EVT SET BDCODSTATUS = 6, BDCODRETIF = NEW.BDCODEVT WHERE (BDCODEMP = NEW.bdcodemp AND BDCODEVT = NEW.bdcodretif);
     END
-- Painel eSocial/Reinf/DCTFWeb - Carlos Xavier 20/06/22
  IF (OLD.bdcodtipo = 11) THEN
    BEGIN
        :wSQL = 'select IIF(V.BDXML like ''%<evtServTm>N</evtServTm>%'',''TRUE'',''FALSE'') BDEVTSERTM, ';
        :wSQL = :wSQL || 'IIF(V.BDXML like ''%<evtServPr>N</evtServPr>%'',''TRUE'',''FALSE'') BDEVTSERVPR, ';
        :wSQL = :wSQL || 'IIF(V.BDXML like ''%<evtAssDespRec>N</evtAssDespRec>%'',''TRUE'',''FALSE'') BDEVTASSDESPREC, ';
        :wSQL = :wSQL || 'IIF(V.BDXML like ''%<evtAssDespRep>N</evtAssDespRep>%'',''TRUE'',''FALSE'') BDEVTASSDESPREP, ';
        :wSQL = :wSQL || 'IIF(V.BDXML like ''%<evtComProd>N</evtComProd>%'',''TRUE'',''FALSE'') BDEVTCOMPROD, ';
        :wSQL = :wSQL || 'IIF(V.BDXML like ''%<evtCPRB>N</evtCPRB>%'',''TRUE'',''FALSE'') BDEVTCPRB ';
        :wSQL = :wSQL || 'from VEF_REINF_EVT V where V.BDCODEVT = '||OLD.bdcodevt||' ';
        :wSQL = :wSQL || 'and V.BDCODEMP = '||OLD.bdcodemp||';';

        EXECUTE STATEMENT :wSQL INTO :evtServTm, :evtServPr, :evtAssDespRec, :evtAssDespRep, :evtComProd, :evtCPRB;

        IF ((:evtServTm) and (:evtServPr) and (:evtAssDespRec) and (:evtAssDespRep) and (:evtComProd) and (:evtCPRB)) THEN
          BEGIN
           IF (OLD.bdcodstatus = 3) THEN
             BEGIN       -- Integrado Sem movimento
               NEW.BDINTEGRADO = 2;
             END
           ELSE
            BEGIN         -- Não integrado
               NEW.BDINTEGRADO = 3;
            END
          END
        ELSE
          BEGIN
            IF (OLD.bdcodstatus = 3) THEN
              BEGIN   -- Integrado
                NEW.BDINTEGRADO = 1;
              END
            ELSE
              BEGIN    -- Não integrado
                NEW.BDINTEGRADO = 3;
              END
          END
    END


      IF (OLD.bdcodtipo = 15) THEN
        BEGIN
          IF (OLD.bdcodstatus = 3) THEN
            BEGIN        -- Integrado
              NEW.BDINTEGRADO = 1;
              exit;
            END
           ELSE
             BEGIN        -- Não integrado
               NEW.BDINTEGRADO = 3;
             END
        END

      -- Evento de R-1000 de exclusao da empresa indo para sucesso
      IF ((NEW.bdcodtipo = 1) AND (NEW.BDCHAVE = 'EXCLUSAO')) THEN
        BEGIN
          IF ((OLD.bdcodstatus <> 3) AND (NEW.bdcodstatus = 3)) THEN
            BEGIN
              UPDATE VEF_REINF_EVT E SET E.bdcodstatus = 8 WHERE E.BDCODEMP = NEW.BDCODEMP AND E.bdcodamb = NEW.BDCODAMB AND E.bdcodstatus IN (1,2,3,9);
        END
        END
  
   new.BDXML = zipblob(new.BDXML);
   new.bdarquivoretonro = zipblob(new.bdarquivoretonro);

   if ( ((new.BDCODSTATUS = 5) or (new.BDCODSTATUS = 4) or (new.BDCODSTATUS = 7) or (new.BDCODSTATUS = 3) ) and ((old.bdvisualizado is null) or (old.bdvisualizado = 1) ) ) then
     begin
      new.bdvisualizado = 0;
     end
END
^

CREATE OR ALTER TRIGGER VEF_REINF_EVT_BI0 FOR VEF_REINF_EVT
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  /* Solicitação #191029 | Título: Reinf - Zipar arquivos xml dos eventos */
  new.BDXML = zipblob(new.BDXML);
  new.bdarquivoretonro = zipblob(new.bdarquivoretonro);
end
^

-- Alt: 21804 - Fernando Jr. 07/12/2017
CREATE OR ALTER TRIGGER tlivro_bi0 FOR tlivro
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodlivro IS NULL) OR (NEW.bdcodlivro = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodlivro)+1),1) FROM TLivro
            Where (bdcodemp = new.bdcodemp) and (bdcodrel = new.bdcodrel) INTO vcodigo;

        NEW.bdcodlivro = vcodigo;
     END
  ELSE
    BEGIN
       SELECT first 1 bdcodlivro FROM TLivro
            WHERE bdcodlivro = NEW.bdcodlivro and (bdcodemp = new.bdcodemp) and (bdcodrel = new.bdcodrel) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodlivro)+1),1) FROM TLivro
                Where (bdcodemp = new.bdcodemp)and (bdcodrel = new.bdcodrel) INTO vcodigo;
            NEW.bdcodlivro = vcodigo;
         END
    END

END^

CREATE OR ALTER PROCEDURE SP_VALIDACHAVE_NFE (
    PRCHAVENFE VARCHAR(60))
RETURNS (
    BDISVALID DM_BOOLEAN)
AS
DECLARE VARIABLE WVERIFICADOR INTEGER;
DECLARE VARIABLE WSOMA INTEGER;
BEGIN
  wSoma = 0;
  
  SELECT UPPER(RESULT) FROM SP_TIRATODOSSINAIS(:PRCHAVENFE) INTO :PRCHAVENFE;

  IF (CHAR_LENGTH(:PRCHAVENFE) <> 44) THEN
    BEGIN
      BDISVALID = 'FALSE';
      SUSPEND;
      EXIT;
    END

  SELECT SUM (
              (CAST(SUBSTRING(:PRCHAVENFE FROM 43 FOR 1) AS INTEGER) * 2) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 42 FOR 1) AS INTEGER) * 3) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 41 FOR 1) AS INTEGER) * 4) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 40 FOR 1) AS INTEGER) * 5) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 39 FOR 1) AS INTEGER) * 6) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 38 FOR 1) AS INTEGER) * 7) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 37 FOR 1) AS INTEGER) * 8) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 36 FOR 1) AS INTEGER) * 9) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 35 FOR 1) AS INTEGER) * 2) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 34 FOR 1) AS INTEGER) * 3) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 33 FOR 1) AS INTEGER) * 4) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 32 FOR 1) AS INTEGER) * 5) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 31 FOR 1) AS INTEGER) * 6) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 30 FOR 1) AS INTEGER) * 7) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 29 FOR 1) AS INTEGER) * 8) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 28 FOR 1) AS INTEGER) * 9) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 27 FOR 1) AS INTEGER) * 2) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 26 FOR 1) AS INTEGER) * 3) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 25 FOR 1) AS INTEGER) * 4) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 24 FOR 1) AS INTEGER) * 5) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 23 FOR 1) AS INTEGER) * 6) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 22 FOR 1) AS INTEGER) * 7) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 21 FOR 1) AS INTEGER) * 8) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 20 FOR 1)) - 48) * 9) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 19 FOR 1)) - 48) * 2) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 18 FOR 1)) - 48) * 3) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 17 FOR 1)) - 48) * 4) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 16 FOR 1)) - 48) * 5) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 15 FOR 1)) - 48) * 6) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 14 FOR 1)) - 48) * 7) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 13 FOR 1)) - 48) * 8) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 12 FOR 1)) - 48) * 9) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 11 FOR 1)) - 48) * 2) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 10 FOR 1)) - 48) * 3) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 9  FOR 1)) - 48) * 4) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 8  FOR 1)) - 48) * 5) +
              ((ASCII_VAL(SUBSTRING(:PRCHAVENFE FROM 7  FOR 1)) - 48) * 6) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 6 FOR 1) AS INTEGER) * 7) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 5 FOR 1) AS INTEGER) * 8) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 4 FOR 1) AS INTEGER) * 9) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 3 FOR 1) AS INTEGER) * 2) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 2 FOR 1) AS INTEGER) * 3) +
              (CAST(SUBSTRING(:PRCHAVENFE FROM 1 FOR 1) AS INTEGER) * 4)
             )
  FROM RDB$DATABASE
  GROUP BY :PRCHAVENFE
  INTO :wSOMA;

  IF (:wSOMA = 0) THEN
    BEGIN
      BDISVALID = 'FALSE';
      SUSPEND;
    END
  ELSE
    BEGIN
      wSoma = wSoma - (11 * (TRUNC(wSoma / 11)));
      IF ((wSoma = 0) OR (wSoma = 1)) THEN
        BEGIN
          wVerificador = 0;
        END
      ELSE
        BEGIN
          wVerificador = 11 - wSoma;
        END

      IF (wVerificador = (CAST(SUBSTRING(:PRCHAVENFE FROM 44 FOR 1) AS INTEGER))) THEN
        BEGIN
          BDISVALID = 'TRUE';
          SUSPEND;
        END
      ELSE
        BEGIN
          BDISVALID = 'FALSE';
          SUSPEND;
        END
    END
END^

CREATE OR ALTER PROCEDURE SP_CALC_RED_BC (
    PRVALOR NUMERIC(15,2),
    PRRED_BC NUMERIC(15,6),
    PRBC_ICMS NUMERIC(15,2),
    PRCSTICMS VARCHAR(3))
RETURNS (
    BDRED_BC NUMERIC(15,2))
AS
BEGIN
  PRRED_BC = COALESCE(:PRRED_BC, 0);
  PRBC_ICMS= COALESCE(:PRBC_ICMS, 0);
  PRCSTICMS = COALESCE(:PRCSTICMS, '');
  
  IF (CHAR_LENGTH(:PRCSTICMS) = 3) THEN
    BEGIN
      IF (NOT (SUBSTRING(COALESCE(:PRCSTICMS, 0) FROM CHAR_LENGTH(:PRCSTICMS)-1 FOR 2) IN(20, 70))) THEN
        BEGIN
          BDRED_BC = 0.00;
          SUSPEND;
          EXIT;
        END
    END

  IF (:PRRED_BC > 0) THEN
    BDRED_BC = (:PRVALOR * (:PRRED_BC / 100));
  ELSE
    BDRED_BC = (:PRVALOR - :PRBC_ICMS);

  IF (:BDRED_BC < 0) THEN
    BDRED_BC = 0;

  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_RETORNA_SO_NUMEROS_CHAVENFE (
    PRSTR VARCHAR(60))
RETURNS (
    BDNUMERO VARCHAR(60))
AS
BEGIN

  BDNUMERO = :PRSTR;
  BDNUMERO = REPLACE(:BDNUMERO, '.', '');
  BDNUMERO = REPLACE(:BDNUMERO, '-', '');
  BDNUMERO = REPLACE(:BDNUMERO, '/', '');

  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_PARSE_DATE (
    PRDATA DATE,
    PRFORMATO VARCHAR(8))
RETURNS (
    BDDATA VARCHAR(10))
AS
DECLARE VARIABLE WAUX VARCHAR(4);
DECLARE VARIABLE WDAY VARCHAR(2);
DECLARE VARIABLE WMONTH VARCHAR(2);
DECLARE VARIABLE WYEAR VARCHAR(4);
BEGIN
  PRFORMATO = UPPER(:PRFORMATO);
  BDDATA = '';

  wDay   = LPAD(EXTRACT(DAY FROM :PRDATA), 2, '0');
  wMonth = LPAD(EXTRACT(MONTH FROM :PRDATA), 2, '0');
  wYear  = EXTRACT(YEAR FROM :PRDATA);

  wAux = SUBSTRING(:PRFORMATO FROM 1 FOR 2);

  /*Primeiro*/
  IF (:wAUX = 'DD') THEN
    BDDATA = :wDay;
  ELSE
  IF (:wAUX = 'MM') THEN
    BDDATA = :wMonth;
  ELSE
  IF (:wAUX = 'YY') THEN
    BDDATA = :wYear;

  PRFORMATO = REPLACE(:PRFORMATO, IIF(:wAUX = 'YY', 'YYYY', ''||:wAux||''), '');

  wAux = SUBSTRING(:PRFORMATO FROM 1 FOR 2);
  /*Segundo*/
  IF (:wAUX = 'DD') THEN
    BDDATA = BDDATA || :wDay;
  ELSE
  IF (:wAUX = 'MM') THEN
    BDDATA = :BDDATA || :wMonth;
  ELSE
  IF (:wAUX = 'YY') THEN
    BDDATA = :BDDATA || :wYear;

  PRFORMATO = REPLACE(:PRFORMATO, IIF(:wAUX = 'YY', 'YYYY', ''||:wAux||''), '');

  wAux = SUBSTRING(:PRFORMATO FROM 1 FOR 2);
  /*Terceiro*/
  IF (:wAUX = 'DD') THEN
    BDDATA = BDDATA || :wDay;
  ELSE
  IF (:wAUX = 'MM') THEN
    BDDATA = :BDDATA || :wMonth;
  ELSE
  IF (:wAUX = 'YY') THEN
    BDDATA = :BDDATA || :wYear;

  SUSPEND;

END^

COMMENT ON PARAMETER SP_PARSE_DATE.PRFORMATO IS 'DDMMYYYY, MMDDYYYY, YYYYMMDD...'^

CREATE OR ALTER PROCEDURE SP_GET_CODPARTICIPANTEEXP (
    PRTIPOEXPCODPART INTEGER,
    PRCODTER INTEGER,
    PRCGCTER VARCHAR(18),
    PRIETER VARCHAR(20),
    PRCODIGOARQUIVO VARCHAR(60))
RETURNS (
    BDRETORNO VARCHAR(60))
AS
DECLARE VARIABLE WI INTEGER;
BEGIN

  IF (:PRTIPOEXPCODPART = 0) THEN
    BDRETORNO = :PRCODTER;
  ELSE
  IF (:PRTIPOEXPCODPART = 1) THEN
    BEGIN
      SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(:PRIETER) INTO :PRIETER;
      SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(:PRCGCTER) INTO :PRCGCTER;

      PRIETER = TRIM(COALESCE(:PRIETER, ''));
      PRCGCTER = TRIM(COALESCE(:PRCGCTER, ''));

      BDRETORNO = :PRCGCTER;

      wI = 0;
      WHILE (wI <= 9) DO
        BEGIN
          IF (:PRCGCTER = LPAD('', CHAR_LENGTH(:PRCGCTER), wI)) THEN
            BEGIN
              BDRETORNO = '';
              BREAK;
            END
          wI = wI + 1;
        END

      IF (:PRIETER <> '') THEN
        BDRETORNO = :BDRETORNO || '_' || :PRIETER;
    END
  ELSE
  IF (:PRTIPOEXPCODPART = 3) THEN
    BDRETORNO = :PRCODIGOARQUIVO;
  ELSE
    BEGIN
      SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(:PRCGCTER) INTO :PRCGCTER;
      PRCGCTER = TRIM(COALESCE(:PRCGCTER, ''));

      BDRETORNO = :PRCGCTER;

      wI = 0;
      WHILE (wI <= 9) DO
        BEGIN
          IF (:PRCGCTER = LPAD('', CHAR_LENGTH(:PRCGCTER), wI)) THEN
            BEGIN
              BDRETORNO = '';
              BREAK;
            END
          wI = wI + 1;
        END
    END

  IF (:BDRETORNO = '') THEN
    BDRETORNO = :PRCODTER;

  BDRETORNO = TRIM(COALESCE(BDRETORNO, ''));

  SUSPEND;
END;^


create or alter procedure SP_GET_FCP (
    PRTIPOFCP integer,
    PRVLRFCP numeric(15,2),
    PRCSTICMS varchar(3),
    PRCODNAT integer)
returns (
    BDRETORNO numeric(15,2))
as
declare variable WNAT varchar(5);
declare variable WST varchar(5);
BEGIN
  BDRETORNO = 0;
  IF (PRVLRFCP > 0) THEN
    BEGIN
      IF (PRCODNAT <= 9999) THEN
        BEGIN
          WNAT = CAST(PRCODNAT AS VARCHAR(4));
          WNAT = (SUBSTRING(WNAT FROM 1 FOR 1))||'.'||(SUBSTRING(WNAT FROM 2 FOR 3));
        END
      ELSE
        WNAT = SUBSTRING((SELECT BDCLASSIFICACAO FROM VEF_BASE_TNATOP WHERE BDCODNAT = :PRCODNAT)FROM 1 FOR 5);

      WST = IIF((WNAT LIKE '1.4%') OR
                (WNAT LIKE '1.9%') OR
                (WNAT LIKE '2.4%') OR
                (WNAT LIKE '2.9%') OR
                (WNAT LIKE '5.4%') OR
                (WNAT LIKE '6.4%'), 'T','F');
    
      IF (/* VL_FCP_OP =  x00, x10, x20, x51, x70 ou x90 */
          ((PRTIPOFCP = 0)  and ((:PRCSTICMS LIKE '_00') OR
                                                      (:PRCSTICMS LIKE '_10') OR
                                                      (:PRCSTICMS LIKE '_20') OR
                                                      (:PRCSTICMS LIKE '_51') OR
                                                      (:PRCSTICMS LIKE '_70') OR
                                                      (:PRCSTICMS LIKE '_90'))) OR
          /* VL_FCP_ST =  x10, x30, x70, x90, 201, 202, 203 ou 900 */
          ((PRTIPOFCP = 1) and ((:PRCSTICMS LIKE '_10') OR
                                (:PRCSTICMS LIKE '_30') OR
                                (:PRCSTICMS LIKE '_70') OR
                                (:PRCSTICMS LIKE '_90') OR
                                (:PRCSTICMS LIKE '201') OR
                                (:PRCSTICMS LIKE '202') OR
                                (:PRCSTICMS LIKE '203') OR
                                (:PRCSTICMS LIKE '900'))) OR
          /* VL_FCP_RET =  x60 ou 500 */
          ((PRTIPOFCP = 2) and ((:PRCSTICMS LIKE '_60') OR
                                (:PRCSTICMS LIKE '500')))) THEN
        BEGIN
          IF (WST = 'T') THEN
            BEGIN
              BDRETORNO = PRVLRFCP;
            END
          ELSE IF (PRTIPOFCP <> 1) THEN
            BDRETORNO = PRVLRFCP;
        END
    END
  SUSPEND;
END^

COMMENT ON PARAMETER SP_GET_FCP.PRTIPOFCP IS '0 - Operação; 1 - ST; 3 - Retido'^


CREATE OR ALTER procedure SP_EXPORTA_BLOCOC_ENT_AUX (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRTIPOEXPCODPART integer,
    PRPERFIL integer,
    PRCODPLAPADRAOREF integer,
    PRSOMAIPIPROD varchar(5),
    PRSOMASTPROD varchar(5),
    PRSESSAOSEGREG integer,
    PRICMSMONO varchar(5))
as
declare variable WSEGREGACAO varchar(5);
declare variable WFCPOP varchar(5);
declare variable WEXP_VL_FCP_OP boolean;
declare variable WUF_EMPRESA varchar(2);
BEGIN
   EXECUTE PROCEDURE SP_SETA_COMPETENCIA(CAST((EXTRACT(YEAR FROM :PRDTINI) || LPAD(EXTRACT(MONTH FROM :PRDTINI),2,'0')) AS INTEGER));

  SELECT Coalesce(rdb$get_context('USER_SESSION', 'W_SEGREGACAO_FISCAL'),'FALSE') FROM rdb$database INTO WSEGREGACAO;

   --Alt: 214074 - obtendo o estado da empresa
   SELECT UF.BDFCPOP, UF.BDSIGLAUF FROM VW_TEMPRESAS_REF EMPR
   LEFT OUTER JOIN TCIDADE CID ON (CID.bdcodcid = EMPR.BDCODCID)
   LEFT OUTER JOIN TUF UF ON (CID.BDCODUF = UF.BDCODUF)
   WHERE :PRCODEMP = EMPR.BDCODEMP
   INTO :WFCPOP, :WUF_EMPRESA; --Alt.: FCP_OP - PEGA O PARÂMETRO FCPOP DA UF, PARA SABER SE DEVE SOMAR O FCP JUNTO AO ICMS.

   --Alt: 217654 - Para exportar o valor do FCP normal se a empresa não for do RJ ou se a competência for inferior à 03/2025 (revogado e alterado para 2099, caso retornar basta alterar aqui).
   :wexp_vl_fcp_op = (:wUF_EMPRESA <> 'RJ') or (EXTRACT(YEAR FROM :PRDTINI)||LPAD(EXTRACT(MONTH FROM :PRDTINI),2,'0') < 209901);

  /*****************************************************************************
   *                                   C190                                    *
   ****************************************************************************/
  /*Monta o C190 a partir do movimento de produto*/
  SETORDEMSEQUENCIAL_STR(:PRCODEMP);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
  SELECT :PRARQUIVO BDID,
        LPAD(C190.BDCODEMP, 6, '0')||'.0.'||LPAD(C190.BDCHAVE, 10, '0')||'.C100.C190.'||C190.BDCODNAT||'.'||REPLACE(CAST(C190.BDALIQICMS AS DM_NUMERIC_7_4_ALIQ), '.', '')||'.'||LPAD(COALESCE(C190.BDCSTICMS, ''), 3, ' '),
        'C190' BDREG,
        '|C190'||
        '|'||COALESCE(C190.BDCSTICMS, '')|| --CST_ICMS
        '|'||COALESCE(C190.BDCODNAT, '')|| --CFOP
        '|'||IIF(((substring(C190.BDCSTICMS from 2 for 3) = '61') AND (:PRICMSMONO = 'TRUE')), REPLACE(COALESCE(0,00, 0.00), '.', ','), REPLACE(CAST(COALESCE(C190.BDALIQICMS, 0) AS DM_NUMERIC_15_2), '.', ','))|| --ALIQ_ICMS

        --'|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, (COALESCE(C190.BDVLRITEM + C190.BDVLRDESPACESSORIA + C190.BDVLRFRETE, 0) - COALESCE(C190.BDVLRDESC, 0)),
        --                                              (IIF(((GETORDEMSEQUENCIAL(C190.BDCHAVE) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT))), 0.00), '.', ',')|| --VL_OPR
        '|'||REPLACE((CASE WHEN C190.BDMODELO = 65 THEN (COALESCE(C190.BDVLRITEM + C190.BDVLRDESPACESSORIA + C190.BDVLRFRETE, 0) - COALESCE(C190.BDVLRDESC, 0))
                           WHEN (tot.bdVLRDESC + tot.bdVLRABATNT) = C190.bdDESCONTONOTA THEN ((IIF(((GETORDEMSEQUENCIAL_STR(C190.BDCHAVE,C190.BDCODEMP) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT)) - c190.bdVLRABATNT) -- Alt.: #125909 #126894 #127057 #127296 #127440 #127528 #127589 #127562 #127779 #127586 - Se a soma do desconto + abatimento dos produtos for igual ao que possui no campo desconto da capa da nota, vai levar no C190 campo "valor da operacao" o valor dos produtos menos desconto e abatimento informados no produto.
                      ELSE (IIF(((GETORDEMSEQUENCIAL_STR(C190.BDCHAVE,C190.BDCODEMP) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT)) END), '.', ',') -- Alt.: #125909 #126894 #127057 #127296 #127440 #127528 #127589 #127562 #127779 #127586 - Se a soma do desconto + abatimento dos produtos for diferente do que possui no campo desconto da capa da nota, vai levar no C190 campo "valor da operacao" o valor dos produtos menos desconto.
           || --VL_OPR
        '|'||IIF(((substring(C190.BDCSTICMS from 2 for 3) = '61') AND (:PRICMSMONO = 'TRUE')), REPLACE(COALESCE(0,00, 0.00), '.', ','),REPLACE(COALESCE(C190.BDBCICMS, 0.00), '.', ','))|| --VL_BC_ICMS
        '|'||REPLACE(COALESCE(C190.BDVLRICMS,0.00) + IIF(:WFCPOP = 'TRUE', COALESCE(C190.BDVLRFCP, 0.00), 0.00)
                     /*COALESCE(IIF(C190.BDREFLAN >= 201901,(SELECT BDRETORNO FROM SP_GET_FCP(0,C190.BDFCPRETIDO,C190.BDCSTICMS, C190.BDCODNAT)),0.00),0.00) --Soma FCP_OP */
                     , '.', ',')|| --VL_ICMS #89669 - Deve somar FCP
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, IIF(ITEM.BDVLRSTITEM = 0, NULL, C190.BDBCST)), 0.00), '.', ',')|| --VL_BC_ICMS_ST
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, COALESCE(IIF(ITEM.BDVLRSTITEM = 0, NULL, C190.BDVLRST),0.00)  + IIF(C190.BDREFLAN >= 201901,IIF(C190.BDCODNAT IN ('1410','1411','1414','1415','1660','1661','1662','2410',
                                                                                                                    '2411','2414','2415','2660','2661','2662'),COALESCE(C190.BDFCPRETIDO,0.00) ,0.00),0.00) -- Na entrada só soma o FCP Retido quando a CFOP é de anulação
                    /* COALESCE(IIF(C190.BDREFLAN >= 201901,(SELECT BDRETORNO FROM SP_GET_FCP(1,C190.BDFCPRETIDO,C190.BDCSTICMS, C190.BDCODNAT)),0.00),0.00) + --Soma FCP_ST
                     COALESCE(IIF(C190.BDREFLAN >= 201901,(SELECT BDRETORNO FROM SP_GET_FCP(2,C190.BDFCPRETIDO,C190.BDCSTICMS, C190.BDCODNAT)),0.00),0.00)   --Soma FCP_RET*/
                     ), 0.00), '.', ',')|| --VL_ICMS_ST
        --'|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, (SELECT BDRED_BC FROM SP_CALC_RED_BC((COALESCE(C190.BDVLRITEM, 0) + COALESCE(C190.BDVLRDESPACESSORIA, 0) + COALESCE(C190.BDVLRIPI, 0) + COALESCE(C190.BDVLRST, 0)), C190.BDREDBCICMS, C190.BDBCICMS, C190.BDCSTICMS))), 0.00), '.', ',')|| --VL_RED_BC
        --'|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, (SELECT BDRED_BC FROM SP_CALC_RED_BC((IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT)), C190.BDREDBCICMS, C190.BDBCICMS, C190.BDCSTICMS))), 0.00), '.', ',')|| --VL_RED_BC
        --'|'||REPLACE((SELECT BDVALOR FROM GET_TRATA_VALOR_NEGATIVO(IIF((SUBSTRING(COALESCE(C190.BDCSTICMS, 0) FROM CHAR_LENGTH(C190.BDCSTICMS)-1 FOR 2)) IN(20, 70), (COALESCE(IIF(C190.BDMODELO = 65, (COALESCE(C190.BDVLRITEM + C190.BDVLRDESPACESSORIA + C190.BDVLRFRETE, 0) - COALESCE(C190.BDVLRDESC, 0)),(IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT))), 0) - COALESCE(C190.BDBCICMS, 0)), 0.00))), '.', ',')|| --VL_RED_BC
        '|'||REPLACE((SELECT BDVALOR FROM GET_TRATA_VALOR_NEGATIVO(IIF((SUBSTRING(C190.BDCSTICMS FROM 2 FOR 2)) IN(20, 70), (COALESCE(IIF(C190.BDMODELO = 65, (COALESCE(C190.BDVLRITEM + C190.BDVLRDESPACESSORIA + C190.BDVLRFRETE, 0) - COALESCE(C190.BDVLRDESC, 0)),(IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT))), 0) - COALESCE(C190.BDBCICMS, 0) - COALESCE(C190.BDVLRST, 0.00) - COALESCE(C190.BDVLRIPI, 0.00)), 0.00))), '.', ',')|| --VL_RED_BC
        '|'||REPLACE(COALESCE(C190.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
        '|'||COALESCE(OBS_ITEM.BDCODEXP, COALESCE(OBS_C195.BDCODEXP,''))|| --COD_OBS
        '|',
        COALESCE(OBS_ITEM.BDCODOBS, OBS_C195.BDCODOBS)
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCSTICMS, MOV.BDCODNAT, MOV.BDALIQICMS, ENT.BDMODELO, MOV.BDVLRITEM,
               MOV.BDVLRDESC, MOV.BDVLRFRETE, MOV.BDVLRDESPACESSORIA, MOV.BDVLRIPI, MOV.BDVLRST, MOV.BDBCICMS,
               MOV.BDVLRICMS, MOV.BDBCST, MOV.BDREDBCICMS, ENT.BDVALORNOTA, ENT.BDREFLAN, MOV.BDFCPRETIDO, ent.bdDESCONTONOTA,
               (COALESCE(MOV.BDVLRFRETE, 0) + COALESCE(MOV.BDVLRITEM, 0) +
                COALESCE(MOV.BDVLRDESPACESSORIA, 0) +
                IIF((Coalesce(:PRSOMAIPIPROD,'FALSE') = 'FALSE') AND (Coalesce(MOV.BDSOMAIPIPROD,'FALSE') = 'FALSE'),COALESCE(MOV.BDVLRIPI, 0),0) +
                IIF((Coalesce(:PRSOMASTPROD,'FALSE') = 'FALSE') AND (Coalesce(MOV.BDSOMASTPROD,'FALSE') = 'FALSE'),COALESCE(MOV.BDVLRST, 0),0) - COALESCE(MOV.BDVLRDESC, 0)  +
                COALESCE(IIF(ENT.BDREFLAN >= 201901,MOV.BDFCPRETIDO,0.00),0.00) --Soma FCP_ST
                ) BDVLRTOT, MOV.BDCODOBS, MOV.bdVLRABATNT, MOV.BDVLRFCP
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                     ICMS.BDCSTICMS,
                     COALESCE(MOV.BDCODNAT, 0) BDCODNAT,
                     --CAST(COALESCE(PRO.BDALIQICMS, 0) AS NUMERIC(6, 2)) BDALIQICMS, Alt.: #228632 - Deve agrupar a aliquota no caso do CST 61 que nao exportar...
                     IIF(((SUBSTRING(ICMS.BDCSTICMS from 2 for 3) = '61') AND (:PRICMSMONO = 'TRUE')) OR -- Alt.: #228632 - Deve agrupar a aliquota no caso do CST 61 que nao exportar...
                         (MOV.BDDEVOL = 'TRUE' AND (SUBSTRING(ICMS.BDCSTICMS FROM 2 FOR 3) = '02' OR SUBSTRING(ICMS.BDCSTICMS FROM 2 FOR 3) = '15' OR SUBSTRING(ICMS.BDCSTICMS FROM 2 FOR 3) = '53')),
                         0,COALESCE(PRO.BDALIQICMS, 0)) BDALIQICMS,
                     SUM(COALESCE(PRO.BDVLRITEM, 0)) BDVLRITEM,
                     SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC,
                     SUM(COALESCE(PRO.BDVLRFRETE, 0)) BDVLRFRETE,
                     SUM(COALESCE(PRO.BDVLRDESPACESSORIA, 0)) BDVLRDESPACESSORIA,
                     SUM(COALESCE(PRO.BDVLRIPI, 0)) BDVLRIPI,
                     SUM(COALESCE(PRO.BDVLRST, 0)) BDVLRST,
                     SUM(COALESCE(PRO.BDBCST, 0)) BDBCST,
                     --SUM(COALESCE(PRO.BDBCICMS, 0)) BDBCICMS, -- Alt.: #228632 - Zera quando CST de ICMS for final 02, 15 ou 53 e a CFOP for de devolução...
                     SUM(IIF((MOV.BDDEVOL = 'TRUE' AND (SUBSTRING(ICMS.BDCSTICMS FROM 2 FOR 3) = '02' OR SUBSTRING(ICMS.BDCSTICMS FROM 2 FOR 3) = '15' OR SUBSTRING(ICMS.BDCSTICMS FROM 2 FOR 3) = '53')),
                             0, COALESCE(PRO.BDBCICMS, 0))) BDBCICMS,
                     SUM(COALESCE(PRO.BDVLRICMS, 0)) BDVLRICMS,
                     SUM(COALESCE(PRO.BDREDBCICMS, 0)) BDREDBCICMS,
                     SUM(COALESCE(PRO.BDFCPRETIDO,0)) BDFCPRETIDO,
                     MAX(COALESCE(MOV.BDCODOBS,0)) BDCODOBS,
                     SUM(COALESCE(PRO.BDVLRFCP,0)) BDVLRFCP,
                     SUM(COALESCE(PRO.bdVLRABATNT,0)) bdVLRABATNT, Max(MOV.BDSOMAIPIPROD) BDSOMAIPIPROD, Max(MOV.BDSOMASTPROD) BDSOMASTPROD
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT, i.BDCODOBS, NATOP.BDSOMAIPIPROD, NATOP.BDSOMASTPROD, NATOP.BDDEVOL
                    FROM VEF_EMP_TMOVENT M
                    LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                    JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)                 
                    LEFT OUTER JOIN VEF_BASE_TNATOP NATOP ON (NATOP.BDCODNAT = I.BDCODNAT)
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                    AND (M.BDMODELO IN (1, 4, 55, 100) OR (:WSEGREGACAO = 'TRUE'))
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (M.BDCODSITNF = 6)*/)
                   ) MOV
              JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
              LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS)
              GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, ICMS.BDCSTICMS, MOV.BDCODNAT,
              --CAST(COALESCE(PRO.BDALIQICMS, 0) AS NUMERIC(6, 2)) Alt.: #228632 - Deve agrupar a aliquota no caso do CST 61 que nao exportar...
              IIF(((SUBSTRING(ICMS.BDCSTICMS from 2 for 3) = '61') AND (:PRICMSMONO = 'TRUE')) OR
                  (MOV.BDDEVOL = 'TRUE' AND (SUBSTRING(ICMS.BDCSTICMS FROM 2 FOR 3) = '02' OR SUBSTRING(ICMS.BDCSTICMS FROM 2 FOR 3) = '15' OR SUBSTRING(ICMS.BDCSTICMS FROM 2 FOR 3) = '53')),
                  0,COALESCE(PRO.BDALIQICMS, 0))
             ) MOV
        JOIN VEF_EMP_TMOVENT ENT ON(ENT.BDCODEMP = MOV.BDCODEMP AND ENT.BDCHAVE = MOV.BDCHAVE)
       ) C190
  LEFT OUTER JOIN (
                   SELECT C190_TOT.BDCODEMP, C190_TOT.BDCHAVE, SUM(C190_TOT.BDVLRDIF) BDVLRDIF, COUNT(C190_TOT.BDCHAVE) BDORDEMMAX,
                          SUM(C190_TOT.bdVLRDESC) AS bdVLRDESC, SUM(C190_TOT.bdVLRABATNT) AS bdVLRABATNT
                   FROM (
                         SELECT MOV.BDCODEMP, MOV.BDCHAVE, PRO.BDCODCSTICMS,
                                SUM(COALESCE(pro.bdVLRDESC, 0)) AS bdVLRDESC,
                                SUM(COALESCE(pro.bdVLRABATNT, 0)) AS bdVLRABATNT,
                                ((SUM(COALESCE(PRO.BDVLRITEM, 0)) +
                                  SUM(COALESCE(PRO.BDVLRDESPACESSORIA, 0)) +
                                  SUM(IIF((Coalesce(:PRSOMAIPIPROD,'FALSE') = 'FALSE') AND (Coalesce(MOV.BDSOMAIPIPROD,'FALSE') = 'FALSE'),COALESCE(PRO.BDVLRIPI, 0),0)) +
                                  SUM(IIF((Coalesce(:PRSOMASTPROD,'FALSE') = 'FALSE') AND (Coalesce(MOV.BDSOMASTPROD,'FALSE') = 'FALSE'),COALESCE(PRO.BDVLRST, 0),0)) +
                                  SUM(COALESCE(PRO.BDVLRFRETE, 0))) -
                                  SUM(COALESCE(PRO.BDVLRDESC, 0)) +
                                  SUM(COALESCE(IIF(MOV.BDREFLAN >= 201901,PRO.BDFCPRETIDO,0.00),0.00)) --Soma FCP
                                 ) BDVLRDIF
                         FROM (
                               SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT, M.BDREFLAN, NATOP.BDSOMAIPIPROD, NATOP.BDSOMASTPROD
                               FROM VEF_EMP_TMOVENT M
                               LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                               JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)                               
                               LEFT OUTER JOIN VEF_BASE_TNATOP NATOP ON (NATOP.BDCODNAT = I.BDCODNAT)
                               WHERE M.BDCODEMP = :PRCODEMP
                               AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                               AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                               AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                               AND (M.BDMODELO IN (1, 4, 55, 100) OR(:WSEGREGACAO = 'TRUE'))
                               AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (M.BDCODSITNF = 6)*/)
                              ) MOV
                         JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)  
                         LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS)
                         GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, PRO.BDCODCSTICMS, MOV.BDCODNAT, CAST(COALESCE(PRO.BDALIQICMS, 0) AS NUMERIC(6, 2))
                        ) C190_TOT
                   GROUP BY C190_TOT.BDCODEMP, C190_TOT.BDCHAVE
                  ) TOT ON(TOT.BDCODEMP = C190.BDCODEMP AND TOT.BDCHAVE = C190.BDCHAVE)
  LEFT OUTER JOIN (
                   SELECT M.BDCODEMP, M.BDCHAVE, SUM(COALESCE(I.BDVLRST, 0)) BDVLRSTITEM
                   FROM VEF_EMP_TMOVENT M
                   LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                   JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                   WHERE M.BDCODEMP = :PRCODEMP
                   AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                   AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                   AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                   AND (M.BDMODELO IN (1, 4, 55, 100) OR (:WSEGREGACAO = 'TRUE'))
                   AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (M.BDCODSITNF = 6)*/)
                   GROUP BY M.BDCODEMP, M.BDCHAVE
                  ) ITEM ON(ITEM.BDCODEMP = C190.BDCODEMP AND ITEM.BDCHAVE = C190.BDCHAVE)
  LEFT OUTER JOIN ( SELECT C.BDCODEMP, C.BDCHAVE, MAX(c.BDCODOBS) BDCODOBS
                    FROM VEF_EMP_TC195ENT C
                    GROUP BY C.BDCODEMP, C.BDCHAVE ) C195 ON (C195.BDCODEMP = C190.BDCODEMP AND C195.BDCHAVE = C190.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TOBSERVACAO OBS_ITEM ON(OBS_ITEM.BDCODOBS = C190.BDCODOBS)
  LEFT OUTER JOIN VEF_BASE_TOBSERVACAO OBS_C195 ON(OBS_C195.BDCODOBS = C195.BDCODOBS);

  /*Monta o C190 a partir da tabela do C190*/
  SETORDEMSEQUENCIAL_STR(:PRCODEMP);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.0.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C190.'||SUBSTRING(MOV.BDCODNAT FROM 1 FOR 4)||'.'||REPLACE(CAST(C190.BDALIQICMS AS DM_NUMERIC_7_4_ALIQ), '.', '')||'.'||LPAD(COALESCE(ICMS.BDCSTICMS, ''), 3, ' '),
          'C190' BDREG,
          '|C190'||
          '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
          '|'||COALESCE(SUBSTRING(MOV.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
          '|'||REPLACE(CAST(COALESCE(C190.BDALIQICMS, 0) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
          '|'||REPLACE(SUM(COALESCE(C190.BDVLROPER, 0.00)), '.', ',')|| --VL_OPR
          '|'||REPLACE(SUM(COALESCE(C190.BDVLRBCICMS, 0.00)), '.', ',')|| --VL_BC_ICMS
          '|'||REPLACE(SUM(COALESCE(C190.BDVLRICMS, 0.00)), '.', ',')|| --VL_ICMS
          '|'||REPLACE(SUM(COALESCE(C190.BDVLRBCICMSST, 0.00)), '.', ',')|| --VL_BC_ICMS_ST
          '|'||REPLACE(SUM(COALESCE(C190.BDVLRICMSST, 0.00)), '.', ',')|| --VL_ICMS_ST
--        '|'||REPLACE((SELECT BDVALOR FROM GET_TRATA_VALOR_NEGATIVO(IIF((SUBSTRING(COALESCE(ICMS.BDCSTICMS, 0) FROM CHAR_LENGTH(ICMS.BDCSTICMS)-1 FOR 2)) IN(20, 70), (COALESCE(C190.BDVLROPER, 0) - COALESCE(C190.BDVLRBCICMS, 0)), 0.00))) , '.', ',')|| --VL_RED_BC
          '|'||REPLACE((SELECT BDVALOR FROM GET_TRATA_VALOR_NEGATIVO(IIF((SUBSTRING(ICMS.BDCSTICMS FROM 2 FOR 2)) IN(20, 70), (SUM(COALESCE(C190.BDVLROPER, 0)) - SUM(COALESCE(C190.BDVLRBCICMS, 0)) - SUM(COALESCE(C190.BDVLRICMSST, 0.00))), 0.00))) , '.', ',')|| --VL_RED_BC
          '|'||REPLACE(SUM(COALESCE(C190.BDVLRIPI, 0.00)), '.', ',')|| --VL_IPI
          '|'||MAX(COALESCE(OBS_ITEM.BDCODEXP, COALESCE(OBS_C190.BDCODEXP,COALESCE(OBS_C195.BDCODEXP,''))))|| --COD_OBS
          '|',
          MAX(COALESCE(OBS_ITEM.BDCODOBS, COALESCE(OBS_C190.BDCODOBS,OBS_C195.BDCODOBS)))
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE, I.BDORDEM, ENT.BDCODSITNF, I.BDCODNAT, ENT.BDREFLAN, I.BDCODOBS
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODSITNF, MOV.BDREFLAN
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODSITNF, M.BDREFLAN
                    FROM VEF_EMP_TMOVENT M
                    LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                    AND ((M.BDMODELO IN (55)) AND (M.BDEMITENTE = 0) OR (M.BDCODSITNF = 6) OR ((M.BDCODSITNF = 8) AND (M.BDMODELO = 1))) /*Sol. 20290 Gabriel Ariel (13/11/2017) - Agora exporta o C190 caso possua modelo 1 e siuação 8*/
                    AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                    AND (M.BDMODELO IN (1, 4, 55, 100) OR (:WSEGREGACAO = 'TRUE'))
                   ) MOV
             ) ENT
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
        WHERE ((NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (ENT.BDCODSITNF = 6)*/)
       ) MOV
  JOIN VEF_EMP_TC190ENT C190 ON(C190.BDCODEMP = MOV.BDCODEMP AND C190.BDCHAVE = MOV.BDCHAVE AND C190.BDORDEM = MOV.BDORDEM)
  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = C190.BDCODCSTICMS)                                    
  LEFT OUTER JOIN ( SELECT C.BDCODEMP, C.BDCHAVE, MAX(c.BDCODOBS) BDCODOBS
                    FROM VEF_EMP_TC195ENT C
                    GROUP BY C.BDCODEMP, C.BDCHAVE ) C195 ON (C195.BDCODEMP = C190.BDCODEMP AND C195.BDCHAVE = C190.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TOBSERVACAO OBS_ITEM ON(OBS_ITEM.BDCODOBS = MOV.BDCODOBS)
  LEFT OUTER JOIN VEF_BASE_TOBSERVACAO OBS_C190 ON(OBS_C190.BDCODOBS = C190.BDCODOBS)
  LEFT OUTER JOIN VEF_BASE_TOBSERVACAO OBS_C195 ON(OBS_C195.BDCODOBS = C195.BDCODOBS)
  GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODNAT, C190.BDALIQICMS, ICMS.BDCSTICMS;

  /*Monta o C191 a partir do movimento de produto*/
  SETORDEMSEQUENCIAL_STR(:PRCODEMP);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID,
        LPAD(C190.BDCODEMP, 6, '0')||'.0.'||LPAD(C190.BDCHAVE, 10, '0')||'.C100.C190.'||C190.BDPREFIXONAT ||'.'||REPLACE(CAST(C190.BDALIQICMS AS DM_NUMERIC_7_4_ALIQ), '.', '')||'.'||LPAD(COALESCE(C190.BDCSTICMS, ''), 3, ' ')||'.C191.' || LPAD(GETORDEMSEQUENCIAL_STR(C190.BDCHAVE,C190.BDCODEMP), 6, '0'),
          'C191' BDREG,
          '|C191'||
          '|'||REPLACE(IIF(:WFCPOP = 'TRUE', C190.BDVLRFCP, 0.00), '.', ',')||  --VL_FCP_OP
          '|'||REPLACE(C190.BDFCPRETIDO, '.', ',')||  --VL_FCP_ST
          '|'||REPLACE(C190.BDVLRFCPSTRET, '.', ',')|| --VL_FCP_RET
          '|'
  FROM (
        SELECT IIF(:wexp_vl_fcp_op,(SELECT BDRETORNO FROM SP_GET_FCP(0,MOV.BDVLRFCP,MOV.BDCSTICMS, MOV.BDPREFIXONAT)), 0) AS BDVLRFCP,
               (IIF(MOV.BDPREFIXONAT IN ('1410','1411','1414','1415','1660','1661','1662','2410','2411','2414','2415','2660','2661','2662'), (SELECT BDRETORNO FROM SP_GET_FCP(1,MOV.BDFCPRETIDO, MOV.BDCSTICMS, MOV.BDPREFIXONAT)), 0.00)) BDFCPRETIDO,
               (IIF(MOV.BDPREFIXONAT IN ('1410','1411','1414','1415','1660','1661','1662','2410','2411','2414','2415','2660','2661','2662'), (SELECT BDRETORNO FROM SP_GET_FCP(2,MOV.BDVLRFCPSTRET,MOV.BDCSTICMS, /*C190.BDCODNAT*/MOV.BDPREFIXONAT)), 0.00)) BDVLRFCPSTRET,
               MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCSTICMS, MOV.BDPREFIXONAT, MOV.BDALIQICMS
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE, ICMS.BDCSTICMS, /*MOV.BDCODNAT,*/ MOV.BDFCPRETIDO, MOV.BDPREFIXONAT, MOV.BDALIQICMS, MOV.BDVLRFCP, MOV.BDVLRFCPSTRET
              FROM (
                    SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                           COALESCE(PRO.BDCODCSTICMS, 0) BDCODCSTICMS,
                           --COALESCE(MOV.BDCODNAT, 0) BDCODNAT, Alt.: #95951 - Ajustado para levar pelo prefixo da CFOP, que é oq leva na exportação...
                           SUM(COALESCE(PRO.BDFCPRETIDO,0)) BDFCPRETIDO,
                           SUM(COALESCE(PRO.BDVLRFCP,0.00)) BDVLRFCP,
                           SUM(COALESCE(PRO.BDVLRFCPSTRET,0.00)) BDVLRFCPSTRET,
                           COALESCE(mov.bdPREFIXONAT, 0) BDPREFIXONAT,
                           CAST(COALESCE(PRO.BDALIQICMS, 0) AS NUMERIC(6, 2)) BDALIQICMS
                    FROM (
                          SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM,I.BDCODNAT, COALESCE(i.BDPREFIXONAT, SUBSTRING(i.bdCODNAT FROM 1 FOR 4)) AS BDPREFIXONAT
                          FROM VEF_EMP_TMOVENT M
                          LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                          JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                          WHERE M.BDCODEMP = :PRCODEMP
                          AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                          AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                          AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)  
                          AND ((M.BDMODELO IN (55))) /*OR (M.BDMODELO IN(65) AND M.BDREFLAN >= 202001)*/--Vilson Daniel #124941--(1, 4, 55, 65, 100) Alt.: #96043 - Apenas modelo 55...
                          AND M.BDREFLAN >= 201901              /* nao vai mais exportar nota modelo 65 na entrada - #174975 - Luiz Roepcke - 24/05/2023 */  
                          AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM AND (P.BDFCPRETIDO > 0 or P.BDVLRFCP > 0 or P.BDVLRFCPSTRET > 0))) /*OR (M.BDCODSITNF = 6)*/)
                         ) MOV
                    JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
                    GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, PRO.BDCODCSTICMS, /*MOV.BDCODNAT,*/  CAST(COALESCE(PRO.BDALIQICMS, 0) AS NUMERIC(6, 2)), MOV.BDPREFIXONAT
                   ) MOV
              LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = MOV.BDCODCSTICMS)
              WHERE MOV.BDFCPRETIDO > 0 OR MOV.BDVLRFCP > 0 or MOV.BDVLRFCPSTRET > 0
              ) MOV
       ) C190
       WHERE C190.BDVLRFCP > 0 or C190.BDFCPRETIDO > 0 or C190.BDVLRFCPSTRET > 0;
       /*IIF(ENT.BDREFLAN >= 201901, IIF(SUBSTRING(CAST(I.BDCODNAT AS VARCHAR(10)) FROM 1 FOR 4) IN ('1410','1411','1414','1415','1660','1661','1662','2410',
                                                                                                                    '2411','2414','2415','2660','2661','2662'),COALESCE(PRO.BDFCPRETIDO,0.00) ,0.00),0.00)    -- Na entrada só soma quando for CFOP de anulação*/
  /*Monta o C191 a partir da tabela do C190*/
  SETORDEMSEQUENCIAL_STR(:PRCODEMP);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID,
         LPAD(Filtro.BDCODEMP, 6, '0')||'.0.'||LPAD(Filtro.BDCHAVE, 10, '0')||'.C100.C190.'|| SUBSTRING(Filtro.bdCODNAT FROM 1 FOR 4)|| '.' || REPLACE(CAST(Filtro.BDALIQICMS AS DM_NUMERIC_7_4_ALIQ), '.', '')||'.'|| LPAD(COALESCE(Filtro.BDCSTICMS, ''), 3, ' ') || '.C191.' || LPAD(GETORDEMSEQUENCIAL_STR(Filtro.BDCHAVE,Filtro.BDCODEMP), 6, '0'),
          'C191' BDREG,
          '|C191'||
          '|'||REPLACE(Filtro.VL_FCP_OP, '.', ',')|| --VL_FCP_OP
          '|'||REPLACE(Filtro.VL_FCP_ST, '.', ',')|| --VL_FCP_ST
          '|'||REPLACE(Filtro.VL_FCP_RET, '.', ',')|| --VL_FCP_RET
          '|'
  FROM (
         SELECT  MOV.BDCODEMP, MOV.BDCHAVE, MOV.bdCODNAT, C190.BDALIQICMS, ICMS.BDCSTICMS,
                 IIF(:wexp_vl_fcp_op, (SELECT BDRETORNO FROM SP_GET_FCP(0,SUM(COALESCE(C190.BDFCPRETIDO,0.00)),ICMS.BDCSTICMS, MOV.BDCODNAT)), 0) AS VL_FCP_OP,
                 (SELECT BDRETORNO FROM SP_GET_FCP(1,SUM(COALESCE(C190.BDFCPRETIDO,0.00)),ICMS.BDCSTICMS, MOV.BDCODNAT)) AS VL_FCP_ST,
                 (SELECT BDRETORNO FROM SP_GET_FCP(2,SUM(COALESCE(C190.BDFCPRETIDO,0.00)),ICMS.BDCSTICMS, MOV.BDCODNAT)) AS VL_FCP_RET
         FROM (
                SELECT ENT.BDCODEMP, ENT.BDCHAVE, I.BDORDEM, ENT.BDCODSITNF, I.BDCODNAT
                FROM (
                       SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODSITNF
                       FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODSITNF
                              FROM VEF_EMP_TMOVENT M
                                 LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                              WHERE M.BDCODEMP = :PRCODEMP
                                 AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                                 AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                                 AND ((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) OR (M.BDCODSITNF = 6) OR ((M.BDCODSITNF = 8) AND (M.BDMODELO = 1))) /*Sol. 20290 Gabriel Ariel (13/11/2017) - Agora exporta o C190 caso possua modelo 1 e siuação 8*/
                                 AND M.BDREFLAN >= 201901
                                 AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                                 AND ((M.BDMODELO IN (55))) /* OR (M.BDMODELO IN(65) AND M.BDREFLAN >= 202001)*/--Vilson Daniel #124941--(1, 4, 55, 65, 100) Alt.: #96043 - Apenas modelo 55...
                            ) MOV                                    /* nao vai mais exportar nota modelo 65 na entrada - #174975 - Luiz Roepcke - 24/05/2023 */
                     ) ENT
                JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
                --elizeu - 20-03-19 - retirado a nf complementar - Exportação Sped Fiscal - NFe Complementar #98405
                WHERE ((NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (ENT.BDCODSITNF = 6)*/)
              ) MOV
         JOIN VEF_EMP_TC190ENT C190 ON(C190.BDCODEMP = MOV.BDCODEMP AND C190.BDCHAVE = MOV.BDCHAVE AND C190.BDORDEM = MOV.BDORDEM)
         LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = C190.BDCODCSTICMS)
         GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODNAT, C190.BDALIQICMS, ICMS.BDCSTICMS
       ) Filtro;
  --WHERE Filtro.VL_FCP_OP > 0 or Filtro.VL_FCP_ST > 0 or Filtro.VL_FCP_RET > 0;


  /*****************************************************************************
   *                                   C195                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.0.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C195.'||LPAD(C195.BDORDEMOBS, 6, '0'),
         'C195' BDREG,
         '|C195'||
         '|'||COALESCE(OBS.BDCODEXP, '')|| --COD_OBS
         '|'||TRIM(COALESCE(REPLACE(C195.BDDESCCOMPL, '|', ''), ''))|| --TXT_COMPL
         '|',
          C195.BDCODOBS
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE
        FROM VEF_EMP_TMOVENT ENT
        LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = ENT.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
        WHERE ENT.BDCODEMP = :PRCODEMP
        AND ENT.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, ENT.BDCHAVE)
        AND ENT.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND ENT.BDMODELO IN (1, 4, 55, /*65,*/ 100) /* nao vai mais exportar nota modelo 65 na entrada - #174975 - Luiz Roepcke - 24/05/2023 */
        AND ENT.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
       ) MOV
  JOIN VEF_EMP_TC195ENT C195 ON(C195.BDCODEMP = MOV.BDCODEMP AND C195.BDCHAVE = MOV.BDCHAVE AND (C195.BDTIPOOPERACAO = 'C195' OR C195.BDTIPOOPERACAO IS NULL))
  JOIN VEF_BASE_TOBSERVACAO OBS ON(OBS.BDCODOBS = C195.BDCODOBS);
  /*****************************************************************************
   *                                   C197                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD)
  SELECT :PRARQUIVO BDID,
       lpad(MOV.BDCODEMP, 6, '0') || '.0.' || lpad(MOV.BDCHAVE, 10, '0') || '.C100.C195.' || lpad(MOV.BDORDEMOBS, 6, '0') || '.C197.' || lpad(MOV.BDORDEMOUTOBR, 6, '0'),
       'C197' BDREG, '|C197' || '|' || coalesce(AJU.BDCODAJUPAD, '') || --COD_AJ
       '|' || trim(coalesce(replace(MOV.BDDESCCOMPL, '|', ''), '')) || --DESCR_COMPL_AJ
       '|' || coalesce(iif(((VINC.BDCODSAIDA is null) or (VINC.BDCODSAIDA = '')), VINC.BDCODPROD, VINC.BDCODSAIDA), '') || --COD_ITEM
       '|' || replace(coalesce(MOV.BDBICMS, 0.00), '.', ',') || --VL_BC_ICMS
       '|' || replace(cast(coalesce(MOV.BDALIQICMS, 0.00) as DM_NUMERIC_15_2), '.', ',') || --ALIQ_ICMS
       '|' || replace(coalesce(MOV.BDVLRICMS, 0.00), '.', ',') || --VL_ICMS
       '|' || replace(coalesce(MOV.BDOUTVLR, 0.00), '.', ',') || --VL_OUTROS
       '|', MOV.BDCODPROD
 from (
      select ENT.BDCODEMP, ENT.BDCHAVE, C197.BDCODPROD, C197.BDCODAJU, C197.BDORDEMOBS,
      MIN(C197.BDORDEMOUTOBR) BDORDEMOUTOBR,
      MAX(C197.BDDESCCOMPL) BDDESCCOMPL,
      MAX(C197.BDALIQICMS) BDALIQICMS, --MIN/MAX para Evitar SubSelect

      sum(C197.BDBICMS) BDBICMS,
      sum(C197.BDVLRICMS) BDVLRICMS,
      sum(C197.BDOUTVLR) BDOUTVLR

      from VEF_EMP_TMOVENT ENT
      LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = ENT.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
      join VEF_EMP_TC195ENT C195 on (C195.BDCODEMP = ENT.BDCODEMP and
            C195.BDCHAVE = ENT.BDCHAVE and
            C195.BDCODOBS is not null AND (C195.BDTIPOOPERACAO = 'C195' OR C195.BDTIPOOPERACAO IS NULL) )
      join VEF_EMP_TC197ENT C197 on (C197.BDCODEMP = C195.BDCODEMP and
            C197.BDCHAVE = C195.BDCHAVE and
            C197.BDORDEMOBS = C195.BDORDEMOBS)
      where ENT.BDCODEMP = :PRCODEMP and
            ENT.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, ENT.BDCHAVE) AND
            ENT.BDDATAENTRADAENT between :PRDTINI and :PRDTFIM and
            ENT.BDMODELO in (1, 4, 55, /*65,*/ 100) and /* nao vai mais exportar nota modelo 65 na entrada - #174975 - Luiz Roepcke - 24/05/2023 */
            ENT.BDCODSITNF not in (2, 3, 4, 5, 10, 11)
      group by ENT.BDCODEMP, ENT.BDCHAVE, C197.BDCODPROD, C197.BDCODAJU, C197.BDORDEMOBS
 ) MOV
 left outer join VEF_BASE_TTABCODAJU AJU on (AJU.BDCODAJU = MOV.BDCODAJU)
 left outer join TCADPRO_VINC VINC on (VINC.BDCODEMP = MOV.BDCODEMP and VINC.BDCODPROD = MOV.BDCODPROD);
 
END^


CREATE OR ALTER procedure SP_EXPORTA_BLOCOC_ENT (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRTIPOEXPCODPART integer,
    PRPERFIL integer,
    PRCODPLAPADRAOREF integer,
    PRSESSAOSEGREG integer,
    PREXPORTARC170EMISSAOPROPRIA varchar(5),
    PRICMSMONO varchar(5))
as
declare variable WSEGREGACAO varchar(5);
declare variable WFCPOP varchar(5);
declare variable WSOMASTPROD varchar(5);
declare variable WSOMAIPIPROD varchar(5);
declare variable WCHAVEMIN integer;
declare variable WCHAVEMAX integer;
declare variable WNAOEXP173 DM_BOOLEAN;
declare variable WEXPINCENTFISCAIS varchar(5);
BEGIN
   EXECUTE PROCEDURE SP_SETA_COMPETENCIA(CAST((EXTRACT(YEAR FROM :PRDTINI) || LPAD(EXTRACT(MONTH FROM :PRDTINI),2,'0')) AS INTEGER));

   SELECT UF.BDFCPOP FROM VW_TEMPRESAS_REF EMPR
   LEFT OUTER JOIN TCIDADE CID ON (CID.bdcodcid = EMPR.BDCODCID)
   LEFT OUTER JOIN TUF UF ON (CID.BDCODUF = UF.BDCODUF)
   WHERE :PRCODEMP = EMPR.BDCODEMP
   INTO :WFCPOP; --Alt.: FCP_OP - PEGA O PARÂMETRO FCPOP DA UF, PARA SABER SE DEVE SOMAR O FCP JUNTO AO ICMS.

  WSOMAIPIPROD = 'FALSE';
  WSOMASTPROD = 'FALSE';
  
  -- ALt.: "Alteracoes para o Sped do Rio Grande do Sul" - Quando tiver o parametro termo marcado, nao deve exportar as notas do modelo 65...
  SELECT FIRST 1 BDEXPINCENTFISCAIS
  FROM VEF_INT_TSPEDICMS
  WHERE bdCODEMP = :prCODEMP
    AND bdREFERENCIA <= EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0')
  ORDER BY bdREFERENCIA DESC        
  INTO :wEXPINCENTFISCAIS;

  SELECT FIRST 1 COALESCE(P.BDSOMAIPIPROD, 'FALSE'), COALESCE(P.BDSOMASTPROD,'FALSE')
  FROM VW_VEF_BASE_TEMPPARINTEG P 
  WHERE P.BDCODEMP = :PRCODEMP
  INTO :WSOMAIPIPROD, :WSOMASTPROD;

  SELECT Coalesce(rdb$get_context('USER_SESSION', 'W_SEGREGACAO_FISCAL'),'FALSE') FROM rdb$database INTO WSEGREGACAO;
--  insert into teste (STRING) values (coalesce(:wsegregacao,'NULO'));
  /***********************************************
   *----------------->>ENTRADA<<-----------------*
   **********************************************/
                 
  /***********************************************
   *                    C100                     *
   ***********************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
  SELECT  :PRARQUIVO BDID,
          LPAD(ENT.BDCODEMP, 6, '0')||'.0.'||LPAD(ENT.BDCHAVE, 10, '0')||'.C100',
          'C100' BDREG,
          ('|C100|0|'||IIF(:WSEGREGACAO = 'TRUE' AND MOD.BDMODELOSTR = '59', 0, M.BDEMITENTE)||         --IND_EMIT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65 AND :WSEGREGACAO = 'FALSE', '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, M.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))))|| --COD_PART
           '|'||MOD.BDMODELOSTR||             --COD_MOD
           '|'||LPAD(M.BDCODSITNF, 2, '0')||  --COD_SIT
           '|'||COALESCE(M.BDSERIE, '')||     --SER
           '|'||M.BDNUMDOCINI||               --NUM_DOC
           '|'||COALESCE(IIF(M.BDMODELO IN (55, 65) OR (:WSEGREGACAO = 'TRUE'), IIF(M.BDCODSITNF IN (5), '',(RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)), 44, ' '))), NULL), '')|| --CHV_NFE
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))||    --DT_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(IIF(M.BDCODSITNF IN(1, 3, 7), M.BDDATAEMISSAO, M.BDDATAENTRADAENT), 'DDMMYYYY')))|| --DT_E_S
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(ENT.BDVLRCONTAB, '.', ','))|| --VL_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(((M.BDCONDPGTO = '2') AND (M.BDDATAEMISSAO < '07/01/2012')), '9', M.BDCONDPGTO))||   --IND_PGTO
           --'|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(M.BDDESCONTONOTA, 0.00) - COALESCE(C100.BDVLRABATNT, 0.00), '.', ','))|| --VL_DESC
           '|'||CASE WHEN M.BDCODSITNF IN (2, 3, 4, 5) THEN '' --VL_DESC
                     WHEN (pro.bdVLRDESC + pro.bdVLRABATNT) = m.bdDESCONTONOTA THEN REPLACE(COALESCE(M.BDDESCONTONOTA, 0.00) - COALESCE(/*C100*/pro.bdVLRABATNT, 0.00), '.', ',') -- Alt.: #125909 #126894 #127057 #127296 #127440 #127528 #127589 #127562 #127779 #127586 - Se a soma do desconto + abatimento dos produtos for igual ao que possui no campo desconto da capa da nota, vai levar no campo "desconto" do C100 o desconto da capa da nota menos o abatimento...
                ELSE REPLACE(COALESCE(M.BDDESCONTONOTA, 0.00), '.', ',') END|| -- Alt.: #125909 #126894 #127057 #127296 #127440 #127528 #127589 #127562 #127779 #127586 - Se a soma do desconto + abatimento dos produtos for diferente do que possui no campo desconto da capa da nota, vai levar no campo "desconto" do C100 o desconto da capa da nota...
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRABATNT, 0.00), '.', ','))|| --VL_ABAT_NT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ','))||    --VL_MERC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', CASE WHEN M.BDMODELO = 65 THEN '9' WHEN (INDFRETEC100.BDCODEXPFRETE IS NULL) THEN '0' ELSE COALESCE(INDFRETEC100.BDCODEXPFRETE, '') END)|| --IND_FRT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRFRETE, 0.00), '.', ','))||  --VL_FRT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRSEGURO, 0.00), '.', ','))|| --VL_SEG
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLROUTDESP, 0.00), '.', ','))||--VL_OUT_DA
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(ENT.BDBASEICMS, 0.00), '.', ','))||   --VL_BC_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(ENT.BDVLRICMS, 0.00) + IIF(:WFCPOP = 'TRUE', COALESCE(ENT.BDVLRFCP, 0.00), 0.00), '.', ','))||    --VL_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(IIF(ENT.BDVLRST > 0, COALESCE(ENT.BDBASEST, 0.00), 0.00), '.', ',')))|| --VL_BC_ICMS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(ENT.BDVLRST, 0.00) + COALESCE(ENT.bdfcpretido,0.00), '.', ',')))||--VL_ICMS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(ENT.BDVLRIPI, 0.00), '.', ',')))||          --VL_IPI
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTPIS, 0.00), '.', ',')))||      --VL_PIS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTCOFINS, 0.00), '.', ',')))||   --VL_COFINS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTPISST, 0.00), '.', ',')))||    --VL_PIS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTCOFINSST, 0.00), '.', ',')))|| --VL_COFINS_ST
           '|') BDLINHA, IIF((((M.BDMODELO = 65) AND (:WSEGREGACAO = 'FALSE')) OR (M.BDCODSITNF IN (2, 3, 4, 5))), NULL, M.BDCODTER) BDCODTER
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE,
               SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB,
               SUM(COALESCE(I.BDDESCONTO, 0.00)) BDVLRDESCONTO,
               (SUM(COALESCE(I.BDBASEICMS, 0.00)) - COALESCE(MONO.BDICMSMONO, 0.00)) BDBASEICMS,
               SUM(COALESCE(I.BDVLRICMS, 0.00)) BDVLRICMS,
               SUM(COALESCE(I.BDBASEST, 0.0)) BDBASEST,
               SUM(COALESCE(I.BDVLRST, 0.00)) BDVLRST,
               SUM(COALESCE(I.BDVLRIPI, 0.00)) BDVLRIPI,
        SUM(COALESCE(I.BDVLRFCP, 0.00)) BDVLRFCP,
               --SUM(COALESCE(I.bdfcpretido, 0.00)) bdfcpretido,
               SUM(IIF(SUBSTRING(CAST(I.BDCODNAT AS VARCHAR(10)) FROM 1 FOR 4) IN
               ('1410','1411','1414','1415','1660','1661','1662','2410','2411','2414','2415','2660','2661','2662'),
               COALESCE(I.bdfcpretido, 0.00),0.00)) bdfcpretido    --#100919 #120308 Só deve somar o valor de FCPRetido quando for CFOP de Devolução, deve-se verificar todos os itens da nota
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
              AND (M.BDMODELO IN (1, 4, 55, 100) OR (:WSEGREGACAO = 'TRUE'))
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
              AND NOT (/*M.BDMODELO IN (55, 65) AND*/ M.BDCODSITNF IN (4, 5, 10, 11) AND M.BDREFLAN >= 202301) --#169202 - Adam - 09/11/2022 - Em 2023 os modelos 55 e 65 deixarão de usar as situações 4 e 5.
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        left outer join (
                   SELECT P.BDCODEMP, P.bdchave, coalesce(SUM(P.bdbcicms), 0.00) BDICMSMONO FROM VEF_EMP_TMOVPROENT P
                   LEFT OUTER JOIN VEF_BASE_TTABCSTICMS CST on (P.bdcodcsticms = CST.bdcodcsticms)
                   WHERE P.BDCODEMP = :PRCODEMP and
                   substring(CST.bdcsticms from 2 for 3) = '61'
                   GROUP BY P.BDCODEMP, P.BDCHAVE
                        ) MONO on (:PRICMSMONO = 'TRUE' and MONO.BDCODEMP = I.BDCODEMP and MONO.BDCHAVE = I.BDCHAVE)
        GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MONO.BDICMSMONO
       ) ENT
  JOIN VEF_EMP_TMOVENT M ON(M.BDCODEMP = ENT.BDCODEMP AND M.BDCHAVE = ENT.BDCHAVE)
  JOIN VEF_BASE_TTABMODELOLAN MOD ON(MOD.BDMODELO = M.BDMODELO)
  LEFT OUTER JOIN VEF_EMP_TC100ENT C100 ON(C100.BDCODEMP = ENT.BDCODEMP AND C100.BDCHAVE = ENT.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TTABINFRETE INDFRETEC100 ON (INDFRETEC100.BDORDEMFRETE = C100.BDINDFRETE)
  LEFT OUTER JOIN (
                   SELECT P.BDCODEMP, P.BDCHAVE, SUM(COALESCE(P.BDVLRITEM, 0)) BDVLRITEM, SUM(COALESCE(p.bdVLRDESC, 0)) AS bdVLRDESC, SUM(COALESCE(p.bdVLRABATNT, 0)) AS bdVLRABATNT
                   FROM VEF_EMP_TMOVPROENT P
                   WHERE P.BDCODEMP = :PRCODEMP
                   GROUP BY P.BDCODEMP, P.BDCHAVE
                  ) PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = M.BDCODTER)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = M.bdcodter);

  /*****************************************************************************
   *                                   C101                                    *
   ****************************************************************************/
  IF (:PRDTINI >= '01/01/2016') THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOV.BDCODEMP, 6, '0')||'.0.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C101.0000000001',
             'C101' BDREG,
             '|C101|'||REPLACE(COALESCE(C.BDVLR_FCP_UF_DEST, 0.00), '.', ',')||
             '|'||REPLACE(COALESCE(C.BDVLRICMS_UF_DEST, 0.00), '.', ',')||
             '|'||REPLACE(COALESCE(C.BDVLRICMS_UF_REM, 0.00), '.', ',')||'|'
      FROM (
            SELECT M.BDCODEMP, M.BDCHAVE
            FROM VEF_EMP_TMOVENT M
            LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
            WHERE M.BDCODEMP = :PRCODEMP
            AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
            AND M.BDMODELO = 55
            AND ((M.BDVALORNOTA > 0) OR
                 (M.BDCODSITNF = 6)) -- Alt.: #145436 - Quando o documento for complementar, vai exportar mesmo que esteja zerado...
            AND M.BDCODSITNF NOT IN(1, 7, 10, 11)
            AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
           ) MOV
      JOIN VEF_EMP_TC100ENT C ON(C.BDCODEMP = MOV.BDCODEMP AND C.BDCHAVE = MOV.BDCHAVE AND
                                 (((C.BDVLR_FCP_UF_DEST IS NOT NULL) AND (C.BDVLR_FCP_UF_DEST > 0)) OR
                                  ((C.BDVLRICMS_UF_DEST IS NOT NULL) AND (C.BDVLRICMS_UF_DEST > 0)) OR
                                  ((C.BDVLRICMS_UF_REM IS NOT NULL) AND (C.BDVLRICMS_UF_REM > 0))));
    END

  IF (:PRPERFIL NOT IN(2)) THEN
    BEGIN
      /*****************************************************************************
       *                                   C110                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODINFCOM, BDORDEMINFCOM)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.0.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0'),
             'C110' BDREG,
             '|C110|'||COALESCE(CADINF.BDCODINFCOM, '')||
             '|'||COALESCE(TRIM(REPLACE(SUBSTRING(MOVINF.BDDESCCOMPIC FROM 1 FOR 255), '|', '')), '')||'|',
             CADINF.BDCODINFCOM, CADINF.BDORDEMINFCOM
      FROM (
            SELECT INF.BDCODEMP, INF.BDCHAVE, INF.BDORDEMIC, INF.BDDESCCOMPIC, INF.BDORDEMINFCOM
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVENT M
                  LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                  AND (M.BDMODELO IN (1, 4, 55, 100) OR (:WSEGREGACAO = 'TRUE'))
                  AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND m.bdcodsitnf NOT IN (2,3,4,5, 10, 11)
                 ) MOV
            JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      LEFT OUTER JOIN VEF_BASE_TCADINFCOM CADINF ON(CADINF.BDORDEMINFCOM = MOVINF.BDORDEMINFCOM AND CADINF.BDCODEMP = MOVINF.BDCODEMP);

      /*****************************************************************************
       *                                   C111                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.0.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C111.'||LPAD(REF.BDORDEMPROREF, 6, '0'),
             'C111',
             '|C111|'||COALESCE(TRIM(SUBSTRING(REF.BDNUMPROC FROM 1 FOR 15)), '')||
             '|'||IIF(REF.BDINDPROCESSO = '4', '9', COALESCE(REF.BDINDPROCESSO, ''))||'|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVENT M
                  LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                  --AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND m.bdcodsitnf NOT IN (2,3,4,5, 10, 11)
                 ) MOV
            JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVENTPROREF REF ON(REF.BDCODEMP = MOVINF.BDCODEMP AND REF.BDCHAVE = MOVINF.BDCHAVE AND REF.BDORDEMIC = MOVINF.BDORDEMIC);
    
      /*****************************************************************************
       *                                   C112                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.0.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C112.'||LPAD(C112.BDORDEMDOCAREF, 6, '0'),
             'C112',
             '|C112'||
             '|'||COALESCE(C112.BDMODCODDA, 0)|| --COD_DA
             '|'||COALESCE(UF.BDSIGLAUF, '')||   --UF
             '|'||COALESCE(C112.BDNUMDA, '')||   --NUM_DA
             '|'||COALESCE(C112.BDCODAUT, '')||  --COD_AUT
             '|'||REPLACE(CAST(COALESCE(C112.BDVLRDA, 0.00) AS NUMERIC(15, 2)), '.', ',')|| --VL_DA
             '|'||(SELECT BDDATA FROM SP_PARSE_DATE(C112.BDDTVCTO, 'DDMMYYYY'))||        --DT_VCTO
             '|'||(SELECT BDDATA FROM SP_PARSE_DATE(C112.BDDTPGTO, 'DDMMYYYY'))||        --DT_PGTO
             '|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVENT M
                  LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND m.bdcodsitnf NOT IN (2,3,4,5, 10 ,11)
                 ) MOV
            JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVENTDOCAREF C112 ON(C112.BDCODEMP = MOVINF.BDCODEMP AND C112.BDCHAVE = MOVINF.BDCHAVE AND C112.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C112.BDCODUF);
    
      /*****************************************************************************
       *                                   C113                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.0.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C113.'||LPAD(C113.BDORDEMDOCFREF, 6, '0'),
             'C113',
             '|C113'||
             '|'||IIF(C113.BDINDOPER IS NULL, 0, C113.BDINDOPER)|| --IND_OPER
             '|'||COALESCE(C113.BDINDEMIT, 0)||   --IND_EMIT
             '|'||(SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, C113.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))|| --COD_PART
             '|'||COALESCE(DOCFIS.BDDOCFIS, '')|| --COD_MOD
             '|'||COALESCE(C113.BDSERIE, '')||    --SER
             '|'||COALESCE(C113.BDSUBSERIE, '')|| --SUB
             '|'||COALESCE(C113.BDNUMDOC, '')||   --NUM_DOC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C113.BDDTEMISSAO, 'DDMMYYYY')), '')|| --DT_DOC
             '|'||COALESCE(IIF(((DOCFIS.BDCODDOCFIS IN(30, 31, 34)) AND (:PRDTINI > '12/31/2016')), (RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)), 44, ' ')), NULL), '')|| --CHV_DOCe
             '|', C113.BDCODTER
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVENT M
                  LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                  --AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND m.bdcodsitnf NOT IN (2,3,4,5, 10, 11)
                 ) MOV
            JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVENTDOCFREF C113 ON(C113.BDCODEMP = MOVINF.BDCODEMP AND C113.BDCHAVE = MOVINF.BDCHAVE AND C113.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOCFIS ON(DOCFIS.BDCODDOCFIS = C113.BDCODDOCFIS)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER= C113.BDCODTER)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                            ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp ON (TerEmp.bdcodter = C113.bdcodter)
      WHERE /*(C113.BDSERIE > 0) AND */(C113.BDNUMDOC > 0)
      AND (C113.BDDTEMISSAO IS NOT NULL);                      
    
      /*****************************************************************************
       *                                   C114                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.0.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C114.'||LPAD(C114.BDORDEMCUPREF, 6, '0'),
             'C114',
             '|C114'||
             '|'||COALESCE(DOCFIS.BDDOCFIS, '')||   --COD_MOD
             '|'||COALESCE(C114.BDNRSERCAIXA, '')|| --ECF_FAB
             '|'||COALESCE(C114.BDNUMCAIXA, '')||   --ECF_CX
             '|'||COALESCE(C114.BDNUMDOC, '')||     --NUM_DOC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C114.BDDTDOC, 'DDMMYYYY')), '')||
             '|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVENT M
                  LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                  --AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND m.bdcodsitnf NOT IN (2,3,4,5, 10, 11)
                 ) MOV
            JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVENTCUPREF C114 ON(C114.BDCODEMP = MOVINF.BDCODEMP AND C114.BDCHAVE = MOVINF.BDCHAVE AND C114.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOCFIS ON(DOCFIS.BDCODDOCFIS = C114.BDCODDOCFIS);

      /*****************************************************************************
       *                                   C116                                    *
       ****************************************************************************/

      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :prarquivo BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.0.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C116.'||LPAD(C116.bdordemcupom, 6, '0'),
             'C116',
             '|C116'||
             '|'||COALESCE(C116.bdmodelo, '')||                                                  -- COD_MOD - Modelo
             '|'||COALESCE(C116.bdcodequipsat, '')||                                             -- NR_SAT  - Codigo do Equipamento
             '|'||COALESCE((RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C116.bdchavecfe)), 44, ' ')), NULL, '')|| -- Chave NF-e
             '|'||COALESCE(C116.bdnumcupom, '')||                                                -- NUM_CFE - N?mero do documento
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C116.bddatadoc, 'DDMMYYYY')), '')|| -- DT_DOC  - Data do documento
             '|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVENT M
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                 ) MOV
            JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVENTCUPOMREF C116 ON(C116.BDCODEMP = MOVINF.BDCODEMP AND C116.BDCHAVE = MOVINF.BDCHAVE AND C116.BDORDEMIC = MOVINF.BDORDEMIC);

      /*****************************************************************************
       *                                   C120                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOV.BDCODEMP, 6, '0')||'.0.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C120.'||LPAD(C120.BDORDEMOPIMP, 6, '0'),
             'C120',
             '|C120'||
             '|'||COALESCE(C120.BDCODDOCIMP, '')|| --COD_DOC_IMP
                iif(:PRDTINI >= DATE '01/01/2022',
                   '|'||COALESCE(c120.bdnumdocimp,''),
                   '|'||COALESCE(substring(c120.bdnumdocimp from 1 for 12),''))||
             '|'||REPLACE(IIF(COALESCE(C120.BDVLRPAGOPIS   , 0.00) > 0, CAST(COALESCE(C120.BDVLRPAGOPIS   , 0.00) AS NUMERIC(15, 2)), ''), '.', ',')||    --PIS_IMP
             '|'||REPLACE(IIF(COALESCE(C120.BDVLRPAGOCOFINS, 0.00) > 0, CAST(COALESCE(C120.BDVLRPAGOCOFINS, 0.00) AS NUMERIC(15, 2)), ''), '.', ',')|| --COFINS_IMP
             '|'||COALESCE(C120.BDNUMDRAW, '')|| --NUM_ACDRAW
             '|'
      FROM (
            SELECT M.BDCODEMP, M.BDCHAVE
            FROM VEF_EMP_TMOVENT M
            LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
            WHERE M.BDCODEMP = :PRCODEMP
            AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
            AND (M.BDMODELO IN (1, 4, 55, 100) or (:WSEGREGACAO = 'TRUE'))
            AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
            AND m.bdcodsitnf NOT IN (2,3,4,5, 10, 11)
           ) MOV
      JOIN VEF_EMP_TMOVENTOPIMP C120 ON(C120.BDCODEMP = MOV.BDCODEMP AND C120.BDCHAVE = MOV.BDCHAVE);

      /*****************************************************************************
       *                                   C140                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PAR.BDCODEMP, 6, '0')||'.0.'||LPAD(PAR.BDCHAVE, 10, '0')||'.C100.C140.'||LPAD(PAR.BDORDEMPAR, 6, '0'),
             'C140',
             '|C140'||
             '|'||COALESCE(MOV.BDEMITENTE, '')|| --IND_EMIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN '00'
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN '01'
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN '02'
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN '03'
                       ELSE '99'
                  END|| --IND_TIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN ''
                       ELSE COALESCE(PAR.BDOUTROSPAR, '')
                  END|| --DESC_TIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN PAR.BDDUPLICATAPAR
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN PAR.BDCHEQUEPAR
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN PAR.BDPROMISSPAR
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN PAR.BDOUTROSPAR
                       ELSE COALESCE(PAR.BDOUTROSPAR, MOV.BDNUMDOCINI)
                  END|| --NUM_TIT
             '|'||COALESCE(TOTPAR.BDQTDPAR, '')|| --QTD_PARC
             '|'||REPLACE(COALESCE(TOTPAR.BDVALORDUPLICATA, 0.00), '.', ',')|| --VL_TIT
             '|'
      FROM (
            SELECT ENT.BDCODEMP, ENT.BDCHAVE, ENT.BDEMITENTE,
                   ENT.BDVALORNOTA, ENT.BDNUMDOCINI
            FROM VEF_EMP_TMOVENT ENT
            LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = ENT.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
            WHERE ENT.BDCODEMP = :PRCODEMP
            AND ENT.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, ENT.BDCHAVE)
            AND ENT.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
            AND ENT.BDMODELO = 1 --somente modelo 1
            AND ent.bdcodsitnf NOT IN (2,3,4,5, 10, 11)
           ) MOV
      JOIN VEF_EMP_TMOVENTPAR PAR ON (PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE AND PAR.BDORDEMPAR = (SELECT MIN(P.BDORDEMPAR) FROM VEF_EMP_TMOVENTPAR P WHERE P.BDCODEMP = PAR.BDCODEMP AND P.BDCHAVE = PAR.BDCHAVE))
      LEFT OUTER JOIN (
                       SELECT P.BDCODEMP, P.BDCHAVE, COUNT(P.BDORDEMPAR) BDQTDPAR, SUM(COALESCE(P.BDVALORPAR, 0)) BDVALORDUPLICATA
                       FROM VEF_EMP_TMOVENTPAR P
                       GROUP BY P.BDCODEMP, P.BDCHAVE
                      ) TOTPAR ON(TOTPAR.BDCODEMP = PAR.BDCODEMP AND TOTPAR.BDCHAVE = PAR.BDCHAVE);

      /*****************************************************************************
       *                                   C141                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PAR.BDCODEMP, 6, '0')||'.0.'||LPAD(PAR.BDCHAVE, 10, '0')||'.C100.C140.C141.'||LPAD(PAR.BDORDEMPAR, 6, '0'),
             'C141',
             '|C141'||
             '|'||PAR.BDORDEMPAR|| --NUM_PARC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(PAR.BDDATAVENCTOPAR, 'DDMMYYYY')), '')|| --DT_VCTO
             '|'||REPLACE(COALESCE(PAR.BDVALORPAR, 0.00), '.', ',')|| --VL_PARC
             '|'
      FROM (
            SELECT ENT.BDCODEMP, ENT.BDCHAVE, ENT.BDEMITENTE,
                   ENT.BDVALORNOTA, ENT.BDNUMDOCINI
            FROM VEF_EMP_TMOVENT ENT
            LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = ENT.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
            WHERE ENT.BDCODEMP = :PRCODEMP
            AND ENT.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, ENT.BDCHAVE)
            AND ENT.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
            AND ENT.BDMODELO = 1 --somente modelo 1
            AND ent.bdcodsitnf NOT IN (2,3,4,5, 10, 11)
           ) MOV
      JOIN VEF_EMP_TMOVENTPAR PAR ON (PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE)
      ORDER BY PAR.BDORDEMPAR;

      SELECT MIN(t.bdCHAVE) AS bdCHAVEMIN, MAX(t.bdCHAVE) AS bdCHAVEMAX
      FROM VEF_EMP_TMOVENT t
      LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = T.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
      WHERE t.bdCODEMP = :PRCODEMP
      AND T.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, T.BDCHAVE)
        AND t.bdREFLAN BETWEEN EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0') AND EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0')
      INTO :wCHAVEMIN, :wCHAVEMAX;

      /*****************************************************************************
       *                                   C170                                    *
       ****************************************************************************/
      SETORDEMSEQUENCIAL_STR(:PRCODEMP);
    
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD, BDCODNAT, BDCODFATCON, BDCHAVE, BDCREDITO, BDANOCREDITO, BDCODPLAPADRAO, BDCREDITOREF, BDCREDITOPLAPADRAOREF, BDCTALON)
      SELECT :PRARQUIVO BDID,
             LPAD(ENT.BDCODEMP, 6, '0')||'.0.'||LPAD(ENT.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0'),
              'C170' BDREG,
              '|C170'||
              --'|'||PRO.BDORDEMPRO|| --NUM_ITEM
              --'|'||GETORDEMSEQUENCIAL_STR(PRO.BDCHAVE,PRO.BDCODEMP)|| --NUM_ITEM
     --#184470 - Exportação sped fiscal - ordenação dos produtos igual ao XML
              '|'||COALESCE(PRO.BDORDEMPROORIG, CAST(GETORDEMSEQUENCIAL_STR(PRO.BDCHAVE,PRO.BDCODEMP) AS INTEGER) +
                (SELECT COALESCE(MAX(PROENT.BDORDEMPROORIG),0) FROM VEF_EMP_TMOVPROENT AS PROENT WHERE PROENT.bdcodemp = ENT.BDCODEMP AND PROENT.BDCHAVE = ENT.BDCHAVE))|| --NUM_ITEM
              --#Alt:21967. Quando a empresa não possuía o respectivo produto vinculado o registro estava levando vazio. Quando isso acontecer foi
              --tratado para levar a informação do produto Único. Esse tratamento é feito para o código e a descrição.
              --'|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')), COALESCE(VINC.BDCODPROD,''), COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
              --'|'||TRIM(REPLACE(COALESCE(VINC.BDDESCPROD, ''), '|', ''))|| --DESCR_COMPL
              '|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')),
                       IIF(((VINC.BDCODPROD IS NULL) OR (COALESCE(VINC.BDCODPROD,'') = '')),COALESCE(PROD_UNICO.BDCODPROD,''),COALESCE(VINC.BDCODPROD,'')),
                       COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
              '|'||TRIM(REPLACE(IIF(((VINC.BDDESCPROD IS NULL) OR (VINC.BDDESCPROD = '')),
                                    COALESCE(PROD_UNICO.BDDESCRICAOUNICA,''),
                                    COALESCE(VINC.BDDESCPROD,'')), '|', ''))|| --DESCR_COMPL
              '|'||REPLACE(CAST(COALESCE(PRO.BDQTDITEM, 0.00) AS NUMERIC(15, 5)), '.', ',')|| --QTD
              '|'||COALESCE(IIF(((COALESCE(UN_FC.BDAPEUNIMED,UN.BDAPEUNIMED) IS NULL) OR (COALESCE(UN_FC.BDAPEUNIMED, UN.BDAPEUNIMED) = '')), UN_REF.BDAPEUNIMED, COALESCE(UN_FC.BDAPEUNIMED,UN.BDAPEUNIMED)), '')|| --UNID
              '|'||REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ',')|| --VL_ITEM
              '|'||REPLACE(COALESCE(PRO.BDVLRDESC, 0.00), '.', ',')|| --VL_DESC
              '|'||IIF((UPPER(PRO.BDMOVFISICO) = 'TRUE'), 0, 1)|| --IND_MOV
              '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
              '|'||COALESCE(SUBSTRING(I.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
              '|'||COALESCE(I.BDCODNAT, '')|| --COD_NAT
              '|'|| IIF(((substring(icms.bdcsticms from 2 for 3) = '61') and (:PRICMSMONO = 'TRUE')), '0,00',    iif(natop.bddevol = 'TRUE' and (substring(icms.bdcsticms from 2 for 3) = '02' or substring(icms.bdcsticms from 2 for 3) = '15' or substring(icms.bdcsticms from 2 for 3) = '53' or substring(icms.bdcsticms from 2 for 3) = '61'), '0,00', REPLACE(COALESCE(PRO.BDBCICMS, ''), '.', ',')))|| --VL_BC_ICMS
              '|'|| IIF(((substring(icms.bdcsticms from 2 for 3) = '61') and (:PRICMSMONO = 'TRUE')), '0,00',  iif(natop.bddevol = 'TRUE' and (substring(icms.bdcsticms from 2 for 3) = '02' or substring(icms.bdcsticms from 2 for 3) = '15'), REPLACE(CAST(COALESCE(PRO.bdaliqicmsmono, 0.00) AS DM_NUMERIC_15_2), '.', ','), REPLACE(CAST(COALESCE(PRO.BDALIQICMS, 0.00) AS DM_NUMERIC_15_2), '.', ',')))|| --ALIQ_ICMS
              --'|'||REPLACE(COALESCE(PRO.BDBCICMS, ''), '.', ',')|| --VL_BC_ICMS
              --'|'||REPLACE(CAST(COALESCE(PRO.BDALIQICMS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
              '|'||REPLACE(COALESCE(PRO.BDVLRICMS, 0.00) + IIF(:WFCPOP = 'TRUE', COALESCE(PRO.BDVLRFCP, 0.00), 0.00), '.', ',')|| --VL_ICMS
              '|'||iif(natop.bddevol = 'TRUE' and (substring(icms.bdcsticms from 2 for 3) = '02' or substring(icms.bdcsticms from 2 for 3) = '15' or substring(icms.bdcsticms from 2 for 3) = '53' or substring(icms.bdcsticms from 2 for 3) = '61'), '0,00', REPLACE(IIF(COALESCE(ENT.BDVLRST, 0) = 0, 0, COALESCE(PRO.BDBCST, 0.00)), '.', ','))||   --VL_BC_ICMS_ST
              '|'||iif(natop.bddevol = 'TRUE' and (substring(icms.bdcsticms from 2 for 3) = '02' or substring(icms.bdcsticms from 2 for 3) = '15' or substring(icms.bdcsticms from 2 for 3) = '53' or substring(icms.bdcsticms from 2 for 3) = '61'), iif(substring(icms.bdcsticms from 2 for 3) = '02' or substring(icms.bdcsticms from 2 for 3) = '61', '0,00', REPLACE(CAST(COALESCE(PRO.BDALIQICMSMONORET, 0.00) AS DM_NUMERIC_15_2), '.', ',')), REPLACE(IIF(COALESCE(ENT.BDVLRST, 0) = 0, 0, CAST(COALESCE(PRO.BDALIQST, 0.00) AS DM_NUMERIC_15_2)), '.', ','))|| --ALIQ_ST
              --'|'||REPLACE(IIF(COALESCE(ENT.BDVLRST, 0) = 0, 0, COALESCE(PRO.BDBCST, 0.00)), '.', ',')||   --VL_BC_ICMS_ST
              --'|'||REPLACE(IIF(COALESCE(ENT.BDVLRST, 0) = 0, 0, CAST(COALESCE(PRO.BDALIQST, 0.00) AS DM_NUMERIC_15_2)), '.', ',')|| --ALIQ_ST
              /*
              '|'||REPLACE(COALESCE(PRO.BDBCICMS, ''), '.', ',')|| --VL_BC_ICMS
              '|'||REPLACE(CAST(COALESCE(PRO.BDALIQICMS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
              '|'||REPLACE(COALESCE(PRO.BDVLRICMS, 0.00) + IIF(:WFCPOP = 'TRUE', COALESCE(PRO.BDVLRFCP, 0.00), 0.00), '.', ',')|| --VL_ICMS
              '|'||REPLACE(IIF(COALESCE(ENT.BDVLRST, 0) = 0, 0, COALESCE(PRO.BDBCST, 0.00)), '.', ',')||   --VL_BC_ICMS_ST
              '|'||REPLACE(IIF(COALESCE(ENT.BDVLRST, 0) = 0, 0, CAST(COALESCE(PRO.BDALIQST, 0.00) AS DM_NUMERIC_15_2)), '.', ',')|| --ALIQ_ST
              */
              '|'||REPLACE(IIF(COALESCE(ENT.BDVLRST, 0) = 0, 0, COALESCE(PRO.BDVLRST, 0.00)) + IIF(ENT.BDREFLAN >= 201901, IIF(SUBSTRING(CAST(I.BDCODNAT AS VARCHAR(10)) FROM 1 FOR 4) IN ('1410','1411','1414','1415','1660','1661','1662','2410',
                                                                                                                    '2411','2414','2415','2660','2661','2662'),COALESCE(PRO.BDFCPRETIDO,0.00) ,0.00),0.00)    -- Na entrada só soma quando for CFOP de anulação
                     /*COALESCE(IIF(ENT.BDREFLAN >= 201901,(SELECT BDRETORNO FROM SP_GET_FCP(1,PRO.BDFCPRETIDO,ICMS.BDCSTICMS, I.BDCODNAT)),0.00),0.00) + --Soma FCP_ST
                     COALESCE(IIF(ENT.BDREFLAN >= 201901,(SELECT BDRETORNO FROM SP_GET_FCP(2,PRO.BDFCPRETIDO,ICMS.BDCSTICMS, I.BDCODNAT)),0.00),0.00)   --Soma FCP_RET*/
                     , '.', ',')||  --VL_ICMS_ST
              '|'|| --IND_APUR
              '|'||IIF(IPI.BDCODCSTIPI IS NULL, '', LPAD(COALESCE(IPI.BDCODEXPCSTIPI, ''), 2, 0))|| --CST_IPI
              '|'|| --COD_ENQ
              '|'||REPLACE(COALESCE(PRO.BDBCIPI, 0.00), '.', ',')|| --VL_BC_IPI
              '|'||REPLACE(CAST(COALESCE(PRO.BDALIQIPI, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_IPI
              '|'||REPLACE(COALESCE(PRO.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
              '|'||COALESCE(PIS.BDCSTPIS, '')|| --CST_PIS
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE','',REPLACE(CAST(COALESCE(PRO.BDBCPIS, 0.00) AS DM_NUMERIC_15_2), '.', ','))|| --VL_BC_PIS
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE','',REPLACE(CAST(COALESCE(PRO.BDALIQPIS, 0.00) AS dm_numeric_7_4_aliq), '.', ','))|| --ALIQ_PIS
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(COALESCE(PRO.BDBCPIS, 0.000), '.', ','),'')|| --QUANT_BC_PIS
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(CAST(COALESCE(PRO.BDALIQPIS, 0.00) AS dm_numeric_7_4_aliq),'.', ',') ,'')|| --ALIQ_PIS(em reais)
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(CAST(COALESCE(PRO.BDBCPIS, 0.00) * COALESCE(PRO.BDALIQPIS, 0.00) AS DM_NUMERIC_15_2), '.', ','),REPLACE(COALESCE(PRO.BDVLRPIS, 0.00), '.', ','))|| --VL_PIS
              '|'||COALESCE(COF.BDCSTCOF, '')|| --CST_COFINS
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE','',REPLACE(CAST(COALESCE(PRO.BDBCCOFINS, 0.00) AS DM_NUMERIC_15_2), '.', ','))|| --VL_BC_COFINS
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE','',REPLACE(CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS dm_numeric_7_4_aliq), '.', ','))|| --ALIQ_COFINS
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE',REPLACE(COALESCE(PRO.BDBCCOFINS, 0.000), '.', ','),'')|| --QUANT_BC_COFINS
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE',REPLACE(CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS dm_numeric_7_4_aliq), '.', ',') ,'')|| --ALIQ_COFINS(em reais)
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE',REPLACE(CAST(COALESCE(PRO.BDBCCOFINS, 0.00) * CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS dm_numeric_7_4_aliq) AS DM_NUMERIC_15_2), '.', ','),REPLACE(COALESCE(PRO.BDVLRCOFINS, 0.00), '.', ','))|| --VL_COFINS
              --'|'||COALESCE(PRO.BDCODCTA, '')|| --COD_CTA
              '|'||COALESCE((CASE ConfSPED.bdTIPOEXPCONTA
                               WHEN '0' THEN COALESCE(CDL.BDCODTPLA, CDLRAT.BDCODTPLA)
                               WHEN '1' THEN COALESCE(CDL.BDCTALON, CDLRAT.BDCTALON)
                               WHEN '2' THEN COALESCE(CDL.BDAPECTA, CDLRAT.BDAPECTA)
                             ELSE COALESCE(CDLEP.bdCTALON,CDLEPRAT.bdCTALON) END), '')||
              IIF((:PRDTINI >= '01/01/2019'),'|'|| REPLACE(COALESCE(PRO.BDVLRABATNT, 0.00), '.', ','), '')|| --VL_ABAT_NT
              '|', PRO.BDCODPROD, I.BDCODNAT, PRO.BDCODFATCON,
              ENT.BDCHAVE, COALESCE(CDL.BDCODTPLA,CDLRAT.BDCODTPLA) BDCREDITO, COALESCE(COALESCE(CDLE.BDANO, CDLERAT.BDANO), CAST(SUBSTRING(ENT.BDREFLAN FROM 1 FOR 4) AS INTEGER)) BDANOCREDITO,
              COALESCE(PRO.BDCODPLAPADRAO, COALESCE(LAN.BDCODPLAPADRAO, LANRAT.BDCODPLAPADRAO)) BDCODPLAPADRAO, COALESCE(CDLEP.BDCODTPLAREF, CDLEPRAT.BDCODTPLAREF) BDCREDITOREF,
              COALESCE(CDLEP.BDCODPLAPADRAOREF, CDLEPRAT.BDCODPLAPADRAOREF) BDCREDITOPLAPADRAOREF, COALESCE(CDL.BDCTALON, CDLRAT.BDCTALON) BDCTALON
      FROM (
            SELECT ENT.BDCODEMP, ENT.BDCHAVE, SUM(COALESCE(I.BDVLRST, 0)) BDVLRST, ENT.BDREFLAN
            FROM (
                  SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN
                  FROM (
                        SELECT M.BDCODEMP, M.BDCHAVE, M.BDREFLAN
                        FROM VEF_EMP_TMOVENT M
                        LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                        LEFT OUTER JOIN VEF_EMP_TMOVPROENTC177 C177 ON (C177.bdCODEMP = M.bdCODEMP AND C177.bdCHAVE = M.bdCHAVE)
                        LEFT OUTER JOIN VEF_BASE_TTABINFAD56 AD56 ON (AD56.BDORDEM56 = C177.BDCODINFAD)
                        LEFT OUTER JOIN VEF_EMP_TMOVC180_1250  C180 ON (C180.bdCODEMP = m.bdCODEMP AND C180.bdCHAVE = m.bdCHAVE )
                        LEFT OUTER JOIN VEF_EMP_TMOVC181_1250  C181 ON (C181.bdCODEMP = m.bdCODEMP AND C181.bdCHAVE = m.bdCHAVE )
                        WHERE M.BDCODEMP = :PRCODEMP
                        AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                        AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                        AND (M.BDMODELO IN (1, 4, 55, 100) or (:WSEGREGACAO = 'TRUE'))
                         AND ((m.bdMODELO NOT IN (55, 65)) OR -- Alt.: #126126 - Caso a nota nao seja modelo 55 ou 65, exporta...
                              (M.BDEMITENTE = 1) OR -- Alt.: #126126 - Caso a nota seja emissao de terceiros, exporta...
                               (:WSEGREGACAO = 'TRUE') OR
                               (:PREXPORTARC170EMISSAOPROPRIA = 'TRUE') OR
                               (:PREXPORTARC170EMISSAOPROPRIA = 'TRUE') OR
                               (--(c176.bdCHAVE IS NOT NULL) OR
                               (COALESCE(C180.BDQTDCONVERTIDA, 0) > 0) OR  --Caso tenha C180 deve exportar Alt.: Instrução Normativa RE 87/20 ST RS
                               (COALESCE(C181.BDQTDCONVERTIDA, 0) > 0) OR  --Caso tenha C181 deve exportar Alt.: Instrução Normativa RE 87/20 ST RS
                                ((IIF((:wEXPINCENTFISCAIS IS NULL) OR (:wEXPINCENTFISCAIS <> 'TRUE'), c177.bdCHAVE, Coalesce(c177.bdCHAVE,1)) IS NOT NULL) AND
                                 (((M.BDREFLAN <= 201812) AND (C177.BDCODSELOIPI > 0)) OR /* Layout até 2018 */

                                  ((M.BDREFLAN >= 201901))))) ) /* Layout a partir de 2019 */
                        AND M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                       ) MOV
                 ) ENT
            JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
            GROUP BY ENT.BDCODEMP, ENT.BDCHAVE, ENT.BDREFLAN
           ) ENT
      JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
      join vef_base_tnatop natop on (i.bdcodnat = natop.bdcodnat)
      JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
      /*Produto*/
      LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
      LEFT OUTER JOIN TUNIDADEMEDIDA UN ON(UN.BDCODUNIMED = VINC.BDCODUNIMED)                           
      LEFT OUTER JOIN TFATCONV FC ON (FC.BDCODEMP = PRO.BDCODEMP AND FC.BDCODPROD = PRO.BDCODPROD AND FC.BDCODFATCON = PRO.BDCODFATCON)  
      LEFT OUTER JOIN TUNIDADEMEDIDA UN_FC ON(UN_FC.BDCODUNIMED = FC.BDCODUNIMED)
      LEFT OUTER JOIN TCADPRO PROD_UNICO ON(PROD_UNICO.BDCODPROD = PRO.BDCODPROD) --#Alt:21967.
      --LEFT OUTER JOIN TCADPRO_REF REF ON(REF.BDCODEMP = PRO.BDCODEMP AND REF.BDCODPROD = PRO.BDCODPROD AND ((UN.BDAPEUNIMED IS NULL) OR (UN.BDAPEUNIMED = '')))
      /*Produto por referência*/
      LEFT OUTER JOIN TCADPRO_VINC VINC_REF ON(VINC_REF.BDCODEMP = PRO.BDCODEMP AND VINC_REF.BDCODPROD = PRO.BDCODPROD)
      LEFT OUTER JOIN TUNIDADEMEDIDA UN_REF ON(UN_REF.BDCODUNIMED = VINC_REF.BDCODUNIMED)
      LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS)
      LEFT OUTER JOIN VEF_BASE_TTABCSTIPI IPI ON(IPI.BDCODCSTIPI = PRO.BDCODCSTIPI)
      LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON(PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
      LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON(COF.BDCODCSTCOF = PRO.BDCODCSTCOF)
      -- Alt.: #87095 #92148 #89325 #92407 #100955 #121349 - Ajustes para levar a conta referencial na exportação do lançamento
      LEFT OUTER JOIN VW_INT_SPEDICMS_REF ConfSPED ON (ConfSPED.bdCODEMP = ent.bdCODEMP)
      LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVEENT, t.bdORDEM, l.bdCODPLAPADRAO, MIN(l.bdDEBITO) bdDEBITO
                       FROM TOL_VEF_EMP_TMOVENT t
                       LEFT OUTER JOIN VSUC_EMPRESAS_TLAN l ON (l.bdCODEMP = t.bdCODEMPSUC AND l.bdCHAVE = t.bdCHAVE)
                       WHERE t.bdFORMULA LIKE '%NAT%LAN(%)' -- Alt.: #92219 - Apenas contas do valor contábil...
                         AND l.bdDEBITO IS NOT NULL -- Alt.: #120050 - Para apenas retornar quando a contabilização tiver uma conta informada, quando tem desconto a conta do desconto vem primeiro...
                         AND t.bdCODEMP = :PRCODEMP
                         AND t.bdCHAVEENT BETWEEN :wCHAVEMIN AND :wCHAVEMAX
                       GROUP BY t.bdCODEMP, t.bdCHAVEENT, t.bdORDEM, l.bdCODPLAPADRAO) LAN ON (lan.bdCODEMP = i.bdCODEMP AND lan.bdCHAVEENT = i.bdCHAVE AND lan.bdORDEM = i.bdORDEM)
      LEFT OUTER JOIN PLANOS_TPLA CDL ON (COALESCE(PRO.BDCODPLAPADRAO,LAN.BDCODPLAPADRAO) = CDL.BDCODPLAPADRAO AND COALESCE(PRO.BDCODTPLA,LAN.BDDEBITO) = CDL.BDCODTPLA)
      LEFT OUTER JOIN PLANOS_TPLA_ECF CDLE ON (CDLE.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF
                                           AND CDLE.BDANO = (SELECT FIRST 1 BDANO
                                                             FROM PLANOS_TPLA_ECF 
                                                             WHERE CAST(BDANO || '01' AS INTEGER) <= ENT.BDREFLAN
                                                               AND BDCODTPLAREF IS NOT NULL
                                                               AND CDLE.BDCODPLAPADRAO = BDCODPLAPADRAO
                                                               AND CDLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF
                                                               AND CDLE.BDCODTPLA = BDCODTPLA
                                                             ORDER BY BDANO DESC)
                                           AND CDLE.BDCODPLAPADRAO = CDL.BDCODPLAPADRAO AND CDLE.BDCODTPLA = CDL.BDCODTPLA)
      LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO CDLEP ON (CDLE.BDCODPLAPADRAOREF = CDLEP.BDCODPLAPADRAOREF AND CDLE.BDCODTPLAREF = CDLEP.BDCODTPLAREF) 
      LEFT OUTER JOIN  (SELECT BDCODEMP,BDCODEMPSUC,BDCHAVELAN,BDORDEM,MIN(BDCHAVE) BDCHAVE FROM TOL_VEF_EMP_TMOVRATENT GROUP BY BDCODEMP,BDCODEMPSUC,BDCHAVELAN,BDORDEM) TOLRAT
                        ON (TOLRAT.BDCODEMP = I.BDCODEMP AND TOLRAT.BDCHAVELAN = I.BDCHAVE AND TOLRAT.BDORDEM = I.BDORDEM) 
      LEFT OUTER JOIN VSUC_EMPRESAS_TLAN LANRAT ON (LANRAT.BDCODEMP = TOLRAT.BDCODEMPSUC AND LANRAT.BDCHAVE = TOLRAT.BDCHAVE) -- Alt.: #168897 - Deve buscar a contabilizacao nas empresas SCP...
      LEFT OUTER JOIN PLANOS_TPLA CDLRAT ON (COALESCE(PRO.BDCODPLAPADRAO,LANRAT.BDCODPLAPADRAO) = CDLRAT.BDCODPLAPADRAO AND COALESCE(PRO.BDCODTPLA,LANRAT.BDDEBITO) = CDLRAT.BDCODTPLA)
      LEFT OUTER JOIN PLANOS_TPLA_ECF CDLERAT ON (CDLERAT.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF
                                              AND CDLERAT.BDANO = (SELECT FIRST 1 BDANO
                                                                   FROM PLANOS_TPLA_ECF 
                                                                   WHERE CAST(BDANO || '01' AS INTEGER) <= LANRAT.BDREFERENCIA
                                                                     AND BDCODTPLAREF IS NOT NULL
                                                                     AND CDLERAT.BDCODPLAPADRAO = BDCODPLAPADRAO
                                                                     AND CDLERAT.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF
                                                                     AND CDLERAT.BDCODTPLA = BDCODTPLA
                                                                   ORDER BY BDANO DESC)
                                              AND CDLERAT.BDCODPLAPADRAO = CDLRAT.BDCODPLAPADRAO
                                              AND CDLERAT.BDCODTPLA = CDLRAT.BDCODTPLA)
      LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO CDLEPRAT ON (CDLERAT.BDCODPLAPADRAOREF = CDLEPRAT.BDCODPLAPADRAOREF AND CDLERAT.BDCODTPLAREF = CDLEPRAT.BDCODTPLAREF);
      -- Alt.: #87095 #92148 #89325 #92407 #100955 #121349 - Fim

      /*****************************************************************************
       *                                   C171                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
               LPAD(PRO.BDCODEMP, 6, '0')||'.0.'||LPAD(PRO.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C171.'||LPAD(C171.BDORDEMC171, 6, '0'),
                'C171' BDREG,
                '|C171'||
                '|'||COALESCE(C171.BDNUMTANQUE, '')|| --NUM_TANQUE
                '|'||COALESCE(REPLACE(C171.BDQTDEVOLUME, '.', ','), '')||--QTDE
                '|'
      FROM (
            SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO
            FROM (
                  SELECT ENT.BDCODEMP, ENT.BDCHAVE, I.BDORDEM
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM VEF_EMP_TMOVENT M
                              LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                              WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                              AND M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                              --Somente gerar C171 se possuir C171 - Mesma regra
                              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Próprio
                             ) MOV
                       ) ENT
                  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
                 ) ENT
            JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = ENT.BDORDEM)
           ) PRO
      JOIN VEF_EMP_TC171ENT C171 ON(C171.BDCODEMP = PRO.BDCODEMP AND C171.BDCHAVE = PRO.BDCHAVE AND C171.BDORDEM = PRO.BDORDEM AND C171.BDORDEMPRO = PRO.BDORDEMPRO);      
    
      /*****************************************************************************
       *                                   C173                                    *
       ****************************************************************************/
       SELECT VW.BDNAOEXPC173
       FROM VW_INT_SPEDICMS_REF VW
       WHERE VW.BDCODEMP = :PRCODEMP
       INTO :wNAOEXP173;
     
       IF (:wNAOEXP173 = 'FALSE') THEN
       BEGIN
           INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
           SELECT :PRARQUIVO BDID,
                    LPAD(PRO.BDCODEMP, 6, '0')||'.0.'||LPAD(PRO.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C173.'||LPAD(C173.BDORDEMOPMED, 6, '0'),
                     'C173' BDREG,
                     '|C173'||
                     '|'||COALESCE(C173.BDNRLOTE, '')|| --LOTE_MED
                     '|'||REPLACE(COALESCE(C173.BDQTDITEM, 0.00), '.', ',')|| --QTD_ITEM
                     '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C173.BDDTFABMED, 'DDMMYYYY')), '')|| --DT_FAB
                     '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C173.BDDTVALMED, 'DDMMYYYY')), '')|| --DT_VAL
                     '|'||COALESCE(C173.BDINDTIPOMED, '')|| --IND_MED
                     '|'||COALESCE(C173.BDTIPOMED, '')||    --TP_PROD
                     '|'||REPLACE(COALESCE(CAST(C173.BDVLRMAXMED AS DM_NUMERIC_15_2), 0.00), '.', ',')||   --VL_TAB_MAX
                     '|'
           FROM (
                 SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO
                 FROM (
                       SELECT ENT.BDCODEMP, ENT.BDCHAVE, I.BDORDEM
                       FROM (
                             SELECT MOV.BDCODEMP, MOV.BDCHAVE
                             FROM (
                                   SELECT M.BDCODEMP, M.BDCHAVE
                                   FROM VEF_EMP_TMOVENT M
                                   LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                                   WHERE M.BDCODEMP = :PRCODEMP
                                   AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                                   AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                                   AND M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                                   AND ((m.bdMODELO = 1) OR (m.bdEMITENTE <> 0)) -- Alt.: #98893 - Ajuste para não levar quando o emitente for "Próprio" ou leva quando for modelo 1...
                                   AND  (M.BDMODELO <> 65) /*#205462*/
                                  ) MOV
                            ) ENT
                       JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
                      ) ENT
                 JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = ENT.BDORDEM)
                ) PRO
           JOIN VEF_EMP_TOPMEDENT C173 ON(C173.BDCODEMP = PRO.BDCODEMP AND C173.BDCHAVE = PRO.BDCHAVE AND C173.BDORDEM = PRO.BDORDEM AND C173.BDORDEMPRO = PRO.BDORDEMPRO);
       END

      /*Camilla M. 04/09/2020 - Criado o registro C177 nas entradas - Registro C177 - entradas #140168 */
      /*****************************************************************************
       *                                   C177                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PRO.BDCODEMP, 6, '0')||'.0.'||LPAD(PRO.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C177.'||LPAD(Coalesce(C177.BDORDEM,1), 6, '0'),
             'C177' BDREG,
             '|C177'||
             IIF((PRO.BDREFLAN <= 201812),
                 ('|'||COALESCE(C177.BDCODSELOIPI, '')|| --COD_SELO_IPI
                  '|'||COALESCE(C177.BDQTDSELOIPI, '')), --QT_SELO_IPI
                 ('|'||COALESCE(AD56.BDCODINFAD56, ''))
                 )||
             '|'
      FROM (
            SELECT PRO.BDCODEMP, PRO.BDCHAVE, ENT.BDREFLAN, PRO.BDORDEM, PRO.BDORDEMPRO
            FROM (
                  SELECT ENT.BDCODEMP, ENT.BDCHAVE, ENT.BDREFLAN, I.BDORDEM
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE, M.BDREFLAN
                              FROM VEF_EMP_TMOVENT M
                              LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                              WHERE M.BDCODEMP = :PRCODEMP
                                AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                                AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                                AND M.BDMODELO IN (1, 4, 55, /*65,*/ 100) /* nao vai mais exportar nota modelo 65 na entrada - #174975 - Luiz Roepcke - 24/05/2023 */
                                AND M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                             ) MOV
                       ) ENT
                  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
                 ) ENT
            JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = ENT.BDORDEM)
           ) PRO
      LEFT OUTER JOIN VEF_EMP_TMOVPROENTC177 C177 ON(C177.BDCODEMP = PRO.BDCODEMP AND C177.BDCHAVE = PRO.BDCHAVE AND C177.BDORDEM = PRO.BDORDEM AND C177.BDORDEMPRO = PRO.BDORDEMPRO)
      JOIN VEF_BASE_TTABINFAD56 AD56 ON (AD56.BDORDEM56 = IIF((:wEXPINCENTFISCAIS IS NULL) OR (:wEXPINCENTFISCAIS <> 'TRUE'), C177.BDCODINFAD, Coalesce(C177.BDCODINFAD,1)))
      WHERE ((PRO.BDREFLAN <= 201812) AND (C177.BDCODSELOIPI > 0)) OR /* Layout até 2018 */
            ((PRO.BDREFLAN >= 201901));     /* Layout a partir de 2019 */
    END


  /*Camilla M. 11/08/2021 - PASSADO O C190 A PARTIR DO PRODUTO PRA OUTRA PROCEDURE*/
  /*PASSADO O C190 A PARTIR DA TABELA DO C190 PARA A OUTRA PROCEDURE*/


  -- SP Auxiliar pois essa estorou o limite...
  EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_ENT_AUX(:prCODEMP, :prDTINI, :prDTFIM, :prARQUIVO, :prTIPOEXPCODPART, :prPERFIL, :prCODPLAPADRAOREF, :WSOMAIPIPROD, :WSOMASTPROD, :PRSESSAOSEGREG, :PRICMSMONO);
END^



CREATE OR ALTER procedure SP_EXPORTA_BLOCOC_SAI_AUX (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRTIPOEXPCODPART integer,
    PRPERFIL integer,
    PRSESSAOSEGREG integer)
as
declare variable WSEGREGACAO varchar(5);
declare variable WFCPOP varchar(5);
declare variable WSOMAIPIPROD varchar(5);
declare variable WSOMASTPROD varchar(5);
declare variable WTERMOACORDO varchar(5);
declare variable WEXPINCENTFISCAIS varchar(5);
declare variable WEXP_VL_FCP_OP boolean;
declare variable WUF_EMPRESA varchar(2);
BEGIN
      EXECUTE PROCEDURE SP_SETA_COMPETENCIA(CAST((EXTRACT(YEAR FROM :PRDTINI) || LPAD(EXTRACT(MONTH FROM :PRDTINI),2,'0')) AS INTEGER));

      WSOMAIPIPROD = 'FALSE';
      WSOMASTPROD = 'FALSE';
  
  SELECT Coalesce(rdb$get_context('USER_SESSION', 'W_SEGREGACAO_FISCAL'),'FALSE') FROM rdb$database INTO WSEGREGACAO;

      SELECT FIRST 1 COALESCE(P.BDSOMAIPIPROD, 'FALSE'), COALESCE(P.BDSOMASTPROD,'FALSE')
      FROM VW_VEF_BASE_TEMPPARINTEG P
      WHERE P.BDCODEMP = :PRCODEMP
      INTO :WSOMAIPIPROD, :WSOMASTPROD;

      -- ALt.: "Alteracoes para o Sped do Rio Grande do Sul" - Quando tiver o parametro termo marcado, nao deve exportar as notas do modelo 65...
      SELECT FIRST 1 bdTERMOACORDO, BDEXPINCENTFISCAIS
      FROM VEF_INT_TSPEDICMS
      WHERE bdCODEMP = :prCODEMP
        AND bdREFERENCIA <= EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0')
      ORDER BY bdREFERENCIA DESC        
      INTO :wTERMOACORDO,:wEXPINCENTFISCAIS;

      IF (:prDTINI < '01-JUL-2020') THEN
        wTERMOACORDO = NULL; -- Alt.: "Alterações para o Sped do Rio Grande do Sul" - Apenas para empresas do RS, a partir de 07/2020...

      --Alt: 214074 - obtendo o estado da empresa
      SELECT UF.BDFCPOP, UF.BDSIGLAUF FROM VW_TEMPRESAS_REF EMPR
      LEFT OUTER JOIN TCIDADE CID ON (CID.bdcodcid = EMPR.BDCODCID)
      LEFT OUTER JOIN TUF UF ON (CID.BDCODUF = UF.BDCODUF)
      WHERE :PRCODEMP = EMPR.BDCODEMP
      INTO :WFCPOP, :WUF_EMPRESA; --Alt.: FCP_OP - PEGA O PARÂMETRO FCPOP DA UF, PARA SABER SE DEVE SOMAR O FCP JUNTO AO ICMS.

      --Alt: 217654 - Para exportar o valor do FCP normal se a empresa não for do RJ ou se a competência for inferior à 03/2025(revogado e alterado para 2099, caso retornar basta alterar aqui).
      :wexp_vl_fcp_op = (:wUF_EMPRESA <> 'RJ') or (EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0') < 209901);

      /*****************************************************************************
       *                                   C172                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT  :PRARQUIVO BDID,
             LPAD(SAI.BDCODEMP, 6, '0')||'.1.'||LPAD(SAI.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C172.0000000001',
              'C172' BDREG,
              '|C172'||
              '|'||REPLACE(COALESCE(PRO.BDBCISSQN, 0.00), '.', ',')|| --VL_BC_ISSQN
              '|'||REPLACE(COALESCE(CAST(PRO.BDALIQISSQN AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --ALIQ_ISSQN
              '|'||REPLACE(COALESCE(PRO.BDVLRISSQN, 0.00), '.', ',')|| --VL_ISSQN
              '|'
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, I.BDCODNAT
            FROM (
                  SELECT MOV.BDCODEMP, MOV.BDCHAVE
                  FROM (
                        SELECT M.BDCODEMP, M.BDCHAVE
                        FROM VEF_EMP_TMOVSAI M
                        LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                        WHERE M.BDCODEMP = :PRCODEMP
                        AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                        AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                        AND M.BDMODELO = 1
                        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Próprio
                        AND M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                        AND ((:wTERMOACORDO IS NULL) OR (:wTERMOACORDO <> 'TRUE') OR (M.BDMODELO <> 65))
                       ) MOV
                 ) SAI
            JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
            WHERE NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = SAI.BDCODEMP AND DF.BDCHAVESAI = SAI.BDCHAVE AND DF.BDORDEMSAI = I.BDORDEM))
           ) SAI
      JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM AND COALESCE(PRO.BDVLRISSQN, 0) > 0);
    
      /*****************************************************************************
       *                                   C173                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
               LPAD(PRO.BDCODEMP, 6, '0')||'.1.'||LPAD(PRO.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C173.'||LPAD(C173.BDORDEMOPMED, 6, '0'),
                'C173' BDREG,
                '|C173'||
                '|'||COALESCE(C173.BDNRLOTE, '')|| --LOTE_MED
                '|'||REPLACE(COALESCE(C173.BDQTDITEM, 0.00), '.', ',')|| --QTD_ITEM
                '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C173.BDDTFABMED, 'DDMMYYYY')), '')|| --DT_FAB
                '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C173.BDDTVALMED, 'DDMMYYYY')), '')|| --DT_VAL
                '|'||COALESCE(C173.BDINDTIPOMED, '')|| --IND_MED
                '|'||COALESCE(C173.BDTIPOMED, '')||    --TP_PROD
                '|'||REPLACE(COALESCE(CAST(C173.BDVLRMAXMED AS DM_NUMERIC_15_2), 0.00), '.', ',')||   --VL_TAB_MAX
                '|'
      FROM (
            SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO
            FROM (
                  SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM VEF_EMP_TMOVSAI M
                              LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                              WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Próprio
                              AND ((M.BDMODELO IN (1, 4, 100)) OR (M.BDEMITENTE <> 1))
                              AND M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                              AND ((:wTERMOACORDO IS NULL) OR (:wTERMOACORDO <> 'TRUE') OR (M.BDMODELO <> 65))
                             ) MOV
                       ) SAI
                  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                  WHERE NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = SAI.BDCODEMP AND DF.BDCHAVESAI = SAI.BDCHAVE AND DF.BDORDEMSAI = I.BDORDEM))
                 ) SAI
            JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
           ) PRO
      JOIN VEF_EMP_TOPMEDSAI C173 ON(C173.BDCODEMP = PRO.BDCODEMP AND C173.BDCHAVE = PRO.BDCHAVE AND C173.BDORDEM = PRO.BDORDEM AND C173.BDORDEMPRO = PRO.BDORDEMPRO);

      /*****************************************************************************
       *                                   C176                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODTERAUX)
      SELECT  :PRARQUIVO BDID,
             LPAD(SAI.BDCODEMP, 6, '0')||'.1.'||LPAD(SAI.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C176.'||LPAD(C176.BDORDEMC176, 6, '0'),
              'C176' BDREG,
              '|C176'||
              '|'||COALESCE(L.BDMODELOSTR, '')|| --COD_MOD_ULT_E
              '|'||COALESCE(C176.BDNUM_DOC_ULT_E, '')|| --NUM_DOC_ULT_E
              '|'||COALESCE(C176.BDSER_ULT_E, '')|| --SER_ULT_E
              '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C176.BDDT_ULT_E, 'DDMMYYYY')), '')|| --DT_ULT_E
              '|'||(SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, C176.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))|| --COD_PART_ULT_E
              '|'||REPLACE(COALESCE(C176.BDQUANT_ULT_E, 0.000), '.', ',')|| --QUANT_ULT_E
              '|'||REPLACE(COALESCE(C176.BDVL_UNIT_ULT_E, 0.000), '.', ',')|| --VL_UNIT_ULT_E
              '|'||REPLACE(COALESCE(C176.BDVL_UNIT_BC_ST, 0.000), '.', ',')|| --VL_UNIT_BC_ST
              '|'||COALESCE(IIF((sai.BDMODELO IN (1)) OR (C176.BDCHAVE_NFE_ULT_E IS NULL) OR (C176.BDCHAVE_NFE_ULT_E = '') OR ((SELECT bdRESULT FROM SONUMEROS((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C176.BDCHAVE_NFE_ULT_E)))) = '0'), -- Ajustes para não imprimir em branco...
                            '',(RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C176.BDCHAVE_NFE_ULT_E)), 44, ' '))), '')|| --CHAVE_NFE_ULT_E
--              '|'||COALESCE(RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C176.BDCHAVE_NFE_ULT_E)), 44, ' '), '')|| --CHAVE_NFE_ULT_E
              '|'||COALESCE(C176.BDNUM_ITEM_ULT_E, '')|| --VL_UNIT_BC_ST
              '|'||IIF(COALESCE(C176.BDVL_UNIT_BC_ICMS_ULT_E, 0) > 0, REPLACE(COALESCE(C176.BDVL_UNIT_BC_ICMS_ULT_E, 0.00), '.', ','), '')|| --VL_UNIT_BC_ICMS_ULT_E
              '|'||IIF(COALESCE(C176.BDALIQ_ICMS_ULT_E, 0) > 0, REPLACE(COALESCE(C176.BDALIQ_ICMS_ULT_E, 0.00), '.', ','), '')|| --ALIQ_ICMS_ULT_E
              '|'||IIF(COALESCE(C176.BDVL_UNIT_LIM_BC_ICMS_ULT_E, 0) > 0, REPLACE(COALESCE(C176.BDVL_UNIT_LIM_BC_ICMS_ULT_E, 0.00), '.', ','), '')|| --VL_UNIT_LIMITE_BC_ICMS_ULT_E
              '|'||IIF(COALESCE(C176.BDVL_UNIT_ICMS_ULT_E, 0) > 0, REPLACE(COALESCE(C176.BDVL_UNIT_ICMS_ULT_E, 0.000), '.', ','), '')|| --VL_UNIT_ICMS_ULT_E
              '|'||IIF(COALESCE(C176.BDALIQ_ST_ULT_E, 0) > 0, REPLACE(COALESCE(C176.BDALIQ_ST_ULT_E, 0.00), '.', ','), '')|| --ALIQ_ST_ULT_E
              '|'||IIF(COALESCE(C176.BDVL_UNIT_RES, 0) > 0, REPLACE(COALESCE(C176.BDVL_UNIT_RES, 0.000), '.', ','), '')|| --VL_UNIT_RES 
              '|'||COALESCE(IIF(C176.BDCOD_RESP_RET = -1, '', C176.BDCOD_RESP_RET + 1), '')|| --COD_RESP_RET
              '|'||COALESCE(M.BDCODEXPMOT, '')|| --COD_MOT_RES
              '|'||COALESCE(IIF((C176.BDCOD_RESP_RET+1 <> 2) OR -- Alt.: #151078 #152803 - Este campo somente poderá ser apresentado quando COD_RESP_RET=2.
                                (sai.BDMODELO IN (1)) OR (C176.BDCHAVE_NFE_RET IS NULL) OR (C176.BDCHAVE_NFE_RET = '') OR
                                ((SELECT bdRESULT FROM SONUMEROS((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C176.BDCHAVE_NFE_ULT_E)))) = '0'), -- Ajustes para não imprimir em branco...
                            '',(RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C176.BDCHAVE_NFE_RET)), 44, ' '))), '')|| --CHAVE_NFE_RET
--              '|'||COALESCE(RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C176.BDCHAVE_NFE_RET)), 44, ' '), '')|| --CHAVE_NFE_RET
              '|'||IIF(COALESCE(C176.BDCODTER_NFE, 0) > 0, (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, C176.BDCODTER_NFE, TER_NFE.BDCGCTER, TER_NFE.BDIETER, TerEmp_NFE.BDCODIGOARQUIVO)), '')|| --COD_PART_NFE_RET
              '|'||COALESCE(C176.BDSER_NFE_RET, '')||  --SER_NFE_RET
              '|'||COALESCE(C176.BDNUM_NFE_RET, '')||  --NUM_NFE_RET
              '|'||COALESCE(C176.BDITEM_NFE_RET, '')|| --ITEM_NFE_RET
              '|'||COALESCE(IIF(C176.BDCOD_DA = -1, '', C176.BDCOD_DA), '')|| --COD_DA
              '|'||COALESCE(C176.BDNUM_DA, '')|| --NUM_DA
              IIF((:PRDTINI >= '01/01/2019'),'|'||REPLACE(COALESCE(C176.bdvl_unit_res_fc, 0.000), '.', ','), '')|| --vl_unit_res_fc elizeu - 18-09-18 - Registro C176: inclusão do Campo 27 - Alterações Sped Fiscal 2019 #89669
              '|', C176.BDCODTER, C176.BDCODTER_NFE
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, I.BDCODNAT,sai.bdmodelo
            FROM (
                  SELECT MOV.BDCODEMP, MOV.BDCHAVE,mov.bdmodelo
                  FROM (
                        SELECT M.BDCODEMP, M.BDCHAVE,m.bdmodelo
                        FROM VEF_EMP_TMOVSAI M
                        LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                        WHERE M.BDCODEMP = :PRCODEMP
                        AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                        /*AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Próprio -- Al.: #126204 - Deve exportar independentemente do emitente... */
                        AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                        AND M.BDMODELO IN(1, 55)
                        AND M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                       ) MOV
                 ) SAI
            JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
            WHERE NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = SAI.BDCODEMP AND DF.BDCHAVESAI = SAI.BDCHAVE AND DF.BDORDEMSAI = I.BDORDEM))
           ) SAI
      JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
      JOIN VEF_EMP_TMOVSTC176 C176 ON(C176.BDCODEMP = PRO.BDCODEMP AND C176.BDCHAVE = PRO.BDCHAVE AND C176.BDORDEM = PRO.BDORDEM AND C176.BDORDEMPRO = PRO.BDORDEMPRO)
      LEFT OUTER JOIN VEF_BASE_TTABMOTRES M ON (M.BDORDEMMOTRES = C176.BDORDEMMOTRES)
      LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN L ON (L.BDMODELO = C176.BDMODELO)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = C176.BDCODTER)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                            ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp ON (TerEmp.bdcodter = C176.bdcodter)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER_NFE ON(TER_NFE.BDCODTER = C176.BDCODTER_NFE)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                            ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp_NFE ON (TerEmp_NFE.bdcodter = C176.BDCODTER_NFE);

      /*****************************************************************************
       *                                   C177                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PRO.BDCODEMP, 6, '0')||'.1.'||LPAD(PRO.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C177.0000000001',
             'C177' BDREG,
             '|C177'||
             IIF((PRO.BDREFLAN <= 201812),
                 ('|'||COALESCE(C177.BDCODSELOIPI, '')|| --COD_SELO_IPI
                  '|'||COALESCE(C177.BDQTDSELOIPI, '')), --QT_SELO_IPI
                 ('|'||COALESCE(AD56.BDCODINFAD56, ''))
                 )||
             '|'
      FROM (
            SELECT PRO.BDCODEMP, PRO.BDCHAVE, SAI.BDREFLAN, PRO.BDORDEM, PRO.BDORDEMPRO
            FROM (
                  SELECT SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDREFLAN, I.BDORDEM
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE, M.BDREFLAN
                              FROM VEF_EMP_TMOVSAI M
                              LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                              WHERE M.BDCODEMP = :PRCODEMP
                                AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                                AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                                AND (M.BDMODELO IN (1, 4, 55, 65, 100))
                                AND ( ((M.BDREFLAN <= 201812) /*AND (NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)))*/) OR --Próprio -- Al.: #126204 - Deve exportar independentemente do emitente...
                                      ((M.BDREFLAN >= 201901) AND (M.BDMODELO IN (55, 65))) OR /* A partir de 2019, leva independente do emitente */
                                      ((M.BDMODELO IN (1, 4, 100)) OR (M.BDEMITENTE <> 1)) )
                                AND M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                                AND ((:wTERMOACORDO IS NULL) OR (:wTERMOACORDO <> 'TRUE') OR (M.BDMODELO <> 65))
                             ) MOV
                       ) SAI
                  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                  WHERE NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = SAI.BDCODEMP AND DF.BDCHAVESAI = SAI.BDCHAVE AND DF.BDORDEMSAI = I.BDORDEM))
                 ) SAI
            JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
           ) PRO
      LEFT OUTER JOIN VEF_EMP_TMOVPROSAIC177 C177 ON(C177.BDCODEMP = PRO.BDCODEMP AND C177.BDCHAVE = PRO.BDCHAVE AND C177.BDORDEM = PRO.BDORDEM AND C177.BDORDEMPRO = PRO.BDORDEMPRO)
      JOIN VEF_BASE_TTABINFAD56 AD56 ON (AD56.BDORDEM56 = IIF((:wEXPINCENTFISCAIS IS NULL) OR (:wEXPINCENTFISCAIS <> 'TRUE'), C177.BDCODINFAD, COALESCE(C177.BDCODINFAD,1)))
      WHERE ((PRO.BDREFLAN <= 201812) AND (C177.BDCODSELOIPI > 0)) OR /* Layout até 2018 */
            ((PRO.BDREFLAN >= 201901));     /* Layout a partir de 2019 */

      /*****************************************************************************
       *                                   C178                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PRO.BDCODEMP, 6, '0')||'.1.'||LPAD(PRO.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.C178.0000000001',
             'C178' BDREG,
             '|C178'||
             '|'||COALESCE(CLIPI.BDCODCLASSEIPI, '')|| --CL_ENQ
             '|'||REPLACE(COALESCE(C178.BDVLRUNIDADE, 0.00), '.', ',')||  --VL_UNID
             '|'||REPLACE(COALESCE(CAST(C178.BDQTDUNIDADE AS DM_NUMERIC_18_3), 0.000), '.', ',')|| --QUANT_PAD
             '|'
      FROM (
            SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO
            FROM (
                  SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM VEF_EMP_TMOVSAI M
                              LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                              WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Próprio
                              AND ((M.BDMODELO IN (1, 4, 100)) OR (M.BDEMITENTE <> 1))
                              AND M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                              AND ((:wTERMOACORDO IS NULL) OR (:wTERMOACORDO <> 'TRUE') OR (M.BDMODELO <> 65))
                             ) MOV
                       ) SAI
                  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                  WHERE NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = SAI.BDCODEMP AND DF.BDCHAVESAI = SAI.BDCHAVE AND DF.BDORDEMSAI = I.BDORDEM))
                 ) SAI
            JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
           ) PRO
      JOIN VEF_EMP_TMOVPROSAIC178 C178 ON(C178.BDCODEMP = PRO.BDCODEMP AND C178.BDCHAVE = PRO.BDCHAVE AND C178.BDORDEM = PRO.BDORDEM AND C178.BDORDEMPRO = PRO.BDORDEMPRO)
      LEFT OUTER JOIN VEF_BASE_TTABCLASSEIPI CLIPI ON (CLIPI.BDORDEMCLAIPI = C178.BDORDEMCLAIPI)
      WHERE ((CLIPI.BDCODCLASSEIPI IS NOT NULL) AND (CLIPI.BDCODCLASSEIPI <> ''));
  
  /*****************************************************************************
   *                                   C190                                    *
   ****************************************************************************/
   /*PARA FAZER O SELECT, NO LUGAR DO GETORDEM(0) COLOCAR (GETORDEM(0)+1), CASO FOR FAZER INSERT SELECT NÃO COLOCAR O +1*/
  SETORDEMSEQUENCIAL_STR(:PRCODEMP);
  /*Monta o C190 a partir do movimento de produto*/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
  SELECT :PRARQUIVO BDID,
        LPAD(C190.BDCODEMP, 6, '0')||'.1.'||LPAD(C190.BDCHAVE, 10, '0')||'.C100.C190.'||C190.BDCODNAT||'.'||REPLACE(CAST(C190.BDALIQICMS AS DM_NUMERIC_7_4_ALIQ), '.', '')||'.'||LPAD(COALESCE(C190.BDCSTICMS, ''), 3, ' '),
        'C190' BDREG,
        '|C190'||
        '|'||COALESCE(C190.BDCSTICMS, '')|| --CST_ICMS
        '|'||COALESCE(C190.BDCODNAT, '')|| --CFOP
        '|'||REPLACE(CAST(COALESCE(C190.BDALIQICMS, 0) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
        --'|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, (COALESCE(C190.BDVLRITEM + C190.BDVLRDESPACESSORIA + C190.BDVLRFRETE, 0) - COALESCE(C190.BDVLRDESC, 0)),
        --                                              (IIF(((GETORDEMSEQUENCIAL(C190.BDCHAVE) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT))), 0.00), '.', ',')|| --VL_OPR
        '|'||REPLACE((CASE WHEN C190.BDMODELO = 65 THEN (COALESCE(C190.BDVLRITEM + C190.BDVLRDESPACESSORIA + C190.BDVLRFRETE, 0) - COALESCE(C190.BDVLRDESC, 0))
                           WHEN (tot.bdVLRDESC + tot.bdVLRABATNT) = C190.bdDESCONTONOTA THEN ((IIF(((GETORDEMSEQUENCIAL_STR(C190.BDCHAVE,C190.BDCODEMP) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT)) - c190.bdVLRABATNT) -- Alt.: #125909 #126894 #127057 #127296 #127440 #127528 #127589 #127562 #127779 #127586 - Se a soma do desconto + abatimento dos produtos for igual ao que possui no campo desconto da capa da nota, vai levar no C190 campo "valor da operacao" o valor dos produtos menos desconto e abatimento informados no produto.
                      ELSE (IIF(((GETORDEMSEQUENCIAL_STR(C190.BDCHAVE,C190.BDCODEMP) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT)) END), '.', ',') -- Alt.: #125909 #126894 #127057 #127296 #127440 #127528 #127589 #127562 #127779 #127586 - Se a soma do desconto + abatimento dos produtos for diferente do que possui no campo desconto da capa da nota, vai levar no C190 campo "valor da operacao" o valor dos produtos menos desconto.
           || --VL_OPR
        '|'||REPLACE(COALESCE(C190.BDBCICMS, 0.00), '.', ',')|| --VL_BC_ICMS
        '|'||REPLACE(COALESCE(C190.BDVLRICMS + IIF(:WFCPOP = 'TRUE', C190.BDVLRFCP, 0.00), 0.00)
                     /*COALESCE(IIF(C190.BDREFLAN >= 201901,(SELECT BDRETORNO FROM SP_GET_FCP(0,C190.BDFCPRETIDO,C190.BDCSTICMS, C190.BDCODNAT)),0.00),0.00) --Soma FCP_OP*/
                     , '.', ',')|| --VL_ICMS #89669 - Deve somar FCP
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, C190.BDBCST), 0.00), '.', ',')|| --VL_BC_ICMS_ST
        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, COALESCE(C190.BDVLRST,0.00) + IIF(C190.BDREFLAN >= 201901,COALESCE(C190.BDFCPRETIDO,0.00),0.00) -- A procedure SP_GET_FCP só é valida para o registro C191
                     /*COALESCE(IIF(C190.BDREFLAN >= 201901,(SELECT BDRETORNO FROM SP_GET_FCP(1,C190.BDFCPRETIDO,C190.BDCSTICMS, C190.BDCODNAT)),0.00),0.00) + --Soma FCP_ST
                     COALESCE(IIF(C190.BDREFLAN >= 201901,(SELECT BDRETORNO FROM SP_GET_FCP(2,C190.BDFCPRETIDO,C190.BDCSTICMS, C190.BDCODNAT)),0.00),0.00)   --Soma FCP_RET*/
                     ), 0.00), '.', ',')|| --VL_ICMS_ST #89669 - Deve somar FCP
--        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, (SELECT BDRED_BC FROM SP_CALC_RED_BC((COALESCE(C190.BDVLRITEM, 0) + COALESCE(C190.BDVLRDESPACESSORIA, 0) + COALESCE(C190.BDVLRIPI, 0) + COALESCE(C190.BDVLRST, 0)), C190.BDREDBCICMS, C190.BDBCICMS, C190.BDCSTICMS))), 0.00), '.', ',')|| --VL_RED_BC
--        '|'||REPLACE(COALESCE(IIF(C190.BDMODELO = 65, NULL, (SELECT BDRED_BC FROM SP_CALC_RED_BC((IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT)), C190.BDREDBCICMS, C190.BDBCICMS, C190.BDCSTICMS))), 0.00), '.', ',')|| --VL_RED_BC
--        '|'||REPLACE((SELECT BDVALOR FROM GET_TRATA_VALOR_NEGATIVO(IIF((SUBSTRING(COALESCE(C190.BDCSTICMS, 0) FROM CHAR_LENGTH(C190.BDCSTICMS)-1 FOR 2)) IN(20, 70), (COALESCE(IIF(C190.BDMODELO = 65, (COALESCE(C190.BDVLRITEM + C190.BDVLRDESPACESSORIA + C190.BDVLRFRETE, 0) - COALESCE(C190.BDVLRDESC, 0)),(IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT))), 0) - COALESCE(C190.BDBCICMS, 0)), 0.00))), '.', ',') ||
        '|'||REPLACE((SELECT BDVALOR FROM GET_TRATA_VALOR_NEGATIVO(IIF((SUBSTRING(C190.BDCSTICMS FROM 2 FOR 2)) IN(20, 70), (COALESCE(IIF(C190.BDMODELO = 65, (COALESCE(C190.BDVLRITEM + C190.BDVLRDESPACESSORIA + C190.BDVLRFRETE, 0) - COALESCE(C190.BDVLRDESC, 0)),(IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C190.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C190.BDVLRTOT + (C190.BDVALORNOTA - TOT.BDVLRDIF)), C190.BDVLRTOT))), 0) - COALESCE(C190.BDBCICMS, 0) - COALESCE(C190.BDVLRST, 0.00) - COALESCE(C190.BDVLRIPI, 0.00)), 0.00))), '.', ',') ||
        '|'||REPLACE(COALESCE(C190.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
        '|'||COALESCE(OBS_ITEM.BDCODEXP, COALESCE(OBS_C195.BDCODEXP,''))|| --COD_OBS
        '|',
        COALESCE(OBS_ITEM.BDCODOBS, OBS_C195.BDCODOBS)
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCSTICMS, MOV.BDCODNAT, MOV.BDALIQICMS, SAI.BDMODELO, MOV.BDVLRITEM,
               MOV.BDVLRDESC, MOV.BDVLRFRETE, MOV.BDVLRDESPACESSORIA, MOV.BDVLRIPI, MOV.BDVLRST, MOV.BDBCICMS,
               MOV.BDVLRICMS, MOV.BDBCST, MOV.BDREDBCICMS, SAI.BDVALORNOTA, SAI.BDREFLAN, MOV.BDFCPRETIDO, sai.bdDESCONTONOTA,
               (COALESCE(MOV.BDVLRFRETE, 0) + COALESCE(MOV.BDVLRITEM, 0) +
                COALESCE(MOV.BDVLRDESPACESSORIA, 0) +
                IIF((Coalesce(:WSOMAIPIPROD,'FALSE') = 'FALSE') AND (Coalesce(MOV.BDSOMAIPIPROD,'FALSE') = 'FALSE'),COALESCE(MOV.BDVLRIPI, 0),0) +
                IIF((Coalesce(:WSOMASTPROD,'FALSE') = 'FALSE') AND (Coalesce(MOV.BDSOMASTPROD,'FALSE') = 'FALSE'),COALESCE(MOV.BDVLRST, 0),0) - COALESCE(MOV.BDVLRDESC, 0)  +
                COALESCE(IIF(SAI.BDREFLAN >= 201901,MOV.BDFCPRETIDO,0.00),0.00) --Soma FCP
                ) BDVLRTOT, MOV.BDCODOBS, mov.bdVLRABATNT, MOV.BDVLRFCP
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                     ICMS.BDCSTICMS,
                     COALESCE(MOV.BDCODNAT, 0) BDCODNAT,
                     iif(substring(icms.bdcsticms from 2 for 3) = '53', CAST(Trunc(COALESCE(PRO.bdaliqicmsmonodif, 0), 2) AS NUMERIC(6, 2)), iif(substring(icms.bdcsticms from 2 for 3) = '02' and CAST(Trunc(COALESCE(PRO.bdaliqicmsmono, 0), 2) AS NUMERIC(6, 2)) > 0, CAST(Trunc(COALESCE(PRO.bdaliqicmsmono, 0), 2) AS NUMERIC(6, 2)), iif(substring(icms.bdcsticms from 2 for 3) = '15' and CAST(Trunc(COALESCE(PRO.bdaliqicmsmonoret, 0), 2) AS NUMERIC(6, 2)) > 0, CAST(Trunc(COALESCE(PRO.bdaliqicmsmonoret, 0), 2) AS NUMERIC(6, 2)), CAST(COALESCE(PRO.BDALIQICMS, 0) AS NUMERIC(6, 2))))) BDALIQICMS,
                     --CAST(COALESCE(PRO.BDALIQICMS, 0) AS NUMERIC(6, 2)) BDALIQICMS,
                     SUM(COALESCE(PRO.BDVLRITEM, 0)) BDVLRITEM,
                     SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC,
                     SUM(COALESCE(PRO.BDVLRFRETE, 0)) BDVLRFRETE,
                     SUM(COALESCE(PRO.BDVLRDESPACESSORIA, 0)) BDVLRDESPACESSORIA,
                     SUM(COALESCE(PRO.BDVLRIPI, 0)) BDVLRIPI,                                                                        /* Solicitação #183143 */
                     sum(iif(substring(icms.bdcsticms from 2 for 3) = '53' or substring(icms.bdcsticms from 2 for 3) = '61', 0, iif(/*substring(icms.bdcsticms from 2 for 3) = '02' or*/ substring(icms.bdcsticms from 2 for 3) = '15', coalesce(pro.bdvlricmsmono, 0) + coalesce(pro.bdvlricmsmonoret, 0), COALESCE(PRO.BDVLRST, 0)))) BDVLRST,
                     sum(iif(substring(icms.bdcsticms from 2 for 3) = '53' or substring(icms.bdcsticms from 2 for 3) = '61', 0, iif(/*substring(icms.bdcsticms from 2 for 3) = '02' or*/ substring(icms.bdcsticms from 2 for 3) = '15', 0, COALESCE(PRO.BDBCST, 0)))) BDBCST,
                     --SUM(COALESCE(PRO.BDVLRST, 0)) BDVLRST,
                     --SUM(COALESCE(PRO.BDBCST, 0)) BDBCST,
                     sum(iif((substring(icms.bdcsticms from 2 for 3) = '02'  or substring(icms.bdcsticms from 2 for 3) = '15' or substring(icms.bdcsticms from 2 for 3) = '53' or substring(icms.bdcsticms from 2 for 3) = '61'), 0, COALESCE(PRO.BDBCICMS, 0))) BDBCICMS,
                     sum(iif((substring(icms.bdcsticms from 2 for 3) = '02' or substring(icms.bdcsticms from 2 for 3) = '15' or substring(icms.bdcsticms from 2 for 3) = '53' or substring(icms.bdcsticms from 2 for 3) = '61'), 0, COALESCE(PRO.BDVLRICMS, 0))) BDVLRICMS,
                     --SUM(COALESCE(PRO.BDBCICMS, 0)) BDBCICMS,
                     --SUM(COALESCE(PRO.BDVLRICMS, 0)) BDVLRICMS,
                     SUM(COALESCE(PRO.BDREDBCICMS, 0)) BDREDBCICMS,
                     SUM(COALESCE(PRO.BDFCPRETIDO,0)) BDFCPRETIDO,
                     MAX(COALESCE(MOV.BDCODOBS,0)) BDCODOBS,
                     SUM(COALESCE(PRO.bdVLRABATNT,0)) bdVLRABATNT,
                     SUM(COALESCE(PRO.BDVLRFCP, 0)) BDVLRFCP,
                     sum(coalesce(pro.bdvlricmsmonoret, 0)) BDVLRICMSMONORET, Max(MOV.BDSOMAIPIPROD) BDSOMAIPIPROD, Max(MOV.BDSOMASTPROD) BDSOMASTPROD
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT, i.BDCODOBS, NATOP.BDSOMAIPIPROD, NATOP.BDSOMASTPROD
                    FROM VEF_EMP_TMOVSAI M
                    LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                    JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)                
                    LEFT OUTER JOIN VEF_BASE_TNATOP NATOP ON (NATOP.BDCODNAT = I.BDCODNAT)
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                    AND (M.BDMODELO IN (1, 4, 55, 65, 100) OR (:WSEGREGACAO = 'TRUE'))
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (M.BDCODSITNF = 6)*/)
                    AND ((:wTERMOACORDO IS NULL) OR (:wTERMOACORDO <> 'TRUE') OR (M.BDMODELO <> 65))
                   ) MOV
              JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
              LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS)
              WHERE NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = MOV.BDCODEMP AND DF.BDCHAVESAI = MOV.BDCHAVE AND DF.BDORDEMSAI = MOV.BDORDEM))
              GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, ICMS.BDCSTICMS, MOV.BDCODNAT, CAST(COALESCE(PRO.BDALIQICMS, 0) AS NUMERIC(6, 2)), CAST(Trunc(COALESCE(PRO.bdaliqicmsmono, 0), 2) AS NUMERIC(6, 2)), CAST(Trunc(COALESCE(PRO.bdaliqicmsmonodif, 0), 2) AS NUMERIC(6, 2)), CAST(Trunc(COALESCE(PRO.bdaliqicmsmonoret, 0), 2) AS NUMERIC(6, 2))
             ) MOV
        JOIN VEF_EMP_TMOVSAI SAI ON(SAI.BDCODEMP = MOV.BDCODEMP AND SAI.BDCHAVE = MOV.BDCHAVE)
       ) C190
  LEFT OUTER JOIN (
                   SELECT C190_TOT.BDCODEMP, C190_TOT.BDCHAVE, SUM(C190_TOT.BDVLRDIF) BDVLRDIF, COUNT(C190_TOT.BDCHAVE) BDORDEMMAX,
                          SUM(C190_TOT.bdVLRDESC) AS bdVLRDESC, SUM(C190_TOT.bdVLRABATNT) AS bdVLRABATNT
                   FROM (
                         SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                                SUM(COALESCE(pro.bdVLRDESC, 0)) AS bdVLRDESC,
                                SUM(COALESCE(pro.bdVLRABATNT, 0)) AS bdVLRABATNT,
                                ((SUM(COALESCE(PRO.BDVLRITEM, 0)) +
                                  SUM(COALESCE(PRO.BDVLRDESPACESSORIA, 0)) +
                                  SUM(IIF((Coalesce(:WSOMAIPIPROD,'FALSE') = 'FALSE') AND (Coalesce(MOV.BDSOMAIPIPROD,'FALSE') = 'FALSE'),COALESCE(PRO.BDVLRIPI, 0),0)) +
                                  SUM(IIF((Coalesce(:WSOMASTPROD,'FALSE') = 'FALSE') AND (Coalesce(MOV.BDSOMASTPROD,'FALSE') = 'FALSE'),COALESCE(PRO.BDVLRST, 0),0)) +
                                  SUM(COALESCE(PRO.BDVLRFRETE, 0))) -
                                  SUM(COALESCE(PRO.BDVLRDESC, 0)) +
                                  SUM(COALESCE(IIF(MOV.BDREFLAN >= 201901,PRO.BDFCPRETIDO,0.00),0.00))  --Soma FCP
                                 
                                 ) BDVLRDIF     
                         FROM (
                               SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT, M.BDREFLAN, NATOP.BDSOMAIPIPROD, NATOP.BDSOMASTPROD
                               FROM VEF_EMP_TMOVSAI M
                               LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                               JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)              
                               LEFT OUTER JOIN VEF_BASE_TNATOP NATOP ON (NATOP.BDCODNAT = I.BDCODNAT)
                               WHERE M.BDCODEMP = :PRCODEMP
                               AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                               AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                               AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                               AND (M.BDMODELO IN (1, 4, 55, 65, 100) OR (:WSEGREGACAO = 'TRUE'))
                               AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (M.BDCODSITNF = 6)*/)
                              ) MOV
                         JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
                         LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS)
                         GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, PRO.BDCODCSTICMS, MOV.BDCODNAT, CAST(COALESCE(PRO.BDALIQICMS, 0) AS NUMERIC(6, 2))
                        ) C190_TOT
                   GROUP BY C190_TOT.BDCODEMP, C190_TOT.BDCHAVE
                  ) TOT ON(TOT.BDCODEMP = C190.BDCODEMP AND TOT.BDCHAVE = C190.BDCHAVE)
  LEFT OUTER JOIN ( SELECT C.BDCODEMP, C.BDCHAVE, MAX(c.BDCODOBS) BDCODOBS
                    FROM VEF_EMP_TC195SAI C
                    GROUP BY C.BDCODEMP, C.BDCHAVE ) C195 ON (C195.BDCODEMP = C190.BDCODEMP AND C195.BDCHAVE = C190.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TOBSERVACAO OBS_ITEM ON(OBS_ITEM.BDCODOBS = C190.BDCODOBS)
  LEFT OUTER JOIN VEF_BASE_TOBSERVACAO OBS_C195 ON(OBS_C195.BDCODOBS = C195.BDCODOBS);

  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
  /*Monta o C190 a partir da tabela do C190*/
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.1.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C190.'||SUBSTRING(MOV.BDCODNAT FROM 1 FOR 4)||'.'||REPLACE(CAST(C190.BDALIQICMS AS DM_NUMERIC_7_4_ALIQ), '.', '')||'.'||LPAD(COALESCE(ICMS.BDCSTICMS, ''), 3, ' '),
          'C190' BDREG,
          '|C190'||
          '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
          '|'||COALESCE(SUBSTRING(MOV.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
          '|'||REPLACE(CAST(COALESCE(C190.BDALIQICMS, 0) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
          '|'||REPLACE(SUM(COALESCE(C190.BDVLROPER, 0.00)), '.', ',')|| --VL_OPR
          '|'||REPLACE(SUM(COALESCE(C190.BDVLRBCICMS, 0.00)), '.', ',')|| --VL_BC_ICMS
          '|'||REPLACE(SUM(COALESCE(C190.BDVLRICMS, 0.00)), '.', ',')|| --VL_ICMS
          '|'||REPLACE(SUM(COALESCE(C190.BDVLRBCICMSST, 0.00)), '.', ',')|| --VL_BC_ICMS_ST
          '|'||REPLACE(SUM(COALESCE(C190.BDVLRICMSST, 0.00)), '.', ',')|| --VL_ICMS_ST
--          '|'||REPLACE((SELECT BDVALOR FROM GET_TRATA_VALOR_NEGATIVO( IIF((SUBSTRING(COALESCE(ICMS.BDCSTICMS, 0) FROM CHAR_LENGTH(ICMS.BDCSTICMS)-1 FOR 2)) IN(20, 70), (COALESCE(C190.BDVLROPER, 0) - COALESCE(C190.BDVLRBCICMS, 0)), 0.00))) , '.', ',')|| --VL_RED_BC
          '|'||REPLACE((SELECT BDVALOR FROM GET_TRATA_VALOR_NEGATIVO( IIF((SUBSTRING(ICMS.BDCSTICMS FROM 2 FOR 2)) IN(20, 70), (SUM(COALESCE(C190.BDVLROPER, 0)) - SUM(COALESCE(C190.BDVLRBCICMS, 0)) - SUM(COALESCE(C190.BDVLRICMSST, 0.00))), 0.00))) , '.', ',')|| --VL_RED_BC
          '|'||REPLACE(SUM(COALESCE(C190.BDVLRIPI, 0.00)), '.', ',')|| --VL_IPI
          '|'||MAX(COALESCE(OBS_ITEM.BDCODEXP, COALESCE(OBS_C190.BDCODEXP,COALESCE(OBS_C195.BDCODEXP,''))))|| --COD_OBS
          '|',
          MAX(COALESCE(OBS_ITEM.BDCODOBS, COALESCE(OBS_C190.BDCODOBS,OBS_C195.BDCODOBS)))
  FROM (
        SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, SAI.BDCODSITNF, I.BDCODNAT, I.BDCODOBS
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODSITNF
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODSITNF
                    FROM VEF_EMP_TMOVSAI M
                    LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                    AND ((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) OR (M.BDCODSITNF = 6) OR ((M.BDCODSITNF = 8) AND (M.BDMODELO = 1))) /*Sol. 20290 Gabriel Ariel (13/11/2017) - Agora exporta o C190 caso possua modelo 1 e siuação 8*/
                    AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                    AND (M.BDMODELO IN (1, 4, 55, 65, 100) OR (:WSEGREGACAO = 'TRUE'))
                    AND ((:wTERMOACORDO IS NULL) OR (:wTERMOACORDO <> 'TRUE') OR (M.BDMODELO <> 65))
                   ) MOV
             ) SAI
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
        WHERE ((NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (SAI.BDCODSITNF = 6)*/)
        AND NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = SAI.BDCODEMP AND DF.BDCHAVESAI = SAI.BDCHAVE AND DF.BDORDEMSAI = I.BDORDEM))
       ) MOV
  JOIN VEF_EMP_TC190SAI C190 ON(C190.BDCODEMP = MOV.BDCODEMP AND C190.BDCHAVE = MOV.BDCHAVE AND C190.BDORDEM = MOV.BDORDEM)
  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = C190.BDCODCSTICMS)   
  LEFT OUTER JOIN ( SELECT C.BDCODEMP, C.BDCHAVE, MAX(c.BDCODOBS) BDCODOBS
                    FROM VEF_EMP_TC195SAI C
                    GROUP BY C.BDCODEMP, C.BDCHAVE ) C195 ON (C195.BDCODEMP = C190.BDCODEMP AND C195.BDCHAVE = C190.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TOBSERVACAO OBS_ITEM ON(OBS_ITEM.BDCODOBS = MOV.BDCODOBS)
  LEFT OUTER JOIN VEF_BASE_TOBSERVACAO OBS_C190 ON(OBS_C190.BDCODOBS = C190.BDCODOBS)
  LEFT OUTER JOIN VEF_BASE_TOBSERVACAO OBS_C195 ON(OBS_C195.BDCODOBS = C195.BDCODOBS)
  GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODNAT, C190.BDALIQICMS, ICMS.BDCSTICMS;

  /*Monta o C191 a partir do movimento de produto*/
  SETORDEMSEQUENCIAL_STR(:PRCODEMP);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID,
        LPAD(C190.BDCODEMP, 6, '0')||'.1.'||LPAD(C190.BDCHAVE, 10, '0')||'.C100.C190.'||C190.bdPREFIXONAT||'.'||REPLACE(CAST(C190.BDALIQICMS AS DM_NUMERIC_7_4_ALIQ), '.', '')||'.'|| LPAD(COALESCE(C190.BDCSTICMS, ''), 3, ' ') || '.C191.'||LPAD(GETORDEMSEQUENCIAL_STR(C190.BDCHAVE,C190.BDCODEMP), 6, '0'),
          'C191' BDREG,
          '|C191'||
          '|'||REPLACE(IIF(:WFCPOP = 'TRUE', C190.BDVLRFCP, 0.00), '.', ',')|| --VL_FCP_OP
          '|'||REPLACE(C190.BDFCPRETIDO, '.', ',')|| --VL_FCP_ST
          '|'||REPLACE(C190.BDVLRFCPSTRET, '.', ',')|| --VL_FCP_RET
          '|'
  FROM (
        SELECT IIF(:wexp_vl_fcp_op, (SELECT BDRETORNO FROM SP_GET_FCP(0,MOV.BDVLRFCP     ,MOV.BDCSTICMS, MOV.BDPREFIXONAT)), 0) BDVLRFCP,
               (SELECT BDRETORNO FROM SP_GET_FCP(1,MOV.BDFCPRETIDO  ,MOV.BDCSTICMS, /*C190.BDCODNAT*/MOV.BDPREFIXONAT)) BDFCPRETIDO,
               (SELECT BDRETORNO FROM SP_GET_FCP(2,MOV.BDVLRFCPSTRET,MOV.BDCSTICMS, /*C190.BDCODNAT*/MOV.BDPREFIXONAT)) BDVLRFCPSTRET,
               MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, mov.BDALIQICMS, MOV.BDPREFIXONAT, MOV.BDCSTICMS
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, ICMS.BDCSTICMS, /*MOV.BDCODNAT,*/ MOV.BDFCPRETIDO, mov.BDPREFIXONAT, mov.BDALIQICMS, MOV.BDVLRFCP, MOV.BDVLRFCPSTRET
              FROM (
                    SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN,
                           COALESCE(PRO.BDCODCSTICMS, 0) BDCODCSTICMS,
                           --COALESCE(MOV.BDCODNAT, 0) BDCODNAT, Alt.: #95951 - Ajustado para levar pelo prefixo da CFOP, que é oq leva na exportação...
                           SUM(COALESCE(PRO.BDFCPRETIDO,0)) BDFCPRETIDO,
                           SUM(COALESCE(PRO.BDVLRFCPSTRET, 0.00)) BDVLRFCPSTRET,
                           COALESCE(mov.bdPREFIXONAT, 0) BDPREFIXONAT,
                           SUM(COALESCE(PRO.BDVLRFCP, 0)) BDVLRFCP,
                           CAST(COALESCE(PRO.BDALIQICMS, 0) AS NUMERIC(6, 2)) BDALIQICMS
                    FROM (
                          SELECT M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, I.BDORDEM, I.BDCODNAT, COALESCE(i.bdPREFIXONAT, SUBSTRING(i.bdCODNAT FROM 1 FOR 4)) AS BDPREFIXONAT
                          FROM VEF_EMP_TMOVSAI M
                          LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                          JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                          WHERE M.BDCODEMP = :PRCODEMP
                          AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                          AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                          AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                          AND ((M.BDMODELO IN (55)) OR (M.BDMODELO IN(65) AND M.BDREFLAN >= 202001))--Vilson Daniel #124941--(1, 4, 55, 65, 100) Alt.: #96043 - Apenas modelo 55...
                          AND M.BDREFLAN >= 201901
                          AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM AND (P.BDFCPRETIDO > 0 OR P.BDVLRFCP > 0 OR P.BDVLRFCPSTRET > 0))) /*OR (M.BDCODSITNF = 6)*/)
                          AND ((:wTERMOACORDO IS NULL) OR (:wTERMOACORDO <> 'TRUE') OR (M.BDMODELO <> 65))
                         ) MOV
                    JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
                    WHERE NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = MOV.BDCODEMP AND DF.BDCHAVESAI = MOV.BDCHAVE))
                    GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, PRO.BDCODCSTICMS, /*MOV.BDCODNAT,*/  CAST(COALESCE(PRO.BDALIQICMS, 0) AS NUMERIC(6, 2)), mov.BDPREFIXONAT
                   ) MOV

              LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = MOV.BDCODCSTICMS)
              WHERE MOV.BDFCPRETIDO > 0 OR MOV.BDVLRFCP > 0 OR MOV.BDVLRFCPSTRET > 0
             ) MOV
       ) C190
       WHERE C190.BDVLRFCP > 0 OR C190.BDFCPRETIDO > 0 OR C190.BDVLRFCPSTRET > 0;

  /*Monta o C191 a partir da tabela do C190*/
  SETORDEMSEQUENCIAL_STR(:PRCODEMP);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID,
         LPAD(Filtro.BDCODEMP, 6, '0')||'.1.'||LPAD(Filtro.BDCHAVE, 10, '0')||'.C100.C190.'|| SUBSTRING(Filtro.bdCODNAT FROM 1 FOR 4)|| '.' || REPLACE(CAST(Filtro.BDALIQICMS AS DM_NUMERIC_7_4_ALIQ), '.', '')||'.'|| LPAD(COALESCE(Filtro.BDCSTICMS, ''), 3, ' ') || '.C191.' || LPAD(GETORDEMSEQUENCIAL_STR(Filtro.BDCHAVE,Filtro.BDCODEMP), 6, '0'),
          'C191' BDREG,
          '|C191'||
          '|'||REPLACE(Filtro.VL_FCP_OP, '.', ',')|| --VL_FCP_OP
          '|'||REPLACE(Filtro.VL_FCP_ST, '.', ',')|| --VL_FCP_ST
          '|'||REPLACE(Filtro.VL_FCP_RET, '.', ',')|| --VL_FCP_RET
          '|'
  FROM (
         SELECT  MOV.BDCODEMP, MOV.BDCHAVE, MOV.bdCODNAT, C190.BDALIQICMS, ICMS.BDCSTICMS,
                 IIF(:wexp_vl_fcp_op, (SELECT BDRETORNO FROM SP_GET_FCP(0,SUM(COALESCE(C190.BDFCPRETIDO,0.00)),ICMS.BDCSTICMS, MOV.BDCODNAT)), 0) AS VL_FCP_OP,
                 (SELECT BDRETORNO FROM SP_GET_FCP(1,SUM(COALESCE(C190.BDFCPRETIDO,0.00)),ICMS.BDCSTICMS, MOV.BDCODNAT)) AS VL_FCP_ST,
                 (SELECT BDRETORNO FROM SP_GET_FCP(2,SUM(COALESCE(C190.BDFCPRETIDO,0.00)),ICMS.BDCSTICMS, MOV.BDCODNAT)) AS VL_FCP_RET
         FROM (
                SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, SAI.BDCODSITNF, I.BDCODNAT
                FROM (
                      SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODSITNF
                      FROM (
                            SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODSITNF
                            FROM VEF_EMP_TMOVSAI M
                            LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                            WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                              AND ((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) OR (M.BDCODSITNF = 6) OR ((M.BDCODSITNF = 8) AND (M.BDMODELO = 1))) /*Sol. 20290 Gabriel Ariel (13/11/2017) - Agora exporta o C190 caso possua modelo 1 e siuação 8*/
                              AND M.BDREFLAN >= 201901
                              AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                              AND ((M.BDMODELO IN (55)) OR (M.BDMODELO IN(65) AND M.BDREFLAN >= 202001))--Vilson Daniel #124941--(1, 4, 55, 65, 100) Alt.: #96043 - Apenas modelo 55...
                              AND ((:wTERMOACORDO IS NULL) OR (:wTERMOACORDO <> 'TRUE') OR (M.BDMODELO <> 65))
                           ) MOV
                     ) SAI
                JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                WHERE ((NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) /*OR (SAI.BDCODSITNF = 6)*/)
                  AND NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = SAI.BDCODEMP AND DF.BDCHAVESAI = SAI.BDCHAVE AND DF.BDORDEMSAI = I.BDORDEM))
              ) MOV
         JOIN VEF_EMP_TC190SAI C190 ON(C190.BDCODEMP = MOV.BDCODEMP AND C190.BDCHAVE = MOV.BDCHAVE AND C190.BDORDEM = MOV.BDORDEM)
         LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = C190.BDCODCSTICMS)
         GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODNAT, C190.BDALIQICMS, ICMS.BDCSTICMS
    ) Filtro;
  --WHERE Filtro.VL_FCP_OP > 0 or Filtro.VL_FCP_ST > 0 or Filtro.VL_FCP_RET > 0;


  --22326
  /*****************************************************************************
   *                                   C195                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.1.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C195.'||LPAD(C195.BDORDEMOBS, 6, '0'),
         'C195' BDREG,
         '|C195'||
         '|'||COALESCE(OBS.BDCODEXP, '')|| --COD_OBS
         '|'||TRIM(COALESCE(REPLACE(C195.BDDESCCOMPL, '|', ''), ''))|| --TXT_COMPL
         '|',
          C195.BDCODOBS
  FROM (
        SELECT SAI.BDCODEMP, SAI.BDCHAVE
        FROM VEF_EMP_TMOVSAI SAI
        LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = SAI.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
        WHERE SAI.BDCODEMP = :PRCODEMP
        AND SAI.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, SAI.BDCHAVE)
        AND SAI.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND SAI.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
        AND NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = SAI.BDCODEMP AND DF.BDCHAVESAI = SAI.BDCHAVE ))
        AND ((:wTERMOACORDO IS NULL) OR (:wTERMOACORDO <> 'TRUE') OR (SAI.BDMODELO <> 65))
       ) MOV
  JOIN VEF_EMP_TC195SAI C195 ON(C195.BDCODEMP = MOV.BDCODEMP AND C195.BDCHAVE = MOV.BDCHAVE AND (C195.BDTIPOOPERACAO = 'C195' OR C195.BDTIPOOPERACAO IS NULL))
  JOIN VEF_BASE_TOBSERVACAO OBS ON(OBS.BDCODOBS = C195.BDCODOBS);

  /*****************************************************************************
   *                                   C197                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD)
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.1.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C195.'||LPAD(C197.BDORDEMOBS, 6, '0')||'.C197.'||LPAD(C197.BDORDEMOUTOBR, 6, '0'),
         'C197' BDREG,
         '|C197'||
         '|'||COALESCE(AJU.BDCODAJUPAD, '')|| --COD_AJ
         '|'||TRIM(COALESCE(REPLACE(C197.BDDESCCOMPL, '|', ''), ''))|| --DESCR_COMPL_AJ
         '|'||COALESCE(IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')), VINC.BDCODPROD, VINC.BDCODSAIDA), '')|| --COD_ITEM
         '|'||REPLACE(COALESCE(C197.BDBICMS, 0.00), '.', ',')|| --VL_BC_ICMS
         '|'||REPLACE(CAST(COALESCE(C197.BDALIQICMS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
         '|'||REPLACE(COALESCE(C197.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
         '|'||REPLACE(COALESCE(C197.BDOUTVLR, 0.00), '.', ',')|| --VL_OUTROS
         '|', C197.BDCODPROD
  FROM (
        SELECT SAI.BDCODEMP, SAI.BDCHAVE
        FROM VEF_EMP_TMOVSAI SAI
        LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = SAI.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
        WHERE SAI.BDCODEMP = :PRCODEMP
        AND SAI.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, SAI.BDCHAVE)
        AND SAI.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND SAI.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
        AND NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = SAI.BDCODEMP AND DF.BDCHAVESAI = SAI.BDCHAVE ))
        AND ((:wTERMOACORDO IS NULL) OR (:wTERMOACORDO <> 'TRUE') OR (SAI.BDMODELO <> 65))
       ) MOV
  JOIN VEF_EMP_TC195SAI C195 ON(C195.BDCODEMP = MOV.BDCODEMP AND C195.BDCHAVE = MOV.BDCHAVE AND C195.BDCODOBS IS NOT NULL AND (C195.BDTIPOOPERACAO = 'C195' OR C195.BDTIPOOPERACAO IS NULL))
  JOIN VEF_EMP_TC197SAI C197 ON(C197.BDCODEMP = C195.BDCODEMP AND C197.BDCHAVE = C195.BDCHAVE AND C197.BDORDEMOBS = C195.BDORDEMOBS)
  LEFT OUTER JOIN VEF_BASE_TTABCODAJU AJU ON(AJU.BDCODAJU = C197.BDCODAJU)  
  LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = MOV.BDCODEMP AND VINC.BDCODPROD = C197.BDCODPROD);
END^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOC_SAI (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRTIPOEXPCODPART integer,
    PRPERFIL integer,
    PRCODPLAPADRAOREF integer,
    PRSESSAOSEGREG integer,
    PREXPORTARC170EMISSAOPROPRIA varchar(5))
as
declare variable WSEGREGACAO varchar(5);
declare variable WFCPOP varchar(5);
declare variable VUFEMPRESA varchar(3);
declare variable WCHAVEMIN integer;
declare variable WCHAVEMAX integer;
declare variable WTERMOACORDO varchar(5);
declare variable WEXPE310 DM_BOOLEAN;
declare variable WEXPINCENTFISCAIS DM_BOOLEAN;
declare variable WAPUSEMANAL varchar(5);
BEGIN
  /*****************************************************************************
   *--------------------------------->>SAÍDA<<---------------------------------*
   ****************************************************************************/

   /*
     OBS: A Ordernação dos registros é feita pelo campo BDCHAVEREG que é uma classificação.
          Classificação: Empresa.Chave.Reg.Chave.Reg....
          EX: C170: 000010.0000012587.C100.C170.000001
              C195: 000010.0000012587.C100.C195.000001
              C197: 000010.0000012587.C100.C195.000001.C197.000001
   */
   /*Quando a empresa é do estado do DF não é exportado o registro C190 para notas conjugadas com lançamento único de serviço*/
   EXECUTE PROCEDURE SP_SETA_COMPETENCIA(CAST((EXTRACT(YEAR FROM :PRDTINI) || LPAD(EXTRACT(MONTH FROM :PRDTINI),2,'0')) AS INTEGER));

  SELECT Coalesce(rdb$get_context('USER_SESSION', 'W_SEGREGACAO_FISCAL'),'FALSE') FROM rdb$database INTO WSEGREGACAO;

   SELECT UF.BDSIGLAUF, UF.BDFCPOP FROM VW_TEMPRESAS_REF EMPR
   LEFT OUTER JOIN TCIDADE CID ON (CID.bdcodcid = EMPR.BDCODCID)
   LEFT OUTER JOIN TUF UF ON (CID.BDCODUF = UF.BDCODUF)
   WHERE :PRCODEMP = EMPR.BDCODEMP
   INTO :vufempresa, :WFCPOP; --Alt.: FCP_OP - PEGA O PARÂMETRO FCPOP DA UF, PARA SABER SE DEVE SOMAR O FCP JUNTO AO ICMS.

   if (:vufempresa = 'DF') then
      begin
         INSERT INTO TMP_VEF_EMP_TMOVDFSAISER_TEMP(BDCODEMP,BDCHAVESAI,BDORDEMSAI)
         SELECT :PRCODEMP BDCODEMP, T.BDCHAVESAI BDCHAVESAI, I.bdordeM BDORDEMSAI
         FROM VEF_EMP_TMOVSAI MOV
         LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
         LEFT OUTER JOIN TOL_VEF_EMP_TMOVSAI_SER T ON (T.bdcodemp = MOV.BDCODEMP AND MOV.BDCHAVE = T.BDCHAVESAI)
         LEFT OUTER JOIN vef_emp_tmovser SER ON (MOV.BDCODEMP = SER.BDCODEMP AND SER.BDCHAVE = T.BDCHAVESER)
         LEFT OUTER JOIN VEF_EMP_TMOVSERITENS ISER ON (MOV.BDCODEMP = ISER.BDCODEMP AND SER.BDCHAVE = ISER.BDCHAVE)
         WHERE MOV.BDCODEMP = :PRCODEMP
               AND MOV.BDMODELO IN (1, 4, 55, 65, 100)
               AND MOV.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
               AND I.BDPREFIXONAT = ISER.BDPREFIXONAT
               AND I.BDCODNAT IN (5933999,6933999)
         GROUP BY :PRCODEMP, T.BDCHAVESAI, I.bdordeM;
      end

  -- ALt.: "Alteracoes para o Sped do Rio Grande do Sul" - Quando tiver o parametro termo marcado, nao deve exportar as notas do modelo 65...
  SELECT FIRST 1 bdTERMOACORDO, BDEXPE310, BDEXPINCENTFISCAIS, COALESCE(BDSEMANAL, 'FALSE') as BDSEMANAL
  FROM VEF_INT_TSPEDICMS
  WHERE bdCODEMP = :prCODEMP
    AND bdREFERENCIA <= EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0')
  ORDER BY bdREFERENCIA DESC
  INTO :wTERMOACORDO, :WEXPE310, :wEXPINCENTFISCAIS, WAPUSEMANAL; -- Ecommerce #148475 #144120 --

  IF (:prDTINI < '01-JUL-2020') THEN
    wTERMOACORDO = NULL; -- Alt.: "Alterações para o Sped do Rio Grande do Sul" - Apenas para empresas do RS, a partir de 07/2020...

  /*****************************************************************************
   *                                   C100                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODCID)
  SELECT  :PRARQUIVO BDID,
          LPAD(SAI.BDCODEMP, 6, '0')||'.1.'||LPAD(SAI.BDCHAVE, 10, '0')||'.C100',
          'C100' BDREG,
          ('|C100|1|'||IIF(:WSEGREGACAO = 'TRUE' AND MOD.BDMODELOSTR = '59', 0, M.BDEMITENTE)||         --IND_EMIT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65 AND :WSEGREGACAO = 'FALSE', '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, M.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))  || IIF(:wexpe310 = 'TRUE' and (COALESCE(C100.BDVLR_FCP_UF_DEST, 0) > 0 or COALESCE(C100.BDVLRICMS_UF_DEST,0) > 0 or COALESCE(C100.BDVLRICMS_UF_REM,0) > 0) and m.BDCODCID <> ter.bdcodcid, '-'||(SELECT cid.bdcodibge from TCIDADE cid where cid.bdcodcid = m.BDCODCID),'')  ))||  --COD_PART
           '|'||MOD.BDMODELOSTR||             --COD_MOD
           '|'||LPAD(M.BDCODSITNF, 2, '0')||  --COD_SIT
           '|'||COALESCE(M.BDSERIE, '')||     --SER
           '|'||M.BDNUMDOCINI||               --NUM_DOC
           '|'||COALESCE(IIF(M.BDMODELO IN (55, 65) OR :WSEGREGACAO = 'TRUE', iif(M.BDCODSITNF IN (5), '',(RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)), 44, ' '))), NULL), '')|| --CHV_NFE
           '|'||CASE WHEN M.BDCODSITNF IN (2, 3, 4, 5) THEN '' --DT_DOC
                     WHEN (M.BDCODSITNF IN (1,7)) AND ((MOD.BDMODELOSTR = '01') OR (MOD.BDMODELOSTR = '1B') OR (MOD.BDMODELOSTR = '04') OR (MOD.BDMODELOSTR = '55') OR (MOD.BDMODELOSTR = '65')) THEN (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATACANC, 'DDMMYYYY'))
                ELSE (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')) END||
           '|'||CASE WHEN M.BDCODSITNF IN (2, 3, 4, 5) or (((SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATASAIDA, 'YYYYMM')) > (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'YYYYMM')))) or ((:WAPUSEMANAL = 'TRUE') AND ((SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATASAIDA, 'DDMMYYYY')) <> (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))) THEN '' --DT_E_S
                     WHEN (M.BDCODSITNF IN (1,7)) AND ((MOD.BDMODELOSTR = '01') OR (MOD.BDMODELOSTR = '1B') OR (MOD.BDMODELOSTR = '04') OR (MOD.BDMODELOSTR = '55') OR (MOD.BDMODELOSTR = '65')) THEN (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATACANC, 'DDMMYYYY'))
                ELSE (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATASAIDA, 'DDMMYYYY')) END||
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(SAI.BDVLRCONTAB, '.', ','))|| --VL_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(((M.BDCONDPGTO = '2') AND (M.BDDATAEMISSAO < '07/01/2012')), '9', M.BDCONDPGTO))|| --IND_PGTO
           --'|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(M.BDDESCONTONOTA, 0.00) - COALESCE(C100.BDVLRABATNT, 0.00), '.', ','))||   --VL_DESC
           '|'||CASE WHEN M.BDCODSITNF IN (2, 3, 4, 5) THEN '' --VL_DESC
                     WHEN (pro.bdVLRDESC + pro.bdVLRABATNT) = m.bdDESCONTONOTA THEN REPLACE(COALESCE(M.BDDESCONTONOTA, 0.00) - COALESCE(/*C100*/pro.bdVLRABATNT, 0.00), '.', ',') -- Alt.: #125909 #126894 #127057 #127296 #127440 #127528 #127589 #127562 #127779 #127586 - Se a soma do desconto + abatimento dos produtos for igual ao que possui no campo desconto da capa da nota, vai levar no campo "desconto" do C100 o desconto da capa da nota menos o abatimento...
                ELSE REPLACE(COALESCE(M.BDDESCONTONOTA, 0.00), '.', ',') END|| -- Alt.: #125909 #126894 #127057 #127296 #127440 #127528 #127589 #127562 #127779 #127586 - Se a soma do desconto + abatimento dos produtos for diferente do que possui no campo desconto da capa da nota, vai levar no campo "desconto" do C100 o desconto da capa da nota...
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRABATNT, 0.00), '.', ','))|| --VL_ABAT_NT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ','))||    --VL_MERC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', CASE WHEN M.BDMODELO = 65 THEN '9' WHEN (INDFRETEC100.BDCODEXPFRETE IS NULL) THEN '0' ELSE COALESCE(INDFRETEC100.BDCODEXPFRETE, '') END)|| --IND_FRT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRFRETE, 0.00), '.', ','))||  --VL_FRT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRSEGURO, 0.00), '.', ','))|| --VL_SEG
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLROUTDESP, 0.00), '.', ','))||--VL_OUT_DA
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(SAI.BDBASEICMS, 0.00), '.', ','))||   --VL_BC_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(SAI.BDVLRICMS, 0.00) + COALESCE(SAI.BDVLRFCP, 0.00), '.', ','))||    --VL_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(SAI.BDBASEST, 0.00), '.', ',')))||          --VL_BC_ICMS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(SAI.BDVLRST, 0.00)+COALESCE(SAI.bdfcpretido,0.00) , '.', ',')))||           --VL_ICMS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(SAI.BDVLRIPI, 0.00), '.', ',')))||          --VL_IPI
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTPIS, 0.00), '.', ',')))||      --VL_PIS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTCOFINS, 0.00), '.', ',')))||   --VL_COFINS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTPISST, 0.00), '.', ',')))||    --VL_PIS_ST
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', REPLACE(COALESCE(C100.BDVLRTOTCOFINSST, 0.00), '.', ',')))|| --VL_COFINS_ST
           '|') BDLINHA, IIF(((M.BDMODELO = 65 AND :WSEGREGACAO = 'FALSE') OR (M.BDCODSITNF IN (2, 3, 4, 5))), NULL, M.BDCODTER) BDCODTER, IIF(:wexpe310 = 'TRUE' and (COALESCE(C100.BDVLR_FCP_UF_DEST, 0) > 0 or COALESCE(C100.BDVLRICMS_UF_DEST,0) > 0 or COALESCE(C100.BDVLRICMS_UF_REM,0) > 0) and m.BDCODCID <> ter.bdcodcid, m.BDCODCID, null)
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE,
               SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB,
               SUM(COALESCE(I.BDDESCONTO, 0.00)) BDVLRDESCONTO,
               SUM(COALESCE(I.BDBASEICMS, 0.00)) BDBASEICMS,
               SUM(COALESCE(I.BDVLRICMS, 0.00)) BDVLRICMS,
               SUM(COALESCE(I.BDBASEST, 0.0)) BDBASEST,
               SUM(COALESCE(I.BDVLRST, 0.00)) BDVLRST,
               SUM(COALESCE(I.BDVLRIPI, 0.00)) BDVLRIPI,
        SUM(IIF(:WFCPOP = 'TRUE', COALESCE(I.BDVLRFCP, 0.00), 0.00)) BDVLRFCP,
               SUM(COALESCE(I.bdfcpretido, 0.00)) bdfcpretido
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, M.bdcodcid
              FROM (
                    SELECT  M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, M.bdcodcid
                    FROM   VEF_EMP_TMOVSAI M
                    LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                    WHERE M.BDCODEMP = :PRCODEMP
                      AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                      AND (M.BDMODELO IN (1, 4, 55, 65, 100) OR (:WSEGREGACAO = 'TRUE'))
                      AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                      AND ((:wTERMOACORDO IS NULL) OR (:wTERMOACORDO <> 'TRUE') OR (M.BDMODELO <> 65) OR (:WSEGREGACAO = 'TRUE'))
                      AND NOT (/*M.BDMODELO IN (55, 65) AND */M.BDCODSITNF IN (4, 5, 10, 11) AND M.BDREFLAN >= 202301) --#169202 - Adam - 09/11/2022 - Em 2023 os modelos 55 e 65 deixarão de usar as situações 4 e 5.
                    ) M
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        WHERE NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = MOV.BDCODEMP AND DF.BDCHAVESAI = MOV.BDCHAVE AND DF.BDORDEMSAI = I.BDORDEM))
        GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
       ) SAI
  JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = SAI.BDCODEMP AND M.BDCHAVE = SAI.BDCHAVE)
  JOIN VEF_BASE_TTABMODELOLAN MOD ON(MOD.BDMODELO = M.BDMODELO)
  LEFT OUTER JOIN VEF_EMP_TC100SAI C100 ON(C100.BDCODEMP = SAI.BDCODEMP AND C100.BDCHAVE = SAI.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TTABINFRETE INDFRETEC100 ON (INDFRETEC100.BDORDEMFRETE = C100.BDINDFRETE)
  LEFT OUTER JOIN (
                   SELECT P.BDCODEMP, P.BDCHAVE, SUM(COALESCE(P.BDVLRITEM, 0)) BDVLRITEM, SUM(COALESCE(p.bdVLRDESC, 0)) AS bdVLRDESC, SUM(COALESCE(p.bdVLRABATNT, 0)) AS bdVLRABATNT
                   FROM VEF_EMP_TMOVPROSAI P
                   WHERE P.BDCODEMP = :PRCODEMP
                   GROUP BY P.BDCODEMP, P.BDCHAVE
                  ) PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = M.BDCODTER)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = M.bdcodter);

  /*****************************************************************************
   *                                   C101                                    *
   ****************************************************************************/
  IF (:PRDTINI >= '01/01/2016') THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOV.BDCODEMP, 6, '0')||'.1.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C101.0000000001',
             'C101' BDREG,
             '|C101|'||REPLACE(COALESCE(C.BDVLR_FCP_UF_DEST, 0.00), '.', ',')||
             '|'||REPLACE(COALESCE(C.BDVLRICMS_UF_DEST, 0.00), '.', ',')||
             '|'||REPLACE(COALESCE(C.BDVLRICMS_UF_REM, 0.00), '.', ',')||'|'
      FROM (
            SELECT M.BDCODEMP, M.BDCHAVE
            FROM ( SELECT M.BDCODEMP, M.BDCHAVE
            FROM VEF_EMP_TMOVSAI M
            LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
            WHERE M.BDCODEMP = :PRCODEMP
            AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
            AND M.BDMODELO = 55
            AND ((M.BDVALORNOTA > 0) OR
                 (M.BDCODSITNF = 6)) -- Alt.: #145436 - Quando o documento for complementar, vai exportar mesmo que esteja zerado...
            AND M.BDCODSITNF NOT IN(1, 7)
            AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                   AND NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = M.BDCODEMP AND DF.BDCHAVESAI = M.BDCHAVE))
           ) M ) MOV
      JOIN VEF_EMP_TC100SAI C ON(C.BDCODEMP = MOV.BDCODEMP AND C.BDCHAVE = MOV.BDCHAVE AND
                                 (((C.BDVLR_FCP_UF_DEST IS NOT NULL) AND (C.BDVLR_FCP_UF_DEST > 0)) OR
                                  ((C.BDVLRICMS_UF_DEST IS NOT NULL) AND (C.BDVLRICMS_UF_DEST > 0)) OR
                                  ((C.BDVLRICMS_UF_REM IS NOT NULL) AND (C.BDVLRICMS_UF_REM > 0))));
    END

  IF (:PRPERFIL NOT IN(2)) THEN
    BEGIN
      /*****************************************************************************
       *                                   C110                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODINFCOM, BDORDEMINFCOM)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.1.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0'),
             'C110' BDREG,
             '|C110|'||COALESCE(CADINF.BDCODINFCOM, '')||
             '|'||COALESCE(TRIM(REPLACE(SUBSTRING(MOVINF.BDDESCCOMPIC FROM 1 FOR 255), '|', '')), '')||'|',
             CADINF.BDCODINFCOM, CADINF.BDORDEMINFCOM
      FROM (
            SELECT INF.BDCODEMP, INF.BDCHAVE, INF.BDORDEMIC, INF.BDDESCCOMPIC, INF.BDORDEMINFCOM
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVSAI M
                  LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                  --AND M.BDMODELO NOT IN (65)
                  AND (M.BDMODELO IN (1, 4, 55, 100) OR (:WSEGREGACAO = 'TRUE'))
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                  AND NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = M.BDCODEMP AND DF.BDCHAVESAI = M.BDCHAVE))
                 ) MOV
            JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      LEFT OUTER JOIN VEF_BASE_TCADINFCOM CADINF ON(CADINF.BDORDEMINFCOM = MOVINF.BDORDEMINFCOM AND CADINF.BDCODEMP = MOVINF.BDCODEMP);
    
      /*****************************************************************************
       *                                   C111                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.1.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C111.'||LPAD(REF.BDORDEMPROREF, 6, '0'),
             'C111',
             --'|C111|'||COALESCE(TRIM(SUBSTRING(REF.BDNUMPROC FROM 1 FOR 15)), '')||
             '|C111|'||IIF(EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0') < 202301, COALESCE(TRIM(SUBSTRING(REF.BDNUMPROC FROM 1 FOR 15)), ''), COALESCE(TRIM(SUBSTRING(REF.BDNUMPROC FROM 1 FOR 60)), ''))||
             '|'||IIF(REF.BDINDPROCESSO = '4', '9', COALESCE(REF.BDINDPROCESSO, ''))||'|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVSAI M
                  LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                  --AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                  AND NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = M.BDCODEMP AND DF.BDCHAVESAI = M.BDCHAVE))
                 ) MOV
            JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVSAIPROREF REF ON(REF.BDCODEMP = MOVINF.BDCODEMP AND REF.BDCHAVE = MOVINF.BDCHAVE AND REF.BDORDEMIC = MOVINF.BDORDEMIC);
    
      /*****************************************************************************
       *                                   C112                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.1.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C112.'||LPAD(C112.BDORDEMDOCAREF, 6, '0'),
             'C112',
             '|C112'||
             '|'||COALESCE(C112.BDMODCODDA, 0)|| --COD_DA
             '|'||COALESCE(UF.BDSIGLAUF, '')||   --UF
             '|'||COALESCE(C112.BDNUMDA, '')||   --NUM_DA
             '|'||COALESCE(C112.BDCODAUT, '')||  --COD_AUT
             '|'||REPLACE(CAST(COALESCE(C112.BDVLRDA, 0.00) AS NUMERIC(15, 2)), '.', ',')|| --VL_DA
             '|'||(SELECT BDDATA FROM SP_PARSE_DATE(C112.BDDTVCTO, 'DDMMYYYY'))||        --DT_VCTO
             '|'||(SELECT BDDATA FROM SP_PARSE_DATE(C112.BDDTPGTO, 'DDMMYYYY'))||        --DT_PGTO
             '|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVSAI M
                  LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                  --AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                  AND NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = M.BDCODEMP AND DF.BDCHAVESAI = M.BDCHAVE))
                 ) MOV
            JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVSAIDOCAREF C112 ON(C112.BDCODEMP = MOVINF.BDCODEMP AND C112.BDCHAVE = MOVINF.BDCHAVE AND C112.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C112.BDCODUF);
    
      /*****************************************************************************
       *                                   C113                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.1.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C113.'||LPAD(C113.BDORDEMDOCFREF, 6, '0'),
             'C113',
             '|C113'||
             '|'||IIF(C113.BDINDOPER IS NULL, 1, C113.BDINDOPER)|| --IND_OPER
             '|'||COALESCE(C113.BDINDEMIT, 0)||   --IND_EMIT
             '|'||(SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, C113.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))|| --COD_PART
             '|'||COALESCE(DOCFIS.BDDOCFIS, '')|| --COD_MOD
             '|'||COALESCE(C113.BDSERIE, '')||    --SER
             '|'||COALESCE(C113.BDSUBSERIE, '')|| --SUB
             '|'||COALESCE(C113.BDNUMDOC, '')||   --NUM_DOC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C113.BDDTEMISSAO, 'DDMMYYYY')), '')|| --DT_DOC
             '|'||COALESCE(IIF(((DOCFIS.BDCODDOCFIS IN(30, 31, 34)) AND (:PRDTINI > '12/31/2016')), (RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)), 44, ' ')), NULL), '')|| --CHV_DOCe
             '|', C113.BDCODTER
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVSAI M
                  LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                  --AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                  AND NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = M.BDCODEMP AND DF.BDCHAVESAI = M.BDCHAVE))
                 ) MOV
            JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVSAIDOCFREF C113 ON(C113.BDCODEMP = MOVINF.BDCODEMP AND C113.BDCHAVE = MOVINF.BDCHAVE AND C113.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOCFIS ON(DOCFIS.BDCODDOCFIS = C113.BDCODDOCFIS)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER= C113.BDCODTER)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                            ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp ON (TerEmp.bdcodter = C113.bdcodter)
      WHERE (C113.BDNUMDOC > 0)
      AND (C113.BDDTEMISSAO IS NOT NULL);
    
      /*****************************************************************************
       *                                   C114                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOVINF.BDCODEMP, 6, '0')||'.1.'||LPAD(MOVINF.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(MOVINF.BDORDEMIC, 6, '0')||'.C114.'||LPAD(C114.BDORDEMCUPREF, 6, '0'),
             'C114',
             '|C114'||
             '|'||COALESCE(DOCFIS.BDDOCFIS, '')||   --COD_MOD
             '|'||COALESCE(C114.BDNRSERCAIXA, '')|| --ECF_FAB
             '|'||COALESCE(C114.BDNUMCAIXA, '')||   --ECF_CX
             '|'||COALESCE(C114.BDNUMDOC, '')||     --NUM_DOC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C114.BDDTDOC, 'DDMMYYYY')), '')||
             '|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVSAI M
                  LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                  --AND M.BDMODELO NOT IN (65)
                  AND M.BDMODELO IN (1, 4, 55, 100)
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                  AND NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = M.BDCODEMP AND DF.BDCHAVESAI = M.BDCHAVE))
                 ) MOV
            JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVSAICUPREF C114 ON(C114.BDCODEMP = MOVINF.BDCODEMP AND C114.BDCHAVE = MOVINF.BDCHAVE AND C114.BDORDEMIC = MOVINF.BDORDEMIC)
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOCFIS ON(DOCFIS.BDCODDOCFIS = C114.BDCODDOCFIS);
    
      /*****************************************************************************
       *                                   C115                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(C115.BDCODEMP, 6, '0')||'.1.'||LPAD(C115.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(C115.BDORDEMIC, 6, '0')||'.C115.'||LPAD(C115.BDORDEMLOCCOL, 6, '0'),
             'C115',
             '|C115'||
             '|'||COALESCE(TIP.BDCODEXPTRAN, '')|| --IND_CARGA
             '|'||IIF(CHAR_LENGTH(COALESCE(TERCOL.BDCGCTER, '')) = 18, (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(4/*Retorna só CNPJ*/, TERCOL.BDCODTER, TERCOL.BDCGCTER, '', '')), '')|| --CNPJ_COL
             '|'||COALESCE(REPLACE(REPLACE(UPPER((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(TERCOL.BDIETER))), 'ISENTO', ''), 'ISENTA', ''), '')|| --IE_COL
             '|'||IIF(CHAR_LENGTH(COALESCE(TERCOL.BDCGCTER, '')) = 18, '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(4/*Retorna só CNPJ*/, TERCOL.BDCODTER, TERCOL.BDCGCTER, '', '')))|| --CPF_COL
             '|'||COALESCE(CIDCOL.BDCODIBGE, '')|| --COD_MUN_COL
             '|'||IIF(CHAR_LENGTH(COALESCE(TERENTG.BDCGCTER, '')) = 18, (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(4/*Retorna só CNPJ*/, TERENTG.BDCODTER, TERENTG.BDCGCTER, '', '')), '')|| --CNPJ_ENTG
             '|'||COALESCE(REPLACE(REPLACE(UPPER((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(TERENTG.BDIETER))), 'ISENTO', ''), 'ISENTA', ''), '')|| --IE_ENTG
             '|'||IIF(CHAR_LENGTH(COALESCE(TERENTG.BDCGCTER, '')) = 18, '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(4/*Retorna só CNPJ*/, TERENTG.BDCODTER, TERENTG.BDCGCTER, '', '')))|| --CPF_ENTG
             '|'||COALESCE(CIDENTG.BDCODIBGE, '')|| --COD_MUN_ENTG
             '|'
      FROM (
            SELECT C115.BDCODEMP, C115.BDCHAVE, C115.BDORDEMIC, C115.BDORDEMLOCCOL, C115.BDCODTRAN,
                   C115.BDCODTERCOLETA, C115.BDCODCIDCOLETA, C115.BDCODTERENTREGA, C115.BDCODCIDENTREGA
            FROM (
                  SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
                  FROM (
                        SELECT M.BDCODEMP, M.BDCHAVE
                        FROM VEF_EMP_TMOVSAI M
                        LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                        WHERE M.BDCODEMP = :PRCODEMP
                        AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                        AND M.BDMODELO IN (1, 4, 55, 100)
                        AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                        AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                        AND NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = M.BDCODEMP AND DF.BDCHAVESAI = M.BDCHAVE))
                       ) MOV
                  JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
                 ) MOVINF
            JOIN VEF_EMP_TMOVSAILOCCOL C115 ON (C115.BDCODEMP = MOVINF.BDCODEMP AND C115.BDCHAVE = MOVINF.BDCHAVE AND C115.BDORDEMIC = MOVINF.BDORDEMIC)
           ) C115
      LEFT OUTER JOIN VEF_BASE_TTABTIPOTRAN TIP ON (TIP.BDCODTRAN = C115.BDCODTRAN)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERCOL ON (TERCOL.BDCODTER = C115.BDCODTERCOLETA)
      LEFT OUTER JOIN TCIDADE CIDCOL  ON (CIDCOL.BDCODCID  = C115.BDCODCIDCOLETA)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERENTG ON (TERENTG.BDCODTER = C115.BDCODTERENTREGA)
      LEFT OUTER JOIN TCIDADE CIDENTG ON (CIDENTG.BDCODCID = C115.BDCODCIDENTREGA);

      /*****************************************************************************
       *                                   C116                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :prarquivo BDID,
             LPAD(C116.BDCODEMP, 6, '0')||'.1.'||LPAD(C116.BDCHAVE, 10, '0')||'.C100.C110.'||LPAD(C116.BDORDEMIC, 6, '0')||'.C116.'||LPAD(C116.bdordemcupom, 6, '0'),
             'C116',
             '|C116'||
             '|'||COALESCE(C116.bdmodelo, '')||                                                  -- COD_MOD - Modelo
             '|'||COALESCE(c116.bdcodequipsat, '')||                                             -- NR_SAT  - Codigo do Equipamento
             '|'||COALESCE((RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C116.bdchavecfe)), 44, ' ')), NULL, '')|| -- CHV_CFE - Chave NF-e
             '|'||COALESCE(C116.bdnumcupom, '')||                                                -- NUM_CFE - N?mero do documento
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(C116.bddatadoc, 'DDMMYYYY')), '')|| -- DT_DOC  - Data do documento
             '|'
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
            FROM (
                  SELECT M.BDCODEMP, M.BDCHAVE
                  FROM VEF_EMP_TMOVSAI M
                  WHERE M.BDCODEMP = :PRCODEMP
                  AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = M.BDCODEMP AND DF.BDCHAVESAI = M.BDCHAVE))
                 ) MOV
            JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
           ) MOVINF
      JOIN VEF_EMP_TMOVSAICUPOMREF C116 ON(C116.BDCODEMP = MOVINF.BDCODEMP AND C116.BDCHAVE = MOVINF.BDCHAVE AND C116.BDORDEMIC = MOVINF.BDORDEMIC);
      
      /*****************************************************************************
       *                                   C140                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PAR.BDCODEMP, 6, '0')||'.1.'||LPAD(PAR.BDCHAVE, 10, '0')||'.C100.C140.'||LPAD(PAR.BDORDEMPAR, 6, '0'),
             'C140',
             '|C140'||
             '|'||COALESCE(MOV.BDEMITENTE, '')|| --IND_EMIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN '00'
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN '01'
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN '02'
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN '03'
                       ELSE '99'
                  END|| --IND_TIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN ''
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN ''
                       ELSE COALESCE(PAR.BDOUTROSPAR, '')
                  END|| --DESC_TIT
             '|'||CASE WHEN (COALESCE(PAR.BDDUPLICATAPAR, '') <> '') THEN PAR.BDDUPLICATAPAR
                       WHEN (COALESCE(PAR.BDCHEQUEPAR,    '') <> '') THEN PAR.BDCHEQUEPAR
                       WHEN (COALESCE(PAR.BDPROMISSPAR,   '') <> '') THEN PAR.BDPROMISSPAR
                       WHEN (COALESCE(PAR.BDRECIBOPAR,   '')  <> '') THEN PAR.BDOUTROSPAR
                       ELSE COALESCE(PAR.BDOUTROSPAR, MOV.BDNUMDOCINI)
                  END|| --NUM_TIT
             '|'||COALESCE(TOTPAR.BDQTDPAR, '')|| --QTD_PARC
             '|'||REPLACE(COALESCE(TOTPAR.BDVALORDUPLICATA, 0.00), '.', ',')|| --VL_TIT
             '|'
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDEMITENTE,
                   SAI.BDVALORNOTA, SAI.BDNUMDOCINI
            FROM ( SELECT SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDEMITENTE,
                   SAI.BDVALORNOTA, SAI.BDNUMDOCINI
            FROM VEF_EMP_TMOVSAI SAI
            LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = SAI.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
            WHERE SAI.BDCODEMP = :PRCODEMP
            AND SAI.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, SAI.BDCHAVE)
            AND SAI.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND SAI.BDMODELO = 1 --somente modelo 1
            AND SAI.BDCODSITNF NOT IN(2, 3, 4, 5, 10 , 11)
                   AND NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = SAI.BDCODEMP AND DF.BDCHAVESAI = SAI.BDCHAVE))
            ) SAI ) MOV
      JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE AND PAR.BDORDEMPAR = (SELECT MIN(P.BDORDEMPAR) FROM VEF_EMP_TMOVSAIPAR P WHERE P.BDCODEMP = PAR.BDCODEMP AND P.BDCHAVE = PAR.BDCHAVE))
      LEFT OUTER JOIN (
                       SELECT P.BDCODEMP, P.BDCHAVE, COUNT(P.BDORDEMPAR) BDQTDPAR, SUM(COALESCE(P.BDVALORPAR, 0)) BDVALORDUPLICATA
                       FROM VEF_EMP_TMOVSAIPAR P
                       GROUP BY P.BDCODEMP, P.BDCHAVE
                      ) TOTPAR ON(TOTPAR.BDCODEMP = PAR.BDCODEMP AND TOTPAR.BDCHAVE = PAR.BDCHAVE);
    
      /*****************************************************************************
       *                                   C141                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(PAR.BDCODEMP, 6, '0')||'.1.'||LPAD(PAR.BDCHAVE, 10, '0')||'.C100.C140.C141.'||LPAD(PAR.BDORDEMPAR, 6, '0'),
             'C141',
             '|C141'||
             '|'||PAR.BDORDEMPAR|| --NUM_PARC
             '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(PAR.BDDATAVENCTOPAR, 'DDMMYYYY')), '')|| --DT_VCTO
             '|'||REPLACE(COALESCE(PAR.BDVALORPAR, 0.00), '.', ',')|| --VL_PARC
             '|'
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDEMITENTE,
                   SAI.BDVALORNOTA, SAI.BDNUMDOCINI
            FROM VEF_EMP_TMOVSAI SAI
            LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = SAI.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
            WHERE SAI.BDCODEMP = :PRCODEMP
            AND SAI.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, SAI.BDCHAVE)
            AND SAI.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND SAI.BDMODELO = 1 --somente modelo 1
            AND SAI.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
            AND NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = SAI.BDCODEMP AND DF.BDCHAVESAI = SAI.BDCHAVE))
           ) MOV
      JOIN VEF_EMP_TMOVSAIPAR PAR ON (PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE)
      ORDER BY PAR.BDORDEMPAR;

      /*****************************************************************************
       *                                   C160                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
      SELECT :PRARQUIVO BDID,
             LPAD(C160.BDCODEMP, 6, '0')||'.1.'||LPAD(C160.BDCHAVE, 10, '0')||'.C100.C160.0000000001',
             'C160',
             '|C160'||
             '|'||(SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, C160.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))|| --COD_PART
             '|'||COALESCE(REPLACE(C160.BDPLACAID, '-', ''), '')|| --VEIC_ID
             '|'||REPLACE(COALESCE(CAST(C160.BDQTDVOLTRAN AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --QTD_VOL
             '|'||REPLACE(COALESCE(CAST(C160.BDPESOBRUTO AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --PESO_BRT
             '|'||REPLACE(COALESCE(CAST(C160.BDPESOLIQUIDO AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --PESO_LIQ
             '|'||COALESCE(UF.BDSIGLAUF, '')|| --UD_ID
             '|', C160.BDCODTER
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE
            FROM VEF_EMP_TMOVSAI SAI
            LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = SAI.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
            WHERE SAI.BDCODEMP = :PRCODEMP
            AND SAI.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, SAI.BDCHAVE)
            AND SAI.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND SAI.BDMODELO IN(1, 4)
            AND SAI.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
            AND NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = SAI.BDCODEMP AND DF.BDCHAVESAI = SAI.BDCHAVE))
           ) MOV
      JOIN VEF_EMP_TMOVSAIVLTRAN C160 ON(C160.BDCODEMP = MOV.BDCODEMP AND C160.BDCHAVE = MOV.BDCHAVE)
      LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C160.BDCODUF)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = C160.BDCODTER)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                            ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp ON (TerEmp.bdcodter = C160.BDCODTER);

      SELECT MIN(t.bdCHAVE) AS bdCHAVEMIN, MAX(t.bdCHAVE) AS bdCHAVEMAX
      FROM VEF_EMP_TMOVSAI t
      LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = T.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
      WHERE t.bdCODEMP = :PRCODEMP
        AND T.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, T.BDCHAVE)
        AND t.bdREFLAN BETWEEN EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0') AND EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0')
      INTO :wCHAVEMIN, :wCHAVEMAX;

      /*****************************************************************************
       *                                   C170                                    *
       ****************************************************************************/
      SETORDEMSEQUENCIAL_STR(:PRCODEMP);
    
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD, BDCODNAT, BDCODFATCON, BDCHAVE, BDCREDITO, BDANOCREDITO, BDCODPLAPADRAO, BDCREDITOREF, BDCREDITOPLAPADRAOREF, BDCTALON)
      SELECT  :PRARQUIVO BDID,
             LPAD(SAI.BDCODEMP, 6, '0')||'.1.'||LPAD(SAI.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0'),
              'C170' BDREG,
              '|C170'||
              --'|'||GETORDEMSEQUENCIAL_STR(PRO.BDCHAVE,PRO.BDCODEMP)|| --NUM_ITEM
     --#184470 - Exportação sped fiscal - ordenação dos produtos igual ao XML
              '|'||COALESCE(PRO.BDORDEMPROORIG, CAST(GETORDEMSEQUENCIAL_STR(PRO.BDCHAVE,PRO.BDCODEMP) AS INTEGER) +
                (SELECT COALESCE(MAX(PROSAI.BDORDEMPROORIG),0) FROM VEF_EMP_TMOVPROSAI AS PROSAI WHERE PROSAI.bdcodemp = SAI.BDCODEMP AND PROSAI.BDCHAVE = SAI.BDCHAVE))|| --NUM_ITEM
              --#Alt:21967. Quando a empresa não possuía o respectivo produto vinculado o registro estava levando vazio. Quando isso acontecer foi
              --tratado para levar a informação do produto Único. Esse tratamento é feito para o código e a descrição.
              --'|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')), COALESCE(VINC.BDCODPROD,''), COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
              --'|'||TRIM(REPLACE(COALESCE(VINC.BDDESCPROD, ''), '|', ''))|| --DESCR_COMPL
              '|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')),
                       IIF(((VINC.BDCODPROD IS NULL) OR (COALESCE(VINC.BDCODPROD,'') = '')),COALESCE(PROD_UNICO.BDCODPROD,''),COALESCE(VINC.BDCODPROD,'')),
                       COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
              '|'||TRIM(REPLACE(IIF(((VINC.BDDESCPROD IS NULL) OR (VINC.BDDESCPROD = '')),
                                    COALESCE(PROD_UNICO.BDDESCRICAOUNICA,''),
                                    COALESCE(VINC.BDDESCPROD, '')), '|', ''))|| --DESCR_COMPL
              '|'||REPLACE(CAST(COALESCE(PRO.BDQTDITEM, 0.00) AS NUMERIC(15, 5)), '.', ',')|| --QTD
              '|'||COALESCE(IIF(((Coalesce(UN_FC.BDAPEUNIMED,UN.BDAPEUNIMED) IS NULL) OR (Coalesce(UN_FC.BDAPEUNIMED,UN.BDAPEUNIMED) = '')), UN_REF.BDAPEUNIMED, Coalesce(UN_FC.BDAPEUNIMED,UN.BDAPEUNIMED)), '')|| --UNID
              '|'||REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ',')|| --VL_ITEM
              '|'||REPLACE(COALESCE(PRO.BDVLRDESC, 0.00), '.', ',')|| --VL_DESC
              '|'||IIF((UPPER(PRO.BDMOVFISICO) = 'TRUE'), 0, 1)|| --IND_MOV
              '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
              '|'||COALESCE(SUBSTRING(SAI.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
              '|'||COALESCE(SAI.BDCODNAT, '')|| --COD_NAT
              '|'||REPLACE(COALESCE(PRO.BDBCICMS, ''), '.', ',')|| --VL_BC_ICMS
              '|'||REPLACE(CAST(COALESCE(PRO.BDALIQICMS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
              '|'||REPLACE(COALESCE(PRO.BDVLRICMS, 0.00) + IIF(:WFCPOP = 'TRUE',COALESCE(PRO.BDVLRFCP,0.00), 0.00), '.', ',')|| --VL_ICMS
              '|'||REPLACE(COALESCE(PRO.BDBCST, 0.00), '.', ',')||   --VL_BC_ICMS_ST
              '|'||REPLACE(CAST(COALESCE(PRO.BDALIQST, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ST
              '|'||REPLACE(COALESCE(PRO.BDVLRST, 0.00)  + IIF(SAI.BDREFLAN >= 201901,COALESCE(PRO.BDFCPRETIDO,0.00),0.00)
                     /*COALESCE(IIF(SAI.BDREFLAN >= 201901,(SELECT BDRETORNO FROM SP_GET_FCP(1,PRO.BDFCPRETIDO,ICMS.BDCSTICMS, SAI.BDCODNAT)),0.00),0.00) + --Soma FCP_ST
                     COALESCE(IIF(SAI.BDREFLAN >= 201901,(SELECT BDRETORNO FROM SP_GET_FCP(2,PRO.BDFCPRETIDO,ICMS.BDCSTICMS, SAI.BDCODNAT)),0.00),0.00)   --Soma FCP_RET*/
                     , '.', ',')||  --VL_ICMS_ST
              '|'|| --IND_APUR
              '|'||IIF(IPI.BDCODCSTIPI IS NULL, '', LPAD(COALESCE(IPI.BDCODEXPCSTIPI, ''), 2, 0))|| --CST_IPI
              '|'|| --COD_ENQ
              '|'||REPLACE(COALESCE(PRO.BDBCIPI, 0.00), '.', ',')|| --VL_BC_IPI
              '|'||REPLACE(CAST(COALESCE(PRO.BDALIQIPI, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_IPI
              '|'||REPLACE(COALESCE(PRO.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
              '|'||COALESCE(PIS.BDCSTPIS, '')|| --CST_PIS
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE','',REPLACE(CAST(COALESCE(PRO.BDBCPIS, 0.00) AS DM_NUMERIC_15_2), '.', ','))|| --VL_BC_PIS
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE','',REPLACE(CAST(COALESCE(PRO.BDALIQPIS, 0.00) AS dm_numeric_7_4_aliq), '.', ','))|| --ALIQ_PIS
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(COALESCE(PRO.BDBCPIS, 0.000), '.', ','),'')|| --QUANT_BC_PIS
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(CAST(COALESCE(PRO.BDALIQPIS, 0.00) AS dm_numeric_7_4_aliq),'.', ',') ,'')|| --ALIQ_PIS(em reais)
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(CAST(COALESCE(PRO.BDBCPIS, 0.00) * COALESCE(PRO.BDALIQPIS, 0.00) AS DM_NUMERIC_15_2), '.', ','),REPLACE(COALESCE(PRO.BDVLRPIS, 0.00), '.', ','))|| --VL_PIS
              '|'||COALESCE(COF.BDCSTCOF, '')|| --CST_COFINS
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE','',REPLACE(CAST(COALESCE(PRO.BDBCCOFINS, 0.00) AS DM_NUMERIC_15_2), '.', ','))|| --VL_BC_COFINS
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE','',REPLACE(CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS dm_numeric_7_4_aliq), '.', ','))|| --ALIQ_COFINS
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE',REPLACE(COALESCE(PRO.BDBCCOFINS, 0.000), '.', ','),'')|| --QUANT_BC_COFINS
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE',REPLACE(CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS dm_numeric_7_4_aliq), '.', ',') ,'')|| --ALIQ_COFINS(em reais)
              '|'||iif(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE',REPLACE(CAST(COALESCE(PRO.BDBCCOFINS, 0.00) * CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS dm_numeric_7_4_aliq) AS DM_NUMERIC_15_2), '.', ','),REPLACE(COALESCE(PRO.BDVLRCOFINS, 0.00), '.', ','))|| --VL_COFINS
              --'|'||COALESCE(PRO.BDCODCTA, '')|| --COD_CTA
              '|'||COALESCE((CASE ConfSPED.bdTIPOEXPCONTA
                               WHEN '0' THEN COALESCE(CCL.BDCODTPLA, CCLRAT.BDCODTPLA)
                               WHEN '1' THEN COALESCE(CCL.BDCTALON, CCLRAT.BDCTALON)
                               WHEN '2' THEN COALESCE(CCL.BDAPECTA, CCLRAT.BDAPECTA)
                             ELSE COALESCE(CCLEP.bdCTALON,CCDERATP.bdCTALON) END), '')||
              IIF((:PRDTINI >= '01/01/2019'),'|'|| REPLACE(COALESCE(PRO.BDVLRABATNT, 0.00), '.', ','), '')|| --VL_ABAT_NT
              '|', PRO.BDCODPROD, SAI.BDCODNAT, PRO.BDCODFATCON,
              SAI.BDCHAVE, COALESCE(CCL.BDCODTPLA,CCLRAT.BDCODTPLA) BDCREDITO,
              COALESCE(COALESCE(CCLE.BDANO, CCDERAT.BDANO), CAST(SUBSTRING(SAI.BDREFLAN FROM 1 FOR 4) AS INTEGER)) BDANOCREDITO,
              COALESCE(PRO.BDCODPLAPADRAO, COALESCE(LAN.BDCODPLAPADRAO, LANRAT.BDCODPLAPADRAO)) BDCODPLAPADRAO, COALESCE(CCLEP.BDCODTPLAREF, CCDERATP.BDCODTPLAREF) BDCREDITOREF,
              COALESCE(CCLEP.BDCODPLAPADRAOREF, CCDERATP.BDCODPLAPADRAOREF) BDCREDITOPLAPADRAOREF, COALESCE(CCL.BDCTALON, CCLRAT.BDCTALON) BDCTALON
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, I.BDCODNAT, SAI.BDREFLAN
            FROM (
                  SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN
                  FROM (
                        SELECT M.BDCODEMP, M.BDCHAVE, M.BDREFLAN
                        FROM VEF_EMP_TMOVSAI M
                        LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = M.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
                        LEFT OUTER JOIN VEF_EMP_TMOVSTC176 c176 ON (c176.bdCODEMP = m.bdCODEMP AND c176.bdCHAVE = m.bdCHAVE)
                        LEFT OUTER JOIN VEF_EMP_TMOVPROSAIC177 c177 ON (c177.bdCODEMP = m.bdCODEMP AND c177.bdCHAVE = m.bdCHAVE)
                        LEFT OUTER JOIN VEF_BASE_TTABINFAD56 AD56 ON (AD56.BDORDEM56 = C177.BDCODINFAD)
                        WHERE M.BDCODEMP = :PRCODEMP
                          AND M.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, M.BDCHAVE)
                          AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                          AND (M.BDMODELO IN (1, 4, 55, 65, 100) OR :WSEGREGACAO = 'TRUE')
                          /*AND ((NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0))) OR --Próprio -- Al.: #126204 - Deve exportar independentemente do emitente...
                                (m.bdREFLAN <= 201812) OR 
                                ((m.bdREFLAN >= 201901) AND ((m.bdMODELO NOT IN (55, 65)) OR -- Alt.: #126126 - Apenas deve obrigar C176 e C177 para os modelos 55 e 65...
                                                             ((c176.bdCHAVE IS NOT NULL) OR (c177.bdCHAVE IS NOT NULL)))) ) */ /* Alt.: #89669 - A partir de 2019 vai levar também caso exista registro C177, independente do emitente */
                          AND ((m.bdMODELO NOT IN (55, 65)) OR -- Alt.: #126126 - Caso a nota nao seja modelo 55 ou 65, exporta...
                               (M.BDEMITENTE = 1) OR -- Alt.: #126126 - Caso a nota seja emissao de terceiros, exporta...
                               (:WSEGREGACAO = 'TRUE') OR
                               (:PREXPORTARC170EMISSAOPROPRIA = 'TRUE') OR
                               ((c176.bdCHAVE IS NOT NULL) OR
                                ((IIF((:wEXPINCENTFISCAIS IS NULL) OR (:wEXPINCENTFISCAIS <> 'TRUE'), c177.bdCHAVE, Coalesce(c177.bdCHAVE,1)) IS NOT NULL) AND
                                 (((M.BDREFLAN <= 201812) AND (C177.BDCODSELOIPI > 0)) OR /* Layout até 2018 */
                                  ((M.BDREFLAN >= 201901))))) ) /* Layout a partir de 2019 */
                          AND M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                          AND ((:wTERMOACORDO IS NULL) OR (:wTERMOACORDO <> 'TRUE') OR (M.BDMODELO <> 65))
                        GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDREFLAN
                       ) MOV
                 ) SAI
            JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
            WHERE NOT EXISTS( SELECT DF.BDCODEMP FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP DF WHERE (DF.BDCODEMP = SAI.BDCODEMP AND DF.BDCHAVESAI = SAI.BDCHAVE AND DF.BDORDEMSAI = I.BDORDEM))
            GROUP BY SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, I.BDCODNAT, SAI.BDREFLAN
           ) SAI
      JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE AND I.BDORDEM = SAI.BDORDEM)
      JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
      /*Produto*/
      LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
      LEFT OUTER JOIN TUNIDADEMEDIDA UN ON(UN.BDCODUNIMED = VINC.BDCODUNIMED)                   
      LEFT OUTER JOIN TFATCONV FC ON (FC.BDCODEMP = PRO.BDCODEMP AND FC.BDCODPROD = PRO.BDCODPROD AND FC.BDCODFATCON = PRO.BDCODFATCON)  
      LEFT OUTER JOIN TUNIDADEMEDIDA UN_FC ON(UN_FC.BDCODUNIMED = FC.BDCODUNIMED)
      LEFT OUTER JOIN TCADPRO PROD_UNICO ON(PROD_UNICO.BDCODPROD = PRO.BDCODPROD) --#Alt:21967.
      --LEFT OUTER JOIN TCADPRO_REF REF ON(REF.BDCODEMP = PRO.BDCODEMP AND REF.BDCODPROD = PRO.BDCODPROD AND ((UN.BDAPEUNIMED IS NULL) OR (UN.BDAPEUNIMED = '')))
      /*Produto por referência*/
      LEFT OUTER JOIN TCADPRO_VINC VINC_REF ON(VINC_REF.BDCODEMP = PRO.BDCODEMP AND VINC_REF.BDCODPROD = PRO.BDCODPROD)
      LEFT OUTER JOIN TUNIDADEMEDIDA UN_REF ON(UN_REF.BDCODUNIMED = VINC_REF.BDCODUNIMED)
      LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS)
      LEFT OUTER JOIN VEF_BASE_TTABCSTIPI IPI ON(IPI.BDCODCSTIPI = PRO.BDCODCSTIPI)
      LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON(PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
      LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON(COF.BDCODCSTCOF = PRO.BDCODCSTCOF)
      LEFT OUTER JOIN VEF_EMP_TMOVPROSAIC177 c177 ON (c177.bdCODEMP = pro.bdCODEMP AND c177.bdCHAVE = pro.bdCHAVE AND c177.BDORDEM = pro.BDORDEM and c177.BDORDEMPRO = pro.BDORDEMPRO)
      LEFT OUTER JOIN VEF_EMP_TMOVSAI S ON (S.BDCODEMP = PRO.BDCODEMP AND S.BDCHAVE = PRO.BDCHAVE)
      -- Alt.: #87095 #92148 #89325 #92407 #100955 #121349 - Ajustes para levar a conta referencial na exportação do lançamento
      LEFT OUTER JOIN VW_INT_SPEDICMS_REF ConfSPED ON (ConfSPED.bdCODEMP = sai.bdCODEMP)
      LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, l.bdCODPLAPADRAO, MIN(l.bdCREDITO) bdCREDITO
                       FROM TOL_VEF_EMP_TMOVSAI t
                       LEFT OUTER JOIN VSUC_EMPRESAS_TLAN l ON (l.bdCODEMP = t.bdCODEMPSUC AND l.bdCHAVE = t.bdCHAVE)
                       WHERE t.bdFORMULA LIKE '%NAT%LAN(%)' -- Alt.: #92219 - Apenas contas do valor contábil...
                         AND l.bdCREDITO IS NOT NULL -- Alt.: #120050 - Para apenas retornar quando a contabilização tiver uma conta informada, quando tem desconto a conta do desconto vem primeiro...
                         AND t.bdCODEMP = :PRCODEMP
                         AND t.bdCHAVESAI BETWEEN :wCHAVEMIN AND :wCHAVEMAX
                       GROUP BY t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, l.bdCODPLAPADRAO) LAN ON (lan.bdCODEMP = i.bdCODEMP AND lan.bdCHAVESAI = i.bdCHAVE AND lan.bdORDEM = i.bdORDEM)
      LEFT OUTER JOIN PLANOS_TPLA CCL ON(COALESCE(PRO.BDCODPLAPADRAO, LAN.BDCODPLAPADRAO) = CCL.BDCODPLAPADRAO AND COALESCE(PRO.BDCODTPLA, LAN.BDCREDITO) = CCL.BDCODTPLA)
      LEFT OUTER JOIN PLANOS_TPLA_ECF CCLE ON (CCLE.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF
                                               AND CCLE.BDANO = (SELECT FIRST 1 BDANO
                                                                 FROM PLANOS_TPLA_ECF
                                                                 WHERE CAST(BDANO || '01' AS INTEGER) <= SAI.BDREFLAN
                                                                   AND BDCODTPLAREF IS NOT NULL
                                                                   AND CCLE.BDCODPLAPADRAO = BDCODPLAPADRAO
                                                                   AND CCLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF
                                                                   AND CCLE.BDCODTPLA = BDCODTPLA
                                                                 ORDER BY BDANO DESC)
                                               AND CCLE.BDCODPLAPADRAO = CCL.BDCODPLAPADRAO AND CCLE.BDCODTPLA = CCL.BDCODTPLA)
     LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO CCLEP ON (CCLE.BDCODPLAPADRAOREF = CCLEP.BDCODPLAPADRAOREF AND CCLE.BDCODTPLAREF = CCLEP.BDCODTPLAREF)
     LEFT OUTER JOIN  (SELECT BDCODEMP,BDCODEMPSUC,BDCHAVELAN,BDORDEM,MIN(BDCHAVE) BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP,BDCODEMPSUC,BDCHAVELAN,BDORDEM) TOLRAT ON (TOLRAT.BDCODEMP = PRO.BDCODEMP AND TOLRAT.BDCHAVELAN = PRO.BDCHAVE AND TOLRAT.BDORDEM = PRO.BDORDEM)
     LEFT OUTER JOIN VSUC_EMPRESAS_TLAN LANRAT ON (LANRAT.BDCODEMP = TOLRAT.BDCODEMPSUC AND LANRAT.BDCHAVE = TOLRAT.BDCHAVE) -- Alt.: #168897 - Deve buscar a contabilizacao nas empresas SCP...
     LEFT OUTER JOIN PLANOS_TPLA CCLRAT ON (LANRAT.BDCODPLAPADRAO = CCLRAT.BDCODPLAPADRAO AND LANRAT.BDCREDITO = CCLRAT.BDCODTPLA)
     LEFT OUTER JOIN PLANOS_TPLA_ECF CCDERAT ON (CCDERAT.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF
                                             AND CCDERAT.BDANO =(SELECT FIRST 1 BDANO 
                                                                 FROM PLANOS_TPLA_ECF 
                                                                 WHERE CAST(BDANO || '01' AS INTEGER) <= LANRAT.BDREFERENCIA
                                                                   AND BDCODTPLAREF IS NOT NULL
                                                                   AND CCDERAT.BDCODPLAPADRAO = BDCODPLAPADRAO
                                                                   AND CCDERAT.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF
                                                                   AND CCDERAT.BDCODTPLA = BDCODTPLA 
                                                                 ORDER BY BDANO DESC)
                                             AND CCDERAT.BDCODPLAPADRAO = CCLRAT.BDCODPLAPADRAO AND CCDERAT.BDCODTPLA = CCLRAT.BDCODTPLA)
     LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO CCDERATP ON (CCDERAT.BDCODPLAPADRAOREF = CCDERATP.BDCODPLAPADRAOREF AND CCDERAT.BDCODTPLAREF = CCDERATP.BDCODTPLAREF)
      -- Alt.: #87095 #92148 #89325 #92407 #100955 #121349 - Fim
      WHERE (((S.bdMODELO NOT IN (55, 65)) OR (:WSEGREGACAO = 'TRUE')) OR -- Alt.: #126126 - Caso a nota nao seja modelo 55 ou 65, exporta...
             (S.BDEMITENTE = 1) OR -- Alt.: #126126 - Caso a nota seja emissao de terceiros, exporta...
             (:PREXPORTARC170EMISSAOPROPRIA = 'TRUE') OR
             (:PREXPORTARC170EMISSAOPROPRIA = 'TRUE') OR
             ((C177.BDCODEMP IS NOT NULL) or NOT ((:wEXPINCENTFISCAIS IS NULL) OR (:wEXPINCENTFISCAIS <> 'TRUE')) ) OR -- Alt.: #126126 - Caso a nota seja emissao de terceiros, exporta...
             (EXISTS(SELECT FIRST 1 C176.BDCODEMP FROM VEF_EMP_TMOVSTC176 c176 -- #128174 - Levar apenas quando o C176 ou C177 forem do lançamento de produto que vai levar
                     WHERE (c176.bdCODEMP = pro.bdCODEMP AND
                            c176.bdCHAVE = pro.bdCHAVE AND
                            c176.BDORDEM = pro.BDORDEM and
                            c176.BDORDEMPRO = pro.BDORDEMPRO) ))); -- Alt.: #126126 - Caso a nota possua C176 ou C177, exporta...

    END

  /*Estourou o tamanho máximo da sp, então a exportação dos registros C176,177,C178,C190,C195 e 197 estão na SP abaixo.
    Exportação de novos registros devem ser feitos na nova SP_EXPORTA_BLOCOC_SAI_AUX*/
  EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_SAI_AUX(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, :PRTIPOEXPCODPART, :PRPERFIL, :PRSESSAOSEGREG);
END
^

--Larissa - 18/03/2021 - Sped Fiscal - Notas de serviços #143666
CREATE OR ALTER procedure SP_EXPORTA_BLOCOC_SER (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRTIPOEXPCODPART integer,
    PRCODPLAPADRAOREF integer)
as
declare variable WCHAVEMIN integer;
declare variable WCHAVEMAX integer;
BEGIN
  /*****************************************************************************
   *------------------------->>SERVIÇOS EMITIDOS<<------------------------------*
   ****************************************************************************/


      /*Criada opção para exportar serviços emitidos (A100/A170) para o Sped fiscal
    como sendo movimento de saída modelo 1 (C100/C170/C190), não afeta notas conjugadas.*/


   /*****************************************************************************
   *                                   C100                                    *
   ****************************************************************************/
  insert into TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
  select  :PRARQUIVO BDID,
          lpad(SER.BDCODEMP, 6, '0')||'.2.'||lpad(SER.BDCHAVE, 10, '0')||'.C100',
          'C100' BDREG,
          ('|C100|1|'||'0'||--IND_EMIT
          '|'||iif(S.BDCODSITNF in (2, 3, 4, 5), '', (select BDRETORNO from SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, S.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO)))||--COD_PART
          '|'||'01'||--COD_MOD
          '|'||lpad(S.BDCODSITNF, 2, '0')||--COD_SIT
          '|'||substring(S.BDSERIE from 1 for 3)||--SER
          '|'||S.BDNUMDOCINI||--NUM_DOC
          '|'||''||--CHV_NFE
          '|'||iif(S.BDCODSITNF in (2, 3, 4, 5), '', (select BDDATA from SP_PARSE_DATE(S.BDDATAEMISSAO, 'DDMMYYYY')))||--DT_DOC
          '|'||iif(S.BDCODSITNF in (2, 3, 4, 5) or ((select BDDATA from SP_PARSE_DATE(S.BDDT_EXE_SERV, 'YYYYMM')) > (select BDDATA from SP_PARSE_DATE(S.BDDATAEMISSAO, 'YYYYMM'))), '', (select BDDATA from SP_PARSE_DATE(S.BDDT_EXE_SERV, 'DDMMYYYY')))||--DT_E_S
          '|'||iif(S.BDCODSITNF in (2, 3, 4, 5), '', replace(SER.BDVALORNOTA, '.', ','))||--VL_DOC
          '|'||iif(S.BDCODSITNF in (2, 3, 4, 5), '', iif(((S.BDCONDPGTO = '2') and (S.BDDATAEMISSAO < '07/01/2012')), '9', S.BDCONDPGTO))|| --IND_PGTO
          '|'||iif(S.bdcodsitnf in (2, 3, 4, 5), '', replace(SER.BDDESCONTONOTA, '.', ',')) ||--VL_DESC
          '|'||'0,00'||--VL_ABAT_NT
          '|'||iif(S.BDCODSITNF in (2, 3, 4, 5), '', replace(coalesce(SER.BDVALORNOTA, 0.00), '.', ','))||--VL_MERC
          '|'||'2'||--IND_FRT
          '|'||'0,00'||--VL_FRT
          '|'||'0,00'||--VL_SEG
          '|'||'0,00'||--VL_OUT_DA
          '|'||'0,00'||--VL_BC_ICMS
          '|'||'0,00'||--VL_ICMS
          '|'||'0,00'||--VL_BC_ICMS_ST
          '|'||'0,00'||--VL_ICMS_ST
          '|'||'0,00'||--VL_IPI
          '|'||iif(S.BDCODSITNF in (2, 3, 4, 5), '', replace(coalesce(SER.BDVL_PIS, 0.00), '.', ','))||      --VL_PIS
          '|'||iif(S.BDCODSITNF in (2, 3, 4, 5), '', replace(coalesce(SER.BDVL_COFINS, 0.00), '.', ','))||   --VL_COFINS
          '|'||'0,00'||--VL_PIS_ST
          '|'||'0,00'|| --VL_COFINS_ST
                '|') BDLINHA, iif(((S.BDCODSITNF in (2, 3, 4, 5))), null, S.BDCODTER) BDCODTER
  from (
        select MOV.BDCODEMP, MOV.BDCHAVE,
               sum(coalesce(A170.BDVL_COFINS, 0.00)) BDVL_COFINS,
               sum(coalesce(A170.BDVL_PIS, 0.00)) BDVL_PIS,
               sum(coalesce(ITENS.BDVLRCONTAB, 0.00)) BDVALORNOTA,
               sum(coalesce(ITENS.BDDESCONTO, 0.00)) BDDESCONTONOTA
        from (
              select S.BDCODEMP, S.BDCHAVE, S.BDREFLAN
              from (
                    select  S.BDCODEMP, S.BDCHAVE, S.BDREFLAN
                    from  VEF_EMP_TMOVSER S
                    where S.BDCODEMP = :PRCODEMP
                    and S.BDDATAEMISSAO between :PRDTINI and :PRDTFIM
                    and S.BDTIPLAN = 0 --Somente lançamentos emitidos
                    and S.BDTIPOLANINCLU <> 135 -- Não trazer lançamentos de serviço conjugados aos lançamentos de saída
                    and s.bdcodsitnf not in (10, 11)
                    ) S
             ) MOV
        left outer join VEF_EMP_TMOVSERITENS ITENS on(ITENS.BDCODEMP = MOV.BDCODEMP and ITENS.BDCHAVE = MOV.BDCHAVE)
        left outer join VEF_EMP_TA170 A170 on(A170.BDCODEMP = MOV.BDCODEMP and A170.BDCHAVE = MOV.BDCHAVE AND A170.BDORDEM = ITENS.BDORDEM)
        group by MOV.BDCODEMP, MOV.BDCHAVE
       ) SER
  join VEF_EMP_TMOVSER S on(S.BDCODEMP = SER.BDCODEMP and S.BDCHAVE = SER.BDCHAVE)
  left outer join VW_TTERCEIRO_SIMPLES TER on(TER.BDCODTER = S.BDCODTER)
  left outer join (
                   select tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   from (
                         select t.bdcodemp, t.bdcodter,
                                coalesce(
                                         (select first 1 e.bdcodigo from TTERCEIRO_EMP e where (e.bdcodemp = t.bdcodemp) and (e.bdcodter = t.bdcodter) and (e.bdreferencia <= (select BDDATA from SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) order by e.bdreferencia desc),
                                         (select first 1 e.bdcodigo from TTERCEIRO_EMP e where (e.bdcodemp = t.bdcodemp) and (e.bdcodter = t.bdcodter) order by e.bdreferencia)
                                        ) BDCODIGO
                         from (select te.bdcodemp, te.bdcodter from TTERCEIRO_EMP te where (te.bdcodemp = :PRCODEMP) group by te.bdcodemp, te.bdcodter) t
                        ) tt
                   left outer join TTERCEIRO_EMP ee on ee.bdcodemp = tt.bdcodemp and ee.bdcodter = tt.bdcodter and ee.bdcodigo = tt.bdcodigo
                  ) TerEmp on (TerEmp.bdcodter = S.bdcodter);

    select min(t.bdCHAVE) as bdCHAVEMIN, max(t.bdCHAVE) as bdCHAVEMAX
      from VEF_EMP_TMOVSER t
      where t.bdCODEMP = :PRCODEMP
        and t.bdREFLAN between extract(year from :prDTINI)||lpad(extract(month from :prDTINI),2,'0') and extract(year from :prDTINI)||lpad(extract(month from :prDTINI),2,'0')
      into :wCHAVEMIN, :wCHAVEMAX;

   /*****************************************************************************
   *                                   C170                                    *
   ****************************************************************************/

      insert into TEXPORTACAO_SPED(BDPRODSER, BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD, BDCODNAT, BDCHAVE, BDCREDITO, BDANOCREDITO, BDCODPLAPADRAO, BDCREDITOREF, BDCREDITOPLAPADRAOREF, BDCTALON)
      select  'TRUE', :PRARQUIVO BDID,
             lpad(SER.BDCODEMP, 6, '0')||'.2.'||lpad(SER.BDCHAVE, 10, '0')||'.C100.C170.'||lpad(A170.BDORDEM, 6, '0')||'.'||lpad(A170.BDNUM_ITEM, 6, '0'),
              'C170' BDREG,
              '|C170'||
              '|'||'1'|| --NUM_ITEM
              '|'||COALESCE(VINC.BDCODSAIDA,'')|| --COD_ITEM
              '|'||trim(replace(iif(((VINC.BDDESCPROD is null) or (VINC.BDDESCPROD = '')), coalesce(PROD_UNICO.BDDESCRICAOUNICA,''),
                        coalesce(VINC.BDDESCPROD, '')), '|', ''))|| --DESCR_COMPL
              '|'||'1'|| --QTD
              '|'||'UN'|| --UNID
              '|'||replace(coalesce(A170.BDVL_ITEM, 0.00), '.', ',')|| --VL_ITEM
              '|'||replace(coalesce(A170.BDVL_DESC, 0.00), '.', ',')|| --VL_DESC
              '|'||'1'|| --IND_MOV
              '|'||'090'|| --CST_ICMS
              '|'||coalesce(substring(SER.BDCODNAT from 1 for 4), '')|| --CFOP
              '|'||coalesce(SER.BDCODNAT, '')|| --COD_NAT
              '|'||'0,00'|| --VL_BC_ICMS
              '|'||'0,00'|| --ALIQ_ICMS
              '|'||'0,00'|| --VL_ICMS
              '|'||'0,00'||   --VL_BC_ICMS_ST
              '|'||'0,00'|| --ALIQ_ST
              '|'||'0,00'||  --VL_ICMS_ST
              '|'|| --IND_APUR
              '|'|| --CST_IPI
              '|'|| --COD_ENQ
              '|'||'0,00'|| --VL_BC_IPI
              '|'||'0,00'|| --ALIQ_IPI
              '|'||'0,00'|| --VL_IPI
              '|'||coalesce(PIS.BDCSTPIS, '')|| --CST_PIS
              '|'||replace(cast(coalesce(A170.BDVL_BC_PIS, 0.00) as DM_NUMERIC_15_2), '.', ',')|| --VL_BC_PIS
              '|'||replace(cast(coalesce(A170.BDALIQ_PIS, 0.00) as dm_numeric_7_4_aliq), '.', ',')|| --ALIQ_PIS
              '|'||'0,00'|| --QUANT_BC_PIS
              '|'||'0,00'|| --ALIQ_PIS(em reais)
              '|'||replace(cast(coalesce(A170.BDVL_PIS, 0.00) as DM_NUMERIC_15_2), '.', ',')|| --VL_PIS
              '|'||coalesce(COF.BDCSTCOF, '')|| --CST_COFINS
              '|'||replace(cast(coalesce(A170.BDVL_BC_COFINS, 0.00) as DM_NUMERIC_15_2), '.', ',')|| --VL_BC_COFINS
              '|'||replace(cast(coalesce(A170.BDALIQ_COFINS, 0.00) as dm_numeric_7_4_aliq), '.', ',')|| --ALIQ_COFINS
              '|'||'0,00'|| --QUANT_BC_COFINS
              '|'||'0,00'|| --ALIQ_COFINS(em reais)
              '|'||replace(cast(coalesce(A170.BDVL_COFINS, 0.00) as DM_NUMERIC_15_2), '.', ',')|| --VL_COFINS
              '|'||coalesce((case ConfigSPED.bdTIPOEXPCONTA
                               when '0' then coalesce(CCL.BDCODTPLA, CCLRAT.BDCODTPLA)
                               when '1' then coalesce(CCL.BDCTALON, CCLRAT.BDCTALON)
                               when '2' then coalesce(CCL.BDAPECTA, CCLRAT.BDAPECTA)
                            else coalesce(CCLEP.bdCTALON,CCDERATP.bdCTALON) end), '')|| --COD_CTA
              '|'||'0,00'|| --VL_ABAT_NT
              '|', A170.BDCODPROD, SER.BDCODNAT, SER.BDCHAVE, COALESCE(CCL.BDCODTPLA,CCLRAT.BDCODTPLA) BDCREDITO,
              COALESCE(COALESCE(CCLE.BDANO, CCDERAT.BDANO), CAST(SUBSTRING(SER.BDREFLAN FROM 1 FOR 4) AS INTEGER)) BDANOCREDITO,
              COALESCE(A170.BDCODPLAPADRAO, COALESCE(LAN.BDCODPLAPADRAO, LANRAT.BDCODPLAPADRAO)) BDCODPLAPADRAO, COALESCE(CCLEP.BDCODTPLAREF, CCDERATP.BDCODTPLAREF) BDCREDITOREF,
              COALESCE(CCLEP.BDCODPLAPADRAOREF, CCDERATP.BDCODPLAPADRAOREF) BDCREDITOPLAPADRAOREF, COALESCE(CCL.BDCTALON, CCLRAT.BDCTALON) BDCTALON
        from (
            select SER.BDCODEMP, SER.BDCHAVE, ITENS.BDORDEM, ITENS.BDCODNAT, SER.BDREFLAN
            from (
                  select MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN
                  from (
                        select S.BDCODEMP, S.BDCHAVE, S.BDREFLAN
                        from VEF_EMP_TMOVSER S
                        where S.BDCODEMP = :PRCODEMP
                        and S.BDDATAEMISSAO between :PRDTINI and :PRDTFIM
                        and S.BDTIPLAN = 0 --Somente lançamentos emitidos
                        and S.BDTIPOLANINCLU <> 135 -- Não trazer lançamentos de serviço conjugados aos lançamentos de saída
                        and s.bdcodsitnf not in (10, 11)
                        group by S.BDCODEMP, S.BDCHAVE, S.BDREFLAN
                       ) MOV
                 ) SER
            join VEF_EMP_TMOVSERITENS ITENS on(ITENS.BDCODEMP = SER.BDCODEMP and ITENS.BDCHAVE = SER.BDCHAVE)
        ) SER
        join VEF_EMP_TA170 A170 on (A170.BDCODEMP = SER.BDCODEMP and A170.BDCHAVE = SER.BDCHAVE and A170.BDORDEM = SER.BDORDEM)
        left outer join TCADPRO_VINC VINC on(VINC.BDCODEMP = A170.BDCODEMP and VINC.BDCODPROD = A170.BDCODPROD)
        left outer join TCADPRO PROD_UNICO on(PROD_UNICO.BDCODPROD = A170.BDCODPROD)
        left outer join VW_INT_SPEDICMS_REF ConfigSPED on (ConfigSPED.bdCODEMP = SER.bdCODEMP)
        left outer join VEF_BASE_TTABCSTPIS PIS ON(PIS.BDCODCSTPIS = A170.BDCODCSTPIS)
        LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON(COF.BDCODCSTCOF = A170.BDCODCSTCOF)
        /*Conta Contábil*/
        left outer join  (select BDCODEMP, BDCHAVELAN, BDORDEM, min(BDCHAVE) BDCHAVE from TOL_VEF_EMP_TMOVRATSER group by BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT on (TOLRAT.BDCODEMP = A170.BDCODEMP and TOLRAT.BDCHAVELAN = A170.BDCHAVE and TOLRAT.BDORDEM = A170.BDORDEM)
        left outer join VSUC_EMPRESAS_TLAN LANRAT on (LANRAT.BDCODEMP = TOLRAT.BDCODEMP and LANRAT.BDCHAVE = TOLRAT.BDCHAVE)
        left outer join PLANOS_TPLA CCLRAT on (LANRAT.BDCODPLAPADRAO = CCLRAT.BDCODPLAPADRAO and LANRAT.BDCREDITO = CCLRAT.BDCODTPLA)
        left outer join (select t.bdCODEMP, t.bdCHAVESER, t.bdORDEM, l.bdCODPLAPADRAO, min(l.bdCREDITO) bdCREDITO
                       from TOL_VEF_EMP_TMOVSER t
                       left outer join VSUC_EMPRESAS_TLAN l on (l.bdCODEMP = t.bdCODEMP and l.bdCHAVE = t.bdCHAVE)
                       where t.bdFORMULA like '%NAT%LAN(%)'
                         and l.bdCREDITO is not null
                         and t.bdCODEMP = :PRCODEMP
                         and t.bdCHAVESER between :wCHAVEMIN and :wCHAVEMAX
                       group by t.bdCODEMP, t.bdCHAVESER, t.bdORDEM, l.bdCODPLAPADRAO) LAN on (lan.bdCODEMP = SER.bdCODEMP and lan.bdCHAVESER = SER.bdCHAVE and lan.bdORDEM = SER.bdORDEM)
      left outer join PLANOS_TPLA CCL on(coalesce(A170.BDCODPLAPADRAO, LAN.BDCODPLAPADRAO) = CCL.BDCODPLAPADRAO and coalesce(A170.BDCODTPLA, LAN.BDCREDITO) = CCL.BDCODTPLA)
      left outer join PLANOS_TPLA_ECF CCLE on (CCLE.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF
                                               and CCLE.BDANO = (select first 1 BDANO
                                                                 from PLANOS_TPLA_ECF
                                                                 where cast(BDANO || '01' as integer) <= SER.BDREFLAN
                                                                   and BDCODTPLAREF is not null
                                                                   and CCLE.BDCODPLAPADRAO = BDCODPLAPADRAO
                                                                   and CCLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF
                                                                   and CCLE.BDCODTPLA = BDCODTPLA
                                                                 order by BDANO desc)
                                               and CCLE.BDCODPLAPADRAO = CCL.BDCODPLAPADRAO and CCLE.BDCODTPLA = CCL.BDCODTPLA)
     left outer join PLANOS_TPLA_ECF_PADRAO CCLEP on (CCLE.BDCODPLAPADRAOREF = CCLEP.BDCODPLAPADRAOREF and CCLE.BDCODTPLAREF = CCLEP.BDCODTPLAREF)
     left outer join PLANOS_TPLA_ECF CCDERAT on (CCDERAT.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF
                                             and CCDERAT.BDANO =(select first 1 BDANO 
                                                                 from PLANOS_TPLA_ECF 
                                                                 where cast(BDANO || '01' as integer) <= LANRAT.BDREFERENCIA
                                                                   and BDCODTPLAREF is not null
                                                                   and CCDERAT.BDCODPLAPADRAO = BDCODPLAPADRAO
                                                                   and CCDERAT.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF
                                                                   and CCDERAT.BDCODTPLA = BDCODTPLA 
                                                                 order by BDANO desc)
                                             and CCDERAT.BDCODPLAPADRAO = CCLRAT.BDCODPLAPADRAO and CCDERAT.BDCODTPLA = CCLRAT.BDCODTPLA)
     left outer join PLANOS_TPLA_ECF_PADRAO CCDERATP on (CCDERAT.BDCODPLAPADRAOREF = CCDERATP.BDCODPLAPADRAOREF and CCDERAT.BDCODTPLAREF = CCDERATP.BDCODTPLAREF);
     

  /*****************************************************************************
   *                                   C190                                    *
   ****************************************************************************/
  insert into TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  select :PRARQUIVO BDID,
        lpad(SER.BDCODEMP, 6, '0')||'.2.'||lpad(SER.BDCHAVE, 10, '0')||'.C100.C190.'||SER.BDCODNAT||'.'||'0,00'||'.'||'090',
        'C190' BDREG,
        '|C190'||
        '|'||'090'|| --CST_ICMS
        '|'||coalesce(SER.BDCODNAT, '')|| --CFOP
        '|'||'0,00'|| --ALIQ_ICMS
        '|'||replace(cast(coalesce(SER.BDVL_ITEM, 0.00) as DM_NUMERIC_15_2), '.', ',')|| --VL_OPR
        '|'||'0,00'|| --VL_BC_ICMS
        '|'||'0,00'|| --VL_ICMS
        '|'||'0,00'|| --VL_BC_ICMS_ST
        '|'||'0,00'|| --VL_ICMS_ST
        '|'||'0,00'|| -- VL_RED_BC
        '|'||'0,00'|| --VL_IPI
        '|'|| --COD_OBS
        '|'
  from (
        select SER.BDCODEMP, SER.BDCHAVE, SER.BDCODNAT, SER.BDVL_ITEM
        from (
              select SER.BDCODEMP, SER.BDCHAVE,
                     coalesce(SER.BDCODNAT, 0) BDCODNAT,
                     sum(coalesce(A170.BDVL_ITEM, 0)) BDVL_ITEM
              from (
                    select S.BDCODEMP, S.BDCHAVE, ITENS.BDORDEM, substring(ITENS.BDCODNAT from 1 for 4) BDCODNAT
                    from VEF_EMP_TMOVSER S
                    join VEF_EMP_TMOVSERITENS ITENS on (ITENS.BDCODEMP = S.BDCODEMP and ITENS.BDCHAVE = S.BDCHAVE)
                    where S.BDCODEMP = :PRCODEMP
                        and S.BDDATAEMISSAO between :PRDTINI and :PRDTFIM
                        and S.BDTIPLAN = 0 --Somente lançamentos emitidos
                        and S.BDTIPOLANINCLU <> 135 -- Não trazer lançamentos de serviço conjugados aos lançamentos de saída
                        and s.bdcodsitnf not in (10, 11)
                   ) SER
              join VEF_EMP_TA170 A170 on(A170.BDCODEMP = SER.BDCODEMP and A170.BDCHAVE = SER.BDCHAVE and A170.BDORDEM = SER.BDORDEM)
              GROUP BY SER.BDCODEMP, SER.BDCHAVE, SER.BDCODNAT
        ) SER )SER ;
END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOK290 (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO varchar(260),
    PRINDK010 integer)
AS
BEGIN
  /*****************************************************************************
   *           REGISTRO K290: PRODUÇÃO CONJUNTA – ORDEM DE PRODUÇÃO            *
   ****************************************************************************/
  if (:prindk010 <> 2) then
  BEGIN
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         LPAD(k290.bdCODEMP, 6, '0')||'.K290'||'.'||LPAD(k290.bdCHAVE, 10, '0') AS bdCHAVEREG,
         'K290' AS bdREG,
         (                                                                      -- Nº Campo      Descrição                                     Tipo Tam Dec Obrig.
          '|K290'||                                                             -- 01 REG        Texto fixo contendo "K290"                    C     4  -   O
          '|'||Coalesce((SELECT bdDATA FROM SP_PARSE_DATE(k290.bdDATAINI, 'DDMMYYYY')), '')|| -- 02 DT_INI_OP  Data de início da ordem de produção           N     8  -   OC
          '|'||Coalesce((SELECT bdDATA FROM SP_PARSE_DATE(k290.bdDATAFIN, 'DDMMYYYY')), '')|| -- 03 DT_FIN_OP  Data de conclusão da ordem de produção        N     8  -   OC
          '|'||TRIM(k290.bdORDEMPROD)||                                         -- 04 COD_DOC_OP Código de identificação da ordem de produção  C    30  -   OC
          '|'
          ) AS bdLINHA
  FROM VEF_EMP_TMOVK290 k290
  WHERE k290.bdCODEMP = :prCODEMP
    AND (k290.bdreflan BETWEEN (CAST((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM')) AS INTEGER)) AND
                               (CAST((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')) AS INTEGER)));
  END

  /*****************************************************************************
   *            REGISTRO K291: PRODUÇÃO CONJUNTA - ITENS PRODUZIDOS            *
   ****************************************************************************/
  if (:prindk010 <> 2) then
  BEGIN
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCODPROD, bdCHAVEREG, bdREG, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         k291.bdCODPROD,
         LPAD(k291.bdCODEMP, 6, '0')||'.K290'||'.'||LPAD(k290.bdCHAVE, 10, '0')||'.K291.'||LPAD(k291.bdCHAVE, 10, '0')||'.'||LPAD(k291.bdORDEM, 10, '0') AS bdCHAVEREG,
         'K291' AS bdREG,
         (                                             -- Nº Campo    Descrição                                            Tipo Tam Dec Obrig.
          '|K291'||                                    -- 01 REG      Texto fixo contendo "K291"                           C     4  -   O 
          '|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')),
                       IIF(((VINC.BDCODPROD IS NULL) OR (COALESCE(VINC.BDCODPROD,'') = '')),COALESCE(k291.BDCODPROD,''),COALESCE(VINC.BDCODPROD,'')),
                       COALESCE(VINC.BDCODSAIDA,''))|| -- 02 COD_ITEM Código do item produzido (campo 02 do Registro 0200) C    60  -   O
          '|'||REPLACE(COALESCE(CAST(k291.bdQTDITEM AS NUMERIC(15,3)), 0.00), '.', ',')|| -- 03 QTD      Quantidade de produção acabada                       N    -   3   O
          '|'
          ) AS bdLINHA
  FROM VEF_EMP_TMOVK290 k290
  JOIN VEF_EMP_TMOVK291 k291 ON (k291.bdCODEMP = k290.bdCODEMP AND k291.bdCHAVE = k290.bdCHAVE) 
  JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = k291.BDCODEMP AND VINC.BDCODPROD = k291.BDCODPROD)
  WHERE k290.bdCODEMP = :prCODEMP
    AND (k290.bdreflan BETWEEN (CAST((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM')) AS INTEGER)) AND
                               (CAST((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')) AS INTEGER)));
  END

  /*****************************************************************************
   *           REGISTRO K292: PRODUÇÃO CONJUNTA – INSUMOS CONSUMIDOS           *
   ****************************************************************************/
  IF (:prindk010 = 1) then
  BEGIN
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCODPROD, bdCHAVEREG, bdREG, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         k292.bdCODPROD,
         LPAD(k292.bdCODEMP, 6, '0')||'.K290'||'.'||LPAD(k290.bdCHAVE, 10, '0')||'.K292.'||LPAD(k292.bdCHAVE, 10, '0')||'.'||LPAD(k292.bdORDEM, 10, '0') AS bdCHAVEREG,
         'K292' AS bdREG,
         (                                             -- Nº Campo    Descrição                                                         Tipo Tam Dec Obrig.
          '|K292'||                                    -- 01 REG      Texto fixo contendo "K292"                                        C     4  -   O  
          '|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')),
                       IIF(((VINC.BDCODPROD IS NULL) OR (COALESCE(VINC.BDCODPROD,'') = '')),COALESCE(k292.BDCODPROD,''),COALESCE(VINC.BDCODPROD,'')),
                       COALESCE(VINC.BDCODSAIDA,''))|| -- 02 COD_ITEM Código do insumo/componente consumido (campo 02 do Registro 0200) C    60  -   O
          '|'||REPLACE(COALESCE(CAST(k292.bdQTDITEM AS NUMERIC(15,3)), 0.00), '.', ',')|| -- 03 QTD      Quantidade consumida                                              N    -   3   O
          '|'
          ) AS bdLINHA
  FROM VEF_EMP_TMOVK290 k290
  JOIN VEF_EMP_TMOVK292 k292 ON (k292.bdCODEMP = k290.bdCODEMP AND k292.bdCHAVE = k290.bdCHAVE) 
  JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = k292.BDCODEMP AND VINC.BDCODPROD = k292.BDCODPROD)
  WHERE k290.bdCODEMP = :prCODEMP
   AND (k290.bdreflan BETWEEN (CAST((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM')) AS INTEGER)) AND
                              (CAST((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')) AS INTEGER)));
END
END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_BLOCOK300 (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO varchar(260),
    PRINDK010 integer)
AS
BEGIN
  /***************************************************************************************************
   *            REGISTRO K300: PRODUÇÃO CONJUNTA – INDUSTRIALIZAÇÃO EFETUADA POR TERCEIROS           *
   ***************************************************************************************************/
  if (:prindk010 <> 2) then
  BEGIN
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         LPAD(k300.bdCODEMP, 6, '0')||'.K300.'||LPAD(k300.bdCHAVE, 10, '0') AS bdCHAVEREG,
         'K300' AS bdREG,
         (                                                                   -- Nº Campo   Descrição                                               Tipo Tam Dec Obrig.
          '|K300'||                                                          -- 01 REG     Texto fixo contendo "K300"                              C    4   -   O
          '|'||(SELECT bdDATA FROM SP_PARSE_DATE(k300.bdDATA, 'DDMMYYYY'))|| -- 02 DT_PROD Data do reconhecimento da produção ocorrida no terceiro N    8   -   O
          '|'
          ) AS bdLINHA
  FROM VEF_EMP_TMOVK300 k300
  WHERE k300.bdCODEMP = :prCODEMP
    AND k300.bdDATA BETWEEN :prDTINI AND :prDTFIM;
  END

  /***************************************************************************************************
   *  REGISTRO K301: PRODUÇÃO CONJUNTA – INDUSTRIALIZAÇÃO EFETUADA POR TERCEIROS – ITENS PRODUZIDOS  *
   ***************************************************************************************************/
  if (:prindk010 <> 2) then
  BEGIN
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCODPROD, bdCHAVEREG, bdREG, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         k301.bdCODPROD,
         LPAD(k301.bdCODEMP, 6, '0')||'.K300.'||LPAD(k300.bdCHAVE, 10, '0')||'.K301.'||LPAD(k301.bdCHAVE, 10, '0')||'.'||LPAD(k301.bdORDEM, 10, '0') AS bdCHAVEREG,
         'K301' AS bdREG,
         (                                             -- Nº Campo    Descrição                                            Tipo Tam Dec Obrig.
          '|K301'||                                    -- 01 REG      Texto fixo contendo "K301"                           C     4  -   O
          '|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')),
                       IIF(((VINC.BDCODPROD IS NULL) OR (COALESCE(VINC.BDCODPROD,'') = '')),COALESCE(k301.BDCODPROD,''),COALESCE(VINC.BDCODPROD,'')),
                       COALESCE(VINC.BDCODSAIDA,''))|| -- 02 COD_ITEM Código do insumo (campo 02 do Registro 0200) C    60  -   O
          '|'||REPLACE(COALESCE(CAST(k301.bdQTDITEM AS NUMERIC(15,3)), 0.00), '.', ',')|| -- 03 QTD      Quantidade produzida                                 N    -   3   O
          '|'
          ) AS bdLINHA
  FROM VEF_EMP_TMOVK300 k300
  JOIN VEF_EMP_TMOVK301 k301 ON (k301.bdCODEMP = k300.bdCODEMP AND k301.bdCHAVE = k300.bdCHAVE)  
  JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = k301.BDCODEMP AND VINC.BDCODPROD = k301.BDCODPROD)
  WHERE k300.bdCODEMP = :prCODEMP
    AND k300.bdDATA BETWEEN :prDTINI AND :prDTFIM;
   END

  /***************************************************************************************************
   * REGISTRO K302: PRODUÇÃO CONJUNTA – INDUSTRIALIZAÇÃO EFETUADA POR TERCEIROS – INSUMOS CONSUMIDOS *
   ***************************************************************************************************/
  if (:prindk010 = 1) then
  BEGIN
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCODPROD, bdCHAVEREG, bdREG, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         k302.bdCODPROD,
         LPAD(k302.bdCODEMP, 6, '0')||'.K300.'||LPAD(k300.bdCHAVE, 10, '0')||'.K302.'||LPAD(k302.bdCHAVE, 10, '0')||'.'||LPAD(k302.bdORDEM, 10, '0') AS bdCHAVEREG,
         'K302' AS bdREG,
         (                                             -- Nº Campo    Descrição                                    Tipo Tam Dec Obrig.
          '|K302'||                                    -- 01 REG      Texto fixo contendo "K302"                   C     4  -   O 
          '|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')),
                       IIF(((VINC.BDCODPROD IS NULL) OR (COALESCE(VINC.BDCODPROD,'') = '')),COALESCE(k302.BDCODPROD,''),COALESCE(VINC.BDCODPROD,'')),
                       COALESCE(VINC.BDCODSAIDA,''))|| -- 02 COD_ITEM Código do insumo (campo 02 do Registro 0200) C    60  -   O
          '|'||REPLACE(COALESCE(CAST(k302.bdQTDITEM AS NUMERIC(15,3)), 0.00), '.', ',')|| -- 03 QTD      Quantidade consumida                         N    -   3   O
          '|'
          ) AS bdLINHA
  FROM VEF_EMP_TMOVK300 k300
  JOIN VEF_EMP_TMOVK302 k302 ON (k302.bdCODEMP = k300.bdCODEMP AND k302.bdCHAVE = k300.bdCHAVE)  
  JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = k302.BDCODEMP AND VINC.BDCODPROD = k302.BDCODPROD)
  WHERE k300.bdCODEMP = :prCODEMP
    AND k300.bdDATA BETWEEN :prDTINI AND :prDTFIM;
END
END
^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOK (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRVALIDAREXPORTACAO DM_BOOLEAN,
    PRARQUIVO varchar(260),
    PRINDK010 integer)
as
declare variable WLINHA blob sub_type 1 segment size 200;
BEGIN
  DELETE FROM TEXPORTACAO_SPED WHERE BDID = :prARQUIVO;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT bdDATA FROM SP_PARSE_DATE(:prDTFIM, 'YYYYMM')));

  /* REGISTROS K290, K291 e K292 */
  EXECUTE PROCEDURE SP_EXPORTA_BLOCOK290 (:prCODEMP, :prDTINI, :prDTFIM, :prARQUIVO, :prINDK010);

  /* REGISTROS K300, K301 e K302 */
  EXECUTE PROCEDURE SP_EXPORTA_BLOCOK300 (:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, :prINDK010);

  /*****************************************************************************
   *                           EXPORTANDO ARQUIVO                              *
   ****************************************************************************/
  OPENARQ(:prARQUIVO,:PRCODEMP);

  FOR SELECT e.bdLINHA
      FROM TEXPORTACAO_SPED e
      WHERE e.bdID = :prARQUIVO
      ORDER BY e.bdCHAVEREG
      INTO :wLinha
  DO
    BEGIN
      WRITELNOA(:wLinha,:PRCODEMP);
    END

  CLOSEARQ(:prARQUIVO,:PRCODEMP);
END
^

--Larissa - 18/03/2021 - Sped Fiscal - Notas de serviços #143666
CREATE OR ALTER procedure SP_VALIDA_EXP_SER (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(100))
AS
BEGIN
    
   /*****************************************************************************
   *            CHECAGEM DAS INCONSISTÊNCIAS DOS SERVIÇOS EMITIDOS              *
   ****************************************************************************/

   --Feito separado pois a procedure SP_VALIDA_EXPORTACAO_SPED estava muito cheia

   /***********************  C100  *************************/

   /*Sem Produto!*/
   INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
      SELECT :PRARQUIVO, SER.BDCHAVE, 18, 2, 'C100'
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE, I.BDORDEM
            FROM VEF_EMP_TMOVSER S
            JOIN VEF_EMP_TMOVSERITENS I ON(I.BDCODEMP = S.BDCODEMP AND I.BDCHAVE = S.BDCHAVE)
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND S.BDCODSITNF NOT IN(2, 3, 4, 5)
            AND BDTIPLAN = 0 --Somente lançamentos emitidos
            AND BDTIPOLANINCLU <> 135 -- Não trazer lançamentos de serviço conjugados aos lançamentos de saída
            ) SER
      LEFT OUTER JOIN VEF_EMP_TA170 A170 ON(A170.BDCODEMP = SER.BDCODEMP AND A170.BDCHAVE = SER.BDCHAVE)
      WHERE A170.BDNUM_ITEM IS NULL;
         
  /* Com indicador de pagamento a prazo sem informação de parcelas. */
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
      SELECT :PRARQUIVO, SER.BDCHAVE, 19, 2, 'C100'
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE, I.BDORDEM
            FROM VEF_EMP_TMOVSER S
            JOIN VEF_EMP_TMOVSERITENS I ON(I.BDCODEMP = S.BDCODEMP AND I.BDCHAVE = S.BDCHAVE)
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND S.BDCODSITNF NOT IN(2, 3, 4, 5)
            AND S.BDTIPLAN = 0 --Somente lançamentos emitidos
            AND S.BDTIPOLANINCLU <> 135 -- Não trazer lançamentos de serviço conjugados aos lançamentos de saída
            AND S.BDCONDPGTO = 1 /*Prazo*/
            ) SER
      LEFT OUTER JOIN VEF_EMP_TMOVSERPAR PAR ON(PAR.BDCODEMP = SER.BDCODEMP AND PAR.BDCHAVE = SER.BDCHAVE)
      WHERE PAR.BDORDEMPAR IS NULL;


   /***********************  C170  *************************/

   /*Produto sem vinculo com a empresa!*/
   INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODPROD, BDCODINCO, BDMOVIMENTO, BDREG)
   SELECT :PRARQUIVO, SER.BDCHAVE, SER.BDORDEM, A170.BDNUM_ITEM, VINC.BDCODPROD, 2, 2, 'C170'
      FROM (
            SELECT SER.BDCODEMP, SER.BDCHAVE, I.BDORDEM
            FROM (
                  SELECT SER.BDCODEMP, SER.BDCHAVE
                  FROM (
                        SELECT S.BDCODEMP, S.BDCHAVE
                        FROM VEF_EMP_TMOVSER S
                        WHERE S.BDCODEMP = :PRCODEMP
                        AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                        AND S.BDCODSITNF NOT IN(2, 3, 4, 5)
                        AND S.BDTIPLAN = 0 --Somente lançamentos emitidos
                        AND S.BDTIPOLANINCLU <> 135 -- Não trazer lançamentos de serviço conjugados aos lançamentos de saída
                       ) SER
                 ) SER
            JOIN VEF_EMP_TMOVSERITENS I ON(I.BDCODEMP = SER.BDCODEMP AND I.BDCHAVE = SER.BDCHAVE)
           ) SER
      JOIN VEF_EMP_TA170 A170 ON(A170.BDCODEMP = SER.BDCODEMP AND A170.BDCHAVE = SER.BDCHAVE AND A170.BDORDEM = SER.BDORDEM)
      JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = A170.BDCODEMP AND VINC.BDCODPROD = A170.BDCODPROD AND ((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')));

END
^

create or alter procedure SP_VALIDA_EXPORTACAO_SPED (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(100),
    PRBLOCO char(4),
    PRCHECASER varchar(5) = 'FALSE')
as
declare variable WENTRADA integer;
declare variable WSAIDA integer;
declare variable WSQL varchar(250);
declare variable WQTD integer;
declare variable WQTDMAX integer;
declare variable WTERMOACORDO varchar(5);
declare variable WCHAVE INTEGER;
BEGIN
  wEntrada = 0;
  wSaida   = 1;
  PRBLOCO  = UPPER(:PRBLOCO);

  wSQL =          'SELECT COUNT(S.BDORDEMINCO) BDQTD ';
  wSQL = :wSQL || 'FROM TEXPORTACAO_SPED_INCO S ';
  wSQL = :wSQL || 'WHERE S.BDID = '''||:PRARQUIVO||''' ';
  wSQL = :wSQL || 'GROUP BY S.BDID';

  SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_LIM_INCO_EXPORTACAO') FROM RDB$DATABASE INTO :wQtdMax;
  SETORDEMSEQUENCIAL(0);  

  IF (:PRBLOCO = 'C100') THEN
    BEGIN
      -- ALt.: "Alteracoes para o Sped do Rio Grande do Sul" - Quando tiver o parametro termo marcado, nao deve exportar as notas do modelo 65...
      SELECT FIRST 1 bdTERMOACORDO
      FROM VEF_INT_TSPEDICMS
      WHERE bdREFERENCIA >= 202007 -- Alt.: "Alterações para o Sped do Rio Grande do Sul" - Apenas para empresas do RS, a partir de 07/2020...
        AND bdCODEMP = :prCODEMP
        AND bdREFERENCIA <= EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0')
      ORDER BY bdREFERENCIA DESC
      INTO :wTERMOACORDO;
    
      IF (wTERMOACORDO = 'TRUE') THEN 
        BEGIN
          SELECT FIRST 1 COUNT(m.bdCODEMP)
          FROM VEF_EMP_TMOVSAI m
          JOIN VEF_EMP_TMOVPROSAI p ON (p.bdCODEMP = m.bdCODEMP AND p.bdCHAVE = m.bdCHAVE)
          WHERE m.bdMODELO IN (65)
            AND p.bdVLRICMS > 0
            AND m.bdCODEMP = :prCODEMP
            AND m.bdDATAEMISSAO BETWEEN :prDTINI AND :prDTFIM
          INTO :wQTD; -- Quando tiver lançamento modelo 65 e não tiver nenhum lançamento de E111, deve lançar uma inconsistência...
            
          IF (:wQTD > 0) THEN
            BEGIN
              SELECT COUNT(a.bdCODEMP)
              FROM VEF_EMP_TAJUICMSE111 a
              LEFT OUTER JOIN VEF_BASE_TTABAJUICMS t ON (t.bdCODAJUICMS = a.bdCODAJUICMS)
              WHERE a.bdCODEMP = :prCODEMP
                AND a.bdREFERENCIA = EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0')
                AND ((t.bdCODAJUPAD LIKE 'RS000500') OR (t.bdCODAJUPAD LIKE 'RS000565'))
              INTO :wQTD;
              
              /* 34 - Empresa com termo de acordo com o Estado, com notas modelo 65 sem lançamento do ajuste E111 do código RS000500! */
              IF (:wQTD = 0) THEN            
                INSERT INTO TEXPORTACAO_SPED_INCO(bdID, bdCHAVE, bdCODINCO, bdMOVIMENTO, bdREG) VALUES (:PRARQUIVO, NULL, 34, :wSaida, 'E111');
            END
        END
    
  /*****************************************************************************
   *                                   C113                                    *
   ****************************************************************************/
    
   IF (:PRDTINI > '12/31/2016') THEN
     BEGIN
       /*1 - Chave NFE inválida!*/
       INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
       SELECT :PRARQUIVO, C113.BDCHAVE, 1, :wEntrada, 'C113' /*Entrada*/
       FROM (
             SELECT MOVINF.BDCHAVE, MOVINF.BDCODEMP, (SELECT BDISVALID FROM SP_VALIDACHAVE_NFE(C113.BDCHAVENFE)) BDISVALID
             FROM (
                   SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
                   FROM (
                         SELECT M.BDCODEMP, M.BDCHAVE
                         FROM VEF_EMP_TMOVENT M
                         WHERE M.BDCODEMP = :PRCODEMP
                         AND M.BDMODELO IN (1, 4, 55, 100)
                         AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                        ) MOV
                   JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
                  ) MOVINF                                                                                                                                            /*Modelos: 55, 57*/
             JOIN VEF_EMP_TMOVENTDOCFREF C113 ON(C113.BDCODEMP = MOVINF.BDCODEMP AND C113.BDCHAVE = MOVINF.BDCHAVE AND C113.BDORDEMIC = MOVINF.BDORDEMIC AND C113.BDCODDOCFIS IN(30, 31))
            ) C113
       WHERE C113.BDISVALID = 'FALSE'
       UNION ALL
       SELECT :PRARQUIVO, C113.BDCHAVE, 1, :wSaida, 'C113' /*Saída*/
       FROM (
             SELECT MOVINF.BDCHAVE, MOVINF.BDCODEMP, (SELECT BDISVALID FROM SP_VALIDACHAVE_NFE(C113.BDCHAVENFE)) BDISVALID
             FROM (
                   SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
                   FROM (
                         SELECT M.BDCODEMP, M.BDCHAVE
                         FROM VEF_EMP_TMOVSAI M
                         WHERE M.BDCODEMP = :PRCODEMP
                         AND M.BDMODELO IN (1, 4, 55, 100)
                         AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                        ) MOV
                   JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
                  ) MOVINF                                                                                                                                            /*Modelos: 55, 57*/
             JOIN VEF_EMP_TMOVSAIDOCFREF C113 ON(C113.BDCODEMP = MOVINF.BDCODEMP AND C113.BDCHAVE = MOVINF.BDCHAVE AND C113.BDORDEMIC = MOVINF.BDORDEMIC AND C113.BDCODDOCFIS IN(30, 31))
            ) C113
       WHERE C113.BDISVALID = 'FALSE';
     END
      
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*****************************************************************************
   *                                   C170                                    *
   ****************************************************************************/
  /*2 - Produto sem vinculo com a empresa!*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODPROD, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ENT.BDCHAVE, ENT.BDORDEM, PRO.BDORDEMPRO, VINC.BDCODPROD, 2, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE, I.BDORDEM
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Próprio
                   ) MOV
             ) ENT
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
       ) ENT
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = ENT.BDORDEM)
  JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD AND ((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')))
  UNION ALL
  SELECT :PRARQUIVO, SAI.BDCHAVE, SAI.BDORDEM, PRO.BDORDEMPRO, VINC.BDCODPROD, 2, :wSaida, 'C170' /*Saída*/
  FROM (
        SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Próprio
                   ) MOV
             ) SAI
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
       ) SAI
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
  JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD AND ((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*3 - O valor total do desconto declarado no Registro C100 não confere com o somatório dos valores dos descontos declarados nos Registros C170.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, 3, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE, SUM(COALESCE(PRO.BDVLRDESC, 0) + COALESCE(PRO.BDVLRABATNT, 0)) BDVLRDESC
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE, I.BDORDEM
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) ENT
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = ENT.BDORDEM)
        GROUP BY ENT.BDCODEMP, ENT.BDCHAVE
       ) PRO
  JOIN VEF_EMP_TMOVENT LAN ON(LAN.BDCODEMP = PRO.BDCODEMP AND LAN.BDCHAVE = PRO.BDCHAVE)
  WHERE LAN.BDDESCONTONOTA <> PRO.BDVLRDESC
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, 3, :wSaida, 'C170' /*Saída*/
  FROM (
        SELECT SAI.BDCODEMP, SAI.BDCHAVE, SUM(COALESCE(PRO.BDVLRDESC, 0) + COALESCE(PRO.BDVLRABATNT, 0)) BDVLRDESC
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE, I.BDORDEM
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) SAI
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
        GROUP BY SAI.BDCODEMP, SAI.BDCHAVE
       ) PRO
  JOIN VEF_EMP_TMOVSAI LAN ON(LAN.BDCODEMP = PRO.BDCODEMP AND LAN.BDCHAVE = PRO.BDCHAVE)
  WHERE LAN.BDDESCONTONOTA <> PRO.BDVLRDESC;
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*4 - O valor declarado no campo Valor do PIS, no Registro C100, deve corresponder à soma dos valores declarados no mesmo campo dos Registros C170.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ITEM.BDCHAVE, 4, :wEntrada, 'C170' /*Entrada*/
  FROM (
        --Everton - 27/11/17 - Comentando apenas para garantir de que vai gerar a versão com a alteração abaixo corretamente.
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, C100.BDVLRTOTPIS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TC100ENT C100 ON(C100.BDCODEMP = MOV.BDCODEMP AND C100.BDCHAVE = MOV.BDCHAVE)
       ) ITEM
  JOIN (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, SUM(COALESCE(PRO.BDVLRPIS, 0)) BDVLRPISPROD
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE
       ) PRO ON(PRO.BDCODEMP = ITEM.BDCODEMP AND PRO.BDCHAVE = ITEM.BDCHAVE)
  WHERE ITEM.BDVLRTOTPIS <> PRO.BDVLRPISPROD
  UNION ALL
  SELECT :PRARQUIVO, ITEM.BDCHAVE, 4, :wSaida, 'C170' /*Saída*/
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, C100.BDVLRTOTPIS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TC100SAI C100 ON(C100.BDCODEMP = MOV.BDCODEMP AND C100.BDCHAVE = MOV.BDCHAVE)
       ) ITEM
  JOIN (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, SUM(COALESCE(PRO.BDVLRPIS, 0)) BDVLRPISPROD
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE
       ) PRO ON(PRO.BDCODEMP = ITEM.BDCODEMP AND PRO.BDCHAVE = ITEM.BDCHAVE)
  WHERE ITEM.BDVLRTOTPIS <> PRO.BDVLRPISPROD;
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*5 - O valor declarado no campo Valor do Cofins, no Registro C100, deve corresponder à soma dos valores declarados no mesmo campo dos Registros C170.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ITEM.BDCHAVE, 5, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, C100.BDVLRTOTCOFINS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TC100ENT C100 ON(C100.BDCODEMP = MOV.BDCODEMP AND C100.BDCHAVE = MOV.BDCHAVE)
       ) ITEM
  JOIN (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, SUM(COALESCE(PRO.BDVLRCOFINS, 0)) BDVLRCOFINSPROD
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE
       ) PRO ON(PRO.BDCODEMP = ITEM.BDCODEMP AND PRO.BDCHAVE = ITEM.BDCHAVE)
  WHERE ITEM.BDVLRTOTCOFINS <> PRO.BDVLRCOFINSPROD
  UNION ALL
  SELECT :PRARQUIVO, ITEM.BDCHAVE, 5, :wSaida, 'C170' /*Saída*/
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, C100.BDVLRTOTCOFINS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TC100SAI C100 ON(C100.BDCODEMP = MOV.BDCODEMP AND C100.BDCHAVE = MOV.BDCHAVE)
       ) ITEM
  JOIN (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, SUM(COALESCE(PRO.BDVLRCOFINS, 0)) BDVLRCOFINSPROD
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE
       ) PRO ON(PRO.BDCODEMP = ITEM.BDCODEMP AND PRO.BDCHAVE = ITEM.BDCHAVE)
  WHERE ITEM.BDVLRTOTCOFINS <> PRO.BDVLRCOFINSPROD;
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*6 - Quando o campo ALIQ_ICMS (Alíquota do ICMS) for preenchido com um valor maior que zero no Registro C170, os valores dos campos VL_BC_ICMS e VL_ICMS também devem ser maiores que zero.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 6, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 ((PRO.BDALIQICMS > 0) AND ((PRO.BDBCICMS IS NULL) OR (PRO.BDBCICMS = 0)) AND ((PRO.BDVLRICMS IS NULL) OR (PRO.BDVLRICMS = 0))))
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 6, :wSaida, 'C170' /*Saída*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 ((PRO.BDALIQICMS > 0) AND ((PRO.BDBCICMS IS NULL) OR (PRO.BDBCICMS = 0)) AND ((PRO.BDVLRICMS IS NULL) OR (PRO.BDVLRICMS = 0))));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*7 - O campo VL_BC_IPI (Valor da base de cálculo do IPI) e/ou VL_IPI (Valor do IPI) está(ão) inconsistente(s) no Registro C170. Observar: Os campos VL_BC_IPI e VL_IPI não devem ser maior que 0 (zero) quando a CST-IPI for diferente de: 00 e/ou 50.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 7, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTIPI NOT IN(1, 8) AND ((PRO.BDBCIPI > 0) OR (PRO.BDVLRIPI > 0)))
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 7, :wSaida, 'C170' /*Saída*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTIPI NOT IN(1, 8) AND ((PRO.BDBCIPI > 0) OR (PRO.BDVLRIPI > 0)));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*8 - Registro C170 se os dois últimos dígitos do Código da Situação Tributária (CST_ICMS) forem diferentes de: 30, 40, 41,50 e/ou 60.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 8, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTICMS = 1 AND (((PRO.BDBCICMS IS NULL) OR (PRO.BDBCICMS = 0)) OR
                                                           ((PRO.BDALIQICMS IS NULL) OR (PRO.BDALIQICMS = 0)) OR
                                                           ((PRO.BDVLRICMS IS NULL) OR (PRO.BDVLRICMS = 0))))
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 8, :wSaida, 'C170' /*Saída*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTICMS = 1 AND (((PRO.BDBCICMS IS NULL) OR (PRO.BDBCICMS = 0)) OR
                                                           ((PRO.BDALIQICMS IS NULL) OR (PRO.BDALIQICMS = 0)) OR
                                                           ((PRO.BDVLRICMS IS NULL) OR (PRO.BDVLRICMS = 0))));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*9 - O campo Base de IPI/aliquota/valor do IPI deve ser maior que 0 (zero) se o Campo CST_IPI estiver preenchido com CST´s representativos de receitas tributadas ou operações com direito a crédito: 00 (Entrada) e/ou 50 (Saídas).*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 9, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTIPI IN (1, 8) AND (((PRO.BDBCIPI IS NULL) OR (PRO.BDBCIPI = 0)) OR
                                                                ((PRO.BDALIQIPI IS NULL) OR (PRO.BDALIQIPI = 0)) OR
                                                                ((PRO.BDVLRIPI IS NULL) OR (PRO.BDVLRIPI = 0))))
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 9, :wSaida, 'C170' /*saída*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND
                                 PRO.BDCODCSTIPI IN (1, 8) AND (((PRO.BDBCIPI IS NULL) OR (PRO.BDBCIPI = 0)) OR
                                                                ((PRO.BDALIQIPI IS NULL) OR (PRO.BDALIQIPI = 0)) OR
                                                                ((PRO.BDVLRIPI IS NULL) OR (PRO.BDVLRIPI = 0))));
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*10 - Itens declarados com CFOP de ativo imobilizado devem ser declarados com o tipo do item igual a 08.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, C170.BDCHAVE, C170.BDORDEM, C170.BDORDEMPRO, 10, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, MOV.BDCODNAT,
               IIF(((VINC.BDCODTIPOSER IS NULL) OR (VINC.BDCODTIPOSER = 0)), UNICO.BDCODTIPOSER, VINC.BDCODTIPOSER) BDCODTIPOSER
        FROM (
              SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) MOV
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        JOIN TCADPRO UNICO ON(UNICO.BDCODPROD = PRO.BDCODPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
       ) C170
  WHERE C170.BDCODTIPOSER <> 9
  AND C170.BDCODNAT IN(1406, 1551, 2406, 2551)
  UNION ALL
  SELECT :PRARQUIVO, C170.BDCHAVE, C170.BDORDEM, C170.BDORDEMPRO, 10, :wSaida, 'C170' /*saída*/
  FROM (
        SELECT PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, MOV.BDCODNAT,
               IIF(((VINC.BDCODTIPOSER IS NULL) OR (VINC.BDCODTIPOSER = 0)), UNICO.BDCODTIPOSER, VINC.BDCODTIPOSER) BDCODTIPOSER
        FROM (
              SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) MOV
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        JOIN TCADPRO UNICO ON(UNICO.BDCODPROD = PRO.BDCODPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
       ) C170
  WHERE C170.BDCODTIPOSER <> 9
  AND C170.BDCODNAT IN(1406, 1551, 2406, 2551);
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*11 - Itens declarados com CFOP de uso e consumo devem ser declarados com o tipo do item igual a 07.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, C170.BDCHAVE, C170.BDORDEM, C170.BDORDEMPRO, 11, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, MOV.BDCODNAT,
               IIF(((VINC.BDCODTIPOSER IS NULL) OR (VINC.BDCODTIPOSER = 0)), UNICO.BDCODTIPOSER, VINC.BDCODTIPOSER) BDCODTIPOSER
        FROM (
              SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVENT M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) MOV
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        JOIN TCADPRO UNICO ON(UNICO.BDCODPROD = PRO.BDCODPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
       ) C170
  WHERE C170.BDCODTIPOSER <> 8
  AND C170.BDCODNAT IN(1407, 1556, 2407, 2556, 1653, 2653)
  UNION ALL
  SELECT :PRARQUIVO, C170.BDCHAVE, C170.BDORDEM, C170.BDORDEMPRO, 11, :wSaida, 'C170' /*saída*/
  FROM (
        SELECT PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, MOV.BDCODNAT,
               IIF(((VINC.BDCODTIPOSER IS NULL) OR (VINC.BDCODTIPOSER = 0)), UNICO.BDCODTIPOSER, VINC.BDCODTIPOSER) BDCODTIPOSER
        FROM (
              SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
              FROM (
                    SELECT M.BDCODEMP, M.BDCHAVE
                    FROM VEF_EMP_TMOVSAI M
                    WHERE M.BDCODEMP = :PRCODEMP
                    AND M.BDMODELO IN (1, 4, 55, 65, 100)
                    AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                   ) MOV
              JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
             ) MOV
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        JOIN TCADPRO UNICO ON(UNICO.BDCODPROD = PRO.BDCODPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
       ) C170
  WHERE C170.BDCODTIPOSER <> 8
  AND C170.BDCODNAT IN(1407, 1556, 2407, 2556, 1653, 2653);
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*12 - Deve ser informado se o Código da Situação Tributária referente ao IPI (CST_IPI) for igual a: 01,02,03,04,05
    13 - Deve ser informado se o Código da Situação Tributária referente ao IPI (CST_IPI) for igual a: 51,52,53,54,55*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 12, :wEntrada, 'C110' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND PRO.BDCODCSTIPI IN(2, 3, 4, 5, 6))
  LEFT OUTER JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
  WHERE INF.BDCHAVE IS NULL /*Não existe informação complementar para este lançamento*/
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 13, :wSaida, 'C110' /*saída*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM AND PRO.BDCODCSTIPI IN(9, 10, 11, 12, 13))
  LEFT OUTER JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
  WHERE INF.BDCHAVE IS NULL; /*Não existe informação complementar para este lançamento*/
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*14 - Normalmente deve ser informado se os dois últimos dígitos do Código da Situação Tributária referente ao ICMS (CST_ICMS) forem iguais a:
         20, 30, 40, 41, 50, 51 e/ou 70. Consulte a legislação do seu estado sobre a obrigatoriedade.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 14, :wEntrada, 'C110' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  LEFT OUTER JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
  WHERE INF.BDCHAVE IS NULL /*Não existe informação complementar para este lançamento*/
  AND SUBSTRING(CST.BDCSTICMS FROM 2 FOR 2) IN (20, 30, 40, 41, 50, 51, 70)
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 14, :wSaida, 'C110' /*saída*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  LEFT OUTER JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
  WHERE INF.BDCHAVE IS NULL /*Não existe informação complementar para este lançamento*/
  AND SUBSTRING(CST.BDCSTICMS FROM 2 FOR 2) IN (20, 30, 40, 41, 50, 51, 70);
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*15 - Divergência entre CST e CFOP em operação sujeita ao regime de substituição tributária no Registro C170. O CST deve possuir final 10,30,60 e 70 ou os códigos 201,202,203 e 500.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 15, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, I.BDCODNAT
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
  WHERE (((MOV.BDCODNAT >= 1401000) AND (MOV.BDCODNAT <= 1415000)) OR ((MOV.BDCODNAT >= 2401000) AND (MOV.BDCODNAT <= 2415000)))
  AND SUBSTRING(CST.BDCSTICMS FROM 2 FOR 2) NOT IN(10, 30, 60, 70)
  AND CST.BDCSTICMS NOT IN(201, 202, 203, 500);
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
    
  /*16 - Divergência entre CST e CFOP em operação de compra de material para uso ou consumo. Para CFOP´s de compra de material para uso ou consumo (1.556 e 2.556), o CST deve ter os 2º e 3º dígitos iguais a 90 – outras.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 16, :wEntrada, 'C170' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  JOIN VEF_BASE_TTABCSTICMS CST ON(CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
  WHERE MOV.BDCODNAT IN(1556, 2556)
  AND SUBSTRING(CST.BDCSTICMS FROM 2 FOR 2) <> '90';
    
  EXECUTE STATEMENT :wSQL INTO :wQtd;
  IF (:wQtd >= :wQtdMax) THEN
    EXIT;
    
  /*17 - Foram detectados CFOP(s) de energia elétrica, comunicação/telecomunicação e/ou transportes indevidamente declarado(s) no Registro C190.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 17, :wEntrada, 'C190' /*Entrada*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVENT M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO = 1
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND
                                       SUBSTRING(I.BDCODNAT FROM 1 FOR 4) IN(1207, 1153, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 2153, 2207, 2251, 2252, 2253, 2254, 2255, 2256, 2257,
                                                                             3207, 3251, 5153, 5207, 5251, 5252, 5253, 5254, 5255, 5256, 5257, 5258, 6153, 6207, 6251, 6252, 6253, 6254,
                                                                             6255, 6256, 6257, 6258, 7207, 7251, 1205, 1301, 1302, 1303, 1304, 1305, 1306, 2205, 2301, 2302, 2303, 2304,
                                                                             2305, 2306, 3205, 3301, 5205, 5301, 5302, 5303, 5304, 5305, 5306, 5307, 6205, 6301, 6302, 6303, 6304, 6305,
                                                                             6306, 6307, 7205, 7301, 1206, 1351, 1352, 1353, 1354, 1355, 1356, 1360, 1931, 1932, 2206, 2351, 2352, 2353,
                                                                             2354, 2355, 2356, 2931, 2932, 3206, 3351, 3352, 3353, 3354, 3355, 3356, 5206, 5351, 5352, 5353, 5354, 5355,
                                                                             5356, 5357, 5359, 5360, 5931, 5932, 6206, 6351, 6352, 6353, 6354, 6355, 6356, 6357, 6359, 6360, 7206, 7358))
       ) MOV
  JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  UNION ALL
  SELECT :PRARQUIVO, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, 17, :wSaida, 'C190' /*saída*/
  FROM (
        SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVSAI M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO = 1
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND
                                       SUBSTRING(I.BDCODNAT FROM 1 FOR 4) IN(1207, 1153, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 2153, 2207, 2251, 2252, 2253, 2254, 2255, 2256, 2257,
                                                                             3207, 3251, 5153, 5207, 5251, 5252, 5253, 5254, 5255, 5256, 5257, 5258, 6153, 6207, 6251, 6252, 6253, 6254,
                                                                             6255, 6256, 6257, 6258, 7207, 7251, 1205, 1301, 1302, 1303, 1304, 1305, 1306, 2205, 2301, 2302, 2303, 2304,
                                                                             2305, 2306, 3205, 3301, 5205, 5301, 5302, 5303, 5304, 5305, 5306, 5307, 6205, 6301, 6302, 6303, 6304, 6305,
                                                                             6306, 6307, 7205, 7301, 1206, 1351, 1352, 1353, 1354, 1355, 1356, 1360, 1931, 1932, 2206, 2351, 2352, 2353,
                                                                             2354, 2355, 2356, 2931, 2932, 3206, 3351, 3352, 3353, 3354, 3355, 3356, 5206, 5351, 5352, 5353, 5354, 5355,
                                                                             5356, 5357, 5359, 5360, 5931, 5932, 6206, 6351, 6352, 6353, 6354, 6355, 6356, 6357, 6359, 6360, 7206, 7358))
       ) MOV
  JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM);
    
  /*****************************************************************************
   *                                   C100                                    *
   ****************************************************************************/
  /*18 - Sem produto.*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, MOV.BDCHAVE, 18, :wEntrada, 'C100' /*Entrada*/
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
        FROM VEF_EMP_TMOVENT M
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        WHERE M.BDCODEMP = :PRCODEMP
        AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
        AND M.BDMODELO IN (1, 4, 55, 65, 100)
        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
       ) MOV
  LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  WHERE PRO.BDORDEMPRO IS NULL
  UNION ALL
  SELECT :PRARQUIVO, MOV.BDCHAVE, 18, :wSaida, 'C100' /*Saída*/
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
        FROM VEF_EMP_TMOVSAI M
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        WHERE M.BDCODEMP = :PRCODEMP
        AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
        AND M.BDMODELO IN (1, 4, 55, 65, 100)
        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
       ) MOV
  LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
  WHERE PRO.BDORDEMPRO IS NULL;
    
  /*19 - Com indicador de pagamento a prazo sem informação de parcelas.*/
  /*A partir dos produtos*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, MOV.BDCHAVE, 19, :wEntrada, 'C100' /*Entrada*/
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE
        FROM VEF_EMP_TMOVENT M
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        WHERE M.BDCODEMP = :PRCODEMP
        AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
        AND M.BDMODELO = 1
        AND M.BDCONDPGTO = 1 /*Prazo*/
        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
       ) MOV
  LEFT OUTER JOIN VEF_EMP_TMOVENTPAR PAR ON(PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE)
  WHERE PAR.BDORDEMPAR IS NULL
  UNION ALL
  SELECT :PRARQUIVO, MOV.BDCHAVE, 19, :wSaida, 'C100' /*Saída*/
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
        FROM VEF_EMP_TMOVSAI M
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        WHERE M.BDCODEMP = :PRCODEMP
        AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
        AND M.BDMODELO IN (1, 4, 55, 65, 100)
        AND M.BDCONDPGTO = 1 /*Prazo*/        
        AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
       ) MOV
  LEFT OUTER JOIN VEF_EMP_TMOVSAIPAR PAR ON(PAR.BDCODEMP = MOV.BDCODEMP AND PAR.BDCHAVE = MOV.BDCHAVE)
  WHERE PAR.BDORDEMPAR IS NULL;
    
  /*20 - Existe diferença entre base/valor de ICMS da nota e a base/valor de ICMS dos produtos.*/
  /*Movimento de produto*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ENT.BDCHAVE, ENT.BDORDEM, 20, :wEntrada, 'C100' /*Entrada*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, SUM(COALESCE(PRO.BDBCICMS, 0)) BDBCICMS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
              FROM VEF_EMP_TMOVENT M
              JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) ENT
  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE AND I.BDORDEM = ENT.BDORDEM)
  WHERE ENT.BDBCICMS <> I.BDBASEICMS
  UNION ALL
  SELECT :PRARQUIVO, SAI.BDCHAVE, SAI.BDORDEM, 20, :wSaida, 'C100' /*Saída*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, SUM(COALESCE(PRO.BDBCICMS, 0)) BDBCICMS
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
              FROM VEF_EMP_TMOVSAI M
              JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) SAI
  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE AND I.BDORDEM = SAI.BDORDEM)
  WHERE SAI.BDBCICMS <> I.BDBASEICMS;
    
  /*21 - Existe diferença entre base/valor de IPI da nota e a base/valor de IPI dos produtos.*/
  /*Movimento de produto*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ENT.BDCHAVE, ENT.BDORDEM, 21, :wEntrada, 'C100' /*Entrada*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, SUM(COALESCE(PRO.BDBCIPI, 0)) BDBCIPI
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
              FROM VEF_EMP_TMOVENT M
              JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) ENT
  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE AND I.BDORDEM = ENT.BDORDEM)
  WHERE ENT.BDBCIPI <> I.BDBASEIPI
  UNION ALL
  SELECT :PRARQUIVO, SAI.BDCHAVE, SAI.BDORDEM, 21, :wSaida, 'C100' /*Saída*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, SUM(COALESCE(PRO.BDBCIPI, 0)) BDBCIPI
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM
              FROM VEF_EMP_TMOVSAI M
              JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) SAI
  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE AND I.BDORDEM = SAI.BDORDEM)
  WHERE SAI.BDBCIPI <> I.BDBASEIPI;

    END
  ELSE
  IF (:PRBLOCO = 'D100') THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
      SELECT :PRARQUIVO, MOV.BDCHAVE, 22, :wEntrada, 'D100'
      FROM (
            SELECT E.BDCODEMP, E.BDCHAVE, COALESCE(TRIM((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D100.BDCHAVECTEREF))), '') BDCHAVECTEREF
            FROM VEF_EMP_TMOVENT E
            JOIN VEF_EMP_TD100ENT D100 ON(D100.BDCODEMP = E.BDCODEMP AND D100.BDCHAVE = E.BDCHAVE)
            WHERE E.BDCODEMP = :PRCODEMP
            AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
            AND E.BDMODELO IN(57, 67)
           ) MOV
      WHERE MOV.BDCHAVECTEREF <> ''
      UNION ALL
      SELECT :PRARQUIVO, MOV.BDCHAVE, 22, :wSaida, 'D100'
      FROM (
            SELECT E.BDCODEMP, E.BDCHAVE, COALESCE(TRIM((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D100.BDCHAVECTEREF))), '') BDCHAVECTEREF
            FROM VEF_EMP_TMOVSAI E
            JOIN VEF_EMP_TD100SAI D100 ON(D100.BDCODEMP = E.BDCODEMP AND D100.BDCHAVE = E.BDCHAVE)
            WHERE E.BDCODEMP = :PRCODEMP
            AND E.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND E.BDMODELO IN(57, 67)
           ) MOV
      WHERE MOV.BDCHAVECTEREF <> '';

      --elizeu 18-09-18 - Alteração da validação do campo 11 do Registro D100 - Alterações Sped Fiscal 2019 #89669
      --Inconsistencia do campo DT_DOC a partir de 01-01-19 não pode mais emitir notas dos modelos 7,8,800/*08B*/,9,10,11,26,27
      INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
      SELECT :PRARQUIVO, MOV.BDCHAVE, 24, :wEntrada, 'D100'
      FROM (
            SELECT E.BDCODEMP, E.BDCHAVE
            FROM VEF_EMP_TMOVENT E
            WHERE E.BDCODEMP = :PRCODEMP
            AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
            AND E.BDMODELO IN(7,8,800/*08B*/,9,10,11,26,27)
            and e.bddataemissao >= '01/01/2019'
           ) MOV
      UNION ALL
      SELECT :PRARQUIVO, MOV.BDCHAVE, 24, :wSaida, 'D100'
      FROM (
            SELECT E.BDCODEMP, E.BDCHAVE
            FROM VEF_EMP_TMOVSAI E
            WHERE E.BDCODEMP = :PRCODEMP
            AND E.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND E.BDMODELO IN(7,8,800/*08B*/,9,10,11,26,27)
            and e.bddataemissao >= '01/01/2019'
           ) MOV ;

      INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
      SELECT :PRARQUIVO, MOV.BDCHAVE, 39, :wEntrada, 'D100'
      FROM (
            SELECT E.BDCODEMP, E.BDCHAVE, D100.BDCIDORIGEM, D100.BDCIDDEST
            FROM VEF_EMP_TMOVENT E
            JOIN VEF_EMP_TD100ENT D100 ON(D100.BDCODEMP = E.BDCODEMP AND D100.BDCHAVE = E.BDCHAVE)
            WHERE E.BDCODEMP = :PRCODEMP
            AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
            AND E.BDMODELO IN(57, 67)
           ) MOV
      WHERE (MOV.BDCIDORIGEM IS NULL) OR
            (MOV.BDCIDDEST IS NULL)
      UNION ALL
      SELECT :PRARQUIVO, MOV.BDCHAVE, 39, :wSaida, 'D100'
      FROM (
            SELECT E.BDCODEMP, E.BDCHAVE, D100.BDCIDORIGEM, D100.BDCIDDEST
            FROM VEF_EMP_TMOVSAI E
            JOIN VEF_EMP_TD100SAI D100 ON(D100.BDCODEMP = E.BDCODEMP AND D100.BDCHAVE = E.BDCHAVE)
            WHERE E.BDCODEMP = :PRCODEMP
            AND E.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND E.BDMODELO IN(57, 67)
           ) MOV
      WHERE (MOV.BDCIDORIGEM IS NULL) OR
            (MOV.BDCIDDEST IS NULL);
   END

        
  /*25 - Valor FCP não exportado para os registros C190 e C191 devido combinação de CST ICMS e CFOP.*/
  /*Movimento de produto*/
  INSERT INTO TEXPORTACAO_SPED_INCO(BDID, BDCHAVE, BDORDEM, BDCODINCO, BDMOVIMENTO, BDREG)
  SELECT :PRARQUIVO, ENT.BDCHAVE, ENT.BDORDEM, 25, :wEntrada, 'C190' /*Entrada*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, I.BDCODNAT
              FROM VEF_EMP_TMOVENT M
              JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)
              AND M.BDREFLAN >= 201901
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
        LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS)
        WHERE (PRO.BDFCPRETIDO > 0) AND Coalesce((SELECT BDRETORNO FROM SP_GET_FCP(0,PRO.BDFCPRETIDO,ICMS.BDCSTICMS, MOV.BDCODNAT)) +
                                                 (SELECT BDRETORNO FROM SP_GET_FCP(1,PRO.BDFCPRETIDO,ICMS.BDCSTICMS, MOV.BDCODNAT)) +
                                                 (SELECT BDRETORNO FROM SP_GET_FCP(2,PRO.BDFCPRETIDO,ICMS.BDCSTICMS, MOV.BDCODNAT)), 0.00) = 0.00
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) ENT
  UNION ALL
  SELECT :PRARQUIVO, SAI.BDCHAVE, SAI.BDORDEM, 25, :wSaida, 'C190' /*Saída*/
  FROM (
        SELECT PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, I.BDCODNAT
              FROM VEF_EMP_TMOVSAI M
              JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5)
              AND M.BDMODELO IN (1, 4, 55, 65, 100)   
              AND M.BDREFLAN >= 201901
              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0) AND (NOT EXISTS(SELECT FIRST 1 BDORDEMPRO FROM VEF_EMP_TMOVPROSAI P WHERE P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)) OR (M.BDCODSITNF = 6))
             ) MOV
        JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)  
        LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS)
        WHERE (PRO.BDFCPRETIDO > 0) AND Coalesce((SELECT BDRETORNO FROM SP_GET_FCP(0,PRO.BDFCPRETIDO,ICMS.BDCSTICMS, MOV.BDCODNAT)) +
                                                 (SELECT BDRETORNO FROM SP_GET_FCP(1,PRO.BDFCPRETIDO,ICMS.BDCSTICMS, MOV.BDCODNAT)) +
                                                 (SELECT BDRETORNO FROM SP_GET_FCP(2,PRO.BDFCPRETIDO,ICMS.BDCSTICMS, MOV.BDCODNAT)), 0.00) = 0.00
        GROUP BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM
       ) SAI;

    IF (:PRCHECASER = 'TRUE') THEN  --Larissa - 18/03/2021 - Sped Fiscal - Notas de serviços #143666
     EXECUTE PROCEDURE SP_VALIDA_EXP_SER(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO);


    -- Solicitação #182941 - Documentos com a situação numeração inutilizada ou denegado não foram exportados.
    WCHAVE = 0;
    wSQL =         'SELECT FIRST 1 M.BDCHAVE FROM VEF_EMP_TMOVSAI M ';
    wSQL = wSQL || 'WHERE M.BDCODEMP = ' ||:PRCODEMP|| ' ';
    wSQL = wSQL || 'AND (M.BDMODELO IN (55, 57, 63, 65, 67) ';
    wSQL = wSQL || 'AND M.BDDATAEMISSAO BETWEEN '''||:PRDTINI||''' AND '''||:PRDTFIM||''' ';
    wSQL = wSQL || 'AND M.BDCODSITNF IN (4, 5) AND M.BDREFLAN >= 202301)';

    EXECUTE STATEMENT :wSQL INTO :WCHAVE;

    if ((:WCHAVE > 0) and (:WCHAVE IS NOT NULL))  then
        BEGIN
            INSERT INTO TEXPORTACAO_SPED_INCO(bdID, bdCHAVE, bdCODINCO, bdREG) VALUES (:PRARQUIVO, NULL, 40, 'C100');
        END

END^

CREATE OR ALTER procedure SP_EXPORTA_ECREDAC (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRFINALIDADE integer,
    PRIEINTIMA varchar(12))
as
declare variable WLINHA blob sub_type 1 segment size 200 character set UTF8;
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')));

  /******************************************************************************
   * REGISTRO 0000: ABERTURA DO ARQUIVO DIGITAL E IDENTIFICAÇÃO DO CONTRIBUINTE *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, '0000', LPAD(:PRCODEMP,6,'0') || '.0000',
           '0000|' || --01 REG Texto fixo contendo "0000" C 004 -
           'LASIMCA|' ||--02 LASIMCA Texto fixo contendo "LASIMCA” C 007 -
           '01|'||--03 COD_VER Código da versão do leiaute conforme a Tabela 3.1 N 002 -
           LPAD(:PRFINALIDADE,2,'0')|| '|' || --04 COD_FIN Código da finalidade do arquivo conforme a Tabela 3.2 N 002 -
           (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'MMYYYY')) || '|' ||--05 PERIODO Período das informações contidas no arquivo N 006 -
           REF.BDNOMEMP || '|' ||--06 NOME Nome empresarial do estabelecimento informante C - -
           (SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(EMP.BDCNPJEMP)) || '|' || --07 CNPJ Número de inscrição no CNPJ do estabelecimento informante N 014 -
           Coalesce((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(REF.BDIEEMP)),'') || '|' ||--08 IE Inscrição Estadual do estabelecimento informante C - -
           LPAD(Coalesce(REF.BDCODCNAE,''),7,'0') || '|' ||--09 CNAE CNAE do contribuinte informante N 007 -
           (SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CID.BDCODIBGE)) || '|' || --10 COD_MUN Código do município do domicílio fiscal do estabelecimento informante
           :PRIEINTIMA --11 IE_INTIMA Inscrição Estadual do Estabelecimento paulista gerador de crédito acumulado notificado, por intimação específica, a entregar arquivo
  FROM TEMPRESAS EMP
  LEFT OUTER JOIN VW_TEMPRESAS_REF REF ON (REF.BDCODEMP = EMP.BDCODEMP)
  LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = REF.BDCODCID)
  WHERE EMP.BDCODEMP = :PRCODEMP;

  /*****************************************************************************
   *                   REGISTRO 5315: OPERAÇÕES DE SAÍDA                       *
   ****************************************************************************/  
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA,BDCODTER)
  SELECT :PRARQUIVO, :PRCODEMP, '5315', LPAD(:PRCODEMP,6,'0') || '.5315.' || LPAD(MOV.BDCHAVE,10,'0'),
  '5315|' || --01 REG Texto fixo contendo "5315". C 004
  (SELECT BDDATA FROM SP_PARSE_DATE(MOV.BDDATAEMISSAO, 'DDMMYYYY')) || '|' || --03 DT_EMISSAO Data da emissão do documento fiscal. N 008
  LPAD(MOD_E.BDCODEXP,2,'0') || '|' || --04 TIP_DOC Tipo do documento conforme a coluna Código Chave da tabela 4.1 N 002
  MOV.BDSERIE || '|' ||--05 SER Série do documento. C
  MOV.BDNUMDOCINI || '|' ||--06 NUM_DOC Número do documento C
  MOV.BDCODTER || '|' || --07 COD_PART Código numérico de identificação do participante no arquivo N
  replace(CAST(MOV.BDVLRSAI AS NUMERIC(15,2)),'.',',') || '|' ||--08 VALOR_SAI Valor de Saída N - 2
  replace(CAST(IIF(MOV.BDVLRICMSOUT > 0, MOV.BDVLRCREDOUT*100/MOV.BDVLRICMSOUT,0) AS NUMERIC(15,2)), '.', ',') || '|' || --09 PERC_CRDOUT Percentual de Crédito Outorgado N - 2
  replace(CAST(MOV.BDVLRCREDOUT AS NUMERIC(15,2)), '.', ',') --10 VALOR_CRDOUT Valor do Crédito Outorgado N - 2
  ,MOV.BDCODTER
  FROM (SELECT MOV.BDDATAEMISSAO, MOV.BDCHAVE, MOV.BDMODELO, MOV.BDSERIE, MOV.BDNUMDOCINI, MOV.BDCODTER,
               SUM(Coalesce(E.BDVLRSAI,i.BDVLRCONTAB)) BDVLRSAI, SUM(Coalesce(E.BDVLRICMSOUT * E.BDALIQCREDOUT/100,0)) BDVLRCREDOUT, SUM(Coalesce(E.BDVLRICMSOUT,0)) BDVLRICMSOUT
        FROM VEF_EMP_TMOVSAI MOV
        LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)                                   
        LEFT OUTER JOIN VEF_EMP_TMOVSAIECREDAC E ON (E.BDCODEMP = I.BDCODEMP AND E.BDCHAVE = I.BDCHAVE AND E.BDORDEM = I.BDORDEM)
        WHERE MOV.BDCODEMP = :PRCODEMP AND (MOV.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM) AND (MOV.BDCODSITNF NOT IN (2,3,4,5))
          AND ((E.BDVLRIVA > 0) OR (E.BDALIQPCM > 0) OR (E.BDVLRCREDEST > 0) OR (E.BDVLRCREDGER > 0) OR -- Alt.: "E-Credac CAT 207/09 - Registro 5330/5350 zerado" - Regra de exportação do 5325
               (I.BDBASEICMS > 0) OR (I.BDVLRICMS > 0)) -- Alt.: "E-Credac CAT 207/09 - Registro 5330/5350 zerado" - Regra de exportação do 5330/5350
        group by MOV.BDCODEMP, MOV.BDCHAVE, mov.BDDATAEMISSAO, MOV.BDMODELO, MOV.BDSERIE, MOV.BDNUMDOCINI, MOV.BDCODTER
        ) MOV
  LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MODELO ON (MOV.BDMODELO = MODELO.BDMODELO)
  LEFT OUTER JOIN VEF_BASE_TTABMODELOECREDAC MOD_E ON (MOD_E.BDMODELOSTR = MODELO.BDMODELOSTR);


  /*****************************************************************************
   *                   REGISTRO 5320 DEVOLUÇÃO DE SAÍDA                        *
   ****************************************************************************/ 
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, '5320', LPAD(:PRCODEMP,6,'0') || '.5315.' || LPAD(MOV.BDCHAVE,10,'0') || '.5320.' || LPAD(ENT.BDCHAVE,10,'0'),
  '5320|' || --01 REG Texto fixo contendo "5320". C 004
  (SELECT BDDATA FROM SP_PARSE_DATE(ent.BDDATAENTRADAENT,'DDMMYYYY')) || '|' ||--02 DT_SAI Data da emissão do documento fiscal que acobertou a operação original. N 008
  LPAD(MOD_E.BDCODEXP,2,'0') || '|' || --03 TIP_DOC Tipo do documento que acobertou a operação original, utilizar a coluna Código Chave da tabela 4.1. N 002
  ENT.BDSERIE || '|' ||--04 SER Série do documento que acobertou a operação original. C
  ENT.BDNUMDOCINI --05 NUM_DOC Número do documento que acobertou a operação original. N
  FROM VEF_EMP_TMOVSAI MOV
  LEFT OUTER JOIN VEF_EMP_TMOVSAIECREDAC C ON (C.BDCODEMP = MOV.BDCODEMP AND C.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = C.BDCODEMP AND ENT.BDCHAVE = C.BDCHAVEENT)          
  LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MODELO ON (MODELO.BDMODELO = ent.BDMODELO)      
  LEFT OUTER JOIN VEF_BASE_TTABMODELOECREDAC MOD_E ON (MOD_E.BDMODELOSTR = MODELO.BDMODELOSTR)
  WHERE MOV.BDCODEMP = :PRCODEMP AND MOV.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM and (MOV.BDCODSITNF not in (2, 3, 4, 5))
  GROUP BY MOV.BDCHAVE,ent.BDDATAENTRADAENT, ENT.BDCHAVE, MOD_E.BDCODEXP, ENT.BDSERIE, ENT.BDNUMDOCINI;

  /*****************************************************************************
   *        REGISTRO 5325 OPERAÇÕES GERADORAS DE CRÉDITO ACUMULADO             *
   ****************************************************************************/       
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA,BDCODENQLEGAL)
  SELECT :PRARQUIVO, :PRCODEMP, '5325', LPAD(:PRCODEMP,6,'0') || '.5315.' || LPAD(MOV.BDCHAVE,10,'0') || '.5325.' || LPAD(C.BDCODENQLEGAL,10,'0'),
         '5325|' || --01 REG Texto fixo contendo "5325". C 004 -
         LPAD(C.BDCODENQLEGAL,4,'0') || '|' ||--02 COD_LEGAL Código do Enquadramento Legal conforme registro 0300. N 004 -
         REPLACE(Cast(Sum(C.BDVLRIVA) AS NUMERIC(7,4)),'.',',') || '|' ||--03 IVA_UTILIZADO IVA - Índice de Valor Acrescido considerado no cálculo do custo estimado da operação ou prestação geradora conforme a legisla N - 4
         REPLACE(Cast(Sum(C.BDALIQPCM) AS NUMERIC(7,4)),'.',',') || '|' ||--04 PER_MED_ICMS Percentual Médio de Crédito do Imposto – é a alíquota média das entradas. N - 4
         REPLACE(Cast(Sum(C.BDVLRCREDEST) AS NUMERIC(15,2)),'.',',') || '|' ||--05 CRED_EST_ICMS Crédito estimado do ICMS N 2
         REPLACE(Cast(Sum(C.BDVLRCREDGER) AS NUMERIC(15,2)),'.',',')--06 ICMS_GERA Crédito Acumulado Gerado na operação N - 2
         ,C.BDCODENQLEGAL
  FROM VEF_EMP_TMOVSAI MOV
  LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TMOVSAIECREDAC C ON (C.BDCODEMP = I.BDCODEMP AND C.BDCHAVE = I.BDCHAVE AND C.BDORDEM = I.BDORDEM)
  LEFT OUTER JOIN VEF_EMP_TENQLEGAL_ECREDAC E ON (E.BDCODEMP = C.BDCODEMP AND E.BDCODENQLEGAL = C.BDCODENQLEGAL)
  WHERE MOV.BDCODEMP = :PRCODEMP AND MOV.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM AND UPPER(C.BDCREDACU) = 'TRUE' and (MOV.BDCODSITNF not in (2, 3, 4, 5))
    AND ((C.BDVLRIVA > 0) OR (C.BDALIQPCM > 0) OR (C.BDVLRCREDEST > 0) OR (C.BDVLRCREDGER > 0))
  GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, C.BDCODENQLEGAL;

  /*****************************************************************************
   *      REGISTRO 5330 OPERAÇÕES GERADORAS APURADAS NAS FICHAS 6A OU 6B       *
   ****************************************************************************/  
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, '5330', LPAD(:PRCODEMP,6,'0') || '.5315.' || LPAD(MOV.BDCHAVE,10,'0') || '.5325.5330',
          '5330|' || --01 REG Texto fixo contendo "5330". C 004 -
         REPLACE(CAST(SUM(I.BDBASEICMS) AS NUMERIC(15,2)),'.',',') || '|' || --02 VALOR_BC Base de Cálculo da operação de saída. N - 2
         REPLACE(CAST(SUM(I.BDVLRICMS) AS NUMERIC(15,2)),'.',',') --03 ICMS_DEB ICMS debitado na operação de saída . N - 2
  FROM VEF_EMP_TMOVSAI MOV
  LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TMOVSAIECREDAC C ON (C.BDCODEMP = I.BDCODEMP AND C.BDCHAVE = I.BDCHAVE AND C.BDORDEM = I.BDORDEM)
  LEFT OUTER JOIN VEF_EMP_TENQLEGAL_ECREDAC E ON (E.BDCODEMP = C.BDCODEMP AND E.BDCODENQLEGAL = C.BDCODENQLEGAL)
  WHERE MOV.BDCODEMP = :PRCODEMP AND MOV.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM AND UPPER(C.BDCREDACU) = 'TRUE' and (MOV.BDCODSITNF not in (2, 3, 4, 5))
    AND ((I.BDBASEICMS > 0) OR (I.BDVLRICMS > 0))
  GROUP BY MOV.BDCODEMP, MOV.BDCHAVE;
   
  /*****************************************************************************
   *      REGISTRO 5335 OPERAÇÕES GERADORAS APURADAS NA FICHA 6C OU 6D         *
   ****************************************************************************/  
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, '5335', LPAD(:PRCODEMP,6,'0') || '.5315.' || LPAD(MOV.BDCHAVE,10,'0') || '.5325.5335',
         '5335|' || -- 01 REG Texto fixo contendo "5335". C 004 -
         TRIM(COALESCE((SELECT RESULT FROM SP_TIRATODOSSINAIS(EXP.BDREGEXPORTACAO)),'')) || '|' || -- 02 NUM_DECL_EXP Número da Declaração para Despacho de Exportação ou Declaração Simplificada de Exportação C
         '1' -- 03 COMP_OPER Comprovação da Operação – preencher com: 0 – Sim 1 – Não N 001
  FROM VEF_EMP_TMOVSAI MOV
  LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TMOVSAIECREDAC C ON (C.BDCODEMP = I.BDCODEMP AND C.BDCHAVE = I.BDCHAVE AND C.BDORDEM = I.BDORDEM)
  LEFT OUTER JOIN VEF_EMP_TMOVSAIEXPSP EXP ON (EXP.BDCODEMP = I.BDCODEMP AND EXP.BDCHAVE = I.BDCHAVE AND EXP.BDORDEM = I.BDORDEM)
  LEFT OUTER JOIN VEF_EMP_TENQLEGAL_ECREDAC E ON (E.BDCODEMP = C.BDCODEMP AND E.BDCODENQLEGAL = C.BDCODENQLEGAL)
  WHERE MOV.BDCODEMP = :PRCODEMP AND MOV.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM AND UPPER(C.BDCREDACU) = 'TRUE' and (MOV.BDCODSITNF not in (2, 3, 4, 5))
    AND E.BDCODLEGAL = 7; -- Inciso III - Saídas sem pagamento de Imposto – Exportação 
   
  /*****************************************************************************
   *   REGISTRO 5350 OPERAÇÕES NÃO GERADORAS DE CRÉDITO ACUMULADO – FICHA 6F   *
   ****************************************************************************/ 
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, '5350', LPAD(:PRCODEMP,6,'0') || '.5315.' || LPAD(MOV.BDCHAVE,10,'0') || '.5350',
          '5350|' || --01 REG Texto fixo contendo "5350". C 004 -
          REPLACE(SUM(I.BDBASEICMS),'.',',') || '|' ||--02 VALOR_BC Base de Cálculo da operação de saída. N - 2
          REPLACE(SUM(I.BDVLRICMS),'.',',') || '|' ||--03 ICMS_DEB ICMS debitado da operação de saída. N - 2
          Coalesce((SELECT FIRST 1 EXP.BDNUMDECLARACAO
                   FROM VEF_EMP_TMOVEXP EXP
                   LEFT OUTER JOIN VEF_EMP_TMOVEXPNFSAI NF ON (NF.BDCODEMP = EXP.BDCODEMP AND NF.BDCHAVE = EXP.BDCHAVE)
                   WHERE NF.BDCODEMP = MOV.BDCODEMP AND NF.BDCHAVELANSAI = MOV.BDCHAVE),'') --04 NUM_DECL_EXP_IND Número da Declaração para Despacho de Exportação ou Declaração Simplificada de Exportação do estabelecimento exportador C
  FROM VEF_EMP_TMOVSAI MOV
  LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  LEFT OUTER JOIN VEF_EMP_TMOVSAIECREDAC C ON (C.BDCODEMP = I.BDCODEMP AND C.BDCHAVE = I.BDCHAVE AND C.BDORDEM = I.BDORDEM)
  WHERE MOV.BDCODEMP = :PRCODEMP AND MOV.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM AND Coalesce(UPPER(C.BDCREDACU),'') <> 'TRUE' and (MOV.BDCODSITNF not in (2, 3, 4, 5))
    AND ((I.BDBASEICMS > 0) OR (I.BDVLRICMS > 0))
  GROUP BY MOV.BDCODEMP, MOV.BDCHAVE;

  /*****************************************************************************
   *                   REGISTRO 5001: ABERTURA DO BLOCO 5                      *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  VALUES (:PRARQUIVO, :PRCODEMP, '5001', LPAD(:PRCODEMP,6,'0') || '.5001',
         '5001|' ||   --01 REG Texto fixo contendo "5001" C 004
         (iif(exists(select first 1 bdcodemp from TEXPORTACAO_ECREDAC WHERE BDID = :PRARQUIVO AND BDCODEMP = :PRCODEMP AND SUBSTRING(BDREG FROM 1 FOR 1) = '5'),0,1))); --02 IND_MOV Indicador de movimento: 0- Bloco com dados informados 1- Bloco sem dados informados N 001 -

  /*****************************************************************************
   *                   REGISTRO 5990: ENCERRAMENTO DO BLOCO 5                  *
   ****************************************************************************/
                                     
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  VALUES (:PRARQUIVO, :PRCODEMP, '5990', LPAD(:PRCODEMP,6,'0') || '.5990',
          '5990|' || -- 01 REG Texto fixo contendo "5990" C 004
           (SELECT COUNT(*) + 1 FROM TEXPORTACAO_ECREDAC WHERE BDID = :PRARQUIVO AND BDCODEMP = :PRCODEMP AND SUBSTRING(BDREG FROM 1 FOR 1) = '5'));--02 QTD_LIN_0 Quantidade total de linhas do Bloco 0 N

   
  /*****************************************************************************
   *    REGISTRO 0150: CADASTRO DE PARTICIPANTES DE OPERAÇÕES E PRESTAÇÕES     *
   ****************************************************************************/ 
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, '0150', LPAD(:PRCODEMP,6,'0') || '.0150.'||LPAD(E.BDCODTER,10,'0'),
         '0150|' ||--01 REG Texto fixo contendo "0150" C 004
         E.BDCODTER || '|' ||--02 COD_PART Código numérico de identificação do participante no arquivo N
         TER.BDNOMETER || '|' ||--03 NOME Razão social ou nome do participante C
         --LPAD(Coalesce(PAIS.BDCODSPED,''),5,'0') || '|' ||--04 COD_PAIS Código do país do participante N 005 | Alt.: #234010 - Ajustado para exportar participantes do exterior corretamente...
         LPAD(Coalesce(PAIS.BDCODSPED,PAISEXT.BDCODSPED,''),5,'0') || '|' ||--04 COD_PAIS Código do país do participante N 005
         iif (PAIS.BDCODSPED = 1058, -- BRASIL
             (SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(TER.BDCGCTER))|| '|' ||--05 CNPJ CNPJ ou CPF do participante N 014
             Coalesce((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(TER.BDIETER)),'')|| '|' ||--06 IE Inscrição Estadual do participante C
             (UF.BDSIGLAUF) || '|' ||--07 UF Sigla da unidade da federação do participante C 002
             LPAD(Coalesce((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(TER.BDCEPTER)),''),8,'0')|| '|' ||--08 CEP Código de Endereçamento Postal N 008
             Coalesce(TER.BDLOGRTER,'') || ' ' || Coalesce(TER.BDENDTER,'')|| '|' ||--09 END Logradouro e endereço do imóvel C
             IIF(Coalesce(TER.BDNUMTER,'') = '', 'SN', Coalesce(TER.BDNUMTER,''))|| '|' ||--10 NUM Número do imóvel C
             Coalesce(TER.BDCOMPTER,'')|| '|' ||--11 COMPL Dados complementares do endereço C
             Coalesce(TER.BDBAITER,'')|| '|' ||--12 BAIRRO Bairro em que o imóvel está situado C
             LPAD(CID.BDCODIBGE,7,'0')|| '|' ||--13 COD_MUN Código do município N 007
             LPAD(Coalesce(TER.BDDDDTER,''),3,'0') || Coalesce(TER.BDFONETER,'') --14 FONE Número do telefone C
         ,'|||||||||') -- No exterior deve deixar os campos em branco
  FROM (SELECT BDCODTER
        FROM TEXPORTACAO_ECREDAC
        WHERE BDID = :PRARQUIVO AND BDCODEMP = :PRCODEMP AND BDCODTER IS NOT NULL
        GROUP BY BDCODTER) E
  LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = E.BDCODTER)
  LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = TER.BDCODCID)
  LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF)
  LEFT OUTER JOIN TPAIS PAIS ON (PAIS.BDCODPAIS = CID.BDCODPAIS)
  LEFT OUTER JOIN TPAIS PAISEXT ON (PAISEXT.BDCODPAIS = TER.BDCODPAIS);
   
   --Visto que deve gerar um 0150 da Empresa que está realizando o processo
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, '0150', LPAD(:PRCODEMP,6,'0') || '.0150.'||LPAD(Coalesce(COD_TER.BDCOD,1),10,'0'),
         '0150|' ||--01 REG Texto fixo contendo "0150" C 004
         Coalesce(COD_TER.BDCOD,1) || '|' ||--02 COD_PART Código numérico de identificação do participante no arquivo N
         REF.BDNOMEMP || '|' ||--03 NOME Razão social ou nome do participante C
         LPAD(Coalesce(PAIS.BDCODSPED,''),5,'0') || '|' ||--04 COD_PAIS Código do país do participante N 005
         iif (PAIS.BDCODSPED = 1058, -- BRASIL
             (SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(EMP.BDCNPJEMP))|| '|' ||--05 CNPJ CNPJ ou CPF do participante N 014
             Coalesce((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(REF.BDIEEMP)),'')|| '|' ||--06 IE Inscrição Estadual do participante C
             (UF.BDSIGLAUF) || '|' ||--07 UF Sigla da unidade da federação do participante C 002
             LPAD(Coalesce((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(REF.BDCEPEMP)),''),8,'0')|| '|' ||--08 CEP Código de Endereçamento Postal N 008
             Coalesce(REF.BDLOGREMP,'') || ' ' || Coalesce(REF.BDENDEMP,'')|| '|' ||--09 END Logradouro e endereço do imóvel C
             IIF(Coalesce(REF.BDNUMEMP,'') = '', 'SN', Coalesce(REF.BDNUMEMP,''))|| '|' ||--10 NUM Número do imóvel C
             Coalesce(REF.BDCOMPLEMP,'')|| '|' ||--11 COMPL Dados complementares do endereço C
             Coalesce(REF.BDBAIEMP,'')|| '|' ||--12 BAIRRO Bairro em que o imóvel está situado C
             LPAD(CID.BDCODIBGE,7,'0')|| '|' ||--13 COD_MUN Código do município N 007
             LPAD(Coalesce(REF.BDDDDEMP,''),3,'0') || Coalesce(REF.BDFONEEMP,'') --14 FONE Número do telefone C
         ,'|||||||||') -- No exterior deve deixar os campos em branco
  FROM TEMPRESAS EMP
  LEFT OUTER JOIN VW_TEMPRESAS_REF REF ON (REF.BDCODEMP = EMP.BDCODEMP)
  LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = REF.BDCODCID)
  LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF)
  LEFT OUTER JOIN TPAIS PAIS ON (PAIS.BDCODPAIS = CID.BDCODPAIS)
  LEFT OUTER JOIN (SELECT MAX(BDCODTER) + 1 BDCOD, BDCODEMP
                   FROM TEXPORTACAO_ECREDAC
                   WHERE BDID = :PRARQUIVO AND BDCODEMP = :PRCODEMP AND BDCODTER IS NOT NULL
                   GROUP BY BDCODEMP
                   ) COD_TER ON (COD_TER.BDCODEMP = EMP.BDCODEMP)
  WHERE EMP.BDCODEMP = :PRCODEMP and not exists (select first 1 EXP.bdcodter
                                                 from TEXPORTACAO_ECREDAC EXP
                                                 JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = EXP.BDCODTER)
                                                 WHERE EXP.BDID = :PRARQUIVO AND TER.BDCGCTER = EMP.BDCNPJEMP);

  /**************************************************************************************************
   * REGISTRO 0300: ENQUADRAMENTO LEGAL DA OPERAÇÃO/PRESTAÇÃO GERADORA DE CRÉDITO ACUMULADO DO ICMS *
   *************************************************************************************************/    
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, '0300', LPAD(:PRCODEMP,6,'0') || '.0300.'||LPAD(E.BDCODENQLEGAL,10,'0'),
         '0300|' || --01 REG Texto fixo contendo "0300" C 004
         LPAD(E.BDCODENQLEGAL,4,'0') || '|' ||--02 COD_LEGAL Código do Enquadramento Legal N 004
         (SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(L.BDCODEXP)) || '|' || --03 DESC Informar um dos seguintes códigos, relativo à hipótese de geração, conforme o inciso do artigo 71 do RICMS/00 N 002
         ENQ.BDANEXO || '|' || --04 ANEX Informar o Anexo do RICMS referente ao enquadramento legal da operação ou prestação geradora do crédito acumulado do ICMS, se existir. C
         ENQ.BDARTIGO || '|' ||--05 ART Informar o Artigo do RICMS referente ao enquadramento legal da operação ou prestação geradora do crédito acumulado do ICMS. C
         ENQ.BDINCISO || '|' || --06 INC Informar o Inciso do RICMS referente ao enquadramento legal da operação ou prestação geradora do crédito acumulado do ICMS, se existir. C
         ENQ.BDALINEA || '|' || --07 ALIN Informar a Alínea do RICMS referente ao enquadramento legal da operação ou prestação geradora do crédito acumulado do ICMS, se existir. C
         ENQ.BDPARAGRAFO || '|' ||--08 PRG Informar o Parágrafo do RICMS referente ao enquadramento legal da operação ou prestação geradora do crédito acumulado do ICMS, se existir. C
         ENQ.BDITEM || '|' ||--09 ITM Informar o Item do RICMS referente ao enquadramento legal da operação ou prestação geradora do crédito acumulado do ICMS, se existir. C
         ENQ.BDLETRA || '|' ||--10 LTR Informar a letra do RICMS referente ao enquadramento legal da operação ou prestação geradora do crédito acumulado do ICMS, se existir. C
         ENQ.BDOBSERVACAO --11 OBS Informação complementar referente ao enquadramento legal da operação ou prestação geradora do crédito acumulado do ICMS. C
  FROM (SELECT BDCODEMP, BDCODENQLEGAL
        FROM TEXPORTACAO_ECREDAC
        WHERE BDID = :PRARQUIVO AND BDCODEMP = :PRCODEMP AND BDCODENQLEGAL IS NOT NULL
        GROUP BY BDCODEMP, BDCODENQLEGAL) E
  LEFT OUTER JOIN VEF_EMP_TENQLEGAL_ECREDAC ENQ ON (ENQ.BDCODEMP = E.BDCODEMP AND ENQ.BDCODENQLEGAL = E.BDCODENQLEGAL)
  LEFT OUTER JOIN VEF_BASE_TENQLEGAL L ON (L.BDCODLEGAL = ENQ.BDCODLEGAL);

  /*****************************************************************************
   *                   REGISTRO 0001: ABERTURA DO BLOCO 0                      *
   ****************************************************************************/     
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  VALUES (:PRARQUIVO, :PRCODEMP, '0001', LPAD(:PRCODEMP,6,'0') || '.0001',
         '0001|' ||   --01 REG Texto fixo contendo "0001" C 004
         (iif(exists(select first 1 bdcodemp from TEXPORTACAO_ECREDAC WHERE BDID = :PRARQUIVO AND BDCODEMP = :PRCODEMP AND BDREG <> '0000' AND SUBSTRING(BDREG FROM 1 FOR 1) = '0'),0,1))); --02 IND_MOV Indicador de movimento: 0- Bloco com dados informados 1- Bloco sem dados informados N 001 -

  /*****************************************************************************
   *                   REGISTRO 0990: ENCERRAMENTO DO BLOCO 0                  *
   ****************************************************************************/ 
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  VALUES (:PRARQUIVO, :PRCODEMP, '0990', LPAD(:PRCODEMP,6,'0') || '.0990',
          '0990|' || -- 01 REG Texto fixo contendo "0990" C 004
           (SELECT COUNT(*) + 1 FROM TEXPORTACAO_ECREDAC WHERE BDID = :PRARQUIVO AND BDCODEMP = :PRCODEMP AND SUBSTRING(BDREG FROM 1 FOR 1) = '0'));--02 QTD_LIN_0 Quantidade total de linhas do Bloco 0 N

  /*****************************************************************************
   *                   REGISTRO 9001: ABERTURA DO BLOCO 9                      *
   ****************************************************************************/ 
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  VALUES (:PRARQUIVO, :PRCODEMP, '9001', LPAD(:PRCODEMP,6,'0') || '.9001',
          '9001|' ||--01 REG Texto fixo contendo "9001" C 004
          '0');--02 IND_MOV Indicador de movimento: 0- Bloco com dados informados;N 001
   
  /*****************************************************************************
   *                   REGISTRO 9900: REGISTROS DO ARQUIVO                     *
   ****************************************************************************/  
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, '9900', LPAD(:PRCODEMP,6,'0') || '.9900.' || E.BDREG,
          '9900|' || --01 REG Texto fixo contendo "9900" C 004
          E.BDREG || '|' || --02 REG_BLC Registro que será totalizado no próximo campo C 004
          COUNT(*)--03 QTD_REG_BLC Total de registros do tipo informado no campo anterior N
  FROM TEXPORTACAO_ECREDAC E
  WHERE E.BDID = :PRARQUIVO AND E.BDCODEMP = :PRCODEMP
  GROUP BY BDREG;
   
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  VALUES (:PRARQUIVO, :PRCODEMP, '9900', LPAD(:PRCODEMP,6,'0') || '.9900.9990',
          '9900|' || --01 REG Texto fixo contendo "9900" C 004
          '9990|' || --02 REG_BLC Registro que será totalizado no próximo campo C 004
          '1'--03 QTD_REG_BLC Total de registros do tipo informado no campo anterior N
          );
          
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  VALUES (:PRARQUIVO, :PRCODEMP, '9900', LPAD(:PRCODEMP,6,'0') || '.9900.9999',
          '9900|' || --01 REG Texto fixo contendo "9900" C 004
          '9999|' || --02 REG_BLC Registro que será totalizado no próximo campo C 004
          '1'--03 QTD_REG_BLC Total de registros do tipo informado no campo anterior N
          );
            
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, '9900', LPAD(:PRCODEMP,6,'0') || '.9900.' || E.BDREG,
          '9900|' || --01 REG Texto fixo contendo "9900" C 004
          E.BDREG || '|' || --02 REG_BLC Registro que será totalizado no próximo campo C 004
          (COUNT(*) + 1)--03 QTD_REG_BLC Total de registros do tipo informado no campo anterior N
  FROM TEXPORTACAO_ECREDAC E
  WHERE E.BDID = :PRARQUIVO AND E.BDCODEMP = :PRCODEMP AND E.BDREG = '9900'
  GROUP BY BDREG;

  /*****************************************************************************
   *                   REGISTRO 9990: ENCERRAMENTO DO BLOCO 9                  *
   ****************************************************************************/ 
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  VALUES (:PRARQUIVO, :PRCODEMP, '9990', LPAD(:PRCODEMP,6,'0') || '.9990',
          '9990|' ||--01 REG Texto fixo contendo "9990" C 004
          (SELECT COUNT(*) + 2 FROM TEXPORTACAO_ECREDAC WHERE BDID = :PRARQUIVO AND BDCODEMP = :PRCODEMP AND SUBSTRING(BDREG FROM 1 FOR 1) = '9'));--02 QTD_LIN_9 Quantidade total de linhas do Bloco 9 N

  /*****************************************************************************
   *                   REGISTRO 9999: ENCERRAMENTO DO ARQUIVO DIGITAL          *
   ****************************************************************************/ 
  INSERT INTO TEXPORTACAO_ECREDAC (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  VALUES (:PRARQUIVO, :PRCODEMP, '9999', LPAD(:PRCODEMP,6,'0') || '.9999',
          '9999|' || --01 REG Texto fixo contendo "9999" C 004
         (SELECT COUNT(*) + 1 FROM TEXPORTACAO_ECREDAC WHERE BDID = :PRARQUIVO AND BDCODEMP = :PRCODEMP));--02 QTD_LIN Quantidade total de linhas do arquivo digital N

  OPENARQ(:PRARQUIVO,:PRCODEMP);

  FOR SELECT E.BDLINHA
      FROM TEXPORTACAO_ECREDAC E
      WHERE E.BDID = :PRARQUIVO
      ORDER BY E.BDCHAVEREG
      INTO :WLINHA
  DO
  BEGIN
    WRITELNOA(:WLINHA,:PRCODEMP);
  END

  CLOSEARQ(:PRARQUIVO,:PRCODEMP);

  DELETE FROM TEXPORTACAO_ECREDAC;
END
^

CREATE OR ALTER procedure SP_EXPORTA_DIMOB (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRDECLRETIF varchar(5),
    PRNUMRECIBO varchar(10),
    PRSITUACAOESPECIAL varchar(5),
    PRDATAEVENTO date,
    PRSITEVENTO integer,
    PRCONSOLIDAR varchar(5),
    PREXPBAIXPAR varchar(5),
    PRVERORGAOPUBLICO varchar(5))
as
declare variable WORDEM integer;
declare variable WDECLRETIF integer;
declare variable WCODSIT varchar(2);
declare variable WSITESPECIAL char(1);
declare variable WLINHA blob sub_type 1 segment size 200 character set UTF8;
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')));

  IF (:PRDECLRETIF = 'TRUE') THEN
    WDECLRETIF = 1;
  ELSE
    WDECLRETIF = 0;

  IF (:PRSITUACAOESPECIAL = 'TRUE') THEN
    WSITESPECIAL = 1;
  ELSE
    WSITESPECIAL = 0;

  WCODSIT = CASE
              WHEN :PRSITEVENTO = 0 THEN '01'
              WHEN :PRSITEVENTO = 1 THEN '02'
              WHEN :PRSITEVENTO = 2 THEN '03'
              WHEN :PRSITEVENTO = 3 THEN '04'
              ELSE '00'
            END;

  /*****************************************************************************
   *                                   HEADER                                  *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_DIMOB (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)
  VALUES (:PRARQUIVO, :PRCODEMP, 1, :PRCODEMP,
           'DIMOB' || -- 01 Fixo DIMOB
           LPAD('', 369, ' ')  -- 02 369 espaços em branco
           ); -- 03 2 posições de EOL


  /*****************************************************************************
   *                                    R01                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_DIMOB (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)
  SELECT :PRARQUIVO BDID, :PRCODEMP BDCODEMP, 2 BDORDEMREG, :PRCODEMP BDORDEM,
         ('R01' || -- 01 Fixo R01
         (SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(EMP.BDCNPJEMP,14)) || -- 02 CNPJ
         (EXTRACT(YEAR FROM :PRDTINI)) || -- 03 Ano da declaração
         :WDECLRETIF || -- 04 Declaração Retificadora
         LPAD(:PRNUMRECIBO,10,'0') || -- 05 Número do Recibo
         :WSITESPECIAL || -- 06 Situação Especial
         LPAD(COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(:PRDATAEVENTO,'DDMMYYYY')),''),8,' ') || -- 07 Data do evento situação especial
         :WCODSIT || -- 08 Código da situação especial
         RPAD(EMP.BDNOMEMP,60,' ') || -- 09 Nome Empresarial
         RPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(SOC.BDCGCCEISOC)), ''),11,' ') || -- 10 CPF do Responsável
         RPAD(EMP.BDLOGREMP||' '||(SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(EMP.BDENDEMP))
                                ||IIF(TRIM(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(EMP.BDNUMEMP)),'')) <> '', ', '||(SELECT RESULT FROM SP_TIRATODOSSINAIS((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(EMP.BDNUMEMP)))), '')
                                ||IIF(TRIM(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(EMP.BDCOMPLEMP)),'')) <> '', ', '||(SELECT RESULT FROM SP_TIRATODOSSINAIS((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(EMP.BDCOMPLEMP)))), ''),120,' ') ||  -- 11 Endereço completo do contribuinte
         UF.BDSIGLAUF || -- 12 UF do Contribuinte
         LPAD(CID.BDCODFED, 4, '0') || -- 13 Código do Município do Contribuinte
         LPAD('', 20, ' ') || -- 14 Reservado – 20 posições em branco
         LPAD('', 10, ' ') -- 15 Reservado – 10 posições em branco
         ) BDLINHA -- 16 Delimitador de Registro – 2 posições EOL
  FROM (SELECT EMP.BDCODMATRIZ, EMP.BDCODEMP, EMP.BDCNPJEMP, REF.BDNOMEMP, REF.BDENDEMP, REF.BDNUMEMP, REF.BDCOMPLEMP, REF.BDCODCID, REF.BDLOGREMP
        FROM (SELECT COALESCE(BDCODMATRIZ, BDCODEMP) AS BDCODMATRIZ, BDCODEMP, BDCNPJEMP
              FROM TEMPRESAS
              WHERE BDCODEMP = :PRCODEMP) EMP
        LEFT OUTER JOIN VW_TEMPRESAS_REF REF ON (EMP.BDCODEMP = REF.BDCODEMP)) EMP
  LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID)
  LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF)
  LEFT OUTER JOIN(SELECT FIRST 1 BDCODEMP, BDCGCCEISOC
                  FROM VW_EMPRESAS_TSOC_REF
                  WHERE BDCODEMP = :PRCODEMP AND
                        BDRESPONSAVELSOC = 'TRUE') SOC ON (SOC.BDCODEMP = EMP.BDCODEMP);

  /*****************************************************************************
   *                                    R02                                    *
   ****************************************************************************/
  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_DIMOB (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)
  SELECT :PRARQUIVO BDID, EMP.BDCODEMP, 3 BDORDEMREG, IMOB.BDCHAVE BDORDEM,
         ('R02' || -- 01 Fixo R02
         (SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(EMP.BDCNPJEMP,14)) || -- 02 CNPJ do declarante
         (EXTRACT(YEAR FROM :PRDTINI)) || -- 03 Ano-calendário
         LPAD(COALESCE(GETORDEMSEQUENCIAL(:WORDEM),'0'),5,'0') || -- 04 Sequencial da Locação
         RPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(LOCADOR.BDCGCTER)), ''),14,' ') || -- 05 CPF/CNPJ do Locador
         RPAD(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(LOCADOR.BDNOMETER)), ''),60,' ') || -- 06 Nome/Nome Empresarial do Locador
         RPAD(COALESCE(
         CASE
           WHEN (LOCATARIO.BDCODPAIS <> 30) THEN 'NDP'
           ELSE (SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(LOCATARIO.BDCGCTER))
         END, ''), 14, ' ') || -- 07 CPF/CNPJ do Locatário
         RPAD(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(LOCATARIO.BDNOMETER)), ''),60,' ') || -- 08 Nome/Nome Empresarial do Locatário
         RPAD(COALESCE(IMOB.BDNRCONTRATO, ''),6,' ') || -- 09 Número do Contrato
         COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(IMOB.BDDTCONTRATO,'DDMMYYYY')), '') || -- 10 Data do Contrato
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 1 THEN CAST(F.BDVL_OPER as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 11 Valor do Aluguel no mês de Janeiro (campo valor da operação)
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 1 THEN CAST(F.BDVLRCOMISSAO as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 12 Valor da Comissão no mês de Janeiro (campo novo valor comissão)
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 1 THEN CAST(F.BDVLRRET as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 13 Valor do Imposto no mês de Janeiro (soma das retenções PIS/Cofins/CSLL/ISS/IR)
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 2 THEN CAST(F.BDVL_OPER as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 14 Valor do Aluguel no mês de Fevereiro
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 2 THEN CAST(F.BDVLRCOMISSAO as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 15 Valor da Comissão no mês de Fevereiro
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 2 THEN CAST(F.BDVLRRET as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 16 Valor do Imposto no mês de Fevereiro
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 3 THEN CAST(F.BDVL_OPER as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 17 Valor do Aluguel no mês de Março
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 3 THEN CAST(F.BDVLRCOMISSAO as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 18 Valor da Comissão no mês de Março
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 3 THEN CAST(F.BDVLRRET as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 19 Valor do Imposto no mês de Março
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 4 THEN CAST(F.BDVL_OPER as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 20 Valor do Aluguel no mês de Abril
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 4 THEN CAST(F.BDVLRCOMISSAO as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 21 Valor da Comissão no mês de Abril
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 4 THEN CAST(F.BDVLRRET as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 22 Valor do Imposto no mês de Abril
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 5 THEN CAST(F.BDVL_OPER as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 23 Valor do Aluguel no mês de Maio
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 5 THEN CAST(F.BDVLRCOMISSAO as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 24 Valor da Comissão no mês de Maio
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 5 THEN CAST(F.BDVLRRET as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 25 Valor do Imposto no mês de Maio
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 6 THEN CAST(F.BDVL_OPER as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 26 Valor do Aluguel no mês de Junho
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 6 THEN CAST(F.BDVLRCOMISSAO as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 27 Valor da Comissão no mês de Junho
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 6 THEN CAST(F.BDVLRRET as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 28 Valor do Imposto no mês de Junho
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 7 THEN CAST(F.BDVL_OPER as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 29 Valor do Aluguel no mês de Julho
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 7 THEN CAST(F.BDVLRCOMISSAO as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 30 Valor da Comissão no mês de Julho
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 7 THEN CAST(F.BDVLRRET as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 31 Valor do Imposto no mês de Julho
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 8 THEN CAST(F.BDVL_OPER as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 32 Valor do Aluguel no mês de Agosto
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 8 THEN CAST(F.BDVLRCOMISSAO as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 33 Valor da Comissão no mês de Agosto
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 8 THEN CAST(F.BDVLRRET as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 34 Valor do Imposto no mês de Agosto
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 9 THEN CAST(F.BDVL_OPER as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 35 Valor do Aluguel no mês de Setembro
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 9 THEN CAST(F.BDVLRCOMISSAO as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 36 Valor da Comissão no mês de Setembro
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 9 THEN CAST(F.BDVLRRET as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 37 Valor do Imposto no mês de Setembro
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 10 THEN CAST(F.BDVL_OPER as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 38 Valor do Aluguel no mês de Outubro
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 10 THEN CAST(F.BDVLRCOMISSAO as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 39 Valor da Comissão no mês de Outubro
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 10 THEN CAST(F.BDVLRRET as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 40 Valor do Imposto no mês de Outubro
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 11 THEN CAST(F.BDVL_OPER as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 41 Valor do Aluguel no mês de Novembro
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 11 THEN CAST(F.BDVLRCOMISSAO as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 42 Valor da Comissão no mês de Novembro
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 11 THEN CAST(F.BDVLRRET as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 43 Valor do Imposto no mês de Novembro
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 12 THEN CAST(F.BDVL_OPER as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 44 Valor do Aluguel no mês de Dezembro
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 12 THEN CAST(F.BDVLRCOMISSAO as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 45 Valor da Comissão no mês de Dezembro
         LPAD(COALESCE((SELECT BDNUMERO FROM sp_retorna_numeros(SUM(CASE WHEN F.BDMES = 12 THEN CAST(F.BDVLRRET as numeric(15,2)) ELSE 0 END))), ''),14,'0') || -- 46 Valor do Imposto no mês de Dezembro
         COALESCE(
         CASE
           WHEN UNID.BDTIPOIMOVEL = 0 THEN 'U'
           ELSE 'R'
         END, '') || -- 47 Tipo do Imóvel
         RPAD(UNID.BDLOGRADOUROUNID||' '||COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(UNID.BDENDERECOUNID)),'')
                                        ||IIF(TRIM(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(UNID.BDNURMEROUNID)),'')) <> '',', '||(SELECT RESULT FROM SP_TIRATODOSSINAIS((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(UNID.BDNURMEROUNID)))),'')
                                        ||IIF(TRIM(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(UNID.BDCOMPLEMENTOUNID)),'')) <> '',', '||(SELECT RESULT FROM SP_TIRATODOSSINAIS((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(UNID.BDCOMPLEMENTOUNID)))),''),60,' ') || -- 48 Endereço do Imóvel
         LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(UNID.BDCEPUNID)), ''),8,'0') || -- 49 CEP
         LPAD(COALESCE(CID.BDCODFED, ''), 4, '0') || -- 50 Código do Município do Imóvel
         LPAD('', 20, ' ') || -- 51 Reservado – 20 posições em branco
         COALESCE(UF.BDSIGLAUF, '  ') || -- 52 UF
         LPAD('', 10, ' ')-- 53 Reservado – 10 posições em branco
         ) BDLINHA -- 54 Delimitador de Registro – 2 posições EOL
  FROM (
        SELECT F.BDCODEMP, F.BDCHAVECONT, CAST(NULL AS NUMERIC(15,2)) BDVL_OPER, CAST(NULL AS NUMERIC(15,2)) BDVLRCOMISSAO,
                COALESCE(SUM(PGTO.BDVALORRETPIS) + SUM(PGTO.BDVALORRETCOFINS) + SUM(PGTO.BDVALORRETCSLL),RET.BDVLRPIS + RET.BDVLRCOFINS + RET.BDVLRCSOCIAL) BDVLRRET,
                    (EXTRACT(MONTH FROM COALESCE(PGTO.BDDATAPGTOPAR, F.BDDT_OPER))) BDMES
             FROM VEF_EMP_TMOVDEMAISDOC_F100 F                                            
             LEFT OUTER JOIN VW_TEMPRESAS_REF EMPREF ON (EMPREF.BDCODEMP = F.BDCODEMP)
             LEFT OUTER JOIN VW_VEF_BASE_TEMPPARGER PARG ON (PARG.BDCODEMP = EMPREF.BDCODEMP)
             LEFT OUTER JOIN VEF_EMP_TMOVDEMRET RET ON (RET.BDCODEMP = F.BDCODEMP AND RET.BDCHAVE = F.BDCHAVE) 
             LEFT OUTER JOIN VEF_EMP_TMOVF100PARPGTO PGTO ON (F.BDCODEMP = PGTO.BDCODEMP AND F.BDCHAVE = PGTO.BDCHAVE AND (((PARG.BDTIPOAPURACAORET = 1) OR ((:PREXPBAIXPAR = 'TRUE') AND (PGTO.BDCODTIPOBAIXA <> 2))) AND (F.BDCONDPGTO = 1)))
             WHERE F.bdcodemp = :PRCODEMP AND
                   (F.BDIND_OPER IN (2, 3)) AND
                   (IIF(:prexpbaixpar = 'TRUE', PGTO.bddatapgtopar, F.BDDT_OPER) >= :PRDTINI AND
                   IIF(:prexpbaixpar = 'TRUE', PGTO.bddatapgtopar, F.BDDT_OPER) <= :PRDTFIM) AND
                   ((PGTO.BDVALORRETPIS > 0) OR
                   (PARG.BDTIPOAPURACAORET <> 1) OR (F.BDCONDPGTO <> 1)) AND
                   ((:PREXPBAIXPAR <> 'TRUE') OR (F.BDCONDPGTO = 0) OR (PGTO.BDCHAVE is not null))
             GROUP BY F.BDCODEMP, F.BDCHAVECONT, F.BDVL_OPER, F.BDVLRCOMISSAO, PARG.BDTIPOAPURACAORET, RET.BDVLRPIS, RET.BDVLRCOFINS, RET.BDVLRCSOCIAL, F.BDCONDPGTO,
                      BDMES
             UNION ALL
             SELECT F.BDCODEMP, F.BDCHAVECONT, CAST(NULL AS NUMERIC(15,2)) BDVL_OPER, CAST(NULL AS NUMERIC(15,2)) BDVLRCOMISSAO,
                   COALESCE(SUM(PGTO.BDVALORRETIRRF), RET.BDVLRIR)BDVLRRET,
                    (EXTRACT(MONTH FROM COALESCE(PGTO.BDDATAPGTOPAR, F.BDDT_OPER))) BDMES
             FROM VEF_EMP_TMOVDEMAISDOC_F100 F
             left outer join (select BDCODTER, RF2.BDORGAOPUBLICO, RF2.BDCGCTER, RF2.BDNOMETER, RF2.BDREFEMP
                from TTERCEIRO_REF RF2
                where RF2.BDREFEMP = coalesce((select first 1 BDREFEMP
                                     from TTERCEIRO_REF RF3
                                     where RF3.BDCODTER = RF2.BDCODTER and
                                           RF3.BDREFEMP <= substring(:PRDTFIM from 1 for 4) || '12'
                                     order by RF3.BDREFEMP desc), (select first 1 BDREFEMP
                                                                   from TTERCEIRO_REF RF3
                                                                   where RF3.BDCODTER = RF2.BDCODTER
                                                                   order by RF3.BDCODTER, RF3.BDREFEMP))) TER on (TER.bdcodter = F.bdcodter)
             LEFT OUTER JOIN VW_TEMPRESAS_REF EMPREF ON (EMPREF.BDCODEMP = F.BDCODEMP)
             LEFT OUTER JOIN VW_VEF_BASE_TEMPPARGER PARG ON (PARG.BDCODEMP = EMPREF.BDCODEMP)
             LEFT OUTER JOIN VEF_EMP_TMOVDEMRET RET ON (RET.BDCODEMP = F.BDCODEMP AND RET.BDCHAVE = F.BDCHAVE) 
             LEFT OUTER JOIN VEF_EMP_TMOVF100PARPGTO PGTO ON (F.BDCODEMP = PGTO.BDCODEMP AND F.BDCHAVE = PGTO.BDCHAVE AND (((IIF(F.BDIND_OPER = 1, PARG.BDTIPOAPURACAORETIRTOM, (iif(:PRVERORGAOPUBLICO = true,iif(ter.bdorgaopublico = true, 1, PARG.BDTIPOAPURACAORETIR), PARG.BDTIPOAPURACAORETIR))) = 1) OR ((:PREXPBAIXPAR = 'TRUE') AND (PGTO.BDCODTIPOBAIXA <> 2))) AND (F.BDCONDPGTO = 1)))
             WHERE F.bdcodemp = :PRCODEMP AND
                   (F.BDIND_OPER IN (2, 3)) AND
                   (IIF(:prexpbaixpar = 'TRUE',  PGTO.bddatapgtopar, F.BDDT_OPER) >= :PRDTINI AND
                   IIF(:prexpbaixpar = 'TRUE', PGTO.bddatapgtopar, F.BDDT_OPER) <= :PRDTFIM) AND
                   ((PGTO.BDVALORRETIRRF > 0) OR
                   (IIF(F.BDIND_OPER = 1, PARG.BDTIPOAPURACAORETIRTOM, (iif(:PRVERORGAOPUBLICO = true,iif(ter.bdorgaopublico = true, 1, PARG.BDTIPOAPURACAORETIR), PARG.BDTIPOAPURACAORETIR))) <> 1) OR (F.BDCONDPGTO <> 1)) AND
                   ((:PREXPBAIXPAR <> 'TRUE') OR (F.BDCONDPGTO = 0) OR (PGTO.BDCHAVE is not null))
             GROUP BY F.BDCODEMP, F.BDCHAVECONT, F.BDVL_OPER, F.BDVLRCOMISSAO, PARG.BDTIPOAPURACAORET, F.BDCONDPGTO, PARG.BDTIPOAPURACAORETIR, PARG.BDTIPOAPURACAORETIRTOM, BDMES, RET.BDVLRIR
             UNION ALL
             SELECT F.BDCODEMP, F.BDCHAVECONT, CAST(NULL AS NUMERIC(15,2)) BDVL_OPER, CAST(NULL AS NUMERIC(15,2)) BDVLRCOMISSAO, IIF(:PREXPBAIXPAR = 'TRUE',RET.BDISSRET/(select IIF(count(PAR.BDORDEMPAR)=0,1,count(PAR.BDORDEMPAR)) from VEF_EMP_TMOVF100PAR PAR where PAR.bdchave = F.bdchave AND PAR.bdcodemp = F.bdcodemp), RET.BDISSRET) BDVLRRET,
                    (EXTRACT(MONTH FROM COALESCE(PGTO.BDDATAPGTOPAR, F.BDDT_OPER))) BDMES
             FROM VEF_EMP_TMOVDEMAISDOC_F100 F
             LEFT OUTER JOIN VEF_EMP_TMOVDEMRET RET ON (RET.BDCODEMP = F.BDCODEMP AND RET.BDCHAVE = F.BDCHAVE)
             LEFT OUTER JOIN VW_TEMPRESAS_REF EMPREF ON (EMPREF.BDCODEMP = F.BDCODEMP)
             LEFT OUTER JOIN VW_VEF_BASE_TEMPPARGER PARG ON (PARG.BDCODEMP = EMPREF.BDCODEMP)
             LEFT OUTER JOIN VEF_EMP_TMOVF100PARPGTO PGTO ON (F.BDCODEMP = PGTO.BDCODEMP AND F.BDCHAVE = PGTO.BDCHAVE AND ((:PREXPBAIXPAR = 'TRUE') AND (PGTO.BDCODTIPOBAIXA <> 2)) AND (F.BDCONDPGTO = 1))
             WHERE F.bdcodemp = :PRCODEMP AND
                   (F.BDIND_OPER IN (2, 3)) AND
                   (IIF(:prexpbaixpar = 'TRUE', PGTO.bddatapgtopar, F.BDDT_OPER) >= :PRDTINI AND
                   IIF(:prexpbaixpar = 'TRUE', PGTO.bddatapgtopar, F.BDDT_OPER) <= :PRDTFIM) AND
                   ((:PREXPBAIXPAR <> 'TRUE') OR (F.BDCONDPGTO = 0) OR (PGTO.BDCHAVE is not null))
             UNION ALL
             SELECT F.BDCODEMP, F.BDCHAVECONT,
                    IIF(:PREXPBAIXPAR = 'TRUE', COALESCE(PGTO.BDVALORPGTOPAR,0) + COALESCE(PGTO.BDVALORRETPIS,0) + COALESCE(PGTO.BDVALORRETCOFINS,0) + COALESCE(PGTO.BDVALORRETCSLL,0) + COALESCE(PGTO.BDVALORRETIRRF,0) + COALESCE(PGTO.BDVALORRETISSQN,0) + COALESCE(PGTO.BDVALORRETINSS,0), F.BDVL_OPER) BDVL_OPER,
                    IIF(:PREXPBAIXPAR = 'TRUE',(((COALESCE(PGTO.BDVALORPGTOPAR,0) + COALESCE(PGTO.BDVALORRETPIS,0) + COALESCE(PGTO.BDVALORRETCOFINS,0) + COALESCE(PGTO.BDVALORRETCSLL,0) + COALESCE(PGTO.BDVALORRETIRRF,0) + COALESCE(PGTO.BDVALORRETISSQN,0) + COALESCE(PGTO.BDVALORRETINSS,0))/COALESCE(F.BDVL_OPER,1)) * COALESCE(F.BDVLRCOMISSAO, 0)), F.BDVLRCOMISSAO) BDVLRCOMISSAO,
                    CAST(NULL AS NUMERIC(15,2)) BDVLRRET, (EXTRACT(MONTH FROM COALESCE(PGTO.BDDATAPGTOPAR, F.BDDT_OPER))) BDMES
             FROM VEF_EMP_TMOVDEMAISDOC_F100 F
             LEFT OUTER JOIN VW_TEMPRESAS_REF EMPREF ON (EMPREF.BDCODEMP = F.BDCODEMP)
             LEFT OUTER JOIN VW_VEF_BASE_TEMPPARGER PARG ON (PARG.BDCODEMP = EMPREF.BDCODEMP)
             LEFT OUTER JOIN VEF_EMP_TMOVF100PARPGTO PGTO ON (F.BDCODEMP = PGTO.BDCODEMP AND F.BDCHAVE = PGTO.BDCHAVE AND ((:PREXPBAIXPAR = 'TRUE') AND (PGTO.BDCODTIPOBAIXA <> 2)) AND (F.BDCONDPGTO = 1))
             WHERE F.bdcodemp = :PRCODEMP AND
                   (F.BDIND_OPER IN (2, 3)) AND
                   (IIF(:prexpbaixpar = 'TRUE', PGTO.bddatapgtopar, F.BDDT_OPER) >= :PRDTINI AND
                   IIF(:prexpbaixpar = 'TRUE', PGTO.bddatapgtopar, F.BDDT_OPER) <= :PRDTFIM) AND
                   ((:PREXPBAIXPAR <> 'TRUE') OR (F.BDCONDPGTO = 0) OR (PGTO.BDCHAVE is not null))
             ) F
  /*LEFT OUTER*/ JOIN TCONTRATO_IMOBILIARIO IMOB ON (F.BDCODEMP = IMOB.BDCODEMP AND F.BDCHAVECONT = IMOB.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TCADUNIDIMOBILIARIA UNID ON (IMOB.BDCODEMP = UNID.BDCODEMP AND IMOB.BDCODEMPREENDIMENTO = UNID.BDCODEMPREENDIMENTO AND IMOB.BDCODIGOUNIIMOB = UNID.BDCODIGOUNIIMOB)
  LEFT OUTER JOIN TCIDADE CID ON (UNID.BDCODCIDUNID = CID.BDCODCID)
  LEFT OUTER JOIN TUF UF ON (CID.BDCODUF = UF.BDCODUF)
  LEFT OUTER JOIN VW_TTERCEIRO LOCADOR ON (LOCADOR.BDCODTER = IMOB.BDCODLOCADOR)
  LEFT OUTER JOIN VW_TTERCEIRO LOCATARIO ON (LOCATARIO.BDCODTER = IMOB.BDCODLOCATARIO)   
  LEFT OUTER JOIN TEMPRESAS EMP ON (IMOB.BDCODEMP = EMP.BDCODEMP)
  GROUP BY EMP.BDCNPJEMP, LOCADOR.BDCODPAIS, LOCADOR.BDCGCTER, LOCADOR.BDNOMETER, LOCATARIO.BDCGCTER, LOCATARIO.BDCODPAIS, LOCATARIO.BDNOMETER, UNID.BDLOGRADOUROUNID,
           IMOB.BDNRCONTRATO, IMOB.BDDTCONTRATO, UNID.BDTIPOIMOVEL, UNID.BDENDERECOUNID, UNID.BDNURMEROUNID, UNID.BDCOMPLEMENTOUNID, UNID.BDCEPUNID, CID.BDCODFED, UF.BDSIGLAUF, BDID, EMP.BDCODEMP, BDORDEM, BDORDEMREG;

  /*****************************************************************************
   *                                    R03                                    *
   ****************************************************************************/

/*
Regras decididas pela qualidade (Graci e fernando - 25/07/2023) a partir da solicitação para inserir mais de um adquirente por lançamento

R03:
-O proprietário não está informado no cadastro da unidade imobiliária, tenho um adquirente
-O proprietário não está informado no cadastro da unidade imobiliária, tenho vários adquirentes
-O proprietário está informado no cadastro da unidade imobiliária, tenho um adquirente igual ao proprietário
-O proprietário está informado no cadastro da unidade imobiliária, tenho vários adquirentes e um deles é igual ao proprietário
*/

  SETORDEMSEQUENCIAL_STR(0);
  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_DIMOB (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)
  --SELECT :PRARQUIVO BDID, EMP.BDCODEMP, 4 BDORDEMREG, (LAN.BDCHAVE + LAN.BDCHAVELAN + LAN.BDCODTER) BDORDEM, Alt.: #190579 - Estava gerando problema de "PK", pois essa soma ficava igual em dois lançamentos...
  SELECT :PRARQUIVO BDID, EMP.BDCODEMP, 4 BDORDEMREG, GETORDEMSEQUENCIAL_STR(EMP.BDCODEMP,0) BDORDEM,
           ('R03' || -- 01 Fixo R03
           (SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(EMP.BDCNPJEMP,14)) || -- 02 – CNPJ do declarante
           (EXTRACT(YEAR FROM :PRDTINI)) || -- 03 – Ano-calendário
           LPAD(COALESCE(GETORDEMSEQUENCIAL(:WORDEM), ''),5,'0') || -- 04 – Sequencial da Venda
           RPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(TER.BDCGCTER)), ''),14,' ') || -- 05 – CPF/CNPJ do Comprador
           RPAD(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(TER.BDNOMETER)), ''),60,' ') || -- 06 – Nome/Nome Empresarial do Comprador
           RPAD(COALESCE(LAN.BDNRCONTRATO, ''), 6, ' ') || -- 07 – Número do Contrato
           COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(LAN.BDDATACONTRATO, 'DDMMYYYY')), '') || -- 08 – Data do Contrato
           LPAD(COALESCE(CAST(((LAN.BDVLRINCIALVENDA * LAN.BDPERCENTUAL) / 100) * 100 AS BIGINT) ,CAST(LAN.BDVLRINCIALVENDA * 100 AS BIGINT), ''), 14, '0') || -- 09 – Valor da Operação
           LPAD(COALESCE(CAST(((LAN.BDVLRTOTRECPAR   * LAN.BDPERCENTUAL) / 100) * 100 AS BIGINT) ,CAST(LAN.BDVLRTOTRECPAR   * 100 AS BIGINT), ''), 14, '0') || -- 10 – Valor Pago no Ano
           COALESCE(
           CASE
           WHEN LAN.BDTIPOIMOVEL = 0 THEN 'U'
             ELSE 'R'
           END, '') || -- 11 – Tipo do Imóvel
         RPAD(LAN.BDLOGRADOUROUNID||' '||COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(LAN.BDENDERECOUNID)),'')
                                       ||IIF(TRIM(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(LAN.BDNURMEROUNID)),'')) <> '', ', '||(SELECT RESULT FROM SP_TIRATODOSSINAIS((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(LAN.BDNURMEROUNID)))), '')
                                       ||IIF(TRIM(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(LAN.BDCOMPLEMENTOUNID)),'')) <> '', ', '||(SELECT RESULT FROM SP_TIRATODOSSINAIS((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(LAN.BDCOMPLEMENTOUNID)))), ''), 60, ' ') || -- 12 – Endereço do Imóvel
         LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(LAN.BDCEPUNID)), ''), 8, '0') || -- 13 – CEP
           LPAD(COALESCE(CID.BDCODFED, ''), 4, '0') || -- 14 – Código do Município do Imóvel
           LPAD('', 20, ' ') || -- 15 – Reservado – 20 posições em branco
           COALESCE(UF.BDSIGLAUF, '') || -- 16 – UF
           LPAD('', 10, ' ') -- 17 – Reservado – 10 posições em branco
         ) BDLINHA -- 18 – Delimitador de Registro – 2 posições EOL
  FROM (SELECT MOV.BDCODEMP, MOV.BDCHAVE,MOV.BDCHAVELAN, MOV.BDNRCONTRATO, MOV.BDDATACONTRATO, MOV.BDPERCENTUAL,MOV.BDVLRINCIALVENDA, MOV.BDCODTER,
               MOV.BDVLRTOTRECPAR, IMOB.BDTIPOIMOVEL, IMOB.BDLOGRADOUROUNID, IMOB.BDENDERECOUNID, IMOB.BDNURMEROUNID, IMOB.BDCOMPLEMENTOUNID, IMOB.BDCEPUNID,
               IMOB.BDCODCIDUNID
        FROM (SELECT F200.BDCODEMP, COALESCE(ADQ.bdchave, F200.BDCHAVE) BDCHAVE, COALESCE(ADQ.BDORDEM, F200.BDCHAVE) BDCHAVELAN ,ADQ.BDPERCENTUAL ,F200.BDNRCONTRATO, F200.BDDATACONTRATO, F200.BDVLRINCIALVENDA, COALESCE(ADQ.BDCODTER, F200.BDCODTER) BDCODTER,
                    F200.BDCODEMPREENDIMENTO, F200.BDCODIGOUNIIMOB, SUM(COALESCE(PGTO.BDVLRTOTRECPAR,0)) BDVLRTOTRECPAR
              FROM (SELECT BDCODEMP, BDCNPJEMP
                    FROM TEMPRESAS
                    WHERE BDCODEMP = :PRCODEMP OR BDCODMATRIZ = :PRCODEMP) EMP
              INNER JOIN VEF_EMP_TMOVOPIMOBILIARIA_F200 F200 ON (F200.BDCODEMP = EMP.BDCODEMP AND (F200.BDDATACONTRATO >= :PRDTINI AND F200.BDDATACONTRATO <= :PRDTFIM))
              LEFT OUTER JOIN VEF_EMP_TMOVADQUIRENTE ADQ ON (ADQ.bdcodemp = F200.BDCODEMP AND ADQ.BDCHAVE = F200.BDCHAVE)
              LEFT OUTER JOIN VEF_EMP_TMOVOPIMOBI_F200_PGTO PGTO ON (PGTO.BDCODEMP = F200.BDCODEMP AND PGTO.BDCHAVE = F200.BDCHAVE AND PGTO.BDDATAPGTO >= :PRDTINI AND PGTO.BDDATAPGTO <= :PRDTFIM)
              GROUP BY F200.BDCODEMP, BDCHAVE,BDCHAVELAN, F200.BDNRCONTRATO, F200.BDDATACONTRATO,ADQ.BDPERCENTUAL ,F200.BDVLRINCIALVENDA, BDCODTER, F200.BDCODEMPREENDIMENTO, F200.BDCODIGOUNIIMOB) MOV         /* Luiz roepcke - 25/07/2023 - #94679 - foi retirado aqui para fazer o filtro no where pq agora ele pode ter mais de um adquirente*/
        INNER JOIN VEF_BASE_TCADUNIDIMOBILIARIA IMOB ON (IMOB.BDCODEMP = MOV.BDCODEMP AND IMOB.BDCODEMPREENDIMENTO = MOV.BDCODEMPREENDIMENTO AND IMOB.BDCODIGOUNIIMOB = MOV.BDCODIGOUNIIMOB /*AND (IMOB.BDCODTER IS NULL OR (IMOB.BDCODTER = MOV.BDCODTER)*/)
        where ((IMOB.BDCODTER is null) or (IMOB.BDCODTER = MOV.BDCODTER) or exists (select first 1 AUX.BDCODTER
        from VEF_EMP_TMOVADQUIRENTE AUX
            where AUX.BDCODEMP = MOV.BDCODEMP and
              AUX.BDCHAVE = MOV.BDCHAVE and
              (AUX.BDCODTER = IMOB.BDCODTER)))) LAN
  LEFT OUTER JOIN TCIDADE CID ON (LAN.BDCODCIDUNID = CID.BDCODCID)
  LEFT OUTER JOIN TUF UF ON (CID.BDCODUF = UF.BDCODUF)
  LEFT OUTER JOIN VW_TTERCEIRO TER ON (LAN.BDCODTER = TER.BDCODTER)
  LEFT OUTER JOIN TEMPRESAS EMP ON EMP.BDCODEMP = LAN.BDCODEMP
  LEFT OUTER JOIN VW_TEMPRESAS_REF REF ON (EMP.BDCODEMP = REF.BDCODEMP);

  /*****************************************************************************
   *                                    R04                                    *
   ****************************************************************************/

/*
Regras decididas pela qualidade (Graci e fernando - 25/07/2023) a partir da solicitação para inserir mais de um adquirente por lançamento

R04
-O proprietário está informado no cadastro da unidade imobiliária, tenho um adquirente diferente do proprietário
-O proprietário está informado no cadastro da unidade imobiliária, tenho vários adquirentes e todos são diferentes do proprietário
*/


  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_DIMOB (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)
  SELECT :PRARQUIVO BDID, EMP.BDCODEMP, 5 BDORDEMREG, coalesce(ADQ.BDORDEM, F200.bdchave) BDORDEM,
         ('R04' || -- 01 Fixo R04
         (SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(EMP.BDCNPJEMP,14)) || -- 02 – CNPJ do declarante
         (EXTRACT(YEAR FROM :PRDTINI)) || -- 03 – Ano-calendário
         LPAD(COALESCE(GETORDEMSEQUENCIAL(:WORDEM), ''),5,'0') || -- 04 – Sequencial da Venda
         RPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(TER.BDCGCTER)), ''),14,' ') || -- 05 – CPF/CNPJ do Comprador
         RPAD(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(TER.BDNOMETER)), ''),60,' ') || -- 06 – Nome/Nome Empresarial do Comprador
         RPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(TERIMOB.BDCGCTER)), ''),14,' ') || -- 07 – CPF/CNPJ do Vendedor
         RPAD(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(TERIMOB.BDNOMETER)), ''),60,' ') || -- 08 – Nome/Nome Empresarial do Vendedor
         RPAD(COALESCE(F200.BDNRCONTRATO, ''),6,' ') || -- 09 – Número do Contrato
         COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(F200.BDDATACONTRATO,'DDMMYYYY')), '') || -- 10 – Data do Contrato
         LPAD(COALESCE(CAST(((F200.BDVLRINCIALVENDA * Coalesce(adq.bdpercentual/ 100,1)) ) * 100 AS BIGINT), ''), 14, '0') || -- 11 – Valor da Venda
         LPAD(COALESCE(CAST(((F200.BDVLRCOMISSAO    * Coalesce(adq.bdpercentual/ 100,1)) ) * 100 AS BIGINT), ''), 14, '0') || -- 12 – Valor da Comissão
         COALESCE(
         CASE
           WHEN IMOB.BDTIPOIMOVEL = 0 THEN 'U'
           ELSE 'R'
         END, '') || -- 13 – Tipo do Imóvel
         RPAD(IMOB.BDLOGRADOUROUNID||' '||COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(IMOB.BDENDERECOUNID)),'')||', '
                                        ||IIF(TRIM(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(IMOB.BDNURMEROUNID)),'')) <> '', ', '||(SELECT RESULT FROM SP_TIRATODOSSINAIS((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(IMOB.BDNURMEROUNID)))), '')
                                        ||IIF(TRIM(COALESCE((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(IMOB.BDCOMPLEMENTOUNID)),'')) <> '', ', '||(SELECT RESULT FROM SP_TIRATODOSSINAIS((SELECT BDRETORNO FROM RETIRA_CHAR_ESPECIAL(IMOB.BDCOMPLEMENTOUNID)))), ''),60,' ') || -- 14 – Endereço do Imóvel
         LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(IMOB.BDCEPUNID)), ''),8,'0') || -- 15 – CEP
         LPAD(COALESCE(CID.BDCODFED,''), 4, '0') || -- 16 – Código do Município do Imóvel
         LPAD('', 20, ' ') || -- 17 – Reservado – 20 posições Branco(s)
         COALESCE(UF.BDSIGLAUF, '') || -- 18 – UF
         LPAD('', 10, ' ') -- 19 – Reservado – 10 posições Branco(s)
         ) BDLINHA-- 20 – Delimitador de Registro – 2 posições EOL
  FROM (SELECT BDCODEMP, BDCNPJEMP
        FROM TEMPRESAS
        WHERE BDCODEMP = :PRCODEMP OR BDCODMATRIZ = :PRCODEMP) EMP
  INNER JOIN VEF_EMP_TMOVOPIMOBILIARIA_F200 F200 ON (F200.BDCODEMP = EMP.BDCODEMP AND (F200.BDDATACONTRATO >= :PRDTINI AND F200.BDDATACONTRATO <= :PRDTFIM))
  LEFT OUTER JOIN VEF_EMP_TMOVADQUIRENTE ADQ ON ADQ.bdcodemp = F200.bdcodemp AND ADQ.bdchave = F200.bdchave
  INNER JOIN VEF_BASE_TCADUNIDIMOBILIARIA IMOB ON (IMOB.BDCODEMP = F200.BDCODEMP AND IMOB.BDCODEMPREENDIMENTO = F200.BDCODEMPREENDIMENTO AND IMOB.BDCODIGOUNIIMOB = F200.BDCODIGOUNIIMOB AND (not exists (select first 1 AUX.BDCODTER from VEF_EMP_TMOVADQUIRENTE AUX where AUX.BDCODEMP = ADQ.BDCODEMP and AUX.BDCHAVE = ADQ.BDCHAVE and (AUX.BDCODTER = IMOB.BDCODTER)) AND (IMOB.BDCODTER <> F200.BDCODTER)))
  LEFT OUTER JOIN TCIDADE CID ON (IMOB.BDCODCIDUNID = CID.BDCODCID)
  LEFT OUTER JOIN TUF UF ON (CID.BDCODUF = UF.BDCODUF)
  LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = COALESCE(ADQ.BDCODTER, F200.BDCODTER))
  LEFT OUTER JOIN VW_TTERCEIRO TERIMOB ON (IMOB.BDCODTER = TERIMOB.BDCODTER)
  LEFT OUTER JOIN VW_TEMPRESAS_REF REF ON (EMP.BDCODEMP = REF.BDCODEMP);

  /*****************************************************************************
   *                                    T09                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_DIMOB (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)
  VALUES (:PRARQUIVO, :PRCODEMP, 6, :PRCODEMP, 'T9' || -- 01 Fixo T09
          LPAD('', 100, ' ') -- 02 – Reservado – 100 posições em branco
          ); -- 03 – Delimitador – 2 posições EOL


  /*****************************************************************************
   *                           EXPORTANDO ARQUIVO                              *
   ****************************************************************************/

  OPENARQ(:PRARQUIVO,:PRCODEMP);

  FOR SELECT E.BDLINHA
      FROM TEXPORTACAO_DIMOB E
      WHERE E.BDID = :PRARQUIVO
      ORDER BY E.BDORDEMREG
      INTO :WLINHA
  DO
  BEGIN
    WRITELNOA(:WLINHA,:PRCODEMP);
  END

  CLOSEARQ(:PRARQUIVO,:PRCODEMP);
  DELETE FROM TEXPORTACAO_DIMOB;
END
^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOC1250 (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260))
as
BEGIN
    EXECUTE PROCEDURE SP_SETA_COMPETENCIA(CAST((EXTRACT(YEAR FROM :PRDTINI) || LPAD(EXTRACT(MONTH FROM :PRDTINI),2,'0')) AS INTEGER));

  /*****************************************************************************
   *                                   C185                                    *
   ****************************************************************************/
   SETORDEMSEQUENCIAL(0);

      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD)
      SELECT :PRARQUIVO BDID,
             LPAD(MOV.BDCODEMP, 6, '0')||'.1.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C185'||LPAD(MOV.BDORDEMITENS, 6, '0')||'.'||LPAD(MOV.BDORDEMPRO, 6, '0')||'.C185.'||LPAD(MOV.BDORDEMITENS, 8, '0'),
             'C185' BDREG,
             --'|C185|'||REPLACE(COALESCE(MOV.BDORDEMPRO, ''), '.', ',')||                                                                                                   /*2*/
             '|C185|'||GETORDEMSEQUENCIAL(MOV.BDCHAVE)||                                                                                                                   /*2*/
             '|'||REPLACE(COALESCE(PROD.BDCODSAIDA, ''), '.', ',')||                                                                                                       /*3*/
             '|'||REPLACE(COALESCE(MOV.BDCSTICMS, ''), '.', ',')||                                                                                                         /*4*/
             '|'||REPLACE(COALESCE(SUBSTRING(MOV.BDCODNAT FROM 1 FOR 4), ''), '.', ',')||                                                                                  /*5*/
             '|'||REPLACE(COALESCE(T57.BDCODAJUR, ''), '.', ',')||                                                                                                         /*6*/
             '|'||REPLACE(COALESCE(C185.BDQTDCONVERTIDA, ''), '.', ',')||                                                                                                  /*7*/
             '|'||REPLACE(COALESCE(UNI.BDAPEUNIMED, ''), '.', ',')||                                                                                                       /*8*/
             '|'||REPLACE(COALESCE(C185.BDVLRUNICONVERTIDO, 0.00000), '.', ',')||                                                                                          /*9*/
             '|'||IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0','2'), '',REPLACE(COALESCE(C185.BDVLRUNITICMSEFETIVO, 0.00000), '.', ','))||                            /*10*/
             '|'||IIF((T57.BDCODAJUR <> 'RS211') and (T57.BDCODAJUR <> 'RS212') and (T57.BDCODAJUR <> 'RS215'), '', IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0','1','3'), '',REPLACE(COALESCE(C185.BDVLRUNITICMSOP, 0.00000), '.', ',')))||                             /*11*/
             '|'||IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0'), '0,000000',REPLACE(COALESCE(C185.BDVLRUNITICMSOPESTOQUE, 0.00000), '.', ','))||                      /*12*/
             '|'||IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0'), '0,000000',REPLACE(COALESCE(C185.BDVLRUNITICMSSTESTOQUE, 0.00000), '.', ','))||                      /*13*/
             '|'||IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0'), '0,000000',REPLACE(COALESCE(C185.BDVLRUNITFCPSTESTOQUE, 0.00000), '.', ','))||                       /*14*/
             '|'||IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0','3'), '',REPLACE(COALESCE(C185.BDVLRUNITICMSSTRESTITUIR, 0.00000), '.', ','))||                        /*15*/
             '|'||IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0','3'), '',REPLACE(COALESCE(C185.BDVLRUNITFCPSTRESTITUIR, 0.00000), '.', ','))||                         /*16*/
             '|'||IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0','1','2'), '',REPLACE(COALESCE(C185.BDVLRUNITICMSSTCOMPLEMENTAR, 0.00000), '.', ','))||                 /*17*/
             '|'||IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0','1','2'), '',REPLACE(COALESCE(C185.BDVLRUNITFCPSTCOMPLEMENTAR, 0.00000), '.', ','))||'|', MOV.BDCODPROD/*18*/
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE, PRO.BDCHAVE AS BDCHAVEPRO,PRO.BDORDEMPRO, PRO.BDCODPROD, CST.BDCSTICMS, ITENS.BDCODNAT, ITENS.BDORDEM AS BDORDEMITENS
            FROM VEF_EMP_TMOVSAI SAI
            LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE)
            LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS ITENS ON (ITENS.BDCODEMP = SAI.BDCODEMP AND ITENS.BDCHAVE = SAI.BDCHAVE AND ITENS.BDORDEM = PRO.BDORDEM)
            LEFT OUTER JOIN VEF_BASE_TTABCSTICMS CST ON (CST.BDCODCSTICMS = PRO.BDCODCSTICMS)

            WHERE SAI.BDCODEMP = :PRCODEMP
            AND SAI.BDDATASAIDA BETWEEN :PRDTINI AND :PRDTFIM
              and SAI.BDCODSITNF not in (10, 11)
           ) MOV
      JOIN VEF_EMP_TMOVC185_1250 C185 ON (C185.BDCODEMP = MOV.BDCODEMP AND C185.BDCHAVE = MOV.BDCHAVEPRO AND C185.BDORDEMPRO = MOV.BDORDEMPRO AND C185.BDORDEM = MOV.BDORDEMITENS)
      JOIN TUNIDADEMEDIDA UNI ON (UNI.BDCODUNIMED = C185.BDCODUNIMED)
      JOIN TCADPRO_VINC PROD ON (PROD.BDCODEMP = C185.BDCODEMP and PROD.BDCODPROD = C185.BDCODPROD)
      LEFT JOIN VEF_BASE_TTABINFAD57  T57  ON (T57.BDORDEM57 = C185.BDCODMOTIVO);

  /*****************************************************************************
   *                                   C380                                    *
   ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOV.BDCODEMP, 6, '0')||'.2.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C300.C370.'||LPAD(MOV.BDORDEMITENS, 6, '0')||'.'||LPAD(MOV.BDORDEMPRO, 6, '0')||'.C380'||LPAD(MOV.BDORDEMITENS, 8, '0'),
             'C380' BDREG,
             '|C380|'||REPLACE(COALESCE(T57.BDCODAJUR, ''), '.', ',')||                                                                                     /*2*/
             '|'||REPLACE(COALESCE(C380.BDQTDCONVERTIDA, ''), '.', ',')||                                                                                   /*3*/
             '|'||REPLACE(COALESCE(UNI.BDAPEUNIMED, ''), '.', ',')||                                                                                        /*4*/
             '|'||REPLACE(COALESCE(C380.BDVLRUNICONVERTIDO, 0.00000), '.', ',')||                                                                           /*5*/
             '|'||IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0','2'), '',REPLACE(COALESCE(C380.BDVLRUNITICMSEFETIVO, 0.00000), '.', ','))||             /*6*/
             '|'||IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0','1', '3'), '',REPLACE(COALESCE(C380.BDVLRUNITICMSOP, 0.00000), '.', ','))||             /*7*/
             '|'||IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0'), '',REPLACE(COALESCE(C380.BDVLRUNITICMSOPESTOQUE, 0.00000), '.', ','))||               /*8*/
             '|'||IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0'), '',REPLACE(COALESCE(C380.BDVLRUNITICMSSTESTOQUE, 0.00000), '.', ','))||               /*9*/
             '|'||IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0'), '',REPLACE(COALESCE(C380.BDVLRUNITFCPSTESTOQUE, 0.00000), '.', ','))||                /*10*/
             '|'||IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0','3'), '',REPLACE(COALESCE(C380.BDVLRUNITICMSSTRESTITUIR, 0.00000), '.', ','))||         /*11*/
             '|'||IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0','3'), '',REPLACE(COALESCE(C380.BDVLRUNITFCPSTRESTITUIR, 0.00000), '.', ','))||          /*12*/
             '|'||IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0','1','2'), '',REPLACE(COALESCE(C380.BDVLRUNITICMSSTCOMPLEMENTAR, 0.00000), '.', ','))||  /*13*/
             '|'||IIF(SUBSTRING(T57.BDCODAJUR FROM 3 FOR 1) IN ('0','1','2'), '',REPLACE(COALESCE(C380.BDVLRUNITFCPSTCOMPLEMENTAR, 0.00000), '.', ','))||   /*14*/
             '|'||REPLACE(COALESCE(MOV.BDCSTICMS, ''), '.', ',')||                                                                                          /*15*/
             '|'||REPLACE(COALESCE(SUBSTRING(MOV.BDCODNAT FROM 1 FOR 4), ''), '.', ',')||'|'                                                                /*16*/
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE, PRO.BDCHAVE AS BDCHAVEPRO,PRO.BDORDEMPRO, PRO.BDCODPROD, CST.BDCSTICMS, ITENS.BDCODNAT, ITENS.BDORDEM AS BDORDEMITENS
            FROM VEF_EMP_TMOVSAI SAI
            LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE)
            LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS ITENS ON (ITENS.BDCODEMP = SAI.BDCODEMP AND ITENS.BDCHAVE = SAI.BDCHAVE AND ITENS.BDORDEM = PRO.BDORDEM)
            LEFT OUTER JOIN VEF_BASE_TTABCSTICMS CST ON (CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
            WHERE SAI.BDCODEMP = :PRCODEMP
            AND SAI.BDDATASAIDA BETWEEN :PRDTINI AND :PRDTFIM
            and SAI.BDCODSITNF not in (10, 11)
           ) MOV
      JOIN VEF_EMP_TMOVC380_1250 C380 ON(C380.BDCODEMP = MOV.BDCODEMP AND C380.BDCHAVE = MOV.BDCHAVEPRO AND C380.BDORDEMPRO = MOV.BDORDEMPRO AND C380.BDORDEM = MOV.BDORDEMITENS)
      JOIN TUNIDADEMEDIDA UNI ON (UNI.BDCODUNIMED = C380.BDCODUNIMED)
      LEFT JOIN VEF_BASE_TTABINFAD57  T57  ON (T57.BDORDEM57 = C380.BDCODMOTIVO);
  /*****************************************************************************
   *                                   C180                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.0.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(MOV.BDORDEMITENS, 6, '0')||'.'||LPAD(MOV.BDORDEMPRO, 6, '0')||'.C180.'||LPAD(C180.BDORDEM, 6, '0'),
         'C180' BDREG,
         '|C180|'||REPLACE(COALESCE(CASE C180.BDRESPRETENCAO when -1 then '' when 0 then 1 when 1 then 2 when 2 then 3 end, ''), '.', ',')||  /*2*/
         '|'||REPLACE(COALESCE(C180.BDQTDCONVERTIDA, ''), '.', ',')||                                         /*3*/
         '|'||REPLACE(COALESCE(UNI.BDAPEUNIMED, ''), '.', ',')||                                              /*4*/
         '|'||REPLACE(COALESCE(C180.BDVLRUNICONVERTIDO, 0.00000), '.', ',')||                                 /*5*/
         '|'||REPLACE(COALESCE(C180.BDVLRUNITICMSOP, 0.00000), '.', ',')||                                    /*6*/
         '|'||REPLACE(COALESCE(C180.BDBCUNITICMSST, 0.00000), '.', ',')||                                     /*7*/
         '|'||REPLACE(COALESCE(C180.BDVLRUNITICMSST, 0.00000), '.', ',')||                                    /*8*/
         '|'||REPLACE(COALESCE(C180.BDVLRUNITFCPST, 0.00000), '.', ',')||                                     /*9*/
         '|'||REPLACE(COALESCE(C180.BDCODARRECADACO, ''), '.', ',')||                                         /*10*/
         '|'||REPLACE(COALESCE(C180.BDNUMDOCARRECADACAO, ''), '.', ',')||'|'                   /*11*/
  FROM (
        SELECT ENT.BDCODEMP, ENT.BDCHAVE, PRO.BDCHAVE AS BDCHAVEPRO,PRO.BDORDEMPRO, PRO.BDCODPROD, PRO.BDCODCSTICMS, ITENS.BDCODNAT, ITENS.BDORDEM AS BDORDEMITENS
        FROM VEF_EMP_TMOVENT ENT
        LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE)
        LEFT OUTER JOIN VEF_EMP_TMOVENTITENS ITENS ON (ITENS.BDCODEMP = ENT.BDCODEMP AND ITENS.BDCHAVE = ENT.BDCHAVE AND ITENS.BDORDEM = PRO.BDORDEM)
        WHERE ENT.BDCODEMP = :PRCODEMP
        AND ENT.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        and ENT.BDCODSITNF not in (10, 11)
       ) MOV
  JOIN VEF_EMP_TMOVC180_1250 C180 ON(C180.BDCODEMP = MOV.BDCODEMP AND C180.BDCHAVE = MOV.BDCHAVEPRO AND C180.BDORDEMPRO = MOV.BDORDEMPRO AND C180.BDORDEM = MOV.BDORDEMITENS)
  JOIN TUNIDADEMEDIDA UNI ON (UNI.BDCODUNIMED = C180.BDCODUNIMED)
  where (COALESCE(C180.BDQTDCONVERTIDA, 0) > 0) ;
/*****************************************************************************
*                                   C181                                    *
****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(MOV.BDCODEMP, 6, '0')||'.0.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C170.'||LPAD(MOV.BDORDEMITENS, 6, '0')||'.'||LPAD(MOV.BDORDEMPRO, 6, '0')||'.C181.'||LPAD(C181.BDORDEM, 6, '0'),
             'C181' BDREG,
             '|C181|'||REPLACE(COALESCE(T57.BDCODAJUR, ''), '.', ',')||                                                                                                            /*2*/
             '|'||REPLACE(COALESCE(C181.BDQTDCONVERTIDA, ''), '.', ',')||                                                                                                          /*3*/
             '|'||REPLACE(COALESCE(UNI.BDAPEUNIMED, ''), '.', ',')||                                                                                                               /*4*/
             '|'||REPLACE(COALESCE(TMOD.BDMODELOSTR, ''), '.', ',')||                                                                                                              /*5*/
             '|'||REPLACE(COALESCE(IIF(TMOD.BDMODELOSTR in ('01', '1B','04'),C181.BDSERIE, '' ), ''), '.', ',')||                                                                  /*6*/
             '|'||REPLACE(COALESCE(C181.BDSERIEMAQ, ''), '.', ',')||                                                                                                               /*7*/
             '|'||REPLACE(COALESCE(IIF(TMOD.BDMODELOSTR in ('01', '1B', '02', '2D', '04'),C181.BDNUMDOC, '' ), ''), '.', ',')||                                                    /*8*/
             '|'||REPLACE(COALESCE((select bdnumero from SP_RETORNA_NUMEROS (C181.BDCHAVENFE)), ''), '.', ',')||                                                                   /*9*/
             '|'||REPLACE(COALESCE((select BDNUMERO from SP_RETORNA_NUMEROS ((select BDDDMMAAAA from DDMMAAAA (C181.BDDTEMISSAO)))), ''), '.', ',')||                          /*10*/
             '|'||REPLACE(COALESCE(C181.BDORDEMPRODORIG, ''), '.', ',')||                                                                                                          /*11*/
             '|'||REPLACE(COALESCE(C181.BDVLRUNICONVERTIDO, 0.00000), '.', ',')||                                                                                                  /*12*/
             '|'||REPLACE(COALESCE(IIF(T57.BDCODAJUR in ('RS500', 'RS501'), '', C181.BDVLRUNITICMSOPESTOQUE), 0.00000), '.', ',')||                                                /*13*/
             '|'||REPLACE(COALESCE(IIF(T57.BDCODAJUR in ('RS500', 'RS501'), '', C181.BDVLRUNITICMSSTESTOQUE), 0.00000), '.', ',')||                                                /*14*/
             '|'||REPLACE(COALESCE(IIF(T57.BDCODAJUR in ('RS500', 'RS501'), '', C181.BDVLRUNITFCPSTESTOQUE), 0.00000), '.', ',')||                                                 /*15*/
             '|'||REPLACE(COALESCE(IIF(T57.BDCODAJUR in ('RS500', 'RS501'), '', C181.BDVLRUNITICMSEFETIVO), 0.00000), '.', ',')||                                                  /*16*/
             '|'||REPLACE(COALESCE(IIF(T57.BDCODAJUR in ('RS500', 'RS501','RS600','RS800'), '', C181.BDVLRUNITICMSOP), 0.00000), '.', ',')||                                       /*17*/
             '|'||REPLACE(COALESCE(IIF(T57.BDCODAJUR in ('RS500', 'RS501','RS600', 'RS713', 'RS714', 'RS717', 'RS719'), '', C181.BDVLRUNITICMSSTRESTITUIR), 0.00000), '.', ',')||  /*18*/
             '|'||REPLACE(COALESCE(IIF(T57.BDCODAJUR in ('RS500', 'RS501','RS600', 'RS713', 'RS714', 'RS717', 'RS719'), '', C181.BDVLRUNITFCPSTRESTITUIR), 0.00000), '.', ',')||   /*19*/
             '|'||REPLACE(COALESCE(IIF(T57.BDCODAJUR in ('RS500', 'RS501','RS800'), '', C181.BDVLRUNITICMSSTCOMPLEMENTAR), 0.00000), '.', ',')||                                   /*20*/
             '|'||REPLACE(COALESCE(IIF(T57.BDCODAJUR in ('RS500', 'RS501','RS800'), '', C181.BDVLRUNITFCPSTCOMPLEMENTAR), 0.00000), '.', ',')||'|'                  /*21*/
      FROM (
            SELECT ENT.BDCODEMP, ENT.BDCHAVE, PRO.BDCHAVE AS BDCHAVEPRO,PRO.BDORDEMPRO, PRO.BDCODPROD, PRO.BDCODCSTICMS, ITENS.BDCODNAT, ITENS.BDORDEM AS BDORDEMITENS, ENT.BDDATAENTRADAENT
            FROM VEF_EMP_TMOVENT ENT
            LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE)
            LEFT OUTER JOIN VEF_EMP_TMOVENTITENS ITENS ON (ITENS.BDCODEMP = ENT.BDCODEMP AND ITENS.BDCHAVE = ENT.BDCHAVE AND ITENS.BDORDEM = PRO.BDORDEM)
            WHERE ENT.BDCODEMP = :PRCODEMP
            AND ENT.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
            and ENT.BDCODSITNF not in (10, 11)
           ) MOV
      JOIN VEF_EMP_TMOVC181_1250 C181 ON(C181.BDCODEMP = MOV.BDCODEMP AND C181.BDCHAVE = MOV.BDCHAVEPRO AND C181.BDORDEMPRO = MOV.BDORDEMPRO AND C181.BDORDEM = MOV.BDORDEMITENS)
      JOIN TUNIDADEMEDIDA UNI ON (UNI.BDCODUNIMED = C181.BDCODUNIMED)
      JOIN VEF_BASE_TTABMODELOLAN TMOD ON (TMOD.BDMODELO = C181.BDMODELO)
      LEFT JOIN VEF_BASE_TTABINFAD57  T57  ON (T57.BDORDEM57 = C181.BDCODMOTIVO)
      where (C181.BDCODMOTIVO IS NOT NULL);
  /*****************************************************************************
   *                                   C186                                    *
   ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD)
      SELECT :PRARQUIVO BDID,
             LPAD(MOV.BDCODEMP, 6, '0')||'.1.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C100.C185.'||LPAD(MOV.BDORDEMITENS, 6, '0')||'.'||LPAD(MOV.BDORDEMPRO, 6, '0')||'.C186.'||LPAD(C186.BDORDEM, 7, '0'),
             'C186' BDREG,
             '|C186|'||REPLACE(COALESCE(MOV.BDORDEMPRO, ''), '.', ',')||                                                                                  /*2*/
             '|'||REPLACE(COALESCE(PROD.BDCODSAIDA, ''), '.', ',')||                                                                                      /*3*/
             '|'||REPLACE(COALESCE(MOV.BDCSTICMS, ''), '.', ',')||                                                                                        /*4*/
             '|'||REPLACE(COALESCE(SUBSTRING(MOV.BDCODNAT FROM 1 FOR 4), ''), '.', ',')||                                                                 /*5*/
             '|'||REPLACE(COALESCE(T57.BDCODAJUR, ''), '.', ',')||                                                                                        /*6*/
             '|'||REPLACE(COALESCE(C186.BDQTDCONVERTIDA, ''), '.', ',')||                                                                                 /*7*/
             '|'||REPLACE(COALESCE(UNI.BDAPEUNIMED, ''), '.', ',')||                                                                                      /*8*/
             '|'||REPLACE(COALESCE(TMOD.BDMODELOSTR, ''), '.', ',')||                                                                                     /*9*/
             '|'||REPLACE(COALESCE(IIF(TMOD.BDMODELOSTR <> '55', C186.BDSERIE, ''), ''), '.', ',')||                                                      /*10*/
             '|'||REPLACE(COALESCE(IIF(TMOD.BDMODELOSTR <> '55', C186.BDNUMDOC, ''), ''), '.', ',')||                                                     /*11*/
             '|'||REPLACE(COALESCE((select bdnumero from SP_RETORNA_NUMEROS (C186.BDCHAVENFE)), ''), '.', ',')||                                          /*12*/
             '|'||REPLACE(COALESCE((select bdnumero from SP_RETORNA_NUMEROS ((select bdDDMMAAAA from DDMMAAAA (C186.BDDTEMISSAO)))), ''), '.', ',')||      /*13*/
             '|'||REPLACE(COALESCE(C186.BDORDEMPRODORIG, ''), '.', ',')||                                                                                 /*14*/
             '|'||REPLACE(COALESCE(C186.BDVLRUNICONVERTIDO, 0.00000), '.', ',')||                                                                         /*15*/
             '|'||REPLACE(COALESCE(C186.BDVLRUNITICMSOP, 0.00000), '.', ',')||                                                                            /*16*/
             '|'||REPLACE(COALESCE(C186.BDBCUNITICMSST, 0.00000), '.', ',')||                                                                             /*17*/
             '|'||REPLACE(COALESCE(C186.BDVLRUNITICMSST, 0.00000), '.', ',')||                                                                            /*18*/
             '|'||REPLACE(COALESCE(C186.BDVLRUNITFCPST, 0.00000), '.', ',')||'|', MOV.BDCODPROD                                                           /*19*/
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDDATASAIDA,PRO.BDCHAVE AS BDCHAVEPRO,PRO.BDORDEMPRO, PRO.BDCODPROD, CST.BDCSTICMS, ITENS.BDCODNAT, ITENS.BDORDEM AS BDORDEMITENS
            FROM VEF_EMP_TMOVSAI SAI
            LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE)
            LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS ITENS ON (ITENS.BDCODEMP = SAI.BDCODEMP AND ITENS.BDCHAVE = SAI.BDCHAVE AND ITENS.BDORDEM = PRO.BDORDEM)
            LEFT OUTER JOIN VEF_BASE_TTABCSTICMS CST ON (CST.BDCODCSTICMS = PRO.BDCODCSTICMS)
            WHERE SAI.BDCODEMP = :PRCODEMP
            AND SAI.BDDATASAIDA BETWEEN :PRDTINI AND :PRDTFIM
            and SAI.BDCODSITNF not in (10, 11)
           ) MOV
      JOIN VEF_EMP_TMOVC186_1250 C186 ON(C186.BDCODEMP = MOV.BDCODEMP AND C186.BDCHAVE = MOV.BDCHAVEPRO AND C186.BDORDEMPRO = MOV.BDORDEMPRO AND C186.BDORDEM = MOV.BDORDEMITENS)
      JOIN TUNIDADEMEDIDA UNI ON (UNI.BDCODUNIMED = C186.BDCODUNIMED)
      JOIN VEF_BASE_TTABMODELOLAN TMOD ON (TMOD.BDMODELO = C186.BDMODELO)
      JOIN TCADPRO_VINC PROD ON (PROD.BDCODEMP = C186.BDCODEMP and PROD.BDCODPROD = C186.BDCODPROD)
      LEFT JOIN VEF_BASE_TTABINFAD57 T57 ON (T57.BDORDEM57 = C186.BDCODMOTIVO);
END
^

create or alter procedure SP_EXPORTA_BLOCOC (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRCODPLAPADRAOREF integer,
    PRVALIDAREXPORTACAO DM_BOOLEAN,
    PRARQUIVO varchar(260),
    PREXPSER varchar(5),
    PRSESSAOSEGREG integer,
    PRMOV integer,
    PREXPORTARC170EMISSAOPROPRIA varchar(5))
as
declare variable WLINHA blob sub_type 1 segment size 200;
declare variable WTIPOEXPCODPART integer;
declare variable WPERFILSPED integer;
declare variable WSEGREGACAO varchar(5);
declare variable WICMSMONO varchar(5);
BEGIN
  DELETE FROM TEXPORTACAO_SPED WHERE BDID = :PRARQUIVO;

  SELECT Coalesce(rdb$get_context('USER_SESSION', 'W_SEGREGACAO_FISCAL'),'FALSE') FROM rdb$database INTO WSEGREGACAO;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')));

  SELECT VW.BDTIPOEXPCODPART
  FROM VW_INT_SPEDICMS_REF VW
  WHERE VW.BDCODEMP = :PRCODEMP
  INTO :wTipoExpCodPart;

  IF (ROW_COUNT = 0) THEN
    wTipoExpCodPart = -1; /*Não achou o TipoExpCodPart*/

  SELECT SP.BDPERFILSPED, SP.BDICMSMONO FROM SP_CONSULTAEMPRESAS_SIS((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')), :PRCODEMP, NULL) SP INTO :wPerfilSped, :wICMSMono;

  wPerfilSped = COALESCE(:wPerfilSped, -1);  

  IF (:WSEGREGACAO = 'TRUE') THEN
     BEGIN
       IF (:PRMOV = 0) THEN
          EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_ENT(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, :wTipoExpCodPart, :wPerfilSped, :prCODPLAPADRAOREF, :PRSESSAOSEGREG, :prexportarc170emissaopropria, :wICMSMono);
       ELSE
          EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_SAI(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, :wTipoExpCodPart, :wPerfilSped, :prCODPLAPADRAOREF, :PRSESSAOSEGREG, :prexportarc170emissaopropria);
     END
  ELSE
     BEGIN
       /*ENTRADA*/
       EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_ENT(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, :wTipoExpCodPart, :wPerfilSped, :prCODPLAPADRAOREF, :PRSESSAOSEGREG, :prexportarc170emissaopropria, :wICMSMono);

       /*SAIDA*/
       EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_SAI(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, :wTipoExpCodPart, :wPerfilSped, :prCODPLAPADRAOREF, :PRSESSAOSEGREG, :prexportarc170emissaopropria);
     END

  /*Se o perfil do sped da empresa for A, exporta registros C350, C370 e C390*/
  IF (:wPerfilSped IN (0)) THEN
    BEGIN
      EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_SAI_REG300(:PRCODEMP, :PRDTINI, :PRDTFIM,:PRARQUIVO, :wPerfilSped);
    END

  /*SERVIÇO EMITIDO*/ 
  if (:prexpser = 'TRUE') then
    BEGIN
      EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_SER(:PRCODEMP, :PRDTINI, :PRDTFIM, :prarquivo, :wTipoExpCodPart, :prCODPLAPADRAOREF);
      /*Criada opção para exportar serviços emitidos (A100/A170) para o Sped fiscal como sendo movimento de saída modelo 1 (C100/C170/C190), não afeta notas conjugadas. Larissa - 18/03/2021 - Sped Fiscal - Notas de serviços #143666 */
    END

  /*Guilherme Bauler. 26/03/2021. Instrução Normativa RE 87/15 #ExportaçãodoSPEDFiscal Exportação dos registros 1200 */
  EXECUTE PROCEDURE SP_EXPORTA_BLOCOC1250(:PRCODEMP, :PRDTINI, :PRDTFIM,:PRARQUIVO);

  /*Cria as inconsistências*/
  IF (UPPER(:PRVALIDAREXPORTACAO) = 'TRUE') THEN
    EXECUTE PROCEDURE SP_VALIDA_EXPORTACAO_SPED(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, 'C100', :PREXPSER);

  /*Deleta os registros da tabela temporária dos lançametos de serviço conjugados */
  DELETE FROM TMP_VEF_EMP_TMOVDFSAISER_TEMP TMP WHERE TMP.BDCODEMP = :PRCODEMP;

  /*****************************************************************************
   *                           EXPORTANDO ARQUIVO                              *
   ****************************************************************************/

  OPENARQ(:PRARQUIVO,:PRCODEMP);

  FOR SELECT E.BDLINHA
      FROM TEXPORTACAO_SPED E
      WHERE E.BDID = :PRARQUIVO
      ORDER BY E.BDCHAVEREG
      INTO :wLinha
  DO
    BEGIN
      WRITELNOA(:wLinha,:PRCODEMP);
    END

  CLOSEARQ(:PRARQUIVO,:PRCODEMP);

  --Limpa os dados da exportação
  --DELETE FROM TEXPORTACAO_SPED WHERE BDID = :PRARQUIVO;

END^



CREATE OR ALTER procedure SP_EXPORTA_BLOCOE (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRPERIODOAPUR integer)
as
declare variable WCODCONFIPI integer;
declare variable WCHAVE varchar(30);
declare variable WCHAVEANT varchar(30);
declare variable WVALOR numeric(15,2);
declare variable WLINHA blob sub_type 1 segment size 200;
declare variable WTIPOEXPCODPART integer;
declare variable WREFINI integer;
declare variable WREFFIM integer;
BEGIN
  SELECT CAST(BDDATA AS INTEGER) FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM') INTO :wRefIni;
  SELECT CAST(BDDATA AS INTEGER) FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM') INTO :wRefFim;

  DELETE FROM TEXPORTACAO_SPED WHERE BDID = :PRARQUIVO;

  SELECT VW.BDTIPOEXPCODPART
  FROM VW_INT_SPEDICMS_REF VW
  WHERE VW.BDCODEMP = :PRCODEMP
  INTO :wTipoExpCodPart;

  IF (ROW_COUNT = 0) THEN
    wTipoExpCodPart = -1; /*Não achou o TipoExpCodPart*/

  SELECT SP.BDCODCONFIPI FROM SP_CONSULTAEMPRESAS_SIS(:wRefFim, :PRCODEMP, NULL) SP INTO :wCodConfIPI;

  wCodConfIPI = COALESCE(:wCodConfIPI, -1);

  IF (:wCodConfIPI > 0) THEN
    BEGIN
       /*Se não houver E520(Apuração de IPI), não exporta o bloco E500. Por isso ele vem antes dos outros registros, para não exportar registro desnecessário*/
      /*****************************************************************************
       *                                   E520                                    *
       ****************************************************************************/
       wChaveAnt = '';
       FOR SELECT LPAD(R.BDCODEMP, 6, '0')||'.'||'E500.E520.'||R.BDREFERENCIA||'.'||R.BDCODPERIODO||'.'||R.BDCODQIPI, CAST(SUM(COALESCE(R.BDVALOR, 0)) AS DM_NUMERIC_15_2) BDVALOR
           FROM VEF_EMP_TIPIGERREG R
           JOIN VEF_BASE_TCONFIPIQ Q ON(Q.BDCODQIPI = R.BDCODQIPI AND Q.BDCLASSIFICACAO = '01.04')
           WHERE R.BDCODEMP = :PRCODEMP
           AND R.BDREFERENCIA BETWEEN :wRefIni AND :wRefFim
           GROUP BY R.BDCODEMP, R.BDREFERENCIA, R.BDCODPERIODO, R.BDNUMCAMPO, R.BDCODQIPI
           ORDER BY R.BDNUMCAMPO
           INTO :wChave, :wValor
       DO
         BEGIN
           IF (:wChave <> :wChaveAnt) THEN
             BEGIN
               IF (:wChaveAnt <> '') THEN
                 INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA) VALUES(:PRARQUIVO, :wChave, 'E520', :wLinha);

               wChaveAnt = :wChave;
               wLinha    = '|E520|';
             END

           wLinha = wLinha || REPLACE(:wValor, '.', ',')||'|';
         END

       IF (:wLinha <> '') THEN
         INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA) VALUES(:PRARQUIVO, :wChave, 'E520', :wLinha);

       IF (ROW_COUNT = 0) THEN
         EXIT;

      /*****************************************************************************
       *                                   E500                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      VALUES(:PRARQUIVO, LPAD(:PRCODEMP, 6, '0')||'.E500', 'E500',
              '|E500|'||:PRPERIODOAPUR||'|'||(SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'DDMMYYYY'))||'|'||(SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'DDMMYYYY'))||'|');

      /*****************************************************************************
       *                                   E510                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(:PRCODEMP, 6, '0')||'.E500.E510.'||COALESCE(IPI.BDPREFIXONAT, '')||'|'||COALESCE(IPI.BDCODEXPCSTIPI, '') BDCHAVEREG,
             'E510' BDREG,
             '|E510'||
             '|'||COALESCE(IPI.BDPREFIXONAT, '')||   --CFOP
             '|'||LPAD(COALESCE(IPI.BDCODEXPCSTIPI, ''), 2, '0')|| --CST_IPI
             '|'||REPLACE(COALESCE(IPI.BDVLRITEM, 0.00), '.', ',')|| --VL_CONT_IPI
             '|'||REPLACE(COALESCE(IPI.BDBCIPI, 0.00), '.', ',')|| --VL_BC_IPI
             '|'||REPLACE(COALESCE(IPI.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
             '|'
      FROM (
            SELECT 0 BDMOV /*Entrada*/, ENT.BDPREFIXONAT, IPI.BDCODEXPCSTIPI,
                 --Elizeu - 10-09-19 - Feito no campo 4 a soma abaixo: Cartão:Exportação Sped Fiscal - Registro E510 #125104
                 --valor das mercadorias + fretes+ seguros + outras despesas acessórias + ICMS_ST + FCP + FCP_ST + IPI - desconto -  abatimento
                   SUM(((COALESCE(PRO.BDVLRITEM, 0) + COALESCE(PRO.bdvlrfrete, 0) +COALESCE(PRO.BDVLRSEGURO, 0) + COALESCE(PRO.bdvlrdespacessoria, 0) + COALESCE(PRO.bdvlrst, 0) +
                        COALESCE(PRO.BDFCPRETIDO, 0) + COALESCE(PRO.bdvlrfcpstret, 0) + COALESCE(PRO.bdvlripi, 0)) - (COALESCE(PRO.bdvlrdesc, 0) + COALESCE(PRO.bdvlrabatnt,0)))
                       ) BDVLRITEM,
                   SUM(COALESCE(PRO.BDBCIPI, 0)) BDBCIPI,
                   SUM(COALESCE(PRO.BDVLRIPI, 0)) BDVLRIPI
            FROM (
                  SELECT ENT.BDCODEMP, ENT.BDCHAVE, I.BDORDEM, I.BDPREFIXONAT
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM VEF_EMP_TMOVENT M
                              WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                             --21769 não precisa olhar o modelo da nota para exportar o E510, segundo a Graci
                              AND M.BDMODELO IN (1, 4, 55, 65, 100)
                              -- elizeu - 03-07-18 - Sped Fiscal - Exportação IPI Totais CFOP - E510 - Valor documento cancelado #79557 #85698
                              and M.BDCODSITNF not IN (2, 3, 4, 5, 10, 11)
--                              AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Próprio
                             ) MOV
                       ) ENT
                  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
                 ) ENT
            JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE AND PRO.BDORDEM = ENT.BDORDEM)
            JOIN VEF_BASE_TTABCSTIPI IPI ON(IPI.BDCODCSTIPI = PRO.BDCODCSTIPI)
            GROUP BY ENT.BDPREFIXONAT, IPI.BDCODEXPCSTIPI
            UNION ALL
            SELECT 1 BDMOV /*Saída*/, SAI.BDPREFIXONAT, IPI.BDCODEXPCSTIPI,
                 --Elizeu - 10-09-19 - Feito no campo 4 a soma abaixo: Cartão:Exportação Sped Fiscal - Registro E510 #125104
                 --valor das mercadorias + fretes+ seguros + outras despesas acessórias + ICMS_ST + FCP + FCP_ST + IPI - desconto -  abatimento
                   SUM(((COALESCE(PRO.BDVLRITEM, 0) + COALESCE(PRO.bdvlrfrete, 0) + COALESCE(PRO.BDVLRSEGURO, 0) + COALESCE(PRO.bdvlrdespacessoria, 0) + COALESCE(PRO.bdvlrst, 0) +
                        COALESCE(PRO.BDFCPRETIDO, 0) + COALESCE(PRO.bdvlrfcpstret, 0) + COALESCE(PRO.bdvlripi, 0)) - (COALESCE(PRO.bdvlrdesc, 0) + COALESCE(PRO.bdvlrabatnt,0)))
                       ) BDVLRITEM,
                   SUM(COALESCE(PRO.BDBCIPI, 0)) BDBCIPI,
                   SUM(COALESCE(PRO.BDVLRIPI, 0)) BDVLRIPI
            FROM (
                  SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, I.BDPREFIXONAT
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM VEF_EMP_TMOVSAI M
                              WHERE M.BDCODEMP = :PRCODEMP
                              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                              -- elizeu - 03-07-18 - Sped Fiscal - Exportação IPI Totais CFOP - E510 - Valor documento cancelado #79557 #85698
                              and M.BDCODSITNF not IN (2, 3, 4, 5, 10, 11)
                              --21769 não precisa olhar o modelo da nota para exportar o E510
                              AND M.BDMODELO IN (1, 4, 55, 65, 100)
--                            AND NOT((M.BDMODELO IN (55, 65)) AND (M.BDEMITENTE = 0)) --Próprio
                             ) MOV
                       ) SAI
                  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                 ) SAI
            JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
            JOIN VEF_BASE_TTABCSTIPI IPI ON(IPI.BDCODCSTIPI = PRO.BDCODCSTIPI)
            GROUP BY SAI.BDPREFIXONAT, IPI.BDCODEXPCSTIPI
           ) IPI
        ORDER BY IPI.BDMOV;

      /*****************************************************************************
       *                                   E530                                    *
       ****************************************************************************/
       INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
       SELECT :PRARQUIVO BDID,
              (LPAD(E530.BDCODEMP, 6, '0')||'.E500.E520.E530.'||LPAD(E530.BDCHAVE, 6, '0')),
              'E530',
              '|E530'||
              '|'||COALESCE((1 - IPI.BDDEBCRED), '')|| --IND_AJ
              '|'||REPLACE(COALESCE(CAST(E530.BDVALOR AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --VL_AJ
              '|'||LPAD(COALESCE(IPI.BDCODAJU, ''), 3, '0')|| --COD_AJ
              '|'||COALESCE(DOC.BDCODEXP, '')|| --IND_DOC
              '|'||REPLACE(COALESCE(E530.BDNUMDOC, ''), '|', '')|| --NUM_DOC
              '|'||REPLACE(COALESCE(E530.BDDESCAJU, ''), '|', '')|| --DESCR_AJ
              '|'
       FROM (
             SELECT E530.BDCODEMP, E530.BDCHAVE, E530.BDCODAJU, E530.BDVALOR,
                    E530.BDINDORIGEM, E530.BDNUMDOC, E530.BDDESCAJU
             FROM VEF_EMP_TAJUSTEIPIE530 E530
             WHERE E530.BDCODEMP = :PRCODEMP
             AND ((E530.BDREFERENCIA >= :wRefIni) AND (E530.BDREFERENCIA <= :wRefFim))
            ) E530
       JOIN VEF_BASE_TTABCODAJUAPUIPI IPI ON (IPI.BDCODAJU = E530.BDCODAJU)
       LEFT OUTER JOIN VEF_BASE_TTABINDDOC DOC ON (DOC.BDINDORIGEM = E530.BDINDORIGEM);

       /*Sol: 20474 Patrick T. Sá 16/11/2017. Feito no banco, havia sido feito na classe*/
      /*****************************************************************************
       *                                   E531                                    *
       ****************************************************************************/
       INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODPROD)
       SELECT :PRARQUIVO BDID,
              (LPAD(E530.BDCODEMP, 6, '0')||'.E500.E520.E530.'||LPAD(E531.BDCHAVE, 6, '0')||'.E531.'||LPAD(E531.BDORDEM, 6, '0')),
              'E531',
              '|E531'||
              '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:wTipoExpCodPart, E531.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO)), '')|| --COD_PART
              '|'||COALESCE(DOC.BDDOCFIS, '')|| --COD_MOD
              '|'||COALESCE(E531.BDSERIE, '')|| --SER
              '|'||COALESCE(E531.BDSUBSERIE, '')|| --SUB
              '|'||COALESCE(E531.BDNUMDOC, '')|| --NUM_DOC
              '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(E531.BDDATAEMISSAO, 'DDMMYYYY')), '')|| --DT_DOC
              '|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')), Coalesce(VINC.BDCODPROD,''), VINC.BDCODSAIDA)|| --COD_ITEM
              '|'||REPLACE(COALESCE(E531.BDVLRAJUSTE, 0.00), '.', ',')|| --VL_AJ_ITEM
              '|'||COALESCE(IIF(E531.BDCODDOCFIS = 30, (RPAD((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(E531.BDCHAVENFE)), 44, ' ')), NULL), '')|| --CHV_NFE
              '|', E531.BDCODTER, E531.BDCODPROD
       FROM (
             SELECT E530.BDCODEMP, E530.BDCHAVE
             FROM VEF_EMP_TAJUSTEIPIE530 E530
             WHERE E530.BDCODEMP = :PRCODEMP
             AND ((E530.BDREFERENCIA >= :wRefIni) AND (E530.BDREFERENCIA <= :wRefFim))
            ) E530
       JOIN VEF_EMP_TAJUSTEIPIE531 E531 ON(E531.BDCODEMP = E530.BDCODEMP AND E531.BDCHAVE = E530.BDCHAVE)
       LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOC ON (DOC.BDCODDOCFIS = E531.BDCODDOCFIS)
       LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = E531.BDCODEMP AND VINC.BDCODPROD = E531.BDCODPROD)
       LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = E531.BDCODTER)
       LEFT OUTER JOIN (
                        SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                        FROM (
                              SELECT t.bdcodemp, t.bdcodter,
                                     COALESCE(
                                              (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= :wRefIni) ORDER BY e.bdreferencia DESC),
                                              (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                             ) BDCODIGO
                              FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                             ) tt
                        LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                       ) TerEmp ON (TerEmp.bdcodter = E531.bdcodter);
    END


  /*****************************************************************************
   *                           EXPORTANDO ARQUIVO                              *
   ****************************************************************************/

  OPENARQ(:PRARQUIVO,:PRCODEMP);

  FOR SELECT E.BDLINHA
      FROM TEXPORTACAO_SPED E
      WHERE E.BDID = :PRARQUIVO
      ORDER BY E.BDCHAVEREG
      INTO :wLinha
  DO
    BEGIN
      WRITELNOA(:wLinha,:PRCODEMP);
  --    WRITELN(:PRARQUIVO, :wLinha);
    END
  CLOSEARQ(:PRARQUIVO,:PRCODEMP);
END^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOD_ENT (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRTIPOEXPCODPART integer,
    PRCODPLAPADRAOREF integer)
as
declare variable WSEGREGACAO varchar(5);
declare variable WCHAVEMIN integer;
declare variable WCHAVEMAX integer;
BEGIN
  /*****************************************************************************
   *-------------------------------->>ENTRADA<<--------------------------------*
   ****************************************************************************/
  SELECT Coalesce(rdb$get_context('USER_SESSION', 'W_SEGREGACAO_FISCAL'),'FALSE') FROM rdb$database INTO WSEGREGACAO;

   SELECT MIN(e.bdCHAVE) AS bdCHAVEMIN, MAX(e.bdCHAVE) AS bdCHAVEMAX
   FROM VEF_EMP_TMOVENT E
   LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = E.BDCODEMP)
   WHERE E.BDCODEMP = :prCODEMP
     AND E.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, E.BDCHAVE)
     AND E.BDDATAENTRADAENT BETWEEN :prDTINI AND :prDTFIM
     AND E.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800,63) -- Novo modelo 63 #123465
   INTO :wCHAVEMIN, :wCHAVEMAX;

  /*****************************************************************************
   *                                   D100                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODINFCOM, BDORDEMINFCOM,BDCHAVE,BDCREDITO,BDANOCREDITO,BDCODPLAPADRAO,BDCREDITOREF,BDCREDITOPLAPADRAOREF,BDCTALON)
  SELECT  :PRARQUIVO BDID,
          LPAD(M.BDCODEMP, 6, '0')||'.0.'||LPAD(M.BDCHAVE, 10, '0')||'.D100',
          'D100' BDREG,
          ('|D100|0'||
           '|'||M.BDEMITENTE||                    /* MODELO 63 NÃO EXPORTA O PARCIPANTE */
           '|'||IIF((M.BDCODSITNF IN (2, 3, 4, 5) OR M.BDMODELO = 63), '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, M.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO)))|| --COD_PART
           '|'||MOD.BDMODELOSTR||            --COD_MOD
           '|'||LPAD(M.BDCODSITNF, 2, '0')|| --COD_SIT
           '|'||COALESCE(M.BDSERIE, '')||    --SER
           '|'||COALESCE(M.BDSUBSERIE, '')|| --SUB
           '|'||M.BDNUMDOCINI||              --NUM_DOC
           '|'||COALESCE(IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)) = '', '', RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)), 44, ' ')), '')||       --CHV_NFE
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))||    --DT_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(IIF(M.BDCODSITNF IN(1, 3, 7), M.BDDATAEMISSAO, M.BDDATAENTRADAENT), 'DDMMYYYY')))|| --DT_A_P
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(IIF(M.BDMODELO IN(57, 67, 63), D100.BDTIPOCTE, ''), ''))|| --TP_CT-e
           /*'|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D100.BDCHAVECTEREF)), ''))|| --CHV_CTE_REF
            Criado modelo 63, só deve ser informado a chave de CTE se o tipo de CTE for 1 ou 2 #123465 - Camilla M. 05/11/19 */
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(IIF(M.BDMODELO = 63,IIF(D100.BDTIPOCTE IN (3),(SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D100.BDCHAVECTEREF)),''),(SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D100.BDCHAVECTEREF))),''))|| --CHV_CTE_REF
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(SUM(COALESCE(MOV.BDVLRCONTAB, 0.00)), '.', ','), ''))||                --VL_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(M.BDDESCONTONOTA, '.', ','), ''))||              --VL_DESC
           '|'||IIF((M.BDCODSITNF IN (2, 3, 4, 5) OR M.BDMODELO = 63), '', COALESCE((IIF(((INDFRETED100.BDCODEXPFRETE = '') OR (INDFRETED100.BDCODEXPFRETE IS NULL)), '0', INDFRETED100.BDCODEXPFRETE)), ''))|| --IND_FRT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(SUM(COALESCE(MOV.BDVLRCONTAB, 0.00)), '.', ','), ''))||                --VL_SERV
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(COALESCE(SUM(COALESCE(MOV.BDBASEICMS, 0.00)), 0.00), '.', ','), ''))|| --VL_BC_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(COALESCE(SUM(COALESCE(MOV.BDVLRICMS, 0.00)), 0.00), '.', ','), ''))||  --VL_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(COALESCE(SUM(COALESCE(MOV.BDISENTASICMS, 0.00)) +  SUM(COALESCE(MOV.BDOUTRASICMS, 0.00)), 0.00), '.', ','), ''))|| --VL_NT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(INFCOMD100.BDCODINFCOM, ''))|| --COD_INF
           --'|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(D100.BDCODCTA, ''))||          --COD_CTA
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE((CASE ConfSPED.bdTIPOEXPCONTA
                                                                  WHEN '0' THEN COALESCE(CDL.BDCODTPLA, CDLRAT.BDCODTPLA)
                                                                  WHEN '1' THEN COALESCE(CDL.BDCTALON, CDLRAT.BDCTALON)
                                                                  WHEN '2' THEN COALESCE(CDL.BDAPECTA, CDLRAT.BDAPECTA)
                                                                ELSE COALESCE(CDLEP.bdCTALON,CDLEPRAT.bdCTALON) END), ''))|| --COD_CTA
           --Campos exportados apartir de 01/01/2018
           IIF((EXTRACT(YEAR FROM :PRDTINI)) < 2018, '', IIF(M.BDCODSITNF IN (2, 3, 4, 5), '|', '|'|| IIF(D100.BDTIPOCTE IN ('05','06'),'9999998',COALESCE(CIDORIGD100.BDCODIBGE, ''))))|| --COD_MUN_ORIG
           IIF((EXTRACT(YEAR FROM :PRDTINI)) < 2018, '', IIF(M.BDCODSITNF IN (2, 3, 4, 5), '|', '|'|| IIF(D100.BDTIPOCTE IN ('05','06'),'9999998',COALESCE(CIDDESTD100.BDCODIBGE, ''))))|| --COD_MUN_DEST
           '|'
           ), IIF(((M.BDCODSITNF IN (2, 3, 4, 5))), NULL, M.BDCODTER) BDCODTER, INFCOMD100.BDCODINFCOM, INFCOMD100.BDORDEMINFCOM,
           M.BDCHAVE, COALESCE(CDL.BDCODTPLA,CDLRAT.BDCODTPLA) BDCREDITO, COALESCE(COALESCE(CDLE.BDANO, CDLERAT.BDANO), CAST(SUBSTRING(MOV.BDREFLAN FROM 1 FOR 4) AS INTEGER)) BDANOCREDITO,
           COALESCE(D100.BDCODPLAPADRAO, COALESCE(LAN.BDCODPLAPADRAO, LANRAT.BDCODPLAPADRAO)) BDCODPLAPADRAO, COALESCE(CDLEP.BDCODTPLAREF, CDLEPRAT.BDCODTPLAREF) BDCREDITOREF,
           COALESCE(CDLEP.BDCODPLAPADRAOREF, CDLEPRAT.BDCODPLAPADRAOREF) BDCREDITOPLAPADRAOREF, COALESCE(CDL.BDCTALON, CDLRAT.BDCTALON) BDCTALON
  FROM (
--        SELECT E.BDCODEMP, E.BDCHAVE, E.BDREFLAN
--        FROM VEF_EMP_TMOVENT E
--        WHERE E.BDCODEMP = :PRCODEMP
--          AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
--          AND E.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800,63) -- Novo modelo 63 #123465

        select lan.bdcodemp,lan.bdchave,lan.bdreflan,Min(i.bdordem) bdordem, sum(I.BDVLRCONTAB) BDVLRCONTAB,
        sum(BDOUTRASICMS) BDOUTRASICMS, sum(BDBASEICMS) BDBASEICMS,sum(BDVLRICMS) BDVLRICMS,sum(BDISENTASICMS) BDISENTASICMS
        from (
                SELECT E.BDCODEMP, E.BDCHAVE, E.BDREFLAN
                FROM VEF_EMP_TMOVENT E
                LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = E.BDCODEMP)
                WHERE E.BDCODEMP = :PRCODEMP
                  AND E.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, E.BDCHAVE)
                  AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND E.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800,63) -- Novo modelo 63 #123465
                  AND NOT (/*E.BDMODELO IN (57, 63, 67) AND */E.BDCODSITNF IN (4, 5, 10, 11) AND E.BDREFLAN >= 202301) --#169202 - Adam - 09/11/2022 - Em 2023 os modelos 57, 63 e 65 deixarão de usar as situações 4 e 5.
              )lan
       LEFT OUTER JOIN VEF_EMP_TMOVENTITENS i ON(I.BDCODEMP = lan.BDCODEMP AND I.BDCHAVE = lan.BDCHAVE)
       group by lan.bdcodemp,lan.bdchave,lan.bdreflan
       ) MOV
  JOIN VEF_EMP_TMOVENT M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
--  LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TTABMODELOLAN MOD ON(MOD.BDMODELO = M.BDMODELO)
  LEFT OUTER JOIN VEF_EMP_TD100ENT D100 ON (D100.BDCODEMP = M.BDCODEMP AND D100.BDCHAVE = M.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TTABINFRETE INDFRETED100 ON (D100.BDINDFRETE = INDFRETED100.BDORDEMFRETE)
  LEFT OUTER JOIN VEF_BASE_TCADINFCOM INFCOMD100 ON (D100.BDORDEMINFCOM = INFCOMD100.BDORDEMINFCOM)
  LEFT OUTER JOIN TCIDADE CIDORIGD100 ON (D100.BDCIDORIGEM = CIDORIGD100.BDCODCID)
  LEFT OUTER JOIN TCIDADE CIDDESTD100 ON (D100.BDCIDDEST = CIDDESTD100.BDCODCID)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = M.BDCODTER)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = M.bdcodter)
  -- Alt.: #87095 #92148 #89325 #92407 #100955 #121349 - Ajustes para levar a conta referencial na exportação do lançamento
  LEFT OUTER JOIN VW_INT_SPEDICMS_REF ConfSPED ON (ConfSPED.bdCODEMP = mov.bdCODEMP)
  LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVEENT, t.bdORDEM, MIN(t.bdCHAVE) AS BDCHAVE, l.bdCODPLAPADRAO, l.bdDEBITO
                   FROM TOL_VEF_EMP_TMOVENT t
                   LEFT OUTER JOIN VSUC_EMPRESAS_TLAN l ON (l.bdCODEMP = t.bdCODEMP AND l.bdCHAVE = t.bdCHAVE)
                   WHERE t.bdFORMULA LIKE '%NAT%LAN(%)' -- Alt.: #92219 - Apenas contas do valor contábil...
                     AND l.bdDEBITO IS NOT NULL -- Alt.: #120050 - Para apenas retornar quando a contabilização tiver uma conta informada, quando tem desconto a conta do desconto vem primeiro...
                     AND t.bdCODEMP = :PRCODEMP
                     AND t.bdCHAVEENT BETWEEN :wCHAVEMIN AND :wCHAVEMAX
                   GROUP BY t.bdCODEMP, t.bdCHAVEENT, t.bdORDEM, l.bdCODPLAPADRAO, l.bdDEBITO) LAN ON (lan.bdCODEMP = MOV.bdCODEMP AND lan.bdCHAVEENT = MOV.bdCHAVE AND lan.bdORDEM = MOV.bdORDEM)
  LEFT OUTER JOIN PLANOS_TPLA CDL ON (COALESCE(D100.BDCODPLAPADRAO,LAN.BDCODPLAPADRAO) = CDL.BDCODPLAPADRAO AND COALESCE(D100.BDCODTPLA,LAN.BDDEBITO) = CDL.BDCODTPLA)
  LEFT OUTER JOIN PLANOS_TPLA_ECF CDLE ON (CDLE.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF
                                       AND CDLE.BDANO = (SELECT FIRST 1 BDANO
                                                         FROM PLANOS_TPLA_ECF 
                                                         WHERE CAST(BDANO || '01' AS INTEGER) <= MOV.BDREFLAN
                                                           AND BDCODTPLAREF IS NOT NULL
                                                           AND CDLE.BDCODPLAPADRAO = BDCODPLAPADRAO
                                                           AND CDLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF
                                                           AND CDLE.BDCODTPLA = BDCODTPLA
                                                         ORDER BY BDANO DESC)
                                       AND CDLE.BDCODPLAPADRAO = CDL.BDCODPLAPADRAO AND CDLE.BDCODTPLA = CDL.BDCODTPLA)
  LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO CDLEP ON (CDLE.BDCODPLAPADRAOREF = CDLEP.BDCODPLAPADRAOREF AND CDLE.BDCODTPLAREF = CDLEP.BDCODTPLAREF) 
  LEFT OUTER JOIN  (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) BDCHAVE FROM TOL_VEF_EMP_TMOVRATENT GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT 
                    ON (TOLRAT.BDCODEMP = MOV.BDCODEMP AND TOLRAT.BDCHAVELAN = MOV.BDCHAVE AND TOLRAT.BDORDEM = MOV.BDORDEM)
  LEFT OUTER JOIN VSUC_EMPRESAS_TLAN LANRAT ON (LANRAT.BDCODEMP = TOLRAT.BDCODEMP AND LANRAT.BDCHAVE = TOLRAT.BDCHAVE) 
  LEFT OUTER JOIN PLANOS_TPLA CDLRAT ON (COALESCE(D100.BDCODPLAPADRAO,LANRAT.BDCODPLAPADRAO) = CDLRAT.BDCODPLAPADRAO AND COALESCE(D100.BDCODTPLA,LANRAT.BDDEBITO) = CDLRAT.BDCODTPLA)
  LEFT OUTER JOIN PLANOS_TPLA_ECF CDLERAT ON (CDLERAT.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF
                                          AND CDLERAT.BDANO = (SELECT FIRST 1 BDANO
                                                               FROM PLANOS_TPLA_ECF 
                                                               WHERE CAST(BDANO || '01' AS INTEGER) <= LANRAT.BDREFERENCIA
                                                                 AND BDCODTPLAREF IS NOT NULL
                                                                 AND CDLERAT.BDCODPLAPADRAO = BDCODPLAPADRAO
                                                                 AND CDLERAT.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF
                                                                 AND CDLERAT.BDCODTPLA = BDCODTPLA
                                                               ORDER BY BDANO DESC)
                                          AND CDLERAT.BDCODPLAPADRAO = CDLRAT.BDCODPLAPADRAO
                                          AND CDLERAT.BDCODTPLA = CDLRAT.BDCODTPLA)
  LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO CDLEPRAT ON (CDLERAT.BDCODPLAPADRAOREF = CDLEPRAT.BDCODPLAPADRAOREF AND CDLERAT.BDCODTPLAREF = CDLEPRAT.BDCODTPLAREF)
  -- Alt.: #87095 #92148 #89325 #92407 #100955 #121349 - Fim
  GROUP BY M.BDCODEMP,M.BDCHAVE,M.BDEMITENTE,M.BDCODSITNF,M.BDMODELO,M.BDCODTER,TER.BDCGCTER,TER.BDIETER,TerEmp.BDCODIGOARQUIVO,
           MOD.BDMODELOSTR,M.BDSERIE,M.BDSUBSERIE,M.BDNUMDOCINI,M.BDCHAVENFE,M.BDDATAEMISSAO,M.BDDATAENTRADAENT,D100.BDTIPOCTE,
           D100.BDCHAVECTEREF,M.BDDESCONTONOTA,INDFRETED100.BDCODEXPFRETE,D100.BDCODCTA,CIDORIGD100.BDCODIBGE,CIDDESTD100.BDCODIBGE,
           M.BDCODSITNF,M.BDCODTER,INFCOMD100.BDCODINFCOM,INFCOMD100.BDORDEMINFCOM,CDL.BDCODTPLA,CDLRAT.BDCODTPLA,CDLE.BDANO,
           CDLERAT.BDANO,MOV.BDREFLAN,D100.BDCODPLAPADRAO,LAN.BDCODPLAPADRAO,LANRAT.BDCODPLAPADRAO,CDLEP.BDCODTPLAREF,CDLEPRAT.BDCODTPLAREF,
           CDLEP.BDCODPLAPADRAOREF,CDLEPRAT.BDCODPLAPADRAOREF,CDL.BDCTALON,CDLRAT.BDCTALON,
           ConfSPED.bdTIPOEXPCONTA,CDL.BDAPECTA,CDLRAT.BDAPECTA,CDLEP.bdCTALON,CDLEPRAT.bdCTALON;

  /*****************************************************************************
   *                                   D101                                    *
   ****************************************************************************/
  IF (:PRDTINI >= '01/01/2016') THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(M.BDCODEMP, 6, '0')||'.0.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D101',
             'D101' BDREG,
             ('|D101'||
              '|'||REPLACE(COALESCE(D100.BDVLR_FCP_UF_DEST, 0.00), '.', ',')||
              '|'||REPLACE(COALESCE(D100.BDVLRICMS_UF_DEST, 0.00), '.', ',')||
              '|'||REPLACE(COALESCE(D100.BDVLRICMS_UF_REM, 0.00), '.', ',')||'|'
             )
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDMODELO,
                   SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB
            FROM (
                  SELECT E.BDCODEMP, E.BDCHAVE, E.BDMODELO
                  FROM VEF_EMP_TMOVENT E
                  LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = E.BDCODEMP)
                  WHERE E.BDCODEMP = :PRCODEMP
                  AND E.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, E.BDCHAVE)
                  AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                  AND E.BDMODELO IN(57, 67, 63)
                  AND E.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11) --Cancelado
                 ) MOV
            LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
            GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDMODELO
           ) M
        JOIN VEF_EMP_TD100ENT D100 ON (D100.BDCODEMP = M.BDCODEMP AND D100.BDCHAVE = M.BDCHAVE)
        JOIN TCIDADE CID_ORIG ON (CID_ORIG.BDCODCID = D100.BDCIDORIGEM)
        JOIN TCIDADE CID_DEST ON (CID_DEST.BDCODCID = D100.BDCIDDEST)
      WHERE ((M.BDVLRCONTAB > 0) AND ((D100.BDVLR_FCP_UF_DEST > 0) OR (D100.BDVLRICMS_UF_DEST > 0) OR (D100.BDVLRICMS_UF_REM > 0))) or ((M.BDMODELO = 63) and (CID_ORIG.BDCODUF <> CID_DEST.BDCODUF));
    END

  /*****************************************************************************
   *                                   D190                                    *
   ****************************************************************************/
  SETORDEMSEQUENCIAL(0);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT  :PRARQUIVO BDID,
          LPAD(M.BDCODEMP, 6, '0')||'.0.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D190.'||LPAD(GETORDEMSEQUENCIAL_STR(M.BDCHAVE,M.BDCODEMP), 10, '0'),
          'D190' BDREG,
          ('|D190'||
           '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
           '|'||COALESCE(SUBSTRING(I.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
           '|'||COALESCE(REPLACE(CAST(I.BDALIQICMS AS NUMERIC(6, 2)), '.', ','), '')||  --ALIQ_ICMS
           '|'||COALESCE(REPLACE(SUM(I.BDVLRCONTAB), '.', ','), '')|| --VL_OPR
           '|'||COALESCE(REPLACE(SUM(I.BDBASEICMS), '.', ','), '0,00')|| --VL_BC_ICMS
           '|'||COALESCE(REPLACE(SUM(I.BDVLRICMS), '.', ','), '0,00')|| --VL_ICMS
           '|'||REPLACE((SELECT BDVALOR FROM GET_TRATA_VALOR_NEGATIVO(IIF((SUBSTRING(ICMS.BDCSTICMS FROM 2 FOR 2) IN (20, 70)), (COALESCE(SUM(I.BDISENTASICMS), 0) + COALESCE(SUM(I.BDOUTRASICMS) , 0)), 0.00))), '.', ',')|| --VL_RED_BC
           '|'||COALESCE(I.BDCODOBS, '')|| --COD_OBS
           '|'  
           )
  FROM (
        SELECT E.BDCODEMP, E.BDCHAVE
        FROM VEF_EMP_TMOVENT E
        LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = E.BDCODEMP)
        WHERE E.BDCODEMP = :PRCODEMP
        AND E.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, E.BDCHAVE)
        AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND E.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800,63)
        AND E.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11) --Cancelado
       ) MOV
  JOIN VEF_EMP_TMOVENT M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = I.BDCODCSTICMS)
  GROUP BY M.BDCODEMP,M.BDCHAVE,ICMS.BDCSTICMS,SUBSTRING(I.BDCODNAT FROM 1 FOR 4),I.BDALIQICMS,I.BDCODOBS; /*Sped Fiscal - D190 duplicado #132552 - Tem que agrupar por CST,CFOP e Aliq de ICMS*/

  /*****************************************************************************
   *                                   D195                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
  SELECT :PRARQUIVO BDID,
         LPAD(D195.BDCODEMP, 6, '0')||'.0.'||LPAD(D195.BDCHAVE, 10, '0')||'.D100.D195.'||LPAD(D195.BDORDEMOBS, 10, '0'),
         'D195' BDREG,
         ('|D195'||
          '|'||COALESCE(OBS.BDCODEXP, '')|| --COD_OBS
          '|'||COALESCE(REPLACE(D195.BDDESCCOMPL, '|', ''), '')|| --TXT_COMPL
          '|'
         ), D195.BDCODOBS
  FROM (
        SELECT E.BDCODEMP, E.BDCHAVE
        FROM VEF_EMP_TMOVENT E
        LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = E.BDCODEMP)
        WHERE E.BDCODEMP = :PRCODEMP
        AND E.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, E.BDCHAVE)
        AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND E.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800,63)
        AND E.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11) --Cancelado
       ) MOV
  JOIN VEF_EMP_TMOVENT M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TD195ENT D195 ON(D195.BDCODEMP = MOV.BDCODEMP AND D195.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TOBSERVACAO OBS ON(OBS.BDCODOBS = D195.BDCODOBS);

  /*****************************************************************************
   *                                   D197                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD)
  SELECT  :PRARQUIVO BDID,
          LPAD(D197.BDCODEMP, 6, '0')||'.0.'||LPAD(D197.BDCHAVE, 10, '0')||'.D100.D195.'||LPAD(D197.BDORDEMOBS, 10, '0')||'.D197.'||LPAD(D197.BDORDEMOUTOBR, 10, '0'),
          'D197' BDREG,
          ('|D197'||
           '|'||COALESCE(AJU.BDCODAJUPAD, '')|| --COD_AJ
           '|'||COALESCE(REPLACE(D197.BDDESCCOMPL, '|', ''), '')|| --DESCR_COMPL_AJ
           '|'||COALESCE(IIF(PRO.BDCODSAIDA <> '', PRO.BDCODSAIDA, PRO.BDCODPROD), '')|| --COD_ITEM
           '|'||COALESCE(REPLACE(D197.BDBICMS, '.', ','), '')|| --VL_BC_ICMS
           '|'||COALESCE(REPLACE(CAST(D197.BDALIQICMS AS DM_NUMERIC_15_2), '.', ','), '')|| --ALIQ_ICMS
           '|'||COALESCE(REPLACE(D197.BDVLRICMS, '.', ','), '')|| --VL_ICMS
           '|'||COALESCE(REPLACE(D197.BDOUTVLR, '.', ','), '')|| --VL_OUTROS
           '|'
           ), D197.BDCODPROD
  FROM (
        SELECT E.BDCODEMP, E.BDCHAVE
        FROM VEF_EMP_TMOVENT E
        LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = E.BDCODEMP)
        WHERE E.BDCODEMP = :PRCODEMP
        AND E.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, E.BDCHAVE)
        AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND E.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800,63)
        AND E.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11) --Cancelado
       ) MOV
  JOIN VEF_EMP_TMOVENT M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TD195ENT D195 ON(D195.BDCODEMP = MOV.BDCODEMP AND D195.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TD197ENT D197 ON(D197.BDCODEMP = D195.BDCODEMP AND D197.BDCHAVE = D195.BDCHAVE AND D197.BDORDEMOBS = D195.BDORDEMOBS)
  LEFT OUTER JOIN VEF_BASE_TTABCODAJU AJU ON(AJU.BDCODAJU = D197.BDCODAJU)
  LEFT OUTER JOIN TCADPRO_VINC PRO ON (PRO.BDCODEMP = D197.BDCODEMP AND PRO.BDCODPROD = D197.BDCODPROD);
  
END^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOD_ENT_D700 (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRTIPOEXPCODPART integer)
as
BEGIN
   /*                                D700                                     */
   INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
    SELECT :PRARQUIVO  BDID,
          LPAD(M.BDCODEMP, 6, '0')||'.0.'||LPAD(m.bdchave, 10, '0')||'.D700' BDCHAVEREG,
          'D700' BDREG,
          ('|D700|0'||                              --REG | IND_OPER
           '|'||M.IND_EMIT||                        
           '|'||(SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, M.BDCODTER, m.BDCGCTER, m.BDIETER, m.BDCODIGOARQUIVO))|| --COD_PART
           '|'||'62'||                              --COD_MOD
           '|'||LPAD(m.COD_SIT, 2, '0')||           
           '|'||M.SER||                             
           '|'||IIF(M.NUM_DOC = 0, '', M.NUM_DOC)|| 
           '|'||M.DT_DOC|| 
           '|'||M.DT_E_S|| 
           '|'||REPLACE(M.VL_DOC,       '.', ',')|| 
           '|'||REPLACE(M.VL_DESC,      '.', ',')|| 
           '|'||REPLACE(m.VL_SERV,      '.', ',')|| 
           '|'||REPLACE(M.VL_SERV_NT,   '.', ',')|| 
           '|'||REPLACE(M.VL_TERC,      '.', ',')|| 
           '|'||REPLACE(M.VL_DA,        '.', ',')|| 
           '|'||REPLACE(m.VL_BC_ICMS,   '.', ',')|| 
           '|'||REPLACE(m.VL_ICMS,      '.', ',')|| 
           '|'||M.COD_INF|| 
           '|'||REPLACE(m.VL_PIS,       '.', ',')|| 
           '|'||REPLACE(m.VL_COFINS,    '.', ',')|| 
           '|'||m.CHV_DOCe||
           '|'||(CASE  WHEN m.FIN_DOCe = 0  THEN 0
                      WHEN m.FIN_DOCe = 1  THEN 3
                      WHEN m.FIN_DOCe = 2  THEN 4
                      when m.FIN_DOCe = -1 then ''
                END) ||     
           '|'||m.TIP_FAT|| 
           '|'||CASE  WHEN m.COD_MOD_DOC_REF = 0  THEN 21
                      WHEN m.COD_MOD_DOC_REF = 1  THEN 22
                      WHEN m.COD_MOD_DOC_REF = 2  THEN 62
                      when m.COD_MOD_DOC_REF = -1 then ''
                 END||      
           '|'||m.CHV_DOCe_REF|| 
           '|'||m.HASH_DOC_REF|| 
           '|'||m.SER_DOC_REF||  
           '|'||m.NUM_DOC_REF||  
           '|'||M.MES_DOC_REF||  
           '|'||M.COD_MUN_DEST|| 
           IIF(m.DED <> '', '|'||REPLACE(m.DED, '.', ','), m.DED)||
           '|'
           ) BDLINHA,
           m.BDCODTER
    FROM (
         SELECT m.bdCODEMP, m.BDCHAVE,
                m.BDEMITENTE IND_EMIT, 
                m.BDCODTER, ter.BDCGCTER, ter.BDIETER, terEmp.BDCODIGOARQUIVO, --COD_PART
                LPAD(m.bdCODSITNF, 2, '0') AS COD_SIT, 
                COALESCE(Substring(m.bdSERIE from 1 for 3), '') AS SER,
                Coalesce(m.BDNUMDOCINI, 0) NUM_DOC,
                (SELECT bdDATA FROM SP_PARSE_DATE(m.bdDATAEMISSAO,    'DDMMYYYY')) AS DT_DOC,
                (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAENTRADAENT, 'DDMMYYYY')) AS DT_E_S,
                SUM(COALESCE(D700.BDVLRSER, 0.00) + Coalesce(D700.BDVLRSERNTRIB, 0.00) + Coalesce(D700.BDVLRCOBTERC, 0.00) - Coalesce(D700.BDVALOR_DEDUCOES, 0.00)) AS VL_DOC, 
                SUM(COALESCE(m.bdDESCONTONOTA, 0.00)) AS VL_DESC,
                SUM(COALESCE(D700.BDVLRSER, 0.00)) AS VL_SERV,          
                SUM(COALESCE(D700.BDVLRSERNTRIB, 0.00)) AS VL_SERV_NT,  
                SUM(COALESCE(D700.BDVLRCOBTERC, 0.00)) AS VL_TERC,      
                SUM(COALESCE(D700.BDVLROUTDESP, 0.00)) AS VL_DA,        
                Cast(SUM(COALESCE(Mov.BDBCICMS, 0.00)) as dm_numeric_15_2) AS VL_BC_ICMS,
                Cast(SUM(COALESCE(Mov.bdVLRICMS, 0.00))as dm_numeric_15_2) AS VL_ICMS,
                Coalesce(INFCOMD700.BDCODINFCOM, '') as COD_INF,        
                SUM(COALESCE(D700.BDVLRPIS, 0.00)) AS VL_PIS,           
                SUM(COALESCE(D700.BDVLRCOFINS, 0.00)) AS VL_COFINS,     
                COALESCE(IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)) = '', '', RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)), 44, ' ')), '') CHV_DOCe,
                COALESCE(D700.BDFINALIDADE, -1) as FIN_DOCe,            
                COALESCE(D700.BDTP_FATURAMENTO, '') as TIP_FAT,         
                COALESCE(IIF(D700.BDFINALIDADE = 1, D700.BDDOCREF_MODELO, null), -1) as COD_MOD_DOC_REF,          
                IIF(D700.BDFINALIDADE = 1 and D700.bddocref_modelo = 2, COALESCE(IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D700.BDDOCREF_CHAVEDFE)) = '', '', RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D700.BDDOCREF_CHAVEDFE)), 44, ' ')), ''), '') as CHV_DOCe_REF,
                COALESCE(IIF(D700.BDFINALIDADE = 1 and D700.BDDOCREF_MODELO in (0, 1), D700.BDDOCREF_HASH, null), '') as HASH_DOC_REF,
                COALESCE(IIF(D700.BDFINALIDADE = 1 and D700.BDDOCREF_MODELO in (0, 1) and Coalesce(D700.BDDOCREF_HASH, '') = '', D700.BDDOCREF_SERIE, null), '') as SER_DOC_REF,
                COALESCE(IIF(D700.BDFINALIDADE = 1 and D700.BDDOCREF_MODELO in (0, 1) and D700.BDDOCREF_NUMERO > 0 and Coalesce(D700.BDDOCREF_HASH, '') = '', D700.BDDOCREF_NUMERO, null), '') as NUM_DOC_REF,
                COALESCE(IIF(D700.BDFINALIDADE = 1 and D700.BDDOCREF_MODELO in (0, 1) and D700.BDDOCREF_REFERENCIA > 0 and Coalesce(D700.BDDOCREF_HASH, '') = '', (SELECT BDDATA FROM SP_PARSE_DATE((Select BDDATA from SP_REFERENCIA_TO_DATA(D700.BDDOCREF_REFERENCIA)), 'MMYYYY')), ''), '') as MES_DOC_REF,
                Coalesce(cid.BDCODIBGE, '') COD_MUN_DEST,
                IIF(Cast((SELECT bdDATA FROM SP_PARSE_DATE(:prDTFIM, 'YYYYMM')) as integer) >= 202501 , SUM(COALESCE(D700.BDVALOR_DEDUCOES, 0.00)), '') as DED
        FROM (
              SELECT s.bdCODEMP, s.bdCHAVE,
                     emp.BDCODCID,
                     Sum(s.bdDESCONTONOTA) BDDESCONTONOTA,
                     Sum(tot.BDBCICMS) BDBCICMS,
                     Sum(tot.BDVLRICMS) BDVLRICMS
              FROM VEF_EMP_TMOVENT s
              LEFT JOIN VEF_EMP_TD590TOTENT TOT on (TOT.bdcodemp = s.bdcodemp and TOT.bdchave  = s.bdchave)
              left join TEMPRESAS_REF emp on (emp.BDCODEMP = s.BDCODEMP and emp.BDREFEMP = s.BDREFLAN)
              WHERE s.bdCODEMP = :prCODEMP
                and Coalesce(TOT.bdcodcsticms, '') <> ''
                AND S.BDNUMDOCINI > 0
                AND s.bdMODELO = 62
                AND s.BDCODSITNF in (0, 8)
                AND S.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
              GROUP BY s.bdCODEMP, s.bdCHAVE, emp.BDCODCID
             ) MOV
        JOIN VEF_EMP_TMOVENT m ON (m.bdCODEMP = mov.bdCODEMP AND m.bdCHAVE = mov.bdCHAVE)
        LEFT JOIN vef_emp_tD500ent D700 on (D700.BDCODEMP = mov.bdcodemp and D700.BDCHAVE = mov.BDCHAVE)
        LEFT JOIN VEF_BASE_TCADINFCOM INFCOMD700 ON (D700.bdordeminfcom = INFCOMD700.BDORDEMINFCOM)
        LEFT JOIN TCIDADE cid ON (cid.BDCODCID = mov.BDCODCID)
        LEFT JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = M.BDCODTER)
        LEFT JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = M.bdcodter)
        GROUP BY m.bdCODEMP, m.bdchave,
                 m.BDEMITENTE,               --IND_EMIT
                 m.bdcodter, ter.bdcgcter, ter.bdieter, teremp.BDCODIGOARQUIVO,  --COD_PART
                 m.bdCODSITNF,               --COD_SIT
                 m.bdSERIE,                  --SER
                 m.bdNUMDOCINI,              --NUM_DOC
                 m.bdDATAEMISSAO,            --DT_DOC
                 M.BDDATAENTRADAENT,         --DT_E_S
                 INFCOMD700.bdcodinfcom,     --COD_INF
                 m.BDCHAVENFE,               --CHV_DOCe
                 D700.BDFINALIDADE,          --FIN_DOCe
                 D700.BDTP_FATURAMENTO,      --TIP_FAT
                 D700.BDDOCREF_MODELO,       --COD_MOD_DOC_REF
                 D700.BDDOCREF_CHAVEDFE,     --CHV_DOCe_REF
                 D700.BDDOCREF_HASH,         --HASH_DOC_REF
                 D700.BDDOCREF_SERIE,        --SER_DOC_REF
                 D700.BDDOCREF_NUMERO,       --NUM_DOC_REF
                 D700.BDDOCREF_REFERENCIA,   --MES_DOC_REF
                 CID.BDCODIBGE               --COD_MUN_DEST
       ) m;

   /*                                D730                                     */
   INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
        SELECT :PRARQUIVO  BDID,
              LPAD(s.BDCODEMP, 6, '0')||'.0.'||LPAD(s.bdchave, 10, '0')||'.D700'||'.D730'||'.'||SUBSTRING(i.BDCODNAT FROM 1 FOR 4)||'.'||D730.BDALIQICMS ||'.'||coalesce(ICMS.BDCSTICMS,'') BDCHAVEREG,
              'D730' BDREG,
              ('|D730'|| --REG
               '|'||ICMS.BDCSTICMS||                     --CST_ICMS
               '|'||COALESCE(SUBSTRING(i.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
               '|'||REPLACE(CAST(Coalesce(D730.BDALIQICMS, 0.00) AS NUMERIC(6, 2)), '.', ',')||       --ALIQ_ICMS
               '|'||REPLACE(Cast(Sum(Coalesce(D730.BDVLROPERACAO, 0.00)) as DM_Numeric_15_2), '.', ',')||  --VL_OPR
               '|'||REPLACE(Cast(Sum(Coalesce(D730.BDBCICMS, 0.00)) as DM_Numeric_15_2), '.', ',')||       --VL_BC_ICMS
               '|'||REPLACE(Cast(Sum(Coalesce(D730.BDVLRICMS, 0.00)) as DM_Numeric_15_2), '.', ',')||      --VL_ICMS
               '|'||REPLACE(Cast(SUM(Coalesce(d730.BDVLRNTRIBICMS, 0.00)) as DM_Numeric_15_2), '.', ',')|| --VL_RED_BC
               '|'||COALESCE(Max(obs.BDCODEXP), '')|| --COD_OBS
               '|'  
               ) BDLINHA,
               Max(i.BDCODOBS) bdcodobs
        FROM (
              SELECT E.BDCODEMP, E.BDCHAVE
              FROM VEF_EMP_TMOVENT E
              WHERE E.BDCODEMP = :PRCODEMP
              AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
              AND E.BDMODELO = 62
              AND E.BDCODSITNF IN (0, 8)
             ) s
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = s.BDCODEMP AND I.BDCHAVE = s.BDCHAVE)
        LEFT JOIN VEF_EMP_TD590TOTENT D730 on (D730.bdcodemp = S.bdcodemp and D730.bdchave = S.bdchave and d730.bdordem = i.bdordem)

        LEFT JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = D730.BDCODCSTICMS)
        LEFT JOIN VEF_BASE_TOBSERVACAO obs ON(obs.bdcodobs = i.BDCODOBS)
        where Coalesce(D730.bdcodcsticms, '') <> ''
        GROUP BY s.BDCODEMP,s.BDCHAVE, ICMS.BDCSTICMS,SUBSTRING(i.BDCODNAT FROM 1 FOR 4),D730.BDALIQICMS;

   /*                                D731                                     */
   INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
   SELECT :PRARQUIVO  BDID,
          LPAD(m.BDCODEMP, 6, '0')||'.0.'||LPAD(m.bdchave, 10, '0')||'.D700'||'.D730'||'.'||SUBSTRING(i.BDCODNAT FROM 1 FOR 4)||'.'||D731.BDALIQICMS||'.'||coalesce(ICMS.BDCSTICMS,'')||'.D731' BDCHAVEREG,
          'D731' BDREG,
          ('|D731'|| --REG
           '|'||REPLACE(SUM(Coalesce(D731.BDVLRFCP_OP, 0.00)), '.', ',')|| --VL_FCP_OP
           '|'  
           ) BDLINHA

        FROM (

              SELECT E.BDCODEMP, E.BDCHAVE
              FROM VEF_EMP_TMOVENT E
              WHERE E.BDCODEMP = :PRCODEMP
              AND E.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
              AND E.BDMODELO = 62
              AND E.BDCODSITNF IN (0, 8)
        ) M
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = m.BDCODEMP AND I.BDCHAVE = m.BDCHAVE)
        LEFT JOIN VEF_EMP_TD590TOTENT D731 on (D731.bdcodemp = m.bdcodemp and D731.bdchave = m.bdchave and d731.bdordem = i.bdordem)
        LEFT JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = D731.BDCODCSTICMS)
        WHERE Coalesce(D731.bdcodcsticms, '') <> ''
        GROUP BY M.BDCODEMP, M.BDCHAVE,SUBSTRING(i.BDCODNAT FROM 1 FOR 4), icms.BDCSTICMS,D731.BDALIQICMS;

END^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOD_SAI_D300 (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRPERFIL integer,
    PRCODPLAPADRAOREF integer)
as
declare variable WCHAVEMIN integer;
declare variable WCHAVEMAX integer;
BEGIN
  /*****************************************************************************
   *--------------------------------->>SAÍDA<<---------------------------------*
   ****************************************************************************/

   SELECT MIN(s.bdCHAVE) AS bdCHAVEMIN, MAX(s.bdCHAVE) AS bdCHAVEMAX
   FROM VEF_EMP_TMOVSAI S
   WHERE S.BDCODEMP = :prCODEMP
     AND S.BDDATAEMISSAO BETWEEN :prDTINI AND :prDTFIM
     AND S.BDMODELO IN(13,14,15,16)
   INTO :wCHAVEMIN, :wCHAVEMAX;

  /*****************************************************************************
   *                                   D300                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDCODOBS, BDCODNAT, BDLINHA)
  SELECT :PRARQUIVO BDID,
         LPAD(m.bdCODEMP, 6, '0')||'.2.D300.'||m.DT_DOC||'.D300.'||m.SER||'.'||m.SUB||'.'||m.NUM_DOC_INI||'.'||m.NUM_DOC_FIM,
         'D300' BDREG, m.COD_OBS, m.CFOP,
         ('|D300'||-- 01 REG Texto fixo contendo "D400" C 004 - Não apresentar O
          '|'||m.COD_MOD||
          '|'||m.SER||
          '|'||m.SUB||
          '|'||m.NUM_DOC_INI||
          '|'||m.NUM_DOC_FIM||
          '|'||m.CST_ICMS||
          '|'||m.CFOP||
          '|'||REPLACE(COALESCE(CAST(m.ALIQ_ICMS AS NUMERIC(6,2)), 0.00), '.', ',')||
          '|'||m.DT_DOC||
          '|'||REPLACE(COALESCE(CAST(m.VL_DOC AS NUMERIC(15,2)), 0.00), '.', ',')||
          '|'||REPLACE(COALESCE(CAST(m.VL_DESC AS NUMERIC(15,2)), 0.00), '.', ',')||
          '|'||REPLACE(COALESCE(CAST(m.VL_SERV AS NUMERIC(15,2)), 0.00), '.', ',')||
          '|'||REPLACE(COALESCE(CAST(m.VL_SEG AS NUMERIC(15,2)), 0.00), '.', ',')||
          '|'||REPLACE(COALESCE(CAST(m.VL_OUT_DESP AS NUMERIC(15,2)), 0.00), '.', ',')||
          '|'||REPLACE(COALESCE(CAST(m.VL_BC_ICMS AS NUMERIC(15,2)), 0.00), '.', ',')||
          '|'||REPLACE(COALESCE(CAST(m.VL_ICMS AS NUMERIC(15,2)), 0.00), '.', ',')||
          '|'||(SELECT BDVALOR FROM GET_TRATA_VALOR_NEGATIVO(m.VL_RED_BC))||
          '|'||IIF(COALESCE(m.COD_OBS, 0) <= 0, '', m.COD_OBS)||
          '|'||COALESCE(m.COD_CTA, '')||
          '|'
          )
  FROM (
        SELECT m.bdCODEMP,
               m.bdMODELO AS COD_MOD, -- 02 COD_MOD Código do modelo do documento fiscal, conforme a Tabela 4.1.1 C 002* - O
               COALESCE(m.bdSERIE, '') AS SER, -- 03 SER Série do documento fiscal C 004 - OC
               COALESCE(m.bdSUBSERIE, '') AS SUB, -- 04 SUB Subsérie do documento fiscal N 003 - OC
               m.bdNUMDOCINI AS NUM_DOC_INI, -- 05 NUM_DOC_INI Número do primeiro documento fiscal emitido (mesmo modelo, série e subsérie). N 006 - O
               m.bdNUMDOCFIM AS NUM_DOC_FIM, -- 06 NUM_DOC_FIM Número do último documento fiscal emitido (mesmo modelo, série e subsérie). N - - O
               ICMS.BDCSTICMS AS CST_ICMS,--07 CST_ICMS Código da Situação Tributária, conforme a Tabela indicada no item 4.3.1 N 003* - O
               SUBSTRING(MOV.BDCODNAT FROM 1 FOR 4) AS CFOP, --08 CFOP Código Fiscal de Operação e Prestação conforme tabela indicada no item 4.2.2 N 004* - O
               mov.bdALIQICMS AS ALIQ_ICMS, --09 ALIQ_ICMS Alíquota do ICMS N 006 02 OC
               (SELECT bdDATA FROM SP_PARSE_DATE(m.bdDATAEMISSAO, 'DDMMYYYY')) AS DT_DOC, -- 10 DT_DOC Data da emissão do documentos fiscais N 008* - O
               SUM(COALESCE(mov.bdVLRCONTAB, 0.00)) AS VL_DOC, -- 11 VL_DOC Valor total do documento fiscal N - 02 O
               SUM(COALESCE(mov.bdDESCONTONOTA, 0.00)) AS VL_DESC, -- 12 VL_DESC Valor total dos descontos N - 02 OC
               SUM(COALESCE(D400.bdVLR_SERV, 0.00)) AS VL_SERV, -- 13 VL_SERV Valor total da prestação de serviço N - 02 O
               SUM(COALESCE(D400.bdVLR_SEGURO, 0.00)) AS VL_SEG, -- 14 VL_SEG Valor de seguro N - 02 OC
               SUM(COALESCE(D400.bdVLR_OUT_DESP, 0.00)) AS VL_OUT_DESP, -- 15 VL_OUT_DESP Valor de outras despesas N - 02 OC
               SUM(COALESCE(mov.bdBASEICMS, 0.00)) AS VL_BC_ICMS, -- 16 VL_BC_ICMS Valor total da base de cálculo do ICMS N - 02 OC
               SUM(COALESCE(mov.bdVLRICMS, 0.00)) AS VL_ICMS, -- 17 VL_ICMS Valor total do ICMS N - 02 OC
               IIF((SUBSTRING(ICMS.BDCSTICMS FROM 2 FOR 2) IN (20, 70)), (COALESCE(SUM(MOV.BDISENTASICMS), 0) + COALESCE(SUM(MOV.BDOUTRASICMS), 0)), 0.00) AS VL_RED_BC, --18 VL_RED_BC Valor não tributado em função da redução da base de cálculo do ICMS, referente à  combinação de CST_ICMS, CFOP e alíquota do  ICMS. N - 02 O
               MOV.bdcodobs AS COD_OBS, --19 COD_OBS Código da observação do lançamento fiscal (campo 02 do Registro 0460) C 006 - OC
               COALESCE(ccl.bdCTALON, ccderatp.bdCTALON) AS COD_CTA -- 20 COD_CTA Código da conta analítica contábil debitada/creditada C - - OC
        FROM (
              SELECT s.bdCODEMP, s.bdCHAVE, i.bdORDEM, s.bdREFLAN, i.bdcodcsticms, i.bdcodnat, i.bdaliqicms, s.bdDESCONTONOTA, MAX(i.bdcodobs) AS bdcodobs, SUM(i.bdVLRCONTAB) AS bdVLRCONTAB,
                     SUM(i.bdBASEICMS) AS bdBASEICMS, SUM(i.bdVLRICMS) AS bdVLRICMS, SUM(i.BDISENTASICMS) AS BDISENTASICMS, SUM(i.BDOUTRASICMS) AS BDOUTRASICMS
              FROM VEF_EMP_TMOVSAI s
              LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i ON (i.bdCODEMP = s.bdCODEMP AND i.bdCHAVE = s.bdCHAVE)
              WHERE s.bdCODEMP = :prCODEMP
                AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                AND s.bdMODELO IN(13,14,15, 16)
                and s.bdcodsitnf not in (10, 11)
              GROUP BY s.bdCODEMP, s.bdCHAVE, i.bdORDEM, s.bdREFLAN, i.bdcodcsticms, i.bdcodnat, i.bdaliqicms, s.bdDESCONTONOTA
             ) MOV
        JOIN VEF_EMP_TMOVSAI m ON (m.bdCODEMP = mov.bdCODEMP AND m.bdCHAVE = mov.bdCHAVE)
        JOIN VEF_EMP_TD400SAI d400 ON (d400.bdCODEMP = m.bdCODEMP AND d400.bdCHAVE = m.bdCHAVE)
        LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = MOV.BDCODCSTICMS)
        LEFT OUTER JOIN VW_INT_SPEDICMS_REF ConfSPED ON (ConfSPED.bdCODEMP = mov.bdCODEMP)
        LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, MIN(t.bdCHAVE) AS BDCHAVE, l.bdCODPLAPADRAO, l.bdCREDITO
                         FROM TOL_VEF_EMP_TMOVSAI t
                         LEFT OUTER JOIN VSUC_EMPRESAS_TLAN l ON (l.bdCODEMP = t.bdCODEMP AND l.bdCHAVE = t.bdCHAVE)
                         WHERE t.bdFORMULA LIKE '%NAT%LAN(%)' -- Alt.: #92219 - Apenas contas do valor contábil...
                           AND l.bdCREDITO IS NOT NULL -- Alt.: #120050 - Para apenas retornar quando a contabilização tiver uma conta informada, quando tem desconto a conta do desconto vem primeiro...
                           AND t.bdCODEMP = :prCODEMP
                           AND t.bdCHAVESAI BETWEEN :wCHAVEMIN AND :wCHAVEMAX
                         GROUP BY t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, l.bdCODPLAPADRAO, l.bdCREDITO) LAN ON (lan.bdCODEMP = MOV.bdCODEMP AND lan.bdCHAVESAI = MOV.bdCHAVE AND lan.bdORDEM = MOV.bdORDEM)
        LEFT OUTER JOIN PLANOS_TPLA ccl ON(COALESCE(d400.bdCODPLAPADRAO, lan.bdCODPLAPADRAO) = ccl.bdCODPLAPADRAO AND COALESCE(d400.bdCODTPLA, lan.bdCREDITO) = ccl.bdCODTPLA)
        LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVELAN, t.bdORDEM, MIN(t.bdCHAVE) AS bdCHAVE
                         FROM TOL_VEF_EMP_TMOVRATSAI t
                         GROUP BY t.bdCODEMP, t.bdCHAVELAN, t.bdORDEM) tolrat ON (tolrat.bdCODEMP = mov.bdCODEMP AND tolrat.bdCHAVELAN = mov.bdCHAVE AND tolrat.bdORDEM = mov.bdORDEM)
        LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat ON (lanrat.bdCODEMP = tolrat.bdCODEMP AND lanrat.bdCHAVE = tolrat.bdCHAVE)
        LEFT OUTER JOIN PLANOS_TPLA cclrat ON (lanrat.bdCODPLAPADRAO = cclrat.bdCODPLAPADRAO AND lanrat.bdCREDITO = cclrat.bdCODTPLA)
        LEFT OUTER JOIN PLANOS_TPLA_ECF ccderat ON (ccderat.bdCODPLAPADRAOREF = :prCODPLAPADRAOREF
                                                AND ccderat.bdANO =(SELECT FIRST 1 bdANO
                                                                    FROM PLANOS_TPLA_ECF 
                                                                    WHERE CAST(bdANO || '01' AS INTEGER) <= lanrat.bdREFERENCIA
                                                                      AND bdCODTPLAREF IS NOT NULL
                                                                      AND ccderat.bdCODPLAPADRAO = bdCODPLAPADRAO
                                                                      AND ccderat.bdCODPLAPADRAOREF = bdCODPLAPADRAOREF
                                                                      AND ccderat.bdCODTPLA = bdCODTPLA 
                                                                    ORDER BY bdANO DESC)
                                                AND ccderat.bdCODPLAPADRAO = cclrat.bdCODPLAPADRAO AND ccderat.bdCODTPLA = cclrat.bdCODTPLA)
        LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO CCDERATP ON (CCDERAT.BDCODPLAPADRAOREF = CCDERATP.BDCODPLAPADRAOREF AND CCDERAT.BDCODTPLAREF = CCDERATP.BDCODTPLAREF)
        GROUP BY m.bdCODEMP, m.bdMODELO, COALESCE(m.bdSERIE, ''), COALESCE(m.bdSUBSERIE, ''), m.bdNUMDOCINI, m.bdNUMDOCFIM, ICMS.BDCSTICMS, SUBSTRING(MOV.BDCODNAT FROM 1 FOR 4), ConfSPED.bdTIPOEXPCONTA,
                 mov.bdALIQICMS, m.bdDATAEMISSAO, ccl.bdCTALON, ccderatp.bdCTALON, MOV.bdcodobs
       ) m;

  /*****************************************************************************
   *                                   D301                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID,
         LPAD(m.bdCODEMP, 6, '0')||'.2.D300.'||m.DT_DOC||'.D300.'||m.bdSERIE||'.'||m.bdSUBSERIE||'.'||m.bdnumdocini||'.'||m.bdnumdocfim||'.D301'||m.bdnumdoc,
         'D301' BDREG,
          ('|D301'||         -- 01 REG Texto fixo contendo "D301" C 004 - Não Apresentar O
           '|'||m.bdnumdoc|| -- 02 NUM_DOC_CANC Número do documento fiscal cancelado N - - O
           '|'
           )
  FROM (
        SELECT s.bdCODEMP, s.bdCHAVE, s.bdnumdocini, s.bdnumdocfim, i.bdnumdoc,
                (SELECT bdDATA FROM SP_PARSE_DATE(s.bdDATAEMISSAO, 'DDMMYYYY')) AS DT_DOC,
                s.bdSERIE, s.bdSUBSERIE
        FROM VEF_EMP_TMOVSAI s
           JOIN vef_emp_td411sai i ON (i.bdCODEMP = s.bdCODEMP AND i.bdCHAVE = s.bdCHAVE)
        WHERE s.bdCODEMP = :prCODEMP
          AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
          AND s.bdMODELO IN (13,14,15, 16)
          and s.bdcodsitnf not in (10, 11)
       ) M;

  IF (:prPERFIL <> 2) THEN -- Perfil "C"
    BEGIN
      /*****************************************************************************
       *                                   D310                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(m.bdCODEMP, 6, '0')||'.2.D300.'||m.DT_DOC||'.D300.'||m.bdSERIE||'.'||m.bdSUBSERIE||'.'||m.bdnumdocini||'.'||m.bdnumdocfim||'.D310.'||m.bdcodibge,
             'D310' BDREG,
              ('|D310'|| -- 01 REG Texto fixo contendo "D420" C 004 - Não apresentar O
               '|'||COALESCE(m.bdCODIBGE,'')|| -- 02 COD_MUN_ORIG Código do município de origem do serviço, conforme a tabela IBGE N 007* - O
               '|'||COALESCE(REPLACE(SUM(COALESCE(m.bdVLRSERCOMP,0.00)), '.', ','), '')|| -- 03 VL_SERV Valor total da prestação de serviço N - 02 O
               '|'||COALESCE(REPLACE(SUM(COALESCE(m.bdBASEICMS,0.00)), '.', ','), '')|| -- 04 VL_BC_ICMS Valor total da base de cálculo do ICMS N - 02 O
               '|'||COALESCE(REPLACE(SUM(COALESCE(m.bdVLRICMS,0.00)), '.', ','), '')|| -- 05 VL_ICMS Valor total do ICMS N - 02 O
               '|'
               )
      FROM (
            SELECT s.bdCODEMP, s.bdCHAVE, s.bdnumdocini, s.bdnumdocfim, cid.bdcodibge, i.bdvlrsercomp, i.bdbaseicms, i.bdVLRICMS,
                   (SELECT bdDATA FROM SP_PARSE_DATE(s.bdDATAEMISSAO, 'DDMMYYYY')) AS DT_DOC,
                   s.bdSERIE, s.bdSUBSERIE
            FROM VEF_EMP_TMOVSAI s
               JOIN vef_emp_td420sai i ON (i.bdCODEMP = s.bdCODEMP AND i.bdCHAVE = s.bdCHAVE)
               JOIN tCidade cid on (cid.bdcodcid = i.bdcodcid)
            WHERE s.bdCODEMP = :prCODEMP
              AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              AND s.bdMODELO IN (13,14,15, 16)
              and s.bdcodsitnf not in (10, 11)
           ) M
      group by m.bdCODEMP, m.DT_DOC, m.bdSERIE, m.bdSUBSERIE, m.bdnumdocini, m.bdnumdocfim, m.bdcodibge;
    END
END
^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOD_SAI_D400 (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRTIPOEXPCODPART integer,
    PRCODPLAPADRAOREF integer,
    PRPERFIL integer)
as
declare variable WCHAVEMIN integer;
declare variable WCHAVEMAX integer;
BEGIN
  /*****************************************************************************
   *--------------------------------->>SAÍDA<<---------------------------------*
   ****************************************************************************/

   SELECT MIN(s.bdCHAVE) AS bdCHAVEMIN, MAX(s.bdCHAVE) AS bdCHAVEMAX
   FROM VEF_EMP_TMOVSAI S
   WHERE S.BDCODEMP = :prCODEMP
     AND S.BDDATAEMISSAO BETWEEN :prDTINI AND :prDTFIM
     AND S.BDMODELO IN(13,14,15,16)
   INTO :wCHAVEMIN, :wCHAVEMAX;

  /*****************************************************************************
   *                                   D400                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
  SELECT :PRARQUIVO BDID,
         LPAD(m.bdCODEMP, 6, '0')||'.2.'||LPAD(m.bdCODIGO, 10, '0')||'.D400.'||m.DT_DOC||'.'||m.COD_PART||'.D400.'||m.COD_SIT||'.'||m.SER||'.'||m.SUB||'.'||m.NUM_DOC,
         'D400' BDREG,
         ('|D400'||-- 01 REG Texto fixo contendo "D400" C 004 - Não apresentar O
          '|'||m.COD_PART||
          '|'||m.COD_MOD||
          '|'||IIF(m.COD_SIT IN (2, 3), '00', m.COD_SIT)||
          '|'||m.SER||
          '|'||m.SUB||
          '|'||m.NUM_DOC||
          '|'||m.DT_DOC||
          '|'||IIF(m.COD_SIT IN (4, 5, 8), '', IIF((m.COD_SIT IN (6, 7) AND SUM(COALESCE(m.VL_DOC,0.00)) = 0.00), '',  -- Situacao 06 deve levar em branco
                                                   REPLACE(SUM(COALESCE(CAST(m.VL_DOC AS NUMERIC(15,2)), 0.00)), '.', ',')))||
          '|'||IIF(m.COD_SIT IN (4, 5, 8), '', IIF((m.COD_SIT IN (6, 7) AND SUM(COALESCE(m.VL_DESC,0.00)) = 0.00), '', -- Situacao 06 deve levar em branco
                                                   REPLACE(SUM(COALESCE(CAST(m.VL_DESC AS NUMERIC(15,2)), 0.00)), '.', ',')))||
          '|'||IIF(m.COD_SIT IN (4, 5, 8), '', IIF((m.COD_SIT IN (6, 7) AND SUM(COALESCE(m.VL_SERV,0.00)) = 0.00), '', -- Situacao 06 deve levar em branco
                                                   REPLACE(SUM(COALESCE(CAST(m.VL_SERV AS NUMERIC(15,2)), 0.00)), '.', ',')))||
          '|'||IIF(m.COD_SIT IN (4, 5, 8), '', REPLACE(SUM(COALESCE(CAST(m.VL_BC_ICMS AS NUMERIC(15,2)), 0.00)), '.', ','))||
          '|'||IIF(m.COD_SIT IN (4, 5, 8), '', REPLACE(SUM(COALESCE(CAST(m.VL_ICMS AS NUMERIC(15,2)), 0.00)), '.', ','))||
          '|'||IIF(m.COD_SIT IN (4, 5, 8), '', REPLACE(SUM(COALESCE(CAST(m.VL_PIS AS NUMERIC(15,2)), 0.00)), '.', ','))||
          '|'||IIF(m.COD_SIT IN (4, 5, 8), '', REPLACE(SUM(COALESCE(CAST(m.VL_COFINS AS NUMERIC(15,2)), 0.00)), '.', ','))||
          '|'||MIN(m.COD_CTA)||
          '|'
          ), m.bdCODTER
  FROM (
        SELECT res.bdCODEMP, res.bdCODIGO, m.bdCODTER,
               (SELECT bdRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:prTIPOEXPCODPART, m.bdCODTER, ter.bdCGCTER, ter.bdIETER, teremp.bdCODIGOARQUIVO)) AS COD_PART, -- 02 COD_PART Código do participante (campo 02 do Registro 0150): - agência, filial ou posto C 060 - O
               '18'/*modl.bdMODELOSTR*/ AS COD_MOD, -- 03 COD_MOD Código do modelo do documento fiscal, conforme a Tabela 4.1.1 C 002* - O
               IIF(m.bdCODSITNF IN (2, 3), '00', LPAD(m.bdCODSITNF, 2, '0')) AS COD_SIT, -- 04 COD_SIT Código da situação do documento fiscal, conforme a Tabela 4.1.2 N 002* - O
               COALESCE(res.bdSERIE, '') AS SER, -- 05 SER Série do documento fiscal C 004 - OC
               COALESCE(res.bdSUBSERIE, '') AS SUB, -- 06 SUB Subsérie do documento fiscal N 003 - OC
               res.bdNUMERO AS NUM_DOC, -- 07 NUM_DOC Número do documento fiscal resumo. N 006 - O
               IIF(m.bdCODSITNF IN (4, 5), '', (SELECT bdDATA FROM SP_PARSE_DATE(m.bdDATAEMISSAO, 'DDMMYYYY'))) AS DT_DOC, -- 08 DT_DOC Data da emissão do documento fiscal N 008* - O
               SUM(COALESCE(mov.bdVLRCONTAB, 0.00)) AS VL_DOC, -- 09 VL_DOC Valor total do documento fiscal N - 02 O
               COALESCE(m.bdDESCONTONOTA, 0.00) AS VL_DESC, -- 10 VL_DESC Valor acumulado dos descontos N - 02 OC
               SUM(COALESCE(mov.bdVLRCONTAB, 0.00)) AS VL_SERV, -- 11 VL_SERV Valor acumulado da prestação de serviço N - 02 O
               SUM(COALESCE(mov.bdBASEICMS, 0.00)) AS VL_BC_ICMS, -- 12 VL_BC_ICMS Valor total da base de cálculo do ICMS N - 02 OC
               SUM(COALESCE(mov.bdVLRICMS, 0.00)) AS VL_ICMS, -- 13 VL_ICMS Valor total do ICMS N - 02 OC
               SUM(COALESCE(d400.bdVL_PIS, 0.00)) AS VL_PIS, -- 14 VL_PIS Valor do PIS N - 02 OC
               SUM(COALESCE(d400.bdVL_COF, 0.00)) AS VL_COFINS, -- 15 VL_COFINS Valor da COFINS N - 02 OC
               IIF(M.BDCODSITNF IN (2, 3, 4, 5, 6, 7, 8), '', COALESCE((CASE ConfSPED.bdTIPOEXPCONTA
                                                                          WHEN '0' THEN COALESCE(ccl.bdCODTPLA, cclrat.bdCODTPLA)
                                                                          WHEN '1' THEN COALESCE(ccl.bdCTALON, cclrat.bdCTALON)
                                                                          WHEN '2' THEN COALESCE(ccl.bdAPECTA, cclrat.bdAPECTA)
                                                                        ELSE COALESCE(ccl.bdCTALON,/*cclep.bdCTALON,*/ccderatp.bdCTALON) END), '')) AS COD_CTA -- 16 COD_CTA Código da conta analítica contábil debitada/creditada C - - OC
        FROM (
              SELECT s.bdCODEMP, s.bdCHAVE, i.bdORDEM, s.bdREFLAN, SUM(i.bdVLRCONTAB) AS bdVLRCONTAB,
                     SUM(i.bdBASEICMS) AS bdBASEICMS, SUM(i.bdVLRICMS) AS bdVLRICMS, SUM(i.bdVLRPIS) AS bdVLRPIS, SUM(i.bdVLRCOFINS) AS bdVLRCOFINS
              FROM VEF_EMP_TMOVSAI s
              LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i ON (i.bdCODEMP = s.bdCODEMP AND i.bdCHAVE = s.bdCHAVE)
              WHERE s.bdCODEMP = :prCODEMP
                AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                AND s.bdMODELO IN(13,14,15, 16)
                and s.BDCODSITNF not in (10, 11)
              GROUP BY s.bdCODEMP, s.bdCHAVE, i.bdORDEM, s.bdREFLAN
             ) MOV
        JOIN VEF_EMP_TMOVSAI m ON (m.bdCODEMP = mov.bdCODEMP AND m.bdCHAVE = mov.bdCHAVE)
        JOIN VEF_EMP_TD400SAI d400 ON (d400.bdCODEMP = m.bdCODEMP AND d400.bdCHAVE = m.bdCHAVE)
        JOIN VEF_EMP_TRESMOVDIARIO res ON (res.bdCODEMP = d400.bdCODEMP AND res.bdCODIGO = d400.bdCODIGO)
        JOIN VEF_BASE_TTABMODELOLAN modl ON (modl.bdMODELO = m.bdMODELO)
        LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES ter ON (ter.bdCODTER = m.bdCODTER)
        LEFT OUTER JOIN (SELECT tt.bdCODEMP, tt.bdCODTER, tt.bdCODIGO, ee.bdREFERENCIA, ee.bdCODIGOARQUIVO
                         FROM (SELECT t.bdCODEMP, t.bdCODTER,
                                      COALESCE((SELECT FIRST 1 e.bdCODIGO FROM TTERCEIRO_EMP e WHERE (e.bdCODEMP = t.bdCODEMP) AND (e.bdCODTER = t.bdCODTER) AND (e.bdREFERENCIA <= (SELECT bdDATA FROM SP_PARSE_DATE(:prDTINI, 'YYYYMM'))) ORDER BY e.bdREFERENCIA DESC),
                                               (SELECT FIRST 1 e.bdCODIGO FROM TTERCEIRO_EMP e WHERE (e.bdCODEMP = t.bdCODEMP) AND (e.bdCODTER = t.bdCODTER) ORDER BY e.bdREFERENCIA)) bdCODIGO
                               FROM (SELECT te.bdCODEMP, te.bdCODTER FROM TTERCEIRO_EMP te WHERE (te.bdCODEMP = :prCODEMP) GROUP BY te.bdCODEMP, te.bdCODTER) t
                               ) tt
                         LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdCODEMP = tt.bdCODEMP AND ee.bdCODTER = tt.bdCODTER AND ee.bdCODIGO = tt.bdCODIGO
                         ) teremp ON (teremp.bdCODTER = m.bdCODTER)
        LEFT OUTER JOIN VW_INT_SPEDICMS_REF ConfSPED ON (ConfSPED.bdCODEMP = mov.bdCODEMP)
        LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, MIN(t.bdCHAVE) AS BDCHAVE, l.bdCODPLAPADRAO, l.bdCREDITO
                         FROM TOL_VEF_EMP_TMOVSAI t
                         LEFT OUTER JOIN VSUC_EMPRESAS_TLAN l ON (l.bdCODEMP = t.bdCODEMP AND l.bdCHAVE = t.bdCHAVE)
                         WHERE t.bdFORMULA LIKE '%NAT%LAN(%)' -- Alt.: #92219 - Apenas contas do valor contábil...
                           AND l.bdCREDITO IS NOT NULL -- Alt.: #120050 - Para apenas retornar quando a contabilização tiver uma conta informada, quando tem desconto a conta do desconto vem primeiro...
                           AND t.bdCODEMP = :prCODEMP
                           AND t.bdCHAVESAI BETWEEN :wCHAVEMIN AND :wCHAVEMAX
                         GROUP BY t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, l.bdCODPLAPADRAO, l.bdCREDITO) LAN ON (lan.bdCODEMP = MOV.bdCODEMP AND lan.bdCHAVESAI = MOV.bdCHAVE AND lan.bdORDEM = MOV.bdORDEM)
        LEFT OUTER JOIN PLANOS_TPLA ccl ON(COALESCE(d400.bdCODPLAPADRAO, lan.bdCODPLAPADRAO) = ccl.bdCODPLAPADRAO AND COALESCE(d400.bdCODTPLA, lan.bdCREDITO) = ccl.bdCODTPLA)
        LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVELAN, t.bdORDEM, MIN(t.bdCHAVE) AS bdCHAVE
                         FROM TOL_VEF_EMP_TMOVRATSAI t
                         GROUP BY t.bdCODEMP, t.bdCHAVELAN, t.bdORDEM) tolrat ON (tolrat.bdCODEMP = mov.bdCODEMP AND tolrat.bdCHAVELAN = mov.bdCHAVE AND tolrat.bdORDEM = mov.bdORDEM)
        LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat ON (lanrat.bdCODEMP = tolrat.bdCODEMP AND lanrat.bdCHAVE = tolrat.bdCHAVE)
        LEFT OUTER JOIN PLANOS_TPLA cclrat ON (lanrat.bdCODPLAPADRAO = cclrat.bdCODPLAPADRAO AND lanrat.bdCREDITO = cclrat.bdCODTPLA)
        LEFT OUTER JOIN PLANOS_TPLA_ECF ccderat ON (ccderat.bdCODPLAPADRAOREF = :prCODPLAPADRAOREF
                                                AND ccderat.bdANO =(SELECT FIRST 1 bdANO
                                                                    FROM PLANOS_TPLA_ECF 
                                                                    WHERE CAST(bdANO || '01' AS INTEGER) <= lanrat.bdREFERENCIA
                                                                      AND bdCODTPLAREF IS NOT NULL
                                                                      AND ccderat.bdCODPLAPADRAO = bdCODPLAPADRAO
                                                                      AND ccderat.bdCODPLAPADRAOREF = bdCODPLAPADRAOREF
                                                                      AND ccderat.bdCODTPLA = bdCODTPLA 
                                                                    ORDER BY bdANO DESC)
                                                AND ccderat.bdCODPLAPADRAO = cclrat.bdCODPLAPADRAO AND ccderat.bdCODTPLA = cclrat.bdCODTPLA)
        LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO CCDERATP ON (CCDERAT.BDCODPLAPADRAOREF = CCDERATP.BDCODPLAPADRAOREF AND CCDERAT.BDCODTPLAREF = CCDERATP.BDCODTPLAREF)
        GROUP BY res.bdCODEMP, res.bdCODIGO, m.bdCODTER, mov.bdORDEM, m.bdCODSITNF, m.bdCODTER, ter.bdCGCTER, ter.bdIETER, teremp.bdCODIGOARQUIVO,
                 modl.bdMODELOSTR, res.bdSERIE, res.bdSUBSERIE, res.bdNUMERO, m.bdDATAEMISSAO, m.bdDESCONTONOTA, ConfSPED.bdTIPOEXPCONTA,
                 ccl.bdCODTPLA, cclrat.bdCODTPLA, ccl.bdCTALON, cclrat.bdCTALON, ccl.bdAPECTA, cclrat.bdAPECTA,/*cclep.bdCTALON,*/ccderatp.bdCTALON
       ) m
  GROUP BY m.bdCODEMP, m.bdCODIGO, m.bdCODTER, m.COD_PART, m.COD_MOD, m.COD_SIT, m.SER, m.SUB, m.NUM_DOC, m.DT_DOC;

  /*****************************************************************************
   *                                   D410                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID,
         LPAD(res.bdCODEMP, 6, '0')||'.2.'||LPAD(res.bdCODIGO, 10, '0')||'.D400.'||(SELECT BDDATA FROM SP_PARSE_DATE(m.bdDATAEMISSAO, 'DDMMYYYY'))||
              '.'||M.BDCODTER||'.D410.'||LPAD(M.BDCODSITNF, 2, '0')||'.'||m.bdSERIE||'.'||m.bdSUBSERIE||'.'||m.bdNUMDOCINI||'.'||m.bdNUMDOCFIM||'.'||i.bdCODNAT,
         'D410' BDREG,
          ('|D410'|| -- 01 REG Texto fixo contendo "D410" C 004 - Não apresentar O
           '|'||modl.bdMODELOSTR|| -- 02 COD_MOD Código do modelo do documento fiscal , conforme a Tabela 4.1.1 C 002* - O
           '|'||m.bdSERIE|| -- 03 SER Série do documento fiscal C 004 - O
           '|'||m.bdSUBSERIE|| -- 04 SUB Subsérie do documento fiscal N 003 - OC
           '|'||m.bdNUMDOCINI|| -- 05 NUM_DOC_INI Número do documento fiscal inicial (mesmo modelo, série e subsérie) N 006 - O
           '|'||m.bdNUMDOCFIM|| -- 06 NUM_DOC_FIN Número do documento fiscal final(mesmo modelo, série e subsérie) N - - O
           '|'||(SELECT BDDATA FROM SP_PARSE_DATE(m.bdDATAEMISSAO, 'DDMMYYYY'))|| -- 07 DT_DOC Data da emissão dos documentos fiscais N 008* - O
           '|'||COALESCE(icms.bdCSTICMS, '')|| -- 08 CST_ICMS Código da Situação Tributária, conforme a Tabela indicada no item 4.3.1 N 003* - O
           '|'||COALESCE(SUBSTRING(i.bdCODNAT FROM 1 FOR 4), '')|| -- 09 CFOP Código Fiscal de Operação e Prestação N 004* - O
           '|'||COALESCE(REPLACE(CAST(IIF(m.bdCODSITNF IN (2, 3), 0.00, i.bdALIQICMS) AS NUMERIC(6, 2)), '.', ','), '')|| -- 10 ALIQ_ICMS Alíquota do ICMS N 006 02 OC
           '|'||COALESCE(REPLACE(SUM(IIF(m.bdCODSITNF IN (2, 3), 0.00, COALESCE(i.bdVLRCONTAB,0.00))), '.', ','), '')|| -- 11 VL_OPR Valor total acumulado das operações correspondentes à combinação de CST_ICMS, CFOP e alíquota do ICMS, incluídas as despesas acessórias e acréscimos. N - 02 O
           '|'||COALESCE(REPLACE(SUM(IIF(m.bdCODSITNF IN (2, 3), 0.00, COALESCE(i.bdDESCONTO,0.00))), '.', ','), '')|| -- 12 VL_DESC Valor acumulado dos descontos N - 02 OC
           '|'||COALESCE(REPLACE(SUM(IIF(m.bdCODSITNF IN (2, 3), 0.00, COALESCE(i.bdVLRCONTAB,0.00))), '.', ','), '')|| -- 13 VL_SERV Valor acumulado da prestação de serviço N - 02 O
           '|'||COALESCE(REPLACE(SUM(IIF(m.bdCODSITNF IN (2, 3), 0.00, COALESCE(i.bdBASEICMS,0.00))), '.', ','), '')|| -- 14 VL_BC_ICMS Valor acumulado da base de cálculo do ICMS N - 02 O
           '|'||COALESCE(REPLACE(SUM(IIF(m.bdCODSITNF IN (2, 3), 0.00, COALESCE(i.bdVLRICMS,0.00))), '.', ','), '')|| -- 15 VL_ICMS Valor acumulado do ICMS N - 02 O
           '|'
           )
  FROM (
        SELECT s.bdCODEMP, s.bdCHAVE
        FROM VEF_EMP_TMOVSAI s
        WHERE s.bdCODEMP = :prCODEMP
          AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
          AND s.bdMODELO IN(13,14,15, 16)
          and s.BDCODSITNF not in (10, 11)
       ) MOV
  JOIN VEF_EMP_TMOVSAI m ON (m.bdCODEMP = mov.bdCODEMP AND m.bdCHAVE = mov.bdCHAVE)
  JOIN VEF_EMP_TMOVSAIITENS i ON (i.bdCODEMP = m.bdCODEMP AND i.bdCHAVE = m.bdCHAVE)
  JOIN VEF_EMP_TD400SAI d400 ON (d400.bdCODEMP = m.bdCODEMP AND d400.bdCHAVE = m.bdCHAVE)
  JOIN VEF_EMP_TRESMOVDIARIO res ON (res.bdCODEMP = d400.bdCODEMP AND res.bdCODIGO = d400.bdCODIGO)
  JOIN VEF_BASE_TTABMODELOLAN modl ON (modl.bdMODELO = m.bdMODELO)
  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS icms ON(icms.bdCODCSTICMS = i.bdCODCSTICMS)
  GROUP BY res.bdCODEMP, res.bdCODIGO, modl.bdMODELOSTR, m.bdSERIE, m.bdSUBSERIE, m.bdNUMDOCINI, m.bdNUMDOCFIM, m.bdDATAEMISSAO,
           icms.bdCSTICMS, i.bdCODNAT, i.bdALIQICMS, m.bdCODSITNF, M.BDCODTER;

  /*****************************************************************************
   *                                   D411                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID,
         LPAD(res.bdCODEMP, 6, '0')||'.2.'||LPAD(res.bdCODIGO, 10, '0')||'.D400.'||(SELECT BDDATA FROM SP_PARSE_DATE(m.bdDATAEMISSAO, 'DDMMYYYY'))||
              '.'||M.BDCODTER||'.D410.'||LPAD(M.BDCODSITNF, 2, '0')||'.'||m.bdSERIE||'.'||m.bdSUBSERIE||'.'||m.bdNUMDOCINI||'.'||m.bdNUMDOCFIM||
              '.'||I.BDCODNAT||'.D411'||COALESCE(canc.bdnumdoc, m.bdnumdocini),
         'D411' BDREG,
          ('|D411'|| -- 01 REG Texto fixo contendo "D411" C 004 - Não Apresentar O
           '|'||COALESCE(canc.bdnumdoc, m.bdnumdocini)|| -- 02 NUM_DOC_CANC Número do documento fiscal cancelado N - - O
           '|'
           )
  FROM (
        SELECT distinct s.bdCODEMP, s.bdCHAVE
        FROM VEF_EMP_TMOVSAI s
           LEFT OUTER JOIN vef_emp_td411sai doc ON (s.bdcodemp = doc.bdcodemp and s.bdchave = doc.bdchave)
        WHERE s.bdCODEMP = :prCODEMP
          AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
          AND s.bdMODELO IN(13,14,15, 16)
          AND (s.bdCODSITNF IN (2) or (doc.bdnumdoc is not null))
          and s.BDCODSITNF not in (10, 11)
       ) MOV
  JOIN VEF_EMP_TMOVSAI m ON (m.bdCODEMP = mov.bdCODEMP AND m.bdCHAVE = mov.bdCHAVE)
  JOIN VEF_EMP_TD400SAI d400 ON (d400.bdCODEMP = m.bdCODEMP AND d400.bdCHAVE = m.bdCHAVE)
  JOIN VEF_EMP_TRESMOVDIARIO res ON (res.bdCODEMP = d400.bdCODEMP AND res.bdCODIGO = d400.bdCODIGO)
  JOIN VEF_EMP_TMOVSAIITENS i ON (i.bdCODEMP = m.bdCODEMP AND i.bdCHAVE = m.bdCHAVE)
  LEFT OUTER JOIN vef_emp_td411sai canc ON (m.bdcodemp = canc.bdcodemp and m.bdchave = canc.bdchave);

  IF (:prPERFIL <> 2) THEN -- Perfil "C"
    BEGIN
      /*****************************************************************************
       *                                   D420                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(res.bdCODEMP, 6, '0')||'.2.'||LPAD(res.bdCODIGO, 10, '0')||'.D400.'||(SELECT BDDATA FROM SP_PARSE_DATE(m.bdDATAEMISSAO, 'DDMMYYYY'))||
             '.'||M.BDCODTER||'.D420.'||LPAD(M.BDCODSITNF, 2, '0')||'.'||cid.bdCODIBGE,
             'D420' BDREG,
              ('|D420'|| -- 01 REG Texto fixo contendo "D420" C 004 - Não apresentar O
               '|'||COALESCE(cid.bdCODIBGE,'')|| -- 02 COD_MUN_ORIG Código do município de origem do serviço, conforme a tabela IBGE N 007* - O
               '|'||COALESCE(REPLACE(SUM(COALESCE(d420.bdVLRSERCOMP,0.00)), '.', ','), '')|| -- 03 VL_SERV Valor total da prestação de serviço N - 02 O
               '|'||COALESCE(REPLACE(SUM(COALESCE(d420.bdBASEICMS,0.00)), '.', ','), '')|| -- 04 VL_BC_ICMS Valor total da base de cálculo do ICMS N - 02 O
               '|'||COALESCE(REPLACE(SUM(COALESCE(d420.bdVLRICMS,0.00)), '.', ','), '')|| -- 05 VL_ICMS Valor total do ICMS N - 02 O
               '|'
               )
      FROM (
            SELECT s.bdCODEMP, s.bdCHAVE
            FROM VEF_EMP_TMOVSAI s
            WHERE s.bdCODEMP = :prCODEMP
              AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              AND s.bdMODELO IN(13,14,15, 16)
              and s.BDCODSITNF not in (10, 11)
           ) MOV
      JOIN VEF_EMP_TMOVSAI m ON (m.bdCODEMP = mov.bdCODEMP AND m.bdCHAVE = mov.bdCHAVE)
      JOIN VEF_EMP_TD400SAI d400 ON (d400.bdCODEMP = m.bdCODEMP AND d400.bdCHAVE = m.bdCHAVE)
      JOIN VEF_EMP_TRESMOVDIARIO res ON (res.bdCODEMP = d400.bdCODEMP AND res.bdCODIGO = d400.bdCODIGO)
      JOIN VEF_EMP_TD420SAI d420 ON (d420.bdCODEMP = m.bdCODEMP AND d420.bdCHAVE = m.bdCHAVE)
      JOIN TCIDADE cid ON (cid.bdCODCID = d420.bdCODCID)
      WHERE d420.bdCODCID > 0
      GROUP BY res.bdCODEMP, res.bdCODIGO, cid.bdCODIBGE, M.BDCODTER, M.BDCODSITNF, M.BDDATAEMISSAO;
    END
END^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOD_SAI_D700 (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260))
as
BEGIN
   /*                               D700                                      */
   if (not Coalesce((select first 1 sped.BDNFCOM_CONSOLIDADA
                    from VEF_INT_TSPEDICMS sped
                    where sped.BDCODEMP = :prCodEmp
                      and sped.BDREFERENCIA <= Cast((Select BDDATA from SP_PARSE_DATE(:prDTIni, 'YYYYMM')) as Integer)
                    order by sped.BDREFERENCIA desc), False)) then
     BEGIN
       INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
        SELECT :PRARQUIVO BDID,
              LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(m.bdchave, 10, '0')||'.D700' BDCHAVEREG,
              'D700' BDREG,
              ('|D700|1'||  --REG | IND_OPER
               '|'||M.IND_EMIT||
               '|'||''||
               '|'||'62'||  --COD_MOD
               '|'||LPAD(m.COD_SIT, 2, '0')||
               '|'||M.SER||
               '|'||IIF(M.NUM_DOC = 0, '', M.NUM_DOC)||
               '|'||M.DT_DOC||
               '|'||''||--'|'||M.DT_E_S||
               '|'||REPLACE(M.VL_DOC,       '.', ',')||
               '|'||REPLACE(M.VL_DESC,      '.', ',')||
               '|'||REPLACE(m.VL_SERV,      '.', ',')||
               '|'||REPLACE(M.VL_SERV_NT,   '.', ',')||
               '|'||REPLACE(M.VL_TERC,      '.', ',')||
               '|'||REPLACE(M.VL_DA,        '.', ',')||
               '|'||REPLACE(m.VL_BC_ICMS,   '.', ',')||
               '|'||REPLACE(m.VL_ICMS,      '.', ',')||
               '|'||M.COD_INF||
               '|'||REPLACE(m.VL_PIS,       '.', ',')||
               '|'||REPLACE(m.VL_COFINS,    '.', ',')||
               '|'||m.CHV_DOCe||
               '|'||CASE  WHEN m.FIN_DOCe = 0  THEN 0
                          WHEN m.FIN_DOCe = 1  THEN 3
                          WHEN m.FIN_DOCe = 2  THEN 4
                          when m.FIN_DOCe = -1 then ''
                    END ||
               '|'||m.TIP_FAT||
               '|'||CASE  WHEN m.COD_MOD_DOC_REF = 0  THEN 21
                          WHEN m.COD_MOD_DOC_REF = 1  THEN 22
                          WHEN m.COD_MOD_DOC_REF = 2  THEN 62
                          when m.COD_MOD_DOC_REF = -1 then ''
                     END||
               '|'||m.CHV_DOCe_REF||
               '|'||m.HASH_DOC_REF||
               '|'||m.SER_DOC_REF||
               '|'||m.NUM_DOC_REF||
               '|'||M.MES_DOC_REF||
               '|'||m.COD_MUN_DEST||
               IIF(m.DED <> '', '|'||REPLACE(m.DED, '.', ','), m.DED)||
               '|'
               ) BDLINHA
        FROM (
             SELECT m.bdCODEMP, m.BDCHAVE,
                    m.BDEMITENTE IND_EMIT,
                    LPAD(m.bdCODSITNF, 2, '0') AS COD_SIT,
                    COALESCE(Substring(m.bdSERIE from 1 for 3), '') AS SER,
                    Coalesce(MOV.BDNUMDOCINI, 0) NUM_DOC,
                    (SELECT bdDATA FROM SP_PARSE_DATE(m.bdDATAEMISSAO, 'DDMMYYYY')) AS DT_DOC,
                    SUM(COALESCE(D700.BDVLRSER, 0.00) + Coalesce(D700.BDVLRSERNTRIB, 0.00) + Coalesce(D700.BDVLRCOBTERC, 0.00) - Coalesce(D700.BDVALOR_DEDUCOES, 0.00)) AS VL_DOC,
                    SUM(COALESCE(m.bdDESCONTONOTA, 0.00)) AS VL_DESC,
                    SUM(COALESCE(D700.BDVLRSER, 0.00)) AS VL_SERV,
                    SUM(COALESCE(D700.BDVLRSERNTRIB, 0.00)) AS VL_SERV_NT,
                    SUM(COALESCE(D700.BDVLRCOBTERC, 0.00)) AS VL_TERC,
                    SUM(COALESCE(D700.BDVLROUTDESP, 0.00)) AS VL_DA,
                    SUM(COALESCE(MOV.bdBCICMS, 0.00)) AS VL_BC_ICMS,
                    SUM(COALESCE(MOV.bdVLRICMS, 0.00)) AS VL_ICMS,
                    Coalesce(INFCOMD700.BDCODINFCOM, '') as COD_INF,
                    SUM(COALESCE(mov.BDVLRPIS, 0.00)) AS VL_PIS,
                    SUM(COALESCE(mov.BDVLRCOFINS, 0.00)) AS VL_COFINS,
                    COALESCE(IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)) = '', '', RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)), 44, ' ')), '') CHV_DOCe,
                    COALESCE(D700.BDFINALIDADE, -1) as FIN_DOCe,
                    COALESCE(D700.BDTP_FATURAMENTO, '') as TIP_FAT,
                    COALESCE(IIF(D700.BDFINALIDADE = 1, D700.BDDOCREF_MODELO, null), -1) as COD_MOD_DOC_REF,
                    IIF(D700.BDFINALIDADE = 1 and D700.bddocref_modelo = 2, COALESCE(IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D700.BDDOCREF_CHAVEDFE)) = '', '', RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D700.BDDOCREF_CHAVEDFE)), 44, ' ')), ''), '') as CHV_DOCe_REF,
                    COALESCE(IIF(D700.BDFINALIDADE = 1 and D700.BDDOCREF_MODELO in (0, 1), D700.BDDOCREF_HASH, null), '') as HASH_DOC_REF,
                    COALESCE(IIF(D700.BDFINALIDADE = 1 and D700.BDDOCREF_MODELO in (0, 1) and Coalesce(D700.BDDOCREF_HASH, '') = '', D700.BDDOCREF_SERIE, null), '') as SER_DOC_REF,
                    COALESCE(IIF(D700.BDFINALIDADE = 1 and D700.BDDOCREF_MODELO in (0, 1) and D700.BDDOCREF_NUMERO > 0 and Coalesce(D700.BDDOCREF_HASH, '') = '', D700.BDDOCREF_NUMERO, null), '') as NUM_DOC_REF,
                    COALESCE(IIF(D700.BDFINALIDADE = 1 and D700.BDDOCREF_MODELO in (0, 1) and D700.BDDOCREF_REFERENCIA > 0 and Coalesce(D700.BDDOCREF_HASH, '') = '', (SELECT BDDATA FROM SP_PARSE_DATE((Select BDDATA from SP_REFERENCIA_TO_DATA(D700.BDDOCREF_REFERENCIA)), 'MMYYYY')), ''), '') as MES_DOC_REF,
                    COALESCE(CIDDESTD700.BDCODIBGE, '') COD_MUN_DEST,
                    IIF(Cast((SELECT bdDATA FROM SP_PARSE_DATE(:prDTFIM, 'YYYYMM')) as integer) >= 202501 , SUM(COALESCE(D700.BDVALOR_DEDUCOES, 0.00)), '') as DED
            FROM (
                  SELECT s.bdCODEMP, S.bdchave,s.BDSERIE,s.BDDATAEMISSAO, s.BDNUMDOCINI,
                         Sum(pro.BDBCICMS) BDBCICMS,
                         Sum(pro.BDVLRICMS) BDVLRICMS,
                         Sum(pro.BDVLRPIS) BDVLRPIS,
                         sum(pro.BDVLRCOFINS) BDVLRCOFINS

                  FROM (
                         Select s.bdcodemp, s.bdchave,s.BDSERIE,s.BDDATAEMISSAO, s.BDNUMDOCINI
                          from VEF_EMP_TMOVSAI s
                           WHERE s.BDCODEMP = :PRCODEMP
                             AND s.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                            AND S.BDNUMDOCINI > 0
                            AND s.bdMODELO = 62
                            and s.BDCODSITNF = 0
                         )s
                  JOIN  VEF_EMP_TMOVPROSAI pro on (pro.BDCODEMP = s.BDCODEMP and pro.BDCHAVE = s.BDCHAVE)
                  WHERE Coalesce(pro.BDCODCSTICMS, '') <> ''
                  GROUP BY s.bdCODEMP, s.bdchave, s.BDSERIE, s.bddataemissao, s.BDNUMDOCINI
                 ) mov
            JOIN VEF_EMP_TMOVSAI m ON (m.bdCODEMP = mov.bdCODEMP AND m.bdCHAVE = mov.bdCHAVE)
            LEFT JOIN vef_emp_tD500SAI D700 on (D700.BDCODEMP = mov.bdcodemp and D700.BDCHAVE = mov.BDCHAVE)
            LEFT JOIN VEF_BASE_TCADINFCOM INFCOMD700 ON (D700.bdordeminfcom = INFCOMD700.BDORDEMINFCOM)
            LEFT JOIN TCIDADE CIDDESTD700 ON (m.BDCODCID = CIDDESTD700.BDCODCID)
            GROUP BY m.bdCODEMP, m.bdchave,
                     m.BDEMITENTE,
                     m.bdCODSITNF,
                     m.bdSERIE,
                     MOV.bdNUMDOCINI,
                     m.bdDATAEMISSAO,
                     INFCOMD700.bdcodinfcom,
                     m.BDCHAVENFE,
                     D700.BDFINALIDADE,
                     D700.BDTP_FATURAMENTO,
                     D700.BDDOCREF_MODELO,
                     D700.BDDOCREF_CHAVEDFE,
                     D700.BDDOCREF_HASH,
                     D700.BDDOCREF_SERIE,
                     D700.BDDOCREF_NUMERO,
                     D700.BDDOCREF_REFERENCIA,
                     ciddestd700.BDCODIBGE
           ) m;
    
       /*                           D730                                      */
       INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
        SELECT :PRARQUIVO  BDID,
              LPAD(s.BDCODEMP, 6, '0')||'.1.'||LPAD(s.bdchave, 10, '0')||'.D700'||'.D730'||'.'||SUBSTRING(i.BDCODNAT FROM 1 FOR 4)||'.'||pro.BDALIQICMS ||'.'||coalesce(ICMS.BDCSTICMS,'') BDCHAVEREG,
              'D730' BDREG,
              ('|D730'|| --REG
               '|'||ICMS.BDCSTICMS||                     --CST_ICMS
               '|'||COALESCE(SUBSTRING(i.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
               '|'||REPLACE(CAST(Coalesce(pro.BDALIQICMS,  0.00) AS NUMERIC(6, 2))  , '.', ',')|| --ALIQ_ICMS
               '|'||REPLACE(CAST(SUM(Coalesce(pro.BDVLRITEM,   0.00)) as dm_numeric_15_2), '.', ',')|| --VL_OPR
               '|'||REPLACE(CAST(SUM(Coalesce(pro.BDBCICMS,    0.00)) as dm_numeric_15_2), '.', ',')|| --VL_BC_ICMS
               '|'||REPLACE(Cast(SUM(Coalesce(pro.BDVLRICMS,   0.00)) as dm_numeric_15_2), '.', ',')|| --VL_ICMS
               '|'||REPLACE(CAST(Sum(Coalesce(pro.BDREDBCICMS, 0.00)) as dm_numeric_15_2), '.', ',')|| --VL_RED_BC
               '|'||COALESCE(Max(obs.BDCODEXP), '')|| --COD_OBS
               '|'  
               ) BDLINHA,
               Max(i.BDCODOBS) bdcodobs
        FROM (
              SELECT E.BDCODEMP, E.BDCHAVE
              FROM VEF_EMP_TMOVSAI E
              WHERE E.BDCODEMP = :PRCODEMP
              AND E.bddataemissao BETWEEN :PRDTINI AND :PRDTFIM
              AND E.BDMODELO = 62
              AND E.BDCODSITNF IN (0, 8)
             ) s
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = s.BDCODEMP AND I.BDCHAVE = s.BDCHAVE)
        LEFT JOIN VEF_EMP_TMOVPROSAI pro on (pro.BDCODEMP = s.BDCODEMP and pro.BDCHAVE = s.BDCHAVE and pro.BDORDEM = i.bdordem)
        LEFT JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = pro.BDCODCSTICMS)
        LEFT JOIN VEF_BASE_TOBSERVACAO obs ON(obs.bdcodobs = i.BDCODOBS)
        where Coalesce(pro.bdcodcsticms, '') <> ''
        GROUP BY s.BDCODEMP,s.BDCHAVE, ICMS.BDCSTICMS,SUBSTRING(i.BDCODNAT FROM 1 FOR 4),pro.BDALIQICMS;
    
       /*                           D731                                      */
       INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
        SELECT :PRARQUIVO BDID,
              LPAD(m.BDCODEMP, 6, '0')||'.1.'||LPAD(m.bdchave, 10, '0')||'.D700'||'.D730'||'.'||SUBSTRING(i.BDCODNAT FROM 1 FOR 4)||'.'||pro.BDALIQICMS||'.'||coalesce(ICMS.BDCSTICMS,'')||'.D731' BDCHAVEREG,
              'D731' BDREG,
              ('|D731'|| --REG
               '|'||REPLACE(SUM(COALESCE(pro.BDVLRFCP, 0.00)), '.', ',')|| --VL_FCP_OP
               '|'  
               ) BDLINHA
        FROM (

              SELECT E.BDCODEMP, E.BDCHAVE
              FROM VEF_EMP_TMOVSAI E
              WHERE E.BDCODEMP = :PRCODEMP
              AND E.bddataemissao BETWEEN :PRDTINI AND :PRDTFIM
              AND E.BDMODELO = 62
              AND E.BDCODSITNF IN (0, 8)
        ) M
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = m.BDCODEMP AND I.BDCHAVE = m.BDCHAVE)
        LEFT JOIN VEF_EMP_TMOVPROSAI pro on (pro.BDCODEMP = m.BDCODEMP and pro.BDCHAVE = m.BDCHAVE and pro.BDORDEM = i.bdordem)
        LEFT JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = pro.BDCODCSTICMS)
        WHERE Coalesce(pro.bdcodcsticms, '') <> ''
        GROUP BY M.BDCODEMP,M.BDCHAVE, i.bdcodnat, pro.BDALIQICMS,ICMS.BDCSTICMS;
     END
    ELSE
     BEGIN
       /*                           D750                                     */
       INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
        SELECT  :PRARQUIVO as BDID,
                LPAD(M.BDCODEMP, 6, '0')||'.1.D750.'||m.SER||'.'||m.DT_DOC||'.'||coalesce(m.IND_PREPAGO,'') BDCHAVEREG,
              'D750' BDREG,
              ('|D750'||                                --REG
               '|'||'62'||                              --COD_MOD
               '|'||M.SER||
               '|'||(SELECT bdDATA FROM SP_PARSE_DATE(M.DT_DOC, 'DDMMYYYY'))||
               '|'||M.QTD_CONS||
               '|'||coalesce(m.IND_PREPAGO,'')||
               '|'||REPLACE(M.VL_DOC,       '.', ',')||
               '|'||REPLACE(m.VL_SERV,      '.', ',')||
               '|'||REPLACE(M.VL_SERV_NT,   '.', ',')||
               '|'||REPLACE(M.VL_TERC,      '.', ',')||
               '|'||REPLACE(M.VL_DESC,      '.', ',')||
               '|'||REPLACE(M.VL_DA,        '.', ',')||
               '|'||REPLACE(m.VL_BC_ICMS,   '.', ',')||
               '|'||REPLACE(m.VL_ICMS,      '.', ',')||
               '|'||REPLACE(m.VL_PIS,       '.', ',')||
               '|'||REPLACE(m.VL_COFINS,    '.', ',')||
               '|'||REPLACE(m.DED, '.', ',')||
               '|'
               ) BDLINHA
        FROM (
             SELECT mov.bdCODEMP,
                    COALESCE(Substring(mov.bdSERIE from 1 for 3), '') AS SER,
                    mov.bdDATAEMISSAO AS DT_DOC,
                    Count(mov.BDCHAVE) QTD_CONS,
                    D750.BDFORMA_PAGAMENTO as IND_PREPAGO,
                    Sum(COALESCE(D750.BDVLRSER, 0.00) + Coalesce(D750.BDVLRSERNTRIB, 0.00) + Coalesce(D750.BDVLRCOBTERC, 0.00) - Coalesce(D750.BDVALOR_DEDUCOES, 0.00)) AS VL_DOC,
                    SUM(COALESCE(D750.BDVLRSER, 0.00)) AS VL_SERV,
                    SUM(COALESCE(D750.BDVLRSERNTRIB, 0.00)) AS VL_SERV_NT,
                    SUM(COALESCE(D750.BDVLRCOBTERC, 0.00)) AS VL_TERC,
                    SUM(COALESCE(sai.bdDESCONTONOTA, 0.00)) AS VL_DESC,
                    SUM(COALESCE(D750.BDVLROUTDESP, 0.00)) AS VL_DA,
                    SUM(COALESCE(mov.BDBCICMS, 0.00)) AS VL_BC_ICMS,
                    SUM(COALESCE(mov.bdVLRICMS, 0.00)) AS VL_ICMS,
                    SUM(COALESCE(MOV.BDVLRPIS, 0.00)) AS VL_PIS,
                    SUM(COALESCE(MOV.BDVLRCOFINS, 0.00)) AS VL_COFINS,
                    SUM(COALESCE(D750.BDVALOR_DEDUCOES, 0.00)) as DED
            FROM (
                  SELECT s.bdCODEMP, S.bdchave,s.BDSERIE,s.BDDATAEMISSAO,
                         Sum(pro.BDBCICMS) BDBCICMS,
                         Sum(pro.BDVLRICMS) BDVLRICMS,
                         Sum(pro.BDVLRPIS) BDVLRPIS,
                         sum(pro.BDVLRCOFINS) BDVLRCOFINS

                  FROM (
                         Select s.bdcodemp, s.bdchave,s.BDSERIE,s.BDDATAEMISSAO
                          from VEF_EMP_TMOVSAI s
                           WHERE s.BDCODEMP = :PRCODEMP
                             AND s.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                            AND S.BDNUMDOCINI > 0
                            AND s.bdMODELO = 62
                            and s.BDCODSITNF = 0
                         )s
                  JOIN  VEF_EMP_TMOVPROSAI pro on (pro.BDCODEMP = s.BDCODEMP and pro.BDCHAVE = s.BDCHAVE)
                  WHERE Coalesce(pro.BDCODCSTICMS, '') <> ''
                  GROUP BY s.bdCODEMP, s.bdchave, s.BDSERIE, s.bddataemissao
                 ) MOV
            LEFT JOIN vef_emp_tD500SAI D750 on (D750.BDCODEMP = mov.bdcodemp and D750.BDCHAVE = mov.bdchave)
            join VEF_EMP_TMOVSAI sai ON(sai.BDCODEMP = mov.BDCODEMP AND sai.BDCHAVE = mov.BDCHAVE)
            where D750.bdfinalidade = 0
            GROUP BY mov.bdCODEMP, mov.BDSERIE,mov.BDDATAEMISSAO, D750.BDFORMA_PAGAMENTO
            ) m;

       /*                           D760                                      */
       INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
        SELECT :PRARQUIVO as BDID,
              LPAD(MOV.BDCODEMP, 6, '0')||'.1.D750.'||MOV.BDSERIE||'.'||MOV.BDDATAEMISSAO||'.'||coalesce(D750.BDFORMA_PAGAMENTO,'')|| '.1.D760.'||coalesce(pro.BDALIQICMS,'')||'.'||SUBSTRING(i.BDCODNAT FROM 1 FOR 4)||'.'||coalesce(ICMS.BDCSTICMS,'') BDCHAVEREG,
              'D760' BDREG,
              ('|D760'|| --REG
               '|'||ICMS.BDCSTICMS||          --CST_ICMS
               '|'||SUBSTRING(i.BDCODNAT FROM 1 FOR 4)||  --CFOP
               '|'||REPLACE(Cast(    Coalesce(pro.BDALIQICMS,  0.00)  as numeric(6,2))   , '.', ',')|| --ALIQ_ICMS
               '|'||REPLACE(Cast(SUM(Coalesce(pro.BDVLRITEM,   0.00)) as dm_numeric_15_2), '.', ',')|| --VL_OPR
               '|'||REPLACE(Cast(SUM(Coalesce(pro.BDBCICMS,    0.00)) as dm_numeric_15_2), '.', ',')|| --VL_BC_ICMS
               '|'||REPLACE(Cast(SUM(Coalesce(pro.BDVLRICMS,   0.00)) as dm_numeric_15_2), '.', ',')|| --VL_ICMS
               '|'||REPLACE(Cast(Sum(Coalesce(pro.BDREDBCICMS, 0.00)) as dm_numeric_15_2), '.', ',')|| --VL_RED_BC
               '|'||Coalesce(Max(obs.BDCODEXP), '')|| --COD_OBS
               '|'  
               ) BDLINHA,
               Max(i.BDCODOBS) BDCODOBS
        FROM (
              SELECT E.BDCODEMP, E.BDCHAVE,e.BDSERIE,e.BDDATAEMISSAO
              FROM VEF_EMP_TMOVSAI E
              WHERE E.BDCODEMP = :PRCODEMP
              AND E.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              AND E.BDMODELO = 62
              AND E.BDCODSITNF = 0
             ) MOV
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = mov.BDCODEMP AND I.BDCHAVE = mov.BDCHAVE)
        JOIN VEF_EMP_TMOVPROSAI pro on (pro.BDCODEMP = mov.BDCODEMP and pro.BDCHAVE = mov.BDCHAVE and pro.BDORDEM = i.BDORDEM)
        LEFT JOIN vef_emp_tD500SAI D750 on (D750.BDCODEMP = mov.bdcodemp and D750.BDCHAVE = mov.bdchave)
        LEFT JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS)
        LEFT JOIN VEF_BASE_TOBSERVACAO obs ON(obs.bdcodobs = i.BDCODOBS)
        where Coalesce(pro.BDCODCSTICMS, '') <> ''
          and D750.BDFINALIDADE = 0
        GROUP BY Mov.BDCODEMP,mov.BDSERIE,mov.BDDATAEMISSAO,D750.BDFORMA_PAGAMENTO,ICMS.BDCSTICMS,i.BDCODNAT, pro.BDALIQICMS;

       /*                           D761                                      */
       INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
        SELECT  :PRARQUIVO BDID,
              LPAD(M.BDCODEMP, 6, '0')||'.1.D750.'||M.BDSERIE||'.'||M.BDDATAEMISSAO||'.'||coalesce(D750.BDFORMA_PAGAMENTO,'')|| '.1.D760.'||pro.BDALIQICMS||'.'||SUBSTRING(i.BDCODNAT FROM 1 FOR 4)||'.'||coalesce(ICMS.BDCSTICMS,'')||'.D761' BDCHAVEREG,
              'D761' BDREG,
              ('|D761'|| --REG
               '|'||REPLACE(Coalesce(Sum(pro.BDVLRFCP), 0.00), '.', ',')|| --VL_FCP_OP
               '|'  
               ) BDLINHA
        FROM (
              SELECT E.BDCODEMP, E.BDCHAVE,E.BDSERIE,e.BDDATAEMISSAO
              FROM VEF_EMP_TMOVSAI E
              WHERE E.BDCODEMP = :PRCODEMP
              AND E.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              AND E.BDMODELO = 62
              AND E.BDCODSITNF = 0
              ) M
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = m.BDCODEMP AND I.BDCHAVE = m.BDCHAVE)
        JOIN  VEF_EMP_TMOVPROSAI pro on (pro.BDCODEMP = m.BDCODEMP and pro.BDCHAVE = m.BDCHAVE and pro.bdordem = i.bdordem)
        LEFT JOIN vef_emp_tD500SAI D750 on (D750.BDCODEMP = m.bdcodemp and D750.bdchave = m.bdchave)
        LEFT JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS)
        WHERE coalesce(PRO.BDCODCSTICMS, '') <> '' and D750.BDFINALIDADE = 0
        GROUP BY M.BDCODEMP,m.BDSERIE,m.BDDATAEMISSAO,D750.BDFORMA_PAGAMENTO, pro.BDALIQICMS, ICMS.BDCSTICMS, i.BDCODNAT;

     END
END^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOD_D700 (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260))
as
declare variable wTipoExpCodPart integer;
declare variable WLINHA blob sub_type 1 segment size 200;
BEGIN

  SELECT VW.BDTIPOEXPCODPART
  FROM VW_INT_SPEDICMS_REF VW
  WHERE VW.BDCODEMP = :PRCODEMP
  INTO :wTipoExpCodPart;

  IF (ROW_COUNT = 0) THEN
    wTipoExpCodPart = -1;

  --Entrada
  EXECUTE PROCEDURE SP_EXPORTA_BLOCOD_ENT_D700(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, :wTipoExpCodPart);

  --Saida
  EXECUTE PROCEDURE SP_EXPORTA_BLOCOD_SAI_D700(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO);

  --        Exporta Arquivo        --
  OPENARQ(:PRARQUIVO,:PRCODEMP);

  FOR SELECT E.BDLINHA
      FROM TEXPORTACAO_SPED E
      WHERE E.BDID = :PRARQUIVO
      ORDER BY E.BDCHAVEREG
      INTO :wLinha
  DO
    BEGIN
      WRITELNOA(:wLinha,:PRCODEMP);
    END

  CLOSEARQ(:PRARQUIVO,:PRCODEMP);
END^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOD_SAI (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRTIPOEXPCODPART integer,
    PRCODPLAPADRAOREF integer,
    PRPERFIL integer)
as
declare variable WSEGREGACAO varchar(5);
declare variable WCHAVEMIN integer;
declare variable WCHAVEMAX integer;
declare variable WEXPE310 DM_BOOLEAN;
declare variable WEXP_REG_D300 DM_BOOLEAN;
declare variable WTIPOEXPCONTA integer;
BEGIN
  /*****************************************************************************
   *--------------------------------->>SAÍDA<<---------------------------------*
   ****************************************************************************/
  SELECT Coalesce(rdb$get_context('USER_SESSION', 'W_SEGREGACAO_FISCAL'),'FALSE') FROM rdb$database INTO WSEGREGACAO;

   SELECT MIN(s.bdCHAVE) AS bdCHAVEMIN, MAX(s.bdCHAVE) AS bdCHAVEMAX
   FROM VEF_EMP_TMOVSAI S
   LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = S.BDCODEMP)
   WHERE S.BDCODEMP = :prCODEMP
     AND S.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, S.BDCHAVE)
     AND S.BDDATAEMISSAO BETWEEN :prDTINI AND :prDTFIM
     AND S.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800, 63)
   INTO :wCHAVEMIN, :wCHAVEMAX;

    SELECT FIRST 1 BDEXPE310, BDEXP_REG_D300
    FROM VEF_INT_TSPEDICMS
    WHERE bdCODEMP = :prCODEMP
    AND bdREFERENCIA <= EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0')
    ORDER BY bdREFERENCIA DESC
    INTO :WEXPE310, :WEXP_REG_D300;

  SELECT bdTIPOEXPCONTA FROM VW_INT_SPEDICMS_REF WHERE bdCODEMP = :prCODEMP INTO :wTIPOEXPCONTA;

  delete from TMP_VEF_EMP_TD160CARGATRANS;
  insert into TMP_VEF_EMP_TD160CARGATRANS select * from
    (SELECT D160.BDCODEMP, D160.BDCHAVE, D160.BDCODCIDREMETENTE, D160.BDCODCIDDESTINATARIO
                   FROM VEF_EMP_TMOVSAI S
                   LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = S.BDCODEMP)
                   LEFT OUTER JOIN VEF_EMP_TD160CARGATRANS D160 ON(D160.BDCODEMP = S.BDCODEMP AND D160.BDCHAVE = S.BDCHAVE AND ((D160.BDCODCIDREMETENTE IS NOT NULL) OR (D160.BDCODCIDDESTINATARIO IS NOT NULL)))
                   WHERE S.BDCODEMP = :PRCODEMP
                   AND S.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, S.BDCHAVE)
                   AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                   AND S.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800, 63)
                   AND D160.bdordemcartrans = 1);

  /*****************************************************************************
   *                                   D100                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODINFCOM, BDORDEMINFCOM, BDCHAVE, BDCREDITO, BDANOCREDITO, BDCODPLAPADRAO, BDCREDITOREF, BDCREDITOPLAPADRAOREF, BDCTALON, BDCODCID)
  SELECT  :PRARQUIVO BDID,
          LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100',
          'D100' BDREG,
          ('|D100|1'||
           '|'||M.BDEMITENTE||                    /* MODELO 63 NÃO EXPORTA O PARCIPANTE */
           '|'||IIF((M.BDCODSITNF IN (2, 3, 4, 5) OR M.BDMODELO = 63), '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, M.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))|| IIF(:wexpe310 = 'TRUE' and (COALESCE(D100.BDVLR_FCP_UF_DEST, 0) > 0 or COALESCE(D100.BDVLRICMS_UF_DEST,0) > 0 or COALESCE(D100.BDVLRICMS_UF_REM,0) > 0) and COALESCE(D100.BDCIDDEST,0) > 0 and D100.BDCIDDEST <> ter.bdcodcid, '-'||(SELECT cid.bdcodibge from TCIDADE cid where cid.bdcodcid = D100.BDCIDDEST),'') )||  --COD_PART
           '|'||MOD.BDMODELOSTR||            --COD_MOD
           '|'||LPAD(M.BDCODSITNF, 2, '0')|| --COD_SIT
           '|'||COALESCE(M.BDSERIE, '')||    --SER
           '|'||COALESCE(M.BDSUBSERIE, '')|| --SUB
           '|'||M.BDNUMDOCINI||              --NUM_DOC
           '|'||COALESCE(IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)) = '', '', RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)), 44, ' ')), '')||       --CHV_NFE
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))|| --DT_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))|| --DT_A_P
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(IIF(M.BDMODELO IN(57, 67, 63), D100.BDTIPOCTE, ''), ''))|| --TP_CT-e
           /*'|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D100.BDCHAVECTEREF)), ''))|| --CHV_CTE_REF --CHV_CTE_REF
            Criado modelo 63, só deve ser informado a chave de CTE se o tipo de CTE for 1 ou 2 #123465 - Camilla M. 05/11/19 */
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(IIF(M.BDMODELO = 63,IIF(D100.BDTIPOCTE IN (3),(SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D100.BDCHAVECTEREF)),''),(SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(D100.BDCHAVECTEREF))),''))|| --CHV_CTE_REF
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(SUM(COALESCE(MOV.BDVLRCONTAB, 0.00)), '.', ','), ''))||                --VL_DOC
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(M.BDDESCONTONOTA, '.', ','), ''))||              --VL_DESC
           '|'||IIF((M.BDCODSITNF IN (2, 3, 4, 5) OR M.BDMODELO = 63), '', COALESCE((IIF(((INDFRETED100.BDCODEXPFRETE = '') OR (INDFRETED100.BDCODEXPFRETE IS NULL)), '0', INDFRETED100.BDCODEXPFRETE)), ''))|| --IND_FRT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(D100.BDTIPOCTE IN ('05','06'), COALESCE(REPLACE(SUM(COALESCE(D130.BDVLRTOTALFRETE, 0.00)), '.', ','), '') ,COALESCE(REPLACE(SUM(COALESCE(MOV.BDVLRCONTAB, 0.00)), '.', ','), '')))||                --VL_SERV
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(COALESCE(SUM(COALESCE(MOV.BDBASEICMS, 0.00)), 0.00), '.', ','), ''))|| --VL_BC_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(COALESCE(SUM(COALESCE(MOV.BDVLRICMS, 0.00)), 0.00), '.', ','), ''))||  --VL_ICMS
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(REPLACE(COALESCE(SUM(COALESCE(MOV.BDISENTASICMS, 0.00)) + SUM(COALESCE(MOV.BDOUTRASICMS, 0.00)), 0.00), '.', ','), ''))|| --VL_NT
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(INFCOMD100.BDCODINFCOM, ''))|| --COD_INF
           --'|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(D100.BDCODCTA, ''))||          --COD_CTA
           '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE((CASE :wTIPOEXPCONTA
                                                                  WHEN '0' THEN CCL.BDCODTPLA
                                                                  WHEN '1' THEN CCL.BDCTALON
                                                                  WHEN '2' THEN CCL.BDAPECTA
                                                                ELSE CCLEP.bdCTALON END), ''))|| --COD_CTA
           --Campos exportados apartir de 01/01/2018
           IIF((EXTRACT(YEAR FROM :PRDTINI)) < 2018, '', IIF(M.BDCODSITNF IN (2, 3, 4, 5), '|', '|'|| IIF(D100.BDTIPOCTE IN ('05','06'),'9999998',COALESCE(COALESCE(CIDORIGD100.BDCODIBGE, ORIG.BDCODIBGE), ''))))|| --COD_MUN_ORIG
           IIF((EXTRACT(YEAR FROM :PRDTINI)) < 2018, '', IIF(M.BDCODSITNF IN (2, 3, 4, 5), '|', '|'|| IIF(D100.BDTIPOCTE IN ('05','06'),'9999998',COALESCE(COALESCE(CIDDESTD100.BDCODIBGE, DEST.BDCODIBGE), ''))))|| --COD_MUN_DEST
           '|'
           ), IIF((M.BDCODSITNF IN (2, 3, 4, 5)) OR (M.BDMODELO = 63), NULL, M.BDCODTER) BDCODTER, INFCOMD100.BDCODINFCOM, INFCOMD100.BDORDEMINFCOM,
          M.BDCHAVE, CCL.BDCODTPLA BDCREDITO,
          COALESCE(CCLE.BDANO, CAST(SUBSTRING(MOV.BDREFLAN FROM 1 FOR 4) AS INTEGER)) BDANOCREDITO,
          COALESCE(D100.BDCODPLAPADRAO, LAN.BDCODPLAPADRAO) BDCODPLAPADRAO, CCLEP.BDCODTPLAREF BDCREDITOREF,
          CCLEP.BDCODPLAPADRAOREF BDCREDITOPLAPADRAOREF, CCL.BDCTALON BDCTALON, IIF(:wexpe310 = 'TRUE' and (COALESCE(D100.BDVLR_FCP_UF_DEST, 0) > 0 or COALESCE(D100.BDVLRICMS_UF_DEST,0) > 0 or COALESCE(D100.BDVLRICMS_UF_REM,0) > 0) and COALESCE(D100.BDCIDDEST,0) > 0 and D100.BDCIDDEST <> ter.bdcodcid, D100.BDCIDDEST, null)
  FROM (
--        SELECT S.BDCODEMP, S.BDCHAVE, s.bdREFLAN
--        FROM VEF_EMP_TMOVSAI S
--        WHERE S.BDCODEMP = :PRCODEMP
--          AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
--          AND S.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800, 63)

        select lan.bdcodemp,lan.bdchave,lan.bdreflan, lan.BDCODCID, Min(i.bdordem) bdordem, sum(I.BDVLRCONTAB) BDVLRCONTAB,
        sum(BDOUTRASICMS) BDOUTRASICMS, sum(BDBASEICMS) BDBASEICMS,sum(BDVLRICMS) BDVLRICMS,sum(BDISENTASICMS) BDISENTASICMS,
       d160.bdCODCIDREMETENTE, d160.bdCODCIDDESTINATARIO
        from (
                SELECT E.BDCODEMP, E.BDCHAVE, E.BDREFLAN, E.BDCODCID
                FROM VEF_EMP_TMOVSAI E
                LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = E.BDCODEMP)
                WHERE E.BDCODEMP = :PRCODEMP
                  AND E.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, E.BDCHAVE)
                  AND E.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND E.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800,63) -- Novo modelo 63 #123465
                  AND NOT (/*E.BDMODELO IN (57, 63, 67) AND*/ E.BDCODSITNF IN (4, 5, 10, 11) AND E.BDREFLAN >= 202301) --#169202 - Adam - 09/11/2022 - Em 2023 os modelos 57, 63 e 65 deixar??o de usar as situa????es 4 e 5.
              )lan
       LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS i ON(I.BDCODEMP = lan.BDCODEMP AND I.BDCHAVE = lan.BDCHAVE)
       LEFT OUTER JOIN TMP_VEF_EMP_TD160CARGATRANS D160 ON(D160.BDCODEMP = lan.bdCODEMP AND D160.BDCHAVE = lan.bdCHAVE)
       group by lan.bdcodemp,lan.bdchave,lan.bdreflan, lan.BDCODCID, bdCODCIDREMETENTE, bdCODCIDDESTINATARIO
       ) MOV
  JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TTABMODELOLAN MOD ON(MOD.BDMODELO = M.BDMODELO)
  LEFT OUTER JOIN VEF_EMP_TD100SAI D100 ON (D100.BDCODEMP = M.BDCODEMP AND D100.BDCHAVE = M.BDCHAVE)
  LEFT OUTER JOIN (SELECT D130.BDCODEMP, D130.BDCHAVE, sum(D130.BDVLRTOTALFRETE) BDVLRTOTALFRETE
                   FROM VEF_EMP_TD130COMPCON D130
                   WHERE BDCODEMP = :PRCODEMP
                   group by BDCODEMP, BDCHAVE) D130 on (D130.BDCODEMP = M.BDCODEMP AND D130.BDCHAVE = M.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TTABINFRETE INDFRETED100 ON (D100.BDINDFRETE = INDFRETED100.BDORDEMFRETE)
  LEFT OUTER JOIN VEF_BASE_TCADINFCOM INFCOMD100 ON (D100.BDORDEMINFCOM = INFCOMD100.BDORDEMINFCOM)
  LEFT OUTER JOIN TCIDADE CIDORIGD100 ON (CIDORIGD100.BDCODCID = D100.BDCIDORIGEM)
  LEFT OUTER JOIN TCIDADE CIDDESTD100 ON (CIDDESTD100.BDCODCID = D100.BDCIDDEST)
  LEFT OUTER JOIN TCIDADE ORIG ON (ORIG.BDCODCID = MOV.BDCODCIDREMETENTE)
  LEFT OUTER JOIN TCIDADE DEST ON (DEST.BDCODCID = MOV.BDCODCIDDESTINATARIO)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = M.BDCODTER)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = M.bdcodter)
   -- Alt.: #87095 #92148 #89325 #92407 #100955 #121349 - Ajustes para levar a conta referencial na exportação do lançamento
   --LEFT OUTER JOIN VW_INT_SPEDICMS_REF ConfSPED ON (ConfSPED.bdCODEMP = mov.bdCODEMP)
   LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, MIN(t.bdCHAVE) AS BDCHAVE, l.bdCODPLAPADRAO, l.bdCREDITO
                    FROM TOL_VEF_EMP_TMOVSAI t
                    LEFT OUTER JOIN VSUC_EMPRESAS_TLAN l ON (l.bdCODEMP = t.bdCODEMP AND l.bdCHAVE = t.bdCHAVE)
                    WHERE t.bdFORMULA LIKE '%NAT%LAN(%)' -- Alt.: #92219 - Apenas contas do valor contábil...
                      AND l.bdCREDITO IS NOT NULL -- Alt.: #120050 - Para apenas retornar quando a contabilização tiver uma conta informada, quando tem desconto a conta do desconto vem primeiro...
                      AND t.bdCODEMP = :PRCODEMP
                      AND t.bdCHAVESAI BETWEEN :wCHAVEMIN AND :wCHAVEMAX
                    GROUP BY t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, l.bdCODPLAPADRAO, l.bdCREDITO) LAN ON (lan.bdCODEMP = MOV.bdCODEMP AND lan.bdCHAVESAI = MOV.bdCHAVE AND lan.bdORDEM = MOV.bdORDEM)
   LEFT OUTER JOIN  (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) BDCHAVE FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM) TOLRAT
                     ON (TOLRAT.BDCODEMP = MOV.BDCODEMP AND TOLRAT.BDCHAVELAN = MOV.BDCHAVE AND TOLRAT.BDORDEM =  MOV.BDORDEM)
   LEFT OUTER JOIN PLANOS_TPLA CCL ON(COALESCE(D100.BDCODPLAPADRAO, LAN.BDCODPLAPADRAO, TOLRAT.BDCODEMP) = CCL.BDCODPLAPADRAO AND COALESCE(D100.BDCODTPLA, LAN.BDCREDITO, TOLRAT.BDCHAVE) = CCL.BDCODTPLA)
   LEFT OUTER JOIN PLANOS_TPLA_ECF CCLE ON (CCLE.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF
                                            AND CCLE.BDANO = (SELECT FIRST 1 BDANO
                                                              FROM PLANOS_TPLA_ECF
                                                              WHERE CAST(BDANO || '01' AS INTEGER) <= MOV.BDREFLAN
                                                                AND BDCODTPLAREF IS NOT NULL
                                                                AND CCLE.BDCODPLAPADRAO = BDCODPLAPADRAO
                                                                AND CCLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF
                                                                AND CCLE.BDCODTPLA = BDCODTPLA
                                                              ORDER BY BDANO DESC)
                                            AND CCLE.BDCODPLAPADRAO = CCL.BDCODPLAPADRAO AND CCLE.BDCODTPLA = CCL.BDCODTPLA)
  LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO CCLEP ON (CCLE.BDCODPLAPADRAOREF = CCLEP.BDCODPLAPADRAOREF AND CCLE.BDCODTPLAREF = CCLEP.BDCODTPLAREF)
  -- Alt.: #87095 #92148 #89325 #92407 #100955 #121349 - Fim
  GROUP BY M.BDCODEMP, M.BDCHAVE,M.BDEMITENTE,M.BDCODSITNF,M.BDMODELO,M.BDCODTER,TER.BDCGCTER,TER.BDIETER,TerEmp.BDCODIGOARQUIVO,
           MOD.BDMODELOSTR,M.BDSERIE,M.BDSUBSERIE,M.BDNUMDOCINI,M.BDCHAVENFE,M.BDDATAEMISSAO,D100.BDTIPOCTE,D100.BDCHAVECTEREF,
           M.BDDESCONTONOTA,INDFRETED100.BDCODEXPFRETE,D100.BDCODCTA,CIDORIGD100.BDCODIBGE,ORIG.BDCODIBGE,CIDDESTD100.BDCODIBGE,
           DEST.BDCODIBGE,INFCOMD100.BDCODINFCOM,INFCOMD100.BDORDEMINFCOM,M.BDCHAVE,CCL.BDCODTPLA,
           CCLE.BDANO,MOV.BDREFLAN,D100.BDCODPLAPADRAO,LAN.BDCODPLAPADRAO,CCLEP.BDCODTPLAREF,
           CCLEP.BDCODPLAPADRAOREF,CCL.BDCTALON,
           CCL.BDAPECTA,CCLEP.bdCTALON,MOV.BDCODCID, m.BDCODCID ,D100.BDVLR_FCP_UF_DEST, D100.BDVLRICMS_UF_DEST, D100.BDVLRICMS_UF_REM, ter.bdcodcid, D100.BDCIDDEST;

  delete from TMP_VEF_EMP_TD160CARGATRANS;
  /*****************************************************************************
   *                                   D101                                    *
   ****************************************************************************/
  IF (:PRDTINI >= '01/01/2016') THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D101',
             'D101' BDREG,
             ('|D101'||
              '|'||REPLACE(COALESCE(D100.BDVLR_FCP_UF_DEST, 0.00), '.', ',')||
              '|'||REPLACE(COALESCE(D100.BDVLRICMS_UF_DEST, 0.00), '.', ',')||
              '|'||REPLACE(COALESCE(D100.BDVLRICMS_UF_REM, 0.00), '.', ',')||'|'
             )
      FROM (
            SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDMODELO,
                   SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB
            FROM (
                  SELECT S.BDCODEMP, S.BDCHAVE, S.BDMODELO
                  FROM VEF_EMP_TMOVSAI S
                  LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = S.BDCODEMP)
                  WHERE S.BDCODEMP = :PRCODEMP
                  AND S.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, S.BDCHAVE)
                  AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  AND S.BDMODELO IN(57, 67, 63)
                  AND S.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11) --Cancelado
                 ) MOV
            LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
            GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDMODELO
           ) M
        JOIN VEF_EMP_TD100SAI D100 ON (D100.BDCODEMP = M.BDCODEMP AND D100.BDCHAVE = M.BDCHAVE)
        JOIN TCIDADE CID_ORIG ON (CID_ORIG.BDCODCID = D100.BDCIDORIGEM)
        JOIN TCIDADE CID_DEST ON (CID_DEST.BDCODCID = D100.BDCIDDEST)
      WHERE ((M.BDVLRCONTAB > 0) AND ((D100.BDVLR_FCP_UF_DEST > 0) OR (D100.BDVLRICMS_UF_DEST > 0) OR (D100.BDVLRICMS_UF_REM > 0))) or ((M.BDMODELO = 63) and (CID_ORIG.BDCODUF <> CID_DEST.BDCODUF));
    END

  /*****************************************************************************
   *                                   D110                                    *
   ****************************************************************************/
  IF (:PRPERFIL NOT IN(2)) THEN
    BEGIN
      SETORDEMSEQUENCIAL(0);
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD)
      SELECT :PRARQUIVO BDID,
             LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D110.'||LPAD(D110.BDORDEMST, 6, '0'),
             'D110' BDREG,
             ('|D110'||
              '|'||GETORDEMSEQUENCIAL(0)||--NUM_ITEM
              '|'||IIF(((PRO_VINC.BDCODSAIDA IS NULL) OR (PRO_VINC.BDCODSAIDA = '')), PRO_VINC.BDCODPROD, PRO_VINC.BDCODSAIDA)|| --COD_ITEM
              '|'||REPLACE(COALESCE(D110.BDVLRSER, 0.00), '.', ',')||
              '|'||REPLACE(COALESCE(D110.BDOUTVAL, 0.00), '.', ',')||
              '|'
             ), PRO_VINC.BDCODPROD
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = S.BDCODEMP)
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, S.BDCHAVE)
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND S.BDMODELO IN(7)
            AND S.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11) --Cancelado
           ) M
      JOIN VEF_EMP_TD110SAI D110 ON(D110.BDCODEMP = M.BDCODEMP AND D110.BDCHAVE = M.BDCHAVE)
      LEFT OUTER JOIN TCADPRO_VINC PRO_VINC ON(PRO_VINC.BDCODEMP = D110.BDCODEMP AND PRO_VINC.BDCODPROD = D110.BDCODPROD);

      /*****************************************************************************
       *                                   D120                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D110.'||LPAD(D120.BDORDEMST, 6, '0')||'.D120.'||LPAD(D120.BDORDEMD120, 6, '0'),
             'D120' BDREG,
             ('|D120'||
              '|'||COALESCE(IIF(UFORIG.BDSIGLAUF = 'EX', '9999999', CIDORIG.BDCODIBGE), '')||
              '|'||COALESCE(IIF(UFDEST.BDSIGLAUF = 'EX', '9999999', CIDDEST.BDCODIBGE), '')||
              '|'||COALESCE(REPLACE(D120.BDPLACAVEICULO, '-', ''), '')||
              '|'||COALESCE(UF.BDSIGLAUF, '')||
              '|'
             )
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = S.BDCODEMP)
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, S.BDCHAVE)
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND S.BDMODELO IN(7)
            AND S.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11) --Cancelado
           ) M
      JOIN VEF_EMP_TD120COMPCON D120 ON(D120.BDCODEMP = M.BDCODEMP AND D120.BDCHAVE = M.BDCHAVE)
      LEFT OUTER JOIN TCIDADE CIDORIG ON (CIDORIG.BDCODCID = D120.BDCODCIDORIG)
      LEFT OUTER JOIN TUF UFORIG ON (UFORIG.BDCODUF = CIDORIG.BDCODUF)
      LEFT OUTER JOIN TCIDADE CIDDEST ON (CIDDEST.BDCODCID = D120.BDCODCIDDEST)
      LEFT OUTER JOIN TUF UFDEST ON (UFDEST.BDCODUF = CIDDEST.BDCODUF)
      LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = D120.BDCODUF);

      /*****************************************************************************
       *                                   D130                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODTERAUX)
      SELECT :PRARQUIVO BDID,
             LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D130' || LPAD(D130.BDORDEM, 6, '0'),
             'D130' BDREG,
             ('|D130'||
              '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, D130.BDCODTERCONSIGNATARIO, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO)), '')|| --COD_PART_CONSG
              '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:PRTIPOEXPCODPART, D130.BDCODTERREDESPACHANTE, TER_DES.BDCGCTER, TER_DES.BDIETER, TerEmp_DES.BDCODIGOARQUIVO)), '')|| --COD_PART_RED
              '|'||COALESCE(D130.BDINDFRETERED, '')|| --IND_FRT_RED
              '|'||COALESCE(IIF(UFORIG.BDSIGLAUF = 'EX', '9999999', CIDORIG.BDCODIBGE), '')|| --COD_MUN_ORIG
              '|'||COALESCE(IIF(UFDEST.BDSIGLAUF = 'EX', '9999999', CIDDEST.BDCODIBGE), '')|| --COD_MUN_DEST
              '|'||COALESCE(TRIM(REPLACE(D130.BDPLACAID, '-', '')), '')||          --VEIC_ID
              '|'||REPLACE(COALESCE(D130.BDVLRLIQFRETE, 0.00), '.', ',')||   --VL_LIQ_FRT
              '|'||REPLACE(COALESCE(D130.BDVLRSECCAT, 0.00), '.', ',')||     --VL_SEC_CAT
              '|'||REPLACE(COALESCE(D130.BDVLRDESPACHO, 0.00), '.', ',')||   --VL_DESP
              '|'||REPLACE(COALESCE(D130.BDVLRPEDAGIO, 0.00), '.', ',')||    --VL_PEDG
              '|'||REPLACE(COALESCE(D130.BDVLROUTVAL, 0.00), '.', ',')||     --VL_OUT
              '|'||REPLACE(COALESCE(D130.BDVLRTOTALFRETE, 0.00), '.', ',')|| --VL_FRT
              '|'||COALESCE(UF.BDSIGLAUF, '')||                              --UF_ID
              '|'
             ), D130.BDCODTERCONSIGNATARIO, D130.BDCODTERREDESPACHANTE
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = S.BDCODEMP)
            LEFT OUTER JOIN VEF_EMP_TD100SAI D100 ON (D100.BDCODEMP = S.BDCODEMP AND D100.BDCHAVE = S.BDCHAVE)
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, S.BDCHAVE)
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND ((S.BDMODELO IN(8, 800)) or (S.BDMODELO = 57 and (D100.BDTIPOCTE IN ('05','06') AND EXTRACT(YEAR FROM :PRDTINI) >= 2025)))
            AND S.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11) --Cancelado
           ) M
      JOIN VEF_EMP_TD130COMPCON D130 ON(D130.BDCODEMP = M.BDCODEMP AND D130.BDCHAVE = M.BDCHAVE)
      LEFT OUTER JOIN TCIDADE CIDORIG ON (CIDORIG.BDCODCID = D130.BDCODCIDORIGEM)
      LEFT OUTER JOIN TUF UFORIG ON (UFORIG.BDCODUF = CIDORIG.BDCODUF)
      LEFT OUTER JOIN TCIDADE CIDDEST ON (CIDDEST.BDCODCID = D130.BDCODCIDDESTINO)
      LEFT OUTER JOIN TUF UFDEST ON (UFDEST.BDCODUF = CIDDEST.BDCODUF)
      LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = D130.BDCODUF)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = D130.BDCODTERCONSIGNATARIO)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                             ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp ON (TerEmp.bdcodter = D130.BDCODTERCONSIGNATARIO)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER_DES ON(TER_DES.BDCODTER = D130.BDCODTERREDESPACHANTE)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                            ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp_DES ON (TerEmp_DES.bdcodter = D130.BDCODTERREDESPACHANTE);

      /*****************************************************************************
       *                                   D160                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D160.'||LPAD(D160.BDORDEMCARTRANS, 6, '0'),
             'D160' BDREG,
             ('|D160'||
              '|'||COALESCE(REPLACE(D160.BDNRDESPACHO, '|', ''), '')|| --DESPACHO
              '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(1/*se todos números forem iguais retorna em branco*/, 0, TERREM.BDCGCTER, '', '')), '')|| --CNPJ_CPF_REM
              '|'||COALESCE(IIF(((POSITION(UPPER(TERREM.BDIETER), 'ISENTO') > 0) OR (POSITION(UPPER(TERREM.BDIETER), 'ISENTA') > 0)), '', (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(TERREM.BDIETER))), '')|| --IE_REM
              '|'||COALESCE(IIF(UFORIG.BDSIGLAUF = 'EX', '9999999', CIDORIG.BDCODIBGE), '')|| --COD_MUN_ORI
              '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(1/*se todos números forem iguais retorna em branco*/, 0, TERDES.BDCGCTER, '', '')), '')|| --CNPJ_CPF_DEST
              '|'||COALESCE(IIF(((POSITION(UPPER(TERDES.BDIETER), 'ISENTO') > 0) OR (POSITION(UPPER(TERDES.BDIETER), 'ISENTA') > 0)), '', (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(TERDES.BDIETER))), '')|| --IE_DEST
              '|'||COALESCE(IIF(UFDEST.BDSIGLAUF = 'EX', '9999999', CIDDEST.BDCODIBGE), '')|| --COD_MUN_DEST
              '|'
             )
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = S.BDCODEMP)
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, S.BDCHAVE)
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND S.BDMODELO IN(8, 9, 10, 11, 26, 27, 800)
            AND S.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11) --Cancelado
           ) M
      JOIN VEF_EMP_TD160CARGATRANS D160 ON(D160.BDCODEMP = M.BDCODEMP AND D160.BDCHAVE = M.BDCHAVE)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERREM ON (TERREM.BDCODTER = D160.BDCODTERREMETENTE)
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERDES ON (TERDES.BDCODTER = D160.BDCODTERDESTINATARIO)
      LEFT OUTER JOIN TCIDADE CIDORIG ON (CIDORIG.BDCODCID = D160.BDCODCIDREMETENTE)
      LEFT OUTER JOIN TUF UFORIG ON (UFORIG.BDCODUF = CIDORIG.BDCODUF)
      LEFT OUTER JOIN TCIDADE CIDDEST ON (CIDDEST.BDCODCID = D160.BDCODCIDDESTINATARIO)
      LEFT OUTER JOIN TUF UFDEST ON (UFDEST.BDCODUF = CIDDEST.BDCODUF);

      /*****************************************************************************
       *                                   D161                                    *
       ****************************************************************************/
      IF (:PRPERFIL = 0) THEN /*Perfil A*/
        BEGIN
          INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
          SELECT :PRARQUIVO BDID,
                 LPAD(M.BDCODEMP, 6, '0')||'.1.'||LPAD(M.BDCHAVE, 10, '0')||'.D100.D160.'||LPAD(D160.BDORDEMCARTRANS, 6, '0')||'.D161',
                 'D161' BDREG,
                 ('|D161'||
                  '|'||COALESCE(TRAN.BDCODEXPTRAN, '')||
                  '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(1/*se todos números forem iguais retorna em branco*/, 0, TERCOL.BDCGCTER, '', '')), '')|| --CNPJ_CPF_COL
                  '|'||COALESCE(IIF(((POSITION(UPPER(TERCOL.BDIETER), 'ISENTO') > 0) OR (POSITION(UPPER(TERCOL.BDIETER), 'ISENTA') > 0)), '', TERCOL.BDIETER), '')||       --IE_REM
                  '|'||COALESCE(IIF(UFCOL.BDSIGLAUF = 'EX', '9999999', CIDCOL.BDCODIBGE), '')|| --COD_MUN_COL
                  '|'||COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(1/*se todos números forem iguais retorna em branco*/, 0, TERENT.BDCGCTER, '', '')), '')|| --CNPJ_CPF_ENT
                  '|'||COALESCE(IIF(((POSITION(UPPER(TERENT.BDIETER), 'ISENTO') > 0) OR (POSITION(UPPER(TERENT.BDIETER), 'ISENTA') > 0)), '', TERENT.BDIETER), '')||       --IE_ENTG
                  '|'||COALESCE(IIF(UFENT.BDSIGLAUF = 'EX', '9999999', CIDENT.BDCODIBGE), '')|| --COD_MUN_ENTG
                  '|'
                 )
          FROM (
                SELECT S.BDCODEMP, S.BDCHAVE
                FROM VEF_EMP_TMOVSAI S
                LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = S.BDCODEMP)
                WHERE S.BDCODEMP = :PRCODEMP
                AND S.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, S.BDCHAVE)
                AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                AND S.BDMODELO IN(8, 9, 10, 11, 26, 27, 800)
                AND S.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11) --Cancelado
               ) M
          JOIN VEF_EMP_TD160CARGATRANS D160 ON(D160.BDCODEMP = M.BDCODEMP AND D160.BDCHAVE = M.BDCHAVE AND D160.BDCODCIDCOLETA > 0)
          JOIN VEF_BASE_TTABTIPOTRAN TRAN ON(TRAN.BDCODTRAN = D160.BDCODTRAN AND TRAN.BDCODEXPTRAN IS NOT NULL)
          LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERCOL ON (TERCOL.BDCODTER = D160.BDCODTERCOLETA)
          LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERENT ON (TERENT.BDCODTER = D160.BDCODTERENTREGA)
          LEFT OUTER JOIN TCIDADE CIDCOL ON (CIDCOL.BDCODCID = D160.BDCODCIDCOLETA)
          LEFT OUTER JOIN TUF UFCOL ON (UFCOL.BDCODUF = CIDCOL.BDCODUF)
          LEFT OUTER JOIN TCIDADE CIDENT ON (CIDENT.BDCODCID = D160.BDCODCIDENTREGA)
          LEFT OUTER JOIN TUF UFENT ON (UFENT.BDCODUF = CIDENT.BDCODUF);
        END

      /*****************************************************************************
       *                                   D162                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
      SELECT :PRARQUIVO BDID,
             LPAD(D162.BDCODEMP, 6, '0')||'.1.'||LPAD(D162.BDCHAVE, 10, '0')||'.D100.D160.'||LPAD(D162.BDORDEMCARTRANS, 6, '0')||'.D162.'||LPAD(D162.BDORDEMDOCFIS, 6, '0'),
             'D162' BDREG,
             ('|D162'||
              '|'||COALESCE(DOC.BDDOCFIS, '')|| --COD_MOD
              '|'||COALESCE(D162.BDSERIE, '')|| --SER
              '|'||COALESCE(D162.BDNRDOC, '')|| --NUM_DOC
              '|'||(SELECT BDDATA FROM SP_PARSE_DATE(D162.BDDTDOC, 'DDMMYYYY'))|| --DT_DOC
              '|'||REPLACE(COALESCE(CAST(D162.BDVLRDOC AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --VL_DOC
              '|'||REPLACE(COALESCE(CAST(D162.BDVLRMER AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --VL_MER
              '|'||COALESCE(SUBSTRING(ROUND(D162.BDQTDVOL) FROM 1 FOR POSITION('.', D162.BDQTDVOL)), 0.00)|| --QTD_VOL
              '|'||REPLACE(COALESCE(CAST(D162.BDPESOBRUTO AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --PESO_BRT
              '|'||REPLACE(COALESCE(CAST(D162.BDPESOLIQ AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --PESO_LIQ
              '|'
             )
      FROM (
            SELECT S.BDCODEMP, S.BDCHAVE
            FROM VEF_EMP_TMOVSAI S
            LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = S.BDCODEMP)
            WHERE S.BDCODEMP = :PRCODEMP
            AND S.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, S.BDCHAVE)
            AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND S.BDMODELO IN(8, 9, 10, 11, 26, 27, 800)
            AND S.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11) --Cancelado
           ) M
      JOIN VEF_EMP_TD160CARGATRANS D160 ON(D160.BDCODEMP = M.BDCODEMP AND D160.BDCHAVE = M.BDCHAVE/* AND D160.BDCODCIDCOLETA > 0*/)
      JOIN VEF_EMP_TD162DOCFIS D162 ON(D162.BDCODEMP = D160.BDCODEMP AND D162.BDCHAVE = D160.BDCHAVE AND D162.BDORDEMCARTRANS = D160.BDORDEMCARTRANS)
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOC ON(DOC.BDCODDOCFIS = D162.BDCODDOCFIS);
   END

  /*****************************************************************************
   *                                   D190                                    *
   ****************************************************************************/
  SETORDEMSEQUENCIAL(:PRCODEMP);
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT  :PRARQUIVO BDID,
          LPAD(MOV.BDCODEMP, 6, '0')||'.1.'||LPAD(MOV.BDCHAVE, 10, '0')||'.D100.D190.'||LPAD(GETORDEMSEQUENCIAL(MOV.BDCODEMP), 10, '0'),
          'D190' BDREG,
          ('|D190'||
           '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
           '|'||COALESCE(I.bdprefixonat, '')|| --CFOP
           '|'||COALESCE(REPLACE(CAST(I.BDALIQICMS AS NUMERIC(6, 2)), '.', ','), '')||  --ALIQ_ICMS
           '|'||COALESCE(REPLACE(SUM(I.BDVLRCONTAB), '.', ','), '')|| --VL_OPR
           '|'||COALESCE(REPLACE(SUM(I.BDBASEICMS), '.', ','), '0,00')|| --VL_BC_ICMS
           '|'||COALESCE(REPLACE(SUM(I.BDVLRICMS), '.', ','), '0,00')|| --VL_ICMS
           '|'||REPLACE((SELECT BDVALOR FROM GET_TRATA_VALOR_NEGATIVO(IIF((SUBSTRING(ICMS.BDCSTICMS FROM 2 FOR 2) IN (20, 70)), (COALESCE(SUM(I.BDISENTASICMS), 0) + COALESCE(SUM(I.BDOUTRASICMS), 0)), 0.00))), '.', ',')|| --VL_RED_BC
           '|'||COALESCE(I.BDCODOBS, '')|| --COD_OBS
           '|'  
           )
  FROM (
        SELECT S.BDCODEMP, S.BDCHAVE
        FROM VEF_EMP_TMOVSAI S
        LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = S.BDCODEMP)
        WHERE S.BDCODEMP = :PRCODEMP
        AND S.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, S.BDCHAVE)
        AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND S.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800,63)
        AND S.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11) --Cancelado
       ) MOV
--  JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = I.BDCODCSTICMS)
  GROUP BY MOV.BDCODEMP,MOV.BDCHAVE,ICMS.BDCSTICMS,I.bdprefixonat,I.BDALIQICMS,I.BDCODOBS; /*Sped Fiscal - D190 duplicado #132552 - Tem que agrupar por CST,CFOP e Aliq de ICMS*/

  /*****************************************************************************
   *                                   D195                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
  SELECT :PRARQUIVO BDID,
         LPAD(D195.BDCODEMP, 6, '0')||'.1.'||LPAD(D195.BDCHAVE, 10, '0')||'.D100.D195.'||LPAD(D195.BDORDEMOBS, 10, '0'),
         'D195' BDREG,
         ('|D195'||
          '|'||COALESCE(OBS.BDCODEXP, '')|| --COD_OBS
          '|'||COALESCE(REPLACE(D195.BDDESCCOMPL, '|', ''), '')|| --TXT_COMPL
          '|'
         ), D195.BDCODOBS
  FROM (
        SELECT S.BDCODEMP, S.BDCHAVE
        FROM VEF_EMP_TMOVSAI S
        LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = S.BDCODEMP)
        WHERE S.BDCODEMP = :PRCODEMP
        AND S.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, S.BDCHAVE)
        AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND S.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800,63)
        AND S.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11) --Cancelado
       ) MOV
  JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TD195SAI D195 ON(D195.BDCODEMP = MOV.BDCODEMP AND D195.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TOBSERVACAO OBS ON(OBS.BDCODOBS = D195.BDCODOBS);

  /*****************************************************************************
   *                                   D197                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD)
  SELECT  :PRARQUIVO BDID,
          LPAD(D197.BDCODEMP, 6, '0')||'.1.'||LPAD(D197.BDCHAVE, 10, '0')||'.D100.D195.'||LPAD(D197.BDORDEMOBS, 10, '0')||'.D197.'||LPAD(D197.BDORDEMOUTOBR, 10, '0'),
          'D197' BDREG,
          ('|D197'||
           '|'||COALESCE(AJU.BDCODAJUPAD, '')|| --COD_AJ
           '|'||COALESCE(REPLACE(D197.BDDESCCOMPL, '|', ''), '')|| --DESCR_COMPL_AJ
           '|'||COALESCE(IIF(PRO.BDCODSAIDA <> '', PRO.BDCODSAIDA, PRO.BDCODPROD), '')|| --COD_ITEM
           '|'||COALESCE(REPLACE(D197.BDBICMS, '.', ','), '')|| --VL_BC_ICMS
           '|'||COALESCE(REPLACE(CAST(D197.BDALIQICMS AS DM_NUMERIC_15_2), '.', ','), '')|| --ALIQ_ICMS
           '|'||COALESCE(REPLACE(D197.BDVLRICMS, '.', ','), '')|| --VL_ICMS
           '|'||COALESCE(REPLACE(D197.BDOUTVLR, '.', ','), '')|| --VL_OUTROS
           '|'
           ), D197.BDCODPROD
  FROM (
        SELECT S.BDCODEMP, S.BDCHAVE
        FROM VEF_EMP_TMOVSAI S
        LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = S.BDCODEMP)
        WHERE S.BDCODEMP = :PRCODEMP
        AND S.BDCHAVE = IIF(SEG.BDCHAVE is not null AND :WSEGREGACAO = 'TRUE', seg.BDCHAVE, S.BDCHAVE)
        AND S.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND S.BDMODELO IN(7, 8, 9, 10, 11, 26, 27, 57, 67, 800,63)
        AND S.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11) --Cancelado
       ) MOV
  JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TD195SAI D195 ON(D195.BDCODEMP = MOV.BDCODEMP AND D195.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TD197SAI D197 ON(D197.BDCODEMP = D195.BDCODEMP AND D197.BDCHAVE = D195.BDCHAVE AND D197.BDORDEMOBS = D195.BDORDEMOBS)
  LEFT OUTER JOIN VEF_BASE_TTABCODAJU AJU ON(AJU.BDCODAJU = D197.BDCODAJU)
  LEFT OUTER JOIN TCADPRO_VINC PRO ON (PRO.BDCODEMP = D197.BDCODEMP AND PRO.BDCODPROD = D197.BDCODPROD);

  IF (:WEXP_REG_D300 = 'TRUE' ) THEN
     BEGIN
        /* Exporta registros D300 e Filhos*/
        EXECUTE PROCEDURE SP_EXPORTA_BLOCOD_SAI_D300(:prCODEMP, :prDTINI, :prDTFIM, :prARQUIVO, :prPERFIL, :prCODPLAPADRAOREF);
     END
  ELSE
     BEGIN
  /* Exporta registros do grupo D400 */
        EXECUTE PROCEDURE SP_EXPORTA_BLOCOD_SAI_D400(:prCODEMP, :prDTINI, :prDTFIM, :prARQUIVO, :prTIPOEXPCODPART, :prCODPLAPADRAOREF, :prPERFIL);
     END

END^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOD (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRCODPLAPADRAOREF integer,
    PRVALIDAREXPORTACAO DM_BOOLEAN,
    PRARQUIVO varchar(260))
as
declare variable WTIPOEXPCODPART integer;
declare variable WPERFILSPED integer;
declare variable WLINHA blob sub_type 1 segment size 200;
BEGIN

  SELECT VW.BDTIPOEXPCODPART
  FROM VW_INT_SPEDICMS_REF VW
  WHERE VW.BDCODEMP = :PRCODEMP
  INTO :wTipoExpCodPart;

  IF (ROW_COUNT = 0) THEN
    wTipoExpCodPart = -1; /*Não achou o TipoExpCodPart*/

  SELECT SP.BDPERFILSPED FROM SP_CONSULTAEMPRESAS_SIS((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')), :PRCODEMP, NULL) SP INTO :wPerfilSped;    

  wPerfilSped = COALESCE(:wPerfilSped, -1);  

  /*ENTRADA*/
  EXECUTE PROCEDURE SP_EXPORTA_BLOCOD_ENT(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, :wTipoExpCodPart, :prCODPLAPADRAOREF);

  /*SAIDA*/
  EXECUTE PROCEDURE SP_EXPORTA_BLOCOD_SAI(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, :wTipoExpCodPart, :prCODPLAPADRAOREF, :wPerfilSped);

  /*Cria as inconsistências*/
  IF (UPPER(:PRVALIDAREXPORTACAO) = 'TRUE') THEN
    EXECUTE PROCEDURE SP_VALIDA_EXPORTACAO_SPED(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, 'D100');  

  /*****************************************************************************
   *                           EXPORTANDO ARQUIVO                              *
   ****************************************************************************/

  OPENARQ(:PRARQUIVO,:PRCODEMP);

  FOR SELECT E.BDLINHA
      FROM TEXPORTACAO_SPED E
      WHERE E.BDID = :PRARQUIVO
      ORDER BY E.BDCHAVEREG
      INTO :wLinha
  DO
    BEGIN
      WRITELNOA(:wLinha,:PRCODEMP);
    END

  CLOSEARQ(:PRARQUIVO,:PRCODEMP);

END
^

CREATE OR ALTER TRIGGER trg_ins_inco_exp_sped FOR texportacao_sped_inco
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF ((NEW.BDORDEMINCO IS NULL) OR (NEW.BDORDEMINCO = 0)) THEN
    BEGIN
      NEW.BDORDEMINCO = GETORDEMSEQUENCIAL(0);
    END
END^

CREATE OR ALTER TRIGGER trg_bef_ins_tcontextodb FOR tcontexto_db
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN

  NEW.BDLINE = REPLACE(NEW.BDLINE, '''', '''''');
  NEW.BDLINE = REPLACE(NEW.BDLINE, '!@|NULL!@|', 'NULL');
  NEW.BDLINE = REPLACE(NEW.BDLINE, '!@|', '''');

END^

CREATE OR ALTER PROCEDURE SP_INSERE_HIERARQUIA_CTX (
    PRTABLE VARCHAR(50))
AS
DECLARE VARIABLE WTABLE VARCHAR(50);
DECLARE VARIABLE WTABLEDEP VARCHAR(50);
BEGIN
  IF ((:PRTABLE IS NULL) OR (PRTABLE = '')) THEN
    BEGIN
      /*Dependencias*/
      SELECT FIRST 1 D.BDTABELA_PRINC FROM TDEPENDENCIAS_CTX D INTO :wTable;

      IF (ROW_COUNT = 0) THEN
        BEGIN
          INSERT INTO TDEPENDENCIAS_CTX(BDTABELA_PRINC, BDTABELA_DEP)
          SELECT TRIM(RC.RDB$RELATION_NAME) BDTABLE_PRINCIPAL, TRIM(I.RDB$RELATION_NAME) BDTABLE_DEP
          FROM RDB$RELATION_CONSTRAINTS R
          LEFT OUTER JOIN RDB$INDICES I ON(I.RDB$INDEX_NAME = R.RDB$INDEX_NAME)
          JOIN RDB$RELATION_CONSTRAINTS RC ON(RC.RDB$INDEX_NAME = I.RDB$FOREIGN_KEY)
          GROUP BY BDTABLE_PRINCIPAL, BDTABLE_DEP;
        END

      /*Dependentes*/
      SELECT FIRST 1 D.BDTABELA_PRINC FROM TDEPENDENTES_CTX D INTO :wTable;
      IF (ROW_COUNT = 0) THEN
        BEGIN
          INSERT INTO TDEPENDENTES_CTX(BDTABELA_PRINC, BDTABELA_DEP)
          SELECT TRIM(RC.RDB$RELATION_NAME) BDTABLE_PRINC,
                 TRIM(I.RDB$RELATION_NAME) BDTABLE_DEPENDENTE
          FROM RDB$RELATION_CONSTRAINTS R
          LEFT OUTER JOIN RDB$INDICES I ON(I.RDB$INDEX_NAME = R.RDB$INDEX_NAME)
          JOIN RDB$RELATION_CONSTRAINTS RC ON(RC.RDB$INDEX_NAME = I.RDB$FOREIGN_KEY)
          GROUP BY BDTABLE_PRINC, BDTABLE_DEPENDENTE;
        END

      FOR /*SELECT TRIM(RDB$RELATION_NAME)
          FROM RDB$RELATIONS
          WHERE RDB$SYSTEM_FLAG = 0
          AND ((RDB$RELATION_NAME LIKE 'TMP_%_TEMP%') OR (RDB$RELATION_TYPE IN (4,5) AND RDB$RELATION_NAME LIKE 'TMP_%'))
          ORDER BY RDB$RELATION_TYPE DESC, RDB$RELATION_NAME*/
          SELECT BDTABLE
          FROM TTABELAS_A_EXPORTAR_CTX          
          INTO :wTable
      DO
        BEGIN
          /*1º - Tabelas que :wTable depende*/
          FOR SELECT D.BDTABELA_PRINC
              FROM TDEPENDENCIAS_CTX D
              WHERE D.BDTABELA_DEP = :wTable
              INTO :wTableDep
          DO
            EXECUTE PROCEDURE SP_INSERE_HIERARQUIA_CTX(:wTableDep);
    
          UPDATE OR INSERT INTO TMP_DEPENDENCIA_CONTEXTO(BDTABLENAME,bdCODEMP) VALUES(:wTable,0) MATCHING(BDTABLENAME); -- Alt.: #161158 - Inserido campo empresa...

          /*2º - Tabelas que dependem de :wTable*/
          FOR SELECT D.BDTABELA_DEP
              FROM TDEPENDENTES_CTX D
              WHERE D.BDTABELA_PRINC = :wTableDep
              INTO :wTableDep
          DO
            EXECUTE PROCEDURE SP_INSERE_HIERARQUIA_CTX(:wTableDep);
        END

      DELETE FROM TDEPENDENCIAS_CTX WHERE BDTABELA_PRINC IS NOT NULL;
      DELETE FROM TDEPENDENTES_CTX WHERE BDTABELA_PRINC IS NOT NULL;
    END
  ELSE
    BEGIN
      /*1º - Tabelas que :PRTABLE depende*/
      FOR SELECT D.BDTABELA_PRINC
          FROM TDEPENDENCIAS_CTX D
          LEFT OUTER JOIN TMP_DEPENDENCIA_CONTEXTO DEP ON(DEP.BDTABLENAME = D.BDTABELA_PRINC)
          WHERE D.BDTABELA_DEP = :PRTABLE
          AND DEP.BDORD IS NULL
          INTO :wTableDep
      DO
        EXECUTE PROCEDURE SP_INSERE_HIERARQUIA_CTX(:wTableDep);
    
      UPDATE OR INSERT INTO TMP_DEPENDENCIA_CONTEXTO(BDTABLENAME,bdCODEMP) VALUES(:PRTABLE,0) MATCHING(BDTABLENAME); -- Alt.: #161158 - Inserido campo empresa...

      /*2º - Tabelas que dependem de :PRTABLE*/
      FOR SELECT D.BDTABELA_DEP
          FROM TDEPENDENTES_CTX D
          LEFT OUTER JOIN TMP_DEPENDENCIA_CONTEXTO DEP ON(DEP.BDTABLENAME = D.BDTABELA_PRINC)
          WHERE D.BDTABELA_PRINC = :PRTABLE
          AND DEP.BDORD IS NULL
          INTO :wTableDep
      DO
        EXECUTE PROCEDURE SP_INSERE_HIERARQUIA_CTX(:wTableDep);
    END
END
^

CREATE OR ALTER procedure SP_EXPORTA_CONTEXTODB (
    PRFILE varchar(1000))
as
declare variable WTABLE varchar(50);
declare variable WCOMMAND varchar(10000);
declare variable WFIELDS varchar(10000);
declare variable WFIELDSSTR varchar(10000);
declare variable WSQL varchar(10000);
declare variable WFIELD varchar(64);
declare variable WTYPECOLUMN integer;
BEGIN
  EXECUTE PROCEDURE SP_INSERE_HIERARQUIA_CTX(NULL);

  FOR SELECT DEP.BDTABLENAME
      FROM TMP_DEPENDENCIA_CONTEXTO DEP
      ORDER BY BDORD
      INTO :wTable
  DO
    BEGIN
      wField      = '';
      wFields     = '';
      wFieldsStr  = '';
      wCommand    = '';
      wSQL        = '';
      wTypeColumn = 0;

      INSERT INTO TCONTEXTO_DB(BDLINE,bdCODEMP) VALUES('DELETE FROM '||:wTable||';',0); -- Alt.: #161158 - Inserido campo empresa...

      wCommand = '''INSERT INTO '||:wTable||'(';

      FOR SELECT TRIM(RF.RDB$FIELD_NAME), F.RDB$FIELD_TYPE
          FROM RDB$RELATION_FIELDS RF
          JOIN RDB$FIELDS F ON(F.RDB$FIELD_NAME = RF.RDB$FIELD_SOURCE)
          WHERE RDB$RELATION_NAME = :wTable
          INTO :wField, :wTypeColumn
      DO
        BEGIN
          wFields = wFields || :wField || ', ';

          /*7, 8, 9, 10, 16, 27 são campos numérios*/
          IF (:wTypeColumn NOT IN(7, 8, 9, 10, 16, 27)) THEN
            wFieldsStr = :wFieldsStr || '''!@|''||'||'IIF('||:wField||' IS NULL, ''NULL'', '||:wField||')'||'||''!@|''';
          ELSE
            wFieldsStr = :wFieldsStr ||'IIF('||:wField||' IS NULL, ''NULL'', '||:wField||')';

          wFieldsStr = :wFieldsStr || '|| '', '' ||';
        END

      wFields    = (SUBSTRING(:wFields FROM 1 FOR CHAR_LENGTH(:wFields)-2));
      wFieldsStr = (SUBSTRING(:wFieldsStr FROM 1 FOR CHAR_LENGTH(:wFieldsStr)-10));

      wCommand = :wCommand || :wFields || ') VALUES ('' || ' || :wFieldsStr ||' || '');''';

      wSQL = 'INSERT INTO TCONTEXTO_DB(BDLINE,bdCODEMP) SELECT '|| :wCommand ||',0 FROM '||:wTable; -- Alt.: #161158 - Inserido campo empresa...

      EXECUTE STATEMENT :wSQL;
    END

  NEWFILE(:PRFILE);
  OPENARQ(:PRFILE,0);

  wCommand = '';
  FOR SELECT BDLINE FROM TCONTEXTO_DB INTO :wCommand DO
    BEGIN
      WRITELNOA(:wCommand,0);
    END

  CLOSEARQ(:PRFILE,0);

  DELETE FROM TCONTEXTO_DB;
  DELETE FROM TMP_DEPENDENCIA_CONTEXTO WHERE BDORD IS NOT NULL;
END
^
create or alter procedure SP_RET_REF_1010_1020_EXPORT (
    PRCODEMP varchar(2000),
    PRSAIDA varchar(5),
    PRDATAINI date,
    PRDATAFIM date,
    PRREG varchar(4))
returns (
    BDORDEMINDORIG integer,
    BDNUMPROC varchar(20),
    BDCHAVE integer,
    BDCODEMP integer,
    BDMOVIMENTO integer,
    BDREF integer,
    BDDATAINI date,
    BDDATAFIM date)
as
declare variable WTABLE varchar(30);
declare variable WMOVIMENTO varchar(20);
declare variable WSQLAUX varchar(10000);
declare variable WSQL varchar(10000);
declare variable WEMPRESAATUAL varchar(8);
declare variable WCAMPODATA varchar(50);
declare variable WSELECIONADA varchar(5);
declare variable WCHAVE integer;
declare variable WCODEQ integer;
begin
  if (:PRREG = 'A111') then
  begin
    WMOVIMENTO = '2,3';
  end

  if ((:PRREG = 'C489') or (:PRREG = 'D359')) then
  begin
    WMOVIMENTO = '4';
  end

  if ((:PRREG = 'C509') or (:PRREG = 'D111') or (:PRREG = 'D509')) then
  begin
    WMOVIMENTO = '0';
  end

  if ((:PRREG = 'C609') or (:PRREG = 'C309') or (:PRREG = 'C890') or (:prreg = 'D609')) then
  begin
    WMOVIMENTO = '1';
  end

  if (:PRREG = 'F111') then
  begin
    WMOVIMENTO = '5,6';
  end

  if (:PRREG = 'ALL') then
  begin
    WMOVIMENTO = '0,1,2,3,4,5,6';
  end

  if (:PRREG = 'D309') then
  begin
    WMOVIMENTO = '0,1';
  end

  WSQLAUX = ' SELECT MOV.BDCODEMP, MOV.BDNOTASE, MOV.BDMOVIMENTO, ';
  WSQLAUX = WSQLAUX || ' CASE MOV.BDMOVIMENTO                         ';
  WSQLAUX = WSQLAUX || '   WHEN 0 THEN ''VEF_EMP_TMOVENT''            ';
  WSQLAUX = WSQLAUX || '   WHEN 1 THEN ''VEF_EMP_TMOVSAI''            ';
  WSQLAUX = WSQLAUX || '   WHEN 2 THEN ''VEF_EMP_TMOVSER''            ';
  WSQLAUX = WSQLAUX || '   WHEN 3 THEN ''VEF_EMP_TMOVSER''            ';
  WSQLAUX = WSQLAUX || '   WHEN 4 THEN ''VEF_EMP_TREDZ''              ';
  WSQLAUX = WSQLAUX || '   WHEN 5 THEN ''VEF_EMP_TMOVDEMAISDOC_F100'' ';
  WSQLAUX = WSQLAUX || '   WHEN 6 THEN ''VEF_EMP_TMOVDEMAISDOC_F100'' ';
  WSQLAUX = WSQLAUX || ' END AS BDTABLE,';
  WSQLAUX = WSQLAUX || ' CASE MOV.BDMOVIMENTO';
  WSQLAUX = WSQLAUX || '   WHEN 0 THEN ''BDDATAENTRADAENT''';
  WSQLAUX = WSQLAUX || '   WHEN 1 THEN ''BDDATASAIDA''     ';
  WSQLAUX = WSQLAUX || '   WHEN 2 THEN ''BDDATAEMISSAO''   ';
  WSQLAUX = WSQLAUX || '   WHEN 3 THEN ''BDDATAEMISSAO''   ';
  WSQLAUX = WSQLAUX || '   WHEN 4 THEN ''BDDATAREDZ''      ';
  WSQLAUX = WSQLAUX || '   WHEN 5 THEN ''BDDT_OPER''       ';
  WSQLAUX = WSQLAUX || '   WHEN 6 THEN ''BDDT_OPER''       ';
  WSQLAUX = WSQLAUX || ' END AS BDCAMPODATA,  MOV.BDCHAVE, MOV.BDCODEQUIPSAT ';
  WSQLAUX = WSQLAUX || '          FROM VEF_EMP_TPROCREFC890 MOV ';             
  if (Coalesce(:PRCODEMP,'') = '') then                                    
    WSQLAUX = WSQLAUX || ' INNER JOIN TMP_EMPRESAS_SELECT ON (TMP_EMPRESAS_SELECT.BDCODEMP = MOV.BDCODEMP) ';

  WSQLAUX = WSQLAUX || '          WHERE  MOV.BDMOVIMENTO IN (' || WMOVIMENTO || ') AND ';
  if (:PRCODEMP <> '') then
    WSQLAUX = WSQLAUX || :PRCODEMP;
  WSQLAUX = WSQLAUX || '                (MOV.BDDTINIVIG <= ''' || :PRDATAINI || ''' OR (MOV.BDDTINIVIG BETWEEN ''' || :PRDATAINI || ''' AND ''' || :PRDATAFIM || ''')) AND';
  WSQLAUX = WSQLAUX || '               ((MOV.BDDTFINVIG is null) or ((MOV.BDDTFINVIG >= ''' || :PRDATAFIM || ''') or (mov.bddtfinvig between ''' || :PRDATAINI || ''' and ''' || :PRDATAFIM || ''')))';

  for execute statement WSQLAUX
          into :WEMPRESAATUAL, WSELECIONADA, WMOVIMENTO, WTABLE, WCAMPODATA, WCHAVE, WCODEQ
  do
  begin
    if ((WSELECIONADA = 'FALSE') or ((:PRREG = 'C890') AND (WSELECIONADA IS NULL))) then
    begin
      WSQL = ' SELECT C890.BDCODEMP, MOV.BDCHAVE, ORI.BDINDORIG, C890.BDNUMPROC, C890.BDMOVIMENTO, C890.BDCHAVE AS BDREF, C890.BDDTINIVIG, C890.BDDTFINVIG ';
      WSQL = WSQL || ' FROM (SELECT *  ';
      WSQL = WSQL || '       FROM ' || WTABLE || ' M ';
      WSQL = WSQL || '       WHERE M.BDCODEMP = ' || WEMPRESAATUAL || ' AND ';
      WSQL = WSQL || '             M.' || WCAMPODATA || ' BETWEEN ''' || :PRDATAINI || ''' AND ''' || :PRDATAFIM || ''' ';
      if (:PRREG = 'C890') then
      begin
        WSQL = WSQL || '     AND M.BDMODELO = 59';
      end
      if (:PRREG = 'D309') then
      begin
        WSQL = WSQL || '     AND M.BDMODELO in (13,14,15,16,18)';
      end
      WSQL = WSQL || ') MOV ';
      WSQL = WSQL || ' JOIN VEF_EMP_TPROCREFC890 C890 ON (C890.BDCODEMP = MOV.BDCODEMP AND ';
      WSQL = WSQL || '       C890.BDCHAVE = (SELECT FIRST 1 C.BDCHAVE ';
      WSQL = WSQL || '                       FROM VEF_EMP_TPROCREFC890 C ';
      WSQL = WSQL || '                       WHERE C.BDCODEMP = MOV.BDCODEMP AND';
      WSQL = WSQL || '                       c.bdchave = ' || WCHAVE || ' and';
      WSQL = WSQL || '                             C.BDDTINIVIG <= MOV.' || WCAMPODATA || ' AND ';
      WSQL = WSQL || '                             C.BDMOVIMENTO = ' || WMOVIMENTO || ' AND ';
      WSQL = WSQL || '                             ((C.BDDTFINVIG IS NULL) OR (C.BDDTFINVIG >= MOV.' || WCAMPODATA || ')) ';
      if ((:PRREG = 'C890') and (WCODEQ IS NOT NULL)) then
      begin
        WSQL = WSQL || '                            AND C.BDCODEQUIPSAT = MOV.BDCODEQUIPSAT';
      end
      WSQL = WSQL || '                       ORDER BY C.BDDTINIVIG)) ';
      WSQL = WSQL || ' INNER JOIN VEF_BASE_TTABINDORIG ORI ON (C890.BDORDEMINDORIG = ORI.BDORDEMINDORIG)';
      if (:PRREG = 'A111') then
      begin
        WSQL = WSQL || ' WHERE MOV.BDTIPLAN = IIF(' || WMOVIMENTO || ' = 2, 1, 0) ';
      end
      if ((WTABLE = 'VEF_EMP_TMOVENT') or (WTABLE = 'VEF_EMP_TMOVSAI')) then
      begin
        WSQL = WSQL || ' WHERE ((C890.BDMODELO IS NULL) OR (MOV.BDMODELO = C890.BDMODELO)) ';
      end
      if (:PRREG = 'F111') then
      begin
        WSQL = WSQL || ' WHERE (IIF(C890.BDMOVIMENTO = 5, MOV.BDIND_OPER = 1, MOV.BDIND_OPER IN (2,3))) ';
      end
    end
    if (WSELECIONADA = 'TRUE') then
    begin
      WSQL = ' select LAN.BDCODEMP, RE.BDCHAVELAN, ORI.BDINDORIG, LAN.BDNUMPROC, LAN.BDMOVIMENTO, LAN.BDCHAVE as BDREF,';
      WSQL = WSQL || '        LAN.BDDTINIVIG, LAN.BDDTFINVIG';
      WSQL = WSQL || ' from (select *';
      WSQL = WSQL || '       from VEF_EMP_TPROCREFC890';
      WSQL = WSQL || '       where BDCODEMP = ' || WEMPRESAATUAL || ') LAN';
      WSQL = WSQL || ' LEFT OUTER JOIN VEF_BASE_TPROCREF RE ON (RE.BDCODEMP = LAN.BDCODEMP AND RE.BDCHAVE = LAN.BDCHAVE)';
      WSQL = WSQL || ' INNER JOIN VEF_BASE_TTABINDORIG ORI ON (LAN.BDORDEMINDORIG = ORI.BDORDEMINDORIG)';
      WSQL = WSQL || ' where RE.BDMOVIMENTO in (' || WMOVIMENTO || ') and';
      WSQL = WSQL || '       RE.BDCHAVE = ' || WCHAVE || ' and';
      WSQL = WSQL || '       RE.BDCHAVELAN = (select FIL.BDCHAVE';
      WSQL = WSQL || '                        from ' || WTABLE || ' FIL';
      WSQL = WSQL || '                        where FIL.BDCODEMP = ' || WEMPRESAATUAL || ' and';
      WSQL = WSQL || '                              FIL.BDCHAVE = RE.BDCHAVELAN and';
      WSQL = WSQL || '                              FIL.' || WCAMPODATA || ' between ''' || :PRDATAINI || ''' and ''' || :PRDATAFIM || ''')';
    end
    for execute statement WSQL
            into :BDCODEMP, :BDCHAVE, :BDORDEMINDORIG, :BDNUMPROC, :BDMOVIMENTO, :BDREF, :BDDATAINI, :BDDATAFIM
    do
      suspend;
  end
end^

SET TERM ; ^

--21893 - ELIZEU - ControlMemory traz desordenado, e partimos pra views com variáveis de sessão "USER_SESSION"
CREATE OR ALTER VIEW VW_EXP_SPED_CONTRIBUICOES_ENT(
    BDCHAVESL,
    BDCODMATRIZ,
    BDCODEMP,
    BDCNPJEMP,
    BDCHAVE,
    BDEMITENTE,
    BDMODELO,
    BDIND_OPER,
    BDMODELOSTR,
    BDCODSITNF,
    BDESPECIE,
    BDSERIE,
    BDSUBSERIE,
    BDNUMDOCINI,
    BDNUMDOCFIM,
    BDCHAVENFE,
    BDDATAEMISSAO,
    BDDATAENTRADAENT,
    BDVALORNOTA,
    BDCONDPGTO,
    BDINDFRETE,
    BDVLRFRETE,
    BDVLRSEGURO,
    BDVLROUTDESP,
    BDCODNAT,
    BDVLRCONTAB,
    BDBASEICMS,
    BDVLRICMS,
    BDBASEST,
    BDVLRST,
    BDORDEM,
    BDVLRIPI,
    BDVLRIPIPROD,
    BDCODPROD,
    BDCODCSTICMS,
    BDCODCSTIPI,
    BDCODFATCON,
    BDMOVFISICO,
    BDQTDITEM,
    BDVLRITEM,
    BDVLRDESC,
    BDVLRDESPACESSORIA,
    BDREDBCICMS,
    BDBCICMS,
    BDBCPIS,
    BDBCST,
    BDBCIPI,
    BDBCCOFINS,
    BDBCISSQN,
    BDALIQICMS,
    BDALIQPIS,
    BDALIQST,
    BDALIQIPI,
    BDALIQCOFINS,
    BDALIQISSQN,
    BDVLRPISPROD,
    BDVLRCOFINSPROD,
    BDVLRISSQN,
    BDVLRFRETEPROD,
    BDORDEMPRO,
    BDDEBITOREF,
    BDDEBITOPLAPADRAOREF,
    BDDEBITO,
    BDCODPLAPADRAO,
    BDANODEBITO,
    BDVLRTOTPISPROD,
    BDVLRTOTCOFINSPROD,
    BDQTDEPROD,
    BDVLRSTPROD,
    BDVLRTOTPIS,
    BDVLRTOTCOFINS,
    BDVLRABATNT,
    BDVLRTOTPISST,
    BDVLRTOTCOFINSST,
    BDDESCONTO,
    BDNAT_BC_CREDC500,
    BDCODINFCOM,
    BDDESCINFCOM,
    BDCSTCOFC500,
    BDCSTPISC500,
    BDISENTASICMS,
    BDOUTRASICMS,
    BDCODTER,
    BDCGCTER,
    BDAPELIDOTER,
    BDNOMETER,
    BDLOGRTER,
    BDENDTER,
    BDNUMTER,
    BDCOMPTER,
    BDCEPTER,
    BDBAITER,
    BDDDDTER,
    BDFONETER,
    BDFAXTER,
    BDEMAILTER,
    BDIETER,
    BDDATACADTER,
    BDIMTER,
    BDPRURALTER,
    BDENQSIMPLESFEDTER,
    BDINSCSUFRAMATER,
    BDCODGPS,
    BDCODCID,
    BDCODPAIS,
    BDDDDFAXTER,
    BDNOMCID,
    BDSIGLAUF,
    BDCODSPED,
    BDTIPOCTE,
    BDCHAVECTEREF,
    BDCODINFCOMD100,
    BDDESCINFCOMD100,
    BDCSTCOFD100,
    BDCSTPISD100,
    BDNAT_BC_CRED,
    BDINDFRETED100,
    BDCODEXPNATF,
    BDVLRPISD100,
    BDVLRCOFINSD100,
    BDVL_BC_PISD100,
    BDALIQ_PISD100,
    BDVL_BC_COFD100,
    BDALIQ_COFD100,
    BDVLRSERD500,
    BDVLRSERNTRIBD500,
    BDVLRCOBTERCD500,
    BDVLROUTDESPD500,
    BDVLRPISD500,
    BDVLRCOFINSD500,
    BDCSTPISD500,
    BDNAT_BC_CREDD500,
    BDVL_BC_PISD500,
    BDALIQ_PISD500,
    BDCSTCOFD500,
    BDVL_BC_COFD500,
    BDALIQ_COFD500,
    BDCODINFCOMD500,
    BDDESCINFCOMD500,
    BDCODTENSAO,
    BDORDEMINFCOM,
    BDORDEMCONS,
    BDVLRCONSFOR,
    BDVLRCOBTER,
    BDVLRDESPACE,
    BDVLRPIS,
    BDVLRCOFINS,
    BDTIPOLIGACAO,
    BDCODCSTPISC500,
    BDVL_BC_PIS,
    BDALIQ_PIS,
    BDVL_PIS,
    BDCODCSTCOFC500,
    BDVL_BC_COF,
    BDALIQ_COF,
    BDVL_COF,
    BDCODNATBC,
    BDCODPAISTER,
    BDCODCTA,
    BDNATBC,
    BDDESCONTONOTA,
    BDCODCSTPIS,
    BDCODCSTCOF,
    BDVLRICMSPROD,
    BDCSTICMS,
    BDDESCUNIMED,
    BDAPEUNIMED,
    BDCODEXPCSTIPI,
    BDCODSAIDA,
    BDDESCPROD,
    BDAPEPROD,
    BDCODUNIMED,
    BDNCMPROD,
    BDGRUPO,
    BDCODCSTIPIENT,
    BDCODCSTCOFENT,
    BDCODCSTPISENT,
    BDCODCSTPISSAI,
    BDCODCSTCOFSAI,
    BDCODCSTIPISAI,
    BDCODTABINCID,
    BDORDEMMARCA,
    BDALIQICMSST,
    BDALIQPISENT,
    BDALIQCOF,
    BDALIQCOFENT,
    BDCAPVOL,
    BDINATIVO,
    BDCODTIPO,
    BDCODTIPOSER,
    BDCODGEN,
    BDCODSER,
    BDCODCOMBANP,
    BDCODTIPI,
    BDCODCEST,
    BDCTALON,
    BDCSTPIS,
    BDCSTCOF,
    BDANOEMISSAO,
    BDCODTPLA,
    BDVLRICMSORI,
    BDBCICMSORI)
AS
SELECT
       (MOV.BDCHAVE || ' - ' || MOV.BDORDEM || ' - ' || MOV.BDORDEMPRO) BDCHAVESL, 
       coalesce(mov.BDCODEMPSCP, MOV.BDCODMATRIZ), coalesce(mov.BDCODEMPSCP, MOV.BDCODEMP), MOV.BDCNPJEMP,
       MOV.BDCHAVE, MOV.BDEMITENTE, MOV.BDMODELO, 0 BDIND_OPER, MODLAN.BDMODELOSTR, 
       MOV.BDCODSITNF, MOV.BDESPECIE, MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDNUMDOCINI, 
       MOV.BDNUMDOCFIM, MOV.BDCHAVENFE, MOV.BDDATAEMISSAO, MOV.BDDATAENTRADAENT, 
       MOV.BDVALORNOTA, MOV.BDCONDPGTO, TABIFC100.BDCODEXPFRETE BDINDFRETE, 
       C100.BDVLRFRETE, C100.BDVLRSEGURO, C100.BDVLROUTDESP, MOV.BDCODNAT, 
       MOV.BDVLRCONTAB, MOV.BDBASEICMS, MOV.BDVLRICMS, MOV.BDBASEST, MOV.BDVLRST, 
       MOV.BDORDEM, MOV.BDVLRIPI, MOV.BDVLRIPIPROD, MOV.BDCODPROD, MOV.BDCODCSTICMS, MOV.BDCODCSTIPI, 
       MOV.BDCODFATCON, MOV.BDMOVFISICO, MOV.BDQTDITEM, MOV.BDVLRITEM,
       MOV.BDVLRDESC, MOV.BDVLRDESPACESSORIA, MOV.BDREDBCICMS, MOV.BDBCICMS, MOV.BDBCPIS, 
       MOV.BDBCST, MOV.BDBCIPI, MOV.BDBCCOFINS, MOV.BDBCISSQN, MOV.BDALIQICMS, MOV.BDALIQPIS, 
       MOV.BDALIQST, MOV.BDALIQIPI, MOV.BDALIQCOFINS, MOV.BDALIQISSQN, MOV.BDVLRPISPROD, 
       MOV.BDVLRCOFINSPROD, MOV.BDVLRISSQN, MOV.BDVLRFRETEPROD, MOV.BDORDEMPRO, 
       MOV.BDDEBITOREF, MOV.BDDEBITOPLAPADRAOREF, MOV.BDDEBITO, 
       MOV.BDCODPLAPADRAO, MOV.BDANODEBITO, 
       MOV.BDVLRTOTPISPROD, MOV.BDVLRTOTCOFINSPROD, MOV.BDQTDEPROD, MOV.BDVLRSTPROD, C100.BDVLRTOTPIS,
       C100.BDVLRTOTCOFINS, C100.BDVLRABATNT, C100.BDVLRTOTPISST, C100.BDVLRTOTCOFINSST, 
       MOV.BDDESCONTO, NATBCC500.BDREGEXP BDNAT_BC_CREDC500, CADINF.BDCODINFCOM, CADINF.BDDESCINFCOM, 
       CSTCOFC500.BDCSTCOF BDCSTCOFC500, CSTPISC500.BDCSTPIS BDCSTPISC500, MOV.BDISENTASICMS, 
       MOV.BDOUTRASICMS, MOV.BDCODTER, MOV.BDCGCTER, MOV.BDAPELIDOTER, MOV.BDNOMETER, 
       MOV.BDLOGRTER, MOV.BDENDTER, MOV.BDNUMTER, MOV.BDCOMPTER, MOV.BDCEPTER, MOV.BDBAITER, 
       MOV.BDDDDTER, MOV.BDFONETER, MOV.BDFAXTER, MOV.BDEMAILTER, MOV.BDIETER, MOV.BDDATACADTER, 
       MOV.BDIMTER, MOV.BDPRURALTER, MOV.BDENQSIMPLESFEDTER, MOV.BDINSCSUFRAMATER, MOV.BDCODGPS, 
       MOV.BDCODCID, MOV.BDCODPAIS, MOV.BDDDDFAXTER, MOV.BDNOMCID, MOV.BDSIGLAUF, MOV.BDCODSPED, 
       D100.BDTIPOCTE, D100.BDCHAVECTEREF, CADINFD100.BDCODINFCOM BDCODINFCOMD100, 
       CADINFD100.BDDESCINFCOM BDDESCINFCOMd100, CSTCOFD100.BDCSTCOF BDCSTCOFD100, 
       CSTPISD100.BDCSTPIS BDCSTPISD100, NATBC.BDREGEXP BDNAT_BC_CRED, TABIFD100.BDCODEXPFRETE BDINDFRETED100, 
       NATFRETE.BDCODEXPNATF, ((D100.BDVLRPIS*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRPISD100,
       ((D100.BDVLRCOFINS*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRCOFINSD100,
       ((D100.BDVL_BC_PIS*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVL_BC_PISD100,
       D100.BDALIQ_PIS BDALIQ_PISD100, ((D100.BDVL_BC_COF*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVL_BC_COFD100,
       D100.BDALIQ_COF BDALIQ_COFD100, ((D500.BDVLRSER*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRSERD500,
       ((D500.BDVLRSERNTRIB*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRSERNTRIBD500,
       D500.BDVLRCOBTERC BDVLRCOBTERCD500, D500.BDVLROUTDESP BDVLROUTDESPD500,
       ((D500.BDVLRPIS)) BDVLRPISD500, --Matheus Amaral - Sped Contribuições - D500 mais de uma CFOP #152298
       ((D500.BDVLRCOFINS)) BDVLRCOFINSD500, --Matheus Amaral - Sped Contribuições - D500 mais de uma CFOP #152298
       CSTPISD500.BDCSTPIS BDCSTPISD500, NATBCD500.BDREGEXP BDNAT_BC_CREDD500,
       ((D500.BDVL_BC_PIS)) BDVL_BC_PISD500, --Matheus Amaral - Sped Contribuições - D500 mais de uma CFOP #152298
         D500.BDALIQ_PIS BDALIQ_PISD500, CSTCOFD500.BDCSTCOF BDCSTCOFD500,
       ((D500.BDVL_BC_COF)) BDVL_BC_COFD500, --Matheus Amaral - Sped Contribuições - D500 mais de uma CFOP #152298
         D500.BDALIQ_COF BDALIQ_COFD500, CADINFD500.BDCODINFCOM BDCODINFCOMD500,
       CADINFD500.BDDESCINFCOM BDDESCINFCOMD500, C500.BDCODTENSAO, C500.BDORDEMINFCOM, C500.BDORDEMCONS, 
       C500.BDVLRCONSFOR, C500.BDVLRCOBTER, C500.BDVLRDESPACE, COALESCE(C500.BDVLRPIS, 0) BDVLRPIS,
       COALESCE(C500.BDVLRCOFINS, 0) BDVLRCOFINS, C500.BDTIPOLIGACAO,C500.BDCODCSTPIS BDCODCSTPISC500,
       COALESCE(C500.BDVL_BC_PIS, 0) BDVL_BC_PIS, C500.BDALIQ_PIS, --Larissa - 06/05/2021 - Alterado o campo BDVL_BC_PIS, BDVL_BC_COF, BDVLRPIS e BDVLRCOFINS - Sped Contribuições - C500 mais de uma CFOP #149987
       ((C500.BDVL_PIS*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVL_PIS, C500.BDCODCSTCOF BDCODCSTCOFC500,
       COALESCE(C500.BDVL_BC_COF,0) BDVL_BC_COF, C500.BDALIQ_COF,
       ((C500.BDVL_COF*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVL_COF, C500.BDCODNATBC, MOV.BDCODPAIS BDCODPAISTER, MOV.BDCODCTA,
       CRED.BDREGEXP BDNATBC, MOV.BDDESCONTONOTA, MOV.BDCODCSTPIS, MOV.BDCODCSTCOF,  MOV.BDVLRICMSPROD, 
       CSTICMS.BDCSTICMS, UM.BDDESCUNIMED, UM.BDAPEUNIMED, CSTIPI.BDCODEXPCSTIPI, PRO.BDCODSAIDA, PRO.BDDESCPROD, 
       PRO.BDAPEPROD, PRO.BDCODUNIMED, PRO.BDNCMPROD, PRO.BDGRUPO, PRO.BDCODCSTIPIENT, PRO.BDCODCSTCOFENT, PRO.BDCODCSTPISENT, 
       PRO.BDCODCSTPISSAI, PRO.BDCODCSTCOFSAI, PRO.BDCODCSTIPISAI, PRO.BDCODTABINCID, PRO.BDORDEMMARCA, PRO.BDALIQICMSST, 
       PRO.BDALIQPISENT, PRO.BDALIQCOF, PRO.BDALIQCOFENT, PRO.BDCAPVOL, PRO.BDINATIVO, PRO.BDCODTIPO, PRO.BDCODTIPOSER, 
       PRO.BDCODGEN, PRO.BDCODSER, PRO.BDCODCOMBANP, PRO.BDCODTIPI, PRO.BDCODCEST, MOV.BDCTALON, CSTPIS.BDCSTPIS,
       CSTCOF.BDCSTCOF, EXTRACT(YEAR FROM MOV.BDDATAENTRADAENT) BDANOEMISSAO, MOV.BDCODTPLA, CAST(IIF(((mov.BDVLRITEM = 0) AND (SUMM.BDBCICMS = 0)), 0, (mov.BDVLRITEM / SUMM.BDBCICMS)) * ORI.BDVLRICMS AS DM_NUMERIC_15_2) as BDVLRICMSORI, 0 as BDBCICMSORI
FROM ( 
      SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM, P.BDORDEMPRO, I.BDMODELO, P.BDCODNATBC,
             I.BDNUMDOCINI, I.BDCODMATRIZ, I.BDCNPJEMP, I.BDEMITENTE, I.BDCODSITNF, 
             I.BDESPECIE, I.BDSERIE, I.BDSUBSERIE, I.BDNUMDOCFIM, I.BDCHAVENFE, 
             I.BDDATAEMISSAO, I.BDDATAENTRADAENT, I.BDVALORNOTA, I.BDCONDPGTO, 
             I.BDCODNAT, I.BDVLRCONTAB, I.BDBASEICMS, I.BDVLRICMS, I.BDBASEST, 
             I.BDVLRST, I.BDVLRIPI, P.BDCODPROD, P.BDCODCSTICMS, P.BDCODCSTIPI, 
             P.BDCODFATCON, P.BDMOVFISICO, P.BDQTDITEM, P.BDVLRITEM,
             P.BDVLRDESC, P.BDVLRDESPACESSORIA, P.BDREDBCICMS, P.BDBCICMS, P.BDBCPIS, 
             P.BDBCST, P.BDBCIPI, P.BDBCCOFINS, P.BDBCISSQN, P.BDALIQICMS, P.BDALIQPIS, 
             P.BDALIQST, P.BDALIQIPI, P.BDALIQCOFINS, P.BDALIQISSQN, P.BDVLRPIS BDVLRPISPROD, 
             P.BDVLRCOFINS BDVLRCOFINSPROD, P.BDVLRISSQN, P.BDVLRFRETE BDVLRFRETEPROD, 
             
             COALESCE(P.BDCODPLAPADRAO, IIF((d100.bdCODCTA IS NOT NULL OR c500.bdCODTPLA IS NOT NULL OR d500.bdCODCTA IS NOT NULL), ref.bdCODPLAPADRAO, NULL), COALESCE(LAN.BDCODPLAPADRAO, LANRAT.BDCODPLAPADRAO), ref.bdCODPLAPADRAO) BDCODPLAPADRAO,
             COALESCE(cdlep.bdcodtplaref, cdleprat.bdcodtplaref) BDDEBITOREF, 
             COALESCE(cdl.bdCODTPLA,d100.bdCODCTA,d500.bdCODCTA,c500.bdCODTPLA,cdlrat.bdCODTPLA) AS BDDEBITO,
             COALESCE(COALESCE(cdle.bdano, cdlerat.bdano), CAST(SUBSTRING(I.bdreflan FROM 1 FOR 4) AS INTEGER)) BDANODEBITO, 
             COALESCE(CDLEP.BDCODPLAPADRAOREF, CDLEPRAT.BDCODPLAPADRAOREF) BDDEBITOPLAPADRAOREF, 
             (SELECT SUM(CAST(movpro.BDVLRPIS AS NUMERIC(15,2))) BDVLRTOTPISPROD 
             FROM vef_emp_tmovproent movpro 
             WHERE (i.bdcodemp = movpro.bdcodemp AND i.bdchave = movpro.bdchave)) BDVLRTOTPISPROD, 
             (SELECT SUM(CAST(movpro.BDVLRCOFINS AS NUMERIC(15,2))) BDVLRTOTCOFINSRTOTPIS 
              FROM vef_emp_tmovproent movpro 
              WHERE (i.bdcodemp = movpro.bdcodemp AND i.bdchave = movpro.bdchave)) BDVLRTOTCOFINSPROD, 
             (SELECT COUNT(movpro.bdCHAVE) BDQTDEPROD 
              FROM vef_emp_tmovproent movpro 
              WHERE (i.bdcodemp = movpro.bdcodemp AND i.bdchave = movpro.bdchave)) BDQTDEPROD,
              P.BDVLRST BDVLRSTPROD, P.BDVLRIPI BDVLRIPIPROD,
             I.BDDESCONTO, 
             I.BDISENTASICMS, I.BDOUTRASICMS, I.BDCODTER, I.BDCGCTER, I.BDREFEMP, I.BDAPELIDOTER, 
             I.BDNOMETER, I.BDLOGRTER, I.BDENDTER, I.BDNUMTER, I.BDCOMPTER, I.BDCEPTER, I.BDBAITER, 
             I.BDDDDTER, I.BDFONETER, I.BDFAXTER, I.BDEMAILTER, I.BDIETER, I.BDDATACADTER, I.BDIMTER, 
             I.BDPRURALTER, I.BDENQSIMPLESFEDTER, I.BDINSCSUFRAMATER, I.BDCODGPS, I.BDCODCID, I.BDCODPAIS, 
             I.BDDDDFAXTER, I.BDNOMCID, I.BDSIGLAUF, I.BDCODSPED, P.BDCODCTA, I.BDDESCONTONOTA, P.BDCODCSTPIS, 
             P.BDCODCSTCOF, P.BDVLRICMS BDVLRICMSPROD, COALESCE(CDL.BDCTALON, CDLRAT.BDCTALON) BDCTALON,
             COALESCE(CDL.BDCODTPLA, CDLRAT.BDCODTPLA) BDCODTPLA, I.BDCODEMPSCP
      FROM ( 
            SELECT I.BDCODEMP, I.BDCHAVE, I.BDORDEM,  E.BDMODELO, E.BDNUMDOCINI, 
                   COALESCE(EMP.BDCODMATRIZ, E.BDCODEMP) BDCODMATRIZ, EMP.BDCNPJEMP, E.BDEMITENTE, 
                   E.BDCODSITNF, E.BDESPECIE, E.BDSERIE, E.BDSUBSERIE, E.BDNUMDOCFIM, 
                   E.BDCHAVENFE, E.BDDATAEMISSAO, E.BDDATAENTRADAENT, E.BDVALORNOTA, E.BDCONDPGTO, 
                   I.BDCODNAT, I.BDVLRCONTAB, I.BDBASEICMS, I.BDVLRICMS, I.BDBASEST, I.BDVLRST, I.BDVLRIPI, 
                   E.BDREFLAN, I.BDDESCONTO, I.BDISENTASICMS, I.BDOUTRASICMS, TER.*, CID.BDNOMCID, UF.BDSIGLAUF, 
                   PAIS.BDCODSPED, E.BDDESCONTONOTA, EMPSCP.BDCODEMPSCP
            FROM (SELECT E.*
                  FROM VEF_EMP_TMOVENT E 
                  JOIN VW_INT_SPEDPISCOFINS_REF empaux ON (E.bdcodemp = empaux.bdcodemp AND empaux.bdsomenteblocop <> 'TRUE') 
                  WHERE E.BDCODEMP = (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_CODEMP') FROM RDB$DATABASE)
                  AND E.BDDATAENTRADAENT BETWEEN (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_DT_INI') FROM RDB$DATABASE) AND (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_DT_FIM') FROM RDB$DATABASE)
                  AND ((E.BDMODELO IN(2, 6, 28, 29, 7, 8, 9, 10, 11, 26, 27, 57, 66, 67, 800, 21, 22, 63, 62, 75)
                         and ( exists (
                                        select first 1 i.bdcodemp
                                        from vef_emp_tmoventitens i
                                        JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT AND ((nat.bdNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.bdNAOEXPEFDCONT)) = TRIM('FALSE'))) )
                                        where i.bdcodemp = e.bdcodemp
                                        and i.bdchave = e.bdchave
                                       )
                         )
                         )
                   or (e.BDMODELO = 55 and exists (
                                                   select first 1 i.bdcodemp
                                                   from vef_emp_tmoventitens i
                                                   JOIN VEF_EMP_TMOVPROENT C ON(C.BDCODEMP = I.BDCODEMP AND C.BDCHAVE = I.BDCHAVE AND C.BDORDEM = I.BDORDEM AND COALESCE(C.BDVLRPIS, 0) > 0 AND COALESCE(C.BDVLRCOFINS, 0) > 0)
                                                   JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT AND ((nat.bdNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.bdNAOEXPEFDCONT)) = TRIM('FALSE'))) )
                                                   where i.bdcodemp = e.bdcodemp
                                                   and i.bdchave = e.bdchave
                                                   and (SUBSTRING(i.BDCODNAT FROM 1 FOR 3) IN(125, 225))
                                                  ))

                                                  )
                 ) E
            LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = E.BDCODEMP AND I.BDCHAVE = E.BDCHAVE)
            LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON ((select RDB$GET_CONTEXT('USER_SESSION', 'W_EXPORTAPORSCP') from RDB$DATABASE) = 'TRUE') and (EMPSCP.BDCODEMP = i.BDCODEMP) AND (EMPSCP.BDREFEMP = i.BDREFSOC) AND (EMPSCP.BDCODSCP = i.BDCODSCP)
            JOIN TEMPRESAS EMP ON (EMP.BDCODEMP = E.BDCODEMP)
            join TTERCEIRO_REF TER on (TER.BDCODTER = E.BDCODTER and TER.BDREFEMP = coalesce((select max(RF2.BDREFEMP)
                                                                                                     from TTERCEIRO_REF RF2
                                                                                                     where RF2.BDCODTER = TER.BDCODTER and
                                                                                                           RF2.BDREFEMP <= (select BDDATA
                                                                                 from SP_PARSE_DATE(cast((select RDB$GET_CONTEXT('USER_SESSION', 'W_DT_INI')
                                                                                                          from RDB$DATABASE) as date), 'YYYYMM'))), (select min(RF2.BDREFEMP)
                                                                                                                                 from TTERCEIRO_REF RF2
                                                                                                                                    where RF2.BDCODTER = TER.BDCODTER)))
            LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = TER.BDCODCID) 
            LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF) 
            LEFT OUTER JOIN TPAIS PAIS ON (PAIS.BDCODPAIS = TER.BDCODPAIS) 
           ) I
      LEFT OUTER JOIN VW_TEMPRESAS_REF ref ON (ref.bdCODEMP = i.bdCODEMP)
      LEFT OUTER JOIN VEF_EMP_TD100ENT d100 ON (d100.bdCODEMP = i.bdCODEMP AND d100.bdCHAVE = i.BDCHAVE)
      LEFT OUTER JOIN VEF_EMP_TC500ENT c500 ON (c500.bdCODEMP = i.bdCODEMP AND c500.bdCHAVE = i.BDCHAVE)
      LEFT OUTER JOIN VEF_EMP_TD500ENT d500 ON (d500.bdCODEMP = i.bdCODEMP AND d500.bdCHAVE = i.BDCHAVE)
      LEFT OUTER JOIN VEF_EMP_TMOVPROENT P ON (P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM) 
      LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVEENT, BDORDEM, MIN(BDCHAVE) BDCHAVE, BDCODEMPSUC FROM TOL_VEF_EMP_TMOVENT GROUP BY BDCODEMP, BDCHAVEENT, BDORDEM, BDCODEMPSUC)  tol ON (tol.bdcodemp = I.bdcodemp AND tol.bdchaveent = I.bdchave AND tol.bdordem = I.bdordem)
      LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.BDCODEMP = tol.BDCODEMPSUC AND lan.bdchave = tol.BDCHAVE)
      LEFT OUTER JOIN PLANOS_TPLA cdl ON (COALESCE(p.bdCODPLAPADRAO,d100.bdCODPLAPADRAO,c500.bdCODPLAPADRAO,d500.bdCODPLAPADRAO,lan.bdCODPLAPADRAO) = cdl.bdCODPLAPADRAO AND COALESCE(p.bdCODTPLA,d100.bdCODTPLA,c500.bdCODTPLA,d500.bdCODTPLA,lan.bdDEBITO) = cdl.bdCODTPLA)
      LEFT OUTER JOIN PLANOS_TPLA_ECF cdle ON (cdle.bdcodplapadraoref = (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_CODPLAPADRAOREF') FROM RDB$DATABASE) AND
                                               cdle.bdano = (SELECT FIRST 1 BDANO 
                                                             FROM PLANOS_TPLA_ECF 
                                                             WHERE CAST(BDANO || '01' AS INTEGER) <= I.bdreflan AND 
                                                             BDCODTPLAREF IS NOT NULL  AND 
                                                               cdle.BDCODPLAPADRAO = BDCODPLAPADRAO AND 
                                                               cdle.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF AND 
                                                               cdle.BDCODTPLA = BDCODTPLA ORDER BY BDANO DESC 
                                                             ) AND 
                                               cdle.bdcodplapadrao = cdl.bdcodplapadrao AND cdle.bdcodtpla = cdl.bdcodtpla) 
      LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO cdlep ON (CDLE.BDCODPLAPADRAOREF = cdlep.BDCODPLAPADRAOREF AND CDLE.BDCODTPLAREF = cdlep.BDCODTPLAREF) 
      LEFT OUTER JOIN  (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) BDCHAVE, BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATENT GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM, BDCODEMPSUC) tolrat
                        ON (tolrat.bdcodemp = I.bdcodemp AND tolrat.bdchavelan = I.bdchave AND tolrat.bdordem = I.bdordem) 
      LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat ON (lanrat.BDCODEMP = tolrat.BDCODEMPSUC AND lanrat.bdchave = tolrat.BDCHAVE)
      LEFT OUTER JOIN planos_tpla cdlrat ON (COALESCE(P.BDCODPLAPADRAO,lanrat.BDCODPLAPADRAO) = cdlrat.bdcodplapadrao AND COALESCE(P.BDCODTPLA,lanrat.bddebito) = cdlrat.bdcodtpla) 
      LEFT OUTER JOIN PLANOS_TPLA_ECF cdlerat ON (cdlerat.bdcodplapadraoref = (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_CODPLAPADRAOREF') FROM RDB$DATABASE) AND
                                               cdlerat.bdano = 
                                                  (SELECT FIRST 1 BDANO 
                                                   FROM PLANOS_TPLA_ECF 
                                                   WHERE CAST(BDANO || '01' AS INTEGER) <= lanrat.bdreferencia AND 
                                                     BDCODTPLAREF IS NOT NULL AND 
                                                     cdlerat.BDCODPLAPADRAO = BDCODPLAPADRAO  AND 
                                                     cdlerat.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF AND 
                                                     cdlerat.BDCODTPLA = BDCODTPLA ORDER BY BDANO DESC 
                                                   ) AND 
                                               cdlerat.bdcodplapadrao = cdlrat.bdcodplapadrao AND 
                                               cdlerat.bdcodtpla = cdlrat.bdcodtpla) 
      LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO cdleprat ON (cdlerat.BDCODPLAPADRAOREF = cdleprat.BDCODPLAPADRAOREF AND cdlerat.BDCODTPLAREF = cdleprat.BDCODTPLAREF) 
     ) MOV
LEFT OUTER JOIN VEF_EMP_TC100ENT C100 ON (C100.bdcodemp = MOV.bdcodemp AND C100.BDCHAVE = MOV.BDCHAVE) 
LEFT OUTER JOIN VEF_BASE_TTABINFRETE TABIFC100 ON (TABIFC100.BDORDEMFRETE = C100.BDINDFRETE) 
LEFT OUTER JOIN VEF_EMP_TC500ENT C500 ON (C500.BDCODEMP = MOV.BDCODEMP AND C500.BDCHAVE = MOV.BDCHAVE) 
LEFT OUTER JOIN VEF_BASE_TNATBCPISCOFINS NATBCC500 ON (NATBCC500.BDCODNATBC = C500.BDCODNATBC) 
LEFT OUTER JOIN VEF_BASE_TCADINFCOM CADINF ON (CADINF.BDORDEMINFCOM = C500.BDORDEMINFCOM) 
LEFT OUTER JOIN VEF_BASE_TTABCSTCOF CSTCOFC500 ON (CSTCOFC500.BDCODCSTCOF = C500.BDCODCSTCOF) 
LEFT OUTER JOIN VEF_BASE_TTABCSTPIS CSTPISC500 ON (CSTPISC500.BDCODCSTPIS = C500.BDCODCSTPIS) 
LEFT OUTER JOIN VEF_EMP_TD100ENT D100 ON (D100.BDCODEMP = MOV.BDCODEMP AND MOV.BDCHAVE = D100.BDCHAVE) 
LEFT OUTER JOIN VEF_BASE_TCADINFCOM CADINFD100 ON (CADINFD100.BDORDEMINFCOM = D100.BDORDEMINFCOM) 
LEFT OUTER JOIN VEF_BASE_TTABCSTCOF CSTCOFD100 ON (CSTCOFD100.BDCODCSTCOF = D100.BDCODCSTCOF) 
LEFT OUTER JOIN VEF_BASE_TTABCSTPIS CSTPISD100 ON (CSTPISD100.BDCODCSTPIS = D100.BDCODCSTPIS) 
LEFT OUTER JOIN VEF_BASE_TNATBCPISCOFINS NATBC ON (NATBC.BDCODNATBC = D100.BDCODNATBC) 
LEFT OUTER JOIN VEF_EMP_TD500ENT D500 ON (D500.BDCODEMP = MOV.BDCODEMP AND D500.BDCHAVE = MOV.BDCHAVE) 
LEFT OUTER JOIN VEF_BASE_TCADINFCOM CADINFD500 ON (CADINFD500.BDORDEMINFCOM = D500.BDORDEMINFCOM) 
LEFT OUTER JOIN VEF_BASE_TNATBCPISCOFINS NATBCD500 ON (NATBCD500.BDCODNATBC = D500.BDCODNATBC) 
LEFT OUTER JOIN VEF_BASE_TTABCSTCOF CSTCOFD500 ON (CSTCOFD500.BDCODCSTCOF = D500.BDCODCSTCOF) 
LEFT OUTER JOIN VEF_BASE_TTABCSTPIS CSTPISD500 ON (CSTPISD500.BDCODCSTPIS = D500.BDCODCSTPIS) 
LEFT OUTER JOIN VEF_BASE_TTABINFRETE TABIFD100 ON (TABIFD100.BDORDEMFRETE = D100.BDINDFRETE) 
LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MODLAN ON (MODLAN.BDMODELO = MOV.BDMODELO) 
LEFT OUTER JOIN VEF_BASE_TTABNATFRETE NATFRETE ON (NATFRETE.BDCODNATF = D100.BDCODNATF) 
LEFT OUTER JOIN VEF_BASE_TNATBCPISCOFINS CRED ON (CRED.BDCODNATBC = MOV.BDCODNATBC) 
LEFT OUTER JOIN TCADPRO_VINC PRO ON (PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCODPROD = MOV.BDCODPROD) 
LEFT OUTER JOIN TUNIDADEMEDIDA UM ON (UM.BDCODUNIMED = PRO.BDCODUNIMED) 
LEFT OUTER JOIN VEF_BASE_TTABCSTICMS CSTICMS ON (CSTICMS.BDCODCSTICMS = MOV.BDCODCSTICMS) 
LEFT OUTER JOIN VEF_BASE_TTABCSTIPI CSTIPI ON (CSTIPI.BDCODCSTIPI = MOV.BDCODCSTIPI) 
LEFT OUTER JOIN VEF_BASE_TTABCSTPIS CSTPIS ON (CSTPIS.BDCODCSTPIS = MOV.BDCODCSTPIS) 
LEFT OUTER JOIN VEF_BASE_TTABCSTCOF CSTCOF ON (CSTCOF.BDCODCSTCOF = MOV.BDCODCSTCOF)
LEFT OUTER JOIN(SELECT SUM(ORI.BDVLRICMS) BDVLRICMS, ORI.BDCODEMP, ORI.BDCHAVE, ORI.BDORDEM, ORI.BDCODPROD
                FROM VEF_EMP_TMOVPROENTIMPORI ORI
                GROUP BY ORI.BDCODEMP, ORI.BDCHAVE, ORI.BDORDEM, ORI.BDCODPROD) ORI ON (ORI.BDCODEMP = mov.BDCODEMP AND ORI.BDCHAVE = mov.BDCHAVE AND ORI.BDORDEM = mov.BDORDEM AND ORI.BDCODPROD = mov.BDCODPROD)
LEFT OUTER JOIN(SELECT SUM(SUMM.BDVLRITEM) AS BDBCICMS, SUMM.BDCODEMP, SUMM.BDCHAVE, SUMM.BDORDEM, summ.bdcodprod
                FROM VEF_EMP_TMOVPROENT SUMM
                GROUP BY SUMM.BDCODEMP, SUMM.BDCHAVE, SUMM.BDORDEM, SUMM.BDCODPROD) SUMM ON (SUMM.BDCODEMP = mov.BDCODEMP AND SUMM.BDCHAVE = mov.BDCHAVE AND SUMM.BDORDEM = mov.BDORDEM AND SUMM.BDCODPROD = mov.BDCODPROD)

ORDER BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDORDEM, MOV.BDORDEMPRO;

--21893 - ELIZEU - ControlMemory traz desordenado, e partimos pra views com variáveis de sessão "USER_SESSION"
CREATE OR ALTER VIEW VW_EXP_SPED_CONTRIBUICOES_SAI(
    BDCODMATRIZ,
    BDCODEMP,
    BDCNPJEMP,
    BDCHAVE,
    BDIND_OPER,
    BDEMITENTE,
    BDCODTER,
    BDESPECIE,
    BDMODELO,
    BDMODELOSTR,
    BDCODSITNF,
    BDSERIE,
    BDNUMDOCINI,
    BDNUMDOCFIM,
    BDCHAVENFE,
    BDDATAEMISSAO,
    BDVALORNOTA,
    BDCONDPGTO,
    BDINDFRETE,
    BDVLRFRETE,
    BDVLRSEGURO,
    BDVLROUTDESP,
    BDORDEM,
    BDCODNAT,
    BDSUBSERIE,
    BDVLRCONTAB,
    BDBASEICMS,
    BDVLRICMS,
    BDBASEST,
    BDVLRST,
    BDVLRIPI,
    BDVLRICMSPROD,
    BDVLRIPIPROD,
    BDVLRSTPROD,
    BDAPEUNIMED,
    BDDESCUNIMED,
    BDDESCPROD,
    BDCODSAIDA,
    BDCSTICMS,
    BDCODEXPCSTIPI,
    BDNATREC,
    BDCODEXP_CODCLAENETEL,
    BDINDREC,
    BDCODPROD,
    BDCODCSTICMS,
    BDCODCSTIPI,
    BDCODFATCON,
    BDMOVFISICO,
    BDQTDITEM,
    BDVLRITEM,
    BDVLRDESC,
    BDVLRDESPACESSORIA,
    BDREDBCICMS,
    BDBCICMS,
    BDBCPIS,
    BDBCST,
    BDBCIPI,
    BDBCCOFINS,
    BDBCISSQN,
    BDALIQICMS,
    BDALIQPIS,
    BDALIQST,
    BDALIQIPI,
    BDALIQCOFINS,
    BDALIQISSQN,
    BDVLRPIS,
    BDVLRCOFINS,
    BDVLRISSQN,
    BDVLRFRETEPROD,
    BDCODNATRECPROD,
    BDVLRPISPROD,
    BDVLRCOFINSPROD,
    BDVLRTOTPISPROD,
    BDVLRTOTCOFINSPROD,
    BDQTDEPROD,
    BDVLRTOTPIS,
    BDVLRTOTCOFINS,
    BDVLRABATNT,
    BDVLRTOTPISST,
    BDVLRTOTCOFINSST,
    BDDESCONTO,
    BDCODINFCOM,
    BDDESCINFCOM,
    BDCSTCOF,
    BDCSTPIS,
    BDISENTASICMS,
    BDOUTRASICMS,
    BDCGCTER,
    BDREFEMP,
    BDAPELIDOTER,
    BDNOMETER,
    BDLOGRTER,
    BDENDTER,
    BDNUMTER,
    BDCOMPTER,
    BDCEPTER,
    BDBAITER,
    BDDDDTER,
    BDFONETER,
    BDFAXTER,
    BDEMAILTER,
    BDIETER,
    BDDATACADTER,
    BDIMTER,
    BDPRURALTER,
    BDENQSIMPLESFEDTER,
    BDINSCSUFRAMATER,
    BDCODGPS,
    BDCODCID,
    BDCODPAIS,
    BDDDDFAXTER,
    BDNOMCID,
    BDSIGLAUF,
    BDCODSPED,
    BDCODTENSAO,
    BDORDEMINFCOM,
    BDCODCONS,
    BDVLRCONSFOR,
    BDVLRCOBTER,
    BDVLRDESPACE,
    BDTIPOLIGACAO,
    BDVL_BC_PIS,
    BDALIQ_PIS,
    BDVL_BC_COF,
    BDALIQ_COF,
    BDVLRPISD200,
    BDVLRCOFINSD200,
    BDVL_BC_PISD200,
    BDALIQ_PISD200,
    BDVL_BC_COFD200,
    BDALIQ_COFD200,
    BDCSTCOFD200,
    BDCSTPISD200,
    BDNATRECD200,
    BDNATRECD600,
    BDCODEXPTPREC,
    BDVLRCOBTERCD600,
    BDVLROUTDESPD600,
    BDVLRPISD600,
    BDVLRCOFINSD600,
    BDCODINFCOMD600,
    BDDESCINFCOMD600,
    BDALIQ_PISD600,
    BDCSTPISD600,
    BDVL_BC_PISD600,
    BDCSTCOFD600,
    BDVL_BC_COFD600,
    BDALIQ_COFD600,
    BDCODPAISTER,
    BDCODPLAPADRAO,
    BDORDEMPRO,
    BDCODCTA,
    BDDESCONTONOTA,
    BDCODCSTPIS,
    BDCODCSTCOF,
    BDCREDITOREF,
    BDCREDITOPLAPADRAOREF,
    BDCREDITO,
    BDANOCREDITO,
    BDCTALON,
    BDANOEMISSAO,
    BDCODTPLA)
AS
SELECT Coalesce(a.BDCODEMPSCP,a.bdcodmatriz),Coalesce(a.BDCODEMPSCP,a.bdemp) bdcodemp, a.bdcnpjemp, a.bdchave, a.BDIND_OPER, a.bdemitente, a.bdter bdcodter, a.bdespecie, a.bdmodelo, a.bdmodelostr,
      a.BDCODSITNF, a.bdserie, a.bdnumdocini, a.bdnumdocfim, 
      a.bdchavenfe, a.bddataemissao, a.bdvalornota, a.bdcondpgto,a.BDINDFRETE,a.BDVLRFRETE,a.BDVLRSEGURO,a.BDVLROUTDESP,a.bdordem, a.bdcodnat, a.bdsubserie, a.BDVLRCONTAB, 
      a.bdbaseicms, a.bdvlricms, a.bdbasest, a.bdvlrst,a.bdvlripi,A.BDVLRICMSPROD,A.BDVLRIPIPROD,A.BDVLRSTPROD, 
      UM.BDAPEUNIMED, UM.BDDESCUNIMED, PRO.BDDESCPROD, PRO.BDCODSAIDA, CSTICMS.BDCSTICMS, NULL BDCODEXPCSTIPI, 
      NATREC.BDNATREC, D601_D605CLASS.BDCODEXP BDCODEXP_CODCLAENETEL, D601_D605.BDINDREC,
      A.BDCODPROD,  A.BDCODCSTICMS, A.BDCODCSTIPI, 
      A.BDCODFATCON, A.BDMOVFISICO, A.BDQTDITEM, A.BDVLRITEM,
      A.BDVLRDESC, A.BDVLRDESPACESSORIA, A.BDREDBCICMS, A.BDBCICMS, A.BDBCPIS, 
      A.BDBCST, A.BDBCIPI, A.BDBCCOFINS, A.BDBCISSQN, A.BDALIQICMS, A.BDALIQPIS, 
      A.BDALIQST, A.BDALIQIPI, A.BDALIQCOFINS, A.BDALIQISSQN,
      A.BDVLRPIS,  A.BDVLRCOFINS, A.BDVLRISSQN,
      A.BDVLRFRETEPROD,A.BDCODNATRECPROD,A.BDVLRPISPROD,A.BDVLRCOFINSPROD , 
      A.BDVLRTOTPISPROD,A.BDVLRTOTCOFINSPROD, A.BDQTDEPROD,
      CASE WHEN (A.BDVLRTOTPIS = 0 OR A.BDVLRTOTPIS IS NULL) THEN 
        A.BDVLRTOTPISPROD 
      ELSE 
        A.BDVLRTOTPIS END BDVLRTOTPIS, 
      CASE WHEN (A.BDVLRTOTCOFINS = 0 OR A.BDVLRTOTCOFINS IS NULL) THEN 
        A.BDVLRTOTCOFINSPROD 
      ELSE 
        A.BDVLRTOTCOFINS END BDVLRTOTCOFINS, 
       A.BDVLRABATNT, a.BDVLRTOTPISST, a.BDVLRTOTCOFINSST, a.BDDESCONTO,a.bdcodinfcom, a.BDDESCINFCOM, a.bdcstcof, a.bdcstpis,
      a.bdisentasicms, a.bdoutrasicms, A.BDCGCTER, A.BDREFEMP, A.BDAPELIDOTER, A.BDNOMETER, A.BDLOGRTER, A.BDENDTER,A.BDNUMTER, A.BDCOMPTER, 
      A.BDCEPTER, A.BDBAITER,A.BDDDDTER, A.BDFONETER, A.BDFAXTER,A.BDEMAILTER, A.BDIETER, A.BDDATACADTER, A.BDIMTER,A.BDPRURALTER, A.BDENQSIMPLESFEDTER, 
      A.BDINSCSUFRAMATER,A.BDCODGPS, A.BDCODCID, A.BDCODPAIS, A.BDDDDFAXTER,a.bdnomcid, a.bdsiglauf, a.bdcodsped, 
      A.BDCODTENSAO, A.BDORDEMINFCOM, a.bdcodcons, A.BDVLRCONSFOR, A.BDVLRCOBTER, A.BDVLRDESPACE, A.BDTIPOLIGACAO, 
      COALESCE(A.BDVL_BC_PIS,0) BDVL_BC_PIS, COALESCE(A.BDALIQ_PIS,0) BDALIQ_PIS,
      COALESCE(A.BDVL_BC_COF,0) BDVL_BC_COF, COALESCE(A.BDALIQ_COF,0) BDALIQ_COF,
      COALESCE(A.BDVLRPISd200,0) BDVLRPISd200, COALESCE(A.BDVLRCOFINSd200,0) BDVLRCOFINSd200, COALESCE(A.BDVL_BC_PISd200,0) BDVL_BC_PISd200, 
      COALESCE(a.BDALIQ_PISd200,0) BDALIQ_PISd200, COALESCE(a.BDVL_BC_COFd200,0) BDVL_BC_COFd200, COALESCE(a.BDALIQ_COFd200,0) BDALIQ_COFd200, 
      a.bdcstcofd200, a.bdcstpisd200, a.BDNATRECd200, a.BDNATRECd600, a.BDCODEXPTPREC, 
      a.BDVLRCOBTERCD600, a.BDVLROUTDESPD600, a.BDVLRPISD600, a.BDVLRCOFINSD600,
      a.bdcodinfcomD600, a.BDDESCINFCOMD600, a.BDALIQ_PISD600, a.bdcstpisD600, a.BDVL_BC_PISD600, 
      a.bdcstcofD600, a.BDVL_BC_COFD600, a.BDALIQ_COFD600, a.BDCODPAISTER,  A.bdcodplapadrao,
      A.BDORDEMPRO, a.bdcodcta, a.bddescontonota, A.BDCODCSTPIS, A.BDCODCSTCOF, A.bdcreditoREF, A.BDCREDITOPLAPADRAOREF, A.BDCREDITO, A.BDANOCREDITO,
      A.BDCTALON, EXTRACT(YEAR FROM A.BDDATAEMISSAO) BDANOEMISSAO, A.BDCODTPLA

 FROM ( 
SELECT 
      COALESCE(emp.bdcodmatriz,mov.bdcodemp) bdcodmatriz, mov.bdcodemp bdemp, emp.bdcnpjemp, mov.bdchave, 1 BDIND_OPER, mov.bdemitente, mov.bdcodter bdter, mov.bdespecie, mov.bdmodelo, modlan.bdmodelostr,
      mov.BDCODSITNF, mov.bdserie, mov.bdnumdocini, mov.bdnumdocfim, 
      mov.bdchavenfe, mov.bddataemissao, mov.bdvalornota, mov.bdcondpgto,tabifc100.BDCODEXPFRETE BDINDFRETE,c100.BDVLRFRETE,c100.BDVLRSEGURO,c100.BDVLROUTDESP,mov.bdordem, mov.bdcodnat, mov.bdsubserie, mov.BDVLRCONTAB, 
      mov.bdbaseicms, mov.bdvlricms, mov.bdbasest, mov.bdvlrst,mov.bdvlripi,MOV.BDVLRICMSPROD,MOV.BDVLRIPIPROD,MOV.BDVLRSTPROD, 
      mov.BDCODPROD,  mov.BDCODCSTICMS, mov.BDCODCSTIPI, 
      mov.BDCODFATCON, mov.BDMOVFISICO, mov.BDQTDITEM, mov.BDVLRITEM,
      mov.BDVLRDESC, mov.BDVLRDESPACESSORIA, mov.BDREDBCICMS, mov.BDBCICMS, mov.BDBCPIS, 
      mov.BDBCST, mov.BDBCIPI, mov.BDBCCOFINS, mov.BDBCISSQN, mov.BDALIQICMS, mov.BDALIQPIS, 
      mov.BDALIQST, mov.BDALIQIPI, mov.BDALIQCOFINS, mov.BDALIQISSQN, 
      mov.BDVLRPISPROD, mov.BDVLRCOFINSPROD, mov.BDVLRISSQN, mov.BDVLRFRETEPROD ,mov.BDCODNATRECPROD, 
      MOV.BDORDEMPRO, MOV.BDCODEMPSCP,
      (SELECT SUM(CAST(movpro.BDVLRPIS AS NUMERIC(15,2)))
      FROM vef_emp_tmovprosai movpro 
      WHERE (mov.bdcodemp = movpro.bdcodemp AND mov.bdchave = movpro.bdchave)) BDVLRTOTPISPROD, 
      (SELECT SUM(CAST(movpro.BDVLRCOFINS AS NUMERIC(15,2))) 
      FROM vef_emp_tmovprosai movpro 
      WHERE (mov.bdcodemp = movpro.bdcodemp AND mov.bdchave = movpro.bdchave)) BDVLRTOTCOFINSPROD, 
      (SELECT COUNT(movpro.bdCHAVE) BDQTDEPROD 
      FROM vef_emp_tmovprosai movpro 
      WHERE (mov.bdcodemp = movpro.bdcodemp AND mov.bdchave = movpro.bdchave)) AS BDQTDEPROD, 
      ((c100.BDVLRTOTPIS*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRTOTPIS,
      ((c100.BDVLRTOTCOFINS*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRTOTCOFINS, ((C100.BDVLRABATNT*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRABATNT,
      ((c100.BDVLRTOTPISST*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRTOTPISST, ((c100.BDVLRTOTCOFINSST*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRTOTCOFINSST, mov.BDDESCONTO,
      cadinf.bdcodinfcom, cadinf.BDDESCINFCOM, cstcof.bdcstcof, cstpis.bdcstpis, mov.bdisentasicms, mov.bdoutrasicms, 
      TER.BDCODTER, TER.BDCGCTER, TER.BDREFEMP, TER.BDAPELIDOTER, TER.BDNOMETER, TER.BDLOGRTER, TER.BDENDTER, 
      TER.BDNUMTER, TER.BDCOMPTER, TER.BDCEPTER, TER.BDBAITER,TER.BDDDDTER, TER.BDFONETER, TER.BDFAXTER, 
      TER.BDEMAILTER, TER.BDIETER, TER.BDDATACADTER, TER.BDIMTER,TER.BDPRURALTER, TER.BDENQSIMPLESFEDTER, TER.BDINSCSUFRAMATER, 
      TER.BDCODGPS, TER.BDCODCID, TER.BDCODPAIS, TER.BDDDDFAXTER,cid.bdnomcid, uf.bdsiglauf, paister.bdcodsped, 
      c500.BDCODTENSAO, c500.BDORDEMINFCOM, codcons.bdcodcons, c500.BDVLRCONSFOR, c500.BDVLRCOBTER, c500.BDVLRDESPACE,
      COALESCE(c500.BDVLRPIS, 0) BDVLRPIS, COALESCE(c500.BDVLRCOFINS, 0) BDVLRCOFINS, c500.BDTIPOLIGACAO,
      c500.BDCODCSTPIS BDCODCSTPISC500, COALESCE(c500.BDVL_BC_PIS, 0) BDVL_BC_PIS, c500.BDALIQ_PIS, c500.BDCODCSTCOF BDCODCSTCOFC500, --Larissa - 06/05/2021 - Alterado o campo BDVL_BC_PIS, BDVL_BC_COF, BDVLRPIS e BDVLRCOFINS- Sped Contribuições - C500 mais de uma CFOP #149987
      COALESCE(c500.BDVL_BC_COF,0) BDVL_BC_COF, c500.BDALIQ_COF, c500.BDCODNATREC BDCODNATRECC500,
      ((d200.BDVLRPIS*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRPISd200, ((d200.BDVLRCOFINS*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVLRCOFINSd200,
      ((d200.BDVL_BC_PIS*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVL_BC_PISd200, d200.BDALIQ_PIS BDALIQ_PISd200,
      ((d200.BDVL_BC_COF*MOV.BDVLRCONTAB)/IIF(MOV.BDVALORNOTA > 0,MOV.BDVALORNOTA,1)) BDVL_BC_COFd200, d200.BDALIQ_COF BDALIQ_COFd200,
      cstcofd200.bdcstcof bdcstcofd200, cstpisd200.bdcstpis bdcstpisd200, natrecd200.BDNATREC BDNATRECd200, natrecd600.BDNATREC BDNATRECd600, TPRECD600.BDCODEXPTPREC, 
      D600.BDVLRCOBTERC BDVLRCOBTERCD600, D600.BDVLROUTDESP BDVLROUTDESPD600, D600.BDVLRPIS BDVLRPISD600, D600.BDVLRCOFINS BDVLRCOFINSD600, D600.BDCODCLAENETEL, 
      cadinfD600.bdcodinfcom bdcodinfcomD600, cadinfD600.BDDESCINFCOM BDDESCINFCOMD600, D600.BDALIQ_PIS BDALIQ_PISD600, cstpisD600.bdcstpis bdcstpisD600, D600.BDVL_BC_PIS BDVL_BC_PISD600, 
      cstcofD600.bdcstcof bdcstcofD600, D600.BDVL_BC_COF BDVL_BC_COFD600, D600.BDALIQ_COF BDALIQ_COFD600, paisTer.BDCODPAIS AS BDCODPAISTER, mov.bdcodcta, mov.bddescontonota 
      , MOV.BDCODCSTCOF, MOV.BDCODCSTPIS, MOV.BDCREDITOREF, MOV.BDCREDITOPLAPADRAOREF, MOV.BDCREDITO, MOV.BDANOCREDITO, mov.bdcodplapadrao, MOV.BDCTALON, MOV.BDCODTPLA
      FROM ( 
            SELECT mov.*,MOVPRO.BDORDEMPRO, MOVPRO.BDCODCTA, 
                         MOVPRO.BDCODPROD, MOVPRO.BDCODCSTCOF, MOVPRO.BDCODCSTICMS, MOVPRO.BDCODCSTPIS, MOVPRO.BDCODCSTIPI, 
                         MOVPRO.BDCODFATCON, MOVPRO.BDMOVFISICO, MOVPRO.BDQTDITEM, MOVPRO.BDVLRITEM,
                         MOVPRO.BDVLRDESC, MOVPRO.BDVLRDESPACESSORIA, MOVPRO.BDREDBCICMS, MOVPRO.BDBCICMS, MOVPRO.BDBCPIS, 
                         MOVPRO.BDBCST, MOVPRO.BDBCIPI, MOVPRO.BDBCCOFINS, MOVPRO.BDBCISSQN, MOVPRO.BDALIQICMS, MOVPRO.BDALIQPIS, 
                         MOVPRO.BDALIQST, MOVPRO.BDALIQIPI, MOVPRO.BDALIQCOFINS, MOVPRO.BDALIQISSQN, MOVPRO.BDVLRICMS BDVLRICMSPROD, 
                         MOVPRO.BDVLRPIS BDVLRPISPROD, MOVPRO.BDVLRST BDVLRSTPROD, MOVPRO.BDVLRIPI BDVLRIPIPROD, MOVPRO.BDVLRCOFINS BDVLRCOFINSPROD, 
                         MOVPRO.BDVLRISSQN, MOVPRO.BDVLRFRETE BDVLRFRETEPROD,MOVPRO.BDCODNATREC BDCODNATRECPROD,
                         
                         COALESCE(MOVPRO.BDCODPLAPADRAO, IIF((d100.bdCODCTA IS NOT NULL OR c500.bdCODTPLA IS NOT NULL OR d500.bdCODCTA IS NOT NULL), ref.bdCODPLAPADRAO, NULL), COALESCE(lan.BDCODPLAPADRAO, LANRAT.BDCODPLAPADRAO), ref.bdCODPLAPADRAO) bdCODPLAPADRAO,
                         COALESCE(cclep.bdcodtplaref, ccderatp.bdcodtplaref) bdcreditoref,
                         COALESCE(ccl.bdCODTPLA,cclrat.bdCODTPLA,d100.bdCODCTA,d500.bdCODCTA) AS bdCREDITO,
                         COALESCE(COALESCE(ccle.bdano, ccderat.bdano), CAST(SUBSTRING(mov.bdreflan FROM 1 FOR 4) AS INTEGER)) bdanocredito,
                         COALESCE(cclep.BDCODPLAPADRAOREF, ccderatp.BDCODPLAPADRAOREF) bdcreditoplapadraoref, COALESCE(CCL.BDCTALON, CCLRAT.BDCTALON) BDCTALON, COALESCE(CCL.BDCODTPLA, CCLRAT.BDCODTPLA) AS BDCODTPLA
            FROM ( 
                  SELECT movaux.bdcodemp, movaux.bdreflan, movaux.bdchave, movaux.bdemitente, movaux.bdcodter, movaux.bdmodelo, movaux.BDCODSITNF, movaux.bdespecie, movaux.bdsubserie, movaux.bdserie, movaux.bdnumdocini, movaux.bdnumdocfim, 
                  movaux.bdchavenfe, movaux.bddataemissao, movaux.bdvalornota, movaux.bdcondpgto, movaux.BDDESCONTONOTA AS BDDESCONTOnota, 
                  itens.bdordem, itens.bdcodnat, itens.BDVLRCONTAB, itens.bdbaseicms, itens.bdvlricms, itens.bdbasest, itens.bdvlrst, itens.bdvlripi, itens.bdisentasicms, itens.bdoutrasicms, 
                  ITENS.BDCODOBS,ITENS.BDBASEIPI, ITENS.BDISENTASIPI, 
                  ITENS.BDOUTRASIPI, ITENS.BDIMPEXCLUIDAS, ITENS.BDOUTROSIMP,ITENS.BDDESCONTO, 
                  ITENS.BDICMSFRETESAI, ITENS.BDPREFIXONAT, ITENS.BDOBSERVACAO, EMPSCP.BDCODEMPSCP
                  FROM (SELECT movaux.bdcodemp, movaux.BDDESCONTONOTA, movaux.bdchave, movaux.bdemitente, movaux.bdcodter, movaux.bdespecie, movaux.bdmodelo, movaux.BDCODSITNF, movaux.bdserie, movaux.bdsubserie, movaux.bdnumdocini, MOVAUX.bdnumdocfim, 
                        movaux.bdchavenfe, movaux.bddataemissao, movaux.bdreflan, movaux.bddatasaida, movaux.bdvalornota, movaux.bdcondpgto 
                        FROM vef_emp_tmovsai movaux 
                        JOIN VW_INT_SPEDPISCOFINS_REF empaux ON (movaux.bdcodemp = empaux.bdcodemp AND empaux.bdsomenteblocop <> 'TRUE')
                        WHERE movaux.BDCODEMP = (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_CODEMP') FROM RDB$DATABASE)
                        AND movaux.bddataemissao BETWEEN (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_DT_INI') FROM RDB$DATABASE) AND (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_DT_FIM') FROM RDB$DATABASE)
                        AND MOVAUX.BDMODELO IN(2, 6, 28, 29, 7, 8, 9, 10, 11, 26, 27, 57, 67, 800, 21, 22, 63, 66, 62, 75)
                        AND EXISTS(SELECT *
                                   FROM VEF_EMP_TMOVSAIITENS i
                                   JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT AND ((nat.bdNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.bdNAOEXPEFDCONT)) = TRIM('FALSE'))) )
                                   WHERE i.bdCODEMP = movaux.bdCODEMP
                                     AND i.bdCHAVE  = movaux.bdCHAVE)
                        ) MOVAUX
                  JOIN VEF_EMP_TMOVSAIITENS itens ON (itens.BDCODEMP = movaux.BDCODEMP AND itens.BDCHAVE = movaux.BDCHAVE) 
                  JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = itens.BDCODNAT AND ((nat.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.BDNAOEXPEFDCONT)) <> TRIM('TRUE'))) ) 
                  JOIN VW_INT_SPEDPISCOFINS_REF empaux ON (movaux.bdcodemp = empaux.bdcodemp AND empaux.bdsomenteblocop <> 'TRUE')
                  LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON ((select RDB$GET_CONTEXT('USER_SESSION', 'W_EXPORTAPORSCP') from RDB$DATABASE) = 'TRUE') and (EMPSCP.BDCODEMP = itens.BDCODEMP) AND (EMPSCP.BDREFEMP = itens.BDREFSOC) AND (EMPSCP.BDCODSCP = itens.BDCODSCP)
                  ) mov 
                  LEFT OUTER JOIN VW_TEMPRESAS_REF ref ON (ref.bdCODEMP = mov.bdCODEMP)
                  LEFT OUTER JOIN VEF_EMP_TD100SAI d100 ON (d100.bdCODEMP = mov.bdCODEMP AND d100.bdCHAVE = mov.BDCHAVE)
                  LEFT OUTER JOIN VEF_EMP_TC500SAI c500 ON (c500.bdCODEMP = mov.bdCODEMP AND c500.bdCHAVE = mov.BDCHAVE)
                  LEFT OUTER JOIN VEF_EMP_TD500SAI d500 ON (d500.bdCODEMP = mov.bdCODEMP AND d500.bdCHAVE = mov.BDCHAVE)
                  LEFT OUTER JOIN VEF_EMP_TMOVPROSAI MOVPRO ON (MOVPRO.BDCODEMP = mov.BDCODEMP AND MOVPRO.BDCHAVE = mov.BDCHAVE AND MOVPRO.BDORDEM = mov.BDORDEM)
                  LEFT OUTER JOIN  (SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) BDCHAVE, BDCODEMPSUC FROM TOL_VEF_EMP_TMOVSAI GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM,BDCODEMPSUC) tol
                       ON (tol.bdcodemp = mov.bdcodemp AND tol.bdchavesai = mov.bdchave AND tol.bdordem = mov.bdordem) 
                  LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.BDCODEMP = tol.BDCODEMPSUC AND lan.bdchave = tol.BDCHAVE)
                  LEFT OUTER JOIN PLANOS_TPLA ccl ON (COALESCE(movpro.bdCODPLAPADRAO,lan.bdCODPLAPADRAO,d100.bdCODPLAPADRAO,c500.bdCODPLAPADRAO,d500.bdCODPLAPADRAO) = ccl.bdCODPLAPADRAO AND COALESCE(movpro.bdCODTPLA,lan.bdCREDITO,d100.bdCODTPLA,c500.bdCODTPLA,d500.bdCODTPLA) = ccl.bdCODTPLA)
                  LEFT OUTER JOIN PLANOS_TPLA_ECF ccle ON (ccle.bdcodplapadraoref = (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_CODPLAPADRAOREF') FROM RDB$DATABASE) AND
                                                           ccle.bdano = (SELECT FIRST 1 BDANO 
                                                                         FROM PLANOS_TPLA_ECF 
                                                                         WHERE CAST(BDANO || '01' AS INTEGER) <= mov.bdreflan AND 
                                                                           BDCODTPLAREF IS NOT NULL AND 
                                                                           CCLE.BDCODPLAPADRAO = BDCODPLAPADRAO AND 
                                                                           CCLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF AND 
                                                                           CCLE.BDCODTPLA = BDCODTPLA 
                                                                         ORDER BY BDANO DESC 
                                                                         ) AND 
                                                           ccle.bdcodplapadrao = ccl.bdcodplapadrao AND ccle.bdcodtpla = ccl.bdcodtpla) 
                  LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO cclep ON (ccle.BDCODPLAPADRAOREF = cclep.BDCODPLAPADRAOREF AND CCLE.BDCODTPLAREF = cclep.BDCODTPLAREF) 
                  LEFT OUTER JOIN  (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) BDCHAVE,BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM,BDCODEMPSUC) tolrat
                       ON (tolrat.bdcodemp = mov.bdcodemp AND tolrat.bdchavelan = mov.bdchave AND tolrat.bdordem = mov.bdordem) 
                  LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat ON (lanrat.BDCODEMP = tolrat.BDCODEMPSUC AND lanrat.bdchave = tolrat.BDCHAVE)
                  LEFT OUTER JOIN planos_tpla cclrat ON (COALESCE(MOVPRO.BDCODPLAPADRAO,lanrat.BDCODPLAPADRAO) = cclrat.bdcodplapadrao AND COALESCE(MOVPRO.BDCODTPLA,lanrat.bdcredito) = cclrat.bdcodtpla) 
                  LEFT OUTER JOIN PLANOS_TPLA_ECF ccderat ON  (ccderat.bdcodplapadraoref = (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_CODPLAPADRAOREF') FROM RDB$DATABASE) AND
                                                               ccderat.bdano = (SELECT FIRST 1 BDANO 
                                                                                FROM PLANOS_TPLA_ECF 
                                                                                WHERE CAST(BDANO || '01' AS INTEGER) <= lanrat.bdreferencia AND 
                                                                                  BDCODTPLAREF IS NOT NULL AND 
                                                                                  ccderat.BDCODPLAPADRAO = BDCODPLAPADRAO AND 
                                                                                  ccderat.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF AND 
                                                                                  ccderat.BDCODTPLA = BDCODTPLA 
                                                                                ORDER BY BDANO DESC 
                                                                                ) AND 
                                                               ccderat.bdcodplapadrao = cclrat.bdcodplapadrao AND ccderat.bdcodtpla = cclrat.bdcodtpla) 
                  LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO ccderatp ON (CCDERAT.BDCODPLAPADRAOREF = ccderatp.BDCODPLAPADRAOREF AND CCDERAT.BDCODTPLAREF = ccderatp.BDCODTPLAREF) 
 ) mov
     JOIN tempresas emp ON (MOV.BDCODEMP = emp.bdcodemp)
     LEFT OUTER JOIN VEF_EMP_TC100SAI c100 ON (mov.bdcodemp = c100.bdcodemp AND mov.bdchave = c100.bdchave) 
     LEFT OUTER JOIN VEF_EMP_TC500SAI c500 ON (mov.bdcodemp = c500.bdcodemp AND mov.bdchave = c500.bdchave) 
     LEFT OUTER JOIN VEF_BASE_TTABCODCONS codcons ON (c500.BDORDEMCONS = codcons.BDORDEMCONS) 
     LEFT OUTER JOIN VEF_BASE_TCADINFCOM cadinf ON (c500.bdordeminfcom = cadinf.bdordeminfcom) 
     LEFT OUTER JOIN vef_base_ttabcstcof cstcof ON (MOV.bdcodcstCOF = cstcof.bdcodcstcof) 
     LEFT OUTER JOIN vef_base_ttabcstpis cstpis ON (MOV.bdcodcstpis = cstpis.bdcodcstpis)
     JOIN TTERCEIRO_REF TER on (TER.BDCODTER = MOV.BDCODTER and TER.BDREFEMP = coalesce((select max(RF2.BDREFEMP)
                                                                                         from TTERCEIRO_REF RF2
                                                                                         where RF2.BDCODTER = TER.BDCODTER and
                                                                                               RF2.BDREFEMP <= (select BDDATA
                                                                                                                from SP_PARSE_DATE(cast((select RDB$GET_CONTEXT('USER_SESSION', 'W_DT_INI')
                                                                                                                                         from RDB$DATABASE) as date), 'YYYYMM'))), 
                                                                                         (select min(RF2.BDREFEMP)
                                                                                                                                  from TTERCEIRO_REF RF2
                                                                                                                                  where RF2.BDCODTER = TER.BDCODTER))) 


     LEFT OUTER JOIN tcidade CID ON (TER.BDCODCID = CID.bdCODCID) 
     LEFT OUTER JOIN tuf UF ON (CID.BDCODUF = UF.bdCODUF) 
     LEFT OUTER JOIN VEF_EMP_TD100SAI d200 ON (mov.bdcodemp = d200.bdcodemp AND mov.bdchave = d200.bdchave) 
     LEFT OUTER JOIN vef_base_ttabcstcof cstcofd200 ON (d200.bdcodcstCOF = cstcofd200.bdcodcstcof) 
     LEFT OUTER JOIN vef_base_ttabcstpis cstpisd200 ON (d200.bdcodcstpis = cstpisd200.bdcodcstpis) 
     LEFT OUTER JOIN VEF_BASE_TTAB_NATREC natrecd200 ON (d200.BDCODNATREC = natrecd200.BDCODNATREC) 
     LEFT OUTER JOIN VEF_EMP_TD500SAI D600 ON (mov.bdcodemp = D600.bdcodemp AND mov.bdchave = D600.bdchave) 
     LEFT OUTER JOIN VEF_BASE_TTAB_NATREC natrecd600 ON (d600.BDCODNATREC = natrecd600.BDCODNATREC) 
     LEFT OUTER JOIN VEF_BASE_TTABTPREC TPRECD600 ON (d600.BDCODTPREC = TPRECD600.BDCODTPREC) 
     LEFT OUTER JOIN VEF_BASE_TCADINFCOM cadinfd600 ON (cadinfd600.bdordeminfcom = d600.bdordeminfcom) 
     LEFT OUTER JOIN vef_base_ttabcstpis cstpisd600 ON (d600.bdcodcstpis = cstpisd600.bdcodcstpis) 
     LEFT OUTER JOIN vef_base_ttabcstcof cstcofd600 ON (d600.bdcodcstCOF = cstcofd600.bdcodcstcof) 
     LEFT OUTER JOIN VEF_BASE_TTABINFRETE tabifc100 ON (c100.BDINDFRETE = tabifc100.BDORDEMFRETE) 
     LEFT OUTER JOIN vef_base_ttabmodelolan modlan ON (modlan.bdmodelo = mov.bdmodelo) 
     LEFT OUTER JOIN tpais paisTer ON (paisTer.BDCODPAIS = ter.bdCODPAIS) 
   )A 
    LEFT OUTER JOIN TCADPRO_VINC PRO ON (A.bdemp = PRO.BDCODEMP AND A.BDCODPROD = PRO.BDCODPROD) 
    LEFT OUTER JOIN TUNIDADEMEDIDA UM ON (PRO.BDCODUNIMED = UM.BDCODUNIMED) 
    LEFT OUTER JOIN VEF_BASE_TTABCSTICMS CSTICMS ON (CSTICMS.BDCODCSTICMS = A.BDCODCSTICMS) 
    LEFT OUTER JOIN VEF_BASE_TTABCSTIPI CSTIPI ON (CSTIPI.BDCODCSTIPI = A.BDCODCSTIPI) 
    LEFT OUTER JOIN VEF_BASE_TTAB_NATREC NATREC ON (NATREC.BDCODNATREC = A.BDCODNATRECPROD) 
    LEFT OUTER JOIN VEF_EMP_TENETELE D601_D605 ON (A.bdemp = D601_D605.BDCODEMP AND A.BDCHAVE = D601_D605.BDCHAVE AND A.BDORDEM = D601_D605.BDORDEM AND A.BDORDEMPRO = D601_D605.BDORDEMPRO)
    LEFT OUTER JOIN VEF_BASE_TTABCLASSENETEL D601_D605CLASS ON(D601_D605CLASS.BDCODCLAENETEL = D601_D605.BDCODCLAENETEL) -- Alt.: #236871 - Deve buscar o codigo de exportacao...
  ORDER BY  A.bdcodmatriz, A.bdemp, A.bdchave, A.bdordem, A.BDORDEMPRO
;

CREATE OR ALTER VIEW VW_VRH_BASE_TTERC_TDEP_REF(
    BDCODTER,
    BDCODDPNTERC,
    BDREFDPN,
    BDPARENESCODPNTERC,
    BDNOMEDPNTERC,
    BDDATANASCDPNTERC,
    BDCPFDPNTERC,
    BDINVALIDODPNTERC,
    BDCODCID,
    BDCARTDPNTERC,
    BDREGDPNTERC,
    BDLIVDPNTERC,
    BDFOLDPNTERC,
    BDDATAENTREDPNTERC,
    BDDATABAUXADPNTERC,
    BDDPNTERC,
    BDREFIRDPNTERC,
    BDMATRICULADPNTERC,
    BDTIPODEPESOCIAL,
    BDUNIVERSITARIO,
    BDDESCRDEPTERC)
AS
SELECT BASE.bdcodter, BASE.bdcoddpnterc, V.bdrefdpn, V.bdparenescodpnterc, V.bdnomedpnterc, v.bddatanascdpnterc, v.bdcpfdpnterc, v.bdinvalidodpnterc, BASE.bdcodcid, BASE.bdcartdpnterc,
BASE.bdregdpnterc, BASE.bdlivdpnterc, BASE.bdfoldpnterc, BASE.bddataentredpnterc, BASE.bddatabauxadpnterc, BASE.bddpnterc, BASE.bdrefirdpnterc, BASE.bdmatriculadpnterc, BASE.bdtipodepesocial,
BASE.bduniversitario, v.BDDESCRDEPTERC
FROM (
  SELECT
      X.bdcodter,
      X.bdcoddpnterc,
      COALESCE
  (
      (SELECT MAX(d2.bdrefdpn) FROM VRH_BASE_TTERC_TDEP_REF d2 WHERE d2.bdcodter = x.bdcodter AND d2.bdcoddpnterc = x.bdcoddpnterc AND CAST(d2.bdrefdpn AS VARCHAR(6)) <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)),
      (SELECT MIN(d1.bdrefdpn) FROM VRH_BASE_TTERC_TDEP_REF d1 WHERE d1.bdcodter = x.bdcodter AND d1.bdcoddpnterc = x.bdcoddpnterc)
  ) AS bdrefdpn,
      X.bdcodcid,
      x.bdcartdpnterc,
      x.bdregdpnterc,
      x.bdlivdpnterc,
      x.bdfoldpnterc,
      x.bddataentredpnterc,
      x.bddatabauxadpnterc,
      x.bddpnterc,
      x.bdrefirdpnterc,
      x.bdmatriculadpnterc,
      x.bdtipodepesocial,
      x.bduniversitario
  FROM  VRH_BASE_TTERC_TDEP x
) AS BASE
left outer join VRH_BASE_TTERC_TDEP_REF v on (BASE.bdcodter = v.bdcodter AND BASE.bdcoddpnterc = v.bdcoddpnterc AND BASE.bdrefdpn = v.bdrefdpn)
;

CREATE OR ALTER VIEW VW_VSUC_TLAN_EXPORTACAO(
    BDCODEMP,
    BDCHAVE,
    BDCODPLAPADRAO,
    BDDEBITO,
    BDCREDITO,
    BDCODHIST,
    BDCODTPHI,
    BDLOTE,
    BDDATA,
    BDVALOR,
    BDCOMPL,
    BDDATALAN,
    BDHORALAN,
    BDDATALANINICIAL,
    BDHORALANINICIAL,
    BDTIPOLAN,
    BDDCTO,
    BDCONCD,
    BDCONCC,
    BDCHAVEZER,
    BDCODUSU,
    BDREFERENCIA,
    BDCODTERCEIROD,
    BDCODTERCEIROC,
    BDTIPOFCONT,
    BDDLPA,
    BDDMPL,
    BDDOAR,
    BDDFC,
    BDDVA,
    BDBE,
    BDLALUR,
    BDCODUSUALTERACAO,
    BDDATALANALT,
    BDHORALANALT,
    BDCODIMPATIVA,
    BDCHAVEONLINE,
    BDTIPOLANCFILIAL,
    BDFILIAL,
    BDCONTABILIZACAO,
    BDTRANSACAO,
    BDTRANFECHADA,
    BDCHAVEVINC,
    BDCHAVETRANSFBEM,
    BDCODTRANS_CONTA,
    BDCODVLRPRES,
    BDTIPOCONC,
    BDCONCILIACAOPENDENTE,
    BDCHAVETRANSFCUSTOINCORP,
    BDCHAVEPROCEVOLUCOBRA,
    BDLANCAEXTEMPORANEO,
    BDDATAEXTEMPORANEO,
    BDCODTIPOFOL)
AS
select LAN.BDCODEMP, LAN.BDCHAVE, LAN.BDCODPLAPADRAO, LAN.BDDEBITO, LAN.BDCREDITO, LAN.BDCODHIST, LAN.BDCODTPHI,
       LAN.BDLOTE, LAN.BDDATA, LAN.BDVALOR, replace(coalesce(LAN.BDCOMPL, cast((substring(COMPL.BDCOMPL FROM 1 FOR 200)) as varchar(200)), ''), '
', ' '), LAN.BDDATALAN, LAN.BDHORALAN, LAN.BDDATALANINICIAL, LAN.BDHORALANINICIAL, LAN.BDTIPOLAN, LAN.BDDCTO,
       LAN.BDCONCD, LAN.BDCONCC, LAN.BDCHAVEZER, LAN.BDCODUSU, LAN.BDREFERENCIA, LAN.BDCODTERCEIROD, LAN.BDCODTERCEIROC,
       LAN.BDTIPOFCONT, LAN.BDDLPA, LAN.BDDMPL, LAN.BDDOAR, LAN.BDDFC, LAN.BDDVA, LAN.BDBE, LAN.BDLALUR,
       LAN.BDCODUSUALTERACAO, LAN.BDDATALANALT, LAN.BDHORALANALT, LAN.BDCODIMPATIVA, LAN.BDCHAVEONLINE,
       LAN.BDTIPOLANCFILIAL, LAN.BDFILIAL, LAN.BDCONTABILIZACAO, LAN.BDTRANSACAO, LAN.BDTRANFECHADA, LAN.BDCHAVEVINC,
       LAN.BDCHAVETRANSFBEM, LAN.BDCODTRANS_CONTA, LAN.BDCODVLRPRES, LAN.BDTIPOCONC, LAN.BDCONCILIACAOPENDENTE,
       LAN.BDCHAVETRANSFCUSTOINCORP, LAN.BDCHAVEPROCEVOLUCOBRA, LAN.BDLANCAEXTEMPORANEO, LAN.BDDATAEXTEMPORANEO, LAN.BDCODTIPOFOL
from VSUC_EMPRESAS_TLAN LAN
left outer join VSUC_EMPRESAS_TLAN_COMPL COMPL on (COMPL.BDCODEMP = LAN.BDCODEMP and COMPL.BDCHAVE = LAN.BDCHAVE)
;

CREATE OR ALTER VIEW VW_USUARIOS_SECAO(
    BDCODUSU,
    BDNOMUSU,
    BDCODUSUINTRANET,
    BDNOMUSUINTRANET,
    bdintegraserv,
    bdismaster)
AS
select sec.BDCODUSU, usu.bdnomusu, sec.BDCODUSUINTRANET, sec.BDNOMUSUINTRANET, usu.bdintegraserv,
       case when((usu.bdcodusu in(1,2,3))or(usu.bdnomusu='schip'))then true
            when(exists(select first 1 bdcodgrupo from tgrupousuario_usuario where(bdcodusu=usu.bdcodusu)and(bdcodgrupo=1)))then true
       else false end as bdismaster
from (
SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_USUARIO'))) AS INTEGER) as BDCODUSU,
       CAST((TRIM(rdb$get_context('USER_SESSION', 'W_CODUSU_INTRANET'))) AS INTEGER) as BDCODUSUINTRANET,
       TRIM(rdb$get_context('USER_SESSION', 'W_NOMUSU_INTRANET')) as BDNOMUSUINTRANET
FROM rdb$database) sec
left outer join tusuario usu on (usu.bdcodusu = sec.BDCODUSU)
;

CREATE OR ALTER VIEW VW_VFIN_TZONA(
    BDCODZONA,
    BDNOMEZONA,
    BDCODCID,
    BDNOMCID)
AS
select
    z.BDCODZONA,
    z.BDNOMEZONA,
    z.BDCODCID,
    cid.BDNOMCID
from TZONA z
inner join TCIDADE cid on (cid.BDCODCID = z.BDCODCID)
;

CREATE OR ALTER VIEW VW_GET_MODULO(
    BDCODSIS,
    BDNOMSIS)
AS
select sec.BDCODSIS, sis.bdNOMSIS from (
SELECT CAST((TRIM(rdb$get_context('USER_SESSION', 'W_CODSIS'))) AS INTEGER) as BDCODSIS
FROM rdb$database) sec
left outer join tsistema sis on (sis.bdcodsis = sec.BDCODsis)
;

CREATE OR ALTER VIEW VW_VRH_BASE_TVERBAS_FICHA_OUT(
    BDCODVER,
    BDCLAVER)
AS
SELECT
  X.BDCODVER,
  X.BDCLAVER
FROM VRH_BASE_TVERBAS X
JOIN VRH_BASE_TCONF_FICHA_OUT Y ON (X.BDCLAVER STARTING WITH Y.BDCLAVER)
;

SET TERM ^ ;

CREATE OR ALTER TRIGGER vrh_emp_tdep_ref_bi0 for vrh_emp_tdep_ref
active before insert position 0
AS
begin
  IF (NEW.BDPARENESCODPN IS NULL) THEN
     NEW.BDPARENESCODPN = 0;
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TTERC_TDEP_REF_BI0 FOR VRH_BASE_TTERC_TDEP_REF
ACTIVE BEFORE INSERT POSITION 0
AS
declare variable vNovoCod Integer;
begin
  IF ((NEW.bdcoddpnterc IS NULL) OR (NEW.bdcoddpnterc = 0)) THEN
    BEGIN
      SELECT MAX(bdcoddpnterc) FROM vrh_base_tterc_tdep WHERE NEW.BDCODTER = BDCODTER INTO :vNovoCod;
      NEW.bdcoddpnterc = :vNovoCod;
    END
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TDEP_REF_BI0 FOR VRH_EMP_TDEP_REF
ACTIVE BEFORE INSERT POSITION 0
AS
declare variable vNovoCod Integer;
begin
  IF ((NEW.BDCODDPN IS NULL) OR (NEW.BDCODDPN = 0)) THEN
    BEGIN
      SELECT MAX(BDCODDPN) FROM vrh_emp_tdep WHERE BDCODEMP = NEW.BDCODEMP AND NEW.BDCODCOL = BDCODCOL INTO :vNovoCod;
      NEW.BDCODDPN = :vNovoCod;
    END

  IF (NEW.BDPARENESCODPN IS NULL) THEN
     NEW.BDPARENESCODPN = 0;
end
^

-- Solicita??o: 22602 Denicio 09/02/2018
create or alter procedure SP_VRH_EXCLUI_INCONFORMIDADE (
    PREMP integer,
    PREVENTO varchar(20),
    PRCADASTRO integer,
    PRCHAVECAD varchar(50),
    PRREF integer,
    PRCAMPO varchar(30))
as
declare variable WCODEMP integer;
declare variable WCAMPO varchar(30);
declare variable WCHAVECAD varchar(50);
declare variable WREFINC integer;
declare variable WREFEMP integer;
declare variable WEVENTO integer;
begin
  select FAS.BDREFINITABELA
  from VRH_ESOCIAL_TFASEAMENTO FAS
  where FAS.BDCODEMP = :premp into :wrefemp;

  select first 1 BDCODTIPO from VRH_ESOCIAL_TTIPO_ARQ where upper(BDDESCRICAO) starting(upper(trim(:prevento))) into :wevento;

  for select BDCODEMP, BDCAMPO, BDCHAVECAD, BDREFINC
      from VRH_ESOCIAL_INCONFORMIDADES
      where BDCODEMP = :premp and BDCADASTRO = :prcadastro and BDEVENTO = :wevento and BDCHAVECAD like :prchavecad and
            BDCAMPO = :prcampo and ((BDREFINC = :prref) or (:prref <= :wrefemp and BDREFINC <= :prref))
  into :wcodemp, :wcampo, :wchavecad, :wrefinc do
  begin
    delete from VRH_ESOCIAL_INCONFORMIDADES where BDCODEMP = :wcodemp and BDEVENTO = :wevento and BDCAMPO = :wcampo and BDCHAVECAD = :wchavecad and BDREFINC = :wrefinc;
  end
end^

CREATE OR ALTER TRIGGER VRH_BASE_TEXPVSUP_BI0 FOR VRH_BASE_TEXPVSUP
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;
begin
  if (coalesce(new.bdcodigo, 0) = 0) then
     begin
       select coalesce(max(BDCODIGO) + 1, 1) from VRH_BASE_TEXPVSUP where BDCODEMP = new.bdcodemp into :vcod;
       new.bdcodigo = vcod;
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TINTERMITENTE_BI0 FOR VRH_EMP_TINTERMITENTE
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;
begin
  if (COALESCE(new.bdcodcontti, 0) = 0) then
     begin
       select COALESCE(MAX(BDCODCONTTI) + 1, 1) from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDCODCONTTI < 999999 into :vcod;
       new.bdcodcontti = :vcod;
     end

  /*Wesley Kowalski | Data: 30/08/2019 | Solicitação: 124832 */   
  IF ((TRIM(NEW.BDCODCONTESOCIAL) = '') or (NEW.BDCODCONTESOCIAL IS NULL))  THEN
    BEGIN
      NEW.BDCODCONTESOCIAL = cast(NEW.BDCODCONTTI AS VARCHAR(30));
      IF (char_length(NEW.BDCODCONTESOCIAL) < 2) then
        NEW.BDCODCONTESOCIAL = '0'||NEW.BDCODCONTESOCIAL;
    END

  if (upper(coalesce(new.bdapenasrescisao, 'FALSE')) = 'FALSE') then
     begin
       vcod = null;
       select first 1 BDCODCOL from VRH_EMP_TRESCISAO
       where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and
             ((BDREFRESCISAO = SUBSTRING(CAST(new.bddatainiservti AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(new.bddatainiservti AS VARCHAR(10)) FROM 6 FOR 2)) or
              (BDREFRESCISAO = SUBSTRING(CAST(new.bddatafimservti AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(new.bddatafimservti AS VARCHAR(10)) FROM 6 FOR 2)))
       into :vcod;
     
       -- Tem rescisão lançada
       if (coalesce(vcod, 0) = new.bdcodcol and upper(coalesce(new.bdconvrescti, 'FALSE')) = 'TRUE') then
          begin
            vcod = null;
            select first 1 BDCODCONTTI from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and upper(coalesce(BDAPENASRESCISAO, 'FALSE')) = 'TRUE' into :vcod;
     
            -- Se tiver convocação fantasma lançada deve excluí-lá lá lá lá lá iá
            if (coalesce(vcod, 0) > 0) then
               begin
                 delete from VRHF_EMP_TFOLHAINT where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDCODCONTTI = :vcod;
                 delete from VRHF_EMP_TFOLHATOMINT where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDCODCONTTI = :vcod;
                 delete from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDCODCONTTI = :vcod;
               end
          end
     end
end
^

CREATE OR ALTER trigger vrh_emp_tverde_amarelo_bi0 for vrh_emp_tverde_amarelo
active before insert position 0
AS
 declare variable vcod INTEGER;
begin
   if (COALESCE(new.bdcodcont, 0) = 0) then
     begin
       select COALESCE(MAX(BDCODCONT) + 1, 1) from VRH_EMP_TVERDE_AMARELO where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol into :vcod;
       new.bdcodcont = :vcod;
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TINTERMITENTE_BU0 FOR VRH_EMP_TINTERMITENTE
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  IF (TRIM(NEW.BDCODCONTESOCIAL) = '') THEN
    BEGIN
      NEW.BDCODCONTESOCIAL = cast(OLD.BDCODCONTTI AS VARCHAR(30));
      IF (char_length(NEW.BDCODCONTESOCIAL) < 2) then
        NEW.BDCODCONTESOCIAL = '0'||NEW.BDCODCONTESOCIAL;
    END
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TINTERMITENTE_AD0 FOR VRH_EMP_TINTERMITENTE
ACTIVE AFTER DELETE POSITION 0
AS
  declare variable wcol INTEGER;
  declare variable wref INTEGER;
  declare variable wdata DATE;
  declare variable whora TIME;
begin
  wcol = null;
  select first 1 BDCODCOL, BDREFRESCISAO, BDDATARESCISAO
  from VRH_EMP_TRESCISAO
  where BDCODEMP = old.bdcodemp and BDCODCOL = old.bdcodemp and
        ((BDREFRESCISAO = SUBSTRING(CAST(old.bddatainiservti AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(old.bddatainiservti AS VARCHAR(10)) FROM 6 FOR 2)) or
         (BDREFRESCISAO = SUBSTRING(CAST(old.bddatafimservti AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(old.bddatafimservti AS VARCHAR(10)) FROM 6 FOR 2)))
  into :wcol, :wref, :wdata;

  -- verifica se existe rescisão lançada
  if (coalesce(wcol, 0) = old.bdcodcol) then
     begin
       -- verifica se existem outras convocações dentro da competência da rescisão
       wcol = null;
       select first 1 BDCODCOL
       from VRH_EMP_TINTERMITENTE
       where BDCODEMP = old.bdcodemp and BDCODCOL = old.bdcodcol and upper(coalesce(BDCONVRESCTI, 'FALSE')) = 'TRUE' and
             BDCODCONTTI <> old.bdcodcontti and
            ((SUBSTRING(CAST(BDDATAINISERVTI AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISERVTI AS VARCHAR(10)) FROM 6 FOR 2) = :wref) or
             (SUBSTRING(CAST(BDDATAFIMSERVTI AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSERVTI AS VARCHAR(10)) FROM 6 FOR 2) = :wref))
       into :wcol;

       -- Não existem outras convocações, então deve criar uma convocação para a rescisão
       if (coalesce(wcol, 0) = 0) then
          begin
            insert into VRH_EMP_TINTERMITENTE(BDCODEMP, BDCODCOL, BDCODCONTTI, BDDESCCONTRATOTI, BDDATAINISERVTI, BDDATAFIMSERVTI, BDAPENASRESCISAO, BDCONVRESCTI)
            values (old.bdcodemp, old.bdcodcol, 999999, 'RESCISÃO INTERMITENTE', :wdata, :wdata, 'TRUE', 'TRUE');

            select CURRENT_TIME from RDB$DATABASE into :whora;

            insert into VRH_EMP_TINTERMITENTE_ACEI(BDCODEMP,BDCODCOL,BDCODCONTTI,BDDATAACEITETI,BDHORAACEITETI,BDCOMUNICACEITETI,BDSTATUSACEITETI)
            values (old.bdcodemp, old.bdcodcol, 999999, :wdata, :whora, 'RESCISÃO INTERMITENTE', 2);
          end
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TINTERMITENTE_AU0 FOR VRH_EMP_TINTERMITENTE
ACTIVE AFTER UPDATE POSITION 0
AS
  declare variable vcod INTEGER;
  declare variable whora TIME;
begin
  if (upper(coalesce(new.bdapenasrescisao, 'FALSE')) = 'FALSE') then
     begin
       vcod = null;
       select first 1 BDCODCOL from VRH_EMP_TRESCISAO
       where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and
             ((BDREFRESCISAO = SUBSTRING(CAST(new.bddatainiservti AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(new.bddatainiservti AS VARCHAR(10)) FROM 6 FOR 2)) or
              (BDREFRESCISAO = SUBSTRING(CAST(new.bddatafimservti AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(new.bddatafimservti AS VARCHAR(10)) FROM 6 FOR 2)))
       into :vcod;
     
       -- Tem rescisão lançada
       if (coalesce(vcod, 0) = new.bdcodcol) then
          begin
            if (upper(coalesce(new.bdconvrescti, 'FALSE')) = 'TRUE') then
               begin
                 vcod = null;
                 select first 1 BDCODCONTTI from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and upper(coalesce(BDAPENASRESCISAO, 'FALSE')) = 'TRUE' into :vcod;
          
                 -- Se tiver convocação fantasma lançada deve excluí-lá lá lá lá lá iá
                 if (coalesce(vcod, 0) > 0) then
                    begin
                      delete from VRHF_EMP_TFOLHAINT where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDCODCONTTI = :vcod;
                      delete from VRHF_EMP_TFOLHATOMINT where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDCODCONTTI = :vcod;
                      delete from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDCODCONTTI = :vcod;
                    end
               end
            else
               begin
                 vcod = null;
                 select first 1 BDCODCONTTI from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and upper(coalesce(BDAPENASRESCISAO, 'FALSE')) = 'TRUE' into :vcod;
          
                 -- Se não tiver convocação fantasma deve criá-lá lá lá lá lá iá
                 if (coalesce(vcod, 0) = 0) then
                    begin
                      insert into VRH_EMP_TINTERMITENTE(BDCODEMP, BDCODCOL, BDCODCONTTI, BDDESCCONTRATOTI, BDDATAINISERVTI, BDDATAFIMSERVTI, BDAPENASRESCISAO, BDCONVRESCTI)
                      values (new.bdcodemp, new.bdcodcol, 999999, 'RESCISÃO INTERMITENTE', new.bddatainiservti, new.bddatainiservti, 'TRUE', 'TRUE');
          
                      select CURRENT_TIME from RDB$DATABASE into :whora;
          
                      insert into VRH_EMP_TINTERMITENTE_ACEI(BDCODEMP,BDCODCOL,BDCODCONTTI,BDDATAACEITETI,BDHORAACEITETI,BDCOMUNICACEITETI,BDSTATUSACEITETI)
                      values (new.bdcodemp, new.bdcodcol, 999999, new.bddatainiservti, :whora, 'RESCISÃO INTERMITENTE', 2);
                    end
               end
          end
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TINTERMITENTE_ACEI_BI0 FOR VRH_EMP_TINTERMITENTE_ACEI
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;
  declare variable vcodcontrato INTEGER;

begin
  if (COALESCE(new.bdcodaceiteti, 0) = 0) then
     begin
       select COALESCE(MAX(BDCODACEITETI) + 1, 1) from VRH_EMP_TINTERMITENTE_ACEI where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDCODCONTTI = new.bdcodcontti into :vcod;
       new.bdcodaceiteti = :vcod;
     end
  if (coalesce(new.BDCODCONTTI, 0) = 0) then
     begin
       select BDCODCONTTI from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDIDRHNET = new.bdidrhnet into :vcodcontrato;
       new.BDCODCONTTI = :vcodcontrato;
     end
end
^

CREATE OR ALTER TRIGGER vrh_emp_tinter_qhdias_bi0 for vrh_emp_tintermitente_qhdias
active before insert position 0
AS
  declare variable vcodcontrato INTEGER;

begin
  if (coalesce(new.BDCODCONTTI, 0) = 0) then
     begin
       select BDCODCONTTI from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDIDRHNET = new.bdidrhnet into :vcodcontrato;
       new.BDCODCONTTI = :vcodcontrato;
     end
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSAIQ48_BI0 FOR VEF_EMP_TMOVSAIQ48
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovsai WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

  IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmovsaiitens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Ordem;
      NEW.BDORDEM = vNova_Ordem;
    END
END
^

CREATE OR ALTER trigger vef_emp_tmoventstatus_bi0 for vef_emp_tmoventstatus
active before insert position 0
as
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    if ((new.BDORDEMSTATUS is null) or (new.BDORDEMSTATUS = 0)) then
    begin
    select first 1 coalesce(STATUS.BDORDEMSTATUS + 1, 1)
    from VEF_EMP_TMOVENTSTATUS STATUS
    where STATUS.BDCODEMP = new.BDCODEMP and
          STATUS.BDCHAVE = new.BDCHAVE
    order by STATUS.BDORDEMSTATUS desc
    into new.BDORDEMSTATUS;

    if (new.bdordemstatus is null) then
      new.bdordemstatus = 1;
    end
  end
end
^

CREATE OR ALTER trigger vef_emp_tmovsaistatus_bi0 for vef_emp_tmovsaistatus
active before insert position 0
as
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    if ((new.BDORDEMSTATUS is null) or (new.BDORDEMSTATUS = 0)) then
    begin
    select first 1 coalesce(STATUS.BDORDEMSTATUS + 1, 1)
    from VEF_EMP_TMOVSAISTATUS STATUS
    where STATUS.BDCODEMP = new.BDCODEMP and
          STATUS.BDCHAVE = new.BDCHAVE
    order by STATUS.BDORDEMSTATUS desc
    into new.BDORDEMSTATUS;

    if (new.bdordemstatus is null) then
      new.bdordemstatus = 1;
    end
  end
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TREDZSTATUS_BI0 FOR VEF_EMP_TREDZSTATUS
ACTIVE BEFORE INSERT POSITION 0
as
begin
  if ((new.BDORDEMSTATUS is null) or (new.BDORDEMSTATUS = 0)) then
  begin
    select first 1 coalesce(STATUS.BDORDEMSTATUS + 1, 1)
    from VEF_EMP_TREDZSTATUS STATUS
    where STATUS.BDCODEMP = new.BDCODEMP and
          STATUS.BDCHAVE = new.BDCHAVE
    order by STATUS.BDORDEMSTATUS desc
    into new.BDORDEMSTATUS;

    if (new.bdordemstatus is null) then
      new.bdordemstatus = 1;
  end
end^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVENTQ48_BI0 FOR VEF_EMP_TMOVENTQ48
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNova_Ordem INTEGER;
  DECLARE VARIABLE vchavelan INTEGER;
BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)), 1) FROM vef_emp_tmovent WHERE (bdcodemp = NEW.bdcodemp) INTO vchavelan;
      NEW.bdchave = vchavelan;
    END

  IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM vef_emp_tmoventitens WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO vNova_Ordem;
      NEW.BDORDEM = vNova_Ordem;
    END
END
^

CREATE OR ALTER TRIGGER TLOG_ERRO_RHNET_BI0 FOR TLOG_ERRO_RHNET
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (COALESCE(new.bdcodlog, 0) = 0) then
     new.bdcodlog = GEN_ID(gen_log_erro_rhnet, 1);

  select localtimestamp from rdb$database into new.bddatahora;

  new.BDSTATUS = coalesce(new.BDSTATUS, 0);
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TCALCVESP_PADRAO_BI0 FOR VRH_BASE_TCALCVESP_PADRAO
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODCVE IS NULL) OR (NEW.BDCODCVE = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODCVE) + 1, 1)
       FROM VRH_BASE_TCALCVESP_PADRAO
       INTO :vNovoCod;

       NEW.BDCODCVE = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VRH_BASE_TCALCITENS_PADRAO_BI0 FOR VRH_BASE_TCALCITENS_PADRAO
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE novocod INTEGER;
BEGIN
  IF ((NEW.bdCODCIT IS NULL) OR (NEW.BDCODCIT = 0))  THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODCIT) + 1, 1)
       FROM VRH_BASE_TCALCITENS_PADRAO
       WHERE BDCODCTP = NEW.BDCODCTP
       INTO
         novocod;
       NEW.BDCODCIT = novocod;
     END
END
^

CREATE OR ALTER TRIGGER vrh_emp_tcomercnfprodrural_bi0 for vrh_emp_tcomercnfprodrural
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdchave)+1), 1) FROM VRH_EMP_TCOMERCNFPRODRURAL WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.bdchave = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdchave FROM VRH_EMP_TCOMERCNFPRODRURAL WHERE (bdchave = NEW.bdchave) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdchave)+1), 1) FROM VRH_EMP_TCOMERCNFPRODRURAL WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.bdchave = vNova_Chave;
         END
    END
END^

CREATE OR ALTER TRIGGER VRHF_EMP_TCOLCON_MVINC_BI0 FOR VRHF_EMP_TCOLCON_MVINC
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODMV IS NULL) OR (NEW.BDCODMV = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(X.BDCODMV) + 1, 1)
      FROM VRHF_EMP_TCOLCON_MVINC X
      WHERE X.BDCODEMP = NEW.BDCODEMP AND X.BDCODCOL = NEW.BDCODCOL
      INTO :vNovoCod;

      NEW.BDCODMV = :vNovoCod;
    END
END^

CREATE OR ALTER TRIGGER VRHF_BASE_TTERC_MVINC_BI0 FOR VRHF_BASE_TTERC_MVINC
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  NEW.BDIDEMP = COALESCE(NEW.BDCODEMP,0); -- 144124 - Raphael Teodoro - 02/12/2020

  IF ((NEW.BDCODMV IS NULL) OR (NEW.BDCODMV = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(X.BDCODMV) + 1, 1)
      FROM VRHF_BASE_TTERC_MVINC X
      WHERE X.BDIDEMP = NEW.BDIDEMP AND X.BDCODTER = NEW.BDCODTER
      INTO :vNovoCod;

      NEW.BDCODMV = :vNovoCod;
    END
END^

create or alter procedure SP_VRHM_EMP_VINC_DEP_CONV_ATU (
    PREMP varchar(25000),
    PRREF integer,
    PRCOL varchar(32700) = null,
    PRDEP integer = null,
    PROPER integer = 0,
    PRCONV integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREFINI integer,
    BDREFFIM integer,
    BDCODPLACONVSAU integer)
as
declare variable WSQL varchar(32700);
begin
  wsql = 'select conv.bdcodemp,conv.bdcodcol,conv.bdcoddpn,conv.bdcodoperadora,conv.bdcodconvenio,conv.bdrefini,conv.bdreffim,conv.bdcodplaconvsau '||
         'from VRH_EMP_VINC_DEP_CONV conv '||
         'where conv.bdrefini <= '||prref||' and '||
               '((conv.bdreffim >= '||prref||') or (COALESCE(conv.bdreffim, 0) = 0)) ';

  if (COALESCE(premp, '') <> '') then
     wsql = wsql||' and '||replace(upper(:premp), 'BDCODEMP', 'CONV.BDCODEMP');

  if (COALESCE(prcol, '') <> '') then
     wsql = wsql||' and '||replace(upper(:prcol), 'BDCODCOL', 'CONV.BDCODCOL');

  if (COALESCE(prdep, 0) <> 0) then
     wsql = wsql||' and conv.bdcoddpn = '||prdep||' ';

  if (COALESCE(proper, 0) <> 0) then
     wsql = wsql||' and conv.bdcodoperadora = '||proper||' ';

  if (COALESCE(prconv, 0) <> 0) then
     wsql = wsql||' and conv.bdcodconvenio = '||prconv||' ';

  wsql = wsql||' and conv.bdcodplaconvsau = coalesce((select first 1 vinc.BDCODPLACONVSAU from VRHF_BASE_TEMPVINC vinc where vinc.BDCODEMP = conv.bdcodemp and vinc.BDREFEMP <= '||prref||' and vinc.bdcodplaconvsau is not null order by vinc.BDREFEMP DESC),(select first 1 vinc.bdcodplaconvsau from VRHF_BASE_TEMPVINC vinc where vinc.bdcodemp = conv.bdcodemp and vinc.bdcodplaconvsau is not null order by vinc.bdrefemp desc))';

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDCODDPN, :BDCODOPERADORA, :BDCODCONVENIO, :BDREFINI, :BDREFFIM, :BDCODPLACONVSAU do
    suspend;
end^


/* Restore proc. body: SP_VRHM_EMP_DEP_VAL_OP_SAU */
create or alter procedure SP_VRHM_EMP_DEP_VAL_OP_SAU (
    PREMP integer,
    PRREF integer,
    PRCOL integer = null,
    PRDEP integer = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDIDADE integer,
    BDIDADEFAIXA integer,
    BDMENSALIDADE numeric(18,2),
    BDTIPO integer,
    BDMENSFORMULA DM_BOOLEAN)
as
declare variable WSQL varchar(10000);
declare variable WCHAVE varchar(200);
declare variable WVALVER numeric(18,6);
declare variable WCODVERDEPMENS integer;
begin
   wsql = 'select conv.bdcodemp,conv.bdcodcol,conv.bdcoddpn,conv.bdcodplaconvsau,conv.bdcodoperadora,conv.bdcodconvenio,id.bdidade,faixa.bdidade,faixa.bdvalor,faixa.bdtipo, '||
                 'CONV_OP.BDMENSFORMULA, CONV_OP.BDCODVERDEPMENS '||
          'from SP_VRHM_EMP_VINC_DEP_CONV_ATU(';

   if (coalesce(premp, 0) <> 0) then
      wsql = wsql||'''BDCODEMP = '||premp||''',';
   else
      wsql = wsql||'null,';


   wsql = wsql||prref||',';

   if (COALESCE(prcol, 0) = 0) then
      wsql = wsql||'null,';
   else
      wsql = wsql||'''BDCODCOL = '||prcol||''',';

   if (COALESCE(prdep, 0) = 0) then
      wsql = wsql||'null';
   else
      wsql = wsql||prdep;

   wsql = wsql||') conv '||
          'join SP_VRH_EMP_IDADE_COL_DEP(';

   if (coalesce(premp, 0) > 0) then
      wsql = wsql||'''BDCODEMP = '||premp||''',';
   else
      wsql = wsql||'null,';

   if (COALESCE(prcol, 0) = 0) then
      wsql = wsql||'null,';
   else
      wsql = wsql||'''BDCODCOL = '||prcol||''',';

   if (COALESCE(prdep, 0) = 0) then
      wsql = wsql||'null,';
   else
      wsql = wsql||'''BDCODDPN = '||prdep||''',';

   wsql = wsql||prref;

   wsql = wsql||', 1) id ON (conv.bdcodemp = id.bdcodemp AND conv.bdcodcol = id.bdcodcol AND conv.bdcoddpn = id.bdcoddpn) '||
          'JOIN VRH_BASE_CONVENIO_OPERADORAS CONV_OP on (CONV_OP.BDCODPLACONVSAU = conv.BDCODPLACONVSAU and CONV_OP.BDCODOPERADORA = conv.BDCODOPERADORA and CONV_OP.BDCODCONVENIO = conv.BDCODCONVENIO) '||
          'LEFT OUTER JOIN VW_VRHM_FAIXA_CONV_OP_SAU_ATU faixa ON (conv.bdcodconvenio = faixa.bdcodconvenio AND '||
                                                               'conv.bdcodoperadora = faixa.bdcodoperadora AND '||
                                                               'conv.bdcodplaconvsau = faixa.bdcodplaconvsau AND '||
                                                               'faixa.bdidade = (SELECT MAX(x.bdidade) FROM VW_VRHM_FAIXA_CONV_OP_SAU_ATU x '||
                                                                                                       'WHERE x.bdidade <= id.bdidade AND '||
                                                                                                             'conv.bdcodoperadora = x.bdcodoperadora AND '||
                                                                                                             'conv.bdcodplaconvsau = x.bdcodplaconvsau AND '||
                                                                                                             'x.bdcodconvenio = conv.bdcodconvenio)) '||
          ' ORDER BY conv.bdcodemp,conv.bdcodcol,conv.bdcoddpn ';


  for execute statement wsql into
    :BDCODEMP,
    :BDCODCOL,
    :BDCODDPN,
    :BDCODPLACONVSAU,
    :BDCODOPERADORA,
    :BDCODCONVENIO,
    :BDIDADE,
    :BDIDADEFAIXA,
    :BDMENSALIDADE,
    :BDTIPO,
    :BDMENSFORMULA,
    :wcodverdepmens
  do
    begin
      if (upper(coalesce(BDMENSFORMULA, 'FALSE')) = 'TRUE') then
         begin
           wchave = BDCODDPN||'.'||BDCODPLACONVSAU||'.'||BDCODOPERADORA||'.'||BDCODCONVENIO||'.';
           BDMENSALIDADE = 0;
           wvalver = null;
           for
             select BDVALVFND
             from VRHF_EMP_TVERBAFN_DET
             where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFFN = :prref and BDINFAUXFND = :wchave and BDCODVER = :wcodverdepmens
           into :wvalver
           do
             BDMENSALIDADE = BDMENSALIDADE + coalesce(wvalver, 0);

           wvalver = null;
           for
             select BDVALVFTD
             from VRHF_EMP_TVERBAFT_DET
             where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFTOMADOR = :prref and BDINFAUXFTD = :wchave and BDCODVER = :wcodverdepmens
           into :wvalver
           do
             BDMENSALIDADE = BDMENSALIDADE + coalesce(wvalver, 0);

           wvalver = null;
           for
             select BDVALVFND
             from VRHF_EMP_TVERBAINT_DET
             where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFFN = :prref and BDINFAUXFND = :wchave and BDCODVER = :wcodverdepmens
           into :wvalver
           do
             BDMENSALIDADE = BDMENSALIDADE + coalesce(wvalver, 0);

           wvalver = null;
           for
             select BDVALVFTD
             from VRHF_EMP_TVERBATOMINT_DET
             where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFTOMADOR = :prref and BDINFAUXFTD = :wchave and BDCODVER = :wcodverdepmens
           into :wvalver
           do
             BDMENSALIDADE = BDMENSALIDADE + coalesce(wvalver, 0);
         end

    suspend;
    end
end^

/* Restore proc. body: SP_VRHM_EMP_DEP_COP_OP_SAU */
create or alter procedure SP_VRHM_EMP_DEP_COP_OP_SAU (
    PREMP integer,
    PRREF integer,
    PRCOL integer = null,
    PRDEP integer = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREF integer,
    BDVALORCOPARDEP numeric(18,2),
    BDVALORMENSALIDADE numeric(18,2),
    BDNAOPAGAMENSALIDADE DM_BOOLEAN,
    BDCODTIPO integer)
as
declare variable WSQL varchar(5000);
declare variable WSQL2 varchar(500);
declare variable WOK DM_BOOLEAN;
begin
  wsql = 'select psf.bdcodemp, psf.bdcodcol, psf.bdcoddpn,psf.bdcodplaconvsau, psf.bdcodoperadora, psf.bdcodconvenio, max(psf.bdref) '||
         'from VRHM_EMP_COPAR_DEP psf ';

  wsql2 = '';

  if (COALESCE(premp, 0) <> 0) then
     wsql2 = wsql2||'psf.BDCODEMP = '||premp;

  if (COALESCE(prcol, 0) <> 0) then
     begin
       if (wsql2 <> '') then
          wsql2 = wsql2||' and ';
        wsql2 = wsql2||'psf.BDCODCOL = '||prcol||' ';
     end

  if (COALESCE(prdep, 0) <> 0) then
     begin
       if (wsql2 <> '') then
          wsql2 = wsql2||' and ';
       wsql2 = wsql2||'psf.BDCODDPN = '||prdep||' ';
     end

  if (coalesce(prref, 0) > 0) then
     begin
  if (wsql2 <> '') then
          wsql2 = wsql2||' and ';
       wsql2 = wsql2||'psf.bdref <= '||prref||' ';
     end

  if (wsql2 <> '') then
     wsql = wsql||' where '||wsql2;

  wsql = wsql||' group by psf.bdcodemp, psf.bdcodcol, psf.bdcoddpn,psf.bdcodplaconvsau, psf.bdcodoperadora, psf.bdcodconvenio ';

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDCODDPN, :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDREF do
    begin
      BDCODTIPO = null;
      BDVALORCOPARDEP = 0;
      BDVALORMENSALIDADE = null;
      BDNAOPAGAMENSALIDADE = null;
      if (coalesce(BDREF, 0) = :prref) then
         select first 1 BDVALORCOPARDEP, BDCODTIPO
         from VRHM_EMP_COPAR_DEP
         where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDCODDPN = :BDCODDPN and BDCODPLACONVSAU = :BDCODPLACONVSAU and BDCODOPERADORA = :BDCODOPERADORA and
           BDCODCONVENIO = :BDCODCONVENIO and BDREF = :BDREF into :BDVALORCOPARDEP, :BDCODTIPO;

      BDNAOPAGAMENSALIDADE = upper(coalesce(BDNAOPAGAMENSALIDADE, 'FALSE'));

      if (BDNAOPAGAMENSALIDADE = 'FALSE') then
         begin
           select first 1 d2.bdvalormensalidade from VRHM_EMP_COPAR_DEP d2
           where d2.bdcodemp = :BDCODEMP and
              d2.bdcodcol = :BDCODCOL and
              d2.bdcoddpn = :BDCODDPN and
              d2.bdcodplaconvsau = :BDCODPLACONVSAU and
              d2.bdcodoperadora = :BDCODOPERADORA and
              d2.bdcodconvenio = :BDCODCONVENIO and
              d2.bdvalormensalidade is not null and
              d2.bdref <= :prref
           order by d2.bdref desc
           into :BDVALORMENSALIDADE;
         end

           if (BDVALORMENSALIDADE = 0) then
              BDNAOPAGAMENSALIDADE = 'TRUE';

           wsql2 = 'select first 1 BDCONVMEDDPN from VRH_EMP_TDEP_REF where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDCODDPN = '||BDCODDPN||' and BDREFDPN <= '||prref||' order by BDREFDPN DESC';
           wok = null;
           execute statement wsql2 into :wok;
           if (upper(coalesce(:wok, 'FALSE')) = 'TRUE') then
              suspend;
           else
              begin
                wsql2 = 'select first 1 BDCONVMEDDPN from VRH_EMP_TDEP_REF where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||' and BDCODDPN = '||BDCODDPN||' order by BDREFDPN';
                wok = null;
                execute statement wsql2 into :wok;
                if (upper(coalesce(:wok, 'FALSE')) = 'TRUE') then
                   suspend;
              end
         end
end^

create or alter procedure SP_VRHM_EMP_VAL_DEP_OP_ATU (
    PREMP integer,
    PRREF integer,
    PRCOL integer = null,
    PRDEP integer = null,
    PRPLANO integer = 0,
    PROPER integer = 0,
    PRCONV integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREFVCS integer,
    BDVALORMENSALIDADEDEP numeric(18,2),
    BDVALORCOPARDEP numeric(18,2),
    BDTIPO integer,
    BDCODTIPO integer)
as
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(5000);
declare variable WNAOPAGAMENSALIDADE DM_BOOLEAN;
declare variable WPGMENS DM_BOOLEAN;
begin
  wsql = 'SELECT psf.bdcodemp, psf.bdcodcol, psf.bdcoddpn, psf.bdcodplaconvsau, psf.bdcodoperadora,psf.bdcodconvenio, COALESCE(x.bdref, 0) bdref, '||
             'CASE WHEN COALESCE(men.bdmensalidade, 0) = 0 THEN x.bdvalormensalidade '||
                  'WHEN men.bdmensalidade > 0 THEN men.bdmensalidade '||
             'END bdmensalidade, '||
             'COALESCE(x.bdvalorcopardep,0) bdvalorcopardep, men.bdtipo, x.bdnaopagamensalidade, x.bdcodtipo '||
         'FROM SP_VRHM_EMP_VINC_DEP_CONV_ATU(';

  if (COALESCE(premp, 0) = 0) then
     wsql = wsql||'null, ';
  else
     wsql = wsql||'''BDCODEMP = '||premp||''',';

  wsql = wsql||prref||',';

  if (COALESCE(prcol, 0) = 0) then
     wsql = wsql||'null, ';
  else
     wsql = wsql||'''BDCODCOL = '||prcol||''', ';

  if (COALESCE(prdep, 0) = 0) then
     wsql = wsql||'null';
  else
     wsql = wsql||prdep;

  wsql = wsql||') psf '||
         'LEFT OUTER JOIN SP_VRHM_EMP_DEP_COP_OP_SAU(';

  if (COALESCE(premp, 0) = 0) then
     wsql = wsql||'null, ';
  else
     wsql = wsql||premp||',';

  wsql = wsql||prref||',';

  if (COALESCE(prcol, 0) = 0) then
     wsql = wsql||'null, ';
  else
     wsql = wsql||prcol||', ';

  if (COALESCE(prdep, 0) = 0) then
     wsql = wsql||'null';
  else
     wsql = wsql||prdep;

  wsql = wsql||') x ON (x.bdcodemp = psf.bdcodemp AND x.bdcodcol = psf.bdcodcol AND x.bdcodoperadora = psf.bdcodoperadora AND x.bdcodconvenio = psf.bdcodconvenio AND x.bdcodplaconvsau = psf.bdcodplaconvsau AND x.bdcoddpn = psf.bdcoddpn) '||
         'JOIN SP_VRHM_EMP_DEP_VAL_OP_SAU(';

  if (COALESCE(premp, 0) = 0) then
     wsql = wsql||'null, ';
  else
     wsql = wsql||premp||',';

  wsql = wsql||prref||',';

  if (COALESCE(prcol, 0) = 0) then
     wsql = wsql||'null, ';
  else
     wsql = wsql||prcol||', ';

  if (COALESCE(prdep, 0) = 0) then
     wsql = wsql||'null';
  else
     wsql = wsql||prdep;

  wsql = wsql||') men ON (men.bdcodemp = psf.bdcodemp AND men.bdcodcol = psf.bdcodcol AND men.bdcoddpn = psf.bdcoddpn AND men.bdcodconvenio = psf.bdcodconvenio AND MEN.bdcodoperadora = PSF.bdcodoperadora) ';

  wwhere = '';
  if (coalesce(prplano, 0) = -1) then
     wwhere = wwhere||'psf.BDCODPLACONVSAU is null';
  else
  if (coalesce(prplano, 0) > 0) then
     wwhere = wwhere||'psf.BDCODPLACONVSAU = '||prplano;

  if (coalesce(proper, 0) = -1) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||'psf.BDCODOPERADORA is null';
     end
  else
  if (coalesce(proper, 0) > 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||'psf.BDCODOPERADORA = '||proper;
     end

  if (coalesce(prconv, 0) = -1) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||'psf.BDCODCONVENIO is null';
     end
  else
  if (coalesce(prconv, 0) > 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||'psf.BDCODCONVENIO = '||prconv;
     end

  if (wwhere <> '') then
     wsql = wsql||' where '||wwhere;

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDCODDPN, :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDREFVCS, :BDVALORMENSALIDADEDEP, :BDVALORCOPARDEP, :BDTIPO, :wnaopagamensalidade, :BDCODTIPO do
    begin
      if ((UPPER(COALESCE(:wnaopagamensalidade, 'FALSE')) = 'TRUE') and (:BDVALORMENSALIDADEDEP = 0)) then
         BDVALORMENSALIDADEDEP = 0;
      else
      if (coalesce(bdrefvcs, 0) > 0 and bdrefvcs = prref and coalesce(BDVALORMENSALIDADEDEP, 0) = 0) then
         begin
           -- Tenta buscar a informação de algum lançamento anterior.
           select first 1 BDVALORMENSALIDADE, BDNAOPAGAMENSALIDADE
           from VRHM_EMP_COPAR_DEP
           where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDCODDPN = :BDCODDPN and BDCODPLACONVSAU = :BDCODPLACONVSAU and BDCODOPERADORA = :BDCODOPERADORA and BDCODCONVENIO = :BDCODCONVENIO and
                 BDREF < :prref order by BDREF DESC into :BDVALORMENSALIDADEDEP, :wpgmens;

           if ((upper(coalesce(:wpgmens, 'FALSE')) = 'TRUE') and (:BDVALORMENSALIDADEDEP = 0)) then
              BDVALORMENSALIDADEDEP = 0;
         end
    suspend;
    end
end^

/* restore proc. body: SP_VRH_CONVSAU_DIRF */
create or alter procedure SP_VRH_CONVSAU_DIRF (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRPLASAUDE integer = 0,
    PRANO integer = 0)
returns (
    BDTIPO integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREF integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDNOME DM_BDNOMCOL,
    BDCPF varchar(14),
    BDVALORMENSALIDADE numeric(18,2),
    BDVALORCOPAR numeric(18,2),
    BDCODTIPOCONV integer,
    BDTIPOFAIXA integer,
    BDDESCRICAO varchar(80),
    BDCNPJ DM_CNPJ_CPF,
    BDREGISTROANS integer,
    BDRAZAOSOCIAL varchar(80),
    BDPARENESCODPN integer,
    BDDATANASCDPN date,
    BDMENSFORMULA DM_BOOLEAN,
    BDCODVERTITMENS integer,
    BDCODVERTITCOP integer,
    BDCODVERDEPMENS integer,
    BDCODVERDEPCOP integer)
as
declare variable WSQL varchar(1000);
declare variable WOK integer;
begin
  execute procedure sp_seta_competencia(prref);

  if (COALESCE(prplasaude, 0) = 0) then
     begin
       wsql = 'select first 1 BDCODPLACONVSAU from VRHF_BASE_TEMPVINC where BDCODEMP = '||premp||' and BDREFEMP <= '||prref||' order by BDREFEMP DESC';
       execute statement wsql into :prplasaude;
     end

  wsql = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||premp||' and BDCODCOL = '||prcol||' and BDREFCOL <= '||prref||' order by BDREFCOL DESC ';
  execute statement wsql into : BDNOME;

  for SELECT x.bdcodplaconvsau,x.bdcodoperadora, x.bdcodconvenio, x.bdrefvcs ,colcon.bdcodemp, colcon.bdcodcol,
             colcon.bdcpfcol bdcpf, COALESCE(x.BDVALORMENSALIDADEFUN,0) bdvalormensalidade, x.bdvalorcoparfun bdvalorcopar, y.bdcodtipoconv, COALESCE(x.bdtipo, 0) bdtipofaixa,
             w.bddescricao, w.bdcnpj, w.bdregistroans, w.bdrazaosocial, upper(coalesce(y.bdmensformula, 'FALSE')), y.bdcodvertitmens, y.bdcodvertitcop, y.bdcodverdepmens,
             y.bdcodverdepcop
      FROM vrh_emp_tcolcon colcon
      LEFT OUTER JOIN SP_VRHM_EMP_VAL_COL_OP_ATU(:premp, :prcol, :prref) x ON (x.bdcodemp = colcon.bdcodemp AND x.bdcodcol = colcon.bdcodcol)
      LEFT OUTER JOIN VRH_BASE_CONVENIO_OPERADORAS y ON (y.bdcodplaconvsau = x.bdcodplaconvsau AND y.bdcodoperadora = x.bdcodoperadora AND y.bdcodconvenio = x.bdcodconvenio)
      LEFT OUTER JOIN VRH_BASE_TCONVSAUDE w on (w.BDCODCONVENIO = X.BDCODOPERADORA)
      WHERE colcon.bdcodemp = :premp and colcon.bdcodcol = :prcol and x.bdcodplaconvsau = :prplasaude
  into
    :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDREF, :BDCODEMP, :BDCODCOL,
    :BDCPF, :BDVALORMENSALIDADE, :BDVALORCOPAR, :BDCODTIPOCONV, :BDTIPOFAIXA,
    :BDDESCRICAO, :BDCNPJ, :BDREGISTROANS, :BDRAZAOSOCIAL, :BDMENSFORMULA,
    :BDCODVERTITMENS,:BDCODVERTITCOP,:BDCODVERDEPMENS,:BDCODVERDEPCOP
  do
    begin
      BDTIPO = 0;
      BDCODDPN = NULL;
      BDPARENESCODPN = NULL;
      BDDATANASCDPN = NULL;
      suspend;
    end

  for SELECT CONV.bdcodplaconvsau,CONV.bdcodoperadora, conv.bdcodconvenio, conv.bdrefvcs, dep.bdcodemp, dep.bdcodcol, dep.bdcoddpn,
             conv.bdvalormensalidadedep, conv.bdvalorcopardep, y.bdcodtipoconv, COALESCE(conv.bdtipo, 0) bdtipofaixa,
             w.bddescricao, w.bdcnpj, w.bdregistroans, w.bdrazaosocial, upper(coalesce(y.bdmensformula, 'FALSE')), y.bdcodvertitmens,
             y.bdcodvertitcop, y.bdcodverdepmens, y.bdcodverdepcop
      FROM vrh_emp_tdep dep
      LEFT OUTER JOIN SP_VRHM_EMP_VAL_DEP_OP_ATU(:premp, :prref, :prcol) conv ON (conv.bdcodemp = dep.bdcodemp AND conv.bdcodcol = dep.bdcodcol AND conv.bdcoddpn = dep.bdcoddpn)
      LEFT OUTER JOIN VRH_BASE_CONVENIO_OPERADORAS y ON (y.bdcodplaconvsau = conv.bdcodplaconvsau AND y.bdcodoperadora = conv.bdcodoperadora AND y.bdcodconvenio = conv.bdcodconvenio)
      LEFT OUTER JOIN VRH_BASE_TCONVSAUDE w on (w.BDCODCONVENIO = conv.BDCODOPERADORA)
      WHERE dep.bdcodemp = :premp and dep.bdcodcol = :prcol and CONV.bdcodplaconvsau = :prplasaude
  into
    :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDREF, :BDCODEMP, :BDCODCOL, :BDCODDPN,
    :BDVALORMENSALIDADE, :BDVALORCOPAR, :BDCODTIPOCONV, :BDTIPOFAIXA,
    :BDDESCRICAO, :BDCNPJ, :BDREGISTROANS, :BDRAZAOSOCIAL, :BDMENSFORMULA,
    :BDCODVERTITMENS,:BDCODVERTITCOP,:BDCODVERDEPMENS,:BDCODVERDEPCOP
  do
    begin
      BDTIPO = 1;
      wok = null;

      if (coalesce(prano, 0) > 0) then
      wsql = 'select first 1 BDCODDPN, BDNOMEDPN, BDPARENESCODPN, BDDATANASCDPN, BDCPFDPN from VRH_EMP_TDEP_REF where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||
                ' and BDCODDPN = '||BDCODDPN||' and BDREFDPN <= '||prano||'12 and upper(coalesce(BDCONVMEDDPN, ''FALSE'')) = ''TRUE'' order by BDREFDPN DESC';
      else
         wsql = 'select first 1 BDCODDPN, BDNOMEDPN, BDPARENESCODPN, BDDATANASCDPN, BDCPFDPN from VRH_EMP_TDEP_REF where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||
             ' and BDCODDPN = '||BDCODDPN||' and BDREFDPN <= '||prref||' and upper(coalesce(BDCONVMEDDPN, ''FALSE'')) = ''TRUE'' order by BDREFDPN DESC';

      execute statement wsql into :wok, :BDNOME, :BDPARENESCODPN, :BDDATANASCDPN, :BDCPF;

      if (coalesce(wok, 0) > 0) then
         suspend;
      else
         begin
           wok = null;
           wsql = 'select first 1 BDCODDPN, BDNOMEDPN, BDPARENESCODPN, BDDATANASCDPN, BDCPFDPN from VRH_EMP_TDEP_REF where BDCODEMP = '||BDCODEMP||' and BDCODCOL = '||BDCODCOL||
                  ' and BDCODDPN = '||BDCODDPN||' and upper(coalesce(BDCONVMEDDPN, ''FALSE'')) = ''TRUE'' order by BDREFDPN DESC ';
     
           execute statement wsql into :wok, :BDNOME, :BDPARENESCODPN, :BDDATANASCDPN, :BDCPF;
     
           if (coalesce(wok, 0) > 0) then
              suspend;
         end
    end        
end^

/* restore proc. body: SP_VRH_CONVSAU_DIRF2 */
create or alter procedure SP_VRH_CONVSAU_DIRF2 (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer,
    PRANO integer = 0)
returns (
    BDTIPO integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREF integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDNOME DM_BDNOMCOL,
    BDCPF varchar(14),
    BDVALORMENSALIDADE numeric(18,2),
    BDVALORCOPAR numeric(18,2),
    BDCODTIPOCONV integer,
    BDTIPOFAIXA integer,
    BDDESCRICAO varchar(80),
    BDCNPJ DM_CNPJ_CPF,
    BDREGISTROANS integer,
    BDRAZAOSOCIAL varchar(80),
    BDPARENESCODPN integer,
    BDDATANASCDPN date,
    BDMENSFORMULA DM_BOOLEAN,
    BDCODVERTITMENS integer,
    BDCODVERTITCOP integer,
    BDCODVERDEPMENS integer,
    BDCODVERDEPCOP integer)
as
declare variable WSQL varchar(32700);
declare variable WSQL2 varchar(500);
begin
  wsql = 'select dep.BDCODEMP, dep.BDCODCOL from VRH_EMP_TCOLCON dep ';

  if (COALESCE(premp, '') <> '') then
     begin
       wsql = wsql||' where '||premp;

       if (COALESCE(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;
     end

  for execute statement wsql into :BDCODEMP, :BDCODCOL do
    begin
      wsql2 = 'select first 1 BDCODPLACONVSAU from VRHF_BASE_TEMPVINC where BDCODEMP = '||BDCODEMP||' and BDREFEMP <= '||prref||' order by BDREFEMP DESC';
      execute statement wsql2 into :BDCODPLACONVSAU;

      for select BDTIPO,BDCODOPERADORA,BDCODCONVENIO,BDREF,BDCODDPN,BDNOME,BDCPF,BDVALORMENSALIDADE,BDVALORCOPAR,BDCODTIPOCONV,BDTIPOFAIXA,
                 BDDESCRICAO,BDCNPJ,BDREGISTROANS,BDRAZAOSOCIAL,BDPARENESCODPN,BDDATANASCDPN,BDMENSFORMULA,BDCODVERTITMENS,BDCODVERTITCOP,BDCODVERDEPMENS,BDCODVERDEPCOP
          from SP_VRH_CONVSAU_DIRF(:BDCODEMP, :BDCODCOL, :prref, :BDCODPLACONVSAU, :prano)
      into :BDTIPO,:BDCODOPERADORA,:BDCODCONVENIO,:BDREF,:BDCODDPN,:BDNOME,:BDCPF,:BDVALORMENSALIDADE,:BDVALORCOPAR,:BDCODTIPOCONV,:BDTIPOFAIXA,
                 :BDDESCRICAO,:BDCNPJ,:BDREGISTROANS,:BDRAZAOSOCIAL,:BDPARENESCODPN,:BDDATANASCDPN,:BDMENSFORMULA,:BDCODVERTITMENS,:BDCODVERTITCOP,
                 :BDCODVERDEPMENS,:BDCODVERDEPCOP do
        suspend;
    end
end^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_TNCM (
    PRSESSAO INTEGER)
AS
BEGIN
  UPDATE TMP_TNCM_TEMP N
  SET N.BDTIPONCM = CASE WHEN N.BDTIPONCMSTR = 'Seção'      THEN 0
                         WHEN N.BDTIPONCMSTR = 'Capítulo'   THEN 1
                         WHEN N.BDTIPONCMSTR = 'Posição'    THEN 2
                         WHEN N.BDTIPONCMSTR = 'Subposição' THEN 3
                         WHEN N.BDTIPONCMSTR = 'Item'       THEN 4
                         WHEN N.BDTIPONCMSTR = 'Subitem'    THEN 5
                    END
  WHERE N.BDSESSAO = :PRSESSAO;
END;^


CREATE OR ALTER procedure SPRH_DIVERGDADOSDIARIOSCOL
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATA date,
    BDDESC varchar(100))
as
declare variable WBDCODEMP integer;
declare variable WBDCODCOL integer;
declare variable WBDDATACOL date;
declare variable WBDCODMAS integer;
declare variable WBDSALBASECOL numeric(15,2);
declare variable WBDCODPLAFUC integer;
declare variable WBDCODTFUC integer;
declare variable WBDCODQH integer;
declare variable WBDREGJORTRAB integer;
declare variable WBDDESCMAS varchar(100);
declare variable WBDTIPOJORNADA integer;
declare variable WBDCODTIPOCONTRATO integer;
declare variable WBDDATAFIMPRAZO1COL date;
declare variable WBDDATAFIMPRAZO2COL date;
declare variable WBDDATAFIMPRAZO date;
declare variable WBDCODEMP_ integer;
declare variable WBDCODCOL_ integer;
declare variable WBDDATACOL_ date;
declare variable WBDCODMAS_ integer;
declare variable WBDSALBASECOL_ numeric(15,2);
declare variable WBDCODPLAFUC_ integer;
declare variable WBDCODTFUC_ integer;
declare variable WBDCODQH_ integer;
declare variable WBDREGJORTRAB_ integer;
declare variable WBDDESCMAS_ varchar(100);
declare variable WBDTIPOJORNADA_ integer;
declare variable WBDCODTIPOCONTRATO_ integer;
declare variable WBDDATAFIMPRAZO1COL_ date;
declare variable WBDDATAFIMPRAZO2COL_ date;
declare variable WBDDATAFIMPRAZO_ date;
declare variable WDIVERGENCIA integer;
begin
  for select COLCON_DIA.BDCODEMP,
             COLCON_DIA.BDCODCOL,
             COLCON_DIA.BDDATACOL,
             COLCON_CALCDIA.BDCODMAS,
             COLCON_CALCDIA.BDSALBASECOL,
             COL_VINCDIA.BDCODPLAFUC,
             COL_VINCDIA.BDCODTFUC,
             COL_VINCDIA.BDCODQH,
             COL_VINCDIA.BDREGJORTRAB,
             MOTAUM.BDDESCMAS,
             COL_VINCDIA.BDTIPOJORNADA,
             TPCONT.BDCODTIPOCONTRATO,
             BDDATAFIMPRAZO1COL,
             BDDATAFIMPRAZO2COL,
             case when BDDATAFIMPRAZO2COL is not null then BDDATAFIMPRAZO2COL else BDDATAFIMPRAZO1COL end BDDATAFIMPRAZO
      from VRH_EMP_TCOLCON_DIA COLCON_DIA
      left outer join VRH_EMP_TCOLCON_CALCDIA COLCON_CALCDIA on (COLCON_CALCDIA.BDCODEMP = COLCON_DIA.BDCODEMP and COLCON_CALCDIA.BDCODCOL = COLCON_DIA.BDCODCOL and COLCON_CALCDIA.BDDATACOL = COLCON_DIA.BDDATACOL)
      left outer join VRH_EMP_TCOL_VINCDIA COL_VINCDIA on (COL_VINCDIA.BDCODEMP = COLCON_DIA.BDCODEMP and COL_VINCDIA.BDCODCOL = COLCON_DIA.BDCODCOL and COL_VINCDIA.BDDATACOL = COLCON_DIA.BDDATACOL)
      left outer join VRHF_BASE_TEMPVINC EMP_VINC on (EMP_VINC.BDCODEMP = COLCON_DIA.BDCODEMP and EMP_VINC.BDREFEMP = (select max(BDREFEMP) from TEMPRESAS_REF where BDCODEMP = EMP_VINC.BDCODEMP and BDREFEMP <= substring(COLCON_DIA.BDDATACOL from 1 for 4) || substring(COLCON_DIA.BDDATACOL from 6 for 2)))
      left outer join VRH_BASE_TMOTAUMSAL MOTAUM on (MOTAUM.BDCODMAS = COLCON_CALCDIA.BDCODMAS)
      left outer join VRH_EMP_TCOLCON_PARTIDA PAR on (PAR.BDCODEMP = COLCON_DIA.BDCODEMP and PAR.BDCODCOL = COLCON_DIA.BDCODCOL)
      left outer join VRH_TIPO_CONTRATO_EXP TPCONT on (TPCONT.BDCODTIPOCONTRATO = PAR.BDCODTIPOCONTRATO)
      left outer join VRH_EMP_TCOL_ADM ADM on (ADM.BDCODEMP = COLCON_DIA.BDCODEMP) and (ADM.BDCODCOL = COLCON_DIA.BDCODCOL)

      where exists (select first 1 * from VRH_EMP_TCOLCON_CALCDIA CALCDIA
                    inner join VRH_BASE_TMOTAUMSAL MOTAUMSAL on (MOTAUMSAL.BDCODMAS = CALCDIA.BDCODMAS and ((MOTAUMSAL.bddescmas = 'Prorrogação do contrato de trabalho') or (MOTAUMSAL.bddescmas = 'Alteração automática do contrato de trabalho')))
                    where CALCDIA.bdcodemp = COLCON_DIA.bdcodemp
                    and CALCDIA.bdcodcol = COLCON_DIA.bdcodcol)

      order by COLCON_DIA.bdcodemp asc, COLCON_DIA.bdcodcol asc, COLCON_DIA.BDDATACOL DESC
      into :wBDCODEMP,:wBDCODCOL,:wBDDATACOL,:wBDCODMAS,:wBDSALBASECOL,:wBDCODPLAFUC,:wBDCODTFUC,:wBDCODQH,:wBDREGJORTRAB,:wBDDESCMAS,:wBDTIPOJORNADA,:wBDCODTIPOCONTRATO,:wBDDATAFIMPRAZO1COL,:wBDDATAFIMPRAZO2COL,:wBDDATAFIMPRAZO do
      begin
        BDDESC = '';

        if ((wBDCODEMP <> wBDCODEMP_) or (wBDCODCOL <> wBDCODCOL_)) then
        begin
          wBDCODEMP_ = null;
          wBDCODCOL_ = null;
        end

        if ((wBDCODEMP_ is not null) and (wBDCODCOL_ is not null)) then
        begin
          BDCODEMP = wBDCODEMP_;
          BDCODCOL = wBDCODCOL_;
          BDDATA = wBDDATACOL_;

          if (wBDCODMAS <> wBDCODMAS_) then
             BDDESC = 'Motivo da alteração';
          if (wBDSALBASECOL > wBDSALBASECOL_) then
             BDDESC = 'Salário base (Valor anterior de '||wBDSALBASECOL||' diminuiu para '||wBDSALBASECOL_||')';
          if (wBDCODPLAFUC <> wBDCODPLAFUC_) then
             BDDESC = 'Plano de função';
          if (wBDCODTFUC <> wBDCODTFUC_) then
             BDDESC = 'Função';
          if (wBDCODQH <> wBDCODQH_) then
             BDDESC = 'Quadro de horário';
          if (wBDREGJORTRAB <> wBDREGJORTRAB_) then
             BDDESC = 'Regime jornada de trabalho';
          if (wBDDESCMAS <> wBDDESCMAS_) then
             BDDESC = 'Motivo da alteração';
          if (wBDTIPOJORNADA <> wBDTIPOJORNADA_) then
             BDDESC = 'Tipo de jornada';
          if (wBDCODTIPOCONTRATO <> wBDCODTIPOCONTRATO_) then
             BDDESC = 'Tipo de contrato';

          if (BDDESC <> '') then
          begin
            suspend;
          end
        end

        wBDCODEMP_ = wBDCODEMP;
        wBDCODCOL_ = wBDCODCOL;
        wBDDATACOL_ = wBDDATACOL;
        wBDCODMAS_ = wBDCODMAS;
        wBDSALBASECOL_ = wBDSALBASECOL;
        wBDCODPLAFUC_ = wBDCODPLAFUC;
        wBDCODTFUC_ = wBDCODTFUC;
        wBDCODQH_ = wBDCODQH;
        wBDREGJORTRAB_ = wBDREGJORTRAB;
        wBDDESCMAS_ = wBDDESCMAS;
        wBDTIPOJORNADA_ = wBDTIPOJORNADA;
        wBDCODTIPOCONTRATO_ = wBDCODTIPOCONTRATO;
        wBDDATAFIMPRAZO1COL_ = wBDDATAFIMPRAZO1COL;
        wBDDATAFIMPRAZO2COL_ = wBDDATAFIMPRAZO2COL;
        wBDDATAFIMPRAZO_ = wBDDATAFIMPRAZO;
      end
end^

CREATE OR ALTER procedure SP_ESOCIAL_TEMPRESA_TABELAS (
    PRCODEMP integer)
returns (
    BDCODEMPORIGINAL integer,
    BDCODEMP integer,
    BDOPCAOESOCIAL integer)
as
declare variable WSQL varchar(3000);
begin
  BDCODEMPORIGINAL = :prcodemp;

  wSQL = 'select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) from TEMPRESAS EMP where EMP.BDCODEMP = ' || :PRCODEMP;
  execute statement :wsql into :BDCODEMP;

  if (:BDCODEMP > 0) then
        begin
      wSQL = 'select coalesce(bdopcaoesocial,0) from vrh_esocial_tfaseamento where bdcodemp = ' || :BDCODEMP;
      execute statement wsql into :BDOPCAOESOCIAL;
        end
        
  Suspend;
end^

CREATE OR ALTER PROCEDURE SP_COMMIT_IMP_NCM (
    PRSESSAO INTEGER,
    PRREF INTEGER)
AS
DECLARE VARIABLE WSESSAO INTEGER;
DECLARE VARIABLE WNCMPROD INTEGER;
DECLARE VARIABLE WNOMENCM VARCHAR(1100);
DECLARE VARIABLE WCLASSIFICACAO VARCHAR(20);
DECLARE VARIABLE WTIPONCM INTEGER;
DECLARE VARIABLE WALIQIPI NUMERIC(15,6);
DECLARE VARIABLE WSECAO VARCHAR(5);
DECLARE VARIABLE WCODCSTICMS INTEGER;
DECLARE VARIABLE WCSTICMS VARCHAR(3);
DECLARE VARIABLE WALIQICMS NUMERIC(7,4);
DECLARE VARIABLE WALIQICMSST NUMERIC(7,4);
DECLARE VARIABLE WCODCSTIPIENT INTEGER;
DECLARE VARIABLE WCSTIPIENT VARCHAR(3);
DECLARE VARIABLE WCODCSTIPISAI INTEGER;
DECLARE VARIABLE WCSTIPISAI VARCHAR(3);
DECLARE VARIABLE WCODCSTPISENT INTEGER;
DECLARE VARIABLE WCSTPISENT VARCHAR(3);
DECLARE VARIABLE WCODCSTPISSAI INTEGER;
DECLARE VARIABLE WCSTPISSAI VARCHAR(3);
DECLARE VARIABLE WALIQPISLR NUMERIC(7,4);
DECLARE VARIABLE WALIQPISLP NUMERIC(7,4);
DECLARE VARIABLE WCODCSTCOFENT INTEGER;
DECLARE VARIABLE WCSTCOFENT VARCHAR(3);
DECLARE VARIABLE WCODCSTCOFSAI INTEGER;
DECLARE VARIABLE WCSTCOFSAI VARCHAR(3);
DECLARE VARIABLE WALIQCOFLR NUMERIC(7,4);
DECLARE VARIABLE WALIQCOFLP NUMERIC(7,4);
BEGIN
  /*Só os existentes*/
  FOR SELECT N.BDNCMPROD, N.BDNOMENCM, N.BDCLASSIFICACAO, N.BDTIPONCM, N.BDALIQIPI, N.BDSECAO, N.BDCODCSTICMS,
             N.BDALIQICMS, N.BDALIQICMSST, N.BDCODCSTIPIENT, N.BDCODCSTIPISAI, N.BDCODCSTPISENT, N.BDCODCSTPISSAI,
             N.BDALIQPISLR, N.BDALIQPISLP, N.BDCODCSTCOFENT, N.BDCODCSTCOFSAI, N.BDALIQCOFLR, N.BDALIQCOFLP
      FROM TMP_TNCM_TEMP N
      JOIN TNCM NCM ON(NCM.BDNCMPROD = N.BDNCMPROD)
      WHERE N.BDSESSAO = :PRSESSAO
      INTO :wNCMPROD, :wNOMENCM, :wCLASSIFICACAO, :wTIPONCM,
           :wALIQIPI, :wSECAO, :wCODCSTICMS, :wALIQICMS, :wALIQICMSST, :wCODCSTIPIENT, :wCODCSTIPISAI,
           :wCODCSTPISENT, :wCODCSTPISSAI, :wALIQPISLR, :wALIQPISLP, :wCODCSTCOFENT, :wCODCSTCOFSAI,
           :wALIQCOFLR, :wALIQCOFLP
  DO
    BEGIN
      UPDATE OR INSERT INTO TNCM(BDNCMPROD, BDNOMENCM, BDCLASSIFICACAO, BDTIPONCM,
                                 BDALIQIPI, BDSECAO, BDCODCSTICMS, BDALIQICMS, BDALIQICMSST, BDCODCSTIPIENT, BDCODCSTIPISAI,
                                 BDCODCSTPISENT, BDCODCSTPISSAI, BDALIQPISLR, BDALIQPISLP, BDCODCSTCOFENT, BDCODCSTCOFSAI,
                                 BDALIQCOFLR, BDALIQCOFLP)
      VALUES(:wNCMPROD, :wNOMENCM, :wCLASSIFICACAO, :wTIPONCM,
             :wALIQIPI, :wSECAO, :wCODCSTICMS, :wALIQICMS, :wALIQICMSST, :wCODCSTIPIENT, :wCODCSTIPISAI,
             :wCODCSTPISENT, :wCODCSTPISSAI, :wALIQPISLR, :wALIQPISLP, :wCODCSTCOFENT, :wCODCSTCOFSAI,
             :wALIQCOFLR, :wALIQCOFLP) MATCHING(BDNCMPROD);
    END

  /*NCM'S novos somente - Não importa novos conforme solicitado pelo Fernando, só atualiza os existentes
  INSERT INTO TNCM(BDNCMPROD, BDNOMENCM, BDCLASSIFICACAO, BDTIPONCM,
                   BDALIQIPI, BDSECAO, BDCODCSTICMS, BDALIQICMS, BDALIQICMSST, BDCODCSTIPIENT, BDCODCSTIPISAI,
                   BDCODCSTPISENT, BDCODCSTPISSAI, BDALIQPISLR, BDALIQPISLP, BDCODCSTCOFENT, BDCODCSTCOFSAI,
                   BDALIQCOFLR, BDALIQCOFLP)
  SELECT N.BDNCMPROD, N.BDNOMENCM, N.BDCLASSIFICACAO, N.BDTIPONCM, N.BDALIQIPI, N.BDSECAO, N.BDCODCSTICMS,
         N.BDALIQICMS, N.BDALIQICMSST, N.BDCODCSTIPIENT, N.BDCODCSTIPISAI, N.BDCODCSTPISENT, N.BDCODCSTPISSAI,
         N.BDALIQPISLR, N.BDALIQPISLP, N.BDCODCSTCOFENT, N.BDCODCSTCOFSAI, N.BDALIQCOFLR, N.BDALIQCOFLP
  FROM TMP_TNCM_TEMP N
  LEFT OUTER JOIN TNCM NCM ON(NCM.BDNCMPROD = N.BDNCMPROD)
  WHERE N.BDSESSAO = :PRSESSAO
  AND ((N.BDNCMPROD IS NOT NULL) AND (N.BDNCMPROD > 0))
  AND NCM.BDNCMPROD IS NULL;
  */
END^

CREATE OR ALTER PROCEDURE SP_VINCULAR_CST_TNCM (
    PRSESSAO INTEGER)
AS
BEGIN

  /*CST ICMS*/
  UPDATE TMP_TNCM_TEMP N
  SET N.BDCODCSTICMS = (SELECT FIRST 1 ICMS.BDCODCSTICMS FROM VEF_BASE_TTABCSTICMS ICMS WHERE ICMS.BDCSTICMS = N.BDCSTICMS)
  WHERE N.BDSESSAO = :PRSESSAO
  AND ((N.BDCSTICMS IS NOT NULL) AND (N.BDCSTICMS <> ''));

  /*CST IPI entrada*/
  UPDATE TMP_TNCM_TEMP N
  SET N.BDCODCSTIPIENT = (SELECT FIRST 1 IPI.BDCODCSTIPI FROM VEF_BASE_TTABCSTIPI IPI WHERE IPI.BDCODEXPCSTIPI = N.BDCSTIPIENT AND IPI.BDCODCSTIPI BETWEEN 1 AND 7)
  WHERE N.BDSESSAO = :PRSESSAO
  AND ((N.BDCSTIPIENT IS NOT NULL) AND (N.BDCSTIPIENT <> ''));

  /*CST IPI saída*/
  UPDATE TMP_TNCM_TEMP N
  SET N.BDCODCSTIPISAI = (SELECT FIRST 1 IPI.BDCODCSTIPI FROM VEF_BASE_TTABCSTIPI IPI WHERE IPI.BDCODEXPCSTIPI = N.BDCSTIPISAI AND IPI.BDCODCSTIPI BETWEEN 8 AND 14)
  WHERE N.BDSESSAO = :PRSESSAO
  AND ((N.BDCSTIPISAI IS NOT NULL) AND (N.BDCSTIPISAI <> ''));

  /*CST PIS entrada*/
  UPDATE TMP_TNCM_TEMP N
  SET N.BDCODCSTPISENT = (SELECT FIRST 1 PIS.BDCODCSTPIS FROM VEF_BASE_TTABCSTPIS PIS WHERE PIS.BDCSTPIS = N.BDCSTPISENT AND PIS.BDCODCSTPIS BETWEEN 50 AND 99)
  WHERE N.BDSESSAO = :PRSESSAO
  AND ((N.BDCSTPISENT IS NOT NULL) AND (N.BDCSTPISENT <> ''));

  /*CST PIS saída*/
  UPDATE TMP_TNCM_TEMP N
  SET N.BDCODCSTPISSAI = (SELECT FIRST 1 PIS.BDCODCSTPIS FROM VEF_BASE_TTABCSTPIS PIS WHERE PIS.BDCSTPIS = N.BDCSTPISSAI AND ((PIS.BDCODCSTPIS BETWEEN 1 AND 49) OR (PIS.BDCODCSTPIS = 99)))
  WHERE N.BDSESSAO = :PRSESSAO
  AND ((N.BDCSTPISSAI IS NOT NULL) AND (N.BDCSTPISSAI <> ''));

  /*CST Cofins entrada*/
  UPDATE TMP_TNCM_TEMP N
  SET N.BDCODCSTCOFENT = (SELECT FIRST 1 COF.BDCODCSTCOF FROM VEF_BASE_TTABCSTCOF COF WHERE COF.BDCSTCOF = N.BDCSTCOFENT AND (COF.BDCODCSTCOF BETWEEN 50 AND 99))
  WHERE N.BDSESSAO = :PRSESSAO
  AND ((N.BDCSTCOFENT IS NOT NULL) AND (N.BDCSTCOFENT <> ''));

  /*CST Cofins saída*/
  UPDATE TMP_TNCM_TEMP N
  SET N.BDCODCSTCOFSAI = (SELECT FIRST 1 COF.BDCODCSTCOF FROM VEF_BASE_TTABCSTCOF COF WHERE COF.BDCSTCOF = N.BDCSTCOFSAI AND ((COF.BDCODCSTCOF BETWEEN 1 AND 49) OR (COF.BDCODCSTCOF = 99)))
  WHERE N.BDSESSAO = :PRSESSAO
  AND ((N.BDCSTCOFSAI IS NOT NULL) AND (N.BDCSTCOFSAI <> ''));
END^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOC_ENT_SPEDCONTR (
    PRCODEMP integer,
    PRCODPLAPADRAOREF integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRBLOCO varchar(4),
    PREXPORTAPORSCP varchar(5),
    PREXBCPISCOF DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
declare variable WEXPCONTACONTAB DM_BOOLEAN;
declare variable WCODPLANOONLINE integer;
declare variable WINCTRIB integer;
declare variable WCODCRIT integer;
declare variable WEXPNFCOMVAL varchar(5);
declare variable WSOMENTEBLOCOP varchar(40);
declare variable WARQUIVO varchar(260);
declare variable WCHAVEMIN integer;
declare variable WCHAVEMAX integer;
declare variable WEXBCPISCOF DM_BOOLEAN;
declare variable WANO integer;
BEGIN
  --Pega da matriz
  WARQUIVO = REPLACE(:PRARQUIVO, '$empresa$', :PRCODEMP);
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')));
  WSOMENTEBLOCOP = 'FALSE';
  WEXPNFCOMVAL   = 'FALSE';
  WCODPLANOONLINE = -1;
  WANO = Extract(year from PRDTFIM);
  WEXBCPISCOF = PREXBCPISCOF;
  
  SELECT FIRST 1 SPED.BDINCTRIB, SPED.BDCODCRIT, SPED.BDEXPNFCOMVALENT, SPED.BDSOMENTEBLOCOP, EMP.BDCODPLANOONLINE, SPED.BDEXPCONTACONTAB
  FROM (SELECT COALESCE(E.BDCODMATRIZ, E.BDCODEMP) BDCODMATRIZ, BDCODPLANOONLINE
        FROM VW_TEMPRESAS_REF TBEM
        JOIN TEMPRESAS E ON(E.BDCODEMP = TBEM.BDCODEMP)
        WHERE TBEM.BDCODEMP = :PRCODEMP
        GROUP BY BDCODMATRIZ, BDCODPLANOONLINE) EMP
  JOIN VW_INT_SPEDPISCOFINS_REF SPED ON(SPED.BDCODEMP = EMP.BDCODMATRIZ AND SPED.BDREFERENCIA <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')))
  ORDER BY SPED.BDREFERENCIA DESC
  INTO :WINCTRIB, :WCODCRIT, :WEXPNFCOMVAL, :WSOMENTEBLOCOP, :WCODPLANOONLINE, :WEXPCONTACONTAB;

  if ((:WINCTRIB is null) and (:PRCODEMPSO > 0)) then
    begin
      SELECT FIRST 1 SPED.BDINCTRIB, SPED.BDCODCRIT, SPED.BDEXPNFCOMVALENT, SPED.BDSOMENTEBLOCOP, EMP.BDCODPLANOONLINE, SPED.BDEXPCONTACONTAB
      FROM (SELECT COALESCE(E.BDCODMATRIZ, E.BDCODEMP) BDCODMATRIZ, BDCODPLANOONLINE
            FROM VW_TEMPRESAS_REF TBEM
            JOIN TEMPRESAS E ON(E.BDCODEMP = TBEM.BDCODEMP)
            WHERE TBEM.BDCODEMP = :PRCODEMPSO
            GROUP BY BDCODMATRIZ, BDCODPLANOONLINE) EMP
      JOIN VW_INT_SPEDPISCOFINS_REF SPED ON(SPED.BDCODEMP = EMP.BDCODMATRIZ AND SPED.BDREFERENCIA <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')))
      ORDER BY SPED.BDREFERENCIA DESC
      INTO :WINCTRIB, :WCODCRIT, :WEXPNFCOMVAL, :WSOMENTEBLOCOP, :WCODPLANOONLINE, :WEXPCONTACONTAB;
    end

  --elizeu - 31-08-18 - Quando for incidência tributária for = 2 - Exclusivamente no regime cumulativo não leva o movimento de entrada
  IF (:WINCTRIB = 1) THEN
    EXIT;

  IF (NOT((:WINCTRIB = 1) AND (:WCODCRIT IN(1, 2)))) THEN
    BEGIN
      IF ((:WSOMENTEBLOCOP <> 'TRUE') AND ((:PRBLOCO = 'C100') OR (:PRBLOCO = ''))) THEN
        BEGIN
          DELETE FROM TMP_VEF_EMP_TMOVENTINFCOM;
          DELETE FROM TMP_VEF_EMP_TMOVENT;
    
          INSERT INTO TMP_VEF_EMP_TMOVENT(BDCODEMP, BDCHAVE, BDCODTER, BDCODSITNF, BDMODELO)
          SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO
          FROM (SELECT * FROM VEF_EMP_TMOVENT M
                WHERE (M.BDCODEMP = :PRCODEMP)
                AND M.BDMODELO IN (1, 4, 55, 100)
                AND M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                and M.BDCODSITNF not in (10, 11)
                ) M
          JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
          JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) <> TRIM('TRUE'))))
          --#91777 - Notas de energia levar no C500
          WHERE NOT((m.BDMODELO = 55) AND (SUBSTRING(i.BDCODNAT FROM 1 FOR 3) IN (125, 225)) AND
                  (SELECT SUM(CAST(MOVPRO.BDVLRPIS AS NUMERIC(15,2)) + CAST(MOVPRO.BDVLRCOFINS AS NUMERIC(15,2))) BDVLR
                   FROM VEF_EMP_TMOVPROENT MOVPRO WHERE (M.BDCODEMP = MOVPRO.BDCODEMP AND M.BDCHAVE = MOVPRO.BDCHAVE)) > 0) AND
                ((:WEXPNFCOMVAL <> 'TRUE') OR (SELECT SUM(CAST(MOVPRO.BDVLRPIS AS NUMERIC(15,2)) + CAST(MOVPRO.BDVLRCOFINS AS NUMERIC(15,2))) BDVLR
                                               FROM VEF_EMP_TMOVPROENT MOVPRO
                                               WHERE (M.BDCODEMP = MOVPRO.BDCODEMP AND M.BDCHAVE = MOVPRO.BDCHAVE)) > 0)
          GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO;

          IF ((:PREXPORTAPORSCP = 'TRUE') AND (:PRCODEMPSO > 0)) THEN
            BEGIN
              --SELECT scp.bdCODSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = :PRCODEMPSO AND scp.bdCODEMPSCP = :PRCODEMP
              --INTO :WCODEMP;

              INSERT INTO TMP_VEF_EMP_TMOVENT(BDCODEMP, BDCHAVE, BDCODTER, BDCODSITNF, BDMODELO)
              SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO
              FROM (SELECT m.* FROM VEF_EMP_TMOVENT m
                    WHERE (M.BDCODEMP = :PRCODEMPSO) AND
                           M.BDMODELO IN (1, 4, 55, 65, 100) AND
                           M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                      and  m.BDCODSITNF not in (10, 11)) M
              JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = I.BDCODNAT AND ((nat.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.BDNAOEXPEFDCONT)) <> TRIM('TRUE'))))
              WHERE NOT((m.BDMODELO = 55) AND (SUBSTRING(i.BDCODNAT FROM 1 FOR 3) IN (125, 225)) AND
                      (SELECT SUM(CAST(MOVPRO.BDVLRPIS AS NUMERIC(15,2)) + CAST(MOVPRO.BDVLRCOFINS AS NUMERIC(15,2))) BDVLR
                       FROM VEF_EMP_TMOVPROENT MOVPRO WHERE (M.BDCODEMP = MOVPRO.BDCODEMP AND M.BDCHAVE = MOVPRO.BDCHAVE)) > 0) AND
                    ((:WEXPNFCOMVAL <> 'TRUE') OR (SELECT SUM(CAST(MOVPRO.BDVLRPIS AS NUMERIC(15,2)) + CAST(MOVPRO.BDVLRCOFINS AS NUMERIC(15,2))) BDVLR
                                                   FROM VEF_EMP_TMOVPROENT MOVPRO
                                                   WHERE (M.BDCODEMP = MOVPRO.BDCODEMP AND M.BDCHAVE = MOVPRO.BDCHAVE)) > 0)
              GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO;
            END

         INSERT INTO TMP_VEF_EMP_TMOVENTINFCOM (BDCODEMP,BDCHAVE,BDORDEMIC,BDORDEMINFCOM,BDDESCCOMPIC)
         SELECT INF.BDCODEMP,INF.BDCHAVE,INF.BDORDEMIC,INF.BDORDEMINFCOM,
                COALESCE(TRIM(SUBSTRING(INF.BDDESCCOMPIC FROM 1 FOR 255)), '')
         FROM (SELECT M.BDCODEMP, M.BDCHAVE
               FROM TMP_VEF_EMP_TMOVENT M
               WHERE M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)) MOV
         JOIN VEF_EMP_TMOVENTINFCOM INF ON (INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE);

          SELECT MIN(t.bdCHAVE) AS bdCHAVEMIN, MAX(t.bdCHAVE) AS bdCHAVEMAX
          FROM TMP_VEF_EMP_TMOVENT t
          WHERE t.bdCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
          INTO :wCHAVEMIN, :wCHAVEMAX;

          /*****************************************************************************
           *                                   C100                                    *
           ****************************************************************************/
          /*Camilla M. Vamos separar a rotina do C100 pra quando for SCP, pois nas SCPs a gente vai fazer rateior e pegar valores de produtos
          processo que não é necessário para empresas que não tem relação com SCP*/
          IF (:PREXPORTAPORSCP = 'TRUE') THEN
             BEGIN
              INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODEMP, BDCODEMPPRO)
              SELECT REPLACE(:PRARQUIVO, '$empresa$', COALESCE(ENT.BDCODEMPSCP, ENT.BDCODEMP)) BDID,
                 'C100.'||LPAD(COALESCE(ENT.BDCODEMPSCP, ENT.BDCODEMP), 6, '0')||'.0.'|| LPAD(ent.BDCHAVE, 10, '0'),
                      'C100' BDREG,
                      ('|C100|0|'||M.BDEMITENTE||         --IND_EMIT
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF((M.BDMODELO = 65) AND (TER.BDCODTER IS NULL), '', M.BDCODTER))|| --COD_PART
                       '|'||MOD.BDMODELOSTR||             --COD_MOD
                       '|'||LPAD(M.BDCODSITNF, 2, '0')||  --COD_SIT
                       '|'||M.BDSERIE||                   --SER
                       '|'||M.BDNUMDOCINI||               --NUM_DOC
                       '|'||COALESCE(IIF(M.BDMODELO IN (55, 65), (((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)))), NULL), '')|| --CHV_NFE
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))||    --DT_DOC
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAENTRADAENT, 'DDMMYYYY')))|| --DT_E_S
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(ENT.BDVLRCONTAB, '.', ','))|| --VL_DOC
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(((M.BDCONDPGTO = '2') AND (M.BDDATAEMISSAO < '07/01/2012')), '9', M.BDCONDPGTO))|| --IND_PGTO
                       '|'||CASE WHEN M.BDCODSITNF IN (2, 3, 4, 5) THEN '' --VL_DESC
                                 WHEN (ent.bdVLRDESC + ent.bdVLRABATNT) = M.BDDESCONTONOTA THEN
                                   REPLACE(COALESCE(IIF(M.BDVALORNOTA <> 0, CAST(((M.BDDESCONTONOTA*ENT.BDVLRCONTAB)/M.BDVALORNOTA) AS NUMERIC(15, 2)), COALESCE(M.BDDESCONTONOTA,0)), 0.00) - COALESCE(IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLRABATNT*ENT.BDVLRCONTAB)/M.BDVALORNOTA) AS NUMERIC(15, 2)), C100.BDVLRABATNT), 0.00), '.', ',') -- Alt.: #125909 #126894 #127057 #127296 #127440 #127528 #127589 #127562 #127779 #127586 - Se a soma do desconto + abatimento dos produtos for igual ao que possui no campo desconto da capa da nota, vai levar no campo "desconto" do C100 o desconto da capa da nota menos o abatimento...
                                 ELSE REPLACE(COALESCE(COALESCE(ENT.BDVLRDESC,IIF(M.BDVALORNOTA <> 0, CAST(((M.BDDESCONTONOTA*ENT.BDVLRCONTAB)/M.BDVALORNOTA) AS NUMERIC(15, 2)), COALESCE(M.BDDESCONTONOTA,0))), 0.00), '.', ',') END || -- Alt.: #125909 #126894 #127057 #127296 #127440 #127528 #127589 #127562 #127779 #127586 - Se a soma do desconto + abatimento dos produtos for diferente do que possui no campo desconto da capa da nota, vai levar no campo "desconto" do C100 o desconto da capa da nota...
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(COALESCE(ENT.BDVLRABATNT,IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLRABATNT*ENT.BDVLRCONTAB)/M.BDVALORNOTA) AS NUMERIC(15, 2)), C100.BDVLRABATNT)), 0.00), '.', ','))|| --VL_ABAT_NT
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(IIF(ENT.BDVLRITEM > 0, ENT.BDVLRITEM, M.BDVALORNOTA), 0.00), '.', ','))||    --VL_MERC
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', CASE WHEN (INDFRETEC100.BDCODEXPFRETE IS NULL) THEN '0' ELSE COALESCE(INDFRETEC100.BDCODEXPFRETE, '') END)|| --IND_FRT
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(COALESCE(ENT.BDVLRFRETE ,IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLRFRETE*ENT.BDVLRCONTAB)/M.BDVALORNOTA)AS NUMERIC(15, 2)), C100.BDVLRFRETE)), 0.00), '.', ','))||  --VL_FRT
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(COALESCE(ENT.BDVLRSEGURO,IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLRSEGURO*ENT.BDVLRCONTAB)/M.BDVALORNOTA)AS NUMERIC(15, 2)), C100.BDVLRSEGURO)), 0.00), '.', ','))|| --VL_SEG
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(COALESCE(ENT.BDVLRDESPACESSORIA,IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLROUTDESP*ENT.BDVLRCONTAB)/M.BDVALORNOTA)AS NUMERIC(15, 2)), C100.BDVLROUTDESP)), 0.00), '.', ','))||--VL_OUT_DA
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(ENT.BDBASEICMS, 0.00), '.', ','))||   --VL_BC_ICMS
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(ENT.BDVLRICMS, 0.00), '.', ','))||    --VL_ICMS
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(IIF(ENT.BDVLRST > 0, COALESCE(ENT.BDBASEST, 0.00),0.00), 0.00), '.', ','))|| --VL_BC_ICMS_ST -- #185951 
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(ENT.BDVLRST, 0.00), '.', ','))||           --VL_ICMS_ST
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(ENT.BDVLRIPI, 0.00), '.', ','))||          --VL_IPI
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(COALESCE(ENT.BDVLRTOTPIS, IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLRTOTPIS*ENT.BDVLRCONTAB)/M.BDVALORNOTA)AS NUMERIC(15, 2)), C100.BDVLRTOTPIS)), 0.00), '.', ',')) || --VL_PIS
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(COALESCE(ENT.BDVLRTOTCOFINS, IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLRTOTCOFINS*ENT.BDVLRCONTAB)/M.BDVALORNOTA)AS NUMERIC(15, 2)), C100.BDVLRTOTCOFINS)), 0.00), '.', ',')) || --VL_COFINS
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLRTOTPISST*ENT.BDVLRCONTAB)/M.BDVALORNOTA) AS NUMERIC(15, 2)), C100.BDVLRTOTPISST), 0.00), '.', ','))||    --VL_PIS_ST
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLRTOTCOFINSST*ENT.BDVLRCONTAB)/M.BDVALORNOTA) AS NUMERIC(15, 2)), C100.BDVLRTOTCOFINSST), 0.00), '.', ','))|| --VL_COFINS_ST
                       '|') BDLINHA, IIF((M.BDCODSITNF IN (2, 3, 4, 5)) OR ((M.BDMODELO = 65) AND (ter.BDCODTER IS NULL)) , NULL, M.BDCODTER) BDCODTER, COALESCE(ENT.BDCODEMPSCP, ENT.BDCODEMP), ENT.BDCODEMP BDCODEMPPRO
                FROM (SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODEMPSCP, SUM(BDVLRCONTAB) BDVLRCONTAB, SUM(BDVLRDESCONTO) BDVLRDESCONTO,
                             SUM(BDBASEICMS) BDBASEICMS, SUM(BDVLRICMS) BDVLRICMS, SUM(BDBASEST) BDBASEST, SUM(BDVLRST) BDVLRST,
                             SUM(BDVLRIPI) BDVLRIPI, SUM(BDVLRTOTPIS) BDVLRTOTPIS, SUM(BDVLRTOTCOFINS) BDVLRTOTCOFINS,
                             SUM(BDVLRITEM) BDVLRITEM, SUM(BDVLRDESC) BDVLRDESC, SUM(BDVLRABATNT) BDVLRABATNT,
                             SUM(MOV.BDVLRFRETE) BDVLRFRETE, SUM(MOV.BDVLRSEGURO) BDVLRSEGURO, SUM(MOV.BDVLRDESPACESSORIA) BDVLRDESPACESSORIA
                      FROM (SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDVLRCONTAB, MOV.BDVLRDESCONTO, MOV.BDBASEICMS, MOV.BDVLRICMS,
                                   MOV.BDBASEST, MOV.BDVLRST, MOV.BDVLRIPI, MOV.BDCODEMPSCP, SUM(PRO.BDVLRPIS) BDVLRTOTPIS,
                                   SUM(PRO.BDVLRCOFINS) BDVLRTOTCOFINS, SUM(COALESCE(PRO.BDVLRITEM, 0)) BDVLRITEM,
                                   SUM(PRO.BDVLRDESC) AS BDVLRDESC, SUM(PRO.BDVLRABATNT) AS BDVLRABATNT,
                                   SUM(PRO.BDVLRFRETE) BDVLRFRETE, SUM(PRO.BDVLRSEGURO) BDVLRSEGURO,SUM(PRO.BDVLRDESPACESSORIA) BDVLRDESPACESSORIA
                            FROM (SELECT MOV.BDCODEMP, MOV.BDCHAVE, EMPSCP.BDCODEMPSCP, I.BDORDEM,
                                         SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB,
                                         SUM(COALESCE(I.BDDESCONTO, 0.00)) BDVLRDESCONTO, SUM(COALESCE(I.BDBASEICMS, 0.00)) BDBASEICMS,
                                         SUM(COALESCE(I.BDVLRICMS, 0.00)) BDVLRICMS, SUM(COALESCE(I.BDBASEST, 0.0)) BDBASEST,
                                         SUM(COALESCE(I.BDVLRST, 0.00)) BDVLRST, SUM(COALESCE(I.BDVLRIPI, 0.00)) BDVLRIPI
                                  FROM TMP_VEF_EMP_TMOVENT MOV
                                  JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                                  LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PREXPORTAPORSCP = 'TRUE') AND (EMPSCP.BDCODEMP = I.BDCODEMP) AND (EMPSCP.BDREFEMP = I.BDREFSOC) AND (EMPSCP.BDCODSCP = I.BDCODSCP)
                                  GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, EMPSCP.BDCODEMPSCP, I.BDORDEM) MOV
                            LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND MOV.BDORDEM = PRO.BDORDEM)
                            GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDVLRCONTAB, MOV.BDVLRDESCONTO, MOV.BDBASEICMS, MOV.BDVLRICMS, MOV.BDBASEST, MOV.BDVLRST, MOV.BDVLRIPI, MOV.BDCODEMPSCP, MOV.BDORDEM
                      ) MOV
                      GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODEMPSCP
                ) ENT
                JOIN VEF_EMP_TMOVENT M ON (M.BDCODEMP = ENT.BDCODEMP AND M.BDCHAVE = ENT.BDCHAVE)
                JOIN VEF_BASE_TTABMODELOLAN MOD ON (MOD.BDMODELO = M.BDMODELO)
                LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = M.BDCODTER AND (SELECT BDRESULT
                                                                                    FROM STRTRAN((SELECT BDNUMERO
                                                                                                  FROM SP_RETORNA_ALFANUMERICO(TER.BDCGCTER)), SUBSTRING(TER.BDCGCTER FROM 1 FOR 1), '')) <> '')
                LEFT OUTER JOIN VEF_EMP_TC100ENT C100 ON (C100.BDCODEMP = ENT.BDCODEMP AND C100.BDCHAVE = ENT.BDCHAVE)
                LEFT OUTER JOIN VEF_BASE_TTABINFRETE INDFRETEC100 ON (INDFRETEC100.BDORDEMFRETE = C100.BDINDFRETE);

             END
          ELSE
             BEGIN
              INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODEMP, BDCODEMPPRO)
              SELECT REPLACE(:PRARQUIVO, '$empresa$', ENT.BDCODEMP) BDID,
                  'C100.'||LPAD(ENT.BDCODEMP, 6, '0')||'.0.'|| LPAD(ent.BDCHAVE, 10, '0'),
                  'C100' BDREG,
                  ('|C100|0|'||M.BDEMITENTE||         --IND_EMIT
              --     '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(0, M.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))))|| --COD_PART
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF((M.BDMODELO = 65) AND (TER.BDCODTER IS NULL), '', M.BDCODTER))|| --COD_PART
                   '|'||MOD.BDMODELOSTR||             --COD_MOD
                   '|'||LPAD(M.BDCODSITNF, 2, '0')||  --COD_SIT
                   '|'||M.BDSERIE||                   --SER
                   '|'||M.BDNUMDOCINI||               --NUM_DOC
                   '|'||COALESCE(IIF(M.BDMODELO IN (55, 65), (((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)))), NULL), '')|| --CHV_NFE
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))||    --DT_DOC
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAENTRADAENT, 'DDMMYYYY')))|| --DT_E_S
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(ENT.BDVLRCONTAB, '.', ','))|| --VL_DOC
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(((M.BDCONDPGTO = '2') AND (M.BDDATAEMISSAO < '07/01/2012')), '9', M.BDCONDPGTO))|| --IND_PGTO
                   --'|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(M.BDDESCONTONOTA, 0.00) - COALESCE(C100.BDVLRABATNT, 0.00), '.', ','))||   --VL_DESC
                   '|'||CASE WHEN M.BDCODSITNF IN (2, 3, 4, 5) THEN '' --VL_DESC
                                                                                    --Erro, desconto retornava negativo quando abatimento era maior que o desconto - #143031 #144139
                                 WHEN (ent.bdVLRDESC + ent.bdVLRABATNT = M.BDDESCONTONOTA) THEN REPLACE(IIF(M.bddescontonota >= COALESCE(C100.BDVLRABATNT, 0.00), COALESCE(M.BDDESCONTONOTA, 0.00) - COALESCE(C100.BDVLRABATNT, 0.00), 0.00), '.', ',') -- Alt.: #125909 #126894 #127057 #127296 #127440 #127528 #127589 #127562 #127779 #127586 - Se a soma do desconto + abatimento dos produtos for igual ao que possui no campo desconto da capa da nota, vai levar no campo "desconto" do C100 o desconto da capa da nota menos o abatimento...
                        ELSE REPLACE(COALESCE(m.bdDESCONTONOTA, 0.00), '.', ',') END|| -- Alt.: #125909 #126894 #127057 #127296 #127440 #127528 #127589 #127562 #127779 #127586 - Se a soma do desconto + abatimento dos produtos for diferente do que possui no campo desconto da capa da nota, vai levar no campo "desconto" do C100 o desconto da capa da nota...
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRABATNT, 0.00), '.', ','))|| --VL_ABAT_NT
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(IIF(ENT.BDVLRITEM > 0, ENT.BDVLRITEM, M.BDVALORNOTA), 0.00), '.', ','))||    --VL_MERC
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', CASE WHEN (INDFRETEC100.BDCODEXPFRETE IS NULL) THEN '0' ELSE COALESCE(INDFRETEC100.BDCODEXPFRETE, '') END)|| --IND_FRT
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRFRETE, 0.00), '.', ','))||  --VL_FRT
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRSEGURO, 0.00), '.', ','))|| --VL_SEG
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLROUTDESP, 0.00), '.', ','))||--VL_OUT_DA
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(ENT.BDBASEICMS, 0.00), '.', ','))||   --VL_BC_ICMS
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(ENT.BDVLRICMS, 0.00), '.', ','))||    --VL_ICMS
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(IIF(ENT.BDVLRST > 0, COALESCE(ENT.BDBASEST, 0.00),0.00), 0.00), '.', ','))|| --VL_BC_ICMS_ST -- #185951
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(ENT.BDVLRST, 0.00), '.', ','))||           --VL_ICMS_ST
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(ENT.BDVLRIPI, 0.00), '.', ','))||          --VL_IPI
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(COALESCE(ENT.BDVLRTOTPIS, C100.BDVLRTOTPIS), 0.00), '.', ',')) || --VL_PIS
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(COALESCE(ENT.BDVLRTOTCOFINS, C100.BDVLRTOTCOFINS), 0.00), '.', ',')) || --VL_COFINS
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRTOTPISST, 0.00), '.', ','))||    --VL_PIS_ST
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRTOTCOFINSST, 0.00), '.', ','))|| --VL_COFINS_ST
                       '|') BDLINHA, IIF((M.BDCODSITNF IN (2, 3, 4, 5)) OR ((M.BDMODELO = 65) AND (ter.BDCODTER IS NULL)) , NULL, M.BDCODTER) BDCODTER, M.BDCODEMP, M.BDCODEMP BDCODEMPPRO
        FROM (SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDVLRCONTAB, MOV.BDVLRDESCONTO, MOV.BDBASEICMS, MOV.BDVLRICMS, MOV.BDBASEST,
                     MOV.BDVLRST, MOV.BDVLRIPI, SUM(PRO.BDVLRPIS) BDVLRTOTPIS, SUM(PRO.BDVLRCOFINS) BDVLRTOTCOFINS, SUM(COALESCE(PRO.BDVLRITEM, 0)) BDVLRITEM,
                     SUM(COALESCE(pro.bdVLRDESC, 0)) AS bdVLRDESC, SUM(COALESCE(pro.bdVLRABATNT, 0)) AS bdVLRABATNT
              FROM (SELECT MOV.BDCODEMP, MOV.BDCHAVE, SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB,
                           SUM(COALESCE(I.BDDESCONTO, 0.00)) BDVLRDESCONTO, SUM(COALESCE(I.BDBASEICMS, 0.00)) BDBASEICMS,
                           SUM(COALESCE(I.BDVLRICMS, 0.00)) BDVLRICMS, SUM(COALESCE(I.BDBASEST, 0.0)) BDBASEST,
                           SUM(COALESCE(I.BDVLRST, 0.00)) BDVLRST, SUM(COALESCE(I.BDVLRIPI, 0.00)) BDVLRIPI
                    FROM TMP_VEF_EMP_TMOVENT MOV
                    JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                    GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
                    ) MOV
              LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE)
              GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDVLRCONTAB, MOV.BDVLRDESCONTO, MOV.BDBASEICMS, MOV.BDVLRICMS, MOV.BDBASEST, MOV.BDVLRST, MOV.BDVLRIPI
              ) ENT
        JOIN VEF_EMP_TMOVENT M ON (M.BDCODEMP = ENT.BDCODEMP AND M.BDCHAVE = ENT.BDCHAVE)
              JOIN VEF_BASE_TTABMODELOLAN MOD ON (MOD.BDMODELO = M.BDMODELO)
        LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.BDCODTER = m.bdcodter AND (SELECT BDRESULT FROM STRTRAN((SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(ter.BDCGCTER)), SUBSTRING(TER.BDCGCTER FROM 1 FOR 1), '')) <> '')
        LEFT OUTER JOIN VEF_EMP_TC100ENT C100 ON (C100.BDCODEMP = ENT.BDCODEMP AND C100.BDCHAVE = ENT.BDCHAVE)
        LEFT OUTER JOIN VEF_BASE_TTABINFRETE INDFRETEC100 ON (INDFRETEC100.BDORDEMFRETE = C100.BDINDFRETE);
             END

      /*****************************************************************************
       *                                   C110                                    *
       ****************************************************************************/ 
        INSERT INTO TEXPORTACAO_SPED (BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODINFCOM, BDORDEMINFCOM, BDCODEMP, BDCODEMPPRO)
        SELECT REPLACE(:PRARQUIVO, '$empresa$', COALESCE(MOVINF.BDCODEMPSCP, MOVINF.BDCODEMP)) BDID,
               'C100.' || LPAD(COALESCE(MOVINF.BDCODEMPSCP, MOVINF.BDCODEMP), 6, '0') || '.0.' || LPAD(MOVINF.BDCHAVE, 10, '0') || '.C110.' || LPAD(MOVINF.BDORDEMIC, 6, '0'),
               'C110' BDREG,
--               '|C110|' || COALESCE(CADINF.BDCODINFCOM, '') || '|' || COALESCE(TRIM(REPLACE(SUBSTRING(MOVINF.BDDESCCOMPIC FROM 1 FOR 255), '|', '')), '') || '|',
               '|C110|' || COALESCE(CADINF.BDCODINFCOM, '') || '|' || REPLACE(MOVINF.BDDESCCOMPIC, '|', '') || '|',
               CADINF.BDCODINFCOM, CADINF.BDORDEMINFCOM, COALESCE(MOVINF.BDCODEMPSCP, MOVINF.BDCODEMP), MOVINF.BDCODEMP BDCODEMPPRO
        FROM (SELECT INF.BDCODEMP, INF.BDCHAVE, INF.BDORDEMIC, INF.BDDESCCOMPIC, INF.BDORDEMINFCOM, EMPSCP.BDCODEMPSCP
      FROM (SELECT M.BDCODEMP, M.BDCHAVE
            FROM TMP_VEF_EMP_TMOVENT M
                    WHERE M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)) MOV
--              JOIN VEF_EMP_TMOVENTINFCOM INF ON (INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
              JOIN TMP_VEF_EMP_TMOVENTINFCOM INF ON (INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
              JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
              LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PREXPORTAPORSCP = 'TRUE') and (EMPSCP.BDCODEMP = I.BDCODEMP) AND (EMPSCP.BDREFEMP = I.BDREFSOC) AND (EMPSCP.BDCODSCP = I.BDCODSCP)
              GROUP BY INF.BDCODEMP, INF.BDCHAVE, INF.BDORDEMIC, INF.BDDESCCOMPIC, INF.BDORDEMINFCOM, EMPSCP.BDCODEMPSCP) MOVINF
        LEFT OUTER JOIN VEF_BASE_TCADINFCOM CADINF ON (CADINF.BDORDEMINFCOM = MOVINF.BDORDEMINFCOM AND CADINF.BDCODEMP = MOVINF.BDCODEMP);

      /*****************************************************************************
       *                                   C111                                    *
       ****************************************************************************/      

      insert into TEXPORTACAO_SPED (BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODEMP, BDCODEMPPRO)
      SELECT REPLACE(:PRARQUIVO, '$empresa$', ref.bdcodemp) BDID,
             'C100.' || lpad(ent.BDCODEMP, 6, '0') || '.0.' || lpad(REF.BDCHAVE, 10, '0') || '.C111.' || REF.BDREF || '.' || REF.BDINDPROCESSO || '.' || REF.BDNUMPROC,
             'C111',
             '|C111|' || coalesce(trim(REF.BDNUMPROC), '') || '|' || iif(REF.BDINDPROCESSO = '4', '9', coalesce(REF.BDINDPROCESSO, '')) || '|',
             coalesce(MOVINF.BDCODEMPSCP, ENT.BDCODEMP), ENT.BDCODEMP BDCODEMPPRO
      from (select MOV.BDCODEMP, MOV.BDCHAVE, EMPSCP.BDCODEMPSCP
            from (select M.BDCODEMP, M.BDCHAVE
                  from TMP_VEF_EMP_TMOVENT M
                  where M.BDCODSITNF not in (2, 3, 4, 5, 10, 11)) MOV
            join VEF_EMP_TMOVENTITENS I on (I.BDCODEMP = MOV.BDCODEMP and
                  I.BDCHAVE = MOV.BDCHAVE)
            left outer join TEMPRESAS_SCP EMPSCP on (:PREXPORTAPORSCP = 'TRUE') and
                  (EMPSCP.BDCODEMP = I.BDCODEMP) and
                  (EMPSCP.BDREFEMP = I.BDREFSOC) and
                  (EMPSCP.BDCODSCP = I.BDCODSCP)
            group by MOV.BDCODEMP, MOV.BDCHAVE, EMPSCP.BDCODEMPSCP) MOVINF
      join(select T.BDCODEMP, T.BDCHAVE,
                  0 as BDORDEMIC, 0 BDORDEMPROREF,
                  T.BDNUMPROC as BDNUMPROC, T.BDORDEMINDORIG as BDINDPROCESSO, T.BDREF
                                                                                               from SP_RET_REF_1010_1020_EXPORT('(mov.BDCODEMP in (' || :PRCODEMP || ')) and', null, :PRDTINI, :PRDTFIM, 'C509') T
                                                                                               union all
           select C.BDCODEMP, C.BDCHAVE, C.BDORDEMIC, C.BDORDEMPROREF, C.BDNUMPROC, C.BDINDPROCESSO, C.bdordemproref
           from (select * from VEF_EMP_TMOVENTPROREF C
                                                                                                     where C.BDCODEMP = :prcodemp) C
                                                                                               left outer join(select T.BDCHAVE
                                                                                                               from SP_RET_REF_1010_1020_EXPORT('(mov.BDCODEMP in (' || :PRCODEMP || ')) and', null, :PRDTINI, :PRDTFIM, 'C509') T) T on (T.BDCHAVE = C.BDCHAVE)
                                                                                               where T.BDCHAVE is null
      ) REF on (REF.BDCODEMP = MOVINF.BDCODEMP and REF.BDCHAVE = MOVINF.BDCHAVE)
      left outer join VEF_EMP_TMOVENT ENT on (MOVINF.BDCODEMP = ENT.BDCODEMP and MOVINF.BDCHAVE = ENT.BDCHAVE);

      /*****************************************************************************
       *                                   C120                                    *
       ****************************************************************************/ 
        INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODEMP, BDCODEMPPRO)
        SELECT REPLACE(:PRARQUIVO, '$empresa$', COALESCE(MOV.BDCODEMPSCP, ENT.BDCODEMP)) BDID,
               'C100.' || LPAD(COALESCE(MOV.BDCODEMPSCP, ENT.BDCODEMP), 6, '0') || '.0.' || LPAD(MOV.BDCHAVE, 10, '0') || '.C120.' || LPAD(C120.BDORDEMOPIMP, 6, '0'),
               'C120', '|C120' || '|' || COALESCE(C120.BDCODDOCIMP, '') || --COD_DOC_IMP
               '|' || COALESCE(C120.BDNUMDOCIMP, '') || --NUM_DOC__IMP
               --'|' || REPLACE(CAST(COALESCE((MOV.BDVLRCONTAB / ENT.BDVALORNOTA) * C120.BDVLRPAGOPIS, 0.00) AS NUMERIC(15,2)), '.', ',') || --PIS_IMP
               '|' || REPLACE(CAST(COALESCE(IIF(ENT.BDVALORNOTA > 0,((MOV.BDVLRCONTAB / ENT.BDVALORNOTA) * C120.BDVLRPAGOPIS),0.00), 0.00) AS NUMERIC(15,2)), '.', ',') || --PIS_IMP
               --'|' || REPLACE(CAST(COALESCE((MOV.BDVLRCONTAB / ENT.BDVALORNOTA) * C120.BDVLRPAGOCOFINS, 0.00) AS NUMERIC(15,2)), '.', ',') || --COFINS_IMP
               '|' || REPLACE(CAST(COALESCE(IIF(ENT.BDVALORNOTA > 0,((MOV.BDVLRCONTAB / ENT.BDVALORNOTA) * C120.BDVLRPAGOCOFINS),0.00), 0.00) AS NUMERIC(15,2)), '.', ',') || --COFINS_IMP
               '|' || COALESCE(C120.BDNUMDRAW, '') || --NUM_ACDRAW
               '|', COALESCE(MOV.BDCODEMPSCP, ENT.BDCODEMP), ENT.BDCODEMP BDCODEMPPRO
        FROM (SELECT MOV.BDCODEMP, MOV.BDCHAVE, EMPSCP.BDCODEMPSCP, SUM(I.BDVLRCONTAB) BDVLRCONTAB
              FROM (SELECT M.BDCODEMP, M.BDCHAVE
            FROM TMP_VEF_EMP_TMOVENT M
                    WHERE M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)) MOV
              JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
              LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PREXPORTAPORSCP = 'TRUE') and (EMPSCP.BDCODEMP = I.BDCODEMP) AND (EMPSCP.BDREFEMP = I.BDREFSOC) AND (EMPSCP.BDCODSCP = I.BDCODSCP)
              GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, EMPSCP.BDCODEMPSCP) MOV
        JOIN VEF_EMP_TMOVENTOPIMP C120 ON (C120.BDCODEMP = MOV.BDCODEMP AND C120.BDCHAVE = MOV.BDCHAVE)
      LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (MOV.BDCODEMP = ENT.BDCODEMP AND MOV.BDCHAVE = ENT.BDCHAVE);

      /*****************************************************************************
       *                                   C170                                    *
       ****************************************************************************/
      SETORDEMSEQUENCIAL_STR(:prCODEMP);

      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODEMP, BDCHAVE, BDCODPROD, BDCODNAT, BDCREDITO, BDANOCREDITO, BDCODPLAPADRAO, BDCREDITOREF, BDCREDITOPLAPADRAOREF, BDCTALON, BDCODEMPPRO)
      SELECT REPLACE(:PRARQUIVO, '$empresa$', COALESCE(EMPSCP.BDCODEMPSCP, M.BDCODEMP)) BDID,
              'C100.'||LPAD(COALESCE(EMPSCP.BDCODEMPSCP, M.BDCODEMP), 6, '0')||'.0.'||LPAD(pro.BDCHAVE, 10, '0')|| '.C170.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.'||GETORDEMSEQUENCIAL_STR(PRO.BDCHAVE,PRO.BDCODEMP),
              'C170' BDREG,
              '|C170'||
              --'|'||PRO.BDORDEMPRO|| --NUM_ITEM
              '|'||GETORDEMSEQUENCIAL_STR(COALESCE(EMPSCP.BDCODEMPSCP, M.BDCODEMP) || PRO.BDCHAVE, :prCODEMP)|| --NUM_ITEM
              --#Alt:21967. Quando a empresa não possuía o respectivo produto vinculado o registro estava levando vazio. Quando isso acontecer foi
              --tratado para levar a informação do produto Único. Esse tratamento é feito para o código e a descrição.
              --'|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')), COALESCE(VINC.BDCODPROD,''), COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
              --'|'||TRIM(REPLACE(COALESCE(VINC.BDDESCPROD, ''), '|', ''))|| --DESCR_COMPL
              '|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')),
                       IIF(((VINC.BDCODPROD IS NULL) OR (COALESCE(VINC.BDCODPROD,'') = '')),COALESCE(PROD_UNICO.BDCODPROD,''),COALESCE(VINC.BDCODPROD,'')),
                       COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
              '|'||TRIM(REPLACE(IIF(((VINC.BDDESCPROD IS NULL) OR (VINC.BDDESCPROD = '')),
                                    COALESCE(PROD_UNICO.BDDESCRICAOUNICA,''),
                                    COALESCE(VINC.BDDESCPROD,'')), '|', ''))|| --DESCR_COMPL
              '|'||REPLACE(CAST(COALESCE(PRO.BDQTDITEM, 0.00) AS NUMERIC(15, 5)), '.', ',')|| --QTD
              '|'||COALESCE(IIF(((UN.BDAPEUNIMED IS NULL) OR (UN.BDAPEUNIMED = '')), UN_REF.BDAPEUNIMED, UN.BDAPEUNIMED), '')|| --UNID
              '|'||REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ',')|| --VL_ITEM
              '|'||REPLACE(COALESCE(PRO.BDVLRDESC, 0.00), '.', ',')|| --VL_DESC
              '|'||IIF((UPPER(PRO.BDMOVFISICO) = 'TRUE'), 0, 1)|| --IND_MOV
              '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
              '|'||COALESCE(SUBSTRING(I.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
              '|'||COALESCE(I.BDCODNAT, '')|| --COD_NAT
              '|'||REPLACE(IIF(((PRO.BDVLRICMS > 0) OR (:WEXBCPISCOF <> 'TRUE')), COALESCE(PRO.BDBCICMS, ''), '0.00'), '.', ',')|| --VL_BC_ICMS
              '|'||REPLACE(CAST(COALESCE(PRO.BDALIQICMS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
              '|'||REPLACE(IIF(((PRO.BDVLRICMS > 0) OR (:WEXBCPISCOF <> 'TRUE')), COALESCE(PRO.BDVLRICMS, 0.00), COALESCE(CAST(IIF(((PRO.BDVLRITEM = 0) AND (SUMM.BDBCICMS = 0)), 0, (PRO.BDVLRITEM / SUMM.BDBCICMS)) * ORI.BDVLRICMS AS DM_NUMERIC_15_2), 0.00)), '.', ',')|| --VL_ICMS
              '|'||REPLACE(IIF(COALESCE(PRO.BDVLRSTTOT, 0) = 0, 0, COALESCE(PRO.BDBCST, 0.00)), '.', ',')||   --VL_BC_ICMS_ST
              '|'||REPLACE(IIF(COALESCE(PRO.BDVLRSTTOT, 0) = 0, 0, CAST(COALESCE(PRO.BDALIQST, 0.00) AS DM_NUMERIC_15_2)), '.', ',')|| --ALIQ_ST
              '|'||REPLACE(IIF(COALESCE(PRO.BDVLRSTTOT, 0) = 0, 0, COALESCE(PRO.BDVLRST, 0.00)), '.', ',')||  --VL_ICMS_ST
              '|'|| --IND_APUR
              '|'||IIF(IPI.BDCODCSTIPI IS NULL, '', LPAD(COALESCE(IPI.BDCODEXPCSTIPI, ''), 2, 0))|| --CST_IPI
              '|'|| --COD_ENQ
              '|'||REPLACE(COALESCE(PRO.BDBCIPI, 0.00), '.', ',')|| --VL_BC_IPI
              '|'||REPLACE(CAST(COALESCE(PRO.BDALIQIPI, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_IPI
              '|'||REPLACE(COALESCE(PRO.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
              '|'||COALESCE(PIS.BDCSTPIS, '')|| --CST_PIS
              '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE','',REPLACE(CAST(COALESCE(PRO.BDBCPIS, 0.00) AS DM_NUMERIC_15_2), '.', ','))|| --VL_BC_PIS     //#87630 #81751 Se a CST é igual a 3 as informações de PIS e COFINS devem ser levadas nos campos 28,29 e 34,35
              '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE','',REPLACE(CAST(COALESCE(PRO.BDALIQPIS, 0.00) AS dm_numeric_7_4_aliq), '.', ','))|| --ALIQ_PIS
              '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(COALESCE(PRO.BDBCPIS, 0.000), '.', ','),'')|| --QUANT_BC_PIS
              '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(CAST(COALESCE(PRO.BDALIQPIS, 0.00)  AS dm_numeric_7_4_aliq),'.', ','),'')|| --ALIQ_PIS(em reais)
              '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(CAST(COALESCE(PRO.BDBCPIS, 0.00) * COALESCE(PRO.BDALIQPIS, 0.00) AS DM_NUMERIC_15_2), '.', ','),REPLACE(COALESCE(PRO.BDVLRPIS, 0.00), '.', ','))|| --VL_PIS
              '|'||COALESCE(COF.BDCSTCOF, '')|| --CST_COFINS
              '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE','',REPLACE(CAST(COALESCE(PRO.BDBCCOFINS, 0.00) AS DM_NUMERIC_15_2), '.', ','))|| --VL_BC_COFINS
              '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE','',REPLACE(CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS dm_numeric_7_4_aliq), '.', ','))|| --ALIQ_COFINS
              '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(COALESCE(PRO.BDBCCOFINS, 0.000), '.', ','),'')|| --QUANT_BC_COFINS
              '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS dm_numeric_7_4_aliq), '.', ',') ,'')|| --ALIQ_COFINS(em reais)
              '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(CAST(COALESCE(PRO.BDBCCOFINS, 0.00) * CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS dm_numeric_7_4_aliq) AS DM_NUMERIC_15_2), '.', ','),REPLACE(COALESCE(PRO.BDVLRCOFINS, 0.00), '.', ','))|| --VL_COFINS
              '|'||IIF(:WEXPCONTACONTAB = 'TRUE', COALESCE(COALESCE(CDL.BDCODTPLA, CDLRAT.BDCODTPLA), COALESCE(CON.BDCODTPLA,'')), COALESCE(COALESCE(CDL.BDCTALON, CDLRAT.BDCTALON), COALESCE(CON.BDCTALON,'')))|| --COD_CTA -- #123954 - Pedro Roweder - 12/03/2020
              '|', COALESCE(EMPSCP.BDCODEMPSCP, M.BDCODEMP), PRO.BDCHAVE, PRO.BDCODPROD, I.BDCODNAT, COALESCE(CDL.BDCODTPLA,CDLRAT.BDCODTPLA) BDCREDITO,
              COALESCE(COALESCE(CDLE.BDANO, CDLERAT.BDANO), CAST(SUBSTRING(M.BDREFLAN FROM 1 FOR 4) AS INTEGER)) BDANOCREDITO,
              COALESCE(PRO.BDCODPLAPADRAO, COALESCE(LAN.BDCODPLAPADRAO, LANRAT.BDCODPLAPADRAO)) BDCODPLAPADRAO, COALESCE(CDLEP.BDCODTPLAREF, CDLEPRAT.BDCODTPLAREF) BDCREDITOREF,
              COALESCE(CDLEP.BDCODPLAPADRAOREF, CDLEPRAT.BDCODPLAPADRAOREF) BDCREDITOPLAPADRAOREF, COALESCE(CDL.BDCTALON, CDLRAT.BDCTALON) BDCTALON, M.BDCODEMP BDCODEMPPRO
      FROM (                                                                    
            SELECT PRO.*, ENT.BDVLRSTTOT
            FROM (
                  SELECT ENT.BDCODEMP, ENT.BDCHAVE, SUM(COALESCE(I.BDVLRST, 0)) BDVLRSTTOT
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE
                        FROM (
                              SELECT M.BDCODEMP, M.BDCHAVE
                              FROM TMP_VEF_EMP_TMOVENT M
                              WHERE M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                               AND M.BDMODELO <> 65
                             ) MOV
                       ) ENT                     
                  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
                  GROUP BY ENT.BDCODEMP, ENT.BDCHAVE
                 )ENT 
            JOIN VEF_EMP_TMOVPROENT PRO ON(PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE)
            ORDER BY PRO.BDCODEMP, PRO.BDCHAVE,  PRO.BDORDEM, PRO.BDORDEMPRO
           ) PRO
      JOIN VEF_EMP_TMOVENT M ON (M.BDCODEMP = PRO.BDCODEMP AND M.BDCHAVE = PRO.BDCHAVE)
      JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = PRO.BDCODEMP AND I.BDCHAVE = PRO.BDCHAVE AND I.BDORDEM = PRO.BDORDEM)
      LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PREXPORTAPORSCP = 'TRUE') and (EMPSCP.BDCODEMP = I.BDCODEMP) AND (EMPSCP.BDREFEMP = I.BDREFSOC) AND (EMPSCP.BDCODSCP = I.BDCODSCP)
      /*Produto*/
      LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
      LEFT OUTER JOIN TUNIDADEMEDIDA UN ON(UN.BDCODUNIMED = VINC.BDCODUNIMED)
      LEFT OUTER JOIN TCADPRO PROD_UNICO ON(PROD_UNICO.BDCODPROD = PRO.BDCODPROD) --#Alt:21967.
      --LEFT OUTER JOIN TCADPRO_REF REF ON(REF.BDCODEMP = PRO.BDCODEMP AND REF.BDCODPROD = PRO.BDCODPROD AND ((UN.BDAPEUNIMED IS NULL) OR (UN.BDAPEUNIMED = '')))
      /*Produto por referência*/
      LEFT OUTER JOIN TCADPRO_VINC VINC_REF ON(VINC_REF.BDCODEMP = PRO.BDCODEMP AND VINC_REF.BDCODPROD = PRO.BDCODPROD)
      LEFT OUTER JOIN TUNIDADEMEDIDA UN_REF ON(UN_REF.BDCODUNIMED = VINC_REF.BDCODUNIMED)
      LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS)
      LEFT OUTER JOIN VEF_BASE_TTABCSTIPI IPI ON(IPI.BDCODCSTIPI = PRO.BDCODCSTIPI)
      LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON(PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
      LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON(COF.BDCODCSTCOF = PRO.BDCODCSTCOF)
      /* Alt.: #120050 - Quando a contabilização tinha desconto a conta do desconto vem primeiro...
      LEFT OUTER JOIN (SELECT BDCODEMP, BDCHAVEENT, BDORDEM, MIN(BDCHAVE) BDCHAVE
                       FROM TOL_VEF_EMP_TMOVENT
                       WHERE bdFORMULA LIKE '%NAT%LAN(%)' -- Alt.: #92219 - Apenas contas do valor contábil...
                       GROUP BY BDCODEMP, BDCHAVEENT, BDORDEM)  TOL ON (TOL.BDCODEMP = I.BDCODEMP AND TOL.BDCHAVEENT = I.BDCHAVE AND TOL.BDORDEM = I.BDORDEM)
      LEFT OUTER JOIN VSUC_EMPRESAS_TLAN LAN ON (LAN.BDCODEMP = TOL.BDCODEMP AND LAN.BDCHAVE = TOL.BDCHAVE) */
      LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVEENT, t.bdORDEM, t.BDCHAVE, l.bdCODPLAPADRAO, l.bdDEBITO
                       FROM (SELECT t.bdCODEMP, t.bdCHAVEENT, t.bdORDEM, MIN(t.bdCHAVE) AS BDCHAVE, T.BDCODEMPSUC
                             FROM TOL_VEF_EMP_TMOVENT t
                             LEFT OUTER JOIN VSUC_EMPRESAS_TLAN l ON (l.bdCODEMP = T.BDCODEMPSUC AND l.bdCHAVE = t.bdCHAVE)
                             WHERE t.bdFORMULA LIKE '%NAT%LAN(%)' -- Alt.: #92219 - Apenas contas do valor contábil...
                               AND l.bdDEBITO IS NOT NULL -- Alt.: #120050 - Para apenas retornar quando a contabilização tiver uma conta informada, quando tem desconto a conta do desconto vem primeiro...
                               AND t.bdCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
                               AND t.bdCHAVEENT BETWEEN :wCHAVEMIN AND :wCHAVEMAX
                             GROUP BY t.bdCODEMP, t.bdCHAVEENT, t.bdORDEM, T.BDCODEMPSUC
                             UNION ALL
                             SELECT i.bdCODEMP, i.bdCHAVE, i.bdORDEM, AUX.bdCHAVE, AUX.BDCODEMPSUC -- Alt.: #136112 - Quando não encontrar a conta na CFOP, vai buscar a primeira que tiver conta.
                             FROM VEF_EMP_TMOVENTITENS i
                             LEFT OUTER JOIN TOL_VEF_EMP_TMOVENT t ON(i.bdCODEMP = t.bdCODEMP AND i.bdCHAVE = t.bdCHAVEENT AND i.bdORDEM = t.bdORDEM)
                             LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVEENT, MIN(t.bdCHAVE) AS bdCHAVE, MIN(t.bdORDEM) AS BDORDEM, T.BDCODEMPSUC
                                              FROM TOL_VEF_EMP_TMOVENT t
                                              WHERE t.bdFORMULA LIKE '%NAT%LAN(%)' -- Alt.: #92219 - Apenas contas do valor contábil...
                                                AND t.bdCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
                                                AND t.bdCHAVEENT BETWEEN :wCHAVEMIN AND :wCHAVEMAX
                                              GROUP BY t.bdCODEMP, t.bdCHAVEENT, T.BDCODEMPSUC) AUX ON (AUX.bdCODEMP = i.bdCODEMP AND AUX.bdCHAVEENT = i.bdCHAVE)
                             WHERE t.bdCODEMP IS NULL
                               AND i.bdCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
                               AND i.bdCHAVE BETWEEN :wCHAVEMIN AND :wCHAVEMAX
                             GROUP BY i.bdCODEMP, i.bdCHAVE, i.bdORDEM, AUX.bdCHAVE, AUX.BDCODEMPSUC
                             ) t
                       LEFT OUTER JOIN VSUC_EMPRESAS_TLAN l ON (l.bdCODEMP = t.BDCODEMPSUC AND l.bdCHAVE = t.bdCHAVE)
                       WHERE l.bdDEBITO IS NOT NULL -- Alt.: #120050 - Para apenas retornar quando a contabilização tiver uma conta informada, quando tem desconto a conta do desconto vem primeiro...
                       ) LAN ON (lan.bdCODEMP = i.bdCODEMP AND lan.bdCHAVEENT = i.bdCHAVE AND lan.bdORDEM = i.bdORDEM)
      -- BEGIN - #99380 - Pedro Roweder
      LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVEENT, t.bdORDEM, CONT.bdcodplapadrao, MAX(CONT.bdcontadebprov) BDCODTPLA
                       FROM TOL_VEF_EMP_TMOVENT t
                       JOIN TCONF_CONTAS_ONLINE CONT ON (CONT.BDCODPLANOONLINE = :WCODPLANOONLINE AND CONT.BDFORMULA = SUBSTRING(t.BDFORMULA from 1 for 4)||'LAN'||SUBSTRING(t.BDFORMULA from POSITION('(' IN t.BDFORMULA) for ((POSITION(')' IN t.BDFORMULA) - POSITION('(' IN t.BDFORMULA) +1))))
                       WHERE t.bdFORMULA LIKE 'NAT%(%)'
                         AND t.bdCODEMP = IIF(:PRCODEMPSO > 0,:PRCODEMPSO,:PRCODEMP)
                         AND t.bdCHAVEENT BETWEEN :wCHAVEMIN AND :wCHAVEMAX
                       GROUP BY t.bdCODEMP, t.bdCHAVEENT, t.bdORDEM, CONT.bdcodplapadrao) LANB ON (LANB.bdCODEMP = i.bdCODEMP AND LANB.BDCHAVEENT = i.bdCHAVE AND LANB.bdORDEM = i.bdORDEM)
      LEFT OUTER JOIN PLANOS_TPLA CON ON (CON.bdcodplapadrao = LANB.BDCODPLAPADRAO AND CON.bdcodtpla = LANB.BDCODTPLA)
      -- END - #99380 - Pedro Roweder
      LEFT OUTER JOIN PLANOS_TPLA CDL ON (COALESCE(PRO.BDCODPLAPADRAO,LAN.BDCODPLAPADRAO) = CDL.BDCODPLAPADRAO AND COALESCE(PRO.BDCODTPLA,LAN.BDDEBITO) = CDL.BDCODTPLA)
      LEFT OUTER JOIN PLANOS_TPLA_ECF CDLE ON (CDLE.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF AND
                                               CDLE.BDANO = Coalesce((select max(BDANO)
                                                            from PLANOS_TPLA_ECF
                                                            where CDLE.BDCODPLAPADRAO = BDCODPLAPADRAO and
                                                                  CDLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF and
                                                                  CDLE.BDCODTPLA = BDCODTPLA
                                                                  and BDANO = :WANO and BDCODTPLAREF is not null
                                                                  ),
                                                                  (select max(BDANO)
                                                                   from PLANOS_TPLA_ECF
                                                                   where CDLE.BDCODPLAPADRAO = BDCODPLAPADRAO and
                                                                         CDLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF and
                                                                         CDLE.BDCODTPLA = BDCODTPLA
                                                                         and BDANO < :WANO and BDCODTPLAREF is not null
                                                                  )) AND
                                               CDLE.BDCODPLAPADRAO = CDL.BDCODPLAPADRAO AND CDLE.BDCODTPLA = CDL.BDCODTPLA) 
      LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO CDLEP ON (CDLE.BDCODPLAPADRAOREF = CDLEP.BDCODPLAPADRAOREF AND CDLE.BDCODTPLAREF = CDLEP.BDCODTPLAREF) 
      LEFT OUTER JOIN  (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) BDCHAVE, BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATENT GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM, BDCODEMPSUC) TOLRAT
                        ON (TOLRAT.BDCODEMP = I.BDCODEMP AND TOLRAT.BDCHAVELAN = I.BDCHAVE AND TOLRAT.BDORDEM = I.BDORDEM) 
      LEFT OUTER JOIN VSUC_EMPRESAS_TLAN LANRAT ON (LANRAT.BDCODEMP = TOLRAT.BDCODEMPSUC AND LANRAT.BDCHAVE = TOLRAT.BDCHAVE)
      LEFT OUTER JOIN PLANOS_TPLA CDLRAT ON (COALESCE(PRO.BDCODPLAPADRAO,LANRAT.BDCODPLAPADRAO) = CDLRAT.BDCODPLAPADRAO AND COALESCE(PRO.BDCODTPLA,LANRAT.BDDEBITO) = CDLRAT.BDCODTPLA)
      LEFT OUTER JOIN PLANOS_TPLA_ECF CDLERAT ON (CDLERAT.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF AND
                                               CDLERAT.BDANO = Coalesce((select max(BDANO)
                                                            from PLANOS_TPLA_ECF
                                                            where CDLERAT.BDCODPLAPADRAO = BDCODPLAPADRAO and
                                                                  CDLERAT.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF and
                                                                  CDLERAT.BDCODTPLA = BDCODTPLA
                                                                  and BDANO = :WANO and BDCODTPLAREF is not null
                                                                  ),
                                                                  (select max(BDANO)
                                                                   from PLANOS_TPLA_ECF
                                                                   where CDLERAT.BDCODPLAPADRAO = BDCODPLAPADRAO and
                                                                         CDLERAT.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF and
                                                                         CDLERAT.BDCODTPLA = BDCODTPLA
                                                                         and BDANO < :WANO and BDCODTPLAREF is not null
                                                                  )) AND
                                               CDLERAT.BDCODPLAPADRAO = CDLRAT.BDCODPLAPADRAO AND 
                                               CDLERAT.BDCODTPLA = CDLRAT.BDCODTPLA) 
      LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO CDLEPRAT ON (CDLERAT.BDCODPLAPADRAOREF = CDLEPRAT.BDCODPLAPADRAOREF AND CDLERAT.BDCODTPLAREF = CDLEPRAT.BDCODTPLAREF)
      LEFT OUTER JOIN(SELECT SUM(ORI.BDVLRICMS) BDVLRICMS, ORI.BDCODEMP, ORI.BDCHAVE, ORI.BDORDEM, ORI.BDCODPROD
                FROM VEF_EMP_TMOVPROENTIMPORI ORI
                GROUP BY ORI.BDCODEMP, ORI.BDCHAVE, ORI.BDORDEM, ORI.BDCODPROD) ORI ON (ORI.BDCODEMP = PRO.BDCODEMP AND ORI.BDCHAVE = PRO.BDCHAVE AND ORI.BDORDEM = PRO.BDORDEM AND ORI.BDCODPROD = PRO.BDCODPROD)
      LEFT OUTER JOIN(SELECT SUM(SUMM.BDVLRITEM) AS BDBCICMS, SUMM.BDCODEMP, SUMM.BDCHAVE, SUMM.BDORDEM, summ.bdcodprod
                FROM VEF_EMP_TMOVPROENT SUMM
                GROUP BY SUMM.BDCODEMP, SUMM.BDCHAVE, SUMM.BDORDEM, SUMM.BDCODPROD) SUMM ON (SUMM.BDCODEMP = PRO.BDCODEMP AND SUMM.BDCHAVE = PRO.BDCHAVE AND SUMM.BDORDEM = PRO.BDORDEM AND SUMM.BDCODPROD = PRO.BDCODPROD);

      /*****************************************************************************
       *                                   C175                                    *
       ****************************************************************************/ 
      IF (:PRDTINI >= '09/01/2014') THEN
      BEGIN
        INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODEMP, BDCHAVE, BDCODNAT, BDCREDITO, BDANOCREDITO, BDCODPLAPADRAO, BDCREDITOREF, BDCREDITOPLAPADRAOREF, BDCTALON, BDCODEMPPRO)
       SELECT REPLACE(:PRARQUIVO, '$empresa$', COALESCE(EMPSCP.BDCODEMPSCP, M.BDCODEMP)) BDID,
              'C100.'||LPAD(COALESCE(EMPSCP.BDCODEMPSCP, M.BDCODEMP), 6, '0')||'.0.'||LPAD(M.BDCHAVE, 10, '0')||'.C175.'||I.BDPREFIXONAT/*SUBSTRING(I.BDCODNAT FROM 1 FOR 4)*/||'.'||COALESCE(PRO.BDCODCSTPIS,'')||COALESCE(PRO.BDCODCSTCOF,'')||LPAD(COALESCE(PRO.BDALIQPIS,''), 3, '0')||LPAD(COALESCE(PRO.BDALIQCOFINS,''), 3, '0')
              ||'.'||PRO.BDPISCOFQTD, -- Alt.: #162997 - Incluido o campo "Lançar Pis e Cofins por quantidade" pois haviam notas em que tinham produtos com e sem esse parametro marcado...
              'C175' BDREG,
              ('|C175' || --REG
              '|' || COALESCE(I.BDPREFIXONAT/*SUBSTRING(I.BDCODNAT FROM 1 FOR 4)*/, '') || --CFOP
              '|' || REPLACE(SUM(PRO.BDVLRITEM), '.', ',') || --VL_OPR
              '|' || REPLACE(SUM(PRO.BDVLRDESC), '.', ',') || --VL_DESC
              '|' || LPAD(COALESCE(PRO.BDCODCSTPIS, ''), 2, '0') || --CST_PIS
              '|' || IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', '', REPLACE(CAST(SUM(PRO.BDBCPIS) AS DM_NUMERIC_15_2), '.', ',')) || --VL_BC_PIS
              '|' || IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', '', REPLACE(CAST(COALESCE(PRO.BDALIQPIS, 0.00) AS DM_NUMERIC_7_4_ALIQ), '.', ',')) || --ALIQ_PIS
              '|' || IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(SUM(PRO.BDBCPIS), '.', ','), '') || --QUANT_BC_PIS
              '|' || IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(CAST(COALESCE(PRO.BDALIQPIS, 0.00) AS DM_NUMERIC_7_4_ALIQ), '.', ','), '') || --ALIQ_PIS_QUANT
              '|' || REPLACE(SUM(PRO.BDVLRPIS), '.', ',') || --VL_PIS
              '|' || LPAD(COALESCE(PRO.BDCODCSTCOF, ''), 2, '0') || --CST_COFINS
              '|' || IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', '', REPLACE(CAST(SUM(PRO.BDBCCOFINS) AS DM_NUMERIC_15_2), '.', ',')) || --VL_BC_COFINS
              '|' || IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', '', REPLACE(CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS DM_NUMERIC_7_4_ALIQ), '.', ',')) || --ALIQ_COFINS
              '|' || IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(SUM(PRO.BDBCCOFINS), '.', ','), '') || --QUANT_BC_COFINS
              '|' || IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS DM_NUMERIC_7_4_ALIQ), '.', ','), '') || --ALIQ_COFINS_QUANT
              '|' || REPLACE(SUM(PRO.BDVLRCOFINS), '.', ',') || --VL_COFINS
              '|' || IIF(:WEXPCONTACONTAB = 'TRUE', MIN(COALESCE(COALESCE(CDL.BDCODTPLA, CDLRAT.BDCODTPLA), '')), MIN(COALESCE(COALESCE(CDL.BDCTALON, CDLRAT.BDCTALON), '')))|| --COD_CTA -- #123954 - Pedro Roweder - 12/03/2020
              '|' || --INFO_COMPL
       
              '|') BDLINHA, COALESCE(EMPSCP.BDCODEMPSCP, M.BDCODEMP), M.BDCHAVE, MIN(I.BDCODNAT), MIN(COALESCE(CDL.BDCODTPLA,CDLRAT.BDCODTPLA)) BDCREDITO,
              MIN(COALESCE(COALESCE(CDLE.BDANO, CDLERAT.BDANO), CAST(SUBSTRING(M.BDREFLAN FROM 1 FOR 4) AS INTEGER))) BDANOCREDITO,
              MIN(COALESCE(PRO.BDCODPLAPADRAO, COALESCE(TOL.BDCODPLAPADRAO, LANRAT.BDCODPLAPADRAO))) BDCODPLAPADRAO,
              MIN(COALESCE(CDLEP.BDCODTPLAREF, CDLEPRAT.BDCODTPLAREF)) BDCREDITOREF,
              MIN(COALESCE(CDLEP.BDCODPLAPADRAOREF, CDLEPRAT.BDCODPLAPADRAOREF)) BDCREDITOPLAPADRAOREF,
              MIN(COALESCE(CDL.BDCTALON, CDLRAT.BDCTALON)) BDCTALON, M.BDCODEMP BDCODEMPPRO
       FROM (SELECT BDCODEMP, BDCHAVE
             FROM TMP_VEF_EMP_TMOVENT
             WHERE BDMODELO = 65 AND
                   BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
            ) MOV
        JOIN VEF_EMP_TMOVENT M ON (MOV.BDCODEMP = M.BDCODEMP AND MOV.BDCHAVE = M.BDCHAVE)
        JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        JOIN(SELECT P.BDCODEMP, P.BDCHAVE, P.BDORDEM, SUM(COALESCE(P.BDVLRITEM, 0)) BDVLRITEM,
                               SUM(COALESCE(P.BDVLRDESC, 0.00)) BDVLRDESC, SUM(COALESCE(P.BDBCPIS, 0.00)) BDBCPIS,
                               SUM(COALESCE(P.BDBCCOFINS, 0.00)) BDBCCOFINS, SUM(COALESCE(P.BDVLRCOFINS, 0.00)) BDVLRCOFINS,
                               SUM(COALESCE(P.BDVLRPIS, 0.00)) BDVLRPIS, P.BDCODCSTPIS, P.BDCODCSTCOF, P.BDALIQPIS,
                               P.BDALIQCOFINS, MAX(BDCODPLAPADRAO) BDCODPLAPADRAO, MAX(BDCODTPLA) BDCODTPLA, COALESCE(P.BDPISCOFQTD,'FALSE') BDPISCOFQTD
                        FROM VEF_EMP_TMOVPROENT P
                        WHERE P.BDCODEMP = IIF(:PRCODEMPSO > 0,:PRCODEMPSO,:PRCODEMP)
                        GROUP BY P.BDCODEMP, P.BDCHAVE, P.BDORDEM, P.BDCODCSTPIS, P.BDCODCSTCOF, P.BDALIQPIS, P.BDALIQCOFINS, /*P.*/BDPISCOFQTD) PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
                LEFT OUTER JOIN(SELECT TOL.BDCODEMP, TOL.BDCHAVEENT, TOL.BDORDEM, MIN(LAN.BDCODPLAPADRAO) BDCODPLAPADRAO, MIN(LAN.BDDEBITO) BDDEBITO
                                FROM TOL_VEF_EMP_TMOVENT TOL
                                LEFT OUTER JOIN VSUC_EMPRESAS_TLAN LAN ON (LAN.BDCODEMP = TOL.BDCODEMPSUC AND LAN.BDCHAVE = TOL.BDCHAVE)
                                WHERE TOL.bdFORMULA LIKE '%NAT%LAN(%)'
                                GROUP BY TOL.BDCODEMP, TOL.BDCHAVEENT, TOL.BDORDEM) TOL ON (TOL.BDCODEMP = PRO.BDCODEMP AND TOL.BDCHAVEENT = PRO.BDCHAVE AND TOL.BDORDEM = PRO.BDORDEM)
        LEFT OUTER JOIN PLANOS_TPLA CDL ON (COALESCE(PRO.BDCODPLAPADRAO,TOL.BDCODPLAPADRAO) = CDL.BDCODPLAPADRAO AND COALESCE(PRO.BDCODTPLA,TOL.BDDEBITO) = CDL.BDCODTPLA)
        LEFT OUTER JOIN PLANOS_TPLA_ECF CDLE ON (CDLE.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF AND
                                               CDLE.BDANO = Coalesce((select max(BDANO)
                                                            from PLANOS_TPLA_ECF
                                                            where CDLE.BDCODPLAPADRAO = BDCODPLAPADRAO and
                                                                  CDLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF and
                                                                  CDLE.BDCODTPLA = BDCODTPLA
                                                                  and BDANO = :WANO and BDCODTPLAREF is not null
                                                                  ),
                                                                  (select max(BDANO)
                                                                   from PLANOS_TPLA_ECF
                                                                   where CDLE.BDCODPLAPADRAO = BDCODPLAPADRAO and
                                                                         CDLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF and
                                                                         CDLE.BDCODTPLA = BDCODTPLA
                                                                         and BDANO < :WANO and BDCODTPLAREF is not null
                                                                  )) AND
                                               CDLE.BDCODPLAPADRAO = CDL.BDCODPLAPADRAO AND CDLE.BDCODTPLA = CDL.BDCODTPLA) 
        LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO CDLEP ON (CDLE.BDCODPLAPADRAOREF = CDLEP.BDCODPLAPADRAOREF AND CDLE.BDCODTPLAREF = CDLEP.BDCODTPLAREF)
        LEFT OUTER JOIN  (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) BDCHAVE, BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATENT GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM, BDCODEMPSUC) TOLRAT
                          ON (TOLRAT.BDCODEMP = I.BDCODEMP AND TOLRAT.BDCHAVELAN = I.BDCHAVE AND TOLRAT.BDORDEM = I.BDORDEM)
        LEFT OUTER JOIN VSUC_EMPRESAS_TLAN LANRAT ON (LANRAT.BDCODEMP = TOLRAT.BDCODEMPSUC AND LANRAT.BDCHAVE = TOLRAT.BDCHAVE)
        LEFT OUTER JOIN PLANOS_TPLA CDLRAT ON (COALESCE(PRO.BDCODPLAPADRAO,LANRAT.BDCODPLAPADRAO) = CDLRAT.BDCODPLAPADRAO AND COALESCE(PRO.BDCODTPLA,LANRAT.BDDEBITO) = CDLRAT.BDCODTPLA)
        LEFT OUTER JOIN PLANOS_TPLA_ECF CDLERAT ON (CDLERAT.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF AND
                                               CDLERAT.BDANO = Coalesce((select max(BDANO)
                                                            from PLANOS_TPLA_ECF
                                                            where CDLERAT.BDCODPLAPADRAO = BDCODPLAPADRAO and
                                                                  CDLERAT.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF and
                                                                  CDLERAT.BDCODTPLA = BDCODTPLA
                                                                  and BDANO = :WANO and BDCODTPLAREF is not null
                                                                  ),
                                                                  (select max(BDANO)
                                                                   from PLANOS_TPLA_ECF
                                                                   where CDLERAT.BDCODPLAPADRAO = BDCODPLAPADRAO and
                                                                         CDLERAT.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF and
                                                                         CDLERAT.BDCODTPLA = BDCODTPLA
                                                                         and BDANO < :WANO and BDCODTPLAREF is not null
                                                                  )) AND
                                                      CDLERAT.BDCODPLAPADRAO = CDLRAT.BDCODPLAPADRAO AND
                                                      CDLERAT.BDCODTPLA = CDLRAT.BDCODTPLA)
        LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO CDLEPRAT ON (CDLERAT.BDCODPLAPADRAOREF = CDLEPRAT.BDCODPLAPADRAOREF AND CDLERAT.BDCODTPLAREF = CDLEPRAT.BDCODTPLAREF)
        LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PREXPORTAPORSCP = 'TRUE') and (EMPSCP.BDCODEMP = I.BDCODEMP) AND (EMPSCP.BDREFEMP = I.BDREFSOC) AND (EMPSCP.BDCODSCP = I.BDCODSCP)
        GROUP BY M.BDCODEMP, M.BDCHAVE, I.BDPREFIXONAT/*I.BDCODNAT*/, PRO.BDCODCSTPIS, PRO.BDCODCSTCOF, PRO.BDALIQPIS, PRO.BDALIQCOFINS, EMPSCP.BDCODEMPSCP, PRO.BDPISCOFQTD;
      END

          DELETE FROM TMP_VEF_EMP_TMOVENTINFCOM;
          DELETE FROM TMP_VEF_EMP_TMOVENT;
        END

   --   DELETE FROM TMP_TOL_VEF_EMP_TMOVENT;
    END
END
^

CREATE OR ALTER procedure SP_EXPORTA_C800_SAI_SPEDCONTR (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(100),
    PREXPORTAPORSCP DM_BOOLEAN,
    PRCODPLAPADRAOREF integer,
    WEXPCONTACONTAB DM_BOOLEAN,
    PREXCLUSAOICMS DM_BOOLEAN)
as
declare variable WDATA date;
declare variable WMIN integer;
declare variable WMAX integer;
declare variable WCHAVEREG varchar(80);
declare variable WCODNAT integer;
declare variable WALIQPIS numeric(15,6);
declare variable WALIQCOFINS numeric(15,6);
declare variable WCHAVE integer;
declare variable WORDEM integer;
begin
          INSERT INTO TMP_VEF_EMP_TMOVSAI(BDCODEMP, BDCHAVE, BDCODTER, BDCODSITNF, BDMODELO)
          SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO
          FROM (SELECT m.* FROM VEF_EMP_TMOVSAI m
                WHERE M.BDCODEMP = :PRCODEMP AND
                      M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM AND
                      M.BDMODELO = 59 AND
                      M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)) M;

         /*****************************************************************************
           *                                   C860                                    *
           ****************************************************************************/
      /*Salva os números de documento menores e maiores por data de emissao e modelo na DLL, na hora de montar o registro busca os dados na DLL*/
          FREEANDNIL_C800(0);
          FOR SELECT S.BDDATAEMISSAO, MIN(S.BDNUMDOCINI) BDMIN, MAX(S.BDNUMDOCINI) BDMAX
              FROM TMP_VEF_EMP_TMOVSAI TMP
              JOIN VEF_EMP_TMOVSAI S ON (S.BDCODEMP = TMP.BDCODEMP AND S.BDCHAVE = TMP.BDCHAVE)
              GROUP BY S.BDDATAEMISSAO, S.BDMODELO
              INTO :wData, :wMin, :wMax
          DO
            BEGIN
              SETNUMDOC_C800(:wData, 59, :wMin, :wMax);
            END
        
            INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODEMP, BDCODEMPPRO)
            SELECT REPLACE(:PRARQUIVO, '$empresa$', COALESCE(MOV.BDCODEMPSCP, MOV.BDCODEMP)) BDID,
                   'C860.' ||(COALESCE(MOV.BDCODEMPSCP, MOV.BDCODEMP) || '_' || COALESCE(MOV.BDNRSERIE, '') || '_' || MOV.BDDATAEMISSAO),
                   'C860' BDREG, '|C860|59' || '|' || COALESCE(MOV.BDNRSERIE, '') || --NR_SAT
                   '|' || COALESCE((SELECT BDDATA
                                    FROM SP_PARSE_DATE(MOV.BDDATAEMISSAO, 'DDMMYYYY')), '') || --DT_DOC
                   '|' || MOV.BDNUMDOCINI || --DOC_INI
                   '|' || MOV.BDNUMDOCFIM || --DOC_FIM
                   '|', COALESCE(MOV.BDCODEMPSCP, MOV.BDCODEMP), MOV.BDCODEMP BDCODEMPPRO
            FROM (SELECT M.BDCODEMP, M.BDDATAEMISSAO, GETNUMDOC_C800_MIN(M.BDDATAEMISSAO, 59) BDNUMDOCINI,
                         GETNUMDOC_C800_MAX(M.BDDATAEMISSAO, 59) BDNUMDOCFIM, EQ.BDNRSERIE, EMPSCP.BDCODEMPSCP    
                  FROM TMP_VEF_EMP_TMOVSAI TMP
                  JOIN VEF_EMP_TMOVSAI M ON (M.BDCODEMP = TMP.BDCODEMP AND M.BDCHAVE = TMP.BDCHAVE)
                  LEFT OUTER JOIN VEF_BASE_TEQUIPASAT EQ ON (EQ.BDCODEMP = M.BDCODEMP AND EQ.BDCODEQUIPSAT = M.BDCODEQUIPSAT)
                  JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                  LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PREXPORTAPORSCP = 'TRUE') and (EMPSCP.BDCODEMP = I.BDCODEMP) AND (EMPSCP.BDREFEMP = I.BDREFSOC) AND (EMPSCP.BDCODSCP = I.BDCODSCP)
                  GROUP BY M.BDCODEMP, M.BDDATAEMISSAO, BDNUMDOCINI, BDNUMDOCFIM, EQ.BDNRSERIE, EMPSCP.BDCODEMPSCP) MOV;
          /*****************************************************************************
           *                                   C870                                    *
           ****************************************************************************/
      /*Grava os dados cfop, alíquota pis, alíquota cofins na DLL*/
      FOR SELECT 'C860.'||(COALESCE(MOV.BDCODEMPSCP,MOV.BDCODEMP)||'_'||COALESCE(EQ.BDNRSERIE, '')||'_'||MOV.BDDATAEMISSAO||'.C870.'||MOV.BDNUMDOCINI||'_'||COALESCE(PRO.BDCODPROD, '')||'_'||LPAD(COALESCE(PIS.BDCSTPIS, ''), 3, '0')||'_'||LPAD(COALESCE(COF.BDCSTCOF, ''), 3, '0')||'_'||LPAD(COALESCE(PRO.BDCODPLAPADRAO, ''), 9, '0')||'_'||LPAD(COALESCE(PRO.BDCODTPLA, ''), 9, '0')) BDCHAVEREG,
                     MOV.BDCODNAT, PRO.BDALIQPIS, PRO.BDALIQCOFINS, MOV.BDCHAVE, MOV.BDORDEM
              FROM (
                    SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, SAI.BDCODEQUIPSAT,
                           SAI.BDDATAEMISSAO, I.BDCODNAT, SAI.BDNUMDOCINI, EMPSCP.BDCODEMPSCP
                    FROM (
                          SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODEQUIPSAT,
                                 MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI
                          FROM (
                                SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODEQUIPSAT, M.BDDATAEMISSAO,
                                       (SELECT GETNUMDOC_C800_MIN(M.BDDATAEMISSAO, 59) FROM RDB$DATABASE) BDNUMDOCINI
                                FROM TMP_VEF_EMP_TMOVSAI TMP
                                JOIN VEF_EMP_TMOVSAI M ON (M.BDCODEMP = TMP.BDCODEMP AND M.BDCHAVE = TMP.BDCHAVE)
                                WHERE M.BDCODEMP = :PRCODEMP
                                AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                                AND M.BDMODELO = 59
                                AND M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                               ) MOV
                         ) SAI
                    JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                    LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PREXPORTAPORSCP = 'TRUE') and (EMPSCP.BDCODEMP = I.BDCODEMP) AND (EMPSCP.BDREFEMP = I.BDREFSOC) AND (EMPSCP.BDCODSCP = I.BDCODSCP)
                   ) MOV
              LEFT OUTER JOIN VEF_BASE_TEQUIPASAT EQ ON (EQ.BDCODEMP = MOV.BDCODEMP AND EQ.BDCODEQUIPSAT = MOV.BDCODEQUIPSAT)
              LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
              LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON (PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
              LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON (COF.BDCODCSTCOF = PRO.BDCODCSTCOF)
              INTO :wChaveReg, :wCodNat, :wAliqPIS, :wAliqCofins, :wChave, :wOrdem
          DO
            BEGIN
              SET_C870(:wChaveReg, :wAliqPIS, :wAliqCofins, :wCodNat, :wChave, :wOrdem);
            END

          DELETE FROM TMP_TOL_VEF_EMP_TMOVSAI;
        
          INSERT INTO TMP_TOL_VEF_EMP_TMOVSAI(BDCHAVESAI, BDORDEM, BDCHAVE, BDCODEMP, BDCODEMPSUC)
          SELECT T.BDCHAVESAI, T.BDORDEM, MIN(T.BDCHAVE) BDCHAVE, T.BDCODEMP, BDCODEMPSUC
          FROM TMP_VEF_EMP_TMOVSAI S
          JOIN TOL_VEF_EMP_TMOVSAI T ON(T.BDCODEMP = S.BDCODEMP AND T.BDCHAVESAI = S.BDCHAVE)
          LEFT OUTER JOIN VSUC_EMPRESAS_TLAN LAN ON (LAN.BDCODEMP = T.BDCODEMPSUC AND LAN.BDCHAVE = T.BDCHAVE)
          WHERE t.bdFORMULA LIKE '%NAT%LAN(%)' -- Alt.: #92219 - Apenas contas do valor contábil...
          AND LAN.BDCREDITO IS NOT NULL
          GROUP BY T.BDCHAVESAI, T.BDORDEM, T.BDCODEMP, BDCODEMPSUC;

          INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD, BDCREDITO, BDANOCREDITO, BDCODPLAPADRAO, BDCREDITOREF, BDCREDITOPLAPADRAOREF, BDCTALON, BDCHAVE, BDCODEMP, BDCODEMPPRO)
          SELECT REPLACE(:PRARQUIVO, '$empresa$', COALESCE(MOV.BDCODEMPSCP, MOV.BDCODEMP)) BDID,
                 MOV.BDCHAVEREG,
                 'C870' BDREG,
                 '|C870'||
                 '|'||COALESCE(IIF(COALESCE(PRO_VINC.BDCODSAIDA, '') = '', PRO_VINC.BDCODPROD, PRO_VINC.BDCODSAIDA), '')|| --COD_ITEM
                 '|'||COALESCE(SUBSTRING(GETCFOP_C870(MOV.BDCHAVEREG) FROM 1 FOR 4), '')|| --CFOP
                 '|'||REPLACE(MOV.BDVLRITEM, '.', ',')|| --VL_ITEM
                 '|'||IIF(:prexclusaoicms = 'TRUE', REPLACE(MOV.BDVLRDESC + MOV.bdvlricms, '.', ','), REPLACE(MOV.BDVLRDESC, '.', ','))|| --VL_DESC
                 '|'||COALESCE(LPAD(MOV.BDCSTPIS, 2, '0'), '')|| --CST_PIS
                 '|'||REPLACE(CAST(MOV.BDBCPIS AS DM_NUMERIC_15_2), '.', ',')|| --VL_BC_PIS
                 '|'||COALESCE(REPLACE(CAST(IIF(MOV.BDALIQPIS = '', '0', MOV.BDALIQPIS) AS NUMERIC(8, 4)), '.', ','), '')|| --ALIQ_PIS
                 '|'||REPLACE(MOV.BDVLRPIS, '.', ',')|| --VL_PIS
                 '|'||COALESCE(LPAD(MOV.BDCSTCOF, 2, '0'), '')|| --CST_COFINS
                 '|'||REPLACE(CAST(MOV.BDBCCOFINS AS DM_NUMERIC_15_2), '.', ',')|| --VL_BC_COFINS
                 '|'||COALESCE(REPLACE(CAST(IIF(MOV.BDALIQCOFINS = '', '0', MOV.BDALIQCOFINS) AS NUMERIC(8, 4)), '.', ','), '')|| --ALIQ_COFINS
                 '|'||REPLACE(MOV.BDVLRCOFINS, '.', ',')|| --VL_COFINS
                 '|'||IIF(:WEXPCONTACONTAB = 'TRUE', COALESCE(COALESCE(CCL.BDCODTPLA, CCLRAT.BDCODTPLA), ''), COALESCE(COALESCE(CCL.BDCTALON, CCLRAT.BDCTALON), ''))|| --COD_CTA -- #123954 - Pedro Roweder - 12/03/2020
                 '|', PRO_VINC.BDCODPROD, COALESCE(ccl.bdcodtpla,cclrat.bdcodtpla) bdcredito, (SELECT BDDATA FROM SP_PARSE_DATE(COALESCE(LAN.BDDATA,MOV.BDDATAEMISSAO), 'YYYY')) bdanocredito,
                      COALESCE(MOV.bdcodplapadrao, lan.bdcodplapadrao) bdcodplapadrao, COALESCE(cclep.BDCODTPLAREF, ccderatp.BDCODTPLAREF) bdcreditoref,
                      COALESCE(cclep.BDCODPLAPADRAOREF, ccderatp.BDCODPLAPADRAOREF) bdcreditoplapadraoref, COALESCE(CCL.BDCTALON, CCLRAT.BDCTALON) BDCTALON,
                      MOV.BDCHAVE, COALESCE(MOV.BDCODEMPSCP, MOV.BDCODEMP) BDCODEMP, MOV.BDCODEMP BDCODEMPPRO
          FROM (
                SELECT MOV.BDCODEMP, MOV.BDNRSERIE, MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI, MOV.BDCODPROD, MOV.BDCSTPIS, MOV.BDCSTCOF, MOV.BDCODPLAPADRAO, MOV.BDCODTPLA,
                       GETCHAVE_C870(MOV.BDCHAVEREG) BDCHAVE, GETORDEM_C870(MOV.BDCHAVEREG) BDORDEM, MOV.BDCHAVEREG, MOV.BDVLRITEM, MOV.BDVLRDESC, MOV.BDBCPIS, MOV.BDVLRPIS, MOV.BDVLRICMS,
                       MOV.BDBCCOFINS, MOV.BDVLRCOFINS, GETALIQPIS_C870(MOV.BDCHAVEREG) BDALIQPIS, GETALIQCOFINS_C870(MOV.BDCHAVEREG) BDALIQCOFINS, MOV.BDREFLAN, MOV.BDCODEMPSCP
                FROM (
                      SELECT MOV.BDCODEMP, EQ.BDNRSERIE, MOV.BDDATAEMISSAO, MOV.BDREFLAN, MOV.BDNUMDOCINI, PRO.BDCODPROD, PIS.BDCSTPIS, COF.BDCSTCOF, PRO.BDCODPLAPADRAO, PRO.BDCODTPLA,
                         ('C860.'||COALESCE(MOV.BDCODEMPSCP, MOV.BDCODEMP)||'_'||COALESCE(EQ.BDNRSERIE, '')||'_'||MOV.BDDATAEMISSAO||'.C870.'||MOV.BDNUMDOCINI||'_'||COALESCE(PRO.BDCODPROD, '')||'_'||LPAD(COALESCE(PIS.BDCSTPIS, ''), 3, '0')||'_'||LPAD(COALESCE(COF.BDCSTCOF, ''), 3, '0')||'_'||LPAD(COALESCE(PRO.BDCODPLAPADRAO, ''), 9, '0')||'_'||LPAD(COALESCE(PRO.BDCODTPLA, ''), 9, '0')) BDCHAVEREG,
                             SUM(COALESCE(PRO.BDVLRITEM, 0)) BDVLRITEM,
                             SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC,
                             SUM(COALESCE(PRO.BDBCPIS, 0)) BDBCPIS,
                             SUM(COALESCE(PRO.BDVLRPIS, 0)) BDVLRPIS,
                             SUM(COALESCE(PRO.BDBCCOFINS, 0)) BDBCCOFINS,
                             SUM(COALESCE(PRO.BDVLRCOFINS, 0)) BDVLRCOFINS,
                             SUM(COALESCE(PRO.bdvlricms, 0)) BDVLRICMS,
                             MOV.BDCODEMPSCP
                      FROM (
                            SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, SAI.BDCODEQUIPSAT,
                                   SAI.BDDATAEMISSAO, SAI.BDNUMDOCINI, SAI.BDREFLAN, EMPSCP.BDCODEMPSCP
                            FROM (
                                  SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODEQUIPSAT,
                                         MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI, MOV.BDREFLAN
                                  FROM (
                                         SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODEQUIPSAT, M.BDDATAEMISSAO, M.BDREFLAN,
                                               (SELECT GETNUMDOC_C800_MIN(M.BDDATAEMISSAO, 59) FROM RDB$DATABASE) BDNUMDOCINI
                                         FROM TMP_VEF_EMP_TMOVSAI TMP
                                         JOIN VEF_EMP_TMOVSAI M ON (M.BDCODEMP = TMP.BDCODEMP AND M.BDCHAVE = TMP.BDCHAVE)
                                       ) MOV
                                 ) SAI
                            JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                            LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PREXPORTAPORSCP = 'TRUE') and (EMPSCP.BDCODEMP = I.BDCODEMP) AND (EMPSCP.BDREFEMP = I.BDREFSOC) AND (EMPSCP.BDCODSCP = I.BDCODSCP)
                           ) MOV
                      LEFT OUTER JOIN VEF_BASE_TEQUIPASAT EQ ON (EQ.BDCODEMP = MOV.BDCODEMP AND EQ.BDCODEQUIPSAT = MOV.BDCODEQUIPSAT)
                      LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
                      LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON (PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
                      LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON (COF.BDCODCSTCOF = PRO.BDCODCSTCOF)
                      GROUP BY MOV.BDCODEMP, EQ.BDNRSERIE, MOV.BDDATAEMISSAO, MOV.BDREFLAN, MOV.BDNUMDOCINI, PRO.BDCODPROD, PIS.BDCSTPIS, COF.BDCSTCOF, PRO.BDCODPLAPADRAO, PRO.BDCODTPLA, MOV.BDCODEMPSCP
                     ) MOV
               ) MOV
          JOIN TCADPRO_VINC PRO_VINC ON(PRO_VINC.BDCODEMP = MOV.BDCODEMP AND PRO_VINC.BDCODPROD = MOV.BDCODPROD)
          LEFT OUTER JOIN TMP_TOL_VEF_EMP_TMOVSAI TOL ON(TOL.BDCHAVESAI = MOV.BDCHAVE AND TOL.BDORDEM = MOV.BDORDEM)
          LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.BDCODEMP = tol.BDCODEMPSUC AND lan.bdchave = tol.BDCHAVE AND LAN.BDCREDITO IS NOT NULL)
          LEFT OUTER JOIN planos_tpla ccl ON (COALESCE(MOV.BDCODPLAPADRAO, lan.BDCODPLAPADRAO) = ccl.bdcodplapadrao AND COALESCE(MOV.bdcodtpla, lan.bdcredito) = ccl.bdcodtpla)
          LEFT OUTER JOIN PLANOS_TPLA_ECF ccle ON (ccle.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF
                                                   AND ccle.bdano = (SELECT FIRST 1 BDANO
                                                                     FROM PLANOS_TPLA_ECF
                                                                     WHERE CAST(BDANO || '01' AS INTEGER) <= MOV.BDREFLAN
                                                                     AND BDCODTPLAREF IS NOT NULL
                                                                     AND CCLE.BDCODPLAPADRAO = BDCODPLAPADRAO
                                                                     AND CCLE.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF
                                                                     AND CCLE.BDCODTPLA = BDCODTPLA
                                                                     ORDER BY BDANO DESC
                                                                    )
                                                   AND ccle.bdcodplapadrao = ccl.bdcodplapadrao AND ccle.bdcodtpla = ccl.bdcodtpla)
         LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO cclep ON (ccle.BDCODPLAPADRAOref = cclep.BDCODPLAPADRAOREF AND ccle.BDCODTPLAREF = cclep.BDCODTPLAREF)
         LEFT OUTER JOIN  (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) BDCHAVE, BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM, BDCODEMPSUC) tolrat ON (tolrat.bdcodemp = mov.bdcodemp AND tolrat.bdchavelan = mov.bdchave AND tolrat.bdordem = mov.bdordem)
         LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat ON (lanrat.BDCODEMP = tolrat.BDCODEMPSUC AND lanrat.bdchave = tolrat.BDCHAVE AND LANRAT.BDCREDITO IS NOT NULL)
         LEFT OUTER JOIN planos_tpla cclrat ON (lanrat.BDCODPLAPADRAO = cclrat.bdcodplapadrao AND lanrat.bdcredito = cclrat.bdcodtpla)
         LEFT OUTER JOIN PLANOS_TPLA_ECF ccderat ON (CCDERAT.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF AND
                                                     CCDERAT.bdano =(SELECT FIRST 1 BDANO 
                                                                     FROM PLANOS_TPLA_ECF 
                                                                     WHERE CAST(BDANO || '01' AS INTEGER) <= lanrat.bdreferencia AND 
                                                                       BDCODTPLAREF IS NOT NULL AND 
                                                                       CCDERAT.BDCODPLAPADRAO = BDCODPLAPADRAO AND 
                                                                       CCDERAT.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF AND 
                                                                       CCDERAT.BDCODTPLA = BDCODTPLA 
                                                                     ORDER BY BDANO DESC
                                                                    ) AND
                                                     ccderat.bdcodplapadrao = cclrat.bdcodplapadrao AND ccderat.bdcodtpla = cclrat.bdcodtpla)
         LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO ccderatp ON (ccderat.BDCODPLAPADRAOref = ccderatp.BDCODPLAPADRAOREF AND ccderat.BDCODTPLAREF = ccderatp.BDCODTPLAREF);
          /*****************************************************************************
           *                                   C890                                    *
           ****************************************************************************/
          INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODEMP, BDCODEMPPRO)
          SELECT REPLACE(:PRARQUIVO, '$empresa$', COALESCE(MOV.BDCODEMPSCP, MOV.BDCODEMP)) BDID,
                 MOV.BDCHAVEREG,
                 'C890' BDREG,
                 '|C890'||
                 '|'||COALESCE(MOV.BDNUMPROC, '')|| --NUM_PROC
                 '|'||COALESCE(MOV.BDORDEMINDORIG, '')||  --IND_PROC
                 '|', COALESCE(MOV.BDCODEMPSCP, MOV.BDCODEMP), MOV.BDCODEMP BDCODEMPPRO
          FROM (
            SELECT ('C860.'||COALESCE(MOV.BDCODEMPSCP, MOV.BDCODEMP)||'_'||COALESCE(MOV.BDNRSERIE, '')||'_'||MOV.BDDATAEMISSAO||'.C870.'||'99999999_'||'99999999_'||'999_'||'999_999999999.C890.'||C890.BDNUMPROC||'_'||C890.BDORDEMINDORIG) BDCHAVEREG,
                       C890.BDNUMPROC, C890.BDORDEMINDORIG, MOV.BDCODEMP, MOV.BDCODEMPSCP
                FROM (
                      SELECT M.BDCODEMP, M.BDDATAEMISSAO,
                             GETNUMDOC_C800_MIN(M.BDDATAEMISSAO, 59) BDNUMDOCINI,
                             GETNUMDOC_C800_MAX(M.BDDATAEMISSAO, 59) BDNUMDOCFIM,
                             EQ.BDNRSERIE,
                             EQ.BDCODEQUIPSAT,
                             EMPSCP.BDCODEMPSCP, I.bdchave
                      FROM TMP_VEF_EMP_TMOVSAI TMP
                      JOIN VEF_EMP_TMOVSAI M ON (M.BDCODEMP = TMP.BDCODEMP AND M.BDCHAVE = TMP.BDCHAVE)
                      LEFT OUTER JOIN VEF_BASE_TEQUIPASAT EQ ON (EQ.BDCODEMP = M.BDCODEMP AND EQ.BDCODEQUIPSAT = M.BDCODEQUIPSAT)
                      JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                      LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PREXPORTAPORSCP = 'TRUE') and (EMPSCP.BDCODEMP = I.BDCODEMP) AND (EMPSCP.BDREFEMP = I.BDREFSOC) AND (EMPSCP.BDCODSCP = I.BDCODSCP)
                      GROUP BY M.BDCODEMP, M.BDDATAEMISSAO, M.BDCODEQUIPSAT, BDNUMDOCINI, BDNUMDOCFIM, EQ.BDNRSERIE, EQ.BDCODEQUIPSAT, EMPSCP.BDCODEMPSCP, I.bdchave
                     ) MOV
                join(select * from SP_RET_REF_1010_1020_EXPORT('(mov.BDCODEMP in ('||:PRCODEMP||')) AND', NULL,:PRDTINI, :PRDTFIM, 'C890') T) C890 on (C890.BDCODEMP = MOV.BDCODEMP and C890.bdchave = mov.bdchave)
               ) MOV;
               
          DELETE FROM TMP_TOL_VEF_EMP_TMOVSAI;
          DELETE FROM TMP_VEF_EMP_TMOVSAI;
end^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOC_SAI_SPEDCONTR (
    PRCODEMP integer,
    PRCODPLAPADRAOREF integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRBLOCO varchar(4),
    PREXPORTAPORSCP varchar(5),
    PREXCLUSAOICMS DM_BOOLEAN,
    PRCODEMPSO integer = 0)
as
declare variable WDATA date;
declare variable WMIN integer;
declare variable WMAX integer;
declare variable WEXPCONTACONTAB DM_BOOLEAN;
declare variable WCHAVEREG varchar(80);
declare variable WCODNAT integer;
declare variable WALIQPIS numeric(15,6);
declare variable WALIQCOFINS numeric(15,6);
declare variable WINCTRIB integer;
declare variable WCODCRIT integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WEXPNFCOMVAL varchar(5);
declare variable WSOMENTEBLOCOP varchar(5);
declare variable WARQUIVO varchar(260);
declare variable WCHAVEMIN integer;
declare variable WCHAVEMAX integer;
declare variable WCODPLANOONLINE integer;
declare variable WANO integer;
BEGIN
  --Pega da matriz
  WARQUIVO = REPLACE(:PRARQUIVO, '$empresa$', :PRCODEMP);
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')));  
  WSOMENTEBLOCOP = 'FALSE';
  wexpnfcomval   = 'FALSE';
  WCODPLANOONLINE = -1;         
  WANO = Extract(year from PRDTFIM);

  SELECT FIRST 1 SPED.BDINCTRIB, SPED.BDCODCRIT, SPED.bdexpnfcomvalsai, SPED.bdsomenteblocop, EMP.BDCODPLANOONLINE, SPED.BDEXPCONTACONTAB
  FROM (SELECT COALESCE(E.BDCODMATRIZ, E.BDCODEMP) BDCODMATRIZ, BDCODPLANOONLINE
        FROM vw_tempresas_ref tbem
        JOIN TEMPRESAS E ON(E.BDCODEMP = TBEM.BDCODEMP)
        WHERE TBEM.BDCODEMP = :PRCODEMP
        GROUP BY BDCODMATRIZ, BDCODPLANOONLINE) EMP
  JOIN VW_INT_SPEDPISCOFINS_REF SPED ON(SPED.BDCODEMP = EMP.BDCODMATRIZ AND SPED.BDREFERENCIA <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')))
  ORDER BY SPED.BDREFERENCIA DESC
  INTO :wIncTrib, :wCodCrit, :wexpnfcomval, :WSOMENTEBLOCOP, :WCODPLANOONLINE, :WEXPCONTACONTAB;

  if ((:WINCTRIB is null) and (:PRCODEMPSO > 0)) then
    begin
      SELECT FIRST 1 SPED.BDINCTRIB, SPED.BDCODCRIT, SPED.bdexpnfcomvalsai, SPED.bdsomenteblocop, EMP.BDCODPLANOONLINE, SPED.BDEXPCONTACONTAB
      FROM (SELECT COALESCE(E.BDCODMATRIZ, E.BDCODEMP) BDCODMATRIZ, BDCODPLANOONLINE
            FROM vw_tempresas_ref tbem
            JOIN TEMPRESAS E ON(E.BDCODEMP = TBEM.BDCODEMP)
            WHERE TBEM.BDCODEMP = :PRCODEMPSO
            GROUP BY BDCODMATRIZ, BDCODPLANOONLINE) EMP
      JOIN VW_INT_SPEDPISCOFINS_REF SPED ON(SPED.BDCODEMP = EMP.BDCODMATRIZ AND SPED.BDREFERENCIA <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')))
      ORDER BY SPED.BDREFERENCIA DESC
      INTO :wIncTrib, :wCodCrit, :wexpnfcomval, :WSOMENTEBLOCOP, :WCODPLANOONLINE, :WEXPCONTACONTAB;
    end

  IF (NOT((:wIncTrib = 1) AND (:wCodCrit IN(1, 2)))) THEN
    BEGIN      
      IF ((:WSOMENTEBLOCOP <> 'TRUE') AND ((:PRBLOCO = 'C100') OR (:PRBLOCO = ''))) THEN
        BEGIN
          DELETE FROM TMP_VEF_EMP_TMOVSAIINFCOM;
          DELETE FROM TMP_VEF_EMP_TMOVSAI;   
        
          INSERT INTO TMP_VEF_EMP_TMOVSAI(BDCODEMP, BDCHAVE, BDCODTER, BDCODSITNF, BDMODELO)
          SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO
          FROM (SELECT m.* FROM VEF_EMP_TMOVSAI m
                WHERE (M.BDCODEMP = :PRCODEMP) AND
                       M.BDMODELO IN (1, 4, 55, 65, 100) AND
                       M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                  and  m.bdcodsitnf not in (10, 11)) M
          JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
          JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = I.BDCODNAT AND ((nat.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.BDNAOEXPEFDCONT)) <> TRIM('TRUE'))))
          WHERE ((:wexpnfcomval <> 'TRUE') OR (SELECT SUM(CAST(movpro.BDVLRPIS AS NUMERIC(15,2)) + CAST(movpro.BDVLRCOFINS AS NUMERIC(15,2))) BDVLR
                                               FROM vef_emp_tmovprosai movpro
                                               WHERE (M.bdcodemp = movpro.bdcodemp AND M.bdchave = movpro.bdchave)) > 0)
          GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.bdcodsitnf, M.BDMODELO;

          IF ((:PREXPORTAPORSCP = 'TRUE') AND (:PRCODEMPSO > 0)) THEN
            BEGIN
              --SELECT scp.bdCODSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = :PRCODEMPSO AND scp.bdCODEMPSCP = :PRCODEMP
              --INTO :WCODEMP;

              INSERT INTO TMP_VEF_EMP_TMOVSAI(BDCODEMP, BDCHAVE, BDCODTER, BDCODSITNF, BDMODELO)
              SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO
              FROM (SELECT m.* FROM VEF_EMP_TMOVSAI m
                    WHERE (M.BDCODEMP = :PRCODEMPSO) AND
                           M.BDMODELO IN (1, 4, 55, 65, 100) AND
                           M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                      and  m.bdcodsitnf not in (10, 11)) M
              JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
              JOIN VEF_BASE_TNATOP nat ON (nat.BDCODNAT = I.BDCODNAT AND ((nat.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(nat.BDNAOEXPEFDCONT)) <> TRIM('TRUE'))))
              WHERE ((:wexpnfcomval <> 'TRUE') OR (SELECT SUM(CAST(movpro.BDVLRPIS AS NUMERIC(15,2)) + CAST(movpro.BDVLRCOFINS AS NUMERIC(15,2))) BDVLR
                                                   FROM vef_emp_tmovprosai movpro
                                                   WHERE (M.bdcodemp = movpro.bdcodemp AND M.bdchave = movpro.bdchave)) > 0)
              GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.bdcodsitnf, M.BDMODELO;
            END

         INSERT INTO TMP_VEF_EMP_TMOVSAIINFCOM (BDCODEMP,BDCHAVE,BDORDEMIC,BDORDEMINFCOM,BDDESCCOMPIC)
         SELECT INF.BDCODEMP,INF.BDCHAVE,INF.BDORDEMIC,INF.BDORDEMINFCOM,
                COALESCE(TRIM(SUBSTRING(INF.BDDESCCOMPIC FROM 1 FOR 255)), '')
         FROM (SELECT M.BDCODEMP, M.BDCHAVE
               FROM TMP_VEF_EMP_TMOVSAI M
               WHERE M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)) MOV
         JOIN VEF_EMP_TMOVSAIINFCOM INF ON (INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE);

          SELECT MIN(t.bdCHAVE) AS bdCHAVEMIN, MAX(t.bdCHAVE) AS bdCHAVEMAX
          FROM TMP_VEF_EMP_TMOVSAI t
          WHERE t.bdCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
          INTO :wCHAVEMIN, :wCHAVEMAX;

          /*****************************************************************************
           *                                   C100                                    *
           ****************************************************************************/
         /*Camilla M. Vamos separar a rotina do C100 pra quando for SCP, pois nas SCPs a gente vai fazer rateior e pegar valores de produtos
          processo que não é necessário para empresas que não tem relação com SCP*/
          IF (:PREXPORTAPORSCP = 'TRUE') THEN
             BEGIN
              INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODEMP, BDCODEMPPRO)
              SELECT REPLACE(:PRARQUIVO, '$empresa$', COALESCE(SAI.BDCODEMPSCP, SAI.BDCODEMP)) BDID,
                      'C100.'||LPAD(COALESCE(SAI.BDCODEMPSCP, SAI.BDCODEMP), 6, '0')||'.1.'|| LPAD(m.BDCHAVE, 10, '0'),
                      'C100' BDREG,
                      ('|C100|1|'||M.BDEMITENTE||         --IND_EMIT
                       --'|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(0, M.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))))|| --COD_PART
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '',  IIF(M.BDMODELO = 65 AND TER.BDCODTER IS NULL, '', M.BDCODTER))|| --COD_PART
                       '|'||MOD.BDMODELOSTR||             --COD_MOD
                       '|'||LPAD(M.BDCODSITNF, 2, '0')||  --COD_SIT
                       '|'||M.BDSERIE||                   --SER
                       '|'||M.BDNUMDOCINI||               --NUM_DOC
                       '|'||COALESCE(IIF(M.BDMODELO IN (55, 65),IIF(M.BDCODSITNF IN (5), '',(((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE))))), NULL), '')|| --CHV_NFE
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))||    --DT_DOC
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATASAIDA, 'DDMMYYYY')))|| --DT_E_S
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(SAI.BDVLRCONTAB, '.', ','))|| --VL_DOC
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(((M.BDCONDPGTO = '2') AND (M.BDDATAEMISSAO < '07/01/2012')), '9', M.BDCONDPGTO))|| --IND_PGTO
                       --'|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(M.BDDESCONTONOTA, 0.00) - COALESCE(C100.BDVLRABATNT, 0.00), '.', ','))||   --VL_DESC
                       '|'||CASE WHEN M.BDCODSITNF IN (2, 3, 4, 5) THEN '' --VL_DESC
                                 WHEN (sai.bdVLRDESC + sai.bdVLRABATNT) = M.BDDESCONTONOTA THEN REPLACE(COALESCE(IIF(M.BDVALORNOTA <> 0, CAST(((M.BDDESCONTONOTA*SAI.BDVLRCONTAB)/M.BDVALORNOTA)AS NUMERIC(15, 2)), M.BDDESCONTONOTA), 0.00) - COALESCE(IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLRABATNT*SAI.BDVLRCONTAB)/M.BDVALORNOTA)AS NUMERIC(15, 2)), C100.BDVLRABATNT), 0.00), '.', ',') -- Alt.: #125909 #126894 #127057 #127296 #127440 #127528 #127589 #127562 #127779 #127586 - Se a soma do desconto + abatimento dos produtos for igual ao que possui no campo desconto da capa da nota, vai levar no campo "desconto" do C100 o desconto da capa da nota menos o abatimento...
                                 ELSE REPLACE(COALESCE(COALESCE(SAI.BDVLRDESC,IIF(M.BDVALORNOTA <> 0, CAST(((M.BDDESCONTONOTA*SAI.BDVLRCONTAB)/M.BDVALORNOTA) AS NUMERIC(15, 2)), M.BDDESCONTONOTA)), 0.00), '.', ',') END|| -- Alt.: #125909 #126894 #127057 #127296 #127440 #127528 #127589 #127562 #127779 #127586 - Se a soma do desconto + abatimento dos produtos for diferente do que possui no campo desconto da capa da nota, vai levar no campo "desconto" do C100 o desconto da capa da nota...
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(COALESCE(SAI.BDVLRABATNT,IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLRABATNT*SAI.BDVLRCONTAB)/M.BDVALORNOTA)AS NUMERIC(15, 2)), C100.BDVLRABATNT)), 0.00), '.', ','))|| --VL_ABAT_NT
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(IIF(SAI.BDVLRITEM > 0, SAI.BDVLRITEM, M.BDVALORNOTA), 0.00), '.', ','))||    --VL_MERC
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', CASE WHEN (INDFRETEC100.BDCODEXPFRETE IS NULL) THEN '0' ELSE COALESCE(INDFRETEC100.BDCODEXPFRETE, '') END)|| --IND_FRT
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(COALESCE(SAI.BDVLRFRETE,IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLRFRETE*SAI.BDVLRCONTAB)/M.BDVALORNOTA)AS NUMERIC(15, 2)), C100.BDVLRFRETE)), 0.00), '.', ','))||  --VL_FRT
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(COALESCE(SAI.BDVLRSEGURO,IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLRSEGURO*SAI.BDVLRCONTAB)/M.BDVALORNOTA)AS NUMERIC(15, 2)), C100.BDVLRSEGURO)), 0.00), '.', ','))|| --VL_SEG
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(COALESCE(SAI.BDVLRDESPACESSORIA,IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLROUTDESP*SAI.BDVLRCONTAB)/M.BDVALORNOTA)AS NUMERIC(15, 2)), C100.BDVLROUTDESP)), 0.00), '.', ','))||--VL_OUT_DA
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(SAI.BDBASEICMS, 0.00), '.', ','))||   --VL_BC_ICMS
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(SAI.BDVLRICMS, 0.00), '.', ','))||    --VL_ICMS
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(SAI.BDBASEST, 0.00), '.', ','))||          --VL_BC_ICMS_ST
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(SAI.BDVLRST, 0.00), '.', ','))||           --VL_ICMS_ST
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(SAI.BDVLRIPI, 0.00), '.', ','))||          --VL_IPI
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(COALESCE(SAI.BDVLRTOTPIS, COALESCE(IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLRTOTPIS*SAI.BDVLRCONTAB)/M.BDVALORNOTA) AS NUMERIC(15, 2)), C100.BDVLRTOTPIS), BDVLRTOTPISF500)), 0.00), '.', ','))||      --VL_PIS
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(COALESCE(SAI.BDVLRTOTCOFINS, COALESCE(IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLRTOTCOFINS*SAI.BDVLRCONTAB)/M.BDVALORNOTA) AS NUMERIC(15, 2)), C100.BDVLRTOTCOFINS), BDVLRTOTCOFINSF500)), 0.00), '.', ','))||   --VL_COFINS
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLRTOTPISST*SAI.BDVLRCONTAB)/M.BDVALORNOTA) AS NUMERIC(15, 2)), C100.BDVLRTOTPISST), 0.00), '.', ','))||    --VL_PIS_ST
                       '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(IIF(M.BDVALORNOTA <> 0, CAST(((C100.BDVLRTOTCOFINSST*SAI.BDVLRCONTAB)/M.BDVALORNOTA) AS NUMERIC(15, 2)), C100.BDVLRTOTCOFINSST), 0.00), '.', ','))|| --VL_COFINS_ST
                       '|') BDLINHA, IIF((M.BDCODSITNF IN (2, 3, 4, 5)) OR ((M.BDMODELO = 65) AND (TER.BDCODTER IS NULL)), NULL, M.BDCODTER) BDCODTER, COALESCE(SAI.BDCODEMPSCP, SAI.BDCODEMP), SAI.BDCODEMP BDCODEMPPRO
                FROM (SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODEMPSCP, SUM(BDVLRCONTAB) BDVLRCONTAB, SUM(BDVLRDESCONTO) BDVLRDESCONTO,
                             SUM(BDBASEICMS) BDBASEICMS, SUM(BDVLRICMS) BDVLRICMS, SUM(BDBASEST) BDBASEST, SUM(BDVLRST) BDVLRST,
                             SUM(BDVLRIPI) BDVLRIPI, SUM(BDVLRTOTPIS) BDVLRTOTPIS, SUM(BDVLRTOTCOFINS) BDVLRTOTCOFINS,
                             SUM(BDVLRITEM) BDVLRITEM, SUM(BDVLRDESC) BDVLRDESC, SUM(BDVLRABATNT) BDVLRABATNT,
                             SUM(MOV.BDVLRFRETE) BDVLRFRETE, SUM(MOV.BDVLRSEGURO) BDVLRSEGURO, SUM(MOV.BDVLRDESPACESSORIA) BDVLRDESPACESSORIA, SUM(BDVLRTOTPISF500) BDVLRTOTPISF500, SUM(BDVLRTOTCOFINSF500) BDVLRTOTCOFINSF500
                FROM (SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDVLRCONTAB, MOV.BDVLRDESCONTO, MOV.BDBASEICMS, MOV.BDVLRICMS, MOV.BDBASEST,
                             MOV.BDVLRST, MOV.BDVLRIPI, MOV.BDCODEMPSCP, SUM(PRO.BDVLRPIS) BDVLRTOTPIS,
                             SUM(PRO.BDVLRCOFINS) BDVLRTOTCOFINS, SUM(PRO.BDVLRITEM) BDVLRITEM,
                             SUM(PRO.BDVLRDESC) AS BDVLRDESC, SUM(PRO.BDVLRABATNT) AS BDVLRABATNT,
                             SUM(PRO.BDVLRFRETE) BDVLRFRETE, SUM(PRO.BDVLRSEGURO) BDVLRSEGURO,SUM(PRO.BDVLRDESPACESSORIA) BDVLRDESPACESSORIA, BDVLRTOTPISF500, BDVLRTOTCOFINSF500
                      FROM (SELECT MOV.BDCODEMP, MOV.BDCHAVE, EMPSCP.BDCODEMPSCP, I.BDORDEM,
                                   SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB, SUM(COALESCE(I.BDDESCONTO, 0.00)) BDVLRDESCONTO,
                                   SUM(COALESCE(I.BDBASEICMS, 0.00)) BDBASEICMS, SUM(COALESCE(I.BDVLRICMS, 0.00)) BDVLRICMS,
                                   SUM(COALESCE(I.BDBASEST, 0.0)) BDBASEST, SUM(COALESCE(I.BDVLRST, 0.00)) BDVLRST,
                                   SUM(COALESCE(I.BDVLRIPI, 0.00)) BDVLRIPI, SUM(COALESCE(F500.BDVLRPIS,0)) BDVLRTOTPISF500, SUM(COALESCE(F500.BDVLRCOF,0)) BDVLRTOTCOFINSF500
                            FROM TMP_VEF_EMP_TMOVSAI MOV
                            LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                            LEFT OUTER JOIN VEF_EMP_TF500SAI F500 ON (F500.BDCODEMP = I.BDCODEMP AND F500.BDCHAVE = I.BDCHAVE AND F500.BDORDEM = I.BDORDEM)
                            LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PREXPORTAPORSCP = 'TRUE') AND (EMPSCP.BDCODEMP = I.BDCODEMP) AND (EMPSCP.BDREFEMP = I.BDREFSOC) AND (EMPSCP.BDCODSCP = I.BDCODSCP)
                            GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, EMPSCP.BDCODEMPSCP, I.BDORDEM) MOV
                      LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
                      GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDVLRCONTAB, MOV.BDVLRDESCONTO, MOV.BDBASEICMS, MOV.BDVLRICMS, MOV.BDBASEST, MOV.BDVLRST, MOV.BDVLRIPI, MOV.BDCODEMPSCP, MOV.BDORDEM, BDVLRTOTPISF500, BDVLRTOTCOFINSF500) MOV
                GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODEMPSCP) SAI 
                JOIN VEF_EMP_TMOVSAI M ON (M.BDCODEMP = SAI.BDCODEMP AND M.BDCHAVE = SAI.BDCHAVE)
                JOIN VEF_BASE_TTABMODELOLAN MOD ON (MOD.BDMODELO = M.BDMODELO)
                LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.BDCODTER = m.bdcodter AND (SELECT BDRESULT FROM STRTRAN((SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(ter.BDCGCTER)), SUBSTRING(TER.BDCGCTER FROM 1 FOR 1), '')) <> '')
                LEFT OUTER JOIN VEF_EMP_TC100SAI C100 ON (C100.BDCODEMP = SAI.BDCODEMP AND C100.BDCHAVE = SAI.BDCHAVE)
                LEFT OUTER JOIN VEF_BASE_TTABINFRETE INDFRETEC100 ON (INDFRETEC100.BDORDEMFRETE = C100.BDINDFRETE);
             END
          ELSE
             BEGIN
              INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODEMP, BDCODEMPPRO)
              SELECT REPLACE(:PRARQUIVO, '$empresa$',SAI.BDCODEMP) BDID,
                  'C100.'||LPAD(SAI.BDCODEMP, 6, '0')||'.1.'|| LPAD(m.BDCHAVE, 10, '0'),
                  'C100' BDREG,
                  ('|C100|1|'||M.BDEMITENTE||         --IND_EMIT
                   --'|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(M.BDMODELO = 65, '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(0, M.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))))|| --COD_PART
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '',  IIF(M.BDMODELO = 65 AND TER.BDCODTER IS NULL, '', M.BDCODTER))|| --COD_PART
                   '|'||MOD.BDMODELOSTR||             --COD_MOD
                   '|'||LPAD(M.BDCODSITNF, 2, '0')||  --COD_SIT
                   '|'||M.BDSERIE||                   --SER
                   '|'||M.BDNUMDOCINI||               --NUM_DOC
                   '|'||COALESCE(IIF(M.BDMODELO IN (55, 65),IIF(M.BDCODSITNF IN (5), '',(((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE))))), NULL), '')|| --CHV_NFE
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))||    --DT_DOC
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATASAIDA, 'DDMMYYYY')))|| --DT_E_S
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(SAI.BDVLRCONTAB, '.', ','))|| --VL_DOC
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', IIF(((M.BDCONDPGTO = '2') AND (M.BDDATAEMISSAO < '07/01/2012')), '9', M.BDCONDPGTO))|| --IND_PGTO
                   --'|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(M.BDDESCONTONOTA, 0.00) - COALESCE(C100.BDVLRABATNT, 0.00), '.', ','))||   --VL_DESC
                   '|'||CASE WHEN M.BDCODSITNF IN (2, 3, 4, 5) THEN '' --VL_DESC
                                                                                                --Erro, desconto retornava negativo quando abatimento era maior que o desconto - #143031 #144139
                                 WHEN (sai.bdVLRDESC + sai.bdVLRABATNT) = m.bdDESCONTONOTA THEN REPLACE(IIF(M.BDDESCONTONOTA >= COALESCE(C100.bdvlrabatnt,0.00), COALESCE(M.BDDESCONTONOTA, 0.00) - COALESCE(C100.BDVLRABATNT, 0.00), 0.00), '.', ',') -- Alt.: #125909 #126894 #127057 #127296 #127440 #127528 #127589 #127562 #127779 #127586 - Se a soma do desconto + abatimento dos produtos for igual ao que possui no campo desconto da capa da nota, vai levar no campo "desconto" do C100 o desconto da capa da nota menos o abatimento...
                        ELSE REPLACE(COALESCE(m.bdDESCONTONOTA, 0.00), '.', ',') END|| -- Alt.: #125909 #126894 #127057 #127296 #127440 #127528 #127589 #127562 #127779 #127586 - Se a soma do desconto + abatimento dos produtos for diferente do que possui no campo desconto da capa da nota, vai levar no campo "desconto" do C100 o desconto da capa da nota...
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRABATNT, 0.00), '.', ','))|| --VL_ABAT_NT
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(IIF(SAI.BDVLRITEM > 0, SAI.BDVLRITEM, M.BDVALORNOTA), 0.00), '.', ','))||    --VL_MERC
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', CASE WHEN (INDFRETEC100.BDCODEXPFRETE IS NULL) THEN '0' ELSE COALESCE(INDFRETEC100.BDCODEXPFRETE, '') END)|| --IND_FRT
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRFRETE, 0.00), '.', ','))||  --VL_FRT
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRSEGURO, 0.00), '.', ','))|| --VL_SEG
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLROUTDESP, 0.00), '.', ','))||--VL_OUT_DA
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(SAI.BDBASEICMS, 0.00), '.', ','))||   --VL_BC_ICMS
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(SAI.BDVLRICMS, 0.00), '.', ','))||    --VL_ICMS
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(SAI.BDBASEST, 0.00), '.', ','))||          --VL_BC_ICMS_ST
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(SAI.BDVLRST, 0.00), '.', ','))||           --VL_ICMS_ST
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(SAI.BDVLRIPI, 0.00), '.', ','))||          --VL_IPI
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(COALESCE(IIF(SAI.BDVLRTOTPIS > 0, SAI.BDVLRTOTPIS, NULL), COALESCE(C100.BDVLRTOTPIS, SAI.BDVLRTOTPISF500)), 0.00), '.', ','))||      --VL_PIS
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(COALESCE(IIF(SAI.BDVLRTOTCOFINS > 0, SAI.BDVLRTOTCOFINS, NULL), COALESCE(C100.BDVLRTOTCOFINS, SAI.BDVLRTOTCOFINSF500)), 0.00), '.', ','))||   --VL_COFINS
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRTOTPISST, 0.00), '.', ','))||    --VL_PIS_ST
                   '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C100.BDVLRTOTCOFINSST, 0.00), '.', ','))|| --VL_COFINS_ST
                       '|') BDLINHA, IIF((M.BDCODSITNF IN (2, 3, 4, 5)) OR ((M.BDMODELO = 65) AND (TER.BDCODTER IS NULL)), NULL, M.BDCODTER) BDCODTER, M.BDCODEMP, M.BDCODEMP BDCODEMPPRO
            FROM (SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDVLRCONTAB, MOV.BDVLRDESCONTO, MOV.BDBASEICMS, MOV.BDVLRICMS, MOV.BDBASEST,
                         MOV.BDVLRST, MOV.BDVLRIPI, SUM(COALESCE(PRO.BDVLRPIS,0)) BDVLRTOTPIS, SUM(COALESCE(PRO.BDVLRCOFINS,0)) BDVLRTOTCOFINS, SUM(COALESCE(pro.BDVLRITEM, 0)) BDVLRITEM,
                         SUM(COALESCE(pro.bdVLRDESC, 0)) AS bdVLRDESC, SUM(COALESCE(pro.bdVLRABATNT, 0)) AS bdVLRABATNT, BDVLRTOTPISF500, BDVLRTOTCOFINSF500
                  FROM (
                        SELECT MOV.BDCODEMP, MOV.BDCHAVE, SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB,
                               SUM(COALESCE(I.BDDESCONTO, 0.00)) BDVLRDESCONTO, SUM(COALESCE(I.BDBASEICMS, 0.00)) BDBASEICMS,
                               SUM(COALESCE(I.BDVLRICMS, 0.00)) BDVLRICMS, SUM(COALESCE(I.BDBASEST, 0.0)) BDBASEST,
                               SUM(COALESCE(I.BDVLRST, 0.00)) BDVLRST, SUM(COALESCE(I.BDVLRIPI, 0.00)) BDVLRIPI, SUM(COALESCE(F500.BDVLRPIS,0)) BDVLRTOTPISF500, SUM(COALESCE(F500.BDVLRCOF,0)) BDVLRTOTCOFINSF500
                        FROM TMP_VEF_EMP_TMOVSAI MOV
                        LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                        LEFT OUTER JOIN VEF_EMP_TF500SAI F500 ON (F500.BDCODEMP = I.BDCODEMP AND F500.BDCHAVE = I.BDCHAVE AND F500.BDORDEM = I.BDORDEM)
                        GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
                        ) MOV
            
                  LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE)
                  GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDVLRCONTAB, MOV.BDVLRDESCONTO, MOV.BDBASEICMS, MOV.BDVLRICMS, MOV.BDBASEST, MOV.BDVLRST, MOV.BDVLRIPI, BDVLRTOTPISF500, BDVLRTOTCOFINSF500
                  ) SAI
            JOIN VEF_EMP_TMOVSAI M ON (M.BDCODEMP = SAI.BDCODEMP AND M.BDCHAVE = SAI.BDCHAVE)
            JOIN VEF_BASE_TTABMODELOLAN MOD ON (MOD.BDMODELO = M.BDMODELO)                                           
            LEFT OUTER JOIN VW_TTERCEIRO ter ON (ter.BDCODTER = m.bdcodter AND (SELECT BDRESULT FROM STRTRAN((SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(ter.BDCGCTER)), SUBSTRING(TER.BDCGCTER FROM 1 FOR 1), '')) <> '')
            LEFT OUTER JOIN VEF_EMP_TC100SAI C100 ON (C100.BDCODEMP = SAI.BDCODEMP AND C100.BDCHAVE = SAI.BDCHAVE)
            LEFT OUTER JOIN VEF_BASE_TTABINFRETE INDFRETEC100 ON (INDFRETEC100.BDORDEMFRETE = C100.BDINDFRETE);
             END

          /*****************************************************************************
           *                                   C110                                    *
           ****************************************************************************/  
            INSERT INTO TEXPORTACAO_SPED (BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODINFCOM, BDORDEMINFCOM, BDCODEMP, BDCODEMPPRO)
            SELECT REPLACE(:PRARQUIVO, '$empresa$', COALESCE(MOVINF.BDCODEMPSCP, MOVINF.BDCODEMP)) BDID,
                   'C100.' || LPAD(COALESCE(MOVINF.BDCODEMPSCP, MOVINF.BDCODEMP), 6, '0') || '.1.' || LPAD(MOVINF.BDCHAVE, 10, '0') || '.C110.' || LPAD(MOVINF.BDORDEMIC, 6, '0'),
                 'C110' BDREG,
--                   '|C110|' || COALESCE(CADINF.BDCODINFCOM, '') || '|' || COALESCE(TRIM(REPLACE(SUBSTRING(MOVINF.BDDESCCOMPIC FROM 1 FOR 255), '|', '')), '') || '|',
                   '|C110|' || COALESCE(CADINF.BDCODINFCOM, '') || '|' || REPLACE(MOVINF.BDDESCCOMPIC, '|', '') || '|',
                   CADINF.BDCODINFCOM, CADINF.BDORDEMINFCOM, COALESCE(MOVINF.BDCODEMPSCP, MOVINF.BDCODEMP), MOVINF.BDCODEMP BDCODEMPPRO
            FROM (SELECT INF.BDCODEMP, INF.BDCHAVE, INF.BDORDEMIC, INF.BDDESCCOMPIC, INF.BDORDEMINFCOM, EMPSCP.BDCODEMPSCP
                  FROM (SELECT M.BDCODEMP, M.BDCHAVE
                      FROM TMP_VEF_EMP_TMOVSAI M
                        WHERE M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)) MOV
--                  JOIN VEF_EMP_TMOVSAIINFCOM INF ON (INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
                  JOIN TMP_VEF_EMP_TMOVSAIINFCOM INF ON (INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
                  JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                  LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PREXPORTAPORSCP = 'TRUE') and (EMPSCP.BDCODEMP = I.BDCODEMP) AND (EMPSCP.BDREFEMP = I.BDREFSOC) AND (EMPSCP.BDCODSCP = I.BDCODSCP)
                  GROUP BY INF.BDCODEMP, INF.BDCHAVE, INF.BDORDEMIC, INF.BDDESCCOMPIC, INF.BDORDEMINFCOM, EMPSCP.BDCODEMPSCP) MOVINF
            LEFT OUTER JOIN VEF_BASE_TCADINFCOM CADINF ON (CADINF.BDORDEMINFCOM = MOVINF.BDORDEMINFCOM AND CADINF.BDCODEMP = MOVINF.BDCODEMP);

          /*****************************************************************************
           *                                   C111                                    *
           ****************************************************************************/

      insert into TEXPORTACAO_SPED (BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODEMP, BDCODEMPPRO)
        select replace(:PRARQUIVO, '$empresa$', coalesce(REF.BDCODEMP, SAI.BDCODEMP)) BDID,
            'C100.' || lpad(SAI.BDCODEMP, 6, '0') || '.1.' || lpad(REF.BDCHAVE, 10, '0') || '.C111.' || REF.BDREF || '.' || REF.BDINDPROCESSO || '.' || REF.BDNUMPROC,
                 'C111',
            '|C111|' || coalesce(trim(REF.BDNUMPROC), '') || '|' || iif(REF.BDINDPROCESSO = '4', '9', coalesce(REF.BDINDPROCESSO, '')) || '|',
            coalesce(MOVINF.BDCODEMPSCP, MOVINF.BDCODEMP), MOVINF.BDCODEMP BDCODEMPPRO
        from (select MOV.BDCODEMP, MOV.BDCHAVE, /*INF.BDORDEMIC,*/ EMPSCP.BDCODEMPSCP
            from (SELECT M.BDCODEMP, M.BDCHAVE
                      FROM TMP_VEF_EMP_TMOVSAI M
                        WHERE M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)) MOV
            join VEF_EMP_TMOVSAIITENS I on (I.BDCODEMP = MOV.BDCODEMP and
                    I.BDCHAVE = MOV.BDCHAVE)
            left outer join TEMPRESAS_SCP EMPSCP on (:PREXPORTAPORSCP = 'TRUE') and
                    (EMPSCP.BDCODEMP = I.BDCODEMP) and
                    (EMPSCP.BDREFEMP = I.BDREFSOC) and
                    (EMPSCP.BDCODSCP = I.BDCODSCP)
            group by MOV.BDCODEMP, MOV.BDCHAVE, /*INF.BDORDEMIC,*/ EMPSCP.BDCODEMPSCP) MOVINF join(
        
                select T.BDCODEMP, T.BDCHAVE, 0 as BDORDEMIC, 0 BDORDEMPROREF, T.BDNUMPROC as BDNUMPROC,
                    T.BDORDEMINDORIG as BDINDPROCESSO, t.bdref
                from SP_RET_REF_1010_1020_EXPORT('(mov.BDCODEMP in (' || :PRCODEMP || ')) and', null, :PRDTINI, :PRDTFIM, 'C609') T
                
                union all
                
                select C.BDCODEMP, C.BDCHAVE, C.BDORDEMIC, C.BDORDEMPROREF, C.BDNUMPROC, C.BDINDPROCESSO, c.bdordemproref
                from (select *
                    from VEF_EMP_TMOVSAIPROREF C
                    where C.BDCODEMP = :PRCODEMP) C
                left outer join(select T.BDCHAVE
                                from SP_RET_REF_1010_1020_EXPORT('(mov.BDCODEMP in (' || :PRCODEMP || ')) and', null, :PRDTINI, :PRDTFIM, 'C609') T) T on (T.BDCHAVE = C.BDCHAVE)
                where T.BDCHAVE is null    
        
        ) REF on (REF.BDCODEMP = MOVINF.BDCODEMP and REF.BDCHAVE = MOVINF.BDCHAVE)
        left outer join VEF_EMP_TMOVSAI SAI on (MOVINF.BDCODEMP = SAI.BDCODEMP and MOVINF.BDCHAVE = SAI.BDCHAVE);

          /*****************************************************************************
           *                                   C170                                    *
           ****************************************************************************/
          SETORDEMSEQUENCIAL_STR(:prCODEMP);
        
          INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODEMP, BDCHAVE, BDCODPROD, BDCODNAT, BDCREDITO, BDANOCREDITO, BDCODPLAPADRAO, BDCREDITOREF, BDCREDITOPLAPADRAOREF, BDCTALON, BDCODEMPPRO)
          SELECT REPLACE(:PRARQUIVO, '$empresa$', COALESCE(PRO.BDCODEMPSCP, M.BDCODEMP)) BDID,
                 --'C100.'||LPAD(M.BDCODEMP, 6, '0')||'.1.'|| M.bdemitente || '|' || RPAD(M.BDNUMDOCINI,9,' ') || '|' || M.bdmodelo || '|' || M.bdserie || '|1|' || M.bdcodsitnf || IIF(M.bdemitente = 0, '', '|' || M.bdcodter)||'.C170.'||GETORDEMSEQUENCIAL(PRO.BDCHAVE),--LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0'),
                 'C100.'||LPAD(COALESCE(PRO.BDCODEMPSCP, m.BDCODEMP), 6, '0')||'.1.'|| LPAD(pro.BDCHAVE, 10, '0')||'.C170.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0')||'.'||GETORDEMSEQUENCIAL(PRO.BDCHAVE),
                  'C170' BDREG,
                  '|C170'||
                  '|'||GETORDEMSEQUENCIAL_STR(COALESCE(PRO.BDCODEMPSCP, M.BDCODEMP) || PRO.BDCHAVE, :prCODEMP)|| --NUM_ITEM
                  --#Alt:21967. Quando a empresa não possuía o respectivo produto vinculado o registro estava levando vazio. Quando isso acontecer foi
                  --tratado para levar a informação do produto Único. Esse tratamento é feito para o código e a descrição.
                  --'|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')), COALESCE(VINC.BDCODPROD,''), COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
                  --'|'||TRIM(REPLACE(COALESCE(VINC.BDDESCPROD, ''), '|', ''))|| --DESCR_COMPL
                  '|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')),
                           IIF(((VINC.BDCODPROD IS NULL) OR (COALESCE(VINC.BDCODPROD,'') = '')),COALESCE(PROD_UNICO.BDCODPROD,''),COALESCE(VINC.BDCODPROD,'')),
                           COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
                  '|'||TRIM(REPLACE(IIF(((VINC.BDDESCPROD IS NULL) OR (VINC.BDDESCPROD = '')),
                                        COALESCE(PROD_UNICO.BDDESCRICAOUNICA,''),
                                        COALESCE(VINC.BDDESCPROD, '')), '|', ''))|| --DESCR_COMPL
                  '|'||REPLACE(CAST(COALESCE(PRO.BDQTDITEM, 0.00) AS NUMERIC(15, 5)), '.', ',')|| --QTD
                  '|'||COALESCE(IIF(((UN.BDAPEUNIMED IS NULL) OR (UN.BDAPEUNIMED = '')), UN_REF.BDAPEUNIMED, UN.BDAPEUNIMED), '')|| --UNID
                  '|'||REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ',')|| --VL_ITEM
                  '|'||REPLACE(COALESCE(PRO.BDVLRDESC, 0.00), '.', ',')|| --VL_DESC
                  '|'||IIF((UPPER(PRO.BDMOVFISICO) = 'TRUE'), 0, 1)|| --IND_MOV
                  '|'||COALESCE(ICMS.BDCSTICMS, '')|| --CST_ICMS
                  '|'||COALESCE(SUBSTRING(PRO.BDCODNAT FROM 1 FOR 4), '')|| --CFOP
                  '|'||COALESCE(PRO.BDCODNAT, '')|| --COD_NAT
                  '|'||REPLACE(COALESCE(PRO.BDBCICMS, ''), '.', ',')|| --VL_BC_ICMS
                  '|'||REPLACE(CAST(COALESCE(PRO.BDALIQICMS, 0.00) AS dm_numeric_15_2), '.', ',')|| --ALIQ_ICMS
                  '|'||REPLACE(COALESCE(PRO.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
                  '|'||REPLACE(COALESCE(PRO.BDBCST, 0.00), '.', ',')||   --VL_BC_ICMS_ST
                  '|'||REPLACE(CAST(COALESCE(PRO.BDALIQST, 0.00) AS dm_numeric_15_2), '.', ',')|| --ALIQ_ST
                  '|'||REPLACE(COALESCE(PRO.BDVLRST, 0.00), '.', ',')||  --VL_ICMS_ST
                  '|'|| --IND_APUR
                  '|'||'' ||--IIF(IPI.BDCODCSTIPI IS NULL, '', LPAD(COALESCE(IPI.BDCODEXPCSTIPI, ''), 2, 0))|| --CST_IPI
                  '|'|| --COD_ENQ
                  '|'||REPLACE(COALESCE(PRO.BDBCIPI, 0.00), '.', ',')|| --VL_BC_IPI
                  '|'||REPLACE(CAST(COALESCE(PRO.BDALIQIPI, 0.00) AS dm_numeric_15_2), '.', ',')|| --ALIQ_IPI
                  '|'||REPLACE(COALESCE(PRO.BDVLRIPI, 0.00), '.', ',')|| --VL_IPI
                  '|'||COALESCE(PIS.BDCSTPIS, '')|| --CST_PIS
                  '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE','',REPLACE(CAST(COALESCE(PRO.BDBCPIS, 0.00) AS DM_NUMERIC_15_2), '.', ','))|| --VL_BC_PIS     //#87630 #81751 Se a CST é igual a 3 as informações de PIS e COFINS devem ser levadas nos campos 28,29 e 34,35
                  '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE','',REPLACE(CAST(COALESCE(PRO.BDALIQPIS, 0.00) AS dm_numeric_7_4_aliq), '.', ','))|| --ALIQ_PIS
                  '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(COALESCE(PRO.BDBCPIS, 0.000), '.', ','),'')|| --QUANT_BC_PIS
                  '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(CAST(COALESCE(PRO.BDALIQPIS, 0.00)  AS dm_numeric_7_4_aliq),'.', ','),'')|| --ALIQ_PIS(em reais)
                  '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(CAST(COALESCE(PRO.BDBCPIS, 0.00) * COALESCE(PRO.BDALIQPIS, 0.00) AS DM_NUMERIC_15_2), '.', ','),REPLACE(COALESCE(PRO.BDVLRPIS, 0.00), '.', ','))|| --VL_PIS
                  '|'||COALESCE(COF.BDCSTCOF, '')|| --CST_COFINS
                  '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE','',REPLACE(CAST(COALESCE(PRO.BDBCCOFINS, 0.00) AS DM_NUMERIC_15_2), '.', ','))|| --VL_BC_COFINS
                  '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE','',REPLACE(CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS dm_numeric_7_4_aliq), '.', ','))|| --ALIQ_COFINS
                  '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(COALESCE(PRO.BDBCCOFINS, 0.000), '.', ','),'')|| --QUANT_BC_COFINS
                  '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS dm_numeric_7_4_aliq), '.', ',') ,'')|| --ALIQ_COFINS(em reais)
                  '|'||IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(CAST(COALESCE(PRO.BDBCCOFINS, 0.00) * CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS dm_numeric_7_4_aliq) AS DM_NUMERIC_15_2), '.', ','),REPLACE(COALESCE(PRO.BDVLRCOFINS, 0.00), '.', ','))|| --VL_COFINS
                  '|'||COALESCE(IIF(:WEXPCONTACONTAB = 'TRUE', COALESCE(COALESCE(CCL.BDCODTPLA, CCLRAT.BDCODTPLA), COALESCE(CON.BDCODTPLA,'')), COALESCE(CCL.BDCTALON, CCLRAT.BDCTALON)),'')|| --COD_CTA
                  '|', COALESCE(PRO.BDCODEMPSCP, m.BDCODEMP), PRO.BDCHAVE, PRO.BDCODPROD, PRO.BDCODNAT, COALESCE(ccl.bdcodtpla,cclrat.bdcodtpla) bdcredito,
                  COALESCE(COALESCE(CCLE.BDANO, CCDERAT.BDANO), CAST(SUBSTRING(M.BDREFLAN FROM 1 FOR 4) AS INTEGER)) bdanocredito,
                  COALESCE(pro.BDCODPLAPADRAO, COALESCE(LAN.BDCODPLAPADRAO, LANRAT.BDCODPLAPADRAO)) bdCODPLAPADRAO, COALESCE(cclep.BDCODTPLAREF, ccderatp.BDCODTPLAREF) bdcreditoref,
                  COALESCE(cclep.BDCODPLAPADRAOREF, ccderatp.BDCODPLAPADRAOREF) bdcreditoplapadraoref,
                  COALESCE(CCL.BDCTALON, CCLRAT.BDCTALON) BDCTALON, m.BDCODEMP BDCODEMPPRO
          FROM (
                SELECT PRO.*, I.BDCODNAT, EMPSCP.BDCODEMPSCP
                FROM (
                      SELECT MOV.BDCODEMP, MOV.BDCHAVE
                      FROM (
                            SELECT M.BDCODEMP, M.BDCHAVE
                            FROM TMP_VEF_EMP_TMOVSAI M
                            WHERE M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                                  AND m.bdmodelo <> 65
                           ) MOV
                     ) SAI
                JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
                LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PREXPORTAPORSCP = 'TRUE') and (EMPSCP.BDCODEMP = I.BDCODEMP) AND (EMPSCP.BDREFEMP = I.BDREFSOC) AND (EMPSCP.BDCODSCP = I.BDCODSCP)
                ORDER BY PRO.BDCODEMP, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO
               ) PRO
          JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = PRO.BDCODEMP AND M.BDCHAVE = PRO.BDCHAVE)
          /*Produto*/
          LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
          LEFT OUTER JOIN TUNIDADEMEDIDA UN ON(UN.BDCODUNIMED = VINC.BDCODUNIMED)
          LEFT OUTER JOIN TCADPRO PROD_UNICO ON(PROD_UNICO.BDCODPROD = PRO.BDCODPROD) --#Alt:21967.
        --  LEFT OUTER JOIN TCADPRO_REF REF ON(REF.BDCODEMP = PRO.BDCODEMP AND REF.BDCODPROD = PRO.BDCODPROD AND ((UN.BDAPEUNIMED IS NULL) OR (UN.BDAPEUNIMED = '')))
          /*Produto por referência*/
          LEFT OUTER JOIN TCADPRO_VINC VINC_REF ON(VINC_REF.BDCODEMP = PRO.BDCODEMP AND VINC_REF.BDCODPROD = PRO.BDCODPROD)
          LEFT OUTER JOIN TUNIDADEMEDIDA UN_REF ON(UN_REF.BDCODUNIMED = VINC_REF.BDCODUNIMED)
          LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS)
          LEFT OUTER JOIN VEF_BASE_TTABCSTIPI IPI ON(IPI.BDCODCSTIPI = PRO.BDCODCSTIPI)
          LEFT OUTER JOIN VEF_BASE_TTABCSTPIS PIS ON(PIS.BDCODCSTPIS = PRO.BDCODCSTPIS)
          LEFT OUTER JOIN VEF_BASE_TTABCSTCOF COF ON(COF.BDCODCSTCOF = PRO.BDCODCSTCOF)
          /* Alt.: #120050 - Quando a contabilização tinha desconto a conta do desconto vem primeiro...
          LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVESAI, BDORDEM, MIN(BDCHAVE) BDCHAVE
                          FROM TOL_VEF_EMP_TMOVSAI
                          WHERE bdFORMULA LIKE '%NAT%LAN(%)' -- Alt.: #92219 - Apenas contas do valor contábil...
                          GROUP BY BDCODEMP, BDCHAVESAI, BDORDEM) TOL ON (TOL.BDCODEMP = PRO.BDCODEMP AND TOL.BDCHAVESAI = PRO.BDCHAVE AND TOL.BDORDEM = PRO.BDORDEM)
          LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.BDCODEMP = TOL.bdcodemp AND lan.bdchave = TOL.BDCHAVE) */
         LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, t.BDCHAVE, l.bdCODPLAPADRAO, l.bdCREDITO
                          FROM (
                                SELECT t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, MIN(t.bdCHAVE) AS BDCHAVE, T.BDCODEMPSUC
                                FROM TOL_VEF_EMP_TMOVSAI t
                                LEFT OUTER JOIN VSUC_EMPRESAS_TLAN l ON (l.bdCODEMP = t.BDCODEMPSUC AND l.bdCHAVE = t.bdCHAVE)
                                WHERE t.bdFORMULA LIKE '%NAT%LAN(%)' -- Alt.: #92219 - Apenas contas do valor contábil...
                                  AND l.bdCREDITO IS NOT NULL -- Alt.: #120050 - Para apenas retornar quando a contabilização tiver uma conta informada, quando tem desconto a conta do desconto vem primeiro...
                                  AND t.bdCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
                                  AND t.bdCHAVESAI BETWEEN :wCHAVEMIN AND :wCHAVEMAX
                                GROUP BY t.bdCODEMP, t.bdCHAVESAI, t.bdORDEM, t.BDCODEMPSUC
                                UNION ALL
                                SELECT i.bdCODEMP, i.bdCHAVE, i.bdORDEM, AUX.bdCHAVE, AUX.BDCODEMPSUC -- Alt.: #136112 - Quando não encontrar a conta na CFOP, vai buscar a primeira que tiver conta.
                                FROM VEF_EMP_TMOVSAIITENS i
                                LEFT OUTER JOIN TOL_VEF_EMP_TMOVSAI t ON(i.bdCODEMP = t.bdCODEMP AND i.bdCHAVE = t.bdCHAVESAI AND i.bdORDEM = t.bdORDEM)
                                LEFT OUTER JOIN (SELECT t.bdCODEMP, t.bdCHAVESAI, MIN(t.bdCHAVE) AS bdCHAVE, MIN(t.bdORDEM) AS BDORDEM, T.BDCODEMPSUC
                                                 FROM TOL_VEF_EMP_TMOVSAI t
                                                 WHERE t.bdFORMULA LIKE '%NAT%LAN(%)' -- Alt.: #92219 - Apenas contas do valor contábil...
                                                   AND t.bdCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
                                                   AND t.bdCHAVESAI BETWEEN :wCHAVEMIN AND :wCHAVEMAX
                                                 GROUP BY t.bdCODEMP, t.bdCHAVESAI, T.BDCODEMPSUC) AUX ON (AUX.bdCODEMP = i.bdCODEMP AND AUX.bdCHAVESAI = i.bdCHAVE)
                                WHERE t.bdCODEMP IS NULL
                                  AND i.bdCODEMP = iif(:PRCODEMPSO > 0, :PRCODEMPSO, :PRCODEMP)
                                  AND i.bdCHAVE BETWEEN :wCHAVEMIN AND :wCHAVEMAX
                                GROUP BY i.bdCODEMP, i.bdCHAVE, i.bdORDEM, AUX.bdCHAVE, AUX.BDCODEMPSUC
                                ) t
                          LEFT OUTER JOIN VSUC_EMPRESAS_TLAN l ON (l.bdCODEMP = t.BDCODEMPSUC AND l.bdCHAVE = t.bdCHAVE)
                          WHERE l.bdCREDITO IS NOT NULL -- Alt.: #120050 - Para apenas retornar quando a contabilização tiver uma conta informada, quando tem desconto a conta do desconto vem primeiro...
                          ) LAN ON (lan.bdCODEMP = pro.bdCODEMP AND lan.bdCHAVESAI = pro.bdCHAVE AND lan.bdORDEM = pro.bdORDEM)
          -- BEGIN - #99380 - Pedro Roweder
          LEFT OUTER JOIN (SELECT t.bdCODEMP, t.BDCHAVESAI, t.bdORDEM, CONT.BDCODPLAPADRAO, MAX(CONT.BDCONTACREDPROV) BDCODTPLA
                       FROM TOL_VEF_EMP_TMOVSAI t
                       JOIN TCONF_CONTAS_ONLINE CONT ON (CONT.BDCODPLANOONLINE = :WCODPLANOONLINE AND CONT.BDFORMULA = SUBSTRING(t.BDFORMULA FROM 1 FOR 4)||'LAN'||SUBSTRING(t.BDFORMULA FROM POSITION('(' IN t.BDFORMULA) FOR ((POSITION(')' IN t.BDFORMULA) - POSITION('(' IN t.BDFORMULA) +1))))
                       WHERE t.bdFORMULA LIKE 'NAT%(%)'
                         AND t.bdCODEMP = IIF(:PRCODEMPSO > 0,:PRCODEMPSO,:PRCODEMP)
                         AND t.BDCHAVESAI BETWEEN :wCHAVEMIN AND :wCHAVEMAX
                       GROUP BY t.bdCODEMP, t.BDCHAVESAI, t.bdORDEM, CONT.bdcodplapadrao) LANB ON (LANB.bdCODEMP = PRO.bdCODEMP AND LANB.BDCHAVESAI = PRO.bdCHAVE AND LANB.bdORDEM = PRO.bdORDEM)
          LEFT OUTER JOIN PLANOS_TPLA CON ON (CON.bdcodplapadrao = LANB.BDCODPLAPADRAO AND CON.bdcodtpla = LANB.BDCODTPLA)
          -- END - #99380 - Pedro Roweder
          LEFT OUTER JOIN planos_tpla ccl ON (COALESCE(PRO.BDCODPLAPADRAO, lan.BDCODPLAPADRAO) = ccl.bdcodplapadrao AND COALESCE(PRO.bdcodtpla, lan.BDCREDITO) = ccl.bdcodtpla)          
          LEFT OUTER JOIN PLANOS_TPLA_ECF ccle ON (ccle.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF AND
                                               ccle.BDANO = Coalesce((select max(BDANO)
                                                            from PLANOS_TPLA_ECF
                                                            where ccle.BDCODPLAPADRAO = BDCODPLAPADRAO and
                                                                  ccle.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF and
                                                                  ccle.BDCODTPLA = BDCODTPLA
                                                                  and BDANO = :WANO and BDCODTPLAREF is not null
                                                                  ),
                                                                  (select max(BDANO)
                                                                   from PLANOS_TPLA_ECF
                                                                   where ccle.BDCODPLAPADRAO = BDCODPLAPADRAO and
                                                                         ccle.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF and
                                                                         ccle.BDCODTPLA = BDCODTPLA
                                                                         and BDANO < :WANO and BDCODTPLAREF is not null
                                                                  ))
                                                   AND ccle.bdcodplapadrao = ccl.bdcodplapadrao AND ccle.bdcodtpla = ccl.bdcodtpla)
         LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO cclep ON (ccle.BDCODPLAPADRAOref = cclep.BDCODPLAPADRAOREF AND ccle.BDCODTPLAREF = cclep.BDCODTPLAREF)
         LEFT OUTER JOIN  (SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) BDCHAVE, BDCODEMPSUC FROM TOL_VEF_EMP_TMOVRATSAI GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM, BDCODEMPSUC) tolrat ON (tolrat.bdcodemp = PRO.bdcodemp AND tolrat.bdchavelan = PRO.bdchave AND tolrat.bdordem = PRO.bdordem)
         LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat ON (lanrat.BDCODEMP = tolrat.BDCODEMPSUC AND lanrat.bdchave = tolrat.BDCHAVE)
         LEFT OUTER JOIN planos_tpla cclrat ON (lanrat.BDCODPLAPADRAO = cclrat.bdcodplapadrao AND lanrat.bdcredito = cclrat.bdcodtpla)
         LEFT OUTER JOIN PLANOS_TPLA_ECF ccderat ON (CCDERAT.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF AND
                                               CCDERAT.BDANO = Coalesce((select max(BDANO)
                                                            from PLANOS_TPLA_ECF
                                                            where CCDERAT.BDCODPLAPADRAO = BDCODPLAPADRAO and
                                                                  CCDERAT.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF and
                                                                  CCDERAT.BDCODTPLA = BDCODTPLA
                                                                  and BDANO = :WANO and BDCODTPLAREF is not null
                                                                  ),
                                                                  (select max(BDANO)
                                                                   from PLANOS_TPLA_ECF
                                                                   where CCDERAT.BDCODPLAPADRAO = BDCODPLAPADRAO and
                                                                         CCDERAT.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF and
                                                                         CCDERAT.BDCODTPLA = BDCODTPLA
                                                                         and BDANO < :WANO and BDCODTPLAREF is not null
                                                                  )) AND
                                                     ccderat.bdcodplapadrao = cclrat.bdcodplapadrao AND ccderat.bdcodtpla = cclrat.bdcodtpla)
         LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO ccderatp ON (ccderat.BDCODPLAPADRAOref = ccderatp.BDCODPLAPADRAOREF AND ccderat.BDCODTPLAREF = ccderatp.BDCODTPLAREF);
          /*****************************************************************************
           *                                   C175                                    *
           ****************************************************************************/
          IF (:PRDTINI >= '09/01/2014') THEN
          BEGIN
               INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODEMP, BDCHAVE, BDCODNAT, BDCREDITO, BDANOCREDITO, BDCODPLAPADRAO, BDCREDITOREF, BDCREDITOPLAPADRAOREF, BDCTALON, BDCODEMPPRO)
               SELECT REPLACE(:PRARQUIVO, '$empresa$', COALESCE(EMPSCP.BDCODEMPSCP, M.BDCODEMP)) BDID,
                      'C100.'||LPAD(COALESCE(EMPSCP.BDCODEMPSCP, M.BDCODEMP), 6, '0')||'.1.'||LPAD(mov.BDCHAVE, 10, '0')||'.C175.'||I.BDPREFIXONAT/*SUBSTRING(I.BDCODNAT FROM 1 FOR 4)*/||'.'||COALESCE(PRO.BDCODCSTPIS,'')||COALESCE(PRO.BDCODCSTCOF,'')||LPAD(COALESCE(PRO.BDALIQPIS,''), 3, '0')||LPAD(COALESCE(PRO.BDALIQCOFINS,''), 3, '0')
                      ||'.'||PRO.BDPISCOFQTD, -- Alt.: #162997 - Incluido o campo "Lançar Pis e Cofins por quantidade" pois haviam notas em que tinham produtos com e sem esse parametro marcado...
                      'C175' BDREG,
                      ('|C175' || --REG
                      '|' || COALESCE(I.BDPREFIXONAT/*SUBSTRING(I.BDCODNAT FROM 1 FOR 4)*/, '') || --CFOP
                      '|' || REPLACE(SUM(PRO.BDVLRITEM), '.', ',') || --VL_OPR
                      '|' || IIF(:PREXCLUSAOICMS = 'TRUE', REPLACE(SUM(PRO.BDVLRDESC) + SUM(PRO.BDVLRICMS), '.', ','), REPLACE(SUM(PRO.BDVLRDESC), '.', ',')) || --VL_DESC
                      '|' || LPAD(COALESCE(PRO.BDCODCSTPIS, ''), 2, '0') || --CST_PIS
                      '|' || IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', '', REPLACE(CAST(SUM(PRO.BDBCPIS) AS DM_NUMERIC_15_2), '.', ',')) || --VL_BC_PIS
                      '|' || IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', '', REPLACE(CAST(COALESCE(PRO.BDALIQPIS, 0.00) AS DM_NUMERIC_7_4_ALIQ), '.', ',')) || --ALIQ_PIS
                      '|' || IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(SUM(PRO.BDBCPIS), '.', ','), '') || --QUANT_BC_PIS
                      '|' || IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(CAST(COALESCE(PRO.BDALIQPIS, 0.00) AS DM_NUMERIC_7_4_ALIQ), '.', ','), '') || --ALIQ_PIS_QUANT
                      '|' || REPLACE(SUM(PRO.BDVLRPIS), '.', ',') || --VL_PIS
                      '|' || LPAD(COALESCE(PRO.BDCODCSTCOF, ''), 2, '0') || --CST_COFINS
                      '|' || IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', '', REPLACE(CAST(SUM(PRO.BDBCCOFINS) AS DM_NUMERIC_15_2), '.', ',')) || --VL_BC_COFINS
                      '|' || IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', '', REPLACE(CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS DM_NUMERIC_7_4_ALIQ), '.', ',')) || --ALIQ_COFINS
                      '|' || IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(SUM(PRO.BDBCCOFINS), '.', ','), '') || --QUANT_BC_COFINS
                      '|' || IIF(Coalesce(UPPER(PRO.BDPISCOFQTD),'FALSE') = 'TRUE', REPLACE(CAST(COALESCE(PRO.BDALIQCOFINS, 0.00) AS DM_NUMERIC_7_4_ALIQ), '.', ','), '') || --ALIQ_COFINS_QUANT
                      '|' || REPLACE(SUM(PRO.BDVLRCOFINS), '.', ',') || --VL_COFINS
                      '|' || MIN(COALESCE(IIF(:WEXPCONTACONTAB = 'TRUE', COALESCE(CCL.BDCODTPLA, CCLRAT.BDCODTPLA), COALESCE(CCL.BDCTALON, CCLRAT.BDCTALON)), '')) || --COD_CTA
                      '|' || --INFO_COMPL
                      '|') BDLINHA, COALESCE(EMPSCP.BDCODEMPSCP, M.BDCODEMP), PRO.BDCHAVE, MIN(I.BDCODNAT), COALESCE(MIN(CCL.BDCODTPLA), MIN(CCLRAT.BDCODTPLA)) BDCREDITO,
                      MIN(COALESCE(COALESCE(CCLE.BDANO, CCDERAT.BDANO), CAST(SUBSTRING(M.BDREFLAN FROM 1 FOR 4) AS INTEGER))) BDANOCREDITO,
                      MIN(COALESCE(PRO.BDCODPLAPADRAO, COALESCE(TOL.BDCODPLAPADRAO, LANRAT.BDCODPLAPADRAO))) BDCODPLAPADRAO,
                      MIN(COALESCE(CCLEP.BDCODTPLAREF, CCDERATP.BDCODTPLAREF)) BDCREDITOREF,
                      MIN(COALESCE(CCLEP.BDCODPLAPADRAOREF, CCDERATP.BDCODPLAPADRAOREF)) BDCREDITOPLAPADRAOREF,
                      MIN(COALESCE(CCL.BDCTALON, CCLRAT.BDCTALON)) BDCTALON, PRO.BDCODEMP BDCODEMPPRO
               FROM (SELECT BDCODEMP, BDCHAVE
                     FROM TMP_VEF_EMP_TMOVSAI
                     WHERE BDMODELO = 65 AND
                           BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                    ) MOV
                JOIN VEF_EMP_TMOVSAI M ON (MOV.BDCODEMP = M.BDCODEMP AND MOV.BDCHAVE = M.BDCHAVE)
                JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)

                /*Produtos*/
                JOIN(

                    select P.BDCODEMP, P.BDCHAVE, P.BDORDEM,
                        sum(coalesce(P.BDVLRITEM, 0)) BDVLRITEM,
                        sum(coalesce(P.BDVLRDESC, 0.00)) BDVLRDESC,
                        sum(coalesce(P.BDVLRICMS, 0.00)) BDVLRICMS,
                        sum(coalesce(P.BDBCPIS, 0.00)) BDBCPIS,
                        sum(coalesce(P.BDBCCOFINS, 0.00)) BDBCCOFINS,
                        sum(coalesce(P.BDVLRCOFINS, 0.00)) BDVLRCOFINS,
                        sum(coalesce(P.BDVLRPIS, 0.00)) BDVLRPIS, P.BDCODCSTPIS, P.BDCODCSTCOF, P.BDALIQPIS, P.BDALIQCOFINS,
                        max(BDCODPLAPADRAO) BDCODPLAPADRAO, max(BDCODTPLA) BDCODTPLA, coalesce(P.BDPISCOFQTD, 'FALSE') BDPISCOFQTD
                                FROM VEF_EMP_TMOVPROSAI P
                                WHERE P.BDCODEMP = IIF(:PRCODEMPSO > 0,:PRCODEMPSO,:PRCODEMP)
                    group by P.BDCODEMP, P.BDCHAVE, P.BDORDEM, P.BDCODCSTPIS, P.BDCODCSTCOF, P.BDALIQPIS, P.BDALIQCOFINS, BDPISCOFQTD
                    
                    union all
                    
                    SELECT F500.BDCODEMP, F500.BDCHAVE, F500.BDORDEM,
                        SUM(COALESCE(F500.bdvlrrec, 0.00)) BDVLRITEM,
                        0 BDVLRDESC,
                        0 BDVLRICMS,
                        SUM(COALESCE(F500.BDBASEPIS, 0.00)) BDBCPIS,
                        SUM(COALESCE(F500.BDBASECOF, 0.00)) BDBCCOFINS,
                        SUM(COALESCE(F500.BDVLRCOF, 0.00)) BDVLRCOFINS,
                        SUM(COALESCE(F500.BDVLRPIS, 0.00)) BDVLRPIS,
                        F500.BDCODCSTPIS, F500.BDCODCSTCOF, F500.BDALIQPIS, F500.BDALIQCOF,
                        null BDCODPLAPADRAO,
                        null BDCODTPLA,
                        'FALSE' BDPISCOFQTD
                    FROM VEF_EMP_TF500SAI F500
                    WHERE F500.BDCODEMP = IIF(:PRCODEMPSO > 0,:PRCODEMPSO,:PRCODEMP)
                      AND NOT EXISTS(SELECT * -- Alt.: #193391 - Quando tiver produtos, nao deve exportar o F500
                                     FROM VEF_EMP_TMOVPROSAI p
                                     WHERE p.bdCODEMP = F500.bdCODEMP
                                       AND p.bdCHAVE = F500.bdCHAVE
                                       AND p.bdORDEM = F500.bdORDEM)
                    GROUP BY F500.BDCODEMP, F500.BDCHAVE, F500.BDORDEM, F500.BDCODCSTPIS, F500.BDCODCSTCOF, F500.BDALIQPIS, F500.BDALIQCOF
                ) PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)

                LEFT OUTER JOIN(SELECT TOL.BDCODEMP, TOL.BDCHAVESAI, TOL.BDORDEM, MIN(LAN.BDCODPLAPADRAO) BDCODPLAPADRAO, MIN(LAN.BDCREDITO) BDCREDITO
                                FROM TOL_VEF_EMP_TMOVSAI TOL
                                LEFT OUTER JOIN VSUC_EMPRESAS_TLAN LAN ON (LAN.BDCODEMP = TOL.BDCODEMPSUC AND LAN.BDCHAVE = TOL.BDCHAVE)
                                WHERE TOL.bdFORMULA LIKE '%NAT%LAN(%)'
                                GROUP BY TOL.BDCODEMP, TOL.BDCHAVESAI, TOL.BDORDEM) TOL ON (TOL.BDCODEMP = PRO.BDCODEMP AND TOL.BDCHAVESAI = PRO.BDCHAVE AND TOL.BDORDEM = PRO.BDORDEM)
                LEFT OUTER JOIN PLANOS_TPLA CCL ON (COALESCE(PRO.BDCODPLAPADRAO,TOL.BDCODPLAPADRAO) = CCL.BDCODPLAPADRAO AND COALESCE(PRO.BDCODTPLA, TOL.BDCREDITO) = CCL.BDCODTPLA)
                LEFT OUTER JOIN PLANOS_TPLA_ECF CCLE ON (CCLE.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF AND 
                                               ccle.BDANO = Coalesce((select max(BDANO)
                                                            from PLANOS_TPLA_ECF
                                                            where ccle.BDCODPLAPADRAO = BDCODPLAPADRAO and
                                                                  ccle.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF and
                                                                  ccle.BDCODTPLA = BDCODTPLA
                                                                  and BDANO = :WANO and BDCODTPLAREF is not null
                                                                  ),
                                                                  (select max(BDANO)
                                                                   from PLANOS_TPLA_ECF
                                                                   where ccle.BDCODPLAPADRAO = BDCODPLAPADRAO and
                                                                         ccle.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF and
                                                                         ccle.BDCODTPLA = BDCODTPLA
                                                                         and BDANO < :WANO and BDCODTPLAREF is not null
                                                                  )) AND CCLE.BDCODPLAPADRAO = CCL.BDCODPLAPADRAO AND CCLE.BDCODTPLA = CCL.BDCODTPLA)
                LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO CCLEP ON (CCLE.BDCODPLAPADRAOREF = CCLEP.BDCODPLAPADRAOREF AND CCLE.BDCODTPLAREF = CCLEP.BDCODTPLAREF)
                LEFT OUTER JOIN(SELECT BDCODEMP, BDCHAVELAN, BDORDEM, MIN(BDCHAVE) BDCHAVE, BDCODEMPSUC
                                FROM TOL_VEF_EMP_TMOVRATSAI
                                GROUP BY BDCODEMP, BDCHAVELAN, BDORDEM, BDCODEMPSUC) TOLRAT ON (TOLRAT.BDCODEMP = PRO.BDCODEMP AND TOLRAT.BDCHAVELAN = PRO.BDCHAVE AND TOLRAT.BDORDEM = PRO.BDORDEM)
                LEFT OUTER JOIN VSUC_EMPRESAS_TLAN LANRAT ON (LANRAT.BDCODEMP = TOLRAT.BDCODEMPSUC AND LANRAT.BDCHAVE = TOLRAT.BDCHAVE)
                LEFT OUTER JOIN PLANOS_TPLA CCLRAT ON (LANRAT.BDCODPLAPADRAO = CCLRAT.BDCODPLAPADRAO AND LANRAT.BDCREDITO = CCLRAT.BDCODTPLA)
                LEFT OUTER JOIN PLANOS_TPLA_ECF CCDERAT ON (CCDERAT.BDCODPLAPADRAOREF = :PRCODPLAPADRAOREF AND 
                                               CCDERAT.BDANO = Coalesce((select max(BDANO)
                                                            from PLANOS_TPLA_ECF
                                                            where CCDERAT.BDCODPLAPADRAO = BDCODPLAPADRAO and
                                                                  CCDERAT.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF and
                                                                  CCDERAT.BDCODTPLA = BDCODTPLA
                                                                  and BDANO = :WANO and BDCODTPLAREF is not null
                                                                  ),
                                                                  (select max(BDANO)
                                                                   from PLANOS_TPLA_ECF
                                                                   where CCDERAT.BDCODPLAPADRAO = BDCODPLAPADRAO and
                                                                         CCDERAT.BDCODPLAPADRAOREF = BDCODPLAPADRAOREF and
                                                                         CCDERAT.BDCODTPLA = BDCODTPLA
                                                                         and BDANO < :WANO and BDCODTPLAREF is not null
                                                                  )) AND CCDERAT.BDCODPLAPADRAO = CCLRAT.BDCODPLAPADRAO AND CCDERAT.BDCODTPLA = CCLRAT.BDCODTPLA)
                LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO CCDERATP ON (CCDERAT.BDCODPLAPADRAOREF = CCDERATP.BDCODPLAPADRAOREF AND CCDERAT.BDCODTPLAREF = CCDERATP.BDCODTPLAREF)
                LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PREXPORTAPORSCP = 'TRUE') and (EMPSCP.BDCODEMP = I.BDCODEMP) AND (EMPSCP.BDREFEMP = I.BDREFSOC) AND (EMPSCP.BDCODSCP = I.BDCODSCP)
                GROUP BY M.BDCODEMP, mov.BDCHAVE, I.BDPREFIXONAT/*I.BDCODNAT*/, PRO.BDCODCSTPIS, PRO.BDCODCSTCOF, PRO.BDALIQPIS, PRO.BDALIQCOFINS,
                         PRO.BDCODEMP, PRO.BDCHAVE, BDCODEMPSCP, PRO.BDPISCOFQTD;
          END
          DELETE FROM TMP_VEF_EMP_TMOVSAIINFCOM;
          DELETE FROM TMP_VEF_EMP_TMOVSAI;
       END

      IF ((:PRBLOCO = 'C800') OR (:PRBLOCO = '')) THEN
        BEGIN
          /*Camilla M. 02/11/2020 - Criado procedure padrão pro C800, pois estourou o tamanho da procedure*/
          EXECUTE PROCEDURE SP_EXPORTA_C800_SAI_SPEDCONTR(:PRCODEMP,:PRDTINI,:PRDTFIM,:PRARQUIVO,:PREXPORTAPORSCP,:PRCODPLAPADRAOREF,:WEXPCONTACONTAB, :PREXCLUSAOICMS);
        END
    END
END
^

CREATE OR ALTER PROCEDURE SP_VALIDA_EXPORTACAO_SPEDCONTR (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(100),
    PRBLOCO CHAR(4))
AS
DECLARE VARIABLE WSQL VARCHAR(200);
DECLARE VARIABLE WEXPNFCOMVAL VARCHAR(5);
DECLARE VARIABLE WSOMENTEBLOCOP VARCHAR(5);
DECLARE VARIABLE WCODCRIT INTEGER;
DECLARE VARIABLE WINCTRIB INTEGER;
DECLARE VARIABLE WQTD INTEGER;
DECLARE VARIABLE WQTDMAX INTEGER;
BEGIN
  --Pega da matriz
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')));
  WSOMENTEBLOCOP = 'FALSE';
  WEXPNFCOMVAL = 'FALSE';
  SELECT FIRST 1 SPED.BDINCTRIB, SPED.BDCODCRIT, SPED.BDEXPNFCOMVALSAI, SPED.BDSOMENTEBLOCOP
  FROM (SELECT COALESCE(E.BDCODMATRIZ, E.BDCODEMP) BDCODMATRIZ
        FROM VW_TEMPRESAS_REF TBEM
        JOIN TEMPRESAS E ON (E.BDCODEMP = TBEM.BDCODEMP)
        WHERE TBEM.BDCODEMP = :PRCODEMP
        GROUP BY BDCODMATRIZ) EMP
  JOIN VW_INT_SPEDPISCOFINS_REF SPED ON (SPED.BDCODEMP = EMP.BDCODMATRIZ AND SPED.BDREFERENCIA <= (SELECT BDDATA
                                                                                                   FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')))
  ORDER BY SPED.BDREFERENCIA DESC
  INTO :WINCTRIB, :WCODCRIT, :WEXPNFCOMVAL, :WSOMENTEBLOCOP;

  IF (NOT((:WINCTRIB = 1) AND
      (:WCODCRIT IN (1, 2)))) THEN
  BEGIN
    IF (:WSOMENTEBLOCOP <> 'TRUE') THEN
    BEGIN

      PRBLOCO = UPPER(:PRBLOCO);

      WSQL = 'SELECT COUNT(S.BDORDEMINCO) BDQTD ';
      WSQL = :WSQL || 'FROM TEXPORTACAO_SPED_INCO S ';
      WSQL = :WSQL || 'WHERE S.BDID = ''' || :PRARQUIVO || ''' ';
      WSQL = :WSQL || 'GROUP BY S.BDID';

      SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_LIM_INCO_EXPORTACAO')
      FROM RDB$DATABASE
      INTO :WQTDMAX;
      SETORDEMSEQUENCIAL(0);

      IF (:PRBLOCO = 'C100') THEN
      BEGIN
        /*****************************************************************************
         *                                   C100                                    *
         ****************************************************************************/
        /*1 - Chave NFE inválida!*/
        INSERT INTO TEXPORTACAO_SPED_INCO (BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
        SELECT :PRARQUIVO, M.BDCHAVE, 1, 0, 'C100' /*Entrada*/
        FROM (SELECT MOV.BDCHAVE, MOV.BDCODEMP, IIF(strlen(COALESCE(MOV.BDCHAVENFE, '')) <> 44, 'FALSE',
                     (SELECT BDISVALID
                      FROM SP_VALIDACHAVE_NFE(MOV.BDCHAVENFE))) BDISVALID
              FROM (SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO, (SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(M.BDCHAVENFE)) BDCHAVENFE
                    FROM VEF_EMP_TMOVENT M
                    JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                    JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) <> TRIM('TRUE'))))
                    WHERE M.BDCODEMP = :PRCODEMP AND
                          M.BDMODELO IN (55, 57, 67) AND
                          M.BDCODSITNF NOT IN (2, 3, 4, 5) AND
                          M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM AND
                          ((:WEXPNFCOMVAL <> 'TRUE') OR (SELECT SUM(CAST(MOVPRO.BDVLRPIS AS NUMERIC(15,2)) + CAST(MOVPRO.BDVLRCOFINS AS NUMERIC(15,2))) BDVLR
                                                         FROM VEF_EMP_TMOVPROENT MOVPRO
                                                         WHERE (M.BDCODEMP = MOVPRO.BDCODEMP AND
                                                               M.BDCHAVE = MOVPRO.BDCHAVE)) > 0)
                    GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO, M.BDCHAVENFE) MOV) M
        WHERE M.BDISVALID = 'FALSE'
        UNION ALL
        SELECT :PRARQUIVO, M.BDCHAVE, 1, 1, 'C100' /*Saída*/
        FROM (SELECT MOV.BDCHAVE, MOV.BDCODEMP, IIF(strlen(COALESCE(MOV.BDCHAVENFE, '')) <> 44, 'FALSE',
                     (SELECT BDISVALID
                      FROM SP_VALIDACHAVE_NFE(MOV.BDCHAVENFE))) BDISVALID
              FROM (SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO, (SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(M.BDCHAVENFE)) BDCHAVENFE
                    FROM VEF_EMP_TMOVSAI M
                    JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                    JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) <> TRIM('TRUE'))))
                    WHERE M.BDCODEMP = :PRCODEMP AND
                          M.BDMODELO IN (55, 57, 67) AND
                          M.BDCODSITNF NOT IN (2, 3, 4, 5) AND
                          M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM AND
                          ((:WEXPNFCOMVAL <> 'TRUE') OR (SELECT SUM(CAST(MOVPRO.BDVLRPIS AS NUMERIC(15,2)) + CAST(MOVPRO.BDVLRCOFINS AS NUMERIC(15,2))) BDVLR
                                                         FROM VEF_EMP_TMOVPROSAI MOVPRO
                                                         WHERE (M.BDCODEMP = MOVPRO.BDCODEMP AND
                                                               M.BDCHAVE = MOVPRO.BDCHAVE)) > 0)
                    GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO, M.BDCHAVENFE) MOV /*Modelos: 55, 57*/
        ) M
        WHERE M.BDISVALID = 'FALSE';
        /*18 - Sem produto.*/
        INSERT INTO TEXPORTACAO_SPED_INCO (BDID, BDCHAVE, BDCODINCO, BDMOVIMENTO, BDREG)
        SELECT :PRARQUIVO, M.BDCHAVE, 18, 0, 'C100' /*Entrada*/
        FROM (SELECT MOV.BDCHAVE, MOV.BDCODEMP
              FROM (SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO, M.BDCHAVENFE
                    FROM VEF_EMP_TMOVENT M
                    JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                    JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) <> TRIM('TRUE'))))
                    WHERE M.BDCODEMP = :PRCODEMP AND
                          M.BDMODELO IN (1, 4, 55, 65, 100) AND
                          M.BDCODSITNF NOT IN (2, 3, 4, 5)  AND
                          M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM AND
                          ((:WEXPNFCOMVAL <> 'TRUE') OR (SELECT SUM(CAST(MOVPRO.BDVLRPIS AS NUMERIC(15,2)) + CAST(MOVPRO.BDVLRCOFINS AS NUMERIC(15,2))) BDVLR
                                                         FROM VEF_EMP_TMOVPROENT MOVPRO
                                                         WHERE (M.BDCODEMP = MOVPRO.BDCODEMP AND
                                                               M.BDCHAVE = MOVPRO.BDCHAVE)) > 0)
                    GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO, M.BDCHAVENFE) MOV) M
        WHERE NOT EXISTS(SELECT BDCODPROD
                         FROM VEF_EMP_TMOVPROENT
                         WHERE BDCODEMP = M.BDCODEMP AND
                               BDCHAVE = M.BDCHAVE)
        UNION ALL
        SELECT :PRARQUIVO, M.BDCHAVE, 18, 1, 'C100' /*Saída*/
        FROM (SELECT MOV.BDCHAVE, MOV.BDCODEMP
              FROM (SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO, M.BDCHAVENFE
                    FROM VEF_EMP_TMOVSAI M
                    JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                    JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) <> TRIM('TRUE'))))
                    WHERE M.BDCODEMP = :PRCODEMP AND
                          M.BDMODELO IN (1, 4, 55, 65, 100) AND
                          M.BDCODSITNF NOT IN (2, 3, 4, 5)  AND
                          M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM AND
                          ((:WEXPNFCOMVAL <> 'TRUE') OR (SELECT SUM(CAST(MOVPRO.BDVLRPIS AS NUMERIC(15,2)) + CAST(MOVPRO.BDVLRCOFINS AS NUMERIC(15,2))) BDVLR
                                                         FROM VEF_EMP_TMOVPROSAI MOVPRO
                                                         WHERE (M.BDCODEMP = MOVPRO.BDCODEMP AND
                                                               M.BDCHAVE = MOVPRO.BDCHAVE)) > 0)
                    GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO, M.BDCHAVENFE) MOV /*Modelos: 55, 57*/
        ) M
        WHERE NOT EXISTS(SELECT BDCODPROD
                         FROM VEF_EMP_TMOVPROSAI
                         WHERE BDCODEMP = M.BDCODEMP AND
                               BDCHAVE = M.BDCHAVE);




        /*****************************************************************************
         *                                   C170                                    *
         ****************************************************************************/
        /*23 - CST de PIS diferente da CST de Cofins*/
        INSERT INTO TEXPORTACAO_SPED_INCO (BDID, BDCHAVE, BDORDEM, BDORDEMAUX, BDCODPROD, BDCODINCO, BDMOVIMENTO, BDREG)
        SELECT :PRARQUIVO, M.BDCHAVE, M.BDORDEM, M.BDORDEMPRO, M.BDCODPROD, 23, 0, 'C170' /*Entrada*/
        FROM (SELECT MOV.BDCHAVE, MOV.BDCODEMP, I.BDORDEM, PRO.BDORDEMPRO, PRO.BDCODPROD
              FROM (SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO, M.BDCHAVENFE
                    FROM VEF_EMP_TMOVENT M
                    JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                    JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) <> TRIM('TRUE'))))
                    WHERE M.BDCODEMP = :PRCODEMP AND
                          M.BDMODELO IN (1, 4, 55, 100) AND
                          M.BDCODSITNF NOT IN (2, 3, 4, 5) AND
                          M.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM AND
                          ((:WEXPNFCOMVAL <> 'TRUE') OR (SELECT SUM(CAST(MOVPRO.BDVLRPIS AS NUMERIC(15,2)) + CAST(MOVPRO.BDVLRCOFINS AS NUMERIC(15,2))) BDVLR
                                                         FROM VEF_EMP_TMOVPROENT MOVPRO
                                                         WHERE (M.BDCODEMP = MOVPRO.BDCODEMP AND
                                                               M.BDCHAVE = MOVPRO.BDCHAVE)) > 0)
                    GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO, M.BDCHAVENFE) MOV
              JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
              JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
              WHERE (PRO.BDCODCSTPIS <> PRO.BDCODCSTCOF)) M
        UNION ALL
        SELECT :PRARQUIVO, M.BDCHAVE, M.BDORDEM, M.BDORDEMPRO, M.BDCODPROD, 23, 1, 'C170' /*Saída*/
        FROM (SELECT MOV.BDCHAVE, MOV.BDCODEMP, I.BDORDEM, PRO.BDORDEMPRO, PRO.BDCODPROD
              FROM (SELECT M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO, M.BDCHAVENFE
                    FROM VEF_EMP_TMOVSAI M
                    JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                    JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT AND ((NAT.BDNAOEXPEFDCONT IS NULL) OR (TRIM(UPPER(NAT.BDNAOEXPEFDCONT)) <> TRIM('TRUE'))))
                    WHERE M.BDCODEMP = :PRCODEMP AND
                          M.BDMODELO IN (1, 4, 55, 100) AND
                          M.BDCODSITNF NOT IN (2, 3, 4, 5) AND
                          M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM AND
                          ((:WEXPNFCOMVAL <> 'TRUE') OR (SELECT SUM(CAST(MOVPRO.BDVLRPIS AS NUMERIC(15,2)) + CAST(MOVPRO.BDVLRCOFINS AS NUMERIC(15,2))) BDVLR
                                                         FROM VEF_EMP_TMOVPROSAI MOVPRO
                                                         WHERE (M.BDCODEMP = MOVPRO.BDCODEMP AND
                                                               M.BDCHAVE = MOVPRO.BDCHAVE)) > 0)
                    GROUP BY M.BDCODEMP, M.BDCHAVE, M.BDCODTER, M.BDCODSITNF, M.BDMODELO, M.BDCHAVENFE) MOV /*Modelos: 55, 57*/
              JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
              JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
              WHERE (PRO.BDCODCSTPIS <> PRO.BDCODCSTCOF)) M;
      END
    END
  END
END^


create or alter procedure SP_EXPORTA_BLOCOC_CONTRIBUICOES (
    PRCODEMP integer,
    PRCODPLAPADRAOREF integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PREXPORTAPORSCP varchar(5),
    PREXCLUSAOICMS DM_BOOLEAN,
    PRCODEMPSCP integer,
    PREXBCPISCOF DM_BOOLEAN)
as
declare variable WLINHA blob sub_type 1 segment size 200;
declare variable WEMPATU integer;
declare variable WARQUIVOEMP varchar(260);
declare variable WCODEMPSO integer;
declare variable WREFFIM integer;
BEGIN
  DELETE FROM TEXPORTACAO_SPED WHERE BDID = :PRARQUIVO;

  SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')
  into :WREFFIM;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(WREFFIM);

  --WHILE (CHAR_LENGTH(:PRCODEMP) > 0) DO
  FOR select coalesce(SCP.BDCODEMPSO, 0) as BDCODEMPSO, EX.BDCODEMP
      from TEMPRESAS EX
      left join(select X.BDCODEMP as BDCODEMPSO, X.BDCODEMPSCP
                 from TEMPRESAS_SCP X
                 where X.BDCODEMPSCP = :PRCODEMP and
                       X.BDREFEMP = (select first 1 Y.BDREFEMP
                                     from TEMPRESAS_SCP Y
                                     where Y.BDCODEMPSCP = X.BDCODEMPSCP and
                                           Y.BDREFEMP <= :WREFFIM
                                     order by Y.BDREFEMP desc)) SCP on (EX.BDCODEMP = SCP.BDCODEMPSCP)
      where EX.BDCODEMP = :PRCODEMP or EX.BDCODMATRIZ = :PRCODEMP
      INTO :WCODEMPSO, :wEmpAtu DO
    BEGIN
     -- wEmpAtu = TRIM(SUBSTRING(:PRCODEMP FROM 1 FOR POSITION(',', :PRCODEMP)-1));
      /* O processo é realizado duas vezes, para registros diferentes, pois existem registros entre eles que são exportados
      pela aplicação, então é necessário levar primeiro os relacionados ao C100 e no final os demais, para isso eles são salvos
      em arquivos distintos*/

      /*Cria arquivo da empresa que vai ser exportada*/
      /*Modificado para ele setar a empresa conforme a SCP ou não dentro das procedures*/
      --wArquivoEmp = REPLACE(:PRARQUIVO, '.tmp', '_e='||:wEmpAtu||'_b=C100.tmp');
      wArquivoEmp = REPLACE(:PRARQUIVO, '.tmp', '_e=$empresa$_b=C100.tmp');

      /*ENTRADA*/
      EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_ENT_SPEDCONTR(:wEmpAtu, :PRCODPLAPADRAOREF, :PRDTINI, :PRDTFIM, :wArquivoEmp, 'C100', PREXPORTAPORSCP, :PREXBCPISCOF, :WCODEMPSO);


      /*SAÍDA*/
      EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_SAI_SPEDCONTR(:wEmpAtu, :PRCODPLAPADRAOREF, :PRDTINI, :PRDTFIM, :wArquivoEmp, 'C100', PREXPORTAPORSCP, :PREXCLUSAOICMS, :WCODEMPSO);

      IF ((:PREXPORTAPORSCP = 'TRUE') AND (:PRCODEMPSCP > 0)) THEN
         wArquivoEmp = REPLACE(:wArquivoEmp, '$empresa$', :PRCODEMPSCP);
      ELSE
      wArquivoEmp = REPLACE(:wArquivoEmp, '$empresa$', :wEmpAtu);

      EXECUTE PROCEDURE SP_VALIDA_EXPORTACAO_SPEDCONTR(:wEmpAtu, :PRDTINI, :PRDTFIM, :wArquivoEmp, 'C100');

      /*****************************************************************************
       *                           EXPORTANDO ARQUIVO-C100                         *
       ****************************************************************************/

      NEWFILE(:wArquivoEmp);
      OPENARQ(:wArquivoEmp,:wEmpAtu);
    
      FOR SELECT E.BDLINHA
          FROM TEXPORTACAO_SPED E
          WHERE E.BDID = :wArquivoEmp
          ORDER BY E.BDCHAVEREG
          INTO :wLinha
      DO
        BEGIN
          WRITELNOA(:wLinha,:wEmpAtu);
        END
    
      CLOSEARQ(:wArquivoEmp,:wEmpAtu);
         
         
      /*Cria arquivo da empresa que vai ser exportada*/
      --wArquivoEmp = REPLACE(:PRARQUIVO, '.tmp', '_e='||:wEmpAtu||'_b=C800.tmp');
      wArquivoEmp = REPLACE(:PRARQUIVO, '.tmp', '_e=$empresa$_b=C800.tmp');

      /*ENTRADA*/
      EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_ENT_SPEDCONTR(:wEmpAtu, :PRCODPLAPADRAOREF, :PRDTINI, :PRDTFIM, :wArquivoEmp, 'C800', PREXPORTAPORSCP, :PREXBCPISCOF);

      /*SAÍDA*/
      EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_SAI_SPEDCONTR(:wEmpAtu, :PRCODPLAPADRAOREF, :PRDTINI, :PRDTFIM, :wArquivoEmp, 'C800', PREXPORTAPORSCP, :prexclusaoicms);


      IF ((:PREXPORTAPORSCP = 'TRUE') AND (:PRCODEMPSCP > 0)) THEN
         wArquivoEmp = REPLACE(:wArquivoEmp, '$empresa$', :PRCODEMPSCP);
      ELSE
      wArquivoEmp = REPLACE(:wArquivoEmp, '$empresa$', :wEmpAtu);

    --  EXECUTE PROCEDURE SP_VALIDA_EXPORTACAO_SPEDCONTR(:wEmpAtu, :PRDTINI, :PRDTFIM, :wArquivoEmp, 'C800');


      /*****************************************************************************
       *                           EXPORTANDO ARQUIVO-C800                         *
       ****************************************************************************/

      NEWFILE(:wArquivoEmp);    
      OPENARQ(:wArquivoEmp,:wEmpAtu);
    
      FOR SELECT E.BDLINHA
          FROM TEXPORTACAO_SPED E
          WHERE E.BDID = :wArquivoEmp
          ORDER BY E.BDCHAVEREG
          INTO :wLinha
      DO
        BEGIN
          WRITELNOA(:wLinha,:wEmpAtu);
        END
    
      CLOSEARQ(:wArquivoEmp,:wEmpAtu);
         

      --PRCODEMP = SUBSTRING(:PRCODEMP FROM POSITION(',', :PRCODEMP)+1 FOR CHAR_LENGTH(:PRCODEMP));

    END
END
^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOD_SAI_SPEDCONTR (
    PRCODEMP integer,
    PRCODPLAPADRAOREF integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PREXPORTAPORSCP varchar(5),
    PREXCLUSAOICMS varchar(5))
as
declare variable WEXPCONTACONTAB DM_BOOLEAN;
BEGIN
  SELECT FIRST 1 sped.bdEXPCONTACONTAB
  FROM (
        SELECT COALESCE(e.bdCODMATRIZ, e.bdCODEMP) AS bdCODMATRIZ, bdCODPLANOONLINE
        FROM VW_TEMPRESAS_REF tbem
        JOIN TEMPRESAS e ON(e.bdCODEMP = tbem.bdCODEMP)
        WHERE tbem.bdCODEMP = :prCODEMP
        GROUP BY bdCODMATRIZ, bdCODPLANOONLINE
       ) EMP
  JOIN VW_INT_SPEDPISCOFINS_REF sped ON(sped.bdCODEMP = emp.bdCODMATRIZ AND sped.bdREFERENCIA <= (SELECT bdDATA FROM SP_PARSE_DATE(:prDTFIM, 'YYYYMM')))
  ORDER BY sped.bdREFERENCIA DESC
  INTO :wEXPCONTACONTAB;

  /*****************************************************************************
   *                                   D300                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCHAVE, BDCREDITO, BDANOCREDITO, BDCODPLAPADRAO, BDCREDITOREF, BDCREDITOPLAPADRAOREF, BDCTALON, BDCODEMPPRO, BDCODEMP)
  SELECT REPLACE(:PRARQUIVO, '$empresa$', COALESCE(EMPSCP.BDCODEMPSCP, d400.bdCODEMP)) BDID,
         LPAD(COALESCE(EMPSCP.BDCODEMPSCP, d400.bdCODEMP), 6, '0')||'.1.'||LPAD(d400.bdCHAVE, 10, '0')||'.D300.'||i.bdCODNAT,
         'D300' BDREG,
          ('|D300'|| -- 01 REG Texto fixo contendo "D300" C 004* - S
           '|'||'18'/*modl.bdMODELOSTR*/|| -- 02 COD_MOD Código do modelo do documento fiscal, conforme a Tabela 4.1.1. C 002* - S
           '|'||COALESCE(res.bdSERIE,'')|| -- 03 SER Série do documento fiscal C 004 - N
           '|'||COALESCE(res.bdSUBSERIE,'')|| -- 04 SUB Subsérie do documento fiscal N 003 - N
           '|'||COALESCE(m.bdNUMDOCINI,'')|| -- 05 NUM_DOC_INI Número do primeiro documento fiscal emitido no período (mesmo modelo, série e subsérie) N 006 - N
           '|'||COALESCE(m.bdNUMDOCFIM,'')|| -- 06 NUM_DOC_FIN Número do último documento fiscal emitido no período (mesmo modelo, série e subsérie) N 006 - N
           '|'||COALESCE(SUBSTRING(i.bdCODNAT FROM 1 FOR 4), '')|| -- 07 CFOP Código Fiscal de Operação e Prestação conforme tabela indicada no item 4.2.2 N 004* - S
           '|'||COALESCE((SELECT bdDATA FROM SP_PARSE_DATE(m.bdDATAEMISSAO, 'DDMMYYYY')),'')|| -- 08 DT_REF Data do dia de referência do resumo diário N 008* - S
           '|'||COALESCE(REPLACE(SUM(COALESCE(i.bdVLRCONTAB,0.00)), '.', ','), '')|| -- 09 VL_DOC Valor total dos documentos fiscais emitidos N - 02 S
           '|'||iif (:PREXCLUSAOICMS = 'TRUE', COALESCE(REPLACE(SUM(COALESCE(i.bdDESCONTO + i.bdvlricms,0.00)), '.', ','), '') , COALESCE(REPLACE(SUM(COALESCE(i.bdDESCONTO,0.00)), '.', ','), ''))|| -- 10 VL_DESC Valor total dos descontos N - 02 N
           '|'||COALESCE(cstpis.bdCSTPIS,'')|| -- 11 CST_PIS Código da Situação Tributária referente ao PIS/PASEP N 002* - S
           '|'||COALESCE(REPLACE(CAST(SUM(COALESCE(d400.bdVL_BC_PIS,0.00))*(i.bdVLRCONTAB/m.bdVALORNOTA) AS NUMERIC(15, 2)), '.', ','), '')|| -- 12 VL_BC_PIS Valor da base de cálculo do PIS/PASEP N - 02 N
           '|'||COALESCE(REPLACE(CAST(d400.bdALIQ_PIS AS NUMERIC(6, 2)), '.', ','), '')|| -- 13 ALIQ_PIS Alíquota do PIS/PASEP (em percentual) N 008 04 N
           '|'||COALESCE(REPLACE(CAST(SUM(COALESCE(d400.bdVL_PIS,0.00))*(i.bdVLRCONTAB/m.bdVALORNOTA) AS NUMERIC(15, 2)), '.', ','), '')|| -- 14 VL_PIS Valor do PIS/PASEP N - 02 N
           '|'||COALESCE(cstcof.bdCSTCOF,'')|| -- 15 CST_COFINS Código da Situação Tributária referente a COFINS N 002* - S
           '|'||COALESCE(REPLACE(CAST(SUM(COALESCE(d400.bdVL_BC_COF,0.00))*(i.bdVLRCONTAB/m.bdVALORNOTA) AS NUMERIC(15, 2)), '.', ','), '')|| -- 16 VL_BC_COFINS Valor da base de cálculo da COFINS N - 02 N
           '|'||COALESCE(REPLACE(CAST(d400.bdALIQ_COF AS NUMERIC(6, 2)), '.', ','), '')|| -- 17 ALIQ_COFINS Alíquota da COFINS (em percentual) N 008 04 N
           '|'||COALESCE(REPLACE(CAST(SUM(COALESCE(d400.bdVL_COF,0.00))*(i.bdVLRCONTAB/m.bdVALORNOTA) AS NUMERIC(15, 2)), '.', ','), '')|| -- 18 VL_COFINS Valor da COFINS N - 02 N
           '|'||MIN(COALESCE(IIF(:wEXPCONTACONTAB = 'TRUE', COALESCE(ccl.bdCODTPLA, cclrat.bdCODTPLA), COALESCE(ccl.bdCTALON, cclrat.bdCTALON)),''))|| -- 19 COD_CTA Código da conta analítica contábil debitada/creditada C 255 - N
           '|'
           ), d400.bdCHAVE,
          COALESCE(ccl.bdCODTPLA,cclrat.bdCODTPLA) AS bdCREDITO,
          COALESCE(COALESCE(ccle.bdANO, ccderat.bdANO),CAST(SUBSTRING(m.bdREFLAN FROM 1 FOR 4) AS INTEGER)) AS bdANOCREDITO,
          COALESCE(d400.bdCODPLAPADRAO,COALESCE(tol.bdCODPLAPADRAO,lanrat.bdCODPLAPADRAO)) AS bdCODPLAPADRAO,
          COALESCE(cclep.bdCODTPLAREF,ccderatp.bdCODTPLAREF) AS bdCREDITOREF,
          COALESCE(cclep.bdCODPLAPADRAOREF,ccderatp.bdCODPLAPADRAOREF) AS bdCREDITOPLAPADRAOREF,
          COALESCE(ccl.bdCTALON,cclrat.bdCTALON) AS bdCTALON, d400.bdCODEMP BDCODEMPPRO,
          COALESCE(EMPSCP.BDCODEMPSCP, d400.bdCODEMP)
  FROM (
        SELECT s.bdCODEMP, s.bdCHAVE
        FROM VEF_EMP_TMOVSAI s
        WHERE s.bdCODEMP = :prCODEMP
          AND s.bdDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
          AND s.bdMODELO IN(13,14,15, 16)
          AND s.bdCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
       ) MOV
  JOIN VEF_EMP_TMOVSAI m ON (m.bdCODEMP = mov.bdCODEMP AND m.bdCHAVE = mov.bdCHAVE)
  JOIN VEF_EMP_TMOVSAIITENS i ON (i.bdCODEMP = m.bdCODEMP AND i.bdCHAVE = m.bdCHAVE)
  JOIN VEF_EMP_TD400SAI d400 ON (d400.bdCODEMP = m.bdCODEMP AND d400.bdCHAVE = m.bdCHAVE)
  LEFT OUTER JOIN VEF_EMP_TRESMOVDIARIO res ON (res.bdCODEMP = d400.bdCODEMP AND res.bdCODIGO = d400.bdCODIGO)
  JOIN VEF_BASE_TTABMODELOLAN modl ON (modl.bdMODELO = m.bdMODELO)
  LEFT OUTER JOIN VEF_BASE_TTABCSTPIS cstpis ON(cstpis.bdCODCSTPIS = d400.bdCODCSTPIS)
  LEFT OUTER JOIN VEF_BASE_TTABCSTCOF cstcof ON(cstcof.bdCODCSTCOF = d400.bdCODCSTCOF)
  LEFT OUTER JOIN(SELECT tol.bdCODEMP, tol.bdCHAVESAI, tol.bdORDEM, MIN(lan.bdCODPLAPADRAO) AS bdCODPLAPADRAO, MIN(lan.bdCREDITO) AS bdCREDITO
                  FROM TOL_VEF_EMP_TMOVSAI tol
                  LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lan ON (lan.bdCODEMP = tol.BDCODEMPSUC AND lan.bdCHAVE = TOL.BDCHAVE)
                  WHERE tol.bdFORMULA LIKE '%NAT%LAN(%)'
                  GROUP BY tol.bdCODEMP, tol.bdCHAVESAI, tol.bdORDEM) tol ON (tol.bdCODEMP = i.bdCODEMP AND tol.bdCHAVESAI = i.bdCHAVE AND tol.bdORDEM = i.bdORDEM)
  LEFT OUTER JOIN PLANOS_TPLA ccl ON (COALESCE(d400.bdCODPLAPADRAO,tol.bdCODPLAPADRAO) = ccl.bdCODPLAPADRAO AND COALESCE(d400.bdCODTPLA,tol.bdCREDITO) = ccl.bdCODTPLA)
  LEFT OUTER JOIN PLANOS_TPLA_ECF ccle ON (ccle.bdCODPLAPADRAOREF = :prCODPLAPADRAOREF AND ccle.bdANO = (SELECT FIRST 1 bdANO
                                                                                                         FROM PLANOS_TPLA_ECF
                                                                                                         WHERE CAST(bdANO || '01' AS INTEGER) <= m.bdREFLAN
                                                                                                           AND bdCODTPLAREF IS NOT NULL
                                                                                                           AND ccle.bdCODPLAPADRAO = bdCODPLAPADRAO
                                                                                                           AND ccle.bdCODPLAPADRAOREF = bdCODPLAPADRAOREF
                                                                                                           AND CCLE.BDCODTPLA = bdCODTPLA
                                                                                                         ORDER BY bdANO DESC) AND ccle.bdCODPLAPADRAO = ccl.bdCODPLAPADRAO AND ccle.bdCODTPLA = ccl.bdCODTPLA)
  LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO cclep ON (ccle.BDCODPLAPADRAOref = cclep.BDCODPLAPADRAOREF AND ccle.BDCODTPLAREF = cclep.BDCODTPLAREF)
  LEFT OUTER JOIN(SELECT t.bdCODEMP, t.bdCHAVELAN, t.bdORDEM, MIN(t.bdCHAVE) AS bdCHAVE, BDCODEMPSUC
                  FROM TOL_VEF_EMP_TMOVRATSAI t
                  GROUP BY t.bdCODEMP, t.bdCHAVELAN, t.bdORDEM, BDCODEMPSUC) tolrat ON (tolrat.bdCODEMP = i.bdCODEMP AND tolrat.bdCHAVELAN = i.bdCHAVE AND tolrat.bdORDEM = i.bdORDEM)
  LEFT OUTER JOIN VSUC_EMPRESAS_TLAN lanrat ON (lanrat.bdCODEMP = tolrat.BDCODEMPSUC AND lanrat.bdCHAVE = tolrat.bdCHAVE)
  LEFT OUTER JOIN PLANOS_TPLA cclrat ON (lanrat.bdCODPLAPADRAO = cclrat.bdCODPLAPADRAO AND lanrat.bdCREDITO = cclrat.bdCODTPLA)
  LEFT OUTER JOIN PLANOS_TPLA_ECF ccderat ON (ccderat.bdCODPLAPADRAOREF = :prCODPLAPADRAOREF AND ccderat.bdANO = (SELECT FIRST 1 bdANO
                                                                                                                  FROM PLANOS_TPLA_ECF
                                                                                                                  WHERE CAST(bdANO || '01' AS INTEGER) <= lanrat.bdREFERENCIA
                                                                                                                    AND bdCODTPLAREF IS NOT NULL
                                                                                                                    AND ccderat.bdCODPLAPADRAO = bdCODPLAPADRAO
                                                                                                                    AND ccderat.bdCODPLAPADRAOREF = bdCODPLAPADRAOREF
                                                                                                                    AND ccderat.bdCODTPLA = bdCODTPLA
                                                                                                                  ORDER BY bdANO DESC) AND ccderat.bdCODPLAPADRAO = cclrat.bdCODPLAPADRAO AND ccderat.bdCODTPLA = cclrat.bdCODTPLA)
  LEFT OUTER JOIN PLANOS_TPLA_ECF_PADRAO ccderatp ON (ccderat.BDCODPLAPADRAOref = ccderatp.BDCODPLAPADRAOREF AND ccderat.BDCODTPLAREF = ccderatp.BDCODTPLAREF)
  LEFT OUTER JOIN TEMPRESAS_SCP EMPSCP ON (:PREXPORTAPORSCP = 'TRUE') and (EMPSCP.BDCODEMP = I.BDCODEMP) AND (EMPSCP.BDREFEMP = I.BDREFSOC) AND (EMPSCP.BDCODSCP = I.BDCODSCP)
  GROUP BY d400.bdCODEMP, d400.bdCHAVE, modl.bdMODELOSTR, res.bdSERIE, res.bdSUBSERIE, m.bdNUMDOCINI, m.bdNUMDOCFIM, m.bdDATAEMISSAO,
           i.bdCODNAT, d400.bdALIQ_PIS, d400.bdALIQ_COF, cstpis.bdCSTPIS, cstcof.bdCSTCOF, ccl.bdCODTPLA,cclrat.bdCODTPLA,
           ccle.bdANO,ccderat.bdANO, m.bdREFLAN, d400.bdCODPLAPADRAO,tol.bdCODPLAPADRAO,lanrat.bdCODPLAPADRAO,
           i.bdVLRCONTAB,m.bdVALORNOTA,cclep.bdCODTPLAREF,ccderatp.bdCODTPLAREF,cclep.bdCODPLAPADRAOREF,ccderatp.bdCODPLAPADRAOREF,ccl.bdCTALON,cclrat.bdCTALON, EMPSCP.BDCODEMPSCP;

  /*****************************************************************************
  *                                   D309                                    *
  ****************************************************************************/

  INSERT INTO TEXPORTACAO_SPED (BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODEMP, BDCODEMPPRO)
  select replace(:PRARQUIVO, '$empresa$', bdcodemp) BDID,
         LPAD(BDCODEMP, 6, '0') || '.1.' || LPAD(BDCHAVE, 10, '0') || '.D300.D309.' || REF.BDREF || '.' || REF.BDINDPROCESSO || '.' || REF.BDNUMPROC,
         'D309',
         '|D309|' || COALESCE(TRIM(REF.BDNUMPROC), '') || '|' || IIF(REF.BDINDPROCESSO = '4', '9', COALESCE(REF.BDINDPROCESSO, '')) || '|',
         BDCODEMP, BDCODEMP
  FROM (SELECT T.BDCODEMP, T.BDCHAVE, 0 AS BDORDEMIC, 0 BDORDEMPROREF, T.BDNUMPROC AS BDNUMPROC,
               T.BDORDEMINDORIG AS BDINDPROCESSO, BDREF
        FROM SP_RET_REF_1010_1020_EXPORT('(MOV.BDCODEMP IN (' || :PRCODEMP || ')) AND', NULL, :PRDTINI, :PRDTFIM, 'D309') T
        inner join TEXPORTACAO_SPED D300 on (D300.BDCHAVE = t.BDCHAVE and D300.bdreg = 'D300')) REF;

END^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOD_CONTRIBUICOES (
    PRCODEMP integer,
    PRCODPLAPADRAOREF integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PREXPORTAPORSCP varchar(5),
    PRCODEMPSOCIA integer,
    PREXCLUSAOICMS DM_BOOLEAN,
    PRCODEMPSCP integer)
as
declare variable WLINHA blob sub_type 1 segment size 200;
declare variable WEMPATU integer;
declare variable WARQUIVOEMP varchar(260);
declare variable WINCTRIB integer;
declare variable WCODCRIT integer;
BEGIN
  DELETE FROM TEXPORTACAO_SPED WHERE bdID = :prARQUIVO;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT bdDATA FROM SP_PARSE_DATE(:prDTFIM, 'YYYYMM')));

  FOR
      SELECT ex.bdCODEMP
      FROM TEMPRESAS ex
      WHERE ex.bdCODEMP = :prCODEMP
         OR ex.bdCODMATRIZ = :prCODEMP
      INTO :wEmpAtu DO
    BEGIN
      /*Cria arquivo da empresa que vai ser exportada*/
      wArquivoEmp = REPLACE(:prARQUIVO, '.tmp', '_e=$empresa$_BlocoDCont.tmp');

      if (PRCODEMPSOCIA <> 0) then
         begin
            SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :PRCODEMPSOCIA
            INTO :wINCTRIB, :wCODCRIT;
         end
      else
         begin
      SELECT BDINCTRIB+1, BDCODCRIT FROM VW_INT_SPEDPISCOFINS_REF WHERE BDCODEMP = :wEmpAtu
      INTO :wINCTRIB, :wCODCRIT;
         end

      IF ((wINCTRIB <> 2) OR -- 2 - Exclusivamente no regime cumulativo
          (wCODCRIT NOT IN (1,2))) THEN -- 1 - Regime de Caixa - Escrituração consolidada (Registro F500) / 2 - Regime de Competência - Escrituração consolidada (Registro F550)
         BEGIN
           /*ENTRADA*/
           --EXECUTE PROCEDURE SP_EXPORTA_BLOCOC_ENT_SPEDCONTR(:wEmpAtu, :prCODPLAPADRAOREF, :prDTINI, :prDTFIM, :wArquivoEmp);
     
           /*SAÍDA*/
           EXECUTE PROCEDURE SP_EXPORTA_BLOCOD_SAI_SPEDCONTR(:wEmpAtu, :prCODPLAPADRAOREF, :prDTINI, :prDTFIM, :wArquivoEmp, :PREXPORTAPORSCP, :PREXCLUSAOICMS);

          IF ((:PREXPORTAPORSCP = 'TRUE') AND (:PRCODEMPSCP > 0)) THEN
             wArquivoEmp = REPLACE(:wArquivoEmp, '$empresa$', :PRCODEMPSCP);
          ELSE
           wArquivoEmp = REPLACE(:wArquivoEmp, '$empresa$', :wEmpAtu);

           NEWFILE(:wArquivoEmp);
           OPENARQ(:wArquivoEmp,:wEmpAtu);
         
           FOR SELECT E.BDLINHA
               FROM TEXPORTACAO_SPED E
               WHERE E.BDID = :wArquivoEmp
               ORDER BY E.BDCHAVEREG
               INTO :wLinha
           DO
             BEGIN
               WRITELNOA(:wLinha,:wEmpAtu);
             END
         
           CLOSEARQ(:wArquivoEmp,:wEmpAtu);
         END
    END
END^

CREATE OR ALTER procedure SP_INSS_IRRF_ESOCIAL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCODTER integer,
    PRCODTIPO integer,
    PRREFARQ integer)
returns (
    BDSISVALORTOTAL numeric(15,6))
as
declare variable VBDINSS numeric(15,6);
declare variable VBDIRRF numeric(15,6);
begin
  if (PRCODTIPO in (40, 41, 42, 43)) then
  begin
    select sum(BDINSS), sum(BDIRRF)
    from (select (F.BDINSSFC + F.BDINSS13FC) BDINSS,
                                             (F.BDIRRFFC + F.BDIRRF13FC) BDIRRF
          from VRHF_EMP_TFOLHACOMP F
          where (((:PRCODTIPO in (40, 41)) and
                (F.BDCODEMP = :PRCODEMP)) or ((:PRCODTIPO in (42, 43)) and
                (F.BDCODEMP in (select BDCODEMP
                                from TEMPRESAS E
                                where E.BDCODEMP = :PRCODEMP or E.BDCODMATRIZ = :PRCODEMP)))) and
                ((:PRCODTIPO in (42, 43) or F.BDCODCOL = :PRCODCOL) and
                F.BDCODTIPOFC <> 3 and
                (((:PRCODTIPO in (40, 42)) and
                (F.BDREFFN = :PRREFARQ)) or ((:PRCODTIPO in (41, 43)) and
                ((select BDDATA
                  from SP_PARSE_DATE(F.BDDATAPAGFC, 'YYYYMM')) = :PRREFARQ))))

          union all
          select (F1.BDINSSFC + F1.BDINSS13FC) BDINSS,
                                               (F1.BDIRRFFC + F1.BDIRRF13FC) BDIRRF
          from VRHF_EMP_TFOLTOMCOMP F1
          where (((:PRCODTIPO in (40, 41)) and
                (F1.BDCODEMP = :PRCODEMP)) or ((:PRCODTIPO in (42, 43)) and
                (F1.BDCODEMP in (select BDCODEMP
                                from TEMPRESAS E
                                where E.BDCODEMP = :PRCODEMP or E.BDCODMATRIZ = :PRCODEMP)))) and
                ((:PRCODTIPO in (42, 43) or F1.BDCODCOL = :PRCODCOL) and
                (((:PRCODTIPO in (40, 42)) and
                (F1.BDREFTOMADOR = :PRREFARQ)) or ((:PRCODTIPO in (41, 43)) and
                ((select BDDATA
                  from SP_PARSE_DATE(F1.BDDATAPAGFC, 'YYYYMM')) = :PRREFARQ))))

          union all
          select (F2.BDINSSFT + F2.BDINSS13FT) BDINSS,
                                               (F2.BDIRRFFT + F2.BDIRRF13FT) BDIRRF
          from VRHF_EMP_TFOLHATOMADOR F2
          where (((:PRCODTIPO in (40, 41)) and
                (F2.BDCODEMP = :PRCODEMP)) or ((:PRCODTIPO in (42, 43)) and
                (F2.BDCODEMP in (select BDCODEMP
                                from TEMPRESAS E
                                where E.BDCODEMP = :PRCODEMP or E.BDCODMATRIZ = :PRCODEMP)))) and
                ((:PRCODTIPO in (42, 43) or F2.BDCODCOL = :PRCODCOL) and
                (((:PRCODTIPO in (40, 42)) and
                (F2.BDREFTOMADOR = :PRREFARQ)) or ((:PRCODTIPO in (41, 43)) and
                ((select BDDATA
                  from SP_PARSE_DATE(F2.BDDATAPGTOFT, 'YYYYMM')) = :PRREFARQ))))

          union all
          select (F3.BDINSSFA + F3.BDINSS13FA) BDINSS,
                                               (F3.BDIRRFFA + F3.BDIRRF13FA) BDIRRF
          from VRHF_EMP_TFOLHAAVULSA F3
          where (((:PRCODTIPO in (40, 41)) and
                (F3.BDCODEMP = :PRCODEMP)) or ((:PRCODTIPO in (42, 43)) and
                (F3.BDCODEMP in (select BDCODEMP
                                from TEMPRESAS E
                                where E.BDCODEMP = :PRCODEMP or E.BDCODMATRIZ = :PRCODEMP)))) and
                ((:PRCODTIPO in (42, 43) or F3.BDCODCOL = :PRCODCOL) and
                (((:PRCODTIPO in (40, 42)) and
                (F3.BDREF = :PRREFARQ)) or ((:PRCODTIPO in (41, 43)) and
                ((select BDDATA
                  from SP_PARSE_DATE(F3.BDDATAPGTOFA, 'YYYYMM')) = :PRREFARQ))))

          union all
          select (F4.BDINSSFN + F4.BDINSS13FN) BDINSS,
                                               (F4.BDIRRFFN + F4.BDIRRF13FN) BDIRRF
          from VRHF_EMP_TFOLHANORMAL F4
          where (((:PRCODTIPO in (40, 41)) and
                (F4.BDCODEMP = :PRCODEMP)) or ((:PRCODTIPO in (42, 43)) and
                (F4.BDCODEMP in (select BDCODEMP
                                from TEMPRESAS E
                                where E.BDCODEMP = :PRCODEMP or E.BDCODMATRIZ = :PRCODEMP)))) and
                ((:PRCODTIPO in (42, 43) or F4.BDCODCOL = :PRCODCOL) and
                (((:PRCODTIPO in (40, 42)) and
                (F4.BDREFFN = :PRREFARQ)) or ((:PRCODTIPO in (41, 43)) and
                ((select BDDATA
                  from SP_PARSE_DATE(F4.BDDATAPGTOFN, 'YYYYMM')) = :PRREFARQ))))

          union all
          select F5.BDVALORINSS13 BDINSS, F5.BDVALORIR13 BDIRRF
          from VRHF_EMP_T13SAL F5
          where (((:PRCODTIPO in (40, 41)) and
                (F5.BDCODEMP = :PRCODEMP)) or ((:PRCODTIPO in (42, 43)) and
                (F5.BDCODEMP in (select BDCODEMP
                                from TEMPRESAS E
                                where E.BDCODEMP = :PRCODEMP or E.BDCODMATRIZ = :PRCODEMP)))) and
                ((:PRCODTIPO in (42, 43) or F5.BDCODCOL = :PRCODCOL) and
                (((:PRCODTIPO in (40, 42)) and
                (F5.BDREF13 = :PRREFARQ)) or ((:PRCODTIPO in (41, 43)) and
                ((select BDDATA
                  from SP_PARSE_DATE(F5.BDDATAPGTO13, 'YYYYMM')) = :PRREFARQ))))
          union all
          select F6.BDINSS13C13 BDINSS, F6.BDVALORIRC13 BDIRRF
          from VRHF_EMP_TC13SAL F6
          where (((:PRCODTIPO in (40, 41)) and
                (F6.BDCODEMP = :PRCODEMP)) or ((:PRCODTIPO in (42, 43)) and
                (F6.BDCODEMP in (select BDCODEMP
                                from TEMPRESAS E
                                where E.BDCODEMP = :PRCODEMP or E.BDCODMATRIZ = :PRCODEMP)))) and
                ((:PRCODTIPO in (42, 43) or F6.BDCODCOL = :PRCODCOL) and
                (((:PRCODTIPO in (40, 42)) and
                (F6.BDREF13 = :PRREFARQ)) or ((:PRCODTIPO in (41, 43)) and
                ((select BDDATA
                  from SP_PARSE_DATE(F6.BDDATAPGTOC13, 'YYYYMM')) = :PRREFARQ))))
          union all
          select (F7.BDINSSFC + F7.BDINSS13FC) BDINSS,
                                               (F7.BDIRRFFC + F7.BDIRRF13FC) BDIRRF
          from VRHF_EMP_TFOLHACOMP F7
          left outer join VRH_EMP_TACCONV A on F7.BDCODEMP = A.BDCODEMP and F7.BDCODACCONV = A.BDCODACCONV
          where (((:PRCODTIPO in (40, 41)) and
                (F7.BDCODEMP = :PRCODEMP)) or ((:PRCODTIPO in (42, 43)) and
                (F7.BDCODEMP in (select BDCODEMP
                                from TEMPRESAS E
                                where E.BDCODEMP = :PRCODEMP or E.BDCODMATRIZ = :PRCODEMP)))) and
                ((:PRCODTIPO in (42, 43) or F7.BDCODCOL = :PRCODCOL) and
                F7.BDCODTIPOFC = 3 and
                (((:PRCODTIPO in (40, 42)) and
                (F7.BDREFFN = :PRREFARQ)) or ((:PRCODTIPO in (41, 43)) and
                ((select BDDATA
                  from SP_PARSE_DATE(F7.BDDATAPAGFC, 'YYYYMM')) = :PRREFARQ))))

          union all

          select F8.BDVALORINSS, F8.BDVALORIR
          from VRHF_BASE_CALC_TERC F8
          left outer join VRH_BASE_TSERVTERC SER on (F8.BDCODEMP = SER.BDCODEMP and F8.BDCODTER = SER.BDCODTER and F8.BDCODSERV = SER.BDCODSERV)
          where (((:PRCODTIPO in (40, 41)) and
                (F8.BDCODEMP = :PRCODEMP)) or ((:PRCODTIPO in (42, 43)) and
                (F8.BDCODEMP in (select BDCODEMP
                                from TEMPRESAS E
                                where E.BDCODEMP = :PRCODEMP or E.BDCODMATRIZ = :PRCODEMP)))) and
                ((:PRCODTIPO in (42, 43) or F8.BDCODTER = :PRCODTER) and
                (((:PRCODTIPO in (40, 42)) and
                (SER.BDREFSERV = :PRREFARQ)) or ((:PRCODTIPO in (41, 43)) and
                ((select BDDATA
                  from SP_PARSE_DATE(F8.BDDATAPAGSERV, 'YYYYMM')) = :PRREFARQ))))

          union all

          select F9.BDINSSFEFOLFN BDINSS, F9.BDIRRFFEFN BDIRRF
          from VRHF_EMP_TFOLHANORMAL F9
          where (((:PRCODTIPO in (40, 41)) and
                (F9.BDCODEMP = :PRCODEMP)) or ((:PRCODTIPO in (42, 43)) and
                (F9.BDCODEMP in (select BDCODEMP
                                from TEMPRESAS E
                                where E.BDCODEMP = :PRCODEMP or E.BDCODMATRIZ = :PRCODEMP)))) and
                ((:PRCODTIPO in (42, 43) or F9.BDCODCOL = :PRCODCOL) and
                (((:PRCODTIPO in (40, 42)) and
                (F9.BDREFFN = :PRREFARQ)) or ((:PRCODTIPO in (41, 43)) and
                ((select BDDATA
                  from SP_PARSE_DATE(F9.BDDATAPGTOFN, 'YYYYMM')) = :PRREFARQ))))

          union all

          select F10.BDINSSFEFOLFT BDINSS, F10.BDIRRFFEFT BDIRRF
          from VRHF_EMP_TFOLHATOMADOR F10
          where (((:PRCODTIPO in (40, 41)) and
                (F10.BDCODEMP = :PRCODEMP)) or ((:PRCODTIPO in (42, 43)) and
                (F10.BDCODEMP in (select BDCODEMP
                                from TEMPRESAS E
                                where E.BDCODEMP = :PRCODEMP or E.BDCODMATRIZ = :PRCODEMP)))) and
                ((:PRCODTIPO in (42, 43) or F10.BDCODCOL = :PRCODCOL) and
                (((:PRCODTIPO in (40, 42)) and
                (F10.BDREFTOMADOR = :PRREFARQ)) or ((:PRCODTIPO in (41, 43)) and
                ((select BDDATA
                  from SP_PARSE_DATE(F10.BDDATAPGTOFT, 'YYYYMM')) = :PRREFARQ))))

          union all

          select 0, F11.BDVALORIRAD BDIRRF
          from VRHF_EMP_TADSAL F11
          where (((:PRCODTIPO in (40, 41)) and
                (F11.BDCODEMP = :PRCODEMP)) or ((:PRCODTIPO in (42, 43)) and
                (F11.BDCODEMP in (select BDCODEMP
                                from TEMPRESAS E
                                where E.BDCODEMP = :PRCODEMP or E.BDCODMATRIZ = :PRCODEMP)))) and
                ((:PRCODTIPO in (42, 43) or F11.BDCODCOL = :PRCODCOL) and
                (select BDDATA
                 from SP_PARSE_DATE(F11.BDDATAAD, 'YYYYMM')) = :PRREFARQ)

    ) F
    into :VBDINSS, :VBDIRRF;
    if (:PRCODTIPO in (40, 42)) then
    begin
      BDSISVALORTOTAL = VBDINSS;
    end
    else
    begin
      BDSISVALORTOTAL = VBDIRRF;
    end
  end
  suspend;
end^


CREATE OR ALTER trigger vrh_emp_tacconv_bi0 for vrh_emp_tacconv
active before insert position 0
AS
begin
  IF ((NEW.bdcodacconv IS NULL) OR (NEW.bdcodacconv = 0)) THEN
     SELECT COALESCE(MAX(bdcodacconv),0)+1 FROM vrh_emp_tacconv WHERE bdcodemp = NEW.bdcodemp INTO NEW.bdcodacconv;
end^

CREATE OR ALTER trigger vrh_emp_ttrabtemp_cpfsubs_bi0 for vrh_emp_ttrabtemp_cpfsubs
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;

BEGIN
  vcodigo = 0;
  IF ((NEW.bdordem IS NULL) OR (NEW.bdordem = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdordem)+1), 1) FROM VRH_EMP_TTRABTEMP_CPFSUBS WHERE (bdcodemp = NEW.bdcodemp)  AND (bdCodcol = NEW.bdcodcol) INTO vNova_Chave;
      NEW.bdordem = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT bdordem FROM VRH_EMP_TTRABTEMP_CPFSUBS WHERE (bdordem = NEW.bdordem) AND (bdcodcol = NEW.bdcodcol) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdordem)+1), 1) FROM VRH_EMP_TTRABTEMP_CPFSUBS WHERE (bdcodemp = NEW.bdcodemp) AND (bdcodcol = NEW.bdcodcol) INTO vNova_Chave;
           NEW.bdordem = vNova_Chave;
         END
    END
END^

CREATE OR ALTER trigger vef_emp_tcadlacre_bi0 for vef_emp_tcadlacre
active before insert position 0
AS
  DECLARE VARIABLE vBOMBA INTEGER;
BEGIN
  IF ((NEW.BDCODBOMBA IS not NULL) and (NEW.BDCODBOMBA > 0)) THEN
    begin
      exit;
    end


  IF ((NEW.BDCODBOMBA IS NULL) OR (NEW.BDCODBOMBA = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCODBOMBA)), 1) FROM vef_emp_tcadbomba WHERE bdcodemp = NEW.bdcodemp INTO vBOMBA;
      NEW.BDCODBOMBA = vBOMBA;
    END
END^

CREATE OR ALTER trigger vrh_emp_ttrabtemp_au0 for vrh_emp_ttrabtemp
active after update position 0
AS
begin
  update or insert into VRH_EMP_TCOL_ADM (BDCODEMP, BDCODCOL, BDDIASPRAZO1COL, BDDATAFIMPRAZO1COL, BDDIASPRAZO2COL, BDDATAFIMPRAZO2COL)
  values (new.BDCODEMP, new.BDCODCOL, new.BDDIASPRAZO1COL, new.BDDATAFIMPRAZO1COL, new.BDDIASPRAZO2COL, new.BDDATAFIMPRAZO2COL)
  matching(BDCODEMP, BDCODCOL);
end^


CREATE OR ALTER trigger vrh_emp_ttrabtemp_ai0 for vrh_emp_ttrabtemp
active after insert position 0
as
begin
  update or insert into VRH_EMP_TCOL_ADM (BDCODEMP, BDCODCOL, BDDIASPRAZO1COL, BDDATAFIMPRAZO1COL, BDDIASPRAZO2COL, BDDATAFIMPRAZO2COL)
  values (new.BDCODEMP, new.BDCODCOL, new.BDDIASPRAZO1COL, new.BDDATAFIMPRAZO1COL, new.BDDIASPRAZO2COL, new.BDDATAFIMPRAZO2COL)
  matching(BDCODEMP, BDCODCOL);
end^


CREATE OR ALTER trigger vati_depreciacao_auto_bi0 for vati_depreciacao_auto
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM VATI_DEPRECIACAO_AUTO INTO vNova_Chave;
      NEW.BDCHAVE = vNova_Chave;
     END
  ELSE
    BEGIN
       SELECT BDCHAVE FROM VATI_DEPRECIACAO_AUTO WHERE (BDCHAVE = NEW.BDCHAVE) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM VATI_DEPRECIACAO_AUTO INTO vNova_Chave;
           NEW.BDCHAVE = vNova_Chave;
         END
    END
END^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHAINT_BI0 FOR VRHF_EMP_TFOLHAINT
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vdata DATE;
  DECLARE VARIABLE vhora TIME;
  DECLARE VARIABLE VCODUSU INTEGER; /* Augusto - 02/04/2024 - #192435 */

BEGIN
  SELECT CURRENT_DATE, CURRENT_TIME FROM rdb$database INTO :vdata, :vhora;

  IF (NEW.bddataprocfn IS NULL) THEN
     NEW.bddataprocfn = vdata;

  IF (NEW.bdhoraprocfn IS NULL) THEN
     NEW.bdhoraprocfn = vhora;

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdreffn, '1', 'BDPERFOLHAINTERMITENTE'); -- 1 - Calculado

  /* Augusto - 02/04/2024 - #192435 */
  SELECT FIRST 1 BDCODUSU FROM VW_USUARIOS_SECAO INTO :VCODUSU;
  NEW.BDCODUSU = :VCODUSU;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHAINT_BU0 FOR VRHF_EMP_TFOLHAINT
ACTIVE BEFORE UPDATE POSITION 0
AS
  DECLARE VARIABLE vdata DATE;
  DECLARE VARIABLE vhora TIME;

BEGIN
  SELECT CURRENT_DATE, CURRENT_TIME FROM rdb$database INTO :vdata, :vhora;

  IF (NEW.bddataprocfn IS NULL) THEN
     NEW.bddataprocfn = vdata;

  IF (NEW.bdhoraprocfn IS NULL) THEN
     NEW.bdhoraprocfn = vhora;

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdreffn, '1', 'BDPERFOLHAINTERMITENTE'); -- 1 - Calculado
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHAINT_AD0 FOR VRHF_EMP_TFOLHAINT
ACTIVE AFTER DELETE POSITION 0
AS
  DECLARE VARIABLE vCOMP13NAFOLHA VARCHAR(5);
  DECLARE VARIABLE vSQL VARCHAR(1000);
BEGIN
  DELETE FROM VRHF_EMP_TFICHARV WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFRV = OLD.BDREFFN AND BDTIPOFRV = 0;
  DELETE FROM VRHF_EMP_TFICHAHE WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFHE = OLD.BDREFFN AND BDTIPOFHE = 0;
  DELETE FROM VRHF_EMP_TFICHAHN WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFHN = OLD.BDREFFN AND BDTIPOFHN = 0;
  DELETE FROM VRHF_EMP_TFICHAOUTRAS WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFOT = OLD.BDREFFN AND BDTIPOFOT = 0;
  DELETE FROM VRHF_EMP_TFICHAIRRF WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFIR = OLD.BDREFFN AND BDTIPOCALCFIR IN (0,3);

  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdtipocalc = 6 AND bdcodemp = OLD.bdcodemp AND
                                                               bdcodcol = OLD.bdcodcol AND
                                                               bdreferencia = OLD.BDREFFN AND
                                                               bdcodcontti = OLD.bdcodcontti;

  IF (SUBSTRING(OLD.BDREFFN FROM 5 FOR 2) = '12') THEN
     BEGIN
       vCOMP13NAFOLHA = '';
       vSQL = 'SELECT FIRST 1 UPPER(BDCALCC13NAFNEMP) FROM VRHF_BASE_TEMPPAR WHERE BDCODEMP = '||OLD.BDCODEMP||' AND BDREFEMP <= '||OLD.BDREFFN||' ORDER BY BDREFEMP DESC';
       EXECUTE STATEMENT vSQL INTO :vCOMP13NAFOLHA;

       IF (vCOMP13NAFOLHA = 'TRUE') THEN
          DELETE FROM VRHF_EMP_TC13SAL WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFC13 = OLD.BDREFFN;
     END

  EXECUTE PROCEDURE sp_vrh_painel_update(OLD.bdcodemp, OLD.bdreffn, '2', 'BDPERFOLHAINTERMITENTE'); -- 2 - Excluido
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHATOMINT_BI0 FOR VRHF_EMP_TFOLHATOMINT
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vdata DATE;
  DECLARE VARIABLE vhora TIME;
  DECLARE VARIABLE VCODUSU INTEGER; /* Augusto - 02/04/2024 - #192435 */

BEGIN
  SELECT CURRENT_DATE, CURRENT_TIME FROM rdb$database INTO :vdata, :vhora;

  IF (NEW.bddataprocft IS NULL) THEN
     NEW.bddataprocft = vdata;

  IF (NEW.bdhoraprocft IS NULL) THEN
     NEW.bdhoraprocft = vhora;

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdreftomador, '1', 'BDPERFOLHAINTERMITENTE'); -- 1 - Calculado

  /* Augusto - 02/04/2024 - #192435 */
  SELECT FIRST 1 BDCODUSU FROM VW_USUARIOS_SECAO INTO :VCODUSU;
  NEW.BDCODUSU = :VCODUSU;
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHATOMINT_BU0 FOR VRHF_EMP_TFOLHATOMINT
ACTIVE BEFORE UPDATE POSITION 0
AS
  DECLARE VARIABLE vdata DATE;
  DECLARE VARIABLE vhora TIME;

BEGIN
  SELECT CURRENT_DATE, CURRENT_TIME FROM rdb$database INTO :vdata, :vhora;

  IF (NEW.bddataprocft IS NULL) THEN
     NEW.bddataprocft = vdata;

  IF (NEW.bdhoraprocft IS NULL) THEN
     NEW.bdhoraprocft = vhora;

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdreftomador, '1', 'BDPERFOLHAINTERMITENTE'); -- 1 - Calculado
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHATOMINT_AD0 FOR VRHF_EMP_TFOLHATOMINT
ACTIVE AFTER DELETE POSITION 0
AS
  DECLARE VARIABLE vCOMP13NAFOLHA VARCHAR(5);
  DECLARE VARIABLE vSQL VARCHAR(1000);
BEGIN
  DELETE FROM VRHF_EMP_TFICHARV WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFRV = OLD.BDREFTOMADOR AND BDTIPOFRV = 100 AND BDCCFRV = OLD.BDORDEM;
  DELETE FROM VRHF_EMP_TFICHAHE WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFHE = OLD.BDREFTOMADOR AND BDTIPOFHE = 100 AND BDCCFHE = OLD.BDORDEM;
  DELETE FROM VRHF_EMP_TFICHAHN WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFHN = OLD.BDREFTOMADOR AND BDTIPOFHN = 100 AND BDCCFHN = OLD.BDORDEM;
  DELETE FROM VRHF_EMP_TFICHAOUTRAS WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFOT = OLD.BDREFTOMADOR AND BDTIPOFOT = 100 AND BDCCFOT = OLD.BDORDEM;
  DELETE FROM VRHF_EMP_TFICHAIRRF WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFIR = OLD.BDREFTOMADOR AND BDTIPOCALCFIR IN (100,300) AND BDCCFIR = OLD.BDORDEM;
  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdtipocalc = 7 AND bdcodemp = OLD.bdcodemp AND bdcodcol = OLD.bdcodcol AND bdreferencia = OLD.BDREFTOMADOR AND bdcodcontti = OLD.BDCODCONTTI;

  IF (SUBSTRING(OLD.BDREFTOMADOR FROM 5 FOR 2) = '12') THEN
     BEGIN
       vCOMP13NAFOLHA = '';
       vSQL = 'SELECT FIRST 1 UPPER(BDCALCC13NAFNEMP) FROM VRHF_BASE_TEMPPAR WHERE BDCODEMP = '||OLD.BDCODEMP||' AND BDREFEMP <= '||OLD.BDREFTOMADOR||' ORDER BY BDREFEMP DESC';
       EXECUTE STATEMENT vSQL INTO :vCOMP13NAFOLHA;

       IF (vCOMP13NAFOLHA = 'TRUE') THEN
          DELETE FROM VRHF_EMP_TC13SAL WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFC13 = OLD.BDREFTOMADOR;
     END

  EXECUTE PROCEDURE sp_vrh_painel_update(OLD.bdcodemp, OLD.bdreftomador, '2', 'BDPERFOLHAINTERMITENTE'); -- 2 - Excluido
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBAINT_DET_BI0 FOR VRHF_EMP_TVERBAINT_DET
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
--  IF (coalesce(NEW.BDITEMFND, 0) = 0) THEN
--     BEGIN
       SELECT COALESCE(MAX(X.BDITEMFND) + 1, 1)
       FROM VRHF_EMP_TVERBAINT_DET X
       WHERE X.BDCODEMP = NEW.BDCODEMP AND X.BDCODCOL = NEW.BDCODCOL AND X.BDREFFN = NEW.BDREFFN AND X.BDCODVER = NEW.BDCODVER
       INTO
         :vNovoCod;

       NEW.BDITEMFND = vNovoCod;
--     END
     END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBATOMINT_BI0 FOR VRHF_EMP_TVERBATOMINT
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vData VARCHAR(10);
  DECLARE VARIABLE vCta VARCHAR(100);
  DECLARE VARIABLE vDtInt INTEGER;
  DECLARE VARIABLE vCodCC INTEGER;

BEGIN
  --Comentário de ajuste
  IF (NEW.BDDATAENTRADAVFT IS NOT NULL) THEN
     BEGIN
       SELECT X.BDNOMCTA,X.BDCODTPCC FROM VW_UNION_DADOS_CC X WHERE
              X.BDCODEMP = NEW.BDCODEMP AND X.BDCODCOL = NEW.BDCODCOL AND X.BDORDEM = NEW.BDORDEM
       INTO vCta,vCodCC;
       vData = CAST(NEW.BDDATAENTRADAVFT AS VARCHAR(10));
       vDtInt = CAST((SUBSTRING(vData FROM 1 FOR 4)||SUBSTRING(vData FROM 6 FOR 2)||SUBSTRING(vData FROM 9 FOR 2)) AS INTEGER);

       IF (vCodCC IS NOT NULL) THEN
          NEW.BDDETALHEVFT = SUBSTRING(('Alocação iniciada em '||SUBSTRING(vData FROM 9 FOR 2)||'/'||SUBSTRING(vData FROM 6 FOR 2)||'/'||SUBSTRING(vData FROM 1 FOR 4)||
                             ' no Centro/tomador: '||vCta) FROM 1 FOR 500);
       ELSE
          NEW.BDDETALHEVFT = SUBSTRING(('Alocação iniciada em '||SUBSTRING(vData FROM 9 FOR 2)||'/'||SUBSTRING(vData FROM 6 FOR 2)||'/'||SUBSTRING(vData FROM 1 FOR 4)||
                             ' na Empresa: '||vCta) FROM 1 FOR 500);

       NEW.BDITEMVFT = vDtInt;
     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBATOMINT_BU0 FOR VRHF_EMP_TVERBATOMINT
ACTIVE BEFORE UPDATE POSITION 0
AS
  DECLARE VARIABLE vData VARCHAR(10);
  DECLARE VARIABLE vCta VARCHAR(100);
  DECLARE VARIABLE vCodCC INTEGER;
  DECLARE VARIABLE vDtInt INTEGER;

BEGIN
  --Comentário de ajuste
  IF (NEW.BDDATAENTRADAVFT IS NOT NULL) THEN
     BEGIN
       SELECT X.BDNOMCTA,X.BDCODTPCC FROM VW_UNION_DADOS_CC X WHERE
              X.BDCODEMP = NEW.BDCODEMP AND X.BDCODCOL = NEW.BDCODCOL AND X.BDORDEM = NEW.BDORDEM
       INTO vCta,vCodCC;
       vData = CAST(NEW.BDDATAENTRADAVFT AS VARCHAR(10));
       vDtInt = CAST((SUBSTRING(vData FROM 1 FOR 4)||SUBSTRING(vData FROM 6 FOR 2)||SUBSTRING(vData FROM 9 FOR 2)) AS INTEGER);

       IF (vCodCC IS NOT NULL) THEN
          NEW.BDDETALHEVFT = SUBSTRING(('Alocação iniciada em '||SUBSTRING(vData FROM 9 FOR 2)||'/'||SUBSTRING(vData FROM 6 FOR 2)||'/'||SUBSTRING(vData FROM 1 FOR 4)||
                             ' no Centro/tomador: '||vCta) FROM 1 FOR 500);
       ELSE
          NEW.BDDETALHEVFT = SUBSTRING(('Alocação iniciada em '||SUBSTRING(vData FROM 9 FOR 2)||'/'||SUBSTRING(vData FROM 6 FOR 2)||'/'||SUBSTRING(vData FROM 1 FOR 4)||
                             ' na Empresa: '||vCta) FROM 1 FOR 500);

       NEW.BDITEMVFT = vDtInt;

     END
END
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBATOMINT_DET_BI0 FOR VRHF_EMP_TVERBATOMINT_DET
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
--  IF (coalesce(NEW.BDITEMFTD, 0) = 0) THEN
--     BEGIN
       SELECT COALESCE(MAX(X.BDITEMFTD) + 1, 1)
       FROM vrhf_emp_tverbatomint_det X
       WHERE X.BDCODEMP = NEW.BDCODEMP AND X.BDCODCOL = NEW.BDCODCOL AND X.BDREFTOMADOR = NEW.BDREFTOMADOR AND X.BDCODVER = NEW.BDCODVER AND NEW.BDORDEM = X.BDORDEM
       INTO
         :vNovoCod;

       NEW.BDITEMFTD = vNovoCod;
--     END
     END
^

CREATE OR ALTER trigger tol_vrhf_emp_tcalc_int_bi0 for tol_vrhf_emp_tcalc_int
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TCALC_INT_AD0 FOR TOL_VRHF_EMP_TCALC_INT
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tfgts_int_bi0 for tol_vrhf_emp_tfgts_int
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TFGTS_INT_AD0 FOR TOL_VRHF_EMP_TFGTS_INT
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
    EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tverba_int_bi0 for tol_vrhf_emp_tverba_int
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TVERBA_INT_AD0 FOR TOL_VRHF_EMP_TVERBA_INT
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tcalc_tomint_bi0 for tol_vrhf_emp_tcalc_tomint
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TCALC_TOMINT_AD0 FOR TOL_VRHF_EMP_TCALC_TOMINT
ACTIVE AFTER DELETE POSITION 0
AS
  DECLARE VARIABLE wConta INTEGER;

BEGIN
  wConta = null;
  SELECT COUNT(bdcodempsuc) FROM TOL_VRHF_EMP_TCALC_TOMINT x WHERE x.bdcodempsuc = OLD.bdcodempsuc AND x.bdchave = OLD.bdchave INTO wConta;

  IF (coalesce(wconta, 0) <= 0) THEN
     EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tfgts_tomint_bi0 for tol_vrhf_emp_tfgts_tomint
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TFGTS_TOMINT_AD0 FOR TOL_VRHF_EMP_TFGTS_TOMINT
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER trigger tol_vrhf_emp_tverba_tomint_bi0 for tol_vrhf_emp_tverba_tomint
active before insert position 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if (coalesce(new.BDCODEMPSUC, 0) = 0) then
    new.BDCODEMPSUC = new.BDCODEMP;
  end
END^

CREATE OR ALTER TRIGGER TOL_VRHF_EMP_TVERBA_TOMINT_AD0 FOR TOL_VRHF_EMP_TVERBA_TOMINT
ACTIVE AFTER DELETE POSITION 0
AS
  DECLARE VARIABLE wConta INTEGER;

BEGIN
  wconta = null;
  SELECT first 1 bdcodempsuc FROM TOL_VRHF_EMP_TVERBA_TOMINT x WHERE x.bdcodempsuc = OLD.bdcodempsuc AND x.bdchave = OLD.bdchave INTO :wConta;

  IF (coalesce(wConta,0) <= 0) THEN
     EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodempsuc,OLD.bdchave);
END
^

CREATE OR ALTER TRIGGER VRH_EMP_CREDITO_TRABALHADOR_BI0 FOR VRH_EMP_CREDITO_TRABALHADOR
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (new.bdlogprocesso is not null) then
     new.bdlogprocesso = zipblob(new.bdlogprocesso);
end
^

CREATE OR ALTER TRIGGER VRH_EMP_CREDITO_TRABALHADOR_BU0 FOR VRH_EMP_CREDITO_TRABALHADOR
ACTIVE BEFORE UPDATE POSITION 0
AS
  declare variable wTextoAtual blob sub_type 1;
  declare variable wTextoNovo blob sub_type 1;
begin
  if (old.bdlogprocesso is not null) then
     wTextoAtual = unzipblob(old.bdlogprocesso);
  else
     wTextoAtual = '';

  if (new.bdlogprocesso is not null) then
     wTextoNovo = wTextoAtual|| ASCII_CHAR(13) || ASCII_CHAR(10) ||new.bdlogprocesso;
  else
     wTextoNovo = wTextoAtual;

  new.bdlogprocesso = zipblob(wTextoNovo);
end
^

CREATE OR ALTER trigger vaud_emp_tinconformidades_bi0 for vaud_emp_tinconformidades
active before insert position 0
AS
  DECLARE VARIABLE vCHAVEINCONF INTEGER;
BEGIN
  IF ((NEW.BDCHAVEINCONF IS NULL) OR (NEW.BDCHAVEINCONF = 0)) THEN
  BEGIN
    SELECT COALESCE(MAX(BDCHAVEINCONF), 0) + 1 BDCHAVEINCONF
    FROM VAUD_EMP_TINCONFORMIDADES
    WHERE
    BDCODEMP = NEW.BDCODEMP
    INTO :vCHAVEINCONF;
    NEW.BDCHAVEINCONF = vCHAVEINCONF;
  END
END
^

CREATE OR ALTER trigger vrh_emp_trescisao_au0 for vrh_emp_trescisao
active after update position 0
as
declare variable wIntAux INTEGER;
begin
  --alterar data de pagamento do cálculo
  if (old.BDDATAPAGRESCISAO <> new.BDDATAPAGRESCISAO) then
  begin
    update VRHF_EMP_TFOLHATOMADOR FT
    set FT.BDDATAPGTOFT = new.BDDATAPAGRESCISAO,
        FT.BDENVIOUESOCIAL = null,
        FT.BDENVIOUPGTOESOCIAL = null
    where FT.BDCODEMP = new.BDCODEMP and
          FT.BDCODCOL = new.BDCODCOL and
          FT.BDREFTOMADOR = new.BDREFRESCISAO;

    update VRHF_EMP_TFOLHANORMAL FN
    set FN.BDDATAPGTOFN = new.BDDATAPAGRESCISAO,
        FN.BDENVIOUESOCIAL = null,
        FN.BDENVIOUPGTOESOCIAL = null
    where FN.BDCODEMP = new.BDCODEMP and
          FN.BDCODCOL = new.BDCODCOL and
          FN.BDREFFN = new.BDREFRESCISAO;
  end

  wIntAux = 0;
  SELECT BDGRRFPRES FROM VRH_BASE_TPREPRESC WHERE BDCODPRES = new.bdcodpres into wIntAux;
  if (COALESCE(wIntAux, 0) > 0) then
     begin
       wIntAux = 0;
       select SUBSTRING(CAST(BDDATAFGTSDIGITAL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFGTSDIGITAL AS VARCHAR(10)) FROM 6 FOR 2) from VRH_ESOCIAL_TFASEAMENTO WHERE BDCODEMP = new.BDCODEMP into wIntAux;

       -- Ao fazer uma alteração no lançamento de rescisão alterando o valor de base de multa fgts faz o disparo para rodar o processo de exportação de grrf automaticamente
       if ((COALESCE(wIntAux,0) > 0) and (new.bdrefrescisao >= wIntAux) and (coalesce(old.bdbasemultafgts,0) <> coalesce(new.bdbasemultafgts, 0))) then
          UPDATE OR INSERT INTO TTHREAD (BDPARAM,BDVALORINT) VALUES ('TTHREADIMP_'||new.bdcodemp||'_'||new.bdcodcol||'_'||new.bdrefrescisao||'_40', 0) MATCHING (BDPARAM);
     end
end^


/* Restore proc. body: SP_CONS_CALC_INTERMITENTE */
create or alter procedure SP_CONS_CALC_INTERMITENTE (
    PRCODEMP integer = null,
    PRCODEMPMULT varchar(15000) = '',
    PRCODCOL integer = null,
    PRCODCOLMULT varchar(15000) = '',
    PRCODCONTRATO integer = null,
    PRDATAINICIAL date = null,
    PRDATAFINAL date = null,
    PRVERBASDEM smallint = 1)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(18),
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDRGCOL varchar(13),
    BDCTPSCOL varchar(11),
    BDSERIECTPSCOL varchar(11),
    BDDSERIECTPSCOL varchar(1),
    BDCODCBO integer,
    BDDESCTFUC varchar(40),
    BDSALBASECOL numeric(18,6),
    BDCODCONTTI integer,
    BDDESCCONTRATOTI varchar(2000),
    BDDATACONVTI date,
    BDHORACONVTI time,
    BDDATAINISERVTI date,
    BDDATAFIMSERVTI date,
    BDDATAPAGTI date,
    BDLIQUIDO numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDDATAPGTOFN date,
    BDFGTSFN numeric(18,6),
    BDFGTS13FN numeric(18,6),
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFVFN numeric(18,6),
    BDREFAUXVFN numeric(18,6),
    BDVALVFN numeric(18,6),
    BDVALIFN numeric(18,6),
    BDDESCVER varchar(40),
    BDTIPOCODVER integer,
    BDORDEMVER integer,
    BDORDEMTIPOCODVER integer,
    BDCLAVER varchar(20))
as
declare variable WSQL varchar(11000);
declare variable WWHERE varchar(5000);
declare variable WSQL2 varchar(10000);
declare variable WWHERE2 varchar(5000);
begin
    --<Local aonde deve ser zerado as variáveis>--
    wSQL   = ' ';
    wWhere = ' ';

    /**************************************************************************/
    /*                      Início da montagem do SQL                         */
    /*                                  |                                     */
    /*                                  |                                     */
    /*                               ___|___                                  */
    /*                               \     /                                  */
    /*                                \   /                                   */
    /*                                 \ /                                    */
    /*                                  v                                     */
    /*                                                                        */
    /**************************************************************************/

    --<Colaborador>--
    wSQL = wSQL ||' SELECT '                                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDCODEMP,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDNOMEMP,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_TEMP.BDCNPJEMP,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDLOGREMP,'                 || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDENDEMP,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDNUMEMP,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDCODCID,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_CIDADE.BDNOMCID,'                   || ASCII_CHAR(13);
    --<Colaborador>--                                         
    wSQL = wSQL ||'    LF_COLCAD.BDNOMCOL,'                   || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_COLDOC1.BDCPFCOL,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_COLDOC2.BDPISCOL,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_COLDOC2.BDRGCOL,'                   || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_COLDOC2.BDCTPSCOL,'                 || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'    LF_COLDOC2.BDSERIECTPSCOL,'            || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'    LF_COLDOC2.BDDSERIECTPSCOL,'           || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'    FUC.BDCODCBO,'                         || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'    FUC.BDDESCTFUC,'                       || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'    COL_CALCDIA.BDSALBASECOL,'             || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    --<Contrato>--
    wSQL = wSQL ||'    J_CONTRATO_INT.BDCODCONTTI,'           || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDESCCONTRATOTI,'      || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATACONVTI,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDHORACONVTI,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATAINISERVTI,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATAFIMSERVTI,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATAPAGTI,'           || ASCII_CHAR(13);
    --<Cálculo>--
    wSQL = wSQL ||'    F_CALC.BDLIQUIDO,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDBINSSFN,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDDATAPGTOFN,'                  || ASCII_CHAR(13);
    WSQL = WSQL ||'    F_CALC.BDFGTSFN,'                      || ASCII_CHAR(13);
    WSQL = WSQL ||'    F_CALC.BDFGTS13FN,'                    || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDCODCOL,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDCODVER,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDREFFN,'                       || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDREFVFN,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDREFAUXVFN,'                   || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDVALVFN,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDVALIFN,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDDESCVER,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDTIPOCODVER,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDORDEMVER,'                    || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDORDEMTIPOCODVER,'             || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDCLAVER'                       || ASCII_CHAR(13);
    wSQL = wSQL ||' FROM (SELECT'                             || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDCODCONTTI,'        || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDLIQUIDO,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDBINSSFN,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDDATAPGTOFN,'       || ASCII_CHAR(13);
    WSQL = WSQL ||'           XF_CALCULO.BDFGTSFN,'           || ASCII_CHAR(13);
    WSQL = WSQL ||'           XF_CALCULO.BDFGTS13FN,'         || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDCODEMP,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDCODCOL,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDCODVER,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_CADVERB.BDDESCVER,'         || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_CADVERB.BDORDEMVER,'        || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_CADVERB.BDCLAVER,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_DESCVERB.BDTIPOCODVER,'     || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_DESCVERB.BDORDEMTIPOCODVER,'|| ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDREFFN,'        || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDREFVFN,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDREFAUXVFN,'    || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDVALVFN,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDVALIFN'        || ASCII_CHAR(13);
    wSQL = wSQL ||'       FROM VRHF_EMP_TFOLHAINT XF_CALCULO' || ASCII_CHAR(13);

    if (prcodemp is null and prcodempmult is null) then
       wSQL = wSQL ||      ' JOIN TMP_EMPRESAS_SELECT EMPSELECT on (EMPSELECT.BDCODEMP = XF_CALCULO.BDCODEMP) ';

    wSQL = wSQL ||'       LEFT JOIN VRHF_EMP_TVERBAINT XLF_VERBASCALC ON (XF_CALCULO.BDCODEMP    = XLF_VERBASCALC.BDCODEMP AND'    || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                       XF_CALCULO.BDCODCOL    = XLF_VERBASCALC.BDCODCOL AND'    || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                       XF_CALCULO.BDCODCONTTI = XLF_VERBASCALC.BDCODCONTTI AND' || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                       XF_CALCULO.BDREFFN     = XLF_VERBASCALC.BDREFFN)'        || ASCII_CHAR(13);
    wSQL = wSQL ||'       LEFT JOIN VRH_BASE_TVERBAS XLF_CADVERB      ON (XLF_VERBASCALC.BDCODVER = XLF_CADVERB.BDCODVER)'         || ASCII_CHAR(13);
    wSQL = wSQL ||'       LEFT JOIN VW_VERBAS_REF_ATUAL XLF_DESCVERB  ON (XLF_CADVERB.BDCODVER    = XLF_DESCVERB.BDCODVER)'        || ASCII_CHAR(13);

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    /*Filtro por empresa*/
    IF (NOT prCODEmp IS NULL AND prCODEmp <> 0) THEN
        BEGIN
            wWhere = wWhere || 'XF_CALCULO.BDCODEMP = ' || prCODEmp;
        END
    ELSE
        BEGIN
            IF (TRIM(prCODEmpMult) <> '') THEN
                BEGIN
                    IF (wWhere <> '') THEN
                        wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

                    wWhere = wWhere || 'XF_CALCULO.BDCODEMP in (' || prCODEmpMult || ')';
                END
        END

    /*Filtro por Contrato*/
    IF (NOT prCODContrato IS NULL AND prCODContrato <> 0) THEN
        BEGIN
            IF (wWhere <> '') THEN
                wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

            wWhere = wWhere || 'XF_CALCULO.BDCODCONTTI = '||prCODContrato;
        END

    /*Filtro por Colaborador*/
    IF (NOT prCODCol IS NULL AND prCODCol <> 0 ) THEN
        BEGIN
            IF (wWhere <> '') THEN
                wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

             wWhere = wWhere || 'XF_CALCULO.BDCODCOL = ' || prCODCol;
        END
    ELSE
        BEGIN
            IF (TRIM(prCODColMult) <> '') THEN
                BEGIN
                    IF (wWhere <> '') THEN
                        wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

                    wWhere = wWhere || 'XF_CALCULO.BDCODCOL in (' || prCODColMult || ')';
                END
        END

    /*Filtro por Data*/
    IF (prdatainicial is not null and prdatafinal is not null) THEN
        BEGIN
          IF (wWhere <> '') THEN
             wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

             wWhere = wWhere || 'XF_CALCULO.BDREFFN between ' || SUBSTRING(CAST(prdatainicial as VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatainicial as VARCHAR(10)) FROM 6 FOR 2)||
                      ' and '||SUBSTRING(CAST(prdatafinal as VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatafinal as VARCHAR(10)) FROM 6 FOR 2);
        END

    /* Filtro verbas demonstrativas */
    IF (coalesce(prverbasdem, 0) = 0) then
        BEGIN
          IF (wWhere <> '') THEN
             wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

             wWhere = wWhere || 'COALESCE(XLF_DESCVERB.BDTIPOCODVER, 0) in (0,1)';
        END

    IF (wWhere <> '') THEN
        BEGIN
            wWhere = ' WHERE ' || ASCII_CHAR(13) || wWhere;
        END

    wSQL = wSQL || wWhere || ASCII_CHAR(13);

    wSQL = wSQL || ') F_CALC ' || ASCII_CHAR(13);
    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------

    wSQL = wSQL ||'JOIN VW_TEMPRESAS_REF       J_EMPPRESA     ON (F_CALC.BDCODEMP         = J_EMPPRESA.BDCODEMP) '              || ASCII_CHAR(13);
    wSQL = wSQL ||'JOIN TEMPRESAS              J_TEMP         ON (F_CALC.BDCODEMP         = J_TEMP.BDCODEMP) '                  || ASCII_CHAR(13);
    wSQL = wSQL ||'JOIN VRH_EMP_TINTERMITENTE  J_CONTRATO_INT ON (F_CALC.BDCODEMP         = J_CONTRATO_INT.BDCODEMP AND '       || ASCII_CHAR(13);
    wSQL = wSQL ||                                               'F_CALC.BDCODCOL         = J_CONTRATO_INT.BDCODCOL AND '       || ASCII_CHAR(13);
    wSQL = wSQL ||                                               'F_CALC.BDCODCONTTI      = J_CONTRATO_INT.BDCODCONTTI) '       || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN TCIDADE                LF_CIDADE      ON (J_EMPPRESA.BDCODCID     = LF_CIDADE.BDCODCID) '    || ASCII_CHAR(13);
--    wSQL = wSQL ||'LEFT OUTER JOIN VW_TCOLCON_REF_ATUAL   LF_REFCOL      ON (J_CONTRATO_INT.BDCODEMP = LF_REFCOL.BDCODEMP) '    || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD    LF_COLCAD      ON (F_CALC.BDCODEMP         = LF_COLCAD.BDCODEMP AND'  || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = LF_COLCAD.BDCODCOL) '    || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC    LF_COLDOC1     ON (F_CALC.BDCODEMP         = LF_COLDOC1.BDCODEMP AND' || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC1.BDCODCOL) '   || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF LF_COLDOC2     ON (F_CALC.BDCODEMP         = LF_COLDOC2.BDCODEMP AND' || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC2.BDCODCOL) '   || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VRH_EMP_TRESCISAO RESC                ON (RESC.BDCODEMP = F_CALC.BDCODEMP and RESC.BDCODCOL = F_CALC.BDCODCOL) '|| ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CALCDIA COL_CALCDIA ON (F_CALC.BDCODEMP = COL_CALCDIA.BDCODEMP AND'       || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'                                                           F_CALC.BDCODCOL = COL_CALCDIA.BDCODCOL) '         || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'LEFT OUTER JOIN VW_VRH_EMP_TCOL_VINCDIA COL_VINCDIA    ON (F_CALC.BDCODEMP = COL_VINCDIA.BDCODEMP AND'       || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'                                                           F_CALC.BDCODCOL = COL_VINCDIA.BDCODCOL) '         || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'LEFT OUTER JOIN VRH_FUNCOES_TFUC FUC ON (COL_VINCDIA.BDCODPLAFUC = FUC.BDCODPLAFUC AND'                      || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'                                         COL_VINCDIA.BDCODTFUC = FUC.BDCODTFUC) '                            || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    wSQL = wSQL||'where ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO is not null and upper(coalesce(J_CONTRATO_INT.BDCONVRESCTI, ''FALSE'')) = ''FALSE'')) ';

    IF (prdatainicial is not null and prdatafinal is not null) THEN
      begin
        wSQL = wSQL||' and ((J_CONTRATO_INT.BDDATAINISERVTI  BETWEEN ''' || prDataInicial || ''' AND ' || '''' || prDataFinal || ''') ';
        wSQL = wSQL||' or (J_CONTRATO_INT.BDDATAFIMSERVTI  BETWEEN ''' || prDataInicial || ''' AND ' || '''' || prDataFinal || ''')) ';
      end

    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------
    /**************************************************************************/
    /*                                                                        */
    /*                                 ^                                      */
    /*                                /|\                                     */
    /*                               /   \                                    */
    /*                              /_____\                                   */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                       Final da montagem do SQL                         */
    /**************************************************************************/

    --<Local aonde deve ser zerado as variáveis>--
    wSQL2   = ' ';
    wWhere2 = ' ';

    /**************************************************************************/
    /*                      Início da montagem do SQL                         */
    /*                                  |                                     */
    /*                                  |                                     */
    /*                               ___|___                                  */
    /*                               \     /                                  */
    /*                                \   /                                   */
    /*                                 \ /                                    */
    /*                                  v                                     */
    /*                                                                        */
    /**************************************************************************/

    --<Colaborador>--
    wSQL2 = wSQL2 ||' SELECT '                                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDCODEMP,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDNOMEMP,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_TEMP.BDCNPJEMP,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDLOGREMP,'                 || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDENDEMP,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDNUMEMP,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDCODCID,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_CIDADE.BDNOMCID,'                   || ASCII_CHAR(13);
    --<Colaborador>--                                         
    wSQL2 = wSQL2 ||'    LF_COLCAD.BDNOMCOL,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_COLDOC1.BDCPFCOL,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_COLDOC2.BDPISCOL,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_COLDOC2.BDRGCOL,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_COLDOC2.BDCTPSCOL,'                 || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'    LF_COLDOC2.BDSERIECTPSCOL,'            || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'    LF_COLDOC2.BDDSERIECTPSCOL,'           || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'    FUC.BDCODCBO,'                         || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'    FUC.BDDESCTFUC,'                       || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'    COL_CALCDIA.BDSALBASECOL,'             || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    --<Contrato>--
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDCODCONTTI,'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDESCCONTRATOTI,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATACONVTI,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDHORACONVTI,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATAINISERVTI,'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATAFIMSERVTI,'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATAPAGTI,'           || ASCII_CHAR(13);
    --<Cálculo>--
    wSQL2 = wSQL2 ||'    F_CALC.BDLIQUIDO,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDBINSSFN,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDDATAPGTOFN,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDFGTSFN,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDFGTS13FN,'                    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDCODCOL,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDCODVER,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDREFFN,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    case '                                 || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'      when F_CALC.BDCLAVER starting with ''9'' then F_CALC.BDREFVFNMAX ' || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    else F_CALC.BDREFVFNSUM '              || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    end BDREFVFN, '                         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDREFAUXVFN,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDVALVFN,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDVALIFN,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDDESCVER,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDTIPOCODVER,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDORDEMVER,'                    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDORDEMTIPOCODVER,'             || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDCLAVER'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||' FROM (SELECT'                                             || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'        XF_CALCULO.BDCODCONTTI,'                            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'SUM(XF_CALCULO.BDLIQUIDO) AS BDLIQUIDO,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XF_CALCULO.BDBINSSFT) AS BDBINSSFN,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XF_CALCULO.BDDATAPGTOFT AS BDDATAPGTOFN,'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XF_CALCULO.BDFGTSFT) AS BDFGTSFN,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XF_CALCULO.BDFGTS13FT) AS BDFGTS13FN,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODEMP,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODCOL,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODVER,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDDESCVER,'                         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDORDEMVER,'                        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_DESCVERB.BDTIPOCODVER,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDCLAVER,'                          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_DESCVERB.BDORDEMTIPOCODVER,'                || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDREFTOMADOR AS BDREFFN,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           sum(XLF_VERBASCALC.BDREFVFT) as BDREFVFNSUM,'   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           max(XLF_VERBASCALC.BDREFVFT) as BDREFVFNMAX,'   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           sum(XLF_VERBASCALC.BDREFAUXVFT) AS BDREFAUXVFN,'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XLF_VERBASCALC.BDVALVFT) AS BDVALVFN,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XLF_VERBASCALC.BDVALIFT) AS BDVALIFN'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       FROM VRHF_EMP_TFOLHATOMINT XF_CALCULO'              || ASCII_CHAR(13);

    if (prcodemp is null and prcodempmult is null) then
       wSQL = wSQL ||      ' JOIN TMP_EMPRESAS_SELECT EMPSELECT on (EMPSELECT.BDCODEMP = XF_CALCULO.BDCODEMP) ';

    wSQL2 = wSQL2 ||'       LEFT JOIN VRHF_EMP_TVERBATOMINT XLF_VERBASCALC ON (XF_CALCULO.BDCODEMP     = XLF_VERBASCALC.BDCODEMP AND'     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDCODCOL     = XLF_VERBASCALC.BDCODCOL AND'     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDCODCONTTI  = XLF_VERBASCALC.BDCODCONTTI AND'  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDREFTOMADOR = XLF_VERBASCALC.BDREFTOMADOR AND' || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDORDEM      = XLF_VERBASCALC.BDORDEM)'         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       LEFT JOIN VRH_BASE_TVERBAS XLF_CADVERB         ON (XLF_VERBASCALC.BDCODVER = XLF_CADVERB.BDCODVER)'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       LEFT JOIN VW_VERBAS_REF_ATUAL XLF_DESCVERB     ON (XLF_CADVERB.BDCODVER    = XLF_DESCVERB.BDCODVER)'          || ASCII_CHAR(13);

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    /*Filtro por empresa*/
    IF (NOT prCODEmp IS NULL AND prCODEmp <> 0) THEN
        BEGIN
            wWhere2 = wWhere2 || 'XF_CALCULO.BDCODEMP = ' || prCODEmp;
        END
    ELSE
        BEGIN
            IF (TRIM(prCODEmpMult) <> '') THEN
                BEGIN
                    IF (wWhere2 <> '') THEN
                        wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);

                    wWhere2 = wWhere2 || 'XF_CALCULO.BDCODEMP in (' || prCODEmpMult || ')';
                END
        END

    /*Filtro por Contrato*/
    IF (NOT prCODContrato IS NULL AND prCODContrato <> 0) THEN
        BEGIN
            IF (wWhere2 <> '') THEN
                wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);

            wWhere2 = wWhere2 || 'XF_CALCULO.BDCODCONTTI = '||prCODContrato;
        END

    /*Filtro por Colaborador*/
    IF (NOT prCODCol IS NULL AND prCODCol <> 0) THEN
        BEGIN
            IF (wWhere2 <> '') THEN
                wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);

             wWhere2 = wWhere2 || 'XF_CALCULO.BDCODCOL = ' || prCODCol;
        END
    ELSE
        BEGIN
            IF (TRIM(prCodColMult) <> '') THEN
                BEGIN
                    IF (wWhere2 <> '') THEN
                        wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);
    
                    wWhere2 = wWhere2 || 'XF_CALCULO.BDCODCOL in (' || prCODColMult || ')';
                END
        END

    /*Filtro por Data*/
    IF (prdatainicial is not null and prdatafinal is not null) THEN
        BEGIN
            IF (wWhere2 <> '') THEN
                wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);

             wWhere2 = wWhere2 || 'XF_CALCULO.BDREFTOMADOR between ' || SUBSTRING(CAST(prdatainicial as VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatainicial as VARCHAR(10)) FROM 6 FOR 2)||
                      ' and '||SUBSTRING(CAST(prdatafinal as VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatafinal as VARCHAR(10)) FROM 6 FOR 2);
        END

    /* Filtro verbas demonstrativas */
    if (coalesce(prverbasdem, 0) = 0) then
        BEGIN
          IF (wWhere <> '') THEN
             wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);
             wWhere2 = wWhere2 || 'COALESCE(XLF_DESCVERB.BDTIPOCODVER, 0) in (0,1)';
        END

    IF (wWhere2 <> '') THEN
        BEGIN
            wWhere2 = ' WHERE ' || ASCII_CHAR(13) || wWhere2;
        END

    wSQL2 = wSQL2 || wWhere2 || ASCII_CHAR(13);

    wSQL2 = wSQL2 ||'       GROUP BY'                            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XF_CALCULO.BDCODCONTTI,'         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XF_CALCULO.BDDATAPGTOFT,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODEMP,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODCOL,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODVER,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDDESCVER,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDORDEMVER,'         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_DESCVERB.BDTIPOCODVER,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDCLAVER,'            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_DESCVERB.BDORDEMTIPOCODVER,' || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDREFTOMADOR'    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||') F_CALC'                                   || ASCII_CHAR(13);

    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------

    wSQL2 = wSQL2 ||'           JOIN VW_TEMPRESAS_REF       J_EMPPRESA     ON (F_CALC.BDCODEMP         = J_EMPPRESA.BDCODEMP)'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           JOIN TEMPRESAS              J_TEMP         ON (F_CALC.BDCODEMP         = J_TEMP.BDCODEMP)'               || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           JOIN VRH_EMP_TINTERMITENTE  J_CONTRATO_INT ON (F_CALC.BDCODEMP         = J_CONTRATO_INT.BDCODEMP     AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = J_CONTRATO_INT.BDCODCOL     AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCONTTI      = J_CONTRATO_INT.BDCODCONTTI)'    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN TCIDADE                LF_CIDADE      ON (J_EMPPRESA.BDCODCID     = LF_CIDADE.BDCODCID)'            || ASCII_CHAR(13);
--    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VW_TCOLCON_REF_ATUAL   LF_REFCOL      ON (J_CONTRATO_INT.BDCODEMP = LF_REFCOL.BDCODEMP          AND'|| ASCII_CHAR(13);
--    wSQL2 = wSQL2 ||'                                                          J_CONTRATO_INT.BDCODCOL = LF_REFCOL.BDCODCOL)'            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD    LF_COLCAD      ON (F_CALC.BDCODEMP         = LF_COLCAD.BDCODEMP          AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = LF_COLCAD.BDCODCOL)'            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC    LF_COLDOC1     ON (F_CALC.BDCODEMP         = LF_COLDOC1.BDCODEMP         AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC1.BDCODCOL)'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF LF_COLDOC2     ON (F_CALC.BDCODEMP         = LF_COLDOC2.BDCODEMP         AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC2.BDCODCOL)'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CALCDIA COL_CALCDIA ON (F_CALC.BDCODEMP = COL_CALCDIA.BDCODEMP AND'              || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'                                                           F_CALC.BDCODCOL = COL_CALCDIA.BDCODCOL) '                || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VW_VRH_EMP_TCOL_VINCDIA COL_VINCDIA    ON (F_CALC.BDCODEMP = COL_VINCDIA.BDCODEMP AND'              || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'                                                           F_CALC.BDCODCOL = COL_VINCDIA.BDCODCOL) '                || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VRH_FUNCOES_TFUC FUC ON (COL_VINCDIA.BDCODPLAFUC = FUC.BDCODPLAFUC AND'                             || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'                                         COL_VINCDIA.BDCODTFUC = FUC.BDCODTFUC) '                                   || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    wWhere2 = ' ';
    if ((prDataInicial is not null) AND ( prDataFinal is not null)) THEN
        BEGIN
            wWhere2 = ' WHERE ((J_CONTRATO_INT.BDDATAINISERVTI  BETWEEN ''' || prDataInicial || ''' AND ' || '''' || prDataFinal || ''') ';
            wWhere2 = wWhere2||' or (J_CONTRATO_INT.BDDATAFIMSERVTI  BETWEEN ''' || prDataInicial || ''' AND ' || '''' || prDataFinal || ''')) ';
        END

    wSQL2 = wSQL2 || wwhere2 || ASCII_CHAR(13);

    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------
    /**************************************************************************/
    /*                                                                        */
    /*                                 ^                                      */
    /*                                /|\                                     */
    /*                               /   \                                    */
    /*                              /_____\                                   */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                       Final da montagem do SQL                         */
    /**************************************************************************/
    
    wSQL = wSQL    || ASCII_CHAR(13) ||
           'UNION' || ASCII_CHAR(13) ||
           wSQL2;

    /*Seta a competência para o banco*/
    EXECUTE PROCEDURE SP_SETA_COMPETENCIA(SUBSTRING(CAST(prdatafinal AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatafinal AS VARCHAR(10)) FROM 6 FOR 2));

    FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :BDNOMEMP,
        :BDCNPJEMP,
        :BDLOGREMP,
        :BDENDEMP,
        :BDNUMEMP,
        :BDCODCID,
        :BDNOMCID,
        :BDNOMCOL,
        :BDCPFCOL,
        :BDPISCOL,
        :BDRGCOL,
        :BDCTPSCOL,        -- 152278 Leonardo Schwab 13/07/2021
        :BDSERIECTPSCOL,   -- 152278 Leonardo Schwab 13/07/2021
        :BDDSERIECTPSCOL,  -- 152278 Leonardo Schwab 13/07/2021
        :BDCODCBO,         -- 152278 Leonardo Schwab 13/07/2021
        :BDDESCTFUC,       -- 152278 Leonardo Schwab 13/07/2021
        :BDSALBASECOL,     -- 152278 Leonardo Schwab 13/07/2021
        :BDCODCONTTI,
        :BDDESCCONTRATOTI,
        :BDDATACONVTI,
        :BDHORACONVTI,
        :BDDATAINISERVTI,
        :BDDATAFIMSERVTI,
        :BDDATAPAGTI,
        :BDLIQUIDO,
        :BDBINSSFN,
        :BDDATAPGTOFN,
        :BDFGTSFN,
        :BDFGTS13FN,
        :BDCODCOL,
        :BDCODVER,
        :BDREFFN,
        :BDREFVFN,
        :BDREFAUXVFN,
        :BDVALVFN,
        :BDVALIFN,
        :BDDESCVER,
        :BDTIPOCODVER,
        :BDORDEMVER,
        :BDORDEMTIPOCODVER,
        :BDCLAVER
    DO
        SUSPEND;
end^

/* Restore proc. body: SP_CONS_CALC_INTERMITENTE_COMP */
create or alter procedure SP_CONS_CALC_INTERMITENTE_COMP (
    PRCODEMP integer = null,
    PRCODEMPMULT varchar(15000) = '',
    PRCODCOL integer = null,
    PRCODCOLMULT varchar(15000) = '',
    PRCODCONTRATO integer = null,
    PRDATAINICIAL date = null,
    PRDATAFINAL date = null,
    PRDATAPGTOINICIAL date = null,
    PRDATAPGTOFINAL date = null,
    PRVERBASDEM smallint = 1)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(18),
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDRGCOL varchar(13),
    BDCTPSCOL varchar(11),
    BDSERIECTPSCOL varchar(11),
    BDDSERIECTPSCOL varchar(1),
    BDCODCBO integer,
    BDDESCTFUC varchar(40),
    BDSALBASECOL numeric(18,6),
    BDCODCONTTI integer,
    BDDESCCONTRATOTI varchar(2000),
    BDDATACONVTI date,
    BDHORACONVTI time,
    BDDATAINISERVTI date,
    BDDATAFIMSERVTI date,
    BDDATAPAGTI date,
    BDLIQUIDO numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDDATAPGTOFN date,
    BDFGTSFN numeric(18,6),
    BDFGTS13FN numeric(18,6),
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFVFN numeric(18,6),
    BDREFAUXVFN numeric(18,6),
    BDVALVFN numeric(18,6),
    BDVALIFN numeric(18,6),
    BDDESCVER varchar(40),
    BDTIPOCODVER integer,
    BDORDEMVER integer,
    BDORDEMTIPOCODVER integer,
    BDCLAVER varchar(40))
as
declare variable WSQL varchar(11000);
declare variable WWHERE varchar(5000);
declare variable WSQL2 varchar(10000);
declare variable WWHERE2 varchar(5000);
begin
    --<Local aonde deve ser zerado as variáveis>--
    wSQL   = ' ';
    wWhere = ' ';

    /**************************************************************************/
    /*                      Início da montagem do SQL                         */
    /*                                  |                                     */
    /*                                  |                                     */
    /*                               ___|___                                  */
    /*                               \     /                                  */
    /*                                \   /                                   */
    /*                                 \ /                                    */
    /*                                  v                                     */
    /*                                                                        */
    /**************************************************************************/

    --<Colaborador>--
    wSQL = wSQL ||' SELECT '                                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDCODEMP,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDNOMEMP,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_TEMP.BDCNPJEMP,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDLOGREMP,'                 || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDENDEMP,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDNUMEMP,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_EMPPRESA.BDCODCID,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_CIDADE.BDNOMCID,'                   || ASCII_CHAR(13);
    --<Colaborador>--                                         
    wSQL = wSQL ||'    LF_COLCAD.BDNOMCOL,'                   || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_COLDOC1.BDCPFCOL,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_COLDOC2.BDPISCOL,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_COLDOC2.BDRGCOL,'                   || ASCII_CHAR(13);
    wSQL = wSQL ||'    LF_COLDOC2.BDCTPSCOL,'                 || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'    LF_COLDOC2.BDSERIECTPSCOL,'            || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'    LF_COLDOC2.BDDSERIECTPSCOL,'           || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'    FUC.BDCODCBO,'                         || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'    FUC.BDDESCTFUC,'                       || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'    COL_CALCDIA.BDSALBASECOL,'             || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    --<Contrato>--
    wSQL = wSQL ||'    J_CONTRATO_INT.BDCODCONTTI,'           || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDESCCONTRATOTI,'      || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATACONVTI,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDHORACONVTI,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATAINISERVTI,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'    J_CONTRATO_INT.BDDATAFIMSERVTI,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDDATAPAGFC,'                   || ASCII_CHAR(13);
    --<Cálculo>--
    wSQL = wSQL ||'    F_CALC.BDLIQUIDO,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDBINSSFC,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDDATAPAGFC,'                   || ASCII_CHAR(13);
    WSQL = WSQL ||'    F_CALC.BDFGTSFC,'                      || ASCII_CHAR(13);
    WSQL = WSQL ||'    F_CALC.BDFGTS13FC,'                    || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDCODCOL,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDCODVER,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDREFFN,'                       || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDREFVFC,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDREFAUXVFC,'                   || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDVALVFC,'                      || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDVALVIFC,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDDESCVER,'                     || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDTIPOCODVER,'                  || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDORDEMVER,'                    || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDORDEMTIPOCODVER,'             || ASCII_CHAR(13);
    wSQL = wSQL ||'    F_CALC.BDCLAVER'                       || ASCII_CHAR(13);
    wSQL = wSQL ||' FROM (SELECT'                             || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDCODCONTTI,'        || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDLIQUIDO,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDBINSSFC,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'           XF_CALCULO.BDDATAPAGFC,'        || ASCII_CHAR(13);
    WSQL = WSQL ||'           XF_CALCULO.BDFGTSFC,'           || ASCII_CHAR(13);
    WSQL = WSQL ||'           XF_CALCULO.BDFGTS13FC,'         || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDCODEMP,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDCODCOL,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDCODVER,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_CADVERB.BDDESCVER,'         || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_CADVERB.BDORDEMVER,'        || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_CADVERB.BDCLAVER,'          || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_DESCVERB.BDTIPOCODVER,'     || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_DESCVERB.BDORDEMTIPOCODVER,'|| ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDREFFN,'        || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDREFVFC,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDREFAUXVFC,'    || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDVALVFC,'       || ASCII_CHAR(13);
    wSQL = wSQL ||'           XLF_VERBASCALC.BDVALVIFC'       || ASCII_CHAR(13);
    wSQL = wSQL ||'       FROM VRHF_EMP_TFOLHACOMPINT XF_CALCULO' || ASCII_CHAR(13);

    if (prcodemp is null and prcodempmult is null) then
       wSQL = wSQL ||      ' JOIN TMP_EMPRESAS_SELECT EMPSELECT on (EMPSELECT.BDCODEMP = XF_CALCULO.BDCODEMP) ';

    wSQL = wSQL ||'       LEFT JOIN VRHF_EMP_TVERBAFCINT XLF_VERBASCALC ON (XF_CALCULO.BDCODEMP    = XLF_VERBASCALC.BDCODEMP AND'  || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                       XF_CALCULO.BDCODCOL    = XLF_VERBASCALC.BDCODCOL AND'    || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                       XF_CALCULO.BDCODCONTTI = XLF_VERBASCALC.BDCODCONTTI AND' || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                       XF_CALCULO.BDREFFC = XLF_VERBASCALC.BDREFFC AND'         || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                       XF_CALCULO.BDREFFN     = XLF_VERBASCALC.BDREFFN)'        || ASCII_CHAR(13);
    wSQL = wSQL ||'       LEFT JOIN VRH_BASE_TVERBAS XLF_CADVERB      ON (XLF_VERBASCALC.BDCODVER = XLF_CADVERB.BDCODVER)'         || ASCII_CHAR(13);
    wSQL = wSQL ||'       LEFT JOIN VW_VERBAS_REF_ATUAL XLF_DESCVERB  ON (XLF_CADVERB.BDCODVER    = XLF_DESCVERB.BDCODVER)'        || ASCII_CHAR(13);

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    /*Filtro por empresa*/
    IF (NOT prCODEmp IS NULL AND prCODEmp <> 0) THEN
        BEGIN
            wWhere = wWhere || 'XF_CALCULO.BDCODEMP = ' || prCODEmp;
        END
    ELSE
        BEGIN
            IF (TRIM(prCODEmpMult) <> '') THEN
                BEGIN
                    IF (wWhere <> '') THEN
                        wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

                    wWhere = wWhere || 'XF_CALCULO.BDCODEMP in (' || prCODEmpMult || ')';
                END
        END

    /*Filtro por Contrato*/
    IF (NOT prCODContrato IS NULL AND prCODContrato <> 0) THEN
        BEGIN
            IF (wWhere <> '') THEN
                wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

            wWhere = wWhere || 'XF_CALCULO.BDCODCONTTI = '||prCODContrato;
        END

    /*Filtro por Colaborador*/
    IF (NOT prCODCol IS NULL AND prCODCol <> 0) THEN
        BEGIN
            IF (wWhere <> '') THEN
                wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

             wWhere = wWhere || 'XF_CALCULO.BDCODCOL = ' || prCODCol;
        END
    ELSE
        BEGIN
            IF (TRIM(prCODColMult) <> '') THEN
                BEGIN
                    IF (wWhere <> '') THEN
                        wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

                    wWhere = wWhere || 'XF_CALCULO.BDCODCOL in (' || prCODColMult || ')';
                END
        END

    /*Filtro por Data*/
    IF (prdatainicial is not null and prdatafinal is not null) THEN
        BEGIN
          IF (wWhere <> '') THEN
             wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

             wWhere = wWhere || 'XF_CALCULO.BDREFFN between ' || SUBSTRING(CAST(prdatainicial as VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatainicial as VARCHAR(10)) FROM 6 FOR 2)||
                      ' and '||SUBSTRING(CAST(prdatafinal as VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatafinal as VARCHAR(10)) FROM 6 FOR 2);
        END

    /*Filtro por Pagamento*/
    IF (prdatapgtoinicial is not null and prdatapgtofinal is not null) THEN
        BEGIN
          IF (wWhere <> '') THEN
             wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

             wWhere = wWhere || 'XF_CALCULO.BDDATAPAGFC between '''||prdatapgtoinicial||''' '||
                      ' and '''||prdatapgtofinal||''' ';
        END

    /* Filtro verbas demonstrativas */
    IF (coalesce(prverbasdem, 0) = 0) then
        BEGIN
          IF (wWhere <> '') THEN
             wWhere = wWhere || ' AND ' || ASCII_CHAR(13);

             wWhere = wWhere || 'COALESCE(XLF_DESCVERB.BDTIPOCODVER, 0) in (0,1)';
        END

    IF (wWhere <> '') THEN
        BEGIN
            wWhere = ' WHERE ' || ASCII_CHAR(13) || wWhere;
        END

    wSQL = wSQL || wWhere || ASCII_CHAR(13);

    wSQL = wSQL || ') F_CALC ' || ASCII_CHAR(13);
    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------

    wSQL = wSQL ||'JOIN VW_TEMPRESAS_REF       J_EMPPRESA     ON (F_CALC.BDCODEMP         = J_EMPPRESA.BDCODEMP) '              || ASCII_CHAR(13);
    wSQL = wSQL ||'JOIN TEMPRESAS              J_TEMP         ON (F_CALC.BDCODEMP         = J_TEMP.BDCODEMP) '                  || ASCII_CHAR(13);
    wSQL = wSQL ||'JOIN VRH_EMP_TINTERMITENTE  J_CONTRATO_INT ON (F_CALC.BDCODEMP         = J_CONTRATO_INT.BDCODEMP AND '       || ASCII_CHAR(13);
    wSQL = wSQL ||                                               'F_CALC.BDCODCOL         = J_CONTRATO_INT.BDCODCOL AND '       || ASCII_CHAR(13);
    wSQL = wSQL ||                                               'F_CALC.BDCODCONTTI      = J_CONTRATO_INT.BDCODCONTTI) '       || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN TCIDADE                LF_CIDADE      ON (J_EMPPRESA.BDCODCID     = LF_CIDADE.BDCODCID) '    || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD    LF_COLCAD      ON (F_CALC.BDCODEMP         = LF_COLCAD.BDCODEMP AND'  || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = LF_COLCAD.BDCODCOL) '    || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC    LF_COLDOC1     ON (F_CALC.BDCODEMP         = LF_COLDOC1.BDCODEMP AND' || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC1.BDCODCOL) '   || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF LF_COLDOC2     ON (F_CALC.BDCODEMP         = LF_COLDOC2.BDCODEMP AND' || ASCII_CHAR(13);
    wSQL = wSQL ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC2.BDCODCOL) '   || ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VRH_EMP_TRESCISAO RESC                ON (RESC.BDCODEMP = F_CALC.BDCODEMP and RESC.BDCODCOL = F_CALC.BDCODCOL) '|| ASCII_CHAR(13);
    wSQL = wSQL ||'LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CALCDIA COL_CALCDIA ON (F_CALC.BDCODEMP = COL_CALCDIA.BDCODEMP AND'              || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'                                                           F_CALC.BDCODCOL = COL_CALCDIA.BDCODCOL) '                || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'LEFT OUTER JOIN VW_VRH_EMP_TCOL_VINCDIA COL_VINCDIA    ON (F_CALC.BDCODEMP = COL_VINCDIA.BDCODEMP AND'              || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'                                                           F_CALC.BDCODCOL = COL_VINCDIA.BDCODCOL) '                || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'LEFT OUTER JOIN VRH_FUNCOES_TFUC FUC ON (COL_VINCDIA.BDCODPLAFUC = FUC.BDCODPLAFUC AND'                             || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL = wSQL ||'                                         COL_VINCDIA.BDCODTFUC = FUC.BDCODTFUC) '                                   || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    wSQL = wSQL||'where ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO is not null and upper(coalesce(J_CONTRATO_INT.BDCONVRESCTI, ''FALSE'')) = ''FALSE'')) ';

    IF (prdatainicial is not null and prdatafinal is not null) THEN
      begin
        wSQL = wSQL||' and ((J_CONTRATO_INT.BDDATAINISERVTI  BETWEEN ''' || prDataInicial || ''' AND ' || '''' || prDataFinal || ''') ';
        wSQL = wSQL||' or (J_CONTRATO_INT.BDDATAFIMSERVTI  BETWEEN ''' || prDataInicial || ''' AND ' || '''' || prDataFinal || ''')) ';
      end

    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------
    /**************************************************************************/
    /*                                                                        */
    /*                                 ^                                      */
    /*                                /|\                                     */
    /*                               /   \                                    */
    /*                              /_____\                                   */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                       Final da montagem do SQL                         */
    /**************************************************************************/

    --<Local aonde deve ser zerado as variáveis>--
    wSQL2   = ' ';
    wWhere2 = ' ';

    /**************************************************************************/
    /*                      Início da montagem do SQL                         */
    /*                                  |                                     */
    /*                                  |                                     */
    /*                               ___|___                                  */
    /*                               \     /                                  */
    /*                                \   /                                   */
    /*                                 \ /                                    */
    /*                                  v                                     */
    /*                                                                        */
    /**************************************************************************/

    --<Colaborador>--
    wSQL2 = wSQL2 ||' SELECT '                                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDCODEMP,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDNOMEMP,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_TEMP.BDCNPJEMP,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDLOGREMP,'                 || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDENDEMP,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDNUMEMP,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_EMPPRESA.BDCODCID,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_CIDADE.BDNOMCID,'                   || ASCII_CHAR(13);
    --<Colaborador>--                                         
    wSQL2 = wSQL2 ||'    LF_COLCAD.BDNOMCOL,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_COLDOC1.BDCPFCOL,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_COLDOC2.BDPISCOL,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_COLDOC2.BDRGCOL,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    LF_COLDOC2.BDCTPSCOL,'                 || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'    LF_COLDOC2.BDSERIECTPSCOL,'            || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'    LF_COLDOC2.BDDSERIECTPSCOL,'           || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'    FUC.BDCODCBO,'                         || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'    FUC.BDDESCTFUC,'                       || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'    COL_CALCDIA.BDSALBASECOL,'             || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    --<Contrato>--
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDCODCONTTI,'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDESCCONTRATOTI,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATACONVTI,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDHORACONVTI,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATAINISERVTI,'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    J_CONTRATO_INT.BDDATAFIMSERVTI,'       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDDATAPAGFC,'                   || ASCII_CHAR(13);
    --<Cálculo>--
    wSQL2 = wSQL2 ||'    F_CALC.BDLIQUIDO,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDBINSSFN,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDDATAPAGFC,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDFGTSFN,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDFGTS13FN,'                    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDCODCOL,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDCODVER,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDREFFN,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    case '                                 || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'      when F_CALC.BDCLAVER starting with ''9'' then F_CALC.BDREFVFNMAX ' || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    else F_CALC.BDREFVFNSUM '              || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    end BDREFVFN, '                        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDREFAUXVFN,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDVALVFN,'                      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDVALIFN,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDDESCVER,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDTIPOCODVER,'                  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDORDEMVER,'                    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDORDEMTIPOCODVER,'             || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'    F_CALC.BDCLAVER'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||' FROM (SELECT'                                             || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'        XF_CALCULO.BDCODCONTTI,'                            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'SUM(XF_CALCULO.BDLIQUIDO) AS BDLIQUIDO,'                   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XF_CALCULO.BDBINSSFC) AS BDBINSSFN,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XF_CALCULO.BDDATAPAGFC,'                        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XF_CALCULO.BDFGTSFC) AS BDFGTSFN,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XF_CALCULO.BDFGTS13FC) AS BDFGTS13FN,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODEMP,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODCOL,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODVER,'                       || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDDESCVER,'                         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDORDEMVER,'                        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDCLAVER,'                          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_DESCVERB.BDTIPOCODVER,'                     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_DESCVERB.BDORDEMTIPOCODVER,'                || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDREFTOMADOR AS BDREFFN,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           sum(XLF_VERBASCALC.BDREFVFC) as BDREFVFNSUM,'   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           max(XLF_VERBASCALC.BDREFVFC) as BDREFVFNMAX,'   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           sum(XLF_VERBASCALC.BDREFAUXVFC) AS BDREFAUXVFN,'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XLF_VERBASCALC.BDVALVFC) AS BDVALVFN,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           SUM(XLF_VERBASCALC.BDVALVIFC) AS BDVALIFN'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       FROM VRHF_EMP_TFOLTOMCOMPINT XF_CALCULO'            || ASCII_CHAR(13);

    if (prcodemp is null and prcodempmult is null) then
       wSQL2 = wSQL2 ||      ' JOIN TMP_EMPRESAS_SELECT EMPSELECT on (EMPSELECT.BDCODEMP = XF_CALCULO.BDCODEMP) ';

    wSQL2 = wSQL2 ||'       LEFT JOIN VRHF_EMP_TVERBAFCTOMINT XLF_VERBASCALC ON (XF_CALCULO.BDCODEMP     = XLF_VERBASCALC.BDCODEMP AND'   || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDCODCOL     = XLF_VERBASCALC.BDCODCOL AND'     || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDCODCONTTI  = XLF_VERBASCALC.BDCODCONTTI AND'  || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDREFTOMADOR = XLF_VERBASCALC.BDREFTOMADOR AND' || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDREFFC = XLF_VERBASCALC.BDREFFC AND'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          XF_CALCULO.BDORDEM      = XLF_VERBASCALC.BDORDEM)'         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       LEFT JOIN VRH_BASE_TVERBAS XLF_CADVERB         ON (XLF_VERBASCALC.BDCODVER = XLF_CADVERB.BDCODVER)'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'       LEFT JOIN VW_VERBAS_REF_ATUAL XLF_DESCVERB     ON (XLF_CADVERB.BDCODVER    = XLF_DESCVERB.BDCODVER)'          || ASCII_CHAR(13);

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    /*Filtro por empresa*/
    IF (NOT prCODEmp IS NULL AND prCODEmp <> 0) THEN
        BEGIN
            wWhere2 = wWhere2 || 'XF_CALCULO.BDCODEMP = ' || prCODEmp;
        END
    ELSE
        BEGIN
            IF (TRIM(prCODEmpMult) <> '') THEN
                BEGIN
                    IF (wWhere2 <> '') THEN
                        wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);

                    wWhere2 = wWhere2 || 'XF_CALCULO.BDCODEMP in (' || prCODEmpMult || ')';
                END
        END

    /*Filtro por Contrato*/
    IF (NOT prCODContrato IS NULL AND prCODContrato <> 0) THEN
        BEGIN
            IF (wWhere2 <> '') THEN
                wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);

            wWhere2 = wWhere2 || 'XF_CALCULO.BDCODCONTTI = '||prCODContrato;
        END

    /*Filtro por Colaborador*/
    IF (NOT prCODCol IS NULL AND prCODCol <> 0) THEN
        BEGIN
            IF (wWhere2 <> '') THEN
                wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);

             wWhere2 = wWhere2 || 'XF_CALCULO.BDCODCOL = ' || prCODCol;
        END
    ELSE
        BEGIN
            IF (TRIM(prCodColMult) <> '') THEN
                BEGIN
                    IF (wWhere2 <> '') THEN
                        wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);

                    wWhere2 = wWhere2 || 'XF_CALCULO.BDCODCOL in (' || prCODColMult || ')';
                END
        END

    /*Filtro por Data*/
    IF (prdatainicial is not null and prdatafinal is not null) THEN
        BEGIN
            IF (wWhere2 <> '') THEN
                wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);

             wWhere2 = wWhere2 || 'XF_CALCULO.BDREFTOMADOR between ' || SUBSTRING(CAST(prdatainicial as VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatainicial as VARCHAR(10)) FROM 6 FOR 2)||
                      ' and '||SUBSTRING(CAST(prdatafinal as VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(prdatafinal as VARCHAR(10)) FROM 6 FOR 2);
        END


    /*Filtro por Pagamento*/
    IF (prdatapgtoinicial is not null and prdatapgtofinal is not null) THEN
        BEGIN
            IF (wWhere2 <> '') THEN
                wWhere2 = wWhere2 || ' AND ' || ASCII_CHAR(13);

             wWhere2 = wWhere2 || 'XF_CALCULO.BDDATAPAGFC between '''||prdatapgtoinicial||''' '|| -- 27813 - Raphael Teodoro - 14/02/2020 - "BDREFFC" por "BDDATAPAGFC"
                      ' and '''||prdatapgtofinal||''' ';
        END

    /* Filtro verbas demonstrativas */
    if (coalesce(prverbasdem, 0) = 0) then
        BEGIN
          IF (wWhere <> '') THEN
             wWhere = wWhere || ' AND ' || ASCII_CHAR(13);
             wWhere = wWhere || 'COALESCE(XLF_DESCVERB.BDTIPOCODVER, 0) in (0,1)';
        END

    IF (wWhere2 <> '') THEN
        BEGIN
            wWhere2 = ' WHERE ' || ASCII_CHAR(13) || wWhere2;
        END

    wSQL2 = wSQL2 || wWhere2 || ASCII_CHAR(13);

    wSQL2 = wSQL2 ||'       GROUP BY'                            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XF_CALCULO.BDCODCONTTI,'         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XF_CALCULO.BDDATAPAGFC,'         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODEMP,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODCOL,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDCODVER,'        || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDDESCVER,'          || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDORDEMVER,'         || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_DESCVERB.BDTIPOCODVER,'      || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_CADVERB.BDCLAVER,'            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_DESCVERB.BDORDEMTIPOCODVER,' || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           XLF_VERBASCALC.BDREFTOMADOR'    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||') F_CALC'                                   || ASCII_CHAR(13);

    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------

    wSQL2 = wSQL2 ||'           JOIN VW_TEMPRESAS_REF       J_EMPPRESA     ON (F_CALC.BDCODEMP         = J_EMPPRESA.BDCODEMP)'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           JOIN TEMPRESAS              J_TEMP         ON (F_CALC.BDCODEMP         = J_TEMP.BDCODEMP)'               || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'           JOIN VRH_EMP_TINTERMITENTE  J_CONTRATO_INT ON (F_CALC.BDCODEMP         = J_CONTRATO_INT.BDCODEMP     AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = J_CONTRATO_INT.BDCODCOL     AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCONTTI      = J_CONTRATO_INT.BDCODCONTTI)'    || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN TCIDADE                LF_CIDADE      ON (J_EMPPRESA.BDCODCID     = LF_CIDADE.BDCODCID)'            || ASCII_CHAR(13);
--    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VW_TCOLCON_REF_ATUAL   LF_REFCOL      ON (J_CONTRATO_INT.BDCODEMP = LF_REFCOL.BDCODEMP          AND'|| ASCII_CHAR(13);
--    wSQL2 = wSQL2 ||'                                                          J_CONTRATO_INT.BDCODCOL = LF_REFCOL.BDCODCOL)'            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD    LF_COLCAD      ON (F_CALC.BDCODEMP         = LF_COLCAD.BDCODEMP          AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = LF_COLCAD.BDCODCOL)'            || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VRH_EMP_TCOLCON_DOC    LF_COLDOC1     ON (F_CALC.BDCODEMP         = LF_COLDOC1.BDCODEMP         AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC1.BDCODCOL)'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_DOCREF LF_COLDOC2     ON (F_CALC.BDCODEMP         = LF_COLDOC2.BDCODEMP         AND'|| ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'                                                          F_CALC.BDCODCOL         = LF_COLDOC2.BDCODCOL)'           || ASCII_CHAR(13);
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CALCDIA COL_CALCDIA ON (F_CALC.BDCODEMP = COL_CALCDIA.BDCODEMP AND'              || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'                                                           F_CALC.BDCODCOL = COL_CALCDIA.BDCODCOL) '                || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VW_VRH_EMP_TCOL_VINCDIA COL_VINCDIA    ON (F_CALC.BDCODEMP = COL_VINCDIA.BDCODEMP AND'              || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'                                                           F_CALC.BDCODCOL = COL_VINCDIA.BDCODCOL) '                || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'LEFT OUTER JOIN VRH_FUNCOES_TFUC FUC ON (COL_VINCDIA.BDCODPLAFUC = FUC.BDCODPLAFUC AND'                             || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021
    wSQL2 = wSQL2 ||'                                         COL_VINCDIA.BDCODTFUC = FUC.BDCODTFUC) '                                   || ASCII_CHAR(13);  -- 152278 Leonardo Schwab 13/07/2021

    ------------------------<INICIO_WHERE_TABELA_AUX>---------------------------
    wWhere2 = ' ';
    if ((prDataInicial is not null) AND ( prDataFinal is not null)) THEN
        BEGIN
            wWhere2 = ' WHERE ((J_CONTRATO_INT.BDDATAINISERVTI  BETWEEN ''' || prDataInicial || ''' AND ' || '''' || prDataFinal || ''') ';
            wWhere2 = wWhere2||' or (J_CONTRATO_INT.BDDATAFIMSERVTI  BETWEEN ''' || prDataInicial || ''' AND ' || '''' || prDataFinal || ''')) ';
        END

    wSQL2 = wSQL2 || wWhere2 || ASCII_CHAR(13);

    ------------------------<FINAL_WHERE_TABELA_AUX>---------------------------
    /**************************************************************************/
    /*                                                                        */
    /*                                 ^                                      */
    /*                                /|\                                     */
    /*                               /   \                                    */
    /*                              /_____\                                   */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                                 |                                      */
    /*                       Final da montagem do SQL                         */
    /**************************************************************************/
    
    wSQL = wSQL    || ASCII_CHAR(13) ||
           'UNION' || ASCII_CHAR(13) ||
           wSQL2;

    /*Seta a competência para o banco*/
    EXECUTE PROCEDURE SP_SETA_COMPETENCIA(EXTRACT(YEAR FROM prdatafinal) * 100 + EXTRACT(MONTH FROM prdatafinal)); -- 27813 - Raphael Teodoro - 14/02/2020 - Substituido CAST por EXTRACT

    FOR EXECUTE STATEMENT wsql
      INTO
        :BDCODEMP,
        :BDNOMEMP,
        :BDCNPJEMP,
        :BDLOGREMP,
        :BDENDEMP,
        :BDNUMEMP,
        :BDCODCID,
        :BDNOMCID,
        :BDNOMCOL,
        :BDCPFCOL,
        :BDPISCOL,
        :BDRGCOL,
        :BDCTPSCOL,        -- 152278 Leonardo Schwab 13/07/2021
        :BDSERIECTPSCOL,   -- 152278 Leonardo Schwab 13/07/2021
        :BDDSERIECTPSCOL,  -- 152278 Leonardo Schwab 13/07/2021
        :BDCODCBO,         -- 152278 Leonardo Schwab 13/07/2021
        :BDDESCTFUC,       -- 152278 Leonardo Schwab 13/07/2021
        :BDSALBASECOL,     -- 152278 Leonardo Schwab 13/07/2021
        :BDCODCONTTI,
        :BDDESCCONTRATOTI,
        :BDDATACONVTI,
        :BDHORACONVTI,
        :BDDATAINISERVTI,
        :BDDATAFIMSERVTI,
        :BDDATAPAGTI,
        :BDLIQUIDO,
        :BDBINSSFN,
        :BDDATAPGTOFN,
        :BDFGTSFN,
        :BDFGTS13FN,
        :BDCODCOL,
        :BDCODVER,
        :BDREFFN,
        :BDREFVFN,
        :BDREFAUXVFN,
        :BDVALVFN,
        :BDVALIFN,
        :BDDESCVER,
        :BDTIPOCODVER,
        :BDORDEMVER,
        :BDORDEMTIPOCODVER,
        :BDCLAVER
    DO
        SUSPEND;
end^


CREATE OR ALTER trigger TRG_INS_E115_TEMP for TMP_VEF_EMP_TAJUICMSE115_TEMP
active before insert position 0
AS
declare variable wcodigo INTEGER;
BEGIN

  IF ((NEW.BDORDEME115 IS NULL) OR (NEW.BDORDEME115 = 0)) THEN
    BEGIN
      SELECT MAX(A.BDORDEME115)+1 FROM TMP_VEF_EMP_TAJUICMSE115_TEMP A WHERE A.BDCODEMP = NEW.BDCODEMP INTO WCODIGO;
      NEW.BDORDEME115 = WCODIGO;
    END
  ELSE
    BEGIN
      SELECT A.BDORDEME115 FROM TMP_VEF_EMP_TAJUICMSE115_TEMP A WHERE A.BDCODEMP = NEW.BDCODEMP AND A.BDORDEME115 = NEW.BDORDEME115 AND A.BDSESSAO = NEW.BDSESSAO INTO WCODIGO;

      if (WCODIGO > 0) then
         BEGIN
          SELECT MAX(A.BDORDEME115)+1 FROM TMP_VEF_EMP_TAJUICMSE115_TEMP A WHERE A.BDCODEMP = NEW.BDCODEMP AND A.BDSESSAO = NEW.BDSESSAO INTO WCODIGO;
          NEW.BDORDEME115 = WCODIGO;
         END
    END
END
^

/* Restore proc. body: SP_GET_EVT_FILA_ESOCIAL */
CREATE OR ALTER procedure SP_GET_EVT_FILA_ESOCIAL (
    PRCODEMP integer,
    PREXCLUSAO integer)
returns (
    BDCODIGO integer,
    BDCODEMP integer,
    BDCHAVE varchar(60),
    BDXML blob sub_type 0 segment size 80,
    BDCODTIPO integer,
    BDSTATUS integer,
    BDDATAEVENTO date,
    BDMOTIVO varchar(100),
    BDGRUPO integer,
    BDDATAININAOPERIOD date,
    BDDATAINITABELA date,
    BDDATAINIPERIOD date,
    BDDATAINISST date,
    BDCODEMPMATRIZ integer,
    BDDATAGERADO date,
    BDHORAGERADO time,
    BDTENTATIVA integer,
    BDCODCOL integer,
    BDIDEVENTO varchar(100),
    BDCPFCOL varchar(14),
    BDEVENTOEXCLUSAO integer,
    BDCPFCOLEXCLUIDO varchar(14),
    BDORDEM_MAIOR_PRIORI_ENVIO integer,
    BDCONTRORDEMENVIOEVTS2500 integer)
as
declare variable WEMPRESA_ATUAL integer;
declare variable WCODTIPO integer;
declare variable WGRUPO integer;
declare variable WIGNORAFECHAMENTO integer;
declare variable WAPENASRT varchar(5);
begin
  if (:PRCODEMP = 0) then
  begin
    delete from TMP_EMPRESAS_SELECT;

    insert into TMP_EMPRESAS_SELECT
    select coalesce(E.BDCODMATRIZ,E.BDCODEMP) bdcodempgrupo
           from TEMPRESAS E
               left outer join TEMPRESAS matriz on (e.bdcodmatriz = matriz.bdcodemp)
           inner join (select bdcodemp from VRH_ESOCIAL_TTOTSTATUS group by bdcodemp) esa on esa.bdcodemp = e.bdcodemp
               where  ((E.BDCODMATRIZ = esa.bdcodemp) or
                      ((e.bdcodmatriz is null) and (e.bdcodemp=esa.bdcodemp)) or
                      ((e.bdcodmatriz is not null) and (matriz.BDSITUACAOESOCIAL = 0) and (e.bdcodemp=esa.bdcodemp))
                      ) and (e.BDSITUACAOESOCIAL <> 0)
    group by bdcodempgrupo;
/*    select coalesce(E.BDCODMATRIZ,E.BDCODEMP)
           from TEMPRESAS E
           inner join (select bdcodemp from VRH_ESOCIAL_TTOTSTATUS group by bdcodemp) esa on esa.bdcodemp = e.bdcodemp
           where (E.BDCODMATRIZ = esa.bdcodemp) or ((e.bdcodmatriz is null) and (e.bdcodemp=esa.bdcodemp)) and (e.BDSITUACAOESOCIAL <> 0);*/
  end
  else
  begin
    insert into TMP_EMPRESAS_SELECT (BDCODEMP)
    values (:PRCODEMP);
  end

  if (PREXCLUSAO = -1) then
  begin
    WCODTIPO = 0;
    WGRUPO = 0;
    WEMPRESA_ATUAL = 0;
    for  select ESOC.BDESOCIALRT, ESOC.BDCODIGO, ESOC.BDCODEMP, ESOC.BDCHAVE, ESOC.BDXML, ESOC.BDCODTIPO, ESOC.BDSTATUS, ESOC.BDDATAEVENTO,
                   ESOC.BDMOTIVO, ESOC.BDGRUPO, ESOC.BDDATAININAOPERIOD, ESOC.BDDATAINITABELA, ESOC.BDDATAINIPERIOD,
                   ESOC.BDDATAINISST, ESOC.BDCODMATRIZ, ESOC.BDDATAGERADO, ESOC.BDHORAGERADO, ESOC.BDTENTATIVA, ESOC.BDCODCOL,
                   ESOC.BDIDEVENTO, ESOC.BDCPFCOL, ESOC.BDEVENTOEXCLUSAO, ESOC.BDCPFCOL BDCPFCOLEXCLUIDO, BDORDEM_MAIOR_PRIORI_ENVIO
            from (select FAS.BDESOCIALRT, EVT.BDCODIGO, EVT.BDCODEMP, EVT.BDCHAVE, EVT.BDXML, EVT.BDCODTIPO, EVT.BDSTATUS, EVT.BDDATAEVENTO,
                         EVT.BDMOTIVO, TP.BDGRUPO, FAS.BDDATAININAOPERIOD, FAS.BDDATAINITABELA, FAS.BDDATAINIPERIOD,
                         FAS.BDDATAINISST, MAT.BDCODEMP BDCODMATRIZ, COL.BDCPFCOL, EVT.BDREFARQ, EVT.BDCODCOL, EVT.BDDATAGERADO,
                         EVT.BDHORAGERADO, EVT.BDTENTATIVA, EVT.BDIDEVENTO, EVT.BDEVENTOEXCLUSAO , EVT.BDORDEM_MAIOR_PRIORI_ENVIO,
                         (select first 1 EMAIL.BDCPFCOL from VRH_EMP_TCOL_EMAIL EMAIL where EMAIL.BDCODEMP = EVT.BDCODEMP and EMAIL.BDCODCOL = EVT.BDCODCOL order by EMAIL.bdcodigo DESC) BDCPFCOLEXCLUIDO
                  from (select EVT1.BDCODIGO, EVT1.BDCODEMP, EVT1.BDCHAVE, EVT1XML.BDXML, EVT1.BDCODTIPO, EVT1.BDSTATUS,
                               EVT1.BDDATAEVENTO, EVT1.BDMOTIVO, EVT1.BDREFARQ, EVT1.BDCODCOL, EVT1.BDDATAGERADO, EVT1.BDHORAGERADO,
                               EVT1.BDTENTATIVA, EVT1.BDIDEVENTO, EVT1.BDEVENTOEXCLUSAO, EVT1.BDORDEM_MAIOR_PRIORI_ENVIO
    
                        from VRH_ESOCIAL_TARQUIVO EVT1
                        inner join VRH_ESOCIAL_TARQUIVO_XML EVT1XML ON (EVT1XML.BDCODIGO = EVT1.BDCODIGO) AND (EVT1XML.BDCODEMP = EVT1.BDCODEMP)
                        inner join(select E.BDCODEMP
                                   from TEMPRESAS E
                                   inner join TMP_EMPRESAS_SELECT ESOC on (ESOC.BDCODEMP = E.BDCODEMP) or (ESOC.BDCODEMP = E.BDCODMATRIZ)) EMP on EVT1.BDCODEMP = EMP.BDCODEMP
    
                        where (EVT1.BDORDEM_MAIOR_PRIORI_ENVIO = -1)) EVT
                  inner join(select EMP_I.*
                             from TEMPRESAS EMP_I
                             inner join TMP_EMPRESAS_SELECT ESA on (ESA.BDCODEMP = EMP_I.BDCODEMP) or ((ESA.BDCODEMP = EMP_I.BDCODMATRIZ) and (coalesce(EMP_I.BDSITUACAOESOCIAL, 0) = 1))) EMP on EMP.BDCODEMP = EVT.BDCODEMP
                  inner join VRH_ESOCIAL_TTIPO_ARQ TP on TP.BDCODTIPO = EVT.BDCODTIPO
                  left outer join TEMPRESAS MAT on ((EMP.BDCODMATRIZ = MAT.BDCODEMP) or (MAT.BDCODEMP = (select first 1 BDCODEMP from TEMPRESAS_SCP where BDCODEMPSCP = EMP.BDCODEMP)))
                  left outer join VRH_ESOCIAL_TFASEAMENTO FAS on FAS.BDCODEMP = EMP.BDCODEMP
                  left outer join VRH_EMP_TCOLCON COL on COL.BDCODEMP = EVT.BDCODEMP and COL.BDCODCOL = EVT.BDCODCOL
                  where (BDORDEM_MAIOR_PRIORI_ENVIO = -1) and BDSTATUS = 0) ESOC

    into :WAPENASRT, :BDCODIGO, :BDCODEMP, :BDCHAVE, :BDXML, :BDCODTIPO, :BDSTATUS, :BDDATAEVENTO, :BDMOTIVO, :BDGRUPO,
             :BDDATAININAOPERIOD, :BDDATAINITABELA, :BDDATAINIPERIOD, :BDDATAINISST, :BDCODEMPMATRIZ, :BDDATAGERADO, :BDHORAGERADO,
             :BDTENTATIVA, :BDCODCOL, :BDIDEVENTO, :BDCPFCOL, :BDEVENTOEXCLUSAO, :BDCPFCOLEXCLUIDO, :BDORDEM_MAIOR_PRIORI_ENVIO
    do
    begin
      if (bdcodtipo not in (49,50,51)) then
         begin
           if (coalesce(upper(wapenasrt),'FALSE') = 'TRUE') then
              continue;
         end

      if ((WEMPRESA_ATUAL = 0) or (WEMPRESA_ATUAL <> BDCODEMP)) then
      begin
        WEMPRESA_ATUAL = BDCODEMP;
        WCODTIPO = 0;
        WGRUPO = 0;
      end

      if ((WCODTIPO = 0) and
          (WGRUPO = 0)) then
      begin
        if (BDGRUPO in (1, 3)) then
          WCODTIPO = BDCODTIPO;
        else
          WGRUPO = BDGRUPO;
      end

      if (((BDGRUPO in (1, 3)) and
          (WCODTIPO = BDCODTIPO)) or ((BDGRUPO = 2) and
          (WGRUPO = BDGRUPO))) then
         begin
           suspend;
         end
    end
  end
  else
  if (PREXCLUSAO = 0) then
  begin
    WCODTIPO = 0;
    WGRUPO = 0;
    WEMPRESA_ATUAL = 0;
    for select ESOC.BDESOCIALRT, ESOC.BDCODIGO, ESOC.BDCODEMP, ESOC.BDCHAVE, ESOC.BDXML, ESOC.BDCODTIPO, ESOC.BDSTATUS, ESOC.BDDATAEVENTO,
               ESOC.BDMOTIVO, ESOC.BDGRUPO, ESOC.BDDATAININAOPERIOD, ESOC.BDDATAINITABELA, ESOC.BDDATAINIPERIOD,
               ESOC.BDDATAINISST, ESOC.BDCODMATRIZ, ESOC.BDDATAGERADO, ESOC.BDHORAGERADO, ESOC.BDTENTATIVA, ESOC.BDCODCOL,
               ESOC.BDIDEVENTO, ESOC.BDCPFCOL, ESOC.BDEVENTOEXCLUSAO, ESOC.BDCPFCOL BDCPFCOLEXCLUIDO, ESOC.BDCONTRORDEMENVIOEVTS2500
        from (select FAS.BDESOCIALRT, EVT.BDCODIGO, EVT.BDCODEMP, EVT.BDCHAVE, EVT.BDXML, EVT.BDCODTIPO, EVT.BDSTATUS, EVT.BDDATAEVENTO,
                     EVT.BDMOTIVO, TP.BDGRUPO, FAS.BDDATAININAOPERIOD, FAS.BDDATAINITABELA, FAS.BDDATAINIPERIOD,
                     FAS.BDDATAINISST, MAT.BDCODEMP BDCODMATRIZ, COL.BDCPFCOL, EVT.BDREFARQ, EVT.BDCODCOL, EVT.BDDATAGERADO,
                     EVT.BDHORAGERADO, EVT.BDTENTATIVA, EVT.BDIDEVENTO, EVT.BDEVENTOEXCLUSAO, BDCONTRORDEMENVIOEVTS2500, EVT.BDORIGEM, --EMAIL.BDCPFCOL BDCPFCOLEXCLUIDO
                     (select first 1 EMAIL.BDCPFCOL from VRH_EMP_TCOL_EMAIL EMAIL where EMAIL.BDCODEMP = EVT.BDCODEMP and EMAIL.BDCODCOL = EVT.BDCODCOL order by EMAIL.bdcodigo DESC) BDCPFCOLEXCLUIDO  -- 170422 Leonardo Schwab 10/11/2022 
                     -- Se adicionar campos na tabela "VRH_ESOCIAL_TARQUIVO", no futuro o "*" causará erro
                     --      from (select EVT1.*
              from (select EVT1.BDCODIGO, EVT1.BDCODEMP, EVT1.BDCHAVE, EVT1XML.BDXML, EVT1.BDCODTIPO, EVT1.BDSTATUS,
                           EVT1.BDDATAEVENTO, EVT1.BDMOTIVO, EVT1.BDREFARQ, EVT1.BDCODCOL, EVT1.BDDATAGERADO, EVT1.BDHORAGERADO,
                           EVT1.BDTENTATIVA, EVT1.BDIDEVENTO, EVT1.BDEVENTOEXCLUSAO, EVT1.BDCONTRORDEMENVIOEVTS2500, EVT1.BDORIGEM

                    from VRH_ESOCIAL_TARQUIVO EVT1
                    inner join VRH_ESOCIAL_TARQUIVO_XML EVT1XML ON (EVT1XML.BDCODIGO = EVT1.BDCODIGO) AND (EVT1XML.BDCODEMP = EVT1.BDCODEMP)
                    inner join(select E.BDCODEMP
                               from TEMPRESAS E
                               inner join TMP_EMPRESAS_SELECT ESOC on (ESOC.BDCODEMP = E.BDCODEMP) or (ESOC.BDCODEMP = E.BDCODMATRIZ)) EMP on EVT1.BDCODEMP = EMP.BDCODEMP
                    where ((EVT1.BDCODTIPO <> 38) and
                          (EVT1.BDMOTIVO <> 'Exclusão')) and
                          (EVT1.BDSTATUS in (0, 3)) and
                          (EVT1.BDDATAENVIAREVT <= 'NOW')) EVT
              -- em dependências com campos obrigatórios, considere usar "INNER JOIN", dessa forma os indices serão utilizado efetivamente, além de trazer apenas os registros realmente pertinentes
              --      left outer join VRH_ESOCIAL_TTIPO_ARQ TP on TP.BDCODTIPO = EVT.BDCODTIPO
              --      left outer join TEMPRESAS EMP on EVT.BDCODEMP = EMP.BDCODEMP
              inner join(select EMP_I.*
                         from TEMPRESAS EMP_I
                         inner join TMP_EMPRESAS_SELECT ESA on (ESA.BDCODEMP = EMP_I.BDCODEMP) or ((ESA.BDCODEMP = EMP_I.BDCODMATRIZ) and (coalesce(EMP_I.BDSITUACAOESOCIAL, 0) = 1))) EMP on EMP.BDCODEMP = EVT.BDCODEMP
              inner join VRH_ESOCIAL_TTIPO_ARQ TP on TP.BDCODTIPO = EVT.BDCODTIPO
              left outer join TEMPRESAS MAT on ((EMP.BDCODMATRIZ = MAT.BDCODEMP) or (MAT.BDCODEMP = (select first 1 BDCODEMP from TEMPRESAS_SCP where BDCODEMPSCP = EMP.BDCODEMP)))
              left outer join VRH_ESOCIAL_TFASEAMENTO FAS on FAS.BDCODEMP = EMP.BDCODEMP
              left outer join VRH_EMP_TCOLCON COL on COL.BDCODEMP = EVT.BDCODEMP and COL.BDCODCOL = EVT.BDCODCOL
--              left join VRH_EMP_TCOL_EMAIL EMAIL on EMAIL.BDCODEMP = EVT.BDCODEMP and EMAIL.BDCODCOL = EVT.BDCODCOL    -- 170422 Leonardo Schwab 10/11/2022
              where ((EVT.BDCODTIPO = 1 and
                    -- first 1 com order by é mais rápido que min, além do order by usar indice
                    --            EVT.BDREFARQ = (select min(BDREFARQ)
                    EVT.BDREFARQ = (select first 1 BDREFARQ
                                    from VRH_ESOCIAL_TARQUIVO EVTREF
                                    where EVTREF.BDCODEMP in (MAT.BDCODEMP, EMP.BDCODEMP) and
                                          EVTREF.BDCODTIPO = 1 and
                                          EVTREF.BDREFARQ >= FAS.BDREFINITABELA
                                    order by EVTREF.BDCODEMP, EVTREF.BDCODTIPO, EVTREF.BDREFARQ)) or (exists(select first 1 EVT1000.BDCODEMP
                                                                   from VRH_ESOCIAL_TARQUIVO EVT1000
                                                                   where EVT1000.BDCODEMP in (MAT.BDCODEMP, EMP.BDCODEMP) and
                                                                         EVT1000.BDCODTIPO = 1 and
                                                                         EVT1000.BDSTATUS = 2))
                                     or ((EVT.BDCODTIPO in (49,50,51)) and (coalesce(FAS.BDESOCIALRT,'FALSE') = 'TRUE' ))
                                     or (coalesce(EMP.BDMATRIZNAOCADSIS, 'FALSE') = 'TRUE') or (coalesce(MAT.BDSITUACAOESOCIAL, 1) = 0))
              order by EVT.BDCODEMP, TP.BDGRUPO, TP.BDCODTIPO) ESOC

        where (((ESOC.BDGRUPO = 1) and
              ((ESOC.BDMOTIVO <> 'Alteração') or (not exists(select first 1 EVTPROC.BDCODEMP
                                                             from VRH_ESOCIAL_TARQUIVO EVTPROC
                                                             where EVTPROC.BDCODEMP in (ESOC.BDCODMATRIZ, ESOC.BDCODEMP) and
                                                                   EVTPROC.BDCODTIPO = ESOC.BDCODTIPO and
                                                                   EVTPROC.BDDATAEVENTO < ESOC.BDDATAEVENTO and
                                                                   EVTPROC.BDMOTIVO <> 'Alteração' and
                                                                   EVTPROC.BDSTATUS not in (2, 3, 4, 5, 6, 7, 8)))) and
              ((ESOC.BDCODTIPO in (1, 9)) or (not exists(select first 1 EVTPROC.BDCODEMP
                                                         from VRH_ESOCIAL_TARQUIVO EVTPROC
                                                         where EVTPROC.BDCODEMP in (ESOC.BDCODMATRIZ, ESOC.BDCODEMP) and
                                                               EVTPROC.BDCODTIPO = 9 and
                                                               EVTPROC.BDMOTIVO <> 'Exclusão' and
                                                               EVTPROC.BDREFARQ <= ESOC.BDREFARQ and
                                                               EVTPROC.BDSTATUS not in (2, 3, 4, 5, 6, 7, 8))))) or (ESOC.BDGRUPO in (2, 3) and
              --Aguarda eventos de tabela
              ((ESOC.BDCODTIPO not in (11, 15, 16)) or (not exists(select first 1 EVTESTAB.BDCODEMP
                                                                   from VRH_ESOCIAL_TARQUIVO EVTESTAB
                                                                   where EVTESTAB.BDCODEMP in (ESOC.BDCODMATRIZ, ESOC.BDCODEMP) and
                                                                         EVTESTAB.BDCODTIPO = 2 and
                                                                         EVTESTAB.BDREFARQ <= ESOC.BDREFARQ and
                                                                         EVTESTAB.BDSTATUS not in (2, 3, 4, 5, 6, 7, 8)))) and
              ((ESOC.BDCODTIPO not in (11, 14, 34, 37)) or (not exists(select first 1 EVTRUB.BDCODEMP
                                                                       from VRH_ESOCIAL_TARQUIVO EVTRUB
                                                                       where EVTRUB.BDCODEMP in (ESOC.BDCODMATRIZ, ESOC.BDCODEMP) and
                                                                             EVTRUB.BDCODTIPO = 3 and
                                                                             EVTRUB.BDREFARQ <= ESOC.BDREFARQ and
                                                                             EVTRUB.BDSTATUS not in (2, 3, 4, 5, 6, 7, 8)))) and
              ((ESOC.BDCODTIPO not in (11, 34, 37)) or (not exists(select first 1 EVTLOT.BDCODEMP
                                                                   from VRH_ESOCIAL_TARQUIVO EVTLOT
                                                                   where EVTLOT.BDCODEMP in (ESOC.BDCODMATRIZ, ESOC.BDCODEMP) and
                                                                         EVTLOT.BDCODTIPO = 4 and
                                                                         EVTLOT.BDREFARQ <= ESOC.BDREFARQ and
                                                                         EVTLOT.BDSTATUS not in (2, 3, 4, 5, 6, 7, 8)))) and
              ((ESOC.BDCODTIPO not in (24, 26, 35, 36)) or (not exists(select first 1 EVTCARGO.BDCODEMP
                                                                       from VRH_ESOCIAL_TARQUIVO EVTCARGO
                                                                       where EVTCARGO.BDCODEMP in (ESOC.BDCODMATRIZ, ESOC.BDCODEMP) and
                                                                             EVTCARGO.BDCODTIPO = 5 and
                                                                             EVTCARGO.BDREFARQ <= ESOC.BDREFARQ and
                                                                             EVTCARGO.BDSTATUS not in (2, 3, 4, 5, 6, 7, 8)))) and
              ((ESOC.BDCODTIPO not in (24, 26)) or (not exists(select first 1 EVTHOR.BDCODEMP
                                                               from VRH_ESOCIAL_TARQUIVO EVTHOR
                                                               where EVTHOR.BDCODEMP in (ESOC.BDCODMATRIZ, ESOC.BDCODEMP) and
                                                                     EVTHOR.BDCODTIPO = 7 and
                                                                     EVTHOR.BDREFARQ <= ESOC.BDREFARQ and
                                                                     EVTHOR.BDSTATUS not in (2, 3, 4, 5, 6, 7, 8)))) and
              ((ESOC.BDCODTIPO not in (11, 15, 16, 33)) or (not exists(select first 1 EVTPROC.BDCODEMP
                                                                       from VRH_ESOCIAL_TARQUIVO EVTPROC
                                                                       where EVTPROC.BDCODEMP in (ESOC.BDCODMATRIZ, ESOC.BDCODEMP) and
                                                                             EVTPROC.BDCODTIPO = 9 and
                                                                             EVTPROC.BDREFARQ <= ESOC.BDREFARQ and
                                                                             EVTPROC.BDSTATUS not in (2, 3, 4, 5, 6, 7, 8)))) and
              --Aguarda evento não periódicos
              ((ESOC.BDCODTIPO not in (34)) or (not exists(select first 1 EVTPER.BDCODEMP
                                                           from VRH_ESOCIAL_TARQUIVO EVTPER
                                                           -- em dependências com campos obrigatórios, considere usar "INNER JOIN", dessa forma os indices serão utilizado efetivamente, além de trazer apenas os registros realmente pertinentes
                                                           --                                                           left outer join VRH_ESOCIAL_TTIPO_ARQ TPPER on TPPER.BDCODTIPO = EVTPER.BDCODTIPO
                                                           inner join VRH_ESOCIAL_TTIPO_ARQ TPPER on TPPER.BDCODTIPO = EVTPER.BDCODTIPO
                                                           where EVTPER.BDCODEMP = ESOC.BDCODEMP and
                                                                 EVTPER.BDCODCOL = ESOC.BDCODCOL and
                                                                 EVTPER.BDDATAEVENTO = ESOC.BDDATAEVENTO and
                                                                 TPPER.BDCODTIPO = 45 and
                                                                 EVTPER.BDSTATUS not in (2, 3, 4, 5, 6, 7, 8)))) and
              ((ESOC.BDCODTIPO not in (34, 37)) or (not exists(select first 1 EVTPER.BDCODEMP
                                                           from VRH_ESOCIAL_TARQUIVO EVTPER
                                                           -- em dependências com campos obrigatórios, considere usar "INNER JOIN", dessa forma os indices serão utilizado efetivamente, além de trazer apenas os registros realmente pertinentes
                                                           --                                                           left outer join VRH_ESOCIAL_TTIPO_ARQ TPPER on TPPER.BDCODTIPO = EVTPER.BDCODTIPO
                                                           inner join VRH_ESOCIAL_TTIPO_ARQ TPPER on TPPER.BDCODTIPO = EVTPER.BDCODTIPO
                                                           where EVTPER.BDCODEMP = ESOC.BDCODEMP and
                                                                 EVTPER.BDCODCOL = ESOC.BDCODCOL and
                                                                 EVTPER.BDDATAEVENTO <= ESOC.BDDATAEVENTO and
                                                                 TPPER.BDCODTIPO in (24, 25, 26, 29, 32, 35, 36) and
                                                                 EVTPER.BDSTATUS not in (2, 3, 4, 5, 6, 7, 8)))) and
              ((ESOC.BDCODTIPO not in (11, 14, 25, 26, 27, 28, 29, 30, 31,
                                       32, 33, 34, 36, 37, 45)) or (not exists(select first 1 EVTPER.BDCODEMP
                                                                           from VRH_ESOCIAL_TARQUIVO EVTPER
                                                                           -- em dependências com campos obrigatórios, considere usar "INNER JOIN", dessa forma os indices serão utilizado efetivamente, além de trazer apenas os registros realmente pertinentes
                                                                           --                                                                     left outer join VRH_ESOCIAL_TTIPO_ARQ TPPER on TPPER.BDCODTIPO = EVTPER.BDCODTIPO
                                                                           inner join VRH_ESOCIAL_TTIPO_ARQ TPPER on TPPER.BDCODTIPO = EVTPER.BDCODTIPO
                                                                           where EVTPER.BDCODEMP = ESOC.BDCODEMP and
                                                                                 EVTPER.BDCODCOL = ESOC.BDCODCOL and
                                                                                 EVTPER.BDREFARQ <= ESOC.BDREFARQ and
                                                                                 TPPER.BDCODTIPO in (24, 35) and
                                                                                 EVTPER.BDSTATUS not in (2, 3, 4, 5, 6, 7, 8)))) and
              ((ESOC.BDCODTIPO <> 24) or (not exists(select first 1 EVT3.BDCODEMP
                                                     from VRH_ESOCIAL_TARQUIVO EVT3
                                                     where (EVT3.BDCODEMP = ESOC.BDCODEMP) and
                                                           (EVT3.BDCODCOL = ESOC.BDCODCOL) and
                                                           (EVT3.BDCODTIPO = 23) and
                                                           (EVT3.BDSTATUS in (0, 1))))) and
              ((ESOC.BDCODTIPO <> 29) or (not exists(select first 1 EVT3.BDCODEMP
                                                     from VRH_ESOCIAL_TARQUIVO EVT3
                                                     where (EVT3.BDCODEMP = ESOC.BDCODEMP) and
                                                           (EVT3.BDCODCOL = ESOC.BDCODCOL) and
                                                           (EVT3.BDDATAEVENTO < ESOC.BDDATAEVENTO) and
                                                           (EVT3.BDCODTIPO = (29)) and
                                                           (EVT3.BDSTATUS in (0, 1, 3, 4))))) and
              --Aguarda evento não periódicos excluídos
              ((ESOC.BDCODTIPO not in (24, 35)) or (not exists(select first 1 EVTEXC.BDCODEMP
                                                               from VRH_ESOCIAL_TARQUIVO EVTEXC
                                                               inner join VRH_ESOCIAL_TARQUIVO EVT on EVTEXC.BDEVTEXCLUIDO = EVT.BDCODIGO and EVTEXC.BDCODEMP = EVT.BDCODEMP
                                                               where EVTEXC.BDCODEMP in (ESOC.BDCODMATRIZ, ESOC.BDCODEMP) and
                                                                     EVTEXC.BDCODCOL = ESOC.BDCODCOL and
                                                                     EVT.BDCODTIPO = 29 and
                                                                     EVTEXC.BDSTATUS not in (-1, 2, 3, 4, 5, 6, 7, 8)))) and
              ((ESOC.BDCODTIPO not in (29, 32, 34, 37)) or (not exists(select first 1 EVTEXC.BDCODEMP
                                                                       from VRH_ESOCIAL_TARQUIVO EVTEXC
                                                                       inner join VRH_ESOCIAL_TARQUIVO EVT on EVTEXC.BDEVTEXCLUIDO = EVT.BDCODIGO and EVTEXC.BDCODEMP = EVT.BDCODEMP
                                                                       where EVTEXC.BDCODEMP in (ESOC.BDCODMATRIZ, ESOC.BDCODEMP) and
                                                                             EVTEXC.BDCODCOL = ESOC.BDCODCOL and
                                                                             EVT.BDCODTIPO in (29, 32, 34, 37) and
                                                                             EVTEXC.BDSTATUS not in (-1, 2, 3, 4, 5, 6, 7, 8)))) and
              --Aguarda eventos periódicos
              ((ESOC.BDCODTIPO not in (20)) or (not exists(select first 1 EVTPER.BDCODEMP
                                                           from VRH_ESOCIAL_TARQUIVO EVTPER
                                                           -- em dependências com campos obrigatórios, considere usar "INNER JOIN", dessa forma os indices serão utilizado efetivamente, além de trazer apenas os registros realmente pertinentes
                                                           --                                                   left outer join TEMPRESAS EMPFEC on EMPFEC.BDCODEMP = EVTPER.BDCODEMP
                                                           --                                                   left outer join VRH_ESOCIAL_TTIPO_ARQ TPPER on TPPER.BDCODTIPO = EVTPER.BDCODTIPO
                                                           inner join TEMPRESAS EMPFEC on EMPFEC.BDCODEMP = EVTPER.BDCODEMP
                                                           inner join VRH_ESOCIAL_TTIPO_ARQ TPPER on TPPER.BDCODTIPO = EVTPER.BDCODTIPO
                                                           where (EMPFEC.BDCODEMP in (ESOC.BDCODMATRIZ, ESOC.BDCODEMP) or EMPFEC.BDCODMATRIZ in (ESOC.BDCODMATRIZ, ESOC.BDCODEMP)) and
                                                                 TPPER.BDGRUPO = 3 and
                                                                 TPPER.BDCODTIPO not in (19, 20, 44) and
                                                                 EVTPER.BDREFARQ <= ESOC.BDREFARQ and
                                                                 EVTPER.BDSTATUS not in (2, 3, 4, 5, 6, 7, 8)))) and
              ((ESOC.BDCODTIPO not in (14)) or (not exists(select first 1 EVTPER.BDCODEMP
                                                           from VRH_ESOCIAL_TARQUIVO EVTPER
                                                           -- em dependências com campos obrigatórios, considere usar "INNER JOIN", dessa forma os indices serão utilizado efetivamente, além de trazer apenas os registros realmente pertinentes
                                                           --                                                           left outer join VRH_ESOCIAL_TTIPO_ARQ TPPER on TPPER.BDCODTIPO = EVTPER.BDCODTIPO
                                                           inner join VRH_ESOCIAL_TTIPO_ARQ TPPER on TPPER.BDCODTIPO = EVTPER.BDCODTIPO
                                                           where EVTPER.BDCODEMP = ESOC.BDCODEMP and
                                                                 EVTPER.BDCODCOL = ESOC.BDCODCOL and
                                                                 EVTPER.BDREFARQ <= ESOC.BDREFARQ and
                                                                 TPPER.BDCODTIPO in (11, 34, 37) and
                                                                 EVTPER.BDSTATUS not in (2, 3, 4, 5, 6, 7, 8)))) and
              --Aguarda eventos periódicos excluídos
              ((ESOC.BDCODTIPO not in (20)) or (not exists(select first 1 EVT3.BDCODEMP
                                                           from VRH_ESOCIAL_TARQUIVO EVT3
                                                           -- em dependências com campos obrigatórios, considere usar "INNER JOIN", dessa forma os indices serão utilizado efetivamente, além de trazer apenas os registros realmente pertinentes
                                                           --                                                           left outer join VRH_ESOCIAL_TARQUIVO EVT4 on EVT3.BDEVTEXCLUIDO = EVT4.BDCODIGO and EVT3.BDCODEMP = EVT4.BDCODEMP
                                                           inner join VRH_ESOCIAL_TARQUIVO EVT4 on EVT3.BDEVTEXCLUIDO = EVT4.BDCODIGO and EVT3.BDCODEMP = EVT4.BDCODEMP
                                                           where (EVT4.BDCODEMP = ESOC.BDCODEMP) and
                                                                 (EVT4.BDREFARQ = ESOC.BDREFARQ) and
                                                                 (EVT4.BDCODTIPO in (11, 14)) and
                                                                 (EVT3.BDSTATUS in (0, 1, 3, 4))))) and
              ((ESOC.BDCODTIPO not in (11, 14, 34, 37)) or (not exists(select first 1 EVTPER.BDCODEMP
                                                                       from VRH_ESOCIAL_TARQUIVO EVTPER
                                                                       -- em dependências com campos obrigatórios, considere usar "INNER JOIN", dessa forma os indices serão utilizado efetivamente, além de trazer apenas os registros realmente pertinentes
                                                                       --                                                                       left outer join VRH_ESOCIAL_TARQUIVO EVT4 on EVTPER.BDEVTEXCLUIDO = EVT4.BDCODIGO and EVTPER.BDCODEMP = EVT4.BDCODEMP
                                                                       inner join VRH_ESOCIAL_TARQUIVO EVT4 on EVTPER.BDEVTEXCLUIDO = EVT4.BDCODIGO and EVTPER.BDCODEMP = EVT4.BDCODEMP
                                                                       where EVTPER.BDCODEMP = ESOC.BDCODEMP and
                                                                             EVTPER.BDCODCOL = ESOC.BDCODCOL and
                                                                             EVTPER.BDREFARQ <= ESOC.BDREFARQ and
                                                                             EVT4.BDCODTIPO in (11, 14, 34, 37) and
                                                                             EVTPER.BDSTATUS in (0, 1, 4)))) and
                                                                             
              --Controle de ordem de envio para o evento S-2500 (Sol.161310 - Nathan de Faria - 15-09-2023)                                                                             
              (not(((ESOC.BDCODTIPO = 49) and ((coalesce(ESOC.BDCONTRORDEMENVIOEVTS2500, 0) = -1))) and (exists(select first 1 EVTPROC.BDCODEMP
                                                                                                        from VRH_ESOCIAL_TARQUIVO EVTPROC
                                                                                                        where EVTPROC.BDCODEMP in (ESOC.BDCODMATRIZ, ESOC.BDCODEMP) and
                                                                                                              EVTPROC.BDCODTIPO = 24 and
                                                                                                              EVTPROC.BDCODCOL = ESOC.BDCODCOL and
                                                                                                              EVTPROC.BDSTATUS not in (0, 1, 3, 4))))) and
              (not(((ESOC.BDCODTIPO = 49) and ((coalesce(ESOC.BDCONTRORDEMENVIOEVTS2500, 0) = -2))) and (exists(select first 1 EVTPROC.BDCODEMP
                                                                                                        from VRH_ESOCIAL_TARQUIVO EVTPROC
                                                                                                        where EVTPROC.BDCODEMP in (ESOC.BDCODMATRIZ, ESOC.BDCODEMP) and
                                                                                                              EVTPROC.BDCODTIPO in (11, 14, 34, 37) and
                                                                                                              EVTPROC.BDCODCOL = ESOC.BDCODCOL and
                                                                                                              EVTPROC.BDSTATUS in (0, 1, 3, 4))))) and
              (not(((ESOC.BDCODTIPO = 49) and ((coalesce(ESOC.BDCONTRORDEMENVIOEVTS2500, 0) = -3))) and (exists(select first 1 EVTPROC.BDCODEMP
                                                                                                        from VRH_ESOCIAL_TARQUIVO EVTPROC
                                                                                                        where EVTPROC.BDCODEMP in (ESOC.BDCODMATRIZ, ESOC.BDCODEMP) and
                                                                                                              EVTPROC.BDCODTIPO in (11, 14, 24, 34, 37) and
                                                                                                              EVTPROC.BDCODCOL = ESOC.BDCODCOL and
                                                                                                              EVTPROC.BDSTATUS in (0, 1, 3, 4))))) and
              (not(((ESOC.BDCODTIPO = 34) and ((upper(ESOC.BDORIGEM)) = (upper('frLancamentoProcessoTrabalhista')))) and (exists(select 1 from VRH_ESOCIAL_TARQUIVO
                                                                                                                                 where BDCODEMP = ESOC.BDCODEMP and
                                                                                                                                       BDCODCOL = ESOC.BDCODCOL and
                                                                                                                                       BDREFARQ >= ESOC.BDREFARQ and
                                                                                                                                       BDCODTIPO = 38 and
                                                                                                                                       BDEVENTOEXCLUSAO = 34 and
                                                                                                                                       BDSTATUS in (0, 1, 3, 4))))) and
              (not((ESOC.BDCODTIPO = 11) and ((upper(ESOC.BDORIGEM)) = (upper('frLancamentoProcessoTrabalhista'))) and (exists(select 1 from VRH_ESOCIAL_TARQUIVO
                                                                                                                                 where BDCODEMP = ESOC.BDCODEMP and
                                                                                                                                       BDCODCOL = ESOC.BDCODCOL and
                                                                                                                                       BDREFARQ <= ESOC.BDREFARQ and
                                                                                                                                       BDCODTIPO = 34 and
                                                                                                                                       BDSTATUS in (0, 1, 3, 4)))))))
        into :wapenasrt, :BDCODIGO, :BDCODEMP, :BDCHAVE, :BDXML, :BDCODTIPO, :BDSTATUS, :BDDATAEVENTO, :BDMOTIVO, :BDGRUPO,
             :BDDATAININAOPERIOD, :BDDATAINITABELA, :BDDATAINIPERIOD, :BDDATAINISST, :BDCODEMPMATRIZ, :BDDATAGERADO, :BDHORAGERADO,
             :BDTENTATIVA, :BDCODCOL, :BDIDEVENTO, :BDCPFCOL, :BDEVENTOEXCLUSAO, :BDCPFCOLEXCLUIDO, :BDCONTRORDEMENVIOEVTS2500
    do
    begin
      -- Deve ignorar os eventos que não são de reclamatórias caso esteja marcado a opção enviar apenas eventos de reclamatoria
      if (bdcodtipo not in (49,50,51)) then
         begin
           if (coalesce(upper(wapenasrt),'FALSE') = 'TRUE') then
              continue;
         end

      -- Quando se tratar de um evento de fechamento(S-1299) não deve ser retornado a fila quando houver eventos 1200, 1210, 2299 e 2399 aguardando (status = 0), pendente (status = 1) ou com erro (status = 4).
      if (BDCODTIPO = 20) then
         begin
            WIGNORAFECHAMENTO = 0;

            select first 1 EVT.BDCODEMP
            from TEMPRESAS EMP
            join VRH_ESOCIAL_TARQUIVO EVT on (EMP.BDCODEMP = EVT.BDCODEMP)
            where (:BDCODEMP = Coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP)) and
                  ((EVT.BDCODTIPO = 11) or (EVT.BDCODTIPO = 14) or (EVT.BDCODTIPO = 34) or (EVT.BDCODTIPO = 37)) and
                  (EVT.BDSTATUS in (0, 1, 4)) and
                  (EVT.bdrefarq = (EXTRACT(YEAR FROM :BDDATAEVENTO) * 100 + EXTRACT(MONTH FROM :BDDATAEVENTO)))

            into :WIGNORAFECHAMENTO;

            if (WIGNORAFECHAMENTO > 0) then
               continue;
         end

      if ((WEMPRESA_ATUAL = 0) or (WEMPRESA_ATUAL <> BDCODEMP)) then
      begin
        WEMPRESA_ATUAL = BDCODEMP;
        WCODTIPO = 0;
        WGRUPO = 0;
      end

      if ((WCODTIPO = 0) and
          (WGRUPO = 0)) then
      begin
        if (BDGRUPO in (1, 3)) then
          WCODTIPO = BDCODTIPO;
        else
          WGRUPO = BDGRUPO;
      end

      if (((BDGRUPO in (1, 3)) and
          (WCODTIPO = BDCODTIPO)) or ((BDGRUPO = 2) and
          (WGRUPO = BDGRUPO))) then
         begin
        suspend;
    end
  end
  end
  else
  begin
    for select *
        from (select FAS.BDESOCIALRT, EVT.BDCODIGO, EVT.BDCODEMP, EVT.BDCHAVE, EVT.BDXML, EVT.BDCODTIPO, EVT.BDSTATUS, EVT.BDDATAEVENTO,
                     EVT.BDMOTIVO, coalesce(TP.BDGRUPO, TPEVT.BDGRUPO) BDGRUPO, FAS.BDDATAININAOPERIOD,
                     FAS.BDDATAINITABELA, FAS.BDDATAINIPERIOD, FAS.BDDATAINISST, EVT.BDCODMATRIZ, EVT.BDDATAGERADO,
                     EVT.BDHORAGERADO, EVT.BDTENTATIVA, EVT.BDCODCOL, EVT.BDIDEVENTO, COL.BDCPFCOL, EVT.BDEVENTOEXCLUSAO, --EMAIL.BDCPFCOL BDCPFCOLEXCLUIDO
                     (select first 1 EMAIL.BDCPFCOL from VRH_EMP_TCOL_EMAIL EMAIL where EMAIL.BDCODEMP = EVT.BDCODEMP and EMAIL.BDCODCOL = EVT.BDCODCOL order by EMAIL.bdcodigo DESC) BDCPFCOLEXCLUIDO    -- 170422 Leonardo Schwab 10/11/2022
              from (select VRH_ESOCIAL_TARQUIVO.BDCODIGO, VRH_ESOCIAL_TARQUIVO.BDCODEMP, VRH_ESOCIAL_TARQUIVO.BDCHAVE,
                           VRH_ESOCIAL_TARQUIVO_XML.BDXML, VRH_ESOCIAL_TARQUIVO.BDCODTIPO, VRH_ESOCIAL_TARQUIVO.BDSTATUS,
                           VRH_ESOCIAL_TARQUIVO.BDDATAEVENTO, VRH_ESOCIAL_TARQUIVO.BDMOTIVO,
                           VRH_ESOCIAL_TARQUIVO.BDEVENTOEXCLUSAO, VRH_ESOCIAL_TARQUIVO.BDCODCOL,
                           VRH_ESOCIAL_TARQUIVO.BDEVTEXCLUIDO, VRH_ESOCIAL_TARQUIVO.BDREFARQ, EMP.BDCODMATRIZ,
                           VRH_ESOCIAL_TARQUIVO.BDDATAGERADO, VRH_ESOCIAL_TARQUIVO.BDHORAGERADO, VRH_ESOCIAL_TARQUIVO.BDTENTATIVA,
                           VRH_ESOCIAL_TARQUIVO.BDIDEVENTO
                    from VRH_ESOCIAL_TARQUIVO
                    inner join VRH_ESOCIAL_TARQUIVO_XML ON (VRH_ESOCIAL_TARQUIVO_XML.BDCODIGO = VRH_ESOCIAL_TARQUIVO.BDCODIGO) AND (VRH_ESOCIAL_TARQUIVO_XML.BDCODEMP = VRH_ESOCIAL_TARQUIVO.BDCODEMP)
                    -- em dependências com campos obrigatórios, considere usar "INNER JOIN", dessa forma os indices serão utilizado efetivamente, além de trazer apenas os registros realmente pertinentes
                    --            left outer join TEMPRESAS EMP on VRH_ESOCIAL_TARQUIVO.BDCODEMP = EMP.BDCODEMP
                    inner join(select E.*
                               from TEMPRESAS E
                               inner join TMP_EMPRESAS_SELECT ESOC on (ESOC.BDCODEMP = E.BDCODEMP) or (ESOC.BDCODEMP = E.BDCODMATRIZ)) EMP on VRH_ESOCIAL_TARQUIVO.BDCODEMP = EMP.BDCODEMP
                    where ((VRH_ESOCIAL_TARQUIVO.BDCODTIPO = 38) or (VRH_ESOCIAL_TARQUIVO.BDMOTIVO = 'Exclusão')) and
                          VRH_ESOCIAL_TARQUIVO.BDSTATUS in (0, 3)) EVT
              left outer join VRH_ESOCIAL_TTIPO_ARQ TP on TP.BDCODTIPO = EVT.BDEVENTOEXCLUSAO
              left outer join VRH_ESOCIAL_TTIPO_ARQ TPEVT on TPEVT.BDCODTIPO = EVT.BDCODTIPO

              left outer join VRH_ESOCIAL_TFASEAMENTO FAS on FAS.BDCODEMP = EVT.BDCODEMP
              left outer join VRH_EMP_TCOLCON COL on COL.BDCODEMP = EVT.BDCODEMP and COL.BDCODCOL = EVT.BDCODCOL
--              left join VRH_EMP_TCOL_EMAIL EMAIL on EMAIL.BDCODEMP = EVT.BDCODEMP and EMAIL.BDCODCOL = EVT.BDCODCOL    -- 170422 Leonardo Schwab 10/11/2022
              left outer join VRH_ESOCIAL_TARQUIVO EVT2 on EVT2.BDCODEMP = EVT.BDCODEMP and EVT2.BDCODIGO = EVT.BDEVTEXCLUIDO and EVT2.BDCODEMP = EVT.BDCODEMP
              where ((EVT2.BDCODTIPO <> 11) or (not exists(select first 1 EVT3.BDCODEMP
                                                           from VRH_ESOCIAL_TARQUIVO EVT3
                                                           -- em dependências com campos obrigatórios, considere usar "INNER JOIN", dessa forma os indices serão utilizado efetivamente, além de trazer apenas os registros realmente pertinentes
                                                           --                                                   left outer join VRH_ESOCIAL_TARQUIVO EVT4 on EVT3.BDEVTEXCLUIDO = EVT4.BDCODIGO and EVT3.BDCODEMP = EVT4.BDCODEMP
                                                           inner join VRH_ESOCIAL_TARQUIVO EVT4 on EVT3.BDEVTEXCLUIDO = EVT4.BDCODIGO and EVT3.BDCODEMP = EVT4.BDCODEMP
                                                           where (EVT4.BDCODEMP = EVT.BDCODEMP) and
                                                                 (EVT4.BDCODCOL = EVT.BDCODCOL) and
                                                                 (EVT4.BDCODTIPO in (14)) and
                                                                 (EVT3.BDSTATUS in (0, 1, 3, 4))))) and
                    ((EVT2.BDCODTIPO <> 23) or (not exists(select first 1 EVT3.BDCODEMP
                                                           from VRH_ESOCIAL_TARQUIVO EVT3
                                                           -- em dependências com campos obrigatórios, considere usar "INNER JOIN", dessa forma os indices serão utilizado efetivamente, além de trazer apenas os registros realmente pertinentes
                                                           --                                                     left outer join VRH_ESOCIAL_TARQUIVO EVT4 on EVT3.BDEVTEXCLUIDO = EVT4.BDCODIGO and EVT3.BDCODEMP = EVT4.BDCODEMP
                                                           inner join VRH_ESOCIAL_TARQUIVO EVT4 on EVT3.BDEVTEXCLUIDO = EVT4.BDCODIGO and EVT3.BDCODEMP = EVT4.BDCODEMP
                                                           where (EVT4.BDCODEMP = EVT.BDCODEMP) and
                                                                 (EVT4.BDCODCOL = EVT.BDCODCOL) and
                                                                 (EVT4.BDCODTIPO in (24)) and
                                                                 (EVT3.BDSTATUS in (0, 1, 3, 4))))) and
                    ((EVT2.BDCODTIPO <> 24) or (not exists(select first 1 EVT3.BDCODEMP
                                                           from VRH_ESOCIAL_TARQUIVO EVT3
                                                           -- em dependências com campos obrigatórios, considere usar "INNER JOIN", dessa forma os indices serão utilizado efetivamente, além de trazer apenas os registros realmente pertinentes
                                                           --                                                     left outer join VRH_ESOCIAL_TARQUIVO EVT4 on EVT3.BDEVTEXCLUIDO = EVT4.BDCODIGO and EVT3.BDCODEMP = EVT4.BDCODEMP
                                                           inner join VRH_ESOCIAL_TARQUIVO EVT4 on EVT3.BDEVTEXCLUIDO = EVT4.BDCODIGO and EVT3.BDCODEMP = EVT4.BDCODEMP
                                                           where (EVT4.BDCODEMP = EVT.BDCODEMP) and
                                                                 (EVT4.BDCODCOL = EVT.BDCODCOL) and
                                                                 (EVT4.BDCODTIPO in (11, 14, 25, 26, 29, 32, 33, 34)) and
                                                                 (EVT3.BDSTATUS in (0, 1, 3, 4))))) and
                    ((EVT2.BDCODTIPO <> 29) or (not exists(select first 1 EVT3.BDCODEMP
                                                           from VRH_ESOCIAL_TARQUIVO EVT3
                                                           -- em dependências com campos obrigatórios, considere usar "INNER JOIN", dessa forma os indices serão utilizado efetivamente, além de trazer apenas os registros realmente pertinentes
                                                           --                                                     left outer join VRH_ESOCIAL_TARQUIVO EVT4 on EVT3.BDEVTEXCLUIDO = EVT4.BDCODIGO and EVT3.BDCODEMP = EVT4.BDCODEMP
                                                           inner join VRH_ESOCIAL_TARQUIVO EVT4 on EVT3.BDEVTEXCLUIDO = EVT4.BDCODIGO and EVT3.BDCODEMP = EVT4.BDCODEMP
                                                           where (EVT4.BDCODEMP = EVT.BDCODEMP) and
                                                                 (EVT4.BDCODCOL = EVT.BDCODCOL) and
                                                                 (EVT4.BDDATAEVENTO > EVT2.BDDATAEVENTO) and
                                                                 (EVT4.BDCODTIPO in (29, 34)) and
                                                                 (EVT3.BDSTATUS in (0, 1, 3, 4))))) and
                    ((EVT2.BDCODTIPO <> 35) or (not exists(select first 1 EVT3.BDCODEMP
                                                           from VRH_ESOCIAL_TARQUIVO EVT3
                                                           where (EVT3.BDCODEMP = EVT.BDCODEMP) and
                                                                 (EVT3.BDCODCOL = EVT.BDCODCOL) and
                                                                 (EVT3.BDCODTIPO in (38)) and
                                                                 (EVT3.BDCODIGO <> EVT.BDCODIGO) and
                                                                 (EVT3.BDEVTEXCLUIDO = EVT2.BDCODIGO) and
                                                                 (EVT3.BDSTATUS in (0, 1, 3, 4))))) and
                    ((EVT.BDCODTIPO <> 9) or ((EVT.BDCODTIPO = 9) and (not exists(select first 1 EVT3.BDCODEMP
                                                           from VRH_ESOCIAL_TARQUIVO EVT3
                                                           where (EVT3.BDCODEMP = EVT.BDCODEMP) and
                                                                 (EVT3.BDCODTIPO in (2,4)) and
                                                                 (EVT3.BDSTATUS in (0, 1, 3, 4)))))) and
                    ((EVT.BDCODTIPO <> 1) or ((EVT.BDCODTIPO = 1 and
                    -- first 1 com order by é mais rápido que min, além do order by usar indice
                    --              EVT.BDREFARQ <> (select min(BDREFARQ)
                    EVT.BDREFARQ <> (select first 1 BDREFARQ
                                     from VRH_ESOCIAL_TARQUIVO EVTREF
                                     where EVTREF.BDCODEMP in (EVT.BDCODMATRIZ, EVT.BDCODEMP) and
                                           EVTREF.BDCODTIPO = 1
                                     order by EVTREF.BDCODEMP, EVTREF.BDCODTIPO, EVTREF.BDREFARQ))) or (not exists(select first 1 EVTTAB.BDCODEMP
                                                                         from VRH_ESOCIAL_TARQUIVO EVTTAB
                                                                         join VRH_ESOCIAL_TFASEAMENTO FAS on EVTTAB.BDCODEMP = FAS.BDCODEMP
                                                                         where EVTTAB.BDCODEMP in (EVT.BDCODMATRIZ, EVT.BDCODEMP) and
                                                                               EVTTAB.BDCODTIPO <> 1 and
                                                                               EVTTAB.BDREFARQ < FAS.BDREFINITABELA and
                                                                               EVTTAB.BDSTATUS in (0, 1, 3, 4)))))
        into :wapenasrt,:BDCODIGO, :BDCODEMP, :BDCHAVE, :BDXML, :BDCODTIPO, :BDSTATUS, :BDDATAEVENTO, :BDMOTIVO, :BDGRUPO,
             :BDDATAININAOPERIOD, :BDDATAINITABELA, :BDDATAINIPERIOD, :BDDATAINISST, :BDCODEMPMATRIZ, :BDDATAGERADO, :BDHORAGERADO,
             :BDTENTATIVA, :BDCODCOL, :BDIDEVENTO, :BDCPFCOL, :BDEVENTOEXCLUSAO, :BDCPFCOLEXCLUIDO
    do
    begin
      if (bdcodtipo not in (49,50,51)) then
         begin
           if (coalesce(upper(wapenasrt),'FALSE') = 'TRUE') then
              continue;
         end
        suspend;
    end
  end
end^

/* Restore proc. body: SP_GET_EVT_FILA_ESOCIAL */
CREATE OR ALTER procedure SP_GET_EVT_FILA_ESOCIAL_V2 (
    PRCODEMP integer,
    PREXCLUSAO integer)
returns (
    BDCODIGO integer,
    BDCODEMP integer,
    BDCHAVE varchar(60),
    BDXML blob sub_type 0 segment size 80,
    BDCODTIPO integer,
    BDSTATUS integer,
    BDDATAEVENTO date,
    BDMOTIVO varchar(100),
    BDGRUPO integer,
    BDDATAININAOPERIOD date,
    BDDATAINITABELA date,
    BDDATAINIPERIOD date,
    BDDATAINISST date,
    BDCODEMPMATRIZ integer,
    BDDATAGERADO date,
    BDHORAGERADO time,
    BDTENTATIVA integer,
    BDCODCOL integer,
    BDIDEVENTO varchar(100),
    BDCPFCOL varchar(14),
    BDEVENTOEXCLUSAO integer,
    BDCPFCOLEXCLUIDO varchar(14),
    BDORDEM_MAIOR_PRIORI_ENVIO integer)
as
declare variable WEMPAUX integer;
declare variable WMOTIVOINT integer;
declare variable WTEM1005PENDENTE varchar(5);
declare variable WTIPOPAGEMP integer;
declare variable WMSG varchar(1000);
declare variable WTEM1010PENDENTE varchar(5);
declare variable WTEM1070PENDENTE varchar(5);
declare variable WREFARQ integer;
declare variable WCODEMPTAB1 integer;
declare variable WEMPRESA_ATUAL integer;
declare variable WCODTIPO integer;
declare variable WSUSPEND varchar(5);
declare variable WCODTIPOEXCLU bigint;
declare variable WTROCOUEMP varchar(5);
declare variable WREF1210 integer;
declare variable WDESCTIPO varchar(300);
declare variable WGRUPO integer;
declare variable WAPENASRT varchar(5);
declare variable WORIGEM varchar(250);
declare variable WCONTRENVIO2500 integer;
declare variable WTIPOEVTPENDENTE integer;
declare variable WDESCTIPOARQ varchar(300);
declare variable WCODTER integer;
declare variable WCHAVEPROCRT integer;
declare variable WIDESEQPROC integer;
declare variable WTEMS2501OUS2555PENDENTE varchar(5);
begin
  if (:PRCODEMP = 0) then
  begin
    delete from TMP_EMPRESAS_SELECT;

    insert into TMP_EMPRESAS_SELECT
    select coalesce(E.BDCODMATRIZ, E.BDCODEMP) BDCODEMPGRUPO
    from TEMPRESAS E
    left outer join TEMPRESAS MATRIZ on (E.BDCODMATRIZ = MATRIZ.BDCODEMP)
    inner join(select distinct E.BDCODEMP
               from TEMPRESAS E
               where exists(select first 1 T.BDCODEMP
                            from VRH_ESOCIAL_TTOTSTATUS T
                            where T.BDCODEMP = E.BDCODEMP)) ESA on ESA.BDCODEMP = E.BDCODEMP
    where ((E.BDCODMATRIZ = ESA.BDCODEMP) or ((E.BDCODMATRIZ is null) and
          (E.BDCODEMP = ESA.BDCODEMP)) or ((E.BDCODMATRIZ is not null) and
          (MATRIZ.BDSITUACAOESOCIAL = 0) and
          (E.BDCODEMP = ESA.BDCODEMP))) and
          (E.BDSITUACAOESOCIAL <> 0)
    group by BDCODEMPGRUPO;
  end
  else
  begin
    delete from TMP_EMPRESAS_SELECT;
    insert into TMP_EMPRESAS_SELECT (BDCODEMP)
    values (:PRCODEMP);
  end

  WTEM1070PENDENTE = 'false';
  if (PREXCLUSAO = -1) then
  begin
    WCODTIPO = 0;
    WGRUPO = 0;
    WEMPRESA_ATUAL = 0;
    for select ESOC.bdesocialrt, ESOC.BDCODIGO, ESOC.BDCODEMP, ESOC.BDCHAVE, ESOC.BDXML, ESOC.BDCODTIPO, ESOC.BDSTATUS, ESOC.BDDATAEVENTO,
               ESOC.BDMOTIVO, ESOC.BDGRUPO, ESOC.BDDATAININAOPERIOD, ESOC.BDDATAINITABELA, ESOC.BDDATAINIPERIOD,
               ESOC.BDDATAINISST, ESOC.BDCODMATRIZ, ESOC.BDDATAGERADO, ESOC.BDHORAGERADO, ESOC.BDTENTATIVA,
               ESOC.BDCODCOL, ESOC.BDIDEVENTO, ESOC.BDCPFCOL, ESOC.BDEVENTOEXCLUSAO, ESOC.BDCPFCOL BDCPFCOLEXCLUIDO,
               BDORDEM_MAIOR_PRIORI_ENVIO
        from (select FAS.bdesocialrt, EVT.BDCODIGO, EVT.BDCODEMP, EVT.BDCHAVE, EVT.BDXML, EVT.BDCODTIPO, EVT.BDSTATUS, EVT.BDDATAEVENTO,
                     EVT.BDMOTIVO, TP.BDGRUPO, FAS.BDDATAININAOPERIOD, FAS.BDDATAINITABELA, FAS.BDDATAINIPERIOD,
                     FAS.BDDATAINISST, MAT.BDCODEMP BDCODMATRIZ, COL.BDCPFCOL, EVT.BDREFARQ, EVT.BDCODCOL,
                     EVT.BDDATAGERADO, EVT.BDHORAGERADO, EVT.BDTENTATIVA, EVT.BDIDEVENTO, EVT.BDEVENTOEXCLUSAO,
                     EVT.BDORDEM_MAIOR_PRIORI_ENVIO,
                     (select first 1 EMAIL.BDCPFCOL
                      from VRH_EMP_TCOL_EMAIL EMAIL
                      where EMAIL.BDCODEMP = EVT.BDCODEMP and
                            EMAIL.BDCODCOL = EVT.BDCODCOL
                      order by EMAIL.BDCODIGO desc) BDCPFCOLEXCLUIDO
              from (select EVT1.BDCODIGO, EVT1.BDCODEMP, EVT1.BDCHAVE, EVT1XML.BDXML, EVT1.BDCODTIPO, EVT1.BDSTATUS,
                           EVT1.BDDATAEVENTO, EVT1.BDMOTIVO, EVT1.BDREFARQ, EVT1.BDCODCOL, EVT1.BDDATAGERADO,
                           EVT1.BDHORAGERADO, EVT1.BDTENTATIVA, EVT1.BDIDEVENTO, EVT1.BDEVENTOEXCLUSAO, EVT1.BDORDEM_MAIOR_PRIORI_ENVIO

                    from VRH_ESOCIAL_TARQUIVO EVT1
                    inner join VRH_ESOCIAL_TARQUIVO_XML EVT1XML on (EVT1XML.BDCODIGO = EVT1.BDCODIGO) and
                          (EVT1XML.BDCODEMP = EVT1.BDCODEMP)
                    inner join(select E.BDCODEMP
                               from TEMPRESAS E
                               inner join TMP_EMPRESAS_SELECT ESOC on (ESOC.BDCODEMP = E.BDCODEMP) or (ESOC.BDCODEMP = E.BDCODMATRIZ)) EMP on EVT1.BDCODEMP = EMP.BDCODEMP

                    where (EVT1.BDORDEM_MAIOR_PRIORI_ENVIO = -1)) EVT
              inner join(select EMP_I.*
                         from TEMPRESAS EMP_I
                         inner join TMP_EMPRESAS_SELECT ESA on (ESA.BDCODEMP = EMP_I.BDCODEMP) or ((ESA.BDCODEMP = EMP_I.BDCODMATRIZ) and
                               (coalesce(EMP_I.BDSITUACAOESOCIAL, 0) = 1))) EMP on EMP.BDCODEMP = EVT.BDCODEMP
              inner join VRH_ESOCIAL_TTIPO_ARQ TP on TP.BDCODTIPO = EVT.BDCODTIPO
              left outer join TEMPRESAS MAT on ((EMP.BDCODMATRIZ = MAT.BDCODEMP) or (MAT.BDCODEMP = (select first 1 BDCODEMP
                                                                                                     from TEMPRESAS_SCP
                                                                                                     where BDCODEMPSCP = EMP.BDCODEMP)))
              left outer join VRH_ESOCIAL_TFASEAMENTO FAS on FAS.BDCODEMP = EMP.BDCODEMP
              left outer join VRH_EMP_TCOLCON COL on COL.BDCODEMP = EVT.BDCODEMP and
                    COL.BDCODCOL = EVT.BDCODCOL
              where (BDORDEM_MAIOR_PRIORI_ENVIO = -1) and
                    BDSTATUS = 0) ESOC

        into :WAPENASRT, :BDCODIGO, :BDCODEMP, :BDCHAVE, :BDXML, :BDCODTIPO, :BDSTATUS, :BDDATAEVENTO, :BDMOTIVO, :BDGRUPO,
             :BDDATAININAOPERIOD, :BDDATAINITABELA, :BDDATAINIPERIOD, :BDDATAINISST, :BDCODEMPMATRIZ, :BDDATAGERADO,
             :BDHORAGERADO, :BDTENTATIVA, :BDCODCOL, :BDIDEVENTO, :BDCPFCOL, :BDEVENTOEXCLUSAO, :BDCPFCOLEXCLUIDO,
             :BDORDEM_MAIOR_PRIORI_ENVIO
    do
    begin
      if (bdcodtipo not in (49,50,51)) then
         begin
           if (coalesce(upper(wapenasrt),'FALSE') = 'TRUE') then
              begin
                WMSG = 'Evento não enviado pois a empresa está configurada para enviar apenas RT';
                update VRH_ESOCIAL_TARQUIVO
                set BDDESCNAOENVIA = :WMSG
                where BDCODEMP = :BDCODEMP and
                      BDCODIGO = :BDCODIGO and Coalesce(BDDESCNAOENVIA,'')<>:WMSG;
                continue;
              end
         end

      WSUSPEND = 'true';
      for select first 1 EVTPROC.BDCODEMP
          from VRH_ESOCIAL_TARQUIVO EVTPROC
          where EVTPROC.BDCODEMP = (:BDCODEMP) and
                EVTPROC.bdchave  = :bdchave  and
                (EVTPROC.BDSTATUS = 1)
          into :WCODEMPTAB1
        do
        begin
          begin
            WMSG = 'Possuí um evento identico esperando retorno. Aguardando retorno para envio.';
            WSUSPEND = 'false';
          end
        end
      if ((WEMPRESA_ATUAL = 0) or (WEMPRESA_ATUAL <> BDCODEMP)) then
      begin
        WEMPRESA_ATUAL = BDCODEMP;
        WCODTIPO = 0;
        WGRUPO = 0;
      end

      if ((WCODTIPO = 0) and
          (WGRUPO = 0)) then
      begin
        if (BDGRUPO in (1, 3)) then
          WCODTIPO = BDCODTIPO;
        else
          WGRUPO = BDGRUPO;
      end

      if (((BDGRUPO in (1, 3)) and
          (WCODTIPO = BDCODTIPO)) or ((BDGRUPO = 2) and
          (WGRUPO = BDGRUPO)) and (wSuspend='true')) then
          begin
           suspend;
          end
       else if ((WSUSPEND='false')  and
              (:WMSG <> ''))   then
         begin
           update VRH_ESOCIAL_TARQUIVO
           set BDDESCNAOENVIA = :WMSG
           where BDCODEMP = :BDCODEMP and
                 BDCODIGO = :BDCODIGO and Coalesce(BDDESCNAOENVIA,'')<>:WMSG;
         end
     end
  end
  else
  begin

    WCODTIPO = 0;
    WGRUPO = 0;
    WEMPRESA_ATUAL = 0;
    WCODTER = 0;
    for select esoc.bdesocialrt, ESOC.BDCODIGO, ESOC.BDCODEMP, ESOC.BDCHAVE, ESOC.BDXML, ESOC.BDCODTIPO, ESOC.BDSTATUS, ESOC.BDDATAEVENTO,
               ESOC.BDMOTIVO, ESOC.BDGRUPO, ESOC.BDDATAININAOPERIOD, ESOC.BDDATAINITABELA, ESOC.BDDATAINIPERIOD,
               ESOC.BDDATAINISST, ESOC.BDCODMATRIZ, ESOC.BDDATAGERADO, ESOC.BDHORAGERADO, ESOC.BDTENTATIVA,
               ESOC.BDCODCOL, ESOC.BDIDEVENTO, ESOC.BDCPFCOL, ESOC.BDEVENTOEXCLUSAO, ESOC.BDCPFCOL BDCPFCOLEXCLUIDO,
               ESOC.BDREFARQ, Coalesce(ESOC.BDMOTIVOINT,0), ESOC.BDORIGEM, ESOC.BDCONTRORDEMENVIOEVTS2500, ESOC.BDCODTER, ESOC.BDCHAVEPROCRT, ESOC.BDIDESEQPROC
        from (select FAS.bdesocialrt, EVT.BDCODIGO, EVT.BDCODEMP, EVT.BDCHAVE, EVT.BDXML, EVT.BDCODTIPO, EVT.BDSTATUS, EVT.BDDATAEVENTO,
                     EVT.BDMOTIVO, TP.BDGRUPO, FAS.BDDATAININAOPERIOD, FAS.BDDATAINITABELA, FAS.BDDATAINIPERIOD,
                     FAS.BDDATAINISST, MAT.BDCODEMP BDCODMATRIZ, COL.BDCPFCOL, EVT.BDREFARQ, EVT.BDCODCOL,
                     EVT.BDDATAGERADO, EVT.BDHORAGERADO, EVT.BDTENTATIVA, EVT.BDIDEVENTO, EVT.BDEVENTOEXCLUSAO, EVT.BDORIGEM, EVT.BDCONTRORDEMENVIOEVTS2500,
                     (select first 1 EMAIL.BDCPFCOL
                      from VRH_EMP_TCOL_EMAIL EMAIL
                      where EMAIL.BDCODEMP = EVT.BDCODEMP and
                            EMAIL.BDCODCOL = EVT.BDCODCOL
                      order by EMAIL.BDCODIGO desc) BDCPFCOLEXCLUIDO, EVT.BDMOTIVOINT, EVT.BDCODTER, EVT.BDCHAVEPROCRT, EVT.BDIDESEQPROC

              from (select EVT1.BDCODIGO, EVT1.BDCODEMP, EVT1.BDCHAVE, EVT1XML.BDXML, EVT1.BDCODTIPO, EVT1.BDSTATUS,
                           EVT1.BDDATAEVENTO, EVT1.BDMOTIVO, EVT1.BDREFARQ, EVT1.BDCODCOL, EVT1.BDDATAGERADO,
                           EVT1.BDHORAGERADO, EVT1.BDTENTATIVA, EVT1.BDIDEVENTO, EVT1.BDEVENTOEXCLUSAO, EVT1.BDMOTIVOINT, EVT1.BDORIGEM, EVT1.BDCONTRORDEMENVIOEVTS2500, EVT1.BDCHAVEPROCRT, EVT1.BDIDESEQPROC, 
                           COALESCE(EVT1.BDCODTER, 0) BDCODTER
                    from VRH_ESOCIAL_TARQUIVO EVT1
                    inner join VRH_ESOCIAL_TARQUIVO_XML EVT1XML on (EVT1XML.BDCODIGO = EVT1.BDCODIGO) and
                          (EVT1XML.BDCODEMP = EVT1.BDCODEMP)
                    inner join(select E.BDCODEMP
                               from TEMPRESAS E
                               inner join TMP_EMPRESAS_SELECT ESOC on (ESOC.BDCODEMP = E.BDCODEMP) or (ESOC.BDCODEMP = E.BDCODMATRIZ)) EMP on EVT1.BDCODEMP = EMP.BDCODEMP
                    where (EVT1.BDSTATUS in (0, 3)) and
                          (EVT1.BDDATAENVIAREVT <= 'NOW')) EVT
              inner join(select EMP_I.*
                         from TEMPRESAS EMP_I
                         inner join TMP_EMPRESAS_SELECT ESA on (ESA.BDCODEMP = EMP_I.BDCODEMP) or ((ESA.BDCODEMP = EMP_I.BDCODMATRIZ) and
                               (coalesce(EMP_I.BDSITUACAOESOCIAL, 0) = 1))) EMP on EMP.BDCODEMP = EVT.BDCODEMP
              inner join VRH_ESOCIAL_TTIPO_ARQ TP on TP.BDCODTIPO = EVT.BDCODTIPO
              left outer join TEMPRESAS MAT on ((EMP.BDCODMATRIZ = MAT.BDCODEMP) or (MAT.BDCODEMP = (select first 1 BDCODEMP
                                                                                                     from TEMPRESAS_SCP
                                                                                                     where BDCODEMPSCP = EMP.BDCODEMP)))
              left outer join VRH_ESOCIAL_TFASEAMENTO FAS on FAS.BDCODEMP = EMP.BDCODEMP
              left join VRH_EMP_TCOLCON COL on COL.BDCODEMP = EVT.BDCODEMP and
                    COL.BDCODCOL = EVT.BDCODCOL
              where  ((EVT.BDCODTIPO = 1 and
                    EVT.BDREFARQ = (select first 1 BDREFARQ
                                    from VRH_ESOCIAL_TARQUIVO EVTREF
                                    where EVTREF.BDCODEMP in (MAT.BDCODEMP, EMP.BDCODEMP) and
                                          EVTREF.BDCODTIPO = 1 and
                                          EVTREF.BDREFARQ >= FAS.BDREFINITABELA
                                    order by EVTREF.BDCODEMP, EVTREF.BDCODTIPO, EVTREF.BDREFARQ)) or (exists(select first 1 EVT1000.BDCODEMP
                                                                                                             from VRH_ESOCIAL_TARQUIVO EVT1000
                                                                                                             where EVT1000.BDCODEMP in (MAT.BDCODEMP, EMP.BDCODEMP) and
                                                                                                                   EVT1000.BDCODTIPO = 1 and
                                                                                                                   EVT1000.BDSTATUS = 2)) or ((EVT.BDCODTIPO in (49,50,51)) and (coalesce(FAS.BDESOCIALRT,'FALSE') = 'TRUE' )) or (coalesce(EMP.BDMATRIZNAOCADSIS, 'FALSE') = 'TRUE') or (coalesce(MAT.BDSITUACAOESOCIAL, 1) = 0))
              order by EVT.BDCODEMP, TP.BDGRUPO, TP.BDCODTIPO) ESOC
        into :wapenasrt, :BDCODIGO, :BDCODEMP, :BDCHAVE, :BDXML, :BDCODTIPO, :BDSTATUS, :BDDATAEVENTO, :BDMOTIVO, :BDGRUPO,
             :BDDATAININAOPERIOD, :BDDATAINITABELA, :BDDATAINIPERIOD, :BDDATAINISST, :BDCODEMPMATRIZ, :BDDATAGERADO,
             :BDHORAGERADO, :BDTENTATIVA, :BDCODCOL, :BDIDEVENTO, :BDCPFCOL, :BDEVENTOEXCLUSAO, :BDCPFCOLEXCLUIDO,
             :WREFARQ, :WMOTIVOINT, :WORIGEM, :WCONTRENVIO2500, :WCODTER, :WCHAVEPROCRT, :WIDESEQPROC
    do
    begin
      if (bdcodtipo not in (49,50,51,55)) then
         begin
           if (coalesce(upper(wapenasrt),'FALSE') = 'TRUE') then
              begin
                WMSG = 'Evento não enviado pois a empresa está configurada para enviar apenas RT';
                update VRH_ESOCIAL_TARQUIVO
                set BDDESCNAOENVIA = :WMSG
                where BDCODEMP = :BDCODEMP and
                      BDCODIGO = :BDCODIGO and Coalesce(BDDESCNAOENVIA,'')<>:WMSG;
                continue;
              end
         end

      WMSG = '';
      WSUSPEND = 'true';

        for select first 1 EVTPROC.BDCODEMP
            from VRH_ESOCIAL_TARQUIVO EVTPROC
            where EVTPROC.BDCODEMP = (:BDCODEMP) and
                  EVTPROC.bdchave  = :bdchave   and
                  (EVTPROC.BDSTATUS = 1)
            into :WCODEMPTAB1
        do
        begin
          begin
            WMSG = 'Possuí um evento identico esperando retorno. Aguardando retorno para envio.';
            WSUSPEND = 'false';
          end
        end

      if ((WEMPRESA_ATUAL = 0) or (WEMPRESA_ATUAL <> BDCODEMP)) then -- Verificações de troca de empresa, 1000,1070
      begin
        WTEM1070PENDENTE = 'false';
        for select first 1 EVTPROC.BDCODEMP
            from VRH_ESOCIAL_TARQUIVO EVTPROC
            where EVTPROC.BDCODEMP = (:BDCODEMP) and
                  EVTPROC.BDCODTIPO = 9 and
                  (EVTPROC.BDSTATUS = 0 or EVTPROC.BDSTATUS = 1)
            into :WCODEMPTAB1
        do
        begin
          WTEM1070PENDENTE = 'true';
        end

        WTEM1005PENDENTE = 'false';
        for select first 1 EVTPROC.BDCODEMP
            from VRH_ESOCIAL_TARQUIVO EVTPROC
            where EVTPROC.BDCODEMP = (:BDCODEMP) and
                  EVTPROC.BDCODTIPO = 2 and
                  (EVTPROC.BDSTATUS = 0 or EVTPROC.BDSTATUS = 1)
            into :WCODEMPTAB1
        do
        begin
          WTEM1005PENDENTE = 'true';
        end
      end

      if ((:BDCODTIPO = 51) and (:BDEVENTOEXCLUSAO = 50)) then /*Evento de exclusão do S-2501 precisa aguardar exclusão do S-2555*/
        begin
           :WCODEMPTAB1 = -1;
           select first 1 EVTPROC.BDCODEMP
            from VRH_ESOCIAL_TARQUIVO EVTPROC
            where EVTPROC.BDCODEMP = (:BDCODEMP) and
                  EVTPROC.BDREFARQ = (:WREFARQ)  and
                  EVTPROC.BDSTATUS in (0, 1, 3, 4) and EVTPROC.BDCODTIPO = 51 and EVTPROC.BDEVENTOEXCLUSAO = 55 into :WCODEMPTAB1;

          if (WCODEMPTAB1 > 0) then
            begin
              WMSG =  'Existe um evento de exclusão de S-2555 com status "pendente", "enviando" ou "erro".';
              WSUSPEND = 'false';
            end
        end

      WTEMS2501OUS2555PENDENTE = 'false';
      if (:BDCODTIPO = 55) then --Controla envio do evento S-2555
      begin
        for select first 1 EVTPROC.BDCODEMP
            from VRH_ESOCIAL_TARQUIVO EVTPROC
            where EVTPROC.BDCODEMP = (:BDCODEMP) and
                  EVTPROC.BDREFARQ = (:WREFARQ) and
                  (EVTPROC.BDCODTIPO = 50 and EVTPROC.BDSTATUS in (0, 1)) or
                  (EVTPROC.BDCODTIPO = 51 and EVTPROC.BDSTATUS in (0, 1) and EVTPROC.BDEVENTOEXCLUSAO = 55)
            into :WCODEMPTAB1
        do
        begin
          WTEMS2501OUS2555PENDENTE = 'true';
        end
      end

      if (WTEMS2501OUS2555PENDENTE = 'false') then
      begin
          if (:BDCODTIPO = 50) then --Controla envio do evento S-2501
          begin
            for select first 1 EVTPROC.BDCODEMP
                from VRH_ESOCIAL_TARQUIVO EVTPROC
                where EVTPROC.BDCODEMP = (:BDCODEMP) and
                      EVTPROC.BDREFARQ = (:WREFARQ) and
                      (EVTPROC.BDCODTIPO = 51 and EVTPROC.BDSTATUS in (0, 1) and EVTPROC.BDEVENTOEXCLUSAO = 55)
                into :WCODEMPTAB1
            do
            begin
              WTEMS2501OUS2555PENDENTE = 'true';
            end
          end
      end

      if ((:WMOTIVOINT in (0, 1, 3)) and (wSuspend='true')) then --Se for inclusão ou alteração ou retificação
      begin
        if (:BDGRUPO = 1) then -- Tabelas
        begin
          if ((:BDCODTIPO in ( 2, 3, 4, 5, 7, 8)) and
              (WTEM1070PENDENTE = 'true')) then -- Se não for S-1000 ou S-1070, não pode enviar se tiver um S-1070 pendente.
          begin
            WMSG =  'Possuí S-1070 aguardando ou enviado, esperando retorno.';
            WSUSPEND = 'false';
          end
          else
            if ((:BDCODTIPO in (3, 4, 5, 7, 8)) and
               (WTEM1070PENDENTE = 'true')) then -- Se não for S-1000 ou 1005 ou S-1070, não pode enviar se tiver um S-1005 pendente.
          begin
            WMSG = 'Possuí S-1005 aguardando ou enviado, esperando retorno.';
            WSUSPEND = 'false';
          end
        end
        else
        if ((:BDGRUPO = 2) or (:BDGRUPO = 3)) then -- Não periodicos e periodicos
        begin
          if (WTEM1005PENDENTE = 'false') then
          begin
            if (:BDCODTIPO = 24) then -- Se for 2200 verifica se tem 2190 pendente
            begin
              for select first 1 EVTPROC.BDCODEMP
                  from VRH_ESOCIAL_TARQUIVO EVTPROC
                  where EVTPROC.BDCODEMP = (:BDCODEMP) and
                        EVTPROC.BDCODTIPO = 23 and
                        (EVTPROC.BDSTATUS = 0 or EVTPROC.BDSTATUS = 1) and
                        BDCODTIPO = 23
                  into :WCODEMPTAB1
              do
              begin
                WSUSPEND = 'false';
                WMSG = WMSG || ' ' || 'Possuí S-2190 aguardando ou enviado, esperando retorno.';
              end

            end
            if (not(:BDCODTIPO in (23, 24, 35)) and
                (:BDCODCOL <> 0)) then --Se não for 2190,2200,2300 e tiver codigo de colab precista ter ou 2190,2200 ou 2300 integrado
            begin
              WSUSPEND = 'false';
              WMSG = WMSG || ' ' || 'Não possui S-2200 ou S-2300 integrado.';
              for select first 1 EVTPROC.BDCODEMP
                  from VRH_ESOCIAL_TARQUIVO EVTPROC
                  where EVTPROC.BDCODEMP = (:BDCODEMP) and
                        EVTPROC.BDSTATUS = 2 and
                        EVTPROC.BDCODCOL = :BDCODCOL and
                        (EVTPROC.BDCODTIPO = 24 or EVTPROC.BDCODTIPO = 35 or EVTPROC.BDCODTIPO = 23)
                  into :WCODEMPTAB1
              do
              begin
                WSUSPEND = 'true';
                WMSG = '';
              end

              -- Se foi colaborador transferido entre matriz e filial não precisa aguardar o 2200
              if (WSUSPEND = 'false') then
                 begin
                    for select first 1 BDCODEMPDEST from VRH_EMP_TTRANSCOL  t
                        left outer join VRH_BASE_TPREPRESC P on T.BDCODPTRAN = P.BDCODPRES
                        where BDCODEMPDEST = :bdcodemp and BDCODCOLDEST = :bdcodcol and p.BDCODMOTESRESC = 99
                        into :WCODEMPTAB1 do
                    begin
                      WSUSPEND = 'true';
                      WMSG = '';
                    end
                 end
                 
              -- Se for evento de folha e não tiver nenhum de cadastro pendente deve enviar pois o mesmo pode ser de autonomo
              if ((WSUSPEND = 'false') and (:BDCODTIPO in (11,13,14))) then
                 begin
                   WSUSPEND = 'true';
                   WMSG = '';
                   for select first 1 EVTPROC.BDCODEMP
                       from VRH_ESOCIAL_TARQUIVO EVTPROC
                       where EVTPROC.BDCODEMP = (:BDCODEMP) and
                             EVTPROC.BDSTATUS in (0,1,3,4,9) and
                             EVTPROC.BDCODCOL = :BDCODCOL and
                             (EVTPROC.BDCODTIPO = 24 or EVTPROC.BDCODTIPO = 35 or EVTPROC.BDCODTIPO = 23)
                   into :WCODEMPTAB1 do
                   begin
                     WSUSPEND = 'false';
                     WMSG = WMSG || ' ' || 'Não possui S-2200 ou S-2300 integrado.';
                   end
                 end
            end

            if ((:BDCODTIPO in (11, 34, 37)) and
                (WSUSPEND='true')) then
            begin
              for SELECT FIRST 1 BDCODEMP FROM (
                    SELECT FIRST 1 EVTPROC.BDCODEMP
                    FROM VRH_ESOCIAL_TARQUIVO EVTPROC
                    JOIN SP_MATRIZ_E_FILIAIS('BDCODEMP = '||:BDCODEMP||'') EMP ON EVTPROC.BDCODEMP = EMP.BDCODEMP
                    JOIN (SELECT COL.BDCODEMP, COL.BDCODCOL FROM VRH_EMP_TCOLCON COL WHERE bdcpfcol = (select first 1 bdcpfcol from vrh_emp_tcolcon where bdcodemp = :BDCODEMP and bdcodcol = :BDCODCOL)
                         ) FILTRO ON EVTPROC.BDCODEMP = FILTRO.BDCODEMP AND EVTPROC.BDCODCOL = FILTRO.BDCODCOL
                    WHERE EVTPROC.BDCODTIPO = 38 AND
                          EVTPROC.BDEVENTOEXCLUSAO = 14 AND
                          (EVTPROC.BDSTATUS = 0 OR EVTPROC.BDSTATUS = 1)
                    UNION
                    SELECT FIRST 1 EVTPROC.BDCODEMP
                    FROM VRH_ESOCIAL_TARQUIVO EVTPROC
                    JOIN SP_MATRIZ_E_FILIAIS('BDCODEMP = '||:BDCODEMP||'') EMP ON EVTPROC.BDCODEMP = EMP.BDCODEMP
                    JOIN (SELECT TER.BDCODTER FROM TTERCEIRO TER WHERE TER.BDCGCTER = (SELECT FIRST 1 BDCGCTER FROM TTERCEIRO WHERE BDCODTER = :WCODTER)
                          UNION ALL
                          SELECT RH.BDCODTER FROM TTERCEIRO_RH RH WHERE RH.BDCPFMEITER = (SELECT FIRST 1 BDCPFMEITER FROM TTERCEIRO_RH WHERE BDCODTER = :WCODTER AND CHAR_LENGTH(BDCPFMEITER) = 14)
                         ) FILTRO ON EVTPROC.BDCODTER = FILTRO.BDCODTER
                    WHERE EVTPROC.BDCODTIPO = 38 AND
                          EVTPROC.BDEVENTOEXCLUSAO = 14 AND
                          (EVTPROC.BDSTATUS = 0 OR EVTPROC.BDSTATUS = 1) and (EVTPROC.BDCODTER > 0))
                into :WCODEMPTAB1
              do
              begin
                WSUSPEND = 'false';
                WMSG = WMSG || ' ' || 'Possuí S-3000 de S-1210 aguardando ou enviado, esperando retorno.';
              end
            end

            if ((:BDCODTIPO = 14) and
                (WSUSPEND='true')) then
            begin
              for SELECT FIRST 1 BDCODEMP FROM (
                  SELECT FIRST 1 EVTPROC.BDCODEMP
                  FROM VRH_ESOCIAL_TARQUIVO EVTPROC
                  JOIN SP_MATRIZ_E_FILIAIS('BDCODEMP = '||:BDCODEMP||'') EMP ON EVTPROC.BDCODEMP = EMP.BDCODEMP
                  JOIN (SELECT COL.BDCODEMP, COL.BDCODCOL FROM VRH_EMP_TCOLCON COL WHERE bdcpfcol = (select first 1 bdcpfcol from vrh_emp_tcolcon where bdcodemp = :BDCODEMP and bdcodcol = :BDCODCOL)
                       ) FILTRO ON EVTPROC.BDCODEMP = FILTRO.BDCODEMP AND EVTPROC.BDCODCOL = FILTRO.BDCODCOL
                  WHERE (EVTPROC.BDCODTIPO = 11 or EVTPROC.BDCODTIPO = 34 or (EVTPROC.BDCODTIPO = 37)) and
                        (EVTPROC.BDSTATUS = 0 or EVTPROC.BDSTATUS = 1) --1200/2299/2399
                  UNION
                  SELECT FIRST 1 EVTPROC.BDCODEMP
                  FROM VRH_ESOCIAL_TARQUIVO EVTPROC
                  JOIN SP_MATRIZ_E_FILIAIS('BDCODEMP = '||:BDCODEMP||'') EMP ON EVTPROC.BDCODEMP = EMP.BDCODEMP
                  JOIN (SELECT TER.BDCODTER FROM TTERCEIRO TER WHERE TER.BDCGCTER = (SELECT FIRST 1 BDCGCTER FROM TTERCEIRO WHERE BDCODTER = :WCODTER)
                        UNION ALL
                        SELECT RH.BDCODTER FROM TTERCEIRO_RH RH WHERE RH.BDCPFMEITER = (SELECT FIRST 1 BDCPFMEITER FROM TTERCEIRO_RH WHERE BDCODTER = :WCODTER AND CHAR_LENGTH(BDCPFMEITER) = 14)
                       ) FILTRO ON EVTPROC.BDCODTER = FILTRO.BDCODTER
                  WHERE (EVTPROC.BDCODTIPO = 11 or EVTPROC.BDCODTIPO = 34 or (EVTPROC.BDCODTIPO = 37)) and
                        (EVTPROC.BDSTATUS = 0 or EVTPROC.BDSTATUS = 1) and (EVTPROC.BDCODTER > 0) --1200/2299/2399
                  )
                    into :WCODEMPTAB1 do
              begin
                WSUSPEND = 'false';
                WMSG = 'Possui S-1200 ou S-2299 ou S-2399 aguardando ou enviado, esperando retorno.';
              end
            end

            if ((:BDCODTIPO in (11,14,20)) and (WSUSPEND='true')) then     -- 1200,1210,1299
            begin
              for select bdcodemp from tempresas
                  where bdcodemp = coalesce(:bdcodempmatriz,:bdcodemp) or
                  bdcodmatriz = coalesce(:bdcodempmatriz,:bdcodemp) into :WEMPAUX do
                  begin
                    for select first 1 EVTPROC.BDCODTIPO
                       from VRH_ESOCIAL_TARQUIVO EVTPROC
--                       join tempresas e on (e.bdcodemp = EVTPROC.bdcodemp)
                       where --EVTPROC.BDCODEMP = (:BDCODEMP) and
                             EVTPROC.BDCODEMP = :WEMPAUX and
                             (EVTPROC.BDCODTIPO = 19 or EVTPROC.BDCODTIPO = 20) and  --1298/1299
                             (EVTPROC.BDSTATUS = 2) and
                             (EVTPROC.BDREFARQ = :WREFARQ)
                       order by EVTPROC.BDDATARETORNO desc, EVTPROC.BDHORARETORNO desc
                       into :WCODEMPTAB1 do
                      begin
                       if (WCODEMPTAB1 = 20) then
                         begin
                            WSUSPEND = 'false';
                            WMSG = 'O período precisa ser reaberto antes de enviar esse evento.';
                          end
                      end

                      if (WSUSPEND = 'false') then
                         break;
                  end
            end
          end
          else
          begin
            if (:BDCODTIPO not in (1, 2)) then -- 2190,2200,2300
            begin
              WSUSPEND = 'false';
              WMSG = WMSG || ' ' || ' Possui S-1005 aguardando ou enviado, esperando retorno.';
            end
          end

          if (WTEMS2501OUS2555PENDENTE = 'true') then
            begin
              WSUSPEND = 'false';
              WMSG = WMSG || ' ' || ' Possui S-2501 ou S-3500 aguardando ou enviado, esperando retorno.';
            end
        end
      end
      else
      begin
        if ((:BDCODTIPO = 38) and (wSuspend='true'))  then
        begin
          if (:BDEVENTOEXCLUSAO in (23)) then --Se for excluir um 2199 tiver qualquer evento integrado não pode enviar
          begin
            for select first 1 BDCODTIPO
                from VRH_ESOCIAL_TARQUIVO
                where BDCODEMP = :BDCODEMP and
                      BDCODCOL = :BDCODCOL and
                      (BDCODTIPO <> 23 and
                      BDCODTIPO <> 38) and
                      BDSTATUS = 2
                order by BDCODTIPO desc
                into :WCODTIPOEXCLU
            do
            begin
              WSUSPEND = 'false';
              WMSG = 'Possui S-2200 integrado. Não é possível excluir.';
            end
          end
          else
          if (:BDEVENTOEXCLUSAO in (24, 35)) then --Se for excluir um 2199,2200 ou 2300 e tiver qualquer evento integrado não pode enviar
          begin
            WMSG = '';
            for select TIPO.BDCODTIPO, substring(TIPO.BDDESCRICAO from 0 for 7) BDDESCRICAOTIPO
                from VRH_ESOCIAL_TARQUIVO ARQ
                join VRH_ESOCIAL_TTIPO_ARQ TIPO on ARQ.BDCODTIPO = TIPO.BDCODTIPO
                where BDCODEMP = :BDCODEMP and
                      BDCODCOL = :BDCODCOL and
                      (ARQ.BDCODTIPO <> 23 and
                      ARQ.BDCODTIPO <> 24 and
                      ARQ.BDCODTIPO <> 35 and
                      ARQ.BDCODTIPO <> 38) and
                      BDSTATUS = 2
                group by TIPO.BDCODTIPO, BDDESCRICAOTIPO
                order by BDCODTIPO desc
                into :WCODTIPOEXCLU, :WDESCTIPO
            do
            begin
              WSUSPEND = 'false';
              WMSG = WMSG || :WDESCTIPO || ',';
            end
            if (not(WSUSPEND= 'true')) then
            begin
              if (char_length(WMSG) > 6) then
                WMSG = 'Possui evento dos tipos ' || WMSG || ' integrados. Não é possível enviar a exclusão.';
              else
                WMSG = 'Possui evento do tipo ' || WMSG || ' integrado. Não é possível enviar a exclusão.';
            end
          end
          else
          if (:BDEVENTOEXCLUSAO = 11) then -- 1200
          begin
            :WREF1210 = null;
            select first 1 coalesce(BDREFIRRFESOCIAL, 0)
            from (select BDREFIRRFESOCIAL
                  from VRHF_EMP_TFOLHANORMAL
                  where BDCODEMP = :BDCODEMP and
                        BDCODCOL = :BDCODCOL and
                        BDREFFN = :WREFARQ
                  union all
                  select BDREFIRRFESOCIAL
                  from VRHF_EMP_TFOLHATOMADOR
                  where BDCODEMP = :BDCODEMP and
                        BDCODCOL = :BDCODCOL and
                        BDREFTOMADOR = :WREFARQ)
            into :WREF1210;

            if (Coalesce(:WREF1210,0) <> 0) then
            begin
              :WCODEMPTAB1 = null;
              select first 1 coalesce(BDCODEMP, 0)
              from VRH_ESOCIAL_TARQUIVO
              where BDCODEMP = :BDCODEMP and
                    BDCODCOL = :BDCODCOL and
                    BDREFARQ = :WREF1210 and
                    BDCODTIPO = 14 and
                    BDSTATUS = 2
              into :WCODEMPTAB1;

              if (Coalesce(WCODEMPTAB1,0) <> 0) then
              begin
                WSUSPEND = 'false';
                WMSG = 'Possuí S-1210 integrado para esta remuneração.';
              end
            end

          end
          else
          if (:BDEVENTOEXCLUSAO = (34)) then --2299
          begin
            :WREF1210 = null;
            select BDREFPAGRESCISAO
            from VRH_EMP_TRESCISAO
            where BDCODEMP = :BDCODEMP and
                  BDCODCOL = :BDCODCOL
            into :WREF1210;
            if (Coalesce(:WREF1210,0) <> 0) then
            begin
             :WCODEMPTAB1 = null;
              select first 1 coalesce(BDCODEMP, 0)
              from VRH_ESOCIAL_TARQUIVO
              where BDCODEMP = :BDCODEMP and
                    BDCODCOL = :BDCODCOL and
                    BDREFARQ = :WREF1210 and
                    BDCODTIPO = 14 and
                    BDSTATUS = 2
              into :WCODEMPTAB1;

              if (Coalesce(WCODEMPTAB1,0) <> 0) then
              begin
                WSUSPEND = 'false';
                WMSG = 'Possuí S-1210 integrado para esta remuneração.';
              end
            end
          end
          else
          if (:BDEVENTOEXCLUSAO = (37)) then --2399
          begin
            select substring(BDDATAPAGBAIXACOL from 1 for 4) || substring(BDDATAPAGBAIXACOL from 6 for 2) BDDATAPAGBAIXACOL
            from VRH_EMP_TCON_DOC
            where BDCODEMP = :BDCODEMP and
                  BDCODCOL = :BDCODCOL
            into :WREF1210;
            if (Coalesce(:WREF1210,0) <> 0) then
            begin
              :WCODEMPTAB1 = null;
              select first 1 coalesce(BDCODEMP, 0)
              from VRH_ESOCIAL_TARQUIVO
              where BDCODEMP = :BDCODEMP and
                    BDCODCOL = :BDCODCOL and
                    BDREFARQ = :WREF1210 and
                    BDCODTIPO = 14 and
                    BDSTATUS = 2
              into :WCODEMPTAB1;

              if (Coalesce(WCODEMPTAB1,0) <> 0) then
              begin
                WSUSPEND = 'false';
                WMSG = 'Possuí S-1210 integrado para esta remuneração.';
              end
            end
          end
        end
        else
        if (:BDCODTIPO in (1, 2)) then
        begin
          WCODTIPOEXCLU = null;
          select first 1 coalesce(TIPO.BDCODTIPO, 0), TIPO.BDDESCRICAO
          from VRH_ESOCIAL_TARQUIVO ARQ
          join VRH_ESOCIAL_TTIPO_ARQ TIPO on ARQ.BDCODTIPO = TIPO.BDCODTIPO
          where BDCODEMP = :BDCODEMP and
                BDCHAVE <> :BDCHAVE and
                BDMOTIVOINT = 2
          into :WCODTIPOEXCLU, :WDESCTIPO;

          if (Coalesce(WCODTIPOEXCLU,0) <> 0) then
          begin
            WSUSPEND = 'false';
            WMSG = 'Possui evento' || :WDESCTIPO || ' de exclusão pendente.';
          end
        end
      end

      if (bdcodtipo in (49,50,51)) then
         begin
           if (coalesce(upper(wapenasrt),'FALSE') = 'TRUE') then
              begin
                WSUSPEND='true';
              end
         end

      if ((bdcodtipo = 34) and ((upper(worigem)) = (upper('frLancamentoProcessoTrabalhista')))) then
         begin
           WSUSPEND = case
                          when exists(select 1 from VRH_ESOCIAL_TARQUIVO -- se existir um S-3000 de evt tipo 34(S-2299) com status pendente ou enviando
                                      where BDCODEMP = :bdcodemp and     -- não deve enviar um novo S-2299
                                            BDCODCOL = :bdcodcol and
                                            BDREFARQ >= :wrefarq and
                                            BDCODTIPO = 38 and
                                            BDEVENTOEXCLUSAO = 34 and
                                            BDSTATUS in (0, 1, 3, 4)) then 'false' else 'true'
                      end;
           if (wsuspend = 'false') then
              WMSG = WMSG || ' ' || 'Existe um evento de exclusão com status "pendente", "enviando" ou "erro".';
         end

      if ((bdcodtipo = 11) and ((upper(worigem)) = (upper('frLancamentoProcessoTrabalhista')))) then
         begin
           WSUSPEND = case
                          when exists(select 1 from VRH_ESOCIAL_TARQUIVO -- se existir um S-2299 com status pendente ou enviando
                                      where BDCODEMP = :bdcodemp and     -- não deve enviar um novo S-1200
                                            BDCODCOL = :bdcodcol and
                                            BDREFARQ <= :wrefarq and
                                            BDCODTIPO = 34 and
                                            BDSTATUS in (0, 1, 3, 4)) then 'false' else 'true'
                      end;
           if (wsuspend = 'false') then
              WMSG = WMSG || ' ' || 'Existe um evento de desligamento com status "pendente", "enviando" ou "erro".';
         end

      -- Se existir algum evento pendente Status (0,1,3,4) de 1200/1202/1210/1250/1260/1270/1280/2299/2399/3000 deles
      if (bdcodtipo = 20) then
         begin
           if (wsuspend = 'true') then
              begin
                for select bdcodemp from tempresas
                  where bdcodemp = coalesce(:bdcodempmatriz,:bdcodemp) or
                  bdcodmatriz = coalesce(:bdcodempmatriz,:bdcodemp) into :WEMPAUX do
                  begin
                    wtipoevtpendente = null;
                    select first 1 a.bdcodtipo,t.bddescricao
                    from vrh_esocial_tarquivo a
--                    join tempresas e on (e.bdcodemp = a.bdcodemp)
                    join vrh_esocial_ttipo_arq t on (a.bdcodtipo = t.bdcodtipo)
                    where a.BDCODEMP = :wempaux and
                          a.BDREFARQ = :wrefarq and
                          a.BDCODTIPO in (11,12,14,15,16,17,18,34,37) and
                          a.BDSTATUS in (0, 1, 3, 4, 9)
                          into :wtipoevtpendente, :wdesctipoarq;
    
                    if (wtipoevtpendente is not null) then
                       begin
                         wsuspend = 'false';
                         WMSG = WMSG || ' ' || 'Existe um evento '||wdesctipoarq||' com status "pendente", "enviando" ou "erro".';
                       end

                    if (wsuspend = 'false') then
                       break;
                  end
              end     

           -- Verifica se existe alguma exclusão de eventos de fechamento
           if (wsuspend = 'true') then
              begin
                wtipoevtpendente = null;
                for select bdcodemp from tempresas
                  where bdcodemp = coalesce(:bdcodempmatriz,:bdcodemp) or
                  bdcodmatriz = coalesce(:bdcodempmatriz,:bdcodemp) into :WEMPAUX do
                  begin
                    select first 1 a.bdcodtipo,t.bddescricao from vrh_esocial_tarquivo a
--                    join tempresas e on (e.bdcodemp = a.bdcodemp)
                    join vrh_esocial_ttipo_arq t on (a.bdcodtipo = t.bdcodtipo)
                    where a.BDCODEMP = :wEmpAux and
                          a.BDREFARQ = :wrefarq and
                          a.bdcodtipo = 38 and
                          a.bdeventoexclusao in (11,12,14,15,16,17,18,34,37) and
                          a.BDSTATUS in (0, 1, 3, 4)
                          into :wtipoevtpendente, :wdesctipoarq;
    
                    if (wtipoevtpendente is not null) then
                       begin
                         wsuspend = 'false';
                         WMSG = WMSG || ' ' || 'Existe um evento de exclusão de '||wdesctipoarq||' com status "pendente", "enviando" ou "erro".';
                       end

                    if (wsuspend = 'false') then
                       break;
                  end
              end
         end

      if ((BDCODTIPO = 49) and ((coalesce(WCONTRENVIO2500, 0) = -1))) then  -- Não envia S-2500 caso tiver S-2200 pendente/enviando/erro
         begin
           WSUSPEND = case
                          when (exists(select first 1 EVTPROC.BDCODEMP from VRH_ESOCIAL_TARQUIVO EVTPROC
                                       where EVTPROC.BDCODEMP in (:BDCODEMPMATRIZ, :BDCODEMP) and
                                             EVTPROC.BDCODTIPO = 24 and
                                             EVTPROC.BDCODCOL = :BDCODCOL and
                                             EVTPROC.BDSTATUS not in (0, 1, 3, 4))) then 'false' else 'true'
                      end;
           if (wsuspend = 'false') then
              WMSG = WMSG || ' ' || 'Existe um evento S-2200 com status "pendente", "enviando" ou "erro".';
         end

      if ((BDCODTIPO = 49) and ((coalesce(WCONTRENVIO2500, 0) = -2))) then  -- Não envia S-2500 caso tiver S-1200/1210/2299/2399 com status pendente/enviando/erro
         begin
           WSUSPEND = case
                          when (exists(select first 1 EVTPROC.BDCODEMP from VRH_ESOCIAL_TARQUIVO EVTPROC
                                       where EVTPROC.BDCODEMP in (:BDCODEMPMATRIZ, :BDCODEMP) and
                                             EVTPROC.BDCODTIPO in (11, 14, 34, 37) and
                                             EVTPROC.BDCODCOL = :BDCODCOL and
                                             EVTPROC.BDSTATUS in (0, 1, 3, 4))) then 'false' else 'true'
                      end;
           if (wsuspend = 'false') then
              WMSG = WMSG || ' ' || 'Existe um evento S-1200/1210/2299/2399 com status "pendente", "enviando" ou "erro".';
         end

       if ((BDCODTIPO = 49) and ((coalesce(WCONTRENVIO2500, 0) = -3))) then  -- Não envia S-2500 caso tiver S-1200/1210/2200/2299/2399 com status pendente/enviando/erro
         begin
           WSUSPEND = case
                          when (exists(select first 1 EVTPROC.BDCODEMP from VRH_ESOCIAL_TARQUIVO EVTPROC
                                       where EVTPROC.BDCODEMP in (:BDCODEMPMATRIZ, :BDCODEMP) and
                                             EVTPROC.BDCODTIPO in (11, 14, 24, 34, 37) and
                                             EVTPROC.BDCODCOL = :BDCODCOL and
                                             EVTPROC.BDSTATUS in (0, 1, 3, 4))) then 'false' else 'true'
                      end;
           if (wsuspend = 'false') then
              WMSG = WMSG || ' ' || 'Existe um evento S-1200/1210/2200/2299/2399 com status "pendente", "enviando" ou "erro".';
         end
      -------------------------
      if ((WEMPRESA_ATUAL = 0) or (WEMPRESA_ATUAL <> BDCODEMP)) then
      begin
        WEMPRESA_ATUAL = BDCODEMP;
        WCODTIPO = 0;
        WGRUPO = 0;
      end
      if (WSUSPEND='true') then
      begin
        if ((WCODTIPO = 0) and
            (WGRUPO = 0)) then
        begin
          if (BDGRUPO in (1, 3)) then
            WCODTIPO = BDCODTIPO;
          else
            WGRUPO = BDGRUPO;
        end
      end

      if ((((BDGRUPO in (1, 3)) and
          (WCODTIPO = BDCODTIPO)) or ((BDGRUPO = 2) and
          (WGRUPO = BDGRUPO))) and
          (WSUSPEND='true')) then
        suspend;

      if (not(WSUSPEND='true') and
          (:WMSG <> '')) then
      begin
        update VRH_ESOCIAL_TARQUIVO
        set BDDESCNAOENVIA = :WMSG
        where BDCODEMP = :BDCODEMP and
              BDCODIGO = :BDCODIGO and Coalesce(BDDESCNAOENVIA,'')<>:WMSG;
      end
    end
  end
end^

CREATE OR ALTER PROCEDURE SP_COPIA_PLANOCONFDRCST (
    PRCODIGOCOPIADO INTEGER,
    PRCODIGONOVO INTEGER)
AS
BEGIN
  DELETE FROM VEF_BASE_TPLANOACOESCONFDRCST WHERE BDCODPLACONFDRCST = :prcodigonovo;


  INSERT INTO VEF_BASE_TPLANOACOESCONFDRCST (BDCODPLACONFDRCST, BDCHAVE, BDTIPOOPER, BDMVASTORIGINAL, BDALIQINTERNA, BDALIQINTERESTADUAL,
                                             BDMVAAJUSTADA, BDMVARED, BDGERAE111, BDGERAC197, BDTPALIQINTERNA, BDTPALIQINTERESTADUAL,
                                             BDCODAJU_GERAC197, BDCODAJUICMS_CRED, BDCODAJUICMS_DEB, BDBUSCAC197, BDQTDFILTRO, BDCODOBSC197)
  SELECT :prcodigonovo, C.BDCHAVE, C.BDTIPOOPER, C.BDMVASTORIGINAL, C.BDALIQINTERNA, C.BDALIQINTERESTADUAL,
         C.BDMVAAJUSTADA, C.BDMVARED, C.BDGERAE111, C.BDGERAC197, C.BDTPALIQINTERNA, C.BDTPALIQINTERESTADUAL,
         C.BDCODAJU_GERAC197, C.BDCODAJUICMS_CRED, C.BDCODAJUICMS_DEB, C.BDBUSCAC197, C.BDQTDFILTRO, C.BDCODOBSC197
  FROM VEF_BASE_TPLANOACOESCONFDRCST C WHERE C.BDCODPLACONFDRCST = :prcodigocopiado;

  INSERT INTO VEF_BASE_TVINCCODPLANODRCST (BDCODPLACONFDRCST, BDCHAVE, BDORDEM, BDCODTER_FIL, BDCODNAT_FIL, BDCODPROD_FIL,
                                           BDNCMPROD_FIL, BDCODCSTICMS_FIL, BDCODAJU_C197, BDCODNAT_VENDAS, BDCODNAT_COMPRAS)
  SELECT :prcodigonovo BDCODPLACONFDRCST, C.BDCHAVE, C.BDORDEM, C.BDCODTER_FIL, C.BDCODNAT_FIL, C.BDCODPROD_FIL,
          C.BDNCMPROD_FIL, C.BDCODCSTICMS_FIL, C.BDCODAJU_C197, C.BDCODNAT_VENDAS, C.BDCODNAT_COMPRAS
  FROM VEF_BASE_TVINCCODPLANODRCST C WHERE C.BDCODPLACONFDRCST = :prcodigocopiado;

END
^

CREATE OR ALTER PROCEDURE SP_COPIA_PLANOCONFADRCST (
    PRCODIGOCOPIADO INTEGER,
    PRCODIGONOVO INTEGER)
AS
BEGIN
  DELETE FROM VEF_BASE_TPLANOACOESCONFADRCST WHERE BDCODPLANOCONFADRCST = :PRCODIGONOVO;


  INSERT INTO VEF_BASE_TPLANOACOESCONFADRCST (BDCODPLANOCONFADRCST, BDCHAVE, BDCODPROCESSO, BDPARTENQFED, BDCONSUFINAL, BDQTDFILTRO)
  SELECT :PRCODIGONOVO BDCODPLANOCONFADRCST, C.BDCHAVE, C.BDCODPROCESSO, C.BDPARTENQFED, C.BDCONSUFINAL, C.BDQTDFILTRO
  FROM VEF_BASE_TPLANOACOESCONFADRCST C WHERE C.BDCODPLANOCONFADRCST = :PRCODIGOCOPIADO;

  INSERT INTO VEF_BASE_TVINCCODPLANOADRCST (BDCODPLANOCONFADRCST, BDCHAVE, BDORDEM, BDCODNAT, BDCODNCM, BDCODPROD, BDCODTER, BDCSTICMS)
  SELECT :PRCODIGONOVO BDCODPLANOCONFADRCST, C.BDCHAVE, C.BDORDEM, C.BDCODNAT, C.BDCODNCM, C.BDCODPROD, C.BDCODTER, C.BDCSTICMS
  FROM VEF_BASE_TVINCCODPLANOADRCST C WHERE C.BDCODPLANOCONFADRCST = :PRCODIGOCOPIADO;
END^

create or alter procedure SP_APURACAO_DRCST_2113 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN                                             
  DELETE FROM TMP_VEF_EMP_DRCST_2113ENT_TEMP WHERE BDSESSAO = :PRSESSAO;

  INSERT INTO TMP_VEF_EMP_DRCST_2113ENT_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD)
  SELECT DISTINCT :PRSESSAO BDSESSAO, GER.BDCODEMP, GER.BDREFERENCIA, MOVPRO.BDCODPROD
  FROM VEF_EMP_TMOVENT MOVE
  JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOVE.BDCODEMP AND I.BDCHAVE = MOVE.BDCHAVE)
  JOIN VEF_EMP_TMOVPROENT MOVPRO ON (MOVPRO.BDCODEMP = I.BDCODEMP AND MOVPRO.BDCHAVE = I.BDCHAVE AND MOVPRO.BDORDEM = I.BDORDEM)
  LEFT OUTER JOIN VEF_BASE_TTABCSTICMS CST ON (CST.BDCODCSTICMS = MOVPRO.BDCODCSTICMS)
  JOIN TMP_VEF_EMP_TDRCSTGER_TEMP GER ON (GER.BDSESSAO = :PRSESSAO AND GER.BDCODEMP = MOVE.BDCODEMP /*AND GER.BDREFERENCIA = mov.BDREFERENCIA*/)
  LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = MOVE.BDCODTER)
  WHERE (MOVE.BDREFLAN BETWEEN(SELECT BDREFERENCIA FROM DEC_REFERENCIA(GER.BDREFERENCIA, 12)) AND GER.BDREFERENCIA) AND
        MOVE.BDMODELO in (55,65) AND
        ((MOVPRO.bdVLRST > 0) OR (MOVPRO.bdVLRICMSSTRET > 0)) AND
        CHAR_LENGTH(TER.BDCGCTER) = 18 AND -- Apenas quando o participante for um CNPJ
        MOVE.BDCODSITNF NOT IN (2, 3, 4, 5, 6, 7) AND
        ((GER.BDDEV_VENDAS = 'FALSE') AND
        NOT I.BDCODNAT IN (SELECT V.BDCODNAT_VENDAS
                           FROM VEF_BASE_TVINCCODPLANODRCST V
                           WHERE V.BDCODPLACONFDRCST = GER.BDCODPLACONFDRCST AND
                                 V.BDCODNAT_VENDAS IS NOT NULL)) AND
        --MOVPRO.BDCODPROD = MOV.BDCODPROD AND
        MOVPRO.BDQTDITEM > 0;

  insert into TMP_VEF_EMP_TDRCST_2113_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO, BDIND_S, BDCHV_NFE,
                                            BDDT_NFE, BDDT_E, BDCODTER, BDNOMTER, BDCNPJ, BDCPF, BDNUM_ITEM, BDQTDE_IND_S, BDCODUNIMED, BDUNID, BDCODFATCON, BDFAT_CONV,
                                            BDQTDE_IND_S_C, BDVL_V_IND_S, BDCODNAT, BDCFOP, BDVL_CREDITO_MVA_SN, BDALIQ_EF, BDCODCSTICMS,
                                            BDALIQ_IE_PRO, BDALIQ_IE_UFORI, BDALIQ_IE_UFDEST, BDALIQ_IE_NF, BDALIQ_I_PRO, BDALIQ_I_UF, BDCODPLACONFDRCST, BDLISTCOMP)
  SELECT :PRSESSAO BDSESSAO, S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD, S.BDIND_OPER, S.BDCHAVE, S.BDORDEM, S.BDORDEMPRO,
         iif(TER.BDENQSIMPLESFEDTER in (0,1), 30, S.BDIND_S) AS BDIND_S, S.BDCHV_NFE,
         S.BDDT_NFE, S.BDDT_E, S.BDCODTER, TER.BDNOMETER AS BDNOMTER,
         IIF(CHAR_LENGTH(TER.BDCGCTER) = 14,null, TER.BDCGCTER) BDCNPJ, IIF(CHAR_LENGTH(TER.BDCGCTER) = 14,TER.BDCGCTER, null) BDCPF,
         S.BDORDEMPRO BDNUM_ITEM, S.BDQTDE_IND_S, Coalesce(UNIFATCONV.BDCODUNIMED,UNIPRO.BDCODUNIMED), Coalesce(UNIFATCONV.BDAPEUNIMED,UNIPRO.BDAPEUNIMED) BDUNID, S.BDCODFATCON, F.BDFATORCONVER BDFAT_CONV,
         (Coalesce(F.BDFATORCONVER,1) * S.BDQTDE_IND_S) BDQTDE_IND_S_C, S.BDVL_V_IND_S, S.BDCODNAT, S.BDCFOP, S.BDVL_CREDITO_MVA_SN, Coalesce(PROD.BDALIQICMSEFETIVO, uf.BDALIQINT) BDALIQ_EF,
         S.BDCODCSTICMS, PROD.BDALIQICMS BDALIQ_IE_PRO, S.BDALIQ_ORIGEM BDALIQ_IE_UFORI, S.BDALIQ_DESTINO BDALIQ_IE_UFDEST,
         S.BDALIQICMS BDALIQ_IE_NF, PROD.BDALIQICMS BDALIQ_I_PRO, UF.BDALIQINT BDALIQ_I_UF, S.BDCODPLACONFDRCST, s.bdLISTCOMP
  FROM (  SELECT S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD, S.BDIND_OPER, S.BDCHAVE, S.BDORDEM, S.BDORDEMPRO, S.BDCHAVENFE BDCHV_NFE, S.BDDT_NFE,
                 S.BDDT_E, S.BDCODTER, Coalesce(S.BDQTDITEM,0) BDQTDE_IND_S, S.BDCODFATCON, S.BDVLRITEM BDVL_V_IND_S, S.BDCODNAT, S.BDCODNAT BDCFOP, S.BDVL_CREDITO_MVA_SN,
                 S.BDALIQICMS, S.BDALIQ_DESTINO, S.BDALIQ_ORIGEM, S.BDIND_S, S.BDCODCSTICMS, S.BDCODPLACONFDRCST, s.bdLISTCOMP
          FROM( SELECT mov.bdCODEMP, mov.BDREFERENCIA AS bdREFERENCIA, mov.bdCODPROD, 0 AS bdIND_OPER, mov.bdCHAVE, mov.bdORDEM, mov.bdORDEMPRO,
                       mov.bdCHAVENFE, mov.bdDATAEMISSAO bdDT_NFE, NULL AS bdDT_E, mov.bdCODTER, mov.bdQTDITEM, mov.bdCODFATCON,
                       mov.bdVLRITEM, mov.bdCODNAT, 0 AS bdVL_CREDITO_MVA_SN, mov.bdALIQICMS,
                       (SELECT FIRST 1 bdALIQ_DESTINO FROM TUF_ALIQEXT ex WHERE ex.bdCODUF = 24) AS bdALIQ_DESTINO, -- SC
                       (SELECT FIRST 1 bdALIQ_ORIGEM  FROM TUF_ALIQEXT ex WHERE ex.bdCODUF = 24) AS bdALIQ_ORIGEM,  -- SC
                       CASE
                         WHEN mov.bdCONSUFINAL = 1 THEN 10
                         WHEN SUBSTRING(mov.bdCODNAT FROM 1 FOR 1) = '6'  THEN 20
                         ELSE NULL
                       END AS bdIND_S, mov.bdCODCSTICMS, mov.bdCODPLACONFDRCST, mov.bdLISTCOMP
                FROM  (
                        SELECT aux.bdCODEMP, aux.bdCHAVE, aux.BDREFERENCIA, aux.bdCHAVENFE, aux.bdDATAEMISSAO, aux.bdCODTER, aux.bdCONSUFINAL, aux.bdCODPLACONFDRCST,
                               LIST(aux.bdCHAVE_COMP||'.'||aux.bdORDEM_COMP||'.'||aux.bdORDEMPRO_COMP) AS BDLISTCOMP,
                               aux.bdMODELO, aux.bdCODSITNF, aux.bdORDEM, aux.bdCODNAT, aux.bdCODPROD, aux.bdORDEMPRO, SUM(aux.bdQTDITEM) AS bdQTDITEM,
                               aux.bdCODFATCON, SUM(aux.bdVLRITEM) AS bdVLRITEM, aux.bdALIQICMS, aux.bdCODCSTICMS, SUM(aux.bdVLRST) AS bdVLRST, SUM(aux.bdVLRICMSSTRET) AS BDVLRICMSSTRET
                        FROM (
                               SELECT m.bdCODEMP, m.bdCHAVE, GER.BDREFERENCIA, m.bdCHAVENFE, m.bdDATAEMISSAO, m.bdCODTER, m.bdCONSUFINAL, m.bdMODELO, m.bdCODSITNF,
                                      i.bdORDEM, i.bdCODNAT, ger.bdCODPLACONFDRCST, NULL AS bdCHAVE_COMP, NULL AS BDORDEM_COMP, NULL AS BDORDEMPRO_COMP,
                                      movpro.bdCODPROD, movpro.bdORDEMPRO, movpro.bdQTDITEM, movpro.bdCODFATCON, COALESCE(movpro.bdVLRITEM,0) AS bdVLRITEM,
                                      movpro.bdALIQICMS, movpro.bdCODCSTICMS, COALESCE(movpro.bdVLRST,0) AS bdVLRST, COALESCE(movpro.bdVLRICMSSTRET,0) AS BDVLRICMSSTRET
                               FROM TMP_VEF_EMP_TDRCSTGER_TEMP GER
                               INNER JOIN VEF_EMP_TMOVSAI m ON (m.bdCODEMP = ger.bdCODEMP AND m.bdREFLAN = ger.bdREFERENCIA)
                               INNER JOIN VEF_EMP_TMOVSAIITENS i ON (i.bdCODEMP = m.bdCODEMP AND i.bdCHAVE = m.bdCHAVE)
                               INNER JOIN VEF_EMP_TMOVPROSAI movpro ON (movpro.bdCODEMP = i.bdCODEMP AND movpro.bdCHAVE = i.bdCHAVE AND movpro.bdORDEM = i.bdORDEM)
                               WHERE ger.bdSESSAO = :prSESSAO
                                 AND m.bdMODELO in (55,65)
                                 AND m.bdCODSITNF NOT IN (2, 3, 4, 5, 6, 7)
                                 AND ((ger.bdDEV_COMPRAS = 'FALSE') AND
                                      (NOT i.bdCODNAT IN (SELECT v.bdCODNAT_COMPRAS
                                                          FROM VEF_BASE_TVINCCODPLANODRCST v
                                                          WHERE v.bdCODPLACONFDRCST = ger.bdCODPLACONFDRCST AND
                                                                v.bdCODNAT_COMPRAS IS NOT NULL)))
                               UNION ALL
                               /* Quando for documento complementar, vai somar os valores dos produtos no primeiro produto da nota a ser complementada...
                                  6 - Documento Fiscal Complementar
                                  7 - Escrituração extemporânea de documento complementar */
                               SELECT mAux.bdCODEMP, mAux.bdCHAVE, GER.BDREFERENCIA, mAux.bdCHAVENFE, mAux.bdDATAEMISSAO, mAux.bdCODTER, mAux.bdCONSUFINAL, mAux.bdMODELO, mAux.bdCODSITNF,
                                      iAux.bdORDEM, iAux.bdCODNAT, ger.bdCODPLACONFDRCST, m.bdCHAVE AS bdCHAVE_COMP, movPro.bdORDEM AS BDORDEM_COMP, movPro.bdORDEMPRO AS BDORDEMPRO_COMP,
                                      movProAux.bdCODPROD, movProAux.bdORDEMPRO, SUM(movPro.bdQTDITEM) AS bdQTDITEM, movProAux.bdCODFATCON, SUM(COALESCE(movPro.bdVLRITEM,0)) AS bdVLRITEM,
                                      movProAux.bdALIQICMS, movProAux.bdCODCSTICMS, SUM(COALESCE(movPro.bdVLRST,0)) AS bdVLRST, SUM(COALESCE(movpro.bdVLRICMSSTRET,0)) AS BDVLRICMSSTRET
                               FROM TMP_VEF_EMP_TDRCSTGER_TEMP GER
                               INNER JOIN VEF_EMP_TMOVSAI m ON (m.bdCODEMP = ger.bdCODEMP /*AND m.bdREFLAN = ger.bdREFERENCIA*/) -- Alt.: #151329 - A referencia, deve pesquisar na nota lançada e não na complementar...
                               INNER JOIN VEF_EMP_TMOVSAIITENS i ON (i.bdCODEMP = m.bdCODEMP AND i.bdCHAVE = m.bdCHAVE)
                               INNER JOIN VEF_EMP_TMOVPROSAI movPro ON (movPro.bdCODEMP = i.bdCODEMP AND movPro.bdCHAVE = i.bdCHAVE AND movPro.bdORDEM = i.bdORDEM)
                               INNER JOIN VEF_EMP_TMOVSAIDOCFREF c113 ON (c113.bdCODEMP = m.bdCODEMP AND c113.bdCHAVE = m.bdCHAVE)
                               INNER JOIN VEF_BASE_TTABDOCFIS docFisc ON (docFisc.bdCODDOCFIS = c113.bdCODDOCFIS AND (docFisc.bdDOCFIS = '55' or docFisc.bdDOCFIS = '65' )) -- #199391 DRCST - NFCe Modelo 65
                               INNER JOIN VEF_EMP_TMOVSAI mAux ON (mAux.bdCODEMP = c113.bdcodemp AND mAux.bdREFLAN = ger.bdREFERENCIA AND -- Alt.: #151329 - A referencia, deve pesquisar na nota lançada...
                                                                   mAux.bdCHAVENFE = c113.bdCHAVENFE AND mAux.bdCODSITNF NOT IN (2, 3, 4, 5, 6, 7)) -- Vincula apenas pela Chave NF-e...
                               LEFT OUTER JOIN (SELECT i.bdCODEMP, i.bdCHAVE, MIN(i.bdORDEM) AS bdORDEM, MIN(i.bdCODNAT) AS bdCODNAT
                                           FROM VEF_EMP_TMOVSAIITENS i
                                           GROUP BY i.bdCODEMP, i.bdCHAVE) iAux ON (iAux.bdCODEMP = mAux.bdCODEMP AND iAux.bdCHAVE = mAux.bdCHAVE)
                               LEFT OUTER JOIN (SELECT p.bdCODEMP, p.bdCHAVE, p.bdORDEM, MIN(p.bdORDEMPRO) AS bdORDEMPRO, p.bdCODPROD, p.bdALIQICMS, p.bdCODCSTICMS, p.bdCODFATCON
                                           FROM VEF_EMP_TMOVPROSAI p
                                           GROUP BY p.bdCODEMP, p.bdCHAVE, p.bdORDEM, p.bdCODPROD, p.bdALIQICMS, p.bdCODCSTICMS, p.bdCODFATCON) movProAux ON (movProAux.bdCODEMP = iAux.bdCODEMP AND movProAux.bdCHAVE = iAux.bdCHAVE AND movProAux.bdORDEM = iAux.bdORDEM AND movProAux.bdCODPROD = movPro.bdCODPROD)
                               WHERE ger.bdSESSAO = :prSESSAO
                                 AND m.bdMODELO in (55,65)
                                 AND m.bdCODSITNF IN (6, 7)
                                 AND ((ger.bdDEV_COMPRAS = 'FALSE') AND
                                      (NOT i.bdCODNAT IN (SELECT v.bdCODNAT_COMPRAS
                                                          FROM VEF_BASE_TVINCCODPLANODRCST v
                                                          WHERE v.bdCODPLACONFDRCST = ger.bdCODPLACONFDRCST AND
                                                                v.bdCODNAT_COMPRAS IS NOT NULL)))
                               GROUP BY mAux.bdCODEMP, mAux.bdCHAVE, GER.BDREFERENCIA, mAux.bdCHAVENFE, mAux.bdDATAEMISSAO, mAux.bdCODTER, mAux.bdCONSUFINAL, mAux.bdMODELO, mAux.bdCODSITNF,
                                        iAux.bdORDEM, iAux.bdCODNAT, ger.bdCODPLACONFDRCST, m.bdCHAVE, movPro.bdORDEM, movPro.bdORDEMPRO,
                                        movProAux.bdCODPROD, movProAux.bdORDEMPRO, movProAux.bdCODFATCON, movProAux.bdALIQICMS, movProAux.bdCODCSTICMS
                              ) aux
                        GROUP BY aux.bdCODEMP, aux.bdCHAVE, aux.BDREFERENCIA, aux.bdCHAVENFE, aux.bdDATAEMISSAO, aux.bdCODTER, aux.bdCONSUFINAL, aux.bdCODPLACONFDRCST,
                                 aux.bdMODELO, aux.bdCODSITNF, aux.bdORDEM, aux.bdCODNAT, aux.bdCODPROD, aux.bdORDEMPRO, aux.bdCODFATCON, aux.bdALIQICMS, aux.bdCODCSTICMS
                        ) MOV
                WHERE SUBSTRING(mov.bdCODNAT FROM 1 FOR 4) <> '5929' AND
                      SUBSTRING(mov.bdCODNAT FROM 1 FOR 4) <> '6929' AND
                      SUBSTRING(mov.bdCODNAT FROM 1 FOR 1) <> '7'    AND
                      --((mov.bdVLRST > 0) OR Alt.: #222491 - Deve olhar tambem o ST Retido...
                      ((mov.bdVLRST > 0) OR (mov.bdVLRICMSSTRET > 0)
                       or (EXISTS(SELECT FIRST 1 AUX2113.BDCODPROD FROM TMP_VEF_EMP_DRCST_2113ENT_TEMP AUX2113
                                  WHERE AUX2113.BDSESSAO = :PRSESSAO AND AUX2113.BDCODEMP = MOV.BDCODEMP AND AUX2113.BDREFERENCIA = MOV.BDREFERENCIA AND AUX2113.BDCODPROD = MOV.BDCODPROD))
                       )

                UNION ALL
                SELECT mov.bdCODEMP, mov.BDREFERENCIA, mov.bdCODPROD, 1 AS bdIND_OPER, mov.bdCHAVE, mov.bdORDEM, mov.bdORDEMPRO,
                       mov.bdCHAVENFE, NULL AS bdDT_NFE, mov.bdDATAENTRADAENT AS bdDT_E, mov.bdCODTER, mov.bdQTDITEM, mov.bdCODFATCON,
                       mov.bdVLRITEM, mov.bdCODNAT, 0 AS bdVL_CREDITO_MVA_SN, mov.bdALIQICMS,
                       (SELECT FIRST 1 bdALIQ_DESTINO FROM TUF_ALIQEXT EX WHERE EX.bdCODUF = 24) AS bdALIQ_DESTINO, -- SC
                       (SELECT FIRST 1 bdALIQ_ORIGEM  FROM TUF_ALIQEXT EX WHERE EX.bdCODUF = 24) AS bdALIQ_ORIGEM,  -- SC
                       CASE
                         WHEN MOV.bdCONSUFINAL = 1 THEN 10
                         WHEN SUBSTRING(mov.bdCODNAT FROM 1 FOR 1) = '2'  THEN 20
                         ELSE NULL
                       END AS bdIND_S, mov.bdCODCSTICMS, mov.bdCODPLACONFDRCST, mov.bdLISTCOMP
                FROM (

                      SELECT aux.bdCODEMP, aux.bdCHAVE, aux.BDREFERENCIA, aux.bdCHAVENFE, aux.bdDATAENTRADAENT, aux.bdCODTER, aux.bdCONSUFINAL, aux.bdMODELO, aux.bdCODSITNF, aux.bdDATAEMISSAO,
                             aux.bdCODPLACONFDRCST, aux.bdSESSAO, aux.bdDEV_VENDAS,
                             aux.bdORDEM, aux.bdCODNAT, LIST(COALESCE(aux.bdCHAVE_COMP,0)||'.'||COALESCE(aux.bdORDEM_COMP,0)||'.'||COALESCE(aux.bdORDEMPRO_COMP,0)) AS BDLISTCOMP,
                             aux.bdCODPROD, aux.bdORDEMPRO, SUM(aux.bdQTDITEM) AS bdQTDITEM, aux.bdCODFATCON, SUM(aux.bdVLRITEM) AS bdVLRITEM, aux.bdALIQICMS, aux.bdCODCSTICMS, SUM(aux.bdVLRST) AS bdVLRST,
                             SUM(aux.bdVLRICMSSTRET) AS BDVLRICMSSTRET
                      FROM (
                             SELECT mov.bdCODEMP, mov.bdCHAVE, ger.BDREFERENCIA, mov.bdCHAVENFE, mov.bdDATAENTRADAENT, mov.bdCODTER, mov.bdCONSUFINAL, mov.bdMODELO, mov.bdCODSITNF, mov.bdDATAEMISSAO,
                                    ger.bdCODPLACONFDRCST, ger.bdSESSAO, ger.bdDEV_VENDAS,
                                    i.bdORDEM, i.bdCODNAT, NULL AS bdCHAVE_COMP, NULL AS BDORDEM_COMP, NULL AS BDORDEMPRO_COMP,
                                    movpro.bdCODPROD, movpro.bdORDEMPRO, movpro.bdQTDITEM, movpro.bdCODFATCON, COALESCE(movpro.bdVLRITEM,0) AS bdVLRITEM,
                                    movpro.bdALIQICMS, movpro.bdCODCSTICMS, COALESCE(movpro.bdVLRST,0) AS bdVLRST, COALESCE(movpro.bdVLRICMSSTRET,0) AS BDVLRICMSSTRET
                             FROM TMP_VEF_EMP_TDRCSTGER_TEMP ger
                             INNER JOIN VEF_EMP_TMOVENT mov ON (mov.bdCODEMP = ger.bdCODEMP AND mov.bdREFLAN = ger.bdREFERENCIA)
                             INNER JOIN VEF_EMP_TMOVENTITENS i ON (i.bdCODEMP = mov.bdCODEMP AND i.bdCHAVE = mov.bdCHAVE)
                             INNER JOIN VEF_EMP_TMOVPROENT movpro ON (movpro.bdCODEMP = i.bdCODEMP AND movpro.bdCHAVE = i.bdCHAVE AND movpro.bdORDEM = i.bdORDEM)
                             WHERE ger.bdSESSAO = :prSESSAO
                               AND mov.bdMODELO in (55, 65)
                               AND mov.bdCODSITNF NOT IN (2, 3, 4, 5, 6, 7)
                             UNION ALL
                             SELECT mAux.bdCODEMP, mAux.bdCHAVE, ger.BDREFERENCIA, mAux.bdCHAVENFE, mAux.bdDATAENTRADAENT, mAux.bdCODTER, mAux.bdCONSUFINAL, mAux.bdMODELO, mAux.bdCODSITNF, mAux.bdDATAEMISSAO,
                                    ger.bdCODPLACONFDRCST, ger.bdSESSAO, ger.bdDEV_VENDAS,
                                    iAux.bdORDEM, iAux.bdCODNAT, mov.bdCHAVE AS bdCHAVE_COMP, movPro.bdORDEM AS BDORDEM_COMP, movPro.bdORDEMPRO AS BDORDEMPRO_COMP,
                                    movProAux.bdCODPROD, movProAux.bdORDEMPRO, movPro.bdQTDITEM, movProAux.bdCODFATCON, COALESCE(movpro.bdVLRITEM,0) AS bdVLRITEM,
                                    movProAux.bdALIQICMS, movProAux.bdCODCSTICMS, COALESCE(movPro.bdVLRST,0) AS bdVLRST, COALESCE(movpro.bdVLRICMSSTRET,0) AS BDVLRICMSSTRET
                             FROM TMP_VEF_EMP_TDRCSTGER_TEMP ger
                             INNER JOIN VEF_EMP_TMOVENT mov ON (mov.bdCODEMP = ger.bdCODEMP /*AND mov.bdREFLAN = ger.bdREFERENCIA*/) -- Alt.: #151329 - A referencia, deve pesquisar na nota lançada e não na complementar...
                             INNER JOIN VEF_EMP_TMOVENTITENS i ON (i.bdCODEMP = mov.bdCODEMP AND i.bdCHAVE = mov.bdCHAVE)
                             INNER JOIN VEF_EMP_TMOVPROENT movpro ON (movpro.bdCODEMP = i.bdCODEMP AND movpro.bdCHAVE = i.bdCHAVE AND movpro.bdORDEM = i.bdORDEM)
                             INNER JOIN VEF_EMP_TMOVENTDOCFREF c113 ON (c113.bdCODEMP = mov.bdCODEMP AND c113.bdCHAVE = mov.bdCHAVE)
                             INNER JOIN VEF_BASE_TTABDOCFIS docFisc ON (docFisc.bdCODDOCFIS = c113.bdCODDOCFIS AND (docFisc.bdDOCFIS = '55' or docFisc.bdDOCFIS = '65')) -- #199391 DRCST - NFCe Modelo 65
                             INNER JOIN VEF_EMP_TMOVENT mAux ON (mAux.bdCODEMP = c113.bdcodemp AND mAux.bdREFLAN = ger.bdREFERENCIA AND -- Alt.: #151329 - A referencia, deve pesquisar na nota lançada...
                                                                 mAux.bdCHAVENFE = c113.bdCHAVENFE AND mAux.bdCODSITNF NOT IN (2, 3, 4, 5, 6, 7)) -- Vincula apenas pela Chave NF-e...
                             LEFT OUTER JOIN (SELECT i.bdCODEMP, i.bdCHAVE, MIN(i.bdORDEM) AS bdORDEM, MIN(i.bdCODNAT) AS bdCODNAT
                                         FROM VEF_EMP_TMOVENTITENS i
                                         GROUP BY i.bdCODEMP, i.bdCHAVE) iAux ON (iAux.bdCODEMP = mAux.bdCODEMP AND iAux.bdCHAVE = mAux.bdCHAVE)
                             LEFT OUTER JOIN (SELECT p.bdCODEMP, p.bdCHAVE, p.bdORDEM, MIN(p.bdORDEMPRO) AS bdORDEMPRO, p.bdCODPROD, p.bdALIQICMS, p.bdCODCSTICMS, p.bdCODFATCON
                                         FROM VEF_EMP_TMOVPROENT p
                                         GROUP BY p.bdCODEMP, p.bdCHAVE, p.bdORDEM, p.bdCODPROD, p.bdALIQICMS, p.bdCODCSTICMS, p.bdCODFATCON) movProAux ON (movProAux.bdCODEMP = iAux.bdCODEMP AND movProAux.bdCHAVE = iAux.bdCHAVE AND movProAux.bdORDEM = iAux.bdORDEM AND movProAux.bdCODPROD = movPro.bdCODPROD)
       
                             WHERE ger.bdSESSAO = :prSESSAO
                               AND mov.bdMODELO in (55,65)
                               AND mov.bdCODSITNF IN (6, 7)
                            ) aux
                      GROUP BY aux.bdCODEMP, aux.bdCHAVE, aux.BDREFERENCIA, aux.bdCHAVENFE, aux.bdDATAENTRADAENT, aux.bdCODTER, aux.bdCONSUFINAL, aux.bdMODELO, aux.bdCODSITNF, aux.bdDATAEMISSAO,
                               aux.bdCODPLACONFDRCST, aux.bdSESSAO, aux.bdDEV_VENDAS,
                               aux.bdORDEM, aux.bdCODNAT,
                               aux.bdCODPROD, aux.bdORDEMPRO, aux.bdCODFATCON, aux.bdALIQICMS, aux.bdCODCSTICMS
                      
                      ) mov
                WHERE mov.bdSESSAO = :PRSESSAO AND
                      MOV.bdMODELO in (55,65) AND
                      MOV.bdCODSITNF NOT IN (2, 3, 4, 5) AND
                      SUBSTRING(mov.bdCODNAT FROM 1 FOR 4) <> '1929' AND
                      SUBSTRING(mov.bdCODNAT FROM 1 FOR 4) <> '2929' AND
                      SUBSTRING(mov.bdCODNAT FROM 1 FOR 1) <> '3' AND    
                      --mov.bdVLRST > 0 AND Alt.: #222491 - Deve olhar tambem o ST Retido...
                      ((MOV.bdVLRST > 0) OR (MOV.bdVLRICMSSTRET > 0)) AND
                      ((mov.bdDEV_VENDAS = 'TRUE') OR
                        mov.bdCODNAT IN (SELECT V.bdCODNAT_VENDAS
                                       FROM VEF_BASE_TVINCCODPLANODRCST V
                                       WHERE V.bdCODPLACONFDRCST = mov.bdCODPLACONFDRCST AND
                                             V.bdCODNAT_VENDAS IS NOT NULL)) AND
                      mov.bdQTDITEM > 0
                      AND
                      EXISTS( SELECT FIRST 1 DOCF.bdCHAVE
                              FROM VEF_EMP_TMOVENTDOCFREF DOCF
                              WHERE DOCF.bdCODEMP = MOV.bdCODEMP AND
                                    DOCF.bdCHAVE = MOV.bdCHAVE AND
                                    EXTRACT(YEAR FROM DOCF.bdDTEMISSAO) = EXTRACT(YEAR FROM MOV.bdDATAEMISSAO) AND
                                    EXTRACT(MONTH FROM DOCF.bdDTEMISSAO) = EXTRACT(MONTH FROM MOV.bdDATAEMISSAO)
                              UNION ALL
                              SELECT FIRST 1 M.bdCHAVE
                              FROM VEF_EMP_TMOVSAI M
                              INNER JOIN VEF_EMP_TMOVPROSAI MPRO ON (MPRO.bdCODEMP = M.bdCODEMP AND MPRO.bdCHAVE = M.bdCHAVE)
                              WHERE M.bdCODEMP = MOV.bdCODEMP AND
                                    M.bdREFLAN = MOV.BDREFERENCIA AND
                                   -- M.bdCODTER = MOV.bdCODTER AND  
                                    MPRO.bdCODPROD = mov.bdCODPROD AND
                                    MPRO.bdQTDITEM > 0 AND
                                    (MPRO.bdVLRITEM/MPRO.bdQTDITEM) = (mov.bdVLRITEM/mov.bdQTDITEM) AND
                                    (MPRO.bdVLRST/MPRO.bdQTDITEM) = (mov.bdVLRST/mov.bdQTDITEM)
                             )
                ) S
        )S
  LEFT OUTER JOIN TCADPRO_VINC PROD ON (PROD.BDCODPROD = S.BDCODPROD AND PROD.BDCODEMP = S.BDCODEMP)
  LEFT OUTER JOIN TUNIDADEMEDIDA UNIPRO ON (UNIPRO.BDCODUNIMED = PROD.BDCODUNIMED)
  LEFT OUTER JOIN TFATCONV F ON (F.BDCODPROD = S.BDCODPROD AND F.BDCODEMP = S.BDCODEMP AND F.BDCODFATCON = S.BDCODFATCON)
  LEFT OUTER JOIN TUNIDADEMEDIDA UNIFATCONV ON (UNIFATCONV.BDCODUNIMED = F.BDCODUNIMED)
  LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = S.BDCODTER)
  LEFT OUTER JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = S.BDCODEMP)
  LEFT OUTER JOIN TCIDADE cid on (cid.BDCODCID = EMP.BDCODCID)
  LEFT OUTER JOIN TUF uf on (UF.BDCODUF = cid.BDCODUF)
  WHERE Coalesce(S.BDIND_S, iif(TER.BDENQSIMPLESFEDTER in (0,1),30,null)) IS NOT NULL AND
        CHAR_LENGTH(TER.BDCGCTER) in (14,18);
END
^

create or alter procedure SP_APURACAO_DRCST_2114 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN
  insert into TMP_VEF_EMP_TDRCST_2114_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD,BDIND_OPER, BDCHAVE,
                                            BDORDEM, BDORDEMPRO, BDORDEMIC, BDORDEMDOCFREF, BDCODTER, BDCNPJ, BDCPF, BDCHV_NFE_REF, BDECF_CX_REF,
                                            BDNUM_DOC_REF, BDDT_DOC_REF)
  SELECT :PRSESSAO BDSESSAO, S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD, S.BDIND_OPER, S.BDCHAVE,
         S.BDORDEM, S.BDORDEMPRO, S.BDORDEMIC, S.BDORDEMDOCFREF, S.BDCODTER,
         --IIF(STRLEN(Coalesce(TER.BDCGCTER,'')) = 12,'',Coalesce(TER.BDCGCTER,'')) BDCNPJ,
         IIF(CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(ter.bdCGCTER,'')))) = 14,ter.bdCGCTER,''),
         --IIF(STRLEN(Coalesce(TER.BDCGCTER,'')) = 12,TER.BDCGCTER,''),
         IIF(((CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(ter.bdCGCTER,'')))) = 11) AND (STRLEN(Coalesce(TER.BDCGCTER,'')) <= 14)),ter.bdCGCTER,''),
         Coalesce(S.BDCHAVENFE,'') BDCHV_NFE_REF, 0 BDECF_CX_REF, S.BDNUMDOC BDNUM_DOC_REF, S.BDDTEMISSAO BDDT_DOC_REF
  FROM( SELECT S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD, S.BDIND_OPER, S.BDCHAVE,
               S.BDORDEM, S.BDORDEMPRO, D.BDORDEMIC, D.BDORDEMDOCFREF, D.BDCODTER, D.BDCHAVENFE, D.BDDTEMISSAO, D.BDNUMDOC
        FROM TMP_VEF_EMP_TDRCST_2113_TEMP S
        INNER JOIN VEF_EMP_TMOVENTDOCFREF D ON (D.BDCODEMP = S.BDCODEMP AND D.BDCHAVE = S.BDCHAVE)
        LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOC ON (DOC.BDCODDOCFIS = D.BDCODDOCFIS)
        WHERE S.BDSESSAO = :PRSESSAO AND S.BDIND_OPER = 1 AND (DOC.BDDOCFIS = '55' or DOC.BDDOCFIS = '65')--#199391 DRCST - NFCe Modelo 65
        ) S
  LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = S.BDCODTER);
END
^

create or alter procedure SP_APURACAO_DRCST_2115 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCHAVECOMP INTEGER;
DECLARE VARIABLE WORDEMCOMP INTEGER;
DECLARE VARIABLE WORDEMPROCOMP INTEGER;
DECLARE VARIABLE WLISTCOMP VARCHAR(2000);
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WAUX VARCHAR(200);
DECLARE VARIABLE WSTRAUX VARCHAR(2000);
BEGIN
  FOR
    SELECT s.bdCODEMP, s.bdLISTCOMP
    FROM TMP_VEF_EMP_TDRCST_2113_TEMP s
    WHERE s.bdSESSAO = :prSESSAO
      AND s.bdIND_OPER = 0
      AND (s.bdLISTCOMP IS NOT NULL) AND (s.bdLISTCOMP <> '')
    INTO :wCodEmp, :wListComp DO
  BEGIN
    SELECT POS.POS FROM POS(',',:wListComp) INTO :wPos;
    IF (:wPos = 0) THEN
      SELECT FIRST 1 SUBSTRING(:wListComp FROM 1 FOR CHAR_LENGTH(:wListComp)) FROM TMP_VEF_EMP_TDRCST_2113_TEMP s INTO :wStrAux;
    ELSE
      SELECT FIRST 1 SUBSTRING(:wListComp FROM 1 FOR :wPos-1) FROM TMP_VEF_EMP_TDRCST_2113_TEMP s INTO :wStrAux;
    WHILE (:wStrAux <> '') DO
      BEGIN
        -- Obtém os campos da lista que compoem o 2115...
        SELECT POS.POS FROM POS('.',:wStrAux) INTO :wPos;
        SELECT FIRST 1 SUBSTRING(:wListComp FROM 1 FOR :wPos-1) FROM TMP_VEF_EMP_TDRCST_2113_TEMP s INTO :wChaveComp;

        SELECT FIRST 1 SUBSTRING(:wStrAux FROM :wPos+1 FOR CHAR_LENGTH(:wStrAux)) FROM TMP_VEF_EMP_TDRCST_2113_TEMP s INTO :wAux;
        SELECT POS.POS FROM POS('.',:wAux) INTO :wPos;
        SELECT FIRST 1 SUBSTRING(:wAux FROM 1 FOR :wPos-1) FROM TMP_VEF_EMP_TDRCST_2113_TEMP s INTO :wOrdemComp;

        SELECT FIRST 1 SUBSTRING(:wAux FROM :wPos+1 FOR CHAR_LENGTH(:wAux)) FROM TMP_VEF_EMP_TDRCST_2113_TEMP s INTO :wOrdemProComp;

        -- Grava o 2115
        INSERT INTO TMP_VEF_EMP_TDRCST_2115_TEMP (bdSESSAO, bdCODEMP, bdREFERENCIA, bdCODPROD, bdIND_OPER, bdCHAVE, bdORDEM, bdORDEMPRO,
                                                        bdORDEM2115, bdCHV_NFE_COMP, bdNUM_ITEM_NFE_COMP, bdCHAVE_COMP, bdORDEM_COMP, bdORDEMPRO_COMP, bdQTDITEM, bdVLRITEM)
        SELECT :prSESSAO bdSESSAO, s.bDCODEMP, s.bdREFERENCIA, s.bdCODPROD, s.bdIND_OPER, s.bdCHAVE, s.bdORDEM, s.bdORDEMPRO,
                     GETORDEMSEQUENCIAL_STR('2115.'||s.bdCODEMP||'.'||s.bdCHAVE, s.bdCODEMP) AS bdORDEM2115, sai.bdCHAVENFE AS bdCHV_NFE_COMP,
                     s.bdORDEMPRO AS bdNUM_ITEM_NFE_COMP, p.bdCHAVE AS bdCHAVE_COMP, p.bdORDEM AS bdORDEM_COMP, p.bdORDEMPRO AS bdORDEMPRO_COMP, p.bdQTDITEM, COALESCE(p.bdVLRITEM,0) AS bdVLRITEM
        FROM(
                    SELECT s.bdCODEMP, s.bdREFERENCIA, s.bdCODPROD, s.bdIND_OPER, s.bdCHAVE, s.bdORDEM, s.bdORDEMPRO
              FROM TMP_VEF_EMP_TDRCST_2113_TEMP s
              WHERE s.bdSESSAO = :prSESSAO
                AND s.bdIND_OPER = 0
                      AND s.bdLISTCOMP LIKE '%'||:wStrAux||'%'
              ) s
              INNER JOIN VEF_EMP_TMOVSAI sai ON (sai.bdCODEMP = s.bdCODEMP AND sai.bdCHAVE = :wChaveComp)
              INNER JOIN VEF_EMP_TMOVPROSAI p ON (p.bdCODEMP = sai.bdCODEMP AND p.bdCHAVE = :wChaveComp AND p.bdORDEM = :wOrdemComp AND p.bdORDEMPRO = :wOrdemProComp);
      
              -- Busca o próximo registro da lista, depois do ","
              SELECT FIRST 1 SUBSTRING(:wListComp FROM CHAR_LENGTH(:wStrAux)+2 FOR CHAR_LENGTH(:wListComp)) FROM TMP_VEF_EMP_TDRCST_2113_TEMP s INTO :wListComp;
              SELECT POS.POS FROM POS(',',:wListComp) INTO :wPos;
              IF (:wPos = 0) THEN
                SELECT FIRST 1 SUBSTRING(:wListComp FROM 1 FOR CHAR_LENGTH(:wListComp)) FROM TMP_VEF_EMP_TDRCST_2113_TEMP s INTO :wStrAux;
              ELSE
                SELECT FIRST 1 SUBSTRING(:wListComp FROM 1 FOR :wPos-1) FROM TMP_VEF_EMP_TDRCST_2113_TEMP s INTO :wStrAux;
      
      END
  END
    
END
^

create or alter procedure SP_APURACAO_DRCST_2112 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN
  insert into TMP_VEF_EMP_TDRCST_2112_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDQTDE_V_CF, BDCODUNIMED, BDUNID, BDVL_V_CF, BDALIQ_EF)
  SELECT :PRSESSAO BDSESSAO, S.BDCODEMP, S.BDREFERENCIA,
          S.BDCODPROD, S.BDQTDE_V_CF, PROD.BDCODUNIMED, U.BDAPEUNIMED BDUNID, S.BDVL_V_CF, Coalesce(PROD.BDALIQICMSEFETIVO, Coalesce(uf.BDALIQINT,0)) BDALIQ_EF
  FROM (  SELECT S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD, SUM(Coalesce(S.BDQTDACU,0)) BDQTDE_V_CF, SUM(Coalesce(S.BDVLRACU,0)) BDVL_V_CF
          FROM( SELECT S.BDCODEMP, ger.BDREFERENCIA, S.BDCODPROD, S.BDQTDACU, S.BDVLRACU
                FROM TMP_VEF_EMP_TDRCSTGER_TEMP GER        
                LEFT OUTER JOIN VEF_EMP_TREDZ Z ON (Z.BDCODEMP = GER.BDCODEMP)
                LEFT OUTER JOIN VEF_EMP_TREDZC425 S ON (S.BDCODEMP = Z.BDCODEMP AND S.BDCHAVE = Z.BDCHAVE)
                WHERE GER.BDSESSAO = :PRSESSAO AND
                       Z.BDREFLAN = GER.BDREFERENCIA AND
                       S.BDORDEMTOT = 5 -- Substituição Tributária – ICMS
                ) S
          WHERE S.BDCODPROD IS NOT NULL
          GROUP BY  S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD
        )S
  LEFT OUTER JOIN TCADPRO_VINC PROD ON (PROD.BDCODPROD = S.BDCODPROD AND PROD.BDCODEMP = S.BDCODEMP)
  LEFT OUTER JOIN TUNIDADEMEDIDA U ON (U.BDCODUNIMED = PROD.BDCODUNIMED)
  LEFT OUTER JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = S.BDCODEMP)
  LEFT OUTER JOIN TCIDADE cid on (cid.BDCODCID = EMP.BDCODCID)
  LEFT OUTER JOIN TUF uf on (UF.BDCODUF = cid.BDCODUF);
END
^

create or alter procedure SP_APURACAO_DRCST_2121 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date,
    PRCODPLACONFDRCST integer)
as
declare variable WIGNORARCOMP DM_BOOLEAN;
BEGIN
  -- Alt.: #132676 - Obtem a configuração de "Ignorar lançamentos sem compra com destaque de ICMS ST e ICMS ST Retido" do plano DRCST.
  SELECT COALESCE(UPPER(bdIGNORARCOMP),'FALSE')
  FROM VEF_BASE_TPLACONFDRCST
  WHERE bdCODPLACONFDRCST = :prCODPLACONFDRCST
  INTO :wIGNORARCOMP;

  
  INSERT INTO TMP_VEF_EMP_TDRCST_2121_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDS_QTDE_C_T, BDS_QTDE_C_VLM, BDS_VL_BCST_INT_VLM, BDVLM_UNIT_BCST_G)
  SELECT D.BDSESSAO, D.BDCODEMP, D.BDREFERENCIA, D.BDCODPROD,
         d.S_QTDE_C_T,
         (d.BDQTDE_C) BDS_QTDE_C_VLM,
         (d.bdS_VL_BCST_INT) BDS_VL_BCST_INT_VLM,
         --IIF((d.BDQTDE_C) > 0, (d.bdS_VL_BCST_INT)/(d.BDQTDE_C),0) BDVLM_UNIT_BCST_G
         CAST(IIF((d.BDQTDE_C) > 0, (d.bdS_VL_BCST_INT)/(d.BDQTDE_C),0) AS NUMERIC(15,2)) BDVLM_UNIT_BCST_G -- Alt.: #154462 #157391 - Deve arredondar os valores em duas casas decimais...
--         (d.S_QTDE_C_T - d.BDQTDE_C) BDS_QTDE_C_VLM,
--         (d.bdS_VL_BCST_INT - d.BDVL_BCST_INT) BDS_VL_BCST_INT_VLM,
--         IIF((d.S_QTDE_C_T - d.BDQTDE_C) > 0, (d.bdS_VL_BCST_INT - d.BDVL_BCST_INT)/(d.S_QTDE_C_T - d.BDQTDE_C),0) BDVLM_UNIT_BCST_G
  FROM (SELECT D2130.BDSESSAO, D2130.BDCODEMP, D2130.BDCODPROD, D2130.BDREFERENCIA,
               --SUM(Coalesce(IIF(D2130.BDIND_OPER = 0,D2130.BDQTDE_C,-D2130.BDQTDE_C),0)) BDQTDE_C, Alt.: #154462 #157391 - Apenas deve considerar os produtos que tenham Base de ST destacada...
               SUM(Coalesce(CASE WHEN ((D2130.BDVL_BCST = 0) OR (D2130.BDVL_BCST IS NULL)) THEN 0
                                 WHEN D2130.BDIND_OPER = 0 THEN D2130.BDQTDE_C
                            ELSE -D2130.BDQTDE_C END,0)) BDQTDE_C,
               SUM(Coalesce(D2130.BDQTDE_C,0)) S_QTDE_C_T, SUM(Coalesce(IIF(D2130.BDIND_OPER = 0,D2130.BDVL_BCST_INT,-D2130.BDVL_BCST_INT),0)) bdS_VL_BCST_INT
        FROM TMP_VEF_EMP_TDRCST_2130_TEMP D2130
--        LEFT OUTER JOIN TMP_VEF_EMP_TDRCST_2134_TEMP D2134  ON (D2130.BDSESSAO = D2134.BDSESSAO AND D2130.BDCODEMP = D2134.BDCODEMP AND
--                                                                D2130.BDREFERENCIA = D2134.BDREFERENCIA AND D2130.BDCODPROD = D2134.BDCODPROD AND
--                                                                D2130.BDIND_OPER = D2134.BDIND_OPER AND D2130.BDCHAVE = D2134.BDCHAVE AND
--                                                                D2130.BDORDEM = D2134.BDORDEM AND D2130.BDORDEMPRO = D2134.BDORDEMPRO)
        WHERE D2130.BDSESSAO = :PRSESSAO and (exists(select first 1 D2134.BDCODEMP
                                                     FROM TMP_VEF_EMP_TDRCST_2134_TEMP D2134
                                                     WHERE D2130.BDSESSAO = D2134.BDSESSAO AND D2130.BDCODEMP = D2134.BDCODEMP AND
                                                           D2130.BDREFERENCIA = D2134.BDREFERENCIA AND D2130.BDCODPROD = D2134.BDCODPROD))
        GROUP BY D2130.BDSESSAO, D2130.BDCODEMP, D2130.BDREFERENCIA, D2130.BDCODPROD
        ) d
  WHERE (:wIGNORARCOMP <> 'TRUE') 
     OR (EXISTS(SELECT * -- Alt.: #132676 - Caso a opção esteja marcada, apenas leva para o 2110, caso tenha o produto no 2130...
                FROM TMP_VEF_EMP_TDRCST_2130_TEMP t2130
                WHERE t2130.bdSESSAO     = :prSESSAO
                  AND t2130.BDCODEMP     = d.bdCODEMP
                  AND t2130.bdREFERENCIA = d.bdREFERENCIA
                  AND t2130.bdCODPROD    = d.bdCODPROD));
END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_DRCST_2130_PROD_SAI (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRCODPROD INTEGER,
    PRQUANTIDADE INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCHAVE INTEGER,
    BDORDEM INTEGER,
    BDORDEMPRO INTEGER)
AS
DECLARE VARIABLE WQTD_ATUAL NUMERIC(15,2);
DECLARE VARIABLE WQTD_TOTAL NUMERIC(15,2);
BEGIN
  WQTD_TOTAL = 0;
  IF (:PRQUANTIDADE = 0) THEN
    EXIT;

  FOR
    SELECT MOVPRO.BDCODEMP, MOVPRO.BDCHAVE, MOVPRO.BDORDEM, MOVPRO.BDORDEMPRO, MOVPRO.BDQTDITEM
    FROM VEF_EMP_TMOVSAI MOV                                                                                
    JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
    JOIN VEF_EMP_TMOVPROSAI MOVPRO ON (MOVPRO.BDCODEMP = I.BDCODEMP AND MOVPRO.BDCHAVE = I.BDCHAVE AND MOVPRO.BDORDEM = I.BDORDEM)  
    LEFT OUTER JOIN TMP_VEF_EMP_TDRCSTGER_TEMP GER ON (GER.BDSESSAO = :PRSESSAO AND GER.BDCODEMP = :PRCODEMP AND GER.BDREFERENCIA = :PRREFERENCIA)
    WHERE MOV.BDCODEMP = :PRCODEMP AND
          MOV.BDREFLAN = :PRREFERENCIA AND                   
          MOV.BDMODELO = 55 AND                      
          MOV.BDCODSITNF NOT IN (2, 3, 4, 5) AND
          ((GER.BDDEV_COMPRAS = 'TRUE') OR
            I.BDCODNAT IN (SELECT V.BDCODNAT_COMPRAS
                           FROM VEF_BASE_TVINCCODPLANODRCST V
                           WHERE V.BDCODPLACONFDRCST = GER.BDCODPLACONFDRCST AND
                                 V.BDCODNAT_COMPRAS IS NOT NULL)) AND
          MOVPRO.BDCODPROD = :PRCODPROD    AND                                     
          MOVPRO.BDQTDITEM > 0
  INTO BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, :WQTD_ATUAL DO
    BEGIN
      IF (WQTD_TOTAL < :PRQUANTIDADE) THEN
        SUSPEND;
      ELSE
        EXIT;

      WQTD_TOTAL = WQTD_TOTAL + WQTD_ATUAL;
    END
END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_DRCST_2130_PROD_ENT (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRCODPROD INTEGER,
    PRQUANTIDADE INTEGER)
RETURNS (
    BDCODEMP INTEGER,
    BDCHAVE INTEGER,
    BDORDEM INTEGER,
    BDORDEMPRO INTEGER)
AS
DECLARE VARIABLE WQTD_ATUAL NUMERIC(15,2);
DECLARE VARIABLE WQTD_TOTAL NUMERIC(15,2);
BEGIN
  WQTD_TOTAL = 0;
  IF (:PRQUANTIDADE = 0) THEN
    EXIT;

  FOR
    SELECT MOVPRO.BDCODEMP, MOVPRO.BDCHAVE, MOVPRO.BDORDEM, MOVPRO.BDORDEMPRO, MOVPRO.BDQTDITEM
    FROM VEF_EMP_TMOVENT MOV
    JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
    JOIN VEF_EMP_TMOVPROENT MOVPRO ON (MOVPRO.BDCODEMP = I.BDCODEMP AND MOVPRO.BDCHAVE = I.BDCHAVE AND MOVPRO.BDORDEM = I.BDORDEM)
    LEFT OUTER JOIN TMP_VEF_EMP_TDRCSTGER_TEMP GER ON (GER.BDSESSAO = :PRSESSAO AND GER.BDCODEMP = :PRCODEMP AND GER.BDREFERENCIA = :PRREFERENCIA)
    WHERE MOV.BDCODEMP = :PRCODEMP AND
         (MOV.BDREFLAN BETWEEN (SELECT BDREFERENCIA FROM DEC_REFERENCIA(:PRREFERENCIA,12)) AND :PRREFERENCIA) AND
          MOV.BDMODELO = 55 AND   
          MOV.BDCODSITNF NOT IN (2, 3, 4, 5) AND
          ((GER.BDDEV_VENDAS = 'FALSE') AND
            NOT I.BDCODNAT IN (SELECT V.BDCODNAT_VENDAS
                           FROM VEF_BASE_TVINCCODPLANODRCST V
                           WHERE V.BDCODPLACONFDRCST = GER.BDCODPLACONFDRCST AND
                                 V.BDCODNAT_VENDAS IS NOT NULL)) AND
          MOVPRO.BDCODPROD = :PRCODPROD AND                                     
          MOVPRO.BDQTDITEM > 0
    ORDER BY MOV.BDREFLAN DESC
  INTO BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, :WQTD_ATUAL DO
    BEGIN
      IF (WQTD_TOTAL < :PRQUANTIDADE) THEN
        SUSPEND;
      ELSE
        EXIT;

      WQTD_TOTAL = WQTD_TOTAL + WQTD_ATUAL;
    END
END
^

CREATE OR ALTER procedure SP_APURACAO_DRCST_2130 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN
  SETQUANTIDADEPRODUTO(0);

  INSERT INTO TMP_VEF_EMP_TDRCST_2130_TEMP (BDSESSAO, BDC176, BDCODEMP, BDREFERENCIA, BDCODPROD, BDIND_OPER, BDCHAVE, BDORDEM,
                                            BDORDEMPRO, BDCHV_NFE, BDDT_E, BDDT_NFE, BDCODTER, BDNOMTER, BDCNPJ,
                                            BDNUM_ITEM, BDCOD_RESP_RET, BDQTDE, BDCODUNIMED, BDUNID, BDCODFATCON, BDFAT_CONV, BDQTDE_C, BDVL_E,
                                            BDCODNAT, BDCFOP, BDVL_BC_ICMS, BDALIQ_ICMS, BDVL_ICMS, BDVL_BCST, BDVL_BCST_INT,
                                            BDALIQ_ST_E, BDALIQ_ST_EF, BDCAL_ICMS_ST, BDVL_ICMS_ST, BDCOD_DA, BDNUM_DARE, BDCOD_AJ, BDALIQ_EF,BDCODCSTICMS, BDCODPLACONFDRCST)
    select distinct :PRSESSAO BDSESSAO, 'TRUE' BDC176, GER.BDCODEMP, GER.BDREFERENCIA, PROD.BDCODPROD, 0 BDIND_OPER,
           Coalesce(MOVENT.BDCHAVE, C.BDCHAVE), Coalesce(MOVENT.BDORDEM, C.BDORDEM), Coalesce(MOVENT.BDORDEMPRO, C.BDORDEMPRO), Coalesce(MOVENT.BDCHAVENFE,C.BDCHAVE_NFE_ULT_E) BDCHV_NFE, C.BDDT_ULT_E BDDT_E,
           null BDDT_NFE, TER.BDCODTER BDCODTER, TER.BDNOMETER BDNOMTER, TER.BDCGCTER BDCNPJ, C.BDNUM_ITEM_ULT_E BDNUM_ITEM,
           (C.BDCOD_RESP_RET + 1) BDCOD_RESP_RET, C.BDQUANT_ULT_E BDQTDE, UNIPRO.BDCODUNIMED, UNIPRO.BDAPEUNIMED BDUNID,
           null BDCODFATCON, null BDFAT_CONV, C.BDQUANT_ULT_E BDQTDE_C, C.BDVL_UNIT_ULT_E * C.BDQUANT_ULT_E BDVL_E,
           I.BDCODNAT, coalesce((select first 1 ITEM.BDCODNAT
                                 from VEF_EMP_TMOVENT ENT
                                 left outer join VEF_EMP_TMOVENTITENS ITEM on (ITEM.BDCODEMP = ENT.BDCODEMP and ITEM.BDCHAVE = ENT.BDCHAVE)
                                 left outer join VEF_EMP_TMOVPROENT MOVP on (MOVP.BDCODEMP = ITEM.BDCODEMP and MOVP.BDCHAVE = ITEM.BDCHAVE and MOVP.BDORDEM = ITEM.BDORDEM)
                                 where ENT.BDCODEMP = MOV.BDCODEMP and
                                       ENT.BDCHAVENFE = C.BDCHAVE_NFE_ULT_E and
                                       MOVP.BDCODPROD = MOVPRO.BDCODPROD),
           case
             when I.BDCODNAT like '5%' then '1'
             when I.BDCODNAT like '6%' then '2'
             when I.BDCODNAT like '7%' then '3'
           end || substring(I.BDCODNAT from 2 for char_length(I.BDCODNAT) - 1)) BDCFOP,
           C.BDVL_UNIT_BC_ICMS_ULT_E * C.BDQUANT_ULT_E BDVL_BC_ICMS, C.BDALIQ_ICMS_ULT_E BDALIQ_ICMS,
           C.BDVL_UNIT_ICMS_ULT_E * C.BDQUANT_ULT_E BDVL_ICMS, C.BDVL_UNIT_BC_ST * C.BDQUANT_ULT_E BDVL_BCST,
           C.BDVL_UNIT_BC_ST * C.BDQUANT_ULT_E BDVL_BCST_INT, C.BDALIQ_ST_ULT_E BDALIQ_ST_E, C.BDALIQ_ST_ULT_E BDALIQ_ST_EF,
           C.BDVL_UNIT_RES * C.BDQUANT_ULT_E BDCAL_ICMS_ST, C.BDVL_UNIT_RES * C.BDQUANT_ULT_E BDVL_ICMS_ST,
           iif(C.BDCOD_DA < 0, 0, C.BDCOD_DA) BDCOD_DA, C.BDNUM_DA BDNUM_DARE,
           (select first 1 AJU.BDCODAJUPAD
            from VEF_EMP_TMOVENT M
            left outer join VEF_EMP_TC197ENT C197 on (C197.BDCODEMP = M.BDCODEMP and C197.BDCHAVE = M.BDCHAVE)
            left outer join VEF_BASE_TTABCODAJU AJU on (AJU.BDCODAJU = C197.BDCODAJU)
            where M.BDCODEMP = MOV.BDCODEMP and
                  M.BDCHAVENFE = C.BDCHAVE_NFE_ULT_E and
                  C197.BDCODPROD = MOVPRO.BDCODPROD) BDCOD_AJ,
           coalesce(PROD.BDALIQICMSEFETIVO, coalesce(UF.BDALIQINT, 0)) BDALIQ_EF, MOVPRO.BDCODCSTICMS,
           GER.BDCODPLACONFDRCST BDCODPLACONFDRCST
    from TMP_VEF_EMP_TDRCSTGER_TEMP GER
    inner join VEF_EMP_TMOVSAI MOV on (MOV.BDCODEMP = GER.BDCODEMP and MOV.BDREFLAN = GER.BDREFERENCIA)
    inner join VEF_EMP_TMOVSAIITENS I on (I.BDCODEMP = MOV.BDCODEMP and I.BDCHAVE = MOV.BDCHAVE)
    inner join VEF_EMP_TMOVPROSAI MOVPRO on (MOVPRO.BDCODEMP = I.BDCODEMP and MOVPRO.BDCHAVE = I.BDCHAVE and MOVPRO.BDORDEM = I.BDORDEM)
    inner join VEF_EMP_TMOVSTC176 C on (C.BDCODEMP = MOVPRO.BDCODEMP and C.BDCHAVE = MOVPRO.BDCHAVE and C.BDORDEM = MOVPRO.BDORDEM and C.BDORDEMPRO = MOVPRO.BDORDEMPRO)
    left outer join VW_TTERCEIRO TER on (TER.BDCODTER = C.BDCODTER)
    left outer join TCADPRO_VINC PROD on (PROD.BDCODPROD = MOVPRO.BDCODPROD and PROD.BDCODEMP = MOVPRO.BDCODEMP)
    left outer join TUNIDADEMEDIDA UNIPRO on (UNIPRO.BDCODUNIMED = PROD.BDCODUNIMED)
    left outer join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = GER.BDCODEMP)
    left outer join TCIDADE CID on (CID.BDCODCID = EMP.BDCODCID)
    left outer join TUF UF on (UF.BDCODUF = CID.BDCODUF)
    left outer join ( select ENT.BDCODEMP, ENT.BDCHAVENFE, ENT.BDNUMDOCINI, MOVP.BDCODPROD, MIN(MOVP.BDCHAVE) BDCHAVE, MIN(MOVP.BDORDEM) BDORDEM, MIN(MOVP.BDORDEMPRO) BDORDEMPRO
                      from VEF_EMP_TMOVENT ENT
                      left outer join VEF_EMP_TMOVENTITENS ITEM on (ITEM.BDCODEMP = ENT.BDCODEMP and ITEM.BDCHAVE = ENT.BDCHAVE)
                      left outer join VEF_EMP_TMOVPROENT MOVP on (MOVP.BDCODEMP = ITEM.BDCODEMP and MOVP.BDCHAVE = ITEM.BDCHAVE and MOVP.BDORDEM = ITEM.BDORDEM)
                      GROUP BY ENT.BDCODEMP, ENT.BDCHAVENFE, ENT.BDNUMDOCINI, MOVP.BDCODPROD
                    ) MOVENT ON (MOVENT.BDCODEMP = MOVPRO.BDCODEMP and MOVENT.BDCODPROD = MOVPRO.BDCODPROD and MOVENT.BDCHAVENFE = C.BDCHAVE_NFE_ULT_E AND MOVENT.BDNUMDOCINI = C.BDNUM_DOC_ULT_E)
    where GER.BDSESSAO = :PRSESSAO and
          MOV.BDMODELO = 55 and
          MOV.BDCODSITNF not in (2, 3, 4, 5) and
          char_length(TER.BDCGCTER) = 18
;

    INSERT INTO TMP_VEF_EMP_TDRCST_2130_TEMP (BDSESSAO, BDC176, BDCODEMP, BDREFERENCIA, BDCODPROD, BDIND_OPER, BDCHAVE, BDORDEM,
                                            BDORDEMPRO, BDCHV_NFE, BDDT_E, BDDT_NFE, BDCODTER, BDNOMTER, BDCNPJ,
                                            BDNUM_ITEM, BDCOD_RESP_RET, BDQTDE, BDCODUNIMED, BDUNID, BDCODFATCON, BDFAT_CONV, BDQTDE_C, BDVL_E,
                                            BDCODNAT, BDCFOP, BDVL_BC_ICMS, BDALIQ_ICMS, BDVL_ICMS, BDVL_BCST, BDVL_BCST_INT,
                                            BDALIQ_ST_E, BDALIQ_ST_EF, BDCAL_ICMS_ST, BDVL_ICMS_ST, BDCOD_DA, BDNUM_DARE, BDCOD_AJ, BDALIQ_EF,
                                            BDCODCSTICMS, BDCODPLACONFDRCST, BDQTDTOTAL, BDALIQST, BDALIQICMSPROD, BDALIQINT, bdLISTCOMP)
  SELECT :PRSESSAO BDSESSAO, 'FALSE' BDC176, S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD, S.BDIND_OPER, S.BDCHAVE, S.BDORDEM,
         S.BDORDEMPRO, S.BDCHV_NFE, S.BDDT_E, S.BDDT_NFE, S.BDCODTER, S.BDNOMETER BDNOMTER, S.BDCGCTER BDCNPJ,
         S.BDORDEMPRO BDNUM_ITEM, S.BDCOD_RESP_RET,
         S.BDQTDE, COALESCE(UNIFATCONV.BDCODUNIMED,UNIPRO.BDCODUNIMED), COALESCE(UNIFATCONV.BDAPEUNIMED,UNIPRO.BDAPEUNIMED) BDUNID, S.BDCODFATCON,
         F.BDFATORCONVER BDFAT_CONV, (S.BDQTDE * COALESCE(F.BDFATORCONVER,1)) BDQTDE_C, S.BDVL_E,
         S.BDCODNAT, S.BDCFOP, S.BDVL_BC_ICMS, S.BDALIQ_ICMS,
         CASE
         WHEN ((S.BDCOD_RESP_RET IN (1,3)) AND (NOT S.BDENQSIMPLESFEDTER IN (0,1))) THEN S.BDVLRICMS
         WHEN S.BDTIPO2134 = 1 THEN S.BDVLRICMS
         --WHEN (S.BDENQSIMPLESFEDTER IN (0,1)) THEN ((S.BDVL_BCST * (S.BDALIQ_ST_E/100)) - S.BDVL_ICMS_ST) Alt.: #242066 - Faz o cast, pois estava com problema de arredondamento...
         WHEN (S.BDENQSIMPLESFEDTER IN (0,1)) THEN (CAST((S.BDVL_BCST * (S.BDALIQ_ST_E/100)) AS NUMERIC(15,2)) - S.BDVL_ICMS_ST)
         ELSE 0
         END BDVL_ICMS,
         S.BDVL_BCST,
         S.BDVL_BCST_INT,
         S.BDALIQ_ST_E,
         CASE                                         
         WHEN S.BDALIQST > 0 THEN S.BDALIQST
         WHEN S.BDALIQICMSPROD > 0 THEN S.BDALIQICMSPROD
         ELSE S.BDALIQINT
         END BDALIQ_ST_EF, (S.BDVL_BCST * (S.BDALIQ_ST_E/100)) BDCAL_ICMS_ST,
         S.BDVL_ICMS_ST, S.BDARRECADACAO, S.BDNUM_DA,
         S.BDCOD_AJ,
         COALESCE(S.BDALIQICMSEFETIVO, COALESCE(S.BDALIQINT,0)) BDALIQ_EF, S.BDCODCSTICMS, S.BDCODPLACONFDRCST, S.BDQTDTOTAL, S.BDALIQST, S.BDALIQICMSPROD, S.BDALIQINT,
         s.bdLISTCOMP
  FROM (  SELECT S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD, S.BDIND_OPER, S.BDCHAVE, S.BDORDEM, S.BDORDEMPRO, S.BDCHAVENFE BDCHV_NFE, S.BDDT_NFE,
                 S.BDDT_E, S.BDCODTER, COALESCE(S.BDQTDITEM,0) BDQTDE, S.BDCODFATCON, S.BDCODNAT, S.BDCODNAT BDCFOP,
                 S.BDCOD_RESP_RET, S.BDVLRICMS, S.BDVL_E,
                 TER.BDNOMETER, TER.BDCGCTER, TER.BDENQSIMPLESFEDTER,
                 PROD.BDCODUNIMED, PROD.BDALIQICMSEFETIVO, PROD.BDALIQICMS AS BDALIQICMSPROD, S.BDALIQST,
                 UF.BDALIQINT,
                 CASE
                 WHEN (S.BDCOD_RESP_RET IN (1,3)) AND (NOT TER.BDENQSIMPLESFEDTER IN (0,1)) THEN S.BDBCICMS
                 WHEN S.BDTIPO2134 = 1 THEN S.BDBCICMS
                 ELSE 0
                 END BDVL_BC_ICMS,
                 CASE
                 WHEN (S.BDCOD_RESP_RET IN (1,3)) AND (NOT TER.BDENQSIMPLESFEDTER IN (0,1)) THEN S.BDALIQICMS
                 WHEN S.BDTIPO2134 = 1 THEN S.BDALIQICMS
                 ELSE 0
                 END BDALIQ_ICMS,
                 CASE
                 WHEN (S.BDCOD_RESP_RET IN (1)) THEN (S.BDBCST + S.BDBCFCPRETIDO)
                 WHEN (S.BDCOD_RESP_RET IN (2)) THEN (S.BDBCICMSSTRET + S.BDBCFCPSTRET)
                 WHEN (S.BDCOD_RESP_RET IN (3)) THEN (S.BDICMS)
                 ELSE 0
                 END BDVL_BCST, 
                 CASE
                 WHEN (S.BDCOD_RESP_RET IN (1)) THEN (S.BDBCST + S.BDBCFCPRETIDO)
                 WHEN (S.BDCOD_RESP_RET IN (2)) THEN (S.BDBCICMSSTRET + S.BDBCFCPSTRET)     
                 WHEN (S.BDCOD_RESP_RET IN (3)) THEN (S.BDICMS)
                 ELSE 0 
                 END BDVL_BCST_INT,
                 CASE
                 WHEN (S.BDCOD_RESP_RET IN (1)) THEN S.BDALIQST
                 WHEN (S.BDCOD_RESP_RET IN (2)) THEN IIF((PROD.BDALIQICMS > 0), PROD.BDALIQICMS, UF.BDALIQINT) -- Alt.: #222491 - Se for "2 - Remetente Indireto" e a aliquota estiver zerada, deve pegar a aliquota do estado...
                 WHEN (S.BDCOD_RESP_RET IN (3)) THEN S.BDALIQINT
                 ELSE 0
                 END BDALIQ_ST_E,
                 CASE
                 WHEN (S.BDCOD_RESP_RET IN (1)) THEN (S.BDVLRST + S.BDFCPRETIDO)
                 WHEN (S.BDCOD_RESP_RET IN (2)) THEN (S.BDVLRICMSSTRET + S.BDVLRFCPSTRET)   
                 WHEN (S.BDCOD_RESP_RET IN (3)) THEN (S.BDICMSNR)
                 ELSE 0
                 END BDVL_ICMS_ST,
                 S.BDCODCSTICMS, S.BDCODPLACONFDRCST, S.BDARRECADACAO, S.BDNUM_DA, S.BDQTDTOTAL, S.BDCOD_AJ,
                 s.bdLISTCOMP, S.BDTIPO2134
          FROM(
                SELECT aux.bdCODEMP, aux.bdREFERENCIA, aux.bdCODPROD, SUM(aux.bdQTDTOTAL) AS bdQTDTOTAL, aux.bdIND_OPER, aux.bdCHAVE, aux.bdORDEM, aux.bdORDEMPRO,
                       aux.bdCHAVENFE, NULL bdDT_NFE, aux.bdDT_E, aux.bdCODTER, SUM(aux.bdQTDITEM) AS bdQTDITEM, aux.bdCODFATCON,
                       aux.bdCODNAT, aux.bdALIQICMS, aux.bdALIQST, SUM(aux.bdVLRST) AS bdVLRST, SUM(aux.bdBCICMS) AS bdBCICMS, SUM(aux.bdVLRICMS) AS bdVLRICMS, SUM(aux.bdBCST) AS bdBCST,
                       SUM(aux.bdVLRICMSSTRET) AS bdVLRICMSSTRET, SUM(aux.bdBCFCPRETIDO) AS bdBCFCPRETIDO, SUM(aux.bdBCFCPSTRET) AS bdBCFCPSTRET, SUM(aux.bdBCICMSSTRET) AS bdBCICMSSTRET, SUM(aux.bdFCPRETIDO) AS bdFCPRETIDO,
                       SUM(aux.bdVLRFCPSTRET) AS bdVLRFCPSTRET, SUM(aux.bdVL_E) AS bdVL_E,
                       aux.bdCOD_RESP_RET, aux.bdCODCSTICMS, aux.bdCODPLACONFDRCST, aux.bdICMS, aux.bdALIQINT, aux.bdARRECADACAO, aux.bdNUM_DA, aux.bdICMSNR,
                       aux.BDCOD_AJ,
                       LIST(aux.bdCHAVE_COMP||'.'||aux.bdORDEM_COMP||'.'||aux.bdORDEMPRO_COMP) AS bdLISTCOMP, MAX(aux.BDTIPO2134) BDTIPO2134
                FROM (
                       SELECT LAN.BDCODEMP, LAN.BDREFERENCIA, MOVPRO.BDCODPROD, LAN.BDQTDTOTAL, 0 BDIND_OPER, MOV.BDCHAVE, I.BDORDEM, MOVPRO.BDORDEMPRO,
                       MOV.BDCHAVENFE, NULL BDDT_NFE, MOV.BDDATAENTRADAENT BDDT_E, MOV.BDCODTER, MOVPRO.BDQTDITEM, MOVPRO.BDCODFATCON,
                       I.BDCODNAT, MOVPRO.BDALIQICMS, MOVPRO.BDALIQST, COALESCE(MOVPRO.BDVLRST,0) AS BDVLRST, COALESCE(MOVPRO.BDBCICMS,0) AS BDBCICMS,
                       COALESCE(MOVPRO.BDVLRICMS,0) AS BDVLRICMS, COALESCE(MOVPRO.BDBCST,0) AS BDBCST, COALESCE(MOVPRO.BDVLRICMSSTRET,0) AS BDVLRICMSSTRET,
                       COALESCE(MOVPRO.BDBCFCPRETIDO,0) AS BDBCFCPRETIDO, COALESCE(MOVPRO.BDBCFCPSTRET,0) AS BDBCFCPSTRET, COALESCE(MOVPRO.BDBCICMSSTRET,0) AS BDBCICMSSTRET,
                       COALESCE(MOVPRO.BDFCPRETIDO,0) AS BDFCPRETIDO, COALESCE(MOVPRO.BDVLRFCPSTRET,0) AS BDVLRFCPSTRET,
                       (COALESCE(MOVPRO.BDVLRITEM,0) + COALESCE(MOVPRO.BDVLRDESPACESSORIA,0)) BDVL_E,
                       CASE 
                         WHEN (Coalesce(MOVPRO.BDTIPO2134,0)) > 0 THEN 2
                         WHEN (COALESCE(MOVPRO.BDVLRST,0) + COALESCE(MOVPRO.BDFCPRETIDO,0)) > 0 THEN 1
                         WHEN (COALESCE(MOVPRO.BDVLRICMSSTRET,0) + COALESCE(MOVPRO.BDVLRFCPSTRET,0)) > 0 THEN 2
                         WHEN (MVA.BDICMSNR) > 0 THEN 3
                      --   WHEN (CST.BDCSTICMS like '_60') THEN 2
                         ELSE 0 -- Busca informação na tela do MVA
                       END BDCOD_RESP_RET, MOVPRO.BDCODCSTICMS, LAN.BDCODPLACONFDRCST, MVA.BDICMS, MVA.BDALIQINT, MVA.BDARRECADACAO, MVA.BDNARREST BDNUM_DA, MVA.BDICMSNR,
                      (SELECT FIRST 1 AJU.BDCODAJUPAD
                       FROM VEF_EMP_TC197ENT C197
                       LEFT OUTER JOIN VEF_BASE_TTABCODAJU AJU ON (AJU.BDCODAJU = C197.BDCODAJU)
                       WHERE C197.BDCODEMP = MOVPRO.BDCODEMP AND C197.BDCHAVE = MOVPRO.BDCHAVE AND C197.BDCODPROD = MOVPRO.BDCODPROD) BDCOD_AJ,
                       NULL AS bdCHAVE_COMP, NULL AS BDORDEM_COMP, NULL AS BDORDEMPRO_COMP, MOVPRO.BDTIPO2134
                       FROM (
                              SELECT D.BDCODEMP, G.BDREFERENCIA, D.BDCODPROD, G.BDCODPLACONFDRCST,
                             SUM(D.BDQTD) BDQTDTOTAL
                       FROM ( SELECT D.BDCODEMP, D.BDREFERENCIA, D.BDCODPROD, D.BDQTDE_V_CF AS BDQTD
                              FROM TMP_VEF_EMP_TDRCST_2112_TEMP D
                              WHERE D.BDSESSAO = :PRSESSAO
                              UNION ALL
                              SELECT D.BDCODEMP, D.BDREFERENCIA, D.BDCODPROD, D.BDQTDE_IND_S_C AS BDQTD
                              FROM TMP_VEF_EMP_TDRCST_2113_TEMP D
                              WHERE D.BDSESSAO = :PRSESSAO AND
                                NOT EXISTS(SELECT FIRST 1 S.BDCODEMP
                                           FROM VEF_EMP_TMOVSTC176 S
                                           WHERE S.BDCODEMP = D.BDCODEMP AND
                                                 S.BDCHAVE = D.BDCHAVE AND
                                                 S.BDORDEM = D.BDORDEM AND
                                                 S.BDORDEMPRO = D.BDORDEMPRO)) D
                       LEFT OUTER JOIN TMP_VEF_EMP_TDRCSTGER_TEMP G ON (G.BDSESSAO = :PRSESSAO AND G.BDCODEMP = D.BDCODEMP AND G.BDREFERENCIA = D.BDREFERENCIA)
                       LEFT OUTER JOIN VEF_BASE_TPLACONFDRCST P ON (P.BDCODPLACONFDRCST = G.BDCODPLACONFDRCST)
                       WHERE COALESCE(P.BDAPENASC176,'FALSE') = 'FALSE' AND
                             D.BDQTD > 0
                       GROUP BY D.BDCODEMP, G.BDREFERENCIA, D.BDCODPROD, G.BDCODPLACONFDRCST
                             ) LAN
                JOIN VEF_EMP_TMOVENT MOV ON (MOV.BDCODEMP = LAN.BDCODEMP)
                JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                JOIN VEF_EMP_TMOVPROENT MOVPRO ON (MOVPRO.BDCODEMP = I.BDCODEMP AND MOVPRO.BDCHAVE = I.BDCHAVE AND MOVPRO.BDORDEM = I.BDORDEM) 
                LEFT OUTER JOIN VEF_BASE_TTABCSTICMS CST ON (CST.BDCODCSTICMS = MOVPRO.BDCODCSTICMS)
                JOIN TMP_VEF_EMP_TDRCSTGER_TEMP GER ON (GER.BDSESSAO = :PRSESSAO AND GER.BDCODEMP = LAN.BDCODEMP AND GER.BDREFERENCIA = LAN.BDREFERENCIA)
                LEFT OUTER JOIN VEF_EMP_TMOVMVASC MVA ON (MVA.BDCODEMP = MOVPRO.BDCODEMP AND MVA.BDCHAVE = MOVPRO.BDCHAVE AND MVA.BDORDEM = MOVPRO.BDORDEM AND MVA.BDCODPROD = MOVPRO.BDCODPROD)
                WHERE (MOV.BDREFLAN BETWEEN(SELECT BDREFERENCIA FROM DEC_REFERENCIA(LAN.BDREFERENCIA, 12)) AND LAN.BDREFERENCIA) AND
                      MOV.BDMODELO = 55 AND
                             MOV.BDCODSITNF NOT IN (2, 3, 4, 5, 6, 7) AND
                      ((GER.BDDEV_VENDAS = 'FALSE') AND
                      NOT I.BDCODNAT IN (SELECT V.BDCODNAT_VENDAS
                                         FROM VEF_BASE_TVINCCODPLANODRCST V
                                         WHERE V.BDCODPLACONFDRCST = GER.BDCODPLACONFDRCST AND
                                               V.BDCODNAT_VENDAS IS NOT NULL)) AND
                      MOVPRO.BDCODPROD = LAN.BDCODPROD AND                     
                      MOVPRO.BDQTDITEM > 0
                UNION ALL
                       /* Quando for documento complementar, vai somar os valores dos produtos no primeiro produto da nota a ser complementada...
                          6 - Documento Fiscal Complementar
                          7 - Escrituração extemporânea de documento complementar */
                       SELECT mAux.bdCODEMP, LAN.BDREFERENCIA, movProAux.BDCODPROD, lan.bdQTDTOTAL, 0 AS bdIND_OPER, mAux.bdCHAVE, iAux.bdORDEM, movProAux.bdORDEMPRO,
                              mAux.bdCHAVENFE, NULL AS bdDT_NFE, mAux.bdDATAENTRADAENT AS bdDT_E, mAux.bdCODTER, movProAux.bdQTDITEM, movProAux.bdCODFATCON,
                              iAux.bdCODNAT, movProAux.bdALIQICMS, movProAux.bdALIQST, COALESCE(movPro.bdVLRST,0) AS bdVLRST, COALESCE(movpro.bdBCICMS,0) AS bdBCICMS,
                              COALESCE(movpro.bdVLRICMS,0) AS bdVLRICMS, COALESCE(movProAux.bdBCST,0) AS bdBCST, COALESCE(movpro.bdVLRICMSSTRET,0) AS bdVLRICMSSTRET, COALESCE(movpro.bdBCFCPRETIDO,0) AS bdBCFCPRETIDO,
                              COALESCE(movpro.bdBCFCPSTRET,0) AS bdBCFCPSTRET, COALESCE(movpro.bdBCICMSSTRET,0) AS bdBCICMSSTRET, COALESCE(movpro.bdFCPRETIDO,0) AS bdFCPRETIDO,
                              COALESCE(movpro.bdVLRFCPSTRET,0) AS bdVLRFCPSTRET, (COALESCE(movpro.bdVLRITEM,0) + COALESCE(movpro.bdVLRDESPACESSORIA,0)) BDVL_E,
                              CASE 
                                WHEN (Coalesce(movProAux.BDTIPO2134,0)) > 0 THEN 2
                                WHEN (COALESCE(movProAux.BDVLRST,0) + COALESCE(movProAux.BDFCPRETIDO,0)) > 0 THEN 1
                                WHEN (COALESCE(movProAux.BDVLRICMSSTRET,0) + COALESCE(movProAux.BDVLRFCPSTRET,0)) > 0 THEN 2
                                WHEN (MVA.BDICMSNR) > 0 THEN 3
                                ELSE 0 -- Busca informação na tela do MVA
                              END BDCOD_RESP_RET, movProAux.BDCODCSTICMS, LAN.BDCODPLACONFDRCST, MVA.BDICMS, MVA.BDALIQINT, MVA.BDARRECADACAO, MVA.BDNARREST BDNUM_DA, MVA.BDICMSNR,
                              (SELECT FIRST 1 AJU.BDCODAJUPAD
                               FROM VEF_EMP_TC197ENT C197
                               LEFT OUTER JOIN VEF_BASE_TTABCODAJU AJU ON (AJU.BDCODAJU = C197.BDCODAJU)
                        WHERE C197.BDCODEMP = movProAux.BDCODEMP AND C197.BDCHAVE = movProAux.BDCHAVE AND C197.BDCODPROD = movProAux.BDCODPROD) BDCOD_AJ,
                       movPro.bdCHAVE AS bdCHAVE_COMP, movPro.bdORDEM AS BDORDEM_COMP, movPro.bdORDEMPRO AS BDORDEMPRO_COMP, MOVPRO.BDTIPO2134
                       FROM (
                              SELECT D.BDCODEMP, D.BDREFERENCIA, D.BDCODPROD, G.BDCODPLACONFDRCST,
                                    SUM(D.BDQTD) BDQTDTOTAL
                              FROM ( SELECT D.BDCODEMP, D.BDREFERENCIA, D.BDCODPROD, D.BDQTDE_V_CF AS BDQTD
                                     FROM TMP_VEF_EMP_TDRCST_2112_TEMP D
                                     WHERE D.BDSESSAO = :PRSESSAO
                                     UNION ALL
                                     SELECT D.BDCODEMP, D.BDREFERENCIA, D.BDCODPROD, D.BDQTDE_IND_S_C AS BDQTD
                                     FROM TMP_VEF_EMP_TDRCST_2113_TEMP D
                                     WHERE D.BDSESSAO = :PRSESSAO AND
                                       NOT EXISTS(SELECT FIRST 1 S.BDCODEMP
                                                  FROM VEF_EMP_TMOVSTC176 S
                                                  WHERE S.BDCODEMP = D.BDCODEMP AND
                                                        S.BDCHAVE = D.BDCHAVE AND
                                                        S.BDORDEM = D.BDORDEM AND
                                                        S.BDORDEMPRO = D.BDORDEMPRO)) D
                              LEFT OUTER JOIN TMP_VEF_EMP_TDRCSTGER_TEMP G ON (G.BDSESSAO = :PRSESSAO AND G.BDCODEMP = D.BDCODEMP AND G.BDREFERENCIA = D.BDREFERENCIA)
                              LEFT OUTER JOIN VEF_BASE_TPLACONFDRCST P ON (P.BDCODPLACONFDRCST = G.BDCODPLACONFDRCST)
                              WHERE COALESCE(P.BDAPENASC176,'FALSE') = 'FALSE' AND
                                    D.BDQTD > 0
                              GROUP BY D.BDCODEMP, D.BDREFERENCIA, D.BDCODPROD, G.BDCODPLACONFDRCST
                              ) LAN
                       JOIN VEF_EMP_TMOVENT MOV ON (MOV.BDCODEMP = LAN.BDCODEMP)
                       JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                       JOIN VEF_EMP_TMOVPROENT MOVPRO ON (MOVPRO.BDCODEMP = I.BDCODEMP AND MOVPRO.BDCHAVE = I.BDCHAVE AND MOVPRO.BDORDEM = I.BDORDEM)
                       INNER JOIN VEF_EMP_TMOVENTDOCFREF c113 ON (c113.bdCODEMP = mov.bdCODEMP AND c113.bdCHAVE = mov.bdCHAVE)
                       INNER JOIN VEF_BASE_TTABDOCFIS docFisc ON (docFisc.bdCODDOCFIS = c113.bdCODDOCFIS AND docFisc.bdDOCFIS = '55') -- Apenas modelo "55"...
                       INNER JOIN VEF_EMP_TMOVENT mAux ON (mAux.bdCODEMP = c113.bdcodemp AND mAux.bdCHAVENFE = c113.bdCHAVENFE AND mAux.bdCODSITNF NOT IN (2, 3, 4, 5, 6, 7)) -- Vincula apenas pela Chave NF-e...
                       LEFT OUTER JOIN (SELECT i.bdCODEMP, i.bdCHAVE, MIN(i.bdORDEM) AS bdORDEM, MIN(i.bdCODNAT) AS bdCODNAT
                                   FROM VEF_EMP_TMOVENTITENS i
                                   GROUP BY i.bdCODEMP, i.bdCHAVE) iAux ON (iAux.bdCODEMP = mAux.bdCODEMP AND iAux.bdCHAVE = mAux.bdCHAVE)
                       LEFT OUTER JOIN (SELECT p.bdCODEMP, p.bdCHAVE, p.bdORDEM, MIN(p.bdORDEMPRO) AS bdORDEMPRO, p.bdCODPROD, p.bdALIQICMS, p.bdCODCSTICMS, p.bdCODFATCON,
                                               SUM(COALESCE(p.bdQTDITEM,0)) AS bdQTDITEM, p.bdALIQST, COALESCE(p.bdBCST,0) AS bdBCST, COALESCE(p.bdVLRST,0) AS bdVLRST,
                                               COALESCE(p.bdFCPRETIDO,0) AS bdFCPRETIDO, COALESCE(p.bdVLRICMSSTRET,0) AS bdVLRICMSSTRET, COALESCE(p.bdVLRFCPSTRET,0) AS bdVLRFCPSTRET,
                                               p.BDTIPO2134
                                        FROM VEF_EMP_TMOVPROENT p
                                        GROUP BY p.bdCODEMP, p.bdCHAVE, p.bdORDEM, p.bdCODPROD, p.bdALIQICMS, p.bdCODCSTICMS, p.bdCODFATCON, p.bdALIQST, p.bdBCST, p.bdVLRST, p.bdFCPRETIDO, p.bdVLRICMSSTRET, p.bdVLRFCPSTRET, p.BDTIPO2134
                                        ) movProAux ON (movProAux.bdCODEMP = iAux.bdCODEMP AND movProAux.bdCHAVE = iAux.bdCHAVE AND movProAux.bdORDEM = iAux.bdORDEM AND movProAux.bdCODPROD = movPro.bdCODPROD)
                       JOIN TMP_VEF_EMP_TDRCSTGER_TEMP GER ON (GER.BDSESSAO = :PRSESSAO AND GER.BDCODEMP = LAN.BDCODEMP AND GER.BDREFERENCIA = LAN.BDREFERENCIA)
                       LEFT OUTER JOIN VEF_EMP_TMOVMVASC MVA ON (MVA.BDCODEMP = MOVPROAUX.BDCODEMP AND MVA.BDCHAVE = MOVPROAUX.BDCHAVE AND MVA.BDORDEM = MOVPROAUX.BDORDEM AND MVA.BDCODPROD = MOVPROAUX.BDCODPROD)
                       --WHERE (MOV.BDREFLAN BETWEEN(SELECT BDREFERENCIA FROM DEC_REFERENCIA(LAN.BDREFERENCIA, 12)) AND LAN.BDREFERENCIA) -- Alt.: #151329 - A referencia, deve pesquisar na nota lançada e não na complementar...
                       WHERE (mAux.BDREFLAN BETWEEN(SELECT BDREFERENCIA FROM DEC_REFERENCIA(LAN.BDREFERENCIA, 12)) AND LAN.BDREFERENCIA) -- Alt.: #151329 - A referencia, deve pesquisar na nota lançada...
                         AND MOV.BDMODELO = 55
                         AND MOV.BDCODSITNF IN (6, 7)
                         AND ((GER.BDDEV_VENDAS = 'FALSE')
                         AND NOT I.BDCODNAT IN (SELECT V.BDCODNAT_VENDAS
                                                FROM VEF_BASE_TVINCCODPLANODRCST V
                                                WHERE V.BDCODPLACONFDRCST = GER.BDCODPLACONFDRCST AND
                                                      V.BDCODNAT_VENDAS IS NOT NULL))
                         AND MOVPRO.BDCODPROD = LAN.BDCODPROD
                         AND MOVPRO.BDQTDITEM > 0
                       ) aux
                GROUP BY aux.bdCODEMP, aux.bdREFERENCIA, aux.bdCODPROD, aux.bdIND_OPER, aux.bdCHAVE, aux.bdORDEM, aux.bdORDEMPRO,
                         aux.bdCHAVENFE, aux.bdDT_E, aux.bdCODTER, aux.bdCODFATCON,
                         aux.bdCODNAT, aux.bdALIQICMS, aux.bdALIQST, 
                         aux.bdCOD_RESP_RET, aux.bdCODCSTICMS, aux.bdCODPLACONFDRCST, aux.bdICMS, aux.bdALIQINT, aux.bdARRECADACAO, aux.bdNUM_DA, aux.bdICMSNR, aux.BDCOD_AJ
                UNION ALL
                SELECT LAN.BDCODEMP, LAN.BDREFERENCIA, MOVPRO.BDCODPROD, LAN.BDQTDTOTAL, 1 BDIND_OPER, MOV.BDCHAVE, I.BDORDEM, MOVPRO.BDORDEMPRO,
                       MOV.BDCHAVENFE, MOV.BDDATAEMISSAO BDDT_NFE, NULL BDDT_E, MOV.BDCODTER, MOVPRO.BDQTDITEM, MOVPRO.BDCODFATCON,
                       I.BDCODNAT,   
                       COALESCE(MOVD.BDALIQICMS, MOVPRO.BDALIQICMS) BDALIQICMS,
                       COALESCE(MOVD.BDALIQST, MOVPRO.BDALIQST) BDALIQST,
                       COALESCE(CAST((MOVPRO.BDQTDITEM / MOVD.BDQTDITEM) * COALESCE(MOVD.BDVLRST,0) AS NUMERIC(15,2)), COALESCE(MOVPRO.BDVLRST,0)) BDVLRST,
                       COALESCE(CAST((MOVPRO.BDQTDITEM / MOVD.BDQTDITEM) * COALESCE(MOVD.BDBCICMS,0) AS NUMERIC(15,2)), COALESCE(MOVPRO.BDBCICMS,0)) BDBCICMS,
                       COALESCE(CAST((MOVPRO.BDQTDITEM / MOVD.BDQTDITEM) * COALESCE(MOVD.BDVLRICMS,0) AS NUMERIC(15,2)), COALESCE(MOVPRO.BDVLRICMS,0)) BDVLRICMS,
                       COALESCE(CAST((MOVPRO.BDQTDITEM / MOVD.BDQTDITEM) * COALESCE(MOVD.BDBCST,0) AS NUMERIC(15,2)), COALESCE(MOVPRO.BDBCST,0)) BDBCST,
                       COALESCE(CAST((MOVPRO.BDQTDITEM / MOVD.BDQTDITEM) * COALESCE(MOVD.BDVLRICMSSTRET,0) AS NUMERIC(15,2)), COALESCE(MOVPRO.BDVLRICMSSTRET,0)) BDVLRICMSSTRET,
                       COALESCE(CAST((MOVPRO.BDQTDITEM / MOVD.BDQTDITEM) * COALESCE(MOVD.BDBCFCPRETIDO,0) AS NUMERIC(15,2)), COALESCE(MOVPRO.BDBCFCPRETIDO,0)) BDBCFCPRETIDO,
                       COALESCE(CAST((MOVPRO.BDQTDITEM / MOVD.BDQTDITEM) * COALESCE(MOVD.BDBCFCPSTRET,0) AS NUMERIC(15,2)), COALESCE(MOVPRO.BDBCFCPSTRET,0)) BDBCFCPSTRET,
                       COALESCE(CAST((MOVPRO.BDQTDITEM / MOVD.BDQTDITEM) * COALESCE(MOVD.BDBCICMSSTRET,0) AS NUMERIC(15,2)), COALESCE(MOVPRO.BDBCICMSSTRET,0)) BDBCICMSSTRET,
                       COALESCE(CAST((MOVPRO.BDQTDITEM / MOVD.BDQTDITEM) * COALESCE(MOVD.BDFCPRETIDO,0) AS NUMERIC(15,2)), COALESCE(MOVPRO.BDFCPRETIDO,0)) BDFCPRETIDO,
                       COALESCE(CAST((MOVPRO.BDQTDITEM / MOVD.BDQTDITEM) * COALESCE(MOVD.BDVLRFCPSTRET,0) AS NUMERIC(15,2)), COALESCE(MOVPRO.BDVLRFCPSTRET,0)) BDVLRFCPSTRET,
                       COALESCE(CAST((MOVPRO.BDQTDITEM / MOVD.BDQTDITEM) * (COALESCE(MOVD.BDVLRITEM,0) + COALESCE(MOVD.BDVLRDESPACESSORIA,0)) AS NUMERIC(15,2)), (COALESCE(MOVPRO.BDVLRITEM,0) + COALESCE(MOVPRO.BDVLRDESPACESSORIA,0)))  BDVL_E,
                       CASE
                         WHEN COALESCE((COALESCE(MOVPRO.BDVLRST,0) + COALESCE(MOVPRO.BDFCPRETIDO,0)), (COALESCE(MOVD.BDVLRST,0) + COALESCE(MOVD.BDFCPRETIDO,0))) > 0 THEN 1
                         WHEN COALESCE((COALESCE(MOVPRO.BDVLRICMSSTRET,0) + COALESCE(MOVPRO.BDVLRFCPSTRET,0)), (COALESCE(MOVD.BDVLRICMSSTRET,0) + COALESCE(MOVD.BDVLRFCPSTRET,0))) > 0 THEN 2
                         ELSE 0
                       END BDCOD_RESP_RET, MOVPRO.BDCODCSTICMS, LAN.BDCODPLACONFDRCST, 0 BDICMS, 0 BDALIQINT, NULL BDARRECADACAO, NULL BDNUM_DA, 0 BDICMSNR,
                      (SELECT FIRST 1 AJU.BDCODAJUPAD
                       FROM VEF_EMP_TC197SAI C197
                       LEFT OUTER JOIN VEF_BASE_TTABCODAJU AJU ON (AJU.BDCODAJU = C197.BDCODAJU)
                       WHERE C197.BDCODEMP = MOVPRO.BDCODEMP AND C197.BDCHAVE = MOVPRO.BDCHAVE AND C197.BDCODPROD = MOVPRO.BDCODPROD) BDCOD_AJ, NULL AS bdLISTCOMP, NULL BDTIPO2134
                FROM ( SELECT D.BDCODEMP, G.BDREFERENCIA, D.BDCODPROD, G.BDCODPLACONFDRCST, SUM(D.BDQTD) BDQTDTOTAL
                       FROM ( SELECT D.BDCODEMP, D.BDREFERENCIA, D.BDCODPROD, D.BDQTDE_V_CF AS BDQTD
                              FROM TMP_VEF_EMP_TDRCST_2112_TEMP D
                              WHERE D.BDSESSAO = :PRSESSAO
                              UNION ALL
                              SELECT D.BDCODEMP, D.BDREFERENCIA, D.BDCODPROD, D.BDQTDE_IND_S_C AS BDQTD
                              FROM TMP_VEF_EMP_TDRCST_2113_TEMP D
                              WHERE D.BDSESSAO = :PRSESSAO) D
                       LEFT OUTER JOIN TMP_VEF_EMP_TDRCSTGER_TEMP G ON (G.BDSESSAO = :PRSESSAO AND G.BDCODEMP = D.BDCODEMP AND G.BDREFERENCIA = D.BDREFERENCIA)
                       GROUP BY D.BDCODEMP, G.BDREFERENCIA, D.BDCODPROD, G.BDCODPLACONFDRCST
                ) LAN
                JOIN VEF_EMP_TMOVSAI MOV ON (MOV.BDCODEMP = LAN.BDCODEMP)
                JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                JOIN VEF_EMP_TMOVPROSAI MOVPRO ON (MOVPRO.BDCODEMP = I.BDCODEMP AND MOVPRO.BDCHAVE = I.BDCHAVE AND MOVPRO.BDORDEM = I.BDORDEM)
                JOIN TMP_VEF_EMP_TDRCSTGER_TEMP GER ON (GER.BDSESSAO = :PRSESSAO AND GER.BDCODEMP = LAN.BDCODEMP AND GER.BDREFERENCIA = LAN.BDREFERENCIA)
                LEFT OUTER JOIN (SELECT DOCF.BDCODEMP, DOCF.BDCHAVE, DOCF.BDDTEMISSAO
                                 FROM VEF_EMP_TMOVSAIDOCFREF DOCF
                                 WHERE NOT EXISTS(SELECT FIRST 1 X.BDCHAVE
                                                  FROM VEF_EMP_TMOVSAIDOCFREF X
                                                  WHERE X.BDCODEMP = DOCF.BDCODEMP AND
                                                        X.BDCHAVE = DOCF.BDCHAVE AND
                                                        (X.BDORDEMIC < DOCF.BDORDEMIC OR
                                                         X.BDORDEMDOCFREF < DOCF.BDORDEMDOCFREF))) DOCF ON (DOCF.BDCODEMP = MOV.BDCODEMP AND DOCF.BDCHAVE = MOV.BDCHAVE)
                LEFT OUTER JOIN (SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDREFLAN, MOVPRO.BDCODPROD, MOVPRO.BDQTDITEM,
                                       (COALESCE(MOVPRO.BDVLRITEM,0) / COALESCE(MOVPRO.BDQTDITEM,1)) BDVLRITEM_UNIDADE, (COALESCE(MOVPRO.BDVLRST,0) / COALESCE(MOVPRO.BDQTDITEM,1)) BDVLRST_UNIDADE,
                                       COALESCE(MOVPRO.BDVLRST,0) AS BDVLRST, COALESCE(MOVPRO.BDBCICMS,0) AS BDBCICMS, MOVPRO.BDALIQICMS, COALESCE(MOVPRO.BDVLRICMS,0) AS BDVLRICMS, COALESCE(MOVPRO.BDBCST,0) AS BDBCST,
                                       COALESCE(MOVPRO.BDVLRICMSSTRET,0) AS BDVLRICMSSTRET,COALESCE(MOVPRO.BDBCFCPRETIDO,0) AS BDBCFCPRETIDO, COALESCE(MOVPRO.BDBCFCPSTRET,0) AS BDBCFCPSTRET,
                                       COALESCE(MOVPRO.BDBCICMSSTRET,0) AS BDBCICMSSTRET, COALESCE(MOVPRO.BDFCPRETIDO,0) AS BDFCPRETIDO, COALESCE(MOVPRO.BDVLRFCPSTRET,0) AS BDVLRFCPSTRET,
                                       MOVPRO.BDALIQST, COALESCE(MOVPRO.BDVLRITEM,0) AS BDVLRITEM, COALESCE(MOVPRO.BDVLRDESPACESSORIA,0) AS BDVLRDESPACESSORIA
                                 FROM VEF_EMP_TMOVENT MOV
                                 JOIN VEF_EMP_TMOVPROENT MOVPRO ON (MOVPRO.BDCODEMP = MOV.BDCODEMP AND MOVPRO.BDCHAVE = MOV.BDCHAVE)
                                 WHERE EXISTS(SELECT M.BDCODEMP
                                              FROM (SELECT FIRST 1 MOVDPRO.BDCODEMP, MOVDPRO.BDCHAVE, MOVDPRO.BDORDEM, MOVDPRO.BDORDEMPRO
                                                    FROM VEF_EMP_TMOVENT MOVD
                                                    JOIN VEF_EMP_TMOVPROENT MOVDPRO ON (MOVDPRO.BDCODEMP = MOVD.BDCODEMP AND MOVDPRO.BDCHAVE = MOVD.BDCHAVE)
                                                    WHERE MOVDPRO.BDQTDITEM > 0 AND
                                                          MOVD.BDCODEMP = MOV.BDCODEMP AND
                                                          MOVD.BDREFLAN = MOV.BDREFLAN AND
                                                          MOVDPRO.BDCODPROD = MOVPRO.BDCODPROD AND
                                                          (MOVDPRO.BDVLRITEM / MOVDPRO.BDQTDITEM) = (MOVPRO.BDVLRITEM / MOVPRO.BDQTDITEM) AND
                                                          (MOVDPRO.BDVLRST / MOVDPRO.BDQTDITEM) = (MOVPRO.BDVLRST / MOVPRO.BDQTDITEM)) M

                                              WHERE M.BDCODEMP = MOVPRO.BDCODEMP AND
                                                    M.BDCHAVE = MOVPRO.BDCHAVE AND
                                                    M.BDORDEM = MOVPRO.BDORDEM AND
                                                    M.BDORDEMPRO = MOVPRO.BDORDEMPRO)
                                ) MOVD ON (MOVD.BDCODEMP = MOV.BDCODEMP AND MOVD.BDREFLAN = MOV.BDREFLAN AND
                                           MOVD.BDCODPROD = MOVPRO.BDCODPROD AND
                                           MOVD.BDVLRITEM_UNIDADE = (MOVPRO.BDVLRITEM / MOVPRO.BDQTDITEM) AND
                                           MOVD.BDVLRST_UNIDADE = (MOVPRO.BDVLRST / MOVPRO.BDQTDITEM))
                WHERE MOV.BDCODEMP = LAN.BDCODEMP AND
                      MOV.BDREFLAN = LAN.BDREFERENCIA AND
                      MOV.BDMODELO = 55 AND                      
                      MOV.BDCODSITNF NOT IN (2, 3, 4, 5) AND
                      ((GER.BDDEV_COMPRAS = 'TRUE') OR
                        I.BDCODNAT IN (SELECT V.BDCODNAT_COMPRAS
                                       FROM VEF_BASE_TVINCCODPLANODRCST V
                                       WHERE V.BDCODPLACONFDRCST = GER.BDCODPLACONFDRCST AND
                                             V.BDCODNAT_COMPRAS IS NOT NULL)) AND
                      MOVPRO.BDCODPROD = LAN.BDCODPROD    AND
                      MOVPRO.BDQTDITEM > 0 AND
                      ((DOCF.BDCHAVE > 0) OR (MOVD.BDCHAVE > 0))
                ) S     
             LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = S.BDCODTER)   
             LEFT OUTER JOIN TCADPRO_VINC PROD ON (PROD.BDCODPROD = S.BDCODPROD AND PROD.BDCODEMP = S.BDCODEMP) 
             LEFT OUTER JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = S.BDCODEMP)
             LEFT OUTER JOIN TCIDADE cid ON (cid.BDCODCID = EMP.BDCODCID)
             LEFT OUTER JOIN TUF uf ON (UF.BDCODUF = cid.BDCODUF)
             WHERE S.BDCOD_RESP_RET > 0   AND
                   CHAR_LENGTH(TER.BDCGCTER) = 18
             ORDER BY S.BDCODEMP, Coalesce(S.BDDT_E, S.BDDT_NFE) DESC, S.BDCODPROD
        )S
  LEFT OUTER JOIN TUNIDADEMEDIDA UNIPRO ON (UNIPRO.BDCODUNIMED = S.BDCODUNIMED)
  LEFT OUTER JOIN TFATCONV F ON (F.BDCODPROD = S.BDCODPROD AND F.BDCODEMP = S.BDCODEMP AND F.BDCODFATCON = S.BDCODFATCON)
  LEFT OUTER JOIN TUNIDADEMEDIDA UNIFATCONV ON (UNIFATCONV.BDCODUNIMED = F.BDCODUNIMED)
  LEFT OUTER JOIN TMP_VEF_EMP_TDRCSTGER_TEMP GER ON (GER.BDSESSAO = :PRSESSAO AND GER.BDCODEMP = S.BDCODEMP AND GER.BDREFERENCIA = S.BDREFERENCIA)
    WHERE ( (not EXISTS (SELECT FIRST 1 * FROM TMP_VEF_EMP_TDRCST_2130_TEMP TMP
                        WHERE TMP.BDSESSAO = BDSESSAO
                        AND TMP.BDCODEMP = S.BDCODEMP
                        AND TMP.BDREFERENCIA = S.BDREFERENCIA
                        AND TMP.BDCODPROD = S.BDCODPROD
                        AND TMP.BDCHV_NFE = S.BDCHV_NFE
                        AND TMP.BDORDEM = S.BDORDEM
                        AND TMP.BDORDEMPRO = S.BDORDEMPRO)) AND
                        S.BDORDEMPRO <> 0 and
            (GETQUANTIDADEPRODUTO(S.BDIND_OPER||'.'||S.BDCODEMP || '.' || S.BDCODPROD|| S.BDREFERENCIA, S.BDQTDE) < S.BDQTDTOTAL OR GER.BDREFERENCIA = CAST((EXTRACT(YEAR FROM S.BDDT_E) || LPAD(EXTRACT(MONTH FROM S.BDDT_E),2,'0')) AS INTEGER) ));


           
  -- 19 - Produto ignorado porque todas notas fiscais de entrada desse respectivo produto possuem o registro 2134 ou não tem destaque de ICMS ST retido anteriormente
/*  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDIND_OPER, BDCODPROD)
  SELECT 19 BDCODINC, S.BDCODEMP, S.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(S.BDCODEMP || '.' || S.BDREFERENCIA, S.BDCODEMP), '2130' BDREG,
         S.BDIND_OPER, S.BDCODPROD
  FROM TMP_VEF_EMP_TDRCST_2130_TEMP S
  WHERE S.BDSESSAO = :prSESSAO AND
        S.BDIND_OPER = 0 AND
     NOT EXISTS(SELECT FIRST 1 A.BDCODEMP
                FROM TMP_VEF_EMP_TDRCST_2130_TEMP A
                LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = A.BDCODEMP AND PRO.BDCHAVE = A.BDCHAVE AND PRO.BDORDEM = A.BDORDEM AND PRO.BDORDEMPRO = A.BDORDEMPRO)
                WHERE A.BDSESSAO = S.BDSESSAO AND
                      A.BDCODEMP = S.BDCODEMP AND
                      A.BDREFERENCIA = S.BDREFERENCIA AND
                      A.BDCODPROD = S.BDCODPROD AND
                      Coalesce(PRO.BDTIPO2134,0) = 0)
  GROUP BY S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD, S.BDIND_OPER;

 DELETE FROM TMP_VEF_EMP_TDRCST_2130_TEMP S
 WHERE S.BDSESSAO = :prSESSAO AND
       S.BDIND_OPER = 0 AND
     NOT EXISTS(SELECT FIRST 1 A.BDCODEMP
                FROM TMP_VEF_EMP_TDRCST_2130_TEMP A
                LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = A.BDCODEMP AND PRO.BDCHAVE = A.BDCHAVE AND PRO.BDORDEM = A.BDORDEM AND PRO.BDORDEMPRO = A.BDORDEMPRO)
                WHERE A.BDSESSAO = S.BDSESSAO AND
                      A.BDCODEMP = S.BDCODEMP AND
                      A.BDREFERENCIA = S.BDREFERENCIA AND
                      A.BDCODPROD = S.BDCODPROD AND
                      Coalesce(PRO.BDTIPO2134,0) = 0);   */

END
^


create or alter procedure SP_APURACAO_DRCST_2132 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN  
  insert into TMP_VEF_EMP_TDRCST_2132_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD,BDIND_OPER, BDCHAVE,
                                            BDORDEM, BDORDEMPRO, BDORDEMIC, BDORDEMDOCFREF, BDCODTER, BDCNPJ, BDCHV_NFE_REF, BDDT_E_REF)
  SELECT :PRSESSAO BDSESSAO, S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD, S.BDIND_OPER, S.BDCHAVE,
         S.BDORDEM, S.BDORDEMPRO, S.BDORDEMIC, S.BDORDEMDOCFREF, S.BDCODTER, TER.BDCGCTER BDCNPJ, S.BDCHAVENFE BDCHV_NFE_REF, S.BDDTEMISSAO BDDT_E_REFF
  FROM( SELECT S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD, S.BDIND_OPER, S.BDCHAVE,
               S.BDORDEM, S.BDORDEMPRO, D.BDORDEMIC, D.BDORDEMDOCFREF, D.BDCODTER, D.BDCHAVENFE, D.BDDTEMISSAO
        FROM TMP_VEF_EMP_TDRCST_2130_TEMP S
        INNER JOIN VEF_EMP_TMOVSAIDOCFREF D ON (D.BDCODEMP = S.BDCODEMP AND D.BDCHAVE = S.BDCHAVE)
        LEFT OUTER JOIN VEF_BASE_TTABDOCFIS MODELO ON (MODELO.BDCODDOCFIS = D.BDCODDOCFIS)
        WHERE S.BDSESSAO = :PRSESSAO AND S.BDIND_OPER = 1 AND MODELO.BDDOCFIS = '55'
        ) S
  LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = S.BDCODTER)
  WHERE STRLEN(Coalesce(TER.BDCGCTER,'')) = 18;
END
^

create or alter procedure SP_APURACAO_DRCST_2133 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCHAVECOMP INTEGER;
DECLARE VARIABLE WORDEMCOMP INTEGER;
DECLARE VARIABLE WORDEMPROCOMP INTEGER;
DECLARE VARIABLE WLISTCOMP VARCHAR(2000);
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WAUX VARCHAR(200);
DECLARE VARIABLE WSTRAUX VARCHAR(2000);
BEGIN
  FOR
    SELECT s.bdCODEMP, s.bdLISTCOMP
    FROM TMP_VEF_EMP_TDRCST_2130_TEMP s
    WHERE s.bdSESSAO = :prSESSAO
      --AND s.bdIND_OPER = 1
      AND (s.bdLISTCOMP IS NOT NULL) AND (s.bdLISTCOMP <> '')
    INTO :wCodEmp, :wListComp DO
  BEGIN
    SELECT POS.POS FROM POS(',',:wListComp) INTO :wPos;
    IF (:wPos = 0) THEN
      SELECT FIRST 1 SUBSTRING(:wListComp FROM 1 FOR CHAR_LENGTH(:wListComp)) FROM TMP_VEF_EMP_TDRCST_2130_TEMP s INTO :wStrAux;
    ELSE
      SELECT FIRST 1 SUBSTRING(:wListComp FROM 1 FOR :wPos-1) FROM TMP_VEF_EMP_TDRCST_2130_TEMP s INTO :wStrAux;
    WHILE (:wStrAux <> '') DO
      BEGIN
        -- Obt m os campos da lista que compoem o 2133...
        SELECT POS.POS FROM POS('.',:wStrAux) INTO :wPos;
        SELECT FIRST 1 SUBSTRING(:wListComp FROM 1 FOR :wPos-1) FROM TMP_VEF_EMP_TDRCST_2130_TEMP s INTO :wChaveComp;

        SELECT FIRST 1 SUBSTRING(:wStrAux FROM :wPos+1 FOR CHAR_LENGTH(:wStrAux)) FROM TMP_VEF_EMP_TDRCST_2130_TEMP s INTO :wAux;
        SELECT POS.POS FROM POS('.',:wAux) INTO :wPos;
        SELECT FIRST 1 SUBSTRING(:wAux FROM 1 FOR :wPos-1) FROM TMP_VEF_EMP_TDRCST_2130_TEMP s INTO :wOrdemComp;

        SELECT FIRST 1 SUBSTRING(:wAux FROM :wPos+1 FOR CHAR_LENGTH(:wAux)) FROM TMP_VEF_EMP_TDRCST_2130_TEMP s INTO :wOrdemProComp;

        -- Grava o 2133
        INSERT INTO TMP_VEF_EMP_TDRCST_2133_TEMP (bdSESSAO, bdCODEMP, bdREFERENCIA, bdCODPROD, bdIND_OPER, bdCHAVE, bdORDEM, bdORDEMPRO,
                                                        bdORDEM2133, bdCHV_NFE_COMP, bdNUM_ITEM_NFE_COMP, bdCHAVE_COMP, bdORDEM_COMP, bdORDEMPRO_COMP, bdQTDITEM, bdVLRITEM)
              SELECT :prSESSAO bdSESSAO, s.bDCODEMP, s.bdREFERENCIA, s.bdCODPROD, s.bdIND_OPER, s.bdCHAVE, s.bdORDEM, s.bdORDEMPRO,
                     GETORDEMSEQUENCIAL_STR('2133.'||s.bdCODEMP||'.'||s.bdCHAVE, s.bdCODEMP) AS bdORDEM2133, sai.bdCHAVENFE AS bdCHV_NFE_COMP,
                     s.bdORDEMPRO AS bdNUM_ITEM_NFE_COMP, p.bdCHAVE AS bdCHAVE_COMP, p.bdORDEM AS bdORDEM_COMP, p.bdORDEMPRO AS bdORDEMPRO_COMP, p.bdQTDITEM, COALESCE(p.bdVLRITEM,0) AS bdVLRITEM
        FROM(
                    SELECT s.bdCODEMP, s.bdREFERENCIA, s.bdCODPROD, s.bdIND_OPER, s.bdCHAVE, s.bdORDEM, s.bdORDEMPRO
                    FROM TMP_VEF_EMP_TDRCST_2130_TEMP s
                    WHERE s.bdSESSAO = :prSESSAO
                      --AND s.bdIND_OPER = 1
                      AND s.bdLISTCOMP LIKE '%'||:wStrAux||'%'
                    ) s
              INNER JOIN VEF_EMP_TMOVENT sai ON (sai.bdCODEMP = s.bdCODEMP AND sai.bdCHAVE = :wChaveComp)
              INNER JOIN VEF_EMP_TMOVPROENT p ON (p.bdCODEMP = sai.bdCODEMP AND p.bdCHAVE = :wChaveComp AND p.bdORDEM = :wOrdemComp AND p.bdORDEMPRO = :wOrdemProComp);
      
              -- Busca o próximo registro da lista, depois do ","
              SELECT FIRST 1 SUBSTRING(:wListComp FROM CHAR_LENGTH(:wStrAux)+2 FOR CHAR_LENGTH(:wListComp)) FROM TMP_VEF_EMP_TDRCST_2130_TEMP s INTO :wListComp;
              SELECT POS.POS FROM POS(',',:wListComp) INTO :wPos;
              IF (:wPos = 0) THEN
                SELECT FIRST 1 SUBSTRING(:wListComp FROM 1 FOR CHAR_LENGTH(:wListComp)) FROM TMP_VEF_EMP_TDRCST_2130_TEMP s INTO :wStrAux;
              ELSE
                SELECT FIRST 1 SUBSTRING(:wListComp FROM 1 FOR :wPos-1) FROM TMP_VEF_EMP_TDRCST_2130_TEMP s INTO :wStrAux;
      
      END
  END

END
^

create or alter procedure SP_APURACAO_DRCST_2134 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN                                                                    
  insert into TMP_VEF_EMP_TDRCST_2134_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDIND_OPER, BDCHAVE,
                                            BDORDEM, BDORDEMPRO, BDORDEM2134, BDCOD_IND_XML)
  SELECT :PRSESSAO BDSESSAO, S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD, S.BDIND_OPER, S.BDCHAVE,
          S.BDORDEM, S.BDORDEMPRO, S.BDORDEM2134, S.BDCOD_IND_XML
  FROM( SELECT S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD, S.BDIND_OPER, S.BDCHAVE,
               S.BDORDEM, S.BDORDEMPRO, GETORDEMSEQUENCIAL_STR('2134.'||s.bdCODEMP||'.'||s.bdCHAVE, s.bdCODEMP) BDORDEM2134, '1' BDCOD_IND_XML
        FROM TMP_VEF_EMP_TDRCST_2130_TEMP S
        WHERE S.BDSESSAO = :PRSESSAO
              --AND S.BDCOD_RESP_RET = 2
              AND S.BDIND_OPER = 0 -- Entrada
              AND ((SELECT FIRST 1 PRO.BDTIPO2134 FROM VEF_EMP_TMOVPROENT PRO WHERE PRO.BDCODEMP = S.BDCODEMP AND PRO.BDCHAVE = S.BDCHAVE AND PRO.BDORDEM = S.BDORDEM AND PRO.BDORDEMPRO = S.BDORDEMPRO) = 1)
        --  AND (SELECT Coalesce(P.BDBCICMSSTRET,0) + Coalesce(P.BDVLRICMSSTRET,0) FROM VEF_EMP_TMOVPROENT P WHERE P.BDCODEMP = S.BDCODEMP AND P.BDCHAVE = S.BDCHAVE AND P.BDORDEM = S.BDORDEM AND P.BDORDEMPRO = S.BDORDEMPRO) = 0
        ) S;
END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_DRCST_2120 (
    PRSESSAO INTEGER,
    PRDATAINICIO DATE,
    PRDATAFIM DATE,
    PRCODPLACONFDRCST integer)
AS
declare variable WIGNORARCOMP DM_BOOLEAN;
BEGIN
  -- Alt.: #132676 - Obtem a configuração de "Ignorar lançamentos sem compra com destaque de ICMS ST e ICMS ST Retido" do plano DRCST.
  SELECT COALESCE(UPPER(bdIGNORARCOMP),'FALSE')
  FROM VEF_BASE_TPLACONFDRCST
  WHERE bdCODPLACONFDRCST = :prCODPLACONFDRCST
  INTO :wIGNORARCOMP;

  INSERT INTO TMP_VEF_EMP_TDRCST_2120_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDS_QTDE_C, BDS_VL_BCST_INT,
                                            BDVLM_UNIT_BCST, BDS_VL_ICMS, BDVLM_UNIT_ICMS, BDS_VL_ICMS_ST,
                                            BDVLM_UNIT_ICMS_ST)
  SELECT :PRSESSAO BDSESSAO, S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD, S.BDS_QTDE_C,
          S.BDS_VL_BCST_INT, --IIF(S.BDS_QTDE_C > 0,S.BDS_VL_BCST_INT / S.BDS_QTDE_C,0) BDVLM_UNIT_BCST,
          CAST(IIF(S.BDS_QTDE_C > 0,S.BDS_VL_BCST_INT / S.BDS_QTDE_C,0) AS NUMERIC(15,2)) BDVLM_UNIT_BCST, -- Alt.: #154462 #157391 - Deve arredondar os valores em duas casas decimais...
          S.BDS_VL_ICMS, IIF(S.BDS_QTDE_C > 0,S.BDS_VL_ICMS / S.BDS_QTDE_C,0) BDVLM_UNIT_ICMS, S.BDS_VL_ICMS_ST,
          IIF(S.BDS_QTDE_C > 0,S.BDS_VL_ICMS_ST / S.BDS_QTDE_C,0) BDVLM_UNIT_ICMS_ST
  FROM(
       SELECT  S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD, SUM(BDS_QTDE_C) BDS_QTDE_C,
       SUM(BDS_VL_BCST_INT) BDS_VL_BCST_INT,SUM(BDS_VL_ICMS) BDS_VL_ICMS, SUM(BDS_VL_ICMS_ST) BDS_VL_ICMS_ST
       FROM (
             SELECT S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD,
                    SUM(IIF(S.BDIND_OPER = 0,S.BDQTDE_C,-S.BDQTDE_C)) BDS_QTDE_C,
                    SUM(IIF(S.BDIND_OPER = 0,S.BDVL_BCST_INT,-S.BDVL_BCST_INT)) BDS_VL_BCST_INT,
               SUM(IIF(S.BDIND_OPER = 0,S.BDVL_ICMS,-S.BDVL_ICMS)) BDS_VL_ICMS, SUM(IIF(S.BDIND_OPER = 0,S.BDVL_ICMS_ST,-S.BDVL_ICMS_ST)) BDS_VL_ICMS_ST
        FROM TMP_VEF_EMP_TDRCST_2130_TEMP S
        WHERE S.BDSESSAO = :PRSESSAO AND
              NOT EXISTS(SELECT FIRST 1 AUX.BDCODEMP FROM TMP_VEF_EMP_TDRCST_2134_TEMP AUX WHERE AUX.BDSESSAO = S.BDSESSAO AND AUX.BDCODEMP = S.BDCODEMP AND AUX.BDREFERENCIA = S.BDREFERENCIA AND AUX.BDCODPROD = S.BDCODPROD AND AUX.BDCHAVE = S.BDCHAVE AND AUX.BDORDEM = S.BDORDEM AND AUX.BDORDEMPRO = S.BDORDEMPRO)
             GROUP BY S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD
             UNION ALL
             SELECT S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD,
                    0 BDS_QTDE_C,
                    0 BDS_VL_BCST_INT,0 BDS_VL_ICMS, 0 BDS_VL_ICMS_ST
                    FROM TMP_VEF_EMP_TDRCST_2130_TEMP S
                    WHERE S.BDSESSAO = :PRSESSAO AND
                          EXISTS(SELECT FIRST 1 AUX.BDCODEMP FROM TMP_VEF_EMP_TDRCST_2134_TEMP AUX WHERE AUX.BDSESSAO = S.BDSESSAO AND AUX.BDCODEMP = S.BDCODEMP AND AUX.BDREFERENCIA = S.BDREFERENCIA AND AUX.BDCODPROD = S.BDCODPROD AND AUX.BDCHAVE = S.BDCHAVE AND AUX.BDORDEM = S.BDORDEM AND AUX.BDORDEMPRO = S.BDORDEMPRO)
                    GROUP BY S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD
            ) S
        GROUP BY S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD
       ) S
  WHERE (:WIGNORARCOMP <> 'TRUE') 
     OR (EXISTS(SELECT * -- ALT.: #132676 - CASO A opção ESTEJA MARCADA, APENAS LEVA PARA O 2110, CASO TENHA O PRODUTO NO 2130...
                FROM TMP_VEF_EMP_TDRCST_2130_TEMP T2130
                WHERE T2130.BDSESSAO     = :PRSESSAO
                  AND T2130.BDCODEMP     = S.BDCODEMP
                  AND T2130.BDREFERENCIA = S.BDREFERENCIA
                  AND T2130.BDCODPROD    = S.BDCODPROD));

--  INSERT INTO TMP_VEF_EMP_TDRCST_2120_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDS_QTDE_C, BDS_VL_BCST_INT,
--                                            BDVLM_UNIT_BCST, BDS_VL_ICMS, BDVLM_UNIT_ICMS, BDS_VL_ICMS_ST,
--                                            BDVLM_UNIT_ICMS_ST)
--  SELECT :PRSESSAO BDSESSAO, S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD, 0 BDS_QTDE_C,
--          0 BDS_VL_BCST_INT, 0 BDVLM_UNIT_BCST,
--          0 BDS_VL_ICMS, 0 BDVLM_UNIT_ICMS, 0 BDS_VL_ICMS_ST,
--          0 BDVLM_UNIT_ICMS_ST
--  FROM( SELECT S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD
--        FROM TMP_VEF_EMP_TDRCST_2130_TEMP S
--        WHERE S.BDSESSAO = :PRSESSAO AND
--              NOT EXISTS(SELECT FIRST 1 AUX.BDCODEMP FROM TMP_VEF_EMP_TDRCST_2120_TEMP AUX WHERE AUX.BDSESSAO = S.BDSESSAO AND AUX.BDCODEMP = S.BDCODEMP AND AUX.BDREFERENCIA = S.BDREFERENCIA AND AUX.BDCODPROD = S.BDCODPROD)
--        GROUP BY S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD) S
--  WHERE (:wIGNORARCOMP <> 'TRUE') 
--     OR (EXISTS(SELECT * -- Alt.: #132676 - Caso a opção esteja marcada, apenas leva para o 2110, caso tenha o produto no 2130...
--                FROM TMP_VEF_EMP_TDRCST_2130_TEMP t2130
--                WHERE t2130.bdSESSAO     = :prSESSAO
--                  AND t2130.BDCODEMP     = s.bdCODEMP
--                  AND t2130.bdREFERENCIA = s.bdREFERENCIA
--                  AND t2130.bdCODPROD    = s.bdCODPROD))
--  ;
END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_DRCST_2110 (
    PRSESSAO INTEGER,
    PRDATAINICIO DATE,
    PRDATAFIM DATE,
    PRCODPLACONFDRCST integer)
AS
declare variable WIGNORARCOMP DM_BOOLEAN;
BEGIN
  wIGNORARCOMP = 'FALSE';
  -- Alt.: #132676 - Obtem a configuração de "Ignorar lançamentos sem compra com destaque de ICMS ST e ICMS ST Retido" do plano DRCST.
  SELECT COALESCE(UPPER(bdIGNORARCOMP),'FALSE')
  FROM VEF_BASE_TPLACONFDRCST
  WHERE bdCODPLACONFDRCST = :prCODPLACONFDRCST
  INTO :wIGNORARCOMP;
  
  
  IF (:wIGNORARCOMP = 'TRUE') THEN
    BEGIN
      /* Alt.: #132676 - Quando não tiver marcada, deleta os lançamentos que não geraram o 2130.
         Deleta aqui pois usa o 2112 e 2113 para gerar o 2130 também... */
      DELETE FROM TMP_VEF_EMP_TDRCST_2112_TEMP t2112
      WHERE NOT EXISTS(SELECT * 
                       FROM TMP_VEF_EMP_TDRCST_2130_TEMP t2130
                       WHERE t2130.bdSESSAO     = :prSESSAO
                         AND t2130.BDCODEMP     = t2112.bdCODEMP
                         AND t2130.bdREFERENCIA = t2112.bdREFERENCIA
                         AND t2130.bdCODPROD    = t2112.bdCODPROD);
    
      DELETE FROM TMP_VEF_EMP_TDRCST_2113_TEMP t2113
      WHERE NOT EXISTS(SELECT * 
                       FROM TMP_VEF_EMP_TDRCST_2130_TEMP t2130
                       WHERE t2130.bdSESSAO     = :prSESSAO
                         AND t2130.BDCODEMP     = t2113.bdCODEMP
                         AND t2130.bdREFERENCIA = t2113.bdREFERENCIA
                         AND t2130.bdCODPROD    = t2113.bdCODPROD);

      /*#239772 Apuração DRCST - erro usando opção de ignorar compra sem ST*/
      DELETE FROM TMP_VEF_EMP_TDRCST_2114_TEMP t2114
      WHERE NOT EXISTS(SELECT * 
                       FROM TMP_VEF_EMP_TDRCST_2130_TEMP t2130
                       WHERE t2130.bdSESSAO     = :prSESSAO
                         AND t2130.BDCODEMP     = t2114.bdCODEMP
                         AND t2130.bdREFERENCIA = t2114.bdREFERENCIA
                         AND t2130.bdCODPROD    = t2114.bdCODPROD);

      DELETE FROM TMP_VEF_EMP_TDRCST_2115_TEMP t2115
      WHERE NOT EXISTS(SELECT * 
                       FROM TMP_VEF_EMP_TDRCST_2130_TEMP t2130
                       WHERE t2130.bdSESSAO     = :prSESSAO
                         AND t2130.BDCODEMP     = t2115.bdCODEMP
                         AND t2130.bdREFERENCIA = t2115.bdREFERENCIA
                         AND t2130.bdCODPROD    = t2115.bdCODPROD);
    
    END

  /* Alt: #144919 - Alterado a regra dos campos BDVL_V_CF e BDQTDE_V_CF */
  UPDATE TMP_VEF_EMP_TDRCST_2112_TEMP T2112                                                                                                                                                                                                                                             
  SET T2112.BDVL_V_CF = T2112.BDVL_V_CF * CAST(TRUNC((SELECT IIF((Coalesce(S.BDS_QTDE_C,0) + Coalesce(S2.BDS_QTDE_C_T,0)) < T2112.BDQTDE_V_CF,(Coalesce(S.BDS_QTDE_C,0) + Coalesce(S2.BDS_QTDE_C_T,0)),T2112.BDQTDE_V_CF) FROM TMP_VEF_EMP_TDRCST_2120_TEMP S LEFT OUTER JOIN TMP_VEF_EMP_TDRCST_2121_TEMP S2 ON (S2.BDSESSAO = T2112.BDSESSAO AND S2.BDCODEMP = T2112.BDCODEMP AND S2.BDREFERENCIA = T2112.BDREFERENCIA AND S2.BDCODPROD = T2112.BDCODPROD) WHERE S.BDSESSAO = T2112.BDSESSAO AND S.BDCODEMP = T2112.BDCODEMP AND S.BDREFERENCIA = T2112.BDREFERENCIA AND S.BDCODPROD = T2112.BDCODPROD) / T2112.BDQTDE_V_CF,5) AS NUMERIC(15,5)),
      T2112.BDQTDE_V_CF = (SELECT IIF((Coalesce(S.BDS_QTDE_C,0) + Coalesce(S2.BDS_QTDE_C_T,0)) < T2112.BDQTDE_V_CF,(Coalesce(S.BDS_QTDE_C,0) + Coalesce(S2.BDS_QTDE_C_T,0)),T2112.BDQTDE_V_CF) FROM TMP_VEF_EMP_TDRCST_2120_TEMP S LEFT OUTER JOIN TMP_VEF_EMP_TDRCST_2121_TEMP S2 ON (S2.BDSESSAO = T2112.BDSESSAO AND S2.BDCODEMP = T2112.BDCODEMP AND S2.BDREFERENCIA = T2112.BDREFERENCIA AND S2.BDCODPROD = T2112.BDCODPROD) WHERE S.BDSESSAO = T2112.BDSESSAO AND S.BDCODEMP = T2112.BDCODEMP AND S.BDREFERENCIA = T2112.BDREFERENCIA AND S.BDCODPROD = T2112.BDCODPROD)
  WHERE T2112.BDSESSAO = :PRSESSAO;
    
  DELETE FROM TMP_VEF_EMP_TDRCST_2112_TEMP t2112
  WHERE T2112.BDSESSAO = :PRSESSAO and Coalesce(t2112.BDQTDE_V_CF,0) = 0;


  INSERT INTO TMP_VEF_EMP_TDRCST_2110_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCOD_ITEM, BDDESCPROD,
                                            BDQTDE_T_V_CF, BDVL_T_V_CF, BDVLM_UNIT_V_CF, BDVL_T_BCST_V_CF,
                                            BDVL_DIF_MAIOR_BCST, BDVL_DIF_MENOR_BCST, BDALIQ_EF, BDQTDE_T_IND_S_OE,
                                            BDQTDE_T_IND_S_SN, BDVL_ICMS_IND_S_OE, BDVL_ICMSST_IND_S_OE,
                                            BDVL_ICMS_ST_REST, BDVL_ICMS_ST_COMPL, BDVL_T_CREDITO_MVA_SN)
  SELECT :PRSESSAO BDSESSAO, S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD,
         IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')),
             IIF(((VINC.BDCODPROD IS NULL) OR (COALESCE(VINC.BDCODPROD,'') = '')),COALESCE(PROD_UNICO.BDCODPROD,''),COALESCE(VINC.BDCODPROD,'')),
             COALESCE(VINC.BDCODSAIDA,'')) BDCOD_ITEM,
         TRIM(REPLACE(IIF(((VINC.BDDESCPROD IS NULL) OR (VINC.BDDESCPROD = '')),
                          COALESCE(PROD_UNICO.BDDESCRICAOUNICA,''),
                          COALESCE(COALESCE(PROD_REF.BDDESCPROD,VINC.BDDESCPROD),'')), '|', '')) BDDESCPROD,
         IIF((S.BDS_QTDE_C + S.BDS_QTDE_C_T) < S.BDQTDE_T_V_CF,(S.BDS_QTDE_C + S.BDS_QTDE_C_T),S.BDQTDE_T_V_CF),  /* Alt: #144919 - Alterado a regra do campo BDQTDE_T_V_CF */
         S.BDVL_T_V_CF,
         --S.BDVLM_UNIT_V_CF,
         CASE WHEN IIF((S.BDS_QTDE_C + S.BDS_QTDE_C_T) < S.BDQTDE_T_V_CF,(S.BDS_QTDE_C + S.BDS_QTDE_C_T),S.BDQTDE_T_V_CF) = 0 THEN 0 -- Alt.: #154462 #157391 - Para evitar divisao por zero...
         ELSE S.BDVL_T_V_CF / IIF((S.BDS_QTDE_C + S.BDS_QTDE_C_T) < S.BDQTDE_T_V_CF,(S.BDS_QTDE_C + S.BDS_QTDE_C_T),S.BDQTDE_T_V_CF)
         END BDVLM_UNIT_V_CF, -- Alt.: #154462 #157391 - Alterada regra do valor unitario para o campos novos..
         S.BDVL_T_BCST_V_CF,
         --S.BDVL_DIF_MAIOR_BCST,
         CASE
           WHEN S.BDS_QTDE_C = 0 THEN 0 -- Alt.: #154462 #157391 - Se nao tiver quantidade no 2120 deve zerar...
           WHEN (S.BDVL_T_BCST_V_CF - S.BDVL_T_V_CF) > 0 THEN (S.BDVL_T_BCST_V_CF - S.BDVL_T_V_CF)
         ELSE 0 END AS BDVL_DIF_MAIOR_BCST, -- Alt.: #154462 #157391 - Campo 7, deve ser a diferenca entre o 6 e o 4...
         --S.BDVL_DIF_MENOR_BCST,
         CASE
           WHEN S.BDS_QTDE_C = 0 THEN 0 -- Alt.: #154462 #157391 - Se nao tiver quantidade no 2120 deve zerar...
           WHEN (S.BDVL_T_V_CF - S.BDVL_T_BCST_V_CF) > 0 THEN (S.BDVL_T_V_CF - S.BDVL_T_BCST_V_CF)
         ELSE 0 END BDVL_DIF_MENOR_BCST,
         S.BDALIQ_EF, S.BDQTDE_T_IND_S_OE,
         S.BDQTDE_T_IND_S_SN,
         S.BDVL_ICMS_IND_S_OE,
         S.BDVL_ICMSST_IND_S_OE,
         --trunc(S.BDVL_DIF_MAIOR_BCST * (S.BDALIQ_EF/100),2) BDVL_ICMS_ST_REST,
         CASE
            WHEN S.BDS_QTDE_C = 0 THEN 0 -- Alt.: #154462 #157391 - Se nao tiver quantidade no 2120 deve zerar...
            WHEN (S.BDVL_T_BCST_V_CF - S.BDVL_T_V_CF) <= 0 THEN 0 -- Alt.: #154462 #157391 - Apenas quando tiver valor no campo "BDVL_DIF_MAIOR_BCST"
            WHEN (S.BDS_QTDE_C < (S.BDQTDE_T_V_CF + S.BDQTDE_T_IND_S_OE)) AND (S.BDS_QTDE_C > 0) THEN -- Alt.: #154462 #157391 - Quando um valor de quantidade de mercadorias do 2120(S_QTDE_C), for menor que a quantidade de mercadorias do 2110(QTDE_T_V_CF) de venda para consumidor final deve proporcionalizar...
               CAST(trunc((S.BDVL_T_BCST_V_CF - S.BDVL_T_V_CF) * (S.BDALIQ_EF/100),2) AS NUMERIC(15,4)) * CAST((S.BDS_QTDE_C / (S.BDQTDE_T_V_CF + S.BDQTDE_T_IND_S_OE)) AS NUMERIC(15,8)) -- Alt.: #154462 #157391 - Campo 7, deve ser a diferenca entre o 6 e o 4...
            ELSE trunc(IIF(S.BDVL_DIF_MAIOR_BCST > 0, S.BDVL_DIF_MAIOR_BCST, (S.BDVL_T_BCST_V_CF - S.BDVL_T_V_CF)) * (S.BDALIQ_EF/100),2) -- Alt.: #154462 #157391 - Campo 7, deve ser a diferenca entre o 6 e o 4...
         END BDVL_ICMS_ST_REST,
         --BDVL_DIF_MENOR_BCST * (S.BDALIQ_EF/100) BDVL_ICMS_ST_COMPL,
         CASE
            WHEN S.BDS_QTDE_C = 0 THEN 0 -- Alt.: #154462 #157391 - Se nao tiver quantidade no 2120 deve zerar...
            WHEN((S.BDVL_T_V_CF - S.BDVL_T_BCST_V_CF) > 0) AND ((S.BDVL_T_V_CF - S.BDVL_T_BCST_V_CF) > 0) THEN (S.BDVL_T_V_CF - S.BDVL_T_BCST_V_CF) * (S.BDALIQ_EF/100)
         ELSE 0 END BDVL_ICMS_ST_COMPL, -- Alt.: #154462 #157391 - Apenas quando tiver valor no campo "BDVL_DIF_MENOR_BCST"
         S.BDVL_T_CREDITO_MVA_SN
  FROM (
        SELECT S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD,
               S.BDQTDE_T_V_CF, S.BDVL_T_V_CF, S.BDVLM_UNIT_V_CF,
               S.BDQTDE_T_IND_S_OE, S.BDQTDE_T_IND_S_SN, S.BDVL_ICMS_IND_S_OE,
               S.BDVL_ICMSST_IND_S_OE, S.BDVL_T_CREDITO_MVA_SN,
               S.BDVL_DIF_MAIOR_BCST, S.BDVL_DIF_MENOR_BCST,
               S.BDALIQ_EF, S.BDS_QTDE_C, S.BDS_QTDE_C_T, S.BDVLM_UNIT_BCST, S.BDVLM_UNIT_BCST_G,
               CASE
                  WHEN CASE
                        WHEN S.BDS_QTDE_C = 0 THEN 0 -- Alt.: #154462 #157391 - Se nao tiver quantidade no 2120 deve zerar...
                        WHEN((S.BDVL_T_V_CF - S.BDVL_T_BCST_V_CF) > 0) AND ((S.BDVL_T_V_CF - S.BDVL_T_BCST_V_CF) > 0) THEN (S.BDVL_T_V_CF - S.BDVL_T_BCST_V_CF) * (S.BDALIQ_EF/100)
                       ELSE 0 END > 0 THEN
                         IIF(S.BDVLM_UNIT_BCST_G > 0, S.BDVLM_UNIT_BCST_G, S.BDVLM_UNIT_BCST) * S.BDQTDE_T_V_CF
                  ELSE S.BDVL_T_BCST_V_CF
               END BDVL_T_BCST_V_CF
        FROM (

              SELECT S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD,
               S.BDQTDE_T_V_CF, S.BDVL_T_V_CF, IIF(S.BDQTDE_T_V_CF > 0,S.BDVL_T_V_CF / IIF((S.BDS_QTDE_C < S.BDQTDE_T_V_CF) and (S.BDS_QTDE_C > 0),S.BDS_QTDE_C,S.BDQTDE_T_V_CF) ,0) BDVLM_UNIT_V_CF,
               S.BDQTDE_T_IND_S_OE, S.BDQTDE_T_IND_S_SN,
               (S.BDVLM_UNIT_ICMS * IIF(S.BDS_QTDE_C < S.BDQTDE_T_IND_S_OE,S.BDS_QTDE_C,S.BDQTDE_T_IND_S_OE) ) BDVL_ICMS_IND_S_OE,
                     (S.BDVLM_UNIT_ICMS_ST * IIF(S.BDS_QTDE_C < S.BDQTDE_T_IND_S_OE,S.BDS_QTDE_C,S.BDQTDE_T_IND_S_OE)) BDVL_ICMSST_IND_S_OE, S.BDVL_T_CREDITO_MVA_SN,
                     --cast(S.BDVL_T_BCST_V_CF as numeric(15,2)) BDVL_T_BCST_V_CF,
                     CASE -- Alt.: #154462 #157391 - Deve proporcionalizar pela quantidade vendida, se tiver 2121 prioriza esse registro, caso contrario, pega do 2120...
                       WHEN BDS_QTDE_C_T > 0 THEN IIF(BDS_QTDE_C_T < BDQTDE_T_V_CF, bdVL_T_BCST_V_CF, BDQTDE_T_V_CF * BDVLM_UNIT_BCST)
                       WHEN BDVLM_UNIT_BCST_G > 0 THEN BDQTDE_T_V_CF * BDVLM_UNIT_BCST_G--IIF(BDS_QTDE_C_T < BDQTDE_T_V_CF, bdVL_T_BCST_V_CF, BDQTDE_T_V_CF * BDVLM_UNIT_BCST_G)
                       ELSE IIF(BDS_QTDE_C < BDQTDE_T_V_CF, bdVL_T_BCST_V_CF, BDQTDE_T_V_CF * BDVLM_UNIT_BCST)
                     END BDVL_T_BCST_V_CF,
              (SELECT BDVALOR FROM SP_RETORNA_MAIOR_ZERO(S.BDVL_T_BCST_V_CF - S.BDVL_T_V_CF)) BDVL_DIF_MAIOR_BCST,
              (SELECT BDVALOR FROM SP_RETORNA_MAIOR_ZERO(S.BDVL_T_V_CF - S.BDVL_T_BCST_V_CF)) BDVL_DIF_MENOR_BCST,
             CASE                                         
             WHEN S.BDALIQ_ST_EF > 0 THEN S.BDALIQ_ST_EF
             ELSE Coalesce(VINC.BDALIQICMS,0)
                   END BDALIQ_EF, S.BDS_QTDE_C, S.BDS_QTDE_C_T, S.BDVLM_UNIT_BCST, S.BDVLM_UNIT_BCST_G
      FROM (SELECT S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD,
                   SUM(COALESCE(S.BDQTDE_V_CF,0)) AS BDQTDE_T_V_CF,
                         --SUM(COALESCE(S.BDVL_V_CF,0)) * CAST(TRUNC(IIF(SUM(COALESCE(S.BDS_QTDE_C,0)) < SUM(COALESCE(S.BDQTDE_V_CF,0)), SUM(COALESCE(S.BDS_QTDE_C,0)) / SUM(COALESCE(S.BDQTDE_V_CF,0)),1),5) AS NUMERIC(15,5)) BDVL_T_V_CF, Alt.: #154462 #157391 - Estava proporcionalizado os valores do 2112 pelos produtos do 2120, aparentemete isso estava errado...
                         SUM(COALESCE(S.BDVL_V_CF,0)) BDVL_T_V_CF,
                   SUM(COALESCE(S.BDVLM_UNIT_BCST,0)) BDVLM_UNIT_BCST,
                         SUM(COALESCE(S.BDVLM_UNIT_BCST_G,0)) BDVLM_UNIT_BCST_G,
                   SUM(COALESCE(S.BDQTDE_T_IND_S_OE,0)) BDQTDE_T_IND_S_OE, SUM(COALESCE(S.BDQTDE_T_IND_S_SN,0)) BDQTDE_T_IND_S_SN, SUM(COALESCE(S.BDVLM_UNIT_ICMS,0)) BDVLM_UNIT_ICMS,
                   SUM(COALESCE(S.BDVLM_UNIT_ICMS_ST,0)) BDVLM_UNIT_ICMS_ST, SUM(COALESCE(S.BDVL_CREDITO_MVA_SN,0)) BDVL_T_CREDITO_MVA_SN,
                   IIF(SUM(COALESCE(S.BDS_QTDE_C,0)) < SUM(COALESCE(S.BDQTDE_V_CF,0)),SUM(s.bdVL_T_BCST_V_CF),SUM(COALESCE(S.BDQTDE_V_CF,0)) * SUM(COALESCE(S.BDVLM_UNIT_BCST,0)))  bdVL_T_BCST_V_CF,
                   MAX(Coalesce(S.BDALIQ_ST_EF,0)) BDALIQ_ST_EF, SUM(COALESCE(S.BDS_QTDE_C,0)) BDS_QTDE_C, SUM(COALESCE(S.BDS_QTDE_C_T,0)) BDS_QTDE_C_T
          FROM (SELECT S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD,
                             S.BDQTDE_V_CF, S.BDVL_V_CF, 0 BDVLM_UNIT_BCST, 0 BDVLM_UNIT_BCST_G,
                       0 BDQTDE_T_IND_S_OE, 0 BDQTDE_T_IND_S_SN, 0 BDVLM_UNIT_ICMS, 0 BDVLM_UNIT_ICMS_ST, 0 BDVL_CREDITO_MVA_SN, 0 BDALIQ_ST_EF, 0 BDS_QTDE_C, 0 bdVL_T_BCST_V_CF, 0 BDS_QTDE_C_T
                FROM TMP_VEF_EMP_TDRCST_2112_TEMP S
                WHERE S.BDSESSAO = :PRSESSAO
                UNION ALL
                SELECT S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD,
                       IIF(S.BDIND_S = 10, IIF(S.BDIND_OPER = 0,S.BDQTDE_IND_S_C,-1 * S.BDQTDE_IND_S_C),0) BDQTDE_V_CF,
                       IIF(S.BDIND_S = 10, IIF(S.BDIND_OPER = 0,S.BDVL_V_IND_S,-1 * S.BDVL_V_IND_S),0) BDVL_V_CF,
                             0 BDVLM_UNIT_BCST, 0 BDVLM_UNIT_BCST_G,
                       --IIF(S.BDIND_S = 20,S.BDQTDE_IND_S_C,0) BDQTDE_T_IND_S_OE, IIF(S.BDIND_S = 30,S.BDQTDE_IND_S_C,0) BDQTDE_T_IND_S_SN, 0 BDVLM_UNIT_ICMS, 0 BDVLM_UNIT_ICMS_ST,
                       CASE WHEN (s.bdIND_OPER = 1) AND (S.BDIND_S = 20) THEN S.BDQTDE_IND_S_C*-1 /*#242066 - Devolucoes deve descontar*/
                            WHEN (S.BDIND_S = 20) THEN S.BDQTDE_IND_S_C
                       ELSE 0 END BDQTDE_T_IND_S_OE,
                       --IIF(S.BDIND_S = 30,S.BDQTDE_IND_S_C,0) BDQTDE_T_IND_S_SN,
                       CASE WHEN (s.bdIND_OPER = 1) AND (S.BDIND_S = 30) THEN S.BDQTDE_IND_S_C*-1 /*#242066 - Devolucoes deve descontar*/
                            WHEN (S.BDIND_S = 30) THEN S.BDQTDE_IND_S_C
                       ELSE 0 END BDQTDE_T_IND_S_SN,
                       0 BDVLM_UNIT_ICMS, 0 BDVLM_UNIT_ICMS_ST,
                       IIF(S.BDIND_OPER = 0, S.BDVL_CREDITO_MVA_SN, -1 * S.BDVL_CREDITO_MVA_SN) BDVL_CREDITO_MVA_SN, 0 BDALIQ_ST_EF, 0 BDS_QTDE_C, 0 bdVL_T_BCST_V_CF, 0 BDS_QTDE_C_T
                FROM TMP_VEF_EMP_TDRCST_2113_TEMP S 
                WHERE S.BDSESSAO = :PRSESSAO
                UNION ALL
                SELECT S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD,
                             0 BDQTDE_V_CF, 0 AS BDVL_V_CF, S.BDVLM_UNIT_BCST, 0 BDVLM_UNIT_BCST_G,
                       0 BDQTDE_T_IND_S_OE, 0 BDQTDE_T_IND_S_SN, S.BDVLM_UNIT_ICMS, S.BDVLM_UNIT_ICMS_ST, 0 BDVL_CREDITO_MVA_SN, 0 BDALIQ_ST_EF, S.BDS_QTDE_C, S.bdS_VL_BCST_INT bdVL_T_BCST_V_CF, 0 BDS_QTDE_C_T
                FROM TMP_VEF_EMP_TDRCST_2120_TEMP S
                WHERE S.BDSESSAO = :PRSESSAO
                UNION ALL
                SELECT S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD,
                             0 BDQTDE_V_CF, 0 AS BDVL_V_CF, 0 BDVLM_UNIT_BCST, 0 BDVLM_UNIT_BCST_G,
                       0 BDQTDE_T_IND_S_OE, 0 BDQTDE_T_IND_S_SN, 0 BDVLM_UNIT_ICMS, 0 BDVLM_UNIT_ICMS_ST, 0 BDVL_CREDITO_MVA_SN, S.BDALIQ_ST_EF, 0 BDS_QTDE_C, 0 bdVL_T_BCST_V_CF, 0 BDS_QTDE_C_T
                FROM TMP_VEF_EMP_TDRCST_2130_TEMP S
                WHERE S.BDSESSAO = :PRSESSAO
                UNION ALL
                SELECT S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD,
                             0 BDQTDE_V_CF, 0 AS BDVL_V_CF, 0 BDVLM_UNIT_BCST, S.BDVLM_UNIT_BCST_G,
                       0 BDQTDE_T_IND_S_OE, 0 BDQTDE_T_IND_S_SN, 0 BDVLM_UNIT_ICMS, 0 BDVLM_UNIT_ICMS_ST, 0 BDVL_CREDITO_MVA_SN, 0 BDALIQ_ST_EF, 0 BDS_QTDE_C, 0 bdVL_T_BCST_V_CF, S.BDS_QTDE_C_T
                FROM TMP_VEF_EMP_TDRCST_2121_TEMP S
                WHERE S.BDSESSAO = :PRSESSAO
          )S
          GROUP BY S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD
      )S
      LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = S.BDCODEMP AND VINC.BDCODPROD = S.BDCODPROD)
  ) S
  ) S
  LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = S.BDCODEMP AND VINC.BDCODPROD = S.BDCODPROD)
  LEFT OUTER JOIN TCADPRO PROD_UNICO ON(PROD_UNICO.BDCODPROD = S.BDCODPROD)
  LEFT OUTER JOIN TCADPRO_REF PROD_REF ON (PROD_REF.BDCODPROD = S.BDCODPROD AND PROD_REF.BDCODEMP = S.BDCODEMP
                                           AND PROD_REF.BDREFPROD = (SELECT MAX(R.BDREFPROD)
                                                                     FROM TCADPRO_REF R
                                                                     WHERE R.BDCODPROD = PROD_REF.BDCODPROD AND R.BDCODEMP = PROD_REF.BDCODEMP AND R.BDREFPROD <= S.BDREFERENCIA))
                                                                     
  WHERE (:wIGNORARCOMP <> 'TRUE') 
     OR (EXISTS(SELECT * -- Alt.: #132676 - Caso a opção esteja marcada, apenas leva para o 2110, caso tenha o produto no 2130...
                FROM TMP_VEF_EMP_TDRCST_2130_TEMP t2130
                WHERE t2130.bdSESSAO     = :prSESSAO
                  AND t2130.BDCODEMP     = s.bdCODEMP
                  AND t2130.bdREFERENCIA = s.bdREFERENCIA
                  AND t2130.bdCODPROD    = s.bdCODPROD))
  ;
END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_DRCST_RESUMO (
    PRSESSAO INTEGER,
    PRDATAINICIO DATE,
    PRDATAFIM DATE)
AS
BEGIN
  INSERT INTO TMP_VEF_EMP_TDRCST_RESUMO_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDS_VL_ICMS_ST_REST,
                                              BDS_VL_ICMS_ST_COMPL, BDSD_ICMS_ST_REST, BDSD_ICMS_ST_RESS,
                                             BDSD_ICMS_ST_COMPL, BDSD_ICMS_OP, BDV_APUR_CRED_ICMS, BDV_APUR_ICMS_COMP)
  SELECT :PRSESSAO BDSESSAO, M.BDCODEMP, M.BDREFERENCIA, M.BDS_VL_ICMS_ST_REST, M.BDS_VL_ICMS_ST_COMPL,
         M.BDSD_ICMS_ST_REST, M.BDSD_ICMS_ST_RESS,
         --M.BDSD_ICMS_ST_COMPL,
         IIF((BDS_VL_ICMS_ST_COMPL - BDS_VL_ICMS_ST_REST) < 0, 0, (BDS_VL_ICMS_ST_COMPL - BDS_VL_ICMS_ST_REST)) BDSD_ICMS_ST_COMPL, -- Alt.: #154462 #157391 - Campo 6, Ajustado para faz a regra do site...
         M.BDSD_ICMS_OP,
        --(SELECT BDVALOR FROM SP_RETORNA_MAIOR_ZERO((M.BDSD_ICMS_ST_REST + M.BDSD_ICMS_ST_RESS) - M.BDSD_ICMS_ST_COMPL)) BDV_APUR_CRED_ICMS,
        (SELECT BDVALOR FROM SP_RETORNA_MAIOR_ZERO((M.BDSD_ICMS_ST_REST + M.BDSD_ICMS_ST_RESS) - IIF((BDS_VL_ICMS_ST_COMPL - BDS_VL_ICMS_ST_REST) < 0, 0, (BDS_VL_ICMS_ST_COMPL - BDS_VL_ICMS_ST_REST)))) BDV_APUR_CRED_ICMS, -- Alt.: #154462 #157391 - Campo 6, Ajustado para faz a regra do site...
        IIF(IIF((BDS_VL_ICMS_ST_COMPL - BDS_VL_ICMS_ST_REST) < 0, 0, (BDS_VL_ICMS_ST_COMPL - BDS_VL_ICMS_ST_REST))-(M.BDSD_ICMS_ST_REST + M.BDSD_ICMS_ST_RESS) < 0, 0,
            IIF((BDS_VL_ICMS_ST_COMPL - BDS_VL_ICMS_ST_REST) < 0, 0, (BDS_VL_ICMS_ST_COMPL - BDS_VL_ICMS_ST_REST))-(M.BDSD_ICMS_ST_REST + M.BDSD_ICMS_ST_RESS)) BDV_APUR_ICMS_COMP
  FROM(
      SELECT M.BDCODEMP, M.BDREFERENCIA, M.BDS_VL_ICMS_ST_REST, iif(M.BDREFERENCIA <= 201812, 0 ,M.BDS_VL_ICMS_ST_COMPL) BDS_VL_ICMS_ST_COMPL,
             (SELECT BDVALOR FROM SP_RETORNA_MAIOR_ZERO(iif(M.BDREFERENCIA <= 201812, M.BDS_VL_ICMS_ST_REST,M.BDS_VL_ICMS_ST_REST - M.BDS_VL_ICMS_ST_COMPL))) BDSD_ICMS_ST_REST,
             M.BDSD_ICMS_ST_RESS,
             (SELECT BDVALOR FROM SP_RETORNA_MAIOR_ZERO(M.BDS_VL_ICMS_ST_COMPL - M.BDS_VL_ICMS_ST_REST)) BDSD_ICMS_ST_COMPL,
             M.BDSD_ICMS_OP
     FROM ( SELECT M.BDCODEMP, M.BDREFERENCIA,
             SUM(M.BDVL_ICMS_ST_REST) BDS_VL_ICMS_ST_REST,
             SUM(M.BDVL_ICMS_ST_COMPL) BDS_VL_ICMS_ST_COMPL, -- O transporte da soma dos campos VL_ICMS_ST_COMPL do Registro 2110, quando informado, torna-se obrigatório a partir do período de referência março de 2018. Antes disso esse campo pode ser preenchido com a informação do registro VL_ICMS_ST_COMPL e outras
             SUM(M.BDVL_ICMSST_IND_S_OE + M.BDVL_T_CREDITO_MVA_SN) BDSD_ICMS_ST_RESS, SUM(M.BDVL_ICMS_IND_S_OE) BDSD_ICMS_OP
           FROM TMP_VEF_EMP_TDRCST_2110_TEMP M
            WHERE M.BDSESSAO = :PRSESSAO
            GROUP BY BDSESSAO, BDCODEMP, BDREFERENCIA
      ) M
  ) M;
END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_DRCST_INCONS (
    PRSESSAO INTEGER,
    PRDATAINICIO DATE,
    PRDATAFIM DATE,
    PRCODPLACONFDRCST integer)
AS
declare variable WIGNORARCOMP DM_BOOLEAN;
BEGIN
  -- 1 - Venda para Simples Nacional, porém não há plano para cálculo, padrão ou vinculado na empresa, para ajustar os créditos conforme redução. VL_CREDITO_MVA_SN
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDIND_OPER, BDCHAVE)
  SELECT 1 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2113' BDREG,
         D.BDIND_OPER, D.BDCHAVE
  FROM TMP_VEF_EMP_TDRCST_2113_TEMP D
  LEFT OUTER JOIN TMP_VEF_EMP_TDRCSTGER_TEMP G ON (G.BDSESSAO = D.BDSESSAO AND G.BDCODEMP = D.BDCODEMP AND G.BDREFERENCIA = D.BDREFERENCIA)
  WHERE D.BDSESSAO = :PRSESSAO AND
        G.BDCODPLACONFDRCST IS NULL AND
        (D.BDIND_S = 30) -- 30 - Venda para SN
  GROUP BY D.BDCODEMP, D.BDREFERENCIA, D.BDCHAVE, D.BDIND_OPER;

  -- 2 - Venda para Simples Nacional, porém o plano #PLANO# não possui chaves que aplicam neste lançamento, para ajustar os créditos conforme redução. VL_CREDITO_MVA_SN
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD,
                                BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODPLACONFDRCST)
  SELECT 2 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2113' BDREG,
         NULL BDCODPROD, D.BDIND_OPER, D.BDCHAVE, D.BDORDEM, D.BDORDEMPRO, G.BDCODPLACONFDRCST
  FROM TMP_VEF_EMP_TDRCST_2113_TEMP D
  LEFT OUTER JOIN TMP_VEF_EMP_TDRCSTGER_TEMP G ON (G.BDSESSAO = D.BDSESSAO AND G.BDCODEMP = D.BDCODEMP AND G.BDREFERENCIA = D.BDREFERENCIA)
  WHERE D.BDSESSAO = :PRSESSAO AND
        G.BDCODPLACONFDRCST > 0 AND
        D.BDCHAVETROCA IS NULL AND
        (D.BDIND_S = 30); -- 30 - Venda para SN
        
  -- 3 -  O valor de crédito para Simples Nacional calculado pelo plano #PLANO# ação #CHAVE_TROCA# é 0. VL_CREDITO_MVA_SN
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD,
                                BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODPLACONFDRCST, BDCHAVETROCA)
  SELECT 3 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2113' BDREG,
         NULL BDCODPROD, D.BDIND_OPER, D.BDCHAVE, D.BDORDEM, D.BDORDEMPRO, D.BDCODPLACONFDRCST, D.BDCHAVETROCA
  FROM TMP_VEF_EMP_TDRCST_2113_TEMP D
  LEFT OUTER JOIN TMP_VEF_EMP_TDRCSTGER_TEMP G ON (G.BDSESSAO = D.BDSESSAO AND G.BDCODEMP = D.BDCODEMP AND G.BDREFERENCIA = D.BDREFERENCIA)
  WHERE D.BDSESSAO = :PRSESSAO AND
        D.BDCODPLACONFDRCST > 0 AND
        D.BDCHAVETROCA > 0 AND
        (COALESCE(D.BDVL_CREDITO_MVA_SN,0) = 0) AND
        (D.BDIND_S = 30); -- 30 - Venda para SN

  -- 4 - O lançamento deve possuir valor de ICMS normal destacado. VL_ICMS
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD,
                                BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT 4 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2130' BDREG,
         NULL BDCODPROD, D.BDIND_OPER, D.BDCHAVE, D.BDORDEM, D.BDORDEMPRO
  FROM TMP_VEF_EMP_TDRCST_2130_TEMP D 
  LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = D.BDCODTER)
  WHERE D.BDSESSAO = :PRSESSAO AND
        (D.BDIND_OPER = 0) AND
        (D.BDC176 = 'FALSE') AND
        (COALESCE(D.BDVL_ICMS,0) = 0) AND
        (D.BDCOD_RESP_RET IN (1,3)) AND
        (NOT TER.BDENQSIMPLESFEDTER IN (0,1));

  -- 5 - O lançamento deve possuir valor de ICMS ST destacado. VL_ICMS
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD,
                                BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT 5 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2130' BDREG,
         NULL BDCODPROD, D.BDIND_OPER, D.BDCHAVE, D.BDORDEM, D.BDORDEMPRO
  FROM TMP_VEF_EMP_TDRCST_2130_TEMP D 
  LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = D.BDCODTER)
  --LEFT OUTER JOIN TMP_VEF_EMP_TDRCST_2134_TEMP D2134 ON (D.BDSESSAO = D2134.BDSESSAO AND D.BDCODEMP = D2134.BDCODEMP AND D.BDREFERENCIA = D2134.BDREFERENCIA AND D.BDCODPROD = D2134.BDCODPROD AND
  --                                                        D.BDIND_OPER = D2134.BDIND_OPER AND D.BDCHAVE = D2134.BDCHAVE AND D.BDORDEM = D2134.BDORDEM)
  WHERE D.BDSESSAO = :PRSESSAO AND         
        (D.BDIND_OPER = 0) AND  
        (D.BDC176 = 'FALSE') AND
        (COALESCE(D.BDVL_ICMS,0) = 0) AND
        (D.BDCOD_RESP_RET IN (1,3)) AND
        (TER.BDENQSIMPLESFEDTER IN (0,1));

  -- 6 - O lançamento deve possuir base de cálculo de ICMS ST destacado. VL_BCST
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD,
                                BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT 6 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2130' BDREG,
         NULL BDCODPROD, D.BDIND_OPER, D.BDCHAVE, D.BDORDEM, D.BDORDEMPRO
  FROM TMP_VEF_EMP_TDRCST_2130_TEMP D
  WHERE D.BDSESSAO = :PRSESSAO AND     
        (D.BDIND_OPER = 0) AND  
        (D.BDC176 = 'FALSE') AND
        (COALESCE(D.BDVL_BCST,0) = 0) AND
        (D.BDCOD_RESP_RET in (1,3));

  -- 7 - O lançamento deve possuir base de cálculo de ICMS ST retido destacado. VL_BCST
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD,
                                BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT 7 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2130' BDREG,
         NULL BDCODPROD, D.BDIND_OPER, D.BDCHAVE, D.BDORDEM, D.BDORDEMPRO
  FROM TMP_VEF_EMP_TDRCST_2130_TEMP D
  LEFT OUTER JOIN TMP_VEF_EMP_TDRCST_2134_TEMP aux ON (aux.BDSESSAO = d.BDSESSAO and aux.BDCODEMP = d.BDCODEMP and aux.BDREFERENCIA = d.BDREFERENCIA and aux.BDCODPROD = d.BDCODPROD and aux.BDIND_OPER = d.BDIND_OPER and aux.BDCHAVE = d.BDCHAVE and aux.BDORDEM = d.BDORDEM and aux.BDORDEMPRO = d.BDORDEMPRO)
  WHERE D.BDSESSAO = :PRSESSAO AND  
        (D.BDIND_OPER = 0) AND  
        (D.BDC176 = 'FALSE') AND
        (COALESCE(D.BDVL_BCST,0) = 0) AND
        (D.BDCOD_RESP_RET = 2) AND
        (aux.BDCHAVE IS NULL);

  -- 8 - O lançamento deve possuir base de cálculo de ICMS ST destacado. VL_BCST_INT
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD,
                                BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT 8 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2130' BDREG,
         NULL BDCODPROD, D.BDIND_OPER, D.BDCHAVE, D.BDORDEM, D.BDORDEMPRO
  FROM TMP_VEF_EMP_TDRCST_2130_TEMP D
  WHERE D.BDSESSAO = :PRSESSAO AND   
        (D.BDIND_OPER = 0) AND  
        (D.BDC176 = 'FALSE') AND
        (COALESCE(D.BDVL_BCST_INT,0) = 0) AND
        (D.BDCOD_RESP_RET = 1);

  -- 9 - O lançamento deve possuir alíquota de ICMS ST. ALIQ_ST_E
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD,
                                BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT 9 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2130' BDREG,
         NULL BDCODPROD, D.BDIND_OPER, D.BDCHAVE, D.BDORDEM, D.BDORDEMPRO
  FROM TMP_VEF_EMP_TDRCST_2130_TEMP D
  WHERE D.BDSESSAO = :PRSESSAO AND   
        (D.BDIND_OPER = 0) AND  
        (D.BDC176 = 'FALSE') AND
        (COALESCE(D.BDALIQ_ST_E,0) = 0) AND
        (D.BDCOD_RESP_RET IN (1));

  -- 10 - O produto deve possuir alíquota de ICMS. ALIQ_ST_E
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD,
                                BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT 10 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2130' BDREG,
         D.BDCODPROD, D.BDIND_OPER, NULL BDCHAVE, NULL BDORDEM, NULL BDORDEMPRO
  FROM TMP_VEF_EMP_TDRCST_2130_TEMP D
  LEFT OUTER JOIN TMP_VEF_EMP_TDRCST_2134_TEMP aux ON (aux.BDSESSAO = d.BDSESSAO and aux.BDCODEMP = d.BDCODEMP and aux.BDREFERENCIA = d.BDREFERENCIA and aux.BDCODPROD = d.BDCODPROD and aux.BDIND_OPER = d.BDIND_OPER and aux.BDCHAVE = d.BDCHAVE and aux.BDORDEM = d.BDORDEM and aux.BDORDEMPRO = d.BDORDEMPRO)
  WHERE D.BDSESSAO = :PRSESSAO AND   
        (D.BDIND_OPER = 0) AND   
        (D.BDC176 = 'FALSE') AND
        (COALESCE(D.BDALIQ_ST_E,0) = 0) AND
        (D.BDCOD_RESP_RET = 2) AND
        (aux.BDCODEMP IS NULL);

  -- 11 - O produto deve possuir alíquota de ICMS efetivo. ALIQ_ST_E
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD,
                                BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT 11 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2130' BDREG,
         D.BDCODPROD, D.BDIND_OPER, NULL BDCHAVE, NULL BDORDEM, NULL BDORDEMPRO
  FROM TMP_VEF_EMP_TDRCST_2130_TEMP D
  WHERE D.BDSESSAO = :PRSESSAO AND  
        (D.BDIND_OPER = 0) AND  
        (D.BDC176 = 'FALSE') AND
        (COALESCE(D.BDALIQ_ST_E,0) = 0) AND
        (D.BDCOD_RESP_RET = 3);

  -- 12 - O produto deve possuir alíquota de ICMS. ALIQ_ST_EF
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD,
                                BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT 12 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2130' BDREG,
         D.BDCODPROD, D.BDIND_OPER, NULL BDCHAVE, NULL BDORDEM, NULL BDORDEMPRO
  FROM TMP_VEF_EMP_TDRCST_2130_TEMP D
  WHERE D.BDSESSAO = :PRSESSAO AND  
        (D.BDIND_OPER = 0) AND  
        (D.BDC176 = 'FALSE') AND
        (COALESCE(D.BDALIQ_ST_EF,0) = 0);

  -- 13 - O lançamento deve possuir valor de ICMS ST destacado. VL_ICMS_ST
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD,
                                BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT 13 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2130' BDREG,
         NULL BDCODPROD, D.BDIND_OPER, D.BDCHAVE, D.BDORDEM, D.BDORDEMPRO
  FROM TMP_VEF_EMP_TDRCST_2130_TEMP D
  WHERE D.BDSESSAO = :PRSESSAO AND  
        (D.BDIND_OPER = 0) AND 
        (D.BDC176 = 'FALSE') AND
        (COALESCE(D.BDVL_ICMS_ST,0) = 0) AND
        (D.BDCOD_RESP_RET IN (1));

  -- 14 - O lançamento deve possuir valor de ICMS ST retido destacado. VL_ICMS_ST
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD,
                                BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT 14 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2130' BDREG,
         NULL BDCODPROD, D.BDIND_OPER, D.BDCHAVE, D.BDORDEM, D.BDORDEMPRO
  FROM TMP_VEF_EMP_TDRCST_2130_TEMP D
  LEFT OUTER JOIN TMP_VEF_EMP_TDRCST_2134_TEMP aux ON (aux.BDSESSAO = d.BDSESSAO and aux.BDCODEMP = d.BDCODEMP and aux.BDREFERENCIA = d.BDREFERENCIA and aux.BDCODPROD = d.BDCODPROD and aux.BDIND_OPER = d.BDIND_OPER and aux.BDCHAVE = d.BDCHAVE and aux.BDORDEM = d.BDORDEM and aux.BDORDEMPRO = d.BDORDEMPRO)
  WHERE D.BDSESSAO = :PRSESSAO AND 
        (D.BDIND_OPER = 0) AND 
        (D.BDC176 = 'FALSE') AND
        (COALESCE(D.BDVL_ICMS_ST,0) = 0) AND
        (D.BDCOD_RESP_RET IN (2)) AND
        (aux.BDCHAVE IS NULL);

  -- 15 - O lançamento deve possuir número da DARE. NUM_DARE
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD,
                                BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT 15 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2130' BDREG,
         NULL BDCODPROD, D.BDIND_OPER, D.BDCHAVE, D.BDORDEM, D.BDORDEMPRO
  FROM TMP_VEF_EMP_TDRCST_2130_TEMP D
  WHERE D.BDSESSAO = :PRSESSAO AND     
        D.BDIND_OPER = 0 AND
        D.BDCOD_RESP_RET = 3 AND
        Coalesce(D.BDNUM_DARE,'') = '' AND
        ((D.BDC176 = 'TRUE' AND D.BDCOD_DA = 0) OR
          EXISTS(SELECT FIRST 1 M.BDCODEMP
                 FROM VEF_EMP_TMOVMVASC M
                 WHERE M.BDCODEMP = D.BDCODEMP AND
                       M.BDCHAVE = D.BDCHAVE AND
                       M.BDORDEM = D.BDORDEM AND
                       M.BDCODPROD = D.BDCODPROD AND
                       M.BDARRECADACAO = 0));

  -- 16 - O lançamento deve possuir um C197 lançado. COD_AJ
  -- Para indicador do tipo de operação “3 - Próprio declarante” e contribuintes com obrigação de EFD ICMS/IPI.
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD,
                                BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT 16 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2130' BDREG,
         NULL BDCODPROD, IIF(D.BDC176 = 'TRUE', 1, D.BDIND_OPER) BDIND_OPER, D.BDCHAVE, D.BDORDEM, D.BDORDEMPRO
  FROM TMP_VEF_EMP_TDRCST_2130_TEMP D
  WHERE D.BDSESSAO = :PRSESSAO AND           
        D.BDIND_OPER = 0 AND
        (COALESCE(D.BDCOD_AJ,'') = '') AND
        (D.BDCOD_RESP_RET = 3);
        
  -- Alt.: #132676 - Obtem a configuração de "Ignorar lançamentos sem compra com destaque de ICMS ST e ICMS ST Retido" do plano DRCST.
  SELECT COALESCE(UPPER(bdIGNORARCOMP),'FALSE')
  FROM VEF_BASE_TPLACONFDRCST
  WHERE bdCODPLACONFDRCST = :prCODPLACONFDRCST
  INTO :wIGNORARCOMP;

  IF (:wIGNORARCOMP <> 'TRUE') THEN -- Alt.: #132676 - Apenas quando o parâmetro estiver desmarcado.
    BEGIN
  -- 17 - Quantidade de saída do produto não foi encontrado nas entradas nos últimos 12 meses
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD,
                                BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT 17 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2130' BDREG,
         D.BDCODPROD, 0, NULL BDCHAVE, NULL BDORDEM, NULL BDORDEMPRO
  FROM ( SELECT D.BDCODEMP, D.BDREFERENCIA, D.BDCODPROD, D.BDQTDE_V_CF AS BDQTD
         FROM TMP_VEF_EMP_TDRCST_2112_TEMP D
         WHERE D.BDSESSAO = :PRSESSAO
         UNION ALL
         SELECT D.BDCODEMP, D.BDREFERENCIA, D.BDCODPROD, D.BDQTDE_IND_S_C AS BDQTD
         FROM TMP_VEF_EMP_TDRCST_2113_TEMP D
         WHERE D.BDSESSAO = :PRSESSAO) D
  LEFT OUTER JOIN ( SELECT E.BDCODEMP, E.BDREFERENCIA, E.BDCODPROD, SUM(E.BDQTDE) BDQTD
                    FROM TMP_VEF_EMP_TDRCST_2130_TEMP E
                    WHERE E.BDSESSAO = :PRSESSAO
                    GROUP BY E.BDCODEMP, E.BDREFERENCIA, E.BDCODPROD) E on (E.BDCODEMP = D.BDCODEMP AND E.BDREFERENCIA = D.BDREFERENCIA AND E.BDCODPROD = D.BDCODPROD)
  WHERE Coalesce(E.BDQTD,0) < D.BDQTD;    
    END

  -- 18 - Valor do ICMS ST Calculado deve ser maior que zero. CAL_ICMS_ST
  INSERT INTO VEF_INCON_TDRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD,
                                BDIND_OPER, BDCHAVE, BDORDEM, BDORDEMPRO, BDORDEMREG, BDCHV_NFE)
  SELECT 18 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '2130' BDREG,
         D.BDCODPROD, D.BDIND_OPER, NULL BDCHAVE, NULL BDORDEM, NULL BDORDEMPRO, D.BDNUM_ITEM, D.BDCHV_NFE
  FROM TMP_VEF_EMP_TDRCST_2130_TEMP D
  LEFT OUTER JOIN TMP_VEF_EMP_TDRCST_2134_TEMP aux ON (aux.BDSESSAO = d.BDSESSAO and aux.BDCODEMP = d.BDCODEMP and aux.BDREFERENCIA = d.BDREFERENCIA and aux.BDCODPROD = d.BDCODPROD and aux.BDIND_OPER = d.BDIND_OPER and aux.BDCHAVE = d.BDCHAVE and aux.BDORDEM = d.BDORDEM and aux.BDORDEMPRO = d.BDORDEMPRO)
  WHERE D.BDSESSAO = :PRSESSAO AND 
        (D.BDC176 = 'FALSE') AND
        (Coalesce(D.BDCAL_ICMS_ST,0) = 0) AND
        (aux.BDCHAVE IS NULL);
END
^

CREATE OR ALTER procedure SP_APURACAO_DRCST_GRAVAR (
    PRSESSAO integer)
as
BEGIN                  
    INSERT INTO VEF_EMP_TDRCST_RESUMO(BDCODEMP, BDREFERENCIA, BDS_VL_ICMS_ST_REST, BDS_VL_ICMS_ST_COMPL, BDSD_ICMS_ST_REST,
                                      BDSD_ICMS_ST_RESS, BDSD_ICMS_ST_COMPL, BDSD_ICMS_OP, BDV_APUR_CRED_ICMS, BDV_APUR_ICMS_COMP)
    SELECT T.BDCODEMP, T.BDREFERENCIA, T.BDS_VL_ICMS_ST_REST, T.BDS_VL_ICMS_ST_COMPL, T.BDSD_ICMS_ST_REST,
           T.BDSD_ICMS_ST_RESS, T.BDSD_ICMS_ST_COMPL, T.BDSD_ICMS_OP, T.BDV_APUR_CRED_ICMS, T.BDV_APUR_ICMS_COMP
    FROM TMP_VEF_EMP_TDRCST_RESUMO_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO;
    
    INSERT INTO VEF_EMP_TDRCST_2110(BDCODEMP, BDREFERENCIA, BDCODPROD, BDCOD_ITEM, BDDESCPROD, BDQTDE_T_V_CF,
                                    BDVL_T_V_CF, BDVLM_UNIT_V_CF, BDVL_T_BCST_V_CF, BDVL_DIF_MAIOR_BCST, BDVL_DIF_MENOR_BCST,
                                    BDALIQ_EF, BDQTDE_T_IND_S_OE, BDQTDE_T_IND_S_SN, BDVL_ICMS_IND_S_OE, BDVL_ICMSST_IND_S_OE,
                                    BDVL_ICMS_ST_REST, BDVL_ICMS_ST_COMPL, BDVL_T_CREDITO_MVA_SN)
    SELECT T.BDCODEMP, T.BDREFERENCIA, T.BDCODPROD, T.BDCOD_ITEM, T.BDDESCPROD, T.BDQTDE_T_V_CF,
           T.BDVL_T_V_CF, T.BDVLM_UNIT_V_CF, T.BDVL_T_BCST_V_CF, T.BDVL_DIF_MAIOR_BCST, T.BDVL_DIF_MENOR_BCST,
           T.BDALIQ_EF, T.BDQTDE_T_IND_S_OE, T.BDQTDE_T_IND_S_SN, T.BDVL_ICMS_IND_S_OE, T.BDVL_ICMSST_IND_S_OE,
           T.BDVL_ICMS_ST_REST, T.BDVL_ICMS_ST_COMPL, T.BDVL_T_CREDITO_MVA_SN
    FROM TMP_VEF_EMP_TDRCST_2110_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO;
    
    INSERT INTO VEF_EMP_TDRCST_2120(BDCODEMP, BDREFERENCIA, BDCODPROD, BDS_QTDE_C, BDS_VL_BCST_INT,
                                    BDVLM_UNIT_BCST, BDS_VL_ICMS, BDVLM_UNIT_ICMS, BDS_VL_ICMS_ST, BDVLM_UNIT_ICMS_ST)
    SELECT T.BDCODEMP, T.BDREFERENCIA, T.BDCODPROD, T.BDS_QTDE_C, T.BDS_VL_BCST_INT,
           T.BDVLM_UNIT_BCST, T.BDS_VL_ICMS, T.BDVLM_UNIT_ICMS, T.BDS_VL_ICMS_ST, T.BDVLM_UNIT_ICMS_ST
    FROM TMP_VEF_EMP_TDRCST_2120_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO;
    
    INSERT INTO VEF_EMP_TDRCST_2121(BDCODEMP, BDREFERENCIA, BDCODPROD, BDS_QTDE_C_T, BDS_QTDE_C_VLM, BDS_VL_BCST_INT_VLM, BDVLM_UNIT_BCST_G)
    SELECT T.BDCODEMP, T.BDREFERENCIA, T.BDCODPROD, T.BDS_QTDE_C_T, T.BDS_QTDE_C_VLM,
           T.BDS_VL_BCST_INT_VLM, T.BDVLM_UNIT_BCST_G
    FROM TMP_VEF_EMP_TDRCST_2121_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO;
    
    INSERT INTO VEF_EMP_TDRCST_2112(BDCODEMP, BDREFERENCIA, BDCODPROD, BDCODUNIMED, BDQTDE_V_CF,
                                    BDUNID, BDVL_V_CF, BDALIQ_EF)
    SELECT T.BDCODEMP, T.BDREFERENCIA, T.BDCODPROD, T.BDCODUNIMED, T.BDQTDE_V_CF,
           T.BDUNID, T.BDVL_V_CF, T.BDALIQ_EF
    FROM TMP_VEF_EMP_TDRCST_2112_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO;
    
    INSERT INTO VEF_EMP_TDRCST_2113(BDCODEMP, BDREFERENCIA, BDCODPROD, BDIND_OPER, BDCHAVE,
                                    BDORDEM, BDORDEMPRO, BDCODUNIMED, BDCODFATCON, BDCODNAT,
                                    BDIND_S, BDCHV_NFE, BDDT_NFE, BDDT_E, BDCODTER,
                                    BDNOMTER, BDCNPJ, BDCPF, BDNUM_ITEM, BDQTDE_IND_S,
                                    BDUNID, BDFAT_CONV, BDQTDE_IND_S_C, BDVL_V_IND_S,  BDCFOP,
                                    BDVL_CREDITO_MVA_SN, BDALIQ_EF)
    SELECT T.BDCODEMP, T.BDREFERENCIA, T.BDCODPROD, T.BDIND_OPER, T.BDCHAVE,
           T.BDORDEM, T.BDORDEMPRO, T.BDCODUNIMED, T.BDCODFATCON, T.BDCODNAT,
           T.BDIND_S, T.BDCHV_NFE, T.BDDT_NFE, T.BDDT_E, T.BDCODTER,
           T.BDNOMTER, T.BDCNPJ, T.BDCPF, T.BDNUM_ITEM, T.BDQTDE_IND_S,
           T.BDUNID, T.BDFAT_CONV, T.BDQTDE_IND_S_C, T.BDVL_V_IND_S,  T.BDCFOP,
           T.BDVL_CREDITO_MVA_SN, T.BDALIQ_EF
    FROM TMP_VEF_EMP_TDRCST_2113_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO;
    
    INSERT INTO VEF_EMP_TDRCST_2114(BDCODEMP, BDREFERENCIA, BDCODPROD, BDIND_OPER, BDCHAVE,
                                    BDORDEM, BDORDEMPRO, BDORDEMIC, BDORDEMDOCFREF, BDCODTER, BDCNPJ, BDCPF,
                                    BDCHV_NFE_REF, BDECF_CX_REF, BDNUM_DOC_REF, BDDT_DOC_REF)
    SELECT  T.BDCODEMP, T.BDREFERENCIA, T.BDCODPROD, T.BDIND_OPER, T.BDCHAVE,
            T.BDORDEM, T.BDORDEMPRO, T.BDORDEMIC, T.BDORDEMDOCFREF, T.BDCODTER, T.BDCNPJ, T.BDCPF,
            T.BDCHV_NFE_REF, T.BDECF_CX_REF, T.BDNUM_DOC_REF, T.BDDT_DOC_REF
    FROM TMP_VEF_EMP_TDRCST_2114_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO;
    
    INSERT INTO VEF_EMP_TDRCST_2115 (bdCODEMP, bdREFERENCIA, bdCODPROD, bdIND_OPER, bdCHAVE, bdORDEM, bdORDEMPRO,
                                     bdORDEM2115, bdCHV_NFE_COMP, bdNUM_ITEM_NFE_COMP, bdCHAVE_COMP, bdORDEM_COMP, bdORDEMPRO_COMP, bdQTDITEM, bdVLRITEM)
    SELECT t.bdCODEMP, t.bdREFERENCIA, t.bdCODPROD, t.bdIND_OPER, t.bdCHAVE, t.bdORDEM, t.bdORDEMPRO,
           t.bdORDEM2115, t.bdCHV_NFE_COMP, t.bdNUM_ITEM_NFE_COMP, t.bdCHAVE_COMP, t.bdORDEM_COMP, t.bdORDEMPRO_COMP, t.bdQTDITEM, t.bdVLRITEM
    FROM TMP_VEF_EMP_TDRCST_2115_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO;
    
    INSERT INTO VEF_EMP_TDRCST_2130(BDCODEMP, BDREFERENCIA, BDCODPROD, BDIND_OPER, BDCHAVE,
                                    BDORDEM, BDORDEMPRO, BDCODUNIMED, BDCODFATCON, BDCODNAT,
                                    BDCHV_NFE, BDDT_E, BDDT_NFE, BDCODTER, BDNOMTER,
                                    BDCNPJ, BDNUM_ITEM, BDCOD_RESP_RET, BDQTDE, BDUNID,
                                    BDFAT_CONV, BDQTDE_C, BDVL_E, BDCFOP, BDVL_BC_ICMS,
                                    BDALIQ_ICMS, BDVL_ICMS, BDVL_BCST, BDVL_BCST_INT,
                                    BDALIQ_ST_E, BDALIQ_ST_EF, BDCAL_ICMS_ST, BDVL_ICMS_ST,
                                    BDCOD_DA, BDNUM_DARE, BDCOD_AJ, BDALIQ_EF, BDC176)
    SELECT T.BDCODEMP, T.BDREFERENCIA, T.BDCODPROD, T.BDIND_OPER, T.BDCHAVE,
           T.BDORDEM, T.BDORDEMPRO, T.BDCODUNIMED, T.BDCODFATCON, T.BDCODNAT,
           T.BDCHV_NFE, T.BDDT_E, T.BDDT_NFE, T.BDCODTER, T.BDNOMTER,
           T.BDCNPJ, T.BDNUM_ITEM, T.BDCOD_RESP_RET, T.BDQTDE, T.BDUNID,
           T.BDFAT_CONV, T.BDQTDE_C, T.BDVL_E, T.BDCFOP, T.BDVL_BC_ICMS,
           T.BDALIQ_ICMS, T.BDVL_ICMS, T.BDVL_BCST, T.BDVL_BCST_INT,
           T.BDALIQ_ST_E, T.BDALIQ_ST_EF, T.BDCAL_ICMS_ST, T.BDVL_ICMS_ST,
           T.BDCOD_DA, T.BDNUM_DARE, T.BDCOD_AJ, T.BDALIQ_EF, T.BDC176
    FROM TMP_VEF_EMP_TDRCST_2130_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO;
    
    INSERT INTO VEF_EMP_TDRCST_2132(BDCODEMP, BDREFERENCIA, BDCODPROD, BDIND_OPER,
                                    BDCHAVE, BDORDEM, BDORDEMPRO, BDORDEMIC, BDORDEMDOCFREF, BDCODTER,
                                    BDCNPJ, BDCHV_NFE_REF, BDDT_E_REF)
    SELECT T.BDCODEMP, T.BDREFERENCIA, T.BDCODPROD, T.BDIND_OPER,
           T.BDCHAVE, T.BDORDEM, T.BDORDEMPRO,T.BDORDEMIC, T.BDORDEMDOCFREF, T.BDCODTER,
           T.BDCNPJ, T.BDCHV_NFE_REF, T.BDDT_E_REF
    FROM TMP_VEF_EMP_TDRCST_2132_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO;

    INSERT INTO VEF_EMP_TDRCST_2133 (bdCODEMP, bdREFERENCIA, bdCODPROD, bdIND_OPER, bdCHAVE, bdORDEM, bdORDEMPRO,
                                     bdORDEM2133, bdCHV_NFE_COMP, bdNUM_ITEM_NFE_COMP, bdCHAVE_COMP, bdORDEM_COMP, bdORDEMPRO_COMP, bdQTDITEM, bdVLRITEM)
    SELECT t.bdCODEMP, t.bdREFERENCIA, t.bdCODPROD, t.bdIND_OPER, t.bdCHAVE, t.bdORDEM, t.bdORDEMPRO,
           t.bdORDEM2133, t.bdCHV_NFE_COMP, t.bdNUM_ITEM_NFE_COMP, t.bdCHAVE_COMP, t.bdORDEM_COMP, t.bdORDEMPRO_COMP, t.bdQTDITEM, t.bdVLRITEM
    FROM TMP_VEF_EMP_TDRCST_2133_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO;

    INSERT INTO VEF_EMP_TDRCST_2134 (BDCODEMP, BDREFERENCIA, BDCODPROD, BDIND_OPER, BDCHAVE,
                                     BDORDEM, BDORDEMPRO, BDORDEM2134, BDCHV_NFE_COMP, BDCOD_IND_XML)
    SELECT t.BDCODEMP, t.BDREFERENCIA, t.BDCODPROD, t.BDIND_OPER, t.BDCHAVE,
           t.BDORDEM, t.BDORDEMPRO, t.BDORDEM2134, t.BDCHV_NFE_COMP, t.BDCOD_IND_XML
    FROM TMP_VEF_EMP_TDRCST_2134_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO;

    INSERT INTO VEF_EMP_TC195SAI(BDCODEMP, BDCHAVE, BDORDEMOBS, BDCODOBS)
    SELECT T.BDCODEMP, T.BDCHAVE, NULL,--(SELECT MAX(Coalesce(BDORDEMOBS,0))+1 FROM VEF_EMP_TC195SAI C WHERE C.BDCODEMP = T.BDCODEMP AND C.BDCHAVE = T.BDCHAVE),
           T.BDCODOBSC197
    FROM TMP_VEF_EMP_TDRCST_2113_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO AND
          T.BDCODAJU_GERAC197 > 0 AND
          T.BDCODOBSC197 > 0 AND
          T.BDIND_OPER = 0 AND
          T.BDVL_CREDITO_MVA_SN > 0 AND
          NOT EXISTS(SELECT FIRST 1 BDCODOBS
                     FROM VEF_EMP_TC195SAI C
                     WHERE C.BDCODEMP = T.BDCODEMP AND
                           C.BDCHAVE = T.BDCHAVE AND
                           C.BDCODOBS = T.BDCODOBSC197);


    INSERT INTO VEF_EMP_TC197SAI(BDCODEMP, BDCHAVE, BDORDEMOBS, BDORDEMOUTOBR, BDCODPROD, BDCODAJU,
                                 BDDESCCOMPL, BDBICMS, BDALIQICMS, BDVLRICMS, BDOUTVLR)
    SELECT T.BDCODEMP, T.BDCHAVE,
           (SELECT FIRST 1 C.BDORDEMOBS FROM VEF_EMP_TC195SAI C WHERE C.BDCODEMP = T.BDCODEMP AND C.BDCHAVE = T.BDCHAVE AND C.BDCODOBS = T.BDCODOBSC197) BDORDEMOBS,
           NULL, T.BDCODPROD, T.BDCODAJU_GERAC197, '', 0, 0, T.BDVL_CREDITO_MVA_SN, 0
    FROM TMP_VEF_EMP_TDRCST_2113_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO AND
          T.BDCODAJU_GERAC197 > 0 AND    
          T.BDCODOBSC197 > 0 AND
          T.BDIND_OPER = 0 AND
          T.BDVL_CREDITO_MVA_SN > 0;

    INSERT INTO TOL_VEF_DRCST_TC197SAI(BDCODEMP, BDCHAVE, BDORDEMOBS, BDORDEMOUTOBR, BDREFERENCIA,
                                       BDCODPROD, BDIND_OPER, BDORDEM, BDORDEMPRO)
    SELECT T.BDCODEMP, T.BDCHAVE,
           (SELECT FIRST 1 C.BDORDEMOBS FROM VEF_EMP_TC195SAI C WHERE C.BDCODEMP = T.BDCODEMP AND C.BDCHAVE = T.BDCHAVE AND C.BDCODOBS = T.BDCODOBSC197) BDORDEMOBS,
           (SELECT MAX(C.BDORDEMOUTOBR)
            FROM VEF_EMP_TC197SAI C
            WHERE C.BDCODEMP = T.BDCODEMP AND
                  C.BDCHAVE = T.BDCHAVE AND
                  C.BDORDEMOBS = (SELECT FIRST 1 C.BDORDEMOBS FROM VEF_EMP_TC195SAI C WHERE C.BDCODEMP = T.BDCODEMP AND C.BDCHAVE = T.BDCHAVE AND C.BDCODOBS = T.BDCODOBSC197) AND
                  C.BDVLRICMS = T.BDVL_CREDITO_MVA_SN AND
                  NOT EXISTS(SELECT FIRST 1 D.BDCHAVE
                             FROM TOL_VEF_DRCST_TC197SAI D
                             WHERE D.BDCODEMP = C.BDCODEMP AND
                                   D.BDCHAVE = C.BDCHAVE AND
                                   D.BDORDEMOBS = C.BDORDEMOBS AND
                                   D.BDORDEMOUTOBR = C.BDORDEMOUTOBR)) BDORDEMOUTOBR,
           T.BDREFERENCIA,T.BDCODPROD, T.BDIND_OPER, T.BDORDEM, T.BDORDEMPRO
    FROM TMP_VEF_EMP_TDRCST_2113_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO AND
          T.BDCODAJU_GERAC197 > 0 AND    
          T.BDCODOBSC197 > 0 AND
          T.BDIND_OPER = 0 AND
          T.BDVL_CREDITO_MVA_SN > 0;
                                       
    INSERT INTO VEF_EMP_TC195ENT(BDCODEMP, BDCHAVE, BDORDEMOBS, BDCODOBS)
    SELECT T.BDCODEMP, T.BDCHAVE, NULL,
           T.BDCODOBSC197
    FROM TMP_VEF_EMP_TDRCST_2130_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO AND
          T.BDCODAJU_GERAC197 > 0 AND
          T.BDCODOBSC197 > 0 AND
          T.BDIND_OPER = 0 AND
          T.BDVLRC197 > 0 AND
          NOT EXISTS(SELECT FIRST 1 BDCODOBS
                     FROM VEF_EMP_TC195ENT C
                     WHERE C.BDCODEMP = T.BDCODEMP AND
                           C.BDCHAVE = T.BDCHAVE AND
                           C.BDCODOBS = T.BDCODOBSC197);

    INSERT INTO VEF_EMP_TC197ENT(BDCODEMP, BDCHAVE, BDORDEMOBS, BDORDEMOUTOBR, BDCODPROD, BDCODAJU,
                                 BDDESCCOMPL, BDBICMS, BDALIQICMS, BDVLRICMS, BDOUTVLR)
    SELECT T.BDCODEMP, T.BDCHAVE,
           (SELECT FIRST 1 C.BDORDEMOBS FROM VEF_EMP_TC195ENT C WHERE C.BDCODEMP = T.BDCODEMP AND C.BDCHAVE = T.BDCHAVE AND C.BDCODOBS = T.BDCODOBSC197) BDORDEMOBS,
           NULL, T.BDCODPROD, T.BDCODAJU_GERAC197, '', 0, 0, T.BDVLRC197, 0
    FROM TMP_VEF_EMP_TDRCST_2130_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO AND
          T.BDCODAJU_GERAC197 > 0 AND    
          T.BDCODOBSC197 > 0 AND
          T.BDIND_OPER = 0 AND
          T.BDVLRC197 > 0;

    INSERT INTO TOL_VEF_DRCST_TC197ENT(BDCODEMP, BDCHAVE, BDORDEMOBS, BDORDEMOUTOBR, BDREFERENCIA,
                                       BDCODPROD, BDIND_OPER, BDORDEM, BDORDEMPRO)
    SELECT T.BDCODEMP, T.BDCHAVE,
           (SELECT FIRST 1 C.BDORDEMOBS FROM VEF_EMP_TC195ENT C WHERE C.BDCODEMP = T.BDCODEMP AND C.BDCHAVE = T.BDCHAVE AND C.BDCODOBS = T.BDCODOBSC197) BDORDEMOBS,
           (SELECT MAX(C.BDORDEMOUTOBR)
            FROM VEF_EMP_TC197ENT C
            WHERE C.BDCODEMP = T.BDCODEMP AND
                  C.BDCHAVE = T.BDCHAVE AND
                  C.BDORDEMOBS = (SELECT FIRST 1 C.BDORDEMOBS FROM VEF_EMP_TC195ENT C WHERE C.BDCODEMP = T.BDCODEMP AND C.BDCHAVE = T.BDCHAVE AND C.BDCODOBS = T.BDCODOBSC197) AND
                  C.BDVLRICMS = T.BDVLRC197 AND
                  NOT EXISTS(SELECT FIRST 1 D.BDCHAVE
                             FROM TOL_VEF_DRCST_TC197ENT D
                             WHERE D.BDCODEMP = C.BDCODEMP AND
                                   D.BDCHAVE = C.BDCHAVE AND
                                   D.BDORDEMOBS = C.BDORDEMOBS AND
                                   D.BDORDEMOUTOBR = C.BDORDEMOUTOBR)) BDORDEMOUTOBR,
           T.BDREFERENCIA,T.BDCODPROD, T.BDIND_OPER, T.BDORDEM, T.BDORDEMPRO
    FROM TMP_VEF_EMP_TDRCST_2130_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO AND
          T.BDCODAJU_GERAC197 > 0 AND    
          T.BDCODOBSC197 > 0 AND
          T.BDIND_OPER = 0 AND
          T.BDVLRC197 > 0;

    DELETE FROM TMP_VEF_EMP_TDRCST_E111_TEMP
    WHERE BDSESSAO = :PRSESSAO;

    INSERT INTO TMP_VEF_EMP_TDRCST_E111_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDVLRST, BDCODAJUICMS, BDDESC, BDORDEM)
    SELECT E.BDSESSAO, E.BDCODEMP, E.BDREFLAN, SUM(E.BDVLRST), E.BDCODAJUICMS, 
           'Nº NF-e ' || E.BDNUMDOCINI ||
           ', participante ' || TRIM(TER.BDNOMETER) ||
           ', valor total NF-e ' || E.BDVALORNOTA ||
           ', data de emissão ' || (SELECT BDDDMMAAAA FROM DDMMAAAA(E.BDDATAEMISSAO)) ||
           COALESCE(' e entrada ' || (SELECT BDDDMMAAAA FROM DDMMAAAA(E.BDDATAENTRADAENT)), '') BDDESC,
           GETORDEMSEQUENCIAL_STR(E.BDSESSAO||'|'||E.BDCODEMP, E.BDCODEMP)
    FROM(
        SELECT :PRSESSAO BDSESSAO, MOV.BDCODEMP, MOV.BDREFLAN, MOV.BDNUMDOCINI, MOV.BDCODTER, MOV.BDVALORNOTA, MOV.BDDATAEMISSAO, MOV.BDDATAENTRADAENT, MOVPRO.BDVLRST,
               COALESCE(( SELECT FIRST 1 A.BDCODAJUICMS_DEB
                          FROM VEF_BASE_TPLANOACOESCONFDRCST A
                          LEFT OUTER JOIN VEF_BASE_TVINCCODPLANODRCST V ON (V.BDCODPLACONFDRCST = A.BDCODPLACONFDRCST AND V.BDCHAVE = A.BDCHAVE)
                          WHERE A.BDCODPLACONFDRCST = GER.BDCODPLACONFDRCST AND
                                A.BDGERAE111 = 'TRUE' AND
                                V.BDCODNAT_VENDAS = I.BDCODNAT),
                         (SELECT FIRST 1 A.BDCODAJUICMS_DEB
                          FROM VEF_BASE_TPLANOACOESCONFDRCST A
                          WHERE A.BDCODPLACONFDRCST = GER.BDCODPLACONFDRCST AND
                                A.BDGERAE111 = 'TRUE' AND
                                NOT EXISTS(SELECT FIRST 1 VINC.BDCODNAT_VENDAS
                                           FROM VEF_BASE_TVINCCODPLANODRCST VINC
                                           WHERE VINC.BDCODPLACONFDRCST = A.BDCODPLACONFDRCST AND
                                                 VINC.BDCHAVE = A.BDCHAVE AND
                                                 VINC.BDCODNAT_VENDAS IS NOT NULL))
                       ) BDCODAJUICMS
        FROM TMP_VEF_EMP_TDRCSTGER_TEMP GER
        LEFT OUTER JOIN VEF_EMP_TMOVENT MOV ON (MOV.BDCODEMP = GER.BDCODEMP AND MOV.BDREFLAN = GER.BDREFERENCIA)
        LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        LEFT OUTER JOIN VEF_EMP_TMOVPROENT MOVPRO ON (MOVPRO.BDCODEMP = I.BDCODEMP AND MOVPRO.BDCHAVE = I.BDCHAVE AND MOVPRO.BDORDEM = I.BDORDEM)
        WHERE GER.BDSESSAO = :PRSESSAO AND
              MOV.BDCODSITNF NOT IN (2, 3, 4, 5) AND
              SUBSTRING(I.BDCODNAT FROM 1 FOR 4) <> '1929' AND
              SUBSTRING(I.BDCODNAT FROM 1 FOR 4) <> '2929' AND
              SUBSTRING(I.BDCODNAT FROM 1 FOR 1) <> '3' AND
              MOVPRO.BDVLRST > 0 AND              
              MOVPRO.BDQTDITEM > 0 AND     
              ((GER.BDDEV_VENDAS = 'TRUE') OR I.BDCODNAT IN (SELECT V.BDCODNAT_VENDAS
                                                             FROM VEF_BASE_TVINCCODPLANODRCST V
                                                             WHERE V.BDCODPLACONFDRCST = GER.BDCODPLACONFDRCST AND
                                                                   V.BDCODNAT_VENDAS IS NOT NULL)) AND
          NOT EXISTS(SELECT FIRST 1 DOCF.BDCHAVE
                     FROM VEF_EMP_TMOVENTDOCFREF DOCF
                     WHERE DOCF.BDCODEMP = MOV.BDCODEMP AND
                           DOCF.BDCHAVE = MOV.BDCHAVE AND
                           MOV.BDMODELO = 55 AND
                           EXTRACT(YEAR FROM DOCF.BDDTEMISSAO) || LPAD(EXTRACT(MONTH FROM DOCF.BDDTEMISSAO),2,'0') = MOV.BDREFLAN
                     UNION ALL
                     SELECT FIRST 1 M.BDCHAVE
                     FROM VEF_EMP_TMOVSAI M                                                                           
                     INNER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                     INNER JOIN VEF_EMP_TMOVPROSAI MPRO ON (MPRO.BDCODEMP = I.BDCODEMP AND MPRO.BDCHAVE = I.BDCHAVE AND MPRO.BDORDEM = I.BDORDEM)
                     WHERE M.BDCODEMP = MOV.BDCODEMP AND
                           M.BDREFLAN = MOV.BDREFLAN AND
                           M.BDMODELO = 55 AND
                           M.BDCODSITNF NOT IN (2, 3, 4, 5) AND
                           SUBSTRING(I.BDCODNAT FROM 1 FOR 4) <> '5929' AND
                           SUBSTRING(I.BDCODNAT FROM 1 FOR 4) <> '6929' AND
                           SUBSTRING(I.BDCODNAT FROM 1 FOR 1) <> '7'    AND
                           MPRO.BDCODPROD = MOVPRO.BDCODPROD AND
                           MPRO.BDQTDITEM > 0 AND
                           (MPRO.BDVLRITEM / MPRO.BDQTDITEM) = (MOVPRO.BDVLRITEM / MOVPRO.BDQTDITEM) AND
                           (MPRO.BDVLRST / MPRO.BDQTDITEM) = (MOVPRO.BDVLRST / MOVPRO.BDQTDITEM))
        UNION ALL
        SELECT :PRSESSAO BDSESSAO, MOV.BDCODEMP, MOV.BDREFLAN, MOV.BDNUMDOCINI, MOV.BDCODTER, MOV.BDVALORNOTA, MOV.BDDATAEMISSAO, NULL BDDATAENTRADAENT, MOVPRO.BDVLRST,
               COALESCE(( SELECT FIRST 1 A.BDCODAJUICMS_CRED
                          FROM VEF_BASE_TPLANOACOESCONFDRCST A
                          LEFT OUTER JOIN VEF_BASE_TVINCCODPLANODRCST V ON (V.BDCODPLACONFDRCST = A.BDCODPLACONFDRCST AND V.BDCHAVE = A.BDCHAVE)
                          WHERE A.BDCODPLACONFDRCST = GER.BDCODPLACONFDRCST AND
                                A.BDGERAE111 = 'TRUE' AND
                                V.BDCODNAT_COMPRAS = I.BDCODNAT),
                         (SELECT FIRST 1 A.BDCODAJUICMS_CRED
                          FROM VEF_BASE_TPLANOACOESCONFDRCST A
                          WHERE A.BDCODPLACONFDRCST = GER.BDCODPLACONFDRCST AND
                                A.BDGERAE111 = 'TRUE' AND
                                NOT EXISTS(SELECT FIRST 1 VINC.BDCODNAT_COMPRAS
                                           FROM VEF_BASE_TVINCCODPLANODRCST VINC
                                           WHERE VINC.BDCODPLACONFDRCST = A.BDCODPLACONFDRCST AND
                                                 VINC.BDCHAVE = A.BDCHAVE AND
                                                 VINC.BDCODNAT_COMPRAS IS NOT NULL))
                       ) BDCODAJUICMS
        FROM TMP_VEF_EMP_TDRCSTGER_TEMP GER
        LEFT OUTER JOIN VEF_EMP_TMOVSAI MOV ON (MOV.BDCODEMP = GER.BDCODEMP AND MOV.BDREFLAN = GER.BDREFERENCIA)
        LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        LEFT OUTER JOIN VEF_EMP_TMOVPROSAI MOVPRO ON (MOVPRO.BDCODEMP = I.BDCODEMP AND MOVPRO.BDCHAVE = I.BDCHAVE AND MOVPRO.BDORDEM = I.BDORDEM)
        WHERE GER.BDSESSAO = :PRSESSAO AND
              MOV.BDCODSITNF NOT IN (2, 3, 4, 5) AND  
              SUBSTRING(I.BDCODNAT FROM 1 FOR 4) <> '5929' AND
              SUBSTRING(I.BDCODNAT FROM 1 FOR 4) <> '6929' AND
              SUBSTRING(I.BDCODNAT FROM 1 FOR 1) <> '7'    AND  
              MOVPRO.BDVLRST > 0 AND              
              MOVPRO.BDQTDITEM > 0 AND
              ((GER.BDDEV_COMPRAS = 'TRUE') OR I.BDCODNAT IN (SELECT V.BDCODNAT_COMPRAS
                                                              FROM VEF_BASE_TVINCCODPLANODRCST V
                                                              WHERE V.BDCODPLACONFDRCST = GER.BDCODPLACONFDRCST AND
                                                                    V.BDCODNAT_COMPRAS IS NOT NULL)) AND
          NOT EXISTS( SELECT FIRST 1 DOCF.BDCHAVE
                      FROM VEF_EMP_TMOVSAIDOCFREF DOCF
                      WHERE DOCF.BDCODEMP = MOV.BDCODEMP AND
                            DOCF.BDCHAVE = MOV.BDCHAVE AND
                            MOV.BDMODELO = 55 AND
                            EXTRACT(YEAR FROM DOCF.BDDTEMISSAO) || LPAD(EXTRACT(MONTH FROM DOCF.BDDTEMISSAO),2,'0') = MOV.BDREFLAN
                      UNION ALL
                      SELECT FIRST 1 M.BDCHAVE
                      FROM VEF_EMP_TMOVENT M
                      INNER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                      INNER JOIN VEF_EMP_TMOVPROENT MPRO ON (MPRO.BDCODEMP = I.BDCODEMP AND MPRO.BDCHAVE = I.BDCHAVE AND MPRO.BDORDEM = I.BDORDEM)
                      WHERE M.BDCODEMP = MOV.BDCODEMP AND
                            M.BDREFLAN = MOV.BDREFLAN AND
                            M.BDMODELO = 55 AND
                            M.BDCODSITNF NOT IN (2, 3, 4, 5) AND
                            SUBSTRING(I.BDCODNAT FROM 1 FOR 4) <> '1929' AND
                            SUBSTRING(I.BDCODNAT FROM 1 FOR 4) <> '2929' AND
                            SUBSTRING(I.BDCODNAT FROM 1 FOR 1) <> '3' AND
                            MPRO.BDCODPROD = MOVPRO.BDCODPROD AND
                            MPRO.BDQTDITEM > 0 AND
                            (MPRO.BDVLRITEM/MPRO.BDQTDITEM) = (MOVPRO.BDVLRITEM/MOVPRO.BDQTDITEM) AND
                            (MPRO.BDVLRST/MPRO.BDQTDITEM) = (MOVPRO.BDVLRST/MOVPRO.BDQTDITEM)
                     )
    ) E
    LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = E.BDCODTER)    
    WHERE E.BDCODAJUICMS > 0     
    GROUP BY E.BDSESSAO, E.BDCODEMP, E.BDREFLAN, E.BDNUMDOCINI, E.BDCODTER, E.BDVALORNOTA, E.BDDATAEMISSAO, E.BDDATAENTRADAENT, E.BDCODAJUICMS, TER.BDNOMETER;

 /*   INSERT INTO VEF_EMP_TAJUICMSE111(BDCODEMP, BDORDEME111220, BDCODAJUICMS, BDREFERENCIA, BDDESCCOMP, BDVLRAJU)
    SELECT E.BDCODEMP, 0, E.BDCODAJUICMS, E.BDREFERENCIA, E.BDDESC, E.BDVLRST
    FROM TMP_VEF_EMP_TDRCST_E111_TEMP E
    WHERE E.BDSESSAO = :PRSESSAO;

    INSERT INTO TOL_VEF_EMP_DRCST_TE111(BDCODEMP, BDORDEME111220, BDREFERENCIA) 
    SELECT E.BDCODEMP, (SELECT MAX(A.BDORDEME111220)
                        FROM VEF_EMP_TAJUICMSE111 A
                        WHERE A.BDCODEMP = E.BDCODEMP AND
                              A.BDREFERENCIA = E.BDREFERENCIA AND
                              A.BDCODAJUICMS = E.BDCODAJUICMS AND
                              A.BDDESCCOMP = E.BDDESC
                              ), E.BDREFERENCIA
    FROM TMP_VEF_EMP_TDRCST_E111_TEMP E
    WHERE E.BDSESSAO = :PRSESSAO;


    DELETE FROM TMP_VEF_EMP_TDRCST_E111_TEMP
    WHERE BDSESSAO = :PRSESSAO;  */
END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_DRCST_APLICA_ACOES (
    PRSESSAO INTEGER,
    PRDATAINICIO DATE,
    PRDATAFIM DATE)
AS
DECLARE VARIABLE WCODPLACONFDRCST INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WMVAALIQ NUMERIC(7,4);
DECLARE VARIABLE WMVARED NUMERIC(7,4);
DECLARE VARIABLE WMVAAJUSTADA NUMERIC(7,4);
DECLARE VARIABLE WALIQINTERESTADUAL NUMERIC(7,4);
DECLARE VARIABLE WALIQINTERNA NUMERIC(7,4);
DECLARE VARIABLE WMVASTORIGINAL NUMERIC(7,4);
DECLARE VARIABLE WCODTER_FIL INTEGER;
DECLARE VARIABLE WCODNAT_FIL INTEGER;
DECLARE VARIABLE WCODPROD_FIL INTEGER;
DECLARE VARIABLE WNCMPROD_FIL INTEGER;
DECLARE VARIABLE WCODCSTICMS_FIL INTEGER;
DECLARE VARIABLE WTPALIQINTERNA INTEGER;
DECLARE VARIABLE WTPALIQINTERESTADUAL INTEGER;
DECLARE VARIABLE WTIPOOPER INTEGER;
DECLARE VARIABLE WGERAC197 INTEGER;
DECLARE VARIABLE WBUSCAC197 VARCHAR(5);
DECLARE VARIABLE WCODOBSC197 INTEGER;
BEGIN
  FOR SELECT P.BDCODPLACONFDRCST, P.BDCHAVE, P.BDTIPOOPER, P.BDMVASTORIGINAL, P.BDALIQINTERNA, P.BDALIQINTERESTADUAL,
             P.BDMVAAJUSTADA, P.BDMVARED, P.BDTPALIQINTERNA, P.BDTPALIQINTERESTADUAL, P.BDBUSCAC197, P.BDCODAJU_GERAC197,
             P.BDCODOBSC197,
             MAX(V.BDCODTER_FIL), MAX(V.BDCODNAT_FIL), MAX(V.BDCODPROD_FIL), MAX(V.BDNCMPROD_FIL), MAX(V.BDCODCSTICMS_FIL)
      FROM VEF_BASE_TPLANOACOESCONFDRCST P    
      LEFT OUTER JOIN VEF_BASE_TVINCCODPLANODRCST V ON (V.BDCODPLACONFDRCST = P.BDCODPLACONFDRCST AND V.BDCHAVE = P.BDCHAVE)
      WHERE EXISTS (SELECT FIRST 1 G.BDCODPLACONFDRCST FROM TMP_VEF_EMP_TDRCSTGER_TEMP G WHERE G.BDSESSAO = :PRSESSAO AND G.BDCODPLACONFDRCST = P.BDCODPLACONFDRCST)
      GROUP BY P.BDCODPLACONFDRCST, P.BDCHAVE, P.BDTIPOOPER, P.BDQTDFILTRO, P.BDMVASTORIGINAL, P.BDALIQINTERNA, P.BDALIQINTERESTADUAL,
               P.BDMVAAJUSTADA, P.BDMVARED, P.BDTPALIQINTERNA, P.BDTPALIQINTERESTADUAL, P.BDBUSCAC197, P.BDCODAJU_GERAC197, P.BDCODOBSC197
      ORDER BY P.BDQTDFILTRO
  INTO :WCODPLACONFDRCST, :WCHAVE, :WTIPOOPER, :WMVASTORIGINAL, :WALIQINTERNA, :WALIQINTERESTADUAL, :WMVAAJUSTADA, :WMVARED,
       :WTPALIQINTERNA, :WTPALIQINTERESTADUAL, :WBUSCAC197, :WGERAC197, :WCODOBSC197,
       :WCODTER_FIL, :WCODNAT_FIL, :WCODPROD_FIL, :WNCMPROD_FIL, :WCODCSTICMS_FIL  DO
  BEGIN
    IF (WTIPOOPER = 0) THEN -- Venda para SN
      BEGIN
        UPDATE TMP_VEF_EMP_TDRCST_2113_TEMP D SET
            D.BDCHAVETROCA =
                 (SELECT FIRST 1 A.BDCHAVE
                  FROM VEF_BASE_TPLANOACOESCONFDRCST A
                  LEFT OUTER JOIN VEF_BASE_TVINCCODPLANODRCST V ON (V.BDCODPLACONFDRCST = A.BDCODPLACONFDRCST AND V.BDCHAVE = A.BDCHAVE)
                  LEFT OUTER JOIN VW_TCADPRO P ON (P.BDCODPROD = D.BDCODPROD AND P.BDCODEMP = D.BDCODEMP)
                  WHERE A.BDCODPLACONFDRCST = :WCODPLACONFDRCST
                    AND A.BDCHAVE = :WCHAVE
                  GROUP BY A.BDCHAVE
                  HAVING MAX(IIF((:WCODTER_FIL IS NULL) OR (V.BDCODTER_FIL = D.BDCODTER),'T','F')) = 'T'
                     AND MAX(IIF((:WCODNAT_FIL IS NULL) OR (V.BDCODNAT_FIL = D.BDCODNAT),'T','F')) = 'T'
                     AND MAX(IIF((:WCODPROD_FIL IS NULL) OR (V.BDCODPROD_FIL = D.BDCODPROD),'T','F')) = 'T'
                     AND MAX(IIF((:WNCMPROD_FIL IS NULL) OR (V.BDNCMPROD_FIL = P.BDNCMPROD),'T','F')) = 'T'
                     AND MAX(IIF((:WCODCSTICMS_FIL IS NULL) OR (V.BDCODCSTICMS_FIL = D.BDCODCSTICMS),'T','F')) = 'T')
        WHERE D.BDSESSAO = :PRSESSAO
          AND D.BDCHAVETROCA IS NULL
          AND D.BDCODPLACONFDRCST = :WCODPLACONFDRCST
          AND D.BDIND_S = 30; -- Apenas de venda para o SN;
        IF (:WBUSCAC197 <> 'TRUE') THEN -- Calcula MVA pelas alíquotas do plano
          BEGIN
            UPDATE TMP_VEF_EMP_TDRCST_2113_TEMP D
            SET D.BDALIQINTERESTADUAL =
                    CASE
                      WHEN :WTPALIQINTERESTADUAL = 1 THEN D.BDALIQ_IE_NF
                      WHEN :WTPALIQINTERESTADUAL = 2 THEN D.BDALIQ_IE_PRO
                      WHEN :WTPALIQINTERESTADUAL = 3 THEN D.BDALIQ_IE_UFORI
                      WHEN :WTPALIQINTERESTADUAL = 4 THEN D.BDALIQ_IE_UFDEST
                      WHEN :WTPALIQINTERESTADUAL = 5 THEN :WALIQINTERESTADUAL
                      ELSE 0
                    END,
                D.BDALIQINTERNA =
                    CASE
                      WHEN :WTPALIQINTERNA = 1 THEN D.BDALIQ_I_PRO
                      WHEN :WTPALIQINTERNA = 2 THEN D.BDALIQ_I_UF
                      WHEN :WTPALIQINTERNA = 3 THEN :WALIQINTERNA
                      ELSE 0
                    END,
                D.BDMVAAJUSTADA = COALESCE(:WMVAAJUSTADA,0),
                D.BDMVASTORIGINAL = COALESCE(:WMVASTORIGINAL,0),
                D.BDMVARED = COALESCE(:WMVARED,0)
            WHERE D.BDSESSAO = :PRSESSAO
              AND D.BDIND_S = 30 -- Apenas de venda para o SN
              AND D.BDCODPLACONFDRCST = :WCODPLACONFDRCST
              AND D.BDCHAVETROCA = :WCHAVE;
              
            UPDATE TMP_VEF_EMP_TDRCST_2113_TEMP D
            SET D.BDMVAAJUSTADA = IIF(D.BDMVAAJUSTADA > 0,D.BDMVAAJUSTADA/100, ((1 + D.BDMVASTORIGINAL/100) * (1 - D.BDALIQINTERESTADUAL/100) / (1 - D.BDALIQINTERNA/100)) - 1)
            WHERE D.BDSESSAO = :PRSESSAO
              AND D.BDIND_S = 30 -- Apenas de venda para o SN
              AND D.BDCODPLACONFDRCST = :WCODPLACONFDRCST
              AND D.BDCHAVETROCA = :WCHAVE;

          END
        ELSE  -- Pega valor do MVA pelo C197
          BEGIN  
            UPDATE TMP_VEF_EMP_TDRCST_2113_TEMP D
            SET D.BDVL_CREDITO_MVA_SN =
                           CASE
                             WHEN D.BDIND_OPER = 0 THEN  -- Saídas
                               (SELECT SUM(COALESCE(C.BDVLRICMS,0))
                                FROM VEF_EMP_TC197SAI C
                                WHERE C.BDCODEMP = D.BDCODEMP AND
                                      C.BDCHAVE = D.BDCHAVE AND
                                      C.BDCODPROD = D.BDCODPROD AND
                                      C.BDCODAJU IN (SELECT A.BDCODAJU_C197
                                                     FROM VEF_BASE_TVINCCODPLANODRCST A
                                                     WHERE A.BDCODPLACONFDRCST = D.BDCODPLACONFDRCST
                                                       AND A.BDCHAVE = D.BDCHAVETROCA))

                             WHEN D.BDIND_OPER = 1 THEN -- Entradas
                               (SELECT SUM(C.BDVLRICMS)
                                FROM VEF_EMP_TC197ENT C
                                WHERE C.BDCODEMP = D.BDCODEMP AND
                                      C.BDCHAVE = D.BDCHAVE AND
                                      C.BDCODPROD = D.BDCODPROD AND
                                      C.BDCODAJU IN (SELECT A.BDCODAJU_C197
                                                     FROM VEF_BASE_TVINCCODPLANODRCST A
                                                     WHERE A.BDCODPLACONFDRCST = D.BDCODPLACONFDRCST
                                                       AND A.BDCHAVE = D.BDCHAVETROCA))
                             ELSE 0
                           END

            WHERE D.BDSESSAO = :PRSESSAO
              AND D.BDIND_S = 30 -- Apenas de venda para o SN
              AND D.BDCODPLACONFDRCST = :WCODPLACONFDRCST
              AND D.BDCHAVETROCA = :WCHAVE;
          END
      END
    ELSE IF (:WTIPOOPER = 1) THEN -- Compra sem destaque de ICMS ST
      BEGIN
        UPDATE TMP_VEF_EMP_TDRCST_2130_TEMP D SET
            D.BDCHAVETROCA =
                 (SELECT FIRST 1 A.BDCHAVE
                  FROM VEF_BASE_TPLANOACOESCONFDRCST A
                  LEFT OUTER JOIN VEF_BASE_TVINCCODPLANODRCST V ON (V.BDCODPLACONFDRCST = A.BDCODPLACONFDRCST AND V.BDCHAVE = A.BDCHAVE)
                  LEFT OUTER JOIN VW_TCADPRO P ON (P.BDCODPROD = D.BDCODPROD AND P.BDCODEMP = D.BDCODEMP)
                  WHERE A.BDCODPLACONFDRCST = :WCODPLACONFDRCST
                    AND A.BDCHAVE = :WCHAVE
                  GROUP BY A.BDCHAVE
                  HAVING MAX(IIF((:WCODTER_FIL IS NULL) OR (V.BDCODTER_FIL = D.BDCODTER),'T','F')) = 'T'
                     AND MAX(IIF((:WCODNAT_FIL IS NULL) OR (V.BDCODNAT_FIL = D.BDCODNAT),'T','F')) = 'T'
                     AND MAX(IIF((:WCODPROD_FIL IS NULL) OR (V.BDCODPROD_FIL = D.BDCODPROD),'T','F')) = 'T'
                     AND MAX(IIF((:WNCMPROD_FIL IS NULL) OR (V.BDNCMPROD_FIL = P.BDNCMPROD),'T','F')) = 'T'
                     AND MAX(IIF((:WCODCSTICMS_FIL IS NULL) OR (V.BDCODCSTICMS_FIL = D.BDCODCSTICMS),'T','F')) = 'T')
        WHERE D.BDSESSAO = :PRSESSAO
          AND D.BDCHAVETROCA IS NULL
          AND D.BDCODPLACONFDRCST = :WCODPLACONFDRCST;
                
        IF (WBUSCAC197 = 'TRUE') THEN
          BEGIN
            --Insert para levar no 2130 as notas que possuem o C197 mas sem ICMS ST destacado
            INSERT INTO TMP_VEF_EMP_TDRCST_2130_TEMP (BDSESSAO, BDC176, BDCODEMP, BDREFERENCIA, BDCODPROD, BDIND_OPER, BDCHAVE, BDORDEM,
                                                      BDORDEMPRO, BDCHV_NFE, BDDT_E, BDDT_NFE, BDCODTER, BDNOMTER, BDCNPJ,
                                                      BDNUM_ITEM, BDCOD_RESP_RET, BDQTDE, BDCODUNIMED, BDUNID, BDCODFATCON, BDFAT_CONV, BDQTDE_C, BDVL_E,
                                                      BDCODNAT, BDCFOP, BDVL_BC_ICMS, BDALIQ_ICMS, BDVL_ICMS, BDVL_BCST, BDVL_BCST_INT,
                                                      BDALIQ_ST_E, BDALIQ_ST_EF, BDCAL_ICMS_ST, BDVL_ICMS_ST, BDCOD_DA, BDNUM_DARE, BDCOD_AJ, BDALIQ_EF,
                                                      BDCODCSTICMS, BDCODPLACONFDRCST, BDQTDTOTAL, BDALIQST, BDALIQICMSPROD, BDALIQINT)
            SELECT  :PRSESSAO BDSESSAO, 'FALSE' BDC176, S.BDCODEMP, S.BDREFERENCIA, S.BDCODPROD, S.BDIND_OPER, S.BDCHAVE, S.BDORDEM,
                     S.BDORDEMPRO, S.BDCHV_NFE, S.BDDT_E, NULL BDDT_NFE, S.BDCODTER, S.BDNOMETER BDNOMTER, S.BDCGCTER BDCNPJ,
                     S.BDORDEMPRO BDNUM_ITEM, S.BDCOD_RESP_RET,
                     S.BDQTDE, COALESCE(UNIFATCONV.BDCODUNIMED,UNIPRO.BDCODUNIMED), COALESCE(UNIFATCONV.BDAPEUNIMED,UNIPRO.BDAPEUNIMED) BDUNID, S.BDCODFATCON,
                     F.BDFATORCONVER BDFAT_CONV, (S.BDQTDE * COALESCE(F.BDFATORCONVER,1)) BDQTDE_C, S.BDVL_E,
                     S.BDCODNAT, S.BDCFOP, S.BDVL_BC_ICMS, S.BDALIQ_ICMS,
                     0 BDVL_ICMS, S.BDVL_BCST, S.BDVL_BCST_INT,
                     S.BDALIQ_ST_E, 
                     CASE                                         
                     WHEN S.BDALIQST > 0 THEN S.BDALIQST
                     WHEN S.BDALIQICMSPROD > 0 THEN S.BDALIQICMSPROD
                     ELSE S.BDALIQINT
                     END BDALIQ_ST_EF, 0 BDCAL_ICMS_ST,
                     S.BDVL_ICMS_ST, NULL BDARRECADACAO, NULL BDNUM_DA,
                     (SELECT FIRST 1 AJU.BDCODAJUPAD
                      FROM VEF_EMP_TC197ENT C197
                      LEFT OUTER JOIN VEF_BASE_TTABCODAJU AJU ON (AJU.BDCODAJU = C197.BDCODAJU)
                      WHERE C197.BDCODEMP = S.BDCODEMP AND C197.BDCHAVE = S.BDCHAVE AND C197.BDCODPROD = S.BDCODPROD) BDCOD_AJ,
                     COALESCE(S.BDALIQICMSEFETIVO, COALESCE(S.BDALIQINT,0)) BDALIQ_EF, S.BDCODCSTICMS, S.BDCODPLACONFDRCST, S.BDQTDTOTAL, S.BDALIQST, S.BDALIQICMSPROD, S.BDALIQINT
            FROM (   SELECT  LAN.BDCODEMP, LAN.BDREFERENCIA, MOVPRO.BDCODPROD, 0 BDIND_OPER, MOV.BDCHAVE, I.BDORDEM, MOVPRO.BDORDEMPRO, MOV.BDCHAVENFE BDCHV_NFE,
                             MOV.BDDATAENTRADAENT BDDT_E, MOV.BDCODTER, COALESCE(MOVPRO.BDQTDITEM,0) BDQTDE, MOVPRO.BDCODFATCON, I.BDCODNAT,
                             I.BDCODNAT BDCFOP, COALESCE(MOVPRO.BDVLRST,0) AS BDVLRST, 3 BDCOD_RESP_RET, COALESCE(MOVPRO.BDVLRICMS,0) AS BDVLRICMS,
                             (COALESCE(MOVPRO.BDVLRITEM,0) + COALESCE(MOVPRO.BDVLRDESPACESSORIA,0)) BDVL_E, TER.BDNOMETER, TER.BDCGCTER,
                             PROD.BDCODUNIMED, PROD.BDALIQICMSEFETIVO, PROD.BDALIQICMS AS BDALIQICMSPROD, MOVPRO.BDALIQST,
                             UF.BDALIQINT, COALESCE(MOVPRO.BDBCICMS,0) AS BDVL_BC_ICMS, MOVPRO.BDALIQICMS BDALIQ_ICMS, 0 BDVL_BCST,
                             0 BDVL_BCST_INT, MOVPRO.BDALIQICMS BDALIQ_ST_E, 0 BDVL_ICMS_ST,
                             MOVPRO.BDCODCSTICMS, LAN.BDCODPLACONFDRCST, LAN.BDQTDTOTAL
                     FROM ( SELECT D.BDCODEMP, D.BDREFERENCIA, D.BDCODPROD, G.BDCODPLACONFDRCST,
                                   SUM(D.BDQTD) BDQTDTOTAL
                            FROM ( SELECT D.BDCODEMP, D.BDREFERENCIA, D.BDCODPROD, D.BDQTDE_V_CF AS BDQTD
                                   FROM TMP_VEF_EMP_TDRCST_2112_TEMP D
                                   WHERE D.BDSESSAO = :PRSESSAO
                                   UNION ALL
                                   SELECT D.BDCODEMP, D.BDREFERENCIA, D.BDCODPROD, D.BDQTDE_IND_S_C AS BDQTD
                                   FROM TMP_VEF_EMP_TDRCST_2113_TEMP D
                                   WHERE D.BDSESSAO = :PRSESSAO AND
                                     NOT EXISTS(SELECT FIRST 1 S.BDCODEMP
                                                FROM VEF_EMP_TMOVSTC176 S
                                                WHERE S.BDCODEMP = D.BDCODEMP AND
                                                      S.BDCHAVE = D.BDCHAVE AND
                                                      S.BDORDEM = D.BDORDEM AND
                                                      S.BDORDEMPRO = D.BDORDEMPRO)) D
                            LEFT OUTER JOIN TMP_VEF_EMP_TDRCSTGER_TEMP G ON (G.BDSESSAO = :PRSESSAO AND G.BDCODEMP = D.BDCODEMP AND G.BDREFERENCIA = D.BDREFERENCIA)
                            LEFT OUTER JOIN VEF_BASE_TPLACONFDRCST P ON (P.BDCODPLACONFDRCST = G.BDCODPLACONFDRCST)
                            WHERE COALESCE(P.BDAPENASC176,'FALSE') = 'FALSE' AND
                                  D.BDQTD > 0
                            GROUP BY D.BDCODEMP, D.BDREFERENCIA, D.BDCODPROD, G.BDCODPLACONFDRCST
                           ) LAN
                     JOIN VEF_EMP_TMOVENT MOV ON (MOV.BDCODEMP = LAN.BDCODEMP)
                     JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                     JOIN VEF_EMP_TMOVPROENT MOVPRO ON (MOVPRO.BDCODEMP = I.BDCODEMP AND MOVPRO.BDCHAVE = I.BDCHAVE AND MOVPRO.BDORDEM = I.BDORDEM)
                     LEFT OUTER JOIN TMP_VEF_EMP_TDRCSTGER_TEMP GER ON (GER.BDSESSAO = :PRSESSAO AND GER.BDCODEMP = LAN.BDCODEMP AND GER.BDREFERENCIA = LAN.BDREFERENCIA)
                     LEFT OUTER JOIN VEF_BASE_TTABCSTICMS CST ON (CST.BDCODCSTICMS = MOVPRO.BDCODCSTICMS)
                     LEFT OUTER JOIN VEF_EMP_TMOVMVASC MVA ON (MVA.BDCODEMP = MOVPRO.BDCODEMP AND MVA.BDCHAVE = MOVPRO.BDCHAVE AND MVA.BDORDEM = MOVPRO.BDORDEM AND MVA.BDCODPROD = MOVPRO.BDCODPROD)
                     LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = MOV.BDCODTER)
                     LEFT OUTER JOIN TCADPRO_VINC PROD ON (PROD.BDCODPROD = MOVPRO.BDCODPROD AND PROD.BDCODEMP = MOVPRO.BDCODEMP)
                     LEFT OUTER JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = LAN.BDCODEMP)
                     LEFT OUTER JOIN TCIDADE cid ON (cid.BDCODCID = EMP.BDCODCID)
                     LEFT OUTER JOIN TUF uf ON (UF.BDCODUF = cid.BDCODUF)
                     WHERE (MOV.BDREFLAN BETWEEN(SELECT BDREFERENCIA FROM DEC_REFERENCIA(LAN.BDREFERENCIA, 12)) AND LAN.BDREFERENCIA) AND
                            MOV.BDMODELO = 55 AND
                            MOV.BDCODSITNF NOT IN (2, 3, 4, 5) AND
                           ((GER.BDDEV_VENDAS = 'FALSE') AND
                            NOT I.BDCODNAT IN (SELECT V.BDCODNAT_VENDAS
                                               FROM VEF_BASE_TVINCCODPLANODRCST V
                                               WHERE V.BDCODPLACONFDRCST = GER.BDCODPLACONFDRCST AND
                                                     V.BDCODNAT_VENDAS IS NOT NULL)) AND
                            MOVPRO.BDCODPROD = LAN.BDCODPROD AND
                            MOVPRO.BDQTDITEM > 0 AND
                            MVA.BDCODEMP IS NULL AND  
                            (COALESCE(MOVPRO.BDVLRST,0) + COALESCE(MOVPRO.BDFCPRETIDO,0)) = 0 AND
                            (COALESCE(MOVPRO.BDVLRICMSSTRET,0) + COALESCE(MOVPRO.BDVLRFCPSTRET,0)) = 0 AND
                            EXISTS(SELECT FIRST 1 A.BDCHAVE
                                   FROM(SELECT A.BDCHAVE,
                                               (IIF((:WCODTER_FIL IS NULL) OR (V.BDCODTER_FIL = MOV.BDCODTER),'T','F')) BDCODTER_FIL,
                                               (IIF((:WCODNAT_FIL IS NULL) OR (V.BDCODNAT_FIL = I.BDCODNAT),'T','F')) BDCODNAT_FIL,
                                               (IIF((:WCODPROD_FIL IS NULL) OR (V.BDCODPROD_FIL = MOVPRO.BDCODPROD),'T','F')) BDCODPROD_FIL,
                                               (IIF((:WNCMPROD_FIL IS NULL) OR (V.BDNCMPROD_FIL = PROD.BDNCMPROD),'T','F')) BDNCMPROD_FIL,
                                               (IIF((:WCODCSTICMS_FIL IS NULL) OR (V.BDCODCSTICMS_FIL = MOVPRO.BDCODCSTICMS),'T','F')) BDCODCSTICMS_FIL
                                        FROM VEF_BASE_TPLANOACOESCONFDRCST A
                                        LEFT OUTER JOIN VEF_BASE_TVINCCODPLANODRCST V ON (V.BDCODPLACONFDRCST = A.BDCODPLACONFDRCST AND V.BDCHAVE = A.BDCHAVE)
                                        WHERE A.BDCODPLACONFDRCST = :WCODPLACONFDRCST
                                          AND A.BDCHAVE = :WCHAVE) A
                                   GROUP BY A.BDCHAVE
                                   HAVING MAX(BDCODTER_FIL)     = 'T'
                                      AND MAX(BDCODNAT_FIL)     = 'T'
                                      AND MAX(BDCODPROD_FIL)    = 'T'
                                      AND MAX(BDNCMPROD_FIL)    = 'T'
                                      AND MAX(BDCODCSTICMS_FIL) = 'T') AND
                            EXISTS(SELECT FIRST 1 C.BDCODEMP
                                   FROM VEF_EMP_TC197ENT C
                                   WHERE C.BDCODEMP = MOV.BDCODEMP
                                     AND C.BDCHAVE = MOV.BDCHAVE
                                     AND C.BDCODPROD = LAN.BDCODPROD
                                     AND C.BDCODAJU IN (SELECT A.BDCODAJU_C197
                                                        FROM VEF_BASE_TVINCCODPLANODRCST A
                                                        WHERE A.BDCODPLACONFDRCST = GER.BDCODPLACONFDRCST
                                                          AND A.BDCHAVE = :WCHAVE))  AND
                            CHAR_LENGTH(TER.BDCGCTER) = 18
                     ORDER BY LAN.BDCODEMP, LAN.BDREFERENCIA DESC, LAN.BDCODPROD
                    )S
            LEFT OUTER JOIN TUNIDADEMEDIDA UNIPRO ON (UNIPRO.BDCODUNIMED = S.BDCODUNIMED)
            LEFT OUTER JOIN TFATCONV F ON (F.BDCODPROD = S.BDCODPROD AND F.BDCODEMP = S.BDCODEMP AND F.BDCODFATCON = S.BDCODFATCON)
            LEFT OUTER JOIN TUNIDADEMEDIDA UNIFATCONV ON (UNIFATCONV.BDCODUNIMED = F.BDCODUNIMED)
            WHERE GETQUANTIDADEPRODUTO(S.BDIND_OPER||'.'||S.BDCODEMP || '.' || S.BDCODPROD, S.BDQTDE) < S.BDQTDTOTAL;

            UPDATE TMP_VEF_EMP_TDRCST_2130_TEMP D
            SET D.BDVL_BCST = IIF(D.BDVL_BCST > 0, D.BDVL_BCST,
                                IIF(D.BDIND_OPER = 0,
                                (SELECT SUM(C.BDBICMS)
                                 FROM VEF_EMP_TC197ENT C
                                 WHERE C.BDCODEMP = D.BDCODEMP AND C.BDCHAVE = D.BDCHAVE AND C.BDCODPROD = D.BDCODPROD
                                   AND D.BDIND_OPER = 0 -- Compras
                                   AND C.BDCODAJU IN (SELECT A.BDCODAJU_C197
                                                     FROM VEF_BASE_TVINCCODPLANODRCST A
                                                     WHERE A.BDCODPLACONFDRCST = D.BDCODPLACONFDRCST
                                                       AND A.BDCHAVE = D.BDCHAVETROCA)
                                  AND NOT EXISTS (SELECT FIRST 1 M.BDCODEMP
                                                  FROM VEF_EMP_TMOVMVASC M
                                                  WHERE M.BDCODEMP = C.BDCODEMP AND
                                                        M.BDCHAVE = C.BDCHAVE AND
                                                        M.BDCODPROD = C.BDCODPROD)),
                                (SELECT SUM(C.BDBICMS)
                                 FROM VEF_EMP_TC197SAI C
                                 WHERE C.BDCODEMP = D.BDCODEMP AND C.BDCHAVE = D.BDCHAVE AND C.BDCODPROD = D.BDCODPROD
                                   AND D.BDIND_OPER = 1 -- Devolução de compras
                                   AND C.BDCODAJU IN (SELECT A.BDCODAJU_C197
                                                      FROM VEF_BASE_TVINCCODPLANODRCST A
                                                      WHERE A.BDCODPLACONFDRCST = D.BDCODPLACONFDRCST
                                                        AND A.BDCHAVE = D.BDCHAVETROCA)))),
                D.BDVL_ICMS_ST =  IIF(D.BDVL_ICMS_ST > 0, D.BDVL_ICMS_ST,
                                IIF(D.BDIND_OPER = 0,
                                (SELECT SUM(C.BDVLRICMS)
                                 FROM VEF_EMP_TC197ENT C
                                 WHERE C.BDCODEMP = D.BDCODEMP AND C.BDCHAVE = D.BDCHAVE AND C.BDCODPROD = D.BDCODPROD
                                   AND D.BDIND_OPER = 0 -- Compras
                                   AND C.BDCODAJU IN (SELECT A.BDCODAJU_C197
                                                     FROM VEF_BASE_TVINCCODPLANODRCST A
                                                     WHERE A.BDCODPLACONFDRCST = D.BDCODPLACONFDRCST
                                                       AND A.BDCHAVE = D.BDCHAVETROCA)
                                  AND NOT EXISTS (SELECT FIRST 1 M.BDCODEMP
                                                  FROM VEF_EMP_TMOVMVASC M
                                                  WHERE M.BDCODEMP = C.BDCODEMP AND
                                                        M.BDCHAVE = C.BDCHAVE AND
                                                        M.BDCODPROD = C.BDCODPROD)),
                                (SELECT SUM(C.BDVLRICMS)
                                 FROM VEF_EMP_TC197SAI C
                                 WHERE C.BDCODEMP = D.BDCODEMP AND C.BDCHAVE = D.BDCHAVE AND C.BDCODPROD = D.BDCODPROD
                                   AND D.BDIND_OPER = 1 -- Devolução de compras
                                   AND C.BDCODAJU IN (SELECT A.BDCODAJU_C197
                                                      FROM VEF_BASE_TVINCCODPLANODRCST A
                                                      WHERE A.BDCODPLACONFDRCST = D.BDCODPLACONFDRCST
                                                        AND A.BDCHAVE = D.BDCHAVETROCA))))
            WHERE D.BDSESSAO = :PRSESSAO
              AND D.BDCODPLACONFDRCST = :WCODPLACONFDRCST
              AND D.BDCHAVETROCA = :WCHAVE;
    
            UPDATE TMP_VEF_EMP_TDRCST_2130_TEMP D
            SET D.BDVL_BCST_INT = IIF(D.BDVL_BCST_INT > 0, D.BDVL_BCST_INT, D.BDVL_BCST),
                D.BDVL_ICMS = IIF(D.BDVL_ICMS > 0, D.BDVL_ICMS, (D.BDVL_BCST * (D.BDALIQ_ST_E/100)) - D.BDVL_ICMS_ST),
                D.BDCAL_ICMS_ST = IIF(D.BDCAL_ICMS_ST > 0, D.BDCAL_ICMS_ST, D.BDVL_BCST * (D.BDALIQ_ST_E/100))
            WHERE D.BDSESSAO = :PRSESSAO
              AND D.BDCODPLACONFDRCST = :WCODPLACONFDRCST
              AND D.BDCHAVETROCA = :WCHAVE;
          END

        IF (WGERAC197 = 'TRUE') THEN
          BEGIN
            UPDATE TMP_VEF_EMP_TDRCST_2130_TEMP D
            SET D.BDVLRC197 = IIF(D.BDVLRC197 > 0, D.BDVLRC197,
                               (SELECT SUM(M.BDICMSNR)
                                FROM VEF_EMP_TMOVMVASC M
                                WHERE M.BDCODEMP = D.BDCODEMP AND M.BDCHAVE = D.BDCHAVE AND M.BDORDEM = D.BDORDEM AND M.BDCODPROD = D.BDCODPROD
                                  AND D.BDIND_OPER = 0 -- Compras
                                  ))
            WHERE D.BDSESSAO = :PRSESSAO
              AND D.BDCODPLACONFDRCST = :WCODPLACONFDRCST
              AND D.BDCHAVETROCA = :WCHAVE;
          END
      END
    IF (WGERAC197 > 0) THEN
      BEGIN              
        UPDATE TMP_VEF_EMP_TDRCST_2113_TEMP D
        SET D.BDCODAJU_GERAC197 = :WGERAC197,
            D.BDCODOBSC197 = :WCODOBSC197
        WHERE D.BDSESSAO = :PRSESSAO
          AND D.BDCODPLACONFDRCST = :WCODPLACONFDRCST
          AND D.BDCHAVETROCA = :WCHAVE;

        UPDATE TMP_VEF_EMP_TDRCST_2130_TEMP D
        SET D.BDCODAJU_GERAC197 = :WGERAC197,
            D.BDCODOBSC197 = :WCODOBSC197
        WHERE D.BDSESSAO = :PRSESSAO
          AND D.BDCODPLACONFDRCST = :WCODPLACONFDRCST
          AND D.BDCHAVETROCA = :WCHAVE;
      END
  END

  UPDATE TMP_VEF_EMP_TDRCST_2113_TEMP D
  SET D.BDVL_CREDITO_MVA_SN =
      CAST(((SELECT CAST(CAST((SUM(COALESCE(D2130.BDVL_BCST,0)) / SUM(COALESCE(D2130.BDQTDE,0))) AS NUMERIC(15,6)) * d.BDQTDE_IND_S AS NUMERIC(15,6))
        FROM TMP_VEF_EMP_TDRCST_2130_TEMP D2130
        WHERE D2130.BDSESSAO = D.BDSESSAO
          AND D2130.BDCODEMP = D.BDCODEMP
          AND D2130.BDREFERENCIA = D.BDREFERENCIA
          AND D2130.BDCODPROD = D.BDCODPROD)/
          (1 + D.BDMVAAJUSTADA)) AS NUMERIC(15,6)) *
      CAST((D.BDMVASTORIGINAL/100 * D.BDMVARED/100) * ((1 - D.BDALIQINTERESTADUAL/100) / (1 - D.BDALIQINTERNA/100)) * (D.BDALIQINTERNA/100) AS NUMERIC(15,6))
  WHERE D.BDSESSAO = :PRSESSAO
    AND D.BDIND_S = 30 -- Apenas de venda para o SN
    AND D.BDCHAVETROCA > 0 -- Apenas registros que já aplicou o plano
    AND COALESCE(D.BDVL_CREDITO_MVA_SN,0) = 0;
END
^

create or alter procedure SP_APURACAO_DRCST (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date,
    PRCODPLACONFDRCST integer)
as
declare variable WCODEMP integer;
declare variable WREFERENCIA integer;
BEGIN
  WREFERENCIA = CAST((EXTRACT(YEAR FROM :PRDATAINICIO) || LPAD(EXTRACT(MONTH FROM PRDATAINICIO),2,'0')) AS INTEGER);
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(WREFERENCIA);

  DELETE FROM TMP_VEF_EMP_TDRCSTGER_TEMP T
  WHERE (SELECT FIRST 1 UF.BDSIGLAUF
         FROM VW_TEMPRESAS_REF R
         LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = R.BDCODCID)
         LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF)
         WHERE R.BDCODEMP = T.BDCODEMP) <> 'SC'; -- Apenas apura para SC

  DELETE FROM VEF_INCON_TDRCST D
  WHERE EXISTS(SELECT FIRST 1 G.BDCODEMP
               FROM TMP_VEF_EMP_TDRCSTGER_TEMP G
               WHERE G.BDSESSAO = :PRSESSAO AND
                     G.BDCODEMP = D.BDCODEMP AND
                     G.BDREFERENCIA = D.BDREFERENCIA);
                                                          
  --SETORDEMSEQUENCIAL_STR(0);
  FOR
    SELECT DISTINCT T.BDCODEMP
    FROM TMP_VEF_EMP_TDRCSTGER_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO
    INTO WCODEMP DO
  BEGIN
    SETORDEMSEQUENCIAL_STR(:WCODEMP);
  END
     
  DELETE FROM VEF_EMP_TDRCSTGER DRCST
  WHERE EXISTS (SELECT FIRST 1 T.BDCODEMP
                FROM TMP_VEF_EMP_TDRCSTGER_TEMP T
                WHERE T.BDSESSAO = :PRSESSAO
                  AND T.BDCODEMP = DRCST.BDCODEMP
                  AND T.BDREFERENCIA = DRCST.BDREFERENCIA);  

  INSERT INTO VEF_EMP_TDRCSTGER(BDCODEMP, BDREFERENCIA, BDCODCONT)
  SELECT T.BDCODEMP, T.BDREFERENCIA, T.BDCODCONT
  FROM TMP_VEF_EMP_TDRCSTGER_TEMP T
  WHERE T.BDSESSAO = :PRSESSAO;
    

  EXECUTE PROCEDURE SP_APURACAO_DRCST_2113(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);
  EXECUTE PROCEDURE SP_APURACAO_DRCST_2112(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);
  EXECUTE PROCEDURE SP_APURACAO_DRCST_2130(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);
   
  EXECUTE PROCEDURE SP_APURACAO_DRCST_APLICA_ACOES(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);
                                                                                 
  EXECUTE PROCEDURE SP_APURACAO_DRCST_2114(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);       
  EXECUTE PROCEDURE SP_APURACAO_DRCST_2115(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);
  EXECUTE PROCEDURE SP_APURACAO_DRCST_2132(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);
  EXECUTE PROCEDURE SP_APURACAO_DRCST_2133(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);
  EXECUTE PROCEDURE SP_APURACAO_DRCST_2134(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);

  EXECUTE PROCEDURE SP_APURACAO_DRCST_2120(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM,:prCODPLACONFDRCST);
  EXECUTE PROCEDURE SP_APURACAO_DRCST_2121(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM,:prCODPLACONFDRCST);
  EXECUTE PROCEDURE SP_APURACAO_DRCST_2110(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM,:prCODPLACONFDRCST);
  EXECUTE PROCEDURE SP_APURACAO_DRCST_RESUMO(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);
    

  EXECUTE PROCEDURE SP_APURACAO_DRCST_GRAVAR(:PRSESSAO);

  EXECUTE PROCEDURE SP_APURACAO_DRCST_INCONS(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM,:prCODPLACONFDRCST);
                                                                               
  DELETE FROM TMP_VEF_EMP_TDRCSTGER_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TDRCST_RESUMO_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TDRCST_2110_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TDRCST_2112_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TDRCST_2113_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TDRCST_2114_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TDRCST_2115_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TDRCST_2120_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TDRCST_2121_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TDRCST_2130_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TDRCST_2132_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TDRCST_2133_TEMP WHERE BDSESSAO = :PRSESSAO;  
  DELETE FROM TMP_VEF_EMP_TDRCST_2134_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_DRCST_2113ENT_TEMP WHERE BDSESSAO = :PRSESSAO;
END
^

CREATE OR ALTER procedure SP_APURACAO_ADRCST_PR_1110_1120 (
    PRSESSAO integer,
    PRDATAINI date,
    PRDATAFIM date)
as
declare variable WSQL varchar(20000);
declare variable WCODEMP integer;
declare variable WCODCHAVE integer;
declare variable WPARTENQFED DM_BOOLEAN;
declare variable WCODPLANODEV varchar(100);
declare variable WPLANO integer;
declare variable WCONSUFINAL integer;
declare variable WTODASCFOP DM_BOOLEAN;
declare variable WTODASNCM DM_BOOLEAN;
declare variable WTODOSTER DM_BOOLEAN;
declare variable WTODOSPROD DM_BOOLEAN;
declare variable WTODASCST DM_BOOLEAN;
declare variable WCHAVEDEV integer;
BEGIN
  FOR  /* PEGA AS CONFIRUAÇÕES DO PLANO */
    SELECT PLA.BDCODPLANOCONFADRCST,ADRCST.BDCODEMP, PLA.BDCHAVE, PLA.BDPARTENQFED, PLA.BDCONSUFINAL,
    IIF((SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASCFOP,
    IIF((SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASNCM,
    IIF((SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODOSTER,
    IIF((SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODOSPROD,
    IIF((SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASCST
    FROM VEF_BASE_TPLANOACOESCONFADRCST PLA
    LEFT OUTER JOIN TMP_VEF_EMP_TADRCSTGER_TEMP ADRCST ON (ADRCST.BDSESSAO = :PRSESSAO)
    WHERE PLA.BDCODPLANOCONFADRCST = ADRCST.BDCODPLACONFADRCST
    AND PLA.BDCODPROCESSO = 0 /*PROCESSO ENTRADAS*/
    INTO :WPLANO,:WCODEMP, :WCODCHAVE, :WPARTENQFED, :WCONSUFINAL, :WTODASCFOP, :WTODASNCM, :WTODOSTER, :WTODOSPROD, :WTODASCST
  DO
    BEGIN

        WSQL =        ' INSERT INTO TMP_VEF_EMP_TADRCST_1100_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, ';
        WSQL = WSQL|| ' BDRESPRETICMSST, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT, BDBCICMSST, BDVLRICMSTTSUPENT, BDTIPONFE, BDCHAVENFE) ';
        WSQL = WSQL|| ' SELECT SAIT.BDSESSAO, ENT.BDCODEMP, ENT.BDREFLAN, SAIT.BDCODPROD, ENT.BDCHAVE, /*SAIT*/PRO.BDORDEM, PRO.BDORDEMPRO, ENT.BDDATAEMISSAO, ';
        WSQL = WSQL|| ' IIF(ENTO.BDBCST > 0 OR ENTO.BDBCFCPRETIDO > 0 OR ENTO.BDBCICMSSTRET > 0 OR ENTO.BDBCFCPSTRET > 0, IIF(ENTO.BDBCST > 0 OR ENTO.BDBCFCPRETIDO > 0, 1, 2), ';
        WSQL = WSQL|| '     IIF(PRO.BDBCST > 0 OR PRO.BDBCFCPRETIDO > 0 OR PRO.BDBCICMSSTRET > 0 OR PRO.BDBCFCPSTRET > 0, IIF(PRO.BDBCST > 0 OR PRO.BDBCFCPRETIDO > 0, 1, 2), ';
        WSQL = WSQL|| '        IIF(COALESCE(MVA.BDVLRICMSST, 0) > 0, 3, 0) ';
        WSQL = WSQL|| '     ) ';
        WSQL = WSQL|| ' ) BDRESPRETICMSST, ';
        WSQL = WSQL|| ' COALESCE(ICMSO.BDCODCSTICMS,ICMS.BDCODCSTICMS) BDCSTICMS, ENT.BDNUMDOCINI,  TER.BDCGCTER, UFT.BDSIGLAUF,EMP.BDCNPJEMP, UF.BDSIGLAUF, ';
        WSQL = WSQL|| ' COALESCE(ENTO.BDCODNAT,I.BDCODNAT) BDCODNAT, COALESCE(UNMF.BDAPEUNIMED, UNMP.BDAPEUNIMED) BDUNIDMED, PRO.BDQTDITEM, ';
        WSQL = WSQL|| ' ((PRO.BDVLRITEM - PRO.BDVLRDESC) / PRO.BDQTDITEM) BDVLRUNIT, ';
        WSQL = WSQL|| ' ((coalesce(PRO.BDBCST,0) + coalesce(PRO.BDBCFCPRETIDO,0) + coalesce(PRO.BDBCICMSSTRET,0) + coalesce(PRO.BDBCFCPSTRET,0) + coalesce(MVA.BDVLRICMSST, 0))/PRO.BDQTDITEM) BDBCICMSST, ';
        WSQL = WSQL|| ' (COALESCE(PRO.BDVLRICMS,0) + COALESCE(PRO.BDVLRST,0) + COALESCE(PRO.BDFCPRETIDO,0) + COALESCE(PRO.BDVLRICMSSTRET,0) + COALESCE(PRO.BDVLRFCPSTRET,0) + COALESCE(MVA.BDVLRICMSSTNAORET,0)) BDVLRICMSTTSUPENT, 0, (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(ENT.BDCHAVENFE)) BDCHAVENFE ';
        WSQL = WSQL|| ' FROM ( ';
             WSQL = WSQL|| ' SELECT T1000.BDCODEMP, T1000.BDSESSAO, T1000.BDCODPROD, T1000.BDREFERENCIA, ';
             WSQL = WSQL|| ' T1000.BDCODUNIMED, T1000.BDNCMPROD ';
             --WSQL = WSQL|| ' , PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO ';
             WSQL = WSQL|| ' FROM TMP_VEF_EMP_TADRCST_1000_TEMP T1000 ';
             --WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = T1000.BDCODEMP AND PRO.BDCODPROD = T1000.BDCODPROD) '; Alt.: #243271 - Alterado o select para primeiro buscar as notas, e s? depois verificar os produtos...
             WSQL = WSQL|| ' WHERE T1000.BDSESSAO = '|| :PRSESSAO||' AND ';
             WSQL = WSQL|| ' T1000.BDCODEMP = '||:WCODEMP;
             WSQL = WSQL|| ' GROUP BY T1000.BDCODEMP, T1000.BDSESSAO, T1000.BDCODPROD, T1000.BDREFERENCIA, T1000.BDCODUNIMED, T1000.BDNCMPROD ';
             --WSQL = WSQL|| ' , PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO ';
        WSQL = WSQL|| ' ) SAIT ';
        --WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = SAIT.BDCODEMP AND PRO.BDCHAVE = SAIT.BDCHAVE AND PRO.BDORDEM = SAIT.BDORDEM AND PRO.BDORDEMPRO = SAIT.BDORDEMPRO) ';
        WSQL = WSQL|| ' JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = SAIT.BDCODEMP AND ';--ENT.BDCHAVE = SAIT.BDCHAVE) ';
        WSQL = WSQL||                              ' ENT.BDMODELO = 55 AND ';
        WSQL = WSQL||                              ' ENT.BDDATAEMISSAO BETWEEN '''||:PRDATAINI||''' AND '''||:PRDATAFIM||''' AND ';
        IF (:WCONSUFINAL = 1) THEN
           WSQL = WSQL||                           ' COALESCE(ENT.BDCONSUFINAL,0) = '||:WCONSUFINAL||' AND ';
        ELSE
           WSQL = WSQL||                           ' COALESCE(ENT.BDCONSUFINAL,0) IN (-1,0) AND ';
        WSQL = WSQL||                              ' ENT.BDCODSITNF NOT IN (2,3,4,5) ) ';

        WSQL = WSQL|| ' JOIN VEF_EMP_TMOVENTITENS I on (I.BDCODEMP = ENT.BDCODEMP and I.BDCHAVE = ENT.BDCHAVE) ';
        WSQL = WSQL|| ' JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM AND PRO.BDCODPROD = SAIT.BDCODPROD) ';

        WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROENTIMPORI ENTO ON (ENTO.BDCODEMP = ENT.BDCODEMP AND ENTO.BDCODPROD = SAIT.BDCODPROD AND ENTO.BDCHAVE = ENT.BDCHAVE AND ENTO.BDORDEM = /*SAIT*/PRO.BDORDEM AND ENTO.bdordemhist = /*SAIT*/PRO.BDORDEMPRO) ';
        WSQL = WSQL|| 'LEFT OUTER JOIN (SELECT MVA.BDCODEMP,MVA.BDCHAVE,MVA.BDORDEM,MVA.BDCODPROD, ';
        WSQL = WSQL||                         'SUM(MVA.BDVLRICMSST)BDVLRICMSST,SUM(MVA.BDVLRICMSSTNAORET)BDVLRICMSSTNAORET ';
        WSQL = WSQL||                  'FROM VEF_EMP_TMOVMVAPR MVA ';
        WSQL = WSQL||                  'GROUP BY MVA.BDCODEMP,MVA.BDCHAVE,MVA.BDORDEM,MVA.BDCODPROD) MVA  ON (MVA.BDCODEMP = SAIT.BDCODEMP AND MVA.BDCHAVE = /*SAIT*/PRO.BDCHAVE AND MVA.BDORDEM = /*SAIT*/PRO.BDORDEM AND MVA.BDCODPROD = SAIT.BDCODPROD) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN TCADPRO CPRO ON (CPRO.BDCODPROD = ENTO.BDCODPROD) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = SAIT.BDCODEMP AND VINC.BDCODPROD = ENTO.BDCODPROD) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = ENT.BDCODTER) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMSO ON (ICMSO.BDCODCSTICMS = ENTO.BDCODCSTICMS) ';
        --WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE AND I.BDORDEM = PRO.BDORDEM) ';
        --WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = ENT.BDCODEMP AND C113.BDCHAVE = ENT.BDCHAVE AND (SELECT BDAAAAMM FROM AAAAMM(C113.BDDTEMISSAO)) = SAIT.BDREFERENCIA) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT) ';
        WSQL = WSQL|| ' JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = ENT.BDCODEMP) ';
        WSQL = WSQL|| ' JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID) ';
        WSQL = WSQL|| ' JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF) ';
        WSQL = WSQL|| ' JOIN TCIDADE CIDT ON (CIDT.BDCODCID = TER.BDCODCID) ';
        WSQL = WSQL|| ' JOIN TUF UFT ON (UFT.BDCODUF = CIDT.BDCODUF) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODEMP = ENT.BDCODEMP AND FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMF ON (UNMF.BDCODUNIMED = FAT.BDCODUNIMED) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMP ON (UNMP.BDCODUNIMED = SAIT.BDCODUNIMED) ';
        --WSQL = WSQL|| ' WHERE ENT.BDMODELO = 55 ';
        WSQL = WSQL|| ' WHERE NAT.BDDEVOL = ''FALSE'' AND ';
        --WSQL = WSQL|| ' AND ENT.BDDATAEMISSAO BETWEEN '''||:PRDATAINI||''' AND '''||:PRDATAFIM||'''';
        --IF (:WCONSUFINAL = 1) THEN
        --   WSQL = WSQL|| ' AND COALESCE(ENT.BDCONSUFINAL,0) = '|| :WCONSUFINAL;
        --ELSE
        --   WSQL = WSQL|| ' AND COALESCE(ENT.BDCONSUFINAL,0) IN (-1,0) ';
        --WSQL = WSQL|| ' AND ENT.BDCODSITNF NOT IN (2,3,4,5) AND ';
      --  WSQL = WSQL|| ' ENT.BDREFLAN = (SELECT MAX(ENTR.BDREFLAN) FROM VEF_EMP_TMOVENT ENTR WHERE ENTR.BDCODEMP = SAIT.BDCODEMP) AND ';
        WSQL = WSQL|| ' (ENTO.BDBCST > 0 OR ENTO.BDBCFCPSTRET > 0 OR ENTO.BDBCFCPRETIDO > 0 OR ENTO.BDBCICMSSTRET > 0 OR ';
        WSQL = WSQL|| ' PRO.BDBCST > 0 OR PRO.BDBCFCPSTRET > 0 OR PRO.BDBCFCPRETIDO > 0 OR PRO.BDBCICMSSTRET > 0 OR PRO.BDVLRST > 0 OR PRO.BDVLRFCPSTRET > 0 OR PRO.BDVLRFCP > 0 OR PRO.BDVLRICMSSTRET > 0 OR MVA.BDVLRICMSST > 0 OR MVA.BDVLRICMSSTNAORET > 0) ';
        WSQL = WSQL|| ' AND NOT EXISTS (SELECT BDCODEMP FROM TMP_VEF_EMP_TADRCST_1100_TEMP T WHERE T.BDSESSAO = SAIT.BDSESSAO AND T.BDCODEMP = ENT.BDCODEMP AND T.BDCHAVE = ENT.BDCHAVE AND T.BDORDEM = /*SAIT*/PRO.BDORDEM AND PRO.BDORDEMPRO = T.BDORDEMPROD)';

         IF (:WPARTENQFED = 'TRUE' ) THEN
            WSQL = WSQL|| ' AND (TER.BDENQSIMPLESFEDTER = 2)';
         ELSE IF (:WTODOSTER = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODTER = ENT.BDCODTER) ';
    
         IF (:WTODASCFOP = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNAT = I.BDCODNAT) ';
         IF (:WTODASNCM = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNCM = SAIT.BDNCMPROD) ';
         IF (:WTODOSPROD = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODPROD = PRO.BDCODPROD) ';
         IF (:WTODASCST = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCSTICMS = PRO.BDCODCSTICMS) ';

        EXECUTE STATEMENT(WSQL);
    END

  FOR  /*PEGA AS CONFIRUAÇÕES DO PLANO DE DEVOLUÇÃO*/
    SELECT PLA.BDCODPLANOCONFADRCST,ADRCST.BDCODEMP, PLA.BDCHAVE, PLA.BDPARTENQFED, PLA.BDCONSUFINAL,
    IIF((SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASCFOP,
    IIF((SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASNCM,
    IIF((SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODOSTER,
    IIF((SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODOSPROD,
    IIF((SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASCST
    FROM VEF_BASE_TPLANOACOESCONFADRCST PLA
    LEFT OUTER JOIN TMP_VEF_EMP_TADRCSTGER_TEMP ADRCST ON (ADRCST.BDSESSAO = :PRSESSAO)
    WHERE PLA.BDCODPLANOCONFADRCST = ADRCST.BDCODPLACONFADRCST
    AND PLA.BDCODPROCESSO = 1 /*PROCESSO DE DEVOLUÇÃO*/
    INTO :WPLANO,:WCODEMP, :WCODCHAVE, :WPARTENQFED, :WCONSUFINAL, :WTODASCFOP, :WTODASNCM, :WTODOSTER, :WTODOSPROD, :WTODASCST
  DO
    BEGIN

        WSQL =        ' INSERT INTO TMP_VEF_EMP_TADRCST_1100_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, ';
        WSQL = WSQL|| ' /*BDRESPRETICMSST,*/ BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT,  ';
        WSQL = WSQL|| ' BDBCICMSST, BDVLRICMSTTSUPENT,BDCHAVENFEREFC113,BDNUMITEMREFC113,BDCODINCONSISTENCIA, BDTIPONFE, BDCHAVENFE) ';
        WSQL = WSQL|| ' SELECT T1000.BDSESSAO, SAI.BDCODEMP, SAI.BDREFLAN, T1000.BDCODPROD, SAI.BDCHAVE, T1000.BDORDEM, PRO.BDORDEMPRO, SAI.BDDATAEMISSAO, ';

        WSQL = WSQL|| ' ICMS.BDCODCSTICMS, SAI.BDNUMDOCINI, EMP.BDCNPJEMP, UF.BDSIGLAUF, TER.BDCGCTER, UFT.BDSIGLAUF, ';
        WSQL = WSQL|| ' I.BDCODNAT BDCODNAT, COALESCE(UNMF.BDAPEUNIMED, UNMP.BDAPEUNIMED) BDUNIDMED, PRO.BDQTDITEM, ';
        WSQL = WSQL|| ' ((PRO.BDVLRITEM - PRO.BDVLRDESC) / PRO.BDQTDITEM) BDVLRUNIT,  ';
        WSQL = WSQL|| ' (coalesce(PRO.BDBCST,0) + coalesce(PRO.BDBCFCPRETIDO,0) + coalesce(PRO.BDBCICMSSTRET,0) + coalesce(PRO.BDBCFCPSTRET,0)) BDBCICMSST, ';
        WSQL = WSQL|| ' (COALESCE(PRO.BDVLRICMS,0) + COALESCE(PRO.BDVLRST,0) + COALESCE(PRO.BDFCPRETIDO,0) + COALESCE(PRO.BDVLRICMSSTRET,0) + COALESCE(PRO.BDVLRFCPSTRET,0)) BDVLRICMSTTSUPENT,';
        WSQL = WSQL|| ' (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) BDCHAVENFEC113,PROREF.BDORDEMPRO,IIF(C113.BDCODEMP IS NULL, 20,IIF((C113.BDCODEMP IS NOT NULL) AND (select BDAAAAMM FROM AAAAMM(C113.bddtemissao)) <> (select BDAAAAMM FROM AAAAMM('''||:PRDATAINI||''')),23,NULL)) BDINCO,1, (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(SAI.BDCHAVENFE)) BDCHAVENFE ';
        WSQL = WSQL|| ' FROM ( ';
                WSQL = WSQL|| 'SELECT * ';
                WSQL = WSQL|| ' FROM TMP_VEF_EMP_TADRCST_1000_TEMP T1000 ';
                WSQL = WSQL|| ' WHERE T1000.BDSESSAO = '||:PRSESSAO||' AND ';
                WSQL = WSQL|| ' T1000.BDCODEMP = '||:WCODEMP||') T1000 ';
        WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (T1000.BDCODEMP = SAI.BDCODEMP AND T1000.BDCHAVE = SAI.BDCHAVE) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = T1000.BDORDEM AND PRO.BDORDEMPRO = T1000.BDORDEMPROD) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = SAI.BDCODTER) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS) ';
        WSQL = WSQL|| ' JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = SAI.BDCODEMP) ';
        WSQL = WSQL|| ' JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID) ';
        WSQL = WSQL|| ' JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF) ';
        WSQL = WSQL|| ' JOIN TCIDADE CIDT ON (CIDT.BDCODCID = TER.BDCODCID) ';
        WSQL = WSQL|| ' JOIN TUF UFT ON (UFT.BDCODUF = CIDT.BDCODUF) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODEMP = SAI.BDCODEMP AND FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMF ON (UNMF.BDCODUNIMED = FAT.BDCODUNIMED) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMP ON (UNMP.BDCODUNIMED = T1000.BDCODUNIMED) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVSAIDOCFREF C113 ON (C113.BDCODEMP = SAI.BDCODEMP AND C113.BDCHAVE = SAI.BDCHAVE /*AND (SELECT BDAAAAMM FROM AAAAMM(C113.BDDTEMISSAO)) = T1000.BDREFERENCIA*/) ';
        --WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = C113.BDCODEMP /*AND ENT.BDREFLAN = SAI.BDREFLAN*/) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = C113.BDCODEMP /*AND ENT.BDREFLAN = SAI.BDREFLAN*/ AND ';
        WSQL = WSQL|| '                                         ((ENT.BDNUMDOCINI = C113.BDNUMDOC AND ';
        WSQL = WSQL|| '                                           ENT.BDDATAEMISSAO = C113.BDDTEMISSAO AND ';
        WSQL = WSQL|| '                                          COALESCE(ENT.BDCHAVENFE, 0) = IIF((SELECT BDNUMERO ';
        WSQL = WSQL|| '                                                                            FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '''', 0, C113.BDCHAVENFE) ';
        WSQL = WSQL|| '                                          ) ) ) ';

        WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROENT PROREF ON (PROREF.BDCODEMP = ENT.BDCODEMP AND PROREF.BDCHAVE = ENT.BDCHAVE AND PROREF.BDCODPROD = PRO.BDCODPROD) ';
        WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT) ';
        WSQL = WSQL|| ' WHERE SAI.BDMODELO = 55  ';
        WSQL = WSQL|| ' AND NAT.BDDEVOL = ''TRUE'' ';
        IF (:WCONSUFINAL = 1) THEN
           WSQL = WSQL|| ' AND COALESCE(SAI.BDCONSUFINAL,0) = '|| :WCONSUFINAL;
        ELSE
           WSQL = WSQL|| ' AND COALESCE(SAI.BDCONSUFINAL,0) IN (-1,0) ';
        WSQL = WSQL|| ' AND SAI.BDDATAEMISSAO BETWEEN '''||:PRDATAINI||''' AND '''||:PRDATAFIM||'''';
        WSQL = WSQL|| ' AND    SAI.BDCODSITNF NOT IN (2, 3, 4, 5) ';
        --WSQL = WSQL|| ' AND ((ENT.BDNUMDOCINI = C113.BDNUMDOC AND COALESCE(ENT.BDCHAVENFE,0) = IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '''', 0, C113.BDCHAVENFE) ';
        --WSQL = WSQL|| ' AND ENT.BDDATAEMISSAO = C113.BDDTEMISSAO) OR (C113.bdcodemp IS NULL))';
        WSQL = WSQL|| ' AND NOT EXISTS (SELECT BDCODEMP FROM TMP_VEF_EMP_TADRCST_1100_TEMP T WHERE T.BDSESSAO = T1000.BDSESSAO AND T.BDCODEMP = T1000.BDCODEMP AND T.BDCHAVE = SAI.BDCHAVE AND T.BDORDEM = T1000.BDORDEM AND PRO.BDORDEMPRO = T.BDORDEMPROD)';

        IF (:WTODOSTER = 'FALSE') THEN
           WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODTER = SAI.BDCODTER) ';
    
        IF (:WTODASCFOP = 'FALSE') THEN
           WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNAT = I.BDCODNAT) ';
        IF (:WTODASNCM = 'FALSE') THEN
           WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNCM = T1000.BDNCMPROD) ';
        IF (:WTODOSPROD = 'FALSE') THEN
           WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODPROD = PRO.BDCODPROD) ';
        IF (:WTODASCST = 'FALSE') THEN
           WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCSTICMS = PRO.BDCODCSTICMS) ';

      EXECUTE STATEMENT(WSQL);
    END

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_ADRCST_RESUMO (
    PRSESSAO INTEGER,
    PRDATAINICIO DATE,
    PRDATAFIM DATE)
AS
BEGIN
  /*Campo 01 - X02 - Valor a recuperar ou a ressarcir nas saídas para consumidor final*/
  INSERT INTO VEF_EMP_TADRCST_RESUMO (BDCODEMP, BDREFERENCIA, BDCAMPO,BDVALOR)
  SELECT T1200.BDCODEMP,T1200.BDREFERENCIA,1, IIF((BDVLRICMSSTRECUPERAR - BDVLRICMSSTCOMPLEMENTAR) < 0, 0,(BDVLRICMSSTRECUPERAR - BDVLRICMSSTCOMPLEMENTAR)) BDVALOR
  FROM (
        SELECT TREG.BDCODEMP,TREG.BDREFERENCIA,
               SUM(COALESCE(T1200.BDVLRICMSSTRECUPERAR,0)) BDVLRICMSSTRECUPERAR, SUM(COALESCE(T1200.BDVLRICMSSTCOMPLEMENTAR,0)) BDVLRICMSSTCOMPLEMENTAR
               /* Alt.: #184536
               IIF(SUM(COALESCE(T1200.BDVLRICMSSTRECUPERAR,0)) = 0 AND SUM(COALESCE(T1200.BDVLRICMSSTCOMPLEMENTAR,0)) = 0,
                   SUM(COALESCE(T1200.BDVLRCONFICMSENT,0)), SUM(COALESCE(T1200.BDVLRICMSSTRECUPERAR,0))) BDVLRICMSSTRECUPERAR,
               IIF(SUM(COALESCE(T1200.BDVLRICMSSTRECUPERAR,0)) = 0 AND SUM(COALESCE(T1200.BDVLRICMSSTCOMPLEMENTAR,0)) = 0,
                   SUM(COALESCE(T1200.BDTTVLRICMSEFETIVO,0)), SUM(COALESCE(T1200.BDVLRICMSSTCOMPLEMENTAR,0))) BDVLRICMSSTCOMPLEMENTAR*/
        FROM TMP_VEF_EMP_TADRCSTGER_TEMP TREG
        LEFT OUTER JOIN VEF_EMP_TADRCST_1200 T1200 ON (T1200.BDCODEMP = TREG.BDCODEMP AND T1200.BDREFERENCIA = TREG.BDREFERENCIA)
        WHERE TREG.BDSESSAO = :PRSESSAO
        GROUP BY TREG.BDCODEMP,TREG.BDREFERENCIA
        ) T1200;

  /*Campo 02 - X03 - Valor a complementar nas saídas para consumidor final*/
  INSERT INTO VEF_EMP_TADRCST_RESUMO (BDCODEMP, BDREFERENCIA, BDCAMPO,BDVALOR)
  SELECT T1200.BDCODEMP,T1200.BDREFERENCIA,2, IIF((BDVLRICMSSTRECUPERAR - BDVLRICMSSTCOMPLEMENTAR) > 0, 0,((BDVLRICMSSTRECUPERAR - BDVLRICMSSTCOMPLEMENTAR) * -1)) BDVALOR
  FROM (
        SELECT TREG.BDCODEMP,TREG.BDREFERENCIA,
               SUM(COALESCE(T1200.BDVLRICMSSTRECUPERAR,0)) BDVLRICMSSTRECUPERAR, SUM(COALESCE(T1200.BDVLRICMSSTCOMPLEMENTAR,0)) BDVLRICMSSTCOMPLEMENTAR
               /* Alt.: #184536
               IIF(SUM(COALESCE(T1200.BDVLRICMSSTRECUPERAR,0)) = 0 AND SUM(COALESCE(T1200.BDVLRICMSSTCOMPLEMENTAR,0)) = 0,
                   SUM(COALESCE(T1200.BDVLRCONFICMSENT,0)), SUM(COALESCE(T1200.BDVLRICMSSTRECUPERAR,0))) BDVLRICMSSTRECUPERAR,
               IIF(SUM(COALESCE(T1200.BDVLRICMSSTRECUPERAR,0)) = 0 AND SUM(COALESCE(T1200.BDVLRICMSSTCOMPLEMENTAR,0)) = 0,
                   SUM(COALESCE(T1200.BDTTVLRICMSEFETIVO,0)), SUM(COALESCE(T1200.BDVLRICMSSTCOMPLEMENTAR,0))) BDVLRICMSSTCOMPLEMENTAR*/
        FROM TMP_VEF_EMP_TADRCSTGER_TEMP TREG
        LEFT OUTER JOIN VEF_EMP_TADRCST_1200 T1200 ON (T1200.BDCODEMP = TREG.BDCODEMP AND T1200.BDREFERENCIA = TREG.BDREFERENCIA)
        WHERE TREG.BDSESSAO = :PRSESSAO
        GROUP BY TREG.BDCODEMP,TREG.BDREFERENCIA
        ) T1200;

  /*Campo 03 - X04 - Valor a recuperar ou a ressarcir nas saídas para outros estados*/
  INSERT INTO VEF_EMP_TADRCST_RESUMO (BDCODEMP, BDREFERENCIA, BDCAMPO,BDVALOR)
  SELECT TREG.BDCODEMP,TREG.BDREFERENCIA,3, SUM(COALESCE(T1300.BDVLRICMSSTRECUPERAR,0)) BDVLRICMSSTRECUPERAR
  FROM TMP_VEF_EMP_TADRCSTGER_TEMP TREG
  LEFT OUTER  JOIN VEF_EMP_TADRCST_1300 T1300 ON (T1300.BDCODEMP = TREG.BDCODEMP AND T1300.BDREFERENCIA = TREG.BDREFERENCIA)
  WHERE TREG.BDSESSAO = :PRSESSAO
  GROUP BY TREG.BDCODEMP,TREG.BDREFERENCIA;

  /*Campo 04 - X05 - Valor a recuperar ou a ressarcir nas saídas de que trata o art. 119*/
  INSERT INTO VEF_EMP_TADRCST_RESUMO (BDCODEMP, BDREFERENCIA, BDCAMPO,BDVALOR)
  SELECT TREG.BDCODEMP,TREG.BDREFERENCIA,4, SUM(COALESCE(T1400.BDVLRICMSRECUPERAR,0)) BDVLRICMSRECUPERAR
  FROM TMP_VEF_EMP_TADRCSTGER_TEMP TREG
  LEFT OUTER  JOIN VEF_EMP_TADRCST_1400 T1400 ON (T1400.BDCODEMP = TREG.BDCODEMP AND T1400.BDREFERENCIA = TREG.BDREFERENCIA)
  WHERE TREG.BDSESSAO = :PRSESSAO
  GROUP BY TREG.BDCODEMP,TREG.BDREFERENCIA;

  /*Campo 05 - X06 - Valor a recuperar ou a ressarcir nas saídas destinadas a contribuinte do Simples Nacional*/
  INSERT INTO VEF_EMP_TADRCST_RESUMO (BDCODEMP, BDREFERENCIA, BDCAMPO,BDVALOR)
  SELECT TREG.BDCODEMP,TREG.BDREFERENCIA,5, SUM(COALESCE(T1500.BDVLRICMSSTRECUPERAR,0)) BDVLRICMSSTRECUPERAR
  FROM TMP_VEF_EMP_TADRCSTGER_TEMP TREG
  LEFT OUTER  JOIN VEF_EMP_TADRCST_1500 T1500 ON (T1500.BDCODEMP = TREG.BDCODEMP AND T1500.BDREFERENCIA = TREG.BDREFERENCIA)
  WHERE TREG.BDSESSAO = :PRSESSAO
  GROUP BY TREG.BDCODEMP,TREG.BDREFERENCIA;

  /*Campo 06 - X07 - Valor a ressarcir do FECOP*/
  INSERT INTO VEF_EMP_TADRCST_RESUMO (BDCODEMP, BDREFERENCIA, BDCAMPO,BDVALOR)
  SELECT BDCODEMP,BDREFERENCIA,6, IIF((SUM(BDVLRFCPRECUPER) - (SUM(BDVLRFCPCOMPLEMENTAR))) < 0,0,(SUM(BDVLRFCPRECUPER) - (SUM(BDVLRFCPCOMPLEMENTAR))))
  FROM(
        SELECT TREG.BDCODEMP, TREG.BDREFERENCIA, SUM(COALESCE(T1200.BDVLRFCPRECUPER, 0)) BDVLRFCPRECUPER,
        SUM(COALESCE(T1200.BDVLRFCPCOMPLEMENTAR, 0)) BDVLRFCPCOMPLEMENTAR
        FROM TMP_VEF_EMP_TADRCSTGER_TEMP TREG
        LEFT OUTER JOIN VEF_EMP_TADRCST_1200 T1200 ON (T1200.BDCODEMP = TREG.BDCODEMP AND T1200.BDREFERENCIA = TREG.BDREFERENCIA)
        WHERE TREG.BDSESSAO = :PRSESSAO
        GROUP BY TREG.BDCODEMP, TREG.BDREFERENCIA
        UNION ALL
        SELECT TREG.BDCODEMP, TREG.BDREFERENCIA,SUM(COALESCE(T1300.BDVLRFCPRECUPER, 0)) BDVLRFCPRECUPER,0 BDVLRFCPCOMPLEMENTAR
        FROM TMP_VEF_EMP_TADRCSTGER_TEMP TREG
        LEFT OUTER JOIN VEF_EMP_TADRCST_1300 T1300 ON (T1300.BDCODEMP = TREG.BDCODEMP AND T1300.BDREFERENCIA = TREG.BDREFERENCIA)
        WHERE TREG.BDSESSAO = :PRSESSAO
        GROUP BY TREG.BDCODEMP, TREG.BDREFERENCIA 
       )
  GROUP BY BDCODEMP,BDREFERENCIA;

  /*Campo 07 - X08 - Valor a complementar do FECOP*/
  INSERT INTO VEF_EMP_TADRCST_RESUMO (BDCODEMP, BDREFERENCIA, BDCAMPO,BDVALOR)
  SELECT BDCODEMP,BDREFERENCIA,7, IIF((SUM(BDVLRFCPRECUPER) - (SUM(BDVLRFCPCOMPLEMENTAR))) > 0,0,((SUM(BDVLRFCPRECUPER) - (SUM(BDVLRFCPCOMPLEMENTAR)))*-1))
  FROM(
        SELECT TREG.BDCODEMP, TREG.BDREFERENCIA, SUM(COALESCE(T1200.BDVLRFCPRECUPER, 0)) BDVLRFCPRECUPER,
        SUM(COALESCE(T1200.BDVLRFCPCOMPLEMENTAR, 0)) BDVLRFCPCOMPLEMENTAR
        FROM TMP_VEF_EMP_TADRCSTGER_TEMP TREG
        LEFT OUTER JOIN VEF_EMP_TADRCST_1200 T1200 ON (T1200.BDCODEMP = TREG.BDCODEMP AND T1200.BDREFERENCIA = TREG.BDREFERENCIA)
        WHERE TREG.BDSESSAO = :PRSESSAO
        GROUP BY TREG.BDCODEMP, TREG.BDREFERENCIA
        UNION ALL
        SELECT TREG.BDCODEMP, TREG.BDREFERENCIA,SUM(COALESCE(T1300.BDVLRFCPRECUPER, 0)) BDVLRFCPRECUPER,0 BDVLRFCPCOMPLEMENTAR
        FROM TMP_VEF_EMP_TADRCSTGER_TEMP TREG
        LEFT OUTER JOIN VEF_EMP_TADRCST_1300 T1300 ON (T1300.BDCODEMP = TREG.BDCODEMP AND T1300.BDREFERENCIA = TREG.BDREFERENCIA)
        WHERE TREG.BDSESSAO = :PRSESSAO
        GROUP BY TREG.BDCODEMP, TREG.BDREFERENCIA 
       )
  GROUP BY BDCODEMP,BDREFERENCIA;

  /*Campo 08 - Total a Complementar*/
  INSERT INTO VEF_EMP_TADRCST_RESUMO (BDCODEMP, BDREFERENCIA, BDCAMPO,BDVALOR)
  SELECT TRES.BDCODEMP,TRES.BDREFERENCIA,8, IIF(TRES.BDVALOR < 0,0,TRES.BDVALOR) BDVALOR
  FROM(
      SELECT TRES.BDCODEMP,TRES.BDREFERENCIA,((SUM(BDCAMPO2)+SUM(BDCAMPO7))-(SUM(BDCAMPO1)+SUM(BDCAMPO3)+SUM(BDCAMPO4)+SUM(BDCAMPO5)+SUM(BDCAMPO6))) BDVALOR
      FROM (
            SELECT TRES.BDCODEMP,TRES.BDREFERENCIA, IIF(TRES.BDCAMPO = 1,TRES.BDVALOR,0) BDCAMPO1, IIF(TRES.BDCAMPO = 2,TRES.BDVALOR,0) BDCAMPO2,
            IIF(TRES.BDCAMPO = 3,TRES.BDVALOR,0) BDCAMPO3,IIF(TRES.BDCAMPO = 4,TRES.BDVALOR,0) BDCAMPO4,IIF(TRES.BDCAMPO = 5,TRES.BDVALOR,0) BDCAMPO5,
            IIF(TRES.BDCAMPO = 6,TRES.BDVALOR,0) BDCAMPO6,IIF(TRES.BDCAMPO = 7,TRES.BDVALOR,0) BDCAMPO7
            FROM(
                SELECT TREG.BDCODEMP, TREG.BDREFERENCIA
                FROM TMP_VEF_EMP_TADRCSTGER_TEMP TREG
                WHERE TREG.BDSESSAO = :PRSESSAO
                )  TREG
            LEFT OUTER JOIN VEF_EMP_TADRCST_RESUMO TRES ON (TRES.BDCODEMP = TREG.BDCODEMP AND TRES.BDREFERENCIA = TREG.BDREFERENCIA)
            ) TRES
        GROUP BY TRES.BDCODEMP,TRES.BDREFERENCIA
       ) TRES;

  /*Campo 09 - Total a recuperar/ressarcir*/
  INSERT INTO VEF_EMP_TADRCST_RESUMO (BDCODEMP, BDREFERENCIA, BDCAMPO,BDVALOR)
  SELECT TRES.BDCODEMP,TRES.BDREFERENCIA,9, IIF(TRES.BDVALOR < 0,0,TRES.BDVALOR) BDVALOR
  FROM(
      SELECT TRES.BDCODEMP,TRES.BDREFERENCIA,((SUM(BDCAMPO1)+SUM(BDCAMPO3)+SUM(BDCAMPO4)+SUM(BDCAMPO5)+SUM(BDCAMPO6))-(SUM(BDCAMPO2)+SUM(BDCAMPO7))) BDVALOR
      FROM (
            SELECT TRES.BDCODEMP,TRES.BDREFERENCIA, IIF(TRES.BDCAMPO = 1,TRES.BDVALOR,0) BDCAMPO1, IIF(TRES.BDCAMPO = 2,TRES.BDVALOR,0) BDCAMPO2,
            IIF(TRES.BDCAMPO = 3,TRES.BDVALOR,0) BDCAMPO3,IIF(TRES.BDCAMPO = 4,TRES.BDVALOR,0) BDCAMPO4,IIF(TRES.BDCAMPO = 5,TRES.BDVALOR,0) BDCAMPO5,
            IIF(TRES.BDCAMPO = 6,TRES.BDVALOR,0) BDCAMPO6,IIF(TRES.BDCAMPO = 7,TRES.BDVALOR,0) BDCAMPO7
            FROM(
                SELECT TREG.BDCODEMP, TREG.BDREFERENCIA
                FROM TMP_VEF_EMP_TADRCSTGER_TEMP TREG
                WHERE TREG.BDSESSAO = :PRSESSAO
                )  TREG
            LEFT OUTER JOIN VEF_EMP_TADRCST_RESUMO TRES ON (TRES.BDCODEMP = TREG.BDCODEMP AND TRES.BDREFERENCIA = TREG.BDREFERENCIA)
            ) TRES
        GROUP BY TRES.BDCODEMP,TRES.BDREFERENCIA
       ) TRES;
END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_ADRCST_PR_VERIF_ENT (
    PRSESSAO INTEGER,
    PRDATAINI DATE,
    PRDATAFIM DATE)
AS
DECLARE VARIABLE WSQL VARCHAR(20000);
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODCHAVE INTEGER;
DECLARE VARIABLE WPARTENQFED DM_BOOLEAN;
DECLARE VARIABLE WCODPLANODEV VARCHAR(100);
DECLARE VARIABLE WPLANO INTEGER;
DECLARE VARIABLE WCONSUFINAL INTEGER;
DECLARE VARIABLE WTODASCFOP DM_BOOLEAN;
DECLARE VARIABLE WTODASNCM DM_BOOLEAN;
DECLARE VARIABLE WTODOSTER DM_BOOLEAN;
DECLARE VARIABLE WTODOSPROD DM_BOOLEAN;
DECLARE VARIABLE WTODASCST DM_BOOLEAN;
DECLARE VARIABLE WCHAVEDEV INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WQTDFALTANTE INTEGER;
DECLARE VARIABLE WREF12MESES INTEGER;
DECLARE VARIABLE WREFATUAL INTEGER;
DECLARE VARIABLE WQTDNOVA INTEGER;
DECLARE VARIABLE WCODPROD INTEGER;
DECLARE VARIABLE WIGNORARPROD DM_BOOLEAN;
DECLARE VARIABLE WQTDTOTAL INTEGER;
DECLARE VARIABLE WVLRUNIT DM_NUMERIC_15_2;
DECLARE VARIABLE WVLRUNITMEDOICMSST DM_NUMERIC_15_2;
DECLARE VARIABLE WVLRTTICMSSUPENT DM_NUMERIC_15_2;
DECLARE VARIABLE WVLRUNITMEDIOITEMSUPENT DM_NUMERIC_15_2;
BEGIN
    /* VERIFICA SE O TOTAL DE ENTRADAS É MENOR QUE O DE SAÍDAS, SE FOR DEVE BUSCAR ENTRADAS ANTERIOR - AI VAI INSERIR NA TEMP PARA BUSCAR NOS SQLS */
    INSERT INTO TMP_VEF_EMP_ENTADRCST_TEMP(BDSESSAO,BDCODEMP, BDREFERENCIA,BDCODPROD,BDQTDFALTANTE)
    SELECT :PRSESSAO BDSESSAO,BDCODEMP, BDREFERENCIA,BDCODPROD,BDQTDFALTANTE
    FROM (
        SELECT BDCODEMP, BDREFERENCIA,BDCODPROD, IIF(SUM(BDQTDTOTALENT) < SUM(BDQTDTOTALSAI),'TRUE','FALSE') BDBUSCAANT,(SUM(BDQTDTOTALSAI)-SUM(BDQTDTOTALENT)) BDQTDFALTANTE
        FROM (
            SELECT T1100.BDCODEMP,T1100.BDREFERENCIA,T1100.BDCODPROD, (SUM(T1100.BDQTDENT) - SUM(T1100.BDQTDSAI)) BDQTDTOTALENT, 0 BDQTDTOTALSAI
            FROM (
                  SELECT T1100.BDCODEMP,T1100.BDREFERENCIA,T1100.BDCODPROD, T1100.BDQTDITEM BDQTDENT , 0 BDQTDSAI
                  FROM TMP_VEF_EMP_TADRCST_1000_TEMP TPROD
                  JOIN TMP_VEF_EMP_TADRCST_1100_TEMP T1100 ON (T1100.BDCODEMP = TPROD.BDCODEMP AND T1100.BDSESSAO = TPROD.BDSESSAO AND T1100.BDCHAVE = TPROD.BDCHAVE AND T1100.BDORDEM = TPROD.BDORDEM AND T1100.BDORDEMPROD = TPROD.BDORDEMPROD AND T1100.BDCODPROD = TPROD.BDCODPROD AND T1100.BDREFERENCIA = TPROD.BDREFERENCIA)
                  WHERE TPROD.BDSESSAO = :PRSESSAO
                 ) T1100
            GROUP BY T1100.BDCODEMP,T1100.BDREFERENCIA,T1100.BDCODPROD
            UNION ALL
            SELECT T1200.BDCODEMP,T1200.BDREFERENCIA,T1200.BDCODPROD, 0 BDQTDTOTALENT, (SUM(BDQTDSAI) - SUM(BDQTDENT)) BDQTDTOTALSAI
            FROM (
                  SELECT T1200.BDCODEMP,T1200.BDREFERENCIA,T1200.BDCODPROD, IIF(T1200.BDTIPONFE = 0,T1200.BDQTDITEM,0) BDQTDENT,
                  IIF(T1200.BDTIPONFE = 1,T1200.BDQTDITEM,0) BDQTDSAI
                  FROM TMP_VEF_EMP_TADRCST_1000_TEMP TPROD
                  JOIN TMP_VEF_EMP_TADRCST_1200_TEMP T1200 ON (T1200.BDCODEMP = TPROD.BDCODEMP AND T1200.BDSESSAO = TPROD.BDSESSAO AND T1200.BDCHAVE = TPROD.BDCHAVE AND T1200.BDORDEM = TPROD.BDORDEM AND T1200.BDORDEMPROD = TPROD.BDORDEMPROD AND T1200.BDCODPROD = TPROD.BDCODPROD AND T1200.BDREFERENCIA = TPROD.BDREFERENCIA)
                  WHERE TPROD.BDSESSAO = :PRSESSAO
                 ) T1200
            GROUP BY T1200.BDCODEMP,T1200.BDREFERENCIA,T1200.BDCODPROD
            UNION ALL
            SELECT T1300.BDCODEMP,T1300.BDREFERENCIA,T1300.BDCODPROD, 0 BDQTDTOTALENT, (SUM(BDQTDSAI) - SUM(BDQTDENT)) BDQTDTOTALSAI
            FROM (
                  SELECT T1300.BDCODEMP,T1300.BDREFERENCIA,T1300.BDCODPROD, IIF(T1300.BDTIPONFE = 0,T1300.BDQTDITEM,0) BDQTDENT,
                  IIF(T1300.BDTIPONFE = 1,T1300.BDQTDITEM,0) BDQTDSAI
                  FROM TMP_VEF_EMP_TADRCST_1000_TEMP TPROD
                  JOIN TMP_VEF_EMP_TADRCST_1300_TEMP T1300 ON (T1300.BDCODEMP = TPROD.BDCODEMP AND T1300.BDSESSAO = TPROD.BDSESSAO AND T1300.BDCHAVE = TPROD.BDCHAVE AND T1300.BDORDEM = TPROD.BDORDEM AND T1300.BDORDEMPROD = TPROD.BDORDEMPROD  AND T1300.BDCODPROD = TPROD.BDCODPROD AND T1300.BDREFERENCIA = TPROD.BDREFERENCIA)
                  WHERE TPROD.BDSESSAO = :PRSESSAO
                 ) T1300
            GROUP BY T1300.BDCODEMP,T1300.BDREFERENCIA,T1300.BDCODPROD
            UNION ALL
            SELECT T1400.BDCODEMP,T1400.BDREFERENCIA,T1400.BDCODPROD, 0 BDQTDTOTALENT, (SUM(BDQTDSAI) - SUM(BDQTDENT)) BDQTDTOTALSAI
            FROM (
                  SELECT T1400.BDCODEMP,T1400.BDREFERENCIA,T1400.BDCODPROD, IIF(T1400.BDTIPONFE = 0,T1400.BDQTDITEM,0) BDQTDENT,
                  IIF(T1400.BDTIPONFE = 1,T1400.BDQTDITEM,0) BDQTDSAI
                  FROM TMP_VEF_EMP_TADRCST_1000_TEMP TPROD
                  JOIN TMP_VEF_EMP_TADRCST_1400_TEMP T1400 ON (T1400.BDCODEMP = TPROD.BDCODEMP AND T1400.BDSESSAO = TPROD.BDSESSAO AND T1400.BDCHAVE = TPROD.BDCHAVE AND T1400.BDORDEM = TPROD.BDORDEM AND T1400.BDORDEMPROD = TPROD.BDORDEMPROD AND T1400.BDCODPROD = TPROD.BDCODPROD AND T1400.BDREFERENCIA = TPROD.BDREFERENCIA)
                  WHERE TPROD.BDSESSAO = :PRSESSAO
                 ) T1400
            GROUP BY T1400.BDCODEMP,T1400.BDREFERENCIA,T1400.BDCODPROD
            UNION ALL
            SELECT T1500.BDCODEMP,T1500.BDREFERENCIA,T1500.BDCODPROD, 0 BDQTDTOTALENT, (SUM(BDQTDSAI) - SUM(BDQTDENT)) BDQTDTOTALSAI
            FROM (
                  SELECT T1500.BDCODEMP,T1500.BDREFERENCIA,T1500.BDCODPROD, IIF(T1500.BDTIPONFE = 0,T1500.BDQTDITEM,0) BDQTDENT,
                  IIF(T1500.BDTIPONFE = 1,T1500.BDQTDITEM,0) BDQTDSAI
                  FROM TMP_VEF_EMP_TADRCST_1000_TEMP TPROD
                  JOIN TMP_VEF_EMP_TADRCST_1500_TEMP T1500 ON (T1500.BDCODEMP = TPROD.BDCODEMP AND T1500.BDSESSAO = TPROD.BDSESSAO AND T1500.BDCHAVE = TPROD.BDCHAVE AND T1500.BDORDEM = TPROD.BDORDEM AND T1500.BDORDEMPROD = TPROD.BDORDEMPROD AND T1500.BDCODPROD = TPROD.BDCODPROD AND T1500.BDREFERENCIA = TPROD.BDREFERENCIA)
                  WHERE TPROD.BDSESSAO = :PRSESSAO
                 ) T1500
            GROUP BY T1500.BDCODEMP,T1500.BDREFERENCIA,T1500.BDCODPROD
        )
        GROUP BY BDCODEMP, BDREFERENCIA,BDCODPROD
    )
    WHERE BDQTDFALTANTE > 0;


    WREFERENCIA = CAST( (SELECT BDAAAAMM FROM AAAAMM(:PRDATAFIM)) AS INTEGER ) ;
    WREF12MESES = (SELECT BDREFERENCIA FROM DEC_REFERENCIA(:WREFERENCIA,12));
    WREFATUAL   = :WREFERENCIA;
    WHILE ((SELECT BDREFERENCIA FROM DEC_REFERENCIA(:WREFATUAL,1)) >= :WREF12MESES) DO
      BEGIN
        --WREFATUAL = (SELECT BDREFERENCIA FROM DEC_REFERENCIA(:WREFATUAL,1));

         FOR  /*PEGA AS CONFIRUAÇÕES DO PLANO*/
            SELECT ADRCST.BDCODEMP,PLA.BDCODPLANOCONFADRCST,PLA.BDCHAVE, PLA.BDPARTENQFED, PLA.BDCONSUFINAL,
            IIF((SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASCFOP,
            IIF((SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASNCM,
            IIF((SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODOSTER,
            IIF((SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODOSPROD,
            IIF((SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASCST
            FROM VEF_BASE_TPLANOACOESCONFADRCST PLA
            LEFT OUTER JOIN TMP_VEF_EMP_TADRCSTGER_TEMP ADRCST ON (ADRCST.BDSESSAO = :PRSESSAO)
            WHERE PLA.BDCODPLANOCONFADRCST = ADRCST.BDCODPLACONFADRCST
            AND PLA.BDCODPROCESSO = 0 /*PROCESSO DE ENTRADA*/
            INTO :WCODEMP,:WPLANO,:WCODCHAVE, :WPARTENQFED, :WCONSUFINAL, :WTODASCFOP, :WTODASNCM, :WTODOSTER, :WTODOSPROD, :WTODASCST
          DO
            BEGIN
        
                WSQL =        ' INSERT INTO TMP_VEF_EMP_TADRCST_1100_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, ';
                WSQL = WSQL|| ' BDRESPRETICMSST, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT, BDBCICMSST, BDVLRICMSTTSUPENT, BDTIPONFE, BDCHAVENFE) ';
                WSQL = WSQL|| ' SELECT SAIT.BDSESSAO, ENT.BDCODEMP, ENT.BDREFLAN, SAIT.BDCODPROD, ENT.BDCHAVE, /*SAIT*/PRO.BDORDEM, PRO.BDORDEMPRO, ENT.BDDATAEMISSAO, ';
                WSQL = WSQL|| ' IIF(ENTO.BDBCST > 0 OR ENTO.BDBCFCPRETIDO > 0 OR ENTO.BDBCICMSSTRET > 0 OR ENTO.BDBCFCPSTRET > 0, IIF(ENTO.BDBCST > 0 OR ENTO.BDBCFCPRETIDO > 0, 1, 2), ';
                WSQL = WSQL|| '     IIF(PRO.BDBCST > 0 OR PRO.BDBCFCPRETIDO > 0 OR PRO.BDBCICMSSTRET > 0 OR PRO.BDBCFCPSTRET > 0, IIF(PRO.BDBCST > 0 OR PRO.BDBCFCPRETIDO > 0, 1, 2), ';
                WSQL = WSQL|| '        IIF(COALESCE(MVA.BDVLRICMSST, 0) > 0, 3, 0) ';
                WSQL = WSQL|| '     ) ';
                WSQL = WSQL|| ' ) BDRESPRETICMSST, ';
                WSQL = WSQL|| ' COALESCE(ICMSO.BDCODCSTICMS,ICMS.BDCODCSTICMS) BDCSTICMS, ENT.BDNUMDOCINI,  TER.BDCGCTER, UFT.BDSIGLAUF,EMP.BDCNPJEMP, UF.BDSIGLAUF, ';
                WSQL = WSQL|| ' COALESCE(ENTO.BDCODNAT,I.BDCODNAT) BDCODNAT, COALESCE(UNMF.BDAPEUNIMED, UNMP.BDAPEUNIMED) BDUNIDMED, PRO.BDQTDITEM, ';
                WSQL = WSQL|| ' ((PRO.BDVLRITEM - PRO.BDVLRDESC) / IIF(COALESCE(PRO.BDQTDITEM, 0) = 0, 1, PRO.BDQTDITEM)) BDVLRUNIT, ';
                WSQL = WSQL|| ' (COALESCE(PRO.BDBCST,0) + COALESCE(PRO.BDBCFCPRETIDO,0) + COALESCE(PRO.BDBCICMSSTRET,0) + COALESCE(PRO.BDBCFCPSTRET,0) + COALESCE(MVA.BDVLRICMSST, 0)) BDBCICMSST, ';
                WSQL = WSQL|| ' (COALESCE(PRO.BDVLRICMS,0) + COALESCE(PRO.BDVLRST,0) + COALESCE(PRO.BDFCPRETIDO,0) + COALESCE(PRO.BDVLRICMSSTRET,0) + COALESCE(PRO.BDVLRFCPSTRET,0) + COALESCE(MVA.BDVLRICMSSTNAORET,0)) BDVLRICMSTTSUPENT, 0, (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(ENT.BDCHAVENFE)) BDCHAVENFE ';
                WSQL = WSQL|| ' FROM ( ';
                         WSQL = WSQL|| ' SELECT TENT.BDCODEMP, TENT.BDSESSAO, TENT.BDCODPROD, TENT.BDREFERENCIA, T1000.BDCODUNIMED, T1000.BDNCMPROD ';
                         --WSQL = WSQL||         ' , PRO.BDCHAVE, PRO.BDORDEM,PRO.BDORDEMPRO ';
                         WSQL = WSQL|| ' FROM TMP_VEF_EMP_ENTADRCST_TEMP TENT ';
                         WSQL = WSQL|| ' LEFT OUTER JOIN TMP_VEF_EMP_TADRCST_1000_TEMP T1000 ON (T1000.BDCODEMP = TENT.BDCODEMP AND T1000.BDCODPROD = TENT.BDCODPROD) ';
                         --WSQL = WSQL|| ' JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = T1000.BDCODEMP AND PRO.BDCODPROD = T1000.BDCODPROD) ';
                         WSQL = WSQL|| ' WHERE T1000.BDSESSAO = '|| :PRSESSAO||' AND ';
                         WSQL = WSQL|| ' T1000.BDCODEMP = '||:WCODEMP;
                         WSQL = WSQL|| ' AND TENT.BDQTDFALTANTE > 0 ';
                         WSQL = WSQL|| ' GROUP BY TENT.BDCODEMP, TENT.BDSESSAO, TENT.BDCODPROD, TENT.BDREFERENCIA, T1000.BDCODUNIMED, T1000.BDNCMPROD ';
                         --WSQL = WSQL||         ' ,PRO.BDCHAVE, PRO.BDORDEM,PRO.BDORDEMPRO ';
                WSQL = WSQL|| ' ) SAIT ';
                --WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = SAIT.BDCODEMP AND PRO.BDCHAVE = SAIT.BDCHAVE AND PRO.BDORDEM = SAIT.BDORDEM AND PRO.BDORDEMPRO = SAIT.BDORDEMPRO) ';
                WSQL = WSQL|| ' JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = SAIT.BDCODEMP AND ';--ENT.BDCHAVE = SAIT.BDCHAVE) ';
                WSQL = WSQL||                              ' ENT.BDMODELO = 55 AND ';
                WSQL = WSQL||                              ' ENT.BDREFLAN = '||:WREFATUAL||' AND ';
                IF (:WCONSUFINAL = 1) THEN
                   WSQL = WSQL||                           ' COALESCE(ENT.BDCONSUFINAL,0) = '|| :WCONSUFINAL||' AND ';
                ELSE
                   WSQL = WSQL||                           ' COALESCE(ENT.BDCONSUFINAL,0) IN (-1,0) AND ';
                WSQL = WSQL||                              ' ENT.BDCODSITNF NOT IN (2,3,4,5) ) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = /*SAIT*/ENT.BDCODEMP AND I.BDCHAVE = /*SAIT*/ENT.BDCHAVE) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM AND PRO.BDCODPROD = SAIT.BDCODPROD) ';
                --WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROENTIMPORI ENTO ON (ENTO.BDCODEMP = ENT.BDCODEMP AND ENTO.BDCODPROD = PRO.BDCODPROD AND ENTO.BDCHAVE = ENT.BDCHAVE) ';
                WSQL = WSQL|| 'LEFT OUTER JOIN (SELECT o.bdCODEMP, o.bdCODPROD, o.bdCHAVE, o.bdCODNAT, o.bdCODCSTICMS, o.bdORDEM, ';
                WSQL = WSQL||                 ' SUM(o.bdBCST) AS bdBCST, SUM(o.bdBCFCPRETIDO) AS bdBCFCPRETIDO, SUM(o.bdBCICMSSTRET) AS bdBCICMSSTRET, SUM(o.bdBCFCPSTRET) AS bdBCFCPSTRET ';
                WSQL = WSQL||                 ' FROM VEF_EMP_TMOVPROENTIMPORI o ';
                WSQL = WSQL||                 ' GROUP BY o.bdCODEMP, o.bdCODPROD, o.bdCHAVE, o.bdCODNAT, o.bdCODCSTICMS, o.bdORDEM) ENTO ON (ento.bdCODEMP = ent.bdCODEMP AND ento.bdCODPROD = pro.bdCODPROD AND ento.bdCODCSTICMS = pro.bdCODCSTICMS AND ento.bdCHAVE = ent.bdCHAVE and ento.bdORDEM = pro.bdORDEM) ';
                WSQL = WSQL|| 'LEFT OUTER JOIN (SELECT MVA.BDCODEMP,MVA.BDCHAVE,MVA.BDORDEM,MVA.BDCODPROD, ';
                WSQL = WSQL||                         'SUM(MVA.BDVLRICMSST)BDVLRICMSST,SUM(MVA.BDVLRICMSSTNAORET)BDVLRICMSSTNAORET ';
                WSQL = WSQL||                  'FROM VEF_EMP_TMOVMVAPR MVA ';
                WSQL = WSQL||                  'GROUP BY MVA.BDCODEMP,MVA.BDCHAVE,MVA.BDORDEM,MVA.BDCODPROD) MVA  ON (MVA.BDCODEMP = /*SAIT*/PRO.BDCODEMP AND MVA.BDCHAVE = /*SAIT*/PRO.BDCHAVE AND MVA.BDORDEM = /*SAIT*/PRO.BDORDEM AND MVA.BDCODPROD = /*SAIT*/PRO.BDCODPROD) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN TCADPRO CPRO ON (CPRO.BDCODPROD = ENTO.BDCODPROD) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = SAIT.BDCODEMP AND VINC.BDCODPROD = ENTO.BDCODPROD) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = ENT.BDCODTER) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMSO ON (ICMSO.BDCODCSTICMS = ENTO.BDCODCSTICMS) ';
                --WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE AND I.BDORDEM = PRO.BDORDEM) ';
                --WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = ENT.BDCODEMP AND C113.BDCHAVE = ENT.BDCHAVE AND (SELECT BDAAAAMM FROM AAAAMM(C113.BDDTEMISSAO)) = SAIT.BDREFERENCIA) ';
                WSQL = WSQL|| ' JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = ENT.BDCODEMP) ';
                WSQL = WSQL|| ' JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID) ';
                WSQL = WSQL|| ' JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF) ';
                WSQL = WSQL|| ' JOIN TCIDADE CIDT ON (CIDT.BDCODCID = TER.BDCODCID) ';
                WSQL = WSQL|| ' JOIN TUF UFT ON (UFT.BDCODUF = CIDT.BDCODUF) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODEMP = ENT.BDCODEMP AND FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMF ON (UNMF.BDCODUNIMED = FAT.BDCODUNIMED) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMP ON (UNMP.BDCODUNIMED = SAIT.BDCODUNIMED) ';
                --WSQL = WSQL|| ' WHERE ENT.BDMODELO = 55 ';
                --WSQL = WSQL|| ' AND ENT.BDREFLAN = '||:WREFATUAL;

                --IF (:WCONSUFINAL = 1) THEN
                --   WSQL = WSQL|| ' AND COALESCE(ENT.BDCONSUFINAL,0) = '|| :WCONSUFINAL;
                --ELSE
                --   WSQL = WSQL|| ' AND COALESCE(ENT.BDCONSUFINAL,0) IN (-1,0) ';
                --WSQL = WSQL|| ' AND ENT.BDCODSITNF NOT IN (2,3,4,5) AND ';
                WSQL = WSQL|| ' WHERE(ENTO.BDBCST > 0 OR ENTO.BDBCFCPSTRET > 0 OR ENTO.BDBCFCPRETIDO > 0 OR ENTO.BDBCICMSSTRET > 0 OR ';
                WSQL = WSQL|| ' PRO.BDBCST > 0 OR PRO.BDBCFCPSTRET > 0 OR PRO.BDBCFCPRETIDO > 0 OR PRO.BDBCICMSSTRET > 0 OR PRO.BDVLRST > 0 OR PRO.BDVLRFCPSTRET > 0 OR PRO.BDVLRFCP > 0 OR PRO.BDVLRICMSSTRET > 0 OR MVA.BDVLRICMSST > 0 OR MVA.BDVLRICMSSTNAORET > 0) ';
                WSQL = WSQL|| ' AND NOT EXISTS (SELECT BDCODEMP FROM TMP_VEF_EMP_TADRCST_1100_TEMP T WHERE T.BDSESSAO = SAIT.BDSESSAO AND T.BDCODEMP = ENT.BDCODEMP AND T.BDCHAVE = ENT.BDCHAVE AND T.BDORDEM = /*SAIT*/PRO.BDORDEM AND PRO.BDORDEMPRO = T.BDORDEMPROD)';

                IF (:WPARTENQFED = 'TRUE' ) THEN
                   WSQL = WSQL|| ' AND (TER.BDENQSIMPLESFEDTER = 2)';
                ELSE IF (:WTODOSTER = 'FALSE') THEN
                   WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODTER = ENT.BDCODTER) ';

                IF (:WTODASCFOP = 'FALSE') THEN
                    WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNAT = I.BDCODNAT) ';
                IF (:WTODASNCM = 'FALSE') THEN
                   WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNCM = SAIT.BDNCMPROD) ';
                IF (:WTODOSPROD = 'FALSE') THEN
                   WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODPROD = PRO.BDCODPROD) ';
                IF (:WTODASCST = 'FALSE') THEN
                    WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCSTICMS = PRO.BDCODCSTICMS) ';
        
        
                EXECUTE STATEMENT(WSQL);
            END
        
          FOR  /*PEGA AS CONFIRUAÇÕES DO PLANO DE DEVOLUÇÃO*/
            SELECT PLA.BDCODPLANOCONFADRCST,ADRCST.BDCODEMP, PLA.BDCHAVE, PLA.BDPARTENQFED, PLA.BDCONSUFINAL,
            IIF((SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASCFOP,
            IIF((SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASNCM,
            IIF((SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODOSTER,
            IIF((SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODOSPROD,
            IIF((SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASCST
            FROM VEF_BASE_TPLANOACOESCONFADRCST PLA
            LEFT OUTER JOIN TMP_VEF_EMP_TADRCSTGER_TEMP ADRCST ON (ADRCST.BDSESSAO = :PRSESSAO)
            WHERE PLA.BDCODPLANOCONFADRCST = ADRCST.BDCODPLACONFADRCST
            AND PLA.BDCODPROCESSO = 1 /*PROCESSO DE DEVOLUÇÃO*/
            INTO :WPLANO,:WCODEMP, :WCODCHAVE, :WPARTENQFED, :WCONSUFINAL, :WTODASCFOP, :WTODASNCM, :WTODOSTER, :WTODOSPROD, :WTODASCST
          DO
            BEGIN
                WSQL =        ' INSERT INTO TMP_VEF_EMP_TADRCST_1100_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, ';
                WSQL = WSQL|| ' /*BDRESPRETICMSST,*/ BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT,  ';
                WSQL = WSQL|| ' BDBCICMSST, BDVLRICMSTTSUPENT,BDCHAVENFEREFC113,BDNUMITEMREFC113,BDCODINCONSISTENCIA, BDTIPONFE, BDCHAVENFE) ';
                WSQL = WSQL|| ' SELECT T1000.BDSESSAO, T1000.BDCODEMP, T1000.BDREFLAN, T1000.BDCODPROD, T1000.BDCHAVESAI, PRO.BDORDEM, PRO.BDORDEMPRO, T1000.BDDATAEMISSAO, ';
                WSQL = WSQL|| ' ICMS.BDCODCSTICMS, T1000.BDNUMDOCINI, T1000.BDCNPJEMP, T1000.BDSIGLAUF, T1000.BDCGCTER, T1000.BDSIGLAUFT, ';
                WSQL = WSQL|| ' I.BDCODNAT BDCODNAT, COALESCE(UNMF.BDAPEUNIMED, UNMP.BDAPEUNIMED) BDUNIDMED, PRO.BDQTDITEM, ';
                WSQL = WSQL|| ' ((PRO.BDVLRITEM - PRO.BDVLRDESC) / IIF(COALESCE(PRO.BDQTDITEM, 0) = 0, 1, PRO.BDQTDITEM)) BDVLRUNIT,  ';
                WSQL = WSQL|| ' (COALESCE(PRO.BDBCST,0) + COALESCE(PRO.BDBCFCPRETIDO,0) + COALESCE(PRO.BDBCICMSSTRET,0) + COALESCE(PRO.BDBCFCPSTRET,0)) BDBCICMSST, ';
                WSQL = WSQL|| ' (COALESCE(PRO.BDVLRICMS,0) + COALESCE(PRO.BDVLRST,0) + COALESCE(PRO.BDFCPRETIDO,0) + COALESCE(PRO.BDVLRICMSSTRET,0) + COALESCE(PRO.BDVLRFCPSTRET,0)) BDVLRICMSTTSUPENT, ';
                WSQL = WSQL|| ' (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) BDCHAVENFEREFC113,PROREF.BDORDEMPRO,IIF(C113.BDCODEMP IS NULL, 20,NULL) BDINCO,1, (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(T1000.BDCHAVENFE)) BDCHAVENFE ';
                WSQL = WSQL|| ' FROM ( ';
                        WSQL = WSQL|| ' SELECT TENT.*, SAI.BDCHAVE BDCHAVESAI, SAI.BDREFLAN, SAI.BDDATAEMISSAO, SAI.BDNUMDOCINI,SAI.BDCODTER, EMP.BDCNPJEMP, UF.BDSIGLAUF, TER.BDCGCTER, UFT.BDSIGLAUF BDSIGLAUFT, SAI.BDCHAVENFE,PRO.BDORDEM, PRO.BDORDEMPRO ';
                        WSQL = WSQL|| ' FROM TMP_VEF_EMP_ENTADRCST_TEMP TENT ';
                        WSQL = WSQL|| ' JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = TENT.BDCODEMP) ';
                        WSQL = WSQL|| ' JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = TENT.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDCODPROD = TENT.BDCODPROD) ';
                        WSQL = WSQL|| ' LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = SAI.BDCODTER) ';
                        WSQL = WSQL|| ' JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = SAI.BDCODEMP) ';
                        WSQL = WSQL|| ' JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID) ';
                        WSQL = WSQL|| ' JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF) ';
                        WSQL = WSQL|| ' JOIN TCIDADE CIDT ON (CIDT.BDCODCID = TER.BDCODCID) ';
                        WSQL = WSQL|| ' JOIN TUF UFT ON (UFT.BDCODUF = CIDT.BDCODUF) ';
                        WSQL = WSQL|| ' WHERE TENT.BDSESSAO = '||:PRSESSAO||' AND ';
                        WSQL = WSQL|| ' TENT.BDCODEMP = '||:WCODEMP;
                        WSQL = WSQL|| ' AND SAI.BDMODELO = 55 ';
                        WSQL = WSQL|| ' AND SAI.BDREFLAN = '||:WREFATUAL;
                        IF (:WCONSUFINAL = 1) THEN
                           WSQL = WSQL|| ' AND COALESCE(SAI.BDCONSUFINAL,0) = '|| :WCONSUFINAL;
                        ELSE
                           WSQL = WSQL|| ' AND COALESCE(SAI.BDCONSUFINAL,0) IN (-1,0) ';
                        WSQL = WSQL|| ' AND SAI.BDCODSITNF NOT IN (2, 3, 4, 5) AND TENT.BDQTDFALTANTE > 0 ';
                WSQL = WSQL|| ') T1000 ';
                WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = T1000.BDCODEMP AND I.BDCHAVE = T1000.BDCHAVESAI AND I.BDORDEM = T1000.BDORDEM) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM AND PRO.BDORDEMPRO = T1000.BDORDEMPRO AND PRO.BDCODPROD = T1000.BDCODPROD) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODEMP = T1000.BDCODEMP AND FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMF ON (UNMF.BDCODUNIMED = FAT.BDCODUNIMED) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN TCADPRO_VINC CAD ON (CAD.BDCODEMP = PRO.BDCODEMP AND CAD.BDCODPROD = PRO.BDCODPROD) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMP ON (UNMP.BDCODUNIMED = CAD.BDCODUNIMED) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVSAIDOCFREF C113 ON (C113.BDCODEMP = I.BDCODEMP AND C113.BDCHAVE = I.BDCHAVE /*AND (SELECT BDAAAAMM FROM AAAAMM(C113.BDDTEMISSAO)) = T1000.BDREFERENCIA*/) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = C113.BDCODEMP /*AND ENT.BDREFLAN = SAI.BDREFLAN*/) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROENT PROREF ON (PROREF.BDCODEMP = ENT.BDCODEMP AND PROREF.BDCHAVE = ENT.BDCHAVE AND PROREF.BDCODPROD = PRO.BDCODPROD) ';
                WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT) ';
                WSQL = WSQL|| ' WHERE NAT.BDDEVOL = ''TRUE'' ';
                WSQL = WSQL|| ' AND ((ENT.BDNUMDOCINI = C113.BDNUMDOC AND COALESCE(ENT.BDCHAVENFE,0) = IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '''', 0, C113.BDCHAVENFE) ';
                WSQL = WSQL|| ' AND ENT.BDDATAEMISSAO = C113.BDDTEMISSAO) OR (C113.BDCODEMP IS NULL))';
                WSQL = WSQL|| ' AND NOT EXISTS (SELECT BDCODEMP FROM TMP_VEF_EMP_TADRCST_1100_TEMP T WHERE T.BDSESSAO = T1000.BDSESSAO AND T.BDCODEMP = T1000.BDCODEMP AND T.BDCHAVE = T1000.BDCHAVESAI AND T.BDORDEM = PRO.BDORDEM AND T.BDORDEMPROD = PRO.BDORDEMPRO )';

                IF (:WTODOSTER = 'FALSE') THEN
                   WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODTER = T1000.BDCODTER) ';
            
                IF (:WTODASCFOP = 'FALSE') THEN
                   WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNAT = I.BDCODNAT) ';
                IF (:WTODASNCM = 'FALSE') THEN
                   WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNCM = CAD.BDNCMPROD) ';
                IF (:WTODOSPROD = 'FALSE') THEN
                   WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODPROD = PRO.BDCODPROD) ';
                IF (:WTODASCST = 'FALSE') THEN
                   WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCSTICMS = PRO.BDCODCSTICMS) ';
        
              EXECUTE STATEMENT(WSQL);
            END           /*FIM DO FOR DO DE DEVOLUCAO*/


             FOR
                SELECT T1100.BDCODPROD, (SUM(T1100.BDQTDENT) - SUM(T1100.BDQTDSAI)) BDQTDTOTAL
                FROM (
                     SELECT T1100.BDCODEMP, T1100.BDREFERENCIA,T1100.BDCODPROD, IIF(T1100.BDTIPONFE = 0,T1100.BDQTDITEM,0) BDQTDENT ,IIF(T1100.BDTIPONFE = 1,T1100.BDQTDITEM,0) BDQTDSAI
                     FROM (
                         SELECT TENT.BDSESSAO,TENT.BDREFERENCIA, TENT.BDCODEMP, TENT.BDCODPROD
                         FROM TMP_VEF_EMP_ENTADRCST_TEMP TENT
                         WHERE TENT.BDSESSAO = :PRSESSAO
                         AND TENT.BDCODEMP = :WCODEMP
                         AND TENT.BDQTDFALTANTE > 0
                         GROUP BY TENT.BDSESSAO,TENT.BDREFERENCIA, TENT.BDCODEMP, TENT.BDCODPROD
                         ) TPROD
                     JOIN TMP_VEF_EMP_TADRCST_1100_TEMP T1100 ON (T1100.BDCODEMP = TPROD.BDCODEMP AND T1100.BDSESSAO = TPROD.BDSESSAO AND T1100.BDCODPROD = TPROD.BDCODPROD)
                     WHERE T1100.BDREFERENCIA = :WREFATUAL
                    ) T1100
               GROUP BY T1100.BDCODEMP, T1100.BDREFERENCIA,T1100.BDCODPROD
             INTO WCODPROD,WQTDNOVA
             DO
               BEGIN
                  UPDATE TMP_VEF_EMP_ENTADRCST_TEMP TENT SET
                  TENT.BDQTDFALTANTE = TENT.BDQTDFALTANTE - :WQTDNOVA
                  WHERE TENT.BDSESSAO = :PRSESSAO AND TENT.BDCODPROD = :WCODPROD;

                  DELETE FROM TMP_VEF_EMP_ENTADRCST_TEMP TENT
                  WHERE TENT.BDSESSAO = :PRSESSAO
                  AND   TENT.BDQTDFALTANTE <= 0;
               END  /*FIM DO FOR DO QUE VERIFICA A QUANTIDADE*/

                WREFATUAL = (SELECT BDREFERENCIA FROM DEC_REFERENCIA(:WREFATUAL,1));
            END /*FIM DO WHILE*/

      /*1110-1120*/
      INSERT INTO VEF_EMP_TADRCST_1110_1120 (BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO,
      BDRESPRETICMSST, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, BDCODNAT, BDUNIDMED, BDQTDITEM,
      BDVLRUNIT, BDBCICMSST, BDVLRICMSTTSUPENT, BDCODINCONSISTENCIA, BDTIPONFE,BDCHAVENFE, BDCHAVENFEREFC113, BDNUMITEMREFC113)
      SELECT T1110.BDCODEMP, :WREFERENCIA, T1110.BDCODPROD, T1110.BDCHAVE, T1110.BDORDEM, T1110.BDORDEMPROD, T1110.BDDATAEMISSAO,
      T1110.BDRESPRETICMSST, T1110.BDCSTICMS, T1110.BDNUMDOC, T1110.BDCNPJEMITENTE, T1110.BDUFEMITENTE, T1110.BDCNPJCPFDESTIN, T1110.BDUFDESTIN, T1110.BDCODNAT, T1110.BDUNIDMED, T1110.BDQTDITEM,
      T1110.BDVLRUNIT, T1110.BDBCICMSST, T1110.BDVLRICMSTTSUPENT, T1110.BDCODINCONSISTENCIA, T1110.BDTIPONFE,T1110.BDCHAVENFE,
      --BDCHAVENFEREFC113, BDNUMITEMREFC113
      IIF ((t1110.bdCHAVENFEREFC113 IS NOT NULL) AND ((SELECT RESULT FROM SP_TIRATODOSSINAIS(t1110.bdCHAVENFEREFC113)) <> ''), t1110.bdCHAVENFEREFC113,
           IIF(t1110.bdTIPONFE = 0, (SELECT RESULT FROM SP_TIRATODOSSINAIS(c113Ent.bdCHAVENFE)), (SELECT RESULT FROM SP_TIRATODOSSINAIS(c113Sai.bdCHAVENFE)))) BDCHAVENFEREFC113,
      T1110.BDNUMITEMREFC113
      FROM TMP_VEF_EMP_TADRCST_1100_TEMP T1110
      --LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF c113Ent ON(c113Ent.bdCODEMP = t1110.bdCODEMP AND c113Ent.bdCHAVE = t1110.bdCHAVE AND t1110.bdTIPONFE = 0)
      LEFT OUTER JOIN (SELECT ref.bdCODEMP, ref.bdCHAVE, MIN(ref.bdCHAVENFE) bdCHAVENFE
                       FROM VEF_EMP_TMOVENTDOCFREF ref
                       WHERE ((ref.bdCHAVENFE IS NOT NULL) AND ((SELECT RESULT FROM SP_TIRATODOSSINAIS(ref.bdCHAVENFE)) <> ''))
                       GROUP BY ref.bdCODEMP, ref.bdCHAVE) c113Ent ON(c113Ent.bdCODEMP = t1110.bdCODEMP AND c113Ent.bdCHAVE = t1110.bdCHAVE AND t1110.bdTIPONFE = 0)
      --LEFT OUTER JOIN VEF_EMP_TMOVSAIDOCFREF c113Sai ON(c113Sai.bdCODEMP = t1110.bdCODEMP AND c113Sai.bdCHAVE = t1110.bdCHAVE AND t1110.bdTIPONFE = 1)
      LEFT OUTER JOIN (SELECT ref.bdCODEMP, ref.bdCHAVE, MIN(ref.bdCHAVENFE) bdCHAVENFE
                       FROM VEF_EMP_TMOVSAIDOCFREF ref
                       WHERE ((ref.bdCHAVENFE IS NOT NULL) AND ((SELECT RESULT FROM SP_TIRATODOSSINAIS(ref.bdCHAVENFE)) <> ''))
                       GROUP BY ref.bdCODEMP, ref.bdCHAVE) c113Sai ON(c113Sai.bdCODEMP = t1110.bdCODEMP AND c113Sai.bdCHAVE = t1110.bdCHAVE AND t1110.bdTIPONFE = 1)
      WHERE BDSESSAO = :PRSESSAO;

      /*TOTAL 1100*/
      INSERT INTO VEF_EMP_TADRCST_1100 (BDCODEMP,BDCODPROD, BDREFERENCIA, BDQTDTOTALITEM, BDMENORVLRUNIITEM, BDVLRUNITMEDOICMSST, BDVLRTTICMSSUPENT, BDVLRUNITMEDIOITEMSUPENT)
      SELECT T1100.BDCODEMP,T1100.BDCODPROD,:WREFERENCIA,(SUM(T1100.BDQTDENT) - SUM(T1100.BDQTDSAI)) BDQTDTOTAL,MIN(T1100.BDVLRUNIT) BDVLRUNIT,
      CAST(CAST((SUM(BDBCICMSSTENT)-SUM(BDBCICMSSTSAI)) AS NUMERIC(15,4))/CAST(IIF((SUM(T1100.BDQTDENT) - SUM(T1100.BDQTDSAI)) = 0,1,(SUM(T1100.BDQTDENT) - SUM(T1100.BDQTDSAI)))  AS NUMERIC(15,4)) AS DM_NUMERIC_15_2) BDVLRUNITMEDOICMSST,
      (SUM(BDVLRICMSTTSUPENTENT)-SUM(BDVLRICMSTTSUPENTSAI)) BDVLRTTICMSSUPENT,
      CAST(CAST((SUM(BDVLRICMSTTSUPENTENT)-SUM(BDVLRICMSTTSUPENTSAI))AS NUMERIC(15,4))/CAST(IIF((SUM(T1100.BDQTDENT) - SUM(T1100.BDQTDSAI)) = 0,1,(SUM(T1100.BDQTDENT) - SUM(T1100.BDQTDSAI))) AS NUMERIC(15,4)) AS DM_NUMERIC_15_2) BDVLRUNITMEDIOITEMSUPENT
      FROM (
            SELECT T1100.BDCODEMP, T1100.BDREFERENCIA,T1100.BDCODPROD,IIF(T1100.BDTIPONFE = 0,T1100.BDQTDITEM,0) BDQTDENT,IIF(T1100.BDTIPONFE = 1,T1100.BDQTDITEM,0) BDQTDSAI,
            IIF(T1100.BDTIPONFE = 0,T1100.BDVLRUNIT,NULL) BDVLRUNIT,IIF(T1100.BDTIPONFE = 0,T1100.BDBCICMSST,0) BDBCICMSSTENT, IIF(T1100.BDTIPONFE = 1,T1100.BDBCICMSST,0) BDBCICMSSTSAI,
            IIF(T1100.BDTIPONFE = 0,T1100.BDVLRICMSTTSUPENT,0) BDVLRICMSTTSUPENTENT, IIF(T1100.BDTIPONFE = 1,T1100.BDVLRICMSTTSUPENT,0) BDVLRICMSTTSUPENTSAI
    
            FROM (
                 SELECT TPROD.BDSESSAO,TPROD.BDREFERENCIA, TPROD.BDCODEMP, TPROD.BDCODPROD
                 FROM TMP_VEF_EMP_TADRCST_1000_TEMP TPROD
                 WHERE TPROD.BDSESSAO = :PRSESSAO
                 GROUP BY TPROD.BDSESSAO,TPROD.BDREFERENCIA,TPROD.BDCODEMP, TPROD.BDCODPROD
                 ) TPROD
            JOIN TMP_VEF_EMP_TADRCST_1100_TEMP T1100 ON (T1100.BDCODEMP = TPROD.BDCODEMP AND T1100.BDSESSAO = TPROD.BDSESSAO AND T1100.BDCODPROD = TPROD.BDCODPROD)
            ) T1100
      GROUP BY T1100.BDCODEMP,T1100.BDCODPROD;

    /*INSERE INCONSISTÊNCIA PARA QUANDO NÃO TEM ENTRADAS SUFICIENTES DO PRODUTO*/
    FOR
        SELECT TENT.BDCODEMP, TENT.BDCODPROD
        FROM TMP_VEF_EMP_ENTADRCST_TEMP TENT
        WHERE TENT.BDSESSAO = :PRSESSAO
        AND TENT.BDQTDFALTANTE > 0
        GROUP BY TENT.BDSESSAO,TENT.BDREFERENCIA, TENT.BDCODEMP, TENT.BDCODPROD
        INTO :WCODEMP, :WCODPROD
    DO
      BEGIN
          -- 22 - O PRODUTO #DESCPROD NÃO POSSUI NOTAS FISCAIS DE ENTRADA SUFICIENTE PARA JUSTIFICAR AS SAÍDAS, VERIFIQUE SEUS LANÇAMENTOS
          INSERT INTO VEF_INCON_TADRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG,BDCODPROD)
          SELECT 22 BDCODINC, :WCODEMP, :WREFERENCIA, GETORDEMSEQUENCIAL_STR(:WCODEMP || '.' || :WREFERENCIA, :WCODEMP), '1110' BDREG,:WCODPROD
          FROM TMP_VEF_EMP_TADRCSTGER_TEMP G
          WHERE G.BDSESSAO = :PRSESSAO
          AND G.BDCODEMP = :WCODEMP;

          SELECT BDIGNORARPROD FROM VEF_BASE_TPLACONFADRCST PLA
          WHERE PLA.BDCODPLANOCONFADRCST = :WPLANO
          INTO WIGNORARPROD;

          /*QUANDO O PARÂMETRO DE IGNORAR PRODUTO ESTIVER MARCADO, DEVE-SE EXCLUIR O PRODUTO DE TODOS OS LOCAIS DA APURAÇÃO - DO 1000 SERÁ EXCLUÍDO DEPOIS*/
          IF (WIGNORARPROD = 'TRUE') THEN
             BEGIN
               DELETE FROM VEF_EMP_TADRCST_1100 T1100 WHERE T1100.BDCODEMP = :WCODEMP AND T1100.BDREFERENCIA = :WREFERENCIA AND T1100.BDCODPROD = :WCODPROD;
               DELETE FROM VEF_EMP_TADRCST_1110_1120 T1100 WHERE T1100.BDCODEMP = :WCODEMP AND T1100.BDREFERENCIA = :WREFERENCIA AND T1100.BDCODPROD = :WCODPROD;
               DELETE FROM VEF_EMP_TADRCST_1200 T1200 WHERE T1200.BDCODEMP = :WCODEMP AND T1200.BDREFERENCIA = :WREFERENCIA AND T1200.BDCODPROD = :WCODPROD;
               DELETE FROM VEF_EMP_TADRCST_1210_1220 T1200 WHERE T1200.BDCODEMP = :WCODEMP AND T1200.BDREFERENCIA = :WREFERENCIA AND T1200.BDCODPROD = :WCODPROD;
               DELETE FROM VEF_EMP_TADRCST_1300 T1300 WHERE T1300.BDCODEMP = :WCODEMP AND T1300.BDREFERENCIA = :WREFERENCIA AND T1300.BDCODPROD = :WCODPROD;
               DELETE FROM VEF_EMP_TADRCST_1310_1320 T1300 WHERE T1300.BDCODEMP = :WCODEMP AND T1300.BDREFERENCIA = :WREFERENCIA AND T1300.BDCODPROD = :WCODPROD;
               DELETE FROM VEF_EMP_TADRCST_1400 T1400 WHERE T1400.BDCODEMP = :WCODEMP AND T1400.BDREFERENCIA = :WREFERENCIA AND T1400.BDCODPROD = :WCODPROD;
               DELETE FROM VEF_EMP_TADRCST_1410_1420 T1400 WHERE T1400.BDCODEMP = :WCODEMP AND T1400.BDREFERENCIA = :WREFERENCIA AND T1400.BDCODPROD = :WCODPROD;
               DELETE FROM VEF_EMP_TADRCST_1500 T1500 WHERE T1500.BDCODEMP = :WCODEMP AND T1500.BDREFERENCIA = :WREFERENCIA AND T1500.BDCODPROD = :WCODPROD;
               DELETE FROM VEF_EMP_TADRCST_1510_1520 T1500 WHERE T1500.BDCODEMP = :WCODEMP AND T1500.BDREFERENCIA = :WREFERENCIA AND T1500.BDCODPROD = :WCODPROD;
             END
      END
END
^

CREATE OR ALTER procedure SP_APURACAO_ADRCST_PR_1510_1520 (
    PRSESSAO integer,
    PRDATAINI date,
    PRDATAFIM date)
as
declare variable WSQL varchar(5000);
declare variable WCODEMP integer;
declare variable WCODCHAVE integer;
declare variable WPARTENQFED DM_BOOLEAN;
declare variable WCODPLANODEV varchar(100);
declare variable WPLANO integer;
declare variable WCONSUFINAL integer;
declare variable WTODASCFOP DM_BOOLEAN;
declare variable WTODASNCM DM_BOOLEAN;
declare variable WTODOSTER DM_BOOLEAN;
declare variable WTODOSPROD DM_BOOLEAN;
declare variable WTODASCST DM_BOOLEAN;
declare variable WCHAVEDEV integer;
BEGIN

  FOR  /*PEGA AS CONFIGURAÇÕES DO PLANO*/
    SELECT PLA.BDCODPLANOCONFADRCST,ADRCST.BDCODEMP, PLA.BDCHAVE, PLA.BDPARTENQFED, PLA.BDCONSUFINAL,
    IIF((SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASCFOP,
    IIF((SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASNCM,
    IIF((SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODOSTER,
    IIF((SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODOSPROD,
    IIF((SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASCST
    FROM VEF_BASE_TPLANOACOESCONFADRCST PLA
    LEFT OUTER JOIN TMP_VEF_EMP_TADRCSTGER_TEMP ADRCST ON (ADRCST.BDSESSAO = :PRSESSAO)
    WHERE PLA.BDCODPLANOCONFADRCST = ADRCST.BDCODPLACONFADRCST
    AND PLA.BDCODPROCESSO = 5 /*PROCESSO DAS SAÍDAS SIMPLES NACIONAL*/
    INTO :WPLANO,:WCODEMP, :WCODCHAVE, :WPARTENQFED, :WCONSUFINAL, :WTODASCFOP, :WTODASNCM, :WTODOSTER, :WTODOSPROD, :WTODASCST
  DO
    BEGIN
      /*Pega somente a CFOP do processo de devolução*/
      WCODPLANODEV = '';
      FOR
        SELECT PLA.BDCHAVE FROM VEF_BASE_TPLANOACOESCONFADRCST PLA WHERE PLA.BDCODPLANOCONFADRCST = :WPLANO AND PLA.BDCODPROCESSO = 1
        INTO :WCHAVEDEV
      DO
      BEGIN
        IF (:WCODPLANODEV <> '') THEN
           WCODPLANODEV = :WCODPLANODEV || ',';

         WCODPLANODEV =  :WCODPLANODEV || :WCHAVEDEV;
      END

     /*BDTIPO NFE - 0 ENTRADA - 1 SAÍDA*/


     /*INSERE OS LANÇAMENTO DE SAÍDA CONFORME O PLANO NO 1510 E 1520*/
     WSQL = ' INSERT INTO TMP_VEF_EMP_TADRCST_1500_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, ';
     WSQL = WSQL|| ' BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT, BDVLRICMSEFETIVO, BDTIPONFE, BDCODINCONSISTENCIA,BDCHAVENFE) ';
     WSQL = WSQL|| ' SELECT T1000.BDSESSAO, SAI.BDCODEMP, SAI.BDREFLAN, PRO.BDCODPROD, SAI.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, SAI.BDDATAEMISSAO, ICMS.BDCODCSTICMS, SAI.BDNUMDOCINI, EMP.BDCNPJEMP, UF.BDSIGLAUF, TER.BDCGCTER,UFT.BDSIGLAUF, ';
     WSQL = WSQL|| ' I.BDCODNAT, COALESCE(UNMF.BDAPEUNIMED, UNMP.BDAPEUNIMED) BDUNIMED,PRO.BDQTDITEM, ((PRO.BDVLRITEM - PRO.BDVLRDESC)/IIF(COALESCE(PRO.BDQTDITEM, 0) = 0, 1, PRO.BDQTDITEM)) BDVLRUNIT, ';
     WSQL = WSQL|| ' IIF(COALESCE(PRO.BDVLRICMS,0) = 0,((PRO.BDVLRITEM - PRO.BDVLRDESC)/IIF(COALESCE(PRO.BDQTDITEM, 0) = 0, 1, PRO.BDQTDITEM))*T1000.BDALIQICMS,(PRO.BDVLRICMS * T1000.BDALIQICMS)) BDVLRICMSEFETIVO, 1,IIF(COALESCE(TER.BDORGAOPUBLICO,''FALSE'') = ''FALSE'',21,NULL), (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(SAI.BDCHAVENFE)) BDCHAVENFE ';
     WSQL = WSQL|| ' FROM (SELECT *';
     WSQL = WSQL|| '       FROM TMP_VEF_EMP_TADRCST_1000_TEMP T1000';
     WSQL = WSQL|| '       WHERE T1000.BDSESSAO = '||:PRSESSAO||' AND';
     WSQL = WSQL|| '             T1000.BDCODEMP = '||:WCODEMP||') T1000';
     WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (T1000.BDCODEMP = SAI.BDCODEMP AND T1000.BDCHAVE = SAI.BDCHAVE)';
     WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE AND I.BDORDEM = T1000.BDORDEM) ';
     WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = T1000.BDORDEM AND PRO.BDORDEMPRO = T1000.BDORDEMPROD)';
     WSQL = WSQL|| ' LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = SAI.BDCODTER)';
     WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS) ';
     WSQL = WSQL|| ' JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = SAI.BDCODEMP) ';
     WSQL = WSQL|| ' JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID) ';
     WSQL = WSQL|| ' JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF) ';
     WSQL = WSQL|| ' JOIN TCIDADE CIDT ON (CIDT.BDCODCID = TER.BDCODCID) ';
     WSQL = WSQL|| ' JOIN TUF UFT ON (UFT.BDCODUF = CIDT.BDCODUF) ';
     WSQL = WSQL|| ' LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODEMP = SAI.BDCODEMP AND FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON) ';
     WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMF ON (UNMF.BDCODUNIMED = FAT.BDCODUNIMED) ';
     WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMP ON (UNMP.BDCODUNIMED = T1000.BDCODUNIMED)';
     WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT) ';
     WSQL = WSQL|| ' WHERE SAI.BDMODELO = 55';
     WSQL = WSQL|| ' AND SAI.BDDATAEMISSAO BETWEEN '''||:PRDATAINI||''' AND '''||:PRDATAFIM||'''';
     IF (:WCONSUFINAL = 1) THEN
        WSQL = WSQL|| ' AND COALESCE(SAI.BDCONSUFINAL,0) = '|| :WCONSUFINAL;
     ELSE
        WSQL = WSQL|| ' AND COALESCE(SAI.BDCONSUFINAL,0) IN (-1,0) ';
     WSQL = WSQL|| ' AND SAI.BDCODSITNF NOT IN (2,3,4,5)';
     WSQL = WSQL|| ' AND NAT.BDDEVOL = ''FALSE'' ';
     
     WSQL = WSQL|| ' AND NOT EXISTS (SELECT BDCODEMP FROM TMP_VEF_EMP_TADRCST_1500_TEMP T WHERE T.BDSESSAO = T1000.BDSESSAO AND T.BDCODEMP = T1000.BDCODEMP AND T.BDCHAVE = SAI.BDCHAVE AND T.BDORDEM = PRO.BDORDEM AND T.BDORDEMPROD = PRO.BDORDEMPRO )';     

     IF (:WPARTENQFED = 'TRUE' ) THEN                  /*ME - EPP*/
        WSQL = WSQL|| ' AND (TER.BDENQSIMPLESFEDTER IN (0,1))';
     ELSE IF (:WTODOSTER = 'FALSE') THEN
        WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODTER = SAI.BDCODTER) ';

     IF (:WTODASCFOP = 'FALSE') THEN
        WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNAT = I.BDCODNAT) ';
     IF (:WTODASNCM = 'FALSE') THEN
        WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNCM = T1000.BDNCMPROD) ';
     IF (:WTODOSPROD = 'FALSE') THEN
        WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODPROD = T1000.BDCODPROD) ';
     IF (:WTODASCST = 'FALSE') THEN
        WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCSTICMS = PRO.BDCODCSTICMS) ';

     EXECUTE STATEMENT(WSQL);

         /*NOTAS DE DEVOLUÇÃO DE ENTRADA - SOMENTE PELO C113*/
         WSQL = ' INSERT INTO TMP_VEF_EMP_TADRCST_1500_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, ';
         WSQL = WSQL|| ' BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT, BDVLRICMSEFETIVO, BDCHAVENFEREFC113,BDNUMITEMREFC113, BDCODINCONSISTENCIA, BDTIPONFE,BDCHAVENFE) ';

         WSQL = WSQL|| ' SELECT  T1000.BDSESSAO, ENT.BDCODEMP, ENT.BDREFLAN, T1000.BDCODPROD, ENT.BDCHAVE, T1000.BDORDEM, PRO.BDORDEMPRO, ENT.BDDATAEMISSAO, ICMS.BDCODCSTICMS, ENT.BDNUMDOCINI, TER.BDCGCTER,UFT.BDSIGLAUF, EMP.BDCNPJEMP, UF.BDSIGLAUF,  ';
         WSQL = WSQL|| ' I.BDCODNAT, COALESCE(UNMF.BDAPEUNIMED, UNMP.BDAPEUNIMED) BDUNIMED,PRO.BDQTDITEM, ((PRO.BDVLRITEM - PRO.BDVLRDESC)/IIF(COALESCE(PRO.BDQTDITEM, 0) = 0, 1, PRO.BDQTDITEM)) BDVLRUNIT, IIF(COALESCE(PRO.BDVLRICMS,0) = 0,((PRO.BDVLRITEM - PRO.BDVLRDESC)/IIF(COALESCE(PRO.BDQTDITEM, 0) = 0, 1, PRO.BDQTDITEM))*PRO.BDALIQICMS,(PRO.BDVLRICMS * PRO.BDALIQICMS)) BDVLRICMSEFETIVO, ';
         WSQL = WSQL|| ' (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) BDCHAVENFEREFC113,PROREF.BDORDEMPRO,IIF(C113.BDCODEMP IS NULL, 20,IIF((C113.BDCODEMP IS NOT NULL) AND (select BDAAAAMM FROM AAAAMM(C113.bddtemissao)) <> (select BDAAAAMM FROM AAAAMM('''||:PRDATAINI||''')),23,NULL)) BDINCO, 0, (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(ENT.BDCHAVENFE)) BDCHAVENFE  ';
         WSQL = WSQL|| ' FROM (SELECT T1000.BDCODEMP,T1000.BDSESSAO, T1000.BDCODPROD, T1000.BDREFERENCIA, PRO.BDCHAVE, PRO.BDORDEM,  T1000.BDCODUNIMED,T1000.BDNCMPROD  ';
         WSQL = WSQL|| '       FROM TMP_VEF_EMP_TADRCST_1000_TEMP T1000 ';
         WSQL = WSQL|| '       LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = T1000.BDCODEMP AND PRO.BDCODPROD = T1000.BDCODPROD) ';
         WSQL = WSQL|| '       WHERE T1000.BDSESSAO = '||:PRSESSAO||' AND ';
         WSQL = WSQL|| '             T1000.BDCODEMP = '||:WCODEMP;
         WSQL = WSQL|| '       GROUP BY T1000.BDCODEMP,T1000.BDSESSAO, T1000.BDCODPROD, T1000.BDREFERENCIA, PRO.BDCHAVE, PRO.BDORDEM, T1000.BDCODUNIMED,T1000.BDNCMPROD ';
         WSQL = WSQL|| '       ) T1000 ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = T1000.BDCODEMP AND PRO.BDCHAVE = T1000.BDCHAVE AND PRO.BDORDEM = T1000.BDORDEM) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE AND I.BDORDEM = PRO.BDORDEM) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = ENT.BDCODEMP AND C113.BDCHAVE = ENT.BDCHAVE /*AND (SELECT BDAAAAMM FROM AAAAMM(C113.BDDTEMISSAO)) = T1000.BDREFERENCIA*/) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = ENT.BDCODTER) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS) ';
         WSQL = WSQL|| ' JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = ENT.BDCODEMP) ';
         WSQL = WSQL|| ' JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID) ';
         WSQL = WSQL|| ' JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF) ';
         WSQL = WSQL|| ' JOIN TCIDADE CIDT ON (CIDT.BDCODCID = TER.BDCODCID) ';
         WSQL = WSQL|| ' JOIN TUF UFT ON (UFT.BDCODUF = CIDT.BDCODUF) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODEMP = ENT.BDCODEMP AND FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMF ON (UNMF.BDCODUNIMED = FAT.BDCODUNIMED) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMP ON (UNMP.BDCODUNIMED = T1000.BDCODUNIMED) ';
         -- Alt.: #171712 - Olhar descrição em "SP_APURACAO_ADRCST_PR_1000"...
         --WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = C113.BDCODEMP /*AND SAI.BDREFLAN = ENT.BDREFLAN*/) ';
         --WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PROREF ON (PROREF.BDCODEMP = SAI.BDCODEMP AND PROREF.BDCHAVE = SAI.BDCHAVE AND PROREF.BDCODPROD = PRO.BDCODPROD) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP SAI ON (SAI.BDSESSAO = -1 AND SAI.BDCODEMP = C113.BDCODEMP /*AND SAI.BDREFLAN = ENT.BDREFLAN*/) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TMP_VEF_EMP_TMOVPROSAI PROREF ON (PROREF.BDSESSAO = -1 AND PROREF.BDCODEMP = SAI.BDCODEMP AND PROREF.BDCHAVE = SAI.BDCHAVE AND PROREF.BDCODPROD = PRO.BDCODPROD) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT) ';
         WSQL = WSQL|| ' WHERE ENT.BDREFLAN = T1000.BDREFERENCIA ';
         WSQL = WSQL|| ' AND ENT.BDMODELO = 55 ';
         WSQL = WSQL|| ' AND ENT.BDDATAEMISSAO BETWEEN '''||:PRDATAINI||''' AND '''||:PRDATAFIM||'''';
         WSQL = WSQL|| ' AND ENT.BDCODSITNF NOT IN (2,3,4,5) ';
         WSQL = WSQL|| ' AND NAT.BDDEVOL = ''TRUE'' ';
         IF (:WCONSUFINAL = 1) THEN
            WSQL = WSQL|| ' AND COALESCE(ENT.BDCONSUFINAL,0) = '|| :WCONSUFINAL;
         ELSE
            WSQL = WSQL|| ' AND COALESCE(ENT.BDCONSUFINAL,0) IN (-1,0) ';
         WSQL = WSQL|| ' AND SUBSTRING(I.BDCODNAT FROM 1 FOR 1) = 1 '; /*Operação interna*/
         WSQL = WSQL|| ' AND ((SAI.BDNUMDOCINI = C113.BDNUMDOC AND COALESCE(SAI.BDCHAVENFE,0) = IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '''', 0, C113.BDCHAVENFE) ';
         WSQL = WSQL|| ' AND SAI.BDDATAEMISSAO = C113.BDDTEMISSAO) OR (C113.bdcodemp IS NULL))';
         WSQL = WSQL|| ' AND NOT EXISTS (SELECT BDCODEMP FROM TMP_VEF_EMP_TADRCST_1500_TEMP T WHERE T.BDSESSAO = T1000.BDSESSAO AND T.BDCODEMP = T1000.BDCODEMP AND T.BDCHAVE = ENT.BDCHAVE AND T.BDORDEM = T1000.BDORDEM AND T.BDORDEMPROD = PRO.BDORDEMPRO )';         

         IF (:WPARTENQFED = 'TRUE' ) THEN
            WSQL = WSQL|| ' AND (TER.BDENQSIMPLESFEDTER IN (0,1))';
         ELSE IF (:WTODOSTER = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODTER = ENT.BDCODTER) ';
    
         IF (:WTODASNCM = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNCM = T1000.BDNCMPROD) ';
         IF (:WTODOSPROD = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODPROD = T1000.BDCODPROD) ';
         IF (:WTODASCST = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCSTICMS = PRO.BDCODCSTICMS) ';

         IF (:WCODPLANODEV <> '') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE IN ('||WCODPLANODEV||') AND VINC.BDCODNAT = I.BDCODNAT) ';

         EXECUTE STATEMENT(WSQL);


    END
END
^

CREATE OR ALTER procedure SP_APURACAO_ADRCST_PR_1410_1420 (
    PRSESSAO integer,
    PRDATAINI date,
    PRDATAFIM date)
as
declare variable WSQL varchar(5000);
declare variable WCODEMP integer;
declare variable WCODCHAVE integer;
declare variable WPARTENQFED DM_BOOLEAN;
declare variable WCODPLANODEV varchar(100);
declare variable WPLANO integer;
declare variable WCONSUFINAL integer;
declare variable WTODASCFOP DM_BOOLEAN;
declare variable WTODASNCM DM_BOOLEAN;
declare variable WTODOSTER DM_BOOLEAN;
declare variable WTODOSPROD DM_BOOLEAN;
declare variable WTODASCST DM_BOOLEAN;
declare variable WCHAVEDEV integer;
BEGIN

  FOR  /*PEGA AS CONFIGURAÇÕES DO PLANO*/
    SELECT PLA.BDCODPLANOCONFADRCST,ADRCST.BDCODEMP, PLA.BDCHAVE, PLA.BDPARTENQFED, PLA.BDCONSUFINAL,
    IIF((SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASCFOP,
    IIF((SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASNCM,
    IIF((SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODOSTER,
    IIF((SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODOSPROD,
    IIF((SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASCST
    FROM VEF_BASE_TPLANOACOESCONFADRCST PLA
    LEFT OUTER JOIN TMP_VEF_EMP_TADRCSTGER_TEMP ADRCST ON (ADRCST.BDSESSAO = :PRSESSAO)
    WHERE PLA.BDCODPLANOCONFADRCST = ADRCST.BDCODPLACONFADRCST
    AND PLA.BDCODPROCESSO = 2 /*PROCESSO DAS Saídas art. 119*/
    INTO :WPLANO,:WCODEMP, :WCODCHAVE, :WPARTENQFED, :WCONSUFINAL, :WTODASCFOP, :WTODASNCM, :WTODOSTER, :WTODOSPROD, :WTODASCST
  DO
    BEGIN
      /*Pega somente a CFOP do processo de devolução*/
      WCODPLANODEV = '';
      FOR
        SELECT PLA.BDCHAVE FROM VEF_BASE_TPLANOACOESCONFADRCST PLA WHERE PLA.BDCODPLANOCONFADRCST = :WPLANO AND PLA.BDCODPROCESSO = 1
        INTO :WCHAVEDEV
      DO
      BEGIN
        IF (:WCODPLANODEV <> '') THEN
           WCODPLANODEV = :WCODPLANODEV || ',';

         WCODPLANODEV =  :WCODPLANODEV || :WCHAVEDEV;
      END

     /*BDTIPO NFE - 0 ENTRADA - 1 SAÍDA*/


     /*INSERE OS LANÇAMENTO DE SAÍDA CONFORME O PLANO NO 1410 E 1420*/
     WSQL = ' INSERT INTO TMP_VEF_EMP_TADRCST_1400_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, ';
     WSQL = WSQL|| ' BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT, BDVLRICMSEFETIVO, BDTIPONFE, BDCODINCONSISTENCIA,BDCHAVENFE) ';
     WSQL = WSQL|| ' SELECT T1000.BDSESSAO, SAI.BDCODEMP, SAI.BDREFLAN, PRO.BDCODPROD, SAI.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, SAI.BDDATAEMISSAO, ICMS.BDCODCSTICMS, SAI.BDNUMDOCINI, EMP.BDCNPJEMP, UF.BDSIGLAUF, TER.BDCGCTER,UFT.BDSIGLAUF, ';
     WSQL = WSQL|| ' I.BDCODNAT, COALESCE(UNMF.BDAPEUNIMED, UNMP.BDAPEUNIMED) BDUNIMED,PRO.BDQTDITEM, ((PRO.BDVLRITEM - PRO.BDVLRDESC)/IIF(COALESCE(PRO.BDQTDITEM, 0) = 0, 1, PRO.BDQTDITEM)) BDVLRUNIT, ';
     WSQL = WSQL|| ' IIF(T1000.BDALIQICMS > 0, IIF(COALESCE(PRO.BDBCICMS,0) = 0,(PRO.BDVLRITEM - PRO.BDVLRDESC)*(T1000.BDALIQICMS/100),(PRO.BDBCICMS * (T1000.BDALIQICMS/100))),0) BDVLRICMSEFETIVO, 1,IIF(COALESCE(TER.BDORGAOPUBLICO,''FALSE'') = ''FALSE'',21,NULL), (SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(SAI.BDCHAVENFE)) BDCHAVENFE ';
     WSQL = WSQL|| ' FROM (SELECT *';
     WSQL = WSQL|| '       FROM TMP_VEF_EMP_TADRCST_1000_TEMP T1000';
     WSQL = WSQL|| '       WHERE T1000.BDSESSAO = '||:PRSESSAO||' AND';
     WSQL = WSQL|| '             T1000.BDCODEMP = '||:WCODEMP||') T1000';
     WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (T1000.BDCODEMP = SAI.BDCODEMP AND T1000.BDCHAVE = SAI.BDCHAVE)';
     WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE AND I.BDORDEM = T1000.BDORDEM) ';
     WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = T1000.BDORDEM AND PRO.BDORDEMPRO = T1000.BDORDEMPROD)';
     WSQL = WSQL|| ' LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = SAI.BDCODTER)';
     WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS) ';
     WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT) ';
     WSQL = WSQL|| ' JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = SAI.BDCODEMP) ';
     WSQL = WSQL|| ' JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID) ';
     WSQL = WSQL|| ' JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF) ';
     WSQL = WSQL|| ' JOIN TCIDADE CIDT ON (CIDT.BDCODCID = TER.BDCODCID) ';
     WSQL = WSQL|| ' JOIN TUF UFT ON (UFT.BDCODUF = CIDT.BDCODUF) ';
     WSQL = WSQL|| ' LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODEMP = SAI.BDCODEMP AND FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON) ';
     WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMF ON (UNMF.BDCODUNIMED = FAT.BDCODUNIMED) ';
     WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMP ON (UNMP.BDCODUNIMED = T1000.BDCODUNIMED)';
     WSQL = WSQL|| ' WHERE SAI.BDMODELO IN (55, 65)';
     WSQL = WSQL|| ' AND SAI.BDDATAEMISSAO BETWEEN '''||:PRDATAINI||''' AND '''||:PRDATAFIM||'''';
     WSQL = WSQL|| ' AND NAT.BDDEVOL = ''FALSE'' ';
     IF (:WCONSUFINAL = 1) THEN
        WSQL = WSQL|| ' AND COALESCE(SAI.BDCONSUFINAL,0) = '|| :WCONSUFINAL;
     ELSE
        WSQL = WSQL|| ' AND COALESCE(SAI.BDCONSUFINAL,0) IN (-1,0) ';
     WSQL = WSQL|| ' AND SAI.BDCODSITNF NOT IN (2,3,4,5)';
     
     WSQL = WSQL|| ' AND NOT EXISTS (SELECT BDCODEMP FROM TMP_VEF_EMP_TADRCST_1400_TEMP T WHERE T.BDSESSAO = T1000.BDSESSAO AND T.BDCODEMP = T1000.BDCODEMP AND T.BDCHAVE = SAI.BDCHAVE AND T.BDORDEM = PRO.BDORDEM AND T.BDORDEMPROD = PRO.BDORDEMPRO )';     

     IF (:WPARTENQFED = 'TRUE' ) THEN
         WSQL = WSQL|| ' AND (TER.BDENQSIMPLESFEDTER = 2)';
     ELSE IF (:WTODOSTER = 'FALSE') THEN
        WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODTER = SAI.BDCODTER) ';

     IF (:WTODASCFOP = 'FALSE') THEN
        WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNAT = I.BDCODNAT) ';
     IF (:WTODASNCM = 'FALSE') THEN
        WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNCM = T1000.BDNCMPROD) ';
     IF (:WTODOSPROD = 'FALSE') THEN
        WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODPROD = T1000.BDCODPROD) ';
     IF (:WTODASCST = 'FALSE') THEN
        WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCSTICMS = PRO.BDCODCSTICMS) ';

     EXECUTE STATEMENT(WSQL);

         /*NOTAS DE DEVOLUÇÃO DE ENTRADA - SOMENTE PELO C113*/
         WSQL = ' INSERT INTO TMP_VEF_EMP_TADRCST_1400_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, ';
         WSQL = WSQL|| ' BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT, BDVLRICMSEFETIVO, BDCHAVENFEREFC113,BDNUMITEMREFC113, BDCODINCONSISTENCIA, BDTIPONFE,BDCHAVENFE) ';

         WSQL = WSQL|| ' SELECT  T1000.BDSESSAO, ENT.BDCODEMP, ENT.BDREFLAN, T1000.BDCODPROD, ENT.BDCHAVE, T1000.BDORDEM, PRO.BDORDEMPRO, ENT.BDDATAEMISSAO, ICMS.BDCODCSTICMS, ENT.BDNUMDOCINI, TER.BDCGCTER,UFT.BDSIGLAUF, EMP.BDCNPJEMP, UF.BDSIGLAUF,  ';
         WSQL = WSQL|| ' I.BDCODNAT, COALESCE(UNMF.BDAPEUNIMED, UNMP.BDAPEUNIMED) BDUNIMED,PRO.BDQTDITEM, ((PRO.BDVLRITEM - PRO.BDVLRDESC)/IIF(COALESCE(PRO.BDQTDITEM, 0) = 0, 1, PRO.BDQTDITEM)) BDVLRUNIT, IIF(COALESCE(PRO.BDVLRICMS,0) = 0,((PRO.BDVLRITEM - PRO.BDVLRDESC)/IIF(COALESCE(PRO.BDQTDITEM, 0) = 0, 1, PRO.BDQTDITEM))*PRO.BDALIQICMS,(PRO.BDVLRICMS * PRO.BDALIQICMS)) BDVLRICMSEFETIVO, ';
         WSQL = WSQL|| ' (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) BDCHAVENFEC113,PROREF.BDORDEMPRO,IIF(C113.BDCODEMP IS NULL, 20,IIF((C113.BDCODEMP IS NOT NULL) AND (select BDAAAAMM FROM AAAAMM(C113.bddtemissao)) <> (select BDAAAAMM FROM AAAAMM('''||:PRDATAINI||''')),23,NULL)) BDINCO, 0, (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(ENT.BDCHAVENFE)) BDCHAVENFE ';
         WSQL = WSQL|| ' FROM (SELECT T1000.BDCODEMP,T1000.BDSESSAO, T1000.BDCODPROD, T1000.BDREFERENCIA, PRO.BDCHAVE, PRO.BDORDEM,  T1000.BDCODUNIMED,T1000.BDNCMPROD ';
         WSQL = WSQL|| '       FROM TMP_VEF_EMP_TADRCST_1000_TEMP T1000 ';
         WSQL = WSQL|| '       LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = T1000.BDCODEMP AND PRO.BDCODPROD = T1000.BDCODPROD) ';
         WSQL = WSQL|| '       WHERE T1000.BDSESSAO = '||:PRSESSAO||' AND ';
         WSQL = WSQL|| '             T1000.BDCODEMP = '||:WCODEMP;
         WSQL = WSQL|| '       GROUP BY T1000.BDCODEMP,T1000.BDSESSAO, T1000.BDCODPROD, T1000.BDREFERENCIA, PRO.BDCHAVE, PRO.BDORDEM, T1000.BDCODUNIMED,T1000.BDNCMPROD ';
         WSQL = WSQL|| '       ) T1000 ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = T1000.BDCODEMP AND PRO.BDCHAVE = T1000.BDCHAVE AND PRO.BDORDEM = T1000.BDORDEM) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE AND I.BDORDEM = PRO.BDORDEM) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = ENT.BDCODEMP AND C113.BDCHAVE = ENT.BDCHAVE /*AND (SELECT BDAAAAMM FROM AAAAMM(C113.BDDTEMISSAO)) = T1000.BDREFERENCIA*/) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = ENT.BDCODTER) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS) ';
         WSQL = WSQL|| ' JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = ENT.BDCODEMP) ';
         WSQL = WSQL|| ' JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID) ';
         WSQL = WSQL|| ' JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF) ';
         WSQL = WSQL|| ' JOIN TCIDADE CIDT ON (CIDT.BDCODCID = TER.BDCODCID) ';
         WSQL = WSQL|| ' JOIN TUF UFT ON (UFT.BDCODUF = CIDT.BDCODUF) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODEMP = ENT.BDCODEMP AND FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMF ON (UNMF.BDCODUNIMED = FAT.BDCODUNIMED) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMP ON (UNMP.BDCODUNIMED = T1000.BDCODUNIMED) ';
         -- Alt.: #171712 - Olhar descrição em "SP_APURACAO_ADRCST_PR_1000"...
         --WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = C113.BDCODEMP /*AND SAI.BDREFLAN = ENT.BDREFLAN*/) ';
         --WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PROREF ON (PROREF.BDCODEMP = SAI.BDCODEMP AND PROREF.BDCHAVE = SAI.BDCHAVE AND PROREF.BDCODPROD = PRO.BDCODPROD) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP SAI ON (SAI.BDSESSAO = -1 AND SAI.BDCODEMP = C113.BDCODEMP /*AND SAI.BDREFLAN = ENT.BDREFLAN*/) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TMP_VEF_EMP_TMOVPROSAI PROREF ON (PROREF.BDSESSAO = -1 AND PROREF.BDCODEMP = SAI.BDCODEMP AND PROREF.BDCHAVE = SAI.BDCHAVE AND PROREF.BDCODPROD = PRO.BDCODPROD) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT) ';
         WSQL = WSQL|| ' WHERE ENT.BDREFLAN = T1000.BDREFERENCIA ';
         WSQL = WSQL|| ' AND ENT.BDMODELO = 55 ';
         WSQL = WSQL|| ' AND ENT.BDDATAEMISSAO BETWEEN '''||:PRDATAINI||''' AND '''||:PRDATAFIM||'''';
         WSQL = WSQL|| ' AND ENT.BDCODSITNF NOT IN (2,3,4,5) ';
         WSQL = WSQL|| ' AND NAT.BDDEVOL = ''TRUE'' ';
         IF (:WCONSUFINAL = 1) THEN
            WSQL = WSQL|| ' AND COALESCE(ENT.BDCONSUFINAL,0) = '|| :WCONSUFINAL;
         ELSE
            WSQL = WSQL|| ' AND COALESCE(ENT.BDCONSUFINAL,0) IN (-1,0) ';
         WSQL = WSQL|| ' AND SUBSTRING(I.BDCODNAT FROM 1 FOR 1) = 1 '; /*Operação interna*/
         WSQL = WSQL|| ' AND ((SAI.BDNUMDOCINI = C113.BDNUMDOC AND COALESCE(SAI.BDCHAVENFE,0) = IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '''', 0, C113.BDCHAVENFE) ';
         WSQL = WSQL|| ' AND SAI.BDDATAEMISSAO = C113.BDDTEMISSAO) OR (C113.bdcodemp IS NULL))';
        WSQL = WSQL|| ' AND NOT EXISTS (SELECT BDCODEMP FROM TMP_VEF_EMP_TADRCST_1400_TEMP T WHERE T.BDSESSAO = T1000.BDSESSAO AND T.BDCODEMP = T1000.BDCODEMP AND T.BDCHAVE = ENT.BDCHAVE AND T.BDORDEM = T1000.BDORDEM AND T.BDORDEMPROD = PRO.BDORDEMPRO )';

        IF (:WPARTENQFED = 'TRUE' ) THEN
            WSQL = WSQL|| ' AND (TER.BDENQSIMPLESFEDTER = 2)';
        ELSE IF (:WTODOSTER = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODTER = ENT.BDCODTER) ';
    
         IF (:WTODASNCM = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNCM = T1000.BDNCMPROD) ';
         IF (:WTODOSPROD = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODPROD = T1000.BDCODPROD) ';
         IF (:WTODASCST = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCSTICMS = PRO.BDCODCSTICMS) ';

         IF (:WCODPLANODEV <> '') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE IN ('||WCODPLANODEV||') AND VINC.BDCODNAT = I.BDCODNAT) ';

         EXECUTE STATEMENT(WSQL);


    END
END
^

CREATE OR ALTER procedure SP_APURACAO_ADRCST_PR_1310_1320 (
    PRSESSAO integer,
    PRDATAINI date,
    PRDATAFIM date)
as
declare variable WSQL varchar(5000);
declare variable WCODEMP integer;
declare variable WCODCHAVE integer;
declare variable WPARTENQFED DM_BOOLEAN;
declare variable WCODPLANODEV varchar(100);
declare variable WPLANO integer;
declare variable WCONSUFINAL integer;
declare variable WTODASCFOP DM_BOOLEAN;
declare variable WTODASNCM DM_BOOLEAN;
declare variable WTODOSTER DM_BOOLEAN;
declare variable WTODOSPROD DM_BOOLEAN;
declare variable WTODASCST DM_BOOLEAN;
declare variable WCHAVEDEV integer;
BEGIN

  FOR  /*PEGA AS CONFIGURAÇÕES DO PLANO*/
    SELECT PLA.BDCODPLANOCONFADRCST,ADRCST.BDCODEMP, PLA.BDCHAVE, PLA.BDPARTENQFED, PLA.BDCONSUFINAL,
    IIF((SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASCFOP,
    IIF((SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASNCM,
    IIF((SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODOSTER,
    IIF((SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODOSPROD,
    IIF((SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASCST
    FROM VEF_BASE_TPLANOACOESCONFADRCST PLA
    LEFT OUTER JOIN TMP_VEF_EMP_TADRCSTGER_TEMP ADRCST ON (ADRCST.BDSESSAO = :PRSESSAO)
    WHERE PLA.BDCODPLANOCONFADRCST = ADRCST.BDCODPLACONFADRCST
    AND PLA.BDCODPROCESSO = 4 /*PROCESSO DAS SAÍDAS INTERESTADUAIS*/
    INTO :WPLANO,:WCODEMP, :WCODCHAVE, :WPARTENQFED, :WCONSUFINAL, :WTODASCFOP, :WTODASNCM, :WTODOSTER, :WTODOSPROD, :WTODASCST
  DO
    BEGIN
      /*Pega somente a CFOP do processo de devolução*/
      WCODPLANODEV = '';
      FOR
        SELECT PLA.BDCHAVE FROM VEF_BASE_TPLANOACOESCONFADRCST PLA WHERE PLA.BDCODPLANOCONFADRCST = :WPLANO AND PLA.BDCODPROCESSO = 1
        INTO :WCHAVEDEV
      DO
      BEGIN
        IF (:WCODPLANODEV <> '') THEN
           WCODPLANODEV = :WCODPLANODEV || ',';

         WCODPLANODEV =  :WCODPLANODEV || :WCHAVEDEV;
      END

     /*BDTIPO NFE - 0 ENTRADA - 1 SAÍDA*/


     /*INSERE OS LANÇAMENTO DE SAÍDA CONFORME O PLANO NO 1310 E 1320*/
     WSQL = ' INSERT INTO TMP_VEF_EMP_TADRCST_1300_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, ';
     WSQL = WSQL|| ' BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT, BDVLRICMSEFETIVO, BDTIPONFE,BDCHAVENFE) ';
     WSQL = WSQL|| ' SELECT T1000.BDSESSAO, SAI.BDCODEMP, SAI.BDREFLAN, PRO.BDCODPROD, SAI.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, SAI.BDDATAEMISSAO, ICMS.BDCODCSTICMS, SAI.BDNUMDOCINI, EMP.BDCNPJEMP, UF.BDSIGLAUF, TER.BDCGCTER,UFT.BDSIGLAUF, ';
     WSQL = WSQL|| ' I.BDCODNAT, COALESCE(UNMF.BDAPEUNIMED, UNMP.BDAPEUNIMED) BDUNIMED,PRO.BDQTDITEM, ((PRO.BDVLRITEM - PRO.BDVLRDESC)/IIF(COALESCE(PRO.BDQTDITEM, 0) = 0, 1, PRO.BDQTDITEM)) BDVLRUNIT, ';
     WSQL = WSQL|| ' /*IIF(COALESCE(PRO.BDVLRICMS,0) = 0,((PRO.BDVLRITEM - PRO.BDVLRDESC)/IIF(COALESCE(PRO.BDQTDITEM, 0) = 0, 1, PRO.BDQTDITEM))*T1000.BDALIQICMS,(PRO.BDVLRICMS * T1000.BDALIQICMS))*/PRO.BDVLRICMS BDVLRICMSEFETIVO, 1, (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(SAI.BDCHAVENFE)) BDCHAVENFE ';
     WSQL = WSQL|| ' FROM (SELECT *';
     WSQL = WSQL|| '       FROM TMP_VEF_EMP_TADRCST_1000_TEMP T1000';
     WSQL = WSQL|| '       WHERE T1000.BDSESSAO = '||:PRSESSAO||' AND';
     WSQL = WSQL|| '             T1000.BDCODEMP = '||:WCODEMP||') T1000';
     WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (T1000.BDCODEMP = SAI.BDCODEMP AND T1000.BDCHAVE = SAI.BDCHAVE)';
     WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE AND I.BDORDEM = T1000.BDORDEM) ';
     WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = T1000.BDORDEM AND PRO.BDORDEMPRO = T1000.BDORDEMPROD)';
     WSQL = WSQL|| ' LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = SAI.BDCODTER)';
     WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS) ';
     WSQL = WSQL|| ' JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = SAI.BDCODEMP) ';
     WSQL = WSQL|| ' JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID) ';
     WSQL = WSQL|| ' JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF) ';
     WSQL = WSQL|| ' JOIN TCIDADE CIDT ON (CIDT.BDCODCID = TER.BDCODCID) ';
     WSQL = WSQL|| ' JOIN TUF UFT ON (UFT.BDCODUF = CIDT.BDCODUF) ';
     WSQL = WSQL|| ' LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODEMP = SAI.BDCODEMP AND FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON) ';
     WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMF ON (UNMF.BDCODUNIMED = FAT.BDCODUNIMED) ';
     WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMP ON (UNMP.BDCODUNIMED = T1000.BDCODUNIMED)';
     WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT) ';
     WSQL = WSQL|| ' WHERE SAI.BDMODELO IN (55, 65)';
     WSQL = WSQL|| ' AND SAI.BDDATAEMISSAO BETWEEN '''||:PRDATAINI||''' AND '''||:PRDATAFIM||'''';
     WSQL = WSQL|| ' AND NAT.BDDEVOL = ''FALSE'' ';
     IF (:WCONSUFINAL = 1) THEN
        WSQL = WSQL|| ' AND COALESCE(SAI.BDCONSUFINAL,0) = '|| :WCONSUFINAL;
     ELSE
        WSQL = WSQL|| ' AND COALESCE(SAI.BDCONSUFINAL,0) IN (-1,0) ';
     WSQL = WSQL|| ' AND SAI.BDCODSITNF NOT IN (2,3,4,5)';
     WSQL = WSQL|| ' AND NOT EXISTS (SELECT BDCODEMP FROM TMP_VEF_EMP_TADRCST_1300_TEMP T WHERE T.BDSESSAO = T1000.BDSESSAO AND T.BDCODEMP = T1000.BDCODEMP AND T.BDCHAVE = SAI.BDCHAVE AND T.BDORDEM = PRO.BDORDEM AND T.BDORDEMPROD = PRO.BDORDEMPRO )';     

     IF (:WPARTENQFED = 'TRUE' ) THEN
        WSQL = WSQL|| ' AND (TER.BDENQSIMPLESFEDTER = 2)';
     ELSE IF (:WTODOSTER = 'FALSE') THEN
        WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODTER = SAI.BDCODTER) ';

     IF (:WTODASCFOP = 'FALSE') THEN
        WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNAT = I.BDCODNAT) ';
     IF (:WTODASNCM = 'FALSE') THEN
        WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNCM = T1000.BDNCMPROD) ';
     IF (:WTODOSPROD = 'FALSE') THEN
        WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODPROD = T1000.BDCODPROD) ';
     IF (:WTODASCST = 'FALSE') THEN
        WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCSTICMS = PRO.BDCODCSTICMS) ';

     EXECUTE STATEMENT(WSQL);

         /*NOTAS DE DEVOLUÇÃO DE ENTRADA - SOMENTE PELO C113*/
         WSQL = ' INSERT INTO TMP_VEF_EMP_TADRCST_1300_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, ';
         WSQL = WSQL|| ' BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT, BDVLRICMSEFETIVO, BDCHAVENFEREFC113,BDNUMITEMREFC113, BDCODINCONSISTENCIA, BDTIPONFE, BDCHAVENFE) ';

         WSQL = WSQL|| ' SELECT  T1000.BDSESSAO, ENT.BDCODEMP, ENT.BDREFLAN, T1000.BDCODPROD, ENT.BDCHAVE, T1000.BDORDEM, PRO.BDORDEMPRO, ENT.BDDATAEMISSAO, ICMS.BDCODCSTICMS, ENT.BDNUMDOCINI, TER.BDCGCTER,UFT.BDSIGLAUF, EMP.BDCNPJEMP, UF.BDSIGLAUF,  ';
         WSQL = WSQL|| ' I.BDCODNAT, COALESCE(UNMF.BDAPEUNIMED, UNMP.BDAPEUNIMED) BDUNIMED,PRO.BDQTDITEM, ((PRO.BDVLRITEM - PRO.BDVLRDESC)/IIF(COALESCE(PRO.BDQTDITEM, 0) = 0, 1, PRO.BDQTDITEM)) BDVLRUNIT, /*IIF(COALESCE(PRO.BDVLRICMS,0) = 0,((PRO.BDVLRITEM - PRO.BDVLRDESC)/IIF(COALESCE(PRO.BDQTDITEM, 0) = 0, 1, PRO.BDQTDITEM))*PRO.BDALIQICMS,(PRO.BDVLRICMS * PRO.BDALIQICMS))*/ PRO.BDVLRICMS BDVLRICMSEFETIVO, ';
         WSQL = WSQL|| ' (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) BDCHAVENFEC113,PROREF.BDORDEMPRO,IIF(C113.BDCODEMP IS NULL, 20,IIF((C113.BDCODEMP IS NOT NULL) AND (select BDAAAAMM FROM AAAAMM(C113.bddtemissao)) <> (select BDAAAAMM FROM AAAAMM('''||:PRDATAINI||''')),23,NULL)) BDINCO, 0, (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(ENT.BDCHAVENFE)) BDCHAVENFE ';
         WSQL = WSQL|| ' FROM (SELECT T1000.BDCODEMP,T1000.BDSESSAO, T1000.BDCODPROD, T1000.BDREFERENCIA, PRO.BDCHAVE, PRO.BDORDEM,  T1000.BDCODUNIMED, T1000.BDNCMPROD ';
         WSQL = WSQL|| '       FROM TMP_VEF_EMP_TADRCST_1000_TEMP T1000 ';
         WSQL = WSQL|| '       LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = T1000.BDCODEMP AND PRO.BDCODPROD = T1000.BDCODPROD) ';
         WSQL = WSQL|| '       WHERE T1000.BDSESSAO = '||:PRSESSAO||' AND ';
         WSQL = WSQL|| '             T1000.BDCODEMP = '||:WCODEMP;
         WSQL = WSQL|| '       GROUP BY T1000.BDCODEMP,T1000.BDSESSAO, T1000.BDCODPROD, T1000.BDREFERENCIA, PRO.BDCHAVE, PRO.BDORDEM, T1000.BDCODUNIMED, T1000.BDNCMPROD ';
         WSQL = WSQL|| '       ) T1000 ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = T1000.BDCODEMP AND PRO.BDCHAVE = T1000.BDCHAVE AND PRO.BDORDEM = T1000.BDORDEM) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE AND I.BDORDEM = PRO.BDORDEM) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = ENT.BDCODEMP AND C113.BDCHAVE = ENT.BDCHAVE /*AND (SELECT BDAAAAMM FROM AAAAMM(C113.BDDTEMISSAO)) = T1000.BDREFERENCIA*/) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = ENT.BDCODTER) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT) ';
         WSQL = WSQL|| ' JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = ENT.BDCODEMP) ';
         WSQL = WSQL|| ' JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID) ';
         WSQL = WSQL|| ' JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF) ';
         WSQL = WSQL|| ' JOIN TCIDADE CIDT ON (CIDT.BDCODCID = TER.BDCODCID) ';
         WSQL = WSQL|| ' JOIN TUF UFT ON (UFT.BDCODUF = CIDT.BDCODUF) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODEMP = ENT.BDCODEMP AND FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMF ON (UNMF.BDCODUNIMED = FAT.BDCODUNIMED) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMP ON (UNMP.BDCODUNIMED = T1000.BDCODUNIMED) ';
         -- Alt.: #171712 - Olhar descrição em "SP_APURACAO_ADRCST_PR_1000"...
         --WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = C113.BDCODEMP /*AND SAI.BDREFLAN = ENT.BDREFLAN*/) ';
         --WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PROREF ON (PROREF.BDCODEMP = SAI.BDCODEMP AND PROREF.BDCHAVE = SAI.BDCHAVE AND PROREF.BDCODPROD = PRO.BDCODPROD) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP SAI ON (SAI.BDSESSAO = -1 AND SAI.BDCODEMP = C113.BDCODEMP /*AND SAI.BDREFLAN = ENT.BDREFLAN*/) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TMP_VEF_EMP_TMOVPROSAI PROREF ON (PROREF.BDSESSAO = -1 AND PROREF.BDCODEMP = SAI.BDCODEMP AND PROREF.BDCHAVE = SAI.BDCHAVE AND PROREF.BDCODPROD = PRO.BDCODPROD) ';
         WSQL = WSQL|| ' WHERE ENT.BDREFLAN = T1000.BDREFERENCIA ';
         WSQL = WSQL|| ' AND ENT.BDMODELO = 55 ';
         WSQL = WSQL|| ' AND ENT.BDDATAEMISSAO BETWEEN '''||:PRDATAINI||''' AND '''||:PRDATAFIM||'''';
         WSQL = WSQL|| ' AND ENT.BDCODSITNF NOT IN (2,3,4,5) ';
         WSQL = WSQL|| ' AND NAT.BDDEVOL = ''TRUE'' ';
         IF (:WCONSUFINAL = 1) THEN
            WSQL = WSQL|| ' AND COALESCE(ENT.BDCONSUFINAL,0) = '|| :WCONSUFINAL;
         ELSE
            WSQL = WSQL|| ' AND COALESCE(ENT.BDCONSUFINAL,0) IN (-1,0) ';
         WSQL = WSQL|| ' AND SUBSTRING(I.BDCODNAT FROM 1 FOR 1) = 2 ';
         WSQL = WSQL|| ' AND ((SAI.BDNUMDOCINI = C113.BDNUMDOC AND COALESCE(SAI.BDCHAVENFE,0) = IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '''', 0, C113.BDCHAVENFE) ';
         WSQL = WSQL|| ' AND SAI.BDDATAEMISSAO = C113.BDDTEMISSAO) OR (C113.bdcodemp IS NULL)) ';
         WSQL = WSQL|| ' AND NOT EXISTS (SELECT BDCODEMP FROM TMP_VEF_EMP_TADRCST_1300_TEMP T WHERE T.BDSESSAO = T1000.BDSESSAO AND T.BDCODEMP = T1000.BDCODEMP AND T.BDCHAVE = ENT.BDCHAVE AND T.BDORDEM = T1000.BDORDEM AND T.BDORDEMPROD = PRO.BDORDEMPRO )';         

         IF (:WTODOSTER = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODTER = ENT.BDCODTER) ';
    
         IF (:WTODASNCM = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNCM = T1000.BDNCMPROD) ';
         IF (:WTODOSPROD = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODPROD = T1000.BDCODPROD) ';
         IF (:WTODASCST = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCSTICMS = PRO.BDCODCSTICMS) ';

         IF (:WCODPLANODEV <> '') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE IN ('||WCODPLANODEV||') AND VINC.BDCODNAT = I.BDCODNAT) ';

         EXECUTE STATEMENT(WSQL);


    END
END
^

CREATE OR ALTER procedure SP_APURACAO_ADRCST_PR_1210_1220 (
    PRSESSAO integer,
    PRDATAINI date,
    PRDATAFIM date)
as
declare variable WSQL varchar(5000);
declare variable WCODEMP integer;
declare variable WCODCHAVE integer;
declare variable WPARTENQFED DM_BOOLEAN;
declare variable WCODPLANODEV varchar(100);
declare variable WPLANO integer;
declare variable WCONSUFINAL integer;
declare variable WTODASCFOP DM_BOOLEAN;
declare variable WTODASNCM DM_BOOLEAN;
declare variable WTODOSTER DM_BOOLEAN;
declare variable WTODOSPROD DM_BOOLEAN;
declare variable WTODASCST DM_BOOLEAN;
declare variable WCHAVEDEV integer;
BEGIN

  FOR  /*PEGA AS CONFIGURAÇÕES DO PLANO*/
    SELECT PLA.BDCODPLANOCONFADRCST,ADRCST.BDCODEMP, PLA.BDCHAVE, PLA.BDPARTENQFED, PLA.BDCONSUFINAL,
    IIF((SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASCFOP,
    IIF((SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASNCM,
    IIF((SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODOSTER,
    IIF((SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODOSPROD,
    IIF((SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = PLA.BDCODPLANOCONFADRCST AND VINC.BDCHAVE = PLA.BDCHAVE) IS NULL, 'TRUE', 'FALSE') AS BDTODASCST
    FROM VEF_BASE_TPLANOACOESCONFADRCST PLA
    LEFT OUTER JOIN TMP_VEF_EMP_TADRCSTGER_TEMP ADRCST ON (ADRCST.BDSESSAO = :PRSESSAO)
    WHERE PLA.BDCODPLANOCONFADRCST = ADRCST.BDCODPLACONFADRCST
    AND PLA.BDCODPROCESSO = 3 /*PROCESSO DO CONSUMIDOR FINAL*/
    INTO :WPLANO,:WCODEMP, :WCODCHAVE, :WPARTENQFED, :WCONSUFINAL, :WTODASCFOP, :WTODASNCM, :WTODOSTER, :WTODOSPROD, :WTODASCST
  DO
    BEGIN
         WCODPLANODEV = '';
         FOR
           SELECT PLA.BDCHAVE FROM VEF_BASE_TPLANOACOESCONFADRCST PLA WHERE PLA.BDCODPLANOCONFADRCST = :WPLANO AND PLA.BDCODPROCESSO = 1
           INTO :WCHAVEDEV
         DO
         BEGIN
           IF (:WCODPLANODEV <> '') THEN
              WCODPLANODEV = :WCODPLANODEV || ',';

            WCODPLANODEV =  :WCODPLANODEV || :WCHAVEDEV;
         END

         /*BDTIPO NFE - 0 ENTRADA - 1 SAÍDA*/
         /*INSERE OS LANÇAMENTO DE SAÍDA CONFORME O PLANO NO 1210 E 1220*/
         WSQL = ' INSERT INTO TMP_VEF_EMP_TADRCST_1200_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, ';
         WSQL = WSQL|| ' BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT, BDVLRICMSEFETIVO, BDTIPONFE, BDCHAVENFE) ';
         WSQL = WSQL|| ' SELECT T1000.BDSESSAO, SAI.BDCODEMP, SAI.BDREFLAN, PRO.BDCODPROD, SAI.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, SAI.BDDATAEMISSAO, ICMS.BDCODCSTICMS, SAI.BDNUMDOCINI, EMP.BDCNPJEMP, UF.BDSIGLAUF, TER.BDCGCTER,UFT.BDSIGLAUF, ';
         --WSQL = WSQL|| ' I.BDCODNAT, COALESCE(UNMF.BDAPEUNIMED, UNMP.BDAPEUNIMED) BDUNIMED,PRO.BDQTDITEM, ((PRO.BDVLRITEM - PRO.BDVLRDESC)/PRO.BDQTDITEM) BDVLRUNIT, IIF(COALESCE(PRO.BDBCICMS,0) = 0,(PRO.BDVLRITEM - PRO.BDVLRDESC)*(T1000.BDALIQICMS/100),(PRO.BDBCICMS * (T1000.BDALIQICMS/100))) BDVLRICMSEFETIVO, 1,  (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(SAI.BDCHAVENFE)) BDCHAVENFE ';
         WSQL = WSQL|| ' I.BDCODNAT, COALESCE(UNMF.BDAPEUNIMED, UNMP.BDAPEUNIMED) BDUNIMED,PRO.BDQTDITEM, ';
         WSQL = WSQL|| ' CAST((PRO.BDVLRITEM - PRO.BDVLRDESC) / IIF(COALESCE(PRO.BDQTDITEM, 0) = 0, 1, PRO.BDQTDITEM) AS NUMERIC(15,2)) BDVLRUNIT, ';
         WSQL = WSQL|| ' IIF(COALESCE(PRO.BDBCICMS,0) = 0,(CAST((PRO.BDVLRITEM - PRO.BDVLRDESC)/IIF(COALESCE(PRO.BDQTDITEM, 0) = 0, 1, PRO.BDQTDITEM) AS NUMERIC(15,2))* PRO.BDQTDITEM) * (T1000.BDALIQICMS / 100), (PRO.BDBCICMS * (T1000.BDALIQICMS/100))) BDVLRICMSEFETIVO, ';

         WSQL = WSQL|| ' 1,  (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(SAI.BDCHAVENFE)) BDCHAVENFE ';
         WSQL = WSQL|| ' FROM (SELECT *';
         WSQL = WSQL|| '       FROM TMP_VEF_EMP_TADRCST_1000_TEMP T1000';
         WSQL = WSQL|| '       WHERE T1000.BDSESSAO = '||:PRSESSAO||' AND';
         WSQL = WSQL|| '             T1000.BDCODEMP = '||:WCODEMP||') T1000';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (T1000.BDCODEMP = SAI.BDCODEMP AND T1000.BDCHAVE = SAI.BDCHAVE)';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE AND I.BDORDEM = T1000.BDORDEM) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = T1000.BDORDEM AND PRO.BDORDEMPRO = T1000.BDORDEMPROD)';
         WSQL = WSQL|| ' LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = SAI.BDCODTER)';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS) ';
         WSQL = WSQL|| ' JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = SAI.BDCODEMP) ';
         WSQL = WSQL|| ' JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID) ';
         WSQL = WSQL|| ' JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF) ';
         WSQL = WSQL|| ' JOIN TCIDADE CIDT ON (CIDT.BDCODCID = TER.BDCODCID) ';
         WSQL = WSQL|| ' JOIN TUF UFT ON (UFT.BDCODUF = CIDT.BDCODUF) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODEMP = SAI.BDCODEMP AND FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMF ON (UNMF.BDCODUNIMED = FAT.BDCODUNIMED) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMP ON (UNMP.BDCODUNIMED = T1000.BDCODUNIMED)';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT) ';
         WSQL = WSQL|| ' WHERE SAI.BDMODELO IN (55, 65)';
         WSQL = WSQL|| ' AND SAI.BDDATAEMISSAO BETWEEN '''||:PRDATAINI||''' AND '''||:PRDATAFIM||'''';
         WSQL = WSQL|| ' AND NAT.BDDEVOL = ''FALSE'' ';
         WSQL = WSQL|| ' AND (SUBSTRING(NAT.BDCODNAT FROM 2 FOR 1) = 4) '; -- Apenas quando a CFOP for 54XX, 64XX ou 74XX...
         IF (:WCONSUFINAL = 1) THEN
            WSQL = WSQL|| ' AND COALESCE(SAI.BDCONSUFINAL,0) = '|| :WCONSUFINAL;
         ELSE
            WSQL = WSQL|| ' AND COALESCE(SAI.BDCONSUFINAL,0) IN (-1,0) ';
         WSQL = WSQL|| ' AND SAI.BDCODSITNF NOT IN (2,3,4,5)';
        WSQL = WSQL|| ' AND NOT EXISTS (SELECT BDCODEMP FROM TMP_VEF_EMP_TADRCST_1200_TEMP T WHERE T.BDSESSAO = T1000.BDSESSAO AND T.BDCODEMP = T1000.BDCODEMP AND T.BDCHAVE = SAI.BDCHAVE AND T.BDORDEM = PRO.BDORDEM AND T.BDORDEMPROD = PRO.BDORDEMPRO )';         
    
         IF (:WPARTENQFED = 'TRUE' ) THEN
            WSQL = WSQL|| ' AND (TER.BDENQSIMPLESFEDTER = 2)';
         ELSE IF (:WTODOSTER = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODTER = SAI.BDCODTER) ';
    
         IF (:WTODASCFOP = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNAT = I.BDCODNAT) ';
         IF (:WTODASNCM = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNCM = T1000.BDNCMPROD) ';
         IF (:WTODOSPROD = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODPROD = T1000.BDCODPROD) ';
         IF (:WTODASCST = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCSTICMS = PRO.BDCODCSTICMS) ';

         EXECUTE STATEMENT(WSQL);

         /*NOTAS DE DEVOLUÇÃO DE ENTRADA - SOMENTE PELO C113*/
         WSQL = ' INSERT INTO TMP_VEF_EMP_TADRCST_1200_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, ';
         WSQL = WSQL|| ' BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT, BDVLRICMSEFETIVO, BDCHAVENFEREFC113,BDNUMITEMREFC113,BDCODINCONSISTENCIA, BDTIPONFE, BDCHAVENFE) ';

         WSQL = WSQL|| ' SELECT  T1000.BDSESSAO, ENT.BDCODEMP, ENT.BDREFLAN, T1000.BDCODPROD, ENT.BDCHAVE, T1000.BDORDEM, PRO.BDORDEMPRO, ENT.BDDATAEMISSAO, ICMS.BDCODCSTICMS, ENT.BDNUMDOCINI, TER.BDCGCTER,UFT.BDSIGLAUF, EMP.BDCNPJEMP, UF.BDSIGLAUF,  ';
         WSQL = WSQL|| ' I.BDCODNAT, COALESCE(UNMF.BDAPEUNIMED, UNMP.BDAPEUNIMED) BDUNIMED,PRO.BDQTDITEM, ((PRO.BDVLRITEM - PRO.BDVLRDESC)/IIF(COALESCE(PRO.BDQTDITEM, 0) = 0, 1, PRO.BDQTDITEM)) BDVLRUNIT, IIF(COALESCE(PRO.BDBCICMS,0) = 0,(PRO.BDVLRITEM - PRO.BDVLRDESC)*(PRO.BDALIQICMS/100),(PRO.BDBCICMS * (PRO.BDALIQICMS/100))) BDVLRICMSEFETIVO, ';
         WSQL = WSQL|| ' (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) BDCHAVENFEC113,PROREF.BDORDEMPRO,IIF(C113.BDCODEMP IS NULL, 20,IIF((C113.BDCODEMP IS NOT NULL) AND (select BDAAAAMM FROM AAAAMM(C113.bddtemissao)) <> (select BDAAAAMM FROM AAAAMM('''||:PRDATAINI||''')),23,NULL)) BDINCO, 0, (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(ENT.BDCHAVENFE)) BDCHAVENFE ';
         --WSQL = WSQL|| ' (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) BDCHAVENFEC113,NULL BDORDEMPRO,IIF(C113.BDCODEMP IS NULL, 20,IIF((C113.BDCODEMP IS NOT NULL) AND (select BDAAAAMM FROM AAAAMM(C113.bddtemissao)) <> (select BDAAAAMM FROM AAAAMM('''||:PRDATAINI||''')),23,NULL)) BDINCO, 0, (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(ENT.BDCHAVENFE)) BDCHAVENFE ';
         WSQL = WSQL|| ' FROM (SELECT T1000.BDCODEMP,T1000.BDSESSAO, T1000.BDCODPROD, T1000.BDREFERENCIA, PRO.BDCHAVE, PRO.BDORDEM,  T1000.BDCODUNIMED, T1000.BDNCMPROD ';
         WSQL = WSQL|| '       FROM TMP_VEF_EMP_TADRCST_1000_TEMP T1000 ';
         WSQL = WSQL|| '       LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = T1000.BDCODEMP AND PRO.BDCODPROD = T1000.BDCODPROD) ';
         WSQL = WSQL|| '       WHERE T1000.BDSESSAO = '||:PRSESSAO||' AND ';
         WSQL = WSQL|| '             T1000.BDCODEMP = '||:WCODEMP;
         WSQL = WSQL|| '       GROUP BY T1000.BDCODEMP,T1000.BDSESSAO, T1000.BDCODPROD, T1000.BDREFERENCIA, PRO.BDCHAVE, PRO.BDORDEM, T1000.BDCODUNIMED, T1000.BDNCMPROD ';
         WSQL = WSQL|| '       ) T1000 ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = T1000.BDCODEMP AND PRO.BDCHAVE = T1000.BDCHAVE AND PRO.BDORDEM = T1000.BDORDEM) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE AND I.BDORDEM = PRO.BDORDEM) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = ENT.BDCODEMP AND C113.BDCHAVE = ENT.BDCHAVE /*AND (SELECT BDAAAAMM FROM AAAAMM(C113.BDDTEMISSAO)) = T1000.BDREFERENCIA*/) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VW_TTERCEIRO TER ON (TER.BDCODTER = ENT.BDCODTER) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = PRO.BDCODCSTICMS) ';
         WSQL = WSQL|| ' JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = ENT.BDCODEMP) ';
         WSQL = WSQL|| ' JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID) ';
         WSQL = WSQL|| ' JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF) ';
         WSQL = WSQL|| ' JOIN TCIDADE CIDT ON (CIDT.BDCODCID = TER.BDCODCID) ';
         WSQL = WSQL|| ' JOIN TUF UFT ON (UFT.BDCODUF = CIDT.BDCODUF) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODEMP = ENT.BDCODEMP AND FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMF ON (UNMF.BDCODUNIMED = FAT.BDCODUNIMED) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TUNIDADEMEDIDA UNMP ON (UNMP.BDCODUNIMED = T1000.BDCODUNIMED) ';
         -- Alt.: #171712 - Olhar descrição em "SP_APURACAO_ADRCST_PR_1000"...
         --WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = C113.BDCODEMP /*AND SAI.BDREFLAN = ENT.BDREFLAN*/) ';
         --WSQL = WSQL|| ' LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PROREF ON (PROREF.BDCODEMP = SAI.BDCODEMP AND PROREF.BDCHAVE = SAI.BDCHAVE AND PROREF.BDCODPROD = PRO.BDCODPROD) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP SAI ON (SAI.BDSESSAO = -1 AND SAI.BDCODEMP = C113.BDCODEMP /*AND SAI.BDREFLAN = ENT.BDREFLAN*/) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN TMP_VEF_EMP_TMOVPROSAI PROREF ON (PROREF.BDSESSAO = -1 AND PROREF.BDCODEMP = SAI.BDCODEMP AND PROREF.BDCHAVE = SAI.BDCHAVE AND PROREF.BDCODPROD = PRO.BDCODPROD) ';
         WSQL = WSQL|| ' LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT) ';
         WSQL = WSQL|| ' WHERE ENT.BDREFLAN = T1000.BDREFERENCIA ';
         WSQL = WSQL|| ' AND ENT.BDMODELO = 55 ';
         WSQL = WSQL|| ' AND ENT.BDDATAEMISSAO BETWEEN '''||:PRDATAINI||''' AND '''||:PRDATAFIM||'''';
         WSQL = WSQL|| ' AND ENT.BDCODSITNF NOT IN (2,3,4,5) ';
         WSQL = WSQL|| ' AND NAT.BDDEVOL = ''TRUE'' ';
         IF (:WCONSUFINAL = 1) THEN
            WSQL = WSQL|| ' AND COALESCE(ENT.BDCONSUFINAL,0) = '|| :WCONSUFINAL;
         ELSE
            WSQL = WSQL|| ' AND COALESCE(ENT.BDCONSUFINAL,0) IN (-1,0) ';
         WSQL = WSQL|| ' AND SUBSTRING(I.BDCODNAT FROM 1 FOR 1) = 1 ';
         WSQL = WSQL|| ' AND ((SAI.BDNUMDOCINI = C113.BDNUMDOC AND COALESCE(SAI.BDCHAVENFE,0) = IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '''', 0, C113.BDCHAVENFE) ';
         WSQL = WSQL|| ' AND SAI.BDDATAEMISSAO = C113.BDDTEMISSAO) OR (C113.bdcodemp IS NULL))';
         WSQL = WSQL|| ' AND NOT EXISTS (SELECT BDCODEMP FROM TMP_VEF_EMP_TADRCST_1200_TEMP T WHERE T.BDSESSAO = T1000.BDSESSAO AND T.BDCODEMP = T1000.BDCODEMP AND T.BDCHAVE = ENT.BDCHAVE AND T.BDORDEM = T1000.BDORDEM AND T.BDORDEMPROD = PRO.BDORDEMPRO )';
         
         IF (:WPARTENQFED = 'TRUE' ) THEN
            WSQL = WSQL|| ' AND (TER.BDENQSIMPLESFEDTER = 2)';
         ELSE IF (:WTODOSTER = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODTER FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODTER = ENT.BDCODTER) ';
    
         IF (:WTODASNCM = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNCM FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODNCM = T1000.BDNCMPROD) ';
         IF (:WTODOSPROD = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODPROD FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCODPROD = T1000.BDCODPROD) ';
         IF (:WTODASCST = 'FALSE') THEN
            WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCSTICMS FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE = '||WCODCHAVE||' AND VINC.BDCSTICMS = PRO.BDCODCSTICMS) ';

         IF (:WCODPLANODEV <> '') THEN
             WSQL = WSQL|| ' AND EXISTS(SELECT FIRST 1 BDCODNAT FROM VEF_BASE_TVINCCODPLANOADRCST VINC WHERE VINC.BDCODPLANOCONFADRCST = '||WPLANO||' AND VINC.BDCHAVE IN ('||WCODPLANODEV||') AND VINC.BDCODNAT = I.BDCODNAT) ';

         EXECUTE STATEMENT(WSQL);
     END

END
^

CREATE OR ALTER procedure SP_APURACAO_ADRCST_PR_1000 (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
declare variable WREF integer;
BEGIN
   wRef = (SELECT BDREFERENCIA FROM DEC_REFERENCIA((SELECT FIRST 1 ADRCST.BDREFERENCIA FROM TMP_VEF_EMP_TADRCSTGER_TEMP ADRCST WHERE ADRCST.BDSESSAO = :PRSESSAO), 36));

   /*Produtos da Saída com ST*/
   INSERT INTO TMP_VEF_EMP_TADRCST_1000_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM,
   BDORDEMPROD, BDCODPRODVINC, BDDESCPROD, BDINDFECOP, BDCODIGOEAN, BDCODCOMBANP, BDNCMPROD,
   BDCODCEST, BDCODUNIMED, BDALIQICMS, BDALIQFECOP,BDPERCMVA)/*, BDQTDENTPERIODO, BDQTDSAIDAPERIODO PREENCHIDO NO 1100*/
   SELECT SAIT.BDSESSAO, SAIT.BDCODEMP, SAIT.BDREFERENCIA, SAIT.BDCODPROD, SAIT.BDCHAVE, SAIT.BDORDEM,
   SAIT.BDORDEMPRO,VINC.BDCODSAIDA, VINC.BDDESCPROD, IIF(VINC.BDALIQFCP > 0, 1, 0) BDINDFECOP, PRO.BDCODIGOEAN,
   VINC.BDCODCOMBANP,VINC.BDNCMPROD, VINC.BDCODCEST, VINC.BDCODUNIMED, VINC.BDALIQICMS, VINC.BDALIQFCP, VINC.BDPERCMVA
   FROM (
        SELECT SAIT.*, ADRCST.BDREFERENCIA FROM TMP_VEF_EMP_TADRCSTGER_TEMP ADRCST
        LEFT OUTER JOIN TMP_VEF_EMP_SAIADRCST_TEMP SAIT ON (SAIT.BDSESSAO = ADRCST.BDSESSAO AND SAIT.BDCODEMP = ADRCST.BDCODEMP)
        WHERE SAIT.BDISPRODST = 'TRUE'
        AND ADRCST.BDSESSAO = :PRSESSAO
        ) SAIT
   LEFT OUTER JOIN TCADPRO PRO ON (PRO.BDCODPROD = SAIT.BDCODPROD)
   LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = SAIT.BDCODEMP AND VINC.BDCODPROD = SAIT.BDCODPROD);

   /*Produtos da Saída sem ST - Olha o produto do lançamento de entrada/Dados originais/Lançamento de MVA*/
   INSERT INTO TMP_VEF_EMP_TADRCST_1000_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM,
   BDORDEMPROD, BDCODPRODVINC, BDDESCPROD, BDINDFECOP, BDCODIGOEAN, BDCODCOMBANP, BDNCMPROD,
   BDCODCEST, BDCODUNIMED, BDALIQICMS, BDALIQFECOP,BDPERCMVA)/*, BDQTDENTPERIODO, BDQTDSAIDAPERIODO PREENCHIDO NO 1100*/
   SELECT SAIT.BDSESSAO, SAIT.BDCODEMP, SAIT.BDREFERENCIA, SAIT.BDCODPROD, SAIT.BDCHAVE, SAIT.BDORDEM,
          SAIT.BDORDEMPRO,VINC.BDCODSAIDA, VINC.BDDESCPROD, IIF(VINC.BDALIQFCP > 0, 1, 0) BDINDFECOP, PRO.BDCODIGOEAN,
           VINC.BDCODCOMBANP,VINC.BDNCMPROD, VINC.BDCODCEST, VINC.BDCODUNIMED, VINC.BDALIQICMS, VINC.BDALIQFCP,VINC.BDPERCMVA
    FROM (
        SELECT SAIT.*, ADRCST.BDREFERENCIA FROM TMP_VEF_EMP_TADRCSTGER_TEMP ADRCST
        LEFT OUTER JOIN TMP_VEF_EMP_SAIADRCST_TEMP SAIT ON (SAIT.BDSESSAO = ADRCST.BDSESSAO AND SAIT.BDCODEMP = ADRCST.BDCODEMP)
        WHERE SAIT.BDISPRODST = 'FALSE'
        AND ADRCST.BDSESSAO = :PRSESSAO
          ) SAIT
--    LEFT OUTER JOIN VEF_EMP_TMOVPROENT MPRO ON (MPRO.BDCODEMP = SAIT.BDCODEMP AND MPRO.BDCODPROD = SAIT.BDCODPROD)
--    LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = MPRO.BDCODEMP AND ENT.BDCHAVE = MPRO.BDCHAVE)
--    LEFT OUTER JOIN TCADPRO PRO ON (PRO.BDCODPROD = MPRO.BDCODPROD)
--    LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = SAIT.BDCODEMP AND VINC.BDCODPROD = MPRO.BDCODPROD)
--    LEFT OUTER JOIN VEF_EMP_TMOVMVAPR MVA ON (MVA.BDCODEMP = MPRO.BDCODEMP AND MVA.BDCHAVE = MPRO.BDCHAVE AND MVA.BDORDEM = MPRO.BDORDEM)
--    LEFT OUTER JOIN VEF_EMP_TMOVPROENTIMPORI ENTO ON (ENTO.BDCODEMP = ENT.BDCODEMP AND ENTO.bdchave = MPRO.bdchave AND ENTO.bdordem = MPRO.bdordem AND ENTO.bdordemhist = MPRO.bdordempro AND ENTO.BDCODPROD = MPRO.BDCODPROD)
--    WHERE ENT.BDREFLAN = (SELECT MAX(ENTR.BDREFLAN) FROM VEF_EMP_TMOVENT ENTR WHERE ENTR.BDCODEMP = SAIT.BDCODEMP)
--    AND (MPRO.BDVLRST > 0 OR MPRO.BDVLRFCPSTRET > 0 OR MPRO.BDVLRFCP > 0 OR MPRO.BDVLRICMSSTRET > 0 OR MVA.BDVLRICMSST > 0 OR MVA.BDVLRICMSSTNAORET > 0 OR
--        (ENTO.BDBCST > 0 OR ENTO.BDBCFCPSTRET > 0 OR ENTO.BDBCFCPRETIDO > 0 OR ENTO.BDVLRICMSSTRET > 0) );
   LEFT OUTER JOIN TCADPRO PRO ON (PRO.BDCODPROD = SAIT.BDCODPROD)
   LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = SAIT.BDCODEMP AND VINC.BDCODPROD = SAIT.BDCODPROD)
   WHERE EXISTS(
                SELECT *
                FROM (
                      SELECT SAIT.*
                      FROM TMP_VEF_EMP_TADRCSTGER_TEMP ADRCST
                      WHERE ADRCST.BDSESSAO = :PRSESSAO
                      ) S
                 --LEFT OUTER JOIN VEF_EMP_TMOVPROENT MPRO ON (MPRO.BDCODEMP = SAIT.BDCODEMP AND MPRO.BDCODPROD = SAIT.BDCODPROD)
                 LEFT OUTER JOIN VEF_EMP_TMOVPROENT MPRO ON (MPRO.BDCODEMP = S.BDCODEMP AND MPRO.BDCODPROD = S.BDCODPROD)
    LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = MPRO.BDCODEMP AND ENT.BDCHAVE = MPRO.BDCHAVE)
    LEFT OUTER JOIN TCADPRO PRO ON (PRO.BDCODPROD = MPRO.BDCODPROD)
    LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = SAIT.BDCODEMP AND VINC.BDCODPROD = MPRO.BDCODPROD)
    LEFT OUTER JOIN VEF_EMP_TMOVMVAPR MVA ON (MVA.BDCODEMP = MPRO.BDCODEMP AND MVA.BDCHAVE = MPRO.BDCHAVE AND MVA.BDORDEM = MPRO.BDORDEM)
    LEFT OUTER JOIN VEF_EMP_TMOVPROENTIMPORI ENTO ON (ENTO.BDCODEMP = ENT.BDCODEMP AND ENTO.bdchave = MPRO.bdchave AND ENTO.bdordem = MPRO.bdordem AND ENTO.bdordemhist = MPRO.bdordempro AND ENTO.BDCODPROD = MPRO.BDCODPROD)
--                 WHERE ENT.BDREFLAN = (SELECT MAX(ENTR.BDREFLAN) FROM VEF_EMP_TMOVENT ENTR WHERE ENTR.BDCODEMP = SAIT.BDCODEMP)
                 /* WHERE ENT.BDREFLAN = SAIT.BDREFERENCIA */
                 WHERE ENT.BDREFLAN BETWEEN :wRef AND SAIT.BDREFERENCIA -- Alt.: #186563
                   AND (S.BDCODEMP = SAIT.BDCODEMP AND S.BDCODPROD = SAIT.BDCODPROD)
    AND (MPRO.BDVLRST > 0 OR MPRO.BDVLRFCPSTRET > 0 OR MPRO.BDVLRFCP > 0 OR MPRO.BDVLRICMSSTRET > 0 OR MVA.BDVLRICMSST > 0 OR MVA.BDVLRICMSSTNAORET > 0 OR
                     (ENTO.BDBCST > 0 OR ENTO.BDBCFCPSTRET > 0 OR ENTO.BDBCFCPRETIDO > 0 OR ENTO.BDVLRICMSSTRET > 0) )
                 );

   /*Produtos da Saída sem ST - Olha os dados originais das entradas*/
--   INSERT INTO TMP_VEF_EMP_TADRCST_1000_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM,
--   BDORDEMPROD, BDCODPRODVINC, BDDESCPROD, BDINDFECOP, BDCODIGOEAN, BDCODCOMBANP, BDNCMPROD,
--   BDCODCEST, BDCODUNIMED, BDALIQICMS, BDALIQFECOP,BDPERCMVA)/*, BDQTDENTPERIODO, BDQTDSAIDAPERIODO PREENCHIDO NO 1100*/
--    SELECT SAIT.BDSESSAO, SAIT.BDCODEMP, SAIT.BDREFERENCIA, SAIT.BDCODPROD, SAIT.BDCHAVE, SAIT.BDORDEM,
--           SAIT.BDORDEMPRO,VINC.BDCODSAIDA, VINC.BDDESCPROD, IIF(VINC.BDALIQFCP > 0, 1, 0) BDINDFECOP, PRO.BDCODIGOEAN,
--           VINC.BDCODCOMBANP,VINC.BDNCMPROD, VINC.BDCODCEST, VINC.BDCODUNIMED, VINC.BDALIQICMS, VINC.BDALIQFCP, VINC.BDPERCMVA
--    FROM (
--        SELECT SAIT.*, ADRCST.BDREFERENCIA FROM TMP_VEF_EMP_TADRCSTGER_TEMP ADRCST
--        LEFT OUTER JOIN TMP_VEF_EMP_SAIADRCST_TEMP SAIT ON (SAIT.BDSESSAO = ADRCST.BDSESSAO AND SAIT.BDCODEMP = ADRCST.BDCODEMP)
--        WHERE SAIT.BDISPRODST = 'FALSE'
--        AND ADRCST.BDSESSAO = :PRSESSAO
--          ) SAIT
--    JOIN VEF_EMP_TMOVPROENTIMPORI ENTO ON (ENTO.BDCODEMP = SAIT.BDCODEMP AND ENTO.BDCODPROD = SAIT.BDCODPROD)
--    JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = ENTO.BDCODEMP AND ENT.BDCHAVE = ENTO.BDCHAVE)
--    LEFT OUTER JOIN TCADPRO PRO ON (PRO.BDCODPROD = ENTO.BDCODPROD)
--    LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = SAIT.BDCODEMP AND VINC.BDCODPROD = ENTO.BDCODPROD)
--    WHERE ENT.BDREFLAN = (SELECT MAX(ENTR.BDREFLAN) FROM VEF_EMP_TMOVENT ENTR WHERE ENTR.BDCODEMP = SAIT.BDCODEMP)
--    AND (ENTO.BDBCST > 0 OR ENTO.BDBCFCPSTRET > 0 OR ENTO.BDBCFCPRETIDO > 0 OR ENTO.BDVLRICMSSTRET > 0);
--
--   UPDATE TMP_VEF_EMP_SAIADRCST_TEMP SAI SET
--   SAI.BDISPRODST = IIF((SELECT FIRST 1 BDCODEMP FROM TMP_VEF_EMP_TADRCST_1000_TEMP T WHERE T.BDCODPROD = SAI.BDCODPROD AND T.BDCODEMP = SAI.BDCODEMP AND T.BDCHAVE = SAI.BDCHAVE AND T.BDSESSAO = SAI.BDSESSAO) > 0,'TRUE','FALSE')
--   WHERE SAI.BDISPRODST = 'FALSE';
--
--   /*Produtos da Saída sem ST - Olha o produto do lançamento de entrada*/
--   INSERT INTO TMP_VEF_EMP_TADRCST_1000_TEMP (BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM,
--   BDORDEMPROD, BDCODPRODVINC, BDDESCPROD, BDINDFECOP, BDCODIGOEAN, BDCODCOMBANP, BDNCMPROD,
--   BDCODCEST, BDCODUNIMED, BDALIQICMS, BDALIQFECOP,BDPERCMVA)/*, BDQTDENTPERIODO, BDQTDSAIDAPERIODO PREENCHIDO NO 1100*/
--   SELECT SAIT.BDSESSAO, SAIT.BDCODEMP, SAIT.BDREFERENCIA, SAIT.BDCODPROD, SAIT.BDCHAVE, SAIT.BDORDEM,
--          SAIT.BDORDEMPRO,VINC.BDCODSAIDA, VINC.BDDESCPROD, IIF(VINC.BDALIQFCP > 0, 1, 0) BDINDFECOP, PRO.BDCODIGOEAN,
--           VINC.BDCODCOMBANP,VINC.BDNCMPROD, VINC.BDCODCEST, VINC.BDCODUNIMED, VINC.BDALIQICMS, VINC.BDALIQFCP,VINC.BDPERCMVA
--    FROM (
--        SELECT SAIT.*, ADRCST.BDREFERENCIA FROM TMP_VEF_EMP_TADRCSTGER_TEMP ADRCST
--        LEFT OUTER JOIN TMP_VEF_EMP_SAIADRCST_TEMP SAIT ON (SAIT.BDSESSAO = ADRCST.BDSESSAO AND SAIT.BDCODEMP = ADRCST.BDCODEMP)
--        WHERE SAIT.BDISPRODST = 'FALSE'
--        AND ADRCST.BDSESSAO = :PRSESSAO
--          ) SAIT
--    JOIN VEF_EMP_TMOVPROENT MPRO ON (MPRO.BDCODEMP = SAIT.BDCODEMP AND MPRO.BDCODPROD = SAIT.BDCODPROD)
--    JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = MPRO.BDCODEMP AND ENT.BDCHAVE = MPRO.BDCHAVE)
--    LEFT OUTER JOIN TCADPRO PRO ON (PRO.BDCODPROD = MPRO.BDCODPROD)
--    LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = SAIT.BDCODEMP AND VINC.BDCODPROD = MPRO.BDCODPROD)
--    LEFT OUTER JOIN VEF_EMP_TMOVMVAPR MVA ON (MVA.BDCODEMP = MPRO.BDCODEMP AND MVA.BDCHAVE = MPRO.BDCHAVE AND MVA.BDORDEM = MPRO.BDORDEM)
--    WHERE ENT.BDREFLAN = (SELECT MAX(ENTR.BDREFLAN) FROM VEF_EMP_TMOVENT ENTR WHERE ENTR.BDCODEMP = SAIT.BDCODEMP)
--    AND (MPRO.BDVLRST > 0 OR MPRO.BDVLRFCPSTRET > 0 OR MPRO.BDVLRFCP > 0 OR MPRO.BDVLRICMSSTRET > 0 OR MVA.BDVLRICMSST > 0 OR MVA.BDVLRICMSSTNAORET > 0);
--
--   UPDATE TMP_VEF_EMP_SAIADRCST_TEMP SAI SET
--   SAI.BDISPRODST = IIF((SELECT FIRST 1 BDCODEMP FROM TMP_VEF_EMP_TADRCST_1000_TEMP T WHERE T.BDCODPROD = SAI.BDCODPROD AND T.BDCODEMP = SAI.BDCODEMP AND T.BDCHAVE = SAI.BDCHAVE AND T.BDSESSAO = SAI.BDSESSAO) > 0,'TRUE','FALSE')
--   WHERE SAI.BDISPRODST = 'FALSE';

   /* Solicitação #171712 | Título: Apuração ADRCST - lentidão na geração
          Ao apurar estava apresentando uma lentidão, pois nas consultas dos registros 1200, 1300, 1400, 1500, sempre que buscava as devoluções das entradas, buscava as notas referenciadas no registro C113 nas notas de saídas.
      Porém isso é muito lento, pois varre toda a tabela de saídas buscando a nota apenas pelo número do documento e como faz isso para todos os registros, a apuração virava uma carroça, para melhorar isso ao invés de fazer
      essa busca em todos os selects, vão ser preenchidas as tabelas temporárias com esses registros e só vai consultar esses registros na apuração, assim só vamos varrer toda a tabela uma única vez. */
--   INSERT INTO TMP_VEF_EMP_TMOVPROSAI (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODPROD)
--   SELECT -1, PROREF.BDCODEMP, PROREF.BDCHAVE, PROREF.BDORDEM, PROREF.BDORDEMPRO, PROREF.BDCODPROD
--   FROM (SELECT T1000.BDCODEMP, T1000.BDSESSAO, T1000.BDCODPROD, T1000.BDREFERENCIA, PRO.BDCHAVE, PRO.BDORDEM,
--                T1000.BDCODUNIMED, T1000.BDNCMPROD, PRO.BDORDEMPRO
--         FROM TMP_VEF_EMP_TADRCST_1000_TEMP T1000
--         LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = T1000.BDCODEMP AND
--               PRO.BDCODPROD = T1000.BDCODPROD)
--         WHERE T1000.BDSESSAO = :PRSESSAO
--         GROUP BY T1000.BDCODEMP, T1000.BDSESSAO, T1000.BDCODPROD, T1000.BDREFERENCIA, PRO.BDCHAVE, PRO.BDORDEM, T1000.BDCODUNIMED, T1000.BDNCMPROD, PRO.BDORDEMPRO) T1000
--   LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = T1000.BDCODEMP AND PRO.BDCHAVE = T1000.BDCHAVE AND PRO.BDORDEM = T1000.BDORDEM AND PRO.BDORDEMPRO = T1000.BDORDEMPRO)
--   LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCHAVE = ENT.BDCHAVE)
--   LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE AND I.BDORDEM = PRO.BDORDEM)
--   LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = ENT.BDCODEMP AND C113.BDCHAVE = ENT.BDCHAVE)
--   LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = C113.BDCODEMP /*AND SAI.BDREFLAN = EXTRACT(YEAR FROM C113.BDDTEMISSAO)||LPAD(EXTRACT(MONTH FROM C113.BDDTEMISSAO),2,'0')*/ )
--   /*LEFT OUTER #243271*/ JOIN VEF_EMP_TMOVPROSAI PROREF ON (PROREF.BDCODEMP = SAI.BDCODEMP AND PROREF.BDCHAVE = SAI.BDCHAVE AND PROREF.BDCODPROD = PRO.BDCODPROD)
--   LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
--   WHERE ENT.BDREFLAN = T1000.BDREFERENCIA
--     AND ENT.BDMODELO = 55
--     AND ENT.BDDATAEMISSAO BETWEEN :PRDATAINICIO AND :PRDATAFIM
--     AND ENT.BDCODSITNF NOT IN (2, 3, 4, 5)
--     AND NAT.BDDEVOL = 'TRUE'
--     AND COALESCE(ENT.BDCONSUFINAL, 0) IN (-1, 0)
--     AND SUBSTRING(I.BDCODNAT FROM 1 FOR 1) = 1
--     AND ((SAI.BDNUMDOCINI = C113.BDNUMDOC AND COALESCE(SAI.BDCHAVENFE, 0) = IIF((SELECT BDNUMERO
--                                                                                  FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '', 0, C113.BDCHAVENFE) AND
--           SAI.BDDATAEMISSAO = C113.BDDTEMISSAO) /*OR (C113.BDCODEMP IS NULL)*/)
--   GROUP BY PROREF.BDCODEMP, PROREF.BDCHAVE, PROREF.BDORDEM, PROREF.BDORDEMPRO, PROREF.BDCODPROD;
   /* Alt.: #243271 - Ajustado o SQL anterior, estava tentando inserir um produto sem saídas e estava muito lento */
   INSERT INTO TMP_VEF_EMP_TMOVPROSAI (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODPROD)
   SELECT -1, PROREF.BDCODEMP, PROREF.BDCHAVE, PROREF.BDORDEM, PROREF.BDORDEMPRO, PROREF.BDCODPROD
   FROM (SELECT T1000.BDCODEMP, T1000.BDSESSAO, T1000.BDCODPROD, T1000.BDREFERENCIA, T1000.BDCODUNIMED, T1000.BDNCMPROD
         FROM TMP_VEF_EMP_TADRCST_1000_TEMP T1000
         WHERE T1000.BDSESSAO = :PRSESSAO
         GROUP BY T1000.BDCODEMP, T1000.BDSESSAO, T1000.BDCODPROD, T1000.BDREFERENCIA, T1000.BDCODUNIMED, T1000.BDNCMPROD) T1000
   JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = T1000.BDCODEMP AND ENT.BDREFLAN = T1000.BDREFERENCIA AND
                                ENT.BDMODELO = 55 AND ENT.BDCODSITNF NOT IN (2, 3, 4, 5) AND
                                ENT.BDDATAEMISSAO BETWEEN :PRDATAINICIO AND :PRDATAFIM )
   JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = ENT.BDCODEMP AND I.BDCHAVE = ENT.BDCHAVE)
   JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = ENT.BDCODEMP AND C113.BDCHAVE = ENT.BDCHAVE)
   JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM AND PRO.BDCODPROD = T1000.BDCODPROD)
   JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = C113.BDCODEMP /*AND SAI.BDREFLAN = EXTRACT(YEAR FROM C113.BDDTEMISSAO)||LPAD(EXTRACT(MONTH FROM C113.BDDTEMISSAO),2,'0')*/ )
   JOIN VEF_EMP_TMOVPROSAI PROREF ON (PROREF.BDCODEMP = SAI.BDCODEMP AND PROREF.BDCHAVE = SAI.BDCHAVE AND PROREF.BDCODPROD = PRO.BDCODPROD)
   JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
   WHERE NAT.BDDEVOL = 'TRUE'
     AND COALESCE(ENT.BDCONSUFINAL, 0) IN (-1, 0)
     AND SUBSTRING(I.BDCODNAT FROM 1 FOR 1) = 1
     AND ((SAI.BDNUMDOCINI = C113.BDNUMDOC AND COALESCE(SAI.BDCHAVENFE, 0) = IIF((SELECT BDNUMERO
                                                                                  FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '', 0, C113.BDCHAVENFE) AND
           SAI.BDDATAEMISSAO = C113.BDDTEMISSAO) /*OR (C113.BDCODEMP IS NULL)*/)
   GROUP BY PROREF.BDCODEMP, PROREF.BDCHAVE, PROREF.BDORDEM, PROREF.BDORDEMPRO, PROREF.BDCODPROD;

   INSERT INTO TMP_VEF_EMP_TMOVSAI_TEMP (BDSESSAO, BDCODEMP, BDCHAVE, BDNUMDOCINI, BDCHAVENFE, BDDATAEMISSAO)
   SELECT -1, SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDNUMDOCINI, SAI.BDCHAVENFE, SAI.BDDATAEMISSAO
   FROM TMP_VEF_EMP_TMOVPROSAI T
   LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON(SAI.BDCODEMP = T.BDCODEMP AND SAI.BDCHAVE = T.BDCHAVE)
   WHERE T.BDSESSAO = -1
   GROUP BY SAI.BDCODEMP, SAI.BDCHAVE, SAI.BDNUMDOCINI, SAI.BDCHAVENFE, SAI.BDDATAEMISSAO;

END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_ADRCST_PR_GRAVAR (
    PRSESSAO INTEGER,
    PRCODPLACONFADRCST INTEGER)
AS
BEGIN

  /*1210-1220*/
  INSERT INTO VEF_EMP_TADRCST_1210_1220 (BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD,
                                         BDDATAEMISSAO, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE,
                                         BDCNPJCPFDESTIN, BDUFDESTIN, BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT,
                                         BDVLRICMSEFETIVO, BDCHAVENFEREFC113,BDNUMITEMREFC113,BDTIPONFE,BDCHAVENFE)
  SELECT BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, BDCSTICMS, BDNUMDOC,
         BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT,
         BDVLRICMSEFETIVO, BDCHAVENFEREFC113,BDNUMITEMREFC113, BDTIPONFE,BDCHAVENFE
  FROM TMP_VEF_EMP_TADRCST_1200_TEMP T1200
  WHERE BDSESSAO = :PRSESSAO;

  /*1310-1320*/
  INSERT INTO VEF_EMP_TADRCST_1310_1320 (BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, BDCODNAT,
                                         BDUNIDMED, BDQTDITEM, BDVLRUNIT, BDVLRICMSEFETIVO, BDCHAVENFEREFC113, BDNUMITEMREFC113, BDTIPONFE, BDCHAVENFE)
  SELECT BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, BDCODNAT,
         BDUNIDMED, BDQTDITEM, BDVLRUNIT, BDVLRICMSEFETIVO, BDCHAVENFEREFC113, BDNUMITEMREFC113, BDTIPONFE, BDCHAVENFE
  FROM TMP_VEF_EMP_TADRCST_1300_TEMP T3200
  WHERE BDSESSAO = :PRSESSAO;

  /*1410-1420*/
  INSERT INTO VEF_EMP_TADRCST_1410_1420 (BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN,
                                         BDUFDESTIN, BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT, BDVLRICMSEFETIVO, BDCHAVENFEREFC113, BDNUMITEMREFC113, BDTIPONFE, BDCHAVENFE)
  SELECT BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE, BDUFEMITENTE, BDCNPJCPFDESTIN,
         BDUFDESTIN, BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT, BDVLRICMSEFETIVO, BDCHAVENFEREFC113, BDNUMITEMREFC113, BDTIPONFE, BDCHAVENFE
  FROM TMP_VEF_EMP_TADRCST_1400_TEMP T1400
  WHERE BDSESSAO = :PRSESSAO;

  /*1510-1520*/
  INSERT INTO VEF_EMP_TADRCST_1510_1520 (BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE,
  BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT, BDVLRICMSEFETIVO, BDCHAVENFEREFC113, BDNUMITEMREFC113, BDTIPONFE, BDCHAVENFE)
  SELECT BDCODEMP, BDREFERENCIA, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPROD, BDDATAEMISSAO, BDCSTICMS, BDNUMDOC, BDCNPJEMITENTE,
  BDUFEMITENTE, BDCNPJCPFDESTIN, BDUFDESTIN, BDCODNAT, BDUNIDMED, BDQTDITEM, BDVLRUNIT, BDVLRICMSEFETIVO, BDCHAVENFEREFC113, BDNUMITEMREFC113, BDTIPONFE, BDCHAVENFE
  FROM TMP_VEF_EMP_TADRCST_1500_TEMP T500
  WHERE BDSESSAO = :PRSESSAO;

  /*TOTAL 1200*/
  INSERT INTO VEF_EMP_TADRCST_1200 (BDCODEMP,BDREFERENCIA, BDCODPROD, BDQTDTOTALSAI, BDTTVLRICMSEFETIVO, BDVLRCONFICMSENT, BDVLRICMSRECUPERAR, BDVLRICMSCOMPLEMENTAR, BDVLRICMSSTRECUPERAR,
                                    BDVLRICMSSTCOMPLEMENTAR, BDVLRFCPRECUPER, BDVLRFCPCOMPLEMENTAR)
  SELECT T1200.BDCODEMP, T1200.BDREFERENCIA,T1200.BDCODPROD,(T1200.BDQTDSAI - T1200.BDQTDENT) BDQTDTOTAL, T1200.BDVLRICMSEFETIVO, T1200.BDVLRCONFICMSENT,
         IIF(T1200.BDVLRICMSRECUPERAR < 0,0,T1200.BDVLRICMSRECUPERAR) BDVLRICMSRECUPERAR, (IIF(T1200.BDVLRCONFICMSENT - T1200.BDVLRICMSEFETIVO > 0, 0, (T1200.BDVLRCONFICMSENT - T1200.BDVLRICMSEFETIVO)*-1)) BDVLRICMSCOMPLEMENTAR,
         IIF(T1200.BDALIQICMS > 0 AND T1200.BDVLRICMSRECUPERAR > 0,(T1200.BDVLRICMSRECUPERAR * ((T1200.BDALIQICMS - coalesce(T1200.BDALIQFECOP,0)) / T1200.BDALIQICMS)),0) BDICMSSTRECUPERAR,
         IIF(T1200.BDALIQICMS > 0,((IIF(T1200.BDVLRCONFICMSENT - T1200.BDVLRICMSEFETIVO > 0, 0, (T1200.BDVLRCONFICMSENT - T1200.BDVLRICMSEFETIVO)*-1)) * ((T1200.BDALIQICMS - coalesce(T1200.BDALIQFECOP,0)) / T1200.BDALIQICMS)),0) BDICMSSTCOMPL,
         IIF(T1200.BDALIQICMS > 0 AND T1200.BDVLRICMSRECUPERAR > 0,(T1200.BDVLRICMSRECUPERAR * (coalesce(T1200.BDALIQFECOP,0) / T1200.BDALIQICMS)),0) BDFECOPRECUPERAR,
         IIF(T1200.BDALIQICMS > 0,((IIF(T1200.BDVLRCONFICMSENT - T1200.BDVLRICMSEFETIVO > 0, 0, (T1200.BDVLRCONFICMSENT - T1200.BDVLRICMSEFETIVO)*-1)) * (coalesce(T1200.BDALIQFECOP,0) / T1200.BDALIQICMS)),0) BDFECOPCOMPL
  FROM (
        SELECT T1200.BDCODEMP, T1200.BDREFERENCIA,T1200.BDCODPROD, SUM(T1200.BDQTDSAI) BDQTDSAI, SUM(T1200.BDQTDENT) BDQTDENT, SUM(BDVLRICMSEFETIVOSAI) BDVLRICMSEFETIVOSAI, SUM(BDVLRICMSEFETIVOENT) BDVLRICMSEFETIVOENT,
               COALESCE(T1100.BDVLRUNITMEDIOITEMSUPENT,0) BDVLRUNITMEDIOITEMSUPENT,(SUM(BDVLRICMSEFETIVOSAI) - SUM(BDVLRICMSEFETIVOENT)) BDVLRICMSEFETIVO,
               COALESCE(((SUM(T1200.BDQTDSAI) - SUM(T1200.BDQTDENT)) * T1100.BDVLRUNITMEDIOITEMSUPENT),0) BDVLRCONFICMSENT, COALESCE(IIF((((SUM(T1200.BDQTDSAI) - SUM(T1200.BDQTDENT)) * T1100.BDVLRUNITMEDIOITEMSUPENT) - (SUM(BDVLRICMSEFETIVOSAI) - SUM(BDVLRICMSEFETIVOENT))) = -0, 0,
               (((SUM(T1200.BDQTDSAI) - SUM(T1200.BDQTDENT)) * T1100.BDVLRUNITMEDIOITEMSUPENT) - (SUM(BDVLRICMSEFETIVOSAI) - SUM(BDVLRICMSEFETIVOENT)))),0) BDVLRICMSRECUPERAR, COALESCE(T1200.BDALIQICMS,0) BDALIQICMS, COALESCE(T1200.BDALIQFECOP,0) BDALIQFECOP
        FROM (
              SELECT T1200.BDCODEMP, T1200.BDREFERENCIA,T1200.BDCODPROD,IIF(T1200.BDTIPONFE = 0, T1200.BDQTDITEM, 0) BDQTDENT, IIF(T1200.BDTIPONFE = 1, T1200.BDQTDITEM, 0) BDQTDSAI,
                     IIF(T1200.BDTIPONFE = 0, T1200.BDVLRICMSEFETIVO, 0) BDVLRICMSEFETIVOENT, IIF(T1200.BDTIPONFE = 1, T1200.BDVLRICMSEFETIVO, 0) BDVLRICMSEFETIVOSAI, TPROD.BDALIQICMS, TPROD.BDALIQFECOP
              FROM (
                     SELECT TPROD.BDSESSAO, TPROD.BDREFERENCIA, TPROD.BDCODEMP, TPROD.BDCODPROD, TPROD.BDALIQICMS,TPROD.BDALIQFECOP
                      FROM TMP_VEF_EMP_TADRCST_1000_TEMP TPROD
                      WHERE TPROD.BDSESSAO = :PRSESSAO
                      GROUP BY TPROD.BDSESSAO, TPROD.BDREFERENCIA, TPROD.BDCODEMP, TPROD.BDCODPROD, TPROD.BDALIQICMS, TPROD.BDALIQFECOP
                    ) TPROD
        JOIN TMP_VEF_EMP_TADRCST_1200_TEMP T1200 ON (T1200.BDCODEMP = TPROD.BDCODEMP AND T1200.BDSESSAO = TPROD.BDSESSAO AND T1200.BDCODPROD = TPROD.BDCODPROD AND T1200.BDREFERENCIA = TPROD.BDREFERENCIA)
             ) T1200
        LEFT OUTER JOIN VEF_EMP_TADRCST_1100 T1100 ON (T1100.BDCODEMP = T1200.BDCODEMP AND T1100.BDREFERENCIA = T1200.BDREFERENCIA AND T1100.BDCODPROD = T1200.BDCODPROD)
        GROUP BY T1200.BDCODEMP, T1200.BDREFERENCIA,T1200.BDCODPROD, T1100.BDVLRUNITMEDIOITEMSUPENT, T1200.BDALIQICMS, T1200.BDALIQFECOP
        ) T1200;

  /*TOTAL 1300*/
    INSERT INTO VEF_EMP_TADRCST_1300 (BDCODEMP,BDREFERENCIA,BDCODPROD,BDQTDTOTALSAI,BDTTVLRICMSEFETIVO,BDVLRCONFICMSENT,BDVLRICMSRECUPERAR,BDVLRICMSSTRECUPERAR,BDVLRFCPRECUPER)
    SELECT BDCODEMP,BDREFERENCIA,BDCODPROD,BDQTDTOTAL, BDVLRICMSEFETIVO,BDVLRCONFICMSSAIDA, BDVLRRECUPERAR,
           IIF((BDVLRRECUPERAR-BDVLRFCPRESSARCIR) < 0,0,(BDVLRRECUPERAR-BDVLRFCPRESSARCIR)) BDVLRICMSSTRECUPERAR,BDVLRFCPRESSARCIR
     FROM(
          SELECT BDCODEMP,BDREFERENCIA,BDCODPROD,(BDQTDSAI - BDQTDENT) BDQTDTOTAL, BDVLRICMSEFETIVO,
                 BDVLRCONFICMSSAIDA,  IIF(PLANO.BDA12 = 0, BDVLRCONFICMSSAIDA, IIF((BDVLRCONFICMSSAIDA-BDVLRICMSEFETIVO) < 0, 0, (BDVLRCONFICMSSAIDA-BDVLRICMSEFETIVO))) BDVLRRECUPERAR,
                 IIF(BDALIQFECOP > 0,((BDVLRUNITMEDOICMSST*(BDALIQFECOP/100))*(BDQTDSAI - BDQTDENT)),0) BDVLRFCPRESSARCIR
            FROM(
                 SELECT T1300.BDCODEMP, T1300.BDREFERENCIA,T1300.BDCODPROD,SUM(T1300.BDQTDSAI) BDQTDSAI, SUM(T1300.BDQTDENT) BDQTDENT,
                        (SUM(BDVLRICMSEFETIVOSAI) - SUM(BDVLRICMSEFETIVOENT)) BDVLRICMSEFETIVO,T1100.BDVLRUNITMEDIOITEMSUPENT,
                        ((SUM(BDQTDSAI) - SUM(BDQTDENT)) * BDVLRUNITMEDIOITEMSUPENT) BDVLRCONFICMSSAIDA,T1100.BDVLRUNITMEDOICMSST,T1300.BDALIQICMS, T1300.BDALIQFECOP
                  FROM (
                        SELECT T1300.BDCODEMP, T1300.BDREFERENCIA,T1300.BDCODPROD, IIF(T1300.BDTIPONFE = 0, T1300.BDQTDITEM, 0) BDQTDENT, IIF(T1300.BDTIPONFE = 1, T1300.BDQTDITEM, 0) BDQTDSAI,
                        IIF(T1300.BDTIPONFE = 0, T1300.BDVLRICMSEFETIVO, 0) BDVLRICMSEFETIVOENT, IIF(T1300.BDTIPONFE = 1, T1300.BDVLRICMSEFETIVO, 0) BDVLRICMSEFETIVOSAI, TPROD.BDALIQICMS, TPROD.BDALIQFECOP
                        FROM (
                              SELECT TPROD.BDSESSAO, TPROD.BDREFERENCIA, TPROD.BDCODEMP, TPROD.BDCODPROD, TPROD.BDALIQICMS,TPROD.BDALIQFECOP
                              FROM TMP_VEF_EMP_TADRCST_1000_TEMP TPROD
                              WHERE TPROD.BDSESSAO = :PRSESSAO
                              GROUP BY TPROD.BDSESSAO, TPROD.BDREFERENCIA, TPROD.BDCODEMP, TPROD.BDCODPROD, TPROD.BDALIQICMS, TPROD.BDALIQFECOP
                             ) TPROD
                  JOIN TMP_VEF_EMP_TADRCST_1300_TEMP T1300 ON (T1300.BDCODEMP = TPROD.BDCODEMP AND T1300.BDSESSAO = TPROD.BDSESSAO AND T1300.BDCODPROD = TPROD.BDCODPROD AND T1300.BDREFERENCIA = TPROD.BDREFERENCIA)) T1300
                  LEFT OUTER JOIN VEF_EMP_TADRCST_1100 T1100 ON (T1100.BDCODEMP = T1300.BDCODEMP AND T1100.BDREFERENCIA = T1300.BDREFERENCIA AND T1100.BDCODPROD = T1300.BDCODPROD)
                  GROUP BY T1300.BDCODEMP, T1300.BDREFERENCIA,T1300.BDCODPROD,T1100.BDVLRUNITMEDIOITEMSUPENT,T1100.BDVLRUNITMEDOICMSST, T1300.BDALIQICMS, T1300.BDALIQFECOP
                 )
            LEFT OUTER JOIN VEF_BASE_TPLACONFADRCST PLANO ON (PLANO.BDCODPLANOCONFADRCST = :PRCODPLACONFADRCST) --MATHEUS AMARAL - ADRCST - Exportação registro 0000 #cartão9! #Exportação2/20!
         );

  /*TOTAL 1400*/
 INSERT INTO VEF_EMP_TADRCST_1400 (BDCODEMP, BDREFERENCIA,BDCODPROD, BDQTDTOTALSAI, BDTTVLRICMSEFETIVO, BDVLRCONFICMSSAI, BDVLRICMSRECUPERAR)
 SELECT BDCODEMP, BDREFERENCIA,BDCODPROD,(BDQTDSAI - BDQTDENT) BDQTDTOTAL, BDVLRICMSEFETIVO, BDVLRCONFICMSSAIDA,IIF(PLANO.BDA13 = 0, BDVLRCONFICMSSAIDA, IIF((BDVLRCONFICMSSAIDA - BDVLRICMSEFETIVO) < 0, 0, (BDVLRCONFICMSSAIDA - BDVLRICMSEFETIVO))) BDVLRRECUPERAR
 FROM (
       SELECT T1400.BDCODEMP, T1400.BDREFERENCIA,T1400.BDCODPROD, SUM(T1400.BDQTDSAI) BDQTDSAI, SUM(T1400.BDQTDENT) BDQTDENT,(SUM(BDVLRICMSEFETIVOSAI) - SUM(BDVLRICMSEFETIVOENT)) BDVLRICMSEFETIVO,
       T1100.BDVLRUNITMEDIOITEMSUPENT,((SUM(BDQTDSAI) - SUM(BDQTDENT)) * COALESCE(BDVLRUNITMEDIOITEMSUPENT,1)) BDVLRCONFICMSSAIDA
       FROM (
             SELECT T1400.BDCODEMP, T1400.BDREFERENCIA,T1400.BDCODPROD, IIF(T1400.BDTIPONFE = 0, T1400.BDQTDITEM, 0) BDQTDENT,IIF(T1400.BDTIPONFE = 1, T1400.BDQTDITEM, 0) BDQTDSAI,
             IIF(T1400.BDTIPONFE = 0, T1400.BDVLRICMSEFETIVO, 0) BDVLRICMSEFETIVOENT, IIF(T1400.BDTIPONFE = 1, T1400.BDVLRICMSEFETIVO, 0) BDVLRICMSEFETIVOSAI
             FROM (
                   SELECT TPROD.BDSESSAO, TPROD.BDREFERENCIA, TPROD.BDCODEMP, TPROD.BDCODPROD, TPROD.BDALIQICMS,TPROD.BDALIQFECOP
                   FROM TMP_VEF_EMP_TADRCST_1000_TEMP TPROD
                   WHERE TPROD.BDSESSAO = :PRSESSAO
                   GROUP BY TPROD.BDSESSAO, TPROD.BDREFERENCIA, TPROD.BDCODEMP, TPROD.BDCODPROD, TPROD.BDALIQICMS, TPROD.BDALIQFECOP
                   ) TPROD
      JOIN TMP_VEF_EMP_TADRCST_1400_TEMP T1400 ON (T1400.BDCODEMP = TPROD.BDCODEMP AND T1400.BDSESSAO = TPROD.BDSESSAO AND T1400.BDCODPROD = TPROD.BDCODPROD AND T1400.BDREFERENCIA = TPROD.BDREFERENCIA)) T1400
      LEFT OUTER JOIN VEF_EMP_TADRCST_1100 T1100 ON (T1100.BDCODEMP = T1400.BDCODEMP AND T1100.BDREFERENCIA = T1400.BDREFERENCIA AND T1100.BDCODPROD = T1400.BDCODPROD)
      GROUP BY T1400.BDCODEMP, T1400.BDREFERENCIA,T1400.BDCODPROD, T1100.BDVLRUNITMEDIOITEMSUPENT, T1100.BDVLRUNITMEDOICMSST
      )
 LEFT OUTER JOIN VEF_BASE_TPLACONFADRCST PLANO ON (PLANO.BDCODPLANOCONFADRCST = :PRCODPLACONFADRCST); --MATHEUS AMARAL - ADRCST - Exportação registro 0000 #cartão9! #Exportação2/20!

  /*TOTAL 1500*/
 INSERT INTO VEF_EMP_TADRCST_1500 (BDCODEMP, BDREFERENCIA,BDCODPROD, BDQTDTOTALSAI, BDVLRICMSRECUPERAR, BDVLRICMSSTRECUPERAR, BDPERCMVA)
 SELECT BDCODEMP, BDREFERENCIA,BDCODPROD,(BDQTDSAI - BDQTDENT) BDQTDTOTAL,BDVLRICMSSTRECUPUNID,((BDQTDSAI - BDQTDENT) *BDVLRICMSSTRECUPUNID) BDAPUICMSSTRECUPERAR,BDPERCMVA
 FROM (
       SELECT T1500.BDCODEMP, T1500.BDREFERENCIA,T1500.BDCODPROD, SUM(T1500.BDQTDSAI) BDQTDSAI, SUM(T1500.BDQTDENT) BDQTDENT,
       IIF(T1500.BDALIQICMS > 0,CAST((((T1100.BDVLRUNITMEDOICMSST/(1+(T1500.BDPERCMVA/100)))*((T1500.BDPERCMVA/100)* IIF(T1500.BDALIQICMS = 18,0.70,0.50)))* (T1500.BDALIQICMS/100)) AS DM_NUMERIC_15_2),0)  BDVLRICMSSTRECUPUNID,
       T1500.BDPERCMVA
       FROM (
             SELECT T1500.BDCODEMP, T1500.BDREFERENCIA,T1500.BDCODPROD, IIF(T1500.BDTIPONFE = 0, T1500.BDQTDITEM, 0) BDQTDENT,IIF(T1500.BDTIPONFE = 1, T1500.BDQTDITEM, 0) BDQTDSAI,
             TPROD.BDPERCMVA,TPROD.BDALIQICMS
             FROM (
                   SELECT TPROD.BDSESSAO, TPROD.BDREFERENCIA, TPROD.BDCODEMP, TPROD.BDCODPROD, TPROD.BDALIQICMS,TPROD.BDPERCMVA
                   FROM TMP_VEF_EMP_TADRCST_1000_TEMP TPROD
                   WHERE TPROD.BDSESSAO = :PRSESSAO
                   GROUP BY TPROD.BDSESSAO, TPROD.BDREFERENCIA, TPROD.BDCODEMP, TPROD.BDCODPROD, TPROD.BDALIQICMS, TPROD.BDPERCMVA
                   ) TPROD
             JOIN TMP_VEF_EMP_TADRCST_1500_TEMP T1500 ON (T1500.BDCODEMP = TPROD.BDCODEMP AND T1500.BDSESSAO = TPROD.BDSESSAO AND T1500.BDCODPROD = TPROD.BDCODPROD AND T1500.BDREFERENCIA = TPROD.BDREFERENCIA)
            ) T1500
      LEFT OUTER JOIN VEF_EMP_TADRCST_1100 T1100 ON (T1100.BDCODEMP = T1500.BDCODEMP AND T1100.BDREFERENCIA = T1500.BDREFERENCIA AND T1100.BDCODPROD = T1500.BDCODPROD)
      GROUP BY T1500.BDCODEMP, T1500.BDREFERENCIA,T1500.BDCODPROD,  T1100.BDVLRUNITMEDIOITEMSUPENT, T1100.BDVLRUNITMEDOICMSST,T1500.BDPERCMVA,T1500.BDALIQICMS

      );
END^

CREATE OR ALTER procedure SP_APURACAO_ADRCST_PR_INCONS (
    PRSESSAO integer,
    PRDATAINICIO date,
    PRDATAFIM date)
as
BEGIN

  -- 20 - Nota fiscal de entrada de devolução X ignorada porque não está referenciada a nota fiscal de compra no registro C113
  -- 23 - Nota fiscal de entrada de devolução ignorada porque a nota fiscal no registro C113 possui a referência da data de emissão diferente da referência apurada
  INSERT INTO VEF_INCON_TADRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT D.BDCODINCONSISTENCIA BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '1100' BDREG,
         D.BDCHAVE, D.BDORDEM, D.BDORDEMPROD
  FROM TMP_VEF_EMP_TADRCST_1100_TEMP D
  LEFT OUTER JOIN TMP_VEF_EMP_TADRCSTGER_TEMP G ON (G.BDSESSAO = D.BDSESSAO AND G.BDCODEMP = D.BDCODEMP AND G.BDREFERENCIA = D.BDREFERENCIA)
  WHERE D.BDSESSAO = :PRSESSAO
  AND D.BDCODINCONSISTENCIA IN (20,23)
  GROUP BY D.BDCODINCONSISTENCIA,D.BDCODEMP, D.BDREFERENCIA, D.BDCHAVE, D.BDORDEM, D.BDORDEMPROD;  

  INSERT INTO VEF_INCON_TADRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT D.BDCODINCONSISTENCIA BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '1200' BDREG,
         D.BDCHAVE, D.BDORDEM, D.BDORDEMPROD
  FROM TMP_VEF_EMP_TADRCST_1200_TEMP D
  LEFT OUTER JOIN TMP_VEF_EMP_TADRCSTGER_TEMP G ON (G.BDSESSAO = D.BDSESSAO AND G.BDCODEMP = D.BDCODEMP AND G.BDREFERENCIA = D.BDREFERENCIA)
  WHERE D.BDSESSAO = :PRSESSAO
  AND D.BDCODINCONSISTENCIA IN (20,23)
  GROUP BY D.BDCODINCONSISTENCIA,D.BDCODEMP, D.BDREFERENCIA, D.BDCHAVE, D.BDORDEM, D.BDORDEMPROD;  

  INSERT INTO VEF_INCON_TADRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT D.BDCODINCONSISTENCIA BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '1300' BDREG,
         D.BDCHAVE, D.BDORDEM, D.BDORDEMPROD
  FROM TMP_VEF_EMP_TADRCST_1300_TEMP D
  LEFT OUTER JOIN TMP_VEF_EMP_TADRCSTGER_TEMP G ON (G.BDSESSAO = D.BDSESSAO AND G.BDCODEMP = D.BDCODEMP AND G.BDREFERENCIA = D.BDREFERENCIA)
  WHERE D.BDSESSAO = :PRSESSAO
  AND D.BDCODINCONSISTENCIA IN (20,23)
  GROUP BY D.BDCODINCONSISTENCIA,D.BDCODEMP, D.BDREFERENCIA, D.BDCHAVE, D.BDORDEM, D.BDORDEMPROD;  

  INSERT INTO VEF_INCON_TADRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT D.BDCODINCONSISTENCIA BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '1400' BDREG,
         D.BDCHAVE, D.BDORDEM, D.BDORDEMPROD
  FROM TMP_VEF_EMP_TADRCST_1400_TEMP D
  LEFT OUTER JOIN TMP_VEF_EMP_TADRCSTGER_TEMP G ON (G.BDSESSAO = D.BDSESSAO AND G.BDCODEMP = D.BDCODEMP AND G.BDREFERENCIA = D.BDREFERENCIA)
  WHERE D.BDSESSAO = :PRSESSAO
  AND D.BDCODINCONSISTENCIA IN (20,23)
  GROUP BY D.BDCODINCONSISTENCIA,D.BDCODEMP, D.BDREFERENCIA, D.BDCHAVE, D.BDORDEM, D.BDORDEMPROD;  

  INSERT INTO VEF_INCON_TADRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT D.BDCODINCONSISTENCIA BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '1500' BDREG,
         D.BDCHAVE, D.BDORDEM, D.BDORDEMPROD
  FROM TMP_VEF_EMP_TADRCST_1500_TEMP D
  LEFT OUTER JOIN TMP_VEF_EMP_TADRCSTGER_TEMP G ON (G.BDSESSAO = D.BDSESSAO AND G.BDCODEMP = D.BDCODEMP AND G.BDREFERENCIA = D.BDREFERENCIA)
  WHERE D.BDSESSAO = :PRSESSAO
  AND D.BDCODINCONSISTENCIA IN (20,23)
  GROUP BY D.BDCODINCONSISTENCIA,D.BDCODEMP, D.BDREFERENCIA, D.BDCHAVE, D.BDORDEM, D.BDORDEMPROD;

   -- 21 - Participante #PARTICIPANTE não está marcado como "Órgão público" no mês da apuração, verifique os dados por referência
  INSERT INTO VEF_INCON_TADRCST (BDCODINC, BDCODEMP, BDREFERENCIA, BDCODIGO, BDREG, BDCHAVE, BDORDEM, BDORDEMPRO)
  SELECT 21 BDCODINC, D.BDCODEMP, D.BDREFERENCIA, GETORDEMSEQUENCIAL_STR(D.BDCODEMP || '.' || D.BDREFERENCIA, D.BDCODEMP), '1400' BDREG,
         D.BDCHAVE, D.BDORDEM, D.BDORDEMPROD
  FROM TMP_VEF_EMP_TADRCST_1400_TEMP D
  LEFT OUTER JOIN TMP_VEF_EMP_TADRCSTGER_TEMP G ON (G.BDSESSAO = D.BDSESSAO AND G.BDCODEMP = D.BDCODEMP AND G.BDREFERENCIA = D.BDREFERENCIA)
  WHERE D.BDSESSAO = :PRSESSAO
  AND D.BDCODINCONSISTENCIA = 21
  GROUP BY D.BDCODEMP, D.BDREFERENCIA, D.BDCHAVE, D.BDORDEM, D.BDORDEMPROD;

  DELETE FROM TMP_VEF_EMP_TADRCST_1100_TEMP
  WHERE BDSESSAO = :PRSESSAO
  AND BDCODINCONSISTENCIA IN (20,23);

  DELETE FROM TMP_VEF_EMP_TADRCST_1200_TEMP
  WHERE BDSESSAO = :PRSESSAO
  AND BDCODINCONSISTENCIA IN (20,23);

  DELETE FROM TMP_VEF_EMP_TADRCST_1300_TEMP
  WHERE BDSESSAO = :PRSESSAO
  AND BDCODINCONSISTENCIA IN (20,23);

  DELETE FROM TMP_VEF_EMP_TADRCST_1400_TEMP
  WHERE BDSESSAO = :PRSESSAO
  AND BDCODINCONSISTENCIA IN (20,23);

  DELETE FROM TMP_VEF_EMP_TADRCST_1500_TEMP
  WHERE BDSESSAO = :PRSESSAO
  AND BDCODINCONSISTENCIA IN (20,23);
  
END
^

CREATE OR ALTER PROCEDURE SP_APURACAO_ADRCST_PR (
    PRSESSAO INTEGER,
    PRDATAINICIO DATE,
    PRDATAFIM DATE,
    PRCODPLACONFADRCST INTEGER)
AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WREFERENCIA INTEGER;
DECLARE VARIABLE WIGNORARPROD VARCHAR(5);
BEGIN
  WREFERENCIA = CAST((EXTRACT(YEAR FROM :PRDATAINICIO) || LPAD(EXTRACT(MONTH FROM PRDATAINICIO),2,'0')) AS INTEGER);
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(WREFERENCIA);

  DELETE FROM VEF_INCON_TADRCST D
  WHERE EXISTS(SELECT FIRST 1 G.BDCODEMP
               FROM TMP_VEF_EMP_TADRCSTGER_TEMP G
               WHERE G.BDSESSAO = :PRSESSAO AND
                     G.BDCODEMP = D.BDCODEMP AND
                     G.BDREFERENCIA = D.BDREFERENCIA);

  --SETORDEMSEQUENCIAL_STR(0);
  FOR
    SELECT DISTINCT T.BDCODEMP
    FROM TMP_VEF_EMP_TADRCSTGER_TEMP T
    WHERE T.BDSESSAO = :PRSESSAO
    INTO WCODEMP DO
  BEGIN
    SETORDEMSEQUENCIAL_STR(:WCODEMP);
  END

  DELETE FROM VEF_EMP_TADRCSTGER ADRCST
  WHERE EXISTS (SELECT FIRST 1 T.BDCODEMP
                FROM TMP_VEF_EMP_TADRCSTGER_TEMP T
                WHERE T.BDSESSAO = :PRSESSAO
                  AND T.BDCODEMP = ADRCST.BDCODEMP
                  AND T.BDREFERENCIA = ADRCST.BDREFERENCIA);

  INSERT INTO VEF_EMP_TADRCSTGER(BDCODEMP, BDREFERENCIA, BDCODCONT)
  SELECT T.BDCODEMP, T.BDREFERENCIA, T.BDCODCONT
  FROM TMP_VEF_EMP_TADRCSTGER_TEMP T
  WHERE T.BDSESSAO = :PRSESSAO;

  /*INSERE OS VALORES DE SAÍDA QUE SERÃO USADOS DEPOIS NUMA TEMP*/
  INSERT INTO TMP_VEF_EMP_SAIADRCST_TEMP (BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODPROD, BDBCST,
  BDVLRST, BDBCFCPSTRET, BDVLRFCPSTRET, BDBCICMSSTRET, BDVLRICMSSTRET, BDBCFCPRETIDO, BDFCPRETIDO, BDISPRODST)
  SELECT :PRSESSAO,SAI.BDCODEMP, SAI.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO, PRO.BDCODPROD,PRO.BDBCST,
        PRO.BDVLRST, PRO.BDBCFCPSTRET, PRO.BDVLRFCPSTRET,PRO.BDBCICMSSTRET,PRO.BDVLRICMSSTRET,PRO.BDBCFCPRETIDO, PRO.BDFCPRETIDO,
        IIF((PRO.BDVLRST > 0) OR (PRO.BDVLRFCPSTRET > 0) OR (PRO.BDVLRICMSSTRET > 0) OR (PRO.BDFCPRETIDO > 0), 'TRUE', 'FALSE') BDISPRODST
        FROM(
            SELECT SAI.BDCODEMP, SAI.BDCHAVE FROM TMP_VEF_EMP_TADRCSTGER_TEMP ADRCST
            LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = ADRCST.BDCODEMP AND SAI.BDREFLAN = ADRCST.BDREFERENCIA)
            WHERE ADRCST.BDSESSAO = :PRSESSAO
        ) SAI
  JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE);

  /*Apuração dos produtos com ST - REG 1000*/
  EXECUTE PROCEDURE SP_APURACAO_ADRCST_PR_1000(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);

  /*Apuração das entradas - REG 1110 e 1120 - Totalizador 1100*/
  EXECUTE PROCEDURE SP_APURACAO_ADRCST_PR_1110_1120(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);

  /*Apuração das Saídas - REG 1210 e 1220 - Totalizador 1100*/
  EXECUTE PROCEDURE SP_APURACAO_ADRCST_PR_1210_1220(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);

  /*Apuração das saídas "interestaduais" e devoluções de vendas - REG 1310 e 1320 - Totalizador 1300*/
  EXECUTE PROCEDURE SP_APURACAO_ADRCST_PR_1310_1320(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);

  /*Apuração das Saídas art. 119  - REG 1410 e 1420 - Totalizador 1400*/
  EXECUTE PROCEDURE SP_APURACAO_ADRCST_PR_1410_1420(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);

  /*Apuração das Saídas do Simples Nacional - REF 1510 e 1520 - Totalizador 1500*/
  EXECUTE PROCEDURE SP_APURACAO_ADRCST_PR_1510_1520(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);

  /*EXECUTA AS INCONSISTÊNCIAS - ANTES DO GRAVAR PORQUE AQUI DELETA ALGUNS REGISTROS INCONSISTENTES*/
  EXECUTE PROCEDURE SP_APURACAO_ADRCST_PR_INCONS(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);

  /*ESSA PROCEDURE VERIFICA A DIFERENÇA DE QUANTIDADE ENTRE AS ENTRADAS E SAÍDAS
  SE EXISTES MAIS SAÍDAS DO QUE ENTRADA, VAI BUSCAS AS NOTAS DE ENTRADAS DE ATÉ 12 MESES ANTERIORES PARA FECHAR O CÁLCULO*/
  EXECUTE PROCEDURE SP_APURACAO_ADRCST_PR_VERIF_ENT(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);

  /*GRAVA AS TEMP NA FISICA*/
  EXECUTE PROCEDURE SP_APURACAO_ADRCST_PR_GRAVAR(:PRSESSAO, :PRCODPLACONFADRCST);  

  /**           AJUSTES DO 1000                    **/

  /*EXCLUI OS PRODUTOS DO T1000 QUE NÃO ENTRARAM EM NENHUMA REGRA*/
 DELETE FROM TMP_VEF_EMP_TADRCST_1000_TEMP T1000 WHERE NOT EXISTS (
                                                     SELECT BDCODPROD
                                                        FROM (
                                                            SELECT T1200.BDCODEMP,T1200.BDREFERENCIA,T1200.BDCODPROD,0 BDQTDTOTALENT, T1200.BDQTDTOTALSAI
                                                            FROM VEF_EMP_TADRCST_1200 T1200
                                                            WHERE T1200.BDCODEMP = T1000.BDCODEMP AND T1200.BDREFERENCIA = T1000.BDREFERENCIA
                                                            GROUP BY T1200.BDCODEMP,T1200.BDREFERENCIA,T1200.BDCODPROD,T1200.BDQTDTOTALSAI
                                                            UNION ALL
                                                            SELECT T1300.BDCODEMP,T1300.BDREFERENCIA,T1300.BDCODPROD,0 BDQTDTOTALENT, T1300.BDQTDTOTALSAI
                                                            FROM VEF_EMP_TADRCST_1300 T1300
                                                            WHERE T1300.BDCODEMP = T1000.BDCODEMP AND T1300.BDREFERENCIA = T1000.BDREFERENCIA
                                                            GROUP BY T1300.BDCODEMP,T1300.BDREFERENCIA,T1300.BDCODPROD,T1300.BDQTDTOTALSAI
                                                            UNION ALL
                                                            SELECT T1400.BDCODEMP,T1400.BDREFERENCIA,T1400.BDCODPROD,0 BDQTDTOTALENT, T1400.BDQTDTOTALSAI
                                                            FROM VEF_EMP_TADRCST_1400 T1400
                                                            WHERE T1400.BDCODEMP = T1000.BDCODEMP AND T1400.BDREFERENCIA = T1000.BDREFERENCIA
                                                            GROUP BY T1400.BDCODEMP,T1400.BDREFERENCIA,T1400.BDCODPROD,T1400.BDQTDTOTALSAI
                                                            UNION ALL
                                                            SELECT T1500.BDCODEMP,T1500.BDREFERENCIA,T1500.BDCODPROD,0 BDQTDTOTALENT, T1500.BDQTDTOTALSAI
                                                            FROM VEF_EMP_TADRCST_1500 T1500
                                                            WHERE T1500.BDCODEMP = T1000.BDCODEMP AND T1500.BDREFERENCIA = T1000.BDREFERENCIA
                                                            GROUP BY T1500.BDCODEMP,T1500.BDREFERENCIA,T1500.BDCODPROD,T1500.BDQTDTOTALSAI
                                                        )
                                                        WHERE BDCODPROD = T1000.BDCODPROD
                                                        GROUP BY BDCODEMP, BDREFERENCIA,BDCODPROD
                                                        );

    /*Exclui do 1110 e 1110 quando não tem no 1000*/
  DELETE FROM VEF_EMP_TADRCST_1100 T1100 WHERE T1100.BDREFERENCIA = :WREFERENCIA AND
                                                NOT EXISTS (SELECT BDCODPROD
                                                        FROM (
                                                            SELECT TPROD.BDCODEMP,TPROD.BDREFERENCIA,TPROD.BDCODPROD
                                                            FROM TMP_VEF_EMP_TADRCST_1000_TEMP TPROD
                                                            WHERE TPROD.BDSESSAO = :PRSESSAO
                                                            GROUP BY TPROD.BDCODEMP,TPROD.BDREFERENCIA,TPROD.BDCODPROD
                                                             )
                                                        WHERE BDCODPROD = T1100.BDCODPROD
                                                        AND BDREFERENCIA = T1100.BDREFERENCIA
                                                        GROUP BY BDCODEMP, BDREFERENCIA,BDCODPROD
                                                        );

  DELETE FROM VEF_EMP_TADRCST_1110_1120 T1110 WHERE T1110.BDREFERENCIA = :WREFERENCIA AND
                                             NOT EXISTS (SELECT BDCODPROD
                                                        FROM (
                                                            SELECT TPROD.BDCODEMP,TPROD.BDREFERENCIA,TPROD.BDCODPROD
                                                            FROM TMP_VEF_EMP_TADRCST_1000_TEMP TPROD
                                                            WHERE TPROD.BDSESSAO = :PRSESSAO
                                                            GROUP BY TPROD.BDCODEMP,TPROD.BDREFERENCIA,TPROD.BDCODPROD
                                                             )
                                                        WHERE BDCODPROD = T1110.BDCODPROD
                                                        AND BDREFERENCIA = T1110.BDREFERENCIA
                                                        GROUP BY BDCODEMP, BDREFERENCIA,BDCODPROD
                                                        );

  /*1000 - Produtos - Insere o 1000 com as quantidades corretas*/
  INSERT INTO VEF_EMP_TADRCST_1000 (BDCODEMP, BDREFERENCIA, BDCODPROD, BDCODPRODVINC,BDDESCPROD, BDINDFECOP, BDCODIGOEAN, BDCODCOMBANP, BDNCMPROD, BDCODCEST,
                                    BDCODUNIMED, BDALIQICMS, BDALIQFECOP, BDQTDENTPERIODO, BDQTDSAIDAPERIODO)
  SELECT T1000.BDCODEMP, T1000.BDREFERENCIA, T1000.BDCODPROD, T1000.BDCODPRODVINC, T1000.BDDESCPROD, T1000.BDINDFECOP,
         T1000.BDCODIGOEAN, T1000.BDCODCOMBANP, T1000.BDNCMPROD, T1000.BDCODCEST, T1000.BDCODUNIMED, T1000.BDALIQICMS,
         T1000.BDALIQFECOP, T1100.BDQTDTOTALITEM, (COALESCE(T1200.BDQTDTOTALSAI,0) + COALESCE(T1300.BDQTDTOTALSAI,0) + COALESCE(T1400.BDQTDTOTALSAI,0) + COALESCE(T1500.BDQTDTOTALSAI,0)) BDQTDSAIDAPERIODO
  FROM (
        SELECT T1000.BDCODEMP, T1000.BDREFERENCIA, T1000.BDCODPROD, T1000.BDCODPRODVINC, T1000.BDDESCPROD,
               T1000.BDINDFECOP, T1000.BDCODIGOEAN, T1000.BDCODCOMBANP, T1000.BDNCMPROD, T1000.BDCODCEST,
               T1000.BDCODUNIMED, T1000.BDALIQICMS, T1000.BDALIQFECOP
        FROM TMP_VEF_EMP_TADRCST_1000_TEMP T1000
        WHERE BDSESSAO = :PRSESSAO
        GROUP BY BDCODEMP, BDREFERENCIA, BDCODPROD, BDCODPRODVINC, BDDESCPROD, BDINDFECOP, BDCODIGOEAN, BDCODCOMBANP, BDNCMPROD, BDCODCEST, BDCODUNIMED, BDALIQICMS, BDALIQFECOP
        ) T1000
  LEFT OUTER JOIN VEF_EMP_TADRCST_1100 T1100 ON (T1100.BDCODEMP = T1000.BDCODEMP AND T1100.BDREFERENCIA = T1000.BDREFERENCIA AND T1100.BDCODPROD = T1000.BDCODPROD)
  LEFT OUTER JOIN VEF_EMP_TADRCST_1200 T1200 ON (T1200.BDCODEMP = T1000.BDCODEMP AND T1200.BDREFERENCIA = T1000.BDREFERENCIA AND T1200.BDCODPROD = T1000.BDCODPROD)
  LEFT OUTER JOIN VEF_EMP_TADRCST_1300 T1300 ON (T1300.BDCODEMP = T1000.BDCODEMP AND T1300.BDREFERENCIA = T1000.BDREFERENCIA AND T1300.BDCODPROD = T1000.BDCODPROD)
  LEFT OUTER JOIN VEF_EMP_TADRCST_1400 T1400 ON (T1400.BDCODEMP = T1000.BDCODEMP AND T1400.BDREFERENCIA = T1000.BDREFERENCIA AND T1400.BDCODPROD = T1000.BDCODPROD)
  LEFT OUTER JOIN VEF_EMP_TADRCST_1500 T1500 ON (T1500.BDCODEMP = T1000.BDCODEMP AND T1500.BDREFERENCIA = T1000.BDREFERENCIA AND T1500.BDCODPROD = T1000.BDCODPROD);

  /**           AJUSTES DO 1000                    **/

  SELECT a.bdIGNORARPROD
  FROM VEF_BASE_TPLACONFADRCST a
  WHERE a.bdCODPLANOCONFADRCST = :prCODPLACONFADRCST
  INTO :wIGNORARPROD;

  IF (:wIGNORARPROD = 'TRUE') THEN
    BEGIN
      /* 17 - Quantidade de saída do produto não foi encontrado nas entradas nos últimos 12 meses
         Faz aqui e na "SP_APURACAO_ADRCST_PR_INCONS".
         Aqui por que precisa ver as quantidades finais de entradas e saidas. */
      INSERT INTO VEF_INCON_TADRCST (bdCODINC, bdCODEMP, bdREFERENCIA, bdCODIGO, bdREG, bdCODPROD)
      SELECT 17 bdCODINC, t1000.bdCODEMP, t1000.bdREFERENCIA, GETORDEMSEQUENCIAL_STR(t1000.bdCODEMP || '.' || t1000.bdREFERENCIA, t1000.bdCODEMP), '1000' bdREG,
             t1000.bdCODPROD
      FROM VEF_EMP_TADRCST_1000 t1000
      WHERE t1000.bdREFERENCIA BETWEEN (EXTRACT(YEAR FROM :PRDATAINICIO) || LPAD(EXTRACT(MONTH FROM :PRDATAINICIO),2,'0')) AND (EXTRACT(YEAR FROM :PRDATAFIM) || LPAD(EXTRACT(MONTH FROM :PRDATAFIM),2,'0'))
        AND COALESCE(t1000.bdQTDENTPERIODO,0) < COALESCE(t1000.bdQTDSAIDAPERIODO,0)
      ORDER BY t1000.bdCODPROD;

      -- Apaga os produtos com a inconsistencia "17 - Quantidade de saída do produto não foi encontrado nas entradas nos últimos 12 meses"
      DELETE FROM VEF_EMP_TADRCST_1000 t1000 WHERE COALESCE(t1000.bdQTDENTPERIODO,0) < COALESCE(t1000.bdQTDSAIDAPERIODO,0);
    
      FOR
        SELECT t.bdCODEMP, t.bdREFERENCIA
        FROM TMP_VEF_EMP_TADRCSTGER_TEMP T
        WHERE T.BDSESSAO = :PRSESSAO
        INTO :wCODEMP, :wREFERENCIA DO
      BEGIN
        -- Apaga os produtos com a inconsistencia "17 - Quantidade de saída do produto não foi encontrado nas entradas nos últimos 12 meses"
        DELETE FROM VEF_EMP_TADRCST_1100      a WHERE a.bdCODEMP = :wCODEMP AND a.bdREFERENCIA = :wREFERENCIA AND a.bdCODPROD IN(SELECT i.bdCODPROD FROM VEF_INCON_TADRCST i WHERE i.bdcodinc = 17 AND i.bdCODEMP = a.bdCODEMP AND i.bdREFERENCIA = a.bdREFERENCIA);
        DELETE FROM VEF_EMP_TADRCST_1110_1120 a WHERE a.bdCODEMP = :wCODEMP AND a.bdREFERENCIA = :wREFERENCIA AND a.bdCODPROD IN(SELECT i.bdCODPROD FROM VEF_INCON_TADRCST i WHERE i.bdcodinc = 17 AND i.bdCODEMP = a.bdCODEMP AND i.bdREFERENCIA = a.bdREFERENCIA);
        DELETE FROM VEF_EMP_TADRCST_1200      a WHERE a.bdCODEMP = :wCODEMP AND a.bdREFERENCIA = :wREFERENCIA AND a.bdCODPROD IN(SELECT i.bdCODPROD FROM VEF_INCON_TADRCST i WHERE i.bdcodinc = 17 AND i.bdCODEMP = a.bdCODEMP AND i.bdREFERENCIA = a.bdREFERENCIA);
        DELETE FROM VEF_EMP_TADRCST_1210_1220 a WHERE a.bdCODEMP = :wCODEMP AND a.bdREFERENCIA = :wREFERENCIA AND a.bdCODPROD IN(SELECT i.bdCODPROD FROM VEF_INCON_TADRCST i WHERE i.bdcodinc = 17 AND i.bdCODEMP = a.bdCODEMP AND i.bdREFERENCIA = a.bdREFERENCIA);
        DELETE FROM VEF_EMP_TADRCST_1300      a WHERE a.bdCODEMP = :wCODEMP AND a.bdREFERENCIA = :wREFERENCIA AND a.bdCODPROD IN(SELECT i.bdCODPROD FROM VEF_INCON_TADRCST i WHERE i.bdcodinc = 17 AND i.bdCODEMP = a.bdCODEMP AND i.bdREFERENCIA = a.bdREFERENCIA);
        DELETE FROM VEF_EMP_TADRCST_1310_1320 a WHERE a.bdCODEMP = :wCODEMP AND a.bdREFERENCIA = :wREFERENCIA AND a.bdCODPROD IN(SELECT i.bdCODPROD FROM VEF_INCON_TADRCST i WHERE i.bdcodinc = 17 AND i.bdCODEMP = a.bdCODEMP AND i.bdREFERENCIA = a.bdREFERENCIA);
        DELETE FROM VEF_EMP_TADRCST_1400      a WHERE a.bdCODEMP = :wCODEMP AND a.bdREFERENCIA = :wREFERENCIA AND a.bdCODPROD IN(SELECT i.bdCODPROD FROM VEF_INCON_TADRCST i WHERE i.bdcodinc = 17 AND i.bdCODEMP = a.bdCODEMP AND i.bdREFERENCIA = a.bdREFERENCIA);
        DELETE FROM VEF_EMP_TADRCST_1410_1420 a WHERE a.bdCODEMP = :wCODEMP AND a.bdREFERENCIA = :wREFERENCIA AND a.bdCODPROD IN(SELECT i.bdCODPROD FROM VEF_INCON_TADRCST i WHERE i.bdcodinc = 17 AND i.bdCODEMP = a.bdCODEMP AND i.bdREFERENCIA = a.bdREFERENCIA);
        DELETE FROM VEF_EMP_TADRCST_1500      a WHERE a.bdCODEMP = :wCODEMP AND a.bdREFERENCIA = :wREFERENCIA AND a.bdCODPROD IN(SELECT i.bdCODPROD FROM VEF_INCON_TADRCST i WHERE i.bdcodinc = 17 AND i.bdCODEMP = a.bdCODEMP AND i.bdREFERENCIA = a.bdREFERENCIA);
        DELETE FROM VEF_EMP_TADRCST_1510_1520 a WHERE a.bdCODEMP = :wCODEMP AND a.bdREFERENCIA = :wREFERENCIA AND a.bdCODPROD IN(SELECT i.bdCODPROD FROM VEF_INCON_TADRCST i WHERE i.bdcodinc = 17 AND i.bdCODEMP = a.bdCODEMP AND i.bdREFERENCIA = a.bdREFERENCIA);
      END
    END

  /*RESUMO*/
  EXECUTE PROCEDURE SP_APURACAO_ADRCST_RESUMO(:PRSESSAO,:PRDATAINICIO,:PRDATAFIM);

  DELETE FROM TMP_VEF_EMP_TADRCSTGER_TEMP   WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_SAIADRCST_TEMP    WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TADRCST_1000_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TADRCST_1100_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TADRCST_1200_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TADRCST_1300_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TADRCST_1400_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TADRCST_1500_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM  TMP_VEF_EMP_ENTADRCST_TEMP   WHERE BDSESSAO = :PRSESSAO;

  DELETE FROM TMP_VEF_EMP_TMOVPROSAI WHERE BDSESSAO = -1; -- Alt.: #171712 - Olhar descrição em "SP_APURACAO_ADRCST_PR_1000"...
  DELETE FROM TMP_VEF_EMP_TMOVSAI_TEMP WHERE BDSESSAO = -1; -- Alt.: #171712 - Olhar descrição em "SP_APURACAO_ADRCST_PR_1000"...
END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_ADRCST_BLOCO_0 (
    PRCODEMP INTEGER,
    PRREFINI INTEGER,
    PRFINALIDADE INTEGER,
    PRARQUIVO varchar(260) character set WIN1252,
    PRA11R12 INTEGER,
    PRA12R13 INTEGER,
    PRA13R14 INTEGER,
    PRA14R15 INTEGER)
AS
BEGIN
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         '0000.'||tref.bdCODEMP AS bdCHAVEREG,
         '0000' AS BDREG,
         tref.bdCODEMP,
         ('0000'||                                                       --A01
          '|110'||                                                       --A02
          '|'||SUBSTRING(:PRREFINI FROM 5 FOR 2)||SUBSTRING(:PRREFINI FROM 1 FOR 4)||  --A03
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(tref.bdCNPJEMP))|| --A04
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(tref.bdIEEMP))||   --A05
          '|'||tref.bdNOMEMP||                                           --A06
          '|'||:prFINALIDADE||                                           --A07
          '|'||                                                          --A08
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(tref.bdCNPJEMP))|| --A09
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(tref.bdIEEMP))||   --A10
          '|'||COALESCE((SELECT FIRST 1 :prA11R12 FROM VEF_EMP_TADRCST_1200 a WHERE a.bdCODEMP = :prCODEMP AND a.bdREFERENCIA = :prREFINI),'')||--A11
          '|'||COALESCE((SELECT FIRST 1 :prA12R13 FROM VEF_EMP_TADRCST_1300 a WHERE a.bdCODEMP = :prCODEMP AND a.bdREFERENCIA = :prREFINI),'')||--A12
          '|'||COALESCE((SELECT FIRST 1 :prA13R14 FROM VEF_EMP_TADRCST_1400 a WHERE a.bdCODEMP = :prCODEMP AND a.bdREFERENCIA = :prREFINI),'')||--A13
          '|'||COALESCE((SELECT FIRST 1 :prA14R15 FROM VEF_EMP_TADRCST_1500 a WHERE a.bdCODEMP = :prCODEMP AND a.bdREFERENCIA = :prREFINI),'')  --A14
          )
  FROM SP_CONSULTAEMPRESAS_SIS(:PRREFINI, :prCODEMP, 0) tref
  LEFT OUTER JOIN VW_EMP_REF_TOTAL trefsis ON (trefsis.bdCODEMP = tref.bdCODEMP);
END
^

create or alter procedure SP_EXPORTA_ADRCST_BLOCO_B (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
  --1000 - PRODUTOS
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDCODEMP, BDLINHA)
  SELECT :PRARQUIVO AS BDID,
         '1000.'||PROD.BDCODEMP||'.'||PROD.BDCODPROD AS BDCHAVEREG,
         '1000' AS BDREG,
         PROD.BDCODEMP,
         ('1000|'||                                  --B01
         COALESCE(PROD.BDINDFECOP, '')||             --B02
         '|'||COALESCE(PROD.BDCODPRODVINC, '')||     --B03
         '|'||COALESCE(PROD.BDCODIGOEAN, '')||       --B04
         '|'||COALESCE(ANP.BDREGEXP, '')||           --B05
         '|'||COALESCE((SELECT RESULT FROM SP_TIRATODOSSINAIS(NCM.BDCLASSIFICACAO)), '')||--B06
         '|'||COALESCE((SELECT RESULT FROM SP_TIRATODOSSINAIS(CEST.BDCLASSCEST)), '')||   --B07
         '|'||COALESCE((SELECT RESULT FROM SP_TIRATODOSSINAIS(PROD.BDDESCPROD)), '')||    --B08
         '|'||COALESCE(UN.BDAPEUNIMED, '')||         --B09
         '|'||FORMATFLOAT('#0.00',PROD.BDALIQICMS)|| --B10
         '|'||IIF(COALESCE(PROD.BDALIQFECOP,0)=0,'',FORMATFLOAT('#0.00',PROD.BDALIQFECOP))||--B11
         '|'||COALESCE(PROD.BDQTDENTPERIODO, '')||   --B12
         '|'||COALESCE(PROD.BDQTDSAIDAPERIODO, '')   --B13
         )
  FROM VEF_EMP_TADRCST_1000 PROD
  LEFT OUTER JOIN TNCM NCM ON (NCM.BDNCMPROD = PROD.BDNCMPROD)
  LEFT OUTER JOIN TCEST CEST ON (CEST.BDCODCEST = PROD.BDCODCEST)
  LEFT OUTER JOIN TUNIDADEMEDIDA UN ON (UN.BDCODUNIMED = PROD.BDCODUNIMED)
  LEFT OUTER JOIN VEF_BASE_TTABCOMBANP ANP ON (ANP.BDCODCOMBANP = PROD.BDCODCOMBANP)
  WHERE PROD.BDCODEMP = :PRCODEMP
  AND PROD.BDREFERENCIA BETWEEN :PRREFINI AND :PRREFFIM;
END
^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_C (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
  --1010 - Lançamento de Inventário
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDCODEMP, BDLINHA)
  SELECT :PRARQUIVO AS BDID,
         '1000.'||INV.BDCODEMP||'.'||INV.BDCODPROD||'.1010' AS BDCHAVEREG,
         '1010' AS BDREG,
         INV.BDCODEMP,
         ('1010|'||                                          --C01
          INV.BDCODPRODVINC||                                --C02
          '|'||INV.BDAPEUNIMED||                             --C03
          '|'||FORMATFLOAT('#0.000',INV.BDQTDINV)||          --C04
          '|'||FORMATFLOAT('#0.00',INV.BDVLRTOTALINV) ||     --C05
          '|'                                                --C06
          ) 
  FROM (
        SELECT MAX(INV.BDREFINV) BDREFINV, INV.BDCODEMP, INV.BDCODPROD, UN.BDAPEUNIMED, PROD.BDCODPRODVINC,
               SUM(COALESCE(INV.BDQTDINV,0)) BDQTDINV, SUM(COALESCE(INV.BDVLRTOTALINV,0)) BDVLRTOTALINV
        FROM(
             SELECT PROD.BDCODEMP,PROD.BDCODPROD,PROD.BDCODUNIMED,PROD.BDCODPRODVINC
             FROM VEF_EMP_TADRCST_1000 PROD
             WHERE PROD.BDCODEMP = :PRCODEMP
             AND PROD.BDREFERENCIA BETWEEN :PRREFINI AND :PRREFFIM
             ) PROD
        JOIN VEF_EMP_TMOVINV INV ON (INV.BDCODEMP = PROD.BDCODEMP AND INV.BDCODPROD = PROD.BDCODPROD)
        LEFT OUTER JOIN TUNIDADEMEDIDA UN ON (UN.BDCODUNIMED = PROD.BDCODUNIMED)
        GROUP BY INV.BDCODEMP, INV.BDCODPROD,UN.BDAPEUNIMED, PROD.BDCODPRODVINC
        ) INV;
END
^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_D (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
  --1100 - TOTALIZADO DO 1110 E 1120
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDCODEMP, BDLINHA)
  SELECT :PRARQUIVO AS BDID,
         '1000.'||TOT.BDCODEMP||'.'||PRO.BDCODPROD||'.1100' AS BDCHAVEREG,
         '1100' AS BDREG,
         TOT.BDCODEMP,
         ('1100|'||                                               --D01
         FORMATFLOAT('#0.000',TOT.BDQTDTOTALITEM)||               --D02
         '|'||FORMATFLOAT('#0.00',TOT.BDMENORVLRUNIITEM)||        --D03
         '|'||FORMATFLOAT('#0.00',TOT.BDVLRUNITMEDOICMSST)||      --D04
         '|'||FORMATFLOAT('#0.00',TOT.BDVLRTTICMSSUPENT)||        --D05
         '|'||FORMATFLOAT('#0.00',TOT.BDVLRUNITMEDIOITEMSUPENT)   --D06
         ) 
  FROM VEF_EMP_TADRCST_1100 TOT
  JOIN TCADPRO_VINC PRO ON PRO.BDCODPROD = TOT.BDCODPROD AND PRO.BDCODEMP = TOT.BDCODEMP
  WHERE TOT.BDCODEMP = :PRCODEMP
  AND TOT.BDREFERENCIA BETWEEN :PRREFINI AND :PRREFFIM;
END
^

create or alter procedure SP_EXPORTA_ADRCST_BLOCO_E (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260) character set WIN1252)
as
BEGIN
  --1110 – IDENTIFICAÇÃO DAS NOTAS FISCAIS DEENTRADA
  --1120 - IDENTIFICAÇÃO DAS NOTAS FISCAIS DE DEVOLUÇÃO DASENTRADAS
  --0 Entrada normal 1 saida devolução
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDCODEMP, BDLINHA)
  SELECT :PRARQUIVO AS BDID,
         '1000.'||REG.BDCODEMP||'.'||REG.BDCODPROD||'.'||REG.BDREG||'.'||EXTRACT(YEAR FROM REG.BDDATAEMISSAO)||LPAD(EXTRACT(MONTH FROM REG.BDDATAEMISSAO),2,'0')||LPAD(EXTRACT(DAY FROM REG.BDDATAEMISSAO),2,'0')||'.'||REG.BDCHAVE||'.'||REG.BDORDEM||'.'||REG.BDORDEMPROD AS BDCHAVEREG,
         REG.BDREG,
         REG.BDCODEMP,
         (REG.BDREG||                                                  --E01
         '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS((SELECT BDDDMMAAAA FROM DDMMAAAA(REG.BDDATAEMISSAO))))||--E02

         IIF(REG.BDTIPONFE = 0,
           '|'||COALESCE(REG.BDRESPRETICMSST, ''),'')||                     --E03

         '|'||COALESCE(IIF(CHAR_LENGTH(REG.BDCSTICMSDESC) > 2, SUBSTRING(REG.BDCSTICMSDESC FROM CHAR_LENGTH(REG.BDCSTICMSDESC)-1 FOR 2), REG.BDCSTICMSDESC), '')|| --E04 CST deve levar apenas os 2 ultimos digitos
         '|'||COALESCE(REG.BDCHAVENFE, '')||                                --E05
         '|'||COALESCE(REG.BDNUMDOC, '')||                                  --E06
         '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(REG.BDCNPJEMITENTE))|| --E07
         '|'||COALESCE(REG.BDUFEMITENTE, '')||                              --E08
         '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(REG.BDCNPJCPFDESTIN))||--E09
         '|'||COALESCE(REG.BDUFDESTIN, '')||                                --E10
         '|'||COALESCE(SUBSTRING(REG.BDCODNAT FROM 1 FOR 4), '')||          --E11
         '|'||COALESCE(REG.BDORDEMPROD, '')||                               --E12
         '|'||COALESCE(REG.BDUNIDMED, '')||                                 --E13
         '|'||FORMATFLOAT('#0.000',REG.BDQTDITEM)||                         --E14
         '|'||FORMATFLOAT('#0.00',REG.BDVLRUNIT)||                          --E15
         '|'||FORMATFLOAT('#0.00',REG.BDBCICMSST)||                         --E16
         '|'||FORMATFLOAT('#0.00',REG.BDVLRICMSTTSUPENT)||                  --E17
         IIF(REG.BDTIPONFE = 1,                                             
             '|'||COALESCE(REG.BDCHAVENFEREFC113, '')||                     --E15D
             '|'||COALESCE(REG.BDNUMITEMREFC113, ''),                       --E16D
             '')
         )
  FROM (SELECT REG.*, ICMS.BDCSTICMS BDCSTICMSDESC, IIF(REG.BDTIPONFE = 0, '1110', '1120') BDREG, PRO.BDCODSAIDA
        FROM VEF_EMP_TADRCST_1110_1120 REG
        JOIN TCADPRO_VINC PRO ON PRO.BDCODPROD = REG.BDCODPROD AND PRO.BDCODEMP = REG.BDCODEMP
        JOIN VEF_BASE_TTABCSTICMS ICMS ON ICMS.BDCODCSTICMS = REG.BDCSTICMS
        WHERE REG.BDCODEMP = :PRCODEMP
          AND REG.BDREFERENCIA BETWEEN :PRREFINI AND :PRREFFIM
          AND ((REG.BDTIPONFE = 0) OR
               (NOT EXISTS(SELECT * FROM VEF_INCON_TADRCST i -- Quando for 1120 e tive inconsistencia, nao deve exportar
                           WHERE i.bdCODINC = 20 AND i.bdREG = '1120' AND i.bdCODEMP = reg.bdCODEMP AND i.bdCHAVE = reg.bdCHAVE
                             AND i.bdORDEM = reg.bdORDEM AND i.bdORDEMPRO = reg.bdORDEMPROD)) )
        ) REG;
END
^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_F (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
  --1200 - Totalizador do 1210 e 1220
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDCODEMP, BDLINHA)
  SELECT :PRARQUIVO AS BDID,
         '1000.'||TOT.BDCODEMP||'.'||PRO.BDCODPROD||'.1200' AS BDCHAVEREG,
         '1200' AS BDREG,
         TOT.BDCODEMP,
         ('1200|'||                                                --F01
          FORMATFLOAT('#0.000',TOT.BDQTDTOTALSAI)||                --F02
          '|'||FORMATFLOAT('#0.00',TOT.BDTTVLRICMSEFETIVO)||       --F03
          '|'||FORMATFLOAT('#0.00',TOT.BDVLRCONFICMSENT)||         --F04
          '|'||FORMATFLOAT('#0.00',TOT.BDVLRICMSRECUPERAR)||       --F05
          '|'||FORMATFLOAT('#0.00',TOT.BDVLRICMSCOMPLEMENTAR)||    --F06
          '|'||FORMATFLOAT('#0.00',TOT.BDVLRICMSSTRECUPERAR)||     --F07
          '|'||FORMATFLOAT('#0.00',TOT.BDVLRICMSSTCOMPLEMENTAR)||  --F08
          '|'||FORMATFLOAT('#0.00',TOT.BDVLRFCPRECUPER)||          --F09
          '|'||FORMATFLOAT('#0.00',TOT.BDVLRFCPCOMPLEMENTAR)       --F10
           )
  FROM VEF_EMP_TADRCST_1200 TOT
  JOIN TCADPRO_VINC PRO ON PRO.BDCODPROD = TOT.BDCODPROD AND PRO.BDCODEMP = TOT.BDCODEMP
  WHERE TOT.BDCODEMP = :PRCODEMP
    AND TOT.BDREFERENCIA BETWEEN :PRREFINI AND :PRREFFIM;
END
^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_G (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
  --1210 – Identificação das notas fiscais de saída para consumidor final
  --1220 – Identificação das notas fiscais de devolução das saídas para consumidor final
  --1 Saída normal 0 Entrada devolução
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDCODEMP, BDLINHA)
  SELECT :PRARQUIVO AS BDID,
         '1000.'||REG.BDCODEMP||'.'||REG.BDCODPROD||'.'||REG.BDREG||'.'||EXTRACT(YEAR FROM REG.BDDATAEMISSAO)||LPAD(EXTRACT(MONTH FROM REG.BDDATAEMISSAO),2,'0')||LPAD(EXTRACT(DAY FROM REG.BDDATAEMISSAO),2,'0')||'.'||REG.BDCHAVE||'.'||REG.BDORDEM||'.'||REG.BDORDEMPROD AS BDCHAVEREG,
         REG.BDREG,
         REG.BDCODEMP,
         (REG.BDREG||                                                  --G01
         '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS((SELECT BDDDMMAAAA FROM DDMMAAAA(REG.BDDATAEMISSAO))))||--G02
         '|'||COALESCE(IIF(CHAR_LENGTH(REG.BDCSTICMSDESC) > 2, SUBSTRING(REG.BDCSTICMSDESC FROM CHAR_LENGTH(REG.BDCSTICMSDESC)-1 FOR 2), REG.BDCSTICMSDESC), '')|| --G03 CST deve levar apenas os 2 ultimos digitos
         '|'||COALESCE(REG.BDCHAVENFE, '')||                                --G04
         '|'||COALESCE(REG.BDNUMDOC, '')||                                  --G05
         '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(REG.BDCNPJEMITENTE))|| --G06
         '|'||COALESCE(REG.BDUFEMITENTE, '')||                              --G07
         '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(REG.BDCNPJCPFDESTIN))||--G08
         '|'||COALESCE(REG.BDUFDESTIN, '')||                                --G09
         '|'||COALESCE(SUBSTRING(REG.BDCODNAT FROM 1 FOR 4), '')||          --G10
         '|'||COALESCE(REG.BDORDEMPROD, '')||                               --G11
         '|'||COALESCE(REG.BDUNIDMED, '')||                                 --G12
         '|'||FORMATFLOAT('#0.000',REG.BDQTDITEM)||                         --G13
         '|'||FORMATFLOAT('#0.00',REG.BDVLRUNIT)||                          --G14
         '|'||FORMATFLOAT('#0.00',REG.BDVLRICMSEFETIVO)||                   --G15
         IIF(REG.BDTIPONFE = 0,
             '|'||COALESCE(REG.BDCHAVENFEREFC113, '')||                     --G16D
             '|'||COALESCE(REG.BDNUMITEMREFC113, ''),                       --G17D
             '')
         )
  FROM (SELECT REG.*, ICMS.BDCSTICMS BDCSTICMSDESC, IIF(REG.BDTIPONFE = 1, '1210', '1220') BDREG, PRO.BDCODSAIDA
        FROM VEF_EMP_TADRCST_1210_1220 REG
        JOIN TCADPRO_VINC PRO ON PRO.BDCODPROD = REG.BDCODPROD AND PRO.BDCODEMP = REG.BDCODEMP
        JOIN VEF_BASE_TTABCSTICMS ICMS ON ICMS.BDCODCSTICMS = REG.BDCSTICMS
        WHERE REG.BDCODEMP = :PRCODEMP
          AND REG.BDREFERENCIA BETWEEN :PRREFINI AND :PRREFFIM
        ) REG;
END
^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_H (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
  --1300 - Totalizador do 1310 e 1320
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDCODEMP, BDLINHA)
  SELECT :PRARQUIVO AS BDID,
         '1000.'||TOT.BDCODEMP||'.'||PRO.BDCODPROD||'.1300' AS BDCHAVEREG,
         '1300' AS BDREG,
         TOT.BDCODEMP,
         ('1300|'||                                                --H01
          FORMATFLOAT('#0.000',TOT.BDQTDTOTALSAI)||                --H02
          '|'||FORMATFLOAT('#0.00',TOT.BDTTVLRICMSEFETIVO)||       --H03
          '|'||FORMATFLOAT('#0.00',TOT.BDVLRCONFICMSENT)||         --H04
          '|'||FORMATFLOAT('#0.00',TOT.BDVLRICMSRECUPERAR)||       --H05
          '|'||FORMATFLOAT('#0.00',TOT.BDVLRICMSSTRECUPERAR)||     --H06
          '|'||FORMATFLOAT('#0.00',TOT.BDVLRFCPRECUPER)            --H07
           )
  FROM VEF_EMP_TADRCST_1300 TOT
  JOIN TCADPRO_VINC PRO ON PRO.BDCODPROD = TOT.BDCODPROD AND PRO.BDCODEMP = TOT.BDCODEMP
  WHERE TOT.BDCODEMP = :PRCODEMP
    AND TOT.BDREFERENCIA BETWEEN :PRREFINI AND :PRREFFIM;
END
^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_I (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
  --1310 – Identificação das notas fiscais de saída para outros estados
  --1320 – Identificação das notas fiscais de devolução das saídas para outros estados
  --1 Saída normal 0 Entrada devolução
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDCODEMP, BDLINHA)
  SELECT :PRARQUIVO AS BDID,
         '1000.'||REG.BDCODEMP||'.'||REG.BDCODPROD||'.'||REG.BDREG||'.'||EXTRACT(YEAR FROM REG.BDDATAEMISSAO)||LPAD(EXTRACT(MONTH FROM REG.BDDATAEMISSAO),2,'0')||LPAD(EXTRACT(DAY FROM REG.BDDATAEMISSAO),2,'0')||'.'||REG.BDCHAVE||'.'||REG.BDORDEM||'.'||REG.BDORDEMPROD AS BDCHAVEREG,
         REG.BDREG,
         REG.BDCODEMP,
         (REG.BDREG||                                                  --I01
         '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS((SELECT BDDDMMAAAA FROM DDMMAAAA(REG.BDDATAEMISSAO))))||--I02
         '|'||COALESCE(IIF(CHAR_LENGTH(REG.BDCSTICMSDESC) > 2, SUBSTRING(REG.BDCSTICMSDESC FROM CHAR_LENGTH(REG.BDCSTICMSDESC)-1 FOR 2), REG.BDCSTICMSDESC), '')|| --I03 CST deve levar apenas os 2 ultimos digitos
         '|'||COALESCE(REG.BDCHAVENFE, '')||                                --I04
         '|'||COALESCE(REG.BDNUMDOC, '')||                                  --I05
         '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(REG.BDCNPJEMITENTE))|| --I06
         '|'||COALESCE(REG.BDUFEMITENTE, '')||                              --I07
         '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(REG.BDCNPJCPFDESTIN))||--I08
         '|'||COALESCE(REG.BDUFDESTIN, '')||                                --I09
         '|'||COALESCE(SUBSTRING(REG.BDCODNAT FROM 1 FOR 4), '')||          --I10
         '|'||COALESCE(REG.BDORDEMPROD, '')||                               --I11
         '|'||COALESCE(REG.BDUNIDMED, '')||                                 --I12
         '|'||FORMATFLOAT('#0.000',REG.BDQTDITEM)||                         --I13
         '|'||FORMATFLOAT('#0.00',REG.BDVLRUNIT)||                          --I14
         '|'||FORMATFLOAT('#0.00',REG.BDVLRICMSEFETIVO)||                   --I15
         IIF(REG.BDTIPONFE = 0,
             '|'||COALESCE(REG.BDCHAVENFEREFC113, '')||                     --I16D
             '|'||COALESCE(REG.BDNUMITEMREFC113, ''),                       --I17D
             '')
         )
  FROM (SELECT REG.*, ICMS.BDCSTICMS BDCSTICMSDESC, IIF(REG.BDTIPONFE = 1, '1310', '1320') BDREG, PRO.BDCODSAIDA
        FROM VEF_EMP_TADRCST_1310_1320 REG
        JOIN TCADPRO_VINC PRO ON PRO.BDCODPROD = REG.BDCODPROD AND PRO.BDCODEMP = REG.BDCODEMP
        JOIN VEF_BASE_TTABCSTICMS ICMS ON ICMS.BDCODCSTICMS = REG.BDCSTICMS
        WHERE REG.BDCODEMP = :PRCODEMP
          AND REG.BDREFERENCIA BETWEEN :PRREFINI AND :PRREFFIM
  ) REG;
END
^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_J (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
  --1400 - Totalizador do 1410 e 1420
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDCODEMP, BDLINHA)
  SELECT :PRARQUIVO AS BDID,
         '1000.'||TOT.BDCODEMP||'.'||PRO.BDCODPROD||'.1400' AS BDCHAVEREG,         
         '1400' AS BDREG,
         TOT.BDCODEMP,
         ('1400|'||                                                --J01
          FORMATFLOAT('#0.000',TOT.BDQTDTOTALSAI)||                --J02
          '|'||FORMATFLOAT('#0.00',TOT.BDTTVLRICMSEFETIVO)||       --J03
          '|'||FORMATFLOAT('#0.00',TOT.BDVLRCONFICMSSAI)||         --J04
          '|'||FORMATFLOAT('#0.00',TOT.BDVLRICMSRECUPERAR)         --J05
           )
  FROM VEF_EMP_TADRCST_1400 TOT
  JOIN TCADPRO_VINC PRO ON PRO.BDCODPROD = TOT.BDCODPROD AND PRO.BDCODEMP = TOT.BDCODEMP
  WHERE TOT.BDCODEMP = :PRCODEMP
    AND TOT.BDREFERENCIA BETWEEN :PRREFINI AND :PRREFFIM;
END
^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_K (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
  --1410 – Identificação das notasfiscais de saídas de que trata o art. 119 do Anexo IX do RICMS/17
  --1420 – Identificação das notas fiscais de devolução das saídas internas de que trata o art. 119 do Anexo IX do RICMS/17
  --1 Saída normal 0 Entrada devolução
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDCODEMP, BDLINHA)
  SELECT :PRARQUIVO AS BDID,
         '1000.'||REG.BDCODEMP||'.'||REG.BDCODPROD||'.'||REG.BDREG||'.'||EXTRACT(YEAR FROM REG.BDDATAEMISSAO)||LPAD(EXTRACT(MONTH FROM REG.BDDATAEMISSAO),2,'0')||LPAD(EXTRACT(DAY FROM REG.BDDATAEMISSAO),2,'0')||'.'||REG.BDCHAVE||'.'||REG.BDORDEM||'.'||REG.BDORDEMPROD AS BDCHAVEREG,
         REG.BDREG,
         REG.BDCODEMP,
         (REG.BDREG||                                                  --K01
         '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS((SELECT BDDDMMAAAA FROM DDMMAAAA(REG.BDDATAEMISSAO))))||--K02
         '|'||COALESCE(IIF(CHAR_LENGTH(REG.BDCSTICMSDESC) > 2, SUBSTRING(REG.BDCSTICMSDESC FROM CHAR_LENGTH(REG.BDCSTICMSDESC)-1 FOR 2), REG.BDCSTICMSDESC), '')|| --K03 CST deve levar apenas os 2 ultimos digitos
         '|'||COALESCE(REG.BDCHAVENFE, '')||                                --K04
         '|'||COALESCE(REG.BDNUMDOC, '')||                                  --K05
         '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(REG.BDCNPJEMITENTE))|| --K06
         '|'||COALESCE(REG.BDUFEMITENTE, '')||                              --K07
         '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(REG.BDCNPJCPFDESTIN))||--K08
         '|'||COALESCE(REG.BDUFDESTIN, '')||                                --K09
         '|'||COALESCE(SUBSTRING(REG.BDCODNAT FROM 1 FOR 4), '')||          --K10
         '|'||COALESCE(REG.BDORDEMPROD, '')||                               --K11
         '|'||COALESCE(REG.BDUNIDMED, '')||                                 --K12
         '|'||FORMATFLOAT('#0.000',REG.BDQTDITEM)||                         --K13
         '|'||FORMATFLOAT('#0.00',REG.BDVLRUNIT)||                          --K14
         '|'||FORMATFLOAT('#0.00',REG.BDVLRICMSEFETIVO)||                   --K15
         IIF(REG.BDTIPONFE = 0,
             '|'||COALESCE(REG.BDCHAVENFEREFC113, '')||                     --K16D
             '|'||COALESCE(REG.BDNUMITEMREFC113, ''),                       --K17D
             '')
         )
  FROM (SELECT REG.*, ICMS.BDCSTICMS BDCSTICMSDESC, IIF(REG.BDTIPONFE = 1, '1410', '1420') BDREG, PRO.BDCODSAIDA
        FROM VEF_EMP_TADRCST_1410_1420 REG
        JOIN TCADPRO_VINC PRO ON PRO.BDCODPROD = REG.BDCODPROD AND PRO.BDCODEMP = REG.BDCODEMP
        JOIN VEF_BASE_TTABCSTICMS ICMS ON ICMS.BDCODCSTICMS = REG.BDCSTICMS
        WHERE REG.BDCODEMP = :PRCODEMP
          AND REG.BDREFERENCIA BETWEEN :PRREFINI AND :PRREFFIM
  ) REG;
END
^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_L (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
  --1500 - Totalizador do 1510 e 1520
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDCODEMP, BDLINHA)
  SELECT :PRARQUIVO AS BDID,
         '1000.'||TOT.BDCODEMP||'.'||PRO.BDCODPROD||'.1500' AS BDCHAVEREG,
         '1500' AS BDREG,
         TOT.BDCODEMP,
         ('1500|'||                                                --L01
          FORMATFLOAT('#0.000',TOT.BDQTDTOTALSAI)||                --L02
          '|'||FORMATFLOAT('#0.00',TOT.BDVLRICMSRECUPERAR)||       --L03
          '|'||FORMATFLOAT('#0.00',TOT.BDVLRICMSSTRECUPERAR)||     --L04
          '|'||FORMATFLOAT('#0.00',TOT.bdpercmva)                  --L05
           )
  FROM VEF_EMP_TADRCST_1500 TOT
  JOIN TCADPRO_VINC PRO ON PRO.BDCODPROD = TOT.BDCODPROD AND PRO.BDCODEMP = TOT.BDCODEMP
  WHERE TOT.BDCODEMP = :PRCODEMP
    AND TOT.BDREFERENCIA BETWEEN :PRREFINI AND :PRREFFIM;

END
^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_M (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
  --1510 – Identificação das notas fiscais destinadas a contribuinte do Simples Nacional
  --1520 – Identificação das notasfiscais de devolução das saídas internas destinadas a contribuinte do Simples Nacional
  --1 Saída normal 0 Entrada devolução
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDCODEMP, BDLINHA)
  SELECT :PRARQUIVO AS BDID,
         '1000.'||REG.BDCODEMP||'.'||REG.BDCODPROD||'.'||REG.BDREG||'.'||EXTRACT(YEAR FROM REG.BDDATAEMISSAO)||LPAD(EXTRACT(MONTH FROM REG.BDDATAEMISSAO),2,'0')||LPAD(EXTRACT(DAY FROM REG.BDDATAEMISSAO),2,'0')||'.'||REG.BDCHAVE||'.'||REG.BDORDEM||'.'||REG.BDORDEMPROD AS BDCHAVEREG,
         REG.BDREG,
         REG.BDCODEMP,
         (REG.BDREG||                                                       --M01
         '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS((SELECT BDDDMMAAAA FROM DDMMAAAA(REG.BDDATAEMISSAO))))||--M02
         '|'||COALESCE(IIF(CHAR_LENGTH(REG.BDCSTICMSDESC) > 2, SUBSTRING(REG.BDCSTICMSDESC FROM CHAR_LENGTH(REG.BDCSTICMSDESC)-1 FOR 2), REG.BDCSTICMSDESC), '')|| --M03 CST deve levar apenas os 2 ultimos digitos
         '|'||COALESCE(REG.BDCHAVENFE, '')||                                --M04
         '|'||COALESCE(REG.BDNUMDOC, '')||                                  --M05
         '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(REG.BDCNPJEMITENTE))|| --M06
         '|'||COALESCE(REG.BDUFEMITENTE, '')||                              --M07
         '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(REG.BDCNPJCPFDESTIN))||--M08
         '|'||COALESCE(REG.BDUFDESTIN, '')||                                --M09
         '|'||COALESCE(SUBSTRING(REG.BDCODNAT FROM 1 FOR 4), '')||          --M10
         '|'||COALESCE(REG.BDORDEMPROD, '')||                               --M11
         '|'||COALESCE(REG.BDUNIDMED, '')||                                 --M12
         '|'||FORMATFLOAT('#0.000',REG.BDQTDITEM)||                         --M13
         '|'||FORMATFLOAT('#0.00',REG.BDVLRUNIT)||                          --M14
         IIF(REG.BDTIPONFE = 0,
             '|'||COALESCE(REG.BDCHAVENFEREFC113, '')||                     --M15D
             '|'||COALESCE(REG.BDNUMITEMREFC113, ''),                       --M16D
             '')
         )
  FROM (SELECT REG.*, ICMS.BDCSTICMS BDCSTICMSDESC, IIF(REG.BDTIPONFE = 1, '1510', '1520') BDREG, PRO.BDCODSAIDA
        FROM VEF_EMP_TADRCST_1510_1520 REG
        JOIN TCADPRO_VINC PRO ON PRO.BDCODPROD = REG.BDCODPROD AND PRO.BDCODEMP = REG.BDCODEMP
        JOIN VEF_BASE_TTABCSTICMS ICMS ON ICMS.BDCODCSTICMS = REG.BDCSTICMS
        WHERE REG.BDCODEMP = :PRCODEMP
          AND REG.BDREFERENCIA BETWEEN :PRREFINI AND :PRREFFIM
  ) REG;
END
^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST_BLOCO_RESUMO (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRARQUIVO varchar(260))
as
BEGIN
  --1999 - Encerramento do Bloco 1
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDCODEMP, BDLINHA)
  SELECT :PRARQUIVO AS BDID,
         '1999.'||BDCODEMP AS BDCHAVEREG,
         '1999' AS BDREG,
         BDCODEMP,
         ('1999'||    --R01
          '|'||CONTA  --R02
           )
    FROM (SELECT COUNT(1) +2 CONTA, BDCODEMP
          FROM TEXPORTACAO_SPED
          WHERE BDID = :PRARQUIVO
            AND BDREG <> '0000'
          GROUP BY BDCODEMP);

  --9000 – Apuração total do arquivo - RESUMO
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDCODEMP, BDLINHA)
  SELECT :PRARQUIVO AS BDID,
         '9000.'||RES.BDCODEMP AS BDCHAVEREG,
         '9000' AS BDREG,
         RES.BDCODEMP,
         ('9000'||                                   --X01
          '|'||FORMATFLOAT('#0.00',RES.BDVLRX02)||   --X02
          '|'||FORMATFLOAT('#0.00',RES.BDVLRX03)||   --X03
          '|'||FORMATFLOAT('#0.00',RES.BDVLRX04)||   --X04
          '|'||FORMATFLOAT('#0.00',RES.BDVLRX05)||   --X05
          '|'||FORMATFLOAT('#0.00',RES.BDVLRX06)||   --X06
          '|'||FORMATFLOAT('#0.00',RES.BDVLRX07)||   --X07
          '|'||FORMATFLOAT('#0.00',RES.BDVLRX08)     --X08

           )
  FROM (
        SELECT RES.BDCODEMP, RES.BDREFERENCIA,SUM(BDVLRX02) BDVLRX02,SUM(BDVLRX03) BDVLRX03,
        SUM(BDVLRX04) BDVLRX04,SUM(BDVLRX05) BDVLRX05,SUM(BDVLRX06) BDVLRX06,SUM(BDVLRX07) BDVLRX07,
        SUM(BDVLRX08) BDVLRX08
        FROM(
            SELECT RES.BDCODEMP,RES.BDREFERENCIA, IIF(RES.BDCAMPO = 1,RES.BDVALOR,0) BDVLRX02,
            IIF(RES.BDCAMPO = 2,RES.BDVALOR,0) BDVLRX03, IIF(RES.BDCAMPO = 3,RES.BDVALOR,0) BDVLRX04,
            IIF(RES.BDCAMPO = 4,RES.BDVALOR,0) BDVLRX05, IIF(RES.BDCAMPO = 5,RES.BDVALOR,0) BDVLRX06,
            IIF(RES.BDCAMPO = 6,RES.BDVALOR,0) BDVLRX07, IIF(RES.BDCAMPO = 7,RES.BDVALOR,0) BDVLRX08
            FROM VEF_EMP_TADRCST_RESUMO RES
            WHERE RES.BDCODEMP = :PRCODEMP
              AND RES.BDREFERENCIA BETWEEN :PRREFINI AND :PRREFFIM
        ) RES
        GROUP BY RES.BDCODEMP, RES.BDREFERENCIA
  ) RES;

  --9999 - Encerramento do arquivo
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDCODEMP, BDLINHA)
  SELECT :PRARQUIVO AS BDID,
         '9999.'||BDCODEMP AS BDCHAVEREG,
         '9999' AS BDREG,
         BDCODEMP,
         ('9999'||     --Z01
          '|'||CONTA   --Z02
           )
    FROM (SELECT COUNT(1) +1 CONTA, BDCODEMP
            FROM TEXPORTACAO_SPED
           WHERE BDID = :PRARQUIVO
          GROUP BY BDCODEMP);
END
^

CREATE OR ALTER procedure SP_EXPORTA_ADRCST (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRDTINV date,
    PRMOTIVOINVENTARIO integer,
    PRFINALIDADE integer,
    PRARQUIVO varchar(260),
    PRA11R12 integer,
    PRA12R13 integer,
    PRA13R14 integer,
    PRA14R15 integer)
as
declare variable WDTINI integer;
declare variable WDTFIM integer;
declare variable WLINHA blob sub_type 1 segment size 200;
declare variable WARQUIVO varchar(260);
begin
  wDtIni = EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0');
  wDtFim = EXTRACT(YEAR FROM :PRDTFIM)||LPAD(EXTRACT(MONTH FROM :PRDTFIM),2,'0');
  
  wArquivo = REPLACE(:prARQUIVO, '.tmp', '_e='||:PRCODEMP||'_.tmp');
  NEWFILE(:wArquivo);  
  
  DELETE FROM TEXPORTACAO_SPED WHERE BDID = :wArquivo;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT bdDATA FROM SP_PARSE_DATE(:prDTFIM, 'YYYYMM')));
  
  EXECUTE PROCEDURE SP_EXPORTA_ADRCST_BLOCO_0(:PRCODEMP, :wDtIni, :PRFINALIDADE, :wArquivo, :PRA11R12, :PRA12R13, :PRA13R14, :PRA14R15);
  EXECUTE PROCEDURE SP_EXPORTA_ADRCST_BLOCO_B(:PRCODEMP, :wDtIni, :wDtFim, :wArquivo);
  EXECUTE PROCEDURE SP_EXPORTA_ADRCST_BLOCO_C(:PRCODEMP, :wDtIni, :wDtFim, :wArquivo);
  EXECUTE PROCEDURE SP_EXPORTA_ADRCST_BLOCO_D(:PRCODEMP, :wDtIni, :wDtFim, :wArquivo);
  EXECUTE PROCEDURE SP_EXPORTA_ADRCST_BLOCO_E(:PRCODEMP, :wDtIni, :wDtFim, :wArquivo);
  EXECUTE PROCEDURE SP_EXPORTA_ADRCST_BLOCO_F(:PRCODEMP, :wDtIni, :wDtFim, :wArquivo);
  EXECUTE PROCEDURE SP_EXPORTA_ADRCST_BLOCO_G(:PRCODEMP, :wDtIni, :wDtFim, :wArquivo);
  EXECUTE PROCEDURE SP_EXPORTA_ADRCST_BLOCO_H(:PRCODEMP, :wDtIni, :wDtFim, :wArquivo);
  EXECUTE PROCEDURE SP_EXPORTA_ADRCST_BLOCO_I(:PRCODEMP, :wDtIni, :wDtFim, :wArquivo);
  EXECUTE PROCEDURE SP_EXPORTA_ADRCST_BLOCO_J(:PRCODEMP, :wDtIni, :wDtFim, :wArquivo);
  EXECUTE PROCEDURE SP_EXPORTA_ADRCST_BLOCO_K(:PRCODEMP, :wDtIni, :wDtFim, :wArquivo);
  EXECUTE PROCEDURE SP_EXPORTA_ADRCST_BLOCO_L(:PRCODEMP, :wDtIni, :wDtFim, :wArquivo);
  EXECUTE PROCEDURE SP_EXPORTA_ADRCST_BLOCO_M(:PRCODEMP, :wDtIni, :wDtFim, :wArquivo);
  EXECUTE PROCEDURE SP_EXPORTA_ADRCST_BLOCO_RESUMO(:PRCODEMP, :wDtIni, :wDtFim, :wArquivo);
  
  OPENARQ(:wArquivo,:PRCODEMP);
  
  FOR SELECT e.bdLINHA
      FROM TEXPORTACAO_SPED e
      WHERE e.bdID = :wArquivo
      ORDER BY e.bdCHAVEREG
      INTO :wLinha
  DO
    BEGIN
      WRITELNOA(:wLinha,:PRCODEMP);
    END

  CLOSEARQ(:wArquivo,:PRCODEMP);
END^

CREATE OR ALTER procedure SP_CARREGAFUNC_FOLHA_FISCAL (
    PRCODEMP integer,
    PRREF integer)
as
declare variable WBDCHAVE integer;
declare variable WBDNOME varchar(100);
declare variable WBDCPF varchar(14);
declare variable WBDESCOLARIDADE integer;
declare variable WBDDATAADMISSAO date;
declare variable WBDDATADESLIGAMENTO date;
declare variable WBDTIPOLAN integer;
begin

  execute procedure SP_SETA_COMPETENCIA(:PRREF);

  SETORDEMSEQUENCIAL_STR(0);

  insert into TMP_VEF_EMP_TCADFUNCIONARIOUNI (BDCODEMP, BDCHAVE, BDNOME, BDCPF, BDHABILITADO, BDESCOLARIDADE, BDDATAADMISSAO, BDDATADESLIGAMENTO, BDTIPOLAN)
  select :PRCODEMP, GETORDEMSEQUENCIAL_STR('INCON.'||:PRCODEMP||'.'||:PRREF, :prCODEMP), CAD.BDNOMCOL, CON.BDCPFCOL, 'FALSE', CAD.BDGRAUINSTCOL, CON.BDDATAADICCOL, RES.BDDATARESCISAO, 156
    from VW_VRH_EMP_TCOLCON_REF RE
    join VRH_EMP_TCOLCON_CAD CAD on (RE.BDCODEMP = CAD.BDCODEMP and RE.BDREFCOL = CAD.BDREFCOL and RE.BDCODCOL = CAD.BDCODCOL)
    join VRH_EMP_TCOLCON CON on (RE.BDCODEMP = CON.BDCODEMP and RE.BDCODCOL = CON.BDCODCOL)
    left outer join VRH_EMP_TRESCISAO RES on (RES.BDCODEMP = RE.BDCODEMP and RES.bdcodcol = RE.BDCODCOL)
  where ((RE.BDCODEMP = :PRCODEMP) and
         (CAD.BDCONTRCOL = 0) and
         (not exists (select BDCHAVE from VEF_EMP_TCADFUNCIONARIO_ISSUNI UNI
                            where UNI.BDCODEMP = RE.BDCODEMP and UNI.BDCPF = CON.BDCPFCOL and UNI.BDDATAADMISSAO = CON.BDDATAADICCOL)));

  for
      select CAD.BDNOMCOL, CON.BDCPFCOL, CAD.BDGRAUINSTCOL, CON.BDDATAADICCOL, RES.BDDATARESCISAO, 156
    from VW_VRH_EMP_TCOLCON_REF RE
    join VRH_EMP_TCOLCON_CAD CAD on (RE.BDCODEMP = CAD.BDCODEMP and RE.BDREFCOL = CAD.BDREFCOL and RE.BDCODCOL = CAD.BDCODCOL)
    join VRH_EMP_TCOLCON CON on (RE.BDCODEMP = CON.BDCODEMP and RE.BDCODCOL = CON.BDCODCOL)
    left outer join VRH_EMP_TRESCISAO RES on (RE.bdcodemp = RES.bdcodemp and RE.bdcodcol = RES.bdcodcol)
    where ((RE.BDCODEMP = :PRCODEMP) and
           (CAD.BDCONTRCOL = 0) and
           (exists(select BDCHAVE from VEF_EMP_TCADFUNCIONARIO_ISSUNI UNI
                            where UNI.BDCODEMP = RE.BDCODEMP and UNI.BDCPF = CON.BDCPFCOL and UNI.BDDATAADMISSAO = CON.BDDATAADICCOL)))
    into :WBDNOME, :WBDCPF, :WBDESCOLARIDADE, :WBDDATAADMISSAO, :WBDDATADESLIGAMENTO, :WBDTIPOLAN
  do
  begin
    update VEF_EMP_TCADFUNCIONARIO_ISSUNI set BDCODEMP = :PRCODEMP, BDNOME = :WBDNOME, BDCPF = :WBDCPF, BDESCOLARIDADE = :WBDESCOLARIDADE, BDDATAADMISSAO = :WBDDATAADMISSAO, BDDATADESLIGAMENTO = :WBDDATADESLIGAMENTO, BDTIPOLAN = :WBDTIPOLAN
        where BDCPF = :WBDCPF and BDDATAADMISSAO = :WBDDATAADMISSAO;
  end
end^

create or alter procedure SP_COPIA_CONFIGURACAO (
    PRTABELA varchar(64),
    PRCODIGOCOPIADO integer,
    PRCODIGONOVO integer,
    PRCAMPOCODIGO varchar(64))
as
declare variable WSQL varchar(3000);
declare variable WCAMPO varchar(64);
declare variable WCAMPOSINSERT varchar(1000);
DECLARE VARIABLE WTABLE VARCHAR(64);
BEGIN
  IF ((:prTABELA = '') OR (:prTABELA IS NULL) OR
      (:prCODIGOCOPIADO <= 0) OR (:prCODIGOCOPIADO IS NULL) OR
      (:prCODIGONOVO <= 0) OR (:prCODIGONOVO IS NULL) OR
      (:PRCAMPOCODIGO = '')) THEN
    EXIT;
    
  /* Limpa a configuração que está sendo copiada */
  wSQL = 'DELETE FROM '||:prTABELA||' WHERE '||:PRCAMPOCODIGO||' = '||:prCODIGONOVO||';';
  EXECUTE STATEMENT wSQL;


  wCamposInsert = '';
  /* Obtém os campos da tabela que seram copiados */
  wSQL = 'SELECT r.RDB$FIELD_NAME as BDCAMPO '||
         'FROM RDB$RELATION_FIELDS r '||
         'WHERE r.RDB$RELATION_NAME = '''||:prTABELA||'''';

  FOR EXECUTE STATEMENT wSQL INTO wCampo DO
    BEGIN
      IF ((UPPER(wCampo) <> UPPER(:PRCAMPOCODIGO)) and (UPPER(wCampo) <> 'BDREADONLY')) THEN /* A PK vai inserir fixa a nova chave */
        wCamposInsert = wCamposInsert||','||TRIM(wCampo);
    END
    
  /* Cria insert da tabela de formulas */
  wSQL = 'INSERT INTO '||:prTABELA||' ('||:PRCAMPOCODIGO||''||wCamposInsert||') '||
         'SELECT '||:prCodigoNovo||wCamposInsert||' FROM '||:prTABELA||' WHERE '||:PRCAMPOCODIGO||'  = '||:prCODIGOCOPIADO;
  EXECUTE STATEMENT wSQL;
  FOR SELECT DISTINCT CO.RDB$RELATION_NAME
      FROM RDB$RELATION_CONSTRAINTS CO
      INNER JOIN RDB$INDEX_SEGMENTS ID ON (CO.RDB$INDEX_NAME = ID.RDB$INDEX_NAME)
      INNER JOIN RDB$REF_CONSTRAINTS RE ON (CO.RDB$CONSTRAINT_NAME = RE.RDB$CONSTRAINT_NAME)
      INNER JOIN RDB$RELATION_CONSTRAINTS CD ON (RE.RDB$CONST_NAME_UQ = CD.RDB$CONSTRAINT_NAME)
      WHERE CD.RDB$RELATION_NAME = :PRTABELA INTO :WTABLE DO
    BEGIN
        EXECUTE PROCEDURE SP_COPIA_CONFIGURACAO(:WTABLE,:PRCODIGOCOPIADO, :PRCODIGONOVO, :PRCAMPOCODIGO);
    END

END
^


CREATE OR ALTER procedure SP_EXPORTA_BLOCOC_SAI_REG300 (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRPERFIL integer)
as
BEGIN
  /*****************************************************************************
   *                                   C350                                    *
   ****************************************************************************/

   INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
   SELECT :PRARQUIVO BDID,
         LPAD(SAI.BDCODEMP, 6, '0')||'.2.'||LPAD(SAI.BDCHAVE, 10, '0')||'.C300.C350.'||LPAD(GETORDEMSEQUENCIAL_STR(SAI.BDCHAVE,SAI.BDCODEMP), 10, '0'),
         'C350' BDREG,
         ('|C350'|| --REG
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(M.BDSERIE, ''))|| -- SER
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(M.BDSUBSERIE, '|', ''))|| --SUB_SER
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(M.BDNUMDOCINI, ''))|| --NUM_DOC
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY')))|| --DT_DOC
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(1/*#95257 - se todos números forem iguais retorna em branco*/, Null, TERCOL.BDCGCTER, '', '')), ''))|| --CNPJ_COL
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ','))||    --VL_MERC
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(sai.BDVLRCONTAB, '.', ','))|| --VL_DOC
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(M.BDDESCONTONOTA, 0.00), '.', ','))|| --VL_DESC
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C350.BDVLRTOTPIS, 0.00), '.', ','))|| --VL_PIS
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', REPLACE(COALESCE(C350.BDVLRTOTCOFINS, 0.00), '.', ','))|| --VL_COFINS
         '|'||IIF(M.BDCODSITNF IN (2, 3, 4, 5), '', COALESCE(C350.BDCODCTA, ''))|| --COD_CTA
         '|') BDLINHA, IIF(((M.BDMODELO = 2) OR (M.BDCODSITNF IN (2, 3, 4, 5))), NULL, M.BDCODTER) BDCODTER
   FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE,
               SUM(COALESCE(I.BDVLRCONTAB, 0.00)) BDVLRCONTAB
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM VEF_EMP_TMOVsai M
              WHERE M.BDCODEMP = :PRCODEMP
              AND M.BDMODELO IN (2)
              AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
       ) SAI
   LEFT OUTER JOIN VEF_EMP_TC300350SAI C350 ON (C350.BDCODEMP = SAI.BDCODEMP AND C350.BDCHAVE = SAI.BDCHAVE)
   LEFT OUTER JOIN (
                    SELECT P.BDCODEMP, P.BDCHAVE, SUM(COALESCE(P.BDVLRDESC, 0)) BDVLRDESC, SUM(COALESCE(P.BDVLRPIS, 0)) BDVLRPIS, SUM(COALESCE(P.BDVLRCOFINS, 0)) BDVLRCOFINS, SUM(COALESCE(P.BDVLRITEM, 0)) BDVLRITEM
                    FROM VEF_EMP_TMOVPROSAI P
                    WHERE P.BDCODEMP = :PRCODEMP
                    GROUP BY P.BDCODEMP, P.BDCHAVE
                  ) PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE)
   JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = SAI.BDCODEMP AND M.BDCHAVE = SAI.BDCHAVE)
   LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TERCOL ON (TERCOL.BDCODTER = M.BDCODTER);

   /*****************************************************************************
   *                                   C370                                    *
   ****************************************************************************/
   SETORDEMSEQUENCIAL_STR(:PRCODEMP);
   INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD)
   SELECT :PRARQUIVO BDID,
          LPAD(SAI.BDCODEMP, 6, '0')||'.2.'||LPAD(SAI.BDCHAVE, 10, '0')||'.C300.C370.'||LPAD(PRO.BDORDEM, 6, '0')||'.'||LPAD(PRO.BDORDEMPRO, 6, '0'),
          'C370' BDREG,
          ('|C370'|| --REG
          '|'||GETORDEMSEQUENCIAL_STR(PRO.BDCHAVE,PRO.BDCODEMP)|| --NUM_ITEM
          '|'||IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')),
                    IIF(((VINC.BDCODPROD IS NULL) OR (COALESCE(VINC.BDCODPROD,'') = '')),COALESCE(PROD_UNICO.BDCODPROD,''),COALESCE(VINC.BDCODPROD,'')),
                    COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
          '|'||REPLACE(CAST(COALESCE(PRO.BDQTDITEM, 0.00) AS NUMERIC(15, 3)), '.', ',')|| --QTD
          '|'||COALESCE(IIF(((UN.BDAPEUNIMED IS NULL) OR (UN.BDAPEUNIMED = '')), UN.BDAPEUNIMED, UN.BDAPEUNIMED), '')|| --UNID
          '|'||REPLACE(COALESCE(PRO.BDVLRITEM, 0.00), '.', ',')|| --VL_ITEM
          '|'||REPLACE(COALESCE(PRO.BDVLRDESC, 0.00), '.', ',')|| --VL_DESC
          '|') BDLINHA, PRO.BDCODPROD
   FROM (
         SELECT SAI.BDCODEMP, SAI.BDCHAVE, I.BDORDEM, I.BDCODNAT
         FROM (
               SELECT MOV.BDCODEMP, MOV.BDCHAVE
               FROM (
                     SELECT M.BDCODEMP, M.BDCHAVE
                     FROM VEF_EMP_TMOVSAI M
                     WHERE M.BDCODEMP = :PRCODEMP
                     AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                     AND M.BDMODELO IN (2)
                     AND M.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                    ) MOV
              ) SAI
         JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
        ) SAI
   JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVE AND PRO.BDORDEM = SAI.BDORDEM)
   LEFT OUTER JOIN TCADPRO PROD_UNICO ON(PROD_UNICO.BDCODPROD = PRO.BDCODPROD)
   LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
   LEFT OUTER JOIN TUNIDADEMEDIDA UN ON(UN.BDCODUNIMED = VINC.BDCODUNIMED)
   JOIN VEF_EMP_TMOVSAI M ON(M.BDCODEMP = SAI.BDCODEMP AND M.BDCHAVE = SAI.BDCHAVE);


  /*****************************************************************************
   *                                   C390                                    *
   ****************************************************************************/
   SETORDEMSEQUENCIAL_STR(:PRCODEMP);
   INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
   SELECT :PRARQUIVO BDID,
         LPAD(C390.BDCODEMP, 6, '0')||'.2.'||LPAD(C390.BDCHAVE, 10, '0')||'.C300.C390.'||LPAD(GETORDEMSEQUENCIAL_STR(C390.BDCHAVE,C390.BDCODEMP), 10, '0'),
         'C390' BDREG,
         ('|C390'|| --REG
         '|'||COALESCE(C390.BDCSTICMS, '')|| --CST_ICMS
         '|'||COALESCE(C390.BDCODNAT, '')|| --CFOP
         '|'||REPLACE(CAST(COALESCE(C390.BDALIQICMS, 0) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
         '|'||REPLACE(COALESCE(IIF(C390.BDMODELO = 2, (COALESCE(C390.BDVLRITEM + C390.BDVLRDESPACESSORIA + C390.BDVLRFRETE, 0) - COALESCE(C390.BDVLRDESC, 0)),
                                                      (IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C390.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C390.BDVLRTOT + (C390.BDVALORNOTA - TOT.BDVLRDIF)), C390.BDVLRTOT))), 0.00), '.', ',')|| --VL_OPR
         '|'||REPLACE(COALESCE(C390.BDBCICMS, 0.00), '.', ',')|| --VL_BC_ICMS
         '|'||REPLACE(COALESCE(C390.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
         '|'||REPLACE(COALESCE(IIF(C390.BDMODELO = 2, NULL, (SELECT BDRED_BC FROM SP_CALC_RED_BC((IIF(((GETORDEM(0) = TOT.BDORDEMMAX) AND ((C390.BDVALORNOTA - TOT.BDVLRDIF) > 0)), (C390.BDVLRTOT + (C390.BDVALORNOTA - TOT.BDVLRDIF)), C390.BDVLRTOT)), C390.BDREDBCICMS, C390.BDBCICMS, C390.BDCSTICMS))), 0.00), '.', ',')|| --VL_RED_BC
         '|'||COALESCE(C390.BDCODEXP, '')|| --COD_OBS
         '|') BDLINHA, C390.BDCODOBS
   FROM (
         SELECT MOV.BDCODEMP, MOV.BDCHAVE, ICMS.BDCSTICMS, MOV.BDCODNAT, MOV.BDALIQICMS, SAI.BDMODELO, MOV.BDVLRITEM,
                MOV.BDVLRDESC, MOV.BDVLRFRETE, MOV.BDVLRDESPACESSORIA, MOV.BDVLRIPI, MOV.BDVLRST, MOV.BDBCICMS, MOV.BDCODOBS, OBS.BDCODEXP,
                MOV.BDVLRICMS, MOV.BDBCST, MOV.BDREDBCICMS, SAI.BDVALORNOTA,
                (COALESCE(MOV.BDVLRFRETE, 0) + COALESCE(MOV.BDVLRITEM, 0) +
                 COALESCE(MOV.BDVLRDESPACESSORIA, 0) + COALESCE(MOV.BDVLRIPI, 0) +
                 COALESCE(MOV.BDVLRST, 0) - COALESCE(MOV.BDVLRDESC, 0)) BDVLRTOT
         FROM (
               SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDCODOBS,
                      COALESCE(PRO.BDCODCSTICMS, 0) BDCODCSTICMS,
                      COALESCE(MOV.BDCODNAT, 0) BDCODNAT,
                      CAST(COALESCE(PRO.BDALIQICMS, 0) AS NUMERIC(6, 2)) BDALIQICMS,
                      SUM(COALESCE(PRO.BDVLRITEM, 0)) BDVLRITEM,
                      SUM(COALESCE(PRO.BDVLRDESC, 0)) BDVLRDESC,
                      SUM(COALESCE(PRO.BDVLRFRETE, 0)) BDVLRFRETE,
                      SUM(COALESCE(PRO.BDVLRDESPACESSORIA, 0)) BDVLRDESPACESSORIA,
                      SUM(COALESCE(PRO.BDVLRIPI, 0)) BDVLRIPI,
                      SUM(COALESCE(PRO.BDVLRST, 0)) BDVLRST,
                      SUM(COALESCE(PRO.BDBCST, 0)) BDBCST,
                      SUM(COALESCE(PRO.BDBCICMS, 0)) BDBCICMS,
                      SUM(COALESCE(PRO.BDVLRICMS, 0)) BDVLRICMS,
                      SUM(COALESCE(PRO.BDREDBCICMS, 0)) BDREDBCICMS
               FROM (
                     SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT, I.BDCODOBS
                     FROM VEF_EMP_TMOVSAI M
                     JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                     WHERE M.BDCODEMP = :PRCODEMP
                     AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                     AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                     AND M.BDMODELO IN (2)
                    ) MOV
               JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
               GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, PRO.BDCODCSTICMS, MOV.BDCODNAT, PRO.BDALIQICMS, MOV.BDCODOBS
              ) MOV
         JOIN VEF_EMP_TMOVSAI SAI ON(SAI.BDCODEMP = MOV.BDCODEMP AND SAI.BDCHAVE = MOV.BDCHAVE)
         LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON(ICMS.BDCODCSTICMS = MOV.BDCODCSTICMS)
         LEFT OUTER JOIN VEF_BASE_TOBSERVACAO OBS ON(OBS.BDCODOBS = MOV.BDCODOBS)
        ) C390
  LEFT OUTER JOIN (
                   SELECT C390_TOT.BDCODEMP, C390_TOT.BDCHAVE, SUM(C390_TOT.BDVLRDIF) BDVLRDIF, COUNT(C390_TOT.BDCHAVE) BDORDEMMAX
                   FROM (
                         SELECT MOV.BDCODEMP, MOV.BDCHAVE,
                                ((SUM(COALESCE(PRO.BDVLRITEM, 0)) +
                                  SUM(COALESCE(PRO.BDVLRDESPACESSORIA, 0)) +
                                  SUM(COALESCE(PRO.BDVLRIPI, 0)) +
                                  SUM(COALESCE(PRO.BDVLRST, 0)) +
                                  SUM(COALESCE(PRO.BDVLRFRETE, 0))) -
                                  SUM(COALESCE(PRO.BDVLRDESC, 0))
                                 ) BDVLRDIF     
                         FROM (
                               SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT
                               FROM VEF_EMP_TMOVSAI M
                               JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
                               WHERE M.BDCODEMP = :PRCODEMP
                               AND M.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                               AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
                               AND M.BDMODELO IN (2)
                              ) MOV
                         JOIN VEF_EMP_TMOVPROSAI PRO ON(PRO.BDCODEMP = MOV.BDCODEMP AND PRO.BDCHAVE = MOV.BDCHAVE AND PRO.BDORDEM = MOV.BDORDEM)
                         GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, PRO.BDCODCSTICMS, MOV.BDCODNAT, PRO.BDALIQICMS
                        ) C390_TOT
                   GROUP BY C390_TOT.BDCODEMP, C390_TOT.BDCHAVE
                  ) TOT ON(TOT.BDCODEMP = C390.BDCODEMP AND TOT.BDCHAVE = C390.BDCHAVE);

END
^

CREATE OR ALTER procedure SP_EXPORTA_NF_GAUCHA (
    PRCODEMP integer,
    PRREFERENCIA integer,
    PRDTINI date,
    PRDTFIM date,
    PRRETIFICADORA integer,
    PRARQUIVO varchar(260))
as
declare variable WLINHA blob sub_type 1 segment size 200 character set UTF8;
declare variable WHASH varchar(256);
declare variable WLINHAAUX varchar(300);
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prREFERENCIA);

  -- Registro Tipo 00 – Identificação do arquivo e emitente das notas fiscais
  INSERT INTO TEXPORTACAO_NF_GAUCHA (bdID, bdCODEMP, bdORDEMREG, bdORDEM, bdLINHA)
  SELECT :prARQUIVO, e.bdCODEMP, 0, '000000',                                   -- Nº Campo               Conteúdo                                                                 Tamanho Posição Formato
         '00'||                                                                 -- 1  Tipo do registro    00                                                                        2       1      N
         '2.0.0'||                                                              -- 2  Versão do leiaute   Versão do leiaute do arquivo. Informar “2.0.0”                            5       3      X
         'MOD2'||                                                               -- 3  Tipo de documento   Tipo de documento contido no arquivo conforme observação contida em “b”   4       8      X
         :prREFERENCIA||                                                        -- 4  Período dos dados   Ano e mês referente a emissão das notas fiscais contidas no arquivo       6      12      N
         LPAD((SELECT RESULT FROM SP_TIRATODOSSINAIS(e.bdIEEMP)),10,'0')        -- 5  Inscrição Estadual  Inscrição Estadual do emitente das notas fiscais contidas no arquivo     10      18      N
  FROM VW_EMPRESAS_REF_ATUAL e
  WHERE e.bdCODEMP = :prCODEMP;

  -- Registro Tipo 10 – Notas Fiscais Modelo 2
  INSERT INTO TEXPORTACAO_NF_GAUCHA (bdID, bdCODEMP, bdORDEMREG, bdORDEM, bdLINHA)
  SELECT :prARQUIVO, s.bdCODEMP, 10, s.bdCHAVE,                                 -- Nº Campo                    Conteúdo                                                              Tamanho Posição Formato
         '10'||                                                                 -- 1  Tipo do registro         “10”                                                                   2       1      N
         LPAD(s.bdNUMDOCINI, 6, '0')||                                          -- 2  Número da nota fiscal    Número do documento original a ser substituído ou cancelado            6       3      N
         RPAD(SUBSTRING(s.bdSERIE FROM 1 FOR 3), 3, ' ')||                      -- 3  Série da nota fiscal     Série do documento original a ser substituído ou cancelado             3       9      X
         RPAD(SUBSTRING(s.bdSUBSERIE FROM 1 FOR 2), 2, ' ')||                   -- 4  Subsérie da nota fiscal  Subsérie do documento original a ser substituído ou cancelado          2      12      X
         LPAD(EXTRACT(YEAR FROM s.bdDATAEMISSAO),4,'0')||
           LPAD(EXTRACT(MONTH FROM s.bdDATAEMISSAO),2,'0')||
           LPAD(EXTRACT(DAY FROM s.bdDATAEMISSAO),2,'0')||                      -- 5  Data de emissão          Data de emissão do documento original a ser substituído ou cancelado   8      14      D
         LPAD(EXTRACT(YEAR FROM s.bdDATASAIDA),4,'0')||
           LPAD(EXTRACT(MONTH FROM s.bdDATASAIDA),2,'0')||
           LPAD(EXTRACT(DAY FROM s.bdDATASAIDA),2,'0')||                        -- 6  Data de Saída            Data da saída da mercadoria do estabelecimento                         8      22      D
         LPAD((SELECT bdNUMERO FROM SP_RETORNA_ALFANUMERICO(t.bdCGCTER)),11,'0')||   -- 7  CPF                      CPF do destinatário da nota fiscal                                    11      30      N
         LPAD((SELECT bdNUMERO FROM SP_RETORNA_NUMEROS(s.bdVALORNOTA)),12,'0')||-- 8  Valor total              Valor total da nota fiscal                                            12      41      N
         CASE                                                                   -- 9  Finalidade               Finalidade do registro 0 – inclusão de nota fiscal                     1      53      N
           WHEN s.bdCODSITNF IN (2,3,4,5) THEN '2'                              --                                                    1 – substituição de nota fiscal
         ELSE '0'                                                               --                                                    2 – Cancelamento de nota fiscal
         END
  FROM VEF_EMP_TMOVSAI s
  JOIN (
         SELECT ter.*, (SELECT bdNUMERO FROM SP_RETORNA_ALFANUMERICO(ter.bdCGCTER)) as bdCPF
         FROM VW_TTERCEIRO_SIMPLES ter
        ) t ON (t.bdCODTER = s.bdCODTER)
  WHERE s.bdCODEMP = :prCODEMP
    AND s.bdREFLAN = :prREFERENCIA
    AND s.bdMODELO = 2 -- Apenas modelo 2
    AND CHAR_LENGTH(t.bdCPF) = 11 -- Apenas CPFs
    --AND s.bdCODSITNF NOT IN (2,3,4,5) -- Notas canceladas
  ORDER BY s.bdCHAVE;

  -- Exporta arquivo...
  OPENARQ(:prARQUIVO,:prCODEMP);

  FOR
    SELECT e.bdLINHA
    FROM TEXPORTACAO_NF_GAUCHA E
    WHERE e.bdID = :prARQUIVO
    ORDER BY e.bdORDEMREG, e.bdORDEM
    INTO :wLINHA
  DO
    BEGIN
      WRITELNOA(:WLINHA,:prCODEMP);
    END

  CLOSEARQ(:prARQUIVO,:prCODEMP);

  -- Obtém o Hash do arquivo
  wHash = GETHASHSHA(:prARQUIVO, 4/*SHA-512*/, 3/*ASCII*/);

  -- Registro Tipo 90 – Encerramento do Arquivo                                 -- Nº Campo                        Conteúdo                                               Tamanho Posição Formato Obrig
  SELECT '90'||                                                                 -- 1  Tipo do registro             90                                                       2      1      N       S
         LPAD(COUNT(e.bdCODEMP), 7, '0')||                                      -- 2  Quantidade de notas fiscais  Quantidade total de notas fiscais contidas no arquivo    7      3      N       S
         LPAD(:wHash, 256, ' ')                                                 -- 3  HASH                         Hash aplicado sobre todo o conteúdo do arquivo.        256     10      X       S
  FROM TEXPORTACAO_NF_GAUCHA e
  WHERE e.bdCODEMP = :prCODEMP
    AND e.bdLINHA NOT LIKE '00%' /* Desconsidera o registro "00" */
  GROUP BY e.bdCODEMP
  INTO wLinhaAux;

  -- Grava a linha 90 no arquivo
  OPENARQ(:prARQUIVO,:prCODEMP);
    WRITELNOA(:WLinhaAux,:prCODEMP);
  CLOSEARQ(:prARQUIVO,:prCODEMP);

  DELETE FROM TEXPORTACAO_NF_GAUCHA;
END
^

CREATE OR ALTER trigger VSUC_EMP_TPROCESSO_AUDITOR_bi0 for VAUD_EMP_TPROCESSOS
active before insert position 0
AS
  DECLARE VARIABLE vCHAVE INTEGER;
BEGIN
  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
  BEGIN
    SELECT COALESCE(MAX(BDCHAVE), 0) + 1 BDCHAVE
    FROM VAUD_EMP_TPROCESSOS
    WHERE
    BDCODEMP = NEW.BDCODEMP
    INTO :vCHAVE;

    NEW.BDCHAVE = vCHAVE;
  END
END
^


CREATE OR ALTER PROCEDURE SP_VRHF_MONTASALMES (PREMP    VARCHAR(20000),
                                               PRCOL    VARCHAR(32700),
                                               PRREFINI INTEGER       ,
                                               PRREFFIM INTEGER        )
RETURNS ( BDCODEMP     INTEGER,
          BDCODCOL     INTEGER,
          BDCODEMPORIG INTEGER,
          BDCODCOLORIG INTEGER,
          BDREF        INTEGER,
          BDSALBASECOL NUMERIC(18,6))
AS
DECLARE VARIABLE WSQL      VARCHAR(32700);
DECLARE VARIABLE WSQLAUX   VARCHAR(5000) ;
DECLARE VARIABLE WSQLTRANS VARCHAR(5000) ;
DECLARE VARIABLE WDATA     VARCHAR(10)   ;
DECLARE VARIABLE WDIA      INTEGER       ;
BEGIN
  /*WESLEY KOWALSKI | DATA: 05/10/2018 | SOLICITAÇÃO: 93441 | REESTRUTURANDO A SP PARA PEGAR TAMBÉM OS SALÁRIOS QUE VEM DE TRANSFERÊNCIA*/
  WSQL = '';

  IF (COALESCE(PREMP, '') <> '') THEN
     BEGIN
       WSQL = WSQL||PREMP;

       IF (COALESCE(PRCOL, '') <> '') THEN
          WSQL = WSQL||' AND '||PRCOL;
     END

  IF (WSQL <> '') THEN
      BEGIN
          WSQL = ' SELECT                                                            '||
                 ' X.BDCODEMP,                                                       '||
                 ' X.BDCODCOL,                                                       '||
                 ' Y.BDCODEMPORIG,                                                   '||
                 ' Y.BDCODCOLORIG                                                    '||
                 ' FROM VRH_EMP_TCOLCON X                                            '||
                 ' LEFT JOIN VRH_EMP_TTRANSCOL Y ON (Y.BDCODEMPDEST = X.BDCODEMP AND '||
                 '                                  Y.BDCODCOLDEST = X.BDCODCOL    ) '||
                 ' WHERE                                                             '||
                 WSQL;
      END
 ELSE
      BEGIN
          WSQL = ' SELECT                                                            '||
                 ' X.BDCODEMP,                                                       '||
                 ' X.BDCODCOL,                                                       '||
                 ' Y.BDCODEMPORIG,                                                   '||
                 ' Y.BDCODCOLORIG                                                    '||
                 ' FROM VRH_EMP_TCOLCON X                                            '||
                 ' LEFT JOIN VRH_EMP_TTRANSCOL Y ON (Y.BDCODEMPDEST = X.BDCODEMP AND '||
                 '                                  Y.BDCODCOLDEST = X.BDCODCOL    ) ';
      END

  WHILE (PRREFINI <= PRREFFIM) DO
    BEGIN
      FOR EXECUTE STATEMENT WSQL INTO :BDCODEMP, :BDCODCOL, :BDCODEMPORIG, :BDCODCOLORIG DO
        BEGIN
          BDREF = PRREFINI;
          SELECT ULTDIA FROM ULTIMO_DIA_MES(CAST(SUBSTRING(:PRREFINI FROM 5 FOR 2) AS SMALLINT), CAST(SUBSTRING(:PRREFINI FROM 1 FOR 4) AS INTEGER)) INTO :WDIA;
          WDATA = SUBSTRING(PRREFINI FROM 1 FOR 4)||'-'||SUBSTRING(PRREFINI FROM 5 FOR 2)||'-'||LPAD(WDIA, 2, '0');
          WSQLAUX = ' SELECT FIRST 1                                                            '||
                    ' X.BDSALBASECOL                                                            '||
                    ' FROM VRH_EMP_TCOLCON_CALCDIA X                                            '||
                    ' LEFT JOIN VRH_EMP_TTRANSCOL Y ON (Y.BDCODEMPDEST = X.BDCODEMP AND         '||
                    '                                   Y.BDCODCOLDEST = X.BDCODCOL)            '||
                    ' WHERE                                                                     ';

         IF (((BDCODEMPORIG IS NOT NULL) OR (BDCODEMPORIG > 0)) AND
             ((BDCODCOLORIG IS NOT NULL) OR (BDCODCOLORIG > 0))) THEN
             BEGIN
                 /*VERIFICA SE VEIO DE TRANSFERÊNCIA, ENTÃO APLICA O FILTRO EM CIMA DO COLABORADOR PARA PEGAR A BASE DE SALÁRIO DAS EMPRESAS ANTIGAS*/
                 WSQLAUX = WSQLAUX ||
                           ' ((X.BDCODEMP = '||BDCODEMP||') OR (X.BDCODEMP  = '||BDCODEMPORIG||')) AND '||
                           ' ((X.BDCODCOL = '||BDCODCOL||') OR (X.BDCODCOL  = '||BDCODCOLORIG||')) AND '||
                           ' (BDDATACOL <= '''||WDATA||''')                                            '||
                           ' ORDER BY                                                                  '||
                           ' BDDATACOL DESC                                                            ';
             END
         ELSE
             BEGIN
                 /*SE FOR COLABORADOR SEM TRANSFERÊNCIA APLICA FILTRO SOMENTE NA EMPRESA ATUAL SEM VÍNCULO COM A EMPRESA ANTERIOR*/
                 WSQLAUX = WSQLAUX ||
                           ' (X.BDCODEMP = '||BDCODEMP||') AND '||
                           ' (X.BDCODCOL = '||BDCODCOL||') AND '||
                           ' (BDDATACOL <= '''||WDATA||''')    '||
                           ' ORDER BY                          '||
                           ' BDDATACOL DESC                    ';
             END

          EXECUTE STATEMENT WSQLAUX INTO :BDSALBASECOL;
          SUSPEND;
        END

      IF (SUBSTRING(PRREFINI FROM 5 FOR 2) = '12') THEN
          PRREFINI = CAST((CAST((CAST((SUBSTRING(PRREFINI FROM 1 FOR 4)) AS INTEGER) + 1) AS VARCHAR(4))||'01') AS INTEGER);
      ELSE
          PRREFINI = CAST((SUBSTRING(PRREFINI FROM 1 FOR 4)||LPAD(CAST((SUBSTRING(PRREFINI FROM 5 FOR 2)) AS INTEGER) + 1, 2, '0')) AS INTEGER);
    END
END^


CREATE OR ALTER procedure SP_VRH_GERAREL_TRANSFERENCIA
returns (
    BDCODEMPORIG integer,
    BDCODCOLORIG integer,
    BDCODEMPDEST integer,
    BDCODCOLDEST integer,
    BDCODPTRAN integer,
    BDDATATRF date,
    BDCNPJEMPD DM_CNPJ_CPF,
    BDNOMEMPD DM_BDNOMEMP,
    BDAPEEMPD DM_BDAPEMP,
    BDENDEMPD DM_BDENDERECO,
    BDNUMEMPD DM_NUMEND,
    BDBAIEMPD DM_BDBAIRRO,
    BDCEPEMPD DM_CEP,
    BDDDDEMPD integer,
    BDFONEEMPD DM_BDTELEFONE,
    BDFAXEMPD DM_BDTELEFONE,
    BDEMAILEMPD DM_BDEMAIL,
    BDCOMPLEMPD DM_BDCOMPENDERECO,
    BDLOGREMPD DM_LOGRADOURO,
    BDNOMCIDD varchar(40),
    BDSIGLAUFEMPD varchar(2),
    BDCNPJEMPO DM_CNPJ_CPF,
    BDNOMEMPO DM_BDNOMEMP,
    BDAPEEMPO DM_BDAPEMP,
    BDENDEMPO DM_BDENDERECO,
    BDNUMEMPO DM_NUMEND,
    BDBAIEMPO DM_BDBAIRRO,
    BDCEPEMPO DM_CEP,
    BDDDDEMPO integer,
    BDFONEEMPO DM_BDTELEFONE,
    BDFAXEMPO DM_BDTELEFONE,
    BDEMAILEMPO DM_BDEMAIL,
    BDCOMPLEMPO DM_BDCOMPENDERECO,
    BDLOGREMPO DM_LOGRADOURO,
    BDNOMCIDO varchar(40),
    BDSIGLAUFEMPO varchar(2),
    BDNOMCOLD DM_BDNOMCOL,
    BDLOGRCOLD DM_LOGRADOURO,
    BDENDCOLD DM_BDENDERECO,
    BDNUMCOLD DM_NUMEND,
    BDCOMPLCOLD DM_BDCOMPENDERECO,
    BDBAICOLD DM_BDBAIRRO,
    BDCEPCOLD DM_CEP,
    BDDDDCOLD integer,
    BDFONECOLD DM_BDTELEFONE,
    BDEMAILCOLD DM_BDEMAIL,
    BDDATANASCCOLD date,
    BDDATAADMCOLD date,
    BDSIGLAUFD varchar(2),
    BDCTPSCOLD DM_BDCTPS,
    BDSERIECTPSCOLD DM_SERIECTPS,
    BDDSERIECTPSCOLD varchar(2),
    BDRGCOLD varchar(13),
    BDORGEMIRGCOLD DM_ORGAOEMISSOR,
    BDDATAEMIRGCOLD date,
    BDCPFCOLD varchar(14),
    BDNOMCIDCOD varchar(40),
    BDSIGLAUFCOLD varchar(2),
    BDNOMCOLO DM_BDNOMCOL,
    BDLOGRCOLO DM_LOGRADOURO,
    BDENDCOLO DM_BDENDERECO,
    BDNUMCOLO DM_NUMEND,
    BDCOMPLCOLO DM_BDCOMPENDERECO,
    BDBAICOLO DM_BDBAIRRO,
    BDCEPCOLO DM_CEP,
    BDDDDCOLO integer,
    BDFONECOLO DM_BDTELEFONE,
    BDEMAILCOLO DM_BDEMAIL,
    BDDATANASCCOLO date,
    BDDATAADMCOLO date,
    BDSIGLAUFO varchar(2),
    BDCTPSCOLO DM_BDCTPS,
    BDSERIECTPSCOLO DM_SERIECTPS,
    BDDSERIECTPSCOLO varchar(2),
    BDRGCOLO varchar(13),
    BDORGEMIRGCOLO DM_ORGAOEMISSOR,
    BDDATAEMIRGCOLO date,
    BDCPFCOLO varchar(14),
    BDNOMCIDCOLO varchar(40))
as
declare variable WSQL varchar(10000);
begin
  for select TRANS.BDCODEMPORIG, TRANS.BDCODCOLORIG, TRANS.BDCODEMPDEST, TRANS.BDCODPTRAN, TRANS.BDDATATRF, TRANS.BDCODCOLDEST, EMPD.BDCNPJEMP, EMPO.BDCNPJEMP
      from VRH_EMP_TTRANSCOL TRANS
      left outer join TEMPRESAS EMPD on (TRANS.BDCODEMPDEST = EMPD.BDCODEMP)
      left outer join TEMPRESAS EMPO on (TRANS.BDCODEMPORIG = EMPO.BDCODEMP)
      where EMPD.BDCODEMP is not null and EMPO.BDCODEMP is not null
  into :BDCODEMPORIG, :BDCODCOLORIG, :BDCODEMPDEST, :BDCODPTRAN, :BDDATATRF, :BDCODCOLDEST, :BDCNPJEMPD, :BDCNPJEMPO do
    begin
      if (Coalesce(BDCODEMPDEST,0)<>0) then
         begin
      wsql = 'select first 1 EMPRD.BDNOMEMP,EMPRD.BDAPEEMP,EMPRD.BDENDEMP,EMPRD.BDNUMEMP,EMPRD.BDBAIEMP,EMPRD.BDCEPEMP,EMPRD.BDDDDEMP,EMPRD.BDFONEEMP,EMPRD.BDFAXEMP,EMPRD.BDEMAILEMP,EMPRD.BDCOMPLEMP,EMPRD.BDLOGREMP,CID.BDNOMCID,UF.BDSIGLAUF '||
             'from TEMPRESAS_REF EMPRD '||
             'left outer join TCIDADE CID on (CID.BDCODCID = EMPRD.BDCODCID) '||
             'left outer join TUF UF on (UF.BDCODUF = CID.BDCODUF) '||
             'where BDCODEMP = '||BDCODEMPDEST||' order by EMPRD.BDREFEMP DESC ';
      execute statement wsql into :BDNOMEMPD,:BDAPEEMPD,:BDENDEMPD,:BDNUMEMPD,:BDBAIEMPD,:BDCEPEMPD,:BDDDDEMPD,:BDFONEEMPD,:BDFAXEMPD,:BDEMAILEMPD,:BDCOMPLEMPD,:BDLOGREMPD,:BDNOMCIDD,:BDSIGLAUFEMPD;

           if (Coalesce(BDCODCOLDEST,0)<>0) then
              begin
      wsql = 'select BDDATAADMCOL, BDDATANASCCOL, BDCPFCOL from VRH_EMP_TCOLCON where BDCODEMP = '||BDCODEMPDEST||' and BDCODCOL = '||BDCODCOLDEST;
      execute statement wsql into :BDDATAADMCOLD,:BDDATANASCCOLD,:BDCPFCOLD;
      wsql = 'select first 1 X.BDNOMCOL,X.BDLOGRCOL,X.BDENDCOL,X.BDNUMCOL,X.BDCOMPLCOL,X.BDBAICOL,X.BDCEPCOL,X.BDDDDCOL,X.BDFONECOL,X.BDEMAILCOL,CID.BDNOMCID, UF.BDSIGLAUF '||
             'from VRH_EMP_TCOLCON_CAD X '||
             'left outer join VRH_EMP_TCOL_VINCDIA v on v.BDCODEMP = x.BDCODEMP and v.BDCODCOL  = x.BDCODCOL ' ||
             '            and v.BDDATACOL = (SELECT FIRST 1 z.BDDATACOL FROM VRH_EMP_TCOL_VINCDIA z where z.BDCODEMP = x.BDCODEMP and z.BDCODCOL  = x.BDCODCOL  ' ||
             '                              and z.BDDATACOL >= ''' || :BDDATATRF || ''' order by Z.BDDATACOL ) ' ||
             'left outer join TCIDADE CID on (CID.BDCODCID = X.BDCODCID) '||
             'left outer join TUF UF on (UF.BDCODUF = CID.BDCODUF) '||
             'where X.BDCODEMP = '||BDCODEMPDEST||' and X.BDCODCOL = '||BDCODCOLDEST;
      execute statement wsql into :BDNOMCOLD,:BDLOGRCOLD,:BDENDCOLD,:BDNUMCOLD,:BDCOMPLCOLD,:BDBAICOLD,:BDCEPCOLD,:BDDDDCOLD,:BDFONECOLD,:BDEMAILCOLD,:BDNOMCIDCOD,:BDSIGLAUFCOLD;
      wsql = 'select first 1 X.BDCTPSCOL,X.BDSERIECTPSCOL,X.BDDSERIECTPSCOL,X.BDRGCOL,X.BDORGEMIRGCOL,X.BDDATAEMIRGCOL,UF.BDSIGLAUF '||
             'from VRH_EMP_TCOLCON_DOCREF X '||
             'left outer join TUF UF on (UF.BDCODUF = X.BDCODUF) '||
             'where X.BDCODEMP = '||BDCODEMPDEST||' and X.BDCODCOL = '||BDCODCOLDEST;
      execute statement wsql into :BDCTPSCOLD,:BDSERIECTPSCOLD,:BDDSERIECTPSCOLD,:BDRGCOLD,:BDORGEMIRGCOLD,:BDDATAEMIRGCOLD,:BDSIGLAUFD;
              end
         end

      wsql = 'select first 1 EMPRO.BDNOMEMP,EMPRO.BDAPEEMP,EMPRO.BDENDEMP,EMPRO.BDNUMEMP,EMPRO.BDBAIEMP,EMPRO.BDCEPEMP,EMPRO.BDDDDEMP,EMPRO.BDFONEEMP,EMPRO.BDFAXEMP,EMPRO.BDEMAILEMP,EMPRO.BDCOMPLEMP,EMPRO.BDLOGREMP,CID.BDNOMCID,UF.BDSIGLAUF '||
             'from TEMPRESAS_REF EMPRO '||
             'left outer join TCIDADE CID on (CID.BDCODCID = EMPRO.BDCODCID) '||
             'left outer join TUF UF on (UF.BDCODUF = CID.BDCODUF) '||
             'where BDCODEMP = '||BDCODEMPORIG||' order by EMPRO.BDREFEMP DESC ';
      execute statement wsql into :BDNOMEMPO,:BDAPEEMPO,:BDENDEMPO,:BDNUMEMPO,:BDBAIEMPO,:BDCEPEMPO,:BDDDDEMPO,:BDFONEEMPO,:BDFAXEMPO,:BDEMAILEMPO,:BDCOMPLEMPO,:BDLOGREMPO,:BDNOMCIDO,:BDSIGLAUFEMPO;


      wsql = 'select BDDATAADMCOL, BDDATANASCCOL, BDCPFCOL from VRH_EMP_TCOLCON where BDCODEMP = '||BDCODEMPORIG||' and BDCODCOL = '||BDCODCOLORIG;
      execute statement wsql into :BDDATAADMCOLO,:BDDATANASCCOLO,:BDCPFCOLO;
      wsql = 'select first 1 X.BDNOMCOL,X.BDLOGRCOL,X.BDENDCOL,X.BDNUMCOL,X.BDCOMPLCOL,X.BDBAICOL,X.BDCEPCOL,X.BDDDDCOL,X.BDFONECOL,X.BDEMAILCOL,CID.BDNOMCID '||
             'from VRH_EMP_TCOLCON_CAD X '||
             'left outer join TCIDADE CID on (CID.BDCODCID = X.BDCODCID) '||
             'where X.BDCODEMP = '||BDCODEMPORIG||' and X.BDCODCOL = '||BDCODCOLORIG;
      execute statement wsql into :BDNOMCOLO,:BDLOGRCOLO,:BDENDCOLO,:BDNUMCOLO,:BDCOMPLCOLO,:BDBAICOLO,:BDCEPCOLO,:BDDDDCOLO,:BDFONECOLO,:BDEMAILCOLO,:BDNOMCIDCOLO;
      wsql = 'select first 1 X.BDCTPSCOL,X.BDSERIECTPSCOL,X.BDDSERIECTPSCOL,X.BDRGCOL,X.BDORGEMIRGCOL,X.BDDATAEMIRGCOL,UF.BDSIGLAUF '||
             'from VRH_EMP_TCOLCON_DOCREF X '||
             'left outer join TUF UF on (UF.BDCODUF = X.BDCODUF) '||
             'where X.BDCODEMP = '||BDCODEMPORIG||' and X.BDCODCOL = '||BDCODCOLORIG;
      execute statement wsql into :BDCTPSCOLO,:BDSERIECTPSCOLO,:BDDSERIECTPSCOLO,:BDRGCOLO,:BDORGEMIRGCOLO,:BDDATAEMIRGCOLO,:BDSIGLAUFO;


      suspend;
    end
end^

CREATE OR ALTER procedure SP_GET_ULTIMA_TRANSFERENCIA (
    PRCODCOL integer,
    PREMPRESA integer,
    PRREFERENCIA integer)
returns (
    BDCODCOL integer,
    BDCODEMP integer)
as
declare variable WSQL varchar(1000);
begin
  WSQL = ' select first 1 coalesce(TRAN.BDCODEMPDEST,' || :PREMPRESA || ') BDCODEMP, coalesce(TRAN.BDCODCOLDEST, ' || :PRCODCOL || ') BDCODCOL ';
  WSQL = WSQL || ' from TEMPRESAS EMP ';
  WSQL = WSQL || ' left outer join TEMPRESAS MAT on MAT.BDCODEMP = EMP.BDCODMATRIZ ';
  WSQL = WSQL || ' inner join VRH_EMP_TCOLCON COL3 on COL3.BDCODEMP = EMP.BDCODEMP and COL3.BDCODCOL = ' ||:PRCODCOL;
  WSQL = WSQL || ' inner join VRH_EMP_TCOLCON COL4 on COL4.BDCODEMP in (select BDCODEMP ';
  WSQL = WSQL || ' from TEMPRESAS ';
  WSQL = WSQL || ' where (BDCODEMP = EMP.BDCODEMP or BDCODEMP = MAT.BDCODEMP or BDCODMATRIZ = EMP.BDCODEMP or BDCODMATRIZ = MAT.BDCODEMP)) and COL4.BDCPFCOL = COL3.BDCPFCOL ';
  WSQL = WSQL || ' left outer join VRH_EMP_TTRANSCOL TRAN on ((TRAN.BDCODEMPORIG = COL4.BDCODEMP and TRAN.BDCODCOLORIG = COL4.BDCODCOL) or (TRAN.BDCODEMPDEST = COL4.BDCODEMP and TRAN.BDCODCOLDEST = COL4.BDCODCOL)) and TRAN.BDREFTRF = ' || :PRREFERENCIA;
  WSQL = WSQL || ' where not exists(select 1 ';
  WSQL = WSQL || ' from VRH_EMP_TTRANSCOL ';
  WSQL = WSQL || ' where BDCODEMPORIG = COL4.BDCODEMP and ';
  WSQL = WSQL || ' BDCODCOLORIG = COL4.BDCODCOL and ';
  WSQL = WSQL || ' BDCODEMPDEST is not null and ';
  WSQL = WSQL || ' (TRAN.BDREFTRF = ' || :PRREFERENCIA || ')) and ';
  WSQL = WSQL || ' EMP.BDCODEMP = ' || :PREMPRESA;
  WSQL = WSQL || ' order by TRAN.BDDATATRF desc ';

  for execute statement WSQL
          into :BDCODEMP, :BDCODCOL
  do
    suspend;
end^



CREATE OR ALTER PROCEDURE SP_ALTERA_DEPENDENTE_TER (
    PRID_TERMINAL INTEGER,
    PROLDCHAVE INTEGER,
    PRNEWCHAVE INTEGER)
AS
DECLARE VARIABLE WSESSAOATU INTEGER;
DECLARE VARIABLE WSQL       VARCHAR(500);
DECLARE VARIABLE WTABLE     VARCHAR(50);
DECLARE VARIABLE wField     VARCHAR(50);
BEGIN

  FOR SELECT UPPER(TRIM(T.RDB$RELATION_NAME)) BDTABLE, UPPER(TRIM(RDB$FIELD_NAME)) BDFIELD
      FROM RDB$RELATION_FIELDS T
      WHERE RDB$RELATION_NAME LIKE 'TMP_%_TEMP%'
      AND RDB$FIELD_NAME LIKE 'BDALTCODTER%'
      INTO :wTable, :wField
  DO
    BEGIN
      wSessaoAtu = NULL;

      SELECT S.BDSESSAO
      FROM TMP_TSESSAO_IMP S
      WHERE S.BDID_TERMINAL = :PRID_TERMINAL
      AND S.BDTABLE = :wTable
      INTO :wSessaoAtu;

      IF (:wSessaoAtu IS NOT NULL) THEN
        BEGIN
          wSQL =          ' UPDATE ' || :wTable || ' T SET T.' || :wField || ' = ' || :PRNEWCHAVE;
          wSQL = :wSQL || ' , T.' || REPLACE(:wField, 'ALT', '') || ' = ' || :PRNEWCHAVE;
          wSQL = :wSQL || ' WHERE T.BDSESSAO = '||:wSessaoAtu;
          wSQL = :wSQL || ' AND T.'||:wField||' = '||:PROLDCHAVE;
          EXECUTE STATEMENT :wSQL;
        END
    END
END^

CREATE OR ALTER PROCEDURE SP_GET_COMPLEMENTO (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRCHAVE INTEGER,
    PRCOMPLEMENTO VARCHAR(1000),
    PRCODNAT INTEGER,
    PRTIPOLAN CHAR(4),
    PROBSERVACAO VARCHAR(100),
    PRORDEM integer = 0)
RETURNS (
    BDRESULT VARCHAR(1000))
AS
DECLARE VARIABLE WVAR VARCHAR(200);
DECLARE VARIABLE WNUMDOC INTEGER;
DECLARE VARIABLE WNUMDOCSER VARCHAR(15);
DECLARE VARIABLE WNOMETER VARCHAR(100);
DECLARE VARIABLE WREFLAN INTEGER;
DECLARE VARIABLE WVALUE VARCHAR(200);
DECLARE VARIABLE WVLRNF NUMERIC(15,6);
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WNRDOCATE INTEGER;
DECLARE VARIABLE WESPECIE VARCHAR(5);
DECLARE VARIABLE WSERIE VARCHAR(6);
DECLARE VARIABLE WMODELO VARCHAR(2);
DECLARE VARIABLE WEMITENTE VARCHAR(9);
DECLARE VARIABLE WSITUACAO INTEGER;
DECLARE VARIABLE WDATAEMISSAO DATE;
DECLARE VARIABLE WDATASAIDA DATE;
DECLARE VARIABLE WCONDPGTO VARCHAR(6);
DECLARE VARIABLE WCNPJ VARCHAR(18);
DECLARE VARIABLE WNOMCIDPART VARCHAR(40);
DECLARE VARIABLE WPOS INTEGER;
DECLARE VARIABLE WPOSULTDEL INTEGER;
DECLARE VARIABLE WCOUNT INTEGER;
declare variable wNrDocAteSer VARCHAR(15);
DECLARE variable WDESCPROD varchar(1000);
BEGIN
  PRCOMPLEMENTO = COALESCE(:PRCOMPLEMENTO, '');
  IF ((:PRCOMPLEMENTO = '') OR (POSITION('*', :PRCOMPLEMENTO) = 0)) THEN
    BEGIN
      BDRESULT = :PRCOMPLEMENTO;
      SUSPEND;
      EXIT;
    END

  PRCOMPLEMENTO = :PRCOMPLEMENTO || ' ';

  /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    Não transformar os select's abaixo em select dinâmico!
    - Concatenando as strings e mudando o nome das tabelas: 16s
    - Sem concatenar, fazendo o select compilado..........: 6s
    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/

  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      SELECT ST.bdnumdocini, ST.bdnometer, ST.BDREFLAN,
             ST.BDVALORNOTA, ST.BDEDITCHAVE, ST.BDNUMDOCFIM,
             ST.BDESPECIE, ST.BDSERIE, M.BDMODELOSTR, IIF(ST.BDMODELO = 0, 'Próprio', 'Terceiros'),
             ST.BDCODSITNF, ST.BDDATAEMISSAO, ST.BDDATASAIDA, CASE WHEN ST.BDCONDPGTO = 0 THEN 'Vista'
                                                                   WHEN ST.BDCONDPGTO = 1 THEN 'Prazo'
                                                                   WHEN ST.BDCONDPGTO = 2 THEN 'Outras'
                                                              END,
             ST.BDCNPJ, C.BDNOMCID, SUBSTRING((select list(P.BDDESCPROD, ', ') FROM
                                                          (select P.BDDESCPROD
                                                           from TMP_VEF_EMP_TMOVPROSAI_TEMP P
                                                           WHERE P.BDSESSAO = :PRSESSAO AND P.BDCODEMP = :PRCODEMP AND P.BDCHAVE = :PRCHAVE AND P.BDORDEM = :PRORDEM
                                                           order by P.BDORDEMPRO) P
                                             ) from 1 for 200) as PRODUTOS
      FROM TMP_VEF_EMP_TMOVSAI_TEMP ST
      LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN M ON(M.BDMODELO = ST.BDMODELO)
      LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ST.BDCODCID)
      WHERE ST.BDSESSAO = :PRSESSAO
      AND ST.BDCODEMP = :PRCODEMP
      AND ST.BDCHAVE = :PRCHAVE
      INTO :wNumDoc, :wNomeTer, :wRefLan, :wVlrNf, :wChave, :wNrDocAte,
           :wEspecie, :wSerie, :wModelo, :wEmitente, :wSituacao, :wDataEmissao,
           :wDataSaida, :wCondPgto, :wCnpj, :wNomCidPart, :wDescProd;
    END
  ELSE
  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      SELECT ST.bdnumdocini, ST.bdnometer, ST.BDREFLAN,
             ST.BDVALORNOTA, ST.BDEDITCHAVE, ST.BDNUMDOCFIM,
             ST.BDESPECIE, ST.BDSERIE, M.BDMODELOSTR, IIF(ST.BDMODELO = 0, 'Próprio', 'Terceiros'),
             ST.BDCODSITNF, ST.BDDATAEMISSAO, ST.BDDATAENTRADAENT, CASE WHEN ST.BDCONDPGTO = 0 THEN 'Vista'
                                                                   WHEN ST.BDCONDPGTO = 1 THEN 'Prazo'
                                                                   WHEN ST.BDCONDPGTO = 2 THEN 'Outras'
                                                              END,
             ST.BDCNPJ, SUBSTRING((select list(P.BDDESCPROD, ', ') FROM
                                                          (select P.BDDESCPROD
                                                           from TMP_VEF_EMP_TMOVPROENT_TEMP P
                                                           WHERE P.BDSESSAO = :PRSESSAO AND P.BDCODEMP = :PRCODEMP AND P.BDCHAVE = :PRCHAVE AND P.BDORDEM = :PRORDEM
                                                           order by P.BDORDEMPRO) P
                                             ) from 1 for 200) as PRODUTOS
      FROM TMP_VEF_EMP_TMOVENT_TEMP ST
      LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN M ON(M.BDMODELO = ST.BDMODELO)
      WHERE ST.BDSESSAO = :PRSESSAO
      AND ST.BDCODEMP = :PRCODEMP
      AND ST.BDCHAVE = :PRCHAVE
      INTO :wNumDoc, :wNomeTer, :wRefLan, :wVlrNf, :wChave, :wNrDocAte,
           :wEspecie, :wSerie, :wModelo, :wEmitente, :wSituacao, :wDataEmissao,
           :wDataSaida, :wCondPgto, :wCnpj, :wDescProd;
    END
  ELSE
  IF (POSITION('SER', :PRTIPOLAN) > 0) THEN
    BEGIN
      SELECT ST.bdnumdocini, ST.BDNOMETER, ST.BDREFLAN, ST.BDVALORNOTA,
             ST.BDEDITCHAVE, ST.BDNUMDOCFIM,
             ST.BDESPECIE, ST.BDSERIE, ST.BDCODSITNF, ST.BDDATAEMISSAO,
             ST.BDDT_EXE_SERV, CASE WHEN ST.BDCONDPGTO = 0 THEN 'Vista'
                                    WHEN ST.BDCONDPGTO = 1 THEN 'Prazo'
                                    WHEN ST.BDCONDPGTO = 2 THEN 'Outras'
                               END,
             ST.BDCNPJ
      FROM TMP_VEF_EMP_TMOVSER_TEMP ST
      WHERE ST.BDSESSAO = :PRSESSAO
      AND ST.BDCODEMP = :PRCODEMP
      AND ST.BDCHAVE = :PRCHAVE
      INTO :wNumDocSer, :wNomeTer, :wRefLan, :wVlrNf, :wChave, :wNrDocAteSer,
           :wEspecie, :wSerie, :wSituacao, :wDataEmissao,
           :wDataSaida, :wCondPgto, :wCnpj;
    END

  wCOUNT = 0;
  /*Monta o complemento histórico da contabilização*/
  WHILE ((POSITION('*', :PRCOMPLEMENTO) > 0) AND
         (wCOUNT < 30)) DO -- Alt.: #95379 - Ocorria que o cliente tinha um participante cadastrado com "**" no meio do nome, e ficava travado. Feito assim só para evitar futuros travamentos...
    BEGIN
      wCOUNT = wCOUNT+1;
      wPosUltDel = 1000;
      wPos = POSITION(' ', SUBSTRING(:PRCOMPLEMENTO FROM (POSITION('*', :PRCOMPLEMENTO)) FOR CHAR_LENGTH(:PRCOMPLEMENTO))); -- Não tem o -1 porque é um espaço, o Trim já remove ele.
      wPosUltDel = POSITION(',', SUBSTRING(:PRCOMPLEMENTO FROM (POSITION('*', :PRCOMPLEMENTO)) FOR CHAR_LENGTH(:PRCOMPLEMENTO)))-1; -- -1 para não pegar a , junto

      IF ((:wPosUltDel > 0) AND (wPosUltDel < :wPos)) THEN
        wPos = :wPosUltDel;

      wPosUltDel = 1000;
      wPosUltDel = POSITION('.', SUBSTRING(:PRCOMPLEMENTO FROM (POSITION('*', :PRCOMPLEMENTO)) FOR CHAR_LENGTH(:PRCOMPLEMENTO)))-1; -- -1 para não pegar o . junto

      IF ((:wPosUltDel > 0) AND (wPosUltDel < :wPos)) THEN
        wPos = :wPosUltDel;

      wVar = TRIM(SUBSTRING(:PRCOMPLEMENTO FROM (POSITION('*', :PRCOMPLEMENTO)) FOR :wPos));
      wVar =  UPPER(REPLACE(REPLACE(:wVar, '(', ''), ')', ''));

      IF (:wVar = '*NRDOC') THEN
        wValue = COALESCE(IIF(POSITION('SER', :PRTIPOLAN) > 0, :wNumDocSer, :wNumDoc), 0);
      ELSE
      IF (:wVar = '*NOMEPART') THEN
        wValue = COALESCE(:wNomeTer, '');
      ELSE
      IF (:wVar = '*REF') THEN
        wValue = COALESCE(SUBSTRING(:wRefLan FROM 5 FOR 2)||'/'||SUBSTRING(:wRefLan FROM 1 FOR 4), '');
      ELSE
      IF (:wVar = '*VLRNF') THEN
        wValue = :wVlrNf;
      ELSE
      IF (:wVar = '*CHAVENF') THEN
        wValue = :wChave;
      ELSE
      IF (:wVar = '*NRDOCATE') THEN
        wValue = COALESCE(IIF(POSITION('SER', :PRTIPOLAN) > 0, :wNrDocAteSer, :wNrDocAte), 0);
      ELSE
      IF (:wVar = '*ESPECIE') THEN
        wValue = :wEspecie;
      ELSE
      IF (:wVar = '*SERIE') THEN
        wValue = :wSerie;
      ELSE
      IF (:wVar = '*MODELO') THEN
        wValue = :wModelo;
      ELSE
      IF (:wVar = '*EMITENTE') THEN
        wValue = :wEmitente;
      ELSE
      IF (:wVar = '*SITUACAO') THEN
        wValue = :wSituacao;
      ELSE
      IF (:wVar = '*DATAEMISSAO') THEN
        wValue = :wDataEmissao;
      ELSE
      IF (:wVar = '*DATASAIDA') THEN
        wValue = :wDataSaida;
      ELSE
      IF (:wVar = '*CFOP') THEN
        wValue = SUBSTRING(:PRCODNAT FROM 1 FOR 1)||'.'||SUBSTRING(:PRCODNAT FROM 2 FOR 3)||'-'||SUBSTRING(:PRCODNAT FROM 5 FOR 3);
      ELSE
      IF (:wVar = '*CONDICAO') THEN
        wValue = :wCondPgto;
      ELSE
      IF (:wVar = '*MES') THEN
        wValue = COALESCE(SUBSTRING(:wRefLan FROM 5 FOR 2), '');
      ELSE
      IF (:wVar = '*ANO') THEN
        wValue = COALESCE(SUBSTRING(:wRefLan FROM 1 FOR 4), '');
      ELSE
      IF (:wVar = '*CNPJPART') THEN
        wValue = :wCnpj;
      ELSE
      IF (:wVar = '*NOMCIDPART') THEN
        wValue = :wNomCidPart;
      ELSE
      IF ((:wVar = '*DESCPROD') and (:wDescProd is not null)) THEN
        wValue = SUBSTRING(:wDescProd from 1 for 200);
      ELSE IF (:wVar <> '') THEN
        wValue = SUBSTRING(:wVar FROM 2 FOR (STRLEN(:wVar) - 1));

      PRCOMPLEMENTO = REPLACE(:PRCOMPLEMENTO, :wVar, :wValue);
      wVar   = NULL;
      wValue = NULL;
    END

  BDRESULT = :PRCOMPLEMENTO;
  if (PROBSERVACAO <> '') then
    BDRESULT = :BDRESULT || IIF(SUBSTRING(:BDRESULT FROM character_length(:BDRESULT) FOR 1) = ' ',:PROBSERVACAO,' '||:PROBSERVACAO);

  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_CANCELAR_LAN (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRSESSAOLANCANC INTEGER,
    PRSESSAOLANINUT INTEGER)
AS
DECLARE VARIABLE WSERIE VARCHAR(6);
DECLARE VARIABLE WMODELO INTEGER;
DECLARE VARIABLE WNUMDOCINI INTEGER;
DECLARE VARIABLE WNUMDOCFIM INTEGER;
DECLARE VARIABLE WCHAVENFE VARCHAR(100);
DECLARE VARIABLE WNOMEARQUIVO VARCHAR(255);
DECLARE VARIABLE WDATACANC DATE;
DECLARE VARIABLE WZERARNFCANC DM_BOOLEAN;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WAUX INTEGER;
BEGIN
  SELECT UPPER(P.BDVALOR)
  FROM TPARGER P
  WHERE UPPER(P.BDCAMPO) = 'BDZERANFCANCELADA'
  INTO :wZerarNFCanc;

  FOR SELECT CI.BDSERIE, CI.BDMODELO, CI.BDNUMDOCINI,
             CI.BDNUMDOCFIM, CI.BDCHAVENFE, CI.BDDATACANC,
             MOV.BDCHAVE, CI.BDNOMEARQUIVO
      FROM TMP_VEF_EMP_TCANC_INUT_TEMP CI
      LEFT OUTER JOIN TMP_VEF_EMP_TMOVSAI_TEMP MOV ON(MOV.BDSESSAO = :PRSESSAO AND MOV.BDCODEMP = :PRCODEMP AND MOV.BDCHAVENFE = CI.BDCHAVENFE)
      WHERE CI.BDSESSAO IN (:PRSESSAOLANCANC, :PRSESSAOLANINUT)
      INTO :wSerie, :wModelo, :wNumDocIni,
           :wNumDocFim, :wChaveNFe, :wDataCanc,
           :wChave, :wNomeArquivo
  DO
    BEGIN
      IF (:wChaveNFe = 'INUT') THEN /*Inutilizados*/
        BEGIN
          /*Altera a situação do lançamento que está sendo importado para "5 - NF-e ou CT-e - Numeração inutilizada"*/
          UPDATE TMP_VEF_EMP_TMOVSAI_TEMP MOV SET MOV.BDCODSITNF = 5
          WHERE MOV.BDSESSAO  = :PRSESSAO
          AND MOV.BDCODEMP    = :PRCODEMP
          AND MOV.BDSERIE     = :wSerie
          AND MOV.BDMODELO    = :wModelo
          AND MOV.BDNUMDOCINI = :wNumDocIni
          AND MOV.BDNUMDOCFIM = :wNumDocFim;

          /* Alt.: #129608 #29319 - Caso a nota inutilizada exista no banco, apaga da tabela temporária e fica apenas #
          com a do banco pois na importação do CT-e as notas inutilizadas quando não existem no banco, são importadas.*/
          DELETE FROM TMP_VEF_EMP_TMOVSAI_TEMP tmp
          WHERE tmp.bdCODEMP    = :prCODEMP
            AND tmp.bdSERIE     = :wSerie
            AND tmp.bdMODELO    = :wModelo
            AND tmp.bdNUMDOCINI = :wNumDocIni
            AND tmp.bdNUMDOCFIM = :wNumDocFim
            AND EXISTS(SELECT *
                       FROM VEF_EMP_TMOVSAI b
                       WHERE b.bdCODEMP  = tmp.bdCODEMP
                         AND b.bdSERIE = tmp.bdSERIE
                         AND b.bdMODELO = tmp.bdMODELO
                         AND b.bdNUMDOCINI = tmp.bdNUMDOCINI
                         AND tmp.bdNUMDOCFIM = tmp.bdNUMDOCFIM);

          /*Verifica se existe o lançamento inutilizado no banco, se existir, insere na TEMP pra aparecer na grid,
            se não existir lança inconsistencia para o usuário*/
          INSERT INTO TMP_VEF_EMP_TMOVSAI_TEMP(BDSESSAO, BDCODEMP, BDCHAVE, BDCODTER, BDNOMETER, BDSIGLAUFTER,
                                               BDNUMDOCINI, BDNUMDOCFIM, BDMODELO, BDESPECIE, BDSERIE, BDDATAEMISSAO,
                                               BDCHAVENFE, BDVALORNOTA)
          SELECT :PRSESSAOLANINUT BDSESSAO, M.BDCODEMP, M.BDCHAVE, M.BDCODTER, TER.BDNOME, UF.BDSIGLAUF,
                 M.BDNUMDOCINI, M.BDNUMDOCFIM, M.BDMODELO, M.BDESPECIE, M.BDSERIE, M.BDDATAEMISSAO,
                 M.BDCHAVENFE, M.BDVALORNOTA
          FROM VEF_EMP_TMOVSAI M
          LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = M.BDCODTER)
          LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = TER.BDCODCID)
          LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
          WHERE M.BDCODEMP  = :PRCODEMP
          AND M.BDSERIE     = :wSerie
          AND M.BDMODELO    = :wModelo
          AND M.BDNUMDOCINI = :wNumDocIni
          AND M.BDNUMDOCFIM = :wNumDocFim;

          /** 147 - Nota de inutilização não encontrada. **/
          /*1º - Procura no banco*/
          SELECT FIRST 1 M.BDCHAVE
          FROM VEF_EMP_TMOVSAI M
          WHERE M.BDCODEMP = :PRCODEMP
          AND M.BDSERIE = :wSerie
          AND M.BDMODELO = :wModelo
          AND M.BDNUMDOCINI = :wNumDocIni
          AND M.BDNUMDOCFIM = :wNumDocFim
          INTO :wAux;

          IF (ROW_COUNT = 0) THEN /*Não encontrou no banco, vai procurar na importação*/
            BEGIN
              /*2º - Procura na importação*/
              SELECT FIRST 1 MOV.BDCHAVE
              FROM TMP_VEF_EMP_TMOVSAI_TEMP MOV
              WHERE MOV.BDSESSAO = :PRSESSAO
              AND MOV.BDCODEMP = :PRCODEMP
              AND MOV.BDSERIE = :wSerie
              AND MOV.BDMODELO = :wModelo
              AND MOV.BDNUMDOCINI = :wNumDocIni
              AND MOV.BDNUMDOCFIM = :wNumDocFim
              INTO :wAux;

              IF (ROW_COUNT = 0) THEN /*Não encontrou na importação também, lança inconsistência*/
                INSERT INTO VEF_INCON_TMOVSAI(BDSESSAO, BDCODEMP, BDCODINCONSISTENCIA, BDTIPOINCON, BDNOMEARQUIVO)
                VALUES(:PRSESSAO, :PRCODEMP, 147, 1, :wNomeArquivo);
            END
        END
      ELSE
        BEGIN /*Lançamentos cancelados*/
          /****************************************** Cancelamento ********************************************/

          /*Altera a situação do lançamento que está sendo importado para "2 - Documento cancelado"*/
          UPDATE TMP_VEF_EMP_TMOVSAI_TEMP MOV SET MOV.BDCODSITNF = 2, MOV.BDDATACANC = :wDataCanc
          WHERE MOV.BDSESSAO  = :PRSESSAO
          AND MOV.BDCODEMP    = :PRCODEMP
          AND MOV.BDCHAVENFE  = :wChaveNFe;
    
          INSERT INTO TMP_VEF_EMP_TMOVSAI_TEMP(BDSESSAO, BDCODEMP, BDCHAVE, BDCODTER, BDNOMETER, BDSIGLAUFTER,
                                               BDNUMDOCINI, BDNUMDOCFIM, BDMODELO, BDESPECIE, BDSERIE, BDDATAEMISSAO,
                                               BDCHAVENFE, BDVALORNOTA, BDDESCONTONOTA, BDDATACANC, BDCHAVENFECANC, BDCODSITNF)
          SELECT :PRSESSAOLANCANC BDSESSAO, M.BDCODEMP, M.BDCHAVE, M.BDCODTER, TER.BDNOME, UF.BDSIGLAUF,
                 M.BDNUMDOCINI, M.BDNUMDOCFIM, M.BDMODELO, M.BDESPECIE, M.BDSERIE, M.BDDATAEMISSAO, M.BDCHAVENFE,
                 M.BDVALORNOTA, M.BDDESCONTONOTA, :wDataCanc BDDATACANC, M.BDCHAVENFE, 2 AS BDCODSITNF -- Alt.: #129648 #130471 #133443 #133377 - Leva a situacao como cancelada...
          FROM VEF_EMP_TMOVSAI M
          LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = M.BDCODTER)
          LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = TER.BDCODCID)
          LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
          WHERE M.BDCODEMP  = :PRCODEMP
          AND M.BDCHAVENFE = :wChaveNFe;

          /*148 - Nota de cancelamento com chave NFe não localizada.*/
          /*1º - Procura no banco*/
          SELECT FIRST 1 M.BDCHAVE
          FROM VEF_EMP_TMOVSAI M
          WHERE M.BDCODEMP = :PRCODEMP
          AND M.BDCHAVENFE = :wChaveNFe
          INTO :wAux;

          IF (ROW_COUNT = 0) THEN /*Não encontrou no banco, vai procurar na importação*/
            BEGIN
              /*2º - Procura na importação*/
              SELECT FIRST 1 MOV.BDCHAVE
              FROM TMP_VEF_EMP_TMOVSAI_TEMP MOV
              WHERE MOV.BDSESSAO = :PRSESSAO
              AND MOV.BDCODEMP   = :PRCODEMP
              AND MOV.BDCHAVENFE = :wChaveNFe
              INTO :wAux;

              IF (ROW_COUNT = 0) THEN /*Não encontrou na importação também, lança inconsistência*/
                INSERT INTO VEF_INCON_TMOVSAI(BDSESSAO, BDCODEMP, BDCODINCONSISTENCIA, BDTIPOINCON, BDNOMEARQUIVO, BDCHAVENFECANC)
                VALUES(:PRSESSAO, :PRCODEMP, 148, 1, :wNomeArquivo, :wChaveNFe);
            END
    
          /*Apaga as parcelas dos lançamentos cancelados*/
          DELETE FROM TMP_VEF_EMP_TMOVSAIPAR_TEMP PAR
          WHERE PAR.BDSESSAO = :PRSESSAO
          AND EXISTS (
                      SELECT S.BDCHAVE
                      FROM TMP_VEF_EMP_TMOVSAI_TEMP S
                      WHERE S.BDSESSAO = PAR.BDSESSAO
                      AND S.BDCODEMP = PAR.BDCODEMP
                      AND S.BDCHAVE = PAR.BDCHAVE
                      AND S.BDCHAVENFE = :wChaveNFe
                     );
    
          /************************************** Zerar valores de NFe cancelada **************************************/
          /************************************** Zerar valores de NFe cancelada **************************************/
          IF (:wZerarNFCanc = 'TRUE') THEN
            BEGIN
              /*Zera valores da capa*/
              UPDATE TMP_VEF_EMP_TMOVSAI_TEMP MOV
              SET MOV.BDVALORNOTA = 0,
                  MOV.BDDESCONTONOTA = 0,
                  --Jaques Dix - 09/04/2021 - #142623 - campos que não estavam sendo zerados
                  MOV.BDTOTVALC190 = 0,
                  MOV.BDVLRTOTPIS = 0,
                  MOV.BDVLRTOTCOFINS = 0,
                  MOV.BDVLRTOTPISST = 0,
                  MOV.BDVLRTOTCOFINSST = 0,
                  MOV.BDVLRTOTOUT = 0
              WHERE MOV.BDSESSAO = :PRSESSAO
              AND MOV.BDCODEMP   = :PRCODEMP
              AND MOV.BDCHAVE    = :wChave;
    
              /*Zera valores dos itens*/
              UPDATE TMP_VEF_EMP_TMOVSAIITENS_TEMP I
              SET -- Alt.: #137131 #132536 - Quando for zerar uma nova váriavel, procurar por essa solucita  o para zerar em todo os pontos...
                  -- Item / CFOP
                  I.BDVLRCONTAB   = 0, -- Valor contábil
                  I.BDDESCONTO    = 0,  -- Desconto
                  I.BDREDBCICMS   = 0, -- Redução base cálculo
                  -- ICMS
                  I.BDBASEICMS    = 0, -- Base
                  I.BDALIQICMS    = 0, -- Alíquota
                  I.BDVLRICMS     = 0, -- Valor
                  I.BDISENTASICMS = 0, -- Isentas
                  I.BDOUTRASICMS  = 0, -- Outras
                  I.BDICMSFRETESAI = 0, -- ICMS frete
                  I.BDOUTROSIMP   = 0, -- Outros impostos
                  -- IPI
                  I.BDBASEIPI     = 0, --  Base
                  I.BDVLRIPI      = 0, --  Valor
                  I.BDISENTASIPI  = 0, --  Isentas
                  I.BDOUTRASIPI   = 0, --  Outras
                  -- Substituição tributária - ICMS
                  I.BDBASEST      = 0, --  Base
                  I.BDALIQST      = 0, --  Alíquota
                  I.BDVLRST       = 0, --  Valor
                  --I.BDVALNTRIBST = 0, --  não retido
                  --I.BDICMSRETENT = 0, --  Retido
                  I.BDFCPRETIDO   = 0, --  FCP ST
                  -- Pis e Cofins
                  I.BDVLRPIS      = 0,
                  I.BDVLRCOFINS   = 0,
                  --Jaques Dix - 09/04/2021 - #142623 - campos que não estavam sendo zerados
                  I.BDIMPEXCLUIDAS = 0,
                  I.BDACRECFINSAI  = 0,
                  I.BDIMPEXCLIPI   = 0,
                  I.BDIMPEXCLST    = 0,
                  I.BDVLRFCP       = 0
              WHERE I.BDSESSAO = :PRSESSAO
              AND I.BDCODEMP   = :PRCODEMP
              AND I.BDCHAVE    = :wChave;
    
              /*Zera valores dos produtos*/
              UPDATE TMP_VEF_EMP_TMOVPROSAI_TEMP P
              SET -- Alt.: #137131 #132536 - Quando for zerar uma nova váriavel, procurar por essa solucita  o para zerar em todo os pontos...
                  -- Produto
                  P.BDQTDITEM          = 0, -- Quantidade
                  P.BDVLRABATNT        = 0, -- Valor do abatimento
                  P.BDVLRITEM          = 0, -- Valor total do produto
                  P.BDREDBCICMS        = 0, -- Redução base de cálculo
                  P.BDVLRSEGURO        = 0, -- Seguro
                  P.BDVLRDESC          = 0, -- Valor do desconto
                  P.BDVLRFRETE         = 0, -- Frete
                  P.BDVLRDESPACESSORIA = 0, -- Despesas acess rias
                  -- Impostos
                  -- ICMS
                  P.BDBCICMS           = 0, -- Base de cálculo
                  P.BDALIQICMS         = 0, -- Alíquota
                  P.BDVLRICMS          = 0, -- Valor
                  -- IPI
                  P.BDBCIPI            = 0, -- Base de cálculo
                  P.BDALIQIPI          = 0, -- Alíquota
                  P.BDVLRIPI           = 0, -- Valor
                  -- PIS
                  P.BDBCPIS            = 0, -- Base de cálculo
                  P.BDALIQPIS          = 0, -- Alíquota
                  P.BDVLRPIS           = 0, -- Valor
                  -- Cofins
                  P.BDBCCOFINS         = 0, -- Base de cálculo
                  P.BDALIQCOFINS       = 0, -- Alíquota
                  P.BDVLRCOFINS        = 0, -- Valor
                  -- ISSQN
                  P.BDBCISSQN          = 0, -- Base de cálculo
                  P.BDALIQISSQN        = 0, -- Alíquota
                  P.BDVLRISSQN         = 0, -- Valor
                  -- ICMS ST
                  P.BDBCST             = 0, -- Base de cálculo
                  P.BDALIQST           = 0, -- Alíquota
                  P.BDVLRST            = 0, -- Valor
                  -- FCP Retido por ST
                  P.BDBCFCPRETIDO      = 0, -- Base de cálculo
                  P.BDALIQFCPRETIDO    = 0, -- Alíquota
                  P.BDFCPRETIDO        = 0, -- Valor
                  -- ICMS ST Retido
                  P.BDBCICMSSTRET      = 0, -- Base de cálculo
                  P.BDALIQIMCSSTRET    = 0, -- Alíquota
                  P.BDVLRICMSSTRET     = 0, -- Valor
                  -- FCP Retido ant.
                  P.BDBCFCPSTRET       = 0, -- Base de cálculo
                  P.BDALIQFCPSTRET     = 0, -- Alíquota
                  P.BDVLRFCPSTRET      = 0, -- Valor
                  -- ICMS Efetiva
                  P.BDBCICMSEFET       = 0, -- Base de cálculo
                  P.BDALIQICMSEFET     = 0, -- Alíquota
                  P.BDVLRICMSEFET      = 0, -- Valor
                  --Jaques Dix - 09/04/2021 - #142623 - campos que não estavam sendo zerados
                  P.BDVLRFCP           = 0,
                  P.BDALQFCP           = 0,
                  P.BDBCFCP            = 0,
                  P.BDBCSTSUBSTITUIDO  = 0,
                  P.BDALIQSTSUBSTITUIDO= 0,
                  P.BDVLRSTSUBSTITUIDO = 0,
                  -- Credito Presumido
                  P.BDALIQCREDPRESUMIDO= 0, -- Alíquota
                  P.BDVLRCREDPRESUMIDO = 0  -- Base de cálculo
              WHERE P.BDSESSAO = :PRSESSAO
              AND P.BDCODEMP   = :PRCODEMP
              AND P.BDCHAVE    = :wChave;

              --Jaques Dix - 09/04/2021 - #142623 - campos que não estavam sendo zerados
              UPDATE TMP_VEF_EMP_TC100SAI_TEMP  C1
              SET -- Alt.: #137131 #132536 - Quando for zerar uma nova váriavel, procurar por essa solucita  o para zerar em todo os pontos...
                  C1.BDVLRFRETE        = 0,
                  C1.BDVLRSEGURO       = 0,
                  C1.BDVLROUTDESP      = 0,
                  C1.BDVLRTOTPIS       = 0,
                  C1.BDVLRTOTCOFINS    = 0,
                  C1.BDVLRTOTPISST     = 0,
                  C1.BDVLRTOTCOFINSST  = 0,
                  C1.BDVLR_FCP_UF_DEST = 0,
                  C1.BDVLRICMS_UF_DEST = 0,
                  C1.BDVLRICMS_UF_REM  = 0,
                  C1.BDVLRABATNT       = 0
              WHERE C1.BDSESSAO = :PRSESSAO
                AND C1.BDCODEMP = :PRCODEMP
                AND C1.BDCHAVE  = :wChave;

              --Jaques Dix - 09/04/2021 - #142623 - campos que não estavam sendo zerados
              UPDATE TMP_VEF_EMP_TD100SAI_TEMP D1
              SET -- Alt.: #137131 #132536 - Quando for zerar uma nova váriavel, procurar por essa solucita  o para zerar em todo os pontos...
                  D1.BDVLRPIS          = 0,
                  D1.BDVLRCOFINS       = 0,
                  D1.BDVL_BC_PIS       = 0,
                  D1.BDALIQ_PIS        = 0,
                  D1.BDVL_BC_COF       = 0,
                  D1.BDALIQ_COF        = 0,
                  D1.BDVLR_FCP_UF_DEST = 0,
                  D1.BDVLRICMS_UF_DEST = 0, 
                  D1.BDVLRICMS_UF_REM  = 0
              WHERE D1.BDSESSAO = :PRSESSAO
                AND D1.BDCODEMP = :PRCODEMP
                AND D1.BDCHAVE  = :wChave;
            END
    
          /**************************** Apagar lançamentos do SN em notas canceladas ****************************/
          DELETE FROM TMP_VEF_EMP_TMOVSAISN_TEMP SN
          WHERE SN.BDSESSAO = :PRSESSAO
          AND SN.BDCODEMP   = :PRCODEMP
          AND SN.BDCHAVE    = :wChave;
        END
    END

  DELETE FROM TMP_VEF_EMP_TCANC_INUT_TEMP WHERE BDSESSAO = :PRSESSAO;
END
^

CREATE OR ALTER TRIGGER TRG_DEP_CTX FOR TMP_DEPENDENCIA_CONTEXTO
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE wNewOrd INTEGER;
BEGIN
  IF ((NEW.BDORD IS NUll) OR (NEW.BDORD = 0)) THEN
    BEGIN
      SELECT MAX(BDORD) + 1 FROM TMP_DEPENDENCIA_CONTEXTO INTO :wNewOrd;

      NEW.BDORD = COALESCE(:wNewOrd, 1);
    END
END^

create or alter procedure SP_CRIA_PRE_CONTABILIZACAO_REDZ (
    PRSESSAO integer,
    PRCODPLANOONLINE integer,
    PRENQFED integer,
    PRFORMATRIBUTACAO integer = 0)
as
declare variable WTIPOINTCOF integer;
declare variable WTIPOINTPIS integer;
declare variable WTIPOINTICMS integer;
declare variable WBDCODCONFIRLP integer;
declare variable WBDCODCONFDACON integer;
declare variable WBDTIPOCONFDACON integer;
declare variable WEF integer;
declare variable WCODEMP integer;
declare variable WDATA date;
declare variable WCONTABGUIAMUN DM_BOOLEAN;
declare variable WTIPOINTPISLP integer;
declare variable WTIPOINTCOFINSLP integer;
BEGIN
  /*
    BDORD - Campo para ordernar a contabilização
    ******************Legenda*******************
    1 - Valor contábil com desconto
    2 - Valor contábil só com conta débito
    3 - desconto
    4 - Impostos
    5 - Diferença
    6 - Outras CFOPS
  */

  wEF = 3;

  SELECT o.bdtipointcofins, o.bdtipointpis, o.bdtipointicms, o.bdtipointpislp, o.bdtipointcofinslp
  FROM TPLANO_CONF_ONLINE O
  WHERE O.BDCODPLANOONLINE = :PRCODPLANOONLINE
  INTO :wTipoIntCof, :wTipoIntPis, :wTipoIntIcms, :WTIPOINTPISLP, :WTIPOINTCOFINSLP;

  SELECT FIRST 1
       BDCODEMP, BDDATAREDZ
  FROM TMP_VEF_EMP_TREDZ_TEMP
  WHERE BDSESSAO = :PRSESSAO AND BDCODEMP IS NOT NULL INTO :WCODEMP, :WDATA;

  SELECT FIRST 1
    FED.BDCONTABGUIAMUN
  FROM
      TEMPRESAS_REF EMPREF
  LEFT JOIN
       VEF_BASE_TEMPPARFED FED ON (FED.BDCODEMP = EMPREF.BDCODEMP AND FED.BDREFEMP = EMPREF.BDREFEMP)
  LEFT JOIN
       TENQFED ENQ ON (ENQ.BDCODEMP = EMPREF.BDCODEMP AND ENQ.BDREFEMP = EMPREF.BDREFEMP)
  WHERE EMPREF.BDCODEMP = :WCODEMP AND
        EMPREF.BDREFEMP <= (SUBSTRING(:WDATA FROM 1 FOR 4) || SUBSTRING(:WDATA FROM 6 FOR 2))
  ORDER BY
        EMPREF.BDREFEMP DESC
  INTO :WCONTABGUIAMUN;



  select coalesce(TREFSIS.BDCODCONFIRLP,0), coalesce(TREFSIS.BDCODCONFDACON,0), conf.bdtipoconfdacon
  from (
        select t.bdcodemp
        from TMP_VEF_EMP_TREDZ_TEMP t
        WHERE BDSESSAO = :PRSESSAO
        group by t.bdcodemp
        ) tmp
  left outer join vw_VEF_BASE_TEMPPARGER TREFSIS on (TREFSIS.bdcodemp = tmp.bdcodemp)
  left outer join VEF_BASE_TCONFDACON conf on (conf.bdcodconfdacon = TREFSIS.BDCODCONFDACON)
  INTO :WBDCODCONFIRLP,:WBDCODCONFDACON ,:Wbdtipoconfdacon;

/*Sol #151792 Contabiliza??o PIS_COFINS Regime de Caixa
  Necess?rio comentar rotina que for?ava ser pelo darf*/
--  --Se for lucro presumido sempre ser?? contabilizado pelo darf
--  --Elizeu - 13-08-18 - Contabilizando PIS/Cofins nota a nota Lucro Presumido
--  if (((:WBDCODCONFIRLP > 0)) or (((:WBDCODCONFDACON > 0) and (:Wbdtipoconfdacon = 0))))   then
--    begin
--      wTipoIntCof = 2; /*tiValoresDarfCofins*/
--      wTipoIntPis = 2; /*tiValoresDarfPis*/
--    end

  /***********************************************VALOR CONTÁBIL C/ DESCONTO***********************************************/
  /*Quanto tem desconto, o valor contábil da PRIMEIRA CFOP é contabilizado apenas no débito, depois contabiliza somente no crédito*/
  /*As demais CFOP's são contabilizadas com conta credito e débito*/
  INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP (BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCHAVE_VSUC, BDCODPLAPADRAO, BDCODUSU,
                                             BDDEBITO, BDCREDITO, BDCOMPL, BDDATA, BDVALOR, BDTIPOLAN, BDDCTO,
                                             BDTRANSACAO, BDTRANFECHADA, BDFORMULA, BDCODPLANOONLINE, BDCHAVETITULO,
                                             BDCLASSIFBUSCA, BDCLASSIFTITULO, BDCODITEMONLINE, BDCHAVECONTA, BDCODTPHI,
                                             BDORD, BDCODHIST)
  SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE, MOV.BDORDEMVARCFOP, MOV.BDSESSAO, MOV.BDCHAVE_VSUC, MOV.BDCODPLAPADRAO, MOV.BDCODUSU,
         MOV.BDCONTADEBPROV, IIF(MOV.BDCHAVEDESC IS NULL, MOV.BDCONTACREDPROV, NULL) BDCONTACREDPROV, MOV.BDCOMPHIST_VLRCONTAB, MOV.BDDATAREDZ, MOV.BDVLRCONTAB,
         MOV.BDTIPOLAN, MOV.BDNUMCUPINI, MOV.BDTRANSACAO, MOV.BDTRANFECHADA, MOV.BDFORMULA, MOV.BDCODPLANOONLINE,
         MOV.BDCHAVECONF, MOV.BDCLASSIFICACAO, MOV.BDCLASS_TITULO, MOV.BDCODITEMONLINE, MOV.BDCHAVE, MOV.BDCODTPHI,
         2 BDORD, MOV.BDCODHIST
  FROM (
        SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEMVARCFOP, I.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU,
               C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRCONTAB, I.BDDATAREDZ, I.BDVLRCONTAB,
               100 BDTIPOLAN /*100 - Escrita fiscal*/ , I.BDNUMCUPINI, NULL BDTRANSACAO, 'TRUE' BDTRANFECHADA,
               C.BDFORMULA, :PRCODPLANOONLINE BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE,
               I.BDVALDESCICMS, C.BDCHAVE, C.BDCODTPHI, D.BDCHAVE BDCHAVEDESC, C.BDCODHIST
        FROM (
              SELECT VC.BDCODEMP, VC.BDEDITCHAVE, VC.BDSESSAO, VC.BDORDEMVARCFOP,
                     VC.BDCOMPHIST_VLRCONTAB, VC.BDCHAVE, VC.BDCODNAT, MOV.BDVLRCONTAB, VC.BDCONDPGTO,
                     R.BDDATAREDZ, R.BDNUMCUPINI, R.BDVALDESCICMS, EXTRACT(YEAR FROM R.BDDATAREDZ)*100+EXTRACT(MONTH FROM R.BDDATAREDZ) as BDREFERENCIA
              FROM (
                    SELECT V.BDSESSAO, V.BDCODEMP, V.BDCHAVE,
                           V.BDCODNAT, V.BDEDITCHAVE, SUM(COALESCE(V.BDVLRCONTAB,0)) BDVLRCONTAB
                    FROM (SELECT BDSESSAO, BDCODEMP, BDCHAVE, BDCODNAT, BDEDITCHAVE, BDVLRCONTAB
                          FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP
                          WHERE BDSESSAO = :PRSESSAO
                          ORDER BY BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMVARCFOP) V
                    GROUP BY V.BDSESSAO, V.BDCODEMP, V.BDCHAVE, V.BDCODNAT, V.BDEDITCHAVE
                   ) MOV
              JOIN TMP_VEF_EMP_TREDZVARCFOP_TEMP VC ON(VC.BDSESSAO = MOV.BDSESSAO AND VC.BDCODEMP = MOV.BDCODEMP AND VC.BDCHAVE = MOV.BDCHAVE AND VC.BDCODNAT = MOV.BDCODNAT)
              JOIN TMP_VEF_EMP_TREDZ_TEMP R ON (R.BDCODEMP = VC.BDCODEMP AND R.BDCHAVE = VC.BDCHAVE AND R.BDSESSAO = VC.BDSESSAO)
              JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = VC.BDCODNAT AND NAT.BDCONTABILIZA = 'TRUE')
              LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = R.BDCODEMP AND IC.BDCODSIS = :wEF)
              WHERE VC.BDORDEMVARCFOP = 1
              AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= R.BDDATAREDZ)))
              AND (R.BDVALDESCICMS > 0)
             ) I
        JOIN TCONTAS_ONLINE_TEMP C ON (C.BDSESSAO = I.BDSESSAO AND C.BDREFERENCIA = I.BDREFERENCIA AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN I.BDCONDPGTO = 0 THEN 111 /*Valor contábil - A vista*/
                                                                                                                         WHEN I.BDCONDPGTO = 1 THEN 117 /*Valor contábil - Prazo*/
                                                                                                                         WHEN I.BDCONDPGTO = 2 THEN 170 /*Valor contábil - Outras*/
                                                                                                                    END))
        LEFT OUTER JOIN TCONTAS_ONLINE_TEMP D ON (D.BDSESSAO = I.BDSESSAO AND D.BDREFERENCIA = I.BDREFERENCIA AND (D.BDCODITEMONLINE IN (207)) AND D.BDCONTADEBPROV IS NOT NULL) /*Somente se tiver conta desconto*/
        LEFT OUTER JOIN TCONTAS_ONLINE_TEMP CD ON(CD.BDSESSAO = I.BDSESSAO AND CD.BDREFERENCIA = I.BDREFERENCIA AND CD.BDCODITEMONLINE IN (207) AND CD.BDCONTADEBPROV IS NOT NULL)
        AND CD.BDCHAVE IS NOT NULL
        AND I.BDVLRCONTAB > 0 -- Alt.: #142225 - Apenas se tiver valor...
        AND NOT EXISTS(SELECT INCO.BDCODINCONSISTENCIA
                       FROM VEF_INCON_TREDZ INCO
                       WHERE INCO.BDCODEMP = I.BDCODEMP
                       AND INCO.BDCHAVE = I.BDCHAVE
                       AND INCO.BDSESSAO = I.BDSESSAO)
       ) MOV;

  /***********************************************VALOR CONTÁBIL S/ DESCONTO (2ª CFOP em diante)***************************/
  /*Aqui contabiliza as outras CFOP's com conta débito e crédito*/
  INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP (BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCHAVE_VSUC, BDCODPLAPADRAO, BDCODUSU,
                                             BDDEBITO, BDCREDITO, BDCOMPL, BDDATA, BDVALOR, BDTIPOLAN, BDDCTO,
                                             BDTRANSACAO, BDTRANFECHADA, BDFORMULA, BDCODPLANOONLINE, BDCHAVETITULO,
                                             BDCLASSIFBUSCA, BDCLASSIFTITULO, BDCODITEMONLINE, BDCHAVECONTA, BDCODTPHI,
                                             BDORD, BDCODHIST)
  SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE, MOV.BDORDEMVARCFOP, MOV.BDSESSAO, MOV.BDCHAVE_VSUC, MOV.BDCODPLAPADRAO, MOV.BDCODUSU,
         MOV.BDCONTADEBPROV, MOV.BDCONTACREDPROV, MOV.BDCOMPHIST_VLRCONTAB, MOV.BDDATAREDZ, MOV.BDVLRCONTAB,
         MOV.BDTIPOLAN, MOV.BDNUMCUPINI, MOV.BDTRANSACAO, MOV.BDTRANFECHADA, MOV.BDFORMULA, MOV.BDCODPLANOONLINE,
         MOV.BDCHAVECONF, MOV.BDCLASSIFICACAO, MOV.BDCLASS_TITULO, MOV.BDCODITEMONLINE, MOV.BDCHAVE, MOV.BDCODTPHI,
         5 BDORD, MOV.BDCODHIST
  FROM (
        SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEMVARCFOP, I.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU,
               C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRCONTAB, I.BDDATAREDZ, I.BDVLRCONTAB,
               100 BDTIPOLAN /*100 - Escrita fiscal*/, I.BDNUMCUPINI, NULL BDTRANSACAO, 'TRUE' BDTRANFECHADA,
               C.BDFORMULA,  :PRCODPLANOONLINE BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE,
               C.BDCHAVE, C.BDCODTPHI, C.BDCODHIST
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE, MOV.BDSESSAO, 1 BDORDEMVARCFOP,
                     MOV.BDCOMPHIST_VLRCONTAB, MOV.BDCHAVE, MOV.BDCODNAT, MOV.BDVLRCONTAB, MOV.BDCONDPGTO,
                     R.BDDATAREDZ, R.BDNUMCUPINI, EXTRACT(YEAR FROM R.BDDATAREDZ)*100+EXTRACT(MONTH FROM R.BDDATAREDZ) as BDREFERENCIA
              FROM (
                    SELECT V.BDSESSAO, V.BDCODEMP, V.BDCHAVE, V.BDCODNAT, V.BDEDITCHAVE,
                           SUM(COALESCE(V.BDVLRCONTAB,0)) BDVLRCONTAB, V.BDCOMPHIST_VLRCONTAB, V.BDCONDPGTO
                    FROM (
                          SELECT BDSESSAO, BDCODEMP, BDCHAVE, BDCODNAT, BDEDITCHAVE,
                                 BDVLRCONTAB, BDCOMPHIST_VLRCONTAB, BDCONDPGTO
                          FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP
                          WHERE BDSESSAO = :PRSESSAO
                          ORDER BY BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMVARCFOP
                         ) V
                    GROUP BY V.BDSESSAO, V.BDCODEMP, V.BDCHAVE, V.BDCODNAT, V.BDEDITCHAVE, V.BDCOMPHIST_VLRCONTAB, V.BDCONDPGTO
                   ) MOV
              JOIN TMP_VEF_EMP_TREDZ_TEMP R ON (R.BDCODEMP = MOV.BDCODEMP AND R.BDCHAVE = MOV.BDCHAVE AND R.BDSESSAO = MOV.BDSESSAO)
              JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = MOV.BDCODNAT AND NAT.BDCONTABILIZA = 'TRUE')
              LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = R.BDCODEMP AND IC.BDCODSIS = :wEF)
              WHERE MOV.BDCODNAT <> COALESCE((SELECT Z.BDCODNAT FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP Z WHERE Z.BDSESSAO = MOV.BDSESSAO AND Z.BDCODEMP = MOV.BDCODEMP AND Z.BDCHAVE = MOV.BDCHAVE AND Z.BDORDEMVARCFOP = 1),0)
              AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= R.BDDATAREDZ)))
             ) I
        JOIN TCONTAS_ONLINE_TEMP C ON (C.BDSESSAO = I.BDSESSAO AND C.BDREFERENCIA = I.BDREFERENCIA AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN I.BDCONDPGTO = 0 THEN 111 /*Valor contábil - A vista*/
                                                                                                                         WHEN I.BDCONDPGTO = 1 THEN 117 /*Valor contábil - Prazo*/
                                                                                                                         WHEN I.BDCONDPGTO = 2 THEN 170 /*Valor contábil - Outras*/
                                                                                                                    END))
        WHERE I.BDVLRCONTAB > 0 -- Alt.: #142225 - Apenas se tiver valor...
          AND NOT EXISTS(SELECT INCO.BDCODINCONSISTENCIA
                         FROM VEF_INCON_TMOVSAI INCO
                         WHERE INCO.BDCODEMP = I.BDCODEMP
                         AND INCO.BDCHAVE = I.BDCHAVE
                         AND INCO.BDSESSAO = I.BDSESSAO)
       ) MOV;

  IF (:wTipoIntIcms = 0) THEN /*Icms e Icms ST nota a nota*/
    BEGIN
      IF (((:PRENQFED NOT IN(1, 2))) OR (:WCONTABGUIAMUN = 'TRUE')) THEN /*Empresas do simples nacional n??o contabilizam ICMS, PIS, Cofins e IPI. Somente ICMS ST*/
        BEGIN
          /*------------------------------------------------------ICMS----------------------------------------------------------------*/
          INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                                    bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                                    bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord, BDCODHIST)
          SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE, 1 BDORDEMVARCFOP, MOV.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV,
                 C.BDCONTACREDPROV, MOV.BDCOMPHIST_VLRICMS, S.BDDATAREDZ, MOV.BDVLRICMS, 100 BDTIPOLAN, S.BDNUMCUPINI, NULL BDTRANSACAO,
                 'TRUE' BDTRANFECHADA, C.BDFORMULA, :PRCODPLANOONLINE BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE,
                 C.BDCHAVE, C.BDCODTPHI, 4 BDORD, C.BDCODHIST
          FROM (
                SELECT V.BDSESSAO, V.BDCODEMP, V.BDCHAVE, V.BDEDITCHAVE, V.BDCODNAT,
                       V.BDCOMPHIST_VLRICMS, SUM(COALESCE(V.BDVLRICMS, 0)) BDVLRICMS, V.BDCONDPGTO
                FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP V
                WHERE V.BDSESSAO = :PRSESSAO
                GROUP BY V.BDSESSAO, V.BDCODEMP, V.BDCHAVE, V.BDEDITCHAVE, V.BDCODNAT, V.BDCOMPHIST_VLRICMS, V.BDCONDPGTO
               ) MOV
          JOIN TMP_VEF_EMP_TREDZ_TEMP S ON(S.BDCODEMP = MOV.BDCODEMP AND S.BDCHAVE = MOV.BDCHAVE AND S.BDSESSAO = MOV.BDSESSAO)
          JOIN TCONTAS_ONLINE_TEMP C ON (C.BDSESSAO = MOV.BDSESSAO AND C.BDREFERENCIA = (EXTRACT(YEAR FROM S.BDDATAREDZ)*100+EXTRACT(MONTH FROM S.BDDATAREDZ))
                                         AND C.BDCODNAT = MOV.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN MOV.BDCONDPGTO = 0 THEN 112 /*ICMS - A vista*/
                                                                                                     WHEN MOV.BDCONDPGTO = 1 THEN 118 /*ICMS - Prazo*/
                                                                                                     WHEN MOV.BDCONDPGTO = 2 THEN 171 /*ICMS - Outras*/
                                                                                                END))
          JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = MOV.BDCODNAT AND NAT.BDCONTABILIZA = 'TRUE')
          LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = MOV.BDCODEMP AND IC.BDCODSIS = :wEF)
          WHERE MOV.BDVLRICMS > 0
          AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAREDZ)))
          AND NOT EXISTS(
                         SELECT INCO.BDCODINCONSISTENCIA
                         FROM VEF_INCON_TREDZ INCO
                         WHERE INCO.BDCODEMP = MOV.BDCODEMP
                         AND   INCO.BDCHAVE  = MOV.BDCHAVE
                         AND   INCO.BDSESSAO = MOV.BDSESSAO
                        );
          /*--------------------------------------------------------------------------------------------------------------------------*/
        END

      /*------------------------------------------------------ICMS ST-------------------------------------------------------------*/
      INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                                bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                                bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord, BDCODHIST)
      SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE, 1 BDORDEMVARCFOP, MOV.BDSESSAO, NULL BDCHAVE_VSUC,
             C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, MOV.BDCOMPHIST_VLRICMSST, S.BDDATAREDZ, MOV.BDVLRST,
             100 BDTIPOLAN, S.BDNUMCUPINI, NULL BDTRANSACAO, 'TRUE' BDTRANFECHADA, C.BDFORMULA, :PRCODPLANOONLINE BDCODPLANOONLINE,
             C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODTPHI, 4 BDORD, C.BDCODHIST
      FROM (
            SELECT V.BDSESSAO, V.BDCODEMP, V.BDCHAVE, V.BDEDITCHAVE, V.BDCODNAT,
                   V.BDCOMPHIST_VLRICMSST, SUM(COALESCE(V.BDVLRST, 0)) BDVLRST, V.BDCONDPGTO
            FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP V
            WHERE V.BDSESSAO = :PRSESSAO
            GROUP BY V.BDSESSAO, V.BDCODEMP, V.BDCHAVE, V.BDEDITCHAVE, V.BDCODNAT, V.BDCOMPHIST_VLRICMSST, V.BDCONDPGTO
           ) MOV
      JOIN TMP_VEF_EMP_TREDZ_TEMP S ON(S.BDCODEMP = MOV.BDCODEMP AND S.BDCHAVE = MOV.BDCHAVE AND S.BDSESSAO = MOV.BDSESSAO)
      JOIN TCONTAS_ONLINE_TEMP C ON (C.BDSESSAO = MOV.BDSESSAO AND C.BDREFERENCIA = (EXTRACT(YEAR FROM S.BDDATAREDZ)*100+EXTRACT(MONTH FROM S.BDDATAREDZ))
                                     AND C.BDCODNAT = MOV.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN MOV.BDCONDPGTO = 0 THEN 113 /*ICMS ST - A vista*/
                                                                                                 WHEN MOV.BDCONDPGTO = 1 THEN 119 /*ICMS ST - Prazo*/
                                                                                                 WHEN MOV.BDCONDPGTO = 2 THEN 172 /*ICMS ST - Outras*/
                                                                                            END))
      JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = MOV.BDCODNAT AND NAT.BDCONTABILIZA = 'TRUE')
      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = MOV.BDCODEMP AND IC.BDCODSIS = :wEF)
      WHERE MOV.BDVLRST > 0
      AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAREDZ)))
      AND NOT EXISTS(
                     SELECT INCO.BDCODINCONSISTENCIA
                     FROM VEF_INCON_TREDZ INCO
                     WHERE INCO.BDCODEMP = MOV.BDCODEMP
                     AND   INCO.BDCHAVE  = MOV.BDCHAVE
                     AND   INCO.BDSESSAO = MOV.BDSESSAO
                    );
      /*--------------------------------------------------------------------------------------------------------------------------*/
    END

  IF (((:wTipoIntPis = 0) AND (:PRENQFED NOT IN(1, 2))) or (((:prenqfed = 3) and (:prformatributacao = 1)) and (:wtipointpislp = 1))) THEN /*Pis nota a nota*/ /*Empresas do simples nacional n??o contabilizam ICMS, PIS, Cofins e IPI. Somente ICMS ST*/
    BEGIN
      /*--------------------------------------------------------PIS---------------------------------------------------------------*/
      INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                                bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                                bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord, BDCODHIST)
      SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE, 1 BDORDEMVARCFOP, MOV.BDSESSAO, NULL BDCHAVE_VSUC,
             C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, MOV.BDCOMPHIST_VLRPIS,
             R.BDDATAREDZ, MOV.BDVLRPIS, 100 BDTIPOLAN, R.BDNUMCUPINI, NULL BDTRANSACAO,
             'TRUE' BDTRANFECHADA, C.BDFORMULA, :PRCODPLANOONLINE BDCODPLANOONLINE,
             C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODTPHI, 4 BDORD, C.BDCODHIST
      FROM (
            SELECT V.BDSESSAO, V.BDCODEMP, V.BDCHAVE, V.BDEDITCHAVE, V.BDCODNAT,
                   V.BDCOMPHIST_VLRPIS, SUM(COALESCE(V.BDVLRPIS, 0)) BDVLRPIS, V.BDCONDPGTO
            FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP V
            WHERE V.BDSESSAO = :PRSESSAO
            GROUP BY V.BDSESSAO, V.BDCODEMP, V.BDCHAVE, V.BDEDITCHAVE, V.BDCODNAT, V.BDCOMPHIST_VLRPIS, V.BDCONDPGTO
           ) MOV
      JOIN TMP_VEF_EMP_TREDZ_TEMP R ON(R.BDCODEMP = MOV.BDCODEMP AND R.BDCHAVE = MOV.BDCHAVE AND R.BDSESSAO = MOV.BDSESSAO)
      JOIN TCONTAS_ONLINE_TEMP C ON (C.BDSESSAO = MOV.BDSESSAO AND C.BDREFERENCIA = (EXTRACT(YEAR FROM R.BDDATAREDZ)*100+EXTRACT(MONTH FROM R.BDDATAREDZ))
                                     AND C.BDCODNAT = MOV.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN MOV.BDCONDPGTO = 0 THEN 115 /*PIS - A vista*/
                                                                                                 WHEN MOV.BDCONDPGTO = 1 THEN 121 /*PIS - Prazo*/
                                                                                                 WHEN MOV.BDCONDPGTO = 2 THEN 174 /*PIS - Outras*/
                                                                                            END))
      JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = MOV.BDCODNAT AND NAT.BDCONTABILIZA = 'TRUE')
      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = MOV.BDCODEMP AND IC.BDCODSIS = :wEF)
      WHERE MOV.BDVLRPIS > 0
      AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= R.BDDATAREDZ)))
      AND NOT EXISTS(
                     SELECT INCO.BDCODINCONSISTENCIA
                     FROM VEF_INCON_TREDZ INCO
                     WHERE INCO.BDCODEMP = MOV.BDCODEMP
                     AND   INCO.BDCHAVE  = MOV.BDCHAVE
                     AND   INCO.BDSESSAO = MOV.BDSESSAO
                    );
      /*--------------------------------------------------------------------------------------------------------------------------*/
    END

  IF (((:wTipoIntCof = 0) AND (:PRENQFED NOT IN(1, 2))) or (((:prenqfed = 3) and (:prformatributacao = 1)) and (:WTIPOINTCOFINSLP = 1))) THEN /*Cofins nota a nota*/ /*Empresas do simples nacional n??o contabilizam ICMS, PIS, Cofins e IPI. Somente ICMS ST*/
    BEGIN
      /*-------------------------------------------------------Cofins-------------------------------------------------------------*/
      INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,
                                                bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline,
                                                bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdcodtphi, bdord, BDCODHIST)
      SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE, 1 BDORDEMVARCFOP, MOV.BDSESSAO, NULL BDCHAVE_VSUC,
             C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, MOV.BDCOMPHIST_VLRCOFINS, R.BDDATAREDZ, MOV.BDVLRCOFINS, 100 BDTIPOLAN,
             R.BDNUMCUPINI, NULL BDTRANSACAO, 'TRUE' BDTRANFECHADA, C.BDFORMULA, :PRCODPLANOONLINE BDCODPLANOONLINE,
             C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODTPHI, 4 BDORD, C.BDCODHIST
      FROM (
            SELECT V.BDSESSAO, V.BDCODEMP, V.BDCHAVE, V.BDEDITCHAVE, V.BDCODNAT,
                   V.BDCOMPHIST_VLRCOFINS, SUM(COALESCE(V.BDVLRCOFINS, 0)) BDVLRCOFINS, V.BDCONDPGTO
            FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP V
            WHERE V.BDSESSAO = :PRSESSAO
            GROUP BY V.BDSESSAO, V.BDCODEMP, V.BDCHAVE, V.BDEDITCHAVE, V.BDCODNAT, V.BDCOMPHIST_VLRCOFINS, V.BDCONDPGTO
           ) MOV
      JOIN TMP_VEF_EMP_TREDZ_TEMP R ON(R.BDCODEMP = MOV.BDCODEMP AND R.BDCHAVE = MOV.BDCHAVE AND R.BDSESSAO = MOV.BDSESSAO)
      JOIN TCONTAS_ONLINE_TEMP C ON (C.BDSESSAO = MOV.BDSESSAO AND C.BDCODNAT = MOV.BDCODNAT AND C.BDREFERENCIA = (EXTRACT(YEAR FROM R.BDDATAREDZ)*100+EXTRACT(MONTH FROM R.BDDATAREDZ))
                                     AND (C.BDCODITEMONLINE = CASE WHEN MOV.BDCONDPGTO = 0 THEN 116 /*Cofins - A vista*/
                                                                   WHEN MOV.BDCONDPGTO = 1 THEN 122 /*Cofins - Prazo*/
                                                                   WHEN MOV.BDCONDPGTO = 2 THEN 175 /*Cofins - Outras*/
                                                              END))
      JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = MOV.BDCODNAT AND NAT.BDCONTABILIZA = 'TRUE')
      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = MOV.BDCODEMP AND IC.BDCODSIS = :wEF)
      WHERE MOV.BDVLRCOFINS > 0
      AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= R.BDDATAREDZ)))
      AND NOT EXISTS(
                     SELECT INCO.BDCODINCONSISTENCIA
                     FROM VEF_INCON_TREDZ INCO
                     WHERE INCO.BDCODEMP = MOV.BDCODEMP
                     AND   INCO.BDCHAVE  = MOV.BDCHAVE
                     AND   INCO.BDSESSAO = MOV.BDSESSAO
                    );
    END

  /********************************************************DESCONTO********************************************************/
  INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP (BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCHAVE_VSUC, BDCODPLAPADRAO, BDCODUSU,
                                             BDDEBITO, BDCREDITO, BDCOMPL, BDDATA, BDVALOR, BDTIPOLAN, BDDCTO,
                                             BDTRANSACAO, BDTRANFECHADA, BDFORMULA, BDCODPLANOONLINE, BDCHAVETITULO,
                                             BDCLASSIFBUSCA, BDCLASSIFTITULO, BDCODITEMONLINE, BDCHAVECONTA, BDCODTPHI, BDORD, BDCODHIST)
  SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEMVARCFOP, I.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU,
         C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRDESCONTO, R.BDDATAREDZ, R.BDVALDESCICMS,
         100 BDTIPOLAN /*100 - Escrita fiscal*/ , R.BDNUMCUPINI, NULL BDTRANSACAO, 'TRUE' BDTRANFECHADA, C.BDFORMULA,
         :PRCODPLANOONLINE BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE,
         C.BDCODTPHI, 3 BDORD, C.BDCODHIST
  FROM (
        SELECT R.BDCODEMP, R.BDCHAVE, R.BDSESSAO,
               R.BDDATAREDZ, R.BDVALDESCICMS, R.BDNUMCUPINI
        FROM TMP_VEF_EMP_TREDZ_TEMP R
        LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = R.BDCODEMP AND IC.BDCODSIS = :wEF)
        WHERE R.BDSESSAO = :PRSESSAO
        AND R.BDVALDESCICMS > 0
        AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= R.BDDATAREDZ)))
      ) R
  JOIN TMP_VEF_EMP_TREDZVARCFOP_TEMP I ON (I.BDCODEMP = R.BDCODEMP AND I.BDCHAVE = R.BDCHAVE AND I.BDSESSAO = R.BDSESSAO AND I.BDORDEMVARCFOP = 1)
  JOIN TCONTAS_ONLINE_TEMP C ON (C.BDSESSAO = I.BDSESSAO AND C.BDREFERENCIA = (EXTRACT(YEAR FROM R.BDDATAREDZ)*100+EXTRACT(MONTH FROM R.BDDATAREDZ)) AND C.BDCODITEMONLINE = 207 AND C.BDCONTADEBPROV IS NOT NULL);

  /***********************************************VALOR CONTÁBIL + DESCONTO************************************************/
  INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP (BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCHAVE_VSUC, BDCODPLAPADRAO, BDCODUSU,
                                             BDDEBITO, BDCREDITO, BDCOMPL, BDDATA, BDVALOR, BDTIPOLAN, BDDCTO,
                                             BDTRANSACAO, BDTRANFECHADA, BDFORMULA, BDCODPLANOONLINE, BDCHAVETITULO,
                                             BDCLASSIFBUSCA, BDCLASSIFTITULO, BDCODITEMONLINE, BDCHAVECONTA, BDCODTPHI,
                                             BDORD, BDCODHIST)
  SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE, 1 BDORDEMVARCFOP, MOV.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU,
         NULL BDCONTADEBPROV, C.BDCONTACREDPROV, MOV.BDCOMPHIST_VLRCONTAB, MOV.BDDATAREDZ,
         (COALESCE(MOV.BDVLRCONTAB, 0) + COALESCE(MOV.BDVALDESCICMS, 0)) BDVLRCONTAB,
         100 BDTIPOLAN /*100 - Escrita fiscal*/ , MOV.BDNUMCUPINI, NULL BDTRANSACAO, 'TRUE' BDTRANFECHADA, C.BDFORMULA,
         :PRCODPLANOONLINE BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE,
         C.BDCODTPHI, 1 BDORD, C.BDCODHIST
  FROM (
        SELECT VC.BDCODEMP, VC.BDEDITCHAVE, VC.BDSESSAO, VC.BDORDEMVARCFOP,
               VC.BDCOMPHIST_VLRCONTAB, VC.BDCHAVE, VC.BDCODNAT, MOV.BDVLRCONTAB, VC.BDCONDPGTO,
               R.BDDATAREDZ, R.BDVALDESCICMS, R.BDNUMCUPINI
        FROM (
              SELECT V.BDSESSAO, V.BDCODEMP, V.BDCHAVE,
                     V.BDCODNAT, V.BDEDITCHAVE, SUM(V.BDVLRCONTAB) BDVLRCONTAB
              FROM (SELECT BDSESSAO, BDCODEMP, BDCHAVE, BDCODNAT, BDEDITCHAVE, BDVLRCONTAB
                    FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP
                    WHERE BDSESSAO = :PRSESSAO
                    ORDER BY BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMVARCFOP) V
              GROUP BY V.BDSESSAO, V.BDCODEMP, V.BDCHAVE, V.BDCODNAT, V.BDEDITCHAVE
             ) MOV
        JOIN TMP_VEF_EMP_TREDZVARCFOP_TEMP VC ON(VC.BDSESSAO = MOV.BDSESSAO AND VC.BDCODEMP = MOV.BDCODEMP AND VC.BDCHAVE = MOV.BDCHAVE AND VC.BDCODNAT = MOV.BDCODNAT)
        JOIN TMP_VEF_EMP_TREDZ_TEMP R ON (R.BDSESSAO = VC.BDSESSAO AND R.BDCODEMP = VC.BDCODEMP AND R.BDCHAVE = VC.BDCHAVE)
        LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = R.BDCODEMP AND IC.BDCODSIS = :wEF)
        WHERE VC.BDORDEMVARCFOP = 1
        AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= R.BDDATAREDZ)))
        AND R.BDVALDESCICMS > 0
       ) MOV
  JOIN TCONTAS_ONLINE_TEMP C ON (C.BDSESSAO = MOV.BDSESSAO AND C.BDCODNAT = MOV.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN MOV.BDCONDPGTO = 0 THEN 111 /*Valor contábil - A vista*/
                                                                                                                       WHEN MOV.BDCONDPGTO = 1 THEN 117 /*Valor contábil - Prazo*/
                                                                                                                       WHEN MOV.BDCONDPGTO = 2 THEN 170 /*Valor contábil - Outras*/
                                                                                                                  END)
                                 AND C.BDREFERENCIA = (EXTRACT(YEAR FROM MOV.BDDATAREDZ)*100+EXTRACT(MONTH FROM MOV.BDDATAREDZ)))
  JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = MOV.BDCODNAT AND NAT.BDCONTABILIZA = 'TRUE')
  JOIN TCONTAS_ONLINE_TEMP D ON (D.BDSESSAO = MOV.BDSESSAO AND (D.BDCODITEMONLINE IN (207)) AND D.BDCONTADEBPROV IS NOT NULL) /*Somente se tiver conta desconto*/
  LEFT OUTER JOIN TCONTAS_ONLINE_TEMP CD ON(CD.BDSESSAO = MOV.BDSESSAO AND CD.BDCODITEMONLINE = 88 AND CD.BDCONTADEBPROV IS NOT NULL)
  AND CD.BDCHAVE IS NOT NULL;

  /************************************* VALOR CONTÁBIL S/ DESCONTO (1ª Ordem de CFOP) ************************************/
  INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP (BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCHAVE_VSUC, BDCODPLAPADRAO, BDCODUSU,
                                             BDDEBITO, BDCREDITO, BDCOMPL, BDDATA, BDVALOR, BDTIPOLAN, BDDCTO,
                                             BDTRANSACAO, BDTRANFECHADA, BDFORMULA, BDCODPLANOONLINE, BDCHAVETITULO,
                                             BDCLASSIFBUSCA, BDCLASSIFTITULO, BDCODITEMONLINE, BDCHAVECONTA, BDCODTPHI,
                                             BDORD, BDCODHIST)
  SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE, 1 BDORDEMVARCFOP, MOV.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU,
         C.BDCONTADEBPROV, C.BDCONTACREDPROV, MOV.BDCOMPHIST_VLRCONTAB, MOV.BDDATAREDZ, COALESCE(MOV.BDVLRCONTAB, 0) BDVLRCONTAB,
         100 BDTIPOLAN /*100 - Escrita fiscal*/ , MOV.BDNUMCUPINI, NULL BDTRANSACAO, 'TRUE' BDTRANFECHADA, C.BDFORMULA,
         :PRCODPLANOONLINE BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE,
         C.BDCODTPHI, 1 BDORD, C.BDCODHIST
  FROM (
        SELECT VC.BDCODEMP, VC.BDEDITCHAVE, VC.BDSESSAO, VC.BDORDEMVARCFOP,
               VC.BDCOMPHIST_VLRCONTAB, VC.BDCHAVE, VC.BDCODNAT, MOV.BDVLRCONTAB, VC.BDCONDPGTO,
               R.BDDATAREDZ, R.BDNUMCUPINI
        FROM (
              SELECT V.BDSESSAO, V.BDCODEMP, V.BDCHAVE,
                     V.BDCODNAT, V.BDEDITCHAVE, SUM(COALESCE(V.BDVLRCONTAB,0)) BDVLRCONTAB
              FROM (SELECT BDSESSAO, BDCODEMP, BDCHAVE, BDCODNAT, BDEDITCHAVE, BDVLRCONTAB
                    FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP
                    WHERE BDSESSAO = :PRSESSAO
                    ORDER BY BDSESSAO, BDCODEMP, BDCHAVE, BDORDEMVARCFOP) V
              GROUP BY V.BDSESSAO, V.BDCODEMP, V.BDCHAVE, V.BDCODNAT, V.BDEDITCHAVE
             ) MOV
        JOIN TMP_VEF_EMP_TREDZVARCFOP_TEMP VC ON(VC.BDSESSAO = MOV.BDSESSAO AND VC.BDCODEMP = MOV.BDCODEMP AND VC.BDCHAVE = MOV.BDCHAVE AND VC.BDCODNAT = MOV.BDCODNAT AND VC.BDORDEMVARCFOP = 1)
        JOIN TMP_VEF_EMP_TREDZ_TEMP R ON (R.BDSESSAO = VC.BDSESSAO AND R.BDCODEMP = VC.BDCODEMP AND R.BDCHAVE = VC.BDCHAVE AND COALESCE(R.BDVALDESCICMS, 0) = 0)
        JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = VC.BDCODNAT AND NAT.BDCONTABILIZA = 'TRUE')
        LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = R.BDCODEMP AND IC.BDCODSIS = :wEF)
        WHERE MOV.BDVLRCONTAB > 0
        AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= R.BDDATAREDZ)))
       ) MOV
  JOIN TCONTAS_ONLINE_TEMP C ON (C.BDSESSAO = MOV.BDSESSAO AND C.BDCODNAT = MOV.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN MOV.BDCONDPGTO = 0 THEN 111 /*Valor contábil - A vista*/
                                                                                                                       WHEN MOV.BDCONDPGTO = 1 THEN 117 /*Valor contábil - Prazo*/
                                                                                                                       WHEN MOV.BDCONDPGTO = 2 THEN 170 /*Valor contábil - Outras*/
                                                                                                                  END)
                                 AND C.BDREFERENCIA = (EXTRACT(YEAR FROM MOV.BDDATAREDZ)*100+EXTRACT(MONTH FROM MOV.BDDATAREDZ)));

  /*AJUSTA A ORDEM DOS REGISTROS*/
  UPDATE TMP_TLANC_CONTABILIZACAO_TEMP C
  SET C.BDORDEM = (COALESCE(
                            (SELECT FIRST 1 V.BDORDEMVARCFOP
                             FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP V
                             WHERE V.BDSESSAO = C.BDSESSAO
                             AND V.BDCODEMP = C.BDCODEMP
                             AND V.BDEDITCHAVE = C.BDCHAVE
                             AND V.BDCODNAT = (SELECT first 1 CO.BDCODNAT FROM TCONTAS_ONLINE_TEMP CO
                                               WHERE CO.BDSESSAO = V.BDSESSAO
                                               AND CO.BDCHAVE = C.BDCHAVECONTA)
                                               ORDER BY V.BDSESSAO, V.BDCODEMP,
                                               V.BDCHAVE, V.BDORDEMVARCFOP), C.BDORDEM)
                  )
  WHERE C.BDSESSAO = :PRSESSAO;
END^

CREATE OR ALTER PROCEDURE SP_CRIA_PRE_CONTABILIZACAODIFAL (
    PRSESSAO INTEGER,
    PRCODPLANOONLINE INTEGER,
    PRTIPOLAN VARCHAR(5),
    PREF INTEGER)
AS
DECLARE VARIABLE WTABLE VARCHAR(50);
DECLARE VARIABLE WTABLEITEM VARCHAR(50);
DECLARE VARIABLE WTABLEC100 VARCHAR(50);
DECLARE VARIABLE WTABLED100 VARCHAR(50);
DECLARE VARIABLE WSQL VARCHAR(5000);
DECLARE VARIABLE WFIELDDATA VARCHAR(32);
DECLARE VARIABLE WANDFIELDREF VARCHAR(200);
BEGIN
  /*
    Patrick T. Sá - 20/07/2017.
    Esta procedure foi criada porque a SP_CRIA_PRE_CONTABILIZACAO excedeu o tamanho maximo de uma stored procedure (64k).

    Aqui é criada a pré contabilização dos valores da Difal
  */

  PRTIPOLAN = UPPER(:PRTIPOLAN);
                               
  wfielddata  = 'BDDATAEMISSAO';
  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTable      = 'TMP_VEF_EMP_TMOVSAI_TEMP';
      wTableItem  = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
      wTableC100  = 'TMP_VEF_EMP_TC100SAI_TEMP';
      wTableD100  = 'TMP_VEF_EMP_TD100SAI_TEMP';
    END
  ELSE
  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTable      = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItem  = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      wTableC100  = 'TMP_VEF_EMP_TC100ENT_TEMP';
      wTableD100  = 'TMP_VEF_EMP_TD100ENT_TEMP';     
      wfielddata  = 'BDDATAENTRADAENT';
    END

  WANDFIELDREF = ' AND C.BDREFERENCIA = EXTRACT(YEAR FROM S.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM S.'||WFIELDDATA||') ';

  /************************************************************************DIFAL************************************************************************/

  /*Valor do FCP da UF de destino*/
  wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, ';
  wSQL = :wSQL ||                                           'bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, ';
  wSQL = :wSQL ||                                           'bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdCODHIST, bdCODTPHI, bdord) ';
  wSQL = :wSQL || 'SELECT C100.BDCODEMP, C100.BDEDITCHAVE BDCHAVE, I.BDORDEM, C100.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, ';
  wSQL = :wSQL ||        'NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLR_FCP_UF_DEST BDCOMPL, ' ||  IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT,  ',  'S.BDDATAEMISSAO,  ');
  wSQL = :wSQL ||        'C100.BDVLR_FCP_UF_DEST, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, ';
  wSQL = :wSQL ||        :PRCODPLANOONLINE ||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, ';
  wSQL = :wSQL ||        'C.bdCODHIST, C.bdCODTPHI, 1 BDORD ';
  wSQL = :wSQL || 'FROM ( ';
  wSQL = :wSQL ||       'SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, ';
  wSQL = :wSQL ||              '(SELECT FIRST 1 O.BDORDEM FROM '||:wTableItem||' O WHERE O.BDSESSAO = I.BDSESSAO AND O.BDCODEMP = I.BDCODEMP AND O.BDCHAVE = I.BDCHAVE ORDER BY O.BDORDEM) BDORDEM ';
  wSQL = :wSQL ||       'FROM '||:wTableItem||' I ';
  wSQL = :wSQL ||       'JOIN '||:wTableC100||' C100 ON (C100.BDSESSAO = I.BDSESSAO AND C100.BDCODEMP = I.BDCODEMP AND C100.BDCHAVE = I.BDCHAVE AND C100.BDVLR_FCP_UF_DEST > 0) ';
  wSQL = :wSQL ||       'WHERE I.BDSESSAO = '||:PRSESSAO||' ';
  wSQL = :wSQL ||       'GROUP BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, BDORDEM ';
  wSQL = :wSQL ||      ') MOV ';
  wSQL = :wSQL || 'JOIN '||:wTableItem||' I ON (I.BDSESSAO = MOV.BDSESSAO AND I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDORDEM = MOV.BDORDEM) ';
  wSQL = :wSQL || 'JOIN '||:wTable||' S ON (S.BDSESSAO = I.BDSESSAO AND S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDCODSITNF NOT IN (2, 3, 4, 5)) ';
  wSQL = :wSQL || 'JOIN '||:wTableC100||' C100 ON (C100.BDSESSAO = S.BDSESSAO AND C100.BDCODEMP = S.BDCODEMP AND C100.BDCHAVE = S.BDCHAVE AND C100.BDVLR_FCP_UF_DEST > 0) ';
  wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON (IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:PREF||') ';
  wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON (C.BDCODNAT = I.BDCODNAT'||WANDFIELDREF||' AND (C.BDCODITEMONLINE = CASE WHEN S.BDCONDPGTO = 0 THEN 225 ';
  wSQL = :wSQL ||                                                                                      'WHEN S.BDCONDPGTO = 1 THEN 226 ';
  wSQL = :wSQL ||                                                                                      'WHEN S.BDCONDPGTO = 2 THEN 227 ';
  wSQL = :wSQL ||                                                                                 'END) AND C.BDCONTADEBPROV IS NOT NULL AND C.BDCONTACREDPROV IS NOT NULL) ';
  wSQL = :wSQL || 'WHERE ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||IIF((:PRTIPOLAN = 'ENT'), 'bdDATAENTRADAENT', 'BDDATAEMISSAO')||'))) ';
  wSQL = :wSQL || 'UNION ';
  wSQL = :wSQL || 'SELECT D100.BDCODEMP, D100.BDEDITCHAVE BDCHAVE, I.BDORDEM, D100.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, ';
  wSQL = :wSQL ||        'NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLR_FCP_UF_DEST BDCOMPL, ' ||  IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT,  ',  'S.BDDATAEMISSAO,  ');
  wSQL = :wSQL ||        'D100.BDVLR_FCP_UF_DEST, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, ';
  wSQL = :wSQL ||        :PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, ';
  wSQL = :wSQL ||        'C.bdCODHIST, C.bdCODTPHI, 1 BDORD ';
  wSQL = :wSQL || 'FROM ( ';
  wSQL = :wSQL ||       'SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, ';
  wSQL = :wSQL ||              '(SELECT FIRST 1 O.BDORDEM FROM '||:wTableItem||' O WHERE O.BDSESSAO = I.BDSESSAO AND O.BDCODEMP = I.BDCODEMP AND O.BDCHAVE = I.BDCHAVE ORDER BY O.BDORDEM) BDORDEM ';
  wSQL = :wSQL ||       'FROM '||:wTableItem||' I ';
  wSQL = :wSQL ||       'JOIN '||:wTableD100||' D100 ON (D100.BDSESSAO = I.BDSESSAO AND D100.BDCODEMP = I.BDCODEMP AND D100.BDCHAVE = I.BDCHAVE AND D100.BDVLR_FCP_UF_DEST > 0) ';
  wSQL = :wSQL ||       'WHERE I.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL ||       'GROUP BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, BDORDEM ';
  wSQL = :wSQL ||      ') MOV ';
  wSQL = :wSQL || 'JOIN '||:wTableItem||' I ON (I.BDSESSAO = MOV.BDSESSAO AND I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDORDEM = MOV.BDORDEM) ';
  wSQL = :wSQL || 'JOIN '||:wTable||' S ON (S.BDSESSAO = I.BDSESSAO AND S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDCODSITNF NOT IN (2, 3, 4, 5)) ';
  wSQL = :wSQL || 'JOIN '||:wTableD100||' D100 ON (D100.BDSESSAO = S.BDSESSAO AND D100.BDCODEMP = S.BDCODEMP AND D100.BDCHAVE = S.BDCHAVE AND D100.BDVLR_FCP_UF_DEST > 0) ';
  wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON (IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:PREF||') ';
  wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON (C.BDCODNAT = I.BDCODNAT'||WANDFIELDREF||' AND (C.BDCODITEMONLINE = CASE WHEN S.BDCONDPGTO = 0 THEN 225 '; /*Valor do ICMS interestadual para UF de destino - A vista*/
  wSQL = :wSQL ||                                                                                      'WHEN S.BDCONDPGTO = 1 THEN 226 '; /*Valor do ICMS interestadual para UF de destino - Prazo*/
  wSQL = :wSQL ||                                                                                      'WHEN S.BDCONDPGTO = 2 THEN 227 '; /*Valor do ICMS interestadual para UF de destino - Outras*/
  wSQL = :wSQL ||                                                                                 'END) AND C.BDCONTADEBPROV IS NOT NULL AND C.BDCONTACREDPROV IS NOT NULL) ';
  wSQL = :wSQL || 'WHERE ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||IIF((:PRTIPOLAN = 'ENT'), 'bdDATAENTRADAENT', 'BDDATAEMISSAO')||'))) ';

  EXECUTE STATEMENT :wSQL;

  /*Valor do ICMS interestadual para UF de destino*/
  wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, ';
  wSQL = :wSQL ||                                           'bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, ';
  wSQL = :wSQL ||                                           'bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdCODHIST, bdCODTPHI, bdord) ';
  wSQL = :wSQL || 'SELECT C100.BDCODEMP, C100.BDEDITCHAVE BDCHAVE, I.BDORDEM, C100.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, ';
  wSQL = :wSQL ||        'C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRICMS_UF_DEST BDCOMPL, '|| IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT,  ',  'S.BDDATAEMISSAO,  ')||' C100.BDVLRICMS_UF_DEST, 100 BDTIPOLAN, ';
  wSQL = :wSQL ||        'S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, ';
  wSQL = :wSQL ||        'C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.bdCODHIST, C.bdCODTPHI, 1 BDORD ';
  wSQL = :wSQL || 'FROM ( ';
  wSQL = :wSQL ||       'SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, ';
  wSQL = :wSQL ||              '(SELECT FIRST 1 O.BDORDEM FROM '||:wTableItem||' O WHERE O.BDSESSAO = I.BDSESSAO AND O.BDCODEMP = I.BDCODEMP AND O.BDCHAVE = I.BDCHAVE ORDER BY O.BDORDEM) BDORDEM ';
  wSQL = :wSQL ||       'FROM '||:wTableItem||' I ';
  wSQL = :wSQL ||       'JOIN '||:wTableC100||' C100 ON (C100.BDSESSAO = I.BDSESSAO AND C100.BDCODEMP = I.BDCODEMP AND C100.BDCHAVE = I.BDCHAVE AND C100.BDVLRICMS_UF_DEST > 0) ';
  wSQL = :wSQL ||       'WHERE I.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL ||       'GROUP BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, BDORDEM ';
  wSQL = :wSQL ||      ') MOV ';
  wSQL = :wSQL || 'JOIN '||:wTableItem||' I ON(I.BDSESSAO = MOV.BDSESSAO AND I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDORDEM = MOV.BDORDEM) ';
  wSQL = :wSQL || 'JOIN '||:wTableC100||' C100 ON(C100.BDSESSAO = I.BDSESSAO AND C100.BDCODEMP = I.BDCODEMP AND C100.BDCHAVE = I.BDCHAVE AND C100.BDVLRICMS_UF_DEST > 0) ';
  wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDSESSAO = I.BDSESSAO AND S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDCODSITNF NOT IN (2, 3, 4, 5)) ';
  wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:PREF||') ';
  wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT'||WANDFIELDREF||' AND (C.BDCODITEMONLINE = CASE WHEN S.BDCONDPGTO = 0 THEN 228 ';/*Valor do ICMS interestadual para UF de destino - A vista*/
  wSQL = :wSQL ||                                                                                     'WHEN S.BDCONDPGTO = 1 THEN 229 ';/*Valor do ICMS interestadual para UF de destino - Prazo*/
  wSQL = :wSQL ||                                                                                     'WHEN S.BDCONDPGTO = 2 THEN 230 ';/*Valor do ICMS interestadual para UF de destino - Outras*/
  wSQL = :wSQL ||                                                                                'END) AND C.BDCONTADEBPROV IS NOT NULL AND C.BDCONTACREDPROV IS NOT NULL) ';
  wSQL = :wSQL || 'WHERE ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||IIF((:PRTIPOLAN = 'ENT'), 'bdDATAENTRADAENT', 'BDDATAEMISSAO')||'))) ';
  wSQL = :wSQL || 'UNION ';
  wSQL = :wSQL || 'SELECT D.BDCODEMP, D.BDEDITCHAVE BDCHAVE, I.BDORDEM, D.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, ';
  wSQL = :wSQL ||        'C.BDCONTADEBPROV, C.BDCONTACREDPROV, NULL BDCOMPL, '|| IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT,  ',  'S.BDDATAEMISSAO,  ')||' D.BDVLRICMS_UF_DEST, 100 BDTIPOLAN, ';
  wSQL = :wSQL ||        'S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, ';
  wSQL = :wSQL ||        'C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.bdCODHIST, C.bdCODTPHI, 1 BDORD ';
  wSQL = :wSQL || 'FROM (';
  wSQL = :wSQL ||       'SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, ';
  wSQL = :wSQL ||              '(SELECT FIRST 1 O.BDORDEM FROM '||:wTableItem||' O WHERE O.BDSESSAO = I.BDSESSAO AND O.BDCODEMP = I.BDCODEMP AND O.BDCHAVE = I.BDCHAVE ORDER BY O.BDORDEM) BDORDEM ';
  wSQL = :wSQL ||       'FROM '||:wTableItem||' I ';
  wSQL = :wSQL ||       'JOIN '||:wTableD100||' D100 ON (D100.BDSESSAO = I.BDSESSAO AND D100.BDCODEMP = I.BDCODEMP AND D100.BDCHAVE = I.BDCHAVE AND D100.BDVLRICMS_UF_DEST > 0) ';
  wSQL = :wSQL ||       'WHERE I.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL ||       'GROUP BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, BDORDEM ';
  wSQL = :wSQL ||      ') MOV ';
  wSQL = :wSQL || 'JOIN '||:wTableItem||' I ON(I.BDSESSAO = MOV.BDSESSAO AND I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDORDEM = MOV.BDORDEM) ';
  wSQL = :wSQL || 'JOIN '||:wTableD100||' D ON(D.BDSESSAO = I.BDSESSAO AND D.BDCODEMP = I.BDCODEMP AND D.BDCHAVE = I.BDCHAVE AND D.BDVLRICMS_UF_DEST > 0) ';
  wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDSESSAO = I.BDSESSAO AND S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDCODSITNF NOT IN (2, 3, 4, 5)) ';
  wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:PREF||') ';
  wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT'||WANDFIELDREF||' AND (C.BDCODITEMONLINE = CASE WHEN S.BDCONDPGTO = 0 THEN 228 ';/*Valor do ICMS interestadual para UF de destino - A vista*/
  wSQL = :wSQL ||                                                                                     'WHEN S.BDCONDPGTO = 1 THEN 229 ';/*Valor do ICMS interestadual para UF de destino - Prazo*/
  wSQL = :wSQL ||                                                                                     'WHEN S.BDCONDPGTO = 2 THEN 230 ';/*Valor do ICMS interestadual para UF de destino - Outras*/
  wSQL = :wSQL ||                                                                                'END) AND C.BDCONTADEBPROV IS NOT NULL AND C.BDCONTACREDPROV IS NOT NULL) ';
  wSQL = :wSQL || 'WHERE ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||IIF((:PRTIPOLAN = 'ENT'), 'bdDATAENTRADAENT', 'BDDATAEMISSAO')||'))); ';
  EXECUTE STATEMENT :wSQL;

  /*Valor do ICMS interestadual para UF do remetente*/
  wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, ';
  wSQL = :wSQL ||                                           'bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, ';
  wSQL = :wSQL ||                                           'bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdCODHIST, bdCODTPHI, bdord) ';
  wSQL = :wSQL || 'SELECT C100.BDCODEMP, C100.BDEDITCHAVE BDCHAVE, I.BDORDEM, C100.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, ';
  wSQL = :wSQL ||        'C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRICMS_UF_REM BDCOMPL, '|| IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT,  ',  'S.BDDATAEMISSAO,  ')||' C100.BDVLRICMS_UF_REM, 100 BDTIPOLAN, ';
  wSQL = :wSQL ||        'S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, ';
  wSQL = :wSQL ||        'C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.bdCODHIST, C.bdCODTPHI, 1 BDORD ';
  wSQL = :wSQL || 'FROM ( ';
  wSQL = :wSQL ||       'SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, ';
  wSQL = :wSQL ||              '(SELECT FIRST 1 O.BDORDEM FROM '||:wTableItem||' O WHERE O.BDSESSAO = I.BDSESSAO AND O.BDCODEMP = I.BDCODEMP AND O.BDCHAVE = I.BDCHAVE ORDER BY O.BDORDEM) BDORDEM ';
  wSQL = :wSQL ||       'FROM '||:wTableItem||' I ';
  wSQL = :wSQL ||       'JOIN '||:wTableC100||' C100 ON (C100.BDSESSAO = I.BDSESSAO AND C100.BDCODEMP = I.BDCODEMP AND C100.BDCHAVE = I.BDCHAVE AND C100.BDVLRICMS_UF_REM > 0) ';
  wSQL = :wSQL ||       'WHERE I.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL ||       'GROUP BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, BDORDEM ';
  wSQL = :wSQL ||      ') MOV ';
  wSQL = :wSQL || 'JOIN '||:wTableItem||' I ON(I.BDSESSAO = MOV.BDSESSAO AND I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDORDEM = MOV.BDORDEM) ';
  wSQL = :wSQL || 'JOIN '||:wTableC100||' C100 ON(C100.BDSESSAO = I.BDSESSAO AND C100.BDCODEMP = I.BDCODEMP AND C100.BDCHAVE = I.BDCHAVE AND C100.BDVLRICMS_UF_REM > 0) ';
  wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDSESSAO = I.BDSESSAO AND S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDCODSITNF NOT IN (2, 3, 4, 5)) ';
  wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:PREF||') ';
  wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT'||WANDFIELDREF||' AND (C.BDCODITEMONLINE = CASE WHEN S.BDCONDPGTO = 0 THEN 231 ';/*Valor do ICMS interestadual para UF de destino - A vista*/
  wSQL = :wSQL ||                                                                                     'WHEN S.BDCONDPGTO = 1 THEN 232 ';/*Valor do ICMS interestadual para UF de destino - Prazo*/
  wSQL = :wSQL ||                                                                                     'WHEN S.BDCONDPGTO = 2 THEN 233 ';/*Valor do ICMS interestadual para UF de destino - Outras*/
  wSQL = :wSQL ||                                                                                'END) AND C.BDCONTADEBPROV IS NOT NULL AND C.BDCONTACREDPROV IS NOT NULL) ';
  wSQL = :wSQL || 'WHERE ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||IIF((:PRTIPOLAN = 'ENT'), 'bdDATAENTRADAENT', 'BDDATAEMISSAO')||'))) ';
  wSQL = :wSQL || 'UNION ';
  wSQL = :wSQL || 'SELECT D.BDCODEMP, D.BDEDITCHAVE BDCHAVE, I.BDORDEM, D.BDSESSAO, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, ';
  wSQL = :wSQL ||        'C.BDCONTADEBPROV, C.BDCONTACREDPROV, NULL BDCOMPL, '|| IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT,  ',  'S.BDDATAEMISSAO,  ')||' D.BDVLRICMS_UF_REM, 100 BDTIPOLAN, ';
  wSQL = :wSQL ||        'S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, ';
  wSQL = :wSQL ||        'C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.bdCODHIST, C.bdCODTPHI, 1 BDORD ';
  wSQL = :wSQL || 'FROM (';
  wSQL = :wSQL ||       'SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, ';
  wSQL = :wSQL ||              '(SELECT FIRST 1 O.BDORDEM FROM '||:wTableItem||' O WHERE O.BDSESSAO = I.BDSESSAO AND O.BDCODEMP = I.BDCODEMP AND O.BDCHAVE = I.BDCHAVE ORDER BY O.BDORDEM) BDORDEM ';
  wSQL = :wSQL ||       'FROM '||:wTableItem||' I ';
  wSQL = :wSQL ||       'JOIN '||:wTableD100||' D100 ON (D100.BDSESSAO = I.BDSESSAO AND D100.BDCODEMP = I.BDCODEMP AND D100.BDCHAVE = I.BDCHAVE AND D100.BDVLRICMS_UF_REM > 0) ';
  wSQL = :wSQL ||       'WHERE I.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL ||       'GROUP BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, BDORDEM ';
  wSQL = :wSQL ||      ') MOV ';
  wSQL = :wSQL || 'JOIN '||:wTableItem||' I ON(I.BDSESSAO = MOV.BDSESSAO AND I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDORDEM = MOV.BDORDEM) ';
  wSQL = :wSQL || 'JOIN '||:wTableD100||' D ON(D.BDSESSAO = I.BDSESSAO AND D.BDCODEMP = I.BDCODEMP AND D.BDCHAVE = I.BDCHAVE AND D.BDVLRICMS_UF_REM > 0) ';
  wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDSESSAO = I.BDSESSAO AND S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDCODSITNF NOT IN (2, 3, 4, 5)) ';
  wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:PREF||') ';
  wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDCODNAT = I.BDCODNAT'||WANDFIELDREF||' AND (C.BDCODITEMONLINE = CASE WHEN S.BDCONDPGTO = 0 THEN 231 ';/*Valor do ICMS interestadual para UF de destino - A vista*/
  wSQL = :wSQL ||                                                                                     'WHEN S.BDCONDPGTO = 1 THEN 232 ';/*Valor do ICMS interestadual para UF de destino - Prazo*/
  wSQL = :wSQL ||                                                                                     'WHEN S.BDCONDPGTO = 2 THEN 233 ';/*Valor do ICMS interestadual para UF de destino - Outras*/
  wSQL = :wSQL ||                                                                                'END) AND C.BDCONTADEBPROV IS NOT NULL AND C.BDCONTACREDPROV IS NOT NULL) ';
  wSQL = :wSQL || 'WHERE ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||IIF((:PRTIPOLAN = 'ENT'), 'bdDATAENTRADAENT', 'BDDATAEMISSAO')||'))); ';
  EXECUTE STATEMENT :wSQL;
  /*****************************************************************************************************************************************************/

END^

CREATE OR ALTER PROCEDURE sp_cria_pre_contab_ret_aposesp (
    prsessao INTEGER,
    prcodplanoonline INTEGER,
    prenqfed INTEGER,
    prtipolan VARCHAR(5))
RETURNS (
    bdsql VARCHAR(5000))
AS
DECLARE VARIABLE wtableincon VARCHAR(50);
DECLARE VARIABLE wef INTEGER;
DECLARE VARIABLE wtable VARCHAR(50);
DECLARE VARIABLE wtiplan INTEGER;
DECLARE VARIABLE wtablerateio VARCHAR(32);
DECLARE VARIABLE wtableitem VARCHAR(50);
DECLARE VARIABLE wtableinss VARCHAR(31);
DECLARE VARIABLE wsql VARCHAR(5000);
DECLARE VARIABLE wsomaret VARCHAR(200);
DECLARE VARIABLE wcoditeminss15 INTEGER;
DECLARE VARIABLE wcoditeminss20 INTEGER;
DECLARE VARIABLE wcoditeminss25 INTEGER;
DECLARE VARIABLE wfielddata VARCHAR(32);
DECLARE VARIABLE wandfieldref VARCHAR(200);
BEGIN

  wTable            = '';
  wTableItem        = '';
  wTableIncon       = '';
  wTableINSS        = '';
  wEF               = 3;
  wTableRateio      = '';
  PRTIPOLAN         = UPPER(:PRTIPOLAN);
  wTipLan           = NULL;
                               
  wfielddata  = 'BDDATAEMISSAO';
  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTable           = 'TMP_VEF_EMP_TMOVSAI_TEMP';
      wTableItem       = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
      wTableIncon      = 'VEF_INCON_TMOVSAI';
      wTableINSS       = 'TMP_VEF_EMP_TMOVSAIDED_TEMP';
      wCodItemInss15   = 304;
      wCodItemInss20   = 305;
      wCodItemInss25   = 306;
    END
  ELSE
  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTable            = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItem        = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      wTableIncon       = 'VEF_INCON_TMOVENT';
      wTableINSS        = 'TMP_VEF_EMP_TMOVENTDED_TEMP';
      wCodItemInss15    = 313;
      wCodItemInss20    = 314;
      wCodItemInss25    = 315;     
      wfielddata        = 'BDDATAENTRADAENT';
    END
  ELSE
  IF ((:PRTIPOLAN = 'SERE') OR (:PRTIPOLAN = 'SERR')) THEN /*SERE - Serviço emitido | SERR - Serviço recebido*/
    BEGIN
      wTable       = 'TMP_VEF_EMP_TMOVSER_TEMP';
      wTableItem   = 'TMP_VEF_EMP_TMOVSERITENS_TEMP';
      wTableIncon  = 'VEF_INCON_TMOVSER';
      wTableINSS   = 'TMP_VEF_EMP_TMOVSERDED_TEMP';
      wTableRateio = 'TMP_VEF_EMP_TMOVRATSER_TEMP';

      IF (:PRTIPOLAN = 'SERE') THEN
        BEGIN
          wTipLan = 0;
          wCodItemInss15 = 307;
          wCodItemInss20 = 308;
          wCodItemInss25 = 309;
        END
      ELSE
        BEGIN
          wTipLan = 1;
          wCodItemInss15 = 310;
          wCodItemInss20 = 311;
          wCodItemInss25 = 312;
        END
    END
  ELSE
    EXIT;

  WSOMARET = '';   
  WANDFIELDREF = ' AND C.BDREFERENCIA = EXTRACT(YEAR FROM S.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM S.'||WFIELDDATA||') ';

  /*---------------------------------------------------------------------------RETENÇÃO DE INSS 15 ANOS------------------------------------------------------------------------------------*/
  /* -------------------------------------------------------------Contabilização INSS aposentadoria especial #123489 #128660 #101172 #100393 #DBS! ----------------------------------------*/
  WSOMARET = '(INSS.BDVLRAPOS15)';

  wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP (BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCHAVE_VSUC, BDCODPLAPADRAO, BDCODUSU, BDDEBITO, BDCREDITO, BDCOMPL, BDDATA, BDVALOR, BDTIPOLAN, BDDCTO, BDTRANSACAO, BDTRANFECHADA, BDFORMULA, BDCODPLANOONLINE, BDCHAVETITULO, BDCLASSIFBUSCA, BDCLASSIFTITULO, BDCODITEMONLINE, BDCHAVECONTA, BDCODHIST,BDCODTPHI, BDORD) ';
  wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, ';

  IF ((:prTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
    wSQL = :wSQL || 'NULL BDCONTADEBPROV, C.BDCONTACREDPROV, ';

  ELSE
  IF ((:prTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE')) THEN
    wSQL = :wSQL || 'C.BDCONTADEBPROV, NULL BDCONTACREDPROV, ';

  wSQL = :wSQL ||        'IIF(COALESCE(I.BDCOMPHIST_VLRINSSAPOS15,'''') <> '''', COALESCE(I.BDCOMPHIST_VLRINSSAPOS15,''''), COALESCE(I.BDCOMPHIST_VLRCONTAB,'''')), ';

  wSQL = :wSQL ||         IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT,  ',  'S.BDDATAEMISSAO,  ') ||
                                           ' COALESCE(IIF(S.BDVALORNOTA > 0 AND S.BDRATEIARET = ''TRUE'', CAST(I.BDVLRCONTAB/CAST(S.BDVALORNOTA AS NUMERIC(15,6)) * ' || WSOMARET ||
                                           ' AS NUMERIC(15,2)) + COALESCE('|| WSOMARET || ' - IO.BDVLRRET,0),' || WSOMARET ||'),0) BDRETINSS15, ';

  wSQL = :wSQL ||        ' 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, ';
  wSQL = :wSQL ||          :PRCODPLANOONLINE || ' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODHIST, C.BDCODTPHI, 4 BDORD ';
  wSQL = :wSQL || 'FROM ' || :wTableINSS || ' INSS ';
  wSQL = :wSQL || 'LEFT OUTER JOIN (';
  wSQL = :wSQL ||                   'SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO, I.BDORDEM, I.BDEDITCHAVE, I.BDCHAVE_VSUC, I.BDCOMPHIST_VLRINSSAPOS15, I.BDCOMPHIST_VLRCONTAB, I.BDVLRCONTAB ';
  wSQL = :wSQL ||                   'FROM ' || :wTableItem || ' I ';

  IF (wTableRateio <> '') THEN
    wSQL = :wSQL ||       'LEFT OUTER JOIN ' || wTableRateio || ' RAT ON (RAT.BDCODEMP = I.BDCODEMP AND RAT.BDCHAVE = I.BDCHAVE AND RAT.BDORDEM = I.BDORDEM AND RAT.BDSESSAO = I.BDSESSAO) '; -- Rateio vão fazer contabilização própria e não aqui

  wSQL = :wSQL ||                  'WHERE I.BDSESSAO = '||:PRSESSAO;

  IF (wTableRateio <> '') THEN
    wSQL = :wSQL ||       ' AND RAT.BDCODEMP IS NULL '; -- Somente quando não tiver rateio no lançamento

  wSQL = :wSQL ||                 ') I ON(I.BDCODEMP = INSS.BDCODEMP AND I.BDCHAVE = INSS.BDCHAVE AND I.BDSESSAO = INSS.BDSESSAO) ';

  IF (:wTipLan IS NOT NULL) THEN
    wSQL = :wSQL || 'JOIN ' || :wTable || ' S ON(S.BDCODEMP = INSS.BDCODEMP AND S.BDCHAVE = INSS.BDCHAVE AND S.BDSESSAO = INSS.BDSESSAO AND S.BDTIPLAN = ' || :wTipLan || ') ';
  ELSE
    wSQL = :wSQL || 'LEFT OUTER JOIN ' || :wTable || ' S ON(S.BDCODEMP = INSS.BDCODEMP AND S.BDCHAVE = INSS.BDCHAVE AND S.BDSESSAO = INSS.BDSESSAO) ';

  wSQL = :wSQL || 'LEFT OUTER JOIN ( ';
  wSQL = :wSQL || '    SELECT I.BDCODEMP, I.BDCHAVE, MAX(I.BDORDEM) BDORDEM, SUM(COALESCE(IIF(M.BDVALORNOTA > 0,CAST(I.BDVLRCONTAB/CAST(M.BDVALORNOTA AS NUMERIC(15,6)) * ' || WSOMARET ||
                  '    AS NUMERIC(15,2)),' || WSOMARET || '),0)) BDVLRRET ';

  wSQL = :wSQL || '    FROM ' || wTable || ' M ';
  wSQL = :wSQL || '    LEFT OUTER JOIN ' || wTableINSS || ' INSS ON (INSS.BDCODEMP = M.BDCODEMP AND INSS.BDCHAVE = M.BDCHAVE AND INSS.BDSESSAO = M.BDSESSAO) ';
  wSQL = :wSQL || '    LEFT OUTER JOIN ' || wTableItem || ' I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE AND I.BDSESSAO = M.BDSESSAO) ';
  wSQL = :wSQL || '    LEFT OUTER JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = I.BDCODNAT) ';
  wSQL = :wSQL || '    WHERE M.BDSESSAO = ' || :PRSESSAO || ' AND ';
  wSQL = :wSQL || '          N.BDCONTABILIZA = ''TRUE'' ';
  wSQL = :wSQL || '    GROUP BY I.BDCODEMP, I.BDCHAVE ';
  wSQL = :wSQL || ')IO ON (IO.BDCODEMP = I.BDCODEMP AND IO.BDCHAVE = I.BDCHAVE AND IO.BDORDEM = I.BDORDEM) ';

  wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO'||WANDFIELDREF||' AND C.BDCODITEMONLINE = ' || :wCodItemInss15 || ') ';
                  /*Saída olha data de emissão, ao fazer a contabilização de entrada/serviço tem que ser adaptado para olhar os outros campos de data*/
  wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = INSS.BDCODEMP AND IC.BDCODSIS = ' || :wEF || ') ';
  wSQL = :wSQL || 'WHERE INSS.BDSESSAO = ' || :PRSESSAO;
  wSQL = :wSQL || ' AND INSS.BDVLRAPOS15 > 0 AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
  wSQL = :wSQL || ' AND (S.BDRATEIARET = ''TRUE'' OR S.BDPRIMEIRAORDEM = I.BDORDEM) ';
  wSQL = :wSQL || ' AND ((IC.BDCODEMP IS NULL) OR (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||IIF((:PRTIPOLAN = 'ENT'), 'BDDATAENTRADAENT', 'BDDATAEMISSAO') || '))) ';
  wSQL = :wSQL || ' AND NOT EXISTS(';
  wSQL = :wSQL ||                'SELECT INCO.BDCODINCONSISTENCIA ';
  wSQL = :wSQL ||                'FROM ' || :wTableIncon || ' INCO ';
  wSQL = :wSQL ||                'WHERE INCO.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL ||                ' AND  INCO.BDCHAVE  = I.BDCHAVE ';
  wSQL = :wSQL ||                ' AND  INCO.BDSESSAO = I.BDSESSAO ';
  wSQL = :wSQL ||               ')';
  EXECUTE STATEMENT :wSQL;

  /*---------------------------------------------------------------------------RETENÇÃO DE INSS 15 ANOS------------------------------------------------------------------------------------*/

  /*---------------------------------------------------------------------------RETENÇÃO DE INSS 20 ANOS------------------------------------------------------------------------------------*/
  /* -------------------------------------------------------------Contabilização INSS aposentadoria especial #123489 #128660 #101172 #100393 #DBS! ----------------------------------------*/
  WSOMARET = '(INSS.BDVLRAPOS20)';

  wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP (BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCHAVE_VSUC, BDCODPLAPADRAO, BDCODUSU, BDDEBITO, BDCREDITO, BDCOMPL, BDDATA, BDVALOR, BDTIPOLAN, BDDCTO, BDTRANSACAO, BDTRANFECHADA, BDFORMULA, BDCODPLANOONLINE, BDCHAVETITULO, BDCLASSIFBUSCA, BDCLASSIFTITULO, BDCODITEMONLINE, BDCHAVECONTA, BDCODHIST,BDCODTPHI, BDORD) ';
  wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, ';

  IF ((:prTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
    wSQL = :wSQL || 'NULL BDCONTADEBPROV, C.BDCONTACREDPROV, ';

  ELSE
  IF ((:prTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE')) THEN
    wSQL = :wSQL || 'C.BDCONTADEBPROV, NULL BDCONTACREDPROV, ';

  wSQL = :wSQL ||        'IIF(COALESCE(I.BDCOMPHIST_VLRINSSAPOS20,'''') <> '''', COALESCE(I.BDCOMPHIST_VLRINSSAPOS20,''''), COALESCE(I.BDCOMPHIST_VLRCONTAB,'''')), ';

  wSQL = :wSQL ||         IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT,  ',  'S.BDDATAEMISSAO,  ') ||
                                           ' COALESCE(IIF(S.BDVALORNOTA > 0 AND S.BDRATEIARET = ''TRUE'', CAST(I.BDVLRCONTAB/CAST(S.BDVALORNOTA AS NUMERIC(15,6)) * ' || WSOMARET ||
                                           ' AS NUMERIC(15,2)) + COALESCE('|| WSOMARET || ' - IO.BDVLRRET,0),' || WSOMARET ||'),0) BDRETINSS20, ';

  wSQL = :wSQL ||        ' 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, ';
  wSQL = :wSQL ||          :PRCODPLANOONLINE || ' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODHIST, C.BDCODTPHI, 4 BDORD ';
  wSQL = :wSQL || 'FROM ' || :wTableINSS || ' INSS ';
  wSQL = :wSQL || 'LEFT OUTER JOIN (';
  wSQL = :wSQL ||                   'SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO, I.BDORDEM, I.BDEDITCHAVE, I.BDCHAVE_VSUC, I.BDCOMPHIST_VLRINSSAPOS20, I.BDCOMPHIST_VLRCONTAB, I.BDVLRCONTAB ';
  wSQL = :wSQL ||                   'FROM ' || :wTableItem || ' I ';

  IF (wTableRateio <> '') THEN
    wSQL = :wSQL ||       'LEFT OUTER JOIN ' || wTableRateio || ' RAT ON (RAT.BDCODEMP = I.BDCODEMP AND RAT.BDCHAVE = I.BDCHAVE AND RAT.BDORDEM = I.BDORDEM AND RAT.BDSESSAO = I.BDSESSAO) '; -- Rateio vão fazer contabilização própria e não aqui

  wSQL = :wSQL ||                  'WHERE I.BDSESSAO = '||:PRSESSAO;

  IF (wTableRateio <> '') THEN
    wSQL = :wSQL ||       ' AND RAT.BDCODEMP IS NULL '; -- Somente quando não tiver rateio no lançamento

  wSQL = :wSQL ||                 ') I ON(I.BDCODEMP = INSS.BDCODEMP AND I.BDCHAVE = INSS.BDCHAVE AND I.BDSESSAO = INSS.BDSESSAO) ';

  IF (:wTipLan IS NOT NULL) THEN
    wSQL = :wSQL || 'JOIN ' || :wTable || ' S ON(S.BDCODEMP = INSS.BDCODEMP AND S.BDCHAVE = INSS.BDCHAVE AND S.BDSESSAO = INSS.BDSESSAO AND S.BDTIPLAN = ' || :wTipLan || ') ';
  ELSE
    wSQL = :wSQL || 'LEFT OUTER JOIN ' || :wTable || ' S ON(S.BDCODEMP = INSS.BDCODEMP AND S.BDCHAVE = INSS.BDCHAVE AND S.BDSESSAO = INSS.BDSESSAO) ';

  wSQL = :wSQL || 'LEFT OUTER JOIN ( ';
  wSQL = :wSQL || '    SELECT I.BDCODEMP, I.BDCHAVE, MAX(I.BDORDEM) BDORDEM, SUM(COALESCE(IIF(M.BDVALORNOTA > 0,CAST(I.BDVLRCONTAB/CAST(M.BDVALORNOTA AS NUMERIC(15,6)) * ' || WSOMARET ||
                  '    AS NUMERIC(15,2)),' || WSOMARET || '),0)) BDVLRRET ';

  wSQL = :wSQL || '    FROM ' || wTable || ' M ';
  wSQL = :wSQL || '    LEFT OUTER JOIN ' || wTableINSS || ' INSS ON (INSS.BDCODEMP = M.BDCODEMP AND INSS.BDCHAVE = M.BDCHAVE AND INSS.BDSESSAO = M.BDSESSAO) ';
  wSQL = :wSQL || '    LEFT OUTER JOIN ' || wTableItem || ' I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE AND I.BDSESSAO = M.BDSESSAO) ';
  wSQL = :wSQL || '    LEFT OUTER JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = I.BDCODNAT) ';
  wSQL = :wSQL || '    WHERE M.BDSESSAO = ' || :PRSESSAO || ' AND ';
  wSQL = :wSQL || '          N.BDCONTABILIZA = ''TRUE'' ';
  wSQL = :wSQL || '    GROUP BY I.BDCODEMP, I.BDCHAVE ';
  wSQL = :wSQL || ')IO ON (IO.BDCODEMP = I.BDCODEMP AND IO.BDCHAVE = I.BDCHAVE AND IO.BDORDEM = I.BDORDEM) ';

  wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO'||WANDFIELDREF||' AND C.BDCODITEMONLINE = ' || :wCodItemInss20 || ') ';
                  /*Saída olha data de emissão, ao fazer a contabilização de entrada/serviço tem que ser adaptado para olhar os outros campos de data*/
  wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = INSS.BDCODEMP AND IC.BDCODSIS = ' || :wEF || ') ';
  wSQL = :wSQL || 'WHERE INSS.BDSESSAO = ' || :PRSESSAO;
  wSQL = :wSQL || ' AND INSS.BDVLRAPOS20 > 0 AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
  wSQL = :wSQL || ' AND (S.BDRATEIARET = ''TRUE'' OR S.BDPRIMEIRAORDEM = I.BDORDEM) ';
  wSQL = :wSQL || ' AND ((IC.BDCODEMP IS NULL) OR (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||IIF((:PRTIPOLAN = 'ENT'), 'BDDATAENTRADAENT', 'BDDATAEMISSAO') || '))) ';
  wSQL = :wSQL || ' AND NOT EXISTS(';
  wSQL = :wSQL ||                'SELECT INCO.BDCODINCONSISTENCIA ';
  wSQL = :wSQL ||                'FROM ' || :wTableIncon || ' INCO ';
  wSQL = :wSQL ||                'WHERE INCO.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL ||                ' AND  INCO.BDCHAVE  = I.BDCHAVE ';
  wSQL = :wSQL ||                ' AND  INCO.BDSESSAO = I.BDSESSAO ';
  wSQL = :wSQL ||               ')';
  EXECUTE STATEMENT :wSQL;

   /*---------------------------------------------------------------------------RETENÇÃO DE INSS 20 ANOS----------------------------------------------------------------------------------------------*/

  /*---------------------------------------------------------------------------RETENÇÃO DE INSS 25 ANOS-----------------------------------------------------------------------------------------------*/
  /* -------------------------------------------------------------Contabilização INSS aposentadoria especial #123489 #128660 #101172 #100393 #DBS! ---------------------------------------------------*/
  WSOMARET = '(INSS.BDVLRAPOS25)';

  wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP (BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCHAVE_VSUC, BDCODPLAPADRAO, BDCODUSU, BDDEBITO, BDCREDITO, BDCOMPL, BDDATA, BDVALOR, BDTIPOLAN, BDDCTO, BDTRANSACAO, BDTRANFECHADA, BDFORMULA, BDCODPLANOONLINE, BDCHAVETITULO, BDCLASSIFBUSCA, BDCLASSIFTITULO, BDCODITEMONLINE, BDCHAVECONTA, BDCODHIST,BDCODTPHI, BDORD) ';
  wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, ';

  IF ((:prTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
    wSQL = :wSQL || 'NULL BDCONTADEBPROV, C.BDCONTACREDPROV, ';

  ELSE
  IF ((:prTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE')) THEN
    wSQL = :wSQL || 'C.BDCONTADEBPROV, NULL BDCONTACREDPROV, ';

  wSQL = :wSQL ||        'IIF(COALESCE(I.BDCOMPHIST_VLRINSSAPOS25,'''') <> '''', COALESCE(I.BDCOMPHIST_VLRINSSAPOS25,''''), COALESCE(I.BDCOMPHIST_VLRCONTAB,'''')), ';

  wSQL = :wSQL ||         IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT,  ',  'S.BDDATAEMISSAO,  ') ||
                                           ' COALESCE(IIF(S.BDVALORNOTA > 0 AND S.BDRATEIARET = ''TRUE'', CAST(I.BDVLRCONTAB/CAST(S.BDVALORNOTA AS NUMERIC(15,6)) * ' || WSOMARET ||
                                           ' AS NUMERIC(15,2)) + COALESCE('|| WSOMARET || ' - IO.BDVLRRET,0),' || WSOMARET ||'),0) BDRETINSS25, ';

  wSQL = :wSQL ||        ' 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, ';
  wSQL = :wSQL ||          :PRCODPLANOONLINE || ' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODHIST, C.BDCODTPHI, 4 BDORD ';
  wSQL = :wSQL || 'FROM ' || :wTableINSS || ' INSS ';
  wSQL = :wSQL || 'LEFT OUTER JOIN (';
  wSQL = :wSQL ||                   'SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO, I.BDORDEM, I.BDEDITCHAVE, I.BDCHAVE_VSUC, I.BDCOMPHIST_VLRINSSAPOS25, I.BDCOMPHIST_VLRCONTAB, I.BDVLRCONTAB ';
  wSQL = :wSQL ||                   'FROM ' || :wTableItem || ' I ';

  IF (wTableRateio <> '') THEN
    wSQL = :wSQL ||       'LEFT OUTER JOIN ' || wTableRateio || ' RAT ON (RAT.BDCODEMP = I.BDCODEMP AND RAT.BDCHAVE = I.BDCHAVE AND RAT.BDORDEM = I.BDORDEM AND RAT.BDSESSAO = I.BDSESSAO) '; -- Rateio vão fazer contabilização própria e não aqui

  wSQL = :wSQL ||                  'WHERE I.BDSESSAO = '||:PRSESSAO;

  IF (wTableRateio <> '') THEN
    wSQL = :wSQL ||       ' AND RAT.BDCODEMP IS NULL '; -- Somente quando não tiver rateio no lançamento

  wSQL = :wSQL ||                 ') I ON(I.BDCODEMP = INSS.BDCODEMP AND I.BDCHAVE = INSS.BDCHAVE AND I.BDSESSAO = INSS.BDSESSAO) ';

  IF (:wTipLan IS NOT NULL) THEN
    wSQL = :wSQL || 'JOIN ' || :wTable || ' S ON(S.BDCODEMP = INSS.BDCODEMP AND S.BDCHAVE = INSS.BDCHAVE AND S.BDSESSAO = INSS.BDSESSAO AND S.BDTIPLAN = ' || :wTipLan || ') ';
  ELSE
    wSQL = :wSQL || 'LEFT OUTER JOIN ' || :wTable || ' S ON(S.BDCODEMP = INSS.BDCODEMP AND S.BDCHAVE = INSS.BDCHAVE AND S.BDSESSAO = INSS.BDSESSAO) ';

  wSQL = :wSQL || 'LEFT OUTER JOIN ( ';
  wSQL = :wSQL || '    SELECT I.BDCODEMP, I.BDCHAVE, MAX(I.BDORDEM) BDORDEM, SUM(COALESCE(IIF(M.BDVALORNOTA > 0,CAST(I.BDVLRCONTAB/CAST(M.BDVALORNOTA AS NUMERIC(15,6)) * ' || WSOMARET ||
                  '    AS NUMERIC(15,2)),' || WSOMARET || '),0)) BDVLRRET ';

  wSQL = :wSQL || '    FROM ' || wTable || ' M ';
  wSQL = :wSQL || '    LEFT OUTER JOIN ' || wTableINSS || ' INSS ON (INSS.BDCODEMP = M.BDCODEMP AND INSS.BDCHAVE = M.BDCHAVE AND INSS.BDSESSAO = M.BDSESSAO) ';
  wSQL = :wSQL || '    LEFT OUTER JOIN ' || wTableItem || ' I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE AND I.BDSESSAO = M.BDSESSAO) ';
  wSQL = :wSQL || '    LEFT OUTER JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = I.BDCODNAT) ';
  wSQL = :wSQL || '    WHERE M.BDSESSAO = ' || :PRSESSAO || ' AND ';
  wSQL = :wSQL || '          N.BDCONTABILIZA = ''TRUE'' ';
  wSQL = :wSQL || '    GROUP BY I.BDCODEMP, I.BDCHAVE ';
  wSQL = :wSQL || ')IO ON (IO.BDCODEMP = I.BDCODEMP AND IO.BDCHAVE = I.BDCHAVE AND IO.BDORDEM = I.BDORDEM) ';

  wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO'||WANDFIELDREF||' AND C.BDCODITEMONLINE = ' || :wCodItemInss25 || ') ';
                  /*Saída olha data de emissão, ao fazer a contabilização de entrada/serviço tem que ser adaptado para olhar os outros campos de data*/
  wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = INSS.BDCODEMP AND IC.BDCODSIS = ' || :wEF || ') ';
  wSQL = :wSQL || 'WHERE INSS.BDSESSAO = ' || :PRSESSAO;
  wSQL = :wSQL || ' AND INSS.BDVLRAPOS25 > 0 AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
  wSQL = :wSQL || ' AND (S.BDRATEIARET = ''TRUE'' OR S.BDPRIMEIRAORDEM = I.BDORDEM) ';
  wSQL = :wSQL || ' AND ((IC.BDCODEMP IS NULL) OR (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||IIF((:PRTIPOLAN = 'ENT'), 'BDDATAENTRADAENT', 'BDDATAEMISSAO') || '))) ';
  wSQL = :wSQL || ' AND NOT EXISTS(';
  wSQL = :wSQL ||                'SELECT INCO.BDCODINCONSISTENCIA ';
  wSQL = :wSQL ||                'FROM ' || :wTableIncon || ' INCO ';
  wSQL = :wSQL ||                'WHERE INCO.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL ||                ' AND  INCO.BDCHAVE  = I.BDCHAVE ';
  wSQL = :wSQL ||                ' AND  INCO.BDSESSAO = I.BDSESSAO ';
  wSQL = :wSQL ||               ')';
  EXECUTE STATEMENT :wSQL;

  /*---------------------------------------------------------------------------RETENÇÃO DE INSS 25 ANOS-----------------------------------------------------------------------------------------------*/

  BDSQL = wSQL;

  SUSPEND;

END^

create or alter procedure SP_CRIA_CONTAB_RET_FUNRURAL (
    PRSESSAO integer,
    PRCODPLANOONLINE integer,
    PRENQFED integer,
    PRTIPOLAN varchar(5),
    PRFORMATRIBUTACAO integer = 0)
as
declare variable WORGAOPUBLICO varchar(5);
declare variable WTABLE varchar(50);
declare variable WTABLEITEM varchar(50);
declare variable WTABLERET varchar(50);
declare variable WTABLEINCON varchar(50);
declare variable WTABLEFUNRURAL varchar(32);
declare variable WSQL varchar(5000);
declare variable WCODITEMPIS integer;
declare variable WCODITEMCOF integer;
declare variable WCODITEMCS integer;
declare variable WCODITEMIR integer;
declare variable WCODITEMINSS integer;
declare variable WCODITEMISS integer;
declare variable WEF integer;
declare variable WCODITEMFUNRURAL integer;
declare variable WTABLERATEIO varchar(32);
declare variable WCAMPOINSS varchar(33);
declare variable WTABLEINSS varchar(31);
declare variable WTIPLAN integer;
declare variable WSOMARET varchar(200);
declare variable WCODITEMROYALTIES integer;
declare variable WTIPOINTCONTRETPCC integer;
declare variable WTIPOINTCONTRETIR integer;
declare variable WTIPOINTCONTRETIRTOM integer;
declare variable WFIELDDATA varchar(32);
declare variable WANDFIELDREF varchar(200);
declare variable WTIPOAPURACAORETIR integer;
BEGIN
  /*BDORD - Campo para ordernar a contabilização
    ******************Legenda*******************
    1 - Valor contábil com desconto 2 - desconto 3 - Impostos 4 - Retenções 5 - Diferença 6 - Outras CFOPS*/
  wTable         = ''; wTableItem     = ''; wTableRet      = '';     wTableIncon    = ''; wTableFunRural = ''; wTableINSS     = ''; wEF = 3; wTableRateio = '';
  wCampoINSS  = 'INSS.BDRETINSS';
  PRTIPOLAN    = UPPER(:PRTIPOLAN);
  wTipLan      = NULL;
  wCodItemRoyalties = 0;
  wfielddata  = 'BDDATAEMISSAO';
  wOrgaoPublico = 'FALSE';
  IF ((:PRTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE'))  THEN
    wOrgaoPublico = (SELECT bdvalor FROM TPARGER  WHERE bdcampo = 'bdIRRFOrgaoPublico');
  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTable      = 'TMP_VEF_EMP_TMOVSAI_TEMP';
      wTableItem  = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
      wTableRet   = 'TMP_VEF_EMP_TMOVSAIRET_TEMP';
      wTableIncon = 'VEF_INCON_TMOVSAI';
      wTableFunRural = 'TMP_VEF_TMOVSAIFUNRURAL_TEMP';
      wTableINSS     = 'TMP_VEF_EMP_TMOVSAIDED_TEMP';
      wCodItemPis      =  89;
      wCodItemCof      =  90;
      wCodItemCS       =  91;
      wCodItemIr       =  92;
      wCodItemInss     =  93;
      wCodItemIss      =  94;
      wCodItemFunRural = 246;
      --wTableRateio = 'TMP_VEF_EMP_TMOVRATSAI_TEMP'; #Não vamos fazer rateio até segunda ordem, o Elizeu quer fazer algumas configurações para validação e seleção das contas.#
    END
  ELSE
  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTable      = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItem  = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      wTableRet   = 'TMP_VEF_EMP_TMOVENTRET_TEMP';
      wTableIncon = 'VEF_INCON_TMOVENT';
      wTableFunRural = 'TMP_VEF_TMOVENTFUNRURAL_TEMP';
      wTableINSS       = 'TMP_VEF_EMP_TMOVENTDED_TEMP';
      wCodItemPis      =  82;
      wCodItemCof      =  83;
      wCodItemCS       =  84;
      wCodItemIr       = 163;
      wCodItemInss     = 164;
      wCodItemIss      = 165;
      wCodItemFunRural =  85;
      wCodItemRoyalties = 86;
      --wTableRateio = 'TMP_VEF_EMP_TMOVRATENT_TEMP'; #Não vamos fazer rateio até segunda ordem, o Elizeu quer fazer algumas configurações para validação e seleção das contas.#  
      wfielddata = 'BDDATAENTRADAENT';
    END
  ELSE
  IF ((:PRTIPOLAN = 'SERE') OR (:PRTIPOLAN = 'SERR')) THEN /*SERE - Serviço emitido | SERR - Serviço recebido*/
    BEGIN
      wTable      = 'TMP_VEF_EMP_TMOVSER_TEMP';
      wTableItem  = 'TMP_VEF_EMP_TMOVSERITENS_TEMP';
      wTableRet   = 'TMP_VEF_EMP_TMOVSERRET_TEMP';
      wTableIncon = 'VEF_INCON_TMOVSER';
      wTableINSS  = 'TMP_VEF_EMP_TMOVSERDED_TEMP';
      wTableRateio= 'TMP_VEF_EMP_TMOVRATSER_TEMP';
      IF (:PRTIPOLAN = 'SERE') THEN
        BEGIN
          wTipLan = 0;
          wCodItemPis  = 99;
          wCodItemCof  = 100;
          wCodItemCS   = 101;
          wCodItemInss = 98;
          wCodItemIss  = 102;
          wCodItemIR   = 97;
        END
      ELSE
        BEGIN
          wTipLan = 1;
          wCodItemPis  = 107;
          wCodItemCof  = 108;
          wCodItemCS   = 109;
          wCodItemInss = 106;
          wCodItemIss  = 110;
          wCodItemIR   = 105;
        END
    END
  ELSE
  IF (:PRTIPOLAN = 'REDZ') THEN
    BEGIN
      /*Redução Z tem que agrupar e montar os registros para contabilizar,
        então como muda muito as query's foi feito em uma sp separada*/
      EXECUTE PROCEDURE SP_CRIA_PRE_CONTABILIZACAO_REDZ(:PRSESSAO, :PRCODPLANOONLINE, :PRENQFED, :PRFORMATRIBUTACAO);
      EXIT;
    END
  ELSE
    EXIT;
  WANDFIELDREF = ' AND C.BDREFERENCIA = EXTRACT(YEAR FROM MOV.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM MOV.'||WFIELDDATA||') ';
  /* Alt.: #141167 - Deve contabilizar igual nos lançamentos manuais, se o parâmetro do "Contabilização da retenção (notas a prazo)" estiver como
   "Regime de caixa", não deve considerar os valores das retenções dos impostos, igual faz na "TCONF_CONTAS_ONLINEMGR.SetContabilizacaoPorRegime" */
  SELECT COALESCE(o.bdREGCONTRETPCC, 0),  -- PIS/Cofins/CSLL
         COALESCE(o.bdREGCONTRETIR, 0),   -- IR Emitido
         COALESCE(o.bdREGCONTRETIRTOM, 0) -- IR Recebido
  FROM TPLANO_CONF_ONLINE O
  WHERE O.BDCODPLANOONLINE = :PRCODPLANOONLINE
  INTO :wTIPOINTCONTRETPCC, :wTIPOINTCONTRETIR, :wTIPOINTCONTRETIRTOM;
   IF ((:PRTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE') OR (:PRTIPOLAN = 'REDZ')) THEN
   wTipoApuracaoRetIR = :wTipoIntContRetIR;
 ELSE IF ((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
   wTipoApuracaoRetIR = :wTipoIntContRetIRTom;
  WSOMARET = '';
  IF (:wTableFunRural <> '') THEN
    BEGIN                               
      /*------------------------------------------------------ FunRural -----------------------------------------------------------*/
      IF (:PRTIPOLAN = 'ENT') THEN
        WSOMARET = '(COALESCE(fr.bdVLRFUNRURAL, 0) + COALESCE(fr.bdVLRGILRAT, 0) + COALESCE(fr.bdVLRFPAS, 0))';
      ELSE
      IF (:PRTIPOLAN = 'SAI') THEN  
        WSOMARET = '(COALESCE(fr.bdVLRFUNRURAL, 0) + COALESCE(fr.bdVLRGILRAT, 0) + COALESCE(fr.bdVLRSENAR, 0))';
      wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdCODHIST, bdCODTPHI, bdord) ';
      wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, ';
      IF (:PRTIPOLAN = 'ENT') THEN
        wSQL = :wSQL ||        'NULL BDCONTADEBPROV, C.BDCONTACREDPROV, ';
      ELSE
      IF (:PRTIPOLAN = 'SAI') THEN  -- Alt.: #131080 - Nas saidas vai buscar a contabilização da "Conta FunRural PJ", quando tiver essa conta informada vai buscar apenas ela e não a retencao do Funrural...
        wSQL = :wSQL ||        'C.BDCONTADEBPROV, IIF(c.bdCODITEMONLINE = 301, c.BDCONTACREDPROV, NULL) AS BDCONTACREDPROV, ';
      wSQL = :wSQL ||        'I.BDCOMPHIST_VLRCONTAB, MOV.'|| wfielddata ||',  ';
      wSQL = :wSQL ||        'Coalesce(IIF(MOV.BDVALORNOTA > 0 and MOV.BDRATEIARET = ''TRUE'',Cast(I.BDVLRCONTAB/CAST(MOV.BDVALORNOTA AS NUMERIC(15,6))*'||WSOMARET||' AS NUMERIC(15,2)) + Coalesce('||WSOMARET||' - IO.BDVLRRET,0),'||WSOMARET||'),0) as BDVALOR,';
      wSQL = :wSQL ||        ' 100 BDTIPOLAN, mov.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.bdCODHIST, C.bdCODTPHI, 4 BDORD ';
      wSQL = :wSQL || 'FROM '||:wTableFunRural||' fr ';
      wSQL = :wSQL || 'LEFT OUTER JOIN ( ';
      wSQL = :wSQL ||                   'SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO, I.BDORDEM, I.BDEDITCHAVE, I.BDCHAVE_VSUC, I.BDCOMPHIST_VLRCONTAB, I.BDVLRCONTAB ';
      wSQL = :wSQL ||                   'FROM '||:wTableItem||' I ';
      IF (wTableRateio <> '') THEN
        wSQL = :wSQL ||       'left outer join '||wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) '; -- Rateio vão fazer contabilização própria e não aqui...
      wSQL = :wSQL ||                   'WHERE I.BDSESSAO = '||:PRSESSAO;
      IF (wTableRateio <> '') THEN
        wSQL = :wSQL ||       ' and rat.bdCODEMP IS NULL '; -- Somente quando não tiver rateio no lançamento..
      wSQL = :wSQL ||                   ') I ON(I.BDCODEMP = fr.BDCODEMP AND I.BDCHAVE = fr.BDCHAVE AND I.BDSESSAO = I.BDSESSAO) ';
      wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTable||' mov ON(mov.BDCODEMP = fr.BDCODEMP AND mov.BDCHAVE = fr.BDCHAVE AND mov.BDSESSAO = fr.BDSESSAO) ';
      wSQL = :wSQL || 'left outer join ( ';
      wSQL = :wSQL || '    SELECT I.BDCODEMP, I.BDCHAVE, max(I.BDORDEM) BDORDEM, SUM(Coalesce(IIF(M.BDVALORNOTA > 0,Cast(I.BDVLRCONTAB/CAST(M.BDVALORNOTA AS NUMERIC(15,6))*'||WSOMARET||' AS NUMERIC(15,2)),'||WSOMARET||'),0)) BDVLRRET ';
      wSQL = :wSQL || '    FROM '||wTable||' M ';
      wSQL = :wSQL || '    LEFT OUTER JOIN '||wTableFunRural||' fr ON (fr.BDCODEMP = M.BDCODEMP AND fr.BDCHAVE = M.BDCHAVE AND fr.BDSESSAO = M.BDSESSAO) ';
      wSQL = :wSQL || '    LEFT OUTER JOIN '||wTableItem||' I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE AND I.BDSESSAO = M.BDSESSAO) ';
      wSQL = :wSQL || '    LEFT OUTER JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = I.BDCODNAT) ';
      wSQL = :wSQL || '    WHERE M.BDSESSAO = ' || :PRSESSAO || ' AND ';
      wSQL = :wSQL || '          N.BDCONTABILIZA = ''TRUE'' ';
      wSQL = :wSQL || '    GROUP BY I.BDCODEMP, I.BDCHAVE ';
      wSQL = :wSQL || ')IO ON (IO.BDCODEMP = I.BDCODEMP AND IO.BDCHAVE = I.BDCHAVE AND IO.BDORDEM = I.BDORDEM) ';
      IF (:PRTIPOLAN = 'SAI') THEN -- Alt.: #131080 - Nas saidas vai buscar a contabilização da "Conta FunRural PJ", quando tiver essa conta informada vai buscar apenas ela e não a retencao do Funrural...
        wSQL = :wSQL || 'join TCONTAS_ONLINE_TEMP C on (C.BDSESSAO = I.BDSESSAO and C.BDCODITEMONLINE IN ('||wCodItemFunRural||',301)'||WANDFIELDREF||') ';
      ELSE
      wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO and c.bdCODITEMONLINE = '||wCodItemFunRural||''||WANDFIELDREF||') ';
                      /*Saída olha data de emissão, ao fazer a contabilização de entrada/serviço tem que ser adaptado para olhar os outros campos de data*/
      wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = fr.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
      wSQL = :wSQL || 'WHERE fr.BDSESSAO = '||:PRSESSAO;
      wSQL = :wSQL ||  ' AND mov.BDCODSITNF NOT IN (2, 3, 4, 5) ';   
      wSQL = :wSQL || ' and (mov.BDRATEIARET = ''TRUE'' OR MOV.BDPRIMEIRAORDEM = I.BDORDEM) ';
      wSQL = :wSQL ||  ' AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= mov.'||wfielddata||'))) ';
      IF (:PRTIPOLAN = 'SAI') THEN
        wSQL = :wSQL ||  ' AND ((fr.bdVLRFUNRURAL > 0) OR (fr.bdVLRGILRAT > 0) OR (fr.bdVLRSENAR > 0)) ';
      ELSE                                                                                                                            
        wSQL = :wSQL ||  ' AND ((fr.bdVLRFUNRURAL > 0) OR (fr.bdVLRGILRAT > 0) OR (fr.BDVLRFPAS > 0)) ';
      wSQL = :wSQL ||  'AND NOT EXISTS(';
      wSQL = :wSQL ||                  'SELECT INCO.BDCODINCONSISTENCIA ';
      wSQL = :wSQL ||                  'FROM '||:wTableIncon||' INCO ';
      wSQL = :wSQL ||                  'WHERE INCO.BDCODEMP = I.BDCODEMP ';
      wSQL = :wSQL ||                    'AND INCO.BDCHAVE = I.BDCHAVE ';
      wSQL = :wSQL ||                    'AND INCO.BDSESSAO = I.BDSESSAO ';
      wSQL = :wSQL ||                 ')';
      EXECUTE STATEMENT :wSQL;
      IF (wCodItemRoyalties > 0) THEN -- Alt.: #98173 - Não estava aplicando os valores de Royalties nos Plano de trocas, Troca global e Recontabilizacao
        BEGIN
          /*------------------------------------------------------ Royalties -----------------------------------------------------------*/
          WSOMARET = '(COALESCE(fr.bdROYALTIES, 0))';
          wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdCODHIST, bdCODTPHI, bdord) ';
          wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, ';
          IF (:PRTIPOLAN = 'ENT') THEN
            wSQL = :wSQL ||        'NULL BDCONTADEBPROV, C.BDCONTACREDPROV, ';
          ELSE
          IF (:PRTIPOLAN = 'SAI') THEN
            wSQL = :wSQL ||        'C.BDCONTADEBPROV, NULL BDCONTACREDPROV, ';
          wSQL = :wSQL ||        'I.BDCOMPHIST_VLRCONTAB, MOV.' || wfielddata || ',  ';
          wSQL = :wSQL ||        'Coalesce(IIF(MOV.BDVALORNOTA > 0 and MOV.BDRATEIARET = ''TRUE'',Cast(I.BDVLRCONTAB/CAST(MOV.BDVALORNOTA AS NUMERIC(15,6))*'||WSOMARET||' AS NUMERIC(15,2))  + Coalesce('||WSOMARET||' - IO.BDVLRRET,0),'||WSOMARET||'),0) AS bdVALOR,';
          wSQL = :wSQL ||        ' 100 BDTIPOLAN, mov.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.bdCODHIST, C.bdCODTPHI, 4 BDORD ';
          wSQL = :wSQL || 'FROM '||:wTableFunRural||' fr ';
          wSQL = :wSQL || 'LEFT OUTER JOIN ( ';
          wSQL = :wSQL ||                   'SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO, I.BDORDEM, I.BDEDITCHAVE, I.BDCHAVE_VSUC, I.BDCOMPHIST_VLRCONTAB, I.BDVLRCONTAB ';
          wSQL = :wSQL ||                   'FROM '||:wTableItem||' I ';
          IF (wTableRateio <> '') THEN
            wSQL = :wSQL ||       'left outer join '||wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) '; -- Rateio vão fazer contabilização própria e não aqui...
          wSQL = :wSQL ||                   'WHERE I.BDSESSAO = '||:PRSESSAO;
          IF (wTableRateio <> '') THEN
            wSQL = :wSQL ||       ' and rat.bdCODEMP IS NULL '; -- Somente quando não tiver rateio no lançamento..
          wSQL = :wSQL ||                   ') I ON(I.BDCODEMP = fr.BDCODEMP AND I.BDCHAVE = fr.BDCHAVE AND I.BDSESSAO = I.BDSESSAO) ';
          wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTable||' mov ON(mov.BDCODEMP = fr.BDCODEMP AND mov.BDCHAVE = fr.BDCHAVE AND mov.BDSESSAO = fr.BDSESSAO) ';
          wSQL = :wSQL || 'left outer join ( ';
          wSQL = :wSQL || '    SELECT I.BDCODEMP, I.BDCHAVE, max(I.BDORDEM) BDORDEM, SUM(Coalesce(IIF(M.BDVALORNOTA > 0,Cast(I.BDVLRCONTAB/CAST(M.BDVALORNOTA AS NUMERIC(15,6))*'||WSOMARET||' AS NUMERIC(15,2)),'||WSOMARET||'),0)) BDVLRRET ';
          wSQL = :wSQL || '    FROM '||wTable||' M ';
          wSQL = :wSQL || '    LEFT OUTER JOIN '||wTableFunRural||' fr ON (fr.BDCODEMP = M.BDCODEMP AND fr.BDCHAVE = M.BDCHAVE AND fr.BDSESSAO = M.BDSESSAO) ';
          wSQL = :wSQL || '    LEFT OUTER JOIN '||wTableItem||' I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE AND I.BDSESSAO = M.BDSESSAO) ';
          wSQL = :wSQL || '    LEFT OUTER JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = I.BDCODNAT) ';
          wSQL = :wSQL || '    WHERE M.BDSESSAO = ' || :PRSESSAO || ' AND ';
          wSQL = :wSQL || '          N.BDCONTABILIZA = ''TRUE'' ';
          wSQL = :wSQL || '    GROUP BY I.BDCODEMP, I.BDCHAVE ';
          wSQL = :wSQL || ')IO ON (IO.BDCODEMP = I.BDCODEMP AND IO.BDCHAVE = I.BDCHAVE AND IO.BDORDEM = I.BDORDEM) ';
          wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO and c.bdCODITEMONLINE = '||wCodItemRoyalties||WANDFIELDREF||') ';
                         /*Saída olha data de emissão, ao fazer a contabilização de entrada/serviço tem que ser adaptado para olhar os outros campos de data*/
          wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = fr.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
          wSQL = :wSQL || 'WHERE fr.BDSESSAO = '||:PRSESSAO;
          wSQL = :wSQL ||  ' AND mov.BDCODSITNF NOT IN (2, 3, 4, 5) ';  
           wSQL = :wSQL || ' and (mov.BDRATEIARET = ''TRUE'' OR MOV.BDPRIMEIRAORDEM = I.BDORDEM) ';
          wSQL = :wSQL ||  ' AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= mov.'||wfielddata||'))) ';
          IF (:PRTIPOLAN = 'SAI') THEN
            wSQL = :wSQL ||  ' AND (fr.bdROYALTIES > 0) ';
          ELSE                                                                                                                            
            wSQL = :wSQL ||  ' AND (fr.bdROYALTIES > 0) ';
          wSQL = :wSQL ||  'AND NOT EXISTS(';
          wSQL = :wSQL ||                  'SELECT INCO.BDCODINCONSISTENCIA ';
          wSQL = :wSQL ||                  'FROM '||:wTableIncon||' INCO ';
          wSQL = :wSQL ||                  'WHERE INCO.BDCODEMP = I.BDCODEMP ';
          wSQL = :wSQL ||                    'AND INCO.BDCHAVE = I.BDCHAVE ';
          wSQL = :wSQL ||                    'AND INCO.BDSESSAO = I.BDSESSAO ';
          wSQL = :wSQL ||                 ')';
          EXECUTE STATEMENT :wSQL;
        END
    END
END^

create or alter procedure SP_CRIA_PRE_CONTABILIZACAO_RET (
    PRSESSAO integer,
    PRCODPLANOONLINE integer,
    PRENQFED integer,
    PRTIPOLAN varchar(5),
    PRFORMATRIBUTACAO integer = 0)
as
declare variable WORGAOPUBLICO varchar(5);
declare variable WTABLE varchar(50);
declare variable WTABLEITEM varchar(50);
declare variable WTABLERET varchar(50);
declare variable WTABLEINCON varchar(50);
declare variable WTABLEFUNRURAL varchar(32);
declare variable WSQL varchar(5000);
declare variable WCODITEMPIS integer;
declare variable WCODITEMCOF integer;
declare variable WCODITEMCS integer;
declare variable WCODITEMIR integer;
declare variable WCODITEMINSS integer;
declare variable WCODITEMISS integer;
declare variable WEF integer;
declare variable WCODITEMFUNRURAL integer;
declare variable WTABLERATEIO varchar(32);
declare variable WCAMPOINSS varchar(33);
declare variable WTABLEINSS varchar(31);
declare variable WTIPLAN integer;
declare variable WSOMARET varchar(200);
declare variable WCODITEMROYALTIES integer;
declare variable WTIPOINTCONTRETPCC integer;
declare variable WTIPOINTCONTRETIR integer;
declare variable WTIPOINTCONTRETIRTOM integer;
declare variable WFIELDDATA varchar(32);
declare variable WANDFIELDREF varchar(200);
declare variable WTIPOAPURACAORETIR integer;
BEGIN
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_RET','1');
  /*BDORD - Campo para ordernar a contabilização
    ******************Legenda*******************
    1 - Valor contábil com desconto 2 - desconto 3 - Impostos 4 - Retenções 5 - Diferença 6 - Outras CFOPS*/
  wTable         = ''; wTableItem     = ''; wTableRet      = '';     wTableIncon    = ''; wTableFunRural = ''; wTableINSS     = ''; wEF = 3; wTableRateio = '';
  wCampoINSS  = 'INSS.BDRETINSS';
  PRTIPOLAN    = UPPER(:PRTIPOLAN);
  wTipLan      = NULL;
  wCodItemRoyalties = 0;
  wfielddata  = 'BDDATAEMISSAO';
  wOrgaoPublico = 'FALSE';
  IF ((:PRTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE'))  THEN
    wOrgaoPublico = (SELECT bdvalor FROM TPARGER  WHERE bdcampo = 'bdIRRFOrgaoPublico');
  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTable      = 'TMP_VEF_EMP_TMOVSAI_TEMP';
      wTableItem  = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
      wTableRet   = 'TMP_VEF_EMP_TMOVSAIRET_TEMP';
      wTableIncon = 'VEF_INCON_TMOVSAI';
      wTableFunRural = 'TMP_VEF_TMOVSAIFUNRURAL_TEMP';
      wTableINSS     = 'TMP_VEF_EMP_TMOVSAIDED_TEMP';
      wCodItemPis      =  89;
      wCodItemCof      =  90;
      wCodItemCS       =  91;
      wCodItemIr       =  92;
      wCodItemInss     =  93;
      wCodItemIss      =  94;
      wCodItemFunRural = 246;
      --wTableRateio = 'TMP_VEF_EMP_TMOVRATSAI_TEMP'; #Não vamos fazer rateio até segunda ordem, o Elizeu quer fazer algumas configurações para validação e seleção das contas.#
    END
  ELSE
  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTable      = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItem  = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      wTableRet   = 'TMP_VEF_EMP_TMOVENTRET_TEMP';
      wTableIncon = 'VEF_INCON_TMOVENT';
      wTableFunRural = 'TMP_VEF_TMOVENTFUNRURAL_TEMP';
      wTableINSS       = 'TMP_VEF_EMP_TMOVENTDED_TEMP';
      wCodItemPis      =  82;
      wCodItemCof      =  83;
      wCodItemCS       =  84;
      wCodItemIr       = 163;
      wCodItemInss     = 164;
      wCodItemIss      = 165;
      wCodItemFunRural =  85;
      wCodItemRoyalties = 86;
      --wTableRateio = 'TMP_VEF_EMP_TMOVRATENT_TEMP'; #Não vamos fazer rateio até segunda ordem, o Elizeu quer fazer algumas configurações para validação e seleção das contas.#  
      wfielddata = 'BDDATAENTRADAENT';
    END
  ELSE
  IF ((:PRTIPOLAN = 'SERE') OR (:PRTIPOLAN = 'SERR')) THEN /*SERE - Serviço emitido | SERR - Serviço recebido*/
    BEGIN
      wTable      = 'TMP_VEF_EMP_TMOVSER_TEMP';
      wTableItem  = 'TMP_VEF_EMP_TMOVSERITENS_TEMP';
      wTableRet   = 'TMP_VEF_EMP_TMOVSERRET_TEMP';
      wTableIncon = 'VEF_INCON_TMOVSER';
      wTableINSS  = 'TMP_VEF_EMP_TMOVSERDED_TEMP';
      wTableRateio= 'TMP_VEF_EMP_TMOVRATSER_TEMP';
      IF (:PRTIPOLAN = 'SERE') THEN
        BEGIN
          wTipLan = 0;
          wCodItemPis  = 99;
          wCodItemCof  = 100;
          wCodItemCS   = 101;
          wCodItemInss = 98;
          wCodItemIss  = 102;
          wCodItemIR   = 97;
        END
      ELSE
        BEGIN
          wTipLan = 1;
          wCodItemPis  = 107;
          wCodItemCof  = 108;
          wCodItemCS   = 109;
          wCodItemInss = 106;
          wCodItemIss  = 110;
          wCodItemIR   = 105;
        END
    END
  ELSE
  IF (:PRTIPOLAN = 'REDZ') THEN
    BEGIN
      /*Redução Z tem que agrupar e montar os registros para contabilizar,
        então como muda muito as query's foi feito em uma sp separada*/
      EXECUTE PROCEDURE SP_CRIA_PRE_CONTABILIZACAO_REDZ(:PRSESSAO, :PRCODPLANOONLINE, :PRENQFED);
      EXIT;
    END
  ELSE
    EXIT;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_RET','2');
  WANDFIELDREF = ' AND C.BDREFERENCIA = EXTRACT(YEAR FROM MOV.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM MOV.'||WFIELDDATA||') ';
  /* Alt.: #141167 - Deve contabilizar igual nos lançamentos manuais, se o parâmetro do "Contabilização da retenção (notas a prazo)" estiver como
   "Regime de caixa", não deve considerar os valores das retenções dos impostos, igual faz na "TCONF_CONTAS_ONLINEMGR.SetContabilizacaoPorRegime" */
  SELECT COALESCE(o.bdREGCONTRETPCC, 0),  -- PIS/Cofins/CSLL
         COALESCE(o.bdREGCONTRETIR, 0),   -- IR Emitido
         COALESCE(o.bdREGCONTRETIRTOM, 0) -- IR Recebido
  FROM TPLANO_CONF_ONLINE O
  WHERE O.BDCODPLANOONLINE = :PRCODPLANOONLINE
  INTO :wTIPOINTCONTRETPCC, :wTIPOINTCONTRETIR, :wTIPOINTCONTRETIRTOM;
  IF ((:PRTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE') OR (:PRTIPOLAN = 'REDZ')) THEN
    wTipoApuracaoRetIR = :wTipoIntContRetIR;
  ELSE IF ((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
    wTipoApuracaoRetIR = :wTipoIntContRetIRTom;
  WSOMARET = '';

  /* Retenções FunRural */
  EXECUTE PROCEDURE SP_CRIA_CONTAB_RET_FUNRURAL (:prSESSAO, :prCODPLANOONLINE, :prENQFED, :prTIPOLAN, :PRFORMATRIBUTACAO);
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_RET','3');
  /*------------------------------------------------------Retenções-----------------------------------------------------------*/
  WANDFIELDREF = ' AND C.BDREFERENCIA = EXTRACT(YEAR FROM S.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM S.'||WFIELDDATA||') ';
  IF ((:wTIPOINTCONTRETPCC = 0) OR -- Alt.: #141167 - Apenas se "PIS/Cofins/CSLL" for "Regime de compet??ncia"...
      (:wTIPOINTCONTRETPCC = 1)) THEN
    BEGIN
      WSOMARET = '(R.BDVLRPIS)';
      /*Retenção de pis*/
      wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdCODHIST, bdCODTPHI, bdord,BDCODEMPSCP) ';
      wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, ';
      IF ((:prTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
        wSQL = :wSQL || 'NULL BDCONTADEBPROV, c.BDCONTACREDPROV, ';
      ELSE
      IF ((:prTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE')) THEN
        wSQL = :wSQL || 'C.BDCONTADEBPROV, NULL BDCONTACREDPROV, ';
      wSQL = :wSQL ||        'IIF(COALESCE(I.BDCOMPHIST_VLRPISRET,'''') <> '''', COALESCE(I.BDCOMPHIST_VLRPISRET,''''), COALESCE(I.BDCOMPHIST_VLRCONTAB,'''')), ';
      wSQL = :wSQL ||        'S.'||wfielddata||', Coalesce(IIF(S.BDVALORNOTA > 0 and S.BDRATEIARET = ''TRUE'',Cast(I.BDVLRCONTAB/CAST(S.BDVALORNOTA AS NUMERIC(15,6))*'||WSOMARET||' AS NUMERIC(15,2)) + Coalesce('||WSOMARET||' - ';
      wSQL = :wSQL ||        'IIF((IO.BDCODEMP IS NOT NULL AND S.BDVALORNOTA > 0), CAST(I.BDVLRCONTAB / CAST(S.BDVALORNOTA AS NUMERIC(15,6)) * '||WSOMARET||' AS NUMERIC(15,2)),0)';
      wSQL = :wSQL ||        ',0),'||WSOMARET||'),0) BDVLRPIS, ';

      wSQL = :wSQL ||        '100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.bdCODHIST, C.bdCODTPHI, 4 BDORD';
      wSQL = :wSQL ||        ',(SELECT FIRST 1 scp.bdCODEMPSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = i.bdCODEMP AND scp.bdCODSCP = i.bdCODSCP AND ';
      wSQL = :wSQL ||         '((scp.bdDATAINICIAL <= s.bdDATAEMISSAO AND scp.bdDATAFINAL IS NULL) OR (s.bdDATAEMISSAO BETWEEN scp.bdDATAINICIAL AND scp.bdDATAFINAL))) ';
      wSQL = :wSQL || 'FROM '||:wTableRet||' R ';
      wSQL = :wSQL || 'LEFT OUTER JOIN (';
      wSQL = :wSQL ||                  'SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO, I.BDORDEM, I.BDEDITCHAVE, I.BDCHAVE_VSUC, I.BDCOMPHIST_VLRPISRET, I.BDCOMPHIST_VLRCONTAB, I.BDVLRCONTAB, I.BDCODSCP ';
      wSQL = :wSQL ||                  'FROM '||:wTableItem||' I ';
      IF (wTableRateio <> '') THEN
        wSQL = :wSQL ||       'left outer join '||wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) '; -- Rateio vão fazer contabilização própria e não aqui...
      wSQL = :wSQL ||                  'WHERE I.BDSESSAO = '||:PRSESSAO;
      IF (wTableRateio <> '') THEN
        wSQL = :wSQL ||       ' and rat.bdCODEMP IS NULL '; -- Somente quando não tiver rateio no lançamento..
      wSQL = :wSQL ||                 ') I ON(I.BDCODEMP = R.BDCODEMP AND I.BDCHAVE = R.BDCHAVE AND I.BDSESSAO = R.BDSESSAO) ';
      IF (:wTipLan IS NOT NULL) THEN
        wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE AND S.BDSESSAO = R.BDSESSAO AND S.BDTIPLAN = '||:wTipLan||') ';
      ELSE
        wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTable||' S ON(S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE AND S.BDSESSAO = R.BDSESSAO) ';
      wSQL = :wSQL || 'LEFT OUTER JOIN(SELECT I.BDCODEMP, I.BDCHAVE, MAX(I.BDORDEM) BDORDEM ';
      wSQL = :wSQL ||                 'FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I ';
      wSQL = :wSQL ||                 'LEFT OUTER JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = I.BDCODNAT) ';
      wSQL = :wSQL ||                 'WHERE I.BDSESSAO = '||:PRSESSAO||' ';
      wSQL = :wSQL ||                   'AND N.BDCONTABILIZA = ''TRUE'' ';
      wSQL = :wSQL ||                 'GROUP BY I.BDCODEMP, I.BDCHAVE) IO ON (IO.BDCODEMP = I.BDCODEMP AND IO.BDCHAVE = I.BDCHAVE AND IO.BDORDEM = I.BDORDEM) ';
      wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND COALESCE(C.BDCODREC,0) = COALESCE(R.BDCODRECPIS,0) AND C.BDCODITEMONLINE = '||:wCodItemPis||WANDFIELDREF||') ';
                      /*Saída olha data de emissão, ao fazer a contabilização de entrada/serviço tem que ser adaptado para olhar os outros campos de data*/
      wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = R.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
      wSQL = :wSQL || 'WHERE R.BDSESSAO = '||:PRSESSAO;
      IF (:wTIPOINTCONTRETPCC = 1) THEN
        wSQL = :wSQL || ' and S.BDCONDPGTO <> 1 '; -- Alt.: #224292 - Apenas quando a nota não for "a prazo"...
      wSQL = :wSQL || ' and R.BDVLRPIS > 0 AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
      wSQL = :wSQL || ' and (S.BDRATEIARET = ''TRUE'' OR S.BDPRIMEIRAORDEM = I.BDORDEM) ';
      wSQL = :wSQL ||' AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';
      wSQL = :wSQL || 'AND NOT EXISTS(';
      wSQL = :wSQL ||                'SELECT INCO.BDCODINCONSISTENCIA ';
      wSQL = :wSQL ||                'FROM '||:wTableIncon||' INCO ';
      wSQL = :wSQL ||                'WHERE INCO.BDCODEMP = I.BDCODEMP ';
      wSQL = :wSQL ||                'AND INCO.BDCHAVE = I.BDCHAVE ';
      wSQL = :wSQL ||                'AND INCO.BDSESSAO = I.BDSESSAO ';
      wSQL = :wSQL ||               ')';
      EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_RET','4');
      /*Retenção de cofins*/
      WSOMARET = '(R.BDVLRCOFINS)';
      wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdCODHIST, bdCODTPHI, bdord, BDCODEMPSCP) ';
      wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, ';
      IF ((:prTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
        wSQL = :wSQL || 'NULL BDCONTADEBPROV, C.BDCONTACREDPROV, ';
      ELSE
      IF ((:prTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE')) THEN
        wSQL = :wSQL || 'C.BDCONTADEBPROV, NULL BDCONTACREDPROV, ';
      wSQL = :wSQL ||        'IIF(COALESCE(I.BDCOMPHIST_VLRCOFRET,'''') <> '''', COALESCE(I.BDCOMPHIST_VLRCOFRET,''''), COALESCE(I.BDCOMPHIST_VLRCONTAB,'''')), ';
      wSQL = :wSQL ||        'S.'||wfielddata||', Coalesce(IIF(S.BDVALORNOTA > 0 and S.BDRATEIARET = ''TRUE'',Cast(I.BDVLRCONTAB/CAST(S.BDVALORNOTA AS NUMERIC(15,6))*'||WSOMARET||' AS NUMERIC(15,2)) + Coalesce('||WSOMARET||' - ';
      wSQL = :wSQL ||        'IIF((IO.BDCODEMP IS NOT NULL AND S.BDVALORNOTA > 0), CAST(I.BDVLRCONTAB / CAST(S.BDVALORNOTA AS NUMERIC(15,6)) * '||WSOMARET||' AS NUMERIC(15,2)),0)';
      wSQL = :wSQL ||        ',0),'||WSOMARET||'),0) BDVLRCOFINS, ';
      wSQL = :wSQL ||        ' 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.bdCODHIST, C.bdCODTPHI, 4 BDORD';
      wSQL = :wSQL ||        ',(SELECT FIRST 1 scp.bdCODEMPSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = i.bdCODEMP AND scp.bdCODSCP = i.bdCODSCP AND ';
      wSQL = :wSQL ||         '((scp.bdDATAINICIAL <= s.bdDATAEMISSAO AND scp.bdDATAFINAL IS NULL) OR (s.bdDATAEMISSAO BETWEEN scp.bdDATAINICIAL AND scp.bdDATAFINAL))) ';
      wSQL = :wSQL || 'FROM '||:wTableRet||' R ';
      wSQL = :wSQL || 'LEFT OUTER JOIN (';      
      wSQL = :wSQL ||                  'SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO, I.BDORDEM, I.BDEDITCHAVE, I.BDCHAVE_VSUC, I.BDCOMPHIST_VLRCOFRET, BDCOMPHIST_VLRCONTAB, I.BDVLRCONTAB, I.BDCODSCP ';
      wSQL = :wSQL ||                  'FROM '||:wTableItem||' I ';
      IF (wTableRateio <> '') THEN
        wSQL = :wSQL ||       'left outer join '||wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) '; -- Rateio vão fazer contabilização própria e não aqui
      wSQL = :wSQL ||                  'WHERE I.BDSESSAO = '||:PRSESSAO;
      IF (wTableRateio <> '') THEN
        wSQL = :wSQL ||       ' and rat.bdCODEMP IS NULL '; -- Somente quando não tiver rateio no lançamento
      wSQL = :wSQL ||                 ') I ON(I.BDCODEMP = R.BDCODEMP AND I.BDCHAVE = R.BDCHAVE AND I.BDSESSAO = R.BDSESSAO) ';
      IF (:wTipLan IS NOT NULL) THEN
        wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE AND S.BDSESSAO = R.BDSESSAO AND S.BDTIPLAN = '||:wTipLan||') ';
      ELSE
        wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTable||' S ON(S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE AND S.BDSESSAO = R.BDSESSAO) ';
      wSQL = :wSQL || 'LEFT OUTER JOIN(SELECT I.BDCODEMP, I.BDCHAVE, MAX(I.BDORDEM) BDORDEM ';
      wSQL = :wSQL ||                 'FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I ';
      wSQL = :wSQL ||                 'LEFT OUTER JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = I.BDCODNAT) ';
      wSQL = :wSQL ||                 'WHERE I.BDSESSAO = '||:PRSESSAO||' ';
      wSQL = :wSQL ||                   'AND N.BDCONTABILIZA = ''TRUE'' ';
      wSQL = :wSQL ||                 'GROUP BY I.BDCODEMP, I.BDCHAVE) IO ON (IO.BDCODEMP = I.BDCODEMP AND IO.BDCHAVE = I.BDCHAVE AND IO.BDORDEM = I.BDORDEM) ';
      wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND COALESCE(C.BDCODREC,0) = COALESCE(R.BDCODRECCOFINS,0) AND C.BDCODITEMONLINE = '||:wCodItemCof||WANDFIELDREF||') ';
                      /*Saída olha data de emissão, ao fazer a contabilização de entrada/serviço tem que ser adaptado para olhar os outros campos de data*/
      wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = R.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';  
      wSQL = :wSQL || 'WHERE R.BDSESSAO = '||:PRSESSAO;
      IF (:wTIPOINTCONTRETPCC = 1) THEN
        wSQL = :wSQL || ' and S.BDCONDPGTO <> 1 '; -- Alt.: #224292 - Apenas quando a nota não for "a prazo"...
      wSQL = :wSQL || ' and R.BDVLRCOFINS > 0  AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
      wSQL = :wSQL || ' and (S.BDRATEIARET = ''TRUE'' OR S.BDPRIMEIRAORDEM = I.BDORDEM) ';
      wSQL = :wSQL ||' AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';
      wSQL = :wSQL || 'AND NOT EXISTS(';
      wSQL = :wSQL ||                'SELECT INCO.BDCODINCONSISTENCIA ';
      wSQL = :wSQL ||                'FROM '||:wTableIncon||' INCO ';
      wSQL = :wSQL ||                'WHERE INCO.BDCODEMP = I.BDCODEMP ';
      wSQL = :wSQL ||                'AND INCO.BDCHAVE = I.BDCHAVE ';
      wSQL = :wSQL ||                'AND INCO.BDSESSAO = I.BDSESSAO ';
      wSQL = :wSQL ||               ')';
      EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_RET','5');
      /*Retenção de contribuição social*/
      WSOMARET = '(R.BDVLRCSOCIAL)';
      wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdCODHIST, bdCODTPHI, bdord, BDCODEMPSCP) ';
      wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, ';
      IF ((:prTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
        wSQL = :wSQL || 'NULL BDCONTADEBPROV, C.BDCONTACREDPROV, ';
      ELSE
      IF ((:prTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE')) THEN
        wSQL = :wSQL || 'C.BDCONTADEBPROV, NULL BDCONTACREDPROV, ';
      wSQL = :wSQL ||        'IIF(COALESCE(I.BDCOMPHIST_VLRCSRET,'''') <> '''', COALESCE(I.BDCOMPHIST_VLRCSRET,''''), COALESCE(I.BDCOMPHIST_VLRCONTAB,'''')), ';
      wSQL = :wSQL ||        'S.'||wfielddata||', Coalesce(IIF(S.BDVALORNOTA > 0 and S.BDRATEIARET = ''TRUE'',Cast(I.BDVLRCONTAB/CAST(S.BDVALORNOTA AS NUMERIC(15,6))*'||WSOMARET||' AS NUMERIC(15,2)) + Coalesce('||WSOMARET||' - ';
      wSQL = :wSQL ||        'IIF((IO.BDCODEMP IS NOT NULL AND S.BDVALORNOTA > 0), CAST(I.BDVLRCONTAB / CAST(S.BDVALORNOTA AS NUMERIC(15,6)) * '||WSOMARET||' AS NUMERIC(15,2)),0)';
      wSQL = :wSQL ||        ',0),'||WSOMARET||'),0) BDVLRCSOCIAL, ';
      wSQL = :wSQL ||        ' 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.bdCODHIST, C.bdCODTPHI, 4 BDORD';
      wSQL = :wSQL ||        ',(SELECT FIRST 1 scp.bdCODEMPSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = i.bdCODEMP AND scp.bdCODSCP = i.bdCODSCP AND ';
      wSQL = :wSQL ||         '((scp.bdDATAINICIAL <= s.bdDATAEMISSAO AND scp.bdDATAFINAL IS NULL) OR (s.bdDATAEMISSAO BETWEEN scp.bdDATAINICIAL AND scp.bdDATAFINAL))) ';
      wSQL = :wSQL || 'FROM '||:wTableRet||' R ';
      wSQL = :wSQL || 'LEFT OUTER JOIN (';
      wSQL = :wSQL ||                  'SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO, I.BDORDEM, I.BDEDITCHAVE, I.BDCHAVE_VSUC, I.BDCOMPHIST_VLRCSRET, I.BDCOMPHIST_VLRCONTAB, I.BDVLRCONTAB,I.BDCODSCP ';
      wSQL = :wSQL ||                  'FROM '||:wTableItem||' I ';
      IF (wTableRateio <> '') THEN
        wSQL = :wSQL ||       'left outer join '||wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) '; -- Rateio vão fazer contabilização própria e não aqui
      wSQL = :wSQL ||                  'WHERE I.BDSESSAO = '||:PRSESSAO;
      IF (wTableRateio <> '') THEN
        wSQL = :wSQL ||       ' and rat.bdCODEMP IS NULL '; -- Somente quando não tiver rateio no lançamento
      wSQL = :wSQL ||                 ') I ON(I.BDCODEMP = R.BDCODEMP AND I.BDCHAVE = R.BDCHAVE AND I.BDSESSAO = R.BDSESSAO) ';
      IF (:wTipLan IS NOT NULL) THEN
        wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE AND S.BDSESSAO = R.BDSESSAO AND S.BDTIPLAN = '||:wTipLan||') ';
      ELSE
        wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTable||' S ON(S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE AND S.BDSESSAO = R.BDSESSAO) ';
      wSQL = :wSQL || 'LEFT OUTER JOIN(SELECT I.BDCODEMP, I.BDCHAVE, MAX(I.BDORDEM) BDORDEM ';
      wSQL = :wSQL ||                 'FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I ';
      wSQL = :wSQL ||                 'LEFT OUTER JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = I.BDCODNAT) ';
      wSQL = :wSQL ||                 'WHERE I.BDSESSAO = '||:PRSESSAO||' ';
      wSQL = :wSQL ||                   'AND N.BDCONTABILIZA = ''TRUE'' ';
      wSQL = :wSQL ||                 'GROUP BY I.BDCODEMP, I.BDCHAVE) IO ON (IO.BDCODEMP = I.BDCODEMP AND IO.BDCHAVE = I.BDCHAVE AND IO.BDORDEM = I.BDORDEM) ';
      wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND COALESCE(C.BDCODREC,0) = COALESCE(R.BDCODRECCSOCIAL,0) AND C.BDCODITEMONLINE = '||:wCodItemCs||WANDFIELDREF||') ';
                      /*Saída olha data de emissão, ao fazer a contabilização de entrada/serviço tem que ser adaptado para olhar os outros campos de data*/
      wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = R.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';    
      wSQL = :wSQL || 'WHERE R.BDSESSAO = '||:PRSESSAO;
      IF (:wTIPOINTCONTRETPCC = 1) THEN
        wSQL = :wSQL || ' and S.BDCONDPGTO <> 1 '; -- Alt.: #224292 - Apenas quando a nota não for "a prazo"...
      wSQL = :wSQL || ' and R.BDVLRCSOCIAL > 0  AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
      wSQL = :wSQL || ' and (S.BDRATEIARET = ''TRUE'' OR S.BDPRIMEIRAORDEM = I.BDORDEM) ';
      wSQL = :wSQL || 'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';
      wSQL = :wSQL || 'AND NOT EXISTS(';
      wSQL = :wSQL ||                'SELECT INCO.BDCODINCONSISTENCIA ';
      wSQL = :wSQL ||                'FROM '||wTableIncon||' INCO ';
      wSQL = :wSQL ||                'WHERE INCO.BDCODEMP = I.BDCODEMP ';
      wSQL = :wSQL ||                'AND INCO.BDCHAVE = I.BDCHAVE ';
      wSQL = :wSQL ||                'AND INCO.BDSESSAO = I.BDSESSAO ';
      wSQL = :wSQL ||               ')';
      EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_RET','6');
    END
  IF ((:WTIPOAPURACAORETIR = 0) OR
      (:WTIPOAPURACAORETIR = 1) OR
      (:wOrgaoPublico = 'TRUE')) THEN
    BEGIN
      /*Retenção de imposto de renda*/
      IF (POSITION('SER', :PRTIPOLAN) = 0) THEN
        BEGIN                       
          WSOMARET = '(R.BDVLRIR)';
          wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdCODHIST, bdCODTPHI, bdord,BDCODEMPSCP) ';
          wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, ';
          IF (:prTIPOLAN = 'ENT') THEN
          wSQL = :wSQL || 'NULL BDCONTADEBPROV, C.BDCONTACREDPROV, ';
          ELSE
          IF (:prTIPOLAN = 'SAI') THEN
          wSQL = :wSQL || 'C.BDCONTADEBPROV, NULL BDCONTACREDPROV, ';
          wSQL = :wSQL ||        'IIF(COALESCE(I.BDCOMPHIST_VLRIRRET,'''') <> '''', COALESCE(I.BDCOMPHIST_VLRIRRET,''''), COALESCE(I.BDCOMPHIST_VLRCONTAB,'''')), ';
          wSQL = :wSQL ||        'S.'||wfielddata||', Coalesce(IIF(S.BDVALORNOTA > 0 and S.BDRATEIARET = ''TRUE'',Cast(I.BDVLRCONTAB/CAST(S.BDVALORNOTA AS NUMERIC(15,6))*'||WSOMARET||' AS NUMERIC(15,2)) + Coalesce('||WSOMARET||' - ';
          wSQL = :wSQL ||        'IIF((IO.BDCODEMP IS NOT NULL AND S.BDVALORNOTA > 0), CAST(I.BDVLRCONTAB / CAST(S.BDVALORNOTA AS NUMERIC(15,6)) * '||WSOMARET||' AS NUMERIC(15,2)),0)';
          wSQL = :wSQL ||        ',0),'||WSOMARET||'),0) BDVLRIR, ';
          wSQL = :wSQL ||        ' 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, ';
          wSQL = :wSQL ||        :PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.bdCODHIST, C.bdCODTPHI, 4 BDORD';
          wSQL = :wSQL ||        ',(SELECT FIRST 1 scp.bdCODEMPSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = i.bdCODEMP AND scp.bdCODSCP = i.bdCODSCP AND ';
          wSQL = :wSQL ||         '((scp.bdDATAINICIAL <= s.bdDATAEMISSAO AND scp.bdDATAFINAL IS NULL) OR (s.bdDATAEMISSAO BETWEEN scp.bdDATAINICIAL AND scp.bdDATAFINAL))) ';
          wSQL = :wSQL || 'FROM '||:wTableRet||' R ';
          wSQL = :wSQL || 'LEFT OUTER JOIN (';
          wSQL = :wSQL ||                  'SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO, I.BDORDEM, I.BDEDITCHAVE, I.BDCHAVE_VSUC, I.BDCOMPHIST_VLRIRRET, BDCOMPHIST_VLRCONTAB, I.BDVLRCONTAB, I.BDCODSCP  ';
          wSQL = :wSQL ||                  'FROM '||:wTableItem||' I ';
          IF (wTableRateio <> '') THEN
            wSQL = :wSQL ||       'left outer join '||wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) '; -- Rateio vão fazer contabilização própria e não aqui
          wSQL = :wSQL ||                  'WHERE I.BDSESSAO = '||:PRSESSAO;
          IF (wTableRateio <> '') THEN
            wSQL = :wSQL ||       ' and rat.bdCODEMP IS NULL '; -- Somente quando não tiver rateio no lançamento
          wSQL = :wSQL ||                 ') I ON(I.BDCODEMP = R.BDCODEMP AND I.BDCHAVE = R.BDCHAVE AND I.BDSESSAO = R.BDSESSAO) ';
          wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTable||' S ON(S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE AND S.BDSESSAO = R.BDSESSAO) ';
          wSQL = :wSQL || 'LEFT OUTER JOIN(SELECT I.BDCODEMP, I.BDCHAVE, MAX(I.BDORDEM) BDORDEM ';
          wSQL = :wSQL ||                 'FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I ';
          wSQL = :wSQL ||                 'LEFT OUTER JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = I.BDCODNAT) ';
          wSQL = :wSQL ||                 'WHERE I.BDSESSAO = '||:PRSESSAO||' ';
          wSQL = :wSQL ||                   'AND N.BDCONTABILIZA = ''TRUE'' ';
          wSQL = :wSQL ||                 'GROUP BY I.BDCODEMP, I.BDCHAVE) IO ON (IO.BDCODEMP = I.BDCODEMP AND IO.BDCHAVE = I.BDCHAVE AND IO.BDORDEM = I.BDORDEM) ';
          IF (UPPER(wOrgaoPublico) = 'TRUE') THEN
            BEGIN
              wSQL = :wSQL || ' left outer join(select BDCODTER, RF2.BDORGAOPUBLICO, RF2.BDCGCTER, RF2.BDNOMETER, RF2.BDREFEMP ';
              wSQL = :wSQL || ' from TTERCEIRO_REF RF2 ';
              wSQL = :wSQL || ' where RF2.BDREFEMP = coalesce((select first 1 BDREFEMP ';
              wSQL = :wSQL || ' from TTERCEIRO_REF RF3 ';
              wSQL = :wSQL || ' where RF3.BDCODTER = RF2.BDCODTER and ';
              wSQL = :wSQL || ' RF3.BDREFEMP <= substring(CURRENT_DATE from 1 for 4) || substring(CURRENT_DATE from 6 for 2) ';
              wSQL = :wSQL || ' order by RF3.BDREFEMP desc), (select first 1 BDREFEMP ';
              wSQL = :wSQL || ' from TTERCEIRO_REF RF3 ';
              wSQL = :wSQL || ' where RF3.BDCODTER = RF2.BDCODTER ';
              wSQL = :wSQL || ' order by RF3.BDCODTER, RF3.BDREFEMP))) TER on (TER.BDCODTER = S.BDCODTER) ';
            END
          wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND COALESCE(C.BDCODREC,0) = COALESCE(R.BDCODRECIR,0) AND C.BDCODITEMONLINE = '||:wCodItemIr||WANDFIELDREF||') ';
                          /*Saída olha data de emissão, ao fazer a contabilização de entrada/serviço tem que ser adaptado para olhar os outros campos de data*/
          wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = R.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';      
          wSQL = :wSQL || 'WHERE R.BDSESSAO = '||:PRSESSAO;
          IF (:WTIPOAPURACAORETIR = 1) THEN
            wSQL = :wSQL || ' and S.BDCONDPGTO <> 1 '; -- Alt.: #224292 - Apenas quando a nota não for "a prazo"...
          wSQL = :wSQL || ' AND R.BDVLRIR > 0  AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
          wSQL = :wSQL || ' AND (S.BDRATEIARET = ''TRUE'' OR S.BDPRIMEIRAORDEM = I.BDORDEM) ';
          wSQL = :wSQL || ' AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';
          wSQL = :wSQL || ' AND NOT EXISTS(';
          wSQL = :wSQL ||                'SELECT INCO.BDCODINCONSISTENCIA ';
          wSQL = :wSQL ||                'FROM '||:wTableIncon||' INCO ';
          wSQL = :wSQL ||                'WHERE INCO.BDCODEMP = I.BDCODEMP ';
          wSQL = :wSQL ||                'AND INCO.BDCHAVE = I.BDCHAVE ';
          wSQL = :wSQL ||                'AND INCO.BDSESSAO = I.BDSESSAO ';
          wSQL = :wSQL ||               ')';
          /* Alt.: #224292 - Aqui segue a regra:
          1 - Notas diferentes de "Prazo", sempre contabilizam.
          2 - Quando o parâmetro do "Órgão público" estiver marcado, se o participante for "Órgão público", contabiliza na baixa da parcela.
          3 - As demais notas, seguem a configuração do plano. */
          if (UPPER(wOrgaoPublico) = 'TRUE') then
            wSQL = :wSQL || ' AND IIF((s.bdCONDPGTO <> 1),0,IIF(COALESCE(ter.bdORGAOPUBLICO,''FALSE'')=''TRUE'',1,'||(:wtipoApuracaoRetIR)||')) = 0';
        END
      ELSE /*Serviço pega o IR da tabela de itens*/
        BEGIN
          wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP (BDCODEMP, BDCHAVE, BDORDEM, BDSESSAO, BDCHAVE_VSUC, BDCODPLAPADRAO, BDCODUSU, ';
          wSQL = :wSQL ||                                            'BDDEBITO, BDCREDITO, BDCOMPL, BDDATA, BDVALOR, BDTIPOLAN, BDDCTO, ';
          wSQL = :wSQL ||                                            'BDTRANSACAO, BDTRANFECHADA, BDFORMULA, BDCODPLANOONLINE, BDCHAVETITULO, ';
          wSQL = :wSQL ||                                            'BDCLASSIFBUSCA, BDCLASSIFTITULO, BDCODITEMONLINE, BDCHAVECONTA, BDCODHIST, ';
          wSQL = :wSQL ||                                            'BDCODTPHI, BDORD, BDCODEMPSCP) ';
          wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, ';
          IF (:prTIPOLAN = 'SERR') THEN
          wSQL = :wSQL || 'NULL BDCONTADEBPROV, C.BDCONTACREDPROV, ';
          ELSE
          IF (:prTIPOLAN = 'SERE') THEN
          wSQL = :wSQL || 'C.BDCONTADEBPROV, NULL BDCONTACREDPROV, ';
          wSQL = :wSQL ||         'I.BDCOMPHIST_VLRIRRET, S.BDDATAEMISSAO, I.BDVLRIRSER, 100 BDTIPOLAN, ';
          wSQL = :wSQL ||         'S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, ';
          wSQL = :wSQL ||         'C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODHIST, C.BDCODTPHI, 4 BDORD';
          wSQL = :wSQL ||         ',(SELECT FIRST 1 scp.bdCODEMPSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = i.bdCODEMP AND scp.bdCODSCP = i.bdCODSCP AND ';
          wSQL = :wSQL ||          '((scp.bdDATAINICIAL <= s.bdDATAEMISSAO AND scp.bdDATAFINAL IS NULL) OR (s.bdDATAEMISSAO BETWEEN scp.bdDATAINICIAL AND scp.bdDATAFINAL))) ';
          wSQL = :wSQL ||         'FROM '||:wTableItem||' I ';
          IF (:wTipLan IS NOT NULL) THEN
            wSQL = :wSQL ||         'JOIN '||:wTable||' S ON (S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO AND S.BDTIPLAN = '||:wTipLan||') ';
          ELSE
            wSQL = :wSQL ||         'JOIN '||:wTable||' S ON (S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO) ';
          if (UPPER(wOrgaoPublico) = 'TRUE') then
            begin
              wSQL = :wSQL || ' left outer join(select BDCODTER, RF2.BDORGAOPUBLICO, RF2.BDCGCTER, RF2.BDNOMETER, RF2.BDREFEMP ';
              wSQL = :wSQL || ' from TTERCEIRO_REF RF2 ';
              wSQL = :wSQL || ' where RF2.BDREFEMP = coalesce((select first 1 BDREFEMP ';
              wSQL = :wSQL || ' from TTERCEIRO_REF RF3 ';
              wSQL = :wSQL || ' where RF3.BDCODTER = RF2.BDCODTER and ';
              wSQL = :wSQL || ' RF3.BDREFEMP <= substring(CURRENT_DATE from 1 for 4) || substring(CURRENT_DATE from 6 for 2) ';
              wSQL = :wSQL || ' order by RF3.BDREFEMP desc), (select first 1 BDREFEMP ';
              wSQL = :wSQL || ' from TTERCEIRO_REF RF3 ';
              wSQL = :wSQL || ' where RF3.BDCODTER = RF2.BDCODTER ';
              wSQL = :wSQL || ' order by RF3.BDCODTER, RF3.BDREFEMP))) TER on (TER.BDCODTER = S.BDCODTER) ';
            end
          wSQL = :wSQL ||         'JOIN TCONTAS_ONLINE_TEMP C ON (C.BDSESSAO = I.BDSESSAO AND C.BDCODREC = I.BDCODREC AND C.BDCODITEMONLINE = '||:wCodItemIR||') ';
          wSQL = :wSQL ||         'JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') ';
          wSQL = :wSQL ||         'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON (IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:wEF||WANDFIELDREF||') ';
          IF (wTableRateio <> '') THEN
            wSQL = :wSQL ||       'LEFT OUTER JOIN '||:wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) '; -- Rateio vão fazer contabilização própria e não aqui
          wSQL = :wSQL ||         'WHERE I.BDSESSAO = '||:PRSESSAO;
          IF (:WTIPOAPURACAORETIR = 1) THEN
            wSQL = :wSQL || ' and S.BDCONDPGTO <> 1 '; -- Alt.: #224292 - Apenas quando a nota não for "a prazo"...
          wSQL = :wSQL ||         'AND I.BDVLRIRSER > 0 ';
          wSQL = :wSQL ||         'AND S.BDCODSITNF NOT IN (2, 3, 4, 5) '; 
          wSQL = :wSQL ||         'AND (S.BDRATEIARET = ''TRUE'' OR S.BDPRIMEIRAORDEM = I.BDORDEM) ';
          wSQL = :wSQL ||         'AND ((IC.BDCODEMP IS NULL) OR (IC.BDDATA IS NULL) OR ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.BDDATAEMISSAO))) ';
          IF (wTableRateio <> '') THEN
            wSQL = :wSQL ||       'AND rat.bdCODEMP IS NULL '; -- Somente quando não tiver rateio no lançamento
          wSQL = :wSQL ||         'AND NOT EXISTS(';
          wSQL = :wSQL ||                        'SELECT INCO.BDCODINCONSISTENCIA ';
          wSQL = :wSQL ||                        'FROM '||:wTableIncon||' INCO ';
          wSQL = :wSQL ||                        'WHERE INCO.BDCODEMP = I.BDCODEMP ';
          wSQL = :wSQL ||                        'AND INCO.BDCHAVE = I.BDCHAVE ';
          wSQL = :wSQL ||                        'AND INCO.BDSESSAO = I.BDSESSAO ';
          wSQL = :wSQL ||                       ')';
          /* Alt.: #224292 - Aqui segue a regra:
          1 - Notas diferentes de "Prazo", sempre contabilizam.
          2 - Quando o parâmetro do "Órgão público" estiver marcado, se o participante for "Órgão público", contabiliza na baixa da parcela.
          3 - As demais notas, seguem a configuração do plano. */
          if (UPPER(wOrgaoPublico) = 'TRUE') then
            wSQL = :wSQL || ' AND IIF((s.bdCONDPGTO <> 1),0,IIF(COALESCE(ter.bdORGAOPUBLICO,''FALSE'')=''TRUE'',1,'||(:wtipoApuracaoRetIR)||')) = 0';
        END

      EXECUTE STATEMENT :wSQL;
  /**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_RET','7');
    END 

  /*Retenção de inss*/
  WSOMARET = '('||:WCAMPOINSS||')';

  wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdCODHIST, bdCODTPHI, bdord, BDCODEMPSCP) ';
  wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, ';
  IF ((:prTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
    wSQL = :wSQL || 'NULL BDCONTADEBPROV, C.BDCONTACREDPROV, ';
  ELSE
  IF ((:prTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE')) THEN
    wSQL = :wSQL || 'C.BDCONTADEBPROV, NULL BDCONTACREDPROV, ';
  wSQL = :wSQL ||        'IIF(COALESCE(I.BDCOMPHIST_VLRINSSRET,'''') <> '''', COALESCE(I.BDCOMPHIST_VLRINSSRET,''''), COALESCE(I.BDCOMPHIST_VLRCONTAB,'''')), ';
  wSQL = :wSQL ||        'S.'||wfielddata||', Coalesce(IIF(S.BDVALORNOTA > 0 and S.BDRATEIARET = ''TRUE'',Cast(I.BDVLRCONTAB/CAST(S.BDVALORNOTA AS NUMERIC(15,6))*'||WSOMARET||' AS NUMERIC(15,2)) + Coalesce('||WSOMARET||' - ';
  wSQL = :wSQL ||        'IIF((IO.BDCODEMP IS NOT NULL AND S.BDVALORNOTA > 0), CAST(I.BDVLRCONTAB / CAST(S.BDVALORNOTA AS NUMERIC(15,6)) * '||WSOMARET||' AS NUMERIC(15,2)),0)';
  wSQL = :wSQL ||        ',0),'||WSOMARET||'),0) BDRETINSS, ';
  wSQL = :wSQL ||        ' 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, ';
  wSQL = :wSQL ||        :PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.bdCODHIST, C.bdCODTPHI, 4 BDORD, NULL BDCODEMPSCP ';
  wSQL = :wSQL || 'FROM '||:wTableINSS||' INSS ';
  wSQL = :wSQL || 'LEFT OUTER JOIN (';
  wSQL = :wSQL ||                  'SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO, I.BDORDEM, I.BDEDITCHAVE, I.BDCHAVE_VSUC, I.BDCOMPHIST_VLRINSSRET, I.BDCOMPHIST_VLRCONTAB, I.BDVLRCONTAB, I.BDCODSCP ';
  wSQL = :wSQL ||                  'FROM '||:wTableItem||' I ';
  IF (wTableRateio <> '') THEN
    wSQL = :wSQL ||       'left outer join '||wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) '; -- Rateio vão fazer contabilização própria e não aqui
  wSQL = :wSQL ||                  'WHERE I.BDSESSAO = '||:PRSESSAO;
  IF (wTableRateio <> '') THEN
    wSQL = :wSQL ||       ' and rat.bdCODEMP IS NULL '; -- Somente quando não tiver rateio no lançamento
  wSQL = :wSQL ||                 ') I ON(I.BDCODEMP = INSS.BDCODEMP AND I.BDCHAVE = INSS.BDCHAVE AND I.BDSESSAO = INSS.BDSESSAO) ';
  IF (:wTipLan IS NOT NULL) THEN
    wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = INSS.BDCODEMP AND S.BDCHAVE = INSS.BDCHAVE AND S.BDSESSAO = INSS.BDSESSAO AND S.BDTIPLAN = '||:wTipLan||') ';
  ELSE
    wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTable||' S ON(S.BDCODEMP = INSS.BDCODEMP AND S.BDCHAVE = INSS.BDCHAVE AND S.BDSESSAO = INSS.BDSESSAO) ';
  wSQL = :wSQL || 'LEFT OUTER JOIN(SELECT I.BDCODEMP, I.BDCHAVE, MAX(I.BDORDEM) BDORDEM ';
  wSQL = :wSQL ||                 'FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I ';
  wSQL = :wSQL ||                 'LEFT OUTER JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = I.BDCODNAT) ';
  wSQL = :wSQL ||                 'WHERE I.BDSESSAO = '||:PRSESSAO||' ';
  wSQL = :wSQL ||                   'AND N.BDCONTABILIZA = ''TRUE'' ';
  wSQL = :wSQL ||                 'GROUP BY I.BDCODEMP, I.BDCHAVE) IO ON (IO.BDCODEMP = I.BDCODEMP AND IO.BDCHAVE = I.BDCHAVE AND IO.BDORDEM = I.BDORDEM) ';
  wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDCODREC = COALESCE(INSS.BDCODRECINSS, 0) AND C.BDCODITEMONLINE = '||:wCodItemInss||WANDFIELDREF||') ';
                  /*Saída olha data de emissão, ao fazer a contabilização de entrada/serviço tem que ser adaptado para olhar os outros campos de data*/
  wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = INSS.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
  wSQL = :wSQL || 'WHERE INSS.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL || ' and '||:wCampoINSS||' > 0 AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
  wSQL = :wSQL || ' and (S.BDRATEIARET = ''TRUE'' OR S.BDPRIMEIRAORDEM = I.BDORDEM) ';
  wSQL = :wSQL || 'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';
  wSQL = :wSQL || 'AND NOT EXISTS(';
  wSQL = :wSQL ||                'SELECT INCO.BDCODINCONSISTENCIA ';
  wSQL = :wSQL ||                'FROM '||:wTableIncon||' INCO ';
  wSQL = :wSQL ||                'WHERE INCO.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL ||                'AND INCO.BDCHAVE = I.BDCHAVE ';
  wSQL = :wSQL ||                'AND INCO.BDSESSAO = I.BDSESSAO ';
  wSQL = :wSQL ||               ')';
  EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_RET','8');
  /* Cria Retenção das aposentadorias especiais de 15,20 e 25 anos */
  wSQL = (SELECT BDSQL FROM SP_CRIA_PRE_CONTAB_RET_APOSESP(:PRSESSAO, :PRCODPLANOONLINE, :PRENQFED, :PRTIPOLAN));
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_RET','9');
  /*Retenção de iss*/           
  WSOMARET = '(R.BDISSRET)';
  wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdCODHIST, bdCODTPHI, bdord, BDCODEMPSCP) ';
  wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, ';
  IF ((:prTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
    wSQL = :wSQL || 'NULL BDCONTADEBPROV, C.BDCONTACREDPROV, ';
  ELSE
  IF ((:prTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE')) THEN
    wSQL = :wSQL || 'C.BDCONTADEBPROV, NULL BDCONTACREDPROV, ';
  wSQL = :wSQL ||        'IIF(COALESCE(I.BDCOMPHIST_VLRISSRET,'''') <> '''', COALESCE(I.BDCOMPHIST_VLRISSRET,''''), COALESCE(I.BDCOMPHIST_VLRCONTAB,'''')), ';
  wSQL = :wSQL ||        'S.'||wfielddata||', Coalesce(IIF(S.BDVALORNOTA > 0 and S.BDRATEIARET = ''TRUE'',Cast(I.BDVLRCONTAB/CAST(S.BDVALORNOTA AS NUMERIC(15,6))*'||WSOMARET||' AS NUMERIC(15,2)) + Coalesce('||WSOMARET||' - ';
  wSQL = :wSQL ||        'IIF((IO.BDCODEMP IS NOT NULL AND S.BDVALORNOTA > 0), CAST(I.BDVLRCONTAB / CAST(S.BDVALORNOTA AS NUMERIC(15,6)) * '||WSOMARET||' AS NUMERIC(15,2)),0)';
  wSQL = :wSQL ||        ',0),'||WSOMARET||'),0) BDISSRET, ';
  wSQL = :wSQL ||        ' 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, ';
  wSQL = :wSQL ||        :PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.bdCODHIST, C.bdCODTPHI, 4 BDORD, NULL BDCODEMPSCP ';
  wSQL = :wSQL || 'FROM '||:wTableRet||' R ';
  wSQL = :wSQL || 'LEFT OUTER JOIN (';
  wSQL = :wSQL ||                  'SELECT I.BDCODEMP, I.BDCHAVE, I.BDSESSAO, I.BDORDEM, I.BDEDITCHAVE, I.BDCHAVE_VSUC, I.BDCOMPHIST_VLRISSRET, I.BDCOMPHIST_VLRCONTAB, I.BDVLRCONTAB, I.BDCODSCP ';
  wSQL = :wSQL ||                  'FROM '||:wTableItem||' I ';
  IF (wTableRateio <> '') THEN
    wSQL = :wSQL ||       'left outer join '||wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) '; -- Rateio vão fazer contabilização própria e não aqui
  wSQL = :wSQL ||                  'WHERE I.BDSESSAO = '||:PRSESSAO;
  IF (wTableRateio <> '') THEN
    wSQL = :wSQL ||       ' and rat.bdCODEMP IS NULL '; -- Somente quando não tiver rateio no lançamento
  wSQL = :wSQL ||                 ') I ON(I.BDCODEMP = R.BDCODEMP AND I.BDCHAVE = R.BDCHAVE AND I.BDSESSAO = R.BDSESSAO) ';
  wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTable||' S ON(S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE AND S.BDSESSAO = R.BDSESSAO) ';
  wSQL = :wSQL || 'LEFT OUTER JOIN(SELECT I.BDCODEMP, I.BDCHAVE, MAX(I.BDORDEM) BDORDEM ';
  wSQL = :wSQL ||                 'FROM TMP_VEF_EMP_TMOVSAIITENS_TEMP I ';
  wSQL = :wSQL ||                 'LEFT OUTER JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = I.BDCODNAT) ';
  wSQL = :wSQL ||                 'WHERE I.BDSESSAO = '||:PRSESSAO||' ';
  wSQL = :wSQL ||                   'AND N.BDCONTABILIZA = ''TRUE'' ';
  wSQL = :wSQL ||                 'GROUP BY I.BDCODEMP, I.BDCHAVE) IO ON (IO.BDCODEMP = I.BDCODEMP AND IO.BDCHAVE = I.BDCHAVE AND IO.BDORDEM = I.BDORDEM) ';
  wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDCODREC = '||IIF((POSITION('SER', :PRTIPOLAN) = 0), 'R.BDCODRECISS', '0')||' AND C.BDCODITEMONLINE = '||:wCodItemIss||WANDFIELDREF||') ';
                  /*Saída olha data de emissão, ao fazer a contabilização de entrada/serviço tem que ser adaptado para olhar os outros campos de data*/
  wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = R.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';        
  wSQL = :wSQL || 'WHERE R.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL || ' and R.BDISSRET > 0 AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
  wSQL = :wSQL || ' and (S.BDRATEIARET = ''TRUE'' OR S.BDPRIMEIRAORDEM = I.BDORDEM OR I.BDORDEM = 1) ';
  wSQL = :wSQL || 'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';
  wSQL = :wSQL || 'AND NOT EXISTS(';
  wSQL = :wSQL ||                'SELECT INCO.BDCODINCONSISTENCIA ';
  wSQL = :wSQL ||                'FROM '||:wTableIncon||' INCO ';
  wSQL = :wSQL ||                'WHERE INCO.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL ||                'AND INCO.BDCHAVE = I.BDCHAVE ';
  wSQL = :wSQL ||                'AND INCO.BDSESSAO = I.BDSESSAO ';
  wSQL = :wSQL ||               ')';
  EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_RET','10');
  WANDFIELDREF = ' AND C.BDREFERENCIA = EXTRACT(YEAR FROM MOV.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM MOV.'||WFIELDDATA||') ';
  /*------------------------------------------------------------Diferença do valor contábil---------------------------------------------------*/
  wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdCODHIST, bdCODTPHI, bdord, BDCODEMPSCP) ';
  wSQL = :wSQL || 'SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE, MOV.BDORDEM, MOV.BDSESSAO, MOV.BDCHAVE_VSUC, MOV.BDCODPLAPADRAO, MOV.BDCODUSU, ';
  IF ((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
    BEGIN
      -- inverte contas quando o valor for negativo - Como em "TContabilizacaoMGR.AddLancamento"
      wSQL = :wSQL ||        'NULL AS BDCONTADEBPROV, MOV.BDCONTACREDPROV AS BDCONTACREDPROV, ';
    END
  ELSE
  IF ((:PRTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE')) THEN
    BEGIN
      -- inverte contas quando o valor for negativo - Como em "TContabilizacaoMGR.AddLancamento"
      wSQL = :wSQL ||        'MOV.BDCONTADEBPROV AS BDCONTADEBPROV, NULL AS BDCONTACREDPROV, ';
    END
  wSQL = :wSQL ||        'MOV.BDCOMPHIST_VLRCONTAB, MOV.'|| wfielddata||', ';
  wSQL = :wSQL ||        'MOV.BDVLRCONTAB - Coalesce(MOV.BDTOTALRET,0) AS BDVLRCON, ';
  wSQL = :wSQL ||        'MOV.BDTIPOLAN, MOV.BDNUMDOCINI, MOV.BDTRANSACAO, MOV.BDTRANFECHADA, MOV.BDFORMULA, MOV.BDCODPLANOONLINE, MOV.BDCHAVECONF, MOV.BDCLASSIFICACAO, MOV.BDCLASS_TITULO, MOV.BDCODITEMONLINE, MOV.BDCHAVELAN, mov.bdCODHIST, mov.bdCODTPHI, 4 BDORD, MOV.BDCODEMPSCP ';
  wSQL = :wSQL || 'FROM (';
  wSQL = :wSQL ||       'SELECT I.BDCODEMP, I.BDCHAVE, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, MOV.BDRATEIARET, MOV.BDPRIMEIRAORDEM, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRCONTAB, mov.BDDATAEMISSAO, I.BDVLRCONTAB, 100 BDTIPOLAN/*100 - Escrita fiscal*/, mov.BDNUMDOCINI, NULL BDTRANSACAO, ';
  wSQL = :wSQL ||              '''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE AS BDCHAVELAN, c.bdCODHIST, c.bdCODTPHI, ';
  wSQL = :wSQL ||       '(SELECT SUM(Coalesce(CT.BDVALOR,0)) FROM TMP_TLANC_CONTABILIZACAO_TEMP CT WHERE CT.BDSESSAO = I.BDSESSAO AND CT.BDCODEMP = I.BDCODEMP AND CT.BDCHAVE = I.BDEDITCHAVE AND CT.BDORDEM = I.BDORDEM AND (CT.BDFORMULA LIKE ''%RET%'' or CT.BDFORMULA LIKE ''%ROYALTIES%'')) BDTOTALRET ';
  wSQL = :wSQL || IIF(:PRTIPOLAN = 'ENT', ',MOV.BDDATAENTRADAENT ',  '');
  wSQL = :wSQL ||       ',(SELECT FIRST 1 scp.bdCODEMPSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = i.bdCODEMP AND scp.bdCODSCP = i.bdCODSCP AND ';
  wSQL = :wSQL ||        '((scp.bdDATAINICIAL <= mov.bdDATAEMISSAO AND scp.bdDATAFINAL IS NULL) OR (mov.bdDATAEMISSAO BETWEEN scp.bdDATAINICIAL AND scp.bdDATAFINAL))) ';
  wSQL = :wSQL ||       'FROM '||:wTableItem||' I ';
  IF (:wTipLan IS NOT NULL) THEN
    wSQL = :wSQL ||       'JOIN '||:wTable||' mov ON (mov.BDCODEMP = I.BDCODEMP AND mov.BDCHAVE = I.BDCHAVE AND mov.BDSESSAO = I.BDSESSAO AND mov.BDTIPLAN = '||:wTipLan||') ';
  ELSE
    wSQL = :wSQL ||       'JOIN '||:wTable||' mov ON (mov.BDCODEMP = I.BDCODEMP AND mov.BDCHAVE = I.BDCHAVE AND mov.BDSESSAO = I.BDSESSAO) ';
  IF (wTableRateio <> '') THEN
    wSQL = :wSQL ||       'left outer join '||wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) '; -- Rateio vão fazer contabilização própria e não aqui
  wSQL = :wSQL ||         ' JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN mov.BDCONDPGTO = 0 THEN 111 '; /*Valor contábil - A vista*/
  wSQL = :wSQL ||                                                                                                                         ' WHEN mov.BDCONDPGTO = 1 THEN 117 '; /*Valor contábil - Prazo*/
  wSQL = :wSQL ||                                                                                                                         ' WHEN mov.BDCONDPGTO = 2 THEN 170 '; /*Valor contábil - Outras*/
  wSQL = :wSQL ||                                                                                             ' END)'||WANDFIELDREF||') ';
                        /*Saída olha data de emissão, ao fazer a contabilização de entrada/serviço tem que ser adaptado para olhar os outros campos de data*/
  wSQL = :wSQL ||       'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
  wSQL = :wSQL ||       'WHERE I.BDSESSAO = '||:PRSESSAO;
  IF (wTableRateio <> '') THEN
    wSQL = :wSQL ||       ' and rat.bdCODEMP IS NULL '; -- Somente quando não tiver rateio no lançamento
  wSQL = :wSQL ||       ' AND mov.BDCODSITNF NOT IN (2, 3, 4, 5) ';
  wSQL = :wSQL ||       'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= mov.'||wfielddata||'))) ';
  wSQL = :wSQL ||       'AND NOT EXISTS(';
  wSQL = :wSQL ||                      'SELECT INCO.BDCODINCONSISTENCIA ';
  wSQL = :wSQL ||                      'FROM '||:wTableIncon||' INCO ';
  wSQL = :wSQL ||                      'WHERE INCO.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL ||                      'AND   INCO.BDCHAVE  = I.BDCHAVE ';
  wSQL = :wSQL ||                      'AND   INCO.BDSESSAO = I.BDSESSAO ';
  wSQL = :wSQL ||                     ')';
  wSQL = :wSQL ||      ') MOV ';
  wSQL = :wSQL || 'WHERE (MOV.BDTOTALRET > 0) AND (MOV.BDRATEIARET = ''TRUE'' OR MOV.BDPRIMEIRAORDEM = MOV.BDORDEM) ';
  wSQL = :wSQL ||       'AND MOV.BDVLRCONTAB - Coalesce(MOV.BDTOTALRET,0) > 0 ';
  EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_RET','11');
END
^

create or alter procedure SP_CRIA_PRE_CONTABILIZACAO_AUX (
    PRSESSAO integer,
    PRCODPLANOONLINE integer,
    PRTIPOLAN varchar(4),
    PRTIPOINTDESC integer,
    PRTIPOINTICMS integer,
    PRCODCONFDIMESC integer,
    PRENQFED integer,
    PRCONTABGUIAMUN varchar(5))
as
declare variable WSQL varchar(4500);
declare variable WTABLE varchar(50);
declare variable WTABLEITEM varchar(50);
declare variable WCODITEMDESC integer;
declare variable WEF integer;
declare variable WTIPLAN integer;
declare variable WCREDITOPRESUMIDO varchar(5);
declare variable WTABLEDIFALIQ varchar(32);
declare variable WTABLEDIFALIQPR varchar(32);
declare variable WFIELDDATA varchar(32);
declare variable WFIELDREFERENCIA varchar(200);
BEGIN
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_AUX','1');
  /* Patrick T. Sá 25/07/2017.
     Está sp é um complemento da SP_CRIA_PRE_CONTABILIZACAO que excedeu os 64k(tamanho máximo de uma stored procedure no Firebird).
     Só deve ser chamada DENTRO da SP_CRIA_PRE_CONTABILIZACAO.
  */

  PRTIPOLAN = UPPER(:PRTIPOLAN);

  wEF     = 3;
  wTipLan = NULL;        
  wfielddata  = 'BDDATAEMISSAO';

  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTable      = 'TMP_VEF_EMP_TMOVSAI_TEMP';
      wTableItem  = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
      wTableDifAliq    = 'TMP_VEF_EMP_TMOVSAIDIFALIQ_TEMP';
      wTableDifAliqPR  = 'TMP_VEF_EMP_TMOVSAIDIFPR_TEMP';

      wCodItemDesc= 88;
    END
  ELSE
  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTable      = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItem  = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      wTableDifAliq    = 'TMP_VEF_EMP_TMOVENTDIFALIQ_TEMP';
      wTableDifAliqPR  = 'TMP_VEF_EMP_TMOVENTDIFPR_TEMP';    
      wfielddata = 'BDDATAENTRADAENT';

      wCodItemDesc= 81;
      SELECT C.BDCREDITOPRESUMIDO FROM VEF_ESTADOS_TCONFDIMESC C WHERE C.BDCODCONFDIMESC = :PRCODCONFDIMESC INTO :WCREDITOPRESUMIDO;
    END
  ELSE
  IF ((:PRTIPOLAN = 'SERE') OR (:PRTIPOLAN = 'SERR')) THEN /*SERE - Serviço emitido | SERR - Serviço recebido*/
    BEGIN
      wTable      = 'TMP_VEF_EMP_TMOVSER_TEMP';
      wTableItem  = 'TMP_VEF_EMP_TMOVSERITENS_TEMP';

      IF (:PRTIPOLAN = 'SERE') THEN
        BEGIN
          wTipLan     = 0;
          wCodItemDesc= 96;
        END
      ELSE
        BEGIN
          wTipLan     = 1;
          wCodItemDesc= 104;
        END
    END

  WFIELDREFERENCIA = 'EXTRACT(YEAR FROM S.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM S.'||WFIELDDATA||')';
  /*----------------------------------------------------------------Desconto------------------------------------------------------------------*/
  IF (:prTipoIntDesc = 0) THEN /*0 - Nota a nota*/
    BEGIN
      /* Contabiliza desconto */
      wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, ';
      wSQL = :wSQL ||                                           'bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, ';
      wSQL = :wSQL ||                                           'bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdCODHIST, bdCODTPHI, bdord, BDCODEMPSCP) ';
      wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, NULL BDCHAVE_VSUC, ';
      wSQL = :wSQL ||        'C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, ';
      wSQL = :wSQL ||        'IIF(COALESCE(I.BDCOMPHIST_VLRDESCONTO,'''') <> '''', COALESCE(I.BDCOMPHIST_VLRDESCONTO,''''), COALESCE(I.BDCOMPHIST_VLRCONTAB,'''')), ';
      wSQL = :wSQL ||         IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT,  ',  'S.BDDATAEMISSAO,  ') || 'S.BDDESCONTONOTA, 100 BDTIPOLAN/*100 - Escrita fiscal*/, S.BDNUMDOCINI, ';
      wSQL = :wSQL ||        'NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, ';
      wSQL = :wSQL ||        'C.BDCHAVE, C.bdCODHIST, C.bdCODTPHI, 2 BDORD';
      --wSQL = :wSQL ||        ', SCP.BDCODEMPSCP ';
      wSQL = :wSQL ||        ',(SELECT FIRST 1 scp.bdCODEMPSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = i.bdCODEMP AND scp.bdCODSCP = i.bdCODSCP AND ';
      wSQL = :wSQL ||         '((scp.bdDATAINICIAL <= '||IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT',  'S.BDDATAEMISSAO')||' AND scp.bdDATAFINAL IS NULL) OR ('||IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT',  'S.BDDATAEMISSAO')||' BETWEEN scp.bdDATAINICIAL AND scp.bdDATAFINAL))) ';
      wSQL = :wSQL || 'FROM (';
      wSQL = :wSQL ||       'SELECT S.BDSESSAO, S.BDCODEMP, S.BDCHAVE, S.BDNUMDOCINI, '||IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT, ',  'S.BDDATAEMISSAO, ');
      wSQL = :wSQL ||              'S.BDCODSITNF, (S.BDDESCONTONOTA - COALESCE(I.BDTOTDESCCFOP, 0)) BDDESCONTONOTA, S.BDTIPLAN ';
      wSQL = :wSQL ||       'FROM (';
      wSQL = :wSQL ||             'SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, SUM(IIF(NAT.BDCONTABILIZA = ''FALSE'', COALESCE(I.BDDESCONTO, 0), 0)) BDTOTDESCCFOP ';
      wSQL = :wSQL ||             'FROM '||:wTableItem||' I ';
      wSQL = :wSQL ||             'LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT) ';
      wSQL = :wSQL ||             'WHERE I.BDSESSAO = '||:PRSESSAO||' ';
      wSQL = :wSQL ||             'GROUP BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE ';
      wSQL = :wSQL ||            ') I ';
      wSQL = :wSQL ||      'JOIN '||:wTable||' S ON(S.BDSESSAO = I.BDSESSAO AND S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE) ';
      wSQL = :wSQL ||     ') S ';
      wSQL = :wSQL || 'JOIN '||:wTableItem||' I ON(I.BDCODEMP = S.BDCODEMP AND I.BDCHAVE = S.BDCHAVE AND I.BDSESSAO = S.BDSESSAO AND I.BDORDEM = COALESCE((SELECT MIN(BDORDEM) FROM '||:wTableItem||' IO JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = IO.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') WHERE IO.BDSESSAO = S.BDSESSAO AND IO.BDCODEMP = S.BDCODEMP AND IO.BDCHAVE = S.BDCHAVE GROUP BY BDSESSAO, BDCODEMP, BDCHAVE), 1)) ';
      wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDCODITEMONLINE = '||:wCodItemDesc||' AND C.BDREFERENCIA = '||WFIELDREFERENCIA||' ';
      IF ((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR'))  THEN
        wSQL = :wSQL || ' AND C.BDCONTACREDPROV IS NOT NULL) ';
      ELSE
      IF ((:PRTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE') OR (:PRTIPOLAN = 'REDZ')) THEN
        wSQL = :wSQL || ' AND C.BDCONTADEBPROV IS NOT NULL) ';

      wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') ';
      /*Camilla M. Pegar o código da empresa SCP*/
      --wSQL = :wSQL || 'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = I.BDCODEMP AND SCP.BDCODSCP = I.BDCODSCP) ';
      /*Saída olha data de emissão, ao fazer a contabilização de entrada/serviço tem que ser adaptado para olhar os outros campos de data*/
      wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
      wSQL = :wSQL || ' WHERE ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= s.'||IIF((:PRTIPOLAN = 'ENT'), 'bdDATAENTRADAENT', 'BDDATAEMISSAO')||'))) ';
      wSQL = :wSQL || ' AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
      wSQL = :wSQL || 'AND S.BDDESCONTONOTA > 0 ';
      IF (:wTipLan IS NOT NULL) THEN
        wSQL = :wSQL || 'AND S.BDTIPLAN = '||:wTipLan;
      EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_AUX','2');

      /* Contabiliza vlrcontab + desconto = Diferença do valor contábil */
      wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, ';
      wSQL = :wSQL ||                                           'bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, ';
      wSQL = :wSQL ||                                           'bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdCODHIST, bdCODTPHI, bdord, ';
      wSQL = :wSQL ||                                           'BDEMPREENDIMENTOPROVD, BDEMPREENDIMENTOPROVC, BDCODEMPREENDIMENTO, BDCODEMPSCP) ';
      wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, NULL BDCHAVE_VSUC, ';
      wSQL = :wSQL ||        'C.BDCODPLAPADRAO, NULL BDCODUSU, ';
      IF ((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR'))  THEN
        wSQL = :wSQL || 'C.BDCONTADEBPROV, NULL BDCONTACREDPROV, ';
      ELSE
      IF ((:PRTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE') OR (:PRTIPOLAN = 'REDZ')) THEN
        wSQL = :wSQL || 'NULL BDCONTADEBPROV, C.BDCONTACREDPROV, ';
      wSQL = :wSQL ||        ' I.BDCOMPHIST_VLRCONTAB, ';
      wSQL = :wSQL ||         IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT,  ',  'S.BDDATAEMISSAO,  ');
      wSQL = :wSQL ||        ' (COALESCE(I.BDVLRCONTAB, 0) + COALESCE(S.BDDESCONTONOTA, 0)) BDVLRCONTAB, ';
      wSQL = :wSQL ||        '100 BDTIPOLAN/*100 - Escrita fiscal*/, S.BDNUMDOCINI, NULL BDTRANSACAO, ';
      wSQL = :wSQL ||        '''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, ';
      wSQL = :wSQL ||        'C.BDCHAVE, C.bdCODHIST, C.bdCODTPHI, 1 BDORD, ';

      IF ((:prTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
        wSQL = :wSQL || 'C.bdEMPREENDIMENTOPROVD, null bdEMPREENDIMENTOPROVC, ';
      ELSE
      IF ((:prTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE')) THEN
        wSQL = :wSQL || 'null bdEMPREENDIMENTOPROVD, C.bdEMPREENDIMENTOPROVC, ';

     wSQL = :wSQL || ' S.BDCODEMPREENDIMENTO ';
      --wSQL = :wSQL || ', SCP.BDCODEMPSCP ';
      wSQL = :wSQL || ',(SELECT FIRST 1 scp.bdCODEMPSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = i.bdCODEMP AND scp.bdCODSCP = i.bdCODSCP AND ';
      wSQL = :wSQL ||   '((scp.bdDATAINICIAL <= '||IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT',  'S.BDDATAEMISSAO')||' AND scp.bdDATAFINAL IS NULL) OR ('||IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT',  'S.BDDATAEMISSAO')||' BETWEEN scp.bdDATAINICIAL AND scp.bdDATAFINAL))) ';

      wSQL = :wSQL || 'FROM (';
      wSQL = :wSQL ||       'SELECT S.BDSESSAO, S.BDCODEMP, S.BDCHAVE, S.BDNUMDOCINI, '||IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT, ',  'S.BDDATAEMISSAO, ');
      wSQL = :wSQL ||              'S.BDCODSITNF, (S.BDDESCONTONOTA - COALESCE(I.BDTOTDESCCFOP, 0)) BDDESCONTONOTA, S.BDTIPLAN, S.BDCONDPGTO,S.BDCODEMPREENDIMENTO ';
      wSQL = :wSQL ||       'FROM (';
      wSQL = :wSQL ||             'SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, SUM(IIF(NAT.BDCONTABILIZA = ''FALSE'', COALESCE(I.BDDESCONTO, 0), 0)) BDTOTDESCCFOP ';
      wSQL = :wSQL ||             'FROM '||:wTableItem||' I ';
      wSQL = :wSQL ||             'LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT) ';
      wSQL = :wSQL ||             'WHERE I.BDSESSAO = '||:PRSESSAO||' ';
      wSQL = :wSQL ||             'GROUP BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE ';
      wSQL = :wSQL ||            ') I ';
      wSQL = :wSQL ||      'JOIN '||:wTable||' S ON(S.BDSESSAO = I.BDSESSAO AND S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE) ';
      wSQL = :wSQL ||      'WHERE S.BDDESCONTONOTA > 0 ';
      wSQL = :wSQL ||     ') S ';
      --wSQL = :wSQL || 'FROM '||:wTable||' S ';
--      wSQL = :wSQL || 'JOIN '||:wTableItem||' I ON(I.BDCODEMP = S.BDCODEMP AND I.BDCHAVE = S.BDCHAVE AND I.BDSESSAO = S.BDSESSAO AND I.BDORDEM = 1) ';
      wSQL = :wSQL || 'JOIN '||:wTableItem||' I ON(I.BDCODEMP = S.BDCODEMP AND I.BDCHAVE = S.BDCHAVE AND I.BDSESSAO = S.BDSESSAO AND I.BDORDEM = COALESCE((SELECT MIN(BDORDEM) FROM '||:wTableItem||' IO JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = IO.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') WHERE IO.BDSESSAO = S.BDSESSAO AND IO.BDCODEMP = S.BDCODEMP AND IO.BDCHAVE = S.BDCHAVE GROUP BY BDSESSAO, BDCODEMP, BDCHAVE), 1)) ';
      wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDREFERENCIA = '||WFIELDREFERENCIA||' AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 111  ';/*Valor contábil - A vista*/
      wSQL = :wSQL ||                                                                                                                 'WHEN s.BDCONDPGTO = 1 THEN 117  ';/*Valor contábil - Prazo*/
      wSQL = :wSQL ||                                                                                                                 'WHEN s.BDCONDPGTO = 2 THEN 170  ';/*Valor contábil - Outras*/
      wSQL = :wSQL ||                                                                                                            'END)) ';
      wSQL = :wSQL || 'LEFT OUTER JOIN TCONTAS_ONLINE_TEMP CD ON(CD.BDSESSAO = I.BDSESSAO AND CD.BDREFERENCIA = '||WFIELDREFERENCIA||' AND CD.BDCODITEMONLINE = '||:wCodItemDesc;
      IF ((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR'))  THEN
        wSQL = :wSQL || ' AND CD.BDCONTACREDPROV IS NOT NULL) ';
      ELSE
      IF ((:PRTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE') OR (:PRTIPOLAN = 'REDZ')) THEN
        wSQL = :wSQL || ' AND CD.BDCONTADEBPROV IS NOT NULL) ';
      wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') ';
      /*Camilla M. Pegar o código da empresa SCP*/
      --wSQL = :wSQL || 'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = I.BDCODEMP AND SCP.BDCODSCP = I.BDCODSCP) ';
                      /*Saída olha data de emissão, ao fazer a contabilização de entrada/serviço tem que ser adaptado para olhar os outros campos de data*/
      wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
      wSQL = :wSQL || 'WHERE S.BDSESSAO = '||:PRSESSAO;
      wSQL = :wSQL || ' AND ((COALESCE(I.BDVLRCONTAB, 0) + COALESCE(S.BDDESCONTONOTA, 0)) > 0) '; -- Alt.: #150548 - Estava tentando contabilizar com valor zerado e acabava dando problemas no contabil por causa disso...
      wSQL = :wSQL || ' AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= s.'||IIF((:PRTIPOLAN = 'ENT'), 'bdDATAENTRADAENT', 'BDDATAEMISSAO')||'))) ';
      wSQL = :wSQL || ' AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
      --wSQL = :wSQL || 'AND S.BDDESCONTONOTA > 0 ';
      wSQL = :wSQL || 'AND CD.BDCHAVE IS NOT NULL '; /*Verifica se tem conta desconto*/
      IF (:wTipLan IS NOT NULL) THEN
        wSQL = :wSQL || 'AND S.BDTIPLAN = '||:wTipLan;

      EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_AUX','3');
    END
  ELSE
    BEGIN /*1 - Nota a nota por CFOP*/
      /* Contabiliza desconto */
      wSQL = 'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, ';
      wSQL = :wSQL ||                                 ' bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, ';
      wSQL = :wSQL ||                                          ' bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdCODHIST, bdCODTPHI, bdord, BDCODEMPSCP) ';
      wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, NULL BDCHAVE_VSUC, ';
      wSQL = :wSQL ||       ' C.BDCODPLAPADRAO, NULL BDCODUSU, ';
      IF ((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR'))  THEN
        wSQL = :wSQL ||     ' NULL AS BDCONTADEBPROV, C.BDCONTACREDPROV, ';
      ELSE
      IF ((:PRTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE') OR (:PRTIPOLAN = 'REDZ')) THEN
        wSQL = :wSQL ||     ' C.BDCONTADEBPROV, NULL AS BDCONTACREDPROV, ';
      wSQL = :wSQL ||        'IIF(COALESCE(I.BDCOMPHIST_VLRDESCONTO,'''') <> '''', COALESCE(I.BDCOMPHIST_VLRDESCONTO,''''), COALESCE(I.BDCOMPHIST_VLRCONTAB,'''')), ';
      wSQL = :wSQL ||        IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT,  ',  'S.BDDATAEMISSAO,  ') || ' I.BDDESCONTO, 100 BDTIPOLAN/*100 - Escrita fiscal*/, S.BDNUMDOCINI, ';
      wSQL = :wSQL ||       ' NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, ';
      wSQL = :wSQL ||       ' C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.bdCODHIST, C.bdCODTPHI, 2 BDORD ';
      --wSQL = :wSQL ||       ', SCP.BDCODEMPSCP ';
      wSQL = :wSQL ||       ',(SELECT FIRST 1 scp.bdCODEMPSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = i.bdCODEMP AND scp.bdCODSCP = i.bdCODSCP AND ';
      wSQL = :wSQL ||        '((scp.bdDATAINICIAL <= '||IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT',  'S.BDDATAEMISSAO')||' AND scp.bdDATAFINAL IS NULL) OR ('||IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT',  'S.BDDATAEMISSAO')||' BETWEEN scp.bdDATAINICIAL AND scp.bdDATAFINAL))) ';
      wSQL = :wSQL || 'FROM '||:wTableItem||' I ';

      IF (:wTipLan IS NOT NULL) THEN
        wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDSESSAO = I.BDSESSAO AND S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDTIPLAN = '||:wTipLan||') ';
      ELSE
        wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDSESSAO = I.BDSESSAO AND S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE) ';

      wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDREFERENCIA = '||WFIELDREFERENCIA||' AND I.BDCODNAT = C.BDCODNAT AND C.BDCODITEMONLINE = (CASE WHEN S.BDCONDPGTO = 0 THEN 243 ';
      wSQL = :wSQL ||                                                                                                                 'WHEN S.BDCONDPGTO = 1 THEN 244 ';
      wSQL = :wSQL ||                                                                                                                 'WHEN S.BDCONDPGTO = 2 THEN 245 ';
      IF ((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR'))  THEN
        wSQL = :wSQL ||                                                                                                            'END) AND C.BDCONTACREDPROV IS NOT NULL) ';
      ELSE
      IF ((:PRTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE') OR (:PRTIPOLAN = 'REDZ')) THEN
        wSQL = :wSQL ||                                                                                                            'END) AND C.BDCONTADEBPROV IS NOT NULL) ';
      wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') ';
      wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
      /*Camilla M. Pegar o código da empresa SCP*/
      --wSQL = :wSQL || 'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = I.BDCODEMP AND SCP.BDCODSCP = I.BDCODSCP) ';
     wSQL = :wSQL || 'WHERE I.BDSESSAO = '||:PRSESSAO||' ';
     wSQL = :wSQL || ' AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= s.'||IIF((:PRTIPOLAN = 'ENT'), 'bdDATAENTRADAENT', 'BDDATAEMISSAO')||'))) ';
     wSQL = :wSQL || 'AND I.BDDESCONTO > 0 ';
      EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_AUX','4');

      /* Contabiliza vlrcontab + desconto = Diferença do valor contábil */
      wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, ';
      wSQL = :wSQL ||                                           'bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, ';
      wSQL = :wSQL ||                                           'bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, bdCODHIST, bdCODTPHI, bdord, BDCODEMPSCP) ';
      wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, NULL BDCHAVE_VSUC, ';
      wSQL = :wSQL ||        'C.BDCODPLAPADRAO, NULL BDCODUSU, ';
      IF ((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR'))  THEN
        wSQL = :wSQL ||        ' C.BDCONTADEBPROV, NULL AS BDCONTACREDPROV, ';
      ELSE
      IF ((:PRTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE') OR (:PRTIPOLAN = 'REDZ')) THEN
        wSQL = :wSQL ||        ' NULL AS BDCONTADEBPROV, C.BDCONTACREDPROV, ';
      wSQL = :wSQL ||        ' I.BDCOMPHIST_VLRCONTAB, ';
      wSQL = :wSQL ||         IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT,  ',  'S.BDDATAEMISSAO,  ') || ' (COALESCE(I.BDVLRCONTAB, 0) + COALESCE(I.BDDESCONTO, 0)) BDVLRCONTAB, ';
      wSQL = :wSQL ||        '100 BDTIPOLAN/*100 - Escrita fiscal*/, S.BDNUMDOCINI, NULL BDTRANSACAO, ';
      wSQL = :wSQL ||        '''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, ';
      wSQL = :wSQL ||        'C.BDCHAVE, C.bdCODHIST, C.bdCODTPHI, 1 BDORD ';
      --wSQL = :wSQL ||        ', SCP.BDCODEMPSCP ';
      wSQL = :wSQL ||        ',(SELECT FIRST 1 scp.bdCODEMPSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = i.bdCODEMP AND scp.bdCODSCP = i.bdCODSCP AND ';
      wSQL = :wSQL ||         '((scp.bdDATAINICIAL <= '||IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT',  'S.BDDATAEMISSAO')||' AND scp.bdDATAFINAL IS NULL) OR ('||IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT',  'S.BDDATAEMISSAO')||' BETWEEN scp.bdDATAINICIAL AND scp.bdDATAFINAL))) ';
      wSQL = :wSQL || 'FROM '||:wTable||' S ';
      wSQL = :wSQL || 'JOIN '||:wTableItem||' I ON(I.BDCODEMP = S.BDCODEMP AND I.BDCHAVE = S.BDCHAVE AND I.BDSESSAO = S.BDSESSAO AND I.BDDESCONTO > 0) ';
      wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDREFERENCIA = '||WFIELDREFERENCIA||' AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 111  ';/*Valor contábil - A vista*/
      wSQL = :wSQL ||                                                                                                                 'WHEN s.BDCONDPGTO = 1 THEN 117  ';/*Valor contábil - Prazo*/
      wSQL = :wSQL ||                                                                                                                 'WHEN s.BDCONDPGTO = 2 THEN 170  ';/*Valor contábil - Outras*/
      wSQL = :wSQL ||                                                                                                            'END)) ';
      wSQL = :wSQL || 'LEFT OUTER JOIN TCONTAS_ONLINE_TEMP CD ON(CD.BDSESSAO = I.BDSESSAO AND CD.BDREFERENCIA = '||WFIELDREFERENCIA||' AND CD.BDCODNAT = I.BDCODNAT AND CD.BDCODITEMONLINE = (CASE WHEN S.BDCONDPGTO = 0 THEN 243 ';
      wSQL = :wSQL ||                                                                                                                                'WHEN S.BDCONDPGTO = 1 THEN 244 ';
      wSQL = :wSQL ||                                                                                                                                'WHEN S.BDCONDPGTO = 2 THEN 245 ';
      IF ((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR'))  THEN
        wSQL = :wSQL ||                                                                                                                           'END) AND CD.BDCONTACREDPROV IS NOT NULL) ';
      ELSE
      IF ((:PRTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE') OR (:PRTIPOLAN = 'REDZ')) THEN
        wSQL = :wSQL ||                                                                                                                           'END) AND CD.BDCONTADEBPROV IS NOT NULL) ';

      wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') ';
      /*Camilla M. Pegar o código da empresa SCP*/
      --wSQL = :wSQL || 'LEFT OUTER JOIN TEMPRESAS_SCP SCP ON (SCP.BDCODEMP = I.BDCODEMP AND SCP.BDCODSCP = I.BDCODSCP) ';
                      /*Saída olha data de emissão, ao fazer a contabilização de entrada/serviço tem que ser adaptado para olhar os outros campos de data*/
      wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';

      wSQL = :wSQL || 'WHERE S.BDSESSAO = '||:PRSESSAO;
      wSQL = :wSQL || ' AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= s.'||IIF((:PRTIPOLAN = 'ENT'), 'bdDATAENTRADAENT', 'BDDATAEMISSAO')||'))) ';
      wSQL = :wSQL || ' AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
      wSQL = :wSQL || 'AND CD.BDCHAVE IS NOT NULL '; /*Verifica se tem conta desconto*/
      IF (:wTipLan IS NOT NULL) THEN
      wSQL = :wSQL || 'AND S.BDTIPLAN = '||:wTipLan;
      EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_AUX','5');
--    END
    END
  /*ICMS Concomitante*/
  if ((:PRTIPOLAN = 'ENT') or (:PRTIPOLAN = 'SAI') AND (:PRTIPOINTICMS IN (0)))  then
     BEGIN
          wSQL = 'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdCODEMP, bdCHAVE, bdORDEM, bdSESSAO, bdCHAVE_VSUC, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdFORMULA, bdCODPLANOONLINE, bdCHAVETITULO, bdCLASSIFBUSCA, bdCLASSIFTITULO, bdCODITEMONLINE, bdCHAVECONTA, bdCODHIST, bdCODTPHI, bdORD, bdEMPREENDIMENTOPROVD, bdEMPREENDIMENTOPROVC, bdCODEMPREENDIMENTO) ';
          wSQL = :wSQL || 'SELECT i.bdCODEMP, i.bdEDITCHAVE, i.bdORDEM, i.bdSESSAO, i.bdCHAVE_VSUC, c.bdCODPLAPADRAO, NULL AS bdCODUSU, c.bdCONTADEBPROV, c.bdCONTACREDPROV, i.bdCOMPHIST_VLRICMSCONC, S.'||wfielddata||', i.bdVLRICMSCONC, ';
          wSQL = :wSQL || '100 AS bdTIPOLAN, s.bdNUMDOCINI, NULL AS bdTRANSACAO, ''TRUE'' AS bdTRANFECHADA, c.bdFORMULA, '||:PRCODPLANOONLINE||', c.bdCHAVECONF, c.bdCLASSIFICACAO, c.bdCLASS_TITULO, c.bdCODITEMONLINE, c.bdCHAVE, c.bdCODHIST, c.bdCODTPHI, 3 AS bdORD, ';
          wSQL = :wSQL || 'c.bdEMPREENDIMENTOPROVD, c.bdEMPREENDIMENTOPROVC, s.bdCODEMPREENDIMENTO ';
          wSQL = :wSQL || 'FROM '||:wTableItem||' i ';
          wSQL = :wSQL || 'JOIN '||:wTable||' s ON (s.bdCODEMP = i.bdCODEMP AND s.bdCHAVE = i.bdCHAVE AND s.bdSESSAO = i.bdSESSAO) ';
          wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP c ON (c.bdSESSAO = i.bdSESSAO AND c.bdCODNAT = i.bdCODNAT AND (c.bdCODITEMONLINE = CASE WHEN s.bdCONDPGTO = 0 THEN 640 '; /*ICMS Concomitante - A vista*/
          wSQL = :wSQL ||                                                                                                                  'WHEN s.bdCONDPGTO = 1 THEN 641 '; /*ICMS Concomitante - Prazo*/
          wSQL = :wSQL ||                                                                                                                  'WHEN s.bdCONDPGTO = 2 THEN 642 '; /*ICMS Concomitante - Outras*/
          wSQL = :wSQL || 'END)) ';
          wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT AND nat.bdCONTABILIZA = ''TRUE'') ';
                          /*Saída olha data de emissão, entrada/serviço tem que ser adaptado para olhar os outros campos de data*/      
          wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO ic ON (ic.bdCODEMP = i.bdCODEMP AND ic.bdCODSIS = '||:wEF||') ';
          wSQL = :wSQL || 'WHERE i.bdSESSAO = '||:PRSESSAO;
          wSQL = :wSQL || ' AND i.bdVLRICMSCONC > 0 ';
          wSQL = :wSQL || ' AND c.bdCONTADEBPROV IS NOT NULL AND c.bdCONTACREDPROV IS NOT NULL ';
          wSQL = :wSQL || ' AND s.bdCODSITNF NOT IN (2, 3, 4, 5) ';
          wSQL = :wSQL || ' AND ((ic.bdCODEMP IS NULL) OR (ic.bdDATA IS NULL) OR ((ic.bdCODEMP IS NOT NULL) AND (ic.bdDATA <= S.'||wfielddata||'))) ';
          EXECUTE STATEMENT :wSQL;
          /**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_AUX','6');
     END
    /*ICMS FCP_OP*/
    if ((:PRTIPOLAN = 'ENT') or (:PRTIPOLAN = 'SAI') AND (:PRTIPOINTICMS IN (0)))  then
     BEGIN
          wSQL = 'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdCODEMP, bdCHAVE, bdORDEM, bdSESSAO, bdCHAVE_VSUC, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdFORMULA, bdCODPLANOONLINE, bdCHAVETITULO, bdCLASSIFBUSCA, bdCLASSIFTITULO, bdCODITEMONLINE, bdCHAVECONTA, bdCODHIST, bdCODTPHI, bdORD, bdEMPREENDIMENTOPROVD, bdEMPREENDIMENTOPROVC, bdCODEMPREENDIMENTO) ';
          wSQL = :wSQL || 'SELECT i.bdCODEMP, i.bdEDITCHAVE, i.bdORDEM, i.bdSESSAO, i.bdCHAVE_VSUC, c.bdCODPLAPADRAO, NULL AS bdCODUSU, c.bdCONTADEBPROV, c.bdCONTACREDPROV, i.BDCOMPHIST_VLRFCP, S.'||wfielddata||', i.BDVLRFCP, ';
          wSQL = :wSQL || '100 AS bdTIPOLAN, s.bdNUMDOCINI, NULL AS bdTRANSACAO, ''TRUE'' AS bdTRANFECHADA, c.bdFORMULA, '||:PRCODPLANOONLINE||', c.bdCHAVECONF, c.bdCLASSIFICACAO, c.bdCLASS_TITULO, c.bdCODITEMONLINE, c.bdCHAVE, c.bdCODHIST, c.bdCODTPHI, 3 AS bdORD, ';
          wSQL = :wSQL || 'c.bdEMPREENDIMENTOPROVD, c.bdEMPREENDIMENTOPROVC, s.bdCODEMPREENDIMENTO ';
          wSQL = :wSQL || 'FROM '||:wTableItem||' i ';
          wSQL = :wSQL || 'JOIN '||:wTable||' s ON (s.bdCODEMP = i.bdCODEMP AND s.bdCHAVE = i.bdCHAVE AND s.bdSESSAO = i.bdSESSAO) ';
          wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP c ON (c.bdSESSAO = i.bdSESSAO AND c.bdCODNAT = i.bdCODNAT AND (c.bdCODITEMONLINE = CASE WHEN s.bdCONDPGTO = 0 THEN 663 '; /*ICMS FCP_OP*/
          wSQL = :wSQL ||                                                                                                                  'WHEN s.bdCONDPGTO = 1 THEN 664 '; /*ICMS FCP_OP - Prazo*/
          wSQL = :wSQL ||                                                                                                                  'WHEN s.bdCONDPGTO = 2 THEN 665 '; /*ICMS FCP_OP - Outras*/
          wSQL = :wSQL || 'END)) ';
          wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT AND nat.bdCONTABILIZA = ''TRUE'') ';
                          /*Sa??da olha data de emiss??o, entrada/servi??o tem que ser adaptado para olhar os outros campos de data*/      
          wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO ic ON (ic.bdCODEMP = i.bdCODEMP AND ic.bdCODSIS = '||:wEF||') ';
          wSQL = :wSQL || 'WHERE i.bdSESSAO = '||:PRSESSAO;
          wSQL = :wSQL || ' AND i.BDVLRFCP > 0 ';
          wSQL = :wSQL || ' AND c.bdCONTADEBPROV IS NOT NULL AND c.bdCONTACREDPROV IS NOT NULL ';
          wSQL = :wSQL || ' AND s.bdCODSITNF NOT IN (2, 3, 4, 5) ';
          wSQL = :wSQL || ' AND ((ic.bdCODEMP IS NULL) OR (ic.bdDATA IS NULL) OR ((ic.bdCODEMP IS NOT NULL) AND (ic.bdDATA <= S.'||wfielddata||'))) ';
          EXECUTE STATEMENT :wSQL;
          /**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_AUX','7');
     END

  /*--------------------------------------------------------Diferencial de alíquota-----------------------------------------------------------*/
  IF (((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SAI')) AND ((:PRTIPOINTICMS IN (0)) OR ((:PRENQFED IN(1, 2)) and (:prcontabguiamun = 'FALSE')) )) THEN
    BEGIN
      wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, BDCODHIST, BDCODTPHI, bdord) ';
      wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRDIFALIQ, '|| IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT ',  'S.BDDATAEMISSAO ')||', DIF.BDVLRDIFENTALIQ, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ';
      wSQL = :wSQL || '       ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||', C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODHIST, C.BDCODTPHI, 3 BDORD ';
      wSQL = :wSQL || 'FROM ( ';
      wSQL = :wSQL || '      SELECT DIF.BDSESSAO, DIF.BDCODEMP, DIF.BDCHAVE, DIF.BDORDEM, ';
      wSQL = :wSQL || '             SUM(COALESCE(DIF.BDVLRDIFENTALIQ, 0)) BDVLRDIFENTALIQ ';
      wSQL = :wSQL || '      FROM '||wTableDifAliq||' DIF ';
      wSQL = :wSQL || '      WHERE DIF.BDSESSAO = '||:PRSESSAO;
      wSQL = :wSQL || '      GROUP BY DIF.BDSESSAO, DIF.BDCODEMP, DIF.BDCHAVE, DIF.BDORDEM ';
      wSQL = :wSQL || '     ) DIF ';
      wSQL = :wSQL || 'JOIN '||:wTableItem||' I ON(I.BDCODEMP = DIF.BDCODEMP AND I.BDCHAVE = DIF.BDCHAVE AND I.BDSESSAO = DIF.BDSESSAO AND I.BDORDEM = DIF.BDORDEM) ';
      wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO AND S.BDCODSITNF NOT IN (2, 3, 4, 5)) ';
      wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDREFERENCIA = '||WFIELDREFERENCIA||' AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 219  /*A vista*/ ';
      wSQL = :wSQL || '                                                                                                                WHEN s.BDCONDPGTO = 1 THEN 220  /*Prazo*/ ';
      wSQL = :wSQL || '                                                                                                                WHEN s.BDCONDPGTO = 2 THEN 221  /*Outras*/ ';
      wSQL = :wSQL || '                                                                                                           END) AND C.BDCONTADEBPROV IS NOT NULL AND C.BDCONTACREDPROV IS NOT NULL) ';
      wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'' AND NAT.BDLANDIFALIQNAT = ''TRUE'') ';
      wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
      wSQL = :wSQL || 'WHERE DIF.BDVLRDIFENTALIQ > 0 ';
      IF (:prTIPOLAN = 'ENT') THEN
      wSQL = :wSQL || 'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.bdDATAENTRADAENT))) ';
      ELSE
        wSQL = :wSQL || 'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.bdDATAEMISSAO))) ';
      wSQL = :wSQL || 'AND NOT EXISTS( ';
      wSQL = :wSQL || '             SELECT INCO.BDCODINCONSISTENCIA ';
      wSQL = :wSQL || '             FROM VEF_INCON_TMOV'||:prTIPOLAN||' INCO ';
      wSQL = :wSQL || '             WHERE INCO.BDCODEMP = I.BDCODEMP ';
      wSQL = :wSQL || '             AND   INCO.BDCHAVE  = I.BDCHAVE ';
      wSQL = :wSQL || '             AND   INCO.BDSESSAO = I.BDSESSAO ';
      wSQL = :wSQL || '            ); ';
      EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_AUX','8');

      /*Paraná*/
      wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, BDCODHIST, BDCODTPHI, bdord) ';
      wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRDIFALIQ, '|| IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT ',  'S.BDDATAEMISSAO ')||', DIF.BDIMPRECOLHER, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ';
      wSQL = :wSQL || '       ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||', C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODHIST, C.BDCODTPHI, 3 BDORD ';
      wSQL = :wSQL || 'FROM ( ';
      wSQL = :wSQL || '      SELECT DIF.BDSESSAO, DIF.BDCODEMP, DIF.BDCHAVE, DIF.BDORDEM, ';
      wSQL = :wSQL || '             SUM(COALESCE(DIF.BDIMPRECOLHER, 0)) BDIMPRECOLHER ';
      wSQL = :wSQL || '      FROM '||wTableDifAliqPR||' DIF ';
      wSQL = :wSQL || '      WHERE DIF.BDSESSAO = '||:PRSESSAO;
      wSQL = :wSQL || '      GROUP BY DIF.BDSESSAO, DIF.BDCODEMP, DIF.BDCHAVE, DIF.BDORDEM ';
      wSQL = :wSQL || '     ) DIF ';
      wSQL = :wSQL || 'JOIN '||:wTableItem||' I ON(I.BDCODEMP = DIF.BDCODEMP AND I.BDCHAVE = DIF.BDCHAVE AND I.BDSESSAO = DIF.BDSESSAO AND I.BDORDEM = DIF.BDORDEM) ';
      wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO AND S.BDCODSITNF NOT IN (2, 3, 4, 5)) ';
      wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDREFERENCIA = '||WFIELDREFERENCIA||' AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 219  /*A vista*/ ';
      wSQL = :wSQL || '                                                                                                                WHEN s.BDCONDPGTO = 1 THEN 220  /*Prazo*/ ';
      wSQL = :wSQL || '                                                                                                                WHEN s.BDCONDPGTO = 2 THEN 221  /*Outras*/ ';
      wSQL = :wSQL || '                                                                                                           END) AND C.BDCONTADEBPROV IS NOT NULL AND C.BDCONTACREDPROV IS NOT NULL ) ';
      wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'' AND NAT.BDLANDIFALIQNAT = ''TRUE'') ';
      wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
      wSQL = :wSQL || 'WHERE DIF.BDIMPRECOLHER > 0 ';
      IF (:prTIPOLAN = 'ENT') THEN      
      wSQL = :wSQL || 'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.bdDATAENTRADAENT))) ';
      ELSE
        wSQL = :wSQL || 'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.bdDATAEMISSAO))) ';
      wSQL = :wSQL || 'AND NOT EXISTS( ';
      wSQL = :wSQL || '             SELECT INCO.BDCODINCONSISTENCIA ';
      wSQL = :wSQL || '             FROM VEF_INCON_TMOV'||:prTIPOLAN||' INCO ';
      wSQL = :wSQL || '             WHERE INCO.BDCODEMP = I.BDCODEMP ';
      wSQL = :wSQL || '             AND   INCO.BDCHAVE  = I.BDCHAVE ';
      wSQL = :wSQL || '             AND   INCO.BDSESSAO = I.BDSESSAO ';
      wSQL = :wSQL || '            ); ';
      EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_AUX','9');
    END

  IF ((:PRTIPOLAN = 'ENT') AND ((:PRTIPOINTICMS IN (0)) OR (:PRENQFED IN(1, 2))  )) THEN
    BEGIN
      /*----------------------------------------------------Antecipação---------------------------------------------------------------------*/

      wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, BDCODHIST, BDCODTPHI, bdord) ';
      wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRANTECIPACAO, '|| IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT ',  'S.BDDATAEMISSAO ')||', ANT.BDIMPRECOLHER, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ';
      wSQL = :wSQL || '       ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||', C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODHIST, C.BDCODTPHI, 3 BDORD ';
      wSQL = :wSQL || 'FROM ( ';
      wSQL = :wSQL || '      SELECT ANT.BDSESSAO, ANT.BDCODEMP, ANT.BDCHAVE, ANT.BDORDEM, ';
      wSQL = :wSQL || '             SUM(COALESCE(ANT.BDIMPRECOLHER, 0)) BDIMPRECOLHER ';
      wSQL = :wSQL || '      FROM TMP_VEF_EMP_TMOVENTANTIMP_TEMP ANT ';
      wSQL = :wSQL || '      WHERE ANT.BDSESSAO = '||:PRSESSAO;
      wSQL = :wSQL || '      GROUP BY ANT.BDSESSAO, ANT.BDCODEMP, ANT.BDCHAVE, ANT.BDORDEM ';
      wSQL = :wSQL || '     ) ANT ';
      wSQL = :wSQL || 'JOIN '||:wTableItem||' I ON(I.BDCODEMP = ANT.BDCODEMP AND I.BDCHAVE = ANT.BDCHAVE AND I.BDSESSAO = ANT.BDSESSAO AND I.BDORDEM = ANT.BDORDEM) ';
      wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO AND S.BDCODSITNF NOT IN (2, 3, 4, 5)) ';
      wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDREFERENCIA = '||WFIELDREFERENCIA||' AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 298  /*A vista*/ ';
      wSQL = :wSQL || '                                                                                                                WHEN s.BDCONDPGTO = 1 THEN 299  /*Prazo*/ ';
      wSQL = :wSQL || '                                                                                                                WHEN s.BDCONDPGTO = 2 THEN 300  /*Outras*/ ';
      wSQL = :wSQL || '                                                                                                           END) AND C.BDCONTADEBPROV IS NOT NULL AND C.BDCONTACREDPROV IS NOT NULL) ';
      wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'' AND NAT.BDANTICMS = ''TRUE'') ';
      wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
      wSQL = :wSQL || 'WHERE ANT.BDIMPRECOLHER > 0 ';
      wSQL = :wSQL || 'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.bdDATAENTRADAENT))) ';
      wSQL = :wSQL || 'AND NOT EXISTS( ';
      wSQL = :wSQL || '             SELECT INCO.BDCODINCONSISTENCIA ';
      wSQL = :wSQL || '             FROM VEF_INCON_TMOVENT INCO ';
      wSQL = :wSQL || '             WHERE INCO.BDCODEMP = I.BDCODEMP ';
      wSQL = :wSQL || '             AND   INCO.BDCHAVE  = I.BDCHAVE ';
      wSQL = :wSQL || '             AND   INCO.BDSESSAO = I.BDSESSAO ';
      wSQL = :wSQL || '            ); ';
      EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_AUX','10');

      /*Paraná/Rio Grande do Sul*/
      wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, BDCODHIST, BDCODTPHI, bdord) ';
      wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRANTECIPACAO, '|| IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT ',  'S.BDDATAEMISSAO ')||', ANT.BDVLRANT, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ';
      wSQL = :wSQL || '       ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||', C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODHIST, C.BDCODTPHI, 3 BDORD ';
      wSQL = :wSQL || 'FROM ( ';
      wSQL = :wSQL || '      SELECT ANT.BDSESSAO, ANT.BDCODEMP, ANT.BDCHAVE, ANT.BDORDEM, ';
      wSQL = :wSQL || '             SUM(COALESCE(ANT.BDVLRANT, 0)) BDVLRANT ';
      wSQL = :wSQL || '      FROM TMP_VEF_EMP_TMOVENTANTPR_TEMP ANT ';
      wSQL = :wSQL || '      WHERE ANT.BDSESSAO = '||:PRSESSAO;
      wSQL = :wSQL || '      GROUP BY ANT.BDSESSAO, ANT.BDCODEMP, ANT.BDCHAVE, ANT.BDORDEM ';
      wSQL = :wSQL || '     ) ANT ';
      wSQL = :wSQL || 'JOIN '||:wTableItem||' I ON(I.BDCODEMP = ANT.BDCODEMP AND I.BDCHAVE = ANT.BDCHAVE AND I.BDSESSAO = ANT.BDSESSAO AND I.BDORDEM = ANT.BDORDEM) ';
      wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO AND S.BDCODSITNF NOT IN (2, 3, 4, 5)) ';
      wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDREFERENCIA = '||WFIELDREFERENCIA||' AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 298  /*A vista*/ ';
      wSQL = :wSQL || '                                                                                                                WHEN s.BDCONDPGTO = 1 THEN 299  /*Prazo*/ ';
      wSQL = :wSQL || '                                                                                                                WHEN s.BDCONDPGTO = 2 THEN 300  /*Outras*/ ';
      wSQL = :wSQL || '                                                                                                           END) AND C.BDCONTADEBPROV IS NOT NULL AND C.BDCONTACREDPROV IS NOT NULL ) ';
      wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'' AND NAT.BDANTICMS = ''TRUE'') ';
      wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
      wSQL = :wSQL || 'WHERE ANT.BDVLRANT > 0 ';
      wSQL = :wSQL || 'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.bdDATAENTRADAENT))) ';
      wSQL = :wSQL || 'AND NOT EXISTS( ';
      wSQL = :wSQL || '             SELECT INCO.BDCODINCONSISTENCIA ';
      wSQL = :wSQL || '             FROM VEF_INCON_TMOVENT INCO ';
      wSQL = :wSQL || '             WHERE INCO.BDCODEMP = I.BDCODEMP ';
      wSQL = :wSQL || '             AND   INCO.BDCHAVE  = I.BDCHAVE ';
      wSQL = :wSQL || '             AND   INCO.BDSESSAO = I.BDSESSAO ';
      wSQL = :wSQL || '            ); ';
      EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_AUX','11');

      /*------------------------------------------------Estorno do ICMS----------------------------------------------------------------*/
      IF ((WCREDITOPRESUMIDO = 'TRUE')) THEN
        BEGIN
          wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, BDCODHIST, BDCODTPHI, bdord, bdEMPREENDIMENTOPROVD, bdEMPREENDIMENTOPROVC, bdCODEMPREENDIMENTO) ';
          wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, CICMS.BDCONTADEBPROV BDCONTACREDPROV, I.BDCOMPHIST_VLRICMSESTORNADO, '|| IIF(:PRTIPOLAN = 'ENT', 'S.BDDATAENTRADAENT ',  'S.BDDATAEMISSAO ')||', I.BDVLRICMS, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ';
          wSQL = :wSQL ||        '''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||', C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODHIST, C.BDCODTPHI, 3 BDORD, ';
          wSQL = :wSQL ||        'c.bdEMPREENDIMENTOPROVD, c.bdEMPREENDIMENTOPROVC, '; -- Alt.: Vínculo de Empreendimento nas Saídas #Contábil!
          IF ((:prTIPOLAN = 'SAI') OR (:prTIPOLAN = 'ENT')) THEN  
            wSQL = :wSQL ||              ' s.bdCODEMPREENDIMENTO '; -- Alt.: Vínculo de Empreendimento nas Saídas #Contábil!
          ELSE
            wSQL = :wSQL ||              ' NULL AS bdCODEMPREENDIMENTO ';
          wSQL = :wSQL ||'FROM '||:wTableItem||' I ';
          wSQL = :wSQL ||'JOIN '||:wTable||' S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO) ';
          wSQL = :wSQL ||'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDREFERENCIA = '||WFIELDREFERENCIA||' AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 290 '; /*Estorno Crédito Presumido - A vista*/
          wSQL = :wSQL ||                                                                                                                'WHEN s.BDCONDPGTO = 1 THEN 291 '; /*Estorno Crédito Presumido - Prazo*/
          wSQL = :wSQL ||                                                                                                                'WHEN s.BDCONDPGTO = 2 THEN 292 '; /*Estorno Crédito Presumido - Outras*/
          wSQL = :wSQL ||                                                                                                           'END)) ';
          wSQL = :wSQL ||'JOIN TCONTAS_ONLINE_TEMP CICMS ON(CICMS.BDSESSAO = I.BDSESSAO AND CICMS.BDREFERENCIA = '||WFIELDREFERENCIA||' AND CICMS.BDCODNAT = I.BDCODNAT AND (CICMS.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 112 '; /*ICMS - A vista*/
          wSQL = :wSQL ||                                                                                                                                'WHEN s.BDCONDPGTO = 1 THEN 118 '; /*ICMS - Prazo*/
          wSQL = :wSQL ||                                                                                                                                'WHEN s.BDCONDPGTO = 2 THEN 171 '; /*ICMS - Outras*/
          wSQL = :wSQL ||                                                                                                                            'END)) ';
          wSQL = :wSQL ||'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') ';

                         /*Saída olha data de emissão, ao fazer a contabilização de entrada/serviço tem que ser adaptado para olhar os outros campos de data*/
          wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';              
          wSQL = :wSQL ||'WHERE I.BDSESSAO = '||:PRSESSAO;
          wSQL = :wSQL ||' AND I.BDVLRICMS > 0 ';
          wSQL = :wSQL ||' AND C.BDCONTADEBPROV > 0 and CICMS.BDCONTACREDPROV > 0 ';
          wSQL = :wSQL ||'AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
          wSQL = :wSQL ||'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||IIF((:PRTIPOLAN = 'ENT'), 'bdDATAENTRADAENT', 'BDDATAEMISSAO')||'))) ';
          wSQL = :wSQL ||'AND NOT EXISTS(';
          wSQL = :wSQL ||               'SELECT INCO.BDCODINCONSISTENCIA ';
          wSQL = :wSQL ||               'FROM VEF_INCON_TMOVENT INCO ';
          wSQL = :wSQL ||               'WHERE INCO.BDCODEMP = I.BDCODEMP ';
          wSQL = :wSQL ||               'AND   INCO.BDCHAVE  = I.BDCHAVE ';
          wSQL = :wSQL ||               'AND   INCO.BDSESSAO = I.BDSESSAO';
          wSQL = :wSQL ||              ')';
          EXECUTE STATEMENT :wSQL;
        END
    END
  /*IVA MVA*/
  if (:PRTIPOLAN = 'ENT') then
    BEGIN
       wSQL = 'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdCODEMP, bdCHAVE, bdORDEM, bdSESSAO, bdCHAVE_VSUC, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA,  ';
       wSQL = :wSQL || 'bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdFORMULA, bdCODPLANOONLINE, bdCHAVETITULO, bdCLASSIFBUSCA, bdCLASSIFTITULO, bdCODITEMONLINE, ';
       wSQL = :wSQL || 'bdCHAVECONTA, bdCODHIST, bdCODTPHI, bdORD, bdEMPREENDIMENTOPROVD, bdEMPREENDIMENTOPROVC, bdCODEMPREENDIMENTO) ';

       wSQL = :wSQL || 'SELECT i.bdCODEMP, i.bdEDITCHAVE, i.bdORDEM, i.bdSESSAO, i.bdCHAVE_VSUC, c.bdCODPLAPADRAO, NULL AS bdCODUSU, c.bdCONTADEBPROV, c.bdCONTACREDPROV, i.BDCOMPHIST_VLRCONTAB, S.'||wfielddata||', i.BDMVAIVA, ';
       wSQL = :wSQL || '100 AS bdTIPOLAN, s.bdNUMDOCINI, NULL AS bdTRANSACAO, ''TRUE'' AS bdTRANFECHADA, c.bdFORMULA, '||:PRCODPLANOONLINE||', c.bdCHAVECONF, c.bdCLASSIFICACAO, c.bdCLASS_TITULO, c.bdCODITEMONLINE, c.bdCHAVE, c.bdCODHIST, c.bdCODTPHI, 3 AS bdORD, ';
       wSQL = :wSQL || 'c.bdEMPREENDIMENTOPROVD, c.bdEMPREENDIMENTOPROVC, s.bdCODEMPREENDIMENTO ';

       wSQL = :wSQL || 'FROM '||:wTableItem||' i ';
       wSQL = :wSQL || 'JOIN '||:wTable||' s ON (s.bdCODEMP = i.bdCODEMP AND s.bdCHAVE = i.bdCHAVE AND s.bdSESSAO = i.bdSESSAO) ';
       wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP c ON (c.bdSESSAO = i.bdSESSAO AND c.bdCODNAT = i.bdCODNAT AND (c.bdCODITEMONLINE = CASE WHEN s.bdCONDPGTO = 0 THEN 666 '; /*A vista*/
       wSQL = :wSQL ||                                                                                                                  'WHEN s.bdCONDPGTO = 1 THEN 667 '; /*Prazo*/
       wSQL = :wSQL ||                                                                                                                  'WHEN s.bdCONDPGTO = 2 THEN 668 '; /*Outras*/
       wSQL = :wSQL || 'END)) ';
       wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT AND nat.bdCONTABILIZA = ''TRUE'') ';
                          /*Sa??da olha data de emiss??o, entrada/servi??o tem que ser adaptado para olhar os outros campos de data*/      
       wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO ic ON (ic.bdCODEMP = i.bdCODEMP AND ic.bdCODSIS = '||:wEF||') ';
       wSQL = :wSQL || 'WHERE i.bdSESSAO = '||:PRSESSAO;
       wSQL = :wSQL || ' AND i.BDMVAIVA > 0 ';
       wSQL = :wSQL || ' AND c.bdCONTADEBPROV IS NOT NULL AND c.bdCONTACREDPROV IS NOT NULL ';
--          wSQL = :wSQL || ' AND s.bdCODSITNF NOT IN (2, 3, 4, 5) ';
       wSQL = :wSQL || ' AND ((ic.bdCODEMP IS NULL) OR (ic.bdDATA IS NULL) OR ((ic.bdCODEMP IS NOT NULL) AND (ic.bdDATA <= S.'||wfielddata||'))) ';
       EXECUTE STATEMENT :wSQL;
       EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_AUX','12');
    END
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO_AUX','13');
END
^

create or alter procedure SP_CRIA_PRE_CONTABILIZACAO (
    PRSESSAO integer,
    PRCODPLANOONLINE integer,
    PRENQFED integer,
    PRCODCONFIRLP integer,
    PRTIPOLAN varchar(5),
    PRCODCONFDIMESC integer = 0,
    PRFORMATRIBUTACAO integer = 0)
as
declare variable WTIPOINTCONTRETIRTOM integer;
declare variable WTIPOINTCOF integer;
declare variable WTIPOINTPIS integer;
declare variable WTIPOINTICMS integer;
declare variable WTIPOINTIPI integer;
declare variable WTABLE varchar(31);
declare variable WTABLEITEM varchar(31);
declare variable WTABLERET varchar(31);
declare variable WTABLEINCON varchar(31);
declare variable WTABLEFUNRURAL varchar(32);
declare variable WSQL varchar(10000);
declare variable WEF integer;
declare variable WTIPOINTDESC integer;
declare variable WTIPOINTCONTRETPCC integer;
declare variable WTIPOINTCONTRETIR integer;
declare variable WCODITEMDESC integer;
declare variable WCONTAPROV varchar(32);
declare variable WTABLERATEIO varchar(31);
declare variable WCAMPOINSS varchar(33);
declare variable WTABLEINSS varchar(31);
declare variable WTIPLAN integer;
declare variable WTABLEPR varchar(31);
declare variable WIGONRAFUNRURAL DM_BOOLEAN;
declare variable WFIELDDATA varchar(32);
declare variable WTIPOAPURACAORETIR integer;
declare variable WCODEMP integer;
declare variable WDATA date;
declare variable WCONTABGUIAMUN DM_BOOLEAN;
declare variable WTIPOINTPISLP integer;
declare variable WTIPOINTCOFLP integer;
declare variable WORGAOPUBLICO varchar(5);
declare variable WTIPOINTICMSORIG integer;
BEGIN
  wTable         = '';
  wTableItem     = '';
  WTablePR = '';
  wTableRet      = '';
  wTableIncon    = '';
  wTableFunRural = '';
  wTableINSS     = '';
  wEF            = 3;
  wTableRateio   = '';
  wTipLan        = NULL;
EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO','1');
  DELETE FROM TMP_TLANC_CONTABILIZACAO_TEMP WHERE BDSESSAO = :PRSESSAO;
EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO','2');
  PRTIPOLAN = UPPER(:PRTIPOLAN);
  wCampoINSS  = 'INSS.BDRETINSS';       
  wfielddata  = 'BDDATAEMISSAO';
  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTable      = 'TMP_VEF_EMP_TMOVSAI_TEMP';
      wTableItem  = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
      WTablePR = 'TMP_VEF_EMP_TMOVSAIPR_TEMP';
      wTableRet   = 'TMP_VEF_EMP_TMOVSAIRET_TEMP';
      wTableIncon = 'VEF_INCON_TMOVSAI';
      wTableFunRural = 'TMP_VEF_TMOVSAIFUNRURAL_TEMP';
      wTableINSS     = 'TMP_VEF_EMP_TMOVSAIDED_TEMP';
      wCodItemDesc   =  88;
      wContaProv = 'BDCONTADEBPROV';
    END
  ELSE
  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTable      = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItem  = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      WTablePR = 'TMP_VEF_EMP_TMOVENTPR_TEMP';
      wTableRet   = 'TMP_VEF_EMP_TMOVENTRET_TEMP';
      wTableIncon = 'VEF_INCON_TMOVENT';
      wTableFunRural = 'TMP_VEF_TMOVENTFUNRURAL_TEMP';
      wCodItemDesc   =  81;
      wContaProv  = 'BDCONTACREDPROV';
      wTableINSS  = 'TMP_VEF_EMP_TMOVENTDED_TEMP'; 
      wfielddata = 'BDDATAENTRADAENT';
    END
  ELSE
  IF ((:PRTIPOLAN = 'SERE') OR (:PRTIPOLAN = 'SERR')) THEN
    BEGIN
      wTable      = 'TMP_VEF_EMP_TMOVSER_TEMP';
      wTableItem  = 'TMP_VEF_EMP_TMOVSERITENS_TEMP';
      wTableRet   = 'TMP_VEF_EMP_TMOVSERRET_TEMP';
      WTablePR = 'TMP_VEF_EMP_TMOVSERPR_TEMP';
      wTableIncon = 'VEF_INCON_TMOVSER';
      wTableINSS  = 'TMP_VEF_EMP_TMOVSERDED_TEMP';
      wTableRateio= 'TMP_VEF_EMP_TMOVRATSER_TEMP';

      IF (:PRTIPOLAN = 'SERE') THEN
        BEGIN
          wTipLan      = 0;
          wCodItemDesc = 96;
          wContaProv   = 'BDCONTADEBPROV';
        END
      ELSE
        BEGIN
          wTipLan      = 1;
          wCodItemDesc = 104;
          wContaProv   = 'BDCONTACREDPROV';
        END
    END
  ELSE
  IF (:PRTIPOLAN = 'REDZ') THEN
    BEGIN
      EXECUTE PROCEDURE SP_CRIA_PRE_CONTABILIZACAO_REDZ(:PRSESSAO, :PRCODPLANOONLINE, :PRENQFED, :PRFORMATRIBUTACAO);
      DELETE FROM TMP_TCFOP_TMOV WHERE BDSESSAO = :PRSESSAO;
      DELETE FROM TCONTAS_ONLINE_TEMP WHERE BDSESSAO = :PRSESSAO;
      EXIT;
    END
  ELSE
    BEGIN     
      DELETE FROM TMP_TCFOP_TMOV WHERE BDSESSAO = :PRSESSAO;
      DELETE FROM TCONTAS_ONLINE_TEMP WHERE BDSESSAO = :PRSESSAO;
    EXIT;
    END
EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO','3');
  IF ((:PRTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERE') OR (:PRTIPOLAN = 'SERR')) THEN
    BEGIN -- Alt.: #176233
      wSQL =          'UPDATE '||:wTable||' s ';
      wSQL = :wSQL || 'SET s.bdPRIMEIRAORDEM = (SELECT FIRST 1 i.bdORDEM ';
      wSQL = :wSQL || ' FROM '||:wTableItem||' i ';
      wSQL = :wSQL || ' JOIN VEF_BASE_TNATOP n ON(n.bdCODNAT = i.bdCODNAT AND n.bdCONTABILIZA = ''TRUE'') ';
      wSQL = :wSQL || ' WHERE i.bdCODEMP = s.bdCODEMP ';
      wSQL = :wSQL || ' AND i.bdCHAVE  = s.bdCHAVE ';
      wSQL = :wSQL || ' AND i.bdSESSAO = s.bdSESSAO ';
      wSQL = :wSQL || ' ORDER BY i.bdORDEM) ';
      wSQL = :wSQL || ' WHERE BDSESSAO = '||:PRSESSAO;
      EXECUTE STATEMENT :wSQL;
    END

  wOrgaoPublico = 'FALSE';
  IF ((:PRTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE'))  THEN
    wOrgaoPublico = (SELECT bdvalor FROM TPARGER  WHERE bdcampo = 'bdIRRFOrgaoPublico');

  SELECT COALESCE(o.bdtipointcofins, 0), COALESCE(o.bdtipointpis, 0), COALESCE(o.bdtipointicms, 0), COALESCE(o.bdtipointipi, 0), COALESCE(o.bdtipointdesconto, 0), COALESCE(o.bdREGCONTRETPCC, 0),
         COALESCE(o.bdREGCONTRETIR, 0),
         COALESCE(o.BDREGCONTRETIRTOM, 0),
         COALESCE(o.BDTIPOINTPISLP, 0), COALESCE(o.BDTIPOINTCOFINSLP, 0)
  FROM TPLANO_CONF_ONLINE O WHERE O.BDCODPLANOONLINE = :PRCODPLANOONLINE
  INTO :wTipoIntCof, :wTipoIntPis, :wTipoIntIcms, :wTipoIntIpi, :wTipoIntDesc, :wTIPOINTCONTRETPCC, :wTIPOINTCONTRETIR, :wTIPOINTCONTRETIRTOM, :WTIPOINTPISLP, :WTIPOINTCOFLP;

  wtipointicmsorig = wTipoIntIcms;  /*#147832 - grava o tipo de integração ICMS original, para no final passar para procedure auxiliar*/ 

 IF ((:PRTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE') OR (:PRTIPOLAN = 'REDZ')) THEN
   wTipoApuracaoRetIR = :wTipoIntContRetIR;
 ELSE IF ((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
   wTipoApuracaoRetIR = :wTipoIntContRetIRTOM;
  IF (:PRTIPOLAN = 'SAI') THEN
        SELECT FIRST 1 BDCODEMP, BDDATAEMISSAO FROM TMP_VEF_EMP_TMOVSAI_TEMP WHERE BDSESSAO = :PRSESSAO AND BDCODEMP IS NOT NULL INTO :WCODEMP, :WDATA;
    ELSE IF (:PRTIPOLAN = 'ENT') THEN
        SELECT FIRST 1 BDCODEMP, BDDATAENTRADAENT FROM TMP_VEF_EMP_TMOVENT_TEMP WHERE BDSESSAO = :PRSESSAO AND BDCODEMP IS NOT NULL INTO :WCODEMP, :WDATA;
  IF ((wTipoIntIcms = 0) or (:PRENQFED NOT IN(3))) THEN
    SELECT FIRST 1 FED.BDCONTABGUIAMUN FROM TEMPRESAS_REF EMPREF
    LEFT JOIN VEF_BASE_TEMPPARFED FED ON (FED.BDCODEMP = EMPREF.BDCODEMP AND FED.BDREFEMP = EMPREF.BDREFEMP)
    LEFT JOIN TENQFED ENQ ON (ENQ.BDCODEMP = EMPREF.BDCODEMP AND ENQ.BDREFEMP = EMPREF.BDREFEMP)
    WHERE EMPREF.BDCODEMP = :WCODEMP AND EMPREF.BDREFEMP <= (SUBSTRING(:WDATA FROM 1 FOR 4) || SUBSTRING(:WDATA FROM 6 FOR 2))
    ORDER BY EMPREF.BDREFEMP DESC
    INTO :WCONTABGUIAMUN;
  IF ((:PRENQFED NOT IN(3)) AND (:PRTIPOLAN = 'SAI')) THEN
    BEGIN
      wTipoIntIpi = 0;
      wTipoIntCof = 0;
      wTipoIntPis = 0;
      wTipoIntIcms= 0;
    END
  IF ((:PRENQFED NOT IN(3)) AND (:PRTIPOLAN = 'ENT')) THEN
    BEGIN
      wTipoIntIcms= 0; -- Alt.: #166221 - Quando for entrada e SN deve contabilizar.
    END
   WIGONRAFUNRURAL = 'FALSE';
   SELECT FIRST 1 'TRUE'
   FROM TCONTAS_ONLINE_TEMP o
   WHERE o.bdCODITEMONLINE = 301
   INTO WIGONRAFUNRURAL;
EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO','4');

  /*Valor cont?bil*/
  wSQL = 'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito,bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, BDCODHIST, BDCODTPHI, bdord, ';
  wSQL = :wSQL || ' bdEMPREENDIMENTOPROVD, bdEMPREENDIMENTOPROVC, bdCODEMPREENDIMENTO,bdcodimovrur, bdtipmov, bdctacor, bdcodter, bdtipdoc, bdtiplan,BDTIPOPE, BDCODEMPSCP) ';
  wSQL = :wSQL || 'SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE, MOV.BDORDEM, MOV.BDSESSAO, MOV.BDCHAVE_VSUC, MOV.BDCODPLAPADRAO, MOV.BDCODUSU, ';
  /*Quanto tem reten??o s? contabiliza com a conta cr?dito or d?bito*/
  IF ((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
    wSQL = :wSQL || 'mov.BDCONTADEBPROV, IIF((MOV.BDTOTALRET = 0) OR ((COALESCE(MOV.BDRATEIARET,''FALSE'') = ''FALSE'') AND (MOV.BDPRIMEIRAORDEM <> MOV.BDORDEM)), MOV.BDCONTACREDPROV, NULL) BDCONTACREDPROV,  ';
  ELSE
  IF ((:PRTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE')) THEN
    wSQL = :wSQL || 'IIF((MOV.BDTOTALRET = 0) OR ((COALESCE(MOV.BDRATEIARET,''FALSE'') = ''FALSE'') AND (MOV.BDPRIMEIRAORDEM <> MOV.BDORDEM)), MOV.BDCONTADEBPROV, NULL) BDCONTADEBPROV, MOV.BDCONTACREDPROV,  ';
  wSQL = :wSQL || 'MOV.BDCOMPHIST_VLRCONTAB, ';
  wSQL = :wSQL || 'MOV.'||WFIELDDATA||', ';
  wSQL = :wSQL || ' MOV.BDVLRCONTAB, MOV.BDTIPOLAN, MOV.BDNUMDOCINI, MOV.BDTRANSACAO, MOV.BDTRANFECHADA, MOV.BDFORMULA, MOV.BDCODPLANOONLINE, MOV.BDCHAVECONF, ';
  wSQL = :wSQL || 'MOV.BDCLASSIFICACAO, MOV.BDCLASS_TITULO, MOV.BDCODITEMONLINE, MOV.BDCHAVELAN, MOV.BDCODHIST, MOV.BDCODTPHI, 1 BDORD, ';
  wSQL = :wSQL || 'mov.bdEMPREENDIMENTOPROVD, mov.bdEMPREENDIMENTOPROVC, mov.bdCODEMPREENDIMENTO, ';
  wSQL = :wSQL || 'MOV.bdcodimovrur, MOV.bdtipmov, MOV.bdctacor, MOV.bdcodter, MOV.bdtipdoc, MOV.bdtiplan ';
  IF ((:prTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
    wSQL = :wSQL ||  ', 1 BDTIPOPE ';
  ELSE
    wSQL = :wSQL ||  ', 0 BDTIPOPE ';
  wSQL = :wSQL || ',MOV.BDCODEMPSCP ';
  wSQL = :wSQL || 'FROM ( ';
  wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDCHAVE, I.BDORDEM, I.BDSESSAO, MOV.BDPRIMEIRAORDEM, MOV.BDRATEIARET, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRCONTAB, mov.BDDATAEMISSAO, I.BDVLRCONTAB, 100 BDTIPOLAN/*100 - Escrita fiscal*/, mov.BDNUMDOCINI, NULL BDTRANSACAO, ';
  wSQL = :wSQL || '''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE AS BDCHAVELAN, C.BDCODHIST, C.BDCODTPHI, mov.BDDESCONTONOTA,  ';
  wSQL = :wSQL || 'c.bdEMPREENDIMENTOPROVD, c.bdEMPREENDIMENTOPROVC, ';
  IF ((:prTIPOLAN = 'SAI') OR (:prTIPOLAN = 'ENT')) THEN  
    wSQL = :wSQL || ' mov.bdCODEMPREENDIMENTO, ';
  ELSE
    wSQL = :wSQL || ' NULL AS bdCODEMPREENDIMENTO, ';
  wSQL = :wSQL || 'PR.bdcodimovrur, pr.bdtipmov, pr.bdctacor, pr.bdcodter, pr.bdtipdoc, pr.bdtiplan, ';
  wSQL = :wSQL || '(';
  -- Alt.: #224292
  wSQL = :wSQL || 'IIF((('||:wTIPOINTCONTRETPCC||'=0) OR (mov.bdCONDPGTO <> 1)),COALESCE(R.BDVLRPIS, 0) + COALESCE(R.BDVLRCOFINS, 0) + COALESCE(R.BDVLRCSOCIAL, 0),0) + ';
  IF (UPPER(wOrgaoPublico) = 'TRUE') THEN
    wSQL = :wSQL || 'IIF(((IIF(TER.BDORGAOPUBLICO = TRUE,1,'||:wTipoApuracaoRetIR||')=0) OR (mov.bdCONDPGTO <> 1)),COALESCE(R.BDVLRIR, 0),0) + ';
  ELSE
    wSQL = :wSQL || 'IIF((('||:wTipoApuracaoRetIR||'=0) OR (mov.bdCONDPGTO <> 1)),COALESCE(R.BDVLRIR, 0),0) + ';

  wSQL = :wSQL || 'COALESCE('||:wCampoINSS||', 0) + COALESCE(R.BDISSRET, 0) + COALESCE(INSS.BDVLRAPOS15, 0) + COALESCE(INSS.BDVLRAPOS20, 0) + COALESCE(INSS.BDVLRAPOS25, 0) ';

  IF (:wTableFunRural <> '') THEN
    BEGIN                      
      IF (:PRTIPOLAN = 'SAI') THEN
        BEGIN
          IF (:WIGONRAFUNRURAL <> 'TRUE') THEN
        wSQL = :wSQL || ' + COALESCE(fr.bdVLRFUNRURAL, 0) + COALESCE(fr.bdVLRGILRAT, 0) + COALESCE(fr.bdVLRSENAR, 0) ';
        END
      ELSE
        wSQL = :wSQL || ' + COALESCE(fr.bdVLRFUNRURAL, 0) + COALESCE(fr.bdVLRGILRAT, 0) + COALESCE(fr.BDVLRFPAS, 0) ';
    END
  wSQL = :wSQL || ') BDTOTALRET ';
  wSQL = :wSQL || IIF(:PRTIPOLAN = 'ENT', ',MOV.BDDATAENTRADAENT ',  '');
  wSQL = :wSQL || ',(SELECT FIRST 1 scp.bdCODEMPSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = i.bdCODEMP AND scp.bdCODSCP = i.bdCODSCP AND ';
  wSQL = :wSQL ||   '((scp.bdDATAINICIAL <= mov.bdDATAEMISSAO AND scp.bdDATAFINAL IS NULL) OR (mov.bdDATAEMISSAO BETWEEN scp.bdDATAINICIAL AND scp.bdDATAFINAL))) ';
  wSQL = :wSQL || 'FROM '||:wTableItem||' I ';

  IF (:wTipLan IS NOT NULL) THEN
    wSQL = :wSQL || 'JOIN '||:wTable||' mov ON(mov.BDCODEMP = I.BDCODEMP AND mov.BDCHAVE = I.BDCHAVE AND mov.BDSESSAO = I.BDSESSAO AND MOV.BDTIPLAN = '||:wTipLan||') ';
  ELSE
    wSQL = :wSQL || 'JOIN '||:wTable||' mov ON(mov.BDCODEMP = I.BDCODEMP AND mov.BDCHAVE = I.BDCHAVE AND mov.BDSESSAO = I.BDSESSAO) ';

  IF (wTableRateio <> '') THEN
    wSQL = :wSQL || 'left outer join '||wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) '; -- Rateio v??o fazer contabiliza????o pr??pria e n??o aqui
  IF (UPPER(wOrgaoPublico) = 'TRUE') THEN
    BEGIN
      wSQL = :wSQL || ' left outer join(select BDCODTER, RF2.BDORGAOPUBLICO, RF2.BDCGCTER, RF2.BDNOMETER, RF2.BDREFEMP ';
      wSQL = :wSQL || ' from TTERCEIRO_REF RF2 ';
      wSQL = :wSQL || ' where RF2.BDREFEMP = coalesce((select first 1 BDREFEMP ';
      wSQL = :wSQL || ' from TTERCEIRO_REF RF3 ';
      wSQL = :wSQL || ' where RF3.BDCODTER = RF2.BDCODTER and ';
      wSQL = :wSQL || ' RF3.BDREFEMP <= substring(CURRENT_DATE from 1 for 4) || substring(CURRENT_DATE from 6 for 2) ';
      wSQL = :wSQL || ' order by RF3.BDREFEMP desc), (select first 1 BDREFEMP ';
      wSQL = :wSQL || ' from TTERCEIRO_REF RF3 ';
      wSQL = :wSQL || ' where RF3.BDCODTER = RF2.BDCODTER ';
      wSQL = :wSQL || ' order by RF3.BDCODTER, RF3.BDREFEMP))) TER on (TER.BDCODTER = MOV.BDCODTER) ';
    END
  wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN mov.BDCONDPGTO = 0 THEN 111 '; /*Valor cont?bil - A vista*/
  wSQL = :wSQL || 'WHEN mov.BDCONDPGTO = 1 THEN 117 '; /*Valor cont?bil - Prazo*/
  wSQL = :wSQL || 'WHEN mov.BDCONDPGTO = 2 THEN 170 '; /*Valor cont?bil - Outras*/
  wSQL = :wSQL || 'END) AND C.BDREFERENCIA = EXTRACT(YEAR FROM mov.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM mov.'||WFIELDDATA||')) ';
  wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') ';

  IF (:wTipoIntDesc = 0) THEN /*0 - Nota a nota*/
    wSQL = :wSQL || 'LEFT OUTER JOIN TCONTAS_ONLINE_TEMP CD ON(CD.BDSESSAO = I.BDSESSAO AND CD.BDCODITEMONLINE = '||:wCodItemDesc||' AND CD.'||wContaProv||' IS NOT NULL) '
    || ' AND CD.BDREFERENCIA = EXTRACT(YEAR FROM mov.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM mov.'||WFIELDDATA||')';
  ELSE
    BEGIN /*1 - Nota a nota por CFOP*/
      wSQL = :wSQL || 'LEFT OUTER JOIN TCONTAS_ONLINE_TEMP CD ON(CD.BDSESSAO = I.BDSESSAO  AND CD.BDCODNAT = I.BDCODNAT AND CD.BDCODITEMONLINE = (CASE WHEN mov.BDCONDPGTO = 0 THEN 243 ';
      wSQL = :wSQL || 'WHEN mov.BDCONDPGTO = 1 THEN 244 ';
      wSQL = :wSQL || 'WHEN mov.BDCONDPGTO = 2 THEN 245 ';
      wSQL = :wSQL || 'END) AND CD.'||wContaProv||' IS NOT NULL AND CD.BDREFERENCIA = EXTRACT(YEAR FROM mov.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM mov.'||WFIELDDATA||')) ';
    END

  wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTableRet||' R ON(R.BDCODEMP = I.BDCODEMP AND R.BDCHAVE = I.BDCHAVE AND R.BDSESSAO = I.BDSESSAO) ';

  IF (:wTableINSS <> '') THEN
    wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTableINSS||' INSS ON(INSS.BDCODEMP = I.BDCODEMP AND INSS.BDCHAVE = I.BDCHAVE AND INSS.BDSESSAO = I.BDSESSAO) ';

  IF (:wTableFunRural <> '') THEN
    wSQL = :wSQL || 'left outer join '||:wTableFunRural||' fr on (fr.bdCODEMP = i.bdCODEMP and fr.bdCHAVE = i.bdCHAVE and fr.bdSESSAO = i.bdSESSAO) ';

  wSQL = :wSQL || 'left outer join '||:WTablePR||' PR on (PR.bdCODEMP = i.bdCODEMP and PR.bdCHAVE = i.bdCHAVE and PR.BDORDEM = I.BDORDEM and PR.bdSESSAO = i.bdSESSAO) ';

  wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
  wSQL = :wSQL || 'WHERE I.BDSESSAO = '||:PRSESSAO;

  IF (wTableRateio <> '') THEN
    wSQL = :wSQL || ' and rat.bdCODEMP IS NULL ';

  IF (:wTipoIntDesc = 0) THEN /*0 - Nota a nota*/
    wSQL = :wSQL || ' AND (((mov.BDDESCONTONOTA = 0) OR (mov.BDDESCONTONOTA IS NULL)) OR (CD.BDCHAVE IS NULL)) ';
  ELSE /*1 - Nota a nota por CFOP*/
    wSQL = :wSQL || ' AND (((I.BDDESCONTO = 0) OR (I.BDDESCONTO IS NULL)) OR (CD.BDCHAVE IS NULL)) ';

  wSQL = :wSQL || 'AND mov.BDCODSITNF NOT IN (2, 3, 4, 5) ';   
  wSQL = :wSQL || 'AND I.BDVLRCONTAB > 0 ';
  wSQL = :wSQL || 'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= mov.'||wfielddata||'))) ';
  wSQL = :wSQL || 'AND NOT EXISTS( ';
  wSQL = :wSQL || 'SELECT INCO.BDCODINCONSISTENCIA ';
  wSQL = :wSQL || 'FROM '||:wTableIncon||' INCO ';
  wSQL = :wSQL || 'WHERE INCO.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL || 'AND   INCO.BDCHAVE  = I.BDCHAVE ';
  wSQL = :wSQL || 'AND   INCO.BDSESSAO = I.BDSESSAO ';
  wSQL = :wSQL || ') ';
  wSQL = :wSQL || ') MOV ';

  EXECUTE STATEMENT :wSQL;
EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO','5');
  /*Valor cont?bil de quando o lan?amento tem desconto*/
  wSQL =          'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, BDCODHIST, BDCODTPHI, bdord, ';
  wSQL = :wSQL || '                                          bdEMPREENDIMENTOPROVD, bdEMPREENDIMENTOPROVC, bdCODEMPREENDIMENTO,bdcodimovrur, bdtipmov, bdctacor, bdcodter, bdtipdoc, bdtiplan,BDTIPOPE,BDCODEMPSCP) ';
  wSQL = :wSQL || 'SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE, MOV.BDORDEM, MOV.BDSESSAO, MOV.BDCHAVE_VSUC, MOV.BDCODPLAPADRAO, MOV.BDCODUSU, ';

  IF ((:prTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
    wSQL = :wSQL || 'NULL BDCONTADEBPROV, mov.BDCONTACREDPROV, ';
  ELSE
  IF ((:prTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE')) THEN
    wSQL = :wSQL || 'MOV.BDCONTADEBPROV, NULL BDCONTACREDPROV, ';

  wSQL = :wSQL || 'MOV.BDCOMPHIST_VLRCONTAB, ';

  wSQL = :wSQL || 'MOV.'||WFIELDDATA||', ';

  wSQL = :wSQL || 'MOV.BDVLRCONTAB, MOV.BDTIPOLAN, MOV.BDNUMDOCINI, MOV.BDTRANSACAO, MOV.BDTRANFECHADA, MOV.BDFORMULA, MOV.BDCODPLANOONLINE, MOV.BDCHAVECONF, MOV.BDCLASSIFICACAO, MOV.BDCLASS_TITULO, MOV.BDCODITEMONLINE, MOV.BDCHAVELAN, MOV.BDCODHIST, MOV.BDCODTPHI, 1 BDORD, ';

  IF ((:prTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
    wSQL = :wSQL || 'NULL bdEMPREENDIMENTOPROVD, mov.bdEMPREENDIMENTOPROVC, ';
  ELSE
  IF ((:prTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE')) THEN
    wSQL = :wSQL || 'mov.bdEMPREENDIMENTOPROVD,null bdEMPREENDIMENTOPROVC, ';

  wSQL = :wSQL || ' mov.bdCODEMPREENDIMENTO, ';
  wSQL = :wSQL || 'MOV.bdcodimovrur, MOV.bdtipmov, MOV.bdctacor, MOV.bdcodter, MOV.bdtipdoc, MOV.bdtiplan ';
  IF ((:prTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
    wSQL = :wSQL || ', 1 BDTIPOPE ';
  ELSE
    wSQL = :wSQL || ', 0 BDTIPOPE ';
  wSQL = :wSQL || ', MOV.BDCODEMPSCP ';
  wSQL = :wSQL || 'FROM (';
  wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDCHAVE,I.BDORDEM, I.BDSESSAO, COALESCE(s.bdPRIMEIRAORDEM,mo.bdORDEM,1) AS bdPRIMEIRAORDEM, '; -- Alt.: #144147 - Quando a primeira CFOP n?o contabilizava, n?o carregava a nota, por isso foi criado o "mo", minima ordem, para buscar a primeira que contabiliza...
  wSQL = :wSQL || 'NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRCONTAB, S.BDDATAEMISSAO, I.BDVLRCONTAB, 100 BDTIPOLAN/*100 - Escrita fiscal*/, S.BDNUMDOCINI, NULL BDTRANSACAO, ';
  wSQL = :wSQL || '''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, S.BDDESCONTONOTA, C.BDCHAVE AS BDCHAVELAN, C.BDCODHIST, C.BDCODTPHI, ';
  wSQL = :wSQL || 'c.bdEMPREENDIMENTOPROVD, c.bdEMPREENDIMENTOPROVC, ';
  IF ((:prTIPOLAN = 'SAI') OR (:prTIPOLAN = 'ENT')) THEN  
    wSQL = :wSQL || ' s.bdCODEMPREENDIMENTO, ';
  ELSE
    wSQL = :wSQL || ' NULL AS bdCODEMPREENDIMENTO, ';

  wSQL = :wSQL || 'PR.bdcodimovrur, pr.bdtipmov, pr.bdctacor, pr.bdcodter, pr.bdtipdoc, pr.bdtiplan, ';

  wSQL = :wSQL || '(';
  IF (:wTIPOINTCONTRETPCC = 0) THEN
    wSQL = :wSQL || 'COALESCE(R.BDVLRPIS, 0) + COALESCE(R.BDVLRCOFINS, 0) + COALESCE(R.BDVLRCSOCIAL, 0) + ';
  IF (:wTipoApuracaoRetIR = 0) THEN
    wSQL = :wSQL || 'COALESCE(R.BDVLRIR, 0) + ';
  wSQL = :wSQL || 'COALESCE('||:wCampoINSS||', 0) + COALESCE(R.BDISSRET, 0) + COALESCE(INSS.BDVLRAPOS15, 0) + COALESCE(INSS.BDVLRAPOS20, 0) + COALESCE(INSS.BDVLRAPOS25, 0)) BDTOTALRET ';

  wSQL = :wSQL || IIF(:PRTIPOLAN = 'ENT', ',S.BDDATAENTRADAENT  ',  '');
  wSQL = :wSQL || ',(SELECT FIRST 1 scp.bdCODEMPSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = i.bdCODEMP AND scp.bdCODSCP = i.bdCODSCP AND ';
  wSQL = :wSQL ||   '((scp.bdDATAINICIAL <= s.bdDATAEMISSAO AND scp.bdDATAFINAL IS NULL) OR (s.bdDATAEMISSAO BETWEEN scp.bdDATAINICIAL AND scp.bdDATAFINAL))) ';
  wSQL = :wSQL || 'FROM '||:wTableItem||' I ';
  wSQL = :wSQL || 'JOIN (SELECT i.bdCODEMP, i.bdCHAVE, i.bdSESSAO, MIN(i.bdORDEM) AS bdORDEM ';
  wSQL = :wSQL ||       'FROM '||:wTableItem||' i ';
  wSQL = :wSQL ||       'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT AND nat.bdCONTABILIZA = ''TRUE'') ';
  wSQL = :wSQL ||       'GROUP BY i.bdCODEMP, i.bdCHAVE, i.bdSESSAO ';
  wSQL = :wSQL ||       ') mo ON (mo.bdCODEMP = i.bdCODEMP AND mo.bdCHAVE = i.bdCHAVE AND mo.bdSESSAO = i.bdSESSAO) ';

  IF (:wTipLan IS NOT NULL) THEN
    wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO AND S.BDTIPLAN = '||:wTipLan||') ';
  ELSE
    wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO) ';

  IF (wTableRateio <> '') THEN
    wSQL = :wSQL || 'left outer join '||wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) ';

  IF (:wTableFunRural <> '') THEN
    wSQL = :wSQL || 'left outer join '||:wTableFunRural||' fr on (fr.bdCODEMP = i.bdCODEMP and fr.bdCHAVE = i.bdCHAVE and fr.bdSESSAO = i.bdSESSAO) ';

  wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 111 '; /*Valor cont?bil - A vista*/
  wSQL = :wSQL || 'WHEN s.BDCONDPGTO = 1 THEN 117 '; /*Valor cont?bil - Prazo*/
  wSQL = :wSQL || 'WHEN s.BDCONDPGTO = 2 THEN 170 '; /*Valor cont?bil - Outras*/
  wSQL = :wSQL || 'END) AND C.BDREFERENCIA = EXTRACT(YEAR FROM s.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM s.'||WFIELDDATA||')) ';
  wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') ';

  IF (:wTipoIntDesc = 0) THEN /*0 - Nota a nota*/
    wSQL = :wSQL || 'LEFT OUTER JOIN TCONTAS_ONLINE_TEMP CD ON(CD.BDSESSAO = I.BDSESSAO AND CD.BDCODITEMONLINE = '||:wCodItemDesc||' AND CD.'||wContaProv||' IS NOT NULL '
    || 'AND CD.BDREFERENCIA = EXTRACT(YEAR FROM s.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM s.'||WFIELDDATA||')) ';
  ELSE
    BEGIN /*1 - Nota a nota por CFOP*/
      wSQL = :wSQL || 'LEFT OUTER JOIN TCONTAS_ONLINE_TEMP CD ON(CD.BDSESSAO = I.BDSESSAO AND CD.BDCODNAT = I.BDCODNAT AND CD.BDCODITEMONLINE = (CASE WHEN S.BDCONDPGTO = 0 THEN 243 ';
      wSQL = :wSQL || 'WHEN S.BDCONDPGTO = 1 THEN 244 ';
      wSQL = :wSQL || 'WHEN S.BDCONDPGTO = 2 THEN 245 ';
      wSQL = :wSQL || 'END) AND CD.'||wContaProv||' IS NOT NULL AND CD.BDREFERENCIA = EXTRACT(YEAR FROM S.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM S.'||WFIELDDATA||')) ';
    END
  wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTableRet||' R ON(R.BDCODEMP = I.BDCODEMP AND R.BDCHAVE = I.BDCHAVE AND R.BDSESSAO = I.BDSESSAO) ';
  IF (:wTableINSS <> '') THEN
    wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTableINSS||' INSS ON(INSS.BDCODEMP = I.BDCODEMP AND INSS.BDCHAVE = I.BDCHAVE AND INSS.BDSESSAO = I.BDSESSAO) ';

  wSQL = :wSQL || 'left outer join '||:WTablePR||' PR on (PR.bdCODEMP = i.bdCODEMP and PR.bdCHAVE = i.bdCHAVE and PR.bdSESSAO = i.bdSESSAO) ';

  wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
  wSQL = :wSQL || 'WHERE I.BDSESSAO = '||:PRSESSAO;

  IF (wTableRateio <> '') THEN
    wSQL = :wSQL || ' and rat.bdCODEMP IS NULL ';
  IF (wTableFunRural <> '') THEN
    BEGIN
      IF (:PRTIPOLAN = 'SAI') THEN
        BEGIN -- Alt.: #179132 - Quando for Funrural deve olhar se tem as contas preparadas al?m dos valores...
          wSQL = :wSQL || ' AND (((SELECT c.bdCODITEMONLINE FROM TCONTAS_ONLINE_TEMP C  WHERE (C.BDSESSAO = I.BDSESSAO and C.BDCODITEMONLINE in (/*246,*/ 301) and C.BDREFERENCIA = extract(year from s.BDDATAEMISSAO)||LPAD(extract(month from s.BDDATAEMISSAO),2,''0'') )) IS NOT NULL) OR ';
          wSQL = :wSQL || '      ((Coalesce(fr.bdVLRFUNRURAL,0) = 0) AND (Coalesce(fr.bdVLRGILRAT,0) = 0) AND (Coalesce(fr.bdVLRSENAR,0) = 0)) ) ';
        END
      ELSE                                                                                                                            
        wSQL = :wSQL || ' AND ((Coalesce(fr.bdVLRFUNRURAL,0) = 0) AND (Coalesce(fr.bdVLRGILRAT,0) = 0) AND (Coalesce(fr.BDVLRFPAS,0) = 0)) ';
    END
  /*Somente lan?amentos que tem desconto*/
  IF (:wTipoIntDesc = 0) THEN /*0 - Nota a nota*/
    wSQL = :wSQL || ' AND ((s.BDDESCONTONOTA > 0) AND (CD.BDCHAVE IS NOT NULL)) ';
  ELSE /*1 - Nota a nota por CFOP*/
    wSQL = :wSQL || ' AND ((I.BDDESCONTO > 0) AND (CD.BDCHAVE IS NOT NULL)) ';

  wSQL = :wSQL || 'AND S.BDCODSITNF NOT IN (2, 3, 4, 5) '; 
  wSQL = :wSQL || 'AND I.BDVLRCONTAB > 0 ';
  wSQL = :wSQL || 'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';
  wSQL = :wSQL || 'AND CD.BDCHAVE IS NOT NULL '; /*Verifica sem tem conta de desconto*/
  wSQL = :wSQL || 'AND NOT EXISTS(';
  wSQL = :wSQL || 'SELECT INCO.BDCODINCONSISTENCIA ';
  wSQL = :wSQL || 'FROM '||:wTableIncon||' INCO ';
  wSQL = :wSQL || 'WHERE INCO.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL || 'AND   INCO.BDCHAVE  = I.BDCHAVE ';
  wSQL = :wSQL || 'AND   INCO.BDSESSAO = I.BDSESSAO ';
  wSQL = :wSQL || ') ';
  wSQL = :wSQL || ') MOV ';
  wSQL = :wSQL || 'WHERE MOV.BDPRIMEIRAORDEM = MOV.BDORDEM ';
  EXECUTE STATEMENT :wSQL;
EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO','6');
  IF (wTableRateio <> '') THEN
    BEGIN
      /*Rateio*/
      wSQL = 'insert into TMP_TLANC_CONTABILIZACAO_TEMP(bdCODEMP, bdCHAVE, bdORDEM, bdSESSAO, bdCHAVE_VSUC, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, ';
      WSQL = :WSQL || 'bdTRANSACAO, bdTRANFECHADA, bdFORMULA, bdCODPLANOONLINE, bdCHAVETITULO, bdCLASSIFBUSCA, bdCLASSIFTITULO, bdCODITEMONLINE, bdCHAVECONTA, BDCODHIST, BDCODTPHI, bdORD, BDCODEMPSCP) ';
      wSQL = :wSQL || 'select mov.bdCODEMP, mov.bdEDITCHAVE, mov.bdORDEM, mov.bdSESSAO, mov.bdCHAVE_VSUC, mov.bdCODPLAPADRAO, mov.bdCODUSU, mov.bdDEB, mov.bdCRED, MOV.BDCOMPHIST, MOV.'||WFIELDDATA||', mov.bdVLRCONTAB, ';
      wSQL = :wSQL || 'mov.bdTIPOLAN, mov.bdNUMDOCINI, mov.bdTRANSACAO, mov.bdTRANFECHADA, mov.bdFORMULA, mov.bdCODPLANOONLINE, mov.bdCHAVECONF, mov.bdCLASSIFICACAO, mov.bdCLASS_TITULO, mov.bdCODITEMONLINE, mov.bdCHAVE, mov.BDCODHIST, mov.BDCODTPHI, 1 as BDORD';
      wSQL = :wSQL || ',MOV.BDCODEMPSCP  ';
      wSQL = :wSQL || 'from ( ';
      wSQL = :wSQL || 'select i.bdCODEMP, i.bdEDITCHAVE, i.bdORDEM, i.bdSESSAO, NULL as BDCHAVE_VSUC, o.bdCODPLAPADRAO, NULL as BDCODUSU, o.bdCONTADEBPROV, o.bdCONTACREDPROV, RAT.BDCOMPHIST, mov.bdDATAEMISSAO,  ';
      wSQL = :wSQL || 'rat.bdVALOR as bdVLRCONTAB, 100 as bdTIPOLAN/*100 - Escrita fiscal*/, mov.bdNUMDOCINI, NULL as bdTRANSACAO, ''TRUE'' as bdTRANFECHADA, o.bdFORMULA, '||:PRCODPLANOONLINE||' as bdCODPLANOONLINE, o.bdCHAVE as bdCHAVECONF, ';
      wSQL = :wSQL || 'o.bdCLASSIFICACAO, o.bdCLASSIFICACAO as bdCLASS_TITULO, o.bdCODITEMONLINE, o.bdCHAVE, o.BDCODHIST, o.BDCODTPHI, mov.bdDESCONTONOTA, 0 as bdTOTALRET, rat.BDDEB, rat.BDCRED ';
      wSQL = :wSQL || IIF(:PRTIPOLAN = 'ENT', ',MOV.BDDATAENTRADAENT  ',  '');
      wSQL = :wSQL || ',(SELECT FIRST 1 scp.bdCODEMPSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = i.bdCODEMP AND scp.bdCODSCP = i.bdCODSCP AND ';
      wSQL = :wSQL ||   '((scp.bdDATAINICIAL <= mov.bdDATAEMISSAO AND scp.bdDATAFINAL IS NULL) OR (mov.bdDATAEMISSAO BETWEEN scp.bdDATAINICIAL AND scp.bdDATAFINAL))) ';
      wSQL = :wSQL || 'from '||:wTableItem||' i ';

      IF (:wTipLan IS NOT NULL) THEN
        wSQL = :wSQL || 'JOIN '||:wTable||' mov ON(mov.BDCODEMP = I.BDCODEMP AND mov.BDCHAVE = I.BDCHAVE AND mov.BDSESSAO = I.BDSESSAO AND mov.BDTIPLAN = '||:wTipLan||') ';
      ELSE
        wSQL = :wSQL || 'join '||:wTable||' mov on (mov.bdCODEMP = i.bdCODEMP and mov.bdCHAVE = i.bdCHAVE and mov.bdSESSAO = i.bdSESSAO) ';

      wSQL = :wSQL || 'join '||:wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) ';
      wSQL = :wSQL || 'join TCONTAS_ONLINE_TEMP o on (o.BDSESSAO = rat.BDSESSAO AND rat.bdCHAVEONLINE = o.bdCHAVE AND O.BDCONTARATEIO = ''TRUE'' AND O.BDREFERENCIA = EXTRACT(YEAR FROM mov.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM mov.'||WFIELDDATA||')) ';
      wSQL = :wSQL || 'left outer join TINICIO_CONTABILIZACAO ic on (ic.bdCODEMP = i.bdCODEMP and ic.bdCODSIS = '||wEF||') ';
      wSQL = :wSQL || 'where i.bdSESSAO = '||:prSESSAO;
      wSQL = :wSQL || 'and mov.bdCODSITNF not in (2, 3, 4, 5) ';
      wSQL = :wSQL || 'and ((ic.bdCODEMP IS NULL) or (IC.BDDATA is null) or ((ic.bdCODEMP IS NOT NULL) and (ic.bdDATA <= mov.'||wfielddata||'))) ';
      wSQL = :wSQL || 'and not exists( ';
      wSQL = :wSQL || 'select inco.bdCODINCONSISTENCIA ';
      wSQL = :wSQL || 'from '||:wTableIncon||' inco ';
      wSQL = :wSQL || 'where inco.bdCODEMP = i.bdCODEMP ';
      wSQL = :wSQL || 'and inco.bdCHAVE  = i.bdCHAVE ';
      wSQL = :wSQL || 'and inco.bdSESSAO = i.bdSESSAO ';
      wSQL = :wSQL || ') ';
      wSQL = :wSQL || ') mov ';
      EXECUTE STATEMENT :wSQL;
    END
EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO','7');

  /*Diferen?a do valor cont?bil*/
  wSQL = 'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, BDCODHIST, BDCODTPHI, bdord, ';
  wSQL = :wSQL || ' BDEMPREENDIMENTOPROVD, BDEMPREENDIMENTOPROVC, BDCODEMPREENDIMENTO, bdcodimovrur, bdtipmov, bdctacor, bdcodter, bdtipdoc, bdtiplan,BDTIPOPE, BDCODEMPSCP) ';
  wSQL = :wSQL || 'SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE, MOV.BDORDEM, MOV.BDSESSAO, MOV.BDCHAVE_VSUC, MOV.BDCODPLAPADRAO, MOV.BDCODUSU, ';

  IF (:wTipoIntDesc = 0) THEN /*0 - Nota a nota*/
    wSQL = :wSQL || 'MOV.BDCONTADEBPROV, MOV.BDCONTACREDPROV, MOV.BDCOMPHIST_VLRCONTAB, '||wfielddata||', MOV.BDVLRCONTAB, ';
  ELSE
    BEGIN
      IF ((:prTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
        wSQL = :wSQL || 'IIF((mov.bdDESCONTO > 0) AND (MOV.BDCHAVEDESC IS NOT NULL), NULL, mov.bdCONTADEBPROV) bdCONTADEBPROV, mov.bdCONTACREDPROV, MOV.BDCOMPHIST_VLRCONTAB, MOV.'||WFIELDDATA||', MOV.BDVLRCONTAB, ';
      ELSE
      IF ((:prTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE')) THEN
        wSQL = :wSQL || 'MOV.BDCONTADEBPROV, IIF((MOV.BDDESCONTO > 0) AND (MOV.BDCHAVEDESC IS NOT NULL), NULL, MOV.BDCONTACREDPROV) BDCONTACREDPROV, MOV.BDCOMPHIST_VLRCONTAB, MOV.BDDATAEMISSAO, MOV.BDVLRCONTAB, ';
    END
  wSQL = :wSQL || 'MOV.BDTIPOLAN, MOV.BDNUMDOCINI, MOV.BDTRANSACAO, MOV.BDTRANFECHADA, MOV.BDFORMULA, MOV.BDCODPLANOONLINE, MOV.BDCHAVECONF, ';
  wSQL = :wSQL || 'MOV.BDCLASSIFICACAO, MOV.BDCLASS_TITULO, MOV.BDCODITEMONLINE, MOV.BDCHAVELAN, mov.BDCODHIST,mov.BDCODTPHI, 5 BDORD, ';
  IF ((:prTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
    wSQL = :wSQL || 'mov.bdEMPREENDIMENTOPROVD, null bdEMPREENDIMENTOPROVC, ';
  ELSE
  IF ((:prTIPOLAN = 'SAI') OR (:PRTIPOLAN = 'SERE')) THEN
    wSQL = :wSQL || 'null bdEMPREENDIMENTOPROVD, mov.bdEMPREENDIMENTOPROVC, ';
  wSQL = :wSQL || ' MOV.BDCODEMPREENDIMENTO, ';
  wSQL = :wSQL || 'MOV.bdcodimovrur, MOV.bdtipmov, MOV.bdctacor, MOV.bdcodter, MOV.bdtipdoc, MOV.bdtiplan ';

  IF ((:prTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SERR')) THEN
    wSQL = :wSQL || ', 1 BDTIPOPE ';
  ELSE
    wSQL = :wSQL || ', 0 BDTIPOPE ';
  wSQL = :wSQL || ',MOV.BDCODEMPSCP ';

  wSQL = :wSQL || 'FROM (';
  wSQL = :wSQL || 'SELECT S.BDDESCONTONOTA, I.BDCODEMP, I.BDCHAVE, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, COALESCE(S.BDPRIMEIRAORDEM,mo.bdORDEM,1) BDPRIMEIRAORDEM, '; -- Alt.: #144147 - Quando a primeira CFOP n?o contabilizava, n?o carregava a nota, por isso foi criado o "mo", minima ordem, para buscar a primeira que contabiliza...
  wSQL = :wSQL || 'S.BDRATEIARET, NULL BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRCONTAB, S.BDDATAEMISSAO, I.BDVLRCONTAB, 100 BDTIPOLAN/*100 - Escrita fiscal*/, S.BDNUMDOCINI, NULL BDTRANSACAO, ';
  wSQL = :wSQL || '''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||' BDCODPLANOONLINE, C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE AS BDCHAVELAN, C.BDCODHIST, C.BDCODTPHI,C.BDEMPREENDIMENTOPROVD,C.BDEMPREENDIMENTOPROVC, S.BDCODEMPREENDIMENTO, COALESCE(I.BDDESCONTO, 0) BDDESCONTO,CD.BDCHAVE BDCHAVEDESC, ';
  wSQL = :wSQL || 'PR.bdcodimovrur, pr.bdtipmov, pr.bdctacor, pr.bdcodter, pr.bdtipdoc, pr.bdtiplan, ';

  wSQL = :wSQL || '(';
  IF (:wTIPOINTCONTRETPCC = 0) THEN
    wSQL = :wSQL || 'COALESCE(R.BDVLRPIS, 0) + COALESCE(R.BDVLRCOFINS, 0) + COALESCE(R.BDVLRCSOCIAL, 0) + ';
  IF (:wTipoApuracaoRetIR = 0) THEN
    wSQL = :wSQL || 'COALESCE(R.BDVLRIR, 0) + ';
  wSQL = :wSQL || 'COALESCE('||:wCampoINSS||', 0) + COALESCE(R.BDISSRET, 0) + COALESCE(INSS.BDVLRAPOS15, 0) + COALESCE(INSS.BDVLRAPOS20, 0) + COALESCE(INSS.BDVLRAPOS25, 0)  ';  

  IF (:wTableFunRural <> '') THEN
    BEGIN                      
      IF (:PRTIPOLAN = 'SAI') THEN
        wSQL = :wSQL || ' + COALESCE(fr.bdVLRFUNRURAL, 0) + COALESCE(fr.bdVLRGILRAT, 0) + COALESCE(fr.bdVLRSENAR, 0) ';
      ELSE
        wSQL = :wSQL || ' + COALESCE(fr.bdVLRFUNRURAL, 0) + COALESCE(fr.bdVLRGILRAT, 0) + COALESCE(fr.BDVLRFPAS, 0) ';
    END

  wSQL = :wSQL || ') BDTOTALRET ';
  wSQL = :wSQL ||  IIF(:PRTIPOLAN = 'ENT', ',S.BDDATAENTRADAENT ',  '');
  wSQL = :wSQL || ',(SELECT FIRST 1 scp.bdCODEMPSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = i.bdCODEMP AND scp.bdCODSCP = i.bdCODSCP AND ';
  wSQL = :wSQL ||   '((scp.bdDATAINICIAL <= s.bdDATAEMISSAO AND scp.bdDATAFINAL IS NULL) OR (s.bdDATAEMISSAO BETWEEN scp.bdDATAINICIAL AND scp.bdDATAFINAL))) ';
  wSQL = :wSQL || 'FROM '||:wTableItem||' I ';
  wSQL = :wSQL || 'JOIN (SELECT i.bdCODEMP, i.bdCHAVE, i.bdSESSAO, MIN(i.bdORDEM) AS bdORDEM ';
  wSQL = :wSQL ||       'FROM '||:wTableItem||' i ';
  wSQL = :wSQL ||       'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT AND nat.bdCONTABILIZA = ''TRUE'') ';
  wSQL = :wSQL ||       'GROUP BY i.bdCODEMP, i.bdCHAVE, i.bdSESSAO ';
  wSQL = :wSQL ||       ') mo ON (mo.bdCODEMP = i.bdCODEMP AND mo.bdCHAVE = i.bdCHAVE AND mo.bdSESSAO = i.bdSESSAO) ';

  IF (:wTipLan IS NOT NULL) THEN
    wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO AND S.BDTIPLAN = '||:wTipLan||') ';
  ELSE
    wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO) ';

  IF (wTableRateio <> '') THEN
    wSQL = :wSQL || 'left outer join '||wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) ';

  wSQL = :wSQL || 'left outer join '||:WTablePR||' PR on (PR.bdCODEMP = i.bdCODEMP and PR.bdCHAVE = i.bdCHAVE and PR.bdSESSAO = i.bdSESSAO) ';

  wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTableRet||' R ON(R.BDCODEMP = I.BDCODEMP AND R.BDCHAVE = I.BDCHAVE AND R.BDSESSAO = I.BDSESSAO) ';

  IF (:wTableINSS <> '') THEN
    wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTableINSS||' INSS ON(INSS.BDCODEMP = I.BDCODEMP AND INSS.BDCHAVE = I.BDCHAVE AND INSS.BDSESSAO = I.BDSESSAO) ';

  IF (:wTableFunRural <> '') THEN
    wSQL = :wSQL || 'left outer join '||:wTableFunRural||' fr on (fr.bdCODEMP = i.bdCODEMP and fr.bdCHAVE = i.bdCHAVE and fr.bdSESSAO = i.bdSESSAO) ';

  wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 111 '; /*Valor cont?bil - A vista*/
  wSQL = :wSQL || 'WHEN s.BDCONDPGTO = 1 THEN 117 '; /*Valor cont?bil - Prazo*/
  wSQL = :wSQL || 'WHEN s.BDCONDPGTO = 2 THEN 170 '; /*Valor cont?bil - Outras*/
  wSQL = :wSQL || 'END) AND C.BDREFERENCIA = EXTRACT(YEAR FROM S.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM S.'||WFIELDDATA||')) ';
  IF (:wTipoIntDesc = 0) THEN /*0 - Nota a nota*/
    wSQL = :wSQL || 'LEFT OUTER JOIN TCONTAS_ONLINE_TEMP CD ON(CD.BDSESSAO = I.BDSESSAO AND CD.BDCODITEMONLINE = '||:wCodItemDesc||' AND CD.'||wContaProv||' IS NOT NULL) '
    || ' AND CD.BDREFERENCIA = EXTRACT(YEAR FROM S.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM S.'||WFIELDDATA||')';
  ELSE
    BEGIN /*1 - Nota a nota por CFOP*/
      wSQL = :wSQL || 'LEFT OUTER JOIN TCONTAS_ONLINE_TEMP CD ON(CD.BDSESSAO = I.BDSESSAO AND CD.BDCODNAT = I.BDCODNAT AND CD.BDCODITEMONLINE = (CASE WHEN S.BDCONDPGTO = 0 THEN 243 ';
      wSQL = :wSQL || 'WHEN S.BDCONDPGTO = 1 THEN 244 ';
      wSQL = :wSQL || 'WHEN S.BDCONDPGTO = 2 THEN 245 ';
      wSQL = :wSQL || 'END) AND CD.'||wContaProv||' IS NOT NULL AND CD.BDREFERENCIA = EXTRACT(YEAR FROM S.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM S.'||WFIELDDATA||')) ';
    END

  wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') ';

  wSQL = :wSQL ||       'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
  wSQL = :wSQL || 'WHERE I.BDSESSAO = '||:PRSESSAO;

  IF (wTableRateio <> '') THEN
    wSQL = :wSQL || ' and rat.bdCODEMP IS NULL ';

  wSQL = :wSQL || ' AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
  wSQL = :wSQL || ' AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';
  
  wSQL = :wSQL || 'AND I.BDVLRCONTAB > 0 ';
  
  IF (:wTipoIntDesc = 0) THEN /*0 - Nota a nota*/
    wSQL = :wSQL || ' AND ((s.BDDESCONTONOTA > 0) AND (CD.BDCHAVE IS NOT NULL)) ';
  ELSE /*1 - Nota a nota por CFOP*/
    wSQL = :wSQL || ' AND ((I.BDDESCONTO > 0) AND (CD.BDCHAVE IS NOT NULL)) ';

  wSQL = :wSQL || 'AND NOT EXISTS(';
  wSQL = :wSQL || 'SELECT INCO.BDCODINCONSISTENCIA ';
  wSQL = :wSQL || 'FROM '||:wTableIncon||' INCO ';
  wSQL = :wSQL || 'WHERE INCO.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL || 'AND   INCO.BDCHAVE  = I.BDCHAVE ';
  wSQL = :wSQL || 'AND   INCO.BDSESSAO = I.BDSESSAO ';
  wSQL = :wSQL || ')) MOV ';
  wSQL = :wSQL || ' WHERE (((MOV.BDRATEIARET = ''FALSE'') OR (MOV.BDRATEIARET IS NULL) OR (Coalesce(MOV.BDTOTALRET,0) <= 0)) AND (MOV.BDPRIMEIRAORDEM <> MOV.BDORDEM)) ';
  EXECUTE STATEMENT :wSQL;

EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO','8');
  /*Impostos*/
  IF ((:wTipoIntIcms = 0) AND (POSITION('SER', :PRTIPOLAN) = 0)) THEN /*Icms e Icms ST nota a nota*/
    BEGIN
      IF ((:PRENQFED NOT IN(1, 2)) OR ((:PRENQFED NOT IN (3)) and (:WCONTABGUIAMUN = 'TRUE') and (wtipointicmsorig = 0))) THEN /*Empresas do simples nacional n?o contabilizam ICMS, PIS, Cofins e IPI. Somente ICMS ST*/
        BEGIN
          /*ICMS*/
          wSQL = 'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, BDCODHIST, BDCODTPHI, bdord, bdEMPREENDIMENTOPROVD, bdEMPREENDIMENTOPROVC, bdCODEMPREENDIMENTO) ';
          wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRICMS, S.'||wfielddata||', I.BDVLRICMS, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ';
          wSQL = :wSQL || '''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||', C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODHIST, C.BDCODTPHI, 3 BDORD, ';
          wSQL = :wSQL || 'c.bdEMPREENDIMENTOPROVD, c.bdEMPREENDIMENTOPROVC, ';
          IF ((:prTIPOLAN = 'SAI') OR (:prTIPOLAN = 'ENT')) THEN  
            wSQL = :wSQL || ' s.bdCODEMPREENDIMENTO ';
          ELSE
            wSQL = :wSQL || ' NULL AS bdCODEMPREENDIMENTO ';
          wSQL = :wSQL ||'FROM '||:wTableItem||' I ';
          wSQL = :wSQL ||'JOIN '||:wTable||' S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO) ';
          IF (wTableRateio <> '') THEN
            wSQL = :wSQL || 'left outer join '||wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) ';

          wSQL = :wSQL ||'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 112 '; /*ICMS - A vista*/
          wSQL = :wSQL || 'WHEN s.BDCONDPGTO = 1 THEN 118 '; /*ICMS - Prazo*/
          wSQL = :wSQL || 'WHEN s.BDCONDPGTO = 2 THEN 171 '; /*ICMS - Outras*/
          wSQL = :wSQL || 'END) AND C.BDREFERENCIA = EXTRACT(YEAR FROM S.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM S.'||WFIELDDATA||')) ';
          wSQL = :wSQL ||'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') ';

                         /*Sa?da olha data de emiss?o, entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/
          wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';              
          wSQL = :wSQL ||'WHERE I.BDSESSAO = '||:PRSESSAO;
          IF (wTableRateio <> '') THEN
            wSQL = :wSQL || ' and rat.bdCODEMP IS NULL ';

          wSQL = :wSQL ||' AND I.BDVLRICMS > 0 ';
          wSQL = :wSQL ||'AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
          wSQL = :wSQL ||'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';
          wSQL = :wSQL ||'AND NOT EXISTS(';
          wSQL = :wSQL || 'SELECT INCO.BDCODINCONSISTENCIA ';
          wSQL = :wSQL || 'FROM '||:wTableIncon||' INCO ';
          wSQL = :wSQL || 'WHERE INCO.BDCODEMP = I.BDCODEMP ';
          wSQL = :wSQL || 'AND   INCO.BDCHAVE  = I.BDCHAVE ';
          wSQL = :wSQL || 'AND   INCO.BDSESSAO = I.BDSESSAO';
          wSQL = :wSQL || ')';
          EXECUTE STATEMENT :wSQL;
        END
      /*ICMS ST*/
      wSQL = 'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, BDCODHIST, BDCODTPHI, bdord, bdEMPREENDIMENTOPROVD, bdEMPREENDIMENTOPROVC, bdCODEMPREENDIMENTO) ';
      wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRICMSST, S.'||wfielddata||', I.BDVLRST, ';
      wSQL = :wSQL || '100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||', C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODHIST, C.BDCODTPHI, 3 BDORD, ';
      wSQL = :wSQL || 'c.bdEMPREENDIMENTOPROVD, c.bdEMPREENDIMENTOPROVC, ';
      IF ((:prTIPOLAN = 'SAI') OR (:prTIPOLAN = 'ENT')) THEN  
        wSQL = :wSQL || ' s.bdCODEMPREENDIMENTO ';
      ELSE
        wSQL = :wSQL || ' NULL AS bdCODEMPREENDIMENTO ';
      wSQL = :wSQL || 'FROM '||:wTableItem||' I ';
      wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO) ';
      IF (wTableRateio <> '') THEN
        wSQL = :wSQL || 'left outer join '||wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) ';

      wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 113 '; /*ICMS ST - A vista*/
      wSQL = :wSQL || 'WHEN s.BDCONDPGTO = 1 THEN 119 '; /*ICMS ST - Prazo*/
      wSQL = :wSQL || 'WHEN s.BDCONDPGTO = 2 THEN 172 '; /*ICMS ST - Outras*/
      wSQL = :wSQL || 'END) AND C.BDREFERENCIA = EXTRACT(YEAR FROM S.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM S.'||WFIELDDATA||')';
      IF (:PRENQFED IN(1, 2)) THEN /*se for do simples n?o deve levar st se n?o tiver conta ICMS ST*/
        wSQL = :wSQL || ' AND C.BDCONTADEBPROV IS NOT NULL AND C.BDCONTACREDPROV IS NOT NULL';
      wSQL = :wSQL || ') ';
      wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') ';
                      /*Sa?da olha data de emiss?o, entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/      
      wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';              
      wSQL = :wSQL || 'WHERE I.BDSESSAO = '||:PRSESSAO;
      IF (wTableRateio <> '') THEN
        wSQL = :wSQL || ' and rat.bdCODEMP IS NULL ';

      wSQL = :wSQL || ' AND I.BDVLRST > 0 ';
      wSQL = :wSQL || ' AND c.bdCONTADEBPROV IS NOT NULL AND c.bdCONTACREDPROV IS NOT NULL ';
      wSQL = :wSQL || 'AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
      wSQL = :wSQL || 'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';
      wSQL = :wSQL || 'AND NOT EXISTS(';
      wSQL = :wSQL || 'SELECT INCO.BDCODINCONSISTENCIA ';
      wSQL = :wSQL || 'FROM '||:wTableIncon||' INCO ';
      wSQL = :wSQL || 'WHERE INCO.BDCODEMP = I.BDCODEMP ';
      wSQL = :wSQL || 'AND   INCO.BDCHAVE  = I.BDCHAVE ';
      wSQL = :wSQL || 'AND   INCO.BDSESSAO = I.BDSESSAO ';
      wSQL = :wSQL || '); ';
      EXECUTE STATEMENT :wSQL;
      IF ((:prTIPOLAN = 'SAI') OR (:prTIPOLAN = 'ENT')) THEN
        BEGIN
          /*ICMS FCP ST*/
          wSQL = 'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdCODEMP, bdCHAVE, bdORDEM, bdSESSAO, bdCHAVE_VSUC, bdCODPLAPADRAO, bdCODUSU, bdDEBITO, bdCREDITO, bdCOMPL, bdDATA, bdVALOR, bdTIPOLAN, bdDCTO, bdTRANSACAO, bdTRANFECHADA, bdFORMULA, bdCODPLANOONLINE, bdCHAVETITULO, bdCLASSIFBUSCA, bdCLASSIFTITULO, bdCODITEMONLINE, bdCHAVECONTA, bdCODHIST, bdCODTPHI, bdORD, bdEMPREENDIMENTOPROVD, bdEMPREENDIMENTOPROVC, bdCODEMPREENDIMENTO) ';
          wSQL = :wSQL || 'SELECT i.bdCODEMP, i.bdEDITCHAVE, i.bdORDEM, i.bdSESSAO, i.bdCHAVE_VSUC, c.bdCODPLAPADRAO, NULL AS bdCODUSU, c.bdCONTADEBPROV, c.bdCONTACREDPROV, i.bdCOMPHIST_VLRICMSFCPST, S.'||wfielddata||', i.bdFCPRETIDO, ';
          wSQL = :wSQL || '100 AS bdTIPOLAN, s.bdNUMDOCINI, NULL AS bdTRANSACAO, ''TRUE'' AS bdTRANFECHADA, c.bdFORMULA, '||:PRCODPLANOONLINE||', c.bdCHAVECONF, c.bdCLASSIFICACAO, c.bdCLASS_TITULO, c.bdCODITEMONLINE, c.bdCHAVE, c.bdCODHIST, c.bdCODTPHI, 3 AS bdORD, ';
          wSQL = :wSQL || 'c.bdEMPREENDIMENTOPROVD, c.bdEMPREENDIMENTOPROVC, s.bdCODEMPREENDIMENTO ';
          wSQL = :wSQL || 'FROM '||:wTableItem||' i ';
          wSQL = :wSQL || 'JOIN '||:wTable||' s ON (s.bdCODEMP = i.bdCODEMP AND s.bdCHAVE = i.bdCHAVE AND s.bdSESSAO = i.bdSESSAO) ';
          IF (wTableRateio <> '') THEN
            wSQL = :wSQL || 'LEFT OUTER JOIN '||wTableRateio||' rat ON (rat.bdCODEMP = i.bdCODEMP AND rat.bdCHAVE = i.bdCHAVE AND rat.bdORDEM = i.bdORDEM AND rat.bdSESSAO = i.bdSESSAO) ';

          wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP c ON (c.bdSESSAO = i.bdSESSAO AND c.bdCODNAT = i.bdCODNAT AND (c.bdCODITEMONLINE = CASE WHEN s.bdCONDPGTO = 0 THEN 286 '; /*ICMS FCP ST - A vista*/
          wSQL = :wSQL ||                                                                                                                  'WHEN s.bdCONDPGTO = 1 THEN 287 '; /*ICMS FCP ST - Prazo*/
          wSQL = :wSQL ||                                                                                                                  'WHEN s.bdCONDPGTO = 2 THEN 288 '; /*ICMS FCP ST - Outras*/
          wSQL = :wSQL || 'END) AND C.BDREFERENCIA = EXTRACT(YEAR FROM S.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM S.'||WFIELDDATA||')';
          IF (:PRENQFED IN(1, 2)) THEN /*se for do simples n?o deve levar st se n?o tiver conta ICMS ST*/
            wSQL = :wSQL || ' AND c.bdCONTADEBPROV IS NOT NULL AND c.bdCONTACREDPROV IS NOT NULL';
          wSQL = :wSQL || ') ';
          wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP nat ON (nat.bdCODNAT = i.bdCODNAT AND nat.bdCONTABILIZA = ''TRUE'') ';
                          /*Sa?da olha data de emiss?o, entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/      
          wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO ic ON (ic.bdCODEMP = i.bdCODEMP AND ic.bdCODSIS = '||:wEF||') ';
          wSQL = :wSQL || 'WHERE i.bdSESSAO = '||:PRSESSAO;
          IF (wTableRateio <> '') THEN
            wSQL = :wSQL || ' AND rat.bdCODEMP IS NULL ';
          wSQL = :wSQL || ' AND i.bdFCPRETIDO > 0 ';
          wSQL = :wSQL || ' AND c.bdCONTADEBPROV IS NOT NULL AND c.bdCONTACREDPROV IS NOT NULL ';
          wSQL = :wSQL || ' AND s.bdCODSITNF NOT IN (2, 3, 4, 5) ';
          wSQL = :wSQL || ' AND ((ic.bdCODEMP IS NULL) OR (ic.bdDATA IS NULL) OR ((ic.bdCODEMP IS NOT NULL) AND (ic.bdDATA <= S.'||wfielddata||'))) ';
          wSQL = :wSQL || ' AND NOT EXISTS(';
          wSQL = :wSQL || 'SELECT inco.bdCODINCONSISTENCIA ';
          wSQL = :wSQL || 'FROM '||:wTableIncon||' inco ';
          wSQL = :wSQL || 'WHERE inco.bdCODEMP = i.bdCODEMP  AND inco.bdCHAVE  = i.bdCHAVE AND inco.bdSESSAO = i.bdSESSAO );';
          EXECUTE STATEMENT :wSQL;
    END
    END
EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO','9');

  IF ((:wTipoIntIpi = 0) AND (:PRENQFED NOT IN(1, 2)) AND (POSITION('SER', :PRTIPOLAN) = 0)) THEN /*Ipi nota a nota*/ /*Redu????o Z n??o tem IPI*/
    BEGIN
      /*IPI*/
      wSQL = 'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, BDCODHIST, BDCODTPHI, bdord, bdEMPREENDIMENTOPROVD, bdEMPREENDIMENTOPROVC, bdCODEMPREENDIMENTO) ';
      wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRIPI, S.'||wfielddata||', I.BDVLRIPI, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ';
      wSQL = :wSQL || '''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||', C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODHIST, C.BDCODTPHI, 3 BDORD, ';
      wSQL = :wSQL || 'c.bdEMPREENDIMENTOPROVD, c.bdEMPREENDIMENTOPROVC, ';
      IF ((:prTIPOLAN = 'SAI') OR (:prTIPOLAN = 'ENT')) THEN  
        wSQL = :wSQL || ' s.bdCODEMPREENDIMENTO ';
      ELSE
        wSQL = :wSQL || ' NULL AS bdCODEMPREENDIMENTO ';
      wSQL = :wSQL || 'FROM '||:wTableItem||' I ';
      wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO) ';

      IF (wTableRateio <> '') THEN
        wSQL = :wSQL || 'left outer join '||wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) ';

      wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 114 '; /*IPI - A vista*/
      wSQL = :wSQL || 'WHEN s.BDCONDPGTO = 1 THEN 120 '; /*IPI - Prazo*/
      wSQL = :wSQL || 'WHEN s.BDCONDPGTO = 2 THEN 173 '; /*IPI - Outras*/
      wSQL = :wSQL || 'END) AND C.BDREFERENCIA = EXTRACT(YEAR FROM S.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM S.'||WFIELDDATA||')) ';
      wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') ';

                      /*Sa?da olha data de emiss?o, entrada/servi?o tem que ser adaptado para olhar os outros campos de data*/      
      wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';                    
      wSQL = :wSQL || 'WHERE I.BDSESSAO = '||:PRSESSAO;

      IF (wTableRateio <> '') THEN
        wSQL = :wSQL || ' and rat.bdCODEMP IS NULL ';

      wSQL = :wSQL ||' AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
      wSQL = :wSQL || 'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';
      wSQL = :wSQL || 'AND I.BDVLRIPI > 0 ';
      wSQL = :wSQL || 'AND NOT EXISTS(';
      wSQL = :wSQL || 'SELECT INCO.BDCODINCONSISTENCIA ';
      wSQL = :wSQL || 'FROM '||:wTableIncon||' INCO ';
      wSQL = :wSQL || 'WHERE INCO.BDCODEMP = I.BDCODEMP AND INCO.BDCHAVE  = I.BDCHAVE AND INCO.BDSESSAO = I.BDSESSAO );';
      EXECUTE STATEMENT :wSQL;
    END
EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO','10');

  IF (((:wTipoIntPis = 0) AND (:PRENQFED NOT IN(1, 2)) AND ((:PRCODCONFIRLP IS NULL) OR (:PRCODCONFIRLP = 0))) or (((:prenqfed = 3) and (:prformatributacao = 1)) and (:wtipointpislp = 1))) THEN
    BEGIN
      /*PIS*/
      wSQL = 'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, BDCODHIST, BDCODTPHI, bdord, bdEMPREENDIMENTOPROVD, bdEMPREENDIMENTOPROVC, bdCODEMPREENDIMENTO, BDCODEMPSCP) ';
      wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRPIS, S.'||wfielddata||', I.BDVLRPIS, 100 BDTIPOLAN, S.BDNUMDOCINI, NULL BDTRANSACAO, ';
      wSQL = :wSQL || '''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||', C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODHIST, C.BDCODTPHI, 3 BDORD, ';
      wSQL = :wSQL || 'c.bdEMPREENDIMENTOPROVD, c.bdEMPREENDIMENTOPROVC, ';
      IF ((:prTIPOLAN = 'SAI') OR (:prTIPOLAN = 'ENT')) THEN  
        wSQL = :wSQL || ' s.bdCODEMPREENDIMENTO ';
      ELSE
        wSQL = :wSQL || ' NULL AS bdCODEMPREENDIMENTO ';
      wSQL = :wSQL || ',(SELECT FIRST 1 scp.bdCODEMPSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = i.bdCODEMP AND scp.bdCODSCP = i.bdCODSCP AND ';
      wSQL = :wSQL ||   '((scp.bdDATAINICIAL <= s.bdDATAEMISSAO AND scp.bdDATAFINAL IS NULL) OR (s.bdDATAEMISSAO BETWEEN scp.bdDATAINICIAL AND scp.bdDATAFINAL))) ';
      wSQL = :wSQL || 'FROM '||:wTableItem||' I ';
     IF (:wTipLan IS NOT NULL) THEN
        wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO AND S.BDTIPLAN = '||:wTipLan||') ';
      ELSE
        wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO) ';

      IF (wTableRateio <> '') THEN
        wSQL = :wSQL || 'left outer join '||wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) ';
      wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 115 '; /*PIS - A vista*/
      wSQL = :wSQL || 'WHEN s.BDCONDPGTO = 1 THEN 121 '; /*PIS - Prazo*/
      wSQL = :wSQL || 'WHEN s.BDCONDPGTO = 2 THEN 174 '; /*PIS - Outras*/
      wSQL = :wSQL || 'END) AND C.BDREFERENCIA = EXTRACT(YEAR FROM S.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM S.'||WFIELDDATA||')) ';
      wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'' ';
      IF ((:PRTIPOLAN = 'ENT') AND (((:PRENQFED = 3) AND (:PRFORMATRIBUTACAO = 1)) AND (:WTIPOINTPISLP = 1))) THEN
        wSQL = :wSQL || 'AND NAT.BDDEVOL = ''TRUE''';
      wSQL = :wSQL || ')';
      wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
      wSQL = :wSQL || 'WHERE I.BDSESSAO = '||:PRSESSAO;
      IF (wTableRateio <> '') THEN
        wSQL = :wSQL || ' and rat.bdCODEMP IS NULL ';
      wSQL = :wSQL || 'AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
      wSQL = :wSQL || 'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';
      wSQL = :wSQL || 'AND I.BDVLRPIS > 0 ';
      wSQL = :wSQL || 'AND NOT EXISTS(';
      wSQL = :wSQL || 'SELECT INCO.BDCODINCONSISTENCIA ';
      wSQL = :wSQL || 'FROM '||:wTableIncon||' INCO WHERE INCO.BDCODEMP = I.BDCODEMP AND INCO.BDCHAVE  = I.BDCHAVE AND INCO.BDSESSAO = I.BDSESSAO );';
      EXECUTE STATEMENT :wSQL;
    END
EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO','11');

  IF (((:wTipoIntCof = 0) AND (:PRENQFED NOT IN(1, 2)) AND ((:PRCODCONFIRLP IS NULL) OR (:PRCODCONFIRLP = 0))) or (((:PRENQFED = 3) and (:PRFORMATRIBUTACAO = 1)) and (:WTIPOINTCOFLP = 1))) Then
    BEGIN
      /*Cofins*/
      wSQL = 'INSERT INTO TMP_TLANC_CONTABILIZACAO_TEMP(bdcodemp, bdchave, bdordem, bdsessao, bdchave_vsuc, bdcodplapadrao, bdcodusu, bddebito, bdcredito, bdcompl, bddata, bdvalor, bdtipolan, bddcto, bdtransacao, bdtranfechada, bdformula, bdcodplanoonline, bdchavetitulo, bdclassifbusca, bdclassiftitulo, bdcoditemonline, bdchaveconta, BDCODHIST, BDCODTPHI, bdord, bdEMPREENDIMENTOPROVD, bdEMPREENDIMENTOPROVC, bdCODEMPREENDIMENTO,BDCODEMPSCP) ';
      wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDEDITCHAVE, I.BDORDEM, I.BDSESSAO, I.BDCHAVE_VSUC, C.BDCODPLAPADRAO, NULL BDCODUSU, C.BDCONTADEBPROV, C.BDCONTACREDPROV, I.BDCOMPHIST_VLRCOFINS, S.'||wfielddata||', I.BDVLRCOFINS, 100 BDTIPOLAN, ';
      wSQL = :wSQL || 'S.BDNUMDOCINI, NULL BDTRANSACAO, ''TRUE'' BDTRANFECHADA, C.BDFORMULA, '||:PRCODPLANOONLINE||', C.BDCHAVECONF, C.BDCLASSIFICACAO, C.BDCLASS_TITULO, C.BDCODITEMONLINE, C.BDCHAVE, C.BDCODHIST, C.BDCODTPHI, 3 BDORD, ';
      wSQL = :wSQL || 'c.bdEMPREENDIMENTOPROVD, c.bdEMPREENDIMENTOPROVC, ';
      IF ((:prTIPOLAN = 'SAI') OR (:prTIPOLAN = 'ENT')) THEN  
        wSQL = :wSQL || ' s.bdCODEMPREENDIMENTO ';
      ELSE
        wSQL = :wSQL || ' NULL AS bdCODEMPREENDIMENTO ';
      wSQL = :wSQL || ',(SELECT FIRST 1 scp.bdCODEMPSCP FROM TEMPRESAS_SCP scp WHERE scp.bdCODEMP = i.bdCODEMP AND scp.bdCODSCP = i.bdCODSCP AND ';
      wSQL = :wSQL ||   '((scp.bdDATAINICIAL <= s.bdDATAEMISSAO AND scp.bdDATAFINAL IS NULL) OR (s.bdDATAEMISSAO BETWEEN scp.bdDATAINICIAL AND scp.bdDATAFINAL))) ';
      wSQL = :wSQL || 'FROM '||:wTableItem||' I ';
      IF (:wTipLan IS NOT NULL) THEN
        wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO AND S.BDTIPLAN = '||:wTipLan||') ';
      ELSE
        wSQL = :wSQL || 'JOIN '||:wTable||' S ON(S.BDCODEMP = I.BDCODEMP AND S.BDCHAVE = I.BDCHAVE AND S.BDSESSAO = I.BDSESSAO) ';
      IF (wTableRateio <> '') THEN
        wSQL = :wSQL || 'left outer join '||wTableRateio||' rat on (rat.bdCODEMP = i.bdCODEMP and rat.bdCHAVE = i.bdCHAVE and rat.bdORDEM = i.bdORDEM and rat.bdSESSAO = i.bdSESSAO) ';
      wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = I.BDSESSAO AND C.BDCODNAT = I.BDCODNAT AND (C.BDCODITEMONLINE = CASE WHEN s.BDCONDPGTO = 0 THEN 116 '; /*Cofins - A vista*/
      wSQL = :wSQL || 'WHEN s.BDCONDPGTO = 1 THEN 122 '; /*Cofins - Prazo*/
      wSQL = :wSQL || 'WHEN s.BDCONDPGTO = 2 THEN 175 '; /*Cofins - Outras*/
      wSQL = :wSQL || 'END) AND C.BDREFERENCIA = EXTRACT(YEAR FROM S.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM S.'||WFIELDDATA||')) ';
      wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'' ';
      IF ((:PRTIPOLAN = 'ENT') AND (((:PRENQFED = 3) AND (:PRFORMATRIBUTACAO = 1)) AND (:WTIPOINTCOFLP = 1))) THEN
        wSQL = :wSQL || 'AND NAT.BDDEVOL = ''TRUE''';
      wSQL = :wSQL || ')';
      wSQL = :wSQL || 'LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = I.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';                                
      wSQL = :wSQL || 'WHERE I.BDSESSAO = '||:PRSESSAO;
      IF (wTableRateio <> '') THEN
        wSQL = :wSQL || ' and rat.bdCODEMP IS NULL ';
      wSQL = :wSQL || ' AND S.BDCODSITNF NOT IN (2, 3, 4, 5) ';
      wSQL = :wSQL || 'AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';
      wSQL = :wSQL || 'AND I.BDVLRCOFINS > 0 ';
      wSQL = :wSQL || 'AND NOT EXISTS(';
      wSQL = :wSQL || 'SELECT INCO.BDCODINCONSISTENCIA ';
      wSQL = :wSQL || 'FROM '||:wTableIncon||' INCO ';
      wSQL = :wSQL || 'WHERE INCO.BDCODEMP = I.BDCODEMP AND INCO.BDCHAVE  = I.BDCHAVE  AND INCO.BDSESSAO = I.BDSESSAO );';
      EXECUTE STATEMENT :wSQL;
    END
EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO','12');

  EXECUTE PROCEDURE SP_CRIA_PRE_CONTABILIZACAO_RET (:prSESSAO, :prCODPLANOONLINE, :prENQFED, :prTIPOLAN, :PRFORMATRIBUTACAO);
EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO','13');

  wTipoIntIcms = wtipointicmsorig;  /*#147832 - recebe o tipo de integração ICMS original, para no final passar para procedure auxiliar*/

  EXECUTE PROCEDURE SP_CRIA_PRE_CONTABILIZACAO_AUX(:PRSESSAO, :PRCODPLANOONLINE, :PRTIPOLAN, :wTipoIntDesc, :wTipoIntICMS, :PRCODCONFDIMESC, :prENQFED, :WCONTABGUIAMUN);
EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO','14');
  IF ((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SAI')) THEN
     IF ((:wTipoIntIcms = 0) OR (:PRENQFED IN(1, 2, 4)))  THEN /*Icms e Icms ST nota a nota ou empresas do simples nacional*/
        EXECUTE PROCEDURE SP_CRIA_PRE_CONTABILIZACAODIFAL(:PRSESSAO, :PRCODPLANOONLINE, :PRTIPOLAN, :wEF);
  DELETE FROM TMP_TCFOP_TMOV WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TCONTAS_ONLINE_TEMP WHERE BDSESSAO = :PRSESSAO;
EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_CRIA_PRE_CONTABILIZACAO','15');
END
^

create or alter procedure SP_INSERT_INCONSISTENCIAS_CONTA (
    PRSESSAO integer,
    PRCODPLANOONLINE integer,
    PRENQFED integer,
    PRCODCONFIRLP integer,
    PRTIPOLAN varchar(5),
    PRFORMATRIB integer = 0)
as
declare variable FCAMPOORDEM varchar(20);
declare variable FCONTABILIZAICMS integer;
declare variable FCONTABILIZACOFINS integer;
declare variable FCONTABILIZAPIS integer;
declare variable FCONTABILIZAIPI integer;
declare variable FTABLEINCON varchar(31);
declare variable FTABLE varchar(31);
declare variable FTABLEITEM varchar(31);
declare variable FTABLERET varchar(31);
declare variable FTABLEINSS varchar(31);
declare variable WSQL varchar(2600);
declare variable FTABLEFUNRUAL varchar(32);
declare variable WCODITEMPIS integer;
declare variable WCODITEMCOFINS integer;
declare variable WCODITEMCSOCIAL integer;
declare variable WCODITEMIR integer;
declare variable WCODITEMINSS integer;
declare variable WCODITEMISS integer;
declare variable WCODITEMFUNRURAL integer;
declare variable WCONTAPROV varchar(32);
declare variable WEF integer;
declare variable WSITCANC integer;
declare variable WTIPLAN integer;
declare variable WFIELDDATA varchar(32);
declare variable WFIELDREF varchar(200);
declare variable FCONTABILIZAPISLP integer;
declare variable FCONTABILIZACOFINSLP integer;
declare variable FCONTPISCOFLP varchar(5);
BEGIN
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERT_INCONSISTENCIAS_CONTA','1');
  wTipLan  = NULL;
  wEF      = 3;
  wSitCanc = 2;
  FCampoOrdem = 'BDORDEM';
  wfielddata = 'BDDATAEMISSAO';
  wCodItemPIS      = 0; --1370   82  89
  wCodItemCofins   = 0; --1371   83  90
  wCodItemCSocial  = 0; --1372   84  91
  wCodItemIR       = 0; --1374  163  92
  wCodItemINSS     = 0; --1375  164  93
  wCodItemISS      = 0; --1378  165  94
  wCodItemFunRural = 0; --       85 246
  FCONTPISCOFLP = 'TRUE';

  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      FTableIncon = 'VEF_INCON_TMOVSAI';
      FTable      = 'TMP_VEF_EMP_TMOVSAI_TEMP';
      FTableItem  = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
      FTableRet   = 'TMP_VEF_EMP_TMOVSAIRET_TEMP';
      FTableFunRual = 'TMP_VEF_TMOVSAIFUNRURAL_TEMP';
      FTableINSS    = 'TMP_VEF_EMP_TMOVSAIDED_TEMP';
      wCodItemPIS      =  89;
      wCodItemCofins   =  90;
      wCodItemCSocial  =  91;
      wCodItemIR       =  92;
      wCodItemINSS     =  93;
      wCodItemISS      =  94;
      wCodItemFunRural = 246;
      wContaProv = 'BDCONTADEBPROV';
    END
  ELSE
  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      FTableIncon = 'VEF_INCON_TMOVENT';
      FTable      = 'TMP_VEF_EMP_TMOVENT_TEMP';
      FTableItem  = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      FTableRet   = 'TMP_VEF_EMP_TMOVENTRET_TEMP';
      FTableFunRual = 'TMP_VEF_TMOVENTFUNRURAL_TEMP';
      FTableINSS    = 'TMP_VEF_EMP_TMOVENTDED_TEMP';
      wCodItemPIS      =  82;
      wCodItemCofins   =  83;
      wCodItemCSocial  =  84;
      wCodItemIR       = 163;
      wCodItemINSS     = 164;
      wCodItemISS      = 165;
      wCodItemFunRural =  85;
      wContaProv = 'BDCONTACREDPROV';
      wfielddata = 'bdDATAENTRADAENT';
    END
  IF (POSITION('SER', :PRTIPOLAN) > 0) THEN
    BEGIN
      FTableIncon= 'VEF_INCON_TMOVSER';
      FTable     = 'TMP_VEF_EMP_TMOVSER_TEMP';
      FTableItem = 'TMP_VEF_EMP_TMOVSERITENS_TEMP';
      FTableRet  = 'TMP_VEF_EMP_TMOVSERRET_TEMP';
      FTableINSS = 'TMP_VEF_EMP_TMOVSERDED_TEMP';

      IF (:PRTIPOLAN = 'SERE') THEN /*Serviço emitido*/
        BEGIN
          wTipLan         = 0;

          wCodItemPIS     = 99;
          wCodItemCofins  = 100;
          wCodItemCSocial = 101;
          wCodItemIR      = 97;
          wCodItemINSS    = 98;
          wCodItemISS     = 102;
          wContaProv      = 'BDCONTADEBPROV';
        END
      ELSE
        BEGIN /*Serviço recebido*/
          wTipLan         = 1;

          wCodItemPIS     = 107;
          wCodItemCofins  = 108;
          wCodItemCSocial = 109;
          wCodItemIR      = 105;
          wCodItemINSS    = 106;
          wCodItemISS     = 110;
          wContaProv      = 'BDCONTACREDPROV';
          FCONTPISCOFLP = 'FALSE';
        END
    END
  ELSE    
  IF (:PRTIPOLAN = 'REDZ') THEN
    BEGIN
      /*Sol: 14207 Patrick T. Sá 17/02/2017. Inconsistencia de conta da redução Z faz em outra SP devido aos tratamentos que precisa de agrupar cfops...*/
      EXECUTE PROCEDURE SP_INSERT_INCONSIS_CONTA_REDZ(:PRSESSAO, :PRCODPLANOONLINE, :PRENQFED);
      EXIT;
    END

/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERT_INCONSISTENCIAS_CONTA','2');
  WFIELDREF = 'EXTRACT(YEAR FROM MOV.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM MOV.'||WFIELDDATA||')';

  SELECT P.BDTIPOINTICMS,  P.BDTIPOINTPIS, P.BDTIPOINTCOFINS, P.BDTIPOINTIPI, P.BDTIPOINTPISLP, P.BDTIPOINTCOFINSLP
  FROM TPLANO_CONF_ONLINE P
  WHERE P.BDCODPLANOONLINE = :PRCODPLANOONLINE
  INTO :FCONTABILIZAICMS, :FCONTABILIZAPIS, :FCONTABILIZACOFINS, :FCONTABILIZAIPI, :FCONTABILIZAPISLP, :FCONTABILIZACOFINSLP;

  /*--------------------------------------------Valor contábil--------------------------------------------*/
  wSQL =          'INSERT INTO '||:FTableIncon||'(bdcodemp, bdchave, '||:FCampoOrdem||', bdsessao, bdcodinconsistencia, BDTIPOINCON, BDCODNAT, BDCONDPGTO,BDCODPLANOONLINE) ';
  wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDCHAVE, I.'||:FCampoOrdem||', I.BDSESSAO, 27 BDINCONSISTENCIA, 2 BDTIPOINCON, I.BDCODNAT, MOV.BDCONDPGTO, '||:PRCODPLANOONLINE;
  wSQL = :wSQL || 'FROM ( ';
  wSQL = :wSQL || '      SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, S.'||wfielddata;
  wSQL = :wSQL || '      FROM '||:FTable||' S ';
  wSQL = :wSQL || '      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
  wSQL = :wSQL || '      WHERE S.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL || '      AND S.BDCODSITNF <> '||:wSitCanc; /*2 - Cancelada, não contabiliza*/
  wSQL = :wSQL || '      AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';

  IF (:wTipLan IS NOT NULL) THEN
    wSQL = :wSQL || '      AND S.BDTIPLAN = '||:wTipLan;

  wSQL = :wSQL || '     ) MOV ';
  wSQL = :wSQL || 'JOIN '||:FTableItem||' I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO AND I.BDVLRCONTAB > 0) ';
  wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') ';
  wSQL = :wSQL || 'JOIN ( ';
  wSQL = :wSQL || '      SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, c.BDREFERENCIA ';
  wSQL = :wSQL || '      FROM TCONTAS_ONLINE_TEMP C ';
  wSQL = :wSQL || '      WHERE (C.BDSESSAO = '||:PRSESSAO||') AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND (C.BDCODITEMONLINE = CASE WHEN C.BDCODTIPOCONTA =  50 THEN 111 '; /*Valor contábil - A vista*/
  wSQL = :wSQL || '                                                                                                                                         WHEN C.BDCODTIPOCONTA =  51 THEN 117 ';/*Valor contábil - Prazo*/
  wSQL = :wSQL || '                                                                                                                                         WHEN C.BDCODTIPOCONTA = 406 THEN 170 ';/*Valor contábil - Outras*/
  wSQL = :wSQL || '                                                                                                   END) ';
  wSQL = :wSQL || '      AND COALESCE(C.BDCONTARATEIO, ''FALSE'') = ''FALSE'' ';
  wSQL = :wSQL || '     ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDREFERENCIA = '||wfieldref||' AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
  wSQL = :wSQL || '                                                                 WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
  wSQL = :wSQL || '                                                                 WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
  wSQL = :wSQL || '                                                            END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL))); ';
  EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERT_INCONSISTENCIAS_CONTA','3');
  /*------------------------------------------------------------------------------------------------------*/

  IF ((:FCONTABILIZAICMS = 0) AND (SUBSTRING(:PRTIPOLAN FROM 1 FOR 3) <> 'SER')) THEN /*0 - nota a nota, deve exigir a conta de icms*/
    BEGIN
      IF (:PRENQFED NOT IN(1, 2)) THEN
        BEGIN
          /*-------------------------------------------------ICMS-------------------------------------------------*/
          wSQL =          'INSERT INTO '||:FTableIncon||'(bdcodemp, bdchave, '||:FCampoOrdem||', bdsessao, bdcodinconsistencia, BDTIPOINCON, bdcodnat, bdcondpgto,BDCODPLANOONLINE) ';
          wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDCHAVE, I.'||:FCampoOrdem||', I.BDSESSAO, 28 BDINCONSISTENCIA, 2 BDTIPOINCON, I.BDCODNAT, MOV.BDCONDPGTO, '||:PRCODPLANOONLINE;
          wSQL = :wSQL || '      FROM ( ';
          wSQL = :wSQL || '            SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, S.'||wfielddata;
          wSQL = :wSQL || '            FROM '||:FTable||' S ';
          wSQL = :wSQL || '            LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
          wSQL = :wSQL || '            WHERE S.BDSESSAO = '||:PRSESSAO;
          wSQL = :wSQL || '            AND S.BDCODSITNF <> '||:wSitCanc; /*2 - Cancelada, não contabiliza*/
          wSQL = :wSQL || '            AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';

          IF (:wTipLan IS NOT NULL) THEN
            wSQL = :wSQL || '      AND S.BDTIPLAN = '||:wTipLan;

          wSQL = :wSQL || '           ) MOV ';
          wSQL = :wSQL || '      JOIN '||:FTableItem||' I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO AND I.BDVLRICMS > 0) ';
          wSQL = :wSQL || '      JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') ';
          wSQL = :wSQL || '      JOIN ( ';
          wSQL = :wSQL || '            SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, c.BDREFERENCIA ';
          wSQL = :wSQL || '            FROM TCONTAS_ONLINE_TEMP C ';
--          wSQL = :wSQL || '            WHERE (C.BDSESSAO = '||:PRSESSAO||') AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE IN (112, 118, 171) /*ICMS*/ ';
          wSQL = :wSQL || '            WHERE (C.BDSESSAO = '||:PRSESSAO||') AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND (C.BDCODITEMONLINE = CASE WHEN C.BDCODTIPOCONTA =  50 THEN 112 ';/*ICMS - A vista*/
          wSQL = :wSQL || '                                                                                                                                               WHEN C.BDCODTIPOCONTA =  51 THEN 118 ';/*ICMS - Prazo*/
          wSQL = :wSQL || '                                                                                                                                               WHEN C.BDCODTIPOCONTA = 406 THEN 171 ';/*ICMS - Outras*/
          wSQL = :wSQL || '                                                                                                                                               END)';
          wSQL = :wSQL || '            AND COALESCE(C.BDCONTARATEIO, ''FALSE'') = ''FALSE'' ';
          wSQL = :wSQL || '           ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDREFERENCIA = '||wfieldref||' AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
          wSQL = :wSQL || '                                                                       WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
          wSQL = :wSQL || '                                                                       WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
          wSQL = :wSQL || '                                                                  END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL))); ';
          EXECUTE STATEMENT :wSQL;
          /*------------------------------------------------------------------------------------------------------*/
        END
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERT_INCONSISTENCIAS_CONTA','4');

      /*------------------------------------------------ICMS ST-----------------------------------------------*/
      wSQL =          'INSERT INTO '||:FTableIncon||'(bdcodemp, bdchave, '||:FCampoOrdem||', bdsessao, bdcodinconsistencia, BDTIPOINCON, bdcodnat, bdcondpgto,BDCODPLANOONLINE) ';
      wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDCHAVE, I.'||:FCampoOrdem||', I.BDSESSAO, 32 BDINCONSISTENCIA, 2 BDTIPOINCON, I.BDCODNAT, MOV.BDCONDPGTO , '||:PRCODPLANOONLINE;
      wSQL = :wSQL || 'FROM ( ';
      wSQL = :wSQL || '      SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, S.'||wfielddata;
      wSQL = :wSQL || '      FROM '||:FTable||' S ';
      wSQL = :wSQL || '      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
      wSQL = :wSQL || '      WHERE S.BDSESSAO = '||:PRSESSAO;
      wSQL = :wSQL || '      AND S.BDCODSITNF <> '||:wSitCanc; /*2 - Cancelada, não contabiliza*/
      wSQL = :wSQL || '      AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';

      IF (:wTipLan IS NOT NULL) THEN
        wSQL = :wSQL || '      AND S.BDTIPLAN = '||:wTipLan;

      wSQL = :wSQL || '     ) MOV ';
      wSQL = :wSQL || 'JOIN '||:FTableItem||' I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO AND I.BDVLRST > 0) ';
      wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') ';
      wSQL = :wSQL || 'JOIN ( ';
      wSQL = :wSQL || '      SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, c.BDREFERENCIA ';
      wSQL = :wSQL || '      FROM TCONTAS_ONLINE_TEMP C ';
--      wSQL = :wSQL || '      WHERE (C.BDSESSAO = '||:PRSESSAO||') AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE IN (113, 119, 172) /*ICMS ST*/ ';
      wSQL = :wSQL || '        WHERE (C.BDSESSAO = '||:PRSESSAO||')' ;
      IF (:PRENQFED IN(1, 2)) THEN
         wSQL = :wSQL || '         AND (((C.BDCONTACREDPROV IS NOT  NULL) AND (C.BDCONTADEBPROV IS NULL)) OR ((C.BDCONTADEBPROV IS NOT NULL) AND (C.BDCONTACREDPROV IS NULL))) ';
      ELSE
         wSQL = :wSQL || '         AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) ';

      wSQL = :wSQL || '        AND (C.BDCODITEMONLINE = CASE WHEN C.BDCODTIPOCONTA =  50 THEN 113 ';/*ICMS ST - A vista*/
      wSQL = :wSQL || '                                      WHEN C.BDCODTIPOCONTA =  51 THEN 119 ';/*ICMS ST - Prazo*/
      wSQL = :wSQL || '                                      WHEN C.BDCODTIPOCONTA = 406 THEN 172 ';/*ICMS ST - Outras*/
      wSQL = :wSQL || '                                 END)';
      wSQL = :wSQL || '        AND COALESCE(C.BDCONTARATEIO, ''FALSE'') = ''FALSE'' ';
      wSQL = :wSQL || '     ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDREFERENCIA = '||wfieldref||' AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
      wSQL = :wSQL || '                                                                 WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
      wSQL = :wSQL || '                                                                 WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
      wSQL = :wSQL || '                                                            END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)));';
      EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERT_INCONSISTENCIAS_CONTA','5');
      /*------------------------------------------------------------------------------------------------------*/
    END

  IF (:PRENQFED NOT IN(1, 2) AND (SUBSTRING(:PRTIPOLAN FROM 1 FOR 3) <> 'SER')) THEN
    BEGIN
      IF (:FCONTABILIZAIPI = 0) THEN
        BEGIN
          /*-------------------------------------------------IPI--------------------------------------------------*/
          wSQL =          'INSERT INTO '||:FTableIncon||'(bdcodemp, bdchave, '||:FCampoOrdem||', bdsessao, bdcodinconsistencia, BDTIPOINCON, bdcodnat, bdcondpgto,BDCODPLANOONLINE) ';
          wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDCHAVE, I.'||:FCampoOrdem||', I.BDSESSAO, 31 BDINCONSISTENCIA, 2 BDTIPOINCON, I.BDCODNAT, MOV.BDCONDPGTO , '||:PRCODPLANOONLINE;
          wSQL = :wSQL || 'FROM (';
          wSQL = :wSQL || '      SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, S.'||wfielddata;
          wSQL = :wSQL || '      FROM '||:FTable||' S ';
          wSQL = :wSQL || '      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
          wSQL = :wSQL || '      WHERE S.BDSESSAO = '||:PRSESSAO;
          wSQL = :wSQL || '      AND S.BDCODSITNF <> '||:wSitCanc; /*2 - Cancelada, não contabiliza*/
          wSQL = :wSQL || '      AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';

          IF (:wTipLan IS NOT NULL) THEN
            wSQL = :wSQL || '      AND S.BDTIPLAN = '||:wTipLan;

          wSQL = :wSQL || '     ) MOV ';
          wSQL = :wSQL || 'JOIN '||:FTableItem||' I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO AND I.BDVLRIPI > 0) ';
          wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'') ';
          wSQL = :wSQL || 'JOIN ( ';
          wSQL = :wSQL || '      SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, c.BDREFERENCIA ';
          wSQL = :wSQL || '      FROM TCONTAS_ONLINE_TEMP C ';
          --wSQL = :wSQL || '      WHERE (C.BDSESSAO = '||:PRSESSAO||') AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE IN (114, 120, 173) /*IPI*/ ';
          wSQL = :wSQL || '        WHERE (C.BDSESSAO = '||:PRSESSAO||') AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND (C.BDCODITEMONLINE = CASE WHEN C.BDCODTIPOCONTA =  50 THEN 114 ';/*IPI - A vista*/
          wSQL = :wSQL || '                                                                                                                                           WHEN C.BDCODTIPOCONTA =  51 THEN 120'; /*IPI - Prazo*/
          wSQL = :wSQL || '                                                                                                                                           WHEN C.BDCODTIPOCONTA = 406 THEN 173'; /*IPI - Outras*/
          wSQL = :wSQL || '                                                                                                                                       END)   ';
          wSQL = :wSQL || '        AND COALESCE(C.BDCONTARATEIO, ''FALSE'') = ''FALSE'' ';
          wSQL = :wSQL || '     ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDREFERENCIA = '||wfieldref||' AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
          wSQL = :wSQL || '                                                                 WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
          wSQL = :wSQL || '                                                                 WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
          wSQL = :wSQL || '                                                            END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL))); ';
          EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERT_INCONSISTENCIAS_CONTA','6');
          /*------------------------------------------------------------------------------------------------------*/
        END

      IF (((:FCONTABILIZAPIS = 0) AND ((:PRCODCONFIRLP IS NULL) OR (:PRCODCONFIRLP = 0))) or ((:FCONTABILIZAPISLP = 1) and (:FCONTPISCOFLP = 'TRUE'))) THEN /*0 - nota a nota, deve exigir a conta de PIS*/
        BEGIN
          /*-------------------------------------------------PIS--------------------------------------------------*/
          wSQL =          'INSERT INTO '||:FTableIncon||'(bdcodemp, bdchave, '||:FCampoOrdem||', bdsessao, bdcodinconsistencia, BDTIPOINCON, bdcodnat, bdcondpgto,BDCODPLANOONLINE) ';
          wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDCHAVE, I.'||:FCampoOrdem||', I.BDSESSAO, 29 BDINCONSISTENCIA, 2 BDTIPOINCON, I.BDCODNAT, MOV.BDCONDPGTO , '||:PRCODPLANOONLINE;
          wSQL = :wSQL || 'FROM ( ';
          wSQL = :wSQL || '      SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, S.'||wfielddata;
          wSQL = :wSQL || '      FROM '||:FTable||' S ';
          wSQL = :wSQL || '      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
          wSQL = :wSQL || '      WHERE S.BDSESSAO = '||:PRSESSAO;
          wSQL = :wSQL || '      AND S.BDCODSITNF <> '||:wSitCanc; /*2 - Cancelada, não contabiliza*/
          wSQL = :wSQL || '      AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';

          IF (:wTipLan IS NOT NULL) THEN
            wSQL = :wSQL || '      AND S.BDTIPLAN = '||:wTipLan;

          wSQL = :wSQL || '     ) MOV ';
          wSQL = :wSQL || 'JOIN '||:FTableItem||' I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO AND I.BDVLRPIS > 0) ';
          wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'' ';

          -- Se for entrada pode ser apenas CFOP de devolução para lucro presumido
          IF ((:PRTIPOLAN = 'ENT') AND (((:PRENQFED = 3) AND (:PRFORMATRIB = 1)) AND (:FCONTABILIZAPISLP = 1))) THEN
            wSQL = :wSQL || 'AND NAT.BDDEVOL = ''TRUE''';
          wSQL = :wSQL || ')';

          wSQL = :wSQL || 'JOIN (';
          wSQL = :wSQL || '      SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, c.BDREFERENCIA ';
          wSQL = :wSQL || '      FROM TCONTAS_ONLINE_TEMP C ';
          --wSQL = :wSQL || '      WHERE (C.BDSESSAO = '||:PRSESSAO||') AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE IN (115, 121, 174) /*PIS*/ ';
          wSQL = :wSQL || '      WHERE (C.BDSESSAO = '||:PRSESSAO||') AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND (C.BDCODITEMONLINE = CASE WHEN C.BDCODTIPOCONTA =  50 THEN 115 '; /*PIS - A vista*/
          wSQL = :wSQL || '                                                                                                                                         WHEN C.BDCODTIPOCONTA =  51 THEN 121 '; /*PIS - Prazo*/
          wSQL = :wSQL || '                                                                                                                                         WHEN C.BDCODTIPOCONTA = 406 THEN 174 '; /*PIS - Outras*/
          wSQL = :wSQL || '                                                                                                                                    END)       ';
          wSQL = :wSQL || '      AND COALESCE(C.BDCONTARATEIO, ''FALSE'') = ''FALSE'' ';
          wSQL = :wSQL || '     ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDREFERENCIA = '||wfieldref||' AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
          wSQL = :wSQL || '                                                                 WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
          wSQL = :wSQL || '                                                                 WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
          wSQL = :wSQL || '                                                            END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL))); ';
          EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERT_INCONSISTENCIAS_CONTA','7');
        END

      IF (((:FCONTABILIZACOFINS = 0) AND ((:PRCODCONFIRLP IS NULL) OR (:PRCODCONFIRLP = 0))) or ((:FCONTABILIZACOFINSLP = 1) and (:FCONTPISCOFLP = 'TRUE')))  THEN /*0 - nota a nota, deve exigir a conta de Cofins*/
        BEGIN
          /*-----------------------------------------------COFINS-------------------------------------------------*/
          wSQL =          'INSERT INTO '||:FTableIncon||'(bdcodemp, bdchave, '||:FCampoOrdem||', bdsessao, bdcodinconsistencia, BDTIPOINCON, bdcodnat, bdcondpgto,BDCODPLANOONLINE) ';
          wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDCHAVE, I.'||:FCampoOrdem||', I.BDSESSAO, 30 BDINCONSISTENCIA, 2 BDTIPOINCON, I.BDCODNAT, MOV.BDCONDPGTO , '||:PRCODPLANOONLINE;
          wSQL = :wSQL || 'FROM ( ';
          wSQL = :wSQL || '      SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, S.'||wfielddata;
          wSQL = :wSQL || '      FROM '||:FTable||' S ';
          wSQL = :wSQL || '      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
          wSQL = :wSQL || '      WHERE S.BDSESSAO = '||:PRSESSAO;
          wSQL = :wSQL || '      AND S.BDCODSITNF <> '||:wSitCanc; /*2 - Cancelada, não contabiliza*/
          wSQL = :wSQL || '      AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';

          IF (:wTipLan IS NOT NULL) THEN
            wSQL = :wSQL || '      AND S.BDTIPLAN = '||:wTipLan;

          wSQL = :wSQL || '     ) MOV ';
          wSQL = :wSQL || 'JOIN '||:FTableItem||' I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO AND I.BDVLRCOFINS > 0) ';
          wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDCONTABILIZA = ''TRUE'' ';

          -- Se for entrada pode ser apenas CFOP de devolução para lucro presumido
          IF ((:PRTIPOLAN = 'ENT') AND (((:PRENQFED = 3) AND (:PRFORMATRIB = 1)) AND (:FCONTABILIZACOFINSLP = 1))) THEN
            wSQL = :wSQL || 'AND NAT.BDDEVOL = ''TRUE''';
          wSQL = :wSQL || ')';

          wSQL = :wSQL || 'JOIN ( ';
          wSQL = :wSQL || '      SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, c.BDREFERENCIA ';
          wSQL = :wSQL || '      FROM TCONTAS_ONLINE_TEMP C ';
--          wSQL = :wSQL || '      WHERE (C.BDSESSAO = '||:PRSESSAO||') AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE IN (116, 122, 175) /*Cofins*/ ';
          wSQL = :wSQL || '      WHERE  (C.BDSESSAO = '||:PRSESSAO||') AND  ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND (C.BDCODITEMONLINE = CASE WHEN C.BDCODTIPOCONTA =  50 THEN 116 '; /*Cofins - A vista*/
          wSQL = :wSQL || '                                                                                                                                           WHEN C.BDCODTIPOCONTA =  51 THEN 122 '; /*Cofins - Prazo*/
          wSQL = :wSQL || '                                                                                                                                           WHEN C.BDCODTIPOCONTA = 406 THEN 175 '; /*Cofins - Outras*/
          wSQL = :wSQL || '                                                                                                                                      END)            ';
          wSQL = :wSQL || '      AND COALESCE(C.BDCONTARATEIO, ''FALSE'') = ''FALSE'' ';
          wSQL = :wSQL || '     ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDREFERENCIA = '||wfieldref||' AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
          wSQL = :wSQL || '                                                                 WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
          wSQL = :wSQL || '                                                                 WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
          wSQL = :wSQL || '                                                            END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL))); ';
          EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERT_INCONSISTENCIAS_CONTA','8');
        END
    END
  /*------------------------------------------------------------------------------------------------------*/

  IF (:FTableFunRual <> '') THEN
    BEGIN
      /*--------------------------------------------- FunRural -----------------------------------------------*/
      wSQL =          'insert into '||:FTableIncon||'(bdCODEMP, bdCHAVE, '||:FCampoOrdem||', bdSESSAO, bdCODINCONSISTENCIA, bdTIPOINCON, bdcodnat, bdcondpgto,BDCODPLANOONLINE) ';
      wSQL = :wSQL || 'select i.bdCODEMP, i.bdCHAVE, i.'||:FCampoOrdem||', i.bdSESSAO, 145 as bdINCONSISTENCIA, 2 as bdTIPOINCON, I.BDCODNAT, MOV.BDCONDPGTO , '||:PRCODPLANOONLINE;
      wSQL = :wSQL || 'from ( ';
      wSQL = :wSQL || '       select s.bdCODEMP, s.bdCHAVE, s.bdSESSAO, COALESCE(s.bdCONDPGTO, 0) as bdCONDPGTO, S.'||wfielddata;
      wSQL = :wSQL || '       from '||:FTable||' s ';
      wSQL = :wSQL || '       join '||:FTableFunRual||' fr on (fr.bdCODEMP = s.bdCODEMP and fr.bdCHAVE = s.bdCHAVE and fr.bdSESSAO = s.bdSESSAO) ';
      wSQL = :wSQL || '       LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
      wSQL = :wSQL || '       where s.bdSESSAO = '||:prSESSAO;
      wSQL = :wSQL || '       AND S.BDCODSITNF <> '||:wSitCanc; /*2 - Cancelada, não contabiliza*/
      wSQL = :wSQL || '       AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';
      
      IF (:PRTIPOLAN = 'SAI') THEN
        wSQL = :wSQL || '       AND ((fr.bdVLRFUNRURAL > 0) or (fr.bdVLRGILRAT > 0) or (fr.bdVLRSENAR > 0)) ';
      ELSE
        wSQL = :wSQL || '       AND ((fr.bdVLRFUNRURAL > 0) or (fr.bdVLRGILRAT > 0) or (fr.BDVLRFPAS > 0)) ';

      IF (:wTipLan IS NOT NULL) THEN
        wSQL = :wSQL || '      AND S.BDTIPLAN = '||:wTipLan;

      wSQL = :wSQL || '     ) mov ';
      wSQL = :wSQL || 'left outer join '||:FTableItem||' i on (i.bdCODEMP = mov.bdCODEMP and i.bdCHAVE = mov.bdCHAVE and i.bdSESSAO = mov.bdSESSAO) ';
      wSQL = :wSQL || 'join TCONTAS_ONLINE_TEMP o on (o.bdSESSAO = mov.bdSESSAO AND O.BDREFERENCIA = '||wfieldref||' and o.bdCODITEMONLINE = '||wCodItemFunRural||') ';
      wSQL = :wSQL || 'where (o.'||wContaProv||' IS NULL); ';
      EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERT_INCONSISTENCIAS_CONTA','9');
      /*------------------------------------------------------------------------------------------------------*/
    END

  IF (:FTableRet = '') THEN
    EXIT;

  /*-------------------------------------------PIS(Retenção)----------------------------------------------*/
  wSQL =          'INSERT INTO '||:FTableIncon||'(bdcodemp, bdchave, '||:FCampoOrdem||', bdsessao, bdcodinconsistencia, BDTIPOINCON,BDCODPLANOONLINE) ';
  wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDCHAVE, I.'||:FCampoOrdem||', I.BDSESSAO, 39 BDINCONSISTENCIA, 2 BDTIPOINCON , '||:PRCODPLANOONLINE;
  wSQL = :wSQL || 'FROM ( ';
  wSQL = :wSQL || '      SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, R.BDCODRECPIS BDCODREC, S.'||wfielddata;
  wSQL = :wSQL || '      FROM '||:FTable||' S ';
  wSQL = :wSQL || '      JOIN '||:FTableRet||' R ON(R.BDCODEMP = S.BDCODEMP AND R.BDCHAVE = S.BDCHAVE AND R.BDSESSAO = R.BDSESSAO AND R.BDVLRPIS > 0) ';
  wSQL = :wSQL || '      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
  wSQL = :wSQL || '      WHERE S.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL || '      AND S.BDCODSITNF <> '||:wSitCanc; /*2 - Cancelada, não contabiliza*/
  wSQL = :wSQL || '      AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';

  IF (:wTipLan IS NOT NULL) THEN
    wSQL = :wSQL || '      AND S.BDTIPLAN = '||:wTipLan;

  wSQL = :wSQL || '     ) MOV ';
  wSQL = :wSQL || 'LEFT OUTER JOIN '||:FTableItem||' I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO) ';
  wSQL = :wSQL || 'JOIN ( ';
  wSQL = :wSQL || '      SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, C.BDCODREC, c.BDREFERENCIA ';
  wSQL = :wSQL || '      FROM TCONTAS_ONLINE_TEMP C ';
  wSQL = :wSQL || '      WHERE (C.BDSESSAO = '||:PRSESSAO||') AND (C.'||wContaProv||' IS NULL) AND (C.BDCODITEMONLINE = '||wCodItemPIS||') /*Pis retenção*/ ';
  wSQL = :wSQL || '     ) O ON(((O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
  wSQL = :wSQL || '                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
  wSQL = :wSQL || '                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
  wSQL = :wSQL || '                                                              END)) OR (COALESCE(O.BDCODREC,0) = COALESCE(MOV.BDCODREC,0))) AND ';
  wSQL = :wSQL || '(o.'||wContaProv||' IS NULL  AND O.BDREFERENCIA = '||wfieldref||')';
  wSQL = :wSQL || '); ';

  EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERT_INCONSISTENCIAS_CONTA','10');
  /*------------------------------------------------------------------------------------------------------*/

  /*------------------------------------------Cofins(Retenção)--------------------------------------------*/
  wSQL =          'INSERT INTO '||:FTableIncon||'(bdcodemp, bdchave, '||:FCampoOrdem||', bdsessao, bdcodinconsistencia, BDTIPOINCON,BDCODPLANOONLINE) ';
  wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDCHAVE, I.'||:FCampoOrdem||', I.BDSESSAO, 40 BDINCONSISTENCIA, 2 BDTIPOINCON , '||:PRCODPLANOONLINE;
  wSQL = :wSQL || 'FROM ( ';
  wSQL = :wSQL || '      SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, R.BDCODRECCOFINS BDCODREC, S.'||wfielddata;
  wSQL = :wSQL || '      FROM '||:FTable||' S ';
  wSQL = :wSQL || '      JOIN '||:FTableRet||' R ON(R.BDCODEMP = S.BDCODEMP AND R.BDCHAVE = S.BDCHAVE AND R.BDSESSAO = R.BDSESSAO AND R.BDVLRCOFINS > 0) ';
  wSQL = :wSQL || '      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
  wSQL = :wSQL || '      WHERE S.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL || '      AND S.BDCODSITNF <> '||:wSitCanc; /*2 - Cancelada, não contabiliza*/
  wSQL = :wSQL || '      AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';

  IF (:wTipLan IS NOT NULL) THEN
    wSQL = :wSQL || '      AND S.BDTIPLAN = '||:wTipLan;

  wSQL = :wSQL || '     ) MOV ';
  wSQL = :wSQL || 'LEFT OUTER JOIN '||:FTableItem||' I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO) ';
  wSQL = :wSQL || 'JOIN ( ';
  wSQL = :wSQL || '      SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, C.BDCODREC, c.BDREFERENCIA ';
  wSQL = :wSQL || '      FROM TCONTAS_ONLINE_TEMP C ';
  wSQL = :wSQL || '      WHERE (C.BDSESSAO = '||:PRSESSAO||') AND (C.'||wContaProv||' IS NULL) AND (C.BDCODITEMONLINE = '||wCodItemCofins||') /*Cofins retenção*/ ';
  wSQL = :wSQL || '     ) O ON(((O.BDCODNAT = I.BDCODNAT AND O.BDREFERENCIA = '||wfieldref||' AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
  wSQL = :wSQL || '                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
  wSQL = :wSQL || '                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
  wSQL = :wSQL || '                                                              END)) OR (COALESCE(O.BDCODREC,0) = COALESCE(MOV.BDCODREC,0))) AND ';
  wSQL = :wSQL || '(o.'||wContaProv||' IS NULL)';
  wSQL = :wSQL || '); ';
  EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERT_INCONSISTENCIAS_CONTA','11');
  /*------------------------------------------------------------------------------------------------------*/

  /*-----------------------------------Contribuição social(Retenção)--------------------------------------*/
  wSQL =          'INSERT INTO '||:FTableIncon||'(bdcodemp, bdchave, '||:FCampoOrdem||', bdsessao, bdcodinconsistencia, BDTIPOINCON,BDCODPLANOONLINE) ';
  wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDCHAVE, I.'||:FCampoOrdem||', I.BDSESSAO, 41 BDINCONSISTENCIA, 2 BDTIPOINCON , '||:PRCODPLANOONLINE;
  wSQL = :wSQL || 'FROM ( ';
  wSQL = :wSQL || '      SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, R.BDCODRECCSOCIAL BDCODREC, S.'||wfielddata;
  wSQL = :wSQL || '      FROM '||:FTable||' S ';
  wSQL = :wSQL || '      JOIN '||:FTableRet||' R ON(R.BDCODEMP = S.BDCODEMP AND R.BDCHAVE = S.BDCHAVE AND R.BDSESSAO = R.BDSESSAO AND R.BDVLRCSOCIAL > 0) ';
  wSQL = :wSQL || '      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
  wSQL = :wSQL || '      WHERE S.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL || '      AND S.BDCODSITNF <> '||:wSitCanc; /*2 - Cancelada, não contabiliza*/
  wSQL = :wSQL || '      AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';

  IF (:wTipLan IS NOT NULL) THEN
    wSQL = :wSQL || '      AND S.BDTIPLAN = '||:wTipLan;

  wSQL = :wSQL || '     ) MOV ';
  wSQL = :wSQL || 'LEFT OUTER JOIN '||:FTableItem||' I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO) ';
  wSQL = :wSQL || 'JOIN ( ';
  wSQL = :wSQL || '      SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, C.BDCODREC, c.BDREFERENCIA ';
  wSQL = :wSQL || '      FROM TCONTAS_ONLINE_TEMP C ';
  wSQL = :wSQL || '      WHERE (C.BDSESSAO = '||:PRSESSAO||') AND (C.'||wContaProv||' IS NULL) AND (C.BDCODITEMONLINE = '||wCodItemCSocial||') /*CS retenção*/ ';
  wSQL = :wSQL || '     ) O ON(((O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
  wSQL = :wSQL || '                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
  wSQL = :wSQL || '                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
  wSQL = :wSQL || '                                                              END)) OR (COALESCE(O.BDCODREC,0) = COALESCE(MOV.BDCODREC,0))) AND ';
  wSQL = :wSQL || '(o.'||wContaProv||' IS NULL AND O.BDREFERENCIA = '||wfieldref||')';
  wSQL = :wSQL || '); ';
  EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERT_INCONSISTENCIAS_CONTA','12');
  /*------------------------------------------------------------------------------------------------------*/

  /*--------------------------------------------IR(Retenção)----------------------------------------------*/
  wSQL =          'INSERT INTO '||:FTableIncon||'(bdcodemp, bdchave, '||:FCampoOrdem||', bdsessao, bdcodinconsistencia, BDTIPOINCON,BDCODPLANOONLINE) ';
  wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDCHAVE, I.'||:FCampoOrdem||', I.BDSESSAO, 44 BDINCONSISTENCIA, 2 BDTIPOINCON, '||:PRCODPLANOONLINE;
  wSQL = :wSQL || 'FROM ( ';
  wSQL = :wSQL || '      SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto '||IIF(POSITION('SER', :PRTIPOLAN) > 0, '', ', R.BDCODRECIR BDCODREC')||', S.'||wfielddata;
  wSQL = :wSQL || '      FROM '||:FTable||' S ';
  wSQL = :wSQL || '      JOIN '||:FTableRet||' R ON(R.BDCODEMP = S.BDCODEMP AND R.BDCHAVE = S.BDCHAVE AND R.BDSESSAO = R.BDSESSAO AND R.BDVLRIR > 0) ';
  wSQL = :wSQL || '      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
  wSQL = :wSQL || '      WHERE S.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL || '      AND S.BDCODSITNF <> '||:wSitCanc; /*2 - Cancelada, não contabiliza*/
  wSQL = :wSQL || '      AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';

  IF (:wTipLan IS NOT NULL) THEN
    wSQL = :wSQL || '      AND S.BDTIPLAN = '||:wTipLan;

  wSQL = :wSQL || '     ) MOV ';
  wSQL = :wSQL || 'LEFT OUTER JOIN '||:FTableItem||' I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO) ';
  wSQL = :wSQL || 'JOIN ( ';
  wSQL = :wSQL || '      SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, C.BDCODREC, c.BDREFERENCIA ';
  wSQL = :wSQL || '      FROM TCONTAS_ONLINE_TEMP C ';
  wSQL = :wSQL || '      WHERE (C.BDSESSAO = '||:PRSESSAO||') AND (C.'||wContaProv||' IS NULL) AND (C.BDCODITEMONLINE = '||wCodItemIR||') /*IR retenção*/ ';
  wSQL = :wSQL || '     ) O ON(((O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
  wSQL = :wSQL || '                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
  wSQL = :wSQL || '                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
  wSQL = :wSQL || '                                                              END)) OR (COALESCE(O.BDCODREC,0) = COALESCE('||IIF(POSITION('SER', :PRTIPOLAN) > 0, 'I.', 'MOV.')||'BDCODREC,0))) AND ';
  wSQL = :wSQL || '(o.'||wContaProv||' IS NULL AND O.BDREFERENCIA = '||wfieldref||')';
  wSQL = :wSQL || '); ';
  EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERT_INCONSISTENCIAS_CONTA','13');
  /*------------------------------------------------------------------------------------------------------*/

  /*--------------------------------------------INSS(Retenção)----------------------------------------------*/
  wSQL =          'INSERT INTO '||:FTableIncon||'(bdcodemp, bdchave, '||:FCampoOrdem||', bdsessao, bdcodinconsistencia, BDTIPOINCON,BDCODPLANOONLINE) ';
  wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDCHAVE, I.'||:FCampoOrdem||', I.BDSESSAO, 42 BDINCONSISTENCIA, 2 BDTIPOINCON , '||:PRCODPLANOONLINE;
  wSQL = :wSQL || 'FROM ( ';
  wSQL = :wSQL || '      SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, S.'||wfielddata;
  wSQL = :wSQL || '      FROM '||:FTable||' S ';
  wSQL = :wSQL || '      JOIN '||:FTableINSS||' D ON(D.BDCODEMP = S.BDCODEMP AND D.BDCHAVE = S.BDCHAVE AND D.BDSESSAO = S.BDSESSAO AND D.BDRETINSS > 0) ';
  wSQL = :wSQL || '      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
  wSQL = :wSQL || '      WHERE S.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL || '      AND S.BDCODSITNF <> '||:wSitCanc; /*2 - Cancelada, não contabiliza*/
  wSQL = :wSQL || '      AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';
  wSQL = :wSQL || '     ) MOV ';
  wSQL = :wSQL || 'LEFT OUTER JOIN '||:FTableItem||' I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO) ';
  wSQL = :wSQL || 'JOIN ( ';
  wSQL = :wSQL || '      SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, c.BDREFERENCIA ';
  wSQL = :wSQL || '      FROM TCONTAS_ONLINE_TEMP C ';
  wSQL = :wSQL || '      WHERE (C.BDSESSAO = '||:PRSESSAO||') AND (C.'||wContaProv||' IS NULL) AND (C.BDCODITEMONLINE = '||wCodItemINSS||') /*INSS retenção*/ ';
  wSQL = :wSQL || '     ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
  wSQL = :wSQL || '                                                                 WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
  wSQL = :wSQL || '                                                                 WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
  wSQL = :wSQL || '                                                            END) AND ';
  wSQL = :wSQL || '(o.'||wContaProv||' IS NULL AND O.BDREFERENCIA = '||wfieldref||')';
  wSQL = :wSQL || '); ';
  EXECUTE STATEMENT :wSQL;     
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERT_INCONSISTENCIAS_CONTA','14');
  wSQL =          'INSERT INTO '||:FTableIncon||'(bdcodemp, bdchave, '||:FCampoOrdem||', bdsessao, bdcodinconsistencia, BDTIPOINCON,BDCODPLANOONLINE) ';
  wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDCHAVE, I.'||:FCampoOrdem||', I.BDSESSAO, 42 BDINCONSISTENCIA, 2 BDTIPOINCON , '||:PRCODPLANOONLINE;
  wSQL = :wSQL || 'FROM ( ';
  wSQL = :wSQL || '      SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, S.'||wfielddata;
  wSQL = :wSQL || '      FROM '||:FTable||' S ';
  wSQL = :wSQL || '      JOIN '||:FTableINSS||' D ON(D.BDCODEMP = S.BDCODEMP AND D.BDCHAVE = S.BDCHAVE AND D.BDSESSAO = S.BDSESSAO AND D.BDRETINSS > 0) ';
  wSQL = :wSQL || '      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
  wSQL = :wSQL || '      WHERE S.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL || '      AND S.BDCODSITNF <> '||:wSitCanc; /*2 - Cancelada, não contabiliza*/
  wSQL = :wSQL || '      AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';
  wSQL = :wSQL || '     ) MOV ';
  wSQL = :wSQL || 'LEFT OUTER JOIN '||:FTableItem||' I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO) ';
  wSQL = :wSQL || 'JOIN ( ';
  wSQL = :wSQL || '      SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, c.BDREFERENCIA ';
  wSQL = :wSQL || '      FROM TCONTAS_ONLINE_TEMP C ';
  wSQL = :wSQL || '      WHERE (C.BDSESSAO = '||:PRSESSAO||') AND (C.'||wContaProv||' IS NULL) AND (C.BDCODITEMONLINE = '||wCodItemINSS||') /*INSS retenção*/ ';
  wSQL = :wSQL || '     ) O ON(O.BDCODNAT IS NULL AND O.BDCODTIPOCONTA IS NULL AND (o.'||wContaProv||' IS NULL AND O.BDREFERENCIA = '||wfieldref||')';
  wSQL = :wSQL || '); ';
  EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERT_INCONSISTENCIAS_CONTA','15');
  /*------------------------------------------------------------------------------------------------------*/

  /*--------------------------------------------ISS(Retenção)----------------------------------------------*/
  
  wSQL =          'INSERT INTO '||:FTableIncon||'(bdcodemp, bdchave, '||:FCampoOrdem||', bdsessao, bdcodinconsistencia, BDTIPOINCON,BDCODPLANOONLINE) ';
  wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDCHAVE, I.'||:FCampoOrdem||', I.BDSESSAO, 43 BDINCONSISTENCIA, 2 BDTIPOINCON , '||:PRCODPLANOONLINE;
  wSQL = :wSQL || 'FROM ( ';
  wSQL = :wSQL || '      SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, '||IIF((POSITION('SER', :PRTIPOLAN) = 0), 'R.BDCODRECISS', '-1')||' BDCODREC, S.'||wfielddata;
  wSQL = :wSQL || '      FROM '||:FTable||' S ';
  wSQL = :wSQL || '      JOIN '||:FTableRet||' R ON(R.BDCODEMP = S.BDCODEMP AND R.BDCHAVE = S.BDCHAVE AND R.BDSESSAO = R.BDSESSAO AND R.BDISSRET > 0) ';
  wSQL = :wSQL || '      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
  wSQL = :wSQL || '      WHERE S.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL || '      AND S.BDCODSITNF <> '||:wSitCanc; /*2 - Cancelada, não contabiliza*/
  wSQL = :wSQL || '      AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';

  IF (:wTipLan IS NOT NULL) THEN
    wSQL = :wSQL || '      AND S.BDTIPLAN = '||:wTipLan;

  wSQL = :wSQL || '     ) MOV ';
  wSQL = :wSQL || 'LEFT OUTER JOIN '||:FTableItem||' I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO) ';
  wSQL = :wSQL || 'JOIN ( ';
  wSQL = :wSQL || '      SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, C.BDCODREC, c.BDREFERENCIA ';
  wSQL = :wSQL || '      FROM TCONTAS_ONLINE_TEMP C ';
  wSQL = :wSQL || '      WHERE (C.BDSESSAO = '||:PRSESSAO||') AND (C.'||wContaProv||' IS NULL) AND (C.BDCODITEMONLINE = '||wCodItemISS||') /*ISS retenção*/ ';
  wSQL = :wSQL || '     ) O ON(((O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
  wSQL = :wSQL || '                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
  wSQL = :wSQL || '                                                                   WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
  wSQL = :wSQL || '                                                              END)) OR (COALESCE(O.BDCODREC,0) = COALESCE(MOV.BDCODREC,0))) AND ';
  wSQL = :wSQL || '(o.'||wContaProv||' IS NULL AND O.BDREFERENCIA = '||wfieldref||')';
  wSQL = :wSQL || '); ';
  EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERT_INCONSISTENCIAS_CONTA','16');

--  wSQL =          'INSERT INTO '||:FTableIncon||'(bdcodemp, bdchave, '||:FCampoOrdem||', bdsessao, bdcodinconsistencia, BDTIPOINCON,BDCODPLANOONLINE) ';
--  wSQL = :wSQL || 'SELECT I.BDCODEMP, I.BDCHAVE, I.'||:FCampoOrdem||', I.BDSESSAO, 43 BDINCONSISTENCIA, 2 BDTIPOINCON , '||:PRCODPLANOONLINE;
--  wSQL = :wSQL || 'FROM ( ';
--  wSQL = :wSQL || '      SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, S.'||wfielddata;
--  wSQL = :wSQL || '      FROM '||:FTable||' S ';
--  wSQL = :wSQL || '      JOIN '||:FTableRet||' R ON(R.BDCODEMP = S.BDCODEMP AND R.BDCHAVE = S.BDCHAVE AND R.BDSESSAO = R.BDSESSAO AND R.BDISSRET > 0) ';
--  wSQL = :wSQL || '      LEFT OUTER JOIN TINICIO_CONTABILIZACAO IC ON(IC.BDCODEMP = S.BDCODEMP AND IC.BDCODSIS = '||:wEF||') ';
--  wSQL = :wSQL || '      WHERE S.BDSESSAO = '||:PRSESSAO;
--  wSQL = :wSQL || '      AND S.BDCODSITNF <> '||:wSitCanc; /*2 - Cancelada, não contabiliza*/
--  wSQL = :wSQL || '      AND ((IC.BDCODEMP IS NULL) or (IC.BDDATA is null) or ((IC.BDCODEMP IS NOT NULL) AND (IC.BDDATA <= S.'||wfielddata||'))) ';
--
--  IF (:wTipLan IS NOT NULL) THEN
--    wSQL = :wSQL || '      AND S.BDTIPLAN = '||:wTipLan;
--
--  wSQL = :wSQL || '     ) MOV ';
--  wSQL = :wSQL || 'LEFT OUTER JOIN '||:FTableItem||' I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO) ';
--  wSQL = :wSQL || 'JOIN ( ';
--  wSQL = :wSQL || '      SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, c.BDREFERENCIA ';
--  wSQL = :wSQL || '      FROM TCONTAS_ONLINE_TEMP C ';
--  wSQL = :wSQL || '      WHERE (C.BDSESSAO = '||:PRSESSAO||') AND (C.'||wContaProv||' IS NULL) AND (C.BDCODITEMONLINE = '||wCodItemISS||') /*ISS retenção*/ ';
--  --wSQL = :wSQL || '      WHERE (C.BDSESSAO = '||:PRSESSAO||') /*ISS retenção*/ ';
--  wSQL = :wSQL || '     ) O ON(O.BDCODNAT = I.BDCODNAT AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
--  wSQL = :wSQL || '                                                                 WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
--  wSQL = :wSQL || '                                                                 WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
--  --wSQL = :wSQL || '                                                            END) ';
--  --wSQL = :wSQL || '(o.'||wContaProv||' IS NULL AND O.BDREFERENCIA = '||wfieldref||')';
--  wSQL = :wSQL || '                                                            END) AND ';
--  wSQL = :wSQL || '(o.'||wContaProv||' IS NULL AND O.BDREFERENCIA = '||wfieldref||')';
--  wSQL = :wSQL || '); ';
--  EXECUTE STATEMENT :wSQL;
  /*------------------------------------------------------------------------------------------------------*/

  /*---------------------------------------BLOQUEIO DE CONTAS---------------------------------------------*/
  wSQL =          'INSERT INTO '||:FTableIncon||'(bdcodemp, bdchave, '||:FCampoOrdem||', bdsessao, bdcodinconsistencia,BDCODPLANOONLINE,BDTIPOINCON, BDCODNAT) ';
  wSQL = :wSQL || '  SELECT I.BDCODEMP, I.BDCHAVE, I.'||:FCampoOrdem||', I.BDSESSAO, 128 BDINCONSISTENCIA , '||:PRCODPLANOONLINE || ', 2 as BDTIPOINCON, I.BDCODNAT ';
  wSQL = :wSQL || 'FROM (SELECT S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, coalesce(S.BDCONDPGTO, 0) BDCONDPGTO, S.'||wfielddata;
  wSQL = :wSQL || '      FROM '||:FTable||' S ';
  wSQL = :wSQL || '      WHERE S.BDSESSAO = '||:PRSESSAO;

  IF (:wTipLan IS NOT NULL) THEN
    wSQL = :wSQL || '      AND S.BDTIPLAN = '||:wTipLan;

  wSQL = :wSQL || '      AND S.BDCODSITNF <> '||:wSitCanc||') MOV '; /*2 - Cancelada, não contabiliza*/
  wSQL = :wSQL || '  LEFT OUTER JOIN '||:FTableItem||' I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDSESSAO = MOV.BDSESSAO) ';
  wSQL = :wSQL || '  JOIN TCONTAS_ONLINE_TEMP O ON (O.BDCODNAT = I.BDCODNAT AND O.BDREFERENCIA = '||wfieldref||' AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50 ';
  wSQL = :wSQL || '                                                                                      WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51 ';
  wSQL = :wSQL || '                                                                                      WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406 ';
  wSQL = :wSQL || '                                                                                 END)) ';
  wSQL = :wSQL || ' JOIN TBLOQCTA_USUARIO TUSU ON (TUSU.BDCODEMP = I.BDCODEMP AND TUSU.BDCODUSU = (SELECT BDCODUSU FROM SP_GET_USUARIO) AND TUSU.BDCODTPLA IN (O.BDCONTADEBPROV, O.BDCONTACREDPROV)) ';
  wSQL = :wSQL || ' WHERE EXISTS(SELECT FIRST 1 TBLOQ.BDCODEMP ';
  wSQL = :wSQL || '              FROM TBLOQCTA TBLOQ ';
  wSQL = :wSQL || '              WHERE (TBLOQ.BDCODPLAPADRAO = TUSU.BDCODPLAPADRAO AND       ';
  wSQL = :wSQL || '                     TBLOQ.BDCODEMP = TUSU.BDCODEMP AND                 ';
  wSQL = :wSQL || '                     TBLOQ.BDREFEMP = TUSU.BDREFEMP AND ';
  wSQL = :wSQL || '                    (TBLOQ.BDCODTPLA = TUSU.BDCODTPLA) AND ';
  wSQL = :wSQL || '                    (TBLOQ.BDCODBLQ = TUSU.BDCODBLQ) ';
  wSQL = :wSQL || '                    AND (MOV.'||wfielddata||' between TBLOQ.BDDATAINICIAL AND TBLOQ.BDDATAFINAL) ';
  wSQL = :wSQL || '                 )); ';
  EXECUTE STATEMENT :wSQL;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERT_INCONSISTENCIAS_CONTA','17');
  /*------------------------------------------------------------------------------------------------------*/
END^

CREATE OR ALTER PROCEDURE sp_insert_inconsis_conta_redz (
    prsessao INTEGER,
    prcodplanoonline INTEGER,
    prenqfed INTEGER)
AS
DECLARE VARIABLE fcontabilizaicms INTEGER;
DECLARE VARIABLE fcontabilizapis INTEGER;
DECLARE VARIABLE fcontabilizacofins INTEGER;
DECLARE VARIABLE wbdcodconfirlp INTEGER;
DECLARE VARIABLE wbdcodconfdacon INTEGER;
DECLARE VARIABLE wbdtipoconfdacon INTEGER;
BEGIN
  SELECT P.BDTIPOINTICMS,  P.BDTIPOINTPIS, P.BDTIPOINTCOFINS
  FROM TPLANO_CONF_ONLINE P
  WHERE P.BDCODPLANOONLINE = :PRCODPLANOONLINE
  INTO :FCONTABILIZAICMS, :FCONTABILIZAPIS, :FCONTABILIZACOFINS;


  select coalesce(TREFSIS.BDCODCONFIRLP,0), coalesce(TREFSIS.BDCODCONFDACON,0), conf.bdtipoconfdacon
  from (
        select t.bdcodemp
        from TMP_VEF_EMP_TREDZVARCFOP_TEMP t
        WHERE BDSESSAO = :PRSESSAO
        group by t.bdcodemp
        ) tmp
  left outer join vw_VEF_BASE_TEMPPARGER TREFSIS on (TREFSIS.bdcodemp = tmp.bdcodemp)
  left outer join VEF_BASE_TCONFDACON conf on (conf.bdcodconfdacon = TREFSIS.BDCODCONFDACON)
  INTO :WBDCODCONFIRLP,:WBDCODCONFDACON ,:Wbdtipoconfdacon;

  --Se for lucro presumido sempre será contabilizado pelo darf
  --Elizeu - 13-08-18 - Contabilizando PIS/Cofins nota a nota Lucro Presumido
  if (((:WBDCODCONFIRLP > 0)) or (((:WBDCODCONFDACON > 0) and (:Wbdtipoconfdacon = 0))))   then
    begin
      FCONTABILIZACOFINS = 2; /*tiValoresDarfCofins*/
      FCONTABILIZAPIS    = 2; /*tiValoresDarfPis*/
    end


  /*27 - Conta(s) do "Valor contábil" não informada(s) para configuração do plano de contabilização da empresa*/
  /*--------------------------------------------Valor contábil--------------------------------------------*/
  INSERT INTO VEF_INCON_TREDZ(bdcodemp, bdchave, BDORDEMVARCFOP, bdsessao, bdcodinconsistencia, bdcodnat, bdcondpgto,BDCODPLANOONLINE)
  SELECT MOV.BDCODEMP, MOV.BDCHAVE, (SELECT FIRST 1 O.BDORDEMVARCFOP
                                     FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP O
                                     WHERE O.BDSESSAO = MOV.BDSESSAO
                                     AND O.BDCODEMP = MOV.BDCODEMP
                                     AND O.BDCHAVE = MOV.BDCHAVE
                                     AND O.BDCODNAT = MOV.BDCODNAT
                                     ORDER BY O.BDORDEMVARCFOP) BDORDEMVARCFOP,
         MOV.BDSESSAO, 27 BDINCONSISTENCIA, MOV.BDCODNAT, MOV.BDCONDPGTO,:PRCODPLANOONLINE
  FROM (
        SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, s.bdcodnat, SUM(COALESCE(S.BDVLRCONTAB, 0)) BDVLRCONTAB,
        EXTRACT(YEAR FROM R.BDDATAREDZ)*100+EXTRACT(MONTH FROM R.BDDATAREDZ) AS BDREFERENCIA
        FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP S
        LEFT OUTER JOIN TMP_VEF_EMP_TREDZ_TEMP R ON (s.bdcodemp = R.BDCODEMP AND s.bdchave = R.BDCHAVE AND s.bdsessao = R.BDSESSAO)
        WHERE S.BDSESSAO = :PRSESSAO
        GROUP BY s.bdcodemp, s.bdchave, s.bdsessao, s.bdcondpgto, s.bdcodnat, EXTRACT(YEAR FROM R.BDDATAREDZ)*100+EXTRACT(MONTH FROM R.BDDATAREDZ)
       ) MOV
  JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = MOV.BDCODNAT AND NAT.BDCONTABILIZA = 'TRUE')
  JOIN (
        SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, c.BDREFERENCIA
        FROM TCONTAS_ONLINE_TEMP C
        --WHERE (C.BDSESSAO = :PRSESSAO) AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE IN (111, 117, 170) /*Valor contábil*/
        WHERE (C.BDSESSAO = :PRSESSAO) AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE = CASE WHEN C.BDCODTIPOCONTA = 50 THEN 111  /*Valor contábil - A vista*/
                                                                                                                                    WHEN C.BDCODTIPOCONTA = 51 THEN 117  /*Valor contábil - Prazo*/
                                                                                                                                    WHEN C.BDCODTIPOCONTA = 406 THEN 170 /*Valor contábil - Outras*/
                                                                                                                               END
       ) O ON(O.BDCODNAT = MOV.BDCODNAT AND O.BDREFERENCIA = MOV.BDREFERENCIA AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                     WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                     WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                                END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)))
  WHERE MOV.BDVLRCONTAB > 0;

  IF (:FCONTABILIZAICMS = 0) THEN
    BEGIN
      IF (:PRENQFED NOT IN(1, 2)) THEN
        BEGIN
          /*28 - Conta(s) do "ICMS" não informada(s) para configuração do plano de contabilização da empresa*/
          /*-------------------------------------------------ICMS-------------------------------------------------*/
          INSERT INTO VEF_INCON_TREDZ(bdcodemp, bdchave, bdordemvarcfop, bdsessao, bdcodinconsistencia, bdcodnat, bdcondpgto,BDCODPLANOONLINE)
          SELECT MOV.BDCODEMP, MOV.BDCHAVE, (SELECT FIRST 1 O.BDORDEMVARCFOP
                                             FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP O
                                             WHERE O.BDSESSAO = MOV.BDSESSAO
                                             AND O.BDCODEMP = MOV.BDCODEMP
                                             AND O.BDCHAVE = MOV.BDCHAVE
                                             AND O.BDCODNAT = MOV.BDCODNAT
                                             ORDER BY O.BDORDEMVARCFOP) BDORDEMVARCFOP, MOV.BDSESSAO, 28 BDINCONSISTENCIA, MOV.BDCODNAT, MOV.BDCONDPGTO,:PRCODPLANOONLINE
          FROM (
                SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, s.bdcodnat, SUM(COALESCE(S.BDVLRICMS, 0)) BDVLRICMS,
                EXTRACT(YEAR FROM R.BDDATAREDZ)*100+EXTRACT(MONTH FROM R.BDDATAREDZ) AS BDREFERENCIA
                FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP S    
                LEFT OUTER JOIN TMP_VEF_EMP_TREDZ_TEMP R ON (s.bdcodemp = R.BDCODEMP AND s.bdchave = R.BDCHAVE AND s.bdsessao = R.BDSESSAO)
                WHERE S.BDSESSAO = :PRSESSAO
                GROUP BY s.bdcodemp, s.bdchave, s.bdsessao, s.bdcondpgto, s.bdcodnat, EXTRACT(YEAR FROM R.BDDATAREDZ)*100+EXTRACT(MONTH FROM R.BDDATAREDZ)
               ) MOV
          JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = MOV.BDCODNAT AND NAT.BDCONTABILIZA = 'TRUE')
          JOIN (
                SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, c.BDREFERENCIA
                FROM TCONTAS_ONLINE_TEMP C
--                WHERE (C.BDSESSAO = :PRSESSAO) AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE IN (112, 118, 171) /*ICMS*/
                WHERE (C.BDSESSAO = :PRSESSAO) AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE = CASE WHEN C.BDCODTIPOCONTA = 50 THEN 112  /*ICMS - A vista*/
                                                                                                                                            WHEN C.BDCODTIPOCONTA = 51 THEN 118  /*ICMS - Prazo*/
                                                                                                                                            WHEN C.BDCODTIPOCONTA = 406 THEN 171 /*ICMS - Outras*/
                                                                                                                                       END
               ) O ON(O.BDCODNAT = MOV.BDCODNAT AND O.BDREFERENCIA = MOV.BDREFERENCIA AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                             WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                             WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                                        END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)))
          WHERE MOV.BDVLRICMS > 0;
          /*------------------------------------------------------------------------------------------------------*/
        END

      /*32 - Conta(s) do "ICMS ST" não informada(s) para configuração do plano de contabilização da empresa*/
      /*------------------------------------------------ICMS ST-----------------------------------------------*/
      INSERT INTO VEF_INCON_TREDZ(bdcodemp, bdchave, bdordemvarcfop, bdsessao, bdcodinconsistencia, bdcodnat, bdcondpgto,BDCODPLANOONLINE)
      SELECT MOV.BDCODEMP, MOV.BDCHAVE, (SELECT FIRST 1 O.BDORDEMVARCFOP
                                         FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP O
                                         WHERE O.BDSESSAO = MOV.BDSESSAO
                                         AND O.BDCODEMP = MOV.BDCODEMP
                                         AND O.BDCHAVE = MOV.BDCHAVE
                                         AND O.BDCODNAT = MOV.BDCODNAT
                                         ORDER BY O.BDORDEMVARCFOP) BDORDEMVARCFOP, MOV.BDSESSAO, 32 BDINCONSISTENCIA, MOV.BDCODNAT, MOV.BDCONDPGTO,:PRCODPLANOONLINE
      FROM (
            SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, s.bdcodnat, SUM(COALESCE(S.BDVLRST, 0)) BDVLRST,
            EXTRACT(YEAR FROM R.BDDATAREDZ)*100+EXTRACT(MONTH FROM R.BDDATAREDZ) AS BDREFERENCIA
            FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP S
            LEFT OUTER JOIN TMP_VEF_EMP_TREDZ_TEMP R ON (s.bdcodemp = R.BDCODEMP AND s.bdchave = R.BDCHAVE AND s.bdsessao = R.BDSESSAO)
            WHERE S.BDSESSAO = :PRSESSAO
            GROUP BY s.bdcodemp, s.bdchave, s.bdsessao, s.bdcondpgto, s.bdcodnat, EXTRACT(YEAR FROM R.BDDATAREDZ)*100+EXTRACT(MONTH FROM R.BDDATAREDZ)
           ) MOV
      JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = MOV.BDCODNAT AND NAT.BDCONTABILIZA = 'TRUE')
      JOIN (
            SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, c.BDREFERENCIA
            FROM TCONTAS_ONLINE_TEMP C
--            WHERE (C.BDSESSAO = :PRSESSAO) AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE IN (113, 119, 172) /*ICMS ST*/
            WHERE (C.BDSESSAO = :PRSESSAO) AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE = CASE WHEN C.BDCODTIPOCONTA = 50 THEN 113  /*ICMS ST - A vista*/
                                                                                                                                        WHEN C.BDCODTIPOCONTA = 51 THEN 119  /*ICMS ST - Prazo*/
                                                                                                                                        WHEN C.BDCODTIPOCONTA = 406 THEN 172 /*ICMS ST - Outras*/
                                                                                                                                   END
           ) O ON(O.BDCODNAT = MOV.BDCODNAT AND O.BDREFERENCIA = MOV.BDREFERENCIA AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                       WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                       WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                                  END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)))
      WHERE MOV.BDVLRST > 0;
      /*------------------------------------------------------------------------------------------------------*/
    END

  IF (:PRENQFED NOT IN(1, 2)) THEN
    BEGIN
      IF (:FCONTABILIZAPIS = 0) THEN /*0 - nota a nota, deve exigir a conta de PIS*/
        BEGIN
          /*29 - Conta(s) do "PIS" não informada(s) para configuração do plano de contabilização da empresa*/
          /*-------------------------------------------------PIS--------------------------------------------------*/
          INSERT INTO VEF_INCON_TREDZ(bdcodemp, bdchave, bdordemvarcfop, bdsessao, bdcodinconsistencia, bdcodnat, bdcondpgto,BDCODPLANOONLINE)
          SELECT MOV.BDCODEMP, MOV.BDCHAVE, (SELECT FIRST 1 O.BDORDEMVARCFOP
                                             FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP O
                                             WHERE O.BDSESSAO = MOV.BDSESSAO
                                             AND O.BDCODEMP = MOV.BDCODEMP
                                             AND O.BDCHAVE = MOV.BDCHAVE
                                             AND O.BDCODNAT = MOV.BDCODNAT
                                             ORDER BY O.BDORDEMVARCFOP) BDORDEMVARCFOP,
                 MOV.BDSESSAO, 29 BDINCONSISTENCIA, MOV.BDCODNAT, MOV.BDCONDPGTO,:PRCODPLANOONLINE
          FROM (
                SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, s.bdcodnat, SUM(COALESCE(S.BDVLRPIS, 0)) BDVLRPIS,
                EXTRACT(YEAR FROM R.BDDATAREDZ)*100+EXTRACT(MONTH FROM R.BDDATAREDZ) AS BDREFERENCIA
                FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP S
                LEFT OUTER JOIN TMP_VEF_EMP_TREDZ_TEMP R ON (s.bdcodemp = R.BDCODEMP AND s.bdchave = R.BDCHAVE AND s.bdsessao = R.BDSESSAO)
                WHERE S.BDSESSAO = :PRSESSAO
                GROUP BY s.bdcodemp, s.bdchave, s.bdsessao, s.bdcondpgto, s.bdcodnat, EXTRACT(YEAR FROM R.BDDATAREDZ)*100+EXTRACT(MONTH FROM R.BDDATAREDZ)
               ) MOV
          JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = MOV.BDCODNAT AND NAT.BDCONTABILIZA = 'TRUE')
          JOIN (
                SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, c.BDREFERENCIA
                FROM TCONTAS_ONLINE_TEMP C
--                WHERE (C.BDSESSAO = :PRSESSAO) AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE IN (115, 121, 174) /*PIS*/
                WHERE (C.BDSESSAO = :PRSESSAO) AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE = CASE WHEN C.BDCODTIPOCONTA = 50 THEN 115  /*PIS - A vista*/
                                                                                                                                            WHEN C.BDCODTIPOCONTA = 51 THEN 121  /*PIS - Prazo*/
                                                                                                                                            WHEN C.BDCODTIPOCONTA = 406 THEN 174 /*PIS - Outras*/
                                                                                                                                       END
               ) O ON(O.BDCODNAT = MOV.BDCODNAT AND O.BDREFERENCIA = MOV.BDREFERENCIA AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                             WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                             WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                                        END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)))
          WHERE MOV.BDVLRPIS > 0;
          /*------------------------------------------------------------------------------------------------------*/
        END

      IF (:FCONTABILIZACOFINS = 0) THEN /*0 - nota a nota, deve exigir a conta de Cofins*/
        BEGIN
          /*30 - Conta(s) do "Cofins" não informada(s) para configuração do plano de contabilização da empresa*/
          /*-----------------------------------------------COFINS-------------------------------------------------*/
          INSERT INTO VEF_INCON_TREDZ(bdcodemp, bdchave, bdordemvarcfop, bdsessao, bdcodinconsistencia, bdcodnat, bdcondpgto,BDCODPLANOONLINE)
          SELECT MOV.BDCODEMP, MOV.BDCHAVE, (SELECT FIRST 1 O.BDORDEMVARCFOP
                                             FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP O
                                             WHERE O.BDSESSAO = MOV.BDSESSAO
                                             AND O.BDCODEMP = MOV.BDCODEMP
                                             AND O.BDCHAVE = MOV.BDCHAVE
                                             AND O.BDCODNAT = MOV.BDCODNAT
                                             ORDER BY O.BDORDEMVARCFOP) BDORDEMVARCFOP, MOV.BDSESSAO, 30 BDINCONSISTENCIA, MOV.BDCODNAT, MOV.BDCONDPGTO,:PRCODPLANOONLINE
          FROM (
                SELECT s.bdcodemp, s.bdchave, s.bdsessao, COALESCE(s.bdcondpgto, 0) bdcondpgto, s.bdcodnat, SUM(COALESCE(S.BDVLRCOFINS, 0)) BDVLRCOFINS,
                EXTRACT(YEAR FROM R.BDDATAREDZ)*100+EXTRACT(MONTH FROM R.BDDATAREDZ) AS BDREFERENCIA
                FROM TMP_VEF_EMP_TREDZVARCFOP_TEMP S
                LEFT OUTER JOIN TMP_VEF_EMP_TREDZ_TEMP R ON (s.bdcodemp = R.BDCODEMP AND s.bdchave = R.BDCHAVE AND s.bdsessao = R.BDSESSAO)
                WHERE S.BDSESSAO = :PRSESSAO
                GROUP BY s.bdcodemp, s.bdchave, s.bdsessao, s.bdcondpgto, s.bdcodnat, EXTRACT(YEAR FROM R.BDDATAREDZ)*100+EXTRACT(MONTH FROM R.BDDATAREDZ)
               ) MOV
          JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = MOV.BDCODNAT AND NAT.BDCONTABILIZA = 'TRUE')
          JOIN (
                SELECT C.bdchave, c.bdcodtipoconta, c.bdcodnat, c.bdclassificacao, c.bdcontadebprov, c.bdcontacredprov, c.BDREFERENCIA
                FROM TCONTAS_ONLINE_TEMP C
--                WHERE (C.BDSESSAO = :PRSESSAO) AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE IN (116, 122, 175) /*Cofins*/
                WHERE (C.BDSESSAO = :PRSESSAO) AND ((C.BDCONTACREDPROV IS NULL) OR (C.BDCONTADEBPROV IS NULL)) AND C.BDCODITEMONLINE = CASE WHEN C.BDCODTIPOCONTA = 50 THEN 116  /*Cofins - A vista*/
                                                                                                                                            WHEN C.BDCODTIPOCONTA = 51 THEN 122  /*Cofins - Prazo*/
                                                                                                                                            WHEN C.BDCODTIPOCONTA = 406 THEN 175 /*Cofins - Outras*/
                                                                                                                                       END
               ) O ON(O.BDCODNAT = MOV.BDCODNAT AND O.BDREFERENCIA = MOV.BDREFERENCIA AND O.BDCODTIPOCONTA = (CASE WHEN COALESCE(MOV.BDCONDPGTO, 0) = 0 THEN 50
                                                                             WHEN COALESCE(MOV.BDCONDPGTO, 0) = 1 THEN 51
                                                                             WHEN COALESCE(MOV.BDCONDPGTO, 0) = 2 THEN 406
                                                                        END) AND ((O.BDCONTACREDPROV IS NULL) OR (O.BDCONTADEBPROV IS NULL)))
          WHERE MOV.BDVLRCOFINS > 0;
            /*------------------------------------------------------------------------------------------------------*/
        END
    END
END^

CREATE OR ALTER PROCEDURE sp_insere_complemento_hist_rat (
    prcodplanoonline INTEGER,
    prsessao INTEGER,
    prtipolan VARCHAR(5))
AS
DECLARE VARIABLE wtable VARCHAR(31);
DECLARE VARIABLE wtablerat VARCHAR(31);
DECLARE VARIABLE wtableinc VARCHAR(31);
DECLARE VARIABLE wsql VARCHAR(1000);
DECLARE VARIABLE wchave INTEGER;
DECLARE VARIABLE wcodigotipo INTEGER;
DECLARE VARIABLE wcomphist BLOB SUB_TYPE 1 SEGMENT SIZE 1000;
DECLARE VARIABLE wfielddata VARCHAR(32);
DECLARE VARIABLE wreferencia INTEGER;
DECLARE VARIABLE wdatini DATE;
DECLARE VARIABLE wdatfin DATE;
declare variable WTABLEITEM varchar(31);
declare variable WOBSERVACAO varchar(100);
BEGIN
  wfielddata = 'BDDATAEMISSAO';
  IF (POSITION('SER', :PRTIPOLAN) > 0) THEN
    BEGIN
      wTable     = 'VEF_EMP_TMOVSER';      
      wTableItem = 'VEF_EMP_TMOVSERITENS';
      wTableRat  = 'VEF_EMP_TMOVRATSER';
      wTableInc  = 'VEF_INCON_TMOVSER';
      wCodigoTipo= IIF(:PRTIPOLAN = 'SERE', 4, 5);
    END
  ELSE
  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTable     = 'VEF_EMP_TMOVSAI';        
      wTableItem  = 'VEF_EMP_TMOVSAIITENS';
      wTableRat  = 'VEF_EMP_TMOVRATSAI';
      wTableInc  = 'VEF_INCON_TMOVSAI';
      wCodigoTipo= 3;
    END
  ELSE
  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTable     = 'VEF_EMP_TMOVENT';       
      wTableItem = 'VEF_EMP_TMOVENTITENS';
      wTableRat  = 'VEF_EMP_TMOVRATENT';
      wTableInc  = 'VEF_INCON_TMOVENT';   
      wfielddata = 'bdDATAENTRADAENT';
      wCodigoTipo= 2;
    END

  wSQL =          'SELECT RAT.BDCHAVEONLINE, C.BDCOMPLEMENTO, C.BDREFERENCIA,  MIN(SER.'||WFIELDDATA||') AS BDDATAINI, MAX(SER.'||WFIELDDATA||') AS BDDATAFIM, MAX(I.BDOBSERVACAO) BDOBSERVACAO ';
  wSQL = :wSQL || 'FROM TMP_'||:wTableRat||'_TEMP RAT ';

  IF (POSITION('SER', :PRTIPOLAN) > 0) THEN
    wSQL = :wSQL || 'JOIN TMP_'||:wTable||'_TEMP SER ON(SER.BDSESSAO = RAT.BDSESSAO AND SER.BDCODEMP = RAT.BDCODEMP AND SER.BDCHAVE = RAT.BDCHAVE AND SER.BDTIPLAN = '||IIF(:PRTIPOLAN = 'SERE', '0', '1')||') ';
  ELSE
    wSQL = :wSQL || 'JOIN TMP_'||:wTable||'_TEMP SER ON(SER.BDSESSAO = RAT.BDSESSAO AND SER.BDCODEMP = RAT.BDCODEMP AND SER.BDCHAVE = RAT.BDCHAVE) ';
                                                               
  wSQL = :wSQL || 'JOIN TMP_'||:wTableItem||'_TEMP I ON(I.BDSESSAO = SER.BDSESSAO AND I.BDCODEMP = SER.BDCODEMP AND I.BDCHAVE = SER.BDCHAVE) ';
  wSQL = :wSQL || 'JOIN TCONTAS_ONLINE_TEMP C ON(C.BDSESSAO = RAT.BDSESSAO AND C.BDCHAVE = RAT.BDCHAVEONLINE AND C.BDREFERENCIA = EXTRACT(YEAR FROM SER.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM SER.'||WFIELDDATA||')) ';
  wSQL = :wSQL || 'WHERE RAT.BDSESSAO = '||:PRSESSAO||' ';
  wSQL = :wSQL || 'AND RAT.BDCODPLANOONLINE = '||:PRCODPLANOONLINE||' ';
  wSQL = :wSQL || 'AND RAT.BDVALOR > 0 ';
  wSQL = :wSQL || 'GROUP BY RAT.BDSESSAO, RAT.BDCODPLANOONLINE, RAT.BDCHAVEONLINE, C.BDCOMPLEMENTO, C.BDREFERENCIA ';

  FOR EXECUTE STATEMENT :wSQL
      INTO :wChave, :wCompHist, :wreferencia, :wdatini, :WDATFIN, :WOBSERVACAO
  DO
    BEGIN
      IF (:wCompHist IS NULL) THEN
        BEGIN
          wCompHist = '';
          SELECT FIRST 1 COALESCE((
                                   /*Se não houver na conta, busca no vinculo de complemento e se lá não houver usa o complemento padrão*/
                                   SELECT h.bdCOMPLEMENTO
                                   FROM TCOMPLEMENTO_HIST_VINC hv
                                   LEFT OUTER JOIN TCOMPLEMENTO_HIST h ON (h.bdCODCOMPHIST = hv.bdCODCOMPHIST)
                                   WHERE hv.bdCODPLANOONLINE = :prCODPLANOONLINE
                                   AND hv.bdCODIGOTIPO = :wCodigoTipo
                                  ),
                                  ('*NRDOC - *NOMEPART') /*Default*/
                                 ) bdCODCOMPHIST
          FROM RDB$DATABASE
          INTO :wCompHist;
        END
      if (WOBSERVACAO <> '') then
        wCompHist = wCompHist || ' ' || :WOBSERVACAO;

      wSQL =          'UPDATE TMP_'||:wTableRat||'_TEMP RAT ';
      wSQL = :wSQL || 'SET RAT.BDCOMPHIST = '''||:wCompHist||''' ';
      wSQL = :wSQL || 'WHERE RAT.BDSESSAO = '||:PRSESSAO||' ';
      wSQL = :wSQL || 'AND RAT.BDCODPLANOONLINE = '||:PRCODPLANOONLINE||' ';
      wSQL = :wSQL || 'AND RAT.BDCHAVEONLINE = '||:wChave||' ';

      wSQL = :wSQL || 'AND EXISTS (';
      wSQL = :wSQL ||             'SELECT MOV.BDCHAVE ';
      wSQL = :wSQL ||             'FROM TMP_'||:wTable||'_TEMP MOV ';
      wSQL = :wSQL ||             'WHERE MOV.BDSESSAO = RAT.BDSESSAO ';
      wSQL = :wSQL ||             'AND MOV.BDCODEMP = RAT.BDCODEMP ';
      wSQL = :wSQL ||             'AND MOV.BDCHAVE = RAT.BDCHAVE ';
      wSQL = :wSQL ||             'AND MOV.'||wfielddata||' between '''||wdatini||''' and '''||wdatfin||''' ';
      IF (POSITION('SER', :PRTIPOLAN) > 0) THEN
        wSQL = :wSQL ||           'AND MOV.BDTIPLAN = '||IIF(:PRTIPOLAN = 'SERE', '0', '1');
      wSQL = :wSQL ||            ') ';

      wSQL = :wSQL || 'AND NOT EXISTS(';
      wSQL = :wSQL ||                'SELECT inco.bdCODEMP, inco.bdCHAVE, inco.bdSESSAO ';
      wSQL = :wSQL ||                'FROM '||:wTableInc||' inco ';
      wSQL = :wSQL ||                'WHERE inco.bdCODEMP = RAT.bdCODEMP ';
      wSQL = :wSQL ||                'AND inco.bdCHAVE = RAT.bdCHAVE ';
      wSQL = :wSQL ||                'AND inco.bdSESSAO = RAT.bdSESSAO ';
      wSQL = :wSQL ||                '); ';
      EXECUTE STATEMENT :wSQL;
    END

  /*Ajusta o complemento de histórico, remove as variáveis*/
  wSQL =          'UPDATE TMP_'||:wTableRat||'_TEMP RAT ';
  wSQL = :wSQL || 'SET RAT.BDCOMPHIST = (SELECT BDRESULT FROM SP_GET_COMPLEMENTO(RAT.BDSESSAO, RAT.BDCODEMP, RAT.BDCHAVE, RAT.BDCOMPHIST, RAT.BDCODNAT, '''||:PRTIPOLAN||''', '''')) ';
  wSQL = :wSQL || 'WHERE RAT.BDSESSAO = '||:PRSESSAO||' ';

  wSQL = :wSQL || ' AND EXISTS (';
  wSQL = :wSQL ||              'SELECT MOV.BDCHAVE ';
  wSQL = :wSQL ||              'FROM TMP_'||:wTable||'_TEMP MOV ';
  wSQL = :wSQL ||              'WHERE MOV.BDSESSAO = RAT.BDSESSAO ';
  wSQL = :wSQL ||              'AND MOV.BDCODEMP = RAT.BDCODEMP ';
  wSQL = :wSQL ||              'AND MOV.BDCHAVE = RAT.BDCHAVE ';  
  IF ((wDATINI IS NOT NULL) AND (wDATFIN IS NOT NULL)) THEN
    wSQL = :wSQL ||              'AND MOV.'||wfielddata||' between '''||wdatini||''' and '''||wdatfin||''' ';
  IF (POSITION('SER', :PRTIPOLAN) > 0) THEN
    wSQL = :wSQL ||            'AND MOV.BDTIPLAN = '||IIF(:PRTIPOLAN = 'SERE', '0', '1');
  wSQL = :wSQL ||              '); ';
  EXECUTE STATEMENT :wSQL;

  WHEN ANY DO
    BEGIN
      IN AUTONOMOUS TRANSACTION DO
        EXECUTE PROCEDURE LANCA_EXCEPTION('SP_INSERE_COMPLEMENTO_HIST_RAT', SQLCODE, GDSCODE);
      EXCEPTION;
    END
END
^

create or alter procedure SP_INSERE_COMPLEMENTO_HIST (
    PRCODPLANOONLINE integer,
    PRSESSAO integer,
    PRTIPOLAN varchar(5))
as
declare variable WCODITEMINSS25 integer;
declare variable WCODITEMINSS20 integer;
declare variable WCODITEMINSS15 integer;
declare variable WSQL varchar(5000);
declare variable WSUBSELECT varchar(2000);
declare variable WTABLE varchar(31);
declare variable WTABLEITEM varchar(31);
declare variable WTABLEINC varchar(31);
declare variable WTABLEC100 varchar(31);
declare variable WTABLED100 varchar(31);
declare variable WTABLERET varchar(31);
declare variable WTABLEINSS varchar(31);
declare variable WTABLERAT varchar(31);
declare variable WCOMPLEMENTOHIST blob sub_type 1 segment size 1000;
declare variable WCOMPHIST_VLRCONTAB blob sub_type 1 segment size 1000;
declare variable WCOMPHIST_VLRPIS blob sub_type 1 segment size 1000;
declare variable WCOMPHIST_VLRICMS blob sub_type 1 segment size 1000;
declare variable WCOMPHIST_VLRICMSST blob sub_type 1 segment size 1000;
declare variable WCOMPHIST_VLRIPI blob sub_type 1 segment size 1000;
declare variable WCOMPHIST_VLRCOFINS blob sub_type 1 segment size 1000;
declare variable WCOMPHIST_DIFAL blob sub_type 1 segment size 1000;
declare variable WCOMPHIST_VLRICMSINTERDEST blob sub_type 1 segment size 1000;
declare variable WCOMPHIST_VLRICMSINTERREM blob sub_type 1 segment size 1000;
declare variable WCOMPHIST_VLRICMSFCPOP blob sub_type 1 segment size 1000;
declare variable WCOMPHIST_VLRICMSCONC blob sub_type 1 segment size 1000;
declare variable WCOMPHIST_VLRICMSFCPST blob sub_type 1 segment size 1000;
declare variable WCOMPHIST_VLRICMSESTORNADO blob sub_type 1 segment size 1000;
declare variable WCODNAT integer;
declare variable WCONDPGTO integer;
declare variable WCODITEMONLINE integer;
declare variable WCODREC integer;
declare variable WFIELDAUX varchar(32);
declare variable WWHEREAUX varchar(500);
declare variable WCODIGOTIPO integer;
declare variable WCODITEMPIS integer;
declare variable WCODITEMCOF integer;
declare variable WCODITEMCS integer;
declare variable WCODITEMIR integer;
declare variable WCODITEMINSS integer;
declare variable WCODITEMISS integer;
declare variable WTABLEDIFALIQ varchar(32);
declare variable WTABLEDIFALIQPR varchar(32);
declare variable WFIELDDATA varchar(32);
declare variable WFIELDREF varchar(200);
declare variable WREFERENCIA integer;
declare variable WDATINI date;
declare variable WDATFIN date;
declare variable WGETCOMPL varchar(100);
declare variable WGETCOMPLFIM varchar(100);
BEGIN
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERE_COMPLEMENTO_HIST','1');
  prTIPOLAN = UPPER(:prTIPOLAN);

  wTable      = '';
  wTableItem  = '';
  wTableC100  = '';
  wTableD100  = '';
  wTableInc   = '';
  wTableRet   = '';
  wTableINSS  = '';
  wTableRat   = '';    
  wfielddata  = 'BDDATAEMISSAO';

  IF (:prTIPOLAN = 'SAI') THEN
    BEGIN
      wTable      = 'VEF_EMP_TMOVSAI';
      wTableItem  = 'VEF_EMP_TMOVSAIITENS';
      wTableC100  = 'VEF_EMP_TC100SAI';
      wTableD100  = 'VEF_EMP_TD100SAI';
      wTableInc   = 'VEF_INCON_TMOVSAI';
      wTableRet   = 'VEF_EMP_TMOVSAIRET';
      wTableINSS  = 'VEF_EMP_TMOVSAIDED';

      wTableDifAliq    = 'TMP_VEF_EMP_TMOVSAIDIFALIQ_TEMP';
      wTableDifAliqPR  = 'TMP_VEF_EMP_TMOVSAIDIFPR_TEMP';
      wCodItemPIS  = 89;
      wCodItemCof  = 90;
      wCodItemCS   = 91;
      wCodItemIR   = 92;
      wCodItemINSS = 93;
      wCodItemISS  = 94;
      wCodItemINSS15 = 304;
      wCodItemINSS20 = 305;
      wCodItemINSS25 = 306;
    END
  ELSE
  IF (:prTIPOLAN = 'ENT') THEN
    BEGIN
      wTable      = 'VEF_EMP_TMOVENT';
      wTableItem  = 'VEF_EMP_TMOVENTITENS';
      wTableC100  = 'VEF_EMP_TC100ENT';
      wTableD100  = 'VEF_EMP_TD100ENT';
      wTableInc   = 'VEF_INCON_TMOVENT';
      wTableRet   = 'VEF_EMP_TMOVENTRET';
      wTableINSS  = 'VEF_EMP_TMOVENTDED';
      wTableDifAliq    = 'TMP_VEF_EMP_TMOVENTDIFALIQ_TEMP';
      wTableDifAliqPR  = 'TMP_VEF_EMP_TMOVENTDIFPR_TEMP';
      wfielddata  = 'BDDATAENTRADAENT';

      wCodItemPIS  = 82;
      wCodItemCof  = 83;
      wCodItemCS   = 84;
      wCodItemIR   = 163;
      wCodItemINSS = 164;
      wCodItemISS  = 165;
      wCodItemINSS15 = 313;
      wCodItemINSS20 = 314;
      wCodItemINSS25 = 315;
    END
  ELSE
  IF (POSITION('SER', :PRTIPOLAN)> 0) THEN
    BEGIN
      wTable      = 'VEF_EMP_TMOVSER';
      wTableItem  = 'VEF_EMP_TMOVSERITENS';
      wTableInc   = 'VEF_INCON_TMOVSER';
      wTableRet   = 'VEF_EMP_TMOVSERRET';
      wTableINSS  = 'VEF_EMP_TMOVSERDED';
      wTableRat   = 'VEF_EMP_TMOVRATSER';

      IF (:PRTIPOLAN = 'SERE') THEN /*Emitido*/
        BEGIN
          wCodItemPIS  = 99;
          wCodItemCof  = 100;
          wCodItemCS   = 101;
          wCodItemIR   = 97;
          wCodItemINSS = 98;
          wCodItemISS  = 102;
          wCodItemINSS15 = 307;
          wCodItemINSS20 = 308;
          wCodItemINSS25 = 309;
        END
      ELSE
        BEGIN /*Recebido*/
          wCodItemPIS  = 107;
          wCodItemCof  = 108;
          wCodItemCS   = 109;
          wCodItemIR   = 105;
          wCodItemINSS = 106;
          wCodItemISS  = 110;
          wCodItemINSS15 = 310;
          wCodItemINSS20 = 311;
          wCodItemINSS25 = 312;
        END
    END
  ELSE
    EXIT;

  wfieldref = 'EXTRACT(YEAR FROM mov.'||WFIELDDATA||')*100+EXTRACT(MONTH FROM mov.'||WFIELDDATA||')';
  wSQL =          'SELECT i.bdCODNAT, CASE WHEN COALESCE(mov.bdCONDPGTO, 0) = 0 THEN 50 ';
  wSQL = wSQL || '                        WHEN COALESCE(mov.bdCONDPGTO, 0) = 1 THEN 51 ';
  wSQL = wSQL || '                        WHEN COALESCE(mov.bdCONDPGTO, 0) = 2 THEN 406 ';
  wSQL = wSQL || '                   END bdCONDPGTO, ';
  wSQL = wSQL || wfieldref || ', MIN(mov.'||WFIELDDATA||'), max(mov.'||WFIELDDATA||')';
  wSQL = wSQL || ' FROM TMP_'||:wTableItem||'_TEMP i ';

  IF (POSITION('SER', :PRTIPOLAN)> 0) THEN
    wSQL = wSQL || ' JOIN TMP_'||wTable||'_TEMP mov ON (mov.bdCODEMP = i.bdCODEMP and mov.bdCHAVE = i.bdCHAVE and mov.bdSESSAO = i.bdSESSAO AND MOV.BDTIPLAN = '||IIF(:PRTIPOLAN = 'SERE', '0', '1')||') ';
  ELSE
    wSQL = wSQL || ' LEFT OUTER JOIN TMP_'||wTable||'_TEMP mov ON (mov.bdCODEMP = i.bdCODEMP and mov.bdCHAVE = i.bdCHAVE and mov.bdSESSAO = i.bdSESSAO) ';

  wSQL = wSQL || ' WHERE i.bdSESSAO = '||:prSESSAO;
  wSQL = wSQL || ' AND I.BDCODNAT IS NOT NULL ';  

  /*Se tiver registro na tabela de rateio não deve contabilizar o item, contabiliza só o rateio*/
  IF (:wTableRat <> '') THEN
    BEGIN
      wSQL = wSQL || ' AND NOT EXISTS (';
      wSQL = wSQL ||                  'SELECT RAT.BDSESSAO ';
      wSQL = wSQL ||                  'FROM TMP_'||:wTableRat||'_TEMP RAT ';
      wSQL = wSQL ||                  'WHERE RAT.BDSESSAO = I.BDSESSAO ';
      wSQL = wSQL ||                  'AND RAT.BDCODEMP = I.BDCODEMP ';
      wSQL = wSQL ||                  'AND RAT.BDCHAVE  = I.BDCHAVE ';
      wSQL = wSQL ||                  'AND RAT.BDORDEM  = I.BDORDEM ';
      wSQL = wSQL ||                 ') ';
    END

  wSQL = wSQL || ' GROUP BY i.bdSESSAO, i.bdCODEMP, i.bdCODNAT, mov.bdCONDPGTO, '||wfieldref;
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERE_COMPLEMENTO_HIST','2');
  /*---------------------Monta o complemento das contas do valor contábil, ICMS, IPI, ICMS ST, PIS e COFINS----------------------*/
  FOR
      EXECUTE STATEMENT wSQL
      INTO :wCodNat, :wCondPgto, :wreferencia, :wdatini, :wdatfin
  DO
    BEGIN
      wCodigoTipo = CASE WHEN :PRTIPOLAN = 'ENT'  THEN 2
                         WHEN :PRTIPOLAN = 'SAI'  THEN 3
                         WHEN :PRTIPOLAN = 'SERE' THEN 4
                         WHEN :PRTIPOLAN = 'SERR' THEN 5
                    END;
      /*-----------------------------Complemento de histórico do valor contábil-----------------------------------*/
      SELECT FIRST 1 COALESCE(
                              (
                               SELECT FIRST 1 t.bdCOMPLEMENTO
                               FROM TCONTAS_ONLINE_TEMP t
                               WHERE t.bdSESSAO = :prSESSAO
                                 AND t.bdCODNAT = :wCodNat
                                 AND t.bdCODTIPOCONTA = :wCondPgto
                                 AND t.BDREFERENCIA = :wreferencia
                                 AND (t.bdCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 111 /*Valor contábil - A vista*/
                                                               WHEN :wCondPgto =  51 THEN 117 /*Valor contábil - Prazo*/
                                                               WHEN :wCondPgto = 406 THEN 170 /*Valor contábil - Outras*/
                                                           END)
                              ),
                              (
                               SELECT FIRST 1 h.bdCOMPLEMENTO
                               FROM TCOMPLEMENTO_HIST_VINC hv
                               LEFT OUTER JOIN TCOMPLEMENTO_HIST h ON (h.bdCODCOMPHIST = hv.bdCODCOMPHIST)
                               WHERE hv.bdCODPLANOONLINE = :prCODPLANOONLINE
                               AND hv.bdCODIGOTIPO = :wCodigoTipo
                              ),
                              ('*NRDOC - *NOMEPART') /*Default*/
                             ) bdCODCOMPHIST
      FROM RDB$DATABASE
      INTO :wCompHist_VlrContab;

      IF (COALESCE(:wCompHist_VlrContab,'') <> '') THEN
        BEGIN
          wCompHist_VlrContab = ' i.bdCOMPHIST_VLRCONTAB =''' || :wCompHist_VlrContab || ''' ';
        END

      /*---------------------------------------Complemento histórico do pis---------------------------------------*/
      wCodigoTipo = CASE WHEN :PRTIPOLAN = 'ENT'  THEN 18
                         WHEN :PRTIPOLAN = 'SAI'  THEN 19
                         WHEN :PRTIPOLAN = 'SERE' THEN 20
                         WHEN :PRTIPOLAN = 'SERR' THEN 21
                    END;

      SELECT FIRST 1 COALESCE(
                              (
                               SELECT FIRST 1 t.bdCOMPLEMENTO
                               FROM TCONTAS_ONLINE_TEMP t
                               WHERE t.bdSESSAO = :prSESSAO
                               AND t.bdCODNAT = :wCodNat
                               AND t.bdCODTIPOCONTA = :wCondPgto 
                               AND t.BDREFERENCIA = :wreferencia
                               AND (t.bdCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 115 /*PIS - A vista*/
                                                             WHEN :wCondPgto =  51 THEN 121 /*PIS - Prazo*/
                                                             WHEN :wCondPgto = 406 THEN 174 /*PIS - Outras*/
                                                        END)
                              ),
                              (
                               SELECT FIRST 1 h.bdCOMPLEMENTO
                               FROM TCOMPLEMENTO_HIST_VINC hv
                               LEFT OUTER JOIN TCOMPLEMENTO_HIST h ON (h.bdCODCOMPHIST = hv.bdCODCOMPHIST)
                               WHERE hv.bdCODPLANOONLINE = :prCODPLANOONLINE
                                 AND hv.bdCODIGOTIPO = :wCodigoTipo
                              ),
                               ('*NRDOC - *NOMEPART') /*Default*/
                              ) bdCODCOMPHIST
      FROM RDB$DATABASE
      INTO :wCompHist_VlrPis;

      IF (COALESCE(:wCompHist_VlrPis,'') <> '') THEN
        BEGIN                                               
          wCompHist_VlrPis = ' i.bdCOMPHIST_VLRPIS = IIF(i.bdVLRPIS > 0,''' || :wCompHist_VlrPis || ''',i.bdCOMPHIST_VLRPIS) ';
        END

      /*---------------------------------------Complemento de histórico de ICMS-----------------------------------*/
      IF (POSITION('SER', :PRTIPOLAN) = 0) THEN
        BEGIN
          wCodigoTipo = CASE WHEN :PRTIPOLAN = 'ENT'  THEN 8
                             WHEN :PRTIPOLAN = 'SAI'  THEN 9
                             WHEN :PRTIPOLAN = 'SERE' THEN 10
                             WHEN :PRTIPOLAN = 'SERR' THEN 11
                        END;

          SELECT FIRST 1 COALESCE(
                                  (
                                   SELECT FIRST 1 t.bdCOMPLEMENTO
                                   FROM TCONTAS_ONLINE_TEMP t
                                   WHERE t.bdSESSAO = :prSESSAO
                                     AND t.bdCODNAT = :wCodNat
                                     AND t.bdCODTIPOCONTA = :wCondPgto  
                                     AND t.BDREFERENCIA = :wreferencia
                                     AND (t.bdCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 112 /*ICMS - A vista*/
                                                                   WHEN :wCondPgto =  51 THEN 118 /*ICMS - Prazo*/
                                                                   WHEN :wCondPgto = 406 THEN 171 /*ICMS - Outras*/
                                                              END)
                                  ),
                                  (
                                   /*Se não houver na conta, busca no vinculo de complemento e se lá não houver usa o complemento padrão*/
                                   SELECT FIRST 1 h.bdCOMPLEMENTO
                                   FROM TCOMPLEMENTO_HIST_VINC hv
                                   LEFT OUTER JOIN  TCOMPLEMENTO_HIST h ON (h.bdCODCOMPHIST = hv.bdCODCOMPHIST)
                                   WHERE hv.bdCODPLANOONLINE = :prCODPLANOONLINE
                                     AND hv.bdCODIGOTIPO = :wCodigoTipo
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                  ) bdCODCOMPHIST
          FROM RDB$DATABASE
          INTO :wCompHist_VlrICMS;
    
          IF (COALESCE(:wCompHist_VlrICMS,'') <> '') THEN
            BEGIN                                                     
              wCompHist_VlrICMS = ' i.bdCOMPHIST_VLRICMS = IIF(i.bdVLRICMS > 0,''' || :wCompHist_VlrICMS || ''',i.bdCOMPHIST_VLRICMS) ';
            END
          /*------------Complemento histórico de ICMS ST------*/
          wCodigoTipo = CASE WHEN :PRTIPOLAN = 'ENT' THEN 13
                             WHEN :PRTIPOLAN = 'SAI' THEN 14
                        END;

          SELECT FIRST 1 COALESCE(
                                  (
                                   SELECT FIRST 1 t.bdCOMPLEMENTO
                                   FROM TCONTAS_ONLINE_TEMP t
                                   WHERE t.bdSESSAO = :prSESSAO
                                     AND t.bdCODNAT = :wCodNat
                                     AND t.bdCODTIPOCONTA = :wCondPgto   
                                     AND t.BDREFERENCIA = :wreferencia
                                     AND (t.bdCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 113 /*ICMS ST - A vista*/
                                                                   WHEN :wCondPgto =  51 THEN 119 /*ICMS ST - Prazo*/
                                                                   WHEN :wCondPgto = 406 THEN 172 /*ICMS ST - Outras*/
                                                              END)
                                  ),
                                  (
                                   /*Se não houver na conta, busca no vinculo de complemento e se lá não houver usa o complemento padrão*/
                                   SELECT FIRST 1 h.bdCOMPLEMENTO
                                   FROM TCOMPLEMENTO_HIST_VINC hv
                                   LEFT OUTER JOIN  TCOMPLEMENTO_HIST h ON (h.bdCODCOMPHIST = hv.bdCODCOMPHIST)
                                   WHERE hv.bdCODPLANOONLINE = :prCODPLANOONLINE
                                     AND hv.bdCODIGOTIPO = :wCodigoTipo
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                 ) bdCODCOMPHIST
          FROM RDB$DATABASE
          INTO :wCompHist_VlrICMSST;
    
          IF (COALESCE(:wCompHist_VlrICMSST,'') <> '') THEN
            BEGIN                        
              wCompHist_VlrICMSST = ' i.bdCOMPHIST_VLRICMSST = IIF(i.bdVLRST > 0,''' || :wCompHist_VlrICMSST || ''',i.bdCOMPHIST_VLRICMSST) ';
            END
          /*---------Complemento histórico de ICMS FCP ST-------------*/
          wCodigoTipo = CASE WHEN :PRTIPOLAN = 'ENT' THEN 149
                             WHEN :PRTIPOLAN = 'SAI' THEN 150
                        END;

          SELECT FIRST 1 COALESCE(
                                  (
                                   SELECT FIRST 1 t.bdCOMPLEMENTO
                                   FROM TCONTAS_ONLINE_TEMP t
                                   WHERE t.bdSESSAO = :prSESSAO
                                     AND t.bdCODNAT = :wCodNat
                                     AND t.bdCODTIPOCONTA = :wCondPgto   
                                     AND t.BDREFERENCIA = :wreferencia
                                     AND (t.bdCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 286 /*ICMS FCP ST - A vista*/
                                                                   WHEN :wCondPgto =  51 THEN 287 /*ICMS FCP ST - Prazo*/
                                                                   WHEN :wCondPgto = 406 THEN 288 /*ICMS FCP ST - Outras*/
                                                              END)
                                  ),
                                  (
                                   /*Se não houver na conta, busca no vinculo de complemento e se lá não houver usa o complemento padrão*/
                                   SELECT FIRST 1 h.bdCOMPLEMENTO
                                   FROM TCOMPLEMENTO_HIST_VINC hv
                                   LEFT OUTER JOIN  TCOMPLEMENTO_HIST h ON (h.bdCODCOMPHIST = hv.bdCODCOMPHIST)
                                   WHERE hv.bdCODPLANOONLINE = :prCODPLANOONLINE
                                     AND hv.bdCODIGOTIPO = :wCodigoTipo
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                 ) bdCODCOMPHIST
          FROM RDB$DATABASE
          INTO :wCompHist_VlrICMSFCPST;
    
          IF (COALESCE(:wCompHist_VlrICMSFCPST,'') <> '') THEN
            BEGIN                        
              -- Alt.: #217914 - Deve considerar tambem os valores de FCP retido...
              --wCompHist_VlrICMSFCPST = ' i.bdCOMPHIST_VLRICMSFCPST = IIF(i.bdVLRST > 0,''' || :wCompHist_VlrICMSFCPST || ''',i.bdCOMPHIST_VLRICMSFCPST) ';
              wCompHist_VlrICMSFCPST = ' i.bdCOMPHIST_VLRICMSFCPST = IIF(((I.BDVLRST > 0) OR (I.BDFCPRETIDO > 0)),''' || :wCompHist_VlrICMSFCPST || ''',i.bdCOMPHIST_VLRICMSFCPST) ';
            END

          /*---------Complemento histórico de ICMS Concomitante-------------*/
          wCodigoTipo = CASE WHEN :PRTIPOLAN = 'ENT' THEN 195
                             WHEN :PRTIPOLAN = 'SAI' THEN 196
                        END;

          SELECT FIRST 1 COALESCE(
                                  (
                                   SELECT FIRST 1 t.bdCOMPLEMENTO
                                   FROM TCONTAS_ONLINE_TEMP t
                                   WHERE t.bdSESSAO = :prSESSAO
                                     AND t.bdCODNAT = :wCodNat
                                     AND t.bdCODTIPOCONTA = :wCondPgto   
                                     AND t.BDREFERENCIA = :wreferencia
                                     AND (t.bdCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 640 /*ICMS Concomitante - A vista*/
                                                                   WHEN :wCondPgto =  51 THEN 641 /*ICMS Concomitante - Prazo*/
                                                                   WHEN :wCondPgto = 406 THEN 642 /*ICMS Concomitante - Outras*/
                                                              END)
                                  ),
                                  (
                                   /*Se não houver na conta, busca no vinculo de complemento e se lá não houver usa o complemento padrão*/
                                   SELECT FIRST 1 h.bdCOMPLEMENTO
                                   FROM TCOMPLEMENTO_HIST_VINC hv
                                   LEFT OUTER JOIN  TCOMPLEMENTO_HIST h ON (h.bdCODCOMPHIST = hv.bdCODCOMPHIST)
                                   WHERE hv.bdCODPLANOONLINE = :prCODPLANOONLINE
                                     AND hv.bdCODIGOTIPO = :wCodigoTipo
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                 ) bdCODCOMPHIST
          FROM RDB$DATABASE
          INTO :wCompHist_VlrICMSCONC;
    
          IF (COALESCE(:wCompHist_VlrICMSCONC,'') <> '') THEN
            BEGIN                        
              wCompHist_VlrICMSCONC = ' i.bdCOMPHIST_VLRICMSCONC = IIF(i.bdVLRICMSCONC > 0,''' || :wCompHist_VlrICMSCONC || ''',i.bdCOMPHIST_VLRICMSCONC) ';
            END

                           /*---------Complemento histórico de ICMS FCP_OP-------------*/
          wCodigoTipo = CASE WHEN :PRTIPOLAN = 'ENT' THEN 195
                             WHEN :PRTIPOLAN = 'SAI' THEN 196
                        END;

          SELECT FIRST 1 COALESCE(
                                  (
                                   SELECT FIRST 1 t.bdCOMPLEMENTO
                                   FROM TCONTAS_ONLINE_TEMP t
                                   WHERE t.bdSESSAO = :prSESSAO
                                     AND t.bdCODNAT = :wCodNat
                                     AND t.bdCODTIPOCONTA = :wCondPgto   
                                     AND t.BDREFERENCIA = :wreferencia
                                     AND (t.bdCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 663 /*ICMS FCP_OP - A vista*/
                                                                   WHEN :wCondPgto =  51 THEN 664 /*ICMS FCP_OP - Prazo*/
                                                                   WHEN :wCondPgto = 406 THEN 665 /*ICMS FCP_OP - Outras*/
                                                              END)
                                  ),
                                  (
                                   /*Se não houver na conta, busca no vinculo de complemento e se lá não houver usa o complemento padrão*/
                                   SELECT FIRST 1 h.bdCOMPLEMENTO
                                   FROM TCOMPLEMENTO_HIST_VINC hv
                                   LEFT OUTER JOIN  TCOMPLEMENTO_HIST h ON (h.bdCODCOMPHIST = hv.bdCODCOMPHIST)
                                   WHERE hv.bdCODPLANOONLINE = :prCODPLANOONLINE
                                     AND hv.bdCODIGOTIPO = :wCodigoTipo
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                 ) bdCODCOMPHIST
          FROM RDB$DATABASE
          INTO :WCOMPHIST_VLRICMSFCPOP;
    
          IF (COALESCE(:WCOMPHIST_VLRICMSFCPOP,'') <> '') THEN
            BEGIN                        
              WCOMPHIST_VLRICMSFCPOP = ' i.BDCOMPHIST_VLRFCP = IIF(i.BDVLRFCP > 0,''' || :WCOMPHIST_VLRICMSFCPOP || ''',i.BDCOMPHIST_VLRFCP) ';
            END
          /*------------Complemento hist??rico do IPI------------*/
          wCodigoTipo = CASE WHEN :PRTIPOLAN = 'ENT'  THEN 15
                             WHEN :PRTIPOLAN = 'SAI'  THEN 16
                        END;

          SELECT FIRST 1 COALESCE(
                                  (
                                   SELECT FIRST 1 t.bdCOMPLEMENTO
                                   FROM TCONTAS_ONLINE_TEMP t
                                   WHERE t.bdSESSAO = :prSESSAO
                                     AND t.bdCODNAT = :wCodNat
                                     AND t.bdCODTIPOCONTA = :wCondPgto  
                                     AND t.BDREFERENCIA = :wreferencia
                                     AND (t.bdCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 114 /*IPI - A vista*/
                                                                   WHEN :wCondPgto =  51 THEN 120 /*IPI - Prazo*/
                                                                   WHEN :wCondPgto = 406 THEN 173 /*IPI - Outras*/
                                                              END)
                                  ),
                                  (
                                   /*Se não houver na conta, busca no vinculo de complemento e se lá não houver usa o complemento padrão*/
                                   SELECT FIRST 1 h.bdCOMPLEMENTO
                                   FROM TCOMPLEMENTO_HIST_VINC hv
                                   LEFT OUTER JOIN  TCOMPLEMENTO_HIST h ON (h.bdCODCOMPHIST = hv.bdCODCOMPHIST)
                                   WHERE hv.bdCODPLANOONLINE = :prCODPLANOONLINE
                                     AND hv.bdCODIGOTIPO = :wCodigoTipo
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                 ) bdCODCOMPHIST
          FROM RDB$DATABASE
          INTO :wCompHist_VlrIPI;
    
          IF (COALESCE(:wCompHist_VlrIPI,'') <> '') THEN
            BEGIN               
              wCompHist_VlrIPI = ' i.bdCOMPHIST_VLRIPI = IIF(i.bdVLRIPI > 0,''' || :wCompHist_VlrIPI || ''',i.bdCOMPHIST_VLRIPI) ';
            END
        END
      /*--------Complemento histórico do Cofins-------------*/
      wCodigoTipo = CASE WHEN :PRTIPOLAN = 'ENT'  THEN 24
                         WHEN :PRTIPOLAN = 'SAI'  THEN 25
                         WHEN :PRTIPOLAN = 'SERE' THEN 26
                         WHEN :PRTIPOLAN = 'SERR' THEN 27
                    END;
      SELECT FIRST 1 COALESCE(
                              (
                               SELECT FIRST 1 t.bdCOMPLEMENTO
                               FROM TCONTAS_ONLINE_TEMP t
                               WHERE t.bdSESSAO = :prSESSAO
                                 AND t.bdCODNAT = :wCodNat
                                 AND t.bdCODTIPOCONTA = :wCondPgto   
                                 AND t.BDREFERENCIA = :wreferencia
                                 AND (t.bdCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 116 /*Cofins - A vista*/
                                                               WHEN :wCondPgto =  51 THEN 122 /*Cofins - Prazo*/
                                                               WHEN :wCondPgto = 406 THEN 175 /*Cofins - Outras*/
                                                          END)
                              ),
                              (
                               /*Se não houver na conta, busca no vinculo de complemento e se lá não houver usa o complemento padrão*/
                               SELECT FIRST 1 h.bdCOMPLEMENTO
                               FROM TCOMPLEMENTO_HIST_VINC hv
                               LEFT OUTER JOIN  TCOMPLEMENTO_HIST h ON (h.bdCODCOMPHIST = hv.bdCODCOMPHIST)
                               WHERE hv.bdCODPLANOONLINE = :prCODPLANOONLINE
                                 AND hv.bdCODIGOTIPO = :wCodigoTipo
                              ),
                               ('*NRDOC - *NOMEPART') /*Default*/
                             ) bdCODCOMPHIST
      FROM RDB$DATABASE
      INTO :wCompHist_VlrCofins;

      IF (COALESCE(:wCompHist_VlrCofins,'') <> '') THEN
        BEGIN
          wCompHist_VlrCofins = ' i.bdCOMPHIST_VLRCOFINS = IIF(i.bdVLRCOFINS > 0,''' || :wCompHist_VlrCofins || ''',i.bdCOMPHIST_VLRCOFINS) ';
        END
      /*---------DIFAL----------*/
      /*---Complemento histórico da FCP da UF de destino-------*/
      IF (POSITION('SER', :PRTIPOLAN) = 0) THEN
        BEGIN
          SELECT FIRST 1 COALESCE(
                                  (
                                   SELECT FIRST 1 t.bdCOMPLEMENTO
                                   FROM TCONTAS_ONLINE_TEMP t
                                   WHERE t.bdSESSAO = :prSESSAO
                                   AND t.bdCODNAT = :wCodNat
                                   AND t.bdCODTIPOCONTA = :wCondPgto 
                                   AND t.BDREFERENCIA = :wreferencia
                                   AND (t.bdCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 225 /*FCP da UF de destino - A vista*/
                                                                 WHEN :wCondPgto =  51 THEN 226 /*FCP da UF de destino - Prazo*/
                                                                 WHEN :wCondPgto = 406 THEN 227 /*FCP da UF de destino - Outras*/
                                                            END)
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                 ) bdCODCOMPHIST
          FROM RDB$DATABASE
          INTO :wCompHist_Difal;
    
          IF (COALESCE(:wCompHist_Difal,'') <> '') THEN
            BEGIN                          
              wSQL =  '   ( ';
              wSQL = wSQL || '        SELECT SUM(fcp.bdVLR_FCP_UF_DEST) as bdVLR_FCP_UF_DEST ';
              wSQL = wSQL || '        FROM ( ';
              wSQL = wSQL || '              SELECT c.bdSESSAO, c.bdCODEMP, c.bdCHAVE, COALESCE(c.bdVLR_FCP_UF_DEST, 0) as BDVLR_FCP_UF_DEST ';
              wSQL = wSQL || '              FROM TMP_'||:wTableC100||'_TEMP c ';
              wSQL = wSQL || '              WHERE c.bdSESSAO = i.bdSESSAO ';
              wSQL = wSQL || '                AND c.bdCODEMP = i.bdCODEMP ';
              wSQL = wSQL || '                AND c.bdCHAVE = i.bdCHAVE ';
              wSQL = wSQL || '              UNION ';
              wSQL = wSQL || '              SELECT d.bdSESSAO, d.bdCODEMP, d.bdCHAVE, COALESCE(d.bdVLR_FCP_UF_DEST, 0) as bdVLR_FCP_UF_DEST ';
              wSQL = wSQL || '              FROM TMP_'||:wTableD100||'_TEMP d ';
              wSQL = wSQL || '              WHERE d.bdSESSAO = i.bdSESSAO ';
              wSQL = wSQL || '                AND d.bdCODEMP = i.bdCODEMP ';
              wSQL = wSQL || '                AND d.bdCHAVE = i.bdCHAVE ';
              wSQL = wSQL || '              ) fcp ';
              wSQL = wSQL || '        GROUP BY fcp.bdSESSAO, fcp.bdCODEMP, fcp.bdCHAVE ';
              wSQL = wSQL || '        ) > 0 ';
    
              wCompHist_Difal = ' i.bdCOMPHIST_VLR_FCP_UF_DEST = IIF('||wSQL||',''' || :wCompHist_Difal || ''',i.bdCOMPHIST_VLR_FCP_UF_DEST) ';
            END
    
          /*---Complemento histórico do Valor do ICMS interestadual para UF de destino----*/
          SELECT FIRST 1 COALESCE(
                                  (
                                   SELECT FIRST 1 t.bdCOMPLEMENTO
                                   FROM TCONTAS_ONLINE_TEMP t
                                   WHERE t.bdSESSAO = :prSESSAO
                                     AND t.bdCODNAT = :wCodNat
                                     AND t.bdCODTIPOCONTA = :wCondPgto 
                                     AND t.BDREFERENCIA = :wreferencia
                                     AND (t.bdCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 228 /*Valor do ICMS interestadual para UF de destino - A vista*/
                                                                   WHEN :wCondPgto =  51 THEN 229 /*Valor do ICMS interestadual para UF de destino - Prazo*/
                                                                   WHEN :wCondPgto = 406 THEN 230 /*Valor do ICMS interestadual para UF de destino - Outras*/
                                                              END)
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                 ) bdCODCOMPHIST
          FROM RDB$DATABASE
          INTO :wCompHist_VlrICMSInterDest;
    
          IF (COALESCE(:wCompHist_VlrICMSInterDest,'') <> '') THEN
            BEGIN                          
              wSQL = '   ( ';
              wSQL = wSQL || '        SELECT SUM(fcp.bdVLRICMS_UF_DEST) as bdVLRICMS_UF_DEST ';
              wSQL = wSQL || '        FROM ( ';
              wSQL = wSQL || '              SELECT c.bdSESSAO, c.bdCODEMP, c.bdCHAVE, COALESCE(c.bdVLRICMS_UF_DEST, 0) as bdVLRICMS_UF_DEST ';
              wSQL = wSQL || '              FROM TMP_'||:wTableC100||'_TEMP c ';
              wSQL = wSQL || '              WHERE c.bdSESSAO = i.bdSESSAO ';
              wSQL = wSQL || '                AND c.bdCODEMP = i.bdCODEMP ';
              wSQL = wSQL || '                AND c.bdCHAVE = i.bdCHAVE ';
              wSQL = wSQL || '              UNION ';
              wSQL = wSQL || '              SELECT d.bdSESSAO, d.bdCODEMP, d.bdCHAVE, COALESCE(d.bdVLRICMS_UF_DEST, 0) as bdVLRICMS_UF_DEST ';
              wSQL = wSQL || '              FROM TMP_'||:wTableD100||'_TEMP d ';
              wSQL = wSQL || '              WHERE d.bdSESSAO = i.bdSESSAO ';
              wSQL = wSQL || '                AND d.bdCODEMP = i.bdCODEMP ';
              wSQL = wSQL || '                AND d.bdCHAVE = i.bdCHAVE ';
              wSQL = wSQL || '              ) fcp ';
              wSQL = wSQL || '        GROUP BY fcp.bdSESSAO, fcp.bdCODEMP, fcp.bdCHAVE ';
              wSQL = wSQL || '        ) > 0 ';
                            
              wCompHist_VlrICMSInterDest = ' i.bdCOMPHIST_VLRICMS_UF_DEST = IIF('||wSQL||',''' || :wCompHist_VlrICMSInterDest || ''',i.bdCOMPHIST_VLRICMS_UF_DEST) ';
            END
    
          /*-----Complemento histórico do Valor do ICMS interestadual para UF do remetente----*/
          SELECT FIRST 1 COALESCE(
                                  (
                                   SELECT FIRST 1 t.bdCOMPLEMENTO
                                   FROM TCONTAS_ONLINE_TEMP t
                                   WHERE t.bdSESSAO = :prSESSAO
                                   AND t.bdCODNAT = :wCodNat
                                   AND t.bdCODTIPOCONTA = :wCondPgto  
                                   AND t.BDREFERENCIA = :wreferencia
                                   AND (t.bdCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 231 /*Valor do ICMS interestadual para UF do remetente - A vista*/
                                                                 WHEN :wCondPgto =  51 THEN 232 /*Valor do ICMS interestadual para UF do remetente - Prazo*/
                                                                 WHEN :wCondPgto = 406 THEN 233 /*Valor do ICMS interestadual para UF do remetente - Outras*/
                                                            END)
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                 ) bdCODCOMPHIST
          FROM RDB$DATABASE
          INTO :wCompHist_VlrICMSInterRem;
    
          IF (COALESCE(:wCompHist_VlrICMSInterRem,'') <> '') THEN
            BEGIN                  
              wSQL =  '   ( ';
              wSQL = wSQL || '        SELECT SUM(fcp.bdVLRICMS_UF_REM) as bdVLRICMS_UF_REM ';
              wSQL = wSQL || '        FROM ( ';
              wSQL = wSQL || '              SELECT c.bdSESSAO, c.bdCODEMP, c.bdCHAVE, COALESCE(c.bdVLRICMS_UF_REM, 0) as bdVLRICMS_UF_REM ';
              wSQL = wSQL || '              FROM TMP_'||:wTableC100||'_TEMP c ';
              wSQL = wSQL || '              WHERE c.bdSESSAO = i.bdSESSAO ';
              wSQL = wSQL || '                AND c.bdCODEMP = i.bdCODEMP ';
              wSQL = wSQL || '                AND c.bdCHAVE = i.bdCHAVE ';
              wSQL = wSQL || '              UNION ';
              wSQL = wSQL || '              SELECT d.bdSESSAO, d.bdCODEMP, d.bdCHAVE, COALESCE(d.bdVLRICMS_UF_REM, 0) as bdVLRICMS_UF_REM ';
              wSQL = wSQL || '              FROM TMP_'||:wTableD100||'_TEMP d ';
              wSQL = wSQL || '              WHERE d.bdSESSAO = i.bdSESSAO ';
              wSQL = wSQL || '                AND d.bdCODEMP = i.bdCODEMP ';
              wSQL = wSQL || '                AND d.bdCHAVE = i.bdCHAVE ';
              wSQL = wSQL || '              ) fcp ';
              wSQL = wSQL || '        GROUP BY fcp.bdSESSAO, fcp.bdCODEMP, fcp.bdCHAVE ';
              wSQL = wSQL || '        ) > 0 ';
                              
              wCompHist_VlrICMSInterRem = ' i.bdCOMPHIST_VLRICMS_UF_REM = IIF('||wSQL||',''' || :wCompHist_VlrICMSInterRem || ''',i.bdCOMPHIST_VLRICMS_UF_REM) ';
            END
        END
      /*-----Complemento histórico do Valor do ICMS de crédito presumido Estornado ----*/
      IF (:PRTIPOLAN = 'ENT') THEN
        BEGIN
          wCodigoTipo = 152;

          SELECT FIRST 1 COALESCE(
                                  (
                                   SELECT FIRST 1 t.bdCOMPLEMENTO
                                   FROM TCONTAS_ONLINE_TEMP t
                                   WHERE t.bdSESSAO = :prSESSAO
                                     AND t.bdCODNAT = :wCodNat
                                     AND t.bdCODTIPOCONTA = :wCondPgto    
                                     AND t.BDREFERENCIA = :wreferencia
                                     AND (t.bdCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 290 /*ICMS - A vista*/
                                                                   WHEN :wCondPgto =  51 THEN 291 /*ICMS - Prazo*/
                                                                   WHEN :wCondPgto = 406 THEN 292 /*ICMS - Outras*/
                                                              END)
                                  ),
                                  (
                                   SELECT FIRST 1 h.bdCOMPLEMENTO
                                   FROM TCOMPLEMENTO_HIST_VINC hv
                                   LEFT OUTER JOIN  TCOMPLEMENTO_HIST h ON (h.bdCODCOMPHIST = hv.bdCODCOMPHIST)
                                   WHERE hv.bdCODPLANOONLINE = :prCODPLANOONLINE
                                     AND hv.bdCODIGOTIPO = :wCodigoTipo
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                  ) bdCODCOMPHIST
          FROM RDB$DATABASE
          INTO :wCompHist_VlrICMSEstornado;
          IF (COALESCE(:wCompHist_VlrICMSEstornado,'') <> '') THEN
            BEGIN                                                     
              wCompHist_VlrICMSEstornado = ' i.BDCOMPHIST_VLRICMSESTORNADO = IIF(i.bdVLRICMS > 0,''' || :wCompHist_VlrICMSEstornado || ''',i.BDCOMPHIST_VLRICMSESTORNADO) ';
            END
        END
    IF ((wCompHist_VlrContab <> '') OR
       (wCompHist_VlrPis <> '') OR
       (wCompHist_VlrICMS <> '') OR
       (wCompHist_VlrICMSST <> '') OR
       (wCompHist_VlrICMSFCPST <> '') OR
       (wCompHist_VlrIPI <> '') OR
       (wCompHist_VlrICMSCONC <> '') OR
       (WCOMPHIST_VLRICMSFCPOP <> '') OR
       (wCompHist_VlrCofins <> '') OR
       (wCompHist_Difal <> '') OR
       (wCompHist_VlrICMSInterDest <> '') OR
       (wCompHist_VlrICMSInterRem <> '') OR
       (wCompHist_VlrICMSEstornado <> '')) THEN
      BEGIN                   
        wSQL =         ' UPDATE TMP_'||:wTableItem||'_TEMP i ';
        wSQL = wSQL || ' SET ';
        IF (wCompHist_VlrContab <> '') THEN
          wSQL = wSQL || wCompHist_VlrContab||',';
        IF (wCompHist_VlrPis <> '') THEN
          wSQL = wSQL || wCompHist_VlrPis||',';
        IF (wCompHist_VlrICMS <> '') THEN
          wSQL = wSQL || wCompHist_VlrICMS||',';
        IF (wCompHist_VlrICMSST <> '') THEN
          wSQL = wSQL || wCompHist_VlrICMSST||',';
        IF (wCompHist_VlrICMSFCPST <> '') THEN
          wSQL = wSQL || wCompHist_VlrICMSFCPST||',';
        IF (wCompHist_VlrICMSCONC <> '') THEN
          wSQL = wSQL || wCompHist_VlrICMSCONC||',';
        IF (WCOMPHIST_VLRICMSFCPOP <> '') THEN
          WSQL = WSQL || WCOMPHIST_VLRICMSFCPOP || ',';
        IF (wCompHist_VlrIPI <> '') THEN
          wSQL = wSQL || wCompHist_VlrIPI||',';
        IF (wCompHist_VlrCofins <> '') THEN
          wSQL = wSQL || wCompHist_VlrCofins||',';
        IF (wCompHist_Difal <> '') THEN
          wSQL = wSQL || wCompHist_Difal||',';
        IF (wCompHist_VlrICMSInterDest <> '') THEN
          wSQL = wSQL || wCompHist_VlrICMSInterDest||',';
        IF (wCompHist_VlrICMSInterRem <> '') THEN
          wSQL = wSQL || wCompHist_VlrICMSInterRem||',';
        IF (wCompHist_VlrICMSEstornado <> '') THEN
          wSQL = wSQL || wCompHist_VlrICMSEstornado||',';
        wSQL = SUBSTRING(wSQL FROM 1 FOR (strlen(wSQL) - 1));

        wSQL = wSQL || ' WHERE i.bdSESSAO = '||:prSESSAO;
        wSQL = wSQL || '   AND i.bdCODNAT = '||:wCodNat;

        wSQL = wSQL || ' AND EXISTS (';
        wSQL = wSQL ||              'SELECT MOV.BDCHAVE ';
        wSQL = wSQL ||              'FROM TMP_'||:wTable||'_TEMP MOV ';
        wSQL = wSQL ||              'WHERE MOV.BDSESSAO = I.BDSESSAO ';
        wSQL = wSQL ||              'AND MOV.BDCODEMP = I.BDCODEMP ';
        wSQL = wSQL ||              'AND MOV.BDCHAVE = I.BDCHAVE ';
        IF ((wDATINI IS NOT NULL) OR (wDATFIN IS NOT NULL)) THEN -- Alt.: #147718 #147785 - Lançamento sem data...
          wSQL = wSQL ||              'AND MOV.'||wfielddata||' between '''||wdatini||''' and '''||wdatfin||''' ';
        IF (POSITION('SER', :PRTIPOLAN)> 0) THEN
          wSQL=wSQL ||              'AND MOV.BDTIPLAN = '||IIF(:PRTIPOLAN = 'SERE', '0', '1');
        wSQL = wSQL ||              ') ';

        wSQL = wSQL || '   AND NOT EXISTS( ';
        wSQL = wSQL || '                  SELECT inco.bdCODEMP, inco.bdCHAVE, inco.bdSESSAO ';
        wSQL = wSQL || '                  FROM '||:wTableInc||' inco ';
        wSQL = wSQL || '                  WHERE inco.bdCODEMP = i.bdCODEMP ';
        wSQL = wSQL || '                    AND inco.bdCHAVE = i.bdCHAVE ';
        wSQL = wSQL || '                    AND inco.bdSESSAO = i.bdSESSAO ';
        wSQL = wSQL || '                  ); ';
                                 
        EXECUTE STATEMENT wSQL;
      END


      IF ((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SAI')) THEN
        BEGIN
          /*-----Diferencial de alíquota------*/
          /*----Complemento histórico do Diferencial de alíquota----*/
          SELECT FIRST 1 COALESCE(
                                  (
                                   SELECT t.bdCOMPLEMENTO
                                   FROM TCONTAS_ONLINE_TEMP t
                                   WHERE t.bdSESSAO = :prSESSAO
                                   AND t.bdCODNAT = :wCodNat
                                   AND t.bdCODTIPOCONTA = :wCondPgto   
                                   AND t.BDREFERENCIA = :wreferencia
                                   AND (t.bdCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 219 /*A vista*/
                                                                 WHEN :wCondPgto =  51 THEN 220 /*Prazo*/
                                                                 WHEN :wCondPgto = 406 THEN 221 /*Outras*/
                                                            END)
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                 ) bdCODCOMPHIST
          FROM RDB$DATABASE
          INTO :wComplementoHist;

          IF (COALESCE(:wComplementoHist,'') <> '') THEN
            BEGIN
              wSQL =         ' UPDATE TMP_'||:wTableItem||'_TEMP i ';
              wSQL = wSQL || ' SET i.bdCOMPHIST_VLRDIFALIQ = '''||:wComplementoHist||'''';
              wSQL = wSQL || ' WHERE i.bdSESSAO = '||:prSESSAO;
              wSQL = wSQL || '   AND i.bdCODNAT = '||:wCodNat;
              wSQL = wSQL || ' AND EXISTS (';
              wSQL = wSQL ||              'SELECT MOV.BDCHAVE ';
              wSQL = wSQL ||              'FROM TMP_'||:wTable||'_TEMP MOV ';
              wSQL = wSQL ||              'WHERE MOV.BDSESSAO = I.BDSESSAO ';
              wSQL = wSQL ||              'AND MOV.BDCODEMP = I.BDCODEMP ';
              wSQL = wSQL ||              'AND MOV.BDCHAVE = I.BDCHAVE ';
              IF ((wDATINI IS NOT NULL) OR (wDATFIN IS NOT NULL)) THEN -- Alt.: #147718 #147785 - Lançamento sem data...
                wSQL = wSQL ||              'AND MOV.'||wfielddata||' between '''||wdatini||''' and '''||wdatfin||''' ';
              IF (POSITION('SER', :PRTIPOLAN)> 0) THEN
                wSQL=wSQL ||              'AND MOV.BDTIPLAN = '||IIF(:PRTIPOLAN = 'SERE', '0', '1');
              wSQL = wSQL ||              ') ';
              wSQL = wSQL || '   AND ((( ';
              wSQL = wSQL || '          SELECT SUM(COALESCE(D.BDVLRDIFENTALIQ, 0)) BDVLRDIF ';
              wSQL = wSQL || '          FROM '||wTableDifAliq||' D ';
              wSQL = wSQL || '          WHERE D.BDSESSAO = I.BDSESSAO ';
              wSQL = wSQL || '          AND D.BDCODEMP = I.BDCODEMP ';
              wSQL = wSQL || '          AND D.BDCHAVE = I.BDCHAVE ';
              wSQL = wSQL || '          AND D.BDORDEM = I.BDORDEM ';
              wSQL = wSQL || '          GROUP BY D.BDSESSAO, D.BDCODEMP, D.BDCHAVE, D.BDORDEM ';
              wSQL = wSQL || '         ) > 0) OR ';
              wSQL = wSQL || '        (( ';
              wSQL = wSQL || '          SELECT SUM(COALESCE(D.BDIMPRECOLHER, 0)) BDVLRDIF ';
              wSQL = wSQL || '          FROM '||wTableDifAliqPR||' D ';
              wSQL = wSQL || '          WHERE D.BDSESSAO = I.BDSESSAO ';
              wSQL = wSQL || '          AND D.BDCODEMP = I.BDCODEMP ';
              wSQL = wSQL || '          AND D.BDCHAVE = I.BDCHAVE ';
              wSQL = wSQL || '          AND D.BDORDEM = I.BDORDEM ';
              wSQL = wSQL || '          GROUP BY D.BDSESSAO, D.BDCODEMP, D.BDCHAVE, D.BDORDEM ';
              wSQL = wSQL || '         ) > 0)) ';
              wSQL = wSQL || '   AND NOT EXISTS( ';
              wSQL = wSQL || '                  SELECT inco.bdCODEMP, inco.bdCHAVE, inco.bdSESSAO ';
              wSQL = wSQL || '                  FROM '||:wTableInc||' inco ';
              wSQL = wSQL || '                  WHERE inco.bdCODEMP = i.bdCODEMP ';
              wSQL = wSQL || '                    AND inco.bdCHAVE = i.bdCHAVE ';
              wSQL = wSQL || '                    AND inco.bdSESSAO = i.bdSESSAO ';
              wSQL = wSQL || '                  ); ';
              EXECUTE STATEMENT wSQL;
            END
        END

      IF (:PRTIPOLAN = 'ENT') THEN
        BEGIN
          /*---------Antecipação de ICMS------*/
          /*-Complemento histórico de Antecipação de ICMS------*/
          SELECT FIRST 1 COALESCE(
                                  (
                                   SELECT t.bdCOMPLEMENTO
                                   FROM TCONTAS_ONLINE_TEMP t
                                   WHERE t.bdSESSAO = :prSESSAO
                                   AND t.bdCODNAT = :wCodNat
                                   AND t.bdCODTIPOCONTA = :wCondPgto 
                                   AND t.BDREFERENCIA = :wreferencia
                                   AND (t.bdCODITEMONLINE = CASE WHEN :wCondPgto =  50 THEN 298 /*A vista*/
                                                                 WHEN :wCondPgto =  51 THEN 299 /*Prazo*/
                                                                 WHEN :wCondPgto = 406 THEN 300 /*Outras*/
                                                            END)
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                 ) bdCODCOMPHIST
          FROM RDB$DATABASE
          INTO :wComplementoHist;

          IF (COALESCE(:wComplementoHist,'') <> '') THEN
            BEGIN
              wSQL =         ' UPDATE TMP_'||:wTableItem||'_TEMP i ';
              wSQL = wSQL || ' SET i.BDCOMPHIST_VLRANTECIPACAO = '''||:wComplementoHist||'''';
              wSQL = wSQL || ' WHERE i.bdSESSAO = '||:prSESSAO;
              wSQL = wSQL || ' AND i.bdCODNAT = '||:wCodNat;
              wSQL = wSQL || ' AND EXISTS (';
              wSQL = wSQL || ' SELECT MOV.BDCHAVE ';
              wSQL = wSQL || ' FROM TMP_'||:wTable||'_TEMP MOV ';
              wSQL = wSQL || ' WHERE MOV.BDSESSAO = I.BDSESSAO ';
              wSQL = wSQL || ' AND MOV.BDCODEMP = I.BDCODEMP ';
              wSQL = wSQL || ' AND MOV.BDCHAVE = I.BDCHAVE ';
              IF ((wDATINI IS NOT NULL) OR (wDATFIN IS NOT NULL)) THEN -- Alt.: #147718 #147785 - Lançamento sem data...
                wSQL = wSQL || ' AND MOV.'||wfielddata||' between '''||wdatini||''' and '''||wdatfin||''') ';
              wSQL = wSQL || '   AND ((( ';
              wSQL = wSQL || '          SELECT SUM(COALESCE(A.BDIMPRECOLHER, 0)) BDIMPRECOLHER ';
              wSQL = wSQL || '          FROM TMP_VEF_EMP_TMOVENTANTIMP_TEMP A ';
              wSQL = wSQL || '          WHERE A.BDSESSAO = I.BDSESSAO ';
              wSQL = wSQL || '          AND A.BDCODEMP = I.BDCODEMP ';
              wSQL = wSQL || '          AND A.BDCHAVE = I.BDCHAVE ';
              wSQL = wSQL || '          AND A.BDORDEM = I.BDORDEM ';
              wSQL = wSQL || '          GROUP BY A.BDSESSAO, A.BDCODEMP, A.BDCHAVE, A.BDORDEM ';
              wSQL = wSQL || '         ) > 0) OR ';
              wSQL = wSQL || '        (( ';
              wSQL = wSQL || '          SELECT SUM(COALESCE(A.BDVLRANT, 0)) BDVLRANT ';
              wSQL = wSQL || '          FROM TMP_VEF_EMP_TMOVENTANTPR_TEMP A ';
              wSQL = wSQL || '          WHERE A.BDSESSAO = I.BDSESSAO ';
              wSQL = wSQL || '          AND A.BDCODEMP = I.BDCODEMP ';
              wSQL = wSQL || '          AND A.BDCHAVE = I.BDCHAVE ';
              wSQL = wSQL || '          AND A.BDORDEM = I.BDORDEM ';
              wSQL = wSQL || '          GROUP BY A.BDSESSAO, A.BDCODEMP, A.BDCHAVE, A.BDORDEM ';
              wSQL = wSQL || '         ) > 0)) ';
              wSQL = wSQL || '   AND NOT EXISTS( ';
              wSQL = wSQL || '                  SELECT inco.bdCODEMP, inco.bdCHAVE, inco.bdSESSAO ';
              wSQL = wSQL || '                  FROM '||:wTableInc||' inco ';
              wSQL = wSQL || '                  WHERE inco.bdCODEMP = i.bdCODEMP ';
              wSQL = wSQL || '                    AND inco.bdCHAVE = i.bdCHAVE ';
              wSQL = wSQL || '                    AND inco.bdSESSAO = i.bdSESSAO ';
              wSQL = wSQL || '                  ); ';
              EXECUTE STATEMENT wSQL;
        END

    END
    END

/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERE_COMPLEMENTO_HIST','3');
  /*-------------Complemento de histórico das retenções-----------*/
  FOR
      SELECT c.bdCODITEMONLINE, c.bdCOMPLEMENTO, COALESCE(c.bdCODREC, 0) AS bdCODREC, c.BDREFERENCIA
      FROM TCONTAS_ONLINE_TEMP c
      WHERE c.bdSESSAO = :prSESSAO
      AND c.bdCODNAT IS NULL
      AND c.bdCODTIPOCONTA IS NULL
      INTO :wCodItemOnline, :wComplementoHist, :wCodRec, :wreferencia
  DO
    BEGIN
      wCodigoTipo = NULL;
      wFieldAux   = NULL;
      wWhereAux   = NULL;
      wSubSelect=                'SELECT TMP.BDCODEMP ';
      wSubSelect= :wSubSelect || 'FROM TMP_'||:wTableRet||'_TEMP TMP ';

      /*PIS*/
      IF (:wCodItemOnline = :wCodItemPIS) THEN
        BEGIN
          wCodigoTipo = CASE WHEN :PRTIPOLAN = 'SAI'  THEN 44
                             WHEN :PRTIPOLAN = 'ENT'  THEN 43
                             WHEN :PRTIPOLAN = 'SERE' THEN 45
                             WHEN :PRTIPOLAN = 'SERR' THEN 46
                        END;

          wFieldAux   = 'bdCOMPHIST_VLRPISRET';
          wWhereAux   = 'WHERE TMP.bdVLRPIS > 0 AND TMP.bdCODRECPIS = '||:wCodRec;
        END
      ELSE /*COFINS*/
      IF (:wCodItemOnline = :wCodItemCof) THEN
        BEGIN
          wCodigoTipo = CASE WHEN :PRTIPOLAN = 'SAI'  THEN 50
                             WHEN :PRTIPOLAN = 'ENT'  THEN 49
                             WHEN :PRTIPOLAN = 'SERE' THEN 51
                             WHEN :PRTIPOLAN = 'SERR' THEN 52
                        END;

          wFieldAux   = 'bdCOMPHIST_VLRCOFRET';
          wWhereAux   = 'WHERE TMP.bdVLRCOFINS > 0 AND TMP.bdCODRECCOFINS = '||:wCodRec;
        END
      ELSE /*Contribuição social*/
      IF (:wCodItemOnline = :wCodItemCS) THEN
        BEGIN
          wCodigoTipo = CASE WHEN :PRTIPOLAN = 'SAI'  THEN 56
                             WHEN :PRTIPOLAN = 'ENT'  THEN 55
                             WHEN :PRTIPOLAN = 'SERE' THEN 57
                             WHEN :PRTIPOLAN = 'SERR' THEN 58
                        END;

          wFieldAux   = 'bdCOMPHIST_VLRCSRET';
          wWhereAux   = 'WHERE TMP.bdVLRCSOCIAL > 0 AND TMP.bdCODRECCSOCIAL = '||:wCodRec;
        END
      ELSE /*IR*/
      IF (:wCodItemOnline = :wCodItemIR) THEN
        BEGIN
          wCodigoTipo = CASE WHEN :PRTIPOLAN = 'SAI'  THEN 62
                             WHEN :PRTIPOLAN = 'ENT'  THEN 61
                             WHEN :PRTIPOLAN = 'SERE' THEN 63
                             WHEN :PRTIPOLAN = 'SERR' THEN 64
                        END;

          wFieldAux   = 'bdCOMPHIST_VLRIRRET';
          IF (POSITION('SER', :PRTIPOLAN) > 0) THEN
            BEGIN
              wSubSelect = 'SELECT TMP.BDCODEMP FROM TMP_'||:wTableItem||'_TEMP TMP ';
              wWhereAux  = 'WHERE TMP.BDVLRIRSER > 0 AND TMP.BDCODREC = '||:wCodRec;
            END
          ELSE
            wWhereAux   = 'WHERE TMP.bdVLRIR > 0 AND TMP.bdCODRECIR = '||:wCodRec;
        END
      ELSE /*INSS*/
      IF (:wCodItemOnline = :wCodItemINSS) THEN
        BEGIN
          wCodigoTipo = CASE WHEN :PRTIPOLAN = 'SAI'  THEN 68
                             WHEN :PRTIPOLAN = 'ENT'  THEN 67
                             WHEN :PRTIPOLAN = 'SERE' THEN 69
                             WHEN :PRTIPOLAN = 'SERR' THEN 70
                        END;

          wFieldAux   = 'bdCOMPHIST_VLRINSSRET';
              wSubSelect = 'SELECT TMP.BDCODEMP FROM TMP_'||:wTableINSS||'_TEMP TMP ';
              wWhereAux  = 'WHERE TMP.BDRETINSS > 0 AND TMP.bdCODRECINSS = '||:wCodRec;
        END
      ELSE /*INSS APOSENTADORIA 15 ANOS*/
      IF (:wCodItemOnline = :wCodItemINSS15) THEN
        BEGIN
          wCodigoTipo = CASE WHEN :PRTIPOLAN = 'SAI'  THEN 304
                             WHEN :PRTIPOLAN = 'ENT'  THEN 313
                             WHEN :PRTIPOLAN = 'SERE' THEN 307
                             WHEN :PRTIPOLAN = 'SERR' THEN 310
                        END;

          wFieldAux   = 'BDCOMPHIST_VLRINSSAPOS15';
          wSubSelect  = 'SELECT TMP.BDCODEMP FROM TMP_' || :wTableINSS || '_TEMP TMP ';
          wWhereAux   = 'WHERE TMP.BDVLRAPOS15 > 0';
        END
      ELSE  /*INSS APOSENTADORIA 20 ANOS*/
      IF (:wCodItemOnline = :wCodItemINSS20) THEN
        BEGIN
          wCodigoTipo = CASE WHEN :PRTIPOLAN = 'SAI'  THEN 305
                             WHEN :PRTIPOLAN = 'ENT'  THEN 314
                             WHEN :PRTIPOLAN = 'SERE' THEN 308
                             WHEN :PRTIPOLAN = 'SERR' THEN 311
                        END;

          wFieldAux   = 'BDCOMPHIST_VLRINSSAPOS20';
          wSubSelect  = 'SELECT TMP.BDCODEMP FROM TMP_' || :wTableINSS || '_TEMP TMP ';
          wWhereAux   = 'WHERE TMP.BDVLRAPOS20 > 0';
        END
      ELSE /*INSS APOSENTADORIA 25 ANOS*/
      IF (:wCodItemOnline = :wCodItemINSS25) THEN
        BEGIN
          wCodigoTipo = CASE WHEN :PRTIPOLAN = 'SAI'  THEN 306
                             WHEN :PRTIPOLAN = 'ENT'  THEN 315
                             WHEN :PRTIPOLAN = 'SERE' THEN 309
                             WHEN :PRTIPOLAN = 'SERR' THEN 312
                        END;

          wFieldAux   = 'BDCOMPHIST_VLRINSSAPOS25';
          wSubSelect  = 'SELECT TMP.BDCODEMP FROM TMP_' || :wTableINSS || '_TEMP TMP ';
          wWhereAux   = 'WHERE TMP.BDVLRAPOS25 > 0';
        END
      ELSE /*ISS*/
      IF (:wCodItemOnline = :wCodItemISS) THEN
        BEGIN
          wCodigoTipo = CASE WHEN :PRTIPOLAN = 'SAI'  THEN 74
                             WHEN :PRTIPOLAN = 'ENT'  THEN 73
                             WHEN :PRTIPOLAN = 'SERE' THEN 75
                             WHEN :PRTIPOLAN = 'SERR' THEN 76
                        END;

          wFieldAux   = 'bdCOMPHIST_VLRISSRET';
          IF (POSITION('SER', :PRTIPOLAN) > 0) THEN
            wWhereAux   = 'WHERE TMP.bdISSRET > 0 ';
          ELSE
            wWhereAux   = 'WHERE TMP.bdISSRET > 0 AND TMP.bdCODRECISS = '||:wCodRec;
        END

      IF (COALESCE(:wComplementoHist,'') = '') THEN
        BEGIN
          wComplementoHist = '*NRDOC - *NOMEPART';
          SELECT FIRST 1 COALESCE(--:wComplementoHist,
                                  (
                                   SELECT FIRST 1 h.bdCOMPLEMENTO
                                   FROM TCOMPLEMENTO_HIST_VINC hv
                                   LEFT OUTER JOIN  TCOMPLEMENTO_HIST h ON (h.bdCODCOMPHIST = hv.bdCODCOMPHIST)
                                   WHERE hv.bdCODPLANOONLINE = :prCODPLANOONLINE
                                     AND hv.bdCODIGOTIPO = :wCodigoTipo
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                 ) bdCODCOMPHIST
          FROM RDB$DATABASE
          INTO :wComplementoHist;
        END

      IF ((COALESCE(:wComplementoHist,'') <> '') AND (COALESCE(:wFieldAux,'') <> '') AND (COALESCE(:wWhereAux,'') <> '')) THEN
        BEGIN
          wSubSelect = :wSubSelect || :wWhereAux;

          wSQL =         ' UPDATE TMP_'||:wTableItem||'_TEMP i ';
          wSQL = wSQL || ' SET '||:wFieldAux||' = '''||:wComplementoHist||'''';
          wSQL = wSQL || ' WHERE i.bdSESSAO = '||:prSESSAO;
          wSQL = wSQL || ' AND EXISTS( ';
          wSQL = wSQL ||              :wSubSelect;
          wSQL = wSQL || '            AND TMP.bdCODEMP = i.bdCODEMP ';
          wSQL = wSQL || '            AND TMP.bdCHAVE  = i.bdCHAVE ';
          wSQL = wSQL || '            AND TMP.bdSESSAO = i.bdSESSAO ';
          wSQL = wSQL || '           ) ';
          wSQL = wSQL || '   AND NOT EXISTS( ';
          wSQL = wSQL || '           SELECT inco.bdCODEMP, inco.bdCHAVE, inco.bdSESSAO ';
          wSQL = wSQL || '           FROM '||:wTableInc||' inco ';
          wSQL = wSQL || '           WHERE inco.bdCODEMP = i.bdCODEMP ';
          wSQL = wSQL || '                    AND inco.bdCHAVE = i.bdCHAVE ';
          wSQL = wSQL || '                    AND inco.bdSESSAO = i.bdSESSAO ';
          wSQL = wSQL || '           ) ';
          wSQL = wSQL || 'AND EXISTS (';
          wSQL = wSQL ||             ' SELECT MOV.BDCHAVE ';
          wSQL = wSQL ||             ' FROM TMP_'||:wTable||'_TEMP MOV ';
          wSQL = wSQL ||             ' WHERE MOV.BDSESSAO = I.BDSESSAO ';
          wSQL = wSQL ||             ' AND MOV.BDCODEMP = I.BDCODEMP ';
          wSQL = wSQL ||             ' AND MOV.BDCHAVE = I.BDCHAVE ';
          wSQL = wSQL ||             ' AND '||wfieldref||' = '||wreferencia;
          IF (POSITION('SER', :PRTIPOLAN)> 0) THEN
            wSQL = wSQL ||             ' AND MOV.BDTIPLAN = '||IIF(:PRTIPOLAN = 'SERE', '0', '1');
          wSQL = wSQL ||            ') ';

          /*Se tiver registro na tabela de rateio não deve contabilizar o item, contabiliza só o rateio*/
          IF (:wTableRat <> '') THEN
            BEGIN
              wSQL = wSQL || ' AND NOT EXISTS ( SELECT RAT.BDSESSAO FROM TMP_'||:wTableRat||'_TEMP RAT WHERE RAT.BDSESSAO = I.BDSESSAO AND RAT.BDCODEMP = I.BDCODEMP AND RAT.BDCHAVE  = I.BDCHAVE AND RAT.BDORDEM  = I.BDORDEM )';
            END

          EXECUTE STATEMENT wSQL;
        END

      wCodItemOnline   = NULL;
      wComplementoHist = NULL;
      wCodRec          = NULL;
    END

/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERE_COMPLEMENTO_HIST','4');
  FOR
      SELECT c.BDREFERENCIA
      FROM TCONTAS_ONLINE_TEMP c
      WHERE c.bdSESSAO = :prSESSAO
      INTO :wreferencia
  DO
    BEGIN
      /*-----Complemento histórico do desconto--*/
      wComplementoHist = '*NRDOC - *NOMEPART';
      SELECT FIRST 1 c.bdCOMPLEMENTO FROM TCONTAS_ONLINE_TEMP c WHERE c.bdSESSAO = :prSESSAO AND c.BDREFERENCIA = :wreferencia AND c.bdCODITEMONLINE = 88 /*Desconto*/ INTO :wComplementoHist;
      wCodigoTipo = CASE WHEN :PRTIPOLAN = 'ENT'  THEN 30
                         WHEN :PRTIPOLAN = 'SAI'  THEN 31
                         WHEN :PRTIPOLAN = 'SERE' THEN 32
                         WHEN :PRTIPOLAN = 'SERR' THEN 33
                    END;
  
      IF (COALESCE(:wComplementoHist,'') = '') THEN
        BEGIN
          SELECT FIRST 1 COALESCE(--:wComplementoHist,
                                  (
                                   SELECT FIRST 1 h.bdCOMPLEMENTO
                                   FROM TCOMPLEMENTO_HIST_VINC hv
                                   LEFT OUTER JOIN  TCOMPLEMENTO_HIST h ON (h.bdCODCOMPHIST = hv.bdCODCOMPHIST)
                                   WHERE hv.bdCODPLANOONLINE = :prCODPLANOONLINE
                                     AND hv.bdCODIGOTIPO = :wCodigoTipo
                                  ),
                                   ('*NRDOC - *NOMEPART') /*Default*/
                                 ) bdCODCOMPHIST
          FROM RDB$DATABASE
          INTO :wComplementohist;
        END
  
      IF ((COALESCE(:wComplementoHist,'') <> '') AND (COALESCE(:wFieldAux,'') <> '') AND (COALESCE(:wWhereAux,'') <> '')) THEN
        BEGIN
          wSQL =         ' UPDATE TMP_'||:wTableItem||'_TEMP i ';
          wSQL = wSQL || ' SET i.bdCOMPHIST_VLRDESCONTO = '''||:wComplementoHist||'''';
          wSQL = wSQL || ' WHERE i.bdSESSAO = '||:prSESSAO;
          wSQL = wSQL || ' AND EXISTS( ';
          wSQL = wSQL || '            SELECT mov.bdDESCONTONOTA ';
          wSQL = wSQL || '            FROM TMP_'||:wTable||'_TEMP mov ';
          wSQL = wSQL || '            WHERE mov.bdDESCONTONOTA > 0 ';
          wSQL = wSQL || '            AND mov.bdCODEMP = i.bdCODEMP ';
          wSQL = wSQL || '            AND mov.bdCHAVE  = i.bdCHAVE ';
          wSQL = wSQL || '            AND mov.bdSESSAO = i.bdSESSAO ';
          wSQL = wSQL || '           ) ';

          wSQL = wSQL || ' AND EXISTS (';
          wSQL = wSQL ||              ' SELECT MOV.BDCHAVE ';
          wSQL = wSQL ||              ' FROM TMP_'||:wTable||'_TEMP MOV ';
          wSQL = wSQL ||              ' WHERE MOV.BDSESSAO = I.BDSESSAO ';
          wSQL = wSQL ||              ' AND MOV.BDCODEMP = I.BDCODEMP ';
          wSQL = wSQL ||              ' AND '||wfieldref||' = '||wreferencia;
          wSQL = wSQL ||              ' AND MOV.BDCHAVE = I.BDCHAVE ';
          IF (POSITION('SER', :PRTIPOLAN)> 0) THEN
            wSQL = wSQL ||              ' AND MOV.BDTIPLAN = '||IIF(:PRTIPOLAN = 'SERE', '0', '1');
          wSQL = wSQL ||             ') ';
  
          wSQL = wSQL || ' AND NOT EXISTS( ';
          wSQL = wSQL || '                SELECT inco.bdCODEMP, inco.bdCHAVE, inco.bdSESSAO ';
          wSQL = wSQL || '                FROM '||:wTableInc||' inco ';
          wSQL = wSQL || '                WHERE inco.bdCODEMP = i.bdCODEMP ';
          wSQL = wSQL || '                AND inco.bdCHAVE = i.bdCHAVE ';
          wSQL = wSQL || '                AND inco.bdSESSAO = i.bdSESSAO ';
          wSQL = wSQL || '               ); ';
   
          EXECUTE STATEMENT wSQL;
        END
  END
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERE_COMPLEMENTO_HIST','5');

 EXECUTE PROCEDURE SP_INSERE_COMPLEMENTO_HIST_CP(prtipolan,prsessao,wtable,wtableitem, wtablerat);



/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERE_COMPLEMENTO_HIST','6');
  IF (:wTableRat <> '') THEN
    EXECUTE PROCEDURE SP_INSERE_COMPLEMENTO_HIST_RAT(:PRCODPLANOONLINE, :PRSESSAO, :PRTIPOLAN);
            
/**/EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERE_COMPLEMENTO_HIST','7');
  WHEN ANY DO
    BEGIN
      IN AUTONOMOUS TRANSACTION DO
        EXECUTE PROCEDURE LANCA_EXCEPTION('SP_VALIDA_CONTA_ONLINE_TEMP = '||SUBSTRING(wSQL FROM 1 FOR 450), SQLCODE, GDSCODE);
      EXCEPTION;
    END
END^

CREATE OR ALTER procedure SP_INSERE_COMPLEMENTO_HIST_CP (
    PRTIPOLAN varchar(5),
    PRSESSAO integer,
    PRTABLE varchar(32),
    PRTABLEITEM varchar(32),
    PRTABLERAT varchar(32))
as
declare variable WGETCOMPL varchar(255) collate WIN_PTBR;
declare variable WGETCOMPLFIM varchar(255) collate WIN_PTBR;
declare variable WSQL varchar(32000) collate WIN_PTBR;
declare variable WWHERE varchar(32000) collate WIN_PTBR;
declare variable WSTR varchar(1000);
declare variable WCODEMP integer;
declare variable WAJUSTA integer;
declare variable WCHAVE integer;
declare variable WBDCODNAT integer;
declare variable WBDOBSERVACAO DM_OBSERVACAO_LAN;
declare variable WKEY varchar(20);
declare variable WRESULTCOMPHIST_VLRPIS varchar(1000);
declare variable WBDCOMPHIST_VLRPIS varchar(1000);
declare variable WRESULTCOMPHIST_VLRCONTAB varchar(1000);
declare variable WBDCOMPHIST_VLRCONTAB varchar(1000);
declare variable WBDCOMPHIST_VLRCOFINS varchar(1000);
declare variable WBDCOMPHIST_VLRPISRET varchar(1000);
declare variable WBDCOMPHIST_VLRCOFRET varchar(1000);
declare variable WBDCOMPHIST_VLRCSRET varchar(1000);
declare variable WBDCOMPHIST_VLRIRRET varchar(1000);
declare variable WBDCOMPHIST_VLRINSSRET varchar(1000);
declare variable WBDCOMPHIST_VLRDESCONTO varchar(1000);
declare variable WBDCOMPHIST_VLRISSRET varchar(1000);
declare variable WBDCOMPHIST_VLRINSSAPOS15 varchar(1000);
declare variable WBDCOMPHIST_VLRINSSAPOS20 varchar(1000);
declare variable WBDCOMPHIST_VLRINSSAPOS25 varchar(1000);
declare variable WBDCOMPHIST_VLRDIFALIQ varchar(1000);
declare variable WRESULTCOMPHIST_VLRCOFINS varchar(1000);
declare variable WRESULTCOMPHIST_VLRPISRET varchar(1000);
declare variable WRESULTCOMPHIST_VLRCOFRET varchar(1000);
declare variable WRESULTCOMPHIST_VLRCSRET varchar(1000);
declare variable WRESULTCOMPHIST_VLRIRRET varchar(1000);
declare variable WRESULTCOMPHIST_VLRINSSRET varchar(1000);
declare variable WRESULTCOMPHIST_VLRDESCONTO varchar(1000);
declare variable WRESULTCOMPHIST_VLRISSRET varchar(1000);
declare variable WRESULTCOMPHIST_VLRINSSAPOS15 varchar(1000);
declare variable WRESULTCOMPHIST_VLRINSSAPOS20 varchar(1000);
declare variable WRESULTCOMPHIST_VLRINSSAPOS25 varchar(1000);
declare variable WRESULTCOMPHIST_VLRDIFALIQ varchar(1000);
declare variable WBDCOMPHIST_VLRICMS varchar(1000);
declare variable WBDCOMPHIST_VLRICMSST varchar(1000);
declare variable WBDCOMPHIST_VLRIPI varchar(1000);
declare variable WBDCOMPHIST_VLR_FCP_UF_DEST varchar(1000);
declare variable WBDCOMPHIST_VLRICMS_UF_DEST varchar(1000);
declare variable WBDCOMPHIST_VLRICMS_UF_REM varchar(1000);
declare variable WBDCOMPHIST_VLRICMSFCPST varchar(1000);
declare variable WBDCOMPHIST_VLRICMSCONC varchar(1000);
declare variable WBDCOMPHIST_VLRFCP varchar(1000);
declare variable WRESULTCOMPHIST_VLRICMS varchar(1000);
declare variable WRESULTCOMPHIST_VLRICMSST varchar(1000);
declare variable WRESULTCOMPHIST_VLRIPI varchar(1000);
declare variable WRESULTCOMPHIST_VLR_FCP_UF_DEST varchar(1000);
declare variable WRESULTCOMPHIST_VLRICMS_UF_DEST varchar(1000);
declare variable WRESULTCOMPHIST_VLRICMS_UF_REM varchar(1000);
declare variable WRESULTCOMPHIST_VLRICMSFCPST varchar(1000);
declare variable WRESULTCOMPHIST_VLRICMSCONC varchar(1000);
declare variable WRESULTCOMPHIST_VLRFCP varchar(1000);
declare variable WORDEM integer;
begin
  EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERE_COMPLEMENTO_HIST_CP_INICIOU','');
  --Fabiano 10-06-2024 aqui na saida sem RAT eu fiz de uma forma diferente que eh mais rapida
  if ((POSITION('SAI', :PRTIPOLAN) > 0) and (:prTableRat = '')) THEN
  begin
    for select
    rdb$db_key,
    bdcodemp,
    bdchave,
    bdCODNAT,
    BDOBSERVACAO,

    BDCOMPHIST_VLRPIS,
    BDCOMPHIST_VLRCONTAB,
    BDCOMPHIST_VLRCOFINS,
    BDCOMPHIST_VLRPISRET,
    BDCOMPHIST_VLRCOFRET,
    BDCOMPHIST_VLRCSRET,
    BDCOMPHIST_VLRIRRET,
    BDCOMPHIST_VLRINSSRET,
    BDCOMPHIST_VLRDESCONTO,
    BDCOMPHIST_VLRISSRET,
    BDCOMPHIST_VLRINSSAPOS15,
    BDCOMPHIST_VLRINSSAPOS20,
    BDCOMPHIST_VLRINSSAPOS25,
    BDCOMPHIST_VLRDIFALIQ,
    BDCOMPHIST_VLRICMS,
    BDCOMPHIST_VLRICMSST,
    BDCOMPHIST_VLRIPI,
    BDCOMPHIST_VLR_FCP_UF_DEST,
    BDCOMPHIST_VLRICMS_UF_DEST,
    BDCOMPHIST_VLRICMS_UF_REM,
    BDCOMPHIST_VLRICMSFCPST,
    BDCOMPHIST_VLRICMSCONC,
    BDCOMPHIST_VLRFCP,
    BDORDEM

    from TMP_VEF_EMP_TMOVSAIITENS_TEMP where bdsessao = :prSESSAO into
    :wKey, :wCODEMP, :wCHAVE, :WBDCODNAT, :WBDOBSERVACAO,

    :wBDCOMPHIST_VLRPIS,
    :wBDCOMPHIST_VLRCONTAB,
    :wBDCOMPHIST_VLRCOFINS,
    :wBDCOMPHIST_VLRPISRET,
    :wBDCOMPHIST_VLRCOFRET,
    :wBDCOMPHIST_VLRCSRET,
    :wBDCOMPHIST_VLRIRRET,
    :wBDCOMPHIST_VLRINSSRET,
    :wBDCOMPHIST_VLRDESCONTO,
    :wBDCOMPHIST_VLRISSRET,
    :wBDCOMPHIST_VLRINSSAPOS15,
    :wBDCOMPHIST_VLRINSSAPOS20,
    :wBDCOMPHIST_VLRINSSAPOS25,
    :wBDCOMPHIST_VLRDIFALIQ,
    :wBDCOMPHIST_VLRICMS,
    :wBDCOMPHIST_VLRICMSST,
    :wBDCOMPHIST_VLRIPI,
    :wBDCOMPHIST_VLR_FCP_UF_DEST,
    :wBDCOMPHIST_VLRICMS_UF_DEST,
    :wBDCOMPHIST_VLRICMS_UF_REM,
    :wBDCOMPHIST_VLRICMSFCPST,
    :wBDCOMPHIST_VLRICMSCONC,
    :wBDCOMPHIST_VLRFCP,
    :wORDEM

    do
    begin
      wAJUSTA = 0;
      WRESULTCOMPHIST_VLRPIS = WBDCOMPHIST_VLRPIS;
      WRESULTCOMPHIST_VLRCONTAB = WBDCOMPHIST_VLRCONTAB;
      WRESULTCOMPHIST_VLRCOFINS = WBDCOMPHIST_VLRCOFINS;
      WRESULTCOMPHIST_VLRPISRET = WBDCOMPHIST_VLRPISRET;
      WRESULTCOMPHIST_VLRCOFRET = WBDCOMPHIST_VLRCOFRET;
      WRESULTCOMPHIST_VLRCSRET = WBDCOMPHIST_VLRCSRET;
      WRESULTCOMPHIST_VLRIRRET = WBDCOMPHIST_VLRIRRET;
      WRESULTCOMPHIST_VLRINSSRET = WBDCOMPHIST_VLRINSSRET;
      WRESULTCOMPHIST_VLRDESCONTO = WBDCOMPHIST_VLRDESCONTO;
      WRESULTCOMPHIST_VLRISSRET = WBDCOMPHIST_VLRISSRET;
      WRESULTCOMPHIST_VLRINSSAPOS15 = WBDCOMPHIST_VLRINSSAPOS15;
      WRESULTCOMPHIST_VLRINSSAPOS20 = WBDCOMPHIST_VLRINSSAPOS20;
      WRESULTCOMPHIST_VLRINSSAPOS25 = WBDCOMPHIST_VLRINSSAPOS25;
      WRESULTCOMPHIST_VLRDIFALIQ = WBDCOMPHIST_VLRDIFALIQ;
      WRESULTCOMPHIST_VLRICMS = WBDCOMPHIST_VLRICMS;
      WRESULTCOMPHIST_VLRICMSST = WBDCOMPHIST_VLRICMSST;
      WRESULTCOMPHIST_VLRIPI = WBDCOMPHIST_VLRIPI;
      WRESULTCOMPHIST_VLR_FCP_UF_DEST = WBDCOMPHIST_VLR_FCP_UF_DEST;
      WRESULTCOMPHIST_VLRICMS_UF_DEST = WBDCOMPHIST_VLRICMS_UF_DEST;
      WRESULTCOMPHIST_VLRICMS_UF_REM = WBDCOMPHIST_VLRICMS_UF_REM;
      WRESULTCOMPHIST_VLRICMSFCPST = WBDCOMPHIST_VLRICMSFCPST;
      WRESULTCOMPHIST_VLRICMSCONC = WBDCOMPHIST_VLRICMSCONC;
      WRESULTCOMPHIST_VLRFCP = WBDCOMPHIST_VLRFCP;
      if (POSITION('*', wBDCOMPHIST_VLRCONTAB) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wBDCOMPHIST_VLRCONTAB, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO, :WORDEM) into :WRESULTCOMPHIST_VLRCONTAB;
      end

      if (POSITION('*', wBDCOMPHIST_VLRPIS) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wBDCOMPHIST_VLRPIS, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wRESULTCOMPHIST_VLRPIS;
      end

      if (POSITION('*', wBDCOMPHIST_VLRCOFINS) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wBDCOMPHIST_VLRCOFINS, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wRESULTCOMPHIST_VLRCOFINS;
      end

      if (POSITION('*', wBDCOMPHIST_VLRPISRET) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wBDCOMPHIST_VLRPISRET, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wRESULTCOMPHIST_VLRPISRET;
      end

      if (POSITION('*', wBDCOMPHIST_VLRCOFRET) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wBDCOMPHIST_VLRCOFRET, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wRESULTCOMPHIST_VLRCOFRET;
      end

      if (POSITION('*', wBDCOMPHIST_VLRCSRET) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wBDCOMPHIST_VLRCSRET, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wRESULTCOMPHIST_VLRCSRET;
      end

      if (POSITION('*', wBDCOMPHIST_VLRIRRET) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wBDCOMPHIST_VLRIRRET, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wRESULTCOMPHIST_VLRIRRET;
      end

      if (POSITION('*', wBDCOMPHIST_VLRINSSRET) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wBDCOMPHIST_VLRINSSRET, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wRESULTCOMPHIST_VLRINSSRET;
      end

      if (POSITION('*', wBDCOMPHIST_VLRDESCONTO) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wBDCOMPHIST_VLRDESCONTO, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wRESULTCOMPHIST_VLRDESCONTO;
      end

      if (POSITION('*', wBDCOMPHIST_VLRISSRET) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wBDCOMPHIST_VLRISSRET, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wRESULTCOMPHIST_VLRISSRET;
      end

      if (POSITION('*', wBDCOMPHIST_VLRINSSAPOS15) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wBDCOMPHIST_VLRINSSAPOS15, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wRESULTCOMPHIST_VLRINSSAPOS15;
      end

      if (POSITION('*', wBDCOMPHIST_VLRINSSAPOS20) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wBDCOMPHIST_VLRINSSAPOS20, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wRESULTCOMPHIST_VLRINSSAPOS20;
      end

      if (POSITION('*', wBDCOMPHIST_VLRINSSAPOS25) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wBDCOMPHIST_VLRINSSAPOS25, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wRESULTCOMPHIST_VLRINSSAPOS25;
      end

      if (POSITION('*', wbdCOMPHIST_VLRDIFALIQ) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wbdCOMPHIST_VLRDIFALIQ, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wRESULTCOMPHIST_VLRDIFALIQ;
      end

      if (POSITION('*', wbdCOMPHIST_VLRICMS) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wbdCOMPHIST_VLRICMS, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wRESULTCOMPHIST_VLRICMS;
      end

      if (POSITION('*', wbdCOMPHIST_VLRICMSST) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wbdCOMPHIST_VLRICMSST, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wResultCOMPHIST_VLRICMSST;
      end

      if (POSITION('*', wbdCOMPHIST_VLRIPI) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wbdCOMPHIST_VLRIPI, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wResultCOMPHIST_VLRIPI;
      end

      if (POSITION('*', wbdCOMPHIST_VLR_FCP_UF_DEST) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wbdCOMPHIST_VLR_FCP_UF_DEST, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wResultCOMPHIST_VLR_FCP_UF_DEST;
      end

      if (POSITION('*', wbdCOMPHIST_VLRICMS_UF_DEST) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wbdCOMPHIST_VLRICMS_UF_DEST, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wResultCOMPHIST_VLRICMS_UF_DEST;
      end

      if (POSITION('*', wbdCOMPHIST_VLRICMS_UF_REM) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wbdCOMPHIST_VLRICMS_UF_REM, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wResultCOMPHIST_VLRICMS_UF_REM;
      end

      if (POSITION('*', wbdCOMPHIST_VLRICMSFCPST) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wbdCOMPHIST_VLRICMSFCPST, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wResultCOMPHIST_VLRICMSFCPST;
      end

      if (POSITION('*', wbdCOMPHIST_VLRICMSCONC) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wbdCOMPHIST_VLRICMSCONC, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wResultCOMPHIST_VLRICMSCONC;
      end

      if (POSITION('*', wBDCOMPHIST_VLRFCP) > 0) then
      begin
        wAjusta = 1;
        select BDRESULT from SP_GET_COMPLEMENTO(:prSESSAO, :wCODEMP, :wCHAVE, :wBDCOMPHIST_VLRFCP, :WBDCODNAT, :prTIPOLAN, :WBDOBSERVACAO) into :wResultCOMPHIST_VLRFCP;
      end

      if (wAjusta = 1) then
      begin
        update TMP_VEF_EMP_TMOVSAIITENS_TEMP set
        BDCOMPHIST_VLRCONTAB=:WRESULTCOMPHIST_VLRCONTAB,
        BDCOMPHIST_VLRPIS=:wRESULTCOMPHIST_VLRPIS,
        BDCOMPHIST_VLRCOFINS=:wRESULTCOMPHIST_VLRCOFINS,
        BDCOMPHIST_VLRPISRET=:wRESULTCOMPHIST_VLRPISRET,
        BDCOMPHIST_VLRCOFRET=:wRESULTCOMPHIST_VLRCOFRET,
        BDCOMPHIST_VLRCSRET=:wRESULTCOMPHIST_VLRCSRET,
        BDCOMPHIST_VLRIRRET=:wRESULTCOMPHIST_VLRIRRET,
        BDCOMPHIST_VLRINSSRET=:wRESULTCOMPHIST_VLRINSSRET,
        BDCOMPHIST_VLRDESCONTO=:wRESULTCOMPHIST_VLRDESCONTO,
        BDCOMPHIST_VLRISSRET=:wRESULTCOMPHIST_VLRISSRET,
        BDCOMPHIST_VLRINSSAPOS15=:wRESULTCOMPHIST_VLRINSSAPOS15,
        BDCOMPHIST_VLRINSSAPOS20=:wRESULTCOMPHIST_VLRINSSAPOS20,
        BDCOMPHIST_VLRINSSAPOS25=:wRESULTCOMPHIST_VLRINSSAPOS25,
        bdCOMPHIST_VLRDIFALIQ=:wRESULTCOMPHIST_VLRDIFALIQ,
        bdCOMPHIST_VLRICMS=:wRESULTCOMPHIST_VLRICMS,
        bdCOMPHIST_VLRICMSST=:wRESULTCOMPHIST_VLRICMSST,
        bdCOMPHIST_VLRIPI=:wRESULTCOMPHIST_VLRIPI,
        bdCOMPHIST_VLR_FCP_UF_DEST=:wRESULTCOMPHIST_VLR_FCP_UF_DEST,
        bdCOMPHIST_VLRICMS_UF_DEST=:wRESULTCOMPHIST_VLRICMS_UF_DEST,
        bdCOMPHIST_VLRICMS_UF_REM=:wRESULTCOMPHIST_VLRICMS_UF_REM,
        bdCOMPHIST_VLRICMSFCPST=:wRESULTCOMPHIST_VLRICMSFCPST,
        bdCOMPHIST_VLRICMSCONC=:wRESULTCOMPHIST_VLRICMSCONC,
        BDCOMPHIST_VLRFCP=:wRESULTCOMPHIST_VLRFCP
        where rdb$db_key=:wKey;
      end
    end
  end
  else
  begin
    wgetcompl = 'SELECT BDRESULT FROM SP_GET_COMPLEMENTO(I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, ';
    wgetcomplfim= ', I.BDCODNAT, '''||:PRTIPOLAN||''', Coalesce(I.BDOBSERVACAO,'''')))';
    /*Ajusta o complemento de histórico, remove as variáveis*/
    wSQL =          'UPDATE TMP_'||:PRTableItem||'_TEMP I ';
    wSQL = wSQL || 'SET I.BDCOMPHIST_VLRCONTAB = ('||wgetcompl||'I.BDCOMPHIST_VLRCONTAB'||wgetcomplfim;
    wSQL = wSQL || ',I.bdCOMPHIST_VLRPIS       = ('||wgetcompl||'I.bdCOMPHIST_VLRPIS'||wgetcomplfim;

    WWHERE = '';

    IF (POSITION('SER', :PRTIPOLAN) = 0) THEN
    BEGIN
      wSQL = wSQL || ',I.bdCOMPHIST_VLRICMS         = ('||wgetcompl||'I.bdCOMPHIST_VLRICMS'||wgetcomplfim;
      wSQL = wSQL || ',I.bdCOMPHIST_VLRICMSST       = ('||wgetcompl||'I.bdCOMPHIST_VLRICMSST'||wgetcomplfim;
      wSQL = wSQL || ',I.bdCOMPHIST_VLRIPI          = ('||wgetcompl||'I.bdCOMPHIST_VLRIPI'||wgetcomplfim;
      wSQL = wSQL || ',I.bdCOMPHIST_VLR_FCP_UF_DEST = ('||wgetcompl||'I.bdCOMPHIST_VLR_FCP_UF_DEST'||wgetcomplfim;
      wSQL = wSQL || ',I.bdCOMPHIST_VLRICMS_UF_DEST = ('||wgetcompl||'I.bdCOMPHIST_VLRICMS_UF_DEST'||wgetcomplfim;
      wSQL = wSQL || ',I.bdCOMPHIST_VLRICMS_UF_REM  = ('||wgetcompl||'I.bdCOMPHIST_VLRICMS_UF_REM'||wgetcomplfim;
      wSQL = wSQL || ',I.bdCOMPHIST_VLRICMSFCPST    = ('||wgetcompl||'I.bdCOMPHIST_VLRICMSFCPST'||wgetcomplfim;
      wSQL = wSQL || ',I.bdCOMPHIST_VLRICMSCONC     = (' ||wgetcompl||'I.bdCOMPHIST_VLRICMSCONC'||wgetcomplfim;
      wSQL = wSQL || ',I.BDCOMPHIST_VLRFCP          = ('||wgetcompl||'I.BDCOMPHIST_VLRFCP'||wgetcomplfim;
      WWHERE = '(COALESCE(I.bdCOMPHIST_VLRICMS,'''') <> '''') OR '||
               '(COALESCE(I.bdCOMPHIST_VLRICMSST,'''') <> '''') OR '||
               '(COALESCE(I.bdCOMPHIST_VLRIPI,'''') <> '''') OR '||
               '(COALESCE(I.bdCOMPHIST_VLRICMSCONC,'''') <> '''') OR '||
               '(COALESCE(I.BDCOMPHIST_VLRFCP,'''') <> '''') OR '||
               '(COALESCE(I.bdCOMPHIST_VLR_FCP_UF_DEST,'''') <> '''') OR '||
               '(COALESCE(I.bdCOMPHIST_VLRICMS_UF_DEST,'''') <> '''') OR '||
               '(COALESCE(I.bdCOMPHIST_VLRICMS_UF_REM,'''') <> '''') OR '||
               '(COALESCE(I.bdCOMPHIST_VLRICMSFCPST,'''') <> '''')';
    END

    wSQL = wSQL || ',I.BDCOMPHIST_VLRCOFINS= ('||wgetcompl||'I.bdCOMPHIST_VLRCOFINS'||wgetcomplfim;
    wSQL = wSQL || ',I.BDCOMPHIST_VLRPISRET= ('||wgetcompl||'I.bdCOMPHIST_VLRPISRET'||wgetcomplfim;
    wSQL = wSQL || ',I.BDCOMPHIST_VLRCOFRET= ('||wgetcompl||'I.bdCOMPHIST_VLRCOFRET'||wgetcomplfim;
    wSQL = wSQL || ',I.BDCOMPHIST_VLRCSRET = ('||wgetcompl||'I.bdCOMPHIST_VLRCSRET'||wgetcomplfim;
    wSQL = wSQL || ',I.BDCOMPHIST_VLRIRRET = ('||wgetcompl||'I.bdCOMPHIST_VLRIRRET'||wgetcomplfim;
    wSQL = wSQL || ',I.BDCOMPHIST_VLRINSSRET   = ('||wgetcompl||'I.bdCOMPHIST_VLRINSSRET'||wgetcomplfim;
    wSQL = wSQL || ',I.BDCOMPHIST_VLRDESCONTO  = ('||wgetcompl||'I.bdCOMPHIST_VLRDESCONTO'||wgetcomplfim;
    wSQL = wSQL || ',I.BDCOMPHIST_VLRISSRET    = ('||wgetcompl||'I.bdCOMPHIST_VLRISSRET'||wgetcomplfim;
    wSQL = wSQL || ',I.BDCOMPHIST_VLRINSSAPOS15= ('||wgetcompl||'I.BDCOMPHIST_VLRINSSAPOS15'||wgetcomplfim;
    wSQL = wSQL || ',I.BDCOMPHIST_VLRINSSAPOS20= ('||wgetcompl||'I.BDCOMPHIST_VLRINSSAPOS20'||wgetcomplfim;
    wSQL = wSQL || ',I.BDCOMPHIST_VLRINSSAPOS25= ('||wgetcompl||'I.BDCOMPHIST_VLRINSSAPOS25'||wgetcomplfim;

    if (WWHERE <> '') then
      WWHERE = WWHERE ||' OR ';
    WWHERE = WWHERE||'(COALESCE(I.BDCOMPHIST_VLRCOFINS,'''') <> '''') OR '||
                  '(COALESCE(I.BDCOMPHIST_VLRPISRET,'''') <> '''') OR '||
                  '(COALESCE(I.BDCOMPHIST_VLRCOFRET,'''') <> '''') OR '||
                  '(COALESCE(I.BDCOMPHIST_VLRCSRET,'''') <> '''') OR '||
                  '(COALESCE(I.BDCOMPHIST_VLRIRRET,'''') <> '''') OR '||
                  '(COALESCE(I.BDCOMPHIST_VLRINSSRET,'''') <> '''') OR '||
                  '(COALESCE(I.BDCOMPHIST_VLRDESCONTO,'''') <> '''') OR '||
                  '(COALESCE(I.BDCOMPHIST_VLRISSRET,'''') <> '''') OR '||
                  '(COALESCE(I.BDCOMPHIST_VLRINSSAPOS15,'''') <> '''') OR '||
                  '(COALESCE(I.BDCOMPHIST_VLRINSSAPOS20,'''') <> '''') OR '||
                  '(COALESCE(I.BDCOMPHIST_VLRINSSAPOS25,'''') <> '''')  ';

    IF ((:PRTIPOLAN = 'ENT') OR (:PRTIPOLAN = 'SAI')) THEN
    BEGIN
      wSQL = wSQL || ', I.bdCOMPHIST_VLRDIFALIQ= ('||wgetcompl||'I.bdCOMPHIST_VLRDIFALIQ'||wgetcomplfim;
      WWHERE = WWHERE||' OR (COALESCE(I.bdCOMPHIST_VLRDIFALIQ,'''') <> '''')';
    END

    IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wSQL = wSQL || ', I.BDCOMPHIST_VLRICMSESTORNADO= ('||wgetcompl||'I.BDCOMPHIST_VLRICMSESTORNADO'||wgetcomplfim;
      wSQL = wSQL || ', I.BDCOMPHIST_VLRANTECIPACAO  = ('||wgetcompl||'I.BDCOMPHIST_VLRANTECIPACAO'||wgetcomplfim;
      WWHERE = WWHERE||' OR (COALESCE(I.BDCOMPHIST_VLRICMSESTORNADO,'''') <> '''')';
      WWHERE = WWHERE||' OR (COALESCE(I.BDCOMPHIST_VLRANTECIPACAO,'''') <> '''')';
    END

    wSQL = wSQL || 'WHERE (I.BDSESSAO = '||:PRSESSAO||') ';
    IF (POSITION('SER', :PRTIPOLAN)> 0) THEN
    BEGIN
      wSQL = wSQL || ' AND (EXISTS (';
      wSQL = wSQL ||              'SELECT MOV.BDCHAVE ';
      wSQL = wSQL ||              'FROM TMP_'||:PRTable||'_TEMP MOV ';
      wSQL = wSQL ||              'WHERE MOV.BDSESSAO = I.BDSESSAO ';
      wSQL = wSQL ||              'AND MOV.BDCODEMP = I.BDCODEMP ';
      wSQL = wSQL ||              'AND MOV.BDCHAVE = I.BDCHAVE ';
      wSQL = wSQL ||              'AND MOV.BDTIPLAN = '||IIF(:PRTIPOLAN = 'SERE', '0', '1');
      wSQL = wSQL ||             ')) ';
    END

    WWHERE = WWHERE||' OR (COALESCE(I.BDCOMPHIST_VLRCONTAB,'''') <> '''')';
    WWHERE = WWHERE||' OR (COALESCE(I.bdCOMPHIST_VLRPIS,'''') <> '''')';

    WSQL = WSQL || ' and ('||WWHERE||')';

    /*Se tiver registro na tabela de rateio não deve contabilizar o item, contabiliza só o rateio*/
    IF (:prTableRat <> '') THEN
    BEGIN
      wSQL = wSQL || ' AND (NOT EXISTS ( SELECT RAT.BDSESSAO FROM TMP_'||:PRTableRat||'_TEMP RAT WHERE RAT.BDSESSAO = I.BDSESSAO AND RAT.BDCODEMP = I.BDCODEMP AND RAT.BDCHAVE  = I.BDCHAVE AND RAT.BDORDEM  = I.BDORDEM))';
    END

    EXECUTE STATEMENT wSQL;
  end

  EXECUTE PROCEDURE SP_GERALOG_TEMP('SP_INSERE_COMPLEMENTO_HIST_CP_FINALIZOU','');
END^

CREATE OR ALTER PROCEDURE SP_GET_INSERT (
    PRTABLE VARCHAR(50) NOT NULL,
    PRAPELIDO VARCHAR(10),
    PRUPDATEORINSERT DM_BOOLEAN = 'FALSE')
RETURNS (
    BDINSERT VARCHAR(10000))
AS
DECLARE VARIABLE WFIELDS VARCHAR(10000);
DECLARE VARIABLE WFIELDSSTR VARCHAR(10000);
DECLARE VARIABLE WFIELD VARCHAR(64);
DECLARE VARIABLE WFIELDSPK VARCHAR(500);
DECLARE VARIABLE WTYPECOLUMN INTEGER;
BEGIN
  IF (:PRUPDATEORINSERT = 'TRUE') THEN
    BDINSERT    = '''UPDATE OR INSERT INTO '||:PRTable||'(';
  ELSE
    BDINSERT    = '''INSERT INTO '||:PRTable||'(';

  wField      = '';
  wFields     = '';
  wFieldsStr  = '';
  wTypeColumn = 0;
  PRAPELIDO   = COALESCE(:PRAPELIDO, '');

  FOR SELECT TRIM(RF.RDB$FIELD_NAME), F.RDB$FIELD_TYPE
      FROM RDB$RELATION_FIELDS RF
      JOIN RDB$FIELDS F ON(F.RDB$FIELD_NAME = RF.RDB$FIELD_SOURCE)
      WHERE RDB$RELATION_NAME = :PRTABLE
      INTO :wField, :wTypeColumn
  DO
    BEGIN
      wFields = wFields || :wField || ', ';

      wField = :PRAPELIDO || :wField;

      /*7, 8, 9, 10, 16, 27 são campos numérios*/
      IF (:wTypeColumn NOT IN(7, 8, 9, 10, 16, 27)) THEN
        wFieldsStr = :wFieldsStr || '''!@|''||'||'IIF('||:wField||' IS NULL, ''NULL'', '||:wField||')'||'||''!@|''';
      ELSE
        wFieldsStr = :wFieldsStr ||'IIF('||:wField||' IS NULL, ''NULL'', '||:wField||')';

      wFieldsStr = :wFieldsStr || '|| '', '' ||';
    END

  wFields    = (SUBSTRING(:wFields FROM 1 FOR CHAR_LENGTH(:wFields)-2));
  wFieldsStr = (SUBSTRING(:wFieldsStr FROM 1 FOR CHAR_LENGTH(:wFieldsStr)-10));

  BDINSERT = :BDINSERT || :wFields || ') VALUES ('' || ' || :wFieldsStr ||' || '')'' || ''';

  IF (:PRUPDATEORINSERT = 'TRUE') THEN
    BEGIN
      SELECT LIST(TRIM(sg.rdb$field_name), ', ') BDFIELDSPK
      FROM rdb$indices ix
      LEFT JOIN rdb$index_segments sg ON ix.rdb$index_name = sg.rdb$index_name
      LEFT JOIN rdb$relation_constraints rc ON rc.rdb$index_name = ix.rdb$index_name
      WHERE rc.RDB$RELATION_NAME = :PRTABLE
      AND rc.rdb$constraint_type = 'PRIMARY KEY'
      GROUP BY rc.RDB$RELATION_NAME
      INTO :wFieldsPK;

      BDINSERT = :BDINSERT || ' MATCHING('||:wFieldsPK||');''';
    END
  ELSE
    BDINSERT = :BDINSERT || ';''';

  SUSPEND;
END^

CREATE OR ALTER procedure SP_EXPORTA_SCRIPT_CONTAB (
    PRCODEMP integer not null,
    PRDATAINI date not null,
    PRDATAFIM date not null,
    PRFILE varchar(260),
    PRTIPOLAN char(4))
as
declare variable WTABLE varchar(50);
declare variable WCOMMAND varchar(10000);
declare variable WSQL varchar(10000);
BEGIN
  DELETE FROM TCONTEXTO_DB;
  DELETE FROM TMP_TCHAVE_CONTABILIZACAO;
  DELETE FROM TMP_DEPENDENCIA_CONTEXTO;

  wSQL =         'INSERT INTO TMP_TCHAVE_CONTABILIZACAO(BDCODEMP, BDCHAVE, BDORDEM) ';
  wSQL = :wSQL ||'SELECT MOV.BDCODEMP, MOV.BDCHAVE, '||IIF(:PRTIPOLAN = 'REDZ', 'I.BDORDEMVARCFOP', 'I.BDORDEM')||' FROM ';
  wSQL = :wSQL ||IIF(:PRTIPOLAN = 'REDZ', 'VEF_EMP_TREDZ', 'VEF_EMP_TMOV'||:PRTIPOLAN) || ' MOV ';

  --wSQL = :wSQL ||'JOIN '||IIF(:PRTIPOLAN = 'REDZ', 'TOL_VEF_EMP_TREDZVARCFOP', 'TOL_VEF_EMP_TMOV'||:PRTIPOLAN)||' TOL ON(TOL.BDCODEMP = MOV.BDCODEMP AND TOL.'||IIF(:PRTIPOLAN = 'REDZ', 'BDCHAVECFOP', 'BDCHAVE'||:PRTIPOLAN)||' = MOV.BDCHAVE) ';
  wSQL = :wSQL ||'JOIN '||IIF(:PRTIPOLAN = 'REDZ', 'VEF_EMP_TREDZVARCFOP', 'VEF_EMP_TMOV'||TRIM(:PRTIPOLAN)||'ITENS')||' I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)';
  wSQL = :wSQL ||'WHERE MOV.BDCODEMP = '||:PRCODEMP||' AND ';

  IF (:PRTIPOLAN = 'ENT') THEN
    wSQL = :wSQL ||'MOV.BDDATAENTRADAENT '; --Entrada
  ELSE
  IF (:PRTIPOLAN = 'REDZ') THEN
    wSQL = :wSQL ||'MOV.BDDATAREDZ '; --Redução Z
  ELSE
    wSQL = :wSQL ||'MOV.BDDATAEMISSAO '; --Saída e Serviço

  wSQL = :wSQL ||'BETWEEN '||''''||:PRDATAINI||''''||' AND '||''''||:PRDATAFIM||'''';

  EXECUTE STATEMENT :wSQL;

  /*Tabelas que vão exportar*/
  INSERT INTO TMP_DEPENDENCIA_CONTEXTO(BDORD, BDTABLENAME,BDCODEMP) VALUES(1, 'VSUC_EMPRESAS_TVINCTRANSACAO',:PRCODEMP);
  INSERT INTO TMP_DEPENDENCIA_CONTEXTO(BDORD, BDTABLENAME,BDCODEMP) VALUES(2, 'VSUC_EMPRESAS_TLAN',:PRCODEMP);
  INSERT INTO TMP_DEPENDENCIA_CONTEXTO(BDORD, BDTABLENAME,BDCODEMP) VALUES(3, 'VSUC_EMPRESAS_TLCC',:PRCODEMP);

  IF (:PRTIPOLAN <> 'REDZ') THEN
    BEGIN
      INSERT INTO TMP_DEPENDENCIA_CONTEXTO(BDORD, BDTABLENAME,BDCODEMP) VALUES(4, 'TOL_VEF_EMP_TMOV'||:PRTIPOLAN,:PRCODEMP);
      INSERT INTO TMP_DEPENDENCIA_CONTEXTO(BDORD, BDTABLENAME,BDCODEMP) VALUES(5, 'TOL_VEF_EMP_TMOVRAT'||:PRTIPOLAN,:PRCODEMP);
    END
  ELSE
    INSERT INTO TMP_DEPENDENCIA_CONTEXTO(BDORD, BDTABLENAME,BDCODEMP) VALUES(4, 'TOL_VEF_EMP_TREDZVARCFOP',:PRCODEMP);

  INSERT INTO TMP_DEPENDENCIA_CONTEXTO(BDORD, BDTABLENAME,BDCODEMP) VALUES(6, 'TOL_UPDATE_CONTA',:PRCODEMP);

  wSQL =          'DELETE FROM '||IIF(:PRTIPOLAN = 'REDZ', 'TOL_VEF_EMP_TREDZVARCFOP', 'TOL_VEF_EMP_TMOV'||:PRTIPOLAN)||' TOL ';
  wSQL = :wSQL || 'WHERE EXISTS ( ';
  wSQL = :wSQL || '              SELECT M.BDCODEMP, M.BDCHAVE ';
  wSQL = :wSQL || '              FROM '||IIF(:PRTIPOLAN = 'REDZ', 'VEF_EMP_TREDZ', 'VEF_EMP_TMOV'||:PRTIPOLAN)||' M ';
  wSQL = :wSQL || '              WHERE M.BDCODEMP = '||:PRCODEMP;
  wSQL = :wSQL || '              AND ';
  IF (:PRTIPOLAN = 'ENT') THEN
    wSQL = :wSQL ||'M.BDDATAENTRADAENT '; --Entrada
  ELSE
  IF (:PRTIPOLAN = 'REDZ') THEN
    wSQL = :wSQL ||'M.BDDATAREDZ '; --Redução Z
  ELSE
    wSQL = :wSQL ||'M.BDDATAEMISSAO '; --Saída e Serviço

  wSQL = :wSQL || '              BETWEEN '||'!@|'||:PRDATAINI||'!@|'||' AND '||'!@|'||:PRDATAFIM||'!@|';
  wSQL = :wSQL || '              AND M.BDCODEMP = TOL.BDCODEMP ';
  wSQL = :wSQL || '              AND M.BDCHAVE = TOL.'||IIF(:PRTIPOLAN = 'REDZ', 'BDCHAVECFOP', 'BDCHAVE'||:PRTIPOLAN);
  wSQL = :wSQL || '             ); ';

  INSERT INTO TCONTEXTO_DB(BDLINE,BDCODEMP) VALUES (:wSQL, :PRCODEMP);

  FOR SELECT DEP.BDTABLENAME
      FROM TMP_DEPENDENCIA_CONTEXTO DEP
      WHERE DEP.BDCODEMP = :PRCODEMP
      ORDER BY BDORD
      INTO :wTable
  DO
    BEGIN
      IF (:wTable = 'VSUC_EMPRESAS_TVINCTRANSACAO') THEN
        SELECT BDINSERT FROM SP_GET_INSERT(:wTable, 'M.', 'TRUE') INTO :wCommand;
      ELSE
        SELECT BDINSERT FROM SP_GET_INSERT(:wTable, 'M.') INTO :wCommand;

      wSQL =          'INSERT INTO TCONTEXTO_DB(BDCODEMP,BDLINE) ';
      wSQL = :wSQL || 'SELECT '||:PRCODEMP||','|| :wCommand ||' FROM '||:wTable || ' M ';

      IF (:wTable = 'VSUC_EMPRESAS_TLAN') THEN
        BEGIN
          wSQL = :wSQL || 'JOIN '||IIF(:PRTIPOLAN = 'REDZ', 'TOL_VEF_EMP_TREDZVARCFOP', 'TOL_VEF_EMP_TMOV'||:PRTIPOLAN)||' TOL ON(TOL.BDCODEMP = M.BDCODEMP AND TOL.BDCHAVE = M.BDCHAVE) ';
          wSQL = :wSQL || 'JOIN TMP_TCHAVE_CONTABILIZACAO C ON(C.BDCODEMP = TOL.BDCODEMP AND C.BDCHAVE = TOL.'||IIF(:PRTIPOLAN = 'REDZ', 'BDCHAVECFOP and c.bdordem = tol.BDORDEMVARCFOP', 'BDCHAVE'||:PRTIPOLAN||'  and c.bdordem = tol.BDORDEM')||') ';
        END
      ELSE
      IF (:wTable = 'VSUC_EMPRESAS_TLCC') THEN
        BEGIN
          wSQL = :wSQL || 'JOIN VSUC_EMPRESAS_TLAN VSUC ON(VSUC.BDCODEMP = M.BDCODEMP AND VSUC.BDCHAVE = M.BDCHAVE) ';
          wSQL = :wSQL || 'JOIN '||IIF(:PRTIPOLAN = 'REDZ', 'TOL_VEF_EMP_TREDZVARCFOP', 'TOL_VEF_EMP_TMOV'||:PRTIPOLAN)||' TOL ON(TOL.BDCODEMP = M.BDCODEMP AND TOL.BDCHAVE = M.BDCHAVE) ';
          wSQL = :wSQL || 'JOIN TMP_TCHAVE_CONTABILIZACAO C ON(C.BDCODEMP = TOL.BDCODEMP AND C.BDCHAVE = TOL.'||IIF(:PRTIPOLAN = 'REDZ', 'BDCHAVECFOP and c.bdordem = tol.BDORDEMVARCFOP', 'BDCHAVE'||:PRTIPOLAN||'  and c.bdordem = tol.BDORDEM')||') ';
        END
      IF ((:wTable = 'TOL_VEF_EMP_TMOV'||:PRTIPOLAN) OR (:wTable = 'TOL_VEF_EMP_TREDZVARCFOP')) THEN
        wSQL = :wSQL || 'JOIN TMP_TCHAVE_CONTABILIZACAO C ON(C.BDCODEMP = M.BDCODEMP AND C.BDCHAVE = M.'||IIF(:PRTIPOLAN = 'REDZ', 'BDCHAVECFOP and c.bdordem = m.BDORDEMVARCFOP', 'BDCHAVE'||:PRTIPOLAN||' and c.bdordem = m.BDORDEM')||' ) ';
      ELSE
      IF (:wTable = 'TOL_VEF_EMP_TMOVRAT'||:PRTIPOLAN) THEN
        wSQL = :wSQL || 'JOIN TMP_TCHAVE_CONTABILIZACAO C ON(C.BDCODEMP = M.BDCODEMP AND C.BDCHAVE = M.BDCHAVELAN and c.bdordem = m.bdordem) ';
      ELSE
      IF (:wTable = 'TOL_UPDATE_CONTA') THEN
        BEGIN
          wSQL = :wSQL || 'JOIN VSUC_EMPRESAS_TLAN VSUC ON(VSUC.BDCODEMP = M.BDCODEMP AND VSUC.BDCHAVE = M.BDCHAVELAN) ';
          wSQL = :wSQL || 'JOIN '||IIF(:PRTIPOLAN = 'REDZ', 'TOL_VEF_EMP_TREDZVARCFOP', 'TOL_VEF_EMP_TMOV'||:PRTIPOLAN)||' TOL ON(TOL.BDCODEMP = VSUC.BDCODEMP AND TOL.BDCHAVE = VSUC.BDCHAVE) ';
          wSQL = :wSQL || 'JOIN TMP_TCHAVE_CONTABILIZACAO C ON(C.BDCODEMP = TOL.BDCODEMP AND C.BDCHAVE = TOL.'||IIF(:PRTIPOLAN = 'REDZ', 'BDCHAVECFOP and c.bdordem = tol.BDORDEMVARCFOP', 'BDCHAVE'||:PRTIPOLAN||'  and c.bdordem = tol.BDORDEM')||') ';
        END
      ELSE
      IF (:wTable = 'VSUC_EMPRESAS_TVINCTRANSACAO') THEN
        BEGIN
          wSQL = :wSQL || 'JOIN VSUC_EMPRESAS_TLAN VSUC ON(VSUC.BDCHAVEVINC = M.BDCHAVEVINC)';
          wSQL = :wSQL || 'JOIN '||IIF(:PRTIPOLAN = 'REDZ', 'TOL_VEF_EMP_TREDZVARCFOP', 'TOL_VEF_EMP_TMOV'||:PRTIPOLAN)||' TOL ON(TOL.BDCODEMP = VSUC.BDCODEMP AND TOL.BDCHAVE = VSUC.BDCHAVE) ';
          wSQL = :wSQL || 'JOIN TMP_TCHAVE_CONTABILIZACAO C ON(C.BDCODEMP = TOL.BDCODEMP AND C.BDCHAVE = TOL.'||IIF(:PRTIPOLAN = 'REDZ', 'BDCHAVECFOP and c.bdordem = tol.BDORDEMVARCFOP', 'BDCHAVE'||:PRTIPOLAN||'  and c.bdordem = tol.BDORDEM')||') ';
        END

      EXECUTE STATEMENT :wSQL;
    END

  OPENARQ(:PRFILE,:PRCODEMP);

  wCommand = '';
  FOR SELECT BDLINE FROM TCONTEXTO_DB WHERE BDCODEMP = :PRCODEMP INTO :wCommand DO
    BEGIN
      WRITELNOA(:wCommand,:PRCODEMP);
    END

  CLOSEARQ(:PRFILE,:PRCODEMP);

  DELETE FROM TCONTEXTO_DB;
  DELETE FROM TMP_TCHAVE_CONTABILIZACAO;
  DELETE FROM TMP_DEPENDENCIA_CONTEXTO;
END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_CONTABILIZACAO (
    PRCODEMP INTEGER NOT NULL,
    PRDATAINI DATE NOT NULL,
    PRDATAFIM DATE NOT NULL,
    PRENT DM_BOOLEAN,
    PRSAI DM_BOOLEAN,
    PRSER DM_BOOLEAN,
    PRREDZ DM_BOOLEAN,
    PRDIRETORIO VARCHAR(150))
AS
DECLARE VARIABLE WFILE VARCHAR(180);
BEGIN
  wFile = :PRDIRETORIO || 'EMPRESA_' || :PRCODEMP || '.ctz';
  NEWFILE(:wFile);

  IF (:PRENT CONTAINING('TRUE')) THEN
    EXECUTE PROCEDURE SP_EXPORTA_SCRIPT_CONTAB(:PRCODEMP, :PRDATAINI, :PRDATAFIM, :wFile, 'ENT');

  IF (:PRSAI CONTAINING('TRUE')) THEN
    EXECUTE PROCEDURE SP_EXPORTA_SCRIPT_CONTAB(:PRCODEMP, :PRDATAINI, :PRDATAFIM, :wFile, 'SAI');

  IF (:PRSER CONTAINING('TRUE')) THEN
    EXECUTE PROCEDURE SP_EXPORTA_SCRIPT_CONTAB(:PRCODEMP, :PRDATAINI, :PRDATAFIM, :wFile, 'SER');

  IF (:PRREDZ CONTAINING('TRUE')) THEN
    EXECUTE PROCEDURE SP_EXPORTA_SCRIPT_CONTAB(:PRCODEMP, :PRDATAINI, :PRDATAFIM, :wFile, 'REDZ');

END^

CREATE OR ALTER procedure SP_VTPO_JUST_INAT (
    PRDATAINICIAL varchar(10),
    PRDATAFINAL varchar(10),
    PRMOTIVOS varchar(1000),
    PRUSUARIOS varchar(1000),
    PRMODELO integer)
returns (
    BDCODMOTIVO integer,
    BDDESCMOTIVO varchar(255),
    BDCODUSU integer,
    BDNOMUSU varchar(255),
    BDOBSERVACAO blob sub_type 0 segment size 32700,
    BDDATA date,
    BDHORAINICIAL time,
    BDHORAFINAL time,
    BDTEMPO timestamp,
    BDTIPO integer)
as
declare variable WWHERE varchar(4000);
declare variable WCOLUNA integer;
declare variable WSQL varchar(30000);
begin
  wWhere = ' where BDDATA >= '''||prdatainicial||''' and BDDATA <= '''||prdatafinal||'''';
  if  (prmotivos != '') then
      wWhere = wWhere||' and MOT.BDCODMOTIVO in ('||prmotivos||') ';
  if  (prusuarios != '') then
      wWhere = wWhere||' and USU.bdcodusu in ('||prusuarios||') ';

  --Selecao de dados normais
  wSQL = 'select * ';
  wSQL = wSQL||'  from (select  MOT.BDDESCRICAO as BDDESCMOTIVO, ';
  wSQL = wSQL||'              MOT.BDCODMOTIVO, ';
  wSQL = wSQL||'              USU.BDNOMUSU, ';
  wSQL = wSQL||'              USU.bdcodusu, ';
  wSQL = wSQL||'              BDDATA, ';
  wSQL = wSQL||'              BDHORAINICIAL, ';
  wSQL = wSQL||'              BDHORAFINAL, ';
  wSQL = wSQL||'              INA.BDOBSERVACAO, ';
  wSQL = wSQL||'              1 as BDTIPO, ';
  wSQL = wSQL||'             cast((cast(''12/30/1899'' as timestamp) + (cast(datediff(second, BDHORAINICIAL, BDHORAFINAL) as double precision)) / 86400) as timestamp) as BDTEMPO ';
  wSQL = wSQL||'      from VTPO_JUSTIFICATIVA_INATIVIDADE INA ';
  wSQL = wSQL||'      left outer join VTPO_MOTIVO_INATIVIDADE MOT on (MOT.BDCODMOTIVO = INA.BDCODMOTIVO) ';
  wSQL = wSQL||'      left outer join TUSUARIO USU on (USU.BDCODUSU = INA.BDCODUSU) ';
  wSQL = wSQL||wWhere;
  wSQL = wSQL||'      union all ';

  --Selecao de totalizadores
  wSQL = wSQL||'      select * ';
  if (prmodelo = 0) then
    begin
  wSQL = wSQL||'  from (select  '''' as BDDESCMOTIVO, ';
  wSQL = wSQL||'              null as BDCODMOTIVO, ';
  wSQL = wSQL||'              USU.BDNOMUSU as BDNOMUSU, ';
  wSQL = wSQL||'              USU.bdcodusu, ';
    end
  else
    begin     
      wSQL = wSQL||'      from (select  MOT.BDDESCRICAO as BDDESCMOTIVO, ';
      wSQL = wSQL||'                    MOT.BDCODMOTIVO, ';
      wSQL = wSQL||'                    '''' as BDNOMUSU, ';
      wSQL = wSQL||'                    null as bdcodusu, ';
    end
  wSQL = wSQL||'                    null as BDDATA, ';
  wSQL = wSQL||'                    null as BDHORAINICIAL, ';
  wSQL = wSQL||'                    null as BDHORAFINAL, ';
  wSQL = wSQL||'                    null as BDOBSERVACAO,  ';
  wSQL = wSQL||'                    2 as BDTIPO, ';
  wSQL = wSQL||'                   cast(cast(''12/30/1899'' as timestamp) + cast((sum((cast(datediff(second, BDHORAINICIAL, BDHORAFINAL) as double precision)) / 86400)) as double precision) as timestamp) as BDTEMPO ';
  wSQL = wSQL||'            from VTPO_JUSTIFICATIVA_INATIVIDADE INA ';
  wSQL = wSQL||'            left outer join VTPO_MOTIVO_INATIVIDADE MOT on (MOT.BDCODMOTIVO = INA.BDCODMOTIVO) ';
  wSQL = wSQL||'            left outer join TUSUARIO USU on (USU.BDCODUSU = INA.BDCODUSU) ';
  wSQL = wSQL||wWhere;
  if (prmodelo = 0) then
    begin
      wSQL = wSQL||'            group by USU.BDNOMUSU, bdcodusu)) ';
      wSQL = wSQL||'order by bdcodusu, BDTIPO, BDDATA, BDHORAINICIAL; ';
    end
  else
    begin     
      wSQL = wSQL||'            group by MOT.BDDESCRICAO, MOT.BDCODMOTIVO)) ';
      wSQL = wSQL||'order by BDCODMOTIVO, BDTIPO, BDDATA, BDHORAINICIAL; ';
    end

  FOR EXECUTE STATEMENT wsql into :bddescmotivo, :bdcodmotivo, :bdnomusu, :bdcodusu, :bddata, :bdhorainicial, :bdhorafinal, :bdobservacao, :bdtipo, :bdtempo do
  BEGIN
    suspend;
  END
end^

CREATE OR ALTER PROCEDURE DEC_REF (
    PRREF INTEGER,
    PRQTDDEC INTEGER = 1)
RETURNS (
    BDREF INTEGER)
AS
BEGIN
  /*Criada nova sp porque a DEC_REFERENCIA não funciona como deveria.*/

  BDREF = :PRREF;
  WHILE (:PRQTDDEC > 0) DO
    BEGIN
      PRQTDDEC = :PRQTDDEC - 1;

      IF (SUBSTRING(:BDREF FROM 5 FOR 2) = '01') THEN
        BDREF = :BDREF - 89;
      ELSE
        BDREF = :BDREF - 1;
    END

  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_LANCA_FUNRURAL (
    PRSESSAO INTEGER,
    PRTIPOLAN CHAR(3))
AS
DECLARE VARIABLE WSQL VARCHAR(1500);
DECLARE VARIABLE WTABLEFUNRURAL VARCHAR(50);
DECLARE VARIABLE WTABLE VARCHAR(50);
DECLARE VARIABLE WTABLEITEM VARCHAR(50);
DECLARE VARIABLE WTABLEINCO VARCHAR(50);
BEGIN
  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTableFunrural = 'TMP_VEF_TMOVENTFUNRURAL_TEMP';
      wTable         = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItem     = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      wTableInco     = 'VEF_INCON_TMOVENT';
    END

  -- elizeu 21-08-18 - Contabilização Funrural #88823 #Trunk!
  --#92761 Estava bloqueando o plano mesmo quando não havia ações de funrural
  /* IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wSQL =          ' INSERT INTO '||wTableInco||' (bdcodemp, bdchave, bdordem, bdsessao, bdcodinconsistencia, BDTIPOINCON) ';
      wSQL = :wSQL || ' SELECT tm.BDCODEMP, tm.BDCHAVE, NULL, tm.BDSESSAO, 150 BDCODINCONSISTENCIA, 1 BDTIPOINCON ';
      wSQL = :wSQL || ' FROM TMP_VEF_TMOVENTFUNRURAL_TEMP tm ';
      wSQL = :wSQL || ' left outer join TOL_VEF_EMP_TMOVENTRURAL t on (t.bdcodemp = tm.bdcodemp and t.bdchaveef = tm.bdchave) ';
      wSQL = :wSQL || ' left outer join VRHF_EMP_TNFPRODRURAL rh on (rh.bdcodemp = t.bdcodemp and t.bdchaverh = rh.bdchave) ';
      wSQL = :wSQL || ' left outer join VRHF_EMP_TNFRURAL_ITENS irh on (rh.bdcodemp = irh.bdcodemp and rh.bdchave = irh.bdchave) ';
      wSQL = :wSQL || ' where irh.bdcodemp is not null ';
      EXECUTE STATEMENT :wSQL;
    end*/

  EXECUTE STATEMENT 'DELETE FROM TMP_VRHF_EMP_TNFPRODRURAL_TEMP WHERE BDSESSAO = '||:PRSESSAO;

  wSQL =          'INSERT INTO TMP_VRHF_EMP_TNFPRODRURAL_TEMP(BDSESSAO, BDCODEMP, BDCHAVEEF, BDCHAVE, BDREFNF, BDNOTAFISCAL, BDTIPONF, BDDESCNF, ';
  wSQL = :wSQL ||                                            'BDPERCFPASNF, BDVALNF, BDPERCTERC, BDCODTER, BDTIPOLAN, BDSERIENF, BDEMISSAONF, BDPERCRAT, BDCODAQUIRUR) ';
  wSQL = :wSQL || 'SELECT '||:PRSESSAO||' BDSESSAO, F.BDCODEMP, M.BDCHAVE, NULL, (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, ''YYYYMM'')), ';
  wSQL = :wSQL ||         'M.BDNUMDOCINI, CASE WHEN CHAR_LENGTH(M.BDCNPJ) = 18 THEN 1 ELSE 0 END BDTIPONF, I.BDOBSERVACAO BDDESCNF, ';
  wSQL = :wSQL ||         'F.BDALIQFUNRURAL, M.BDVALORNOTA BDVALNF, F.BDALIQFPAS BDPERCTERC, M.BDCODTER, 100 BDTIPOLAN, M.BDSERIE BDSERIENF, M.BDDATAEMISSAO BDEMISSAONF, F.BDALIQGILRAT BDPERCRAT, F.BDCODAQUIRUR ';
  wSQL = :wSQL || 'FROM '||:wTableFunrural||' F ';
  wSQL = :wSQL || 'JOIN '||:wTable||' M ON(M.BDSESSAO = F.BDSESSAO AND M.BDCODEMP = F.BDCODEMP AND M.BDCHAVE = F.BDCHAVE)';
  wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTableItem||' I ON (I.BDSESSAO = M.BDSESSAO AND I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE AND I.BDORDEM = 1) ';
  wSQL = :wSQL || 'left outer join TOL_VEF_EMP_TMOVENTRURAL t on (t.bdcodemp = F.bdcodemp and t.bdchaveef = F.bdchave) ';
  wSQL = :wSQL || 'left outer join VRHF_EMP_TNFPRODRURAL rh on (rh.bdcodemp = t.bdcodemp and t.bdchaverh = rh.bdchave) ';
  wSQL = :wSQL || 'left outer join VRHF_EMP_TNFRURAL_ITENS irh on (rh.bdcodemp = irh.bdcodemp and rh.bdchave = irh.bdchave) ';
  wSQL = :wSQL || 'WHERE F.BDSESSAO = '||:PRSESSAO;                                                                           
  wSQL = :wSQL || '  and irh.bdcodemp is null '; --#92761 Não apagar o lançamento da folha se tem GPS emitida
  wSQL = :wSQL || 'AND NOT EXISTS(';
  wSQL = :wSQL ||                'SELECT INCO.BDCHAVE ';
  wSQL = :wSQL ||                'FROM '||:wTableInco||' INCO ';
  wSQL = :wSQL ||                'WHERE INCO.BDSESSAO = M.BDSESSAO ';
  wSQL = :wSQL ||                'AND INCO.BDCODEMP = M.BDCODEMP ';
  wSQL = :wSQL ||                'AND INCO.BDCHAVE = M.BDCHAVE';
  wSQL = :wSQL ||               ');';
  EXECUTE STATEMENT :wSQL;

END^

CREATE OR ALTER TRIGGER trg_new_chave_nfprodrural FOR tmp_vrhf_emp_tnfprodrural_temp
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  IF (NEW.BDCHAVE > 0) THEN
    BEGIN
      NEW.BDCHAVE = (NEW.BDCHAVE - GETORDEMSEQUENCIAL(1))+1;
    END
END^

CREATE OR ALTER PROCEDURE SP_LANCA_NFCONT_INSS_ENT_SER (
    PRSESSAO INTEGER,
    PRTIPOLAN CHAR(3))
AS
DECLARE VARIABLE WSQL VARCHAR(1500);
DECLARE VARIABLE WTABLEFUNRURAL VARCHAR(50);
DECLARE VARIABLE WTABLE VARCHAR(50);
DECLARE VARIABLE WTABLEITEM VARCHAR(50);
DECLARE VARIABLE WTABLEINCO VARCHAR(50);
DECLARE VARIABLE WTABLETOL VARCHAR(50);
DECLARE VARIABLE WTABLEDED VARCHAR(32);
BEGIN
  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTableFunrural = 'TMP_VEF_EMP_TMOVENTRET_TEMP';
      wTable         = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItem     = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      wTableInco     = 'VEF_INCON_TMOVENT';
      wTableTol      = 'TOL_VEF_EMP_TENTINSSCONT';
      wTableDed      = 'TMP_VEF_EMP_TMOVENTDED_TEMP';
    END

  EXECUTE STATEMENT 'DELETE FROM TMP_VRHF_EMP_TNFCONT_TEMP WHERE BDSESSAO = '||:PRSESSAO;


  wSQL =          'INSERT INTO TMP_VRHF_EMP_TNFCONT_TEMP(BDSESSAO, BDCODEMP, BDCHAVEEF, BDCHAVE, BDREFNF, BDNOTAFISCAL, BDTIPONF, ';
  wSQL = :wSQL || '                                       BDVALNF,  BDCODTER, BDTIPOLAN,BDDATAEMINF) ';
  wSQL = :wSQL || 'SELECT '||:PRSESSAO||' , D.BDCODEMP, M.BDCHAVE, NULL, (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAENTRADAENT,  ''YYYYMM'')), ';
  wSQL = :wSQL || 'M.BDNUMDOCINI, 0 BDTIPONF, ';
  wSQL = :wSQL || 'D.bdretinss BDVALNF, M.BDCODTER, 100 BDTIPOLAN,  M.BDDATAENTRADAENT BDDATAEMINF ';
  wSQL = :wSQL || 'FROM '||:wTableDed||' D ';
  wSQL = :wSQL || 'JOIN '||:wTable||' M ON(M.BDSESSAO = D.BDSESSAO AND M.BDCODEMP = D.BDCODEMP AND M.BDCHAVE = D.BDCHAVE)';
  wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTableItem||' I ON (I.BDSESSAO = M.BDSESSAO AND I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE AND I.BDORDEM = 1) ';
  wSQL = :wSQL || 'left outer join '||:wTableTol||' Ii on (D.bdcodemp = Ii.bdcodemp and D.bdchave = Ii.bdchaveef) ';
  wSQL = :wSQL || 'left outer join VRHF_EMP_TNFCONT N on (II.BDCODEMP = N.BDCODEMP and II.BDCHAVERH = N.BDCHAVE) ';
  wSQL = :wSQL || 'LEFT OUTER join VRHF_EMP_DARF_TNFCONT H on (N.BDCODEMP = H.BDCODEMP and N.BDCHAVE = H.BDCHAVE) ';
  wSQL = :wSQL || 'WHERE D.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL || 'AND H.bdcodemp IS NULL and CHAR_LENGTH(M.BDCNPJ) = 18 ';
  wSQL = :wSQL || 'AND NOT EXISTS(';
  wSQL = :wSQL ||                'SELECT INCO.BDCHAVE ';
  wSQL = :wSQL ||                'FROM '||:wTableInco||' INCO ';
  wSQL = :wSQL ||                'WHERE INCO.BDSESSAO = M.BDSESSAO ';
  wSQL = :wSQL ||                'AND INCO.BDCODEMP = M.BDCODEMP ';
  wSQL = :wSQL ||                'AND INCO.BDCHAVE = M.BDCHAVE';
  wSQL = :wSQL ||               ');';

  EXECUTE STATEMENT :wSQL;

END^

CREATE OR ALTER PROCEDURE SP_GRAVAR_FUNRURAL (
    PRSESSAO INTEGER,
    PRULTCHAVE INTEGER)
AS
BEGIN

  DELETE FROM TOL_VEF_EMP_TMOVENTRURAL T
  WHERE EXISTS (
                SELECT *
                FROM TMP_VRHF_EMP_TNFPRODRURAL_TEMP R
                WHERE R.BDSESSAO = :PRSESSAO
                AND R.BDCODEMP = T.BDCODEMP
                AND R.BDCHAVEEF = T.BDCHAVEEF
               );

  SETORDEMSEQUENCIAL(0);
  UPDATE TMP_VRHF_EMP_TNFPRODRURAL_TEMP S SET S.BDCHAVE = :PRULTCHAVE WHERE S.BDSESSAO = :PRSESSAO;

  INSERT INTO VRHF_EMP_TNFPRODRURAL(BDCODEMP, BDCHAVE, BDREFNF, BDNOTAFISCAL, BDTIPONF, BDDESCNF, BDPERCFPASNF,
                                    BDVALNF, BDPERCTERC, BDCODTER, BDTIPOLAN, BDSERIENF, BDEMISSAONF, BDPERCRAT, BDCODAQUIRUR)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDREFNF, S.BDNOTAFISCAL, S.BDTIPONF, S.BDDESCNF, S.BDPERCFPASNF,
         S.BDVALNF, S.BDPERCTERC, S.BDCODTER, S.BDTIPOLAN, S.BDSERIENF, S.BDEMISSAONF, S.BDPERCRAT, S.BDCODAQUIRUR
  FROM TMP_VRHF_EMP_TNFPRODRURAL_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO;

  INSERT INTO TOL_VEF_EMP_TMOVENTRURAL(BDCODEMP, BDCHAVEEF, BDCODTER, BDCHAVERH)
  SELECT S.BDCODEMP, S.BDCHAVEEF, S.BDCODTER, S.BDCHAVE
  FROM TMP_VRHF_EMP_TNFPRODRURAL_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO;
END^


CREATE OR ALTER procedure SP_GRAVAR_NFCONT_INSS_ENT_SER (
    PRSESSAO integer,
    PRULTCHAVE integer,
    PRTIPOLAN varchar(3))
as
declare variable WSQL varchar(1500);
declare variable WTABLETOL varchar(50);
BEGIN
  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTableTol      = 'TOL_VEF_EMP_TENTINSSCONT';
    END

  WSQL =          'DELETE FROM '||wTableTol||' T ';
  wSQL = :wSQL || '  WHERE EXISTS ( ';
  wSQL = :wSQL || '                SELECT * ';
  wSQL = :wSQL || '                FROM TMP_VRHF_EMP_TNFCONT_TEMP R ';
  wSQL = :wSQL || '                WHERE R.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL || '                AND R.BDCODEMP = T.BDCODEMP ';
  wSQL = :wSQL || '                AND R.BDCHAVEEF = T.BDCHAVEEF ';
  wSQL = :wSQL || '               ); ';

  EXECUTE STATEMENT wSql;

  SETORDEMSEQUENCIAL(0);
  UPDATE TMP_VRHF_EMP_TNFCONT_TEMP S SET S.BDCHAVE = :PRULTCHAVE  WHERE S.BDSESSAO = :PRSESSAO;

  INSERT INTO VRHF_EMP_TNFCONT(BDCODEMP, BDCHAVE, BDREFNF, BDNOTAFISCAL, BDTIPONF,  BDVALNF,  BDCODTER,  BDTIPOLAN, BDDATAEMINF)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDREFNF, S.BDNOTAFISCAL, S.BDTIPONF, S.BDVALNF, S.BDCODTER, S.BDTIPOLAN, S.BDDATAEMINF
  FROM TMP_VRHF_EMP_TNFCONT_TEMP S
  WHERE S.BDSESSAO = :PRSESSAO;

  WSQL = ' INSERT INTO '||wTableTol||'(BDCODEMP, BDCHAVEEF,  BDCHAVERH) ';
  wSQL = :wSQL || '  SELECT S.BDCODEMP, S.BDCHAVEEF,  S.BDCHAVE ';
  wSQL = :wSQL || '  FROM TMP_VRHF_EMP_TNFCONT_TEMP S ';
  wSQL = :wSQL || '  WHERE S.BDSESSAO = '||:PRSESSAO;

  EXECUTE STATEMENT wSql;

END^


CREATE OR ALTER trigger VSUC_SAVE_SELSOC_bi0 for VSUC_SAVE_SELSOC
active before insert position 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdchave) + 1, 1)
       FROM VSUC_SAVE_SELSOC
       INTO :vNovoCod;

       NEW.bdchave = :vNovoCod;
     END
END
^

CREATE OR ALTER trigger VSUC_SAVE_SELEMPSOC_bi0 for VSUC_SAVE_SELEMPSOC
active before insert position 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.bdsave IS NULL) OR (NEW.bdsave = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdchave), 1)
       FROM VSUC_SAVE_SELSOC
       INTO :vNovoCod;

       NEW.bdsave = :vNovoCod;
     END
END
^

CREATE OR ALTER TRIGGER VCT_BASE_ORCADO_BI0 FOR VCT_BASE_ORCADO
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcodigo INTEGER;
  declare variable vnewkey boolean;
BEGIN
  vnewkey = false;
  vcodigo = null;
  if (coalesce(new.bdchaveorc,0) > 0) then
  begin
    select first 1 bdchaveorc from vct_base_orcado where bdchaveorc = new.bdchaveorc into :vcodigo;
    if (coalesce(:vcodigo,0) > 0) then
       vnewkey = true;
  end
  else
     vnewkey = true;

  if (vnewkey) then
  begin
    vcodigo = 1;
  if (GEN_ID(gen_vct_orcado, 0) = 0) then
       select coalesce(max(BDCHAVEORC), 0)+1 from VCT_BASE_ORCADO into :vcodigo;
  
    NEW.BDCHAVEORC = GEN_ID(gen_vct_orcado, :vcodigo);
  end
END
^

CREATE OR ALTER trigger vct_base_orcado_emp_bi0 for vct_base_orcado_emp
active before insert or update position 0
AS
  DECLARE VARIABLE vCodOrc INTEGER;
BEGIN
  IF ((NEW.BDCHAVEORC IS NULL) OR (NEW.BDCHAVEORC = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCHAVEORC), 1)
       FROM vct_base_orcado
       INTO :vCodOrc;

       NEW.BDCHAVEORC = :vCodOrc;
     END
END^

CREATE OR ALTER trigger vct_base_orcado_emp_ad0 for vct_base_orcado_emp
active after delete position 0
AS
begin
  -- Sol: 85291 Morgana. 03/09/2018. Excluir a chave de orçamento se for a última empresa vinculada ao orçamento.
  /*delete from VCT_BASE_ORCADO orc
  where orc.bdchaveorc = old.bdchaveorc
  and not exists
        (
            select orcemp.bdcodemp from VCT_BASE_ORCADO_EMP orcemp
            where orcemp.bdchaveorc = orc.bdchaveorc
        );*/
end^

CREATE OR ALTER TRIGGER VSUC_CONFIG_BLOQUEIO_AUTO_BI0 FOR VSUC_CONFIG_BLOQUEIO_AUTO
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM VSUC_CONFIG_BLOQUEIO_AUTO INTO vNova_Chave;
      NEW.BDCHAVE = vNova_Chave;
     END
  ELSE
    BEGIN
       SELECT BDCHAVE FROM VSUC_CONFIG_BLOQUEIO_AUTO WHERE (BDCHAVE = NEW.BDCHAVE) INTO vcodigo;
       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM VSUC_CONFIG_BLOQUEIO_AUTO INTO vNova_Chave;
           NEW.BDCHAVE = vNova_Chave;
         END
    END
END
^

CREATE OR ALTER TRIGGER VSUC_SAVE_SELCONT_BI0 FOR VSUC_SAVE_SELCONT
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdchave) + 1, 1)
       FROM VSUC_SAVE_SELCONT
       INTO :vNovoCod;

       NEW.bdchave = :vNovoCod;
     END
END
^
CREATE OR ALTER TRIGGER VSUC_SAVE_SELEMPCONT_BI0 FOR VSUC_SAVE_SELEMPCONT
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.bdsave IS NULL) OR (NEW.bdsave = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdchave), 1)
       FROM VSUC_SAVE_SELCONT
       INTO :vNovoCod;

       NEW.bdsave = :vNovoCod;
     END
END
^

create or alter procedure VCT_ORCAMENTO_EMAIL (
    PRDATA date = current_date)
returns (
    BDCODEMP integer,
    BDEMAIL varchar(200),
    BDNOMUSU varchar(20),
    BDCODESC integer,
    BDNOMESC varchar(100),
    BDNOMEMP varchar(100),
    BDREFEMP integer,
    BDREFCALC integer,
    BDCODSIS integer,
    BDNOMSIS varchar(100),
    BDDATA date,
    BD_ORC integer,
    BD_REAL integer,
    BDMAX integer,
    BDREFORC integer,
    BDDESCORC varchar(200))
as
declare variable WCODEMP integer;
declare variable WCODSIS integer;
declare variable WDATAINI date;
declare variable WDATAFIN date;
declare variable WARRAY varchar(64);
declare variable WTIPO integer;
declare variable WPOS integer;
begin
-- Há um problema de duplicidade quando inserido usuário para sistema e para todos os sistema (VCT_BASE_TIPOCONTROLE.BDCODSIS = 1)
-- não vou resolver agora proque preciso entregar a solicitação, a paliativa seria criar apenas para um sistema ou apenas para todos os sistemas

  -- definição de data inicial e final do mês
  wdataini = DATEADD(1-EXTRACT(DAY FROM :prdata) DAY TO :prdata);
  wdatafin = DATEADD(-EXTRACT(DAY FROM DATEADD(1 MONTH TO :prdata)) DAY TO DATEADD(1 MONTH TO :prdata));
  -- limpa tamela temporária dos orçamentos da empresas
  delete from tmp_orcado_email where bdcodemp is not null;
  -- listar apenas as empresas e sistemas para não calcular repetidas vezes as mesmas empresas
  for select CN.BDCODEMP,TC.BDCODSIS from VCT_CENTRAL_NOTIFICACOES CN
      left join TEMPRESAS EMP on(EMP.BDCODEMP=CN.BDCODEMP)
      left join TESCRITORIO ESC on(ESC.BDCODESC=EMP.BDCODESC or ESC.BDCODESC=(select first 1 BDCODESC from TESCRITORIO order by BDCODESC))
      join VCT_BASE_TIPOCONTROLE TC on(TC.BDCODTIPCTRL=CN.BDCODTIPCTRL and TC.BDCLASSIFICACAO starting '4')
      join TSISTEMA SIS on(SIS.BDCODSIS=TC.BDCODSIS)
      where exists(select first 1 X.BDCODIGO from TSMTP_SCI X
                   join TMODULO_SMTP Y on((Y.BDCODIGO=X.BDCODIGO)and
                                          ((Y.BDCODSIS is null)or(Y.BDCODSIS=TC.BDCODSIS)))and
                                          (trim(X.BDSERVIDOR)<>''))

      group by CN.BDCODEMP,TC.BDCODSIS
  into :wcodemp, :wcodsis do
  begin
    -- limpar a tabela temporária de empresas e inserir apenas a empresa atual
    delete from tmp_empresas_select where bdcodemp is not null;
    insert into tmp_empresas_select(bdcodemp)select bdcodemp from tempresas emp
                                             where bdcodemp=:wcodemp
                                             and not exists(select first 1 bdcodemp
                                                            from tmp_empresas_select
                                                            where bdcodemp=emp.bdcodemp);
    -- inserindo calculos no vetor
    if (:wcodsis in (1,2)) then-- Folha
    begin
      warray = --'7,'||  -- Colaboradores
               '14,'|| -- Folha Normal
               '15,'|| -- Folha Complementar
               '17,'|| -- 13º salário
               '18,'|| -- Adiantamento 13º
               '19,'|| -- Adiantamento Salarial
               '20,'|| -- Complemento de 13º
               '21,'|| -- Férias
               '22,'|| -- Rescisão
               '23,'|| -- PLR
               '24,'|| -- Intermitente
               '25,'|| -- Autônomo
               '26,'|| -- Estagiário
               '27,';  -- Pro-Labore
    end

    if (:wcodsis in (1,3)) then-- Fiscal
    begin
      warray = '2,'|| -- ORCAMENTO_FISCAL_ENTRADAS
               '3,'|| -- SAIDAS
               '4,'|| -- SERVICO
               '5,'|| -- Serviços recebidos
               '6,';  -- Serviços emitidos
    end

    if (:wcodsis in (1,4)) then-- Contábil,Patrimônio,Lalur
    begin
      warray = '1,'||  -- Lançamentos
               '10,'|| --  ORCAMENTO_BENS
               '9,'||  -- ORCAMENTO_LALUR_B
               '8,';   -- ORCAMENTO_LALUR_A
    end

    if (:wcodsis in (1,5)) then-- Financeiro
       warray = '12,'; -- ORCAMENTO_HONORARIO

    -- laço para inserir os cálculos na tabela temporária
    while (Trim(warray) <> '') do
    begin
      wpos = position(',', :warray);
      wtipo = cast(substring(:warray from 1 for :wpos-1) as integer);
      warray = substring(:warray from :wpos+1 for strlen(:warray));

      insert into tmp_orcado_email
      (BDCODEMP,BDNOMEMP,BDREFEMP,BDREFCALC,BDCODSIS,BDNOMSIS,BDDATA,BD_ORC,BD_REAL,BDMAX,BDREFORC,BDDESCORC)
      select BDCODEMP,BDNOMEMP,BDREFEMP,BDREFCALC,BDCODSIS,BDNOMSIS,BDDATA,BD_ORC,BD_REAL,BDMAX,BDREFORC,BDDESCORC
      from vct_orcado_realizado(:wdataini, :wdatafin, :wtipo);
    end
  end

  -- listar os calculos para os usuários responsáveis inseridos na central de notificações
  for select CN.BDCODEMP,USU.BDEMAIL,USU.BDNOMUSU,ESC.bdcodesc,ESC.BDNOMESC,
             tmp.bdnomemp,tmp.BDREFEMP,tmp.BDREFCALC,tmp.BDCODSIS,tmp.BDNOMSIS,
             tmp.BDDATA,tmp.BD_ORC,tmp.BD_REAL,tmp.BDMAX,tmp.BDREFORC,tmp.BDDESCORC
      from VCT_CENTRAL_NOTIFICACOES CN
      join VCT_BASE_TIPOCONTROLE TC on(TC.BDCODTIPCTRL=CN.BDCODTIPCTRL and TC.BDCLASSIFICACAO starting '4')
      join TUSUARIO USU on(USU.BDCODUSU=CN.BDCODUSU)
      join tmp_orcado_email tmp on(tmp.bdcodemp=CN.bdcodemp and-- quando inserido usuários na pasta ORÇAMENTO, representa que o usuário receberá e-mail de todos os módulos
                                   ((tmp.bdcodsis=tc.bdcodsis)or(tmp.bdcodsis is not null and tc.bdcodsis=1)))
      left join TEMPRESAS EMP on(EMP.BDCODEMP=CN.BDCODEMP)
      left join TESCRITORIO ESC on(ESC.BDCODESC=EMP.BDCODESC or
                                   ESC.BDCODESC=(select first 1 BDCODESC from TESCRITORIO order by BDCODESC))

      where(tmp.bdmax<tmp.bd_real)
      order by USU.BDNOMUSU, CN.BDCODEMP, TC.BDCODSIS
  into :BDCODEMP,:BDEMAIL,:BDNOMUSU,:BDCODESC,:BDNOMESC,
       :bdnomemp,:BDREFEMP,:BDREFCALC,:BDCODSIS,:BDNOMSIS,
       :BDDATA,:BD_ORC,:BD_REAL,:BDMAX,:BDREFORC,:BDDESCORC do
  suspend;
end^

CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCCOL (
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  WSQL = 'select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
             BDLANCTAMIN_ORC, BDMINLAN_ORC, BDTOTLANABAIXO_REAL, BDPERLANABAIXO_REAL, BDLANCTAMAX_ORC, BDMAXLAN_ORC,
             BDTOTLANACIMA_REAL, BDPERLANACIMA_REAL,
             case
               when (BDTOTLANABAIXO_REAL > 0) then BDTOTLANABAIXO_REAL * -1
               when (BDTOTLANACIMA_REAL > 0) then BDTOTLANACIMA_REAL
               else 0
             end as BDTOTALLANCAMENTO_REAL,
             case
               when (BDPERLANABAIXO_REAL > 0) then BDPERLANABAIXO_REAL * -1
               when (BDPERLANACIMA_REAL > 0) then BDPERLANACIMA_REAL
               else 0
             end as BDPERCENTUALLANCAMENTO_REAL,
             10 as BDTIPOLAN, BDVLRUN_ORC, BDHONORARIO
      from (select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
                   BDLANCTAMIN_ORC, cast(BDMINLAN_ORC as integer) as BDMINLAN_ORC, cast(
                   case
                     when ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0) then BDMINLAN_ORC - BDTOTLAN_REAL
                     else 0
                   end as integer) BDTOTLANABAIXO_REAL,
                   case
                     when ((BDMINLAN_ORC <> 0) and ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0)) then 100 - ((BDTOTLAN_REAL * 100) / BDMINLAN_ORC)
                     else 0
                   end BDPERLANABAIXO_REAL,
                   BDLANCTAMAX_ORC, cast(BDMAXLAN_ORC as integer) as BDMAXLAN_ORC, cast(
                   case
                     when ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0) then BDTOTLAN_REAL - BDMAXLAN_ORC
                     else 0
                   end as integer) BDTOTLANACIMA_REAL,
                   case
                     when ((BDMAXLAN_ORC <> 0) and ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0)) then ((BDTOTLAN_REAL * 100) / BDMAXLAN_ORC) - 100
                     else 0
                   end BDPERLANACIMA_REAL, BDVLRUN_ORC, BDHONORARIO
            from (select TREAL.BDCODEMP as BDCODEMP_REAL, TREAL.BDREFEMP as BDREFEMP_REAL,
                         TREAL.BDTOTLAN as BDTOTLAN_REAL, TORC.BDREFORC as BDREFEMP_ORC,
                         TORC.BDCODENQFED as BDCODENQFED_ORC, coalesce(TORC.BDQTDCALCCOL, 0) as BDLANCTAQTD_ORC,
                         coalesce(TORC.BDCALCCOLMIN, 0) as BDLANCTAMIN_ORC,
                         case
                           when ((TORC.BDQTDCALCCOL - (TORC.BDQTDCALCCOL * (TORC.BDCALCCOLMIN / 100))) > 0) then (TORC.BDQTDCALCCOL - (TORC.BDQTDCALCCOL * (TORC.BDCALCCOLMIN / 100)))
                           else 0
                         end as BDMINLAN_ORC,
                         coalesce(TORC.BDCALCCOLMAX, 0) as BDLANCTAMAX_ORC,
                         case
                           when ((TORC.BDQTDCALCCOL + (TORC.BDQTDCALCCOL * (TORC.BDCALCCOLMAX / 100))) > 0) then (TORC.BDQTDCALCCOL + (TORC.BDQTDCALCCOL * (TORC.BDCALCCOLMAX / 100)))
                           else 0
                         end as BDMAXLAN_ORC, TORC.BDCALCCOLVLRUNI as BDVLRUN_ORC, BDHONORARIO
                  from (select FN.BDCODEMP, FN.BDREFFN as BDREFEMP, count(FN.BDCODEMP) as BDTOTLAN
                        from (
                        select BDCODEMP, BDCODCOL, BDREFFN
                        from VRHF_EMP_TFOLHANORMAL 
                        where BDREFFN between ' || PRREFINI || ' and ' || PRREFFIN||'
                        union all
                        select BDCODEMP, BDCODCOL, BDREFTOMADOR 
                        from VRHF_EMP_TFOLHATOMADOR 
                        where BDREFTOMADOR between ' || PRREFINI || ' and ' || PRREFFIN||'
                        ) FN
                        left outer join VRH_EMP_TCOLCON C on (C.BDCODEMP = FN.BDCODEMP and C.BDCODCOL = FN.BDCODCOL)
                        left outer join VW_VRH_EMP_TCOLCON_VINC COLV on (COLV.BDCODEMP = FN.BDCODEMP and COLV.BDCODCOL = FN.BDCODCOL)
                        left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = COLV.BDCODCLA)
                        where (COALESCE(C.BDCONTRCOL, 0) = 0) and (CLA.BDGRUPOCLA <> 5)';
                        --#144357 Antony Rairon (27/04/2021) - Colaboradores diferentes do BDGRUPOCLA 5 (Estagiários)
                        IF (PRCODEMP <> '') THEN
                              wsql = wsql||'and FN.BDCODEMP ' || PRCODEMP || ' and ';
                        wsql = wsql||' FN.BDREFFN between ' || PRREFINI || ' and ' || PRREFFIN;
                        wsql = wsql||' group by BDCODEMP, BDREFEMP) TREAL ';
                         --W152747 - Antony R. (30/03/2022)
                        wsql = wsql||'left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = (select first 1 EMP.BDCHAVEORC
                                                                              from VCT_BASE_ORCADO_EMP EMP
                                                                              inner join VCT_BASE_ORCADO ORC on (ORC.BDCHAVEORC = EMP.BDCHAVEORC)
                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
                                                                                    ORC.BDREFORC <= TREAL.BDREFEMP
                                                                              order by ORC.BDREFORC desc)))) ';
--                  left outer join VCT_BASE_ORCADO_EMP TORCEMP on (TORCEMP.BDCODEMP = TREAL.BDCODEMP)
--                  left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = TORCEMP.BDCHAVEORC and TORC.BDREFORC = (select first 1 TX.BDREFORC
--                                                                                                                     from VCT_BASE_ORCADO TX
--                                                                                                                     inner join VCT_BASE_ORCADO_EMP EMP on (EMP.BDCHAVEORC = TX.BDCHAVEORC)
--                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
--                                                                                                                           TX.BDREFORC <= TREAL.BDREFEMP
--                                                                                                                     order by TX.BDREFORC desc)))) ';

     FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP_REAL,
    :BDREFEMP_REAL,
    :BDTOTLAN_REAL,
    :BDREFEMP_ORC,
    :BDCODENQFED_ORC,
    :BDLANCTAQTD_ORC,
    :BDLANCTAMIN_ORC,
    :BDMINLAN_ORC,
    :BDTOTLANABAIXO_REAL,
    :BDPERLANABAIXO_REAL,
    :BDLANCTAMAX_ORC,
    :BDMAXLAN_ORC,
    :BDTOTLANACIMA_REAL,
    :BDPERLANACIMA_REAL,
    :BDTOTALLANCAMENTO_REAL,
    :BDPERCENTUALLANCAMENTO_REAL,
    :BDTIPOLAN,
    :BDVLRUN_ORC,
    :BDHONORARIO
  DO
   SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCPROLAB(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  WSQL = 'select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
             BDLANCTAMIN_ORC, BDMINLAN_ORC, BDTOTLANABAIXO_REAL, BDPERLANABAIXO_REAL, BDLANCTAMAX_ORC, BDMAXLAN_ORC,
             BDTOTLANACIMA_REAL, BDPERLANACIMA_REAL,
             case
               when (BDTOTLANABAIXO_REAL > 0) then BDTOTLANABAIXO_REAL * -1
               when (BDTOTLANACIMA_REAL > 0) then BDTOTLANACIMA_REAL
               else 0
             end as BDTOTALLANCAMENTO_REAL,
             case
               when (BDPERLANABAIXO_REAL > 0) then BDPERLANABAIXO_REAL * -1
               when (BDPERLANACIMA_REAL > 0) then BDPERLANACIMA_REAL
               else 0
             end as BDPERCENTUALLANCAMENTO_REAL,
             11 as BDTIPOLAN, BDVLRUN_ORC, BDHONORARIO
      from (select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
                   BDLANCTAMIN_ORC, cast(BDMINLAN_ORC as integer) as BDMINLAN_ORC, cast(
                   case
                     when ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0) then BDMINLAN_ORC - BDTOTLAN_REAL
                     else 0
                   end as integer) BDTOTLANABAIXO_REAL,
                   case
                     when ((BDMINLAN_ORC <> 0) and ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0)) then 100 - ((BDTOTLAN_REAL * 100) / BDMINLAN_ORC)
                     else 0
                   end BDPERLANABAIXO_REAL,
                   BDLANCTAMAX_ORC, cast(BDMAXLAN_ORC as integer) as BDMAXLAN_ORC, cast(
                   case
                     when ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0) then BDTOTLAN_REAL - BDMAXLAN_ORC
                     else 0
                   end as integer) BDTOTLANACIMA_REAL,
                   case
                     when ((BDMAXLAN_ORC <> 0) and ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0)) then ((BDTOTLAN_REAL * 100) / BDMAXLAN_ORC) - 100
                     else 0
                   end BDPERLANACIMA_REAL, BDVLRUN_ORC, BDHONORARIO
            from (select TREAL.BDCODEMP as BDCODEMP_REAL, TREAL.BDREFEMP as BDREFEMP_REAL,
                         TREAL.BDTOTLAN as BDTOTLAN_REAL, TORC.BDREFORC as BDREFEMP_ORC,
                         TORC.BDCODENQFED as BDCODENQFED_ORC, coalesce(TORC.BDQTDCALCPROLAB, 0) as BDLANCTAQTD_ORC,
                         coalesce(TORC.BDCALCPROLABMIN, 0) as BDLANCTAMIN_ORC,
                         case
                           when ((TORC.BDQTDCALCPROLAB - (TORC.BDQTDCALCPROLAB * (TORC.BDCALCPROLABMIN / 100))) > 0) then (TORC.BDQTDCALCPROLAB - (TORC.BDQTDCALCPROLAB * (TORC.BDCALCPROLABMIN / 100)))
                           else 0
                         end as BDMINLAN_ORC,
                         coalesce(TORC.BDCALCPROLABMAX, 0) as BDLANCTAMAX_ORC,
                         case
                           when ((TORC.BDQTDCALCPROLAB + (TORC.BDQTDCALCPROLAB * (TORC.BDCALCPROLABMAX / 100))) > 0) then (TORC.BDQTDCALCPROLAB + (TORC.BDQTDCALCPROLAB * (TORC.BDCALCPROLABMAX / 100)))
                           else 0
                         end as BDMAXLAN_ORC, TORC.BDCALCPROLABVLRUNI as BDVLRUN_ORC, BDHONORARIO
                  from (select FN.BDCODEMP, count(FN.BDCODEMP) as BDTOTLAN, FN.BDREFFN as BDREFEMP
                        from (select TFN.BDCODEMP, TFN.BDCODCOL, TFN.BDREFFN
                              from VRHF_EMP_TFOLHANORMAL TFN
                              where TFN.BDREFFN between '||PRREFINI||' and '||PRREFFIN;
                              wsql = wsql||' union all
                              select TFT.BDCODEMP, TFT.BDCODCOL, TFT.BDREFTOMADOR
                              from VRHF_EMP_TFOLHATOMADOR TFT
                              where TFT.BDREFTOMADOR between '||PRREFINI||' and '||PRREFFIN||') FN
                        left outer join VRH_EMP_TCOLCON C on (C.BDCODEMP = FN.BDCODEMP and C.BDCODCOL = FN.BDCODCOL)
                        where COALESCE(C.BDCONTRCOL, 0) = 1 ';
                        IF (PRCODEMP <> '') THEN
                           wsql = wsql||' and FN.BDCODEMP ' || PRCODEMP || '';
                  wsql = wsql||' group by BDCODEMP, BDREFFN) TREAL ';
                  --W152747 - Antony R. (30/03/2022)
                  wsql = wsql||'left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = (select first 1 EMP.BDCHAVEORC
                                                                         from VCT_BASE_ORCADO_EMP EMP
                                                                          inner join VCT_BASE_ORCADO ORC on (ORC.BDCHAVEORC = EMP.BDCHAVEORC)
                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
                                                                                ORC.BDREFORC <= TREAL.BDREFEMP
                                                                          order by ORC.BDREFORC desc)))) ';
--                  left outer join VCT_BASE_ORCADO_EMP TORCEMP on (TORCEMP.BDCODEMP = TREAL.BDCODEMP)
--                  left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = TORCEMP.BDCHAVEORC and TORC.BDREFORC = (select first 1 TX.BDREFORC
--                                                                                                                     from VCT_BASE_ORCADO TX
--                                                                                                                     inner join VCT_BASE_ORCADO_EMP EMP on (EMP.BDCHAVEORC = TX.BDCHAVEORC)
--                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
--                                                                                                                           TX.BDREFORC <= TREAL.BDREFEMP
--                                                                                                                     order by TX.BDREFORC desc)))) ';



     FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP_REAL,
    :BDREFEMP_REAL,
    :BDTOTLAN_REAL,
    :BDREFEMP_ORC,
    :BDCODENQFED_ORC,
    :BDLANCTAQTD_ORC,
    :BDLANCTAMIN_ORC,
    :BDMINLAN_ORC,
    :BDTOTLANABAIXO_REAL,
    :BDPERLANABAIXO_REAL,
    :BDLANCTAMAX_ORC,
    :BDMAXLAN_ORC,
    :BDTOTLANACIMA_REAL,
    :BDPERLANACIMA_REAL,
    :BDTOTALLANCAMENTO_REAL,
    :BDPERCENTUALLANCAMENTO_REAL,
    :BDTIPOLAN,
    :BDVLRUN_ORC,
    :BDHONORARIO
  DO
   SUSPEND;
END^

CREATE OR ALTER procedure SP_VCT_ORC_X_REL_QTDCALCESTAG (
    PRCODEMP varchar(10000),
    PRREFINI integer,
    PRREFFIN integer)
returns (
    BDCODEMP_REAL integer,
    BDREFEMP_REAL integer,
    BDTOTLAN_REAL integer,
    BDREFEMP_ORC integer,
    BDCODENQFED_ORC integer,
    BDLANCTAQTD_ORC integer,
    BDLANCTAMIN_ORC integer,
    BDMINLAN_ORC integer,
    BDTOTLANABAIXO_REAL integer,
    BDPERLANABAIXO_REAL integer,
    BDLANCTAMAX_ORC integer,
    BDMAXLAN_ORC integer,
    BDTOTLANACIMA_REAL integer,
    BDPERLANACIMA_REAL integer,
    BDTOTALLANCAMENTO_REAL integer,
    BDPERCENTUALLANCAMENTO_REAL integer,
    BDTIPOLAN integer,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
as
declare variable WSQL varchar(32700);
BEGIN
  WSQL = 'select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
             BDLANCTAMIN_ORC, BDMINLAN_ORC, BDTOTLANABAIXO_REAL, BDPERLANABAIXO_REAL, BDLANCTAMAX_ORC, BDMAXLAN_ORC,
             BDTOTLANACIMA_REAL, BDPERLANACIMA_REAL,
             case
               when (BDTOTLANABAIXO_REAL > 0) then BDTOTLANABAIXO_REAL * -1
               when (BDTOTLANACIMA_REAL > 0) then BDTOTLANACIMA_REAL
               else 0
             end as BDTOTALLANCAMENTO_REAL,
             case
               when (BDPERLANABAIXO_REAL > 0) then BDPERLANABAIXO_REAL * -1
               when (BDPERLANACIMA_REAL > 0) then BDPERLANACIMA_REAL
               else 0
             end as BDPERCENTUALLANCAMENTO_REAL,
             12 as BDTIPOLAN, BDVLRUN_ORC, BDHONORARIO
      from (select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
                   BDLANCTAMIN_ORC, cast(BDMINLAN_ORC as integer) as BDMINLAN_ORC, cast(
                   case
                     when ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0) then BDMINLAN_ORC - BDTOTLAN_REAL
                     else 0
                   end as integer) BDTOTLANABAIXO_REAL,
                   case
                     when ((BDMINLAN_ORC <> 0) and ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0)) then 100 - ((BDTOTLAN_REAL * 100) / BDMINLAN_ORC)
                     else 0
                   end BDPERLANABAIXO_REAL,
                   BDLANCTAMAX_ORC, cast(BDMAXLAN_ORC as integer) as BDMAXLAN_ORC, cast(
                   case
                     when ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0) then BDTOTLAN_REAL - BDMAXLAN_ORC
                     else 0
                   end as integer) BDTOTLANACIMA_REAL,
                   case
                     when ((BDMAXLAN_ORC <> 0) and ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0)) then ((BDTOTLAN_REAL * 100) / BDMAXLAN_ORC) - 100
                     else 0
                   end BDPERLANACIMA_REAL, BDVLRUN_ORC, BDHONORARIO
            from (select TREAL.BDCODEMP as BDCODEMP_REAL, TREAL.BDREFEMP as BDREFEMP_REAL,
                         TREAL.BDTOTLAN as BDTOTLAN_REAL, TORC.BDREFORC as BDREFEMP_ORC,
                         TORC.BDCODENQFED as BDCODENQFED_ORC, coalesce(TORC.BDQTDCALCESTAG, 0) as BDLANCTAQTD_ORC,
                         coalesce(TORC.BDCALCESTAGMIN, 0) as BDLANCTAMIN_ORC,
                         case
                           when ((TORC.BDQTDCALCESTAG - (TORC.BDQTDCALCESTAG * (TORC.BDCALCESTAGMIN / 100))) > 0) then (TORC.BDQTDCALCESTAG - (TORC.BDQTDCALCESTAG * (TORC.BDCALCESTAGMIN / 100)))
                           else 0
                         end as BDMINLAN_ORC,
                         coalesce(TORC.BDCALCESTAGMAX, 0) as BDLANCTAMAX_ORC,
                         case
                           when ((TORC.BDQTDCALCESTAG + (TORC.BDQTDCALCESTAG * (TORC.BDCALCESTAGMAX / 100))) > 0) then (TORC.BDQTDCALCESTAG + (TORC.BDQTDCALCESTAG * (TORC.BDCALCESTAGMAX / 100)))
                           else 0
                         end as BDMAXLAN_ORC, TORC.BDCALCESTAGVLRUNI as BDVLRUN_ORC, BDHONORARIO
                  from (select FOLEST.BDCODEMP, count(FOLEST.BDCODEMP) as BDTOTLAN, FOLEST.BDREFFN as BDREFEMP
                        from (select BDCODEMP, BDCODCOL, BDREFFN
                              from VRHF_EMP_TFOLHANORMAL TFN
                              where TFN.BDREFFN between '||PRREFINI||' and '||PRREFFIN;
               wsql = wsql||' union all
                              select BDCODEMP, BDCODCOL, BDREFTOMADOR
                              from VRHF_EMP_TFOLHATOMADOR TFT
                              where TFT.BDREFTOMADOR between '||PRREFINI||' and '||PRREFFIN||') FOLEST
                        left outer join VW_VRH_EMP_TCOLCON_VINC C on (C.BDCODEMP = FOLEST.BDCODEMP and C.BDCODCOL = FOLEST.BDCODCOL)
                        left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = C.BDCODCLA)
                        where CLA.BDGRUPOCLA = 5 ';
                        IF (PRCODEMP <> '') THEN
                           wsql = wsql||' and FOLEST.BDCODEMP ' || PRCODEMP || ' ';
                        wsql = wsql||'group by BDCODEMP, BDREFEMP) TREAL ';
                        --W152747 - Antony R. (30/03/2022)
                        wsql = wsql||'left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = (select first 1 EMP.BDCHAVEORC
                                                                              from VCT_BASE_ORCADO_EMP EMP
                                                                              inner join VCT_BASE_ORCADO ORC on (ORC.BDCHAVEORC = EMP.BDCHAVEORC)
                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
                                                                                    ORC.BDREFORC <= TREAL.BDREFEMP
                                                                              order by ORC.BDREFORC desc)))) ';
--                  left outer join VCT_BASE_ORCADO_EMP TORCEMP on (TORCEMP.BDCODEMP = TREAL.BDCODEMP)
--                  left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = TORCEMP.BDCHAVEORC and TORC.BDREFORC = (select first 1 TX.BDREFORC
--                                                                                                                     from VCT_BASE_ORCADO TX
--                                                                                                                     inner join VCT_BASE_ORCADO_EMP EMP on (EMP.BDCHAVEORC = TX.BDCHAVEORC)
--                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
--                                                                                                                           TX.BDREFORC <= TREAL.BDREFEMP
--                                                                                                                     order by TX.BDREFORC desc))))';



     FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP_REAL,
    :BDREFEMP_REAL,
    :BDTOTLAN_REAL,
    :BDREFEMP_ORC,
    :BDCODENQFED_ORC,
    :BDLANCTAQTD_ORC,
    :BDLANCTAMIN_ORC,
    :BDMINLAN_ORC,
    :BDTOTLANABAIXO_REAL,
    :BDPERLANABAIXO_REAL,
    :BDLANCTAMAX_ORC,
    :BDMAXLAN_ORC,
    :BDTOTLANACIMA_REAL,
    :BDPERLANACIMA_REAL,
    :BDTOTALLANCAMENTO_REAL,
    :BDPERCENTUALLANCAMENTO_REAL,
    :BDTIPOLAN,
    :BDVLRUN_ORC,
    :BDHONORARIO
  DO
   SUSPEND;
END^

create or alter procedure SP_VCT_ORC_X_REL_QTDCALCRESC (
    PRCODEMP varchar(10000),
    PRREFINI integer,
    PRREFFIN integer)
returns (
    BDCODEMP_REAL integer,
    BDREFEMP_REAL integer,
    BDTOTLAN_REAL integer,
    BDREFEMP_ORC integer,
    BDCODENQFED_ORC integer,
    BDLANCTAQTD_ORC integer,
    BDLANCTAMIN_ORC integer,
    BDMINLAN_ORC integer,
    BDTOTLANABAIXO_REAL integer,
    BDPERLANABAIXO_REAL integer,
    BDLANCTAMAX_ORC integer,
    BDMAXLAN_ORC integer,
    BDTOTLANACIMA_REAL integer,
    BDPERLANACIMA_REAL integer,
    BDTOTALLANCAMENTO_REAL integer,
    BDPERCENTUALLANCAMENTO_REAL integer,
    BDTIPOLAN integer,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
as
declare variable WSQL varchar(32700);
BEGIN
  WSQL = ' select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
             BDLANCTAMIN_ORC, BDMINLAN_ORC, BDTOTLANABAIXO_REAL, BDPERLANABAIXO_REAL, BDLANCTAMAX_ORC, BDMAXLAN_ORC,
             BDTOTLANACIMA_REAL, BDPERLANACIMA_REAL,
             case
               when (BDTOTLANABAIXO_REAL > 0) then BDTOTLANABAIXO_REAL * -1
               when (BDTOTLANACIMA_REAL > 0) then BDTOTLANACIMA_REAL
               else 0
             end as BDTOTALLANCAMENTO_REAL,
             case
               when (BDPERLANABAIXO_REAL > 0) then BDPERLANABAIXO_REAL * -1
               when (BDPERLANACIMA_REAL > 0) then BDPERLANACIMA_REAL
               else 0
             end as BDPERCENTUALLANCAMENTO_REAL,
             13 as BDTIPOLAN, BDVLRUN_ORC, BDHONORARIO
      from (select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
                   BDLANCTAMIN_ORC, cast(BDMINLAN_ORC as integer) as BDMINLAN_ORC, cast(
                   case
                     when ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0) then BDMINLAN_ORC - BDTOTLAN_REAL
                     else 0
                   end as integer) BDTOTLANABAIXO_REAL,
                   case
                     when ((BDMINLAN_ORC <> 0) and ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0)) then 100 - ((BDTOTLAN_REAL * 100) / BDMINLAN_ORC)
                     else 0
                   end BDPERLANABAIXO_REAL,
                   BDLANCTAMAX_ORC, cast(BDMAXLAN_ORC as integer) as BDMAXLAN_ORC, cast(
                   case
                     when ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0) then BDTOTLAN_REAL - BDMAXLAN_ORC
                     else 0
                   end as integer) BDTOTLANACIMA_REAL,
                   case
                     when ((BDMAXLAN_ORC <> 0) and ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0)) then ((BDTOTLAN_REAL * 100) / BDMAXLAN_ORC) - 100
                     else 0
                   end BDPERLANACIMA_REAL, BDVLRUN_ORC, BDHONORARIO
            from (select TREAL.BDCODEMP as BDCODEMP_REAL, TREAL.BDREFEMP as BDREFEMP_REAL,
                         TREAL.BDTOTLAN as BDTOTLAN_REAL, TORC.BDREFORC as BDREFEMP_ORC,
                         TORC.BDCODENQFED as BDCODENQFED_ORC, coalesce(TORC.BDQTDCALCRESC, 0) as BDLANCTAQTD_ORC,
                         coalesce(TORC.BDCALCRESCMIN, 0) as BDLANCTAMIN_ORC,
                         case
                           when ((TORC.BDQTDCALCRESC - (TORC.BDQTDCALCRESC * (TORC.BDCALCRESCMIN / 100))) > 0) then (TORC.BDQTDCALCRESC - (TORC.BDQTDCALCRESC * (TORC.BDCALCRESCMIN / 100)))
                           else 0
                         end as BDMINLAN_ORC,
                         coalesce(TORC.BDCALCRESCMAX, 0) as BDLANCTAMAX_ORC,
                         case
                           when ((TORC.BDQTDCALCRESC + (TORC.BDQTDCALCRESC * (TORC.BDCALCRESCMAX / 100))) > 0) then (TORC.BDQTDCALCRESC + (TORC.BDQTDCALCRESC * (TORC.BDCALCRESCMAX / 100)))
                           else 0
                         end as BDMAXLAN_ORC, TORC.BDCALCRESCVLRUNI as BDVLRUN_ORC, BDHONORARIO
                  from (';

                 /* Augusto - 02/08/2024 - Essa rotina lixa e imunda causava erro de contagem e duplicava as recisões
                            - #202558    - além de dar uma dor de cabeça de ver como é feita, ajustei apenas a merda que tava feita.*/
                 wsql = wsql || 'select RESC.BDCODEMP, count(RESC.BDCODEMP) as BDTOTLAN, RESC.BDREFRESCISAO as BDREFEMP ';
                 wsql = wsql || ' from VRH_EMP_TRESCISAO RESC ';
--                 wsql = wsql||       from (select BDCODEMP, BDCODCOL, BDREFTOMADOR
--                 wsql = wsql||             from VRHF_EMP_TFOLHATOMADOR TFT
--                 wsql = wsql||             where TFT.BDREFTOMADOR between '||PRREFINI||' and '||PRREFFIN||'
--                 wsql = wsql||             union all
--                 wsql = wsql||             select BDCODEMP, BDCODCOL, BDREFFN
--                 wsql = wsql||             from VRHF_EMP_TFOLHANORMAL TFN
--                 wsql = wsql||             where TFN.BDREFFN between '||PRREFINI||' and '||PRREFFIN||') FN
                 wsql = wsql || '      left outer join VRH_EMP_TCOLCON C on (C.BDCODEMP = RESC.BDCODEMP and C.BDCODCOL = RESC.BDCODCOL) ';
--                 wsql = wsql||       left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FN.BDCODEMP and RESC.BDCODCOL = FN.BDCODCOL)

                 wsql = wsql || '       where coalesce(C.BDCONTRCOL, 0) = 0 and ';
                 wsql = wsql || '             RESC.BDREFRESCISAO between '||PRREFINI||' and '||PRREFFIN||'' ;

                       IF (PRCODEMP <> '') THEN
                           wsql = wsql||' and RESC.BDCODEMP ' || PRCODEMP || ' ';
                        wsql = wsql||'group by BDCODEMP, BDREFEMP) TREAL ';

                        --W152747 - Antony R. (30/03/2022)
                        wsql = wsql||'left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = (select first 1 EMP.BDCHAVEORC
                                                                              from VCT_BASE_ORCADO_EMP EMP
                                                                              inner join VCT_BASE_ORCADO ORC on (ORC.BDCHAVEORC = EMP.BDCHAVEORC)
                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
                                                                                    ORC.BDREFORC <= TREAL.BDREFEMP
                                                                              order by ORC.BDREFORC desc)))) ';
--                  left outer join VCT_BASE_ORCADO_EMP TORCEMP on (TORCEMP.BDCODEMP = TREAL.BDCODEMP)
--                  left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = TORCEMP.BDCHAVEORC and TORC.BDREFORC = (select first 1 TX.BDREFORC
--                                                                                                                     from VCT_BASE_ORCADO TX
--                                                                                                                     inner join VCT_BASE_ORCADO_EMP EMP on (EMP.BDCHAVEORC = TX.BDCHAVEORC)
--                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
--                                                                                                                           TX.BDREFORC <= TREAL.BDREFEMP
--                                                                                                                     order by TX.BDREFORC desc))))';

     FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP_REAL,
    :BDREFEMP_REAL,
    :BDTOTLAN_REAL,
    :BDREFEMP_ORC,
    :BDCODENQFED_ORC,
    :BDLANCTAQTD_ORC,
    :BDLANCTAMIN_ORC,
    :BDMINLAN_ORC,
    :BDTOTLANABAIXO_REAL,
    :BDPERLANABAIXO_REAL,
    :BDLANCTAMAX_ORC,
    :BDMAXLAN_ORC,
    :BDTOTLANACIMA_REAL,
    :BDPERLANACIMA_REAL,
    :BDTOTALLANCAMENTO_REAL,
    :BDPERCENTUALLANCAMENTO_REAL,
    :BDTIPOLAN,
    :BDVLRUN_ORC,
    :BDHONORARIO
  DO
   SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCAUT(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  WSQL = ' select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
             BDLANCTAMIN_ORC, BDMINLAN_ORC, BDTOTLANABAIXO_REAL, BDPERLANABAIXO_REAL, BDLANCTAMAX_ORC, BDMAXLAN_ORC,
             BDTOTLANACIMA_REAL, BDPERLANACIMA_REAL,
             case
               when (BDTOTLANABAIXO_REAL > 0) then BDTOTLANABAIXO_REAL * -1
               when (BDTOTLANACIMA_REAL > 0) then BDTOTLANACIMA_REAL
               else 0
             end as BDTOTALLANCAMENTO_REAL,
             case
               when (BDPERLANABAIXO_REAL > 0) then BDPERLANABAIXO_REAL * -1
               when (BDPERLANACIMA_REAL > 0) then BDPERLANACIMA_REAL
               else 0
             end as BDPERCENTUALLANCAMENTO_REAL,
             14 as BDTIPOLAN, BDVLRUN_ORC, BDHONORARIO
      from (select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
                   BDLANCTAMIN_ORC, cast(BDMINLAN_ORC as integer) as BDMINLAN_ORC, cast(
                   case
                     when ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0) then BDMINLAN_ORC - BDTOTLAN_REAL
                     else 0
                   end as integer) BDTOTLANABAIXO_REAL,
                   case
                     when ((BDMINLAN_ORC <> 0) and ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0)) then 100 - ((BDTOTLAN_REAL * 100) / BDMINLAN_ORC)
                     else 0
                   end BDPERLANABAIXO_REAL,
                   BDLANCTAMAX_ORC, cast(BDMAXLAN_ORC as integer) as BDMAXLAN_ORC, cast(
                   case
                     when ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0) then BDTOTLAN_REAL - BDMAXLAN_ORC
                     else 0
                   end as integer) BDTOTLANACIMA_REAL,
                   case
                     when ((BDMAXLAN_ORC <> 0) and ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0)) then ((BDTOTLAN_REAL * 100) / BDMAXLAN_ORC) - 100
                     else 0
                   end BDPERLANACIMA_REAL, BDVLRUN_ORC, BDHONORARIO
            from (select TREAL.BDCODEMP as BDCODEMP_REAL, TREAL.BDREFEMP as BDREFEMP_REAL,
                         TREAL.BDTOTLAN as BDTOTLAN_REAL, TORC.BDREFORC as BDREFEMP_ORC,
                         TORC.BDCODENQFED as BDCODENQFED_ORC, coalesce(TORC.BDQTDCALCAUT, 0) as BDLANCTAQTD_ORC,
                         coalesce(TORC.BDCALCAUTMIN, 0) as BDLANCTAMIN_ORC,
                         case
                           when ((TORC.BDQTDCALCAUT - (TORC.BDQTDCALCAUT * (TORC.BDCALCAUTMIN / 100))) > 0) then (TORC.BDQTDCALCAUT - (TORC.BDQTDCALCAUT * (TORC.BDCALCAUTMIN / 100)))
                           else 0
                         end as BDMINLAN_ORC,
                         coalesce(TORC.BDCALCAUTMAX, 0) as BDLANCTAMAX_ORC,
                         case
                           when ((TORC.BDQTDCALCAUT + (TORC.BDQTDCALCAUT * (TORC.BDCALCAUTMAX / 100))) > 0) then (TORC.BDQTDCALCAUT + (TORC.BDQTDCALCAUT * (TORC.BDCALCAUTMAX / 100)))
                           else 0
                         end as BDMAXLAN_ORC, TORC.BDCALCAUTVLRUNI as BDVLRUN_ORC, BDHONORARIO
                  from (select BDCODEMP, count(BDCODEMP) as BDTOTLAN, BDREFINSSSERV as BDREFEMP
                        from VRHF_BASE_CALC_TERC TERC
                        where TERC.BDREFINSSSERV between '||PRREFINI||' and '||PRREFFIN;
                        IF (PRCODEMP <> '') THEN
                           wsql = wsql||' and TERC.BDCODEMP ' || PRCODEMP || ' ';
                        wsql = wsql||'group by BDCODEMP, BDREFEMP) TREAL ';
                        --W152747 - Antony R. (30/03/2022)
                        wsql = wsql||'left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = (select first 1 EMP.BDCHAVEORC
                                                                              from VCT_BASE_ORCADO_EMP EMP
                                                                              inner join VCT_BASE_ORCADO ORC on (ORC.BDCHAVEORC = EMP.BDCHAVEORC)
                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
                                                                                    ORC.BDREFORC <= TREAL.BDREFEMP
                                                                              order by ORC.BDREFORC desc)))) ';
--                  left outer join VCT_BASE_ORCADO_EMP TORCEMP on (TORCEMP.BDCODEMP = TREAL.BDCODEMP)
--                  left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = TORCEMP.BDCHAVEORC and TORC.BDREFORC = (select first 1 TX.BDREFORC
--                                                                                                                     from VCT_BASE_ORCADO TX
--                                                                                                                     inner join VCT_BASE_ORCADO_EMP EMP on (EMP.BDCHAVEORC = TX.BDCHAVEORC)
--                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
--                                                                                                                           TX.BDREFORC <= TREAL.BDREFEMP
--                                                                                                                     order by TX.BDREFORC desc))))';


     FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP_REAL,
    :BDREFEMP_REAL,
    :BDTOTLAN_REAL,
    :BDREFEMP_ORC,
    :BDCODENQFED_ORC,
    :BDLANCTAQTD_ORC,
    :BDLANCTAMIN_ORC,
    :BDMINLAN_ORC,
    :BDTOTLANABAIXO_REAL,
    :BDPERLANABAIXO_REAL,
    :BDLANCTAMAX_ORC,
    :BDMAXLAN_ORC,
    :BDTOTLANACIMA_REAL,
    :BDPERLANACIMA_REAL,
    :BDTOTALLANCAMENTO_REAL,
    :BDPERCENTUALLANCAMENTO_REAL,
    :BDTIPOLAN,
    :BDVLRUN_ORC,
    :BDHONORARIO
  DO
   SUSPEND;
END ^

CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCFERCOL(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  WSQL = 'select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
             BDLANCTAMIN_ORC, BDMINLAN_ORC, BDTOTLANABAIXO_REAL, BDPERLANABAIXO_REAL, BDLANCTAMAX_ORC, BDMAXLAN_ORC,
             BDTOTLANACIMA_REAL, BDPERLANACIMA_REAL,
             case
               when (BDTOTLANABAIXO_REAL > 0) then BDTOTLANABAIXO_REAL * -1
               when (BDTOTLANACIMA_REAL > 0) then BDTOTLANACIMA_REAL
               else 0
             end as BDTOTALLANCAMENTO_REAL,
             case
               when (BDPERLANABAIXO_REAL > 0) then BDPERLANABAIXO_REAL * -1
               when (BDPERLANACIMA_REAL > 0) then BDPERLANACIMA_REAL
               else 0
             end as BDPERCENTUALLANCAMENTO_REAL,
             15 as BDTIPOLAN, BDVLRUN_ORC, BDHONORARIO
      from (select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
                   BDLANCTAMIN_ORC, cast(BDMINLAN_ORC as integer) as BDMINLAN_ORC, cast(
                   case
                     when ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0) then BDMINLAN_ORC - BDTOTLAN_REAL
                     else 0
                   end as integer) BDTOTLANABAIXO_REAL,
                   case
                     when ((BDMINLAN_ORC <> 0) and ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0)) then 100 - ((BDTOTLAN_REAL * 100) / BDMINLAN_ORC)
                     else 0
                   end BDPERLANABAIXO_REAL,
                   BDLANCTAMAX_ORC, cast(BDMAXLAN_ORC as integer) as BDMAXLAN_ORC, cast(
                   case
                     when ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0) then BDTOTLAN_REAL - BDMAXLAN_ORC
                     else 0
                   end as integer) BDTOTLANACIMA_REAL,
                   case
                     when ((BDMAXLAN_ORC <> 0) and ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0)) then ((BDTOTLAN_REAL * 100) / BDMAXLAN_ORC) - 100
                     else 0
                   end BDPERLANACIMA_REAL, BDVLRUN_ORC, BDHONORARIO
            from (select TREAL.BDCODEMP as BDCODEMP_REAL, TREAL.BDREFEMP as BDREFEMP_REAL,
                         TREAL.BDTOTLAN as BDTOTLAN_REAL, TORC.BDREFORC as BDREFEMP_ORC,
                         TORC.BDCODENQFED as BDCODENQFED_ORC, coalesce(TORC.BDQTDCALCFERCOL, 0) as BDLANCTAQTD_ORC,
                         coalesce(TORC.BDCALCFERCOLMIN, 0) as BDLANCTAMIN_ORC,
                         case
                           when ((TORC.BDQTDCALCFERCOL - (TORC.BDQTDCALCFERCOL * (TORC.BDCALCFERCOLMIN / 100))) > 0) then (TORC.BDQTDCALCFERCOL - (TORC.BDQTDCALCFERCOL * (TORC.BDCALCFERCOLMIN / 100)))
                           else 0
                         end as BDMINLAN_ORC,
                         coalesce(TORC.BDCALCFERCOLMAX, 0) as BDLANCTAMAX_ORC,
                         case
                           when ((TORC.BDQTDCALCFERCOL + (TORC.BDQTDCALCFERCOL * (TORC.BDCALCFERCOLMAX / 100))) > 0) then (TORC.BDQTDCALCFERCOL + (TORC.BDQTDCALCFERCOL * (TORC.BDCALCFERCOLMAX / 100)))
                           else 0
                         end as BDMAXLAN_ORC, TORC.BDCALCFERCOLVLRUNI  as BDVLRUN_ORC, BDHONORARIO
                  from (select BDCODEMP, count(BDCODEMP) as BDTOTLAN, BDREFINIFE as BDREFEMP
                        from VRH_EMP_TFERIAS
                        where BDREFINIFE between '||PRREFINI||' and '||PRREFFIN||' and
                              upper(coalesce(BDCOLETIVASFE, '||'''FALSE'''||')) = '||'''TRUE'''||' ';
                       IF (PRCODEMP <> '') THEN
                           wsql = wsql||' and BDCODEMP ' || PRCODEMP || '';
                        wsql = wsql||'group by BDCODEMP, BDREFEMP) TREAL ';
                        --W152747 - Antony R. (30/03/2022)
                        wsql = wsql||'left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = (select first 1 EMP.BDCHAVEORC
                                                                              from VCT_BASE_ORCADO_EMP EMP
                                                                              inner join VCT_BASE_ORCADO ORC on (ORC.BDCHAVEORC = EMP.BDCHAVEORC)
                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
                                                                                    ORC.BDREFORC <= TREAL.BDREFEMP
                                                                              order by ORC.BDREFORC desc)))) ';
--                  left outer join VCT_BASE_ORCADO_EMP TORCEMP on (TORCEMP.BDCODEMP = TREAL.BDCODEMP)
--                  left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = TORCEMP.BDCHAVEORC and TORC.BDREFORC = (select first 1 TX.BDREFORC
--                                                                                                                     from VCT_BASE_ORCADO TX
--                                                                                                                     inner join VCT_BASE_ORCADO_EMP EMP on (EMP.BDCHAVEORC = TX.BDCHAVEORC)
--                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
--                                                                                                                           TX.BDREFORC <= TREAL.BDREFEMP
--                                                                                                                     order by TX.BDREFORC desc))))';

     FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP_REAL,
    :BDREFEMP_REAL,
    :BDTOTLAN_REAL,
    :BDREFEMP_ORC,
    :BDCODENQFED_ORC,
    :BDLANCTAQTD_ORC,
    :BDLANCTAMIN_ORC,
    :BDMINLAN_ORC,
    :BDTOTLANABAIXO_REAL,
    :BDPERLANABAIXO_REAL,
    :BDLANCTAMAX_ORC,
    :BDMAXLAN_ORC,
    :BDTOTLANACIMA_REAL,
    :BDPERLANACIMA_REAL,
    :BDTOTALLANCAMENTO_REAL,
    :BDPERCENTUALLANCAMENTO_REAL,
    :BDTIPOLAN,
    :BDVLRUN_ORC,
    :BDHONORARIO
  DO
   SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCFERIND(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  WSQL = ' select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
             BDLANCTAMIN_ORC, BDMINLAN_ORC, BDTOTLANABAIXO_REAL, BDPERLANABAIXO_REAL, BDLANCTAMAX_ORC, BDMAXLAN_ORC,
             BDTOTLANACIMA_REAL, BDPERLANACIMA_REAL,
             case
               when (BDTOTLANABAIXO_REAL > 0) then BDTOTLANABAIXO_REAL * -1
               when (BDTOTLANACIMA_REAL > 0) then BDTOTLANACIMA_REAL
               else 0
             end as BDTOTALLANCAMENTO_REAL,
             case
               when (BDPERLANABAIXO_REAL > 0) then BDPERLANABAIXO_REAL * -1
               when (BDPERLANACIMA_REAL > 0) then BDPERLANACIMA_REAL
               else 0
             end as BDPERCENTUALLANCAMENTO_REAL,
             16 as BDTIPOLAN, BDVLRUN_ORC, BDHONORARIO
      from (select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
                   BDLANCTAMIN_ORC, cast(BDMINLAN_ORC as integer) as BDMINLAN_ORC, cast(
                   case
                     when ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0) then BDMINLAN_ORC - BDTOTLAN_REAL
                     else 0
                   end as integer) BDTOTLANABAIXO_REAL,
                   case
                     when ((BDMINLAN_ORC <> 0) and ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0)) then 100 - ((BDTOTLAN_REAL * 100) / BDMINLAN_ORC)
                     else 0
                   end BDPERLANABAIXO_REAL,
                   BDLANCTAMAX_ORC, cast(BDMAXLAN_ORC as integer) as BDMAXLAN_ORC, cast(
                   case
                     when ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0) then BDTOTLAN_REAL - BDMAXLAN_ORC
                     else 0
                   end as integer) BDTOTLANACIMA_REAL,
                   case
                     when ((BDMAXLAN_ORC <> 0) and ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0)) then ((BDTOTLAN_REAL * 100) / BDMAXLAN_ORC) - 100
                     else 0
                   end BDPERLANACIMA_REAL, BDVLRUN_ORC, BDHONORARIO
            from (select TREAL.BDCODEMP as BDCODEMP_REAL, TREAL.BDREFEMP as BDREFEMP_REAL,
                         TREAL.BDTOTLAN as BDTOTLAN_REAL, TORC.BDREFORC as BDREFEMP_ORC,
                         TORC.BDCODENQFED as BDCODENQFED_ORC, coalesce(TORC.BDQTDCALCFERIND, 0) as BDLANCTAQTD_ORC,
                         coalesce(TORC.BDCALCFERINDMIN, 0) as BDLANCTAMIN_ORC,
                         case
                           when ((TORC.BDQTDCALCFERIND - (TORC.BDQTDCALCFERIND * (TORC.BDCALCFERINDMIN / 100))) > 0) then (TORC.BDQTDCALCFERIND - (TORC.BDQTDCALCFERIND * (TORC.BDCALCFERINDMIN / 100)))
                           else 0
                         end as BDMINLAN_ORC,
                         coalesce(TORC.BDCALCFERINDMAX, 0) as BDLANCTAMAX_ORC,
                         case
                           when ((TORC.BDQTDCALCFERIND + (TORC.BDQTDCALCFERIND * (TORC.BDCALCFERINDMAX / 100))) > 0) then (TORC.BDQTDCALCFERIND + (TORC.BDQTDCALCFERIND * (TORC.BDCALCFERINDMAX / 100)))
                           else 0
                         end as BDMAXLAN_ORC, TORC.BDCALCFERINDVLRUNI as BDVLRUN_ORC, BDHONORARIO
                  from (select BDCODEMP, count(BDCODEMP) as BDTOTLAN, BDREFINIFE as BDREFEMP
                        from VRH_EMP_TFERIAS
                        where BDREFINIFE between '||PRREFINI||' and '||PRREFFIN||' and
                              upper(coalesce(BDCOLETIVASFE, '||'''FALSE'''||')) = '||'''FALSE'''||' ';
                        IF (PRCODEMP <> '') THEN
                           wsql = wsql||' and BDCODEMP ' || PRCODEMP || ' ';
                        wsql = wsql||'group by BDCODEMP, BDREFEMP) TREAL ';
                        --W152747 - Antony R. (30/03/2022)
                        wsql = wsql||'left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = (select first 1 EMP.BDCHAVEORC
                                                                              from VCT_BASE_ORCADO_EMP EMP
                                                                              inner join VCT_BASE_ORCADO ORC on (ORC.BDCHAVEORC = EMP.BDCHAVEORC)
                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
                                                                                    ORC.BDREFORC <= TREAL.BDREFEMP
                                                                              order by ORC.BDREFORC desc)))) ';
--                  left outer join VCT_BASE_ORCADO_EMP TORCEMP on (TORCEMP.BDCODEMP = TREAL.BDCODEMP)
--                  left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = TORCEMP.BDCHAVEORC and TORC.BDREFORC = (select first 1 TX.BDREFORC
--                                                                                                                     from VCT_BASE_ORCADO TX
--                                                                                                                     inner join VCT_BASE_ORCADO_EMP EMP on (EMP.BDCHAVEORC = TX.BDCHAVEORC)
--                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
--                                                                                                                           TX.BDREFORC <= TREAL.BDREFEMP
--                                                                                                                     order by TX.BDREFORC desc))))';

     FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP_REAL,
    :BDREFEMP_REAL,
    :BDTOTLAN_REAL,
    :BDREFEMP_ORC,
    :BDCODENQFED_ORC,
    :BDLANCTAQTD_ORC,
    :BDLANCTAMIN_ORC,
    :BDMINLAN_ORC,
    :BDTOTLANABAIXO_REAL,
    :BDPERLANABAIXO_REAL,
    :BDLANCTAMAX_ORC,
    :BDMAXLAN_ORC,
    :BDTOTLANACIMA_REAL,
    :BDPERLANACIMA_REAL,
    :BDTOTALLANCAMENTO_REAL,
    :BDPERCENTUALLANCAMENTO_REAL,
    :BDTIPOLAN,
    :BDVLRUN_ORC,
    :BDHONORARIO
  DO
   SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCADISAL(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  WSQL = 'select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
             BDLANCTAMIN_ORC, BDMINLAN_ORC, BDTOTLANABAIXO_REAL, BDPERLANABAIXO_REAL, BDLANCTAMAX_ORC, BDMAXLAN_ORC,
             BDTOTLANACIMA_REAL, BDPERLANACIMA_REAL,
             case
               when (BDTOTLANABAIXO_REAL > 0) then BDTOTLANABAIXO_REAL * -1
               when (BDTOTLANACIMA_REAL > 0) then BDTOTLANACIMA_REAL
               else 0
             end as BDTOTALLANCAMENTO_REAL,
             case
               when (BDPERLANABAIXO_REAL > 0) then BDPERLANABAIXO_REAL * -1
               when (BDPERLANACIMA_REAL > 0) then BDPERLANACIMA_REAL
               else 0
             end as BDPERCENTUALLANCAMENTO_REAL,
             17 as BDTIPOLAN, BDVLRUN_ORC, BDHONORARIO
      from (select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
                   BDLANCTAMIN_ORC, cast(BDMINLAN_ORC as integer) as BDMINLAN_ORC, cast(
                   case
                     when ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0) then BDMINLAN_ORC - BDTOTLAN_REAL
                     else 0
                   end as integer) BDTOTLANABAIXO_REAL,
                   case
                     when ((BDMINLAN_ORC <> 0) and ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0)) then 100 - ((BDTOTLAN_REAL * 100) / BDMINLAN_ORC)
                     else 0
                   end BDPERLANABAIXO_REAL,
                   BDLANCTAMAX_ORC, cast(BDMAXLAN_ORC as integer) as BDMAXLAN_ORC, cast(
                   case
                     when ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0) then BDTOTLAN_REAL - BDMAXLAN_ORC
                     else 0
                   end as integer) BDTOTLANACIMA_REAL,
                   case
                     when ((BDMAXLAN_ORC <> 0) and ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0)) then ((BDTOTLAN_REAL * 100) / BDMAXLAN_ORC) - 100
                     else 0
                   end BDPERLANACIMA_REAL, BDVLRUN_ORC, BDHONORARIO
            from (select TREAL.BDCODEMP as BDCODEMP_REAL, TREAL.BDREFEMP as BDREFEMP_REAL,
                         TREAL.BDTOTLAN as BDTOTLAN_REAL, TORC.BDREFORC as BDREFEMP_ORC,
                         TORC.BDCODENQFED as BDCODENQFED_ORC, coalesce(TORC.BDQTDCALCADISAL, 0) as BDLANCTAQTD_ORC,
                         coalesce(TORC.BDCALCADISALMIN, 0) as BDLANCTAMIN_ORC,
                         case
                           when ((TORC.BDQTDCALCADISAL - (TORC.BDQTDCALCADISAL * (TORC.BDCALCADISALMIN / 100))) > 0) then (TORC.BDQTDCALCADISAL - (TORC.BDQTDCALCADISAL * (TORC.BDCALCADISALMIN / 100)))
                           else 0
                         end as BDMINLAN_ORC,
                         coalesce(TORC.BDCALCADISALMAX, 0) as BDLANCTAMAX_ORC,
                         case
                           when ((TORC.BDQTDCALCADISAL + (TORC.BDQTDCALCADISAL * (TORC.BDCALCADISALMAX / 100))) > 0) then (TORC.BDQTDCALCADISAL + (TORC.BDQTDCALCADISAL * (TORC.BDCALCADISALMAX / 100)))
                           else 0
                         end as BDMAXLAN_ORC, TORC.BDCALCADISALVLRUNI as BDVLRUN_ORC, BDHONORARIO
                  from (select BDCODEMP, count(BDCODEMP) as BDTOTLAN, BDREFAD as BDREFEMP
                        from VRHF_EMP_TADSAL
                        where BDREFAD between '||PRREFINI||' and '||PRREFFIN||' ';
                       IF (PRCODEMP <> '') THEN
                           wsql = wsql||' and BDCODEMP ' || PRCODEMP || ' ';
                        wsql = wsql||'group by BDCODEMP, BDREFEMP) TREAL ';
                        --W152747 - Antony R. (30/03/2022)
                        wsql = wsql||'left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = (select first 1 EMP.BDCHAVEORC
                                                                              from VCT_BASE_ORCADO_EMP EMP
                                                                              inner join VCT_BASE_ORCADO ORC on (ORC.BDCHAVEORC = EMP.BDCHAVEORC)
                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
                                                                                    ORC.BDREFORC <= TREAL.BDREFEMP
                                                                              order by ORC.BDREFORC desc)))) ';
--                  left outer join VCT_BASE_ORCADO_EMP TORCEMP on (TORCEMP.BDCODEMP = TREAL.BDCODEMP)
--                  left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = TORCEMP.BDCHAVEORC and TORC.BDREFORC = (select first 1 TX.BDREFORC
--                                                                                                                     from VCT_BASE_ORCADO TX
--                                                                                                                     inner join VCT_BASE_ORCADO_EMP EMP on (EMP.BDCHAVEORC = TX.BDCHAVEORC)
--                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
--                                                                                                                           TX.BDREFORC <= TREAL.BDREFEMP
--                                                                                                                     order by TX.BDREFORC desc))))';

     FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP_REAL,
    :BDREFEMP_REAL,
    :BDTOTLAN_REAL,
    :BDREFEMP_ORC,
    :BDCODENQFED_ORC,
    :BDLANCTAQTD_ORC,
    :BDLANCTAMIN_ORC,
    :BDMINLAN_ORC,
    :BDTOTLANABAIXO_REAL,
    :BDPERLANABAIXO_REAL,
    :BDLANCTAMAX_ORC,
    :BDMAXLAN_ORC,
    :BDTOTLANACIMA_REAL,
    :BDPERLANACIMA_REAL,
    :BDTOTALLANCAMENTO_REAL,
    :BDPERCENTUALLANCAMENTO_REAL,
    :BDTIPOLAN,
    :BDVLRUN_ORC,
    :BDHONORARIO
  DO
   SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCFOLCOMP(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  WSQL = 'select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
             BDLANCTAMIN_ORC, BDMINLAN_ORC, BDTOTLANABAIXO_REAL, BDPERLANABAIXO_REAL, BDLANCTAMAX_ORC, BDMAXLAN_ORC,
             BDTOTLANACIMA_REAL, BDPERLANACIMA_REAL,
             case
               when (BDTOTLANABAIXO_REAL > 0) then BDTOTLANABAIXO_REAL * -1
               when (BDTOTLANACIMA_REAL > 0) then BDTOTLANACIMA_REAL
               else 0
             end as BDTOTALLANCAMENTO_REAL,
             case
               when (BDPERLANABAIXO_REAL > 0) then BDPERLANABAIXO_REAL * -1
               when (BDPERLANACIMA_REAL > 0) then BDPERLANACIMA_REAL
               else 0
             end as BDPERCENTUALLANCAMENTO_REAL,
             18 as BDTIPOLAN, BDVLRUN_ORC, BDHONORARIO
      from (select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
                   BDLANCTAMIN_ORC, cast(BDMINLAN_ORC as integer) as BDMINLAN_ORC, cast(
                   case
                     when ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0) then BDMINLAN_ORC - BDTOTLAN_REAL
                     else 0
                   end as integer) BDTOTLANABAIXO_REAL,
                   case
                     when ((BDMINLAN_ORC <> 0) and ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0)) then 100 - ((BDTOTLAN_REAL * 100) / BDMINLAN_ORC)
                     else 0
                   end BDPERLANABAIXO_REAL,
                   BDLANCTAMAX_ORC, cast(BDMAXLAN_ORC as integer) as BDMAXLAN_ORC, cast(
                   case
                     when ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0) then BDTOTLAN_REAL - BDMAXLAN_ORC
                     else 0
                   end as integer) BDTOTLANACIMA_REAL,
                   case
                     when ((BDMAXLAN_ORC <> 0) and ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0)) then ((BDTOTLAN_REAL * 100) / BDMAXLAN_ORC) - 100
                     else 0
                   end BDPERLANACIMA_REAL, BDVLRUN_ORC, BDHONORARIO
            from (select TREAL.BDCODEMP as BDCODEMP_REAL, TREAL.BDREFEMP as BDREFEMP_REAL,
                         TREAL.BDTOTLAN as BDTOTLAN_REAL, TORC.BDREFORC as BDREFEMP_ORC,
                         TORC.BDCODENQFED as BDCODENQFED_ORC, coalesce(TORC.BDQTDCALCFOLCOMP, 0) as BDLANCTAQTD_ORC,
                         coalesce(TORC.BDCALCFOLCOMPMIN, 0) as BDLANCTAMIN_ORC,
                         case
                           when ((TORC.BDQTDCALCFOLCOMP - (TORC.BDQTDCALCFOLCOMP * (TORC.BDCALCFOLCOMPMIN / 100))) > 0) then (TORC.BDQTDCALCFOLCOMP - (TORC.BDQTDCALCFOLCOMP * (TORC.BDCALCFOLCOMPMIN / 100)))
                           else 0
                         end as BDMINLAN_ORC,
                         coalesce(TORC.BDCALCFOLCOMPMAX, 0) as BDLANCTAMAX_ORC,
                         case
                           when ((TORC.BDQTDCALCFOLCOMP + (TORC.BDQTDCALCFOLCOMP * (TORC.BDCALCFOLCOMPMAX / 100))) > 0) then (TORC.BDQTDCALCFOLCOMP + (TORC.BDQTDCALCFOLCOMP * (TORC.BDCALCFOLCOMPMAX / 100)))
                           else 0
                         end as BDMAXLAN_ORC, TORC.BDCALCFOLCOMPVLRUNI as BDVLRUN_ORC, BDHONORARIO
                  from (select FN.BDCODEMP, count(FN.BDCODEMP) as BDTOTLAN, FN.BDREFCOMP as BDREFEMP
                        from (select TFC.BDCODEMP, TFC.BDCODCOL, TFC.BDREFCOMP
                              from VRHF_EMP_TFOLHACOMP TFC
                              where TFC.BDREFCOMP between '||PRREFINI||' and '||PRREFFIN||'
                              union all
                              select TFTC.BDCODEMP, TFTC.BDCODCOL, TFTC.BDREFCOMP
                              from VRHF_EMP_TFOLTOMCOMP TFTC
                              where TFTC.BDREFCOMP between '||PRREFINI||' and '||PRREFFIN||') FN
                        left outer join VRH_EMP_TCOLCON C on (C.BDCODEMP = FN.BDCODEMP and C.BDCODCOL = FN.BDCODCOL)
                        where coalesce(C.BDCONTRCOL, 0) = 0 ';
                        IF (PRCODEMP <> '') THEN
                           wsql = wsql||' and FN.BDCODEMP ' || PRCODEMP || ' ';
                        wsql = wsql||'group by BDCODEMP, BDREFEMP) TREAL ';
                        --W152747 - Antony R. (30/03/2022)
                        wsql = wsql||'left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = (select first 1 EMP.BDCHAVEORC
                                                                              from VCT_BASE_ORCADO_EMP EMP
                                                                              inner join VCT_BASE_ORCADO ORC on (ORC.BDCHAVEORC = EMP.BDCHAVEORC)
                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
                                                                                    ORC.BDREFORC <= TREAL.BDREFEMP
                                                                              order by ORC.BDREFORC desc)))) ';
--                  left outer join VCT_BASE_ORCADO_EMP TORCEMP on (TORCEMP.BDCODEMP = TREAL.BDCODEMP)
--                  left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = TORCEMP.BDCHAVEORC and TORC.BDREFORC = (select first 1 TX.BDREFORC
--                                                                                                                     from VCT_BASE_ORCADO TX
--                                                                                                                     inner join VCT_BASE_ORCADO_EMP EMP on (EMP.BDCHAVEORC = TX.BDCHAVEORC)
--                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
--                                                                                                                           TX.BDREFORC <= TREAL.BDREFEMP
--                                                                                                                     order by TX.BDREFORC desc))))';
     FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP_REAL,
    :BDREFEMP_REAL,
    :BDTOTLAN_REAL,
    :BDREFEMP_ORC,
    :BDCODENQFED_ORC,
    :BDLANCTAQTD_ORC,
    :BDLANCTAMIN_ORC,
    :BDMINLAN_ORC,
    :BDTOTLANABAIXO_REAL,
    :BDPERLANABAIXO_REAL,
    :BDLANCTAMAX_ORC,
    :BDMAXLAN_ORC,
    :BDTOTLANACIMA_REAL,
    :BDPERLANACIMA_REAL,
    :BDTOTALLANCAMENTO_REAL,
    :BDPERCENTUALLANCAMENTO_REAL,
    :BDTIPOLAN,
    :BDVLRUN_ORC,
    :BDHONORARIO
  DO
   SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCPLR(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  WSQL = 'select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
             BDLANCTAMIN_ORC, BDMINLAN_ORC, BDTOTLANABAIXO_REAL, BDPERLANABAIXO_REAL, BDLANCTAMAX_ORC, BDMAXLAN_ORC,
             BDTOTLANACIMA_REAL, BDPERLANACIMA_REAL,
             case
               when (BDTOTLANABAIXO_REAL > 0) then BDTOTLANABAIXO_REAL * -1
               when (BDTOTLANACIMA_REAL > 0) then BDTOTLANACIMA_REAL
               else 0
             end as BDTOTALLANCAMENTO_REAL,
             case
               when (BDPERLANABAIXO_REAL > 0) then BDPERLANABAIXO_REAL * -1
               when (BDPERLANACIMA_REAL > 0) then BDPERLANACIMA_REAL
               else 0
             end as BDPERCENTUALLANCAMENTO_REAL,
             19 as BDTIPOLAN, BDVLRUN_ORC, BDHONORARIO
      from (select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
                   BDLANCTAMIN_ORC, cast(BDMINLAN_ORC as integer) as BDMINLAN_ORC, cast(
                   case
                     when ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0) then BDMINLAN_ORC - BDTOTLAN_REAL
                     else 0
                   end as integer) BDTOTLANABAIXO_REAL,
                   case
                     when ((BDMINLAN_ORC <> 0) and ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0)) then 100 - ((BDTOTLAN_REAL * 100) / BDMINLAN_ORC)
                     else 0
                   end BDPERLANABAIXO_REAL,
                   BDLANCTAMAX_ORC, cast(BDMAXLAN_ORC as integer) as BDMAXLAN_ORC, cast(
                   case
                     when ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0) then BDTOTLAN_REAL - BDMAXLAN_ORC
                     else 0
                   end as integer) BDTOTLANACIMA_REAL,
                   case
                     when ((BDMAXLAN_ORC <> 0) and ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0)) then ((BDTOTLAN_REAL * 100) / BDMAXLAN_ORC) - 100
                     else 0
                   end BDPERLANACIMA_REAL, BDVLRUN_ORC, BDHONORARIO
            from (select TREAL.BDCODEMP as BDCODEMP_REAL, TREAL.BDREFEMP as BDREFEMP_REAL,
                         TREAL.BDTOTLAN as BDTOTLAN_REAL, TORC.BDREFORC as BDREFEMP_ORC,
                         TORC.BDCODENQFED as BDCODENQFED_ORC, coalesce(TORC.BDQTDCALCPLR, 0) as BDLANCTAQTD_ORC,
                         coalesce(TORC.BDCALCPLRMIN, 0) as BDLANCTAMIN_ORC,
                         case
                           when ((TORC.BDQTDCALCPLR - (TORC.BDQTDCALCPLR * (TORC.BDCALCPLRMIN / 100))) > 0) then (TORC.BDQTDCALCPLR - (TORC.BDQTDCALCPLR * (TORC.BDCALCPLRMIN / 100)))
                           else 0
                         end as BDMINLAN_ORC,
                         coalesce(TORC.BDCALCPLRMAX, 0) as BDLANCTAMAX_ORC,
                         case
                           when ((TORC.BDQTDCALCPLR + (TORC.BDQTDCALCPLR * (TORC.BDCALCPLRMAX / 100))) > 0) then (TORC.BDQTDCALCPLR + (TORC.BDQTDCALCPLR * (TORC.BDCALCPLRMAX / 100)))
                           else 0
                         end as BDMAXLAN_ORC, TORC.BDCALCPLRVLRUNI as BDVLRUN_ORC, BDHONORARIO
                  from (select BDCODEMP, count(BDCODEMP) as BDTOTLAN, BDREF as BDREFEMP
                        from VRHF_EMP_TFOLHAAVULSA TFA JOIN VRH_BASE_TTIPOCALCAVUL TCA on (TCA.BDCODTCA = TFA.BDCODTCA)
                        where TFA.BDREF between '||PRREFINI||' and '||PRREFFIN||' and
                              TCA.BDCODCTP = 7 ';
                       IF (PRCODEMP <> '') THEN
                           wsql = wsql||' and BDCODEMP ' || PRCODEMP || ' ';
                        wsql = wsql||' group by BDCODEMP, BDREFEMP) TREAL ';
                        --W152747 - Antony R. (30/03/2022)
                        wsql = wsql||'left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = (select first 1 EMP.BDCHAVEORC
                                                                              from VCT_BASE_ORCADO_EMP EMP
                                                                              inner join VCT_BASE_ORCADO ORC on (ORC.BDCHAVEORC = EMP.BDCHAVEORC)
                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
                                                                                    ORC.BDREFORC <= TREAL.BDREFEMP
                                                                              order by ORC.BDREFORC desc)))) ';
--                  left outer join VCT_BASE_ORCADO_EMP TORCEMP on (TORCEMP.BDCODEMP = TREAL.BDCODEMP)
--                  left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = TORCEMP.BDCHAVEORC and TORC.BDREFORC = (select first 1 TX.BDREFORC
--                                                                                                                     from VCT_BASE_ORCADO TX
--                                                                                                                     inner join VCT_BASE_ORCADO_EMP EMP on (EMP.BDCHAVEORC = TX.BDCHAVEORC)
--                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
--                                                                                                                           TX.BDREFORC <= TREAL.BDREFEMP
--                                                                                                                     order by TX.BDREFORC desc))))';

     FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP_REAL,
    :BDREFEMP_REAL,
    :BDTOTLAN_REAL,
    :BDREFEMP_ORC,
    :BDCODENQFED_ORC,
    :BDLANCTAQTD_ORC,
    :BDLANCTAMIN_ORC,
    :BDMINLAN_ORC,
    :BDTOTLANABAIXO_REAL,
    :BDPERLANABAIXO_REAL,
    :BDLANCTAMAX_ORC,
    :BDMAXLAN_ORC,
    :BDTOTLANACIMA_REAL,
    :BDPERLANACIMA_REAL,
    :BDTOTALLANCAMENTO_REAL,
    :BDPERCENTUALLANCAMENTO_REAL,
    :BDTIPOLAN,
    :BDVLRUN_ORC,
    :BDHONORARIO
  DO
   SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALCADI13(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  WSQL = 'select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
             BDLANCTAMIN_ORC, BDMINLAN_ORC, BDTOTLANABAIXO_REAL, BDPERLANABAIXO_REAL, BDLANCTAMAX_ORC, BDMAXLAN_ORC,
             BDTOTLANACIMA_REAL, BDPERLANACIMA_REAL,
             case
               when (BDTOTLANABAIXO_REAL > 0) then BDTOTLANABAIXO_REAL * -1
               when (BDTOTLANACIMA_REAL > 0) then BDTOTLANACIMA_REAL
               else 0
             end as BDTOTALLANCAMENTO_REAL,
             case
               when (BDPERLANABAIXO_REAL > 0) then BDPERLANABAIXO_REAL * -1
               when (BDPERLANACIMA_REAL > 0) then BDPERLANACIMA_REAL
               else 0
             end as BDPERCENTUALLANCAMENTO_REAL,
             20 as BDTIPOLAN, BDVLRUN_ORC, BDHONORARIO
      from (select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
                   BDLANCTAMIN_ORC, cast(BDMINLAN_ORC as integer) as BDMINLAN_ORC, cast(
                   case
                     when ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0) then BDMINLAN_ORC - BDTOTLAN_REAL
                     else 0
                   end as integer) BDTOTLANABAIXO_REAL,
                   case
                     when ((BDMINLAN_ORC <> 0) and ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0)) then 100 - ((BDTOTLAN_REAL * 100) / BDMINLAN_ORC)
                     else 0
                   end BDPERLANABAIXO_REAL,
                   BDLANCTAMAX_ORC, cast(BDMAXLAN_ORC as integer) as BDMAXLAN_ORC, cast(
                   case
                     when ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0) then BDTOTLAN_REAL - BDMAXLAN_ORC
                     else 0
                   end as integer) BDTOTLANACIMA_REAL,
                   case
                     when ((BDMAXLAN_ORC <> 0) and ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0)) then ((BDTOTLAN_REAL * 100) / BDMAXLAN_ORC) - 100
                     else 0
                   end BDPERLANACIMA_REAL, BDVLRUN_ORC, BDHONORARIO
            from (select TREAL.BDCODEMP as BDCODEMP_REAL, TREAL.BDREFEMP as BDREFEMP_REAL,
                         TREAL.BDTOTLAN as BDTOTLAN_REAL, TORC.BDREFORC as BDREFEMP_ORC,
                         TORC.BDCODENQFED as BDCODENQFED_ORC, coalesce(TORC.BDQTDCALCADI13, 0) as BDLANCTAQTD_ORC,
                         coalesce(TORC.BDCALCADI13MIN, 0) as BDLANCTAMIN_ORC,
                         case
                           when ((TORC.BDQTDCALCADI13 - (TORC.BDQTDCALCADI13 * (TORC.BDCALCADI13MIN / 100))) > 0) then (TORC.BDQTDCALCADI13 - (TORC.BDQTDCALCADI13 * (TORC.BDCALCADI13MIN / 100)))
                           else 0
                         end as BDMINLAN_ORC,
                         coalesce(TORC.BDCALCADI13MAX, 0) as BDLANCTAMAX_ORC,
                         case
                           when ((TORC.BDQTDCALCADI13 + (TORC.BDQTDCALCADI13 * (TORC.BDCALCADI13MAX / 100))) > 0) then (TORC.BDQTDCALCADI13 + (TORC.BDQTDCALCADI13 * (TORC.BDCALCADI13MAX / 100)))
                           else 0
                         end as BDMAXLAN_ORC, TORC.BDCALCADI13VLRUNI as BDVLRUN_ORC, BDHONORARIO
                  from (select BDCODEMP, count(BDCODEMP) as BDTOTLAN, BDREFA13 as BDREFEMP
                        from VRHF_EMP_TA13SAL WHERE BDREFA13 between '||PRREFINI||' and '||PRREFFIN||' ';
                        IF (PRCODEMP <> '') THEN
                           wsql = wsql||' and BDCODEMP ' || PRCODEMP || ' ';
                        wsql = wsql||'group by BDCODEMP, BDREFEMP) TREAL ';
                        --W152747 - Antony R. (30/03/2022)
                        wsql = wsql||'left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = (select first 1 EMP.BDCHAVEORC
                                                                              from VCT_BASE_ORCADO_EMP EMP
                                                                              inner join VCT_BASE_ORCADO ORC on (ORC.BDCHAVEORC = EMP.BDCHAVEORC)
                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
                                                                                    ORC.BDREFORC <= TREAL.BDREFEMP
                                                                              order by ORC.BDREFORC desc)))) ';
--                  left outer join VCT_BASE_ORCADO_EMP TORCEMP on (TORCEMP.BDCODEMP = TREAL.BDCODEMP)
--                  left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = TORCEMP.BDCHAVEORC and TORC.BDREFORC = (select first 1 TX.BDREFORC
--                                                                                                                     from VCT_BASE_ORCADO TX
--                                                                                                                     inner join VCT_BASE_ORCADO_EMP EMP on (EMP.BDCHAVEORC = TX.BDCHAVEORC)
--                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
--                                                                                                                           TX.BDREFORC <= TREAL.BDREFEMP
--                                                                                                                     order by TX.BDREFORC desc))))';
     FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP_REAL,
    :BDREFEMP_REAL,
    :BDTOTLAN_REAL,
    :BDREFEMP_ORC,
    :BDCODENQFED_ORC,
    :BDLANCTAQTD_ORC,
    :BDLANCTAMIN_ORC,
    :BDMINLAN_ORC,
    :BDTOTLANABAIXO_REAL,
    :BDPERLANABAIXO_REAL,
    :BDLANCTAMAX_ORC,
    :BDMAXLAN_ORC,
    :BDTOTLANACIMA_REAL,
    :BDPERLANACIMA_REAL,
    :BDTOTALLANCAMENTO_REAL,
    :BDPERCENTUALLANCAMENTO_REAL,
    :BDTIPOLAN,
    :BDVLRUN_ORC,
    :BDHONORARIO
  DO
  SUSPEND;
END^


/* Restore proc. body: SP_SIT_DEC_RHNET */
create or alter procedure SP_SIT_DEC_RHNET (
    PREMP integer,
    PRCOL integer,
    PRDATAINISEFIP date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATAINISEFIP date,
    BDCODSITDEC integer,
    BDDESCSITDEC varchar(70),
    BDQTDDIASATESTADO integer,
    BDDATAINIATES date,
    BDDATAFIMATES date,
    BDIDRHNETDEC integer)
as
begin
  BDCODEMP = premp;
  BDCODCOL = prcol;

  for select first 1 SD.BDDATAINISEFIP, SD.BDDATAINISEFIPDEC, SC.BDCODSIT, PSIT.BDDESCSIT, SC.BDDIASATESTADO, SC.BDDATAFIMATESTADOAUX, SC.BDIDRHNET
      from VRH_EMP_TSITCOL_DEC SD
      join VRH_EMP_TSITCOL SC on (SC.BDCODEMP = SD.BDCODEMP and SC.BDCODCOL = SD.BDCODCOL and SC.BDDATAINISEFIP = SD.BDDATAINISEFIPDEC)
      join VRH_BASE_TPREPSIT PSIT on (PSIT.BDCODSIT = SC.BDCODSIT)
      where SD.BDCODEMP = :premp and SD.BDCODCOL = :prcol and SD.BDDATAINISEFIP = :prdatainisefip
      order by SD.BDCODEMP desc, SD.BDCODCOL desc, SD.BDDATAINISEFIPDEC desc
  into
    :BDDATAINISEFIP, :BDDATAINIATES, :BDCODSITDEC, :BDDESCSITDEC, :BDQTDDIASATESTADO, :BDDATAFIMATES, :BDIDRHNETDEC
  do
    suspend;
end^


CREATE OR ALTER TRIGGER VRH_EMP_TCOL_VINC_AI0 FOR VRH_EMP_TCOL_VINC
ACTIVE AFTER INSERT POSITION 0
AS
  declare variable wrhnet DM_BOOLEAN;
begin
  if (new.bdcodsintrab is not null) then
     begin
       wrhnet = null;
       select first 1 BDRHNET from TEMPRESAS where BDCODEMP = new.bdcodemp into :wrhnet;
       wrhnet = upper(coalesce(wrhnet, 'FALSE'));
       if (wrhnet = 'TRUE') then
          begin
            update or insert into VRH_RHNET_TSINDTRAB (BDCODEMP, BDCODSINTRAB) values (new.bdcodemp, new.bdcodsintrab) matching (BDCODEMP, BDCODSINTRAB);
          end
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_VINC_AU0 FOR VRH_EMP_TCOL_VINC
ACTIVE AFTER UPDATE POSITION 0
AS
  declare variable wrhnet DM_BOOLEAN;

begin
  if (new.bdcodsintrab is not null and new.bdcodsintrab <> old.bdcodsintrab) then
     begin
       wrhnet = null;
       select first 1 BDRHNET from TEMPRESAS where BDCODEMP = new.bdcodemp into :wrhnet;
       wrhnet = upper(coalesce(wrhnet, 'FALSE'));

       if (wrhnet = 'TRUE') then
          begin
            update or insert into VRH_RHNET_TSINDTRAB (BDCODEMP, BDCODSINTRAB) values (new.bdcodemp, new.bdcodsintrab) matching (BDCODEMP, BDCODSINTRAB);
          end
     end

end
^

CREATE OR ALTER TRIGGER VRH_BASE_TSINDTRAB_AD0 FOR VRH_BASE_TSINDTRAB
ACTIVE AFTER DELETE POSITION 0
AS
begin
  delete from VRH_RHNET_TSINDTRAB where BDCODSINTRAB = old.bdcodsintrab;
end
^

CREATE OR ALTER trigger tmp_vef_emp_tmovproent_temp_au0 for tmp_vef_emp_tmovproent_temp
inactive after update position 0
AS
begin
  if ((new.BDORDEM <> old.BDORDEM) or (new.BDORDEMPRO <> old.BDORDEMPRO)) then
    begin
      update TMP_VEF_EMP_TOPMEDENT_TEMP MED
      set MED.BDORDEM = new.BDORDEM,
          MED.BDORDEMPRO = new.BDORDEMPRO
      where MED.BDSESSAO = old.BDSESSAO and
            MED.BDCODEMP = old.BDCODEMP and
            MED.BDCHAVE = old.BDCHAVE and
            MED.BDORDEM = old.BDORDEM and
            MED.BDORDEMPRO = old.BDORDEMPRO;
    end

  execute statement 'alter trigger TMP_VEF_EMP_TMOVPROENT_TEMP_AU0 inactive;';
end
^

CREATE OR ALTER trigger tmp_vef_emp_tmovprosai_temp_au0 for tmp_vef_emp_tmovprosai_temp
inactive after update position 0
as
begin
  if ((new.BDORDEM <> old.BDORDEM) or (new.BDORDEMPRO <> old.BDORDEMPRO)) then
    begin
      update TMP_VEF_EMP_TOPMEDSAI_TEMP MED
      set MED.BDORDEM = new.BDORDEM,
          MED.BDORDEMPRO = new.BDORDEMPRO
      where MED.BDSESSAO = old.BDSESSAO and
            MED.BDCODEMP = old.BDCODEMP and
            MED.BDCHAVE = old.BDCHAVE and
            MED.BDORDEM = old.BDORDEM and
            MED.BDORDEMPRO = old.BDORDEMPRO;
    end

  execute statement 'alter trigger TMP_VEF_EMP_TMOVPROSAI_TEMP_AU0 inactive;';
end
^

create or alter procedure SP_EXPORTA_LOG_E113 (
    PRCODEMP integer,
    PRLOCAL varchar(255),
    PRREFERENCIA char(9))
returns (
    BDFILE varchar(255))
as
declare variable WCODIGO integer;
declare variable WORDEME111_ORI integer;
declare variable WORDEME113_ORI integer;
declare variable WORDEME111_GER integer;
declare variable WORDEME113_GER integer;
declare variable WDATAHORA timestamp;
declare variable WLINHA varchar(255);
begin
  BDFILE = :PRLOCAL;

  NEWFILE(:BDFILE);

  OPENARQ(:BDFILE,:PRCODEMP);
  for select E113.BDCODIGO, E113.BDORDEME111_ORI, E113.BDORDEME113_ORI, E113.BDORDEME111_GER, E113.BDORDEME113_GER, E113.BDDATAHORA
      from VEF_BASE_TLOG_E113 E113
      order by E113.BDCODIGO, E113.BDORDEME111_ORI, E113.BDORDEME113_ORI, E113.BDORDEME111_GER, E113.BDORDEME113_GER, E113.BDDATAHORA
      into :WCODIGO, :WORDEME111_ORI, :WORDEME113_ORI, :WORDEME111_GER, :WORDEME113_GER, :WDATAHORA
  do
    begin
      WLINHA = 'Lançamento de E111 Ordem ' || :WORDEME111_GER || ', E113 ordem: ' || :WORDEME113_GER || ', Aplicada configuração do Sped fiscal ' || :WCODIGO || ' ' || :PRREFERENCIA || ', E111 ordem ' || :WORDEME111_ORI || ', E113 ordem ' || :WORDEME113_ORI;
      WRITELNOA(:WLINHA, :PRCODEMP);
    end
  CLOSEARQ(:BDFILE,:PRCODEMP);

  SUSPEND;
end
^

CREATE OR ALTER procedure SP_E111_E113_AUTO_SPED (
    PRCODEMP integer,
    PRCODIGO integer,
    PRCODPERIODO integer,
    PRREFERENCIA integer,
    PRTOL boolean,
    prsemanal boolean,
    prdataaju varchar(10))
as
declare variable WSQL varchar(30000); /* Select da SP */
declare variable WSUM varchar(500); /* Concatena os  campos que serão somados */
declare variable WDEC varchar(500); /* Concatena os  campos que serão subtraidos */
declare variable WDATA varchar(25); /* Campo da data do tipo do lançamento */
declare variable WNEWORDEME111 integer; /* Ordem gerada para o E111 */
declare variable WLASTORDEME111 integer; /* Útima ordem do E111 na tabela física */
declare variable WLASTORDEME113 integer; /* Última ordem do E113 na tabela temporária */
declare variable WVALOR varchar(30); /* Tipo do cálculo do valor da combobox */
declare variable WCODAJUICMS integer; /* Código de ajuste do E111 */
declare variable WINSERTPROD char(10); /* Campo auxiliar do produto no insert */
declare variable WSELECTPROD char(12); /* Campo auxiliar do produto no select */
declare variable WCODEMP integer;
declare variable WCODIGO integer;
declare variable WORDEMCONFE111 integer;
declare variable WORDEMCONFE113 integer;
declare variable WTIPOMOVIMENTO char(3);
declare variable WTIPOPARTICIPANTE integer;
declare variable WMODELO integer;
declare variable WALIQICMS DM_NUMERIC_7_4_ALIQ;
declare variable WCODSITNF integer;
declare variable WAPLICAR DM_BOOLEAN; /* Aplica os filtros do E113 por produto */
declare variable WTIPOVALOR integer;
declare variable WPERCENTUAL DM_NUMERIC_7_4_ALIQ;
declare variable WTEMFILIAL DM_BOOLEAN;
declare variable WTEMCFOP DM_BOOLEAN;
declare variable WTEMCST DM_BOOLEAN;
declare variable WTEMPROD DM_BOOLEAN;
declare variable WTEMNCM DM_BOOLEAN;
declare variable WSUMVLRPROD DM_BOOLEAN;
declare variable WSUMSEGURO DM_BOOLEAN;
declare variable WSUMDESCONTO DM_BOOLEAN;
declare variable WSUMABAT DM_BOOLEAN;
declare variable WSUMDESPACESS DM_BOOLEAN;
declare variable WSUMVLRIPI DM_BOOLEAN;
declare variable WSUMBCICMS DM_BOOLEAN;
declare variable WSUMVLRSTRET DM_BOOLEAN;
declare variable WSUMVLRICMS DM_BOOLEAN;
declare variable WSUMFRETE DM_BOOLEAN;
declare variable WSUMVLRICMSST DM_BOOLEAN;
declare variable WSUMQTD DM_BOOLEAN;
declare variable WSUMVLRMONODIF DM_BOOLEAN;
declare variable WSUMVLRMONORETANT DM_BOOLEAN;
declare variable WDECVLRPROD DM_BOOLEAN;
declare variable WDECSEGURO DM_BOOLEAN;
declare variable WDECDESCONTO DM_BOOLEAN;
declare variable WDECABAT DM_BOOLEAN;
declare variable WDECDESPACESS DM_BOOLEAN;
declare variable WDECVLRIPI DM_BOOLEAN;
declare variable WDECBCICMS DM_BOOLEAN;
declare variable WDECVLRSTRET DM_BOOLEAN;
declare variable WDECVLRICMS DM_BOOLEAN;
declare variable WDECFRETE DM_BOOLEAN;
declare variable WDECVLRICMSST DM_BOOLEAN;
declare variable WDECQTD DM_BOOLEAN;
declare variable WDECVLRMONODIF DM_BOOLEAN;
declare variable WDECVLRMONORETANT DM_BOOLEAN;
declare variable WSUMANTICMS boolean;
declare variable WSUMDIFALIQ boolean;
declare variable WDECANTICMS boolean;
declare variable WDECDIFALIQ boolean;
DECLARE VARIABLE wDATAJU VARCHAR(20);
begin
  execute statement 'delete from TMP_VEF_EMP_TAJUICMSE113 ';
  execute statement 'delete from VEF_BASE_TLOG_E113 ';

  execute statement 'select first 1 E111.BDORDEME111220 ' ||
                    'from VEF_EMP_TAJUICMSE111 E111 ' ||
                    'order by E111.BDORDEME111220 desc ' into :WLASTORDEME111;

  if (:WLASTORDEME111 is null) then
    begin
      :WLASTORDEME111 = 0;
    end

  for select E113.BDCODEMP, E113.BDCODIGO, E113.BDORDEMCONFE111, E113.BDORDEMCONFE113, iif(E113.BDTIPOMOVIMENTO = 0, 'ENT', 'SAI') as BDTIPOMOVIMENTO,
             E113.BDTIPOPARTICIPANTE, E113.BDMODELO, E113.BDALIQICMS, E113.BDCODSITNF,
             E113.BDAPLICAR, E113.BDTIPOVALOR, E113.BDPERCENTUAL,
             iif(FILIAL.BDCODFILIAL is not null, true, false) as BDTEMFILIAL,
             iif(CFOP.BDCODNAT is not null, true, false) as BDTEMCFOP,
             iif(CST.BDCODCSTICMS is not null, true, false) as BDTEMCST,
             iif(PROD.BDCODPROD is not null, true, false) as BDTEMPROD,
             iif(NCM.BDCODNCM is not null, true, false) as BDTEMNCM, E113.BDSUMVLRPROD, E113.BDSUMSEGURO,
             E113.BDSUMDESCONTO, E113.BDSUMABAT, E113.BDSUMDESPACESS, E113.BDSUMVLRIPI, E113.BDSUMBCICMS,
             E113.BDSUMVLRSTRET, E113.BDSUMVLRICMS, E113.BDSUMFRETE, E113.BDSUMVLRICMSST, E113.BDSUMQTD,
             E113.BDSUMVLRMONODIF, E113.BDSUMVLRMONORETANT, E113.BDDECVLRPROD, E113.BDDECSEGURO, E113.BDDECDESCONTO,
             E113.BDDECABAT, E113.BDDECDESPACESS, E113.BDDECVLRIPI, E113.BDDECBCICMS, E113.BDDECVLRSTRET,
             E113.BDDECVLRICMS, E113.BDDECFRETE, E113.BDDECVLRICMSST, E113.BDDECQTD, E113.BDDECVLRMONODIF,
             E113.BDDECVLRMONORETANT, dense_rank() over(order by E113.BDORDEMCONFE111) + :WLASTORDEME111 as BDNEWORDEME111, E111.BDCODAJUICMS, E113.BDSUMANTICMS, E113.BDSUMDIFALIQ, E113.BDDECANTICMS,
             E113.BDDECDIFALIQ
      from VEF_INT_TSPEDICMSCONFE113 E113
      inner join VEF_INT_TSPEDICMSCONFE111 E111 on (E113.BDCODEMP = E111.BDCODEMP and E113.BDCODIGO = E111.BDCODIGO and E113.BDORDEMCONFE111 = E111.BDORDEMCONFE111)
      left join VEF_INT_E113_FILIAL FILIAL on (E113.BDCODEMP = FILIAL.BDCODEMP and
            E113.BDCODIGO = FILIAL.BDCODIGO and
            E113.BDORDEMCONFE111 = FILIAL.BDORDEMCONFE111 and
            E113.BDORDEMCONFE113 = FILIAL.BDORDEMCONFE113)
      left join VEF_INT_E113_CFOP CFOP on (E113.BDCODEMP = CFOP.BDCODEMP and
            E113.BDCODIGO = CFOP.BDCODIGO and
            E113.BDORDEMCONFE111 = CFOP.BDORDEMCONFE111 and
            E113.BDORDEMCONFE113 = CFOP.BDORDEMCONFE113)
      left join VEF_INT_E113_CST CST on (E113.BDCODEMP = CST.BDCODEMP and
            E113.BDCODIGO = CST.BDCODIGO and
            E113.BDORDEMCONFE111 = CST.BDORDEMCONFE111 and
            E113.BDORDEMCONFE113 = CST.BDORDEMCONFE113)
      left join VEF_INT_E113_PROD PROD on (E113.BDCODEMP = PROD.BDCODEMP and
            E113.BDCODIGO = PROD.BDCODIGO and
            E113.BDORDEMCONFE111 = PROD.BDORDEMCONFE111 and
            E113.BDORDEMCONFE113 = PROD.BDORDEMCONFE113)
      left join VEF_INT_E113_NCM NCM on (E113.BDCODEMP = NCM.BDCODEMP and
            E113.BDCODIGO = NCM.BDCODIGO and
            E113.BDORDEMCONFE111 = NCM.BDORDEMCONFE111 and
            E113.BDORDEMCONFE113 = NCM.BDORDEMCONFE113)
      where E113.BDCODEMP = :PRCODEMP and
            E113.BDCODIGO = :PRCODIGO and
            E111.BDTIPOGERACAO = 1
      group by E113.BDCODEMP, E113.BDCODIGO, E113.BDORDEMCONFE111, E113.BDORDEMCONFE113, E113.BDTIPOMOVIMENTO, E113.BDTIPOPARTICIPANTE, E113.BDMODELO, E113.BDALIQICMS, E113.BDCODSITNF, E113.BDAPLICAR, E113.BDTIPOVALOR, E113.BDPERCENTUAL, BDTEMFILIAL, BDTEMCFOP, BDTEMCST, BDTEMPROD, BDTEMNCM, E113.BDSUMVLRPROD, E113.BDSUMSEGURO, E113.BDSUMDESCONTO, E113.BDSUMABAT, E113.BDSUMDESPACESS, E113.BDSUMVLRIPI, E113.BDSUMBCICMS, E113.BDSUMVLRSTRET, E113.BDSUMVLRICMS, E113.BDSUMFRETE, E113.BDSUMVLRICMSST, E113.BDSUMQTD, E113.BDSUMVLRMONODIF, E113.BDSUMVLRMONORETANT, E113.BDDECVLRPROD, E113.BDDECSEGURO, E113.BDDECDESCONTO, E113.BDDECABAT, E113.BDDECDESPACESS, E113.BDDECVLRIPI, E113.BDDECBCICMS, E113.BDDECVLRSTRET, E113.BDDECVLRICMS, E113.BDDECFRETE, E113.BDDECVLRICMSST, E113.BDDECQTD, E113.BDDECVLRMONODIF, E113.BDDECVLRMONORETANT, E111.BDCODAJUICMS, E113.BDSUMANTICMS, E113.BDSUMDIFALIQ, E113.BDDECANTICMS,
             E113.BDDECDIFALIQ
      into :WCODEMP, :WCODIGO, :WORDEMCONFE111, :WORDEMCONFE113, :WTIPOMOVIMENTO, :WTIPOPARTICIPANTE,
           :WMODELO, :WALIQICMS, :WCODSITNF, :WAPLICAR, :WTIPOVALOR, :WPERCENTUAL, :WTEMFILIAL, :WTEMCFOP, :WTEMCST,
           :WTEMPROD, :WTEMNCM, :WSUMVLRPROD, :WSUMSEGURO, :WSUMDESCONTO, :WSUMABAT, :WSUMDESPACESS, :WSUMVLRIPI,
           :WSUMBCICMS, :WSUMVLRSTRET, :WSUMVLRICMS, :WSUMFRETE, :WSUMVLRICMSST, :WSUMQTD, :WSUMVLRMONODIF,
           :WSUMVLRMONORETANT, :WDECVLRPROD, :WDECSEGURO, :WDECDESCONTO, :WDECABAT, :WDECDESPACESS, :WDECVLRIPI,
           :WDECBCICMS, :WDECVLRSTRET, :WDECVLRICMS, :WDECFRETE, :WDECVLRICMSST, :WDECQTD, :WDECVLRMONODIF,
           :WDECVLRMONORETANT, :WNEWORDEME111, :WCODAJUICMS, :WSUMANTICMS, :WSUMDIFALIQ, :WDECANTICMS, :WDECDIFALIQ
  do
  begin
    WSUM = '';
    WDEC = '';
    WVALOR = '';
    WINSERTPROD = '';
    WSELECTPROD = '';
    WLASTORDEME113 = 0;

    execute statement 'select first 1 BDORDEME113240 ' ||
                      'from TMP_VEF_EMP_TAJUICMSE113 ' ||
                      'where BDORDEME111220 = ' || :WNEWORDEME111 ||
                      ' order by BDORDEME113240 desc ' into :WLASTORDEME113;

    if ((:WTIPOVALOR = 1) and (:WPERCENTUAL > 0)) then
      begin
        WVALOR = ' * ' || cast(:WPERCENTUAL/100 as varchar(20));
      end
    else
    if ((:WTIPOVALOR = 2) and (:WPERCENTUAL > 0)) then
      begin
        WVALOR = ' * ' || cast(:WPERCENTUAL as varchar(20));
      end

    if (:WTIPOMOVIMENTO = 'ENT') then
      begin
        WDATA = 'BDDATAENTRADAENT';
      end
    else
      begin
        WDATA = 'BDDATAEMISSAO';
      end

    if (:WAPLICAR = 'TRUE') then
      begin
        WINSERTPROD = 'BDCODPROD,';
        WSELECTPROD = 'G.BDCODPROD,';
      end

    if (:WSUMVLRPROD = 'TRUE') then
      begin
        WSUM = WSUM || 'coalesce(G.BDVLRITEM, 0) + ';
      end
    
    if (:WSUMSEGURO = 'TRUE') then
      begin
        WSUM = WSUM || 'coalesce(G.BDVLRSEGURO, 0) + ';
      end
    
    if (:WSUMDESCONTO = 'TRUE') then
      begin
        WSUM = WSUM || 'coalesce(G.BDDESCONTO, 0) + ';
      end
    
    if (:WSUMABAT = 'TRUE') then
      begin
        WSUM = WSUM || 'coalesce(G.BDVLRABATNT, 0) + ';
      end
    
    if (:WSUMDESPACESS = 'TRUE') then
      begin
        WSUM = WSUM || 'coalesce(G.BDVLRDESPACESSORIA, 0) + ';
      end
    
    if (:WSUMVLRIPI = 'TRUE') then
      begin
        WSUM = WSUM || 'coalesce(G.BDVLRIPI, 0) + ';
      end
    
    if (:WSUMBCICMS = 'TRUE') then
      begin
        WSUM = WSUM || 'coalesce(G.BDBCICMS, 0) + ';
      end
    
    if (:WSUMVLRSTRET = 'TRUE') then
      begin
        WSUM = WSUM || 'coalesce(G.BDVLRICMSSTRET, 0) + ';
      end
    
    if (:WSUMVLRICMS = 'TRUE') then
      begin
        WSUM = WSUM || 'coalesce(G.BDVLRICMS, 0) + ';
      end
    
    if (:WSUMFRETE = 'TRUE') then
      begin
        WSUM = WSUM || 'coalesce(G.BDVLRFRETE, 0) + ';
      end
    
    if (:WSUMVLRICMSST = 'TRUE') then
      begin
        WSUM = WSUM || 'coalesce(G.BDVLRST, 0) + ';
      end
    
    if (:WSUMQTD = 'TRUE') then
      begin
        WSUM = WSUM || 'coalesce(G.BDQTDITEM, 0) + ';
      end
    
    if (:WSUMVLRMONODIF = 'TRUE') then
      begin
        WSUM = WSUM || 'coalesce(G.BDVLRICMSMONODIF, 0) + ';
      end
    
    if (:WSUMVLRMONORETANT = 'TRUE') then
      begin
        WSUM = WSUM || 'coalesce(G.BDVLRICMSMONORETANT, 0) + ';
      end
      
    if (:WSUMANTICMS = 'TRUE') then
      begin
        WSUM = WSUM || 'coalesce(G.BDVLRANTECIPACAO, 0) + ';
      end

    if (:WSUMDIFALIQ = 'TRUE') then
      begin
        WSUM = WSUM || 'coalesce(G.BDVLRDIFALIQ, 0) + ';
      end

    WSUM = WSUM || ' 0 ';
    
    if (:WDECVLRPROD = 'TRUE') then
      begin
        WDEC = WDEC || 'coalesce(G.BDVLRITEM, 0) + ';
      end
    
    if (:WDECSEGURO = 'TRUE') then
      begin
        WDEC = WDEC || 'coalesce(G.BDVLRSEGURO, 0) + ';
      end
    
    if (:WDECDESCONTO = 'TRUE') then
      begin
        WDEC = WDEC || 'coalesce(G.BDDESCONTO, 0) + ';
      end
    
    if (:WDECABAT = 'TRUE') then
      begin
        WDEC = WDEC || 'coalesce(G.BDVLRABATNT, 0) + ';
      end
    
    if (:WDECDESPACESS = 'TRUE') then
      begin
        WDEC = WDEC || 'coalesce(G.BDVLRDESPACESSORIA, 0) + ';
      end
    
    if (:WDECVLRIPI = 'TRUE') then
      begin
        WDEC = WDEC || 'coalesce(G.BDVLRIPI, 0) + ';
      end
    
    if (:WDECBCICMS = 'TRUE') then
      begin
        WDEC = WDEC || 'coalesce(G.BDBCICMS, 0) + ';
      end
    
    if (:WDECVLRSTRET = 'TRUE') then
      begin
        WDEC = WDEC || 'coalesce(G.BDVLRICMSSTRET, 0) + ';
      end
    
    if (:WDECVLRICMS = 'TRUE') then
      begin
        WDEC = WDEC || 'coalesce(G.BDVLRICMS, 0) + ';
      end
    
    if (:WDECFRETE = 'TRUE') then
      begin
        WDEC = WDEC || 'coalesce(G.BDVLRFRETE, 0) + ';
      end
    
    if (:WDECVLRICMSST = 'TRUE') then
      begin
        WDEC = WDEC || 'coalesce(G.BDVLRST, 0) + ';
      end
    
    if (:WDECQTD = 'TRUE') then
      begin
        WDEC = WDEC || 'coalesce(G.BDQTDITEM, 0) + ';
      end
    
    if (:WDECVLRMONODIF = 'TRUE') then
      begin
        WDEC = WDEC || 'coalesce(G.BDVLRICMSMONODIF, 0) + ';
      end
    
    if (:WDECVLRMONORETANT = 'TRUE') then
      begin
        WDEC = WDEC || 'coalesce(G.BDVLRICMSMONORETANT, 0) + ';
      end
      
    if (:WDECANTICMS = 'TRUE') then
      begin
        WDEC = WDEC || 'coalesce(G.BDVLRANTECIPACAO, 0) + ';
      end

    if (:WDECDIFALIQ = 'TRUE') then
      begin
        WDEC = WDEC || 'coalesce(G.BDVLRDIFALIQ, 0) + ';
      end

    WDEC = WDEC || ' 0 ';

    if (:WSUM <> ' 0 ') then
      begin
    WSQL = 'insert into TMP_VEF_EMP_TAJUICMSE113(BDCODEMP, BDORDEME111220, BDORDEME113240, BDCODTER, ' || :WINSERTPROD || ' BDNUMDOC, BDSERIE, ' ||
                                                'BDSUBSERIE, BDVLRAJUSTE, BDDATAEMISAO, BDCHAVENFE, BDCODDOCFIS, BDCODAJUICMS) ' ||
    'select GYATT.* ' ||
    'from (select G.BDCODEMP, ' || :WNEWORDEME111 || ' as BDORDEME111220, row_number() over(order by G.BDCODEMP) + ' || :WLASTORDEME113 || ' as BDORDEME113240, ' ||
                     'G.BDCODTER, ' || :WSELECTPROD || ' G.BDNUMDOCINI, G.BDSERIE, G.BDSUBSERIE, cast((sum(' || WSUM || ') - sum(' || WDEC || ')) ' || :WVALOR || ' as numeric(15, 2)) as BDTOTAL, ' ||
                 'G.' || :WDATA || ', G.BDCHAVENFE, G.BDCODDOCFIS, ' || :WCODAJUICMS || ' as BDCODTIPO ' ||
              'from (select ' || :WCODEMP || ' as BDCODEMP, MOV.BDCHAVE, ITEM.BDORDEM, MOV.BDCODTER, DOC.BDCODDOCFIS, PROD.BDCODPROD, ' ||
                           'MIN(prod.bdORDEMPRO) OVER(PARTITION BY PROD.BDCODEMP,PROD.BDCHAVE,PROD.BDORDEM) AS bdORDEMPRO_MIN, '|| -- Alt.: #247094
                           'MOV.BDSERIE, MOV.BDSUBSERIE, MOV.BDNUMDOCINI, MOV.' || WDATA || ', MOV.BDCHAVENFE, ' ||
                           'MOV.BDCODTIPO, MOV.BDCODSITNF, ITEM.BDCODNAT, ITEM.BDCODCSTICMS, ' ||
                           'iif(MOV.BDMODELO in (7, 8, 9, 10, 11, 26, 27, 57, 63, 67), coalesce(ITEM.BDVLRCONTAB, 0), coalesce(PROD.BDVLRITEM, 0)) as BDVLRITEM, ' ||
                           'coalesce(PROD.BDVLRSEGURO, 0) as BDVLRSEGURO, ' ||
                           'iif(MOV.BDMODELO in (7, 8, 9, 10, 11, 26, 27, 57, 63, 67), coalesce(ITEM.BDDESCONTO, 0), coalesce(PROD.BDVLRDESC, 0)) as BDDESCONTO, ' ||
                       'coalesce(PROD.BDVLRABATNT, 0) as BDVLRABATNT, ' ||
                       'coalesce(PROD.BDVLRDESPACESSORIA, 0) as BDVLRDESPACESSORIA, ' ||
                           'iif(MOV.BDMODELO in (7, 8, 9, 10, 11, 26, 27, 57, 63, 67), coalesce(ITEM.BDVLRIPI, 0), coalesce(PROD.BDVLRIPI, 0)) as BDVLRIPI, ';

    if (:WTIPOMOVIMENTO = 'ENT') then
      begin
            WSQL = WSQL || 'case ' ||
                             'when MOV.BDMODELO in (7, 8, 9, 10, 11, 26, 27, 57, 63, 67) then coalesce(ITEM.BDBASEICMS, 0) ' ||
                             'when MOV.BDMODELO in (21, 22, 62) then coalesce(D590.BDBCICMS, coalesce(ITEM.BDBASEICMS, 0)) ' ||
                             'when MOV.BDMODELO in (6, 28, 29, 66) then coalesce(C590.BDBCICMS, coalesce(ITEM.BDBASEICMS, 0)) ' ||
                             'else coalesce(PROD.BDBCICMS, 0) ' ||
                           'end as BDBCICMS, ' ||
                           'case ' ||
                             'when MOV.BDMODELO in (7, 8, 9, 10, 11, 26, 27, 57, 63, 67) then coalesce(ITEM.BDVLRICMS, 0) ' ||
                             'when MOV.BDMODELO in (21, 22, 62) then coalesce(D590.BDVLRICMS, coalesce(ITEM.BDVLRICMS, 0)) ' ||
                             'when MOV.BDMODELO in (6, 28, 29, 66) then coalesce(C590.BDVLRICMS, coalesce(ITEM.BDVLRICMS, 0))' ||
                             'else coalesce(PROD.BDVLRICMS, 0) ' ||
                           'end as BDVLRICMS, ' ||
                           'iif(MOV.BDMODELO in (7, 8, 9, 10, 11, 26, 27, 57, 63, 67), coalesce(ITEM.BDICMSRETENT, 0), coalesce(PROD.BDVLRICMSSTRET, 0)) as BDVLRICMSSTRET, ' ||
                           /* Alt.: #247094 - Esses campos sao da capa, entao so vao retornar no primeiro produto, C590 ou D590 para nao multiplicar...
                           'COALESCE(ANT_DIFALIQ.BDVLRANTECIPACAO, 0) AS BDVLRANTECIPACAO, ' ||
                           'COALESCE(ANT_DIFALIQ.BDVLRDIFALIQ, 0) AS BDVLRDIFALIQ, '; */
                           'COALESCE(IIF(MIN(COALESCE(prod.bdORDEMPRO,0)) OVER(PARTITION BY PROD.BDCODEMP,PROD.BDCHAVE,PROD.BDORDEM) = COALESCE(prod.bdORDEMPRO,0) AND '||
                                        'MIN(COALESCE(C590.BDORDEMTOT, 0)) OVER(PARTITION BY C590.BDCODEMP, C590.BDCHAVE, C590.BDORDEM) = COALESCE(C590.BDORDEMTOT, 0) AND '||
                                        'MIN(COALESCE(D590.BDORDEMTOT, 0)) OVER(PARTITION BY D590.BDCODEMP, D590.BDCHAVE, D590.BDORDEM) = COALESCE(D590.BDORDEMTOT, 0),ANT_DIFALIQ.BDVLRANTECIPACAO,NULL), 0) AS BDVLRANTECIPACAO, ' ||
                           'COALESCE(IIF(MIN(COALESCE(prod.bdORDEMPRO,0)) OVER(PARTITION BY PROD.BDCODEMP,PROD.BDCHAVE,PROD.BDORDEM) = COALESCE(prod.bdORDEMPRO,0) AND '||
                                        'MIN(COALESCE(C590.BDORDEMTOT, 0)) OVER(PARTITION BY C590.BDCODEMP, C590.BDCHAVE, C590.BDORDEM) = COALESCE(C590.BDORDEMTOT, 0) AND '||
                                        'MIN(COALESCE(D590.BDORDEMTOT, 0)) OVER(PARTITION BY D590.BDCODEMP, D590.BDCHAVE, D590.BDORDEM) = COALESCE(D590.BDORDEMTOT, 0),ANT_DIFALIQ.BDVLRDIFALIQ,NULL), 0) AS BDVLRDIFALIQ, ';

      end
    else
      begin
            WSQL = WSQL || 'case ' ||
                             'when MOV.BDMODELO in (7, 8, 9, 10, 11, 26, 27, 57, 63, 67) then coalesce(ITEM.BDBASEICMS, 0) ' ||
                             'else coalesce(PROD.BDBCICMS, 0) ' ||
                           'end as BDBCICMS, ' ||
                           'case ' ||
                             'when MOV.BDMODELO in (7, 8, 9, 10, 11, 26, 27, 57, 63, 67) then coalesce(ITEM.BDVLRICMS, 0) ' ||
                             'else coalesce(PROD.BDVLRICMS, 0) ' ||
                           'end as BDVLRICMS, ' ||
                           'coalesce(PROD.BDVLRICMSSTRET, 0) as BDVLRICMSSTRET, ';
      end

        WSQL = WSQL ||     'coalesce(PROD.BDVLRFRETE, 0) as BDVLRFRETE, ' ||
                           'iif(MOV.BDMODELO in (7, 8, 9, 10, 11, 26, 27, 57, 63, 67), coalesce(ITEM.BDVLRST, 0), coalesce(PROD.BDVLRST, 0)) as BDVLRST, ' ||
                       'coalesce(PROD.BDQTDITEM, 0) as BDQTDITEM, ' ||
                       'coalesce(PROD.BDVLRICMSMONODIF, 0) as BDVLRICMSMONODIF, ' ||
                       'coalesce(PROD.BDVLRICMSMONORETANT, 0) as BDVLRICMSMONORETANT ' ||
                    'from VEF_EMP_TMOV' || :WTIPOMOVIMENTO || ' MOV ';

        if (:WTEMFILIAL = 'TRUE') then
          begin
            WSQL = WSQL || 'inner join(select FILIAL.BDCODFILIAL ' ||
                                      'from VEF_INT_E113_FILIAL FILIAL ' ||
                                      'where FILIAL.BDCODEMP = ' || :WCODEMP || ' and ' ||
                                            'FILIAL.BDCODIGO = ' || :WCODIGO || ' and ' ||
                                            'FILIAL.BDORDEMCONFE111 = ' || :WORDEMCONFE111 || ' and ' ||
                                            'FILIAL.BDORDEMCONFE113 = ' || :WORDEMCONFE113 || ') FILIAL on (MOV.BDCODEMP = FILIAL.BDCODFILIAL) ';
          end

        WSQL = WSQL || 'inner join VEF_EMP_TMOV' || :WTIPOMOVIMENTO || 'ITENS ITEM on (MOV.BDCODEMP = ITEM.BDCODEMP and MOV.BDCHAVE = ITEM.BDCHAVE) ' ||
                'left join VEF_EMP_TMOVPRO' || :WTIPOMOVIMENTO || ' PROD on (ITEM.BDCODEMP = PROD.BDCODEMP and ITEM.BDCHAVE = PROD.BDCHAVE and ITEM.BDORDEM = PROD.BDORDEM) ' ||
                'inner join VEF_BASE_TTABMODELOLAN MODLAN on (MOV.BDMODELO = MODLAN.BDMODELO) ' ||
                'left join VEF_BASE_TTABDOCFIS DOC on (MODLAN.BDMODELOSTR = DOC.BDDOCFIS) ';

        if (:WTIPOMOVIMENTO = 'ENT') then
          begin
            WSQL = WSQL || 'left join VEF_EMP_TD590TOTENT D590 on (ITEM.BDCODEMP = D590.BDCODEMP and ITEM.BDCHAVE = D590.BDCHAVE and ITEM.BDORDEM = D590.BDORDEM) ' ||
                           'left join VEF_EMP_TC590TOTENT C590 on (ITEM.BDCODEMP = C590.BDCODEMP and ITEM.BDCHAVE = C590.BDCHAVE and ITEM.BDORDEM = C590.BDORDEM) ' ||
                           'LEFT OUTER JOIN (SELECT ANT_DIFALIQ.BDCODEMP, ANT_DIFALIQ.BDCHAVE, ANT_DIFALIQ.BDORDEM, SUM(COALESCE(ANT_DIFALIQ.BDVLRDIFALIQ, 0)) BDVLRDIFALIQ, ' ||
                                                    'SUM(COALESCE(ANT_DIFALIQ.BDVLRANTECIPACAO, 0)) BDVLRANTECIPACAO ' ||
                                            'FROM (SELECT BDCODEMP, BDCHAVE, BDORDEM, BDVLRDIFENTALIQ BDVLRDIFALIQ, 0 BDVLRANTECIPACAO ' ||
                                                  'FROM VEF_EMP_TMOVENTDIFALIQ ' ||
                                                  'UNION ALL ' ||
                                                  'SELECT BDCODEMP, BDCHAVE, BDORDEM, BDIMPRECOLHER BDVLRDIFALIQ, 0 BDVLRANTECIPACAO ' ||
                                                  'FROM VEF_EMP_TMOVENTDIFPR ' ||
                                                  'UNION ALL ' ||
                                                  'SELECT BDCODEMP, BDCHAVE, BDORDEM, 0 BDVLRDIFALIQ, BDIMPRECOLHER BDVLRANTECIPACAO ' ||
                                                  'FROM VEF_EMP_TMOVENTANTIMP ' ||
                                                  'UNION ALL ' ||
                                                  'SELECT BDCODEMP, BDCHAVE, BDORDEM, 0 BDVLRDIFALIQ, BDVLRANT BDVLRANTECIPACAO ' ||
                                                  'FROM VEF_EMP_TMOVENTANTPR) ANT_DIFALIQ ' ||
                                            'GROUP BY ANT_DIFALIQ.BDCODEMP, ANT_DIFALIQ.BDCHAVE, ANT_DIFALIQ.BDORDEM) ANT_DIFALIQ ON (ANT_DIFALIQ.BDCODEMP = ITEM.BDCODEMP AND ANT_DIFALIQ.BDCHAVE = ITEM.BDCHAVE AND ANT_DIFALIQ.BDORDEM = ITEM.BDORDEM) ';
          end
    
    if (:WTIPOPARTICIPANTE > 0) then
      begin
        WSQL = WSQL || 'inner join(select TER.BDCODTER ' ||
                                  'from TTERCEIRO TER ';
    
        if (WTIPOPARTICIPANTE = 1) then
          begin
            WSQL = WSQL || 'where position(''.'', TER.BDCGCTER) = 3 '; -- PJ
          end
        else
          begin
            WSQL = WSQL || 'where position(''-'', TER.BDCGCTER) = 12 '; -- PF
          end
    
        WSQL = WSQL || ') TER on (MOV.BDCODTER = TER.BDCODTER) ';
      end
    
    if (:WTEMCFOP = 'TRUE') then
      begin
        WSQL = WSQL || 'inner join(select CFOP.BDCODEMP, CFOP.BDCODIGO, CFOP.BDORDEMCONFE111, CFOP.BDORDEMCONFE113, CFOP.BDCODNAT ' ||
                                  'from VEF_INT_E113_CFOP CFOP ' ||
                                  'where CFOP.BDCODEMP = ' || :WCODEMP || ' and ' ||
                                         'CFOP.BDCODIGO = ' || :WCODIGO || ' and ' ||
                                         'CFOP.BDORDEMCONFE111 = ' || :WORDEMCONFE111 || ' and ' ||
                                         'CFOP.BDORDEMCONFE113 = ' || :WORDEMCONFE113 || ') CFOP on (ITEM.BDCODNAT = CFOP.BDCODNAT) ';
      end
    
    if (:WTEMCST = 'TRUE') then
      begin
        WSQL = WSQL || 'inner join(select CST.BDCODEMP, CST.BDCODIGO, CST.BDORDEMCONFE111, CST.BDORDEMCONFE113, CST.BDCODCSTICMS ' ||
                                  'from VEF_INT_E113_CST CST ' ||
                                  'where CST.BDCODEMP = ' || :WCODEMP || ' and ' ||
                                        'CST.BDCODIGO = ' || :WCODIGO || ' and ' ||
                                        'CST.BDORDEMCONFE111 = ' || :WORDEMCONFE111 || ' and ' ||
                                            'CST.BDORDEMCONFE113 = ' || :WORDEMCONFE113 || ') CST on ';

            if (:WTIPOMOVIMENTO = 'ENT') then
              begin
                WSQL = WSQL || '(case ' ||
                                  'when MOV.BDMODELO in (21, 22, 62) then D590.BDCODCSTICMS ' ||
                                  'when MOV.BDMODELO in (6, 28, 29, 66) then C590.BDCODCSTICMS ' ||
                                  --'else ITEM.BDCODCSTICMS ' ||
                                  'else COALESCE(PROD.BDCODCSTICMS,ITEM.BDCODCSTICMS) ' || -- Alt.: #228540 - Segundo a Graci, e eu tenho juizo e nao vou discurtir, deve olhar a CST do produto, entao olhamos o produto e pronto...
                                'end = CST.BDCODCSTICMS) ';
      end
            else
              begin
                --WSQL = WSQL || '(ITEM.BDCODCSTICMS = CST.BDCODCSTICMS) ';
                WSQL = WSQL || ' (COALESCE(PROD.BDCODCSTICMS,ITEM.BDCODCSTICMS) = CST.BDCODCSTICMS) '; -- Alt.: #228540
              end
          end
    
    if (:WTEMPROD = 'TRUE') then
      begin
        WSQL = WSQL || 'inner join(select PROD.BDCODEMP, PROD.BDCODIGO, PROD.BDORDEMCONFE111, PROD.BDORDEMCONFE113, PROD.BDCODPROD ' ||
                                  'from VEF_INT_E113_PROD PROD ' ||
                                  'where PROD.BDCODEMP = ' || :WCODEMP || ' and ' ||
                                        'PROD.BDCODIGO = ' || :WCODIGO || ' and ' ||
                                        'PROD.BDORDEMCONFE111 = ' || :WORDEMCONFE111 || ' and ' ||
                                        'PROD.BDORDEMCONFE113 = ' || :WORDEMCONFE113 || ') FPROD on (PROD.BDCODPROD = FPROD.BDCODPROD) ';
      end
    
    if (:WTEMNCM = 'TRUE') then
      begin
            WSQL = WSQL || 'left join TCADPRO_VINC VPROD on (PROD.BDCODEMP = VPROD.BDCODEMP and PROD.BDCODPROD = VPROD.BDCODPROD) ' ||
                           'inner join(select NCM.BDCODEMP, NCM.BDCODIGO, NCM.BDORDEMCONFE111, NCM.BDORDEMCONFE113, NCM.BDCODNCM ' ||
                                  'from VEF_INT_E113_NCM NCM ' ||
                                  'where NCM.BDCODEMP = ' || :WCODEMP || ' and ' ||
                                        'NCM.BDCODIGO = ' || :WCODIGO || ' and ' ||
                                        'NCM.BDORDEMCONFE111 = ' || :WORDEMCONFE111 || ' and ' ||
                                        'NCM.BDORDEMCONFE113 = ' || :WORDEMCONFE113 || ') NCM on (VPROD.BDNCMPROD = NCM.BDCODNCM) ';
      end
    
    WSQL = WSQL || ' where MOV.BDREFLAN = ' || :PRREFERENCIA || ' and MOV.BDCODSITNF <> 2 ';
    
    if (:WTEMFILIAL = 'FALSE') then
      begin
        WSQL = WSQL || ' and MOV.BDCODEMP = ' || :WCODEMP; -- Empresa do Sped
      end
    
    if (:WMODELO is not null) then
      begin
        WSQL = WSQL || ' and MOV.BDMODELO = ' || :WMODELO; -- Modelo
      end
    
    if (:WCODSITNF is not null) then
      begin
        WSQL = WSQL || ' and MOV.BDCODSITNF = ' || :WCODSITNF; -- Situação
      end
    
    if (:WALIQICMS > 0) then
      begin
            WSQL = WSQL || ' and case ' ||
                                  'when MOV.BDMODELO in (7, 8, 9, 10, 11, 26, 27, 57, 63, 67) then coalesce(ITEM.BDALIQICMS, 0) ';

            if (:WTIPOMOVIMENTO = 'ENT') then
              begin
                WSQL = WSQL ||    'when MOV.BDMODELO in (21, 22, 62) then coalesce(D590.BDALIQICMS, coalesce(ITEM.BDALIQICMS, 0)) ' ||
                                  'when MOV.BDMODELO in (6, 28, 29, 66) then coalesce(C590.BDALIQICMS, coalesce(ITEM.BDALIQICMS, 0)) ';
              end

            WSQL = WSQL ||        'else coalesce(PROD.BDALIQICMS, 0) ' ||
                                'end = ' || :WALIQICMS; -- Alíquota
          end
    
    WSQL = WSQL || ') G ';
        WSQL = WSQL || 'group by G.BDCODEMP, G.BDCHAVE, G.BDCODTER, ' || :WSELECTPROD || ' G.BDNUMDOCINI, G.BDSERIE, G.BDSUBSERIE, G.' || :WDATA || ', G.BDCHAVENFE, G.BDCODDOCFIS) GYATT ';
    WSQL = WSQL || 'where GYATT.BDTOTAL > 0 ';
    
    execute statement :WSQL;
    
    execute statement 'insert into VEF_BASE_TLOG_E113(BDCODIGO, BDORDEME111_ORI, BDORDEME113_ORI, BDORDEME111_GER, BDORDEME113_GER, BDDATAHORA) ' ||
                      'select ' || :WCODIGO || ', ' || :WORDEMCONFE111 || ', ' || :WORDEMCONFE113 || ', E113.BDORDEME111220, E113.BDORDEME113240, current_timestamp ' ||
                      ' from TMP_VEF_EMP_TAJUICMSE113 E113 ' ||
                      'where E113.BDCODEMP = ' || :WCODEMP || ' and ' ||
                            'E113.BDORDEME111220 = ' || :WNEWORDEME111;
  end
  end

  IF (:PRSEMANAL) THEN
    WDATAJU = '''' || :PRDATAAJU || '''';
  ELSE
      WDATAJU = 'null';

  execute statement 'insert into VEF_EMP_TAJUICMSE111 (BDCODEMP, BDORDEME111220, BDCODAJUICMS, BDREFERENCIA, BDVLRAJU, BDCODTIPO, BDDATA) ' ||
                    'select E113.BDCODEMP, E113.BDORDEME111220, E113.BDCODAJUICMS, ' || :PRREFERENCIA || ' as BDREFERENCIA, sum(cast(BDVLRAJUSTE as numeric(15, 2))) as BDTOTAL, 141 as BDTIPO, ' ||
                    :WDATAJU || ' as BDDATA ' ||
                    'from TMP_VEF_EMP_TAJUICMSE113 E113 ' ||
                    'group by E113.BDCODEMP, E113.BDORDEME111220, E113.BDCODAJUICMS ';

  if (:PRTOL = True) then
    begin
  execute statement 'insert into VEF_EMP_TAJUICMSE113(BDCODEMP, BDORDEME111220, BDORDEME113240, BDCODTER, BDCODDOCFIS, BDCODPROD, ' ||
                                                     'BDNUMDOC, BDSERIE, BDSUBSERIE, BDVLRAJUSTE, BDDATAEMISAO, BDCHAVENFE, BDCODTIPO) ' ||
                    'select BDCODEMP, BDORDEME111220, BDORDEME113240, BDCODTER, BDCODDOCFIS, BDCODPROD, BDNUMDOC, BDSERIE, BDSUBSERIE, BDVLRAJUSTE, BDDATAEMISAO, BDCHAVENFE, 141 ' ||
                    'from TMP_VEF_EMP_TAJUICMSE113 ';

  execute statement 'insert into TOL_VEF_EMP_TICMSSPEDGER_E111(BDCODEMP, BDORDEME111220, BDCODPERIODO, BDREFERENCIA) ' ||
                    'select E113.BDCODEMP, E113.BDORDEME111220, ' || :PRCODPERIODO || ', ' || :PRREFERENCIA ||
                    'from TMP_VEF_EMP_TAJUICMSE113 E113 ' ||
                    'group by E113.BDCODEMP, E113.BDORDEME111220 ';
    end

  execute statement 'delete from TMP_VEF_EMP_TAJUICMSE113 ';
end
^

/* Restore proc. body: SP_VRH_EMPS_SIND_RHNET */
create or alter procedure SP_VRH_EMPS_SIND_RHNET (
    PRCODSINTRAB integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDRHNET boolean,
    BDVINCCOL boolean)
as
declare variable WDATA date;
declare variable WREF integer;
declare variable WOK integer;
declare variable WCADCOL integer;
begin
  SELECT CURRENT_DATE FROM RDB$DATABASE into :wdata;

  wref = cast((substring(cast(wdata as varchar(10)) from 1 for 4)||substring(cast(wdata as varchar(10)) from 6 for 2)) as integer);

  for select BDCODEMP from TEMPRESAS where upper(coalesce(BDRHNET, 'FALSE')) = 'TRUE' order by BDCODEMP
  into :BDCODEMP
  do
    begin
      select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :wref order by BDCODEMP desc, BDREFEMP desc into :BDNOMEMP;

      wok = null;
      select first 1 BDCODEMP from VRH_RHNET_TSINDTRAB where BDCODEMP = :BDCODEMP and BDCODSINTRAB = :prcodsintrab into :wok;

      BDRHNET = FALSE;
      if (coalesce(wok, 0) > 0) then
         BDRHNET = TRUE;

      wcadcol = null;
      select first 1 CV.BDCODSINTRAB
      from VRH_EMP_TCOL_VINC CV
      left outer join VRH_EMP_TRESCISAO R on (R.BDCODEMP = CV.BDCODEMP and R.BDCODCOL = CV.BDCODCOL)
      where CV.BDCODEMP = :BDCODEMP and CV.BDCODSINTRAB = :prcodsintrab and ((R.BDDATARESCISAO is null) or (R.BDREFRESCISAO >= :wref))
      into :wcadcol;

      BDVINCCOL = FALSE;
      if (coalesce(wcadcol, 0) > 0) then
         BDVINCCOL = TRUE;

      suspend;
    end
end^

CREATE OR ALTER TRIGGER VRH_RHNET_TSINDTRAB_BIU0 FOR VRH_RHNET_TSINDTRAB
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
  declare variable wok INTEGER;

begin
  wok = null;
  select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where BDCODEMP = new.bdcodemp and BDCODSINTRAB = new.bdcodsintrab into :wok;

  new.bdcadcol = FALSE;
  if (coalesce(wok, 0) > 0) then
     new.bdcadcol = TRUE;
end
^

CREATE OR ALTER TRIGGER VRH_RHNET_TBANCOS_AG_BIU0 FOR VRH_RHNET_TBANCOS_AG
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
  declare variable wok INTEGER;

begin
  wok = null;
  select first 1 BDCODAG from VRHF_EMP_TCOLCON_BANCO where BDCODEMP = new.bdcodemp and BDCODBAN = new.BDCODBAN AND BDCODAG = NEW.BDCODAG into :wok;

  new.bdcadcol = FALSE;
  if (coalesce(wok, 0) > 0) then
     new.bdcadcol = TRUE;
end^

CREATE OR ALTER PROCEDURE SP_VCT_ORC_X_REL_QTDCALC13(
    PRCODEMP VARCHAR(10000),
    PRREFINI INTEGER,
    PRREFFIN INTEGER)
RETURNS (
    BDCODEMP_REAL INTEGER,
    BDREFEMP_REAL INTEGER,
    BDTOTLAN_REAL INTEGER,
    BDREFEMP_ORC INTEGER,
    BDCODENQFED_ORC INTEGER,
    BDLANCTAQTD_ORC INTEGER,
    BDLANCTAMIN_ORC INTEGER,
    BDMINLAN_ORC INTEGER,
    BDTOTLANABAIXO_REAL INTEGER,
    BDPERLANABAIXO_REAL INTEGER,
    BDLANCTAMAX_ORC INTEGER,
    BDMAXLAN_ORC INTEGER,
    BDTOTLANACIMA_REAL INTEGER,
    BDPERLANACIMA_REAL INTEGER,
    BDTOTALLANCAMENTO_REAL INTEGER,
    BDPERCENTUALLANCAMENTO_REAL INTEGER,
    BDTIPOLAN INTEGER,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
AS
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  WSQL = 'select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
             BDLANCTAMIN_ORC, BDMINLAN_ORC, BDTOTLANABAIXO_REAL, BDPERLANABAIXO_REAL, BDLANCTAMAX_ORC, BDMAXLAN_ORC,
             BDTOTLANACIMA_REAL, BDPERLANACIMA_REAL,
             case
               when (BDTOTLANABAIXO_REAL > 0) then BDTOTLANABAIXO_REAL * -1
               when (BDTOTLANACIMA_REAL > 0) then BDTOTLANACIMA_REAL
               else 0
             end as BDTOTALLANCAMENTO_REAL,
             case
               when (BDPERLANABAIXO_REAL > 0) then BDPERLANABAIXO_REAL * -1
               when (BDPERLANACIMA_REAL > 0) then BDPERLANACIMA_REAL
               else 0
             end as BDPERCENTUALLANCAMENTO_REAL,
             21 as BDTIPOLAN, BDVLRUN_ORC, BDHONORARIO
      from (select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,
                   BDLANCTAMIN_ORC, cast(BDMINLAN_ORC as integer) as BDMINLAN_ORC, cast(
                   case
                     when ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0) then BDMINLAN_ORC - BDTOTLAN_REAL
                     else 0
                   end as integer) BDTOTLANABAIXO_REAL,
                   case
                     when ((BDMINLAN_ORC <> 0) and ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0)) then 100 - ((BDTOTLAN_REAL * 100) / BDMINLAN_ORC)
                     else 0
                   end BDPERLANABAIXO_REAL,
                   BDLANCTAMAX_ORC, cast(BDMAXLAN_ORC as integer) as BDMAXLAN_ORC, cast(
                   case
                     when ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0) then BDTOTLAN_REAL - BDMAXLAN_ORC
                     else 0
                   end as integer) BDTOTLANACIMA_REAL,
                   case
                     when ((BDMAXLAN_ORC <> 0) and ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0)) then ((BDTOTLAN_REAL * 100) / BDMAXLAN_ORC) - 100
                     else 0
                   end BDPERLANACIMA_REAL, BDVLRUN_ORC, BDHONORARIO
            from (select TREAL.BDCODEMP as BDCODEMP_REAL, TREAL.BDREFEMP as BDREFEMP_REAL,
                         TREAL.BDTOTLAN as BDTOTLAN_REAL, TORC.BDREFORC as BDREFEMP_ORC,
                         TORC.BDCODENQFED as BDCODENQFED_ORC, coalesce(TORC.BDQTDCALC13, 0) as BDLANCTAQTD_ORC,
                         coalesce(TORC.BDCALC13MIN, 0) as BDLANCTAMIN_ORC,
                         case
                           when ((TORC.BDQTDCALC13 - (TORC.BDQTDCALC13 * (TORC.BDCALC13MIN / 100))) > 0) then (TORC.BDQTDCALC13 - (TORC.BDQTDCALC13 * (TORC.BDCALC13MIN / 100)))
                           else 0
                         end as BDMINLAN_ORC,
                         coalesce(TORC.BDCALC13MAX, 0) as BDLANCTAMAX_ORC,
                         case
                           when ((TORC.BDQTDCALC13 + (TORC.BDQTDCALC13 * (TORC.BDCALC13MAX / 100))) > 0) then (TORC.BDQTDCALC13 + (TORC.BDQTDCALC13 * (TORC.BDCALC13MAX / 100)))
                           else 0
                         end as BDMAXLAN_ORC, TORC.BDCALC13VLRUNI as BDVLRUN_ORC, BDHONORARIO
                  from (select BDCODEMP, count(BDCODEMP) as BDTOTLAN, BDREF13 as BDREFEMP
                        from VRHF_EMP_T13SAL
                        where BDREF13 between '||PRREFINI||' and '||PRREFFIN||' ';
                       IF (PRCODEMP <> '') THEN
                           wsql = wsql||' and BDCODEMP ' || PRCODEMP || ' ';
                        wsql = wsql||'group by BDCODEMP, BDREFEMP) TREAL ';
                        --W152747 - Antony R. (30/03/2022)
                        wsql = wsql||'left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = (select first 1 EMP.BDCHAVEORC
                                                                              from VCT_BASE_ORCADO_EMP EMP
                                                                              inner join VCT_BASE_ORCADO ORC on (ORC.BDCHAVEORC = EMP.BDCHAVEORC)
                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
                                                                                    ORC.BDREFORC <= TREAL.BDREFEMP
                                                                              order by ORC.BDREFORC desc)))) ';
--                  left outer join VCT_BASE_ORCADO_EMP TORCEMP on (TORCEMP.BDCODEMP = TREAL.BDCODEMP)
--                  left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = TORCEMP.BDCHAVEORC and TORC.BDREFORC = (select first 1 TX.BDREFORC
--                                                                                                                     from VCT_BASE_ORCADO TX
--                                                                                                                     inner join VCT_BASE_ORCADO_EMP EMP on (EMP.BDCHAVEORC = TX.BDCHAVEORC)
--                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
--                                                                                                                           TX.BDREFORC <= TREAL.BDREFEMP
--                                                                                                                     order by TX.BDREFORC desc))))';
     FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP_REAL,
    :BDREFEMP_REAL,
    :BDTOTLAN_REAL,
    :BDREFEMP_ORC,
    :BDCODENQFED_ORC,
    :BDLANCTAQTD_ORC,
    :BDLANCTAMIN_ORC,
    :BDMINLAN_ORC,
    :BDTOTLANABAIXO_REAL,
    :BDPERLANABAIXO_REAL,
    :BDLANCTAMAX_ORC,
    :BDMAXLAN_ORC,
    :BDTOTLANACIMA_REAL,
    :BDPERLANACIMA_REAL,
    :BDTOTALLANCAMENTO_REAL,
    :BDPERCENTUALLANCAMENTO_REAL,
    :BDTIPOLAN,
    :BDVLRUN_ORC,
    :BDHONORARIO
  DO
   SUSPEND;
END^


create or alter procedure SP_VCT_ORC_X_REL_QTDCALCCOMP13 (
    PRCODEMP varchar(10000),
    PRREFINI integer,
    PRREFFIN integer)
returns (
    BDCODEMP_REAL integer,
    BDREFEMP_REAL integer,
    BDTOTLAN_REAL integer,
    BDREFEMP_ORC integer,
    BDCODENQFED_ORC integer,
    BDLANCTAQTD_ORC integer,
    BDLANCTAMIN_ORC integer,
    BDMINLAN_ORC integer,
    BDTOTLANABAIXO_REAL integer,
    BDPERLANABAIXO_REAL integer,
    BDLANCTAMAX_ORC integer,
    BDMAXLAN_ORC integer,
    BDTOTLANACIMA_REAL integer,
    BDPERLANACIMA_REAL integer,
    BDTOTALLANCAMENTO_REAL integer,
    BDPERCENTUALLANCAMENTO_REAL integer,
    BDTIPOLAN integer,
    BDVLRUN_ORC numeric(15,2),
    BDHONORARIO numeric(15,2))
as
declare variable WSQL varchar(32700);
BEGIN
  WSQL = 'select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,';
  wsql = wsql||'BDLANCTAMIN_ORC, BDMINLAN_ORC, BDTOTLANABAIXO_REAL, BDPERLANABAIXO_REAL, BDLANCTAMAX_ORC, BDMAXLAN_ORC,';
  wsql = wsql||'BDTOTLANACIMA_REAL, BDPERLANACIMA_REAL,';
  wsql = wsql||'case when(BDTOTLANABAIXO_REAL>0)then BDTOTLANABAIXO_REAL * -1 ';
  wsql = wsql||'when(BDTOTLANACIMA_REAL>0)then BDTOTLANACIMA_REAL else 0 end as BDTOTALLANCAMENTO_REAL,';
  wsql = wsql||'case when(BDPERLANABAIXO_REAL>0)then BDPERLANABAIXO_REAL * -1 ';
  wsql = wsql||'when(BDPERLANACIMA_REAL>0)then BDPERLANACIMA_REAL else 0 end as BDPERCENTUALLANCAMENTO_REAL,';
  wsql = wsql||'22 as BDTIPOLAN, BDVLRUN_ORC, BDHONORARIO ';
  wsql = wsql||'from(select BDCODEMP_REAL, BDREFEMP_REAL, BDTOTLAN_REAL, BDREFEMP_ORC, BDCODENQFED_ORC, BDLANCTAQTD_ORC,';
  wsql = wsql||'BDLANCTAMIN_ORC, cast(BDMINLAN_ORC as integer) as BDMINLAN_ORC,';
  wsql = wsql||'cast(case when((BDMINLAN_ORC - BDTOTLAN_REAL)>0)then BDMINLAN_ORC - BDTOTLAN_REAL else 0 end as integer) BDTOTLANABAIXO_REAL,';
  wsql = wsql||'case when ((BDMINLAN_ORC <> 0) and ((BDMINLAN_ORC - BDTOTLAN_REAL) > 0)) then 100 - ((BDTOTLAN_REAL * 100) / BDMINLAN_ORC) else 0 end BDPERLANABAIXO_REAL,';
  wsql = wsql||'BDLANCTAMAX_ORC, cast(BDMAXLAN_ORC as integer) as BDMAXLAN_ORC, ';
  wsql = wsql||'cast(case when ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0) then BDTOTLAN_REAL - BDMAXLAN_ORC else 0 end as integer) BDTOTLANACIMA_REAL,';
  wsql = wsql||'case when ((BDMAXLAN_ORC <> 0) and ((BDTOTLAN_REAL - BDMAXLAN_ORC) > 0)) then ((BDTOTLAN_REAL * 100) / BDMAXLAN_ORC) - 100 else 0 end BDPERLANACIMA_REAL,';
  wsql = wsql||'BDVLRUN_ORC, BDHONORARIO ';
  wsql = wsql||'from(select TREAL.BDCODEMP as BDCODEMP_REAL, TREAL.BDREFEMP as BDREFEMP_REAL,';
  wsql = wsql||'TREAL.BDTOTLAN as BDTOTLAN_REAL, TORC.BDREFORC as BDREFEMP_ORC,';
  wsql = wsql||'TORC.BDCODENQFED as BDCODENQFED_ORC, coalesce(TORC.BDQTDCALCCOMP13, 0) as BDLANCTAQTD_ORC,';
  wsql = wsql||'coalesce(TORC.BDCALCCOMP13MIN, 0) as BDLANCTAMIN_ORC,';
  wsql = wsql||'case when ((TORC.BDQTDCALCCOMP13 - (TORC.BDQTDCALCCOMP13 * (TORC.BDCALCCOMP13MIN / 100))) > 0) then (TORC.BDQTDCALCCOMP13 - (TORC.BDQTDCALCCOMP13 * (TORC.BDCALCCOMP13MIN / 100))) else 0 end as BDMINLAN_ORC,';
  wsql = wsql||'coalesce(TORC.BDCALCCOMP13MAX, 0) as BDLANCTAMAX_ORC,';
  wsql = wsql||'case when ((TORC.BDQTDCALCCOMP13 + (TORC.BDQTDCALCCOMP13 * (TORC.BDCALCCOMP13MAX / 100))) > 0) then (TORC.BDQTDCALCCOMP13 + (TORC.BDQTDCALCCOMP13 * (TORC.BDCALCCOMP13MAX / 100))) else 0 end as BDMAXLAN_ORC, TORC.BDCALCCOMP13VLRUNI as BDVLRUN_ORC,';
  wsql = wsql||'BDHONORARIO from (select BDCODEMP, count(BDCODEMP) as BDTOTLAN, BDREFC13 as BDREFEMP ';
  wsql = wsql||'from VRHF_EMP_TC13SAL ';
  wsql = wsql||'where BDREFC13 between '||PRREFINI||' and '||PRREFFIN||' and ';
  wsql = wsql||'upper(coalesce(BDPAGOFNC13, '||'''FALSE'''||')) = '||'''FALSE'''||' ';
  iF (PRCODEMP <> '') THEN
     wsql = wsql||' and BDCODEMP ' || PRCODEMP || ' ';
  wsql = wsql||'group by BDCODEMP, BDREFEMP) TREAL ';
  --W152747 - Antony R. (30/03/2022)
  wsql = wsql||'left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = (select first 1 EMP.BDCHAVEORC ';
  wsql = wsql||'from VCT_BASE_ORCADO_EMP EMP ';
  wsql = wsql||'inner join VCT_BASE_ORCADO ORC on (ORC.BDCHAVEORC = EMP.BDCHAVEORC)';
  wsql = wsql||'where EMP.BDCODEMP = TREAL.BDCODEMP ';
  wsql = wsql||'and ORC.BDREFORC <= TREAL.BDREFEMP ';
  wsql = wsql||'order by ORC.BDREFORC desc)))) ';

--                  left outer join VCT_BASE_ORCADO_EMP TORCEMP on (TORCEMP.BDCODEMP = TREAL.BDCODEMP)
--                  left outer join VCT_BASE_ORCADO TORC on (TORC.BDCHAVEORC = TORCEMP.BDCHAVEORC and TORC.BDREFORC = (select first 1 TX.BDREFORC
--                                                                                                                     from VCT_BASE_ORCADO TX
--                                                                                                                     inner join VCT_BASE_ORCADO_EMP EMP on (EMP.BDCHAVEORC = TX.BDCHAVEORC)
--                                                                                                                     where EMP.BDCODEMP = TREAL.BDCODEMP and
--                                                                                                                           TX.BDREFORC <= TREAL.BDREFEMP
--                                                                                                                     order by TX.BDREFORC desc))))';
     FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP_REAL,
    :BDREFEMP_REAL,
    :BDTOTLAN_REAL,
    :BDREFEMP_ORC,
    :BDCODENQFED_ORC,
    :BDLANCTAQTD_ORC,
    :BDLANCTAMIN_ORC,
    :BDMINLAN_ORC,
    :BDTOTLANABAIXO_REAL,
    :BDPERLANABAIXO_REAL,
    :BDLANCTAMAX_ORC,
    :BDMAXLAN_ORC,
    :BDTOTLANACIMA_REAL,
    :BDPERLANACIMA_REAL,
    :BDTOTALLANCAMENTO_REAL,
    :BDPERCENTUALLANCAMENTO_REAL,
    :BDTIPOLAN,
    :BDVLRUN_ORC,
    :BDHONORARIO
  DO
   SUSPEND;
END^


CREATE OR ALTER PROCEDURE SP_CARREGAR_TABELAS_TEMPORARIAS (
    PRINICIALIZANDOSERVIDOR DM_BOOLEAN = 'FALSE')
AS
BEGIN
  /*Sol: 88208 Patrick T. Sá 10/08/2018. Centralizado dentro dessa SP porque tem mais lugares que reiniciam as tabelas temporárias.*/

  /*EXECUTE PROCEDURE CLEAR_ALL_TEMPORARY_TABLE;
  EXECUTE PROCEDURE SP_CARREGAR_TMP_TTERCEIRO(:PRINICIALIZANDOSERVIDOR);*/
  --EXECUTE PROCEDURE SP_CARREGAR_TMP_TCADPRO(:PRINICIALIZANDOSERVIDOR);
  EXECUTE PROCEDURE SP_CARREGAR_TMP_TOBSERVACAO(:PRINICIALIZANDOSERVIDOR);
  --EXECUTE PROCEDURE SP_CARREGAR_TMP_TCADINFCOM(:PRINICIALIZANDOSERVIDOR);
END^


CREATE OR ALTER TRIGGER TR_BF_INSERT_TEMP_TOT_ESOCIAL FOR TEMP_TOTALIZADORES_ESOCIAL
ACTIVE BEFORE INSERT POSITION 0
AS
   DECLARE VARIABLE vCodigo INTEGER;
   DECLARE VARIABLE vNova_Chave INTEGER;
BEGIN
   vcodigo = 0;
   IF ((NEW.bdcodtot IS NULL) OR (NEW.bdcodtot = 0))  THEN
      BEGIN
         SELECT COALESCE(MAX(bdcodtot), 0) + 1 FROM TEMP_TOTALIZADORES_ESOCIAL WHERE bdcodret = NEW.bdcodret INTO vNova_Chave;
         NEW.bdcodtot = vNova_Chave;
      END
   ELSE
      BEGIN
         SELECT bdcodtot FROM TEMP_TOTALIZADORES_ESOCIAL WHERE (bdcodret = NEW.bdcodret) AND (bdcodtot = NEW.bdcodtot)  INTO vcodigo;
         IF (vcodigo > 0) THEN
            BEGIN
               SELECT COALESCE(MAX(bdcodtot), 0) + 1 FROM TEMP_TOTALIZADORES_ESOCIAL WHERE bdcodret = NEW.bdcodret INTO vNova_Chave;
               NEW.bdcodtot = vNova_Chave;
            END
      END
END^


CREATE OR ALTER TRIGGER TR_BF_INSERT_TEMP_RETORNO_EVT FOR TEMP_RETORNO_EVT
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  /* Trigger text */
  vcodigo = 0;
  IF ((NEW.bdcodret IS NULL) OR (NEW.bdcodret = 0)) THEN
     BEGIN
        SELECT COALESCE(MAX(bdcodret), 0) + 1 FROM TEMP_RETORNO_EVT INTO vcodigo;
        NEW.bdcodret = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodret FROM TEMP_RETORNO_EVT WHERE bdcodret = NEW.bdcodret INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(bdcodret)+1),1) FROM TEMP_RETORNO_EVT INTO vcodigo;
           NEW.bdcodret = vcodigo;
         END
    END
END^

CREATE OR ALTER PROCEDURE SP_ATUALIZAR_TMP_DAPI (
    PRSESSAO INTEGER NOT NULL,
    PRTIPOLAN CHAR(3) NOT NULL)
AS
DECLARE VARIABLE WSQL VARCHAR(1000);
BEGIN
  /*151 - Tipo isentas/outras com código inválido.*/
  wSQL =          'INSERT INTO VEF_INCON_TMOV'||:PRTIPOLAN||'(bdcodemp, bdchave, bdordem, bdsessao, BDTIPOISEOUT, BDORDEMST, bdcodinconsistencia, BDTIPOINCON) ';
  wSQL = :wSQL || 'SELECT DAPI.BDCODEMP, DAPI.BDCHAVE, DAPI.BDORDEM, DAPI.BDSESSAO, DAPI.BDTIPOISEOUT, DAPI.BDORDEMST, 151 BDCODINCONSISTENCIA, 19 BDTIPOINCON ';
  wSQL = :wSQL || 'FROM TMP_VEF_EMP_TMOV'||:PRTIPOLAN||'STDAPI_TEMP DAPI ';
  wSQL = :wSQL || 'WHERE DAPI.BDSESSAO = '||:PRSESSAO|| ' ';
  wSQL = :wSQL || 'AND ((DAPI.BDTIPOISEOUT = 0) OR (DAPI.BDTIPOISEOUT IS NULL)) ';
  wSQL = :wSQL || 'GROUP BY DAPI.BDCODEMP, DAPI.BDCHAVE, DAPI.BDORDEM, DAPI.BDSESSAO, DAPI.BDTIPOISEOUT, DAPI.BDORDEMST, BDCODINCONSISTENCIA, BDTIPOINCON;';
  EXECUTE STATEMENT :wSQL;

END^

CREATE OR ALTER TRIGGER vfin_base_tescimposto_bi0 FOR vfin_base_tescimposto
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodesc IS NULL) OR (NEW.bdcodesc = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodesc)),1) FROM tescritorio INTO vcodigo;
        NEW.bdcodesc = vcodigo;
     END
  ELSE
    BEGIN
       SELECT bdcodesc FROM tescritorio WHERE bdcodesc = NEW.bdcodesc INTO vcodigo;

       IF (vcodigo = 0) THEN
         BEGIN
            SELECT COALESCE((MAX(bdcodesc)),1) FROM tescritorio INTO vcodigo;
            NEW.bdcodesc = vcodigo;
         END
    END
END^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TENTINSSCONT_AD0 FOR TOL_VEF_EMP_TENTINSSCONT
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    DELETE FROM vrhf_emp_tnfcont tnf WHERE tnf.bdcodemp = OLD.bdcodemp AND tnf.bdchave = OLD.bdchaverh;
  end
END
^

CREATE OR ALTER TRIGGER TRG_NEW_CHAVE_VRHF_TNFCONT FOR TMP_VRHF_EMP_TNFCONT_TEMP
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  IF (NEW.BDCHAVE > 0) THEN
    BEGIN
      NEW.BDCHAVE = (NEW.BDCHAVE - GETORDEMSEQUENCIAL(1))+1;
    END
END^

CREATE OR ALTER trigger vrh_esocial_solcontingencia_bi0 for vrh_esocial_solcontingencia
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCodigo = 0;
  IF ((NEW.BDCODIGO IS NULL) OR (NEW.BDCODIGO = 0)) THEN
  BEGIN
      SELECT COALESCE((MAX(BDCODIGO) + 1), 1) FROM VRH_ESOCIAL_SOLCONTINGENCIA C where C.bdcodemp = new.bdcodemp and C.bdref = new.bdref INTO vCodigo;
    NEW.BDCODIGO = vCodigo;
  END
END^

CREATE OR ALTER trigger vrh_esocial_tmensagens_bi0 for vrh_esocial_tmensagens
active before insert position 0
as
declare variable VCODIGO integer;
begin
  /* Trigger text */
  VCODIGO = 0;
  if ((new.BDCODMENS is null) or (new.BDCODMENS = 0)) then
  begin
    select coalesce((max(BDCODMENS) + 1), 1)
    from VRH_ESOCIAL_TMENSAGENS
    into VCODIGO;
    new.BDCODMENS = VCODIGO;
  end
end^

CREATE OR ALTER PROCEDURE SP_GET_R1070_ENVIADO (
    PRCODEMP INTEGER,
    PRNROPROCESSO VARCHAR(21),
    PRREFFIM INTEGER)
RETURNS (
    BDEXISTE DM_BOOLEAN)
AS
DECLARE VARIABLE WCODEVT INTEGER;
BEGIN

  SELECT EVT.BDCODEVT
  FROM (
        SELECT EVT.BDCODEVT, (SELECT SP.BDDADO FROM SP_SPLIT(EVT.BDPARAMETROS, '|') SP WHERE SP.BDPOS = 1) BDNROPROCESSO
        FROM VEF_REINF_EVT EVT
        WHERE EVT.BDCODEMP = :PRCODEMP
        AND EVT.BDCODTIPO = 2 /*R-1070*/
        AND EVT.BDCODSTATUS IN(3, 6) /*2 - Sucesso | 6 - Substituido*/
        AND EVT.BDREFERENCIA <= :PRREFFIM
       ) EVT
  WHERE EVT.BDNROPROCESSO = LPAD(:PRNROPROCESSO, 21, '0')
  INTO :wCodEvt;

  IF (ROW_COUNT > 0) THEN
    BDEXISTE = 'TRUE';
  ELSE
    BDEXISTE = 'FALSE';

  SUSPEND;
END^



create or alter procedure SP_COPIA_PLANOCONFIGURACAOSN (
    PRPLANODE integer,
    PRPLANOPARA integer)
as
begin
    /*
      Elizeu - 01-10-18 - criado procedure  no cartão Simples Nacional - Criar plano de configuração para o simples nacional #81223 #68755 #89517 #89811 #Cartão2!
    */
   --pro cfop
    delete from vef_base_tnatopconfsn where BDCODPLANOCONFSN = :PRPLANOPARA;

    INSERT INTO VEF_BASE_TNATOPCONFSN (BDCODNAT, BDCODATIVSIMPNAC, BDCODCONFSN, BDCODBASESN, BDPREPONDERANTE, BDFORMULASUB, BDFORMULAADI, BDCODPLANOCONFSN)
    select                             BDCODNAT, BDCODATIVSIMPNAC, BDCODCONFSN, BDCODBASESN, BDPREPONDERANTE, BDFORMULASUB, BDFORMULAADI, :PRPLANOPARA
    from vef_base_tnatopconfsn where BDCODPLANOCONFSN = :PRPLANODE;

    INSERT INTO VEF_BASE_TNATOPCONFSN_TRIB (BDCODPLANOCONFSN, BDCODNAT, BDCODATIVSIMPNAC, BDCODCONFSN, BDORDEMTRIB, BDCODIMPOSTO, BDCODTIPOIMPOSTO)
    select                                  :PRPLANOPARA, BDCODNAT, BDCODATIVSIMPNAC, BDCODCONFSN, BDORDEMTRIB, BDCODIMPOSTO, BDCODTIPOIMPOSTO
    from  VEF_BASE_TNATOPCONFSN_TRIB where BDCODPLANOCONFSN = :PRPLANODE;

   --atividade municipal
    delete from VEF_BASE_TCONFATVMSN  where BDCODPLANOCONFSN = :PRPLANOPARA;

    INSERT INTO VEF_BASE_TCONFATVMSN (BDCODATIVSIMPNAC, BDCODCID, BDCODATVM, BDCODCONFATVMSN, BDCODBASESN, BDPREPONDERANTE, BDFORMULAADI, BDFORMULASUB, BDCODPLANOCONFSN)
    select                             BDCODATIVSIMPNAC, BDCODCID, BDCODATVM, BDCODCONFATVMSN, BDCODBASESN,BDPREPONDERANTE, BDFORMULAADI, BDFORMULASUB, :PRPLANOPARA
    from VEF_BASE_TCONFATVMSN where BDCODPLANOCONFSN = :PRPLANODE;

    INSERT INTO VEF_BASE_TCONFATVMSN_TRIB (BDCODPLANOCONFSN, BDCODATIVSIMPNAC, BDCODATVM, BDCODCID, BDCODCONFATVMSN, BDORDEMATVTRIB, BDCODIMPOSTO, BDCODTIPOIMPOSTO)
    select                                 :PRPLANOPARA,      BDCODATIVSIMPNAC, BDCODATVM, BDCODCID, BDCODCONFATVMSN, BDORDEMATVTRIB, BDCODIMPOSTO, BDCODTIPOIMPOSTO
    from  VEF_BASE_TCONFATVMSN_TRIB where BDCODPLANOCONFSN = :PRPLANODE;
end^



CREATE OR ALTER trigger vef_reinf_evt_bd0 for vef_reinf_evt
active before delete position 0
AS
begin
  /* Trigger text */
  if ((old.bdcodstatus IN (2,9)) and (old.bdcodtipo = 11) and (upper(old.bddescerro) = 'EM PROCESSAMENTO') ) then
    EXCEPTION EX_REINF_R2099;

  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    if (((old.bdrecibo is not null) and (Trim(old.bdrecibo) <> ''))) then
      EXCEPTION EX_DELETE_REINF_RECIBO;
  end

  if ((select first 1 upper(BDVALUE) from VW_GET_EXCLUIREMPRESAS) = 'TRUE') then
     update vef_reinf_evt set BDCODRETIF = null where bdcodemp = old.bdcodemp and BDCODRETIF = old.bdcodevt;

  if (old.bdcodstatus IN (2,9)) then
     EXCEPTION EX_REINF_ENVIO;
end^

CREATE OR ALTER procedure SP_NAOEXECUTA_TRIGGER_ESTAGIO (PREXECUTATRIGGER DM_BOOLEAN)
AS
BEGIN
    if (prexecutatrigger = 'TRUE') then
        begin
            RDB$SET_CONTEXT('USER_SESSION', 'W_NAOEXECUTA_TRIGGER_ESTAGIO', 'TRUE');
        end

    if (prexecutatrigger = 'FALSE') then
        begin
            RDB$SET_CONTEXT('USER_SESSION', 'W_NAOEXECUTA_TRIGGER_ESTAGIO', 'FALSE');
        end

END^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_ESTAGIO_BIU0 FOR VRH_EMP_TCOLCON_ESTAGIO
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
    DECLARE VARIABLE wSQL                 VARCHAR(1000);
    DECLARE VARIABLE wCodigoColCon        INTEGER;
    DECLARE VARIABLE wAchouNaBaseColCon   VARCHAR(5);
    DECLARE VARIABLE wCodigoSocio         INTEGER;
    DECLARE VARIABLE wAchouNaBaseSocio    VARCHAR(5);
    DECLARE VARIABLE wJaExecutou          VARCHAR(5);
    DECLARE VARIABLE wNaoPodeExecutar     VARCHAR(5);
    DECLARE VARIABLE wCodigo              INTEGER;
    DECLARE VARIABLE wRef              INTEGER;
BEGIN
    /*Verifica se pode executar a trigger, pois so pode executar se estiver importando dados do RHNET*/
    wNaoPodeExecutar = 'FALSE';
    wSQL = 'SELECT RDB$GET_CONTEXT(''USER_SESSION'', ''W_NAOEXECUTA_TRIGGER_ESTAGIO'') AS EXECUTA_TRIGGER FROM RDB$DATABASE';
    EXECUTE STATEMENT wSQL INTO wNaoPodeExecutar;

    if (Coalesce(new.bdcodcolsup,0)<>0) then
        begin
           Select first 1 cad.bdcodcol,bdnomcol,bdcpfcol,max(bdrefcol) from vrh_emp_tcolcon_cad cad
           left join vrh_emp_tcolcon_doc doc on cad.bdcodemp=doc.bdcodemp and cad.bdcodcol=doc.bdcodcol
           where cad.bdcodemp=new.bdcodemp and cad.bdcodcol=new.bdcodcolsup
           group by  cad.bdcodcol,bdnomcol,bdcpfcol into :wcodigo,new.bdnomcoordest,new.bdcpfcoordest,:wref;
        end
    else if ((Coalesce(new.bdcodsocsup,0)<>0)) then
        begin
           select first 1 sref.bdcodsoc,sref.bdnomsoc,soc.bdcgcceisoc,max(sref.bdrefsoc) from EMPRESAS_TSOC_REF sref
           left join empresas_tsoc soc on sref.bdcodemp=soc.bdcodemp and sref.bdcodsoc=soc.bdcodsoc
           where sref.bdcodemp=new.bdcodemp and sref.bdcodsoc=new.bdcodsocsup
           group by  sref.bdcodsoc,soc.bdcgcceisoc,sref.bdnomsoc  into :wcodigo,new.bdnomcoordest,new.bdcpfcoordest,:wref;
        end 

    IF ((wNaoPodeExecutar <> 'TRUE')or (wNaoPodeExecutar is null))  THEN
        BEGIN
            wJaExecutou = 'FALSE';
            IF (NEW.BDCPFCOORDEST <> '') THEN
                BEGIN
                    /******************************************************************************/
                    /*   BUSCA NO CADASTRO DE COLABORADOR PARA VER SE JÁ EXITE O CPF CADASTRADO   */
                    /******************************************************************************/
                    WSQL = ' SELECT FIRST 1'                                ||
                           ' X.BDCODCOL '                                   ||
                           ' FROM VRH_EMP_TCOLCON X '                       ||
                           ' WHERE '                                        ||
                           ' X.BDCODEMP = '  || NEW.BDCODEMP      ||' AND  '||
                           ' X.BDCPFCOL = '''|| NEW.BDCPFCOORDEST ||''''    ||
                           ' ORDER BY '                                     ||
                           ' X.BDCODEMP, X.BDCODCOL ';
                
                    /*EXECUTA*/
                    EXECUTE STATEMENT wSQL INTO wCodigoColCon;
                
                    /*VERIFICA SE ENCONTROU O CÓDIGO NO SQL*/
                    IF ((wCodigoColCon IS NOT NULL) AND (wCodigoColCon > 0)) THEN
                        BEGIN
                            wAchouNaBaseColCon = 'TRUE';
                        END
                    ELSE
                        BEGIN
                            wAchouNaBaseColCon = 'FALSE';
                        END
                
                    /******************************************************************************/
                    /*       BUSCA NO CADASTRO DE SÓCIO PARA VER SE JÁ EXITE O CPF CADASTRADO     */
                    /******************************************************************************/
                    WSQL = ' SELECT FIRST 1'                                   ||
                           ' X.BDCODSOC '                                      ||
                           ' FROM EMPRESAS_TSOC X '                            ||
                           ' WHERE '                                           ||
                           ' X.BDCODEMP    = '  || NEW.BDCODEMP      ||' AND  '||
                           ' X.BDCGCCEISOC = '''|| NEW.BDCPFCOORDEST ||''''    ||
                           ' ORDER BY '                                        ||
                           ' X.BDCODEMP, X.BDCODSOC ';
                
                    /*EXECUTA*/
                    EXECUTE STATEMENT wSQL INTO wCodigoSocio;
                
                    /*VERIFICA SE ENCONTROU O CÓDIGO NO SQL*/
                    IF ((wCodigoSocio IS NOT NULL) AND (wCodigoSocio > 0)) THEN
                        BEGIN
                            wAchouNaBaseSocio = 'TRUE';
                        END
                    ELSE
                        BEGIN
                            wAchouNaBaseSocio = 'FALSE';
                        END
                
                    /******************************************************************************/
                    /*    VERIFICA O QUE DEVE SER FEITO COM A INFORMAÇÃO QUE CHEGOU NA TRIGGER    */
                    /******************************************************************************/
                    if (((wAchouNaBaseColCon = 'TRUE') AND (wAchouNaBaseSocio = 'TRUE')) AND
                        (wJaExecutou         = 'FALSE'                                 )    ) THEN
                        BEGIN
                            /*Se entrar aqui é porque existe um Colaborador/Contribuinte e um Sócio com o mesmo CPF cadastrado no sistema*/
                            NEW.BDCODSOCSUP = NULL;
                            NEW.BDCODCOLSUP = wCodigoColCon;
                            wJaExecutou     = 'TRUE';
                        END
                
                    if (((wAchouNaBaseColCon = 'FALSE') AND (wAchouNaBaseSocio = 'FALSE')) AND
                        (wJaExecutou         = 'FALSE'                                   )    ) THEN
                        BEGIN
                            /*Se entrar aqui é porque não existe nenhum um Colaborador/Contribuinte ou Sócio com o CPF informado na WEB,
                              Então passa Null para os dois campos de coordenador.*/
                            NEW.BDCODSOCSUP = NULL;
                            NEW.BDCODCOLSUP = NULL;
                            wJaExecutou     = 'TRUE';
                        END
                
                    if ((wAchouNaBaseSocio = 'TRUE' ) AND
                        (wJaExecutou       = 'FALSE')    ) THEN
                        BEGIN
                            /*Se entrou aqui quer fizer que o CPF é compatível com sócio, e vai ser salvo como sócio e não como Colaborador/Contribuinte,
                              Então passa NULL para o campo de coordenador Colaborador/Contribuinte e passa o código sócio cordenador dentro do sistema */
                            NEW.BDCODSOCSUP = wCodigoSocio;
                            NEW.BDCODCOLSUP = NULL;
                            wJaExecutou     = 'TRUE';
                        END
                
                    if ((wAchouNaBaseColCon = 'TRUE' ) AND
                        (wJaExecutou        = 'FALSE')    ) THEN
                        BEGIN
                            /*Se entrou aqui quer dizer que é compatível com colaborador, e não vai salvar como coordenador sócio*/
                            NEW.BDCODCOLSUP = wCodigoColCon;
                            NEW.BDCODSOCSUP = NULL;
                            wJaExecutou     = 'TRUE';
                        END
                END
        END
END^

/* Restore proc. body: SP_VRH_EMAILS_RHNETSOCIAL */
create or alter procedure SP_VRH_EMAILS_RHNETSOCIAL (
    PREMP varchar(25000))
returns (
    BDCODEMPRHNET integer,
    BDCODEMP integer,
    BDCODTIPCTRL integer,
    BDEMAIL varchar(20000))
as
declare variable WSQL varchar(32000);
declare variable WEMPRHNETATU integer;
declare variable WEMPATU integer;
declare variable WPROCATU integer;
declare variable WEMAIL varchar(20000);
declare variable WEMPRHNET integer;
declare variable WCODEMP integer;
declare variable WCODTIP integer;
declare variable WEMAL DM_BDEMAIL;
begin
  wsql = 'select coalesce(emp.bdcodweb, emp.bdcodemp) bdcodemprhnet, emp.bdcodemp, notf.bdcodtipctrl, usu.bdemail '||
         'from vct_central_notificacoes notf '||
         'join tusuario usu on usu.bdcodusu = notf.bdcodusu '||
         'join tempresas emp on ((emp.bdcodemp = notf.bdcodemp) or (notf.bdcodemp is null)) '||
         'join vct_base_tipocontrole tpc on (tpc.bdcodtipctrl = notf.bdcodtipctrl) '||
         'where upper(coalesce(emp.bdrhnet, ''FALSE'')) = ''TRUE'' '||
               'and upper(coalesce(usu.bdcontdesativousu, ''FALSE'')) <> ''TRUE'' '||
               'and ((tpc.bdclassificacao like ''2.1.1%'') or (tpc.bdclassificacao = ''2'') or (tpc.bdclassificacao = ''2.1'')) ';


  if (coalesce(premp, '') <> '') then
     wsql = wsql||' and '||premp;

  wsql = wsql||' order by notf.bdcodemp, notf.bdcodtipctrl ';

  wemprhnetatu = 0;
  wempatu = 0;
  wprocatu = -1;
  wemail = '';

  for execute statement wsql
  into
    :wemprhnet, :wcodemp, :wcodtip, :wemal
  do
    begin
      if (wemprhnetatu = 0) then
         wemprhnetatu = wemprhnet;

      if (wempatu = 0) then
         wempatu = wcodemp;

      if (wprocatu = -1) then
         wprocatu = wcodtip;

      if ((wempatu <> wcodemp) or (wprocatu <> wcodtip)) then
         begin
           if (wemail <> '') then
              begin
                bdcodemprhnet = wemprhnetatu;
                bdcodemp = wempatu;
                bdcodtipctrl = wprocatu;
                bdemail = wemail;
                suspend;
              end

           wemprhnetatu = wemprhnet;
           wempatu = wcodemp;
           wprocatu = wcodtip;
           wemail = '';
         end

      if (wemail <> '') then
         wemail = wemail||';';

      wemail = wemail||wemal;
    end

  if (wemail <> '') then
     begin
       bdcodemprhnet = wemprhnetatu;
       bdcodemp = wempatu;
       bdcodtipctrl = wprocatu;
       bdemail = wemail;
       suspend;
     end
end^


create or alter procedure SP_VRH_STANDBY_RHNET (
    PRFILTRO integer)
returns (
    BDCODSB integer,
    BDTIPOSB integer,
    BDDESCRICAOSB varchar(3000))
as
declare variable WSQL varchar(5000);
declare variable WDESC varchar(3000);
declare variable WCODTIPO integer;
declare variable WI integer;
declare variable WF integer;
declare variable WAUX varchar(200);
declare variable WAUX2 varchar(20);
begin
  wsql = 'select SB.BDCODSB, SB.BDDADOSSB, SB.BDTIPOSB, SB.BDCODTIPO '||
         'from VRH_RHNET_TSTANDBY SB ';

  if (coalesce(prfiltro, 0) <> 0) then
     wsql = wsql||'where SB.BDCODTIPO = '||prfiltro;

  wsql = wsql||' order by SB.BDCODSB ';

  for execute statement wsql
  into :BDCODSB, :wdesc, :BDTIPOSB, :wcodtipo
  do
    begin
      -- Exclusão
      if (coalesce(bdtiposb, 0) = 1) then
         begin
            BDDESCRICAOSB = 'Exclusão';
         end
      else
      -- Bancos e agências
      if (coalesce(wcodtipo, 0) = 2) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Banco: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Agência: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Colaborador
      if (coalesce(wcodtipo, 0) = 3) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Empresa: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Colaborador: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Contribuinte
      if (coalesce(wcodtipo, 0) = 4) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Empresa: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Contribuinte: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Dependente
      if (coalesce(wcodtipo, 0) = 5) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Empresa: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Colaborador: '||substring(wdesc from 1 for :wf);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Dependente: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Médico
      if (coalesce(wcodtipo, 0) = 6) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = 'Médico: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Instituição de ensino
      if (coalesce(wcodtipo, 0) = 7) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = 'Instituição de ensino: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Agente de ensino
      if (coalesce(wcodtipo, 0) = 8) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = 'Agente de ensino: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Estágio
      if (coalesce(wcodtipo, 0) = 9) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Empresa: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Colaborador: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Estágio: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Centro de custos
      if (coalesce(wcodtipo, 0) = 10) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Plano: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Centro/tomador: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Empresa: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Motivo de rescisão
      if (coalesce(wcodtipo, 0) = 11) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = 'Código: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Motivo de situação
      if (coalesce(wcodtipo, 0) = 12) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = 'Código: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Função
      if (coalesce(wcodtipo, 0) = 14) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Plano: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Função: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Horário
      if (coalesce(wcodtipo, 0) = 15) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Plano: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Horário: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           waux = '; Empresa: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           waux2 = trim(substring(wdesc from 1 for :wf));

           if (waux2 = '0') then
              waux2 = 'Domingo';
           else
           if (waux2 = '1') then
              waux2 = 'Segunda';
           else
           if (waux2 = '2') then
              waux2 = 'Terça';
           else
           if (waux2 = '3') then
              waux2 = 'Quarta';
           else
           if (waux2 = '4') then
              waux2 = 'Quinta';
           else
           if (waux2 = '5') then
              waux2 = 'Sexta';
           else
           if (waux2 = '6') then
              waux2 = 'Sábado';
           else
              waux2 = '';

           BDDESCRICAOSB = BDDESCRICAOSB||'; Dia da semana: '||waux2;
           BDDESCRICAOSB = BDDESCRICAOSB||waux;
         end
      else
      -- Sindicato
      if (coalesce(wcodtipo, 0) = 16) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Sindicato: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Empresa: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Qualificação cadastral
      if (coalesce(wcodtipo, 0) = 17) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Empresa: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Colaborador/contribuinte: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Mandato CIPA
      if (coalesce(wcodtipo, 0) = 18) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Empresa: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Colaborador: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Código: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Emails notificações
      if (coalesce(wcodtipo, 0) = 19) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Empresa: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           waux2 = trim(substring(wdesc from 1 for :wf));

           if (waux2 = '31') then
              waux2 = '32';

           select first 1 BDDESCRICAO from VCT_BASE_TIPOCONTROLE where BDCODTIPCTRL = :waux2 into :waux;
           BDDESCRICAOSB = BDDESCRICAOSB||'; Notificação: '||waux2||' - '||waux;
         end
      else
      -- Agente causador - CAT
      if (coalesce(wcodtipo, 0) = 20) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = 'Código: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Vínculo entre empresa e banco/agência
      if (coalesce(wcodtipo, 0) = 21) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Empresa: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Banco: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Agência: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Partes atingidas - CAT
      if (coalesce(wcodtipo, 0) = 22) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = 'Código: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Situação geradora - CAT
      if (coalesce(wcodtipo, 0) = 23) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = 'Código: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Feriado
      if (coalesce(wcodtipo, 0) = 24) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Empresa: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           BDDESCRICAOSB = 'Data: '||substring(wdesc from 1 for 2)||'/'||substring(wdesc from 3 for 2)||'/'||substring(wdesc from 5 for 4);
         end
      else
      -- Bloqueios
      if (coalesce(wcodtipo, 0) = 25) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Empresa: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           waux2 = trim(substring(wdesc from 1 for :wf));

           if (waux2 = '3') then
              waux = 'Cadastro de colaborador';
           else
           if (waux2 = '4') then
              waux = 'Cadastro de contribuinte';
           else
           if (waux2 = '5') then
              waux = 'Cadastro de dependente';
           else
           if (waux2 = '6') then
              waux = 'Contrato de estágio';
           else
           if (waux2 = '51') then
              waux = 'Planilha de centro de custos';
           else
           if (waux2 = '52') then
              waux = 'Planilha de lançamento';
           else
           if (waux2 = '53') then
              waux = 'Planilha de valores de planos de saúde';
           else
           if (waux2 = '54') then
              waux = 'Planilha de faltas';
           else
           if (waux2 = '55') then
              waux = 'Planilha de histórico de alocação';
           else
           if (waux2 = '56') then
              waux = 'Planilha de cartão ponto';
           else
           if (waux2 = '57') then
              waux = 'Planilha de atestado de saúde ocupacional';
           else
           if (waux2 = '58') then
              waux = 'Planilha de alvará judicial';
           else
           if (waux2 = '59') then
              waux = 'Planilha de isenções';
           else
           if (waux2 = '60') then
              waux = 'Planilha de processos judiciais';
           else
           if (waux2 = '61') then
              waux = 'Planilha de CAT';
           else
           if (waux2 = '81') then
              waux = 'Agendamento de férias';
           else
           if (waux2 = '82') then
              waux = 'Agendamento de rescisões';
           else
           if (waux2 = '83') then
              waux = 'Agendamento de afastamentos';
           else
           if (waux2 = '84') then
              waux = 'Agendamento de aumento salarial';
           else
           if (waux2 = '85') then
              waux = 'Agendamento de 13º salário';
           else
           if (waux2 = '86') then
              waux = 'Alteração de função ';
           else
           if (waux2 = '87') then
              waux = 'Alteração de quadro de horário';
           else
              waux = 'Outras telas';

           BDDESCRICAOSB = BDDESCRICAOSB||'; Tela: '||waux;
         end
         else
      -- Verba
      if (coalesce(wcodtipo, 0) = 26) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Empresa: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Verba: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Planos de saúde
      if (coalesce(wcodtipo, 0) = 27) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Operadora: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Convênio: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Empresa: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Vínculo com planos de saúde
      if (coalesce(wcodtipo, 0) = 28) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Empresa: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Colaborador: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Operadora: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Convênio: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Empresa
      if (coalesce(wcodtipo, 0) = 29) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = 'Empresa: '||substring(wdesc from 1 for :wf);
         end
      else
      -- Exame toxicológico
      if (coalesce(wcodtipo, 0) = 118) then
         begin
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = 'Empresa: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = position('.', wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Colaborador: '||substring(wdesc from 1 for :wf - 1);
           wi = position('.', wdesc);
           wf = char_length(wdesc);
           wdesc = substring(wdesc from :wi + 1 for :wf);
           wf = char_length(wdesc);
           BDDESCRICAOSB = BDDESCRICAOSB||'; Código: '||substring(wdesc from 1 for :wf);
         end
       else
          BDDESCRICAOSB = wdesc;
      suspend;
    end
end^

create or alter procedure SP_RAZAO_LANCAMENTO_BANC (
    PRCHAVEBAN varchar(1000),
    PRDATAINI date,
    PRDATAFIN date,
    PRMODELO integer = 0)
returns (
    BDCODTIPO integer,
    BDSALDOATUAL numeric(15,2),
    BDSALDOANTERIOR numeric(15,2),
    BDVALORSAIDA numeric(15,2),
    BDVALORENTRADA numeric(15,2),
    BDDESCTIPOLAN varchar(100),
    BDDATALAN date,
    BDCODCLI integer,
    BDNOMCLI varchar(100),
    BDCODFOR integer,
    BDNOMEFOR varchar(100),
    BDCODDESP integer,
    BDDESCDESP varchar(100),
    BDCODOBRSER integer,
    BDDESCRICAO varchar(100),
    BDCHAVECTABAN integer,
    BDDESCCTABAN varchar(200),
    BDCHAVELAN integer,
    BDSTATUS integer,
    BDNOMESC varchar(100),
    BDNUMPAR varchar(100),
    BDORIGEM integer,
    BDSERIE varchar(6),
    BDREF varchar(20),
    BDCHAVECTAPAG integer,
    BDCODESC integer,
    BDVALORLANC numeric(15,2))
as
declare variable WSQL varchar(10000);
declare variable WSALDOANTERIOR numeric(15,2);
declare variable WCTABAN integer;
declare variable WWHERE varchar(500);
BEGIN
  WSALDOANTERIOR = 0;
  WCTABAN = 0;


  if (prmodelo = 0) then -- Serviços/despesas
     begin
       WSQL = 'select BDCHAVELAN, (LAN.BDTIPOMOV) BDSTATUS, (TIPOLAN.BDDESCRICAO) BDDESCTIPOLAN, LAN.BDDATALAN, LAN.BDCODCLI, CLI.BDNOMCLI, LAN.BDCODFOR, FORN.BDNOMEFOR, ';
       WSQL = WSQL || ' LAN.BDCODDESP, DESP.BDDESCDESP, SER.BDCODOBRSER, SER.BDDESCRICAO, CTA.BDCHAVECTABAN, CTA.BDDESCCTABAN, BDVALORLANC ';
       WSQL = WSQL || ' from VFIN_ESC_TLANCBANCARIO LAN ';
       WSQL = WSQL || ' left outer join VW_VFIN_CLIENTES_REF CLI on (CLI.BDCODCLI = LAN.BDCODCLI) ';
       WSQL = WSQL || ' left outer join VW_VFIN_BASE_TFORNECEDOR FORN on (FORN.BDCODFOR = LAN.BDCODFOR) ';
       WSQL = WSQL || ' left outer join VFIN_BASE_TDESPESA DESP on (DESP.BDCODDESP = LAN.BDCODDESP) ';
       WSQL = WSQL || ' left outer join VCT_BASE_SERVICO SER on (SER.BDCODOBRSER = LAN.BDCODOBRSER) ';
       WSQL = WSQL || ' left outer join VFIN_ESC_TCONTASBAN CTA on (CTA.BDCHAVECTABAN = LAN.BDCHAVECTABAN) ';
       WSQL = WSQL || ' left outer join TIPOS_LANCAMENTOS_PADRAO TIPOLAN on (TIPOLAN.BDCODTIPO = LAN.BDCODTIPO) ';

       WWHERE = '';
       if ((PRCHAVEBAN is not null) and (PRCHAVEBAN <> '')) then
           WWHERE = ' LAN.BDCHAVECTABAN in ('||:PRCHAVEBAN||') ';

    if (PRDATAINI is not null) then
          begin
            if (WWHERE <> '') then
                WWHERE = WWHERE||' and ';        ---mm/dd/aaaa
            WWHERE = WWHERE||' (LAN.BDDATALAN >= '||''''||:PRDATAINI||''''||') ';
          end
    
    if (PRDATAFIN is not null) then
         begin
           if (WWHERE <> '') then
              WWHERE = WWHERE||' and ';           ---mm/dd/aaaa
           WWHERE = WWHERE||' (LAN.BDDATALAN <= '||''''||:PRDATAFIN||''''||') ';
         end
    
      if (WWHERE <> '') then
         WSQL = WSQL||' where '||WWHERE;
    
      WSQL = WSQL || ' order by LAN.BDCHAVECTABAN, LAN.BDCHAVECTABAN, LAN.BDDATALAN, LAN.BDCHAVELAN  ';
 
    FOR EXECUTE STATEMENT WSQL
        INTO :BDCHAVELAN, :BDSTATUS, :BDDESCTIPOLAN, :BDDATALAN, :BDCODCLI, :BDNOMCLI, :BDCODFOR, :BDNOMEFOR,
             :BDCODDESP, :BDDESCDESP, :BDCODOBRSER, :BDDESCRICAO, :BDCHAVECTABAN, :BDDESCCTABAN, :BDVALORLANC DO
        BEGIN
          IF (WCTABAN <> BDCHAVECTABAN) THEN
              begin
        --Novo banco zerar a variavel WSALDOANTERIOR pra começar a calcular novamente...
        --Buscar o saldo anterior sempre que for um novo banco porque pode ser que seja um periodo específico...
                WCTABAN = BDCHAVECTABAN;
--        WSQL = 'select coalesce(sum(SAI.BDVALORLANC),0) - coalesce((select sum(ENT.BDVALORLANC) ';
--        WSQL =                                 wsql||' from VFIN_ESC_TLANCBANCARIO ENT';
--        WSQL =                                 wsql||' where ENT.BDCHAVECTABAN = '||BDCHAVECTABAN||' and ';
--        WSQL =                                 wsql||' (ENT.BDDATALAN <= '||''''||BDDATALAN||''''||') and ';
--        WSQL =                                 wsql||'(ENT.BDCHAVELAN < '||BDCHAVELAN||') and ';
--        WSQL =                                 wsql||' ENT.BDTIPOMOV = 1), 0) ';
--        WSQL = wsql||' from VFIN_ESC_TLANCBANCARIO SAI where SAI.BDCHAVECTABAN = '||BDCHAVECTABAN||' and ';
--        WSQL = wsql||' (SAI.BDDATALAN <= '||''''||BDDATALAN||''''||') and ';
--        WSQL = wsql||' (SAI.BDCHAVELAN < '||BDCHAVELAN||') and SAI.BDTIPOMOV = 0 ';
        wsql = 'select sum(coalesce(case when (coalesce(lanc.bdtipomov, 0) = 0) then lanc.bdvalorlanc else lanc.bdvalorlanc*-1 end, 0)) ';
        wsql = wsql||'from VFIN_ESC_TLANCBANCARIO LANC ';
        wsql = wsql||'where LANC.BDCHAVECTABAN ='||bdchavectaban;
        wsql = wsql||'and(LANC.BDDATALAN < '||''''||bddatalan||''''||')';
                EXECUTE STATEMENT WSQL INTO :WSALDOANTERIOR;
              END

          IF (BDSTATUS = 0) THEN
             BEGIN
               BDVALORSAIDA = 0;
               BDVALORENTRADA = BDVALORLANC;
               BDSALDOATUAL = wSALDOANTERIOR + BDVALORLANC;
               BDSALDOANTERIOR = wSALDOANTERIOR;
               wSALDOANTERIOR = wSALDOANTERIOR + BDVALORLANC;
             END
          ELSE
            BEGIN
              BDVALORENTRADA = 0;
              BDVALORSAIDA = BDVALORLANC;
              BDSALDOATUAL = wSALDOANTERIOR - BDVALORLANC;
              BDSALDOANTERIOR = wSALDOANTERIOR;
              wSALDOANTERIOR = wSALDOANTERIOR - BDVALORLANC;
            END
        SUSPEND;
       END
     end
   else
     if (prmodelo = 1) then -- Faturas/contas a pagar
        begin
          wsql = 'select LAN.*, ESC.BDNOMESC, CTA.BDDESCCTABAN, FORN.BDNOMEFOR, CLI.BDNOMCLI, SER.BDDESCRICAO BDDESCSER, DESP.BDDESCDESP, ';
          wsql = wsql||'(case when LAN.BDVALORSAI > 0 then LAN.BDVALORSAI else LAN.BDVALORENT end) BDVALORLANC ';
          wsql = wsql||'from (select LANFAT.BDCODESC, LANFAT.BDCODCLI, 0 BDCODFOR, LANFAT.BDCHAVECTABAN, ';
          wsql = wsql||'LANFAT.BDTIPOMOV, LANFAT.BDDATALAN, FAT.BDREFFAT BDREF, FAT.BDSERIE, 0 as BDCHAVECTAPAG, 0 AS BDCHAVELAN, 1 as BDORIGEM, ';
          wsql = wsql||'(coalesce(sum(LANFAT.BDVALORLANC), 0) - (select coalesce(sum(BDVALORLANC), 0) ';
          wsql = wsql||'from VFIN_ESC_TLANCBANCARIO LAN ';
          wsql = wsql||'where (LAN.BDCHAVEFATURA > 0) and ';
          wsql = wsql||'(LAN.BDTIPOMOV = 1) and ';

          if ((PRCHAVEBAN is not null) and (PRCHAVEBAN <> '')) then
             wsql = wsql||' LAN.BDCHAVECTABAN in ('||:PRCHAVEBAN||') and ';

    if (PRDATAINI is not null) then
             wsql = wsql||'(LAN.BDDATALAN >= '||''''||:PRDATAINI||''''||') and ';

    if (PRDATAFIN is not null) then
             wsql = wsql||'(LAN.BDDATALAN <= '||''''||:PRDATAFIN||''''||') and ';

          wsql = wsql||'(LAN.BDCODESC = LANFAT.BDCODESC) and ';
          wsql = wsql||'(LAN.BDCODCLI = LANFAT.BDCODCLI) and ';
          wsql = wsql||'(LAN.BDCHAVEFATURA = LANFAT.BDCHAVEFATURA))) BDVALORENT, ';
          wsql = wsql||'0 BDVALORSAI, 0 BDCODSER, 0 BDCODDESP, 0 BDNUMPAR, '||'''Fatura'''||' as BDDESCTIPOLAN  ';
          wsql = wsql||'from VFIN_ESC_TLANCBANCARIO LANFAT ';
          wsql = wsql||'left outer join VFIN_ESC_TFATURA FAT on (FAT.BDCODCLI = LANFAT.BDCODCLI and FAT.BDCODESC = LANFAT.BDCODESC and FAT.BDCHAVEFATURA = LANFAT.BDCHAVEFATURA) ';
          wsql = wsql||'where (LANFAT.BDCHAVEFATURA > 0) and ';

          if ((PRCHAVEBAN is not null) and (PRCHAVEBAN <> '')) then
             wsql = wsql||' LANFAT.BDCHAVECTABAN in ('||:PRCHAVEBAN||') and ';

    if (PRDATAINI is not null) then
             wsql = wsql||'(LANFAT.BDDATALAN >= '||''''||:PRDATAINI||''''||') and ';

    if (PRDATAFIN is not null) then
             wsql = wsql||'(LANFAT.BDDATALAN <= '||''''||:PRDATAFIN||''''||') and ';

          wsql = wsql||'(LANFAT.BDTIPOMOV = 0) ';

          wsql = wsql||'group by LANFAT.BDCODESC, LANFAT.BDCODCLI, LANFAT.BDCODFOR, LANFAT.BDCHAVEFATURA, LANFAT.BDCHAVECTABAN, LANFAT.BDDATALAN, LANFAT.BDTIPOMOV, FAT.BDREFFAT, FAT.BDSERIE ';
          wsql = wsql||'union all ';
          wsql = wsql||'select LANPAG.BDCODESC, 0 BDCODCLI, LANPAG.BDCODFOR, LANPAG.BDCHAVECTABAN, ';
          wsql = wsql||'LANPAG.BDTIPOMOV, LANPAG.BDDATALAN, ';
          wsql = wsql||'(case when PARC.BDORDEMPAR is null then PAG.BDREFERENCIA else (select substring(DAT.BDNOVADATA from 1 for 4) || substring(DAT.BDNOVADATA from 6 for 2) ';
          wsql = wsql||'from ADD_MESES(cast(substring(PAG.BDREFERENCIA from 5 for 2) || '||'''/01/'''||' || substring(PAG.BDREFERENCIA from 1 for 4) as date), PARC.BDORDEMPAR - 1) DAT) end) BDREF, ';
          wsql = wsql||''''' as BDSERIE, LANPAG.BDCHAVECTAPAG, 0 as BDCHAVELAN, 2 as BDORIGEM, 0 BDVALORENT, ';
          wsql = wsql||'(coalesce(sum(LANPAG.BDVALORLANC), 0) - (select coalesce(sum(LAN.BDVALORLANC), 0) ';
          wsql = wsql||'from VFIN_ESC_TLANCBANCARIO LAN ';
          wsql = wsql||'left outer join VFIN_ESC_TPARCELAPAGAR PARC2 on (PARC2.BDCODESC = LAN.BDCODESC and PARC2.BDCHAVECTAPAG = LAN.BDCHAVECTAPAG) ';
          wsql = wsql||'where (LAN.BDCHAVECTAPAG > 0) and ';
          wsql = wsql||'(LAN.BDTIPOMOV = 0) and ';

          if ((PRCHAVEBAN is not null) and (PRCHAVEBAN <> '')) then
             wsql = wsql||' LAN.BDCHAVECTABAN in ('||:PRCHAVEBAN||') and ';

    if (PRDATAINI is not null) then
             wsql = wsql||'(LAN.BDDATALAN >= '||''''||:PRDATAINI||''''||') and ';

    if (PRDATAFIN is not null) then
             wsql = wsql||'(LAN.BDDATALAN <= '||''''||:PRDATAFIN||''''||') and ';

          wsql = wsql||'(LAN.BDCODESC = LANPAG.BDCODESC) and ';
          wsql = wsql||'(LAN.BDCODFOR = LANPAG.BDCODFOR) and ';
          wsql = wsql||'(LAN.BDCHAVECTAPAG = LANPAG.BDCHAVECTAPAG) and ';
          wsql = wsql||'((PARC2.BDORDEMPAR = PARC.BDORDEMPAR) or (PARC2.BDORDEMPAR is null and ';
          wsql = wsql||'PARC.BDORDEMPAR is null)))) BDVALORSAI, 0 BDCODSER, 0 BDCODDESP, (PARC.BDNUMPAR || '||'''/'''||' || PAG.BDNUMPARC) BDNUMPAR, '||'''Contas a pagar'''||' as BDDESCTIPOLAN ';
          wsql = wsql||'from VFIN_ESC_TLANCBANCARIO LANPAG ';
          wsql = wsql||'left outer join VFIN_ESC_TCONTASAPAGAR PAG on (PAG.BDCODESC = LANPAG.BDCODESC and PAG.BDCHAVECTAPAG = LANPAG.BDCHAVECTAPAG) ';
          wsql = wsql||'left outer join VFIN_ESC_TPAGDESP PAGDESP on (PAGDESP.BDCODESC = LANPAG.BDCODESC and PAGDESP.BDCHAVECTAPAG = LANPAG.BDCHAVECTAPAG and PAGDESP.BDORDEMPAG = LANPAG.BDORDEMPAG and PAGDESP.BDORDEMDESP = LANPAG.BDORDEMDESP and PAGDESP.BDORDEMPAGDESP = LANPAG.BDORDEMPAGDESP) ';
          wsql = wsql||'left outer join VFIN_ESC_TPAGAMENTOS PGTO on (PGTO.BDCODESC = PAGDESP.BDCODESC and PGTO.BDCHAVECTAPAG = PAGDESP.BDCHAVECTAPAG and PGTO.BDORDEMPAG = PAGDESP.BDORDEMPAG) ';
          wsql = wsql||'left outer join VFIN_ESC_TPARCELAPAGAR PARC on (PARC.BDCODESC = PGTO.BDCODESC and PARC.BDCHAVECTAPAG = PGTO.BDCHAVECTAPAG and PARC.BDORDEMPAR = PGTO.BDORDEMPAR) ';
          wsql = wsql||'where (LANPAG.BDCHAVECTAPAG > 0) and ';

          if ((PRCHAVEBAN is not null) and (PRCHAVEBAN <> '')) then
             wsql = wsql||' LANPAG.BDCHAVECTABAN in ('||:PRCHAVEBAN||') and ';

    if (PRDATAINI is not null) then
             wsql = wsql||'(LANPAG.BDDATALAN >= '||''''||:PRDATAINI||''''||') and ';

    if (PRDATAFIN is not null) then
             wsql = wsql||'(LANPAG.BDDATALAN <= '||''''||:PRDATAFIN||''''||') and ';

          wsql = wsql||'(LANPAG.BDTIPOMOV = 1) ';

          wsql = wsql||'group by LANPAG.BDCODESC, LANPAG.BDCODFOR, LANPAG.BDCHAVECTAPAG, BDSERIE, BDCHAVELAN, LANPAG.BDCHAVECTABAN, LANPAG.BDTIPOMOV, LANPAG.BDDATALAN, PAG.BDREFERENCIA, PARC.BDORDEMPAR, PARC.BDNUMPAR, PAG.BDNUMPARC ';
          wsql = wsql||'union all ';
          wsql = wsql||'select LAN.BDCODESC, LAN.BDCODCLI, LAN.BDCODFOR, LAN.BDCHAVECTABAN, LAN.BDTIPOMOV, ';
          wsql = wsql||'LAN.BDDATALAN, 0 BDREF, '''' as BDSERIE, 0 as BDCHAVECTAPAG, LAN.BDCHAVELAN,  3 as BDORIGEM, ';
          wsql = wsql||'(case when LAN.BDTIPOMOV = 0 then LAN.BDVALORLANC else 0 end) BDVALORENT, (case when LAN.BDTIPOMOV = 1 then LAN.BDVALORLANC else 0 end) BDVALORSAI, ';
          wsql = wsql||'LAN.BDCODOBRSER BDCODSER, LAN.BDCODDESP, 0 as BDNUMPAR, (case when lan.bdcodtipo = 3006 then '||'''Transferência entre contas'''||' else '||'''Manual'''||' end) as BDDESCTIPOLAN ';
          wsql = wsql||'from VFIN_ESC_TLANCBANCARIO LAN ';
          wsql = wsql||'where (LAN.BDCHAVEFATURA is null) and ';

          if ((PRCHAVEBAN is not null) and (PRCHAVEBAN <> '')) then
             wsql = wsql||' LAN.BDCHAVECTABAN in ('||:PRCHAVEBAN||') and ';

    if (PRDATAINI is not null) then
             wsql = wsql||'(LAN.BDDATALAN >= '||''''||:PRDATAINI||''''||') and ';

    if (PRDATAFIN is not null) then
             wsql = wsql||'(LAN.BDDATALAN <= '||''''||:PRDATAFIN||''''||') and ';

          wsql = wsql||'(LAN.BDCHAVECTAPAG is null) ';
          wsql = wsql||') lan ';

          wsql = wsql||'left outer join TESCRITORIO ESC on (ESC.BDCODESC = LAN.BDCODESC) ';
          wsql = wsql||'left outer join VW_VFIN_BASE_TFORNECEDOR FORN on (FORN.BDCODFOR = LAN.BDCODFOR) ';
          wsql = wsql||'left outer join VW_VFIN_CLIENTES_REF CLI on (CLI.BDCODCLI = LAN.BDCODCLI) ';
          wsql = wsql||'left outer join VFIN_ESC_TCONTASBAN CTA on (CTA.BDCHAVECTABAN = LAN.BDCHAVECTABAN) ';
          wsql = wsql||'left outer join VFIN_BASE_TDESPESA DESP on (DESP.BDCODDESP = LAN.BDCODDESP) ';
          wsql = wsql||'left outer join VCT_BASE_SERVICO SER on (SER.BDCODOBRSER = LAN.BDCODSER) ';
          wsql = wsql||'order by LAN.BDCHAVECTABAN, LAN.BDDATALAN, LAN.BDORIGEM, LAN.BDREF ';


    FOR EXECUTE STATEMENT WSQL
        INTO :BDCODESC,:BDCODCLI,:BDCODFOR,:BDCHAVECTABAN,:BDSTATUS,:BDDATALAN,:BDREF,
             :BDSERIE,:BDCHAVECTAPAG,:BDCHAVELAN,:BDORIGEM,:BDVALORENTRADA,:BDVALORSAIDA,
             :BDCODOBRSER,:BDCODDESP,:BDNUMPAR,:BDDESCTIPOLAN,:BDNOMESC,:BDDESCCTABAN,
             :BDNOMEFOR,:BDNOMCLI,:BDDESCRICAO,:BDDESCDESP,:BDVALORLANC DO
          BEGIN
            IF (WCTABAN <> BDCHAVECTABAN) THEN
                begin
                  WCTABAN = BDCHAVECTABAN;
--        wsql = 'select coalesce(sum(SAI.BDVALORLANC),0) - coalesce((select sum(ENT.BDVALORLANC) ';
--        wsql =                                 wsql||' from VFIN_ESC_TLANCBANCARIO ENT';
--        wsql =                                 wsql||' where ENT.BDCHAVECTABAN = '||BDCHAVECTABAN||' and ';
--        wsql =                                 wsql||' (ENT.BDDATALAN < '||''''||BDDATALAN||''''||') and ';
--        wsql =                                 wsql||' ENT.BDTIPOMOV = 1), 0) ';
--        wsql = wsql||' from VFIN_ESC_TLANCBANCARIO SAI where SAI.BDCHAVECTABAN = '||BDCHAVECTABAN||' and ';
--        wsql = wsql||' (SAI.BDDATALAN < '||''''||BDDATALAN||''''||') and ';
--        wsql = wsql||'  SAI.BDTIPOMOV = 0 ';
        wsql = 'select sum(coalesce(case when (coalesce(lanc.bdtipomov, 0) = 0) then lanc.bdvalorlanc else lanc.bdvalorlanc*-1 end, 0)) ';
        wsql = wsql||'from VFIN_ESC_TLANCBANCARIO LANC ';
        wsql = wsql||'where LANC.BDCHAVECTABAN ='||bdchavectaban;
        wsql = wsql||'and(LANC.BDDATALAN < '||''''||bddatalan||''''||')';
                  EXECUTE STATEMENT wsql INTO :WSALDOANTERIOR;
                END
        
            IF (BDSTATUS = 0) THEN
               BEGIN
                 BDVALORSAIDA = 0;
                 BDVALORENTRADA = BDVALORLANC;
                 BDSALDOATUAL = wSALDOANTERIOR + BDVALORLANC;
                 BDSALDOANTERIOR = wSALDOANTERIOR;
                 wSALDOANTERIOR = wSALDOANTERIOR + BDVALORLANC;
               END
            ELSE
              BEGIN
                BDVALORENTRADA = 0;
                BDVALORSAIDA = BDVALORLANC;
                BDSALDOATUAL = wSALDOANTERIOR - BDVALORLANC;
                BDSALDOANTERIOR = wSALDOANTERIOR;
                wSALDOANTERIOR = wSALDOANTERIOR - BDVALORLANC;
              END
            SUSPEND;
          END
        end
     else
       if (prmodelo = 2) then
          begin
            wsql = 'select LAN.*, FORN.BDNOMEFOR, CLI.BDNOMCLI, CTA.BDDESCCTABAN ';
            wsql = wsql||'from (select LAN.BDCODCLI, LAN.BDCODFOR, coalesce(sum(LAN.BDVALORLANC), 0) BDVALORENT, 0 BDVALORSAI, LAN.BDCHAVECTABAN, ';
            wsql = wsql||'LAN.BDTIPOMOV, LAN.BDCODTIPO, LAN.BDDATALAN, 1 as BDORIGEM ';
            wsql = wsql||'from VFIN_ESC_TLANCBANCARIO LAN ';
            wsql = wsql||'where LAN.BDCODCLI > 0 and ';

            if ((PRCHAVEBAN is not null) and (PRCHAVEBAN <> '')) then
               wsql = wsql||' LAN.BDCHAVECTABAN in ('||:PRCHAVEBAN||') and ';

    if (PRDATAINI is not null) then
               wsql = wsql||'(LAN.BDDATALAN >= '||''''||:PRDATAINI||''''||') and ';

    if (PRDATAFIN is not null) then
               wsql = wsql||'(LAN.BDDATALAN <= '||''''||:PRDATAFIN||''''||') and ';

            wsql = wsql||'LAN.BDTIPOMOV = 0 ';
            wsql = wsql||'group by BDCODCLI, BDCODFOR, BDCHAVECTABAN, BDTIPOMOV, BDCODTIPO, BDDATALAN, BDORIGEM ';
            wsql = wsql||'union all ';
            wsql = wsql||'select LAN.BDCODCLI, LAN.BDCODFOR, 0 BDVALORENT, coalesce(sum(LAN.BDVALORLANC), 0) BDVALORSAI, LAN.BDCHAVECTABAN, ';
            wsql = wsql||'LAN.BDTIPOMOV, LAN.BDCODTIPO, LAN.BDDATALAN, 2 as BDORIGEM ';
            wsql = wsql||'from VFIN_ESC_TLANCBANCARIO LAN ';
            wsql = wsql||'where LAN.BDCODFOR > 0 and ';

            if ((PRCHAVEBAN is not null) and (PRCHAVEBAN <> '')) then
               wsql = wsql||' LAN.BDCHAVECTABAN in ('||:PRCHAVEBAN||') and ';

    if (PRDATAINI is not null) then
               wsql = wsql||'(LAN.BDDATALAN >= '||''''||:PRDATAINI||''''||') and ';

    if (PRDATAFIN is not null) then
               wsql = wsql||'(LAN.BDDATALAN <= '||''''||:PRDATAFIN||''''||') and ';

            wsql = wsql||'LAN.BDTIPOMOV = 1 ';
            wsql = wsql||'group by BDCODCLI, BDCODFOR, BDCHAVECTABAN, BDTIPOMOV, BDCODTIPO, BDDATALAN, BDORIGEM ';
            wsql = wsql||'union all ';
            wsql = wsql||'select LAN.BDCODCLI, LAN.BDCODFOR, coalesce(sum(LAN.BDVALORLANC), 0) BDVALORENTR, 0 BDVALORSAI, LAN.BDCHAVECTABAN, ';
            wsql = wsql||'LAN.BDTIPOMOV, LAN.BDCODTIPO, LAN.BDDATALAN, 3 as BDORIGEM ';
            wsql = wsql||'from VFIN_ESC_TLANCBANCARIO LAN ';
            wsql = wsql||'where LAN.BDCODCLI is null and ';
            wsql = wsql||'LAN.BDCODFOR is null and ';

            if ((PRCHAVEBAN is not null) and (PRCHAVEBAN <> '')) then
               wsql = wsql||' LAN.BDCHAVECTABAN in ('||:PRCHAVEBAN||') and ';

    if (PRDATAINI is not null) then
               wsql = wsql||'(LAN.BDDATALAN >= '||''''||:PRDATAINI||''''||') and ';

    if (PRDATAFIN is not null) then
               wsql = wsql||'(LAN.BDDATALAN <= '||''''||:PRDATAFIN||''''||') and ';

            wsql = wsql||'LAN.BDTIPOMOV = 0 and ';
            wsql = wsql||'LAN.BDCODTIPO <> 3006 ';
            wsql = wsql||'group by BDCODCLI, BDCODFOR, BDCHAVECTABAN, BDTIPOMOV, BDCODTIPO, BDDATALAN, BDORIGEM ';
            wsql = wsql||'union all ';
            wsql = wsql||'select LAN.BDCODCLI, LAN.BDCODFOR, 0 BDVALORENTR, coalesce(sum(LAN.BDVALORLANC), 0) BDVALORSAI, LAN.BDCHAVECTABAN, ';
            wsql = wsql||'LAN.BDTIPOMOV, LAN.BDCODTIPO, LAN.BDDATALAN, 3 as BDORIGEM ';
            wsql = wsql||'from VFIN_ESC_TLANCBANCARIO LAN ';
            wsql = wsql||'where LAN.BDCODCLI is null and ';
            wsql = wsql||'LAN.BDCODFOR is null and ';

            if ((PRCHAVEBAN is not null) and (PRCHAVEBAN <> '')) then
               wsql = wsql||' LAN.BDCHAVECTABAN in ('||:PRCHAVEBAN||') and ';

    if (PRDATAINI is not null) then
               wsql = wsql||'(LAN.BDDATALAN >= '||''''||:PRDATAINI||''''||') and ';

    if (PRDATAFIN is not null) then
               wsql = wsql||'(LAN.BDDATALAN <= '||''''||:PRDATAFIN||''''||') and ';

            wsql = wsql||'LAN.BDTIPOMOV = 1 and ';
            wsql = wsql||'LAN.BDCODTIPO <> 3006 ';
            wsql = wsql||'group by BDCODCLI, BDCODFOR, BDCHAVECTABAN, BDTIPOMOV, BDCODTIPO, BDDATALAN, BDORIGEM ';
            wsql = wsql||'union all ';
            wsql = wsql||'select LAN.BDCODCLI, LAN.BDCODFOR, coalesce(sum(LAN.BDVALORLANC), 0) BDVALORENTR, 0 BDVALORSAI, LAN.BDCHAVECTABAN, ';
            wsql = wsql||'LAN.BDTIPOMOV, LAN.BDCODTIPO, LAN.BDDATALAN, 3 as BDORIGEM ';
            wsql = wsql||'from VFIN_ESC_TLANCBANCARIO LAN ';
            wsql = wsql||'where LAN.BDCODCLI is null and ';
            wsql = wsql||'LAN.BDCODFOR is null and ';

            if ((PRCHAVEBAN is not null) and (PRCHAVEBAN <> '')) then
               wsql = wsql||' LAN.BDCHAVECTABAN in ('||:PRCHAVEBAN||') and ';

    if (PRDATAINI is not null) then
               wsql = wsql||'(LAN.BDDATALAN >= '||''''||:PRDATAINI||''''||') and ';

    if (PRDATAFIN is not null) then
               wsql = wsql||'(LAN.BDDATALAN <= '||''''||:PRDATAFIN||''''||') and ';

            wsql = wsql||'LAN.BDTIPOMOV = 0 and ';
            wsql = wsql||'LAN.BDCODTIPO = 3006 ';
            wsql = wsql||'group by BDCODCLI, BDCODFOR, BDCHAVECTABAN, BDTIPOMOV, BDCODTIPO, BDDATALAN, BDORIGEM ';
            wsql = wsql||'union all ';
            wsql = wsql||'select LAN.BDCODCLI, LAN.BDCODFOR, 0 BDVALORENTR, coalesce(sum(LAN.BDVALORLANC), 0) BDVALORSAI, LAN.BDCHAVECTABAN, ';
            wsql = wsql||'LAN.BDTIPOMOV, LAN.BDCODTIPO, LAN.BDDATALAN, 3 as BDORIGEM ';
            wsql = wsql||'from VFIN_ESC_TLANCBANCARIO LAN ';
            wsql = wsql||'where LAN.BDCODCLI is null and ';
            wsql = wsql||'LAN.BDCODFOR is null and ';

            if ((PRCHAVEBAN is not null) and (PRCHAVEBAN <> '')) then
               wsql = wsql||' LAN.BDCHAVECTABAN in ('||:PRCHAVEBAN||') and ';

    if (PRDATAINI is not null) then
               wsql = wsql||'(LAN.BDDATALAN >= '||''''||:PRDATAINI||''''||') and ';

    if (PRDATAFIN is not null) then
               wsql = wsql||'(LAN.BDDATALAN <= '||''''||:PRDATAFIN||''''||') and ';

            wsql = wsql||'LAN.BDTIPOMOV = 1 and ';
            wsql = wsql||'LAN.BDCODTIPO = 3006 ';
            wsql = wsql||'group by BDCODCLI, BDCODFOR, BDCHAVECTABAN, BDTIPOMOV, BDCODTIPO, BDDATALAN, BDORIGEM) LAN ';
            wsql = wsql||'left outer join VW_VFIN_BASE_TFORNECEDOR FORN on (FORN.BDCODFOR = LAN.BDCODFOR) ';
            wsql = wsql||'left outer join VW_VFIN_CLIENTES_REF CLI on (CLI.BDCODCLI = LAN.BDCODCLI) ';
            wsql = wsql||'left outer join VFIN_ESC_TCONTASBAN CTA on (CTA.BDCHAVECTABAN = LAN.BDCHAVECTABAN) ';
            wsql = wsql||'order by LAN.BDCHAVECTABAN, LAN.BDDATALAN, LAN.BDORIGEM, LAN.BDCODCLI, LAN.BDCODFOR ';

    FOR EXECUTE STATEMENT WSQL
        INTO :BDCODCLI,:BDCODFOR,:BDVALORENTRADA,:BDVALORSAIDA,:BDCHAVECTABAN,:BDSTATUS,
             :BDCODTIPO,:BDDATALAN,:BDORIGEM,:BDNOMEFOR,:BDNOMCLI,:BDDESCCTABAN DO
            BEGIN
              BDCODESC = 0;
              BDREF = substring(BDDATALAN from 1 for 4) || substring(BDDATALAN from 6 for 2);
              BDSERIE = '';
              BDCHAVECTAPAG = 0;
              BDCHAVELAN = 0;
              BDCODOBRSER = 0;
              BDCODDESP = 0;
              BDNUMPAR = 0;
              BDDESCTIPOLAN = '';
              BDDESCRICAO = '';
              BDDESCDESP = '';

              if (BDVALORENTRADA > 0) then
                   BDVALORLANC = :BDVALORENTRADA;
              else
                BDVALORLANC = :BDVALORSAIDA;

              IF (WCTABAN <> BDCHAVECTABAN) THEN
                 begin
                   WCTABAN = BDCHAVECTABAN;
--        wsql = 'select coalesce(sum(SAI.BDVALORLANC),0) - coalesce((select sum(ENT.BDVALORLANC) ';
--        wsql =                                 wsql||' from VFIN_ESC_TLANCBANCARIO ENT';
--        wsql =                                 wsql||' where ENT.BDCHAVECTABAN = '||BDCHAVECTABAN||' and ';
--        wsql =                                 wsql||' (ENT.BDDATALAN < '||''''||BDDATALAN||''''||') and ';
--        wsql =                                 wsql||' ENT.BDTIPOMOV = 1), 0) ';
--        wsql = wsql||' from VFIN_ESC_TLANCBANCARIO SAI where SAI.BDCHAVECTABAN = '||BDCHAVECTABAN||' and ';
--        wsql = wsql||' (SAI.BDDATALAN < '||''''||BDDATALAN||''''||') and ';
--        wsql = wsql||'  SAI.BDTIPOMOV = 0 ';
        wsql = 'select sum(coalesce(case when (coalesce(lanc.bdtipomov, 0) = 0) then lanc.bdvalorlanc else lanc.bdvalorlanc*-1 end, 0)) ';
        wsql = wsql||'from VFIN_ESC_TLANCBANCARIO LANC ';
        wsql = wsql||'where LANC.BDCHAVECTABAN ='||bdchavectaban;
        wsql = wsql||'and(LANC.BDDATALAN < '||''''||bddatalan||''''||')';
                   EXECUTE STATEMENT wsql INTO :WSALDOANTERIOR;
                 END

             IF (BDSTATUS = 0) THEN
                BEGIN
                  BDVALORSAIDA = 0;
                  BDVALORENTRADA = BDVALORLANC;
                  BDSALDOATUAL = wSALDOANTERIOR + BDVALORLANC;
                  BDSALDOANTERIOR = wSALDOANTERIOR;
                  wSALDOANTERIOR = wSALDOANTERIOR + BDVALORLANC;
                END
             ELSE
               BEGIN
                 BDVALORENTRADA = 0;
                 BDVALORSAIDA = BDVALORLANC;
                 BDSALDOATUAL = wSALDOANTERIOR - BDVALORLANC;
                 BDSALDOANTERIOR = wSALDOANTERIOR;
                 wSALDOANTERIOR = wSALDOANTERIOR - BDVALORLANC;
               END
             SUSPEND;
          end
  end
END^


/* Restore proc. body: SP_CALC_IDADE */
CREATE OR ALTER PROCEDURE SP_CALC_IDADE(PRNASCIMENTO DATE,
PRDATAATUAL DATE)
 RETURNS(BDANOS INTEGER)
 AS
BEGIN
  IF (prdataatual IS NULL) THEN
     prdataatual = CAST((SELECT TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES')) FROM rdb$database) AS DATE);

  /* Procedure Text */
  bdanos = EXTRACT(YEAR FROM prdataatual) - EXTRACT(YEAR FROM prnascimento);

  IF (EXTRACT(MONTH FROM prdataatual) < EXTRACT(MONTH FROM prnascimento)) THEN
     bdanos = bdanos - 1;
  ELSE IF (EXTRACT(MONTH FROM prdataatual) = EXTRACT(MONTH FROM prnascimento)) THEN
     BEGIN
       IF (EXTRACT(DAY FROM prdataatual) < EXTRACT(DAY FROM prnascimento)) THEN
          bdanos = bdanos - 1;
     END

  IF ((bdanos IS NULL) OR (bdanos < 0))  THEN
     bdanos = 0;

  SUSPEND;
END
^

/* Restore proc. body: SP_VRH_EMP_IDADE_COL */
create or alter procedure SP_VRH_EMP_IDADE_COL (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer,
    PRATIVOS smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDIDADE integer)
as
declare variable WSQL varchar(32700);
declare variable WDATANASC date;
declare variable WEMPSAUDE DM_BOOLEAN;
declare variable WEMPATU integer;
declare variable WULTDIA integer;
declare variable WDATAFIM date;
begin
  if (coalesce(prativos, 0) = 1) then
     begin
       wsql = 'SELECT COL.bdcodemp, COL.bdcodcol, COL.bddatanasccol '||
              'FROM vrh_emp_tcolcon COL '||
              'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) '||
              'WHERE COL.bddatanasccol IS NOT NULL and COL.BDREFADMCOL <= '||prref||' and ((RESC.BDDATARESCISAO is null) or (RESC.BDREFRESCISAO >= '||prref||'))';
     
       if (coalesce(premp, '') <> '') then
          wsql = wsql||' and '||replace(upper(premp), 'BDCODEMP', 'COL.BDCODEMP');
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||replace(upper(prcol), 'BDCODCOL', 'COL.BDCODCOL');
     
       wsql = wsql||' order by COL.bdcodemp';
     end
  else
     begin
  wsql = 'SELECT bdcodemp, bdcodcol, bddatanasccol '||
         'FROM vrh_emp_tcolcon '||
         'WHERE bddatanasccol IS NOT NULL ';
     
  if (coalesce(premp, '') <> '') then
     wsql = wsql||' and '||premp;
     
  if (coalesce(prcol, '') <> '') then
     wsql = wsql||' and '||prcol;
     
  wsql = wsql||' order by bdcodemp';
     end

  wempatu = 0;
  wempsaude = 'FALSE';
  for execute statement wsql into :BDCODEMP, :BDCODCOL, :wdatanasc 
  do
    begin
      if (wempatu <> BDCODEMP) then
         begin
           select first 1 BDIDADESAUDEEMP from VRHF_BASE_TEMPCALC where BDCODEMP = :BDCODEMP and BDREFEMP <= :prref order by BDREFEMP DESC into :wempsaude;
           wempsaude = upper(coalesce(wempsaude, 'FALSE'));
           wempatu = BDCODEMP;
         end

      if (wempsaude = 'TRUE') then
         begin
           wultdia = null;
           select ULTDIA from ULTIMO_DIA_MES(CAST(SUBSTRING(:prref FROM 5 FOR 2) AS SMALLINT), CAST(SUBSTRING(:prref FROM 1 FOR 4) AS INTEGER)) into :wultdia;
           wultdia = coalesce(wultdia, 0);

           if (wultdia > 0) then
              wdatafim = CAST((SUBSTRING(:prref FROM 5 FOR 2)||'-'||lpad(wultdia, 2, '0')||'-'||SUBSTRING(:prref FROM 1 FOR 4)) AS DATE);
           else
              wdatafim = CAST((SUBSTRING(:prref FROM 5 FOR 2)||'-01-'||SUBSTRING(:prref FROM 1 FOR 4)) AS DATE);
         end
      else
         begin
           if (SUBSTRING(:prref FROM 5 FOR 2) = '01') then
              prref = CAST((CAST((CAST(SUBSTRING(:prref FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
           else
              prref = SUBSTRING(:prref FROM 1 FOR 4)||LPAD(CAST(SUBSTRING(:prref FROM 5 FOR 2) AS INTEGER) - 1, 2, '0');

           wultdia = null;
           select ULTDIA from ULTIMO_DIA_MES(CAST(SUBSTRING(:prref FROM 5 FOR 2) AS SMALLINT), CAST(SUBSTRING(:prref FROM 1 FOR 4) AS INTEGER)) into :wultdia;
           wultdia = coalesce(wultdia, 0);

           if (wultdia > 0) then
              wdatafim = CAST((SUBSTRING(:prref FROM 5 FOR 2)||'-'||lpad(wultdia, 2, '0')||'-'||SUBSTRING(:prref FROM 1 FOR 4)) AS DATE);
           else
              wdatafim = CAST((SUBSTRING(:prref FROM 5 FOR 2)||'-01-'||SUBSTRING(:prref FROM 1 FOR 4)) AS DATE);
         end

      SELECT bdanos FROM sp_calc_idade(:wdatanasc, :wdatafim) into :BDIDADE;

      suspend;
    end
end^


/* Restore proc. body: SP_VRH_EMP_IDADE_COL_DEP */
create or alter procedure SP_VRH_EMP_IDADE_COL_DEP (
    PREMP varchar(15000),
    PRCOL varchar(32700),
    PRDEP varchar(10000),
    PRREF integer,
    PRATIVO smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDIDADE integer)
as
declare variable WSQL varchar(32700);
declare variable WDATANASC date;
declare variable WEMPSAUDE DM_BOOLEAN;
declare variable WEMPATU integer;
declare variable WULTDIA integer;
declare variable WDATAFIM date;
declare variable WREF integer;
begin
  if (coalesce(prativo, 0) = 1) then
     begin
  wsql = 'SELECT DEP.bdcodemp, DEP.bdcodcol, DEP.bdcoddpn '||
              'FROM vrh_emp_tdep DEP '||
              'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = DEP.BDCODEMP and COL.BDCODCOL = DEP.BDCODCOL) '||
              'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = DEP.BDCODEMP and RESC.BDCODCOL = DEP.BDCODCOL) '||
              'where COL.BDREFADMCOL <= '||prref||' and ((RESC.BDDATARESCISAO is null) or (RESC.BDREFRESCISAO >= '||prref||'))';
     
       if (coalesce(premp, '') <> '') then
          begin
            wsql = wsql||' and '||replace(upper(premp), 'BDCODEMP', 'DEP.BDCODEMP');
          
            if (coalesce(prcol, '') <> '') then
               wsql = wsql||' and '||replace(upper(prcol), 'BDCODCOL', 'DEP.BDCODCOL');
          
            if (coalesce(prdep, '') <> '') then
               wsql = wsql||' and '||replace(upper(prdep), 'BDCODDPN', 'DEP.BDCODDPN');
          end
     
       wsql = wsql||' order by DEP.bdcodemp';
     end
  else
     begin
       wsql = 'SELECT DEP.bdcodemp, DEP.bdcodcol, DEP.bdcoddpn '||
         'FROM vrh_emp_tdep DEP ';
     
  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||' where '||replace(upper(premp), 'BDCODEMP', 'DEP.BDCODEMP');
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||replace(upper(prcol), 'BDCODCOL', 'DEP.BDCODCOL');
     
       if (coalesce(prdep, '') <> '') then
          wsql = wsql||' and '||replace(upper(prdep), 'BDCODDPN', 'DEP.BDCODDPN');
     end
     
  wsql = wsql||' order by DEP.bdcodemp';
     end

  wempatu = 0;
  wempsaude = 'FALSE';
  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDCODDPN
  do
    begin
      wref = prref;
      wdatanasc = null;
      select first 1 BDDATANASCDPN from VRH_EMP_TDEP_REF where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDCODDPN = :BDCODDPN and BDREFDPN <= :wref order by BDREFDPN DESC into :wdatanasc;

      if (wdatanasc is null) then
         begin
           select first 1 BDDATANASCDPN from VRH_EMP_TDEP_REF where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDCODDPN = :BDCODDPN order by BDREFDPN into :wdatanasc;
         end

      if (wdatanasc is not null) then
         begin
           if (wempatu <> BDCODEMP) then
              begin
                select first 1 BDIDADESAUDEEMP from VRHF_BASE_TEMPCALC where BDCODEMP = :BDCODEMP and BDREFEMP <= :wref order by BDREFEMP DESC into :wempsaude;
                wempsaude = upper(coalesce(wempsaude, 'FALSE'));
                wempatu = BDCODEMP;
              end
     
           if (wempsaude = 'TRUE') then
              begin
                wultdia = null;
                select ULTDIA from ULTIMO_DIA_MES(CAST(SUBSTRING(:wref FROM 5 FOR 2) AS SMALLINT), CAST(SUBSTRING(:wref FROM 1 FOR 4) AS INTEGER)) into :wultdia;
                wultdia = coalesce(wultdia, 0);
     
                if (wultdia > 0) then
                   wdatafim = CAST((SUBSTRING(:wref FROM 5 FOR 2)||'-'||lpad(wultdia, 2, '0')||'-'||SUBSTRING(:wref FROM 1 FOR 4)) AS DATE);
                else
                   wdatafim = CAST((SUBSTRING(:wref FROM 5 FOR 2)||'-01-'||SUBSTRING(:wref FROM 1 FOR 4)) AS DATE);
              end
           else
              begin
                if (SUBSTRING(:wref FROM 5 FOR 2) = '01') then
                   wref = CAST((CAST((CAST(SUBSTRING(:wref FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER);
                else
                   wref = SUBSTRING(:wref FROM 1 FOR 4)||LPAD(CAST(SUBSTRING(:wref FROM 5 FOR 2) AS INTEGER) - 1, 2, '0');
     
                wultdia = null;
                select ULTDIA from ULTIMO_DIA_MES(CAST(SUBSTRING(:wref FROM 5 FOR 2) AS SMALLINT), CAST(SUBSTRING(:wref FROM 1 FOR 4) AS INTEGER)) into :wultdia;
                wultdia = coalesce(wultdia, 0);
     
                if (wultdia > 0) then
                   wdatafim = CAST((SUBSTRING(:wref FROM 5 FOR 2)||'-'||lpad(wultdia, 2, '0')||'-'||SUBSTRING(:wref FROM 1 FOR 4)) AS DATE);
                else
                   wdatafim = CAST((SUBSTRING(:wref FROM 5 FOR 2)||'-01-'||SUBSTRING(:wref FROM 1 FOR 4)) AS DATE);
              end
     
           SELECT bdanos FROM sp_calc_idade(:wdatanasc, :wdatafim) into :BDIDADE;
     
           suspend;
         end
    end
end^

CREATE OR ALTER procedure SP_VEF_BASE_TCONFSN_TRIB (
    PRTABELA varchar(30),
    PRBDCODPLANOCONFSN integer,
    PRBDCODATIVSIMPNAC integer,
    PRBDCODNAT integer,
    PRCODCONFSN integer,
    PRBDCODCID integer,
    PRBDCODATVM integer)
returns (
    BDCODCONFSN integer,
    BDCODTIPOIMPPIS integer,
    BDCODTIPOIMPCOFINS integer,
    BDCODTIPOIMPCSLL integer,
    BDCODTIPOIMPICMS integer,
    BDCODTIPOIMPINSSCPP integer,
    BDCODTIPOIMPIRPJ integer,
    BDCODTIPOIMPIPI integer,
    BDCODTIPOIMPISS integer,
    BDCODPLANOCONFSN integer,
    BDCODATIVSIMPNAC integer,
    BDCODNAT integer,
    BDCODCID integer,
    BDCODATVM integer,
    BDCODBASESN integer,
    BDFORMULASUB varchar(500),
    BDFORMULAADI varchar(500),
    BDPERCISENCAOICMS DM_NUMERIC_7_4_ALIQ,
    BDPERCREDBASEISS DM_NUMERIC_7_4_ALIQ,
    BDPERCREDUCAOBASEICMS DM_NUMERIC_7_4_ALIQ)
as
declare variable WSQL varchar(3000);
declare variable WCODIMPOSTO integer;
declare variable WCODTIPOIMPOSTO integer;
declare variable WBDCODBASESN integer;
declare variable WBDFORMULASUB varchar(500);
declare variable WBDFORMULAADI varchar(500);
declare variable WBDPERCISENCAOICMS DM_NUMERIC_7_4_ALIQ;
declare variable WBDPERCREDBASEISS DM_NUMERIC_7_4_ALIQ;
declare variable WBDPERCREDUCAOBASEICMS DM_NUMERIC_7_4_ALIQ;
begin
  /* Procedure Text */
  WSQL = 'select a.bdcodbasesn,a.BDFORMULASUB,a.BDFORMULAADI,t.bdcodimposto,t.bdcodtipoimposto,  ';

  if (prTabela = 'VEF_BASE_TNATOPCONFSN_TRIB') then /*Camilla M. 18/02/2022 - Isenção de ICMS na BC*/
     WSQL = WSQL || ' t.BDPERCISENCAOICMS, t.BDPERCREDUCAOBASEICMS ';
  else
     WSQL = WSQL || ' 0 BDPERCISENCAOICMS, 0 BDPERCREDUCAOBASEICMS ';
                                                 
  WSQL = WSQL || ' ,t.BDPERCREDBASEISS ';
  WSQL = WSQL || ' from ' || :prTabela || ' t ';

  if (prTabela = 'VEF_BASE_TNATOPCONFSN_TRIB') then
    begin
      WSQL = WSQL || ' left outer join vef_base_tnatopconfsn a on (a.BDCODPLANOCONFSN = t.bdcodplanoconfsn and a.BDCODATIVSIMPNAC = t.BDCODATIVSIMPNAC and ';
      WSQL = WSQL || '                                             a.BDCODNAT = t.BDCODNAT and a.BDCODCONFSN = t.BDCODCONFSN) ';
    end
  else
    begin
      WSQL = WSQL || ' left outer join vef_base_tconfatvmsn a on (a.BDCODPLANOCONFSN = t.bdcodplanoconfsn and a.BDCODATIVSIMPNAC = t.BDCODATIVSIMPNAC and ';
      WSQL = WSQL || '                                            a.BDCODCID = t.bdcodcid and a.BDCODATVM = t.bdcodatvm and a.BDCODCONFATVMSN = t.BDCODCONFATVMSN) ';
    end

  WSQL = WSQL || ' where t.bdcodplanoconfsn = ' || :prBDCODPLANOCONFSN;
  WSQL = WSQL || ' and t.BDCODATIVSIMPNAC = ' || :prBDCODATIVSIMPNAC;

  if (prTabela = 'VEF_BASE_TNATOPCONFSN_TRIB') then
    begin
      WSQL = WSQL || ' and t.BDCODNAT = ' || :prBDCODNAT;

      if (:prCodConfSN > 0) then
        WSQL = WSQL || ' and t.BDCODCONFSN = ' || :prCodConfSN;
    end
  else
    begin
--      WSQL = 'select t.bdcodimposto,t.bdcodtipoimposto from VEF_BASE_TCONFATVMSN_TRIB t ';
--      WSQL = WSQL || 'where t.bdcodplanoconfsn = '||:prbdcodplanoconfsn;
--      WSQL = WSQL || 'and t.BDCODATIVSIMPNAC = '||:prBDCODATIVSIMPNAC;
      if (:prCodConfSN > 0) then
        WSQL = WSQL || ' and t.BDCODCONFATVMSN = ' || :prCodConfSN;

      if (:prBDCODCID > 0) then
        WSQL = WSQL || ' and t.bdcodcid = ' || :prBDCODCID;

      if (:prBDCODATVM > 0) then
        WSQL = WSQL || ' and t.bdcodatvm = ' || :prBDCODATVM;
    end

  --valor default
  BDCODTIPOIMPCOFINS    = 1;
  BDCODTIPOIMPCSLL      = 1;
  BDCODTIPOIMPICMS      = 1;
  BDCODTIPOIMPINSSCPP   = 1;
  BDCODTIPOIMPIRPJ      = 1;
  BDCODTIPOIMPPIS       = 1;
  BDCODTIPOIMPIPI       = 1;
  BDCODTIPOIMPISS       = 1;
  BDPERCISENCAOICMS     = 0;
  BDPERCREDBASEISS      = 0;
  BDPERCREDUCAOBASEICMS = 0;

  for EXECUTE STATEMENT WSQL
  into :WBDCODBASESN, :WBDFORMULASUB, :WBDFORMULAADI, :wCodImposto, :wCodTipoImposto, :WBDPERCISENCAOICMS, :WBDPERCREDUCAOBASEICMS, :WBDPERCREDBASEISS do
  begin
    BDCODCONFSN = prCodConfSN;
    BDCODPLANOCONFSN = prBDCODPLANOCONFSN;
    BDCODATIVSIMPNAC = prBDCODATIVSIMPNAC;
    BDCODNAT = prBDCODNAT;
    BDCODCID = prBDCODCID;
    BDCODATVM = prBDCODATVM;
    BDCODBASESN = WBDCODBASESN;
    BDFORMULASUB = WBDFORMULASUB;
    BDFORMULAADI = WBDFORMULAADI;

    if (:wCodImposto = 1) then
      BDCODTIPOIMPCOFINS = wCodTipoImposto;
    else
    if (:wCodImposto = 2) then
      BDCODTIPOIMPCSLL = wCodTipoImposto;
    else
    if (:wCodImposto = 3) then
      begin
        BDCODTIPOIMPICMS = wCodTipoImposto;
        BDPERCISENCAOICMS = WBDPERCISENCAOICMS; /*Camilla M. 18/02/2022 - Isenção de ICMS na BC*/
        BDPERCREDUCAOBASEICMS = WBDPERCREDUCAOBASEICMS;
      end
    else
    if (:wCodImposto = 4) then
      BDCODTIPOIMPINSSCPP = wCodTipoImposto;
    else
    if (:wCodImposto = 5) then
      BDCODTIPOIMPIRPJ = wCodTipoImposto;
    else
    if (:wCodImposto = 6) then
      BDCODTIPOIMPPIS = wCodTipoImposto;
    else
    if (:wCodImposto = 7) then
      BDCODTIPOIMPIPI = wCodTipoImposto;
    else
    if (:wCodImposto = 8) then
      begin
        BDCODTIPOIMPISS = wCodTipoImposto;
        BDPERCREDBASEISS = WBDPERCREDBASEISS;
      end

--//  BDCODIMPOSTO    BDDESCIMP                         BDIGNORACALCULO
--//               1  Cofins                            BDCOFINS
--//               2  CSLL                              BDCSLL
--//               3  ICMS                              BDICMS
--//               4  INSS/CPP                          BDCPP
--//               5  IRPJ                              BDIRPJ
--//               6  PIS                               BDPIS_PASEP
--//               7  IPI                               BDIPI
--//               8  ISS                               BDISS

  end

  suspend;
end^


/* Restore proc. body: SP_VRHM_EMP_COL_VAL_OP_SAU */
create or alter procedure SP_VRHM_EMP_COL_VAL_OP_SAU (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDIDADE integer,
    BDIDADEFAIXA integer,
    BDMENSALIDADE numeric(18,6),
    BDTIPO integer,
    BDMENSFORMULA DM_BOOLEAN)
as
declare variable WSQL varchar(32700);
declare variable WVALVER numeric(18,6);
declare variable WCHAVE varchar(200);
declare variable WCODVERTITMENS integer;
begin
  wsql = 'SELECT conv.bdcodemp,conv.bdcodcol,conv.bdcodplaconvsau,conv.bdcodoperadora,conv.bdcodconvenio,id.bdidade,faixa.bdidade,faixa.bdvalor bdvalor,faixa.bdtipo, '||
                'CONV_OP.BDMENSFORMULA, CONV_OP.BDCODVERTITMENS '||
         'FROM SP_VRHM_EMP_VINC_COL_CONV_ATU(';

  if (coalesce(premp, '') <> '') then
     wsql = wsql||''''||premp||''', ';
  else
     wsql = wsql||'null, ';

  if (coalesce(prcol, '') <> '') then
     wsql = wsql||''''||prcol||''', ';
  else
     wsql = wsql||'null, ';

  wsql = wsql||prref||') conv '||
         'JOIN SP_VRH_EMP_IDADE_COL(';

  if (coalesce(premp, '') <> '') then
     wsql = wsql||''''||premp||''', ';
  else
     wsql = wsql||'null, ';

  if (coalesce(prcol, '') <> '') then
     wsql = wsql||''''||prcol||''', ';
  else
     wsql = wsql||'null, ';

  wsql = wsql||prref||',0) id ON (conv.bdcodemp = id.bdcodemp AND conv.bdcodcol = id.bdcodcol) '||
         'JOIN VRH_BASE_CONVENIO_OPERADORAS CONV_OP on (CONV_OP.BDCODPLACONVSAU = conv.BDCODPLACONVSAU and CONV_OP.BDCODOPERADORA = conv.BDCODOPERADORA and CONV_OP.BDCODCONVENIO = conv.BDCODCONVENIO) '||
         'LEFT OUTER JOIN VW_VRHM_FAIXA_CONV_OP_SAU_ATU faixa ON '||
               '(conv.bdcodconvenio = faixa.bdcodconvenio AND conv.bdcodoperadora = faixa.bdcodoperadora AND conv.bdcodplaconvsau = faixa.bdcodplaconvsau AND '||
                'faixa.bdidade = (SELECT MAX(x.bdidade) FROM VW_VRHM_FAIXA_CONV_OP_SAU_ATU x '||
                 'WHERE x.bdidade <= id.bdidade AND x.bdcodconvenio = conv.bdcodconvenio AND '||
                 'x.bdcodoperadora = conv.bdcodoperadora AND '||
                 'x.bdcodplaconvsau = conv.bdcodplaconvsau)) ';

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||' where '||replace(upper(premp), 'BDCODEMP', 'CONV.BDCODEMP');

       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||replace(upper(prcol), 'BDCODCOL', 'CONV.BDCODCOL');
     end

  wsql = wsql||' ORDER BY conv.bdcodemp,conv.bdcodcol ';

  for execute statement wsql
  into :BDCODEMP, :BDCODCOL, :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDIDADE, :BDIDADEFAIXA, :BDMENSALIDADE, :BDTIPO,
       :BDMENSFORMULA, :wcodvertitmens
  do
    begin
      if (upper(coalesce(BDMENSFORMULA, 'FALSE')) = 'TRUE') then
         begin
           wchave = '.'||BDCODPLACONVSAU||'.'||BDCODOPERADORA||'.'||BDCODCONVENIO||'.';
           BDMENSALIDADE = 0;
           wvalver = null;
           for
             select BDVALVFND
             from VRHF_EMP_TVERBAFN_DET
             where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFFN = :prref and BDINFAUXFND = :wchave and BDCODVER = :wcodvertitmens
           into :wvalver
           do
             BDMENSALIDADE = BDMENSALIDADE + coalesce(wvalver, 0);

           wvalver = null;
           for
             select BDVALVFTD
             from VRHF_EMP_TVERBAFT_DET
             where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFTOMADOR = :prref and BDINFAUXFTD = :wchave and BDCODVER = :wcodvertitmens
           into :wvalver
           do
             BDMENSALIDADE = BDMENSALIDADE + coalesce(wvalver, 0);

           wvalver = null;
           for
             select BDVALVFND
             from VRHF_EMP_TVERBAINT_DET
             where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFFN = :prref and BDINFAUXFND = :wchave and BDCODVER = :wcodvertitmens
           into :wvalver
           do
             BDMENSALIDADE = BDMENSALIDADE + coalesce(wvalver, 0);

           wvalver = null;
           for
             select BDVALVFTD
             from VRHF_EMP_TVERBATOMINT_DET
             where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFTOMADOR = :prref and BDINFAUXFTD = :wchave and BDCODVER = :wcodvertitmens
           into :wvalver
           do
             BDMENSALIDADE = BDMENSALIDADE + coalesce(wvalver, 0);
         end

    suspend;
    end
end^

/* Restore proc. body: SP_VRHM_EMP_VAL_COL_OP_ATU */
CREATE OR ALTER procedure SP_VRHM_EMP_VAL_COL_OP_ATU (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRPLANOSAUDE integer = 0,
    PROPER integer = 0,
    PRCONV integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREFVCS integer,
    BDVALORMENSALIDADEFUN numeric(18,6),
    BDVALORCOPARFUN numeric(18,6),
    BDTIPO integer,
    BDCODTIPO integer)
as
declare variable WSQL varchar(32700);
declare variable WWHE varchar(5000);
declare variable WNAOPAGAMENSALIDADE DM_BOOLEAN;
declare variable WPGMENS DM_BOOLEAN;
declare variable WMENSFORMULA DM_BOOLEAN;
begin
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRREF);

  wsql = 'SELECT psf.bdcodemp, psf.bdcodcol, psf.bdcodplaconvsau, psf.bdcodoperadora, psf.bdcodconvenio, COALESCE(x.bdref, 0) bdref, '||
             'CASE WHEN COALESCE(men.bdmensalidade, 0) = 0 THEN x.BDVALORMENSALIDADE '||
                  'WHEN men.bdmensalidade > 0 THEN men.bdmensalidade '||
             'END bdmensalidade, '||
             'COALESCE(x.bdvalorcoparfun,0) bdvalorcoparcol, men.bdtipo, x.bdnaopagamensalidade, x.bdcodtipo, men.BDMENSFORMULA '||
         'FROM SP_VRHM_EMP_VINC_COL_CONV_ATU(';

  if (coalesce(premp, 0) > 0) then
     wsql = wsql||'''BDCODEMP = '||premp||''',';
  else
     wsql = wsql||'null,';

  if (coalesce(prcol, 0) > 0) then
     wsql = wsql||'''BDCODCOL = '||prcol||''',';
  else
     wsql = wsql||'null,';

  wsql = wsql||prref||') psf '||
         'JOIN SP_VRHM_EMP_COL_VAL_OP_SAU(';

  if (coalesce(premp, 0) > 0) then
     wsql = wsql||'''BDCODEMP = '||premp||''',';
  else
     wsql = wsql||'null,';

  if (coalesce(prcol, 0) > 0) then
     wsql = wsql||'''BDCODCOL = '||prcol||''',';
  else
     wsql = wsql||'null,';

  wsql = wsql||prref||') men ON (men.bdcodemp = psf.bdcodemp AND men.bdcodcol = psf.bdcodcol AND men.bdcodconvenio = psf.bdcodconvenio AND men.bdcodplaconvsau = psf.bdcodplaconvsau AND men.bdcodoperadora = psf.bdcodoperadora) '||
         'LEFT OUTER JOIN SP_VRHM_EMP_COL_COP_OP_SAU(';

  if (coalesce(premp, 0) > 0) then
     wsql = wsql||premp||',';
  else
     wsql = wsql||'null,';

  if (coalesce(prcol, 0) > 0) then
     wsql = wsql||prcol||',';
  else
     wsql = wsql||'null,';


  wsql = wsql||prref||') x ON (x.bdcodemp = psf.bdcodemp AND x.bdcodcol = psf.bdcodcol AND x.bdcodplaconvsau = psf.bdcodplaconvsau AND x.bdcodoperadora = psf.bdcodoperadora AND x.bdcodconvenio = psf.bdcodconvenio) ';

  wwhe = '';

  if (coalesce(premp, 0) > 0) then
     wwhe = wwhe||'psf.BDCODEMP = '||premp;

  if (coalesce(prcol, 0) > 0) then
     begin
       if (wwhe <> '') then
          wwhe = wwhe||' and ';
       wwhe = wwhe||'psf.BDCODCOL= '||prcol;
     end

  if (coalesce(prplanosaude , 0) = -1) then
     begin
       if (wwhe <> '') then
          wwhe = wwhe||' and ';
       wwhe = wwhe||'psf.bdcodplaconvsau is null';
     end
  else
  if (coalesce(prplanosaude , 0) > 0) then
     begin
       if (wwhe <> '') then
          wwhe = wwhe||' and ';
       wwhe = wwhe||'psf.bdcodplaconvsau = '||prplanosaude;
     end

  if (coalesce(proper, 0) = -1) then
     begin
       if (wwhe <> '') then
          wwhe = wwhe||' and ';
       wwhe = wwhe||'psf.bdcodoperadora is null';
     end
  else
  if (coalesce(proper, 0) > 0) then
     begin
       if (wwhe <> '') then
          wwhe = wwhe||' and ';
       wwhe = wwhe||'psf.bdcodoperadora = '||proper;
     end

  if (coalesce(prconv , 0) = -1) then
     begin
       if (wwhe <> '') then
          wwhe = wwhe||' and ';
       wwhe = wwhe||'psf.bdcodconvenio is null';
     end
  else
  if (coalesce(prconv , 0) > 0) then
     begin
       if (wwhe <> '') then
          wwhe = wwhe||' and ';
       wwhe = wwhe||'psf.bdcodconvenio = '||prconv;
     end

  if (wwhe <> '') then
     wsql = wsql||' where '||wwhe;

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDCODPLACONVSAU, :BDCODOPERADORA, :BDCODCONVENIO, :BDREFVCS, :BDVALORMENSALIDADEFUN,
    :BDVALORCOPARFUN, :BDTIPO, :wnaopagamensalidade, :BDCODTIPO, :wmensformula do
    begin
      if (upper(coalesce(:wmensformula, 'FALSE')) = 'FALSE') then
         begin
      if (UPPER(COALESCE(:wnaopagamensalidade, 'FALSE')) = 'TRUE') then
         BDVALORMENSALIDADEFUN = 0;
      else
      if (coalesce(bdrefvcs, 0) > 0 and bdrefvcs = prref and coalesce(bdvalormensalidadefun, 0) = 0) then
         begin
           -- Tenta buscar a informação de algum lançamento anterior.
           select first 1 BDVALORMENSALIDADE, BDNAOPAGAMENSALIDADE
           from VRHM_EMP_COPAR_COL
           where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDCODPLACONVSAU = :BDCODPLACONVSAU and BDCODOPERADORA = :BDCODOPERADORA and BDCODCONVENIO = :BDCODCONVENIO and
                 BDREF < :prref order by BDREF DESC into :BDVALORMENSALIDADEFUN, :wpgmens;

           if (upper(coalesce(:wpgmens, 'FALSE')) = 'TRUE') then
              BDVALORMENSALIDADEFUN = 0;
         end
         end
    suspend;
    end
end^

create or alter procedure SP_VRH_EMP_SEM_VALORES_TCONV (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRPLANO integer = 0,
    PROPERADORA integer = 0,
    PRCONVENIO integer = 0)
returns (
    BDTIPO integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREF integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDNOME varchar(70),
    BDCPF varchar(14),
    BDVALORMENSALIDADE numeric(18,6),
    BDVALORCOPAR numeric(18,6))
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(5000);
begin
  wsql = 'SELECT bdtipo, bdcodplaconvsau, bdcodoperadora, bdcodconvenio, 0 bdref, bdcodemp, bdcodcol, bdcoddpn, bdnomcol, bdcpf, 0 bdvalormensalidade, 0 bdvalorcopar '||
         'FROM ( '||
            'SELECT 0 bdtipo, faixa.bdcodplaconvsau, faixa.bdcodoperadora,faixa.bdcodconvenio BDCODCONVENIO, colcon.bdcodemp, colcon.bdcodcol, NULL bdcoddpn, '||
                   'COLCAD.bdnomcol, doc.bdcpfcol bdcpf, 0 bdvalormensalidade, NULL bdvalorcopar '||
            'FROM vrh_emp_tcolcon colcon '||
            'LEFT OUTER JOIN vrh_emp_tcolcon_doc doc ON (colcon.bdcodemp = doc.bdcodemp AND colcon.bdcodcol = doc.bdcodcol) '||
            'LEFT OUTER JOIN SP_VRH_EMP_IDADE_COL(';

            if (coalesce(premp, 0) > 0) then
               wsql = wsql||'''BDCODEMP = '||premp||''', ';
            else
               wsql = wsql||'null, ';

            if (coalesce(prcol, 0) > 0) then
               wsql = wsql||'''BDCODCOL = '||prcol||''', ';
            else
               wsql = wsql||'null, ';


  wwhere = '';

  if (coalesce(premp, 0) > 0) then
     wwhere = wwhere||'colcon.bdcodemp = '||premp;

  if (coalesce(prcol, 0) > 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||'colcon.bdcodcol = '||prcol;
     end

  if (coalesce(prplano, 0) = -1) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||'faixa.bdcodplaconvsau is null';
     end
  else
  if (coalesce(prplano, 0) > 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||'faixa.bdcodplaconvsau = '||prplano;
     end

  if (coalesce(properadora, 0) = -1) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||'faixa.bdcodoperadora is null';
     end
  else
  if (coalesce(properadora, 0) > 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||'faixa.bdcodoperadora = '||properadora;
     end

  if (coalesce(prconvenio, 0) = -1) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||'faixa.bdcodconvenio is null';
     end
  else
  if (coalesce(prconvenio, 0) > 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||'faixa.bdcodconvenio = '||prconvenio;
     end

  if (wwhere <> '') then
     wwhere = ' where '||wwhere;

  wsql = wsql||prref||') id ON (colcon.bdcodemp = id.bdcodemp AND colcon.bdcodcol = id.bdcodcol) '||
            'LEFT OUTER JOIN VW_VRHM_FAIXA_CONV_OP_SAU_ATU faixa ON (faixa.bdidade = (SELECT MAX(x.bdidade) FROM VW_VRHM_FAIXA_CONV_OP_SAU_ATU x '||
                                                                                     'WHERE x.bdidade <= id.bdidade AND x.bdcodconvenio = faixa.bdcodconvenio '||
                                                                                     'AND x.bdcodoperadora = faixa.bdcodoperadora '||
                                                                                     'AND x.bdcodplaconvsau = faixa.bdcodplaconvsau)) '||
            'LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON (COLCAD.BDCODEMP = COLCON.BDCODEMP AND COLCAD.BDCODCOL = COLCON.BDCODCOL) '||
            wwhere||' '||
            'UNION '||
            'SELECT 1 bdtipo, faixa.bdcodplaconvsau, faixa.bdcodoperadora,faixa.bdcodconvenio, dep.bdcodemp, dep.bdcodcol, dep.bdcoddpn, ref.bdnomedpn,ref.bdcpfdpn, 0 bdvalor, NULL '||
            'FROM vrh_emp_tdep dep '||
            'LEFT OUTER JOIN VW_VRH_EMP_TDEP_REF ref on (dep.bdcodemp = ref.bdcodemp and dep.bdcodcol = ref.bdcodcol and dep.bdcoddpn = ref.bdcoddpn) '||
            'LEFT OUTER JOIN SP_VRH_EMP_IDADE_COL_DEP(';

            if (coalesce(premp, 0) > 0) then
               wsql = wsql||'''BDCODEMP = '||premp||''', ';
            else
               wsql = wsql||'null, ';

            if (coalesce(prcol, 0) > 0) then
               wsql = wsql||'''BDCODCOL = '||prcol||''', ';
            else
               wsql = wsql||'null, ';

  wwhere = '';

  if (coalesce(premp, 0) > 0) then
     wwhere = wwhere||'dep.bdcodemp = '||premp;

  if (coalesce(prcol, 0) > 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||'dep.bdcodcol = '||prcol;
     end

  if (coalesce(prplano, 0) > 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';

       wwhere = wwhere||'faixa.bdcodplaconvsau = '||prplano;
     end

  if (coalesce(properadora, 0) > 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||'faixa.bdcodoperadora = '||properadora;
     end

  if (coalesce(prconvenio, 0) > 0) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||'faixa.bdcodconvenio = '||prconvenio;
     end

  if (wwhere <> '') then
     wwhere = ' where '||wwhere;

  wsql = wsql||'null, ';
  wsql = wsql||prref||') idx ON (dep.bdcodemp = idx.bdcodemp AND dep.bdcodcol = idx.bdcodcol AND dep.bdcoddpn = idx.bdcoddpn) '||
            'LEFT OUTER JOIN VW_VRHM_FAIXA_CONV_OP_SAU_ATU faixa ON (faixa.bdidade = (SELECT MAX(x.bdidade) FROM VW_VRHM_FAIXA_CONV_OP_SAU_ATU x '||
                                                                    'WHERE x.bdidade <= idx.bdidade AND x.bdcodconvenio = faixa.bdcodconvenio '||
                                                                    'AND x.bdcodoperadora = faixa.bdcodoperadora '||
                                                                    'AND x.bdcodplaconvsau = faixa.bdcodplaconvsau)) '||
            wwhere||
         ')';

  for execute statement wsql into :BDTIPO,:BDCODPLACONVSAU,:BDCODOPERADORA,:BDCODCONVENIO,:BDREF,:BDCODEMP,:BDCODCOL,:BDCODDPN,:BDNOME,:BDCPF,:BDVALORMENSALIDADE,:BDVALORCOPAR do
    suspend;
end^

/* Restore proc. body: SP_VRHM_EMP_VAL_TOD_OP_ATU */
create or alter procedure SP_VRHM_EMP_VAL_TOD_OP_ATU (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRPLANO integer = 0,
    PROPER integer = 0,
    PRCONV integer = 0)
returns (
    BDTIPO integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREF integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDNOME varchar(70),
    BDCPF varchar(14),
    BDVALORMENSALIDADE numeric(18,6),
    BDVALORCOPAR numeric(18,6),
    BDCODTIPOCONV integer,
    BDTIPOFAIXA integer,
    BDCODTIPO integer,
    BDMENSFORMULA DM_BOOLEAN,
    BDCODVERTITMENS integer,
    BDCODVERTITCOP integer,
    BDCODVERDEPMENS integer,
    BDCODVERDEPCOP integer)
as
declare variable WSQL varchar(32700);
begin
  prplano = coalesce(prplano, 0);
  proper  = coalesce(proper, 0);
  prconv  = coalesce(prconv, 0);

  wsql = 'SELECT colcon.bdcodemp, colcon.bdcodcol, '||
                'doc.bdcpfcol bdcpf '||
         'FROM vrh_emp_tcolcon colcon '||
         'LEFT OUTER JOIN vrh_emp_tcolcon_doc doc ON (colcon.bdcodemp = doc.bdcodemp AND colcon.bdcodcol = doc.bdcodcol) '||
         'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = colcon.BDCODEMP and RESC.BDCODCOL = colcon.BDCODCOL) '||
         'where (((colcon.BDREFADMCOL is not null) and (colcon.BDREFADMCOL <= '||prref||')) or '||
         '      ((colcon.BDREFADMCOL is not null) and (colcon.BDREFADMCOL >= '||prref||')))';
         --    ' and ((RESC.BDDATARESCISAO is null) or (RESC.BDREFRESCISAO >= '||prref||'))';

  if (coalesce(premp, 0) > 0) then
     begin
       wsql = wsql||' and colcon.BDCODEMP = '||premp;

  if (coalesce(prcol, 0) > 0) then
          wsql = wsql||' and colcon.BDCODCOL = '||prcol;
     end

  for execute statement wsql into :BDCODEMP,:BDCODCOL,:BDCPF do
     begin
      BDCODDPN = null;
      BDTIPO   = 0;
      select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prref order by BDREFCOL DESC into :BDNOME;

      for select SAUDE.BDCODPLACONVSAU,
                 SAUDE.BDCODOPERADORA,
                 SAUDE.BDCODCONVENIO,
                 SAUDE.BDREFVCS,
                 COALESCE(SAUDE.BDVALORMENSALIDADEFUN,0),
                 SAUDE.bdvalorcoparfun,
                 COALESCE(SAUDE.bdtipo, 0),
                 SAUDE.bdcodtipo,
                 CONV_OP.bdcodtipoconv,
                 upper(coalesce(CONV_OP.bdmensformula, 'FALSE')),
                 CONV_OP.BDCODVERTITMENS,
                 CONV_OP.BDCODVERTITCOP,
                 CONV_OP.BDCODVERDEPMENS,
                 CONV_OP.BDCODVERDEPCOP
          from SP_VRHM_EMP_VAL_COL_OP_ATU(:BDCODEMP, :BDCODCOL, :prref, :prplano, :proper, :prconv) SAUDE
          left outer join VRH_BASE_CONVENIO_OPERADORAS CONV_OP on (CONV_OP.bdcodplaconvsau = SAUDE.bdcodplaconvsau AND CONV_OP.bdcodoperadora = SAUDE.bdcodoperadora AND CONV_OP.bdcodconvenio = SAUDE.bdcodconvenio)
      into :BDCODPLACONVSAU,
           :BDCODOPERADORA,
           :BDCODCONVENIO,
           :BDREF,
           :BDVALORMENSALIDADE,
           :BDVALORCOPAR,
           :BDCODTIPOCONV,
           :BDTIPOFAIXA,
           :BDCODTIPO,
           :BDMENSFORMULA,
           :BDCODVERTITMENS,
           :BDCODVERTITCOP,
           :BDCODVERDEPMENS,
           :BDCODVERDEPCOP
      do
        suspend;

      BDTIPO = 1;

      for select DEP.BDCODDPN,
                 SAUDE.bdcodplaconvsau,
                 SAUDE.bdcodoperadora,
                 SAUDE.bdcodconvenio,
                 SAUDE.bdrefvcs,
                 SAUDE.bdvalormensalidadedep,
                 SAUDE.bdvalorcopardep,
                 COALESCE(SAUDE.bdtipo, 0),
                 SAUDE.bdcodtipo,
                 CONV_OP.bdcodtipoconv,
                 upper(coalesce(CONV_OP.BDMENSFORMULA, 'FALSE')),
                 CONV_OP.BDCODVERTITMENS,
                 CONV_OP.BDCODVERTITCOP,
                 CONV_OP.BDCODVERDEPMENS,
                 CONV_OP.BDCODVERDEPCOP
          from SP_VRHM_EMP_VAL_DEP_OP_ATU(:BDCODEMP, :prref, :BDCODCOL, null, :prplano, :proper, :prconv) SAUDE
          join VRH_EMP_TDEP DEP on (DEP.BDCODEMP = SAUDE.BDCODEMP and DEP.BDCODCOL = SAUDE.BDCODCOL and DEP.BDCODDPN = SAUDE.BDCODDPN)
          LEFT OUTER JOIN VRH_BASE_CONVENIO_OPERADORAS CONV_OP ON (CONV_OP.bdcodplaconvsau = SAUDE.bdcodplaconvsau AND CONV_OP.bdcodoperadora = SAUDE.bdcodoperadora AND CONV_OP.bdcodconvenio = SAUDE.bdcodconvenio)
          where ((DEP.BDDATABAUXADPN is null) or (substring(DEP.BDDATABAUXADPN from 1 for 4) || substring(DEP.BDDATABAUXADPN from 6 for 2) > :prref))
      into :BDCODDPN,
           :BDCODPLACONVSAU,
           :BDCODOPERADORA,
           :BDCODCONVENIO,
           :BDREF,
           :BDVALORMENSALIDADE,
           :BDVALORCOPAR,
           :BDCODTIPOCONV,
           :BDTIPOFAIXA,
           :BDCODTIPO,
           :BDMENSFORMULA,
           :BDCODVERTITMENS,
           :BDCODVERTITCOP,
           :BDCODVERDEPMENS,
           :BDCODVERDEPCOP
      do
     begin
          BDNOME = null;
          BDCPF = null;
          select first 1 BDNOMEDPN, BDCPFDPN from VRH_EMP_TDEP_REF where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDCODDPN = :BDCODDPN and BDREFDPN <= :prref order by BDREFDPN DESC into :BDNOME, :BDCPF;

          if ((bdnome is null) or (bdcpf is null)) then
            begin
              select first 1 BDNOMEDPN, BDCPFDPN from VRH_EMP_TDEP_REF where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDCODDPN = :BDCODDPN order by ABS(BDREFDPN - :prref) ASC, BDREFDPN DESC into :BDNOME, :BDCPF;
          suspend;
     end
          else
            suspend;
     end

     end
end^

/* Restore proc.: SP_VRHM_EMP_COL_COP_OP_SAU */
create or alter procedure SP_VRHM_EMP_COL_COP_OP_SAU (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRPLANO integer = 0,
    PROPER integer = 0,
    PRCONV integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREF integer,
    BDVALORCOPARFUN numeric(18,6),
    BDVALORMENSALIDADE numeric(18,6),
    BDNAOPAGAMENSALIDADE DM_BOOLEAN,
    BDCODTIPO integer)
as
declare variable WSQL varchar(32700);
declare variable WCODTIPO integer;
begin
  wsql = 'SELECT psf.bdcodemp, psf.bdcodcol, psf.bdcodplaconvsau, psf.bdcodoperadora, psf.bdcodconvenio, max(psf.bdref) '||
         'FROM VRHM_EMP_COPAR_COL psf '||
         'WHERE ';

  if (coalesce(premp, 0) > 0) then
     begin
       wsql = wsql||'psf.BDCODEMP = '||premp||' and ';

       if (coalesce(prcol, 0) > 0) then
          wsql = wsql||'psf.BDCODCOL = '||prcol||' and ';
     end

  if (coalesce(prplano, 0) > 0) then
     wsql = wsql||'psf.BDCODPLACONVSAU = '||prplano||' and ';

  if (coalesce(proper, 0) > 0) then
     wsql = wsql||'psf.BDCODOPERADORA = '||proper||' and ';

  if (coalesce(prconv, 0) > 0) then
     wsql = wsql||'psf.BDCODCONVENIO = '||prconv||' and ';


  wsql = wsql||'psf.bdref <= '||prref;

  wsql = wsql||' group by psf.bdcodemp, psf.bdcodcol, psf.bdcodplaconvsau, psf.bdcodoperadora, psf.bdcodconvenio ';

  for execute statement wsql into :BDCODEMP,:BDCODCOL,:BDCODPLACONVSAU,:BDCODOPERADORA,:BDCODCONVENIO,:BDREF do
    begin
      BDCODTIPO = null;
      BDVALORCOPARFUN = null;
      BDVALORMENSALIDADE = null;
      BDNAOPAGAMENSALIDADE = '';
      wcodtipo = null;

      if (coalesce(bdref, 0) = prref) then
         select first 1 BDVALORCOPARCOL, BDCODTIPO from VRHM_EMP_COPAR_COL where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDCODPLACONVSAU = :BDCODPLACONVSAU and
           BDCODOPERADORA = :BDCODOPERADORA and BDCODCONVENIO = :BDCODCONVENIO and BDREF = :BDREF into :BDVALORCOPARFUN, :BDCODTIPO;

      SELECT FIRST 1 c.bdnaopagamensalidade, c.bdvalormensalidade, c.bdcodtipo
      FROM VRHM_EMP_COPAR_COL c
      WHERE
        c.bdcodemp = :bdcodemp AND
        c.bdcodcol = :bdcodcol AND
        c.bdcodplaconvsau = :bdcodplaconvsau AND
        c.bdcodoperadora = :bdcodoperadora AND
        c.bdcodconvenio = :bdcodconvenio AND
        c.bdvalormensalidade is not null AND
        c.bdref <= :prref
      ORDER BY c.BDREF DESC
      INTO :BDNAOPAGAMENSALIDADE, :BDVALORMENSALIDADE, :wcodtipo;

      BDNAOPAGAMENSALIDADE = UPPER(coalesce(BDNAOPAGAMENSALIDADE, 'FALSE'));

      if (UPPER(COALESCE(:BDNAOPAGAMENSALIDADE, 'FALSE')) = 'TRUE') then
         BDVALORMENSALIDADE = 0;

      if (bdref = prref and BDVALORMENSALIDADE = 0) then
         BDNAOPAGAMENSALIDADE = 'TRUE';

      if (BDCODTIPO is null) then
         BDCODTIPO = wcodtipo;

      suspend;
    end
end^

/* Restore proc.: SP_VRHM_EMP_VINC_COL_CONV_ATU */
create or alter procedure SP_VRHM_EMP_VINC_COL_CONV_ATU (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer,
    PROPER integer = 0,
    PRCONV integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREFINI integer,
    BDREFFIM integer,
    BDCODPLACONVSAU integer)
as
declare variable WSQL varchar(32700);
begin
  wsql = 'SELECT bdcodemp,bdcodcol,bdcodoperadora,bdcodconvenio,bdrefini,bdreffim,bdcodplaconvsau '||
         'FROM VRH_EMP_VINC_COL_CONV '||
         'WHERE bdrefini <= '||prref||' AND '||
               '((bdreffim >= '||prref||') OR (coalesce(bdreffim, 0) = 0)) and bdcodplaconvsau = (Select first 1 bdcodplaconvsau from VRHF_BASE_TEMPVINC where  '||prEmp|| ' and bdrefemp<='||prref||' order by bdrefemp desc) ';

  if (coalesce(premp, '') <> '') then
     wsql = wsql||' and '||premp;

  if (coalesce(prcol, '') <> '') then
     wsql = wsql||' and '||prcol;

  if (coalesce(proper, 0) > 0) then
     wsql = wsql||' and BDCODOPERADORA = '||proper;

  if (coalesce(prconv, 0) > 0) then
     wsql = wsql||' and BDCODCONVENIO = '||prconv;

  for execute statement wsql into :BDCODEMP,:BDCODCOL,:BDCODOPERADORA,:BDCODCONVENIO,:BDREFINI,:BDREFFIM,:BDCODPLACONVSAU do
    suspend;
end^


CREATE OR ALTER TRIGGER VRH_BASE_TVERBA_RELACAO_BI0 FOR VRH_BASE_TVERBA_RELACAO
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcodigo INTEGER;
begin
  if (coalesce(new.bdcodigo, 0) = 0) then
     begin
       select COALESCE(MAX(BDCODIGO) + 1, 1) from VRH_BASE_TVERBA_RELACAO into :vcodigo;
       new.bdcodigo = :vcodigo;
     end
end
^

CREATE OR ALTER TRIGGER VRHBASETVERBARELACAOITENS_BI0 FOR VRH_BASE_TVERBA_RELACAOITENS
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;
begin
  if (coalesce(new.bditem, 0) = 0) then
     begin
       select COALESCE(MAX(BDITEM) + 1, 1) from VRH_BASE_TVERBA_RELACAOITENS where BDCODIGO = new.bdcodigo into :vcod;
       new.bditem = :vcod;
     end
end
^

/* Trigger: VFIN_ESC_TSERVICOFATCC_BI0  07/11/2018 */
CREATE OR ALTER TRIGGER VFIN_ESC_TSERVICOFATCC_BI0 FOR VFIN_ESC_TSERVICOFATCC
ACTIVE BEFORE INSERT POSITION 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDORDEMCC is null) or (new.BDORDEMCC = 0)) then
  begin
    select coalesce((max(BDORDEMCC) + 1), 1)
    from VFIN_ESC_TSERVICOFATCC
    where (new.BDCODCLI = BDCODCLI) and
          (new.BDCODESC = BDCODESC) and
          (new.BDCHAVEFATURA = BDCHAVEFATURA) and
          (new.BDORDEMSER = BDORDEMSER)
    into VCODIGO;
    new.BDORDEMCC = VCODIGO;
  end
  else
  begin
    select BDORDEMCC
    from VFIN_ESC_TSERVICOFATCC
    where (new.BDCODCLI = BDCODCLI) and
          (new.BDCODESC = BDCODESC) and
          (new.BDCHAVEFATURA = BDCHAVEFATURA) and
          (new.BDORDEMSER = BDORDEMSER)
    into VCODIGO;
    if (VCODIGO > 0) then
    begin
      select coalesce((max(BDORDEMCC) + 1), 1)
      from VFIN_ESC_TSERVICOFATCC
      where (new.BDCODCLI = BDCODCLI) and
            (new.BDCODESC = BDCODESC) and
            (new.BDCHAVEFATURA = BDCHAVEFATURA) and
            (new.BDORDEMSER = BDORDEMSER)
      into VCODIGO;
      new.BDORDEMCC = VCODIGO;
    end
  END
END
^

CREATE OR ALTER TRIGGER VFIN_BASE_TCONCIBAN_BI0 FOR VFIN_BASE_TCONCILIACAOBANCARIA
ACTIVE BEFORE INSERT POSITION 0
AS
 declare variable wchave int;
begin
   if ((new.bdchaveseq = 0) or (new.bdchaveseq is null)) then
   begin
     select first 1 coalesce(bdchaveseq,0) from vfin_base_tconciliacaobancaria order by bdchaveseq desc
     into :wchave;
     new.bdchaveseq = coalesce(:wchave,0)+1;
   end
end
^

CREATE OR ALTER TRIGGER TAREFA_BI0 FOR TAREFA
ACTIVE BEFORE INSERT POSITION 0
as
declare variable BDCODIGO integer;
begin
  if ((new.BDCODTAREFA is null) or (new.BDCODTAREFA = 0)) then
  begin
    select coalesce(max(BDCODTAREFA) + 1, 1)
    from TAREFA
    where BDCODEMP = new.BDCODEMP
    into BDCODIGO;
    new.BDCODTAREFA = BDCODIGO;
  end
end
^

CREATE OR ALTER TRIGGER VRH_RHNET_TSTANDBY_BI0 FOR VRH_RHNET_TSTANDBY
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;
begin
  if (coalesce(new.bdcodsb, 0) = 0) then
     begin
       select COALESCE(MAX(BDCODSB) + 1, 1) from VRH_RHNET_TSTANDBY into :vcod;
       new.bdcodsb = :vcod;
     end

  select localtimestamp from rdb$database into new.bddatahora;
end
^
     
create or alter procedure SP_DATA_UTIL (
    PRCODEMP integer,
    PRDATA date)
returns (
    BDDATA date)
as
declare variable WFERIADO varchar(5);
declare variable WDATAVALIDA varchar(5);
begin
  bddata = :prdata;
  wdatavalida = 'FALSE';

  while (wdatavalida = 'FALSE') do
    begin
      select bdferiado from sp_feriado_empresa(:prcodemp, :bddata) into :wferiado;

      if (wferiado = 'TRUE' or extract(weekday from bddata) in (0,6)) then
        begin            
          bddata = dateadd(-1 day to :bddata);
        end
      else
        begin     
          wdatavalida = 'TRUE';
        end
    end

  suspend;
end
^

create or alter procedure SP_VRHF_PAGAMENTO_FN (
    PRCODEMP varchar(10000),
    PRCODCOL varchar(32700),
    PRREFFN integer,
    PRCODACCONV integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDPAGEMP integer,
    BDDATAPGTOFN date,
    BDDATAPGTOFNINT integer)
as
declare variable WSQL varchar(32700);
declare variable WAND varchar(7);
declare variable WIGNORAR type of DM_BOOLEAN;
declare variable WULTIMODIAMES date;
declare variable WDIAS integer;
declare variable WEMPCACHEPAGMES integer;
declare variable WDATACACHEPAGMES date;
declare variable WEMPCACHEPAGPOST integer;
declare variable WDATACACHEPAGPOST date;
declare variable WCODEMPCOMP integer;
declare variable WCODCOLCOMP integer;
declare variable WCODTIPOFCCOMP integer;
declare variable WCODACCONVCOMP integer;
declare variable WDATAPAGFC date;
begin
  wultimodiames = substring(cast(prreffn as varchar(6)) from 5 for 2)||'/01/'||substring(cast(prreffn as varchar(6)) from 1 for 4);
  wultimodiames = dateadd(-1 day to dateadd(1 month to wultimodiames));

  wempcachepagmes   = 0;
  wdatacachepagmes  = null;
  wempcachepagpost  = 0;
  wdatacachepagpost = null;

  wsql = 'select VINC.BDCODEMP, VINC.BDCODCOL,'||
          ' case'||
            ' when (CLASSE.BDGRUPOCLA = 2) then EMP.BDPAGEMPCONTR'||
            ' else EMP.BDPAGEMP'||
          ' end as BDPAGEMP'||
         ' from VW_VRHF_BASE_TEMPCALC EMP'||
         ' left outer join VW_VRH_EMP_TCOLCON_VINC VINC on (VINC.BDCODEMP = EMP.BDCODEMP)'||
         ' left outer join VRH_BASE_TCLASSE CLASSE on (CLASSE.BDCODCLA = VINC.BDCODCLA)';

  wand = ' where ';

  if (coalesce(prcodemp,'') <> '') then
     begin
       wsql = wsql||wand||'('||replace(prcodemp,'BDCODEMP','EMP.BDCODEMP')||')';
       wand = ' and ';
     end

  if (coalesce(prcodcol,'') <> '') then
     wsql = wsql||wand||'('||replace(prcodcol,'BDCODCOL','VINC.BDCODCOL')||')';

  execute procedure SP_SETA_COMPETENCIA(prreffn);

  for execute statement wsql into :bdcodemp, :bdcodcol, :bdpagemp do
    begin
      if (bdpagemp = 1) then
         begin
           -- Mes da competencia
           if (bdcodemp <> wempcachepagmes) then
              begin
                wempcachepagmes = bdcodemp;
                select BDDATA from SP_DATA_UTIL(:bdcodemp, :wultimodiames) into :wdatacachepagmes;
              end

           bddatapgtofn = wdatacachepagmes;
         end
      else
         begin
           -- Mes posterior
           if (bdcodemp <> wempcachepagpost) then
              begin
                wempcachepagpost  = bdcodemp;
                wdatacachepagpost = wultimodiames;
                wdias = 5;
                while (wdias > 0) do
                  begin
                    wdatacachepagpost = dateadd(1 day to wdatacachepagpost);

                    if (extract(weekday from wdatacachepagpost) = 0) then
                       wignorar = 'TRUE';
                    else
                       select bdferiado from sp_feriado_empresa(0, :wdatacachepagpost) into :wignorar;

                    if (wignorar <> 'TRUE') then
                       wdias = wdias-1;
                  end
                if (extract(weekday from wdatacachepagpost) = 6) then
                  wdatacachepagpost = wdatacachepagpost - 1;
              end

           bddatapgtofn = wdatacachepagpost;
         end

      bddatapgtofnint = (extract(year  from bddatapgtofn) * 10000) +
                        (extract(month from bddatapgtofn) * 100) +
                        (extract(day   from bddatapgtofn));

      suspend;
    end

  if (PRCODACCONV > 0) then
    begin
      wsql = 'select COMP.BDCODEMP, COMP.BDCODCOL, COMP.BDCODTIPOFC, COMP.BDCODACCONV, COMP.BDDATAPAGFC ' ||
             ' from (select FCTOM.BDCODEMP, FCTOM.BDCODCOL, FCTOM.BDCODTIPOFC, FCTOM.BDCODACCONV, FCTOM.BDDATAPAGFC ' ||
             '       from VRHF_EMP_TFOLTOMCOMP FCTOM ' ||
             ' where  FCTOM.BDCODTIPOFC = 3 and ' ||
             '        FCTOM.BDCODACCONV = ' ||  PRCODACCONV;

      if (coalesce(prcodemp,'') <> '') then
        wsql = wsql || ' and ' || replace(prcodemp,'BDCODEMP','FCTOM.BDCODEMP');

      if (coalesce(prcodcol,'') <> '') then
        wsql = wsql || ' and ' || replace(prcodcol,'BDCODCOL','FCTOM.BDCODCOL');

      wsql = wsql || '       group by FCTOM.BDCODEMP, FCTOM.BDCODCOL, FCTOM.BDCODTIPOFC, FCTOM.BDCODACCONV, FCTOM.BDDATAPAGFC ';

      wsql = wsql || '       union all ';


      wsql = wsql || ' select FC.BDCODEMP, FC.BDCODCOL, FC.BDCODTIPOFC, FC.BDCODACCONV, FC.BDDATAPAGFC ' ||
             ' from VRHF_EMP_TFOLHACOMP FC ' ||
             ' where FC.BDCODTIPOFC = 3 and ' ||
             '       FC.BDCODACCONV = ' ||  PRCODACCONV;

      if (coalesce(prcodemp,'') <> '') then
        wsql = wsql || ' and ' || replace(prcodemp,'BDCODEMP','FC.BDCODEMP');

      if (coalesce(prcodcol,'') <> '') then
        wsql = wsql || ' and ' || replace(prcodcol,'BDCODCOL','FC.BDCODCOL');

      wsql = wsql || ' group by FC.BDCODEMP, FC.BDCODCOL, FC.BDCODTIPOFC, FC.BDCODACCONV, FC.BDDATAPAGFC) COMP ';

      for execute statement wsql into :wcodempcomp, :wcodcolcomp, :wcodtipofccomp, :wcodacconvcomp, :wdatapagfc do
        begin
          :bdcodemp = wcodempcomp;
          :bdcodcol = wcodcolcomp;
          if (wdatapagfc is not null) then
            begin
              bddatapgtofn = wdatapagfc;
              bddatapgtofnint = (extract(year  from wdatapagfc) * 10000) +
                                (extract(month from wdatapagfc) * 100) +
                                (extract(day   from wdatapagfc));
            end
          suspend;
        end
    end

end^

create or alter procedure SP_VRH_REL_MOVIMENTACAO (
    PRCODEMP varchar(25000),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDNOMEMPUPPER DM_BDNOMEMP,
    BDATIVOSANT integer,
    BDADM integer,
    BDDEM integer)
as
declare variable WSQL varchar(30000);
declare variable WREF integer;
begin
  wsql = 'select BDCODEMP, BDNOMEMP, UPPER(BDNOMEMP) from VW_TEMPRESAS_REF';

  if (coalesce(prcodemp, '') <> '') then
     wsql = wsql||' where '||prcodemp;

  for execute statement wsql into :BDCODEMP, :BDNOMEMP, :BDNOMEMPUPPER do
    begin
      BDATIVOSANT = 0;
      BDADM = 0;
      BDDEM = 0;
      wref = prref;
      select first 1 BDADMITIDOS from VRH_SP_ADMITIDOS_NO_MES('X.BDCODEMP = '||:BDCODEMP, :wref) into :BDADM;
      select first 1 BDDEMITIDOS from VRH_SP_DEMITIDOS_NO_MES('X.BDCODEMP = '||:BDCODEMP, :wref) into :BDDEM;

      if (SUBSTRING(:wref FROM 5 FOR 2) = '01') then
         wref = CAST((CAST((CAST(SUBSTRING(:wref FROM 1 FOR 4) AS INTEGER) - 1) AS VARCHAR(4))||'12') AS INTEGER); -- Sol. 132754 | Michel Luciano | Data 04/02/2020
      else
         wref = CAST((SUBSTRING(:wref FROM 1 FOR 4)||LPAD(CAST(SUBSTRING(:wref FROM 5 FOR 2) AS INTEGER) - 1, 2, '0')) AS INTEGER);

      select first 1 BDATIVOS from VRH_SP_ATIVOS_NO_MES('X.BDCODEMP = '||:BDCODEMP, :wref) into :BDATIVOSANT; -- Mês anterior
      suspend;
    end
end^

CREATE OR ALTER PROCEDURE SP_INSERE_DEPENDENTES (
    PRCODEMP INTEGER,
    PRCHAVE INTEGER,
    PRTABLEORIGEM VARCHAR(50),
    PRCONDICAO VARCHAR(250),
    PREXCECAO VARCHAR(255))
AS
DECLARE VARIABLE WTABLEDEPENDENT VARCHAR(50);
DECLARE VARIABLE WSQL VARCHAR(32750);
DECLARE VARIABLE WCONDLEFT VARCHAR(255);
DECLARE VARIABLE WFIELDS VARCHAR(10000);
DECLARE VARIABLE WFIELD VARCHAR(64);
DECLARE VARIABLE WCAMPO VARCHAR(40);
DECLARE VARIABLE WCONDICAO VARCHAR(250);
DECLARE VARIABLE WEMPAUX INTEGER;
BEGIN

  wTableDependent = NULL;
  SELECT FIRST 1 BDTABLE_DEPENDENTE FROM TDEPENDENCIAS_DB INTO :wTableDependent;

  IF (ROW_COUNT = 0) THEN
    BEGIN
      INSERT INTO TDEPENDENCIAS_DB(BDTABLE_PRINCIPAL, BDTABLE_DEPENDENTE)
      SELECT TRIM(RC.RDB$RELATION_NAME) BDTABLE_PRINCIPAL, TRIM(I.RDB$RELATION_NAME) BDTABLE_DEPENDENTE
      FROM RDB$RELATION_CONSTRAINTS R
      LEFT OUTER JOIN RDB$INDICES I ON(I.RDB$INDEX_NAME = R.RDB$INDEX_NAME)
      JOIN RDB$RELATION_CONSTRAINTS RC ON(RC.RDB$INDEX_NAME = I.RDB$FOREIGN_KEY)
      WHERE I.RDB$RELATION_NAME NOT CONTAINING('TOL_')
      GROUP BY BDTABLE_PRINCIPAL, BDTABLE_DEPENDENTE;
    END


  FOR SELECT BDTABLE_DEPENDENTE
      FROM TDEPENDENCIAS_DB
      WHERE BDTABLE_PRINCIPAL = :PRTABLEORIGEM
      INTO :wTableDependent
  DO
    BEGIN
      IF ((:PREXCECAO = '') OR ((:PREXCECAO <> '') AND (:PREXCECAO NOT CONTAINING(:wTableDependent)))) THEN
        BEGIN
          SELECT LIST(TRIM(RDB$FIELD_NAME)) BDFIELDS
          FROM RDB$RELATION_FIELDS
          WHERE RDB$RELATION_NAME = :wTableDependent
          GROUP BY RDB$RELATION_NAME
          ORDER BY RDB$RELATION_NAME DESC
          INTO :wFields;
    
          wSQL =          'INSERT INTO '||:wTableDependent||'('||:wFields||')';
    
          wFields = 'T.'||:wFields;
          wFields = REPLACE(:wFields, ',BD', ',T.BD');
          wFields = REPLACE(:wFields, 'T.BDCODEMP', :PRCODEMP||' BDCODEMP');
          wFields = REPLACE(:wFields, 'T.BDCHAVE,', :PRCHAVE||' BDCHAVE,');
    
          wSQL = :wSQL || 'SELECT '||:wFields||' FROM '||:wTableDependent||' T ';

          /*Vai fazer o left das fks relacionadas*/
          SELECT FIRST 1 FKS.BDCODEMP FROM TMP_TTRANSFERENCIA_FKS FKS WHERE FKS.BDTABLE = :wTableDependent INTO :wEmpAux;

          IF (ROW_COUNT > 0) THEN
            BEGIN

              FOR SELECT 'T.'||TRIM(RDB$FIELD_NAME)
                  FROM RDB$RELATION_FIELDS FK
                  WHERE RDB$RELATION_NAME = 'TMP_TTRANSFERENCIA_FKS'
                  AND RDB$FIELD_NAME <> 'BDTABLE'
                  AND NOT EXISTS (
                                  SELECT IDX.RDB$FIELD_NAME
                                  FROM (
                                        SELECT RDB$INDEX_NAME
                                        FROM RDB$RELATION_CONSTRAINTS
                                        WHERE RDB$RELATION_NAME = :wTableDependent
                                        AND RDB$CONSTRAINT_TYPE = 'PRIMARY KEY'
                                       ) PK
                                  JOIN RDB$INDEX_SEGMENTS IDX ON(IDX.RDB$INDEX_NAME = PK.RDB$INDEX_NAME)
                                  WHERE IDX.RDB$FIELD_NAME = FK.RDB$FIELD_NAME
                                 )
                  INTO :wField
              DO
                BEGIN
                  IF ((:wSQL CONTAINING(:wField||',')) OR (:wSQL CONTAINING(:wField||' '))) THEN
                    wSQL = REPLACE(:wSQL, :wField, ' COALESCE(FK.'||REPLACE(:wField, 'T.', '')||', '||:wField||')');
                END

              wSQL = :wSQL || ' LEFT OUTER JOIN TMP_TTRANSFERENCIA_FKS FK ON(';

              SELECT LIST('AND FK.'||TRIM(IDX.RDB$FIELD_NAME)||'=T.'||TRIM(IDX.RDB$FIELD_NAME), ' ') BDFIELD_PK
              FROM (
                    SELECT RDB$INDEX_NAME
                    FROM RDB$RELATION_CONSTRAINTS
                    WHERE RDB$RELATION_NAME = :wTableDependent
                    AND RDB$CONSTRAINT_TYPE = 'PRIMARY KEY'
                   ) PK
              JOIN RDB$INDEX_SEGMENTS IDX ON(IDX.RDB$INDEX_NAME = PK.RDB$INDEX_NAME)
              INTO :wCondLeft;

              wSQL = :wSQL || SUBSTRING(:wCondLeft FROM 4 FOR CHAR_LENGTH(:wCondLeft)-3)||') ';
            END

          wCondicao = '';
          FOR SELECT BDDADO FROM SP_SPLIT(:PRCONDICAO, ';')
              INTO :wCampo
          DO
            BEGIN
              IF (:wFields CONTAINING (SUBSTRING(:wCampo FROM 1 FOR POSITION('=', :wCampo)-1)||',')) THEN
                BEGIN
                  IF (:wCondicao = '') THEN
                    wCondicao = ' WHERE ';
                  ELSE
                    wCondicao = :wCondicao || ' AND ';

                    wCondicao = :wCondicao || 'T.'||:wCampo;
                END
            END

          wSQL = :wSQL || :wCondicao;
    
          EXECUTE STATEMENT :wSQL;
        END    
      EXECUTE PROCEDURE SP_INSERE_DEPENDENTES(:PRCODEMP, :PRCHAVE, :wTableDependent, :PRCONDICAO, :PREXCECAO);
    END
END
^

CREATE OR ALTER PROCEDURE SP_GRAVAR_LAN (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRTIPOLAN CHAR(3))
AS
DECLARE VARIABLE WCABECALHO VARCHAR(800);
DECLARE VARIABLE WFIELDS VARCHAR(800);
DECLARE VARIABLE WSELECT VARCHAR(800);
DECLARE VARIABLE WTABLETMP VARCHAR(31);
DECLARE VARIABLE WTABLE VARCHAR(31);
DECLARE VARIABLE WTABLEITEM VARCHAR(31);
DECLARE VARIABLE WTABLEITEMTMP VARCHAR(31);
DECLARE VARIABLE WTABLEINCON VARCHAR(31);
DECLARE VARIABLE WTABLERET VARCHAR(31);
DECLARE VARIABLE WTABLERETTMP VARCHAR(31);
DECLARE VARIABLE WTABLEPAR VARCHAR(31);
DECLARE VARIABLE WTABLEPARTMP VARCHAR(31);
DECLARE VARIABLE WTABLERAT VARCHAR(31);
DECLARE VARIABLE WTABLERATTMP VARCHAR(31);
DECLARE VARIABLE WTABLEMOVPRO VARCHAR(31);
DECLARE VARIABLE WTABLEMOVPROTMP VARCHAR(31);
DECLARE VARIABLE wCodICMSSped INTEGER;
DECLARE VARIABLE wDtObrigSped DATE;
BEGIN

  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTable         = 'VEF_EMP_TMOVENT';
      wTableTMP      = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItem     = 'VEF_EMP_TMOVENTITENS';
      wTableItemTMP  = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      wTableIncon    = 'VEF_INCON_TMOVENT';
      wTableRet      = 'VEF_EMP_TMOVENTRET';
      wTableRetTMP   = 'TMP_VEF_EMP_TMOVENTRET_TEMP';
      wTablePar      = 'VEF_EMP_TMOVENTPAR';
      wTableParTMP   = 'TMP_VEF_EMP_TMOVENTPAR_TEMP';
      wTableRat      = 'VEF_EMP_TMOVRATENT';
      wTableRatTMP   = 'TMP_VEF_EMP_TMOVRATENT_TEMP';
      wTableMovPro   = 'VEF_EMP_TMOVPROENT';
      wTableMovProTMP= 'TMP_VEF_EMP_TMOVPROENT_TEMP';
    END
  ELSE
  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTable         = 'VEF_EMP_TMOVSAI';
      wTableTMP      = 'TMP_VEF_EMP_TMOVSAI_TEMP';
      wTableItem     = 'VEF_EMP_TMOVSAIITENS';
      wTableItemTMP  = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
      wTableIncon    = 'VEF_INCON_TMOVSAI';
      wTableRet      = 'VEF_EMP_TMOVSAIRET';
      wTableRetTMP   = 'TMP_VEF_EMP_TMOVSAIRET_TEMP';
      wTablePar      = 'VEF_EMP_TMOVSAIPAR';
      wTableParTMP   = 'TMP_VEF_EMP_TMOVSAIPAR_TEMP';
      wTableRat      = 'VEF_EMP_TMOVRATSAI';
      wTableRatTMP   = 'TMP_VEF_EMP_TMOVRATSAI_TEMP';
      wTableMovPro   = 'VEF_EMP_TMOVPROSAI';
      wTableMovProTMP= 'TMP_VEF_EMP_TMOVPROSAI_TEMP';
    END
  ELSE
  IF (:PRTIPOLAN = 'SER') THEN
    BEGIN
      wTable         = 'VEF_EMP_TMOVSER';
      wTableTMP      = 'TMP_VEF_EMP_TMOVSER_TEMP';
      wTableItem     = 'VEF_EMP_TMOVSERITENS';
      wTableItemTMP  = 'TMP_VEF_EMP_TMOVSERITENS_TEMP';
      wTableIncon    = 'VEF_INCON_TMOVSER';
      wTableRet      = 'VEF_EMP_TMOVSERRET';
      wTableRetTMP   = 'TMP_VEF_EMP_TMOVSERRET_TEMP';
      wTablePar      = 'VEF_EMP_TMOVSERPAR';
      wTableParTMP   = 'TMP_VEF_EMP_TMOVSERPAR_TEMP';
      wTableRat      = 'VEF_EMP_TMOVRATSER';
      wTableRatTMP   = 'TMP_VEF_EMP_TMOVRATSER_TEMP';
      wTableMovPro   = 'VEF_EMP_TA170';
      wTableMovProTMP= 'TMP_VEF_EMP_TA170_TEMP';
    END

  /******************************** Lançamento ********************************/
  SELECT LIST(TRIM(RDB$FIELD_NAME), ', ') FROM RDB$RELATION_FIELDS
  WHERE RDB$RELATION_NAME = :wTable
  INTO :wFields;

  wCabecalho = 'INSERT INTO ' || :wTable || '('||:wFields||')';

  wSelect =             ' SELECT ' || REPLACE(:wFields, 'BDCHAVE,', 'BDEDITCHAVE,') || ' FROM ' || :wTableTMP || ' MOV ';
  wSelect = :wSelect || ' WHERE BDSESSAO = ' || :PRSESSAO;
  wSelect = :wSelect || ' AND NOT EXISTS(';
  wSelect = :wSelect ||                 'SELECT * ';
  wSelect = :wSelect ||                 'FROM '||:wTableIncon||' S ';
  wSelect = :wSelect ||                 'WHERE S.BDSESSAO = MOV.BDSESSAO ';
--  wSelect = :wSelect ||                 'AND S.BDCODEMP = MOV.BDCODEMP_OLD ';
  wSelect = :wSelect ||                 'AND S.BDCHAVE = MOV.BDCHAVE';
  wSelect = :wSelect ||                ')';

  EXECUTE STATEMENT (:wCabecalho || :wSelect);

  /*********************************** Item ***********************************/
  wFields    = NULL;
  wCabecalho = NULL;
  wSelect    = NULL;

  SELECT LIST(TRIM(RDB$FIELD_NAME), ', ') FROM RDB$RELATION_FIELDS
  WHERE RDB$RELATION_NAME = :wTableItem
  AND RDB$FIELD_NAME <> 'BDCODSCP'
  AND RDB$FIELD_NAME <> 'BDREFSOC'  
  INTO :wFields;

  wCabecalho = 'INSERT INTO ' || :wTableItem || '('||:wFields||')';

  SELECT LIST(IIF(POSITION('BDCODREC', RDB$FIELD_NAME) > 0, 'IIF('||TRIM(RDB$FIELD_NAME)||' = 0, NULL, '||TRIM(RDB$FIELD_NAME)||')', TRIM(RDB$FIELD_NAME)), ', ')
  FROM RDB$RELATION_FIELDS
  WHERE RDB$RELATION_NAME = :wTableItem
  AND RDB$FIELD_NAME <> 'BDCODSCP'
  AND RDB$FIELD_NAME <> 'BDREFSOC'  
  INTO :wFields;  

  wSelect =             ' SELECT ' || REPLACE(:wFields, 'BDCHAVE,', 'BDEDITCHAVE,') || ' FROM ' || :wTableItemTMP || ' MOV ';
  wSelect = :wSelect || ' WHERE BDSESSAO = ' || :PRSESSAO;
  wSelect = :wSelect || ' AND NOT EXISTS(';
  wSelect = :wSelect ||                 'SELECT * ';
  wSelect = :wSelect ||                 'FROM '||:wTableIncon||' S ';
  wSelect = :wSelect ||                 'WHERE S.BDSESSAO = MOV.BDSESSAO ';
--  wSelect = :wSelect ||                 'AND S.BDCODEMP = '||:PRCODEMPORI;
  wSelect = :wSelect ||                 'AND S.BDCHAVE = MOV.BDCHAVE';
  wSelect = :wSelect ||                ')';

  EXECUTE STATEMENT (:wCabecalho || :wSelect);

  /********************************** Rateio **********************************/
  wFields    = NULL;
  wCabecalho = NULL;
  wSelect    = NULL;

  SELECT LIST(TRIM(RDB$FIELD_NAME), ', ') FROM RDB$RELATION_FIELDS
  WHERE RDB$RELATION_NAME = :wTableRat
  INTO :wFields;

  wCabecalho = 'INSERT INTO ' || :wTableRat || '('||:wFields||')';

  SELECT LIST(IIF(POSITION('BDCODREC', RDB$FIELD_NAME) > 0, 'IIF('||TRIM(RDB$FIELD_NAME)||' = 0, NULL, '||TRIM(RDB$FIELD_NAME)||')', TRIM(RDB$FIELD_NAME)), ', ')
  FROM RDB$RELATION_FIELDS
  WHERE RDB$RELATION_NAME = :wTableRat
  INTO :wFields;  

  wSelect =             ' SELECT ' || REPLACE(:wFields, 'BDCHAVE,', 'BDEDITCHAVE,') || ' FROM ' || :wTableRatTMP || ' MOV ';
  wSelect = :wSelect || ' WHERE BDSESSAO = ' || :PRSESSAO;
  wSelect = :wSelect || ' AND NOT EXISTS(';
  wSelect = :wSelect ||                 'SELECT * ';
  wSelect = :wSelect ||                 'FROM '||:wTableIncon||' S ';
  wSelect = :wSelect ||                 'WHERE S.BDSESSAO = MOV.BDSESSAO ';
  wSelect = :wSelect ||                 'AND S.BDCHAVE = MOV.BDCHAVE';
  wSelect = :wSelect ||                ')';

  EXECUTE STATEMENT (:wCabecalho || :wSelect);

  /********************************* Retenção *********************************/
  wFields    = NULL;
  wCabecalho = NULL;
  wSelect    = NULL;

  SELECT LIST(TRIM(RDB$FIELD_NAME), ', ') FROM RDB$RELATION_FIELDS
  WHERE RDB$RELATION_NAME = :wTableRet
  INTO :wFields;

  wCabecalho = 'INSERT INTO ' || :wTableRet || '('||:wFields||')';

  SELECT LIST(IIF(POSITION('BDCODREC', RDB$FIELD_NAME) > 0, 'IIF('||TRIM(RDB$FIELD_NAME)||' = 0, NULL, '||TRIM(RDB$FIELD_NAME)||')', TRIM(RDB$FIELD_NAME)), ', ') FROM RDB$RELATION_FIELDS
  WHERE RDB$RELATION_NAME = :wTableRet
  INTO :wFields;

  wSelect =             ' SELECT ' || REPLACE(:wFields, 'BDCHAVE,', 'BDEDITCHAVE,') || ' FROM ' || :wTableRetTMP || ' MOV ';
  wSelect = :wSelect || ' WHERE BDSESSAO = ' || :PRSESSAO;
  wSelect = :wSelect || ' AND NOT EXISTS(';
  wSelect = :wSelect ||                 'SELECT * ';
  wSelect = :wSelect ||                 'FROM '||:wTableIncon||' S ';
  wSelect = :wSelect ||                 'WHERE S.BDSESSAO = MOV.BDSESSAO ';
--  wSelect = :wSelect ||                 'AND S.BDCODEMP = '||:PRCODEMPORI;
  wSelect = :wSelect ||                 'AND S.BDCHAVE = MOV.BDCHAVE';
  wSelect = :wSelect ||                ')';

  EXECUTE STATEMENT (:wCabecalho || :wSelect);

  /*Retenção de INSS do serviço*/
  IF (:PRTIPOLAN = 'SER') THEN
    BEGIN
      wFields    = NULL;
      wCabecalho = NULL;
      wSelect    = NULL;
    
      SELECT LIST(TRIM(RDB$FIELD_NAME), ', ') FROM RDB$RELATION_FIELDS
      WHERE RDB$RELATION_NAME = 'VEF_EMP_TMOVSERDED'
      INTO :wFields;
    
      wCabecalho = 'INSERT INTO VEF_EMP_TMOVSERDED('||:wFields||')';
    
      SELECT LIST(IIF(POSITION('BDCODREC', RDB$FIELD_NAME) > 0, 'IIF('||TRIM(RDB$FIELD_NAME)||' = 0, NULL, '||TRIM(RDB$FIELD_NAME)||')', TRIM(RDB$FIELD_NAME)), ', ') FROM RDB$RELATION_FIELDS
      WHERE RDB$RELATION_NAME = 'VEF_EMP_TMOVSERDED'
      INTO :wFields;
    
      wSelect =             ' SELECT ' || REPLACE(:wFields, 'BDCHAVE,', 'BDEDITCHAVE,') || ' FROM TMP_VEF_EMP_TMOVSERDED_TEMP MOV ';
      wSelect = :wSelect || ' WHERE BDSESSAO = ' || :PRSESSAO;
      wSelect = :wSelect || ' AND NOT EXISTS(';
      wSelect = :wSelect ||                 'SELECT * ';
      wSelect = :wSelect ||                 'FROM '||:wTableIncon||' S ';
      wSelect = :wSelect ||                 'WHERE S.BDSESSAO = MOV.BDSESSAO ';
      wSelect = :wSelect ||                 'AND S.BDCHAVE = MOV.BDCHAVE';
      wSelect = :wSelect ||                ')';
    
      EXECUTE STATEMENT (:wCabecalho || :wSelect);

    END

  /********************************* Parcelas *********************************/
  wFields    = NULL;
  wCabecalho = NULL;
  wSelect    = NULL;

  SELECT LIST(TRIM(RDB$FIELD_NAME), ', ') FROM RDB$RELATION_FIELDS
  WHERE RDB$RELATION_NAME = :wTablePar
  INTO :wFields;

  wCabecalho = 'INSERT INTO ' || :wTablePar || '('||:wFields||')';

  wSelect =             ' SELECT ' || REPLACE(:wFields, 'BDCHAVE,', 'BDEDITCHAVE,') || ' FROM ' || :wTableParTMP || ' MOV ';
  wSelect = :wSelect || ' WHERE BDSESSAO = ' || :PRSESSAO;
  wSelect = :wSelect || ' AND NOT EXISTS(';
  wSelect = :wSelect ||                 'SELECT * ';
  wSelect = :wSelect ||                 'FROM '||:wTableIncon||' S ';
  wSelect = :wSelect ||                 'WHERE S.BDSESSAO = MOV.BDSESSAO ';
  wSelect = :wSelect ||                 'AND S.BDCHAVE = MOV.BDCHAVE';
  wSelect = :wSelect ||                ')';

  EXECUTE STATEMENT (:wCabecalho || :wSelect);

  SELECT SP.BDCODCONFICMSSPED, SP.BDDTOBRIGSPEDCONT FROM SP_CONSULTAEMPRESAS_SIS((SELECT CAST(RDB$GET_CONTEXT('USER_SESSION', 'W_ANOMES') AS INTEGER) FROM RDB$DATABASE), :PRCODEMP, NULL) SP INTO :wCodICMSSped, :wDtObrigSped;
  IF ((COALESCE(:wCodICMSSped, 0) > 0) OR (:wDtObrigSped IS NOT NULL)) THEN
    BEGIN
      /********************************* Produtos *********************************/
      wFields    = NULL;
      wCabecalho = NULL;
      wSelect    = NULL;

      SELECT LIST(TRIM(RDB$FIELD_NAME), ', ') FROM RDB$RELATION_FIELDS
      WHERE RDB$RELATION_NAME = :wTableMovPro
      INTO :wFields;

      wCabecalho = 'INSERT INTO ' || :wTableMovPro || '('||:wFields||')';

      wSelect =             ' SELECT ' || REPLACE(:wFields, 'BDCHAVE,', 'BDEDITCHAVE,') || ' FROM ' || :wTableMovProTMP || ' MOV ';
      wSelect = :wSelect || ' WHERE BDSESSAO = ' || :PRSESSAO;
      wSelect = :wSelect || ' AND NOT EXISTS(';
      wSelect = :wSelect ||                 'SELECT * ';
      wSelect = :wSelect ||                 'FROM '||:wTableIncon||' S ';
      wSelect = :wSelect ||                 'WHERE S.BDSESSAO = MOV.BDSESSAO ';
      wSelect = :wSelect ||                 'AND S.BDCHAVE = MOV.BDCHAVE';
      wSelect = :wSelect ||                ')';

      EXECUTE STATEMENT (:wCabecalho || :wSelect);
    END

  WHEN ANY DO
    BEGIN
      IN AUTONOMOUS TRANSACTION DO
        EXECUTE PROCEDURE LANCA_EXCEPTION('SP_GRAVAR_LAN', SQLCODE, GDSCODE);
      EXCEPTION;
    END
END^

CREATE OR ALTER PROCEDURE GET_ATIVIDADES_SN (
    PRCODEMP INTEGER,
    PRDATALAN DATE,
    prUMAUM DM_BOOLEAN)
RETURNS (
    BDATIVIDADES VARCHAR(11))
AS
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WCOMERCIO DM_BOOLEAN;
DECLARE VARIABLE WINDUSTRIA DM_BOOLEAN;
DECLARE VARIABLE WSERVICO DM_BOOLEAN;
DECLARE VARIABLE WANEXOIII DM_BOOLEAN;
DECLARE VARIABLE WANEXOIV DM_BOOLEAN;
DECLARE VARIABLE WANEXOV DM_BOOLEAN;
DECLARE VARIABLE WANEXOVI DM_BOOLEAN;
BEGIN
  wAno = CAST((SELECT BDDATA FROM SP_PARSE_DATE(:PRDATALAN, 'YYYY')) AS INTEGER);

  SELECT VW.BDCOMERCIO, VW.BDINDUSTRIA, VW.BDSERVICO,
         IIF(:wAno >= 2018, VW.BDANEXOIII_2018, VW.BDANEXOIII) BDANEXOIII,
         IIF(:wAno >= 2018, VW.BDANEXOIV_2018, VW.BDANEXOIV) BDANEXOIV,
         IIF(:wAno >= 2018, VW.BDANEXOV_2018, VW.BDANEXOV) BDANEXOV,
         VW.BDANEXOVI
  FROM VW_VEF_BASE_TEMPITEMSATV VW
  WHERE VW.BDCODEMP = :PRCODEMP
  INTO :wComercio, :wIndustria, :wServico, :wAnexoIII,
       :wAnexoIV, :wAnexoV, :wAnexoVI;

  BDATIVIDADES = '';

  IF (ROW_COUNT > 0) THEN
    BEGIN
      IF (:wComercio = 'TRUE') THEN
        BEGIN
          BDATIVIDADES = '1';

          IF (:PRUMAUM = 'TRUE') THEN
            BEGIN
              SUSPEND;
              BDATIVIDADES = '';
            END
        END

      IF (:wIndustria = 'TRUE') THEN
        BEGIN
          IF (:BDATIVIDADES <> '') THEN
            BDATIVIDADES = BDATIVIDADES || ',';
          BDATIVIDADES = BDATIVIDADES || '2';

          IF (:PRUMAUM = 'TRUE') THEN
            BEGIN
              SUSPEND;
              BDATIVIDADES = '';
            END
        END

      IF (:wServico = 'TRUE') THEN
        BEGIN
          IF (:wAnexoIII = 'TRUE') THEN
            BEGIN
              IF (:BDATIVIDADES <> '') THEN
                BDATIVIDADES = BDATIVIDADES || ',';
              BDATIVIDADES = BDATIVIDADES || '3';

              IF (:PRUMAUM = 'TRUE') THEN
                BEGIN
                  SUSPEND;
                  BDATIVIDADES = '';
                END
            END

          IF (:wAnexoIV = 'TRUE') THEN
            BEGIN
              IF (:BDATIVIDADES <> '') THEN
                BDATIVIDADES = BDATIVIDADES || ',';
              BDATIVIDADES = BDATIVIDADES || '4';

              IF (:PRUMAUM = 'TRUE') THEN
                BEGIN
                  SUSPEND;
                  BDATIVIDADES = '';
                END
            END

          IF (:wAnexoV = 'TRUE') THEN
            BEGIN
              IF (:BDATIVIDADES <> '') THEN
                BDATIVIDADES = BDATIVIDADES || ',';
              BDATIVIDADES = BDATIVIDADES || '5';

              IF (:PRUMAUM = 'TRUE') THEN
                BEGIN
                  SUSPEND;
                  BDATIVIDADES = '';
                END
            END

          IF ((wAno < 2018) AND (:wAnexoVI = 'TRUE')) THEN
            BEGIN
              IF (:BDATIVIDADES <> '') THEN
                BDATIVIDADES = BDATIVIDADES || ',';
              BDATIVIDADES = BDATIVIDADES || '6';
            END
        END
    END

  IF (COALESCE(:BDATIVIDADES, '') <> '') THEN
    SUSPEND;
END^

create or alter procedure SP_GET_DEPENDENCIAS (
    PRTABELA varchar(100),
    PRWHERE varchar(1000))
returns (
    BDTABELA varchar(100),
    BDDESCRICAO varchar(1000))
as
declare variable WWHERE varchar(1000);
declare variable WCAMPO varchar(33);
declare variable WTABELA varchar(33);
declare variable WFOREINGKEY varchar(33);
declare variable WPOSITION integer;
declare variable WCAMPOPK varchar(33);
declare variable WSQL varchar(1000);
declare variable WFIELDS varchar(1000);
declare variable WEXISTS integer;
declare variable WFIELDSPK varchar(1000);
begin
  -- nome da foreing keys feitas com a tabela selecionada
  for SELECT distinct trim(rc.RDB$CONSTRAINT_NAME) AS constraint_name
      FROM RDB$INDEX_SEGMENTS s
      inner JOIN RDB$INDICES i ON i.RDB$INDEX_NAME = s.RDB$INDEX_NAME
      inner JOIN RDB$RELATION_CONSTRAINTS rc ON rc.RDB$INDEX_NAME = s.RDB$INDEX_NAME
      inner JOIN RDB$REF_CONSTRAINTS refc ON refc.RDB$CONSTRAINT_NAME = rc.RDB$CONSTRAINT_NAME
      inner JOIN RDB$RELATION_CONSTRAINTS rc2 ON rc2.RDB$CONSTRAINT_NAME = refc.RDB$CONST_NAME_UQ
      WHERE rc.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY'
      AND rc2.RDB$RELATION_NAME = upper(:prtabela)
      AND ((refc.RDB$DELETE_RULE <> 'CASCADE') and (refc.RDB$DELETE_RULE <> 'SET NULL'))
      ORDER BY rc.RDB$CONSTRAINT_NAME, s.RDB$FIELD_POSITION
  into :wforeingkey do
  begin
    wwhere = prwhere;
    wfields = '';
    wfieldspk = '';
    -- foreing key com seus campos
    for SELECT trim(i.RDB$RELATION_NAME) AS table_name,
               trim(s.RDB$FIELD_NAME) AS field_name,
               s.RDB$FIELD_POSITION
        FROM RDB$INDEX_SEGMENTS s
        inner JOIN RDB$INDICES i ON i.RDB$INDEX_NAME = s.RDB$INDEX_NAME
        inner JOIN RDB$RELATION_CONSTRAINTS rc ON rc.RDB$INDEX_NAME = s.RDB$INDEX_NAME
        inner JOIN RDB$REF_CONSTRAINTS refc ON rc.RDB$CONSTRAINT_NAME = refc.RDB$CONSTRAINT_NAME
        inner JOIN RDB$RELATION_CONSTRAINTS rc2 ON rc2.RDB$CONSTRAINT_NAME = refc.RDB$CONST_NAME_UQ
        WHERE rc.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY'
        AND trim(rc.RDB$CONSTRAINT_NAME) = upper(:wforeingkey)
        ORDER BY rc.RDB$CONSTRAINT_NAME, s.RDB$FIELD_POSITION
    into :wtabela, :wcampo, :wposition do
    begin
      wfields = wfields||wcampo||',';
      if (wfieldspk = '') then
         wfieldspk = wfieldspk||''''||'  '||wcampo||'='||''''||'||'||'trim('||wcampo||')';
      else
         wfieldspk = wfieldspk||'||'||''''||'  '||wcampo||'='||''''||'||'||'trim('||wcampo||')';

      for SELECT trim(s.rdb$field_name)
          FROM RDB$INDEX_SEGMENTS s
          inner JOIN RDB$RELATION_CONSTRAINTS rc ON rc.RDB$INDEX_NAME = s.RDB$INDEX_NAME
          WHERE rc.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY'
          AND trim(rc.RDB$RELATION_NAME) = upper(:prtabela)
          and s.RDB$FIELD_POSITION = :wposition
      into :wcampopk do
      begin
        wwhere = replace(upper(wwhere), upper(wcampopk), upper(wcampo));
      end
    end

    if (wfields <> '') then
    begin
      bdtabela = wtabela;
      wfields = substring(wfields from 1 for strlen(wfields)-1);
      wsql = 'select coalesce(count(*), 0) as bdexists from (select first 1 '||wfields||' from '||wtabela||' '||wwhere||')';
      execute statement wsql into :WEXISTS;
      if (wexists > 0) then
      begin
        select bddescricao from TDESC_TABLE_BANCO where trim(bdtable) = trim(:wtabela) into :BDDESCRICAO;
        suspend;
--        wsql = 'select '||wfieldspk||' from '||wtabela||' '||wwhere||'';
--        for execute statement wsql into :bddescricao do
--        suspend;
      end
    end
  end
end^

CREATE OR ALTER PROCEDURE SP_VALIDAR_TRANSFERENCIA (
    PRID_TERMINAL INTEGER,
    PRCODEMPORI INTEGER,
    PRCODEMPDEST INTEGER,
    PRREFTRANS INTEGER,
    PRTIPOLAN CHAR(3))
AS
DECLARE VARIABLE WTABLE VARCHAR(31);
DECLARE VARIABLE WTABLEITEM VARCHAR(31);
DECLARE VARIABLE WTABLEMOVPROD VARCHAR(31);
DECLARE VARIABLE WTABLEINCON VARCHAR(31);
DECLARE VARIABLE WTABLEPGTO VARCHAR(31);
DECLARE VARIABLE WSESSAODEST INTEGER;
DECLARE VARIABLE WNRNOTASER DM_BOOLEAN;
DECLARE VARIABLE WDATAEMISER DM_BOOLEAN;
DECLARE VARIABLE WSERIESER DM_BOOLEAN;
DECLARE VARIABLE WESPECIESER DM_BOOLEAN;
DECLARE VARIABLE WNATOPSER DM_BOOLEAN;
DECLARE VARIABLE WPARTSER DM_BOOLEAN;
DECLARE VARIABLE WCHAVENFSER DM_BOOLEAN;
DECLARE VARIABLE WSQL VARCHAR(2500);
DECLARE VARIABLE WCODENQFED INTEGER;
DECLARE VARIABLE WRETINSS DM_BOOLEAN;
DECLARE VARIABLE WPERINSS DM_NUMERIC_7_4_ALIQ;
DECLARE VARIABLE WCODCONFICMSSPED INTEGER;
DECLARE VARIABLE wDtObrigSped DATE;
DECLARE VARIABLE WSIGLAUFDEST VARCHAR(2);
BEGIN
  /*Sessão empresa destino*/
  SELECT S.BDSESSAO
  FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRID_TERMINAL
  AND S.BDTABLE = 'DESTINO'
  INTO :wSessaoDest;

  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTable       = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItem   = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      wTableMovProd= 'VEF_EMP_TMOVPROENT';
      wTableIncon  = 'VEF_INCON_TMOVENT';
      wTablePgto   = 'VEF_EMP_TMOVENTPARPGTO';
    END
  ELSE
  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTable       = 'TMP_VEF_EMP_TMOVSAI_TEMP';
      wTableItem   = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
      wTableMovProd= 'VEF_EMP_TMOVPROSAI';
      wTableIncon  = 'VEF_INCON_TMOVSAI';
      wTablePgto   = 'VEF_EMP_TMOVSAIPARPGTO';
    END
  ELSE
  IF (:PRTIPOLAN = 'SER') THEN
    BEGIN
      wTable       = 'TMP_VEF_EMP_TMOVSER_TEMP';
      wTableItem   = 'TMP_VEF_EMP_TMOVSERITENS_TEMP';
      wTableMovProd= 'VEF_EMP_TA170';
      wTableIncon  = 'VEF_INCON_TMOVSER';
      wTablePgto   = 'VEF_EMP_TMOVSERPARPGTO';
    END

  EXECUTE STATEMENT 'DELETE FROM '||:wTableIncon||' WHERE BDSESSAO = '||:wSessaoDest;

  SELECT SP.BDCODENQFED, SP.BDRETINSS, SP.BDALIQINSS, SP.BDCODCONFICMSSPED, SP.BDDTOBRIGSPEDCONT, SP.BDSIGLAUF FROM SP_CONSULTAEMPRESAS_SIS(:PRREFTRANS, :PRCODEMPDEST, NULL) SP
  INTO :wCodEnqFed, :wRetINSS, :wPerINSS, :wCodConfICMSSped, :wDtObrigSped, :wSiglaUFDest;

  /*VALIDAÇÕES*/
  IF ((COALESCE(:wCodConfICMSSped, 0) > 0) OR (:wDtObrigSped IS NOT NULL)) THEN /*Só valida o produto se a empresa destino for do sped*/
    BEGIN
      /*170 - Produto não cadastrado na empresa de destino.*/
      wSQL =          'INSERT INTO '||:wTableIncon||'(BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINCONSISTENCIA) ';
      wSQL = :wSQL || 'SELECT I.BDSESSAO, I.BDCODEMP_OLD, I.BDCHAVE, I.BDORDEM, '||IIF(:PRTIPOLAN = 'SER', 'A.BDNUM_ITEM', 'A.BDORDEMPRO')||', 170 BDCODINCONSISTENCIA ';
      wSQL = :wSQL || 'FROM (';
      wSQL = :wSQL ||      ' SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEM, '||:PRCODEMPORI||' BDCODEMP_OLD, I.BDCHAVE_OLD ';
      wSQL = :wSQL ||      ' FROM '||:wTableItem||' I ';
      wSQL = :wSQL ||      ' WHERE I.BDSESSAO = '||:wSessaoDest;
      wSQL = :wSQL ||      ') I ';
      wSQL = :wSQL || 'JOIN '||:wTableMovProd||' A ON(A.BDCODEMP = I.BDCODEMP_OLD AND A.BDCHAVE = I.BDCHAVE_OLD AND A.BDORDEM = I.BDORDEM AND A.BDCODPROD IS NOT NULL) ';
      wSQL = :wSQL || 'JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = I.BDCODEMP_OLD AND PRO.BDCODPROD = A.BDCODPROD) ';
      wSQL = :wSQL || 'LEFT OUTER JOIN TCADPRO_VINC PRO_D ON(PRO_D.BDCODEMP = I.BDCODEMP AND PRO_D.BDDESCPROD = PRO.BDDESCPROD) ';
      wSQL = :wSQL || 'WHERE PRO_D.BDCODPROD IS NULL; '; /*Não está cadastrado na empresa destino*/

      EXECUTE STATEMENT :wSQL;
    END

  /*22 - Lançamento já existente na base de dados*/
  IF (:PRTIPOLAN = 'SER') THEN /*Validações específicas de serviço*/
    BEGIN
      /*Verifica se não existe o lançamento na base */
      SELECT R.BDNRNOTASER, R.BDDATAEMISER, R.BDSERIESER, R.BDESPECIESER, R.BDNATOPSER, R.BDPARTSER, R.BDCHAVENFSER
      FROM VEF_BASE_TCONFLANCREPETIDOS R
      INTO :wNrNotaSer, :wDataEmiSer, :wSerieSer, :wEspecieSer, :wNatOpSer, :wPartSer, :wChaveNFSer;
          
      /*Se não tem configuração de lançamento repetido, usa todos os parametros para comparar.*/
      IF (ROW_COUNT = 0) THEN
        BEGIN
          wNRNotaSer = 'TRUE';
          wDataEmiSer= 'TRUE';
          wSerieSer  = 'TRUE';
          wEspecieSer= 'TRUE';
          wNatOpSer  = 'TRUE';
          wPartSer   = 'TRUE';
          wChaveNFSer= 'TRUE';
        END
        
      /* Insere incosistência de lançamentos repetidos */
      /* Caso a nota seja cancelada e já exista na base, está importando evento de cancelamento, apenas vai cancelar a nota existente... */
      wSQL = '          INSERT INTO '||:wTableIncon||'(BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA) ';
      wSQL = :wSQL || ' SELECT T.BDCODEMP, T.BDCHAVE, T.BDSESSAO, 22 BDCODINCONSISTENCIA ';
      wSQL = :wSQL || ' FROM '||:wTable||' T ';
      IF (UPPER(:wNatOpSer) = 'TRUE') THEN
        wSQL = :wSQL || ' JOIN '||:wTableItem||' IT ON(IT.BDSESSAO = T.BDSESSAO AND IT.BDCODEMP = T.BDCODEMP AND IT.BDCHAVE = T.BDCHAVE) ';
      wSQL = :wSQL || ' WHERE T.BDSESSAO = '||:wSessaoDest;
      wSQL = :wSQL || ' AND EXISTS( ';
      wSQL = :wSQL || '            SELECT * ';
      wSQL = :wSQL || '            FROM VEF_EMP_TMOVSER S ';
      IF (UPPER(:wNatOpSer) = 'TRUE') THEN
        wSQL = :wSQL || '            JOIN VEF_EMP_TMOVSERITENS I ON(I.BDCODEMP = S.BDCODEMP AND I.BDCHAVE = S.BDCHAVE) ';
      wSQL = :wSQL || '            WHERE S.BDCODEMP = T.BDCODEMP ';
      --wSQL = :wSQL || '            AND S.BDCHAVE = T.BDCHAVE ';
      IF (UPPER(:wNRNotaSer) = 'TRUE') THEN
        wSQL = :wSQL || ' AND S.BDNUMDOCINI = T.BDNUMDOCINI AND S.BDNUMDOCFIM = T.BDNUMDOCFIM ';
      IF (UPPER(:wDataEmiSer) = 'TRUE') THEN
        wSQL = :wSQL || ' AND S.BDDATAEMISSAO = T.BDDATAEMISSAO ';
      IF (UPPER(:wSerieSer)   = 'TRUE') THEN
        wSQL = :wSQL || ' AND COALESCE(S.BDSERIE, '''') = COALESCE(T.BDSERIE, '''') ';
      IF (UPPER(:wEspecieSer) = 'TRUE') THEN
        wSQL = :wSQL || ' AND COALESCE(S.BDESPECIE, '''') = COALESCE(T.BDESPECIE, '''') ';
      IF (UPPER(:wPartSer) = 'TRUE') THEN
        wSQL = :wSQL || ' AND S.BDCODTER = T.BDCODTER ';
      IF (UPPER(:wChaveNFSer) = 'TRUE') THEN
        wSQL = :wSQL || ' AND COALESCE(S.BDCHAVENFE, '''') = COALESCE(T.BDCHAVENFE, '''') ';
      IF (UPPER(:wNatOpSer) = 'TRUE') THEN
        wSQL = :wSQL || ' AND I.BDCODNAT = IT.BDCODNAT ';
      wSQL = :wSQL || '           ) ';
      wSQL = :wSQL || ' GROUP BY T.BDCODEMP, T.BDCHAVE, T.BDSESSAO, BDCODINCONSISTENCIA ';
        
      EXECUTE STATEMENT :wSQL;
    END

  /*Empresa do simples nacional*/
  IF ((:wCodEnqFed IS NOT NULL) AND (:wCodEnqFed IN(1, 2, 4))) THEN
    BEGIN
      /*171 - Natureza de operação não está parametrizada com as bases do simples nacional.*/
      wSQL =          'INSERT INTO '||:wTableIncon||'(BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA) ';
      wSQL = :wSQL || 'SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDSESSAO, 171 BDCODINCONSISTENCIA ';
      wSQL = :wSQL || 'FROM ( ';
      wSQL = :wSQL ||       'SELECT M.BDSESSAO, M.BDCHAVE, M.BDCODEMP, M.BDDATAEMISSAO, ';
      wSQL = :wSQL ||             ' CASE WHEN UF.BDSIGLAUF <> '''||:wSiglaUFDest||''' THEN ''6''||SUBSTRING(I.BDCODNAT FROM 2 FOR CHAR_LENGTH(I.BDCODNAT)-1) ';
      wSQL = :wSQL ||                  ' WHEN UF.BDSIGLAUF = ''EX''                   THEN ''7''||SUBSTRING(I.BDCODNAT FROM 2 FOR CHAR_LENGTH(I.BDCODNAT)-1) ';
      wSQL = :wSQL ||             ' ELSE ';
      wSQL = :wSQL ||             '   ''5''||SUBSTRING(I.BDCODNAT FROM 2 FOR CHAR_LENGTH(I.BDCODNAT)-1) ';
      wSQL = :wSQL ||              'END BDCODNAT, I.BDCODATVM ';
      wSQL = :wSQL ||       'FROM '||:wTable||' M ';
      wSQL = :wSQL ||       'JOIN '||:wTableItem||' I ON (I.BDSESSAO = M.BDSESSAO AND I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE/* AND I.BDCODATVM IS NOT NULL*/) ';
      wSQL = :wSQL ||       'JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = M.BDCODTER) ';
      wSQL = :wSQL ||       'JOIN TCIDADE CID ON(CID.BDCODCID = TER.BDCODCID) ';
      wSQL = :wSQL ||       'JOIN TUF UF ON(UF.BDCODUF = CID.BDCODUF) ';
      wSQL = :wSQL ||       'WHERE M.BDSESSAO = '||:wSessaoDest||' ';

      IF (:PRTIPOLAN = 'SER') THEN
        wSQL = :wSQL ||     'AND M.BDTIPLAN = 0 ';

      wSQL = :wSQL ||      ') MOV ';
      wSQL = :wSQL || 'JOIN VW_TEMPRESAS_REF EMP ON(EMP.BDCODEMP = MOV.BDCODEMP AND EMP.BDCODCID IS NOT NULL) ';
      wSQL = :wSQL || 'LEFT OUTER JOIN VEF_BASE_TNATOPCONFSN ATV ON (ATV.BDCODNAT = MOV.BDCODNAT AND ATV.BDCODATIVSIMPNAC IN (SELECT CAST(BDATIVIDADES AS INTEGER) ';
      wSQL = :wSQL || '                                                                                          FROM GET_ATIVIDADES_SN(MOV.BDCODEMP, MOV.BDDATAEMISSAO, ''TRUE''))) ';
      wSQL = :wSQL || 'JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = MOV.BDCODNAT AND NAT.BDNAOLEVARSN = ''FALSE'') ';
--      wSQL = :wSQL || 'LEFT OUTER JOIN VEF_BASE_TCONFATVMSN ATVM ON (ATVM.BDCODATVM = MOV.BDCODATVM AND ATVM.BDCODCID = EMP.BDCODCID AND ATVM.BDCODATIVSIMPNAC IN (SELECT CAST(BDATIVIDADES AS INTEGER) ';
--      wSQL = :wSQL || '                                                                                          FROM GET_ATIVIDADES_SN(MOV.BDCODEMP, MOV.BDDATAEMISSAO, ''TRUE''))) ';
      wSQL = :wSQL || 'LEFT OUTER JOIN TATVMUNICIPAL ATVO ON(ATVO.BDCODATVM = MOV.BDCODATVM) ';
      wSQL = :wSQL || 'LEFT OUTER JOIN TATVMUNICIPAL ATVD ON(ATVD.BDCODCID = EMP.BDCODCID AND ATVD.BDCODMUNATVM = ATVO.BDCODMUNATVM AND ATVD.BDREFATVM = (SELECT MAX(A.BDREFATVM) FROM TATVMUNICIPAL A WHERE A.BDCODCID = ATVD.BDCODCID AND A.BDCODMUNATVM = ATVD.BDCODMUNATVM)) ';
      wSQL = :wSQL || 'LEFT OUTER JOIN VEF_BASE_TCONFATVMSN ATVM ON (ATVM.BDCODATVM = ATVD.BDCODATVM AND ATVM.BDCODATIVSIMPNAC IN (SELECT CAST(BDATIVIDADES AS INTEGER) ';
      wSQL = :wSQL ||                                                                                                             'FROM GET_ATIVIDADES_SN(MOV.BDCODEMP, MOV.BDDATAEMISSAO, ''TRUE''))) ';
      wSQL = :wSQL || 'WHERE (SELECT BDATIVIDADES ';
      wSQL = :wSQL || '       FROM GET_ATIVIDADES_SN(MOV.BDCODEMP, MOV.BDDATAEMISSAO, ''FALSE'')) <> '''' ';
      wSQL = :wSQL || 'AND (COALESCE(ATVM.BDCODATIVSIMPNAC, ATV.BDCODATIVSIMPNAC) IS NULL); ';
      EXECUTE STATEMENT :wSQL;
    END

  IF (:PRTIPOLAN = 'SER') THEN
    BEGIN
      /*172 - Empreendimento não cadastrado na empresa de destino.*/
      wSQL =          'INSERT INTO '||:wTableIncon||'(BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA) ';
      wSQL = :wSQL || 'SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDSESSAO, 172 BDCODINCONSISTENCIA ';
      wSQL = :wSQL || 'FROM ( ';
      wSQL = :wSQL || '      SELECT M.BDSESSAO, M.BDCODEMP, M.BDCHAVE, M.BDCODEMPREENDIMENTO, M.BDCODEMP_OLD ';
      wSQL = :wSQL || '      FROM '||:wTable||' M ';
      wSQL = :wSQL || '      WHERE M.BDSESSAO = '||:wSessaoDest||' ';
      wSQL = :wSQL || '      AND M.BDCODEMPREENDIMENTO IS NOT NULL ';
      wSQL = :wSQL || '     ) MOV ';
      wSQL = :wSQL || 'JOIN VEF_EMP_TCADEMPREENDIMENTO EMP ON(EMP.BDCODEMP = MOV.BDCODEMP_OLD AND EMP.BDCODEMPREENDIMENTO = MOV.BDCODEMPREENDIMENTO) ';
      wSQL = :wSQL || 'LEFT OUTER JOIN VEF_EMP_TCADEMPREENDIMENTO EMP_D ON(EMP_D.BDCODEMP = MOV.BDCODEMP AND EMP_D.BDNOMEEMPRE = EMP.BDNOMEEMPRE) ';
      wSQL = :wSQL || 'WHERE EMP_D.BDCODEMPREENDIMENTO IS NULL;';
      EXECUTE STATEMENT :wSQL;

      /*174 - já transmitida para Reinf, não será feito a transferência dos dados para outra empresa.*/
      wSQL =          'INSERT INTO '||:wTableIncon||'(BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA) ';
      wSQL = :wSQL || 'SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDSESSAO, 174 BDCODINCONSISTENCIA ';
      wSQL = :wSQL || 'FROM ( ';
      wSQL = :wSQL || '      SELECT M.BDSESSAO, M.BDCODEMP, M.BDCHAVE, M.BDCODEMP_OLD ';
      wSQL = :wSQL || '      FROM '||:wTable||' M ';
      wSQL = :wSQL || '      WHERE M.BDSESSAO = '||:wSessaoDest;
      wSQL = :wSQL || '     ) MOV ';
      wSQL = :wSQL || 'JOIN TOL_VEF_REINF_EVT_SER EVT ON(EVT.BDCODEMPMOV = MOV.BDCODEMP_OLD AND EVT.BDCHAVE = MOV.BDCHAVE)';
      EXECUTE STATEMENT :wSQL;

      IF (COALESCE(:wCodConfICMSSped, 0) > 0) THEN /*Só valida o produto se a empresa destino for do sped*/
        BEGIN
          /*175 - A informação complementar do registro A110 não esta cadastrada na empresa de destino.*/
          wSQL =          'INSERT INTO '||:wTableIncon||'(BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA) ';
          wSQL = :wSQL || 'SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDSESSAO, 175 BDCODINCONSISTENCIA ';
          wSQL = :wSQL || 'FROM ( ';
          wSQL = :wSQL || '      SELECT M.BDSESSAO, M.BDCODEMP, M.BDCHAVE, M.BDCODEMP_OLD ';
          wSQL = :wSQL || '      FROM '||:wTable||' M ';
          wSQL = :wSQL || '      WHERE M.BDSESSAO = '||:wSessaoDest;
          wSQL = :wSQL || '     ) MOV ';
          wSQL = :wSQL || 'JOIN VEF_EMP_TA110 A110 ON(A110.BDCODEMP = MOV.BDCODEMP_OLD AND A110.BDCHAVE = MOV.BDCHAVE) ';
          wSQL = :wSQL || 'JOIN VEF_BASE_TCADINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP_OLD AND INF.BDORDEMINFCOM = A110.BDORDEMINFCOM) ';
          wSQL = :wSQL || 'LEFT OUTER JOIN VEF_BASE_TCADINFCOM INF_D ON(INF_D.BDCODEMP = MOV.BDCODEMP AND INF_D.BDDESCINFCOMHASH = INF.BDDESCINFCOMHASH) ';
          wSQL = :wSQL || 'WHERE INF_D.BDORDEMINFCOM IS NULL;';
          EXECUTE STATEMENT :wSQL;
        END

      /*178 - Lançamento com valor de INSS e empresa destino sem percentual de INSS informado no cadastro da empresa.*/
      IF ((:wRetINSS = 'TRUE') AND ((:wPerINSS IS NULL) OR (:wPerINSS = 0))) THEN /*Retenção de INSS (empreiteira de mão de obra)*/
        BEGIN
          wSQL =          'INSERT INTO '||:wTableIncon||'(BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA) ';
          wSQL = :wSQL || 'SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDSESSAO, 178 BDCODINCONSISTENCIA ';
          wSQL = :wSQL || 'FROM ( ';
          wSQL = :wSQL || '      SELECT M.BDSESSAO, M.BDCODEMP, M.BDCHAVE, M.BDCODEMP_OLD ';
          wSQL = :wSQL || '      FROM '||:wTable||' M ';
          wSQL = :wSQL || '      WHERE M.BDSESSAO = '||:wSessaoDest;
          wSQL = :wSQL || '     ) MOV ';
          wSQL = :wSQL || 'JOIN VEF_EMP_TMOVSERDED INSS ON(INSS.BDCODEMP = MOV.BDCODEMP_OLD AND INSS.BDCHAVE = MOV.BDCHAVE AND COALESCE(INSS.BDRETINSS, 0) > 0)';
          EXECUTE STATEMENT :wSQL;
        END
    END

  IF ((:PRTIPOLAN = 'SER') OR (:PRTIPOLAN = 'ENT')) THEN
    BEGIN
      /*173 - Este lançamento possui darf gerado.*/
      wSQL =          'INSERT INTO '||:wTableIncon||'(BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA) ';
      wSQL = :wSQL || 'SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDSESSAO, 173 BDCODINCONSISTENCIA ';
      wSQL = :wSQL || 'FROM ( ';
      wSQL = :wSQL || '      SELECT M.BDSESSAO, M.BDCODEMP, M.BDCHAVE, M.BDCODEMP_OLD ';
      wSQL = :wSQL || '      FROM '||:wTable||' M ';
      wSQL = :wSQL || '      WHERE M.BDSESSAO = '||:wSessaoDest;
      wSQL = :wSQL || '     ) MOV ';
      wSQL = :wSQL || 'JOIN VEF_EMP_DARF_RET DARF ON(DARF.BDCODEMP = MOV.BDCODEMP_OLD AND DARF.'||IIF(:PRTIPOLAN = 'SER', 'BDCHAVE', 'BDCHAVEENT')||' = MOV.BDCHAVE)';
      EXECUTE STATEMENT :wSQL;

      /*176 - O lançamento já possui GPS gerada na Folha e não pode ser transferido.*/
      wSQL =          'INSERT INTO '||:wTableIncon||'(BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA) ';
      wSQL = :wSQL || 'SELECT MOV.BDCODEMP_OLD, MOV.BDCHAVE, MOV.BDSESSAO, 176 BDCODINCONSISTENCIA '; /*Recebido*/
      wSQL = :wSQL || 'FROM ( ';
      wSQL = :wSQL || '      SELECT M.BDSESSAO, M.BDCODEMP, M.BDCHAVE, M.BDCODEMP_OLD, TOL.BDCHAVERH ';
      wSQL = :wSQL || '      FROM '||:wTable||' M ';
      wSQL = :wSQL || '      JOIN TOL_VEF_EMP_T'||:PRTIPOLAN||'INSSCONT TOL ON(TOL.BDCODEMP = M.BDCODEMP_OLD AND TOL.BDCHAVEEF = M.BDCHAVE) ';
      wSQL = :wSQL || '      WHERE M.BDSESSAO = '||:wSessaoDest;
      wSQL = :wSQL || '     ) MOV ';
      wSQL = :wSQL || 'JOIN VRHF_EMP_TNFCONT N ON (N.BDCODEMP = MOV.BDCODEMP_OLD AND N.BDCHAVE = MOV.BDCHAVERH) ';
      wSQL = :wSQL || 'JOIN VRHF_EMP_DARF_TNFCONT H ON (H.BDCODEMP = N.BDCODEMP AND H.BDCHAVE = N.BDCHAVE) ';
      wSQL = :wSQL || 'UNION ';
      wSQL = :wSQL || 'SELECT MOV.BDCODEMP_OLD, MOV.BDCHAVE, MOV.BDSESSAO, 176 BDCODINCONSISTENCIA '; /*Emitido*/
      wSQL = :wSQL || 'FROM ( ';
      wSQL = :wSQL || '      SELECT M.BDSESSAO, M.BDCODEMP, M.BDCHAVE, M.BDCODEMP_OLD, TOL.BDCHAVERH ';
      wSQL = :wSQL || '      FROM '||:wTable||' M ';
      wSQL = :wSQL || '      JOIN TOL_VEF_EMP_T'||:PRTIPOLAN||'INSS TOL ON(TOL.BDCODEMP = M.BDCODEMP_OLD AND TOL.BDCHAVEEF = M.BDCHAVE) ';
      wSQL = :wSQL || '      WHERE M.BDSESSAO = '||:wSessaoDest;
      wSQL = :wSQL || '     ) MOV ';
      wSQL = :wSQL || 'JOIN VRHF_EMP_TNOTASFISCAIS N ON (N.BDCODEMP = MOV.BDCODEMP_OLD AND N.BDCHAVE = MOV.BDCHAVERH) ';
      wSQL = :wSQL || 'JOIN VRHF_EMP_THISTNF H ON (H.BDCODEMP = N.BDCODEMP AND H.BDCHAVE = N.BDCHAVE) ';
      EXECUTE STATEMENT :wSQL;
    END

  /*177 - O lançamento já possui parcela com baixa e não pode ser transferido.*/
  wSQL =          'INSERT INTO '||:wTableIncon||'(BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA) ';
  wSQL = :wSQL || 'SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDSESSAO, 177 BDCODINCONSISTENCIA ';
  wSQL = :wSQL || 'FROM ( ';
  wSQL = :wSQL || '      SELECT M.BDSESSAO, M.BDCODEMP, M.BDCHAVE, M.BDCODEMP_OLD ';
  wSQL = :wSQL || '      FROM '||:wTable||' M ';
  wSQL = :wSQL || '      WHERE M.BDSESSAO = '||:wSessaoDest;
  wSQL = :wSQL || '     ) MOV ';
  wSQL = :wSQL || 'JOIN '||:wTablePGTO||' PGTO ON(PGTO.BDCODEMP = MOV.BDCODEMP_OLD AND PGTO.BDCHAVE = MOV.BDCHAVE) ';
  wSQL = :wSQL || 'GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDSESSAO, BDCODINCONSISTENCIA;';
  EXECUTE STATEMENT :wSQL;
END^

CREATE OR ALTER PROCEDURE SP_TRANSFERENCIA_TOL (
    PRID_TERMINAL INTEGER,
    PRTIPOLAN CHAR(3),
    PRSTATE CHAR(3))
AS
DECLARE VARIABLE WSESSAODEST INTEGER;
DECLARE VARIABLE WSESSAOORI INTEGER;
DECLARE VARIABLE WULTCHAVE INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
BEGIN

  /*Sessão empresa destino*/
  SELECT S.BDSESSAO
  FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRID_TERMINAL
  AND S.BDTABLE = 'DESTINO'
  INTO :wSessaoDest;

  /*Sessão empresa origem*/
  SELECT S.BDSESSAO
  FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRID_TERMINAL
  AND S.BDTABLE = 'ORIGEM'
  INTO :wSessaoOri;

  IF (:PRSTATE = 'INS') THEN
    BEGIN
      IF (:PRTIPOLAN = 'SER') THEN
        BEGIN
          SELECT C.BDULTCHAVE
          FROM TMP_TCHAVE_TRANSFERENCIA C
          WHERE C.BDTABLE = 'TOL_VEF_EMP_TSERINSS'
          INTO :wUltChave;
    
          IF ((:wUltChave IS NOT NULL) AND (:wUltChave > 0)) THEN
            BEGIN
              SETORDEMSEQUENCIAL(0);
    
              /*VRHF_EMP_TNOTASFISCAIS*/
              /*Cria o registro na tabela TEMP para inserir na física e na tol*/
              INSERT INTO TMP_VRHF_EMP_TNOTASFISCAIS_TEMP(BDSESSAO, BDCODEMP, BDCHAVEEF, BDCHAVE, BDREFNF, BDNOTAFISCAL,
                                                          BDDATAEMINF, BDVALNF, BDVALDESCNF, BDPERCRETENCAONF, BDTIPOLAN)
              SELECT SER.BDSESSAO, SER.BDCODEMP, SER.BDEDITCHAVE, (:wUltChave - GETORDEMSEQUENCIAL(0))+1 BDCHAVE, RH.BDREFNF,
                     RH.BDNOTAFISCAL, RH.BDDATAEMINF, SER.BDVALNF, SER.BDRETINSS,
                     IIF(SER.BDVALNF > 0, ((SER.BDRETINSS * 100) / SER.BDVALNF), 0), RH.BDTIPOLAN
              FROM (
                    SELECT SER.BDSESSAO, SER.BDCODEMP, SER.BDCHAVE, SER.BDEDITCHAVE, COALESCE(DED.BDRETINSS, 0) BDRETINSS,
                           SER.BDCODEMP_OLD,
                           (SER.BDVALORNOTA - COALESCE(DED.BDVLRMATERIAIS, 0) - COALESCE(DED.BDVLRSUBEMPREITEIRAS, 0)) BDVALNF
                    FROM TMP_VEF_EMP_TMOVSER_TEMP SER
                    LEFT OUTER JOIN VEF_EMP_TMOVSERDED DED ON(DED.BDCODEMP = SER.BDCODEMP_OLD AND DED.BDCHAVE = SER.BDCHAVE)
                    WHERE SER.BDSESSAO = :wSessaoDest
                    AND NOT EXISTS (
                                    SELECT INCO.BDCODINCONSISTENCIA
                                    FROM VEF_INCON_TMOVSER INCO
                                    WHERE INCO.BDSESSAO = SER.BDSESSAO
                                    AND INCO.BDCHAVE = SER.BDCHAVE
                                   )
                   ) SER
              JOIN TOL_VEF_EMP_TSERINSS TOL ON(TOL.BDCODEMP = SER.BDCODEMP_OLD AND TOL.BDCHAVEEF = SER.BDCHAVE)
              JOIN VRHF_EMP_TNOTASFISCAIS RH ON(RH.BDCODEMP = TOL.BDCODEMP AND RH.BDCHAVE = TOL.BDCHAVERH);
    
              /*Insere na física*/
              INSERT INTO VRHF_EMP_TNOTASFISCAIS(BDCODEMP, BDCHAVE, BDCODCENTRO, BDCODTPCC, BDREFNF, BDNOTAFISCAL,
                                                 BDDATAEMINF, BDVALNF, BDVALDESCNF, BDPERCRETENCAONF, BDTIPOLAN)
              SELECT TMP.BDCODEMP, TMP.BDCHAVE, TMP.BDCODCENTRO, TMP.BDCODTPCC, TMP.BDREFNF, TMP.BDNOTAFISCAL,
                     TMP.BDDATAEMINF, TMP.BDVALNF, TMP.BDVALDESCNF, TMP.BDPERCRETENCAONF, TMP.BDTIPOLAN
              FROM TMP_VRHF_EMP_TNOTASFISCAIS_TEMP TMP
              WHERE TMP.BDSESSAO = :wSessaoDest;
    
              /*Insere na TOL*/
              INSERT INTO TOL_VEF_EMP_TSERINSS(BDCHAVERH, BDCODEMP, BDCHAVEEF)
              SELECT TMP.BDCHAVE, TMP.BDCODEMP, TMP.BDCHAVEEF
              FROM TMP_VRHF_EMP_TNOTASFISCAIS_TEMP TMP
              WHERE TMP.BDSESSAO = :wSessaoDest;
            END

          SELECT C.BDULTCHAVE
          FROM TMP_TCHAVE_TRANSFERENCIA C
          WHERE C.BDTABLE = 'TOL_VEF_EMP_TSERINSSCONT'
          INTO :wUltChave;

          IF ((:wUltChave IS NOT NULL) AND (:wUltChave > 0)) THEN
            BEGIN
              SETORDEMSEQUENCIAL(0);

              /*VRHF_EMP_TNFCONT*/
              /*Cria o registro na tabela TEMP para inserir na física e na tol*/
              INSERT INTO TMP_VRHF_EMP_TNFCONT_TEMP(BDSESSAO, BDCODEMP, BDCHAVEEF, BDCHAVE, BDREFNF, BDNOTAFISCAL, BDTIPONF,
                                                    BDCODTER, BDCODCENTRO, BDCODTPCC, BDDATAEMINF, BDVALNF, BDTIPOLAN)
              SELECT SER.BDSESSAO, SER.BDCODEMP, SER.BDEDITCHAVE, (:wUltChave - GETORDEMSEQUENCIAL(0))+1 BDCHAVE, RH.BDREFNF, RH.BDNOTAFISCAL, RH.BDTIPONF,
                     RH.BDCODTER, RH.BDCODCENTRO, RH.BDCODTPCC, RH.BDDATAEMINF, RH.BDVALNF, RH.BDTIPOLAN
              FROM TMP_VEF_EMP_TMOVSER_TEMP SER
              JOIN TOL_VEF_EMP_TSERINSSCONT TOL ON(TOL.BDCODEMP = SER.BDCODEMP_OLD AND TOL.BDCHAVEEF = SER.BDCHAVE)
              JOIN VRHF_EMP_TNFCONT RH ON(RH.BDCODEMP = TOL.BDCODEMP AND RH.BDCHAVE = TOL.BDCHAVERH)
              WHERE SER.BDSESSAO = :wSessaoDest
              AND NOT EXISTS (
                              SELECT INCO.BDCODINCONSISTENCIA
                              FROM VEF_INCON_TMOVSER INCO
                              WHERE INCO.BDSESSAO = SER.BDSESSAO
                              AND INCO.BDCHAVE = SER.BDCHAVE
                             );

              INSERT INTO VRHF_EMP_TNFCONT(BDCODEMP, BDCHAVE, BDREFNF, BDNOTAFISCAL, BDTIPONF, BDCODTER, BDCODCENTRO, BDCODTPCC, BDDATAEMINF,
                                           BDVALNF, BDTIPOLAN)
              SELECT TMP.BDCODEMP, TMP.BDCHAVE, TMP.BDREFNF, TMP.BDNOTAFISCAL, TMP.BDTIPONF, TMP.BDCODTER,
                     TMP.BDCODCENTRO, TMP.BDCODTPCC, TMP.BDDATAEMINF, TMP.BDVALNF, TMP.BDTIPOLAN
              FROM TMP_VRHF_EMP_TNFCONT_TEMP TMP
              WHERE TMP.BDSESSAO = :wSessaoDest;

              /*Insere na TOL*/
              INSERT INTO TOL_VEF_EMP_TSERINSSCONT(BDCHAVERH, BDCODEMP, BDCHAVEEF)
              SELECT TMP.BDCHAVE, TMP.BDCODEMP, TMP.BDCHAVEEF
              FROM TMP_VRHF_EMP_TNFCONT_TEMP TMP
              WHERE TMP.BDSESSAO = :wSessaoDest;
            END

          FOR SELECT C.BDULTCHAVE, C.BDCODTER
              FROM TMP_TCHAVE_TRANSFERENCIA C
              WHERE C.BDTABLE = 'TOL_VEF_EMP_TSERAUTOFOLHA'
              INTO :wUltChave, :wCodTer
          DO
            BEGIN
              IF ((:wUltChave IS NOT NULL) AND (:wUltChave > 0)) THEN
                BEGIN
                  SETORDEMSEQUENCIAL(0);
    
                  /*VRH_BASE_TSERVTERC*/
                  /*Cria o registro na tabela TEMP para inserir na física e na tol*/
                  INSERT INTO TMP_VRH_BASE_TSERVTERC_TEMP(BDSESSAO, BDCODTER, BDCODEMP, BDCODSERV, BDCHAVEEF, BDCODCENTRO, BDCODTPCC, BDCODEMPPER,
                                                          BDCODTERPER, BDCODSEQ, BDCODTIPOSERV, BDDATASERV, BDDATAPAGSERV, BDVALORSERV, BDHORASERV,
                                                          BDDATABAIXA, BDOBSSERV, BDREFSERV, BDCODTIPO, BDNRDOC, BDREFPAGSERV, BDCODATVM, BDCODCID,
                                                          BDPERCISS, BDORDEMEF)
                  SELECT I.BDSESSAO, RH.BDCODTER, I.BDCODEMP, (:wUltChave - GETORDEMSEQUENCIAL(0))+1 BDCODSERV, SER.BDEDITCHAVE,
                         RH.BDCODCENTRO, RH.BDCODTPCC, RH.BDCODEMPPER, RH.BDCODTERPER, RH.BDCODSEQ, RH.BDCODTIPOSERV, RH.BDDATASERV, RH.BDDATAPAGSERV,
                         I.BDVLRCONTAB, RH.BDHORASERV, RH.BDDATABAIXA, RH.BDOBSSERV, RH.BDREFSERV, RH.BDCODTIPO, RH.BDNRDOC, RH.BDREFPAGSERV, RH.BDCODATVM,
                         RH.BDCODCID, RH.BDPERCISS, I.BDORDEM
                  FROM TMP_VEF_EMP_TMOVSERITENS_TEMP I
                  JOIN TMP_VEF_EMP_TMOVSER_TEMP SER ON(SER.BDSESSAO = I.BDSESSAO AND SER.BDCODEMP = I.BDCODEMP AND SER.BDCHAVE = I.BDCHAVE AND SER.BDCODTER = :wCodTer)
                  JOIN TOL_VEF_EMP_TSERAUTOFOLHA TOL ON(TOL.BDCODEMP = SER.BDCODEMP_OLD AND TOL.BDCHAVEEF = I.BDCHAVE AND TOL.BDORDEMEF = I.BDORDEM)
                  JOIN VRH_BASE_TSERVTERC RH ON(RH.BDCODEMP = TOL.BDCODEMP AND RH.BDCODTER = TOL.BDCODTERRH AND RH.BDCODSERV = TOL.BDCHAVERH)
                  WHERE I.BDSESSAO = :wSessaoDest
                  AND NOT EXISTS (
                                  SELECT INCO.BDCODINCONSISTENCIA
                                  FROM VEF_INCON_TMOVSER INCO
                                  WHERE INCO.BDSESSAO = SER.BDSESSAO
                                  AND INCO.BDCHAVE = SER.BDCHAVE
                                 );
                END
            END

          INSERT INTO VRH_BASE_TSERVTERC(BDCODTER, BDCODEMP, BDCODSERV, BDCODCENTRO, BDCODTPCC, BDCODEMPPER,
                                         BDCODTERPER, BDCODSEQ, BDCODTIPOSERV, BDDATASERV, BDDATAPAGSERV, BDVALORSERV, BDHORASERV,
                                         BDDATABAIXA, BDOBSSERV, BDREFSERV, BDCODTIPO, BDNRDOC, BDREFPAGSERV, BDCODATVM, BDCODCID,
                                         BDPERCISS)
          SELECT TMP.BDCODTER, TMP.BDCODEMP, TMP.BDCODSERV, TMP.BDCODCENTRO, TMP.BDCODTPCC, TMP.BDCODEMPPER, TMP.BDCODTERPER,
                 TMP.BDCODSEQ, TMP.BDCODTIPOSERV, TMP.BDDATASERV, TMP.BDDATAPAGSERV, TMP.BDVALORSERV, TMP.BDHORASERV, TMP.BDDATABAIXA,
                 TMP.BDOBSSERV, TMP.BDREFSERV, TMP.BDCODTIPO, TMP.BDNRDOC, TMP.BDREFPAGSERV, TMP.BDCODATVM, TMP.BDCODCID, TMP.BDPERCISS
          FROM TMP_VRH_BASE_TSERVTERC_TEMP TMP
          WHERE TMP.BDSESSAO = :wSessaoDest;

          INSERT INTO TOL_VEF_EMP_TSERAUTOFOLHA(BDCODEMP, BDCHAVEEF, BDORDEMEF, BDCODTERRH, BDCHAVERH)
          SELECT TMP.BDCODEMP, TMP.BDCHAVEEF, TMP.BDORDEMEF, TMP.BDCODTER, TMP.BDCODSERV
          FROM TMP_VRH_BASE_TSERVTERC_TEMP TMP
          WHERE TMP.BDSESSAO = :wSessaoDest;
        END
    END
  ELSE
    BEGIN

      IF (:PRTIPOLAN = 'SER') THEN
        BEGIN
          /*Altera o registro da empresa origem*/
          UPDATE VRHF_EMP_TNOTASFISCAIS RH SET RH.BDVALNF = (
                                                             SELECT (SER.BDVALORNOTA - COALESCE(DED.BDVLRMATERIAIS, 0) - COALESCE(DED.BDVLRSUBEMPREITEIRAS, 0)) BDVALNF
                                                             FROM TMP_VEF_EMP_TMOVSER_TEMP TMP
                                                             JOIN VEF_EMP_TMOVSER SER ON(SER.BDCODEMP = TMP.BDCODEMP AND SER.BDCHAVE = TMP.BDCHAVE)
                                                             JOIN TOL_VEF_EMP_TSERINSS TOL ON(TOL.BDCODEMP = TMP.BDCODEMP AND TOL.BDCHAVEEF = TMP.BDCHAVE)
                                                             JOIN VRHF_EMP_TNOTASFISCAIS NF ON(NF.BDCODEMP = TOL.BDCODEMP AND NF.BDCHAVE = TOL.BDCHAVERH)
                                                             LEFT OUTER JOIN VEF_EMP_TMOVSERDED DED ON(DED.BDCODEMP = TMP.BDCODEMP AND DED.BDCHAVE = TMP.BDCHAVE)
                                                             WHERE TMP.BDSESSAO = :wSessaoOri
                                                             AND RH.BDCODEMP = NF.BDCODEMP
                                                             AND RH.BDCHAVE = NF.BDCHAVE
                                                            ),
                                               RH.BDPERCRETENCAONF = (
                                                                      SELECT ((COALESCE(DED.BDRETINSS, 0) * 100) / (SER.BDVALORNOTA - COALESCE(DED.BDVLRMATERIAIS, 0) - COALESCE(DED.BDVLRSUBEMPREITEIRAS, 0)))
                                                                      FROM TMP_VEF_EMP_TMOVSER_TEMP TMP
                                                                      JOIN VEF_EMP_TMOVSER SER ON(SER.BDCODEMP = TMP.BDCODEMP AND SER.BDCHAVE = TMP.BDCHAVE)
                                                                      JOIN TOL_VEF_EMP_TSERINSS TOL ON(TOL.BDCODEMP = TMP.BDCODEMP AND TOL.BDCHAVEEF = TMP.BDCHAVE)
                                                                      JOIN VRHF_EMP_TNOTASFISCAIS NF ON(NF.BDCODEMP = TOL.BDCODEMP AND NF.BDCHAVE = TOL.BDCHAVERH)
                                                                      LEFT OUTER JOIN VEF_EMP_TMOVSERDED DED ON(DED.BDCODEMP = TMP.BDCODEMP AND DED.BDCHAVE = TMP.BDCHAVE)
                                                                      WHERE TMP.BDSESSAO = :wSessaoOri
                                                                      AND RH.BDCODEMP = NF.BDCODEMP
                                                                      AND RH.BDCHAVE = NF.BDCHAVE
                                                                     )
          WHERE EXISTS(
                       SELECT *
                       FROM TMP_VEF_EMP_TMOVSER_TEMP TMP
                       JOIN TOL_VEF_EMP_TSERINSS TOL ON(TOL.BDCODEMP = TMP.BDCODEMP AND TOL.BDCHAVEEF = TMP.BDCHAVE)
                       JOIN VRHF_EMP_TNOTASFISCAIS NF ON(NF.BDCODEMP = TOL.BDCODEMP AND NF.BDCHAVE = TOL.BDCHAVERH)
                       WHERE TMP.BDSESSAO = :wSessaoOri
                       AND NOT EXISTS (
                                       SELECT INCO.BDCODINCONSISTENCIA
                                       FROM VEF_INCON_TMOVSER INCO
                                       WHERE INCO.BDSESSAO = TMP.BDSESSAO
                                       AND INCO.BDCHAVE = TMP.BDCHAVE
                                      )
                       AND RH.BDCODEMP = NF.BDCODEMP
                       AND RH.BDCHAVE = NF.BDCHAVE
                      );

          UPDATE VRH_BASE_TSERVTERC RH SET RH.BDVALORSERV = (
                                                             SELECT I.BDVLRCONTAB
                                                             FROM TMP_VEF_EMP_TMOVSER_TEMP TMP
                                                             JOIN VEF_EMP_TMOVSERITENS I ON(I.BDCODEMP = TMP.BDCODEMP AND I.BDCHAVE = TMP.BDCHAVE)
                                                             JOIN TOL_VEF_EMP_TSERAUTOFOLHA TOL ON(TOL.BDCODEMP = I.BDCODEMP AND TOL.BDCHAVEEF = I.BDCHAVE AND TOL.BDORDEMEF = I.BDORDEM)
                                                             JOIN VRH_BASE_TSERVTERC SERV ON(SERV.BDCODEMP = TOL.BDCODEMP AND SERV.BDCODTER = TOL.BDCODTERRH AND SERV.BDCODSERV = TOL.BDCHAVERH)
                                                             WHERE TMP.BDSESSAO = :wSessaoOri
                                                             AND RH.BDCODEMP = SERV.BDCODEMP
                                                             AND RH.BDCODTER = SERV.BDCODTER
                                                             AND RH.BDCODSERV = SERV.BDCODSERV
                                                            )
          WHERE EXISTS(
                       SELECT *
                       FROM TMP_VEF_EMP_TMOVSER_TEMP TMP
                       JOIN TMP_VEF_EMP_TMOVSERITENS_TEMP I ON(I.BDSESSAO = TMP.BDSESSAO AND I.BDCODEMP = TMP.BDCODEMP AND I.BDCHAVE = TMP.BDCHAVE)
                       JOIN TOL_VEF_EMP_TSERAUTOFOLHA TOL ON(TOL.BDCODEMP = I.BDCODEMP AND TOL.BDCHAVEEF = I.BDCHAVE AND TOL.BDORDEMEF = I.BDORDEM)
                       JOIN VRH_BASE_TSERVTERC SERV ON(SERV.BDCODEMP = TOL.BDCODEMP AND SERV.BDCODTER = TOL.BDCODTERRH AND SERV.BDCODSERV = TOL.BDCHAVERH)
                       WHERE TMP.BDSESSAO = :wSessaoOri
                       AND NOT EXISTS (
                                       SELECT INCO.BDCODINCONSISTENCIA
                                       FROM VEF_INCON_TMOVSER INCO
                                       WHERE INCO.BDSESSAO = TMP.BDSESSAO
                                       AND INCO.BDCHAVE = TMP.BDCHAVE
                                      )
                       AND RH.BDCODEMP = SERV.BDCODEMP
                       AND RH.BDCODTER = SERV.BDCODTER
                       AND RH.BDCODSERV = SERV.BDCODSERV
                      );
        END
    END

END
^

COMMENT ON PARAMETER SP_TRANSFERENCIA_TOL.PRSTATE IS 'INS - Insert / UPT - Update'^

CREATE OR ALTER PROCEDURE SP_TRANSFERENCIA_PARCELAS (
    PRID_TERMINAL INTEGER,
    PRTIPOLAN CHAR(3))
AS
DECLARE VARIABLE WSESSAODEST INTEGER;
DECLARE VARIABLE WSESSAOORI INTEGER;
DECLARE VARIABLE WSESSAO INTEGER;
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WCODEMPANT INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;
DECLARE VARIABLE WCHAVEANT INTEGER;
DECLARE VARIABLE WORDEMPAR INTEGER;
DECLARE VARIABLE WQTDPAR INTEGER;
DECLARE VARIABLE WQTDPARAUX INTEGER;
DECLARE VARIABLE WVALORNOTA DM_NUMERIC_15_2;
DECLARE VARIABLE WVALORNOTAAUX DM_NUMERIC_15_2;
DECLARE VARIABLE WVALORBRUTO DM_NUMERIC_15_2;
DECLARE VARIABLE WVALORPARCELA DM_NUMERIC_15_2;
DECLARE VARIABLE WRETPIS DM_NUMERIC_15_2;
DECLARE VARIABLE WRETCOF DM_NUMERIC_15_2;
DECLARE VARIABLE WRETCSLL DM_NUMERIC_15_2;
DECLARE VARIABLE WRETINSS DM_NUMERIC_15_2;
DECLARE VARIABLE WRETISS DM_NUMERIC_15_2;
DECLARE VARIABLE WRETIR DM_NUMERIC_15_2;
DECLARE VARIABLE WRETPARPIS DM_BOOLEAN;
DECLARE VARIABLE WRETPARCOFINS DM_BOOLEAN;
DECLARE VARIABLE WRETPARCSLL DM_BOOLEAN;
DECLARE VARIABLE WRETPARINSS DM_BOOLEAN;
DECLARE VARIABLE WRETPARIRRF DM_BOOLEAN;
DECLARE VARIABLE WRETPARISS DM_BOOLEAN;
DECLARE VARIABLE WTABLEPAR VARCHAR(31);
DECLARE VARIABLE WTABLE VARCHAR(31);
DECLARE VARIABLE WTABLERET VARCHAR(31);
DECLARE VARIABLE WTABLEINSS VARCHAR(31);
DECLARE VARIABLE WTABLEINCON VARCHAR(31);
DECLARE VARIABLE WSQL VARCHAR(2000);
BEGIN
  /*Sessão empresa destino*/
  SELECT S.BDSESSAO
  FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRID_TERMINAL
  AND S.BDTABLE = 'DESTINO'
  INTO :wSessaoDest;

  /*Sessão empresa origem*/
  SELECT S.BDSESSAO
  FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRID_TERMINAL
  AND S.BDTABLE = 'ORIGEM'
  INTO :wSessaoOri;

  wTableINSS = '';
  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTable       = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableRet    = 'TMP_VEF_EMP_TMOVENTRET_TEMP';
      wTablePar    = 'TMP_VEF_EMP_TMOVENTPAR_TEMP';
      wTableIncon  = 'VEF_INCON_TMOVENT';
    END
  ELSE
  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTable       = 'TMP_VEF_EMP_TMOVSAI_TEMP';
      wTableRet    = 'TMP_VEF_EMP_TMOVSAIRET_TEMP';
      wTablePar    = 'TMP_VEF_EMP_TMOVSAIPAR_TEMP';
      wTableIncon  = 'VEF_INCON_TMOVSAI';
    END
  ELSE
  IF (:PRTIPOLAN = 'SER') THEN
    BEGIN
      wTable       = 'TMP_VEF_EMP_TMOVSER_TEMP';
      wTableRet    = 'TMP_VEF_EMP_TMOVSERRET_TEMP';
      wTablePar    = 'TMP_VEF_EMP_TMOVSERPAR_TEMP';
      wTableINSS   = 'TMP_VEF_EMP_TMOVSERDED_TEMP';
      wTableIncon  = 'VEF_INCON_TMOVSER';
    END

  wCodEmpAnt = 0;
  wChaveAnt  = 0;

  wSQL =          'SELECT PAR.BDSESSAO, PAR.BDCODEMP, PAR.BDEDITCHAVE, PAR.BDORDEMPAR, ';
  wSQL = :wSQL ||        'MOV.BDVALORNOTA, ';
  wSQL = :wSQL ||        'COALESCE(RET.BDVLRPIS, 0), ';
  wSQL = :wSQL ||        'COALESCE(RET.BDVLRCOFINS, 0), ';
  wSQL = :wSQL ||        'COALESCE(RET.BDVLRCSOCIAL, 0), ';

  IF (:PRTIPOLAN = 'SER') THEN
    wSQL = :wSQL ||      'COALESCE(INSS.BDRETINSS, 0), ';
  ELSE
    wSQL = :wSQL ||      'COALESCE(RET.BDVLRINSS, 0), ';

  wSQL = :wSQL ||        'COALESCE(RET.BDVLRIR, 0), ';
  wSQL = :wSQL ||        'COALESCE(RET.BDISSRET, 0), ';
  wSQL = :wSQL ||        '( ';
  wSQL = :wSQL ||         'SELECT COUNT(C.BDORDEMPAR) BDQTDPAR ';
  wSQL = :wSQL ||         'FROM '||:wTablePar||' C ';
  wSQL = :wSQL ||         'WHERE C.BDSESSAO = PAR.BDSESSAO ';
  wSQL = :wSQL ||         'AND C.BDCODEMP = PAR.BDCODEMP ';
  wSQL = :wSQL ||         'AND C.BDCHAVE = PAR.BDCHAVE ';
  wSQL = :wSQL ||         'GROUP BY C.BDSESSAO, C.BDCODEMP, C.BDCHAVE ';
  wSQL = :wSQL ||        ') ';
  wSQL = :wSQL || 'FROM '||:wTablePar||' PAR ';
  wSQL = :wSQL || 'JOIN '||:wTable||' MOV ON(MOV.BDSESSAO = PAR.BDSESSAO AND MOV.BDCODEMP = PAR.BDCODEMP AND MOV.BDCHAVE = PAR.BDCHAVE) ';
  wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTableRet||' RET ON(RET.BDSESSAO = PAR.BDSESSAO AND RET.BDCODEMP = PAR.BDCODEMP AND RET.BDCHAVE = PAR.BDCHAVE) ';
  IF (:wTableINSS <> '') THEN
    wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTableINSS||' INSS ON(INSS.BDSESSAO = PAR.BDSESSAO AND INSS.BDCODEMP = PAR.BDCODEMP AND INSS.BDCHAVE = PAR.BDCHAVE) ';
  wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTableIncon||' INCO ON(INCO.BDSESSAO = '||:wSessaoDest||' AND INCO.BDCHAVE = PAR.BDCHAVE) ';
  wSQL = :wSQL || 'WHERE PAR.BDSESSAO IN('||:wSessaoOri||', '||:wSessaoDest||') ';
  wSQL = :wSQL || 'AND INCO.BDCODINCONSISTENCIA IS NULL ';
  wSQL = :wSQL || 'ORDER BY PAR.BDSESSAO, PAR.BDCODEMP, PAR.BDCHAVE ';

  FOR EXECUTE STATEMENT :wSQL
      INTO :wSessao, :wCodEmp, :wChave, :wOrdemPar, :wValorNota,
           :wRetPis, :wRetCof, wRetCSLL, :wRetINSS, :wRetIR,
           :wRetISS, :wQtdPar
  DO
    BEGIN
      IF (:wCodEmp <> :wCodEmpAnt) THEN
        BEGIN
          SELECT VW.BDRETPARPIS, VW.BDRETPARCOFINS, VW.BDRETPARCSLL,
                 VW.BDRETPARINSS, VW.BDRETPARIRRF, VW.BDRETPARISSQN
          FROM VW_EMP_REF_TOTAL VW
          WHERE VW.BDCODEMP = :wCodEmp
          INTO :wRetParPIS, :wRetParCofins, :wRetParCSLL,
               :wRetParINSS, :wRetParIRRF, :wRetParISS;
        END

      IF (:wChave <> :wChaveAnt) THEN
        wQtdParAux = 0;

      wQtdParAux = :wQtdParAux + 1;

      wValorNotaAux = :wValorNota;
      wValorBruto   = :wValorNota / :wQtdPar;

      IF (:wRetParPIS = 'TRUE') THEN
        wValorNota = :wValorNota - :wRetPIS;
      IF (:wRetParCofins = 'TRUE') THEN
        wValorNota = :wValorNota - :wRetCof;
      IF (:wRetParCSLL = 'TRUE') THEN
        wValorNota = :wValorNota - :wRetCSLL;
      IF (:wRetParINSS = 'TRUE') THEN
        wValorNota = :wValorNota - :wRetINSS;
      IF (:wRetParIRRF = 'TRUE') THEN
        wValorNota = :wValorNota - :wRetIR;
      IF (:wRetParISS = 'TRUE') THEN
        wValorNota = :wValorNota - :wRetISS;

      wValorParcela = :wValorNota / :wQtdPar;
      IF (:wRetParPIS = 'TRUE') THEN
        wRetPIS = :wRetPIS  * (:wValorBruto / :wValorNotaAux);
      ELSE
        wRetPIS = 0;

      IF (:wRetParCofins = 'TRUE') THEN
        wRetCof = :wRetCof  * (:wValorBruto / :wValorNotaAux);
      ELSE
        wRetCof = 0;

      IF (:wRetParCSLL = 'TRUE') THEN
        wRetCSLL = :wRetCSLL * (:wValorBruto / :wValorNotaAux);
      ELSE
        wRetCSLL = 0;

      IF (:wRetParINSS = 'TRUE') THEN
        wRetINSS = :wRetINSS * (:wValorBruto / :wValorNotaAux);
      ELSE
        wRetINSS = 0;

      IF (:wRetParIRRF = 'TRUE') THEN
        wRetIR = :wRetIR   * (:wValorBruto / :wValorNotaAux);
      ELSE
        wRetIR = 0;

      IF (:wRetParISS = 'TRUE') THEN
        wRetISS = :wRetISS   * (:wValorBruto / :wValorNotaAux);
      ELSE
        wRetISS = 0;

      wSQL =          'UPDATE '||:wTablePar||' PAR ';
      wSQL = :wSQL || 'SET PAR.BDVALORPAR   = '||:wValorParcela||', ';
      wSQL = :wSQL ||     'PAR.BDVALORBRUTO = '||:wValorBruto||', ';
      wSQL = :wSQL ||     'PAR.BDVALORRETPIS= '||:wRetPIS||', ';
      wSQL = :wSQL ||     'PAR.BDVALORRETCOFINS = '||:wRetCof||', ';
      wSQL = :wSQL ||     'PAR.BDVALORRETCSLL   = '||:wRetCSLL||', ';
      wSQL = :wSQL ||     'PAR.BDVALORRETIRRF   = '||:wRetIR||', ';
      wSQL = :wSQL ||     'PAR.BDVALORRETISSQN  = '||:wRetISS||', ';
      wSQL = :wSQL ||     'PAR.BDVALORRETINSS   = '||:wRetINSS||' ';
      wSQL = :wSQL || 'WHERE PAR.BDSESSAO  = '||:wSessao||' ';
      wSQL = :wSQL || 'AND PAR.BDCODEMP    = '||:wCodEmp||' ';
      wSQL = :wSQL || 'AND PAR.BDEDITCHAVE = '||:wChave||' ';
      wSQL = :wSQL || 'AND PAR.BDORDEMPAR  = '||:wOrdemPar||';';
      EXECUTE STATEMENT :wSQL;

      /*Vai jogar o resto na última parcela*/
      IF (:wQtdPar = :wQtdParAux) THEN
        BEGIN
          wSQL =          'SELECT  COALESCE((SER.BDVALORNOTA - (PAR.BDVALORPAR + RET.BDVLRPIS + RET.BDVLRCOFINS + RET.BDVLRCSOCIAL + RET.BDVLRIR + RET.BDISSRET + '||IIF(:PRTIPOLAN = 'SER', 'INSS.BDRETINSS', 'RET.BDVLRINSS')||')), 0) BDRESTOPAR, ';
          wSQL = :wSQL ||        ' COALESCE((SER.BDVALORNOTA - PAR.BDVALORBRUTO), 0) BDRESTOBRUTO, ';
          wSQL = :wSQL ||        ' COALESCE((RET.BDVLRPIS    - PAR.BDVALORRETPIS), 0) BDRESTOPIS, ';
          wSQL = :wSQL ||        ' COALESCE((RET.BDVLRCOFINS - PAR.BDVALORRETCOFINS), 0) BDRESTOCOF, ';
          wSQL = :wSQL ||        ' COALESCE((RET.BDVLRCSOCIAL- PAR.BDVALORRETCSLL), 0) BDRESTOCSLL, ';
          wSQL = :wSQL ||        ' COALESCE((RET.BDVLRIR     - PAR.BDVALORRETIRRF), 0) BDRESTOIR, ';
          wSQL = :wSQL ||        ' COALESCE((RET.BDISSRET    - PAR.BDVALORRETISSQN), 0) BDRESTOISS, ';

          IF (:PRTIPOLAN = 'SER') THEN
            wSQL = :wSQL ||      ' COALESCE((INSS.BDRETINSS  - PAR.BDVALORRETINSS), 0) BDRESTOINSS ';
          ELSE
            wSQL = :wSQL ||      ' COALESCE((RET.BDVLRINSS   - PAR.BDVALORRETINSS), 0) BDRESTOINSS ';

          wSQL = :wSQL || 'FROM (';
          wSQL = :wSQL ||       'SELECT PAR.BDSESSAO, PAR.BDCODEMP, PAR.BDCHAVE, ';
          wSQL = :wSQL ||              'SUM(COALESCE(PAR.BDVALORPAR, 0)) BDVALORPAR, ';
          wSQL = :wSQL ||              'SUM(COALESCE(PAR.BDVALORBRUTO, 0)) BDVALORBRUTO, ';
          wSQL = :wSQL ||              'SUM(COALESCE(PAR.BDVALORRETPIS, 0)) BDVALORRETPIS, ';
          wSQL = :wSQL ||              'SUM(COALESCE(PAR.BDVALORRETCOFINS, 0)) BDVALORRETCOFINS, ';
          wSQL = :wSQL ||              'SUM(COALESCE(PAR.BDVALORRETCSLL, 0)) BDVALORRETCSLL, ';
          wSQL = :wSQL ||              'SUM(COALESCE(PAR.BDVALORRETIRRF, 0)) BDVALORRETIRRF, ';
          wSQL = :wSQL ||              'SUM(COALESCE(PAR.BDVALORRETISSQN, 0)) BDVALORRETISSQN, ';
          wSQL = :wSQL ||              'SUM(COALESCE(PAR.BDVALORRETINSS, 0)) BDVALORRETINSS ';
          wSQL = :wSQL ||       'FROM '||:wTablePar||' PAR ';
          wSQL = :wSQL ||       'WHERE PAR.BDSESSAO  = '||:wSessao;
          wSQL = :wSQL ||       'AND PAR.BDCODEMP    = '||:wCodEmp;
          wSQL = :wSQL ||       'AND PAR.BDEDITCHAVE = '||:wChave;
          wSQL = :wSQL ||       'GROUP BY PAR.BDSESSAO, PAR.BDCODEMP, PAR.BDCHAVE ';
          wSQL = :wSQL ||      ') PAR ';
          wSQL = :wSQL || 'JOIN '||:wTableRet||' RET ON(RET.BDSESSAO = PAR.BDSESSAO AND RET.BDCODEMP = PAR.BDCODEMP AND RET.BDCHAVE = PAR.BDCHAVE) ';
          wSQL = :wSQL || 'JOIN '||:wTable||' SER ON(SER.BDSESSAO = PAR.BDSESSAO AND SER.BDCODEMP = PAR.BDCODEMP AND SER.BDCHAVE = PAR.BDCHAVE) ';
          IF (:wTableINSS <> '') THEN
            wSQL = :wSQL || 'LEFT OUTER JOIN '||:wTableINSS||' INSS ON(INSS.BDSESSAO = PAR.BDSESSAO AND INSS.BDCODEMP = PAR.BDCODEMP AND INSS.BDCHAVE = PAR.BDCHAVE) ';

          EXECUTE STATEMENT :wSQL
          INTO :wValorParcela, :wValorBruto,
               :wRetPIS, :wRetCof, :wRetCSLL,
               :wRetIR, :wRetISS, :wRetINSS;

          IF ((:wValorParcela > 0) OR (:wValorBruto > 0) OR
              (:wRetPIS > 0) OR (:wRetCof > 0) OR (:wRetCSLL > 0) OR
              (:wRetIR > 0) OR (:wRetISS > 0) OR (:wRetINSS > 0)) THEN
            BEGIN
              wSQL =          'UPDATE '||:wTablePar||' PAR ';
              wSQL = :wSQL || 'SET PAR.BDVALORPAR       = PAR.BDVALORPAR   + '||:wValorParcela||', ';
              wSQL = :wSQL ||     'PAR.BDVALORBRUTO     = PAR.BDVALORBRUTO + '||:wValorBruto||', ';
              wSQL = :wSQL ||     'PAR.BDVALORRETPIS    = PAR.BDVALORRETPIS+ '||:wRetPIS||', ';
              wSQL = :wSQL ||     'PAR.BDVALORRETCOFINS = PAR.BDVALORRETCOFINS + '||:wRetCof||', ';
              wSQL = :wSQL ||     'PAR.BDVALORRETCSLL   = PAR.BDVALORRETCSLL   + '||:wRetCSLL||', ';
              wSQL = :wSQL ||     'PAR.BDVALORRETIRRF   = PAR.BDVALORRETIRRF   + '||:wRetIR||', ';
              wSQL = :wSQL ||     'PAR.BDVALORRETISSQN  = PAR.BDVALORRETISSQN  + '||:wRetISS||', ';
              wSQL = :wSQL ||     'PAR.BDVALORRETINSS   = PAR.BDVALORRETINSS   + '||:wRetINSS||' ';
              wSQL = :wSQL || 'WHERE PAR.BDSESSAO  = '||:wSessao||' ';
              wSQL = :wSQL || 'AND PAR.BDCODEMP    = '||:wCodEmp||' ';
              wSQL = :wSQL || 'AND PAR.BDEDITCHAVE = '||:wChave||' ';
              wSQL = :wSQL || 'AND PAR.BDORDEMPAR  = '||:wOrdemPar||' ';
              EXECUTE STATEMENT :wSQL;
            END
        END

      wCodEmpAnt = :wCodEmp;
      wChaveAnt  = :wChave;
    END

  WHEN ANY DO
    BEGIN
      IN AUTONOMOUS TRANSACTION DO
        EXECUTE PROCEDURE LANCA_EXCEPTION('SP_TRANSFERENCIA_LAN', SQLCODE, GDSCODE);
      EXCEPTION;
    END

END^

CREATE OR ALTER PROCEDURE SP_TRANSFERENCIA_RATEIO (
    PRID_TERMINAL INTEGER,
    PRCODEMPORI INTEGER,
    PRCODEMPDEST INTEGER,
    PRREFTRANS INTEGER,
    PRTIPOLAN CHAR(3))
AS
DECLARE VARIABLE WSESSAODEST INTEGER;
DECLARE VARIABLE WSESSAOORI INTEGER;
DECLARE VARIABLE WTABLEFIS VARCHAR(31);
DECLARE VARIABLE WTABLEITEM VARCHAR(31);
DECLARE VARIABLE WTABLERAT VARCHAR(31);
DECLARE VARIABLE WTABLEINCON VARCHAR(31);
DECLARE VARIABLE WSQL VARCHAR(1000);
BEGIN
  /*Sessão empresa destino*/
  SELECT S.BDSESSAO
  FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRID_TERMINAL
  AND S.BDTABLE = 'DESTINO'
  INTO :wSessaoDest;

  /*Sessão empresa origem*/
  SELECT S.BDSESSAO
  FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRID_TERMINAL
  AND S.BDTABLE = 'ORIGEM'
  INTO :wSessaoOri;

  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTableFis    = 'VEF_EMP_TMOVENT';
      wTableItem   = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      wTableRat    = 'TMP_VEF_EMP_TMOVRATENT_TEMP';
      wTableIncon  = 'VEF_INCON_TMOVENT';
    END
  ELSE
  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTableFis    = 'VEF_EMP_TMOVSAI';
      wTableItem   = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
      wTableRat    = 'TMP_VEF_EMP_TMOVRATSAI_TEMP';
      wTableIncon  = 'VEF_INCON_TMOVSAI';
    END
  ELSE
  IF (:PRTIPOLAN = 'SER') THEN
    BEGIN
      wTableFis    = 'VEF_EMP_TMOVSER';
      wTableItem   = 'TMP_VEF_EMP_TMOVSERITENS_TEMP';
      wTableRat    = 'TMP_VEF_EMP_TMOVRATSER_TEMP';
      wTableIncon  = 'VEF_INCON_TMOVSER';
    END
  ELSE
    EXIT;

  /*Só faz o rateio se o plano de contas da empresa origem e destino for o mesmo*/
  IF ((SELECT SP.BDCODPLANOONLINE FROM SP_CONSULTAEMPRESAS_SIS(:PRREFTRANS, :PRCODEMPORI, NULL) SP) <> (SELECT SP.BDCODPLANOONLINE FROM SP_CONSULTAEMPRESAS_SIS(:PRREFTRANS, :PRCODEMPDEST, NULL) SP)) THEN
    BEGIN
      /*Caso o plano de contas seja diferente, limpa o rateio do destino porque deve contabilizar através da CFOP.*/
      wSQL = 'DELETE FROM '||:wTableRat||' R WHERE R.BDSESSAO = '||:wSessaoDest;
      EXECUTE STATEMENT :wSQL;
    END

  /*Proporcionaliza o valor de rateio, pega o valor original do lançamento da tabela física e multiplica pelo novo valor do item, depois divide pelo valor de rateio existente*/
  wSQL =          'UPDATE '||:wTableRat||' RAT ';
  wSQL = :wSQL || 'SET RAT.BDVALOR = ((SELECT I.BDVLRCONTAB FROM '||:wTableItem||' I WHERE I.BDSESSAO = RAT.BDSESSAO AND I.BDCODEMP = RAT.BDCODEMP AND I.BDCHAVE = RAT.BDCHAVE AND I.BDORDEM = RAT.BDORDEM) * RAT.BDVALOR) /';
  wSQL = :wSQL ||                    '(SELECT MOV.BDVALORNOTA FROM '||:wTableFis||' MOV WHERE MOV.BDCODEMP = '||:PRCODEMPORI||' AND MOV.BDCHAVE = RAT.BDCHAVE) ';
  wSQL = :wSQL || 'WHERE RAT.BDSESSAO IN('||:wSessaoOri||', '||:wSessaoDest||') ';
  wSQL = :wSQL || 'AND RAT.BDVALOR > 0 ';
  wSQL = :wSQL || 'AND NOT EXISTS(';
  wSQL = :wSQL ||                'SELECT * ';
  wSQL = :wSQL ||                'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL ||                'JOIN '||:wTableIncon||' INCO ON(INCO.BDSESSAO = '||:wSessaoDest||' AND INCO.BDCHAVE = TNF.BDCHAVE) ';
  wSQL = :wSQL ||                'WHERE TNF.BDCHAVE = RAT.BDCHAVE ';
  wSQL = :wSQL ||               '); ';
  EXECUTE STATEMENT :wSQL;

  WHEN ANY DO
    BEGIN
      IN AUTONOMOUS TRANSACTION DO
        EXECUTE PROCEDURE LANCA_EXCEPTION('SP_TRANSFERENCIA_RATEIO', SQLCODE, GDSCODE);
      EXCEPTION;
    END
END^

CREATE OR ALTER PROCEDURE SP_GET_VALOR_ISE_OUT (
    PRCODEMP INTEGER NOT NULL,
    PRREF INTEGER NOT NULL,
    PRCODNAT INTEGER NOT NULL,
    PRISE_OR_OUT CHAR(1) NOT NULL,
    PRVLRCONTAB DM_NUMERIC_15_2,
    PRBCISS DM_NUMERIC_15_2,
    PRVLRISE DM_NUMERIC_15_2,
    PRVLROUT DM_NUMERIC_15_2)
RETURNS (
    BDVLR DM_NUMERIC_15_2)
AS
DECLARE VARIABLE WLANCEMNATOP INTEGER;
DECLARE VARIABLE WLANCEMEMP INTEGER;
BEGIN
  SELECT N.BDLANBCICMSISEOUT FROM VEF_SP_LANCAMENTOS(:PRREF, :PRCODEMP) N INTO :wLancEmEmp;
  SELECT NAT.BDLANEMISENTASOUTRASNAT FROM VEF_BASE_TNATOP NAT WHERE NAT.BDCODNAT = :PRCODNAT INTO :wLancEmNatOp;

  IF (:wLancEmNatOp = 0) THEN
    BEGIN
      IF (:wLancEmEmp = 0) THEN
        BEGIN
          IF (:PRISE_OR_OUT = 'I') THEN
            BDVLR = :PRVLRCONTAB - (:PRBCISS + :PRVLROUT);
        END
      ELSE
        BEGIN
          IF (:PRISE_OR_OUT = 'O') THEN
            BDVLR = :PRVLRCONTAB - (:PRBCISS + :PRVLRISE);
        END
    END
  ELSE
    BEGIN
      IF (:wLancEmNatOp = 1) THEN
        BEGIN
          IF (:PRISE_OR_OUT = 'I') THEN
            BDVLR = :PRVLRCONTAB - (:PRBCISS + :PRVLROUT);
        END
      ELSE
        BEGIN
          IF (:PRISE_OR_OUT = 'O') THEN
            BDVLR = :PRVLRCONTAB - (:PRBCISS + :PRVLRISE);
        END
    END

  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_TRANSFERENCIA_PRODUTOS (
    PRID_TERMINAL INTEGER,
    PRCODEMPORI INTEGER,
    PRCODEMPDEST INTEGER,
    PRREFTRANS INTEGER,
    PRTIPOLAN CHAR(3))
AS
DECLARE VARIABLE WSESSAOORI VARCHAR(31);
DECLARE VARIABLE WSESSAODEST VARCHAR(31);
DECLARE VARIABLE WTABLEITEMFIS VARCHAR(31);
DECLARE VARIABLE WTABLEITEM VARCHAR(31);
DECLARE VARIABLE WTABLEMOVPRO VARCHAR(31);
DECLARE VARIABLE WTABLEMOVPROFIS VARCHAR(31);
DECLARE VARIABLE WSQL VARCHAR(3000);
DECLARE VARIABLE WCODPLAPADRAODEST INTEGER;
DECLARE VARIABLE WCODPLANOONLINEDEST INTEGER;
BEGIN
  /*Sessão empresa destino*/
  SELECT S.BDSESSAO
  FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRID_TERMINAL
  AND S.BDTABLE = 'DESTINO'
  INTO :wSessaoDest;

  /*Sessão empresa origem*/
  SELECT S.BDSESSAO
  FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRID_TERMINAL
  AND S.BDTABLE = 'ORIGEM'
  INTO :wSessaoOri;

  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTableItemFis= 'VEF_EMP_TMOVENTITENS';
      wTableItem   = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      wTableMovPro = 'TMP_VEF_EMP_TMOVPROENT_TEMP';
      wTableMovProFis = 'VEF_EMP_TMOVPROENT';
    END
  ELSE
  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTableItemFis= 'VEF_EMP_TMOVSAIITENS';
      wTableItem   = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
      wTableMovPro = 'TMP_VEF_EMP_TMOVPROSAI_TEMP';
      wTableMovProFis = 'VEF_EMP_TMOVPROSAI';
    END
  ELSE
  IF (:PRTIPOLAN = 'SER') THEN
    BEGIN
      wTableItemFis= 'VEF_EMP_TMOVSERITENS';
      wTableItem   = 'TMP_VEF_EMP_TMOVSERITENS_TEMP';
      wTableMovPro = 'TMP_VEF_EMP_TA170_TEMP';
      wTableMovProFis = 'VEF_EMP_TA170';
    END

  /*(ValorNovoCFOP * ValorVelhoProduto) / ValorVelhoCFOP*/

  wSQL =          'UPDATE '||:wTableMovPro||' PRO ';
  wSQL = :wSQL || 'SET PRO.BDCODPROD = (SELECT FIRST 1 FK.BDCODPROD FROM TMP_TTRANSFERENCIA_FKS FK WHERE FK.BDCODEMP = '||:PRCODEMPORI||' AND FK.BDCHAVE = PRO.BDCHAVE AND FK.BDORDEM = PRO.BDORDEM AND FK.BDNUM_ITEM = PRO.BDNUM_ITEM AND FK.BDTABLE = '''||:wTableMovProFis||''') ';
  wSQL = :wSQL || 'WHERE PRO.BDSESSAO = '||:wSessaoDest;
  EXECUTE STATEMENT :wSQL;

  /*Particiona o valor do produto e atualiza as alíquotas de acordo com o novo produto vinculado a empresa*/
  wSQL =          'UPDATE '||:wTableMovPro||' P ';
  wSQL = :wSQL || 'SET P.BDVL_ITEM = (((SELECT I.BDVLRCONTAB FROM '||:wTableItem||' I WHERE I.BDSESSAO = P.BDSESSAO AND I.BDCODEMP = P.BDCODEMP AND I.BDCHAVE = P.BDCHAVE AND I.BDORDEM = P.BDORDEM) * P.BDVL_ITEM) / ';
  wSQL = :wSQL ||                     '(SELECT SIF.BDVLRCONTAB FROM '||:wTableItemFis||' SIF WHERE SIF.BDCODEMP = '||:PRCODEMPORI||' AND SIF.BDCHAVE = P.BDCHAVE AND SIF.BDORDEM = P.BDORDEM)) ';
  /*PIS*/
--  wSQL = :wSQL ||     'P.BDALIQ_PIS  = IIF((SELECT BDTIPLAN FROM '||:wTable||' S WHERE S.BDSESSAO = P.BDSESSAO AND S.BDCODEMP = P.BDCODEMP AND S.BDCHAVE = P.BDCHAVE) = 0, ';
--  wSQL = :wSQL ||                         '(SELECT A.BDALIQPIS FROM TCADPRO_VINC A WHERE A.BDCODEMP = P.BDCODEMP AND A.BDCODPROD = P.BDCODPROD), ';     /*Emitido*/
--  wSQL = :wSQL ||                         '(SELECT A.BDALIQPISENT FROM TCADPRO_VINC A WHERE A.BDCODEMP = P.BDCODEMP AND A.BDCODPROD = P.BDCODPROD)), '; /*Recebido*/
--  wSQL = :wSQL ||     'P.BDCODCSTPIS = IIF((SELECT BDTIPLAN FROM '||:wTable||' S WHERE S.BDSESSAO = P.BDSESSAO AND S.BDCODEMP = P.BDCODEMP AND S.BDCHAVE = P.BDCHAVE) = 0, ';
--  wSQL = :wSQL ||                         '(SELECT A.BDCODCSTPISSAI FROM TCADPRO_VINC A WHERE A.BDCODEMP = P.BDCODEMP AND A.BDCODPROD = P.BDCODPROD), '; /*Emitido*/
--  wSQL = :wSQL ||                         '(SELECT A.BDCODCSTPISENT FROM TCADPRO_VINC A WHERE A.BDCODEMP = P.BDCODEMP AND A.BDCODPROD = P.BDCODPROD)), '; /*Recebido*/
  /*Cofins*/
--  wSQL = :wSQL ||     'P.BDALIQ_COFINS  = IIF((SELECT BDTIPLAN FROM '||:wTable||' S WHERE S.BDSESSAO = P.BDSESSAO AND S.BDCODEMP = P.BDCODEMP AND S.BDCHAVE = P.BDCHAVE) = 0, ';
--  wSQL = :wSQL ||                            '(SELECT A.BDALIQCOF FROM TCADPRO_VINC A WHERE A.BDCODEMP = P.BDCODEMP AND A.BDCODPROD = P.BDCODPROD), ';     /*Emitido*/
--  wSQL = :wSQL ||                            '(SELECT A.BDALIQCOFENT FROM TCADPRO_VINC A WHERE A.BDCODEMP = P.BDCODEMP AND A.BDCODPROD = P.BDCODPROD)), '; /*Recebido*/
--  wSQL = :wSQL ||     'P.BDCODCSTCOF = IIF((SELECT BDTIPLAN FROM '||:wTable||' S WHERE S.BDSESSAO = P.BDSESSAO AND S.BDCODEMP = P.BDCODEMP AND S.BDCHAVE = P.BDCHAVE) = 0, ';
--  wSQL = :wSQL ||                         '(SELECT A.BDCODCSTCOFSAI FROM TCADPRO_VINC A WHERE A.BDCODEMP = P.BDCODEMP AND A.BDCODPROD = P.BDCODPROD), '; /*Emitido*/
--  wSQL = :wSQL ||                         '(SELECT A.BDCODCSTCOFENT FROM TCADPRO_VINC A WHERE A.BDCODEMP = P.BDCODEMP AND A.BDCODPROD = P.BDCODPROD)) '; /*Recebido*/
  wSQL = :wSQL || 'WHERE P.BDSESSAO IN ('||:wSessaoOri||', '||:wSessaoDest||') AND COALESCE(P.BDVL_ITEM, 0) > 0; ';
  EXECUTE STATEMENT :wSQL;

  /*Atualiza o valor da base de PIS/Cofins*/
  wSQL =          'UPDATE '||:wTableMovPro||' P ';
  wSQL = :wSQL || 'SET P.BDVL_BC_PIS    = P.BDVL_ITEM, ';
  wSQL = :wSQL ||     'P.BDVL_BC_COFINS = P.BDVL_ITEM, ';
  /*Gera os valores de PIS/Cofins caso o lançamento de origem tinha informado*/
  wSQL = :wSQL ||     'P.BDVL_PIS    = IIF(COALESCE(P.BDVL_PIS, 0) > 0, (P.BDVL_ITEM * (P.BDALIQ_PIS / 100)), NULL), ';
  wSQL = :wSQL ||     'P.BDVL_COFINS = IIF(COALESCE(P.BDVL_COFINS, 0) > 0, (P.BDVL_ITEM * (P.BDALIQ_COFINS / 100)), NULL) ';
  wSQL = :wSQL || 'WHERE P.BDSESSAO IN('||:wSessaoOri||', '||:wSessaoDest||'); ';
  EXECUTE STATEMENT :wSQL;

  SELECT SP.BDCODPLANOONLINE, SP.BDCODPLAPADRAO FROM SP_CONSULTAEMPRESAS_SIS(:PRREFTRANS, :PRCODEMPDEST, NULL) SP INTO :wCodPlanoOnlineDest, :wCodPlaPadraoDest;

  wSQL = 'UPDATE '||:wTableMovPro||' A SET ';
  /*Caso o plano de contas da empresa origem e destino sejam diferentes, zera o código da conta no movimento de produto*/
  IF ((SELECT SP.BDCODPLANOONLINE FROM SP_CONSULTAEMPRESAS_SIS(:PRREFTRANS, :PRCODEMPORI, NULL) SP) <> :wCodPlanoOnlineDest) THEN
    wSQL = :wSQL || 'A.BDCODTPLA = NULL, ';
  wSQL = :wSQL || 'A.BDCODPLAPADRAO = '||:wCodPlaPadraoDest||' ';
  wSQL = :wSQL || 'WHERE A.BDSESSAO = '||:wSessaoDest;
  EXECUTE STATEMENT :wSQL;
END^

CREATE OR ALTER PROCEDURE SP_TRANSFERENCIA_CFOP (
    PRID_TERMINAL INTEGER,
    PRUFEMP CHAR(2),
    PRTIPOLAN CHAR(3))
AS
DECLARE VARIABLE WSQL VARCHAR(2500);
DECLARE VARIABLE WTABLE VARCHAR(31);
DECLARE VARIABLE WTABLEITEM VARCHAR(31);
DECLARE VARIABLE WSESSAODEST INTEGER;
BEGIN
  /*Sessão empresa destino*/
  SELECT S.BDSESSAO
  FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRID_TERMINAL
  AND S.BDTABLE = 'DESTINO'
  INTO :wSessaoDest;

  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTable     = 'TMP_VEF_EMP_TMOVSAI_TEMP';
      wTableItem = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
    END
  ELSE
  IF(:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTable     = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItem = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
    END
  ELSE
  IF(:PRTIPOLAN = 'SER') THEN
    BEGIN
      wTable     = 'TMP_VEF_EMP_TMOVSER_TEMP';
      wTableItem = 'TMP_VEF_EMP_TMOVSERITENS_TEMP';
    END

  wSQL =          'UPDATE '||:wTableItem||' I ';
  wSQL = :wSQL || 'SET I.BDSIGLAUFTER = (';
  wSQL = :wSQL ||                       'SELECT UF.BDSIGLAUF ';
  wSQL = :wSQL ||                       'FROM '||:wTable||' MOV ';
  wSQL = :wSQL ||                       'JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = MOV.BDCODTER) ';
  wSQL = :wSQL ||                       'JOIN TCIDADE CID ON(CID.BDCODCID = TER.BDCODCID) ';
  wSQL = :wSQL ||                       'JOIN TUF UF ON(UF.BDCODUF = CID.BDCODUF) ';
  wSQL = :wSQL ||                       'WHERE MOV.BDSESSAO = I.BDSESSAO ';
  wSQL = :wSQL ||                       'AND MOV.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL ||                       'AND MOV.BDCHAVE = I.BDCHAVE ';
  wSQL = :wSQL ||                      ') ';
  wSQL = :wSQL || 'WHERE I.BDSESSAO = '||:wSessaoDest;
  EXECUTE STATEMENT :wSQL;

  EXECUTE STATEMENT 'DELETE FROM TMP_VEF_BASE_TNATOP_TEMP WHERE bdcodnat IS NOT NULL;';

      /*Busca as cfops existentes na importação, agrupa e insere na tabela*/
  wSQL =          'INSERT INTO TMP_VEF_BASE_TNATOP_TEMP (bdcodnat, BDNAOSOMARSTISEOUT, bdclassificacao, bdCODNATEX, bdCODNATufigual, bdCODNATufdif) ';
  wSQL = :wSQL || 'SELECT I.BDCODNAT, COALESCE(N.BDNAOSOMARSTISEOUT, ''FALSE'') BDNAOSOMARSTISEOUT, N.BDCLASSIFICACAO, ';
  wSQL = :wSQL ||        '(''7''||SUBSTRING(N.BDCODNAT FROM 2 FOR CHAR_LENGTH(N.BDCODNAT)-1)) BDEXTERIOR, ';
  wSQL = :wSQL ||        '(''5''||SUBSTRING(N.BDCODNAT FROM 2 FOR CHAR_LENGTH(N.BDCODNAT)-1)) BDUFIGUAL, ';
  wSQL = :wSQL ||        '(''6''||SUBSTRING(N.BDCODNAT FROM 2 FOR CHAR_LENGTH(N.BDCODNAT)-1)) BDUFDIF ';
  wSQL = :wSQL || 'FROM '||:wTableItem||' I ';
  wSQL = :wSQL || 'LEFT OUTER JOIN VEF_BASE_TNATOP N ON(N.BDCODNAT = I.BDCODNAT) ';
  wSQL = :wSQL || 'WHERE I.BDSESSAO = '||:wSessaoDest;
  wSQL = :wSQL || 'AND I.BDCODNAT IS NOT NULL ';
  wSQL = :wSQL || 'GROUP BY I.BDCODNAT, N.BDNAOSOMARSTISEOUT, N.BDCLASSIFICACAO, BDEXTERIOR, BDUFIGUAL, BDUFDIF; ';
  EXECUTE STATEMENT :wSQL;

  /*Muda a cfop se tiver setado para mudar no plano de inconsistencias - troca inicio da cfop para 5, 6 ou 7*/
  /*                  EX                */
  wSQL =          'UPDATE '||:wTableItem||' U ';
  wSQL = :wSQL || 'SET BDCODNAT = (';
  wSQL = :wSQL ||                 'COALESCE(';
  wSQL = :wSQL ||                          '(';
  wSQL = :wSQL ||                           'SELECT N.BDCODNATEX ';
  wSQL = :wSQL ||                           'FROM '||:wTableItem||' IT ';
  wSQL = :wSQL ||                           'LEFT OUTER JOIN TMP_VEF_BASE_TNATOP_TEMP N ON(N.BDCODNAT = IT.BDCODNAT) ';
  wSQL = :wSQL ||                           'WHERE IT.BDSESSAO = '||:wSessaoDest||' ';
  wSQL = :wSQL ||                           'AND N.BDCODNATEX IS NOT NULL ';
  wSQL = :wSQL ||                           'AND IT.BDSIGLAUFTER = ''EX'' ';
  wSQL = :wSQL ||                           'AND u.bdcodemp = it.bdcodemp ';
  wSQL = :wSQL ||                           'AND u.bdsessao = it.bdsessao ';
  wSQL = :wSQL ||                           'AND u.bdchave  = it.bdchave ';
  wSQL = :wSQL ||                           'AND u.bdordem  = it.bdordem ';
  wSQL = :wSQL ||                          '), BDCODNAT) ';
  wSQL = :wSQL ||                ') ';
  wSQL = :wSQL || 'WHERE U.BDSIGLAUFTER = ''EX'' ';
  wSQL = :wSQL || 'AND u.bdsessao = '||:wSessaoDest;
  EXECUTE STATEMENT :wSQL;

  /*                UF IGUAL          */
  wSQL =          'UPDATE '||:wTableItem||' U ';
  wSQL = :wSQL || 'SET BDCODNAT = (';
  wSQL = :wSQL ||                 'COALESCE(';
  wSQL = :wSQL ||                          '(';
  wSQL = :wSQL ||                           'SELECT N.BDCODNATUFIGUAL ';
  wSQL = :wSQL ||                           'FROM '||:wTableItem||' IT ';
  wSQL = :wSQL ||                           'LEFT OUTER JOIN TMP_VEF_BASE_TNATOP_TEMP N ON(N.BDCODNAT = IT.BDCODNAT) ';
  wSQL = :wSQL ||                           'WHERE IT.BDSESSAO = '||:wSessaoDest||' ';
  wSQL = :wSQL ||                           'AND N.BDCODNATEX IS NOT NULL ';
  wSQL = :wSQL ||                           'AND IT.BDSIGLAUFTER = '''||:PRUFEMP||''' ';
  wSQL = :wSQL ||                           'AND u.bdcodemp = it.bdcodemp ';
  wSQL = :wSQL ||                           'AND u.bdsessao = it.bdsessao ';
  wSQL = :wSQL ||                           'AND u.bdchave  = it.bdchave ';
  wSQL = :wSQL ||                           'AND u.bdordem  = it.bdordem ';
  wSQL = :wSQL ||                          '), BDCODNAT) ';
  wSQL = :wSQL ||                ') ';
  wSQL = :wSQL || 'WHERE U.BDSIGLAUFTER = '''||:PRUFEMP||''' ';
  wSQL = :wSQL || 'AND u.bdsessao = '||:wSessaoDest;
  EXECUTE STATEMENT :wSQL;

  /*                UF DIF            */
  wSQL =          'UPDATE '||:wTableItem||' U ';
  wSQL = :wSQL || 'SET BDCODNAT = (';
  wSQL = :wSQL ||                 'COALESCE(';
  wSQL = :wSQL ||                          '(';
  wSQL = :wSQL ||                           'SELECT N.BDCODNATUFDIF ';
  wSQL = :wSQL ||                           'FROM '||:wTableItem||' IT ';
  wSQL = :wSQL ||                           'LEFT OUTER JOIN TMP_VEF_BASE_TNATOP_TEMP N ON(N.BDCODNAT = IT.BDCODNAT) ';
  wSQL = :wSQL ||                           'WHERE IT.BDSESSAO = '||:wSessaoDest||' ';
  wSQL = :wSQL ||                           'AND N.BDCODNATEX IS NOT NULL ';
  wSQL = :wSQL ||                           'AND ((IT.BDSIGLAUFTER <> '''||:PRUFEMP||''') AND (IT.BDSIGLAUFTER <> ''EX'')) ';
  wSQL = :wSQL ||                           'AND u.bdcodemp = it.bdcodemp ';
  wSQL = :wSQL ||                           'AND u.bdsessao = it.bdsessao ';
  wSQL = :wSQL ||                           'AND u.bdchave  = it.bdchave ';
  wSQL = :wSQL ||                           'AND u.bdordem  = it.bdordem ';
  wSQL = :wSQL ||                          '), BDCODNAT) ';
  wSQL = :wSQL ||                ') ';
  wSQL = :wSQL || '  WHERE ((U.BDSIGLAUFTER <> '''||:PRUFEMP||''') AND (U.BDSIGLAUFTER <> ''EX'')) ';
  wSQL = :wSQL || '  AND u.bdsessao = '||:wSessaoDest;
  EXECUTE STATEMENT :wSQL;
END^

create or alter procedure SP_TRANSFERENCIA_LAN (
    PRID_TERMINAL integer,
    PRCODEMPORI integer,
    PRCODEMPDEST integer,
    PRREFTRANS integer,
    PRTIPOLAN char(3))
as
declare variable WCODPLANOONLINE integer;
declare variable WENQFED integer;
declare variable WCODCONFIRLP integer;
declare variable WTIPLAN integer;
declare variable WSESSAODEST integer;
declare variable WSESSAOORI integer;
declare variable WSESSAO integer;
declare variable WCODEMP integer;
declare variable WSQL varchar(8000);
declare variable WCONDICAO varchar(500);
declare variable WCHAVEDEST integer;
declare variable WTABLE varchar(31);
declare variable WTABLEFIS varchar(31);
declare variable WTABLEITEM varchar(31);
declare variable WTABLEITEMFIS varchar(31);
declare variable WTABLEINCON varchar(31);
declare variable WTABLERETFIS varchar(31);
declare variable WTABLERET varchar(31);
declare variable WTABLETOL varchar(31);
declare variable WTABLETOLRAT varchar(31);
declare variable WTABLEPAR varchar(31);
declare variable WTABLEPARFIS varchar(31);
declare variable WTABLEINSSFIS varchar(31);
declare variable WTABLERATFIS varchar(31);
declare variable WTABLEMOVPRO varchar(31);
declare variable WTABLEMOVPROFIS varchar(31);
declare variable WTABLERAT varchar(31);
declare variable WTABLECOPIA varchar(31);
declare variable WCAMPOTOL varchar(31);
declare variable WSIGLAUFORI char(2);
declare variable WSIGLAUFDEST char(2);
declare variable WCODCIDDEST integer;
declare variable WCHAVE integer;
declare variable WVLRIRSER DM_NUMERIC_15_2;
declare variable WRATEIARETENCOES varchar(500);
declare variable WFORMATRIBUTACAO integer;
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREFTRANS);

  /*Sessão empresa destino*/
  SELECT S.BDSESSAO
  FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRID_TERMINAL
  AND S.BDTABLE = 'DESTINO'
  INTO :wSessaoDest;

  SELECT S.BDSESSAO
  FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRID_TERMINAL
  AND S.BDTABLE = 'ORIGEM'
  INTO :wSessaoOri;

  SELECT SP.BDSIGLAUF FROM SP_CONSULTAEMPRESAS_SIS(:PRREFTRANS, :PRCODEMPORI, NULL)  SP INTO :wSiglaUFOri;
  SELECT SP.BDSIGLAUF, SP.BDCODCID FROM SP_CONSULTAEMPRESAS_SIS(:PRREFTRANS, :PRCODEMPDEST, NULL) SP INTO :wSiglaUFDest, :wCodCidDest;

  /*************************************************************************************************/
  /***************************************** TABELAS USADAS ****************************************/
  /*************************************************************************************************/

  wTableINSSFis = '';
  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTableFis    = 'VEF_EMP_TMOVENT';
      wTable       = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItem   = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      wTableItemFis= 'VEF_EMP_TMOVENTITENS';
      wTableIncon  = 'VEF_INCON_TMOVENT';
      wTableRetFis = 'VEF_EMP_TMOVENTRET';
      wTableRet    = 'TMP_VEF_EMP_TMOVENTRET_TEMP';
      wTableTOL    = 'TOL_VEF_EMP_TMOVENT';
      wCampoTol    = 'BDCHAVEENT';
      wTablePar    = 'TMP_VEF_EMP_TMOVENTPAR_TEMP';
      wTableParFis = 'VEF_EMP_TMOVENTPAR';
      wTableINSSFis= 'VEF_EMP_TMOVENTDED';
      wTableRat    = 'TMP_VEF_EMP_TMOVRATENT_TEMP';
      wTableRatFis = 'VEF_EMP_TMOVRATENT';
      wTableTolRat = 'TOL_VEF_EMP_TMOVRATENT';
      wTableMovPro = 'TMP_VEF_EMP_TMOVPROENT_TEMP';
      wTableMovProFis = 'VEF_EMP_TMOVPROENT';
    END
  ELSE
  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTableFis    = 'VEF_EMP_TMOVSAI';
      wTable       = 'TMP_VEF_EMP_TMOVSAI_TEMP';
      wTableItem   = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
      wTableItemFis= 'VEF_EMP_TMOVSAIITENS';
      wTableIncon  = 'VEF_INCON_TMOVSAI';
      wTableRetFis = 'VEF_EMP_TMOVSAIRET';
      wTableRet    = 'TMP_VEF_EMP_TMOVSAIRET_TEMP';
      wTableTOL    = 'TOL_VEF_EMP_TMOVSAI';
      wCampoTol    = 'BDCHAVESAI';
      wTablePar    = 'TMP_VEF_EMP_TMOVSAIPAR_TEMP';
      wTableParFis = 'VEF_EMP_TMOVSAIPAR';
      wTableINSSFis= 'VEF_EMP_TMOVSAIDED';
      wTableRat    = 'TMP_VEF_EMP_TMOVRATSAI_TEMP';
      wTableRatFis = 'VEF_EMP_TMOVRATSAI';
      wTableTolRat = 'TOL_VEF_EMP_TMOVRATSAI';
      wTableMovPro = 'TMP_VEF_EMP_TMOVPROSAI_TEMP';
      wTableMovProFis = 'VEF_EMP_TMOVPROSAI';
    END
  ELSE
  IF (:PRTIPOLAN = 'SER') THEN
    BEGIN
      wTableFis    = 'VEF_EMP_TMOVSER';
      wTable       = 'TMP_VEF_EMP_TMOVSER_TEMP';
      wTableItem   = 'TMP_VEF_EMP_TMOVSERITENS_TEMP';
      wTableItemFis= 'VEF_EMP_TMOVSERITENS';
      wTableIncon  = 'VEF_INCON_TMOVSER';
      wTableRetFis = 'VEF_EMP_TMOVSERRET';
      wTableRet    = 'TMP_VEF_EMP_TMOVSERRET_TEMP';
      wTableTOL    = 'TOL_VEF_EMP_TMOVSER';
      wCampoTol    = 'BDCHAVESER';
      wTablePar    = 'TMP_VEF_EMP_TMOVSERPAR_TEMP';
      wTableParFis = 'VEF_EMP_TMOVSERPAR';
      wTableINSSFis= 'VEF_EMP_TMOVSERDED';
      wTableRat    = 'TMP_VEF_EMP_TMOVRATSER_TEMP';
      wTableRatFis = 'VEF_EMP_TMOVRATSER';
      wTableTolRat = 'TOL_VEF_EMP_TMOVRATSER';
      wTableMovPro = 'TMP_VEF_EMP_TA170_TEMP';
      wTableMovProFis = 'VEF_EMP_TA170';
    END

  /*************************************************************************************************/
  /*************************************************************************************************/
  /*************************************************************************************************/

  IF (:wSessaoDest IS NULL) THEN
    EXIT;

  /*Joga o BDEDITCHAVE na tabela de itens*/
  wSQL =          'UPDATE '||:wTableItem||' T ';
  wSQL = :wSQL || 'SET T.BDEDITCHAVE = ( ';
  wSQL = :wSQL || '                     SELECT BDEDITCHAVE ';
  wSQL = :wSQL || '                     FROM '||:wTable||' S ';
  wSQL = :wSQL || '                     WHERE S.BDSESSAO = T.BDSESSAO ';
  wSQL = :wSQL || '                     AND S.BDCODEMP = T.BDCODEMP';
  wSQL = :wSQL || '                     AND S.BDCHAVE = T.BDCHAVE ';
  wSQL = :wSQL || '                    ) ';
  wSQL = :wSQL || 'WHERE T.BDSESSAO = '||:wSessaoDest;
  EXECUTE STATEMENT :wSQL;

  /*Seta a chave nova no mesmo registro*/
  wSQL =          'UPDATE TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL || 'SET TNF.BDCHAVEDEST = ( ';
  wSQL = :wSQL ||                        'SELECT I.BDEDITCHAVE ';
  wSQL = :wSQL ||                        'FROM '||:wTableItem||' I ';
  wSQL = :wSQL ||                        'WHERE I.BDSESSAO = '||:wSessaoDest;
  wSQL = :wSQL ||                        'AND I.BDCODEMP = '||:PRCODEMPDEST;
  wSQL = :wSQL ||                        'AND I.BDCHAVE_OLD = TNF.BDCHAVE ';
  wSQL = :wSQL ||                        'AND I.BDORDEM = TNF.BDORDEM ';
  wSQL = :wSQL ||                       ')';
  wSQL = :wSQL || 'WHERE TNF.BDCODEMP = '||:PRCODEMPDEST;
  EXECUTE STATEMENT :wSQL;

  /*Define o valor total de cada lançamento, destino e origem*/
  wSQL =          'UPDATE '||:wTable||' T ';
  wSQL = :wSQL || 'SET T.BDVALORNOTA = ( ';
  wSQL = :wSQL ||                      'SELECT SUM(COALESCE(I.BDVLRCONTAB, 0)) ';
  wSQL = :wSQL ||                      'FROM '||:wTableItem||' I ';
  wSQL = :wSQL ||                      'WHERE I.BDSESSAO = T.BDSESSAO ';
  wSQL = :wSQL ||                      'AND I.BDCODEMP = T.BDCODEMP ';
  wSQL = :wSQL ||                      'AND I.BDCHAVE = T.BDCHAVE ';
  wSQL = :wSQL ||                      'GROUP BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE ';
  wSQL = :wSQL ||                     ') ';
  wSQL = :wSQL || 'WHERE T.BDSESSAO IN('||:wSessaoOri||', '||:wSessaoDest||') ';
  wSQL = :wSQL || 'AND NOT EXISTS (';
  wSQL = :wSQL ||                 'SELECT I.BDSESSAO ';
  wSQL = :wSQL ||                 'FROM '||:wTableIncon||' I ';
  wSQL = :wSQL ||                 'WHERE I.BDSESSAO = '||:wSessaoDest||' ';
  /*Não filtra empresa porque se tiver inconsistencia tem que ignorar na empresa origem e destino*/
  wSQL = :wSQL ||                 'AND I.BDSESSAO = T.BDSESSAO ';
  wSQL = :wSQL ||                 'AND I.BDCHAVE = T.BDCHAVE';
  wSQL = :wSQL ||                ')';
  EXECUTE STATEMENT :wSQL;

  /*Recalcular retenções da empresa origem e destino, faz update da TEMP*/
  wSQL =          'UPDATE '||:wTableRet||' R ';
  wSQL = :wSQL || 'SET R.BDVLRPIS    = IIF(COALESCE(R.BDVLRPIS, 0) > 0, COALESCE((SELECT S.BDVALORNOTA FROM '||:wTable||' S WHERE S.BDSESSAO = R.BDSESSAO AND S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE) * CAST((SELECT RDB$GET_CONTEXT(''USER_SESSION'', ''W_PER_PIS'') FROM RDB$DATABASE) AS DM_NUMERIC_17_4), 0), 0), ';
  wSQL = :wSQL ||     'R.BDVLRCOFINS = IIF(COALESCE(R.BDVLRCOFINS, 0) > 0, COALESCE((SELECT S.BDVALORNOTA FROM '||:wTable||' S WHERE S.BDSESSAO = R.BDSESSAO AND S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE) * CAST((SELECT RDB$GET_CONTEXT(''USER_SESSION'', ''W_PER_COFINS'') FROM RDB$DATABASE) AS DM_NUMERIC_17_4), 0), 0), ';
  wSQL = :wSQL ||     'R.BDVLRCSOCIAL= IIF(COALESCE(R.BDVLRCSOCIAL, 0) > 0, COALESCE((SELECT S.BDVALORNOTA FROM '||:wTable||' S WHERE S.BDSESSAO = R.BDSESSAO AND S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE) * CAST((SELECT RDB$GET_CONTEXT(''USER_SESSION'', ''W_PER_CSOCIAL'') FROM RDB$DATABASE) AS DM_NUMERIC_17_4), 0), 0), ';

  wSQL = :wSQL ||   'R.BDVLRIR     = IIF(COALESCE(R.BDVLRIR, 0) > 0, IIF((SELECT SP.BDMOVIRRF FROM SP_CONSULTAEMPRESAS_SIS('||:PRREFTRANS||', R.BDCODEMP, NULL) SP) = ''TRUE'', ';
  IF (:PRTIPOLAN = 'SER') THEN /*Serviço pega a alíquota de IR do cadastro da empresa*/
    BEGIN
      wSQL = :wSQL ||                        '(COALESCE((SELECT S.BDVALORNOTA FROM '||:wTable||' S WHERE S.BDSESSAO = R.BDSESSAO AND S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE) * ';
      wSQL = :wSQL ||                        '(SELECT IIF((COALESCE(SP.BDALIQIRRF, 0)  / 100) > 0, (COALESCE(SP.BDALIQIRRF, 0)  / 100), CAST((SELECT RDB$GET_CONTEXT(''USER_SESSION'', ''W_PER_IRRET'') FROM RDB$DATABASE) AS DM_NUMERIC_17_4)) ';
      wSQL = :wSQL ||                        ' FROM SP_CONSULTAEMPRESAS_SIS('||:PRREFTRANS||', R.BDCODEMP, NULL) SP), 0)), 0), 0), ';
    END
  ELSE
    wSQL = :wSQL ||                        '(COALESCE((SELECT S.BDVALORNOTA FROM '||:wTable||' S WHERE S.BDSESSAO = R.BDSESSAO AND S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE) * CAST((SELECT RDB$GET_CONTEXT(''USER_SESSION'', ''W_PER_IRRET'') FROM RDB$DATABASE) AS DM_NUMERIC_17_4), 0)), 0), 0), ';

  IF (:PRTIPOLAN <> 'SER') THEN /*Retenção de INSS do serviço fica em outra tabela, faz logo abaixo.*/
    wSQL = :wSQL ||     'R.BDVLRINSS   = IIF(COALESCE(R.BDVLRINSS, 0) > 0, COALESCE((SELECT S.BDVALORNOTA FROM '||:wTable||' S WHERE S.BDSESSAO = R.BDSESSAO AND S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE) * CAST((SELECT RDB$GET_CONTEXT(''USER_SESSION'', ''W_PER_INSSRET'') FROM RDB$DATABASE) AS DM_NUMERIC_17_4), 0), 0), ';

  wSQL = :wSQL ||     'R.BDISSRET    = IIF(COALESCE(R.BDISSRET, 0) > 0, COALESCE((((SELECT S.BDVALORNOTA FROM '||:wTable||' S WHERE S.BDSESSAO = R.BDSESSAO AND S.BDCODEMP = R.BDCODEMP AND S.BDCHAVE = R.BDCHAVE) * (SELECT SP.BDPERCISS FROM SP_CONSULTAEMPRESAS_SIS('||:PRREFTRANS||', R.BDCODEMP, NULL) SP)) / 100), 0), 0) ';
  wSQL = :wSQL || 'WHERE R.BDSESSAO IN ('||:wSessaoOri||', '||:wSessaoDest||') ';
  wSQL = :wSQL || 'AND EXISTS(';
  wSQL = :wSQL ||            'SELECT TMP.BDEDITCHAVE ';
  wSQL = :wSQL ||            'FROM '||:wTable||' TMP ';
  wSQL = :wSQL ||            'WHERE TMP.BDSESSAO = R.BDSESSAO ';
  wSQL = :wSQL ||            'AND TMP.BDCODEMP = R.BDCODEMP ';
  wSQL = :wSQL ||            'AND TMP.BDCHAVE = R.BDCHAVE ';
  wSQL = :wSQL ||           ') ';
  wSQL = :wSQL || 'AND NOT EXISTS( ';
  wSQL = :wSQL || '               SELECT * ';
  wSQL = :wSQL || '               FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL || '               JOIN '||:wTableIncon||' INCO ON(INCO.BDSESSAO = '||:wSessaoDest||' AND INCO.BDCHAVE = TNF.BDCHAVE) ';
  wSQL = :wSQL || '               WHERE TNF.BDCHAVE = R.BDCHAVE ';
  wSQL = :wSQL || '              ); ';
  EXECUTE STATEMENT :wSQL;

  /*Recalcula a retenção de INSS*/
  IF (:PRTIPOLAN = 'SER') THEN
    BEGIN
      /*Calcula o valor proporcional dos materiais e subEmpreiteiras, usa esses valores para calcular o valor de inss depois*/
      UPDATE TMP_VEF_EMP_TMOVSERDED_TEMP INSS
      SET INSS.BDVLRMATERIAIS = (
                                 ((SELECT S.BDVALORNOTA FROM TMP_VEF_EMP_TMOVSER_TEMP S WHERE S.BDSESSAO = INSS.BDSESSAO AND S.BDCODEMP = INSS.BDCODEMP AND S.BDCHAVE = INSS.BDCHAVE) * COALESCE(INSS.BDVLRMATERIAIS, 0)) /
                                  (SELECT SER.BDVALORNOTA FROM VEF_EMP_TMOVSER SER WHERE SER.BDCODEMP = :PRCODEMPORI AND SER.BDCHAVE = INSS.BDCHAVE)
                                ),
          INSS.BDVLRSUBEMPREITEIRAS = (
                                       ((SELECT S.BDVALORNOTA FROM TMP_VEF_EMP_TMOVSER_TEMP S WHERE S.BDSESSAO = INSS.BDSESSAO AND S.BDCODEMP = INSS.BDCODEMP AND S.BDCHAVE = INSS.BDCHAVE) * COALESCE(INSS.BDVLRSUBEMPREITEIRAS, 0)) /
                                        (SELECT SER.BDVALORNOTA FROM VEF_EMP_TMOVSER SER WHERE SER.BDCODEMP = :PRCODEMPORI AND SER.BDCHAVE = INSS.BDCHAVE)
                                      )
      WHERE INSS.BDSESSAO IN(:wSessaoDest, :wSessaoOri)
      AND ((COALESCE(INSS.BDVLRMATERIAIS, 0) > 0) OR (COALESCE(INSS.BDVLRSUBEMPREITEIRAS, 0) > 0));

      UPDATE TMP_VEF_EMP_TMOVSERDED_TEMP INSS
      SET INSS.BDRETINSS = IIF((SELECT SP.BDRETINSS FROM SP_CONSULTAEMPRESAS_SIS(:PRREFTRANS, INSS.BDCODEMP, NULL) SP) = 'TRUE',
                           ((
                             SELECT S.BDVALORNOTA
                             FROM TMP_VEF_EMP_TMOVSER_TEMP S
                             WHERE S.BDSESSAO = INSS.BDSESSAO
                             AND S.BDCODEMP = INSS.BDCODEMP
                             AND S.BDCHAVE = INSS.BDCHAVE) - COALESCE(INSS.BDVLRMATERIAIS, 0) - COALESCE(INSS.BDVLRSUBEMPREITEIRAS, 0)) *
                             ((SELECT SP.BDALIQINSS FROM SP_CONSULTAEMPRESAS_SIS(:PRREFTRANS, INSS.BDCODEMP, NULL) SP) / 100), 0)
      WHERE INSS.BDSESSAO IN(:wSessaoDest, :wSessaoOri)
      AND INSS.BDRETINSS > 0;

      /*Atualiza o campo BDEDITCHAVE na empresa destino*/
      UPDATE TMP_VEF_EMP_TMOVSERDED_TEMP INSS
      SET INSS.BDEDITCHAVE = (
                              SELECT FIRST 1 T.BDEDITCHAVE
                              FROM TMP_VEF_EMP_TMOVSER_TEMP T
                              WHERE T.BDSESSAO = INSS.BDSESSAO
                              AND T.BDCODEMP = INSS.BDCODEMP
                              AND T.BDCHAVE = INSS.BDCHAVE
                             )
      WHERE INSS.BDSESSAO = :wSessaoDest
      AND INSS.BDEDITCHAVE IS NULL;

      /*Atualizando atividade municipal na empresa destino*/
      UPDATE TMP_VEF_EMP_TMOVSERITENS_TEMP I
      SET I.BDCODATVM = (
                         SELECT FIRST 1 BDCODATVM
                         FROM TATVMUNICIPAL ATVM
                         LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = ATVM.BDCODCID)
                         WHERE ATVM.BDCODCID = :wCodCidDest
                         AND ATVM.BDREFATVM = (
                                               SELECT FIRST 1 DISTINCT BDREFATVM
                                               FROM TATVMUNICIPAL
                                               WHERE BDCODCID = :wCodCidDest
                                               AND BDREFATVM <= (SELECT (SELECT BDDATA FROM SP_PARSE_DATE(MOV.BDDATAEMISSAO, 'YYYYMM')) FROM TMP_VEF_EMP_TMOVSER_TEMP MOV WHERE MOV.BDSESSAO = I.BDSESSAO AND MOV.BDCODEMP = I.BDCODEMP AND MOV.BDCHAVE = I.BDCHAVE)
                                               ORDER BY BDREFATVM DESC
                                              )
                         AND ATVM.BDCODMUNATVM = (SELECT FIRST 1 A.BDCODMUNATVM FROM TATVMUNICIPAL A WHERE A.BDCODATVM = I.BDCODATVM)
                         ORDER BY BDREFATVM, BDCODATVM
                        )
      WHERE I.BDSESSAO = :wSessaoDest
      AND I.BDCODATVM IS NOT NULL;
    END

  
  WRATEIARETENCOES = '(COALESCE(R.BDVLRPIS, 0) + COALESCE(R.BDVLRCOFINS, 0) + COALESCE(R.BDVLRCSOCIAL, 0) + COALESCE(R.BDVLRIR, 0) + COALESCE(INSS.BDRETINSS, 0) + COALESCE(R.BDISSRET, 0))';
  WRATEIARETENCOES = 'IIF((SELECT FIRST 1 IT.BDVLRCONTAB FROM '||wTableItem||' IT WHERE IT.BDSESSAO = M.BDSESSAO AND IT.BDCODEMP = M.BDCODEMP AND IT.BDCHAVE = M.BDCHAVE) <= '||:WRATEIARETENCOES||',''TRUE'',''FALSE'')';

  wSQL =  'UPDATE '||:WTABLE||' MOV SET ';
                                                                                                               
  wSQL = :wSQL || ' BDRATEIARET = ';
  wSQL = :wSQL || '(';
  wSQL = :wSQL || '  SELECT '||:WRATEIARETENCOES||' ';
  wSQL = :wSQL || '  FROM '||wTable||' M ';
  wSQL = :wSQL || '  LEFT OUTER JOIN '||wTableRet||' R on (R.BDSESSAO = M.BDSESSAO AND R.BDCODEMP = M.BDCODEMP AND R.BDCHAVE = M.BDCHAVE) ';
  wSQL = :wSQL || '  LEFT OUTER JOIN '||wTableINSSFis||' inss on (INSS.bdCODEMP = M.BDCODEMP_OLD and INSS.bdCHAVE = M.bdCHAVE) ';
  wSQL = :wSQL || '  WHERE M.BDSESSAO = MOV.BDSESSAO AND M.BDCODEMP = MOV.BDCODEMP AND M.BDCHAVE = MOV.BDCHAVE ';
  wSQL = :wSQL || ') ';
  wSQL = :wSQL || ', BDPRIMEIRAORDEM = ';
  wSQL = :wSQL || '(';
  wSQL = :wSQL || '  SELECT MIN(I.BDORDEM) BDORDEM ';
  wSQL = :wSQL || '  FROM '||wTableItem||' I ';
  wSQL = :wSQL || '  LEFT OUTER JOIN VEF_BASE_TNATOP N ON (N.BDCODNAT = i.bdcodnat) ';
  wSQL = :wSQL || '  WHERE I.BDSESSAO = MOV.BDSESSAO AND I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND N.BDCONTABILIZA = ''TRUE'' ';
  wSQL = :wSQL || ') ';
  wSQL = :wSQL || 'WHERE MOV.BDSESSAO IN ('||:wSessaoOri||', '||:wSessaoDest||'); ';
  EXECUTE STATEMENT :wSQL;

  /*Atualizar o campo BDEDITCHAVE das parcelas*/
  wSQL =          'UPDATE '||:wTablePar||' PAR ';
  wSQL = :wSQL || 'SET PAR.BDEDITCHAVE = (';
  wSQL = :wSQL ||                        'SELECT FIRST 1 T.BDEDITCHAVE ';
  wSQL = :wSQL ||                        'FROM '||:wTable||' T ';
  wSQL = :wSQL ||                        'WHERE T.BDSESSAO = PAR.BDSESSAO ';
  wSQL = :wSQL ||                        'AND T.BDCODEMP = PAR.BDCODEMP ';
  wSQL = :wSQL ||                        'AND T.BDCHAVE = PAR.BDCHAVE';
  wSQL = :wSQL ||                       ') ';
  wSQL = :wSQL || 'WHERE PAR.BDSESSAO IN ('||:wSessaoOri||', '||:wSessaoDest||'); ';
  EXECUTE STATEMENT :wSQL;

  /*Altera o valor das parcelas*/
  EXECUTE PROCEDURE SP_TRANSFERENCIA_PARCELAS(:PRID_TERMINAL, :PRTIPOLAN);
  /*Altera o valor do rateio*/
  EXECUTE PROCEDURE SP_TRANSFERENCIA_RATEIO(:PRID_TERMINAL, :PRCODEMPORI, :PRCODEMPDEST, :PRREFTRANS, :PRTIPOLAN);
  /*Altera o valor dos produtos do lançamento*/
  EXECUTE PROCEDURE SP_TRANSFERENCIA_PRODUTOS(:PRID_TERMINAL, :PRCODEMPORI, :PRCODEMPDEST, :PRREFTRANS, :PRTIPOLAN);

  /*Altera a CFOP caso o estado da origem e destino sejam diferentes.*/
  IF (:wSiglaUFDest <> :wSiglaUFOri) THEN
    EXECUTE PROCEDURE SP_TRANSFERENCIA_CFOP(:PRID_TERMINAL, :wSiglaUFDest, :PRTIPOLAN);

  /*Calcular a Base de ISS na empresa DESTINO*/
  wSQL =          'UPDATE '||:wTableItem||' I ';
  wSQL = :wSQL || 'SET I.BDBCISSSER = IIF(COALESCE(I.BDBCISSSER, 0) > 0, ';
  IF (:wSiglaUFDest = 'MG') THEN
    wSQL = :wSQL || '(I.BDVLRCONTAB - I.BDALIQREDBCISSSER), 0) ';
  ELSE
    wSQL = :wSQL || ' IIF(COALESCE(I.BDALIQREDBCISSSER, 0) > 0, (I.BDVLRCONTAB - ((I.BDVLRCONTAB * I.BDALIQREDBCISSSER) / 100)),I.BDVLRCONTAB), 0) '; -- Alt.: 173463 - Apenas quando tiver reducao ela deve ser considerada no calculo...
  wSQL = :wSQL || 'WHERE I.BDSESSAO = '||:wSessaoDest;
  EXECUTE STATEMENT :wSQL;

  /*Calcular o valor de ISS na empresa DESTINO*/
  wSQL =          'UPDATE '||:wTableItem||' I ';
  wSQL = :wSQL || 'SET I.BDVLRISSSER = (I.BDBCISSSER * (I.BDALIQREDISSSER / 100))';
  wSQL = :wSQL || 'WHERE I.BDSESSAO = '||:wSessaoDest||' ';
  wSQL = :wSQL || 'AND COALESCE(I.BDALIQREDISSSER, 0) > 0; ';
  EXECUTE STATEMENT :wSQL;

  /*Calcular o valor de Isentas ou Outras na empresa DESTINO*/
  wSQL =          'UPDATE '||:wTableItem||' I ';
  wSQL = :wSQL || 'SET I.BDISENTASISSSER = (SELECT BDVLR FROM SP_GET_VALOR_ISE_OUT(I.BDCODEMP, '||:PRREFTRANS||', I.BDCODNAT, ''I'', I.BDVLRCONTAB, I.BDBCISSSER, I.BDISENTASISSSER, I.BDOUTRASISSSER)), ';
  wSQL = :wSQL ||     'I.BDOUTRASISSSER  = (SELECT BDVLR FROM SP_GET_VALOR_ISE_OUT(I.BDCODEMP, '||:PRREFTRANS||', I.BDCODNAT, ''O'', I.BDVLRCONTAB, I.BDBCISSSER, I.BDISENTASISSSER, I.BDOUTRASISSSER)), ';
  wSQL = :wSQL ||     'I.BDCODREC = COALESCE((';
  wSQL = :wSQL ||                            'SELECT FIRST 1 BDCODRECIR ';
  wSQL = :wSQL ||                            'FROM (';
  wSQL = :wSQL ||                                  'SELECT * FROM (SELECT FIRST 1 * FROM VEF_INT_TRETENCAO WHERE bdCODEMP = I.BDCODEMP AND bdREFERENCIA <= '||:PRREFTRANS||' ORDER BY bdCODEMP, bdREFERENCIA DESC) ';
  wSQL = :wSQL ||                                  'UNION ALL ';
  wSQL = :wSQL ||                                  'SELECT * FROM (SELECT FIRST 1 * FROM VEF_INT_TRETENCAO WHERE bdCODEMP = I.BDCODEMP AND bdREFERENCIA > '||:PRREFTRANS||' ORDER BY bdCODEMP, bdREFERENCIA ASC) ';
  wSQL = :wSQL ||                                  'UNION ALL ';
  wSQL = :wSQL ||                                  'SELECT * FROM (SELECT FIRST 1 * FROM VEF_INT_TRETENCAO WHERE bdCODEMP IS NULL AND bdREFERENCIA <= '||:PRREFTRANS||' ORDER BY bdCODEMP, bdREFERENCIA DESC) ';
  wSQL = :wSQL ||                                  'UNION ALL ';
  wSQL = :wSQL ||                                  'SELECT * FROM (SELECT FIRST 1 * FROM VEF_INT_TRETENCAO WHERE bdCODEMP IS NULL AND bdREFERENCIA > '||:PRREFTRANS||' ORDER BY bdCODEMP, bdREFERENCIA ASC) ';
  wSQL = :wSQL ||                                 ')';
  wSQL = :wSQL ||                           '), 0) ';
  wSQL = :wSQL || 'WHERE I.BDSESSAO = '||:wSessaoDest;
  EXECUTE STATEMENT :wSQL;

  /*Preenche a base e alíquota de IR na empresa ORIGEM e DESTINO*/
  wSQL =          'UPDATE '||:wTableItem||' I ';
  wSQL = :wSQL || 'SET I.BDBCIRSER   = I.BDVLRCONTAB, ';
  wSQL = :wSQL ||     'I.BDALIQIRSER = COALESCE((SELECT IIF(COALESCE(SP.BDALIQIRRF, 0) > 0, SP.BDALIQIRRF, ';
  wSQL = :wSQL ||                               'CAST((SELECT RDB$GET_CONTEXT(''USER_SESSION'', ''W_PER_IRRET'') FROM RDB$DATABASE) ';
  wSQL = :wSQL ||                               'AS DM_NUMERIC_17_4)*100) FROM SP_CONSULTAEMPRESAS_SIS('||:PRREFTRANS||', I.BDCODEMP, NULL) SP), 0), ';
  wSQL = :wSQL ||     'I.BDVLRIRSER  = 0 ';
  wSQL = :wSQL || 'WHERE I.BDSESSAO IN ('||:wSessaoOri||', '||:wSessaoDest||') ';
  wSQL = :wSQL || 'AND COALESCE(I.BDVLRIRSER, 0) > 0;'; /*Significa que tinha IR no lançamento de origem*/
  EXECUTE STATEMENT :wSQL;

  /*Calcular valor de IR na empresa ORIGEM e DESTINO*/
  wSQL =          'UPDATE '||:wTableItem||' I ';
  wSQL = :wSQL || 'SET I.BDVLRIRSER   =  I.BDBCIRSER * (I.BDALIQIRSER / 100)';
  wSQL = :wSQL || 'WHERE I.BDSESSAO IN ('||:wSessaoOri||', '||:wSessaoDest||') ';
  wSQL = :wSQL || 'AND I.BDBCIRSER > 0 ';
  wSQL = :wSQL || 'AND I.BDALIQIRSER > 0;';
  EXECUTE STATEMENT :wSQL;

  /*Zera os valores de Base, alíquota e valor de IR caso o valor seja menor que isenção de IR na empresa ORIGEM e DESTINO*/
  wSQL =          'UPDATE '||:wTableItem||' I ';
  wSQL = :wSQL || 'SET I.BDBCIRSER   = 0,';
  wSQL = :wSQL || '    I.BDALIQIRSER = 0,';
  wSQL = :wSQL || '    I.BDVLRIRSER  = 0 ';
  wSQL = :wSQL || 'WHERE I.BDSESSAO IN ('||:wSessaoOri||', '||:wSessaoDest||') ';
  wSQL = :wSQL || 'AND ((I.BDVLRIRSER <= (SELECT SP.BDISENTOIRRF FROM SP_CONSULTAEMPRESAS_SIS('||:PRREFTRANS||', I.BDCODEMP, NULL) SP)) OR ';
  wSQL = :wSQL || '     ((SELECT SP.BDMOVIRRF FROM SP_CONSULTAEMPRESAS_SIS('||:PRREFTRANS||', I.BDCODEMP, NULL) SP) <> ''TRUE''));';
  EXECUTE STATEMENT :wSQL;

  IF (:PRTIPOLAN = 'SER') THEN
    BEGIN
      FOR SELECT MOV.BDSESSAO, MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDVLRIRSER
          FROM (
                SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE,
                       SUM(COALESCE(I.BDVLRIRSER, 0)) BDVLRIRSER
                FROM TMP_VEF_EMP_TMOVSERITENS_TEMP I
                WHERE I.BDSESSAO IN (:wSessaoOri, :wSessaoDest)
                GROUP BY I.BDSESSAO, I.BDCODEMP, I.BDCHAVE
               ) MOV
          WHERE MOV.BDVLRIRSER > 0
          INTO :wSessao, :wCodEmp, :wChave, :wVlrIRSer
      DO
        BEGIN
          UPDATE OR INSERT INTO TMP_VEF_EMP_TMOVSERRET_TEMP(BDSESSAO, BDCODEMP, BDCHAVE, BDVLRIR)
          VALUES(:wSessao, :wCodEmp, :wChave, :wVlrIRSer) MATCHING(BDSESSAO, BDCODEMP, BDCHAVE);
        END
    END


  /*Joga o BDEDITCHAVE nas tabelas dependentes na EMPRESA ORIGEM, a empresa destino faz no inicio do processo.*/
  EXECUTE PROCEDURE SP_ATUALIZAR_CAMPO_CHAVE_TEMP(:wSessaoOri, :wTable); /*Joga a chave do lançamento para os dependentes*/
  EXECUTE PROCEDURE SP_ATUALIZAR_CAMPO_CHAVE_TEMP(:wSessaoDest, :wTable); /*Joga a chave do lançamento para os dependentes*/

  /*Valida as contas dos lançamentos*/
  FOR SELECT S.BDSESSAO
      FROM TMP_TSESSAO_IMP S
      WHERE S.BDID_TERMINAL = :PRID_TERMINAL
      INTO :wSessao
  DO
    BEGIN
      EXECUTE STATEMENT 'SELECT FIRST 1 BDCODEMP FROM '||:wTable||' WHERE BDSESSAO = '||:wSessao INTO :wCodEmp;
      IF (:wCodEmp > 0) THEN
        BEGIN
          SELECT SP.BDCODPLANOONLINE, SP.BDCODENQFED, SP.BDCODCONFIRLP, sp.BDFORMATRIBUTACAO
          FROM SP_CONSULTAEMPRESAS_SIS(:PRREFTRANS, :wCodEmp, NULL) SP
          INTO :wCodPlanoOnline, :wEnqFed, :wCodConfIRLP, :WFORMATRIBUTACAO;
    
          IF (:PRTIPOLAN = 'SER') THEN
            BEGIN
              wTipLan = NULL;
              /*0 - Emitido
                1 - Recebido*/
              SELECT FIRST 1 S.BDTIPLAN
              FROM TMP_VEF_EMP_TMOVSER_TEMP S
              LEFT OUTER JOIN VEF_INCON_TMOVSER I ON(I.BDSESSAO = :wSessaoDest AND I.BDCHAVE = S.BDCHAVE)
              WHERE S.BDSESSAO = :wSessao
              AND S.BDTIPLAN = 0
              AND I.BDCODINCONSISTENCIA IS NULL
              INTO :wTipLan;
    
              /*Tem lançamento emitido*/
              IF (:wTipLan IS NOT NULL) THEN
                BEGIN
                  EXECUTE PROCEDURE SP_VALIDA_CONTA_ONLINE_TEMP(:wCodPlanoOnline, :wSessao, :wEnqFed, :wCodConfIRLP, 'SERE');
                  /*Monta o complemento de histórico dos lançamentos*/
                  EXECUTE PROCEDURE SP_INSERE_COMPLEMENTO_HIST (:wCodPlanoOnline, :wSessao, 'SERE');
                  EXECUTE PROCEDURE SP_CRIA_PRE_CONTABILIZACAO(:wSessao, :wCodPlanoOnline, :wEnqFed, :wCodConfIRLP, 'SERE', 0, :WFORMATRIBUTACAO); /*Cria a contaliza????o em uma tabela TEMP*/
                  DELETE FROM TMP_TCFOP_TMOV WHERE BDCODITEMONLINE IS NOT NULL;
                  DELETE FROM TCONTAS_ONLINE_TEMP WHERE BDSESSAO = :wSessao;
                END
    
              wTipLan = NULL;
              /*0 - Emitido
                1 - Recebido*/
              SELECT FIRST 1 S.BDTIPLAN
              FROM TMP_VEF_EMP_TMOVSER_TEMP S
              LEFT OUTER JOIN VEF_INCON_TMOVSER I ON(I.BDSESSAO = :wSessaoDest AND I.BDCHAVE = S.BDCHAVE)
              WHERE S.BDSESSAO = :wSessao
              AND S.BDTIPLAN = 1
              AND I.BDCODINCONSISTENCIA IS NULL
              INTO :wTipLan;
    
              /*Tem lançamento recebido*/
              IF (:wTipLan IS NOT NULL) THEN
                BEGIN
                  EXECUTE PROCEDURE SP_VALIDA_CONTA_ONLINE_TEMP(:wCodPlanoOnline, :wSessao, :wEnqFed, :wCodConfIRLP, 'SERR');
                  /*Monta o complemento de histórico dos lançamentos*/
                  EXECUTE PROCEDURE SP_INSERE_COMPLEMENTO_HIST (:wCodPlanoOnline, :wSessao, 'SERR');
                  EXECUTE PROCEDURE SP_CRIA_PRE_CONTABILIZACAO(:wSessao, :wCodPlanoOnline, :wEnqFed, :wCodConfIRLP, 'SERR', 0, :WFORMATRIBUTACAO); /*Cria a contaliza????o em uma tabela TEMP*/
                  DELETE FROM TMP_TCFOP_TMOV WHERE BDCODITEMONLINE IS NOT NULL;
                  DELETE FROM TCONTAS_ONLINE_TEMP WHERE BDSESSAO = :wSessao;
                END
            END
          ELSE
            BEGIN
              EXECUTE PROCEDURE SP_VALIDA_CONTA_ONLINE_TEMP(:wCodPlanoOnline, :wSessao, :wEnqFed, :wCodConfIRLP, :PRTIPOLAN);
              /*Monta o complemento de histórico dos lançamentos*/
              EXECUTE PROCEDURE SP_INSERE_COMPLEMENTO_HIST (:wCodPlanoOnline, :wSessao, :PRTIPOLAN);
              EXECUTE PROCEDURE SP_CRIA_PRE_CONTABILIZACAO(:wSessao, :wCodPlanoOnline, :wEnqFed, :wCodConfIRLP, :PRTIPOLAN, 0, :WFORMATRIBUTACAO); /*Cria a contaliza????o em uma tabela TEMP*/

              DELETE FROM TMP_TCFOP_TMOV WHERE BDCODITEMONLINE IS NOT NULL;
              DELETE FROM TCONTAS_ONLINE_TEMP WHERE BDSESSAO = :wSessao;
            END
      END
    END

  /****************************************************************************************************************************/
  /****************************************Inserindo os lançamentos na empresa destino*****************************************/
  /****************************************************************************************************************************/
  EXECUTE PROCEDURE SP_GRAVAR_LAN(:wSessaoDest, :PRCODEMPDEST, :PRTIPOLAN);

  wSQL =          'SELECT ''BDCODEMP='||:PRCODEMPORI||';BDCHAVE=''||TNF.BDCHAVE||'';''||IIF(TNF.BDORDEM > 0, ''BDORDEM=''||TNF.BDORDEM||'';'', '';''), TNF.BDCHAVEDEST ';
  wSQL = :wSQL || 'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL || 'WHERE TNF.BDCODEMP = '||:PRCODEMPDEST;
  wSQL = :wSQL || 'AND NOT EXISTS (';
  wSQL = :wSQL ||                 'SELECT * ';
  wSQL = :wSQL ||                 'FROM '||:wTableIncon||' S ';
  wSQL = :wSQL ||                 'WHERE S.BDSESSAO = '||:wSessaoDest;
  wSQL = :wSQL ||                 'AND S.BDCHAVE = TNF.BDCHAVE ';
  wSQL = :wSQL ||                ')';

  wTableCopia = :wTableFis;
  FOR EXECUTE STATEMENT :wSQL
      INTO :wCondicao, :wChaveDest
  DO
    BEGIN
      EXECUTE PROCEDURE SP_INSERE_DEPENDENTES(:PRCODEMPDEST, :wChaveDest, :wTableCopia, :wCondicao, (:wTableItemFis||';'||:wTableRetFis||';'||:wTableParFis||';'||:wTableINSSFis||';'||:wTableRatFis||';'||:wTableMovProFis));
      wTableCopia = :wTableItemFis;
    END

  /****************************************************************************************************************************/

  /*Insere os registros NOVOS nas tol's (empresa de destino)*/
  EXECUTE PROCEDURE SP_TRANSFERENCIA_TOL(:PRID_TERMINAL, :PRTIPOLAN, 'INS');

  /*Tratamento dos lançamentos da empresa origem no caso de exclusão total do lançamento*/
  /*1º - Apagar a contabilização */
  wSQL =          'DELETE FROM '||:wTableTOL||' TOL ';
  wSQL = :wSQL || 'WHERE TOL.BDCODEMP = '||:PRCODEMPORI||' ';
  wSQL = :wSQL || 'AND EXISTS(';
  wSQL = :wSQL ||            'SELECT * ';
  wSQL = :wSQL ||            'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL ||            'WHERE TNF.BDCODEMP = '||:PRCODEMPDEST||' ';
  wSQL = :wSQL ||            'AND TNF.BDCHAVE = TOL.'||:wCampoTol||' ';
  wSQL = :wSQL ||           ') ';
  wSQL = :wSQL || 'AND NOT EXISTS(';
  wSQL = :wSQL ||                'SELECT * ';
  wSQL = :wSQL ||                'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL ||                'JOIN '||:wTableIncon||' INCO ON(INCO.BDSESSAO = '||:wSessaoDest||' AND INCO.BDCHAVE = TNF.BDCHAVE) ';
  wSQL = :wSQL ||                'WHERE TNF.BDCHAVE = TOL.'||:wCampoTol||' ';
  wSQL = :wSQL ||               ')';
  EXECUTE STATEMENT :wSQL;

  wSQL =          'DELETE FROM '||:wTableTOLRat||' TOL ';
  wSQL = :wSQL || 'WHERE TOL.BDCODEMP = '||:PRCODEMPORI||' ';
  wSQL = :wSQL || 'AND EXISTS(';
  wSQL = :wSQL ||            'SELECT * ';
  wSQL = :wSQL ||            'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL ||            'WHERE TNF.BDCODEMP = '||:PRCODEMPDEST||' ';
  wSQL = :wSQL ||            'AND TNF.BDCHAVE = TOL.BDCHAVELAN ';
  wSQL = :wSQL ||           ') ';
  wSQL = :wSQL || 'AND NOT EXISTS(';
  wSQL = :wSQL ||                'SELECT * ';
  wSQL = :wSQL ||                'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL ||                'JOIN '||:wTableIncon||' INCO ON(INCO.BDSESSAO = '||:wSessaoDest||' AND INCO.BDCHAVE = TNF.BDCHAVE) ';
  wSQL = :wSQL ||                'WHERE TNF.BDCHAVE = TOL.BDCHAVELAN ';
  wSQL = :wSQL ||               ')';
  EXECUTE STATEMENT :wSQL;

  /*Apagando itens que foram transferidos para outra empresa*/
  wSQL =          'DELETE FROM '||:wTableItemFis||' I ';
  wSQL = :wSQL || 'WHERE I.BDCODEMP = '||:PRCODEMPORI||' ';
  wSQL = :wSQL || 'AND EXISTS(';
  wSQL = :wSQL ||            'SELECT * ';
  wSQL = :wSQL ||            'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL ||            'WHERE TNF.BDCODEMP = '||:PRCODEMPDEST||' ';
  wSQL = :wSQL ||            'AND TNF.BDCHAVE = I.BDCHAVE ';
  wSQL = :wSQL ||            'AND TNF.BDORDEM = I.BDORDEM ';
  wSQL = :wSQL ||            'AND TNF.BDTIPO = 0 '; /*Total*/
  wSQL = :wSQL ||           ') ';
  wSQL = :wSQL || 'AND NOT EXISTS(';
  wSQL = :wSQL ||                'SELECT * ';
  wSQL = :wSQL ||                'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL ||                'JOIN '||:wTableIncon||' INCO ON(INCO.BDSESSAO = '||:wSessaoDest||' AND INCO.BDCHAVE = TNF.BDCHAVE) ';
  wSQL = :wSQL ||                'WHERE TNF.BDCHAVE = I.BDCHAVE ';
  wSQL = :wSQL ||               ')';
  EXECUTE STATEMENT :wSQL;

  /*Apagando lançamentos que não tem itens*/
  wSQL =          'DELETE FROM '||:wTableFis||' S ';
  wSQL = :wSQL || 'WHERE S.BDCODEMP = '||:PRCODEMPORI||' ';
  wSQL = :wSQL || 'AND NOT EXISTS(';
  wSQL = :wSQL ||                'SELECT * ';
  wSQL = :wSQL ||                'FROM '||:wTableItemFis||' I ';
  wSQL = :wSQL ||                'WHERE I.BDCODEMP = S.BDCODEMP ';
  wSQL = :wSQL ||                'AND I.BDCHAVE = S.BDCHAVE ';
  wSQL = :wSQL ||               ')   ';
  wSQL = :wSQL || 'AND EXISTS(';
  wSQL = :wSQL ||            'SELECT * ';
  wSQL = :wSQL ||            'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL ||            'LEFT OUTER JOIN '||:wTableIncon||' INCO ON(INCO.BDSESSAO = '||:wSessaoDest||' AND INCO.BDCHAVE = TNF.BDCHAVE) ';
  wSQL = :wSQL ||            'WHERE INCO.BDCODINCONSISTENCIA IS NULL ';
  wSQL = :wSQL ||            'AND TNF.BDCHAVE = S.BDCHAVE ';
  wSQL = :wSQL ||           ')';
  EXECUTE STATEMENT :wSQL;

  /*Em caso de transferencia de metade do lançamento, só faz update*/
  /*Atualizando valor da capa */
  wSQL =          'UPDATE '||:wTableFis||' S ';
  wSQL = :wSQL || 'SET S.BDVALORNOTA = COALESCE((SELECT SUM(COALESCE(T.BDVALORNOTA, 0)) ';
  wSQL = :wSQL ||                               'FROM TMP_VEF_EMP_TMOVSER_TEMP T ';
  wSQL = :wSQL ||                               'WHERE T.BDSESSAO = '||:wSessaoOri;
  wSQL = :wSQL ||                               'AND T.BDCODEMP = S.BDCODEMP ';
  wSQL = :wSQL ||                               'AND T.BDCHAVE = S.BDCHAVE ';
  wSQL = :wSQL ||                               'GROUP BY T.BDSESSAO, T.BDCODEMP, T.BDCHAVE ';
  wSQL = :wSQL ||                              '), S.BDVALORNOTA) ';
  wSQL = :wSQL || 'WHERE S.BDCODEMP = '||:PRCODEMPORI;
  wSQL = :wSQL || 'AND EXISTS (';
  wSQL = :wSQL ||             'SELECT * ';
  wSQL = :wSQL ||             'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL ||             'WHERE TNF.BDCODEMP = '||:PRCODEMPDEST||' ';
  wSQL = :wSQL ||             'AND TNF.BDCHAVE = S.BDCHAVE ';
  wSQL = :wSQL ||            ') ';
  wSQL = :wSQL || 'AND NOT EXISTS(';
  wSQL = :wSQL ||                'SELECT * ';
  wSQL = :wSQL ||                'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL ||                'JOIN '||:wTableIncon||' INCO ON(INCO.BDSESSAO = '||:wSessaoDest||' AND INCO.BDCHAVE = TNF.BDCHAVE) ';
  wSQL = :wSQL ||                'WHERE TNF.BDCHAVE = S.BDCHAVE ';
  wSQL = :wSQL ||               ')';
  EXECUTE STATEMENT :wSQL;

  /*Atualizando valor das cfop's - Empresa ORIGEM*/
  wSQL =          'UPDATE '||:wTableItemFis||' I ';
  wSQL = :wSQL || 'SET I.BDVLRCONTAB = (';
  wSQL = :wSQL ||                      'SELECT TMP.BDVLRCONTAB ';
  wSQL = :wSQL ||                      'FROM '||:wTableItem||' TMP ';
  wSQL = :wSQL ||                      'WHERE TMP.BDSESSAO = '||:wSessaoOri||' ';
  wSQL = :wSQL ||                      'AND TMP.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL ||                      'AND TMP.BDCHAVE = I.BDCHAVE ';
  wSQL = :wSQL ||                      'AND TMP.BDORDEM = I.BDORDEM';
  wSQL = :wSQL ||                     '), ';
  wSQL = :wSQL ||     'I.BDBCIRSER = (';
  wSQL = :wSQL ||                      'SELECT TMP.BDBCIRSER ';
  wSQL = :wSQL ||                      'FROM '||:wTableItem||' TMP ';
  wSQL = :wSQL ||                      'WHERE TMP.BDSESSAO = '||:wSessaoOri||' ';
  wSQL = :wSQL ||                      'AND TMP.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL ||                      'AND TMP.BDCHAVE = I.BDCHAVE ';
  wSQL = :wSQL ||                      'AND TMP.BDORDEM = I.BDORDEM';
  wSQL = :wSQL ||                     '), ';
  wSQL = :wSQL ||     'I.BDALIQIRSER = (';
  wSQL = :wSQL ||                      'SELECT TMP.BDALIQIRSER ';
  wSQL = :wSQL ||                      'FROM '||:wTableItem||' TMP ';
  wSQL = :wSQL ||                      'WHERE TMP.BDSESSAO = '||:wSessaoOri||' ';
  wSQL = :wSQL ||                      'AND TMP.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL ||                      'AND TMP.BDCHAVE = I.BDCHAVE ';
  wSQL = :wSQL ||                      'AND TMP.BDORDEM = I.BDORDEM';
  wSQL = :wSQL ||                     '), ';
  wSQL = :wSQL ||     'I.BDVLRIRSER = (';
  wSQL = :wSQL ||                      'SELECT TMP.BDVLRIRSER ';
  wSQL = :wSQL ||                      'FROM '||:wTableItem||' TMP ';
  wSQL = :wSQL ||                      'WHERE TMP.BDSESSAO = '||:wSessaoOri||' ';
  wSQL = :wSQL ||                      'AND TMP.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL ||                      'AND TMP.BDCHAVE = I.BDCHAVE ';
  wSQL = :wSQL ||                      'AND TMP.BDORDEM = I.BDORDEM';
  wSQL = :wSQL ||                     ') ';
  wSQL = :wSQL || 'WHERE I.BDCODEMP = '||:PRCODEMPORI;
  wSQL = :wSQL || 'AND EXISTS( ';
  wSQL = :wSQL || '           SELECT TMP.BDVLRCONTAB ';
  wSQL = :wSQL || '           FROM '||:wTableItem||' TMP ';
  wSQL = :wSQL || '           WHERE TMP.BDSESSAO = '||:wSessaoOri||' ';
  wSQL = :wSQL || '           AND TMP.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL || '           AND TMP.BDCHAVE = I.BDCHAVE ';
  wSQL = :wSQL || '           AND TMP.BDORDEM = I.BDORDEM ';
  wSQL = :wSQL || '          ) ';
  wSQL = :wSQL || 'AND NOT EXISTS( ';
  wSQL = :wSQL || '               SELECT * ';
  wSQL = :wSQL || '               FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL || '               JOIN '||:wTableIncon||' INCO ON(INCO.BDSESSAO = '||:wSessaoDest||' AND INCO.BDCHAVE = TNF.BDCHAVE) ';
  wSQL = :wSQL || '               WHERE TNF.BDCHAVE = I.BDCHAVE ';
  wSQL = :wSQL || '              ); ';
  EXECUTE STATEMENT :wSQL;

  /*Atualizando a base de ISS - Empresa ORIGEM*/
  wSQL =          'UPDATE '||:wTableItemFis||' I ';
  wSQL = :wSQL || 'SET I.BDBCISSSER = IIF(I.BDBCISSSER > 0, ';

  IF (:wSiglaUFOri = 'MG') THEN
    wSQL = :wSQL || '(I.BDVLRCONTAB - I.BDALIQREDBCISSSER), 0) ';
  ELSE
    wSQL = :wSQL || '(I.BDVLRCONTAB - ((I.BDVLRCONTAB * I.BDALIQREDBCISSSER) / 100)), 0) ';

  wSQL = :wSQL || 'WHERE I.BDCODEMP = '||:PRCODEMPORI;
  wSQL = :wSQL || 'AND EXISTS( ';
  wSQL = :wSQL || '           SELECT TMP.BDVLRCONTAB ';
  wSQL = :wSQL || '           FROM '||:wTableItem||' TMP ';
  wSQL = :wSQL || '           WHERE TMP.BDSESSAO = '||:wSessaoOri||' ';
  wSQL = :wSQL || '           AND TMP.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL || '           AND TMP.BDCHAVE = I.BDCHAVE ';
  wSQL = :wSQL || '           AND TMP.BDORDEM = I.BDORDEM ';
  wSQL = :wSQL || '          ) ';
  wSQL = :wSQL || 'AND NOT EXISTS( ';
  wSQL = :wSQL || '               SELECT * ';
  wSQL = :wSQL || '               FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL || '               JOIN '||:wTableIncon||' INCO ON(INCO.BDSESSAO = '||:wSessaoDest||' AND INCO.BDCHAVE = TNF.BDCHAVE) ';
  wSQL = :wSQL || '               WHERE TNF.BDCHAVE = I.BDCHAVE ';
  wSQL = :wSQL || '              ); ';
  EXECUTE STATEMENT :wSQL;

  /*Atualizando valor de ISS - Empresa ORIGEM*/
  wSQL =          'UPDATE '||:wTableItemFis||' I ';
  wSQL = :wSQL || 'SET I.BDVLRISSSER = (I.BDBCISSSER * (I.BDALIQREDISSSER / 100)) ';
  wSQL = :wSQL || 'WHERE I.BDCODEMP = '||:PRCODEMPORI||' ';
  wSQL = :wSQL || 'AND COALESCE(I.BDALIQREDISSSER, 0) > 0 ';
  wSQL = :wSQL || 'AND EXISTS( ';
  wSQL = :wSQL || '           SELECT TMP.BDVLRCONTAB ';
  wSQL = :wSQL || '           FROM '||:wTableItem||' TMP ';
  wSQL = :wSQL || '           WHERE TMP.BDSESSAO = '||:wSessaoOri||' ';
  wSQL = :wSQL || '           AND TMP.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL || '           AND TMP.BDCHAVE = I.BDCHAVE ';
  wSQL = :wSQL || '           AND TMP.BDORDEM = I.BDORDEM ';
  wSQL = :wSQL || '          ) ';
  wSQL = :wSQL || 'AND NOT EXISTS( ';
  wSQL = :wSQL || '               SELECT * ';
  wSQL = :wSQL || '               FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL || '               JOIN '||:wTableIncon||' INCO ON(INCO.BDSESSAO = '||:wSessaoDest||' AND INCO.BDCHAVE = TNF.BDCHAVE) ';
  wSQL = :wSQL || '               WHERE TNF.BDCHAVE = I.BDCHAVE ';
  wSQL = :wSQL || '              ); ';
  EXECUTE STATEMENT :wSQL;

  /*Atualizando o valor de Isentas ou Outras - Empresa ORIGEM*/
  wSQL =          'UPDATE '||:wTableItemFis||' I ';
  wSQL = :wSQL || 'SET I.BDISENTASISSSER = (SELECT BDVLR FROM SP_GET_VALOR_ISE_OUT(I.BDCODEMP, '||:PRREFTRANS||', I.BDCODNAT, ''I'', I.BDVLRCONTAB, I.BDBCISSSER, I.BDISENTASISSSER, I.BDOUTRASISSSER)), ';
  wSQL = :wSQL ||     'I.BDOUTRASISSSER  = (SELECT BDVLR FROM SP_GET_VALOR_ISE_OUT(I.BDCODEMP, '||:PRREFTRANS||', I.BDCODNAT, ''O'', I.BDVLRCONTAB, I.BDBCISSSER, I.BDISENTASISSSER, I.BDOUTRASISSSER)) ';
  wSQL = :wSQL || 'WHERE I.BDCODEMP = '||:PRCODEMPORI||' ';
--  wSQL = :wSQL || 'AND COALESCE(I.BDALIQREDISSSER, 0) > 0 ';
  wSQL = :wSQL || 'AND EXISTS( ';
  wSQL = :wSQL || '           SELECT TMP.BDVLRCONTAB ';
  wSQL = :wSQL || '           FROM '||:wTableItem||' TMP ';
  wSQL = :wSQL || '           WHERE TMP.BDSESSAO = '||:wSessaoOri||' ';
  wSQL = :wSQL || '           AND TMP.BDCODEMP = I.BDCODEMP ';
  wSQL = :wSQL || '           AND TMP.BDCHAVE = I.BDCHAVE ';
  wSQL = :wSQL || '           AND TMP.BDORDEM = I.BDORDEM ';
  wSQL = :wSQL || '          ) ';
  wSQL = :wSQL || 'AND NOT EXISTS( ';
  wSQL = :wSQL || '               SELECT * ';
  wSQL = :wSQL || '               FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL || '               JOIN '||:wTableIncon||' INCO ON(INCO.BDSESSAO = '||:wSessaoDest||' AND INCO.BDCHAVE = TNF.BDCHAVE) ';
  wSQL = :wSQL || '               WHERE TNF.BDCHAVE = I.BDCHAVE ';
  wSQL = :wSQL || '              ); ';
  EXECUTE STATEMENT :wSQL;

  /*Apaga e grava as parcelas da empresa origem*/
  wSQL =          'DELETE FROM '||:wTableParFis||' P ';
  wSQL = :wSQL || 'WHERE P.BDCODEMP = '||:PRCODEMPORI;
  wSQL = :wSQL || 'AND EXISTS (';
  wSQL = :wSQL ||             'SELECT * ';
  wSQL = :wSQL ||             'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL ||             'WHERE TNF.BDCODEMP = '||:PRCODEMPORI||' ';
  wSQL = :wSQL ||             'AND TNF.BDCODEMP = P.BDCODEMP ';
  wSQL = :wSQL ||             'AND TNF.BDCHAVE  = P.BDCHAVE ';
  wSQL = :wSQL ||            ') ';
  wSQL = :wSQL || 'AND NOT EXISTS( ';
  wSQL = :wSQL || '               SELECT * ';
  wSQL = :wSQL || '               FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL || '               JOIN '||:wTableIncon||' INCO ON(INCO.BDSESSAO = '||:wSessaoDest||' AND INCO.BDCHAVE = TNF.BDCHAVE) ';
  wSQL = :wSQL || '               WHERE TNF.BDCHAVE = P.BDCHAVE ';
  wSQL = :wSQL || '              ); ';
  EXECUTE STATEMENT :wSQL;

  /*Inserido as parcelas geradas novamente pela empresa origem*/
  wSQL =          'INSERT INTO '||:wTableParFis||'(BDCODEMP, BDCHAVE, BDORDEMPAR, BDCODIGOPLA, BDPARCELAPAR, ';
  wSQL = :wSQL ||                                 'BDCHEQUEPAR, BDDUPLICATAPAR, BDVALORPAR, BDDATAVENCTOPAR, ';
  wSQL = :wSQL ||                                 'BDOUTROSPAR, BDRECIBOPAR, BDPROMISSPAR, BDVALORRETPIS, ';
  wSQL = :wSQL ||                                 'BDVALORRETCOFINS, BDVALORRETCSLL, BDVALORRETIRRF, ';
  wSQL = :wSQL ||                                 'BDVALORRETISSQN, BDVALORRETINSS, BDVALORBRUTO) ';
  wSQL = :wSQL || 'SELECT PAR.BDCODEMP, PAR.BDEDITCHAVE, PAR.BDORDEMPAR, PAR.BDCODIGOPLA, PAR.BDPARCELAPAR, ';
  wSQL = :wSQL ||        'PAR.BDCHEQUEPAR, PAR.BDDUPLICATAPAR, PAR.BDVALORPAR, PAR.BDDATAVENCTOPAR, ';
  wSQL = :wSQL ||        'PAR.BDOUTROSPAR, PAR.BDRECIBOPAR, PAR.BDPROMISSPAR, PAR.BDVALORRETPIS, ';
  wSQL = :wSQL ||        'PAR.BDVALORRETCOFINS, PAR.BDVALORRETCSLL, PAR.BDVALORRETIRRF, ';
  wSQL = :wSQL ||        'PAR.BDVALORRETISSQN, PAR.BDVALORRETINSS, PAR.BDVALORBRUTO ';
  wSQL = :wSQL || 'FROM '||:wTablePar||' PAR ';
  wSQL = :wSQL || 'WHERE PAR.BDSESSAO = '||:wSessaoOri||' ';
  wSQL = :wSQL || 'AND NOT EXISTS( ';
  wSQL = :wSQL || '               SELECT * ';
  wSQL = :wSQL || '               FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL || '               JOIN '||:wTableIncon||' INCO ON(INCO.BDSESSAO = '||:wSessaoDest||' AND INCO.BDCHAVE = TNF.BDCHAVE) ';
  wSQL = :wSQL || '               WHERE TNF.BDCHAVE = PAR.BDCHAVE ';
  wSQL = :wSQL || '              ); ';
  EXECUTE STATEMENT :wSQL;

  /*Atualiza os valores de retenção na empresa origem*/
  wSQL =          'UPDATE '||:wTableRetFis||' RET ';
  wSQL = :wSQL || 'SET RET.BDVLRPIS    = (SELECT TMP.BDVLRPIS     FROM '||:wTableRet||' TMP WHERE TMP.BDSESSAO = '||:wSessaoOri||' AND TMP.BDCODEMP = RET.BDCODEMP AND TMP.BDEDITCHAVE = RET.BDCHAVE), ';
  wSQL = :wSQL ||     'RET.BDVLRCOFINS = (SELECT TMP.BDVLRCOFINS  FROM '||:wTableRet||' TMP WHERE TMP.BDSESSAO = '||:wSessaoOri||' AND TMP.BDCODEMP = RET.BDCODEMP AND TMP.BDEDITCHAVE = RET.BDCHAVE), ';
  wSQL = :wSQL ||     'RET.BDVLRCSOCIAL= (SELECT TMP.BDVLRCSOCIAL FROM '||:wTableRet||' TMP WHERE TMP.BDSESSAO = '||:wSessaoOri||' AND TMP.BDCODEMP = RET.BDCODEMP AND TMP.BDEDITCHAVE = RET.BDCHAVE), ';
  wSQL = :wSQL ||     'RET.BDVLRIR     = (SELECT TMP.BDVLRIR      FROM '||:wTableRet||' TMP WHERE TMP.BDSESSAO = '||:wSessaoOri||' AND TMP.BDCODEMP = RET.BDCODEMP AND TMP.BDEDITCHAVE = RET.BDCHAVE), ';
  IF (:PRTIPOLAN <> 'SER') THEN
    wSQL = :wSQL ||     'RET.BDVLRINSS   = (SELECT TMP.BDVLRINSS    FROM '||:wTableRet||' TMP WHERE TMP.BDSESSAO = '||:wSessaoOri||' AND TMP.BDCODEMP = RET.BDCODEMP AND TMP.BDEDITCHAVE = RET.BDCHAVE), ';
  wSQL = :wSQL ||     'RET.BDISSRET    = (SELECT TMP.BDISSRET     FROM '||:wTableRet||' TMP WHERE TMP.BDSESSAO = '||:wSessaoOri||' AND TMP.BDCODEMP = RET.BDCODEMP AND TMP.BDEDITCHAVE = RET.BDCHAVE) ';
  wSQL = :wSQL || 'WHERE RET.BDCODEMP = '||:PRCODEMPORI||' ';
  wSQL = :wSQL || 'AND EXISTS (';
  wSQL = :wSQL ||             'SELECT * ';
  wSQL = :wSQL ||             'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL ||             'WHERE TNF.BDCODEMP = '||:PRCODEMPORI||' ';
  wSQL = :wSQL ||             'AND TNF.BDCODEMP = RET.BDCODEMP ';
  wSQL = :wSQL ||             'AND TNF.BDCHAVE  = RET.BDCHAVE ';
  wSQL = :wSQL ||            ') ';
  wSQL = :wSQL || 'AND NOT EXISTS(';
  wSQL = :wSQL ||                'SELECT * ';
  wSQL = :wSQL ||                'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL ||                'JOIN '||:wTableIncon||' INCO ON(INCO.BDSESSAO = '||:wSessaoDest||' AND INCO.BDCHAVE = TNF.BDCHAVE) ';
  wSQL = :wSQL ||                'WHERE TNF.BDCHAVE = RET.BDCHAVE ';
  wSQL = :wSQL ||               '); ';
  EXECUTE STATEMENT :wSQL;

  /*Atualiza a retenção de INSS que fica em outra tabela*/
  IF (:PRTIPOLAN = 'SER') THEN
    BEGIN
      UPDATE VEF_EMP_TMOVSERDED RET
      SET RET.BDVLRMATERIAIS       = (SELECT INSS.BDVLRMATERIAIS FROM TMP_VEF_EMP_TMOVSERDED_TEMP INSS WHERE INSS.BDSESSAO = :wSessaoOri AND INSS.BDCODEMP = RET.BDCODEMP AND INSS.BDEDITCHAVE = RET.BDCHAVE),
          RET.BDVLRSUBEMPREITEIRAS = (SELECT INSS.BDVLRSUBEMPREITEIRAS FROM TMP_VEF_EMP_TMOVSERDED_TEMP INSS WHERE INSS.BDSESSAO = :wSessaoOri AND INSS.BDCODEMP = RET.BDCODEMP AND INSS.BDEDITCHAVE = RET.BDCHAVE),
          RET.BDRETINSS            = (SELECT INSS.BDRETINSS FROM TMP_VEF_EMP_TMOVSERDED_TEMP INSS WHERE INSS.BDSESSAO = :wSessaoOri AND INSS.BDCODEMP = RET.BDCODEMP AND INSS.BDEDITCHAVE = RET.BDCHAVE)
      WHERE RET.BDCODEMP = :PRCODEMPORI
      AND EXISTS (
                  SELECT *
                  FROM TMP_VEF_EMP_TTRANSF_NF TNF
                  WHERE TNF.BDCODEMP = :PRCODEMPORI
                  AND TNF.BDCODEMP = RET.BDCODEMP
                  AND TNF.BDCHAVE  = RET.BDCHAVE
                 )
      AND NOT EXISTS(
                     SELECT *
                     FROM TMP_VEF_EMP_TTRANSF_NF TNF
                     JOIN VEF_INCON_TMOVSER INCO ON(INCO.BDSESSAO = :wSessaoDest AND INCO.BDCHAVE = TNF.BDCHAVE)
                     WHERE TNF.BDCHAVE = RET.BDCHAVE
                    );
    END

  /*Atualiza os valores de rateio na empresa origem*/
  wSQL =          'UPDATE '||:wTableRatFis||' RAT ';
  wSQL = :wSQL || 'SET RAT.BDVALOR = (';
  wSQL = :wSQL ||                    'SELECT TMP.BDVALOR ';
  wSQL = :wSQL ||                    'FROM '||:wTableRat||' TMP ';
  wSQL = :wSQL ||                    'WHERE TMP.BDSESSAO = '||:wSessaoOri||' ';
  wSQL = :wSQL ||                    'AND TMP.BDCODEMP = RAT.BDCODEMP ';
  wSQL = :wSQL ||                    'AND TMP.BDEDITCHAVE = RAT.BDCHAVE ';
  wSQL = :wSQL ||                    'AND TMP.BDORDEM = RAT.BDORDEM ';
  wSQL = :wSQL ||                    'AND TMP.BDORDEMRAT = RAT.BDORDEMRAT';
  wSQL = :wSQL ||                   ') ';
  wSQL = :wSQL || 'WHERE RAT.BDCODEMP = '||:PRCODEMPORI||' ';
  wSQL = :wSQL || 'AND EXISTS (';
  wSQL = :wSQL ||             'SELECT * ';
  wSQL = :wSQL ||             'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL ||             'WHERE TNF.BDCODEMP = '||:PRCODEMPORI||' ';
  wSQL = :wSQL ||             'AND TNF.BDCODEMP = RAT.BDCODEMP ';
  wSQL = :wSQL ||             'AND TNF.BDCHAVE  = RAT.BDCHAVE ';
  wSQL = :wSQL ||            ') ';
  wSQL = :wSQL || 'AND NOT EXISTS(';
  wSQL = :wSQL ||                'SELECT * ';
  wSQL = :wSQL ||                'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL ||                'JOIN '||:wTableIncon||' INCO ON(INCO.BDSESSAO = '||:wSessaoDest||' AND INCO.BDCHAVE = TNF.BDCHAVE) ';
  wSQL = :wSQL ||                'WHERE TNF.BDCHAVE = RAT.BDCHAVE ';
  wSQL = :wSQL ||               '); ';
  EXECUTE STATEMENT :wSQL;

  /*Atualiza os valores dos produtos na empresa origem*/
  wSQL =          'UPDATE '||:wTableMovProFis||' PRO ';
  wSQL = :wSQL || 'SET PRO.BDVL_ITEM = (';
  wSQL = :wSQL ||                      'SELECT TMP.BDVL_ITEM ';
  wSQL = :wSQL ||                      'FROM '||:wTableMovPro||' TMP ';
  wSQL = :wSQL ||                      'WHERE TMP.BDSESSAO = '||:wSessaoOri||' ';
  wSQL = :wSQL ||                      'AND TMP.BDCODEMP = PRO.BDCODEMP ';
  wSQL = :wSQL ||                      'AND TMP.BDEDITCHAVE = PRO.BDCHAVE ';
  wSQL = :wSQL ||                      'AND TMP.BDORDEM = PRO.BDORDEM ';
  wSQL = :wSQL ||                      'AND TMP.BDNUM_ITEM = PRO.BDNUM_ITEM';
  wSQL = :wSQL ||                     '), ';
  wSQL = :wSQL ||     'PRO.BDVL_BC_PIS = (';
  wSQL = :wSQL ||                        'SELECT TMP.BDVL_BC_PIS ';
  wSQL = :wSQL ||                        'FROM '||:wTableMovPro||' TMP ';
  wSQL = :wSQL ||                        'WHERE TMP.BDSESSAO = '||:wSessaoOri||' ';
  wSQL = :wSQL ||                        'AND TMP.BDCODEMP = PRO.BDCODEMP ';
  wSQL = :wSQL ||                        'AND TMP.BDEDITCHAVE = PRO.BDCHAVE ';
  wSQL = :wSQL ||                        'AND TMP.BDORDEM = PRO.BDORDEM ';
  wSQL = :wSQL ||                        'AND TMP.BDNUM_ITEM = PRO.BDNUM_ITEM';
  wSQL = :wSQL ||                       '), ';
  wSQL = :wSQL ||     'PRO.BDVL_BC_COFINS = (';
  wSQL = :wSQL ||                           'SELECT TMP.BDVL_BC_COFINS ';
  wSQL = :wSQL ||                           'FROM '||:wTableMovPro||' TMP ';
  wSQL = :wSQL ||                           'WHERE TMP.BDSESSAO = '||:wSessaoOri||' ';
  wSQL = :wSQL ||                           'AND TMP.BDCODEMP = PRO.BDCODEMP ';
  wSQL = :wSQL ||                           'AND TMP.BDEDITCHAVE = PRO.BDCHAVE ';
  wSQL = :wSQL ||                           'AND TMP.BDORDEM = PRO.BDORDEM ';
  wSQL = :wSQL ||                           'AND TMP.BDNUM_ITEM = PRO.BDNUM_ITEM';
  wSQL = :wSQL ||                          '), ';
  wSQL = :wSQL ||     'PRO.BDVL_PIS = (';
  wSQL = :wSQL ||                     'SELECT TMP.BDVL_PIS ';
  wSQL = :wSQL ||                     'FROM '||:wTableMovPro||' TMP ';
  wSQL = :wSQL ||                     'WHERE TMP.BDSESSAO = '||:wSessaoOri||' ';
  wSQL = :wSQL ||                     'AND TMP.BDCODEMP = PRO.BDCODEMP ';
  wSQL = :wSQL ||                     'AND TMP.BDEDITCHAVE = PRO.BDCHAVE ';
  wSQL = :wSQL ||                     'AND TMP.BDORDEM = PRO.BDORDEM ';
  wSQL = :wSQL ||                     'AND TMP.BDNUM_ITEM = PRO.BDNUM_ITEM';
  wSQL = :wSQL ||                    '), ';
  wSQL = :wSQL ||     'PRO.BDVL_COFINS = (';
  wSQL = :wSQL ||                        'SELECT TMP.BDVL_COFINS ';
  wSQL = :wSQL ||                        'FROM '||:wTableMovPro||' TMP ';
  wSQL = :wSQL ||                        'WHERE TMP.BDSESSAO = '||:wSessaoOri||' ';
  wSQL = :wSQL ||                        'AND TMP.BDCODEMP = PRO.BDCODEMP ';
  wSQL = :wSQL ||                        'AND TMP.BDEDITCHAVE = PRO.BDCHAVE ';
  wSQL = :wSQL ||                        'AND TMP.BDORDEM = PRO.BDORDEM ';
  wSQL = :wSQL ||                        'AND TMP.BDNUM_ITEM = PRO.BDNUM_ITEM';
  wSQL = :wSQL ||                       ') ';
  wSQL = :wSQL || 'WHERE PRO.BDCODEMP = '||:PRCODEMPORI||' ';
  wSQL = :wSQL || 'AND EXISTS (';
  wSQL = :wSQL ||             'SELECT * ';
  wSQL = :wSQL ||             'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL ||             'WHERE TNF.BDCODEMP = '||:PRCODEMPORI||' ';
  wSQL = :wSQL ||             'AND TNF.BDCODEMP = PRO.BDCODEMP ';
  wSQL = :wSQL ||             'AND TNF.BDCHAVE  = PRO.BDCHAVE ';
  wSQL = :wSQL ||            ') ';
  wSQL = :wSQL || 'AND NOT EXISTS(';
  wSQL = :wSQL ||                'SELECT * ';
  wSQL = :wSQL ||                'FROM TMP_VEF_EMP_TTRANSF_NF TNF ';
  wSQL = :wSQL ||                'JOIN '||:wTableIncon||' INCO ON(INCO.BDSESSAO = '||:wSessaoDest||' AND INCO.BDCHAVE = TNF.BDCHAVE) ';
  wSQL = :wSQL ||                'WHERE TNF.BDCHAVE = PRO.BDCHAVE ';
  wSQL = :wSQL ||               '); ';
  EXECUTE STATEMENT :wSQL;

  /*Altera os registros nas tol's (empresa de origem)*/
  EXECUTE PROCEDURE SP_TRANSFERENCIA_TOL(:PRID_TERMINAL, :PRTIPOLAN, 'UPT');

  DELETE FROM TMP_VEF_EMP_TTRANSF_NF WHERE BDCODEMP IS NOT NULL;
  DELETE FROM TMP_TTRANSFERENCIA_FKS WHERE BDCODEMP IS NOT NULL;
  DELETE FROM TMP_TCHAVE_TRANSFERENCIA WHERE BDTABLE IS NOT NULL;
  DELETE FROM TMP_VEF_EMP_TMOVSER_TEMP WHERE BDSESSAO IN (:wSessaoOri, :wSessaoDest);

  WHEN ANY DO
    BEGIN
      IN AUTONOMOUS TRANSACTION DO
        EXECUTE PROCEDURE LANCA_EXCEPTION('SP_TRANSFERENCIA_LAN', SQLCODE, GDSCODE);
      EXCEPTION;
    END
END^

CREATE OR ALTER TRIGGER TRG_NEW_EDTICHAVE FOR TMP_VEF_EMP_TMOVSER_TEMP
ACTIVE BEFORE UPDATE POSITION 0
AS
DECLARE VARIABLE wChave INTEGER;
BEGIN
  IF (OLD.BDEDITCHAVE IS NULL) THEN
    BEGIN
      wChave = GETORDEMSEQUENCIAL(1);
      NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - :wChave)+1;
    END
END^

CREATE OR ALTER PROCEDURE SP_COPIAR_LANCAMENTO (
    PRSESSAO INTEGER,
    PRCODUSU INTEGER,
    PRCODEMPORI INTEGER,
    PRCODEMPDEST INTEGER,
    PRTIPOLAN CHAR(3),
    PRISEMPORIGEM DM_BOOLEAN)
AS
DECLARE VARIABLE WTABLE VARCHAR(31);
DECLARE VARIABLE WTABLETMP VARCHAR(31);
DECLARE VARIABLE WTABLEITEM VARCHAR(31);
DECLARE VARIABLE WTABLEITEMTMP VARCHAR(31);
DECLARE VARIABLE WTABLERET VARCHAR(31);
DECLARE VARIABLE WTABLERETTMP VARCHAR(31);
DECLARE VARIABLE WTABLEPAR VARCHAR(31);
DECLARE VARIABLE WTABLEPARTMP VARCHAR(31);
DECLARE VARIABLE WTABLERATTMP VARCHAR(31);
DECLARE VARIABLE WTABLEMOVPROTMP VARCHAR(31);
DECLARE VARIABLE WTABLEMOVPRO VARCHAR(31);
DECLARE VARIABLE WTABLERAT VARCHAR(31);
DECLARE VARIABLE WCABECALHO VARCHAR(1000);
DECLARE VARIABLE WSELECT VARCHAR(5000);
DECLARE VARIABLE WFIELDS VARCHAR(2000);
DECLARE VARIABLE WRATEIARETENCOES VARCHAR(500);
DECLARE VARIABLE WTABLEDED VARCHAR(31);
BEGIN
  PRISEMPORIGEM = UPPER(:PRISEMPORIGEM);

  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTable        = 'VEF_EMP_TMOVENT';
      wTableTMP     = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItem    = 'VEF_EMP_TMOVENTITENS';
      wTableItemTMP = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      wTableRet     = 'VEF_EMP_TMOVENTRET';
      wTableRetTMP  = 'TMP_VEF_EMP_TMOVENTRET_TEMP'; 
      wTableDed     = 'VEF_EMP_TMOVENTDED';
      wTablePar     = 'VEF_EMP_TMOVENTPAR';
      wTableParTMP  = 'TMP_VEF_EMP_TMOVENTPAR_TEMP';
      wTableRat     = 'VEF_EMP_TMOVRATENT';
      wTableRatTMP  = 'TMP_VEF_EMP_TMOVRATENT_TEMP';
      wTableMovPro  = 'VEF_EMP_TMOVPROENT';
      wTableMovProTMP= 'TMP_VEF_EMP_TMOVPROENT_TEMP';
    END
  ELSE
  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTable        = 'VEF_EMP_TMOVENT';
      wTableTMP     = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItem    = 'VEF_EMP_TMOVENTITENS';
      wTableItemTMP = 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      wTableRet     = 'VEF_EMP_TMOVSAIRET';
      wTableRetTMP  = 'TMP_VEF_EMP_TMOVSAIRET_TEMP'; 
      wTableDed     = 'VEF_EMP_TMOVSAIDED';
      wTablePar     = 'VEF_EMP_TMOVSAIPAR';
      wTableParTMP  = 'TMP_VEF_EMP_TMOVSAIPAR_TEMP';
      wTableRat     = 'VEF_EMP_TMOVRATSAI';
      wTableRatTMP  = 'TMP_VEF_EMP_TMOVRATSAI_TEMP';
      wTableMovPro  = 'VEF_EMP_TMOVPROSAI';
      wTableMovProTMP= 'TMP_VEF_EMP_TMOVPROSAI_TEMP';
    END
  ELSE
  IF (:PRTIPOLAN = 'SER') THEN
    BEGIN
      wTable        = 'VEF_EMP_TMOVSER';
      wTableTMP     = 'TMP_VEF_EMP_TMOVSER_TEMP';
      wTableItem    = 'VEF_EMP_TMOVSERITENS';
      wTableItemTMP = 'TMP_VEF_EMP_TMOVSERITENS_TEMP';
      wTableRet     = 'VEF_EMP_TMOVSERRET';
      wTableRetTMP  = 'TMP_VEF_EMP_TMOVSERRET_TEMP'; 
      wTableDed     = 'VEF_EMP_TMOVSERDED';
      wTablePar     = 'VEF_EMP_TMOVSERPAR';
      wTableParTMP  = 'TMP_VEF_EMP_TMOVSERPAR_TEMP';
      wTableRat     = 'VEF_EMP_TMOVRATSER';
      wTableRatTMP  = 'TMP_VEF_EMP_TMOVRATSER_TEMP';
      wTableMovPro  = 'VEF_EMP_TA170';
      wTableMovProTMP= 'TMP_VEF_EMP_TA170_TEMP';
    END

  /***************************************************************************************************************************/
  /************************************************* CABEÇALHO DO LANÇAMENTO *************************************************/
  /***************************************************************************************************************************/

  EXECUTE STATEMENT 'DELETE FROM ' || :wTableTMP || ' WHERE BDSESSAO = ' || :PRSESSAO;

  SELECT 'BDSESSAO, BDCODEMP, BDCODEMP_OLD, BDCODTIPO, BDCODUSU, BDDATALAN, BDHORALAN, BDDATAINCLUSAO, BDHORAINCLUSAO, BDNOMETER, BDCNPJ, BDEDITCHAVE, ' || LIST(TRIM(RDB$FIELD_NAME), ', ') FROM RDB$RELATION_FIELDS
  WHERE RDB$RELATION_NAME = :wTable
  AND RDB$FIELD_NAME <> 'BDCODEMP'
  AND RDB$FIELD_NAME <> 'BDCODTIPO'
  AND RDB$FIELD_NAME <> 'BDCODUSU'
  AND RDB$FIELD_NAME <> 'BDDATALAN'
  AND RDB$FIELD_NAME <> 'BDHORALAN'
  AND RDB$FIELD_NAME <> 'BDDATAINCLUSAO'
  AND RDB$FIELD_NAME <> 'BDHORAINCLUSAO'
  INTO :wFields;

  wCabecalho = 'INSERT INTO '||:wTableTMP||'(' || :wFields || ') ';
  SELECT 'MOV.BDSESSAO, MOV.BDCODEMP, MOV.BDCODEMP_OLD, MOV.BDCODTIPO, MOV.BDCODUSU, MOV.BDDATALAN, MOV.BDHORALAN, MOV.BDDATAINCLUSAO, MOV.BDHORAINCLUSAO, MOV.BDNOMETER, MOV.BDCNPJ, BDEDITCHAVE, ' || LIST('MOV.'||TRIM(RDB$FIELD_NAME), ', ') FROM RDB$RELATION_FIELDS
  WHERE RDB$RELATION_NAME = :wTable
  AND RDB$FIELD_NAME <> 'BDCODEMP'
  AND RDB$FIELD_NAME <> 'BDCODTIPO'
  AND RDB$FIELD_NAME <> 'BDCODUSU'
  AND RDB$FIELD_NAME <> 'BDDATALAN'
  AND RDB$FIELD_NAME <> 'BDHORALAN'
  AND RDB$FIELD_NAME <> 'BDDATAINCLUSAO'
  AND RDB$FIELD_NAME <> 'BDHORAINCLUSAO'
  INTO :wFields;

  wSelect = ' SELECT ' || :wFields || ' FROM ' || :wTable || ' MOV ';
  wSelect = REPLACE(:wSelect, 'MOV.BDSESSAO', :PRSESSAO);
  wSelect = REPLACE(:wSelect, 'MOV.BDCODEMP_OLD, '  , :PRCODEMPORI||', ');

  wSelect = :wSelect || 'JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = MOV.BDCODTER) ';


    wSelect = REPLACE(:wSelect, 'MOV.BDNOMETER, ', 'TER.BDNOME, ');
    wSelect = REPLACE(:wSelect, 'MOV.BDCNPJ, ', 'TER.BDCGCTER, ');

  IF (:PRISEMPORIGEM = 'TRUE') THEN
    BEGIN
      wSelect = REPLACE(:wSelect, 'MOV.BDCODEMP, ', :PRCODEMPORI||', ');
      wSelect = REPLACE(:wSelect, 'BDEDITCHAVE, ' , 'MOV.BDCHAVE, ');
    END
  ELSE
    BEGIN
      wSelect = REPLACE(:wSelect, 'MOV.BDCODEMP, '      , :PRCODEMPDEST||', ');
      wSelect = REPLACE(:wSelect, 'MOV.BDCODTIPO, '     , 139||', ');
      wSelect = REPLACE(:wSelect, 'MOV.BDCODUSU, '      , :PRCODUSU||', ');
      wSelect = REPLACE(:wSelect, 'MOV.BDDATALAN, '     , 'CAST(''NOW'' AS DATE), ');
      wSelect = REPLACE(:wSelect, 'MOV.BDHORALAN, '     , 'CAST(''NOW'' AS TIME), ');
      wSelect = REPLACE(:wSelect, 'MOV.BDDATAINCLUSAO, ', 'CAST(''NOW'' AS DATE), ');
      wSelect = REPLACE(:wSelect, 'MOV.BDHORAINCLUSAO, ', 'CAST(''NOW'' AS TIME), ');
      wSelect = REPLACE(:wSelect, 'BDEDITCHAVE, ' , 'NULL, ');
    END

  wSelect = :wSelect || ' WHERE MOV.BDCODEMP = ' || :PRCODEMPORI;
  wSelect = :wSelect || ' AND EXISTS (';
  wSelect = :wSelect ||              'SELECT T.BDCHAVE ';
  wSelect = :wSelect ||              'FROM TMP_VEF_EMP_TTRANSF_NF T ';
  IF (:PRISEMPORIGEM = 'TRUE') THEN
    wSelect = :wSelect ||              'WHERE T.BDCODEMP = '||:PRCODEMPORI||' ';
  ELSE
    wSelect = :wSelect ||              'WHERE T.BDCODEMP = '||:PRCODEMPDEST||' ';
  wSelect = :wSelect ||              'AND T.BDCHAVE = MOV.BDCHAVE ';
  wSelect = :wSelect ||             ')';

  EXECUTE STATEMENT (:wCabecalho || :wSelect);

  /***************************************************************************************************************************/
  /*************************************************** ITEM DO LANÇAMENTO ****************************************************/
  /***************************************************************************************************************************/

  wFields    = NULL;
  wCabecalho = NULL;
  wSelect    = NULL;

  EXECUTE STATEMENT 'DELETE FROM ' || :wTableItemTMP || ' WHERE BDSESSAO = ' || :PRSESSAO;

  SELECT 'BDSESSAO, BDCODEMP, BDCHAVE_OLD, BDCHAVE, BDORDEM, BDVLRCONTAB, ' || LIST(TRIM(RDB$FIELD_NAME), ', ') FROM RDB$RELATION_FIELDS
  WHERE RDB$RELATION_NAME = :wTableItem
  AND RDB$FIELD_NAME <> 'BDCODEMP'
  AND RDB$FIELD_NAME <> 'BDCHAVE'
  AND RDB$FIELD_NAME <> 'BDORDEM'
  AND RDB$FIELD_NAME <> 'BDVLRCONTAB'
  AND RDB$FIELD_NAME <> 'BDCODSCP'
  AND RDB$FIELD_NAME <> 'BDREFSOC'  
  INTO :wFields;

  wCabecalho = 'INSERT INTO '||:wTableItemTMP||'(' || :wFields || ') ';

  SELECT 'BDSESSAO, BDCODEMP, BDCHAVE_OLD, BDCHAVE, BDORDEM, BDVLRCONTAB, ' || LIST(TRIM(IIF(POSITION('BDCODREC', RF.RDB$FIELD_NAME) > 0, 'COALESCE('||TRIM(RF.RDB$FIELD_NAME)||', 0)', TRIM(RF.RDB$FIELD_NAME))), ', ')
  FROM RDB$RELATION_FIELDS RF
  JOIN RDB$FIELDS F ON(F.RDB$FIELD_NAME = RF.RDB$FIELD_SOURCE)
  WHERE RF.RDB$RELATION_NAME = :wTableItem
  AND RF.RDB$FIELD_NAME <> 'BDCODEMP'
  AND RF.RDB$FIELD_NAME <> 'BDCHAVE'
  AND RF.RDB$FIELD_NAME <> 'BDORDEM'
  AND RF.RDB$FIELD_NAME <> 'BDVLRCONTAB'
  AND RF.RDB$FIELD_NAME <> 'BDCODSCP'
  AND RF.RDB$FIELD_NAME <> 'BDREFSOC'  
  INTO :wFields;

  wSelect = ' SELECT ' || :wFields || ' FROM ' || :wTableItem || ' I ';
  wSelect = REPLACE(:wSelect, 'BDSESSAO, '   , :PRSESSAO||', ');
  wSelect = REPLACE(:wSelect, 'BDCHAVE_OLD, ', 'BDCHAVE, ');
  wSelect = REPLACE(:wSelect, 'BDCHAVE, '    , 'I.BDCHAVE, ');
  wSelect = REPLACE(:wSelect, 'BDORDEM, '    , 'I.BDORDEM, ');

  IF (:PRISEMPORIGEM = 'TRUE') THEN
    BEGIN
      wSelect = REPLACE(:wSelect, 'BDCODEMP, '   , :PRCODEMPORI||', ');
      wSelect = REPLACE(:wSelect, 'BDVLRCONTAB, ', 'T.BDVLRNOTA, ');

      wSelect = :wSelect || 'JOIN TMP_VEF_EMP_TTRANSF_NF T ON(T.BDCODEMP = '||:PRCODEMPORI||' AND T.BDCHAVE = I.BDCHAVE AND T.BDORDEM = I.BDORDEM) ';
    END
  ELSE
    BEGIN
      wSelect = REPLACE(:wSelect, 'BDCODEMP'   , :PRCODEMPDEST);
      wSelect = REPLACE(:wSelect, 'BDVLRCONTAB', 'IIF(T.BDTIPO = 0, T.BDVLRNOTA, (COALESCE(I.BDVLRCONTAB, 0) - COALESCE(T.BDVLRNOTA, 0)))');

      wSelect = :wSelect || 'JOIN TMP_VEF_EMP_TTRANSF_NF T ON(T.BDCODEMP = '||:PRCODEMPDEST||' AND T.BDCHAVE = I.BDCHAVE AND T.BDORDEM = I.BDORDEM) ';
    END

  wSelect = :wSelect || ' WHERE I.BDCODEMP = ' || :PRCODEMPORI;

  EXECUTE STATEMENT (:wCabecalho || :wSelect);

  /***************************************************************************************************************************/
  /************************************************** RATEIO DO LANÇAMENTO ***************************************************/
  /***************************************************************************************************************************/
  wFields    = NULL;
  wCabecalho = NULL;
  wSelect    = NULL;

  EXECUTE STATEMENT 'DELETE FROM ' || :wTableRatTMP || ' WHERE BDSESSAO = ' || :PRSESSAO;

  SELECT 'BDSESSAO, BDCODEMP, BDCHAVE, BDORDEM, ' || LIST(TRIM(RDB$FIELD_NAME), ', ') FROM RDB$RELATION_FIELDS
  WHERE RDB$RELATION_NAME = :wTableRat
  AND RDB$FIELD_NAME <> 'BDCODEMP'
  AND RDB$FIELD_NAME <> 'BDCHAVE'
  AND RDB$FIELD_NAME <> 'BDORDEM'
  INTO :wFields;

  wCabecalho = 'INSERT INTO '||:wTableRatTMP||'(' || :wFields || ') ';

  wSelect = ' SELECT ' || :wFields || ' FROM ' || :wTableRat || ' I ';
  wSelect = REPLACE(:wSelect, 'BDSESSAO, '   , :PRSESSAO||', ');
  wSelect = REPLACE(:wSelect, 'BDCHAVE, '    , 'I.BDCHAVE, ');
  wSelect = REPLACE(:wSelect, 'BDORDEM, '    , 'I.BDORDEM, ');

  IF (:PRISEMPORIGEM = 'TRUE') THEN
    BEGIN
      wSelect = REPLACE(:wSelect, 'BDCODEMP, ', :PRCODEMPORI||', ');
      wSelect = :wSelect || 'JOIN TMP_VEF_EMP_TTRANSF_NF T ON(T.BDCODEMP = '||:PRCODEMPORI||' AND T.BDCHAVE = I.BDCHAVE AND T.BDORDEM = I.BDORDEM) ';
    END
  ELSE
    BEGIN
      wSelect = REPLACE(:wSelect, 'BDCODEMP, ', :PRCODEMPDEST||', ');
      wSelect = :wSelect || 'JOIN TMP_VEF_EMP_TTRANSF_NF T ON(T.BDCODEMP = '||:PRCODEMPDEST||' AND T.BDCHAVE = I.BDCHAVE AND T.BDORDEM = I.BDORDEM) ';
    END

  wSelect = :wSelect || ' WHERE I.BDCODEMP = ' || :PRCODEMPORI;
  wSelect = :wSelect || ' AND EXISTS (';
  wSelect = :wSelect ||              'SELECT T.BDCHAVE ';
  wSelect = :wSelect ||              'FROM TMP_VEF_EMP_TTRANSF_NF T ';
  IF (:PRISEMPORIGEM = 'TRUE') THEN
    wSelect = :wSelect ||              'WHERE T.BDCODEMP = '||:PRCODEMPORI||' ';
  ELSE
    wSelect = :wSelect ||              'WHERE T.BDCODEMP = '||:PRCODEMPDEST||' ';
  wSelect = :wSelect ||              'AND T.BDCHAVE = I.BDCHAVE ';
  wSelect = :wSelect ||             ')';

  EXECUTE STATEMENT (:wCabecalho || :wSelect);

  /***************************************************************************************************************************/
  /************************************************* RETENÇÃO DO LANÇAMENTO **************************************************/
  /***************************************************************************************************************************/

  wFields    = NULL;
  wCabecalho = NULL;
  wSelect    = NULL;

  EXECUTE STATEMENT 'DELETE FROM ' || :wTableRetTMP || ' WHERE BDSESSAO = ' || :PRSESSAO;

  SELECT 'BDSESSAO, BDCODEMP, ' || LIST(TRIM(RF.RDB$FIELD_NAME), ', ')
  FROM RDB$RELATION_FIELDS RF
  WHERE RF.RDB$RELATION_NAME = :wTableRet
  AND RF.RDB$FIELD_NAME <> 'BDCODEMP'
  INTO :wFields;

  wCabecalho = 'INSERT INTO '||:wTableRetTMP||'(' || :wFields || ') ';

  SELECT 'BDSESSAO, BDCODEMP, ' || LIST(IIF(((F.RDB$FIELD_TYPE IN(16)) OR (POSITION('BDCODREC', RF.RDB$FIELD_NAME) > 0)), 'COALESCE('||TRIM(RF.RDB$FIELD_NAME)||', 0)', TRIM(RF.RDB$FIELD_NAME)), ', ')
  FROM RDB$RELATION_FIELDS RF
  JOIN RDB$FIELDS F ON(F.RDB$FIELD_NAME = RF.RDB$FIELD_SOURCE)
  WHERE RF.RDB$RELATION_NAME = :wTableRet
  AND RF.RDB$FIELD_NAME <> 'BDCODEMP'
  INTO :wFields;

  wSelect = ' SELECT ' || :wFields || ' FROM ' || :wTableRet || ' RET ';
  wSelect = REPLACE(:wSelect, 'BDSESSAO, ', :PRSESSAO||', ');

  IF (:PRISEMPORIGEM = 'TRUE') THEN
    BEGIN
      wSelect = REPLACE(:wSelect, 'BDCODEMP, ', :PRCODEMPORI||', ');
    END
  ELSE
    BEGIN
      wSelect = REPLACE(:wSelect, 'BDCODEMP, ', :PRCODEMPDEST||', ');
    END

  wSelect = :wSelect || ' WHERE RET.BDCODEMP = ' || :PRCODEMPORI;
  wSelect = :wSelect || ' AND EXISTS (';
  wSelect = :wSelect ||              'SELECT T.BDCHAVE ';
  wSelect = :wSelect ||              'FROM TMP_VEF_EMP_TTRANSF_NF T ';
  IF (:PRISEMPORIGEM = 'TRUE') THEN
    wSelect = :wSelect ||              'WHERE T.BDCODEMP = '||:PRCODEMPORI||' ';
  ELSE
    wSelect = :wSelect ||              'WHERE T.BDCODEMP = '||:PRCODEMPDEST||' ';
  wSelect = :wSelect ||              'AND T.BDCHAVE = RET.BDCHAVE ';
  wSelect = :wSelect ||             ')';

  EXECUTE STATEMENT (:wCabecalho || :wSelect);

  /*No serviço a retenção de INSS fica em outra tabela*/
  IF (:PRTIPOLAN = 'SER') THEN
    BEGIN
      wFields    = NULL;
      wCabecalho = NULL;
      wSelect    = NULL;

      EXECUTE STATEMENT 'DELETE FROM TMP_VEF_EMP_TMOVSERDED_TEMP WHERE BDSESSAO = ' || :PRSESSAO;

      SELECT 'BDSESSAO, BDCODEMP, ' || LIST(TRIM(RF.RDB$FIELD_NAME), ', ')
      FROM RDB$RELATION_FIELDS RF
      WHERE RF.RDB$RELATION_NAME = 'VEF_EMP_TMOVSERDED'
      AND RF.RDB$FIELD_NAME <> 'BDCODEMP'
      INTO :wFields;

      wCabecalho = 'INSERT INTO TMP_VEF_EMP_TMOVSERDED_TEMP(' || :wFields || ') ';

      SELECT 'BDSESSAO, BDCODEMP, ' || LIST(IIF(((F.RDB$FIELD_TYPE IN(16)) OR (POSITION('BDCODREC', RF.RDB$FIELD_NAME) > 0)), 'COALESCE('||TRIM(RF.RDB$FIELD_NAME)||', 0)', TRIM(RF.RDB$FIELD_NAME)), ', ')
      FROM RDB$RELATION_FIELDS RF
      JOIN RDB$FIELDS F ON(F.RDB$FIELD_NAME = RF.RDB$FIELD_SOURCE)
      WHERE RF.RDB$RELATION_NAME = 'VEF_EMP_TMOVSERDED'
      AND RF.RDB$FIELD_NAME <> 'BDCODEMP'
      INTO :wFields;

      wSelect = ' SELECT ' || :wFields || ' FROM VEF_EMP_TMOVSERDED DED ';
      wSelect = REPLACE(:wSelect, 'BDSESSAO, ', :PRSESSAO||', ');

      IF (:PRISEMPORIGEM = 'TRUE') THEN
        BEGIN
          wSelect = REPLACE(:wSelect, 'BDCODEMP, ', :PRCODEMPORI||', ');
        END
      ELSE
        BEGIN
          wSelect = REPLACE(:wSelect, 'BDCODEMP, ', :PRCODEMPDEST||', ');
        END
    
      wSelect = :wSelect || ' WHERE DED.BDCODEMP = ' || :PRCODEMPORI;
      wSelect = :wSelect || ' AND EXISTS (';
      wSelect = :wSelect ||              'SELECT T.BDCHAVE ';
      wSelect = :wSelect ||              'FROM TMP_VEF_EMP_TTRANSF_NF T ';
      IF (:PRISEMPORIGEM = 'TRUE') THEN
        wSelect = :wSelect ||              'WHERE T.BDCODEMP = '||:PRCODEMPORI||' ';
      ELSE
        wSelect = :wSelect ||              'WHERE T.BDCODEMP = '||:PRCODEMPDEST||' ';
      wSelect = :wSelect ||              'AND T.BDCHAVE = DED.BDCHAVE ';
      wSelect = :wSelect ||             ')';
    
      EXECUTE STATEMENT (:wCabecalho || :wSelect);
    END

  /***************************************************************************************************************************/
  /************************************************* PARCELAS DO LANÇAMENTO **************************************************/
  /***************************************************************************************************************************/
  wFields    = NULL;
  wCabecalho = NULL;
  wSelect    = NULL;

  EXECUTE STATEMENT 'DELETE FROM ' || :wTableParTMP || ' WHERE BDSESSAO = ' || :PRSESSAO;

  SELECT 'BDSESSAO, BDCODEMP, ' || LIST(TRIM(RF.RDB$FIELD_NAME), ', ')
  FROM RDB$RELATION_FIELDS RF
  WHERE RF.RDB$RELATION_NAME = :wTablePar
  AND RF.RDB$FIELD_NAME <> 'BDCODEMP'
  INTO :wFields;

  wCabecalho = 'INSERT INTO '||:wTableParTMP||'(' || :wFields || ') ';

  wSelect = ' SELECT ' || :wFields || ' FROM ' || :wTablePar || ' RET ';
  wSelect = REPLACE(:wSelect, 'BDSESSAO, ', :PRSESSAO||', ');

  IF (:PRISEMPORIGEM = 'TRUE') THEN
    BEGIN
      wSelect = REPLACE(:wSelect, 'BDCODEMP, ', :PRCODEMPORI||', ');
    END
  ELSE
    BEGIN
      wSelect = REPLACE(:wSelect, 'BDCODEMP, ', :PRCODEMPDEST||', ');
    END

  wSelect = :wSelect || ' WHERE RET.BDCODEMP = ' || :PRCODEMPORI;
  wSelect = :wSelect || ' AND EXISTS (';
  wSelect = :wSelect ||              'SELECT T.BDCHAVE ';
  wSelect = :wSelect ||              'FROM TMP_VEF_EMP_TTRANSF_NF T ';
  IF (:PRISEMPORIGEM = 'TRUE') THEN
    wSelect = :wSelect ||              'WHERE T.BDCODEMP = '||:PRCODEMPORI||' ';
  ELSE
    wSelect = :wSelect ||              'WHERE T.BDCODEMP = '||:PRCODEMPDEST||' ';
  wSelect = :wSelect ||              'AND T.BDCHAVE = RET.BDCHAVE ';
  wSelect = :wSelect ||             ')';

  EXECUTE STATEMENT (:wCabecalho || :wSelect);

  /***************************************************************************************************************************/
  /************************************************* PRODUTOS DO LANÇAMENTO **************************************************/
  /***************************************************************************************************************************/
  wFields    = NULL;
  wCabecalho = NULL;
  wSelect    = NULL;

  EXECUTE STATEMENT 'DELETE FROM ' || :wTableMovProTMP || ' WHERE BDSESSAO = ' || :PRSESSAO;

  SELECT 'BDSESSAO, BDCODEMP, ' || LIST(TRIM(RF.RDB$FIELD_NAME), ', ')
  FROM RDB$RELATION_FIELDS RF
  WHERE RF.RDB$RELATION_NAME = :wTableMovPro
  AND RF.RDB$FIELD_NAME <> 'BDCODEMP'
  INTO :wFields;

  wCabecalho = 'INSERT INTO '||:wTableMovProTMP||'(' || :wFields || ') ';

  wSelect = ' SELECT ' || :wFields || ' FROM ' || :wTableMovPro || ' RET ';
  wSelect = REPLACE(:wSelect, 'BDSESSAO, ', :PRSESSAO||', ');

  IF (:PRISEMPORIGEM = 'TRUE') THEN
    BEGIN
      wSelect = REPLACE(:wSelect, 'BDCODEMP, ', :PRCODEMPORI||', ');
    END
  ELSE
    BEGIN
      wSelect = REPLACE(:wSelect, 'BDCODEMP, ', :PRCODEMPDEST||', ');
    END

  wSelect = :wSelect || ' WHERE RET.BDCODEMP = ' || :PRCODEMPORI;
  wSelect = :wSelect || ' AND EXISTS (';
  wSelect = :wSelect ||              'SELECT T.BDCHAVE ';
  wSelect = :wSelect ||              'FROM TMP_VEF_EMP_TTRANSF_NF T ';
  IF (:PRISEMPORIGEM = 'TRUE') THEN
    wSelect = :wSelect ||              'WHERE T.BDCODEMP = '||:PRCODEMPORI||' ';
  ELSE
    wSelect = :wSelect ||              'WHERE T.BDCODEMP = '||:PRCODEMPDEST||' ';
  wSelect = :wSelect ||              'AND T.BDCHAVE = RET.BDCHAVE ';
  wSelect = :wSelect ||             ')';

  EXECUTE STATEMENT (:wCabecalho || :wSelect);

  WHEN ANY DO
    BEGIN
      IN AUTONOMOUS TRANSACTION DO
        EXECUTE PROCEDURE LANCA_EXCEPTION('SP_COPIAR_LANCAMENTO', SQLCODE, GDSCODE);
      EXCEPTION;
    END
END^

CREATE OR ALTER PROCEDURE SP_GET_ORDEMINFCOM (
    PRCODEMP INTEGER NOT NULL,
    PRHASH BIGINT NOT NULL)
RETURNS (
    BDORDEMINFCOM INTEGER)
AS
BEGIN

  SELECT FIRST 1 INF.BDORDEMINFCOM
  FROM VEF_BASE_TCADINFCOM INF
  WHERE INF.BDCODEMP = :PRCODEMP
  AND INF.BDDESCINFCOMHASH = :PRHASH
  INTO :BDORDEMINFCOM;

  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_TRANSFERENCIA_GET_CHAVES_REL (
    PRID_TERMINAL INTEGER,
    PRTIPOLAN CHAR(3))
AS
DECLARE VARIABLE WTABLE VARCHAR(31);
DECLARE VARIABLE WTABLETMP VARCHAR(31);
DECLARE VARIABLE WTABLEITEMTMP VARCHAR(31);
DECLARE VARIABLE WTABLEMOVPROD VARCHAR(31);
DECLARE VARIABLE WTABLEINCON VARCHAR(31);
DECLARE VARIABLE WSQL VARCHAR(1000);
DECLARE VARIABLE WSESSAODEST INTEGER;
BEGIN
  SELECT S.BDSESSAO
  FROM TMP_TSESSAO_IMP S
  WHERE S.BDID_TERMINAL = :PRID_TERMINAL
  AND S.BDTABLE = 'DESTINO'
  INTO :wSessaoDest;

  IF (:PRTIPOLAN = 'SER') THEN
    BEGIN
      wTable       = 'VEF_EMP_TMOVSER';
      wTableTMP    = 'TMP_VEF_EMP_TMOVSER_TEMP';
      wTableItemTMP= 'TMP_VEF_EMP_TMOVSERITENS_TEMP';
      wTableMovProd= 'VEF_EMP_TA170';
      wTableIncon  = 'VEF_INCON_TMOVSER';
    END
  ELSE
  IF (:PRTIPOLAN = 'ENT') THEN
    BEGIN
      wTable       = 'VEF_EMP_TMOVENT';
      wTableTMP    = 'TMP_VEF_EMP_TMOVENT_TEMP';
      wTableItemTMP= 'TMP_VEF_EMP_TMOVENTITENS_TEMP';
      wTableMovProd= 'VEF_EMP_TMOVPROENT';
      wTableIncon  = 'VEF_INCON_TMOVENT';
    END
  ELSE
  IF (:PRTIPOLAN = 'SAI') THEN
    BEGIN
      wTable       = 'VEF_EMP_TMOVSAI';
      wTableTMP    = 'TMP_VEF_EMP_TMOVSAI_TEMP';
      wTableItemTMP= 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
      wTableMovProd= 'VEF_EMP_TMOVPROSAI';
      wTableIncon  = 'VEF_INCON_TMOVSAI';
    END


  DELETE FROM TMP_TTRANSFERENCIA_FKS;

  /*Produto correspondente na empresa destino*/
  wSQL =          'INSERT INTO TMP_TTRANSFERENCIA_FKS(BDCODEMP, BDCHAVE, BDORDEM, '||IIF(:PRTIPOLAN = 'SER', 'BDNUM_ITEM', 'BDORDEMPRO')||', BDCODPROD, BDTABLE)';
  wSQL = :wSQL || 'SELECT M.BDCODEMP_OLD, M.BDCHAVE, I.BDORDEM, '||IIF(:PRTIPOLAN = 'SER', 'A.BDNUM_ITEM', 'A.BDORDEMPRO')||' BDORDEMPRO, PRO_D.BDCODPROD, '''||:wTableMovProd||'''';
  wSQL = :wSQL || 'FROM (';
  wSQL = :wSQL ||      ' SELECT I.BDSESSAO, I.BDCODEMP, I.BDCHAVE, I.BDORDEM ';
  wSQL = :wSQL ||      ' FROM '||:wTableItemTMP||' I ';
  wSQL = :wSQL ||      ' LEFT OUTER JOIN '||:wTableIncon|| ' INCO ON(INCO.BDSESSAO = I.BDSESSAO AND INCO.BDCODEMP = I.BDCODEMP AND INCO.BDCHAVE = I.BDCHAVE)';
  wSQL = :wSQL ||      ' WHERE I.BDSESSAO = '||:wSessaoDest;
  wSQL = :wSQL ||      ' AND INCO.BDCODINCONSISTENCIA IS NULL ';
  wSQL = :wSQL ||      ') I ';
  wSQL = :wSQL || 'JOIN '||:wTableTMP||' M ON(M.BDSESSAO = I.BDSESSAO AND M.BDCODEMP = I.BDCODEMP AND M.BDCHAVE = I.BDCHAVE) ';
  wSQL = :wSQL || 'JOIN '||:wTableMovProd||' A ON(A.BDCODEMP = M.BDCODEMP_OLD AND A.BDCHAVE = I.BDCHAVE AND A.BDORDEM = I.BDORDEM AND A.BDCODPROD IS NOT NULL) ';
  wSQL = :wSQL || 'JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = M.BDCODEMP_OLD AND PRO.BDCODPROD = A.BDCODPROD) ';
  wSQL = :wSQL || 'JOIN TCADPRO_VINC PRO_D ON(PRO_D.BDCODEMP = I.BDCODEMP AND PRO_D.BDDESCPROD = PRO.BDDESCPROD); ';
  EXECUTE STATEMENT :wSQL;

  IF (:PRTIPOLAN = 'SER') THEN
    BEGIN
      /*Empreendimento correspondente na empresa destino*/
      wSQL =          'INSERT INTO TMP_TTRANSFERENCIA_FKS(BDCODEMP, BDCHAVE, BDCODEMPREENDIMENTO, BDTABLE)';
      wSQL = :wSQL || 'SELECT MOV.BDCODEMP_OLD, MOV.BDCHAVE, EMP_D.BDCODEMPREENDIMENTO, '''||:wTable||'''';
      wSQL = :wSQL || 'FROM ( ';
      wSQL = :wSQL || '      SELECT M.BDSESSAO, M.BDCODEMP, M.BDCHAVE, M.BDCODEMPREENDIMENTO, M.BDCODEMP_OLD ';
      wSQL = :wSQL || '      FROM '||:wTableTMP||' M ';
      wSQL = :wSQL || '      WHERE M.BDSESSAO = '||:wSessaoDest||' ';
      wSQL = :wSQL || '      AND M.BDCODEMPREENDIMENTO IS NOT NULL ';
      wSQL = :wSQL || '     ) MOV ';
      wSQL = :wSQL || 'JOIN VEF_EMP_TCADEMPREENDIMENTO EMP ON(EMP.BDCODEMP = MOV.BDCODEMP_OLD AND EMP.BDCODEMPREENDIMENTO = MOV.BDCODEMPREENDIMENTO) ';
      wSQL = :wSQL || 'JOIN VEF_EMP_TCADEMPREENDIMENTO EMP_D ON(EMP_D.BDCODEMP = MOV.BDCODEMP AND EMP_D.BDNOMEEMPRE = EMP.BDNOMEEMPRE);';
      EXECUTE STATEMENT :wSQL;

      /*Informação complementar correspondente na empresa destino*/
      wSQL =          'INSERT INTO TMP_TTRANSFERENCIA_FKS(BDCODEMP, BDCHAVE, BDORDEMA110, BDORDEMINFCOM, BDTABLE)';
      wSQL = :wSQL || 'SELECT MOV.BDCODEMP_OLD, MOV.BDCHAVE, A110.BDORDEMA110, INF_D.BDORDEMINFCOM, '''||'VEF_EMP_TA110'||'''';
      wSQL = :wSQL || 'FROM ( ';
      wSQL = :wSQL || '      SELECT M.BDSESSAO, M.BDCODEMP, M.BDCHAVE, M.BDCODEMP_OLD ';
      wSQL = :wSQL || '      FROM '||:wTableTMP||' M ';
      wSQL = :wSQL || '      WHERE M.BDSESSAO = '||:wSessaoDest;
      wSQL = :wSQL || '     ) MOV ';
      wSQL = :wSQL || 'JOIN VEF_EMP_TA110 A110 ON(A110.BDCODEMP = MOV.BDCODEMP_OLD AND A110.BDCHAVE = MOV.BDCHAVE) ';
      wSQL = :wSQL || 'JOIN VEF_BASE_TCADINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP_OLD AND INF.BDORDEMINFCOM = A110.BDORDEMINFCOM) ';
      --wSQL = :wSQL || 'JOIN VEF_BASE_TCADINFCOM INF_D ON(INF_D.BDCODEMP = MOV.BDCODEMP AND INF_D.BDDESCINFCOMHASH = INF.BDDESCINFCOMHASH);';
      wSQL = :wSQL || 'JOIN VEF_BASE_TCADINFCOM INF_D ON (INF_D.BDCODEMP = MOV.BDCODEMP AND INF_D.BDORDEMINFCOM = (SELECT BDORDEMINFCOM FROM SP_GET_ORDEMINFCOM(MOV.BDCODEMP, INF.BDDESCINFCOMHASH))) ';
      EXECUTE STATEMENT :wSQL;
    END

END^

CREATE OR ALTER PROCEDURE LANCA_EXCEPTION (
    PRMESSAGE VARCHAR(500),
    PRSQLCODE CHAR(4),
    PRGDSCODE CHAR(9))
AS
BEGIN
  /*Patrick T. Sá 15/10/2018 - Captura erros no banco

    COMO USAR (Exemplo):

    INSERT INTO TESTE(BDCODIGO) VALUES(1);
    INSERT INTO TESTE(BDCODIGO) VALUES(1); --Vai dar erro de PK

    WHEN ANY DO
      BEGIN
        IN AUTONOMOUS TRANSACTION DO -- Vai executar a procedure que grava o erro em outra sessão para que a sessão atual retorne a exceção.
          EXECUTE PROCEDURE LANCA_EXCEPTION('DESCRIÇÃO DO ERRO, LOCALIZAÇÃO...', SQLCODE, GDSCODE);
        EXCEPTION; -- Tem que lançar a exceção novamente, senão tudo que foi feito na SP até o ocorrer o erro sera comitado.
      END

    Tabelas com código dos erros:
    SQLCODE e GDSCODE = https://firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-appx02-sqlcodes.html

  */

  INSERT INTO TLOG_EXCEPTION(BDERRO, BDSQLCODE, BDGDSCODE, BDDATA) VALUES(:PRMESSAGE, :PRSQLCODE, :PRGDSCODE, (SELECT CAST('NOW' AS TIMESTAMP) FROM RDB$DATABASE));

  /*Apaga erros com mais de 2 meses*/
  DELETE FROM TLOG_EXCEPTION LG WHERE (SELECT BDMESES FROM DIFERENCA_MESES(LG.bddata,  (SELECT CAST('NOW' AS TIMESTAMP) FROM RDB$DATABASE))) > 2;
END^

CREATE OR ALTER TRIGGER VRH_BASE_TFPAS_ALIQ_TERC_BI0 FOR VRH_BASE_TFPAS_ALIQ_TERC
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcodterc INTEGER;
  declare variable vcod INTEGER;
begin
  if (coalesce(new.bdcodfpasterc, 0) = 0) then
     begin
       select coalesce(max(BDCODFPASTERC) + 1, 1) from VRH_BASE_TFPAS_ALIQ_TERC into :vcod;
       new.bdcodfpasterc = :vcod;
     end

  new.bdtipofpas = 0;

  vcodterc = 0;

  if (coalesce(new.bdsaleduc, 0) > 0) then
     vcodterc = vcodterc + 1;

  if (coalesce(new.bdincra, 0) > 0) then
     vcodterc = vcodterc + 2;

  if (coalesce(new.bdsenai, 0) > 0) then
     vcodterc = vcodterc + 4;

  if (coalesce(new.bdsesi, 0) > 0) then
     vcodterc = vcodterc + 8;

  if (coalesce(new.bdsenac, 0) > 0) then
     vcodterc = vcodterc + 16;

  if (coalesce(new.bdsesc, 0) > 0) then
     vcodterc = vcodterc + 32;

  if (coalesce(new.bdsebrae, 0) > 0) then
     vcodterc = vcodterc + 64;

  if (coalesce(new.bddpc, 0) > 0) then
     vcodterc = vcodterc + 128;

  if (coalesce(new.bdfundoaero, 0) > 0) then
     vcodterc = vcodterc + 256;

  if (coalesce(new.bdsenar, 0) > 0) then
     vcodterc = vcodterc + 512;

  if (coalesce(new.bdsest, 0) > 0) then
     vcodterc = vcodterc + 1024;

  if (coalesce(new.bdsenat, 0) > 0) then
     vcodterc = vcodterc + 2048;

  if (coalesce(new.bdsescoop, 0) > 0) then
     vcodterc = vcodterc + 4096;

  new.bdcodterceiro = :vcodterc;
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TFPAS_ALIQ_TERC_BU0 FOR VRH_BASE_TFPAS_ALIQ_TERC
ACTIVE BEFORE UPDATE POSITION 0
AS
  declare variable vcodterc INTEGER;

begin
  vcodterc = 0;

  if (coalesce(new.bdsaleduc, 0) > 0) then
     vcodterc = vcodterc + 1;

  if (coalesce(new.bdincra, 0) > 0) then
     vcodterc = vcodterc + 2;

  if (coalesce(new.bdsenai, 0) > 0) then
     vcodterc = vcodterc + 4;

  if (coalesce(new.bdsesi, 0) > 0) then
     vcodterc = vcodterc + 8;

  if (coalesce(new.bdsenac, 0) > 0) then
     vcodterc = vcodterc + 16;

  if (coalesce(new.bdsesc, 0) > 0) then
     vcodterc = vcodterc + 32;

  if (coalesce(new.bdsebrae, 0) > 0) then
     vcodterc = vcodterc + 64;

  if (coalesce(new.bddpc, 0) > 0) then
     vcodterc = vcodterc + 128;

  if (coalesce(new.bdfundoaero, 0) > 0) then
     vcodterc = vcodterc + 256;

  if (coalesce(new.bdsenar, 0) > 0) then
     vcodterc = vcodterc + 512;

  if (coalesce(new.bdsest, 0) > 0) then
     vcodterc = vcodterc + 1024;

  if (coalesce(new.bdsenat, 0) > 0) then
     vcodterc = vcodterc + 2048;

  if (coalesce(new.bdsescoop, 0) > 0) then
     vcodterc = vcodterc + 4096;

  new.bdcodterceiro = :vcodterc;
end
^

CREATE OR ALTER PROCEDURE SP_RETIRAR_CARACTER_ESP (
    PRSTR VARCHAR(255))
RETURNS (
    BDSTR VARCHAR(255))
AS
DECLARE VARIABLE WI INTEGER;
DECLARE VARIABLE WDE VARCHAR(1);
DECLARE VARIABLE WPARA VARCHAR(1);
BEGIN
  BDSTR = '';

  wI = 1;
  WHILE (wI <= CHAR_LENGTH(:PRSTR)) DO
    BEGIN
      wPara = NULL;
      wDe   = SUBSTRING(:PRSTR FROM :wI FOR 1);

      SELECT E.BDLETRA
      FROM TCARACTER_ESPECIAL E
      WHERE CAST(E.BDCARACTER AS VARCHAR(1)) = :wDe
      INTO :wPara;

      /*Tem caracter especial*/
      IF (:wPara IS NOT NULL) THEN
        BDSTR = :BDSTR || :wPara;
      ELSE
        BDSTR = :BDSTR || :wDe;

      wI = :wI + 1;
    END

  SUSPEND;
END^

CREATE OR ALTER procedure SP_EXPORTA_ECREDRURAL (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRARQUIVO varchar(260),
    PRFINALIDADE integer,
    PRCODPROTRANS integer,
    PRCODPROTELECOM integer,
    PREXPPRODUTOUNICO DM_BOOLEAN)
as
declare variable WREFINI integer;
declare variable WREFFIM integer;
declare variable WLINHA blob sub_type 1 segment size 200 character set UTF8;
declare variable WTEMREGBLOCO9 DM_BOOLEAN;
declare variable WQTDE integer;
BEGIN
  SELECT CAST(BDDATA AS INTEGER) FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM') INTO :wRefIni;
  SELECT CAST(BDDATA AS INTEGER) FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM') INTO :wRefFIM;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:wRefIni);

  /***********************************************************************************
   *                                    ENTRADA                                      *
   **********************************************************************************/

  /***********************************************************************************
   * REGISTRO 5200: DOCUMENTOS FISCAIS DE ENTRADA DE MERCADORIAS OU SERVIÇOS TOMADOS *
   **********************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA, BDCODTER)
  SELECT :PRARQUIVO, M.BDCODEMP, '5200',  LPAD(M.BDCODEMP, 6, '0')||'.5200.'||LPAD(M.BDCHAVE, 6, '0'),
         '5200|'||                                                                                              -- 1 - Texto fixo contendo "5200"
         IIF(M.BDREFENT BETWEEN :wRefIni AND :wRefFim, '0', '1')||'|'||                                         -- 2 - Indicador de extemporaneidade 0 - relativo a documentos fiscais da própria referência do arquivo digital 1 – documentos de referências anteriores
         (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY'))||'|'||                                 -- 3 - Data da emissão do documento fiscal.
         LPAD(IIF(M.BDMODELO IN(59, 65, 67), '99', MODE.BDCODEXP), 2, '0')||'|'||                               -- 4 - Tipo do documento conforme a coluna Código Chave da tabela 5.1
         RPAD(COALESCE(M.BDSERIE, ''), 3, ' ')||'|'||                                                           -- 5 - Série do documento.
         COALESCE(M.BDNUMDOCINI, '')||'|'||                                                                     -- 6 - Número do documento
         COALESCE(M.BDCODTER, '')||'|'||                                                                        -- 7 - Código numérico de identificação do participante no arquivo
         (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAENTRADAENT, 'DDMMYYYY'))||'|'||                              -- 8 - Data da entrada
         REPLACE(M.BDVALORNOTA, '.', ',')||'|'||                                                                -- 9 - Valor total do documento fiscal
         REPLACE(BC.BDBASEICMS, '.', ',')||'|'||                                                                -- 10- Valor da base de cálculo do ICMS, no caso de haver direito a crédito
         REPLACE(BC.BDVLRICMS, '.', ',')||'|'||                                                                 -- 11- Valor do ICMS, quando houver direito a crédito
         IIF(MODE.BDCODEXP IN(31, 32), (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)), ''),-- 12- Para o caso de Nota Fiscal Eletrônica ou Conhecimento de Transporte Eletrônico – documentos com código chave 31 e 32
         M.BDCODTER
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDMODELO, MOV.BDSERIE, MOV.BDNUMDOCINI, MOV.BDCODTER,
               MOV.BDVALORNOTA, MOV.BDDATAEMISSAO, MOV.BDDATAENTRADAENT, MOV.BDCHAVENFE,
               CAST((SELECT BDDATA FROM SP_PARSE_DATE(MOV.BDDATAENTRADAENT, 'YYYYMM')) AS INTEGER) BDREFENT
        FROM VEF_EMP_TMOVENT MOV
        WHERE MOV.BDCODEMP = :PRCODEMP
        AND MOV.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND MOV.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
        AND EXISTS(SELECT *
                   FROM VEF_EMP_TMOVENTITENS i
                   WHERE i.bdCODEMP = mov.bdCODEMP
                   AND i.bdCHAVE = mov.bdCHAVE)
       ) M
  LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MOD ON(MOD.BDMODELO = M.BDMODELO)
  LEFT OUTER JOIN VEF_BASE_TTABMODELOECREDAC MODE ON(MODE.BDMODELOSTR = MOD.BDMODELOSTR)
  LEFT OUTER JOIN (
                   SELECT MOV.BDCODEMP, MOV.BDCHAVE, SUM(COALESCE(I.BDBASEICMS, 0)) BDBASEICMS, SUM(COALESCE(I.BDVLRICMS, 0)) BDVLRICMS
                   FROM VEF_EMP_TMOVENT MOV
                   LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                   WHERE MOV.BDCODEMP = :PRCODEMP
                   AND MOV.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
                   AND MOV.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                   GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
                  ) BC ON(BC.BDCODEMP = M.BDCODEMP AND BC.BDCHAVE = M.BDCHAVE);

  /*****************************************************************
   * REGISTRO 5220: ITENS/MERCADORIAS ENTRADAS OU SERVIÇOS TOMADOS *
   ****************************************************************/
                                                 
  --MODELOS TRANSPORTE      = (7,8,9,10,11,26,27,57,67,800)
  --MODELOS TELECOMUNICAÇÃO = (21,22)
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA, BDCODPROD)
  SELECT :PRARQUIVO, I.BDCODEMP, '5220', LPAD(I.BDCODEMP, 6, '0')||'.5200.'||LPAD(I.BDCHAVE, 6, '0')||'.5220.'||LPAD(I.BDORDEM, 6, '0')||'.'||LPAD(Coalesce(I.BDORDEMPRO,0), 6, '0'),
         '5220|'||                                                                                                                                                  -- 1 - Texto fixo contendo "5220"
         I.BDCODNAT||'|'||                                                                                                                                          -- 2 - Classifica  o Fiscal de Opera  es e Presta  es
         iif(:PREXPPRODUTOUNICO <> 'TRUE', COALESCE(IIF(I.BDCODNAT IN(1604), NULL, IIF(Coalesce(PRO.BDCODSAIDA,'') = '', I.BDCODPROD, PRO.BDCODSAIDA)), ''), pro.BDCODPROD) ||'|'|| -- 3 - Código de item entrada  cfe. cadastro atribuido pelo contribuinte
         COALESCE(IIF(I.BDCODNAT IN(1604, 1356, 2356, 3356, 1306, 2306), NULL, REPLACE(CAST(COALESCE(I.BDQTDITEM, 0.00) AS DM_NUMERIC_15_2), '.', ',')), '')||'|'|| -- 4 - Quantidade comprada
         COALESCE(IIF(I.BDCODNAT IN(1604), NULL, REPLACE(CAST(COALESCE(I.BDVLRITEM, 0) AS DM_NUMERIC_15_2), '.', ',')), '0,00')||'|'||                              -- 5 - Valor do item comprado
         COALESCE(IIF(I.BDCODNAT IN(1604), NULL, REPLACE(COALESCE(I.BDBCICMS, 0), '.', ',')), '0,00')||'|'||                                                        -- 6 - Valor da Base de Cálculo, no caso de haver direito ao crédito do imposto
         COALESCE(IIF(I.BDCODNAT IN(1604), NULL, REPLACE(CAST(COALESCE(I.BDALIQICMS, 0) AS DM_NUMERIC_15_2), '.', ',')), '0,00'),                                   -- 7 - Alíquota do ICMS aplicável a mercadoria, no caso de haver direito ao crédito do imposto
         IIF(I.BDCODNAT IN(1604), NULL, I.BDCODPROD)
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT,
               IIF(P.BDCODPROD > 0, P.BDORDEMPRO,I.BDORDEM) BDORDEMPRO,
               IIF(P.BDCODPROD > 0, P.BDQTDITEM ,1.00) BDQTDITEM,
               IIF(P.BDCODPROD > 0, P.BDVLRITEM ,I.BDVLRCONTAB) BDVLRITEM,
               IIF(P.BDCODPROD > 0, P.BDBCICMS  ,I.BDBASEICMS) BDBCICMS,
               IIF(P.BDCODPROD > 0, P.BDALIQICMS,I.BDALIQICMS) BDALIQICMS,
               CASE
                 WHEN P.BDCODPROD > 0 THEN P.BDCODPROD
                 WHEN M.BDMODELO IN (7,8,9,10,11,26,27,57,67,800) THEN :PRCODPROTRANS
                 WHEN M.BDMODELO IN (21,22) THEN :PRCODPROTELECOM
               END BDCODPROD
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDMODELO
              FROM VEF_EMP_TMOVENT MOV
              WHERE MOV.BDCODEMP = :PRCODEMP
              AND MOV.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
              AND MOV.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
             ) M
        JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        LEFT OUTER JOIN VEF_EMP_TMOVPROENT P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
       ) I
  LEFT OUTER JOIN TCADPRO_VINC PRO ON(PRO.BDCODPROD = I.BDCODPROD AND PRO.BDCODEMP = I.BDCODEMP)
  WHERE I.BDCODPROD > 0;

  /*****************************************************************
   * REGISTRO 5240: DOCUMENTO DE ARRECADAÇÃO REFERENCIADO          *
   ****************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  SELECT :PRARQUIVO, M.BDCODEMP, '5240', LPAD(C112.BDCODEMP, 6, '0')||'.5200.'||LPAD(C112.BDCHAVE, 6, '0')||'.5240.'||LPAD(C112.BDORDEMIC, 6, '0')||'.'||LPAD(C112.BDORDEMDOCAREF, 6, '0'),
         '5240|'||                                                                       -- 1 - Texto fixo contendo "5240"
         C112.BDMODCODDA||'|'||                                                          -- 2 - Código do modelo do documento de arrecadação: 0 - Documento estadual de arrecadação 1 – GNRE
         COALESCE(UF.BDSIGLAUF, '')||'|'||                                               -- 3 - Unidade federada beneficiária do recolhimento
         COALESCE(C112.BDNUMDA, '')||'|'||                                               -- 4 - Número do documento de arrecadação
         COALESCE(C112.BDCODAUT, '')||'|'||                                              -- 5 - Código completo da autenticação bancária
         REPLACE(CAST(COALESCE(C112.BDVLRDA, 0.00) AS DM_NUMERIC_15_2), '.', ',')||'|'|| -- 6 - Valor do total do documento de arrecadação (principal, atualização monetária, juros e multa)
         (SELECT BDDATA FROM SP_PARSE_DATE(C112.BDDTVCTO, 'DDMMYYYY'))||'|'||            -- 7 - Data de vencimento do documento de arrecadação
         (SELECT BDDATA FROM SP_PARSE_DATE(C112.BDDTPGTO, 'DDMMYYYY'))||'|'||            -- 8 - Data de pagamento do documento de arrecadação, ou data do vencimento, no caso de ICMS antecipado a recolher.
        ''                                                                               -- 9 - Valor do crédito utilizado para abatimento do ICMS a recolher
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
        FROM VEF_EMP_TMOVENT MOV
        JOIN VEF_EMP_TMOVENTINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
        WHERE MOV.BDCODEMP = :PRCODEMP
        AND MOV.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND MOV.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
       ) M
  JOIN VEF_EMP_TMOVENTDOCAREF C112 ON(C112.BDCODEMP = M.BDCODEMP AND C112.BDCHAVE = M.BDCHAVE AND C112.BDORDEMIC = M.BDORDEMIC)
  LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C112.BDCODUF);

  /*****************************************************************
   * REGISTRO 5260: OPERAÇÕES DE IMPORTAÇÃO                        *
   ****************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  SELECT :PRARQUIVO, M.BDCODEMP, '5260', LPAD(C120.BDCODEMP, 6, '0')||'.5200.'||LPAD(C120.BDCHAVE, 6, '0')||'.5260.'||LPAD(C120.BDORDEMOPIMP, 6, '0'),
         '5260|'||               -- 1 - Texto fixo contendo "5260"
         C120.BDCODDOCIMP||'|'|| -- 2 - Documento de importação: 0 - Declaração de Importação; 1 - Declaração Simplificada de Importação
         C120.BDNUMDOCIMP        -- 3 - Número do documento de Importação.
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE
        FROM VEF_EMP_TMOVENT MOV
        WHERE MOV.BDCODEMP = :PRCODEMP
        AND MOV.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
        AND MOV.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
       ) M
  JOIN VEF_EMP_TMOVENTOPIMP C120 ON(C120.BDCODEMP = M.BDCODEMP AND C120.BDCHAVE = M.BDCHAVE);

  /***********************************************************************************
   *                                    SAÍDA                                        *
   **********************************************************************************/

  /***********************************************************************************
   * REGISTRO 5400: NOTA FISCAL DE SAÍDA – EMITIDA PELO PRODUTOR RURAL               *
   **********************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA, BDCODTER)
  SELECT :PRARQUIVO, M.BDCODEMP, '5400',  LPAD(M.BDCODEMP, 6, '0')||'.5400.'||LPAD(M.BDCHAVE, 6, '0'),
         '5400|'||                                                                                           -- 1 - Texto fixo contendo "5400"
         (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY'))||'|'||                              -- 2 - Data da emissão do documento fiscal.
         LPAD(IIF(M.BDMODELO IN(59, 65, 67), '99', MODE.BDCODEXP), 2, '0')||'|'||                            -- 3 - Tipo do documento conforme a coluna Código Chave da tabela 5.1
         RPAD(COALESCE(M.BDSERIE, ''), 3, ' ')||'|'||                                                        -- 4 - Série do documento.
         COALESCE(M.BDNUMDOCINI, '')||'|'||                                                                  -- 5 - Número do documento
         COALESCE(M.BDCODTER, '')||'|'||                                                                     -- 6 - Código numérico de identificação do participante no arquivo
         COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATASAIDA, 'DDMMYYYY')), '')||'|'||                  -- 7 - Data da saída
         REPLACE(M.BDVALORNOTA, '.', ',')||'|'||                                                             -- 8 - Valor total do documento fiscal
         REPLACE(BC.BDBASEICMS, '.', ',')||'|'||                                                             -- 9 - Valor da base de cálculo do ICMS, no caso de haver direito a crédito
         REPLACE(BC.BDVLRICMS, '.', ',')||'|'||                                                              -- 10- Valor do ICMS, quando houver direito a crédito
         IIF(MODE.BDCODEXP IN(31), (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)), ''), -- 11- Para o caso de Nota Fiscal Eletrônica ou Conhecimento de Transporte Eletrônico – documentos com código chave 31 e 32
         M.BDCODTER
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDMODELO, MOV.BDSERIE, MOV.BDNUMDOCINI, MOV.BDCODTER,
               MOV.BDVALORNOTA, MOV.BDDATAEMISSAO, MOV.BDCHAVENFE, MOV.BDDATASAIDA
        FROM VEF_EMP_TMOVSAI MOV
        WHERE MOV.BDCODEMP = :PRCODEMP
        AND MOV.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND MOV.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
        AND MOV.BDEMITENTE = 0 /*Próprio*/
        /*Modelo 4 e CFOP 5949 serão levadas no registro 5480*/
        AND MOV.BDMODELO <> 4
        AND EXISTS(SELECT I.BDCHAVE
                   FROM VEF_EMP_TMOVSAIITENS I
                   WHERE I.BDCODEMP = MOV.BDCODEMP
                   AND I.BDCHAVE = MOV.BDCHAVE)
        AND NOT EXISTS(
                       SELECT I.BDCHAVE
                       FROM VEF_EMP_TMOVSAIITENS I
                       WHERE I.BDCODEMP = MOV.BDCODEMP
                       AND I.BDCHAVE = MOV.BDCHAVE
                       AND SUBSTRING(I.BDCODNAT FROM 1 FOR 4) = 5949
                      )
       ) M
  LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MOD ON(MOD.BDMODELO = M.BDMODELO)
  LEFT OUTER JOIN VEF_BASE_TTABMODELOECREDAC MODE ON(MODE.BDMODELOSTR = MOD.BDMODELOSTR)
  LEFT OUTER JOIN (
                   SELECT MOV.BDCODEMP, MOV.BDCHAVE, SUM(COALESCE(I.BDBASEICMS, 0)) BDBASEICMS, SUM(COALESCE(I.BDVLRICMS, 0)) BDVLRICMS
                   FROM VEF_EMP_TMOVSAI MOV
                   LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                   WHERE MOV.BDCODEMP = :PRCODEMP
                   AND MOV.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                   AND MOV.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                   GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
                  ) BC ON(BC.BDCODEMP = M.BDCODEMP AND BC.BDCHAVE = M.BDCHAVE);

  /*****************************************************************
   * REGISTRO 5440: ITENS/MERCADORIAS SAÍDAS                       *
   ****************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA, BDCODPROD)
  SELECT :PRARQUIVO, I.BDCODEMP, '5440', LPAD(I.BDCODEMP, 6, '0')||'.5400.'||LPAD(I.BDCHAVE, 6, '0')||'.5440.'||LPAD(I.BDORDEM, 6, '0')||'.'||LPAD(I.BDORDEMPRO, 6, '0'),
         '5440|'||                                                                                      -- 1 - Texto fixo contendo "5440"
         I.BDCODNAT||'|'||                                                                              -- 2 - Classifica  o Fiscal de Opera  es e Presta  es
         iif(:PREXPPRODUTOUNICO <> 'TRUE', COALESCE(IIF(I.BDCODSAIDA = '', I.BDCODPROD, I.BDCODSAIDA), ''), I.BDCODPRODUNI) ||'|'|| -- 3 - Código de item entrado é cfe. cadastro atribuído pelo contribuinte
         COALESCE(REPLACE(CAST(COALESCE(I.BDQTDITEM, 0.00) AS DM_NUMERIC_15_2), '.', ','), '')||'|'||   -- 4 - Quantidade de sa da do item
         COALESCE(REPLACE(CAST(COALESCE(I.BDVLRITEM, 0) AS DM_NUMERIC_15_2), '.', ','), '0,00')||'|'||  -- 5 - Valor de sa da do item
         COALESCE(REPLACE(COALESCE(I.BDBCICMS, 0), '.', ','), '0,00')||'|'||                            -- 6 - Base de C lculo do ICMS
         COALESCE(REPLACE(CAST(COALESCE(I.BDALIQICMS, 0) AS DM_NUMERIC_15_2), '.', ','), '0,00')||'|'|| -- 7 - Al quota do ICMS aplic vel
         COALESCE(REPLACE(CAST(COALESCE(I.BDVLRICMS, 0) AS DM_NUMERIC_15_2), '.', ','), '0,00'),        -- 8 - Valor do ICMS devido
         I.BDCODPROD
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, P.BDORDEMPRO, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT,
               P.BDCODPROD, P.BDQTDITEM, P.BDVLRITEM, P.BDBCICMS, P.BDALIQICMS, P.BDVLRICMS, COALESCE(TRIM(PRO.BDCODSAIDA), '') BDCODSAIDA, pro.BDCODPROD as BDCODPRODUNI
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE
              FROM VEF_EMP_TMOVSAI MOV
              WHERE MOV.BDCODEMP = :PRCODEMP
              AND MOV.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              AND MOV.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
              AND MOV.BDEMITENTE = 0 /*Próprio*/
              /*Modelo 4 e CFOP 5949 serão levadas no registro 5480*/
              AND MOV.BDMODELO <> 4
              AND NOT EXISTS(
                             SELECT I.BDCHAVE
                             FROM VEF_EMP_TMOVSAIITENS I
                             WHERE I.BDCODEMP = MOV.BDCODEMP
                             AND I.BDCHAVE = MOV.BDCHAVE
                             AND SUBSTRING(I.BDCODNAT FROM 1 FOR 4) = 5949
                            )
             ) M
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        JOIN VEF_EMP_TMOVPROSAI P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
        LEFT OUTER JOIN TCADPRO_VINC PRO ON(PRO.BDCODPROD = P.BDCODPROD AND PRO.BDCODEMP = P.BDCODEMP)
       ) I;

  /*****************************************************************
   * REGISTRO 5460: DOCUMENTO DE ARRECADAÇÃO REFERENCIADO          *
   ****************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  SELECT :PRARQUIVO, M.BDCODEMP, '5460', LPAD(C112.BDCODEMP, 6, '0')||'.5400.'||LPAD(C112.BDCHAVE, 6, '0')||'.5460.'||LPAD(C112.BDORDEMIC, 6, '0')||'.'||LPAD(C112.BDORDEMDOCAREF, 6, '0'),
         '5460|'||                                                                       -- 1 - Texto fixo contendo "5460"
         C112.BDMODCODDA||'|'||                                                          -- 2 - Código do modelo do documento de arrecadação: 0 - Documento estadual de arrecadação 1 – GNRE
         COALESCE(UF.BDSIGLAUF, '')||'|'||                                               -- 3 - Unidade federada beneficiária do recolhimento
         COALESCE(C112.BDNUMDA, '')||'|'||                                               -- 4 - Número do documento de arrecadação
         COALESCE(C112.BDCODAUT, '')||'|'||                                              -- 5 - Código completo da autenticação bancária
         REPLACE(CAST(COALESCE(C112.BDVLRDA, 0.00) AS DM_NUMERIC_15_2), '.', ',')||'|'|| -- 6 - Valor do total do documento de arrecadação (principal, atualização monetária, juros e multa)
         (SELECT BDDATA FROM SP_PARSE_DATE(C112.BDDTVCTO, 'DDMMYYYY'))||'|'||            -- 7 - Data de vencimento do documento de arrecadação
         (SELECT BDDATA FROM SP_PARSE_DATE(C112.BDDTPGTO, 'DDMMYYYY'))||'|'||            -- 8 - Data de pagamento do documento de arrecadação, ou data do vencimento, no caso de ICMS antecipado a recolher
        ''                                                                               -- 9 - Valor do crédito utilizado para abatimento da GR
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, INF.BDORDEMIC
        FROM VEF_EMP_TMOVSAI MOV
        JOIN VEF_EMP_TMOVSAIINFCOM INF ON(INF.BDCODEMP = MOV.BDCODEMP AND INF.BDCHAVE = MOV.BDCHAVE)
        WHERE MOV.BDCODEMP = :PRCODEMP
        AND MOV.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND MOV.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
        AND MOV.BDEMITENTE = 0 /*Próprio*/
        /*Modelo 4 e CFOP 5949 serão levadas no registro 5480*/
        AND MOV.BDMODELO <> 4
        AND NOT EXISTS(
                       SELECT I.BDCHAVE
                       FROM VEF_EMP_TMOVSAIITENS I
                       WHERE I.BDCODEMP = MOV.BDCODEMP
                       AND I.BDCHAVE = MOV.BDCHAVE
                       AND SUBSTRING(I.BDCODNAT FROM 1 FOR 4) = 5949
                      )
       ) M
  JOIN VEF_EMP_TMOVSAIDOCAREF C112 ON(C112.BDCODEMP = M.BDCODEMP AND C112.BDCHAVE = M.BDCHAVE AND C112.BDORDEMIC = M.BDORDEMIC)
  LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C112.BDCODUF);

  /*******************************************************************************************************
   * REGISTRO 5480: NOTA FISCAL MODELO 4 – CFOP 5949 – EMITIDA PARA ACOBERTAR O TRANSPORTE DE MERCADORIA *
                    NA HIPÓTESE DE IMPOSSIBILIDADE DE EMISSÃO DA NOTA FISCAL ELETRÔNICA – MODELO 55      *
   ******************************************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  SELECT :PRARQUIVO, M.BDCODEMP, '5480',  LPAD(M.BDCODEMP, 6, '0')||'.5480.'||LPAD(M.BDCHAVE, 6, '0'),
         '5480|'||                                                                          -- 1 - Texto fixo contendo "5480"
         (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY'))||'|'||             -- 2 - Data da emissão do documento fiscal.
         COALESCE(M.BDSERIE, '')||'|'||                                                     -- 3 - Série do documento.
         COALESCE(M.BDNUMDOCINI, '')||'|'||                                                 -- 4 - Número do documento
         COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATASAIDA, 'DDMMYYYY')), '')||'|'|| -- 5 - Data da saída
         REPLACE(M.BDVALORNOTA, '.', ',')                                                   -- 6 - Valor total do documento fiscal
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDSERIE, MOV.BDNUMDOCINI,
               MOV.BDVALORNOTA, MOV.BDDATAEMISSAO, MOV.BDDATASAIDA
        FROM VEF_EMP_TMOVSAI MOV
        WHERE MOV.BDCODEMP = :PRCODEMP
        AND MOV.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND MOV.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
        AND MOV.BDEMITENTE = 0 /*Próprio*/
        /*Modelo 4 e CFOP 5949 serão levadas no registro 5480*/
        AND MOV.BDMODELO = 4
        AND EXISTS(
                   SELECT I.BDCHAVE
                   FROM VEF_EMP_TMOVSAIITENS I
                   WHERE I.BDCODEMP = MOV.BDCODEMP
                   AND I.BDCHAVE = MOV.BDCHAVE
                   AND SUBSTRING(I.BDCODNAT FROM 1 FOR 4) = 5949
                  )
       ) M;

  /***********************************************************************************
   * REGISTRO 5600: DOCUMENTO FISCAL EMITIDO PELO DESTINATÁRIO DA PRODUÇÃO           *
   **********************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA, BDCODTER)
  SELECT :PRARQUIVO, M.BDCODEMP, '5600',  LPAD(M.BDCODEMP, 6, '0')||'.5600.'||LPAD(M.BDCHAVE, 6, '0'),
         '5600|'||                                                                                           -- 1 - Texto fixo contendo "5600"
         (SELECT BDDATA FROM SP_PARSE_DATE(M.BDDATAEMISSAO, 'DDMMYYYY'))||'|'||                              -- 2 - Data da emissão do documento fiscal.
         LPAD(IIF(M.BDMODELO IN(59, 65, 67), '99', MODE.BDCODEXP), 2, '0')||'|'||                            -- 3 - Tipo do documento conforme a coluna Código Chave da tabela 5.1
         COALESCE(M.BDSERIE, '')||'|'||                                                                      -- 4 - Série do documento.
         COALESCE(M.BDNUMDOCINI, '')||'|'||                                                                  -- 5 - Número do documento
         COALESCE(M.BDCODTER, '')||'|'||                                                                     -- 6 - Código numérico de identificação do participante/emitente do documento fiscal
         REPLACE(M.BDVALORNOTA, '.', ',')||'|'||                                                             -- 7 - Valor total do documento fiscal
         REPLACE(BC.BDBASEICMS, '.', ',')||'|'||                                                             -- 8 - Valor da base de cálculo do ICMS
         REPLACE(BC.BDVLRICMS, '.', ',')||'|'||                                                              -- 9 - Valor do ICMS
         IIF(MODE.BDCODEXP IN(31), (SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(M.BDCHAVENFE)), ''), -- 10- Para o caso de Nota Fiscal Eletrônica – documentos com código chave 31
         M.BDCODTER
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, MOV.BDMODELO, MOV.BDSERIE, MOV.BDNUMDOCINI, MOV.BDCODTER,
               MOV.BDVALORNOTA, MOV.BDDATAEMISSAO, MOV.BDCHAVENFE
        FROM VEF_EMP_TMOVSAI MOV
        WHERE MOV.BDCODEMP = :PRCODEMP
        AND MOV.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
        AND MOV.BDCODSITNF NOT IN (2, 3, 4, 5)
        AND MOV.BDEMITENTE = 1 /*Terceiros*/
       ) M
  LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MOD ON(MOD.BDMODELO = M.BDMODELO)
  LEFT OUTER JOIN VEF_BASE_TTABMODELOECREDAC MODE ON(MODE.BDMODELOSTR = MOD.BDMODELOSTR)
  LEFT OUTER JOIN (
                   SELECT MOV.BDCODEMP, MOV.BDCHAVE, SUM(COALESCE(I.BDBASEICMS, 0)) BDBASEICMS, SUM(COALESCE(I.BDVLRICMS, 0)) BDVLRICMS
                   FROM VEF_EMP_TMOVSAI MOV
                   LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                   WHERE MOV.BDCODEMP = :PRCODEMP
                   AND MOV.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
                   AND MOV.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
                   GROUP BY MOV.BDCODEMP, MOV.BDCHAVE
                  ) BC ON(BC.BDCODEMP = M.BDCODEMP AND BC.BDCHAVE = M.BDCHAVE);

  /*****************************************************************
   * REGISTRO 5640: ITENS/MERCADORIAS VENDIDAS                     *
   ****************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA, BDCODPROD)
  SELECT :PRARQUIVO, I.BDCODEMP, '5640', LPAD(I.BDCODEMP, 6, '0')||'.5600.'||LPAD(I.BDCHAVE, 6, '0')||'.5640.'||LPAD(I.BDORDEM, 6, '0')||'.'||LPAD(I.BDORDEMPRO, 6, '0'),
         '5640|'||                                                                                      -- 1 - Texto fixo contendo "5640"
         I.BDCODNAT||'|'||                                                                              -- 2 - Classifica  o Fiscal de Opera  es e Presta  es
         iif(:PREXPPRODUTOUNICO <> 'TRUE', COALESCE(IIF(I.BDCODSAIDA = '', I.BDCODPROD, I.BDCODSAIDA), ''), I.BDCODPRODUNI) ||'|'|| -- 3 - Código de item entrado é cfe. cadastro atribuído pelo contribuinte
         COALESCE(REPLACE(CAST(COALESCE(I.BDQTDITEM, 0.00) AS DM_NUMERIC_15_2), '.', ','), '')||'|'||   -- 4 - Quantidade vendida
         COALESCE(REPLACE(CAST(COALESCE(I.BDVLRITEM, 0) AS DM_NUMERIC_15_2), '.', ','), '0,00')||'|'||  -- 5 - Valor do item vendido
         COALESCE(REPLACE(COALESCE(I.BDBCICMS, 0), '.', ','), '0,00')||'|'||                            -- 6 - Valor da Base de Cálculo do ICMS
         COALESCE(REPLACE(CAST(COALESCE(I.BDALIQICMS, 0) AS DM_NUMERIC_15_2), '.', ','), '0,00')||'|'|| -- 7 - Alíquota do ICMS aplicável à mercadoria
         COALESCE(REPLACE(CAST(COALESCE(I.BDVLRICMS, 0) AS DM_NUMERIC_15_2), '.', ','), '0,00'),        -- 8 - Valor do ICMS relativo ao item
         I.BDCODPROD
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE, I.BDORDEM, P.BDORDEMPRO, SUBSTRING(I.BDCODNAT FROM 1 FOR 4) BDCODNAT,
               P.BDCODPROD, P.BDQTDITEM, P.BDVLRITEM, P.BDBCICMS, P.BDALIQICMS, P.BDVLRICMS, COALESCE(TRIM(PRO.BDCODSAIDA), '') BDCODSAIDA, pro.BDCODPROD as BDCODPRODUNI
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE
              FROM VEF_EMP_TMOVSAI MOV
              WHERE MOV.BDCODEMP = :PRCODEMP
              AND MOV.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
              AND MOV.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
              AND MOV.BDEMITENTE = 1 /*Terceiros*/
             ) M
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        JOIN VEF_EMP_TMOVPROSAI P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
        LEFT OUTER JOIN TCADPRO_VINC PRO ON(PRO.BDCODPROD = P.BDCODPROD AND PRO.BDCODEMP = P.BDCODEMP)
       ) I;

  /*****************************************************************
   * REGISTRO 5800: OUTROS CRÉDITOS                                *
   ****************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  SELECT :PRARQUIVO, E.BDCODEMP, '5800', LPAD(E.BDCODEMP, 6, '0')||'.5800.'||LPAD(E.BDORDEMAJU, 6, '0')||'.0',
         '5800|'||                                                                                        -- 1 - Texto fixo contendo "5800"
         COALESCE(REPLACE(CAST(COALESCE(E.BDVLRCRED, 0.00) AS DM_NUMERIC_15_2), '.', ','), '0,00')||'|'|| -- 2 - Valor do crédito
         COALESCE(E.BDDESCRICAO, '')                                                                      -- 3 - Descrição do lançamento
  FROM VEF_EMP_TAJUECREDRURAL E
  WHERE E.BDCODEMP = :PRCODEMP
  AND E.BDREFERENCIA BETWEEN :wRefIni AND :wRefFim;

  /*****************************************************************
   * REGISTRO 5001: ABERTURA DO BLOCO 5                            *
   ****************************************************************/
  /*0 - Dados informados
    1 - Dados não informados*/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  VALUES(:PRARQUIVO, :PRCODEMP, '5001', LPAD(:PRCODEMP, 6, '0')||'.5001',
         ('5001|'||IIF(COALESCE((SELECT COUNT(BDID) FROM TEXPORTACAO_SPED S WHERE S.BDID = :PRARQUIVO GROUP BY S.BDID), 0) > 0, '0', '1')));

  /*****************************************************************
   * REGISTRO 5990: ENCERRAMENTO DO BLOCO 5                        *
   ****************************************************************/
  INSERT INTO TEXPORTACAO_SPED (BDID,BDCODEMP,BDREG,BDCHAVEREG,BDLINHA)
  VALUES (:PRARQUIVO, :PRCODEMP, '5990', LPAD(:PRCODEMP,6,'0') || '.5990',
          '5990|' || -- 01 REG Texto fixo contendo "5990" C 004
           (SELECT COUNT(*) + 1 FROM TEXPORTACAO_SPED WHERE BDID = :PRARQUIVO AND BDCODEMP = :PRCODEMP AND SUBSTRING(BDREG FROM 1 FOR 1) = '5'));--02 QTD_LIN_0 Quantidade total de linhas do Bloco 0 N

  /******************************************************************************
   * REGISTRO 0001: ABERTURA DO BLOCO 0                                         *
   *****************************************************************************/
  /*0 - Dados informados
    1 - Dados não informados*/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  VALUES(:PRARQUIVO, :PRCODEMP, '0001', LPAD(:PRCODEMP, 6, '0')||'.0001',
         ('0001|'||IIF(COALESCE((SELECT COUNT(BDID) FROM TEXPORTACAO_SPED S WHERE S.BDID = :PRARQUIVO AND S.BDREG <> '5001' AND S.BDREG <> '5990' GROUP BY S.BDID), 0) > 0, '0', '1')));

  /******************************************************************************
   * REGISTRO 0000: CADASTRO DE PARTICIPANTES DE OPERAÇÕES E PRESTAÇÕES         *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, '0000', LPAD(:PRCODEMP,6,'0') || '.0000',
           '0000|' ||                                                                     --01 REG Texto fixo contendo "0000" C 004 -
           'PRODCRED|' ||                                                                 --02 PRODCRED Texto fixo contendo "PRODCRED” C 007 -
           '01|' ||                                                                       --03 COD_VER Código da versão do leiaute conforme a Tabela 4.1 N 002 -
           LPAD(:PRFINALIDADE, 2, '0')|| '|' ||                                           --04 COD_FIN Código da finalidade do arquivo conforme a Tabela 4.2 N 002 -
           (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'MMYYYY')) || '|' ||               --05 PERIODO Período das informações contidas no arquivo N 006 -
           COALESCE((SELECT BDSTR FROM SP_RETIRAR_CARACTER_ESP(REF.BDNOMEMP)), '')||'|'|| --06 NOME Nome do produtor C - -
           (SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(EMP.BDCNPJEMP)) || '|' ||             --07 CNPJ Número de inscrição no CNPJ do produtor N 014 -
           COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(REF.BDIEEMP)),'')            --08 IE Inscrição Estadual do produtor C - -
  FROM TEMPRESAS EMP
  LEFT OUTER JOIN VW_TEMPRESAS_REF REF ON (REF.BDCODEMP = EMP.BDCODEMP)
  WHERE EMP.BDCODEMP = :PRCODEMP;

  /******************************************************************************
   * REGISTRO 0150: ABERTURA DO ARQUIVO DIGITAL E IDENTIFICAÇÃO DO CONTRIBUINTE *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, '0150', LPAD(:PRCODEMP,6,'0') || '.0150'||S.BDCODTER,
         '0150|'||                                                                                                    -- 1 - Texto fixo contendo "0150"
         TER.BDCODTER||'|'||                                                                                          -- 2 - Código numérico de identificação do participante no arquivo
         COALESCE(TER.BDNOMETER, '')||'|'||                                                                           -- 3 - Razão social ou nome do participante
         LPAD(COALESCE(P.BDCODSPED, ''), 5, '0')||'|'||                                                               -- 4 - Código do país do participante, conforme a tabela indicada na Tabela de Países do Banco Central do Brasil: www.bcb.gov.br
         COALESCE((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(TER.BDCGCTER)), '')||'|'||                     -- 5 - CNPJ ou CPF do participante
         CASE
           WHEN UPPER(TER.BDIETER) = 'ISENTO' THEN ''
           ELSE  REPLACE(REPLACE(REPLACE(COALESCE(TER.BDIETER, ''), '.', ''), '/', ''), '-', '')
         END||'|'||                                                                                                   -- 6 - Inscrição Estadual do participante
         COALESCE(U.BDSIGLAUF, '')||'|'||                                                                             -- 7 - Sigla da unidade da federação do participante
         LPAD(TRIM(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(TER.BDCEPTER)), '')), 8, '0')||'|'|| -- 8 - Código de Endereçamento Postal
         IIF(TRIM(COALESCE(TER.BDENDTER, '')) = '', '-', TRIM(COALESCE(TER.BDENDTER, '')))||'|'||                     -- 9 - Logradouro e endereço do imóvel
         TRIM(COALESCE(TER.BDNUMTER, ''))||'|'||                                                                      -- 10- Número do imóvel
         TRIM(COALESCE(TER.BDCOMPTER, ''))||'|'||                                                                     -- 11- Dados complementares do endereço
         TRIM(COALESCE(TER.BDBAITER, ''))||'|'||                                                                      -- 12- Bairro em que o imóvel está situado
         TRIM(COALESCE(C.BDCODIBGE, ''))||'|'||                                                                       -- 13- Código do município, conforme Tabela de Municípios (IBGE: www.ibge.gov.br)
         REPLACE(TRIM(COALESCE(TRIM(TER.BDDDDTER)||TRIM(TER.BDFONETER), '')), '-', '')                                -- 14- Número do telefone
  FROM (
        SELECT S.BDCODTER
        FROM TEXPORTACAO_SPED S
        WHERE S.BDID = :PRARQUIVO
        AND S.BDCODTER IS NOT NULL
        GROUP BY S.BDID, S.BDCODTER
       ) S
  JOIN VW_TTERCEIRO TER ON(TER.BDCODTER = S.BDCODTER)
  LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = TER.BDCODCID)
  LEFT OUTER JOIN TUF U ON(U.BDCODUF = C.BDCODUF)
  LEFT OUTER JOIN TPAIS P ON(P.BDCODPAIS = TER.BDCODPAIS);

  /******************************************************************************
   * REGISTRO 0300: CADASTRO DAS MERCADORIAS COMPRADAS E PRODUZIDAS             *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, '0300', LPAD(:PRCODEMP ,6, '0') || '.0300'||S.BDCODPROD,
         '0300|'||                                                                            -- 1 - Texto fixo contendo "0300"
         iif(:PREXPPRODUTOUNICO <> 'TRUE', IIF(TRIM(COALESCE(PRO_V.BDCODSAIDA, '')) = '', S.BDCODPROD, PRO_V.BDCODSAIDA), PRO.BDCODPROD) ||'|'|| -- 2 - Código numérico de identificação das mercadorias no arquivo
         REPLACE(COALESCE(IIF(PRO.BDCODPROD IN (:PRCODPROTELECOM, :PRCODPROTRANS),'',NCM.BDCLASSIFICACAO), ''), '.', '')||'|'|| -- 3 - C digo NCM da mercadoria comercializada/produzida
         COALESCE(PRO_V.BDDESCPROD, PRO.BDDESCRICAOUNICA, '')||'|'||                          -- 4 - Descri  o da mercadoria
         COALESCE(UN.BDDESCUNIMED, '')                                                        -- 5 - Unidade em que a mercadoria   comercializada
  FROM (
        SELECT S.BDCODEMP, S.BDCODPROD
        FROM TEXPORTACAO_SPED S
        WHERE S.BDID = :PRARQUIVO
        AND S.BDCODPROD IS NOT NULL
        GROUP BY S.BDID, S.BDCODEMP, S.BDCODPROD
       ) S
  LEFT OUTER JOIN TCADPRO PRO ON(PRO.BDCODPROD = S.BDCODPROD)
  LEFT OUTER JOIN TCADPRO_VINC PRO_V ON(PRO_V.BDCODPROD = S.BDCODPROD AND PRO_V.BDCODEMP = S.BDCODEMP)
  LEFT OUTER JOIN  TNCM NCM ON(NCM.BDNCMPROD = PRO_V.BDNCMPROD)
  LEFT OUTER JOIN  TUNIDADEMEDIDA UN ON(UN.BDCODUNIMED = PRO_V.BDCODUNIMED);

  /******************************************************************************
   * REGISTRO 0990: ENCERRAMENTO DO BLOCO 0                                     *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, '0990', LPAD(:PRCODEMP, 6, '0')||'.0990.0990',
         '0990|'||COALESCE(COUNT(S.BDID)+1, 0)
  FROM TEXPORTACAO_SPED S
  WHERE S.BDID = :PRARQUIVO
  AND ((S.BDREG = '0001') OR (S.BDREG = '0150') OR (S.BDREG = '0300'))
  GROUP BY S.BDID;

  wTemRegBloco9 = 'FALSE';

  /******************************************************************************
   * REGISTRO 9900:  REGISTROS DO ARQUIVO                                       *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, '9900', LPAD(:PRCODEMP, 6, '0')||'.9900.'||S.BDREG,
         '9900|'||TRIM(S.BDREG)||'|'||COALESCE(COUNT(S.BDREG), 0)
  FROM TEXPORTACAO_SPED S
  WHERE S.BDID = :PRARQUIVO
  GROUP BY S.BDID, S.BDREG;

  SELECT COUNT(*) FROM TEXPORTACAO_SPED WHERE BDID = :PRARQUIVO AND BDCODEMP = :PRCODEMP  AND SUBSTRING(BDREG FROM 1 FOR 2) = '99' INTO :wQTDE;

  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  VALUES(:PRARQUIVO, :PRCODEMP, '9900', LPAD(:PRCODEMP, 6, '0')||'.9900.9900',
         '9900|9900|'||COALESCE(:wQTDE+4, 1));

  wTemRegBloco9 = IIF(:wQTDE > 0, 'TRUE', 'FALSE');

  /******************************************************************************
   * REGISTRO 9001: ABERTURA DO BLOCO 9                                         *
   *****************************************************************************/
  /*0 - Dados informados
    1 - Dados não informados*/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  VALUES(:PRARQUIVO, :PRCODEMP, '9001', LPAD(:PRCODEMP, 6, '0')||'.9001',
         ('9001|'||IIF(:wTemRegBloco9 = 'TRUE', '0', '1')));

  /******************************************************************************
   * REGISTRO 9990: ENCERRAMENTO DO BLOCO 9                                     *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, '9990', LPAD(:PRCODEMP, 6, '0')||'.9990.'||S.BDREG,
         '9990|'|| COALESCE(COUNT(S.BDREG)+4, 0)
  FROM (
        SELECT S.BDID, SUBSTRING(S.BDREG FROM 1 FOR 1) BDREG
        FROM TEXPORTACAO_SPED S
        WHERE S.BDID = :PRARQUIVO
        AND SUBSTRING(S.BDREG FROM 1 FOR 1) = '9'
       ) S
  GROUP BY S.BDREG;

  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  VALUES(:PRARQUIVO, :PRCODEMP, '9900', LPAD(:PRCODEMP, 6, '0')||'.9900.9999', '9900|9999|1');

  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  VALUES(:PRARQUIVO, :PRCODEMP, '9900', LPAD(:PRCODEMP, 6, '0')||'.9900.9990', '9900|9990|1');

  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  VALUES(:PRARQUIVO, :PRCODEMP, '9900', LPAD(:PRCODEMP, 6, '0')||'.9900.9001', '9900|9001|1');

  /******************************************************************************
   * REGISTRO 9999: ENCERRAMENTO DO ARQUIVO DIGITAL                             *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCODEMP, BDREG, BDCHAVEREG, BDLINHA)
  SELECT :PRARQUIVO, :PRCODEMP, '9999', LPAD(:PRCODEMP, 6, '0')||'.9999.9999',
         '9999|'|| COALESCE(COUNT(S.BDID)+1, 0)
  FROM TEXPORTACAO_SPED S
  WHERE S.BDID = :PRARQUIVO
  GROUP BY S.BDID;

  OPENARQ(:PRARQUIVO,:PRCODEMP);

  FOR SELECT E.BDLINHA
      FROM TEXPORTACAO_SPED E
      WHERE E.BDID = :PRARQUIVO
      ORDER BY E.BDCHAVEREG
      INTO :WLINHA
  DO
  BEGIN
    WRITELNOA(:WLINHA,:PRCODEMP);
  END

  CLOSEARQ(:PRARQUIVO,:PRCODEMP);

  DELETE FROM TEXPORTACAO_SPED WHERE BDID = :PRARQUIVO;
END^

CREATE OR ALTER procedure SP_ULTIMA_SITFINANCLI (
    PRDATAMICRO varchar(10),
    PRFILTROCONSULTA varchar(3000),
    PRCODCLIENTE varchar(2000),
    PRSITATUAL varchar(5))
returns (
    BDCODCLI integer,
    BDNOMCLI varchar(100),
    BDCHAVESITCLI integer,
    BDCODSITCLI integer,
    BDDESCSITCLI varchar(100),
    BDDATASITCLI date,
    BDSITTEMP varchar(5),
    BDDIASSITTEMP integer,
    BDBLOQCLI varchar(5),
    BDSITATUAL varchar(5))
as
declare variable WSQL varchar(5000);
declare variable WULTCLI integer;
declare variable WCHAVESITATU integer;
declare variable WWHERE varchar(3000);
begin
  WULTCLI = 0;
  WWHERE = '';
  WSQL = 'select SIT.* ';
  WSQL = WSQL || ' from (select SIT.BDCODCLI, CLI.BDNOMCLI, SIT.BDCHAVESITCLI, SIT.BDCODSITCLI, TAB.BDDESCSITCLI, SIT.BDDATASITCLI, ';
  WSQL = WSQL || ' SIT.BDSITTEMP, SIT.BDDIASSITTEMP , SIT.BDBLOQCLI, SIT.BDSITATUAL ';
  WSQL = WSQL || ' from VFIN_BASE_TSITCLIENTE SIT ';
  WSQL = WSQL || ' left outer join VW_VFIN_CLIENTES_REF CLI on (CLI.BDCODCLI = SIT.BDCODCLI) ';
  WSQL = WSQL || ' left outer join VFIN_BASE_TTABSITCLI TAB on (TAB.BDCODSITCLI = SIT.BDCODSITCLI) ';
  WSQL = WSQL || ' left outer join VFIN_BASE_TSITCLIENTEOBS SITOBS on (SITOBS.BDCODCLI = SIT.BDCODCLI and SITOBS.BDCHAVESITCLI = SIT.BDCHAVESITCLI) ';

  if ((PRFILTROCONSULTA <> '') and (PRFILTROCONSULTA is not null)) then
     WWHERE = ' Where '||PRFILTROCONSULTA;

  if ((PRCODCLIENTE <> '') and (PRCODCLIENTE is not null)) then
     begin
       if (WWHERE = '') then
           WWHERE = ' where SIT.BDCODCLI in ('||PRCODCLIENTE||') ';
       else
         WWHERE = WWHERE||' and SIT.BDCODCLI in ('||PRCODCLIENTE||')';
     end

  WSQL = WSQL ||WWHERE;
  WSQL = WSQL || ' group by BDCODCLI, BDNOMCLI, BDCHAVESITCLI, BDCODSITCLI, BDDESCSITCLI, BDDATASITCLI, BDSITTEMP, BDDIASSITTEMP, BDBLOQCLI, BDSITATUAL ';
  WSQL = WSQL || ' order by SIT.BDDATASITCLI) SIT ';
  WSQL = WSQL || ' order by BDCODCLI ';


  for execute statement WSQL
  into
   :BDCODCLI,
   :BDNOMCLI,
   :BDCHAVESITCLI,
   :BDCODSITCLI,
   :BDDESCSITCLI,
   :BDDATASITCLI,
   :BDSITTEMP,
   :BDDIASSITTEMP,
   :BDBLOQCLI,
   :BDSITATUAL
  do
   begin
/* #127924 - Antony Rairon (01/06/2021) - Foi criado o campo BDSITATUAL na tabela VFIN_BASE_TSITCLIENTE
    if (WULTCLI <> :BDCODCLI) then
       begin
       wSQL = ' select first 1 BDCHAVESITCLI ';
       wSQL = wSQL || ' from VFIN_BASE_TSITCLIENTE ';
       wSQL = wSQL || ' where BDCODCLI = '||:BDCODCLI||' and ';
       wSQL = wSQL || ' BDDATASITCLI <= '||''''||:PRDATAMICRO||'''';
       wSQL = wSQL || ' order by BDCODCLI desc, BDDATASITCLI desc, BDCHAVESITCLI desc ';

       execute statement wSQL into wCHAVESITATU;

       if (wCHAVESITATU = :BDCHAVESITCLI) then
          begin
            BDSITATUAL = 'TRUE';
            WULTCLI = :BDCODCLI;
          end
         else
          BDSITATUAL = 'FALSE';
       end
      else
       BDSITATUAL = 'FALSE';*/

      if ((PRSITATUAL = 'FALSE') or (prsitatual = '')) then
          suspend;
      else
        if ((PRSITATUAL = 'TRUE') and (BDSITATUAL = 'TRUE')) then
           suspend;
   end
end^

/* create proc. body: SP_VRHF_EMP_TCOLCON_MVINC */
CREATE OR ALTER procedure SP_VRHF_EMP_TCOLCON_MVINC (
    PREMP varchar(32700),
    PRCOL varchar(32000),
    PRREF integer,
    PRPUXAFILIAIS smallint = 0,
    PRTIPOCALC integer = -1,
    PRSEMEMPRESAFILIAL smallint = 0,
    PRSEPARACNPJ smallint = 0,
    PRAGRUPACOL smallint = 0,
    PRCARREGARDEMISSOES smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDBASEINSSNCOL numeric(18,6),
    BDVALORINSSNCOL numeric(18,6),
    BDBASEINSS13NCOL numeric(18,6),
    BDVALORINSS13NCOL numeric(18,6),
    BDBASEIRRFNCOL numeric(18,6),
    BDVALORIRRFNCOL numeric(18,6),
    BDBASEINSS13COL numeric(18,6),
    BDVALORINSS13COL numeric(18,6),
    BDBASEIRRF13COL numeric(18,6),
    BDVALORIRRF13COL numeric(18,6),
    BDCALCMVNOVO DM_BOOLEAN,
    BDCNPJEMP DM_CNPJ_CPF,
    BDCNPJRESP DM_CNPJ_CPF,
    BDCATEGORIAESOCIAL integer)
as
declare variable WSQL varchar(32700);
declare variable WFIELDCATEGMV varchar(200);
declare variable WJOINCATEGMV varchar(32700);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREFFIM integer;
declare variable WREFCOL integer;
declare variable WCNPJINSS type of DM_CNPJ_CPF;
declare variable WTIPOCALC integer;
declare variable WCNPJRESP DM_CNPJ_CPF;
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WREFATU integer;
declare variable WCNPJATU DM_CNPJ_CPF;
declare variable WBASE1 numeric(18,6);
declare variable WVAL1 numeric(18,6);
declare variable WBASE2 numeric(18,6);
declare variable WVAL2 numeric(18,6);
declare variable WREFINIPERIOD integer;
declare variable WCNPJEMP DM_CNPJ_CPF;
declare variable WCNPJEMPATU DM_CNPJ_CPF;
declare variable WCATEG integer;
declare variable WCATEGATU integer;
declare variable WCODEMPVINC integer;
declare variable WCODCOLVINC integer;
declare variable WCODTERVINC integer;
declare variable WWHERERESCISAO varchar(500);
declare variable WBASE3 numeric(18,6);
declare variable WVAL3 numeric(18,6);
declare variable WBASE4 numeric(18,6);
declare variable WVAL4 numeric(18,6);
declare variable WBASE13FN numeric(18,6);
declare variable WVAL13FN numeric(18,6);
begin

  -- 133599 - Raphael Teodoro - 24/02/2020
  wwhererescisao = '';
  if (prref >= 202003) then
     begin
         if (PRCARREGARDEMISSOES = 0) then
            wwhererescisao = 'and (((not RESC.BDREFRESCISAO = ' || prref || ') or (RESC.BDDATARESCISAO is null)) or ' ||
                                '((RESC2.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO <= RESC2.BDDATARESCISAO))) ';

       wfieldcategmv = 'MV.BDCNPJRESP AS BDCNPJINSS,'||
                       'MV.BDBASEINSSNCOL, MV.BDVALORINSSNCOL, MV.BDBASEIRRFNCOL, MV.BDVALORIRRFNCOL';
--       wjoincategmv  = ' left outer join (select MV_AUX.BDCODEMP, MV_AUX.BDCODCOL, MV_AUX.BDCNPJRESP '||
--                                         'from VRHF_EMP_TCOLCON_MVINC MV_AUX '||
--                                         'join VRHF_EMP_TCOLCON_FGTSGPS X on (X.BDCODEMP = MV_AUX.BDCODEMP) and (X.BDCODCOL = MV_AUX.BDCODCOL) and (X.BDREFCOL <= MV_AUX.BDREFCOL) '||
--                                         'where ';
       wjoincategmv = ' ';
--       if ((coalesce(premp, '') <> '') and (position('tmp_empresas_select' in upper(premp)) = 0)) then
--         wjoincategmv = wjoincategmv || '('||replace(upper(premp), 'BDCODEMP', 'MV_AUX.BDCODEMP')||') and ';

--       wjoincategmv = wjoincategmv ||    ' (MV_AUX.BDCATEGORIAESOCIAL not in (701, 711, 712, 721, 722, 723, 731, 734, 738, 741, 751, 761, 771)) or (X.BDCATEGORIAESOCIAL not in (101, 102, 103, 104, 105, 106, 111, 201, 201, 202)) '||
--                                         'group by MV_AUX.BDCODEMP, MV_AUX.BDCODCOL, MV_AUX.BDCNPJRESP) MV_COL on (MV_COL.BDCODEMP = MV.BDCODEMP) and (MV_COL.BDCODCOL = MV.BDCODCOL) and (MV_COL.BDCNPJRESP = MV.BDCNPJRESP)';
     end
  else
     begin
       wfieldcategmv = '''OK'' AS BDCNPJINSS,'||
                       '0 AS BDBASEINSSNCOL, 0 AS BDVALORINSSNCOL, 0 AS BDBASEIRRFNCOL, 0 AS BDVALORIRRFNCOL';
       wjoincategmv = '';
     end

  if (coalesce(prpuxafiliais, 0) = 0) then
     begin
       wsql = 'select MV.BDCODEMP, MV.BDCODCOL, MV.BDREFFIM,';
       if (coalesce(prtipocalc, 0) = 1) then
          wsql = wsql|| 'case when (MV.BDTIPOCALC = 0 and MVAUT.BDREFINI <= ' || :prref || ' and (case when (coalesce(MVAUT.BDREFFIM, 0) = 0) then 999999 else MVAUT.BDREFFIM end >= ' || :prref || ')) then 1 else MV.BDTIPOCALC end BDTIPOCALC, ';
       else
          wsql = wsql|| 'MV.BDTIPOCALC, ';

       if (coalesce(prseparacnpj, 0) = 1) then
          wsql = wsql||'MV.BDCNPJRESP, MV.BDCATEGORIAESOCIAL, ';
       else
          wsql = wsql||'CAST(null as VARCHAR(18)) BDCNPJRESP, 0 BDCATEGORIAESOCIAL, ';

       wsql = wsql||'EMP.BDCNPJEMP, MV.BDREFCOL, '||wfieldcategmv||', '|| -- 133599 - Raphael Teodoro - 21/02/2020 - "wfieldcategmv"
                    'MV.BDCODEMPVINC, MV.BDCODCOLVINC, MV.BDCODTERVINC '||
              'from VRHF_EMP_TCOLCON_MVINC MV '||
              'join TEMPRESAS EMP on (EMP.BDCODEMP = MV.BDCODEMP) '||
              'left join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = MV.BDCODEMP and RESC.BDCODCOL = MV.BDCODCOL) '||
              'left join VRH_EMP_TRESCISAO RESC2 on (RESC2.BDCODEMP = MV.BDCODEMPVINC and RESC2.BDCODCOL = MV.BDCODCOLVINC) '||
              'join VRH_EMP_TCOLCON COL on (MV.BDCODEMP = COL.BDCODEMP and MV.BDCODCOL = COL.BDCODCOL) '||
              'left join VRHF_MVAUT MVAUT on ((MVAUT.BDCPF = COL.BDCPFCOL) and '||

              ' (case when coalesce(MVAUT.bdrefini,0) <> 0 then MVAUT.bdrefini else '||prref||' end <= '||prref||') '||
              ' and (case when coalesce(MVAUT.bdreffim,0) <> 0 then MVAUT.bdreffim else '||prref||' end >= '||prref||') '||
              ' ) '||

              wjoincategmv|| -- 133599 - Raphael Teodoro - 21/02/2020
              'where MV.BDREFCOL <= '||prref||' AND (MV.BDREFFIM >= '||prref||' or COALESCE(MV.BDREFFIM,0) = 0) ';

       if (coalesce(prsemempresafilial, 0) = 1) then
          wsql = wsql||' and SUBSTRING(EMP.BDCNPJEMP FROM 1 FOR 10) <> SUBSTRING(MV.BDCNPJRESP FROM 1 FOR 10)';
     
       if (coalesce(prtipocalc, 0) >= 0) then
          begin
            wsql = wsql||' and ((MV.BDTIPOCALC = '||prtipocalc||')';
            if (coalesce(prtipocalc, 0) = 1) then
               wsql = wsql || 'or (MV.BDTIPOCALC = 0 and MVAUT.BDREFINI <= '||prref||' and (case when (coalesce(MVAUT.BDREFFIM, 0) = 0) then 999999 else MVAUT.BDREFFIM end >= '||prref||'))';
            wsql = wsql || ')';
          end
     
       if (coalesce(premp, '') <> '') then
          begin
            if (position('tmp_empresas_select' in upper(premp)) > 0) then
               begin
                 premp = upper(premp);
                 premp = replace(premp, 'SELECT BDCODEMP FROM tmp_empresas_select', '#@$#');
                 premp = replace(upper(premp), 'BDCODEMP', 'MV.BDCODEMP');
                 premp = replace(premp, '#@$#', 'SELECT BDCODEMP FROM tmp_empresas_select');
                 wsql = wsql||' and '||premp;
               end
            else
            wsql = wsql||' and '||replace(upper(premp), 'BDCODEMP', 'MV.BDCODEMP');
     
            if (coalesce(prcol, '') <> '') then
               wsql = wsql||' and '||replace(upper(prcol), 'BDCODCOL', 'MV.BDCODCOL');
          end

       wsql = wsql || wwhererescisao;

       wsql = wsql||' order by MV.BDCODEMP, MV.BDCODCOL, MV.BDREFCOL';

       if (coalesce(prseparacnpj, 0) = 1) then
          wsql = wsql||',MV.BDCNPJRESP, MV.BDCATEGORIAESOCIAL';
     end
  else
     begin
       wsql = 'select MV.BDCODEMP, MV.BDCODCOL, MV.BDREFFIM,';
       if (coalesce(prtipocalc, 0) = 1) then
          wsql = wsql|| 'case when (MV.BDTIPOCALC = 0 and MVAUT.BDREFINI <= ' || :prref || ' and (case when (coalesce(MVAUT.BDREFFIM, 0) = 0) then 999999 else MVAUT.BDREFFIM end >= ' || :prref || ')) then 1 else MV.BDTIPOCALC end BDTIPOCALC, ';
       else
          wsql = wsql|| 'MV.BDTIPOCALC, ';

       if (coalesce(prseparacnpj, 0) = 1) then
          wsql = wsql||'MV.BDCNPJRESP, MV.BDCATEGORIAESOCIAL, ';
       else
          wsql = wsql||'CAST(null AS VARCHAR(18)) BDCNPJRESP, 0 BDCATEGORIAESOCIAL, ';

       wsql = wsql||'EMP.BDCNPJEMP, MV.BDREFCOL, '||wfieldcategmv||', '|| -- 133599 - Raphael Teodoro - 21/02/2020 - "wfieldcategmv"
                    'MV.BDCODEMPVINC, MV.BDCODCOLVINC, MV.BDCODTERVINC '||
              'from TEMPRESAS EMP '||
              'join VRHF_EMP_TCOLCON_MVINC MV on (MV.BDCODEMP = EMP.BDCODEMP) '||
              'join VRH_EMP_TCOLCON COL on (MV.BDCODEMP = COL.BDCODEMP and MV.BDCODCOL = COL.BDCODCOL) '||
              'left join VRHF_MVAUT MVAUT on ((MVAUT.BDCPF = COL.BDCPFCOL) and '||

              ' (case when coalesce(MVAUT.bdrefini,0) <> 0 then MVAUT.bdrefini else '||prref||' end <= '||prref||') '||
              ' and (case when coalesce(MVAUT.bdreffim,0) <> 0 then MVAUT.bdreffim else '||prref||' end >= '||prref||') '||
              ' ) '||

              wjoincategmv|| -- 133599 - Raphael Teodoro - 21/02/2020
              'where MV.BDREFCOL <= '||prref||' AND (MV.BDREFFIM >= '||prref||' or COALESCE(MV.BDREFFIM,0) = 0) ';
     
       if (coalesce(prsemempresafilial, 0) = 1) then
          wsql = wsql||' and SUBSTRING(MV.BDCNPJRESP FROM 1 FOR 10) <> SUBSTRING(EMP.BDCNPJEMP FROM 1 FOR 10)';

       if (coalesce(prtipocalc, 0) >= 0) then
          begin
            wsql = wsql||' and ((MV.BDTIPOCALC = '||prtipocalc||')';
            if (coalesce(prtipocalc, 0) = 1) then
               wsql = wsql || 'or (MV.BDTIPOCALC = 0 and MVAUT.BDREFINI <= '||prref||' and (case when (coalesce(MVAUT.BDREFFIM, 0) = 0) then 999999 else MVAUT.BDREFFIM end >= '||prref||'))';
            wsql = wsql || ')';
          end

       if (coalesce(premp, '') <> '') then
          begin
            if (position('tmp_empresas_select' in upper(premp)) > 0) then
               begin
                 premp = upper(premp);
                 premp = replace(premp, 'SELECT BDCODEMP FROM tmp_empresas_select', '#@$#');
                 premp = replace(upper(premp), 'BDCODEMP', 'EMP.BDCODEMP');
                 premp = replace(premp, '#@$#', 'SELECT BDCODEMP FROM tmp_empresas_select');
                 wsql = wsql||' and (('||premp||') or ('||replace(premp, 'EMP.BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';
               end
            else
            wsql = wsql||' and (('||replace(upper(premp), 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(upper(premp), 'BDCODEMP', 'EMP.BDCODMATRIZ')||'))';
          end

       wsql = wsql||' order by EMP.BDCODEMP, MV.BDCODCOL, MV.BDREFCOL';

       if (coalesce(prseparacnpj, 0) = 1) then
          wsql = wsql||',MV.BDCNPJRESP, MV.BDCATEGORIAESOCIAL';
     end

  BDBASEINSSNCOL   = 0;
  BDVALORINSSNCOL  = 0;
  BDBASEINSS13NCOL  = 0;
  BDVALORINSS13NCOL = 0;
  
  BDBASEIRRFNCOL   = 0;
  BDVALORIRRFNCOL  = 0;
  BDBASEINSS13COL  = 0;
  BDVALORINSS13COL = 0;
  BDBASEIRRF13COL  = 0;
  BDVALORIRRF13COL = 0;
  BDCALCMVNOVO     = 'FALSE';

  wempatu          = 0;
  wcolatu          = 0;
  wrefatu          = 0;
  wcnpjatu         = null;
  wcategatu        = null;

  for execute statement wsql
  into :wcodemp, :wcodcol, :wreffim, :wtipocalc, :wcnpjresp, :wcateg, :wcnpjemp, :wrefcol, :wcnpjinss, :wbase1, :wval1, :wbase2, :wval2, :wcodempvinc, :wcodcolvinc, :wcodtervinc
  do
    begin
      if (wempatu = 0) then
         wempatu = wcodemp;

      if (wcolatu = 0) then
         wcolatu = wcodcol;

      if (wcnpjatu is null) then
         wcnpjatu = coalesce(wcnpjresp, '');

      -- 144124 - Raphael Teodoro - 11/11/2020
      if (COALESCE(wcodtervinc,0) <> 0) then
         begin
           -- Categoria eSocial terceiro
           select first 1 FGTS.BDCATEGORIAESOCIAL
           from VRHF_BASE_TTERC_FGTSGPS FGTS
           where (FGTS.BDCODTER = :wcodtervinc) and (FGTS.BDREFTERC <= :prref)
           order by FGTS.BDCODTER DESC, FGTS.BDREFTERC DESC
           into :wcateg;
         end
      else
      if ((COALESCE(wcodempvinc,0) <> 0) and
          (COALESCE(wcodcolvinc,0) <> 0)) then
         begin
           -- Categoria eSocial
           select first 1 FGTS.BDCATEGORIAESOCIAL
           from VRHF_EMP_TCOLCON_FGTSGPS FGTS
           where (FGTS.BDCODEMP = :wcodempvinc) and (FGTS.BDCODCOL = :wcodcolvinc) and (FGTS.BDREFCOL <= :prref)
           order by FGTS.BDCODEMP DESC, FGTS.BDCODCOL DESC, FGTS.BDREFCOL DESC
           into :wcateg;
         end

      if (wcategatu is null) then
         wcategatu = wcateg;

      if (wempatu <> wcodemp) then
         begin
             wrefiniperiod    = null;
             select first 1 BDREFINIPERIOD from VRH_ESOCIAL_TFASEAMENTO where BDCODEMP = :wempatu into :wrefiniperiod;
             wrefiniperiod    = coalesce(wrefiniperiod, 0);
         end
       
      if ((wempatu <> wcodemp) or (wcolatu <> wcodcol) or ((coalesce(wcnpjatu, '') <> coalesce(wcnpjresp, '')) or (coalesce(wcateg, 0) <> coalesce(wcategatu, 0)) and (pragrupacol = 0))) then
         begin
           if (wrefatu > 0) then
              begin
                BDCODEMP         = wempatu;
                BDCODCOL         = wcolatu;
                BDREFCOL         = wrefatu;

                if (wrefiniperiod = 201805) then
                   begin
                     if (prref >= 201805) then
                        BDCALCMVNOVO = 'TRUE';
                     else
                        BDCALCMVNOVO = 'FALSE';
                   end
                else
                if (wrefiniperiod > 201805) then
                   begin
                     if (prref >= 201901) then
                        BDCALCMVNOVO = 'TRUE';
                     else
                        BDCALCMVNOVO = 'FALSE';
                   end
                else
                   BDCALCMVNOVO = 'TRUE';

                BDCNPJEMP          = wcnpjempatu;
                BDCNPJRESP         = wcnpjatu;
                BDCATEGORIAESOCIAL = wcategatu;
                suspend;
              end

           BDBASEINSSNCOL   = 0;
           BDVALORINSSNCOL  = 0;
           BDBASEINSS13NCOL   = 0;
           BDVALORINSS13NCOL  = 0;

           BDBASEIRRFNCOL   = 0;
           BDVALORIRRFNCOL  = 0;
           BDBASEINSS13COL  = 0;
           BDVALORINSS13COL = 0;
           BDBASEIRRF13COL  = 0;
           BDVALORIRRF13COL = 0;
         
           wempatu          = wcodemp;
           wcolatu          = wcodcol;
           wcnpjatu         = coalesce(wcnpjresp, '');
           wcategatu        = wcateg;
           wrefatu          = 0;
         end

      wcnpjempatu = wcnpjemp;

      if ((coalesce(wreffim, 0) = 0) or (coalesce(wreffim, 0) >= :prref)) then
         begin
           wrefatu = wrefcol;

           if (prref >= 202003) then -- 133599 - Raphael Teodoro - 24/02/2020
              begin
                -- 133599 - Raphael Teodoro - 24/02/2020
                wbase1 = coalesce(wbase1, 0);
                wval1  = coalesce(wval1, 0);
                wbase2 = coalesce(wbase2, 0);
                wval2  = coalesce(wval2, 0);

                if (coalesce(wtipocalc, 0) = 1) then
                   begin
                     -- 13 salario
                     if (wcnpjinss is not null) then
                        begin
                          -- 144124 - Raphael Teodoro - 11/11/2020
                          if (COALESCE(wcodtervinc,0) <> 0) then
                             begin
                               -- Autonomo
                               wbase1 = 0;
                               wval1  = 0;
                               wbase3 = 0;
                               wval3  = 0;
                               wbase4 = 0;
                               wval4  = 0;
                               wbase13fn = 0;
                               wval13fn  = 0;
                             end
                          else
                          if ((COALESCE(wcodempvinc,0) <> 0) and
                              (COALESCE(wcodcolvinc,0) <> 0)) then
                             begin
                               -- 13º salário integral
                               select sum(F13.BDBASEINSS13), sum(F13.BDVALORINSS13)
                               from (SELECT
                                       BDBASEINSS13,
                                       BDVALORINSS13,
                                       3 BDTIPO
                                     FROM VRHF_EMP_T13SAL F
                                     where (F.BDCODEMP = :wcodempvinc) and (F.BDCODCOL = :wcodcolvinc) and (F.BDREF13 = :prref)
                                     ) F13
                               into :wbase1, :wval1;

                               -- 13º salário complementar
                               select sum(C13.BDBASEINSSC13), sum(C13.BDBASEINSSC13)
                               from (SELECT
                                      BDBASEINSSC13,
                                      BDVALORINSSC13,
                                      4 BDTIPO
                                    FROM VRHF_EMP_TC13SAL F
                                    where (F.BDCODEMP = :wcodempvinc) and (F.BDCODCOL = :wcodcolvinc) and (F.BDREF13 = :prref)
                                    ) C13
                               into :wbase3, :wval3;
                             end

                          BDBASEINSS13COL  = BDBASEINSS13COL  + coalesce(wbase1,0) + coalesce(wbase3,0);
                          BDVALORINSS13COL = BDVALORINSS13COL + coalesce(wval1,0) + coalesce(wval3,0);
                        end

                     BDBASEIRRF13COL  = BDBASEIRRF13COL  + wbase2;
                     BDVALORIRRF13COL = BDVALORIRRF13COL + wval2;
                   end
                else
                   begin
                     -- Folha normal
                     if (wcnpjinss is not null) then
                        begin
                          wbase3 = 0;
                          wval3  = 0;
                          wbase4 = 0;
                          wval4  = 0;

                          -- 144124 - Raphael Teodoro - 11/11/2020
                          if (COALESCE(wcodtervinc,0) <> 0) then
                             begin
                               -- Autonomo
                               select SUM(FA.BDBASEINSS), SUM(FA.BDVALORINSS)
                               from VRHF_SP_CONS_IR_TERCEIROS(NULL, 'SERV.BDCODTER = '||:wcodtervinc, :prref, :prref) FA
                               into :wbase1, :wval1;
                             end
                          else
                          if ((COALESCE(wcodempvinc,0) <> 0) and
                              (COALESCE(wcodcolvinc,0) <> 0)) then
                             begin
                               -- Folha normal
                               select sum(F.BDBINSS), sum(F.BDINSS),sum(F.BDBINSS13), sum(F.BDINSS13)
                               from
                                  (select FN.BDBINSSFN BDBINSS, FN.BDINSSFN BDINSS, FN.BDBINSS13FN BDBINSS13, FN.BDINSS13FN BDINSS13
                                  FROM VRHF_EMP_TFOLHANORMAL FN
                                  where (FN.BDCODEMP = :wcodempvinc) and (FN.BDCODCOL = :wcodcolvinc) and (FN.BDREFFN = :prref)
                                  union all
                                  select FT.BDBINSSFT BDBINSS, FT.BDINSSFT BDINSS, FT.BDBINSS13FT BDBINSS13, FT.BDINSS13FT BDINSS13
                                  FROM VRHF_EMP_TFOLHATOMADOR FT
                                  where (FT.BDCODEMP = :wcodempvinc) and (FT.BDCODCOL = :wcodcolvinc) and (FT.BDREFTOMADOR = :prref)
                                  union all
                                  select FI.BDBINSSFN BDBINSS, FI.BDINSSFN BDINSS, FI.BDBINSS13FN BDBINSS13, FI.BDINSS13FN BDINSS13
                                  FROM VRHF_EMP_TFOLHAINT FI
                                  where (FI.BDCODEMP = :wcodempvinc) and (FI.BDCODCOL = :wcodcolvinc) and (FI.BDREFFN = :prref)
                                  union
                                  select FIT.BDBINSSFT BDBINSS, FIT.BDINSSFT BDINSS, FIT.BDBINSS13FT BDBINSS13, FIT.BDINSS13FT BDINSS13
                                  FROM VRHF_EMP_TFOLHATOMINT FIT
                                  where (FIT.BDCODEMP = :wcodempvinc) and (FIT.BDCODCOL = :wcodcolvinc) and (FIT.BDREFTOMADOR = :prref)
                                  ) F
                               into :wbase1, :wval1, :wbase13fn, :wval13fn;

                               if (prtipocalc = -1) then
                                  begin
                                    select sum(FN.BDBINSSFN), sum(FN.BDINSSFN), sum(FN.BDBINSS13FN), sum(FN.BDINSS13FN)
                                    from ( SELECT
                                              BDBINSSFC as BDBINSSFN,
                                              BDINSSFC   as BDINSSFN,
                                              BDBINSS13FC as BDBINSS13FN,
                                              BDINSS13FC as BDINSS13FN,
                                              1 BDTIPO
                                            FROM VRHF_EMP_TFOLHACOMP
                                            where (BDCODEMP = :wcodempvinc) and (BDCODCOL = :wcodcolvinc) and (BDREFFN = :prref)
                                            UNION
                                            SELECT
                                              SUM(x.bdbinssfc) as BDBINSSFN,
                                              SUM(x.bdinssfc) as BDINSSFN,
                                              SUM(x.bdbinss13fc) as BDBINSS13FN,
                                              SUM(x.bdbinss13fc) as BDINSS13FN,
                                              1 BDTIPO
                                            FROM vrhf_emp_tfoltomcomp x
                                            where (BDCODEMP = :wcodempvinc) and (BDCODCOL = :wcodcolvinc) and (BDREFTOMADOR = :prref)
                                            GROUP BY x.bdcodemp, x.bdcodcol, x.bdreftomador
                                         ) FN
                                    into :wbase3, :wval3, :wbase4, :wval4;
                                  end
                             end

                          BDBASEINSSNCOL  = BDBASEINSSNCOL  + coalesce(wbase1,0) + coalesce(wbase3,0);
                          BDVALORINSSNCOL = BDVALORINSSNCOL + coalesce(wval1,0) + coalesce(wval3,0);

                          BDBASEINSS13NCOL  = BDBASEINSS13NCOL  + coalesce(wbase13fn,0) + coalesce(wbase4,0);
                          BDVALORINSS13NCOL = BDVALORINSS13NCOL + coalesce(wval13fn,0) + coalesce(wval4,0);
                        end

                     BDBASEIRRFNCOL  = BDBASEIRRFNCOL  + wbase2;
                     BDVALORIRRFNCOL = BDVALORIRRFNCOL + wval2;
                   end
              end
           else
              begin
                if (coalesce(prseparacnpj, 0) = 1) then
                   begin
                     select SUM(BDBASEINSSNCOL), SUM(BDVALORINSSNCOL), SUM(BDBASEIRRFNCOL), SUM(BDVALORIRRFNCOL)
                     from VRHF_EMP_TCOLCON_MVINC
                     where BDCODEMP = :wcodemp and BDCODCOL = :wcodcol and BDREFCOL <= :wrefcol and BDTIPOCALC = :wtipocalc and BDCNPJRESP = :wcnpjresp and
                           ((COALESCE(BDREFFIM, 0) = 0) or (COALESCE(BDREFFIM, 0) >= :prref))
                     into :wbase1, :wval1, :wbase2, :wval2;
                   end
                else
                   begin
                     select SUM(BDBASEINSSNCOL), SUM(BDVALORINSSNCOL), SUM(BDBASEIRRFNCOL), SUM(BDVALORIRRFNCOL)
                     from VRHF_EMP_TCOLCON_MVINC
                     where BDCODEMP = :wcodemp and BDCODCOL = :wcodcol and BDREFCOL <= :wrefcol and BDTIPOCALC = :wtipocalc and
                           ((COALESCE(BDREFFIM, 0) = 0) or (COALESCE(BDREFFIM, 0) >= :prref))
                     into :wbase1, :wval1, :wbase2, :wval2;
                   end

                wbase1 = coalesce(wbase1, 0);
                wval1  = coalesce(wval1, 0);
                wbase2 = coalesce(wbase2, 0);
                wval2  = coalesce(wval2, 0);

                if (coalesce(wtipocalc, 0) = 1) then
                   begin
                     BDBASEINSS13COL  = wbase1;
                     BDVALORINSS13COL = wval1;
                     BDBASEIRRF13COL  = wbase2;
                     BDVALORIRRF13COL = wval2;
                   end
                else
                   begin
                     BDBASEINSSNCOL  = wbase1;
                     BDVALORINSSNCOL = wval1;
                     BDBASEIRRFNCOL  = wbase2;
                     BDVALORIRRFNCOL = wval2;
                   end
              end
         end
    end

  if (wempatu <> 0 and wcolatu <> 0 and wrefatu <> 0) then
     begin
       BDCODEMP         = wempatu;
       BDCODCOL         = wcolatu;
       BDREFCOL         = wrefatu;

       wrefiniperiod    = null;
       select first 1 BDREFINIPERIOD from VRH_ESOCIAL_TFASEAMENTO where BDCODEMP = :wempatu into: wrefiniperiod;
       wrefiniperiod    = coalesce(wrefiniperiod, 0);

       if (wrefiniperiod = 201805) then
          begin
            if (prref >= 201805) then
               BDCALCMVNOVO = 'TRUE';
            else
               BDCALCMVNOVO = 'FALSE';
          end
       else
       if (wrefiniperiod > 201805) then
          begin
            if (prref >= 201901) then
               BDCALCMVNOVO = 'TRUE';
            else
               BDCALCMVNOVO = 'FALSE';
          end
       else
          BDCALCMVNOVO = 'TRUE';

       BDCNPJEMP          = wcnpjempatu;
       BDCNPJRESP         = wcnpjatu;
       BDCATEGORIAESOCIAL = wcategatu;
       suspend;
     end


-- VERIFICAR SE TEM RESCISÃO DOS COLABORADORES, ONDE OS COLABORADORES ESTÃO VINCULADOS
  if (prref >= 202003) then
     begin
       wwhererescisao = '';

       wwhererescisao = 'and (RESC.BDREFRESCISAO = ' || prref  || ') AND (RESC.BDDATARESCISAO < RESC2.BDDATARESCISAO or RESC2.BDDATARESCISAO is null) ';

       wfieldcategmv = 'MV_COL.BDCNPJRESP AS BDCNPJINSS,'||
                       'MV.BDBASEINSSNCOL, MV.BDVALORINSSNCOL, MV.BDBASEIRRFNCOL, MV.BDVALORIRRFNCOL';
       wjoincategmv  = ' left outer join (select MV_AUX.BDCODEMP, MV_AUX.BDCODCOL, MV_AUX.BDCNPJRESP '||
                                         'from VRHF_EMP_TCOLCON_MVINC MV_AUX '||
                                         'join VRHF_EMP_TCOLCON_FGTSGPS X on (X.BDCODEMP = MV_AUX.BDCODEMP) and (X.BDCODCOL = MV_AUX.BDCODCOL) and (X.BDREFCOL <= MV_AUX.BDREFCOL) '||
                                         'where ';

       if ((coalesce(premp, '') <> '') and (position('tmp_empresas_select' in upper(premp)) = 0)) then
         wjoincategmv = wjoincategmv || '(MV_AUX.BDCODEMP = X.BDCODEMP) and ';

       wjoincategmv = wjoincategmv ||    ' (MV_AUX.BDCATEGORIAESOCIAL not in (701, 711, 712, 721, 722, 723, 731, 734, 738, 741, 751, 761, 771)) or (X.BDCATEGORIAESOCIAL not in (101, 102, 103, 104, 105, 106, 111, 201, 201, 202)) '||
                                         'group by MV_AUX.BDCODEMP, MV_AUX.BDCODCOL, MV_AUX.BDCNPJRESP) MV_COL on (MV_COL.BDCODEMP = MV.BDCODEMP) and (MV_COL.BDCODCOL = MV.BDCODCOL) and (MV_COL.BDCNPJRESP = MV.BDCNPJRESP)';

       if (coalesce(prpuxafiliais, 0) = 0) then
          begin
            wsql = 'select MV.BDCODEMP, MV.BDCODCOL, MV.BDREFFIM,';
            if (coalesce(prtipocalc, 0) = 1) then
               wsql = wsql|| 'case when (MV.BDTIPOCALC = 0 and MVAUT.BDREFINI <= ' || :prref || ' and (case when (coalesce(MVAUT.BDREFFIM, 0) = 0) then 999999 else MVAUT.BDREFFIM end >= ' || :prref || ')) then 1 else MV.BDTIPOCALC end BDTIPOCALC, ';
            else
               wsql = wsql|| 'MV.BDTIPOCALC, ';

            if (coalesce(prseparacnpj, 0) = 1) then
               wsql = wsql||'MV.BDCNPJRESP, MV.BDCATEGORIAESOCIAL, ';
            else
               wsql = wsql||'CAST(null as VARCHAR(18)) BDCNPJRESP, 0 BDCATEGORIAESOCIAL, ';
     
            wsql = wsql||'EMP.BDCNPJEMP, MV.BDREFCOL, '||wfieldcategmv||', '|| -- 133599 - Raphael Teodoro - 21/02/2020 - "wfieldcategmv"
                         'MV.BDCODEMPVINC, MV.BDCODCOLVINC, MV.BDCODTERVINC '||
                   'from VRHF_EMP_TCOLCON_MVINC MV '||
                   'join TEMPRESAS EMP on (EMP.BDCODEMP = MV.BDCODEMP) '||
                   'join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = MV.BDCODEMP and RESC.BDCODCOL = MV.BDCODCOL) '||
                   'left join VRH_EMP_TRESCISAO RESC2 on (RESC2.BDCODEMP = MV.BDCODEMPVINC and RESC2.BDCODCOL = MV.BDCODCOLVINC) '||
                   'join VRH_EMP_TCOLCON COL on (MV.BDCODEMP = COL.BDCODEMP and MV.BDCODCOL = COL.BDCODCOL) '||
                   'left join VRHF_MVAUT MVAUT on (MVAUT.BDCPF = COL.BDCPFCOL) '||
                   wjoincategmv|| -- 133599 - Raphael Teodoro - 21/02/2020
                   'where MV.BDREFCOL <= '||prref||' AND (MV.BDREFFIM >= '||prref||' or COALESCE(MV.BDREFFIM,0) = 0) ';
     
            if (coalesce(prsemempresafilial, 0) = 1) then
               wsql = wsql||' and SUBSTRING(EMP.BDCNPJEMP FROM 1 FOR 10) <> SUBSTRING(MV.BDCNPJRESP FROM 1 FOR 10)';
          
            if (coalesce(prtipocalc, 0) >= 0) then
               begin
                 wsql = wsql||' and ((MV.BDTIPOCALC = '||prtipocalc||')';
                 if (coalesce(prtipocalc, 0) = 1) then
                    wsql = wsql || 'or (MV.BDTIPOCALC = 0 and MVAUT.BDREFINI <= '||prref||' and (case when (coalesce(MVAUT.BDREFFIM, 0) = 0) then 999999 else MVAUT.BDREFFIM end >= '||prref||'))';
                 wsql = wsql || ')';
               end

            if (coalesce(premp, '') <> '') then
               begin
                 if (position('tmp_empresas_select' in upper(premp)) > 0) then
                    begin
                      premp = upper(premp);
                      premp = replace(premp, 'SELECT BDCODEMP FROM tmp_empresas_select', '#@$#');
                      premp = replace(upper(premp), 'BDCODEMP', 'MV.BDCODEMP');
                      premp = replace(premp, '#@$#', 'SELECT BDCODEMP FROM tmp_empresas_select');
                      wsql = wsql||' and '||premp;
                    end
                 else
                 wsql = wsql||' and '||replace(upper(premp), 'BDCODEMP', 'MV.BDCODEMPVINC');
          
                 if (coalesce(prcol, '') <> '') then
                    wsql = wsql||' and '||replace(upper(prcol), 'BDCODCOL', 'MV.BDCODCOLVINC');
               end
     

            wsql = wsql || wwhererescisao;
     
            wsql = wsql||' order by MV.BDCODEMP, MV.BDCODCOL, MV.BDREFCOL';

            if (coalesce(prseparacnpj, 0) = 1) then
               wsql = wsql||',MV.BDCNPJRESP, MV.BDCATEGORIAESOCIAL';
          end
       else
          begin
            wsql = 'select MV.BDCODEMP, MV.BDCODCOL, MV.BDREFFIM,';
            if (coalesce(prtipocalc, 0) = 1) then
               wsql = wsql|| 'case when (MV.BDTIPOCALC = 0 and MVAUT.BDREFINI <= ' || :prref || ' and (case when (coalesce(MVAUT.BDREFFIM, 0) = 0) then 999999 else MVAUT.BDREFFIM end >= ' || :prref || ')) then 1 else MV.BDTIPOCALC end BDTIPOCALC, ';
            else
               wsql = wsql|| 'MV.BDTIPOCALC, ';

            if (coalesce(prseparacnpj, 0) = 1) then
               wsql = wsql||'MV.BDCNPJRESP, MV.BDCATEGORIAESOCIAL, ';
            else
               wsql = wsql||'CAST(null AS VARCHAR(18)) BDCNPJRESP, 0 BDCATEGORIAESOCIAL, ';
     
            wsql = wsql||'EMP.BDCNPJEMP, MV.BDREFCOL, '||wfieldcategmv||', '|| -- 133599 - Raphael Teodoro - 21/02/2020 - "wfieldcategmv"
                         'MV.BDCODEMPVINC, MV.BDCODCOLVINC, MV.BDCODTERVINC '||
                   'from TEMPRESAS EMP '||
                   'join VRHF_EMP_TCOLCON_MVINC MV on (MV.BDCODEMP = EMP.BDCODEMP) '||
                   'join VRH_EMP_TCOLCON COL on (MV.BDCODEMP = COL.BDCODEMP and MV.BDCODCOL = COL.BDCODCOL) '||
                   'left join VRHF_MVAUT MVAUT on (MVAUT.BDCPF = COL.BDCPFCOL) '||
                   wjoincategmv|| -- 133599 - Raphael Teodoro - 21/02/2020
                   'where MV.BDREFCOL <= '||prref||' AND (MV.BDREFFIM >= '||prref||' or COALESCE(MV.BDREFFIM,0) = 0) ';
          
            if (coalesce(prsemempresafilial, 0) = 1) then
               wsql = wsql||' and SUBSTRING(MV.BDCNPJRESP FROM 1 FOR 10) <> SUBSTRING(EMP.BDCNPJEMP FROM 1 FOR 10)';
     
            if (coalesce(prtipocalc, 0) >= 0) then
               begin
                 wsql = wsql||' and ((MV.BDTIPOCALC = '||prtipocalc||')';
                 if (coalesce(prtipocalc, 0) = 1) then
                    wsql = wsql || 'or (MV.BDTIPOCALC = 0 and MVAUT.BDREFINI <= '||prref||' and (case when (coalesce(MVAUT.BDREFFIM, 0) = 0) then 999999 else MVAUT.BDREFFIM end >= '||prref||'))';
                 wsql = wsql || ')';
               end

            if (coalesce(premp, '') <> '') then
               begin
                 if (position('tmp_empresas_select' in upper(premp)) > 0) then
                    begin
                      premp = upper(premp);
                      premp = replace(premp, 'SELECT BDCODEMP FROM tmp_empresas_select', '#@$#');
                      premp = replace(upper(premp), 'BDCODEMP', 'EMP.BDCODEMP');
                      premp = replace(premp, '#@$#', 'SELECT BDCODEMP FROM tmp_empresas_select');
                      wsql = wsql||' and (('||premp||') or ('||replace(premp, 'EMP.BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';
                    end
                 else
                 wsql = wsql||' and (('||replace(upper(premp), 'BDCODEMP', 'EMP.BDCODEMP')||') or ('||replace(upper(premp), 'BDCODEMP', 'EMP.BDCODMATRIZ')||'))';
               end
     
            wsql = wsql||' order by EMP.BDCODEMP, MV.BDCODCOL, MV.BDREFCOL';

            if (coalesce(prseparacnpj, 0) = 1) then
               wsql = wsql||',MV.BDCNPJRESP, MV.BDCATEGORIAESOCIAL';
          end
     
       BDBASEINSSNCOL   = 0;
       BDVALORINSSNCOL  = 0;
       BDBASEIRRFNCOL   = 0;
       BDVALORIRRFNCOL  = 0;
       BDBASEINSS13COL  = 0;
       BDVALORINSS13COL = 0;
       BDBASEIRRF13COL  = 0;
       BDVALORIRRF13COL = 0;
       BDCALCMVNOVO     = 'FALSE';
     
       wempatu          = 0;
       wcolatu          = 0;
       wrefatu          = 0;
       wcnpjatu         = null;
       wcategatu        = null;
     
       for execute statement wsql
       into :wcodempvinc, :wcodcolvinc, :wreffim, :wtipocalc, :wcnpjresp, :wcateg, :wcnpjemp, :wrefcol, :wcnpjinss, :wbase1, :wval1, :wbase2, :wval2, :wcodemp, :wcodcol, :wcodtervinc
       do
         begin
           if (wempatu = 0) then
              wempatu = wcodemp;
     
           if (wcolatu = 0) then
              wcolatu = wcodcol;
     
           if (wcnpjatu is null) then
              wcnpjatu = coalesce(wcnpjresp, '');
     
           -- 144124 - Raphael Teodoro - 11/11/2020
           if (COALESCE(wcodtervinc,0) <> 0) then
              begin
                -- Categoria eSocial terceiro
                select first 1 FGTS.BDCATEGORIAESOCIAL
                from VRHF_BASE_TTERC_FGTSGPS FGTS
                where (FGTS.BDCODTER = :wcodtervinc) and (FGTS.BDREFTERC <= :prref)
                order by FGTS.BDCODTER DESC, FGTS.BDREFTERC DESC
                into :wcateg;
              end
           else
           if ((COALESCE(wcodempvinc,0) <> 0) and
               (COALESCE(wcodcolvinc,0) <> 0)) then
              begin
                -- Categoria eSocial
                select first 1 FGTS.BDCATEGORIAESOCIAL
                from VRHF_EMP_TCOLCON_FGTSGPS FGTS
                where (FGTS.BDCODEMP = :wcodempvinc) and (FGTS.BDCODCOL = :wcodcolvinc) and (FGTS.BDREFCOL <= :prref)
                order by FGTS.BDCODEMP DESC, FGTS.BDCODCOL DESC, FGTS.BDREFCOL DESC
                into :wcateg;
              end
     
           if (wcategatu is null) then
              wcategatu = wcateg;
     
           if (wempatu <> wcodemp) then
              begin
                  wrefiniperiod    = null;
                  select first 1 BDREFINIPERIOD from VRH_ESOCIAL_TFASEAMENTO where BDCODEMP = :wempatu into :wrefiniperiod;
                  wrefiniperiod    = coalesce(wrefiniperiod, 0);
              end

           if ((wempatu <> wcodemp) or (wcolatu <> wcodcol) or (coalesce(wcnpjatu, '') <> coalesce(wcnpjresp, '')) or (coalesce(wcateg, 0) <> coalesce(wcategatu, 0))) then
              begin
                if (wrefatu > 0) then
                   begin
                     BDCODEMP         = wempatu;
                     BDCODCOL         = wcolatu;
                     BDREFCOL         = wrefatu;
     
                     if (wrefiniperiod = 201805) then
                        begin
                          if (prref >= 201805) then
                             BDCALCMVNOVO = 'TRUE';
                          else
                             BDCALCMVNOVO = 'FALSE';
                        end
                     else
                     if (wrefiniperiod > 201805) then
                        begin
                          if (prref >= 201901) then
                             BDCALCMVNOVO = 'TRUE';
                          else
                             BDCALCMVNOVO = 'FALSE';
                        end
                     else
                        BDCALCMVNOVO = 'TRUE';
     
                     BDCNPJEMP          = wcnpjempatu;
                     BDCNPJRESP         = wcnpjatu;
                     BDCATEGORIAESOCIAL = wcategatu;
                     suspend;
                   end
     
                BDBASEINSSNCOL   = 0;
                BDVALORINSSNCOL  = 0;
                BDBASEINSS13NCOL   = 0;
                BDVALORINSS13NCOL  = 0;

                BDBASEIRRFNCOL   = 0;
                BDVALORIRRFNCOL  = 0;
                BDBASEINSS13COL  = 0;
                BDVALORINSS13COL = 0;
                BDBASEIRRF13COL  = 0;
                BDVALORIRRF13COL = 0;
              
                wempatu          = wcodemp;
                wcolatu          = wcodcol;
                wcnpjatu         = coalesce(wcnpjresp, '');
                wcategatu        = wcateg;
                wrefatu          = 0;
              end
     
           wcnpjempatu = wcnpjemp;
     
           if ((coalesce(wreffim, 0) = 0) or (coalesce(wreffim, 0) >= :prref)) then
              begin
                wrefatu = wrefcol;
     
                if (prref >= 202003) then -- 133599 - Raphael Teodoro - 24/02/2020
                   begin
                     -- 133599 - Raphael Teodoro - 24/02/2020
                     wbase1 = coalesce(wbase1, 0);
                     wval1  = coalesce(wval1, 0);
                     wbase2 = coalesce(wbase2, 0);
                     wval2  = coalesce(wval2, 0);
     
                     if (coalesce(wtipocalc, 0) = 1) then
                        begin
                          -- 13 salario
                          if (wcnpjinss is not null) then
                             begin
                               -- 144124 - Raphael Teodoro - 11/11/2020
                               if (COALESCE(wcodtervinc,0) <> 0) then
                                  begin
                                    -- Autonomo
                                    wbase1 = 0;
                                    wval1  = 0;
                                    wbase3 = 0;
                                    wval3 = 0;
                                    wbase4 = 0;
                                    wval4 = 0;
                                  end
                               else
                               if ((COALESCE(wcodempvinc,0) <> 0) and
                                   (COALESCE(wcodcolvinc,0) <> 0)) then
                                  begin
                                    -- 13º salário integral
                                    select sum(F13.BDBASEINSS13), sum(F13.BDINSS13)
                                    from VW_INSS_13S F13
                                    where (F13.BDCODEMP = :wcodempvinc) and (F13.BDCODCOL = :wcodcolvinc) and (F13.BDREF = :prref)
                                    into :wbase1, :wval1;

                                    -- 13º salário complementar
                                    select sum(C13.BDBASEINSSC13), sum(C13.BDINSSC13)
                                    from VW_INSS_C13 C13
                                    where (C13.BDCODEMP = :wcodempvinc) and (C13.BDCODCOL = :wcodcolvinc) and (C13.BDREF = :prref)
                                    into :wbase3, :wval3;
                                  end
     
                               BDBASEINSS13COL  = BDBASEINSS13COL  + coalesce(wbase1,0) + coalesce(wbase3,0);
                               BDVALORINSS13COL = BDVALORINSS13COL + coalesce(wval1,0) + coalesce(wval3,0);
                             end
     
                          BDBASEIRRF13COL  = BDBASEIRRF13COL  + wbase2;
                          BDVALORIRRF13COL = BDVALORIRRF13COL + wval2;
                        end
                     else
                        begin
                          -- Folha normal
                          if (wcnpjinss is not null) then
                             begin
                               wbase3 = 0;
                               wval3  = 0;
                               wbase4 = 0;
                               wval4  = 0;

                               -- 144124 - Raphael Teodoro - 11/11/2020
                               if (COALESCE(wcodtervinc,0) <> 0) then
                                  begin
                                    -- Autonomo
                                    select SUM(FA.BDBASEINSS), SUM(FA.BDVALORINSS)
                                    from VRHF_SP_CONS_IR_TERCEIROS(NULL, 'SERV.BDCODTER = '||:wcodtervinc, :prref, :prref) FA
                                    into :wbase1, :wval1;
                                  end
                               else
                               if ((COALESCE(wcodempvinc,0) <> 0) and
                                   (COALESCE(wcodcolvinc,0) <> 0)) then
                                  begin
                                    -- Folha normal
                                    select sum(BDREFAUXVFN), sum(BDVALVFN) from (
                                       select VERB_FN.BDREFAUXVFN, VERB_FN.BDVALVFN
                                       FROM
                                       (SELECT
                                          FN.BDCODVER,
                                          FN.BDCODEMP,
                                          FN.BDCODCOL,
                                          FN.BDREFFN,
                                          FN.BDREFVFN,
                                          FN.BDREFAUXVFN,
                                          FN.BDVALVFN,
                                          FN.BDIGNREFVFN,
                                          FN.BDIGNVALVFN
                                        FROM VRHF_EMP_TVERBAFN FN
                                        where (FN.BDCODEMP = :wcodempvinc) and (FN.BDCODCOL = :wcodcolvinc) and (FN.BDREFFN = :prref)

                                        UNION

                                        SELECT
                                          FNT.BDCODVER,
                                          FNT.BDCODEMP,
                                          FNT.BDCODCOL,
                                          FNT.BDREFTOMADOR,
                                          FNT.BDREFVFT,
                                          FNT.BDREFAUXVFT,
                                          FNT.BDVALVFT,
                                          FNT.BDIGNREFVFT,
                                          FNT.BDIGNVALVFT
                                        FROM VRHF_EMP_TVERBATOMADOR FNT
                                        where (FNT.BDCODEMP = :wcodempvinc) and (FNT.BDCODCOL = :wcodcolvinc) and (FNT.BDREFTOMADOR = :prref)
                                        ) VERB_FN
                                       JOIN VRH_BASE_TVERBAS VERB ON (VERB.BDCODVER = VERB_FN.BDCODVER)
                                       where (SUBSTRING(VERB.BDCLAVER FROM 1 FOR 7) = '9.010.0')

                                       union all

                                       select VERB_FN.BDREFAUXVFN_SUM, VERB_FN.BDVALVIFN
                                       FROM SP_VRHF_UNION_INT_INTTOM_MES('FN.BDCODEMP = ' || :wcodempvinc, 'FN.BDCODCOL = ' || :wcodcolvinc, null, :prref, 1) VERB_FN
                                       where (VERB_FN.BDCODEMP = :wcodempvinc) and (VERB_FN.BDCODCOL = :wcodcolvinc) and (VERB_FN.BDREFFN = :prref)
                                       and (SUBSTRING(VERB_FN.BDCLAVER FROM 1 FOR 7) = '9.010.0')
                                    )
                                    into :wbase1, :wval1;

                                    if (prtipocalc = -1) then
                                       begin
                                         select sum(FN.BDBINSSFN), sum(FN.BDINSSFN),  sum(FN.BDBINSS13FN), sum(FN.BDINSS13FN)
                                         from
                                            (SELECT
                                              BDCODEMP,
                                              BDCODCOL,
                                              BDREFFN,
                                              BDBINSSFC BDBINSSFN,
                                              BDINSSFC BDINSSFN,
                                              BDBINSS13FC BDBINSS13FN,
                                              BDINSS13FC BDINSS13FN,
                                              0.0 BDBASEINSSC13,
                                              0.0 BDINSSC13,
                                              1 BDTIPO
                                            FROM VRHF_EMP_TFOLHACOMP
                                            where (BDCODEMP = :wcodempvinc) and (BDCODCOL = :wcodcolvinc) and (BDREFFN = :prref)
                                            UNION
                                            SELECT
                                              x.bdcodemp,
                                              x.bdcodcol,
                                              x.bdreftomador,
                                              SUM(x.bdbinssfc) BDBINSSFN,
                                              SUM(x.bdinssfc) BDINSSFN,
                                              SUM(x.bdbinss13fc) BDBINSS13FN,
                                              SUM(x.bdbinss13fc) BDINSS13FN,
                                              0.0 BDBASEINSSC13,
                                              0.0 BDINSSC13,
                                              1 BDTIPO
                                            FROM vrhf_emp_tfoltomcomp x
                                            where (x.BDCODEMP = :wcodempvinc) and (x.BDCODCOL = :wcodcolvinc) and (x.bdreftomador = :prref)
                                            GROUP BY x.bdcodemp, x.bdcodcol, x.bdreftomador
                                            ) FN
                                         into :wbase3, :wval3, :wbase4, :wval4;
                                       end
                                  end
     
                               BDBASEINSSNCOL  = BDBASEINSSNCOL  + coalesce(wbase1,0) + coalesce(wbase3,0);
                               BDVALORINSSNCOL = BDVALORINSSNCOL + coalesce(wval1,0) + coalesce(wval3,0);
                               BDBASEINSS13NCOL  = BDBASEINSS13NCOL  + coalesce(wbase4,0);
                               BDVALORINSS13NCOL = BDVALORINSS13NCOL + coalesce(wval4,0);
                             end
     
                          BDBASEIRRFNCOL  = BDBASEIRRFNCOL  + wbase2;
                          BDVALORIRRFNCOL = BDVALORIRRFNCOL + wval2;
                        end
                   end
                else
                   begin
                     if (coalesce(prseparacnpj, 0) = 1) then
                        begin
                          select SUM(BDBASEINSSNCOL), SUM(BDVALORINSSNCOL), SUM(BDBASEIRRFNCOL), SUM(BDVALORIRRFNCOL)
                          from VRHF_EMP_TCOLCON_MVINC
                          where BDCODEMP = :wcodemp and BDCODCOL = :wcodcol and BDREFCOL <= :wrefcol and BDTIPOCALC = :wtipocalc and BDCNPJRESP = :wcnpjresp and
                                ((COALESCE(BDREFFIM, 0) = 0) or (COALESCE(BDREFFIM, 0) >= :prref))
                          into :wbase1, :wval1, :wbase2, :wval2;
                        end
                     else
                        begin
                          select SUM(BDBASEINSSNCOL), SUM(BDVALORINSSNCOL), SUM(BDBASEIRRFNCOL), SUM(BDVALORIRRFNCOL)
                          from VRHF_EMP_TCOLCON_MVINC
                          where BDCODEMP = :wcodemp and BDCODCOL = :wcodcol and BDREFCOL <= :wrefcol and BDTIPOCALC = :wtipocalc and
                                ((COALESCE(BDREFFIM, 0) = 0) or (COALESCE(BDREFFIM, 0) >= :prref))
                          into :wbase1, :wval1, :wbase2, :wval2;
                        end
     
                     wbase1 = coalesce(wbase1, 0);
                     wval1  = coalesce(wval1, 0);
                     wbase2 = coalesce(wbase2, 0);
                     wval2  = coalesce(wval2, 0);
     
                     if (coalesce(wtipocalc, 0) = 1) then
                        begin
                          BDBASEINSS13COL  = wbase1;
                          BDVALORINSS13COL = wval1;
                          BDBASEIRRF13COL  = wbase2;
                          BDVALORIRRF13COL = wval2;
                        end
                     else
                        begin
                          BDBASEINSSNCOL  = wbase1;
                          BDVALORINSSNCOL = wval1;
                          BDBASEIRRFNCOL  = wbase2;
                          BDVALORIRRFNCOL = wval2;
                        end
                   end
              end
         end

       if (wempatu <> 0 and wcolatu <> 0 and wrefatu <> 0) then
          begin
            BDCODEMP         = wempatu;
            BDCODCOL         = wcolatu;
            BDREFCOL         = wrefatu;
     
            wrefiniperiod    = null;
            select first 1 BDREFINIPERIOD from VRH_ESOCIAL_TFASEAMENTO where BDCODEMP = :wempatu into: wrefiniperiod;
            wrefiniperiod    = coalesce(wrefiniperiod, 0);
     
            if (wrefiniperiod = 201805) then
               begin
                 if (prref >= 201805) then
                    BDCALCMVNOVO = 'TRUE';
                 else
                    BDCALCMVNOVO = 'FALSE';
               end
            else
            if (wrefiniperiod > 201805) then
               begin
                 if (prref >= 201901) then
                    BDCALCMVNOVO = 'TRUE';
                 else
                    BDCALCMVNOVO = 'FALSE';
               end
            else
               BDCALCMVNOVO = 'TRUE';
     
            BDCNPJEMP          = wcnpjempatu;
            BDCNPJRESP         = wcnpjatu;
            BDCATEGORIAESOCIAL = wcategatu;
            suspend;
          end
     end
end^

CREATE OR ALTER TRIGGER TRG_BEF_INS_TCHAVESN FOR TOL_VEF_EMP_TCHAVESN
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE wCodEmp INTEGER;
DECLARE VARIABLE wCodImp INTEGER;
DECLARE VARIABLE wRef INTEGER;
DECLARE VARIABLE wOrdem INTEGER;
DECLARE VARIABLE wOrdemCompl INTEGER;
DECLARE VARIABLE wOrdemSN INTEGER;
BEGIN
  wCodEmp = COALESCE(NEW.BDCODEMP, 0);
  wCodImp = COALESCE(NEW.BDCODIMP, 0);
  wRef    = COALESCE(NEW.BDREFERENCIA, 0);
  wOrdem  = COALESCE(NEW.BDORDEM, 0);
  wOrdemCompl = COALESCE(NEW.BDORDEMCOMPL, 0);
  wOrdemSN    = COALESCE(NEW.BDORDEMCHAVESN, 0);

  IF (wOrdemSN = 0) THEN
    BEGIN
      SELECT FIRST 1 COALESCE(TOL.BDORDEMCHAVESN,0)+1  FROM TOL_VEF_EMP_TCHAVESN TOL
      WHERE TOL.BDCODEMP = :wCodEmp
      AND TOL.BDCODIMP = :wCodImp
      AND TOL.BDREFERENCIA = :wRef
      AND TOL.BDORDEM = :wOrdem
      AND TOL.BDORDEMCOMPL = :wOrdemCompl
      ORDER BY TOL.BDCODEMP DESC,TOL.BDCODIMP DESC,TOL.BDREFERENCIA DESC,TOL.BDORDEM DESC,TOL.BDORDEMCOMPL DESC,TOL.BDORDEMCHAVESN DESC
      INTO :wOrdemSN;

      NEW.BDORDEMCHAVESN = COALESCE(:wOrdemSN, 1);
    END
END^

CREATE OR ALTER TRIGGER trg_bef_ins_tformulasn FOR vef_emp_tformulassn
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE wCodEmp INTEGER;
DECLARE VARIABLE wCodImp INTEGER;
DECLARE VARIABLE wRef INTEGER;
DECLARE VARIABLE wOrdem INTEGER;
DECLARE VARIABLE wOrdemCompl INTEGER;
DECLARE VARIABLE wOrdemSN INTEGER;
BEGIN
  wCodEmp = COALESCE(NEW.BDCODEMP, 0);
  wCodImp = COALESCE(NEW.BDCODIMP, 0);
  wRef    = COALESCE(NEW.BDREFERENCIA, 0);
  wOrdem  = COALESCE(NEW.BDORDEM, 0);
  wOrdemCompl = COALESCE(NEW.BDORDEMCOMPL, 0);
  wOrdemSN    = COALESCE(NEW.BDORDEMFORMULASN, 0);

  /*IF ((:wCodEmp > 0) AND (:wCodImp > 0) AND (:wRef > 0) AND (:wOrdem > 0) AND (:wOrdemCompl > 0) AND (:wOrdemSN = 0)) THEN*/
  IF (:wOrdemSN = 0) THEN
    BEGIN
      SELECT MAX(F.BDORDEMFORMULASN)+1 FROM VEF_EMP_TFORMULASSN F
      WHERE F.BDCODEMP = :wCodEmp
      AND F.BDCODIMP = :wCodImp
      AND F.BDREFERENCIA = :wRef
      AND F.BDORDEM = :wOrdem
      AND F.BDORDEMCOMPL = :wOrdemCompl
      INTO :wOrdemSN;

      NEW.BDORDEMFORMULASN = COALESCE(:wOrdemSN, 1);
    END
END^

/* Restore proc. body: SP_VRHF_EMP_TCOLCON_MVINC_CALC */
CREATE OR ALTER procedure SP_VRHF_EMP_TCOLCON_MVINC_CALC (
    PREMP varchar(25000),
    PRCOL varchar(32000),
    PRREF integer,
    PRTIPOCALC integer = -1,
    PRCARREGARDEMISSOES smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDTIPOCALC integer,
    BDBASEINSS numeric(18,6),
    BDVALORINSS numeric(18,6),
    BDBASEINSS13NCOL numeric(18,6),
    BDVALORINSS13NCOL numeric(18,6),
    BDBASEIRRF numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDCALCMVNOVO DM_BOOLEAN,
    BDCNPJEMP DM_CNPJ_CPF,
    BDCNPJRESP DM_CNPJ_CPF,
    BDCATEGORIAESOCIAL integer)
as
declare variable WSQL varchar(32700);
declare variable WFIELDCATEGMV varchar(50);
declare variable WJOINCATEGMV varchar(5000);
declare variable WREFFIM integer;
declare variable WREFINIPERIOD integer;
declare variable WCNPJINSS type of DM_CNPJ_CPF;
declare variable WCODEMPVINC integer;
declare variable WCODCOLVINC integer;
declare variable WCODTERVINC integer;
declare variable WWHERERESCISAO varchar(500);
declare variable WBASEINSSCOMP numeric(18,6);
declare variable WVALINSSCOMP numeric(18,6);
declare variable WBASEINSSC13 numeric(18,6);
declare variable WVALORINSSC13 numeric(18,6);
declare variable WBASEINSSINT numeric(18,6);
declare variable WVALORINSSINT numeric(18,6);
begin
  -- 133599 - Raphael Teodoro - 21/02/2020
  wwhererescisao = '';
  if (prref >= 202003) then
     begin
       if (PRCARREGARDEMISSOES = 0) then
           wwhererescisao = 'and ( ((RESC.BDDATARESCISAO is null) OR (RESC.BDREFRESCISAO <> ' || PRREF || ')) or ' ||
                             '   ((RESC2.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO <= RESC2.BDDATARESCISAO)) ) ';

       wfieldcategmv = 'MV.BDCNPJRESP AS BDCNPJINSS';
       wjoincategmv = '';
/*       wjoincategmv = ' left outer join (select distinct MV_AUX.BDCODEMP, MV_AUX.BDCODCOL, MV_AUX.BDCNPJRESP'||
                                ' from VRHF_EMP_TCOLCON_MVINC MV_AUX'||
                                ' where (MV_AUX.BDCATEGORIAESOCIAL not in (701, 711, 712, 721, 722, 723, 731, 734, 738, 741, 751, 761, 771) )'||
                                   ' or ((select first 1 X.BDCATEGORIAESOCIAL '||
                                        ' from VRHF_EMP_TCOLCON_FGTSGPS X '||
                                        ' where (X.BDCODEMP = MV_AUX.BDCODEMP) '||
                                          ' and (X.BDCODCOL = MV_AUX.BDCODCOL) '||
                                        ' order by X.BDCATEGORIAESOCIAL desc) not in (101, 102, 103, 104, 105, 106, 111, 201, 201, 202))'||
                                        ') MV_COL on (MV_COL.BDCODEMP = MV.BDCODEMP) and (MV_COL.BDCODCOL = MV.BDCODCOL) and (MV_COL.BDCNPJRESP = MV.BDCNPJRESP)';*/
     end
  else
     begin
       wfieldcategmv = '''OK'' AS BDCNPJINSS';
       wjoincategmv = '';
     end


  wsql = 'select MV.BDCODEMP, MV.BDCODCOL, MV.BDREFFIM, ';
  if (coalesce(prtipocalc, 0) = 1) then
     wsql = wsql|| 'case when (MV.BDTIPOCALC = 0 and MVAUT.BDREFINI <= ' || :prref || ' and (case when (coalesce(MVAUT.BDREFFIM, 0) = 0) then 999999 else MVAUT.BDREFFIM end >= ' || :prref || ')) then 1 else MV.BDTIPOCALC end BDTIPOCALC, ';
  else
     wsql = wsql|| 'MV.BDTIPOCALC, ';

  wsql = wsql|| 'MV.BDCNPJRESP, MV.BDCATEGORIAESOCIAL, EMP.BDCNPJEMP, MV.BDREFCOL, '||wfieldcategmv||', '|| -- 133599 - Raphael Teodoro - 21/02/2020 - "wfieldcategmv"
                'MV.BDBASEINSSNCOL, MV.BDVALORINSSNCOL, MV.BDBASEIRRFNCOL, MV.BDVALORIRRFNCOL, MV.BDCODEMPVINC, MV.BDCODCOLVINC, MV.BDCODTERVINC '||
         'from VRHF_EMP_TCOLCON_MVINC MV '||
         wjoincategmv|| -- 133599 - Raphael Teodoro - 21/02/2020
         'join TEMPRESAS EMP on (EMP.BDCODEMP = MV.BDCODEMP) '||
         'left join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = MV.BDCODEMP and RESC.BDCODCOL = MV.BDCODCOL) '||
         'left join VRH_EMP_TRESCISAO RESC2 on (RESC2.BDCODEMP = MV.BDCODEMPVINC and RESC2.BDCODCOL = MV.BDCODCOLVINC) '||
         'join VRH_EMP_TCOLCON COL on (MV.BDCODEMP = COL.BDCODEMP and MV.BDCODCOL = COL.BDCODCOL) '||
         'left join VRHF_MVAUT MVAUT on ((MVAUT.BDCPF = COL.BDCPFCOL) and '||

         ' (case when coalesce(MVAUT.bdrefini,0) <> 0 then MVAUT.bdrefini else '||prref||' end <= '||prref||') '||
         ' and (case when coalesce(MVAUT.bdreffim,0) <> 0 then MVAUT.bdreffim else '||prref||' end >= '||prref||') '||
         ' ) '||

         'where MV.BDREFCOL <=  '||prref||' '||
           'and ((coalesce(MV.BDREFFIM, 0) = 0) or (coalesce(MV.BDREFFIM, 0) >= '||prref||')) '||
           'and ((coalesce(MV.BDTIPOCALC, 0) = 0) or (coalesce(MV.BDTIPOCALC, 0) = 1 and SUBSTRING(MV.BDREFCOL FROM 1 FOR 4) = '||SUBSTRING(:prref FROM 1 FOR 4)||'))' ;

  if (coalesce(premp, '') <> '') then
     begin
       if (POSITION('tmp_empresas_select' in upper(premp)) > 0) then
          begin
            premp = upper(premp);
            premp = replace(premp, 'SELECT BDCODEMP FROM tmp_empresas_select', '#@$#');
            premp = replace(upper(premp), 'BDCODEMP', 'MV.BDCODEMP');
            premp = replace(premp, '#@$#', 'SELECT BDCODEMP FROM tmp_empresas_select');

            wsql = wsql||' and '||premp;
          end
       else
       wsql = wsql||' and '||replace(upper(premp), 'BDCODEMP', 'MV.BDCODEMP');

       if ((coalesce(prcol, '') <> '') and (not position('TEMP_FILTRO_COLCON_REL', prcol) > 0)) then
          wsql = wsql||' and '||replace(upper(prcol), 'BDCODCOL', 'MV.BDCODCOL');
       else if (position('TEMP_FILTRO_COLCON_REL', prcol) > 0) then
          wsql = wsql||' and '||'MV.'||prcol;
     end

  wsql = wsql || wwhererescisao;

  wsql = wsql||
         ' order by MV.BDCODEMP, MV.BDCODCOL, MV.BDREFCOL DESC ';

  BDCALCMVNOVO     = 'FALSE';

  for execute statement wsql
  into :BDCODEMP, :BDCODCOL, :wreffim, :BDTIPOCALC, :BDCNPJRESP, :BDCATEGORIAESOCIAL, :BDCNPJEMP, :BDREFCOL, :wcnpjinss,
       :BDBASEINSS, :BDVALORINSS, :BDBASEIRRF, :BDVALORIRRF, :wcodempvinc, :wcodcolvinc, :wcodtervinc
  do
    begin
      if ((coalesce(wreffim, 0) = 0) or (coalesce(wreffim, 0) >= :prref)) then
         begin
           wrefiniperiod    = null;
           select first 1 BDREFINIPERIOD from VRH_ESOCIAL_TFASEAMENTO where BDCODEMP = :BDCODEMP into :wrefiniperiod;
           wrefiniperiod    = coalesce(wrefiniperiod, 0);

           if (wrefiniperiod = 201805) then
              begin
                if (prref >= 201805) then
                   BDCALCMVNOVO = 'TRUE';
                else
                   BDCALCMVNOVO = 'FALSE';
              end
           else
           if (wrefiniperiod > 201805) then
              begin
                if (prref >= 201901) then
                   BDCALCMVNOVO = 'TRUE';
                else
                   BDCALCMVNOVO = 'FALSE';
              end
           else
              BDCALCMVNOVO = 'TRUE';

           if ((BDCNPJRESP is null) or (trim(replace(replace(replace(BDCNPJRESP, '.', ''), '-', ''), '/', '')) = '') or (BDCNPJRESP = '00.000.000/0000-00')) then
              BDCNPJRESP = BDCNPJEMP;

           -- 133599 - Raphael Teodoro - 21/02/2020
           if (wcnpjinss is null) then
              begin
                BDBASEINSS  = 0;
                BDVALORINSS = 0;
                BDBASEINSS13NCOL  = 0;
                BDVALORINSS13NCOL = 0;
                WBASEINSSINT  = 0;
                WVALORINSSINT = 0;
              end
           else
           -- 144124 - Raphael Teodoro - 11/11/2020
           if (COALESCE(wcodtervinc,0) <> 0) then
              begin
                -- Categoria eSocial terceiro
                select first 1 FGTS.BDCATEGORIAESOCIAL
                from VRHF_BASE_TTERC_FGTSGPS FGTS
                where (FGTS.BDCODTER = :wcodtervinc) and (FGTS.BDREFTERC <= :prref)
                order by FGTS.BDCODTER DESC, FGTS.BDREFTERC DESC
                into :BDCATEGORIAESOCIAL;

                if (COALESCE(BDTIPOCALC,0) = 0) then
                   begin
                     -- Autonomo
                     for select FA.BDCNPJEMP, SUM(FA.BDBASEINSS), SUM(FA.BDVALORINSS)
                         from VRHF_SP_CONS_IR_TERCEIROS(NULL, 'SERV.BDCODTER = '||:wcodtervinc, :prref, :prref) FA
                         group by BDCNPJEMP
                         into :BDCNPJRESP, :BDBASEINSS, :BDVALORINSS
                     do
                       begin
                         SUSPEND;
                       end
                   end
              end
           else
              begin
                if ((COALESCE(wcodempvinc,0) <> 0) and
                    (COALESCE(wcodcolvinc,0) <> 0)) then
                   begin
                     BDBASEINSS  = 0;
                     BDVALORINSS = 0;
                     BDBASEINSS13NCOL  = 0;
                     BDVALORINSS13NCOL = 0;
                     WBASEINSSINT  = 0;
                     WVALORINSSINT = 0;
                     wbaseinsscomp = 0;
                     wvalinsscomp = 0;
    
                     -- Categoria eSocial
                     select first 1 BDCATEGORIAESOCIAL
                     from VRHF_EMP_TCOLCON_FGTSGPS FGTS
                     where (FGTS.BDCODEMP = :wcodempvinc) and (FGTS.BDCODCOL = :wcodcolvinc) and (FGTS.BDREFCOL <= :prref)
                     order by FGTS.BDCODEMP DESC, FGTS.BDCODCOL DESC, FGTS.BDREFCOL DESC
                     into :BDCATEGORIAESOCIAL;
    
                     if (COALESCE(BDTIPOCALC,0) = 0) then
                        begin
                          -- Folha normal
                          select sum(BDBINSSFN), sum(BDINSSFN), sum(BDBINSS13FN), sum(BDINSS13FN) from (
                             select f.BDBINSSFN, f.BDINSSFN, f.BDBINSS13FN, f.BDINSS13FN
                             from
                              (SELECT FN.BDBINSSFN, FN.BDINSSFN, FN.BDBINSS13FN, FN.BDINSS13FN
                                FROM VRHF_EMP_TFOLHANORMAL FN
                                WHERE (FN.BDCODEMP = :wcodempvinc) and (FN.BDCODCOL = :wcodcolvinc) and (FN.BDREFFN = :prref)
                                UNION
                                SELECT FNT.BDBINSSFT AS BDBINSSFN, FNT.BDINSSFT AS BDINSSFN, FNT.BDBINSS13FT AS BDBINSS13FN, FNT.BDINSS13FT AS BDINSS13FN
                                FROM VRHF_EMP_TFOLHATOMADOR FNT
                                WHERE (FNT.BDCODEMP = :wcodempvinc) and (FNT.BDCODCOL = :wcodcolvinc) and (FNT.BDREFTOMADOR = :prref)
                             ) f
                          )
                          into :BDBASEINSS, :BDVALORINSS, :BDBASEINSS13NCOL, :BDVALORINSS13NCOL;
   
                          -- Folha INTERMITENTE
                          select sum(BDREFAUXVFN_SUM), sum(BDVALVIFN) from (
                             select VERB_FN.BDREFAUXVFN_SUM, VERB_FN.BDVALVIFN
                             FROM SP_VRHF_UNION_INT_INTTOM_MES('FN.BDCODEMP = ' || :wcodempvinc, 'FN.BDCODCOL = ' || :wcodcolvinc, null, :prref, 1) VERB_FN
                             where (VERB_FN.BDCODEMP = :wcodempvinc) and (VERB_FN.BDCODCOL = :wcodcolvinc) and (VERB_FN.BDREFFN = :prref) and (SUBSTRING(VERB_FN.BDCLAVER FROM 1 FOR 7) = '9.010.0')
                          )
                          into :WBASEINSSINT, :WVALORINSSINT;

                          if (BDBASEINSS IS NULL) then
                            BDBASEINSS = 0;
                          if (BDVALORINSS IS NULL) then
                            BDVALORINSS = 0;

                          if (WBASEINSSINT IS NULL) then
                            WBASEINSSINT = 0;
                          if (WVALORINSSINT IS NULL) then
                            WVALORINSSINT = 0;

                          BDBASEINSS = BDBASEINSS + WBASEINSSINT;
                          BDVALORINSS =  BDVALORINSS + WVALORINSSINT;

                          select sum(FN.BDBINSSFN), sum(FN.BDINSSFN)
                          from
                              (
                                       SELECT
                                         BDBINSSFC /*+ BDBINSS13FC*/ BDBINSSFN,
                                         BDINSSFC /*+ BDINSS13FC*/ BDINSSFN,
                                         BDBINSS13FC/*0.0*/ BDBASEINSS13,
                                         BDINSS13FC/*0.0*/ BDINSS13,
                                         0.0 BDBASEINSSC13,
                                         0.0 BDINSSC13,
                                         1 BDTIPO
                                       FROM VRHF_EMP_TFOLHACOMP
                                       where (BDCODEMP = :wcodempvinc) and (BDCODCOL = :wcodcolvinc) and (BDREFFN = :prref)
                                       UNION
                                       SELECT
                                         SUM(x.bdbinssfc) /*+ SUM(x.bdbinss13fc)*/ BDBINSSFN,
                                         SUM(x.bdinssfc) /*+ SUM(x.bdbinss13fc)*/ BDINSSFN,
                                         SUM(x.bdbinss13fc)/*0.0*/ BDBASEINSS13,
                                         SUM(x.bdbinss13fc)/*0.0*/ BDINSS13,
                                         0.0 BDBASEINSSC13,
                                         0.0 BDINSSC13,
                                         1 BDTIPO
                                       FROM vrhf_emp_tfoltomcomp x
                                       where (x.BDCODEMP = :wcodempvinc) and (x.BDCODCOL = :wcodcolvinc) and (x.bdreftomador = :prref)
                                       GROUP BY x.bdcodemp, x.bdcodcol, x.bdreftomador
                              ) FN
                          into :wbaseinsscomp, :wvalinsscomp;

                          if (wbaseinsscomp is not null) then
                             BDBASEINSS = BDBASEINSS + wbaseinsscomp;

                          if (wvalinsscomp is not null) then
                             BDVALORINSS = BDVALORINSS + wvalinsscomp;
                        end
                     else
                        begin
                          -- 13 salario
                          select sum(F13.BDBASEINSS13), sum(F13.BDVALORINSS13)
                          from VRHF_EMP_T13SAL F13
                          where (F13.BDCODEMP = :wcodempvinc) and (F13.BDCODCOL = :wcodcolvinc) and (F13.BDREF13 = :prref)
                          into :BDBASEINSS, :BDVALORINSS;

                          -- 13º salário complementar
                          select sum(C13.BDBASEINSSC13), sum(C13.BDVALORINSSC13)
                          from VRHF_EMP_TC13SAL C13
                          where (C13.BDCODEMP = :wcodempvinc) and (C13.BDCODCOL = :wcodcolvinc) and (C13.BDREFC13 = :prref)
                          into :wbaseinssc13, :wvalorinssc13;

                          BDBASEINSS = COALESCE(BDBASEINSS, 0) + COALESCE(WBASEINSSC13, 0);
                          BDVALORINSS = COALESCE(BDVALORINSS, 0) + COALESCE(WVALORINSSC13, 0);
                        end
                   end

                SUSPEND;
              end
         end
    end


-- VERIFICAR SE TEM RESCISÃO DOS COLABORADORES, ONDE OS COLABORADORES ESTÃO VINCULADOS
  if (prref >= 202003) then
     begin
       wwhererescisao = '';

       wwhererescisao = 'and (RESC.BDREFRESCISAO = ' || PRREF || ') ';

       wfieldcategmv = 'MV_COL.BDCNPJRESP AS BDCNPJINSS';
       wjoincategmv = ' left outer join (select distinct MV_AUX.BDCODEMP, MV_AUX.BDCODCOL, MV_AUX.BDCNPJRESP'||
                                ' from VRHF_EMP_TCOLCON_MVINC MV_AUX'||
                                ' where (MV_AUX.BDCATEGORIAESOCIAL not in (701, 711, 712, 721, 722, 723, 731, 734, 738, 741, 751, 761, 771) )'||
                                   ' or ((select first 1 X.BDCATEGORIAESOCIAL '||
                                        ' from VRHF_EMP_TCOLCON_FGTSGPS X '||
                                        ' where (X.BDCODEMP = MV_AUX.BDCODEMP) '||
                                          ' and (X.BDCODCOL = MV_AUX.BDCODCOL) '||
                                        ' order by X.BDCATEGORIAESOCIAL desc) not in (101, 102, 103, 104, 105, 106, 111, 201, 201, 202))'||
                                        ') MV_COL on (MV_COL.BDCODEMP = MV.BDCODEMP) and (MV_COL.BDCODCOL = MV.BDCODCOL) and (MV_COL.BDCNPJRESP = MV.BDCNPJRESP)';


       wsql = 'select MV.BDCODEMP, MV.BDCODCOL, MV.BDREFFIM, ';
       if (coalesce(prtipocalc, 0) = 1) then
          wsql = wsql|| 'case when (MV.BDTIPOCALC = 0 and MVAUT.BDREFINI <= ' || :prref || ' and (case when (coalesce(MVAUT.BDREFFIM, 0) = 0) then 999999 else MVAUT.BDREFFIM end >= ' || :prref || ')) then 1 else MV.BDTIPOCALC end BDTIPOCALC, ';
       else
          wsql = wsql|| 'MV.BDTIPOCALC, ';

       wsql = wsql|| 'MV.BDCNPJRESP, MV.BDCATEGORIAESOCIAL, EMP.BDCNPJEMP, MV.BDREFCOL, '||wfieldcategmv||', '|| -- 133599 - Raphael Teodoro - 21/02/2020 - "wfieldcategmv"
                     'MV.BDBASEINSSNCOL, MV.BDVALORINSSNCOL, MV.BDBASEIRRFNCOL, MV.BDVALORIRRFNCOL, MV.BDCODEMPVINC, MV.BDCODCOLVINC, MV.BDCODTERVINC '||
              'from VRHF_EMP_TCOLCON_MVINC MV '||
              wjoincategmv|| -- 133599 - Raphael Teodoro - 21/02/2020
              'join TEMPRESAS EMP on (EMP.BDCODEMP = MV.BDCODEMP) '||
              'join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = MV.BDCODEMP and RESC.BDCODCOL = MV.BDCODCOL) '||
              'left join VRH_EMP_TRESCISAO RESC2 on (RESC2.BDCODEMP = MV.BDCODEMPVINC and RESC2.BDCODCOL = MV.BDCODCOLVINC) '||
              'join VRH_EMP_TCOLCON COL on (MV.BDCODEMP = COL.BDCODEMP and MV.BDCODCOL = COL.BDCODCOL) '||
              'left join VRHF_MVAUT MVAUT on (MVAUT.BDCPF = COL.BDCPFCOL) '||
              'where MV.BDREFCOL <=  '||prref||' '||
                'and ((coalesce(MV.BDREFFIM, 0) = 0) or (coalesce(MV.BDREFFIM, 0) >= '||prref||')) '||
                'and ((coalesce(MV.BDTIPOCALC, 0) = 0) or (coalesce(MV.BDTIPOCALC, 0) = 1 and SUBSTRING(MV.BDREFCOL FROM 1 FOR 4) = '||SUBSTRING(:prref FROM 1 FOR 4)||'))' ;
     
       if (coalesce(premp, '') <> '') then
          begin
            if (POSITION('tmp_empresas_select' in upper(premp)) > 0) then
               begin
                 premp = upper(premp);
                 premp = replace(premp, 'SELECT BDCODEMP FROM tmp_empresas_select', '#@$#');
                 premp = replace(upper(premp), 'BDCODEMP', 'MV.BDCODEMP');
                 premp = replace(premp, '#@$#', 'SELECT BDCODEMP FROM tmp_empresas_select');
     
                 wsql = wsql||' and '||premp;
               end
            else
            wsql = wsql||' and '||replace(upper(premp), 'BDCODEMP', 'MV.BDCODEMPVINC');
     
            if (coalesce(prcol, '') <> '') then
               wsql = wsql||' and '||replace(upper(prcol), 'BDCODCOL', 'MV.BDCODCOLVINC');
          end
     
       wsql = wsql || wwhererescisao ||
              ' order by MV.BDCODEMP, MV.BDCODCOL, MV.BDREFCOL DESC ';
     
       BDCALCMVNOVO     = 'FALSE';
     
       for execute statement wsql
       into :wcodempvinc, :wcodcolvinc, :wreffim, :BDTIPOCALC, :BDCNPJRESP, :BDCATEGORIAESOCIAL, :BDCNPJEMP, :BDREFCOL, :wcnpjinss,
            :BDBASEINSS, :BDVALORINSS, :BDBASEIRRF, :BDVALORIRRF, :BDCODEMP, :BDCODCOL, :wcodtervinc
       do
         begin
           if ((coalesce(wreffim, 0) = 0) or (coalesce(wreffim, 0) >= :prref)) then
              begin
                wrefiniperiod    = null;
                select first 1 BDREFINIPERIOD from VRH_ESOCIAL_TFASEAMENTO where BDCODEMP = :BDCODEMP into :wrefiniperiod;
                wrefiniperiod    = coalesce(wrefiniperiod, 0);
     
                if (wrefiniperiod = 201805) then
                   begin
                     if (prref >= 201805) then
                        BDCALCMVNOVO = 'TRUE';
                     else
                        BDCALCMVNOVO = 'FALSE';
                   end
                else
                if (wrefiniperiod > 201805) then
                   begin
                     if (prref >= 201901) then
                        BDCALCMVNOVO = 'TRUE';
                     else
                        BDCALCMVNOVO = 'FALSE';
                   end
                else
                   BDCALCMVNOVO = 'TRUE';
     
                if ((BDCNPJRESP is null) or (trim(replace(replace(replace(BDCNPJRESP, '.', ''), '-', ''), '/', '')) = '') or (BDCNPJRESP = '00.000.000/0000-00')) then
                   BDCNPJRESP = BDCNPJEMP;
     
                -- 133599 - Raphael Teodoro - 21/02/2020
                if (wcnpjinss is null) then
                   begin
                     BDBASEINSS  = 0;
                     BDVALORINSS = 0;
                     WBASEINSSINT  = 0;
                     WVALORINSSINT = 0;
                   end
                else
                -- 144124 - Raphael Teodoro - 11/11/2020
                if (COALESCE(wcodtervinc,0) <> 0) then
                   begin
                     -- Categoria eSocial terceiro
                     select first 1 FGTS.BDCATEGORIAESOCIAL
                     from VRHF_BASE_TTERC_FGTSGPS FGTS
                     where (FGTS.BDCODTER = :wcodtervinc) and (FGTS.BDREFTERC <= :prref)
                     order by FGTS.BDCODTER DESC, FGTS.BDREFTERC DESC
                     into :BDCATEGORIAESOCIAL;
     
                     if (COALESCE(BDTIPOCALC,0) = 0) then
                        begin
                          -- Autonomo
                          for select FA.BDCNPJEMP, SUM(FA.BDBASEINSS), SUM(FA.BDVALORINSS)
                              from VRHF_SP_CONS_IR_TERCEIROS(NULL, 'SERV.BDCODTER = '||:wcodtervinc, :prref, :prref) FA
                              group by BDCNPJEMP
                              into :BDCNPJRESP, :BDBASEINSS, :BDVALORINSS
                          do
                            begin
                              SUSPEND;
                            end
                        end
                   end
                else
                   begin
                     if ((COALESCE(wcodempvinc,0) <> 0) and
                         (COALESCE(wcodcolvinc,0) <> 0)) then
                        begin
                          BDBASEINSS  = 0;
                          BDVALORINSS = 0;
                          wbaseinsscomp = 0;
                          wvalinsscomp = 0;
         
                          -- Categoria eSocial
                          select first 1 BDCATEGORIAESOCIAL
                          from VRHF_EMP_TCOLCON_FGTSGPS FGTS
                          where (FGTS.BDCODEMP = :wcodempvinc) and (FGTS.BDCODCOL = :wcodcolvinc) and (FGTS.BDREFCOL <= :prref)
                          order by FGTS.BDCODEMP DESC, FGTS.BDCODCOL DESC, FGTS.BDREFCOL DESC
                          into :BDCATEGORIAESOCIAL;
         
                          if (COALESCE(BDTIPOCALC,0) = 0) then
                             begin
                               -- Folha normal
                              select sum(BDREFAUXVFN), sum(BDVALVFN) from (
                                 select VERB_FN.BDREFAUXVFN, VERB_FN.BDVALVFN
                                 from
                                  (SELECT FN.BDCODVER, FN.BDREFAUXVFN, FN.BDVALVFN
                                    FROM VRHF_EMP_TVERBAFN FN
                                    WHERE (FN.BDCODEMP = :wcodempvinc) and (FN.BDCODCOL = :wcodcolvinc) and (FN.BDREFFN = :prref)
                                    UNION
                                    SELECT FNT.BDCODVER, FNT.BDREFAUXVFT AS BDREFAUXVFN, FNT.BDVALVFT AS BDVALVFN
                                    FROM VRHF_EMP_TVERBATOMADOR FNT
                                    WHERE (FNT.BDCODEMP = :wcodempvinc) and (FNT.BDCODCOL = :wcodcolvinc) and (FNT.BDREFTOMADOR = :prref)
                                 ) VERB_FN
                                 JOIN VRH_BASE_TVERBAS VERB ON (VERB.BDCODVER = VERB_FN.BDCODVER)
                                 where (SUBSTRING(VERB.BDCLAVER FROM 1 FOR 7) = '9.010.0')
                              )
                              into :BDBASEINSS, :BDVALORINSS;
   
                              -- Folha INTERMITENTE
                              select sum(BDREFAUXVFN_SUM), sum(BDVALVIFN) from (
                                 select VERB_FN.BDREFAUXVFN_SUM, VERB_FN.BDVALVIFN
                                 FROM SP_VRHF_UNION_INT_INTTOM_MES('FN.BDCODEMP = ' || :wcodempvinc, 'FN.BDCODCOL = ' || :wcodcolvinc, null, :prref, 1) VERB_FN
                                 where (VERB_FN.BDCODEMP = :wcodempvinc) and (VERB_FN.BDCODCOL = :wcodcolvinc) and (VERB_FN.BDREFFN = :prref) and (SUBSTRING(VERB_FN.BDCLAVER FROM 1 FOR 7) = '9.010.0')
                              )
                              into :WBASEINSSINT, :WVALORINSSINT;

                              if (BDBASEINSS IS NULL) then
                                BDBASEINSS = 0;
                              if (BDVALORINSS IS NULL) then
                                BDVALORINSS = 0;
                              BDBASEINSS = BDBASEINSS + WBASEINSSINT;
                              BDVALORINSS =  BDVALORINSS + WVALORINSSINT;

                               select sum(FN.BDBINSSFN), sum(FN.BDINSSFN)
                               from (
                                          SELECT
                                            BDBINSSFC /*+ BDBINSS13FC */  BDBINSSFN,
                                            BDINSSFC /*+ BDINSS13FC */ BDINSSFN,
                                            BDBINSS13FC /*0.0*/ BDBASEINSS13,
                                            BDINSS13FC/*0.0*/ BDINSS13,
                                            0.0 BDBASEINSSC13,
                                            0.0 BDINSSC13,
                                            1 BDTIPO
                                          FROM VRHF_EMP_TFOLHACOMP
                                          where (BDCODEMP = :wcodempvinc) and (BDCODCOL = :wcodcolvinc) and (BDREFFN = :prref)
                                          UNION
                                          SELECT
                                            SUM(x.bdbinssfc) /*+ SUM(x.bdbinss13fc)*/ BDBINSSFN,
                                            SUM(x.bdinssfc) /*+ SUM(x.bdbinss13fc)*/ BDINSSFN,
                                            SUM(x.bdbinss13fc)/*0.0*/ BDBASEINSS13,
                                            SUM(x.bdbinss13fc)/*0.0*/ BDINSS13,
                                            0.0 BDBASEINSSC13,
                                            0.0 BDINSSC13,
                                            1 BDTIPO
                                          FROM vrhf_emp_tfoltomcomp x
                                          where (X.BDCODEMP = :wcodempvinc) and (X.BDCODCOL = :wcodcolvinc) and (X.bdreftomador = :prref)
                                          GROUP BY x.bdcodemp, x.bdcodcol, x.bdreftomador)
                                FN
                               into :wbaseinsscomp, :wvalinsscomp;
     
                               if (wbaseinsscomp is not null) then
                                  BDBASEINSS = BDBASEINSS + wbaseinsscomp;
     
                               if (wvalinsscomp is not null) then
                                  BDVALORINSS = BDVALORINSS + wvalinsscomp;
                             end
                          else
                             begin
                               -- 13 salario
                               select sum(F13.BDBASEINSS13), sum(F13.BDVALORINSS13)
                               from VRHF_EMP_T13SAL F13
                               where (F13.BDCODEMP = :wcodempvinc) and (F13.BDCODCOL = :wcodcolvinc) and (F13.BDREF13 = :prref)
                               into :BDBASEINSS, :BDVALORINSS;

                               -- 13º salário complementar
                               select sum(C13.BDBINSS13C13), sum(C13.BDINSS13C13)
                               from VRHF_EMP_TC13SAL C13
                               where (C13.BDCODEMP = :wcodempvinc) and (C13.BDCODCOL = :wcodcolvinc) and (C13.BDREFC13 = :prref)
                               into :wbaseinssc13, :wvalorinssc13;
     
                               BDBASEINSS = COALESCE(BDBASEINSS, 0) + COALESCE(WBASEINSSC13, 0);
                               BDVALORINSS = COALESCE(BDVALORINSS, 0) + COALESCE(WVALORINSSC13, 0);
                             end
                        end
         
                     SUSPEND;
                   end
              end
         end
     end
end^

CREATE OR ALTER procedure SP_VRHF_BASE_TTERC_MVINC_CALC (
    PREMP varchar(25000),
    PRCOL varchar(32000),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDBASEINSS numeric(18,6),
    BDVALORINSS numeric(18,6),
    BDBASEIRRF numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDCALCMVNOVO DM_BOOLEAN,
    BDCNPJEMP DM_CNPJ_CPF,
    BDCNPJRESP DM_CNPJ_CPF,
    BDCATEGORIAESOCIAL integer,
    BDTIPOCALC integer,
    BDCODEMPVINC integer,
    BDCODCOLVINC integer,
    BDCODTERVINC integer)
as
declare variable WSQL varchar(32700);
declare variable WREFFIM integer;
declare variable WREFINIPERIOD integer;
declare variable WCODEMPVINC integer;
declare variable WCODCOLVINC integer;
declare variable WCODTERVINC integer;
declare variable WCODEMPSTR varchar(25);
begin
  wsql = 'select MV.BDCODEMP, MV.BDCODTER, MV.BDREFTERCFIM, MV.BDCNPJRESP, MV.BDCATEGORIAESOCIAL, EMP.BDCNPJEMP, MV.BDREFTERC, MV.BDBASEINSSNTER, '||
                'MV.BDVALORINSSNTER, MV.BDBASEIRRFNTER, MV.BDVALORIRRFNTER, MV.BDCODEMPVINC, MV.BDCODCOLVINC, MV.BDCODTERVINC '||
         'from VRHF_BASE_TTERC_MVINC MV '||
         'left outer join TEMPRESAS EMP on (EMP.BDCODEMP = MV.BDCODEMP) '||
         'where MV.BDREFTERC <=  '||prref||' and ((coalesce(MV.BDREFTERCFIM, 0) = 0) or (coalesce(MV.BDREFTERCFIM, 0) >= '||prref||')) ' ;

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||' and ((MV.BDCODEMP is NULL) or '||replace(upper(premp), 'BDCODEMP', 'MV.BDCODEMP')||')';

       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||replace(upper(prcol), 'BDCODTER', 'MV.BDCODTER');
     end

  wsql = wsql||
         ' order by MV.BDCODEMP, MV.BDCODTER, MV.BDREFTERC DESC ';

  BDCALCMVNOVO = 'FALSE';
  BDTIPOCALC   = 0;

  for execute statement wsql
  into :BDCODEMP, :BDCODCOL, :wreffim, :BDCNPJRESP, :BDCATEGORIAESOCIAL, :BDCNPJEMP, :BDREFCOL, :BDBASEINSS, :BDVALORINSS, :BDBASEIRRF, :BDVALORIRRF,
       :wcodempvinc, :wcodcolvinc, :wcodtervinc
  do
    begin
      bdcodempvinc = wcodempvinc;
      bdcodcolvinc = wcodcolvinc;
      BDCODTERVINC = null;

      if ((coalesce(wreffim, 0) = 0) or (coalesce(wreffim, 0) >= :prref)) then
         begin
           wrefiniperiod    = null;
           select first 1 BDREFINIPERIOD from VRH_ESOCIAL_TFASEAMENTO where BDCODEMP = :BDCODEMP into :wrefiniperiod;
           wrefiniperiod    = coalesce(wrefiniperiod, 0);

           if (wrefiniperiod = 201805) then
              begin
                if (prref >= 201805) then
                   BDCALCMVNOVO = 'TRUE';
                else
                   BDCALCMVNOVO = 'FALSE';
              end
           else
           if (wrefiniperiod > 201805) then
              begin
                if (prref >= 201901) then
                   BDCALCMVNOVO = 'TRUE';
                else
                   BDCALCMVNOVO = 'FALSE';
              end
           else
              BDCALCMVNOVO = 'TRUE';

           if ((BDCNPJRESP is null) or (trim(replace(replace(replace(BDCNPJRESP, '.', ''), '-', ''), '/', '')) = '') or (BDCNPJRESP = '00.000.000/0000-00')) then
              BDCNPJRESP = BDCNPJEMP;

           BDTIPOCALC = 0;

           -- 144124 - Raphael Teodoro - 11/11/2020
           if ((COALESCE(wcodtervinc,0) <> 0) or
               ((COALESCE(wcodempvinc,0) <> 0) and
                (COALESCE(wcodcolvinc,0) <> 0))) then
              begin
                BDBASEINSS  = NULL;
                BDVALORINSS = NULL;

                if (COALESCE(wcodtervinc,0) <> 0) then
                   begin
                     BDCODTERVINC = wcodtervinc;
                     bdcodcolvinc = null;

                     -- Categoria eSocial terceiro
                     select first 1 FGTS.BDCATEGORIAESOCIAL
                     from VRHF_BASE_TTERC_FGTSGPS FGTS
                     where (FGTS.BDCODTER = :wcodtervinc) and (FGTS.BDREFTERC <= :prref)
                     order by FGTS.BDCODTER DESC, FGTS.BDREFTERC DESC
                     into :BDCATEGORIAESOCIAL;

                     -- Autonomo
                     if (COALESCE(wcodempvinc,0) <> 0) then
                        wcodempstr = 'SERV.BDCODEMP = '||wcodempvinc;
                     else
                        wcodempstr = NULL;

                     for select FA.BDCODEMP, EMP.BDCNPJEMP, SUM(FA.BDBASEINSS), SUM(FA.BDVALORINSS)
                         from VRHF_SP_CONS_IR_TERCEIROS(:wcodempstr, 'SERV.BDCODTER = '||:wcodtervinc, :prref, :prref) FA
                         left outer join TEMPRESAS EMP on (EMP.BDCODEMP = FA.BDCODEMP)
                         group by BDCODEMP, BDCNPJEMP
                         into :BDCODEMP, :BDCNPJRESP, :BDBASEINSS, :BDVALORINSS
                     do
                       begin
                         SUSPEND;
                       end
                   end
                else
                   begin
                     bdcodcolvinc = wcodcolvinc;

                     -- Categoria eSocial
                     select first 1 FGTS.BDCATEGORIAESOCIAL
                     from VRHF_EMP_TCOLCON_FGTSGPS FGTS
                     where (FGTS.BDCODEMP = :wcodempvinc) and (FGTS.BDCODCOL = :wcodcolvinc) and (FGTS.BDREFCOL <= :prref)
                     order by FGTS.BDCODEMP DESC, FGTS.BDCODCOL DESC, FGTS.BDREFCOL DESC
                     into :BDCATEGORIAESOCIAL;

                     -- Folha normal
                     select FN.BDBINSSFN, FN.BDINSSFN
                     from VW_INSS_FOL_NORMAL FN
                     where (FN.BDCODEMP = :wcodempvinc) and (FN.BDCODCOL = :wcodcolvinc) and (FN.BDREF = :prref)
                     into :BDBASEINSS, :BDVALORINSS;

                     SUSPEND;
                   end
              end
           else
              SUSPEND;
         end
    end
end^

create or alter trigger VFIN_ESC_TVINC_PAG_SERVIC_BI0 for VFIN_ESC_TVINC_PAG_SERVIC
active before insert position 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDCHAVESEQ is null) or (new.BDCHAVESEQ = 0)) then
  begin
    select coalesce((max(BDCHAVESEQ) + 1), 1)
    from VFIN_ESC_TVINC_PAG_SERVIC
    where (BDCODESC = new.BDCODESC)
    into VCODIGO;
    new.BDCHAVESEQ = VCODIGO;
  end
end^

CREATE or ALTER trigger vfin_esc_tconf_conta_contab_bi0 for vfin_esc_tconf_conta_contabil
active before insert position 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDCHAVECONF is null) or (new.BDCHAVECONF = 0)) then
  begin
    select coalesce((max(BDCHAVECONF) + 1), 1)
    from VFIN_ESC_TCONF_CONTA_CONTABIL
    where (BDCHAVECTABAN = new.BDCHAVECTABAN)
    into VCODIGO;
    new.BDCHAVECONF = VCODIGO;
  end
end^

CREATE or alter trigger vfin_esc_tvinc_desp_movent_bi0 for vfin_esc_tvinc_desp_movent
active before insert position 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDCHAVESEQ is null) or (new.BDCHAVESEQ = 0)) then
  begin
    select coalesce((max(BDCHAVESEQ) + 1), 1)
    from VFIN_ESC_TVINC_DESP_MOVENT
    where (BDCODESC = new.BDCODESC)
    into VCODIGO;
    new.BDCHAVESEQ = VCODIGO;
  end
end^


CREATE OR ALTER procedure SP_APURACAOISS_BLOCOB_B470 (
    PREMPRESAS varchar(1000),
    PRREFINI integer,
    PRREFFIM integer,
    PRREL varchar(5))
returns (
    BDCODEMP integer,
    BDREFLAN integer,
    BDNRCAMPO varchar(2),
    BDDESCRICAO varchar(150),
    BDVALOR numeric(15,2),
    BDLINHA varchar(1000),
    BDCHAVEREG varchar(50))
as
declare variable WBDCODEMP integer;
declare variable WBDREFLAN integer;
declare variable VL_CONT DM_NUMERIC_15_2;
declare variable VL_MAT_TERC DM_NUMERIC_15_2;
declare variable VL_MAT_PROP DM_NUMERIC_15_2;
declare variable VL_SUB DM_NUMERIC_15_2;
declare variable VL_ISNT DM_NUMERIC_15_2;
declare variable VL_DED_BC DM_NUMERIC_15_2;
declare variable VL_BC_ISS DM_NUMERIC_15_2;
declare variable VL_BC_ISS_RT DM_NUMERIC_15_2;
declare variable VL_ISS DM_NUMERIC_15_2;
declare variable VL_ISS_RT DM_NUMERIC_15_2;
declare variable VL_DED DM_NUMERIC_15_2;
declare variable VL_ISS_REC DM_NUMERIC_15_2;
declare variable VL_ISS_ST DM_NUMERIC_15_2;
declare variable VL_ISS_REC_UNI DM_NUMERIC_15_2;
declare variable WSQL varchar(7500);
begin
  /* Procedure Text */

   wsql = 'select M.BDCODEMP, M.BDREFLAN, VL_CONT, VL_MAT_TERC, VL_MAT_PROP, VL_SUB, VL_ISNT, ';
   wsql = wsql || '       (VL_MAT_TERC + VL_MAT_PROP + VL_SUB + VL_ISNT) /*B + C + D + E*/ VL_DED_BC, VL_BC_ISS, ';
   wsql = wsql || '        VL_BC_ISS_RT, VL_ISS, VL_ISS_RT, /*tabela de ajustes*/ VL_DED, ';
   wsql = wsql || '       /*I - J - K*/ (VL_ISS - (VL_ISS_RT + VL_DED)) VL_ISS_REC, iif(VL_ISS_ST > 0,VL_ISS_ST,0) , VL_ISS_REC_UNI ';
   wsql = wsql || 'from ( ';
   wsql = wsql || '       select M.BDCODEMP, M.BDREFLAN, sum(M.VL_CONT) VL_CONT, sum(coalesce(M.VL_MAT_TERC, 0)) VL_MAT_TERC, ';
   wsql = wsql || '             Sum(VL_MAT_PROP) VL_MAT_PROP, sum(VL_SUB) VL_SUB, ';
   wsql = wsql || '             sum(VL_ISNT) VL_ISNT, Sum(VL_DED_BC) VL_DED_BC, ';
   wsql = wsql || '             sum(VL_BC_ISS) VL_BC_ISS, Sum(VL_BC_ISS_RT) VL_BC_ISS_RT, Sum(VL_ISS) VL_ISS, ';
   wsql = wsql || '             sum(VL_ISS_RT) VL_ISS_RT, Sum(VL_DED) VL_DED, Sum(VL_ISS_REC) VL_ISS_REC, Sum(VL_ISS_ST) VL_ISS_ST, Sum(VL_ISS_REC_UNI) VL_ISS_REC_UNI ';
   wsql = wsql || '      from ( ';
   wsql = wsql || '             select M.BDCODEMP, M.BDREFLAN, sum(M.BDVLRCONTAB) VL_CONT, sum(coalesce(M.BDVLRMATERIAIS, 0)) VL_MAT_TERC, ';
   wsql = wsql || '                     0 VL_MAT_PROP, sum(coalesce(M.BDVLRSUBEMPREITEIRAS, 0)) VL_SUB, ';
   wsql = wsql || '                     (sum(coalesce(M.BDISENTASISSSER, 0)) + sum(coalesce(M.BDOUTRASISSSER, 0))) VL_ISNT, 0 VL_DED_BC, ';
   wsql = wsql || '                     sum(coalesce(M.BDBCISSSER, 0)) VL_BC_ISS, SUM(iif(m.BDISSRET > 0, M.BDVLRCONTAB, 0)) VL_BC_ISS_RT , sum(coalesce(M.BDVLRISSSER, 0)) VL_ISS, ';
   wsql = wsql || '                     sum(coalesce(M.BDISSRET, 0)) VL_ISS_RT, 0 VL_DED, 0 VL_ISS_REC, 0 VL_ISS_ST, 0 VL_ISS_REC_UNI ';
   wsql = wsql || '              from ( ';
   wsql = wsql || '                    select M.BDCODEMP, M.BDCHAVE, M.BDDATAEMISSAO, M.BDCODCID, M.BDCODTER, M.BDNUMDOCINI, M.BDESPECIE, ';
   wsql = wsql || '                           M.BDSERIE, M.BDNUMDOCFIM, M.BDTIPLAN, M.BDREFLAN, M.BDCODTPNF, M.BDCODSITNF, M.BDCODTIPO, ';
   wsql = wsql || '                           M.BDCHAVENFE, M.BDVALORNOTA, M.BDDESCONTONOTA, M.BDDT_EXE_SERV, I.BDVLRCONTAB, I.BDISENTASISSSER, ';
   wsql = wsql || '                           I.BDOUTRASISSSER, D.BDVLRMATERIAIS, D.BDVLRSUBEMPREITEIRAS, I.BDALIQREDBCISSSER, I.BDBCISSSER, ';
   wsql = wsql || '                           I.BDVLRISSSER, I.BDCODOBS, R.BDISSRET ';
   wsql = wsql || '                    from (select M.BDCODEMP, M.BDCHAVE, M.BDDATAEMISSAO, M.BDCODCID, M.BDCODTER, M.BDNUMDOCINI, M.BDESPECIE, ';
   wsql = wsql || '                                 M.BDSERIE, M.BDNUMDOCFIM, M.BDTIPLAN, M.BDREFLAN, M.BDCODTPNF, M.BDCODSITNF, M.BDCODTIPO, ';
   wsql = wsql || '                                 M.BDCHAVENFE, M.BDVALORNOTA, M.BDDESCONTONOTA, M.BDDT_EXE_SERV ';
   wsql = wsql || '                          from VEF_EMP_TMOVSER M ';
   wsql = wsql || '                          where M.BDTIPLAN = 0 /*Somente emitidos*/ and M.BDREFLAN between '||prrefini ||' and '||prreffim ||'  ';
   wsql = wsql || '                           AND (m.BDCODSITNF not in (2,3,4,5)) and ';
   if ((prempresas <> '') and (prempresas is not null)) then
     wsql = wsql ||prempresas;
   wsql = wsql || '                          ) M ';
   wsql = wsql || '                    left outer join VEF_EMP_TMOVSERITENS I on (M.BDCODEMP = I.BDCODEMP and M.BDCHAVE = I.BDCHAVE) ';
   wsql = wsql || '                    left outer join VEF_EMP_TMOVSERDED D on (M.BDCODEMP = D.BDCODEMP and M.BDCHAVE = D.BDCHAVE) ';
   wsql = wsql || '                    left outer join VEF_EMP_TMOVSERRET R on (M.BDCODEMP = R.BDCODEMP and M.BDCHAVE = R.BDCHAVE)) M ';
   wsql = wsql || '             group by M.BDCODEMP, M.BDREFLAN ';
   wsql = wsql || '             union all ';
   wsql = wsql || '             select M.BDCODEMP, M.BDREFLAN, 0 VL_CONT, 0 VL_MAT_TERC, 0 VL_MAT_PROP, 0 VL_SUB, 0 VL_ISNT, 0 VL_DED_BC, ';
   wsql = wsql || '             0 VL_BC_ISS, 0 VL_BC_ISS_RT, 0 VL_ISS, 0 VL_ISS_RT, 0 VL_DED, 0 VL_ISS_REC, sum(coalesce(M.BDISSRET, 0)) VL_ISS_ST, ';
   wsql = wsql || '             0 VL_ISS_REC_UNI ';
   wsql = wsql || '             from ( ';
   wsql = wsql || '                    select M.BDCODEMP, M.BDCHAVE, M.BDDATAEMISSAO, M.BDCODCID, M.BDCODTER, M.BDNUMDOCINI, M.BDESPECIE, ';
   wsql = wsql || '                           M.BDSERIE, M.BDNUMDOCFIM, M.BDTIPLAN, M.BDREFLAN, M.BDCODTPNF, M.BDCODSITNF, M.BDCODTIPO,  ';
   wsql = wsql || '                           M.BDCHAVENFE, M.BDVALORNOTA, M.BDDESCONTONOTA, M.BDDT_EXE_SERV, I.BDVLRCONTAB, I.BDISENTASISSSER,  ';
   wsql = wsql || '                           I.BDOUTRASISSSER, D.BDVLRMATERIAIS, D.BDVLRSUBEMPREITEIRAS, I.BDALIQREDBCISSSER, I.BDBCISSSER,  ';
   wsql = wsql || '                           I.BDVLRISSSER, I.BDCODOBS, R.BDISSRET ';
   wsql = wsql || '                    from (select M.BDCODEMP, M.BDCHAVE, M.BDDATAEMISSAO, M.BDCODCID, M.BDCODTER, M.BDNUMDOCINI, M.BDESPECIE,  ';
   wsql = wsql || '                                 M.BDSERIE, M.BDNUMDOCFIM, M.BDTIPLAN, M.BDREFLAN, M.BDCODTPNF, M.BDCODSITNF, M.BDCODTIPO,  ';
   wsql = wsql || '                                 M.BDCHAVENFE, M.BDVALORNOTA, M.BDDESCONTONOTA, M.BDDT_EXE_SERV  ';
   wsql = wsql || '                          from VEF_EMP_TMOVSER M  ';
   wsql = wsql || '                          where M.BDTIPLAN = 1 /*Somente Recebidos*/ and M.BDREFLAN between '||prrefini ||' and '||prreffim ||' ';
   wsql = wsql || '                           AND (m.BDCODSITNF not in (2,3,4,5)) and ';
   if ((prempresas <> '') and (prempresas is not null)) then
     wsql = wsql ||prempresas;
   wsql = wsql || '                          ) M ';
   wsql = wsql || '                    left outer join VEF_EMP_TMOVSERITENS I on (M.BDCODEMP = I.BDCODEMP and M.BDCHAVE = I.BDCHAVE)  ';
   wsql = wsql || '                    left outer join VEF_EMP_TMOVSERDED D on (M.BDCODEMP = D.BDCODEMP and M.BDCHAVE = D.BDCHAVE)  ';
   wsql = wsql || '                    left outer join VEF_EMP_TMOVSERRET R on (M.BDCODEMP = R.BDCODEMP and M.BDCHAVE = R.BDCHAVE)  ';
   wsql = wsql || '                  ) M  ';
   wsql = wsql || '              group by M.BDCODEMP, M.BDREFLAN  ';
   wsql = wsql || '              union all ';
   wsql = wsql || '              select A.BDCODEMP, A.BDREFLAN, 0 VL_CONT, 0 VL_MAT_TERC, 0 VL_MAT_PROP, 0 VL_SUB, 0 VL_ISNT, 0 VL_DED_BC, ';
   wsql = wsql || '                     0 VL_BC_ISS, 0 VL_BC_ISS_RT, 0 VL_ISS, 0 VL_ISS_RT, ';
   wsql = wsql || '                     sum(coalesce(iif(A.BDCODTIPOPROCINDISS = 1, A.BDVALOR, 0), 0)) VL_DED, 0 VL_ISS_REC, ';
   wsql = wsql || '                     (sum(coalesce(iif(A.BDCODTIPOPROCINDISS = 2, A.BDVALOR, 0), 0)) *-1) VL_ISS_ST, 0 VL_ISS_REC_UNI ';
   wsql = wsql || '              from (select M.BDCODEMP, M.BDREFERENCIA BDREFLAN,  M.BDVALOR, M.BDCODTIPOPROCISS, ';
   wsql = wsql || '                           M.BDCODTIPOPROCINDISS, M.BDNUM_PROC, M.BDDESC_PROC, M.BDCODOBS ';
   wsql = wsql || '                    from VEF_EMP_TAJUISSB460 M ';
   wsql = wsql || '                    where M.BDREFERENCIA between '||prrefini ||' and '||prreffim ||' and ';
   if ((prempresas <> '') and (prempresas is not null)) then
     wsql = wsql ||prempresas;
   wsql = wsql || '                      and  M.BDCODTIPOPROCINDISS in (1, 2) /*equivale ao zero*/ ) A ';
   wsql = wsql || '              group by A.BDCODEMP, A.BDREFLAN ';
   wsql = wsql || '         ) m ';
   wsql = wsql || '       group by m.BDCODEMP, m.BDREFLAN ';
   wsql = wsql || '      ) M ';

  FOR EXECUTE STATEMENT wsql
  INTO
    :wBDCODEMP,
    :wbdreflan,
    :VL_CONT,
    :VL_MAT_TERC,
    :VL_MAT_PROP,
    :VL_SUB,
    :VL_ISNT ,
    :VL_DED_BC,
    :VL_BC_ISS,
    :VL_BC_ISS_RT,
    :VL_ISS,
    :VL_ISS_RT,
    :VL_DED ,
    :VL_ISS_REC ,
    :VL_ISS_ST ,
    :VL_ISS_REC_UNI

  DO
    BEGIN
        bdcodemp = wBDCODEMP;
        BDREFLAN = wbdreflan;
    
        if (prRel = 'TRUE') then
          begin
        --02 VL_CONT A - Valor total referente às prestações de serviço do período
            BDNRCAMPO  = '02'; BDDESCRICAO = 'A - Valor total referente às prestações de serviço do período'; BDVALOR  = :VL_CONT;
            suspend;
        --03 VL_MAT_TERC B - Valor total do material fornecido por terceiros na prestação do serviço
            BDNRCAMPO  = '03'; BDDESCRICAO = 'B - Valor total do material fornecido por terceiros na prestação do serviço'; BDVALOR  = :VL_MAT_TERC;
            suspend;
        --04 VL_MAT_PROP C - Valor do material próprio utilizado na prestação do serviço
            BDNRCAMPO  = '04'; BDDESCRICAO = 'C - Valor do material próprio utilizado na prestação do serviço'; BDVALOR  = :VL_MAT_PROP;
            suspend;
        --05 VL_SUB D - Valor total das subempreitadas
            BDNRCAMPO  = '05'; BDDESCRICAO = 'D - Valor total das subempreitadas'; BDVALOR  = :VL_SUB;
            suspend;
        --06 VL_ISNT E - Valor total das operações isentas ou não-tributadas pelo ISS
            BDNRCAMPO  = '06'; BDDESCRICAO = 'E - Valor total das operações isentas ou não-tributadas pelo ISS'; BDVALOR  = :VL_ISNT;
            suspend;
        --07 VL_DED_BC F - Valor total das deduções da base de cálculo (B + C + D + E)
            BDNRCAMPO  = '07'; BDDESCRICAO = 'F - Valor total das deduções da base de cálculo (B + C + D + E)'; BDVALOR  = :VL_DED_BC;
            suspend;
        --08 VL_BC_ISS G - Valor total da base de cálculo do ISS
            BDNRCAMPO  = '08'; BDDESCRICAO = 'G - Valor total da base de cálculo do ISS'; BDVALOR  = :VL_BC_ISS;
            suspend;
        --09 VL_BC_ISS_RT H - Valor total da base de cálculo de retenção do ISS referente às prestações do declarante.
            BDNRCAMPO  = '09'; BDDESCRICAO = 'H - Valor total da base de cálculo de retenção do ISS referente às prestações do declarante.'; BDVALOR  = :VL_BC_ISS_RT;
            suspend;
        --10 VL_ISS I - Valor total do ISS destacado
            BDNRCAMPO  = '10'; BDDESCRICAO = 'I - Valor total do ISS destacado'; BDVALOR  = :VL_ISS;
            suspend;
        --11 VL_ISS_RT J - Valor total do ISS retido pelo tomador nas prestações do declarante
            BDNRCAMPO  = '11'; BDDESCRICAO = 'J - Valor total do ISS retido pelo tomador nas prestações do declarante'; BDVALOR  = :VL_ISS_RT;
            suspend;
        --12 VL_DED K - Valor total das deduções do ISS próprio
            BDNRCAMPO  = '12'; BDDESCRICAO = 'K - Valor total das deduções do ISS próprio'; BDVALOR  = :VL_DED;
            suspend;
        --13 VL_ISS_REC L - Valor total apurado do ISS próprio a recolher (I - J - K)
            BDNRCAMPO  = '13'; BDDESCRICAO = 'L - Valor total apurado do ISS próprio a recolher (I - J - K)'; BDVALOR  = iif(:VL_ISS_REC<0,0,:VL_ISS_REC);
            suspend;
        --14 VL_ISS_ST M - Valor total do ISS substituto a recolher pelas aquisições do declarante (tomador)
            BDNRCAMPO  = '14'; BDDESCRICAO = 'M - Valor total do ISS substituto a recolher pelas aquisições do declarante (tomador)'; BDVALOR  = :VL_ISS_ST;
            suspend;
        --15 VL_ISS_REC_UNI N - Valor do ISS próprio a recolher pela Sociedade Uniprofissional
            BDNRCAMPO  = '15'; BDDESCRICAO = 'N - Valor do ISS próprio a recolher pela Sociedade Uniprofissional'; BDVALOR  = :VL_ISS_REC_UNI;
            suspend;
          end
        else
          begin
             BDCHAVEREG = LPAD(wBDCODEMP, 6, '0')||'.B470.';
             BDLINHA = '|B470';
             BDLINHA = BDLINHA ||'|'||REPLACE(COALESCE(:VL_CONT, 0.00), '.', ','); --VL_CONT
             BDLINHA = BDLINHA ||'|'||REPLACE(COALESCE(:VL_MAT_TERC, 0.00), '.', ','); --VL_MAT_TERC
             BDLINHA = BDLINHA ||'|'||REPLACE(COALESCE(:VL_MAT_PROP, 0.00), '.', ','); --VL_MAT_PROP
             BDLINHA = BDLINHA ||'|'||REPLACE(COALESCE(:VL_SUB, 0.00), '.', ','); --VL_SUB
             BDLINHA = BDLINHA ||'|'||REPLACE(COALESCE(:VL_ISNT, 0.00), '.', ','); --VL_ISNT
             BDLINHA = BDLINHA ||'|'||REPLACE(COALESCE(:VL_DED_BC, 0.00), '.', ','); --VL_DED_BC
             BDLINHA = BDLINHA ||'|'||REPLACE(COALESCE(:VL_BC_ISS, 0.00), '.', ','); --VL_BC_ISS
             BDLINHA = BDLINHA ||'|'||REPLACE(COALESCE(:VL_BC_ISS_RT, 0.00), '.', ','); --VL_BC_ISS_RT
             BDLINHA = BDLINHA ||'|'||REPLACE(COALESCE(:VL_ISS, 0.00), '.', ','); --VL_ISS
             BDLINHA = BDLINHA ||'|'||REPLACE(COALESCE(:VL_ISS_RT, 0.00), '.', ','); --VL_ISS_RT
             BDLINHA = BDLINHA ||'|'||REPLACE(COALESCE(:VL_DED, 0.00), '.', ','); --VL_DED
             BDLINHA = BDLINHA ||'|'||REPLACE(COALESCE(iif(:VL_ISS_REC<0,0,:VL_ISS_REC), 0.00), '.', ','); --VL_ISS_REC
             BDLINHA = BDLINHA ||'|'||REPLACE(COALESCE(iif(:VL_ISS_ST > 0,:VL_ISS_ST,0), 0.00), '.', ','); --VL_ISS_ST
             BDLINHA = BDLINHA ||'|'||REPLACE(COALESCE(:VL_ISS_REC_UNI, 0.00), '.', ','); --VL_ISS_REC_UNI
             BDLINHA = BDLINHA ||'|';
             suspend;
          end

    END

end^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOB (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRVALIDAREXPORTACAO DM_BOOLEAN,
    PRARQUIVO varchar(260))
as
declare variable WLINHA blob sub_type 1 segment size 200;
declare variable WTIPOEXPCODPART integer;
declare variable WPESQUISA varchar(20);
declare variable WMIN varchar(15);
declare variable WMAX varchar(15);
declare variable WCANC integer;
BEGIN
  DELETE FROM TEXPORTACAO_SPED WHERE BDID = :PRARQUIVO;
  DELETE FROM TMP_VEF_EMP_TMOVSER;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM')));

  SELECT VW.BDTIPOEXPCODPART
  FROM VW_INT_SPEDICMS_REF VW
  WHERE VW.BDCODEMP = :PRCODEMP
  INTO :wTipoExpCodPart;

  IF (ROW_COUNT = 0) THEN
    wTipoExpCodPart = -1; /*Não achou o TipoExpCodPart*/

  INSERT INTO TMP_VEF_EMP_TMOVSER(BDCODEMP, BDCHAVE,BDMODELO,BDTIPLAN,BDCODSITNF,BDDATAEMISSAO,BDSERIE,bdREFLAN)
  SELECT MOV.BDCODEMP, MOV.BDCHAVE,MOV.BDMODELO,MOV.BDTIPLAN,MOV.BDCODSITNF,MOV.BDDATAEMISSAO,BDSERIE,bdREFLAN
  FROM VEF_EMP_TMOVSER MOV
  WHERE MOV.BDCODEMP = :PRCODEMP
  AND MOV.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
  AND MOV.BDMODELO IN(1, 3, 4, 8, 55, 65, 802,801);

  /*****************************************************************************
   *                                   B020                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA,BDCODTER)
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.B020'||'.'||LPAD(MOV.BDCHAVE, 10, '0'),
         'B020' BDREG,
         '|B020|'||IIF(SER.BDTIPLAN = 0, '1', '0')|| --IND_OPER
         '|'||IIF(SER.BDTIPLAN = 0, '0', '1')||      --IND_EMIT
         '|'||IIF(SER.BDCODSITNF IN(2, 3, 4, 5), '', (SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:wTipoExpCodPart, SER.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO)))|| --COD_PART
         '|'||COALESCE(MOD.BDMODELOSTR, '')||             --COD_MOD
         '|'||LPAD(COALESCE(SER.BDCODSITNF, 0), 2, '0')|| --COD_SIT - Por padrão leva como regular se não tiver situação(Quando o lançamento de serviço vem da folha não vem a situação).
         '|'||COALESCE(SER.BDSERIE, '')||                                   --SER
         --'|'||SUBSTRING(SER.BDNUMDOCINI FROM 1 FOR 9)||                   --NUM_DOC
         '|'||TRIM(SUBSTRING(LPAD(SER.BDNUMDOCINI, 15, ' ') FROM 7 FOR 9))|| --NUM_DOC
         '|'||IIF(SER.BDMODELO NOT IN(55, 65), '', COALESCE(IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(SER.BDCHAVENFE_MOD55)) = '', '', (RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(SER.BDCHAVENFE_MOD55)), 44, ' '))), ''))|| --CHV_NFE
         '|'||IIF(SER.BDCODSITNF IN(2, 3, 4, 5), '', (SELECT BDDATA FROM SP_PARSE_DATE(SER.BDDATAEMISSAO, 'DDMMYYYY')))||               --DT_DOC
         '|'||IIF(SER.BDCODSITNF IN(2, 3, 4, 5), '', COALESCE(CID_PREST.BDCODIBGE, ''))||                                               --COD_MUN_SERV
         '|'||IIF(SER.BDCODSITNF IN(2, 3, 4, 5), '', REPLACE(COALESCE(SER.BDVALORNOTA, 0.00), '.', ','))||                              --VL_CONT
         '|'||IIF(SER.BDCODSITNF IN(2, 3, 4, 5), '', REPLACE(COALESCE(DED.BDVLRMATERIAIS, 0.00), '.', ','))||                           --VL_MAT_TERC
         '|'||IIF(SER.BDCODSITNF IN(2, 3, 4, 5), '', REPLACE(COALESCE(DED.BDVLRSUBEMPREITEIRAS, 0.00), '.', ','))||                     --VL_SUB
         '|'||IIF(SER.BDCODSITNF IN(2, 3, 4, 5), '', REPLACE(COALESCE((I.BDISEISSSER + I.BDOUTISSSER), 0.00), '.', ','))||              --VL_ISNT_ISS
         '|'||IIF(SER.BDCODSITNF IN(2, 3, 4, 5), '', REPLACE(COALESCE((SER.BDVALORNOTA - I.BDBCISSSER), 0.00), '.', ','))||             --VL_DED_BC
         '|'||IIF(SER.BDCODSITNF IN(2, 3, 4, 5), '', REPLACE(COALESCE(I.BDBCISSSER, 0.00), '.', ','))||                                 --VL_BC_ISS
         '|'||IIF(SER.BDCODSITNF IN(2, 3, 4, 5), '', REPLACE(COALESCE(IIF(RET.BDISSRET > 0, SER.BDVALORNOTA, 0.00), 0.00), '.', ','))|| --VL_BC_ISS_RT
         '|'||IIF(SER.BDCODSITNF IN(2, 3, 4, 5), '', REPLACE(COALESCE(IIF(SER.BDMODELO IN(65), 0.00, RET.BDISSRET), 0.00), '.', ','))|| --VL_ISS_RT
         '|'||IIF(SER.BDCODSITNF IN(2, 3, 4, 5), '', REPLACE(COALESCE(I.BDVLRISSSER, 0), '.', ','))||                                   --VL_ ISS
         '|'||'|',SER.BDCODTER                                                                                                            --COD_INF_OBS
  FROM (
        SELECT M.BDCODEMP, M.BDCHAVE
        FROM TMP_VEF_EMP_TMOVSER M
        WHERE M.BDMODELO IN(1, 3, 802, 4, 8, 55, 65)
          and m.BDCODSITNF not in (10, 11)
       ) MOV
  JOIN VEF_EMP_TMOVSER SER ON(SER.BDCODEMP = MOV.BDCODEMP AND SER.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TTABMODELOLAN MOD ON(MOD.BDMODELO = SER.BDMODELO)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = SER.BDCODTER)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = SER.bdcodter)
  LEFT OUTER JOIN TCIDADE CID_PREST ON(CID_PREST.BDCODCID = SER.BDCODCID)
  LEFT OUTER JOIN VEF_EMP_TMOVSERDED DED ON(DED.BDCODEMP = SER.BDCODEMP AND DED.BDCHAVE = SER.BDCHAVE)
  LEFT OUTER JOIN VEF_EMP_TMOVSERRET RET ON(RET.BDCODEMP = SER.BDCODEMP AND RET.BDCHAVE = SER.BDCHAVE)
  LEFT OUTER JOIN (
                   SELECT S.BDCODEMP, S.BDCHAVE,
                          SUM(COALESCE(I.BDISENTASISSSER, 0)) BDISEISSSER,
                          SUM(COALESCE(I.BDOUTRASISSSER, 0)) BDOUTISSSER,
                          SUM(COALESCE(I.BDBCISSSER, 0)) BDBCISSSER,
                          SUM(COALESCE(I.BDVLRISSSER, 0)) BDVLRISSSER
                   FROM TMP_VEF_EMP_TMOVSER S
                   JOIN VEF_EMP_TMOVSERITENS I ON(I.BDCODEMP = S.BDCODEMP AND I.BDCHAVE = S.BDCHAVE)
                   GROUP BY S.BDCODEMP, S.BDCHAVE
                  ) I ON(I.BDCODEMP = SER.BDCODEMP AND I.BDCHAVE = SER.BDCHAVE);

  /*****************************************************************************
   *                                   B025                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.B020.'||LPAD(MOV.BDCHAVE, 10, '0')||'.B025.'||LPAD(COALESCE(MOV.BDCODATVM, '0'), 10, '0')||'|'||LPAD(COALESCE(MOV.BDALIQREDISSSER, '0'), 10, '0'),
         'B025' BDREG,
         '|B025|'||REPLACE(MOV.BDVLRCONTAB, '.', ',')||                                         --VL_CONT_P
         '|'||REPLACE(MOV.BDBCISSSER, '.', ',')||                                               --VL_BC_ISS_P
         '|'||REPLACE(CAST(COALESCE(MOV.BDALIQREDISSSER, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ISS
         '|'||REPLACE(MOV.BDVLRISSSER, '.', ',')||                                              --VL_ISS_P
         '|'||REPLACE((MOV.BDISEISSSER + MOV.BDOUTISSSER), '.', ',')||                          --VL_ISNT_ISS_P
         '|'||COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(ATV.BDCODMUNATVM)), '')||       --COD_SERV
         '|'
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE, I.BDCODATVM, I.BDALIQREDISSSER,
               SUM(COALESCE(I.BDVLRCONTAB, 0)) BDVLRCONTAB,
               SUM(COALESCE(I.BDBCISSSER, 0)) BDBCISSSER,
               SUM(COALESCE(I.BDVLRISSSER, 0)) BDVLRISSSER,
               SUM(COALESCE(I.BDISENTASISSSER, 0)) BDISEISSSER,
               SUM(COALESCE(I.BDOUTRASISSSER, 0)) BDOUTISSSER
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM TMP_VEF_EMP_TMOVSER M
              WHERE M.BDMODELO IN(1, 3, 802, 4, 8, 55, 65)
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11) /*Ignora as canceladas no B025*/
             ) MOV
        JOIN VEF_EMP_TMOVSER SER ON(SER.BDCODEMP = MOV.BDCODEMP AND SER.BDCHAVE = MOV.BDCHAVE AND SER.BDCODSITNF NOT IN(5))
        LEFT OUTER JOIN VEF_EMP_TMOVSERITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        GROUP BY MOV.BDCODEMP, MOV.BDCHAVE, I.BDCODATVM, I.BDALIQREDISSSER
       ) MOV
  LEFT OUTER JOIN TATVMUNICIPAL ATV ON(ATV.BDCODATVM = MOV.BDCODATVM);



  /*****************************************************************************
  *    B030 NOTA FISCAL DE SERVIÇOS SIMPLIFICADA (CÓDIGO 3A)                   *
  ****************************************************************************/

  /*Salva os números de documento menores e maiores por data de emissao e modelo na DLL, na hora de montar o registro busca os dados na DLL*/
  FREEANDNIL_B030(0);

  FOR SELECT SER.BDDATAEMISSAO||'|'||coalesce(SER.BDMODELO,'')||'|'||LPAD(COALESCE(SER.bdserie,''),5,' ') bdPESQUISA, MIN(SER.BDNUMDOCINI) BDMIN, MAX(SER.BDNUMDOCINI) BDMAX,
      SUM(BDCANCELAMENTO) BDCANCELAMENTO
      FROM (
            SELECT M.BDCODEMP,M.BDCHAVE,M.BDMODELO,IIF(M.BDCODSITNF IN(2, 3, 4, 5),1,0) BDCANCELAMENTO
            FROM TMP_VEF_EMP_TMOVSER M
            where M.BDMODELO IN(801)
              and m.BDCODSITNF not in (10, 11)  
            )M
      JOIN VEF_EMP_TMOVSER SER ON(SER.BDCODEMP = M.BDCODEMP AND SER.BDCHAVE = M.BDCHAVE)
      GROUP BY SER.BDCODEMP, SER.BDDATAEMISSAO, SER.BDMODELO,SER.bdserie
      INTO :wPesquisa, :wMin, :wMax,:wCanc
  DO
    BEGIN
      SETNUMDOC_B030(:wPesquisa, :wMin, :wMax,:wCanc);
    END


  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.B030.'||MOV.BDDATAEMISSAO||'.'||coalesce(MOV.BDMODELO,'')||'.'||LPAD(COALESCE(MOV.bdserie,''),5,' '),
         'B030' BDREG,
         '|B030'||
         '|'||COALESCE(MOD.bdmodelostr,'') ||--COD_MOD    |B030|3A|F|1|6284|31012019|1|50886,00|50886,00|0,00|0,00||2019-01-31|801|F
         '|'||COALESCE(MOV.bdserie, '')|| --SER
         '|'||MOV.BDNUMDOCINI|| --DOC_INI
         '|'||MOV.BDNUMDOCFIM|| --DOC_FIM
         '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(MOV.BDDATAEMISSAO, 'DDMMYYYY')), '')|| --DT_DOC
         '|' ||MOV.BDQTDCANC || --QTD_CANC
         '|'||REPLACE(MOV.bdvlrcontab, '.', ',')|| --VL_CONT
         '|'||REPLACE(MOV.VL_ISNT_ISS, '.', ',')|| --VL_ISNT_ISS
         '|'||REPLACE(MOV.bdbcissser, '.', ',')|| --VL_BC_ISS
         '|'||REPLACE(MOV.BDVLRISSSER, '.', ',')|| --VL_ISS
         '||'
  FROM (
        SELECT SER.BDCODEMP, SER.BDDATAEMISSAO,SER.BDSERIE,SER.bdmodelo,
               GETNUMDOC_B030(SER.BDDATAEMISSAO||'|'||coalesce(SER.BDMODELO,'')||'|'||LPAD(COALESCE(SER.bdserie,''),5,' '),'MIN') BDNUMDOCINI,
               GETNUMDOC_B030(SER.BDDATAEMISSAO||'|'||coalesce(SER.BDMODELO,'')||'|'||LPAD(COALESCE(SER.bdserie,''),5,' '),'MAX') BDNUMDOCFIM,
               GETNUMDOC_B030(SER.BDDATAEMISSAO||'|'||coalesce(SER.BDMODELO,'')||'|'||LPAD(COALESCE(SER.bdserie,''),5,' '),'CAN') BDQTDCANC,
               SUM(IIF(SER.BDCODSITNF IN(2, 3, 4, 5),0, i.bdvlrcontab)) bdvlrcontab,
               (SUM(IIF(SER.BDCODSITNF IN(2, 3, 4, 5),0, I.bdisentasissser))+SUM(IIF(SER.BDCODSITNF IN(2, 3, 4, 5),0, I.bdoutrasissser))) VL_ISNT_ISS,
               SUM(IIF(SER.BDCODSITNF IN(2, 3, 4, 5),0, I.bdbcissser)) bdbcissser,
               SUM(IIF(SER.BDCODSITNF IN(2, 3, 4, 5),0, I.bdvlrissser)) bdvlrissser
        FROM (
                SELECT M.BDCODEMP,M.BDCHAVE,M.BDMODELO
                FROM TMP_VEF_EMP_TMOVSER M
                where M.BDMODELO IN(801)
                  and m.BDCODSITNF not in (10, 11)
             )M
        JOIN VEF_EMP_TMOVSER SER ON(SER.BDCODEMP = M.BDCODEMP AND SER.BDCHAVE = M.BDCHAVE)
        LEFT OUTER jOIN VEF_EMP_TMOVSERITENS I ON (I.BDCODEMP = M.BDCODEMP AND I.BDCHAVE = M.BDCHAVE)
        GROUP BY SER.BDCODEMP, SER.BDDATAEMISSAO, BDNUMDOCINI, BDNUMDOCFIM,BDQTDCANC, SER.bdserie,SER.BDMODELO
       ) MOV
  JOIN VEF_BASE_TTABMODELOLAN MOD ON(MOD.BDMODELO = MOV.BDMODELO)
  ;


   /*******************************************************************************************************
   *  REGISTRO B035: DETALHAMENTO POR COMBINAÇÃO DE ALÍQUOTA E ITEM DA LISTA DE SERVIÇOS DA LC 116/2003)  *
   ********************************************************************************************************/

--02 VL_CONT_P Parcela correspondente ao "Valor Contábil" referente à combinação da alíquota e item da lista N - 02 O
--03 VL_BC_ISS_P Parcela correspondente ao "Valor da base de cálculo do ISS" referente à combinação da alíquota e item da lista N - 02 O
--04 ALIQ_ISS Alíquota do ISS N - 02 O
--05 VL_ISS_P Parcela correspondente ao "Valor do ISS" referente à combinação da alíquota e item da lista N - 02 O
--06 VL_ISNT_ISS_P Parcela correspondente ao "Valor das operações isentas ou nãotributadas pelo ISS" referente à combinação da alíquota e item da lista N - 02 O
--07 COD_SERV Item da lista de serviços, conforme Tabela 4.6.3. C 004* -


  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID, MOV.BDCHAVEREG,
         'B035' BDREG,
         '|B035'||
         '|'||REPLACE(MOV.bdvlrcontab, '.', ',')|| --VL_CONT
         '|'||REPLACE(MOV.BDBCISSSER, '.', ',')|| --VL_BC_ISS_P
         '|'||REPLACE(CAST(MOV.bdaliqredissser AS NUMERIC(8, 2)), '.', ',')|| --ALIQ_ISS
         '|'||REPLACE(MOV.BDVLRISSSER, '.', ',')|| --VL_ISS_P
         '|'||REPLACE(MOV.VL_ISNT_ISS_P, '.', ',')|| --VL_ISNT_ISS_P
         '|'||REPLACE(MOV.bdcodmunatvm, '.', '')|| --COD_SERV
         '|'
  FROM (
        SELECT MOV.BDCHAVEREG,MOV.bdaliqredissser,MOV.bdcodatvm,MOV.bdvlrcontab,MOV.BDBCISSSER,MOV.bdvlrissser,MOV.VL_ISNT_ISS_P,COALESCE(MOV.bdcodmunatvm,'9999') bdcodmunatvm
        FROM (
              SELECT LPAD(MOV.BDCODEMP, 6, '0')||'.B030.'||MOV.BDDATAEMISSAO||'.'||coalesce(MOV.BDMODELO,'')||'.'||LPAD(COALESCE(MOV.bdserie,''),5,' ')||LPAD(MOV.BDNUMDOCINI,10,'0')||'.B035.'||LPAD(REPLACE(MOV.bdaliqredissser, '.', ','),7,'0')||LPAD(MOV.bdcodatvm,10,'0') BDCHAVEREG
                     ,COALESCE(MOV.bdaliqredissser,0) bdaliqredissser,MOV.bdcodatvm,MOV.bdvlrcontab,MOV.BDBCISSSER,MOV.bdvlrissser,MOV.VL_ISNT_ISS_P ,MOV.bdcodmunatvm
              FROM (
                    SELECT MOV.BDCODEMP, MOV.BDDATAEMISSAO,MOV.BDMODELO,MOV.bdserie, I.bdcodatvm, MOV.BDNUMDOCINI ,I.bdaliqredissser,ATV.bdcodmunatvm,
                    SUM(I.bdvlrcontab) bdvlrcontab, SUM(I.bdbcissser) bdbcissser,SUM(COALESCE(I.bdisentasissser,0)+COALESCE(I.bdoutrasissser,0)) VL_ISNT_ISS_P,
                    SUM(I.bdvlrissser) bdvlrissser
                    FROM (
                          SELECT MOV.BDCODEMP, MOV.BDCHAVE,MOV.BDDATAEMISSAO, MOV.BDNUMDOCINI,MOV.BDMODELO,MOV.bdserie
                          FROM (
                                SELECT M.BDCODEMP, M.BDCHAVE,M.BDDATAEMISSAO,M.BDMODELO,M.BDSERIE,
                                (SELECT GETNUMDOC_B030(M.BDDATAEMISSAO||'|'||coalesce(M.BDMODELO,'')||'|'||LPAD(COALESCE(M.bdserie,''),5,' '),'MIN') FROM RDB$DATABASE) BDNUMDOCINI
                                FROM TMP_VEF_EMP_TMOVSER M
                                where M.BDMODELO IN(801)
                                  and not M.BDCODSITNF IN(2, 3, 4, 5, 10, 11)
                               ) MOV
                         ) MOV
                    JOIN VEF_EMP_TMOVSERITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                    LEFT OUTER JOIN tatvmunicipal ATV ON (I.bdcodatvm = ATV.bdcodatvm)
                    GROUP BY MOV.BDCODEMP, MOV.BDDATAEMISSAO, MOV.BDMODELO,MOV.bdserie,MOV.BDNUMDOCINI,I.bdaliqredissser,I.bdcodatvm,ATV.bdcodmunatvm
                   ) MOV
             ) MOV
       ) MOV
;




 /*****************************************************************************
   *                                   B420                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.B420.'||LPAD(COALESCE(MOV.BDCODATVM, '0'), 10, '0')||'|'||LPAD(COALESCE(REPLACE(MOV.BDALIQREDISSSER, '.', ''), '0'), 10, '0'),
         'B420' BDREG,
         '|B420|'||REPLACE(COALESCE(MOV.BDVLRCONTAB, 0.00), '.', ',')||                         --VL_CONT
         '|'||REPLACE(COALESCE(MOV.BDBCISSSER, 0.00), '.', ',')||                               --VL_BC_ISS
         '|'||REPLACE(COALESCE(CAST(MOV.BDALIQREDISSSER AS DM_NUMERIC_15_2), 0.00), '.', ',')|| --ALIQ_ISS
         '|'||REPLACE(COALESCE((MOV.BDISEISSSER + MOV.BDOUTISSSER), 0.00), '.', ',')||          --VL_ISNT_ISS
         '|'||REPLACE(COALESCE(MOV.BDVLRISSSER, 0.00), '.', ',')||                              --VL_ISS
         '|'||COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(ATV.BDCODMUNATVM)), '')||       --COD_SERV
         '|'
  FROM (
        SELECT I.BDCODEMP, I.BDCODATVM, I.BDALIQREDISSSER, mov.bdREFLAN,
               SUM(COALESCE(I.BDVLRCONTAB, 0)) BDVLRCONTAB,
               SUM(COALESCE(I.BDBCISSSER, 0)) BDBCISSSER,
               SUM(COALESCE(I.BDVLRISSSER, 0)) BDVLRISSSER,
               SUM(COALESCE(I.BDISENTASISSSER, 0)) BDISEISSSER,
               SUM(COALESCE(I.BDOUTRASISSSER, 0)) BDOUTISSSER
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE, m.bdREFLAN
              FROM TMP_VEF_EMP_TMOVSER M
              WHERE  M.BDTIPLAN = 0 /*Somente emitidos*/
              AND M.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11) /*Ignora as canceladas no B420*/
             ) MOV
        LEFT OUTER JOIN VEF_EMP_TMOVSERITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        GROUP BY I.BDCODEMP, I.BDCODATVM, I.BDALIQREDISSSER, mov.bdREFLAN
       ) MOV
  LEFT OUTER JOIN TATVMUNICIPAL ATV ON(ATV.BDCODATVM = MOV.BDCODATVM)
  WHERE ((MOV.BDALIQREDISSSER > 0) OR
         (SELECT FIRST 1 e.bdCODENQFED -- Alt.: #157195 #157622 - Deve sempre exportar quando a empresa for optante do Simples Nacional...
          FROM TENQFED e
          WHERE e.bdCODEMP = mov.bdCODEMP
            AND e.bdREFEMP = (SELECT FIRST 1 e.bdREFEMP
                              FROM TENQFED e
                              WHERE e.bdCODEMP = mov.bdCODEMP
                                AND e.bdREFEMP <= mov.bdREFLAN
                              ORDER BY e.bdREFEMP DESC)) IN (1,2,4));

  /*****************************************************************************
   *                                   B440                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER)
  SELECT :PRARQUIVO BDID,
         LPAD(MOV.BDCODEMP, 6, '0')||'.B440.'||LPAD(MOV.BDTIPLAN, 10, '0')||'|'||LPAD(MOV.BDCODTER, 10, '0'),
         'B440' BDREG,
         '|B440|'||IIF(MOV.BDTIPLAN = 0, '1', '0')|| --IND_OPER
         '|'||(SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:wTipoExpCodPart, MOV.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))|| --COD_PART
         '|'||REPLACE(COALESCE(MOV.BDVALORNOTA, 0.00), '.', ',')|| --VL_CONT_RT
         '|'||IIF(MOV.BDISSRET = 0, '0,00', REPLACE(COALESCE(MOV.BDVALORNOTA, 0.00), '.', ','))|| --VL_BC_ISS_RT
         '|'||REPLACE(COALESCE(MOV.BDISSRET, 0.00), '.', ',')||    --VL_ISS_RT
         '|', MOV.BDCODTER
  FROM (
        SELECT SER.BDCODEMP, SER.BDTIPLAN, SER.BDCODTER,
               SUM(COALESCE(SER.BDVALORNOTA, 0)) BDVALORNOTA,
               SUM(COALESCE(RET.BDISSRET, 0)) BDISSRET
        FROM (
              SELECT M.BDCODEMP, M.BDCHAVE
              FROM TMP_VEF_EMP_TMOVSER M
              WHERE M.BDMODELO IN(1, 3, 4, 8, 55, 65, 801, 802)
             ) MOV
        JOIN VEF_EMP_TMOVSER SER ON(SER.BDCODEMP = MOV.BDCODEMP AND SER.BDCHAVE = MOV.BDCHAVE)
        LEFT OUTER JOIN VEF_EMP_TMOVSERRET RET ON(RET.BDCODEMP = MOV.BDCODEMP AND RET.BDCHAVE = MOV.BDCHAVE)
        GROUP BY SER.BDCODEMP, SER.BDTIPLAN, SER.BDCODTER
       ) MOV
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = MOV.BDCODTER)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = MOV.bdcodter);




  /*****************************************************************************
   *                                   B460                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
  SELECT :PRARQUIVO BDID,
         LPAD(B.BDCODEMP, 6, '0')||'.B460.'||LPAD(B.BDCHAVE, 10, '0'),
         'B460' BDREG,
         '|B460|'||COALESCE(OCO.BDCODTIPOEXP, '')||          --IND_DED
         '|'||REPLACE(COALESCE(B.BDVALOR, 0.00), '.', ',')|| --VL_DED
         '|'||COALESCE(B.BDNUM_PROC, '')||                   --NUM_PROC
         '|'||COALESCE(PROC.BDCODTIPOEXP, '')||              --IND_PROC
         '|'||COALESCE(B.BDDESC_PROC, '')||                  --PROC
         '|'||COALESCE(OBS.BDCODEXP, '')||                   --COD_INF_OBS
         '|'||COALESCE(IND.BDCODTIPOEXP, '')||               --IND_OBR
         '|', OBS.BDCODOBS
  FROM VEF_EMP_TAJUISSB460 B
  LEFT OUTER JOIN VEF_BASE_TTAB_TIPOOCO_ISS OCO ON(OCO.BDCODTIPOCOISS = B.BDCODTIPOCOISS)
  LEFT OUTER JOIN VEF_BASE_TTAB_TIPOPROC_ISS PROC ON(PROC.BDCODTIPOPROCISS = B.BDCODTIPOPROCISS)
  LEFT OUTER JOIN VEF_BASE_TOBSERVACAO OBS ON(OBS.BDCODOBS = B.BDCODOBS)
  LEFT OUTER JOIN VEF_BASE_TTAB_TIPOPROCIND_ISS IND ON(IND.BDCODTIPOPROCINDISS = B.BDCODTIPOPROCINDISS)
  WHERE B.BDCODEMP = :PRCODEMP
  AND B.BDREFERENCIA >= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM'))
  AND B.BDREFERENCIA <= (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTFIM, 'YYYYMM'));


  /*****************************************************************************
   *                                   B470                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA)
  SELECT :PRARQUIVO BDID, bdchavereg,'B470' BDREG,BDLINHA
  FROM  SP_APURACAOISS_BLOCOB_B470('M.BDCODEMP = '||:PRCODEMP,(SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM')),
                                  (SELECT BDDATA FROM SP_PARSE_DATE(:PRDTINI, 'YYYYMM')),'FALSE')
  ;




  /*Cria as inconsistências
  IF (UPPER(:PRVALIDAREXPORTACAO) = 'TRUE') THEN
    EXECUTE PROCEDURE SP_VALIDA_EXPORTACAO_SPED(:PRCODEMP, :PRDTINI, :PRDTFIM, :PRARQUIVO, 'C100');*/

  /*****************************************************************************
   *                           EXPORTANDO ARQUIVO                              *
   ****************************************************************************/

  OPENARQ(:PRARQUIVO,:PRCODEMP);

  FOR SELECT E.BDLINHA
      FROM TEXPORTACAO_SPED E
      WHERE E.BDID = :PRARQUIVO
      ORDER BY E.BDCHAVEREG
      INTO :wLinha
  DO
    BEGIN
      WRITELNOA(:wLinha,:PRCODEMP);
    END

  CLOSEARQ(:PRARQUIVO,:PRCODEMP);

  DELETE FROM TMP_VEF_EMP_TMOVSER;

  WHEN ANY DO
    BEGIN
      IN AUTONOMOUS TRANSACTION DO
        BEGIN
          DELETE FROM TMP_VEF_EMP_TMOVSER;
          EXECUTE PROCEDURE LANCA_EXCEPTION('SP_EXPORTA_BLOCOB', SQLCODE, GDSCODE);
        END
      EXCEPTION;
    END
END^

CREATE OR ALTER TRIGGER TDICIONARIO_REL_ESOCIAL_BI0 FOR TDICIONARIO_REL_ESOCIAL
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;
begin
  if (coalesce(new.bdcodtag, 0) = 0) then
     begin
       select coalesce(max(BDCODTAG) + 1, 1) from TDICIONARIO_REL_ESOCIAL into :vcod;
       new.bdcodtag = :vcod;
     end

  if (coalesce(new.bdnodopai, '') = '') then
     new.bdnodopai = 'eSocial';

  if (coalesce(new.bdatributosnodo, '') = '') then
     new.bdatributosnodo = 'FALSE';

end
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_ADMPREL_BI0 FOR VRH_EMP_TCOL_ADMPREL
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
  DECLARE VARIABLE VNOVOCOD INTEGER;
BEGIN
  IF ((NEW.BDCODCOL IS NULL) OR (NEW.BDCODCOL = 0)) THEN
  BEGIN
      IF (coalesce(NEW.BDTIPOCADASTRO, 0) = 0) THEN
      BEGIN
        SELECT COALESCE(MAX(X.BDCODCOL) + 1, 1)
          FROM VRH_EMP_TCOLCON X
          WHERE X.BDCODEMP = NEW.BDCODEMP AND coalesce(bdcontrcol, 0) = 0 AND X.BDCODCOL < 900000
        INTO :VNOVOCOD;
      END
    ELSE
      BEGIN
        SELECT COALESCE(MAX(X.BDCODCOL) + 1, 900000)
          FROM VRH_EMP_TCOLCON X
          WHERE X.BDCODEMP = NEW.BDCODEMP AND coalesce(bdcontrcol, 0) = 1 AND X.BDCODCOL >= 900000
        INTO :VNOVOCOD;
      END

    SELECT BDCODCOL
    FROM SP_EXISTE_COLABORADOR_NOVO(NEW.BDCODEMP, :VNOVOCOD)
    INTO :VNOVOCOD;

    NEW.BDCODCOL = :VNOVOCOD;
  END
END
^

CREATE OR ALTER TRIGGER TMP_VEF_EMP_APURET1800_TEMP_BI0 FOR TMP_VEF_EMP_APURET1800_TEMP
ACTIVE BEFORE INSERT POSITION 0
AS
declare variable wPesq varchar(200);
begin

  WPESQ = '';

  if (NEW.BDCODREC IS NOT NULL) then
     begin
       WPESQ = substring(COALESCE(NEW.BDCNPJINCORP,COALESCE(NEW.BDIDENTIFICACAOSCP,COALESCE(NEW.BDCODMATRIZ,NEW.BDCODEMP)))||'|'||NEW.BDCODREC from 1  for 200);
     end
  else
     begin
       WPESQ = substring(COALESCE(NEW.BDCNPJINCORP,COALESCE(NEW.BDIDENTIFICACAOSCP,COALESCE(NEW.BDCODMATRIZ,NEW.BDCODEMP)))||'|'||COALESCE(NEW.BDCODRECIRPJ,'0')||'|'||COALESCE(NEW.BDCODRECPIS,'0')||'|'||COALESCE(NEW.BDCODRECCSLL,'0')||'|'||COALESCE(NEW.BDCODRECCOFINS,'0') from 1 for 200);
     end

  NEW.BDCHAVE = GETORDEMSEQUENCIAL_pesq(wPesq);
  -- Alt.: #214221 - Comentario para forcar a compilar a trigger...

end^

create or alter procedure SP_INS_VRH_ESOCIAL_TLOTE_ARQUIV (
    PRCODEMP integer,
    PRSTATUS integer,
    PRDESCSTATUS varchar(300),
    PRTEMPOESTIMADO integer,
    PRPROTOCOLO varchar(50))
returns (
    BDCODLOTE integer)
as
begin
  insert into VRH_ESOCIAL_TLOTE_ARQUIVOS (BDCODEMP, BDCODSTATUS, BDDESCSTATUS, BDTEMPOESTIMADO, BDPROTOCOLO)
  values (:prcodemp, :prstatus, :prdescstatus, :prtempoestimado, :prprotocolo)
  returning BDCODLOTE into :BDCODLOTE;
  suspend;
end^

CREATE OR ALTER trigger tterceiro_ref_bd0 for tterceiro_ref
active before delete position 0
AS
  DECLARE VARIABLE wDelTer DM_BOOLEAN;
BEGIN
  /*SELECT COALESCE(RDB$GET_CONTEXT('USER_SESSION', 'W_DEL_TTERCEIRO'), '') FROM RDB$DATABASE INTO :wDelTer;
  IF (:wDelTer <> 'TRUE') THEN
    EXCEPTION EX_TTERCEIRO_DEL;*/

  /* Caso esteja vindo do cadastro de participantes, desbloqueia e bloqueia em seguida... */
  SELECT COALESCE(RDB$GET_CONTEXT('USER_SESSION', 'W_DEL_TTERCEIRO'), '') FROM RDB$DATABASE INTO :wDelTer;
  IF (:wDelTer <> 'TRUE') THEN
    BEGIN
      SELECT FIRST 1 bdDELTER
      FROM (/* Caso a referencia seja igual a menor "Data de cadastro" do participante */
            SELECT 'TRUE' AS bdDELTER
            FROM TTERCEIRO_REF r
            WHERE r.bdCODTER = old.bdCODTER
              AND r.bdREFEMP = old.bdREFEMP
              AND r.bdREFEMP = (SELECT FIRST 1 CAST(EXTRACT(YEAR FROM r.bdDATACADTER)||LPAD(EXTRACT(MONTH FROM r.bdDATACADTER),2,'0') AS INTEGER) AS bdREFERENCIA
                                FROM TTERCEIRO_REF r
                                WHERE r.bdCODTER = old.bdCODTER
                                  AND r.bdDATACADTER = (SELECT MIN(r.bdDATACADTER) AS bdDATACADTER
                                                        FROM TTERCEIRO_REF r
                                                        WHERE r.bdCODTER = old.bdCODTER))
            UNION ALL
            /* Caso seja a unica referencia do participante */
            SELECT IIF(COUNT(r.bdCODTER) = 1, 'TRUE', 'FALSE') AS bdDELTER
            FROM TTERCEIRO_REF r
            WHERE r.bdCODTER = old.bdCODTER
            )
      INTO :wDelTer;
    
      IF (:wDelTer = 'TRUE') THEN
    EXCEPTION EX_TTERCEIRO_DEL;
    END

end^

create or alter procedure SP_AJUSTE_ISE_OUT (
    PRCODEMP integer,
    PRCHAVE integer,
    PRORDEM integer,
    PRTIPOLAN char(3),
    PRLANCAREM integer)
returns (
    BDVALORISE DM_NUMERIC_15_2,
    BDVALOROUT DM_NUMERIC_15_2)
as
declare variable WSQL varchar(1000);
declare variable WTABLEITEM varchar(31);
declare variable WTABLEIMPRETSP varchar(31);
declare variable WNAOSOMARISEOUTRAS DM_BOOLEAN;
declare variable WLANBCICMSISEOUT DM_BOOLEAN;
declare variable WVALORIMPRETSP DM_NUMERIC_15_2;
declare variable WVALOR DM_NUMERIC_15_2;
declare variable WVALORCONTAB DM_NUMERIC_15_2;
declare variable WVALORST DM_NUMERIC_15_2;
declare variable WVALORBCICMS DM_NUMERIC_15_2;
declare variable WVALOROUTICMS DM_NUMERIC_15_2;
declare variable WVALORISEICMS DM_NUMERIC_15_2;
declare variable WVALOROUTIMP DM_NUMERIC_15_2;
declare variable WLANCAREMAUX integer;
declare variable WRETST varchar(31);
declare variable WNAOSOMARSTISEOUT DM_BOOLEAN;
begin
  IF (:prTipoLan = 'ENT') THEN
    BEGIN
      wTableImpRetSP = 'VEF_EMP_TMOVENTIMPRETSP';
      wTableItem     = 'VEF_EMP_TMOVENTITENS';
      wRetST    = 'Coalesce(R.BDICMSRETENT,0)';
    END
  ELSE
  IF (:prTipoLan = 'SAI') THEN
    BEGIN
      wTableImpRetSP = 'VEF_EMP_TMOVSAIIMPRETSP';
      wTableItem     = 'VEF_EMP_TMOVSAIITENS';
      wRetST    = '0';
    END

  wSQL =          'SELECT (COALESCE(R.BDIMPSUBSTITUTO, 0) + COALESCE(R.BDIMPSUBSTITUIDO, 0)) BDVLR ';
  wSQL = :wSQL || 'FROM '||:wTableImpRetSP||' R ';
  wSQL = :wSQL || 'WHERE R.BDCODEMP = '||:PRCODEMP||' ';
  wSQL = :wSQL || 'AND R.BDCHAVE = '||:PRCHAVE||' ';
  wSQL = :wSQL || 'AND R.BDORDEM = '||:PRORDEM||' ';

  EXECUTE STATEMENT :wSQL INTO :wValorImpRetSP;

  if (:wValorImpRetSP IS NULL) then
    :wValorImpRetSP = 0;

  wSQL =          'SELECT ((COALESCE(R.BDBASEICMS, 0) + COALESCE(R.BDISENTASICMS, 0) + ';
  wSQL = :wSQL ||          'COALESCE(R.BDOUTRASICMS, 0) + COALESCE(R.BDOUTROSIMP, 0)) - COALESCE(R.BDVLRCONTAB, 0)), ';
  wSQL = :wSQL ||          'R.BDVLRCONTAB, NAT.BDNAOSOMARSTISEOUT, R.BDBASEICMS, R.BDOUTRASICMS, R.BDISENTASICMS, R.BDOUTROSIMP, ';
  wSQL = :wSQL ||          'NAT.BDLANEMISENTASOUTRASNAT, Coalesce(NAT.BDNAOSOMARSTISEOUT,''FALSE''), ';
  IF (:PRTIPOLAN = 'ENT') THEN
    wSQL = :wSQL || ' (COALESCE(R.BDVLRST, 0) + COALESCE(R.BDICMSRETENT, 0) + COALESCE(R.BDVALNTRIBST, 0)) BDVLRST ';
  ELSE
    wSQL = :wSQL || ' COALESCE(R.BDVLRST, 0) BDVLRST ';
  wSQL = :wSQL || 'FROM '||:wTableItem||' R ';
  wSQL = :wSQL || 'LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = R.BDCODNAT) ';
  wSQL = :wSQL || 'WHERE R.BDCODEMP = '||:PRCODEMP||' ';
  wSQL = :wSQL || 'AND R.BDCHAVE = '||:PRCHAVE||' ';
  wSQL = :wSQL || 'AND R.BDORDEM = '||:PRORDEM||' ';
  EXECUTE STATEMENT :wSQL INTO :wValor, :wValorContab, :wNaoSomarIseOutras,
                               :wValorBCICMS, :wValorOutICMS, :wValorIseICMS,
                               :wValorOutIMP, :wLancarEmAux, :wNaoSomarSTIseOut, :wValorST;

  /* Se o valor ja vier correto aqui, nao precisa jogar para isentas ou para outro, pois ja é para estar correto aqui */
  if ((:wValorIseICMS + wValorOutICMS) = :wValorContab) then
    BEGIN
      BDVALOROUT = wValorOutICMS;
      BDVALORISE = wValorIseICMS;

      IF ((:wValorImpRetSP > 0) OR (:wValorOutIMP > 0))  THEN -- Alt.: #223507 - Nos ajustes finais, deve descontar o valor dos outros impostos quando tiver...
        BEGIN
          IF (:PRLANCAREM = 0) THEN --Isentas e outras
            SELECT bdLANBCICMSISEOUT FROM VW_VEF_BASE_TEMPPARGER WHERE BDCODEMP = :PRCODEMP INTO :wLanBCICMSIseOut;
          ELSE
            wLanBCICMSIseOut = :PRLANCAREM;
    
          IF (:wLanBCICMSIseOut = 0) THEN
            BEGIN
              IF ((BDVALORISE = 0) AND (BDVALOROUT > (:wValorOutIMP + :wValorImpRetSP))) THEN -- Se esta tentando lancar em um campo, mas o valor está em outro, desconta do campo que tem o realmente tem o valor...
                BDVALOROUT = COALESCE(:BDVALOROUT, 0) - COALESCE(:wValorOutIMP, 0) - COALESCE(:wValorImpRetSP, 0);
              ELSE
                BDVALORISE = COALESCE(:BDVALORISE, 0) - COALESCE(:wValorOutIMP, 0) - COALESCE(:wValorImpRetSP, 0);
            END
          ELSE
            BEGIN
              IF ((BDVALOROUT = 0) AND (BDVALORISE > (:wValorOutIMP + :wValorImpRetSP))) THEN -- Se esta tentando lancar em um campo, mas o valor está em outro, desconta do campo que tem o realmente tem o valor...
                BDVALORISE = COALESCE(:BDVALORISE, 0) - COALESCE(:wValorOutIMP, 0) - COALESCE(:wValorImpRetSP, 0);
              ELSE
                BDVALOROUT = COALESCE(:BDVALOROUT, 0)  - COALESCE(:wValorOutIMP, 0)- COALESCE(:wValorImpRetSP, 0);
            END
        END

      IF ((:wNaoSomarSTIseOut = 'TRUE') AND (:wValorImpRetSP <= 0)) THEN
        BEGIN
          if (BDVALORISE > 0) then
            BDVALORISE = BDVALORISE - :wValorST;
          if (BDVALOROUT > 0) then
            BDVALOROUT = BDVALOROUT - :wValorST;
        END
      SUSPEND;
      EXIT;
    END

  --if (:wValor = 0) then --Não tem diferença
    --EXIT;

  IF (:prLancarEm = 0) THEN
    prLancarEm = :wLancarEmAux;

/*  IF ((:wNaoSomarIseOutras = 'TRUE') AND (:wValorST > 0)) THEN
    BEGIN
      IF (COALESCE(:wValorImpRetSP, 0) = 0) THEN
        wValorContab = :wValorContab - :wValorST;
    END*/

  BDVALOROUT = 0;
  BDVALORISE = 0;

  IF (:PRLANCAREM = 0) THEN --Isentas e outras
    BEGIN
      SELECT bdLANBCICMSISEOUT FROM VW_VEF_BASE_TEMPPARGER WHERE BDCODEMP = :PRCODEMP INTO :wLanBCICMSIseOut;

      if (:wLanBCICMSIseOut = 0) then
        BEGIN
          BDVALORISE = COALESCE(:wValorContab, 0) - COALESCE(:wValorBCICMS, 0) - COALESCE(:wValorOutICMS, 0) - COALESCE(:wValorOutIMP, 0) - COALESCE(:wValorImpRetSP, 0);
          BDVALOROUT = :wValorOutICMS ; -- Alt.: #222353 - Deve fazer igual quando joga em Isentas/Ouras, caso contrario zerava o campo...
        END
      ELSE
        BEGIN
          BDVALOROUT = COALESCE(:wValorContab, 0) - COALESCE(:wValorBCICMS, 0) - COALESCE(:wValorIseICMS, 0) - COALESCE(:wValorOutIMP, 0) - COALESCE(:wValorImpRetSP, 0);
          BDVALORISE = :wValorIseICMS ; -- Alt.: #222353 - Deve fazer igual quando joga em Isentas/Ouras, caso contrario zerava o campo...
        END

     IF ((:wNaoSomarSTIseOut = 'TRUE') AND (:wValorImpRetSP <= 0)) THEN
    BEGIN
      BDVALORISE = BDVALORISE - :wValorST;
      BDVALOROUT = BDVALOROUT - :wValorST;
    END

    END
  ELSE
  IF (:PRLANCAREM = 1) THEN --Isentas
    BEGIN
    BDVALORISE = (COALESCE(:wValorContab, 0) - COALESCE(:wValorBCICMS, 0) - COALESCE(:wValorOutICMS, 0) - COALESCE(:wValorOutIMP, 0) - COALESCE(:wValorImpRetSP, 0));
      BDVALOROUT = :wValorOutICMS /*- (BDVALOROUT - :wValorOutICMS)*/; -- Alt.: Alt.: #126335 - Deve manter o valor dos dois campos e nao zerar o outro...

    IF ((:wNaoSomarSTIseOut = 'TRUE') AND (:wValorImpRetSP <= 0)) THEN
    BEGIN
      BDVALORISE = BDVALORISE - :wValorST;
    END
    END
  ELSE --Outras
    BEGIN
    BDVALOROUT = (COALESCE(:wValorContab, 0) - COALESCE(:wValorBCICMS, 0) - COALESCE(:wValorIseICMS, 0) - COALESCE(:wValorOutIMP, 0) - COALESCE(:wValorImpRetSP, 0));
      BDVALORISE = :wValorIseICMS /*- (BDVALOROUT - :wValorOutICMS)*/; -- Alt.: Alt.: #126335 - Deve manter o valor dos dois campos e nao zerar o outro...

    IF ((:wNaoSomarSTIseOut = 'TRUE') AND (:wValorImpRetSP = 0)) THEN
      BEGIN
        BDVALOROUT = BDVALOROUT - :wValorST;
      END
    END         

  IF (:BDVALORISE < 0) THEN
    BDVALORISE = 0;
  IF (:BDVALOROUT < 0) THEN
    BDVALOROUT = 0;

  SUSPEND;
end
^

COMMENT ON PARAMETER SP_AJUSTE_ISE_OUT.PRTIPOLAN IS 'ENT/SAI'^

create or alter procedure VSUC_SP_REL_CTA_MOVIMENTADA (
    PRCODPLAPADRAO integer,
    PRCTALONINI varchar(40),
    PRCTALONFIM varchar(40),
    PRDATINI date,
    PRDATFIN date,
    PRCONTABILIZACAO integer,
    PRPARTINI integer,
    PRPARTFIM integer,
    PRPART integer,
 PRLANCEXCLUIDOS integer = 0)
returns (
    BDCODPLAPADRAO integer,
    BDNOMEPLANOPADRAO varchar(80),
    BDCODTPLA integer,
    BDCTALON varchar(40),
    BDNOMCTA varchar(100),
    BDCODEMP integer,
    BDNOMEMP varchar(100),
    BDCHAVE integer,
    BDDATA date,
    BDDEBITO integer,
    BDCREDITO integer,
    BDVALOR numeric(15,2),
    BDCOMPL varchar(200),
    BDNOMEHIST varchar(200),
    BDCOMPLEMENTO blob sub_type 1 segment size 32700,
    BDTRANSACAO integer,
    BDCODTER integer,
    BDNOMETER varchar(200),
    BDPARTICIPANTE integer,
 BDDATAEXCLUSAO date)
as
declare variable WSQL_CTA varchar(7000);
declare variable WSQL varchar(7000);
declare variable WCODTPLA integer;
declare variable WCTALON varchar(40);
declare variable WNOMCTA varchar(100);
declare variable WCODPLAPADRAO integer;
declare variable WNOMEPLANOPADRAO varchar(80);
declare variable WCODEMP integer;
declare variable WNOMEMP varchar(100);
declare variable WCHAVE integer;
begin
  wSQL_CTA = 'Select TPLA.BDCODTPLA, TPLA.BDCTALON, TPLA.BDNOMCTA, TPLA.BDCODPLAPADRAO, TPLANO.BDNOME, TPLA.BDPARTICIPANTE';
  wSQL_CTA = wSQL_CTA||' from (';
  wSQL_CTA = wSQL_CTA||'        Select BDCODTPLA, BDCTALON, BDNOMCTA, BDCODPLAPADRAO, BDPARTICIPANTE ';
  wSQL_CTA = wSQL_CTA||'        from PLANOS_TPLA ';
  wSQL_CTA = wSQL_CTA||'        where ';
  wSQL_CTA = wSQL_CTA||'        (BDTIPCTA = 1) and '; -- Apenas contas analísticas, pois não posso ter lançamentos contábeis em contas títulos.

  IF ((prCTALONINI IS NOT NULL) AND (prCTALONINI <> '')) THEN
     wSQL_CTA = wSQL_CTA||'        (BDCTALON between '''||:PRCTALONINI||''' and '''||:PRCTALONFIM||''') and ';

  wSQL_CTA = wSQL_CTA||'        (BDCODPLAPADRAO = '||:PRCODPLAPADRAO||')';
  wSQL_CTA = wSQL_CTA||'      ) TPLA ';
  wSQL_CTA = wSQL_CTA||'inner join TPLANO_PADRAO TPLANO on (TPLANO.BDCODPLAPADRAO = TPLA.BDCODPLAPADRAO) ';

  IF ((prCTALONINI IS NULL) OR (prCTALONINI = '')) THEN
     wSQL_CTA = wSQL_CTA||'inner join VSUC_SELECT_CONTAS TSEL on (TSEL.BDCODPLAPADRAO = TPLA.BDCODPLAPADRAO and TSEL.BDCODTPLA = TPLA.BDCODTPLA) ';

  FOR EXECUTE STATEMENT wSQL_CTA
  INTO :wCODTPLA,:wCTALON,:wNOMCTA,:wCODPLAPADRAO,:wNOMEPLANOPADRAO, :BDPARTICIPANTE  DO
    BEGIN
      BDCODPLAPADRAO    = wCODPLAPADRAO;
      BDNOMEPLANOPADRAO = wNOMEPLANOPADRAO;
      BDCODTPLA         = wCODTPLA;
      BDCTALON          = wCTALON;
      BDNOMCTA          = wNOMCTA;

      FOR EXECUTE STATEMENT 'SELECT EMP.BDCODEMP, BDNOMEMP
         FROM VW_TEMPRESAS_REF EMP
         INNER JOIN VW_EMPRESAS_USU USU on (EMP.BDCODEMP = USU.BDCODEMP)
         WHERE (BDCODPLAPADRAO = '||:wCODPLAPADRAO||')
         ORDER BY EMP.BDCODEMP'
      INTO :wCODEMP,:wNOMEMP  DO
        BEGIN
          BDCODEMP = wCODEMP;
          BDNOMEMP = wNOMEMP;

          IF ( wCODTPLA = 51) THEN
            wCODTPLA = wCODTPLA;
--#177038 - Contas movimentadas por empresa - detalhar participante. Marcela. 27/04/2023
--          IF (prMOSTRARLANCAMENTOS = 0) THEN -- Não quero mostrar os lançamentos contábeis
--             BEGIN
--               if (prPart = 1) then
--                 begin
--                   wSQL = 'Select first 1 COALESCE(BDCHAVE,0), ';
--                   wSQL = wSQL||'iif(BDCODTERCEIROD > 0, BDCODTERCEIROD,iif(BDCODTERCEIROC > 0, BDCODTERCEIROC, null)) as BDCODTER ';
--                   wSQL = wSQL||'from VSUC_EMPRESAS_TLAN ';
--                   wSQL = wSQL||'where ';
--                   wSQL = wSQL||'(BDCONTABILIZACAO in (0, '||:prCONTABILIZACAO||')) and ';
--                   wSQL = wSQL||'(BDDATA between '''||:prDATINI||''' and '''||:prDATFIN||''') and ';
--                   wSQL = wSQL||'(BDCODEMP = '||:wCODEMP||') and ';
--                   --#alt:125069. Filtro participante. Ana - 27/09/2019
--                   IF ((PRPARTINI > 0) AND (PRPARTINI IS NOT NULL) AND (PRPARTFIM > 0) AND (PRPARTFIM IS NOT NULL)) THEN
--                     BEGIN
--                       wSQL = wSQL||'    (((BDDEBITO = '||:wCODTPLA||')  and (BDCODTERCEIROD in (select BDCODTER from TTERCEIRO where BDCODTER between '||:prpartini||' and '||prpartfim||')))';
--                       wSQL = wSQL||'  or ((BDCREDITO = '||:wCODTPLA||') and (BDCODTERCEIROC in (select BDCODTER from TTERCEIRO where BDCODTER between '||:prpartini||' and '||prpartfim||')))) ';
--                     END
--                   ELSE
--                     wSQL = wSQL||' ((BDDEBITO = '||:wCODTPLA||') or (BDCREDITO = '||:wCODTPLA||')) ';
--
--                   FOR EXECUTE STATEMENT wSQL
--                   INTO :wCHAVE, :bdcodter DO
--                   BEGIN
--                     IF (WCHAVE > 0) THEN
--                       begin
--                         if (NOT :BDCODTER IS NULL) then
--                           begin
--                             wSQL = '';
--                             wSQL = 'SELECT BDNOMETER FROM VW_TTERCEIRO WHERE bdcodter = '||:BDCODTER;
--                             EXECUTE STATEMENT wSQL
--                             INTO :BDNOMETER;
--                           end
--                         else
--                           :BDNOMETER = NULL;
--    
--                         SUSPEND;
--                       end
--                   end
--               END
--             else
--                 BEGIN
--                   wSQL = 'Select first 1 COALESCE(BDCHAVE,0) from VSUC_EMPRESAS_TLAN ';
--                   wSQL = wSQL||'where ';
--                   wSQL = wSQL||'(BDCONTABILIZACAO in (0, '||:prCONTABILIZACAO||')) and ';
--                   wSQL = wSQL||'(BDDATA between '''||:prDATINI||''' and '''||:prDATFIN||''') and ';
--                   wSQL = wSQL||'(BDCODEMP = '||:wCODEMP||') and ';
--                   --#alt:125069. Filtro participante. Ana - 27/09/2019
--                   IF ((PRPARTINI > 0) AND (PRPARTINI IS NOT NULL) AND (PRPARTFIM > 0) AND (PRPARTFIM IS NOT NULL)) THEN
--                     BEGIN
--                       wSQL = wSQL||'    (((BDDEBITO = '||:wCODTPLA||')  and (BDCODTERCEIROD in (select BDCODTER from TTERCEIRO where BDCODTER between '||:prpartini||' and '||prpartfim||')))';
--                       wSQL = wSQL||'  or ((BDCREDITO = '||:wCODTPLA||') and (BDCODTERCEIROC in (select BDCODTER from TTERCEIRO where BDCODTER between '||:prpartini||' and '||prpartfim||')))) ';
--                     END
--                   ELSE
--                     wSQL = wSQL||' ((BDDEBITO = '||:wCODTPLA||') or (BDCREDITO = '||:wCODTPLA||')) ';
--    
--                   FOR EXECUTE STATEMENT wSQL
--                   INTO :wCHAVE DO
--                   BEGIN
--                     IF (WCHAVE > 0) THEN
--                        SUSPEND;
--                   END
--                 END
--             END
--          ELSE  -- Mostrar os lançamentos contábeis
--            BEGIN
              if (prPart = 1) then
                begin
                   wSQL = 'Select TLAN.BDCHAVE,TLAN.BDDATA, TLAN.BDCODTER, TLAN.BDDEBITO, TLAN.BDCREDITO, TLAN.BDVALOR, TLAN.BDCOMPL,';
                   wsql = wSQL||'TLAN.BDTRANSACAO, TPHI.BDNOME, TCOMPL.BDCOMPL ';
                   wSQL = wSQL||'from ( ';
                   wSQL = wSQL||'       Select BDCODEMP,BDCHAVE,BDDATA,';
                   wSQL = wSQL||' iif(BDCODTERCEIROD > 0, BDCODTERCEIROD,iif(BDCODTERCEIROC > 0, BDCODTERCEIROC, null)) as BDCODTER,';
                   wSQL = wSQL||'BDDEBITO,BDCREDITO,BDVALOR,BDCOMPL,BDCODHIST,BDCODTPHI,BDTRANSACAO ';
                   wSQL = wSQL||'       from VSUC_EMPRESAS_TLAN ';
                   wSQL = wSQL||'       where ';
                   wSQL = wSQL||'       (BDCONTABILIZACAO in (0, '||:prCONTABILIZACAO||')) and ';
                   wSQL = wSQL||'       (BDDATA between '''||:prDATINI||''' and '''||:prDATFIN||''') and ';
                   wSQL = wSQL||'       (BDCODEMP = '||:wCODEMP||') and ';
                   --#alt:125069. Filtro participante. Ana - 27/09/2019
                   IF ((PRPARTINI > 0) AND (PRPARTINI IS NOT NULL) AND (PRPARTFIM > 0) AND (PRPARTFIM IS NOT NULL)) THEN
                     BEGIN
                       wSQL = wSQL||'     (((BDDEBITO = '||:wCODTPLA||')  and (BDCODTERCEIROD in (select BDCODTER from TTERCEIRO where BDCODTER between '||:prpartini||' and '||prpartfim||')))';
                       wSQL = wSQL||'   or ((BDCREDITO = '||:wCODTPLA||') and (BDCODTERCEIROC in (select BDCODTER from TTERCEIRO where BDCODTER between '||:prpartini||' and '||prpartfim||')))) ';
                     END
                   ELSE
                     wSQL = wSQL||'((BDDEBITO = '||:wCODTPLA||') or (BDCREDITO = '||:wCODTPLA||')) ';
                   wSQL = wSQL||'     ) TLAN ';
                   wSQL = wSQL||'left outer join HIST_TPHI TPHI ON (TLAN.BDCODHIST = TPHI.BDCODHIST AND TLAN.BDCODTPHI = TPHI.BDCODTPHI) ';
                   wSQL = wSQL||'left outer join VSUC_EMPRESAS_TLAN_COMPL TCOMPL on (TLAN.BDCODEMP = TCOMPL.BDCODEMP AND TLAN.BDCHAVE = TCOMPL.BDCHAVE) ';
    
                   FOR EXECUTE STATEMENT wSQL
                   INTO :BDCHAVE,:BDDATA,:BDCODTER,:BDDEBITO,:BDCREDITO,:BDVALOR,:BDCOMPL,:BDTRANSACAO,:BDNOMEHIST,:BDCOMPLEMENTO DO
                     BEGIN

                       if (NOT :BDCODTER IS NULL) then
                         begin
                           wSQL = '';
                           wSQL = 'SELECT BDNOMETER FROM VW_TTERCEIRO WHERE bdcodter = '||:BDCODTER;
                           EXECUTE STATEMENT wSQL
                           INTO :BDNOMETER;
                         end
                       else
                         :BDNOMETER = NULL;

                       SUSPEND;
                     END
               end
             else
               begin
                 wSQL = 'Select TLAN.BDCHAVE,TLAN.BDDATA,TLAN.BDDEBITO,TLAN.BDCREDITO,TLAN.BDVALOR,TLAN.BDCOMPL,TLAN.BDTRANSACAO,TPHI.BDNOME,TCOMPL.BDCOMPL ';
                 wSQL = wSQL||'from ( ';
                 wSQL = wSQL||'       Select BDCODEMP,BDCHAVE,BDDATA,BDDEBITO,BDCREDITO,BDVALOR,BDCOMPL,BDCODHIST,BDCODTPHI,BDTRANSACAO ';
                 wSQL = wSQL||'       from VSUC_EMPRESAS_TLAN ';
                 wSQL = wSQL||'       where ';
                 wSQL = wSQL||'       (BDCONTABILIZACAO in (0, '||:prCONTABILIZACAO||')) and ';
                 wSQL = wSQL||'       (BDDATA between '''||:prDATINI||''' and '''||:prDATFIN||''') and ';
                 wSQL = wSQL||'       (BDCODEMP = '||:wCODEMP||') and ';
                 --#alt:125069. Filtro participante. Ana - 27/09/2019
                 IF ((PRPARTINI > 0) AND (PRPARTINI IS NOT NULL) AND (PRPARTFIM > 0) AND (PRPARTFIM IS NOT NULL)) THEN
                   BEGIN
                     wSQL = wSQL||'     (((BDDEBITO = '||:wCODTPLA||')  and (BDCODTERCEIROD in (select BDCODTER from TTERCEIRO where BDCODTER between '||:prpartini||' and '||prpartfim||')))';
                     wSQL = wSQL||'   or ((BDCREDITO = '||:wCODTPLA||') and (BDCODTERCEIROC in (select BDCODTER from TTERCEIRO where BDCODTER between '||:prpartini||' and '||prpartfim||')))) ';
                   END
                 ELSE
                   wSQL = wSQL||'((BDDEBITO = '||:wCODTPLA||') or (BDCREDITO = '||:wCODTPLA||')) ';
                 wSQL = wSQL||'     ) TLAN ';
                 wSQL = wSQL||'left outer join HIST_TPHI TPHI ON (TLAN.BDCODHIST = TPHI.BDCODHIST AND TLAN.BDCODTPHI = TPHI.BDCODTPHI) ';
                 wSQL = wSQL||'left outer join VSUC_EMPRESAS_TLAN_COMPL TCOMPL on (TLAN.BDCODEMP = TCOMPL.BDCODEMP AND TLAN.BDCHAVE = TCOMPL.BDCHAVE) ';
    
                 FOR EXECUTE STATEMENT wSQL
                 INTO :BDCHAVE,:BDDATA,:BDDEBITO,:BDCREDITO,:BDVALOR,:BDCOMPL,:BDTRANSACAO,:BDNOMEHIST,:BDCOMPLEMENTO DO
                   BEGIN
                     SUSPEND;
                   END
               end
     if ((PRLANCEXCLUIDOS = 1) and (prPart = 1)) then  --#186053 - Filtrar Lançamentos excluidos - Djonathan
                begin
                   wSQL = 'Select TLAN.BDCHAVE,TLAN.BDDATA, TLAN.BDCODTER, TLAN.BDDEBITO, TLAN.BDCREDITO, TLAN.BDVALOR, TLAN.BDCOMPL,';
                   wsql = wSQL||'TLAN.BDTRANSACAO, TPHI.BDNOME, TCOMPL.BDCOMPL, TLAN.BDDATAEXCLUSAO ';
                   wSQL = wSQL||'from ( ';
                   wSQL = wSQL||'       Select BDCODEMP,BDCHAVE,BDDATA,';
                   wSQL = wSQL||' iif(BDCODTERCEIROD > 0, BDCODTERCEIROD,iif(BDCODTERCEIROC > 0, BDCODTERCEIROC, null)) as BDCODTER,';
                   wSQL = wSQL||'BDDEBITO,BDCREDITO,BDVALOR,BDCOMPL,BDCODHIST,BDCODTPHI,BDTRANSACAO,BDDATAEXCLUSAO ';
                   wSQL = wSQL||'       from VSUC_LX_EMPRESAS_TLAN ';
                   wSQL = wSQL||'       where ';
                   wSQL = wSQL||'       (BDCONTABILIZACAO in (0, '||:prCONTABILIZACAO||')) and ';
                   wSQL = wSQL||'       (BDDATA between '''||:prDATINI||''' and '''||:prDATFIN||''') and ';
                   wSQL = wSQL||'       (BDCODEMP = '||:wCODEMP||') and ';

                   IF ((PRPARTINI > 0) AND (PRPARTINI IS NOT NULL) AND (PRPARTFIM > 0) AND (PRPARTFIM IS NOT NULL)) THEN
                     BEGIN
                        wSQL = wSQL||'     (((BDDEBITO = '||:wCODTPLA||')  and (BDCODTERCEIROD in (select BDCODTER from TTERCEIRO where BDCODTER between '||:prpartini||' and '||prpartfim||')))';
                        wSQL = wSQL||'   or ((BDCREDITO = '||:wCODTPLA||') and (BDCODTERCEIROC in (select BDCODTER from TTERCEIRO where BDCODTER between '||:prpartini||' and '||prpartfim||')))) ';
                     END
                   ELSE
                      wSQL = wSQL||'((BDDEBITO = '||:wCODTPLA||') or (BDCREDITO = '||:wCODTPLA||')) ';
                      wSQL = wSQL||'     ) TLAN ';
                      wSQL = wSQL||'left outer join HIST_TPHI TPHI ON (TLAN.BDCODHIST = TPHI.BDCODHIST AND TLAN.BDCODTPHI = TPHI.BDCODTPHI) ';
                      wSQL = wSQL||'left outer join VSUC_EMPRESAS_TLAN_COMPL TCOMPL on (TLAN.BDCODEMP = TCOMPL.BDCODEMP AND TLAN.BDCHAVE = TCOMPL.BDCHAVE) ';
              
                   FOR EXECUTE STATEMENT wSQL
                   INTO :BDCHAVE,:BDDATA,:BDCODTER,:BDDEBITO,:BDCREDITO,:BDVALOR,:BDCOMPL,:BDTRANSACAO,:BDNOMEHIST,:BDCOMPLEMENTO,:BDDATAEXCLUSAO DO
                     BEGIN
    
                       if (NOT :BDCODTER IS NULL) then
                         begin
                            wSQL = '';
                            wSQL = 'SELECT BDNOMETER FROM VW_TTERCEIRO WHERE bdcodter = '||:BDCODTER;
                            EXECUTE STATEMENT wSQL
                            INTO :BDNOMETER;
                         end
                       else
                          :BDNOMETER = NULL;
                        SUSPEND;
                          :BDDATAEXCLUSAO = NULL;  
                     END
                end
              else if (PRLANCEXCLUIDOS = 1) then ----#186053 - Filtrar Lançamentos excluidos - Djonathan
               begin
                 wSQL = 'Select TLAN.BDCHAVE,TLAN.BDDATA,TLAN.BDDEBITO,TLAN.BDCREDITO,TLAN.BDVALOR,TLAN.BDCOMPL,TLAN.BDTRANSACAO,TPHI.BDNOME,TCOMPL.BDCOMPL, TLAN.BDDATAEXCLUSAO ';
                 wSQL = wSQL||'from ( ';
                 wSQL = wSQL||'       Select BDCODEMP,BDCHAVE,BDDATA,BDDEBITO,BDCREDITO,BDVALOR,BDCOMPL,BDCODHIST,BDCODTPHI,BDTRANSACAO,BDDATAEXCLUSAO ';
                 wSQL = wSQL||'       from VSUC_LX_EMPRESAS_TLAN ';
                 wSQL = wSQL||'       where ';
                 wSQL = wSQL||'       (BDCONTABILIZACAO in (0, '||:prCONTABILIZACAO||')) and ';
                 wSQL = wSQL||'       (BDDATA between '''||:prDATINI||''' and '''||:prDATFIN||''') and ';
                 wSQL = wSQL||'       (BDCODEMP = '||:wCODEMP||') and ';

                 IF ((PRPARTINI > 0) AND (PRPARTINI IS NOT NULL) AND (PRPARTFIM > 0) AND (PRPARTFIM IS NOT NULL)) THEN
                   BEGIN
                     wSQL = wSQL||'     (((BDDEBITO = '||:wCODTPLA||')  and (BDCODTERCEIROD in (select BDCODTER from TTERCEIRO where BDCODTER between '||:prpartini||' and '||prpartfim||')))';
                     wSQL = wSQL||'   or ((BDCREDITO = '||:wCODTPLA||') and (BDCODTERCEIROC in (select BDCODTER from TTERCEIRO where BDCODTER between '||:prpartini||' and '||prpartfim||')))) ';
                   END
                 ELSE
                   wSQL = wSQL||'((BDDEBITO = '||:wCODTPLA||') or (BDCREDITO = '||:wCODTPLA||')) ';
                 wSQL = wSQL||'     ) TLAN ';
                 wSQL = wSQL||'left outer join HIST_TPHI TPHI ON (TLAN.BDCODHIST = TPHI.BDCODHIST AND TLAN.BDCODTPHI = TPHI.BDCODTPHI) ';
                 wSQL = wSQL||'left outer join VSUC_EMPRESAS_TLAN_COMPL TCOMPL on (TLAN.BDCODEMP = TCOMPL.BDCODEMP AND TLAN.BDCHAVE = TCOMPL.BDCHAVE) ';
    
                 FOR EXECUTE STATEMENT wSQL
                 INTO :BDCHAVE,:BDDATA,:BDDEBITO,:BDCREDITO,:BDVALOR,:BDCOMPL,:BDTRANSACAO,:BDNOMEHIST,:BDCOMPLEMENTO,:BDDATAEXCLUSAO DO
                   BEGIN
                     SUSPEND;
                     :BDDATAEXCLUSAO = NULL;
                   END
               end 
--            END
        END
    END
END^

CREATE OR ALTER procedure SP_VALIDA_CPF_CNPJ (
    PRDOC DM_CNPJ_CPF)
returns (
    BDISVALID DM_BOOLEAN)
as
begin
  PRDOC = COALESCE(:PRDOC, '');
  BDISVALID = 'FALSE';

  IF (CHAR_LENGTH(:PRDOC) = 14) THEN
    SELECT BDISVALID FROM SP_VALIDA_CPF(:PRDOC) INTO :BDISVALID;
  ELSE
  IF (CHAR_LENGTH(:PRDOC) = 18) THEN
    SELECT BDISVALID FROM SP_VALIDA_CNPJ(:PRDOC) INTO :BDISVALID;


  SUSPEND;
end^

CREATE OR ALTER procedure SP_VALIDA_EMAIL (
    PREMAIL DM_BDEMAIL)
returns (
    BDISVALID DM_BOOLEAN)
as
declare variable WCARAC char(1);
declare variable WI integer;
declare variable WEMAIL DM_BDEMAIL;
declare variable WDOMINIO DM_BDEMAIL;
declare variable WTIPO varchar(50);
declare variable WLIMITADOR char(1);
begin

  wI         = 1;
  wEmail     = '';
  wDominio   = '';
  wTipo      = '';
  wLimitador = '';

  WHILE (:wI <= CHAR_LENGTH(:PREMAIL)) DO
    BEGIN
      wCarac = TRIM(SUBSTRING(:PREMAIL FROM :wI FOR 1));

      IF ((:wCarac = '@') OR (:wCarac = '.')) THEN
        wLimitador = :wCarac;
      ELSE
        BEGIN
          IF (:wLimitador = '@') THEN
            wDominio = :wDominio || :wCarac;
          ELSE
          IF (:wLimitador = '.') THEN
            wTipo = :wTipo || :wCarac;
          ELSE
            wEmail = :wEmail || :wCarac;
        END

      wI = :wI + 1;
    END

  BDISVALID = IIF(((:wEmail <> '') AND (:wDominio <> '') AND (:wTipo <> '')), 'TRUE', 'FALSE');
  SUSPEND;
end^

CREATE OR ALTER procedure SP_AUDITORIA_REINF_R1000 (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRCODUSU integer,
    PRCODINCONFORMIDADE integer)
as
begin

  /*
    BDTIPOINCONF
    1 - Erros
    2 - Avisos
    3 - Informativos    
  */

  IF (:PRCODINCONFORMIDADE IN(0, 35)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 35
       Inconformidade:  Informação do campo número de inscrição do contribuinte (CNPJ/CPF) está em branco. Este campo
                        é obrigatório exigido no evento R-1000 Da Reinf.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 35 BDCODINCONF, 6 BDCODTELASIS, 'edCNPJEMP' BDCAMPO, E.BDCODEMP,
             'Cadastros/Empresas/Empresa '||E.BDCODEMP|| '/aba Cadastrais Campo "CNPJ/CPF"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM TEMPRESAS E
      WHERE E.BDCODEMP = :PRCODEMP
      AND ((E.BDCNPJEMP IS NULL) OR (E.BDCNPJEMP = ''));
    END

  IF (:PRCODINCONFORMIDADE IN(0, 36)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 36
       Inconformidade: A informação do número do CNPJ/CPF está inválida. Este campo é obrigatório exigido no evento R-1000 da Reinf.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 36 BDCODINCONF, 6 BDCODTELASIS, 'edCNPJEMP' BDCAMPO, E.BDCODEMP,
             'Cadastros/Empresas/Empresa '||E.BDCODEMP|| '/aba Cadastrais Campo "CNPJ/CPF"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM (
            SELECT E.BDCODEMP, (SELECT BDISVALID FROM SP_VALIDA_CPF_CNPJ(E.BDCNPJEMP)) BDISVALID
            FROM TEMPRESAS E
            WHERE E.BDCODEMP = :PRCODEMP
            AND COALESCE((SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(E.BDCNPJEMP)), '') <> ''
           ) E
      WHERE E.BDISVALID = 'FALSE';
    END

  IF (:PRCODINCONFORMIDADE IN(0, 37)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 37
       Inconformidade: A informação do campo de classificação tributária está em branco. Este campo é obrigatório exigido no evento R-1000 da Reinf.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 37 BDCODINCONF, 6 BDCODTELASIS, 'edCODCLATRI' BDCAMPO, E.BDCODEMP,
             'Cadastros/Empresas/Empresa '||E.BDCODEMP|| '/aba Folha - GPS Campo "Classificação tributária"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM VW_VRHF_BASE_TEMPESOCIAL E
      WHERE E.BDCODEMP = :PRCODEMP
      AND E.BDCODCLATRI IS NULL;
    END

  IF (:PRCODINCONFORMIDADE IN(0, 39)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 39
       Inconformidade: A informação do campo classificação tributária está inválida para o tipo de inscrição da empresa. Para este tipo de inscrição são válidos apenas os códigos 21 e 22 da tabela 8.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 39 BDCODINCONF, 6 BDCODTELASIS, 'edCODCLATRI' BDCAMPO, E.BDCODEMP,
             'Cadastros/Empresas/Empresa '||E.BDCODEMP|| '/aba Folha - GPS Campo "Classificação tributária"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM TEMPRESAS E
      JOIN VW_VRHF_BASE_TEMPESOCIAL RH ON(RH.BDCODEMP = E.BDCODEMP)
      WHERE E.BDCODEMP = :PRCODEMP
      AND CHAR_LENGTH(E.BDCNPJEMP) = 14 /*CPF*/
      AND RH.BDCODCLATRI NOT IN(21, 22); /*Para CPF só é valido as classificações 21 e 22*/
    END

  IF (:PRCODINCONFORMIDADE IN(0, 40)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 40
       Inconformidade: A informação do campo classificação tributária está inválida para o tipo de inscrição da empresa. Para este tipo de inscrição não são válidos os códigos 21 e 22 da tabela 8.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 40 BDCODINCONF, 6 BDCODTELASIS, 'edCODCLATRI' BDCAMPO, E.BDCODEMP,
             'Cadastros/Empresas/Empresa '||E.BDCODEMP|| '/aba Folha - GPS Campo "Classificação tributária"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM TEMPRESAS E
      JOIN VW_VRHF_BASE_TEMPESOCIAL RH ON(RH.BDCODEMP = E.BDCODEMP)
      WHERE E.BDCODEMP = :PRCODEMP
      AND CHAR_LENGTH(E.BDCNPJEMP) = 18 /*CNPJ*/
      AND RH.BDCODCLATRI IN(21, 22); /*Para CNPJ não é valido as classificações 21 e 22*/
    END

  IF (:PRCODINCONFORMIDADE IN(0, 41)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 41
       Inconformidade: A empresa não pode ser participante do CPRB se a classificação tributária não for igual a 02, 03 e 99. Esta informação é exigida no evento R-1000 da Reinf.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 41 BDCODINCONF, 6 BDCODTELASIS, 'edCODCONFCPRBREINF' BDCAMPO, E.BDCODEMP,
             'Cadastros/Empresas/Empresa '||E.BDCODEMP|| '/aba Fiscal/Parâmetros Campo "CPRB/Reinf"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM VW_VEF_BASE_TEMPPARGER E
      JOIN VW_VRHF_BASE_TEMPESOCIAL RH ON(RH.BDCODEMP = E.BDCODEMP)
      WHERE E.BDCODEMP = :PRCODEMP
      AND E.BDCODCONFCPRBREINF IS NOT NULL --É participante do CPRB
      AND RH.BDCODCLATRI NOT IN(2, 3, 99); --A classificação tributária é diferente de 2, 3 ou 99
    END

  IF (:PRCODINCONFORMIDADE IN(0, 42)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 42
       Inconformidade: A empresa não possui nenhum sócio marcado como responsável pela empresa. O evento R-1000 da Reinf exige que haja um responsável padrão que responde pela empresa.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 42 BDCODINCONF, 24 BDCODTELASIS, 'edCODSOC' BDCAMPO, E.BDCODEMP,
             'Cadastros/Sócios/Empresa '||E.BDCODEMP||' Campo "Sócio responsável pela empresa"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM TEMPRESAS E
      LEFT OUTER JOIN (SELECT S.BDCODEMP, S.BDCODSOC FROM VW_EMPRESAS_TSOC_REF S WHERE S.BDCODEMP = :PRCODEMP AND S.BDRESPONSAVELSOC = 'TRUE') SOC ON(SOC.BDCODEMP = E.BDCODEMP)
      WHERE E.BDCODEMP = :PRCODEMP
      AND SOC.BDCODEMP IS NULL;
    END

  IF (:PRCODINCONFORMIDADE IN(0, 43)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 43
       Inconformidade: O sócio responsável pela empresa está sem informação de CPF no cadastro. No evento R-1000 da Reinf este campo consta como obrigatório.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 43 BDCODINCONF, 24 BDCODTELASIS, 'edCGCCEISOC' BDCAMPO, E.BDCODEMP||'.'||SOC.BDCODSOC,
             'Cadastros/Sócios/Empresa '||E.BDCODEMP||'/Reponsável '||SOC.BDCODSOC||' Campo "CPF"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM TEMPRESAS E
      JOIN VW_EMPRESAS_TSOC_REF SOC ON(SOC.BDCODEMP = E.BDCODEMP AND SOC.BDRESPONSAVELSOC = 'TRUE' AND COALESCE((SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(SOC.BDCGCCEISOC)), '') = '')
      WHERE E.BDCODEMP = :PRCODEMP;
    END

  IF (:PRCODINCONFORMIDADE IN(0, 44)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 44
       Inconformidade: O cadastro do sócio responsável está com o nome em branco. Esta informação é obrigatória no evento R-1000 da Reinf.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 44 BDCODINCONF, 24 BDCODTELASIS, 'edNOMSOC' BDCAMPO, E.BDCODEMP||'.'||SOC.BDCODSOC,
             'Cadastros/Sócios/Empresa '||E.BDCODEMP||'/Reponsável '||SOC.BDCODSOC||' Campo "Nome"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM TEMPRESAS E
      JOIN VW_EMPRESAS_TSOC_REF SOC ON(SOC.BDCODEMP = E.BDCODEMP AND SOC.BDRESPONSAVELSOC = 'TRUE' AND SOC.BDNOMSOC = '')
      WHERE E.BDCODEMP = :PRCODEMP;
    END

  IF (:PRCODINCONFORMIDADE IN(0, 45)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 45
       Inconformidade: O cadastro do sócio responsável está com o campo CPF inválido. Esta informação é obrigatória de acordo com o layout do evento R-1000 da Reinf.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 45 BDCODINCONF, 24 BDCODTELASIS, 'edCGCCEISOC' BDCAMPO, E.BDCODEMP||'.'||E.BDCODSOC,
             'Cadastros/Sócios/Empresa '||E.BDCODEMP||'/Reponsável '||E.BDCODSOC||' Campo "CPF"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM (
            SELECT E.BDCODEMP, (SELECT BDISVALID FROM SP_VALIDA_CPF_CNPJ(SOC.BDCGCCEISOC)) BDISVALID, SOC.BDCODSOC
            FROM TEMPRESAS E
            JOIN VW_EMPRESAS_TSOC_REF SOC ON(SOC.BDCODEMP = E.BDCODEMP AND SOC.BDRESPONSAVELSOC = 'TRUE')
            WHERE E.BDCODEMP = :PRCODEMP
            AND COALESCE((SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(SOC.BDCGCCEISOC)), '') <> ''
           ) E
      WHERE E.BDISVALID = 'FALSE';
    END

  IF (:PRCODINCONFORMIDADE IN(0, 46)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 46
       Inconformidade: O cadastro do sócio responsável está com a informação no campo DDD/telefone inválida,
                       sendo que o mesmo não é obrigatório de acordo com o layout do evento R-1000 da Reinf mas
                       quando o DDD/celular não estiver preenchido precisa ser válido.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 46 BDCODINCONF, 24 BDCODTELASIS, 'edDDDSOC' BDCAMPO, E.BDCODEMP||'.'||E.BDCODSOC,
             'Cadastros/Sócios/Empresa '||E.BDCODEMP||'/Reponsável '||E.BDCODSOC||' Campo "DDD/Telefone"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM (
            SELECT E.BDCODEMP, SOC.BDCODSOC,
                   (COALESCE(TRIM(SOC.BDDDDSOC), '')||COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(TRIM(SOC.BDTELRESSOC))), '')) BDTELEFONE,
                   (COALESCE(TRIM(SOC.BDDDCELSOC), '')||COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(TRIM(SOC.BDTELCELSOC))), '')) BDCELULAR
      FROM TEMPRESAS E
            JOIN VW_EMPRESAS_TSOC_REF SOC ON(SOC.BDCODEMP = E.BDCODEMP AND SOC.BDRESPONSAVELSOC = 'TRUE')
            WHERE E.BDCODEMP = :PRCODEMP
           ) E
      WHERE CHAR_LENGTH(E.BDCELULAR) = 0
      AND CHAR_LENGTH(E.BDTELEFONE) > 0
      AND CHAR_LENGTH(E.BDTELEFONE) < 10;
    END

  IF (:PRCODINCONFORMIDADE IN(0, 47)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 47
       Inconformidade: O cadastro do sócio responsável está com a informação no campo DDD/celular está inválido,
                       sendo que o mesmo é obrigatório de acordo com o layout do evento R-1000 da Reinf.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 47 BDCODINCONF, 24 BDCODTELASIS, 'edDDCelSOC' BDCAMPO, E.BDCODEMP||'.'||E.BDCODSOC,
             'Cadastros/Sócios/Empresa '||E.BDCODEMP||'/Reponsável '||E.BDCODSOC||' Campo "DDD/Celular"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM (
            SELECT E.BDCODEMP, SOC.BDCODSOC,
                   (COALESCE(TRIM(SOC.BDDDDSOC), '')||COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(TRIM(SOC.BDTELRESSOC))), '')) BDTELEFONE,
                   (COALESCE(TRIM(SOC.BDDDCELSOC), '')||COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(TRIM(SOC.BDTELCELSOC))), '')) BDCELULAR
      FROM TEMPRESAS E
            JOIN VW_EMPRESAS_TSOC_REF SOC ON(SOC.BDCODEMP = E.BDCODEMP AND SOC.BDRESPONSAVELSOC = 'TRUE')
            WHERE E.BDCODEMP = :PRCODEMP
           ) E
      WHERE CHAR_LENGTH(E.BDTELEFONE) = 0
      AND CHAR_LENGTH(E.BDCELULAR) > 0
      AND CHAR_LENGTH(E.BDCELULAR) < 10;
    END

  IF (:PRCODINCONFORMIDADE IN(0, 48)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 48
       Inconformidade: O cadastro do sócio está sem informação do DDD/Celular, sendo que o mesmo é obrigatório de
                       acordo com o layout do evento R-1000 da Reinf.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 48 BDCODINCONF, 24 BDCODTELASIS, 'edDDCelSOC' BDCAMPO, E.BDCODEMP||'.'||E.BDCODSOC,
             'Cadastros/Sócios/Empresa '||E.BDCODEMP||'/Reponsável '||E.BDCODSOC||' Campo "DDD/Celular"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM (
            SELECT E.BDCODEMP, SOC.BDCODSOC,
                   (COALESCE(TRIM(SOC.BDDDDSOC), '')||COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(TRIM(SOC.BDTELRESSOC))), '')) BDTELEFONE,
                   (COALESCE(TRIM(SOC.BDDDCELSOC), '')||COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(TRIM(SOC.BDTELCELSOC))), '')) BDCELULAR
      FROM TEMPRESAS E
            JOIN VW_EMPRESAS_TSOC_REF SOC ON(SOC.BDCODEMP = E.BDCODEMP AND SOC.BDRESPONSAVELSOC = 'TRUE')
            WHERE E.BDCODEMP = :PRCODEMP
           ) E
      WHERE CHAR_LENGTH(E.BDTELEFONE) = 0
      AND CHAR_LENGTH(E.BDCELULAR) = 0;
    END

  IF (:PRCODINCONFORMIDADE IN(0, 49)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 49
       Inconformidade: O cadastro do sócio responsável está com a informação no campo DDD/telefone está divergente,
                       sendo que o mesmo não é obrigatório de acordo com o layout do evento R-1000 da Reinf mas quando
                       o DDD/celular não estiver preenchido precisa ser válido.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 49 BDCODINCONF, 24 BDCODTELASIS, 'edDDDSOC' BDCAMPO, E.BDCODEMP||'.'||E.BDCODSOC,
             'Cadastros/Sócios/Empresa '||E.BDCODEMP||'/Reponsável '||E.BDCODSOC||' Campo "DDD/Telefone"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM (
            SELECT E.BDCODEMP, SOC.BDCODSOC,
                   (COALESCE(TRIM(SOC.BDDDDSOC), '')||COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(TRIM(SOC.BDTELRESSOC))), '')) BDTELEFONE,
                   (COALESCE(TRIM(SOC.BDDDCELSOC), '')||COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(TRIM(SOC.BDTELCELSOC))), '')) BDCELULAR
            FROM TEMPRESAS E
            JOIN VW_EMPRESAS_TSOC_REF SOC ON(SOC.BDCODEMP = E.BDCODEMP AND SOC.BDRESPONSAVELSOC = 'TRUE')
            WHERE E.BDCODEMP = :PRCODEMP
           ) E
      WHERE CHAR_LENGTH(E.BDCELULAR) > 0
      AND CHAR_LENGTH(E.BDTELEFONE) > 0
      AND CHAR_LENGTH(E.BDTELEFONE) < 10;
    END

  IF (:PRCODINCONFORMIDADE IN(0, 50)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 50
       Inconformidade: O cadastro do sócio responsável está com a informação no campo DDD/celular está divergente,
                       sendo que o mesmo é obrigatório de acordo com o layout do evento R-1000 da Reinf.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 50 BDCODINCONF, 24 BDCODTELASIS, 'edDDCelSOC' BDCAMPO, E.BDCODEMP||'.'||E.BDCODSOC,
             'Cadastros/Sócios/Empresa '||E.BDCODEMP||'/Reponsável '||E.BDCODSOC||' Campo "DDD/Celular"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM (
            SELECT E.BDCODEMP, SOC.BDCODSOC,
                   (COALESCE(TRIM(SOC.BDDDDSOC), '')||COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(TRIM(SOC.BDTELRESSOC))), '')) BDTELEFONE,
                   (COALESCE(TRIM(SOC.BDDDCELSOC), '')||COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(TRIM(SOC.BDTELCELSOC))), '')) BDCELULAR
            FROM TEMPRESAS E
            JOIN VW_EMPRESAS_TSOC_REF SOC ON(SOC.BDCODEMP = E.BDCODEMP AND SOC.BDRESPONSAVELSOC = 'TRUE')
            WHERE E.BDCODEMP = :PRCODEMP
           ) E
      WHERE CHAR_LENGTH(E.BDTELEFONE) > 0
      AND CHAR_LENGTH(E.BDCELULAR) > 0
      AND CHAR_LENGTH(E.BDCELULAR) < 10;
    END

  IF (:PRCODINCONFORMIDADE IN(0, 56)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 56
       Inconformidade: O cadastro do sócio responsável está sem a informação no campo e-mail, sendo que é obrigatório
                       de acordo com o layout do evento R-1000 da Reinf.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 56 BDCODINCONF, 24 BDCODTELASIS, 'edEMAILSOC' BDCAMPO, E.BDCODEMP||'.'||SOC.BDCODSOC,
             'Cadastros/Sócios/Empresa '||E.BDCODEMP||'/Reponsável '||SOC.BDCODSOC||' Campo "E-mail"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM TEMPRESAS E
      JOIN VW_EMPRESAS_TSOC_REF SOC ON(SOC.BDCODEMP = E.BDCODEMP AND SOC.BDRESPONSAVELSOC = 'TRUE' AND
                                       TRIM(COALESCE(SOC.BDEMAILSOC, '')) = '')
      WHERE E.BDCODEMP = :PRCODEMP;
    END

  IF (:PRCODINCONFORMIDADE IN(0, 57)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 57
       Inconformidade: O cadastro do sócio responsável, campo e-mail está inconforme com o layout do evento R-1000 da
                       Reinf: deve possuir o caracter “@” e o mesmo não pode estar no início e nem no fim e deve
                       possuir pelo menos um caractere ”.” depois do @.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 57 BDCODINCONF, 24 BDCODTELASIS, 'edEMAILSOC' BDCAMPO, E.BDCODEMP||'.'||E.BDCODSOC,
             'Cadastros/Sócios/Empresa '||E.BDCODEMP||'/Reponsável '||E.BDCODSOC||' Campo "E-mail"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM (
            SELECT E.BDCODEMP, SOC.BDCODSOC, (SELECT BDISVALID FROM SP_VALIDA_EMAIL(SOC.BDEMAILSOC)) BDISVALID
            FROM TEMPRESAS E
            JOIN VW_EMPRESAS_TSOC_REF SOC ON(SOC.BDCODEMP = E.BDCODEMP AND SOC.BDRESPONSAVELSOC = 'TRUE' AND TRIM(COALESCE(SOC.BDEMAILSOC, '')) <> '')
            WHERE E.BDCODEMP = :PRCODEMP
           ) E
      WHERE E.BDISVALID = 'FALSE';
    END

  IF (:PRCODINCONFORMIDADE IN(0, 58)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 58
       Inconformidade: A informação que consta no campo de classificação tributária pertence a um Ente Federativo,
                       Órgãos da União, Autarquias e Fundações Públicas. Este tipo de empresa não é atendido na Reinf
                       pelo nosso sistema. Entre em contato com nosso setor de atendimento informando o código que
                       consta no campo “Classificação tributária”.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT E.BDCODEMP, :PRCODUSU, 17 BDCODEVENTO, 58 BDCODINCONF, 6 BDCODTELASIS, 'edCODCLATRI' BDCAMPO, E.BDCODEMP,
             'Cadastros/Empresas/Empresa '||E.BDCODEMP|| '/aba Folha - GPS Campo "Classificação tributária"' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      FROM VW_VRHF_BASE_TEMPESOCIAL E
      WHERE E.BDCODCLATRI = 85;
    END
end^

CREATE OR ALTER procedure SP_AUDITORIA_REINF_R2050 (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRCODUSU integer,
    PRCODINCONFORMIDADE integer)
as
begin

  /*
    BDTIPOINCONF
    1 - Erros
    2 - Avisos
    3 - Informativos    
  */

 /*  IF (:PRCODINCONFORMIDADE IN(0, 59)) THEN
    BEGIN
      --***********************************************************************************************************
      -- Código: 59
      --Inconformidade: O evento R-2050 só pode ser enviado por contribuinte cujo a classificação tributária seja igual a 6 – Agroindústria ou 7 – Produtor Rural Pessoa Juridica
      --************************************************************************************************************
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT SAI.BDCODEMP, :PRCODUSU, 20 BDCODEVENTO, 59 BDCODINCONF, 6 BDCODTELASIS, 'edCODCLATRI' BDCAMPO, SAI.BDCODEMP,
             'Cadastros - Empresas - Empresa '||SAI.BDCODEMP|| ' - aba Folha/ GPS - campo “Classificação tributária”' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
        from (
              select s.BDCODEMP, s.BDCHAVE,S.BDREFLAN
                    from (
                          select l.bdcodemp,L.BDCHAVE,L.bdreflan
                          from vef_emp_tmovsai l
                          where l.BDCODEMP = :PRCODEMP
                          and   l.bdreflan between :PRREFINI and :prreffim
                          ) s
                    INNER join tempresas e on (e.bdcodemp = s.bdcodemp)
                    INNER join (SELECT BDCODEMP,
                                       COALESCE((SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x WHERE x.bdcodemp = :PRCODEMP AND X.BDREFEMP <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database) ORDER BY x.bdcodemp DESC, x.bdrefemp DESC )
                                               ,(SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x WHERE x.bdcodemp = :PRCODEMP AND x.bdcodplapadrao IS NOT NULL AND x.bdcodhist IS NOT NULL ORDER BY x.bdcodemp, x.bdrefemp )
                                               ,(SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x WHERE x.bdcodemp = :PRCODEMP ORDER BY x.bdcodemp, x.bdrefemp )
                                               ) BDREFEMP
                               from tempresas where bdcodemp = :PRCODEMP
                               ) REF on (REF.bdcodemp = E.bdcodemp)
                    INNER JOIN VRHF_BASE_TEMPESOCIAL esocial on (esocial.bdcodemp = REF.BDCODEMP and esocial.bdrefemp = REF.BDREFEMP)
                    where coalesce(e.bdcodmatriz,e.bdcodemp) = :PRCODEMP
                    and not esocial.BDCODCLATRI in(6,7)
               ) SAI
        left outer join VEF_EMP_TMOVSAIFUNRURAL FUN on (FUN.BDCODEMP = SAI.BDCODEMP and FUN.BDCHAVE = SAI.BDCHAVE)
        where ((Coalesce(FUN.BDVLRFUNRURAL,0) + Coalesce(FUN.BDVLRGILRAT,0) + Coalesce(FUN.BDVLRSENAR,0)) > 0)    ;

    END  */
end^

create or alter procedure SP_AUDITORIA_REINF_R2055 (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRCODUSU integer,
    PRCODINCONFORMIDADE integer)
as
begin

  /*
    BDTIPOINCONF
    1 - Erros
    2 - Avisos
    3 - Informativos    
  */

  IF (:PRCODINCONFORMIDADE IN(0, 141)) THEN
    BEGIN
      --************************************************************************************************************
      -- Código: 141
      --Inconformidade: Declarante pessoa física {ideContri/tpInsc} = [2], Indicativo da aquisição deve ser igual a 1, 4 ou 7.
      --************************************************************************************************************
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, 45 BDCODEVENTO, 141 BDCODINCONF, (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOENTRADA') BDCODTELASIS,
             '' BDCAMPO, 'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVENT.BDAUD=FISCAL',
             'Lançamentos/Entradas/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.BDREFLAN BDREFERENCIA, NULL BDCHAVEPROCESSO
        from (
              select mov.BDCODEMP, mov.BDCHAVE,mov.BDREFLAN, mov.BDNUMDOCINI
                    from (
                          select mov.bdcodemp, mov.BDCHAVE, mov.bdreflan, mov.BDNUMDOCINI, mov.bdcodsitnf
                          from vef_emp_tmovent mov
                          where mov.BDCODEMP = :PRCODEMP
                          and   mov.bdreflan between :PRREFINI and :prreffim
                          ) mov
                    join tempresas e on (e.bdcodemp = mov.bdcodemp)
                    join VW_TEMPRESAS_REF REF on (REF.bdcodemp = E.bdcodemp)
                    JOIN VRHF_BASE_TEMPESOCIAL esocial on (esocial.bdcodemp = REF.BDCODEMP and esocial.bdrefemp = REF.BDREFEMP)
                    where coalesce(e.bdcodmatriz,e.bdcodemp) = :PRCODEMP
                          and esocial.BDCODCLATRI <> 22
                          and mov.bdcodsitnf not in (2,3,4,5)  
                          and strlen(E.bdcnpjemp) <> 18
               ) MOV
        left outer join VEF_EMP_TMOVENTFUNRURAL FUN on (FUN.BDCODEMP = MOV.BDCODEMP and FUN.BDCHAVE = MOV.BDCHAVE)
        where ((Coalesce(FUN.BDVLRFUNRURAL,0) + Coalesce(FUN.BDVLRGILRAT,0) + Coalesce(FUN.bdvlrfpas,0)) > 0)
              AND FUN.bdcodaquirur NOT IN (1,4,7);
    END

  IF (:PRCODINCONFORMIDADE IN(0, 142)) THEN
    BEGIN
      --***********************************************************************************************************
      -- Código: 142
      --Inconformidade: Lançamento com produtor rural PF {tpInscProd} = [2], Indicativo da aquisição deve ser igual a 1, 2, 4, 5 ou 7.
      --************************************************************************************************************
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, 45 BDCODEVENTO, 142 BDCODINCONF, (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOENTRADA') BDCODTELASIS,
             '' BDCAMPO, 'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVENT.BDAUD=FISCAL',
             'Lançamentos/Entradas/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.BDREFLAN BDREFERENCIA, NULL BDCHAVEPROCESSO
        from (
              select mov.BDCODEMP, mov.BDCHAVE,mov.BDREFLAN, mov.BDNUMDOCINI
                    from (
                          select mov.bdcodemp, mov.BDCHAVE, mov.bdreflan, mov.BDNUMDOCINI, mov.bdcodsitnf, mov.bdcodter
                          from vef_emp_tmovent mov
                          where mov.BDCODEMP = :PRCODEMP
                          and   mov.bdreflan between :PRREFINI and :prreffim
                          ) mov
                    join tempresas e on (e.bdcodemp = mov.bdcodemp)
                    join VW_TEMPRESAS_REF REF on (REF.bdcodemp = E.bdcodemp)
                    JOIN VRHF_BASE_TEMPESOCIAL esocial on (esocial.bdcodemp = REF.BDCODEMP and esocial.bdrefemp = REF.BDREFEMP)
                    left outer join TTERCEIRO TER on (TER.BDCODTER = MOV.BDCODTER)
                    where coalesce(e.bdcodmatriz,e.bdcodemp) = :PRCODEMP
                          and esocial.BDCODCLATRI <> 22
                          and mov.bdcodsitnf not in (2,3,4,5)  
                          and strlen(ter.bdcgcter) = 14
               ) MOV
        left outer join VEF_EMP_TMOVENTFUNRURAL FUN on (FUN.BDCODEMP = MOV.BDCODEMP and FUN.BDCHAVE = MOV.BDCHAVE)
        where ((Coalesce(FUN.BDVLRFUNRURAL,0) + Coalesce(FUN.BDVLRGILRAT,0) + Coalesce(FUN.bdvlrfpas,0)) > 0)
              AND FUN.bdcodaquirur NOT IN (1,2,4,5,7);
    END

  IF (:PRCODINCONFORMIDADE IN(0, 143)) THEN
    BEGIN
      --***********************************************************************************************************
      -- Código: 143
      --Inconformidade: Lançamento com produtor rural PJ {tpInscProd} = [1], Indicativo da aquisição deve ser igual a 3 ou 6.
      --************************************************************************************************************
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, 45 BDCODEVENTO, 143 BDCODINCONF, (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOENTRADA') BDCODTELASIS,
             '' BDCAMPO, 'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVENT.BDAUD=FISCAL',
             'Lançamentos/Entradas/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.BDREFLAN BDREFERENCIA, NULL BDCHAVEPROCESSO
        from (
              select mov.BDCODEMP, mov.BDCHAVE,mov.BDREFLAN, mov.BDNUMDOCINI
                    from (
                          select mov.bdcodemp, mov.BDCHAVE, mov.bdreflan, mov.BDNUMDOCINI, mov.bdcodsitnf, mov.bdcodter
                          from vef_emp_tmovent mov
                          where mov.BDCODEMP = :PRCODEMP
                          and   mov.bdreflan between :PRREFINI and :prreffim
                          ) mov
                    join tempresas e on (e.bdcodemp = mov.bdcodemp)
                    join VW_TEMPRESAS_REF REF on (REF.bdcodemp = E.bdcodemp)
                    JOIN VRHF_BASE_TEMPESOCIAL esocial on (esocial.bdcodemp = REF.BDCODEMP and esocial.bdrefemp = REF.BDREFEMP)
                    left outer join TTERCEIRO TER on (TER.BDCODTER = MOV.BDCODTER)
                    where coalesce(e.bdcodmatriz,e.bdcodemp) = :PRCODEMP
                          and esocial.BDCODCLATRI <> 22
                          and mov.bdcodsitnf not in (2,3,4,5)  
                          and strlen(ter.bdcgcter) <> 14
               ) MOV
        left outer join VEF_EMP_TMOVENTFUNRURAL FUN on (FUN.BDCODEMP = MOV.BDCODEMP and FUN.BDCHAVE = MOV.BDCHAVE)
        where ((Coalesce(FUN.BDVLRFUNRURAL,0) + Coalesce(FUN.BDVLRGILRAT,0) + Coalesce(FUN.bdvlrfpas,0)) > 0)
              AND FUN.bdcodaquirur NOT IN (3,6);
    END

  IF (:PRCODINCONFORMIDADE IN(0, 144)) THEN
    BEGIN
      --***********************************************************************************************************
      -- Código: 144
      --Inconformidade: Declarante pessoa física {ideContri/tpInsc} = [2] não informado o CAEPF – Cadastro de Atividade Econômica da Pessoa Física.
      --************************************************************************************************************
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT First 1 MOV.BDCODEMP, :PRCODUSU, 45 BDCODEVENTO, 144 BDCODINCONF, 6 BDCODTELASIS, 'edCODCLATRI' BDCAMPO, MOV.BDCODEMP,
             'Cadastros - Empresas - Empresa '||MOV.BDCODEMP|| ' - aba Folha/ GPS - campo “Classificação tributária”' BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
        from (
              select mov.BDCODEMP, mov.BDCHAVE,mov.BDREFLAN, mov.BDNUMDOCINI
                    from (
                          select mov.bdcodemp, mov.BDCHAVE, mov.bdreflan, mov.BDNUMDOCINI, mov.bdcodsitnf
                          from vef_emp_tmovent mov
                          where mov.BDCODEMP = :PRCODEMP
                          and   mov.bdreflan between :PRREFINI and :prreffim
                          ) mov
                    join tempresas e on (e.bdcodemp = mov.bdcodemp)
                    join VW_TEMPRESAS_REF REF on (REF.bdcodemp = E.bdcodemp)
                    JOIN VRHF_BASE_TEMPESOCIAL esocial on (esocial.bdcodemp = REF.BDCODEMP and esocial.bdrefemp = REF.BDREFEMP)
                    where coalesce(e.bdcodmatriz,e.bdcodemp) = :PRCODEMP
                          and esocial.BDCODCLATRI <> 22
                          and mov.bdcodsitnf not in (2,3,4,5)
                          and ((Coalesce(e.BDDOCAUXILIARCAEPF,'') = '') or (Coalesce(e.BDDOCAUXILIARCAEPF,'   .   .   /   -') = '   .   .   /   -'))
                          and strlen(E.bdcnpjemp) <> 18
               ) MOV
        left outer join VEF_EMP_TMOVENTFUNRURAL FUN on (FUN.BDCODEMP = MOV.BDCODEMP and FUN.BDCHAVE = MOV.BDCHAVE)
        where ((Coalesce(FUN.BDVLRFUNRURAL,0) + Coalesce(FUN.BDVLRGILRAT,0) + Coalesce(FUN.bdvlrfpas,0)) > 0);
    END
end^

CREATE OR ALTER procedure SP_AUD_DESC_DETALHADA_INCON (
    PRTROCAS_DESC varchar(1000),
    PRDESC_DETALHADA varchar(1000))
returns (
    BDRESULT varchar(1000))
as
declare variable WPOS integer;
declare variable WCOUNT integer;
declare variable WDADO varchar(100);
declare variable WTROCA varchar(7);
declare variable WDADOTROCAR varchar(20);
BEGIN

  wCOUNT = 0;
  WHILE ((POSITION('XXXXXXX', :PRDESC_DETALHADA) > 0) or
        (POSITION('$$$$$$$', :PRDESC_DETALHADA) > 0))  DO
    BEGIN
      wCOUNT = wCOUNT+1;
      SELECT BDDADO FROM SP_SPLIT(:PRTROCAS_DESC, '#') where bdpos = :wCOUNT -1 INTO :wDado ;

      wTroca = SUBSTRING(:wDado FROM 1 FOR POSITION('=', :wDado)-1);
      wDadoTrocar = SUBSTRING(:wDado FROM POSITION('=', :wDado)+1 FOR CHAR_LENGTH(:wDado));
      wPos = POSITION(wTroca, :PRDESC_DETALHADA);
      if (WPOS > 0) then
        prdesc_detalhada = SUBSTRING(prdesc_detalhada FROM 1 FOR :WPOS-1) || :wDadoTrocar || SUBSTRING(:prdesc_detalhada FROM (:WPOS+7) FOR CHAR_LENGTH(:prdesc_detalhada));

    END

  BDRESULT = :PRDESC_DETALHADA;
  SUSPEND;


END^


CREATE OR ALTER procedure SP_AUDITORIA_REINF_R2060 (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRCODUSU integer,
    PRCODINCONFORMIDADE integer)
as
begin

  /*
    BDTIPOINCONF
    1 - Erros
    2 - Avisos
    3 - Informativos    
  */

  IF (:PRCODINCONFORMIDADE IN(0, 60)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 60
       Inconformidade: A soma receita por atividade Campo 1 do Quadro 02.02 não pode ser maior que o valor da receita bruta total do campo 1 do quadro 02.01
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT CPRB.BDCODEMP, :PRCODUSU, 21 BDCODEVENTO, 60 BDCODINCONF, (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRAPURACAOREINF') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||CPRB.BDCODEMP||'.BDREFERENCIA='||CPRB.BDREFERENCIA||'.BDTABLE=VEF_EMP_TBLOCOPGER.BDAUD=FISCAL',
             'Apuração CPRB - Empresa '||CPRB.BDCODEMP|| ' - Periodo '||(SUBSTRING(cprb.BDREFERENCIA FROM 5 FOR 2)||'/'||SUBSTRING(cprb.BDREFERENCIA FROM 1 FOR 4)) BDCAMINHO,
             NULL BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
        from (
                select FIL.BDCODEMPFILIAL AS BDCODEMP,  FIL.BDCODEMP AS BDCODMATRIZ, FIL.BDCODPERIODO, FIL.BDREFERENCIA
                       ,SUM(IIF(FIL.BDCODQBLOCOP = 4,FIL.BDVALOR,0)) BDVALOR_02_01
                       ,SUM(IIF(FIL.BDCODQBLOCOP = 5,FIL.BDVALOR,0)) BDVALOR_02_02
                from (
                      select a.bdcodemp,a.bdreferencia,a.BDCODPERIODO,A.bdcodconfblocop
                      from vef_emp_tblocopger a
                      left outer join tempresas e on (e.bdcodemp = a.bdcodemp)
                      where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                        and a.bdreferencia between :prRefini and :prreffim
                        and a.BDREINF = 'T'
                    ) CPRB
                INNER join VEF_EMP_TBLOCOPGER_FILIAL FIL on (FIL.BDCODEMP = CPRB.BDCODEMP AND FIL.BDCODPERIODO = CPRB.BDCODPERIODO AND FIL.BDREFERENCIA = CPRB.BDREFERENCIA AND FIL.BDCODCONFBLOCOP = CPRB.BDCODCONFBLOCOP)
                WHERE FIL.BDCODQBLOCOP IN(4,5) AND FIL.bdnumcampo IN(1)
                GROUP BY FIL.BDCODEMPFILIAL,  FIL.BDCODEMP, FIL.BDCODPERIODO, FIL.BDREFERENCIA
              ) CPRB
      where cprb.BDVALOR_02_02 > cprb.bdvalor_02_01
    ;

    END

  IF (:PRCODINCONFORMIDADE IN(0, 61)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 61
       Inconformidade: Valor da exclusão da atividade XXXXXXX campo 2 quadro 02.02 não pode ser maior que o valor da receita bruta da atividade XXXXXXXX campo 01 do Quadro 02.02
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO,BDDESCINCONFESP)
      SELECT CPRB.BDCODEMP, :PRCODUSU, 21 BDCODEVENTO, 61 BDCODINCONF, (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRAPURACAOREINF') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||CPRB.BDCODEMP||'.BDREFERENCIA='||CPRB.BDREFERENCIA||'.BDTABLE=VEF_EMP_TBLOCOPGER.BDAUD=FISCAL',
             'Apuração CPRB - Empresa '||CPRB.BDCODEMP|| ' - Periodo '||(SUBSTRING(cprb.BDREFERENCIA FROM 5 FOR 2)||'/'||SUBSTRING(cprb.BDREFERENCIA FROM 1 FOR 4)) ||' - Atividade '||cprb.bdcodigoatvprev BDCAMINHO,
             NULL BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO,
             (SELECT BDRESULT FROM SP_AUD_DESC_DETALHADA_INCON('$$$$$$$='||FORMATFLOAT('R$ ###,###,##0.00',CPRB.BDVALOR_02_02_02)||'#XXXXXXX='||cprb.bdcodigoatvprev||'#$$$$$$$='||FORMATFLOAT('R$ ###,###,##0.00',cprb.BDVALOR_02_02_01)||'#XXXXXXX='||cprb.bdcodigoatvprev||'#',AD.BDDESCRICAO)) BDDESCINCONFESP
        from (
                select FIL.BDCODEMPFILIAL AS BDCODEMP,  FIL.BDCODEMP AS BDCODMATRIZ, FIL.BDCODPERIODO, FIL.BDREFERENCIA,ati.bdcodigoatvprev
                       ,SUM(IIF(FIL.bdnumcampo = 1,FIL.BDVALOR,0)) BDVALOR_02_02_01
                       ,SUM(IIF(FIL.bdnumcampo = 2,FIL.BDVALOR,0)) BDVALOR_02_02_02
                from (
                      select a.bdcodemp,a.bdreferencia,a.BDCODPERIODO,A.bdcodconfblocop
                      from vef_emp_tblocopger a
                      left outer join tempresas e on (e.bdcodemp = a.bdcodemp)
                      where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                        and a.bdreferencia between :prRefini and :prreffim
                        and a.BDREINF = 'T'
                    ) CPRB
                INNER join VEF_EMP_TBLOCOPGER_FILIAL FIL on (FIL.BDCODEMP = CPRB.BDCODEMP AND FIL.BDCODPERIODO = CPRB.BDCODPERIODO AND FIL.BDREFERENCIA = CPRB.BDREFERENCIA AND FIL.BDCODCONFBLOCOP = CPRB.BDCODCONFBLOCOP)
                left outer join VEF_BASE_TTABATVCONPREV ati on (fil.bdordenatvprev = ati.bdordenatvprev)
                WHERE FIL.BDCODQBLOCOP IN(5) AND FIL.bdnumcampo IN(1,2)
                GROUP BY FIL.BDCODEMPFILIAL,  FIL.BDCODEMP, FIL.BDCODPERIODO, FIL.BDREFERENCIA,ati.bdcodigoatvprev
              ) CPRB
      LEFT OUTER JOIN VAUD_BASE_TDESCINCONF AD ON (AD.bdcodinconf = 61)
      where cprb.BDVALOR_02_02_02 > cprb.BDVALOR_02_02_01    ;

    END

  IF (:PRCODINCONFORMIDADE IN(0, 62)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 62
       Inconformidade: O valor informado no campo 2 do Quadro 02.02 de exclusão da base, deve ser igual a soma dos valores informados no campo valor do ajuste do tipo 0 – Ajustes de exclusão
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT CPRB.BDCODEMP, :PRCODUSU, 21 BDCODEVENTO, 62 BDCODINCONF, (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOAJUSTECPRBREINF') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||CPRB.BDCODEMP||'.BDCHAVE=1'||/*CPRB.BDCHAVE||*/'.BDTABLE=VEF_EMP_TLANAJU_R2060.BDAUD=FISCAL',
             'Apuração CPRB - Empresa '||CPRB.BDCODEMP|| ' - Periodo '||(SUBSTRING(cprb.BDREFERENCIA FROM 5 FOR 2)||'/'||SUBSTRING(cprb.BDREFERENCIA FROM 1 FOR 4)) BDCAMINHO,
             NULL BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
        from (
               select cprb.BDCODEMP,  cprb.BDCODMATRIZ, cprb.BDCODPERIODO, cprb.BDREFERENCIA
                  ,SUM(BDVALOR_02_02_02) BDVALOR_02_02_02 , sum(BDVALORAJUSTE) BDVALORAJUSTE
              from (
                    select FIL.BDCODEMPFILIAL AS BDCODEMP,  FIL.BDCODEMP AS BDCODMATRIZ, FIL.BDCODPERIODO, FIL.BDREFERENCIA
                           ,SUM(IIF(FIL.bdnumcampo = 2,FIL.BDVALOR,0)) BDVALOR_02_02_02 ,0 BDVALORAJUSTE
                    from (
                          select a.bdcodemp,a.bdreferencia,a.BDCODPERIODO,A.bdcodconfblocop
                          from vef_emp_tblocopger a
                          left outer join tempresas e on (e.bdcodemp = a.bdcodemp)
                          where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                            and a.bdreferencia between :prRefini and :prreffim
                            and a.BDREINF = 'T'
                        ) CPRB
                    INNER join VEF_EMP_TBLOCOPGER_FILIAL FIL on (FIL.BDCODEMP = CPRB.BDCODEMP AND FIL.BDCODPERIODO = CPRB.BDCODPERIODO AND FIL.BDREFERENCIA = CPRB.BDREFERENCIA AND FIL.BDCODCONFBLOCOP = CPRB.BDCODCONFBLOCOP)
                    WHERE FIL.BDCODQBLOCOP IN(5) AND FIL.bdnumcampo IN(1,2)
                    GROUP BY FIL.BDCODEMPFILIAL,  FIL.BDCODEMP, FIL.BDCODPERIODO, FIL.BDREFERENCIA
                    UNION ALL
                    SELECT AJ.BDCODEMP,AJ.BDCODEMP BDCODMATRIZ, 7 BDCODPERIODO, aj.BDREFERENCIA,0 BDVALOR_02_02_02, AJ.bdvalor BDVALORAJUSTE
                    FROM VEF_EMP_TLANAJU_R2060 AJ
                    where AJ.bdcodemp = :prcodemp
                      and AJ.bdreferencia between :prRefini and :prreffim
                      AND AJ.BDTIPOAJU = 0
                  ) CPRB
             group by cprb.BDCODEMP,  cprb.BDCODMATRIZ, cprb.BDCODPERIODO, cprb.BDREFERENCIA
            ) CPRB
      where cprb.BDVALOR_02_02_02 <> cprb.BDVALORAJUSTE     ;

    END


  IF (:PRCODINCONFORMIDADE IN(0, 63)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 63
       Inconformidade: O valor informado no campo 3 do Quadro 02.02 de adição da base, deve ser igual a soma dos valores informados no campo valor do ajuste do tipo 1 – Ajustes de adição
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT CPRB.BDCODEMP, :PRCODUSU, 21 BDCODEVENTO, 63 BDCODINCONF, (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOAJUSTECPRBREINF') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||CPRB.BDCODEMP||'.BDCHAVE=1'||/*CPRB.BDCHAVE||*/'.BDTABLE=VEF_EMP_TLANAJU_R2060.BDAUD=FISCAL',
             'Apuração CPRB - Empresa '||CPRB.BDCODEMP|| ' - Periodo '||(SUBSTRING(cprb.BDREFERENCIA FROM 5 FOR 2)||'/'||SUBSTRING(cprb.BDREFERENCIA FROM 1 FOR 4)) BDCAMINHO,
             NULL BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
      from (
             select cprb.BDCODEMP,  cprb.BDCODMATRIZ, cprb.BDCODPERIODO, cprb.BDREFERENCIA
                       ,SUM(BDVALOR_02_02_03) BDVALOR_02_02_03 , sum(BDVALORAJUSTE) BDVALORAJUSTE
             from (
                   select FIL.BDCODEMPFILIAL AS BDCODEMP,  FIL.BDCODEMP AS BDCODMATRIZ, FIL.BDCODPERIODO, FIL.BDREFERENCIA
                       ,SUM(IIF(FIL.bdnumcampo = 3,FIL.BDVALOR,0)) BDVALOR_02_02_03 ,0 BDVALORAJUSTE
                   from (
                          select a.bdcodemp,a.bdreferencia,a.BDCODPERIODO,A.bdcodconfblocop
                          from vef_emp_tblocopger a
                          left outer join tempresas e on (e.bdcodemp = a.bdcodemp)
                          where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                            and a.bdreferencia between :prRefini and :prreffim
                            and a.BDREINF = 'T'
                        ) CPRB
                    INNER join VEF_EMP_TBLOCOPGER_FILIAL FIL on (FIL.BDCODEMP = CPRB.BDCODEMP AND FIL.BDCODPERIODO = CPRB.BDCODPERIODO AND FIL.BDREFERENCIA = CPRB.BDREFERENCIA AND FIL.BDCODCONFBLOCOP = CPRB.BDCODCONFBLOCOP)
                    WHERE FIL.BDCODQBLOCOP IN(5) AND FIL.bdnumcampo IN(3)
                    GROUP BY FIL.BDCODEMPFILIAL,  FIL.BDCODEMP, FIL.BDCODPERIODO, FIL.BDREFERENCIA
                    UNION ALL
                    SELECT AJ.BDCODEMP,AJ.BDCODEMP BDCODMATRIZ, 7 BDCODPERIODO, aj.BDREFERENCIA,0 BDVALOR_02_02_03, AJ.bdvalor BDVALORAJUSTE
                    FROM VEF_EMP_TLANAJU_R2060 AJ
                    where AJ.bdcodemp = :prcodemp
                      and AJ.bdreferencia between :prRefini and :prreffim
                      AND AJ.BDTIPOAJU = 1
                ) CPRB
             group by cprb.BDCODEMP,  cprb.BDCODMATRIZ, cprb.BDCODPERIODO, cprb.BDREFERENCIA
          ) CPRB
      where cprb.BDVALOR_02_02_03 <> cprb.BDVALORAJUSTE       ;

    END


  IF (:PRCODINCONFORMIDADE IN(0, 64)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 64
       Inconformidade: Lançamento de ajuste da CPRB sem informação da descrição 
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT aju.BDCODEMP, :PRCODUSU, 21 BDCODEVENTO, 64 BDCODINCONF, (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOAJUSTECPRBREINF') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||AJU.BDCODEMP||'.BDCHAVE='||AJU.BDCHAVE||'.BDTABLE=VEF_EMP_TLANAJU_R2060.BDAUD=FISCAL',
             'Lançamentos/Reinf/Ajustes CPRB Reinf – Empresa '||aju.BDCODEMP|| ' - Periodo '||(SUBSTRING(aju.BDREFERENCIA FROM 5 FOR 2)||'/'||SUBSTRING(aju.BDREFERENCIA FROM 1 FOR 4))|| ' - Chave '||aju.BDchave BDCAMINHO,
             NULL BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, :PRREFFIM BDREFERENCIA, NULL BDCHAVEPROCESSO
        from (
                SELECT AJ.BDCODEMP,aj.bdreferencia,aj.bdchave
                FROM VEF_EMP_TLANAJU_R2060 AJ
                where AJ.bdcodemp = :prcodemp
                  and AJ.bdreferencia between :prRefini and :prreffim
                  AND ((AJ.bddescricao is null) or (aj.bddescricao = ''))
              ) aju ;
    END

end^


CREATE OR ALTER procedure SP_AUDITORIA_REINF_R2010_2020 (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRCODUSU integer,
    PRCODINCONFORMIDADE integer,
    PRREGVALIDAR varchar(100))
as
declare variable WTIPLANEMI integer;
declare variable WTIPLANREC integer;
begin
  /*
    1 - Erros
    2 - Avisos
    3 - Informativos    
  */
  -- Códigos 2010: 59, 65, 67, 69, 71, 72, 75, 77, 79, 81, 83, 85, 87, 89, 91
  -- Códigos 2020: 55, 66, 68, 70, 73, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92
  wTipLanEmi = -1;
  wTipLanRec = -1;
  if (((prREGVALIDAR = '') or (POSITION('R2010', :PRREGVALIDAR) > 0)) and not(:PRCODINCONFORMIDADE IN(55, 66, 68, 70, 73, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92))) then
    wTipLanRec = 1;
  if (((prREGVALIDAR = '') or (POSITION('R2020', :PRREGVALIDAR) > 0)) and not(:PRCODINCONFORMIDADE IN(59, 65, 67, 69, 71, 72, 75, 77, 79, 81, 83, 85, 87, 89, 91))) then
    wTipLanEmi = 0;


  IF (:PRCODINCONFORMIDADE IN(0, 59,55)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 59,55
       Inconformidade: Número do CNO inválido, de acordo com o layout do R-2010/2020 essa informação deve ter 14 posições.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, IIF(MOV.bdtiplan = 1,18,19) BDCODEVENTO, IIF(MOV.bdtiplan = 1,59,55) BDCODINCONF,
             (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOSERVICO') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSER.BDAUD=FISCAL',
             'Lançamentos/Serviços/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             null BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.bdreflan, NULL BDCHAVEPROCESSO
        from (
                select mov.bdcodemp,mov.bdchave,mov.bdreflan,ded.bdretinss,MOV.bdnumdocini,MOV.bdtiplan
                from (
                      select mov.bdcodemp,mov.bdchave,mov.bdreflan,MOV.bdnumdocini,MOV.bdtiplan, MOV.BDCODTER
                      from VEF_EMP_TMOVSER mov
                      inner join tempresas e on (e.bdcodemp = mov.bdcodemp)
                      where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                        and mov.bdreflan between :prRefini and :prreffim
                        AND MOV.bdcodsitnf not in (2,3,4,5)
                        and mov.bdtiplan in (:wtiplanemi,:wtiplanrec)--rotina pra filtrar os registros de acordo com os parâmetros selecionados na tela da exportação da reinf
                    ) mov
                inner join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = mov.BDCODEMP and DED.BDCHAVE = mov.BDCHAVE)
                left outer join TTERCEIRO TER on (TER.BDCODTER = MOV.BDCODTER)
                where (ded.bdretinss > 0) and (char_length(ded.BDCNO) < 12 ) and ((STRLEN(ter.bdcgcter) = 18) or (DED.BDINDICADOROBRA > 0))
              ) mov    ;
    END

  IF (:PRCODINCONFORMIDADE IN(0, 65,66)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 65,66
       Inconformidade: Nota de serviços recebidos PJ com informação de retenção de INSS sem dados da Reinf preenchidos. Dados obrigatórios para geração do evento R-2010 da Reinf.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, IIF(MOV.bdtiplan = 1,18,19) BDCODEVENTO, IIF(MOV.bdtiplan = 1,65,66) BDCODINCONF,
             (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOSERVICO') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSER.BDAUD=FISCAL',
             'Lançamentos/Serviços/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             '' BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.bdreflan, NULL BDCHAVEPROCESSO
        from (
                select mov.bdcodemp,mov.bdchave,mov.bdreflan,ded.bdretinss,MOV.bdnumdocini,MOV.bdtiplan--,DED.*
                from (
                      select mov.bdcodemp,mov.bdchave,mov.bdreflan,MOV.bdnumdocini,MOV.bdtiplan,MOV.BDCODTER
                      from VEF_EMP_TMOVSER mov
                      inner join tempresas e on (e.bdcodemp = mov.bdcodemp)
                      where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                        and mov.bdreflan between :prRefini and :prreffim
                        AND MOV.bdcodsitnf not in (2,3,4,5)
                        and mov.bdtiplan in (:wtiplanemi,:wtiplanrec)--rotina pra filtrar os registros de acordo com os parâmetros selecionados na tela da exportação da reinf
                    ) mov
                inner join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = mov.BDCODEMP and DED.BDCHAVE = mov.BDCHAVE)  
                left outer join TTERCEIRO TER on (TER.BDCODTER = MOV.BDCODTER)
                where (ded.bdretinss > 0)
                 and (ded.BDCNO is null) and (ded.bdindicadorobra is null) and (ded.BDINCIDCPRB is null)
                 and ((STRLEN(ter.bdcgcter) = 18) or (DED.BDINDICADOROBRA > 0))
              ) mov    ;

    END

 IF (:PRCODINCONFORMIDADE IN(0, 67,68)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 67,68
       Inconformidade: Nota de serviços recebidos PJ com informação de retenção de INSS sem informação do CNPJ. Essa informação é obrigatória no evento R-2010 da Reinf quando o indicador de obra for igual a 1 – Obra de Construção Civil Empreiteira total ou 2 – Obra de Construção Civil Empreitada Parcial.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, IIF(MOV.bdtiplan = 1,18,19) BDCODEVENTO, IIF(MOV.bdtiplan = 1,67,68) BDCODINCONF,
             (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOSERVICO') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSER.BDAUD=FISCAL',
             'Lançamentos/Serviços/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             null BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.bdreflan, NULL BDCHAVEPROCESSO
        from (
                select mov.bdcodemp,mov.bdchave,mov.bdreflan,ded.bdretinss,MOV.bdnumdocini,MOV.bdtiplan--,DED.*
                from (
                      select mov.bdcodemp,mov.bdchave,mov.bdreflan,MOV.bdnumdocini,MOV.bdtiplan,mov.bdcodter
                      from VEF_EMP_TMOVSER mov
                      inner join tempresas e on (e.bdcodemp = mov.bdcodemp)
                      where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                        and mov.bdreflan between :prRefini and :prreffim
                        AND MOV.bdcodsitnf not in (2,3,4,5)
                        and mov.bdtiplan in (:wtiplanemi,:wtiplanrec)--rotina pra filtrar os registros de acordo com os parâmetros selecionados na tela da exportação da reinf
                    ) mov
                inner join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = mov.BDCODEMP and DED.BDCHAVE = mov.BDCHAVE)  
                left outer join TTERCEIRO TER on (TER.BDCODTER = MOV.BDCODTER)
                where (ded.bdretinss > 0) and (ded.BDINDICADOROBRA in(1,2)) and ((ded.BDCNO is null) or (ded.bdcno = '') )
                  and ((STRLEN(ter.bdcgcter) = 18) or (DED.BDINDICADOROBRA > 0))
              ) mov    ;
    END


  IF (:PRCODINCONFORMIDADE IN(0, 69,70)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 69,70
       Inconformidade: Valor da retenção de INSS não confere com o esperado. Conforme evento R-2020 da Reinf este campo não pode ser maior que 11% sobre a base.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, IIF(MOV.bdtiplan = 1,18,19) BDCODEVENTO, IIF(MOV.bdtiplan = 1,69,70) BDCODINCONF,
             (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOSERVICO') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSER.BDAUD=FISCAL',
             'Lançamentos/Serviços/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             null BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.bdreflan, NULL BDCHAVEPROCESSO
        from (
                select mov.bdcodemp,mov.bdchave,mov.bdreflan,ded.bdretinss,MOV.bdnumdocini,MOV.bdtiplan--,DED.*
                from (
                      select mov.bdcodemp,mov.bdchave,mov.bdreflan,MOV.bdnumdocini,MOV.bdtiplan,mov.bdcodter
                      from VEF_EMP_TMOVSER mov
                      inner join tempresas e on (e.bdcodemp = mov.bdcodemp)
                      where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                        and mov.bdreflan between :prRefini and :prreffim
                        AND MOV.bdcodsitnf not in (2,3,4,5)
                        and mov.bdtiplan in (:wtiplanemi,:wtiplanrec)--rotina pra filtrar os registros de acordo com os parâmetros selecionados na tela da exportação da reinf
                    ) mov
                inner join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = mov.BDCODEMP and DED.BDCHAVE = mov.BDCHAVE)
                LEFT OUTER JOIN VEF_EMP_TMOVSERITENS I on (i.bdcodemp = mov.bdcodemp and i.bdchave = mov.bdchave)  
                left outer join TTERCEIRO TER on (TER.BDCODTER = MOV.BDCODTER)
                where (ded.bdretinss > 0) and ( ded.bdretinss > cast(((i.bdvlrcontab -(ded.bdvlrmateriais+ded.bdvlrsubempreiteiras )) * 0.11) as numeric(15,2)) )
                  and ((STRLEN(ter.bdcgcter) = 18) or (DED.BDINDICADOROBRA > 0))
              ) mov    ;
    END


  IF (:PRCODINCONFORMIDADE IN(0, 71,72)) THEN     --2010
    BEGIN
      /*************************************************************************************************************
       Código: 71,72
       Inconformidade: Valor da retenção de INSS não confere com o indicador 0 – Não é contribuinte da CPRB – 11%. 
                       Valor da retenção de INSS não confere com o indicador 1 – Contribuinte da  CPRB – 3,5%.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, 18 BDCODEVENTO, IIF(MOV.bdincidcprb = 0,71,72) BDCODINCONF,
             (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOSERVICO') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSER.BDAUD=FISCAL',
             'Lançamentos/Serviços/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             null BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.bdreflan, NULL BDCHAVEPROCESSO
        from (
              select mov.bdcodemp,mov.bdchave,mov.bdreflan,mov.bdretinss,MOV.bdnumdocini,MOV.bdtiplan,mov.bdincidcprb
              from (
                    select mov.bdcodemp,mov.bdchave,mov.bdreflan,ded.bdretinss,MOV.bdnumdocini,MOV.bdtiplan,coalesce(ded.bdincidcprb,0) bdincidcprb,
                     cast(((i.bdvlrcontab -(ded.bdvlrmateriais+ded.bdvlrsubempreiteiras )) * 0.11) as numeric(15,2)) BDVLRINSS_11,
                     cast(((i.bdvlrcontab -(ded.bdvlrmateriais+ded.bdvlrsubempreiteiras )) * 0.035) as numeric(15,2)) BDVLRINSS_3_5
                    from (
                          select mov.bdcodemp,mov.bdchave,mov.bdreflan,MOV.bdnumdocini,MOV.bdtiplan,mov.bdcodter
                          from VEF_EMP_TMOVSER mov
                          inner join tempresas e on (e.bdcodemp = mov.bdcodemp)
                          where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                            and mov.bdreflan between :prRefini and :prreffim
                            AND MOV.bdcodsitnf not in (2,3,4,5)
--                            AND MOV.bdtiplan = 1
                            and mov.bdtiplan in (:wtiplanrec)--rotina pra filtrar os registros de acordo com os parâmetros selecionados na tela da exportação da reinf
                        ) mov
                    inner join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = mov.BDCODEMP and DED.BDCHAVE = mov.BDCHAVE)
                    LEFT OUTER JOIN VEF_EMP_TMOVSERITENS I on (i.bdcodemp = mov.bdcodemp and i.bdchave = mov.bdchave)  
                    left outer join TTERCEIRO TER on (TER.BDCODTER = MOV.BDCODTER)
                    where (ded.bdretinss > 0)
                      and ((STRLEN(ter.bdcgcter) = 18) or (DED.BDINDICADOROBRA > 0))
                  )mov
              WHERE  ((mov.bdincidcprb = 0 ) and (BDVLRINSS_11 <> mov.bdretinss))
                  or ((mov.bdincidcprb = 1 ) and (BDVLRINSS_3_5 <> mov.bdretinss))

              ) mov    ;
    END



  IF (:PRCODINCONFORMIDADE IN(0, 73,74)) THEN  --2020
    BEGIN
      /*************************************************************************************************************
       Código: 73,74
       Inconformidade: Empresa não é contribuinte da CPRB e valor da retenção de INSS não confere com o percentual esperado de 11%.  Conforme evento R-2020 da Reinf este campo deve ser apurado de acordo com a legislação vigente.  
                       Empresa é contribuinte da CPRB e valor da retenção de INSS não confere com o percentual esperado de 3,5%.  Conforme evento R-2020 da Reinf este campo deve ser apurado de acordo com a legislação vigente.  
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, 19 BDCODEVENTO, IIF(MOV.bdcodconfcprbreinf = 0,73,74) BDCODINCONF,
             (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOSERVICO') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSER.BDAUD=FISCAL',
             'Lançamentos/Serviços/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             null BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.bdreflan, NULL BDCHAVEPROCESSO
        from (
              select mov.bdcodemp,mov.bdchave,mov.bdreflan,mov.bdretinss,MOV.bdnumdocini,MOV.bdtiplan,mov.bdcodconfcprbreinf
              from (
                    select mov.bdcodemp,mov.bdchave,mov.bdreflan,ded.bdretinss,MOV.bdnumdocini,MOV.bdtiplan,coalesce(parger.bdcodconfcprbreinf,0) bdcodconfcprbreinf,
                     cast(((i.bdvlrcontab -(coalesce(ded.bdvlrmateriais,0)+coalesce(ded.bdvlrsubempreiteiras,0) )) * 0.11) as numeric(15,2)) BDVLRINSS_11,
                     cast(((i.bdvlrcontab -(coalesce(ded.bdvlrmateriais,0)+coalesce(ded.bdvlrsubempreiteiras,0) )) * 0.035) as numeric(15,2)) BDVLRINSS_3_5
                    from (
                          select mov.bdcodemp,mov.bdchave,mov.bdreflan,MOV.bdnumdocini,MOV.bdtiplan,mov.bdcodter
                          from VEF_EMP_TMOVSER mov
                          inner join tempresas e on (e.bdcodemp = mov.bdcodemp)
                          where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                            and mov.bdreflan between :prRefini and :prreffim
                            AND MOV.bdcodsitnf not in (2,3,4,5)
--                            AND MOV.bdtiplan = 0
                            and mov.bdtiplan in (:wtiplanemi)--rotina pra filtrar os registros de acordo com os parâmetros selecionados na tela da exportação da reinf
                        ) mov
                    inner join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = mov.BDCODEMP and DED.BDCHAVE = mov.BDCHAVE)
                    LEFT OUTER JOIN VEF_EMP_TMOVSERITENS I on (i.bdcodemp = mov.bdcodemp and i.bdchave = mov.bdchave)
                    INNER join (SELECT BDCODEMP,
                                       COALESCE((SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x WHERE x.bdcodemp = :PRCODEMP AND X.BDREFEMP <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database) ORDER BY x.bdcodemp DESC, x.bdrefemp DESC )
                                               ,(SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x WHERE x.bdcodemp = :PRCODEMP AND x.bdcodplapadrao IS NOT NULL AND x.bdcodhist IS NOT NULL ORDER BY x.bdcodemp, x.bdrefemp )
                                               ,(SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x WHERE x.bdcodemp = :PRCODEMP ORDER BY x.bdcodemp, x.bdrefemp )
                                               ) BDREFEMP
                               from tempresas where bdcodemp = :PRCODEMP
                               ) REF on (REF.bdcodemp = mov.bdcodemp)
                    JOIN vef_base_tempparger parger ON (parger.bdcodemp = REF.bdCODEMP AND parger.bdrefemp = REF.bdrefemp)     
                    left outer join TTERCEIRO TER on (TER.BDCODTER = MOV.BDCODTER)
                    where (ded.bdretinss > 0)
                      and ((STRLEN(ter.bdcgcter) = 18) or (DED.BDINDICADOROBRA > 0))
                  )mov
              WHERE  ((mov.bdcodconfcprbreinf = 0 ) and (BDVLRINSS_11 <> mov.bdretinss))
                  or ((mov.bdcodconfcprbreinf > 0 ) and (BDVLRINSS_3_5 <> mov.bdretinss))

              ) mov    ;
    END


 IF (:PRCODINCONFORMIDADE IN(0, 75,76)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 75,76
       Inconformidade: Participante com CNPJ inválido, essa informação é obrigatória para indicador da obra igual a 1 – Empreitada Total no evento R-2010 da Reinf. 
                       Participante com CNPJ inválido, essa informação é obrigatória para indicador da obra igual a 0 – Não é obra de construção civil no evento R-2020 da Reinf.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, IIF(MOV.bdtiplan = 1,18,19) BDCODEVENTO, IIF(MOV.bdtiplan = 1,75,76) BDCODINCONF,
             (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOSERVICO') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSER.BDAUD=FISCAL',
             'Lançamentos/Serviços/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             null BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.bdreflan, NULL BDCHAVEPROCESSO
        from (
              select mov.bdcodemp,mov.bdchave,mov.bdreflan,mov.bdretinss,MOV.bdnumdocini,MOV.bdtiplan
              from (
                    select mov.bdcodemp,mov.bdchave,mov.bdreflan,ded.bdretinss,MOV.bdnumdocini,MOV.bdtiplan,COALESCE(DED.bdindicadorobra,0) bdindicadorobra
                    ,iif(CHAR_LENGTH(ter.bdcgcter) < 18,'FALSE',(SELECT BDISVALID FROM SP_VALIDA_CNPJ(ter.bdcgcter))) BDISVALID
                    from (
                          select mov.bdcodemp,mov.bdchave,mov.bdreflan,MOV.bdnumdocini,MOV.bdtiplan,mov.bdcodter
                          from VEF_EMP_TMOVSER mov
                          inner join tempresas e on (e.bdcodemp = mov.bdcodemp)
                          where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                            and mov.bdreflan between :prRefini and :prreffim
                            AND MOV.bdcodsitnf not in (2,3,4,5)
                            and mov.bdtiplan in (:wtiplanemi,:wtiplanrec)--rotina pra filtrar os registros de acordo com os parâmetros selecionados na tela da exportação da reinf
                        ) mov
                    inner join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = mov.BDCODEMP and DED.BDCHAVE = mov.BDCHAVE)
                    left outer join tterceiro ter on (ter.bdcodter = mov.bdcodter)
                    where (ded.bdretinss > 0)
                      and ((STRLEN(ter.bdcgcter) = 18) or (DED.BDINDICADOROBRA > 0))
                  )mov
               WHERE ((MOV.bdtiplan = 0) AND (MOV.bdindicadorobra = 0) AND (MOV.BDISVALID = 'FALSE'))
                  or ((MOV.bdtiplan = 1) AND (MOV.BDISVALID = 'FALSE'))

              ) mov    ;
    END

  IF (:PRCODINCONFORMIDADE IN(0, 77,78)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 77,78
       Inconformidade: Nota de serviços tomados PJ com informação de retenção não efetuada de INSS sem informação do código do processo relacionado. Essa informação é obrigatória no evento R-2010 da Reinf.
                       Nota de serviços emitidos PJ com informação de retenção não efetuada de INSS sem informação do código do processo relacionado. Essa informação é obrigatória no evento R-2020 da Reinf.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, IIF(MOV.bdtiplan = 1,18,19) BDCODEVENTO, IIF(MOV.bdtiplan = 1,77,78) BDCODINCONF,
             (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOSERVICO') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSER.BDAUD=FISCAL',
             'Lançamentos/Serviços/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             null BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.bdreflan, NULL BDCHAVEPROCESSO
        from (
              select mov.bdcodemp,mov.bdchave,mov.bdreflan,mov.bdretinss,MOV.bdnumdocini,MOV.bdtiplan
              from (
                    select mov.bdcodemp,mov.bdchave,mov.bdreflan,ded.bdretinss,MOV.bdnumdocini,MOV.bdtiplan
                    ,coalesce(DED.BDVLRNRETPRINC,0) BDVLRNRETPRINC,coalesce(DED.BDVLRNRETADIC,0) BDVLRNRETADIC,
                    DED.BDCODPROCESSOPRINC,DED.BDCODPROCESSOADIC,DED.BDCODITEMPROCPRINC,DED.BDCODITEMPROCADIC
                    from (
                          select mov.bdcodemp,mov.bdchave,mov.bdreflan,MOV.bdnumdocini,MOV.bdtiplan,mov.bdcodter
                          from VEF_EMP_TMOVSER mov
                          inner join tempresas e on (e.bdcodemp = mov.bdcodemp)
                          where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                            and mov.bdreflan between :prRefini and :prreffim
                            AND MOV.bdcodsitnf not in (2,3,4,5)
                            and mov.bdtiplan in (:wtiplanemi,:wtiplanrec)--rotina pra filtrar os registros de acordo com os parâmetros selecionados na tela da exportação da reinf
                        ) mov
                    inner join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = mov.BDCODEMP and DED.BDCHAVE = mov.BDCHAVE) 
                    left outer join TTERCEIRO TER on (TER.BDCODTER = MOV.BDCODTER)
                    where (ded.bdretinss > 0)
                      and ((STRLEN(ter.bdcgcter) = 18) or (DED.BDINDICADOROBRA > 0))
                  )mov
               WHERE ((MOV.BDVLRNRETPRINC > 0) AND (MOV.BDCODPROCESSOPRINC is null))
              ) mov    ;
    END

  IF (:PRCODINCONFORMIDADE IN(0, 79,80)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 79,80
       Inconformidade:Nota de serviços tomados PJ com informação de retenção adicional não efetuada de INSS sem informação do código do processo relacionado. Essa informação é obrigatória no evento R-2010 da Reinf.
                      Nota de serviços emitidos PJ com informação de retenção adicional não efetuada de INSS sem informação do código do processo relacionado. Essa informação é obrigatória no evento R-2020 da Reinf.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, IIF(MOV.bdtiplan = 1,18,19) BDCODEVENTO, IIF(MOV.bdtiplan = 1,79,80) BDCODINCONF,
             (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOSERVICO') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSER.BDAUD=FISCAL',
             'Lançamentos/Serviços/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             null BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.bdreflan, NULL BDCHAVEPROCESSO
        from (
              select mov.bdcodemp,mov.bdchave,mov.bdreflan,mov.bdretinss,MOV.bdnumdocini,MOV.bdtiplan
              from (
                    select mov.bdcodemp,mov.bdchave,mov.bdreflan,ded.bdretinss,MOV.bdnumdocini,MOV.bdtiplan
                    ,coalesce(DED.BDVLRNRETPRINC,0) BDVLRNRETPRINC,coalesce(DED.BDVLRNRETADIC,0) BDVLRNRETADIC,
                    DED.BDCODPROCESSOPRINC,DED.BDCODPROCESSOADIC,DED.BDCODITEMPROCPRINC,DED.BDCODITEMPROCADIC
                    from (
                          select mov.bdcodemp,mov.bdchave,mov.bdreflan,MOV.bdnumdocini,MOV.bdtiplan,mov.bdcodter
                          from VEF_EMP_TMOVSER mov
                          inner join tempresas e on (e.bdcodemp = mov.bdcodemp)
                          where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                            and mov.bdreflan between :prRefini and :prreffim
                            AND MOV.bdcodsitnf not in (2,3,4,5)
                            and mov.bdtiplan in (:wtiplanemi,:wtiplanrec)--rotina pra filtrar os registros de acordo com os parâmetros selecionados na tela da exportação da reinf
                        ) mov
                    inner join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = mov.BDCODEMP and DED.BDCHAVE = mov.BDCHAVE)  
                    left outer join TTERCEIRO TER on (TER.BDCODTER = MOV.BDCODTER)
                    where (ded.bdretinss > 0)
                      and ((STRLEN(ter.bdcgcter) = 18) or (DED.BDINDICADOROBRA > 0))
                  )mov
               WHERE ((MOV.BDVLRNRETADIC > 0) AND (MOV.BDCODPROCESSOADIC is null))

              ) mov    ;
    END



  IF (:PRCODINCONFORMIDADE IN(0, 81,82)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 81,82
       Inconformidade:Nota de serviços emitidos PJ com informação de retenção subcontrata superior ao valor do INSS. 
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, IIF(MOV.bdtiplan = 1,18,19) BDCODEVENTO, IIF(MOV.bdtiplan = 1,81,82) BDCODINCONF,
             (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOSERVICO') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSER.BDAUD=FISCAL',
             'Lançamentos/Serviços/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             null BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.bdreflan, NULL BDCHAVEPROCESSO
        from (
              select mov.bdcodemp,mov.bdchave,mov.bdreflan,mov.bdretinss,MOV.bdnumdocini,MOV.bdtiplan
              from (
                    select mov.bdcodemp,mov.bdchave,mov.bdreflan,ded.bdretinss,MOV.bdnumdocini,MOV.bdtiplan
                    ,ded.bdvlrretdestsub
                    from (
                          select mov.bdcodemp,mov.bdchave,mov.bdreflan,MOV.bdnumdocini,MOV.bdtiplan,mov.bdcodter
                          from VEF_EMP_TMOVSER mov
                          inner join tempresas e on (e.bdcodemp = mov.bdcodemp)
                          where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                            and mov.bdreflan between :prRefini and :prreffim
                            AND MOV.bdcodsitnf not in (2,3,4,5)
                            and mov.bdtiplan in (:wtiplanemi,:wtiplanrec)--rotina pra filtrar os registros de acordo com os parâmetros selecionados na tela da exportação da reinf
                        ) mov
                    inner join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = mov.BDCODEMP and DED.BDCHAVE = mov.BDCHAVE)   
                    left outer join TTERCEIRO TER on (TER.BDCODTER = MOV.BDCODTER)
                    where (ded.bdretinss > 0)
                      and ((STRLEN(ter.bdcgcter) = 18) or (DED.BDINDICADOROBRA > 0))
                  )mov
               WHERE ((MOV.bdvlrretdestsub > mov.bdretinss))
              ) mov    ;
    END

  IF (:PRCODINCONFORMIDADE IN(0, 83,84)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 83,84
       Inconformidade:Nota de serviços tomados PJ com informação de valores de serviços por segurado após 15 anos não pode ser superior ao valor da base de cálculo da retenção da contribuição previdenciária.
                      Nota de serviços emitidos PJ com informação de valores de serviços prestados por segurado após 15 anos não pode ser superior ao valor da base de cálculo da retenção da contribuição previdenciária.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, IIF(MOV.bdtiplan = 1,18,19) BDCODEVENTO, IIF(MOV.bdtiplan = 1,83,84) BDCODINCONF,
             (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOSERVICO') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSER.BDAUD=FISCAL',
             'Lançamentos/Serviços/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             null BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.bdreflan, NULL BDCHAVEPROCESSO
        from (
              select mov.bdcodemp,mov.bdchave,mov.bdreflan,mov.bdretinss,MOV.bdnumdocini,MOV.bdtiplan,mov.bdvalornota
              from (
                    select mov.bdcodemp,mov.bdchave,mov.bdreflan,ded.bdretinss,MOV.bdnumdocini,MOV.bdtiplan,mov.bdvalornota
                    ,coalesce(ded.BDVLRREC15,0) BDVLRREC15,coalesce(ded.BDVLRREC20,0) BDVLRREC20,coalesce(ded.BDVLRREC25,0) BDVLRREC25

                    from (
                          select mov.bdcodemp,mov.bdchave,mov.bdreflan,MOV.bdnumdocini,MOV.bdtiplan,mov.bdvalornota,mov.bdcodter
                          from VEF_EMP_TMOVSER mov
                          inner join tempresas e on (e.bdcodemp = mov.bdcodemp)
                          where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                            and mov.bdreflan between :prRefini and :prreffim
                            AND MOV.bdcodsitnf not in (2,3,4,5)
                            and mov.bdtiplan in (:wtiplanemi,:wtiplanrec)--rotina pra filtrar os registros de acordo com os parâmetros selecionados na tela da exportação da reinf
                        ) mov
                    inner join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = mov.BDCODEMP and DED.BDCHAVE = mov.BDCHAVE)  
                    left outer join TTERCEIRO TER on (TER.BDCODTER = MOV.BDCODTER)
                    where (ded.bdretinss > 0)
                      and ((STRLEN(ter.bdcgcter) = 18) or (DED.BDINDICADOROBRA > 0))
                  )mov
               WHERE ((MOV.BDVLRREC15 > mov.bdvalornota))
             ) mov    ;
    END
  IF (:PRCODINCONFORMIDADE IN(0, 85,86)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 85,86
       Inconformidade:Nota de serviços tomados PJ com informação de valores de serviços por segurado após 20 anos não pode ser superior ao valor da base de cálculo da retenção da contribuição previdenciária.
                      Nota de serviços emitidos PJ com informação de valores de serviços prestados por segurado após 20 anos não pode ser superior ao valor da base de cálculo da retenção da contribuição previdenciária.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, IIF(MOV.bdtiplan = 1,18,19) BDCODEVENTO, IIF(MOV.bdtiplan = 1,85,86) BDCODINCONF,
             (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOSERVICO') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSER.BDAUD=FISCAL',
             'Lançamentos/Serviços/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             null BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.bdreflan, NULL BDCHAVEPROCESSO
        from (
              select mov.bdcodemp,mov.bdchave,mov.bdreflan,mov.bdretinss,MOV.bdnumdocini,MOV.bdtiplan,mov.bdvalornota
              from (
                    select mov.bdcodemp,mov.bdchave,mov.bdreflan,ded.bdretinss,MOV.bdnumdocini,MOV.bdtiplan,mov.bdvalornota
                    ,coalesce(ded.BDVLRREC15,0) BDVLRREC15,coalesce(ded.BDVLRREC20,0) BDVLRREC20,coalesce(ded.BDVLRREC25,0) BDVLRREC25

                    from (
                          select mov.bdcodemp,mov.bdchave,mov.bdreflan,MOV.bdnumdocini,MOV.bdtiplan,mov.bdvalornota,mov.bdcodter
                          from VEF_EMP_TMOVSER mov
                          inner join tempresas e on (e.bdcodemp = mov.bdcodemp)
                          where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                            and mov.bdreflan between :prRefini and :prreffim
                            AND MOV.bdcodsitnf not in (2,3,4,5)
                            and mov.bdtiplan in (:wtiplanemi,:wtiplanrec)--rotina pra filtrar os registros de acordo com os parâmetros selecionados na tela da exportação da reinf
                        ) mov
                    inner join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = mov.BDCODEMP and DED.BDCHAVE = mov.BDCHAVE)
                    left outer join TTERCEIRO TER on (TER.BDCODTER = MOV.BDCODTER)
                    where (ded.bdretinss > 0)
                      and ((STRLEN(ter.bdcgcter) = 18) or (DED.BDINDICADOROBRA > 0))
                  )mov
               WHERE ((MOV.BDVLRREC20 > mov.bdvalornota))
             ) mov    ;
    END

  IF (:PRCODINCONFORMIDADE IN(0, 87,88)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 87,88
       Inconformidade:Nota de serviços tomados PJ com informação de valores de serviços por segurado após 25 anos não pode ser superior ao valor da base de cálculo da retenção da contribuição previdenciária.
                      Nota de serviços emitidos PJ com informação de valores de serviços prestados por segurado após 25 anos não pode ser superior ao valor da base de cálculo da retenção da contribuição previdenciária.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, IIF(MOV.bdtiplan = 1,18,19) BDCODEVENTO, IIF(MOV.bdtiplan = 1,87,88) BDCODINCONF,
             (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOSERVICO') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSER.BDAUD=FISCAL',
             'Lançamentos/Serviços/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             null BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.bdreflan, NULL BDCHAVEPROCESSO
        from (
              select mov.bdcodemp,mov.bdchave,mov.bdreflan,mov.bdretinss,MOV.bdnumdocini,MOV.bdtiplan,mov.bdvalornota
              from (
                    select mov.bdcodemp,mov.bdchave,mov.bdreflan,ded.bdretinss,MOV.bdnumdocini,MOV.bdtiplan,mov.bdvalornota
                    ,coalesce(ded.BDVLRREC15,0) BDVLRREC15,coalesce(ded.BDVLRREC20,0) BDVLRREC20,coalesce(ded.BDVLRREC25,0) BDVLRREC25
                    from (
                          select mov.bdcodemp,mov.bdchave,mov.bdreflan,MOV.bdnumdocini,MOV.bdtiplan,mov.bdvalornota,mov.bdcodter
                          from VEF_EMP_TMOVSER mov
                          inner join tempresas e on (e.bdcodemp = mov.bdcodemp)
                          where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                            and mov.bdreflan between :prRefini and :prreffim
                            AND MOV.bdcodsitnf not in (2,3,4,5)
                            and mov.bdtiplan in (:wtiplanemi,:wtiplanrec)--rotina pra filtrar os registros de acordo com os parâmetros selecionados na tela da exportação da reinf
                        ) mov
                    inner join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = mov.BDCODEMP and DED.BDCHAVE = mov.BDCHAVE)   
                    left outer join TTERCEIRO TER on (TER.BDCODTER = MOV.BDCODTER)
                    where (ded.bdretinss > 0)
                      and ((STRLEN(ter.bdcgcter) = 18) or (DED.BDINDICADOROBRA > 0))
                  )mov
               WHERE ((MOV.BDVLRREC25 > mov.bdvalornota))
             ) mov    ;
    END

  IF (:PRCODINCONFORMIDADE IN(0, 89,90)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 89,90
       Inconformidade: Total dos valores de serviços tomados sujeitos a aposentadoria especial não pode ser superior ao valor da base de cálculo da retenção da contribuição previdenciária.
                       Total dos valores de serviços prestados sujeitos a aposentadoria especial não pode ser superior ao valor da base de cálculo da retenção da contribuição previdenciária.
      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, IIF(MOV.bdtiplan = 1,18,19) BDCODEVENTO, IIF(MOV.bdtiplan = 1,89,90) BDCODINCONF,
             (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOSERVICO') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSER.BDAUD=FISCAL',
             'Lançamentos/Serviços/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             null BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.bdreflan, NULL BDCHAVEPROCESSO
        from (
              select mov.bdcodemp,mov.bdchave,mov.bdreflan,mov.bdretinss,MOV.bdnumdocini,MOV.bdtiplan,mov.bdvalornota
              from (
                    select mov.bdcodemp,mov.bdchave,mov.bdreflan,ded.bdretinss,MOV.bdnumdocini,MOV.bdtiplan,mov.bdvalornota
                    ,coalesce(ded.BDVLRREC15,0) BDVLRREC15,coalesce(ded.BDVLRREC20,0) BDVLRREC20,coalesce(ded.BDVLRREC25,0) BDVLRREC25
                    from (
                          select mov.bdcodemp,mov.bdchave,mov.bdreflan,MOV.bdnumdocini,MOV.bdtiplan,mov.bdvalornota,mov.bdcodter
                          from VEF_EMP_TMOVSER mov
                          inner join tempresas e on (e.bdcodemp = mov.bdcodemp)
                          where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                            and mov.bdreflan between :prRefini and :prreffim
                            AND MOV.bdcodsitnf not in (2,3,4,5)
                            and mov.bdtiplan in (:wtiplanemi,:wtiplanrec)--rotina pra filtrar os registros de acordo com os parâmetros selecionados na tela da exportação da reinf
                        ) mov
                    inner join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = mov.BDCODEMP and DED.BDCHAVE = mov.BDCHAVE) 
                    left outer join TTERCEIRO TER on (TER.BDCODTER = MOV.BDCODTER)
                    where (ded.bdretinss > 0)
                      and ((STRLEN(ter.bdcgcter) = 18) or (DED.BDINDICADOROBRA > 0))
                  )mov
               WHERE (((MOV.BDVLRREC15+MOV.BDVLRREC20+MOV.BDVLRREC25) > mov.bdvalornota))
             ) mov    ;
    END


  IF (:PRCODINCONFORMIDADE IN(0, 91,92)) THEN
    BEGIN
      /*************************************************************************************************************
       Código: 91,92
       Inconformidade: Nota de serviços recebidos PJ com informação de retenção de INSS sem informação do tipo de serviço conforme tabela 6. Essa informação é obrigatória no evento R-2010 e 2020 da Reinf.

      *************************************************************************************************************/
      INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO, BDCHAVECAD,
                                            BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO)
      SELECT MOV.BDCODEMP, :PRCODUSU, IIF(MOV.bdtiplan = 1,18,19) BDCODEVENTO, IIF(MOV.bdtiplan = 1,91,92) BDCODINCONF,
             (SELECT FIRST 1 BDCODTELASIS FROM TTELA_SISTEMA WHERE BDNOMETELA = 'TFRLANCAMENTOSERVICO') BDCODTELASIS,
             '' BDCAMPO,'BDCODEMP='||MOV.BDCODEMP||'.BDCHAVE='||MOV.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSER.BDAUD=FISCAL',
             'Lançamentos/Serviços/Empresa '||MOV.BDCODEMP|| ' chave '||MOV.BDCHAVE||' NF '||MOV.bdnumdocini BDCAMINHO,
             null BDPARAMETROSDESC, 'FALSE' BDIGNORAINC, mov.bdreflan, NULL BDCHAVEPROCESSO
        from (
              select mov.bdcodemp,mov.bdchave,mov.bdreflan,mov.bdretinss,MOV.bdnumdocini,MOV.bdtiplan
              from (
                    select mov.bdcodemp,mov.bdchave,mov.bdreflan,ded.bdretinss,MOV.bdnumdocini,MOV.bdtiplan
                    from (
                          select mov.bdcodemp,mov.bdchave,mov.bdreflan,MOV.bdnumdocini,MOV.bdtiplan,mov.bdcodter
                          from VEF_EMP_TMOVSER mov
                          inner join tempresas e on (e.bdcodemp = mov.bdcodemp)
                          where coalesce(e.bdcodmatriz,e.bdcodemp) = :prcodemp
                            and mov.bdreflan between :prRefini and :prreffim
                            AND MOV.bdcodsitnf not in (2,3,4,5)
                            and mov.bdtiplan in (:wtiplanemi,:wtiplanrec)--rotina pra filtrar os registros de acordo com os parâmetros selecionados na tela da exportação da reinf
                        ) mov
                    inner join VEF_EMP_TMOVSERDED DED on (DED.BDCODEMP = mov.BDCODEMP and DED.BDCHAVE = mov.BDCHAVE)  
                    left outer join TTERCEIRO TER on (TER.BDCODTER = MOV.BDCODTER)
                    where (ded.bdretinss > 0) and (ded.BDORDEMTAB6_TPSER is null)
                      and ((STRLEN(ter.bdcgcter) = 18) or (DED.BDINDICADOROBRA > 0))
                  )mov
             ) mov    ;
    END


end^


CREATE OR ALTER procedure SP_AUDITORIA_REINF (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRCODUSU integer,
    PRCODINCONFORMIDADE integer,
    PRREGVALIDAR varchar(100) = '')
as
begin


  /*************************************************************************************
  *                                       R-1000                                       *
  *************************************************************************************/
  if ((prREGVALIDAR = '') or (POSITION('R1000', :PRREGVALIDAR) > 0)) then
  execute procedure SP_AUDITORIA_REINF_R1000(:PRCODEMP, :PRREFINI, :PRREFFIM, :PRCODUSU, :PRCODINCONFORMIDADE);


  /*************************************************************************************
  *                                       R-2010/2020                                  *
  *************************************************************************************/
  execute procedure SP_AUDITORIA_REINF_R2010_2020(:PRCODEMP, :PRREFINI, :PRREFFIM, :PRCODUSU, :PRCODINCONFORMIDADE,PRREGVALIDAR);


  /*************************************************************************************
  *                                       R-2050                                       *
  *************************************************************************************/
  if ((prREGVALIDAR = '') or (POSITION('R2050', :PRREGVALIDAR) > 0)) then
  execute procedure SP_AUDITORIA_REINF_R2050(:PRCODEMP, :PRREFINI, :PRREFFIM, :PRCODUSU, :PRCODINCONFORMIDADE);

  /*************************************************************************************
  *                                       R-2055                                       *
  *************************************************************************************/
  if ((prREGVALIDAR = '') or (POSITION('R2055', :PRREGVALIDAR) > 0)) then
  execute procedure SP_AUDITORIA_REINF_R2055(:PRCODEMP, :PRREFINI, :PRREFFIM, :PRCODUSU, :PRCODINCONFORMIDADE);

  /*************************************************************************************
  *                                       R-2060                                       *
  *************************************************************************************/
  if ((prREGVALIDAR = '') or (POSITION('R2060', :PRREGVALIDAR) > 0)) then
  execute procedure SP_AUDITORIA_REINF_R2060(:PRCODEMP, :PRREFINI, :PRREFFIM, :PRCODUSU, :PRCODINCONFORMIDADE);


end^

CREATE OR ALTER procedure SP_AUDITOR_FISCAL (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRAUDITORIAREINF DM_BOOLEAN,
    PRCODINCONFORMIDADE integer = 0,
    PRREGVALIDAR varchar(100) = '',
    PRAUDITORIADOCS DM_BOOLEAN = '')
as
declare variable WCODUSU integer;
declare variable WSQL varchar(5000);
declare variable WWEREEMP varchar(5000);
declare variable wemp integer;
begin
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREFINI);
  SELECT BDCODUSU FROM SP_GET_USUARIO INTO :wCodUsu;

  wWereEmp = '';
  for select bdcodemp from tempresas where bdcodmatriz = :prCodemp into wemp
    do
      begin
         if (wWereEmp = '') then
           wWereEmp = wemp;
         else
           wWereEmp = wWereEmp || ','||wemp;
      end

  if (wwereemp = '') then
    wWereEmp = wWereEmp ||prCodemp;
  else
    wWereEmp = wWereEmp || ','||prCodemp;

  wSQL =          ' WHERE BDCODEMP in( '||wWereEmp||')';
  wSQL = :wSQL || ' AND BDREFERENCIA >= '||:PRREFINI;
  wSQL = :wSQL || ' AND BDREFERENCIA <= '||:PRREFFIM;
  IF (:PRCODINCONFORMIDADE > 0) THEN
    wSQL = :wSQL || ' AND BDCODINCONF = '||:PRCODINCONFORMIDADE;

  wSQL = :wSQL||' AND (BDCODEVENTO IN (SELECT BDCODEVENTO FROM VAUD_BASE_TEVENTO WHERE (BDCODTIPOEXP in (-1';
  IF (UPPER(:PRAUDITORIAREINF) = 'TRUE') THEN wSQL = :wSQL||',4';
  IF (UPPER(:PRAUDITORIADOCS ) = 'TRUE') THEN wSQL = :wSQL||',6';
  wSQL = :wSQL || '))))';

  -- Salva registros ignorados
  IF (UPPER(:PRAUDITORIADOCS) = 'TRUE') THEN
     BEGIN
       EXECUTE STATEMENT 'INSERT INTO TMP_VAUD_EMP_TINCONFORMIDADES'||
                              ' (BDCODEMP, BDCHAVEINCONF, BDCODINCONF, BDCODEVENTO, BDCHAVECAD, BDIGNORAINC, BDREFERENCIA, BDPARAMETROSDESC, BDDESCINCONFESP)'||
                        ' SELECT BDCODEMP, BDCHAVEINCONF, BDCODINCONF, BDCODEVENTO, BDCHAVECAD, BDIGNORAINC, BDREFERENCIA, BDPARAMETROSDESC, BDDESCINCONFESP'||
                        ' FROM VAUD_EMP_TINCONFORMIDADES'||:wSQL||
                         ' AND (UPPER(BDIGNORAINC) = ''TRUE'')';
     END

  EXECUTE STATEMENT 'DELETE FROM VAUD_EMP_TINCONFORMIDADES'||:wSQL;

  /*Auditoria da Reinf*/
  IF (UPPER(:PRAUDITORIAREINF) = 'TRUE') THEN
    EXECUTE PROCEDURE SP_AUDITORIA_REINF(:PRCODEMP, :PRREFINI, :PRREFFIM, :wCodUsu, :PRCODINCONFORMIDADE,:PRREGVALIDAR);

  -- 138704 - Raphael Teodoro - 23/09/2020
  /*Auditoria de Documentos fiscais*/
  IF (UPPER(:PRAUDITORIADOCS) = 'TRUE') THEN
     EXECUTE PROCEDURE SP_AUDITORIA_DOCUMENTOS(:PRCODEMP, :PRREFINI, :PRREFFIM, :wCodUsu, :PRCODINCONFORMIDADE, :PRREGVALIDAR);

  -- Salva registros ignorados
  IF (UPPER(:PRAUDITORIADOCS) = 'TRUE') THEN
     BEGIN
       -- Recupera registros ignorados
       MERGE INTO VAUD_EMP_TINCONFORMIDADES INC
       USING TMP_VAUD_EMP_TINCONFORMIDADES TMP
       ON (INC.BDCODEMP = TMP.BDCODEMP) and
          (INC.BDCODINCONF = TMP.BDCODINCONF) and (INC.BDCODEVENTO = TMP.BDCODEVENTO) and
          (INC.BDCHAVECAD = TMP.BDCHAVECAD) and (INC.BDREFERENCIA = TMP.BDREFERENCIA) and
          (INC.BDPARAMETROSDESC = TMP.BDPARAMETROSDESC) and (INC.BDDESCINCONFESP = TMP.BDDESCINCONFESP)
       WHEN MATCHED THEN UPDATE SET BDIGNORAINC = TMP.BDIGNORAINC;

       EXECUTE STATEMENT 'DELETE FROM TMP_VAUD_EMP_TINCONFORMIDADES'||:wSQL;
     END
end^

CREATE OR ALTER procedure SP_AUDITORIA_DOCUMENTOS (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRCODUSU integer,
    PRCODINCONFORMIDADE integer,
    PRREGVALIDAR varchar(100) = '')
as
declare variable WDOCENT integer;
declare variable WDOCSAI integer;
begin
  if ((PRREGVALIDAR = '') or (POSITION('DOCENT', PRREGVALIDAR) > 0)) then wdocent = 1; else wdocent = 0;
  if ((PRREGVALIDAR = '') or (POSITION('DOCSAI', PRREGVALIDAR) > 0)) then wdocsai = 1; else wdocsai = 0;

  PRREGVALIDAR = REPLACE(REPLACE(PRREGVALIDAR,'DOCENT',''),'DOCSAI','');

  /* Geral */
  execute procedure SP_AUDITORIA_DOCS_GERAL(:PRCODEMP, :PRREFINI, :PRREFFIM, :PRCODUSU, :PRCODINCONFORMIDADE, wdocent, wdocsai, :PRREGVALIDAR);

  /* Entradas */
  if (wdocent = 1) then
     execute procedure SP_AUDITORIA_DOCS_MOVENT(:PRCODEMP, :PRREFINI, :PRREFFIM, :PRCODUSU, :PRCODINCONFORMIDADE, :PRREGVALIDAR);

  /* Saidas */
  if (wdocsai = 1) then
     execute procedure SP_AUDITORIA_DOCS_MOVSAI(:PRCODEMP, :PRREFINI, :PRREFFIM, :PRCODUSU, :PRCODINCONFORMIDADE, :PRREGVALIDAR);
end^

CREATE OR ALTER procedure SP_AUDITORIA_DOCS_GERAL (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRCODUSU integer,
    PRCODINCONFORMIDADE integer,
    PRDOCENT integer,
    PRDOCSAI integer,
    PRREGVALIDAR varchar(100) = '')
as
declare variable WDATAINI integer;
declare variable WDATAFIM integer;
begin
  wdataini = (prrefini * 100 + 1);
  wdatafim = (prreffim * 100 + 31);

  -- Inconformidade 137 - Chave não lançada (adcSemLanc)
  IF ((prcodinconformidade = 137) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D137', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT NFE.BDCODEMP, :PRCODUSU, CASE WHEN (NFE.BDINDMOV = 1) THEN 42 /* Saída */ ELSE 41 /* Entrada */ END AS BDCODEVENTO,
              137 AS BDCODINCONF, 21 AS BDCODTELASIS, 'edCHAVENFE' AS BDCAMPO,
              'BDCODEMP='||NFE.BDCODEMP||'.BDTABLE='||CASE WHEN (NFE.BDINDMOV = 1) THEN 'VEF_EMP_TMOVSAI' /* Saída */ ELSE 'VEF_EMP_TMOVENT' /* Entrada */ END,
              'Lançamentos/'||CASE WHEN (NFE.BDINDMOV = 1) THEN 'Saídas' /* Saída */ ELSE 'Entradas' /* Entrada */ END||'/Empresa '||NFE.BDCODEMP AS BDCAMINHO,
              NFE.BDCHAVENFE AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM VAUD_EMP_NFE NFE
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND ((:prdocsai = 1) OR (NFE.BDINDMOV <> 1)) -- Traz saida ou é entrada (filtro por saída)
         AND ((:prdocent = 1) OR (NFE.BDINDMOV = 1))  -- Traz entrada ou é saida (filtro por entrada)
         AND ((NFE.BDINDMOV = 1) OR (NFE.BDINDSIT <> 2)) -- É saída ou não está cancelada (ignora entrada cancelada)

         AND (NOT EXISTS(SELECT ENT.BDCODEMP FROM VEF_EMP_TMOVENT ENT WHERE (ENT.BDCODEMP = NFE.BDCODEMP) AND (ENT.BDCHAVENFE = NFE.BDCHAVENFE)))

         and (NOT EXISTS(SELECT SAI.BDCODEMP FROM VEF_EMP_TMOVSAI SAI WHERE (SAI.BDCODEMP = NFE.BDCODEMP) AND (SAI.BDCHAVENFE = NFE.BDCHAVENFE)));

     END
end^

create or alter procedure SP_AUDITORIA_DOCS_MOVENT (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRCODUSU integer,
    PRCODINCONFORMIDADE integer,
    PRREGVALIDAR varchar(100) = '')
as
declare variable WDATAINI integer;
declare variable WDATAFIM integer;
begin
  wdataini = (prrefini * 100 + 1);
  wdatafim = (prreffim * 100 + 31);

  -- Inconformidade 133 - Valor total diferente do portal (adcValorTotal)
  IF ((prcodinconformidade = 133) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D133', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT ENT.BDCODEMP, :PRCODUSU, 41 AS BDCODEVENTO, 133 AS BDCODINCONF, 21 AS BDCODTELASIS, 'edValorNota' AS BDCAMPO,
              'BDCODEMP='||ENT.BDCODEMP||'.BDCHAVE='||ENT.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVENT',
              'Lançamentos/Entradas/Empresa '||ENT.BDCODEMP|| '/Chave '||ENT.BDCHAVE||' Campo "Valor da nota"' AS BDCAMINHO,
              REPLACE(ENT.BDVALORNOTA,'.',',')||'#'||REPLACE(NFE.BDVALORTOTALNOTA,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM VAUD_EMP_NFE NFE
       LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = NFE.BDCODEMP) AND (ENT.BDCHAVENFE = NFE.BDCHAVENFE)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (ENT.BDCODEMP IS NOT NULL)
         AND (NFE.BDVALORTOTALNOTA <> ENT.BDVALORNOTA)
         AND (ENT.BDCODSITNF not in (2,3,4,5)); --Larissa - 05/11/2021 - Auditor DF-e nota emissão própria cancelada - Não verificar valores quando nota cancelada
     END

  -- Inconformidade 134 - Data de emissao diferente do portal (adcDataEmissao)
  IF ((prcodinconformidade = 134) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D134', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT ENT.BDCODEMP, :PRCODUSU, 41 AS BDCODEVENTO, 134 AS BDCODINCONF, 21 AS BDCODTELASIS, 'dtDataEmissao' AS BDCAMPO,
              'BDCODEMP='||ENT.BDCODEMP||'.BDCHAVE='||ENT.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVENT',
              'Lançamentos/Entradas/Empresa '||ENT.BDCODEMP|| '/Chave '||ENT.BDCHAVE||' Campo "Emissão"' AS BDCAMINHO,
              LPAD(EXTRACT(DAY FROM ENT.BDDATAEMISSAO),2,'0')||'/'||LPAD(EXTRACT(MONTH FROM ENT.BDDATAEMISSAO),2,'0' )||'/'||LPAD(EXTRACT(YEAR FROM ENT.BDDATAEMISSAO),4,'0')||'#'||
              LPAD(EXTRACT(DAY FROM NFE.BDDATAEMISSAO),2,'0')||'/'||LPAD(EXTRACT(MONTH FROM NFE.BDDATAEMISSAO),2,'0' )||'/'||LPAD(EXTRACT(YEAR FROM NFE.BDDATAEMISSAO),4,'0') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM VAUD_EMP_NFE NFE
       LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = NFE.BDCODEMP) AND (ENT.BDCHAVENFE = NFE.BDCHAVENFE)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (ENT.BDCODEMP IS NOT NULL)
         AND (NFE.BDDATAEMISSAO <> ENT.BDDATAEMISSAO);
     END

  -- Inconformidade 135 - ICMS diferente do portal (adcValorICMS)
  IF ((prcodinconformidade = 135) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D135', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT ENT.BDCODEMP, :PRCODUSU, 41 AS BDCODEVENTO, 135 AS BDCODINCONF, 21 AS BDCODTELASIS, 'edVLRICMS' AS BDCAMPO,
              'BDCODEMP='||ENT.BDCODEMP||'.BDCHAVE='||ENT.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVENT',
              'Lançamentos/Entradas/Empresa '||ENT.BDCODEMP|| '/Chave '||ENT.BDCHAVE||' Campo "ICMS - Valor"' AS BDCAMINHO,
              REPLACE((SELECT SUM(ITEM.BDVLRICMS)
                       FROM VEF_EMP_TMOVENTITENS ITEM
                       WHERE (ITEM.BDCODEMP = ENT.BDCODEMP)
                        AND (ITEM.BDCHAVE = ENT.BDCHAVE)),'.',',')||'#'||REPLACE(NFE.BDVALORTOTALICMS,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM VAUD_EMP_NFE NFE
       LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = NFE.BDCODEMP) AND (ENT.BDCHAVENFE = NFE.BDCHAVENFE)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (ENT.BDCODEMP IS NOT NULL)
         AND (NFE.BDVALORTOTALICMS <> (SELECT SUM(ITEM.BDVLRICMS)
                                       FROM VEF_EMP_TMOVENTITENS ITEM
                                       WHERE (ITEM.BDCODEMP = ENT.BDCODEMP)
                                         AND (ITEM.BDCHAVE = ENT.BDCHAVE)))
         AND (ENT.BDCODSITNF not in (2,3,4,5)); --Larissa - 05/11/2021 - Auditor DF-e nota emissão própria cancelada - Não verificar valores quando nota cancelada
     END

  -- Inconformidade 136 - IPI diferente do portal (adcValorIPI)
  IF ((prcodinconformidade = 136) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D136', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT ENT.BDCODEMP, :PRCODUSU, 41 AS BDCODEVENTO, 136 AS BDCODINCONF, 21 AS BDCODTELASIS, 'edVLRIPI' AS BDCAMPO,
              'BDCODEMP='||ENT.BDCODEMP||'.BDCHAVE='||ENT.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVENT',
              'Lançamentos/Entradas/Empresa '||ENT.BDCODEMP|| '/Chave '||ENT.BDCHAVE||' Campo "IPI - Valor"' AS BDCAMINHO,
              REPLACE((SELECT SUM(ITEM.BDVLRIPI)
                       FROM VEF_EMP_TMOVENTITENS ITEM
                       WHERE (ITEM.BDCODEMP = ENT.BDCODEMP)
                         AND (ITEM.BDCHAVE = ENT.BDCHAVE)),'.',',')||'#'||REPLACE(NFE.BDIPI,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM (select * from VAUD_EMP_NFE aud where aud.bdorigem <> 1) NFE
       LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = NFE.BDCODEMP) AND (ENT.BDCHAVENFE = NFE.BDCHAVENFE)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (ENT.BDCODEMP IS NOT NULL)
         AND (NFE.BDIPI <> (SELECT SUM(ITEM.BDVLRIPI)
                            FROM VEF_EMP_TMOVENTITENS ITEM
                            WHERE (ITEM.BDCODEMP = ENT.BDCODEMP)
                              AND (ITEM.BDCHAVE = ENT.BDCHAVE)))
        AND (ENT.BDCODSITNF not in (2,3,4,5)); --Larissa - 05/11/2021 - Auditor DF-e nota emissão própria cancelada - Não verificar valores quando nota cancelada
     END

  -- Inconformidade 138 - Situação divergente (adcSituacao)
  IF ((prcodinconformidade = 138) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D138', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT ENT.BDCODEMP, :PRCODUSU, 41 AS BDCODEVENTO, 138 AS BDCODINCONF, 21 AS BDCODTELASIS, 'edCODSITNF' AS BDCAMPO,
              'BDCODEMP='||ENT.BDCODEMP||'.BDCHAVE='||ENT.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVENT',
              'Lançamentos/Entradas/Empresa '||ENT.BDCODEMP|| '/Chave '||ENT.BDCHAVE||' Campo "Situação"' AS BDCAMINHO,
              ENT.BDCODSITNF||' - '||SITNF.BDDESCSITNF||'#'||CASE NFE.BDINDSIT
                                                               WHEN 1 THEN 'Autorizada'
                                                               WHEN 2 THEN 'Cancelada'
                                                               WHEN 3 THEN 'Denegada'
                                                               ELSE ''
                                                             END AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM VAUD_EMP_NFE NFE
       LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = NFE.BDCODEMP) AND (ENT.BDCHAVENFE = NFE.BDCHAVENFE)
       LEFT OUTER JOIN VEF_BASE_TTABSITNF SITNF ON (SITNF.BDCODSITNF = ENT.BDCODSITNF)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (ENT.BDCODEMP IS NOT NULL)
         AND (NFE.BDINDSIT <> CASE
                                WHEN (ENT.BDCODSITNF in (0,1,6,8)) THEN 1 -- adsAutorizada
                                WHEN (ENT.BDCODSITNF in (2,3)) THEN 2 -- adsCancelada
                                WHEN (ENT.BDCODSITNF = 4) THEN 3 -- adsDenegada
                                ELSE NFE.BDINDSIT -- Não gera inconsistência nos demais
                              END);
     END

     -- Inconformidade 145 - Frete diferente do portal (adcValorFrete)
  IF ((prcodinconformidade = 145) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D145', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
      SELECT ENTR.BDCODEMP, :PRCODUSU, 41 AS BDCODEVENTO, 145 AS BDCODINCONF, 21 AS BDCODTELASIS, 'edVLRFrete' AS BDCAMPO,
              'BDCODEMP='||ENTR.BDCODEMP||'.BDCHAVE='||ENTR.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVENT',
              'Lançamentos/Entradas/Empresa '||ENTR.BDCODEMP|| '/Chave '||ENTR.BDCHAVE||' Campo "Frete - Valor"' AS BDCAMINHO,
              REPLACE(iif(ENTR.bdvlrfrete > 0, ENTR.BDVLRFRETE, COALESCE(C100.bdvlrfrete,0)),'.',',')||'#'||REPLACE(ENTR.BDFRETE,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(ENTR.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              ENTR.BDCHAVENFE AS BDDESCINCONFESP
       FROM (
       SELECT ENT.BDCODEMP, ENT.bdchave, COALESCE(sum(ITEM.bdvlrfrete), 0) BDVLRFRETE, nfe.bdchavenfe, nfe.bddataemissaoint, nfe.bdfrete
       FROM (select * from VAUD_EMP_NFE aud where aud.bdorigem <> 1) NFE
       LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = NFE.BDCODEMP) AND (ENT.BDCHAVENFE = NFE.BDCHAVENFE)
       LEFT OUTER JOIN VEF_EMP_TMOVPROENT ITEM ON (ITEM.BDCODEMP = ENT.bdcodemp) AND (ITEM.bdchave = ENT.bdchave)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (ENT.BDCODEMP IS NOT NULL)
       GROUP by ENT.BDCODEMP, ENT.bdchave, nfe.bdchavenfe, nfe.bddataemissaoint, nfe.bdfrete
         ) ENTR
       LEFT OUTER JOIN vef_emp_tc100ent C100 ON (C100.BDCODEMP = ENTR.BDCODEMP) AND (C100.BDCHAVE = ENTR.BDCHAVE)
        WHERE (ENTR.BDFRETE <> IIF(ENTR.bdvlrfrete > 0, ENTR.BDVLRFRETE, COALESCE(C100.bdvlrfrete,0)));
     END

         -- Inconformidade 146 - Despesas diferente do portal (adcDespesas)
  IF ((prcodinconformidade = 146) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D146', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
      SELECT ENTR.BDCODEMP, :PRCODUSU, 41 AS BDCODEVENTO, 146 AS BDCODINCONF, 21 AS BDCODTELASIS, 'edVLRDESPACESSORIA' AS BDCAMPO,
              'BDCODEMP='||ENTR.BDCODEMP||'.BDCHAVE='||ENTR.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVENT',
              'Lançamentos/Entradas/Empresa '||ENTR.BDCODEMP|| '/Chave '||ENTR.BDCHAVE||' Campo "Despesas acessórias - Valor"' AS BDCAMINHO,
              REPLACE(iif(ENTR.BDVLRDESPACESSORIA > 0, ENTR.BDVLRDESPACESSORIA, COALESCE(C100.bdvlroutdesp,0)),'.',',')||'#'||REPLACE(ENTR.BDDESPESAS,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(ENTR.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              ENTR.BDCHAVENFE AS BDDESCINCONFESP
       FROM (
       SELECT ENT.BDCODEMP, ENT.bdchave, COALESCE(sum(ITEM.BDVLRDESPACESSORIA),0) BDVLRDESPACESSORIA, nfe.bdchavenfe, nfe.bddataemissaoint, nfe.bddespesas
       FROM (select * from VAUD_EMP_NFE aud where aud.bdorigem <> 1) NFE
       LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = NFE.BDCODEMP) AND (ENT.BDCHAVENFE = NFE.BDCHAVENFE)
       LEFT OUTER JOIN VEF_EMP_TMOVPROENT ITEM ON (ITEM.BDCODEMP = ENT.bdcodemp) AND (ITEM.bdchave = ENT.bdchave)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (ENT.BDCODEMP IS NOT NULL)
       GROUP by ENT.BDCODEMP, ENT.bdchave, nfe.bdchavenfe, nfe.bddataemissaoint, nfe.bddespesas
         ) ENTR
       LEFT OUTER JOIN vef_emp_tc100ent C100 ON (C100.BDCODEMP = ENTR.BDCODEMP) AND (C100.BDCHAVE = ENTR.BDCHAVE)
        WHERE (ENTR.BDDESPESAS <> IIF(ENTR.BDVLRDESPACESSORIA > 0, ENTR.BDVLRDESPACESSORIA, COALESCE(C100.bdvlroutdesp,0)));
     END
     
  -- Inconformidade 168 - Desconto
  IF ((prcodinconformidade = 168) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D168', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT ENT.BDCODEMP, :PRCODUSU, 41 AS BDCODEVENTO, 168 AS BDCODINCONF, 21 AS BDCODTELASIS, 'edDescontoNota' AS BDCAMPO,
              'BDCODEMP='||ENT.BDCODEMP||'.BDCHAVE='||ENT.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVENT',
              'Lançamentos/Entradas/Empresa '||ENT.BDCODEMP|| '/Chave '||ENT.BDCHAVE||' Campo "Desconto da nota"' AS BDCAMINHO,
              REPLACE(ENT.bddescontonota,'.',',')||'#'||REPLACE(NFE.bdvlrdesconto,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM VAUD_EMP_NFE NFE
       LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = NFE.BDCODEMP) AND (ENT.BDCHAVENFE = NFE.BDCHAVENFE)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (ENT.BDCODEMP IS NOT NULL)
         AND (NFE.bdvlrdesconto <> ENT.bddescontonota)
         AND (ENT.BDCODSITNF not in (2,3,4,5));
     END
  -- Inconformidade 169 - Seguro
  IF ((prcodinconformidade = 169) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D169', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
      SELECT ENTR.BDCODEMP, :PRCODUSU, 41 AS BDCODEVENTO, 169 AS BDCODINCONF, 21 AS BDCODTELASIS, 'edVLRSEGURO' AS BDCAMPO,
              'BDCODEMP='||ENTR.BDCODEMP||'.BDCHAVE='||ENTR.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVENT',
              'Lançamentos/Entradas/Empresa '||ENTR.BDCODEMP|| '/Chave '||ENTR.BDCHAVE||' Campo "Seguro - Valor"' AS BDCAMINHO,
              REPLACE(iif(ENTR.BDVLRSEGURO > 0, ENTR.BDVLRSEGURO, COALESCE(C100.bdvlrseguro,0)),'.',',')||'#'||REPLACE(ENTR.BDSEGURO,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(ENTR.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              ENTR.BDCHAVENFE AS BDDESCINCONFESP
       FROM (
       SELECT ENT.BDCODEMP, ENT.bdchave, sum(Coalesce(ITEM.bdvlrseguro,0)) BDVLRSEGURO, nfe.bdchavenfe, nfe.bddataemissaoint, nfe.BDVLRSEGURO BDSEGURO
       FROM (select * from VAUD_EMP_NFE aud where aud.bdorigem <> 1) NFE
       LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = NFE.BDCODEMP) AND (ENT.BDCHAVENFE = NFE.BDCHAVENFE)
       LEFT OUTER JOIN VEF_EMP_TMOVPROENT ITEM ON (ITEM.BDCODEMP = ENT.bdcodemp) AND (ITEM.bdchave = ENT.bdchave)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (ENT.BDCODEMP IS NOT NULL)
       GROUP by ENT.BDCODEMP, ENT.bdchave, nfe.bdchavenfe, nfe.bddataemissaoint, nfe.BDVLRSEGURO
         ) ENTR
       LEFT OUTER JOIN vef_emp_tc100ent C100 ON (C100.BDCODEMP = ENTR.BDCODEMP) AND (C100.BDCHAVE = ENTR.BDCHAVE)
        WHERE (ENTR.BDSEGURO <> IIF(ENTR.BDVLRSEGURO > 0, ENTR.BDVLRSEGURO, COALESCE(C100.bdvlrseguro,0)));
     END
  -- Inconformidade 170 - Valor do ICMS ST OK
  IF ((prcodinconformidade = 170) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D170', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT ENT.BDCODEMP, :PRCODUSU, 41 AS BDCODEVENTO, 170 AS BDCODINCONF, 21 AS BDCODTELASIS, 'edVLRST' AS BDCAMPO,
              'BDCODEMP='||ENT.BDCODEMP||'.BDCHAVE='||ENT.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVENT',
              'Lançamentos/Entradas/Empresa '||ENT.BDCODEMP|| '/Chave '||ENT.BDCHAVE||' Campo "Substituição tributária - ICMS - Valor' AS BDCAMINHO,
              REPLACE((SELECT SUM(Coalesce(ITEM.bdvlrst,0))
                       FROM VEF_EMP_TMOVENTITENS ITEM
                       WHERE (ITEM.BDCODEMP = ENT.BDCODEMP)
                         AND (ITEM.BDCHAVE = ENT.BDCHAVE)),'.',',')||'#'||REPLACE(NFE.bdvlricmsst,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM VAUD_EMP_NFE NFE
       LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = NFE.BDCODEMP) AND (ENT.BDCHAVENFE = NFE.BDCHAVENFE)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (ENT.BDCODEMP IS NOT NULL)
         AND (NFE.bdvlricmsst <> (SELECT SUM(Coalesce(ITEM.bdvlrst,0))
                       FROM VEF_EMP_TMOVENTITENS ITEM
                       WHERE (ITEM.BDCODEMP = ENT.BDCODEMP)
                         AND (ITEM.BDCHAVE = ENT.BDCHAVE)))
         AND (ENT.BDCODSITNF not in (2,3,4,5));
     END
  -- Inconformidade 171 - Base de ICMS ST OK
  IF ((prcodinconformidade = 171) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D171', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT ENT.BDCODEMP, :PRCODUSU, 41 AS BDCODEVENTO, 171 AS BDCODINCONF, 21 AS BDCODTELASIS, 'edBASEST' AS BDCAMPO,
              'BDCODEMP='||ENT.BDCODEMP||'.BDCHAVE='||ENT.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVENT',
              'Lançamentos/Entradas/Empresa '||ENT.BDCODEMP|| '/Chave '||ENT.BDCHAVE||' Campo "Substituição tributária - ICMS - Base"' AS BDCAMINHO,
              REPLACE((SELECT SUM(Coalesce(ITEM.bdbasest,0))
                       FROM VEF_EMP_TMOVENTITENS ITEM
                       WHERE (ITEM.BDCODEMP = ENT.BDCODEMP)
                         AND (ITEM.BDCHAVE = ENT.BDCHAVE)),'.',',')||'#'||REPLACE(NFE.bdbaseicmsst,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM VAUD_EMP_NFE NFE
       LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = NFE.BDCODEMP) AND (ENT.BDCHAVENFE = NFE.BDCHAVENFE)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (ENT.BDCODEMP IS NOT NULL)
         AND (NFE.bdbaseicmsst <> (SELECT SUM(Coalesce(ITEM.bdbasest,0))
                       FROM VEF_EMP_TMOVENTITENS ITEM
                       WHERE (ITEM.BDCODEMP = ENT.BDCODEMP)
                         AND (ITEM.BDCHAVE = ENT.BDCHAVE)))
         AND (ENT.BDCODSITNF not in (2,3,4,5));
     END
  -- Inconformidade 172 - Base de ICMS OK
  IF ((prcodinconformidade = 172) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D172', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT ENT.BDCODEMP, :PRCODUSU, 41 AS BDCODEVENTO, 172 AS BDCODINCONF, 21 AS BDCODTELASIS, 'edBASEICMS' AS BDCAMPO,
              'BDCODEMP='||ENT.BDCODEMP||'.BDCHAVE='||ENT.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVENT',
              'Lançamentos/Entradas/Empresa '||ENT.BDCODEMP|| '/Chave '||ENT.BDCHAVE||' Campo "ICMS - Base"' AS BDCAMINHO,
              REPLACE((SELECT SUM(Coalesce(ITEM.bdbaseicms,0))
                       FROM VEF_EMP_TMOVENTITENS ITEM
                       WHERE (ITEM.BDCODEMP = ENT.BDCODEMP)
                         AND (ITEM.BDCHAVE = ENT.BDCHAVE)),'.',',')||'#'||REPLACE(NFE.bdbaseicms,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM VAUD_EMP_NFE NFE
       LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = NFE.BDCODEMP) AND (ENT.BDCHAVENFE = NFE.BDCHAVENFE)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (ENT.BDCODEMP IS NOT NULL)
         AND (NFE.bdbaseicms <> (SELECT SUM(Coalesce(ITEM.bdbaseicms,0))
                       FROM VEF_EMP_TMOVENTITENS ITEM
                       WHERE (ITEM.BDCODEMP = ENT.BDCODEMP)
                         AND (ITEM.BDCHAVE = ENT.BDCHAVE)))
         AND (ENT.BDCODSITNF not in (2,3,4,5));
     END
end^

create or alter procedure SP_AUDITORIA_DOCS_MOVSAI (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRCODUSU integer,
    PRCODINCONFORMIDADE integer,
    PRREGVALIDAR varchar(100) = '')
as
declare variable WDATAINI integer;
declare variable WDATAFIM integer;
begin
  wdataini = (prrefini * 100 + 1);
  wdatafim = (prreffim * 100 + 31);

  -- Inconformidade 133 - Valor total diferente do portal (adcValorTotal)
  IF ((prcodinconformidade = 133) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D133', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT SAI.BDCODEMP, :PRCODUSU, 42 AS BDCODEVENTO, 133 AS BDCODINCONF, 63 AS BDCODTELASIS, 'edValorNota' AS BDCAMPO,
              'BDCODEMP='||SAI.BDCODEMP||'.BDCHAVE='||SAI.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSAI',
              'Lançamentos/Saídas/Empresa '||SAI.BDCODEMP|| '/Chave '||SAI.BDCHAVE||' Campo "Valor da nota"' AS BDCAMINHO,
              REPLACE(SAI.BDVALORNOTA,'.',',')||'#'||REPLACE(NFE.BDVALORTOTALNOTA,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM VAUD_EMP_NFE NFE
       LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = NFE.BDCODEMP) AND (SAI.BDCHAVENFE = NFE.BDCHAVENFE)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (SAI.BDCODEMP IS NOT NULL)
         AND (NFE.BDVALORTOTALNOTA <> SAI.BDVALORNOTA)
         AND (SAI.BDCODSITNF not in (2,3,4,5)); --Larissa - 05/11/2021 - Auditor DF-e nota emissão própria cancelada - Não verificar valores quando nota cancelada
     END

  -- Inconformidade 134 - Data de emissao diferente do portal (adcDataEmissao)
  IF ((prcodinconformidade = 134) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D134', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT SAI.BDCODEMP, :PRCODUSU, 42 AS BDCODEVENTO, 134 AS BDCODINCONF, 63 AS BDCODTELASIS, 'dtDataEmissao' AS BDCAMPO,
              'BDCODEMP='||SAI.BDCODEMP||'.BDCHAVE='||SAI.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSAI',
              'Lançamentos/Saídas/Empresa '||SAI.BDCODEMP|| '/Chave '||SAI.BDCHAVE||' Campo "Emissão"' AS BDCAMINHO,
              LPAD(EXTRACT(DAY FROM SAI.BDDATAEMISSAO),2,'0')||'/'||LPAD(EXTRACT(MONTH FROM SAI.BDDATAEMISSAO),2,'0' )||'/'||LPAD(EXTRACT(YEAR FROM SAI.BDDATAEMISSAO),4,'0')||'#'||
              LPAD(EXTRACT(DAY FROM NFE.BDDATAEMISSAO),2,'0')||'/'||LPAD(EXTRACT(MONTH FROM NFE.BDDATAEMISSAO),2,'0' )||'/'||LPAD(EXTRACT(YEAR FROM NFE.BDDATAEMISSAO),4,'0') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM VAUD_EMP_NFE NFE
       LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = NFE.BDCODEMP) AND (SAI.BDCHAVENFE = NFE.BDCHAVENFE)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (SAI.BDCODEMP IS NOT NULL)
         AND (NFE.BDDATAEMISSAO <> SAI.BDDATAEMISSAO);
     END

  -- Inconformidade 135 - ICMS diferente do portal (adcValorICMS)
  IF ((prcodinconformidade = 135) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D135', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT SAI.BDCODEMP, :PRCODUSU, 42 AS BDCODEVENTO, 135 AS BDCODINCONF, 63 AS BDCODTELASIS, 'edVLRICMS' AS BDCAMPO,
              'BDCODEMP='||SAI.BDCODEMP||'.BDCHAVE='||SAI.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSAI',
              'Lançamentos/Saídas/Empresa '||SAI.BDCODEMP|| '/Chave '||SAI.BDCHAVE||' Campo "ICMS - Valor"' AS BDCAMINHO,
              REPLACE((SELECT SUM(ITEM.BDVLRICMS)
                       FROM VEF_EMP_TMOVSAIITENS ITEM
                       WHERE (ITEM.BDCODEMP = SAI.BDCODEMP)
                         AND (ITEM.BDCHAVE = SAI.BDCHAVE)),'.',',')||'#'||REPLACE(NFE.BDVALORTOTALICMS,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM VAUD_EMP_NFE NFE
       LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = NFE.BDCODEMP) AND (SAI.BDCHAVENFE = NFE.BDCHAVENFE)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (SAI.BDCODEMP IS NOT NULL)
         AND (SAI.BDCODSITNF not in (2,3,4,5)) --Larissa - 05/11/2021 - Auditor DF-e nota emissão própria cancelada - Não verificar valores quando nota cancelada
         AND (NFE.BDVALORTOTALICMS <> (SELECT SUM(ITEM.BDVLRICMS)
                                       FROM VEF_EMP_TMOVSAIITENS ITEM
                                       WHERE (ITEM.BDCODEMP = SAI.BDCODEMP)
                                         AND (ITEM.BDCHAVE = SAI.BDCHAVE)));
     END

  -- Inconformidade 136 - IPI diferente do portal (adcValorIPI)
  IF ((prcodinconformidade = 136) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D136', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT SAI.BDCODEMP, :PRCODUSU, 42 AS BDCODEVENTO, 136 AS BDCODINCONF, 63 AS BDCODTELASIS, 'edVLRIPI' AS BDCAMPO,
              'BDCODEMP='||SAI.BDCODEMP||'.BDCHAVE='||SAI.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSAI',
              'Lançamentos/Saídas/Empresa '||SAI.BDCODEMP|| '/Chave '||SAI.BDCHAVE||' Campo "IPI - Valor"' AS BDCAMINHO,
              REPLACE((SELECT SUM(ITEM.BDVLRIPI)
                       FROM VEF_EMP_TMOVSAIITENS ITEM
                       WHERE (ITEM.BDCODEMP = SAI.BDCODEMP)
                         AND (ITEM.BDCHAVE = SAI.BDCHAVE)),'.',',')||'#'||REPLACE(NFE.BDIPI,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM (select * from VAUD_EMP_NFE aud where aud.bdorigem <> 1) NFE
       LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = NFE.BDCODEMP) AND (SAI.BDCHAVENFE = NFE.BDCHAVENFE)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (SAI.BDCODEMP IS NOT NULL)
         AND (SAI.BDCODSITNF not in (2,3,4,5)) --Larissa - 05/11/2021 - Auditor DF-e nota emissão própria cancelada - Não verificar valores quando nota cancelada
         AND (NFE.BDIPI <> (SELECT SUM(ITEM.BDVLRIPI)
                            FROM VEF_EMP_TMOVSAIITENS ITEM
                            WHERE (ITEM.BDCODEMP = SAI.BDCODEMP)
                              AND (ITEM.BDCHAVE = SAI.BDCHAVE)));
     END

  -- Inconformidade 138 - Situação divergente (adcSituacao)
  IF ((prcodinconformidade = 138) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D138', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT SAI.BDCODEMP, :PRCODUSU, 42 AS BDCODEVENTO, 138 AS BDCODINCONF, 63 AS BDCODTELASIS, 'edCODSITNF' AS BDCAMPO,
              'BDCODEMP='||SAI.BDCODEMP||'.BDCHAVE='||SAI.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSAI',
              'Lançamentos/Saídas/Empresa '||SAI.BDCODEMP|| '/Chave '||SAI.BDCHAVE||' Campo "Situação"' AS BDCAMINHO,
              SAI.BDCODSITNF||' - '||SITNF.BDDESCSITNF||'#'||CASE NFE.BDINDSIT
                                                               WHEN 1 THEN 'Autorizada'
                                                               WHEN 2 THEN 'Cancelada'
                                                               WHEN 3 THEN 'Denegada'
                                                               ELSE ''
                                                             END AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM VAUD_EMP_NFE NFE
       LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = NFE.BDCODEMP) AND (SAI.BDCHAVENFE = NFE.BDCHAVENFE)
       LEFT OUTER JOIN VEF_BASE_TTABSITNF SITNF ON (SITNF.BDCODSITNF = SAI.BDCODSITNF)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (SAI.BDCODEMP IS NOT NULL)
         AND (NFE.BDINDSIT <> CASE
                                WHEN (SAI.BDCODSITNF in (0,1,6,8)) THEN 1 -- adsAutorizada
                                WHEN (SAI.BDCODSITNF in (2,3)) THEN 2 -- adsCancelada
                                WHEN (SAI.BDCODSITNF = 4) THEN 3 -- adsDenegada
                                ELSE NFE.BDINDSIT -- Não gera inconsistência nos demais
                              END);
     END

  -- Inconformidade 145 - Frete diferente do portal (adcValorFrete)
  IF ((prcodinconformidade = 145) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D145', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
      SELECT SAIR.BDCODEMP, :PRCODUSU, 41 AS BDCODEVENTO, 145 AS BDCODINCONF, 63 AS BDCODTELASIS, 'edVLRFrete' AS BDCAMPO,
              'BDCODEMP='||SAIR.BDCODEMP||'.BDCHAVE='||SAIR.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSAI',
              'Lançamentos/Saídas/Empresa '||SAIR.BDCODEMP|| '/Chave '||SAIR.BDCHAVE||' Campo "Frete - Valor"' AS BDCAMINHO,
              REPLACE(iif(SAIR.bdvlrfrete > 0, SAIR.BDVLRFRETE, COALESCE(C100.bdvlrfrete,0)),'.',',')||'#'||REPLACE(SAIR.BDFRETE,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(SAIR.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              SAIR.BDCHAVENFE AS BDDESCINCONFESP
       FROM (
       SELECT SAI.BDCODEMP, SAI.bdchave, COALESCE(sum(ITEM.bdvlrfrete), 0) BDVLRFRETE, nfe.bdchavenfe, nfe.bddataemissaoint, nfe.bdfrete
       FROM (select * from VAUD_EMP_NFE aud where aud.bdorigem <> 1) NFE
       LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = NFE.BDCODEMP) AND (SAI.BDCHAVENFE = NFE.BDCHAVENFE)
       LEFT OUTER JOIN VEF_EMP_TMOVPROSAI ITEM ON (ITEM.BDCODEMP = SAI.bdcodemp) AND (ITEM.bdchave = SAI.bdchave)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (SAI.BDCODEMP IS NOT NULL)
       GROUP by SAI.BDCODEMP, SAI.bdchave, nfe.bdchavenfe, nfe.bddataemissaoint, nfe.bdfrete
         ) SAIR
       LEFT OUTER JOIN vef_emp_tc100SAI C100 ON (C100.BDCODEMP = SAIR.BDCODEMP) AND (C100.BDCHAVE = SAIR.BDCHAVE)
        WHERE (SAIR.BDFRETE <> IIF(SAIR.bdvlrfrete > 0, SAIR.BDVLRFRETE, COALESCE(C100.bdvlrfrete,0)));
     END

         -- Inconformidade 146 - Despesas diferente do portal (adcDespesas)
  IF ((prcodinconformidade = 146) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D146', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
      SELECT SAIR.BDCODEMP, :PRCODUSU, 41 AS BDCODEVENTO, 146 AS BDCODINCONF, 63 AS BDCODTELASIS, 'edVLRDESPACESSORIA' AS BDCAMPO,
              'BDCODEMP='||SAIR.BDCODEMP||'.BDCHAVE='||SAIR.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSAI',
              'Lançamentos/Saídas/Empresa '||SAIR.BDCODEMP|| '/Chave '||SAIR.BDCHAVE||' Campo "Despesas acessórias - Valor"' AS BDCAMINHO,
              REPLACE(iif(SAIR.BDVLRDESPACESSORIA > 0, SAIR.BDVLRDESPACESSORIA, COALESCE(C100.bdvlroutdesp,0)),'.',',')||'#'||REPLACE(SAIR.BDDESPESAS,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(SAIR.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              SAIR.BDCHAVENFE AS BDDESCINCONFESP
       FROM (
       SELECT SAI.BDCODEMP, SAI.bdchave, COALESCE(sum(ITEM.BDVLRDESPACESSORIA),0) BDVLRDESPACESSORIA, nfe.bdchavenfe, nfe.bddataemissaoint, nfe.bddespesas
       FROM (select * from VAUD_EMP_NFE aud where aud.bdorigem <> 1) NFE
       LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = NFE.BDCODEMP) AND (SAI.BDCHAVENFE = NFE.BDCHAVENFE)
       LEFT OUTER JOIN VEF_EMP_TMOVPROSAI ITEM ON (ITEM.BDCODEMP = SAI.bdcodemp) AND (ITEM.bdchave = SAI.bdchave)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (SAI.BDCODEMP IS NOT NULL)
       GROUP by SAI.BDCODEMP, SAI.bdchave, nfe.bdchavenfe, nfe.bddataemissaoint, nfe.bddespesas
         ) SAIR
       LEFT OUTER JOIN vef_emp_tc100SAI C100 ON (C100.BDCODEMP = SAIR.BDCODEMP) AND (C100.BDCHAVE = SAIR.BDCHAVE)
        WHERE (SAIR.BDDESPESAS <> IIF(SAIR.BDVLRDESPACESSORIA > 0, SAIR.BDVLRDESPACESSORIA, COALESCE(C100.bdvlroutdesp,0)));
     END 
  -- Inconformidade 168 - Desconto
  IF ((prcodinconformidade = 168) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D168', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT SAI.BDCODEMP, :PRCODUSU, 42 AS BDCODEVENTO, 168 AS BDCODINCONF, 63 AS BDCODTELASIS, 'edDescontoNota' AS BDCAMPO,
              'BDCODEMP='||SAI.BDCODEMP||'.BDCHAVE='||SAI.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSAI',
              'Lançamentos/Saídas/Empresa '||SAI.BDCODEMP|| '/Chave '||SAI.BDCHAVE||' Campo "Desconto"' AS BDCAMINHO,
              REPLACE(SAI.bddescontonota,'.',',')||'#'||REPLACE(NFE.bdvlrdesconto,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM VAUD_EMP_NFE NFE
       LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = NFE.BDCODEMP) AND (SAI.BDCHAVENFE = NFE.BDCHAVENFE)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (SAI.BDCODEMP IS NOT NULL)
         AND (NFE.bdvlrdesconto <> SAI.bddescontonota)
         AND (SAI.BDCODSITNF not in (2,3,4,5));
     END
  -- Inconformidade 169 - Seguro
  IF ((prcodinconformidade = 169) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D169', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
      SELECT SAIR.BDCODEMP, :PRCODUSU, 41 AS BDCODEVENTO, 169 AS BDCODINCONF, 63 AS BDCODTELASIS, 'edVLRSEGURO' AS BDCAMPO,
              'BDCODEMP='||SAIR.BDCODEMP||'.BDCHAVE='||SAIR.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSAI',
              'Lançamentos/Saídas/Empresa '||SAIR.BDCODEMP|| '/Chave '||SAIR.BDCHAVE||' Campo "Seguro - Valor"' AS BDCAMINHO,
              REPLACE(iif(SAIR.BDVLRSEGURO > 0, SAIR.BDVLRSEGURO, COALESCE(C100.bdvlrseguro,0)),'.',',')||'#'||REPLACE(SAIR.BDSEGURO,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(SAIR.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              SAIR.BDCHAVENFE AS BDDESCINCONFESP
       FROM (
       SELECT SAI.BDCODEMP, SAI.bdchave, sum(Coalesce(ITEM.BDVLRSEGURO,0)) BDVLRSEGURO, nfe.bdchavenfe, nfe.bddataemissaoint, nfe.BDVLRSEGURO BDSEGURO
       FROM (select * from VAUD_EMP_NFE aud where aud.bdorigem <> 1) NFE
       LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = NFE.BDCODEMP) AND (SAI.BDCHAVENFE = NFE.BDCHAVENFE)
       LEFT OUTER JOIN VEF_EMP_TMOVPROSAI ITEM ON (ITEM.BDCODEMP = SAI.bdcodemp) AND (ITEM.bdchave = SAI.bdchave)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (SAI.BDCODEMP IS NOT NULL)
       GROUP by SAI.BDCODEMP, SAI.bdchave, nfe.bdchavenfe, nfe.bddataemissaoint, nfe.BDVLRSEGURO
         ) SAIR
       LEFT OUTER JOIN vef_emp_tc100SAI C100 ON (C100.BDCODEMP = SAIR.BDCODEMP) AND (C100.BDCHAVE = SAIR.BDCHAVE)
        WHERE (SAIR.BDSEGURO <> IIF(SAIR.BDVLRSEGURO > 0, SAIR.BDVLRSEGURO, COALESCE(C100.BDVLRSEGURO,0)));
     END
  -- Inconformidade 170 - Valor de ICMS ST
  IF ((prcodinconformidade = 170) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D170', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT SAI.BDCODEMP, :PRCODUSU, 42 AS BDCODEVENTO, 170 AS BDCODINCONF, 63 AS BDCODTELASIS, 'edVLRST' AS BDCAMPO,
              'BDCODEMP='||SAI.BDCODEMP||'.BDCHAVE='||SAI.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSAI',
              'Lançamentos/Saídas/Empresa '||SAI.BDCODEMP|| '/Chave '||SAI.BDCHAVE||' Campo "Substituição tributária - ICMS - Valor"' AS BDCAMINHO,
              REPLACE((SELECT SUM(Coalesce(ITEM.bdvlrst,0))
                       FROM VEF_EMP_TMOVSAIITENS ITEM
                       WHERE (ITEM.BDCODEMP = SAI.BDCODEMP)
                         AND (ITEM.BDCHAVE = SAI.BDCHAVE)),'.',',')||'#'||REPLACE(NFE.bdvlricmsst,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM VAUD_EMP_NFE NFE
       LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = NFE.BDCODEMP) AND (SAI.BDCHAVENFE = NFE.BDCHAVENFE)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (SAI.BDCODEMP IS NOT NULL)
         AND (NFE.bdvlricmsst <> (SELECT SUM(Coalesce(ITEM.bdvlrst,0))
                       FROM VEF_EMP_TMOVSAIITENS ITEM
                       WHERE (ITEM.BDCODEMP = SAI.BDCODEMP)
                         AND (ITEM.BDCHAVE = SAI.BDCHAVE)))
         AND (SAI.BDCODSITNF not in (2,3,4,5));
     END
  -- Inconformidade 171 - Base de ICMS ST
  IF ((prcodinconformidade = 171) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D171', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT SAI.BDCODEMP, :PRCODUSU, 42 AS BDCODEVENTO, 171 AS BDCODINCONF, 63 AS BDCODTELASIS, 'edBASEST' AS BDCAMPO,
              'BDCODEMP='||SAI.BDCODEMP||'.BDCHAVE='||SAI.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSAI',
              'Lançamentos/Saídas/Empresa '||SAI.BDCODEMP|| '/Chave '||SAI.BDCHAVE||' Campo "Substituição tributária - ICMS - Base"' AS BDCAMINHO,
              REPLACE((SELECT SUM(Coalesce(ITEM.bdbasest,0))
                       FROM VEF_EMP_TMOVSAIITENS ITEM
                       WHERE (ITEM.BDCODEMP = SAI.BDCODEMP)
                         AND (ITEM.BDCHAVE = SAI.BDCHAVE)),'.',',')||'#'||REPLACE(NFE.bdbaseicmsst,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM VAUD_EMP_NFE NFE
       LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = NFE.BDCODEMP) AND (SAI.BDCHAVENFE = NFE.BDCHAVENFE)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (SAI.BDCODEMP IS NOT NULL)
         AND (NFE.bdbaseicmsst <> (SELECT SUM(Coalesce(ITEM.bdbasest,0))
                       FROM VEF_EMP_TMOVSAIITENS ITEM
                       WHERE (ITEM.BDCODEMP = SAI.BDCODEMP)
                         AND (ITEM.BDCHAVE = SAI.BDCHAVE)))
         AND (SAI.BDCODSITNF not in (2,3,4,5));
     END
  -- Inconformidade 172 - Base de ICMS
  IF ((prcodinconformidade = 172) or
      ((prcodinconformidade = 0) and ((prregvalidar = '') or (POSITION('D172', :prregvalidar) > 0) or (POSITION('D999', :prregvalidar) > 0)))) THEN
     BEGIN
       INSERT INTO VAUD_EMP_TINCONFORMIDADES(BDCODEMP, BDCODUSU, BDCODEVENTO, BDCODINCONF, BDCODTELASIS, BDCAMPO,
                                             BDCHAVECAD, BDCAMINHO, BDPARAMETROSDESC, BDIGNORAINC, BDREFERENCIA, BDCHAVEPROCESSO, BDDESCINCONFESP)
       SELECT SAI.BDCODEMP, :PRCODUSU, 42 AS BDCODEVENTO, 172 AS BDCODINCONF, 63 AS BDCODTELASIS, 'edBASEICMS' AS BDCAMPO,
              'BDCODEMP='||SAI.BDCODEMP||'.BDCHAVE='||SAI.BDCHAVE||'.BDTABLE=VEF_EMP_TMOVSAI',
              'Lançamentos/Saídas/Empresa '||SAI.BDCODEMP|| '/Chave '||SAI.BDCHAVE||' Campo "ICMS - Base"' AS BDCAMINHO,
              REPLACE((SELECT SUM(Coalesce(ITEM.bdbaseicms,0))
                       FROM VEF_EMP_TMOVSAIITENS ITEM
                       WHERE (ITEM.BDCODEMP = SAI.BDCODEMP)
                         AND (ITEM.BDCHAVE = SAI.BDCHAVE)),'.',',')||'#'||REPLACE(NFE.bdbaseicms,'.',',') AS BDPARAMETROSDESC,
              'FALSE' AS BDIGNORAINC, TRUNC(NFE.BDDATAEMISSAOINT/100) AS BDREFERENCIA, NULL AS BDCHAVEPROCESSO,
              NFE.BDCHAVENFE AS BDDESCINCONFESP
       FROM VAUD_EMP_NFE NFE
       LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = NFE.BDCODEMP) AND (SAI.BDCHAVENFE = NFE.BDCHAVENFE)
       WHERE (NFE.BDCODEMP = :prcodemp)
         AND (NFE.BDDATAEMISSAOINT BETWEEN :wdataini AND :wdatafim)
         AND (SAI.BDCODEMP IS NOT NULL)
         AND (NFE.bdbaseicms <> (SELECT SUM(Coalesce(ITEM.bdbaseicms,0))
                       FROM VEF_EMP_TMOVSAIITENS ITEM
                       WHERE (ITEM.BDCODEMP = SAI.BDCODEMP)
                         AND (ITEM.BDCHAVE = SAI.BDCHAVE)))
         AND (SAI.BDCODSITNF not in (2,3,4,5));
     END
end^

create or alter procedure SP_VRH_FAIXAS_PLANO_SAUDE (
    PRCODEMP varchar(25000),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDORDEM integer,
    BDIDADE integer,
    BDVALOR numeric(18,6))
as
declare variable WSQL varchar(28000);
declare variable WREFFAIXA integer;
begin
  wsql = 'select BDCODEMP, BDCODPLACONVSAU '||
         'from VW_VRHF_BASE_TEMPVINC '||
         'where BDCODPLACONVSAU is not null ';

  if (coalesce(prcodemp, '') <> '') then
     wsql = wsql||' and '||prcodemp;

  for execute statement wsql into :BDCODEMP, :BDCODPLACONVSAU do
    begin
      for select BDCODOPERADORA, BDCODCONVENIO, max(BDREF)
          from VRH_BASE_FAIXAS_CONVENIOS
          where BDCODPLACONVSAU = :BDCODPLACONVSAU and BDREF <= :prref
          group by BDCODOPERADORA,BDCODCONVENIO
      into :BDCODOPERADORA, :BDCODCONVENIO, :wreffaixa do
        begin
          for select BDORDEM, BDIDADE, BDVALOR
              from VRH_BASE_FAIXAS_CONVENIOS
              where BDCODPLACONVSAU = :BDCODPLACONVSAU and BDCODOPERADORA = :BDCODOPERADORA and BDCODCONVENIO = :BDCODCONVENIO and BDREF = :wreffaixa
          into :BDORDEM, :BDIDADE, :BDVALOR do
            suspend;
        end
    end
end^

CREATE OR ALTER procedure SP_VRH_BASE_TTERC_REF (
    PRBDCODTER integer,
    PRBDREFTERC integer)
as
declare variable VBDREFTERC integer;
begin
  for select TR.BDREFEMP
      from TTERCEIRO_REF TR
      where TR.BDCODTER = :PRBDCODTER and
            TR.BDREFEMP <> :PRBDREFTERC
      into :VBDREFTERC
  do
  begin
    insert into VRH_BASE_TTERC_REF (BDCODTER, BDREFTERC, BDNRODEPIRTER, BDESTCIVTER, BDGRAUINSTTER)
    select BDCODTER, :VBDREFTERC, BDNRODEPIRTER, BDESTCIVTER, BDGRAUINSTTER
    from VRH_BASE_TTERC_REF TR1
    where not exists(select *
                     from VRH_BASE_TTERC_REF TR2
                     where TR2.BDCODTER = TR1.BDCODTER and
                           TR2.BDREFTERC = :VBDREFTERC) and
          TR1.BDCODTER = :PRBDCODTER and
          TR1.BDREFTERC = (select max(TR2.BDREFTERC)
                           from VRH_BASE_TTERC_REF TR2
                           where TR2.BDCODTER = TR1.BDCODTER and
                                 TR2.BDREFTERC <= :VBDREFTERC);

    insert into VRHF_BASE_TTERC_FGTSGPS (BDCODTER, BDREFTERC, BDCATEGORIATER, BDOCORRENCIATER, BDPERCRATTER,
                                         BDPERTRANSPINSSTER, BDPERTRANSPIRTER, BDCATEGORIAESOCIAL, BDVINCEMPTER,
                                         BDCODMULTVINC)
    select BDCODTER, :VBDREFTERC, BDCATEGORIATER, BDOCORRENCIATER, BDPERCRATTER, BDPERTRANSPINSSTER, BDPERTRANSPIRTER,
           BDCATEGORIAESOCIAL, BDVINCEMPTER, BDCODMULTVINC
    from VRHF_BASE_TTERC_FGTSGPS TR1
    where not exists(select *
                     from VRHF_BASE_TTERC_FGTSGPS TR2
                     where TR2.BDCODTER = TR1.BDCODTER and
                           TR2.BDREFTERC = :VBDREFTERC) and
          TR1.BDCODTER = :PRBDCODTER and
          TR1.BDREFTERC = (select max(TR2.BDREFTERC)
                           from VRHF_BASE_TTERC_FGTSGPS TR2
                           where TR2.BDCODTER = TR1.BDCODTER and
                                 TR2.BDREFTERC <= :VBDREFTERC);

    insert into VRHF_BASE_TTERC_BANCO (BDCODTER, BDREFTERC, BDCODBAN, BDCODAG, BDCTADEPTER, BDDIGCTADEPTER,
                                       BDTIPOCTATER, BDMODOPAGTOTER, BDCARTAOSALTER)
    select BDCODTER, :VBDREFTERC, BDCODBAN, BDCODAG, BDCTADEPTER, BDDIGCTADEPTER, BDTIPOCTATER, BDMODOPAGTOTER,
           BDCARTAOSALTER
    from VRHF_BASE_TTERC_BANCO TR1
    where not exists(select *
                     from VRHF_BASE_TTERC_BANCO TR2
                     where TR2.BDCODTER = TR1.BDCODTER and
                           TR2.BDREFTERC = :VBDREFTERC) and
          TR1.BDCODTER = :PRBDCODTER and
          TR1.BDREFTERC = (select max(TR2.BDREFTERC)
                           from VRHF_BASE_TTERC_BANCO TR2
                           where TR2.BDCODTER = TR1.BDCODTER and
                                 TR2.BDREFTERC <= :VBDREFTERC);

    insert into VRH_BASE_TTERC_VINC (BDCODTER, BDREFTERC, BDCODCLA, BDCODCBO, BDCODCBOTSIN, BDCODSINTRAB,
                                     BDACORDOINSSTERC, BDPERCIRTERC, BDPIRTERC)
    select BDCODTER, :VBDREFTERC, BDCODCLA, BDCODCBO, BDCODCBOTSIN, BDCODSINTRAB, BDACORDOINSSTERC, BDPERCIRTERC,
           BDPIRTERC
    from VRH_BASE_TTERC_VINC TR1
    where not exists(select *
                     from VRH_BASE_TTERC_VINC TR2
                     where TR2.BDCODTER = TR1.BDCODTER and
                           TR2.BDREFTERC = :VBDREFTERC) and
          TR1.BDCODTER = :PRBDCODTER and
          TR1.BDREFTERC = (select max(TR2.BDREFTERC)
                           from VRH_BASE_TTERC_VINC TR2
                           where TR2.BDCODTER = TR1.BDCODTER and
                                 TR2.BDREFTERC <= :VBDREFTERC);

    insert into VRH_BASE_TTERC_DOCREF (BDCODTER, BDREFTERC, BDRGTER, BDORGEMIRGTER, BDDATAEMIRGTER, BDCODUFRG, BDPISTER,
                                       BDNROCONSPROTER, BDSIGLACONSPROTER, BDCODCCMPROTER, BDCNHTER, BDCATCNHTER,
                                       BDORGAOCNH, BDCODUFCNH, BDDATAEMICNH, BDVENCCNHTER, BDCTPSTER, BDSERIECTPSTER,
                                       BDDSERIECTPSTER, BDDATAEMICTPSTER, BDCODUFCTPS, BDNUMRICCOL, BDDATAEMIRICCOL,
                                       BDORGAORICCOL, BDCODCIDRIC, BDNUMOCCOL, BDORGAOOCCOL, BDDATAEMIOCCOL,
                                       BDDATAVALOCCOL, BDDATAEMIRNECOL, BDORGAORNECOL, BDNUMRNECOL)
    select BDCODTER, :VBDREFTERC, BDRGTER, BDORGEMIRGTER, BDDATAEMIRGTER, BDCODUFRG, BDPISTER, BDNROCONSPROTER,
           BDSIGLACONSPROTER, BDCODCCMPROTER, BDCNHTER, BDCATCNHTER, BDORGAOCNH, BDCODUFCNH, BDDATAEMICNH, BDVENCCNHTER,
           BDCTPSTER, BDSERIECTPSTER, BDDSERIECTPSTER, BDDATAEMICTPSTER, BDCODUFCTPS, BDNUMRICCOL, BDDATAEMIRICCOL,
           BDORGAORICCOL, BDCODCIDRIC, BDNUMOCCOL, BDORGAOOCCOL, BDDATAEMIOCCOL, BDDATAVALOCCOL, BDDATAEMIRNECOL,
           BDORGAORNECOL, BDNUMRNECOL
    from VRH_BASE_TTERC_DOCREF TR1
    where not exists(select *
                     from VRH_BASE_TTERC_DOCREF TR2
                     where TR2.BDCODTER = TR1.BDCODTER and
                           TR2.BDREFTERC = :VBDREFTERC) and
          TR1.BDCODTER = :PRBDCODTER and
          TR1.BDREFTERC = (select max(TR2.BDREFTERC)
                           from VRH_BASE_TTERC_DOCREF TR2
                           where TR2.BDCODTER = TR1.BDCODTER and
                                 TR2.BDREFTERC <= :VBDREFTERC);

    insert into VRH_BASE_TTERC_FISREF (BDCODTER, BDREFTERC, BDSEXOTER, BDRACACORTER, BDDEFFISICOTER, BDOBSDEFFISICOTER,
                                       BDDEFFISTER, BDDEFVISTER, BDDEFAUDTER, BDDEFMENTER, BDDEFINTTER, BDDEFREABTER,
                                       BDCOTADEFTER)
    select BDCODTER, :VBDREFTERC, BDSEXOTER, BDRACACORTER, BDDEFFISICOTER, BDOBSDEFFISICOTER, BDDEFFISTER, BDDEFVISTER,
           BDDEFAUDTER, BDDEFMENTER, BDDEFINTTER, BDDEFREABTER, BDCOTADEFTER
    from VRH_BASE_TTERC_FISREF TR1
    where not exists(select *
                     from VRH_BASE_TTERC_FISREF TR2
                     where TR2.BDCODTER = TR1.BDCODTER and
                           TR2.BDREFTERC = :VBDREFTERC) and
          TR1.BDCODTER = :PRBDCODTER and
          TR1.BDREFTERC = (select max(TR2.BDREFTERC)
                           from VRH_BASE_TTERC_FISREF TR2
                           where TR2.BDCODTER = TR1.BDCODTER and
                                 TR2.BDREFTERC <= :VBDREFTERC);

  end

  for select TR.BDREFEMP
      from TTERCEIRO_REF TR
      where TR.BDCODTER = :PRBDCODTER and
            TR.BDREFEMP <> :PRBDREFTERC
      into :VBDREFTERC
  do
  begin
    insert into VRH_BASE_TTERC_REF (BDCODTER, BDREFTERC, BDNRODEPIRTER, BDESTCIVTER, BDGRAUINSTTER)
    select BDCODTER, :VBDREFTERC, BDNRODEPIRTER, BDESTCIVTER, BDGRAUINSTTER
    from VRH_BASE_TTERC_REF TR1
    where not exists(select *
                     from VRH_BASE_TTERC_REF TR2
                     where TR2.BDCODTER = TR1.BDCODTER and
                           TR2.BDREFTERC = :VBDREFTERC) and
          TR1.BDCODTER = :PRBDCODTER and
          TR1.BDREFTERC = (select min(TR2.BDREFTERC)
                           from VRH_BASE_TTERC_REF TR2
                           where TR2.BDCODTER = TR1.BDCODTER and
                                 TR2.BDREFTERC >= :VBDREFTERC);

    insert into VRHF_BASE_TTERC_FGTSGPS (BDCODTER, BDREFTERC, BDCATEGORIATER, BDOCORRENCIATER, BDPERCRATTER,
                                         BDPERTRANSPINSSTER, BDPERTRANSPIRTER, BDCATEGORIAESOCIAL, BDVINCEMPTER,
                                         BDCODMULTVINC)
    select BDCODTER, :VBDREFTERC, BDCATEGORIATER, BDOCORRENCIATER, BDPERCRATTER, BDPERTRANSPINSSTER, BDPERTRANSPIRTER,
           BDCATEGORIAESOCIAL, BDVINCEMPTER, BDCODMULTVINC
    from VRHF_BASE_TTERC_FGTSGPS TR1
    where not exists(select *
                     from VRHF_BASE_TTERC_FGTSGPS TR2
                     where TR2.BDCODTER = TR1.BDCODTER and
                           TR2.BDREFTERC = :VBDREFTERC) and
          TR1.BDCODTER = :PRBDCODTER and
          TR1.BDREFTERC = (select min(TR2.BDREFTERC)
                           from VRHF_BASE_TTERC_FGTSGPS TR2
                           where TR2.BDCODTER = TR1.BDCODTER and
                                 TR2.BDREFTERC >= :VBDREFTERC);

    insert into VRHF_BASE_TTERC_BANCO (BDCODTER, BDREFTERC, BDCODBAN, BDCODAG, BDCTADEPTER, BDDIGCTADEPTER,
                                       BDTIPOCTATER, BDMODOPAGTOTER, BDCARTAOSALTER)
    select BDCODTER, :VBDREFTERC, BDCODBAN, BDCODAG, BDCTADEPTER, BDDIGCTADEPTER, BDTIPOCTATER, BDMODOPAGTOTER,
           BDCARTAOSALTER
    from VRHF_BASE_TTERC_BANCO TR1
    where not exists(select *
                     from VRHF_BASE_TTERC_BANCO TR2
                     where TR2.BDCODTER = TR1.BDCODTER and
                           TR2.BDREFTERC = :VBDREFTERC) and
          TR1.BDCODTER = :PRBDCODTER and
          TR1.BDREFTERC = (select min(TR2.BDREFTERC)
                           from VRHF_BASE_TTERC_BANCO TR2
                           where TR2.BDCODTER = TR1.BDCODTER and
                                 TR2.BDREFTERC >= :VBDREFTERC);

    insert into VRH_BASE_TTERC_VINC (BDCODTER, BDREFTERC, BDCODCLA, BDCODCBO, BDCODCBOTSIN, BDCODSINTRAB,
                                     BDACORDOINSSTERC, BDPERCIRTERC, BDPIRTERC)
    select BDCODTER, :VBDREFTERC, BDCODCLA, BDCODCBO, BDCODCBOTSIN, BDCODSINTRAB, BDACORDOINSSTERC, BDPERCIRTERC,
           BDPIRTERC
    from VRH_BASE_TTERC_VINC TR1
    where not exists(select *
                     from VRH_BASE_TTERC_VINC TR2
                     where TR2.BDCODTER = TR1.BDCODTER and
                           TR2.BDREFTERC = :VBDREFTERC) and
          TR1.BDCODTER = :PRBDCODTER and
          TR1.BDREFTERC = (select min(TR2.BDREFTERC)
                           from VRH_BASE_TTERC_VINC TR2
                           where TR2.BDCODTER = TR1.BDCODTER and
                                 TR2.BDREFTERC >= :VBDREFTERC);

    insert into VRH_BASE_TTERC_DOCREF (BDCODTER, BDREFTERC, BDRGTER, BDORGEMIRGTER, BDDATAEMIRGTER, BDCODUFRG, BDPISTER,
                                       BDNROCONSPROTER, BDSIGLACONSPROTER, BDCODCCMPROTER, BDCNHTER, BDCATCNHTER,
                                       BDORGAOCNH, BDCODUFCNH, BDDATAEMICNH, BDVENCCNHTER, BDCTPSTER, BDSERIECTPSTER,
                                       BDDSERIECTPSTER, BDDATAEMICTPSTER, BDCODUFCTPS, BDNUMRICCOL, BDDATAEMIRICCOL,
                                       BDORGAORICCOL, BDCODCIDRIC, BDNUMOCCOL, BDORGAOOCCOL, BDDATAEMIOCCOL,
                                       BDDATAVALOCCOL, BDDATAEMIRNECOL, BDORGAORNECOL, BDNUMRNECOL)
    select BDCODTER, :VBDREFTERC, BDRGTER, BDORGEMIRGTER, BDDATAEMIRGTER, BDCODUFRG, BDPISTER, BDNROCONSPROTER,
           BDSIGLACONSPROTER, BDCODCCMPROTER, BDCNHTER, BDCATCNHTER, BDORGAOCNH, BDCODUFCNH, BDDATAEMICNH, BDVENCCNHTER,
           BDCTPSTER, BDSERIECTPSTER, BDDSERIECTPSTER, BDDATAEMICTPSTER, BDCODUFCTPS, BDNUMRICCOL, BDDATAEMIRICCOL,
           BDORGAORICCOL, BDCODCIDRIC, BDNUMOCCOL, BDORGAOOCCOL, BDDATAEMIOCCOL, BDDATAVALOCCOL, BDDATAEMIRNECOL,
           BDORGAORNECOL, BDNUMRNECOL
    from VRH_BASE_TTERC_DOCREF TR1
    where not exists(select *
                     from VRH_BASE_TTERC_DOCREF TR2
                     where TR2.BDCODTER = TR1.BDCODTER and
                           TR2.BDREFTERC = :VBDREFTERC) and
          TR1.BDCODTER = :PRBDCODTER and
          TR1.BDREFTERC = (select min(TR2.BDREFTERC)
                           from VRH_BASE_TTERC_DOCREF TR2
                           where TR2.BDCODTER = TR1.BDCODTER and
                                 TR2.BDREFTERC >= :VBDREFTERC);

    insert into VRH_BASE_TTERC_FISREF (BDCODTER, BDREFTERC, BDSEXOTER, BDRACACORTER, BDDEFFISICOTER, BDOBSDEFFISICOTER,
                                       BDDEFFISTER, BDDEFVISTER, BDDEFAUDTER, BDDEFMENTER, BDDEFINTTER, BDDEFREABTER,
                                       BDCOTADEFTER)
    select BDCODTER, :VBDREFTERC, BDSEXOTER, BDRACACORTER, BDDEFFISICOTER, BDOBSDEFFISICOTER, BDDEFFISTER, BDDEFVISTER,
           BDDEFAUDTER, BDDEFMENTER, BDDEFINTTER, BDDEFREABTER, BDCOTADEFTER
    from VRH_BASE_TTERC_FISREF TR1
    where not exists(select *
                     from VRH_BASE_TTERC_FISREF TR2
                     where TR2.BDCODTER = TR1.BDCODTER and
                           TR2.BDREFTERC = :VBDREFTERC) and
          TR1.BDCODTER = :PRBDCODTER and
          TR1.BDREFTERC = (select min(TR2.BDREFTERC)
                           from VRH_BASE_TTERC_FISREF TR2
                           where TR2.BDCODTER = TR1.BDCODTER and
                                 TR2.BDREFTERC >= :VBDREFTERC);

  end
end^

CREATE OR ALTER procedure SP_CODRECEXP (
    PRCODRECOF varchar(6),
    PRCODUF_REC integer,
    PRCODUF_EMP integer)
returns (
    BDCODRECEXP varchar(10))
as
declare variable WCODUF integer;
begin
  BDCODRECEXP = COALESCE(:PRCODRECOF, '');

  IF (CHAR_LENGTH(:BDCODRECEXP) < 6) THEN
    BEGIN

      IF ((COALESCE(:PRCODUF_EMP, 0) = 0) AND (COALESCE(:PRCODUF_REC, 0) > 0)) THEN
        wCodUF = :PRCODUF_REC;
      ELSE
        wCodUF =:PRCODUF_EMP;

      IF (:wCodUF IN (8, 26)) THEN /*ES e SP*/
        BEGIN
          SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(:BDCODRECEXP) INTO :BDCODRECEXP;
          BDCODRECEXP = LPAD(:BDCODRECEXP, 4, '0');
          BDCODRECEXP = SUBSTRING(:BDCODRECEXP FROM 1 FOR 3)||'-'||SUBSTRING(:BDCODRECEXP FROM 4 FOR 1);
        END
    END

  SUSPEND;
end^

CREATE OR ALTER procedure SP_VALORES_1920 (
  PRCODEMP INTEGER,
  PRCODPERIODO INTEGER,
  PRREFINI INTEGER,
  PRREFFIM INTEGER)
returns (
    BDCODQICMSSPED integer ,
    BDCODEMP integer ,
    BDCODPERIODO integer ,
    BDREFERENCIA integer ,
    BDCODSUBAPU integer ,
    BDVL_TOT_TRANSF_DEBITOS_OA DM_NUMERIC_15_2,
    BDVL_TOT_AJ_DEBITOS_OA DM_NUMERIC_15_2,
    BDVL_ESTORNOS_CRED_OA DM_NUMERIC_15_2,
    BDVL_TOT_TRANSF_CREDITOS_OA DM_NUMERIC_15_2,
    BDVL_TOT_AJ_CREDITOS_OA DM_NUMERIC_15_2,
    BDVL_ESTORNOS_DEB_OA DM_NUMERIC_15_2,
    BDVL_SLD_CREDOR_ANT_OA DM_NUMERIC_15_2,
    BDVL_SLD_APURADO_OA DM_NUMERIC_15_2,
    BDVL_TOT_DED DM_NUMERIC_15_2,
    BDVL_ICMS_RECOLHER_OA DM_NUMERIC_15_2,
    BDVL_SLD_CREDOR_TRANSP_OA DM_NUMERIC_15_2,
    BDDEB_ESP_OA DM_NUMERIC_15_2)
as
declare variable WNUMCAMPO integer;
declare variable WVALOR DM_NUMERIC_15_2;
begin

  FOR SELECT SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO, SPED.BDREFERENCIA, SPED.BDCODSUBAPU
      FROM VEF_EMP_TICMSSPED1920 SPED
      JOIN VEF_EMP_TICMSSPEDGER ICMS ON(ICMS.BDCODEMP = SPED.BDCODEMP AND ICMS.BDCODPERIODO = SPED.BDCODPERIODO AND ICMS.BDREFERENCIA = SPED.BDREFERENCIA)
      JOIN VEF_BASE_TCONFICMSSPEDQ QSPED ON(QSPED.BDCODTIPO = 144 AND QSPED.BDCODQICMSSPED = SPED.BDCODQICMSSPED)
      JOIN VW_INT_SPEDICMS_REF CONF ON(CONF.BDCODEMP = SPED.BDCODEMP)
      JOIN VEF_INT_TSPEDICMSCONF1900 R1900 ON(R1900.BDCODEMP = CONF.BDCODEMP AND R1900.BDCODIGO = CONF.BDCODIGO AND R1900.BDCODSUBAPU = SPED.BDCODSUBAPU)      
      WHERE SPED.BDCODEMP = :PRCODEMP
      AND SPED.BDREFERENCIA BETWEEN :PRREFINI AND :PRREFFIM
      AND SPED.BDCODPERIODO = :PRCODPERIODO
      GROUP BY SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO, SPED.BDREFERENCIA, SPED.BDCODSUBAPU
      INTO :BDCODQICMSSPED, :BDCODEMP, :BDCODPERIODO, :BDREFERENCIA, :BDCODSUBAPU
  DO
    BEGIN
      BDVL_TOT_TRANSF_DEBITOS_OA  = 0;
      BDVL_TOT_AJ_DEBITOS_OA      = 0;
      BDVL_ESTORNOS_CRED_OA       = 0;
      BDVL_TOT_TRANSF_CREDITOS_OA = 0;
      BDVL_TOT_AJ_CREDITOS_OA     = 0;
      BDVL_ESTORNOS_DEB_OA        = 0;
      BDVL_SLD_CREDOR_ANT_OA      = 0;
      BDVL_SLD_APURADO_OA         = 0;
      BDVL_TOT_DED                = 0;
      BDVL_ICMS_RECOLHER_OA       = 0;
      BDVL_SLD_CREDOR_TRANSP_OA   = 0;
      BDDEB_ESP_OA                = 0;
    
      FOR SELECT APU.BDNUMCAMPO, APU.BDVALOR
          FROM VEF_EMP_TICMSSPED1920 APU
          WHERE APU.BDCODQICMSSPED = :BDCODQICMSSPED
          AND APU.BDCODEMP = :BDCODEMP
          AND APU.BDCODPERIODO = :BDCODPERIODO
          AND APU.BDREFERENCIA = :BDREFERENCIA
          AND APU.BDCODSUBAPU = :BDCODSUBAPU
          INTO :wNumCampo, :wValor
      DO
        BEGIN
          IF (:wNumCampo = 1) THEN
            BDVL_TOT_TRANSF_DEBITOS_OA  = :wValor;
          ELSE
          IF (:wNumCampo = 2) THEN
            BDVL_TOT_AJ_DEBITOS_OA      = :wValor;
          ELSE
          IF (:wNumCampo = 3) THEN
            BDVL_ESTORNOS_CRED_OA       = :wValor;
          ELSE
          IF (:wNumCampo = 4) THEN
            BDVL_TOT_TRANSF_CREDITOS_OA = :wValor;
          ELSE
          IF (:wNumCampo = 5) THEN
            BDVL_TOT_AJ_CREDITOS_OA     = :wValor;
          ELSE
          IF (:wNumCampo = 6) THEN
            BDVL_ESTORNOS_DEB_OA        = :wValor;
          ELSE
          IF (:wNumCampo = 7) THEN
            BDVL_SLD_CREDOR_ANT_OA      = :wValor;
          ELSE
          IF (:wNumCampo = 8) THEN
            BDVL_SLD_APURADO_OA         = :wValor;
          ELSE
          IF (:wNumCampo = 9) THEN
            BDVL_TOT_DED                = :wValor;
          ELSE
          IF (:wNumCampo = 10) THEN
            BDVL_ICMS_RECOLHER_OA       = :wValor;
          ELSE
          IF (:wNumCampo = 11) THEN
            BDVL_SLD_CREDOR_TRANSP_OA   = :wValor;
          ELSE
          IF (:wNumCampo = 12) THEN
            BDDEB_ESP_OA                = :wValor;
        END
    
      SUSPEND;

      BDCODQICMSSPED = NULL;
      BDCODEMP       = NULL;
      BDCODPERIODO   = NULL;
      BDREFERENCIA   = NULL;
      BDCODSUBAPU    = NULL;
  END
end^

CREATE OR ALTER procedure SP_EXPORTA_BLOCO1900 (
    PRCODEMP integer not null,
    PRDATAINI date not null,
    PRDATAFIM date not null,
    PRVALIDAREXPORTACAO DM_BOOLEAN not null,
    PRARQUIVO varchar(260) not null)
as
declare variable WLINHA blob sub_type 1 segment size 200;
declare variable WREFINI integer;
declare variable WREFFIM integer;
declare variable WTIPOEXPCODPART integer;
declare variable WCODUF integer;
begin
  DELETE FROM TEXPORTACAO_SPED WHERE BDID = :PRARQUIVO;

  SELECT BDDATA FROM SP_PARSE_DATE(:PRDATAINI, 'YYYYMM') INTO :wRefIni;
  SELECT BDDATA FROM SP_PARSE_DATE(:PRDATAFIM, 'YYYYMM') INTO :wRefFim;

  SELECT VW.BDTIPOEXPCODPART
  FROM VW_INT_SPEDICMS_REF VW
  WHERE VW.BDCODEMP = :PRCODEMP
  INTO :wTipoExpCodPart;

  SELECT UF.BDCODUF
  FROM VW_TEMPRESAS_REF EMP
  JOIN TCIDADE CID ON(CID.BDCODCID = EMP.BDCODCID)
  JOIN TUF UF ON(UF.BDCODUF = CID.BDCODUF)
  WHERE EMP.BDCODEMP = :PRCODEMP
  INTO :wCodUF;

  IF (ROW_COUNT = 0) THEN
    wTipoExpCodPart = -1; /*Não achou o TipoExpCodPart*/

  /*****************************************************************************
   *                                   1910                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODSUBAPU)
  SELECT :PRARQUIVO BDID,
         LPAD(R1900.BDCODEMP, 6, '0')||'.1900.'||LPAD(R1900.BDCODSUBAPU, 10, '0')||'.1910.'||R1900.BDREFERENCIA,
         '1910' BDREG,
         '|1910|'||(SELECT BDDATA FROM SP_PARSE_DATE(:PRDATAINI, 'DDMMYYYY'))||
         '|'||(SELECT BDDATA FROM SP_PARSE_DATE(:PRDATAFIM, 'DDMMYYYY'))||
         '|', R1900.BDCODSUBAPU
  FROM (
        SELECT SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO, SPED.BDREFERENCIA, SPED.BDCODSUBAPU
        FROM VEF_EMP_TICMSSPED1920 SPED
        JOIN VEF_EMP_TICMSSPEDGER ICMS ON(ICMS.BDCODEMP = SPED.BDCODEMP AND ICMS.BDCODPERIODO = SPED.BDCODPERIODO AND ICMS.BDREFERENCIA = SPED.BDREFERENCIA)
        JOIN VEF_BASE_TCONFICMSSPEDQ QSPED ON(QSPED.BDCODTIPO = 144 AND QSPED.BDCODQICMSSPED = SPED.BDCODQICMSSPED)
        JOIN VW_INT_SPEDICMS_REF CONF ON(CONF.BDCODEMP = SPED.BDCODEMP)
        JOIN VEF_INT_TSPEDICMSCONF1900 R1900 ON(R1900.BDCODEMP = CONF.BDCODEMP AND R1900.BDCODIGO = CONF.BDCODIGO AND R1900.BDCODSUBAPU = SPED.BDCODSUBAPU)        
        WHERE SPED.BDCODEMP = :PRCODEMP
        AND SPED.BDREFERENCIA BETWEEN :wRefIni AND :wRefFim
        AND SPED.BDCODPERIODO = 7
        GROUP BY SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO, SPED.BDREFERENCIA, SPED.BDCODSUBAPU
       ) R1900;

  /*****************************************************************************
   *                                   1920                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODSUBAPU)
  SELECT :PRARQUIVO BDID,
         LPAD(R1920.BDCODEMP, 6, '0')||'.1900.'||LPAD(R1920.BDCODSUBAPU, 10, '0')||'.1910.'||R1920.BDREFERENCIA||'.1920',
         '1920' BDREG,
         '|1920|'||REPLACE(COALESCE(R1920.BDVL_TOT_TRANSF_DEBITOS_OA, 0.00), '.', ',')||
         '|'||REPLACE(COALESCE(R1920.BDVL_TOT_AJ_DEBITOS_OA, 0.00), '.', ',')||
         '|'||REPLACE(COALESCE(R1920.BDVL_ESTORNOS_CRED_OA, 0.00), '.', ',')||
         '|'||REPLACE(COALESCE(R1920.BDVL_TOT_TRANSF_CREDITOS_OA, 0.00), '.', ',')||
         '|'||REPLACE(COALESCE(R1920.BDVL_TOT_AJ_CREDITOS_OA, 0.00), '.', ',')||
         '|'||REPLACE(COALESCE(R1920.BDVL_ESTORNOS_DEB_OA, 0.00), '.', ',')||
         '|'||REPLACE(COALESCE(R1920.BDVL_SLD_CREDOR_ANT_OA, 0.00), '.', ',')||
         '|'||REPLACE(COALESCE(R1920.BDVL_SLD_APURADO_OA, 0.00), '.', ',')||
         '|'||REPLACE(COALESCE(R1920.BDVL_TOT_DED, 0.00), '.', ',')||
         '|'||REPLACE(COALESCE(R1920.BDVL_ICMS_RECOLHER_OA, 0.00), '.', ',')||
         '|'||REPLACE(COALESCE(R1920.BDVL_SLD_CREDOR_TRANSP_OA, 0.00), '.', ',')||
         '|'||REPLACE(COALESCE(R1920.BDDEB_ESP_OA, 0.00), '.', ',')||
         '|', R1920.BDCODSUBAPU
  FROM SP_VALORES_1920(:PRCODEMP, 7, :wRefIni, :wRefFim) R1920;

  /*****************************************************************************
   *                                   1921                                    *
   ****************************************************************************/
  /*1921 - Não consolidado*/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODSUBAPU)
  SELECT :PRARQUIVO BDID,
         LPAD(R1921.BDCODEMP, 6, '0')||'.1900.'||LPAD(R1921.BDCODSUBAPU, 10, '0')||'.1910.'||R1921.BDREFERENCIA||'.1920.1921.'||LPAD(R1921.BDCODAJUPAD, 8, '0')||'.'||LPAD(R1921.BDORDEM1921,8,'0'),
         '1921' BDREG,
         '|1921|'||COALESCE(R1921.BDCODAJUPAD, '')||
         '|'||COALESCE(R1921.BDDESCCOMP, '')||
         '|'||REPLACE(COALESCE(R1921.BDVALOR, 0.00), '.', ',')||
         '|', R1921.BDCODSUBAPU
  FROM (
        SELECT R1921.BDCODEMP, R1921.BDCODSUBAPU, R1921.BDREFERENCIA, AJUICMS.BDCODAJUPAD,
               R1921.BDDESCCOMP, COALESCE(R1921.BDVALOR, 0) BDVALOR,R1921.bdordem1921
        FROM (
              SELECT SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO, SPED.BDREFERENCIA, SPED.BDCODSUBAPU
              FROM VEF_EMP_TICMSSPED1920 SPED
              JOIN VEF_EMP_TICMSSPEDGER ICMS ON(ICMS.BDCODEMP = SPED.BDCODEMP AND ICMS.BDCODPERIODO = SPED.BDCODPERIODO AND ICMS.BDREFERENCIA = SPED.BDREFERENCIA)
              JOIN VEF_BASE_TCONFICMSSPEDQ QSPED ON(QSPED.BDCODTIPO = 144 AND QSPED.BDCODQICMSSPED = SPED.BDCODQICMSSPED)
              JOIN VW_INT_SPEDICMS_REF CONF ON(CONF.BDCODEMP = SPED.BDCODEMP)
              JOIN VEF_INT_TSPEDICMSCONF1900 R1900 ON(R1900.BDCODEMP = CONF.BDCODEMP AND R1900.BDCODIGO = CONF.BDCODIGO AND R1900.BDCODSUBAPU = SPED.BDCODSUBAPU AND R1900.BDEXP1921CONSOLID = 'FALSE')
              WHERE SPED.BDCODEMP = :PRCODEMP
              AND SPED.BDREFERENCIA BETWEEN :wRefIni AND :wRefFim
              AND SPED.BDCODPERIODO = 7
              GROUP BY SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO,
                       SPED.BDREFERENCIA, SPED.BDCODSUBAPU
             ) R1920
        JOIN VEF_EMP_TMOVAJU1921 R1921 ON(R1921.BDCODEMP = R1920.BDCODEMP AND R1921.BDCODSUBAPU = R1920.BDCODSUBAPU AND R1921.BDREFERENCIA = R1920.BDREFERENCIA)
        LEFT OUTER JOIN VEF_BASE_TTABAJUICMS AJUICMS ON(AJUICMS.BDCODAJUICMS = R1921.BDCODAJUICMS)
       ) R1921;

  /*1921 - Consolidado*/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODSUBAPU)
  SELECT :PRARQUIVO BDID,
         LPAD(R1921.BDCODEMP, 6, '0')||'.1900.'||LPAD(R1921.BDCODSUBAPU, 10, '0')||'.1910.'||R1921.BDREFERENCIA||'.1920.1921.'||LPAD(R1921.BDCODAJUPAD, 8, '0'),
         '1921' BDREG,
         '|1921|'||COALESCE(R1921.BDCODAJUPAD, '')||
         '|'||COALESCE(R1921.BDDESCCOMP, '')||
         '|'||REPLACE(COALESCE(R1921.BDVALOR, 0.00), '.', ',')||
         '|', R1921.BDCODSUBAPU
  FROM (
        SELECT R1921.BDCODEMP, R1921.BDCODSUBAPU, R1921.BDREFERENCIA, AJUICMS.BDCODAJUPAD,
                ''BDDESCCOMP, SUM(COALESCE(R1921.BDVALOR, 0)) BDVALOR
        FROM (
              SELECT SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO, SPED.BDREFERENCIA, SPED.BDCODSUBAPU
              FROM VEF_EMP_TICMSSPED1920 SPED
              JOIN VEF_EMP_TICMSSPEDGER ICMS ON(ICMS.BDCODEMP = SPED.BDCODEMP AND ICMS.BDCODPERIODO = SPED.BDCODPERIODO AND ICMS.BDREFERENCIA = SPED.BDREFERENCIA)
              JOIN VEF_BASE_TCONFICMSSPEDQ QSPED ON(QSPED.BDCODTIPO = 144 AND QSPED.BDCODQICMSSPED = SPED.BDCODQICMSSPED)
              JOIN VW_INT_SPEDICMS_REF CONF ON(CONF.BDCODEMP = SPED.BDCODEMP)
              JOIN VEF_INT_TSPEDICMSCONF1900 R1900 ON(R1900.BDCODEMP = CONF.BDCODEMP AND R1900.BDCODIGO = CONF.BDCODIGO AND R1900.BDCODSUBAPU = SPED.BDCODSUBAPU AND R1900.BDEXP1921CONSOLID = 'TRUE')
              WHERE SPED.BDCODEMP = :PRCODEMP
              AND SPED.BDREFERENCIA BETWEEN :wRefIni AND :wRefFim
              AND SPED.BDCODPERIODO = 7
              GROUP BY SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO,
                       SPED.BDREFERENCIA, SPED.BDCODSUBAPU
             ) R1920
        JOIN VEF_EMP_TMOVAJU1921 R1921 ON(R1921.BDCODEMP = R1920.BDCODEMP AND R1921.BDCODSUBAPU = R1920.BDCODSUBAPU AND R1921.BDREFERENCIA = R1920.BDREFERENCIA)
        LEFT OUTER JOIN VEF_BASE_TTABAJUICMS AJUICMS ON(AJUICMS.BDCODAJUICMS = R1921.BDCODAJUICMS)
        GROUP BY R1921.BDCODEMP, R1921.BDCODSUBAPU, R1921.BDREFERENCIA, AJUICMS.BDCODAJUPAD, BDDESCCOMP
       ) R1921;

  /*****************************************************************************
   *                                   1922                                    *
   ****************************************************************************/
  /*1922 - Não consolidado*/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODSUBAPU)
  SELECT :PRARQUIVO BDID,
         LPAD(R1921.BDCODEMP, 6, '0')||'.1900.'||LPAD(R1921.BDCODSUBAPU, 10, '0')||'.1910.'||R1921.BDREFERENCIA||'.1920.1921.'||LPAD(R1921.BDCODAJUPAD, 8, '0')||'.'||LPAD(R1921.BDORDEM1921,8,'0')||'.1922.'||R1922.BDORDEM1922,
         '1922' BDREG,
         '|1922|'||COALESCE(R1922.BDNRDOC, '')||
         --'|'||COALESCE(R1922.BDNUMPROC, '')||
         '|'||IIF(:wRefIni < 202301, COALESCE(TRIM(SUBSTRING(R1922.BDNUMPROC FROM 1 FOR 15)), ''), COALESCE(TRIM(SUBSTRING(R1922.BDNUMPROC FROM 1 FOR 60)), ''))||
         '|'||IIF(COALESCE(R1922.BDINDPROC, '') = 3, '9', COALESCE(R1922.BDINDPROC, ''))||
         '|'||COALESCE(R1922.BDDESCPROC, '')||
         '|'||COALESCE(R1922.BDDESCCOMP, '')||
         '|', R1921.BDCODSUBAPU
  FROM (
        SELECT R1921.BDCODEMP, R1921.BDCODSUBAPU, R1921.BDREFERENCIA, R1921.BDORDEM1921, R1921.BDCODAJUPAD
        FROM (
              SELECT R1921.BDCODEMP, R1921.BDCODSUBAPU, R1921.BDREFERENCIA, R1921.BDORDEM1921, AJUICMS.BDCODAJUPAD,
                     R1921.BDDESCCOMP, COALESCE(R1921.BDVALOR, 0) BDVALOR
              FROM (
                    SELECT SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO, SPED.BDREFERENCIA, SPED.BDCODSUBAPU
                    FROM VEF_EMP_TICMSSPED1920 SPED
                    JOIN VEF_EMP_TICMSSPEDGER ICMS ON(ICMS.BDCODEMP = SPED.BDCODEMP AND ICMS.BDCODPERIODO = SPED.BDCODPERIODO AND ICMS.BDREFERENCIA = SPED.BDREFERENCIA)
                    JOIN VEF_BASE_TCONFICMSSPEDQ QSPED ON(QSPED.BDCODTIPO = 144 AND QSPED.BDCODQICMSSPED = SPED.BDCODQICMSSPED)
                    JOIN VW_INT_SPEDICMS_REF CONF ON(CONF.BDCODEMP = SPED.BDCODEMP)
                    JOIN VEF_INT_TSPEDICMSCONF1900 R1900 ON(R1900.BDCODEMP = CONF.BDCODEMP AND R1900.BDCODIGO = CONF.BDCODIGO AND R1900.BDCODSUBAPU = SPED.BDCODSUBAPU AND R1900.BDEXP1921CONSOLID = 'FALSE')
                    WHERE SPED.BDCODEMP = :PRCODEMP
                    AND SPED.BDREFERENCIA BETWEEN :wRefIni AND :wRefFim
                    AND SPED.BDCODPERIODO = 7
                    GROUP BY SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO,
                             SPED.BDREFERENCIA, SPED.BDCODSUBAPU
                   ) R1920
              JOIN VEF_EMP_TMOVAJU1921 R1921 ON(R1921.BDCODEMP = R1920.BDCODEMP AND R1921.BDCODSUBAPU = R1920.BDCODSUBAPU AND R1921.BDREFERENCIA = R1920.BDREFERENCIA)
              LEFT OUTER JOIN VEF_BASE_TTABAJUICMS AJUICMS ON(AJUICMS.BDCODAJUICMS = R1921.BDCODAJUICMS)
             ) R1921
       ) R1921
  JOIN VEF_EMP_TMOVAJU1922 R1922 ON(R1922.BDCODEMP = R1921.BDCODEMP AND R1922.BDCODSUBAPU = R1921.BDCODSUBAPU AND R1922.BDORDEM1921 = R1921.BDORDEM1921);

  /*1922 - Consolidado*/
  SETORDEMSEQUENCIAL_STR(:PRCODEMP);

  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODSUBAPU)
  SELECT :PRARQUIVO BDID,
         LPAD(R1921.BDCODEMP, 6, '0')||'.1900.'||LPAD(R1921.BDCODSUBAPU, 10, '0')||'.1910.'||R1921.BDREFERENCIA||'.1920.1921.'||LPAD(R1921A.BDCODAJUPAD, 8, '0')||'.1922.'||GETORDEMSEQUENCIAL_STR(R1921.BDCODAJUICMS, R1921.BDCODEMP),
         '1922' BDREG,
         '|1922|'||COALESCE(R1922.BDNRDOC, '')||
         '|'||COALESCE(R1922.BDNUMPROC, '')||
         '|'||IIF(COALESCE(R1922.BDINDPROC, '') = 3, '9', COALESCE(R1922.BDINDPROC, ''))||
         '|'||COALESCE(R1922.BDDESCPROC, '')||
         '|'||COALESCE(R1922.BDDESCCOMP, '')||
         '|', R1921.BDCODSUBAPU
  FROM (
        SELECT R1921.BDCODEMP, R1921.BDCODSUBAPU, R1921.BDREFERENCIA, AJUICMS.BDCODAJUPAD, R1921.BDCODAJUICMS
        FROM (
              SELECT SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO, SPED.BDREFERENCIA, SPED.BDCODSUBAPU
              FROM VEF_EMP_TICMSSPED1920 SPED
              JOIN VEF_EMP_TICMSSPEDGER ICMS ON(ICMS.BDCODEMP = SPED.BDCODEMP AND ICMS.BDCODPERIODO = SPED.BDCODPERIODO AND ICMS.BDREFERENCIA = SPED.BDREFERENCIA)
              JOIN VEF_BASE_TCONFICMSSPEDQ QSPED ON(QSPED.BDCODTIPO = 144 AND QSPED.BDCODQICMSSPED = SPED.BDCODQICMSSPED)
              JOIN VW_INT_SPEDICMS_REF CONF ON(CONF.BDCODEMP = SPED.BDCODEMP)
              JOIN VEF_INT_TSPEDICMSCONF1900 R1900 ON(R1900.BDCODEMP = CONF.BDCODEMP AND R1900.BDCODIGO = CONF.BDCODIGO AND R1900.BDCODSUBAPU = SPED.BDCODSUBAPU AND R1900.BDEXP1921CONSOLID = 'TRUE')
              WHERE SPED.BDCODEMP = :PRCODEMP
              AND SPED.BDREFERENCIA BETWEEN :wRefIni AND :wRefFim
              AND SPED.BDCODPERIODO = 7
              GROUP BY SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO,
                       SPED.BDREFERENCIA, SPED.BDCODSUBAPU
             ) R1920
        JOIN VEF_EMP_TMOVAJU1921 R1921 ON(R1921.BDCODEMP = R1920.BDCODEMP AND R1921.BDCODSUBAPU = R1920.BDCODSUBAPU AND R1921.BDREFERENCIA = R1920.BDREFERENCIA)
        LEFT OUTER JOIN VEF_BASE_TTABAJUICMS AJUICMS ON(AJUICMS.BDCODAJUICMS = R1921.BDCODAJUICMS)
        GROUP BY R1921.BDCODEMP, R1921.BDCODSUBAPU, R1921.BDREFERENCIA, AJUICMS.BDCODAJUPAD, R1921.BDCODAJUICMS
       ) R1921A
  JOIN VEF_EMP_TMOVAJU1921 R1921 ON(R1921.BDCODEMP = R1921A.BDCODEMP AND R1921.BDCODSUBAPU = R1921A.BDCODSUBAPU AND R1921.BDCODAJUICMS = R1921A.BDCODAJUICMS and r1921.bdreferencia = R1921A.BDREFERENCIA)
  JOIN VEF_EMP_TMOVAJU1922 R1922 ON(R1922.BDCODEMP = R1921.BDCODEMP AND R1922.BDCODSUBAPU = R1921.BDCODSUBAPU AND R1922.BDORDEM1921 = R1921.BDORDEM1921);

  /*****************************************************************************
   *                                   1923                                    *
   ****************************************************************************/
  /*1923 - Não consolidado*/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODPROD, BDCODSUBAPU)
  SELECT :PRARQUIVO BDID,
         LPAD(R1921.BDCODEMP, 6, '0')||'.1900.'||LPAD(R1921.BDCODSUBAPU, 10, '0')||'.1910.'||R1921.BDREFERENCIA||'.1920.1921.'||LPAD(R1921.BDCODAJUPAD, 8, '0')||'.'||LPAD(R1921.BDORDEM1921,8,'0')||'.1923.'||R1923.BDORDEM1923,
         '1923' BDREG,
         '|1923|'||IIF(DOC.BDDOCFIS = '65', '', COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:wTipoExpCodPart, R1923.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO)), ''))||
         '|'||COALESCE(DOC.BDDOCFIS, '')||
         '|'||COALESCE(R1923.BDSERIE, '')||
         '|'||COALESCE(R1923.BDSUBSERIE, '')||
         '|'||COALESCE(R1923.BDNUMDOC, '')||
         '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(R1923.BDDTDOC, 'DDMMYYYY')), '')||
         '|'||IIF(COALESCE(VINC.BDCODSAIDA, '') = '', IIF(COALESCE(VINC.BDCODPROD, '') = '', COALESCE(PROD_UNICO.BDCODPROD, ''), COALESCE(VINC.BDCODPROD, '')), COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
         '|'||REPLACE(COALESCE(R1923.BDVALOR, 0.00), '.', ',')||
         '|'||IIF(TRIM((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(COALESCE(R1923.BDCHAVENFE, '')))) = '', '', (RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(COALESCE(R1923.BDCHAVENFE, ''))), 44, ' ')))||
         '|', IIF(DOC.BDDOCFIS = '65', NULL, R1923.BDCODTER), R1923.BDCODPROD, R1921.BDCODSUBAPU
  FROM (
        SELECT R1921.BDCODEMP, R1921.BDCODSUBAPU, R1921.BDREFERENCIA, R1921.BDORDEM1921, AJUICMS.BDCODAJUPAD
        FROM (
              SELECT SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO, SPED.BDREFERENCIA, SPED.BDCODSUBAPU
              FROM VEF_EMP_TICMSSPED1920 SPED
              JOIN VEF_EMP_TICMSSPEDGER ICMS ON(ICMS.BDCODEMP = SPED.BDCODEMP AND ICMS.BDCODPERIODO = SPED.BDCODPERIODO AND ICMS.BDREFERENCIA = SPED.BDREFERENCIA)
              JOIN VEF_BASE_TCONFICMSSPEDQ QSPED ON(QSPED.BDCODTIPO = 144 AND QSPED.BDCODQICMSSPED = SPED.BDCODQICMSSPED)
              JOIN VW_INT_SPEDICMS_REF CONF ON(CONF.BDCODEMP = SPED.BDCODEMP)
              JOIN VEF_INT_TSPEDICMSCONF1900 R1900 ON(R1900.BDCODEMP = CONF.BDCODEMP AND R1900.BDCODIGO = CONF.BDCODIGO AND R1900.BDCODSUBAPU = SPED.BDCODSUBAPU AND R1900.BDEXP1921CONSOLID = 'FALSE')
              WHERE SPED.BDCODEMP = :PRCODEMP
              AND SPED.BDREFERENCIA BETWEEN :wRefIni AND :wRefFim
              AND SPED.BDCODPERIODO = 7
              GROUP BY SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO,
                       SPED.BDREFERENCIA, SPED.BDCODSUBAPU
             ) R1920
        JOIN VEF_EMP_TMOVAJU1921 R1921 ON(R1921.BDCODEMP = R1920.BDCODEMP AND R1921.BDCODSUBAPU = R1920.BDCODSUBAPU AND R1921.BDREFERENCIA = R1920.BDREFERENCIA)
        LEFT OUTER JOIN VEF_BASE_TTABAJUICMS AJUICMS ON(AJUICMS.BDCODAJUICMS = R1921.BDCODAJUICMS)
       ) R1921
  JOIN VEF_EMP_TMOVAJU1923 R1923 ON(R1923.BDCODEMP = R1921.BDCODEMP AND R1923.BDCODSUBAPU = R1921.BDCODSUBAPU AND R1923.BDORDEM1921 = R1921.BDORDEM1921)
  /*Produto*/
  LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = R1923.BDCODEMP AND VINC.BDCODPROD = R1923.BDCODPROD)
  LEFT OUTER JOIN TCADPRO PROD_UNICO ON(PROD_UNICO.BDCODPROD = R1923.BDCODPROD)
  LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOC ON(DOC.BDCODDOCFIS = R1923.BDCODDOCFIS)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = R1923.BDCODTER)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= :wRefIni) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = R1923.bdcodter);

  /*1923 - Consolidado*/
  SETORDEMSEQUENCIAL_STR(:PRCODEMP);

  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODTER, BDCODPROD, BDCODSUBAPU)
  SELECT :PRARQUIVO BDID,
         LPAD(R1921A.BDCODEMP, 6, '0')||'.1900.'||LPAD(R1921A.BDCODSUBAPU, 10, '0')||'.1910.'||R1921A.BDREFERENCIA||'.1920.1921.'||LPAD(R1921A.BDCODAJUPAD, 8, '0')||'.1923.'||GETORDEMSEQUENCIAL_STR(R1921.BDCODAJUICMS, R1921.BDCODEMP),
         '1923' BDREG,
         '|1923|'||IIF(DOC.BDDOCFIS = '65', '', COALESCE((SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(:wTipoExpCodPart, R1923.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO)), ''))||
         '|'||COALESCE(DOC.BDDOCFIS, '')||
         '|'||COALESCE(R1923.BDSERIE, '')||
         '|'||COALESCE(R1923.BDSUBSERIE, '')||
         '|'||COALESCE(R1923.BDNUMDOC, '')||
         '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(R1923.BDDTDOC, 'DDMMYYYY')), '')||
         '|'||IIF(COALESCE(VINC.BDCODSAIDA, '') = '', IIF(COALESCE(VINC.BDCODPROD, '') = '', COALESCE(PROD_UNICO.BDCODPROD, ''), COALESCE(VINC.BDCODPROD, '')), COALESCE(VINC.BDCODSAIDA,''))|| --COD_ITEM
         '|'||REPLACE(COALESCE(R1923.BDVALOR, 0.00), '.', ',')||
         '|'||IIF(TRIM((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(COALESCE(R1923.BDCHAVENFE, '')))) = '', '', (RPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(COALESCE(R1923.BDCHAVENFE, ''))), 44, ' ')))||
         '|', IIF(DOC.BDDOCFIS = '65', NULL, R1923.BDCODTER), R1923.BDCODPROD, R1921.BDCODSUBAPU
  FROM (
        SELECT R1921.BDCODEMP, R1921.BDCODSUBAPU, R1921.BDREFERENCIA, AJUICMS.BDCODAJUPAD, R1921.BDCODAJUICMS
        FROM (
              SELECT SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO, SPED.BDREFERENCIA, SPED.BDCODSUBAPU
              FROM VEF_EMP_TICMSSPED1920 SPED
              JOIN VEF_EMP_TICMSSPEDGER ICMS ON(ICMS.BDCODEMP = SPED.BDCODEMP AND ICMS.BDCODPERIODO = SPED.BDCODPERIODO AND ICMS.BDREFERENCIA = SPED.BDREFERENCIA)
              JOIN VEF_BASE_TCONFICMSSPEDQ QSPED ON(QSPED.BDCODTIPO = 144 AND QSPED.BDCODQICMSSPED = SPED.BDCODQICMSSPED)
              JOIN VW_INT_SPEDICMS_REF CONF ON(CONF.BDCODEMP = SPED.BDCODEMP)
              JOIN VEF_INT_TSPEDICMSCONF1900 R1900 ON(R1900.BDCODEMP = CONF.BDCODEMP AND R1900.BDCODIGO = CONF.BDCODIGO AND R1900.BDCODSUBAPU = SPED.BDCODSUBAPU AND R1900.BDEXP1921CONSOLID = 'TRUE')
              WHERE SPED.BDCODEMP = :PRCODEMP
              AND SPED.BDREFERENCIA BETWEEN :wRefIni AND :wRefFim
              AND SPED.BDCODPERIODO = 7
              GROUP BY SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO,
                       SPED.BDREFERENCIA, SPED.BDCODSUBAPU
             ) R1920
        JOIN VEF_EMP_TMOVAJU1921 R1921 ON(R1921.BDCODEMP = R1920.BDCODEMP AND R1921.BDCODSUBAPU = R1920.BDCODSUBAPU AND R1921.BDREFERENCIA = R1920.BDREFERENCIA)
        LEFT OUTER JOIN VEF_BASE_TTABAJUICMS AJUICMS ON(AJUICMS.BDCODAJUICMS = R1921.BDCODAJUICMS)
        GROUP BY R1921.BDCODEMP, R1921.BDCODSUBAPU, R1921.BDREFERENCIA, AJUICMS.BDCODAJUPAD, R1921.BDCODAJUICMS
       ) R1921A
  JOIN VEF_EMP_TMOVAJU1921 R1921 ON(R1921.BDCODEMP = R1921A.BDCODEMP AND R1921.BDCODSUBAPU = R1921A.BDCODSUBAPU AND R1921.BDCODAJUICMS = R1921A.BDCODAJUICMS AND R1921.BDREFERENCIA = R1921A.BDREFERENCIA)
  JOIN VEF_EMP_TMOVAJU1923 R1923 ON(R1923.BDCODEMP = R1921.BDCODEMP AND R1923.BDCODSUBAPU = R1921.BDCODSUBAPU AND R1923.BDORDEM1921 = R1921.BDORDEM1921)
  /*Produto*/
  LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = R1923.BDCODEMP AND VINC.BDCODPROD = R1923.BDCODPROD)
  LEFT OUTER JOIN TCADPRO PROD_UNICO ON(PROD_UNICO.BDCODPROD = R1923.BDCODPROD)
  LEFT OUTER JOIN VEF_BASE_TTABDOCFIS DOC ON(DOC.BDCODDOCFIS = R1923.BDCODDOCFIS)
  LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON(TER.BDCODTER = R1923.BDCODTER)
  LEFT OUTER JOIN (
                   SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                   FROM (
                         SELECT t.bdcodemp, t.bdcodter,
                                COALESCE(
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= :wRefIni) ORDER BY e.bdreferencia DESC),
                                         (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                        ) BDCODIGO
                         FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                        ) tt
                   LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                  ) TerEmp ON (TerEmp.bdcodter = R1923.bdcodter);

  /*****************************************************************************
   *                                   1926                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODSUBAPU)
  SELECT :PRARQUIVO BDID,
         LPAD(R1920.BDCODEMP, 6, '0')||'.1900.'||LPAD(R1920.BDCODSUBAPU, 10, '0')||'.1910.'||R1920.BDREFERENCIA||'.1920.1926.'||R1926.BDORDEM1926,
         '1926' BDREG,
         '|1926|'||COALESCE(ICMSREC.BDICMSRECEXP, '')||
         '|'||REPLACE(COALESCE(R1926.BDVALOR, 0.00), '.', ',')||
         '|'||COALESCE((SELECT BDDATA FROM SP_PARSE_DATE(R1926.BDDTVENCIMENTO, 'DDMMYYYY')), '')||
         '|'||COALESCE((SELECT BDCODRECEXP FROM SP_CODRECEXP(COALESCE(CR.BDCODRECOF, ''), CR.BDCODUF, :wCodUF)), '')||COALESCE(R1926.BDCLAVENC, '')||
         --'|'||COALESCE(R1926.BDNUMPROC, '')||
         '|'||IIF(:wRefIni < 202301, COALESCE(TRIM(SUBSTRING(R1926.BDNUMPROC FROM 1 FOR 15)), ''), COALESCE(TRIM(SUBSTRING(R1926.BDNUMPROC FROM 1 FOR 60)), ''))||
         '|'||IIF(COALESCE(R1926.BDINDPROC, '') = 3, '9', iif(COALESCE(R1926.BDINDPROC, '') = -1,'',COALESCE(R1926.BDINDPROC, '')) )||
         '|'||COALESCE(R1926.BDDESCPROC, '')||
         '|'||COALESCE(R1926.BDDESCCOMP, '')||
         '|'||SUBSTRING(COALESCE(R1926.BDREFERENCIA, '') FROM 5 FOR 2)||SUBSTRING(COALESCE(R1926.BDREFERENCIA, '') FROM 1 FOR 4)||
         '|', R1920.BDCODSUBAPU
  FROM (
        SELECT SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO, SPED.BDREFERENCIA, SPED.BDCODSUBAPU
        FROM VEF_EMP_TICMSSPED1920 SPED
        JOIN VEF_EMP_TICMSSPEDGER ICMS ON(ICMS.BDCODEMP = SPED.BDCODEMP AND ICMS.BDCODPERIODO = SPED.BDCODPERIODO AND ICMS.BDREFERENCIA = SPED.BDREFERENCIA)
        JOIN VEF_BASE_TCONFICMSSPEDQ QSPED ON(QSPED.BDCODTIPO = 144 AND QSPED.BDCODQICMSSPED = SPED.BDCODQICMSSPED)
        JOIN VW_INT_SPEDICMS_REF CONF ON(CONF.BDCODEMP = SPED.BDCODEMP)
        JOIN VEF_INT_TSPEDICMSCONF1900 R1900 ON(R1900.BDCODEMP = CONF.BDCODEMP AND R1900.BDCODIGO = CONF.BDCODIGO AND R1900.BDCODSUBAPU = SPED.BDCODSUBAPU)
        WHERE SPED.BDCODEMP = :PRCODEMP
        AND SPED.BDREFERENCIA BETWEEN :wRefIni AND :wRefFim
        AND SPED.BDCODPERIODO = 7
        GROUP BY SPED.BDCODQICMSSPED, SPED.BDCODEMP, SPED.BDCODPERIODO,
                 SPED.BDREFERENCIA, SPED.BDCODSUBAPU
       ) R1920
  JOIN VEF_EMP_TMOVAJU1926 R1926 ON(R1926.BDCODEMP = R1920.BDCODEMP AND R1926.BDCODSUBAPU = R1920.BDCODSUBAPU AND R1926.BDREFERENCIA = R1920.BDREFERENCIA)
  LEFT OUTER JOIN VEF_BASE_TTABCODICMSREC ICMSREC ON(ICMSREC.BDCODICMSREC= R1926.BDCODICMSREC)
  LEFT OUTER JOIN TCODREC CR ON(CR.BDCODREC = R1926.BDCODREC);

  /*****************************************************************************
   *                                   1900                                    *
   ****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODSUBAPU)
  SELECT :PRARQUIVO BDID,
         LPAD(R1900.BDCODEMP, 6, '0')||'.1900.'||LPAD(R1900.BDCODSUBAPU, 10, '0'),
         '1900' BDREG,
         '|1900|'||COALESCE(SA.BDCODEXPAPU, '')||
         '|'||COALESCE(R1900.BDDESCCOMP, '')||
         '|', R1900.BDCODSUBAPU
  FROM (
        SELECT E.BDCODSUBAPU
        FROM TEXPORTACAO_SPED E
        WHERE E.BDID = :PRARQUIVO
        GROUP BY E.BDCODSUBAPU
       ) E
  JOIN VW_INT_SPEDICMS_REF CONF ON(CONF.BDCODEMP = :PRCODEMP)
  JOIN VEF_INT_TSPEDICMSCONF1900 R1900 ON(R1900.BDCODEMP = CONF.BDCODEMP AND R1900.BDCODIGO = CONF.BDCODIGO AND R1900.BDCODSUBAPU = E.BDCODSUBAPU)
  LEFT OUTER JOIN VEF_BASE_TTIPOSUBAPURACAO SA ON(SA.BDCODSUBAPU = R1900.BDCODSUBAPU);

  /*****************************************************************************
   *                           EXPORTANDO ARQUIVO                              *
   ****************************************************************************/

  OPENARQ(:PRARQUIVO,:PRCODEMP);

  FOR SELECT E.BDLINHA
      FROM TEXPORTACAO_SPED E
      WHERE E.BDID = :PRARQUIVO
      ORDER BY E.BDCHAVEREG
      INTO :wLinha
  DO
    BEGIN
      WRITELNOA(:wLinha,:PRCODEMP);
    END

  CLOSEARQ(:PRARQUIVO,:PRCODEMP);

  WHEN ANY DO
    BEGIN
      IN AUTONOMOUS TRANSACTION DO
        EXECUTE PROCEDURE LANCA_EXCEPTION('SP_EXPORTA_BLOCO1900', SQLCODE, GDSCODE);
      EXCEPTION;
    END

end^

CREATE OR ALTER trigger tmp_vef_emp_taju1921_temp_bu0 for tmp_vef_emp_tmovaju1921_temp
active before update position 0
AS
begin
  IF ((COALESCE(OLD.BDEDITCHAVE, 0) = 0) AND (NEW.BDEDITCHAVE > 0)) THEN
    NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - GETORDEMSEQUENCIAL(0))+1;
end^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_1921 (
    PRSESSAO integer,
    PRULTCHAVE integer)
as
begin
  DELETE FROM VEF_INCON_TBLOCO1900 R WHERE R.BDSESSAO = :PRSESSAO AND R.BDORDEM1921 IS NOT NULL;

  IF (:PRULTCHAVE > 0) THEN
    BEGIN
--      FOR SELECT BDDADO FROM SP_SPLIT(:PRSTRULTCHAVE, '.') INTO :wStr DO
--        BEGIN
--          wCodSubApu = SUBSTRING(:wStr FROM 1 FOR POSITION('=', :wStr)-1);
--          wUltChave  = SUBSTRING(:wStr FROM POSITION('=', :wStr)+1 FOR CHAR_LENGTH(:wStr));
    
          SETORDEMSEQUENCIAL(0);
          UPDATE TMP_VEF_EMP_TMOVAJU1921_TEMP T SET T.BDEDITCHAVE = :PRULTCHAVE
          WHERE T.BDSESSAO  = :PRSESSAO;
          --AND T.BDCODSUBAPU = :wCodSubapu;
--        END
    END

  /*184 - Referência não informada.*/
  INSERT INTO VEF_INCON_TBLOCO1900(BDSESSAO, BDCODEMP, BDCODSUBAPU, BDORDEM1921, BDCODINCONSISTENCIA)
  SELECT R1921.BDSESSAO, R1921.BDCODEMP, R1921.BDCODSUBAPU, R1921.BDORDEM1921, 184 BDCODINCONSISTENCIA
  FROM (
        SELECT T.BDSESSAO, T.BDCODEMP, T.BDCODSUBAPU, T.BDORDEM1921,
               COALESCE(T.BDREFERENCIA, 0) BDREFERENCIA
        FROM TMP_VEF_EMP_TMOVAJU1921_TEMP T
        WHERE T.BDSESSAO = :PRSESSAO
       ) R1921
  WHERE R1921.BDREFERENCIA = 0;

  /*185 - Código do ajuste não informado.*/
  INSERT INTO VEF_INCON_TBLOCO1900(BDSESSAO, BDCODEMP, BDCODSUBAPU, BDORDEM1921, BDCODINCONSISTENCIA)
  SELECT R1921.BDSESSAO, R1921.BDCODEMP, R1921.BDCODSUBAPU, R1921.BDORDEM1921, 185 BDCODINCONSISTENCIA
  FROM (
        SELECT T.BDSESSAO, T.BDCODEMP, T.BDCODSUBAPU, T.BDORDEM1921,
               COALESCE(T.BDCODAJUICMS, 0) BDCODAJUICMS
        FROM TMP_VEF_EMP_TMOVAJU1921_TEMP T
        WHERE T.BDSESSAO = :PRSESSAO
       ) R1921
  WHERE R1921.BDCODAJUICMS = 0;

  EXECUTE PROCEDURE SP_ATUALIZAR_CAMPO_CHAVE_TEMP(:PRSESSAO, 'TMP_VEF_EMP_TMOVAJU1921_TEMP', 'BDORDEM1921');
end^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_1923 (
    PRSESSAO integer,
    PRSESSAOTER integer,
    PRSESSAOPRO integer)
as
begin
  /*186 - Número do documento não informado.*/
  INSERT INTO VEF_INCON_TBLOCO1900(BDSESSAO, BDCODEMP, BDCODSUBAPU, BDORDEM1921, BDORDEM1923, BDCODINCONSISTENCIA)
  SELECT R1923.BDSESSAO, R1923.BDCODEMP, R1923.BDCODSUBAPU, R1923.BDORDEM1921, R1923.BDORDEM1923, 186 BDCODINCONSISTENCIA
  FROM (
        SELECT T.BDSESSAO, T.BDCODEMP, T.BDCODSUBAPU, T.BDORDEM1921, T.BDORDEM1923, COALESCE(T.BDNUMDOC, 0) BDNUMDOC
        FROM TMP_VEF_EMP_TMOVAJU1923_TEMP T
        WHERE T.BDSESSAO = :PRSESSAO
       ) R1923
  WHERE R1923.BDNUMDOC = 0;

  /*187 - Modelo não informado ou inconsistente.*/
  INSERT INTO VEF_INCON_TBLOCO1900(BDSESSAO, BDCODEMP, BDCODSUBAPU, BDORDEM1921, BDORDEM1923, BDCODINCONSISTENCIA)
  SELECT R1923.BDSESSAO, R1923.BDCODEMP, R1923.BDCODSUBAPU, R1923.BDORDEM1921, R1923.BDORDEM1923, 187 BDCODINCONSISTENCIA
  FROM (
        SELECT T.BDSESSAO, T.BDCODEMP, T.BDCODSUBAPU, T.BDORDEM1921, T.BDORDEM1923, COALESCE(T.BDCODDOCFIS, 0) BDCODDOCFIS
        FROM TMP_VEF_EMP_TMOVAJU1923_TEMP T
        WHERE T.BDSESSAO = :PRSESSAO
       ) R1923
  WHERE NOT EXISTS (
                    SELECT D.BDCODDOCFIS
                    FROM VEF_BASE_TTABDOCFIS D
                    WHERE D.BDCODDOCFIS = R1923.BDCODDOCFIS
                   );

  /*188 - Data de emissão não informada.*/
  INSERT INTO VEF_INCON_TBLOCO1900(BDSESSAO, BDCODEMP, BDCODSUBAPU, BDORDEM1921, BDORDEM1923, BDCODINCONSISTENCIA)
  SELECT R1923.BDSESSAO, R1923.BDCODEMP, R1923.BDCODSUBAPU, R1923.BDORDEM1921, R1923.BDORDEM1923, 188 BDCODINCONSISTENCIA
  FROM (
        SELECT T.BDSESSAO, T.BDCODEMP, T.BDCODSUBAPU, T.BDORDEM1921, T.BDORDEM1923, T.BDDTDOC
        FROM TMP_VEF_EMP_TMOVAJU1923_TEMP T
        WHERE T.BDSESSAO = :PRSESSAO
       ) R1923
  WHERE R1923.BDDTDOC IS NULL;

  /*Se não tiver participante vinculado o lançamento é inconsistente*/
  INSERT INTO VEF_INCON_TBLOCO1900(BDSESSAO, BDCODEMP, BDCODSUBAPU, BDORDEM1921, BDORDEM1923, BDCODINCONSISTENCIA)
  SELECT R1923.BDSESSAO, R1923.BDCODEMP, R1923.BDCODSUBAPU, R1923.BDORDEM1921, R1923.BDORDEM1923, 17 BDCODINCONSISTENCIA
  FROM (
        SELECT T.BDSESSAO, T.BDCODEMP, T.BDCODSUBAPU, T.BDORDEM1921, T.BDORDEM1923, T.BDALTCODTER,t.bddocfis
        FROM TMP_VEF_EMP_TMOVAJU1923_TEMP T
        WHERE T.BDSESSAO = :PRSESSAO
       ) R1923
  WHERE (((R1923.BDALTCODTER IS NULL) OR (R1923.BDALTCODTER = 0)) and R1923.bddocfis <> 65); /*Este campo deve estar preenchido, é o código do banco no participante*/

  /*Torna o lançamento inconsistente se o cadastro do participante está inconsistente*/
  INSERT INTO VEF_INCON_TBLOCO1900(BDSESSAO, BDCODEMP, BDCODSUBAPU, BDORDEM1921, BDORDEM1923, BDCODINCONSISTENCIA)
  SELECT R1923.BDSESSAO, R1923.BDCODEMP, R1923.BDCODSUBAPU, R1923.BDORDEM1921, R1923.BDORDEM1923, 74 BDCODINCONSISTENCIA
  FROM (
        SELECT T.BDSESSAO, T.BDCODEMP, T.BDCODSUBAPU, T.BDORDEM1921, T.BDORDEM1923,
               T.BDDTDOC, T.BDALTCODTER, T.BDPARTEXISTENTE, T.BDCODTER
        FROM TMP_VEF_EMP_TMOVAJU1923_TEMP T
        WHERE T.BDSESSAO = :PRSESSAO
       ) R1923
  JOIN VEF_INCON_TTERCEIROS T ON(T.BDSESSAO = :PRSESSAOTER AND T.BDCODTER = R1923.BDALTCODTER)
  AND ((R1923.BDPARTEXISTENTE IS NULL) OR (R1923.BDPARTEXISTENTE <> 'TRUE'))
  AND (R1923.BDCODTER > 0);

  /*Se a situação do produto estiver como 0 - Não relacionado ele não irá ser importado e tudo que tiver produto deve se tornar inconsistente*/
  --73 - Produto não cadastrado.
  INSERT INTO VEF_INCON_TBLOCO1900(BDSESSAO, BDCODEMP, BDCODSUBAPU, BDORDEM1921, BDORDEM1923, BDCODINCONSISTENCIA)
  SELECT R1923.BDSESSAO, R1923.BDCODEMP, R1923.BDCODSUBAPU, R1923.BDORDEM1921, R1923.BDORDEM1923, 73 BDCODINCONSISTENCIA
  FROM (
        SELECT T.BDSESSAO, T.BDCODEMP, T.BDCODSUBAPU, T.BDORDEM1921, T.BDORDEM1923, T.BDCODPROD
        FROM TMP_VEF_EMP_TMOVAJU1923_TEMP T
        WHERE T.BDSESSAO = :PRSESSAO
        AND COALESCE(T.BDCODSAIDA, '') <> ''
       ) R1923
  JOIN TMP_TCADPRO_TEMP P ON(P.BDSESSAO = :PRSESSAOPRO AND P.BDCODPROD = R1923.BDCODPROD AND COALESCE(P.BDSITUACAO, 0) = 0);

  /*Se o produto for inconsistente, torna o lançamento inconsistente tambem*/
  INSERT INTO VEF_INCON_TBLOCO1900(BDSESSAO, BDCODEMP, BDCODSUBAPU, BDORDEM1921, BDORDEM1923, BDCODINCONSISTENCIA)
  SELECT R1923.BDSESSAO, R1923.BDCODEMP, R1923.BDCODSUBAPU, R1923.BDORDEM1921, R1923.BDORDEM1923, 76 BDCODINCONSISTENCIA
  FROM (
        SELECT T.BDSESSAO, T.BDCODEMP, T.BDCODSUBAPU, T.BDORDEM1921, T.BDORDEM1923, T.BDALTCODPROD
        FROM TMP_VEF_EMP_TMOVAJU1923_TEMP T
        WHERE T.BDSESSAO = :PRSESSAO
        AND COALESCE(T.BDCODSAIDA, '') <> ''
       ) R1923
  LEFT OUTER JOIN VEF_INCON_TCADPRO PRO ON(PRO.BDSESSAO = :PRSESSAOPRO AND PRO.BDCODEMP = R1923.BDCODEMP AND PRO.BDCODPROD = R1923.BDALTCODPROD)
  LEFT OUTER JOIN VEF_INCON_TBLOCO1900 INCO ON(INCO.BDSESSAO = :PRSESSAO AND INCO.BDCODEMP = R1923.BDCODEMP AND INCO.BDCODSUBAPU = R1923.BDCODSUBAPU AND
                                               INCO.BDORDEM1921 = R1923.BDORDEM1921 AND INCO.BDORDEM1923 = R1923.BDORDEM1923 AND INCO.BDCODINCONSISTENCIA = 73)
  WHERE PRO.BDCODINCONSISTENCIA IS NOT NULL
  AND INCO.BDCODINCONSISTENCIA IS NULL
  GROUP BY R1923.BDSESSAO, R1923.BDCODEMP, R1923.BDCODSUBAPU, R1923.BDORDEM1921, R1923.BDORDEM1923, BDCODINCONSISTENCIA;
end^

CREATE OR ALTER trigger tmp_vef_emp_aju1926_temp_newkey for tmp_vef_emp_tmovaju1926_temp
active before update position 0
AS
begin
  IF ((COALESCE(OLD.BDEDITCHAVE, 0) = 0) AND (NEW.BDEDITCHAVE > 0)) THEN
    NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - GETORDEMSEQUENCIAL(0))+1;
end^

CREATE OR ALTER procedure SP_ATUALIZAR_TMP_1926 (
    PRSESSAO integer,
    PRSTRULTCHAVE varchar(60))
as
declare variable WSTR varchar(10);
declare variable WULTCHAVE integer;
declare variable WCODSUBAPU integer;
begin
  DELETE FROM VEF_INCON_TBLOCO1900 R WHERE R.BDSESSAO = :PRSESSAO AND R.BDORDEM1926 IS NOT NULL;

  IF (:PRSTRULTCHAVE <> '') THEN
    BEGIN
      FOR SELECT BDDADO FROM SP_SPLIT(:PRSTRULTCHAVE, '.') INTO :wStr DO
        BEGIN
          wCodSubApu = SUBSTRING(:wStr FROM 1 FOR POSITION('=', :wStr)-1);
          wUltChave  = SUBSTRING(:wStr FROM POSITION('=', :wStr)+1 FOR CHAR_LENGTH(:wStr));
    
          SETORDEMSEQUENCIAL(0);
          UPDATE TMP_VEF_EMP_TMOVAJU1926_TEMP T SET T.BDEDITCHAVE = :wUltChave
          WHERE T.BDSESSAO  = :PRSESSAO
          AND T.BDCODSUBAPU = :wCodSubapu;
        END
    END

  /*22 - Lançamento já existente na base de dados*/
  INSERT INTO VEF_INCON_TBLOCO1900(BDSESSAO, BDCODEMP, BDCODSUBAPU, BDORDEM1926, BDCODINCONSISTENCIA)
  SELECT R1926.BDSESSAO, R1926.BDCODEMP, R1926.BDCODSUBAPU, R1926.BDORDEM1926, 22 BDCODINCONSISTENCIA
  FROM (
        SELECT T.BDSESSAO, T.BDCODEMP, T.BDCODSUBAPU, T.BDORDEM1926,
               T.BDCODREC, T.BDCODICMSREC, T.BDREFERENCIA
        FROM TMP_VEF_EMP_TMOVAJU1926_TEMP T
        WHERE T.BDSESSAO = :PRSESSAO
       ) R1926
  WHERE EXISTS (
                SELECT A.BDORDEM1926
                FROM VEF_EMP_TMOVAJU1926 A
                WHERE A.BDCODSUBAPU = R1926.BDCODSUBAPU
                AND A.BDCODREC = R1926.BDCODREC
                AND A.BDCODICMSREC = R1926.BDCODICMSREC
                AND A.BDREFERENCIA = R1926.BDREFERENCIA
               );

  /*189 - Código de receita não informado.*/
  INSERT INTO VEF_INCON_TBLOCO1900(BDSESSAO, BDCODEMP, BDCODSUBAPU, BDORDEM1926, BDCODINCONSISTENCIA)
  SELECT R1926.BDSESSAO, R1926.BDCODEMP, R1926.BDCODSUBAPU, R1926.BDORDEM1926, 189 BDCODINCONSISTENCIA
  FROM (
        SELECT T.BDSESSAO, T.BDCODEMP, T.BDCODSUBAPU, T.BDORDEM1926, COALESCE(T.BDCODREC, 0) BDCODREC
        FROM TMP_VEF_EMP_TMOVAJU1926_TEMP T
        WHERE T.BDSESSAO = :PRSESSAO
       ) R1926
  WHERE R1926.BDCODREC = 0;  
end^

CREATE OR ALTER procedure SP_GRAVAR_DAO (
    PRSESSAO integer,
    PRTABLENAMEPHYSICIST varchar(64),
    PRTABLEINCON varchar(64),
    PRKEYFIELD varchar(64) = 'BDCHAVE')
returns (
    WSQL varchar(2555))
as
declare variable WFIELDS varchar(20000);
declare variable WFIELD varchar(500);
declare variable WI integer;
declare variable WTABELAREPLACE varchar(64);
begin
  wSQL = 'INSERT INTO '||REPLACE(REPLACE(:PRTABLENAMEPHYSICIST, 'TMP_', ''), '_TEMP', '')||'(';

  wTabelaReplace = REPLACE(REPLACE(:PRTABLENAMEPHYSICIST, 'TMP_', ''), '_TEMP', '');
--  SELECT LIST(TRIM(RDB$FIELD_NAME)) FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME = REPLACE(REPLACE(:PRTABLENAMEPHYSICIST, 'TMP_', ''), '_TEMP', '') INTO :wFields;
  SELECT LIST(TRIM(RDB$FIELD_NAME)) FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME = :wTabelaReplace INTO :wFields;

  wSQL = :wSQL ||:wFields||') ';

  --Chave
  wFields = REPLACE(:wFields, ','||:PRKEYFIELD||',', ',BDEDITCHAVE,');
  --Produto
  wFields = REPLACE(:wFields, ',BDCODPROD,', ',BDALTCODPROD,');
  --Participante
  wFields = REPLACE(:wFields, ',BDCODTER,', ',BDALTCODTER,');

  wFields = REPLACE('T.'||:wFields, ',BD', ',T.BD');

  wSQL = :wSQL || 'SELECT '||:wFields||' ';
  wSQL = :wSQL || 'FROM '||:PRTABLENAMEPHYSICIST||' T ';
  wSQL = :wSQL || 'WHERE T.BDSESSAO = '||:PRSESSAO||' ';

  IF (:PRTABLEINCON <> '') THEN
    BEGIN
      wSQL = :wSQL || 'AND NOT EXISTS (';
      wSQL = :wSQL ||                 'SELECT I.* ';
      wSQL = :wSQL ||                 'FROM '||:PRTABLEINCON||' I ';

      wI = 0;
      FOR select BDFIELDPK
            from (
                    SELECT 0 bdordem, IDX.RDB$FIELD_NAME BDFIELDPK
          FROM RDB$RELATION_CONSTRAINTS C
          JOIN RDB$INDEX_SEGMENTS IDX ON(IDX.RDB$INDEX_NAME = C.RDB$INDEX_NAME)
          WHERE C.RDB$RELATION_NAME = TRIM(:PRTABLENAMEPHYSICIST)
                             AND C.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY'
                    
                    union all
                    SELECT 1  bdordem, IDX.RDB$FIELD_NAME BDFIELDPK
                              FROM RDB$RELATION_CONSTRAINTS C
                              JOIN RDB$INDEX_SEGMENTS IDX ON(IDX.RDB$INDEX_NAME = C.RDB$INDEX_NAME)
                              WHERE C.RDB$RELATION_NAME = TRIM(:PRTABLENAMEPHYSICIST)
          AND C.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY'
                 )
            where  ((bdordem = 0) and exists(SELECT IDX.RDB$FIELD_NAME BDFIELDPK FROM RDB$RELATION_CONSTRAINTS C
                                             JOIN RDB$INDEX_SEGMENTS IDX ON(IDX.RDB$INDEX_NAME = C.RDB$INDEX_NAME)
                                             WHERE C.RDB$RELATION_NAME = TRIM(:PRTABLENAMEPHYSICIST)
                                             AND C.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY') )
               or ((bdordem = 1) and not exists(SELECT IDX.RDB$FIELD_NAME BDFIELDPK FROM RDB$RELATION_CONSTRAINTS C
                                            JOIN RDB$INDEX_SEGMENTS IDX ON(IDX.RDB$INDEX_NAME = C.RDB$INDEX_NAME)
                                             WHERE C.RDB$RELATION_NAME = TRIM(:PRTABLENAMEPHYSICIST)
                                             AND C.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY' ))
          INTO :wField
      DO
        BEGIN
          wI = :wI + 1;

          wSQL = :wSQL || IIF(:wI = 1, ' WHERE ', ' AND ');
          wSQL = :wSQL || 'T.'||:wField||' = I.'||:wField;

        END

      wSQL = :wSQL ||                ');';
    END

  EXECUTE STATEMENT :wSQL;

  WHEN ANY DO
    BEGIN
      IN AUTONOMOUS TRANSACTION DO
        EXECUTE PROCEDURE LANCA_EXCEPTION('SP_GRAVAR_DAO - '||:PRTABLENAMEPHYSICIST, SQLCODE, GDSCODE);
      EXCEPTION;
    END
end^

CREATE OR ALTER procedure SP_SET_MASK (
    PRMASK varchar(50),
    PRSTR varchar(255))
returns (
    BDRESULT varchar(255))
as
declare variable WI integer;
declare variable wIStr integer;
declare variable wCarac CHAR(1);
begin
  SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(TRIM(:PRSTR)) INTO :PRSTR;

  wI    = 1;
  wIStr = 1;
  BDRESULT = '';
  WHILE (:wI <= CHAR_LENGTH(:PRMASK)) DO
    BEGIN
      wCarac = SUBSTRING(:PRMASK FROM :wI FOR 1);
      IF (:wCarac = '9') THEN
        BEGIN
          BDRESULT = :BDRESULT || SUBSTRING(:PRSTR FROM :wIStr FOR 1);
          wIStr = :wIStr + 1;
        END
      ELSE
        BEGIN
          BDRESULT = :BDRESULT || :wCarac;
        END

      wI = :wI + 1;
    END

  SUSPEND;
end^

COMMENT ON PARAMETER SP_SET_MASK.PRMASK IS 'EX: 999.999-9'^

CREATE OR ALTER procedure SP_APLICA_PLANO_1900_REDZ (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer,
    WBDCODSUBAPU integer,
    WBDCODAJU integer,
    WBDCODNAT integer,
    WBDVARIASCFOPS integer,
    WBDCODCSTICMS integer,
    WBDVARIOSNCMS integer,
    WPLANO integer,
    WBDCHAVE integer,
    WBDVLRAJU integer,
    WBDDESCCOMP varchar(255))
as
declare variable WSQL varchar(5000);
begin

      wSQL = ' INSERT INTO TMP_VEF_EMP_TMOVAJU1921_PL_TEMP  (BDSESSAO,BDCODEMP,BDTIPOLAN,BDCODSUBAPU,BDORDEM1921,BDCHAVE,BDREFERENCIA,BDCODAJUICMS,BDCODTIPO,BDDESCCOMP,BDVALOR,bdvlraju) ';
      wSQL = wSQL ||'select '||:PRSESSAO||' BDSESSAO, M.BDCODEMP,3,'||wBDCODSUBAPU||',/*'||'GETORDEMSEQUENCIAL(M.BDCODEMP)'||'*/M.BDCHAVE,M.BDCHAVE,'||:PRREF||', '||wbdcodaju||', 141 BDCODTIPO, '''||wbddesccomp||''' , M.bdvalor, '||:wbdvlraju;
      wSQL = wSQL ||' FROM ( ';
      wSQL = wSQL ||'        select M.BDCODEMP,M.BDCHAVE,M.BDREFLAN , Sum(coalesce(P.BDICMSEFETIVO, 0)) bdvalor';
      wSQL = wSQL ||'        from ( ';
      wSQL = wSQL ||'              select M.BDCODEMP, M.BDCHAVE, M.BDORDEMDOCECF BDORDEM,m.bdREFLAN ';
      wSQL = wSQL ||'              from ( ';
      wSQL = wSQL ||'                    select M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, DOC.BDORDEMDOCECF ';
      wSQL = wSQL ||'                    from VEF_EMP_TREDZ M ';
      wSQL = wSQL ||'                    left outer join VEF_EMP_TDOCECF DOC ON (DOC.BDCODEMP = M.BDCODEMP AND DOC.BDCHAVE = M.BDCHAVE)';
      wSQL = wSQL ||'                            where m.bdcodemp = '||:PRCODEMP;
      wSQL = wSQL ||'                            and m.bdreflan = '||:PRREF;
      wSQL = wSQL ||'                            and DOC.BDCODSITNF NOT IN (2, 3, 4, 5) ';
      wSQL = wSQL ||'                   ) M ';
      wSQL = wSQL ||'              join VEF_EMP_TITEMDOCECF I on (M.BDCODEMP = I.BDCODEMP and M.BDCHAVE = I.BDCHAVE AND M.BDORDEMDOCECF = I.BDORDEMDOCECF) ';
      if ((wbdcodnat is not null)  and (wbdcodnat > 0))then
        wSQL = wSQL ||'            WHERE i.bdcodnat = '||:wbdcodnat ;
      else
        if ((wbdVariasCFOPs is not null) or (wbdVariasCFOPs > 0)) then
          wSQL = wSQL ||'          WHERE exists (select f.bdcodnat from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodnat = i.bdcodnat) ';
      wSQL = wSQL ||'            ) M ';
      wSQL = wSQL ||'        left outer join VEF_EMP_TITEMDOCECF P on (M.BDCODEMP = P.BDCODEMP and M.BDCHAVE = P.BDCHAVE and M.BDORDEM = P.BDORDEMDOCECF) ';
      if ((wbdcodcsticms is not null)  and (wbdcodcsticms > 0))then
        wSQL = wSQL ||'      where p.bdcodcsticms = '||:wbdcodcsticms ;
      else
        if ((wBDVARIOSNCMS is not null) or (wBDVARIOSNCMS > 0)) then
          wSQL = wSQL ||'      where exists (select f.bdcodcsticms from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodcsticms = p.bdcodcsticms) ';
      wSQL = wSQL ||'        GROUP by  M.BDCODEMP,M.BDCHAVE,M.BDREFLAN ';
      wSQL = wSQL ||'     )M ';
      wSQL = wSQL ||'    where bdvalor > 0 ' ;
    
      execute statement wsql;
    
      SETORDEMSEQUENCIAL_STR(:prCODEMP);
      wSQL = ' INSERT INTO TMP_VEF_EMP_TMOVAJU1923_PL_TEMP (BDSESSAO,BDCODEMP,BDTIPOLAN,BDCODSUBAPU,BDORDEM1921,BDORDEM1923,BDCODTER, ';
      wSQL = wSQL ||'                                      BDCODDOCFIS,BDSERIE,BDSUBSERIE,BDNUMDOC,BDDTDOC,BDCODPROD,BDCHAVENFE,BDVALOR,BDQTDPROD,BDCODAJUICMS,bdvlraju) ';
      wSQL = wSQL ||'select M.BDSESSAO, M.BDCODEMP,3,M.BDCODSUBAPU,M.BDORDEM1921,GETORDEMSEQUENCIAL_STR(M.BDCODEMP||''.''||M.BDORDEM1921, '||:prCODEMP||')'||',M.BDCODTER,';
      wSQL = wSQL ||' 1 bdmodelo,SUBSTRING(m.bdserie from 1 FOR 4) bdserie,SUBSTRING(m.bdsubserie from 1 FOR 3) bdsubserie,m.bdnumdocini,m.bddataemissao,M.bdcodprod, '''' bdchavenfe ,M.bdvalor,m.BDQTDITEM , ' ||wbdcodaju||','||wbdvlraju;
      wSQL = wSQL ||' FROM ( ';
      wSQL = wSQL ||'        select '||:PRSESSAO||' BDSESSAO, M.BDCODEMP,'||wBDCODSUBAPU||' BDCODSUBAPU,M.BDCHAVE BDORDEM1921, 0 BDORDEM1923, M.BDCODTER,';
      wSQL = wSQL ||'        M.BDSERIE, M.BDSUBSERIE, M.BDNUMDOCINI, M.BDDATAEMISSAO, M.BDQTDITEM, M.BDCODPROD,coalesce(M.BDICMSEFETIVO, 0) BDVALOR ';
      wSQL = wSQL ||'        from ( ';
      wSQL = wSQL ||'              SELECT M.BDCODEMP, M.BDCHAVE, M.BDORDEMDOCECF BDORDEM, M.BDDATAEMISSAO, M.BDNUMDOCINI, M.BDSERIE,M.BDSUBSERIE, M.BDCODTER, I.BDQTDITEM,I.BDCODPROD,I.BDICMSEFETIVO ';
      wSQL = wSQL ||'              from ( ';
      wSQL = wSQL ||'                    select M.BDCODEMP, M.BDCHAVE, M.BDREFLAN,DOC.BDORDEMDOCECF, DOC.BDDATAEMI BDDATAEMISSAO,DOC.BDNUMDOCCOO BDNUMDOCINI, ''2D'' BDSERIE, ';
      wSQL = wSQL ||'                    '''' BDSUBSERIE, MIN(COALESCE(TER.BDCODTER, DOC.BDCODTER)) BDCODTER ';
      wSQL = wSQL ||'                    from VEF_EMP_TREDZ M ';
      wSQL = wSQL ||'                    left outer join VEF_EMP_TDOCECF DOC ON (DOC.BDCODEMP = M.BDCODEMP AND DOC.BDCHAVE = M.BDCHAVE)';
      wSQL = wSQL ||'                    left outer join TEMPRESAS EMP ON (EMP.BDCODEMP = M.BDCODEMP)';
      wSQL = wSQL ||'                    left outer join VW_TTERCEIRO TER ON (TER.BDCGCTER = EMP.BDCNPJEMP)';
      wSQL = wSQL ||'                    where m.bdcodemp = '||:PRCODEMP;
      wSQL = wSQL ||'                    and m.bdreflan = '||:PRREF;
      wSQL = wSQL ||'                    and DOC.BDCODSITNF NOT IN (2, 3, 4, 5) ';
      wSQL = wSQL ||'                    group by M.BDCODEMP, M.BDCHAVE, M.BDREFLAN,DOC.BDORDEMDOCECF,BDDATAEMISSAO,BDNUMDOCINI, BDSERIE, BDSUBSERIE';
      wSQL = wSQL ||'                   ) M ';
      wSQL = wSQL ||'              join VEF_EMP_TITEMDOCECF I on (M.BDCODEMP = I.BDCODEMP and M.BDCHAVE = I.BDCHAVE AND M.BDORDEMDOCECF = I.BDORDEMDOCECF) ';
      if ((wbdcodnat is not null)  and (wbdcodnat > 0))then
        wSQL = wSQL ||'            WHERE i.bdcodnat = '||:wbdcodnat ;
      else
        if ((wbdVariasCFOPs is not null) or (wbdVariasCFOPs > 0)) then
          wSQL = wSQL ||'          WHERE exists (select f.bdcodnat from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodnat = i.bdcodnat) ';
      if ((wbdcodcsticms is not null)  and (wbdcodcsticms > 0))then
        wSQL = wSQL ||'      AND I.bdcodcsticms = '||:wbdcodcsticms ;
      else
        if ((wBDVARIOSNCMS is not null) or (wBDVARIOSNCMS > 0)) then
          wSQL = wSQL ||'      AND exists (select f.bdcodcsticms from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodcsticms = i.bdcodcsticms) ';
      wSQL = wSQL ||'    ) M )M ';
      wSQL = wSQL ||'    where bdvalor > 0 ' ;
    
      execute statement wsql;

  INSERT INTO TOL_VEF_EMP_TMOVREDZAJU1921_TMP (BDSESSAO,BDCODEMP,BDCHAVE,BDORDEM1921,BDCODPERIODO,BDREFERENCIA,BDCODAJUICMS,bdordem1923,bdvlraju)
  SELECT :prsessao, T.BDCODEMP,T.BDORDEM1921,0,7,BDREFERENCIA,:wbdcodaju,pl.bdordem1923,:wbdvlraju
  FROM TMP_VEF_EMP_TMOVAJU1921_PL_TEMP T
  LEFT OUTER JOIN TMP_VEF_EMP_TMOVAJU1923_PL_TEMP PL ON  (T.bdsessao = PL.BDSESSAO AND T.BDCODEMP = PL.BDCODEMP AND T.BDORDEM1921 = PL.BDORDEM1921 and t.bdcodajuicms = pl.bdcodajuicms and t.bdvlraju = pl.bdvlraju)
  where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp AND T.BDTIPOLAN = 3 and t.bdvlraju = :wbdvlraju
  and not exists (select a.bdcodemp from TOL_VEF_EMP_TMOVREDZAJU1921_TMP  a  where a.bdsessao = :prsessao and a.bdcodemp = t.bdcodemp and a.bdchave = t.bdordem1921 and a.BDORDEM1923 = pl.BDORDEM1923 and a.bdcodajuicms = pl.bdcodajuicms and a.bdvlraju = pl.bdvlraju);

end^


create or alter procedure SP_APLICA_PLANO_1900 (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer)
as
declare variable WPLANO integer;
declare variable WBDCODSUBAPU integer;
declare variable WBDTIPOMOV integer;
declare variable WBDMODELO varchar(2);
declare variable WBDCONSUFINAL integer;
declare variable WBDCODAJU integer;
declare variable WBDDESCCOMP varchar(255);
declare variable WBDVLRAJU integer;
declare variable WBDCODCSTICMS integer;
declare variable WBDCODNAT integer;
declare variable WBDCHAVE integer;
declare variable WBDVARIOSNCMS integer;
declare variable WBDVARIASCFOPS integer;
declare variable WSQL varchar(5000);
declare variable WCAMPOVALOR varchar(1000);
declare variable WCAMPOVALOR1921 varchar(1000);
declare variable WALIQINTERNAUF DM_NUMERIC_7_4_ALIQ;
declare variable WTIPOEMP integer;
declare variable WMAXENT integer;
declare variable WMAXSAI integer;
declare variable WMINENT integer;
declare variable WMINSAI integer;
declare variable WCONSOLIDA1923 DM_BOOLEAN;
BEGIN
  execute procedure sp_seta_competencia(:prref);

  select u.bdaliqint from VW_TEMPRESAS_REF e
  left outer join tcidade c on (c.bdcodcid = e.bdcodcid)
  left outer join tuf u on (c.bdcoduf = u.bdcoduf)
  where e.bdcodemp = :prcodemp and e.bdrefemp <= :prref
  into :wAliqInternaUF;

  if (waliqinternauf is null) then
    waliqinternauf = 0;

  DELETE FROM TMP_VEF_EMP_TMOVAJU1921_PL_TEMP T where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;
  DELETE FROM TOL_VEF_EMP_TMOVSAIAJU1921_TEMP T where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;
  DELETE FROM TOL_VEF_EMP_TMOVENTAJU1921_TEMP T where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;
  DELETE FROM TOL_VEF_EMP_TMOVREDZAJU1921_TMP T where t.BDSESSAO = :PRSESSAO and t.BDCODEMP = :PRCODEMP;

  SETORDEMSEQUENCIAL(0);

  ---PEGA O PLANO
  FOR  select first 1 ci.BDPLANCONF1900,ci.BDCODSUBAPU,ci.BDCONS1923 from VEF_INT_TSPEDICMS c
       left outer join VEF_INT_TSPEDICMSCONF1900 ci on (c.bdcodemp = ci.bdcodemp and c.bdcodigo = ci.bdcodigo)
       where c.bdcodemp = :PRCODEMP  and c.bdreferencia <= :PRREF ORDER BY C.BDCODEMP,C.BDREFERENCIA DESC into wplano,wBDCODSUBAPU,wConsolida1923
  DO
    begin
      rdb$set_context('USER_SESSION', 'W_CONSOLIDA1923', :wConsolida1923);

      select Max(M.BDCHAVE) bdmax , min(m.bdchave) bdmin from VEF_EMP_TMOVENT M where M.BDCODEMP = :prcodemp and m.bdreflan = :prref into wmaxent,wminEnt;
      select Max(M.BDCHAVE) bdmax , min(m.bdchave) bdmin from VEF_EMP_TMOVSAI M where M.BDCODEMP = :prcodemp and m.bdreflan = :prref into wmaxSai,wminSai;

      FOR select  a.bdchave,a.bdtipomov, d.bddocfis bdmodelo, a.bdconsufinal,a.bdcodcsticms,a.bdcodnat , a.bdcodaju, a.bddesccomp, a.bdvlraju,
          (select first 1 v.bdcodnat FROM VEF_BASE_TVINCCODPLANO1900 v where a.bdcodplanconf1900 = v.bdcodplanconf1900 and a.bdchave = v.bdchave ) bdVariasCFOPs,
          (select first 1 v.bdcodcsticms FROM VEF_BASE_TVINCCODPLANO1900 v where a.bdcodplanconf1900 = v.bdcodplanconf1900 and a.bdchave = v.bdchave ) BDVARIOSNCMS,
          p.BDTIPOEMP
          from VEF_BASE_TPLANOACOESCONF1900 a
          left outer join vef_base_tplaconf1900 p on (a.bdcodplanconf1900 = p.bdcodplanconf1900)
          left outer join vef_base_ttabdocfis d on (a.bdmodelo = d.bdcoddocfis)
          where a.bdcodplanconf1900 = :wplano
          order by a.bdcodplanconf1900,a.bdtipomov desc
--          order by a.bdcodplanconf1900,A.bdchave
          --order by a.bdqtdfiltro
          into wbdchave,wbdtipomov, wbdmodelo, wbdconsufinal,wbdcodcsticms,wbdcodnat,/*a  es*/ wbdcodaju, wbddesccomp, wbdvlraju,wbdvariascfops,wbdvariosncms,wTipoEmp
      DO
        begin
        --Movimento
        --0 - Entrada
        --1 - Sa da
        --2 - Apuração 1921
        --3 - Apuração E220
        --4 - Invent rio
    
        --tipo valor ajuste
        --(1, 'ICMS Efetivo')
        --(2, 'ICMS Presumido')
        --(3, 'ICMS Invent rio')
        --(4, 'ICMS a pagar')
        --(5, 'ICMS a recuperar')
        --(6, 'ICMS PRESUMIDO - ESTORNO')
        --(7, 'ICMS EFETIVO - ESTORNO')

          if (:WBDMODELO = '1B' ) then
            wbdmodelo = '100';
          else
          if (:WBDMODELO = '2D' ) then
            wbdmodelo = '200';
          else
          if (:WBDMODELO = '2E' ) then
            wbdmodelo = '201';
          else
          if (:WBDMODELO = '8B' ) then
            wbdmodelo = '800';
          else
          if (:WBDMODELO = '3A' ) then
            wbdmodelo = '801';
          else
          if (:WBDMODELO = '3B' ) then
            wbdmodelo = '802';

          --Entrada
          if (wbdtipomov = 0) then
            begin
              WCAMPOVALOR1921 = '';
              if (wbdvlraju in(1,6,7)) then
                begin
                  wCampoValor  = 'sum(coalesce(p.BDVLRICMSEFET,0))';
                  wCAMPOVALOR1921 = 'coalesce(p.BDVLRICMSEFET,0)';
                end
              if (wbdvlraju = 2) then           --PEGAR A Base st  x aliquota do estado em questão
                begin
--                  wCampoValor    = '(SUM(iif(coalesce(p.BDBCST,0)>0,p.BDBCST,IIF(coalesce(p.BDBCFCPRETIDO,0)>0,p.BDBCFCPRETIDO,IIF(coalesce(p.BDBCICMSSTRET,0)>0,p.BDBCICMSSTRET,coalesce(p.BDBCFCPSTRET,0))))) * '||:waliqinternauf||') / 100';
--                  wCAMPOVALOR1921 = '((iif(coalesce(p.BDBCST,0)>0,p.BDBCST,IIF(coalesce(p.BDBCFCPRETIDO,0)>0,p.BDBCFCPRETIDO,IIF(coalesce(p.BDBCICMSSTRET,0)>0,p.BDBCICMSSTRET,coalesce(p.BDBCFCPSTRET,0))))* '||:waliqinternauf||') / 100'||')';
                  wCampoValor     = '(SUM(iif(coalesce(p.BDBCST,0)>0,p.BDBCST,IIF(coalesce(p.BDBCFCPRETIDO,0)>0,p.BDBCFCPRETIDO,IIF(coalesce(p.BDBCICMSSTRET,0)>0,p.BDBCICMSSTRET,IIF(coalesce(p.BDBCFCPSTRET,0)>0,p.BDBCFCPSTRET,    ';
                  wCampoValor     = wCampoValor || ' iif(coalesce(po.BDBCST,0)>0,po.BDBCST,IIF(coalesce(po.BDBCFCPRETIDO,0)>0,po.BDBCFCPRETIDO,IIF(coalesce(po.BDBCICMSSTRET,0)>0,po.BDBCICMSSTRET,coalesce(po.BDBCFCPSTRET,0))))/*normal*/ ))))';
                  wCampoValor     = wCampoValor || ' ) * '||:waliqinternauf||') / 100';
                  wCAMPOVALOR1921 = '((iif(coalesce(p.BDBCST,0)>0,p.BDBCST,IIF(coalesce(p.BDBCFCPRETIDO,0)>0,p.BDBCFCPRETIDO,IIF(coalesce(p.BDBCICMSSTRET,0)>0,p.BDBCICMSSTRET,IIF(coalesce(p.BDBCFCPSTRET,0)>0,coalesce(p.BDBCFCPSTRET,0),   ';
                  wCAMPOVALOR1921 = wCAMPOVALOR1921 || '  iif(coalesce(po.BDBCST,0)>0,po.BDBCST,IIF(coalesce(po.BDBCFCPRETIDO,0)>0,po.BDBCFCPRETIDO,IIF(coalesce(po.BDBCICMSSTRET,0)>0,po.BDBCICMSSTRET,coalesce(po.BDBCFCPSTRET,0)))) /*normal*/ )))';
                  wCAMPOVALOR1921 = wCAMPOVALOR1921 || ')* '||:waliqinternauf||') / 100'||')';
                end
                --BDBCST,BDBCICMSEFET,BDBCICMSSTRET,BDBCFCPSTRET,
--              if (wbdvlraju = 6) then
--                wCampoValor  = 'coalesce(bdfcpretido,0) ';
              if (wbdvlraju = 7) then
                begin
                  wCampoValor  = 'sum(coalesce(p.BDVLRICMSEFET,0))';
                  wCAMPOVALOR1921 = 'coalesce(p.BDVLRICMSEFET,0)';
                end

               -- VAREJISTA          NÃO VAREJISTA
              if (((wtipoemp = 0) AND (wbdvlraju <> 2) ) or ((wtipoemp = 1) AND (wbdvlraju IN(1,6)))) then
                begin
                  --SETORDEMSEQUENCIAL(0);
                  wSQL = ' INSERT INTO TMP_VEF_EMP_TMOVAJU1921_PL_TEMP  (BDSESSAO,BDCODEMP,BDTIPOLAN,BDCODSUBAPU,BDORDEM1921,BDCHAVE,BDREFERENCIA,BDCODAJUICMS,BDCODTIPO,BDDESCCOMP,BDVALOR,bdvlraju) ';
        
                  wSQL = wSQL ||' select '||:PRSESSAO||' BDSESSAO, M.BDCODEMP,0,'||wBDCODSUBAPU||',M.BDCHAVE,M.BDCHAVE,'||:PRREF||', '||wbdcodaju||', 141 BDCODTIPO, '''||wbddesccomp||''' , BDVALOR, '||:wbdvlraju;
                  wSQL = wSQL ||' FROM ( ';
                  wSQL = wSQL ||'        select M.BDCODEMP,M.BDCHAVE,M.BDREFLAN , '||:wCampoValor||' bdVALOR ';
                  wSQL = wSQL ||'        from ( ';
                  wSQL = wSQL ||'              select M.BDCODEMP, M.BDCHAVE, I.BDORDEM,m.bdREFLAN ';
                  wSQL = wSQL ||'              from ( ';
                  wSQL = wSQL ||'                    select M.BDCODEMP, M.BDCHAVE, M.BDREFLAN ';
                  wSQL = wSQL ||'                    from VEF_EMP_TMOVENT M ';
                  wSQL = wSQL ||'                            where m.bdcodemp = '||:PRCODEMP;
                  wSQL = wSQL ||'                            and m.bdreflan = '||:PRREF;
                  wSQL = wSQL ||'                            and M.BDCODSITNF NOT IN (2, 3, 4, 5) ';
                  if ((:wbdmodelo is not null)  and (:wbdmodelo > '0')) then
                    wSQL = wSQL ||'                          and m.bdmodelo = '|| :wbdmodelo;
                  if ((wbdconsufinal is not null)  and (wbdconsufinal > -1)) then
                    wSQL = wSQL ||'                          and m.bdconsufinal = '|| :wbdconsufinal;
                  wSQL = wSQL ||'                   ) M ';
                  wSQL = wSQL ||'              join VEF_EMP_TMOVENTITENS I on (M.BDCODEMP = I.BDCODEMP and M.BDCHAVE = I.BDCHAVE) ';

                  if ((wbdcodnat is not null)  and (wbdcodnat > 0))then
                    wSQL = wSQL ||'            WHERE i.bdcodnat = '||:wbdcodnat ;
                  else
                    if ((wbdVariasCFOPs is not null) or (wbdVariasCFOPs > 0)) then
                      wSQL = wSQL ||'          WHERE exists (select f.bdcodnat from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodnat = i.bdcodnat) ';
                  wSQL = wSQL ||'        ) M ';
                  wSQL = wSQL ||'        left outer join VEF_EMP_TMOVPROENT P on (M.BDCODEMP = P.BDCODEMP and M.BDCHAVE = P.BDCHAVE and M.BDORDEM = P.BDORDEM) ';
                  wSQL = wSQL ||'        left outer join ( ';
                  wSQL = wSQL ||'                         select o.bdcodemp,o.bdchave, o.bdcodprod, sum(BDBCST) BDBCST, sum(BDBCFCPRETIDO) BDBCFCPRETIDO , sum(BDBCICMSSTRET) BDBCICMSSTRET,  sum(BDBCFCPSTRET) BDBCFCPSTRET ';
                  wSQL = wSQL ||'                         from vef_emp_tmovproentimpori o ';
                  wSQL = wSQL ||'                         where o.bdcodemp = '||:PRCODEMP;
                  wSQL = wSQL ||'                         and o.bdchave between '||Coalesce(:wminEnt,0)||' and ' ||Coalesce(:wMaxent,0);
                  wSQL = wSQL ||'                         group by o.bdcodemp,o.bdchave,o.bdcodprod ';
                  wSQL = wSQL ||'                         ) PO on (M.BDCODEMP = PO.BDCODEMP and M.BDCHAVE = PO.BDCHAVE and P.bdcodprod = PO.bdcodprod) ';

                  if ((wbdcodcsticms is not null)  and (wbdcodcsticms > 0))then
                    wSQL = wSQL ||'      where p.bdcodcsticms = '||:wbdcodcsticms ;
                  else
                    if ((wBDVARIOSNCMS is not null) or (wBDVARIOSNCMS > 0)) then
                      wSQL = wSQL ||'      where exists (select f.bdcodcsticms from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodcsticms = p.bdcodcsticms) ';
        
                  wSQL = wSQL ||'        GROUP by  M.BDCODEMP,M.BDCHAVE,M.BDREFLAN ';
                  wSQL = wSQL ||'     )M ';
    
                  wSQL = wSQL ||'    where bdvalor > 0 ' ;
        
                  execute statement wsql;
    
                  --SETORDEMSEQUENCIAL(0);
                  SETORDEMSEQUENCIAL_STR(:prCODEMP);
        
                  wSQL = ' INSERT INTO TMP_VEF_EMP_TMOVAJU1923_PL_TEMP  (BDSESSAO,BDCODEMP,BDTIPOLAN,BDCODSUBAPU,BDORDEM1921,BDORDEM1923,BDCODTER, ';
                  wSQL = wSQL ||'                                     BDCODDOCFIS,BDSERIE,BDSUBSERIE,BDNUMDOC,BDDTDOC,BDCODPROD,BDCHAVENFE,BDVALOR,BDCODAJUICMS,bdvlraju) ';
        
                  wSQL = wSQL ||'select M.BDSESSAO, M.BDCODEMP,0,M.BDCODSUBAPU,M.BDORDEM1921,GETORDEMSEQUENCIAL_STR(M.BDCODEMP||''.''||M.BDORDEM1921, '||:prCODEMP||')'||',M.BDCODTER, M.bdmodelo,SUBSTRING(m.bdserie from 1 FOR 4) bdserie,SUBSTRING(m.bdsubserie from 1 FOR 3) bdsubserie,m.bdnumdocini,m.BDDATAENTRADAENT, M.bdcodprod,m.bdchavenfe ,M.BDVALOR, ' ||wbdcodaju||','||wbdvlraju ;
                  wSQL = wSQL ||' FROM ( ';
                  wSQL = wSQL ||'  select '||:PRSESSAO||' BDSESSAO, M.BDCODEMP,'||wBDCODSUBAPU||' BDCODSUBAPU,'||'M.BDCHAVE'||' BDORDEM1921,'||'0 BDORDEM1923,M.BDCODTER, M.bdmodelo,m.bdserie,m.bdsubserie,m.bdnumdocini,m.BDDATAENTRADAENT, p.bdcodprod,m.bdchavenfe ,'||iif(wCAMPOVALOR1921<>'',wCAMPOVALOR1921,wCampoValor) ||' BDVALOR';
                  wSQL = wSQL ||'  from ( ';
                  wSQL = wSQL ||'      select M.BDCODEMP, M.BDCHAVE, I.BDORDEM,m.bdchavenfe,m.BDDATAENTRADAENT,m.bdnumdocini,m.bdserie,m.bdsubserie,M.BDCODTER,M.BDMODELO ';
                  wSQL = wSQL ||'      from ( ';
                  wSQL = wSQL ||'            select M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, M.BDMODELO, M.BDCONSUFINAL,m.bdchavenfe,m.BDDATAENTRADAENT,m.bdnumdocini,m.bdserie,m.bdsubserie,M.BDCODTER ';
                  wSQL = wSQL ||'            from VEF_EMP_TMOVENT M ';
                  wSQL = wSQL ||'                            where m.bdcodemp = '||:PRCODEMP;
                  wSQL = wSQL ||'                            and m.bdreflan = '||:PRREF;
                  wSQL = wSQL ||'                            and M.BDCODSITNF NOT IN (2, 3, 4, 5) ';
                  if ((:wbdmodelo is not null)  and (:wbdmodelo > '0')) then
                    wSQL = wSQL ||'                          and m.bdmodelo = '|| :wbdmodelo;
                  if ((wbdconsufinal is not null)  and (wbdconsufinal > -1)) then
                    wSQL = wSQL ||'                          and m.bdconsufinal = '|| :wbdconsufinal;
                  wSQL = wSQL ||'           ) M ';
                  wSQL = wSQL ||'      join VEF_EMP_TMOVENTITENS I on (M.BDCODEMP = I.BDCODEMP and M.BDCHAVE = I.BDCHAVE) ';
--                  wSQL = wSQL ||'      where not exists (select t.bdcodemp from TMP_VEF_EMP_TMOVAJU1923_PL_TEMP t ';
--                  wSQL = wSQL ||'                        left OUTER JOIN TOL_VEF_EMP_TMOVENTAJU1921_TEMP TL ON (TL.bdsessao = T.bdsessao AND TL.bdcodemp = T.bdcodemp AND TL.bdchave = T.bdordem1921) ';
--                  wSQL = wSQL ||'                        where t.bdsessao = '||:prsessao ||' and t.bdcodemp = m.bdcodemp and t.bdordem1921 = m.bdchave AND TL.BDCODEMP IS NULL)';
    
                  if ((wbdcodnat is not null)  and (wbdcodnat > 0))then
                    wSQL = wSQL ||'            WHERE i.bdcodnat = '||:wbdcodnat ;
                  else
                    if ((wbdVariasCFOPs is not null) or (wbdVariasCFOPs > 0)) then
                      wSQL = wSQL ||'           WHERE exists (select f.bdcodnat from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodnat = i.bdcodnat) ';
                  wSQL = wSQL ||'        ) M ';
                  wSQL = wSQL ||'left outer join VEF_EMP_TMOVPROENT P on (M.BDCODEMP = P.BDCODEMP and M.BDCHAVE = P.BDCHAVE and M.BDORDEM = P.BDORDEM) ';
                  wSQL = wSQL ||'left outer join ( ';
                  wSQL = wSQL ||'                 select o.bdcodemp,o.bdchave, o.bdcodprod, sum(BDBCST) BDBCST, sum(BDBCFCPRETIDO) BDBCFCPRETIDO , sum(BDBCICMSSTRET) BDBCICMSSTRET,  sum(BDBCFCPSTRET) BDBCFCPSTRET ';
                  wSQL = wSQL ||'                 from vef_emp_tmovproentimpori o ';
                  wSQL = wSQL ||'                 where o.bdcodemp = '||:PRCODEMP;
                  wSQL = wSQL ||'                 and o.bdchave between '||Coalesce(:wminEnt,0)||' and ' ||Coalesce(:wMaxent,0);
                  wSQL = wSQL ||'                 group by o.bdcodemp,o.bdchave,o.bdcodprod ';
                  wSQL = wSQL ||'                ) PO on (M.BDCODEMP = PO.BDCODEMP and M.BDCHAVE = PO.BDCHAVE and P.bdcodprod = PO.bdcodprod) ';
    --
                  if ((wbdcodcsticms is not null)  and (wbdcodcsticms > 0))then
                    wSQL = wSQL ||'      where p.bdcodcsticms = '||:wbdcodcsticms ;
                  else
                    if ((wBDVARIOSNCMS is not null) or (wBDVARIOSNCMS > 0)) then
                      wSQL = wSQL ||'      where exists (select f.bdcodcsticms from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodcsticms = p.bdcodcsticms) ';
        
                  wSQL = wSQL ||') M ';
                  wSQL = wSQL ||'    where bdvalor > 0 ' ;
         
                   execute statement wsql;
              
    --              --CAMPO BDORDEM1921 TEM A CHAVE DO LANÇAMENTO DE ENTRADA
                  INSERT INTO TOL_VEF_EMP_TMOVENTAJU1921_TEMP (BDSESSAO,BDCODEMP,BDCHAVE,BDORDEM1921,BDCODPERIODO,BDREFERENCIA,BDCODAJUICMS,bdordem1923,bdvlraju)
                  SELECT :prsessao, T.BDCODEMP,T.BDORDEM1921,0,7,BDREFERENCIA,:wbdcodaju,pl.bdordem1923,:wbdvlraju
                  FROM TMP_VEF_EMP_TMOVAJU1921_PL_TEMP T
                  LEFT OUTER JOIN TMP_VEF_EMP_TMOVAJU1923_PL_TEMP PL ON  (T.bdsessao = PL.BDSESSAO AND T.BDCODEMP = PL.BDCODEMP and t.bdtipolan = pl.bdtipolan AND T.BDORDEM1921 = PL.BDORDEM1921 and t.bdcodajuicms = pl.bdcodajuicms and t.bdvlraju = pl.bdvlraju)
                  where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp AND T.BDTIPOLAN = 0 and t.bdvlraju = :wbdvlraju
                  and not exists (select a.bdcodemp from TOL_VEF_EMP_TMOVENTAJU1921_TEMP a  where a.bdsessao = :prsessao and a.bdcodemp = t.bdcodemp and a.bdchave = t.bdordem1921 and a.BDORDEM1923 = pl.BDORDEM1923 and a.bdcodajuicms = pl.bdcodajuicms and a.bdvlraju = pl.bdvlraju);

               end
             else
               begin
                 if (((wtipoemp = 0) AND (wbdvlraju = 2) )) then
                    begin

                      wSQL = ' INSERT INTO TMP_VEF_EMP_TMOVAJU1921_PL_TEMP  (BDSESSAO,BDCODEMP,BDTIPOLAN,BDCODSUBAPU,BDORDEM1921,BDCHAVE,BDREFERENCIA,BDCODAJUICMS,BDCODTIPO,BDDESCCOMP,BDVALOR,bdvlraju) ';
                      wSQL = wSQL ||' select '||:PRSESSAO||' BDSESSAO, M.BDCODEMP,0,'||wBDCODSUBAPU||',M.BDCHAVE,M.BDCHAVE,'||:PRREF||', '||wbdcodaju||', 141 BDCODTIPO, '''||wbddesccomp||''' , BDVALOR, '||:wbdvlraju;
                      wSQL = wSQL ||' FROM ( ';
                      wSQL = wSQL ||'       select M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, ';
                      wSQL = wSQL ||'              (sum(iif(coalesce(M.BDBCST, 0) > 0, M.BDBCST, iif(coalesce(M.BDBCFCPRETIDO, 0) > 0, M.BDBCFCPRETIDO, iif(coalesce(M.BDBCICMSSTRET, 0) > 0, M.BDBCICMSSTRET, iif(coalesce(M.BDBCFCPSTRET, 0) > 0, M.BDBCFCPSTRET, iif(coalesce(M.BDBCSTPO, 0) > 0, M.BDBCSTPO, iif(coalesce(M.BDBCFCPRETIDOPO, 0) > 0, M.BDBCFCPRETIDOPO, iif(coalesce(M.BDBCICMSSTRETPO, 0) > 0, M.BDBCICMSSTRETPO, coalesce(M.BDBCFCPSTRETPO, 0)))) /*normal*/ )))) * bdaliquota)) / 100 BDVALOR ';
                      wSQL = wSQL ||'       from ( ';
                      wSQL = wSQL ||'             select M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, P.BDBCST,P.BDBCFCPRETIDO,P.BDBCICMSSTRET,P.BDBCFCPSTRET,PO.BDBCST BDBCSTPO,PO.BDBCFCPRETIDO BDBCFCPRETIDOPO,PO.BDBCICMSSTRET BDBCICMSSTRETPO,PO.BDBCFCPSTRET BDBCFCPSTRETPO , ';
                      wSQL = wSQL ||'                   (iif(/*aliquota lancamento produto > 0*/ iif(coalesce(P.BDBCST, 0) > 0, P.BDALIQST, iif(coalesce(P.BDBCFCPRETIDO, 0) > 0, P.BDALIQFCPRETIDO, iif(coalesce(P.BDBCICMSSTRET, 0) > 0, P.BDALIQIMCSSTRET, iif(coalesce(P.BDBCFCPSTRET, 0) > 0, P.BDALIQFCPSTRET,0 /*normal*/ )))) > 0, ';
                      wSQL = wSQL ||'                   /*pegar a sequencia acima*/ iif(coalesce(P.BDBCST, 0) > 0, P.BDALIQST, iif(coalesce(P.BDBCFCPRETIDO, 0) > 0, P.BDALIQFCPRETIDO, iif(coalesce(P.BDBCICMSSTRET, 0) > 0, P.BDALIQIMCSSTRET, iif(coalesce(P.BDBCFCPSTRET, 0) > 0, P.BDALIQFCPSTRET,0 /*normal*/ )))), ';
                      wSQL = wSQL ||'                      iif(iif(coalesce(P.BDBCST, 0) > 0, CP.BDALIQICMSST, iif(coalesce(P.BDBCFCPRETIDO, 0) > 0, 0, iif(coalesce(P.BDBCICMSSTRET, 0) > 0, CP.BDALIQICMSSTRET, iif(coalesce(P.BDBCFCPSTRET, 0) > 0, 0, 0 /*normal*/ )))) > 0, ';
                      wSQL = wSQL ||'                    iif(coalesce(P.BDBCST, 0) > 0, CP.BDALIQICMSST, iif(coalesce(P.BDBCFCPRETIDO, 0) > 0, 0, iif(coalesce(P.BDBCICMSSTRET, 0) > 0, CP.BDALIQICMSSTRET, iif(coalesce(P.BDBCFCPSTRET, 0) > 0, 0, 0 /*normal*/ )))), '||:waliqinternauf||') ';
                      wSQL = wSQL ||'                       )) BDALIQUOTA ';
                      wSQL = wSQL ||'               from ( ';
                      wSQL = wSQL ||'              select M.BDCODEMP, M.BDCHAVE, I.BDORDEM,m.bdREFLAN ';
                      wSQL = wSQL ||'              from ( ';
                      wSQL = wSQL ||'                    select M.BDCODEMP, M.BDCHAVE, M.BDREFLAN ';
                      wSQL = wSQL ||'                    from VEF_EMP_TMOVENT M ';
                      wSQL = wSQL ||'                            where m.bdcodemp = '||:PRCODEMP;
                      wSQL = wSQL ||'                            and m.bdreflan = '||:PRREF;
                      wSQL = wSQL ||'                            and M.BDCODSITNF NOT IN (2, 3, 4, 5) ';
                      if ((:wbdmodelo is not null)  and (:wbdmodelo > '0')) then
                        wSQL = wSQL ||'                          and m.bdmodelo = '|| :wbdmodelo;
                      if ((wbdconsufinal is not null)  and (wbdconsufinal > -1)) then
                        wSQL = wSQL ||'                          and m.bdconsufinal = '|| :wbdconsufinal;
                      wSQL = wSQL ||'                   ) M ';
                      wSQL = wSQL ||'              join VEF_EMP_TMOVENTITENS I on (M.BDCODEMP = I.BDCODEMP and M.BDCHAVE = I.BDCHAVE) ';
    
                      if ((wbdcodnat is not null)  and (wbdcodnat > 0))then
                        wSQL = wSQL ||'            WHERE i.bdcodnat = '||:wbdcodnat ;
                      else
                        if ((wbdVariasCFOPs is not null) or (wbdVariasCFOPs > 0)) then
                          wSQL = wSQL ||'          WHERE exists (select f.bdcodnat from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodnat = i.bdcodnat) ';
                      wSQL = wSQL ||'        ) M ';
                      wSQL = wSQL ||'        left outer join VEF_EMP_TMOVPROENT P on (M.BDCODEMP = P.BDCODEMP and M.BDCHAVE = P.BDCHAVE and M.BDORDEM = P.BDORDEM) ';
                      wSQL = wSQL ||'        left outer join tcadpro_vinc cp on (p.bdcodemp = cp.bdcodemp and p.bdcodprod = cp.bdcodprod) ';
                      wSQL = wSQL ||'        left outer join ( ';
                      wSQL = wSQL ||'                         select o.bdcodemp,o.bdchave, o.bdcodprod, sum(BDBCST) BDBCST,o.bdaliqst,o.bdaliqicmsefet, o.bdaliqimcsstret, o.bdaliqfcpstret, o.bdaliqfcpretido, sum(BDBCFCPRETIDO) BDBCFCPRETIDO , sum(BDBCICMSSTRET) BDBCICMSSTRET,  sum(BDBCFCPSTRET) BDBCFCPSTRET ';
                      wSQL = wSQL ||'                         from vef_emp_tmovproentimpori o ';
                      wSQL = wSQL ||'                         where o.bdcodemp = '||:PRCODEMP;
                      wSQL = wSQL ||'                         and o.bdchave between '||Coalesce(:wminEnt,0)||' and ' ||Coalesce(:wMaxent,0);
                      wSQL = wSQL ||'                         group by o.bdcodemp,o.bdchave,o.bdcodprod,o.bdaliqst,o.bdaliqicmsefet, o.bdaliqimcsstret, o.bdaliqfcpstret, o.bdaliqfcpretido ';
                      wSQL = wSQL ||'                         ) PO on (M.BDCODEMP = PO.BDCODEMP and M.BDCHAVE = PO.BDCHAVE and P.bdcodprod = PO.bdcodprod) ';
    
                      if ((wbdcodcsticms is not null)  and (wbdcodcsticms > 0))then
                        wSQL = wSQL ||'      where p.bdcodcsticms = '||:wbdcodcsticms ;
                      else
                        if ((wBDVARIOSNCMS is not null) or (wBDVARIOSNCMS > 0)) then
                          wSQL = wSQL ||'      where exists (select f.bdcodcsticms from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodcsticms = p.bdcodcsticms) ';

                      wSQL = wSQL ||'       ) M ';
            
                      wSQL = wSQL ||'        GROUP by  M.BDCODEMP,M.BDCHAVE,M.BDREFLAN ';
                      wSQL = wSQL ||'     )M ';
        
                      wSQL = wSQL ||'    where bdvalor > 0 ' ;

                      execute statement wsql;
        
                      --SETORDEMSEQUENCIAL(0);
                      SETORDEMSEQUENCIAL_STR(:prCODEMP);
            
                      wSQL = ' INSERT INTO TMP_VEF_EMP_TMOVAJU1923_PL_TEMP  (BDSESSAO,BDCODEMP,BDTIPOLAN,BDCODSUBAPU,BDORDEM1921,BDORDEM1923,BDCODTER, ';
                      wSQL = wSQL ||'                                     BDCODDOCFIS,BDSERIE,BDSUBSERIE,BDNUMDOC,BDDTDOC,BDCODPROD,BDCHAVENFE,BDVALOR,BDCODAJUICMS,bdvlraju) ';
                      wSQL = wSQL ||'select M.BDSESSAO, M.BDCODEMP,0,M.BDCODSUBAPU,M.BDORDEM1921,GETORDEMSEQUENCIAL_STR(M.BDCODEMP||''.''||M.BDORDEM1921, '||:prCODEMP||')'||',M.BDCODTER, M.bdmodelo,SUBSTRING(m.bdserie from 1 FOR 4) bdserie,SUBSTRING(m.bdsubserie from 1 FOR 3) bdsubserie,m.bdnumdocini,m.BDDATAENTRADAENT, M.bdcodprod,m.bdchavenfe ,M.BDVALOR, ' ||wbdcodaju||','||wbdvlraju ;
                      wSQL = wSQL ||' FROM ( ';
                      wSQL = wSQL ||'  select '||:PRSESSAO||' BDSESSAO, M.BDCODEMP,'||wBDCODSUBAPU||' BDCODSUBAPU,'||'M.BDCHAVE'||' BDORDEM1921,'||'0 BDORDEM1923,M.BDCODTER, M.bdmodelo,m.bdserie,m.bdsubserie,m.bdnumdocini,m.BDDATAENTRADAENT, p.bdcodprod,m.bdchavenfe ,';
                      wSQL = wSQL ||'             ((iif(coalesce(P.BDBCST, 0) > 0, P.BDBCST, iif(coalesce(P.BDBCFCPRETIDO, 0) > 0, P.BDBCFCPRETIDO, iif(coalesce(P.BDBCICMSSTRET, 0) > 0, P.BDBCICMSSTRET, iif(coalesce(P.BDBCFCPSTRET, 0) > 0, coalesce(P.BDBCFCPSTRET, 0), iif(coalesce(PO.BDBCST, 0) > 0, PO.BDBCST, iif(coalesce(PO.BDBCFCPRETIDO, 0) > 0, PO.BDBCFCPRETIDO, iif(coalesce(PO.BDBCICMSSTRET, 0) > 0, PO.BDBCICMSSTRET, coalesce(PO.BDBCFCPSTRET, 0)))) /*normal*/ )))) * ';
                      wSQL = wSQL ||'             (iif(/*aliquota lancamento produto > 0*/ iif(coalesce(P.BDBCST, 0) > 0, P.BDALIQST, iif(coalesce(P.BDBCFCPRETIDO, 0) > 0, P.BDALIQFCPRETIDO, iif(coalesce(P.BDBCICMSSTRET, 0) > 0, P.BDALIQIMCSSTRET, iif(coalesce(P.BDBCFCPSTRET, 0) > 0, P.BDALIQFCPSTRET,0 /*normal*/ )))) > 0, ';
                      wSQL = wSQL ||'             /*pegar a sequencia acima*/ iif(coalesce(P.BDBCST, 0) > 0, P.BDALIQST, iif(coalesce(P.BDBCFCPRETIDO, 0) > 0, P.BDALIQFCPRETIDO, iif(coalesce(P.BDBCICMSSTRET, 0) > 0, P.BDALIQIMCSSTRET, iif(coalesce(P.BDBCFCPSTRET, 0) > 0, P.BDALIQFCPSTRET,0 /*normal*/ )))), ';
                      wSQL = wSQL ||'             iif(iif(coalesce(P.BDBCST, 0) > 0, CP.BDALIQICMSST, iif(coalesce(P.BDBCFCPRETIDO, 0) > 0, 0, iif(coalesce(P.BDBCICMSSTRET, 0) > 0, CP.BDALIQICMSSTRET, iif(coalesce(P.BDBCFCPSTRET, 0) > 0, 0, 0 /*normal*/ )))) > 0, ';
                      wSQL = wSQL ||'             iif(coalesce(P.BDBCST, 0) > 0, CP.BDALIQICMSST, iif(coalesce(P.BDBCFCPRETIDO, 0) > 0, 0,iif(coalesce(P.BDBCICMSSTRET, 0) > 0, CP.BDALIQICMSSTRET, iif(coalesce(P.BDBCFCPSTRET, 0) > 0, 0, 0 /*normal*/ )))), '||:waliqinternauf||')))) / 100) BDVALOR ';
                      wSQL = wSQL ||'  from ( ';
                      wSQL = wSQL ||'      select M.BDCODEMP, M.BDCHAVE, I.BDORDEM,m.bdchavenfe,m.BDDATAENTRADAENT,m.bdnumdocini,m.bdserie,m.bdsubserie,M.BDCODTER,M.BDMODELO ';
                      wSQL = wSQL ||'      from ( ';
                      wSQL = wSQL ||'            select M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, M.BDMODELO, M.BDCONSUFINAL,m.bdchavenfe,m.BDDATAENTRADAENT,m.bdnumdocini,m.bdserie,m.bdsubserie,M.BDCODTER ';
                      wSQL = wSQL ||'            from VEF_EMP_TMOVENT M ';
                      wSQL = wSQL ||'                            where m.bdcodemp = '||:PRCODEMP;
                      wSQL = wSQL ||'                            and m.bdreflan = '||:PRREF;
                      wSQL = wSQL ||'                            and M.BDCODSITNF NOT IN (2, 3, 4, 5) ';
                      if ((:wbdmodelo is not null)  and (:wbdmodelo > '0')) then
                        wSQL = wSQL ||'                          and m.bdmodelo = '|| :wbdmodelo;
                      if ((wbdconsufinal is not null)  and (wbdconsufinal > -1)) then
                        wSQL = wSQL ||'                          and m.bdconsufinal = '|| :wbdconsufinal;
                      wSQL = wSQL ||'           ) M ';
                      wSQL = wSQL ||'      join VEF_EMP_TMOVENTITENS I on (M.BDCODEMP = I.BDCODEMP and M.BDCHAVE = I.BDCHAVE) ';

                      if ((wbdcodnat is not null)  and (wbdcodnat > 0))then
                        wSQL = wSQL ||'            WHERE i.bdcodnat = '||:wbdcodnat ;
                      else
                        if ((wbdVariasCFOPs is not null) or (wbdVariasCFOPs > 0)) then
                          wSQL = wSQL ||'           WHERE exists (select f.bdcodnat from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodnat = i.bdcodnat) ';
                      wSQL = wSQL ||'        ) M ';
                      wSQL = wSQL ||'left outer join VEF_EMP_TMOVPROENT P on (M.BDCODEMP = P.BDCODEMP and M.BDCHAVE = P.BDCHAVE and M.BDORDEM = P.BDORDEM) ';
                      wSQL = wSQL ||'left outer join tcadpro_vinc cp on (p.bdcodemp = cp.bdcodemp and p.bdcodprod = cp.bdcodprod) ';
                      wSQL = wSQL ||'        left outer join ( ';
                      wSQL = wSQL ||'                         select o.bdcodemp,o.bdchave, o.bdcodprod, sum(BDBCST) BDBCST,o.bdaliqst,o.bdaliqicmsefet, o.bdaliqimcsstret, o.bdaliqfcpstret, o.bdaliqfcpretido, sum(BDBCFCPRETIDO) BDBCFCPRETIDO , sum(BDBCICMSSTRET) BDBCICMSSTRET,  sum(BDBCFCPSTRET) BDBCFCPSTRET ';
                      wSQL = wSQL ||'                         from vef_emp_tmovproentimpori o ';
                      wSQL = wSQL ||'                         where o.bdcodemp = '||:PRCODEMP;
                      wSQL = wSQL ||'                         and o.bdchave between '||Coalesce(:wminEnt,0)||' and ' ||Coalesce(:wMaxent,0);
                      wSQL = wSQL ||'                         group by o.bdcodemp,o.bdchave,o.bdcodprod,o.bdaliqst,o.bdaliqicmsefet, o.bdaliqimcsstret, o.bdaliqfcpstret, o.bdaliqfcpretido ';
                      wSQL = wSQL ||'                         ) PO on (M.BDCODEMP = PO.BDCODEMP and M.BDCHAVE = PO.BDCHAVE and P.bdcodprod = PO.bdcodprod) ';
        --
                      if ((wbdcodcsticms is not null)  and (wbdcodcsticms > 0))then
                        wSQL = wSQL ||'      where p.bdcodcsticms = '||:wbdcodcsticms ;
                      else
                        if ((wBDVARIOSNCMS is not null) or (wBDVARIOSNCMS > 0)) then
                          wSQL = wSQL ||'      where exists (select f.bdcodcsticms from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodcsticms = p.bdcodcsticms) ';
            
                      wSQL = wSQL ||') M ';
                      wSQL = wSQL ||'    where bdvalor > 0 ' ;
             
                       execute statement wsql;
                  
        --              --CAMPO BDORDEM1921 TEM A CHAVE DO LANÇAMENTO DE ENTRADA
                      INSERT INTO TOL_VEF_EMP_TMOVENTAJU1921_TEMP (BDSESSAO,BDCODEMP,BDCHAVE,BDORDEM1921,BDCODPERIODO,BDREFERENCIA,BDCODAJUICMS,bdordem1923,bdvlraju)
                      SELECT :prsessao, T.BDCODEMP,T.BDORDEM1921,0,7,BDREFERENCIA,:wbdcodaju,pl.bdordem1923,:wbdvlraju
                      FROM TMP_VEF_EMP_TMOVAJU1921_PL_TEMP T
                      LEFT OUTER JOIN TMP_VEF_EMP_TMOVAJU1923_PL_TEMP PL ON  (T.bdsessao = PL.BDSESSAO AND T.BDCODEMP = PL.BDCODEMP and t.bdtipolan = pl.bdtipolan AND T.BDORDEM1921 = PL.BDORDEM1921 and t.bdcodajuicms = pl.bdcodajuicms and t.bdvlraju = pl.bdvlraju)
                      where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp AND T.BDTIPOLAN = 0 and t.bdvlraju = :wbdvlraju
                      and not exists (select a.bdcodemp from TOL_VEF_EMP_TMOVENTAJU1921_TEMP a  where a.bdsessao = :prsessao and a.bdcodemp = t.bdcodemp and a.bdchave = t.bdordem1921 and a.BDORDEM1923 = pl.BDORDEM1923 and a.bdcodajuicms = pl.bdcodajuicms and a.bdvlraju = pl.bdvlraju);

                    end
                 else
               --não varejista
                 if (wbdvlraju = 2) then
                   begin

                      wSQL = ' INSERT INTO TMP_VEF_EMP_TMOVAJU1921_PL_TEMP  (BDSESSAO,BDCODEMP,BDTIPOLAN,BDCODSUBAPU,BDORDEM1921,BDCHAVE,BDREFERENCIA,BDCODAJUICMS,BDCODTIPO,BDDESCCOMP,BDVALOR,bdvlraju) ';
                      wSQL = wSQL ||'select '||:PRSESSAO||' BDSESSAO, M.BDCODEMP,0,'||wBDCODSUBAPU||', M.BDCHAVE,M.BDCHAVE,'||:PRREF||', '||wbdcodaju||', 141 BDCODTIPO, '''||wbddesccomp||''' , BDVALOR, '||:wbdvlraju;
                      wSQL = wSQL ||' FROM ( ';
                      wSQL = wSQL ||'        select M.BDCODEMP,M.BDCHAVE,M.BDREFLAN , sum(((iif(coalesce(p.BDBCST,0)>0,coalesce(p.BDBCST,0),coalesce(po.BDBCST,0)) / p.bdqtditem) * si.bdqtdprod)) bdVALOR ';
                      wSQL = wSQL ||'        from ( ';
                      wSQL = wSQL ||'              select M.BDCODEMP, M.BDCHAVE, I.BDORDEM,m.bdREFLAN ';
                      wSQL = wSQL ||'              from ( ';
                      wSQL = wSQL ||'                    select M.BDCODEMP, M.BDCHAVE, M.BDREFLAN ';
                      wSQL = wSQL ||'                    from VEF_EMP_TMOVENT M ';
                      wSQL = wSQL ||'                            where m.bdcodemp = '||:PRCODEMP;
                      wSQL = wSQL ||'                            and m.bdreflan = '||:PRREF;
                      wSQL = wSQL ||'                            and M.BDCODSITNF NOT IN (2, 3, 4, 5) ';
                      if ((:wbdmodelo is not null)  and (:wbdmodelo > '0')) then
                        wSQL = wSQL ||'                          and m.bdmodelo = '|| :wbdmodelo;
                      if ((wbdconsufinal is not null)  and (wbdconsufinal > -1)) then
                        wSQL = wSQL ||'                          and m.bdconsufinal = '|| :wbdconsufinal;
                      wSQL = wSQL ||'                   ) M ';
                      wSQL = wSQL ||'              join VEF_EMP_TMOVENTITENS I on (M.BDCODEMP = I.BDCODEMP and M.BDCHAVE = I.BDCHAVE) ';
    --                  wSQL = wSQL ||'              where not exists (select t.bdcodemp from TMP_VEF_EMP_TMOVAJU1921_TEMP t ';
    --                  wSQL = wSQL ||'                                left OUTER JOIN TOL_VEF_EMP_TMOVENTAJU1921_TEMP TL ON (TL.bdsessao = T.bdsessao AND TL.bdcodemp = T.bdcodemp AND TL.bdchave = T.bdordem1921) ';
    --                  wSQL = wSQL ||'                                where t.bdsessao = '||:prsessao ||' and t.bdcodemp = m.bdcodemp and t.bdordem1921 = m.bdchave AND TL.BDCODEMP IS NULL)';
        
                      if ((wbdcodnat is not null)  and (wbdcodnat > 0))then
                        wSQL = wSQL ||'            WHERE i.bdcodnat = '||:wbdcodnat ;
                      else
                        if ((wbdVariasCFOPs is not null) or (wbdVariasCFOPs > 0)) then
                          wSQL = wSQL ||'          WHERE exists (select f.bdcodnat from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodnat = i.bdcodnat) ';
                      wSQL = wSQL ||'        ) M ';
                      wSQL = wSQL ||'        left outer join VEF_EMP_TMOVPROENT P on (M.BDCODEMP = P.BDCODEMP and M.BDCHAVE = P.BDCHAVE and M.BDORDEM = P.BDORDEM) ';
                      --wSQL = wSQL ||'        JOIN tmp_vef_emp_tmovaju1921_pl_temp S ON (S.bdsessao = '||:PRSESSAO||' and s.bdcodemp = m.bdcodemp and s.bdtipolan = 1 ) ';
                      wSQL = wSQL ||'        join tmp_vef_emp_tmovaju1923_pl_temp SI ON ('||:PRSESSAO||' = si.bdsessao and m.bdcodemp = si.bdcodemp and 1 = si.bdtipolan and si.BDCODPROD = p.bdcodprod) ';

                      wSQL = wSQL ||'        left outer join ( ';
                      wSQL = wSQL ||'                         select o.bdcodemp,o.bdchave, o.bdcodprod, sum(BDBCST) BDBCST, sum(BDBCFCPRETIDO) BDBCFCPRETIDO , sum(BDBCICMSSTRET) BDBCICMSSTRET,  sum(BDBCFCPSTRET) BDBCFCPSTRET ';
                      wSQL = wSQL ||'                         from vef_emp_tmovproentimpori o ';
                      wSQL = wSQL ||'                         where o.bdcodemp = '||:PRCODEMP;
                      wSQL = wSQL ||'                         and o.bdchave between '||Coalesce(:wminEnt,0)||' and ' ||Coalesce(:wMaxent,0);
                      wSQL = wSQL ||'                         group by o.bdcodemp,o.bdchave,o.bdcodprod ';
                      wSQL = wSQL ||'                         ) PO on (M.BDCODEMP = PO.BDCODEMP and M.BDCHAVE = PO.BDCHAVE and P.bdcodprod = PO.bdcodprod) ';

                      if ((wbdcodcsticms is not null)  and (wbdcodcsticms > 0))then
                        wSQL = wSQL ||'      where p.bdcodcsticms = '||:wbdcodcsticms ;
                      else
                        if ((wBDVARIOSNCMS is not null) or (wBDVARIOSNCMS > 0)) then
                          wSQL = wSQL ||'      where exists (select f.bdcodcsticms from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodcsticms = p.bdcodcsticms) ';
            
                      wSQL = wSQL ||'        GROUP by  M.BDCODEMP,M.BDCHAVE,M.BDREFLAN ';
                      wSQL = wSQL ||'     )M ';
        
                      wSQL = wSQL ||'    where bdvalor > 0 ' ;

                      execute statement wsql;
        
                      --SETORDEMSEQUENCIAL(0);
                      SETORDEMSEQUENCIAL_STR(:prCODEMP);
            
                      wSQL = ' INSERT INTO TMP_VEF_EMP_TMOVAJU1923_PL_TEMP  (BDSESSAO,BDCODEMP,BDTIPOLAN,BDCODSUBAPU,BDORDEM1921,BDORDEM1923,BDCODTER, ';
                      wSQL = wSQL ||'                                     BDCODDOCFIS,BDSERIE,BDSUBSERIE,BDNUMDOC,BDDTDOC,BDCODPROD,BDCHAVENFE,BDVALOR,BDCODAJUICMS,bdvlraju) ';
            
                      wSQL = wSQL ||'select M.BDSESSAO, M.BDCODEMP,0,M.BDCODSUBAPU,M.BDORDEM1921,GETORDEMSEQUENCIAL_STR(M.BDCODEMP||''.''||M.BDORDEM1921, '||:prCODEMP||')'||',M.BDCODTER, M.bdmodelo,SUBSTRING(m.bdserie from 1 FOR 4) bdserie,SUBSTRING(m.bdsubserie from 1 FOR 3) bdsubserie,m.bdnumdocini,m.BDDATAENTRADAENT, M.bdcodprod,m.bdchavenfe ,M.BDVALOR,  ' ||wbdcodaju||','||wbdvlraju ;
                      wSQL = wSQL ||' FROM ( ';
                      wSQL = wSQL ||'  select '||:PRSESSAO||' BDSESSAO, M.BDCODEMP,'||wBDCODSUBAPU||' BDCODSUBAPU,'||'M.BDCHAVE'||' BDORDEM1921,'||'0 BDORDEM1923,M.BDCODTER, M.bdmodelo,m.bdserie,m.bdsubserie,m.bdnumdocini,m.BDDATAENTRADAENT, p.bdcodprod,m.bdchavenfe ,((iif(coalesce(p.BDBCST,0)>0,coalesce(p.BDBCST,0),coalesce(po.BDBCST,0)) / p.bdqtditem) * si.bdqtdprod) BDVALOR';
                      wSQL = wSQL ||'  from ( ';
                      wSQL = wSQL ||'      select M.BDCODEMP, M.BDCHAVE, I.BDORDEM,m.bdchavenfe,m.BDDATAENTRADAENT,m.bdnumdocini,m.bdserie,m.bdsubserie,M.BDCODTER,M.BDMODELO ';
                      wSQL = wSQL ||'      from ( ';
                      wSQL = wSQL ||'            select M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, M.BDMODELO, M.BDCONSUFINAL,m.bdchavenfe,m.BDDATAENTRADAENT,m.bdnumdocini,m.bdserie,m.bdsubserie,M.BDCODTER ';
                      wSQL = wSQL ||'            from VEF_EMP_TMOVENT M ';
                      wSQL = wSQL ||'                            where m.bdcodemp = '||:PRCODEMP;
                      wSQL = wSQL ||'                            and m.bdreflan = '||:PRREF;
                      wSQL = wSQL ||'                            and M.BDCODSITNF NOT IN (2, 3, 4, 5) ';
                      if ((:wbdmodelo is not null)  and (:wbdmodelo > '0')) then
                        wSQL = wSQL ||'                          and m.bdmodelo = '|| :wbdmodelo;
                      if ((wbdconsufinal is not null)  and (wbdconsufinal > -1)) then
                        wSQL = wSQL ||'                          and m.bdconsufinal = '|| :wbdconsufinal;
                      wSQL = wSQL ||'           ) M ';
                      wSQL = wSQL ||'      join VEF_EMP_TMOVENTITENS I on (M.BDCODEMP = I.BDCODEMP and M.BDCHAVE = I.BDCHAVE) ';
    --                  wSQL = wSQL ||'      where not exists (select t.bdcodemp from TMP_VEF_EMP_TMOVAJU1923_PL_TEMP t ';
    --                  wSQL = wSQL ||'                        left OUTER JOIN TOL_VEF_EMP_TMOVENTAJU1921_TEMP TL ON (TL.bdsessao = T.bdsessao AND TL.bdcodemp = T.bdcodemp AND TL.bdchave = T.bdordem1921) ';
    --                  wSQL = wSQL ||'                        where t.bdsessao = '||:prsessao ||' and t.bdcodemp = m.bdcodemp and t.bdordem1921 = m.bdchave AND TL.BDCODEMP IS NULL)';
        
                      if ((wbdcodnat is not null)  and (wbdcodnat > 0))then
                        wSQL = wSQL ||'            WHERE i.bdcodnat = '||:wbdcodnat ;
                      else
                        if ((wbdVariasCFOPs is not null) or (wbdVariasCFOPs > 0)) then
                          wSQL = wSQL ||'            WHERE exists (select f.bdcodnat from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodnat = i.bdcodnat) ';
                      wSQL = wSQL ||'        ) M ';
                      wSQL = wSQL ||'left outer join VEF_EMP_TMOVPROENT P on (M.BDCODEMP = P.BDCODEMP and M.BDCHAVE = P.BDCHAVE and M.BDORDEM = P.BDORDEM) ';

                      --wSQL = wSQL ||'        JOIN tmp_vef_emp_tmovaju1921_pl_temp S ON (S.bdsessao = '||:PRSESSAO||' and s.bdcodemp = m.bdcodemp and s.bdtipolan = 1 ) ';
                      wSQL = wSQL ||'        join tmp_vef_emp_tmovaju1923_pl_temp SI ON ('||:PRSESSAO||' = si.bdsessao and M.bdcodemp = si.bdcodemp and 1 = si.bdtipolan and si.BDCODPROD = p.bdcodprod) ';
                      wSQL = wSQL ||'        left outer join ( ';
                      wSQL = wSQL ||'                         select o.bdcodemp,o.bdchave, o.bdcodprod, sum(BDBCST) BDBCST, sum(BDBCFCPRETIDO) BDBCFCPRETIDO , sum(BDBCICMSSTRET) BDBCICMSSTRET,  sum(BDBCFCPSTRET) BDBCFCPSTRET ';
                      wSQL = wSQL ||'                         from vef_emp_tmovproentimpori o ';
                      wSQL = wSQL ||'                         where o.bdcodemp = '||:PRCODEMP;
                      wSQL = wSQL ||'                         and o.bdchave between '||Coalesce(:wminEnt,0)||' and ' ||Coalesce(:wMaxent,0);
                      wSQL = wSQL ||'                         group by o.bdcodemp,o.bdchave,o.bdcodprod ';
                      wSQL = wSQL ||'                         ) PO on (M.BDCODEMP = PO.BDCODEMP and M.BDCHAVE = PO.BDCHAVE and P.bdcodprod = PO.bdcodprod) ';

        --
                      if ((wbdcodcsticms is not null)  and (wbdcodcsticms > 0))then
                        wSQL = wSQL ||'      where p.bdcodcsticms = '||:wbdcodcsticms ;
                      else
                        if ((wBDVARIOSNCMS is not null) or (wBDVARIOSNCMS > 0)) then
                          wSQL = wSQL ||'      where exists (select f.bdcodcsticms from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodcsticms = p.bdcodcsticms) ';
            
                      wSQL = wSQL ||') M ';
                      wSQL = wSQL ||'    where bdvalor > 0 ' ;
             
                       execute statement wsql;
                  
        --              --CAMPO BDORDEM1921 TEM A CHAVE DO LANÇAMENTO DE ENTRADA
                      INSERT INTO TOL_VEF_EMP_TMOVENTAJU1921_TEMP (BDSESSAO,BDCODEMP,BDCHAVE,BDORDEM1921,BDCODPERIODO,BDREFERENCIA,BDCODAJUICMS,bdordem1923,bdvlraju)
                      SELECT :prsessao, T.BDCODEMP,T.BDORDEM1921,0,7,BDREFERENCIA,:wbdcodaju,pl.bdordem1923,:wbdvlraju
                      FROM TMP_VEF_EMP_TMOVAJU1921_PL_TEMP T
                      LEFT OUTER JOIN TMP_VEF_EMP_TMOVAJU1923_PL_TEMP PL ON  (T.bdsessao = PL.BDSESSAO AND T.BDCODEMP = PL.BDCODEMP and t.bdtipolan = pl.bdtipolan AND T.BDORDEM1921 = PL.BDORDEM1921 and t.bdcodajuicms = pl.bdcodajuicms and t.bdvlraju = pl.bdvlraju)
                      where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp AND T.BDTIPOLAN = 0 and t.bdvlraju = :wbdvlraju
                      and not exists (select a.bdcodemp from TOL_VEF_EMP_TMOVENTAJU1921_TEMP a  where a.bdsessao = :prsessao and a.bdcodemp = t.bdcodemp and a.bdchave = t.bdordem1921 and a.BDORDEM1923 = pl.BDORDEM1923 and a.bdcodajuicms = pl.bdcodajuicms and a.bdvlraju = pl.bdvlraju);
                         
                   end
               end
            end
          else
          --Saída
          if (wbdtipomov = 1) then
            begin
              --tipo valor ajuste
              --(1, 'ICMS Efetivo')
              --(2, 'ICMS Presumido')
              --(3, 'ICMS Inventário')
              --(4, 'ICMS a pagar')
              --(5, 'ICMS a recuperar')
              --(6, 'ICMS PRESUMIDO - ESTORNO')
              --(7, 'ICMS EFETIVO - ESTORNO')
              if (wbdvlraju = 1) then
                wCampoValor  = 'coalesce(p.BDVLRICMSEFET,0)';
              if (wbdvlraju = 6) then
                begin
                  wCampoValor = '(iif(coalesce(p.BDVLRST,0)>0,p.BDVLRST,IIF(coalesce(p.BDFCPRETIDO,0)>0,p.BDFCPRETIDO,IIF(coalesce(p.BDVLRICMSSTRET,0)>0,p.BDVLRICMSSTRET,IIF(coalesce(p.BDVLRFCPSTRET,0)>0,coalesce(p.BDVLRFCPSTRET,0),  ';
                  wCampoValor = wCampoValor || 'iif(coalesce(po.BDVLRST,0)>0,po.BDVLRST,IIF(coalesce(po.BDFCPRETIDO,0)>0,po.BDFCPRETIDO,IIF(coalesce(po.BDVLRICMSSTRET,0)>0,po.BDVLRICMSSTRET,coalesce(po.BDVLRFCPSTRET,0)))) /*normal*/ )))) )';
                end
--                wCampoValor  = 'coalesce(p.BDBCST,0)+coalesce(p.BDBCICMSEFET,0)+coalesce(p.BDBCICMSSTRET,0)+coalesce(p.BDBCFCPSTRET,0) ';
--              if (wbdvlraju = 6) then
--                wCampoValor  = 'coalesce(p.BDBCFCPRETIDO,0) ';

--              SETORDEMSEQUENCIAL(0);
              wSQL = ' INSERT INTO TMP_VEF_EMP_TMOVAJU1921_PL_TEMP  (BDSESSAO,BDCODEMP,BDTIPOLAN,BDCODSUBAPU,BDORDEM1921,BDCHAVE,BDREFERENCIA,BDCODAJUICMS,BDCODTIPO,BDDESCCOMP,BDVALOR,bdvlraju) ';
    
              wSQL = wSQL ||'select '||:PRSESSAO||' BDSESSAO, M.BDCODEMP,1,'||wBDCODSUBAPU||',/*'||'GETORDEMSEQUENCIAL(M.BDCODEMP)'||'*/M.BDCHAVE,M.BDCHAVE,'||:PRREF||', '||wbdcodaju||', 141 BDCODTIPO, '''||wbddesccomp||''' , M.bdvalor, '||:wbdvlraju;
              wSQL = wSQL ||' FROM ( ';
              wSQL = wSQL ||'        select M.BDCODEMP,M.BDCHAVE,M.BDREFLAN , Sum('||:wcampovalor ||') bdvalor';
              wSQL = wSQL ||'        from ( ';
              wSQL = wSQL ||'              select M.BDCODEMP, M.BDCHAVE, I.BDORDEM,m.bdREFLAN ';
              wSQL = wSQL ||'              from ( ';
              wSQL = wSQL ||'                    select M.BDCODEMP, M.BDCHAVE, M.BDREFLAN ';
              wSQL = wSQL ||'                    from VEF_EMP_TMOVSAI M ';
              wSQL = wSQL ||'                            where m.bdcodemp = '||:PRCODEMP;
              wSQL = wSQL ||'                            and m.bdreflan = '||:PRREF;
              wSQL = wSQL ||'                            and M.BDCODSITNF NOT IN (2, 3, 4, 5) ';
              if ((:wbdmodelo is not null)  and (:wbdmodelo > '0')) then
                wSQL = wSQL ||'                          and m.bdmodelo = '|| :wbdmodelo;
              if ((wbdconsufinal is not null)  and (wbdconsufinal > -1)) then
                wSQL = wSQL ||'                          and m.bdconsufinal = '|| :wbdconsufinal;
              wSQL = wSQL ||'                   ) M ';
              wSQL = wSQL ||'              join VEF_EMP_TMOVSAIITENS I on (M.BDCODEMP = I.BDCODEMP and M.BDCHAVE = I.BDCHAVE) ';
--              wSQL = wSQL ||'              where not exists (select t.bdcodemp from TMP_VEF_EMP_TMOVAJU1921_TEMP t where t.bdsessao = '||:prsessao ||' and t.bdcodemp = m.bdcodemp and t.bdordem1921 = m.bdchave)';
              if ((wbdcodnat is not null)  and (wbdcodnat > 0))then
                wSQL = wSQL ||'            WHERE i.bdcodnat = '||:wbdcodnat ;
              else
                if ((wbdVariasCFOPs is not null) or (wbdVariasCFOPs > 0)) then
                  wSQL = wSQL ||'          WHERE exists (select f.bdcodnat from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodnat = i.bdcodnat) ';
              wSQL = wSQL ||'        ) M ';
              wSQL = wSQL ||'        left outer join VEF_EMP_TMOVPROSAI P on (M.BDCODEMP = P.BDCODEMP and M.BDCHAVE = P.BDCHAVE and M.BDORDEM = P.BDORDEM) ';
              wSQL = wSQL ||'left outer join ( ';
              wSQL = wSQL ||'                 select o.bdcodemp,o.bdchave, o.bdcodprod, sum(BDBCST) BDBCST, sum(BDBCFCPRETIDO) BDBCFCPRETIDO , sum(BDBCICMSSTRET) BDBCICMSSTRET,  sum(BDBCFCPSTRET) BDBCFCPSTRET ';
              wSQL = wSQL ||'                 ,sum(BDVLRST) BDVLRST,sum(BDFCPRETIDO) BDFCPRETIDO,sum(BDVLRICMSSTRET) BDVLRICMSSTRET,sum(BDVLRFCPSTRET) BDVLRFCPSTRET ';
              wSQL = wSQL ||'                 from vef_emp_tmovprosaiimpori o ';
              wSQL = wSQL ||'                 where o.bdcodemp = '||:PRCODEMP;
              wSQL = wSQL ||'                 and o.bdchave between '||Coalesce(:wminSai,0)||' and '||Coalesce(:wMaxSai,0);
              wSQL = wSQL ||'                 group by o.bdcodemp,o.bdchave,o.bdcodprod ';
              wSQL = wSQL ||'                ) PO on (M.BDCODEMP = PO.BDCODEMP and M.BDCHAVE = PO.BDCHAVE and P.bdcodprod = PO.bdcodprod) ';

              if ((wbdcodcsticms is not null)  and (wbdcodcsticms > 0))then
                wSQL = wSQL ||'      where p.bdcodcsticms = '||:wbdcodcsticms ;
              else
                if ((wBDVARIOSNCMS is not null) or (wBDVARIOSNCMS > 0)) then
                  wSQL = wSQL ||'      where exists (select f.bdcodcsticms from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodcsticms = p.bdcodcsticms) ';
    
              wSQL = wSQL ||'        GROUP by  M.BDCODEMP,M.BDCHAVE,M.BDREFLAN ';
              wSQL = wSQL ||'     )M ';

              wSQL = wSQL ||'    where bdvalor > 0 ' ;

              execute statement wsql;

--              SETORDEMSEQUENCIAL(0);
              SETORDEMSEQUENCIAL_STR(:prCODEMP);
    
              wSQL = ' INSERT INTO TMP_VEF_EMP_TMOVAJU1923_PL_TEMP (BDSESSAO,BDCODEMP,BDTIPOLAN,BDCODSUBAPU,BDORDEM1921,BDORDEM1923,BDCODTER, ';
              wSQL = wSQL ||'                                      BDCODDOCFIS,BDSERIE,BDSUBSERIE,BDNUMDOC,BDDTDOC,BDCODPROD,BDCHAVENFE,BDVALOR,BDQTDPROD,BDCODAJUICMS,bdvlraju) ';
    
              wSQL = wSQL ||'select M.BDSESSAO, M.BDCODEMP,1,M.BDCODSUBAPU,M.BDORDEM1921,GETORDEMSEQUENCIAL_STR(M.BDCODEMP||''.''||M.BDORDEM1921, '||:prCODEMP||')'||',M.BDCODTER, M.bdmodelo,SUBSTRING(m.bdserie from 1 FOR 4) bdserie,SUBSTRING(m.bdsubserie from 1 FOR 3) bdsubserie,m.bdnumdocini,m.bddataemissao,M.bdcodprod,m.bdchavenfe ,M.bdvalor,m.BDQTDITEM , ' ||wbdcodaju||','||wbdvlraju ;
              wSQL = wSQL ||' FROM ( ';
              wSQL = wSQL ||'  select '||:PRSESSAO||' BDSESSAO, M.BDCODEMP,'||wBDCODSUBAPU||' BDCODSUBAPU,'||'M.BDCHAVE'||' BDORDEM1921,'||'0 BDORDEM1923,M.BDCODTER, M.bdmodelo,m.bdserie,m.bdsubserie,m.bdnumdocini,m.bddataemissao,p.BDQTDITEM, p.bdcodprod,m.bdchavenfe , '||:wcampovalor || ' bdvalor ';
              wSQL = wSQL ||'  from ( ';
              wSQL = wSQL ||'      select M.BDCODEMP, M.BDCHAVE, I.BDORDEM,m.bdchavenfe,m.bddataemissao,m.bdnumdocini,m.bdserie,m.bdsubserie,M.BDCODTER,M.BDMODELO ';
              wSQL = wSQL ||'      from ( ';
              wSQL = wSQL ||'            select M.BDCODEMP, M.BDCHAVE, M.BDREFLAN, M.BDMODELO, M.BDCONSUFINAL,m.bdchavenfe,m.bddataemissao,m.bdnumdocini,m.bdserie,m.bdsubserie,M.BDCODTER ';
              wSQL = wSQL ||'            from VEF_EMP_TMOVSAI M ';
              wSQL = wSQL ||'                            where m.bdcodemp = '||:PRCODEMP;
              wSQL = wSQL ||'                            and m.bdreflan = '||:PRREF;
              wSQL = wSQL ||'                            and M.BDCODSITNF NOT IN (2, 3, 4, 5) ';
              if ((:wbdmodelo is not null)  and (:wbdmodelo > '0')) then
                wSQL = wSQL ||'                          and m.bdmodelo = '|| :wbdmodelo;
              if ((wbdconsufinal is not null)  and (wbdconsufinal > -1)) then
                wSQL = wSQL ||'                          and m.bdconsufinal = '|| :wbdconsufinal;
              wSQL = wSQL ||'           ) M ';
              wSQL = wSQL ||'      join VEF_EMP_TMOVSAIITENS I on (M.BDCODEMP = I.BDCODEMP and M.BDCHAVE = I.BDCHAVE) ';
--              wSQL = wSQL ||'      where not exists (select t.bdcodemp from TMP_VEF_EMP_TMOVAJU1923_PL_TEMP t where t.bdsessao = '||:prsessao ||' and t.bdcodemp = m.bdcodemp and t.bdordem1921 = m.bdchave)';
              if ((wbdcodnat is not null)  and (wbdcodnat > 0))then
                wSQL = wSQL ||'            WHERE i.bdcodnat = '||:wbdcodnat ;
              else
                if ((wbdVariasCFOPs is not null) or (wbdVariasCFOPs > 0)) then
                  wSQL = wSQL ||'            WHERE exists (select f.bdcodnat from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodnat = i.bdcodnat) ';
              wSQL = wSQL ||'        ) M ';
              wSQL = wSQL ||'left outer join VEF_EMP_TMOVPROSAI P on (M.BDCODEMP = P.BDCODEMP and M.BDCHAVE = P.BDCHAVE and M.BDORDEM = P.BDORDEM) ';
              wSQL = wSQL ||'left outer join ( ';
              wSQL = wSQL ||'                 select o.bdcodemp,o.bdchave, o.bdcodprod, sum(BDBCST) BDBCST, sum(BDBCFCPRETIDO) BDBCFCPRETIDO , sum(BDBCICMSSTRET) BDBCICMSSTRET,  sum(BDBCFCPSTRET) BDBCFCPSTRET ';
              wSQL = wSQL ||'                 ,sum(BDVLRST) BDVLRST,sum(BDFCPRETIDO) BDFCPRETIDO,sum(BDVLRICMSSTRET) BDVLRICMSSTRET,sum(BDVLRFCPSTRET) BDVLRFCPSTRET ';
              wSQL = wSQL ||'                 from vef_emp_tmovprosaiimpori o ';
              wSQL = wSQL ||'                 where o.bdcodemp = '||:PRCODEMP;
              wSQL = wSQL ||'                 and o.bdchave between '||Coalesce(:wminSai,0)||' and ' ||Coalesce(:wMaxSai,0);
              wSQL = wSQL ||'                 group by o.bdcodemp,o.bdchave,o.bdcodprod ';
              wSQL = wSQL ||'                ) PO on (M.BDCODEMP = PO.BDCODEMP and M.BDCHAVE = PO.BDCHAVE and P.bdcodprod = PO.bdcodprod) ';

              if ((wbdcodcsticms is not null)  and (wbdcodcsticms > 0))then
                wSQL = wSQL ||'      where p.bdcodcsticms = '||:wbdcodcsticms ;
              else
                if ((wBDVARIOSNCMS is not null) or (wBDVARIOSNCMS > 0)) then
                  wSQL = wSQL ||'      where exists (select f.bdcodcsticms from VEF_BASE_TVINCCODPLANO1900 f where f.bdcodplanconf1900 = '||:wplano||' and f.bdchave = '||:wbdchave||' and f.bdcodcsticms = p.bdcodcsticms) ';
    
              wSQL = wSQL ||') M ';
              wSQL = wSQL ||'    where bdvalor > 0 ' ;
     
              execute statement wsql;

              /*Camilla M. ICMS Efetivo - Redução Z - Criado os ajustes do 1921 a partir da redução Z */
              if (wbdvlraju = 1) then
                 begin
                   EXECUTE PROCEDURE SP_APLICA_PLANO_1900_REDZ(:PRSESSAO,:PRCODEMP,:PRREF,:WBDCODSUBAPU,:WBDCODAJU,:WBDCODNAT,
                   :WBDVARIASCFOPS,:WBDCODCSTICMS,:WBDVARIOSNCMS,:WPLANO,:WBDCHAVE,:WBDVLRAJU,:WBDDESCCOMP);
                 end

              INSERT INTO TOL_VEF_EMP_TMOVSAIAJU1921_TEMP (BDSESSAO,BDCODEMP,BDCHAVE,BDORDEM1921,BDCODPERIODO,BDREFERENCIA,BDCODAJUICMS,bdordem1923,bdvlraju)
              SELECT :prsessao, T.BDCODEMP,T.BDORDEM1921,0,7,BDREFERENCIA,:wbdcodaju,pl.bdordem1923,:wbdvlraju
              FROM TMP_VEF_EMP_TMOVAJU1921_PL_TEMP T
              LEFT OUTER JOIN TMP_VEF_EMP_TMOVAJU1923_PL_TEMP PL ON  (T.bdsessao = PL.BDSESSAO AND T.BDCODEMP = PL.BDCODEMP AND T.BDORDEM1921 = PL.BDORDEM1921 and t.bdcodajuicms = pl.bdcodajuicms and t.bdvlraju = pl.bdvlraju)
              where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp AND T.BDTIPOLAN = 1 and t.bdvlraju = :wbdvlraju
              and not exists (select a.bdcodemp from TOL_VEF_EMP_TMOVSAIAJU1921_TEMP a  where a.bdsessao = :prsessao and a.bdcodemp = t.bdcodemp and a.bdchave = t.bdordem1921 and a.BDORDEM1923 = pl.BDORDEM1923 and a.bdcodajuicms = pl.bdcodajuicms and a.bdvlraju = pl.bdvlraju);

            end
    
        END

   END

END^

CREATE OR ALTER procedure SP_INSEREREG_PLANO_1250 (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer)
as
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WORDEMPRO integer;
declare variable WCODPROD integer;
declare variable WMOTIVO integer;
declare variable WQUANTIDADE numeric(15,6);
declare variable WVLRUNIT numeric(15,6);
declare variable WVLRUNITICMSEFETIVO numeric(15,6);
declare variable WICMSOPPRESUMIDO numeric(15,6);
declare variable WICMSSTPRESUMIDO numeric(15,6);
declare variable WVLRRESTITUIR numeric(15,6);
declare variable WVLRCOMPLEMENTAR numeric(15,6);
declare variable WMODELO integer;
declare variable WSERIE integer;
declare variable WCHAVENFE varchar(60);
declare variable WDTEMISSAO date;
declare variable WNUMDOC integer;
declare variable WCHAVEC113 integer;
declare variable WCODUNIMED integer;
declare variable WVLRUNITFCPESTOQUE numeric(15,6);
declare variable WVLRUNITICMSOP numeric(15,6);
declare variable WVLRUNITFCPRESTITUIR numeric(15,6);
declare variable WVLRUNITFCPCOMPLEMENTAR numeric(15,6);
declare variable WRESPRETENCAO integer;
declare variable WCODARRECADACAO integer;
declare variable WBCUNITICMSST numeric(15,6);
declare variable WVLRUNITFCPST numeric(15,6);
declare variable WORDEMPRODDEV integer;
declare variable WREFERENCIA integer;
BEGIN
    /*INSERE REGISTROS NAS TABELAS FÍSICAS DOS LANÇAMENTOS*/

    /*VAI DELETAR ANTES OS REGISTROS, POR QUE SE TIVER ALGUM DA IMPORTAÇÃO ELE VAI SER SUBSTITUÍDO - OS VINCULADOS NA TOL JÁ FORAM EXCLUÍDOS
    TEM O PARÂMETRO DE NÃO RECALCULAR, ENTÃO SE CHEGOU AQUI É PORQUE DEVE SIM SER RECALCULADO */
    DELETE FROM VEF_EMP_TMOVC185_1250 C185
    WHERE C185.BDCODEMP = :PRCODEMP
    AND COALESCE(C185.BDTIPOLANCAMENTO,0) <> 141
    AND EXISTS (SELECT FIRST 1 BDCODEMP FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP TC185
                  WHERE TC185.BDCODEMP = C185.BDCODEMP AND TC185.BDCHAVE = C185.BDCHAVE AND TC185.BDCODPERIODO = 7
                  AND TC185.BDORDEM = C185.BDORDEM AND TC185.BDORDEMPROD = C185.BDORDEMPRO
                  AND TC185.BDSESSAO = :PRSESSAO AND TC185.BDREFERENCIA = :PRREF
                  AND TC185.BDREG = 'C185');

    DELETE FROM VEF_EMP_TMOVC380_1250 C380
    WHERE C380.BDCODEMP = :PRCODEMP
    AND COALESCE(C380.BDTIPOLANCAMENTO,0) <> 141
    AND EXISTS (SELECT FIRST 1 BDCODEMP FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP T
                  WHERE T.BDCODEMP = C380.BDCODEMP AND T.BDCHAVE = C380.BDCHAVE AND T.BDCODPERIODO = 7
                  AND T.BDORDEM = C380.BDORDEM AND T.BDORDEMPROD = C380.BDORDEMPRO
                  AND T.BDSESSAO = :PRSESSAO AND T.BDREFERENCIA = :PRREF
                  AND T.BDREG = 'C380');

    DELETE FROM VEF_EMP_TMOVC480_1250 C480
    WHERE C480.BDCODEMP = :PRCODEMP
    AND COALESCE(C480.BDTIPOLANCAMENTO,0) <> 141
    AND EXISTS (SELECT FIRST 1 BDCODEMP FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP T
                  WHERE T.BDCODEMP = C480.BDCODEMP AND T.BDCHAVE = C480.BDCHAVE AND T.BDCODPERIODO = 7
                  AND T.BDORDEM = C480.BDORDEMDOCECF AND T.BDORDEMPROD = C480.BDORDEMITEM
                  AND T.BDSESSAO = :PRSESSAO AND T.BDREFERENCIA = :PRREF
                  AND T.BDREG = 'C480');

    UPDATE VEF_EMP_TMOVC180_1250 C180 SET
    BDCODARRECADACO      = NULL,
    BDQTDCONVERTIDA      = NULL,
    BDVLRUNICONVERTIDO   = NULL,
    BDVLRUNITICMSST      = NULL,
    BDBCUNITICMSST       = NULL,
    BDVLRUNITICMSOP      = NULL,
    BDVLRUNITFCPST       = NULL
    WHERE C180.BDCODEMP = :PRCODEMP
    AND COALESCE(C180.BDTIPOLANCAMENTO,0) <> 141
    AND EXISTS (SELECT FIRST 1 BDCODEMP FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP T
                  WHERE T.BDCODEMP = C180.BDCODEMP AND T.BDCHAVE = C180.BDCHAVE AND T.BDCODPERIODO = 7
                  AND T.BDORDEM = C180.BDORDEM AND T.BDORDEMPROD = C180.BDORDEMPRO
                  AND T.BDSESSAO = :PRSESSAO AND T.BDREFERENCIA = :PRREF
                  AND T.BDREG = 'C180');

    DELETE FROM VEF_EMP_TMOVC186_1250 C186
    WHERE C186.BDCODEMP = :PRCODEMP
    AND COALESCE(C186.BDTIPOLANCAMENTO,0) <> 141
    AND EXISTS (SELECT FIRST 1 BDCODEMP FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP T
                  WHERE T.BDCODEMP = C186.BDCODEMP AND T.BDCHAVE = C186.BDCHAVE AND T.BDCODPERIODO = 7
                  AND T.BDORDEM = C186.BDORDEM AND T.BDORDEMPROD = C186.BDORDEMPRO
                  AND T.BDSESSAO = :PRSESSAO AND T.BDREFERENCIA = :PRREF
                  AND T.BDREG = 'C186');

    /*Como as informações da referenciada vem da tela, no caso das reduções Z, a gente não pode excluir o lançamento*/
    UPDATE VEF_EMP_TMOVC181_1250 C181 SET
    BDQTDCONVERTIDA              = NULL,
    BDVLRUNICONVERTIDO           = NULL,
    BDVLRUNITICMSEFETIVO         = NULL,
    BDVLRUNITICMSOPESTOQUE       = NULL,
    BDVLRUNITICMSSTESTOQUE       = NULL,
    BDVLRUNITICMSSTRESTITUIR     = NULL,
    BDVLRUNITICMSSTCOMPLEMENTAR  = NULL,
    BDCODUNIMED                  = NULL,
    BDVLRUNITICMSOP              = NULL,
    BDVLRUNITFCPSTESTOQUE        = NULL,
    BDVLRUNITFCPSTRESTITUIR      = NULL,
    BDVLRUNITFCPSTCOMPLEMENTAR   = NULL
    WHERE C181.BDCODEMP = :PRCODEMP
    AND COALESCE(C181.BDTIPOLANCAMENTO,0) <> 141
    AND EXISTS (SELECT FIRST 1 BDCODEMP FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP T
                  WHERE T.BDCODEMP = C181.BDCODEMP AND T.BDCHAVE = C181.BDCHAVE AND T.BDCODPERIODO = 7
                  AND T.BDORDEM = C181.BDORDEM AND T.BDORDEMPROD = C181.BDORDEMPRO
                  AND T.BDSESSAO = :PRSESSAO AND T.BDREFERENCIA = :PRREF
                  AND T.BDREG = 'C181');

    /*-----------INSERÇÃO-------------*/

    /*C185 - SAÍDA*/
    INSERT INTO VEF_EMP_TMOVC185_1250 (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODPROD, BDCODMOTIVO, BDQTDCONVERTIDA, BDVLRUNICONVERTIDO,
                                       BDVLRUNITICMSEFETIVO, BDVLRUNITICMSOPESTOQUE, BDVLRUNITICMSSTESTOQUE, BDVLRUNITICMSSTRESTITUIR, BDVLRUNITICMSSTCOMPLEMENTAR,
                                       BDCODUNIMED, BDVLRUNITICMSOP, BDVLRUNITFCPSTESTOQUE, BDVLRUNITFCPSTRESTITUIR, BDVLRUNITFCPSTCOMPLEMENTAR, BDTIPOLANCAMENTO)
    SELECT C185.BDCODEMP, C185.BDCHAVE, C185.BDORDEM,C185.BDORDEMPROD, C185.BDCODPROD, FC185.BDMOTIVO, C185.BDQUANTIDADE, C185.BDVLRUNITICMS,
           C185.BDVLRUNITICMSEFETIVO, FC185.BDICMSOPPRESUMIDO, IIF(SUBSTRING(INFAD.BDCODAJUR FROM 1 FOR 3) = 'RS0',0,C185.BDICMSSTPRESUMIDO) BDICMSSTPRESUMIDO,FC185.BDVLRRESTITUIR, FC185.BDVLRCOMPLEMENTAR,
           VINC.BDCODUNIMED, IIF(INFAD.BDCODAJUR IN ('RS212','RS211','RS215'),FC185.BDICMSOPPRESUMIDO,0) BDVLRUNITICMSOP,
           ((FC185.BDICMSSTPRESUMIDO*(C185.BDALIQFCP/100))/(IIF(VINC.BDALIQICMS > 0,(VINC.BDALIQICMS/100),(UF.BDALIQINT/100))+(C185.BDALIQFCP/100)))  BDVLRUNITFCPSTESTOQUE,
           IIF(FC185.BDVLRRESTITUIR > 0,(FC185.BDVLRRESTITUIR*(C185.BDALIQFCP/100))/(IIF(VINC.BDALIQICMS > 0,(VINC.BDALIQICMS/100),(UF.BDALIQINT/100))+(C185.BDALIQFCP/100)),0) BDVLRUNITFCPSTRESTITUIR,
           IIF(FC185.BDVLRCOMPLEMENTAR > 0,(FC185.BDVLRCOMPLEMENTAR*(C185.BDALIQFCP/100))/(IIF(VINC.BDALIQICMS > 0,(VINC.BDALIQICMS/100),(UF.BDALIQINT/100))+(C185.BDALIQFCP/100)),0) BDVLRUNITFCPSTCOMPLEMENTAR,
           141
    FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP C185
    LEFT OUTER JOIN VEF_EMP_TICMSSPED_1250_C185 FC185 ON (FC185.BDCODEMP = C185.BDCODEMP AND FC185.BDCODPERIODO = C185.BDCODPERIODO AND FC185.BDREFERENCIA = C185.BDREFERENCIA AND FC185.BDCHAVE = C185.BDCHAVE AND FC185.BDORDEM = C185.BDORDEM AND FC185.BDORDEMPROD = C185.BDORDEMPROD)
    LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = C185.BDCODEMP AND VINC.BDCODPROD = C185.BDCODPROD)
    LEFT OUTER JOIN VEF_BASE_TTABINFAD57 INFAD ON (INFAD.BDORDEM57 = FC185.BDMOTIVO)
    LEFT OUTER JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = FC185.BDCODEMP)
    LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID)
    LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF)
    WHERE C185.BDCODEMP = :PRCODEMP AND C185.BDSESSAO = :PRSESSAO
    AND C185.BDREFERENCIA = :PRREF
    AND C185.BDREG = 'C185';

    /*TOL DO C185*/
    INSERT INTO TOL_VEF_EMP_TICMSSPED_C185(BDCODEMP,BDREFERENCIA,BDCODPERIODO, BDCHAVE, BDORDEM, BDORDEMPRO)
    SELECT C185.BDCODEMP, C185.BDREFERENCIA, 7, C185.BDCHAVE, C185.BDORDEM, C185.BDORDEMPROD
    FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP C185
    WHERE C185.BDCODEMP = :PRCODEMP AND C185.BDSESSAO = :PRSESSAO
    AND C185.BDREFERENCIA = :PRREF
    AND C185.BDREG = 'C185';

    /*C380 - SAÍDA*/
    INSERT INTO VEF_EMP_TMOVC380_1250 (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODPROD, BDCODMOTIVO, BDQTDCONVERTIDA, BDVLRUNICONVERTIDO,
                                       BDVLRUNITICMSEFETIVO, BDVLRUNITICMSOPESTOQUE, BDVLRUNITICMSSTESTOQUE, BDVLRUNITICMSSTRESTITUIR, BDVLRUNITICMSSTCOMPLEMENTAR,
                                       BDCODUNIMED, BDVLRUNITICMSOP, BDVLRUNITFCPSTESTOQUE, BDVLRUNITFCPSTRESTITUIR, BDVLRUNITFCPSTCOMPLEMENTAR, BDTIPOLANCAMENTO)
    SELECT C380.BDCODEMP, C380.BDCHAVE, C380.BDORDEM,C380.BDORDEMPROD, C380.BDCODPROD, FC380.BDMOTIVO, C380.BDQUANTIDADE, C380.BDVLRUNITICMS,
           C380.BDVLRUNITICMSEFETIVO, FC380.BDICMSOPPRESUMIDO, IIF(SUBSTRING(INFAD.BDCODAJUR FROM 1 FOR 3) = 'RS0',0,C380.BDICMSSTPRESUMIDO) BDICMSSTPRESUMIDO,FC380.BDVLRRESTITUIR, FC380.BDVLRCOMPLEMENTAR,
           VINC.BDCODUNIMED, IIF(INFAD.BDCODAJUR IN ('RS212','RS211','RS215'),FC380.BDICMSOPPRESUMIDO,0) BDVLRUNITICMSOP,
           ((FC380.BDICMSSTPRESUMIDO*(C380.BDALIQFCP/100))/(IIF(VINC.BDALIQICMS > 0,(VINC.BDALIQICMS/100),(UF.BDALIQINT/100))+(C380.BDALIQFCP/100)))  BDVLRUNITFCPSTESTOQUE,
           IIF(FC380.BDVLRRESTITUIR > 0,(FC380.BDVLRRESTITUIR*(C380.BDALIQFCP/100))/(IIF(VINC.BDALIQICMS > 0,(VINC.BDALIQICMS/100),(UF.BDALIQINT/100))+(C380.BDALIQFCP/100)),0) BDVLRUNITFCPSTRESTITUIR,
           IIF(FC380.BDVLRCOMPLEMENTAR > 0,(FC380.BDVLRCOMPLEMENTAR*(C380.BDALIQFCP/100))/(IIF(VINC.BDALIQICMS > 0,(VINC.BDALIQICMS/100),(UF.BDALIQINT/100))+(C380.BDALIQFCP/100)),0) BDVLRUNITFCPSTCOMPLEMENTAR,
           141
    FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP C380
    LEFT OUTER JOIN VEF_EMP_TICMSSPED_1250_C380 FC380 ON (FC380.BDCODEMP = C380.BDCODEMP AND FC380.BDCODPERIODO = C380.BDCODPERIODO AND FC380.BDREFERENCIA = C380.BDREFERENCIA AND FC380.BDCHAVE = C380.BDCHAVE AND FC380.BDORDEM = C380.BDORDEM AND FC380.BDORDEMPROD = C380.BDORDEMPROD)
    LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = C380.BDCODEMP AND VINC.BDCODPROD = C380.BDCODPROD)
    LEFT OUTER JOIN VEF_BASE_TTABINFAD57 INFAD ON (INFAD.BDORDEM57 = FC380.BDMOTIVO)
    LEFT OUTER JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = FC380.BDCODEMP)
    LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID)
    LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF)
    WHERE C380.BDCODEMP = :PRCODEMP AND C380.BDSESSAO = :PRSESSAO
    AND C380.BDREFERENCIA = :PRREF
    AND C380.BDREG = 'C380';

    /*TOL DO C380*/
    INSERT INTO TOL_VEF_EMP_TICMSSPED_C380(BDCODEMP,BDREFERENCIA,BDCODPERIODO, BDCHAVE, BDORDEM, BDORDEMPRO)
    SELECT C380.BDCODEMP, C380.BDREFERENCIA, 7, C380.BDCHAVE, C380.BDORDEM, C380.BDORDEMPROD
    FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP C380
    WHERE C380.BDCODEMP = :PRCODEMP AND C380.BDSESSAO = :PRSESSAO
    AND C380.BDREFERENCIA = :PRREF
    AND C380.BDREG = 'C380';

    /*C480 - REDUÇÃO Z*/
    INSERT INTO VEF_EMP_TMOVC480_1250 (BDCODEMP, BDCHAVE, BDORDEMDOCECF, BDORDEMITEM, BDCODMOTIVO, BDQTDCONVERTIDA,BDVLRUNICONVERTIDO,
                                       BDVLRUNITICMSEFETIVO, BDVLRUNITICMSOPESTOQUE, BDVLRUNITICMSSTESTOQUE, BDVLRUNITICMSSTRESTITUIR,BDVLRUNITICMSSTCOMPLEMENTAR, 
                                       BDCODUNIMED, BDVLRUNITICMSOP, BDTIPOLANCAMENTO)
    SELECT C480.BDCODEMP, C480.BDCHAVE, C480.BDORDEM,C480.BDORDEMPROD, FC480.BDMOTIVO, C480.BDQUANTIDADE, C480.BDVLRUNITICMS,
           C480.BDVLRUNITICMSEFETIVO, FC480.BDICMSOPPRESUMIDO, IIF(SUBSTRING(INFAD.BDCODAJUR FROM 1 FOR 3) = 'RS0',0,C480.BDICMSSTPRESUMIDO) BDICMSSTPRESUMIDO,FC480.BDVLRRESTITUIR, FC480.BDVLRCOMPLEMENTAR,
           VINC.BDCODUNIMED, IIF(INFAD.BDCODAJUR IN ('RS212','RS211','RS215'),FC480.BDICMSOPPRESUMIDO,0) BDVLRUNITICMSOP,141
    FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP C480
    LEFT OUTER JOIN VEF_EMP_TICMSSPED_1250_C480 FC480 ON (FC480.BDCODEMP = C480.BDCODEMP AND FC480.BDCODPERIODO = C480.BDCODPERIODO AND FC480.BDREFERENCIA = C480.BDREFERENCIA AND FC480.BDCHAVE = C480.BDCHAVE AND FC480.BDORDEM = C480.BDORDEM AND FC480.BDORDEMPROD = C480.BDORDEMPROD)
    LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = C480.BDCODEMP AND VINC.BDCODPROD = C480.BDCODPROD)
    LEFT OUTER JOIN VEF_BASE_TTABINFAD57 INFAD ON (INFAD.BDORDEM57 = FC480.BDMOTIVO)
    WHERE C480.BDCODEMP = :PRCODEMP AND C480.BDSESSAO = :PRSESSAO
    AND C480.BDREFERENCIA = :PRREF
    AND C480.BDREG = 'C480';

    /*TOL DO C480*/
    INSERT INTO TOL_VEF_EMP_TICMSSPED_C480(BDCODEMP,BDREFERENCIA,BDCODPERIODO, BDCHAVE, BDORDEMDOCECF, BDORDEMITEM)
    SELECT C480.BDCODEMP, C480.BDREFERENCIA, 7, C480.BDCHAVE, C480.BDORDEM, C480.BDORDEMPROD
    FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP C480
    WHERE C480.BDCODEMP = :PRCODEMP AND C480.BDSESSAO = :PRSESSAO
    AND C480.BDREFERENCIA = :PRREF
    AND C480.BDREG = 'C480';

    /*C180 - ENTRADA - FOI FEITO UPDATE PARA MANTER O CÓDIGO DE ARRECADAÇÃO*/
    FOR
        SELECT C180.BDCODEMP, C180.BDCHAVE, C180.BDORDEM,C180.BDORDEMPROD, C180.BDCODPROD,VINC.BDCODUNIMED,
                IIF(MC180.bdrespretencao is not null, MC180.bdrespretencao, IIF(SUBSTRING(ICMS.BDCSTICMS FROM 2 FOR 2) IN ('10','70'),0/*REM DIRETO*/,IIF(SUBSTRING(ICMS.BDCSTICMS FROM 2 FOR 2) = 60,1 /*REM IND*/,
                IIF(C180.BDVLRICMSSTNAORETIDO > 0,2/*PROP DECLARANTE*/,-1)))) BDRESPRETENCAO,
                IIF(SUBSTRING(FC180.BDCODNAT FROM 1 FOR 1) = 1, 0 , IIF((select first 1 TCON.BDCODEMP from VEF_EMP_TCONSUB TCON where TCON.BDCODUFCONSUB = C180.BDCODUFTER AND TCON.bdcodemp = :prcodemp) is null,1 ,0)) BDCODARRECADACO,
                C180.BDQUANTIDADE, C180.BDVLRUNIT,FC180.BDICMSSTPRESUMIDO BDVLRUNITICMSST, FC180.BDBCUNITICMSST,
                FC180.BDVLRUNITICMS BDVLRUNITICMSOP,(FC180.BDBCUNITICMSST*(C180.BDALIQFCP/100)) BDVLRUNITFCPST
        FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP C180
        LEFT OUTER JOIN VEF_EMP_TICMSSPED_1250_C180 FC180 ON (FC180.BDCODEMP = C180.BDCODEMP AND FC180.BDCODPERIODO = C180.BDCODPERIODO AND FC180.BDREFERENCIA = C180.BDREFERENCIA AND FC180.BDCHAVE = C180.BDCHAVE AND FC180.BDORDEM = C180.BDORDEM AND FC180.BDORDEMPROD = C180.BDORDEMPROD)
        LEFT OUTER JOIN VEF_EMP_TMOVC180_1250 MC180 ON (MC180.BDCODEMP = C180.BDCODEMP AND MC180.BDCHAVE = C180.BDCHAVE AND MC180.BDORDEM = C180.BDORDEM AND MC180.BDORDEMPRO = C180.BDORDEMPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = C180.BDCODEMP AND VINC.BDCODPROD = C180.BDCODPROD)
        LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = FC180.BDCSTICMS)
        LEFT OUTER JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = FC180.BDCODEMP)
        LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID)
        LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF)
        WHERE C180.BDCODEMP = :PRCODEMP AND C180.BDSESSAO = :PRSESSAO
        AND C180.BDREFERENCIA = :PRREF
        AND C180.BDREG = 'C180'
        INTO :WCODEMP,:WCHAVE,:WORDEM,:WORDEMPRO,:WCODPROD,:WCODUNIMED,:WRESPRETENCAO,:WCODARRECADACAO, :WQUANTIDADE,:WVLRUNIT,:WICMSSTPRESUMIDO,
             :WBCUNITICMSST,:WVLRUNITICMSOP,:WVLRUNITFCPST
    DO
      BEGIN
         UPDATE OR INSERT INTO VEF_EMP_TMOVC180_1250 (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODPROD, BDCODUNIMED, BDRESPRETENCAO, BDCODARRECADACO,BDQTDCONVERTIDA,
                                                      BDVLRUNICONVERTIDO, BDVLRUNITICMSST, BDBCUNITICMSST, BDVLRUNITICMSOP, BDVLRUNITFCPST, BDTIPOLANCAMENTO)
         VALUES (:WCODEMP, :WCHAVE,:WORDEM,:WORDEMPRO,:WCODPROD,:WCODUNIMED,:WRESPRETENCAO,:WCODARRECADACAO,:WQUANTIDADE,:WVLRUNIT,:WICMSSTPRESUMIDO,
                :WBCUNITICMSST,:WVLRUNITICMSOP,:WVLRUNITFCPST,141)
                 MATCHING (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO);
      END

    /*TOL DO C180*/
    INSERT INTO TOL_VEF_EMP_TICMSSPED_C180(BDCODEMP,BDREFERENCIA,BDCODPERIODO, BDCHAVE, BDORDEM, BDORDEMPRO)
    SELECT C180.BDCODEMP, C180.BDREFERENCIA, 7, C180.BDCHAVE, C180.BDORDEM, C180.BDORDEMPROD
    FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP C180
    WHERE C180.BDCODEMP = :PRCODEMP AND C180.BDSESSAO = :PRSESSAO
    AND C180.BDREFERENCIA = :PRREF
    AND C180.BDREG = 'C180';


    /*C186 - DEVOLUÇÃO SAÍDA - Registro na ENTRADA*/
   INSERT INTO VEF_EMP_TMOVC186_1250 (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODPROD, BDCODMOTIVO, BDQTDCONVERTIDA, BDVLRUNICONVERTIDO, BDVLRUNITICMSST,
                                      BDBCUNITICMSST,BDVLRUNITICMSOP, BDVLRUNITFCPST, BDCODUNIMED, BDMODELO, BDSERIE, BDCHAVENFE, BDDTEMISSAO, BDNUMDOC,
                                      BDTIPOLANCAMENTO,BDORDEMPRODORIG)
    SELECT  C186.BDCODEMP, C186.BDCHAVE, C186.BDORDEM,C186.BDORDEMPROD,C186.BDCODPROD, FC186.BDMOTIVO, FC186.BDQUANTIDADE,
            C186.BDVLRUNIT, FC186.BDICMSSTPRESUMIDO, C186.BDBCUNITICMS,C186.BDVLRUNITICMS, MOV.BDVLRUNITFCPST,VINC.BDCODUNIMED,
            MOVM.BDMODELO, C113.BDSERIE, C113.BDCHAVENFE, C113.BDDTEMISSAO, C113.BDNUMDOC,141, C186.BDORDEMPRODEV
    FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP C186
    LEFT OUTER JOIN VEF_EMP_TICMSSPED_1250_C186 FC186 ON (FC186.BDCODEMP = C186.BDCODEMP AND FC186.BDCODPERIODO = C186.BDCODPERIODO AND FC186.BDREFERENCIA = C186.BDREFERENCIA AND FC186.BDCHAVE = C186.BDCHAVE AND FC186.BDORDEM = C186.BDORDEM AND FC186.BDORDEMPROD = C186.BDORDEMPROD)
    LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = C186.BDCODEMP AND VINC.BDCODPROD = C186.BDCODPROD)
    LEFT OUTER JOIN VEF_BASE_TTABCSTICMS ICMS ON (ICMS.BDCODCSTICMS = FC186.BDCSTICMS)
    LEFT OUTER JOIN VEF_EMP_TMOVSAIDOCFREF C113 ON (C113.BDCODEMP = C186.BDCODEMP AND C113.BDCHAVE = C186.BDCHAVE)
    LEFT OUTER JOIN VEF_BASE_TTABDOCFIS C113M ON (C113.BDCODDOCFIS = C113M.BDCODDOCFIS)
    LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MOVM ON (MOVM.BDMODELOSTR = C113M.BDDOCFIS)
    LEFT OUTER JOIN VEF_EMP_TMOVC180_1250 MOV ON (MOV.BDCODEMP = C186.BDCODEMP AND MOV.BDCHAVE = C186.BDCHAVEDEV AND MOV.BDORDEM = C186.BDORDEMDEV AND MOV.BDORDEMPRO = C186.BDORDEMPRODEV)
    WHERE C186.BDCODEMP = :PRCODEMP AND C186.BDSESSAO = :PRSESSAO
    AND C186.BDREFERENCIA = :PRREF
    AND C186.BDREG = 'C186';

    /*TOL DO C186*/
    INSERT INTO TOL_VEF_EMP_TICMSSPED_C186(BDCODEMP,BDREFERENCIA,BDCODPERIODO, BDCHAVE, BDORDEM, BDORDEMPRO)
    SELECT C186.BDCODEMP, C186.BDREFERENCIA, 7, C186.BDCHAVE, C186.BDORDEM, C186.BDORDEMPROD
    FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP C186
    WHERE C186.BDCODEMP = :PRCODEMP AND C186.BDSESSAO = :PRSESSAO
    AND C186.BDREFERENCIA = :PRREF
    AND C186.BDREG = 'C186';

    /*C181 - A GENTE TEM QUE INSERE OU DAR UPDATE - PORQUE O CLIENTE PODE TER INFORMADO A NOTA REFERENCIADA DA REDUÇÃO Z NA MÃO OU PELA IMPORTAÇÃO
     AI A GENTE NÃO PODE PERDER ESSA INFORMAÇÃO - LEMBRANDO QUE O CLIENTE NÃO TERIA INFORMAÇÃO NO C113 NESSE CASO, ENTÃO SE TIVER DADOS DO C113
     NA NOTA, A GENTE VAI INFORMAR ESSES
     A EXCLUSÃO PELA TOL, TBM SERÁ APENAS APAGADO OS CAMPOS DE VALORES*/

     FOR
        SELECT C181.BDCODEMP,C181.BDREFERENCIA, C181.BDCHAVE, C181.BDORDEM,C181.BDORDEMPROD,C181.BDCODPROD,
        C181.BDMOTIVO, C181.BDQUANTIDADE,MOV.BDVLRUNICONVERTIDO, C181.BDVLRUNITICMSEFETIVO,
        C181.BDICMSOPPRESUMIDO,C181.BDICMSSTPRESUMIDO, C181.BDVLRRESTITUIR, C181.BDVLRCOMPLEMENTAR, VINC.BDCODUNIMED,
        MOV.BDVLRUNITFCPSTESTOQUE, MOV.BDVLRUNITICMSOP,MOV.BDVLRUNITFCPSTCOMPLEMENTAR, MOV.BDVLRUNITFCPSTRESTITUIR,
        MOVM.BDMODELO, C113.BDSERIE, C113.BDCHAVENFE, C113.BDDTEMISSAO, C113.BDNUMDOC, C113.BDCHAVE BDCHAVEC113, C181.BDORDEMPRODEV
        FROM (
             SELECT C181.BDCODEMP,C181.BDREFERENCIA, C181.BDCHAVE, C181.BDORDEM,C181.BDORDEMPROD,C181.BDCODPROD,
                    FC181.BDMOTIVO, FC181.BDQUANTIDADE, C181.BDCHAVEDEV,C181.BDORDEMDEV, C181.BDORDEMPRODEV,
                    FC181.BDVLRUNITICMSEFETIVO,C181.BDICMSOPPRESUMIDO,C181.BDICMSSTPRESUMIDO, C181.BDVLRRESTITUIR,C181.BDVLRCOMPLEMENTAR
                    FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP C181
                    LEFT OUTER JOIN VEF_EMP_TICMSSPED_1250_C181 FC181 ON (FC181.BDCODEMP = C181.BDCODEMP AND FC181.BDCODPERIODO = C181.BDCODPERIODO AND FC181.BDREFERENCIA = C181.BDREFERENCIA AND FC181.BDCHAVE = C181.BDCHAVE AND FC181.BDORDEM = C181.BDORDEM AND FC181.BDORDEMPROD = C181.BDORDEMPROD)
                    WHERE C181.BDCODEMP = :PRCODEMP AND C181.BDSESSAO = :PRSESSAO
                    AND C181.BDREFERENCIA = :PRREF AND  C181.BDREG = 'C181'
                    AND C181.BDVERIFICLANANTDEV = 'FALSE'
              ) C181
        JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = C181.BDCODEMP AND C113.BDCHAVE = C181.BDCHAVE)
        JOIN VEF_EMP_TMOVC185_1250 MOV ON (MOV.BDCODEMP = C181.BDCODEMP  AND MOV.BDCODPROD = C181.BDCODPROD AND MOV.BDCHAVE = C181.BDCHAVEDEV AND MOV.BDORDEM = C181.BDORDEMDEV AND MOV.BDORDEMPRO = C181.BDORDEMPRODEV)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = C181.BDCODEMP AND VINC.BDCODPROD = C181.BDCODPROD)
        LEFT OUTER JOIN VEF_BASE_TTABDOCFIS C113M ON (C113.BDCODDOCFIS = C113M.BDCODDOCFIS)
        LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MOVM ON (MOVM.BDMODELOSTR = C113M.BDDOCFIS)
        UNION ALL
        SELECT C181.BDCODEMP,C181.BDREFERENCIA, C181.BDCHAVE, C181.BDORDEM,C181.BDORDEMPROD,C181.BDCODPROD,
               C181.BDMOTIVO, C181.BDQUANTIDADE,MOV.BDVLRUNICONVERTIDO, C181.BDVLRUNITICMSEFETIVO,
               C181.BDICMSOPPRESUMIDO,C181.BDICMSSTPRESUMIDO, C181.BDVLRRESTITUIR, C181.BDVLRCOMPLEMENTAR, VINC.BDCODUNIMED,
               MOV.BDVLRUNITFCPSTESTOQUE, MOV.BDVLRUNITICMSOP,MOV.BDVLRUNITFCPSTCOMPLEMENTAR, MOV.BDVLRUNITFCPSTRESTITUIR,
               MOVM.BDMODELO, C113.BDSERIE, C113.BDCHAVENFE, C113.BDDTEMISSAO, C113.BDNUMDOC, C113.BDCHAVE BDCHAVEC113, C181.BDORDEMPRODEV
         FROM (
               SELECT C181.BDCODEMP,C181.BDREFERENCIA, C181.BDCHAVE, C181.BDORDEM,C181.BDORDEMPROD,C181.BDCODPROD,
                      FC181.BDMOTIVO, FC181.BDQUANTIDADE, C181.BDCHAVEDEV,C181.BDORDEMDEV, C181.BDORDEMPRODEV,
                      FC181.BDVLRUNITICMSEFETIVO,C181.BDICMSOPPRESUMIDO,C181.BDICMSSTPRESUMIDO, C181.BDVLRRESTITUIR,C181.BDVLRCOMPLEMENTAR
                       FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP C181
                       LEFT OUTER JOIN VEF_EMP_TICMSSPED_1250_C181 FC181 ON (FC181.BDCODEMP = C181.BDCODEMP AND FC181.BDCODPERIODO = C181.BDCODPERIODO AND FC181.BDREFERENCIA = C181.BDREFERENCIA AND FC181.BDCHAVE = C181.BDCHAVE AND FC181.BDORDEM = C181.BDORDEM AND FC181.BDORDEMPROD = C181.BDORDEMPROD)
                       WHERE C181.BDCODEMP = :PRCODEMP AND C181.BDSESSAO = :PRSESSAO
                       AND C181.BDREFERENCIA = :PRREF AND  C181.BDREG = 'C181'
                       AND C181.BDVERIFICLANANTDEV = 'FALSE'
                ) C181
        LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = C181.BDCODEMP AND C113.BDCHAVE = C181.BDCHAVE)
        JOIN VEF_EMP_TMOVC380_1250 MOV ON (MOV.BDCODEMP = C181.BDCODEMP  AND MOV.BDCODPROD = C181.BDCODPROD AND MOV.BDCHAVE = C181.BDCHAVEDEV AND MOV.BDORDEM = C181.BDORDEMDEV AND MOV.BDORDEMPRO = C181.BDORDEMPRODEV)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = C181.BDCODEMP AND VINC.BDCODPROD = C181.BDCODPROD)
        LEFT OUTER JOIN VEF_BASE_TTABDOCFIS C113M ON (C113.BDCODDOCFIS = C113M.BDCODDOCFIS)
        LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MOVM ON (MOVM.BDMODELOSTR = C113M.BDDOCFIS)
        UNION ALL
        SELECT C181.BDCODEMP,C181.BDREFERENCIA, C181.BDCHAVE, C181.BDORDEM,C181.BDORDEMPROD,C181.BDCODPROD,
               C181.BDMOTIVO, C181.BDQUANTIDADE,MOV.BDVLRUNICONVERTIDO, C181.BDVLRUNITICMSEFETIVO,
               C181.BDICMSOPPRESUMIDO,C181.BDICMSSTPRESUMIDO,C181.BDVLRRESTITUIR,C181.BDVLRCOMPLEMENTAR,VINC.BDCODUNIMED,
               MOV.BDVLRUNITFCPSTESTOQUE, MOV.BDVLRUNITICMSOP,MOV.BDVLRUNITFCPSTCOMPLEMENTAR,MOV.BDVLRUNITFCPSTRESTITUIR,
               MOVM.BDMODELO, C113.BDSERIE, C113.BDCHAVENFE, C113.BDDTEMISSAO, C113.BDNUMDOC, C113.BDCHAVE BDCHAVEC113, C181.BDORDEMPRODEV
         FROM (
               SELECT C181.BDCODEMP,C181.BDREFERENCIA, C181.BDCHAVE, C181.BDORDEM,C181.BDORDEMPROD,C181.BDCODPROD,
                      FC181.BDMOTIVO, FC181.BDQUANTIDADE, C181.BDCHAVEDEV,C181.BDORDEMDEV, C181.BDORDEMPRODEV,
                      FC181.BDVLRUNITICMSEFETIVO,C181.BDICMSOPPRESUMIDO,C181.BDICMSSTPRESUMIDO, C181.BDVLRRESTITUIR,C181.BDVLRCOMPLEMENTAR
                      FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP C181
                      LEFT OUTER JOIN VEF_EMP_TICMSSPED_1250_C181 FC181 ON (FC181.BDCODEMP = C181.BDCODEMP AND FC181.BDCODPERIODO = C181.BDCODPERIODO AND FC181.BDREFERENCIA = C181.BDREFERENCIA AND FC181.BDCHAVE = C181.BDCHAVE AND FC181.BDORDEM = C181.BDORDEM AND FC181.BDORDEMPROD = C181.BDORDEMPROD)
                      WHERE C181.BDCODEMP = :PRCODEMP AND C181.BDSESSAO = :PRSESSAO
                      AND C181.BDREFERENCIA = :PRREF AND  C181.BDREG = 'C181'
                      AND C181.BDVERIFICLANANTDEV = 'FALSE'
              ) C181
        LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = C181.BDCODEMP AND C113.BDCHAVE = C181.BDCHAVE)
        JOIN VEF_EMP_TMOVC480_1250 MOV ON (MOV.BDCODEMP = C181.BDCODEMP AND MOV.BDCHAVE = C181.BDCHAVEDEV AND MOV.BDORDEMDOCECF = C181.BDORDEMDEV AND MOV.BDORDEMITEM = C181.BDORDEMPRODEV)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = C181.BDCODEMP AND VINC.BDCODPROD = C181.BDCODPROD)
        LEFT OUTER JOIN VEF_BASE_TTABDOCFIS C113M ON (C113.BDCODDOCFIS = C113M.BDCODDOCFIS)
        LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MOVM ON (MOVM.BDMODELOSTR = C113M.BDDOCFIS)
        UNION ALL
        SELECT C181.BDCODEMP,C181.BDREFERENCIA, C181.BDCHAVE, C181.BDORDEM,C181.BDORDEMPROD,C181.BDCODPROD,
        C181.BDMOTIVO, C181.BDQUANTIDADE,C181.BDVLRUNIT,C181.BDVLRUNITICMSEFETIVO,
        C181.BDICMSOPPRESUMIDO,C181.BDICMSSTPRESUMIDO,C181.BDVLRRESTITUIR,C181.BDVLRCOMPLEMENTAR,
        VINC.BDCODUNIMED, IIF(C181.BDREG = 'C480',0,((C181.BDICMSSTPRESUMIDO*(C181.BDALIQFCP/100))/(IIF(VINC.BDALIQICMS > 0,(VINC.BDALIQICMS/100),(UF.BDALIQINT/100))+(C181.BDALIQFCP/100)))) BDVLRUNITFCPSTESTOQUE,
        C181.BDICMSOPPRESUMIDO BDVLRUNITICMSOP, IIF(C181.BDREG = 'C480',0,IIF(C181.BDVLRCOMPLEMENTAR > 0 , (C181.BDVLRCOMPLEMENTAR*C181.BDALIQFCP/100)/((IIF(VINC.BDALIQICMS > 0,(VINC.BDALIQICMS/100),(UF.BDALIQINT/100)))+(C181.BDALIQFCP/100)) ,0)) BDVLRUNITFCPSTCOMPLEMENTAR ,
        IIF(C181.BDREG = 'C480',0,IIF(C181.BDVLRRESTITUIR > 0 , (C181.BDVLRRESTITUIR*C181.BDALIQFCP/100)/((IIF(VINC.BDALIQICMS > 0,(VINC.BDALIQICMS/100),(UF.BDALIQINT/100)))+(C181.BDALIQFCP/100)) ,0))  BDVLRUNITFCPSTRESTITUIR,
        MOVM.BDMODELO, C113.BDSERIE, C113.BDCHAVENFE, C113.BDDTEMISSAO, C113.BDNUMDOC, C113.BDCHAVE BDCHAVEC113, C181.BDORDEMPRODEV
        FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP C181
        LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = C181.BDCODEMP AND C113.BDCHAVE = C181.BDCHAVE)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = C181.BDCODEMP AND VINC.BDCODPROD = C181.BDCODPROD)
        LEFT OUTER JOIN VEF_BASE_TTABDOCFIS C113M ON (C113.BDCODDOCFIS = C113M.BDCODDOCFIS)
        LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MOVM ON (MOVM.BDMODELOSTR = C113M.BDDOCFIS)
        LEFT OUTER JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = C181.BDCODEMP)
        LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID)
        LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF)
        WHERE C181.BDCODEMP = :PRCODEMP AND C181.BDSESSAO = :PRSESSAO
        AND C181.BDREFERENCIA = :PRREF AND  C181.BDREG = 'C181'
        AND C181.BDVERIFICLANANTDEV = 'TRUE'
        INTO :WCODEMP,:WREFERENCIA ,:WCHAVE,:WORDEM,:WORDEMPRO,:WCODPROD,:WMOTIVO,:WQUANTIDADE,:WVLRUNIT,:WVLRUNITICMSEFETIVO,:WICMSOPPRESUMIDO,:WICMSSTPRESUMIDO,
             :WVLRRESTITUIR,:WVLRCOMPLEMENTAR,:WCODUNIMED,:WVLRUNITFCPESTOQUE, :WVLRUNITICMSOP, :WVLRUNITFCPRESTITUIR, :WVLRUNITFCPCOMPLEMENTAR,
             :WMODELO,:WSERIE,:WCHAVENFE,:WDTEMISSAO,:WNUMDOC,:WCHAVEC113,:WORDEMPRODDEV
     DO
       BEGIN
         IF (COALESCE(WCHAVEC113,0) > 0) THEN
            BEGIN
              UPDATE OR INSERT INTO VEF_EMP_TMOVC181_1250 (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODPROD, BDCODMOTIVO, BDQTDCONVERTIDA, BDVLRUNICONVERTIDO,
                                                           BDVLRUNITICMSEFETIVO, BDVLRUNITICMSOPESTOQUE, BDVLRUNITICMSSTESTOQUE, BDVLRUNITICMSSTRESTITUIR, BDVLRUNITICMSSTCOMPLEMENTAR,
                                                           BDCODUNIMED, BDVLRUNITICMSOP, BDVLRUNITFCPSTESTOQUE, BDVLRUNITFCPSTRESTITUIR, BDVLRUNITFCPSTCOMPLEMENTAR, BDMODELO, BDSERIE,
                                                           BDCHAVENFE, BDDTEMISSAO, BDNUMDOC, BDTIPOLANCAMENTO, BDORDEMPRODORIG)
              VALUES (:WCODEMP, :WCHAVE,:WORDEM,:WORDEMPRO,:WCODPROD,:WMOTIVO,:WQUANTIDADE,:WVLRUNIT,:WVLRUNITICMSEFETIVO,:WICMSOPPRESUMIDO,:WICMSSTPRESUMIDO,:WVLRRESTITUIR,:WVLRCOMPLEMENTAR,
                      :WCODUNIMED,:WVLRUNITICMSOP, :WVLRUNITFCPESTOQUE,:WVLRUNITFCPRESTITUIR, :WVLRUNITFCPCOMPLEMENTAR, :WMODELO,:WSERIE,:WCHAVENFE,:WDTEMISSAO,:WNUMDOC,141,:WORDEMPRODDEV)
              MATCHING (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO);
            END
         ELSE
            BEGIN
              UPDATE OR INSERT INTO VEF_EMP_TMOVC181_1250 (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODPROD, BDCODMOTIVO, BDQTDCONVERTIDA, BDVLRUNICONVERTIDO,
                                                           BDVLRUNITICMSEFETIVO, BDVLRUNITICMSOPESTOQUE, BDVLRUNITICMSSTESTOQUE, BDVLRUNITICMSSTRESTITUIR, BDVLRUNITICMSSTCOMPLEMENTAR,
                                                           BDCODUNIMED, BDVLRUNITICMSOP, BDVLRUNITFCPSTESTOQUE, BDVLRUNITFCPSTRESTITUIR, BDVLRUNITFCPSTCOMPLEMENTAR,BDTIPOLANCAMENTO,BDORDEMPRODORIG)
              VALUES (:WCODEMP, :WCHAVE,:WORDEM,:WORDEMPRO,:WCODPROD,:WMOTIVO,:WQUANTIDADE,:WVLRUNIT,:WVLRUNITICMSEFETIVO,:WICMSOPPRESUMIDO,:WICMSSTPRESUMIDO,:WVLRRESTITUIR,:WVLRCOMPLEMENTAR,
                      :WCODUNIMED,:WVLRUNITICMSOP, :WVLRUNITFCPESTOQUE,:WVLRUNITFCPRESTITUIR, :WVLRUNITFCPCOMPLEMENTAR,141,:WORDEMPRODDEV)
              MATCHING (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMPRO);
            END
       END

    /*TOL DO C181*/
    INSERT INTO TOL_VEF_EMP_TICMSSPED_C181(BDCODEMP,BDREFERENCIA,BDCODPERIODO, BDCHAVE, BDORDEM, BDORDEMPRO)
    SELECT C181.BDCODEMP, C181.BDREFERENCIA, 7, C181.BDCHAVE, C181.BDORDEM, C181.BDORDEMPROD
    FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP C181
    WHERE C181.BDCODEMP = :PRCODEMP AND C181.BDSESSAO = :PRSESSAO
    AND C181.BDREFERENCIA = :PRREF
    AND C181.BDREG = 'C181';


END^

CREATE OR ALTER PROCEDURE SP_REGISTROS_PLANO_1250 (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS
BEGIN
     /*Registro C185 - SAÍDA*/
      INSERT INTO TMP_VEF_EMP_TICMSSPED_1250_TEMP(BDSESSAO,BDCODEMP,BDCODPERIODO,BDREFERENCIA,BDCHAVE,BDORDEM,BDORDEMPROD,BDCODPROD,BDCSTICMS,BDCODNAT,BDMOTIVO,BDQUANTIDADE,BDVLRUNITICMS,
                                                  BDVLRUNITICMSEFETIVO,BDREG, BDDATALAN,BDALIQFCP,BDNUMDOCINI,BDVLRFRETE,BDVLRSEGURO,BDVLRDESPACESSORIA,BDVLRDESC,BDREDBCICMS)
       SELECT :PRSESSAO,PRO.BDCODEMP,7, PRO.BDREFERENCIA, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO,PRO.BDCODPROD, PRO.BDCODCSTICMS, PRO.BDCODNAT,PRO.BDMOTIVO,
              PRO.BDQTDITEM, ((COALESCE(PRO.BDVLRITEM,0) - COALESCE(PRO.BDVLRABATNT,0) - COALESCE(PRO.BDVLRDESC,0) + COALESCE(PRO.BDVLRFRETE,0) + COALESCE(PRO.BDVLRDESPACESSORIA,0) + COALESCE(PRO.BDVLRSEGURO, 0)) / PRO.BDQTDITEM)  BDVLRUNIT, (PRO.BDVLRUNITICMSEFETIVO/PRO.BDQTDITEM) BDVLRUNITICMSEFETIVO,
              'C185', PRO.BDDATAEMISSAO, PRO.BDALIQST, PRO.BDNUMDOCINI, PRO.BDVLRFRETE, PRO.BDVLRSEGURO, PRO.BDVLRDESPACESSORIA, PRO.BDVLRDESC, PRO.BDREDBCICMS
       FROM(
            SELECT PRO.BDCODEMP,SAI.BDREFERENCIA, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO,PRO.BDCODPROD, PRO.BDCODCSTICMS, I.BDCODNAT,SAI.BDMOTIVO,
            (COALESCE(PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1)) BDQTDITEM,PRO.BDVLRITEM,
            (PRO.BDVLRICMSEFET + PRO.BDVLRFCP) BDVLRUNITICMSEFETIVO, MOV.BDDATAEMISSAO,
            IIF(PRO.BDALIQFCPRETIDO > 0, PRO.BDALIQFCPRETIDO,PRO.BDALIQFCPSTRET) BDALIQST, MOV.BDNUMDOCINI, PRO.BDVLRABATNT, PRO.BDVLRDESC, PRO.BDVLRFRETE, PRO.BDVLRDESPACESSORIA, PRO.BDVLRSEGURO, PRO.BDREDBCICMS
            FROM (
                  SELECT *
                  FROM TMP_VEF_EMP_TMOVSAISTRS_TEMP SAI
                  WHERE SAI.BDCODEMP = :PRCODEMP AND
                        SAI.BDSESSAO = :PRSESSAO AND
                        SAI.BDREG    = 'SAI'
                  ) SAI
      LEFT OUTER JOIN VEF_EMP_TMOVSAI MOV ON (MOV.BDCODEMP = SAI.BDCODEMP AND MOV.BDCHAVE = SAI.BDCHAVE)
      LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDORDEM =  SAI.BDORDEM)
      JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDORDEM = I.BDORDEM AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEMPRO = SAI.BDORDEMPRO)
      LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MODE ON (MODE.BDMODELO = MOV.BDMODELO)
      LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
      LEFT OUTER JOIN VEF_BASE_TTABINFAD57 TAB ON (TAB.BDORDEM57 = SAI.BDMOTIVO)
      LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON)
      WHERE MOV.BDCODEMP = SAI.BDCODEMP
      AND MOV.BDREFLAN = SAI.BDREFERENCIA
      AND MODE.BDMODELOSTR IN ('01','1B','04','55','65')
      AND NAT.BDDEVOL = 'FALSE' AND
      MOV.BDCODSITNF NOT IN (2,3,4,5)
      ) PRO;

      /*Registro C380 - SAÍDA */
      INSERT INTO TMP_VEF_EMP_TICMSSPED_1250_TEMP(BDSESSAO,BDCODEMP,BDCODPERIODO,BDREFERENCIA,BDCHAVE,BDORDEM,BDORDEMPROD,BDCODPROD,BDCSTICMS,BDCODNAT,
                                               BDMOTIVO,BDQUANTIDADE,BDVLRUNITICMS,BDVLRUNITICMSEFETIVO,BDREG,BDDATALAN,BDALIQFCP,BDNUMDOCINI)
       SELECT :PRSESSAO,PRO.BDCODEMP,7, PRO.BDREFERENCIA, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO,PRO.BDCODPROD, PRO.BDCODCSTICMS, PRO.BDCODNAT,PRO.BDMOTIVO,
              PRO.BDQTDITEM, ((COALESCE(PRO.BDVLRITEM,0) - COALESCE(PRO.BDVLRABATNT,0) - COALESCE(PRO.BDVLRDESC,0) + COALESCE(PRO.BDVLRFRETE,0) + COALESCE(PRO.BDVLRDESPACESSORIA,0) + COALESCE(PRO.BDVLRSEGURO, 0)) / PRO.BDQTDITEM) BDVLRUNIT, (PRO.BDVLRUNITICMSEFETIVO/PRO.BDQTDITEM) BDVLRUNITICMSEFETIVO,
              'C380', PRO.BDDATAEMISSAO, PRO.BDALIQST, PRO.BDNUMDOCINI
       FROM(
            SELECT PRO.BDCODEMP,SAI.BDREFERENCIA, PRO.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO,PRO.BDCODPROD, PRO.BDCODCSTICMS, I.BDCODNAT,SAI.BDMOTIVO,
            (COALESCE(PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1)) BDQTDITEM,PRO.BDVLRITEM,
            (PRO.BDVLRICMSEFET + PRO.BDVLRFCP) BDVLRUNITICMSEFETIVO, MOV.BDDATAEMISSAO, IIF(PRO.BDALIQFCPRETIDO > 0, PRO.BDALIQFCPRETIDO ,PRO.BDALIQFCPSTRET) BDALIQST,
            MOV.BDNUMDOCINI, PRO.BDVLRABATNT, PRO.BDVLRDESC, PRO.BDVLRFRETE, PRO.BDVLRDESPACESSORIA, PRO.BDVLRSEGURO
            FROM (
                  SELECT *
                  FROM TMP_VEF_EMP_TMOVSAISTRS_TEMP SAI
                  WHERE SAI.BDCODEMP = :PRCODEMP AND
                        SAI.BDSESSAO = :PRSESSAO AND
                        SAI.BDREG    = 'SAI'
                  ) SAI
      LEFT OUTER JOIN VEF_EMP_TMOVSAI MOV ON (MOV.BDCODEMP = SAI.BDCODEMP AND MOV.BDCHAVE = SAI.BDCHAVE)
      LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDORDEM =  SAI.BDORDEM)
      JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDORDEM = I.BDORDEM AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEMPRO = SAI.BDORDEMPRO)
      LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MODE ON (MODE.BDMODELO = MOV.BDMODELO)
      LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
      LEFT OUTER JOIN VEF_BASE_TTABINFAD57 TAB ON (TAB.BDORDEM57 = SAI.BDMOTIVO)
      LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON)
      WHERE MOV.BDCODEMP = SAI.BDCODEMP
      AND MOV.BDREFLAN = SAI.BDREFERENCIA
      AND MODE.BDMODELOSTR IN ('02','2D','60')
      AND NAT.BDDEVOL = 'FALSE' AND
      MOV.BDCODSITNF NOT IN (2,3,4,5)
      ) PRO;

    /*Registro C480 - REDUÇÃO Z*/
    INSERT INTO TMP_VEF_EMP_TICMSSPED_1250_TEMP (BDSESSAO, BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCHAVE, BDORDEM,
                                                 BDORDEMPROD, BDCODPROD, BDCSTICMS, BDCODNAT, BDMOTIVO, BDQUANTIDADE,
                                                 BDVLRUNITICMS, BDVLRUNITICMSEFETIVO,BDREG,BDNUMDOCINI,BDDATALAN)
    SELECT :PRSESSAO, PRO.BDCODEMP, 7, MOV.BDREFLAN, MOV.BDCHAVE, I.BDORDEMDOCECF, PRO.BDORDEMITEM, PRO.BDCODPROD, PRO.BDCODCSTICMS,
           PRO.BDCODNAT, REDZ.BDMOTIVO, PRO.BDQTDITEM,(PRO.BDVLRTOTPRO/IIF(COALESCE(PRO.BDQTDITEM,1) = 0,1,COALESCE(PRO.BDQTDITEM,1))),
           (PRO.BDICMSEFETIVO/IIF(COALESCE(PRO.BDQTDITEM,1) = 0,1,COALESCE(PRO.BDQTDITEM,1))),'C480', I.BDNUMDOCCOO, I.BDDATAEMI
    FROM (
          SELECT *
          FROM TMP_VEF_EMP_TMOVSAISTRS_TEMP REDZ
          WHERE REDZ.BDCODEMP = :PRCODEMP AND
                REDZ.BDSESSAO = :PRSESSAO AND
                REDZ.BDREG    = 'RED'
          ) REDZ
    JOIN VEF_EMP_TREDZ MOV ON (MOV.BDCODEMP = REDZ.BDCODEMP AND MOV.BDCHAVE = REDZ.BDCHAVE)
    LEFT OUTER JOIN VEF_EMP_TDOCECF I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDORDEMDOCECF = REDZ.BDORDEM)
    LEFT OUTER JOIN VEF_EMP_TITEMDOCECF PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEMDOCECF = I.BDORDEMDOCECF AND PRO.BDORDEMITEM = REDZ.BDORDEMPRO)
    WHERE MOV.BDREFLAN = REDZ.BDREFERENCIA AND I.BDCODSITNF NOT IN (2,3,4,5);

    /*REGISTRO C180 - ENTRADA*/
    INSERT INTO TMP_VEF_EMP_TICMSSPED_1250_TEMP (BDSESSAO, BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCHAVE, BDORDEM,
                                                 BDORDEMPROD, BDCODPROD, BDCSTICMS, BDCODNAT, BDQUANTIDADE,BDVLRUNIT,
                                                 BDVLRUNITICMS,BDBCUNITICMS,BDICMSSTPRESUMIDO,BDREG, BDALIQFCP,BDNUMDOCINI, BDCODUFTER,BDDATALAN,BDVLRICMSSTNAORETIDO)
    SELECT :PRSESSAO,ENT.BDCODEMP,7, ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,ENT.BDQTDITEM,
            ENT.BDVLRUNIT, ENT.BDVLRUNITICMS, ENT.BDBCST BDBCUNITICMS,
             ((ENT.BDBCST * (BDALIQICMS)) - ENT.BDVLRUNITICMS) BDICMSSTPRESUMIDO,'C180', ENT.BDALIQST, ENT.BDNUMDOCINI, ENT.BDCODUF, ENT.BDDATAENTRADAENT, ENT.BDVLRICMSSTNAORET
           FROM (
                 SELECT ENT.BDCODEMP, ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,ENT.BDQTDITEM,
                 CAST((ENT.BDVLRUNIT/ENT.BDQTDITEM) AS NUMERIC(15,6)) BDVLRUNIT, CAST((ENT.BDBCST/ENT.BDQTDITEM) AS NUMERIC(15,6)) BDBCST,ENT.BDALIQICMS, ENT.BDALIQST,ENT.BDREDBCICMS, ENT.BDALIQICMSUNIT,ENT.BDALIQ_ORIGEM,
                 cast(iif((ENT.BDVLRUNIT / BDQTDITEM) < (ENT.BDBCST / BDQTDITEM), iif(substring(ENT.BDCODNAT from 1 for 1) = 1,
                 ((cast((ENT.BDVLRUNIT / BDQTDITEM) as numeric(15,6)) * iif(coalesce(ENT.BDREDBCICMS, 0) > 0,
                 (1 - (ENT.BDREDBCICMS) / 100), 1)) * iif(substring(ENT.BDCODCSTICMS from 1 for 1) in (1, 2, 3, 8), 0.04, BDALIQICMSUNIT)),
                 ((cast((ENT.BDVLRUNIT / BDQTDITEM) as numeric(15,6)) * iif(coalesce(ENT.BDREDBCICMS, 0) > 0,
                 (1 - (ENT.BDREDBCICMS) / 100), 1)) * iif(substring(ENT.BDCODCSTICMS from 1 for 1) in (1, 2, 3, 8), 0.04, ENT.BDALIQ_ORIGEM))), iif(substring(ENT.BDCODNAT from 1 for 1) = 1,
                 (cast((ENT.BDBCST / BDQTDITEM) as numeric(15,6)) * iif(coalesce(ENT.BDREDBCICMS, 0) > 0,
                 (1 - (ENT.BDREDBCICMS) / 100), 1)) * iif(substring(ENT.BDCODCSTICMS from 1 for 1) in (1, 2, 3, 8), 0.04, BDALIQICMSUNIT),
                 (cast((ENT.BDBCST / BDQTDITEM) as numeric(15,6)) * iif(coalesce(ENT.BDREDBCICMS, 0) > 0,
                 (1 - (ENT.BDREDBCICMS) / 100), 1)) * iif(substring(ENT.BDCODCSTICMS from 1 for 1) in (1, 2, 3, 8), 0.04, ENT.BDALIQ_ORIGEM))) as numeric(15,6)) BDVLRUNITICMS,

                 /*CAST(IIF((ENT.BDVLRUNIT/BDQTDITEM) < (ENT.BDBCST/BDQTDITEM),
                 IIF(SUBSTRING(ENT.BDCODNAT FROM 1 FOR 1) = 1,((CAST((ENT.BDVLRUNIT/BDQTDITEM) AS NUMERIC(15,6))* IIF(COALESCE(ENT.BDREDBCICMS,0) > 0,(1-(ENT.BDREDBCICMS)/100),1))*BDALIQICMSUNIT)
                 ,((CAST((ENT.BDVLRUNIT/BDQTDITEM) AS NUMERIC(15,6))* IIF(COALESCE(ENT.BDREDBCICMS,0) > 0,(1-(ENT.BDREDBCICMS)/100),1))*ENT.BDALIQ_ORIGEM))
                 ,IIF(SUBSTRING(ENT.BDCODNAT FROM 1 FOR 1) = 1,(CAST((ENT.BDBCST/BDQTDITEM) AS NUMERIC(15,6))*IIF(COALESCE(ENT.BDREDBCICMS,0) > 0,(1-(ENT.BDREDBCICMS)/100),1))*BDALIQICMSUNIT,
                 (CAST((ENT.BDBCST/BDQTDITEM) AS NUMERIC(15,6))*IIF(COALESCE(ENT.BDREDBCICMS,0) > 0,(1-(ENT.BDREDBCICMS)/100),1))*ENT.BDALIQ_ORIGEM)) AS NUMERIC(15,6)) BDVLRUNITICMS,*/

                 ENT.BDNUMDOCINI, ENT.BDCODUF, ENT.BDDATAENTRADAENT, ENT.BDVLRICMSSTNAORET
                FROM (
                      SELECT PRO.BDCODEMP, MOV.BDREFLAN,MOV.BDCHAVE, I.BDORDEM, PRO.BDORDEMPRO,PRO.BDCODPROD, PRO.BDCODCSTICMS, I.BDCODNAT, (IIF(COALESCE(PRO.BDQTDITEM,0) = 0,1,PRO.BDQTDITEM)*COALESCE(FAT.BDFATORCONVER,1)) BDQTDITEM,
                      ((PRO.BDVLRITEM + COALESCE(PRO.BDVLRDESPACESSORIA,0) + COALESCE(PRO.BDVLRFRETE,0) + COALESCE(PRO.BDVLRSEGURO,0)) - (COALESCE(PRO.BDVLRDESC,0) + COALESCE(PRO.BDVLRABATNT,0))) BDVLRUNIT,
                       IIF(ORI.BDBCST > 0,ORI.BDBCST,IIF(ORI.BDBCICMSSTRET > 0,ORI.BDBCICMSSTRET,IIF(PRO.BDBCST > 0,PRO.BDBCST,PRO.BDBCICMSSTRET))) BDBCST, (IIF(COALESCE(VINC.BDALIQICMS,0) > 0,(VINC.BDALIQICMS/100),(MOV.BDALIQINT/100)) + IIF(COALESCE(PRO.BDALIQFCPRETIDO,0) > 0, (PRO.BDALIQFCPRETIDO/100) ,IIF(COALESCE(PRO.BDALIQFCPSTRET,0) > 0,(PRO.BDALIQFCPSTRET/100),0))) BDALIQICMS,IIF(COALESCE(PRO.BDALIQFCPRETIDO,0) > 0, (PRO.BDALIQFCPRETIDO/100) ,IIF(COALESCE(PRO.BDALIQFCPSTRET,0) > 0,(PRO.BDALIQFCPSTRET/100),0)) BDALIQST,
                       PRO.BDREDBCICMS, IIF(COALESCE(VINC.BDALIQICMS,0) > 0,(VINC.BDALIQICMS/100),(MOV.BDALIQINT/100)) BDALIQICMSUNIT,(MOV.BDALIQ_ORIGEM/100) BDALIQ_ORIGEM, MOV.BDNUMDOCINI, MOV.BDCODUF, MOV.BDDATAENTRADAENT,
                       COALESCE(I.BDVALNTRIBST,0) BDVLRICMSSTNAORET
                       FROM (
                             SELECT MOV.BDCODEMP,MOV.BDREFLAN,MOV.BDCHAVE,UF.BDALIQINT,ALIQEXT.BDALIQ_ORIGEM, MOV.BDNUMDOCINI, UFT.BDCODUF, MOV.BDDATAENTRADAENT
                             FROM VEF_EMP_TMOVENT MOV
                             LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MODE ON (MODE.BDMODELO = MOV.BDMODELO)
                             LEFT OUTER JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = MOV.BDCODEMP)
                             LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID)
                             LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF)
                             LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES TER ON (TER.BDCODTER = MOV.BDCODTER)
                             LEFT OUTER JOIN TCIDADE CIDT ON (CIDT.BDCODCID = TER.BDCODCID)
                             LEFT OUTER JOIN TUF UFT ON (UFT.BDCODUF = CIDT.BDCODUF)
                             LEFT OUTER JOIN TUF_ALIQEXT ALIQEXT ON (ALIQEXT.BDCODUF = UF.BDCODUF AND ALIQEXT.BDCODUFDEST = UFT.BDCODUF)
                             WHERE MOV.BDCODEMP = :PRCODEMP AND
                              MOV.BDREFLAN = :PRREF AND
                              MODE.BDMODELOSTR IN ('01','1B','04','55') and
                              MOV.BDCODSITNF NOT IN (2,3,4,5)
                       ) MOV
                LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
                LEFT OUTER JOIN VEF_EMP_TMOVPROENTIMPORI ORI ON (ORI.BDCODEMP = MOV.BDCODEMP AND ORI.BDCHAVE = PRO.BDCHAVE AND ORI.BDORDEM = PRO.BDORDEM AND ORI.BDORDEMHIST = PRO.BDORDEMPRO AND  ORI.BDCODPROD = PRO.BDCODPROD)
                LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
                LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON)
                LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = PRO.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
                WHERE NAT.BDDEVOL = 'FALSE' AND
                      (PRO.BDBCST > 0 OR ORI.BDBCST > 0 OR PRO.BDBCICMSSTRET > 0 OR ORI.BDBCICMSSTRET > 0 OR PRO.BDVLRST > 0 OR PRO.BDVLRICMSSTRET > 0 OR ORI.BDVLRST > 0 or (ORI.BDVLRICMSSTRET > 0) )
                 ) ENT
         ) ENT;
END^

CREATE OR ALTER procedure SP_MEMCALCULO_PLANO_1250 (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer,
    PRCODUF integer = 23)
as
declare variable PRREFERENCIA integer;
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WCODPROD integer;
declare variable WVLRICMSOPPRESUMIDO numeric(15,6);
declare variable WVLRICMSSTPRESUMIDO numeric(15,6);
declare variable WREGVALOR varchar(4);
declare variable WORDEM integer;
declare variable WORDEMPROD integer;
BEGIN
   SETORDEMSEQUENCIAL_STR(:prCODEMP);

   SELECT COALESCE(MIN(BDREFERENCIA),0) FROM VEF_EMP_TICMSSPED1250_PROD
   WHERE BDCODEMP = :PRCODEMP
     AND BDREFERENCIA <= :PRREF
   INTO :PRREFERENCIA;

   /*BUSCA DO IVENTÁRIO*/
   IF ((:PRREFERENCIA = 0) OR (:PRREFERENCIA = :PRREF) OR (:PRREFERENCIA > :PRREF)) THEN
      BEGIN
         /*INSERE O INVENTÁRIO*/
         INSERT INTO TMP_VEF_EMP_TMEMCALC_1250_TEMP (BDSESSAO,BDCODEMP,BDCHAVE, BDCODPERIODO,BDREFERENCIA, BDCODPROD, BDREG,BDORDEMCALC, BDICMSOPPRESUMIDO,BDBCICMSOPPRESUMIDO,BDBCICMSSTPRESUMIDO,
                                                     BDDATALAN,BDQUANTIDADE,BDREFLAN,BDCHAVELANCALC,BDREGVALOR,BDORDEM,BDORDEMPROD,BDDATALANNOTA,BDVLRFRETE,BDVLRSEGURO,BDVLRDESPACESSORIA,BDVLRDESC,BDREDBCICMS)
         SELECT  :PRSESSAO, INV.BDCODEMP,TAB.BDCHAVE, 7, TAB.BDREFERENCIA, INV.BDCODPROD, 'MINV',GETORDEMSEQUENCIAL_STR('MINV.'||INV.BDCODPROD||INV.BDCODEMP||TAB.BDCHAVE, :prCODEMP),
                 INV.BDVLRICMSOP,CAST((CAST((INV.BDVLRICMSOP * INV.BDQTDINV) AS NUMERIC(15,6)) / (IIF(COALESCE(VINC.BDALIQICMS,0) > 0,VINC.BDALIQICMS,UF.BDALIQINT) / 100)) AS NUMERIC(15,6)) BDICMSOP,
                 CAST((INV.BDVLRBCICMSST * INV.BDQTDINV) AS NUMERIC(15,6)) BDICMSST,
                 CAST(SUBSTRING(INV.BDREFINV FROM 5 FOR 2)||'/'||(SELECT ULTDIA FROM ULTIMO_DIA_MES(SUBSTRING(INV.BDREFINV FROM 5 FOR 2), SUBSTRING(INV.BDREFINV FROM 1 FOR 4)))||'/'||SUBSTRING(INV.BDREFINV FROM 1 FOR 4) AS DATE) BDDATALAN,
                 INV.BDQTDINV, INV.BDREFINV, INV.BDCHAVE, TAB.BDREG, TAB.BDORDEM, TAB.BDORDEMPROD, TAB.BDDATALAN, TAB.BDVLRFRETE, TAB.BDVLRSEGURO, TAB.BDVLRDESPACESSORIA, TAB.BDVLRDESC, TAB.BDREDBCICMS
         FROM (SELECT BDCODEMP, BDREFERENCIA, BDCHAVE, BDCODPROD, TAB.BDREG, TAB.BDORDEM, TAB.BDORDEMPROD, TAB.BDDATALAN, TAB.BDVLRFRETE, TAB.BDVLRSEGURO, TAB.BDVLRDESPACESSORIA, TAB.BDVLRDESC, TAB.BDREDBCICMS
               FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP TAB
               WHERE TAB.BDCODEMP = :PRCODEMP AND TAB.BDSESSAO = :PRSESSAO
                     AND TAB.BDREFERENCIA = :PRREF  AND TAB.BDREG IN ('C185','C380','C480') AND
                     SUBSTRING(TAB.BDREFERENCIA FROM 1 FOR 4) >= IIF(:PRCODUF = 19, '2024', '2021')
               GROUP BY BDCODEMP,BDREFERENCIA,BDCHAVE, BDCODPROD, TAB.BDREG,BDORDEM,BDORDEMPROD, TAB.BDDATALAN, TAB.BDVLRFRETE, TAB.BDVLRSEGURO, TAB.BDVLRDESPACESSORIA, TAB.BDVLRDESC, TAB.BDREDBCICMS
               ) TAB
         JOIN VEF_EMP_TMOVINV INV ON (INV.BDCODEMP = TAB.BDCODEMP AND INV.BDCODPROD = TAB.BDCODPROD)
         LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = INV.BDCODEMP AND VINC.BDCODPROD = INV.BDCODPROD)
         LEFT OUTER JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = TAB.BDCODEMP)
         LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID)
         LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF)
         WHERE BDREFINV < TAB.BDREFERENCIA
           AND INV.BDREFINV >= (SELECT FIRST 1 i.bdREFINV FROM VEF_EMP_TMOVINV i WHERE i.bdCODEMP = inv.bdCODEMP AND i.bdCODPROD = inv.bdCODPROD AND i.bdREFINV < :PRREF ORDER BY i.BDREFINV DESC);
      END
   ELSE /*BUSCA DA APURAÇÃO ANTERIOR*/
      BEGIN
        /*INSERE COMO INVENTÁRIO OS DADOS DA APURAÇÃO ANTERIOR*/
        INSERT INTO TMP_VEF_EMP_TMEMCALC_1250_TEMP (BDSESSAO, BDCODEMP, BDCHAVE, BDCODPERIODO, BDREFERENCIA, BDCODPROD, BDREG, BDORDEMCALC, BDBCICMSOPPRESUMIDO,BDBCICMSSTPRESUMIDO,
                                                    BDDATALAN,BDQUANTIDADE, BDREFLAN,BDREGVALOR,BDORDEM,BDORDEMPROD,BDDATALANNOTA,BDVLRFRETE,BDVLRSEGURO,BDVLRDESPACESSORIA,BDVLRDESC,BDREDBCICMS)
        SELECT :PRSESSAO, INV.BDCODEMP, TAB.BDCHAVE, 7, TAB.BDREFERENCIA, TAB.BDCODPROD, 'MINV',
               GETORDEMSEQUENCIAL_STR('MINV.' || TAB.BDCODEMP || TAB.BDCODPROD || TAB.BDCHAVE, :prCODEMP), INV.BDBCICMSOPPRESUMIDO,INV.BDBCICMSSTPRESUMIDO,
               CAST(SUBSTRING((:PRREF - 1) FROM 5 FOR 2)||'/'||(SELECT ULTDIA FROM ULTIMO_DIA_MES(SUBSTRING((:PRREF - 1) FROM 5 FOR 2), SUBSTRING((:PRREF - 1) FROM 1 FOR 4)))||'/'||SUBSTRING((:PRREF - 1) FROM 1 FOR 4) AS DATE) BDDATALAN,
               INV.BDQUANTIDADE, INV.BDREFINV, TAB.BDREG, TAB.BDORDEM, TAB.BDORDEMPROD, TAB.BDDATALAN, TAB.BDVLRFRETE, TAB.BDVLRSEGURO, TAB.BDVLRDESPACESSORIA, TAB.BDVLRDESC, TAB.BDREDBCICMS
        FROM (
              SELECT CALC.BDCODEMP,CALC.BDCODPROD,SUM(CALC.BDQUANTIDADE) BDQUANTIDADE,
              SUM(CALC.BDBCICMSOPPRESUMIDO) BDBCICMSOPPRESUMIDO, SUM(CALC.BDBCICMSSTPRESUMIDO) BDBCICMSSTPRESUMIDO, CALC.BDREFERENCIA BDREFINV
              FROM (
                    SELECT CALC.BDCODEMP, CALC.BDREG, CALC.BDCHAVELANCALC, CALC.BDREFERENCIA, CALC.BDCODPROD,
                           CALC.BDQUANTIDADE, CALC.BDBCICMSOPPRESUMIDO, CALC.BDBCICMSSTPRESUMIDO,
                          MAX(CALC.BDDATALANNOTA) BDDATALANNOTA
                   FROM VEF_EMP_TMEMCALC_1250 CALC
                   WHERE BDCODEMP = :PRCODEMP AND BDREFERENCIA = (:PRREF - 1)
                   GROUP BY CALC.BDCODEMP, CALC.BDREG, CALC.BDCHAVELANCALC, CALC.BDREFERENCIA, CALC.BDCODPROD,
                            CALC.BDQUANTIDADE, CALC.BDBCICMSOPPRESUMIDO, CALC.BDBCICMSSTPRESUMIDO
                  ) CALC
        GROUP BY CALC.BDCODEMP,CALC.BDCODPROD,CALC.BDREFERENCIA
             ) INV
        JOIN TMP_VEF_EMP_TICMSSPED_1250_TEMP TAB ON (TAB.BDCODEMP = INV.BDCODEMP AND TAB.BDSESSAO = :PRSESSAO AND TAB.BDREFERENCIA = :PRREF AND TAB.BDCODPROD = INV.BDCODPROD);


        /*INSERE O INVENTARIO*/ -- Alt.: #228032 - Quando nao existe o produto na apuracao anterior, busca direto do inventario...
        INSERT INTO TMP_VEF_EMP_TMEMCALC_1250_TEMP (BDSESSAO,BDCODEMP,BDCHAVE, BDCODPERIODO,BDREFERENCIA, BDCODPROD, BDREG,BDORDEMCALC, BDICMSOPPRESUMIDO,BDBCICMSOPPRESUMIDO,BDBCICMSSTPRESUMIDO,
                                                    BDDATALAN,BDQUANTIDADE,BDREFLAN,BDCHAVELANCALC,BDREGVALOR,BDORDEM,BDORDEMPROD,BDDATALANNOTA,BDVLRFRETE,BDVLRSEGURO,BDVLRDESPACESSORIA,BDVLRDESC,BDREDBCICMS)
        SELECT  :PRSESSAO, INV.BDCODEMP,TAB.BDCHAVE, 7, TAB.BDREFERENCIA, INV.BDCODPROD, 'MINV',GETORDEMSEQUENCIAL_STR('MINV.'||INV.BDCODPROD||INV.BDCODEMP||TAB.BDCHAVE, :prCODEMP),
                INV.BDVLRICMSOP,CAST((CAST((INV.BDVLRICMSOP * INV.BDQTDINV) AS NUMERIC(15,6)) / (IIF(COALESCE(VINC.BDALIQICMS,0) > 0,VINC.BDALIQICMS,UF.BDALIQINT) / 100)) AS NUMERIC(15,6)) BDICMSOP,
                CAST((INV.BDVLRBCICMSST * INV.BDQTDINV) AS NUMERIC(15,6)) BDICMSST,
                CAST(SUBSTRING(INV.BDREFINV FROM 5 FOR 2)||'/'||(SELECT ULTDIA FROM ULTIMO_DIA_MES(SUBSTRING(INV.BDREFINV FROM 5 FOR 2), SUBSTRING(INV.BDREFINV FROM 1 FOR 4)))||'/'||SUBSTRING(INV.BDREFINV FROM 1 FOR 4) AS DATE) BDDATALAN,
                INV.BDQTDINV, INV.BDREFINV, INV.BDCHAVE, TAB.BDREG, TAB.BDORDEM, TAB.BDORDEMPROD, TAB.BDDATALAN, TAB.BDVLRFRETE, TAB.BDVLRSEGURO, TAB.BDVLRDESPACESSORIA, TAB.BDVLRDESC, TAB.BDREDBCICMS
        FROM (SELECT BDCODEMP, BDREFERENCIA, BDCHAVE, BDCODPROD, TAB.BDREG, TAB.BDORDEM, TAB.BDORDEMPROD, TAB.BDDATALAN, TAB.BDVLRFRETE, TAB.BDVLRSEGURO, TAB.BDVLRDESPACESSORIA, TAB.BDVLRDESC, TAB.BDREDBCICMS
              FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP TAB
              WHERE TAB.BDCODEMP = :PRCODEMP AND TAB.BDSESSAO = :PRSESSAO
                    AND TAB.BDREFERENCIA = :PRREF  AND TAB.BDREG IN ('C185','C380','C480') AND
                    SUBSTRING(TAB.BDREFERENCIA FROM 1 FOR 4) >= IIF(:PRCODUF = 19, '2024', '2021')
              AND NOT EXISTS(SELECT * FROM TMP_VEF_EMP_TMEMCALC_1250_TEMP x WHERE x.bdSESSAO = tab.bdSESSAO AND x.bdCODEMP = tab.bdCODEMP AND x.bdCHAVE = tab.bdCHAVE AND x.bdCODPROD = tab.bdCODPROD)
              GROUP BY BDCODEMP,BDREFERENCIA,BDCHAVE, BDCODPROD, TAB.BDREG,BDORDEM,BDORDEMPROD, TAB.BDDATALAN, TAB.BDVLRFRETE, TAB.BDVLRSEGURO, TAB.BDVLRDESPACESSORIA, TAB.BDVLRDESC, TAB.BDREDBCICMS
              ) TAB
        JOIN VEF_EMP_TMOVINV INV ON (INV.BDCODEMP = TAB.BDCODEMP AND INV.BDCODPROD = TAB.BDCODPROD)
        LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = INV.BDCODEMP AND VINC.BDCODPROD = INV.BDCODPROD)
        LEFT OUTER JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = TAB.BDCODEMP)
        LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID)
        LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF)
        WHERE inv.bdREFINV < tab.bdREFERENCIA
          AND INV.BDREFINV >= (SELECT FIRST 1 i.bdREFINV FROM VEF_EMP_TMOVINV i WHERE i.bdCODEMP = inv.bdCODEMP AND i.bdCODPROD = inv.bdCODPROD AND i.bdREFINV < :PRREF ORDER BY i.BDREFINV DESC);
      END

        /*INSERE NOTA DE ENT - DEVOLUÇÃO OU NÃO COM ST
          INSERE NOTA DE SAI - DEVOULÇÃO COM ST
          SOMENTE QUANDO A NOTA FOR SUPERIOR A DATA DO INVENTÁRIO E MENOR OU IGUAL A NOTA DO LANÇAMENTO APURADO*/
      INSERT INTO TMP_VEF_EMP_TMEMCALC_1250_TEMP (BDSESSAO,BDCODEMP,BDCODPERIODO,BDREFERENCIA, BDCODPROD, BDREG,BDCHAVE,BDORDEMCALC,
                                                  BDBCICMSOPPRESUMIDO,BDBCICMSSTPRESUMIDO,BDDATALAN,BDQUANTIDADE,BDREFLAN,BDCHAVELANCALC,BDALIQST,BDREGVALOR,BDORDEM,BDORDEMPROD,BDDATALANNOTA)
      SELECT :PRSESSAO,TAB.BDCODEMP,7,TAB.BDREFERENCIA,TAB.BDCODPROD,'MENT',TAB.BDCHAVE,
      GETORDEMSEQUENCIAL_STR('MENT.'||TAB.BDCHAVE||TAB.BDCODEMP, :prCODEMP),
      ((PRO.BDVLRITEM + COALESCE(PRO.BDVLRFRETE,0)+COALESCE(PRO.BDVLRSEGURO,0)+COALESCE(PRO.BDVLRDESPACESSORIA,0))-(COALESCE(PRO.BDVLRDESC,0)+COALESCE(PRO.BDVLRABATNT,0)))*IIF(COALESCE(PRO.BDREDBCICMS,0) > 0,(1-(PRO.BDREDBCICMS/ 100)) ,1) BDBCICMSOPPRESUMIDO,
      (IIF(PRO.BDBCST > 0, PRO.BDBCST, IIF(PRO.BDBCICMSSTRET > 0,PRO.BDBCICMSSTRET, IIF(ORI.BDBCST > 0,ORI.BDBCST,
                                   IIF(ORI.BDBCICMSSTRET > 0,ORI.BDBCICMSSTRET,0))))) BCICMSSTPRESUMIDO,
      ENT.BDDATAENTRADAENT, PRO.BDQTDITEM, ENT.BDREFLAN, ENT.BDCHAVE, IIF(PRO.BDALIQFCPRETIDO > 0, PRO.BDALIQFCPRETIDO ,PRO.BDALIQFCPSTRET) BDALIQST,TAB.BDREGVALOR, TAB.BDORDEM, TAB.BDORDEMPROD,
      TAB.BDDATALAN
      FROM (
          SELECT TAB.BDCODEMP, TAB.BDCHAVE, TAB.BDREFERENCIA, TAB.BDCODPROD, TAB.BDDATALAN, TAB.BDREG, TAB.BDORDEM, TAB.BDORDEMPROD,CALC.BDREFLAN,  COALESCE(CALC.BDREGVALOR,TAB.BDREG) BDREGVALOR
          FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP TAB
          LEFT OUTER JOIN TMP_VEF_EMP_TMEMCALC_1250_TEMP CALC ON (CALC.BDSESSAO = :PRSESSAO AND CALC.BDCODEMP = TAB.BDCODEMP AND CALC.BDCHAVE = TAB.BDCHAVE AND CALC.BDCODPROD = TAB.BDCODPROD AND CALC.BDREG = 'MINV' AND CALC.BDREGVALOR = TAB.BDREG AND CALC.BDORDEM = TAB.BDORDEM AND CALC.BDORDEMPROD = TAB.BDORDEMPROD)
          WHERE TAB.BDCODEMP = :PRCODEMP AND
                TAB.BDSESSAO = :PRSESSAO AND
                TAB.BDREFERENCIA = :PRREF  AND
                TAB.BDREG IN ('C185', 'C380','C480') AND
                SUBSTRING(TAB.BDREFERENCIA FROM 1 FOR 4) >= IIF(:PRCODUF = 19, '2024', '2021')
      ) TAB
      JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = TAB.BDCODEMP AND PRO.BDCODPROD = TAB.BDCODPROD)
      LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = PRO.BDCODEMP AND ENT.BDCHAVE = PRO.BDCHAVE)
      LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = PRO.BDCODEMP AND I.BDCHAVE = PRO.BDCHAVE AND I.BDORDEM = PRO.BDORDEM)
      LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
      LEFT OUTER JOIN VEF_EMP_TMOVPROENTIMPORI ORI ON (ORI.BDCODEMP = PRO.BDCODEMP AND ORI.BDCHAVE = PRO.BDCHAVE AND ORI.BDORDEM = PRO.BDORDEM AND ORI.BDCODPROD = PRO.BDCODPROD AND ORI.BDORDEMHIST = PRO.BDORDEMPRO)
      WHERE ENT.BDREFLAN > COALESCE(TAB.BDREFLAN,'202012') AND IIF(:PRCODUF = 19, extract(year from ENT.BDDATAENTRADAENT)||LPAD(extract(month from ENT.BDDATAENTRADAENT), 2, '0') <= extract(year from TAB.BDDATALAN)||LPAD(extract(month from TAB.BDDATALAN), 2, '0'), ENT.BDDATAENTRADAENT <= TAB.BDDATALAN)
      AND (PRO.BDVLRST > 0 OR PRO.BDVLRICMSSTRET > 0) AND NAT.BDCODNAT NOT IN (1407000,2407000,1406000,2406000,1413000,2413000,1412000,2412000)
      AND NAT.BDDEVOL = 'FALSE' AND ENT.BDCODSITNF NOT IN (2,3,4,5)
      UNION ALL  /*DEV ENTRADA C380*/
      SELECT :PRSESSAO,PRO.BDCODEMP,7,PRO.BDREFERENCIA,PRO.BDCODPROD,'DEVT',PRO.BDCHAVE,
      GETORDEMSEQUENCIAL_STR('DEVT.'||PRO.BDCHAVE||PRO.BDCODEMP, :prCODEMP),
      PRO.BDBCICMSOPPRESUMIDO, 0 BCICMSSTPRESUMIDO, /*Será calculado no FOR abaixo*/
      PRO.BDDATAENTRADAENT, PRO.BDQTDITEM, PRO.BDREFLAN, PRO.BDCHAVEENT, PRO.BDALIQST,
      PRO.BDREGVALOR, PRO.BDORDEM, PRO.BDORDEMPROD, PRO.BDDATALAN
      FROM (
            SELECT TAB.BDCODEMP,TAB.BDREFERENCIA,TAB.BDCODPROD,TAB.BDCHAVE,
                   TAB.BDORDEM, TAB.BDORDEMPROD, TAB.BDDATALAN,
                   ((PRO.BDVLRITEM + COALESCE(PRO.BDVLRFRETE,0)+COALESCE(PRO.BDVLRSEGURO,0)+COALESCE(PRO.BDVLRDESPACESSORIA,0))-(COALESCE(PRO.BDVLRDESC,0)+COALESCE(PRO.BDVLRABATNT,0)))*IIF(COALESCE(PRO.BDREDBCICMS,0) > 0,(1-(PRO.BDREDBCICMS/ 100)) ,1) BDBCICMSOPPRESUMIDO,
                   IIF(PRO.BDALIQFCPRETIDO > 0, PRO.BDALIQFCPRETIDO ,PRO.BDALIQFCPSTRET) BDALIQST, TAB.BDREGVALOR, ENT.BDDATAENTRADAENT,ENT.BDREFLAN, ENT.BDCHAVE BDCHAVEENT,(IIF(PRO.BDQTDITEM>0,PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1)) BDQTDITEM
            FROM (
                  SELECT TAB.BDCODEMP, TAB.BDCHAVE, TAB.BDREFERENCIA, TAB.BDCODPROD, TAB.BDDATALAN, TAB.BDREG, TAB.BDORDEM, TAB.BDORDEMPROD,CALC.BDREFLAN,COALESCE(CALC.BDREGVALOR,TAB.BDREG) BDREGVALOR
                  FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP TAB
                  LEFT OUTER JOIN TMP_VEF_EMP_TMEMCALC_1250_TEMP CALC ON (CALC.BDSESSAO = :PRSESSAO AND CALC.BDCODEMP = TAB.BDCODEMP AND CALC.BDCHAVE = TAB.BDCHAVE AND CALC.BDCODPROD = TAB.BDCODPROD AND CALC.BDREG = 'MINV' AND CALC.BDREGVALOR = TAB.BDREG)
                  WHERE TAB.BDCODEMP = :PRCODEMP AND
                        TAB.BDSESSAO = :PRSESSAO AND
                        TAB.BDREFERENCIA = :PRREF  AND
                        TAB.BDREG = 'C380' AND
                        SUBSTRING(TAB.BDREFERENCIA FROM 1 FOR 4) >= IIF(:PRCODUF = 19, '2024', '2021')
                  ) TAB
            LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = TAB.BDCODEMP AND PRO.BDCODPROD = TAB.BDCODPROD)
            LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON)
            LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = PRO.BDCODEMP AND ENT.BDCHAVE = PRO.BDCHAVE)
            LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = PRO.BDCODEMP AND I.BDCHAVE = PRO.BDCHAVE AND I.BDORDEM = PRO.BDORDEM)
            LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
            JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = ENT.BDCODEMP AND C113.BDCHAVE = ENT.BDCHAVE)
            WHERE ENT.BDREFLAN > COALESCE(TAB.BDREFLAN,'202012') AND IIF(:PRCODUF = 19, extract(year from ENT.BDDATAENTRADAENT)||LPAD(extract(month from ENT.BDDATAENTRADAENT), 2, '0') >= extract(year from TAB.BDDATALAN)||LPAD(extract(month from TAB.BDDATALAN), 2, '0'), ENT.BDDATAENTRADAENT >= TAB.BDDATALAN)
            AND (PRO.BDVLRST > 0 OR PRO.BDVLRICMSSTRET > 0) AND NAT.BDCODNAT NOT IN (1407000,2407000,1406000,2406000,1413000,2413000,1412000,2412000)
            AND NAT.BDDEVOL = 'TRUE' and ENT.BDCODSITNF NOT IN (2,3,4,5)
           ) PRO
      LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = PRO.BDCODEMP AND C113.BDCHAVE = PRO.BDCHAVEENT)
      LEFT OUTER JOIN VEF_EMP_TICMSSPED_1250_C380 C380 ON (C380.BDCODEMP = PRO.BDCODEMP  AND C380.BDCODPROD = PRO.BDCODPROD)
      LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = C380.BDCODEMP AND SAI.BDCHAVE = C380.BDCHAVE)
      LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI1250 ON (SAI1250.BDCODEMP = PRO.BDCODEMP AND SAI1250.BDCHAVE = PRO.BDCHAVE)
      WHERE ((SAI.BDNUMDOCINI = C113.BDNUMDOC AND COALESCE(SAI.BDCHAVENFE,0) = IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '', 0, C113.BDCHAVENFE)
      AND SAI.BDDATAEMISSAO = C113.BDDTEMISSAO) OR (SAI1250.BDNUMDOCINI = C113.BDNUMDOC AND COALESCE(SAI1250.BDCHAVENFE,0) = IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '', 0, C113.BDCHAVENFE)
      AND SAI1250.BDDATAEMISSAO = C113.BDDTEMISSAO))
      UNION ALL   /*DEV ENTRADA C185*/
      SELECT :PRSESSAO,PRO.BDCODEMP,7,PRO.BDREFERENCIA,PRO.BDCODPROD,'DEVT',PRO.BDCHAVE,
      GETORDEMSEQUENCIAL_STR('DEVT.'||PRO.BDCHAVE||PRO.BDCODEMP, :prCODEMP),
      PRO.BDBCICMSOPPRESUMIDO,0 BCICMSSTPRESUMIDO, /*Será calculado no FOR abaixo*/
      PRO.BDDATAENTRADAENT, PRO.BDQTDITEM, PRO.BDREFLAN, PRO.BDCHAVEENT, PRO.BDALIQST,
      PRO.BDREGVALOR, PRO.BDORDEM, PRO.BDORDEMPROD, PRO.BDDATALAN
      FROM (
            SELECT TAB.BDCODEMP,TAB.BDREFERENCIA,TAB.BDCODPROD,TAB.BDCHAVE,
                   TAB.BDORDEM, TAB.BDORDEMPROD, TAB.BDDATALAN,
                   ((PRO.BDVLRITEM + COALESCE(PRO.BDVLRFRETE,0)+COALESCE(PRO.BDVLRSEGURO,0)+COALESCE(PRO.BDVLRDESPACESSORIA,0))-(COALESCE(PRO.BDVLRDESC,0)+COALESCE(PRO.BDVLRABATNT,0)))*IIF(COALESCE(PRO.BDREDBCICMS,0) > 0,(1-(PRO.BDREDBCICMS/ 100)) ,1) BDBCICMSOPPRESUMIDO,
                   IIF(PRO.BDALIQFCPRETIDO > 0, PRO.BDALIQFCPRETIDO ,PRO.BDALIQFCPSTRET) BDALIQST, TAB.BDREGVALOR, ENT.BDDATAENTRADAENT,ENT.BDREFLAN, ENT.BDCHAVE BDCHAVEENT,(IIF(PRO.BDQTDITEM>0,PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1)) BDQTDITEM
            FROM (
                  SELECT TAB.BDCODEMP, TAB.BDCHAVE, TAB.BDREFERENCIA, TAB.BDCODPROD, TAB.BDDATALAN, TAB.BDREG, TAB.BDORDEM, TAB.BDORDEMPROD,CALC.BDREFLAN,COALESCE(CALC.BDREGVALOR,TAB.BDREG) BDREGVALOR
                  FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP TAB
                  LEFT OUTER JOIN TMP_VEF_EMP_TMEMCALC_1250_TEMP CALC ON (CALC.BDSESSAO = :PRSESSAO AND CALC.BDCODEMP = TAB.BDCODEMP AND CALC.BDCHAVE = TAB.BDCHAVE AND CALC.BDCODPROD = TAB.BDCODPROD AND CALC.BDREG = 'MINV' AND CALC.BDREGVALOR = TAB.BDREG)
                  WHERE TAB.BDCODEMP = :PRCODEMP AND
                        TAB.BDSESSAO = :PRSESSAO AND
                        TAB.BDREFERENCIA = :PRREF  AND
                        TAB.BDREG = 'C185' AND
                        SUBSTRING(TAB.BDREFERENCIA FROM 1 FOR 4) >= IIF(:PRCODUF = 19, '2024', '2021')
                  ) TAB
            LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = TAB.BDCODEMP AND PRO.BDCODPROD = TAB.BDCODPROD)
            LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON)
            LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = PRO.BDCODEMP AND ENT.BDCHAVE = PRO.BDCHAVE)
            LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = PRO.BDCODEMP AND I.BDCHAVE = PRO.BDCHAVE AND I.BDORDEM = PRO.BDORDEM)
            LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
            JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = ENT.BDCODEMP AND C113.BDCHAVE = ENT.BDCHAVE)
            WHERE ENT.BDREFLAN > COALESCE(TAB.BDREFLAN,'202012') AND IIF(:PRCODUF = 19, extract(year from ENT.BDDATAENTRADAENT)||LPAD(extract(month from ENT.BDDATAENTRADAENT), 2, '0') >= extract(year from TAB.BDDATALAN)||LPAD(extract(month from TAB.BDDATALAN), 2, '0'), ENT.BDDATAENTRADAENT >= TAB.BDDATALAN)
            AND (PRO.BDVLRST > 0 OR PRO.BDVLRICMSSTRET > 0) AND NAT.BDCODNAT NOT IN (1407000,2407000,1406000,2406000,1413000,2413000,1412000,2412000)
            AND NAT.BDDEVOL = 'TRUE' and ENT.BDCODSITNF NOT IN (2,3,4,5)
           ) PRO
      LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = PRO.BDCODEMP AND C113.BDCHAVE = PRO.BDCHAVEENT)
      LEFT OUTER JOIN VEF_EMP_TICMSSPED_1250_C185 C185 ON (C185.BDCODEMP = PRO.BDCODEMP  AND C185.BDCODPROD = PRO.BDCODPROD)
      LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = C185.BDCODEMP AND SAI.BDCHAVE = C185.BDCHAVE)
      LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI1250 ON (SAI1250.BDCODEMP = PRO.BDCODEMP AND SAI1250.BDCHAVE = PRO.BDCHAVE)
      WHERE ((SAI.BDNUMDOCINI = C113.BDNUMDOC AND COALESCE(SAI.BDCHAVENFE,0) = IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '', 0, C113.BDCHAVENFE)
      AND SAI.BDDATAEMISSAO = C113.BDDTEMISSAO) OR (SAI1250.BDNUMDOCINI = C113.BDNUMDOC AND COALESCE(SAI1250.BDCHAVENFE,0) = IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '', 0, C113.BDCHAVENFE)
      AND SAI1250.BDDATAEMISSAO = C113.BDDTEMISSAO))
      UNION ALL  /*DEV ENTRADA C480*/
      SELECT :PRSESSAO,PRO.BDCODEMP,7,PRO.BDREFERENCIA,PRO.BDCODPROD,'DEVT',PRO.BDCHAVE,
      GETORDEMSEQUENCIAL_STR('DEVT.'||PRO.BDCHAVE||PRO.BDCODEMP, :prCODEMP),
      PRO.BDBCICMSOPPRESUMIDO, 0 BCICMSSTPRESUMIDO, /*Será calculado no FOR abaixo*/
      PRO.BDDATAENTRADAENT, PRO.BDQTDITEM, PRO.BDREFLAN, PRO.BDCHAVEENT, PRO.BDALIQST,
      PRO.BDREGVALOR, PRO.BDORDEM, PRO.BDORDEMPROD, PRO.BDDATALAN
      FROM (
            SELECT TAB.BDCODEMP,TAB.BDREFERENCIA,TAB.BDCODPROD,TAB.BDCHAVE,
                   TAB.BDORDEM, TAB.BDORDEMPROD, TAB.BDDATALAN,
                   ((PRO.BDVLRITEM + COALESCE(PRO.BDVLRFRETE,0)+COALESCE(PRO.BDVLRSEGURO,0)+COALESCE(PRO.BDVLRDESPACESSORIA,0))-(COALESCE(PRO.BDVLRDESC,0)+COALESCE(PRO.BDVLRABATNT,0)))*IIF(COALESCE(PRO.BDREDBCICMS,0) > 0,(1-(PRO.BDREDBCICMS/ 100)) ,1) BDBCICMSOPPRESUMIDO,
                   IIF(PRO.BDALIQFCPRETIDO > 0, PRO.BDALIQFCPRETIDO ,PRO.BDALIQFCPSTRET) BDALIQST, TAB.BDREGVALOR, ENT.BDDATAENTRADAENT,ENT.BDREFLAN, ENT.BDCHAVE BDCHAVEENT,(IIF(PRO.BDQTDITEM>0,PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1)) BDQTDITEM
            FROM (
                  SELECT TAB.BDCODEMP, TAB.BDCHAVE, TAB.BDREFERENCIA, TAB.BDCODPROD, TAB.BDDATALAN, TAB.BDREG, TAB.BDORDEM, TAB.BDORDEMPROD,CALC.BDREFLAN,COALESCE(CALC.BDREGVALOR,TAB.BDREG) BDREGVALOR
                  FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP TAB
                  LEFT OUTER JOIN TMP_VEF_EMP_TMEMCALC_1250_TEMP CALC ON (CALC.BDSESSAO = :PRSESSAO AND CALC.BDCODEMP = TAB.BDCODEMP AND CALC.BDCHAVE = TAB.BDCHAVE AND CALC.BDCODPROD = TAB.BDCODPROD AND CALC.BDREG = 'MINV' AND CALC.BDREGVALOR = TAB.BDREG)
                  WHERE TAB.BDCODEMP = :PRCODEMP AND
                        TAB.BDSESSAO = :PRSESSAO AND
                        TAB.BDREFERENCIA = :PRREF  AND
                        TAB.BDREG = 'C480' AND
                        SUBSTRING(TAB.BDREFERENCIA FROM 1 FOR 4) >= IIF(:PRCODUF = 19, '2024', '2021')
                  ) TAB
            LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = TAB.BDCODEMP AND PRO.BDCODPROD = TAB.BDCODPROD)
            LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON)
            LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = PRO.BDCODEMP AND ENT.BDCHAVE = PRO.BDCHAVE)
            LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = PRO.BDCODEMP AND I.BDCHAVE = PRO.BDCHAVE AND I.BDORDEM = PRO.BDORDEM)
            LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
            WHERE ENT.BDREFLAN > COALESCE(TAB.BDREFLAN,'202012') AND IIF(:PRCODUF = 19, extract(year from ENT.BDDATAENTRADAENT)||LPAD(extract(month from ENT.BDDATAENTRADAENT), 2, '0') >= extract(year from TAB.BDDATALAN)||LPAD(extract(month from TAB.BDDATALAN), 2, '0'), ENT.BDDATAENTRADAENT >= TAB.BDDATALAN)
            AND (PRO.BDVLRST > 0 OR PRO.BDVLRICMSSTRET > 0) AND NAT.BDCODNAT NOT IN (1407000,2407000,1406000,2406000,1413000,2413000,1412000,2412000)
            AND NAT.BDDEVOL = 'TRUE' AND ENT.BDCODSITNF NOT IN (2,3,4,5)
           ) PRO
      LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = PRO.BDCODEMP AND C113.BDCHAVE = PRO.BDCHAVE)
      LEFT OUTER JOIN VEF_EMP_TMOVC181_1250 C181 ON (C181.BDCODEMP = PRO.BDCODEMP AND C181.BDCHAVE = PRO.BDCHAVEENT)
      LEFT OUTER JOIN VEF_EMP_TICMSSPED_1250_C480 TAB ON (TAB.BDCODEMP = PRO.BDCODEMP AND TAB.BDCODPROD = PRO.BDCODPROD)
      LEFT OUTER JOIN VEF_EMP_TREDZ MOV ON (MOV.BDCODEMP = TAB.BDCODEMP AND MOV.BDCHAVE = TAB.BDCHAVE)
      LEFT OUTER JOIN VEF_EMP_TDOCECF I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDORDEMDOCECF = TAB.BDORDEM)
      LEFT OUTER JOIN VEF_BASE_TCADMAQMRC MAQ ON (MAQ.BDCODEMP = MOV.BDCODEMP AND MAQ.BDORDEMMAQ = MOV.BDORDEMMAQ)
      LEFT OUTER JOIN VEF_EMP_TREDZ MOV1250 ON (MOV1250.BDCODEMP = PRO.BDCODEMP AND MOV1250.BDCHAVE = PRO.BDCHAVE)
      LEFT OUTER JOIN VEF_EMP_TDOCECF I1250 ON (I1250.BDCODEMP = PRO.BDCODEMP AND I1250.BDCHAVE = PRO.BDCHAVE AND I1250.BDORDEMDOCECF = PRO.BDORDEM)
      LEFT OUTER JOIN VEF_BASE_TCADMAQMRC MAQ1250 ON (MAQ1250.BDCODEMP = MOV1250.BDCODEMP AND MAQ1250.BDORDEMMAQ = MOV1250.BDORDEMMAQ)
      LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MC181 ON (MC181.BDMODELO = C181.BDMODELO)
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS MC160 ON (MC160.BDCODDOCFIS = I.BDCODDOCFIS)
      LEFT OUTER JOIN VEF_BASE_TTABDOCFIS M1250 ON (M1250.BDCODDOCFIS = I1250.BDCODDOCFIS)
      WHERE (C113.BDORDEMDOCFREF IS NULL)
      AND ((MAQ.BDSERIEMAQ = C181.BDSERIEMAQ AND MC160.BDDOCFIS = MC181.BDMODELOSTR
      AND I.BDDATAEMI = C181.BDDTEMISSAO AND I.BDNUMDOCCOO = C181.BDNUMDOC) OR
      (MAQ1250.BDSERIEMAQ = C181.BDSERIEMAQ AND M1250.BDDOCFIS = MC181.BDMODELOSTR
      AND I1250.BDDATAEMI = C181.BDDTEMISSAO AND I1250.BDNUMDOCCOO = C181.BDNUMDOC))
      UNION ALL /*SAI DEV*/
      SELECT :PRSESSAO,SAI.BDCODEMP,7,SAI.BDREFERENCIA,SAI.BDCODPROD,'DEVS',SAI.BDCHAVE,
      GETORDEMSEQUENCIAL_STR('DEVS.'||SAI.BDCHAVE||SAI.BDCODEMP, :prCODEMP),
      ((PRO.BDVLRITEM + COALESCE(PRO.BDVLRFRETE,0)+COALESCE(PRO.BDVLRSEGURO,0)+COALESCE(PRO.BDVLRDESPACESSORIA,0))-(COALESCE(PRO.BDVLRDESC,0)+COALESCE(PRO.BDVLRABATNT,0)+COALESCE(PRO.BDREDBCICMS,0)))*-1 BDBCICMSOPPRESUMIDO,
      (IIF(PRO.BDBCST > 0, PRO.BDBCST, IIF(PRO.BDBCICMSSTRET > 0,PRO.BDBCICMSSTRET, IIF(ORI.BDBCST > 0,ORI.BDBCST,IIF(ORI.BDBCICMSSTRET > 0,ORI.BDBCICMSSTRET,0)))))*-1 BCICMSSTPRESUMIDO,
      SAI.BDDATAEMISSAO, PRO.BDQTDITEM*-1, SAI.BDREFLAN, SAI.BDCHAVESAI, IIF(PRO.BDALIQFCPRETIDO > 0, PRO.BDALIQFCPRETIDO ,PRO.BDALIQFCPSTRET) BDALIQST,
      SAI.BDREGVALOR, SAI.BDORDEM, SAI.BDORDEMPROD,SAI.BDDATALAN
      FROM (
          SELECT SAI.BDCODEMP, SAI.BDCHAVE BDCHAVESAI,TAB.BDCODPROD, TAB.BDREFERENCIA,TAB.BDCHAVE, SAI.BDDATAEMISSAO,SAI.BDREFLAN, TAB.BDDATALAN,
          COALESCE(CALC.BDREGVALOR,TAB.BDREG) BDREGVALOR, TAB.BDORDEM, TAB.BDORDEMPROD
          FROM (
                  SELECT SAI.BDCODEMP,SAI.BDCHAVE,I.BDORDEM, SAI.BDREFLAN, SAI.BDDATAEMISSAO, PROSAI.BDCODPROD
                  FROM VEF_EMP_TMOVSAI SAI
                  JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = SAI.BDCODEMP AND I.BDCHAVE = SAI.BDCHAVE)
                  JOIN VEF_EMP_TMOVPROSAI PROSAI on (PROSAI.BDCODEMP = I.BDCODEMP and PROSAI.BDCHAVE = I.BDCHAVE)
                  JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
                  WHERE SAI.BDCODEMP = :PRCODEMP AND SAI.BDCODSITNF NOT IN (2,3,4,5)
                  AND NAT.BDDEVOL = IIF(:PRCODUF = 19, 'NOT', 'TRUE')
              ) SAI
           LEFT OUTER JOIN TMP_VEF_EMP_TICMSSPED_1250_TEMP TAB ON (TAB.BDCODEMP = SAI.BDCODEMP AND TAB.BDSESSAO = :PRSESSAO AND TAB.BDCODPROD = SAI.BDCODPROD AND TAB.BDREFERENCIA = :PRREF AND TAB.BDREG IN ('C185', 'C380','C480'))
           LEFT OUTER JOIN TMP_VEF_EMP_TMEMCALC_1250_TEMP CALC ON (CALC.BDSESSAO = :PRSESSAO AND CALC.BDCODEMP = TAB.BDCODEMP AND CALC.BDCHAVE = TAB.BDCHAVE AND CALC.BDCODPROD = TAB.BDCODPROD AND CALC.BDREG = 'MINV' AND CALC.BDREGVALOR = TAB.BDREG AND CALC.BDORDEM = TAB.BDORDEM AND CALC.BDORDEMPROD = TAB.BDORDEMPROD)
           WHERE SUBSTRING(TAB.BDREFERENCIA FROM 1 FOR 4) >= IIF(:PRCODUF = 19, '2024', '2021')
           AND SAI.BDREFLAN > COALESCE(CALC.BDREFLAN,'202012') AND IIF(:PRCODUF = 19, extract(year from SAI.BDDATAEMISSAO)||LPAD(extract(month from SAI.BDDATAEMISSAO), 2, '0') <= extract(year from TAB.BDDATALAN)||LPAD(extract(month from TAB.BDDATALAN), 2, '0'), SAI.BDDATAEMISSAO <= TAB.BDDATALAN)
       ) SAI
       JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCHAVE = SAI.BDCHAVESAI AND PRO.BDORDEM = SAI.BDORDEM)
      LEFT OUTER JOIN VEF_EMP_TMOVPROSAIIMPORI ORI ON (ORI.BDCODEMP = PRO.BDCODEMP AND ORI.BDCHAVE = PRO.BDCHAVE AND ORI.BDORDEM = PRO.BDORDEM AND ORI.BDCODPROD = PRO.BDCODPROD AND ORI.BDORDEMHIST = PRO.BDORDEMPRO)
       WHERE PRO.BDCODPROD = SAI.BDCODPROD;

      /*VAI INSERIR AS DEVOLUÇÕES DE ENTRADAS PARAS OS LANÇAMENTOS CORRETOS*/
      INSERT INTO TMP_VEF_EMP_TMEMCALC_1250_TEMP (BDSESSAO,BDCODEMP,BDCODPERIODO,BDREFERENCIA, BDCODPROD, BDREG,BDCHAVE,BDORDEMCALC,
                                                  BDBCICMSOPPRESUMIDO,BDBCICMSSTPRESUMIDO,BDDATALAN,BDQUANTIDADE,BDREFLAN,BDCHAVELANCALC,BDALIQST,BDREGVALOR,BDORDEM,BDORDEMPROD,BDDATALANNOTA)
      SELECT :PRSESSAO, TAB.BDCODEMP,7,CALC.BDREFERENCIA,CALC.BDCODPROD,'DEVE',
      TAB.BDCHAVE,GETORDEMSEQUENCIAL_STR('DEVE.'||TAB.BDCHAVE||TAB.BDCODEMP, :prCODEMP),
      CALC.BDBCICMSOPPRESUMIDO, CAST((CAST((CALC.BDBCICMSSTPRESUMIDO/CALC.BDQUANTIDADE) AS NUMERIC(15,6))*CALC.BDQTDDEV) AS NUMERIC(15,6)) BDBCICMSSTPRESUMIDO,
      CALC.BDDATALAN, CALC.BDQTDDEV,CALC.BDREFERENCIA, CALC.BDCHAVELANCALC,
      CALC.BDALIQST, TAB.BDREG, TAB.BDORDEM,TAB.BDORDEMPROD, TAB.BDDATALAN
      FROM(
      SELECT CALC.BDSESSAO, CALC.BDCODEMP, CALC.BDREFERENCIA,MIN(CALC.BDCHAVELANCALC) BDCHAVELANCALC, CALC.BDCODPROD,CALC.BDBCICMSOPPRESUMIDO,
            CALC.BDBCICMSSTPRESUMIDO, CALC.BDDATALANNOTA, CALC.BDDATALAN, CALC.BDQUANTIDADE, CALC.BDQTDDEV,CALC.BDALIQST, MIN(CALC.BDREGVALOR) BDREGVALOR
      FROM (
           SELECT CALC.BDSESSAO, CALC.BDCODEMP, CALC.BDREFERENCIA,CALCD.BDCHAVELANCALC, CALC.BDCODPROD,CALCD.BDBCICMSOPPRESUMIDO,
           SUM(CALC.BDBCICMSSTPRESUMIDO) BDBCICMSSTPRESUMIDO, CALCD.BDDATALANNOTA, CALCD.BDDATALAN, SUM(CALC.BDQUANTIDADE) BDQUANTIDADE,
           CALCD.BDQUANTIDADE BDQTDDEV,CALCD.BDALIQST,CALC.BDREGVALOR, CALC.BDCHAVE
           FROM  TMP_VEF_EMP_TMEMCALC_1250_TEMP CALC
           JOIN TMP_VEF_EMP_TMEMCALC_1250_TEMP CALCD ON (CALCD.BDSESSAO = CALC.BDSESSAO AND CALCD.BDCODEMP = CALC.BDCODEMP AND CALCD.BDREFERENCIA = CALC.BDREFERENCIA AND CALCD.BDCODPROD = CALC.BDCODPROD AND CALCD.BDREG = 'DEVT')
           WHERE CALC.BDREG <> 'DEVT' AND
           CALC.BDCODEMP =  :PRCODEMP AND CALC.BDSESSAO = :PRSESSAO AND
           CALC.BDREFERENCIA = :PRREF AND CALC.BDDATALANNOTA = CALCD.BDDATALANNOTA
           GROUP BY CALC.BDCODEMP, CALC.BDREFERENCIA, CALC.BDCODPROD,CALC.BDSESSAO,CALCD.BDBCICMSOPPRESUMIDO , CALCD.BDDATALANNOTA,
           CALCD.BDDATALAN,CALCD.BDQUANTIDADE,CALCD.BDCHAVELANCALC,CALCD.BDALIQST,CALC.BDREGVALOR, CALC.BDCHAVE
      ) CALC
      GROUP BY CALC.BDSESSAO, CALC.BDCODEMP, CALC.BDREFERENCIA,CALC.BDCODPROD,CALC.BDBCICMSOPPRESUMIDO,
            CALC.BDBCICMSSTPRESUMIDO, CALC.BDDATALANNOTA, CALC.BDDATALAN, CALC.BDQUANTIDADE, CALC.BDQTDDEV,CALC.BDALIQST
      ) CALC
      JOIN TMP_VEF_EMP_TICMSSPED_1250_TEMP TAB ON (TAB.BDCODEMP = CALC.BDCODEMP AND TAB.BDSESSAO = CALC.BDSESSAO AND TAB.BDREFERENCIA = CALC.BDREFERENCIA AND TAB.BDCODPROD = CALC.BDCODPROD /*AND TAB.BDREG = CALC.BDREGVALOR*/)
      WHERE SUBSTRING(TAB.BDREFERENCIA FROM 1 FOR 4) >= IIF(:PRCODUF = 19, '2024', '2021')
      AND TAB.BDREG IN ('C185','C380','C480')
      AND IIF(:PRCODUF = 19, extract(year from TAB.BDDATALAN)||LPAD(extract(month from TAB.BDDATALAN), 2, '0') = extract(year from CALC.BDDATALAN)||LPAD(extract(month from CALC.BDDATALAN), 2, '0'), TAB.BDDATALAN >= CALC.BDDATALAN);

       INSERT INTO TMP_VEF_EMP_TVLRPRES_1250_TEMP (BDCODEMP,BDCHAVE,BDREFERENCIA,BDCODPROD,BDVLRICMSOPPRESUMIDO,BDVLRICMSSTPRESUMIDO,BDREGVALOR,BDORDEM,BDORDEMPROD, BDSESSAO)
         SELECT CALC.BDCODEMP, CALC.BDCHAVE,CALC.BDREFERENCIA, CALC.BDCODPROD,(CALC.BDBCICMSOPPRESUMIDO/IIF(CALC.BDQUANTIDADE > 0,COALESCE(CALC.BDQUANTIDADE,1) ,1))* (IIF(COALESCE(VINC.BDALIQICMS,0) > 0,VINC.BDALIQICMS,UF.BDALIQINT)/100),
         (CALC.BDBCICMSSTPRESUMIDO/IIF(CALC.BDQUANTIDADE > 0,COALESCE(CALC.BDQUANTIDADE,1) ,1))* (IIF(COALESCE(VINC.BDALIQICMS,0) > 0,(VINC.BDALIQICMS/100),(UF.BDALIQINT/100))+(BDALIQST/100)) BDSTUNI,
         CALC.BDREGVALOR, CALC.BDORDEM, CALC.BDORDEMPROD, :PRSESSAO
         FROM (
              SELECT BDCODEMP,BDCHAVE,CALC.BDREFERENCIA,CALC.BDCODPROD,SUM(CALC.BDQUANTIDADE) BDQUANTIDADE,
              SUM(CALC.BDBCICMSOPPRESUMIDO) BDBCICMSOPPRESUMIDO,SUM(CALC.BDBCICMSSTPRESUMIDO) BDBCICMSSTPRESUMIDO,COALESCE(MAX(CALC.BDALIQST),0) BDALIQST, CALC.BDREGVALOR, CALC.BDORDEM, CALC.BDORDEMPROD
              FROM TMP_VEF_EMP_TMEMCALC_1250_TEMP CALC
              WHERE BDCODEMP = :PRCODEMP AND BDSESSAO = :PRSESSAO
              AND BDREFERENCIA = :PRREF AND BDREG NOT IN ('DEVT')
              GROUP BY BDCODEMP,BDCHAVE,CALC.BDREFERENCIA,CALC.BDCODPROD,CALC.BDREGVALOR, CALC.BDORDEM, CALC.BDORDEMPROD
               ) CALC
       LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = CALC.BDCODEMP AND VINC.BDCODPROD = CALC.BDCODPROD)
       LEFT OUTER JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = CALC.BDCODEMP)
       LEFT OUTER JOIN TCIDADE CID ON (CID.BDCODCID = EMP.BDCODCID)
       LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = CID.BDCODUF);

       UPDATE TMP_VEF_EMP_TICMSSPED_1250_TEMP T -- Alt.: #231593 - Colocado "COALESCE" para nao zerar...
       SET BDICMSOPPRESUMIDO = COALESCE((SELECT FIRST 1 P.BDVLRICMSOPPRESUMIDO FROM TMP_VEF_EMP_TVLRPRES_1250_TEMP P WHERE T.BDCODEMP = P.BDCODEMP AND T.BDREFERENCIA = P.BDREFERENCIA AND
                                         T.BDSESSAO = P.BDSESSAO AND T.BDCHAVE = P.BDCHAVE AND T.BDCODPROD = P.BDCODPROD AND T.BDREG = P.BDREGVALOR AND T.BDORDEM = P.BDORDEM AND
                                         T.BDORDEMPROD = P.BDORDEMPROD), T.BDICMSOPPRESUMIDO),
           BDICMSSTPRESUMIDO = COALESCE((SELECT FIRST 1 P.BDVLRICMSSTPRESUMIDO FROM TMP_VEF_EMP_TVLRPRES_1250_TEMP P WHERE T.BDCODEMP = P.BDCODEMP AND T.BDREFERENCIA = P.BDREFERENCIA AND
                                         T.BDSESSAO = P.BDSESSAO AND T.BDCHAVE = P.BDCHAVE AND T.BDCODPROD = P.BDCODPROD AND T.BDREG = P.BDREGVALOR AND T.BDORDEM = P.BDORDEM AND
                                         T.BDORDEMPROD = P.BDORDEMPROD), T.BDICMSSTPRESUMIDO)
       WHERE T.BDSESSAO = :PRSESSAO AND T.BDCODEMP = :PRCODEMP;

END
^

CREATE OR ALTER procedure SP_DEVOLUCOES_PLANO_1250 (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer,
    PRCODUF integer = 23)
as
declare variable WREFERENCIA integer;
declare variable WCHAVE integer;
declare variable WORDEM integer;
declare variable WORDEMPROD integer;
declare variable WBDREFLAN integer;
declare variable WVLRICMSOPPRESUMIDO DM_NUMERIC_15_2;
declare variable WVLRICMSSTPRESUMIDO DM_NUMERIC_15_2;
BEGIN
    /*--------------------------------------------------C181---------------------------------------------------------------*/
      /*REGISTRO C181 - ENTRADA - OLHANDO A DEVOLUÇÃO PELO C113*/
     INSERT INTO TMP_VEF_EMP_TICMSSPED_1250_TEMP (BDSESSAO, BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCHAVE, BDORDEM,
                                                 BDORDEMPROD, BDCODPROD, BDCSTICMS, BDCODNAT, BDMOTIVO, BDQUANTIDADE,
                                                 BDVLRUNITICMSEFETIVO ,BDICMSOPPRESUMIDO,BDICMSSTPRESUMIDO,BDVLRRESTITUIR,BDVLRCOMPLEMENTAR,
                                                 BDREG,BDVERIFICLANANTDEV,BDREFLANSAIDADEV2021,BDNUMDOCINI,BDCHAVEDEV,BDORDEMDEV,BDORDEMPRODEV,BDDATALAN,BDCODINCO)
     SELECT  :PRSESSAO, ENT.BDCODEMP,7, ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,
             CASE INF.BDCODAJUR
             WHEN 'RS000' THEN 17 /*RS500*/ WHEN 'RS001' THEN 18 /*RS501*/ WHEN 'RS100' THEN 19 /*RS600*/
             WHEN 'RS213' THEN 20 /*RS713*/ WHEN 'RS214' THEN 21 /*RS714*/ WHEN 'RS217' THEN 22 /*RS717*/
             WHEN 'RS219' THEN 23 /*RS719*/ WHEN 'RS300' THEN 24 /*RS800*/
             WHEN 'RJ000' THEN 29 /*RJ500*/ WHEN 'RJ100' THEN 30 /*RJ600*/ WHEN 'RJ300' THEN 31 /*RJ800*/ END BDMOTIVO, ENT.BDQTDITEM,
             TAB.BDVLRUNITICMSEFETIVO,TAB.BDICMSOPPRESUMIDO, TAB.BDICMSSTPRESUMIDO,
             IIF(TAB.BDVLRCOMPLEMENTAR > 0,(TAB.BDVLRUNITICMSEFETIVO - TAB.BDICMSOPPRESUMIDO - TAB.BDICMSSTPRESUMIDO) ,0) BDVLRRESTITUIR,
             IIF(INF.BDCODAJUR = IIF(:PRCODUF = 19,'RJ100','RS100'),(TAB.BDICMSOPPRESUMIDO + TAB.BDICMSSTPRESUMIDO)-TAB.BDVLRUNITICMSEFETIVO,IIF((INF.BDCODAJUR IN ('RS213','RS214','RS217','RS219')),TAB.BDICMSSTPRESUMIDO,0)) BDVLRCOMPLEMENTAR,
             'C181', IIF(ENT.BDREFLAN >= IIF(:PRCODUF = 19, 202406, 202101) AND ENT.BDREFLANSAI < IIF(:PRCODUF = 19, 202406, 202101),'TRUE','FALSE'),ENT.BDREFLANSAI, ENT.BDNUMDOCINI,
             TAB.BDCHAVE, TAB.BDORDEM, TAB.BDORDEMPROD, ENT.BDDATAENTRADAENT,
             IIF(TAB.BDCHAVE IS NULL,37,IIF((COALESCE(INF.BDCODAJUR,0) IN ('RS000','RS001','RS100','RS213','RS214','RS217','RS219','RS300','RJ000','RJ100','RJ300')), NULL,1)) BDCODINCO
      FROM(
           SELECT ENT.BDCODEMP,ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,
                  ENT.BDQTDITEM,ENT.BDDATAENTRADAENT, SAI.BDREFLAN BDREFLANSAI,ENT.BDNUMDOCINI,
                  SAI.BDCHAVE BDCHAVESAI, PRO.BDORDEM BDORDEMSAI, PRO.BDORDEMPRO BDORDEMPROSAI
             FROM(
                    SELECT COALESCE(PRO.BDCODEMP,MOV.BDCODEMP) BDCODEMP, MOV.BDREFLAN,MOV.BDCHAVE, I.BDORDEM, PRO.BDORDEMPRO,PRO.BDCODPROD, PRO.BDCODCSTICMS,
                    I.BDCODNAT,IIF(PRO.BDQTDITEM > 0,PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1) BDQTDITEM, MOV.BDNUMDOCINI, MOV.BDDATAENTRADAENT
                    FROM VEF_EMP_TMOVENT MOV
                    LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                    JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
                    LEFT OUTER JOIN VEF_EMP_TMOVPROENTIMPORI ORI ON (ORI.BDCODEMP = MOV.BDCODEMP AND ORI.BDCHAVE = PRO.BDCHAVE AND ORI.BDORDEM = PRO.BDORDEM AND ORI.BDCODPROD = PRO.BDCODPROD)
                    LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MODE ON (MODE.BDMODELO = MOV.BDMODELO)
                    LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
                    LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON)
                    WHERE MOV.BDCODEMP = :PRCODEMP AND
                          MOV.BDREFLAN = :PRREF AND
                          NAT.BDDEVOL = 'TRUE'  AND
                          MOV.BDCODSITNF NOT IN (2,3,4,5)
                  ) ENT
      JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = ENT.BDCODEMP AND C113.BDCHAVE = ENT.BDCHAVE)
      LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCODPROD = ENT.BDCODPROD)
      LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = PRO.BDCODEMP AND SAI.BDCHAVE = PRO.BDCHAVE)
      WHERE ((SAI.BDNUMDOCINI = C113.BDNUMDOC AND COALESCE(SAI.BDCHAVENFE,0) = IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '', 0, C113.BDCHAVENFE)
      AND SAI.BDDATAEMISSAO = C113.BDDTEMISSAO)) AND SAI.BDREFLAN >= IIF(:PRCODUF = 19, 202406, 202101)
          ) ENT
      LEFT OUTER JOIN VEF_EMP_TICMSSPED_1250_C185 TAB ON (TAB.BDCODEMP = ENT.BDCODEMP AND TAB.BDCODPROD = ENT.BDCODPROD AND TAB.BDCHAVE = ENT.BDCHAVESAI AND TAB.BDORDEM = ENT.BDORDEMSAI AND TAB.BDORDEMPROD = ENT.BDORDEMPROSAI)
      LEFT OUTER JOIN VEF_BASE_TTABINFAD57 INF ON (INF.BDORDEM57 = TAB.BDMOTIVO);


      INSERT INTO TMP_VEF_EMP_TICMSSPED_1250_TEMP (BDSESSAO, BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCHAVE, BDORDEM,
                                                   BDORDEMPROD, BDCODPROD, BDCSTICMS, BDCODNAT, BDMOTIVO, BDQUANTIDADE,
                                                   BDVLRUNITICMSEFETIVO ,BDICMSOPPRESUMIDO,BDICMSSTPRESUMIDO,BDVLRRESTITUIR,BDVLRCOMPLEMENTAR,
                                                   BDREG,BDVERIFICLANANTDEV,BDREFLANSAIDADEV2021,BDNUMDOCINI,BDCHAVEDEV,BDORDEMDEV,BDORDEMPRODEV,BDDATALAN,BDCODINCO)
     SELECT  :PRSESSAO, ENT.BDCODEMP,7, ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,
             CASE INF.BDCODAJUR
             WHEN 'RS000' THEN 17 /*RS500*/ WHEN 'RS001' THEN 18 /*RS501*/ WHEN 'RS100' THEN 19 /*RS600*/
             WHEN 'RS213' THEN 20 /*RS713*/ WHEN 'RS214' THEN 21 /*RS714*/ WHEN 'RS217' THEN 22 /*RS717*/
             WHEN 'RS219' THEN 23 /*RS719*/ WHEN 'RS300' THEN 24 /*RS800*/
             WHEN 'RJ000' THEN 29 /*RJ500*/ WHEN 'RJ100' THEN 30 /*RJ600*/ WHEN 'RJ300' THEN 31 /*RJ800*/ END BDMOTIVO, ENT.BDQTDITEM,
             TAB.BDVLRUNITICMSEFETIVO,TAB.BDICMSOPPRESUMIDO, TAB.BDICMSSTPRESUMIDO,
             IIF(TAB.BDVLRCOMPLEMENTAR > 0,(TAB.BDVLRUNITICMSEFETIVO - TAB.BDICMSOPPRESUMIDO - TAB.BDICMSSTPRESUMIDO) ,0) BDVLRRESTITUIR,
             IIF(INF.BDCODAJUR = IIF(:PRCODUF = 19,'RJ100','RS100'),(TAB.BDICMSOPPRESUMIDO + TAB.BDICMSSTPRESUMIDO)-TAB.BDVLRUNITICMSEFETIVO,IIF((INF.BDCODAJUR IN ('RS213','RS214','RS217','RS219')),TAB.BDICMSSTPRESUMIDO,0)) BDVLRCOMPLEMENTAR,
             'C181', IIF(ENT.BDREFLAN >= IIF(:PRCODUF = 19, 202406, 202101) AND ENT.BDREFLANSAI < IIF(:PRCODUF = 19, 202406, 202101),'TRUE','FALSE'),ENT.BDREFLANSAI, ENT.BDNUMDOCINI,
             TAB.BDCHAVE, TAB.BDORDEM, TAB.BDORDEMPROD, ENT.BDDATAENTRADAENT,
             IIF(TAB.BDCHAVE IS NULL,37,IIF((COALESCE(INF.BDCODAJUR,0) IN ('RS000','RS001','RS100','RS213','RS214','RS217','RS219','RS300','RJ000','RJ100','RJ300')), NULL,1)) BDCODINCO
      FROM(
           SELECT ENT.BDCODEMP,ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,
                  ENT.BDQTDITEM,ENT.BDDATAENTRADAENT, SAI.BDREFLAN BDREFLANSAI,ENT.BDNUMDOCINI,
                  SAI.BDCHAVE BDCHAVESAI, PRO.BDORDEM BDORDEMSAI, PRO.BDORDEMPRO BDORDEMPROSAI
             FROM(
                    SELECT COALESCE(PRO.BDCODEMP,MOV.BDCODEMP) BDCODEMP, MOV.BDREFLAN,MOV.BDCHAVE, I.BDORDEM, PRO.BDORDEMPRO,PRO.BDCODPROD, PRO.BDCODCSTICMS,
                    I.BDCODNAT,IIF(PRO.BDQTDITEM > 0,PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1) BDQTDITEM, MOV.BDNUMDOCINI, MOV.BDDATAENTRADAENT
                    FROM VEF_EMP_TMOVENT MOV
                    LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                    JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
                    LEFT OUTER JOIN VEF_EMP_TMOVPROENTIMPORI ORI ON (ORI.BDCODEMP = MOV.BDCODEMP AND ORI.BDCHAVE = PRO.BDCHAVE AND ORI.BDORDEM = PRO.BDORDEM AND ORI.BDCODPROD = PRO.BDCODPROD)
                    LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MODE ON (MODE.BDMODELO = MOV.BDMODELO)
                    LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
                    LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON)
                    WHERE MOV.BDCODEMP = :PRCODEMP AND
                          MOV.BDREFLAN = :PRREF AND
                          NAT.BDDEVOL = 'TRUE'  AND
                          MOV.BDCODSITNF NOT IN (2,3,4,5)
                  ) ENT
      JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = ENT.BDCODEMP AND C113.BDCHAVE = ENT.BDCHAVE)
      LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCODPROD = ENT.BDCODPROD)
      LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = PRO.BDCODEMP AND SAI.BDCHAVE = PRO.BDCHAVE)
      WHERE ((SAI.BDNUMDOCINI = C113.BDNUMDOC AND COALESCE(SAI.BDCHAVENFE,0) = IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '', 0, C113.BDCHAVENFE)
      AND SAI.BDDATAEMISSAO = C113.BDDTEMISSAO))  AND SAI.BDREFLAN >= IIF(:PRCODUF = 19, 202406, 202101)
          ) ENT
      LEFT OUTER JOIN VEF_EMP_TICMSSPED_1250_C380 TAB ON (TAB.BDCODEMP = ENT.BDCODEMP AND TAB.BDCODPROD = ENT.BDCODPROD AND TAB.BDCHAVE = ENT.BDCHAVESAI AND TAB.BDORDEM = ENT.BDORDEMSAI AND TAB.BDORDEMPROD = ENT.BDORDEMPROSAI)
      LEFT OUTER JOIN VEF_BASE_TTABINFAD57 INF ON (INF.BDORDEM57 = TAB.BDMOTIVO)
      WHERE NOT EXISTS (SELECT BDCODEMP FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP T1250
      WHERE T1250.BDCODEMP = ENT.BDCODEMP AND T1250.BDSESSAO = :PRSESSAO
      AND T1250.BDREFERENCIA = ENT.BDREFLAN AND T1250.BDCHAVE = ENT.BDCHAVE
      AND T1250.BDORDEM = ENT.BDORDEM AND T1250.BDORDEMPROD = ENT.BDORDEMPRO
      AND T1250.BDREG = 'C181');


     /*REGISTRO C181 - ENTRADA - OLHANDO A DEVOLUÇÃO PELO C181 - REDUÇÃO Z - Documento 02*/
      INSERT INTO TMP_VEF_EMP_TICMSSPED_1250_TEMP (BDSESSAO, BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCHAVE, BDORDEM,
                                                 BDORDEMPROD, BDCODPROD, BDCSTICMS, BDCODNAT, BDMOTIVO, BDQUANTIDADE,
                                                 BDVLRUNITICMSEFETIVO ,BDICMSOPPRESUMIDO,BDICMSSTPRESUMIDO,BDVLRRESTITUIR,BDVLRCOMPLEMENTAR,
                                                 BDREG,BDVERIFICLANANTDEV,BDREFLANSAIDADEV2021,BDNUMDOCINI,BDCHAVEDEV,BDORDEMDEV,BDORDEMPRODEV,BDDATALAN,BDCODINCO)
           SELECT  :PRSESSAO, ENT.BDCODEMP,7, ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,
             CASE INF.BDCODAJUR
             WHEN 'RS000' THEN 17 /*RS500*/ WHEN 'RS001' THEN 18 /*RS501*/ WHEN 'RS100' THEN 19 /*RS600*/
             WHEN 'RS213' THEN 20 /*RS713*/ WHEN 'RS214' THEN 21 /*RS714*/ WHEN 'RS217' THEN 22 /*RS717*/
             WHEN 'RS219' THEN 23 /*RS719*/ WHEN 'RS300' THEN 24 /*RS800*/
             WHEN 'RJ000' THEN 29 /*RJ500*/ WHEN 'RJ100' THEN 30 /*RJ600*/ WHEN 'RJ300' THEN 31 /*RJ800*/ END BDMOTIVO, ENT.BDQTDITEM,
             TAB.BDVLRUNITICMSEFETIVO,TAB.BDICMSOPPRESUMIDO, TAB.BDICMSSTPRESUMIDO,
             IIF(TAB.BDVLRCOMPLEMENTAR > 0,(TAB.BDVLRUNITICMSEFETIVO - TAB.BDICMSOPPRESUMIDO - TAB.BDICMSSTPRESUMIDO) ,0) BDVLRRESTITUIR,
             IIF(INF.BDCODAJUR = IIF(:PRCODUF = 19,'RJ100','RS100'),(TAB.BDICMSOPPRESUMIDO + TAB.BDICMSSTPRESUMIDO)-TAB.BDVLRUNITICMSEFETIVO,IIF((INF.BDCODAJUR IN ('RS213','RS214','RS217','RS219')),TAB.BDICMSSTPRESUMIDO,0)) BDVLRCOMPLEMENTAR,
             'C181', IIF(ENT.BDREFLAN >= IIF(:PRCODUF = 19, 202406, 202101) AND ENT.BDREFLANRED < IIF(:PRCODUF = 19, 202406, 202101),'TRUE','FALSE'),ENT.BDREFLANRED, ENT.BDNUMDOCINI,
             TAB.BDCHAVE, TAB.BDORDEM, TAB.BDORDEMPROD, ENT.BDDATAENTRADAENT, IIF(TAB.BDCHAVE IS NULL,37,IIF((COALESCE(INF.BDCODAJUR,0) IN ('RS000','RS001','RS100','RS213','RS214','RS217','RS219','RS300','RJ000','RJ100','RJ300')), NULL,1)) BDCODINCO
        FROM(
             SELECT ENT.BDCODEMP, ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,
                    ENT.BDQTDITEM,ENT.BDNUMDOCINI,ENT.BDDATAENTRADAENT,
                    MOV.BDREFLAN BDREFLANRED,
                    PRO.BDCHAVE BDCHAVERED, PRO.BDORDEMDOCECF BDORDEMRED, PRO.BDORDEMITEM BDORDEMPRORED
             FROM(
                   SELECT COALESCE(PRO.BDCODEMP,MOV.BDCODEMP) BDCODEMP, MOV.BDREFLAN,MOV.BDCHAVE, I.BDORDEM, PRO.BDORDEMPRO,PRO.BDCODPROD, PRO.BDCODCSTICMS,
                    I.BDCODNAT,IIF(PRO.BDQTDITEM > 0,PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1) BDQTDITEM, MOV.BDNUMDOCINI, MOV.BDDATAENTRADAENT
                    FROM VEF_EMP_TMOVENT MOV
                    LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                    JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
                    LEFT OUTER JOIN VEF_EMP_TMOVPROENTIMPORI ORI ON (ORI.BDCODEMP = MOV.BDCODEMP AND ORI.BDCHAVE = PRO.BDCHAVE AND ORI.BDORDEM = PRO.BDORDEM AND ORI.BDCODPROD = PRO.BDCODPROD)
                    LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MODE ON (MODE.BDMODELO = MOV.BDMODELO)
                    LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
                    LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON)
                    WHERE MOV.BDCODEMP = :PRCODEMP AND MOV.BDREFLAN = :PRREF AND NAT.BDDEVOL = 'TRUE' AND MOV.BDCODSITNF NOT IN (2,3,4,5)
                ) ENT
             LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = ENT.BDCODEMP AND C113.BDCHAVE = ENT.BDCHAVE)
             LEFT OUTER JOIN VEF_EMP_TMOVC181_1250 C181 ON (C181.BDCODEMP = ENT.BDCODEMP AND C181.BDCHAVE = ENT.BDCHAVE)
             LEFT OUTER JOIN VEF_EMP_TITEMDOCECF PRO ON (PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCODPROD = ENT.BDCODPROD)
             LEFT OUTER JOIN VEF_EMP_TREDZ MOV ON (MOV.BDCODEMP = PRO.BDCODEMP AND MOV.BDCHAVE = PRO.BDCHAVE)
             LEFT OUTER JOIN VEF_EMP_TDOCECF I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDORDEMDOCECF = PRO.BDORDEMDOCECF)
             LEFT OUTER JOIN VEF_BASE_TCADMAQMRC MAQ ON (MAQ.BDCODEMP = MOV.BDCODEMP AND MAQ.BDORDEMMAQ = MOV.BDORDEMMAQ)
             LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MC181 ON (MC181.BDMODELO = C181.BDMODELO)
             LEFT OUTER JOIN VEF_BASE_TTABDOCFIS MC160 ON (MC160.BDCODDOCFIS = I.BDCODDOCFIS)
             WHERE (C113.BDORDEMDOCFREF IS NULL)
             AND (MAQ.BDSERIEMAQ = C181.BDSERIEMAQ AND MC160.BDDOCFIS = MC181.BDMODELOSTR
             AND I.BDDATAEMI = C181.BDDTEMISSAO AND I.BDNUMDOCCOO = C181.BDNUMDOC) AND MOV.BDREFLAN >= IIF(:PRCODUF = 19, 202406, 202101)
            ) ENT
        LEFT OUTER JOIN VEF_EMP_TICMSSPED_1250_C480 TAB ON (TAB.BDCODEMP = ENT.BDCODEMP AND TAB.BDCHAVE = ENT.BDCHAVERED AND TAB.BDORDEM = ENT.BDORDEMRED AND TAB.BDORDEMPROD = ENT.BDORDEMPRORED)
        LEFT OUTER JOIN VEF_BASE_TTABINFAD57 INF ON (INF.BDORDEM57 = TAB.BDMOTIVO)
        WHERE NOT EXISTS (SELECT BDCODEMP FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP T1250
              WHERE T1250.BDCODEMP = ENT.BDCODEMP AND T1250.BDSESSAO = :PRSESSAO
              AND T1250.BDREFERENCIA = ENT.BDREFLAN AND T1250.BDCHAVE = ENT.BDCHAVE
              AND T1250.BDORDEM = ENT.BDORDEM AND T1250.BDORDEMPROD = ENT.BDORDEMPRO
              AND T1250.BDREG = 'C181');


      INSERT INTO TMP_VEF_EMP_TICMSSPED_1250_TEMP (BDSESSAO, BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCHAVE, BDORDEM,
                                                  BDORDEMPROD, BDCODPROD, BDCSTICMS, BDCODNAT, BDMOTIVO, BDQUANTIDADE,
                                                  BDVLRUNITICMSEFETIVO ,BDICMSOPPRESUMIDO,BDICMSSTPRESUMIDO,BDVLRRESTITUIR,BDVLRCOMPLEMENTAR,
                                                  BDREG,BDVERIFICLANANTDEV,BDREFLANSAIDADEV2021,BDNUMDOCINI,BDCHAVEDEV,BDORDEMDEV,BDORDEMPRODEV,BDDATALAN,BDCODINCO)
      SELECT :PRSESSAO, ENT.BDCODEMP,7, ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,
             CASE INF.BDCODAJUR
             WHEN 'RS000' THEN 17 /*RS500*/ WHEN 'RS001' THEN 18 /*RS501*/ WHEN 'RS100' THEN 19 /*RS600*/
             WHEN 'RS213' THEN 20 /*RS713*/ WHEN 'RS214' THEN 21 /*RS714*/ WHEN 'RS217' THEN 22 /*RS717*/
             WHEN 'RS219' THEN 23 /*RS719*/ WHEN 'RS300' THEN 24 /*RS800*/
             WHEN 'RJ000' THEN 29 /*RJ500*/ WHEN 'RJ100' THEN 30 /*RJ600*/ WHEN 'RJ300' THEN 31 /*RJ800*/ END BDMOTIVO, ENT.BDQTDITEM,
             TAB.BDVLRUNITICMSEFETIVO,TAB.BDICMSOPPRESUMIDO, TAB.BDICMSSTPRESUMIDO,
             IIF(TAB.BDVLRCOMPLEMENTAR > 0,(TAB.BDVLRUNITICMSEFETIVO - TAB.BDICMSOPPRESUMIDO - TAB.BDICMSSTPRESUMIDO) ,0) BDVLRRESTITUIR,
             IIF(INF.BDCODAJUR = IIF(:PRCODUF = 19,'RJ100','RS100'),(TAB.BDICMSOPPRESUMIDO + TAB.BDICMSSTPRESUMIDO)-TAB.BDVLRUNITICMSEFETIVO,IIF((INF.BDCODAJUR IN ('RS213','RS214','RS217','RS219')),TAB.BDICMSSTPRESUMIDO,0)) BDVLRCOMPLEMENTAR,
             'C181', IIF(ENT.BDREFLAN >= IIF(:PRCODUF = 19, 202406, 202101) AND ENT.BDREFLANSAI < IIF(:PRCODUF = 19, 202406, 202101),'TRUE','FALSE'),ENT.BDREFLANSAI, ENT.BDNUMDOCINI,
             TAB.BDCHAVE, TAB.BDORDEM, TAB.BDORDEMPROD, ENT.BDDATAENTRADAENT, IIF(TAB.BDCHAVE IS NULL,37,IIF((COALESCE(INF.BDCODAJUR,0) IN ('RS000','RS001','RS100','RS213','RS214','RS217','RS219','RS300','RJ000','RJ100','RJ300')), NULL,1)) BDCODINCO
     FROM(
          SELECT ENT.BDCODEMP,ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,ENT.BDQTDITEM,
                 ENT.BDNUMDOCINI,ENT.BDDATAENTRADAENT, SAI.BDREFLAN BDREFLANSAI,
                 PRO.BDCHAVE BDCHAVESAI, PRO.BDORDEM BDORDEMSAI, PRO.BDORDEMPRO BDORDEMPROSAI
             FROM(
                   SELECT COALESCE(PRO.BDCODEMP,MOV.BDCODEMP) BDCODEMP, MOV.BDREFLAN,MOV.BDCHAVE, I.BDORDEM, PRO.BDORDEMPRO,PRO.BDCODPROD, PRO.BDCODCSTICMS,
                    I.BDCODNAT,IIF(PRO.BDQTDITEM > 0,PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1) BDQTDITEM, MOV.BDNUMDOCINI, MOV.BDDATAENTRADAENT
                    FROM VEF_EMP_TMOVENT MOV
                    LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                    JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
                    LEFT OUTER JOIN VEF_EMP_TMOVPROENTIMPORI ORI ON (ORI.BDCODEMP = MOV.BDCODEMP AND ORI.BDCHAVE = PRO.BDCHAVE AND ORI.BDORDEM = PRO.BDORDEM AND ORI.BDCODPROD = PRO.BDCODPROD)
                    LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MODE ON (MODE.BDMODELO = MOV.BDMODELO)
                    LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
                    LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON)
                    WHERE MOV.BDCODEMP = :PRCODEMP AND MOV.BDREFLAN = :PRREF AND NAT.BDDEVOL = 'TRUE' AND MOV.BDCODSITNF NOT IN (2,3,4,5)
                ) ENT
             LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = ENT.BDCODEMP AND C113.BDCHAVE = ENT.BDCHAVE)
             LEFT OUTER JOIN VEF_EMP_TMOVC181_1250 C181 ON (C181.BDCODEMP = ENT.BDCODEMP AND C181.BDCHAVE = ENT.BDCHAVE)
             LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCODPROD = ENT.BDCODPROD)
             LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = PRO.BDCODEMP AND SAI.BDCHAVE = PRO.BDCHAVE)
             WHERE (C113.BDORDEMDOCFREF IS NULL)
             AND (SAI.BDMODELO = C181.BDMODELO
             AND SAI.BDDATAEMISSAO = C181.BDDTEMISSAO AND SAI.BDNUMDOCINI = C181.BDNUMDOC) AND SAI.BDREFLAN >= IIF(:PRCODUF = 19, 202406, 202101)
             ) ENT
          LEFT OUTER JOIN VEF_EMP_TICMSSPED_1250_C380 TAB ON (TAB.BDCODEMP = ENT.BDCODEMP  AND TAB.BDCHAVE = ENT.BDCHAVESAI AND TAB.BDORDEM = ENT.BDORDEMSAI AND TAB.BDORDEMPROD = ENT.BDORDEMPROSAI)
          LEFT OUTER JOIN VEF_BASE_TTABINFAD57 INF ON (INF.BDORDEM57 = TAB.BDMOTIVO)
          WHERE NOT EXISTS (SELECT BDCODEMP FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP T1250
                WHERE T1250.BDCODEMP = ENT.BDCODEMP AND T1250.BDSESSAO = :PRSESSAO
                AND T1250.BDREFERENCIA = ENT.BDREFLAN AND T1250.BDCHAVE = ENT.BDCHAVE
                AND T1250.BDORDEM = ENT.BDORDEM AND T1250.BDORDEMPROD = ENT.BDORDEMPRO
                AND T1250.BDREG = 'C181');


    /*REGISTRO C181 - A NOTA REFERENCIADA NA DEVOLUÇÃO COM DATA DE EMISSÃO INFERIOR A 202101*/
    /*C181 - C113 COM NOTA REFERENCIADA NA SAÍDA ANTES DE 2021*/
     INSERT INTO TMP_VEF_EMP_TICMSSPED_1250_TEMP (BDSESSAO, BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCHAVE, BDORDEM,
                                                 BDORDEMPROD, BDCODPROD, BDCSTICMS, BDCODNAT, BDMOTIVO, BDQUANTIDADE,
                                                 BDVLRUNITICMSEFETIVO ,BDICMSOPPRESUMIDO,BDICMSSTPRESUMIDO,BDVLRRESTITUIR,BDVLRCOMPLEMENTAR,
                                                 BDREG,BDVERIFICLANANTDEV,BDREFLANSAIDADEV2021,BDNUMDOCINI,BDCHAVEDEV,BDORDEMDEV,BDORDEMPRODEV,BDDATALAN, BDVLRUNIT,BDALIQFCP)
     SELECT distinct :PRSESSAO,ENT.BDCODEMP,7, ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,
            IIF(ENT.BDVLRUNITICMSEFETIVO < (ENT.BDICMSSTPRESUMIDO+ENT.BDICMSOPPRESUMIDO),IIF(:PRCODUF = 19,30,19), IIF(:PRCODUF = 19,31,24)) BDMOTIVO,
            ENT.BDQTDITEM, ENT.BDVLRUNITICMSEFETIVO, ENT.BDICMSOPPRESUMIDO, ENT.BDICMSSTPRESUMIDO,
            IIF(ENT.BDVLRUNITICMSEFETIVO < (ENT.BDICMSSTPRESUMIDO+ENT.BDICMSOPPRESUMIDO),(ENT.BDICMSSTPRESUMIDO+ENT.BDICMSOPPRESUMIDO)-ENT.BDVLRUNITICMSEFETIVO,0) BDVLRRESTITUIR,
            IIF(ENT.BDVLRUNITICMSEFETIVO > (ENT.BDICMSSTPRESUMIDO+ENT.BDICMSOPPRESUMIDO),ENT.BDVLRUNITICMSEFETIVO-(ENT.BDICMSSTPRESUMIDO+ENT.BDICMSOPPRESUMIDO),0) BDVLRRCOMPLEMENTAR,
            'C181','TRUE',ENT.BDREFLANSAI, ENT.BDNUMDOCINI,ENT.BDCHAVESAI, ENT.BDORDEMSAI , ENT.BDORDEMPROSAI , ENT.BDDATAENTRADAENT, ENT.BDVLRUNIT, ENT.BDALIQFCP

     FROM (
             SELECT  ENT.BDCODEMP,ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,
                     ENT.BDQTDITEM,
                     ENT.BDVLRICMSEFET BDVLRUNITICMSEFETIVO,  IIF(COALESCE(PROE.BDVLRICMS,0) > 0,(PROE.BDVLRICMS/(IIF(PROE.BDQTDITEM > 0,PROE.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1))),0) BDICMSOPPRESUMIDO,
                     IIF(COALESCE(PROE.BDVLRST,0) > 0,(PROE.BDVLRST/(IIF(PROE.BDQTDITEM > 0,PROE.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1))),
                       IIF(COALESCE(PROE.BDVLRICMSSTRET,0) > 0,(PROE.BDVLRICMSSTRET/(IIF(PROE.BDQTDITEM > 0,PROE.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1))),0)) BDICMSSTPRESUMIDO,ENT.BDREFLANSAI, ENT.BDNUMDOCINI,
                     ENT.BDCHAVESAI, ENT.BDORDEMSAI , ENT.BDORDEMPROSAI, ENT.BDDATAENTRADAENT, ENT.BDVLRUNIT, ENT.BDALIQFCP
              FROM(
                   SELECT ENT.BDCODEMP,ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,
                          ENT.BDQTDITEM,ENT.BDDATAENTRADAENT, SAI.BDREFLAN BDREFLANSAI,ENT.BDNUMDOCINI,
                          SAI.BDCHAVE BDCHAVESAI, PRO.BDORDEM BDORDEMSAI, PRO.BDORDEMPRO BDORDEMPROSAI,
                          (COALESCE(PRO.BDVLRICMSEFET,0)/(IIF(PRO.BDQTDITEM > 0,PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1))) BDVLRICMSEFET, SAI.BDDATAEMISSAO,
                          ((COALESCE(PRO.BDVLRITEM,0) - COALESCE(PRO.BDVLRABATNT,0) - COALESCE(PRO.BDVLRDESC,0) + COALESCE(PRO.BDVLRFRETE,0) + COALESCE(PRO.BDVLRDESPACESSORIA,0) + COALESCE(PRO.BDVLRSEGURO, 0)) / (IIF(PRO.BDQTDITEM > 0,PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1))) BDVLRUNIT,
                          IIF(COALESCE(PRO.BDALIQFCPRETIDO,0) > 0, PRO.BDALIQFCPRETIDO ,COALESCE(PRO.BDALIQFCPSTRET,0)) BDALIQFCP
                     FROM(
                            SELECT COALESCE(PRO.BDCODEMP,MOV.BDCODEMP) BDCODEMP, MOV.BDREFLAN,MOV.BDCHAVE, I.BDORDEM, PRO.BDORDEMPRO,PRO.BDCODPROD, PRO.BDCODCSTICMS,
                            I.BDCODNAT,IIF(PRO.BDQTDITEM > 0,PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1) BDQTDITEM, MOV.BDNUMDOCINI, MOV.BDDATAENTRADAENT
                            FROM VEF_EMP_TMOVENT MOV
                            LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                            JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
                            LEFT OUTER JOIN VEF_EMP_TMOVPROENTIMPORI ORI ON (ORI.BDCODEMP = MOV.BDCODEMP AND ORI.BDCHAVE = PRO.BDCHAVE AND ORI.BDORDEM = PRO.BDORDEM AND ORI.BDCODPROD = PRO.BDCODPROD)
                            LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MODE ON (MODE.BDMODELO = MOV.BDMODELO)
                            LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
                            LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON)
                            WHERE MOV.BDCODEMP = :PRCODEMP AND
                                  MOV.BDREFLAN = :PRREF AND
                                  NAT.BDDEVOL = 'TRUE'  AND
                                  MOV.BDCODSITNF NOT IN (2,3,4,5)
                          ) ENT
              JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = ENT.BDCODEMP AND C113.BDCHAVE = ENT.BDCHAVE)
              LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCODPROD = ENT.BDCODPROD)
              LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = PRO.BDCODEMP AND SAI.BDCHAVE = PRO.BDCHAVE)
              LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON)
              WHERE ((SAI.BDNUMDOCINI = C113.BDNUMDOC AND COALESCE(SAI.BDCHAVENFE,0) = IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '', 0, C113.BDCHAVENFE)
              AND SAI.BDDATAEMISSAO = C113.BDDTEMISSAO)) AND SAI.BDREFLAN < IIF(:PRCODUF = 19, 202406, 202101)
                  ) ENT
              LEFT OUTER JOIN VEF_EMP_TMOVPROENT PROE ON (PROE.BDCODEMP = ENT.BDCODEMP AND PROE.BDCODPROD =  ENT.BDCODPROD)
              JOIN VEF_EMP_TMOVENT MOVE ON (MOVE.BDCODEMP = PROE.BDCODEMP AND MOVE.BDCHAVE = PROE.BDCHAVE)
              LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PROE.BDCODPROD AND FAT.BDCODFATCON = PROE.BDCODFATCON)
              WHERE (MOVE.BDDATAENTRADAENT <= ENT.BDDATAEMISSAO)
              AND MOVE.BDCHAVE = (SELECT FIRST 1 E.BDCHAVE
                                  FROM VEF_EMP_TMOVENT E
                                  LEFT OUTER JOIN VEF_EMP_TMOVPROENT PE ON (PE.BDCODEMP = E.BDCODEMP AND PE.BDCHAVE = E.BDCHAVE)
                                  WHERE E.BDCODEMP = MOVE.BDCODEMP AND E.BDREFLAN = MOVE.BDREFLAN AND PE.BDCODPROD = PROE.BDCODPROD
                                  AND E.BDDATAENTRADAENT <= ENT.BDDATAEMISSAO
                                  ORDER BY E.BDDATAENTRADAENT DESC)
            ) ENT;

     /*C181 - C181 COM NOTA REFERENCIADA NA SAÍDA ANTES DE 2021*/
     INSERT INTO TMP_VEF_EMP_TICMSSPED_1250_TEMP (BDSESSAO, BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCHAVE, BDORDEM,
                                                 BDORDEMPROD, BDCODPROD, BDCSTICMS, BDCODNAT, BDMOTIVO, BDQUANTIDADE,
                                                 BDVLRUNITICMSEFETIVO ,BDICMSOPPRESUMIDO,BDICMSSTPRESUMIDO,BDVLRRESTITUIR,BDVLRCOMPLEMENTAR,
                                                 BDREG,BDVERIFICLANANTDEV,BDREFLANSAIDADEV2021,BDNUMDOCINI,BDCHAVEDEV,BDORDEMDEV,BDORDEMPRODEV,BDDATALAN, BDVLRUNIT,BDALIQFCP)
     SELECT :PRSESSAO,ENT.BDCODEMP,7, ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,
            IIF(ENT.BDVLRUNITICMSEFETIVO < (ENT.BDICMSSTPRESUMIDO+ENT.BDICMSOPPRESUMIDO),IIF(:PRCODUF = 19,30,19), IIF(:PRCODUF = 19,31,24)) BDMOTIVO,
            ENT.BDQTDITEM, ENT.BDVLRUNITICMSEFETIVO, ENT.BDICMSOPPRESUMIDO, ENT.BDICMSSTPRESUMIDO,
            IIF(ENT.BDVLRUNITICMSEFETIVO < (ENT.BDICMSSTPRESUMIDO+ENT.BDICMSOPPRESUMIDO),(ENT.BDICMSSTPRESUMIDO+ENT.BDICMSOPPRESUMIDO)-ENT.BDVLRUNITICMSEFETIVO,0) BDVLRRESTITUIR,
            IIF(ENT.BDVLRUNITICMSEFETIVO > (ENT.BDICMSSTPRESUMIDO+ENT.BDICMSOPPRESUMIDO),ENT.BDVLRUNITICMSEFETIVO-(ENT.BDICMSSTPRESUMIDO+ENT.BDICMSOPPRESUMIDO),0) BDVLRRCOMPLEMENTAR,
            'C181','TRUE',ENT.BDREFLANSAI, ENT.BDNUMDOCINI,ENT.BDCHAVESAI, ENT.BDORDEMSAI , ENT.BDORDEMPROSAI , ENT.BDDATAENTRADAENT, ENT.BDVLRUNIT, ENT.BDALIQFCP

     FROM (
             SELECT  ENT.BDCODEMP,ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,
                     ENT.BDQTDITEM,
                     ENT.BDVLRICMSEFET BDVLRUNITICMSEFETIVO,  IIF(COALESCE(PROE.BDVLRICMS,0) > 0,(PROE.BDVLRICMS/(IIF(PROE.BDQTDITEM > 0,PROE.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1))),0) BDICMSOPPRESUMIDO,
                     IIF(COALESCE(PROE.BDVLRST,0) > 0,(PROE.BDVLRST/(IIF(PROE.BDQTDITEM > 0,PROE.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1))),
                         IIF(COALESCE(PROE.BDVLRICMSSTRET,0) > 0,(PROE.BDVLRICMSSTRET/(IIF(PROE.BDQTDITEM > 0,PROE.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1))),0)) BDICMSSTPRESUMIDO,ENT.BDREFLANSAI, ENT.BDNUMDOCINI,
                     ENT.BDCHAVESAI, ENT.BDORDEMSAI , ENT.BDORDEMPROSAI, ENT.BDDATAENTRADAENT, ENT.BDVLRUNIT, ENT.BDALIQFCP
              FROM(
                   SELECT ENT.BDCODEMP,ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,
                          ENT.BDQTDITEM,ENT.BDDATAENTRADAENT, SAI.BDREFLAN BDREFLANSAI,ENT.BDNUMDOCINI,
                          SAI.BDCHAVE BDCHAVESAI, PRO.BDORDEM BDORDEMSAI, PRO.BDORDEMPRO BDORDEMPROSAI,
                          (COALESCE(PRO.BDVLRICMSEFET,0)/(IIF(PRO.BDQTDITEM > 0,PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1))) BDVLRICMSEFET, SAI.BDDATAEMISSAO,
                          ((COALESCE(PRO.BDVLRITEM,0) - COALESCE(PRO.BDVLRABATNT,0) - COALESCE(PRO.BDVLRDESC,0) + COALESCE(PRO.BDVLRFRETE,0) + COALESCE(PRO.BDVLRDESPACESSORIA,0) + COALESCE(PRO.BDVLRSEGURO, 0)) / (IIF(PRO.BDQTDITEM > 0,PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1))) BDVLRUNIT,
                          IIF(COALESCE(PRO.BDALIQFCPRETIDO,0) > 0, PRO.BDALIQFCPRETIDO ,COALESCE(PRO.BDALIQFCPSTRET,0)) BDALIQFCP
                     FROM(
                            SELECT COALESCE(PRO.BDCODEMP,MOV.BDCODEMP) BDCODEMP, MOV.BDREFLAN,MOV.BDCHAVE, I.BDORDEM, PRO.BDORDEMPRO,PRO.BDCODPROD, PRO.BDCODCSTICMS,
                            I.BDCODNAT,IIF(PRO.BDQTDITEM > 0,PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1) BDQTDITEM, MOV.BDNUMDOCINI, MOV.BDDATAENTRADAENT
                            FROM VEF_EMP_TMOVENT MOV
                            LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                            JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
                            LEFT OUTER JOIN VEF_EMP_TMOVPROENTIMPORI ORI ON (ORI.BDCODEMP = MOV.BDCODEMP AND ORI.BDCHAVE = PRO.BDCHAVE AND ORI.BDORDEM = PRO.BDORDEM AND ORI.BDCODPROD = PRO.BDCODPROD)
                            LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MODE ON (MODE.BDMODELO = MOV.BDMODELO)
                            LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
                            LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON)
                            WHERE MOV.BDCODEMP = :PRCODEMP AND
                                  MOV.BDREFLAN = :PRREF AND
                                  NAT.BDDEVOL = 'TRUE'  AND
                                  MOV.BDCODSITNF NOT IN (2,3,4,5)
                          ) ENT
              LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = ENT.BDCODEMP AND C113.BDCHAVE = ENT.BDCHAVE)
              LEFT OUTER JOIN VEF_EMP_TMOVC181_1250 C181 ON (C181.BDCODEMP = ENT.BDCODEMP AND C181.BDCHAVE = ENT.BDCHAVE)
              LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCODPROD = ENT.BDCODPROD)
              LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = PRO.BDCODEMP AND SAI.BDCHAVE = PRO.BDCHAVE)
              LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON)
              WHERE (C113.BDORDEMDOCFREF IS NULL) AND (SAI.BDMODELO = C181.BDMODELO
              AND SAI.BDDATAEMISSAO = C181.BDDTEMISSAO AND SAI.BDNUMDOCINI = C181.BDNUMDOC) AND SAI.BDREFLAN < IIF(:PRCODUF = 19, 202406, 202101)
              AND NOT EXISTS (SELECT BDCODEMP FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP T1250
                   WHERE T1250.BDCODEMP = ENT.BDCODEMP AND T1250.BDSESSAO = :PRSESSAO
                   AND T1250.BDREFERENCIA = ENT.BDREFLAN AND T1250.BDCHAVE = ENT.BDCHAVE
                   AND T1250.BDORDEM = ENT.BDORDEM AND T1250.BDORDEMPROD = ENT.BDORDEMPRO
                   AND T1250.BDREG = 'C181')
                  ) ENT
              LEFT OUTER JOIN VEF_EMP_TMOVPROENT PROE ON (PROE.BDCODEMP = ENT.BDCODEMP AND PROE.BDCODPROD =  ENT.BDCODPROD)
              JOIN VEF_EMP_TMOVENT MOVE ON (MOVE.BDCODEMP = PROE.BDCODEMP AND MOVE.BDCHAVE = PROE.BDCHAVE)
              LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PROE.BDCODPROD AND FAT.BDCODFATCON = PROE.BDCODFATCON)
              WHERE (MOVE.BDDATAENTRADAENT <= ENT.BDDATAEMISSAO)
              AND MOVE.BDCHAVE = (SELECT FIRST 1 E.BDCHAVE
                                  FROM VEF_EMP_TMOVENT E
                                  LEFT OUTER JOIN VEF_EMP_TMOVPROENT PE ON (PE.BDCODEMP = E.BDCODEMP AND PE.BDCHAVE = E.BDCHAVE)
                                  WHERE E.BDCODEMP = MOVE.BDCODEMP AND E.BDREFLAN = MOVE.BDREFLAN AND PE.BDCODPROD = PROE.BDCODPROD
                                  AND E.BDDATAENTRADAENT <= ENT.BDDATAEMISSAO
                                  ORDER BY E.BDDATAENTRADAENT DESC)
            ) ENT;


    /*C181 - C181 COM REDUÇÃO Z*/
     INSERT INTO TMP_VEF_EMP_TICMSSPED_1250_TEMP (BDSESSAO, BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCHAVE, BDORDEM,
                                                 BDORDEMPROD, BDCODPROD, BDCSTICMS, BDCODNAT, BDMOTIVO, BDQUANTIDADE,
                                                 BDVLRUNITICMSEFETIVO ,BDICMSOPPRESUMIDO,BDICMSSTPRESUMIDO,BDVLRRESTITUIR,BDVLRCOMPLEMENTAR,
                                                 BDREG,BDVERIFICLANANTDEV,BDREFLANSAIDADEV2021,BDNUMDOCINI,BDCHAVEDEV,BDORDEMDEV,BDORDEMPRODEV,BDDATALAN, BDVLRUNIT)
     SELECT :PRSESSAO,ENT.BDCODEMP,7, ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,
            IIF(ENT.BDVLRUNITICMSEFETIVO < (ENT.BDICMSSTPRESUMIDO+ENT.BDICMSOPPRESUMIDO),IIF(:PRCODUF = 19,30,19), IIF(:PRCODUF = 19,31,24)) BDMOTIVO,
            ENT.BDQTDITEM, ENT.BDVLRUNITICMSEFETIVO, ENT.BDICMSOPPRESUMIDO, ENT.BDICMSSTPRESUMIDO,
            IIF(ENT.BDVLRUNITICMSEFETIVO < (ENT.BDICMSSTPRESUMIDO+ENT.BDICMSOPPRESUMIDO),(ENT.BDICMSSTPRESUMIDO+ENT.BDICMSOPPRESUMIDO)-ENT.BDVLRUNITICMSEFETIVO,0) BDVLRRESTITUIR,
            IIF(ENT.BDVLRUNITICMSEFETIVO > (ENT.BDICMSSTPRESUMIDO+ENT.BDICMSOPPRESUMIDO),ENT.BDVLRUNITICMSEFETIVO-(ENT.BDICMSSTPRESUMIDO+ENT.BDICMSOPPRESUMIDO),0) BDVLRRCOMPLEMENTAR,
            'C181','TRUE',ENT.BDREFLANSAI, ENT.BDNUMDOCINI,ENT.BDCHAVESAI, ENT.BDORDEMSAI , ENT.BDORDEMPROSAI , ENT.BDDATAENTRADAENT, ENT.BDVLRUNIT

     FROM (
             SELECT  ENT.BDCODEMP,ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,
                     ENT.BDQTDITEM,
                     ENT.BDICMSEFETIVO BDVLRUNITICMSEFETIVO,  IIF(COALESCE(PROE.BDVLRICMS,0) > 0,(PROE.BDVLRICMS/(IIF(PROE.BDQTDITEM > 0,PROE.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1))),0) BDICMSOPPRESUMIDO,
                     IIF(COALESCE(PROE.BDVLRST,0) > 0,(PROE.BDVLRST/(IIF(PROE.BDQTDITEM > 0,PROE.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1))),
                         IIF(COALESCE(PROE.BDVLRICMSSTRET,0) > 0,(PROE.BDVLRICMSSTRET/(IIF(PROE.BDQTDITEM > 0,PROE.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1))),0)) BDICMSSTPRESUMIDO,ENT.BDREFLANSAI, ENT.BDNUMDOCINI,
                     ENT.BDCHAVESAI, ENT.BDORDEMSAI , ENT.BDORDEMPROSAI, ENT.BDDATAENTRADAENT, ENT.BDVLRUNIT
              FROM(
                   SELECT ENT.BDCODEMP,ENT.BDREFLAN,ENT.BDCHAVE, ENT.BDORDEM, ENT.BDORDEMPRO,ENT.BDCODPROD, ENT.BDCODCSTICMS, ENT.BDCODNAT,
                          ENT.BDQTDITEM,ENT.BDDATAENTRADAENT, MOV.BDREFLAN BDREFLANSAI,ENT.BDNUMDOCINI,
                          MOV.BDCHAVE BDCHAVESAI, PRO.BDORDEMDOCECF BDORDEMSAI, PRO.BDORDEMITEM BDORDEMPROSAI,
                          (COALESCE(PRO.BDICMSEFETIVO,0)/IIF(COALESCE(PRO.BDQTDITEM,1) = 0,1,COALESCE(PRO.BDQTDITEM,1))) BDICMSEFETIVO, I.BDDATAEMI BDDATAEMISSAO,
                          (PRO.BDVLRTOTPRO/IIF(COALESCE(PRO.BDQTDITEM,1) = 0,1,COALESCE(PRO.BDQTDITEM,1))) BDVLRUNIT
                     FROM(
                            SELECT COALESCE(PRO.BDCODEMP,MOV.BDCODEMP) BDCODEMP, MOV.BDREFLAN,MOV.BDCHAVE, I.BDORDEM, PRO.BDORDEMPRO,PRO.BDCODPROD, PRO.BDCODCSTICMS,
                            I.BDCODNAT,IIF(PRO.BDQTDITEM > 0,PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1) BDQTDITEM, MOV.BDNUMDOCINI, MOV.BDDATAENTRADAENT
                            FROM VEF_EMP_TMOVENT MOV
                            LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                            JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
                            LEFT OUTER JOIN VEF_EMP_TMOVPROENTIMPORI ORI ON (ORI.BDCODEMP = MOV.BDCODEMP AND ORI.BDCHAVE = PRO.BDCHAVE AND ORI.BDORDEM = PRO.BDORDEM AND ORI.BDCODPROD = PRO.BDCODPROD)
                            LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MODE ON (MODE.BDMODELO = MOV.BDMODELO)
                            LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
                            LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON)
                            WHERE MOV.BDCODEMP = :PRCODEMP AND
                                  MOV.BDREFLAN = :PRREF AND
                                  NAT.BDDEVOL = 'TRUE'  AND
                                  MOV.BDCODSITNF NOT IN (2,3,4,5)
                          ) ENT
             LEFT OUTER JOIN VEF_EMP_TMOVENTDOCFREF C113 ON (C113.BDCODEMP = ENT.BDCODEMP AND C113.BDCHAVE = ENT.BDCHAVE)
             LEFT OUTER JOIN VEF_EMP_TMOVC181_1250 C181 ON (C181.BDCODEMP = ENT.BDCODEMP AND C181.BDCHAVE = ENT.BDCHAVE)
             LEFT OUTER JOIN VEF_EMP_TITEMDOCECF PRO ON (PRO.BDCODEMP = ENT.BDCODEMP AND PRO.BDCODPROD = ENT.BDCODPROD)
             LEFT OUTER JOIN VEF_EMP_TREDZ MOV ON (MOV.BDCODEMP = PRO.BDCODEMP AND MOV.BDCHAVE = PRO.BDCHAVE)
             LEFT OUTER JOIN VEF_EMP_TDOCECF I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE AND I.BDORDEMDOCECF = PRO.BDORDEMDOCECF)
             LEFT OUTER JOIN VEF_BASE_TCADMAQMRC MAQ ON (MAQ.BDCODEMP = MOV.BDCODEMP AND MAQ.BDORDEMMAQ = MOV.BDORDEMMAQ)
             LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MC181 ON (MC181.BDMODELO = C181.BDMODELO)
             LEFT OUTER JOIN VEF_BASE_TTABDOCFIS MC160 ON (MC160.BDCODDOCFIS = I.BDCODDOCFIS)
             WHERE (C113.BDORDEMDOCFREF IS NULL)
             AND (MAQ.BDSERIEMAQ = C181.BDSERIEMAQ AND MC160.BDDOCFIS = MC181.BDMODELOSTR
             AND I.BDDATAEMI = C181.BDDTEMISSAO AND I.BDNUMDOCCOO = C181.BDNUMDOC)
             AND MOV.BDREFLAN < IIF(:PRCODUF = 19, 202406, 202101)
              AND NOT EXISTS (SELECT BDCODEMP FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP T1250
                   WHERE T1250.BDCODEMP = ENT.BDCODEMP AND T1250.BDSESSAO = :PRSESSAO
                   AND T1250.BDREFERENCIA = ENT.BDREFLAN AND T1250.BDCHAVE = ENT.BDCHAVE
                   AND T1250.BDORDEM = ENT.BDORDEM AND T1250.BDORDEMPROD = ENT.BDORDEMPRO
                   AND T1250.BDREG = 'C181')
                  ) ENT
              LEFT OUTER JOIN VEF_EMP_TMOVPROENT PROE ON (PROE.BDCODEMP = ENT.BDCODEMP AND PROE.BDCODPROD =  ENT.BDCODPROD)
              JOIN VEF_EMP_TMOVENT MOVE ON (MOVE.BDCODEMP = PROE.BDCODEMP AND MOVE.BDCHAVE = PROE.BDCHAVE)
              LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PROE.BDCODPROD AND FAT.BDCODFATCON = PROE.BDCODFATCON)
              WHERE (MOVE.BDDATAENTRADAENT <= ENT.BDDATAEMISSAO)
              AND MOVE.BDCHAVE = (SELECT FIRST 1 E.BDCHAVE
                                  FROM VEF_EMP_TMOVENT E
                                  LEFT OUTER JOIN VEF_EMP_TMOVPROENT PE ON (PE.BDCODEMP = E.BDCODEMP AND PE.BDCHAVE = E.BDCHAVE)
                                  WHERE E.BDCODEMP = MOVE.BDCODEMP AND E.BDREFLAN = MOVE.BDREFLAN AND PE.BDCODPROD = PROE.BDCODPROD
                                  AND E.BDDATAENTRADAENT <= ENT.BDDATAEMISSAO
                                  ORDER BY E.BDDATAENTRADAENT DESC)
            ) ENT;


    /*--------------------------------------------------C186---------------------------------------------------------------*/
     /*Vai pegar as notas de saída com devolução, verificar se a nota referenciada no C113 entrou na apuração em algum outro periodo*/
     INSERT INTO TMP_VEF_EMP_TICMSSPED_1250_TEMP (BDSESSAO, BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCHAVE, BDORDEM,
                                                  BDORDEMPROD, BDCODPROD, BDCSTICMS, BDCODNAT, BDMOTIVO, BDQUANTIDADE,
                                                  BDVLRUNIT,BDVLRUNITICMS,BDBCUNITICMS,BDICMSSTPRESUMIDO,
                                                  BDREG,BDVERIFICLANANTDEV,BDREFLANSAIDADEV2021,BDVLRFCPORIGINAL,BDCHAVEDEV,BDORDEMDEV,BDORDEMPRODEV,BDNUMDOCINI,BDDATALAN, BDCODINCO)
     SELECT  :PRSESSAO, SAI.BDCODEMP,7, SAI.BDREFLAN,SAI.BDCHAVE, SAI.BDORDEM, SAI.BDORDEMPRO,SAI.BDCODPROD, SAI.BDCODCSTICMS, SAI.BDCODNAT,
             IIF(SAI.BDVALNTRIBST > 0, IIF(:PRCODUF = 19, 29, 16) /*RJ500/RS413*/, IIF(:PRCODUF = 19, 28, 15) /*RJ400/RS400*/) BDMOTIVO, SAI.BDQTDITEM, TAB.BDVLRUNIT, TAB.BDVLRUNITICMS /*ICMS OP*/, TAB.BDBCUNITICMSST,TAB.BDICMSSTPRESUMIDO,
             'C186', IIF(SAI.BDREFLAN >= 202101 AND SAI.BDREFLANENT < 202101,'TRUE','FALSE'),SAI.BDREFLANENT,SAI.BDVLRFCP,
             SAI.BDCHAVEENT,SAI.BDORDEMENT BDORDEMDEV, SAI.BDORDEMPROENT BDORDEMPRODEV, SAI.BDNUMDOCINI, SAI.BDDATAEMISSAO,
             IIF(TAB.BDCHAVE IS NULL,36,NULL) BDCODINCO
  FROM(
       SELECT SAI.BDCODEMP,SAI.BDREFLAN,SAI.BDCHAVE, SAI.BDORDEM, SAI.BDORDEMPRO,SAI.BDCODPROD, SAI.BDCODCSTICMS, SAI.BDCODNAT,
              SAI.BDQTDITEM, ENT.BDREFLAN BDREFLANENT,SAI.BDVLRFCP, SAI.BDNUMDOCINI, SAI.BDDATAEMISSAO,
              ENT.BDCHAVE BDCHAVEENT, PRO.BDORDEM BDORDEMENT, PRO.BDORDEMPRO BDORDEMPROENT,
              COALESCE(I.BDVALNTRIBST,0) BDVALNTRIBST
             FROM(
                    SELECT COALESCE(PRO.BDCODEMP,MOV.BDCODEMP) BDCODEMP, MOV.BDREFLAN,MOV.BDCHAVE, I.BDORDEM, PRO.BDORDEMPRO,PRO.BDCODPROD, PRO.BDCODCSTICMS,
                    I.BDCODNAT,IIF(PRO.BDQTDITEM > 0,PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1) BDQTDITEM, PRO.BDVLRFCP, MOV.BDNUMDOCINI, MOV.BDDATAEMISSAO
                    FROM VEF_EMP_TMOVSAI MOV
                    LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                    JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
                    LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MODE ON (MODE.BDMODELO = MOV.BDMODELO)
                    LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
                    LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON)
                    WHERE MOV.BDCODEMP = :PRCODEMP AND
                          MOV.BDREFLAN = :PRREF AND
                          NAT.BDDEVOL = 'TRUE' AND
                          MOV.BDCODSITNF NOT IN (2,3,4,5)
                  ) SAI
      LEFT OUTER JOIN VEF_EMP_TMOVSAIDOCFREF C113 ON (C113.BDCODEMP = SAI.BDCODEMP AND C113.BDCHAVE = SAI.BDCHAVE)
      LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCODPROD = SAI.BDCODPROD)
      LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = PRO.BDCODEMP AND I.BDCHAVE = PRO.BDCHAVE AND I.BDORDEM = PRO.BDORDEM)
      LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = PRO.BDCODEMP AND ENT.BDCHAVE = PRO.BDCHAVE)
      WHERE (ENT.BDNUMDOCINI = C113.BDNUMDOC AND COALESCE(ENT.BDCHAVENFE,0) = IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '', 0, C113.BDCHAVENFE)
             AND ENT.BDDATAEMISSAO = C113.BDDTEMISSAO) AND ENT.BDREFLAN >= IIF(:PRCODUF = 19, 202406, 202101)
      ) SAI
   LEFT OUTER JOIN VEF_EMP_TICMSSPED_1250_C180 TAB ON (TAB.BDCODEMP = SAI.BDCODEMP  AND TAB.BDCHAVE = SAI.BDCHAVEENT AND TAB.BDORDEM = SAI.BDORDEMENT AND TAB.BDORDEMPROD = SAI.BDORDEMPROENT);


    /*C186 - QUANDO A NOTA REFERENCIADA FOI ANTES DE 202101*/
     INSERT INTO TMP_VEF_EMP_TICMSSPED_1250_TEMP (BDSESSAO, BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCHAVE, BDORDEM,
                                                  BDORDEMPROD, BDCODPROD, BDCSTICMS, BDCODNAT, BDMOTIVO, BDQUANTIDADE,
                                                  BDVLRUNIT,BDVLRUNITICMS,BDBCUNITICMS,BDICMSSTPRESUMIDO,
                                                  BDREG,BDVERIFICLANANTDEV,BDREFLANSAIDADEV2021,BDVLRFCPORIGINAL,BDCHAVEDEV,BDORDEMDEV,BDORDEMPRODEV,BDNUMDOCINI,BDDATALAN, BDCODINCO)
     SELECT :PRSESSAO, SAI.BDCODEMP,7, SAI.BDREFLAN,SAI.BDCHAVE, SAI.BDORDEM, SAI.BDORDEMPRO,SAI.BDCODPROD, SAI.BDCODCSTICMS, SAI.BDCODNAT,
            IIF(SAI.BDVALNTRIBST > 0, IIF(:PRCODUF = 19, 29, 16) /*RJ500/RS413*/, IIF(:PRCODUF = 19, 28, 15) /*RJ400/RS400*/) BDMOTIVO, SAI.BDQTDITEM,
            IIF((COALESCE(INV.BDVLRICMSOP,0) > 0) AND (COALESCE(INV.BDVLRICMSST,0) > 0) AND (COALESCE(INV.BDVLRBCICMSST,0) > 0),CAST((CAST((COALESCE(INV.BDVLRICMSOP,0)+COALESCE(INV.BDVLRICMSST,0))/COALESCE(INV.BDVLRICMSOP,1) AS NUMERIC(15,10))*COALESCE(INV.BDVLRBCICMSST,1)) AS NUMERIC(15,6)),0) BDVLRUNIT,
            COALESCE(INV.BDVLRICMSOP,0) BDVLRUNITICMS /*ICMS OP*/,COALESCE(INV.BDVLRBCICMSST,1)  BDBCUNITICMSST, COALESCE(INV.BDVLRICMSST,0) BDICMSSTPRESUMIDO,
            'C186', 'TRUE',SAI.BDREFLANENT,SAI.BDVLRFCP, SAI.BDCHAVEENT,SAI.BDORDEMENT BDORDEMDEV, SAI.BDORDEMPROENT BDORDEMPRODEV, SAI.BDNUMDOCINI, SAI.BDDATAEMISSAO,
            IIF((COALESCE(INV.BDVLRICMSOP,0) = 0) OR (COALESCE(INV.BDVLRICMSST,0) = 0) OR (COALESCE(INV.BDVLRBCICMSST,0) = 0),38,NULL) BDCODINCO
     FROM(
          SELECT SAI.BDCODEMP,SAI.BDREFLAN,SAI.BDCHAVE, SAI.BDORDEM, SAI.BDORDEMPRO,SAI.BDCODPROD, SAI.BDCODCSTICMS, SAI.BDCODNAT,
                 SAI.BDQTDITEM, ENT.BDREFLAN BDREFLANENT,SAI.BDVLRFCP, SAI.BDNUMDOCINI, SAI.BDDATAEMISSAO,
                 ENT.BDCHAVE BDCHAVEENT, PRO.BDORDEM BDORDEMENT, PRO.BDORDEMPRO BDORDEMPROENT,
                 COALESCE(I.BDVALNTRIBST,0) BDVALNTRIBST,MIN(INV.BDREFINV) BDREFINV
            FROM(
                 SELECT COALESCE(PRO.BDCODEMP,MOV.BDCODEMP) BDCODEMP, MOV.BDREFLAN,MOV.BDCHAVE, I.BDORDEM, PRO.BDORDEMPRO,PRO.BDCODPROD, PRO.BDCODCSTICMS,
                 I.BDCODNAT,IIF(PRO.BDQTDITEM > 0,PRO.BDQTDITEM,1)*COALESCE(FAT.BDFATORCONVER,1) BDQTDITEM, PRO.BDVLRFCP, MOV.BDNUMDOCINI, MOV.BDDATAEMISSAO
                 FROM VEF_EMP_TMOVSAI MOV
                 LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                 JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM)
                 LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN MODE ON (MODE.BDMODELO = MOV.BDMODELO)
                 LEFT OUTER JOIN VEF_BASE_TNATOP NAT ON (NAT.BDCODNAT = I.BDCODNAT)
                 LEFT OUTER JOIN TFATCONV FAT ON (FAT.BDCODPROD = PRO.BDCODPROD AND FAT.BDCODFATCON = PRO.BDCODFATCON)
                 WHERE MOV.BDCODEMP = :PRCODEMP AND MOV.BDREFLAN = :PRREF AND
                       NAT.BDDEVOL = 'TRUE'  AND MOV.BDCODSITNF NOT IN (2,3,4,5)
                 ) SAI
     LEFT OUTER JOIN VEF_EMP_TMOVSAIDOCFREF C113 ON (C113.BDCODEMP = SAI.BDCODEMP AND C113.BDCHAVE = SAI.BDCHAVE)
     LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = SAI.BDCODEMP AND PRO.BDCODPROD = SAI.BDCODPROD)
     LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = PRO.BDCODEMP AND I.BDCHAVE = PRO.BDCHAVE AND I.BDORDEM = PRO.BDORDEM)
     LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = PRO.BDCODEMP AND ENT.BDCHAVE = PRO.BDCHAVE)
     JOIN VEF_EMP_TMOVINV INV ON (INV.BDCODEMP = SAI.BDCODEMP AND INV.BDCODPROD = SAI.BDCODPROD)
     WHERE (ENT.BDNUMDOCINI = C113.BDNUMDOC AND COALESCE(ENT.BDCHAVENFE,0) = IIF((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(C113.BDCHAVENFE)) = '', 0, C113.BDCHAVENFE)
            AND ENT.BDDATAEMISSAO = C113.BDDTEMISSAO) AND ENT.BDREFLAN < IIF(:PRCODUF = 19, 202406, 202101)
            AND ENT.BDREFLAN <= INV.BDREFINV
     GROUP BY SAI.BDCODEMP,SAI.BDREFLAN,SAI.BDCHAVE, SAI.BDORDEM, SAI.BDORDEMPRO,SAI.BDCODPROD, SAI.BDCODCSTICMS, SAI.BDCODNAT,
              SAI.BDQTDITEM, ENT.BDREFLAN,SAI.BDVLRFCP, SAI.BDNUMDOCINI, SAI.BDDATAEMISSAO,
              ENT.BDCHAVE, PRO.BDORDEM, PRO.BDORDEMPRO,
              BDVALNTRIBST
     ) SAI
     JOIN VEF_EMP_TMOVINV INV ON (INV.BDCODEMP = SAI.BDCODEMP AND INV.BDCODPROD = SAI.BDCODPROD AND INV.BDREFINV = SAI.BDREFINV);

    /*INCONSISTÊNCIA DE QUANDO A NOTA REFERENCIADA NÃO ENTROU NA APURAÇÃO OU QUANDO NÃO TEM AS INFORMAÇÕES NO INVENTÁRIO PARA NOTAS ANTES DE 2021*/
    INSERT INTO VEF_INCON_TAPUSPEDICMS (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDCODPRODVINC)
    SELECT T1250.BDCODEMP,7, T1250.BDREFERENCIA, GETORDEMSEQUENCIAL_STR('INCON.'||T1250.BDCODEMP||'.'||T1250.BDREFERENCIA, :prCODEMP), T1250.BDREG, T1250.BDCODPROD,
    T1250.BDCHAVE, T1250.BDORDEM, T1250.BDORDEMPROD, T1250.BDCODINCO, VINC.BDCODSAIDA
    FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP T1250
    LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = T1250.BDCODEMP AND VINC.BDCODPROD = T1250.BDCODPROD)
    WHERE T1250.BDSESSAO = :PRSESSAO
    AND T1250.BDCODEMP = :PRCODEMP
    AND T1250.BDREFERENCIA = :PRREF
    AND T1250.BDREG IN ('C181','C186')
    AND (T1250.BDCODINCO IS NOT NULL
    AND T1250.BDCODINCO <> 1);

    DELETE FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP T1250
    WHERE T1250.BDSESSAO = :PRSESSAO
    AND T1250.BDCODEMP = :PRCODEMP
    AND T1250.BDREFERENCIA = :PRREF
    AND T1250.BDREG IN ('C181','C186')
    AND T1250.BDCODINCO IS NOT NULL;
END^

CREATE OR ALTER procedure SP_GRAVA_PLANO_1250 (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer,
    PRCODUF integer = 23)
as
declare variable WCODEMP integer;
declare variable WREFERENCIA integer;
declare variable WMOTIVO integer;
declare variable WVLRCREDICMSPROPRIO DM_NUMERIC_15_2;
declare variable WVLRICMSSTRETITUIR DM_NUMERIC_15_2;
BEGIN
     /*GRAVA O C185*/
     INSERT INTO VEF_EMP_TICMSSPED_1250_C185(BDCODEMP,BDCODPERIODO,BDREFERENCIA,BDCHAVE,BDORDEM,BDORDEMPROD,BDCODPROD,BDCSTICMS,BDCODNAT,
                                               BDMOTIVO,BDQUANTIDADE,BDVLRUNITICMSEFETIVO,BDICMSOPPRESUMIDO,BDICMSSTPRESUMIDO,BDVLRRESTITUIR,BDVLRCOMPLEMENTAR,BDNUMDOCINI,BDDATALAN)
     SELECT BDCODEMP,BDCODPERIODO,BDREFERENCIA,BDCHAVE,BDORDEM,BDORDEMPROD,BDCODPROD,BDCSTICMS,BDCODNAT,BDMOTIVO,BDQUANTIDADE,BDVLRUNITICMSEFETIVO,BDICMSOPPRESUMIDO,
            BDICMSSTPRESUMIDO,IIF(BDVLRRESTITUIR < 0,0,BDVLRRESTITUIR) BDVLRRESTITUIR, IIF(BDVLRRESTITUIR < 0,BDVLRRESTITUIR*-1,0) BDVLRCOMPLEMENTAR,BDNUMDOCINI,BDDATALAN
     FROM (
     SELECT BDCODEMP,BDCODPERIODO,BDREFERENCIA,BDCHAVE,BDORDEM,BDORDEMPROD,BDCODPROD,BDCSTICMS,BDCODNAT,IIF(BDMOTIVO IN(6,14,26,27),IIF((BDICMSOPPRESUMIDO+BDICMSSTPRESUMIDO)-BDVLRUNITICMSEFETIVO > 0,IIF(:PRCODUF = 19,26,6),IIF(:PRCODUF = 19,27,14)),BDMOTIVO) BDMOTIVO,BDQUANTIDADE,BDVLRUNITICMSEFETIVO,IIF(SUBSTRING(TAB.BDCODAJUR FROM 1 FOR 3) = IIF(:PRCODUF = 19,'RJ0','RS0'),0,BDICMSOPPRESUMIDO) BDICMSOPPRESUMIDO,
     IIF(SUBSTRING(TAB.BDCODAJUR FROM 1 FOR 3) = IIF(:PRCODUF = 19,'RJ0','RS0'),0,BDICMSSTPRESUMIDO) BDICMSSTPRESUMIDO,
     IIF(SUBSTRING(TAB.BDCODAJUR FROM 1 FOR 3) = IIF(:PRCODUF = 19,'RJ0','RS0'),0,IIF(SUBSTRING(TAB.BDCODAJUR FROM 1 FOR 3) = IIF(:PRCODUF = 19,'RJ2','RS2'),BDICMSSTPRESUMIDO,IIF(TAB.BDCODAJUR IN ('RS100','RS300','RJ100','RJ300'),((BDICMSOPPRESUMIDO+BDICMSSTPRESUMIDO)-BDVLRUNITICMSEFETIVO),0))) BDVLRRESTITUIR,REG.BDNUMDOCINI,
     REG.BDDATALAN
     FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP REG
     LEFT OUTER JOIN VEF_BASE_TTABINFAD57 TAB ON (TAB.BDORDEM57 = REG.BDMOTIVO)
     WHERE REG.BDCODEMP = :PRCODEMP
     AND REG.BDSESSAO = :PRSESSAO
     AND REG.BDREG = 'C185'
     );

     /*GRAVA O C380*/
     INSERT INTO VEF_EMP_TICMSSPED_1250_C380(BDCODEMP,BDCODPERIODO,BDREFERENCIA,BDCHAVE,BDORDEM,BDORDEMPROD,BDCODPROD,BDCSTICMS,BDCODNAT,
                                               BDMOTIVO,BDQUANTIDADE,BDVLRUNITICMSEFETIVO,BDICMSOPPRESUMIDO,BDICMSSTPRESUMIDO,BDVLRRESTITUIR,BDVLRCOMPLEMENTAR,BDNUMDOCINI,BDDATALAN)
     SELECT BDCODEMP,BDCODPERIODO,BDREFERENCIA,BDCHAVE,BDORDEM,BDORDEMPROD,BDCODPROD,BDCSTICMS,BDCODNAT,BDMOTIVO,BDQUANTIDADE,BDVLRUNITICMSEFETIVO,BDICMSOPPRESUMIDO,
            BDICMSSTPRESUMIDO,IIF(BDVLRRESTITUIR < 0,0,BDVLRRESTITUIR) BDVLRRESTITUIR, IIF(BDVLRRESTITUIR < 0,BDVLRRESTITUIR*-1,0) BDVLRCOMPLEMENTAR,BDNUMDOCINI,BDDATALAN
     FROM (
     SELECT BDCODEMP,BDCODPERIODO,BDREFERENCIA,BDCHAVE,BDORDEM,BDORDEMPROD,BDCODPROD,BDCSTICMS,BDCODNAT, IIF(BDMOTIVO IN(6,14,26,27),IIF((BDICMSOPPRESUMIDO+BDICMSSTPRESUMIDO)-BDVLRUNITICMSEFETIVO > 0,IIF(:PRCODUF = 19,26,6),IIF(:PRCODUF = 19,27,14)),BDMOTIVO) BDMOTIVO,BDQUANTIDADE,BDVLRUNITICMSEFETIVO,
     IIF(SUBSTRING(TAB.BDCODAJUR FROM 1 FOR 3) = IIF(:PRCODUF = 19,'RJ0','RS0'),0,BDICMSOPPRESUMIDO) BDICMSOPPRESUMIDO,IIF(SUBSTRING(TAB.BDCODAJUR FROM 1 FOR 3) = IIF(:PRCODUF = 19,'RJ0','RS0'),0,BDICMSSTPRESUMIDO) BDICMSSTPRESUMIDO,
     IIF(SUBSTRING(TAB.BDCODAJUR FROM 1 FOR 3) = IIF(:PRCODUF = 19,'RJ0','RS0'),0,IIF(SUBSTRING(TAB.BDCODAJUR FROM 1 FOR 3) = IIF(:PRCODUF = 19,'RJ2','RS2'),BDICMSSTPRESUMIDO,IIF(TAB.BDCODAJUR IN ('RS100','RS300','RJ100','RJ300'),((BDICMSOPPRESUMIDO+BDICMSSTPRESUMIDO)-BDVLRUNITICMSEFETIVO),0))) BDVLRRESTITUIR,
     REG.BDNUMDOCINI, REG.BDDATALAN
     FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP REG
     LEFT OUTER JOIN VEF_BASE_TTABINFAD57 TAB ON (TAB.BDORDEM57 = REG.BDMOTIVO)
     WHERE REG.BDCODEMP = :PRCODEMP
     AND REG.BDSESSAO = :PRSESSAO
     AND REG.BDREG = 'C380'
     );

     /*GRAVA O C480*/
     INSERT INTO VEF_EMP_TICMSSPED_1250_C480(BDCODEMP,BDCODPERIODO,BDREFERENCIA,BDCHAVE,BDORDEM,BDORDEMPROD,BDCODPROD,BDCSTICMS,BDCODNAT,
                                               BDMOTIVO,BDQUANTIDADE,BDVLRUNITICMSEFETIVO,BDICMSOPPRESUMIDO,BDICMSSTPRESUMIDO, BDVLRRESTITUIR,BDVLRCOMPLEMENTAR,BDNUMDOCINI,BDDATALAN)
     SELECT BDCODEMP,BDCODPERIODO,BDREFERENCIA,BDCHAVE,BDORDEM,BDORDEMPROD,BDCODPROD,BDCSTICMS,BDCODNAT,BDMOTIVO,BDQUANTIDADE,BDVLRUNITICMSEFETIVO,BDICMSOPPRESUMIDO,
            BDICMSSTPRESUMIDO,IIF(BDVLRRESTITUIR < 0,0,BDVLRRESTITUIR) BDVLRRESTITUIR, IIF(BDVLRRESTITUIR < 0,BDVLRRESTITUIR*-1,0) BDVLRCOMPLEMENTAR,BDNUMDOCINI,BDDATALAN
     FROM (
     SELECT BDCODEMP,BDCODPERIODO,BDREFERENCIA,BDCHAVE,BDORDEM,BDORDEMPROD,BDCODPROD,BDCSTICMS,BDCODNAT,IIF(BDMOTIVO IN(6,14,26,27),IIF((BDICMSOPPRESUMIDO+BDICMSSTPRESUMIDO)-BDVLRUNITICMSEFETIVO > 0,IIF(:PRCODUF = 19,26,6),IIF(:PRCODUF = 19,27,14)),BDMOTIVO) BDMOTIVO,BDQUANTIDADE,BDVLRUNITICMSEFETIVO,
     IIF(SUBSTRING(TAB.BDCODAJUR FROM 1 FOR 3) = IIF(:PRCODUF = 19,'RJ0','RS0'),0,BDICMSOPPRESUMIDO) BDICMSOPPRESUMIDO,IIF(SUBSTRING(TAB.BDCODAJUR FROM 1 FOR 3) = IIF(:PRCODUF = 19,'RJ0','RS0'),0,BDICMSSTPRESUMIDO) BDICMSSTPRESUMIDO,
     IIF(SUBSTRING(TAB.BDCODAJUR FROM 1 FOR 3) = IIF(:PRCODUF = 19,'RJ0','RS0'),0,IIF(SUBSTRING(TAB.BDCODAJUR FROM 1 FOR 3) = IIF(:PRCODUF = 19,'RJ2','RS2'),BDICMSSTPRESUMIDO,((BDICMSOPPRESUMIDO+BDICMSSTPRESUMIDO)-BDVLRUNITICMSEFETIVO))) BDVLRRESTITUIR,
     REG.BDNUMDOCINI, REG.BDDATALAN
     FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP REG
     LEFT OUTER JOIN VEF_BASE_TTABINFAD57 TAB ON (TAB.BDORDEM57 = REG.BDMOTIVO)
     WHERE REG.BDCODEMP = :PRCODEMP
     AND REG.BDSESSAO = :PRSESSAO
     AND REG.BDREG = 'C480'
     );

     /*GRAVA O C180*/
     INSERT INTO VEF_EMP_TICMSSPED_1250_C180(BDCODEMP,BDCODPERIODO,BDREFERENCIA,BDCHAVE,BDORDEM,BDORDEMPROD,BDCODPROD,BDCSTICMS,BDCODNAT,
                                               BDQUANTIDADE,BDVLRUNIT,BDVLRUNITICMS,BDBCUNITICMSST,BDICMSSTPRESUMIDO,BDNUMDOCINI,BDDATALAN)
     SELECT BDCODEMP,BDCODPERIODO,BDREFERENCIA,BDCHAVE,BDORDEM,BDORDEMPROD,BDCODPROD,BDCSTICMS,BDCODNAT,BDQUANTIDADE,BDVLRUNIT,
     BDVLRUNITICMS,BDBCUNITICMS,BDICMSSTPRESUMIDO,BDNUMDOCINI,BDDATALAN
     FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP REG
     WHERE REG.BDCODEMP = :PRCODEMP
     AND REG.BDSESSAO = :PRSESSAO
     AND REG.BDREG = 'C180';

     /*REGISTRO DO C181 - PEGA OS VALORES DA APURAÇÃO, VERIFICA AS ENTRADAS ANTERIORES E INSERE NO C181*/
     /*REGISTRO DO C186 - PEGA OS VALORES DA APURAÇÃO, VERIFICA O INVENTÁRIO E INSERE NO C186*/
     EXECUTE PROCEDURE SP_DEVOLUCOES_PLANO_1250(:PRSESSAO,:PRCODEMP,:PRREF,:PRCODUF);

     /*GRAVA O C181*/
     INSERT INTO VEF_EMP_TICMSSPED_1250_C181(BDCODEMP,BDCODPERIODO,BDREFERENCIA,BDCHAVE,BDORDEM,BDORDEMPROD,BDCODPROD,BDMOTIVO,BDCSTICMS,BDCODNAT,
                                              BDQUANTIDADE,BDVLRUNITICMSEFETIVO,BDICMSOPPRESUMIDO,BDICMSSTPRESUMIDO,BDVLRRESTITUIR,BDVLRCOMPLEMENTAR,BDNUMDOCINI,BDDATALAN)
     SELECT BDCODEMP,BDCODPERIODO,BDREFERENCIA,BDCHAVE,BDORDEM,BDORDEMPROD,BDCODPROD,BDMOTIVO,BDCSTICMS,BDCODNAT,BDQUANTIDADE,
     BDVLRUNITICMSEFETIVO,BDICMSOPPRESUMIDO,BDICMSSTPRESUMIDO,BDVLRRESTITUIR,BDVLRCOMPLEMENTAR,BDNUMDOCINI,BDDATALAN
     FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP REG                    /*O valor a restituir vai no complementar e o complementar no a restituir*/
     WHERE REG.BDCODEMP = :PRCODEMP
     AND REG.BDSESSAO = :PRSESSAO
     AND REG.BDREG = 'C181';

     /*GRAVA O C186*/
     INSERT INTO VEF_EMP_TICMSSPED_1250_C186(BDCODEMP,BDCODPERIODO,BDREFERENCIA,BDCHAVE,BDORDEM,BDORDEMPROD,BDCODPROD,BDMOTIVO,BDCSTICMS,BDCODNAT,
                                              BDQUANTIDADE,BDVLRUNITARIO,BDVLRUNITICMS,BDBCICMSSTUNIT,BDICMSSTPRESUMIDO,BDNUMDOCINI,BDDATALAN)
     SELECT BDCODEMP,BDCODPERIODO,BDREFERENCIA,BDCHAVE,BDORDEM,BDORDEMPRODEV,BDCODPROD,BDMOTIVO,BDCSTICMS,BDCODNAT,BDQUANTIDADE,
     BDVLRUNIT,BDVLRUNITICMS,BDBCUNITICMS,BDICMSSTPRESUMIDO,BDNUMDOCINI,BDDATALAN
     FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP REG
     WHERE REG.BDCODEMP = :PRCODEMP
     AND REG.BDSESSAO = :PRSESSAO
     AND REG.BDREG = 'C186';
         
     /*GRAVA OS PRODUTOS*/
     INSERT INTO VEF_EMP_TICMSSPED1250_PROD (BDCODEMP, BDCODPERIODO, BDREFERENCIA,BDCODPROD,BDCODPRODEMP,BDDESCPROD)
     SELECT TSAI.BDCODEMP, 7, :PRREF, TSAI.BDCODPROD,VINC.BDCODSAIDA, VINC.BDDESCPROD
     FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP TSAI
     LEFT OUTER JOIN TCADPRO PRO ON (PRO.BDCODPROD = TSAI.BDCODPROD)
     LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = TSAI.BDCODEMP AND VINC.BDCODPROD = PRO.BDCODPROD)
     WHERE TSAI.BDCODEMP = :PRCODEMP
     AND TSAI.BDSESSAO = :PRSESSAO
     GROUP BY TSAI.BDCODEMP,TSAI.BDCODPROD,VINC.BDCODSAIDA, VINC.BDDESCPROD;

     /*GRAVA A MEMÓRIA DO CÁLCULO*/
     INSERT INTO VEF_EMP_TMEMCALC_1250 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCODPROD, BDREG, BDCHAVE, BDORDEMCALC, BDICMSOPPRESUMIDO,
                                        BDBCICMSOPPRESUMIDO, BDICMSSTPRESUMIDO, BDBCICMSSTPRESUMIDO, BDDATALAN, BDQUANTIDADE, BDCHAVELANCALC, BDREFLAN,BDREGVALOR, BDORDEM,BDORDEMPROD,BDDATALANNOTA)
     SELECT BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCODPROD, BDREG, BDCHAVE, BDORDEMCALC, BDICMSOPPRESUMIDO, BDBCICMSOPPRESUMIDO,
                                       BDICMSSTPRESUMIDO, BDBCICMSSTPRESUMIDO, BDDATALAN, BDQUANTIDADE, BDCHAVELANCALC, BDREFLAN,BDREGVALOR, BDORDEM,BDORDEMPROD,BDDATALANNOTA
     FROM TMP_VEF_EMP_TMEMCALC_1250_TEMP REG
     WHERE REG.BDCODEMP = :PRCODEMP
     AND REG.BDSESSAO = :PRSESSAO
     AND REG.BDREG <> 'DEVT';
END^

CREATE OR ALTER procedure SP_APLICA_PLANO_1250 (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer)
as
declare variable WBDCHAVE integer;
declare variable WPLANO integer;
declare variable WNAOEFETUARRECAL DM_BOOLEAN;
declare variable WGERARAJUE220E111 DM_BOOLEAN;
declare variable WLANCAE220 DM_BOOLEAN;
declare variable WBDMODELO varchar(2);
declare variable WBDCONSUFINAL integer;
declare variable WBDVARIASCFOPS integer;
declare variable WVARIASCSTS integer;
declare variable WTIPOEMP integer;
declare variable WBDTABELA57 integer;
declare variable WSQL varchar(5000);
declare variable WCODEMP integer;
declare variable WREFERENCIA integer;
declare variable WMOTIVO integer;
declare variable WNEGATIVO varchar(5);
declare variable WORDEM integer;
declare variable WVALOR numeric(15,2);
declare variable WVALORE110 numeric(15,6);
declare variable WVLRCREDICMSPROPRIO DM_NUMERIC_15_2;
declare variable WVLRICMSSTRETITUIR DM_NUMERIC_15_2;
declare variable WVLRUNITFCPSTRESTITUIR DM_NUMERIC_15_2;
declare variable WVLRUNITICMSSTCOMPLEMENTAR DM_NUMERIC_15_2;
declare variable WVLRUNITFCPSTCOMPLEMENTAR DM_NUMERIC_15_2;
declare variable WCODUF integer;
declare variable WCAMPOAPU varchar(8);
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREF);

  /* Pega o código da UF, pois agora faz do RS e RJ */
  :WCODUF = null;
  select first 1 CID.BDCODUF
  from TEMPRESAS_REF X
  inner join TCIDADE CID on (X.BDCODCID = CID.BDCODCID)
  where X.BDCODEMP = :PRCODEMP and
        X.BDREFEMP = (select first 1 Y.BDREFEMP
                      from TEMPRESAS_REF Y
                      where Y.BDCODEMP = X.BDCODEMP and
                            Y.BDREFEMP <= :PRREF
                      order by Y.BDREFEMP desc)
  into WCODUF;

  ---PEGA O PLANO CONFIGURADO NA EMPRESA
  SELECT FIRST 1 CI.BDPLANCONF1200, COALESCE(CI.BDNAOEFETUARECALC,'FALSE') BDNAOEFETUARECALC, COALESCE(CI.BDGERARAJUE220E111,'FALSE') BDGERARAJUE220E111 ,IIF(COALESCE(CI.BDE220,'FALSE') = 'TRUE','TRUE','FALSE') BDLANCAE220
  FROM VEF_INT_TSPEDICMS C
  LEFT OUTER JOIN VEF_INT_TSPEDICMSCONF1250 CI ON (C.BDCODEMP = CI.BDCODEMP AND C.BDCODIGO = CI.BDCODIGO)
  WHERE C.BDCODEMP = :PRCODEMP  AND C.BDREFERENCIA <= :PRREF ORDER BY C.BDCODEMP,C.BDREFERENCIA DESC
  INTO WPLANO,WNAOEFETUARRECAL,WGERARAJUE220E111,WLANCAE220;

    /*Quando não efetuar recalculo estiver como verdadeiro, vai ser apenas  calculado o 1250 e 1255 a partir do lançamentos já existentes/importados*/
  if (WNAOEFETUARRECAL = 'FALSE') then
     BEGIN
      FOR SELECT A.BDCHAVE, COALESCE(D.BDMODELOSTR,'00') BDMODELOSTR, COALESCE(A.BDCONSUFINAL,-1) BDCONSUFINAL, A.BDTABELA57,
          (SELECT FIRST 1 V.BDCODNAT FROM VEF_BASE_TVINCCODPLANO1250 V WHERE A.BDCODPLANCONF1200 = V.BDCODPLANCONF1200 AND A.BDCHAVE = V.BDCHAVE ) BDVARIASCFOPS,
          (SELECT FIRST 1 V.BDCODCSTICMS FROM VEF_BASE_TVINCCODPLANO1250 V WHERE A.BDCODPLANCONF1200 = V.BDCODPLANCONF1200 AND A.BDCHAVE = V.BDCHAVE ) BDVARIASCSTS,
          P.BDTIPOEMP
          FROM VEF_BASE_TPLANOACOESCONF1250 A
          LEFT OUTER JOIN VEF_BASE_TPLACONF1250 P ON (A.BDCODPLANCONF1200 = P.BDCODPLANCONF1200)
          LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN D ON (A.BDMODELO = D.BDMODELO)
          WHERE A.BDCODPLANCONF1200 = :WPLANO
          ORDER BY A.BDCHAVE
          INTO WBDCHAVE,WBDMODELO, WBDCONSUFINAL,WBDTABELA57,WBDVARIASCFOPS,WVARIASCSTS,WTIPOEMP
      DO
        BEGIN
          /*Produtos das saídas - C180*/
          wSQL = ' INSERT INTO TMP_VEF_EMP_TMOVSAISTRS_TEMP(BDCODEMP, BDSESSAO, BDCHAVE,BDORDEM,BDORDEMPRO, BDDATAEMISSAO, BDREFERENCIA, BDCODPROD, BDMOTIVO, BDREG) ';
          wSQL = wSQL ||' SELECT PRO.BDCODEMP,'|| :PRSESSAO ||',MOV.BDCHAVE, I.BDORDEM, PRO.BDORDEMPRO,  MOV.BDDATAEMISSAO, MOV.BDREFLAN, PRO.BDCODPROD, '||:WBDTABELA57||', ''SAI''';
          wSQL = wSQL ||' FROM VEF_EMP_TMOVSAI MOV ';
          wSQL = wSQL ||' LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE) ';
          wSQL = wSQL ||' LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEM = I.BDORDEM) ';
          wSQL = wSQL ||' LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN D ON (MOV.BDMODELO = D.BDMODELO) ';
          wSQL = wSQL ||' WHERE MOV.BDCODEMP = '||:PRCODEMP ;
          wSQL = wSQL ||' AND MOV.BDREFLAN = '|| :PRREF ;
          wSQL = wSQL ||' AND MOV.BDCODSITNF NOT IN (2,3,4,5) ';

          if (WBDCONSUFINAL = 1) then
             wSQL = wSQL ||' AND COALESCE(MOV.BDCONSUFINAL,0) = '|| :WBDCONSUFINAL;
          ELSE if (WBDCONSUFINAL = 0) then
             wSQL = wSQL ||' AND COALESCE(MOV.BDCONSUFINAL,0) IN (-1,0) ';

          if (:WBDMODELO <> '00') then
             wSQL = wSQL ||' AND D.BDMODELOSTR = '|| '''' || :WBDMODELO ||'''';
          if ((wbdVariasCFOPs is not null) or (wbdVariasCFOPs > 0)) then
              wSQL = wSQL ||' AND EXISTS (SELECT FIRST 1 F.BDCODNAT FROM VEF_BASE_TVINCCODPLANO1250 F WHERE F.BDCODPLANCONF1200 = '||WPLANO||' AND F.BDCHAVE = '||WBDCHAVE||' AND F.BDCODNAT = I.BDCODNAT) ';
          if ((WVARIASCSTS is not null) or (WVARIASCSTS > 0)) then
              wSQL = wSQL ||' AND EXISTS (SELECT FIRST 1 F.BDCODCSTICMS FROM VEF_BASE_TVINCCODPLANO1250 F WHERE F.BDCODPLANCONF1200 = '||WPLANO||' AND F.BDCHAVE = '||WBDCHAVE||' AND F.BDCODCSTICMS = PRO.BDCODCSTICMS) ';
         /*Caso a mesma nota/produto entre no plano por diferentes chaves - O importante aqui é pegar o produto da saída, pra depois achar as entrada*/
          wSQL = wSQL ||' AND NOT EXISTS (SELECT FIRST 1 BDCODPROD FROM TMP_VEF_EMP_TMOVSAISTRS_TEMP T WHERE T.BDCODEMP = MOV.BDCODEMP AND T.BDSESSAO ='||:PRSESSAO||'AND T.BDCODPROD = PRO.BDCODPROD AND T.BDREG = ''SAI'' AND T.BDCHAVE = MOV.BDCHAVE AND T.BDORDEM = I.BDORDEM AND T.BDORDEMPRO = PRO.BDORDEMPRO) ';
         -- wSQL = wSQL ||' GROUP BY PRO.BDCODEMP, MOV.BDDATAEMISSAO, MOV.BDREFLAN, PRO.BDCODPROD; ';
    
          EXECUTE STATEMENT(wSQL);
    
          /*Produtos da REDZ - C480*/
          wSQL = ' INSERT INTO TMP_VEF_EMP_TMOVSAISTRS_TEMP(BDCODEMP, BDSESSAO, BDCHAVE,BDORDEM,BDORDEMPRO, BDDATAEMISSAO, BDREFERENCIA, BDCODPROD, BDMOTIVO, BDREG) ';
          wSQL = wSQL ||' SELECT PRO.BDCODEMP,'|| :PRSESSAO ||',MOV.BDCHAVE, I.BDORDEMDOCECF, PRO.BDORDEMITEM, I.BDDATAEMI, MOV.BDREFLAN, PRO.BDCODPROD, '||:WBDTABELA57||', ''RED''';
          wSQL = wSQL ||' FROM VEF_EMP_TREDZ MOV ';
          wSQL = wSQL ||' LEFT OUTER JOIN VEF_EMP_TDOCECF I ON (I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE) ';
          wSQL = wSQL ||' LEFT OUTER JOIN VEF_EMP_TITEMDOCECF PRO ON (PRO.BDCODEMP = I.BDCODEMP AND PRO.BDCHAVE = I.BDCHAVE AND PRO.BDORDEMDOCECF = I.BDORDEMDOCECF) ';
          WSQL = WSQL ||' LEFT OUTER JOIN VEF_BASE_TTABDOCFIS MODE ON (MODE.BDCODDOCFIS = I.BDCODDOCFIS) ';
          wSQL = wSQL ||' WHERE MOV.BDCODEMP = '||:PRCODEMP ;
          wSQL = wSQL ||' AND MOV.BDREFLAN = '|| :PRREF ;
          wSQL = wSQL ||' AND I.BDCODSITNF NOT IN (2,3,4,5) ';
          if (:WBDMODELO <> '00') then
             wSQL = wSQL ||' AND MODE.BDDOCFIS = '|| '''' || :WBDMODELO ||'''';
          /*Redução Z vai assumir que deve ser consumidor final*/
          IF ((WBDCONSUFINAL = 1) OR (WBDCONSUFINAL = -1))  THEN
             WSQL = WSQL ||' AND 1 = 1 ';
          ELSE
            WSQL = WSQL ||' AND 1 = 0 ';

          if ((wbdVariasCFOPs is not null) or (wbdVariasCFOPs > 0)) then
              wSQL = wSQL ||' AND EXISTS (SELECT FIRST 1 F.BDCODNAT FROM VEF_BASE_TVINCCODPLANO1250 F WHERE F.BDCODPLANCONF1200 = '||WPLANO||' AND F.BDCHAVE = '||WBDCHAVE||' AND F.BDCODNAT = PRO.BDCODNAT) ';
          if ((WVARIASCSTS is not null) or (WVARIASCSTS > 0)) then
              wSQL = wSQL ||' AND EXISTS (SELECT FIRST 1 F.BDCODCSTICMS FROM VEF_BASE_TVINCCODPLANO1250 F WHERE F.BDCODPLANCONF1200 = '||WPLANO||' AND F.BDCHAVE = '||WBDCHAVE||' AND F.BDCODCSTICMS = PRO.BDCODCSTICMS) ';
          /*Caso a mesma nota/produto entre no plano por diferentes chaves - O importante aqui é pegar o produto da saída, pra depois achar as entrada*/
          wSQL = wSQL ||' AND NOT EXISTS (SELECT FIRST 1 BDCODPROD FROM TMP_VEF_EMP_TMOVSAISTRS_TEMP T WHERE T.BDCODEMP = MOV.BDCODEMP AND T.BDSESSAO ='||:PRSESSAO||' AND T.BDCODPROD = PRO.BDCODPROD AND T.BDREG = ''RED'' AND T.BDCHAVE = MOV.BDCHAVE AND T.BDORDEM = I.BDORDEMDOCECF AND T.BDORDEMPRO = PRO.BDORDEMITEM) ';
          --wSQL = wSQL ||' GROUP BY PRO.BDCODEMP, MOV.BDDATAEMISSAO, MOV.BDREFLAN, PRO.BDCODPROD; ';
    
          EXECUTE STATEMENT(wSQL);
    
        END

        /*INCONSISTÊNCIA DE QUANDO VAI TER QUE EXCLUIR - O item da saída não existe nas entradas ou no inventário.*/
        INSERT INTO VEF_INCON_TAPUSPEDICMS (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDCODPRODVINC)
        SELECT TSAI.BDCODEMP,7, TSAI.BDREFERENCIA, GETORDEMSEQUENCIAL_STR('INCON.'||TSAI.BDCODEMP||'.'||TSAI.BDREFERENCIA, :PRCODEMP), TSAI.BDREG, TSAI.BDCODPROD,
        TSAI.BDCHAVE, TSAI.BDORDEM, TSAI.BDORDEMPRO, 35, VINC.BDCODSAIDA
        FROM TMP_VEF_EMP_TMOVSAISTRS_TEMP TSAI
        LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = TSAI.BDCODEMP AND VINC.BDCODPROD = TSAI.BDCODPROD)
        WHERE TSAI.BDCODEMP = :PRCODEMP AND TSAI.BDREFERENCIA = :PRREF
        AND TSAI.BDSESSAO = :PRSESSAO
        AND NOT EXISTS (
                         SELECT FIRST 1 ENT.BDCODPROD--COALESCE(PROE.BDCODPROD, INV.BDCODPROD) BDCODPROD
                         FROM (     /*LANÇAMENTO DE ENTRADA*/
                               SELECT FIRST 1 ENT.BDCODEMP, ENT.BDCHAVE, PROE.BDCODPROD
                               FROM (
                                     SELECT *
                                     FROM VEF_EMP_TMOVENT ENT
                                     WHERE ENT.BDCODEMP = TSAI.BDCODEMP
                                     AND (ENT.BDDATAENTRADAENT <= TSAI.BDDATAEMISSAO AND ENT.BDDATAENTRADAENT >= '01/01/'||SUBSTRING(TSAI.BDDATAEMISSAO FROM 1 FOR 4))
                                    ) ENT
                         JOIN VEF_EMP_TMOVPROENT PROE ON (PROE.BDCODEMP = ENT.BDCODEMP AND PROE.BDCHAVE = ENT.BDCHAVE)
                         WHERE PROE.BDCODPROD = TSAI.BDCODPROD
                         AND  ((PROE.BDVLRICMSSTRET > 0) OR (PROE.BDVLRST > 0))
                         UNION ALL /*LANÇAMENTO DE INVENTÁRIO*/
                         SELECT FIRST 1 INV.BDCODEMP, 0 BDCHAVE, INV.BDCODPROD
                         FROM VEF_EMP_TMOVINV INV
                         WHERE INV.BDCODEMP = TSAI.BDCODEMP AND INV.BDCODPROD = TSAI.BDCODPROD
                         /* Alt.: #228032 - Estava olhando o inventario apenas do ano anterior, mas basta ser anterior ou igual...
                         AND (INV.BDREFINV BETWEEN CAST(CAST(SUBSTRING(TSAI.BDDATAEMISSAO FROM 1 FOR 4) AS INTEGER )-1 AS VARCHAR(04))||'01'
                         AND CAST(CAST(SUBSTRING(TSAI.BDDATAEMISSAO FROM 1 FOR 4) AS INTEGER )-1 AS VARCHAR(04))||'12' AND INV.BDCHAVE IS NOT NULL) */
                         AND (INV.BDREFINV < EXTRACT(YEAR FROM TSAI.BDDATAEMISSAO)||LPAD(EXTRACT(MONTH FROM TSAI.BDDATAEMISSAO),2,'0') AND INV.BDCHAVE IS NOT NULL)
                         AND (INV.BDVLRICMSST > 0)
                         ) ENT
                         GROUP BY BDCODPROD
                       );

        /*INCONSISTÊNCIA DE QUANDO VAI TER QUE EXCLUIR - O item da saída não existe nas entradas ou no inventário.*/
       /* INSERT INTO VEF_INCON_TAPUSPEDICMS (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCODIGO, BDREG, BDCODPROD, BDCHAVE, BDORDEM, BDORDEMPRO, BDCODINC, BDCODPRODVINC)
        SELECT TSAI.BDCODEMP,7, TSAI.BDREFERENCIA, GETORDEMSEQUENCIAL_STR('INCON.'||TSAI.BDCODEMP||'.'||TSAI.BDREFERENCIA, :PRCODEMP), TSAI.BDREG, TSAI.BDCODPROD,
        TSAI.BDCHAVE, TSAI.BDORDEM, TSAI.BDORDEMPRO, 35, VINC.BDCODSAIDA
        FROM TMP_VEF_EMP_TMOVSAISTRS_TEMP TSAI
        LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = TSAI.BDCODEMP AND VINC.BDCODPROD = TSAI.BDCODPROD)
        WHERE NOT EXISTS (
                         SELECT FIRST 1 ENT.BDCODPROD--COALESCE(PROE.BDCODPROD, INV.BDCODPROD) BDCODPROD
                         FROM (   */  /*LANÇAMENTO DE ENTRADA*/
                          /*    SELECT FIRST 1 ENT.BDCODEMP, ENT.BDCHAVE, SAI.BDCODPROD
                    FROM (
                          SELECT *
                          FROM TMP_VEF_EMP_TMOVSAISTRS_TEMP SAI
                          WHERE SAI.BDCODEMP = :PRCODEMP AND
                                SAI.BDSESSAO = :PRSESSAO AND
                                SAI.BDREG   IN ('SAI','RED')
                                          AND SAI.BDCODPROD = TSAI.BDCODPROD
                          ) SAI
                              JOIN VEF_EMP_TMOVPROENT PROE ON (PROE.BDCODEMP = SAI.BDCODEMP  AND PROE.BDCODPROD = SAI.BDCODPROD)
                              LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP =  PROE.BDCODEMP AND PROE.BDCHAVE = ENT.BDCHAVE)
                              WHERE (ENT.BDDATAENTRADAENT <= SAI.BDDATAEMISSAO AND ENT.BDDATAENTRADAENT >= '01/01/'||SUBSTRING(SAI.BDDATAEMISSAO FROM 1 FOR 4))
                              AND ((PROE.BDVLRICMSSTRET > 0) OR (PROE.BDVLRST > 0))
                              UNION ALL */ /*LANÇAMENTO DE INVENTÁRIO*/
                           /*   SELECT FIRST 1 INV.BDCODEMP, 0 BDCHAVE, INV.BDCODPROD
                    FROM (
                          SELECT *
                          FROM TMP_VEF_EMP_TMOVSAISTRS_TEMP SAI
                          WHERE SAI.BDCODEMP = :PRCODEMP AND
                                SAI.BDSESSAO = :PRSESSAO AND
                                SAI.BDREG  IN ('SAI','RED')
                                          AND SAI.BDCODPROD = TSAI.BDCODPROD
                          ) SAI
                              JOIN VEF_EMP_TMOVINV INV ON (INV.BDCODEMP = SAI.BDCODEMP AND INV.BDCODPROD = SAI.BDCODPROD)
                              WHERE (INV.BDREFINV BETWEEN CAST(CAST(SUBSTRING(SAI.BDDATAEMISSAO FROM 1 FOR 4) AS INTEGER )-1 AS VARCHAR(04))||'01'
                              AND CAST(CAST(SUBSTRING(SAI.BDDATAEMISSAO FROM 1 FOR 4) AS INTEGER )-1 AS VARCHAR(04))||'12' AND INV.BDCHAVE IS NOT NULL)
                              AND (INV.BDVLRICMSST > 0)
                              ) ENT
                    GROUP BY BDCODPROD
                       );   */



        DELETE FROM TMP_VEF_EMP_TMOVSAISTRS_TEMP TSAI
        WHERE TSAI.BDCODEMP = :PRCODEMP AND TSAI.BDREFERENCIA = :PRREF AND TSAI.BDSESSAO = :PRSESSAO
        AND NOT EXISTS (
                         SELECT FIRST 1 ENT.BDCODPROD--COALESCE(PROE.BDCODPROD, INV.BDCODPROD) BDCODPROD
                         FROM (     /*LANÇAMENTO DE ENTRADA*/
                               SELECT FIRST 1 ENT.BDCODEMP, ENT.BDCHAVE, PROE.BDCODPROD
                               FROM (
                                     SELECT *
                                     FROM VEF_EMP_TMOVENT ENT
                                     WHERE ENT.BDCODEMP = TSAI.BDCODEMP
                                     AND (ENT.BDDATAENTRADAENT <= TSAI.BDDATAEMISSAO AND ENT.BDDATAENTRADAENT >= '01/01/'||SUBSTRING(TSAI.BDDATAEMISSAO FROM 1 FOR 4))
                                    ) ENT
                         JOIN VEF_EMP_TMOVPROENT PROE ON (PROE.BDCODEMP = ENT.BDCODEMP AND PROE.BDCHAVE = ENT.BDCHAVE)
                         WHERE PROE.BDCODPROD = TSAI.BDCODPROD
                         AND  ((PROE.BDVLRICMSSTRET > 0) OR (PROE.BDVLRST > 0))
                         UNION ALL /*LANÇAMENTO DE INVENTÁRIO*/
                         SELECT FIRST 1 INV.BDCODEMP, 0 BDCHAVE, INV.BDCODPROD
                         FROM VEF_EMP_TMOVINV INV
                         WHERE INV.BDCODEMP = TSAI.BDCODEMP AND INV.BDCODPROD = TSAI.BDCODPROD
                         /* Alt.: #228032 - Estava olhando o inventario apenas do ano anterior, mas basta ser anterior ou igual...
                         AND (INV.BDREFINV BETWEEN CAST(CAST(SUBSTRING(TSAI.BDDATAEMISSAO FROM 1 FOR 4) AS INTEGER )-1 AS VARCHAR(04))||'01'
                         AND CAST(CAST(SUBSTRING(TSAI.BDDATAEMISSAO FROM 1 FOR 4) AS INTEGER )-1 AS VARCHAR(04))||'12' AND INV.BDCHAVE IS NOT NULL) */
                         AND (INV.BDREFINV < EXTRACT(YEAR FROM TSAI.BDDATAEMISSAO)||LPAD(EXTRACT(MONTH FROM TSAI.BDDATAEMISSAO),2,'0') AND INV.BDCHAVE IS NOT NULL)
                         AND (INV.BDVLRICMSST > 0)
                         ) ENT
                         GROUP BY BDCODPROD
                     );


      /*Procedure para dos registros - C185-C380-C480*/
      EXECUTE PROCEDURE SP_REGISTROS_PLANO_1250(:PRSESSAO,:PRCODEMP,:PRREF);

      /*EXECUTA A MEMÓRIA DE CÁLCULO DA ST E OP*/
      EXECUTE PROCEDURE SP_MEMCALCULO_PLANO_1250(:PRSESSAO,:PRCODEMP,:PRREF,:WCODUF);

      /*Procedure para gravar os dados na tabela física da apuração*/
      EXECUTE PROCEDURE SP_GRAVA_PLANO_1250(:PRSESSAO,:PRCODEMP,:PRREF,:WCODUF);

      /*INSERE OS REGISTROS NA TABELA FÍSICA, NOS LANÇAMENTOS*/
      EXECUTE PROCEDURE SP_INSEREREG_PLANO_1250(:PRSESSAO,:PRCODEMP,:PRREF);
  END /*END DO NÃO EFETUAR RECALCULO*/
  ELSE /*Vai inserir os registros dos lançamentos nas tabelas de apuração*/
  BEGIN
    /*C180*/
    INSERT INTO VEF_EMP_TICMSSPED_1250_C180 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPROD, BDCODPROD, BDCSTICMS, BDCODNAT,
                                             BDQUANTIDADE, BDVLRUNIT, BDVLRUNITICMS, BDBCUNITICMSST, BDICMSSTPRESUMIDO, BDNUMDOCINI, BDDATALAN)
    SELECT C180.BDCODEMP, 7, ENT.BDREFLAN, C180.BDCHAVE, C180.BDORDEM, C180.BDORDEMPRO,PRO.BDCODPROD, PRO.BDCODCSTICMS, I.BDCODNAT,
    C180.BDQTDCONVERTIDA,C180.BDVLRUNICONVERTIDO,C180.BDVLRUNITICMSOP, C180.BDBCUNITICMSST, C180.BDVLRUNITICMSST,
    ENT.BDNUMDOCINI, ENT.BDDATAENTRADAENT
    FROM VEF_EMP_TMOVC180_1250 C180
    LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = C180.BDCODEMP AND PRO.BDCHAVE = C180.BDCHAVE AND PRO.BDORDEM = C180.BDORDEM AND PRO.BDORDEMPRO = C180.BDORDEMPRO)
    LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = PRO.BDCODEMP AND I.BDCHAVE = PRO.BDCHAVE AND I.BDORDEM = PRO.BDORDEM)
    LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = PRO.BDCODEMP AND ENT.BDCHAVE = PRO.BDCHAVE)
    WHERE C180.BDCODEMP = :PRCODEMP AND ENT.BDREFLAN = :PRREF;

    /*C181*/
    INSERT INTO VEF_EMP_TICMSSPED_1250_C181 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPROD, BDCODPROD, BDMOTIVO, BDCSTICMS, BDCODNAT,
                                             BDQUANTIDADE, BDVLRUNITICMSEFETIVO, BDICMSOPPRESUMIDO, BDICMSSTPRESUMIDO, BDVLRRESTITUIR, BDVLRCOMPLEMENTAR, BDNUMDOCINI, BDDATALAN)
    
    
    
    SELECT C181.BDCODEMP, 7, ENT.BDREFLAN, C181.BDCHAVE, C181.BDORDEM, C181.BDORDEMPRO,PRO.BDCODPROD,C181.BDCODMOTIVO,PRO.BDCODCSTICMS, I.BDCODNAT,
    C181.BDQTDCONVERTIDA, C181.BDVLRUNITICMSEFETIVO, C181.BDVLRUNITICMSOPESTOQUE, C181.BDVLRUNITICMSSTESTOQUE, C181.BDVLRUNITICMSSTRESTITUIR, C181.BDVLRUNITICMSSTCOMPLEMENTAR,
    ENT.BDNUMDOCINI, ENT.BDDATAENTRADAENT
    FROM VEF_EMP_TMOVC181_1250 C181
    LEFT OUTER JOIN VEF_EMP_TMOVPROENT PRO ON (PRO.BDCODEMP = C181.BDCODEMP AND PRO.BDCHAVE = C181.BDCHAVE AND PRO.BDORDEM = C181.BDORDEM AND PRO.BDORDEMPRO = C181.BDORDEMPRO)
    LEFT OUTER JOIN VEF_EMP_TMOVENTITENS I ON (I.BDCODEMP = PRO.BDCODEMP AND I.BDCHAVE = PRO.BDCHAVE AND I.BDORDEM = PRO.BDORDEM)
    LEFT OUTER JOIN VEF_EMP_TMOVENT ENT ON (ENT.BDCODEMP = PRO.BDCODEMP AND ENT.BDCHAVE = PRO.BDCHAVE)
    WHERE C181.BDCODEMP = :PRCODEMP AND ENT.BDREFLAN = :PRREF;

    /*C185*/
    INSERT INTO VEF_EMP_TICMSSPED_1250_C185 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPROD, BDCODPROD, BDCSTICMS, BDCODNAT,
                                             BDMOTIVO, BDQUANTIDADE, BDVLRUNITICMSEFETIVO, BDICMSOPPRESUMIDO, BDICMSSTPRESUMIDO, BDVLRRESTITUIR,
                                             BDVLRCOMPLEMENTAR, BDNUMDOCINI, BDDATALAN)
    SELECT C185.BDCODEMP, 7, SAI.BDREFLAN, C185.BDCHAVE, C185.BDORDEM, C185.BDORDEMPRO,PRO.BDCODPROD, PRO.BDCODCSTICMS, I.BDCODNAT,
    C185.BDCODMOTIVO, C185.BDQTDCONVERTIDA, C185.BDVLRUNITICMSEFETIVO,C185.BDVLRUNITICMSOPESTOQUE, C185.BDVLRUNITICMSSTESTOQUE,
    C185.BDVLRUNITICMSSTRESTITUIR, C185.BDVLRUNITICMSSTCOMPLEMENTAR, SAI.BDNUMDOCINI, SAI.BDDATAEMISSAO
    FROM VEF_EMP_TMOVC185_1250 C185
    LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = C185.BDCODEMP AND PRO.BDCHAVE = C185.BDCHAVE AND PRO.BDORDEM = C185.BDORDEM AND PRO.BDORDEMPRO = C185.BDORDEMPRO)
    LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = PRO.BDCODEMP AND I.BDCHAVE = PRO.BDCHAVE AND I.BDORDEM = PRO.BDORDEM)
    LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = PRO.BDCODEMP AND SAI.BDCHAVE = PRO.BDCHAVE)
    WHERE C185.BDCODEMP = :PRCODEMP AND SAI.BDREFLAN = :PRREF;

    /*C186*/
    INSERT INTO VEF_EMP_TICMSSPED_1250_C186 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPROD, BDCODPROD, BDMOTIVO, BDCSTICMS, BDCODNAT,
                                         BDQUANTIDADE, BDVLRUNITARIO, BDVLRUNITICMS, BDBCICMSSTUNIT, BDICMSSTPRESUMIDO, BDNUMDOCINI, BDDATALAN)
    SELECT C186.BDCODEMP, 7, SAI.BDREFLAN, C186.BDCHAVE, C186.BDORDEM, C186.BDORDEMPRO,PRO.BDCODPROD,C186.BDCODMOTIVO,PRO.BDCODCSTICMS, I.BDCODNAT,
    C186.BDQTDCONVERTIDA,C186.BDVLRUNICONVERTIDO, C186.BDVLRUNITICMSOP, C186.BDBCUNITICMSST, C186.BDVLRUNITICMSST,
    SAI.BDNUMDOCINI, SAI.BDDATAEMISSAO
    FROM VEF_EMP_TMOVC186_1250 C186
    LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = C186.BDCODEMP AND PRO.BDCHAVE = C186.BDCHAVE AND PRO.BDORDEM = C186.BDORDEM AND PRO.BDORDEMPRO = C186.BDORDEMPRO)
    LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = PRO.BDCODEMP AND I.BDCHAVE = PRO.BDCHAVE AND I.BDORDEM = PRO.BDORDEM)
    LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = PRO.BDCODEMP AND SAI.BDCHAVE = PRO.BDCHAVE)
    WHERE C186.BDCODEMP = :PRCODEMP AND SAI.BDREFLAN = :PRREF;

    /*C380*/
    INSERT INTO VEF_EMP_TICMSSPED_1250_C380 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPROD, BDCODPROD, BDCSTICMS, BDCODNAT,
                                             BDMOTIVO, BDQUANTIDADE, BDVLRUNITICMSEFETIVO, BDICMSOPPRESUMIDO, BDICMSSTPRESUMIDO, BDVLRRESTITUIR, BDVLRCOMPLEMENTAR, BDNUMDOCINI, BDDATALAN)
    SELECT C380.BDCODEMP, 7, SAI.BDREFLAN, C380.BDCHAVE, C380.BDORDEM, C380.BDORDEMPRO,PRO.BDCODPROD,PRO.BDCODCSTICMS, I.BDCODNAT,C380.BDCODMOTIVO,
    C380.BDQTDCONVERTIDA,C380.BDVLRUNITICMSEFETIVO, C380.BDVLRUNITICMSOPESTOQUE, C380.BDVLRUNITICMSSTESTOQUE, C380.BDVLRUNITICMSSTRESTITUIR,
    C380.BDVLRUNITICMSSTCOMPLEMENTAR, SAI.BDNUMDOCINI, SAI.BDDATAEMISSAO
    FROM VEF_EMP_TMOVC380_1250 C380
    LEFT OUTER JOIN VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = C380.BDCODEMP AND PRO.BDCHAVE = C380.BDCHAVE AND PRO.BDORDEM = C380.BDORDEM AND PRO.BDORDEMPRO = C380.BDORDEMPRO)
    LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS I ON (I.BDCODEMP = PRO.BDCODEMP AND I.BDCHAVE = PRO.BDCHAVE AND I.BDORDEM = PRO.BDORDEM)
    LEFT OUTER JOIN VEF_EMP_TMOVSAI SAI ON (SAI.BDCODEMP = PRO.BDCODEMP AND SAI.BDCHAVE = PRO.BDCHAVE)
    WHERE C380.BDCODEMP = :PRCODEMP AND SAI.BDREFLAN = :PRREF;

    INSERT INTO VEF_EMP_TICMSSPED_1250_C480 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCHAVE, BDORDEM, BDORDEMPROD, BDCODPROD, BDCSTICMS, BDCODNAT, BDMOTIVO,
                                         BDQUANTIDADE, BDVLRUNITICMSEFETIVO, BDICMSOPPRESUMIDO, BDICMSSTPRESUMIDO, BDVLRRESTITUIR, BDVLRCOMPLEMENTAR, BDNUMDOCINI, BDDATALAN)
    SELECT C480.BDCODEMP, 7, SAI.BDREFLAN, C480.BDCHAVE, C480.BDORDEMDOCECF, C480.BDORDEMITEM,PRO.BDCODPROD,PRO.BDCODCSTICMS, PRO.BDCODNAT,C480.BDCODMOTIVO,
    C480.BDQTDCONVERTIDA, C480.BDVLRUNITICMSEFETIVO, C480.BDVLRUNITICMSOPESTOQUE, C480.BDVLRUNITICMSSTESTOQUE, C480.BDVLRUNITICMSSTRESTITUIR, C480.BDVLRUNITICMSSTCOMPLEMENTAR,
    I.BDNUMDOCCOO, I.BDDATAEMI
    FROM VEF_EMP_TMOVC480_1250 C480
    LEFT OUTER JOIN VEF_EMP_TITEMDOCECF PRO ON (PRO.BDCODEMP = C480.BDCODEMP AND PRO.BDCHAVE = C480.BDCHAVE AND PRO.BDORDEMDOCECF = C480.BDORDEMDOCECF AND PRO.BDORDEMITEM = C480.BDORDEMITEM)
    LEFT OUTER JOIN VEF_EMP_TDOCECF I ON (I.BDCODEMP = PRO.BDCODEMP AND I.BDCHAVE = PRO.BDCHAVE AND I.BDORDEMDOCECF = PRO.BDORDEMDOCECF)
    LEFT OUTER JOIN VEF_EMP_TREDZ SAI ON (SAI.BDCODEMP = PRO.BDCODEMP AND SAI.BDCHAVE = PRO.BDCHAVE)
    WHERE C480.BDCODEMP = :PRCODEMP AND SAI.BDREFLAN = :PRREF;

    /*INSERE REGISTROS NOS PRODUTOS*/
    INSERT INTO VEF_EMP_TICMSSPED1250_PROD (BDCODEMP, BDCODPERIODO, BDREFERENCIA,BDCODPROD,BDCODPRODEMP,BDDESCPROD)
    SELECT PROD.BDCODEMP,7, PROD.BDREFERENCIA, PROD.BDCODPROD,VINC.BDCODSAIDA, VINC.BDDESCPROD
    FROM (
          SELECT C180.BDCODEMP, C180.BDREFERENCIA, C180.BDCODPROD
          FROM VEF_EMP_TICMSSPED_1250_C180 C180
          WHERE C180.BDCODEMP = :PRCODEMP AND C180.BDREFERENCIA = :PRREF
          GROUP BY C180.BDCODEMP, C180.BDREFERENCIA, C180.BDCODPROD
          UNION ALL
          SELECT C181.BDCODEMP, C181.BDREFERENCIA, C181.BDCODPROD
          FROM VEF_EMP_TICMSSPED_1250_C181 C181
          WHERE C181.BDCODEMP = :PRCODEMP AND C181.BDREFERENCIA = :PRREF
          GROUP BY C181.BDCODEMP, C181.BDREFERENCIA, C181.BDCODPROD
          UNION ALL
          SELECT C185.BDCODEMP, C185.BDREFERENCIA, C185.BDCODPROD
          FROM VEF_EMP_TICMSSPED_1250_C185 C185
          WHERE C185.BDCODEMP = :PRCODEMP AND C185.BDREFERENCIA = :PRREF
          GROUP BY C185.BDCODEMP, C185.BDREFERENCIA, C185.BDCODPROD
          UNION ALL
          SELECT C186.BDCODEMP, C186.BDREFERENCIA, C186.BDCODPROD
          FROM VEF_EMP_TICMSSPED_1250_C186 C186
          WHERE C186.BDCODEMP = :PRCODEMP AND C186.BDREFERENCIA = :PRREF
          GROUP BY C186.BDCODEMP, C186.BDREFERENCIA, C186.BDCODPROD
          UNION ALL
          SELECT C380.BDCODEMP, C380.BDREFERENCIA, C380.BDCODPROD
          FROM VEF_EMP_TICMSSPED_1250_C380 C380
          WHERE C380.BDCODEMP = :PRCODEMP AND C380.BDREFERENCIA = :PRREF
          GROUP BY C380.BDCODEMP, C380.BDREFERENCIA, C380.BDCODPROD
          UNION ALL
          SELECT C480.BDCODEMP, C480.BDREFERENCIA, C480.BDCODPROD
          FROM VEF_EMP_TICMSSPED_1250_C480 C480
          WHERE C480.BDCODEMP = :PRCODEMP AND C480.BDREFERENCIA = :PRREF
          GROUP BY C480.BDCODEMP, C480.BDREFERENCIA, C480.BDCODPROD
       ) PROD
     LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = PROD.BDCODEMP AND VINC.BDCODPROD = PROD.BDCODPROD)
     WHERE PROD.BDCODPROD IS NOT NULL
     GROUP BY PROD.BDCODEMP, PROD.BDREFERENCIA, PROD.BDCODPROD,VINC.BDCODSAIDA, VINC.BDDESCPROD;
  END

  /*INSERIR O 1255*/
  FOR
    SELECT REG.BDCODEMP, REG.BDREFERENCIA, REG.BDMOTIVO, IIF((SUM(REG.BDVLRCREDICMS)-SUM(REG.BDVLRCREDICMSC181)) < 0,0,(SUM(REG.BDVLRCREDICMS)-SUM(REG.BDVLRCREDICMSC181))) BDVLRCREDICMSPROPRIO,
    SUM(BDVLRICMSSTRESTITUIR) BDVLRICMSSTRESTITUIR, SUM(BDVLRUNITFCPSTRESTITUIR) BDVLRUNITFCPSTRESTITUIR, SUM(BDVLRUNITICMSSTCOMPLEMENTAR) BDVLRUNITICMSSTCOMPLEMENTAR, SUM(BDVLRUNITFCPSTCOMPLEMENTAR) BDVLRUNITFCPSTCOMPLEMENTAR
    FROM (
          SELECT C185.BDCODEMP, C185.BDREFERENCIA,C185.BDMOTIVO, SUM((C185.BDQUANTIDADE* C185.BDICMSOPPRESUMIDO)) BDVLRCREDICMS, 0 BDVLRCREDICMSC181,
          SUM((COALESCE(C185.BDVLRRESTITUIR,0)*C185.BDQUANTIDADE)) BDVLRICMSSTRESTITUIR,
          SUM((COALESCE(MOV.BDVLRUNITFCPSTRESTITUIR,0)*C185.BDQUANTIDADE)) BDVLRUNITFCPSTRESTITUIR, SUM((COALESCE(MOV.BDVLRUNITICMSSTCOMPLEMENTAR,0)*C185.BDQUANTIDADE)) BDVLRUNITICMSSTCOMPLEMENTAR, SUM((COALESCE(MOV.BDVLRUNITFCPSTCOMPLEMENTAR,0)*C185.BDQUANTIDADE)) BDVLRUNITFCPSTCOMPLEMENTAR
          FROM VEF_EMP_TICMSSPED_1250_C185 C185
          LEFT OUTER JOIN VEF_EMP_TMOVC185_1250 MOV ON (MOV.BDCODEMP = C185.BDCODEMP AND MOV.BDCHAVE = C185.BDCHAVE AND MOV.BDORDEM = C185.BDORDEM AND MOV.BDORDEMPRO = C185.BDORDEMPROD)
          WHERE C185.BDCODEMP = :PRCODEMP AND C185.BDREFERENCIA = :PRREF
          GROUP BY C185.BDCODEMP, C185.BDREFERENCIA,C185.BDMOTIVO
          UNION ALL
          SELECT C380.BDCODEMP, C380.BDREFERENCIA,C380.BDMOTIVO, SUM((C380.BDQUANTIDADE*C380.BDICMSOPPRESUMIDO))  BDVLRCREDICMS, 0 BDVLRCREDICMSC181,
          SUM((COALESCE(C380.BDVLRRESTITUIR,0)*C380.BDQUANTIDADE)) BDVLRICMSSTRESTITUIR,
          SUM((COALESCE(MOV.BDVLRUNITFCPSTRESTITUIR,0)*C380.BDQUANTIDADE)) BDVLRUNITFCPSTRESTITUIR, SUM((COALESCE(MOV.BDVLRUNITICMSSTCOMPLEMENTAR,0)*C380.BDQUANTIDADE)) BDVLRUNITICMSSTCOMPLEMENTAR, SUM((COALESCE(MOV.BDVLRUNITFCPSTCOMPLEMENTAR,0)*C380.BDQUANTIDADE)) BDVLRUNITFCPSTCOMPLEMENTAR
          FROM VEF_EMP_TICMSSPED_1250_C380 C380
          LEFT OUTER JOIN VEF_EMP_TMOVC380_1250 MOV ON (MOV.BDCODEMP = C380.BDCODEMP AND MOV.BDCHAVE = C380.BDCHAVE AND MOV.BDORDEM = C380.BDORDEM AND MOV.BDORDEMPRO = C380.BDORDEMPROD)
          WHERE C380.BDCODEMP = :PRCODEMP AND C380.BDREFERENCIA = :PRREF
          GROUP BY C380.BDCODEMP, C380.BDREFERENCIA,C380.BDMOTIVO
          UNION ALL
          SELECT C480.BDCODEMP, C480.BDREFERENCIA,C480.BDMOTIVO, SUM((C480.BDQUANTIDADE*C480.BDICMSOPPRESUMIDO))   BDVLRCREDICMS, 0 BDVLRCREDICMSC181,
          SUM((COALESCE(C480.BDVLRRESTITUIR,0)*C480.BDQUANTIDADE)) BDVLRICMSSTRESTITUIR,
          SUM((COALESCE(MOV.BDVLRUNITFCPSTRESTITUIR,0)*C480.BDQUANTIDADE)) BDVLRUNITFCPSTRESTITUIR, SUM((COALESCE(MOV.BDVLRUNITICMSSTCOMPLEMENTAR,0)*C480.BDQUANTIDADE)) BDVLRUNITICMSSTCOMPLEMENTAR, SUM((COALESCE(MOV.BDVLRUNITFCPSTCOMPLEMENTAR,0)*C480.BDQUANTIDADE)) BDVLRUNITFCPSTCOMPLEMENTAR
          FROM VEF_EMP_TICMSSPED_1250_C480 C480
          LEFT OUTER JOIN VEF_EMP_TMOVC480_1250 MOV ON (MOV.BDCODEMP = C480.BDCODEMP AND MOV.BDCHAVE = C480.BDCHAVE AND MOV.BDORDEMDOCECF = C480.BDORDEM AND MOV.BDORDEMITEM = C480.BDORDEMPROD)
          WHERE C480.BDCODEMP = :PRCODEMP AND C480.BDREFERENCIA = :PRREF
          GROUP BY C480.BDCODEMP, C480.BDREFERENCIA,C480.BDMOTIVO
          UNION ALL
          SELECT C181.BDCODEMP, C181.BDREFERENCIA,C181.BDMOTIVO,
          0 BDVLRCREDICMS, 0 BDVLRCREDICMSC181,
          SUM((COALESCE(C181.BDVLRRESTITUIR,0)*C181.BDQUANTIDADE)) BDVLRICMSSTRESTITUIR,
          SUM((COALESCE(MOV.BDVLRUNITFCPSTRESTITUIR,0) *C181.BDQUANTIDADE)) BDVLRUNITFCPSTRESTITUIR, SUM((COALESCE(MOV.BDVLRUNITICMSSTCOMPLEMENTAR,0)*C181.BDQUANTIDADE)) BDVLRUNITICMSSTCOMPLEMENTAR, SUM((COALESCE(MOV.BDVLRUNITFCPSTCOMPLEMENTAR,0)*C181.BDQUANTIDADE)) BDVLRUNITFCPSTCOMPLEMENTAR
          FROM VEF_EMP_TICMSSPED_1250_C181 C181
          LEFT OUTER JOIN VEF_EMP_TMOVC181_1250 MOV ON (MOV.BDCODEMP = C181.BDCODEMP AND MOV.BDCHAVE = C181.BDCHAVE AND MOV.BDORDEM = C181.BDORDEM AND MOV.BDORDEMPRO = C181.BDORDEMPROD)
          WHERE C181.BDCODEMP = :PRCODEMP AND C181.BDREFERENCIA = :PRREF
          GROUP BY C181.BDCODEMP, C181.BDREFERENCIA,BDMOTIVO
          UNION ALL /*Para descontar o valor de cred das saídas*/
          SELECT C181.BDCODEMP, C181.BDREFERENCIA,
                 CASE TAB.BDCODAJUR
                 WHEN 'RS500' THEN 1  /*RS000*/ WHEN 'RS501' THEN 2  /*RS001*/ WHEN 'RS600' THEN 6  /*RS100*/
                 WHEN 'RS713' THEN 9  /*RS213*/ WHEN 'RS714' THEN 10 /*RS214*/ WHEN 'RS717' THEN 12 /*RS217*/
                 WHEN 'RS719' THEN 13 /*RS219*/ WHEN 'RS800' THEN 14 /*RS300*/ END BDMOTIVO,
                 0 BDVLRCREDICMS, SUM((C181.BDQUANTIDADE*C181.BDICMSOPPRESUMIDO)) BDVLRCREDICMSC181,
                 0 BDVLRICMSSTRESTITUIR,0 BDVLRUNITFCPSTRESTITUIR, 0 BDVLRUNITICMSSTCOMPLEMENTAR, 0 BDVLRUNITFCPSTCOMPLEMENTAR
           FROM(
                  SELECT C185.BDCODEMP, C185.BDREFERENCIA,C185.BDMOTIVO
                  FROM VEF_EMP_TICMSSPED_1250_C185 C185
                  WHERE C185.BDCODEMP = :PRCODEMP AND C185.BDREFERENCIA = :PRREF
                  GROUP BY C185.BDCODEMP, C185.BDREFERENCIA,C185.BDMOTIVO
                  UNION ALL
                  SELECT C380.BDCODEMP, C380.BDREFERENCIA,C380.BDMOTIVO
                  FROM VEF_EMP_TICMSSPED_1250_C380 C380
                  WHERE C380.BDCODEMP = :PRCODEMP AND C380.BDREFERENCIA = :PRREF
                  GROUP BY C380.BDCODEMP, C380.BDREFERENCIA,C380.BDMOTIVO
                  UNION ALL
                  SELECT C480.BDCODEMP, C480.BDREFERENCIA,C480.BDMOTIVO
                  FROM VEF_EMP_TICMSSPED_1250_C480 C480
                  WHERE C480.BDCODEMP = :PRCODEMP AND C480.BDREFERENCIA = :PRREF
                  GROUP BY C480.BDCODEMP, C480.BDREFERENCIA,C480.BDMOTIVO
                  UNION ALL
                  SELECT C181.BDCODEMP, C181.BDREFERENCIA,C181.BDMOTIVO
                  FROM VEF_EMP_TICMSSPED_1250_C181 C181
                  WHERE C181.BDCODEMP = :PRCODEMP AND C181.BDREFERENCIA = :PRREF
                  GROUP BY C181.BDCODEMP, C181.BDREFERENCIA,BDMOTIVO
               ) MOT
           JOIN VEF_EMP_TICMSSPED_1250_C181 C181 ON (C181.BDCODEMP = MOT.BDCODEMP AND C181.BDREFERENCIA = MOT.BDREFERENCIA)
           LEFT OUTER JOIN VEF_BASE_TTABINFAD57 TAB ON (TAB.BDORDEM57 = C181.BDMOTIVO)
           WHERE MOT.BDMOTIVO = (CASE TAB.BDCODAJUR
                 WHEN 'RS500' THEN 1  /*RS000*/ WHEN 'RS501' THEN 2  /*RS001*/ WHEN 'RS600' THEN 6  /*RS100*/
                 WHEN 'RS713' THEN 9  /*RS213*/ WHEN 'RS714' THEN 10 /*RS214*/ WHEN 'RS717' THEN 12 /*RS217*/
                 WHEN 'RS719' THEN 13 /*RS219*/ WHEN 'RS800' THEN 14 /*RS300*/ END)
           GROUP BY C181.BDCODEMP, C181.BDREFERENCIA,BDMOTIVO
          ) REG
    LEFT OUTER JOIN VEF_BASE_TTABINFAD57 TAB ON (TAB.BDORDEM57 = REG.BDMOTIVO)
    WHERE (REG.BDMOTIVO IS NOT NULL) /*AND (SUBSTRING(TAB.BDCODAJUR FROM 1 FOR 3)) <> 'RS0'*/
    GROUP BY REG.BDCODEMP, REG.BDREFERENCIA, REG.BDMOTIVO
    INTO :WCODEMP,:WREFERENCIA,:WMOTIVO,:WVLRCREDICMSPROPRIO,:WVLRICMSSTRETITUIR,:WVLRUNITFCPSTRESTITUIR,:WVLRUNITICMSSTCOMPLEMENTAR,:WVLRUNITFCPSTCOMPLEMENTAR
  DO
    BEGIN
       UPDATE OR INSERT INTO VEF_EMP_TICMSSPED1255 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCODMOTIVO, BDNUMCAMPO, BDVALOR,BDCODQICMSSPED)
                                 VALUES (:WCODEMP, 7, :WREFERENCIA,:WMOTIVO, 1,:WVLRCREDICMSPROPRIO,13)
                               MATCHING (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO,BDCODMOTIVO);

       UPDATE OR INSERT INTO VEF_EMP_TICMSSPED1255 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCODMOTIVO, BDNUMCAMPO, BDVALOR,BDCODQICMSSPED)
                                 VALUES (:WCODEMP, 7, :WREFERENCIA,:WMOTIVO, 2,:WVLRICMSSTRETITUIR,13)
                               MATCHING (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO,BDCODMOTIVO);

       UPDATE OR INSERT INTO VEF_EMP_TICMSSPED1255 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCODMOTIVO, BDNUMCAMPO, BDVALOR,BDCODQICMSSPED)
                                 VALUES (:WCODEMP, 7, :WREFERENCIA,:WMOTIVO, 3,:WVLRUNITFCPSTRESTITUIR,13)
                               MATCHING (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO,BDCODMOTIVO);

       UPDATE OR INSERT INTO VEF_EMP_TICMSSPED1255 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCODMOTIVO, BDNUMCAMPO, BDVALOR,BDCODQICMSSPED)
                                 VALUES (:WCODEMP, 7, :WREFERENCIA,:WMOTIVO, 4,:WVLRUNITICMSSTCOMPLEMENTAR,13)
                               MATCHING (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO,BDCODMOTIVO);

       UPDATE OR INSERT INTO VEF_EMP_TICMSSPED1255 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDCODMOTIVO, BDNUMCAMPO, BDVALOR,BDCODQICMSSPED)
                                 VALUES (:WCODEMP, 7, :WREFERENCIA,:WMOTIVO, 5,:WVLRUNITFCPSTCOMPLEMENTAR,13)
                               MATCHING (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO,BDCODMOTIVO);
    END

   UPDATE OR INSERT INTO VEF_EMP_TICMSSPED1250 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO, BDVALOR, BDCODQICMSSPED)
                                     VALUES (:PRCODEMP, 7, :PRREF, 1, 0, 12);

   UPDATE OR INSERT INTO VEF_EMP_TICMSSPED1250 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO, BDVALOR, BDCODQICMSSPED)
                                     VALUES (:PRCODEMP, 7, :PRREF, 2, 0, 12);

   UPDATE OR INSERT INTO VEF_EMP_TICMSSPED1250 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO, BDVALOR, BDCODQICMSSPED)
                                     VALUES (:PRCODEMP, 7, :PRREF, 3, 0, 12);

   UPDATE OR INSERT INTO VEF_EMP_TICMSSPED1250 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO, BDVALOR, BDCODQICMSSPED)
                                     VALUES (:PRCODEMP, 7, :PRREF, 4, 0, 12);

   UPDATE OR INSERT INTO VEF_EMP_TICMSSPED1250 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO, BDVALOR, BDCODQICMSSPED)
                                     VALUES (:PRCODEMP, 7, :PRREF, 5, 0, 12);

  FOR
    SELECT SPE.BDCODEMP, SPE.BDREFERENCIA, SUM(BDVALOR01) BDVALOR01, SUM(BDVALOR02) BDVALOR02, SUM(BDVALOR03) BDVALOR03,
           SUM(BDVALOR04) BDVALOR04, SUM(BDVALOR05) BDVALOR05
    FROM (
          SELECT SPE.BDCODEMP, SPE.BDREFERENCIA, IIF(SPE.BDNUMCAMPO = 1, SPE.BDVALOR, 0) BDVALOR01,
                 IIF(SPE.BDNUMCAMPO = 2, SPE.BDVALOR, 0) BDVALOR02, IIF(SPE.BDNUMCAMPO = 3, SPE.BDVALOR, 0) BDVALOR03,
                 IIF(SPE.BDNUMCAMPO = 4, SPE.BDVALOR, 0) BDVALOR04, IIF(SPE.BDNUMCAMPO = 5, SPE.BDVALOR, 0) BDVALOR05
          FROM VEF_EMP_TICMSSPED1255 SPE
          WHERE SPE.BDCODEMP = :PRCODEMP AND
                SPE.BDREFERENCIA = :PRREF
          ) SPE
    GROUP BY SPE.BDCODEMP, SPE.BDREFERENCIA
    INTO :WCODEMP,:WREFERENCIA,:WVLRCREDICMSPROPRIO,:WVLRICMSSTRETITUIR,:WVLRUNITFCPSTRESTITUIR,:WVLRUNITICMSSTCOMPLEMENTAR,:WVLRUNITFCPSTCOMPLEMENTAR
  DO
    BEGIN
       UPDATE OR INSERT INTO VEF_EMP_TICMSSPED1250 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO, BDVALOR, BDCODQICMSSPED)
                                         VALUES (:WCODEMP, 7, :WREFERENCIA, 1, :WVLRCREDICMSPROPRIO, 12)
                                         MATCHING (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO);

       UPDATE OR INSERT INTO VEF_EMP_TICMSSPED1250 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO, BDVALOR, BDCODQICMSSPED)
                                         VALUES (:WCODEMP, 7, :WREFERENCIA, 2, :WVLRICMSSTRETITUIR, 12)
                                         MATCHING (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO);

       UPDATE OR INSERT INTO VEF_EMP_TICMSSPED1250 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO, BDVALOR, BDCODQICMSSPED)
                                         VALUES (:WCODEMP, 7, :WREFERENCIA, 3, :WVLRUNITFCPSTRESTITUIR, 12)
                                         MATCHING (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO);

       UPDATE OR INSERT INTO VEF_EMP_TICMSSPED1250 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO, BDVALOR, BDCODQICMSSPED)
                                         VALUES (:WCODEMP, 7, :WREFERENCIA, 4, :WVLRUNITICMSSTCOMPLEMENTAR, 12)
                                         MATCHING (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO);

       UPDATE OR INSERT INTO VEF_EMP_TICMSSPED1250 (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO, BDVALOR, BDCODQICMSSPED)
                                         VALUES (:WCODEMP, 7, :WREFERENCIA, 5, :WVLRUNITFCPSTCOMPLEMENTAR, 12)
                                         MATCHING (BDCODEMP, BDCODPERIODO, BDREFERENCIA, BDNUMCAMPO);

    END

  if (WGERARAJUE220E111 = 'TRUE') then
    begin
      if (WCODUF = 19) then
        begin
          :WCAMPOAPU = null;
          for select sum(coalesce(S1255.BDVALOR, 0.00)) as BDVALOR,
                     iif(sum(coalesce(S1255.BDVALOR, 0.00)) < 0, 'TRUE', 'FALSE') as BDNEGATIVO, S1255.BDNUMCAMPO
              from (select coalesce(T1255.BDVALOR, 0.00) as BDVALOR, iif(T1255.BDNUMCAMPO = 4, 'RJ050025', 'RJ050026') as BDNUMCAMPO /* ICMS ST e FCP ST */
                    from VEF_EMP_TICMSSPED1255 T1255
                    where T1255.BDCODEMP = :PRCODEMP and
                          T1255.BDREFERENCIA = :PRREF and
                          (T1255.BDNUMCAMPO = 4 or T1255.BDNUMCAMPO = 5)
                    union all
                    select coalesce(T1255.BDVALOR, 0.00) as BDVALOR, 'RJ020079' as BDNUMCAMPO /* ICMS ST + FCP ST */
                    from VEF_EMP_TICMSSPED1255 T1255
                    where T1255.BDCODEMP = :PRCODEMP and
                          T1255.BDREFERENCIA = :PRREF and
                          (T1255.BDNUMCAMPO = 2 or T1255.BDNUMCAMPO = 3)) S1255
              group by S1255.BDNUMCAMPO
              into WVALOR, WNEGATIVO, WCAMPOAPU
          do
            begin
              if (coalesce(WVALOR, 0) <> 0) then
                begin
                  select coalesce((max(BDORDEMe111220)), 0) + 1 from VEF_EMP_TAJUICMSE111 where BDCODEMP = :PRCODEMP into :WORDEM; /*Busca a ordem*/

                  if (WNEGATIVO = 'TRUE') then
                    begin
                      select bdvalor from VEF_EMP_TICMSSPEDGERREG
                      where bdcodemp = :prcodemp and bdreferencia = :prref
                      and BDNUMCAMPO = 13 and BDCODQICMSSPED = 2 into :WVALORE110;
        
                      if (coalesce(:WVALORE110, 0) > 0) then
                        begin
                          /*Insere E111*/
                          insert into VEF_EMP_TAJUICMSE111 (BDCODEMP, BDORDEME111220 ,BDCODAJUICMS, BDREFERENCIA, BDDESCCOMP, BDVLRAJU, BDCODTIPO, BDBENEFICIO)
                          values (:PRCODEMP, :WORDEM , (select first 1 BDCODAJUICMSST
                                                        from  VEF_BASE_TTABAJUICMSST
                                                        where BDCODAJUST = :WCAMPOAPU and
                                                              (((select BDAAAAMM from AAAAMM(BDDATAINI)) <= CAST(:PRREF as VARCHAR(6))) and
                                                              (((select BDAAAAMM from AAAAMM(BDDATAFIM)) >= CAST(:PRREF as VARCHAR(6))) or (BDDATAFIM is null))) order by BDCODAJUICMSST desc), :PRREF, '', iif(:WVALORE110 < iif(:wValor < 0, :wValor * -1, :wValor), :WVALORE110, iif(:wValor < 0, :wValor * -1, :wValor)), 141, null);
                          /*Insere TOL E111*/
                          insert into TOL_VEF_EMP_TICMSSPEDGER_E111 (BDCODEMP, BDORDEME111220, BDCODPERIODO, BDREFERENCIA)
                          values (:PRCODEMP, :WORDEM, 7, :PRREF);
                        end
                    end
                  else
                    begin
                      /*Insere E111*/
                      insert into VEF_EMP_TAJUICMSE111 (BDCODEMP, BDORDEME111220 ,BDCODAJUICMS, BDREFERENCIA, BDDESCCOMP, BDVLRAJU, BDCODTIPO, BDBENEFICIO)
                      values (:PRCODEMP, :WORDEM , (select first 1 BDCODAJUICMS
                                                    from VEF_BASE_TTABAJUICMS
                                                    where BDCODAJUPAD = :WCAMPOAPU and
                                                          (((select BDAAAAMM from AAAAMM(BDDATAINI)) <= CAST(:PRREF as VARCHAR(6))) and
                                                          (((select BDAAAAMM from AAAAMM(BDDATAFIM)) >= CAST(:PRREF as VARCHAR(6))) or (BDDATAFIM is null))) order by BDCODAJUICMS desc) , :PRREF, '', :WVALOR, 141, null);
                       /*Insere TOL E111*/
                       insert into TOL_VEF_EMP_TICMSSPEDGER_E111 (BDCODEMP, BDORDEME111220, BDCODPERIODO, BDREFERENCIA)
                       values (:PRCODEMP, :WORDEM, 7, :PRREF);
                    end
                end
            end
        end
      else
        begin
      for select ((BDVALOR_RS100 + BDVALOR_RS800) - (BDVALOR_RS300 + BDVALOR_RS600)) as BDVALORTOTAL,
                                                                           iif(((BDVALOR_RS100 + BDVALOR_RS800) - (BDVALOR_RS300 + BDVALOR_RS600)) < 0, 'TRUE', 'FALSE') as BDNEGATIVO
          from (select sum(BDVALOR_RS100) BDVALOR_RS100, sum(BDVALOR_RS800) BDVALOR_RS800, sum(BDVALOR_RS300) BDVALOR_RS300,
                       sum(BDVALOR_RS600) BDVALOR_RS600
                from (select iif(BDNUMCAMPO = 2, BDVALOR, 0) BDVALOR_RS100, 0 BDVALOR_RS800, 0 BDVALOR_RS300, 0 BDVALOR_RS600
                      from VEF_EMP_TICMSSPED1255 T1255
                      left outer join VEF_BASE_TTABINFAD57 T57 on (T57.BDORDEM57 = T1255.BDCODMOTIVO)
                      where T1255.BDCODEMP = :PRCODEMP and
                            T1255.BDREFERENCIA = :PRREF and
                            T57.BDCODAJUR = 'RS100'
                      union all
                      select 0 BDVALOR_RS100, iif(BDNUMCAMPO = 2, BDVALOR, 0) BDVALOR_RS800, 0 BDVALOR_RS300, 0 BDVALOR_RS600
                      from VEF_EMP_TICMSSPED1255 T1255
                      left outer join VEF_BASE_TTABINFAD57 T57 on (T57.BDORDEM57 = T1255.BDCODMOTIVO)
                      where T1255.BDCODEMP = :PRCODEMP and
                            T1255.BDREFERENCIA = :PRREF and
                            T57.BDCODAJUR = 'RS800'
                      union all
                      select 0 BDVALOR_RS100, 0 BDVALOR_RS800, iif(BDNUMCAMPO = 4, BDVALOR, 0) BDVALOR_RS300, 0 BDVALOR_RS600
                      from VEF_EMP_TICMSSPED1255 T1255
                      left outer join VEF_BASE_TTABINFAD57 T57 on (T57.BDORDEM57 = T1255.BDCODMOTIVO)
                      where T1255.BDCODEMP = :PRCODEMP and
                            T1255.BDREFERENCIA = :PRREF and
                            T57.BDCODAJUR = 'RS300'
                      union all
                      select 0 BDVALOR_RS100, 0 BDVALOR_RS800, 0 BDVALOR_RS300, iif(BDNUMCAMPO = 4, BDVALOR, 0) BDVALOR_RS600
                      from VEF_EMP_TICMSSPED1255 T1255
                      left outer join VEF_BASE_TTABINFAD57 T57 on (T57.BDORDEM57 = T1255.BDCODMOTIVO)
                      where T1255.BDCODEMP = :PRCODEMP and
                            T1255.BDREFERENCIA = :PRREF and
                            T57.BDCODAJUR = 'RS600'))
          into wvalor,  wnegativo
       do
        begin
          if (coalesce(wVALOR, 0) <> 0) then
            begin
              if (WNEGATIVO = 'TRUE') then
                begin
                  /*Busca a ordem*/
                  SELECT COALESCE((MAX(bdordemE111220)), 0) +1 FROM VEF_EMP_TAJUICMSSTE220 WHERE bdcodemp = :PRCODEMP INTO :WORDEM;
                  /*Insere E220*/
                  insert into VEF_EMP_TAJUICMSSTE220 (BDCODEMP, BDORDEME111220,BDCODUF, BDCODAJUICMS, BDREFERENCIA, BDDESCCOMP, BDVLRAJU,BDCODTIPO, BDBENEFICIO)
                     values (:PRCODEMP, :WORDEM ,23, (select first 1 BDCODAJUICMSST
                                                   from  VEF_BASE_TTABAJUICMSST
                                                   where BDCODAJUST = 'RS101255' and
                                                         (((select BDAAAAMM from AAAAMM(BDDATAINI)) <= CAST(:PRREF as VARCHAR(6))) and
                                                            (((select BDAAAAMM from AAAAMM(BDDATAFIM)) >= CAST(:PRREF as VARCHAR(6))) or (BDDATAFIM is null))) order by BDCODAJUICMSST desc),:PRREF, '', iif(:wValor < 0, :wValor * -1, :wValor), 141, null);
                  /*Insere TOL E220*/
                  insert into TOL_VEF_EMP_TMOVAJUE220 (BDCODEMP, BDORDEME111220, BDCODPERIODO, BDREFERENCIA)
                  values (:PRCODEMP, :WORDEM, 7, :PRREF);
    
                  select bdvalor from VEF_EMP_TICMSSPEDGERREG
                  where bdcodemp = :prcodemp and bdreferencia = :prref
                  and BDNUMCAMPO = 13 and BDCODQICMSSPED = 2 into :WVALORE110;
    
                  if (coalesce(:WVALORE110, 0) > 0) then
                    begin
                      /*Busca a ordem*/
                      SELECT COALESCE((MAX(bdordemE111220)), 0) +1 FROM VEF_EMP_TAJUICMSE111 WHERE bdcodemp = :PRCODEMP INTO :WORDEM;
                      /*Insere E111*/
                      insert into VEF_EMP_TAJUICMSE111 (BDCODEMP, BDORDEME111220 ,BDCODAJUICMS, BDREFERENCIA, BDDESCCOMP, BDVLRAJU, BDCODTIPO, BDBENEFICIO)
                         values (:PRCODEMP, :WORDEM , (select first 1 BDCODAJUICMS
                                                    from VEF_BASE_TTABAJUICMS
                                                    where BDCODAJUPAD = 'RS011513' and
                                                          (((select BDAAAAMM from AAAAMM(BDDATAINI)) <= CAST(:PRREF as VARCHAR(6))) and
                                                             (((select BDAAAAMM from AAAAMM(BDDATAFIM)) >= CAST(:PRREF as VARCHAR(6))) or (BDDATAFIM is null))) order by BDCODAJUICMS desc) , :PRREF, '', iif(:WVALORE110 < iif(:wValor < 0, :wValor * -1, :wValor), :WVALORE110, iif(:wValor < 0, :wValor * -1, :wValor)), 141, null);
                      /*Insere TOL E111*/
                      insert into TOL_VEF_EMP_TICMSSPEDGER_E111 (BDCODEMP, BDORDEME111220, BDCODPERIODO, BDREFERENCIA)
                      values (:PRCODEMP, :WORDEM, 7, :PRREF);
    
                      /*Busca a ordem*/
                      SELECT COALESCE((MAX(bdordemE111220)), 0) +1 FROM VEF_EMP_TAJUICMSSTE220 WHERE bdcodemp = :PRCODEMP INTO :WORDEM;
                      /*Insere E220*/
                      insert into VEF_EMP_TAJUICMSSTE220 (BDCODEMP, BDORDEME111220,BDCODUF, BDCODAJUICMS, BDREFERENCIA, BDDESCCOMP, BDVLRAJU,BDCODTIPO, BDBENEFICIO)
                         values (:PRCODEMP, :WORDEM ,23, (select first 1 BDCODAJUICMSST
                                                       from  VEF_BASE_TTABAJUICMSST
                                                       where BDCODAJUST = 'RS122702' and
                                                             (((select BDAAAAMM from AAAAMM(BDDATAINI)) <= CAST(:PRREF as VARCHAR(6))) and
                                                                (((select BDAAAAMM from AAAAMM(BDDATAFIM)) >= CAST(:PRREF as VARCHAR(6))) or (BDDATAFIM is null))) order by BDCODAJUICMSST desc),:PRREF, '', iif(:WVALORE110 < iif(:wValor < 0, :wValor * -1, :wValor), :WVALORE110, iif(:wValor < 0, :wValor * -1, :wValor)), 141, null);
                      /*Insere TOL E220*/
                      insert into TOL_VEF_EMP_TMOVAJUE220 (BDCODEMP, BDORDEME111220, BDCODPERIODO, BDREFERENCIA)
                      values (:PRCODEMP, :WORDEM, 7, :PRREF);
                   end
                end
              else
                begin
                  if (WLANCAE220 = 'TRUE') then
                    begin
                      /*Busca a ordem*/
                      SELECT COALESCE((MAX(bdordemE111220)), 0) +1 FROM VEF_EMP_TAJUICMSSTE220 WHERE bdcodemp = :PRCODEMP INTO :WORDEM;
                      /*Insere E220*/
                      insert into VEF_EMP_TAJUICMSSTE220 (BDCODEMP, BDORDEME111220,BDCODUF, BDCODAJUICMS, BDREFERENCIA, BDDESCCOMP, BDVLRAJU,BDCODTIPO, BDBENEFICIO)
                         values (:PRCODEMP, :WORDEM ,23, (select first 1 BDCODAJUICMSST
                                                       from  VEF_BASE_TTABAJUICMSST
                                                       where BDCODAJUST = 'RS121255' and
                                                             (((select BDAAAAMM from AAAAMM(BDDATAINI)) <= CAST(:PRREF as VARCHAR(6))) and
                                                                (((select BDAAAAMM from AAAAMM(BDDATAFIM)) >= CAST(:PRREF as VARCHAR(6))) or (BDDATAFIM is null))) order by BDCODAJUICMSST desc),:PRREF, '', :WVALOR, 141, null);
                      /*Insere TOL E220*/
                      insert into TOL_VEF_EMP_TMOVAJUE220 (BDCODEMP, BDORDEME111220, BDCODPERIODO, BDREFERENCIA)
                      values (:PRCODEMP, :WORDEM, 7, :PRREF);
                    end
                  else
                    begin
                      /*Busca a ordem*/
                      SELECT COALESCE((MAX(bdordemE111220)), 0) +1 FROM VEF_EMP_TAJUICMSE111 WHERE bdcodemp = :PRCODEMP INTO :WORDEM;
                      /*Insere E111*/
                      insert into VEF_EMP_TAJUICMSE111 (BDCODEMP, BDORDEME111220 ,BDCODAJUICMS, BDREFERENCIA, BDDESCCOMP, BDVLRAJU, BDCODTIPO, BDBENEFICIO)
                         values (:PRCODEMP, :WORDEM , (select first 1 BDCODAJUICMS
                                                    from VEF_BASE_TTABAJUICMS
                                                    where BDCODAJUPAD = 'RS021255' and
                                                          (((select BDAAAAMM from AAAAMM(BDDATAINI)) <= CAST(:PRREF as VARCHAR(6))) and
                                                             (((select BDAAAAMM from AAAAMM(BDDATAFIM)) >= CAST(:PRREF as VARCHAR(6))) or (BDDATAFIM is null))) order by BDCODAJUICMS desc) , :PRREF, '', :WVALOR, 141, null);
                      /*Insere TOL E111*/
                      insert into TOL_VEF_EMP_TICMSSPEDGER_E111 (BDCODEMP, BDORDEME111220, BDCODPERIODO, BDREFERENCIA)
                      values (:PRCODEMP, :WORDEM, 7, :PRREF);
                    end
                end
            end
        end
    end
    end

  DELETE FROM TMP_VEF_EMP_TMOVSAISTRS_TEMP SAI WHERE SAI.BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TICMSSPED_1250_TEMP TAB WHERE TAB.BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TMEMCALC_1250_TEMP TAB WHERE TAB.BDSESSAO = :PRSESSAO;
END
^


CREATE OR ALTER procedure SP_MODELOCORRESPONDENTE1923 (
    PRMODELO integer)
returns (
    BDMODELO1923 integer)
as
BEGIN
  bdmodelo1923 = prmodelo;

    if (prmodelo = 6) then
      bdmodelo1923 = 7;
    else
    if (prmodelo = 7) then
      bdmodelo1923 = 8;
    else
    if (prmodelo = 8) then
      bdmodelo1923 = 9;
    else
    if (prmodelo = 10) then
      bdmodelo1923 = 12;
    else
    if (prmodelo = 11) then
      bdmodelo1923 = 13;
    else
    if (prmodelo = 13) then
      bdmodelo1923 = 14;
    else
    if (prmodelo = 14) then
      bdmodelo1923 = 15;
    else
    if (prmodelo = 15) then
      bdmodelo1923 = 16;
    else
    if (prmodelo = 16) then
      bdmodelo1923 = 18;
    else
    if (prmodelo = 55) then
      bdmodelo1923 = 30;
    else
    if (prmodelo = 57) then
      bdmodelo1923 = 31;
    else
    if (prmodelo = 59) then
      bdmodelo1923 = 32;
    else
    if (prmodelo = 65) then
      bdmodelo1923 = 34;
    else
    if (prmodelo = 67) then
      bdmodelo1923 = 36;
    else
    if (prmodelo = 800) then
      bdmodelo1923 = 10;
    else
    if (prmodelo = 100) then
      bdmodelo1923 = 2;
  suspend;
END^


CREATE OR ALTER procedure SP_COMMIT_PLANO_1900 (
    PRSESSAO integer,
    PRCODEMP integer,
    PRCHAVE1921 integer)
as
BEGIN

--  TROCA CHAVES 1921
  SETORDEMSEQUENCIAL_PESQ(0);
  update TMP_VEF_EMP_TMOVAJU1921_PL_TEMP t set t.bdeditchave = :prchave1921 where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;

--  TROCA CHAVES 1923
  SETORDEMSEQUENCIAL_STR(:prCODEMP);
  update TMP_VEF_EMP_TMOVAJU1923_PL_TEMP t
  set t.bdeditchave = (select first 1 t21.bdeditchave from TMP_VEF_EMP_TMOVAJU1921_PL_TEMP t21
                       where t.bdsessao = t21.bdsessao and t.bdcodemp = t21.bdcodemp AND T.bdtipolan = T21.bdtipolan and t.bdordem1921 = t21.bdordem1921
                       and t.bdcodajuicms = t21.bdcodajuicms and t.bdvlraju = t21.bdvlraju)
  where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;

  --seta a ordem do 923
  SETORDEMSEQUENCIAL_PESQ(0);
  SETORDEMSEQUENCIAL_STR(:prCODEMP);
  update TMP_VEF_EMP_TMOVAJU1923_PL_TEMP t
  set t.bdeditordem1923 = 1
  where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;

  --edit chave do 1921
  update TOL_VEF_EMP_TMOVSAIAJU1921_TEMP t
  set t.bdeditchave = (select first 1 t21.bdeditchave from TMP_VEF_EMP_TMOVAJU1921_PL_TEMP t21 where t.bdsessao = t21.bdsessao and t.bdcodemp = t21.bdcodemp
  and t.bdchave = t21.bdordem1921 and t.bdcodajuicms = t21.bdcodajuicms and t.bdvlraju = t21.bdvlraju and t21.bdtipolan = 1)
  where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;

  update TOL_VEF_EMP_TMOVENTAJU1921_TEMP t
  set t.bdeditchave = (select first 1 t21.bdeditchave from TMP_VEF_EMP_TMOVAJU1921_PL_TEMP t21 where t.bdsessao = t21.bdsessao and t.bdcodemp = t21.bdcodemp
  and t.bdchave = t21.bdordem1921  and t.bdcodajuicms = t21.bdcodajuicms and t.bdvlraju = t21.bdvlraju and t21.bdtipolan = 0)
  where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;

  update TOL_VEF_EMP_TMOVREDZAJU1921_TMP t
  set t.BDEDITCHAVE = (select first 1 t21.bdeditchave from TMP_VEF_EMP_TMOVAJU1921_PL_TEMP t21 where t.bdsessao = t21.bdsessao and t.bdcodemp = t21.bdcodemp
  and t.bdchave = t21.bdordem1921  and t.bdcodajuicms = t21.bdcodajuicms and t.bdvlraju = t21.bdvlraju and t21.bdtipolan = 3) /*Red */
  where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;

  --edit ordem do 1923
  update TOL_VEF_EMP_TMOVSAIAJU1921_TEMP t
  set t.BDEDITORDEM1923 = (select first 1 t21.BDEDITORDEM1923 from TMP_VEF_EMP_TMOVAJU1923_PL_TEMP t21 where t.bdsessao = t21.bdsessao and t.bdcodemp = t21.bdcodemp
  and t.bdchave = t21.bdordem1921 and t.bdordem1923 = t21.bdordem1923  and t.bdcodajuicms = t21.bdcodajuicms and t.bdvlraju = t21.bdvlraju  and t21.bdtipolan = 1)
  where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;

  update TOL_VEF_EMP_TMOVENTAJU1921_TEMP t
  set t.BDEDITORDEM1923 = (select first 1 t21.BDEDITORDEM1923 from TMP_VEF_EMP_TMOVAJU1923_PL_TEMP t21 where t.bdsessao = t21.bdsessao and t.bdcodemp = t21.bdcodemp
  and t.bdchave = t21.bdordem1921 and t.bdordem1923 = t21.bdordem1923 and t.bdcodajuicms = t21.bdcodajuicms and t.bdvlraju = t21.bdvlraju  and t21.bdtipolan = 0)
  where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;

  update TOL_VEF_EMP_TMOVREDZAJU1921_TMP t
  set t.BDEDITORDEM1923 = (select first 1 t21.BDEDITORDEM1923 from TMP_VEF_EMP_TMOVAJU1923_PL_TEMP t21 where t.bdsessao = t21.bdsessao and t.bdcodemp = t21.bdcodemp
  and t.bdchave = t21.bdordem1921 and t.bdordem1923 = t21.bdordem1923 and t.bdcodajuicms = t21.bdcodajuicms and t.bdvlraju = t21.bdvlraju  and t21.bdtipolan = 3)
  where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;

--  GRACAR 1921
  insert into VEF_EMP_TMOVAJU1921 (BDCODEMP,BDORDEM1921,BDREFERENCIA,BDCODAJUICMS,BDDESCCOMP,BDCODSUBAPU,BDCODTIPO,BDVALOR)
  select t.BDCODEMP,t.bdeditchave,t.BDREFERENCIA,t.BDCODAJUICMS,t.BDDESCCOMP,t.BDCODSUBAPU,t.BDCODTIPO,Sum(t3.BDVALOR) bdvalor
  from TMP_VEF_EMP_TMOVAJU1921_PL_TEMP t
  left outer join TMP_VEF_EMP_TMOVAJU1923_PL_TEMP t3 on (t.bdsessao = t3.bdsessao and t.bdcodemp = t3.bdcodemp
  and t.bdchave = t3.bdordem1921 and t.bdcodajuicms = t3.bdcodajuicms and t.bdvlraju = t3.bdvlraju )
  where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp
  Group by BDCODEMP,bdeditchave,BDREFERENCIA,BDCODAJUICMS,BDDESCCOMP,BDCODSUBAPU,BDCODTIPO;


  --  GRAVAR TOLLL 1921
  INSERT INTO TOL_VEF_EMP_TMOVAJU1921 (BDCODEMP,BDORDEM1921,BDCODPERIODO,BDREFERENCIA)
  select BDCODEMP,bdeditchave,7,BDREFERENCIA
  from TMP_VEF_EMP_TMOVAJU1921_PL_TEMP t
  where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp
  Group by BDCODEMP,bdeditchave,BDREFERENCIA,BDCODAJUICMS,BDDESCCOMP,BDCODSUBAPU;


  if (UPPER((SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_CONSOLIDA1923') FROM RDB$DATABASE)) = 'TRUE') then
    begin

    ----------entrada normal
    --  GRAVAR 1923
      insert into VEF_EMP_TMOVAJU1923 (BDCODEMP,BDORDEM1921,BDORDEM1923,BDCODTER,BDCODDOCFIS,BDSERIE,BDSUBSERIE,BDNUMDOC,BDDTDOC,BDCODPROD,BDVALOR,BDCHAVENFE,BDCODSUBAPU)
      select BDCODEMP,bdeditchave,BDEDITORDEM1923,BDCODTER,(select BDMODELO1923 from SP_MODELOCORRESPONDENTE1923(BDCODDOCFIS)) BDMODELO,BDSERIE,BDSUBSERIE,BDNUMDOC,BDDTDOC,BDCODPROD,BDVALOR,BDCHAVENFE,BDCODSUBAPU
      from TMP_VEF_EMP_TMOVAJU1923_PL_TEMP t
      where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp and t.bdtipolan = 0;
    
      --ENTRADA 1923
      INSERT INTO TOL_VEF_EMP_TMOVENTAJU1921 (BDCODEMP,BDCHAVE,BDORDEM1921,BDCODPERIODO,BDREFERENCIA,BDORDEM1923)
      SELECT T.BDCODEMP,T.bdchave,t.bdeditchave,7,BDREFERENCIA,t.BDEDITORDEM1923
      FROM TOL_VEF_EMP_TMOVENTAJU1921_TEMP T
      where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;

    -------------- Saída agrupada

      --  GRAVAR 1923
      insert into VEF_EMP_TMOVAJU1923 (BDCODEMP,BDORDEM1921,BDORDEM1923,BDCODTER,BDCODDOCFIS,BDSERIE,BDSUBSERIE,BDNUMDOC,BDDTDOC,BDCHAVENFE,BDCODSUBAPU,BDVALOR)
      select BDCODEMP,bdeditchave,BDEDITORDEM1923,BDCODTER, BDMODELO,BDSERIE,BDSUBSERIE,BDNUMDOC,BDDTDOC,BDCHAVENFE,BDCODSUBAPU,sum(BDVALOR)
      from (
            select BDCODEMP,bdeditchave,BDEDITORDEM1923,BDCODTER,(select BDMODELO1923 from SP_MODELOCORRESPONDENTE1923(BDCODDOCFIS)) BDMODELO,BDSERIE,BDSUBSERIE,BDNUMDOC,BDDTDOC,BDCHAVENFE,BDCODSUBAPU,BDVALOR
      from TMP_VEF_EMP_TMOVAJU1923_PL_TEMP t
      where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp and t.bdtipolan = 1
            )t
      group by BDCODEMP,bdeditchave,BDEDITORDEM1923,BDCODTER,BDMODELO,BDSERIE,BDSUBSERIE,BDNUMDOC,BDDTDOC,BDCHAVENFE,BDCODSUBAPU;

    -- SAIDA 1923
      INSERT INTO TOL_VEF_EMP_TMOVSAIAJU1921 (BDCODEMP,BDCHAVE,BDORDEM1921,BDCODPERIODO,BDREFERENCIA,BDORDEM1923)
      SELECT T.BDCODEMP,t.bdchave,t.bdeditchave,7,BDREFERENCIA,T.BDEDITORDEM1923
      FROM TOL_VEF_EMP_TMOVSAIAJU1921_TEMP T
      where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp
      group by BDCODEMP,bdchave,bdeditchave,BDREFERENCIA,BDEDITORDEM1923;

      -- REDUÇÃO Z AGRUPADA

      -- GRAVAR 1923
      insert into VEF_EMP_TMOVAJU1923 (BDCODEMP,BDORDEM1921,BDORDEM1923,BDCODTER,BDCODDOCFIS,BDSERIE,BDSUBSERIE,BDNUMDOC,BDDTDOC,BDCHAVENFE,BDCODSUBAPU,BDVALOR)
      select BDCODEMP,bdeditchave,BDEDITORDEM1923,BDCODTER, BDMODELO,BDSERIE,BDSUBSERIE,BDNUMDOC,BDDTDOC,BDCHAVENFE,BDCODSUBAPU,sum(BDVALOR)
      from (
            select BDCODEMP,bdeditchave,BDEDITORDEM1923,BDCODTER,(select BDMODELO1923 from SP_MODELOCORRESPONDENTE1923(BDCODDOCFIS)) BDMODELO,BDSERIE,BDSUBSERIE,BDNUMDOC,BDDTDOC,BDCHAVENFE,BDCODSUBAPU,BDVALOR
      from TMP_VEF_EMP_TMOVAJU1923_PL_TEMP t
      where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp and t.bdtipolan = 3
            )t
      group by BDCODEMP,bdeditchave,BDEDITORDEM1923,BDCODTER,BDMODELO,BDSERIE,BDSUBSERIE,BDNUMDOC,BDDTDOC,BDCHAVENFE,BDCODSUBAPU;

      -- REDUÇÃO Z 1923
      INSERT INTO TOL_VEF_EMP_TMOVREDZAJU1921 (BDCODEMP,BDCHAVE,BDORDEM1921,BDCODPERIODO,BDREFERENCIA,BDORDEM1923)
      SELECT T.BDCODEMP,T.bdchave,t.bdeditchave,7,BDREFERENCIA,t.BDEDITORDEM1923
      FROM TOL_VEF_EMP_TMOVREDZAJU1921_TMP T
      where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp
      group by BDCODEMP,bdchave,bdeditchave,BDREFERENCIA,BDEDITORDEM1923;

    end
  else
    begin
    --  GRAVAR 1923
      insert into VEF_EMP_TMOVAJU1923 (BDCODEMP,BDORDEM1921,BDORDEM1923,BDCODTER,BDCODDOCFIS,BDSERIE,BDSUBSERIE,BDNUMDOC,BDDTDOC,BDCODPROD,BDVALOR,BDCHAVENFE,BDCODSUBAPU)
      select BDCODEMP,bdeditchave,BDEDITORDEM1923,BDCODTER,(select BDMODELO1923 from SP_MODELOCORRESPONDENTE1923(BDCODDOCFIS)) BDMODELO,BDSERIE,BDSUBSERIE,BDNUMDOC,BDDTDOC,BDCODPROD,BDVALOR,BDCHAVENFE,BDCODSUBAPU
      from TMP_VEF_EMP_TMOVAJU1923_PL_TEMP t
      where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;
    
--    --  GRAVAR TOLLL 1921
--      INSERT INTO TOL_VEF_EMP_TMOVAJU1921 (BDCODEMP,BDORDEM1921,BDCODPERIODO,BDREFERENCIA)
--      select BDCODEMP,bdeditchave,7,BDREFERENCIA
--      from TMP_VEF_EMP_TMOVAJU1921_PL_TEMP t
--      where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp
--      Group by BDCODEMP,bdeditchave,BDREFERENCIA,BDCODAJUICMS,BDDESCCOMP,BDCODSUBAPU;
    
    -- SAIDA 1923
      INSERT INTO TOL_VEF_EMP_TMOVSAIAJU1921 (BDCODEMP,BDCHAVE,BDORDEM1921,BDCODPERIODO,BDREFERENCIA,BDORDEM1923)
      SELECT T.BDCODEMP,t.bdchave,t.bdeditchave,7,BDREFERENCIA,T.BDEDITORDEM1923
      FROM TOL_VEF_EMP_TMOVSAIAJU1921_TEMP T
      where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;
    
      --ENTRADA 1923
      INSERT INTO TOL_VEF_EMP_TMOVENTAJU1921 (BDCODEMP,BDCHAVE,BDORDEM1921,BDCODPERIODO,BDREFERENCIA,BDORDEM1923)
      SELECT T.BDCODEMP,T.bdchave,t.bdeditchave,7,BDREFERENCIA,t.BDEDITORDEM1923
      FROM TOL_VEF_EMP_TMOVENTAJU1921_TEMP T
      where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;

      -- REDUÇÃO Z 1923
      INSERT INTO TOL_VEF_EMP_TMOVREDZAJU1921 (BDCODEMP,BDCHAVE,BDORDEM1921,BDCODPERIODO,BDREFERENCIA,BDORDEM1923)
      SELECT T.BDCODEMP,T.bdchave,t.bdeditchave,7,BDREFERENCIA,t.BDEDITORDEM1923
      FROM TOL_VEF_EMP_TMOVREDZAJU1921_TMP T
      where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;
    end

  DELETE FROM TMP_VEF_EMP_TMOVAJU1921_PL_TEMP T where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;
  DELETE FROM TOL_VEF_EMP_TMOVSAIAJU1921_TEMP T where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;
  DELETE FROM TOL_VEF_EMP_TMOVENTAJU1921_TEMP T where t.bdsessao = :prsessao and t.bdcodemp = :prcodemp;
  DELETE FROM TOL_VEF_EMP_TMOVREDZAJU1921_TMP T where t.BDSESSAO = :PRSESSAO and t.BDCODEMP = :PRCODEMP;


END^


CREATE OR ALTER trigger tol_vef_emp_tmovaju1921_ad0 for tol_vef_emp_tmovaju1921
active after delete position 0
AS
begin
  delete from VEF_EMP_TMOVAJU1921 where bdcodemp = old.bdcodemp and bdordem1921 = old.bdordem1921;
end^

CREATE OR ALTER trigger tol_vef_emp_tmovajue220_ad0 for tol_vef_emp_tmovajue220
active after delete position 0
AS
begin
  delete from VEF_EMP_TAJUICMSSTE220 where bdcodemp = old.bdcodemp and BDORDEME111220 = old.BDORDEME111220;
end^

CREATE OR ALTER trigger tol_vef_emp_tmovajue250_ad0 for tol_vef_emp_tmovajue250
active after delete position 0
AS
begin
    delete from VEF_EMP_TAJUICMSSTE250 where bdcodemp = old.bdcodemp and BDORDEME116250 = old.BDORDEME116250;
end^

CREATE OR ALTER trigger tmp_vef_emp_taju1921_pl_bu0 for tmp_vef_emp_tmovaju1921_pl_temp
active before update position 0
AS
declare variable WCOMP VARCHAR(200);
begin
  WCOMP = SUBSTRING(old.BDCODAJUICMS||OLD.bddesccomp FROM 1 FOR 200);
  IF ((COALESCE(OLD.BDEDITCHAVE, 0) = 0) AND (NEW.BDEDITCHAVE > 0)) THEN
    NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - GETORDEMSEQUENCIAL_PESQ(WCOMP))+1;
end^

CREATE OR ALTER trigger vef_emp_tmovaju1923_ad0 for vef_emp_tmovaju1923
active after delete position 0
AS
begin
  /* Trigger text */
  delete from TOL_VEF_EMP_TMOVENTAJU1921 where bdcodemp = old.bdcodemp and bdordem1921 = old.bdordem1921 AND BDORDEM1923 = OLD.BDORDEM1923;
  delete from TOL_VEF_EMP_TMOVSAIAJU1921 where bdcodemp = old.bdcodemp and bdordem1921 = old.bdordem1921 AND BDORDEM1923 = OLD.BDORDEM1923;
end^

CREATE OR ALTER trigger TMP_VEF_EMP_TMOVA1923_PL_T_BU0 for TMP_VEF_EMP_TMOVAJU1923_PL_TEMP
active before update position 0
AS
declare variable wPesq varchar(200);
declare variable wConsolida1923 dm_boolean;
begin

  if (wconsolida1923 is null) then
    wconsolida1923 = (SELECT RDB$GET_CONTEXT('USER_SESSION', 'W_CONSOLIDA1923') FROM RDB$DATABASE);

  if ((UPPER(wconsolida1923) = 'TRUE') and ((old.bdtipolan = 1) or (old.bdtipolan = 3)) )then
    begin
      wPesq = Substring(old.bdvlraju||'|'||old.bdcodsubapu||'|'||old.bdnumdoc||'|'||old.bdserie||'|'||old.bddtdoc||'|'||old.bdcodajuicms from 1 for 200);
      NEW.BDEDITORDEM1923 =  GETORDEMSEQUENCIAL_pesq(wPesq);
    end
  else
    begin
      wPesq = OLD.bdeditchave;
      NEW.BDEDITORDEM1923 =  GETORDEMSEQUENCIAL_str(wPesq, old.bdCODEMP);
    end
end^

CREATE OR ALTER trigger tol_vef_emp_tmovaju1926_ad0 for tol_vef_emp_tmovaju1926
active after delete position 0
AS
begin
  DELETE FROM VEF_EMP_TMOVAJU1926 WHERE BDCODEMP = OLD.BDCODEMP AND BDORDEM1926 = OLD.BDORDEM1926 AND BDCODSUBAPU = OLD.BDCODSUBAPU;
end^

create or alter procedure VCT_USUARIO_RESP_TAREFAS (
    PRCODSER integer,
    PRCODOBR integer,
    PRCODIMP integer)
as
begin
  -- Gilberto - 14/11/2024 - #212394 - Não usa mais essas tabelas nas tarefas
end^


CREATE OR ALTER TRIGGER TEMPRESAS_SEQ_DED_BI0 FOR TEMPRESAS_SEQ_DED
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;
begin
  if (coalesce(new.bdcodigo, 0) = 0) then
     begin
       select coalesce(max(BDCODIGO) + 1, 1) from TEMPRESAS_SEQ_DED where BDCODEMP = new.bdcodemp into :vcod;
       new.bdcodigo = :vcod;
     end
end
^

CREATE OR ALTER PROCEDURE SP_MUDA_TIPO_COLCON(
  premp INTEGER,
  prcol INTEGER,
  prcontrcol INTEGER)
AS
BEGIN
  update VRHF_EMP_TCOLCON_BANCO set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRHF_EMP_TCOLCON_CALC set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRHF_EMP_TCOLCON_FGTSGPS set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRHF_EMP_TCOL_ANO set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRHF_EMP_TCOL_CALC set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRHF_EMP_TCOL_HIST set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRHF_EMP_TCON_VINC set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOLCON set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOLCON_CAD set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOLCON_CALCDIA set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOLCON_DIA set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOLCON_DOC set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOLCON_DOCREF set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOLCON_FIS set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOLCON_IMG set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOLCON_PARTIDA set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOLCON_REF set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOLCON_VINC set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOL_ADM set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOL_ADMREF set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOL_DOC set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOL_FIS set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOL_HIST set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOL_PARENT set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOL_VINC set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCOL_VINCDIA set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;
  update VRH_EMP_TCON_DOC set BDCONTRCOL = :prcontrcol where BDCODEMP = :premp and BDCODCOL = :prcol;

END^

CREATE OR ALTER procedure SP_VFIN_GERARCONFIGIMP
as
declare variable VCODESC integer;
declare variable VCODCLI integer;
declare variable VCHAVEFATURA integer;
declare variable VCODOBRSER integer;
declare variable VPERINSS numeric(15,4);
declare variable VUSARPERISS integer;
declare variable VRETIR varchar(5);
declare variable VRETCSLL varchar(5);
declare variable VRETCOF varchar(5);
declare variable VRETPIS varchar(5);
declare variable VRETIMP integer;
declare variable VDESTIR varchar(5);
declare variable VDESTCSLL varchar(5);
declare variable VDESTPIS varchar(5);
declare variable VDESTCOF varchar(5);
declare variable VCALCINSS varchar(5);
declare variable VPERCOF numeric(15,4);
declare variable VPERPIS numeric(15,4);
declare variable VPERCSLL numeric(15,4);
declare variable VPERIRRF numeric(15,4);
declare variable VDEDISS varchar(5);
declare variable VPERISS numeric(15,4);
declare variable VCODESCNEW integer;
declare variable VCODCLINEW integer;
declare variable VREFCONFIGNEW integer;
declare variable VDESTRETINSSNEW integer;
declare variable VPERINSSNEW numeric(15,4);
declare variable VDESTRETIRRFNEW integer;
declare variable VPERIRRFNEW numeric(15,4);
declare variable VDESTRETCSLLNEW integer;
declare variable VPERCSLLNEW numeric(15,4);
declare variable VDESTRETPISNEW integer;
declare variable VPERPISNEW numeric(15,4);
declare variable VDESTRETCOFINSNEW integer;
declare variable VPERCOFINSNEW numeric(15,4);
declare variable VDESTIBSESTADUALNEW integer;
declare variable VDESTIBSMUNICIPALNEW integer;
declare variable VDESTCBSNEW integer;
declare variable VDESTRETISSNEW integer;
begin
  execute procedure sp_seta_competencia(cast(substring(current_date from 1 for 4)||substring(current_date from 6 for 2) as integer));
  delete from VFIN_ESC_TCONFIGIMPOSTOS;

  for
  select res.bdcodesc, res.bdcodcli, res.bdchavefatura, serfat.bdcodobrser
  from (
  select SERFAT.BDCODESC, SERFAT.BDCODCLI, max(SERFAT.BDCHAVEFATURA) bdchavefatura
  from VFIN_ESC_TSERVICOFATURADO SERFAT
  inner join VFIN_ESC_TFATURA FAT on (FAT.BDCODESC = SERFAT.BDCODESC and FAT.BDCODCLI = SERFAT.BDCODCLI and FAT.BDCHAVEFATURA = SERFAT.BDCHAVEFATURA)
  where FAT.BDREFFAT <= extract(year from current_date) * 100 + extract(month from current_date)
  group by bdcodesc, bdcodcli
  order by SERFAT.BDCODESC, SERFAT.BDCODCLI
  ) res
  inner join VFIN_ESC_TSERVICOFATURADO SERFAT on (serfat.bdcodcli = res.bdcodcli and serfat.bdcodesc = res.bdcodesc and serfat.bdchavefatura = res.bdchavefatura)
  where serfat.bdvlrtotser = (select max(bdvlrtotser) from VFIN_ESC_TSERVICOFATURADO aux where aux.bdcodcli = serfat.bdcodcli and
  aux.bdcodesc = serfat.bdcodesc and aux.bdchavefatura = serfat.bdchavefatura)
  into :vCodEsc, :vCodCli, :vChaveFatura, :vCodObrSer
  do
  begin
    vCodEscNew = 0;
    vCodCliNew = 0;
    vRefConfigNew = 0;
    vDestRetInssNew = 0;
    vPerInssNew = 0;
    vDestRetIrrfNew = 0;
    vPerIrrfNew = 0;
    vDestRetCsllNew = 0;
    vPerCsllNew = 0;
    vDestRetPisNew = 0;
    vPerPisNew = 0;
    vDestRetCofinsNew = 0;
    vPerCofinsNew = 0;
    vDestIbsEstadualNew = 1;
    vDestIbsMunicipalNew = 1;
    vDestCbsNew = 1;
    vDestRetIssNew = 0;

    select BDPERINSS, BDUSARPERISS, BDRETIR, BDRETCSLL, BDRETCOF, BDRETPIS, BDRETIMP, BDDESTIR, BDDESTCSLL, BDDESTPIS, BDDESTCOF
    from VW_VFIN_BASE_TCLIIMPOSTO
    where bdcodcli = :vCodCli
    into
    :vPerInss,
    :vUsarPerIss,
    :vRetIr,
    :vRetCsll,
    :vRetCof,
    :vRetPis,
    :vRetImp,
    :vDestIr,
    :vDestCsll,
    :vDestPis,
    :vDestCof;

    :vCodEscNew = :vCodEsc;
    :vCodCliNew = :vCodCli;

    SELECT EXTRACT(YEAR FROM DATEADD(-1 MONTH TO current_date)) * 100 + EXTRACT(MONTH FROM DATEADD(-1 MONTH TO current_date)) AS REFERENCIA_ANTERIOR FROM RDB$DATABASE into :vRefConfigNew;

    select bdcalcinss, bdperirrf, bdpercof, bdperpis, bdpercsll, bddediss, bdperiss
    from VCT_BASE_SERVICO
    where bdcodobrser = :vCodObrSer into :vCalcInss, :vPerIrrf, :vPerCof, :vPerPis, :vPerCsll, :vDedIss, :vPerIss;

    if (:vPerInss > 0) then -- INSS
       begin
         if (Upper(:vCalcInss) = 'TRUE') then
            begin
              :vPerInssNew = :vPerInss;
              :vDestRetInssNew = 2;
            end
       end

    if (:vUsarPerIss = 0) then -- Serviço
       begin
         if ((Upper(:vDedIss) = 'TRUE') and (:vPerIss > 0)) then
            begin
              :vDestRetIssNew = 2;
            end
         else
           if (:vPerIss > 0) then
              begin
                :vDestRetIssNew = 1;
              end
           else
             begin
               :vDestRetIssNew = 0;
             end
       end
    else
      if (:vUsarPerIss = 1) then -- Cidade
         begin
           select vinc.bddediss, vinc.bdperiss
           from TESCRITORIO esc
           inner join TCIDADE cid on (cid.bdcodcid = esc.bdcodcid)
           inner join VW_VEF_BASE_TVINCULOISS vinc on (vinc.bdcodcid = cid.bdcodcid)
           where esc.bdcodesc = :vCodEsc
           into :vDedIss, :vPerIss;

           if ((Upper(:vDedIss) = 'TRUE') and (:vPerIss > 0)) then
              begin
                :vDestRetIssNew = 2;
              end
           else
             if (:vPerIss > 0) then
                begin
                  :vDestRetIssNew = 1;
                end
             else
               begin
                 :vDestRetIssNew = 0;
               end
         end
      else
        if (:vUsarPerIss = 2) then -- Atividade municipal
           begin
             select max(atvm.bddediss) bddediss, max(atvm.bdaliqatvm) bdaliqatvm
             from VW_VFIN_ESC_TSERVICOGEST_ATUAL sg
             left outer join TATVMUNICIPAL atvm on (atvm.bdcodcid = sg.bdcodcid and atvm.bdcodatvm = atvm.bdcodatvm)
             where sg.bdcodobrser = :vCodObrSer
             and sg.bdcodesc = :vCodEsc
             into :vDedIss, :vPerIss;

              if ((Upper(:vDedIss) = 'TRUE') and (:vPerIss > 0)) then
                 begin
                   :vDestRetIssNew = 2;
                 end
              else
                if (:vPerIss > 0) then
                   begin
                     :vDestRetIssNew = 1;
                   end
                else
                  begin
                    :vDestRetIssNew = 0;
                  end
           end

    if (:vRetImp = 1) then -- Cliente
       begin
         if (Upper(:vRetIr) = 'TRUE') then -- IR
            begin
              :vPerIrrfNew = :vPerIrrf;
              :vDestRetIrrfNew = 2;
            end
         else
           if (Upper(:vDestIr) = 'TRUE') then
              begin
                :vPerIrrfNew = :vPerIrrf;
                :vDestRetIrrfNew = 1;
              end

         if (Upper(:vRetPis) = 'TRUE') then -- PIS
            begin
              :vPerPisNew = :vPerPis;
              :vDestRetPisNew = 2;
            end
         else
           if (Upper(:vDestPis) = 'TRUE') then
              begin
                :vPerPisNew = :vPerPis;
                :vDestRetPisNew = 1;
              end

         if (Upper(:vRetCof) = 'TRUE') then -- COFINS
            begin
              :vPerCofinsNew = :vPerCof;
              :vDestRetCofinsNew = 2;
            end
         else
           if (Upper(:vDestCof) = 'TRUE') then
              begin
                :vPerCofinsNew = :vPerCof;
                :vDestRetCofinsNew = 1;
              end

         if (Upper(:vRetCsll) = 'TRUE') then -- CSLL
            begin
              :vPerCsllNew = :vPerCsll;
              :vDestRetCsllNew = 2;
            end
         else
           if (Upper(:vDestCsll) = 'TRUE') then
              begin
                :vPerCsllNew = :vPerCsll;
                :vDestRetCsllNew = 1;
              end
       end
    else
      if (:vRetImp = 2) then -- Escritório
         begin
           select BDRETIR, BDRETCSLL, BDRETCOF, BDRETPIS, BDDESTIR, BDDESTCSLL, BDDESTPIS, BDDESTCOF
           from VFIN_BASE_TESCIMPOSTO
           where bdcodesc = :vCodEsc
           into
           :vRetIr,
           :vRetCsll,
           :vRetCof,
           :vRetPis,
           :vDestIr,
           :vDestCsll,
           :vDestPis,
           :vDestCof;

           if (Upper(:vRetIr) = 'TRUE') then -- IR
              begin
                :vPerIrrfNew = :vPerIrrf;
                :vDestRetIrrfNew = 2;
              end
           else
             if (Upper(:vDestIr) = 'TRUE') then
                begin
                  :vPerIrrfNew = :vPerIrrf;
                  :vDestRetIrrfNew = 1;
                end

           if (Upper(:vRetPis) = 'TRUE') then -- PIS
              begin
                :vPerPisNew = :vPerPis;
                :vDestRetPisNew = 2;
              end
           else
             if (Upper(:vDestPis) = 'TRUE') then
                begin
                  :vPerPisNew = :vPerPis;
                  :vDestRetPisNew = 1;
                end

           if (Upper(:vRetCof) = 'TRUE') then -- COFINS
              begin
                :vPerCofinsNew = :vPerCof;
                :vDestRetCofinsNew = 2;
              end
           else
             if (Upper(:vDestCof) = 'TRUE') then
                begin
                  :vPerCofinsNew = :vPerCof;
                  :vDestRetCofinsNew = 1;
                end

           if (Upper(:vRetCsll) = 'TRUE') then -- CSLL
              begin
                :vPerCsllNew = :vPerCsll;
                :vDestRetCsllNew = 2;
              end
           else
             if (Upper(:vDestCsll) = 'TRUE') then
                begin
                  :vPerCsllNew = :vPerCsll;
                  :vDestRetCsllNew = 1;
                end
           end

    update or insert into VFIN_ESC_TCONFIGIMPOSTOS (BDCODESC, BDCODCLI, BDREFCONFIG, BDDESTRETINSS, BDPERINSS, BDDESTRETIRRF, BDPERIRRF, BDDESTRETCSLL,
    BDPERCSLL, BDDESTRETPIS, BDPERPIS, BDDESTRETCOFINS, BDPERCOFINS, BDDESTIBSESTADUAL, BDDESTIBSMUNICIPAL, BDDESTCBS, BDDESTRETISS)
    values (:vCodEscNew, :vCodCliNew, :vRefConfigNew, :vDestRetInssNew, :vPerInssNew, :vDestRetIrrfNew, :vPerIrrfNew, :vDestRetCsllNew, :vPerCsllNew, :vDestRetPisNew,
    :vPerPisNew, :vDestRetCofinsNew, :vPerCofinsNew, :vDestIbsEstadualNew, :vDestIbsMunicipalNew, :vDestCbsNew, :vDestRetIssNew)
    matching (bdcodesc, bdcodcli, bdrefconfig);
  end
end^

CREATE OR ALTER procedure SP_VFIN_GETSQL_COBRAR_SOBRE (
    BDCODCOBSERV integer,
    BDCODEMP integer,
    BDREFATUAL integer)
returns (
    WSQLAUX varchar(3000))
as
declare variable WDATAINI date;
declare variable WDATAFIN date;
declare variable WFILIAIS varchar(500);
begin
  wsqlaux = '';
  if (BDCODCOBSERV = 3) then--Admitidos COLABORADOR
     begin
                 wsqlaux = wsqlaux||'VRH_EMP_TCOLCON COL ';
     wsqlaux = wsqlaux||'where substring(cast(COL.BDDATAADMCOL as varchar(10)) from 1 for 4) || substring(cast(COL.BDDATAADMCOL as varchar(10)) from 6 for 2) = '||bdrefatual||' and ';
                 wsqlaux = wsqlaux||'coalesce(COL.BDCONTRCOL, 0) = 0 and ';
     wsqlaux = wsqlaux||'COL.BDCODEMP = '||bdcodemp;--wbdcodcli;
                end
            else
    if (BDCODCOBSERV = 4) then--Demitidos COLABORADOR
                begin
                  wsqlaux = wsqlaux||'VRH_EMP_TRESCISAO RESC ';
                  wsqlaux = wsqlaux||'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = RESC.BDCODEMP and COL.BDCODCOL = RESC.BDCODCOL) ';
          wsqlaux = wsqlaux||'where RESC.BDREFRESCISAO = '||bdrefatual;
                  wsqlaux = wsqlaux||' and COALESCE(COL.BDCONTRCOL, 0) = 0';
          wsqlaux = wsqlaux||'and RESC.BDCODEMP = '||bdcodemp;--wbdcodcli;
                end
            else
    if (BDCODCOBSERV = 5) then--Ativos COLABORADOR
               begin
                wsqlaux = wsqlaux||'VRH_EMP_TCOLCON C ';
                wsqlaux = wsqlaux||'left outer join VRH_EMP_TRESCISAO R on (R.BDCODEMP = C.BDCODEMP and R.BDCODCOL = C.BDCODCOL) ';
                wsqlaux = wsqlaux||'where coalesce(C.bdcontrcol, 0) = 0';
        wsqlaux = wsqlaux||'and C.BDCODEMP = '||bdcodemp||' and ';--wbdcodcli||' and ';
        wsqlaux = wsqlaux||'(substring(cast(c.bddataadmcol as varchar(10)) from 1 for 4)||substring(cast(c.bddataadmcol as varchar(10)) from 6 for 2)) <= '||bdrefatual||' and ';
        wsqlaux = wsqlaux||'((R.BDDATARESCISAO is null) or (substring(cast(R.BDDATARESCISAO as varchar(10)) from 1 for 4)||substring(cast(R.BDDATARESCISAO as varchar(10)) from 6 for 2)) >= '||bdrefatual||')';
               end
            else
    if (BDCODCOBSERV = 7) then--Admitidos contribuinte
                begin
                 wsqlaux = wsqlaux||'VRH_EMP_TCOLCON COL ';
         wsqlaux = wsqlaux||'where substring(cast(COL.BDDATAADMCOL as varchar(10)) from 1 for 4) || substring(cast(COL.BDDATAADMCOL as varchar(10)) from 6 for 2) = '||bdrefatual||' and ';
                 wsqlaux = wsqlaux||'coalesce(COL.BDCONTRCOL, 0) = 1 and ';
         wsqlaux = wsqlaux||'COL.BDCODEMP = '||bdcodemp;--wbdcodcli;
                end
            else
    if (BDCODCOBSERV = 8) then--Demitidos contribuinte
               begin
                  wsqlaux = wsqlaux||'VRH_EMP_TRESCISAO RESC ';
                  wsqlaux = wsqlaux||'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = RESC.BDCODEMP and COL.BDCODCOL = RESC.BDCODCOL) ';
          wsqlaux = wsqlaux||'where RESC.BDREFRESCISAO = '||bdrefatual;
                  wsqlaux = wsqlaux||' and COALESCE(COL.BDCONTRCOL, 0) = 1';
          wsqlaux = wsqlaux||'and RESC.BDCODEMP = '||bdcodemp;--wbdcodcli;
               end
            else
    if (BDCODCOBSERV = 9) then--Ativos contribuintes
               begin
                 wsqlaux = wsqlaux||'VRH_EMP_TCOLCON C ';
                 wsqlaux = wsqlaux||'left outer join VRH_EMP_TRESCISAO R on (R.BDCODEMP = C.BDCODEMP and R.BDCODCOL = C.BDCODCOL) ';
                 wsqlaux = wsqlaux||'where coalesce(C.bdcontrcol, 0) = 1';
         wsqlaux = wsqlaux||'and C.BDCODEMP = '||bdcodemp||' and ';--wbdcodcli||' and ';
         wsqlaux = wsqlaux||'(substring(cast(c.bddataadmcol as varchar(10)) from 1 for 4)||substring(cast(c.bddataadmcol as varchar(10)) from 6 for 2)) <= '||bdrefatual||' and ';
         wsqlaux = wsqlaux||'((R.BDDATARESCISAO is null) or (substring(cast(R.BDDATARESCISAO as varchar(10)) from 1 for 4)||substring(cast(R.BDDATARESCISAO as varchar(10)) from 6 for 2)) >= '||bdrefatual||')';
               end
            else
    if (BDCODCOBSERV = 11) then--Folha normal
               begin
                 wsqlaux = wsqlaux||'(select BDCODEMP, BDCODCOL, BDREFFN, cast(null as integer) BDORDEM ';
                 wsqlaux = wsqlaux||'from VRHF_EMP_TFOLHANORMAL ';
         wsqlaux = wsqlaux||'where BDREFFN = '||bdrefatual;
                 wsqlaux = wsqlaux||' union all ';
                 wsqlaux = wsqlaux||'select BDCODEMP, BDCODCOL, BDREFTOMADOR as BDREFFN, max(BDORDEM) ';
                 wsqlaux = wsqlaux||'from VRHF_EMP_TFOLHATOMADOR ';
         wsqlaux = wsqlaux||'where BDREFTOMADOR = '||bdrefatual;
                 wsqlaux = wsqlaux||' group by BDCODEMP, BDCODCOL, BDREFTOMADOR';
         if (BDCODCOBSERV <> 11) then
                 begin
                   wsqlaux = wsqlaux||'union all ';
                   wsqlaux = wsqlaux||'select BDCODEMP, BDCODCOL, BDREFFN, cast(null as integer) BDORDEM ';
                   wsqlaux = wsqlaux||'from VRHF_EMP_TFOLHAINT ';
           wsqlaux = wsqlaux||'where BDREFFN = '||bdrefatual;
                   wsqlaux = wsqlaux||' union all ';
                   wsqlaux = wsqlaux||'select BDCODEMP, BDCODCOL, BDREFTOMADOR as BDREFFN, max(BDORDEM) ';
                   wsqlaux = wsqlaux||'from VRHF_EMP_TFOLHATOMINT ';
           wsqlaux = wsqlaux||'where BDREFTOMADOR = '||bdrefatual;
                   wsqlaux = wsqlaux||' group by BDCODEMP, BDCODCOL, BDREFTOMADOR';
                 end
                 wsqlaux = wsqlaux||') FN ';
                 wsqlaux = wsqlaux||'left outer join VRH_EMP_TCOLCON C on (C.BDCODEMP = FN.BDCODEMP and C.BDCODCOL = FN.BDCODCOL) ';
                 wsqlaux = wsqlaux||'where coalesce(C.BDCONTRCOL, 0) = 0 and ';
         wsqlaux = wsqlaux||'FN.BDCODEMP in ('||bdcodemp||') ';--wbdcodcli||') ';
                 wsqlaux = wsqlaux||'group by FN.BDCODEMP, BDREFFN';
               end
            else
    if (BDCODCOBSERV = 12) then--Folha pro-labore
               begin
                 wsqlaux = wsqlaux||'(select BDCODEMP, BDCODCOL, BDREFFN ';
                 wsqlaux = wsqlaux||'from VRHF_EMP_TFOLHANORMAL ';
         wsqlaux = wsqlaux||'where BDREFFN = '||bdrefatual;
                 wsqlaux = wsqlaux||' union all ';
                 wsqlaux = wsqlaux||'select BDCODEMP, BDCODCOL, BDREFTOMADOR ';
                 wsqlaux = wsqlaux||'from VRHF_EMP_TFOLHATOMADOR ';
         wsqlaux = wsqlaux||'where BDREFTOMADOR = '||bdrefatual||') FN ';
                 wsqlaux = wsqlaux||'left outer join VRH_EMP_TCOLCON C on (C.BDCODEMP = FN.BDCODEMP and C.BDCODCOL = FN.BDCODCOL) ';
         wsqlaux = wsqlaux||'where coalesce(C.BDCONTRCOL, 0) = 1 and FN.BDCODEMP = '||bdcodemp;--wbdcodcli;
                 wsqlaux = wsqlaux||' group by FN.BDCODEMP, BDREFFN';
               end
            else
    if (BDCODCOBSERV = 13) then--Folha Estagiarios
               begin
                 wsqlaux = wsqlaux||'(select BDCODEMP, BDCODCOL, BDREFFN ';
                 wsqlaux = wsqlaux||'from VRHF_EMP_TFOLHANORMAL ';
         wsqlaux = wsqlaux||'where BDREFFN = '||bdrefatual;
                 wsqlaux = wsqlaux||' union all ';
                 wsqlaux = wsqlaux||'select BDCODEMP, BDCODCOL, BDREFTOMADOR ';
                 wsqlaux = wsqlaux||'from VRHF_EMP_TFOLHATOMADOR ';
         wsqlaux = wsqlaux||'where BDREFTOMADOR = '||bdrefatual||') FN ';
                 wsqlaux = wsqlaux||'left outer join VW_VRH_EMP_TCOLCON_VINC C on (C.BDCODEMP = FN.BDCODEMP and C.BDCODCOL = FN.BDCODCOL) ';
                 wsqlaux = wsqlaux||'left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = C.BDCODCLA) ';
                 wsqlaux = wsqlaux||'where CLA.BDGRUPOCLA = 5 and ';
         wsqlaux = wsqlaux||'FN.BDCODEMP = '||bdcodemp;--wbdcodcli;
                 wsqlaux = wsqlaux||' group by FN.BDCODEMP, BDREFFN';
               end
            else
    if (BDCODCOBSERV = 14) then--Recisões
               begin
                 wsqlaux = wsqlaux||'(select BDCODEMP, BDCODCOL, BDREFFN ';
                 wsqlaux = wsqlaux||'from VRHF_EMP_TFOLHANORMAL ';
         wsqlaux = wsqlaux||'where BDREFFN = '||bdrefatual;
                 wsqlaux = wsqlaux||' union all ';
                 wsqlaux = wsqlaux||'select BDCODEMP, BDCODCOL, BDREFTOMADOR ';
                 wsqlaux = wsqlaux||'from VRHF_EMP_TFOLHATOMADOR ';
         wsqlaux = wsqlaux||'where BDREFTOMADOR = '||bdrefatual||') FN ';
                 wsqlaux = wsqlaux||'left outer join VRH_EMP_TCOLCON C on (C.BDCODEMP = FN.BDCODEMP and C.BDCODCOL = FN.BDCODCOL) ';
                 wsqlaux = wsqlaux||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FN.BDCODEMP and RESC.BDCODCOL = FN.BDCODCOL) ';
                 wsqlaux = wsqlaux||'where coalesce(C.BDCONTRCOL, 0) = 0 and ';
         wsqlaux = wsqlaux||'RESC.BDREFRESCISAO = '||bdrefatual||' and ';
         wsqlaux = wsqlaux||'FN.BDCODEMP = '||bdcodemp;--wbdcodcli;
                 wsqlaux = wsqlaux||' group by FN.BDCODEMP, RESC.BDREFRESCISAO';
               end
            else
    if (BDCODCOBSERV = 15) then--Calculos de autonomo
               begin
                 wsqlaux = wsqlaux||'VRHF_BASE_CALC_TERC ';
         wsqlaux = wsqlaux||'where BDREFINSSSERV = '||bdrefatual||' and ';
         wsqlaux = wsqlaux||'BDCODEMP = '||bdcodemp;--wbdcodcli;
               end
            else
    if (BDCODCOBSERV = 16) then--Ferias coletivas
               begin
                 wsqlaux = wsqlaux||'VRH_EMP_TFERIAS ';
         wsqlaux = wsqlaux||'where substring(cast(BDDATAPAGFE as varchar(10)) from 1 for 4) || substring(cast(BDDATAPAGFE as varchar(10)) from 6 for 2) = '||bdrefatual||' and ';
                 wsqlaux = wsqlaux||'upper(coalesce(BDCOLETIVASFE, '||'''FALSE'''||')) = '||'''TRUE'''||' and ';
         wsqlaux = wsqlaux||'BDCODEMP = '||bdcodemp;--wbdcodcli;
               end
            else
    if (BDCODCOBSERV = 17) then--Ferias individual
               begin
                 wsqlaux = wsqlaux||'VRH_EMP_TFERIAS ';
         wsqlaux = wsqlaux||'where substring(cast(BDDATAPAGFE as varchar(10)) from 1 for 4) || substring(cast(BDDATAPAGFE as varchar(10)) from 6 for 2) = '||bdrefatual||' and ';
                 wsqlaux = wsqlaux||'upper(coalesce(BDCOLETIVASFE, '||'''FALSE'''||')) = '||'''FALSE'''||' and ';
         wsqlaux = wsqlaux||'BDCODEMP = '||bdcodemp;--wbdcodcli;
               end
            else
    if (BDCODCOBSERV = 18) then--Adiantamento salarial
               begin
                 wsqlaux = wsqlaux||'VRHF_EMP_TADSAL ';
         wsqlaux = wsqlaux||'where substring(cast(BDDATAAD as varchar(10)) from 1 for 4) || substring(cast(BDDATAAD as varchar(10)) from 6 for 2) = '||bdrefatual||' and ';
         wsqlaux = wsqlaux||'BDCODEMP = '||bdcodemp;--wbdcodcli;
               end
            else
    if (BDCODCOBSERV = 19) then--Folha Complementar
               begin
                 wsqlaux = wsqlaux||'(select BDCODEMP, BDCODCOL, BDREFCOMP ';
                 wsqlaux = wsqlaux||'from VRHF_EMP_TFOLHACOMP ';
         wsqlaux = wsqlaux||'where BDREFCOMP = '||bdrefatual;
                 wsqlaux = wsqlaux||' union all ';
                 wsqlaux = wsqlaux||'select BDCODEMP, BDCODCOL, BDREFCOMP ';
                 wsqlaux = wsqlaux||'from VRHF_EMP_TFOLTOMCOMP ';
         wsqlaux = wsqlaux||'where BDREFCOMP = '||bdrefatual||') FN ';
                 wsqlaux = wsqlaux||'left outer join VRH_EMP_TCOLCON C on (C.BDCODEMP = FN.BDCODEMP and C.BDCODCOL = FN.BDCODCOL) ';
                 wsqlaux = wsqlaux||'where coalesce(C.BDCONTRCOL, 0) = 0 and ';
         wsqlaux = wsqlaux||'FN.BDCODEMP  = '||bdcodemp;--wbdcodcli;
                 wsqlaux = wsqlaux||' group by FN.BDCODEMP, BDREFCOMP';
               end
            else
    if (BDCODCOBSERV = 20) then--Calculo PLR
               begin
                 wsqlaux = wsqlaux||'(select FA.BDCODEMP, FA.BDCODCOL, FA.BDDATAFA ';
                 wsqlaux = wsqlaux||'from VRHF_EMP_TFOLHAAVULSA FA ';
                 wsqlaux = wsqlaux||'join VRH_BASE_TTIPOCALCAVUL TCA on (TCA.BDCODTCA = FA.BDCODTCA) ';
         wsqlaux = wsqlaux||'where substring(cast(FA.BDDATAFA as varchar(10)) from 1 for 4) || substring(cast(FA.BDDATAFA as varchar(10)) from 6 for 2) = '||bdrefatual||' and ';
                 wsqlaux = wsqlaux||'TCA.BDCODCTP = 7) FN ';
         wsqlaux = wsqlaux||'where FN.BDCODEMP = '||bdcodemp;--wbdcodcli;
                 wsqlaux = wsqlaux||' group by FN.BDCODEMP, BDREF';
               end
            else
    if (BDCODCOBSERV = 21) then--Adiantamento 13° Salario
               begin
                 wsqlaux = wsqlaux||'VRHF_EMP_TA13SAL ';
         wsqlaux = wsqlaux||'where BDREFA13 = '||bdrefatual||' and ';
         wsqlaux = wsqlaux||'BDCODEMP = '||bdcodemp;--wbdcodcli;
               end
            else
    if (BDCODCOBSERV = 22) then--Calculo 13° salario
               begin
                 wsqlaux = wsqlaux||'VRHF_EMP_T13SAL ';
         wsqlaux = wsqlaux||'where BDREF13 = '||bdrefatual||' and ';
         wsqlaux = wsqlaux||'BDCODEMP = '||bdcodemp;--wbdcodcli;
               end
            else
    if (BDCODCOBSERV = 23) then--Complemento 13° Salario
               begin
                 wsqlaux = wsqlaux||'VRHF_EMP_TC13SAL ';
         wsqlaux = wsqlaux||'where BDREFC13 = '||bdrefatual||' and ';
                 wsqlaux = wsqlaux||'upper(coalesce(BDPAGOFNC13, '||'''FALSE'''||')) = '||'''FALSE'''||' and ';
         wsqlaux = wsqlaux||'BDCODEMP = '||bdcodemp;--wbdcodcli;
               end
            else
    if (BDCODCOBSERV = 24) then--Ativos Normais
               begin
                 wsqlaux = wsqlaux||'VRH_EMP_TCOLCON C ';
                 wsqlaux = wsqlaux||'left outer join VRH_EMP_TRESCISAO R on (R.BDCODEMP = C.BDCODEMP and R.BDCODCOL = C.BDCODCOL) ';
                 wsqlaux = wsqlaux||'left outer join VW_VRH_EMP_TCOLCON_VINC COLVINC on (COLVINC.BDCODEMP = C.BDCODEMP and COLVINC.BDCODCOL = C.BDCODCOL) ';
                 wsqlaux = wsqlaux||'left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = COLVINC.BDCODCLA) ';
                 wsqlaux = wsqlaux||'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS COLFGTS on (COLFGTS.BDCODEMP = C.BDCODEMP and COLFGTS.BDCODCOL = C.BDCODCOL) ';
                 wsqlaux = wsqlaux||'where coalesce(C.BDCONTRCOL, 0) = 0 and ';
         wsqlaux = wsqlaux||'C.BDCODEMP = '||bdcodemp||' and ';--wbdcodcli||' and ';
                 wsqlaux = wsqlaux||'coalesce(CLA.BDGRUPOCLA, 0) not in (5, 8) and ';
                 wsqlaux = wsqlaux||'((coalesce(COLFGTS.BDCATEGORIACOL, 0) = 4 and ';
                 wsqlaux = wsqlaux||'coalesce(COLFGTS.BDCATEGORIAESOCIAL, 0) <> 111) or (coalesce(COLFGTS.BDCATEGORIACOL, 0) <> 4 and ';
                 wsqlaux = wsqlaux||'coalesce(COLFGTS.BDCATEGORIAESOCIAL, 0) = 111) or (coalesce(COLFGTS.BDCATEGORIACOL, 0) <> 4 and ';
                 wsqlaux = wsqlaux||'coalesce(COLFGTS.BDCATEGORIAESOCIAL, 0) <> 111)) and ';
         wsqlaux = wsqlaux||'(substring(cast(C.BDDATAADMCOL as varchar(10)) from 1 for 4) || substring(cast(C.BDDATAADMCOL as varchar(10)) from 6 for 2)) <= '||bdrefatual||' and ';
         wsqlaux = wsqlaux||'(R.BDREFRESCISAO is null or R.BDREFRESCISAO >= '||bdrefatual||')';
               end
            else
    if (BDCODCOBSERV = 25) then--Estagiarios ativos
               begin
                 wsqlaux = wsqlaux||'VRH_EMP_TCOLCON C ';
                 wsqlaux = wsqlaux||'left outer join VRH_EMP_TRESCISAO R on (R.BDCODEMP = C.BDCODEMP and R.BDCODCOL = C.BDCODCOL) ';
                 wsqlaux = wsqlaux||'left outer join VW_VRH_EMP_TCOLCON_VINC COLVINC on (COLVINC.BDCODEMP = C.BDCODEMP and COLVINC.BDCODCOL = C.BDCODCOL) ';
                 wsqlaux = wsqlaux||'left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = COLVINC.BDCODCLA) ';
                 wsqlaux = wsqlaux||'left outer join VW_VRHF_EMP_TCOLCON_FGTSGPS COLFGTS on (COLFGTS.BDCODEMP = C.BDCODEMP and COLFGTS.BDCODCOL = C.BDCODCOL) ';
                 wsqlaux = wsqlaux||'where coalesce(C.BDCONTRCOL, 0) = 0 and ';
         wsqlaux = wsqlaux||'C.BDCODEMP = '||bdcodemp||' and ';--wbdcodcli||' and ';
                 wsqlaux = wsqlaux||'coalesce(CLA.BDGRUPOCLA, 0) = 5 and ';
         wsqlaux = wsqlaux||'(substring(cast(C.BDDATAADMCOL as varchar(10)) from 1 for 4) || substring(cast(C.BDDATAADMCOL as varchar(10)) from 6 for 2)) <= '||bdrefatual||' and ';
         wsqlaux = wsqlaux||'(R.BDREFRESCISAO is null or R.BDREFRESCISAO >= '||bdrefatual||')';
               end
            else
    if (bdcodcobserv = 26) then--Intermitentes
                begin
                 wsqlaux = wsqlaux||'(select BDCODEMP, BDCODCOL, BDREFFN, cast(null as integer) BDORDEM from VRHF_EMP_TFOLHAINT ';
         wsqlaux = wsqlaux||'where BDREFFN = '||bdrefatual||' ';
                 wsqlaux = wsqlaux||'union all ';
                 wsqlaux = wsqlaux||'select BDCODEMP, BDCODCOL, BDREFTOMADOR as BDREFFN, max(BDORDEM) ';
                 wsqlaux = wsqlaux||'from VRHF_EMP_TFOLHATOMINT ';
         wsqlaux = wsqlaux||'where BDREFTOMADOR ='||bdrefatual||' ';
                 wsqlaux = wsqlaux||'group by BDCODEMP, BDCODCOL, BDREFTOMADOR) FN ';
                 wsqlaux = wsqlaux||'left outer join VRH_EMP_TCOLCON C on (C.BDCODEMP = FN.BDCODEMP and C.BDCODCOL = FN.BDCODCOL) ';
                 wsqlaux = wsqlaux||'where coalesce(C.BDCONTRCOL, 0) = 0 and ';
         wsqlaux = wsqlaux||'FN.BDCODEMP in ('||bdcodemp||') ';--wbdcodcli||') ';
                 wsqlaux = wsqlaux||'group by FN.BDCODEMP, BDREFFN ';
                end
            else
    if (bdcodcobserv = 27) then--Ativos menos afastados
       begin
         wdataini = cast(substring(bdrefatual from 5 for 2)||'-01-'||substring(bdrefatual from 1 for 4) as date);
         wdatafin = cast(substring(:bdrefatual from 5 for 2)||'-'||(select ULTDIA from ultimo_dia_mes(substring(:bdrefatual from 5 for 2), substring(:bdrefatual from 1 for 4)))||'-'||substring(:bdrefatual from 1 for 4) as date);
         wsqlaux = wsqlaux||'SP_ATI_SEM_AFAST_MES_INT('''||wdataini||''','''||wdatafin||''',0) C ';
         wsqlaux = wsqlaux||'where C.BDCODEMP = '||bdcodemp||' ';
       end
    else
    if (bdcodcobserv = 29) then--Quantidade de entradas
       begin
         wsqlaux = wsqlaux||'VEF_EMP_TMOVENT ';
         wsqlaux = wsqlaux||'where bdcodemp = '||bdcodemp||' and ';
         wsqlaux = wsqlaux||'bdcodsitnf not in (2, 3, 4, 5) and ';-- Documento cancelado
         wsqlaux = wsqlaux||'bdreflan = '||bdrefatual;
       end
    else
    if (bdcodcobserv = 30) then--Quantidade de saídas
       begin
         wsqlaux = wsqlaux||'VEF_EMP_TMOVSAI ';
         wsqlaux = wsqlaux||'where bdcodemp = '||bdcodemp||' and ';
         wsqlaux = wsqlaux||'bdcodsitnf not in (2, 3, 4, 5) and ';-- Documento cancelado
         wsqlaux = wsqlaux||'bdreflan = '||bdrefatual;
       end
    else
    if (bdcodcobserv = 31) then--Quantidade de serviços emitidos
       begin
         wsqlaux = wsqlaux||'VEF_EMP_TMOVSER ';
         wsqlaux = wsqlaux||'where bdcodemp = '||bdcodemp||' and ';
         wsqlaux = wsqlaux||'bdcodsitnf not in (2, 3, 4, 5) and ';-- Documento cancelado
         wsqlaux = wsqlaux||'bdtiplan = 0 and ';-- Emitido
         wsqlaux = wsqlaux||'bdreflan = '||bdrefatual;
       end
    else
    if (bdcodcobserv = 32) then--Quantidade de serviços recebidos
       begin
         wsqlaux = wsqlaux||'VEF_EMP_TMOVSER ';
         wsqlaux = wsqlaux||'where bdcodemp = '||bdcodemp||' and ';
         wsqlaux = wsqlaux||'bdcodsitnf not in (2, 3, 4, 5) and ';-- Documento cancelado
         wsqlaux = wsqlaux||'bdtiplan = 1 and ';-- Recebido
         wsqlaux = wsqlaux||'bdreflan = '||bdrefatual;
       end
    else
    if (bdcodcobserv = 34) then--Lançamentos contábeis
       begin
         select list(bdcodemp) from SP_RETORNA_EMPRESA_FILIAIS(:bdcodemp,:bdrefatual) into :wfiliais;
         wsqlaux = wsqlaux||'VSUC_EMPRESAS_TLAN ';
         wsqlaux = wsqlaux||'where bdcodemp in( '||wfiliais||') and ';
         wsqlaux = wsqlaux||'bdreferencia = '||bdrefatual;
       end
  suspend;
end^

CREATE OR ALTER procedure SP_VFIN_COBRAR_SOBRE (
    PREMPRESAS varchar(100),
    PRCLIENTES varchar(3000),
    PRCODSERV integer,
    PRREFINI integer,
    PRREFFIN integer)
as
declare variable WSQL varchar(10000);
declare variable WWHERE varchar(3000);
declare variable WSQLAUX varchar(2000);
declare variable WBDCODCLI integer;
declare variable WBDCODESC integer;
declare variable WBDCHAVESERFIX integer;
declare variable WBDORDEMSERFIX integer;
declare variable WBDREFINI integer;
declare variable WBDREFFIN integer;
declare variable WBDQTDSERFIX numeric(15,2);
declare variable WBDVLRUNITSERFIX numeric(15,2);
declare variable WBDCODCOBSERV integer;
declare variable WBDDESCSERFIX integer;
declare variable WBDTIPDESC integer;
declare variable WQTDSERVFIX numeric(15,2);
declare variable WREFATUAL integer;
declare variable WREFINI integer;
declare variable WCODESC_REF integer;
declare variable WCODCLI_REF integer;
declare variable WCHAVESERFIX_REF integer;
declare variable WORDEMSERFIX_REF integer;
declare variable WCHAVEREF_REF integer;
declare variable WVALOR_ATE numeric(15,2);
declare variable WVALOR_APOS numeric(15,2);
declare variable WLIMITE_LANC integer;
declare variable WCOBRAEXCED varchar(5);
declare variable WORDEM_FILHO integer;
declare variable WNOVA_ORDEM integer;
declare variable WCODEMP integer;
begin
  -- buscar todos os servi??os com cobrar sobre
  wwhere = '';
  wsql = 'select serfix.bdcodcli, serfix.bdcodesc, serfix.bdchaveserfix, serfix.bdordemserfix, ';
  wsql = wsql||'serfix.bdrefini, serfix.bdreffin, serfix.bdqtdserfix, serfix.BDVLRUNITSERFIX, ser.bdcodcobserv, BDDESCSERFIX, BDTIPDESC ';
  wsql = wsql||',emp.bdcodemp ';
  wsql = wsql||'from ( ';
  wsql = wsql||'select * from VFIN_ESC_TSERVICOFIXO serfix ';

  if ((prclientes <> '') and (prclientes is not null)) then
      wwhere = wwhere||'(bdcodcli in('||prclientes||'))';

  if ((prempresas <> '') and (prempresas is not null)) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||'(bdcodesc in('||prempresas||'))';
     end
  if ((prcodserv > 0) and (prcodserv is not null)) then
     begin
      if (wwhere <> '') then
         wwhere = wwhere||' and ';
      wwhere = wwhere||'(bdcodobrser='||prcodserv||')';
     end

  if ((prreffin > 0) and (prreffin is not null)) then
     begin
       if (wwhere <> '') then
         wwhere = wwhere||' and ';
        wwhere = wwhere||'(BDREFINI<='||prreffin||')';
     end

  if ((prrefini > 0) and (prrefini is not null)) then
     begin
       if (wwhere <> '') then
          wwhere = wwhere||' and ';
       wwhere = wwhere||'((BDREFFIN is null)or(BDREFFIN=0)or(BDREFFIN>='||prrefini||'))';
     end

  if (((prreffin = 0) or (prreffin is null)) and ((prrefini = 0) or (prrefini is null))) then
      begin
       if (wwhere <> '') then
          wsql = wsql||' where '||wwhere||' and ';
       else
          wsql = wsql||' where ';
       wsql = wsql||'not exists (select * from vfin_esc_torigemserfat orig ';
       wsql = wsql||'where bdcodcli = serfix.bdcodcli ';
       wsql = wsql||'and bdcodesc = serfix.bdcodesc ';
       wsql = wsql||'and bdchaveserfix = serfix.bdchaveserfix ';
       wsql = wsql||'and bdordemserfix = serfix.bdordemserfix) ';
      end
   else
   if (wwhere <> '') then
      wsql = wsql||' where '||wwhere||' ';
  wsql = wsql||') serfix ';
  wsql = wsql||'inner join VCT_BASE_SERVICO ser on (ser.bdcodobrser = serfix.bdcodobrser) ';
  wsql = wsql||'left join tempresas emp on(emp.bdcodcli=serfix.bdcodcli)';
  wsql = wsql||'where (ser.bdcodcobserv is not null) and (emp.bdcodemp is not null) and coalesce(BDORDEM_PAI,0) = 0 ';
  wsql = wsql||'order by bdrefini, bdcodcli, bdchaveserfix, bdordemserfix ';

  for execute statement :wsql into
    :WBDCODCLI,
    :WBDCODESC,
    :WBDCHAVESERFIX,
    :WBDORDEMSERFIX,
    :WBDREFINI,
    :WBDREFFIN,
    :WBDQTDSERFIX,
    :WBDVLRUNITSERFIX,
    :WBDCODCOBSERV,
    :WBDDESCSERFIX,
    :WBDTIPDESC,
    :wcodemp
  do
   begin
     WVALOR_ATE = null;
     WVALOR_APOS = null;
     WLIMITE_LANC = null;
     select first 1 CON.BDVALORATE, CON.BDVALORAPOS, CON.BDQTD, CON.BDCOBRAEXCED
            from VFIN_BASE_TCONFCOBSERV CON
            where CON.BDCODESC = :WBDCODESC and
                  (CON.BDCODCLI = :WBDCODCLI or CON.BDCODCLI is null) and
                  CON.BDCODCOBSERV = :WBDCODCOBSERV  order by CON.BDCODCLI desc
            into :WVALOR_ATE, :WVALOR_APOS, :WLIMITE_LANC, :WCOBRAEXCED;
    if ((:WBDREFINI <> :WBDREFFIN) and (prrefini > 0)) then
       begin
         wqtdservfix = 0;
         if (prrefini >  wbdrefini) then
            wrefini = prrefini;
         else
            wrefini = wbdrefini;

         while (wrefini <= prreffin) do
           begin
            wRefAtual = wRefIni;

            select wsqlaux from SP_VFIN_GETSQL_COBRAR_SOBRE(:wbdcodcobserv, :wcodemp, :wrefatual) into :wsqlaux;
            wsqlaux = 'select count(*) from '||wsqlaux;

            execute statement wsqlaux into :wqtdservfix;

            wcodcli_ref = null;
            wcodesc_ref = null;
            wchaveserfix_ref = null;
            wordemserfix_ref = null;
            wchaveref_ref = null;
            wsql = 'select BDCODCLI, BDCODESC, BDCHAVESERFIX,BDORDEMSERFIX, BDchaveref  from VFIN_ESC_TSERVICOFIXO_REF ';
            wsql = wsql||'where ';
            wsql = wsql||'BDCODCLI = '||:wbdcodcli||' and ';
            wsql = wsql||'BDCODESC = '||:wbdcodesc||' and ';
            wsql = wsql||'BDCHAVESERFIX = '||wbdchaveserfix||' and ';
            wsql = wsql||'BDORDEMSERFIX = '||wbdordemserfix||' and ';
            wsql = wsql||'BDMESREF = '||CAST(SUBSTRING(CAST(:wrefatual AS VARCHAR(6)) FROM 5 FOR 2) AS SMALLINT)||' and ';
            wsql = wsql||'BDANOREF = '||CAST(SUBSTRING(CAST(:wrefatual AS VARCHAR(6)) FROM 1 FOR 4) AS SMALLINT);

            execute statement :wsql into :wcodcli_ref, :wcodesc_ref, :wchaveserfix_ref, :wordemserfix_ref, :wchaveref_ref;

            if (coalesce(:WLIMITE_LANC,0) > 0) then
               begin--Se tiver configuração de cobrar sobre
                if (WLIMITE_LANC >= WQTDSERVFIX) then
                   begin--Se não atingiu o limite cobrar o valor até
                     if (coalesce(:wchaveref_ref,0) > 0) then
                        begin
                     update VFIN_ESC_TSERVICOFIXO_REF
                             set BDQTDSERREF = :WQTDSERVFIX,
                                 BDVLRTOTSERREF = (:WQTDSERVFIX * :WVALOR_ATE)
                             where BDCODCLI = :WCODCLI_REF and
                                   BDCODESC = :WCODESC_REF and
                                   BDCHAVESERFIX = :WCHAVESERFIX_REF and
                                   BDORDEMSERFIX = :WORDEMSERFIX_REF and
                                   BDCHAVEREF = :WCHAVEREF_REF;
                   end
                     else
                       begin
                         insert into VFIN_ESC_TSERVICOFIXO_REF (BDCODCLI, BDCODESC, BDCHAVESERFIX, BDORDEMSERFIX, BDCHAVEREF, BDMESREF, BDANOREF,
                                                  BDVLRUNITSERREF, BDQTDSERREF, BDTIPDESCREF, BDDESCSERREF, BDVLRTOTSERREF,BDOBSREF, BDPROPORCIONAL)
                         values (:WBDCODCLI, :WBDCODESC, :WBDCHAVESERFIX, :WBDORDEMSERFIX, null, cast(substring(cast(:WREFATUAL as varchar(6)) from 5 for 2) as smallint),
                         cast(substring(cast(:WREFATUAL as varchar(6)) from 1 for 4) as smallint), :WVALOR_ATE, :WQTDSERVFIX, :WBDTIPDESC, :WBDDESCSERFIX, (:WQTDSERVFIX * :WVALOR_ATE), '', 'FALSE');
                       end
                   end
                 else--Se passou do limite então
                   begin--Verifica se deve cobrar o excedente
                    if (coalesce(WCOBRAEXCED,'FALSE') = 'TRUE') then
                       begin--Se for pra cobrar excedente deve criar uma nova ordem com uma observa????o
                       if ((coalesce(wchaveref_ref,0) = 0) and (WVALOR_ATE > 0)) then
                           begin
                             insert into VFIN_ESC_TSERVICOFIXO_REF (BDCODCLI, BDCODESC, BDCHAVESERFIX, BDORDEMSERFIX, BDCHAVEREF, BDMESREF, BDANOREF,
                                                  BDVLRUNITSERREF, BDQTDSERREF, BDTIPDESCREF, BDDESCSERREF, BDVLRTOTSERREF,BDOBSREF, BDPROPORCIONAL)
                             values (:WBDCODCLI, :WBDCODESC, :WBDCHAVESERFIX, :WBDORDEMSERFIX, null, cast(substring(cast(:WREFATUAL as varchar(6)) from 5 for 2) as smallint),
                             cast(substring(cast(:WREFATUAL as varchar(6)) from 1 for 4) as smallint), :WVALOR_ATE, :WLIMITE_LANC,:WBDTIPDESC, :WBDDESCSERFIX, (:WLIMITE_LANC * :WVALOR_ATE), '', 'FALSE');
                            end

                         WORDEM_FILHO = 0;
                         select BDORDEMSERFIX
                                from VFIN_ESC_TSERVICOFIXO
                                where BDCODESC = :WBDCODESC and
                                      BDCODCLI = :WBDCODCLI and
                                      BDCHAVESERFIX = :WBDCHAVESERFIX and
                                      BDORDEM_PAI = :WBDORDEMSERFIX and
                                      BDREFINI = :wrefatual and
                                      BDREFFIN = :wrefatual into :WORDEM_FILHO;

                             if (coalesce(WORDEM_FILHO,0) > 0) then
                                begin--Se essa ordem do servi??o j?? tiver um filho ent??o s?? atualiza.
                                   update VFIN_ESC_TSERVICOFIXO SERFIX
                                      set BDQTDSERFIX = (:WQTDSERVFIX - :WLIMITE_LANC),
                                          BDVLRUNITSERFIX = :WVALOR_APOS,
                                          BDVLRTOTSERFIX = (:WVALOR_APOS * (:WQTDSERVFIX - :WLIMITE_LANC))
                                    where BDCODCLI = :WBDCODCLI and
                                          BDCODESC = :WBDCODESC and
                                          BDCHAVESERFIX = :WBDCHAVESERFIX and
                                          BDORDEMSERFIX = :WORDEM_FILHO;
                                end
                             else--Se n??o tiver um filho cria uma nova ordem copiando a ordem pai.
                                begin
                                  if (WVALOR_APOS > 0) then
                                      begin
                                  insert into VFIN_ESC_TSERVICOFIXO (BDCODCLI, BDCODESC, BDCHAVESERFIX, BDCHAVEACOR, BDCHAVEREAJ, BDORDEMREAJ, BDCODCONTR, BDCHAVEGER,
                                         BDCODOBRSER, BDREFINI, BDREFFIN, BDQTDSERFIX, BDDESCSERFIX, BDTIPDESC, BDVLRTOTSERFIX, BDDIAVENC, BDFATURAR,
                                         BDREAJCONTR, BDSABDOMFER, BDVLRUNITSERFIX, BDTIPSERVCONTR, BDNUMPARC, BDCODEMP, BDCODST, BDMES01, BDMES02,
                                         BDMES03, BDMES04, BDMES05, BDMES06, BDMES07, BDMES08, BDMES09, BDMES10, BDMES11, BDMES12, BDSERVCONTR, BDCODCAT,
                                         BDCONTABILIZAR,BDORDEM_PAI)
                                  select BDCODCLI, BDCODESC, BDCHAVESERFIX, BDCHAVEACOR, BDCHAVEREAJ, BDORDEMREAJ, BDCODCONTR, BDCHAVEGER,
                                         BDCODOBRSER, :wrefatual, :wrefatual, (:WQTDSERVFIX - :WLIMITE_LANC) as BDQTDSERFIX, BDDESCSERFIX, BDTIPDESC,
                                         ((:WQTDSERVFIX - :WLIMITE_LANC) * :WVALOR_APOS) as BDVLRTOTSERFIX, BDDIAVENC, BDFATURAR,
                                         BDREAJCONTR, BDSABDOMFER, :WVALOR_APOS as BDVLRUNITSERFIX, BDTIPSERVCONTR, BDNUMPARC, BDCODEMP, BDCODST, BDMES01, BDMES02,
                                         BDMES03, BDMES04, BDMES05, BDMES06, BDMES07, BDMES08, BDMES09, BDMES10, BDMES11, BDMES12, BDSERVCONTR, BDCODCAT,
                                         BDCONTABILIZAR,BDORDEMSERFIX
                                  from VFIN_ESC_TSERVICOFIXO
                                  where BDCODESC = :WBDCODESC and
                                        BDCODCLI = :WBDCODCLI and
                                        BDCHAVESERFIX = :WBDCHAVESERFIX and
                                        BDORDEMSERFIX = :WBDORDEMSERFIX returning BDORDEMSERFIX into :WNOVA_ORDEM;
        
                                  INSERT INTO VFIN_ESC_TSERVICOFIXOOBS (BDCODCLI, BDCODESC, BDCHAVESERFIX, BDORDEMSERFIX, BDOBSSERFIX)
                                  VALUES (:WBDCODCLI, :WBDCODESC, :WBDCHAVESERFIX, :WNOVA_ORDEM, 'Lançamento criado com excedente dos serviços de cobrar sobre');
                                end
                       end
                       end
                    else--Se n??o for deve apenas usar o valor apos.
                       begin
                          if ((coalesce(WCHAVESERFIX_REF,0) = 0) and (WVALOR_APOS > 0)) then
                             begin
                               insert into VFIN_ESC_TSERVICOFIXO_REF (BDCODCLI, BDCODESC, BDCHAVESERFIX, BDORDEMSERFIX, BDCHAVEREF, BDMESREF, BDANOREF,
                                                                      BDVLRUNITSERREF, BDQTDSERREF, BDTIPDESCREF, BDDESCSERREF, BDVLRTOTSERREF, BDOBSREF, BDPROPORCIONAL)
                               values (:WBDCODCLI, :WBDCODESC, :WBDCHAVESERFIX, :WBDORDEMSERFIX, null, cast(substring(cast(:WREFATUAL as varchar(6)) from 5 for 2) as smallint),
                               cast(substring(cast(:WREFATUAL as varchar(6)) from 1 for 4) as smallint), :WVALOR_APOS, :WQTDSERVFIX,:WBDTIPDESC, :WBDDESCSERFIX, (:WQTDSERVFIX * :WVALOR_APOS), '', 'FALSE');
                             end
                          else
                            begin
                              update VFIN_ESC_TSERVICOFIXO_REF
                                 set BDQTDSERREF = :WQTDSERVFIX,
                                     BDVLRUNITSERREF  = :WVALOR_APOS,
                                     BDVLRTOTSERREF = (:WQTDSERVFIX * :WVALOR_APOS)
                                 where BDCODCLI = :WCODCLI_REF and
                                       BDCODESC = :WCODESC_REF and
                                       BDCHAVESERFIX = :WCHAVESERFIX_REF and
                                       BDORDEMSERFIX = :WORDEMSERFIX_REF and
                                       BDCHAVEREF = :WCHAVEREF_REF;
                            end
                       end
                   end
                end
             else
                begin
                 if ((wcodcli_ref is not null) and (wcodcli_ref > 0)) then
                    begin
                      update VFIN_ESC_TSERVICOFIXO_REF
                             set BDQTDSERREF = :WQTDSERVFIX,
                                 BDVLRTOTSERREF = (:WQTDSERVFIX * BDVLRUNITSERREF)
                             where BDCODCLI = :WCODCLI_REF and
                                   BDCODESC = :WCODESC_REF and
                                   BDCHAVESERFIX = :WCHAVESERFIX_REF and
                                   BDORDEMSERFIX = :WORDEMSERFIX_REF and
                                   BDCHAVEREF = :WCHAVEREF_REF;
                    end
                 else
                    begin
                    if ((wqtdservfix > 0) and (WBDVLRUNITSERFIX > 0)) then
                       begin
                          insert into VFIN_ESC_TSERVICOFIXO_REF (BDCODCLI, BDCODESC, BDCHAVESERFIX, BDORDEMSERFIX, BDCHAVEREF, BDMESREF, BDANOREF,
                                           BDVLRUNITSERREF, BDQTDSERREF, BDTIPDESCREF, BDDESCSERREF, BDVLRTOTSERREF,
                                           BDOBSREF, BDPROPORCIONAL)
                          values (:WBDCODCLI, :WBDCODESC, :WBDCHAVESERFIX, :WBDORDEMSERFIX, null, cast(substring(cast(:WREFATUAL as varchar(6)) from 5 for 2) as smallint),
                          cast(substring(cast(:WREFATUAL as varchar(6)) from 1 for 4) as smallint), :WBDVLRUNITSERFIX, :WQTDSERVFIX,:WBDTIPDESC, :WBDDESCSERFIX, :WBDVLRUNITSERFIX, '', 'FALSE');

                       end
                    end
                end
            execute statement 'select BDREFERENCIA from inc_referencia('||wrefini||')' into :wrefini;
           end
       end
     else
       begin
         if (:wbdrefini = :wbdreffin) then
            begin
              WQTDSERVFIX = 0;
              wrefatual   = wbdrefini;

            select wsqlaux from SP_VFIN_GETSQL_COBRAR_SOBRE(:wbdcodcobserv, :wcodemp, :wrefatual) into :wsqlaux;
            wsqlaux = 'select count(*) from '||wsqlaux;

            execute statement wsqlaux into :wqtdservfix;

            if (coalesce(:WLIMITE_LANC,0) > 0) then
               begin---Se tiver configura????o de cobrar sobre
                if (WLIMITE_LANC >= WQTDSERVFIX) then
                   begin ---Se n??o atingiu o limite cobrar o valor at??
                     update VFIN_ESC_TSERVICOFIXO SERFIX
                            set BDQTDSERFIX = :WQTDSERVFIX,
                                BDVLRUNITSERFIX = :WVALOR_ATE,
                                BDVLRTOTSERFIX = (:WVALOR_ATE * :WQTDSERVFIX)
                            where BDCODCLI = :WBDCODCLI and
                                  BDCODESC = :WBDCODESC and
                                  BDCHAVESERFIX = :WBDCHAVESERFIX and
                                  BDORDEMSERFIX = :WBDORDEMSERFIX;
                   end
                 else --Se passou do limite ent??o
                   begin ---Verifica se deve cobrar o excedente
                    if (coalesce(WCOBRAEXCED,'FALSE') = 'TRUE') then
                       begin---Se for pra cobrar excedente deve criar uma nova ordem com uma observa????o
                         update VFIN_ESC_TSERVICOFIXO SERFIX
                            set BDQTDSERFIX = :WLIMITE_LANC,
                                BDVLRUNITSERFIX = :WVALOR_ATE,
                                BDVLRTOTSERFIX = (:WVALOR_ATE * :WLIMITE_LANC)
                            where BDCODCLI = :WBDCODCLI and
                                  BDCODESC = :WBDCODESC and
                                  BDCHAVESERFIX = :WBDCHAVESERFIX and
                                  BDORDEMSERFIX = :WBDORDEMSERFIX;

                         WORDEM_FILHO = 0;
                         select BDORDEMSERFIX
                                from VFIN_ESC_TSERVICOFIXO
                                where BDCODESC = :WBDCODESC and
                                      BDCODCLI = :WBDCODCLI and
                                      BDCHAVESERFIX = :WBDCHAVESERFIX and
                                      BDORDEM_PAI = :WBDORDEMSERFIX into :WORDEM_FILHO;
                             if (coalesce(WORDEM_FILHO,0) > 0) then
                                begin ----Se essa ordem do servi??o j?? tiver um filho ent??o s?? atualiza.
                                   update VFIN_ESC_TSERVICOFIXO SERFIX
                                   set BDQTDSERFIX = (:WQTDSERVFIX - :WLIMITE_LANC),
                                       BDVLRUNITSERFIX = :WVALOR_APOS,
                                       BDVLRTOTSERFIX = (:WVALOR_APOS * (:WQTDSERVFIX - :WLIMITE_LANC))
                                   where BDCODCLI = :WBDCODCLI and
                                         BDCODESC = :WBDCODESC and
                                         BDCHAVESERFIX = :WBDCHAVESERFIX and
                                         BDORDEMSERFIX = :WORDEM_FILHO;
                                end
                             else --Se n??o tiver um filho cria uma nova ordem copiando a ordem pai.
                                begin
                                  if (WVALOR_APOS > 0) then
                                     begin
                                     insert into VFIN_ESC_TSERVICOFIXO (BDCODCLI, BDCODESC, BDCHAVESERFIX, BDCHAVEACOR, BDCHAVEREAJ, BDORDEMREAJ, BDCODCONTR, BDCHAVEGER,
                                            BDCODOBRSER, BDREFINI, BDREFFIN, BDQTDSERFIX, BDDESCSERFIX, BDTIPDESC, BDVLRTOTSERFIX, BDDIAVENC, BDFATURAR,
                                            BDREAJCONTR, BDSABDOMFER, BDVLRUNITSERFIX, BDTIPSERVCONTR, BDNUMPARC, BDCODEMP, BDCODST, BDMES01, BDMES02,
                                            BDMES03, BDMES04, BDMES05, BDMES06, BDMES07, BDMES08, BDMES09, BDMES10, BDMES11, BDMES12, BDSERVCONTR, BDCODCAT,
                                            BDCONTABILIZAR,BDORDEM_PAI)
                                     select BDCODCLI, BDCODESC, BDCHAVESERFIX, BDCHAVEACOR, BDCHAVEREAJ, BDORDEMREAJ, BDCODCONTR, BDCHAVEGER,
                                            BDCODOBRSER, BDREFINI, BDREFFIN, (:WQTDSERVFIX - :WLIMITE_LANC) as BDQTDSERFIX, BDDESCSERFIX, BDTIPDESC,
                                            ((:WQTDSERVFIX - :WLIMITE_LANC) * :WVALOR_APOS) as BDVLRTOTSERFIX, BDDIAVENC, BDFATURAR,
                                            BDREAJCONTR, BDSABDOMFER, :WVALOR_APOS as BDVLRUNITSERFIX, BDTIPSERVCONTR, BDNUMPARC, BDCODEMP, BDCODST, BDMES01, BDMES02,
                                            BDMES03, BDMES04, BDMES05, BDMES06, BDMES07, BDMES08, BDMES09, BDMES10, BDMES11, BDMES12, BDSERVCONTR, BDCODCAT,
                                            BDCONTABILIZAR,BDORDEMSERFIX
                                     from VFIN_ESC_TSERVICOFIXO
                                     where BDCODESC = :WBDCODESC and
                                           BDCODCLI = :WBDCODCLI and
                                           BDCHAVESERFIX = :WBDCHAVESERFIX and
                                           BDORDEMSERFIX = :WBDORDEMSERFIX returning BDORDEMSERFIX into :WNOVA_ORDEM;
    
                                     INSERT INTO VFIN_ESC_TSERVICOFIXOOBS (BDCODCLI, BDCODESC, BDCHAVESERFIX, BDORDEMSERFIX, BDOBSSERFIX)
                                     VALUES (:WBDCODCLI, :WBDCODESC, :WBDCHAVESERFIX, :WNOVA_ORDEM, 'Lan?amento criado com excedente dos servi?os de cobrar sobre');
                                end
                       end
                       end
                    else--Se não é pra cobrar excedente deve apenas usar o valor após.
                       begin
                          update VFIN_ESC_TSERVICOFIXO SERFIX
                            set BDQTDSERFIX = :WQTDSERVFIX,
                                BDVLRUNITSERFIX = :WVALOR_APOS,
                                BDVLRTOTSERFIX = (:WVALOR_APOS * :WQTDSERVFIX)
                            where BDCODCLI = :WBDCODCLI and
                                  BDCODESC = :WBDCODESC and
                                  BDCHAVESERFIX = :WBDCHAVESERFIX and
                                  BDORDEMSERFIX = :WBDORDEMSERFIX;

                       end
                   end
                end
            else--Se não tiver configura????o do cobrar sobre usar a quantidade normal.
                if (WQTDSERVFIX <> WBDQTDSERFIX) then
                   begin
                     update VFIN_ESC_TSERVICOFIXO SERFIX
                            set BDQTDSERFIX = :WQTDSERVFIX
                            where BDCODCLI = :WBDCODCLI and
                                  BDCODESC = :WBDCODESC and
                                  BDCHAVESERFIX = :WBDCHAVESERFIX and
                                  BDORDEMSERFIX = :WBDORDEMSERFIX;
                   end
            end
       end
   end
end^

CREATE OR ALTER procedure SP_PROX_DIA_DA_SEMANA (
    PRDATA date,
    PRWEEKDAY char(7),
    PRCONSIDERARDATAATUAL DM_BOOLEAN collate WIN_PTBR = 'FALSE')
returns (
    BDDATA date)
as
declare variable WWEEKDAY integer;
declare variable WFIND DM_BOOLEAN;
begin
  /*Patrick T. Sá 31/07/2019. Busca o próxima dia de semana a partir da data informada*/
  PRWEEKDAY = UPPER(:PRWEEKDAY);

  IF (:PRWEEKDAY = 'DOMINGO') THEN
    wWeekDay = 0;
  ELSE
  IF (:PRWEEKDAY = 'SEGUNDA') THEN
    wWeekDay = 1;
  ELSE
  IF (:PRWEEKDAY = 'TERÇA') THEN
    wWeekDay = 2;
  ELSE
  IF (:PRWEEKDAY = 'QUARTA') THEN
    wWeekDay = 3;
  ELSE
  IF (:PRWEEKDAY = 'QUINTA') THEN
    wWeekDay = 4;
  ELSE
  IF (:PRWEEKDAY = 'SEXTA') THEN
    wWeekDay = 5;
  ELSE
  IF (:PRWEEKDAY = 'SÁBADO') THEN
    wWeekDay = 6;
  ELSE
    wWeekDay = :PRWEEKDAY; /*Pode passar o weekDay por código também, */

  wFind  = 'FALSE';
  BDDATA = :PRDATA;

  IF (:PRCONSIDERARDATAATUAL = 'TRUE') THEN
    BEGIN
      IF (:wWeekDay = EXTRACT(WEEKDAY FROM :PRDATA)) THEN
        wFind = 'TRUE';
    END

  WHILE (:wFind = 'FALSE') DO
    BEGIN
      BDDATA = ADDDAY(:BDDATA, 1);

      wFind = IIF(EXTRACT(WEEKDAY FROM :BDDATA) = :wWeekDay, 'TRUE', 'FALSE');
    END

  SUSPEND;
end^

COMMENT ON PARAMETER SP_PROX_DIA_DA_SEMANA.PRWEEKDAY IS 'Segunda, Terça, Quarta...'^

CREATE OR ALTER TRIGGER vsh_emp_tlista_processos_bu0 FOR vsh_emp_tlista_processos
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  IF ((COALESCE(NEW.BDCODSTATUS, 0) IN (3, 6, 11)) AND (OLD.BDDATAFIM IS NULL)) THEN
    NEW.BDDATAFIM = CAST('NOW' AS TIMESTAMP);

  IF ((COALESCE(OLD.BDCODSTATUS, 0) <> 6) AND (COALESCE(NEW.BDCODSTATUS, 0) = 6)) THEN /*Erro*/
    NEW.BDDESCPROCESSO = 'Processo não realizado... '||COALESCE(NEW.BDDESCPROCESSO, '');

  IF ((COALESCE(OLD.BDCODSTATUS, 0) > 0) AND (COALESCE(NEW.BDCODSTATUS, 0)> 0)) THEN
    BEGIN
      IF ((OLD.BDCODSTATUS = 1) AND (NEW.BDCODSTATUS = 2)) THEN
        BEGIN
          NEW.BDDATAINI = localtimestamp;
        END
    END
end^

CREATE OR ALTER TRIGGER TDARFGERPGTO_AD0 FOR TDARFGERPGTO
ACTIVE AFTER DELETE POSITION 0
AS
begin
  UPDATE VEF_EMP_TIMPOSTOS_IC SET BDSTATUSBAIXA = 10 WHERE BDCODEMP = OLD.BDCODEMP AND BDORDEMIMP = OLD.BDORDEMIC;
end
^

CREATE OR ALTER TRIGGER TINTEGRACAO_ARQ_CLIENTE_FILA_AD0 FOR TINTEGRACAO_ARQ_CLIENTE_FILA
ACTIVE AFTER DELETE POSITION 0
AS
begin
  DELETE FROM TINTEGRACAO_ARQ_CLIENTE_FILA_ARQ WHERE BDCODEMP = OLD.BDCODEMP AND BDLOTE = OLD.BDLOTE;
end^



CREATE OR ALTER TRIGGER VSH_BASE_TAGENDAMENTO_BU0 FOR VSH_BASE_TAGENDAMENTO
ACTIVE BEFORE UPDATE POSITION 0
AS
  declare CODPERSONALIZACAO integer;
  declare CODPROCESSO integer;
begin

  IF ((OLD.BDCODPERIODICIDADE <> NEW.BDCODPERIODICIDADE) OR (OLD.BDDIA <> NEW.BDDIA) OR (OLD.BDHORA <> NEW.BDHORA) OR (COALESCE(OLD.BDINATIVO, 'FALSE') <> NEW.BDINATIVO)) THEN
    NEW.BDULTIMAEXECUCAO = NULL;

  IF (NEW.BDHORA < LOCALTIME and COALESCE(NEW.BDCODPERIODICIDADE, 0) <> 9) THEN
    NEW.BDULTIMAEXECUCAO = CURRENT_DATE;    

  select FIRST 1 BDCODIGO from TPERSONALIZACAO WHERE (BDCODIGO BETWEEN 80000 AND 89999)
  INTO :CODPERSONALIZACAO;

  if (CODPERSONALIZACAO > 0) then /*SE FOR PERSONALIZACAO SCI NAO INATIVA O PROCESSO DE CONSULTA CREDITO TRAB */
    begin
        select FIRST 1 p.BDCODPROCESSO from VSH_BASE_TAGENDAMENTO_PLANO ap
        join VSH_BASE_TPLANO p on p.BDCODPLANOSCHIP = ap.BDCODPLANOSCHIP
        where ap.BDCODAGENDAMENTO = OLD.BDCODAGENDAMENTO INTO :CODPROCESSO;

        if (CODPROCESSO = 58) then
           NEW.BDINATIVO = 'FALSE';
    end
end^

CREATE OR ALTER procedure SP_VSH_PODE_INICIAR_PROCESSO (
    PRCODAGENDAMENTO integer,
    PRCODPLANOSCHIP integer,
    PRREFPROC integer,
    PRCODAUTOTHREAD integer,
    PRCODEMP integer)
returns (
    BDPODEEXECUTAR DM_BOOLEAN)
as
declare variable WPROCESSOJAEXISTE integer;
declare variable WPARAMVALUE varchar(255);
declare variable WPARAMVALUE2 varchar(255);
declare variable WPARAMVALUE3 varchar(255);
declare variable WCONFIGCERTIFICADO integer;
declare variable WDATAWSCREDITO date;
declare variable WBAIXAWSCREDITO date;
declare variable WREFWSCREDITO integer;
declare variable WCNPJEMPWSCREDITO varchar(18);
declare variable WMATRIZWSCREDITO integer;
declare variable WBDCODIGO_PERSONALIZACAO integer;
begin
  BDPODEEXECUTAR = 'TRUE';
  WBDCODIGO_PERSONALIZACAO = 0;

  -- SCI Report. Verifica se a empresa está marcada para exportar para SCI Report.
  if (coalesce(prcodautothread, 0) in (3, 5)) then
     begin
       select first 1 BDSCIREPORT from TEMPRESAS where BDCODEMP = :prcodemp into :BDPODEEXECUTAR;
       BDPODEEXECUTAR = upper(coalesce(BDPODEEXECUTAR, 'FALSE'));

       -- Veririca se os parâmetro para geração foram marcados.
       if (BDPODEEXECUTAR = 'TRUE' and coalesce(prcodplanoschip, 0) > 0) then
          begin
            -- Espelho resumo
            if (coalesce(prcodautothread, 0) = 3) then
               begin
                 wparamvalue = null;
                 select first 1 BDPARAMVALUE from VSH_BASE_TPLANO_PARAMS where BDCODPLANOSCHIP = :PRCODPLANOSCHIP and Upper(BDPARAMNAME) = Upper('ckConferirEspelhoResumo') into :wparamvalue;
                 wparamvalue = upper(coalesce(wparamvalue, 'FALSE'));

                 wparamvalue2 = null;
                 select first 1 BDPARAMVALUE from VSH_BASE_TPLANO_PARAMS where BDCODPLANOSCHIP = :PRCODPLANOSCHIP and Upper(BDPARAMNAME) = Upper('ckPublicarEspelhoResumo') into :wparamvalue2;
                 wparamvalue2 = upper(coalesce(wparamvalue2, 'FALSE'));

                 wparamvalue3 = null;
                 select first 1 BDPARAMVALUE from VSH_BASE_TPLANO_PARAMS where BDCODPLANOSCHIP = :PRCODPLANOSCHIP and Upper(BDPARAMNAME) = Upper('ckConferirPorColEspelhoResumo') into :wparamvalue3;
                 wparamvalue3 = upper(coalesce(wparamvalue3, 'FALSE'));

                 if (wparamvalue <> 'TRUE' and wparamvalue2 <> 'TRUE' and wparamvalue3 <> 'TRUE') then
                    BDPODEEXECUTAR = 'FALSE';
               end
            else
            -- Recibo de salário
            if (coalesce(prcodautothread, 0) = 5) then
               begin
                 wparamvalue = null;
                 select first 1 BDPARAMVALUE from VSH_BASE_TPLANO_PARAMS where BDCODPLANOSCHIP = :PRCODPLANOSCHIP and Upper(BDPARAMNAME) = Upper('ckConferirReciboMensal') into :wparamvalue;
                 wparamvalue = upper(coalesce(wparamvalue, 'FALSE'));

                 wparamvalue2 = null;
                 select first 1 BDPARAMVALUE from VSH_BASE_TPLANO_PARAMS where BDCODPLANOSCHIP = :PRCODPLANOSCHIP and Upper(BDPARAMNAME) = Upper('ckPublicarReciboMensal') into :wparamvalue2;
                 wparamvalue2 = upper(coalesce(wparamvalue2, 'FALSE'));

                 if (wparamvalue <> 'TRUE' and wparamvalue2 <> 'TRUE') then
                    BDPODEEXECUTAR = 'FALSE';
               end
          end
     end
  else
  -- e-mail. Verifica se as configurações de e-mail estão marcadas.
  if (coalesce(prcodautothread, 0) in (2, 4)) then
     begin
       -- Veririca se os parâmetro para geração foram marcados.
       if (coalesce(prcodplanoschip, 0) > 0) then
          begin
            -- Espelho resumo
            if (coalesce(prcodautothread, 0) = 2) then
               begin
                 wparamvalue = null;
                 select first 1 BDPARAMVALUE from VSH_BASE_TPLANO_PARAMS where BDCODPLANOSCHIP = :PRCODPLANOSCHIP and Upper(BDPARAMNAME) = Upper('ckConferirEspelhoResumo') into :wparamvalue;
                 wparamvalue = upper(coalesce(wparamvalue, 'FALSE'));

                 wparamvalue2 = null;
                 select first 1 BDPARAMVALUE from VSH_BASE_TPLANO_PARAMS where BDCODPLANOSCHIP = :PRCODPLANOSCHIP and Upper(BDPARAMNAME) = Upper('ckEnviarEmailEspelhoResumo') into :wparamvalue2;
                 wparamvalue2 = upper(coalesce(wparamvalue2, 'FALSE'));

                 wparamvalue3 = null;
                 select first 1 BDPARAMVALUE from VSH_BASE_TPLANO_PARAMS where BDCODPLANOSCHIP = :PRCODPLANOSCHIP and Upper(BDPARAMNAME) = Upper('ckConferirPorColEspelhoResumo') into :wparamvalue3;
                 wparamvalue3 = upper(coalesce(wparamvalue3, 'FALSE'));

                 if (wparamvalue <> 'TRUE' and wparamvalue2 <> 'TRUE' and wparamvalue3 <> 'TRUE') then
                    BDPODEEXECUTAR = 'FALSE';
               end
            else
            -- Recibo de salário
            if (coalesce(prcodautothread, 0) = 4) then
               begin
                 wparamvalue = null;
                 select first 1 BDPARAMVALUE from VSH_BASE_TPLANO_PARAMS where BDCODPLANOSCHIP = :PRCODPLANOSCHIP and Upper(BDPARAMNAME) = Upper('ckConferirReciboMensal') into :wparamvalue;
                 wparamvalue = upper(coalesce(wparamvalue, 'FALSE'));

                 wparamvalue2 = null;
                 select first 1 BDPARAMVALUE from VSH_BASE_TPLANO_PARAMS where BDCODPLANOSCHIP = :PRCODPLANOSCHIP and Upper(BDPARAMNAME) = Upper('ckEnviarEmailReciboMensal') into :wparamvalue2;
                 wparamvalue2 = upper(coalesce(wparamvalue2, 'FALSE'));

                 if (wparamvalue <> 'TRUE' and wparamvalue2 <> 'TRUE') then
                    BDPODEEXECUTAR = 'FALSE';
               end
          end
     end
  else
  -- Solicitação #222382 | Título: Webservice de comunicação do crédito do trabalhador | INÍCIO --
  if (coalesce(prcodautothread, 0) = 58) then
      BEGIN
        WDATAWSCREDITO = null;
        wbaixawscredito = null;
        WMATRIZWSCREDITO = NULL;

        BDPODEEXECUTAR = 'FALSE';

--        select a.bdreferencia from INC_REFERENCIA(:prrefproc,1) a into :wrefwscredito;

        SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WBDCODIGO_PERSONALIZACAO;
        if ((WBDCODIGO_PERSONALIZACAO <> 50) or (:prcodemp in (1005, 1006, 1007, 1020))) then
            begin
                select first 1 e.bdcnpjemp, e.bdcodmatriz, x.bddataconsulta, x.bddatabaixaarqws from TEMPRESAS e
                left outer join VRH_EMP_CREDITO_TRABALHADOR X on (x.bdcodemp = e.bdcodemp and (X.BDCOMPETENCIA = :prrefproc))
                where (e.BDCODEMP = :prcodemp)
                into :WCNPJEMPWSCREDITO, :WMATRIZWSCREDITO, :WDATAWSCREDITO, :wbaixawscredito;

                if ((WMATRIZWSCREDITO is null) and ((WDATAWSCREDITO is null) or (WDATAWSCREDITO < current_date)) and (wbaixawscredito is null)) then
                  begin
                    if ((WDATAWSCREDITO is null) or (extract(day from WDATAWSCREDITO) < 26)) then
                        BDPODEEXECUTAR = 'TRUE';
                  end
           end
      END
  -- Solicitação #222382 | Título: Webservice de comunicação do crédito do trabalhador | FIM --

  --Caso o processo para essa empresa/referência/thread já exista em fila e esteja em execução, não inclui o processo novamente.
  --Não faz sentido fazer a inclusão nesse caso
  WPROCESSOJAEXISTE = null;

  if (prcodautothread = 36) then
     begin
        select count(*) from vsh_emp_tlista_processos lp where lp.bdcodemp = :prcodemp and lp.bdcodagendamento = :prcodplanoschip and lp.bdcodautothread = :prcodautothread and lp.bdrefproc = :prrefproc and lp.bdcodstatus in (1,2) into :WPROCESSOJAEXISTE;
     end
  else
     select count(*) from vsh_emp_tlista_processos lp where lp.bdcodemp = :prcodemp and lp.bdcodautothread = :prcodautothread and lp.bdrefproc = :prrefproc and lp.bdcodstatus in (1,2) into :WPROCESSOJAEXISTE;

  if((WPROCESSOJAEXISTE IS NOT NULL) AND (WPROCESSOJAEXISTE > 0)) THEN
     BDPODEEXECUTAR = 'FALSE';

    -- Processos da DIRBI nunca devem ser incluidos, pois funcionam de forma assíncrona com a API da SERPRO
  if (prcodautothread = 59) then
     BDPODEEXECUTAR = 'FALSE';

  suspend;
end^


/* Restore proc. body: SP_FILA_PROCESSOS_SCHIP */
create or alter procedure SP_FILA_PROCESSOS_SCHIP (
    PRDATAFIXA date = null)
as
declare variable WDESCPROCESSO varchar(255);
declare variable WCODAGENDAMENTO integer;
declare variable WCODEMP integer;
declare variable WDIA integer;
declare variable WMES integer;
declare variable WANTECIPARDIAS DM_BOOLEAN;
declare variable WCODPERIODICIDADE integer;
declare variable WCODPLANOSCHIP integer;
declare variable WCODPROCDEPENDENTE integer;
declare variable WDATAEXEC date;
declare variable WULTIMAEXECUCAO date;
declare variable WWEEKDAY integer;
declare variable WORDEMAGENDAMENTO integer;
declare variable WREFPROC integer;
declare variable WCLASSIFICACAO varchar(255);
declare variable WCODAUTOTHREAD integer;
declare variable WEXECUCAOMANUAL DM_BOOLEAN;
declare variable WQTDPLANOS integer;
declare variable WORDEMEXECUCAO integer;
declare variable WTSID timestamp;
declare variable WIDPROC varchar(19);
declare variable WIDPROCPAI varchar(19);
declare variable WCODPLANOEXECANTERIOR integer;
declare variable WDATAATUAL date;
declare variable WEHFILIAL DM_BOOLEAN;
declare variable WSOMENTEMATRIZ DM_BOOLEAN;
declare variable WPODEINCLUIRPROC DM_BOOLEAN;
declare variable WFORAEXPEDIENTE DM_BOOLEAN;
declare variable WDATAINI timestamp;
declare variable WPARAMVALUE integer;
declare variable WINICIOAGENDAMENTO integer;
declare variable WCODORDEMEMPLISTAMANUAL integer;
declare variable WCODLISTAEMPMANUAL integer;
declare variable WSISTEMA integer;
declare variable WEMPRESAINATIVA boolean;
declare variable WIGNORARINATIVAS boolean = false;
declare variable WREFDATAATUAL integer;
declare variable WEXISTEREGISTRO boolean;
declare variable WEDUCACIONAL varchar(1);
declare variable WEXISTEEMP varchar(5);
begin
  select upper(p.bdvalor) = 'TRUE' from tparger p where p.bdcampo = 'BDIGNORARINATIVASSCHIP' into :wignorarinativas;

  select first 1 X.bdsituacao from TPERSONALIZACAO X into :WEDUCACIONAL;

  wdataatual = CAST('NOW' AS DATE);
  wDataIni   = null;         
  IF (prdatafixa is not null) then
    wdataatual = prdatafixa;
  WREFDATAATUAL = extract(YEAR from wdataatual) * 100 + extract(month from wdataatual);

  /*Time out no processo, se passou de 1 dia, move para não concluído*/
  UPDATE VSH_EMP_TLISTA_PROCESSOS LP
  SET LP.BDCODSTATUS = 6,
      LP.BDDESCPROCESSO = 'O processo excedeu o tempo máximo de processamento'
  WHERE LP.BDCODSTATUS = 2
  AND CAST('NOW' AS TIMESTAMP) - LP.BDDATAINI >= 1
  AND ((lp.bdcodstatus <> 6) or (lp.bddescprocesso <> 'O processo excedeu o tempo máximo de processamento')) ;

  wTSID = localtimestamp;
  FOR SELECT A.BDCODAGENDAMENTO, A.BDCODLISTAEMPMANUAL, AE.BDCODEMP, COALESCE(A.BDDIA, -1) + 1, COALESCE(A.BDMES, -1) + 1,
             UPPER(COALESCE(A.BDANTECIPARDIAS, 'FALSE')), A.BDCODPERIODICIDADE,
             AP.BDCODPLANOSCHIP, A.BDULTIMAEXECUCAO, COALESCE(PT.BDCLASSIFICACAO, ''),
             (SELECT BDDATA FROM SP_PARSE_DATE(ADDMONTH(CURRENT_DATE, IIF(A.BDINICIOAGENDAMENTO = 0, -1, 0)), 'YYYYMM')) BDREFPROC,
             PT.BDCODAUTOTHREAD, A.BDEXECUCAOMANUAL, AP.BDORDEMEXECUCAO,
             IIF(E.BDCODMATRIZ IS NOT NULL, 'TRUE', 'FALSE') BDEHFILIAL, UPPER(T.BDSOMENTEMATRIZ),
             A.BDFORAEXPEDIENTE, coalesce(PR.BDPARAMVALUE, 0) BDPARAMVALUE, A.BDINICIOAGENDAMENTO,
             TP.bdcodsis, 
    case
               when (coalesce(upper(er.bdsitemp), 'FALSE') = 'TRUE') or (coalesce(upper(E.bdexcluiremp), 'FALSE') = 'TRUE') then TRUE
               else FALSE
             end as BDSITEMP
      FROM (
            SELECT A.BDCODAGENDAMENTO, A.BDCODLISTAEMPMANUAL ,A.BDDIA, A.BDMES,
                   A.BDANTECIPARDIAS, A.BDCODPERIODICIDADE,
                   A.BDULTIMAEXECUCAO, A.BDINICIOAGENDAMENTO,
                   UPPER(COALESCE(A.BDEXECUCAOMANUAL, 'FALSE')) BDEXECUCAOMANUAL,
                   UPPER(COALESCE(A.BDFORAEXPEDIENTE, 'FALSE')) BDFORAEXPEDIENTE
            FROM VSH_BASE_TAGENDAMENTO A
            WHERE A.BDINATIVO <> 'TRUE'
            AND ((A.BDHORA <= CAST('NOW' AS TIME) OR (UPPER(A.BDREADONLY) = 'TRUE')) OR (COALESCE(UPPER(A.BDEXECUCAOMANUAL), 'FALSE') = 'TRUE'))
           ) A
      LEFT OUTER JOIN VSH_BASE_TAGENDAMENTO_PLANO AP ON(AP.BDCODAGENDAMENTO = A.BDCODAGENDAMENTO)
      INNER JOIN VSH_EMP_TAGENDAMENTO_EMPRESAS AE ON(AE.BDCODAGENDAMENTO = A.BDCODAGENDAMENTO)
      LEFT OUTER JOIN VSH_BASE_TPLANO P ON(P.BDCODPLANOSCHIP = AP.BDCOdpLANOSCHIP)
      JOIN VSH_BASE_TPLANO_THREAD PT ON(PT.BDCODPLANOSCHIP = P.BDCODPLANOSCHIP)
      JOIN VSH_BASE_TTHREAD T ON(T.BDCODAUTOTHREAD = PT.BDCODAUTOTHREAD)
      LEFT OUTER JOIN VSH_BASE_TIPO_TPROCESSO TP ON(TP.BDCODPROCESSO = P.BDCODPROCESSO)
      LEFT OUTER JOIN TEMPRESAS E ON(E.BDCODEMP = AE.BDCODEMP)
      LEFT OUTER JOIN sp_getreferencia(E.bdcodemp, :WREFDATAATUAL) egr on (1=1)
      LEFT OUTER JOIN TEMPRESAS_REF er on (er.bdcodemp = e.bdcodemp and er.bdrefemp = egr.bdrefemp)
      LEFT OUTER JOIN(SELECT PR.*
                FROM VSH_BASE_TPLANO_PARAMS PR
                WHERE PR.BDPARAMNAME = 'cbTipoGuia') PR on (PR.BDCODPLANOSCHIP = AP.BDCODPLANOSCHIP)
      WHERE EXISTS (
                    SELECT DT.BDINIEXECAGENDAMENTO
                    FROM (
                          SELECT FIRST 1 DT.BDINIEXECAGENDAMENTO
                          FROM (
                                SELECT FIRST 1 CE.BDINIEXECAGENDAMENTO, 1 BDORD
                                FROM VSH_EMP_TCONFEMPRESAS CE
                                WHERE CE.BDCODEMP = AE.BDCODEMP
                                AND CE.BDCODSIS = TP.BDCODSIS
                                UNION ALL
                                SELECT CAST((SELECT BDDATA FROM SP_PARSE_DATE(CURRENT_DATE, 'YYYYMM')) AS INTEGER) BDINIEXECAGENDAMENTO, 2 BDORD
                                FROM RDB$DATABASE
                               ) DT
                          ORDER BY DT.BDORD
                         ) DT
                    WHERE DT.BDINIEXECAGENDAMENTO <= CAST((SELECT BDDATA FROM SP_PARSE_DATE(CURRENT_DATE, 'YYYYMM')) AS INTEGER)
                   )
      ORDER BY AE.BDCODAGENDAMENTO, AE.BDCODEMP, AP.BDORDEMEXECUCAO, AP.BDCODPLANOSCHIP, PT.BDCLASSIFICACAO
      INTO :wCodAgendamento, :WCODLISTAEMPMANUAL ,:wCodEmp, :wDia, :wMes, :wAnteciparDias,
           :wCodPeriodicidade, :wCodPlanoSChIp, :wUltimaExecucao,
           :wClassificacao, :wRefProc, :wCodAutoThread, :wExecucaoManual,
           :wOrdemExecucao, :wEhFilial, :wSomenteMatriz, :wForaExpediente, :wParamValue,
           :WINICIOAGENDAMENTO, :wsistema, :wempresainativa
  DO
    BEGIN
      if ((:wignorarinativas and :wempresainativa and :wsistema <> 5) or ((:wsistema = 2) and (:wcodemp is NULL))) then
      continue;

    -- Solicitação #222382 | Título: Webservice de comunicação do crédito do trabalhador
    if (WCODAUTOTHREAD = 58) then
    begin
      if ((extract(day from current_date) < 21) or (WEDUCACIONAL = 'W')) then
        continue;

      select case when exists(select 1 from TEMPRESAS where BDCODEMP = :WCODEMP) THEN 'TRUE' else 'FALSE' end from RDB$DATABASE into :WEXISTEEMP;
      if (WEXISTEEMP = 'FALSE') then
        begin
           delete from VSH_EMP_TAGENDAMENTO_EMPRESAS A where A.BDCODEMP = :WCODEMP and A.BDCODAGENDAMENTO = :WCODAGENDAMENTO;
           continue;
        end

      select a.bdreferencia from INC_REFERENCIA(:wrefproc,1) a into :wrefproc;
    end

    if ((:WCODAUTOTHREAD in (38, 41, 43)) and
        (coalesce(:WINICIOAGENDAMENTO, 0) = 0)) then
      :WREFPROC = :WREFPROC - 100;

      IF (prdatafixa is not null) then
        wdataatual = prdatafixa;
      IF ((:wCodAutoThread = 30) and (:wparamvalue = 1)) then /*TAutoThreadDCTFWeb_Baixas - Anual (13° salário)*/
        BEGIN
          :wRefProc = EXTRACT(YEAR FROM wdataatual)||13;
        END

      if (WCODLISTAEMPMANUAL > 0) then
        BEGIN
          wCodOrdemEmpListaManual = 0;
          select EXEC.bdordememp FROM VSH_BASE_EMP_TEXECMANUAL EXEC where EXEC.bdcodlistaempmanual = :WCODLISTAEMPMANUAL and EXEC.bdcodemp =  :wCodEmp INTO :wCodOrdemEmpListaManual;
        END


      /*Vai pular essa empresa porque a thread só executa com matriz*/ /*Vai pular caso for executado manualmente e selecionado as empresas para processar*/
      IF (((:wSomenteMatriz = 'TRUE') AND (:wEhFilial = 'TRUE')) OR ((:WCODLISTAEMPMANUAL > 0) AND (coalesce(:wcodordememplistamanual,0) = 0)))   THEN
        BEGIN
          wUltimaExecucao = CURRENT_DATE;
          wDataExec       = CURRENT_DATE;
        END
      ELSE
        BEGIN
          IF (:wExecucaoManual = 'TRUE') THEN
            BEGIN
              wUltimaExecucao = NULL;
              wDataExec       = CURRENT_DATE;
              wAnteciparDias  = 'FALSE';

              IF ((:wForaExpediente = 'TRUE') AND (Extract(hour from Current_time) > 7) AND (Extract(hour from Current_time) < 18)) THEN
                 BEGIN
                    wDataIni = dateadd(60 - Extract(minute from Current_time) minute to dateadd (17 - Extract(hour from Current_time) hour to current_timestamp));
            END
            END
          ELSE
            BEGIN
              IF (:wCodPeriodicidade BETWEEN 0 AND 6) THEN --Dias da semana
                SELECT BDDATA FROM SP_PROX_DIA_DA_SEMANA(CURRENT_DATE, :wCodPeriodicidade, 'TRUE') INTO :wDataExec;
              ELSE
                BEGIN
                  IF (:wCodPeriodicidade = 7) THEN --Mensalmente
                    BEGIN
                      IF ((:wDia = 31) or (EXTRACT(month FROM wdataatual)=2 and :wDia>28)) THEN --Pega o último dia do mês
                         SELECT ULTDIA FROM ULTIMO_DIA_MES(SUBSTRING(CURRENT_DATE FROM 6 FOR 2), SUBSTRING(CURRENT_DATE FROM 1 FOR 4)) INTO :wDia;

                      wDataExec = CAST((SUBSTRING(CURRENT_DATE FROM 6 FOR 2) || '/' || :wDia || '/'|| SUBSTRING(CURRENT_DATE FROM 1 FOR 4)) AS DATE);
                    END
                  ELSE
                  IF (:wCodPeriodicidade = 9) THEN --Anualmente
                    BEGIN
                       wDataExec = :wMes || '/' || :wDia || '/' || EXTRACT(YEAR FROM CURRENT_DATE);

                       if (prdatafixa is not null) then
                          wdataatual = prdatafixa;
                    END
                  ELSE
                  IF (:wCodPeriodicidade = 10) THEN --Segunda a Sexta
                    BEGIN
                      wDataExec = CURRENT_DATE;
                      if (EXTRACT(WEEKDAY from CURRENT_DATE) = 0) then --Domingo
                        wDataExec = DATEADD(day, 1, wDataExec);
                      if (EXTRACT(WEEKDAY from CURRENT_DATE) = 6) then --Sábado
                        wDataExec = DATEADD(day, 2, wDataExec);
                    END
                  ELSE  --Diário
                    wDataExec = CURRENT_DATE;
                END
            END
        END

      IF (:wAnteciparDias = 'TRUE') THEN
        BEGIN
          wWeekDay = EXTRACT(WEEKDAY FROM :wDataExec);

          IF (:wWeekDay IN (0, 6)) THEN --0 - Domingo, 1 - Sábado. Antecipam para sexta
            wDataExec = ADDDAY(:wDataExec, IIF(:wWeekDay = 0, -2, -1));

          SELECT BDDATA
          FROM SP_DATA_UTIL(:wCodEmp, :wDataExec) --Verifica se tem feriado na data
          INTO :wDataExec;
        END

      IF ((:wUltimaExecucao IS NULL) OR (:wUltimaExecucao <> :wDataExec)) THEN
        BEGIN
          IF ((:wDataExec = :wdataatual) or ((:PRDATAFIXA IS NOT NULL) and (:wDataExec = CAST('NOW' AS DATE))))  THEN
            BEGIN
              wDescProcesso = 'Aguardando processamento...';
              wCodProcDependente = NULL;

              IF (POSITION('.', :wClassificacao) > 0) THEN --É um processo dependente de outro
                BEGIN
                  SELECT FIRST 1 LP.BDORDEMAGENDAMENTO
                  FROM VSH_EMP_TLISTA_PROCESSOS LP
                  JOIN VSH_BASE_TPLANO_THREAD PT ON(PT.BDCODPLANOSCHIP = LP.BDCODPLANOSCHIP AND
                                                    PT.BDCLASSIFICACAO = REVERSE(SUBSTRING(REVERSE(:wClassificacao) FROM POSITION('.', REVERSE(:wClassificacao))+1 FOR CHAR_LENGTH(:wClassificacao))) AND
                                                    PT.BDCODAUTOTHREAD = LP.BDCODAUTOTHREAD)
                  WHERE LP.BDCODAGENDAMENTO = :wCodAgendamento
                  AND LP.BDCODEMP = :wCodEmp
                  AND LP.BDCODPLANOSCHIP = :wCodPlanoSChIp
                  AND LP.BDCODSTATUS = 1 --Aguardando
                  INTO :wCodProcDependente;

                  IF (COALESCE(:wCodProcDependente, 0) > 0) THEN
                    wDescProcesso = 'Aguardando conclusão de processos anteriores...';
                END

              /*Caso tenha mais de um plano no agendamento, monta uma ordem de execução*/
              SELECT COUNT(AP.BDORDEMEXECUCAO)
              FROM VSH_BASE_TAGENDAMENTO_PLANO AP
              WHERE AP.BDCODAGENDAMENTO = :wCodAgendamento
              INTO :wQtdPlanos;

              wIDProcPai            = NULL;
              wCodPlanoExecAnterior = NULL;
              IF (COALESCE(:wQtdPlanos, 0) > 0) THEN
                BEGIN
                  SELECT FIRST 1 AP.BDCODPLANOSCHIP
                  FROM VSH_BASE_TAGENDAMENTO_PLANO AP
                  WHERE AP.BDCODAGENDAMENTO = :wCodAgendamento
                  AND AP.BDORDEMEXECUCAO < :wOrdemExecucao
                  INTO :wCodPlanoExecAnterior;

                  --Busca o plano que deve rodar antes
                  IF (COALESCE(:wCodPlanoExecAnterior, 0) > 0) THEN
                    BEGIN
                      SELECT FIRST 1 LP.BDIDPROC
                      FROM VSH_EMP_TLISTA_PROCESSOS LP
                      WHERE LP.BDCODAGENDAMENTO = :wCodAgendamento
                      AND LP.BDCODEMP = :wCodEmp
                      AND LP.BDCODPLANOSCHIP = :wCodPlanoExecAnterior
                      AND LP.BDCODSTATUS = 1 --Aguardando
                      ORDER BY LP.BDINCLUSAO DESC
                      INTO :wIDProcPai;

                      wDescProcesso = 'Aguardando a conclusão de outro(s) plano(s) do mesmo agendamento...';
                    END
                  ELSE
                    BEGIN
                      wIDProcPai            = NULL;
                      wCodPlanoExecAnterior = NULL;
                    END
                END

              SELECT MAX(LP.BDORDEMAGENDAMENTO) + 1
              FROM VSH_EMP_TLISTA_PROCESSOS LP
              WHERE LP.BDCODAGENDAMENTO = :wCodAgendamento
              AND LP.BDCODEMP = :wCodEmp
              AND LP.BDCODPLANOSCHIP = :wCodPlanoSChIp
              AND LP.BDCODSTATUS = 1 --Aguardando
              INTO :wOrdemAgendamento;

              IF (COALESCE(:wOrdemAgendamento, 0) = 0) THEN
                BEGIN
                  SELECT MAX(LP.BDORDEMAGENDAMENTO) + 1
                  FROM VSH_EMP_TLISTA_PROCESSOS LP
                  WHERE LP.BDCODAGENDAMENTO = :wCodAgendamento
                  AND LP.BDCODEMP = :wCodEmp
                  AND LP.BDCODPLANOSCHIP = :wCodPlanoSChIp
                  INTO :wOrdemAgendamento;

                  wOrdemAgendamento = COALESCE(:wOrdemAgendamento, 1);
                END

              wIDProc = HASH(:wCodAgendamento||'.'||:wCodPlanoSChIp||'.'||:wCodEmp||'.'||:wTSID);

              wpodeincluirproc = null;
              execute statement 'select BDPODEEXECUTAR from SP_VSH_PODE_INICIAR_PROCESSO('||:wcodagendamento||','||:wcodplanoschip||','||:wrefproc||','||:wcodautothread||','||:wcodemp||')'
              into :wpodeincluirproc;

              wpodeincluirproc = upper(coalesce(wpodeincluirproc, 'FALSE'));

        if (WPODEINCLUIRPROC = 'TRUE') then
        begin
          insert into VSH_EMP_TLISTA_PROCESSOS (BDCODAGENDAMENTO, BDCODPLANOSCHIP, BDCODEMP, BDCODSTATUS,
                                                BDDESCPROCESSO, BDORDEMAGENDAMENTO, BDINCLUSAO, BDREFPROC,
                                                BDPROCESSOPAI, BDCODAUTOTHREAD, BDIDPROC, BDIDPROCPAI, BDCODEXEC,
                                                BDDATAINI)
          values (:WCODAGENDAMENTO, :WCODPLANOSCHIP, :WCODEMP, 1, :WDESCPROCESSO, :WORDEMAGENDAMENTO,
                  cast('NOW' as timestamp), :WREFPROC, :WCODPROCDEPENDENTE, :WCODAUTOTHREAD, :WIDPROC, :WIDPROCPAI,
                  IIF(:wExecucaoManual = 'TRUE', 2, 1), :WDATAINI);

          if (WCODAUTOTHREAD = 58) then
          begin
             update or insert into VRH_EMP_CREDITO_TRABALHADOR (BDCODEMP, BDCOMPETENCIA, BDDATACONSULTA, BDLOGPROCESSO) values (:WCODEMP, :WREFPROC, current_date, current_date||'_'||current_time||': (SP_FILA_PROCESSOS_SCHIP) Processo adicionado na fila para execução');
          end
        end

              IF (:wExecucaoManual = 'TRUE') THEN
                UPDATE VSH_BASE_TAGENDAMENTO A SET A.BDEXECUCAOMANUAL = 'FALSE', A.bdcodlistaempmanual = NULL,A.BDFORAEXPEDIENTE = 'FALSE' WHERE A.BDCODAGENDAMENTO = :wCodAgendamento;
              ELSE
                UPDATE VSH_BASE_TAGENDAMENTO A SET A.BDULTIMAEXECUCAO = :wdataatual WHERE A.BDCODAGENDAMENTO = :wCodAgendamento;
            END
        END
    END

  UPDATE VSH_EMP_TLISTA_PROCESSOS LP
  SET LP.BDCODSTATUS = 6,
      LP.BDDESCPROCESSO = 'Este processo não pode ser realizado pois depende de processos que falharam anteriormente'
  WHERE LP.BDPROCESSOPAI IS NOT NULL
  AND EXISTS (
              SELECT *
              FROM VSH_EMP_TLISTA_PROCESSOS LPE
              WHERE LPE.BDCODAGENDAMENTO = LP.BDCODAGENDAMENTO
              AND LPE.BDCODEMP = LP.BDCODEMP
              AND LPE.BDCODPLANOSCHIP = LP.BDCODPLANOSCHIP
              AND LPE.BDORDEMAGENDAMENTO = LP.BDPROCESSOPAI
              AND LPE.BDCODSTATUS = 6
             )
  AND ((LP.BDCODSTATUS <> 6) OR
       (LP.BDDESCPROCESSO <> 'Este processo não pode ser realizado pois depende de processos que falharam anteriormente'));

  /*Quando algum plano da erro (em qualquer processo), automaticamente o próximo plano da fila falha...*/
  UPDATE VSH_EMP_TLISTA_PROCESSOS LP
  SET LP.BDCODSTATUS = 6,
      LP.BDDESCPROCESSO = 'Este processo não pode ser realizado pois outro(s) plano(s) do mesmo agendamento falharam anteriormente'
  WHERE LP.BDIDPROCPAI IS NOT NULL
  AND LP.BDINTEGRACONTADOR <> 'TRUE'
  AND EXISTS (
              SELECT *
              FROM VSH_EMP_TLISTA_PROCESSOS LPE
              WHERE LPE.BDIDPROC = LP.BDIDPROCPAI
              AND LPE.BDCODSTATUS = 6
             )
  AND ((LP.BDCODSTATUS <> 6) OR
       (LP.BDDESCPROCESSO <> 'Este processo não pode ser realizado pois outro(s) plano(s) do mesmo agendamento falharam anteriormente'));
end^

create or alter procedure PADRONIZA_TEXTO (
    PRTEXTO varchar(100))
returns (
    BDRESULT varchar(100))
as
declare variable WCOUNT integer;
declare variable WESPACO smallint;
BEGIN
  wcount = 1;
  WESPACO = 1;
  bdresult = '';
  WHILE (wcount <= char_length(prtexto)) DO
    BEGIN        
      if (SUBSTRING(prtexto FROM wcount FOR 1) = ' ') then          
        begin
            WESPACO = 1;
            bdresult = :bdresult || SUBSTRING(prtexto FROM wcount FOR 1);
        end
      ELSE
      if (WESPACO = 1) then
        begin
            bdresult = :bdresult || UPPER(SUBSTRING(prtexto FROM wcount FOR 1));
            WESPACO = 0;
        end
      ELSE
        BEGIN           
            bdresult = :bdresult || LOWER(SUBSTRING(prtexto FROM wcount FOR 1));
        END
      wcount = wcount + 1;
    END
  SUSPEND;
END^

create or alter procedure SP_ATUALIZA_NOME_PARTICIPANTES (
    PRREFERENCIA integer,
    PRTIPO integer,
    PRTODASREF varchar(5))
as
BEGIN              
  -- #183828 - Rotina de atualizar nome de participante nao deve passar na trigger, por conta de performance
  rdb$set_context('USER_SESSION', 'W_ATUALIZANDO_PARTICIPANTE', 'TRUE');
  if (UPPER(:PRTODASREF) = 'TRUE') then
    BEGIN
      if (:PRTIPO = 0) then
        BEGIN
          UPDATE TTERCEIRO_REF TER
          SET TER.BDNOMETER = UPPER(TER.BDNOMETER)
          WHERE TER.BDNOMETER <> UPPER(TER.BDNOMETER);
        END
      ELSE      
      if (:PRTIPO = 1) then
        BEGIN
          UPDATE TTERCEIRO_REF TER
          SET TER.BDNOMETER = LOWER(TER.BDNOMETER)
          WHERE TER.BDNOMETER <> LOWER(TER.BDNOMETER);
        END
      ELSE
      if (:PRTIPO = 2) then
        BEGIN                  
          UPDATE TTERCEIRO_REF TER
          SET TER.BDNOMETER = (SELECT BDRESULT FROM PADRONIZA_TEXTO(TER.BDNOMETER))
          WHERE TER.BDNOMETER <> (SELECT BDRESULT FROM PADRONIZA_TEXTO(TER.BDNOMETER));
        END
    END
  ELSE
    BEGIN  
      if (:PRTIPO = 0) then
        BEGIN
          UPDATE TTERCEIRO_REF TER
          SET TER.BDNOMETER = UPPER(TER.BDNOMETER)
          WHERE TER.BDNOMETER <> UPPER(TER.BDNOMETER) and TER.BDREFEMP = :PRREFERENCIA;
        END
      ELSE      
      if (:PRTIPO = 1) then
        BEGIN
          UPDATE TTERCEIRO_REF TER
          SET TER.BDNOMETER = LOWER(TER.BDNOMETER)
          WHERE TER.BDNOMETER <> LOWER(TER.BDNOMETER) and TER.BDREFEMP = :PRREFERENCIA;
        END
      ELSE
      if (:PRTIPO = 2) then
        BEGIN                  
          UPDATE TTERCEIRO_REF TER
          SET TER.BDNOMETER = (SELECT BDRESULT FROM PADRONIZA_TEXTO(TER.BDNOMETER))
          WHERE TER.BDNOMETER <> (SELECT BDRESULT FROM PADRONIZA_TEXTO(TER.BDNOMETER)) and TER.BDREFEMP = :PRREFERENCIA;
        END
    END        
  rdb$set_context('USER_SESSION', 'W_ATUALIZANDO_PARTICIPANTE', 'FALSE');
END^

CREATE OR ALTER procedure SP_GET_ORDEM_SEQ_PLANO_SCHIP (
    PRCODAGENDAMENTO integer,
    PRCODPLANOSCHIP integer)
returns (
    BDORDEMEXECUCAO integer)
as
declare variable WDIFORD integer;
declare variable WFIRSTORD integer;
declare variable WORDTABLE integer;
begin
  SELECT MIN(AP.BDORDEMEXECUCAO)
  FROM VSH_BASE_TAGENDAMENTO_PLANO AP
  WHERE AP.BDCODAGENDAMENTO = :PRCODAGENDAMENTO
  INTO :wFirstOrd;

  wFirstOrd = COALESCE(:wFirstOrd, 1);

  SELECT AP.BDORDEMEXECUCAO
  FROM VSH_BASE_TAGENDAMENTO_PLANO AP
  WHERE AP.BDCODAGENDAMENTO = :PRCODAGENDAMENTO
  AND AP.BDCODPLANOSCHIP = :PRCODPLANOSCHIP
  INTO :wOrdTable;

  wOrdTable = COALESCE(:wOrdTable, 1);

  wDifOrd = (:wOrdTable - :wFirstOrd);

  BDORDEMEXECUCAO = 1;
  WHILE (:wDifOrd > 0) DO
    BEGIN
      BDORDEMEXECUCAO = :BDORDEMEXECUCAO + 1;

      wDifOrd = :wDifOrd - 1;
    END

  SUSPEND;
end^

/* Restore proc. body: SP_CRIA_REFERENCIA_CLIENTES_REF */
CREATE OR ALTER procedure SP_CRIA_REFERENCIA_CLIENTES_REF (
    PRCODCLI integer,
    PRAAAAMM integer)
as
declare variable WTABELA varchar(300);
declare variable WSQL varchar(5000);
declare variable WCAMPOS_TAB varchar(3000);
declare variable WCAMPO varchar(300);
declare variable WREFCLI integer;
begin
  ---inserir referencia na tabelas de cliente ref, se não tiver
  SELECT MAX(BDREFCLI) FROM VFIN_BASE_TCLIENTE_REF WHERE BDCODCLI = :prcodcli AND BDREFCLI <= :praaaamm INTO :WREFCLI;

  if (WREFCLI <> praaaamm) then
     begin
       wsql = '';
       wsql = ' select RDB$FIELD_NAME BDNOMECAMPO ';
       wsql = wsql||' from RDB$RELATION_FIELDS ';
       wsql = wsql||' where RDB$RELATION_NAME = '||'''VFIN_BASE_TCLIENTE_REF'''||' and ';
       wsql = wsql||' (RDB$FIELD_NAME <> '||'''BDCODCLI'''||') and ';
       wsql = wsql||' (RDB$FIELD_NAME <> '||'''BDREFCLI'''||') ';

       wCAMPOS_TAB = '';
       for EXECUTE STATEMENT wsql into :WCAMPO do
           begin
             WCAMPO = trim(WCAMPO);
             wCAMPOS_TAB = wCAMPOS_TAB||:WCAMPO||', ';
           end
       wsql = '';
       wsql = ' insert into '||'VFIN_BASE_TCLIENTE_REF'||' ('||wCAMPOS_TAB||'BDCODCLI, BDREFCLI) ';
       wsql = wsql||' select '||wCAMPOS_TAB||prcodcli||' as BDCODCLI, '||praaaamm||' as BDREFCLI ';
       wsql = wsql||' from '||'VFIN_BASE_TCLIENTE_REF'||' X where BDCODCLI = '||prcodcli||' and ';
       wsql = wsql||' BDREFCLI = (select max(BDREFCLI) from '||'VFIN_BASE_TCLIENTE_REF'||' where BDCODCLI = X.BDCODCLI and BDREFCLI < '||praaaamm||') ';
       EXECUTE STATEMENT wsql;
     end
    wsql = '';
    wsql = 'select X.RDB$RELATION_NAME BDNOMETABELA ';
    wsql = wsql||'from RDB$RELATION_CONSTRAINTS X ';
    wsql = wsql||'join RDB$REF_CONSTRAINTS Y on (X.RDB$CONSTRAINT_NAME = Y.RDB$CONSTRAINT_NAME) ';
    wsql = wsql||'join RDB$RELATION_CONSTRAINTS Z on (Z.RDB$CONSTRAINT_NAME = Y.RDB$CONST_NAME_UQ) ';
    wsql = wsql||'where X.RDB$CONSTRAINT_TYPE = ('||'''FOREIGN KEY'''||') and ';
    wsql = wsql||'Y.RDB$DELETE_RULE = ('||'''CASCADE'''||') and ';
    wsql = wsql||'Z.RDB$RELATION_NAME = '||'''VFIN_BASE_TCLIENTE_REF''';
    
    FOR EXECUTE STATEMENT wsql into :WTABELA do
        begin
            WTABELA = trim(WTABELA);
            wsql = '';
            wsql = ' select RDB$FIELD_NAME BDNOMECAMPO ';
            wsql = wsql||' from RDB$RELATION_FIELDS ';
            wsql = wsql||' where RDB$RELATION_NAME = '||''''||:WTABELA||''''||' and ';
            wsql = wsql||' (RDB$FIELD_NAME <> '||'''BDCODCLI'''||') and ';
            wsql = wsql||' (RDB$FIELD_NAME <> '||'''BDREFCLI'''||') ';
            wCAMPOS_TAB = '';
            for EXECUTE STATEMENT wsql into :WCAMPO do
               begin
                 WCAMPO = trim(WCAMPO);
                 wCAMPOS_TAB = wCAMPOS_TAB||:WCAMPO||', ';
               end
            wsql = '';
            wsql = ' insert into '||WTABELA||' ('||wCAMPOS_TAB||'BDCODCLI, BDREFCLI) ';
            wsql = wsql||' select '||wCAMPOS_TAB||prcodcli||' as BDCODCLI, '||praaaamm||' as BDREFCLI ';
            wsql = wsql||' from '||WTABELA||' X where BDCODCLI = '||prcodcli||' and ';
            wsql = wsql||' BDREFCLI = (select max(BDREFCLI) from '||WTABELA||' where BDCODCLI = X.BDCODCLI) and BDREFCLI < '||praaaamm;

            EXECUTE STATEMENT wsql;
        end

end^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCST_INCONSISTENCIA (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRDTINV DATE,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
  DELETE FROM TEXPORTACAO_SPED_INCO WHERE bdID = :prARQUIVO;
  
  SETORDEMSEQUENCIAL(0);

  /* Registro "0000" - Quando a empresa for optante pelo Simples Nacional (cadastro da empresa / enquadramento federal / ME-EPP),
   e o perfil de apresentacao for diferente de |Perfil C| (cadastro da empresa / Fiscal / Federal / Sped ICMS/IPI - Perfil de apresentacao)
   apresentar a inconsistencia (igual do Sped Fiscal): "Empresas optantes do Simples Nacional devem ser perfil de apresentacao Perfil C!" */
  INSERT INTO TEXPORTACAO_SPED_INCO(bdID, bdORDEMINCO, bdREG, bdCODINCO)
  SELECT :prARQUIVO AS bdID,
         GETORDEMSEQUENCIAL(:prCODEMP) AS bdCHAVEREG,
         '0000' AS BDREG,
         26
  FROM SP_CONSULTAEMPRESAS_SIS(EXTRACT(YEAR FROM :prDTFIM)||LPAD(EXTRACT(MONTH FROM :prDTFIM),2,'0'), :prCODEMP, NULL) tref  
  LEFT OUTER JOIN VW_EMP_REF_TOTAL trefsis ON (trefsis.bdCODEMP = tref.bdCODEMP)
  WHERE tref.bdCODENQFED IN (1,2) -- 1-ME / 2-EPP
    AND tref.bdPERFILSPED IN (0,1); -- 0-Perfil A / 1-Perfil B

  /* Registro "0190" - Campo 06 UNID_INV - cadastro do produto - informacao obrigatoria -
   quando nao houver no produto que esta sendo exportado, apresentar inconsistencia |Unidade de medida obrigatoria nao informada para o produto X|*/
  INSERT INTO TEXPORTACAO_SPED_INCO(bdID, bdORDEMINCO, bdREG, bdCODINCO, bdCODPROD, bdCODSAIDA)
  SELECT :prARQUIVO AS bdID,
         GETORDEMSEQUENCIAL(:prCODEMP) AS bdCHAVEREG,
         '0200' AS BDREG, -- Alterado para ir no "0200"...
         27,
         s.bdCODPROD,
         pro.bdCODSAIDA
  FROM TEXPORTACAO_SPED s
  LEFT OUTER JOIN TCADPRO cadpro ON (cadpro.bdCODPROD = s.bdCODPROD)
  LEFT OUTER JOIN TCADPRO_VINC pro ON (pro.bdCODPROD = cadpro.bdCODPROD AND pro.bdCODEMP = :prCODEMP)
  LEFT OUTER JOIN TUNIDADEMEDIDA um ON (um.bdCODUNIMED = s.bdCODUNIMED)
  LEFT OUTER JOIN TUNIDADEMEDIDA umEmp ON (umEmp.bdCODUNIMED = pro.bdCODUNIMED)
  WHERE s.bdID = :prARQUIVO
    AND s.bdCODEMP = :prCODEMP
    AND s.bdCODPROD IS NOT NULL
    AND (((um.bdCODUNIMED IS NULL) OR (um.bdCODUNIMED <= 0)) AND
         ((umEmp.bdCODUNIMED IS NULL) OR (umEmp.bdCODUNIMED <= 0)));
    
  /* Registro "0200" - Campo 08 COD_NCM - cadastro do produto - informacao obrigatoria -
   quando nao houver no produto que esta sendo exportado, apresentar inconsistencia |Codigo de NCM obrigatorio nao informado para o produto X| */
  INSERT INTO TEXPORTACAO_SPED_INCO(bdID, bdORDEMINCO, bdREG, bdCODINCO, bdCODPROD, bdCODSAIDA)
  SELECT :prARQUIVO AS bdID,
         GETORDEMSEQUENCIAL(:prCODEMP) AS bdCHAVEREG,
         '0200' AS BDREG,
         28,
         pro.bdCODPROD,
         pro.bdCODSAIDA
  FROM ( 
        SELECT cadpro.bdCODPROD, cadpro.bdCODIGOEAN, pro.bdNCMPROD, pro.bdCODSAIDA
        FROM (SELECT DISTINCT(s.bdCODPROD)
              FROM TEXPORTACAO_SPED s
              WHERE s.bdCODPROD IS NOT NULL
                AND s.bdID = :prARQUIVO
                AND s.bdCODEMP = :prCODEMP) s
        JOIN TCADPRO cadpro ON (cadpro.bdCODPROD = s.bdCODPROD)
        JOIN TCADPRO_VINC pro ON (PRO.BDCODPROD = CADPRO.BDCODPROD AND pro.bdCODEMP = :prCODEMP)
        ) PRO
  LEFT OUTER JOIN TNCM ncm ON (ncm.bdNCMPROD = pro.bdNCMPROD)
  WHERE ncm.bdCLASSIFICACAO IS NULL
    AND pro.bdNCMPROD IS NULL;
    
  /* Registro "0200" - Campo 12 ALIQ_ICMS - aliquota efetiva no lancamento da nota fiscal -
    informacao obrigatoria - quando nao houver no produto que esta sendo exportado, apresentar inconsistencia |Aliquota ICMS obrigatoria nao informada para o produto X| */
  INSERT INTO TEXPORTACAO_SPED_INCO(bdID, bdORDEMINCO, bdREG, bdCODINCO, bdCODPROD, bdCODSAIDA)
  SELECT :prARQUIVO AS bdID,
         GETORDEMSEQUENCIAL(:prCODEMP) AS bdCHAVEREG,
         '0200' AS BDREG,
         29,
         pro.bdCODPROD,
         pro.bdCODSAIDA
  FROM ( 
        SELECT cadpro.bdCODPROD, cadpro.bdCODIGOEAN, s.BDALIQ_ST_EF, pro.bdCODSAIDA
        FROM (SELECT s.bdCODPROD, MAX(Coalesce(S.BDALIQ_ST_EF,0)) BDALIQ_ST_EF
              FROM TEXPORTACAO_SPED s
              WHERE s.bdCODPROD IS NOT NULL
                AND s.bdID = :prARQUIVO
                AND s.bdCODEMP = :prCODEMP
              GROUP BY S.BDCODPROD) s
        JOIN TCADPRO cadpro ON (cadpro.bdCODPROD = s.bdCODPROD)
        JOIN TCADPRO_VINC pro ON (PRO.BDCODPROD = CADPRO.BDCODPROD AND pro.bdCODEMP = :prCODEMP)
        ) PRO
  WHERE (pro.BDALIQ_ST_EF IS NULL) OR (pro.BDALIQ_ST_EF = 0);

  /* Registro "0200" - Campo 13 CEST - cadastro do produto - informacao obrigatoria -
    quando nao houver no produto que esta sendo exportado, apresentar inconsistencia |Codigo CEST obrigatorio nao informado para o produto X| */
  INSERT INTO TEXPORTACAO_SPED_INCO(bdID, bdORDEMINCO, bdREG, bdCODINCO, bdCODPROD, bdCODSAIDA)
  SELECT :prARQUIVO AS bdID,
         GETORDEMSEQUENCIAL(:prCODEMP) AS bdCHAVEREG,
         '0200' AS BDREG,
         30,
         pro.bdCODPROD,
         pro.bdCODSAIDA
  FROM ( 
        SELECT cadpro.bdCODPROD, cadpro.bdCODIGOEAN, pro.bdALIQICMS, pro.bdCODSAIDA, COALESCE(pro.bdCODCEST,cadpro.bdCODCEST) BDCODCEST
         FROM (SELECT DISTINCT(s.bdCODPROD)
               FROM TEXPORTACAO_SPED s
               WHERE s.bdCODPROD IS NOT NULL
                 AND s.bdID = :prARQUIVO
                 AND s.bdCODEMP = :prCODEMP) s
        JOIN TCADPRO cadpro ON (cadpro.bdCODPROD = s.bdCODPROD)
        JOIN TCADPRO_VINC pro ON (PRO.BDCODPROD = CADPRO.BDCODPROD AND pro.bdCODEMP = :prCODEMP)
        ) PRO
  LEFT OUTER JOIN TCEST cest ON (cest.bdCODCEST = pro.bdCODCEST)
  WHERE cest.bdCLASSCEST IS NULL;
  
  /* Registro "H010" - Campo 07 IND_PROP - devera ser sempre |0-Item de propriedade do informante e em seu poder|,
   verificar para exportar apenas os produtos nessa condicao, e acusar inconsistencia nos demais */
  IF ((:prDTINV IS NOT NULL) AND (:prDTINV > '12-31-1899')) THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED_INCO(bdID, bdORDEMINCO, bdREG, bdCODINCO, bdCODPROD, bdCODSAIDA)
      SELECT :prARQUIVO AS bdID,
             GETORDEMSEQUENCIAL(:prCODEMP) AS bdCHAVEREG,
             'H010' AS BDREG,
             31,
             inv.bdCODPROD,
             pro.bdCODSAIDA
      FROM VEF_EMP_TMOVINV inv
      LEFT OUTER JOIN TCADPRO_VINC pro ON (pro.bdCODEMP = inv.bdCODEMP AND pro.bdCODPROD = inv.bdCODPROD)
      LEFT OUTER JOIN TUNIDADEMEDIDA um ON (um.bdCODUNIMED = pro.bdCODUNIMED)
      WHERE inv.bdREFINV = EXTRACT(YEAR FROM :prDTINV)||LPAD(EXTRACT(MONTH FROM :prDTINV),2,'0')
        AND inv.bdCODEMP = :prCODEMP
        AND inv.bdCODPOSSE <> 1;
        
      IF (:prDTINV <> :prDTFIM) THEN
        BEGIN
          INSERT INTO TEXPORTACAO_SPED_INCO(bdID, bdORDEMINCO, bdREG, bdCODINCO)
                                     VALUES(:prARQUIVO, GETORDEMSEQUENCIAL(:prCODEMP), 'H005', 33);
    END
    END
    
  /* Registro "H010" - Campo 07 IND_PROP - devera ser sempre |0-Item de propriedade do informante e em seu poder|,
   verificar para exportar apenas os produtos nessa condicao, e acusar inconsistencia nos demais */
  INSERT INTO TEXPORTACAO_SPED_INCO(bdID, bdORDEMINCO, bdREG, bdCODINCO)      
  SELECT :prARQUIVO AS bdID,
         GETORDEMSEQUENCIAL(:prCODEMP) AS bdCHAVEREG,
         'H010' AS BDREG,
         32
  FROM VEF_EMP_TDRCST_2130 d
  WHERE d.bdCODEMP = :prCODEMP
    AND d.bdREFERENCIA = EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0')
    AND ((CHAR_LENGTH(COALESCE(d.bdCNPJ,'')) <> 18)
     OR  ((SELECT BDISVALID FROM SP_VALIDA_CNPJ(COALESCE(d.bdCNPJ,''))) <> 'TRUE'));

END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCST_BLOCO9 (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRDTINV DATE,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
  /*****************************************************************************
   *                                   9001                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  VALUES (:prARQUIVO, 'Z9001.'||:prCODEMP, 'Z9001', :prCODEMP,
          '|9001'|| -- 01 REG Texto fixo contendo |9001|.
          '|0'|| -- 02 IND_MOV Indicador de movimento: 0- Bloco com dados informados; 1- Bloco sem dados informados.
          '|');
                       
  /*****************************************************************************
   *                                   9900                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         'Z9900.'||s.bdCODEMP||'.'||s.bdREG AS bdCHAVEREG,
         'Z9900' AS BDREG,
         s.bdCODEMP,
         ('|9900'|| -- 01 REG Texto fixo contendo |9900|. C 004 - O
          -- Remove o "Z", que serve apenas para jogar esse registro no final da exportacao.
          '|'||TRIM(IIF(SUBSTRING(s.bdREG FROM 1 FOR 1) = 'Z', SUBSTRING(s.bdREG FROM 2 FOR 4), s.bdREG))|| -- 02 REG_BLC Registro que sera totalizado no proximo campo. C 004 - O
          '|'||(COUNT(s.bdREG))|| -- 03 QTD_REG_BLC Total de registros do tipo informado no campo anterior. N - - O
          '|')
  FROM TEXPORTACAO_SPED s
  WHERE s.bdID = :prARQUIVO
    AND s.bdCODEMP = :prCODEMP
  GROUP BY s.bdCODEMP, s.bdREG;

  /*****************************************************************************
   *                                   9990                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         'Z9990.'||s.bdCODEMP AS bdCHAVEREG,
         'Z9990' AS BDREG,
         s.bdCODEMP,
         ('|9990'|| -- 01 REG Texto fixo contendo |9990|. C 004 - O
          '|'||(COUNT(COALESCE(s.bdCODEMP,1))+5)|| -- 02 QTD_LIN_9 Quantidade total de linhas do Bloco 9. N - - O
          '|')
  FROM TEXPORTACAO_SPED s
  WHERE s.bdREG LIKE 'Z9%'
    AND s.bdID = :prARQUIVO
    AND s.bdCODEMP = :prCODEMP
  GROUP BY s.bdCODEMP;

  /*****************************************************************************
   *                                   9999                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         'Z9999.'||s.bdCODEMP AS bdCHAVEREG,
         'Z9999' AS BDREG,
         s.bdCODEMP,
         ('|9999'|| -- 01 REG Texto fixo contendo |9999|. C 004 - O
          '|'||(COUNT(COALESCE(s.bdCODEMP,1))+4)|| -- 02 QTD_LIN Quantidade total de linhas do arquivo digital. N - - O
          '|')
  FROM TEXPORTACAO_SPED s
  WHERE s.bdID = :prARQUIVO
    AND s.bdCODEMP = :prCODEMP
  GROUP BY s.bdCODEMP;
                           
  /*****************************************************************************
   *                            9900 do 9990 e 9999                            *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         'Z9900.'||s.bdCODEMP||'.'||s.bdREG AS bdCHAVEREG,
         'Z9900' AS BDREG,
         s.bdCODEMP,
         ('|9900'|| -- 01 REG Texto fixo contendo |9900|. C 004 - O
          -- Remove o "Z", que serve apenas para jogar esse registro no final da exportacao.
          '|'||TRIM(IIF(SUBSTRING(s.bdREG FROM 1 FOR 1) = 'Z', SUBSTRING(s.bdREG FROM 2 FOR 4), s.bdREG))|| -- 02 REG_BLC Registro que sera totalizado no proximo campo. C 004 - O
          '|'||(COUNT(s.bdREG))|| -- 03 QTD_REG_BLC Total de registros do tipo informado no campo anterior. N - - O
          '|')
  FROM TEXPORTACAO_SPED s
  WHERE s.bdID = :prARQUIVO
    AND s.bdCODEMP = :prCODEMP
    AND s.BDREG LIKE 'Z999%'
  GROUP BY s.bdCODEMP, s.bdREG;
  
                           
  /*****************************************************************************
   *                            9900 do 9900                                   *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         'Z9900.'||s.bdCODEMP||'.'||s.bdREG AS bdCHAVEREG,
         'Z9900' AS BDREG,
         s.bdCODEMP,
         ('|9900'|| -- 01 REG Texto fixo contendo |9900|. C 004 - O
          -- Remove o "Z", que serve apenas para jogar esse registro no final da exportacao.
          '|'||TRIM(IIF(SUBSTRING(s.bdREG FROM 1 FOR 1) = 'Z', SUBSTRING(s.bdREG FROM 2 FOR 4), s.bdREG))|| -- 02 REG_BLC Registro que sera totalizado no proximo campo. C 004 - O
          '|'||(COUNT(s.bdREG)+1)|| -- 03 QTD_REG_BLC Total de registros do tipo informado no campo anterior. N - - O
          '|')
  FROM TEXPORTACAO_SPED s
  WHERE s.bdID = :prARQUIVO
    AND s.bdCODEMP = :prCODEMP
    AND s.BDREG LIKE 'Z9900%'
  GROUP BY s.bdCODEMP, s.bdREG;
END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCST_BLOCO0_AUX (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
  /*****************************************************************************
   *                                   0005                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         '0005.'||tref.bdCODEMP AS bdCHAVEREG,
         '0005' AS BDREG,
         tref.bdCODEMP,
         ('|0005'|| -- 01 REG Texto fixo contendo |0005| C 004 - O
          '|'||COALESCE(CASE WHEN ((tref.bdNOMFANEMP IS NOT NULL) AND (tref.bdNOMFANEMP <> '')) THEN REPLACE(SUBSTRING(tref.bdNOMFANEMP FROM 1 FOR 60), '|', '') -- Alt.: #93156 - Alterado para o nome da
                        ELSE REPLACE(tref.bdNOMEMP, '|', '') END,'')|| -- 02 FANTASIA Nome de fantasia associado ao nome empresarial. C 060 - O
          '|'||COALESCE((SELECT RESULT FROM SP_TIRATODOSSINAIS(tref.bdCEPEMP)),'')|| -- 03 CEP Codigo de Enderecamento Postal. N 008* - O
          '|'||COALESCE(COALESCE(tref.bdLOGREMP||' ', '')||SUBSTRING(TREF.BDENDEMP FROM 1 FOR 60-CHAR_LENGTH(tref.bdLOGREMP)),'')|| -- 04 END Logradouro e endereco do imovel. C 060 - O
          '|'||COALESCE(tref.bdNUMEMP,'')|| -- 05 NUM Numero do imovel. C - - OC
          '|'||COALESCE(REPLACE(SUBSTRING(tref.bdCOMPLEMP FROM 1 FOR 60), '|', ''),'')|| -- 06 COMPL Dados complementares do endereco. C 060 - OC
          '|'||COALESCE(REPLACE(SUBSTRING(tref.bdBAIEMP FROM 1 FOR 60), '|', ''),'')|| -- 07 BAIRRO Bairro em que o imovel esta situado. C 060 - O
          '|'||COALESCE(tref.bdDDDEMP,'')||(SELECT RESULT FROM SP_TIRATODOSSINAIS(TRIM(COALESCE(tref.bdFONEEMP,''))))|| -- 08 FONE Numero do telefone (DDD+FONE). C 11* - OC
          '|'||COALESCE(TRIM(COALESCE(tref.bdDDDFAXEMP,'')||(SELECT RESULT FROM SP_TIRATODOSSINAIS(TRIM(COALESCE(tref.bdFAXEMP,''))))),'')|| -- 09 FAX Numero do fax. C 11* - OC
          '|'||COALESCE(REPLACE(SUBSTRING(tref.bdEMAILEMP FROM 1 FOR 60), '|', ''),'')|| -- 10 EMAIL Endereco do correio eletronico. C - - O
          '|')
  FROM SP_CONSULTAEMPRESAS(EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTFIM),2,'0'), 'temp.bdCODEMP = '||:prCODEMP, 0) tref;
--  LEFT OUTER JOIN VW_EMP_REF_TOTAL trefsis ON (trefsis.bdCODEMP = tref.bdCODEMP);

  /*****************************************************************************
   *                                   0100                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         '0100.'||tref.bdCODEMP AS bdCHAVEREG,
         '0100' AS BDREG,
         tref.bdCODEMP,
         ('|0100'|| -- 01 REG Texto fixo contendo |0100| C 004 - O
          '|'||REPLACE(c.bdNOMECONT, '|', '')|| -- 02 NOME Nome do contabilista. C 060 - O
          '|'||COALESCE((SELECT RESULT FROM SP_TIRATODOSSINAIS(c.bdCPFCONT)),'')|| -- 03 CPF Numero de inscricao do contabilista no CPF. N 011* - O
          '|'||COALESCE((SELECT RESULT FROM SP_TIRATODOSSINAIS(c.bdCRCCONT)),'')|| -- 04 CRC Numero de inscricao do contabilista no Conselho Regional de Contabilidade. C 011 - O
          '|'||CASE WHEN (CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(e.bdCNPJESC))) = 14) THEN (SELECT RESULT FROM SP_TIRATODOSSINAIS(e.bdCNPJESC)) -- Sol. 20841 Gabriel Ariel (20/02/2018) - So levar o campo quando o escritorio utilizar CNPJ, se nao da erro de validacao
               ELSE '' END|| -- 05 CNPJ Numero de inscricao do escritorio de contabilidade no CNPJ, se houver.N 014* - OC
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(c.bdCEPCONT))|| -- 06 CEP Codigo de Enderecamento Postal. N 008* - OC
          '|'||COALESCE(c.bdLOGRCONT||' ', '')||SUBSTRING(c.bdENDCONT FROM 1 FOR 60-CHAR_LENGTH(c.bdLOGRCONT))|| -- 07 END Logradouro e endereco do imovel. C 060 - OC
          '|'||c.bdNUMEROCONT|| -- 08 NUM Numero do imovel. C - - OC
          '|'||REPLACE(SUBSTRING(c.bdCOMPLCONT FROM 1 FOR 60), '|', '')|| -- 09 COMPL Dados complementares do endereco. C 060 - OC
          '|'||REPLACE(c.bdBAIRROCONT, '|', '')|| -- 10 BAIRRO Bairro em que o imovel esta situado. C 060 - OC
          '|'||COALESCE(c.bdDDDCONT,'')||(SELECT RESULT FROM SP_TIRATODOSSINAIS(TRIM(COALESCE(c.bdFONECONT,''))))|| -- 11 FONE Numero do telefone (DDD+FONE). C 11* - OC
          '|'||TRIM(COALESCE(c.bdDDDFAXCONT,'')||(SELECT RESULT FROM SP_TIRATODOSSINAIS(TRIM(COALESCE(c.bdFAXCONT,'')))))|| -- 12 FAX Numero do fax. C 11* - OC
          '|'||REPLACE(c.bdEMAILCONT, '|', '')|| -- 13 EMAIL Endereco do correio eletronico. C - - OC
          '|'||cid.bdCODIBGE|| -- 14 COD_MUN Codigo do municipio, conforme tabela IBGE. N 007* - O
          '|')
  FROM SP_CONSULTAEMPRESAS(EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTFIM),2,'0'), 'temp.bdCODEMP = '||:prCODEMP, 0) tref
  JOIN TCONTADOR_PADRAO c ON (c.bdCODCONT = tref.bdCODCONTEF)
  LEFT OUTER JOIN TCIDADE cid ON (cid.bdCODCID = c.bdCODCID)
  LEFT OUTER JOIN TESCRITORIO e ON (c.bdCODESC = e.bdCODESC); -- compatibilidade com o modulo financeiro, tem contador no escritorio tambem

  /*****************************************************************************
   *                                   0190                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         '0190.'||:prCODEMP||'.'||COALESCE(um.bdAPEUNIMED,'') AS bdCHAVEREG,
         '0190' AS BDREG,
         :prCODEMP,
         ('|0190'|| -- 01 REG Texto fixo contendo "0190" C 004 - O
          '|'||um.bdAPEUNIMED|| -- 02 UNID Codigo da unidade de medida C 006 - O
          '|'||um.bdDESCUNIMED|| -- 03 DESCR Descricao da unidade de medida C - - O
          '|')
  FROM (SELECT DISTINCT(s.bdCODUNIMED)
        FROM (SELECT s.bdCODUNIMED
        FROM TEXPORTACAO_SPED s
        WHERE s.bdID = :prARQUIVO
                AND s.bdCODEMP = :prCODEMP
              UNION ALL
              SELECT fat.bdCODUNIMED
              FROM TEXPORTACAO_SPED s
              JOIN TFATCONV fat on (fat.bdCODPROD = s.bdCODPROD AND fat.bdCODEMP = :prCODEMP) -- Alt.: #157315 - para exportar as unidades de medida do fator de conversao...
              WHERE s.bdID = :prARQUIVO
          AND s.bdCODEMP = :prCODEMP) s
        ) s
  JOIN TUNIDADEMEDIDA um ON (um.bdCODUNIMED = s.bdCODUNIMED)
  WHERE um.bdCODUNIMED > 0;

  /*****************************************************************************
   *                                   0200                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         '0200'||'.'||pro.bdCODPROD||'.0000.'||:prCODEMP||'.'||COALESCE(pro.bdCODSAIDA,'')||'.'||COALESCE(pro.bdCODPROD,'')||'.'||COALESCE(pro.bdCODIGOEAN,'') AS bdCHAVEREG,
         '0200' AS BDREG,
         :prCODEMP,
         ('|0200'|| -- 01 REG Texto fixo contendo "0200" C 004 - O
          '|'||COALESCE(pro.bdCODSAIDA,pro.bdCODPROD)|| -- 02 COD_ITEM Codigo do item C 060 - O
          '|'||(SELECT bdSTR FROM SP_RETIRAR_CARACTER_ESP(pro.bdDESCPROD))|| -- 03 DESCR_ITEM Descricao do item C - - O
          '|'||COALESCE(pro.bdCODIGOEAN,'')|| -- 04 COD_BARRA Representacao alfanumerico do codigo de barra do produto, se houver C - - OC
          '|'|| -- 05 COD_ANT_ITEM Codigo anterior do item com relacao a ultima informacao apresentada. C 060 - OC
          '|'||COALESCE(um.bdAPEUNIMED,'')|| -- 06 UNID_INV Unidade de medida utilizada na quantificacao de estoques. C 006 - O
          '|'||COALESCE(ser.bdTIPOSER,'00')|| -- 07 TIPO_ITEM Tipo do item |. Atividades Industriais, Comerciais e Servicos: 00 |. Mercadoria para Revenda; 01 |. Materia-Prima; 02 |. Embalagem; 03 |. Produto em Processo; 04 |. Produto Acabado; 05 |. Subproduto; 06 |. Produto Intermediario; 07 |. Material de Uso e Consumo; 08 |. Ativo Imobilizado; 09 |. Servicos; 10 |. Outros insumos; 99 |. Outras
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(ncm.bdCLASSIFICACAO,pro.bdNCMPROD,'')))|| -- 08 COD_NCM Codigo da Nomenclatura Comum do Mercosul C 008 - OC
          '|'|| -- 09 EX_IPI Codigo EX, conforme a TIPI C 003 - OC
          '|'||COALESCE(gen.bdGENERO,'')|| -- 10 COD_GEN Codigo do genero do item, conforme a Tabela 4.2.1 N 002* - OC
          -- 11 COD_LST Codigo do servico conforme lista do Anexo I da Lei Complementar Federal na 116/03. N 004 OC
          -- alt:#10928 - atualizacao do leiaute, agora tem que ser com ponto nn.nn  COD_LST
          '|'||CASE WHEN (:prDTINI <= '12-31-2014') THEN (SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(codser.bdSERVICO,'')))
                    WHEN codser.bdSERVICO IS NOT NULL THEN (LPAD(SUBSTRING(COALESCE(codser.bdSERVICO,'') FROM 1 FOR POSITION('.' IN COALESCE(codser.bdSERVICO,''))), 3, '0')||
                                                            SUBSTRING(COALESCE(codser.bdSERVICO,'') FROM POSITION('.' IN COALESCE(codser.bdSERVICO,''))+1 FOR 2))
               ELSE '' END||
          -- 12 ALIQ_ICMS Aliquota de ICMS aplicavel ao item nas operacoes internas N 006 02 OC
          -- #120922 - Quando houver preenchido no produto, levar a aliquota de ICMS
          '|'||IIF((pro.BDALIQ_ST_EF IS NOT NULL) AND (pro.BDALIQ_ST_EF > 0), FORMATFLOAT('#0.00',pro.BDALIQ_ST_EF),FORMATFLOAT('#0.00',IIF(PRO.BDALIQICMS > 0,PRO.BDALIQICMS,PRO.BDALIQICMSEFETIVO)))||
          IIF(:prDTINI >= '01-01-2017','|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(cest.bdCLASSCEST,''))),'')|| -- 13 CEST Codigo Especificador da Substituicao Tributaria N 007* - OC
          '|')
  FROM ( 
        SELECT
               COALESCE(pro.bdCODPROD,cadpro.bdCODPROD) AS bdCODPROD, COALESCE(cadpro.bdCODIGOEAN,'') AS bdCODIGOEAN,
               COALESCE(pro.bdCODUNIMED,0) AS bdCODUNIMED, COALESCE(pro.bdNCMPROD,0) AS bdNCMPROD,
               COALESCE(pro.bdALIQICMS,0) AS bdALIQICMS, COALESCE(pro.bdCODSAIDA,'') AS bdCODSAIDA,
               COALESCE(pro.bdCODSER,cadpro.bdCODSER) AS bdCODSER, COALESCE(pro.bdCODTIPOSER,cadpro.bdCODTIPOSER) AS bdCODTIPOSER,
               COALESCE(pro.bdCODGEN,cadpro.bdCODGEN) AS bdCODGEN, COALESCE(pro.bdDESCPROD,cadpro.bdAPELIDOUNICO) AS bdDESCPROD,
               COALESCE(pro.bdCODCOMBANP,cadpro.bdCODCOMBANP) AS bdCODCOMBANP, COALESCE(pro.bdCODCEST,cadpro.bdCODCEST) AS BDCODCEST,
               S.BDALIQ_ST_EF, Coalesce(pro.BDALIQICMSEFETIVO,0) BDALIQICMSEFETIVO
         FROM (SELECT s.bdCODPROD, MAX(Coalesce(S.BDALIQ_ST_EF,0)) BDALIQ_ST_EF
               FROM TEXPORTACAO_SPED s
               WHERE s.bdCODPROD IS NOT NULL
                 AND s.bdID = :prARQUIVO
                 AND s.bdCODEMP = :prCODEMP
               GROUP BY S.BDCODPROD) s
        JOIN TCADPRO_VINC pro ON (pro.bdCODPROD = s.bdCODPROD AND pro.bdCODEMP = :prCODEMP)
        JOIN TCADPRO cadpro ON (cadpro.bdCODPROD = pro.bdCODPROD)
        ) PRO
  LEFT OUTER JOIN TUNIDADEMEDIDA um ON (pro.bdCODUNIMED = um.bdCODUNIMED)
  LEFT OUTER JOIN TGENEROPRO gen ON (pro.bdCODGEN = gen.bdCODGEN)
  LEFT OUTER JOIN TTIPO_SERVICO ser ON (pro.bdCODTIPOSER = ser.bdCODTIPOSER)
  LEFT OUTER JOIN TCODIGO_SERVICO codser ON (pro.bdCODSER = codser.bdCODSER)
  LEFT OUTER JOIN TNCM ncm ON (ncm.bdNCMPROD = pro.bdNCMPROD)
  LEFT OUTER JOIN TCEST cest ON (cest.bdCODCEST = pro.bdCODCEST);

  /*****************************************************************************
   *                                   0205                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         '0200'||'.'||COALESCE(prod.bdCODPROD,'')||'.0205.'||:prCODEMP||'.'||prod.bdCODPROD AS bdCHAVEREG,
         '0205' AS BDREG,
         :prCODEMP,
         ('|0205'|| -- 01 REG Texto fixo contendo "0205" C 004 - O
          '|'||(SELECT bdSTR FROM SP_RETIRAR_CARACTER_ESP(prod.bdDESCPROD))|| -- 02 DESCR_ANT_ITEM Descricao anterior do item C - - O
          '|'||'01'||SUBSTRING(prod.bdREFPROD FROM 5 FOR 2)||SUBSTRING(prod.bdREFPROD FROM 1 FOR 4)|| -- 03 DT_INI Data inicial de utilizacao da descricao do item N 008* - O
          '|'||(SELECT ULTDIA FROM ULTIMO_DIA_MES(SUBSTRING(prod.bdREFPROD FROM 5 FOR 2),SUBSTRING(prod.bdREFPROD FROM 1 FOR 4)))||
                SUBSTRING(prod.bdREFPROD FROM 5 FOR 2)||SUBSTRING(prod.bdREFPROD FROM 1 FOR 4)|| -- 04 DT_FIM Data final de utilizacao da descricao do item N 008* - O
          '|'|| -- 05 COD_ANT_ITEM Codigo anterior do item com relacao a ultima informacao apresentada.C 060 - O
          '|')
  FROM(
       SELECT pro.bdCODPROD, pro.bdCODEMP, pro.bdDESCPROD, pro.bdREFPROD
       FROM (
       SELECT ref.bdCODPROD, ref.bdCODEMP, ref.bdDESCPROD, ref.bdREFPROD
       FROM (SELECT DISTINCT(s.bdCODPROD)
             FROM TEXPORTACAO_SPED s
             WHERE s.bdCODPROD IS NOT NULL
               AND s.bdID = :prARQUIVO
               AND s.bdCODEMP = :prCODEMP) s
       LEFT OUTER JOIN TCADPRO_VINC pro ON (pro.bdCODPROD = s.bdCODPROD AND pro.bdCODEMP = :prCODEMP)
       LEFT OUTER JOIN TCADPRO_REF ref ON (ref.bdCODPROD = pro.bdCODPROD AND ref.bdCODEMP = pro.bdCODEMP)
       WHERE (pro.bdCODEMP = :prCODEMP)
               AND (ref.bdREFPROD = (SELECT bdREF FROM DEC_REF((EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTFIM),2,'0')))))
             ) pro
       JOIN TCADPRO_REF ref ON (ref.bdCODPROD = pro.bdCODPROD AND ref.bdCODEMP = pro.bdCODEMP AND (ref.bdREFPROD = (SELECT MAX(proref.bdREFPROD) -- A primeira referencia anterior
                              FROM TCADPRO_REF proref
                                                                                                                    WHERE proref.bdCODEMP = pro.bdCODEMP
                                                                                                                      AND proref.bdCODPROD = pro.bdCODPROD
                                                                                                                      AND proref.bdREFPROD > pro.bdREFPROD)))
       WHERE ref.bdDESCPROD <> pro.bdDESCPROD
       ) prod;

  /*****************************************************************************
   *                                   0206                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         '0200'||'.'||COALESCE(pro.bdCODPROD,'')||'.0206.'||:prCODEMP||'.'||pro.bdCODCOMBANP AS bdCHAVEREG,
         '0206' AS BDREG,
         :prCODEMP,
         ('|0206'|| -- 01 REG Texto fixo cotendo "0206" C 004 - O
          '|'||anp.bdREGEXP|| -- 02 COD_COMB Codigo do combustivel, conforme tabela publicada pela ANP
          '|')
  FROM (
        --SELECT DISTINCT(COALESCE(pro.bdCODCOMBANP,cadpro.bdCODCOMBANP)) AS bdCODCOMBANP
        SELECT pro.bdCODPROD, COALESCE(pro.bdCODCOMBANP,cadpro.bdCODCOMBANP) AS bdCODCOMBANP
         FROM (SELECT DISTINCT(s.bdCODPROD)
               FROM TEXPORTACAO_SPED s
               WHERE s.bdCODPROD IS NOT NULL
                 AND s.bdID = :prARQUIVO
                 AND s.bdCODEMP = :prCODEMP) s
        JOIN TCADPRO cadpro ON (cadpro.bdCODPROD = s.bdCODPROD)
        JOIN TCADPRO_VINC pro ON (pro.bdCODPROD = cadpro.bdCODPROD AND pro.bdCODEMP = :prCODEMP)
        ) PRO
  JOIN VEF_BASE_TTABCOMBANP anp ON (anp.bdCODCOMBANP = pro.bdCODCOMBANP);

  /*****************************************************************************
   *                                   0220                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT
         :prARQUIVO AS bdID,
         '0200'||'.'||COALESCE(s.bdCODPROD,'')||'.0220.'||:prCODEMP||'.'||fat.bdCODFATCON||'.'||COALESCE(um.bdAPEUNIMED,'') AS bdCHAVEREG,
         '0220' AS BDREG,
         :prCODEMP,
         ('|0220'|| -- 01 REG Texto fixo contendo "0220" C 004 - O
          '|'||COALESCE(um.bdAPEUNIMED,'')|| -- 02 UNID_CONV Unidade comercial a ser convertida na unidade de estoque,referida no registro 0200.C 006 - O
          '|'||FORMATFLOAT('#0.000000',fat.bdFATORCONVER)|| -- 03 FAT_CONV Fator de conversao: fator utilizado para converter (multiplicar) a unidade a ser convertida na unidade adotada no inventario.N - 6 O
          '|')
  FROM (SELECT DISTINCT(s.bdCODPROD)
        FROM TEXPORTACAO_SPED s
        WHERE s.bdID = :prARQUIVO
          AND s.bdCODEMP = :prCODEMP) s
  JOIN TFATCONV fat on (fat.bdCODPROD = s.bdCODPROD AND fat.bdCODEMP = :prCODEMP)
  JOIN TUNIDADEMEDIDA um ON (um.bdCODUNIMED = fat.bdCODUNIMED);
  
  /*****************************************************************************
   *                                   0990                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         '0990.'||s.bdCODEMP AS bdCHAVEREG,
         '0990' AS BDREG,
         s.bdCODEMP,
         ('|0990'|| -- 01 REG Texto fixo contendo "0990"          C  004    -  O
          '|'||(COUNT(COALESCE(s.bdCODEMP,1))+1)|| -- 02 QTD_LIN_H Quantidade total de linhas do Bloco 0 N - - O
          '|')
  FROM TEXPORTACAO_SPED s
  WHERE SUBSTRING(s.bdREG FROM 1 FOR 1) LIKE '0'
    AND s.bdID = :prARQUIVO
    AND s.bdCODEMP = :prCODEMP
  GROUP BY s.bdCODEMP;

END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCST_BLOCO0 (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRFINALIDADE INTEGER,
    PRARQUIVO VARCHAR(260))
AS
DECLARE VARIABLE WVER VARCHAR(3);
BEGIN
  IF (:prDTINI <= '12-31-2009') THEN
    wVER = '002';
  ELSE
  IF ((:prDTINI >= '01-01-2010') AND (:prDTINI <= '12-31-2010')) THEN
    wVER = '003';
  ELSE
  IF ((:prDTINI >= '01-01-2011') AND (:prDTINI <= '12-31-2011')) THEN
    wVER = '004';
  ELSE
  IF ((:prDTINI >= '01-01-2012') AND (:prDTINI <= '06-30-2012')) THEN
    wVER = '005';
  ELSE
  IF ((:prDTINI >= '07-01-2012') AND (:prDTINI <= '12-31-2012')) THEN
    wVER = '006';
  ELSE
  IF ((:prDTINI >= '01-01-2013') AND (:prDTINI <= '12-31-2013')) THEN
    wVER = '007';
  ELSE
  IF ((:prDTINI >= '01-01-2014') AND (:prDTINI <= '12-31-2014')) THEN -- alt:#7693 - versao do validador modificado para 08
    wVER = '008';
  ELSE
  IF ((:prDTINI >= '01-01-2015') AND (:prDTINI <= '12-31-2015')) THEN
    wVER = '009';
  ELSE
  IF ((:prDTINI >= '01-01-2016') AND (:prDTINI <= '12-31-2016')) THEN -- Versao 10 - Inclusao do bloco K
    wVER = '010';
  ELSE
  IF ((:prDTINI >= '01-01-2017') AND (:prDTINI <= '12-31-2017')) THEN -- Alt.: 14516 - Novo layout a partir de 01/2017
    wVER = '011';
  ELSE
  IF ((:prDTINI >= '01-01-2018') AND (:prDTINI <= '12-31-2018')) THEN -- Alt.: 20476 - Novo layout a partir de 01/2018
    wVER = '012';
  ELSE
  IF (:prDTINI >= '01-01-2019') THEN -- Alt.: "Exportacao Sped Fiscal 2019" - Novo layout a partir de 01/2019
    wVER = '013';

  /*****************************************************************************
   *                                   0000                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         '0000.'||tref.bdCODEMP AS bdCHAVEREG,
         '0000' AS BDREG,
         tref.bdCODEMP,
         ('|0000'|| -- 01 REG Texto fixo contendo |0000| C 004 - O
          --'|'||:wVER|| -- 02 COD_VER Codigo da versao do leiaute conforme a tabela indicada no Ato Cotepe .N 003* - O
          -- 02 COD_VER Codigo da versao do leiaute conforme a tabela indicada no Ato Cotepe .N 003* - O
          CASE WHEN ((trefsis.bdPERFILSPED = 0) OR (trefsis.bdPERFILSPED = 1)) THEN '|'||:wVER
          ELSE '|' END|| -- Quando for "Perfil C" deve levar em branco...
          '|'||:prFINALIDADE|| -- 03 COD_FIN Codigo da finalidade do arquivo:  0 - Remessa do arquivo original;  1 - Remessa do arquivo substituto. N 001 - O
          '|'||LPAD(EXTRACT(DAY FROM :prDTINI),2,'0')||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0')||EXTRACT(YEAR FROM :prDTINI)|| -- 04 DT_INI Data inicial das informacoes contidas no arquivo. N 008* - O
          '|'||LPAD(EXTRACT(DAY FROM :prDTFIM),2,'0')||LPAD(EXTRACT(MONTH FROM :prDTFIM),2,'0')||EXTRACT(YEAR FROM :prDTFIM)|| -- 05 DT_FIN Data final das informacoes contidas no arquivo. N 008* - O
          '|'||tref.bdNOMEMP|| -- 06 NOME Nome empresarial da entidade. C 060 - O
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(tref.bdCNPJEMP))||-- 07 CNPJ Numero de inscricao da entidade no CNPJ. N 014* - OC
          '|'|| -- 08 CPF Numero de inscricao da entidade no CPF. N 011* OC
          '|'||tref.bdSIGLAUF|| -- 09 UF Sigla da unidade da federacao da entidade. C 002* - O
          '|'||CASE WHEN ((tref.bdSIGLAUF LIKE 'MT') AND ((tref.bdIEEMP LIKE 'ISENTO') OR (tref.bdIEEMP LIKE 'ISENTA'))) THEN '' -- Quando o estado e do MT deve-se exluir os zeros da frente Camilla M. #122777
               ELSE (SELECT RESULT FROM SP_TIRATODOSSINAIS(tref.bdIEEMP)) END|| -- 10 IE Inscricao Estadual da entidade. C 014 - O
          '|'||tref.bdCODIBGE|| -- 11 COD_MUN Codigo do municipio do domicilio fiscal da entidade,conforme a tabela IBGEN 007* - O
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(tref.bdIMEMP))|| -- 12 IM Inscricao Municipal da entidade. C - - OC
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(trefsis.bdSUFRAMA))|| -- 13 SUFRAMA Inscricao da entidade na Suframa C 009* - OC
          -- 14 IND_PERFIL Perfil de apresentacao do arquivo fiscal;  A |. Perfil A; B |. Perfil B.; C |. Perfil C.C 001 - O
          CASE WHEN trefsis.bdPERFILSPED = 0 THEN '|A'
               WHEN trefsis.bdPERFILSPED = 1 THEN '|B'
          ELSE '|C' END||
          '|'||COALESCE(tref.bdATIVIDADESPED,'')|| -- 15 IND_ATIV Indicador de tipo de atividade:  0 |. Industrial ou equiparado a industrial; 1 |. Outros.
          '|')
  FROM SP_CONSULTAEMPRESAS_SIS(EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTFIM),2,'0'), :prCODEMP, 0) tref
  LEFT OUTER JOIN VW_EMP_REF_TOTAL trefsis ON (trefsis.bdCODEMP = tref.bdCODEMP);

  /*****************************************************************************
   *                                   0001                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  VALUES (:prARQUIVO, '0001.'||:prCODEMP, '0001', :prCODEMP,
          '|0001'|| -- 01 REG Texto fixo contendo |0001| C 004 - O
          '|0|');   -- 02 IND_MOV Indicador de movimento: 0- Bloco com dados informados; 1- Bloco sem dados informados.

  -- Continacao da procedure...
  EXECUTE PROCEDURE SP_EXPORTA_DRCST_BLOCO0_AUX(:prCODEMP, :prDTINI, :prDTFIM, :prARQUIVO);
END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCST_BLOCO2 (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRDTINV DATE,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
  /*****************************************************************************
   *                                   2001                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  VALUES (:prARQUIVO, '2001.'||:prCODEMP, '2001', :prCODEMP,
          '|2001'|| -- 01 REG Texto fixo contendo |2001| C 004 - O
          '|'||IIF((SELECT FIRST 1 d.bdCODEMP FROM VEF_EMP_TDRCST_2110 d -- 02 IND_MOV Indicador de movimento: 0 - Bloco com dados informados; 1- Bloco sem dados informados N 001* - O
                    WHERE d.bdCODEMP = :prCODEMP
                      AND d.bdREFERENCIA = EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0')) = :prCODEMP,'0','1')||
          '|');

  /*****************************************************************************
   *                                   2100                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         '2100.'||d.bdCODEMP AS bdCHAVEREG,
         '2100' AS BDREG,
         d.bdCODEMP,
         ('|2100'|| -- 01 REG Texto fixo contendo |2100|. C 004* - O
         '|'||FORMATFLOAT('#0.00',Coalesce(d.bdS_VL_ICMS_ST_REST,0))|| -- 02 S_VL_ICMS_ST_REST Soma geral no mes dos valores do ICMS-ST correspondente a diferenca a maior da base de calculo da substituicao tributaria quando comparada com o valor efetivo da saida dos itens de mercadoria do Registro 2110. Soma dos campos VL_ICMS_ST_REST do Registro 2110. N - 02 OC
         '|'||FORMATFLOAT('#0.00',Coalesce(d.bdS_VL_ICMS_ST_COMPL,0))|| -- 03 S_VL_ICMS_ST_COMPL Soma geral no mes dos valores do ICMS-ST correspondente a diferenca a menor da base de calculo da substituicao tributaria quando comparada com o valor efetivo da saida no mes. O transporte da soma dos campos VL_ICMS_ST_COMPL do Registro 2110,quando informado, torna-se obrigatorio a partir do periodo de referencia marco de 2018. N - 02 OC
         '|'||FORMATFLOAT('#0.00',Coalesce(d.bdSD_ICMS_ST_REST,0))|| -- 04 SD_ICMS_ST_REST Saldo do ICMS no mes com direito a restituicao, resultante da apuracao das diferencas de base de calculo nas vendas a consumidor final em que houve a incidencia de ICMS-ST nas operacoes anteriores. Preencher com o valor positivo da diferenca entre os campos S_VL_ICMS_ST_REST e S_VL_ICMS_ST_COMPL deste Registro. N - 02 OC
         '|'||FORMATFLOAT('#0.00',Coalesce(d.bdSD_ICMS_ST_RESS,0))|| -- 05 SD_ICMS_ST_RESS Saldo do ICMS_ST apurado no mes relativo as saidas com direto a ressarcimento. Preencher com o valor da soma dos campos VL_ICMS_ST_IND_S_OE e VL_T_CREDITO_MVA_SN do Registro 2110. N - 02 OC
         '|'||FORMATFLOAT('#0.00',Coalesce(d.bdSD_ICMS_ST_COMPL,0))|| -- 06 SD_ICMS_ST_COMPL Saldo do ICMS a complementar no mes, resultante da apuracao das diferencas de base de calculo nas vendas a consumidor final em que houve a incidencia de ICMS-ST nas operacoes anteriores. Preencher com o valor positivo da diferenca entre os campos S_VL_ICMS_ST_COMPL e S_VL_ICMS_ST_REST deste Registro. N - 02 OC
         '|'||FORMATFLOAT('#0.00',Coalesce(d.bdSD_ICMS_OP,0))|| -- 07 SD_ICMS_OP Saldo do ICMS sobre operacoes proprias apurado no campo VL_ICMS_IND_S_OE do Registro 2110. Soma dos campos VL_ICMS_IND_S_OE do Registro 2110.
         '|'||FORMATFLOAT('#0.00',Coalesce(d.BDV_APUR_CRED_ICMS,0))|| -- 08 V_APUR_CRED_ICMS Valor do credito do ICMS resultante da diferenca da soma dos saldos do ICMS a restituir e ressarcir deduzido do saldo do ICMS a complementar, quando a soma dos saldos do ICMS a restituir ou ressarcir for maior que o valor do saldo do ICMS a complementar. Preencher com o valor positivo da diferenca entre a soma dos campos SD_ICMS_ST_REST e SD_ICMS_ST_RESS deduzido do campo SD_ICMS_COMPL deste Registro. N - 02 OC
         '|'||FORMATFLOAT('#0.00',Coalesce(D.BDV_APUR_ICMS_COMP,0))|| -- 09 V_APUR_ICMS_COMP Valor do ICMS a complementar resultante da diferenca do saldo do ICMS a complementar deduzido da soma do saldo do ICMS a restituir e ressarcir, quando o valor do saldo do ICMS a complementar for maior que a soma ICMS a restituir ou ressarcir. Preencher com o valor positivo da diferenca entre o campo SD_ICMS_ST_COMPL deduzido da soma dos campos SD_ICMS_ST_REST e SD_ICMS_ST_RESS deste Registro N - 02 OC
         '|')   
  FROM VEF_EMP_TDRCST_RESUMO d
  WHERE d.bdCODEMP = :prCODEMP
    AND d.bdREFERENCIA = EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0');

  /*****************************************************************************
   *                                   2110                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA, bdCODPROD, bdALIQ_ST_ef)
  SELECT :prARQUIVO AS bdID,
         '2110.'||d.bdCODEMP||'.'||d.bdCODPROD AS bdCHAVEREG,
         '2110' AS BDREG,
         d.bdCODEMP,
         ('|2110'|| -- 01 REG Texto fixo contendo |2110|. C 004* - O
          '|'||d.bdCOD_ITEM|| -- 02 COD_ITEM Codigo do item (campo 02 do Registro 0200). C 060 - O
          '|'||FORMATFLOAT('#0.00000',Coalesce(d.bdQTDE_T_V_CF,0))|| -- 03 QTDE_T_V_CF Quantidade total de vendas da mercadoria a consumidor final em que houve a incidencia de ICMS-ST nas operacoes anteriores. Preencher com a soma dos campos QTDE_V_CF_C do Registro 2112 e QTDE_IND_S_C do Registro 2113, do IND_S de codigo 10, deduzidas das devolucoes. N - 05 OC
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdVL_T_V_CF,0))|| -- 04 VL_T_V_CF Valor total das vendas da mercadoria a consumidor final em que houve a incidencia de ICMS-ST nas operacoes anteriores. Preencher com a soma dos campos VL_V_CF do Registro 2112 e VL_V_IND_S do Registro 2113, do IND_S de codigo 10, deduzidas das devolucoes. N - 02 OC
          '|'||FORMATFLOAT('#0.000',Coalesce(d.bdVLM_UNIT_V_CF,0))|| -- 05 VLM_UNIT_V_CF Valor medio unitario das vendas da mercadoria a consumidor final. Preencher com o resultado da divisao do campo VL_T_V_CF pelo campo QTDE_T_V_C deste registro. N - 03 OC
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdVL_T_BCST_V_CF,0))|| -- 06 VL_T_BCST_V_CF Valor total da Base de Calculo da Substituicao Tributaria proporcional a quantidade de vendas da mercadoria a consumidor final em que houve a incidencia de ICMS-ST nas operacoes anteriores. Preencher com o produto do campo QTDE_T_V_CF deste registro pelo campo VLM_UNIT_BCST do Registro 2120. N - 02 OC
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdVL_DIF_MAIOR_BCST,0))|| -- 07 VL_DIF_MAIOR_BCST Valor da diferenca a maior da base de calculo da substituicao tributaria quando comparada com o valor efetivo da saida a consumidor final. Preencher com o valor positivo da diferenca entre o campo VL_T_BCST_V_CF e o campo VL_T_V_CF deste registro. N - 02 OC
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdVL_DIF_MENOR_BCST,0))|| -- 08 VL_DIF_MENOR_BCST Valor da diferenca a menor da base de calculo da substituicao tributaria quando comparada com o valor efetivo da saida a consumidor. Preencher com o valor positivo da diferenca entre o campo VL_T_V_CF e o campo VL_T_BCST_V_CF deste registro. N - 02 OC
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdALIQ_EF,0))|| -- 09 ALIQ_EF Aliquota efetiva do ICMS da mercadoria na venda a consumidor final. Deve o mesmo valor informado no campo ALIQ_ICMS do Registro 0200. N - 02 OC
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdVL_ICMS_ST_REST,0))|| -- 10 VL_ICMS_ST_REST Valor do ICMS-ST a restituir correspondente a diferenca a maior da base de calculo da substituicao tributaria quando comparada com o valor efetivo da saida. Preencher com o produto do campo VL_DIF_MAIOR_BCST pelo campo ALIQ_EF deste registro. N - 02 OC
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdVL_ICMS_ST_COMPL,0))|| -- 11 VL_ICMS_ST_COMPL Valor do ICMS-ST a complementar correspondente a diferenca a menor da base de calculo da substituicao tributaria quando comparada com o valor efetivo da saida. Preencher com o produto do campo VL_DIF_MENOR_BCST pelo campo ALIQ_EF deste registro. N - 02 OC
          '|'||FORMATFLOAT('#0.00000',Coalesce(d.bdQTDE_T_IND_S_OE,0))|| -- 12 QTDE_T_IND_S_OE Quantidade total de saidas destinadas a outros estados com direito a ressarcimento. Preencher com a soma do campo QTDE_IND_S_C, para o IND_S de codigo 20 do Registro 2113, deduzida das devolucoes. N _ 05 OC
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdVL_ICMS_IND_S_OE,0))|| -- 13 VL_ICMS_ IND_S_OE Total do ICMS sobre operacoes proprias referentes as saidas destinadas a outros estados. Preencher com o resultado da multiplicacao do campo VLM_UNIT_ICMS do Registro 2120 pelo campo QTDE_T_IND_S_OE deste registro. N - 02 OC
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdVL_ICMSST_IND_S_OE,0))|| -- 14 VL_ICMS_ ST_IND_S_OE Total do ICMS_ST sobre operacoes referentes as saidas destinadas a outros estados. Preencher com o resultado da multiplicacao do VLM_UNIT_ICMS_ST do Registro 2120 pelo campo QTDE_T_IND_S_OE deste registro. N - 02 OC
          '|'||FORMATFLOAT('#0.00000',Coalesce(d.bdQTDE_T_IND_S_SN,0))|| -- 15 QTDE_T_IND_S_SN Quantidade total das saidas destinadas a optantes pelo Simples Nacional de mercadoria cuja substituicao tributaria da operacao anterior foi apurada com MVA de contribuinte normal. Preencher com a soma do campo QTDE_IND_S_C, para o IND_S de codigo 30 do Registro 2113. N _ 05 OC
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdVL_T_CREDITO_MVA_SN,0))|| -- 16 VL_T_CREDITO_MVA_SN Total dos creditos em decorrencia da saida destinada a contribuinte optante pelo Simples Nacional de mercadoria cuja substituicao tributaria da operacao anterior foi apurada com MVA de contribuinte normal. Preencher com a soma do VL_CREDITO_MVA_SN do Registro 2113. N - 02 OC
          '|'),
        d.bdCODPROD,
        d.BDALIQ_EF
  FROM VEF_EMP_TDRCST_2110 d
  WHERE d.bdCODEMP = :prCODEMP
    AND d.bdREFERENCIA = EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0');

  /*****************************************************************************
   *                                   2112                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA, bdCODUNIMED, bdCODPROD)
  SELECT :prARQUIVO AS bdID,
         '2110.'||d.bdCODEMP||'.'||d.bdCODPROD||'.2112' AS bdCHAVEREG,
         '2112' AS BDREG,
         d.bdCODEMP,
         ('|2112'|| -- 01 REG Texto fixo contendo |2112|. C 004* - O
          '|'||FORMATFLOAT('#0.00000',Coalesce(d.bdQTDE_V_CF,0))|| -- 02 QTDE_V_CF Quantidade de vendas a consumidor final da mercadoria identificada no Registro 2110 que constam nos documentos fiscais de saida. N - 05 O
          '|'||COALESCE(d.bdUNID,'')|| -- 03 UNID Unidade do item (Campo 02 do registro 0190). C 006 - O
          --'|'||COALESCE(um.bdAPEUNIMED,'')|| -- 04 FAT_CONV Fator de conversao: fator utilizado para converter (multiplicar) a unidade a ser convertida na unidade adotada no inventario. N - 06 O
          '|1'|| -- 04 FAT_CONV Fator de conversao: fator utilizado para converter (multiplicar) a unidade a ser convertida na unidade adotada no inventario. N - 06 O
          '|'||FORMATFLOAT('#0.00000',Coalesce(d.bdQTDE_V_CF,0))|| -- 05 QTDE_V_CF_C Quantidade de vendas da mercadoria a consumidor final da mercadoria identificada no Registro 2110 convertida para a unidade padrao de medida indicada no Registro 0200. N - 05 O
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdVL_V_CF,0))|| -- 06 VL_V_CF Valor das vendas da mercadoria a consumidor final da mercadoria identificada no Registro 2110. N - 02 O
          '|'),
         d.bdCODUNIMED,
         d.bdCODPROD
  FROM VEF_EMP_TDRCST_2112 d
  WHERE d.bdCODEMP = :prCODEMP
    AND d.bdREFERENCIA = EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0');

  /*****************************************************************************
   *                                   2113                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA, bdCODUNIMED, bdCODPROD)
  SELECT :prARQUIVO AS bdID,
         '2110.'||d.bdCODEMP||'.'||d.bdCODPROD||'.2113.'||d.bdIND_OPER||'.'||d.bdCHAVE||'.'||d.bdORDEM||'.'||d.bdORDEMPRO AS bdCHAVEREG,
         '2113' AS BDREG,
         d.bdCODEMP,
         ('|2113'|| -- 01 REG Texto fixo contendo |2113| C 004* - O
          '|'||COALESCE(d.bdIND_OPER,'')|| -- 02 IND_OPER Indicador do tipo de operacao: 0 - Saida; (Venda) 1- Devolucao de vendas C 001* - O
          '|'||COALESCE(d.bdIND_S,'')|| -- 03 IND_S Codigo que indica o tipo de operacao de saida: 10 - Venda a consumidor final; 20 - Venda para outra unidade da federacao; 30 - Venda para Simples Nacional N 001* - O
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(d.bdCHV_NFE,'')))|| -- 04 CHV_NFE Numero completo da chave da NF-e de venda ou de devolucao de vendas N 044* - O
          '|'||COALESCE(LPAD(EXTRACT(DAY FROM d.bdDT_NFE),2,'0')||LPAD(EXTRACT(MONTH FROM d.bdDT_NFE),2,'0')||EXTRACT(YEAR FROM d.bdDT_NFE),'')|| -- 05 DT_NFE Data da emissao de NF-e informada na EFD ICMS/IPI N 008* - OC
          '|'||COALESCE(LPAD(EXTRACT(DAY FROM d.bdDT_E),2,'0')||LPAD(EXTRACT(MONTH FROM d.bdDT_E),2,'0')||EXTRACT(YEAR FROM d.bdDT_E),'')|| -- 06 DT_E Data da entrada da devolucao de venda informada na EFD ICMS/IPI N 008* - OC
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(d.bdCNPJ,'')))|| -- 07 CNPJ CNPJ do destinatario que constou da NF-e de venda. Deve ser o mesmo na devolucao de vendas N 014* - OC
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(d.bdCPF,'')))|| -- 08 CPF CPF que consta na NF-e de venda N 011* - OC
          '|'||COALESCE(d.bdNUM_ITEM,'')|| -- 09 NUM_ITEM Numero sequencial do item que identifica a mercadoria e consta na NFe de venda ou de devolucao de venda N 003 - O
          '|'||FORMATFLOAT('#0.00000',COALESCE(d.bdQTDE_IND_S,0))|| -- 10 QTDE_IND_S Quantidade do item da mercadoria que consta da NF-e de venda, inclusive na devolucao de venda N - 05 O
          '|'||COALESCE(d.bdUNID,'')|| -- 11 UNID Unidade do item (Campo 02 do registro 0190) C 006 - O
          '|'||FORMATFLOAT('#0.000000',Coalesce(d.bdFAT_CONV,1))|| -- 12 FAT_CONV Fator de conversao: fator utilizado para converter (multiplicar) a unidade a ser convertida na unidade adotada no inventario N - 06 O
          '|'||FORMATFLOAT('#0.00000',COALESCE(d.bdQTDE_IND_S_C,0))|| -- 13 QTDE_IND_S_C Quantidade do item de mercadoria convertido para a unidade padrao de medida constante no Registro 0200 N - 05 O
          '|'||FORMATFLOAT('#0.00',COALESCE(d.bdVL_V_IND_S,0))|| -- 14 VL_V_IND_S Valor da venda da mercadoria identificada no Registro 2110 N - 02 O
          '|'||COALESCE(SUBSTRING(d.bdCFOP FROM 1 FOR 4),'')|| -- 15 CFOP Codigo Fiscal de Operacao e Prestacao N 004* - O
          '|'||FORMATFLOAT('#0.00',COALESCE(d.bdVL_CREDITO_MVA_SN,0))|| -- 16 VL_CREDITO_MVA_SN Valor credito em decorrencia da saida destinada a contribuinte optante pelo Simples Nacional de mercadoria cuja substituicao tributaria da operacao anterior foi apurada com MVA de contribuinte normal N - 02 OC
          '|'),
         d.bdCODUNIMED,
         d.bdCODPROD
  FROM VEF_EMP_TDRCST_2113 d
  WHERE d.bdCODEMP = :prCODEMP
    AND d.bdREFERENCIA = EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0');

  /*****************************************************************************
   *                                   2114                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA, bdCODPROD)
  SELECT :prARQUIVO AS bdID,
         '2110.'||d.bdCODEMP||'.'||d.bdCODPROD||'.2113.'||d.bdIND_OPER||'.'||d.bdCHAVE||'.'||d.bdORDEM||'.'||d.bdORDEMPRO||'.2114.'||d.bdORDEMIC||'.'||d.bdORDEMDOCFREF AS bdCHAVEREG,
         '2114' AS BDREG,
         d.bdCODEMP,
         ('|2114'||-- 01 REG Texto fixo contendo "2114" C 004 - O
          '|'||IIF(CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(d.bdCNPJ,'')))) = 14,
                   (SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(d.bdCNPJ,''))), '')|| -- 02 CNPJ CNPJ do destinatario da NF-e de venda referenciada N 014* - OC
          '|'||CASE WHEN CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(d.bdCPF,'')))) = 11 THEN (SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(d.bdCPF,''))) -- Comentario apenas para forcar a recompilar a SP pois teve alteracao no campo CPF, de varchar 12 para 14...
                    WHEN CHAR_LENGTH((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(d.bdCNPJ,'')))) = 11 THEN (SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(d.bdCNPJ,''))) -- Haviam casos onde o CPF estava sendo gravado no campo CPF, por isso, valida ambos...
               ELSE '' END|| -- 03 CPF CPF que consta na NF-e de venda referenciada N 011* - OC
          '|'||(TRIM((SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(d.bdCHV_NFE_REF,'')))))|| -- 04 CHV_NFE_REF Numero completo da chave da NF-e de saida referenciada N 044* - OC
          '|'||COALESCE(IIF(d.bdECF_CX_REF > 0, d.bdECF_CX_REF, ''),'')|| -- 05 ECF_CX_REF Numero do caixa atribuido ao ECF N 003 - OC
          '|'||COALESCE(d.bdNUM_DOC_REF,'')|| -- 06 NUM_DOC_REF Numero do documento fiscal N 009 OC
          '|'||LPAD(EXTRACT(DAY FROM d.bdDT_DOC_REF),2,'0')||LPAD(EXTRACT(MONTH FROM d.bdDT_DOC_REF),2,'0')||EXTRACT(YEAR FROM d.bdDT_DOC_REF)|| -- 07 DT_DOC_REF Data da emissao do cupom ou a NF-e de saida referenciada N 008* - O
          '|'),
         d.bdCODPROD
  FROM VEF_EMP_TDRCST_2114 d
  WHERE d.bdCODEMP = :prCODEMP
    AND d.bdREFERENCIA = EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0');

  /*****************************************************************************
   *                                   2115                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA, bdCODPROD)
  SELECT :prARQUIVO AS bdID,
         '2110.'||d.bdCODEMP||'.'||d.bdCODPROD||'.2113.'||d.bdIND_OPER||'.'||d.bdCHAVE||'.'||d.bdORDEM||'.'||d.bdORDEMPRO||'.2115.'||d.bdORDEM2115 AS bdCHAVEREG,
         '2115' AS BDREG,
         d.bdCODEMP,
         ('|2115'|| -- 01 REG Texto fixo contendo "2115" C 004 - O
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(d.bdCHV_NFE_COMP,'')))|| -- 02 CHV_NFE_COMP Número completo da chave da NF-e complementar que referenciou a Nota Fiscal de venda informada no Registro 2113 N 044* - O
          '|'||COALESCE(d.bdNUM_ITEM_NFE_COMP,'')|| -- 03 NUM_ITEM_NFE_COMP Número sequencial do item na NF-e complementar, que corresponde à mercadoria identificada no Registro 2110 N 003 - O
          '|'),
         d.bdCODPROD
  FROM VEF_EMP_TDRCST_2115 d
  WHERE d.bdCODEMP = :prCODEMP
    AND d.bdREFERENCIA = EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0');

  /*****************************************************************************
   *                                   2120                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA, bdCODPROD)
  SELECT :prARQUIVO AS bdID,
         '2110.'||d.bdCODEMP||'.'||d.bdCODPROD||'.2120' AS bdCHAVEREG,
         '2120' AS BDREG,
         d.bdCODEMP,
         ('|2120'|| -- 01 REG Texto fixo contendo "2120|. C 004 - O
          '|'||FORMATFLOAT('#0.00000',Coalesce(d.bdS_QTDE_C,0))|| -- 02 S_QTDE_C Soma das quantidades da mercadoria informadas no campo QTDE_C do Registro 2130 N - 05 O
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdS_VL_BCST_INT,0))|| -- 03 S_VL_BCST_INT Soma dos valores integrais da base de calculo da substituicao tributaria informadas no campo VL_BCST_INT do Registro 2130 N - 02 O
          '|'||FORMATFLOAT('#0.000',Coalesce(d.bdVLM_UNIT_BCST,0))|| -- 04 VLM_UNIT_BCST Valor medio unitario da base de calculo da substituicao tributaria resultado da divisao do campo S_VL_BCST_INT pelo campo S_QTDE _C deste registro N - 03 O
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdS_VL_ICMS,0))|| -- 05 S_VL_ICMS Soma do valor do ICMS sobre operacoes proprias informados no campo VL_ICMS do Registro 2130 N - 02 O
          '|'||FORMATFLOAT('#0.000',Coalesce(d.bdVLM_UNIT_ICMS,0))|| -- 06 VLM_UNIT_ICMS Valor medio unitario do valor do ICMS sobre operacoes proprias resultado da divisao do campo S_VL_ICMS pelo campo S_QTDE_C deste registro N - 03 O
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdS_VL_ICMS_ST,0))|| -- 07 S_VL_ICMS_ST Soma do valor do ICMS_ST dos campos VL_ICMS_ST do Registro 2130 N - 02 O
          '|'||FORMATFLOAT('#0.000',Coalesce(d.bdVLM_UNIT_ICMS_ST,0))|| -- 08 VLM_UNIT_ICMS_ST Valor medio unitario do valor do ICMS_ST resultado da divisao do campo S_VL_ICMS_ST pelo campo S_QTDE_C deste registro N - 03 O
          '|'),
         d.bdCODPROD
  FROM VEF_EMP_TDRCST_2120 d
  WHERE d.bdCODEMP = :prCODEMP
    AND d.bdREFERENCIA = EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0');
    --AND not exists(select first 1 aux.bdcodemp from VEF_EMP_TDRCST_2134 AUX WHERE (AUX.BDCODEMP = D.BDCODEMP AND AUX.BDREFERENCIA = D.BDREFERENCIA AND AUX.BDCODPROD = D.BDCODPROD));
  /*****************************************************************************
   *                                   2121                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA, bdCODPROD)
  SELECT :prARQUIVO AS bdID,
         '2110.'||d.bdCODEMP||'.'||d.bdCODPROD||'.2120'||'.2121' AS bdCHAVEREG,
         '2121' AS BDREG,
         d.bdCODEMP,
         ('|2121'|| -- 01 REG Texto fixo contendo "2121|. C 004 - O
          '|'||FORMATFLOAT('#0.00000',COALESCE(d.BDS_QTDE_C_T,0))|| -- 02 S_QTDE_C_T
          '|'||FORMATFLOAT('#0.00',COALESCE(D.BDS_QTDE_C_VLM,0))|| -- 03 S_QTDE_C_VLM
          '|'||FORMATFLOAT('#0.000',COALESCE(d.BDS_VL_BCST_INT_VLM,0))|| -- 04 S_VL_BCST_INT_VLM
          '|'||FORMATFLOAT('#0.00',COALESCE(d.BDVLM_UNIT_BCST_G,0))|| -- 05 VLM_UNIT_BCST_G
          '|'),
         d.bdCODPROD
  FROM VEF_EMP_TDRCST_2121 D
  WHERE d.bdCODEMP = :prCODEMP
    AND d.bdREFERENCIA = EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0');

  /*****************************************************************************
   *                                   2130                                    *
   *****************************************************************************/
  SETORDEMSEQUENCIAL_STR(0); -- Alt.: #159146 - Alterado para seguir uma ordem por lançamento, quando a nota tinha mais de uma CFOP, acabava exportando mais de um produto com a mesma ordem...
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA, bdCODPROD)
  SELECT :prARQUIVO AS bdID,
         '2110.'||d.bdCODEMP||'.'||d.bdCODPROD||'.2130.'||d.bdIND_OPER||'.'||d.bdCHAVE||'.'||d.bdORDEM||'.'||d.bdORDEMPRO AS bdCHAVEREG,
         '2130' AS BDREG,
         d.bdCODEMP,
         ('|2130'|| -- 01 REG Texto fixo contendo "2130|. C 004 - O
          '|'||COALESCE(d.bdIND_OPER,'')|| -- 02 IND_OPER Indicador do tipo de operacao: 0 - Entrada (Aquisicao); 1- Devolucao de aquisicoes C 001* - O
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(d.bdCHV_NFE,'')))|| -- 03 CHV_NFE Numero completo da chave da NF-e de entrada da mercadoria ou da devolucao de aquisicao N 044* - O
          '|'||COALESCE(LPAD(EXTRACT(DAY FROM d.bdDT_E),2,'0')||LPAD(EXTRACT(MONTH FROM d.bdDT_E),2,'0')||EXTRACT(YEAR FROM d.bdDT_E),'')|| -- 04 DT_E Data da entrada da mercadoria informada na EFD ICMS/IPI N 008* - OC
          '|'||COALESCE(LPAD(EXTRACT(DAY FROM d.bdDT_NFE),2,'0')||LPAD(EXTRACT(MONTH FROM d.bdDT_NFE),2,'0')||EXTRACT(YEAR FROM d.bdDT_NFE),'')|| -- 05 DT_NFE Data da emissao da NF-e de devolucao de aquisicao informada na EFD ICMS/IPI N 008* - OC
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(d.bdCNPJ,'')))|| -- 06 CNPJ CNPJ do emitente da NF-e de aquisicao ou do destinatario que consta da NF-e na devolucao de aquisicao N 014* - O
          '|'||COALESCE(/*d.bdNUM_ITEM*/GETORDEMSEQUENCIAL_STR(d.bdCODEMP||'.'||d.bdCHAVE, 0),'')|| -- 07 NUM_ITEM Numero sequencial do item que consta na NF-e de entrada ou de devolucao de aquisicao que identifica a mercadoria N 003 - O
          '|'||COALESCE(d.bdCOD_RESP_RET,'')|| -- 08 COD_RESP_RET Codigo que indica o responsavel pela retencao do ICMS-ST: 1 |. Remetente Direto 2 |. Remetente Indireto 3 |. Proprio declarante N 001* - OC
          '|'||FORMATFLOAT('#0.00000',Coalesce(d.bdQTDE,0))|| -- 09 QTDE Quantidade do item da mercadoria que consta da NF-e de entrada ou de devolucao de aquisicao N - 05 O
          '|'||COALESCE(d.bdUNID,'')|| -- 10 UNID Unidade do item (Campo 02 do registro 0190) C 006 - O
          '|'||FORMATFLOAT('#0.000000',Coalesce(d.bdFAT_CONV,1))|| -- 11 FAT_CONV Fator de conversao: fator utilizado para converter (multiplicar) a unidade a ser convertida na unidade adotada no inventario N - 06 O
          '|'||FORMATFLOAT('#0.00000',Coalesce(d.bdQTDE_C,0))|| -- 12 QTDE_C Quantidade do item de mercadoria convertido para a unidade padrao de medida constante no Registro 0200 N - 05 O
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdVL_E,0))|| -- 13 VL_E Valor da mercadoria que consta no documento fiscal de entrada incluindo despesas acessorias. Deve ser informado com o mesmo valor no caso de devolucao de aquisicao N - 02 O
          '|'||COALESCE(SUBSTRING(d.bdCFOP FROM 1 FOR 4),'')|| -- 14 CFOP Codigo Fiscal de Operacao e Prestacao N 004* - O
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdVL_BC_ICMS,0))|| -- 15 VL_BC_ICMS Valor da base de calculo da operacao propria que consta na NF-e de entrada ou de devolucao de aquisicao N - 02 OC
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdALIQ_ICMS,0))|| -- 16 ALIQ_ICMS Aliquota do ICMS que consta na NF-e de entrada ou de devolucao de aquisicao N - 02 OC
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdVL_ICMS,0))|| -- 17 VL_ICMS Valor de ICMS sobre operacoes proprias N - 02 O
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdVL_BCST,0))|| -- 18 VL_BCST Valor da base de calculo utilizado no calculo do ICMS pago por substituicao tributaria que consta do documento fiscal de entrada N - 02 OC
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdVL_BCST_INT,0))|| -- 19 VL_BCST_INT Valor integral da base de calculo do ICMS substituicao tributaria quando se utilizar a aliquota efetiva aplicavel, informada no campo ALIQ_ST_EF, na apuracao do imposto devido N - 02 O
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdALIQ_ST_E,0))|| -- 20 ALIQ_ST_E Aliquota utilizada no calculo do ICMS pago por substituicao tributaria que consta do documento fiscal de entrada N - 02 OC
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdALIQ_ST_EF,0))|| -- 21 ALIQ_ST_ EF Aliquota do ICMS efetiva (percentual de carga tributaria efetiva) da substituicao tributaria, aplicavel a base de calculo integral, informada no campo VL_BCST_INT deste registro N - 02 OC
          '|'||FORMATFLOAT('#0.000',Coalesce(d.bdCAL_ICMS_ST,0))|| -- 22 CAL_ICMS_ST Valor do ICMS-ST calculado pela multiplicacao dos campos VL_BCST e ALIQ_ST_E e dos campos VL_BCST_INT e ALIQ_ST_ EF deste registro N - 03 OC
          '|'||FORMATFLOAT('#0.00',Coalesce(d.bdVL_ICMS_ST,0))|| -- 23 VL _ICMS_ST Valor do ICMS-ST que consta da NF-e ou, se for o caso, o valor declarado pelo proprio informante, no caso de COD_RESP_RET = 3 N - 02 O
          '|'||COALESCE(d.bdCOD_DA,'')|| -- 24 COD_DA Codigo do modelo do documento de arrecadacao: 0 - DARE 1 - GNRE C 001* - OC
          '|'||COALESCE(d.bdNUM_DARE,'')|| -- 25 NUM_DARE Numero do DARE C - - OC
          '|'||COALESCE(d.bdCOD_AJ,'')|| -- 26 COD_AJ Codigo do Ajuste de debito informado no Registro C197 da EFD ICMS/IPI C - - OC
          '|'),
         d.bdCODPROD
  FROM VEF_EMP_TDRCST_2130 d
  WHERE d.bdCODEMP = :prCODEMP
    AND d.bdREFERENCIA = EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0');

  /*****************************************************************************
   *                                   2132                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA, bdCODPROD)
  SELECT :prARQUIVO AS bdID,
         '2110.'||d.bdCODEMP||'.'||d.bdCODPROD||'.2130.'||d.bdIND_OPER||'.'||d.bdCHAVE||'.'||d.bdORDEM||'.'||d.bdORDEMPRO||'.2130.'||d.bdORDEMIC||'.'||d.bdORDEMDOCFREF AS bdCHAVEREG,
         '2132' AS BDREG,
         d.bdCODEMP,
         ('|2132'|| -- 01 REG Texto fixo contendo "2132" C 004 - O
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(d.bdCNPJ,'')))|| -- 02 CNPJ CNPJ do emitente da NF-e referenciada N 014* - O
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(d.bdCHV_NFE_REF,'')))|| -- 03 CHV_NFE_REF Numero completo da chave da NF-e da entrada referenciada N 044* - O
          '|'||LPAD(EXTRACT(DAY FROM d.bdDT_E_REF),2,'0')||LPAD(EXTRACT(MONTH FROM d.bdDT_E_REF),2,'0')||EXTRACT(YEAR FROM d.bdDT_E_REF)|| -- 04 DT_E_REF Data da entrada da NF-e referenciada informada no demonstrativo onde registrado sua entrada N 008* - O
          '|'),
         d.bdCODPROD
  FROM VEF_EMP_TDRCST_2132 d
  WHERE d.bdCODEMP = :prCODEMP
    AND d.bdREFERENCIA = EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0');

  /*****************************************************************************
   *                                   2133                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA, bdCODPROD)
  SELECT :prARQUIVO AS bdID,
         '2110.'||d.bdCODEMP||'.'||d.bdCODPROD||'.2130.'||d.bdIND_OPER||'.'||d.bdCHAVE||'.'||d.bdORDEM||'.'||d.bdORDEMPRO||'.2133.'||d.bdORDEM2133 AS bdCHAVEREG,
         '2133' AS BDREG,
         d.bdCODEMP,
         ('|2133'|| -- 01 REG Texto fixo contendo "2133" C 004 - O
          '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(COALESCE(d.bdCHV_NFE_COMP,'')))|| -- 02 CHV_NFE_COMP Número completo da chave da NF-e complementar que referenciou a Nota Fiscal de entrada informada no Registro 2130 N 044* - O
          '|'||COALESCE(d.bdNUM_ITEM_NFE_COMP,'')|| -- 03 NUM_ITEM_NFE_COMP Número sequencial do item na NF-e complementar, que corresponde a mercadoria identificada no Registro 2110 N 003 - O
          '|'),
         d.bdCODPROD
  FROM VEF_EMP_TDRCST_2133 d
  WHERE d.bdCODEMP = :prCODEMP
    AND d.bdREFERENCIA = EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0');

  /*****************************************************************************
   *                                   2134                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA, bdCODPROD)
  SELECT :prARQUIVO AS bdID,
         '2110.'||d.bdCODEMP||'.'||d.bdCODPROD||'.2130.'||d.bdIND_OPER||'.'||d.bdCHAVE||'.'||d.bdORDEM||'.'||d.bdORDEMPRO||'.2134.'||d.bdORDEM2134 AS bdCHAVEREG,
         '2134' AS BDREG,
         d.bdCODEMP,
         ('|2134'|| -- 01 REG Texto fixo contendo "2134" C 004 - O
          '|'||COALESCE(d.BDCOD_IND_XML,'')|| -- 02 COD_IND_XML Codigo preenchimento de tag com informacao do ICMS cobrado anteriormente por ST  N 001 - O
          '|'),
         d.bdCODPROD
  FROM VEF_EMP_TDRCST_2134 d
  WHERE d.bdCODEMP = :prCODEMP
    AND d.bdREFERENCIA = EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0');

  /*****************************************************************************
   *                                   2990                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         '2990.'||s.bdCODEMP AS bdCHAVEREG,
         '2990' AS BDREG,
         s.bdCODEMP,
         ('|2990'|| -- 01 REG Texto fixo contendo "2990" C 004 - O
          '|'||(COUNT(COALESCE(s.bdCODEMP,1))+1)|| -- 02 QTD_LIN_2 Quantidade total de linhas do Bloco 2 N - - O
          '|')
  FROM TEXPORTACAO_SPED s
  WHERE SUBSTRING(s.bdREG FROM 1 FOR 1) LIKE '2'
    AND s.bdID = :prARQUIVO
    AND s.bdCODEMP = :prCODEMP
  GROUP BY s.bdCODEMP;

END
^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCST_BLOCOH (
    PRCODEMP INTEGER,
    PRDTINI DATE,
    PRDTFIM DATE,
    PRDTINV DATE,
    PRMOTIVOINVENTARIO INTEGER,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
  /*****************************************************************************
   *                                   H010                                    *
   *****************************************************************************/
  IF ((:prDTINV IS NOT NULL) AND (:prDTINV > '12-31-1899')) THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA, bdCODPROD, bdCODUNIMED, bdVALOR, bdCODTER)
      SELECT :prARQUIVO AS bdID,
             'H010.'||inv.bdCODEMP||'.'||COALESCE(pro.bdCODSAIDA,'')||'.'||COALESCE(inv.bdCODPROD,'')||'.'||COALESCE(um.bdAPEUNIMED,'')||'.'||COALESCE(inv.bdCODTER,'') AS bdCHAVEREG,
             'H010' AS BDREG,
             inv.bdCODEMP,
             ('|H010'|| -- 01 REG Texto fixo contendo "H010" C 004 - O
              '|'||COALESCE(pro.bdCODSAIDA,inv.bdCODPROD)|| -- 02 COD_ITEM Codigo do item (campo 02 do Registro 0200) C 060 - O
              '|'||COALESCE(um.bdAPEUNIMED,'')|| -- 03 UNID Unidade do item C 006 - O
              '|'||FORMATFLOAT('#0.000',inv.bdQTDINV)|| -- 04 QTD Quantidade do item N - 03 O
              '|'||FORMATFLOAT('#0.000000',inv.bdVLRUNITINV)|| -- 05 VL_UNIT Valor unitario do item N - 06 O
              '|'||FORMATFLOAT('#0.00',(inv.bdVLRUNITINV * inv.bdQTDINV))|| -- 06 VL_ITEM Valor do item N - 02 O
              '|'||COALESCE(inv.bdCODPOSSE-1,-1)|| -- 07 IND_PROP Indicador de propriedade/posse do item: 0- Item de propriedade do informante e em seu poder; 1- Item de propriedade do informante em posse de terceiros;  2- Item de propriedade de terceiros em posse do informante
              '|'||COALESCE(inv.bdCODTER,'')|| -- 08 COD_PART Codigo do participante (campo 02 do Registro 0150): - proprietario/possuidor que nao seja o informante do arquivo C 060 - OC
              '|'||REPLACE((COALESCE(obs.bdNOMEOBS,'')), '|', '')|| -- 09 TXT_COMPL Descricao complementar. C - - OC
              '|'||COALESCE(cta.bdCONTACTA,'')|| -- 10 COD_CTA Codigo da conta analitica contabil debitada/creditada C - - O
              -- Alt:#11077  Elizeu - 18-02-2015 - falta um campo no leiaute novo 009, isso ocasiona erro de estrutura
              IIF((:prDTINI >= '01-01-2015'),'|'||FORMATFLOAT('#0.00',(inv.bdVLRITEMIR)),'')|| -- Maicon S. Silva 18/04/2016 - 13543 - Campo novo do IR
              '|'),
              COALESCE(pro.bdCODPROD,inv.bdCODPROD),
              pro.bdCODUNIMED,
              (inv.bdVLRUNITINV * inv.bdQTDINV),
              inv.bdCODTER
      FROM VEF_EMP_TMOVINV inv
      LEFT OUTER JOIN VEF_BASE_TTABCTA cta ON (inv.bdCODCTA = cta.bdCODCTA)
      LEFT OUTER JOIN VEF_BASE_TOBSERVACAO obs ON (inv.bdCODOBS = obs.bdCODOBS)
      LEFT OUTER JOIN TCADPRO_VINC pro ON (pro.bdCODEMP = inv.bdCODEMP AND pro.bdCODPROD = inv.bdCODPROD)
      LEFT OUTER JOIN TUNIDADEMEDIDA um ON (um.bdCODUNIMED = pro.bdCODUNIMED)         
      JOIN (SELECT s.bdCODPROD
               FROM TEXPORTACAO_SPED s
               WHERE s.bdCODPROD IS NOT NULL
                 AND s.bdID = :prARQUIVO
                 AND s.bdCODEMP = :prCODEMP
               GROUP BY S.BDCODPROD) S ON (S.BDCODPROD = COALESCE(pro.bdCODPROD,inv.bdCODPROD))
      WHERE inv.bdREFINV = EXTRACT(YEAR FROM :prDTINV)||LPAD(EXTRACT(MONTH FROM :prDTINV),2,'0')
        AND inv.bdCODEMP = :prCODEMP
        AND inv.bdCODPOSSE = 1;
    END

  /*****************************************************************************
   *                                   H001                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  VALUES (:prARQUIVO, 'H001.'||:prCODEMP, 'H001', :prCODEMP,
          '|H001'|| -- 01 REG Texto fixo contendo |H001|. C 004 - O
          '|'||IIF((SELECT FIRST 1 s.bdCODEMP FROM TEXPORTACAO_SPED s WHERE s.bdCODEMP = :prCODEMP AND s.bdID = :prARQUIVO) = :prCODEMP,'0','1')||
          '|');   -- 02 IND_MOV Indicador de movimento: 0- Bloco com dados informados; 1- Bloco sem dados informados.

  /*****************************************************************************
   *                                   H005                                    *
   *****************************************************************************/
  IF ((:prDTINV IS NOT NULL) AND (:prDTINV > '12-31-1899')) THEN
    BEGIN
      INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
      SELECT :prARQUIVO AS bdID,
             'H005.'||s.bdCODEMP AS bdCHAVEREG,
             'H005' AS BDREG,
             s.bdCODEMP,
             ('|H005'|| -- 01 REG Texto fixo contendo "H005"          C  004    -  O
              '|'||LPAD(EXTRACT(DAY FROM :prDTINV),2,'0')||LPAD(EXTRACT(MONTH FROM :prDTINV),2,'0')||EXTRACT(YEAR FROM :prDTINV)|| -- 02 DT_INV Data do inventario               N  008*   -  O
              '|'||FORMATFLOAT('#0.00',SUM(COALESCE(s.bdVALOR,0)))|| -- 03 VL_INV Valor total do estoque           N    -   02  O
              '|'||LPAD(COALESCE(:prMOTIVOINVENTARIO+1,''), 2, '0')|| -- 04 MOT_INV Informe o motivo do Inventario  C  002*   -  O
                                                        -- "01 |. No final no periodo;"
                                                        -- "02 |. Na mudanca de forma de tributacao da mercadoria (ICMS);"
                                                        -- "03 |. Na solicitacao da baixa cadastral, paralisacao temporaria e outras situacoes;"
                                                        -- "04 |. Na alteracao de regime de pagamento |. condicao do contribuinte;"
                                                        -- "05 |. Por determinacao dos fiscos."
              '|')
      FROM TEXPORTACAO_SPED s
      WHERE s.bdID = :prARQUIVO
        AND s.bdCODEMP = :prCODEMP
      GROUP BY s.bdCODEMP;
    END

  /*****************************************************************************
   *                                   H990                                    *
   *****************************************************************************/
  INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
  SELECT :prARQUIVO AS bdID,
         'H990.'||s.bdCODEMP AS bdCHAVEREG,
         'H990' AS BDREG,
         s.bdCODEMP,
         ('|H990'|| -- 01 REG Texto fixo contendo "H990"          C  004    -  O
          '|'||(COUNT(COALESCE(s.bdCODEMP,1))+1)|| -- 02 QTD_LIN_H Quantidade total de linhas do Bloco H N - - O
          '|')
  FROM TEXPORTACAO_SPED s
  WHERE SUBSTRING(s.bdREG FROM 1 FOR 1) LIKE 'H'
    AND s.bdID = :prARQUIVO
    AND s.bdCODEMP = :prCODEMP
  GROUP BY s.bdCODEMP;

END
^

CREATE OR ALTER procedure SP_EXPORTA_DRCST (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRDTINV date,
    PRMOTIVOINVENTARIO integer,
    PRFINALIDADE integer,
    PRARQUIVO varchar(260))
as
declare variable WLINHA blob sub_type 1 segment size 200;
declare variable WEMPATU integer;
declare variable WARQUIVOEMP varchar(260);
BEGIN
  DELETE FROM TEXPORTACAO_SPED WHERE BDID = :prARQUIVO;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA((SELECT bdDATA FROM SP_PARSE_DATE(:prDTFIM, 'YYYYMM')));

  FOR
      SELECT e.BDCODEMP
      FROM TEMPRESAS e
      WHERE (e.bdCODEMP = :prCODEMP)
        AND EXISTS(SELECT d.* -- Apenas se existir apuracao com algum valor...
                   FROM VEF_EMP_TDRCST_2110 d
                   WHERE d.bdCODEMP = e.bdCODEMP
                     AND d.bdREFERENCIA = EXTRACT(YEAR FROM :prDTINI)||LPAD(EXTRACT(MONTH FROM :prDTINI),2,'0')
                     AND ((d.bdQTDE_T_V_CF > 0)
                      OR  (d.bdVL_T_V_CF > 0)
                      OR  (d.bdVLM_UNIT_V_CF > 0)
                      OR  (d.bdVL_T_BCST_V_CF > 0)
                      OR  (d.bdVL_DIF_MAIOR_BCST > 0)
                      OR  (d.bdVL_DIF_MENOR_BCST > 0)
                      OR  (d.bdALIQ_EF > 0)
                      OR  (d.bdQTDE_T_IND_S_OE > 0)
                      OR  (d.bdQTDE_T_IND_S_SN > 0)
                      OR  (d.bdVL_ICMS_IND_S_OE > 0)
                      OR  (d.bdVL_ICMSST_IND_S_OE > 0)
                      OR  (d.bdVL_ICMS_ST_REST > 0)
                      OR  (d.bdVL_ICMS_ST_COMPL > 0)
                      OR  (d.bdVL_T_CREDITO_MVA_SN > 0)))
  INTO :wEMPATU DO
    BEGIN
      /*Cria arquivo da empresa que vai ser exportada*/
      wARQUIVOEMP = REPLACE(:prARQUIVO, '.tmp', '_e='||:wEMPATU||'_.tmp'); -- Precisa do "_" para conseguir exportar várias empresas em "TExternalFile.Exportar"
      NEWFILE(:wARQUIVOEMP);

      /* BLOCO 2 */
      EXECUTE PROCEDURE SP_EXPORTA_DRCST_BLOCO2(:wEMPATU, :prDTINI, :prDTFIM, :prDTINV, :wARQUIVOEMP);         

      /* BLOCO H */
      EXECUTE PROCEDURE SP_EXPORTA_DRCST_BLOCOH(:wEMPATU, :prDTINI, :prDTFIM, :prDTINV, :prMOTIVOINVENTARIO, :wARQUIVOEMP);

      /* BLOCO 0 */
      EXECUTE PROCEDURE SP_EXPORTA_DRCST_BLOCO0(:wEMPATU, :prDTINI, :prDTFIM, :prFINALIDADE, :wARQUIVOEMP);

      /* BLOCO 9 */
      EXECUTE PROCEDURE SP_EXPORTA_DRCST_BLOCO9(:wEMPATU, :prDTINI, :prDTFIM, :prDTINV, :wARQUIVOEMP);

      /* Inconsistencias */
      EXECUTE PROCEDURE SP_EXPORTA_DRCST_INCONSISTENCIA(:wEMPATU, :prDTINI, :prDTFIM, :prDTINV, :wARQUIVOEMP);

      /*****************************************************************************
       *                             EXPORTANDO ARQUIVO                            *
       *****************************************************************************/
      OPENARQ(:wARQUIVOEMP,:wEMPATU);
      
      FOR SELECT e.bdLINHA
          FROM TEXPORTACAO_SPED e
          WHERE e.bdID = :wARQUIVOEMP
          ORDER BY e.bdCHAVEREG
          INTO :wLINHA
      DO
        BEGIN
          WRITELNOA(:wLINHA,:wEMPATU);
        END
    
      CLOSEARQ(:wARQUIVOEMP,:wEMPATU);
    END
END
^

CREATE OR ALTER TRIGGER TSQLLENTO_BI0 FOR TSQLLENTO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  new.BDDATAHORA = localtimestamp;
end
^

create or alter  trigger tzona_bi0 for tzona
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;

BEGIN
  IF ((NEW.bdcodzona IS NULL) OR (NEW.bdcodzona = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodzona), 0) + 1 FROM TZONA INTO :vCodigo;
       NEW.bdcodzona = :vCodigo;
     END
END^



CREATE OR ALTER TRIGGER TMP_VTPO_ATIVIDADE_EXE_REG_BI0 FOR TMP_VTPO_ATIVIDADE_EXE_REGISTRO
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (NEW.BDCHAVE IS NULL OR NEW.BDCHAVE = 0) THEN
    BEGIN
      SELECT COALESCE(MAX(BDCHAVE) + 1, 1) FROM TMP_VTPO_ATIVIDADE_EXE_REGISTRO INTO NEW.BDCHAVE;
    END
END
^

/* Trigger: VEF_EMP_TMOVRATREDZVARCFOP_BI0 */
CREATE OR ALTER TRIGGER VEF_EMP_TMOVRATREDZVARCFOP_BI0 FOR VEF_EMP_TMOVRATREDZVARCFOP
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vCODIGO = 0;

  IF ((new.bdCHAVE IS NULL) OR (new.bdCHAVE = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(z.bdCHAVE)), 1) FROM VEF_EMP_TREDZ z WHERE (z.bdCODEMP = new.bdCODEMP) INTO vCODIGO;
      new.bdCHAVE = vCODIGO;
    END

  IF ((new.bdORDEMVARCFOP IS NULL) OR (new.bdORDEMVARCFOP = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(v.bdORDEMVARCFOP)), 1) FROM VEF_EMP_TREDZVARCFOP v WHERE (v.bdCODEMP = new.bdCODEMP) AND (v.bdCHAVE = new.bdCHAVE) INTO vCODIGO;
      new.bdORDEMVARCFOP = vCODIGO;
    END

  IF ((new.bdORDEMRAT IS NULL) OR (new.bdORDEMRAT = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEMRAT) + 1), 1) FROM VEF_EMP_TMOVRATREDZVARCFOP WHERE (bdCODEMP = new.bdCODEMP AND bdCHAVE = new.bdCHAVE AND bdORDEMVARCFOP = new.bdORDEMVARCFOP) INTO vCODIGO;
      new.bdORDEMRAT = vCODIGO;
    END
  ELSE
    BEGIN
      SELECT bdORDEMRAT FROM VEF_EMP_TMOVRATREDZVARCFOP WHERE (bdCODEMP = new.bdCODEMP AND bdCHAVE = new.bdCHAVE AND bdORDEMVARCFOP = new.bdORDEMVARCFOP AND bdORDEMRAT = new.bdORDEMRAT) INTO vCODIGO;

      IF (vCODIGO > 0) THEN
        BEGIN
          SELECT COALESCE((MAX(bdORDEMRAT) + 1), 1) FROM VEF_EMP_TMOVRATREDZVARCFOP WHERE (bdCODEMP = new.bdCODEMP AND bdCHAVE = new.bdCHAVE AND bdORDEMVARCFOP = new.bdORDEMVARCFOP) INTO vCODIGO;
          new.bdORDEMRAT = vCODIGO;
        END
   END
END
^

CREATE OR ALTER trigger tol_vef_emp_tmovratredzvarcf_bi for tol_vef_emp_tmovratredzvarcfop
active before insert position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdcodempsuc is null)  or (new.bdcodempsuc = 0) )  then
    new.bdcodempsuc = new.bdcodemp;
  end
end^

/* Trigger: TOL_VEF__TMOVRATREDZVARCFOP_AD0 */
CREATE OR ALTER TRIGGER TOL_VEF__TMOVRATREDZVARCFOP_AD0 FOR TOL_VEF_EMP_TMOVRATREDZVARCFOP
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(old.BDCODEMPSUC,old.bdCHAVE);
END
^

CREATE OR ALTER procedure VEF_SP_PLANO_TROCA_LISTA_CFOPS (
    PRPLANO integer,
    PRCHAVE integer)
returns (
   bdcodplatroca INTEGER,
   BDCHAVE INTEGER,
   BDCFOPS varchar(32765)
    )
as
BEGIN

  select BDCODPLATROCA, BDCHAVE,list(C.BDCLASSIFICACAO) from VEF_BASE_TPLANOACOESTROCACFOPS N
  join VEF_BASE_TNATOP C on (C.BDCODNAT = N.BDCODNAT)
  where N.BDCODPLATROCA = :PRPLANO and N.BDCHAVE = :PRCHAVE
  group by BDCODPLATROCA, BDCHAVE INTO
  :BDCODPLATROCA, :BDCHAVE,:BDCFOPS;

  SUSPEND;

END^

/* Restore proc. body: SP_VRHF_REL_ACOMPANHAMENTO */
CREATE OR ALTER procedure SP_VRHF_REL_ACOMPANHAMENTO (
    PRCODEMP varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXAFILIAIS smallint = 0,
    PRAGRUPAFILIAIS smallint = 0)
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDCOMPETENCIA integer,
    BDDATABASEEMP varchar(20),
    BDTRIBUTACAO varchar(200),
    BDTOTSAL numeric(18,2),
    BDTOTSALMENOR numeric(18,2),
    BDTOTSALPRO numeric(18,2),
    BDTOTSALSERV numeric(18,2),
    BDTOTARRED numeric(18,2),
    BDTOTDESC numeric(18,2),
    BDTOTDESCMENOR numeric(18,2),
    BDTOTDESCPRO numeric(18,2),
    BDTOTDESCSERV numeric(18,2),
    BDLIQFERIAS numeric(18,2),
    BDLIQRESC numeric(18,2),
    BDLIQSERV numeric(18,2),
    BDLIQUIDO numeric(18,2),
    BDFGTS numeric(18,2),
    BDFGTSMENOR numeric(18,2),
    BDGRRF numeric(18,2),
    BDGRRF40 numeric(18,2),
    BDGRRF20 numeric(18,2),
    BDGRRF10 numeric(18,2),
    BDCONTSIND numeric(18,2),
    BDCONTCONF numeric(18,2),
    BDMENSSALSIND numeric(18,2),
    BDTAXAASSIST numeric(18,2),
    BDREVERSAL numeric(18,2),
    BDSUBPAT numeric(18,2),
    BDSUBCONJ numeric(18,2),
    BDATIVOSMESANT integer,
    BDADMISSOES integer,
    BDRESCISOES integer,
    BDDATAMESANT date,
    BDULTDIAMES date,
    BDTOTAFASTAMENTOS integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP DM_CNPJ_CPF,
    BDVALFUNRURAL numeric(18,2),
    BDVALAGROIND numeric(18,2),
    BDIRRFCOL numeric(18,2),
    BDIRRFPRO numeric(18,2),
    BDIRRFSERV numeric(18,2),
    BDPERCPIS numeric(18,2),
    BDVALORPIS numeric(18,2),
    BDTOTSALA13 numeric(18,2),
    BDTOTSAL13 numeric(18,2))
as
declare variable WSQL varchar(32700);
declare variable WREFATU integer;
declare variable WCODMATRIZ integer;
declare variable WCODCOL integer;
declare variable WANOMESC varchar(6);
declare variable WPRIDIAC varchar(10);
declare variable WULTDIAC varchar(10);
declare variable WPRIDIA date;
declare variable WULTDIA date;
declare variable WULTDIAANT date;
declare variable WDIA integer;
declare variable WCAT integer;
declare variable WCATESOCIAL integer;
declare variable WDATAADM date;
declare variable WDATARESC date;
declare variable WDATATRF date;
declare variable WGRUPOCLA integer;
declare variable WCODVER integer;
declare variable WVALVFN numeric(18,6);
declare variable WCLAVER varchar(20);
declare variable WTIPOCODVER integer;
declare variable WFGTS numeric(18,2);
declare variable W40 numeric(18,2);
declare variable W10 numeric(18,2);
declare variable WREFFN integer;
declare variable WREFFC integer;
declare variable WCODSINPAT integer;
declare variable WDATABASE integer;
declare variable WCODENQFED integer;
declare variable WFORMATRIB integer;
declare variable WTRIBUT varchar(200);
declare variable WLIQUIDO numeric(18,2);
declare variable WREFRESC integer;
declare variable WCOMPANT integer;
declare variable WBASEPIS DM_BOOLEAN;
begin
  wsql = 'select BDCODEMP, BDCODEMPORIGINAL, BDCNPJEMP from ('||
             'select COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, case when EMP.BDCODMATRIZ is null then null else EMP.BDCODEMP end BDCODEMPORIGINAL, EMP.BDCNPJEMP '||
             'from TEMPRESAS EMP ';

  if (coalesce(prcodemp, '') <> '') then
     begin
       wsql = wsql||' where ('||REPLACE(UPPER(prcodemp), 'BDCODEMP', 'EMP.BDCODEMP')||') ';

       if (coalesce(prpuxafiliais, 0) = 1) then
          wsql = wsql||' or ('||REPLACE(UPPER(prcodemp), 'BDCODEMP', 'EMP.BDCODMATRIZ')||') ';
     end

  wsql = wsql||') order by BDCODEMP, BDCODEMPORIGINAL ';

  select TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) from rdb$database into :wanomesc;
  select TRIM(rdb$get_context('USER_SESSION', 'W_PRIDIAMES')) from rdb$database into :wpridiac;
  select TRIM(rdb$get_context('USER_SESSION', 'W_ULTDIAMES')) from rdb$database into :wultdiac;

  for execute statement wsql into :BDCODEMP, :wcodmatriz, :BDCNPJEMP do
    begin
      BDCODMATRIZ       = BDCODEMP;
      BDCODEMP          = COALESCE(wcodmatriz, BDCODEMP);
      BDDATABASEEMP     = 0;
      BDTRIBUTACAO      = '';
      BDTOTSAL          = 0;
      BDTOTSALMENOR     = 0;
      BDTOTSALPRO       = 0;
      BDTOTSALSERV      = 0;
      BDTOTARRED        = 0;
      BDTOTDESC         = 0;
      BDTOTDESCMENOR    = 0;
      BDTOTDESCPRO      = 0;
      BDTOTDESCSERV     = 0;
      BDLIQFERIAS       = 0;
      BDLIQRESC         = 0;
      BDLIQSERV         = 0;
      BDLIQUIDO         = 0;
      BDFGTS            = 0;
      BDFGTSMENOR       = 0;
      BDGRRF            = 0;
      BDGRRF40          = 0;
      BDGRRF20          = 0;
      BDGRRF10          = 0;
      BDCONTSIND        = 0;
      BDCONTCONF        = 0;
      BDMENSSALSIND     = 0;
      BDTAXAASSIST      = 0;
      BDREVERSAL        = 0;
      BDSUBPAT          = 0;
      BDSUBCONJ         = 0;
      BDATIVOSMESANT    = 0;
      BDADMISSOES       = 0;
      BDRESCISOES       = 0;
      BDDATAMESANT      = null;
      BDULTDIAMES       = null;
      BDTOTAFASTAMENTOS = 0;
      BDVALFUNRURAL     = 0;
      BDVALAGROIND      = 0;
      BDIRRFCOL         = 0;
      BDIRRFPRO         = 0;
      BDIRRFSERV        = 0;
      BDPERCPIS         = 0;
      BDVALORPIS        = 0;
      BDTOTSALA13       = 0;
      BDTOTSAL13        = 0;

      wrefatu           = prrefini;

      while (wrefatu <= prreffim) do
        begin
          BDCOMPETENCIA = wrefatu;

          wcodsinpat = null;
          if (coalesce(pragrupafiliais, 0) = 1) then
             select first 1 BDCODSINPAT from VRHF_BASE_TEMPGRCS where BDCODEMP = :BDCODMATRIZ and BDREFEMP <= :wrefatu order by BDREFEMP DESC into :wcodsinpat;
          else
             select first 1 BDCODSINPAT from VRHF_BASE_TEMPGRCS where BDCODEMP = :BDCODEMP and BDREFEMP <= :wrefatu order by BDREFEMP DESC into :wcodsinpat;

          BDNOMEMP = null;
          if (coalesce(pragrupafiliais, 0) = 1) then
             select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :BDCODMATRIZ and BDREFEMP <= :wrefatu order by BDREFEMP DESC into :BDNOMEMP;
          else
             select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :wrefatu order by BDREFEMP DESC into :BDNOMEMP;

          wdatabase = null;
          select first 1 BDDATABASEEMP - 1 from VRHF_BASE_TEMPRAIS where BDCODEMP = :BDCODEMP and BDREFEMP <= :wrefatu  order by BDCODEMP,BDREFEMP desc into :wdatabase;
          wdatabase = coalesce(wdatabase, 0);

          if ((wdatabase = 0) and (coalesce(wcodsinpat, 0) > 0)) then
             begin
               select BDDATABASESINPAT from VRHF_BASE_TSINDPATRONAL where BDCODSINPAT = :wcodsinpat into :wdatabase;
               wdatabase = coalesce(wdatabase, 0);
             end

               if (wdatabase = 1) then
                  BDDATABASEEMP = 'Fevereiro';
               else
               if (wdatabase = 2) then
                  BDDATABASEEMP = 'Março';
               else
               if (wdatabase = 3) then
                  BDDATABASEEMP = 'Abril';
               else
               if (wdatabase = 4) then
                  BDDATABASEEMP = 'Maio';
               else
               if (wdatabase = 5) then
                  BDDATABASEEMP = 'Junho';
               else
               if (wdatabase = 6) then
                  BDDATABASEEMP = 'Julho';
               else
               if (wdatabase = 7) then
                  BDDATABASEEMP = 'Agosto';
               else
               if (wdatabase = 8) then
                  BDDATABASEEMP = 'Setembro';
               else
               if (wdatabase = 9) then
                  BDDATABASEEMP = 'Outubro';
               else
               if (wdatabase = 10) then
                  BDDATABASEEMP = 'Novembro';
               else
               if (wdatabase = 11) then
                  BDDATABASEEMP = 'Dezembro';
               else
                  BDDATABASEEMP = 'Janeiro';

          wtribut = '';
          wcodenqfed = null;
          wformatrib = null;
          if (coalesce(pragrupafiliais, 0) = 1) then
             select first 1 BDCODENQFED, BDFORMATRIBUTACAO from TENQFED where BDCODEMP = :BDCODMATRIZ and BDREFEMP <= :wrefatu order by BDREFEMP DESC into :wcodenqfed, :wformatrib;
          else
             select first 1 BDCODENQFED, BDFORMATRIBUTACAO from TENQFED where BDCODEMP = :BDCODEMP and BDREFEMP <= :wrefatu order by BDREFEMP DESC into :wcodenqfed, :wformatrib;

          wcodenqfed = coalesce(wcodenqfed, 0);
          wformatrib = coalesce(wformatrib, 0);

          if (wcodenqfed > 0) then
             begin
               select BDDESCENQFED from TCADENQFED where BDCODENQFED = :wcodenqfed into :wtribut;
               BDTRIBUTACAO = coalesce(wtribut, '');
             end


          -- Enquadramento Federal igual a Normal
          if (wcodenqfed = 3) then
             begin
               if (wformatrib >= 0 and BDTRIBUTACAO <> '') then
                  BDTRIBUTACAO = BDTRIBUTACAO||' - ';

               if (wformatrib = 1) then
                  BDTRIBUTACAO = BDTRIBUTACAO||'Lucro presumido';
               else
               if (wformatrib = 2) then
                  BDTRIBUTACAO = BDTRIBUTACAO||'Lucro real';
               else
               if (wformatrib = 3) then
                  BDTRIBUTACAO = BDTRIBUTACAO||'Imune do IRPJ';
               else
               if (wformatrib = 4) then
                  BDTRIBUTACAO = BDTRIBUTACAO||'Isento do IRPJ';
             end

          -- Primeiro dia da competência atual
          wpridia = CAST((SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2)||'-01-'||SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4)) AS DATE);
          -- Último dia da competência atual
          select ULTDIA from ULTIMO_DIA_MES(CAST(SUBSTRING(:BDCOMPETENCIA FROM 5 FOR 2) AS SMALLINT), CAST(SUBSTRING(:BDCOMPETENCIA FROM 1 FOR 4) AS INTEGER)) into :wdia;
          wultdia = CAST((SUBSTRING(BDCOMPETENCIA FROM 5 FOR 2)||'-'||LPAD(wdia, 2, '0')||'-'||SUBSTRING(BDCOMPETENCIA FROM 1 FOR 4)) AS DATE);
          execute procedure sp_seta_competencia(:BDCOMPETENCIA, :wpridia, :wultdia);
          wultdiaant = wpridia - 1;
          wcompant = CAST((SUBSTRING(CAST(wultdiaant AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(wultdiaant AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER);

          BDDATAMESANT = wultdiaant;
          BDULTDIAMES  = wultdia;

          for select BDCODCOL, SUM(coalesce(BDFGTSFN, 0) + coalesce(BDFGTS13FN, 0) + coalesce(BDFGTSFEFN, 0)), SUM(coalesce(BDLIQUIDO, 0)) from (
                  select BDCODEMP, BDCODCOL, BDFGTSFN, BDFGTS13FN, BDFGTSFEFN, BDLIQUIDO
                  from VRHF_EMP_TFOLHANORMAL
                  where BDCODEMP = :BDCODEMP and BDREFFN = :wrefatu
                  union all
                  select BDCODEMP, BDCODCOL, BDFGTSFN, BDFGTS13FN, BDFGTSFEFN, BDLIQUIDO
                  from VRHF_EMP_TFOLHAINT
                  where BDCODEMP = :BDCODEMP and BDREFFN = :wrefatu
                  union all
                  select BDCODEMP, BDCODCOL, BDFGTSFT, BDFGTS13FT, BDFGTSFEFT, BDLIQUIDO
                  from VRHF_EMP_TFOLHATOMADOR
                  where BDCODEMP = :BDCODEMP and BDREFTOMADOR = :wrefatu
                  union all
                  select BDCODEMP, BDCODCOL, BDFGTSFT, BDFGTS13FT, BDFGTSFEFT, BDLIQUIDO
                  from VRHF_EMP_TFOLHATOMINT
                  where BDCODEMP = :BDCODEMP and BDREFTOMADOR = :wrefatu
                  union all
                  select BDCODEMP, BDCODCOL, BDFGTSFC, BDFGTS13FC, BDFGTSFEFC, BDLIQUIDO
                  from VRHF_EMP_TFOLHACOMP
                  where BDCODEMP = :BDCODEMP and ((BDCODTIPOFC =  1 and BDREFFN =:wrefatu) or
                                                  (BDCODTIPOFC <> 1 and BDDATAPAGFC between :wpridia and :wultdia))
                  union all
                  select BDCODEMP, BDCODCOL, BDFGTSFC, BDFGTS13FC, BDFGTSFEFC, BDLIQUIDO
                  from VRHF_EMP_TFOLTOMCOMP
                  where BDCODEMP = :BDCODEMP and  ((BDCODTIPOFC =  1 and BDREFTOMADOR =:wrefatu) or
                                                   (BDCODTIPOFC <> 1 and BDDATAPAGFC between :wpridia and :wultdia))
                  union all
                  select BDCODEMP, BDCODCOL, BDFGTSA13, 0 BD01, 0 BD02, 0 BD03
                  from VRHF_EMP_TA13SAL
                  where BDCODEMP = :BDCODEMP and BDREFA13 = :wrefatu
                  union all
                  select BDCODEMP, BDCODCOL, BDFGTS13, 0 BD01, 0 BD02, 0 BD03
                  from VRHF_EMP_T13SAL
                  where BDCODEMP = :BDCODEMP and BDREF13 = :wrefatu
                  union all
                  select BDCODEMP, BDCODCOL, BDFGTSC13, 0 BD01, 0 BD02, 0 BD03
                  from VRHF_EMP_TC13SAL
                  where BDCODEMP = :BDCODEMP and BDREFC13 = :wrefatu
                  union all
                  select BDCODEMP, BDCODCOL, BDFGTSFA, BDFGTS13FA, 0 BD02, 0 BD03
                  from VRHF_EMP_TFOLHAAVULSA
                  where BDCODEMP = :BDCODEMP and BDREF = :wrefatu)
                  group by BDCODCOL
          into :wcodcol, :wfgts, :wliquido
          do
            begin
              wcat        = null;
              wcatesocial = null;
              select first 1 BDCATEGORIACOL, BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS where BDCODEMP = :BDCODEMP and BDCODCOL = :wcodcol and BDREFCOL <= :wrefatu order by BDREFCOL DESC into :wcat, :wcatesocial;
              wcat        = coalesce(wcat, 0);
              wcatesocial = coalesce(wcatesocial, 0);

              wgrupocla = null;
              select first 1 CLASSE.BDGRUPOCLA from VRH_EMP_TCOLCON_VINC COLVINC join VRH_BASE_TCLASSE CLASSE on (CLASSE.BDCODCLA = COLVINC.BDCODCLA) where COLVINC.BDCODEMP = :BDCODEMP and COLVINC.BDCODCOL = :wcodcol and COLVINC.BDREFCOL <= :wrefatu order by COLVINC.BDREFCOL DESC into :wgrupocla;
              wgrupocla = coalesce(wgrupocla, 0);

              wrefresc = null;
              select first 1 BDREFRESCISAO from VRH_EMP_TRESCISAO where BDCODEMP = :BDCODEMP and BDCODCOL = :wcodcol into :wrefresc;
              wrefresc = coalesce(wrefresc, 0);

              if (wrefresc > 0) then
                 begin
                   if (wrefresc <= wrefatu) then
                      BDLIQRESC = BDLIQRESC + coalesce(wliquido, 0);
                 end

              for select FN.BDREFFN, FN.BDCODVER, VERBAS.BDCLAVER, SUM(FN.BDVALVFN) BDVALVFN from (
                    select F.BDREFFN, F.BDCODVER, F.BDVALVFN
                    from VRHF_EMP_TVERBAFN F
                    join VRHF_EMP_TFOLHANORMAL F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDREFFN = F.BDREFFN)
                    where F.BDCODEMP = :BDCODEMP and F.BDCODCOL = :wcodcol and ((F.BDREFFN = :wrefatu) or (F2.BDDATAPGTOFN between :wpridia and :wultdia))
                    union all
                    select F.BDREFFN, F.BDCODVER, F.BDVALVFN
                    from VRHF_EMP_TVERBAINT F
                    join VRHF_EMP_TFOLHAINT F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDREFFN = F.BDREFFN and F2.BDCODCONTTI = F.BDCODCONTTI)
                    where F.BDCODEMP = :BDCODEMP and F.BDCODCOL = :wcodcol and ((F.BDREFFN = :wrefatu) or (F2.BDDATAPGTOFN between :wpridia and :wultdia))
                    union all
                    select F.BDREFTOMADOR, F.BDCODVER, F.BDVALVFT
                    from VRHF_EMP_TVERBATOMADOR F
                    join VRHF_EMP_TFOLHATOMADOR F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDREFTOMADOR = F.BDREFTOMADOR and F2.BDORDEM = F.BDORDEM)
                    where F.BDCODEMP = :BDCODEMP and F.BDCODCOL = :wcodcol and ((F.BDREFTOMADOR = :wrefatu) or (F2.BDDATAPGTOFT between :wpridia and :wultdia))
                    union all
                    select F.BDREFTOMADOR, F.BDCODVER, F.BDVALVFT
                    from VRHF_EMP_TVERBATOMINT F
                    join VRHF_EMP_TFOLHATOMINT F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDREFTOMADOR = F.BDREFTOMADOR and F2.BDORDEM = F.BDORDEM and F2.BDCODCONTTI = F.BDCODCONTTI)
                    where F.BDCODEMP = :BDCODEMP and F.BDCODCOL = :wcodcol and F.BDREFTOMADOR = :wrefatu
                    union all
                    select :wrefatu BDREF, F.BDCODVER, F.BDVALVFC
                    from VRHF_EMP_TVERBAFC F
                    join VRHF_EMP_TFOLHACOMP F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDREFFN = F.BDREFFN and F2.BDREFFC = F.BDREFFC)
                    where F.BDCODEMP = :BDCODEMP and F.BDCODCOL = :wcodcol and
                          ((F2.BDCODTIPOFC =  1 and F2.BDREFFN = :wrefatu) or
                           (F2.BDCODTIPOFC <> 1 and F2.BDDATAPAGFC between :wpridia and :wultdia))
                    union all
                    select :wrefatu BDREF, F.BDCODVER, F.BDVALVFC
                    from VRHF_EMP_TVERBAFCTOMADOR F
                    join VRHF_EMP_TFOLTOMCOMP F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDREFTOMADOR = F.BDREFTOMADOR and F2.BDREFFC = F.BDREFFC and F2.BDORDEM = F.BDORDEM)
                    where F.BDCODEMP = :BDCODEMP and F.BDCODCOL = :wcodcol and
                          ((F2.BDCODTIPOFC =  1 and F2.BDREFTOMADOR = :wrefatu) or
                           (F2.BDCODTIPOFC <> 1 and F2.BDDATAPAGFC between :wpridia and :wultdia))
                    union all
                    select BDREFA13, BDCODVER, BDVALVA13 from VRHF_EMP_TVERBAA13 where BDCODEMP = :BDCODEMP and BDCODCOL = :wcodcol and BDREFA13 = :wrefatu
                    union all
                    select F.BDREF13, F.BDCODVER, F.BDVALV13
                    from VRHF_EMP_TVERBA13 F
                    join VRHF_EMP_T13SAL F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDREF13 = F.BDREF13)
                    where F.BDCODEMP = :BDCODEMP and F.BDCODCOL = :wcodcol and ((F.BDREF13 = :wrefatu) or (F2.BDDATAPGTO13 between :wpridia and :wultdia))
                    union all
                    select F.BDREFC13, F.BDCODVER, F.BDVALVC13
                    from VRHF_EMP_TVERBAC13 F
                    join VRHF_EMP_TC13SAL F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDREF13 = F.BDREF13 and F2.BDREFC13 = F.BDREFC13)
                    where F.BDCODEMP = :BDCODEMP and F.BDCODCOL = :wcodcol and ((F.BDREFC13 = :wrefatu) or (F2.BDDATAPGTOC13 between :wpridia and :wultdia))
                    union all
                    select CAST((SUBSTRING(CAST(F.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(F.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER), F.BDCODVER, F.BDVALVFA
                    from VRHF_EMP_TVERBAFA F
                    where F.BDCODEMP = :BDCODEMP and F.BDCODCOL = :wcodcol and ((SUBSTRING(CAST(F.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(F.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2) = CAST(:wrefatu AS VARCHAR(6))) or (F.BDDATAFA between :wpridia and :wultdia))
                  ) FN
                  join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FN.BDCODVER)
                  group by FN.BDREFFN, FN.BDCODVER, VERBAS.BDCLAVER
              into :wreffn, :wcodver, :wclaver, :wvalvfn
              do
                begin
                  select first 1 BDTIPOCODVER, BDPISVER
                  from VRH_BASE_TVERBAS_REF
                  where BDCODVER = :wcodver and BDREFVER <= :wrefatu order by BDREFVER
                  into :wtipocodver, :wbasepis;

                  if (wreffn = wrefatu) then
                     begin
                       -- Proventos
                       if (coalesce(wtipocodver, 0) = 0) then
                          begin
                            -- Prolaborista
                            if (coalesce(wgrupocla, 0) = 2) then
                               begin
                                 if (SUBSTRING(wclaver FROM 1 FOR 5) <> '9.001') then
                                    BDTOTSALPRO = BDTOTSALPRO + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                                 else
                                    BDTOTARRED = BDTOTARRED + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                               end
                            else
                            -- Autônomo no cadastro de contribuintes
                            if (coalesce(wgrupocla, 0) = 3) then
                               begin
                                 if (SUBSTRING(wclaver FROM 1 FOR 5) <> '9.001') then
                                    BDTOTSALSERV = BDTOTSALSERV + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                                 else
                                    BDTOTARRED = BDTOTARRED + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);

                                 BDLIQSERV = BDLIQSERV + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                               end
                            else
                            -- Menor aprendiz
                            if (coalesce(wcat, 0 ) = 7 and coalesce(wcatesocial, 0) = 103) then
                               begin
                                 if (SUBSTRING(wclaver FROM 1 FOR 5) <> '9.001') then
                                    BDTOTSALMENOR = BDTOTSALMENOR + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                                 else
                                    BDTOTARRED = BDTOTARRED + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                               end
                            else
                            -- Colaborador
                               begin
                            if (SUBSTRING(wclaver FROM 1 FOR 5) = '4.001') then
                               BDTOTSALA13 = BDTOTSALA13 + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                            else
                            if (SUBSTRING(wclaver FROM 1 FOR 5) = '5.001') then
                               BDTOTSAL13 = BDTOTSAL13 + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                            else
                                 if (SUBSTRING(wclaver FROM 1 FOR 5) <> '9.001') then
                                    BDTOTSAL = BDTOTSAL + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                                 else
                                    BDTOTARRED = BDTOTARRED + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                               end

                            if ((UPPER(coalesce(wbasepis, 'FALSE')) = 'TRUE')) then
                               BDVALORPIS = BDVALORPIS + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);

                            -- Mensalidade sindical
                            if ((SUBSTRING(wclaver FROM 1 for 9) = '0.004.0.0') or (SUBSTRING(wclaver FROM 1 for 9) = '3.040.0.0') or (SUBSTRING(wclaver FROM 1 for 9) = '4.047.0.0') or
                                (SUBSTRING(wclaver FROM 1 for 9) = '5.070.0.0') or (SUBSTRING(wclaver FROM 1 for 9) = '6.070.0.0')) then
                               BDMENSSALSIND = BDMENSSALSIND + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                            else
                            -- Contribuição sindical
                            if ((SUBSTRING(wclaver FROM 1 for 9) = '0.004.0.1') or (SUBSTRING(wclaver FROM 1 for 9) = '3.040.0.1') or (SUBSTRING(wclaver FROM 1 for 9) = '4.047.0.1') or
                                (SUBSTRING(wclaver FROM 1 for 9) = '5.070.0.1') or (SUBSTRING(wclaver FROM 1 for 9) = '6.070.0.1')) then
                               BDCONTSIND = BDCONTSIND + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                            else
                            -- Contribuição confederativa
                            if ((SUBSTRING(wclaver FROM 1 for 9) = '0.004.0.2') or (SUBSTRING(wclaver FROM 1 for 9) = '3.040.0.2') or (SUBSTRING(wclaver FROM 1 for 9) = '4.047.0.2') or
                                (SUBSTRING(wclaver FROM 1 for 9) = '5.070.0.2') or (SUBSTRING(wclaver FROM 1 for 9) = '6.070.0.2')) then
                               BDCONTCONF = BDCONTCONF + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                            else
                            -- Taxa assistencial
                            if ((SUBSTRING(wclaver FROM 1 for 9) = '0.004.0.3') or (SUBSTRING(wclaver FROM 1 for 9) = '3.040.0.3') or (SUBSTRING(wclaver FROM 1 for 9) = '4.047.0.3') or
                                (SUBSTRING(wclaver FROM 1 for 9) = '5.070.0.3') or (SUBSTRING(wclaver FROM 1 for 9) = '6.070.0.3')) then
                               BDTAXAASSIST = BDTAXAASSIST + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                            else
                            -- Reversão salarial
                            if ((SUBSTRING(wclaver FROM 1 for 9) = '0.004.0.4') or (SUBSTRING(wclaver FROM 1 for 9) = '3.040.0.4') or (SUBSTRING(wclaver FROM 1 for 9) = '4.047.0.4') or
                                (SUBSTRING(wclaver FROM 1 for 9) = '5.070.0.4') or (SUBSTRING(wclaver FROM 1 for 9) = '6.070.0.4')) then
                               BDREVERSAL = BDREVERSAL + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                            else
                            -- Subvenção patronal
                            if ((SUBSTRING(wclaver FROM 1 for 9) = '0.004.0.5') or (SUBSTRING(wclaver FROM 1 for 9) = '3.040.0.5') or (SUBSTRING(wclaver FROM 1 for 9) = '4.047.0.5') or
                                (SUBSTRING(wclaver FROM 1 for 9) = '5.070.0.5') or (SUBSTRING(wclaver FROM 1 for 9) = '6.070.0.5')) then
                               BDSUBPAT = BDSUBPAT + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                            else
                            -- Subsídio cônjuge
                            if ((SUBSTRING(wclaver FROM 1 for 9) = '0.004.0.6') or (SUBSTRING(wclaver FROM 1 for 9) = '3.040.0.6') or (SUBSTRING(wclaver FROM 1 for 9) = '4.047.0.6') or
                                (SUBSTRING(wclaver FROM 1 for 9) = '5.070.0.6') or (SUBSTRING(wclaver FROM 1 for 9) = '6.070.0.6')) then
                               BDSUBCONJ = BDSUBCONJ + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                          end
                       else
                       -- Descontos
                       if (coalesce(wtipocodver, 0) = 1) then
                          begin
                            -- Prolaborista
                            if (coalesce(wgrupocla, 0) = 2) then
                               BDTOTDESCPRO = BDTOTDESCPRO + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                            else
                            -- Autônomo no cadastro de contribuintes
                            if (coalesce(wgrupocla, 0) = 3) then
                               begin
                                 BDTOTDESCSERV = BDTOTDESCSERV + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                                 BDLIQSERV = BDLIQSERV - coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                               end
                            else
                            -- Menor aprendiz
                            if (coalesce(wcat, 0 ) = 7 and coalesce(wcatesocial, 0) = 103) then
                               BDTOTDESCMENOR = BDTOTDESCMENOR + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                            else
                            -- Colaborador
                               BDTOTDESC = BDTOTDESC + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);

                            if ((UPPER(coalesce(wbasepis, 'FALSE')) = 'TRUE')) then
                               BDVALORPIS = BDVALORPIS - coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);

                            -- Mensalidade sindical
                            if ((SUBSTRING(wclaver FROM 1 for 9) = '0.004.0.0') or (SUBSTRING(wclaver FROM 1 for 9) = '3.040.0.0') or (SUBSTRING(wclaver FROM 1 for 9) = '4.047.0.0') or
                                (SUBSTRING(wclaver FROM 1 for 9) = '5.070.0.0') or (SUBSTRING(wclaver FROM 1 for 9) = '6.070.0.0')) then
                               BDMENSSALSIND = BDMENSSALSIND + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                            else
                            -- Contribuição sindical
                            if ((SUBSTRING(wclaver FROM 1 for 9) = '0.004.0.1') or (SUBSTRING(wclaver FROM 1 for 9) = '3.040.0.1') or (SUBSTRING(wclaver FROM 1 for 9) = '4.047.0.1') or
                                (SUBSTRING(wclaver FROM 1 for 9) = '5.070.0.1') or (SUBSTRING(wclaver FROM 1 for 9) = '6.070.0.1')) then
                               BDCONTSIND = BDCONTSIND + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                            else
                            -- Contribuição confederativa
                            if ((SUBSTRING(wclaver FROM 1 for 9) = '0.004.0.2') or (SUBSTRING(wclaver FROM 1 for 9) = '3.040.0.2') or (SUBSTRING(wclaver FROM 1 for 9) = '4.047.0.2') or
                                (SUBSTRING(wclaver FROM 1 for 9) = '5.070.0.2') or (SUBSTRING(wclaver FROM 1 for 9) = '6.070.0.2')) then
                               BDCONTCONF = BDCONTCONF + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                            else
                            -- Taxa assistencial
                            if ((SUBSTRING(wclaver FROM 1 for 9) = '0.004.0.3') or (SUBSTRING(wclaver FROM 1 for 9) = '3.040.0.3') or (SUBSTRING(wclaver FROM 1 for 9) = '4.047.0.3') or
                                (SUBSTRING(wclaver FROM 1 for 9) = '5.070.0.3') or (SUBSTRING(wclaver FROM 1 for 9) = '6.070.0.3')) then
                               BDTAXAASSIST = BDTAXAASSIST + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                            else
                            -- Reversão salarial
                            if ((SUBSTRING(wclaver FROM 1 for 9) = '0.004.0.4') or (SUBSTRING(wclaver FROM 1 for 9) = '3.040.0.4') or (SUBSTRING(wclaver FROM 1 for 9) = '4.047.0.4') or
                                (SUBSTRING(wclaver FROM 1 for 9) = '5.070.0.4') or (SUBSTRING(wclaver FROM 1 for 9) = '6.070.0.4')) then
                               BDREVERSAL = BDREVERSAL + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                            else
                            -- Subvenção patronal
                            if ((SUBSTRING(wclaver FROM 1 for 9) = '0.004.0.5') or (SUBSTRING(wclaver FROM 1 for 9) = '3.040.0.5') or (SUBSTRING(wclaver FROM 1 for 9) = '4.047.0.5') or
                                (SUBSTRING(wclaver FROM 1 for 9) = '5.070.0.5') or (SUBSTRING(wclaver FROM 1 for 9) = '6.070.0.5')) then
                               BDSUBPAT = BDSUBPAT + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                            else
                            -- Subsídio cônjuge
                            if ((SUBSTRING(wclaver FROM 1 for 9) = '0.004.0.6') or (SUBSTRING(wclaver FROM 1 for 9) = '3.040.0.6') or (SUBSTRING(wclaver FROM 1 for 9) = '4.047.0.6') or
                                (SUBSTRING(wclaver FROM 1 for 9) = '5.070.0.6') or (SUBSTRING(wclaver FROM 1 for 9) = '6.070.0.6')) then
                               BDSUBCONJ = BDSUBCONJ + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                          end
                     end
                end

              wfgts = coalesce(wfgts, 0);

              -- Menor aprendiz
              if (coalesce(wcat, 0 ) = 7 and coalesce(wcatesocial, 0) = 103) then
                 BDFGTSMENOR = BDFGTSMENOR + wfgts;
              else
              -- Colaborador
                 BDFGTS = BDFGTS + wfgts;

              wfgts    = null;
              w40      = null;
              w10      = null;

              execute statement 'select CAST((coalesce(BDFGTSMES, 0) + coalesce(BDFGTSIND, 0)) AS NUMERIC(18,2)), CAST(BDFGTS40 AS NUMERIC(18,2)), CAST(BDFGTS10 AS NUMERIC(18,2)) '||
                                'from VRHF_EMP_VAL_GRRF('||BDCODEMP||', '||wcodcol||', '||wrefatu||', '||wrefatu||', 0)'
              into :wfgts, :w40, :w10;

              wfgts = coalesce(wfgts, 0);
              w40   = coalesce(w40, 0);
              w10   = coalesce(w10, 0);

              -- Menor aprendiz
              if (coalesce(wcat, 0 ) = 7 and coalesce(wcatesocial, 0) = 103) then
                 begin
                   BDFGTSMENOR = BDFGTSMENOR - wfgts;
                   BDGRRF20    = BDGRRF20 + wfgts;
                 end
              else
              -- Colaborador
                 begin
                   BDFGTS = BDFGTS - wfgts;
                   BDGRRF   = BDGRRF + wfgts;
                 end

              BDGRRF40 = BDGRRF40 + w40;

              if (prreffim < 202001) then --Sol. 129769 | Michel Luciano | Data 17/12/2019
                BDGRRF10 = BDGRRF10 + w10;

              -- Folhas complementares
              for select BDREFFN, BDREFFC
                  from (select BDREFFN, BDREFCOMP BDREFFC from VRHF_EMP_TFOLHACOMP
                        where BDCODEMP = :BDCODEMP and BDCODCOL = :wcodcol and
                              ((BDCODTIPOFC = 1  and BDREFFN = :wrefatu) or
                               (BDCODTIPOFC <> 1 and BDDATAPAGFC between :wpridia and :wultdia))
                        union all
                        select BDREFTOMADOR, BDREFCOMP from VRHF_EMP_TFOLTOMCOMP
                        where BDCODEMP = :BDCODEMP and BDCODCOL = :wcodcol and
                              ((BDCODTIPOFC = 1 and BDREFTOMADOR = :wrefatu) or
                               (BDCODTIPOFC <> 1 and BDDATAPAGFC between :wpridia and :wultdia))
                       )
              into :wreffn, :wreffc
              do
                begin
                  wfgts    = null;
                  w40      = null;
                  w10      = null;
    
                  execute statement 'select CAST((coalesce(BDFGTSMES, 0) + coalesce(BDFGTSIND, 0)) AS NUMERIC(18,2)), CAST(BDFGTS40 AS NUMERIC(18,2)), CAST(BDFGTS10 AS NUMERIC(18,2)) '||
                                    'from VRHF_EMP_VAL_GRRF('||BDCODEMP||', '||wcodcol||', '||wreffn||', '||wreffc||', 1) '
                  into :wfgts, :w40, :w10;
    
                  wfgts = coalesce(wfgts, 0);
                  w40   = coalesce(w40, 0);
                  w10   = coalesce(w10, 0);
    
                  -- Menor aprendiz
                  if (coalesce(wcat, 0 ) = 7 and coalesce(wcatesocial, 0) = 103) then
                     begin
                       BDFGTSMENOR = BDFGTSMENOR - wfgts;
                       BDGRRF20    = BDGRRF20 + wfgts;
                     end
                  else
                  -- Colaborador
                     begin
                       BDFGTS = BDFGTS - wfgts;
                       BDGRRF   = BDGRRF + wfgts;
                     end
    
                  BDGRRF40 = BDGRRF40 + w40;

                  if (prrefini < 202001) then --Sol. 129769 | Michel Luciano | Data 17/12/2019
                    BDGRRF10 = BDGRRF10 + w10;
                end
            end

          -- Sol. 134137 | Jarde | 01/04/2020 | Inicio
          for select FN.BDREFFN, FN.BDCODVER, VERBAS.BDCLAVER, SUM(FN.BDVALVFN) BDVALVFN from (
                select F.BDREFFN, F.BDCODVER, F.BDVALVFN
                from VRHF_EMP_TVERBAFN F
                join VRHF_EMP_TFOLHANORMAL F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDREFFN = F.BDREFFN)
                where F.BDCODEMP = :BDCODEMP and ((F2.BDDATAPGTOFN between :wpridia and :wultdia))
                union all
                select F.BDREFFN, F.BDCODVER, F.BDVALVFN
                from VRHF_EMP_TVERBAINT F
                join VRHF_EMP_TFOLHAINT F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDREFFN = F.BDREFFN and F2.BDCODCONTTI = F.BDCODCONTTI)
                where F.BDCODEMP = :BDCODEMP and ((F2.BDDATAPGTOFN between :wpridia and :wultdia))
                union all
                select F.BDREFTOMADOR, F.BDCODVER, F.BDVALVFT
                from VRHF_EMP_TVERBATOMADOR F
                join VRHF_EMP_TFOLHATOMADOR F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDREFTOMADOR = F.BDREFTOMADOR and F2.BDORDEM = F.BDORDEM)
                where F.BDCODEMP = :BDCODEMP and ((F2.BDDATAPGTOFT between :wpridia and :wultdia))
                union all
                select F.BDREFTOMADOR, F.BDCODVER, F.BDVALVFT
                from VRHF_EMP_TVERBATOMINT F
                join VRHF_EMP_TFOLHATOMINT F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDREFTOMADOR = F.BDREFTOMADOR and F2.BDORDEM = F.BDORDEM and F2.BDCODCONTTI = F.BDCODCONTTI)
                where F.BDCODEMP = :BDCODEMP and ((F2.BDDATAPGTOFT between :wpridia and :wultdia))
                union all
                select CAST(SUBSTRING(F.BDREFFC FROM 1 FOR 6) AS INTEGER), F.BDCODVER, F.BDVALVFC
                from VRHF_EMP_TVERBAFC F
                join VRHF_EMP_TFOLHACOMP F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDREFFN = F.BDREFFN and F2.BDREFFC = F.BDREFFC)
                where F.BDCODEMP = :BDCODEMP and
                      ((F2.BDCODTIPOFC =  1 and F2.BDREFFN = :wrefatu) or
                       (F2.BDCODTIPOFC <> 1 and F2.BDDATAPAGFC between :wpridia and :wultdia))
                union all
                select CAST(SUBSTRING(F.BDREFFC FROM 1 FOR 6) AS INTEGER), F.BDCODVER, F.BDVALVFC
                from VRHF_EMP_TVERBAFCTOMADOR F
                join VRHF_EMP_TFOLTOMCOMP F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDREFTOMADOR = F.BDREFTOMADOR and F2.BDREFFC = F.BDREFFC and F2.BDORDEM = F.BDORDEM)
                where F.BDCODEMP = :BDCODEMP and
                      ((F2.BDCODTIPOFC = 1 and F2.BDREFTOMADOR = :wrefatu) or
                       (F2.BDCODTIPOFC <> 1 and F2.BDDATAPAGFC between :wpridia and :wultdia))
                union all
                select F.BDREFA13, F.BDCODVER, F.BDVALVA13
                from VRHF_EMP_TVERBAA13 F
                join VRHF_EMP_TA13SAL F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDREFA13 = F.BDREFA13)
                where F.BDCODEMP = :BDCODEMP and ((F2.BDDATAPGTOA13 between :wpridia and :wultdia))
                union all
                select F.BDREF13, F.BDCODVER, F.BDVALV13
                from VRHF_EMP_TVERBA13 F
                join VRHF_EMP_T13SAL F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDREF13 = F.BDREF13)
                where F.BDCODEMP = :BDCODEMP and ((F2.BDDATAPGTO13 between :wpridia and :wultdia))
                union all
                select F.BDREFC13, F.BDCODVER, F.BDVALVC13
                from VRHF_EMP_TVERBAC13 F
                join VRHF_EMP_TC13SAL F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDREF13 = F.BDREF13 and F2.BDREFC13 = F.BDREFC13)
                where F.BDCODEMP = :BDCODEMP and ((F2.BDDATAPGTOC13 between :wpridia and :wultdia))
                union all
                select CAST((SUBSTRING(CAST(F.BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(F.BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER), F.BDCODVER, F.BDVALVFA
                from VRHF_EMP_TVERBAFA F
                where F.BDCODEMP = :BDCODEMP and ((F.BDDATAFA between :wpridia and :wultdia))
                union all
                select CAST((SUBSTRING(CAST(F2.BDDATAPAGFE AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(F2.BDDATAPAGFE AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER), F.BDCODVER, F.BDVALVFE
                from VRHF_EMP_TVERBAFE F
                join VRH_EMP_TFERIAS F2 on (F2.BDCODEMP = F.BDCODEMP and F2.BDCODCOL = F.BDCODCOL and F2.BDINIPERAQUISFE = F.BDINIPERAQUISFE and F2.BDCODFE = F.BDCODFE)
                where F.BDCODEMP = :BDCODEMP and ((F2.BDDATAPAGFE between :wpridia and :wultdia))
                union all
                select CAST((SUBSTRING(CAST(F.BDDATAAD AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(F.BDDATAAD AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER), F.BDCODVER, F.BDVALVAD
                from VRHF_EMP_TVERBAAD F
                where F.BDCODEMP = :BDCODEMP and ((F.BDDATAAD between :wpridia and :wultdia))
              ) FN
              join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FN.BDCODVER)
              group by FN.BDREFFN, FN.BDCODVER, VERBAS.BDCLAVER
           into :wreffn, :wcodver, :wclaver, :wvalvfn
           do
             begin
               if (SUBSTRING(wclaver FROM 1 FOR 7) = '9.010.1') then
                  begin
                    if ((SUBSTRING(wclaver FROM 1 FOR 9) <> '9.010.1.2') and (SUBSTRING(wclaver FROM 1 FOR 9) <> '9.010.1.8')) then
                       begin
                          -- Prolaborista
                          if (coalesce(wgrupocla, 0) = 2) then
                             BDIRRFPRO = BDIRRFPRO + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                          else
                          -- Autônomo no cadastro de contribuintes
                          if (coalesce(wgrupocla, 0) = 3) then
                             BDIRRFSERV = BDIRRFSERV + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                          else
                             BDIRRFCOL = BDIRRFCOL + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                       end
                  end
             end
          -- Sol 134137 | Jarde | 01/04/2020 | Fim

          for select FN.BDREFINSSSERV, FN.BDCODVER, VER.BDCLAVER, FN.BDVALVFN from (
                  select SERVFN.BDREFINSSSERV, VSERV.BDCODVER, SUM(coalesce(VSERV.BDVALOR, 0)) BDVALVFN
                  from VRHF_BASE_ITEMS_CALCTERC VSERV
                  join VRHF_BASE_CALC_TERC SERVFN on (SERVFN.BDCODEMP = VSERV.BDCODEMP and SERVFN.BDCODTER = VSERV.BDCODTER and SERVFN.BDCODSERV = VSERV.BDCODSERV)
                  where ((SERVFN.BDREFINSSSERV = :wrefatu) or (SERVFN.BDDATAPAGSERV between :wpridia and :wultdia)) and VSERV.BDCODEMP = :BDCODEMP
                  group by SERVFN.BDREFINSSSERV, VSERV.BDCODVER
              ) FN
              join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER)
          into :wreffn, :wcodver, :wclaver, :wvalvfn
          do
            begin
              select first 1 BDTIPOCODVER, BDPISVER
              from VRH_BASE_TVERBAS_REF
              where BDCODVER = :wcodver and BDREFVER <= :wrefatu order by BDREFVER
              into :wtipocodver, :wbasepis;

              if (wreffn = :wrefatu) then
                 begin
                   -- Proventos
                   if (coalesce(wtipocodver, 0) = 0) then
                      begin
                        if (SUBSTRING(wclaver FROM 1 FOR 5) <> '9.001') then
                           BDTOTSALSERV = BDTOTSALSERV + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                        else
                           BDTOTARRED = BDTOTARRED + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
     
                        BDLIQSERV = BDLIQSERV + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);

                        if (UPPER(coalesce(wbasepis, 'FALSE')) = 'TRUE') then
                           BDVALORPIS = BDVALORPIS + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                      end
                   else
                   -- Descontos
                   if (coalesce(wtipocodver, 0) = 1) then
                      begin
                        BDTOTDESCSERV = BDTOTDESCSERV + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                        BDLIQSERV = BDLIQSERV - coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);

                        if (UPPER(coalesce(wbasepis, 'FALSE')) = 'TRUE') then
                           BDVALORPIS = BDVALORPIS - coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                      end

                   if (SUBSTRING(wclaver FROM 1 FOR 9) = '9.010.1.0') then
                      BDIRRFSERV = BDIRRFSERV + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
                 end
--              else
--              -- Essa é a parte do IR
--              if (SUBSTRING(wclaver FROM 1 FOR 7) = '9.010.1') then
--                 BDIRRFSERV = BDIRRFSERV + coalesce(CAST(wvalvfn AS NUMERIC(18,2)), 0);
            end

          -- Líquido das férias
          select SUM(CAST(BDLIQUIDO AS NUMERIC(18,2))) from VRH_EMP_TFERIAS where BDCODEMP = :BDCODEMP and BDDATAPAGFE between :wpridia and :wultdia into :BDLIQFERIAS;
          BDLIQFERIAS = coalesce(BDLIQFERIAS, 0);

          BDLIQUIDO = BDTOTSAL + BDTOTSALA13 + BDTOTSAL13 + BDTOTSALMENOR + BDTOTSALPRO + BDTOTSALSERV + BDTOTARRED - BDTOTDESC - BDTOTDESCMENOR - BDTOTDESCPRO - BDTOTDESCSERV - BDLIQRESC - BDLIQSERV;

          for select COL.BDDATAADMCOL, RESC.BDDATARESCISAO, COALESCE(COLPARTIDA.BDDATATRFCOL, TRANS.BDDATATRF)
              from VRH_EMP_TCOLCON COL
              left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL)
              left outer join VRH_EMP_TTRANSCOL TRANS on (TRANS.BDCODEMPDEST = COL.BDCODEMP and TRANS.BDCODCOLDEST = COL.BDCODCOL)
              left outer join VRH_EMP_TCOLCON_PARTIDA COLPARTIDA on (COLPARTIDA.BDCODEMP = COL.BDCODEMP and COLPARTIDA.BDCODCOL = COL.BDCODCOL)
              where COL.BDCODEMP = :BDCODEMP and COL.BDDATAADMCOL <= :wultdia and coalesce(COL.BDCONTRCOL, 0) = 0
                    and ((RESC.BDDATARESCISAO is null) or (RESC.BDREFRESCISAO >= :wcompant))
          into :wdataadm, :wdataresc, :wdatatrf
          do
            begin
              -- Admitido na competência
              if (coalesce(wdatatrf, wdataadm) >= wpridia and coalesce(wdatatrf, wdataadm) <= wultdia) then
                 BDADMISSOES = BDADMISSOES + 1;
              -- Rescisões na competência
              if (wdataresc is not null and wdataresc >= wpridia and wdataresc <= wultdia) then
                 BDRESCISOES = BDRESCISOES + 1;

              -- Ativos na competência anterior
              if ((coalesce(wdatatrf, wdataadm) < wpridia) and ((wdataresc is null) or (wdataresc >= wultdiaant))) then
                 BDATIVOSMESANT = BDATIVOSMESANT + 1;
            end

          select Count(*) BDTOTAL_AFAST
          from TEMPRESAS EMP
          join VRH_EMP_TSITCOL SIT on (SIT.BDCODEMP = EMP.BDCODEMP)
          where (SIT.BDDATAINISIT <= :wultdia) and ((SIT.BDDATAFIMSIT is null) or (SIT.BDDATAFIMSIT + 1 >= :wpridia))
                and (EMP.BDCODEMP = :BDCODEMP) into :BDTOTAFASTAMENTOS;

          /* FUNRURAL Compra */
          select CAST(SUM(coalesce(BDVALOR, 0) + coalesce(BDVALTERC, 0) + coalesce(BDVALORACU, 0) + coalesce(BDVALACUTERC, 0) + coalesce(BDVALRAT, 0)) AS NUMERIC(18,2))
          from vrhf_sp_gps_funrural_resumo('bdcodemp = '||:BDCODEMP,:wrefatu,null,1,null)
          into :BDVALFUNRURAL;
          BDVALFUNRURAL = coalesce(BDVALFUNRURAL, 0);

          /* FUNRURAL Venda */
          select CAST(SUM(coalesce(BDVALOR, 0) + coalesce(BDVALTERC, 0) + coalesce(BDVALORACU, 0) + coalesce(BDVALACUTERC, 0) + coalesce(BDVALRAT, 0)) AS NUMERIC(18,2))
          from vrhf_sp_gps_funrural_resumo('bdcodemp = '||:BDCODEMP,:wrefatu,null,2,null)
          into :BDVALAGROIND;
          BDVALAGROIND = coalesce(BDVALAGROIND, 0);

          if (BDVALORPIS <> 0) then
             begin
               BDPERCPIS = null;
               select first 1 COALESCE(BDALIQIMPOSTO, 0.0) from SP_IMPOSTO_EMPRESA(:BDCODEMP, 2, 1, :wrefatu, 1) where coalesce(BDTIPORETENCAO, 0) = 1 into :BDPERCPIS;
               BDPERCPIS = coalesce(BDPERCPIS, 0);
               BDVALORPIS = CAST((BDVALORPIS * BDPERCPIS / 100) AS NUMERIC(18,2));
             end

          suspend;

          if (SUBSTRING(wrefatu from 5 for 2) = '12') then
             wrefatu = CAST((CAST((CAST(SUBSTRING(wrefatu from 1 for 4) as integer) + 1) AS VARCHAR(4))||'01') AS INTEGER);
          else
             wrefatu = CAST((SUBSTRING(wrefatu from 1 for 4)||LPAD(CAST((CAST(SUBSTRING(wrefatu from 5 for 2) as integer) + 1) AS VARCHAR(2)), 2, '0')) AS INTEGER);

          BDDATABASEEMP     = 0;
          BDTRIBUTACAO      = '';
          BDTOTSAL          = 0;
          BDTOTSALMENOR     = 0;
          BDTOTSALPRO       = 0;
          BDTOTSALSERV      = 0;
          BDTOTARRED        = 0;
          BDTOTDESC         = 0;
          BDTOTDESCMENOR    = 0;
          BDTOTDESCPRO      = 0;
          BDTOTDESCSERV     = 0;
          BDLIQFERIAS       = 0;
          BDLIQRESC         = 0;
          BDLIQSERV         = 0;
          BDLIQUIDO         = 0;
          BDFGTS            = 0;
          BDFGTSMENOR       = 0;
          BDGRRF            = 0;
          BDGRRF40          = 0;
          BDGRRF20          = 0;
          BDGRRF10          = 0;
          BDCONTSIND        = 0;
          BDCONTCONF        = 0;
          BDMENSSALSIND     = 0;
          BDTAXAASSIST      = 0;
          BDREVERSAL        = 0;
          BDSUBPAT          = 0;
          BDSUBCONJ         = 0;
          BDATIVOSMESANT    = 0;
          BDADMISSOES       = 0;
          BDRESCISOES       = 0;
          BDDATAMESANT      = null;
          BDULTDIAMES       = null;
          BDTOTAFASTAMENTOS = 0;
          BDVALFUNRURAL     = 0;
          BDVALAGROIND      = 0;
          BDIRRFCOL         = 0;
          BDIRRFPRO         = 0;
          BDIRRFSERV        = 0;
          BDPERCPIS         = 0;
          BDVALORPIS        = 0;
          BDTOTSALA13       = 0;
          BDTOTSAL13        = 0;
        end
    end

  rdb$set_context('USER_SESSION', 'W_ANOMES', :wanomesc);
  rdb$set_context('USER_SESSION', 'W_PRIDIAMES', :wpridiac);
  rdb$set_context('USER_SESSION', 'W_ULTDIAMES', :wultdiac);
end^

create or alter procedure SP_VTPO_ADD_ACESSO_TELA (
    PRCODEMP integer,
    PRUSUARIO integer,
    PRDATA date,
    PRSISTEMA integer,
    PRNOMETELA varchar(150),
    PRCAPTION varchar(1000),
    PRQTDACESSO integer = 0,
    PRQTDPROC integer = 0,
    PRADDSEGPROC integer = 0)
as
declare variable WCODEMP integer;
declare variable WCODIGO_TELA integer;
declare variable WCODSIS integer;
begin
  select first 1 coalesce(bdcodemp, 0) from tempresas where bdcodemp = :prcodemp into :wcodemp;
  if ((:PRNOMETELA <> '') and (:wcodemp > 0)) then
  begin
    select first 1 BDCODTELASIS from sp_getcodigo_tela(substring(:prnometela from 1 for 100), substring(:prcaption from 1 for 150)) into :wcodigo_tela;
    -- gilberto - 07/10/2025 - #232639 - Garantindo que gere o registro mesmo que alguma Fk esteja errada
    select bdcodemp from tempresas where bdcodemp = :prcodemp into :wcodemp;
    --select bdcodsis from tsistema where bdcodsis = :prsistema into wcodsis;
    select first 1 BDCODSIS from (select bdcodsis from tsistema where bdcodsis = :prsistema
                                  union all
                                  select first 1 BDCODSIS from tsistema)
    where bdcodsis is not null into wcodsis;    

-- Gilberto - 11/01/2022 - não faz sentido a forma que faz a contagem no sistema, isso deve ser revisado no futuro,
-- exemplo: um cadastro pode registrar inúmeras ocorrências, devido aos DAOs agregados, mas não faz o menos sentido tem 16 acessos se o cliente apenas alterou o número do endereço e salvou.
        update or insert into VTPO_ATIVIDADE_EXE_QTD (BDCODUSU, BDCODEMP, BDDATA, BDCODSIS, BDCODTELASIS, BDQTDACESSO,BDQTDPROC,BDTEMPOPROC)
        values (:PRUSUARIO, :wcodemp, :PRDATA, :wcodsis, :WCODIGO_TELA, ((select first 1 BDQTDACESSO from (
                                                                                    select coalesce(BDQTDACESSO,0)+:prqtdacesso BDQTDACESSO
                                                                                    from VTPO_ATIVIDADE_EXE_QTD
                                                                                    where BDCODUSU = :PRUSUARIO and
                                                                                          coalesce(:PRCODEMP,0) = coalesce(BDCODEMP,0) and
                                                                                          BDDATA = :PRDATA and
                                                                                          BDCODSIS = :PRSISTEMA and
                                                                                          BDCODTELASIS = :WCODIGO_TELA
                                                                                    UNION ALL
                                                                                    select (case when :prqtdproc = 1 then 0 else 1 end) BDQTDACESSO
                                                                                    from RDB$DATABASE))),
                                                                           (coalesce((select BDQTDPROC
                                                                                    from VTPO_ATIVIDADE_EXE_QTD
                                                                                    where BDCODUSU = :PRUSUARIO and
                                                                                          coalesce(:PRCODEMP,0) = coalesce(BDCODEMP,0) and
                                                                                          BDDATA = :PRDATA and
                                                                                          BDCODSIS = :PRSISTEMA and
                                                                                          BDCODTELASIS = :WCODIGO_TELA),0)+:prqtdproc),
                                                                           (coalesce((select BDTEMPOPROC
                                                                                    from VTPO_ATIVIDADE_EXE_QTD
                                                                                    where BDCODUSU = :PRUSUARIO and
                                                                                          coalesce(:PRCODEMP,0) = coalesce(BDCODEMP,0) and
                                                                                          BDDATA = :PRDATA and
                                                                                          BDCODSIS = :PRSISTEMA and
                                                                                          BDCODTELASIS = :WCODIGO_TELA),0)+:PRADDSEGPROC))
        matching (BDCODUSU, BDCODEMP, BDDATA, BDCODSIS, BDCODTELASIS);
  end
end^

create or alter procedure VTIPO_IMPORTA_PLANILHA (
    PIMPORTARTIMEOUT boolean)
returns (
    CALCULATEDRELEASETIMEOUT integer,
    OLDBDCHAVE integer,
    NEWBDCHAVE integer)
as
declare variable VBDCHAVE integer;
declare variable VBDCODUSU integer;
declare variable VBDCODEMP integer;
declare variable VBDCODATI integer;
declare variable VBDDATAINI date;
declare variable VBDHORAINI time;
declare variable VBDDATAFIN date;
declare variable VBDHORAFIN time;
declare variable VBDOBSERVACAO varchar(1000);
declare variable VBDCODSIS integer;
declare variable VBDTIPOREGISTRO integer;
declare variable VBDTEMPO integer;
declare variable VCALCULATEDRELEASETIMEOUT integer;
declare variable VBDTIMEOUT smallint;
BEGIN
  FOR
    SELECT
      r.BDCHAVE,
      r.BDCODUSU,
      r.BDCODEMP,
      r.BDCODATI,
      r.BDDATAINI,
      r.BDHORAINI,
      r.BDDATAFIN,
      r.BDHORAFIN,
      13 AS BDCODSIS,
      2 AS BDTIPOREGISTRO,
      r.BDOBSERVACAO,
      DATEDIFF(SECOND FROM CAST(r.BDDATAINI || ' ' || r.BDHORAINI AS TIMESTAMP)
                      TO CAST(r.BDDATAFIN || ' ' || r.BDHORAFIN AS TIMESTAMP)) AS BDTEMPO,
      (SELECT FIRST 1
           CAST(EXTRACT(HOUR FROM t.BDRELEASESTIMEOUT) AS INTEGER)*3600 +
           CAST(EXTRACT(MINUTE FROM t.BDRELEASESTIMEOUT) AS INTEGER)*60 +
           CAST(EXTRACT(SECOND FROM t.BDRELEASESTIMEOUT) AS INTEGER)
       FROM VTPO_TCONF t
       WHERE t.BDREFCONF <= CAST(EXTRACT(YEAR FROM r.BDDATAINI)
                         || LPAD(CAST(EXTRACT(MONTH FROM r.BDDATAINI) AS VARCHAR(2)), 2, '0') AS INTEGER)
       ORDER BY t.BDREFCONF DESC
      ) AS CalculatedReleaseTimeout
    FROM TMP_IMP_VTPO_ATIVIDADE_EXE r
      INNER JOIN VTPO_ATIVIDADE_EXE atv ON atv.BDCODATI = r.BDCODATI
      JOIN TUSUARIO USU ON(USU.BDCODUSU = R.BDCODUSU)
      LEFT JOIN TEMPRESAS emp ON emp.BDCODEMP = r.BDCODEMP
    WHERE
          ((emp.BDCODEMP = r.BDCODEMP) OR ((emp.BDCODEMP IS NULL) AND (r.BDCODEMP IS NULL)))
      AND USU.BDCODUSU IS NOT NULL 
      AND r.BDDATAINI IS NOT NULL
      AND r.BDHORAINI IS NOT NULL
      AND r.BDDATAFIN IS NOT NULL
      AND r.BDHORAFIN IS NOT NULL
      AND r.BDCODATI <> 2
    INTO :vBDCHAVE, :vBDCODUSU, :vBDCODEMP, :vBDCODATI, :vBDDATAINI, :vBDHORAINI, :vBDDATAFIN, :vBDHORAFIN,
         :vBDCODSIS, :vBDTIPOREGISTRO, :vBDOBSERVACAO, :vBDTEMPO, :vCalculatedReleaseTimeout
  DO
  BEGIN
    IF (vCalculatedReleaseTimeout IS NOT NULL) THEN
    BEGIN
      IF (vBDTEMPO > vCalculatedReleaseTimeout) THEN
        vBDTIMEOUT = 1;
      ELSE
        vBDTIMEOUT = 0;
    END
    ELSE
      vBDTIMEOUT = 0;

    IF ((vBDTIMEOUT = 1) AND (pImportarTimeout = FALSE)) THEN
      CONTINUE;
      
    INSERT INTO VTPO_ATIVIDADE_EXE_REGISTRO (
      BDCODUSU, BDCODEMP, BDCODATI, BDDATAINI, BDHORAINI,
      BDDATAFIN, BDHORAFIN, BDCODSIS, BDTIPOREGISTRO, BDOBSERVACAO
    )
    VALUES (
      :vBDCODUSU, :vBDCODEMP, :vBDCODATI, :vBDDATAINI, :vBDHORAINI,
      :vBDDATAFIN, :vBDHORAFIN, :vBDCODSIS, :vBDTIPOREGISTRO, :vBDOBSERVACAO
    )

    RETURNING BDCHAVE INTO :newBDCHAVE;
    oldbdchave = :vbdchave;
    calculatedreleasetimeout = :vCalculatedReleaseTimeout;

    SUSPEND;
  END
End^

create or alter procedure SP_INSERIR_TEMPO (
    PRTABELA_TEMP varchar(5),
    PRCODEMP integer = null,
    PRCODUSU integer = null,
    PRCODATI integer = null,
    PRDATAHORAINI timestamp = null,
    PRDATAHORAFIN timestamp = null,
    PRCODSIS integer = null,
    PRNOMETELA varchar(100) = null /* COLLATE WIN1252 - default */ ,
    PRCAPTION varchar(150) = null /* COLLATE WIN1252 - default */ ,
    PRTIPOREGISTRO integer = null,
    PRHOST integer = null,
    PRSESSAO integer = null,
    PROBSERVACAO varchar(300) = null /* COLLATE WIN1252 - default */ )
as
declare variable WCODUSU integer;
declare variable WCODEMP integer;
declare variable WCODATI integer;
declare variable WCODSIS integer;
declare variable WTIPOREGISTRO integer;
declare variable WOBSERVACAO varchar(300);
declare variable WCODIGO_TELA integer;
declare variable WCHAVE bigint;
declare variable WTEMPOOCIOSO varchar(5);
declare variable WCOUNT integer;
declare variable WHORAINI_REG time;
declare variable WHORAFIN_REG time;
declare variable WTEMPO integer;
declare variable WACTUAL_HOST integer;
declare variable WACTUAL_CONNECT integer;
declare variable WCOUNT_CONF integer;
declare variable WDATAINI date;
declare variable WDATAFIN date;
declare variable WHORAINI time;
declare variable WHORAFIN time;
declare variable WCONNECTID integer;
declare variable WHOSTID integer;
declare variable WREGISTRATEMPOEXCEDENTE integer;
BEGIN

  -- Não inserir tempo quando o temporizador estiver desativado (#204416)
  SELECT FIRST 1 bdcodconf
  FROM VTPO_TCONF
  WHERE BDREFCONF <= EXTRACT(YEAR FROM CURRENT_DATE) * 100
                   + EXTRACT(MONTH FROM CURRENT_DATE)
  INTO :WCOUNT_CONF;

  SELECT FIRST 1 bdcodconf FROM VTPO_TCONF
  WHERE BDREFCONF <= EXTRACT(YEAR FROM CURRENT_DATE) * 100
      + EXTRACT(MONTH FROM CURRENT_DATE)
  and bdtempoexcedente = true
  into :wregistratempoexcedente;

  IF (WCOUNT_CONF IS NULL) THEN
    EXIT;

  -- Não inserir tempo quando não estiver personalizado para o temporizador (#204416)
  SELECT FIRST 1 BDCODIGO
  FROM TPERSONALIZACAO
  WHERE BDSISTEMAS CONTAINING '65' or BDSISTEMAS CONTAINING '1523'
  INTO :WCODSIS;

  IF (COALESCE(WCODSIS, 0) = 0) THEN
    EXIT;

  -- Evitar lançamento de tempo negativo
  IF (PRDATAHORAFIN < PRDATAHORAINI) THEN
    EXIT;

  -- Resolver host/sessão: preferir parâmetros; fallback para contexto da sessão
  SELECT FIRST 1
    COALESCE(:PRHOST,   CAST(TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_HOSTID'))    AS INTEGER)),
    COALESCE(:PRSESSAO, CAST(TRIM(RDB$GET_CONTEXT('USER_SESSION', 'W_CONNECTID')) AS INTEGER))
  FROM RDB$DATABASE
  INTO :WACTUAL_HOST, :WACTUAL_CONNECT;


  IF (PRTABELA_TEMP IS NULL OR COALESCE(PRTABELA_TEMP, 'FALSE') = 'FALSE') THEN
  BEGIN
    WCODIGO_TELA = NULL;
    IF (TRIM(PRNOMETELA) <> '') THEN
      SELECT FIRST 1 BDCODTELASIS
      FROM SP_GETCODIGO_TELA(:PRNOMETELA, :PRCAPTION)
      INTO :WCODIGO_TELA;

    -- Garantindo que gere o registro mesmo que alguma FK esteja errada (#232639)
    SELECT BDCODEMP FROM TEMPRESAS        WHERE BDCODEMP = :PRCODEMP  INTO :WCODEMP;
    SELECT BDCODATI FROM VTPO_ATIVIDADE_EXE WHERE BDCODATI = :PRCODATI INTO :WCODATI;

    SELECT FIRST 1 BDCODSIS
    FROM (
      SELECT BDCODSIS FROM TSISTEMA WHERE BDCODSIS = :PRCODSIS
      UNION ALL
      SELECT FIRST 1 BDCODSIS FROM TSISTEMA
    )
    WHERE BDCODSIS IS NOT NULL
    INTO :WCODSIS;

    SELECT BDID FROM VTPO_BASE_USERHOST WHERE BDID = :WACTUAL_HOST INTO :WACTUAL_HOST;

    -- Impedir duplicidade de registros
    SELECT FIRST 1 BDCHAVE
    FROM VTPO_ATIVIDADE_EXE_REGISTRO
    WHERE BDCODUSU    = :PRCODUSU
      AND BDDATAINI   = cast(:PRDATAHORAINI as date)
      AND (BDHORAINI <= cast(:prdatahoraini as time) AND BDHORAFIN >= cast(:prdatahorafin as time))
      AND BDCONNECTID = :WACTUAL_CONNECT
      AND BDHOSTID    = :WACTUAL_HOST
    INTO :WCHAVE;

    IF (WCHAVE IS NOT NULL) THEN
       exception EX_CUSTOM 'Erro inserindo duplicidade.';
    else
      INSERT INTO VTPO_ATIVIDADE_EXE_REGISTRO (
        BDCODUSU, BDCODEMP, BDCODATI,
        BDDATAINI, BDHORAINI,
        BDDATAFIN, BDHORAFIN,
        BDCODSIS, BDCODTELASIS, BDTIPOREGISTRO,
        BDOBSERVACAO, BDCONNECTID, BDHOSTID
      ) VALUES (
        :PRCODUSU, :WCODEMP, :WCODATI,
        CAST(:PRDATAHORAINI AS DATE), CAST(:PRDATAHORAINI AS TIME),
        CAST(:PRDATAHORAFIN AS DATE), CAST(:PRDATAHORAFIN AS TIME),
        :WCODSIS, :WCODIGO_TELA, :PRTIPOREGISTRO,
        :PROBSERVACAO, :WACTUAL_CONNECT, :WACTUAL_HOST
      );
  END
  ELSE
  BEGIN
    WCOUNT = 0;

    FOR
      SELECT
        REG.BDCODUSU, REG.BDCODEMP, REG.BDCODATI,
        REG.BDDATAINI, REG.BDHORAINI,
        REG.BDDATAFIN, REG.BDHORAFIN,
        REG.BDCODSIS,  REG.BDTIPOREGISTRO,
        REG.BDOBSERVACAO, REG.BDCODTELASIS,
        ATI.BDTEMPOOCIOSO,
        REG.BDCONNECTID, REG.BDHOSTID,
        REG.BDTEMPO
      FROM TMP_VTPO_ATIVIDADE_EXE_REGISTRO REG
        LEFT JOIN VTPO_ATIVIDADE_EXE ATI ON ATI.BDCODATI = REG.BDCODATI
      ORDER BY REG.BDCHAVE
      INTO
        :WCODUSU, :WCODEMP, :WCODATI,
        :WDATAINI, :WHORAINI,
        :WDATAFIN, :WHORAFIN,
        :WCODSIS, :WTIPOREGISTRO,
        :WOBSERVACAO, :WCODIGO_TELA,
        :WTEMPOOCIOSO,
        :WCONNECTID, :WHOSTID,
        :WTEMPO
    DO
    BEGIN
      -- Exibir código de tela somente para atividade ociosa
      IF (UPPER(WTEMPOOCIOSO) IS DISTINCT FROM 'TRUE') THEN
        WCODIGO_TELA = NULL;

      WCHAVE = NULL;

      -- Na primeira iteração: buscar registro existente para possível UPDATE (#244193)
      IF (WCOUNT = 0) THEN
      BEGIN
        WHORAINI_REG = WHORAINI;

--        if (wregistratempoexcedente is null) then
--        begin
          SELECT FIRST 1 BDCHAVE
          FROM VTPO_ATIVIDADE_EXE_REGISTRO
          WHERE BDDATAINI   = :WDATAINI
--            AND BDHORAINI   = :WHORAINI
            AND BDHORAINI <= :whorafin
            and BDHORAFIN >= :WHORAINI
            AND BDCODATI    = 2
            AND BDCONNECTID = :WACTUAL_CONNECT
            AND BDHOSTID    = :WACTUAL_HOST
          ORDER BY BDCHAVE DESC
          INTO :WCHAVE;
--        end
--        else
--           WCHAVE = null;
      END

      -- Calcular hora final somando o tempo registrado à hora inicial acumulada
      WHORAFIN_REG = DATEADD(SECOND, :WTEMPO, :WHORAINI_REG);

--      IF ((wregistratempoexcedente is null) and (WCHAVE IS NOT NULL)) THEN
      IF (WCHAVE IS NOT NULL) THEN
        UPDATE VTPO_ATIVIDADE_EXE_REGISTRO SET
          BDCODEMP       = :WCODEMP,
          BDCODATI       = :WCODATI,
          BDHORAFIN      = :WHORAFIN_REG,
          BDTIPOREGISTRO = :WTIPOREGISTRO,
          BDOBSERVACAO   = :WOBSERVACAO,
          BDCODTELASIS   = :WCODIGO_TELA
        WHERE BDCHAVE = :WCHAVE;
      ELSE
        INSERT INTO VTPO_ATIVIDADE_EXE_REGISTRO (
          BDCODUSU, BDCODEMP, BDCODATI,
          BDDATAINI, BDHORAINI,
          BDDATAFIN, BDHORAFIN,
          BDCODSIS, BDTIPOREGISTRO,
          BDOBSERVACAO, BDCODTELASIS,
          BDCONNECTID, BDHOSTID
        ) VALUES (
          :WCODUSU, :WCODEMP, :WCODATI,
          :WDATAINI, :WHORAINI_REG,
          :WDATAFIN, :WHORAFIN_REG,
          :WCODSIS, :WTIPOREGISTRO,
          :WOBSERVACAO, :WCODIGO_TELA,
          :WACTUAL_CONNECT, :WACTUAL_HOST
        )
        RETURNING BDCHAVE INTO :WCHAVE;

      -- Hora inicial da próxima iteração passa a ser a hora final atual (#244193)
      WHORAINI_REG = WHORAFIN_REG;
      WCOUNT = WCOUNT + 1;
    END
  END
END^

create or alter  trigger vtpo_atividade_exe_qtd_bi0 for vtpo_atividade_exe_qtd
active before insert position 0
AS
begin
 IF (NEW.BDCHAVE IS NULL OR NEW.BDCHAVE = 0) THEN
    BEGIN
      NEW.BDCHAVE = coalesce((select first 1 BDCHAVE from VTPO_ATIVIDADE_EXE_QTD order by BDCHAVE desc),0)+1;
    END
end^

CREATE OR ALTER TRIGGER VSH_EMP_TLOG_PROCESSO_BI0 FOR VSH_EMP_TLOG_PROCESSO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  IF (COALESCE(NEW.BDORDEMLOG, 0) = 0) THEN
    BEGIN
      SELECT MAX(BDORDEMLOG) + 1
      FROM VSH_EMP_TLOG_PROCESSO LP
      WHERE LP.BDCODAGENDAMENTO = NEW.BDCODAGENDAMENTO
      AND LP.BDCODEMP           = NEW.BDCODEMP
      AND LP.BDCODPLANOSCHIP    = NEW.BDCODPLANOSCHIP
      AND LP.BDORDEMAGENDAMENTO = NEW.BDORDEMAGENDAMENTO
      INTO NEW.BDORDEMLOG;
      NEW.BDORDEMLOG = COALESCE(NEW.BDORDEMLOG, 1);
    END

  NEW.BDDATAHORA = CAST('NOW' AS TIMESTAMP);
end^

CREATE OR ALTER trigger vrhf_emp_tpgto_rural_ai0 for vrhf_emp_tpgto_rural
active after insert position 0
AS
  declare variable wcodplanoonline INTEGER;
  declare variable wchave INTEGER;
  declare variable wcontacredpgto INTEGER;
  declare variable wcontadebpgto INTEGER;
  declare variable wcredito INTEGER;
  declare variable wdebito INTEGER;
  declare variable wchavevsuc INTEGER;
begin
  wcodplanoonline = null;
  wchave          = null;

  select first 1 BDCODPLANOONLINE, BDCHAVE
  from VRHF_EMP_TPGTO_CALC
  where BDCODEMP = new.bdcodemp and BDCHAVEPGTO = new.bdchavepgto and BDCODPGTO = new.bdcodpgto
  into :wcodplanoonline, :wchave;

  if (coalesce(wcodplanoonline, 0) > 0 and coalesce(wchave, 0) > 0) then
     begin
       wcontacredpgto = null;
       wcontadebpgto  = null;
       select first 1 BDCONTADEBPGTO, BDCONTACREDPGTO from TCONF_CONTAS_ONLINE where BDCODPLANOONLINE = :wcodplanoonline and BDCHAVE = :wchave into :wcontadebpgto, :wcontacredpgto;

       if (coalesce(wcontadebpgto, wcontacredpgto, 0) > 0) then
          begin
            for select TOL.BDCHAVE, LAN.BDCREDITO, LAN.BDCREDITO
                from TOL_VRHF_EMP_TPGTO_CALC TOL
                join VSUC_EMPRESAS_TLAN LAN on (LAN.BDCODEMP = TOL.BDCODEMP and LAN.BDCHAVE = TOL.BDCHAVE)
                where TOL.BDCODEMP = new.bdcodemp and TOL.BDCHAVEPGTO = new.BDCHAVEPGTO and TOL.BDCODPGTO = new.bdcodpgto
            into :wchavevsuc, :wdebito, :wcredito
            do
              begin
                if ((coalesce(wdebito, 0) > 0 and coalesce(wdebito, 0) = coalesce(wcontadebpgto, 0)) or (coalesce(wcredito, 0) > 0 and coalesce(wcredito, 0) = coalesce(wcontacredpgto, 0))) then
                   update or insert into VSUC_EMPRESAS_TLPR (BDCODEMP,BDCHAVE,BDCODIMOVRUR,BDTIPMOV,BDCTACOR,BDCODTER,BDTIPDOC,BDTIPLAN,BDTIPOPE,
                                                             BDTRANSFERENCIA,BDTRANSTIPMOV,BDTRANSCTACOR,BDTRANSTIPOPE, BDTIPOPARTICIPANTE, BDCPFMANUAL)
                   values (new.bdcodemp, :wchavevsuc, new.BDCODIMOVRUR, new.BDTIPMOV, new.BDCTAEMPRESA, new.BDCODTER, new.BDTIPDOC, new.BDTIPLAN, new.BDTIPOPE,
                           new.BDTRANSFERENCIA, new.BDTRANSTIPMOV, new.BDCTAEMPRESATRANS, new.BDTRANSTIPOPE, new.BDTIPOPARTICIPANTE, new.BDCPFMANUAL)
                   matching (BDCODEMP, BDCHAVE);
              end
          end
     end
end^


CREATE OR ALTER trigger tdarfgerpgto_rural_au0 for tdarfgerpgto_rural
active after update position 0
AS
  declare variable wcodplanoonline INTEGER;
  declare variable wchave INTEGER;
  declare variable wcontacredpgto INTEGER;
  declare variable wcontadebpgto INTEGER;
  declare variable wcredito INTEGER;
  declare variable wdebito INTEGER;
  declare variable wchavevsuc INTEGER;
begin
  wcodplanoonline = null;
  wchave          = null;

  select first 1 BDCODPLANOONLINE, BDCHAVECONFONLINE
  from TDARFGERPGTO
  where BDCODEMP = new.bdcodemp and BDCHAVEPGTODARF = new.bdchavepgto
  into :wcodplanoonline, :wchave;

  if (coalesce(wcodplanoonline, 0) > 0 and coalesce(wchave, 0) > 0) then
     begin
       wcontacredpgto = null;
       wcontadebpgto  = null;
       select first 1 BDCONTADEBPGTO, BDCONTACREDPGTO from TCONF_CONTAS_ONLINE where BDCODPLANOONLINE = :wcodplanoonline and BDCHAVE = :wchave into :wcontadebpgto, :wcontacredpgto;

       if (coalesce(wcontadebpgto, wcontacredpgto, 0) > 0) then
          begin
            for select TOL.BDCHAVE, LAN.BDCREDITO, LAN.BDCREDITO
                from TOL_UNICO_PAG_DARF TOL
                join VSUC_EMPRESAS_TLAN LAN on (LAN.BDCODEMP = TOL.BDCODEMP and LAN.BDCHAVE = TOL.BDCHAVE)
                where TOL.BDCODEMP = new.bdcodemp and TOL.BDCHAVEPGTODARF = new.BDCHAVEPGTO
            into :wchavevsuc, :wdebito, :wcredito
            do
              begin
                if ((coalesce(wdebito, 0) > 0 and coalesce(wdebito, 0) = coalesce(wcontadebpgto, 0)) or (coalesce(wcredito, 0) > 0 and coalesce(wcredito, 0) = coalesce(wcontacredpgto, 0))) then
                   update or insert into VSUC_EMPRESAS_TLPR (BDCODEMP,BDCHAVE,BDCODIMOVRUR,BDTIPMOV,BDCTACOR,BDCODTER,BDTIPDOC,BDTIPLAN,BDTIPOPE,
                                                             BDTRANSFERENCIA,BDTRANSTIPMOV,BDTRANSCTACOR,BDTRANSTIPOPE, BDTIPOPARTICIPANTE, BDCPFMANUAL)
                   values (new.bdcodemp, :wchavevsuc, new.BDCODIMOVRUR, new.BDTIPMOV, new.BDCTAEMPRESA, new.BDCODTER, new.BDTIPDOC, new.BDTIPLAN, new.BDTIPOPE,
                           new.BDTRANSFERENCIA, new.BDTRANSTIPMOV, new.BDCTAEMPRESATRANS, new.BDTRANSTIPOPE, new.BDTIPOPARTICIPANTE, new.BDCPFPARTICIPANTE)
                   matching (BDCODEMP, BDCHAVE);
              end
          end
     end
end
^

CREATE OR ALTER trigger tdarfgerpgto_rural_ai0 for tdarfgerpgto_rural
active after insert position 0
AS
  declare variable wcodplanoonline INTEGER;
  declare variable wchave INTEGER;
  declare variable wcontacredpgto INTEGER;
  declare variable wcontadebpgto INTEGER;
  declare variable wcredito INTEGER;
  declare variable wdebito INTEGER;
  declare variable wchavevsuc INTEGER;
begin
  wcodplanoonline = null;
  wchave          = null;

  select first 1 BDCODPLANOONLINE, BDCHAVECONFONLINE
  from TDARFGERPGTO
  where BDCODEMP = new.bdcodemp and BDCHAVEPGTODARF = new.bdchavepgto
  into :wcodplanoonline, :wchave;

  if (coalesce(wcodplanoonline, 0) > 0 and coalesce(wchave, 0) > 0) then
     begin
       wcontacredpgto = null;
       wcontadebpgto  = null;
       select first 1 BDCONTADEBPGTO, BDCONTACREDPGTO from TCONF_CONTAS_ONLINE where BDCODPLANOONLINE = :wcodplanoonline and BDCHAVE = :wchave into :wcontadebpgto, :wcontacredpgto;

       if (coalesce(wcontadebpgto, wcontacredpgto, 0) > 0) then
          begin
            for select TOL.BDCHAVE, LAN.BDCREDITO, LAN.BDCREDITO
                from TOL_UNICO_PAG_DARF TOL
                join VSUC_EMPRESAS_TLAN LAN on (LAN.BDCODEMP = TOL.BDCODEMP and LAN.BDCHAVE = TOL.BDCHAVE)
                where TOL.BDCODEMP = new.bdcodemp and TOL.BDCHAVEPGTODARF = new.BDCHAVEPGTO
            into :wchavevsuc, :wdebito, :wcredito
            do
              begin
                if ((coalesce(wdebito, 0) > 0 and coalesce(wdebito, 0) = coalesce(wcontadebpgto, 0)) or (coalesce(wcredito, 0) > 0 and coalesce(wcredito, 0) = coalesce(wcontacredpgto, 0))) then
                   update or insert into VSUC_EMPRESAS_TLPR (BDCODEMP,BDCHAVE,BDCODIMOVRUR,BDTIPMOV,BDCTACOR,BDCODTER,BDTIPDOC,BDTIPLAN,BDTIPOPE,
                                                             BDTRANSFERENCIA,BDTRANSTIPMOV,BDTRANSCTACOR,BDTRANSTIPOPE, BDTIPOPARTICIPANTE, BDCPFMANUAL)
                   values (new.bdcodemp, :wchavevsuc, new.BDCODIMOVRUR, new.BDTIPMOV, new.BDCTAEMPRESA, new.BDCODTER, new.BDTIPDOC, new.BDTIPLAN, new.BDTIPOPE,
                           new.BDTRANSFERENCIA, new.BDTRANSTIPMOV, new.BDCTAEMPRESATRANS, new.BDTRANSTIPOPE, new.BDTIPOPARTICIPANTE, new.BDCPFPARTICIPANTE)
                   matching (BDCODEMP, BDCHAVE);
              end
          end
     end
end^


CREATE OR ALTER trigger vrhf_emp_tpgto_rural_au0 for vrhf_emp_tpgto_rural
active after update position 0
AS
  declare variable wcodplanoonline INTEGER;
  declare variable wchave INTEGER;
  declare variable wcontacredpgto INTEGER;
  declare variable wcontadebpgto INTEGER;
  declare variable wcredito INTEGER;
  declare variable wdebito INTEGER;
  declare variable wchavevsuc INTEGER;
begin
  wcodplanoonline = null;
  wchave          = null;

  select first 1 BDCODPLANOONLINE, BDCHAVE
  from VRHF_EMP_TPGTO_CALC
  where BDCODEMP = new.bdcodemp and BDCHAVEPGTO = new.bdchavepgto and BDCODPGTO = new.bdcodpgto
  into :wcodplanoonline, :wchave;

  if (coalesce(wcodplanoonline, 0) > 0 and coalesce(wchave, 0) > 0) then
     begin
       wcontacredpgto = null;
       wcontadebpgto  = null;
       select first 1 BDCONTADEBPGTO, BDCONTACREDPGTO from TCONF_CONTAS_ONLINE where BDCODPLANOONLINE = :wcodplanoonline and BDCHAVE = :wchave into :wcontadebpgto, :wcontacredpgto;

       if (coalesce(wcontadebpgto, wcontacredpgto, 0) > 0) then
          begin
            for select TOL.BDCHAVE, LAN.BDCREDITO, LAN.BDCREDITO
                from TOL_VRHF_EMP_TPGTO_CALC TOL
                join VSUC_EMPRESAS_TLAN LAN on (LAN.BDCODEMP = TOL.BDCODEMP and LAN.BDCHAVE = TOL.BDCHAVE)
                where TOL.BDCODEMP = new.bdcodemp and TOL.BDCHAVEPGTO = new.BDCHAVEPGTO and TOL.BDCODPGTO = new.bdcodpgto
            into :wchavevsuc, :wdebito, :wcredito
            do
              begin
                if ((coalesce(wdebito, 0) > 0 and coalesce(wdebito, 0) = coalesce(wcontadebpgto, 0)) or (coalesce(wcredito, 0) > 0 and coalesce(wcredito, 0) = coalesce(wcontacredpgto, 0))) then
                   update or insert into VSUC_EMPRESAS_TLPR (BDCODEMP,BDCHAVE,BDCODIMOVRUR,BDTIPMOV,BDCTACOR,BDCODTER,BDTIPDOC,BDTIPLAN,BDTIPOPE,
                                                             BDTRANSFERENCIA,BDTRANSTIPMOV,BDTRANSCTACOR,BDTRANSTIPOPE, BDTIPOPARTICIPANTE, BDCPFMANUAL)
                   values (new.bdcodemp, :wchavevsuc, new.BDCODIMOVRUR, new.BDTIPMOV, new.BDCTAEMPRESA, new.BDCODTER, new.BDTIPDOC, new.BDTIPLAN, new.BDTIPOPE,
                           new.BDTRANSFERENCIA, new.BDTRANSTIPMOV, new.BDCTAEMPRESATRANS, new.BDTRANSTIPOPE, new.BDTIPOPARTICIPANTE, new.BDCPFMANUAL)
                   matching (BDCODEMP, BDCHAVE);
              end
          end
     end
end
^

CREATE OR ALTER TRIGGER VSH_EMP_TCONFERENCIA_FOLHA_BI0 FOR VSH_EMP_TCONFERENCIA_FOLHA
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE wConfigSCIReport VARCHAR(5);
begin
  IF (NEW.BDORIGEM = 'SChIp') THEN
    BEGIN
      NEW.BDDATAGERACAO = localtimestamp;
      NEW.BDDATAINI = localtimestamp;
    END
  ELSE
    NEW.BDDATAALTERACAO = localtimestamp;

  IF (COALESCE(NEW.BDEMAIL, 0) = 0) THEN
    NEW.BDEMAIL = 2;

  IF (COALESCE(NEW.BDSCIREPORT, 0) = 0) THEN
    NEW.BDSCIREPORT = 2;

  SELECT UPPER(BDSCIREPORT) FROM TEMPRESAS X
  WHERE X.BDCODEMP = NEW.BDCODEMP INTO :wConfigSCIReport;

  NEW.BDCONFIGSCIREPORT = :wConfigSCIReport;
end^

CREATE OR ALTER TRIGGER VSH_EMP_TCONFERENCIA_FOLHA_BU0 FOR VSH_EMP_TCONFERENCIA_FOLHA
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  if (upper(coalesce(new.bdnaoalteradata, 'FALSE')) = 'FALSE') then
     begin
       if (new.bdorigem = 'Manual') then
         new.bddataalteracao = localtimestamp;

       if (new.bdorigem = 'SChIp') then
         new.bddatageracao = localtimestamp;
     end

  new.bdnaoalteradata = 'FALSE';
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TOCORRENCIA_COL_BI0 FOR VRH_EMP_TOCORRENCIA_COL
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (coalesce(new.BDCODOCO, 0) = 0) then
    select coalesce(max(BDCODOCO), 0) + 1
    from VRH_EMP_TOCORRENCIA_COL
    where BDCODEMP = new.BDCODEMP and
          BDCODCOL = new.BDCODCOL and
          BDREF = new.BDREF and
          BDCODAUTOTHREAD = new.BDCODAUTOTHREAD
    into new.BDCODOCO;
end^

CREATE OR ALTER TRIGGER VSH_EMP_TARQUIVO_PROCESSO_BI FOR VSH_EMP_TARQUIVO_PROCESSO
ACTIVE BEFORE INSERT POSITION 0
as
begin
  if (coalesce(new.BDCODARQ, 0) = 0) then
    select coalesce(max(BDCODARQ), 0) + 1
    from VSH_EMP_TARQUIVO_PROCESSO
    where BDCODAGENDAMENTO = new.BDCODAGENDAMENTO and
          BDCODEMP = new.BDCODEMP and
          BDCODPLANOSCHIP = new.BDCODPLANOSCHIP
    into new.BDCODARQ;
end^

CREATE OR ALTER TRIGGER VSH_EMP_TARQUIVO_PROCESSO_BU0 FOR VSH_EMP_TARQUIVO_PROCESSO
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  if (coalesce(new.BDCODARQ, 0) = 0) then
    select coalesce(max(BDCODARQ), 0) + 1
    from VSH_EMP_TARQUIVO_PROCESSO
    where BDCODAGENDAMENTO = new.BDCODAGENDAMENTO and
          BDCODEMP = new.BDCODEMP and
          BDCODPLANOSCHIP = new.BDCODPLANOSCHIP
    into new.BDCODARQ;
end^

CREATE OR ALTER TRIGGER vsh_base_tagendamento_bi0 FOR vsh_base_tagendamento
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  IF (NEW.BDHORA < LOCALTIME) THEN
    NEW.BDULTIMAEXECUCAO = CURRENT_DATE;
end^

CREATE OR ALTER TRIGGER VSH_BASE_TAGENDAMENTO_BD0 FOR VSH_BASE_TAGENDAMENTO
ACTIVE BEFORE DELETE POSITION 0
AS
begin
  IF (OLD.BDREADONLY = TRUE) THEN
    EXCEPTION EX_EXCLUSAO_IC;
end
^

CREATE OR ALTER TRIGGER VSH_BASE_TPLANO_BD0 FOR VSH_BASE_TPLANO
ACTIVE BEFORE DELETE POSITION 0
AS
begin
  IF (OLD.BDREADONLY = TRUE) THEN
    EXCEPTION EX_EXCLUSAO_IC;
end
^

CREATE OR ALTER procedure SP_COPIAR_CONF_SCHIP (
    PRCODEMPORI integer,
    PRCODSISORI integer,
    PRCODEMPDEST integer)
as
declare variable WSQL varchar(500);
declare variable WVALUES varchar(500);
declare variable WFIELDS varchar(500);
declare variable WQUERY varchar(1500);
begin
  IF (:PRCODEMPORI = :PRCODEMPDEST) THEN
    EXIT;

  SELECT LIST('COALESCE(''''''''||'||TRIM(RDB$FIELD_NAME)||'||'''''''', ''NULL'')', '||'',''||') BDFIELDS FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME = 'VSH_EMP_TCONFEMPRESAS' INTO :wFields;

  wFields = REPLACE(:wFields, 'BDCODEMP', :PRCODEMPDEST);
  wFields = REPLACE(:wFields, 'BDORDEMCONF', '0');

  wSQL =         'SELECT ('||:wFields||') BDVALUES FROM VSH_EMP_TCONFEMPRESAS ';
  wSQL = wSQL || 'WHERE BDCODEMP = '||:PRCODEMPORI;
  wSQL = wSQL || 'AND BDCODSIS = '||:PRCODSISORI;
  EXECUTE STATEMENT :wSQL INTO :wValues;

  SELECT LIST(TRIM(RDB$FIELD_NAME)) BDFIELDS FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME = 'VSH_EMP_TCONFEMPRESAS' INTO :wFields;
  wQuery =            'UPDATE OR INSERT INTO VSH_EMP_TCONFEMPRESAS ('||:wFields||') ';
  wQuery = :wQuery || 'VALUES ('||:wValues||') MATCHING(BDCODEMP, BDCODSIS);';
  EXECUTE STATEMENT :wQuery;
end^

CREATE OR ALTER procedure SP_GET_STATUS_NOTIFICACAO_SCHIP (
    PRCODEMP integer,
    PRCODSIS integer)
returns (
    BDCODSTATUS integer)
as
declare variable WPROCREALIZADO DM_BOOLEAN;
declare variable WPROCREALIZADOINCO DM_BOOLEAN;
declare variable WPROCNAOREALIZADO DM_BOOLEAN;
begin
  SELECT FIRST 1 UPPER(COALESCE(CE.BDPROCREALIZADO, 'FALSE')),
                 UPPER(COALESCE(CE.BDPROCREALIZADOINCO, 'FALSE')),
                 UPPER(COALESCE(CE.BDPROCNAOREALIZADO, 'FALSE'))
  FROM VSH_EMP_TCONFEMPRESAS CE
  WHERE CE.BDCODEMP = :PRCODEMP
  AND CE.BDCODSIS = :PRCODSIS
  INTO :wProcRealizado, :wProcRealizadoInco, :wProcNaoRealizado;

  IF (ROW_COUNT = 0) THEN
    BEGIN
      BDCODSTATUS = 6; --Erro
      SUSPEND;
      BDCODSTATUS = 11; --Concluído com inconsistência
      SUSPEND;
    END
  ELSE
    BEGIN
      IF (:wProcRealizado = 'TRUE') THEN
        BEGIN
          BDCODSTATUS = 3;
          SUSPEND;
        END

      IF (:wProcRealizadoInco = 'TRUE') THEN
        BEGIN
          BDCODSTATUS = 11;
          SUSPEND;
        END

      IF (:wProcNaoRealizado = 'TRUE') THEN
        BEGIN
          BDCODSTATUS = 6;
          SUSPEND;
        END
    END
end^

create or alter procedure GETPRIVILEGIOSEMPRESAS_SCHIP (
    PRCODEMP integer,
    PRPRIVILEGIO varchar(200),
    PRCODSIS integer)
returns (
    BDCODEMP integer,
    BDCODGRUPO integer,
    BDCODUSU integer,
    BDITEMPRIV varchar(200))
as
declare variable WCOUNT integer;
declare variable WSQL varchar(2000);
declare variable WCOUNTGRP integer;
declare variable WCOUNTUSU integer;
declare variable WSQLX varchar(2000);
BEGIN
  -- verifica se o usuario pertence aos grupos 1 ou 2
  SELECT COUNT(bdcodgrupo) FROM tgrupousuario_usuario
  WHERE bdcodusu = (SELECT bdcodusu FROM sp_get_usuario)
  AND bdcodgrupo IN (1,2)
  INTO :wcount;
  IF (wcount > 0) THEN
     BEGIN
       -- carrega todas as empresas e privilegios
       wsql = 'select bdcodemp from tempresas ';
       IF ((prcodemp <> 0) OR (prcodemp IS NOT NULL)) THEN
          wsql = wsql||'where bdcodemp = '||prcodemp;
       wsql = wsql||' order by bdcodemp';
       FOR EXECUTE STATEMENT wsql INTO :bdcodemp DO
           BEGIN
             -- retorna todos os privilegios do ususario se não houver empresa configurada
             wsqlx = 'select 1 as bdcodgrupo, (select bdcodusu from sp_get_usuario) bdcodusu, tpriv.bditempriv ';
             wsqlx = wsqlx||'from tprivilegio_grupousuario tpriv ';
             IF ((prprivilegio IS NOT NULL) AND (TRIM(prprivilegio) <> '')) THEN
                wsqlx = wsqlx||'where upper(tpriv.bditempriv) containing upper('''||TRIM(prprivilegio)||''')  and bdcodsis = '||prcodsis;
             wsqlx = wsqlx||'group by 1,2,3 ';
             FOR EXECUTE STATEMENT wsqlx INTO :bdcodgrupo, :bdcodusu, :bditempriv DO
                 SUSPEND;
           END
     END
  ELSE
     BEGIN
       -- verifica se há empresas no grupo de usuários
       wsql = 'select count(bdcodemp) from tempresa_grupousuario tegu ';
       wsql = wsql||'inner join tgrupousuario_usuario tgrp on(tgrp.bdcodgrupo = tegu.bdcodgrupo and tgrp.bdcodusu = (select bdcodusu from sp_get_usuario)) ';
       EXECUTE STATEMENT wsql INTO :wcountgrp;
       -- verifica as empresas por usuário
       wsql = 'select count(bdcodemp) from tempresa_usuario where bdcodusu = (select bdcodusu from sp_get_usuario) ';
       EXECUTE STATEMENT wsql INTO :wcountusu;

       -- verifica se tem empresa configurada para usuario ou grupo de usuario
       wsql = 'select count(temp.bdcodemp) ';--  select temp.bdcodemp, temp.bdcodgrupo, tgrp.bdcodusu
       wsql = wsql||'from tempresa_grupousuario temp ';
       wsql = wsql||'inner join tgrupousuario_usuario tgrp on (tgrp.bdcodgrupo = temp.bdcodgrupo and tgrp.bdcodusu = (select x.bdcodusu from sp_get_usuario x)) ';
       IF (wcountusu > 0) THEN
          wsql = wsql||'inner join tempresa_usuario teu on (teu.bdcodemp = temp.bdcodemp and teu.bdcodusu = tgrp.bdcodusu) ';
       IF ((prcodemp <> 0) OR (prcodemp IS NOT NULL)) THEN
          wsql = wsql||'and temp.bdcodemp = '||prcodemp;
       EXECUTE STATEMENT wsql INTO :wcount;
     
       IF (wcount = 0) THEN
          BEGIN
            -- retorna empresas por escritorio
            wsql = 'select distinct temp.bdcodemp from tempresas temp ';
            IF (wcountgrp > 0) THEN
               BEGIN
                 wsql = wsql||'inner join tgrupousuario_usuario tusu on (tusu.bdcodusu = (select bdcodusu from sp_get_usuario)) ';
                 wsql = wsql||'inner join tgrupousuario tgrp on (tgrp.bdcodgrupo = tusu.bdcodgrupo and tgrp.bdcodesc = temp.bdcodesc) ';
                 wsql = wsql||'inner join tempresa_grupousuario tegu on (tegu.bdcodemp = temp.bdcodemp and tegu.bdcodgrupo =  tgrp.bdcodgrupo) ';
               END
            IF (wcountusu > 0) THEN
               wsql = wsql||'inner join tempresa_usuario teu on (teu.bdcodemp = temp.bdcodemp and teu.bdcodusu = (select bdcodusu from sp_get_usuario)) ';
            IF ((prcodemp <> 0) OR (prcodemp IS NOT NULL)) THEN
               wsql = wsql||' where temp.bdcodemp = '||prcodemp;
            wsql = wsql||' order by temp.bdcodemp';
            FOR EXECUTE STATEMENT wsql INTO :bdcodemp DO
              BEGIN
                -- retorna todos os privilegios do ususario se não houver empresa configurada
                wsqlx = 'select tpriv.bdcodgrupo, tgrp.bdcodusu, tpriv.bditempriv ';
                wsqlx = wsqlx||'from tprivilegio_grupousuario tpriv ';
                wsqlx = wsqlx||'inner join tgrupousuario_usuario tgrp on (tgrp.bdcodgrupo = tpriv.bdcodgrupo and tgrp.bdcodusu = (select bdcodusu from sp_get_usuario)) ';
                IF ((prprivilegio IS NOT NULL) AND (TRIM(prprivilegio) <> '')) THEN
                   wsqlx = wsqlx||'where upper(tpriv.bditempriv) containing upper('''||TRIM(prprivilegio)||''') ';
                wsqlx = wsqlx||'order by tpriv.bdcodgrupo, tpriv.bditempriv ';
                FOR EXECUTE STATEMENT wsqlx INTO :bdcodgrupo, :bdcodusu, :bditempriv DO
                  SUSPEND;
              END
          END
       ELSE
          BEGIN
            -- retorna privilegios do usuario com empresa configurada
            wsql = 'select temp.bdcodemp, temp.bdcodgrupo, tgrp.bdcodusu, tpriv.bditempriv ';
            wsql = wsql||'from tempresa_grupousuario temp ';
            wsql = wsql||'inner join tgrupousuario_usuario tgrp on (tgrp.bdcodgrupo = temp.bdcodgrupo and tgrp.bdcodusu = (select x.bdcodusu from sp_get_usuario x)) ';

            IF ((prprivilegio IS NOT NULL) AND (TRIM(prprivilegio) <> '')) THEN
               wsql = wsql||'inner join tprivilegio_grupousuario tpriv on (tpriv.bdcodgrupo = tgrp.bdcodgrupo and (upper(tpriv.bditempriv) containing upper('''||TRIM(prprivilegio)||'''))) ';
            ELSE
               wsql = wsql||'inner join tprivilegio_grupousuario tpriv on (tpriv.bdcodgrupo = tgrp.bdcodgrupo ) ';
            IF (wcountusu > 0) THEN
               wsql = wsql||'inner join tempresa_usuario tusu on (tusu.bdcodemp = temp.bdcodemp and tusu.bdcodusu = tgrp.bdcodusu) ';
            IF ((prcodemp <> 0) OR (prcodemp IS NOT NULL)) THEN
               wsql = wsql||'where temp.bdcodemp = '||prcodemp;
            FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdcodgrupo, :bdcodusu, :bditempriv DO
               SUSPEND;
          END
     END
END^

CREATE OR ALTER TRIGGER vsh_emp_tconfempresas_bi0 FOR vsh_emp_tconfempresas
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE wOrdemExist INTEGER;
DECLARE VARIABLE wBuscaChave DM_BOOLEAN;
begin
  IF (COALESCE(NEW.BDORDEMCONF, 0) > 0) THEN
    BEGIN
      wOrdemExist = NULL;

      SELECT C.BDORDEMCONF
      FROM VSH_EMP_TCONFEMPRESAS C
      WHERE C.BDCODEMP  = NEW.BDCODEMP
      AND C.BDORDEMCONF = NEW.BDORDEMCONF
      INTO :wOrdemExist;

      wBuscaChave = IIF((COALESCE(:wOrdemExist, 0) > 0), 'TRUE', 'FALSE');
    END
  ELSE
    wBuscaChave = 'TRUE';


  IF (:wBuscaChave = 'TRUE') THEN
    BEGIN
      SELECT MAX(C.BDORDEMCONF) + 1
      FROM VSH_EMP_TCONFEMPRESAS C
      WHERE C.BDCODEMP = NEW.BDCODEMP
      INTO NEW.BDORDEMCONF;

      IF (COALESCE(NEW.BDORDEMCONF, 0) = 0) THEN
        NEW.BDORDEMCONF = 1;
    END
end^

CREATE OR ALTER TRIGGER vsh_emp_tconfempresas_bu0 FOR vsh_emp_tconfempresas
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  IF (COALESCE(NEW.BDORDEMCONF, 0) = 0) THEN
    NEW.BDORDEMCONF = OLD.BDORDEMCONF;
end^

CREATE OR ALTER TRIGGER VSH_EMP_TCONIA_IMPOSTO_BI0 FOR VSH_EMP_TCONFERENCIA_IMPOSTO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  IF (COALESCE(NEW.BDORDEMPROC, 0) = 0) THEN
    BEGIN
      if (Coalesce(new.bdcodstatus,0) = 0) then
      NEW.BDCODSTATUS = 1;

      SELECT MAX(BDORDEMPROC) + 1
      FROM VSH_EMP_TCONFERENCIA_IMPOSTO FI
      WHERE FI.BDCODEMP = NEW.BDCODEMP
      INTO NEW.BDORDEMPROC;

      NEW.BDORDEMPROC = COALESCE(NEW.BDORDEMPROC, 1);

      /*
        Threads que vão jogar como substituído o registro anterior do mesmo processo
        7 - Envio PGDAS-D
      */
      IF (COALESCE(NEW.BDINTEGRACONTADOR, 'FALSE') = 'TRUE') THEN
        BEGIN
          UPDATE VSH_EMP_TCONFERENCIA_IMPOSTO CI
          SET CI.BDCODSTATUS = 3
          WHERE CI.BDCODEMP = NEW.BDCODEMP
          AND CI.BDREFERENCIA = NEW.BDREFERENCIA
          AND CI.BDCODAUTOTHREAD = NEW.BDCODAUTOTHREAD
          AND CI.BDIDSERVICO = NEW.BDIDSERVICO
          AND COALESCE(CI.BDCOMPLEMENTODESC, '') = COALESCE(NEW.BDCOMPLEMENTODESC, '')
          AND CI.BDCODIMP = NEW.BDCODIMP
          AND CI.BDCODSTATUS <> 3;
        END
      ELSE
      IF (NEW.BDCODAUTOTHREAD IN(6, 7)) THEN
        BEGIN
          UPDATE VSH_EMP_TCONFERENCIA_IMPOSTO CI
          SET CI.BDCODSTATUS = 3
          WHERE CI.BDCODEMP = NEW.BDCODEMP
          AND CI.BDREFERENCIA = NEW.BDREFERENCIA
          AND CI.BDCODAUTOTHREAD = NEW.BDCODAUTOTHREAD
          AND CI.BDCODSTATUS <> 3;
    END
    END

  NEW.BDDATAGERACAO = localtimestamp;
  NEW.BDCODUSUORI   = (SELECT BDCODUSU FROM SP_GET_USUARIO);
end^

CREATE OR ALTER TRIGGER vsh_emp_tconfia_imposto_bu0 FOR vsh_emp_tconferencia_imposto
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  /*Recalculou manualmente e esta alterando a tabela de conferência*/
  IF ((COALESCE(NEW.BDCHAVEDARF, 0) > 0) AND (OLD.BDCHAVEDARF IS NULL)) THEN
    BEGIN
      NEW.BDCODSTATUS = 1; /*Sucesso*/

      IF ((SELECT FIRST 1 U.BDCODUSU FROM TUSUARIO U WHERE U.BDNOMUSU = 'schip') <> (SELECT BDCODUSU FROM SP_GET_USUARIO)) THEN
        BEGIN
          NEW.BDCODUSUALT     = (SELECT BDCODUSU FROM SP_GET_USUARIO);
          NEW.BDDATAALTERACAO = localtimestamp;
        END
      ELSE
        BEGIN
          NEW.BDCODUSUALT     = NULL;
          NEW.BDDATAALTERACAO = NULL;
        END
    END

  /*Vai recalcular manualmente, tem que apagar as inconsistências*/
  IF ((COALESCE(NEW.BDCHAVEDARF, 0) = 0) AND (OLD.BDCHAVEDARF IS NOT NULL)) THEN
    BEGIN
      NEW.BDCONFERIDO = 'FALSE';
      DELETE FROM VSH_EMP_TCONF_IMPOSTO_INCO WHERE BDCODEMP = NEW.BDCODEMP AND BDORDEMPROC = NEW.BDORDEMPROC AND NEW.BDCODAUTOTHREAD = 4;

      IF (OLD.BDCODAUTOTHREAD = 6) THEN /*Cálculo do imposto*/
        NEW.BDCODSTATUS = 4; /*Excluído*/
    END
end^

CREATE OR ALTER TRIGGER VSH_BASE_TIPO_TPROCESSO_BI0 FOR VSH_BASE_TIPO_TPROCESSO
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;
begin
  if (coalesce(new.bdcodprocesso, 0) = 0) then
     begin
       select coalesce(max(BDCODPROCESSO) + 1, 1) from VSH_BASE_TIPO_TPROCESSO into :vcod;
       new.bdcodprocesso = :vcod;
     end
end^

CREATE OR ALTER TRIGGER VSH_BASE_TPLANO_THREAD_BI0 FOR VSH_BASE_TPLANO_THREAD
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;
begin
  if (coalesce(new.bdordemthread, 0) = 0) then
     begin
       select coalesce(max(bdordemthread) + 1, 1) from VSH_BASE_TPLANO_THREAD where BDCODPLANOSCHIP = new.BDCODPLANOSCHIP into :vcod;
       new.bdordemthread = :vcod;
     end
end^

CREATE OR ALTER TRIGGER VSH_BASE_TTHREAD_BI0 FOR VSH_BASE_TTHREAD
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;
begin
  if (coalesce(new.bdcodautothread, 0) = 0) then
     begin
       select coalesce(max(BDCODAUTOTHREAD) + 1, 1) from VSH_BASE_TTHREAD into :vcod;
       new.bdcodautothread = :vcod;
     end
end^

CREATE OR ALTER TRIGGER vsh_emp_tconf_imposto_inc_bi0 FOR vsh_emp_tconf_imposto_inco
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  IF (COALESCE(NEW.BDORDEMINCO, 0) = 0) THEN
    BEGIN
      SELECT MAX(I.BDORDEMINCO) + 1
      FROM VSH_EMP_TCONF_IMPOSTO_INCO I
      WHERE I.BDCODEMP = NEW.BDCODEMP
      AND I.BDORDEMPROC = NEW.BDORDEMPROC
      INTO NEW.BDORDEMINCO;

      NEW.BDORDEMINCO = COALESCE(NEW.BDORDEMINCO, 1);

      UPDATE VSH_EMP_TCONFERENCIA_IMPOSTO CI
      SET CI.BDCODSTATUS = 2
      WHERE CI.BDCODEMP = NEW.BDCODEMP
      AND CI.BDORDEMPROC = NEW.BDORDEMPROC
      AND CI.BDCODSTATUS = 1
      AND CI.BDINTEGRACONTADOR <> TRUE;      
    END
end^

CREATE OR ALTER TRIGGER vsh_emp_tconf_imp_arq_bi0 FOR vsh_emp_tconferencia_imp_arq
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  IF (COALESCE(NEW.BDORDEMARQ, 0) = 0) THEN
    BEGIN
      SELECT MAX(IA.BDORDEMARQ) + 1
      FROM VSH_EMP_TCONFERENCIA_IMP_ARQ IA
      WHERE IA.BDCODEMP = NEW.BDCODEMP
      AND IA.BDORDEMPROC = NEW.BDORDEMPROC
      INTO NEW.BDORDEMARQ;

      NEW.BDORDEMARQ = COALESCE(NEW.BDORDEMARQ, 1);
    END
end^

CREATE OR ALTER procedure SP_STATUS_PLANO_SCHIP (
    PRIDPROC varchar(19) not null)
returns (
    BDSTATUS varchar(10))
as
declare variable WCODSTATUS integer;
begin
  BDSTATUS = 'FINALIZADO';

  FOR SELECT LP.BDCODSTATUS
      FROM VSH_EMP_TLISTA_PROCESSOS LP
      WHERE LP.BDIDPROC = :PRIDPROC
      GROUP BY LP.BDCODSTATUS
      INTO :wCodStatus
  DO
    BEGIN
      IF (:wCodStatus = 6) THEN
        BEGIN
          BDSTATUS = 'ERRO';
          SUSPEND;
          EXIT;
        END
      ELSE
      IF (:wCodStatus = 2) THEN
        BEGIN
          BDSTATUS = 'EXECUTANDO';
          SUSPEND;
          EXIT;
        END
      ELSE
      IF (:wCodStatus = 1) THEN
        BEGIN
          BDSTATUS = 'AGUARDANDO';
          SUSPEND;
          EXIT;
        END
    END

  SUSPEND;
end^

CREATE OR ALTER TRIGGER VSH_BASE_TAGENDAMENTO_PLANO_AD0 FOR VSH_BASE_TAGENDAMENTO_PLANO
ACTIVE AFTER DELETE POSITION 0
AS
begin
  delete from VSH_EMP_TAGENDAMENTO_EMPRESAS where BDCODAGENDAMENTO = old.BDCODAGENDAMENTO;
end^

CREATE OR ALTER procedure SP_EXPORTAR_LOG_SCHIP (
    PRCODAGENDAMENTO integer,
    PRCODEMP integer,
    PRCODPLANOSCHIP integer,
    PRORDEMAGENDAMENTO integer,
    PRLOCAL varchar(255))
returns (
    BDFILE varchar(255))
as
declare variable WDATAHORA timestamp;
declare variable WDESC blob sub_type 1 segment size 16384;
begin
  BDFILE = :PRLOCAL;

  NEWFILE(:BDFILE);

  OPENARQ(:BDFILE,:PRCODEMP);
  FOR SELECT LP.BDDATAHORA, LP.BDDESCRICAO
      FROM VSH_EMP_TLOG_PROCESSO LP
      WHERE LP.BDCODAGENDAMENTO = :PRCODAGENDAMENTO
      AND   LP.BDCODEMP = :PRCODEMP
      AND   LP.BDCODPLANOSCHIP = :PRCODPLANOSCHIP
      AND   LP.BDORDEMAGENDAMENTO = :PRORDEMAGENDAMENTO
      ORDER BY LP.BDDATAHORA DESC
      INTO :wDataHora, :wDesc
  DO
    BEGIN
      WRITELNOA(:wDataHora || ' - ' || :wDesc,:PRCODEMP);
    END
  CLOSEARQ(:BDFILE,:PRCODEMP);

  SUSPEND;
end^


CREATE OR ALTER TRIGGER TPERSONALIZACAO_BD0 FOR TPERSONALIZACAO
ACTIVE BEFORE DELETE POSITION 0
AS
   declare variable WUSR varchar(255);
begin
  SELECT TRIM(rdb$get_context('USER_SESSION', 'W_USUARIO')) FROM rdb$database into :WUSR;

  if (WUSR IS NULL) then
     EXCEPTION EX_PERSONALIZACAO;
end
^

CREATE OR ALTER trigger tpersonalizacao_bu0 for tpersonalizacao
active before update position 0
AS
   declare variable WUSR varchar(255);
begin
  if (new.bdultimobackupcorrompido='TRUE' and new.bdmotivocorrupcao is not null) then
  begin
    if (new.BDULTIMOBACKUPCORROMPIDODATA is null) then
      new.BDULTIMOBACKUPCORROMPIDODATA = current_timestamp;
  end
  else
  begin
    new.BDULTIMOBACKUPCORROMPIDODATA = null;
    new.BDULTIMOBACKUPCORROMPIDONOBKP = null;
  end

  if (((old.bdultimobackupcorrompido is not null) or (old.bdmotivocorrupcao is not null)) and
     ((new.bdultimobackupcorrompido is null) or (new.bdmotivocorrupcao is null))) then
     begin
        SELECT TRIM(rdb$get_context('USER_SESSION', 'W_USUARIO')) FROM rdb$database into :WUSR;

        if (WUSR IS NULL) then
           EXCEPTION EX_PERSONALIZACAO;
     end
end^

CREATE OR ALTER trigger tmensagens_email_bi0 for tmensagens_email
active before insert position 0
AS
begin
    if (new.bdchave is null or new.bdchave = 0 ) then
        begin
          select coalesce(max(bdchave)+ 1,1) from TMENSAGENS_EMAIL where BDCODSIS = new.BDCODSIS into new.bdchave;
        end
end^

CREATE OR ALTER TRIGGER tol_vef_emp_tapue316_ad0 for tol_vef_emp_tapue316
active after delete position 0
AS
begin
  DELETE FROM VEF_EMP_TAJUICMSSTE316 aju where aju.bdcodemp = old.bdcodemp and aju.bdordeme116250 = old.bdordeme116250;
end^

CREATE OR ALTER trigger tmoedas_ad0 for tmoedas
active after delete position 0
AS
begin
  update VEF_EMP_TMOVSAI set BDCODMOEDAS = null WHERE BDCODMOEDAS = old.BDCODMOEDAS;
end^

CREATE OR ALTER trigger vef_emp_tmovsai_bd0 for vef_emp_tmovsai
active after delete position 0
AS
begin
  DELETE FROM VEF_EMP_TC100SAI WHERE BDCODEMP = OLD.bdcodemp AND BDCHAVE = OLD.bdchave;
  DELETE FROM VEF_EMP_TMOVSAIITENS WHERE BDCODEMP = OLD.bdcodemp AND BDCHAVE = OLD.bdchave;  
  DELETE FROM VEF_EMP_TMOVPROSAIIMPORI WHERE BDCODEMP = OLD.bdcodemp AND BDCHAVE = OLD.bdchave;
  INSERT INTO VCT_EMP_VEF_EXCLUSOES(bdcodemp, bdcodusu, bdreferencia, bdtabela) VALUES (OLD.bdcodemp, OLD.bdcodusu, OLD.bdreflan, 1);   
end^

CREATE  OR ALTER trigger vef_emp_tmovser_bd0 for vef_emp_tmovser
active before delete position 0
AS
begin
  INSERT INTO VCT_EMP_VEF_EXCLUSOES(bdcodemp, bdcodusu, bdreferencia, bdtabela) VALUES (OLD.bdcodemp, OLD.bdcodusu, OLD.bdreflan, 3);
end^

CREATE OR ALTER trigger vef_emp_tmovexp_bd0 for vef_emp_tmovexp
active before delete position 0
AS
begin
  INSERT INTO VCT_EMP_VEF_EXCLUSOES(bdcodemp, bdcodusu, bdreferencia, bdtabela)
    VALUES (OLD.bdcodemp, OLD.bdcodusu, cast(extract(year from OLD.bddataregistro)||lpad(extract(month from OLD.bddataregistro), 2, 0) as integer), 9);
end^

CREATE  OR ALTER trigger vef_emp_tredz_bd0 for vef_emp_tredz
active before delete position 0
AS
begin
  INSERT INTO VCT_EMP_VEF_EXCLUSOES(bdcodemp, bdcodusu, bdreferencia, bdtabela) VALUES (OLD.bdcodemp, OLD.bdcodusu, OLD.bdreflan, 10);
end^

CREATE  OR ALTER trigger vef_emp_tmovfini100_bd0 for vef_emp_tmovfini100
active before delete position 0
AS
begin
  INSERT INTO VCT_EMP_VEF_EXCLUSOES(bdcodemp, bdcodusu, bdreferencia, bdtabela) VALUES (OLD.bdcodemp, OLD.bdcodusu, OLD.bdreferencia, 8);
end^

CREATE  OR ALTER trigger vef_emp_tmovinv_bd0 for vef_emp_tmovinv
active before delete position 0
AS
begin
  INSERT INTO VCT_EMP_VEF_EXCLUSOES(bdcodemp, bdcodusu, bdreferencia, bdtabela) VALUES (OLD.bdcodemp, OLD.bdcodusu, OLD.bdrefinv, 7);
end^

CREATE OR ALTER trigger vef_emp_tmovorec_bd0 for vef_emp_tmovorec
active before delete position 0
AS
begin
  INSERT INTO VCT_EMP_VEF_EXCLUSOES(bdcodemp, bdcodusu, bdreferencia, bdtabela)
    VALUES (OLD.bdcodemp, OLD.bdcodusu, cast(extract(year from OLD.bddatalan)||lpad(extract(month from OLD.bddatalan), 2, 0) as integer), 4);
end^

CREATE OR ALTER trigger vef_emp_tmovopimobiliaria_f200_bd0 for vef_emp_tmovopimobiliaria_f200
active before delete position 0
AS
begin
  INSERT INTO VCT_EMP_VEF_EXCLUSOES(bdcodemp, bdcodusu, bdreferencia, bdtabela)
    VALUES (OLD.bdcodemp, OLD.bdcodusu, cast(extract(year from OLD.bddatalan)||lpad(extract(month from OLD.bddatalan), 2, 0) as integer), 5);
end^

CREATE  OR ALTER trigger vef_emp_tmovdemaisdoc_f100_bd0 for vef_emp_tmovdemaisdoc_f100
active before delete position 0
AS
begin
  INSERT INTO VCT_EMP_VEF_EXCLUSOES(bdcodemp, bdcodusu, bdreferencia, bdtabela) VALUES (OLD.bdcodemp, OLD.bdcodusu, OLD.bdreflan, 4);
end^

CREATE  OR ALTER trigger vef_emp_tmovent_bd0 for vef_emp_tmovent
active before delete position 0
AS
begin
  INSERT INTO VCT_EMP_VEF_EXCLUSOES(bdcodemp, bdcodusu, bdreferencia, bdtabela) VALUES (OLD.bdcodemp, OLD.bdcodusu, OLD.bdreflan, 2);
end^

CREATE OR ALTER trigger vef_base_ttabinfad52_ad0 for vef_base_ttabinfad52
active after delete position 0
AS
begin
  update VEF_EMP_TMOVPROSAI set BDCBNEF = null WHERE BDCBNEF = old.BDORDEM52;
end^

CREATE OR ALTER trigger vef_emp_tmovprosaiimpori_biu0 for vef_emp_tmovprosaiimpori
active before insert or update position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  -- Verifica se os campos não são nulos e se foram alterados
  IF (NEW.BDCODEMP IS NOT NULL AND NEW.BDCHAVE IS NOT NULL AND (NEW.BDCODEMP IS DISTINCT FROM OLD.BDCODEMP OR NEW.BDCHAVE IS DISTINCT FROM OLD.BDCHAVE)) THEN
  BEGIN
    -- Verifica se os novos valores existem na tabela VEF_EMP_TMOVSAI
    IF (NOT EXISTS (
      SELECT 1
      FROM VEF_EMP_TMOVSAI A
      WHERE A.BDCODEMP = NEW.BDCODEMP
        AND A.BDCHAVE = NEW.BDCHAVE
    )) THEN
    BEGIN
      -- Lança exceção se não existir
      EXCEPTION EX_CHAVE_ESTRANGEIRA USING (
        'vef_emp_tmovprosaiimpori',
        NEW.BDCODEMP || ',' || NEW.BDCHAVE,
        'BDCODEMP,BDCHAVE',
        'VEF_EMP_TMOVSAI'
      );
    END
  END
  if ((NEW.BDCODPROD IS NOT NULL) AND (NEW.BDCODPROD is distinct from OLD.BDCODPROD) and (not exists(SELECT FIRST 1 A.BDCODPROD FROM TCADPRO A WHERE A.BDCODPROD = NEW.BDCODPROD))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVPROSAIIMPORI', NEW.BDCODPROD, 'BDCODPROD', 'TCADPRO');
  if ((NEW.BDCODCSTCOF IS NOT NULL) AND (NEW.BDCODCSTCOF is distinct from OLD.BDCODCSTCOF) and (not exists(SELECT FIRST 1 A.BDCODCSTCOF FROM VEF_BASE_TTABCSTCOF A WHERE A.BDCODCSTCOF = NEW.BDCODCSTCOF))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVPROSAIIMPORI', NEW.BDCODCSTCOF, 'BDCODCSTCOF', 'VEF_BASE_TTABCSTCOF');
  if ((NEW.BDCODCSTICMS IS NOT NULL) AND (NEW.BDCODCSTICMS is distinct from OLD.BDCODCSTICMS) and (not exists(SELECT FIRST 1 A.BDCODCSTICMS FROM VEF_BASE_TTABCSTICMS A WHERE A.BDCODCSTICMS = NEW.BDCODCSTICMS))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVPROSAIIMPORI', NEW.BDCODCSTICMS, 'BDCODCSTICMS', 'VEF_BASE_TTABCSTICMS');
  if ((NEW.BDCODCSTIPI IS NOT NULL) AND (NEW.BDCODCSTIPI is distinct from OLD.BDCODCSTIPI) and (not exists(SELECT FIRST 1 A.BDCODCSTIPI FROM VEF_BASE_TTABCSTIPI A WHERE A.BDCODCSTIPI = NEW.BDCODCSTIPI))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVPROSAIIMPORI', NEW.BDCODCSTIPI, 'BDCODCSTIPI', 'VEF_BASE_TTABCSTIPI');
  if ((NEW.BDCODUNIMED IS NOT NULL) AND (NEW.BDCODUNIMED is distinct from OLD.BDCODUNIMED) and (not exists(SELECT FIRST 1 A.BDCODUNIMED FROM TUNIDADEMEDIDA A WHERE A.BDCODUNIMED = NEW.BDCODUNIMED))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVPROSAIIMPORI', NEW.BDCODUNIMED, 'BDCODUNIMED', 'TUNIDADEMEDIDA');
  if ((NEW.BDNCMPROD IS NOT NULL) AND (NEW.BDNCMPROD is distinct from OLD.BDNCMPROD) and (not exists(SELECT FIRST 1 A.BDNCMPROD FROM TNCM A WHERE A.BDNCMPROD = NEW.BDNCMPROD))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVPROSAIIMPORI', NEW.BDNCMPROD, 'BDNCMPROD', 'TNCM');
  if ((NEW.BDCODCSTPIS IS NOT NULL) AND (NEW.BDCODCSTPIS is distinct from OLD.BDCODCSTPIS) and (not exists(SELECT FIRST 1 A.BDCODCSTPIS FROM VEF_BASE_TTABCSTPIS A WHERE A.BDCODCSTPIS = NEW.BDCODCSTPIS))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVPROSAIIMPORI', NEW.BDCODCSTPIS, 'BDCODCSTPIS', 'VEF_BASE_TTABCSTPIS');
  end
end^ 

CREATE OR ALTER trigger vef_emp_tmovsaipar_bu0 for vef_emp_tmovsaipar
active before insert or update position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    if ((NEW.BDCODIGOPLA IS NOT NULL) AND (NEW.BDCODIGOPLA is distinct from OLD.BDCODIGOPLA) and (not exists(SELECT FIRST 1 A.BDCODIGOPLA FROM TPLANO_PAGAMENTO A WHERE A.BDCODIGOPLA = NEW.BDCODIGOPLA))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSAIPAR', NEW.BDCODIGOPLA, 'BDCODIGOPLA', 'TPLANO_PAGAMENTO');
  end
end^

CREATE OR ALTER trigger vef_emp_tc195sai_bu0 for vef_emp_tc195sai
active before insert or update position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    if ((NEW.BDCODTIPO IS NOT NULL) AND (NEW.BDCODTIPO is distinct from OLD.BDCODTIPO) and (not exists(SELECT FIRST 1 A.BDCODTIPO FROM TIPOS_LANCAMENTOS_PADRAO A WHERE A.BDCODTIPO = NEW.BDCODTIPO))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TC195SAI', NEW.BDCODTIPO, 'BDCODTIPO', 'TIPOS_LANCAMENTOS_PADRAO');
    if ((NEW.BDCODOBS IS NOT NULL) AND (NEW.BDCODOBS is distinct from OLD.BDCODOBS) and (not exists(SELECT FIRST 1 A.BDCODOBS FROM VEF_BASE_TOBSERVACAO A WHERE A.BDCODOBS = NEW.BDCODOBS))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TC195SAI', NEW.BDCODOBS, 'BDCODOBS', 'VEF_BASE_TOBSERVACAO');
  end
end^

CREATE OR ALTER trigger vef_base_ttabinfrete_bd0 for vef_base_ttabinfrete
active before delete position 0
AS
begin
    IF (EXISTS(SELECT FIRST 1 bdcodemp FROM VEF_EMP_TC100SAI WHERE BDINDFRETE = OLD.BDORDEMFRETE)) THEN
    EXCEPTION EX_DELETE 'VEF_EMP_TC100SAI';
end^

CREATE OR ALTER trigger tcadpro_bd0 for tcadpro
active before delete position 0
AS
begin
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TC197SAI SAI
             WHERE (SAI.BDCODPROD = OLD.BDCODPROD))) then
    EXCEPTION ex_delete 'VEF_EMP_TC197SAI';
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVPROSAI SAI
             WHERE (SAI.BDCODPROD = OLD.BDCODPROD))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVPROSAI';
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVPROSAIIMPORI SAI
             WHERE (SAI.BDCODPROD = OLD.BDCODPROD))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVPROSAIIMPORI';
end^

CREATE OR ALTER trigger tempresas_scp_bd0 for tempresas_scp
active before delete position 0
as
begin
  IF (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVSAIITENS SAI
             WHERE (SAI.BDCODEMP = OLD.BDCODEMP AND
                   SAI.BDREFSOC = OLD.BDREFEMP AND
                   SAI.BDCODSCP = OLD.BDCODSCP))) THEN
    EXCEPTION EX_DELETE 'VEF_EMP_TMOVSAIITENS';
end^

CREATE OR ALTER trigger tplano_pagamento_bd0 for tplano_pagamento
active before delete position 0
as
begin
  IF (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVSAIPAR SAI
             WHERE (SAI.BDCODIGOPLA = OLD.BDCODIGOPLA))) THEN
    EXCEPTION EX_DELETE 'VEF_EMP_TMOVSAIPAR';
end^

CREATE OR ALTER trigger vef_base_ttabcta_bd0 for vef_base_ttabcta
active before delete position 0
AS
begin
  IF (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVPROSAI SAI
             WHERE (SAI.BDCODCTA = OLD.BDCODCTA))) THEN
    EXCEPTION EX_DELETE 'VEF_EMP_TMOVPROSAI';
end^

CREATE OR ALTER trigger tunidademedida_bd0 for tunidademedida
active before delete position 0
AS
begin
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVPROSAIIMPORI SAI
             WHERE (SAI.BDCODUNIMED = OLD.BDCODUNIMED))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVPROSAIIMPORI';
end^

CREATE OR ALTER trigger tncm_bd0 for tncm
active before delete position 0
AS
begin
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVPROSAIIMPORI SAI
             WHERE (SAI.BDNCMPROD = OLD.BDNCMPROD))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVPROSAIIMPORI';
end^

CREATE OR ALTER trigger tterceiro_bd0 for tterceiro
active before delete position 0
AS
begin
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVSAI SAI
             WHERE (SAI.BDCODTER = OLD.BDCODTER))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVSAI';
end^

CREATE OR ALTER trigger vef_base_tequipasat_bd0 for vef_base_tequipasat
active before delete position 0
AS
begin
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVSAI SAI
             WHERE (SAI.BDCODEMP = OLD.BDCODEMP and sai.BDCODEQUIPSAT = old.bdcodequipsat))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVSAI';
end
^

CREATE OR ALTER trigger vef_emp_tcadempreendimento_bd0 for vef_emp_tcadempreendimento
active before delete position 0
AS
begin
  if (EXISTS(SELECT FIRST 1 SAI.BDCODEMP
             FROM VEF_EMP_TMOVSAI SAI
             WHERE (SAI.BDCODEMP = OLD.BDCODEMP AND sai.bdcodempreendimento = old.bdcodempreendimento))) then
    EXCEPTION ex_delete 'VEF_EMP_TMOVSAI';
end
^

CREATE OR ALTER trigger vef_emp_tc100sai_bu0 for vef_emp_tc100sai
active before insert or update position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
    if ((NEW.BDINDFRETE IS NOT NULL) AND (NEW.BDINDFRETE is distinct from OLD.BDINDFRETE) and (not exists(SELECT FIRST 1 A.BDORDEMFRETE FROM VEF_BASE_TTABINFRETE A WHERE A.BDORDEMFRETE = NEW.BDINDFRETE))) then
      EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TC100SAI', NEW.BDINDFRETE, 'BDINDFRETE', 'VEF_BASE_TTABINFRETE');
  end
end
^

CREATE OR ALTER TRIGGER tol_vef_emp_tapue250_ad0 for tol_vef_emp_tapue250
active after delete position 0
AS
begin
  DELETE FROM VEF_EMP_TAJUICMSSTE250 aju where aju.bdcodemp = old.bdcodemp and aju.bdordeme116250 = old.bdordeme250;
end^

/* Restore proc. body: SP_VRHF_RETORNA_TOMADOR */
create or alter procedure SP_VRHF_RETORNA_TOMADOR (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRREF integer,
    PRDATAINICIAL date = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDREFTOMADOR integer,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
declare variable WSQL varchar(32700);
declare variable WCTALON varchar(20);
declare variable WTIPO integer;
declare variable WP integer;
declare variable WCODTPCC integer;
begin
  wsql = 'select FT.BDCODEMP, FT.BDCODCOL, FT.BDORDEM, FT.BDREFTOMADOR, PFN.BDCODCENTRO, PFN.BDCODTPCC '||
         'from VRHF_EMP_TFOLHATOMADOR FT '||
         'join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FT.BDCODEMP and PFN.BDCODCOL = FT.BDCODCOL and PFN.BDORDEM = FT.BDORDEM) '||
         'where PFN.BDCODCENTRO is not null and PFN.BDCODTPCC is not null ';

  if (coalesce(premp, '') <> '') then
     begin
       premp = upper(premp);

       wsql = wsql||' and '||replace(premp, 'BDCODEMP', 'FT.BDCODEMP');

       if (coalesce(prcol, '') <> '') then
          begin
            prcol = upper(prcol);
            wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FT.BDCODCOL');
          end

       if (coalesce(prref, 0) > 0) then
          wsql = wsql||' and FT.BDREFTOMADOR = '||prref;
     end
  else
  if (coalesce(prref, 0) > 0) then
     wsql = wsql||' and FT.BDREFTOMADOR = '||prref;


  if (prdatainicial is not null) then
     wsql = wsql||' and FT.BDREFTOMADOR >= '||substring(cast(prdatainicial as varchar(10)) from 1 for 4)||substring(cast(prdatainicial as varchar(10)) from 6 for 2);

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDORDEM, :BDREFTOMADOR, :BDCODCENTRO, :BDCODTPCC do
    begin
      wctalon = null;
      wtipo   = null;
      select first 1 BDCTALON, BDTIPO from CENTROS_TPCC where BDCODCENTRO = :bdcodcentro and BDCODTPCC = :bdcodtpcc into :wctalon, :wtipo;

      -- Não é tomador. Buscar pela classificação
      if (coalesce(wtipo, 0) = 0) then
         begin
           while (coalesce(wtipo,  0) = 0 and coalesce(wctalon, '') <> '') do
             begin
               wctalon = reverse(wctalon);
               wp = position('.', :wctalon);

               if (wp > 0) then
                  begin
                    wctalon = substring(:wctalon from (:wp + 1) for strlen(:wctalon));
                    wctalon = reverse(wctalon);
                    wcodtpcc = null;
                    wtipo = null;
                    select first 1 BDCODTPCC, BDTIPO from CENTROS_TPCC where BDCODCENTRO = :bdcodcentro and BDCTALON = :wctalon into :wcodtpcc, :wtipo;

                    if (coalesce(wcodtpcc, 0) > 0 and coalesce(wtipo, 0) > 0) then
                       begin
                         BDCODTPCC = wcodtpcc;
                         wctalon = '';
                       end
                  end
               else
                  begin
                    wctalon = '';
                    wtipo = 1;
                  end
             end
         end

      suspend;
    end
end^

/* Restore proc. body: SP_VRHF_RETORNA_TOMADOR_AUT */
create or alter procedure SP_VRHF_RETORNA_TOMADOR_AUT (
    PREMP varchar(15000),
    PRAUT varchar(32000),
    PRREF integer,
    PRDATAINICIAL date = null)
returns (
    BDCODEMP integer,
    BDCODTER integer,
    BDCODSERV integer,
    BDREF integer,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
declare variable WSQL varchar(32700);
declare variable WCTALON varchar(20);
declare variable WTIPO integer;
declare variable WP integer;
declare variable WCODTPCC integer;
begin
  wsql = 'select FT.BDCODEMP, FT.BDCODTER, PFN.BDCODSERV, PFN.BDREFSERV, PFN.BDCODCENTRO, PFN.BDCODTPCC '||
         'from vrh_base_tservterc PFN '||
         'join vrhf_base_calc_terc FT on (FT.BDCODEMP = PFN.BDCODEMP and FT.BDCODTER = PFN.BDCODTER and FT.BDCODSERV = PFN.BDCODSERV) '||
         'where PFN.BDCODCENTRO is not null and PFN.BDCODTPCC is not null ';

  if (coalesce(premp, '') <> '') then
     begin
       premp = upper(premp);

       wsql = wsql||' and '||replace(premp, 'BDCODEMP', 'PFN.BDCODEMP');

       if (coalesce(praut, '') <> '') then
          begin
            praut = upper(praut);
            wsql = wsql||' and '||replace(praut, 'BDCODTER', 'PFN.BDCODTER');
          end

       if (coalesce(prref, 0) > 0) then
          wsql = wsql||' and PFN.BDREFSERV = '||prref;
     end
  else
  if (coalesce(prref, 0) > 0) then
     wsql = wsql||' and PFN.BDREFSERV = '||prref;

  if (prdatainicial is not null) then
     wsql = wsql||' and PFN.BDDATASERV >= '''||prdatainicial||''' ';

  for execute statement wsql into :BDCODEMP, :BDCODTER, :BDCODSERV, :BDREF, :BDCODCENTRO, :BDCODTPCC do
    begin
      wctalon = null;
      wtipo   = null;
      select first 1 BDCTALON, BDTIPO from CENTROS_TPCC where BDCODCENTRO = :bdcodcentro and BDCODTPCC = :bdcodtpcc into :wctalon, :wtipo;

      -- Não é tomador. Buscar pela classificação
      if (coalesce(wtipo, 0) = 0) then
         begin
           while (coalesce(wtipo,  0) = 0 and coalesce(wctalon, '') <> '') do
             begin
               wctalon = reverse(wctalon);
               wp = position('.', :wctalon);

               if (wp > 0) then
                  begin
                    wctalon = substring(:wctalon from (:wp + 1) for strlen(:wctalon));
                    wctalon = reverse(wctalon);
                    wcodtpcc = null;
                    wtipo = null;
                    select first 1 BDCODTPCC, BDTIPO from CENTROS_TPCC where BDCODCENTRO = :bdcodcentro and BDCTALON = :wctalon into :wcodtpcc, :wtipo;

                    if (coalesce(wcodtpcc, 0) > 0 and coalesce(wtipo, 0) > 0) then
                       begin
                         BDCODTPCC = wcodtpcc;
                         wctalon = '';
                       end
                  end
               else
                  begin
                    wctalon = '';
                    wtipo = 1;
                  end
             end
         end

      suspend;
    end
end^

/* Restore proc. body: SP_VRHF_RETORNA_TOMADOR_13 */
create or alter procedure SP_VRHF_RETORNA_TOMADOR_13 (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRREF integer,
    PRDATAINICIAL date = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF13 integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
declare variable WSQL varchar(32700);
declare variable WCTALON varchar(20);
declare variable WTIPO integer;
declare variable WP integer;
declare variable WCODTPCC integer;
begin
  wsql = 'select FT.BDCODEMP, FT.BDCODCOL, FT.BDREF13, FT.BDORDEM, PFN.BDCODCENTRO, PFN.BDCODTPCC '||
         'from VRHF_EMP_T13SAL FT '||
         'join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FT.BDCODEMP and PFN.BDCODCOL = FT.BDCODCOL and PFN.BDORDEM = FT.BDORDEM) '||
         'where PFN.BDCODCENTRO is not null and PFN.BDCODTPCC is not null ';

  if (coalesce(premp, '') <> '') then
     begin
       premp = upper(premp);

       wsql = wsql||' and '||replace(premp, 'BDCODEMP', 'FT.BDCODEMP');

       if (coalesce(prcol, '') <> '') then
          begin
            prcol = upper(prcol);
            wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FT.BDCODCOL');
          end

       if (coalesce(prref, 0) > 0) then
          wsql = wsql||' and FT.BDREF13 = '||prref;
     end
  else
  if (coalesce(prref, 0) > 0) then
     wsql = wsql||' and FT.BDREF13 = '||prref;

  if (prdatainicial is not null) then
     wsql = wsql||' and FT.BDREF13 >= '||substring(cast(prdatainicial as varchar(10)) from 1 for 4)||substring(cast(prdatainicial as varchar(10)) from 6 for 2);

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDREF13, :BDORDEM, :BDCODCENTRO, :BDCODTPCC do
    begin
      wctalon = null;
      wtipo   = null;
      select first 1 BDCTALON, BDTIPO from CENTROS_TPCC where BDCODCENTRO = :bdcodcentro and BDCODTPCC = :bdcodtpcc into :wctalon, :wtipo;

      -- Não é tomador. Buscar pela classificação
      if (coalesce(wtipo, 0) = 0) then
         begin
           while (coalesce(wtipo,  0) = 0 and coalesce(wctalon, '') <> '') do
             begin
               wctalon = reverse(wctalon);
               wp = position('.', :wctalon);

               if (wp > 0) then
                  begin
                    wctalon = substring(:wctalon from (:wp + 1) for strlen(:wctalon));
                    wctalon = reverse(wctalon);
                    wcodtpcc = null;
                    wtipo = null;
                    select first 1 BDCODTPCC, BDTIPO from CENTROS_TPCC where BDCODCENTRO = :bdcodcentro and BDCTALON = :wctalon into :wcodtpcc, :wtipo;

                    if (coalesce(wcodtpcc, 0) > 0 and coalesce(wtipo, 0) > 0) then
                       begin
                         BDCODTPCC = wcodtpcc;
                         wctalon = '';
                       end
                  end
               else
                  begin
                    wctalon = '';
                    wtipo = 1;
                  end
             end
         end

      suspend;
    end
end^

/* Restore proc. body: SP_VRHF_RETORNA_TOMADOR_INT */
create or alter procedure SP_VRHF_RETORNA_TOMADOR_INT (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRREF integer,
    PRDATAINICIAL date = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODCONTTI integer,
    BDORDEM integer,
    BDREFTOMADOR integer,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
declare variable WSQL varchar(32700);
declare variable WCTALON varchar(20);
declare variable WTIPO integer;
declare variable WP integer;
declare variable WCODTPCC integer;
begin
  wsql = 'select FT.BDCODEMP, FT.BDCODCOL, FT.BDCODCONTTI, FT.BDORDEM, FT.BDREFTOMADOR, PFN.BDCODCENTRO, PFN.BDCODTPCC '||
         'from VRHF_EMP_TFOLHATOMINT FT '||
         'join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FT.BDCODEMP and PFN.BDCODCOL = FT.BDCODCOL and PFN.BDORDEM = FT.BDORDEM) '||
         'where PFN.BDCODCENTRO is not null and PFN.BDCODTPCC is not null ';

  if (coalesce(premp, '') <> '') then
     begin
       premp = upper(premp);

       wsql = wsql||' and '||replace(premp, 'BDCODEMP', 'FT.BDCODEMP');

       if (coalesce(prcol, '') <> '') then
          begin
            prcol = upper(prcol);
            wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FT.BDCODCOL');
          end

       if (coalesce(prref, 0) > 0) then
          wsql = wsql||' and FT.BDREFTOMADOR = '||prref;
     end
  else
  if (coalesce(prref, 0) > 0) then
     wsql = wsql||' and FT.BDREFTOMADOR = '||prref;

  if (prdatainicial is not null) then
     wsql = wsql||' and FT.BDREFTOMADOR >= '||substring(cast(prdatainicial as varchar(10)) from 1 for 4)||substring(cast(prdatainicial as varchar(10)) from 6 for 2);

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDCODCONTTI, :BDORDEM, :BDREFTOMADOR, :BDCODCENTRO, :BDCODTPCC do
    begin
      wctalon = null;
      wtipo   = null;
      select first 1 BDCTALON, BDTIPO from CENTROS_TPCC where BDCODCENTRO = :bdcodcentro and BDCODTPCC = :bdcodtpcc into :wctalon, :wtipo;

      -- Não é tomador. Buscar pela classificação
      if (coalesce(wtipo, 0) = 0) then
         begin
           while (coalesce(wtipo,  0) = 0 and coalesce(wctalon, '') <> '') do
             begin
               wctalon = reverse(wctalon);
               wp = position('.', :wctalon);

               if (wp > 0) then
                  begin
                    wctalon = substring(:wctalon from (:wp + 1) for strlen(:wctalon));
                    wctalon = reverse(wctalon);
                    wcodtpcc = null;
                    wtipo = null;
                    select first 1 BDCODTPCC, BDTIPO from CENTROS_TPCC where BDCODCENTRO = :bdcodcentro and BDCTALON = :wctalon into :wcodtpcc, :wtipo;

                    if (coalesce(wcodtpcc, 0) > 0 and coalesce(wtipo, 0) > 0) then
                       begin
                         BDCODTPCC = wcodtpcc;
                         wctalon = '';
                       end
                  end
               else
                  begin
                    wctalon = '';
                    wtipo = 1;
                  end
             end
         end

      suspend;
    end
end^

/* Restore proc. body: SP_VRHF_RETORNA_TOMADOR_A13 */
create or alter procedure SP_VRHF_RETORNA_TOMADOR_A13 (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRREF integer,
    PRDATAINICIAL date = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFA13 integer,
    BDORDEM integer,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
declare variable WSQL varchar(32700);
declare variable WCTALON varchar(20);
declare variable WTIPO integer;
declare variable WP integer;
declare variable WCODTPCC integer;
begin
  wsql = 'select FT.BDCODEMP, FT.BDCODCOL, FT.BDREFA13, FT.BDORDEM, PFN.BDCODCENTRO, PFN.BDCODTPCC '||
         'from VRHF_EMP_TA13SAL FT '||
         'join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FT.BDCODEMP and PFN.BDCODCOL = FT.BDCODCOL and PFN.BDORDEM = FT.BDORDEM) '||
         'where PFN.BDCODCENTRO is not null and PFN.BDCODTPCC is not null ';

  if (coalesce(premp, '') <> '') then
     begin
       premp = upper(premp);

       wsql = wsql||' and '||replace(premp, 'BDCODEMP', 'FT.BDCODEMP');

       if (coalesce(prcol, '') <> '') then
          begin
            prcol = upper(prcol);
            wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FT.BDCODCOL');
          end

       if (coalesce(prref, 0) > 0) then
          wsql = wsql||' and FT.BDREFA13 = '||prref;
     end
  else
  if (coalesce(prref, 0) > 0) then
     wsql = wsql||' and FT.BDREFA13 = '||prref;

  if (prdatainicial is not null) then
     wsql = wsql||' and FT.BDREFA13 >= '||substring(cast(prdatainicial as varchar(10)) from 1 for 4)||substring(cast(prdatainicial as varchar(10)) from 6 for 2);

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDREFA13, :BDORDEM, :BDCODCENTRO, :BDCODTPCC do
    begin
      wctalon = null;
      wtipo   = null;
      select first 1 BDCTALON, BDTIPO from CENTROS_TPCC where BDCODCENTRO = :bdcodcentro and BDCODTPCC = :bdcodtpcc into :wctalon, :wtipo;

      -- Não é tomador. Buscar pela classificação
      if (coalesce(wtipo, 0) = 0) then
         begin
           while (coalesce(wtipo,  0) = 0 and coalesce(wctalon, '') <> '') do
             begin
               wctalon = reverse(wctalon);
               wp = position('.', :wctalon);

               if (wp > 0) then
                  begin
                    wctalon = substring(:wctalon from (:wp + 1) for strlen(:wctalon));
                    wctalon = reverse(wctalon);
                    wcodtpcc = null;
                    wtipo = null;
                    select first 1 BDCODTPCC, BDTIPO from CENTROS_TPCC where BDCODCENTRO = :bdcodcentro and BDCTALON = :wctalon into :wcodtpcc, :wtipo;

                    if (coalesce(wcodtpcc, 0) > 0 and coalesce(wtipo, 0) > 0) then
                       begin
                         BDCODTPCC = wcodtpcc;
                         wctalon = '';
                       end
                  end
               else
                  begin
                    wctalon = '';
                    wtipo = 1;
                  end
             end
         end

      suspend;
    end
end^

/* Restore proc. body: SP_VRHF_RETORNA_TOMADOR_FA */
create or alter procedure SP_VRHF_RETORNA_TOMADOR_FA (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRREF integer,
    PRDATAINICIAL date = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDCODTCA integer,
    BDDATAFA date,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
declare variable WSQL varchar(32700);
declare variable WCTALON varchar(20);
declare variable WTIPO integer;
declare variable WP integer;
declare variable WCODTPCC integer;
begin
  wsql = 'select FT.BDCODEMP, FT.BDCODCOL, FT.BDORDEM, FT.BDCODTCA, FT.BDDATAFA, PFN.BDCODCENTRO, PFN.BDCODTPCC '||
         'from VRHF_EMP_TFOLHAAVULSA FT '||
         'join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FT.BDCODEMP and PFN.BDCODCOL = FT.BDCODCOL and PFN.BDORDEM = FT.BDORDEM) '||
         'where PFN.BDCODCENTRO is not null and PFN.BDCODTPCC is not null ';

  if (coalesce(premp, '') <> '') then
     begin
       premp = upper(premp);

       wsql = wsql||' and '||replace(premp, 'BDCODEMP', 'FT.BDCODEMP');

       if (coalesce(prcol, '') <> '') then
          begin
            prcol = upper(prcol);
            wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FT.BDCODCOL');
          end

       if (coalesce(prref, 0) > 0) then
          wsql = wsql||' and FT.BDREF = '||prref;
     end
  else
  if (coalesce(prref, 0) > 0) then
     wsql = wsql||' and FT.BDREF = '||prref;


  if (prdatainicial is not null) then
     wsql = wsql||' and FT.BDDATAFA >= '''||prdatainicial||''' ';

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDORDEM, :BDCODTCA, :BDDATAFA, :BDCODCENTRO, :BDCODTPCC do
    begin
      wctalon = null;
      wtipo   = null;
      select first 1 BDCTALON, BDTIPO from CENTROS_TPCC where BDCODCENTRO = :bdcodcentro and BDCODTPCC = :bdcodtpcc into :wctalon, :wtipo;

      -- Não é tomador. Buscar pela classificação
      if (coalesce(wtipo, 0) = 0) then
         begin
           while (coalesce(wtipo,  0) = 0 and coalesce(wctalon, '') <> '') do
             begin
               wctalon = reverse(wctalon);
               wp = position('.', :wctalon);

               if (wp > 0) then
                  begin
                    wctalon = substring(:wctalon from (:wp + 1) for strlen(:wctalon));
                    wctalon = reverse(wctalon);
                    wcodtpcc = null;
                    wtipo = null;
                    select first 1 BDCODTPCC, BDTIPO from CENTROS_TPCC where BDCODCENTRO = :bdcodcentro and BDCTALON = :wctalon into :wcodtpcc, :wtipo;

                    if (coalesce(wcodtpcc, 0) > 0 and coalesce(wtipo, 0) > 0) then
                       begin
                         BDCODTPCC = wcodtpcc;
                         wctalon = '';
                       end
                  end
               else
                  begin
                    wctalon = '';
                    wtipo = 1;
                  end
             end
         end

      suspend;
    end
end^

/* Restore proc. body: SP_VRHF_RETORNA_TOMADOR_FER */
create or alter procedure SP_VRHF_RETORNA_TOMADOR_FER (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRREF integer,
    PRDATAINICIAL date = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
declare variable WSQL varchar(32700);
declare variable WCTALON varchar(20);
declare variable WTIPO integer;
declare variable WP integer;
declare variable WCODTPCC integer;
begin
  wsql = 'select FT.BDCODEMP, FT.BDCODCOL, FT.BDORDEM, FT.BDINIPERAQUISFE, FT.BDCODFE, PFN.BDCODCENTRO, PFN.BDCODTPCC '||
         'from VRH_EMP_TFERIAS FT '||
         'join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FT.BDCODEMP and PFN.BDCODCOL = FT.BDCODCOL and PFN.BDORDEM = FT.BDORDEM) '||
         'where PFN.BDCODCENTRO is not null and PFN.BDCODTPCC is not null ';

  if (coalesce(premp, '') <> '') then
     begin
       premp = upper(premp);

       wsql = wsql||' and '||replace(premp, 'BDCODEMP', 'FT.BDCODEMP');

       if (coalesce(prcol, '') <> '') then
          begin
            prcol = upper(prcol);
            wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FT.BDCODCOL');
          end

       if (coalesce(prref, 0) > 0) then
          wsql = wsql||' and FT.BDREFFIMFE <= '||prref||' and FT.BDREFINIFE >= '||prref;
     end
  else
  if (coalesce(prref, 0) > 0) then
     wsql = wsql||' and FT.BDREFFIMFE <= '||prref||' and FT.BDREFINIFE >= '||prref;


  if (prdatainicial is not null) then
     wsql = wsql||' and FT.BDDATAPAGFE >= '''||prdatainicial||''' ';

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDORDEM, :BDINIPERAQUISFE, :BDCODFE, :BDCODCENTRO, :BDCODTPCC do
    begin
      wctalon = null;
      wtipo   = null;
      select first 1 BDCTALON, BDTIPO from CENTROS_TPCC where BDCODCENTRO = :bdcodcentro and BDCODTPCC = :bdcodtpcc into :wctalon, :wtipo;

      -- Não é tomador. Buscar pela classificação
      if (coalesce(wtipo, 0) = 0) then
         begin
           while (coalesce(wtipo,  0) = 0 and coalesce(wctalon, '') <> '') do
             begin
               wctalon = reverse(wctalon);
               wp = position('.', :wctalon);

               if (wp > 0) then
                  begin
                    wctalon = substring(:wctalon from (:wp + 1) for strlen(:wctalon));
                    wctalon = reverse(wctalon);
                    wcodtpcc = null;
                    wtipo = null;
                    select first 1 BDCODTPCC, BDTIPO from CENTROS_TPCC where BDCODCENTRO = :bdcodcentro and BDCTALON = :wctalon into :wcodtpcc, :wtipo;

                    if (coalesce(wcodtpcc, 0) > 0 and coalesce(wtipo, 0) > 0) then
                       begin
                         BDCODTPCC = wcodtpcc;
                         wctalon = '';
                       end
                  end
               else
                  begin
                    wctalon = '';
                    wtipo = 1;
                  end
             end
         end

      suspend;
    end
end^

/* Restore proc. body: SP_VRHF_RETORNA_TOMADOR_AD */
create or alter procedure SP_VRHF_RETORNA_TOMADOR_AD (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRREF integer,
    PRDATAINICIAL date = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDDATAAD date,
    BDCODCENTRO integer,
    BDCODTPCC integer)
as
declare variable WSQL varchar(32700);
declare variable WCTALON varchar(20);
declare variable WTIPO integer;
declare variable WP integer;
declare variable WCODTPCC integer;
begin
  wsql = 'select FT.BDCODEMP, FT.BDCODCOL, FT.BDORDEM, FT.BDDATAAD, PFN.BDCODCENTRO, PFN.BDCODTPCC '||
         'from VRHF_EMP_TADSAL FT '||
         'join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FT.BDCODEMP and PFN.BDCODCOL = FT.BDCODCOL and PFN.BDORDEM = FT.BDORDEM) '||
         'where PFN.BDCODCENTRO is not null and PFN.BDCODTPCC is not null ';

  if (coalesce(premp, '') <> '') then
     begin
       premp = upper(premp);

       wsql = wsql||' and '||replace(premp, 'BDCODEMP', 'FT.BDCODEMP');

       if (coalesce(prcol, '') <> '') then
          begin
            prcol = upper(prcol);
            wsql = wsql||' and '||replace(prcol, 'BDCODCOL', 'FT.BDCODCOL');
          end

       if (coalesce(prref, 0) > 0) then
          wsql = wsql||' and FT.BDREFAD = '||prref||' ';
     end
  else
  if (coalesce(prref, 0) > 0) then
     wsql = wsql||' and FT.BDREFAD = '||prref||' ';


  if (prdatainicial is not null) then
     wsql = wsql||' and FT.BDDATAAD >= '''||prdatainicial||''' ';

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDORDEM, :BDDATAAD, :BDCODCENTRO, :BDCODTPCC do
    begin
      wctalon = null;
      wtipo   = null;
      select first 1 BDCTALON, BDTIPO from CENTROS_TPCC where BDCODCENTRO = :bdcodcentro and BDCODTPCC = :bdcodtpcc into :wctalon, :wtipo;

      -- Não é tomador. Buscar pela classificação
      if (coalesce(wtipo, 0) = 0) then
         begin
           while (coalesce(wtipo,  0) = 0 and coalesce(wctalon, '') <> '') do
             begin
               wctalon = reverse(wctalon);
               wp = position('.', :wctalon);

               if (wp > 0) then
                  begin
                    wctalon = substring(:wctalon from (:wp + 1) for strlen(:wctalon));
                    wctalon = reverse(wctalon);
                    wcodtpcc = null;
                    wtipo = null;
                    select first 1 BDCODTPCC, BDTIPO from CENTROS_TPCC where BDCODCENTRO = :bdcodcentro and BDCTALON = :wctalon into :wcodtpcc, :wtipo;

                    if (coalesce(wcodtpcc, 0) > 0 and coalesce(wtipo, 0) > 0) then
                       begin
                         BDCODTPCC = wcodtpcc;
                         wctalon = '';
                       end
                  end
               else
                  begin
                    wctalon = '';
                    wtipo = 1;
                  end
             end
         end

      suspend;
    end
end^

CREATE OR ALTER PROCEDURE SP_VEF_TREEVIEW_CONS_GIAST (
    PRCODEMP VARCHAR(10000),
    PRANOMESINICIAL INTEGER,
    PRANOMESFINAL INTEGER,
    PRCODPERIODO VARCHAR(1000),
    PRCODQUADRO INTEGER,
    PRUF INTEGER)
RETURNS (
    BDCODTIPO INTEGER,
    BDSIGLAUF VARCHAR(2),
    BDCODUF INTEGER,
    BDCLASSIFICACAO VARCHAR(10),
    BDNUMITEM INTEGER,
    BDVALOR NUMERIC(18,6),
    BDDESCQGIAST VARCHAR(150),
    BDCODQUADRO INTEGER,
    BDCODPERIODO INTEGER,
    BDREFERENCIA INTEGER,
    BDCODCONFGIAST INTEGER,
    BDNOMEMP DM_BDNOMEMP,
    BDCODEMP INTEGER,
    BDDESCFORM VARCHAR(150),
    BDNUMCAMPO INTEGER)
AS
DECLARE VARIABLE PRQUADROANT INTEGER;
DECLARE VARIABLE PRNUMCAMPO INTEGER;
DECLARE VARIABLE WVALOR NUMERIC(18,6);
DECLARE VARIABLE PRDESCFORM VARCHAR(150);
DECLARE VARIABLE WUFANT INTEGER;
DECLARE VARIABLE WREFANT INTEGER;
DECLARE VARIABLE WWHERE VARCHAR(32700);
DECLARE VARIABLE WSQL VARCHAR(32700);
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRANOMESFINAL, NULL, NULL);

  wSQL =         ' SELECT BDCODEMP, BDNOMEMP, BDCODCONFGIAST, BDREFERENCIA, BDCODPERIODO, BDNUMCAMPO, ';
  wSQL = wSQL || '        BDCODQUADRO, BDDESCQGIAST, BDDESCFORM, BDVALOR, ';
  wSQL = wSQL || '        BDNUMITEM, BDCLASSIFICACAO, BDCODUF, BDSIGLAUF, BDCODTIPO ';
  wSQL = wSQL || ' FROM( ';
  wSQL = wSQL || '       SELECT GERREG.BDCODEMP,  ';
  wSQL = wSQL || '       EMP.BDNOMEMP,            ';
  wSQL = wSQL || '       EMPRESAS.BDCODCONFGIAST, ';
  wSQL = wSQL || '       GERREG.BDREFERENCIA,     ';
  wSQL = wSQL || '       GERREG.BDCODPERIODO,     ';
  wSQL = wSQL || '       GERREG.BDNUMCAMPO,       ';
  wSQL = wSQL || '       GERREG.BDCODQUADRO,      ';
  wSQL = wSQL || '       TCONFQ.BDDESCQGIAST,     ';
  wSQL = wSQL || '       TCONFFORM.BDDESCFORM,    ';
  wSQL = wSQL || '       GERREG.BDVALOR,          ';
  wSQL = wSQL || '       TCONFFORM.BDNUMITEM,     ';
  wSQL = wSQL || '       TCONFQ.BDCLASSIFICACAO,  ';
  wSQL = wSQL || '       GERREG.BDCODUF,          ';
  wSQL = wSQL || '       UF.BDSIGLAUF,            ';
  wSQL = wSQL || '       TCONFQ.BDCODTIPO         ';

  wSQL = wSQL || ' FROM VEF_EMP_TGIASTGERREG GERREG ';

  wSQL = wSQL || ' LEFT OUTER JOIN VW_VEF_BASE_TEMPPAREST EMPRESAS ON (EMPRESAS.BDCODEMP = GERREG.BDCODEMP) ';
  wSQL = wSQL || ' LEFT OUTER JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = GERREG.BDCODEMP) ' ;
  wSQL = wSQL || ' LEFT OUTER JOIN TUF UF ON (UF.BDCODUF = GERREG.BDCODUF ) ';
  wSQL = wSQL || ' LEFT OUTER JOIN VEF_BASE_TCONFGIASTQ TCONFQ ON (TCONFQ.BDCODQGIAST = GERREG.BDCODQUADRO) ';
  wSQL = wSQL || ' LEFT OUTER JOIN VEF_BASE_TCONFGIASTFORM TCONFFORM ON ( TCONFFORM.BDCODCONFGIAST = EMPRESAS.BDCODCONFGIAST AND
                                                                          TCONFFORM.BDCODQUADRO = GERREG.BDCODQUADRO AND
                                                                          TCONFFORM.BDNUMCAMPO = GERREG.BDNUMCAMPO
                                                                         ) ' ;

  wWhere = '';

  IF (:PRCODEMP IS NOT NULL) THEN
      wWhere = ' WHERE GERREG.' || :PRCODEMP;

  IF (:PRANOMESINICIAL IS NOT NULL) THEN
     BEGIN
       IF (wWhere <> '') THEN
           wWhere = wWhere || ' AND ';
       ELSE
           wWhere = wWhere || ' WHERE ';

       wWhere = wWhere || ' GERREG.BDREFERENCIA >= ' || :PRANOMESINICIAL;

       IF (wWhere <> '') THEN
           wWhere = wWhere || ' AND ';

       wWhere = wWhere || ' GERREG.BDREFERENCIA <= ' || :PRANOMESFINAL;
     END

  IF (:PRCODQUADRO IS NOT NULL) THEN
    BEGIN
       IF (wWhere <> '') THEN
           wWhere = wWhere || ' AND ';
       ELSE
          wWhere = wWhere || ' WHERE ';

       wWhere = wWhere || ' GERREG.BDCODQUADRO = ' || :PRCODQUADRO;
    END

  IF (:PRCODPERIODO IS NOT NULL) THEN
    BEGIN
       IF (wWhere <> '') THEN
           wWhere = wWhere || ' AND GERREG. ';
       ELSE
          wWhere = wWhere ||' WHERE GERREG. ';

       wWhere = wWhere || :PRCODPERIODO;
    END

  IF( (:PRUF IS NOT NULL) AND (:PRUF <> 0) ) THEN
    BEGIN
       IF (wWhere <> '') THEN
           wWhere = wWhere || ' AND ';
       ELSE
          wWhere = wWhere || ' WHERE ';

       wWhere = wWhere || ' GERREG.BDCODUF = ' || :PRUF;
    END

    wWhere = wWhere || ' ) ';
    wSQL = wSQL || wWhere || ' ORDER BY BDCODEMP, BDREFERENCIA, BDCODPERIODO, BDCODQUADRO, BDCODUF, BDNUMCAMPO ';

 --SUSPEND;

  wREFANT         = 0;
  PRQUADROANT     = 0;
  wUFANT          = 0;

  FOR EXECUTE STATEMENT wSQL
  INTO
    BDCODEMP,
    BDNOMEMP,
    BDCODCONFGIAST,
    BDREFERENCIA,
    BDCODPERIODO,
    BDNUMCAMPO,
    BDCODQUADRO,
    BDDESCQGIAST,
    BDDESCFORM,
    BDVALOR,
    BDNUMITEM,
    BDCLASSIFICACAO,
    BDCODUF,
    BDSIGLAUF,
    BDCODTIPO
  DO
  BEGIN
    PRNUMCAMPO = BDNUMCAMPO;
    PRDESCFORM = BDDESCFORM;
    wVALOR = BDVALOR;

    --REFERENCIA
    IF ((wREFANT <> BDREFERENCIA) AND (PRANOMESINICIAL <> PRANOMESFINAL)) THEN
      BEGIN
        BDNUMCAMPO = NULL;
        BDDESCFORM =  CAST(BDREFERENCIA AS VARCHAR(6));
        BDDESCFORM =  SUBSTRING(BDDESCFORM FROM 5 FOR 2)||'/'||SUBSTRING(BDDESCFORM FROM 1 FOR 4);
        BDVALOR = NULL;
        SUSPEND;
      END

    --QUADRO
    IF ((PRQUADROANT <> BDCODQUADRO)) THEN
      BEGIN
        BDNUMCAMPO = NULL;
        BDDESCFORM =  BDDESCQGIAST;
        BDVALOR = NULL;
        SUSPEND;

        --ESTADO
        IF ((BDCODUF IS NOT NULL))THEN
          BEGIN
            BDDESCFORM =  BDSIGLAUF;
            SUSPEND;
          END

      END

    --ESTADO
    IF ((wUFANT <> BDCODUF) AND (PRQUADROANT = BDCODQUADRO)) THEN
      BEGIN
        BDNUMCAMPO = NULL;
        BDDESCFORM =  BDSIGLAUF;
        BDVALOR = NULL;
        SUSPEND;
      END

    BDNUMCAMPO = PRNUMCAMPO;
    BDDESCFORM = PRDESCFORM;
    BDVALOR = wVALOR;

    wREFANT = BDREFERENCIA;
    PRQUADROANT = BDCODQUADRO;

    wUFANT  = BDCODUF;
    SUSPEND;

  END

END^

create or alter procedure SP_EXPORTA_GIAST (
    PRCODEMP integer,
    PRDATAINI integer,
    PRDATAFIM integer,
    PRARQUIVO varchar(260))
as
declare variable WANO integer;
declare variable WMES integer;
declare variable WSQL varchar(3100);
declare variable WCFOP varchar(200);
declare variable WLINHA blob sub_type 1 segment size 200 character set UTF8;
BEGIN
  DELETE FROM TEXPORTA_GIAST WHERE BDCODEMP = :PRCODEMP;
  DELETE FROM TMP_VEF_EMP_TVALCAMPOSGIAST WHERE BDCODEMP = :PRCODEMP;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRDATAFIM);

   /****************************************************************************
   * INSERINDO VALORES DOS CAMPOS DA APURAÇÃO EM UMA TABELA TMP                *
   ****************************************************************************/

    INSERT INTO TMP_VEF_EMP_TVALCAMPOSGIAST
    (
        BDCODEMP, BDCODUF, BDREFERENCIA, BDVLRCAMPO07, BDVLRCAMPO08, BDVLRCAMPO09, BDVLRCAMPO10, BDVLRCAMPO11, BDVLRCAMPO12, BDVLRCAMPO13,
        BDVLRCAMPO14, BDVLRCAMPO15, BDVLRCAMPO16, BDVLRCAMPO17, BDVLRCAMPO18, BDVLRCAMPO19, BDVLRCAMPO20, BDVLRCAMPO21, BDVLRCAMPO22,
        BDVLRCAMPO23, BDVLRCAMPO24, BDVLRCAMPO25, BDVLRCAMPO26, BDVLRCAMPO27, BDVLRCAMPO28
    )
        SELECT GERR.BDCODEMP, GERR.BDCODUF, GERR.BDREFERENCIA,
            COALESCE(SUM(CASE WHEN GERR.BDNUMCAMPO = 7  THEN GERR.BDVALOR END), 0) AS VLRCAMPO07,
            COALESCE(SUM(CASE WHEN GERR.BDNUMCAMPO = 8  THEN GERR.BDVALOR END), 0) AS VLRCAMPO08,
            COALESCE(SUM(CASE WHEN GERR.BDNUMCAMPO = 9  THEN GERR.BDVALOR END), 0) AS VLRCAMPO09,
            COALESCE(SUM(CASE WHEN GERR.BDNUMCAMPO = 10 THEN GERR.BDVALOR END), 0) AS VLRCAMPO10,
            COALESCE(SUM(CASE WHEN GERR.BDNUMCAMPO = 11 THEN GERR.BDVALOR END), 0) AS VLRCAMPO11,
            COALESCE(SUM(CASE WHEN GERR.BDNUMCAMPO = 12 THEN GERR.BDVALOR END), 0) AS VLRCAMPO12,
            COALESCE(SUM(CASE WHEN GERR.BDNUMCAMPO = 13 THEN GERR.BDVALOR END), 0) AS VLRCAMPO13,
            COALESCE(SUM(CASE WHEN GERR.BDNUMCAMPO = 14 THEN GERR.BDVALOR END), 0) AS VLRCAMPO14,
            COALESCE(SUM(CASE WHEN GERR.BDNUMCAMPO = 15 THEN GERR.BDVALOR END), 0) AS VLRCAMPO15,
            COALESCE(SUM(CASE WHEN GERR.BDNUMCAMPO = 16 THEN GERR.BDVALOR END), 0) AS VLRCAMPO16,
            COALESCE(SUM(CASE WHEN GERR.BDNUMCAMPO = 17 THEN GERR.BDVALOR END), 0) AS VLRCAMPO17,
            COALESCE(SUM(CASE WHEN GERR.BDNUMCAMPO = 18 THEN GERR.BDVALOR END), 0) AS VLRCAMPO18,
            COALESCE(SUM(CASE WHEN GERR.BDNUMCAMPO = 19 THEN GERR.BDVALOR END), 0) AS VLRCAMPO19,
            COALESCE(SUM(CASE WHEN GERR.BDNUMCAMPO = 20 THEN GERR.BDVALOR END), 0) AS VLRCAMPO20,
            COALESCE(SUM(CASE WHEN GERR.BDNUMCAMPO = 21 THEN GERR.BDVALOR END), 0) AS VLRCAMPO21,
            COALESCE(SUM(CASE WHEN GERR.BDNUMCAMPO = 22 THEN GERR.BDVALOR END), 0) AS VLRCAMPO22, -- 22 - Total do ICMS ST - FCP - 140709-EC 87/15
            COALESCE(SUM(CASE WHEN (GERR.BDCODQUADRO = 3) AND (GERR.BDNUMCAMPO = 1) THEN GERR.BDVALOR END), 0) AS VLRCAMPO23, --1 - Valor do ICMS Devido à UF de Destino - 140709-EC 87/15
            COALESCE(SUM(CASE WHEN (GERR.BDCODQUADRO = 3) AND (GERR.BDNUMCAMPO = 2) THEN GERR.BDVALOR END), 0) AS VLRCAMPO24, --2 - Devoluções ou Anulações - 140709-EC 87/15
            COALESCE(SUM(CASE WHEN (GERR.BDCODQUADRO = 3) AND (GERR.BDNUMCAMPO = 3) THEN GERR.BDVALOR END), 0) AS VLRCAMPO25, --3 - Pagamentos Antecipados - 140709-EC 87/15
            COALESCE(SUM(CASE WHEN (GERR.BDCODQUADRO = 3) AND (GERR.BDNUMCAMPO = 4) THEN GERR.BDVALOR END), 0) AS VLRCAMPO26, --4 - Total do ICMS Devido à UF de Destino - 140709-EC 87/15
            COALESCE(SUM(CASE WHEN (GERR.BDCODQUADRO = 3) AND (GERR.BDNUMCAMPO = 5) THEN GERR.BDVALOR END), 0) AS VLRCAMPO27, --5 - Total ICMS FCP - 140709-EC 87/15
            COALESCE(SUM(CASE WHEN GERR.BDNUMCAMPO in (1,2,3,4,5,22) THEN GERR.BDVALOR END), 0) AS VLRCAMPO28 --6 - Soma total do quadro EC87/15 - 140709-EC 87/15
        FROM VEF_EMP_TGIASTGERREG GERR
        WHERE GERR.BDCODEMP = :PRCODEMP AND GERR.BDREFERENCIA BETWEEN :PRDATAINI AND :PRDATAFIM
        GROUP BY GERR.BDCODUF, GERR.BDCODEMP, GERR.BDREFERENCIA
        ORDER BY BDCODEMP, BDREFERENCIA, BDCODUF;

 /******************************************************************************
 *                  CFOP'S CADASTRADAS NA FÓRMULA VALSUBUF                     *
 ******************************************************************************/

    wCFOP = (SELECT FIRST 1 FORM.BDFORMULA
             FROM VEF_BASE_TCONFGIASTFORM FORM
             WHERE FORM.BDDESCFORM = 'ICMS de Devoluções de Mercadorias');

    wCFOP = REPLACE(wCFOP,'VALSUBEUF','');
    wCFOP = REPLACE(wCFOP,'(','');
    wCFOP = REPLACE(wCFOP,')','');
    wCFOP = REPLACE(wCFOP,'+','');
    wCFOP = REPLACE(wCFOP,'TTVALICMSSTDEVRUF','');

 /******************************************************************************
 *                                      A1                                     *
 ******************************************************************************/

    wSQL =         ' INSERT INTO TEXPORTA_GIAST (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA) ';
    wSQL = wSQL || ' SELECT ID, EMP, REG, ORDEM, BDLINHAA1 ';
    wSQL = wSQL || ' FROM( ';
    wSQL = wSQL || '        SELECT '''||:PRARQUIVO||''' AS ID , ' || :PRCODEMP || ' AS EMP ' || ' , ' || ' 1 AS REG,  RPAD(''A0|'' || RPAD(MOVE.BDSIGLAUF, 2, '' '') || ''|A1|'' || MOVE.BDNUMDOCINI||''.''||MOVE.BDIETER, 25, 0) AS ORDEM, ' ;
    wSQL = wSQL || '        ( ';
    wSQL = wSQL || '            ''A1''||'; --ID do registro
    wSQL = wSQL || '            LPAD(COALESCE(MOVE.BDNUMDOCINI, 0), 13, 0)|| '; --Número da nota fiscal
    wSQL = wSQL || '            RPAD(COALESCE(MOVE.BDSERIE, ''''), 3, '' '')|| '; --Série da nota fiscal
    wSQl = wSQL || '            RPAD(MOVE.BDIETER, 14, '' '')|| '; --Inscrição Estadual
    wSQl = wSQL || '            (SELECT BDDATA FROM SP_PARSE_DATE(MOVE.BDDATAEMISSAO, ' || '''YYYYMMDD''' || ' ))|| '; --Data de Emissão da Nota Fiscal – Formato: AAAAMMDD
    wSQL = wSQL || '            LPAD(COALESCE(REPLACE(CAST(MOVE.BDVLRST AS NUMERIC(15,2)), ''.'', ''''), 0), 15, 0) '; --Valor do ICMS-ST de Devolução
    wSQL = wSQL || '        )BDLINHAA1 ';
    wSQL = wSQL || '        FROM( ';
    wSQL = wSQL || '                SELECT MOVE.BDCODEMP, MOVE.BDCHAVE, MOVE.BDREFLAN, MOVE.BDNUMDOCINI, MOVE.BDSERIE, MOVE.BDDATAEMISSAO, MOVE.BDCODTER, SUM(MOVI.BDVLRST) + COALESCE(SUM(MOVI.BDFCPRETIDO),0) BDVLRST, TREF.BDCODCID, UF.BDSIGLAUF, UF.BDCODUF, ';
    wSQL = wSQL || '                       IIF(TREF.BDIETER = ''ISENTO'',TREF.BDIETER,(SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(COALESCE(TREF.BDIETER, ''''), 14))) BDIETER ';
    wSQL = wSQL || '                FROM( ';
    wSQL = wSQL || '                        SELECT MOVE.BDCODEMP, MOVE.BDCHAVE, MOVE.BDREFLAN, MOVE.BDNUMDOCINI, MOVE.BDSERIE, MOVE.BDDATAEMISSAO, MOVE.BDCODTER ';
    wSQL = wSQL || '                        FROM VEF_EMP_TMOVENT MOVE ';
    wSQL = wSQL || '                        WHERE MOVE.BDCODEMP = ' || :PRCODEMP ||  ' AND ';
    wSQL = wSQL || '                        MOVE.BDREFLAN BETWEEN ' || :PRDATAINI || ' AND ' || :PRDATAFIM;
    wSQL = wSQL || '                    )MOVE ';
    wSQL = wSQL || '                LEFT JOIN VEF_EMP_TMOVENTITENS MOVI ON ( ';
    wSQL = wSQL || '                                                 MOVI.BDCODEMP = MOVE.BDCODEMP AND MOVI.BDCHAVE = MOVE.BDCHAVE AND ';
    wSQL = wSQL || '                                                 MOVI.BDPREFIXONAT IN ( ' || :wCFOP || ' ) ';
    wSQL = wSQL || '                                               ) ';
    wSQL = wSQL || '                LEFT JOIN VEF_EMP_TCONSUB SUB       ON(SUB.BDCODEMP = MOVE.BDCODEMP) ';
    wSQL = wSQL || '                LEFT JOIN VW_TTERCEIRO_SIMPLES TREF ON(TREF.BDCODTER = MOVE.BDCODTER AND TREF.BDREFEMP <= MOVE.BDREFLAN) ';
    wSQL = wSQL || '                JOIN TCIDADE CID                    ON(CID.BDCODCID = TREF.BDCODCID) ';
    wSQL = wSQL || '                JOIN TUF UF                         ON(UF.BDCODUF = CID.BDCODUF) ';
    wSQL = wSQL || '                WHERE SUB.BDCODUFCONSUB = UF.BDCODUF AND MOVI.BDVLRST > 0 ';
    wSQL = wSQL || '                GROUP BY MOVE.BDCODEMP, MOVE.BDCHAVE, MOVE.BDREFLAN, MOVE.BDNUMDOCINI, MOVE.BDSERIE, MOVE.BDDATAEMISSAO, MOVE.BDCODTER, ';
    wSQL = wSQL || '                         TREF.BDIETER, TREF.BDCODCID, UF.BDSIGLAUF, UF.BDCODUF ';
    wSQL = wSQL || '           )MOVE ';
    wSQL = wSQL || '        LEFT JOIN VEF_EMP_TGIASTGER GER              ON(GER.BDCODEMP = MOVE.BDCODEMP AND GER.BDREFERENCIA = MOVE.BDREFLAN) ';
    wSQL = wSQL || '        LEFT JOIN VEF_BASE_TCONFGIASTFORM FORM       ON(FORM.BDCODCONFGIAST = GER.BDCODCONFGIAST AND FORM.BDNUMCAMPO = 14) ';
    wSQL = wSQL || '        LEFT JOIN TMP_VEF_EMP_TVALCAMPOSGIAST VLRGIA ON(VLRGIA.BDCODEMP = MOVE.BDCODEMP AND VLRGIA.BDREFERENCIA = MOVE.BDREFLAN AND VLRGIA.BDCODUF = MOVE.BDCODUF) ';
    wSQL = wSQL || '        WHERE COALESCE(VLRGIA.BDVLRCAMPO14, 0) > 0 AND FORM.BDDESCFORM = ''ICMS de Devoluções de Mercadorias'' ';
    wSQL = wSQL || '     ) ';
    wSQL = wSQL || ' GROUP BY ID, EMP, REG, ORDEM, BDLINHAA1 ';

    EXECUTE STATEMENT :wSQL;



/******************************************************************************
 *                                      A1 GiaST                                     *
 ******************************************************************************/

insert into TEXPORTA_GIAST (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)
SELECT :PRARQUIVO AS ID, :PRCODEMP AS EMP, 0 AS REG, RPAD('A0|' || RPAD(VLRGIA.BDSIGLAUF, 2, ' ') || '|' || LPAD(VLRGIA.BDCODCONSUB, 5, 0) , 20, 0)|| '|' ||VLRGIA.bdnumnf || '|' || VLRGIA.BDCHAVE AS ORDEM,
       ('A1' || lpad((select BDNUMERO
                      from SP_RETORNA_NUMEROS(coalesce(VLRGIA.BDNUMNF, 0), 13)), 13, 0) || rpad(coalesce(VLRGIA.BDSERIENF, ''), 3, ' ') || rpad(iif(VLRGIA.BDCONTRIBUINTE = 'ISENTO', VLRGIA.BDCONTRIBUINTE,
       (select BDNUMERO
        from SP_RETORNA_NUMEROS(coalesce(VLRGIA.BDCONTRIBUINTE, ''), 14))), 14, ' ') ||(select BDDATA
                                                                                     from SP_PARSE_DATE((VLRGIA.BDDATAEMISSAO), 'YYYYMMDD')) || lpad(coalesce(replace(cast(VLRGIA.BDVALOR as numeric(15,2)), '.', ''), 0), 15, 0)

                                                                                     ) BDLINHAA0
from (select VLRGIA.BDCODEMP, VLRGIA.BDCHAVE, VLRGIA.BDREFERENCIA, VLRGIA.BDTIPOICMS, VLRGIA.BDDATAEMISSAO,
             VLRGIA.BDNUMNF, VLRGIA.BDCONTRIBUINTE, VLRGIA.BDVALOR, VLRGIA.BDSERIENF, UF.bdcoduf, UF.bdsiglauf,SUB.BDCODCONSUB
      from VEF_EMP_TLANAJUGIAST VLRGIA
      left join TUF UF on (VLRGIA.BDCODUF = UF.BDCODUF)
      LEFT JOIN VEF_EMP_TCONSUB SUB ON(SUB.BDCODEMP = VLRGIA.BDCODEMP) and (SUB.BDCODUFCONSUB = UF.bdcoduf)
      where VLRGIA.BDCODEMP = :prcodemp and
            VLRGIA.BDREFERENCIA between :prdataini and :prdatafim) VLRGIA
where VLRGIA.BDTIPOICMS = 2 and
      VLRGIA.BDCODEMP = :prcodemp and
      VLRGIA.BDREFERENCIA between :prdataini and :prdatafim;


 /******************************************************************************
 *                                      A2                                     *
 ******************************************************************************/

    INSERT INTO TEXPORTA_GIAST (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)
     SELECT :PRARQUIVO, :PRCODEMP, 2, RPAD('A0|' || LPAD(UF.BDSIGLAUF, 2, ' ') || '|A2|' || LPAD(LAN.BDCHAVE, 5, 0), 20, 0),
    (
            'A2' || --ID do registro
            LPAD((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(COALESCE(LAN.BDNUMNF, 0), 13)), 13, 0)   || --Número da nota fiscal
            RPAD(COALESCE(LAN.BDSERIENF, ''), 3, ' ')|| --Série da nota fiscal
            RPAD(IIF(LAN.BDCONTRIBUINTE = 'ISENTO', LAN.BDCONTRIBUINTE,(SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(COALESCE(LAN.BDCONTRIBUINTE, ''), 14))), 14, ' ') || --Inscrição Estadual
            (SELECT BDDATA FROM SP_PARSE_DATE((LAN.BDDATAEMISSAO), 'YYYYMMDD')) || --Data de Emissão da Nota Fiscal – Formato: AAAAMMDD
            LPAD(COALESCE(REPLACE(CAST(LAN.BDVALOR AS NUMERIC(15,2)), '.', ''), 0), 15, 0) --Valor do ICMS-ST de Ressarcimento
   )BDLINHAA2
    FROM(
            SELECT VLRGIA.BDCODEMP, VLRGIA.BDREFERENCIA, VLRGIA.BDCODUF, VLRGIA.BDVLRCAMPO15
            FROM TMP_VEF_EMP_TVALCAMPOSGIAST VLRGIA
            WHERE VLRGIA.BDCODEMP = :PRCODEMP AND
                  VLRGIA.BDREFERENCIA BETWEEN :PRDATAINI AND :PRDATAFIM
            
        )VLRGIA
 LEFT JOIN VEF_EMP_TLANAJUGIAST LAN ON(LAN.BDCODEMP = VLRGIA.BDCODEMP AND LAN.BDREFERENCIA = VLRGIA.BDREFERENCIA AND LAN.BDCODUF = VLRGIA.BDCODUF)
 LEFT JOIN TUF UF ON(LAN.BDCODUF = UF.BDCODUF)
 WHERE COALESCE(VLRGIA.BDVLRCAMPO15, 0) > 0 AND LAN.BDTIPOICMS = 0;

  /*****************************************************************************
  *                                 CABEÇALHO A4                               *
  *****************************************************************************/

    INSERT INTO TEXPORTA_GIAST (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)
     select distinct :PRARQUIVO, :PRCODEMP, 4, rpad('A0|' || lpad(UF.BDSIGLAUF, 2, ' ') || '|A4|' || lpad(SUB.BDCODCONSUB, 5, 0), 20, 0),
     (
           'A4' --ID do registro
          || case
               when (SUB.BDCLASSEVENC = 0 and VLRGIA.BDVLRCAMPO26 > 0.00) then GERR.BDREFERENCIA || lpad(SUB.BDDIAVCTO, 2, 0)
               when (SUB.BDCLASSEVENC = 1 and VLRGIA.BDVLRCAMPO26 > 0.00) then (select BDREFERENCIA from INC_REFERENCIA(GERR.BDREFERENCIA, 1)) || lpad(SUB.BDDIAVCTO, 2, 0)
               when (SUB.BDCLASSEVENC = 2 and VLRGIA.BDVLRCAMPO26 > 0.00) then (select BDREFERENCIA from INC_REFERENCIA(GERR.BDREFERENCIA, 2)) || lpad(SUB.BDDIAVCTO, 2, 0)
             else lpad('', 8, 0)
           end  --Data de Vencimento do ICMS Devido à UF de Destino – Formato: AAAAMMDD
    
          || lpad(coalesce((select BDNUMERO from SP_RETORNA_NUMEROS(cast(VLRGIA.BDVLRCAMPO26 as numeric(15,2)), 0)), 0), 15, 0) --11 Total do ICMS Devido à UF de Destino (Posição 1002 a 1016)
    
          || case
               when (SUB.BDCLASSEVENC = 0 and VLRGIA.BDVLRCAMPO27 > 0.00) then GERR.BDREFERENCIA || lpad(SUB.BDDIAVCTO, 2, 0)
               when (SUB.BDCLASSEVENC = 1 and VLRGIA.BDVLRCAMPO27 > 0.00) then (select BDREFERENCIA from INC_REFERENCIA(GERR.BDREFERENCIA, 1)) || lpad(SUB.BDDIAVCTO, 2, 0)
               when (SUB.BDCLASSEVENC = 2 and VLRGIA.BDVLRCAMPO27 > 0.00) then (select BDREFERENCIA from INC_REFERENCIA(GERR.BDREFERENCIA, 2)) || lpad(SUB.BDDIAVCTO, 2, 0)
             else lpad('', 8, 0)
           end --Data de Vencimento FCP – Formato: AAAAMMDD
    
          || lpad(coalesce((select BDNUMERO from SP_RETORNA_NUMEROS(cast(VLRGIA.BDVLRCAMPO27 as numeric(15,2)), 0)), 0), 15, 0) --12 Total ICMS FCP (Posição 1017 a 1031)
    
           ) BDLINHAA4
    
          from (select GER.BDRETIFICADORA, GER.BDCODCONTADOR, GER.BDREFERENCIA, GER.BDCODEMP
                from VEF_EMP_TGIASTGER GER
                where GER.BDCODEMP = :PRCODEMP and GER.BDREFERENCIA between :PRDATAINI and :PRDATAFIM) GER
    
    left join VEF_EMP_TCONSUB SUB on (SUB.BDCODEMP = GER.BDCODEMP)
    left join VEF_EMP_TGIASTGERREG GERR on (GERR.BDCODEMP = GER.BDCODEMP and GERR.BDCODUF = SUB.BDCODUFCONSUB and GERR.BDREFERENCIA = GER.BDREFERENCIA)
    left join TUF UF on (UF.BDCODUF = GERR.BDCODUF)
    left join TMP_VEF_EMP_TVALCAMPOSGIAST VLRGIA on (VLRGIA.BDCODEMP = GER.BDCODEMP and VLRGIA.BDCODUF = GERR.BDCODUF and VLRGIA.BDREFERENCIA = GER.BDREFERENCIA)
    where coalesce((VLRGIA.BDVLRCAMPO26 + VLRGIA.BDVLRCAMPO27), 0) > 0;


  /*****************************************************************************
  *                                 CABEÇALHO A0                               *
  *****************************************************************************/

    INSERT INTO TEXPORTA_GIAST (BDID, BDCODEMP, BDORDEMREG, BDORDEM, BDLINHA)

    SELECT ID, EMP, REG, ORDEM, BDLINHAA0
    FROM(
            SELECT :PRARQUIVO AS ID, :PRCODEMP AS EMP, 0 AS REG, RPAD('A0|' || RPAD(UF.BDSIGLAUF, 2, ' ') || '|' || LPAD(SUB.BDCODCONSUB, 5, 0), 20, 0) AS ORDEM,
            (
                'A0' || --ID REGISTRO
                'GST'|| --FIXO
                '03' || --VERSÃO
                SUBSTRING(GER.BDREFERENCIA FROM 5 FOR 2) || SUBSTRING(GER.BDREFERENCIA FROM 1 FOR 4) || --Período Referência da Declaração – Formato: MMAAAA
                RPAD(IIF(SUB.BDIEEMPSUB = 'ISENTO', RPAD(SUB.BDIEEMPSUB, 14, ' '),(SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(SUB.BDIEEMPSUB, 14))), 14, ' ') || --Inscrição Estadual
                CASE
                    WHEN (
                          (VLRGIA.BDVLRCAMPO07 = 0.00) AND (VLRGIA.BDVLRCAMPO08 = 0.00) AND (VLRGIA.BDVLRCAMPO09 = 0.00) AND (VLRGIA.BDVLRCAMPO10 = 0.00) AND
                          (VLRGIA.BDVLRCAMPO11 = 0.00) AND (VLRGIA.BDVLRCAMPO12 = 0.00) AND (VLRGIA.BDVLRCAMPO13 = 0.00) AND (VLRGIA.BDVLRCAMPO14 = 0.00) AND
                          (VLRGIA.BDVLRCAMPO15 = 0.00) AND (VLRGIA.BDVLRCAMPO16 = 0.00) AND (VLRGIA.BDVLRCAMPO17 = 0.00) AND (VLRGIA.BDVLRCAMPO18 = 0.00) AND
                          (VLRGIA.BDVLRCAMPO19 = 0.00) AND (VLRGIA.BDVLRCAMPO20 = 0.00) AND (VLRGIA.BDVLRCAMPO21 = 0.00)
                         ) THEN 'S'
                    ELSE ('N')
                END || --GIA Sem Movimento (Sim/Não)
                CASE
                    WHEN (GER.BDRETIFICADORA = 'TRUE') THEN 'S'
                    ELSE ('N')
                END  || --Substituição de GIA (Sim/Não)
                CASE
                    WHEN (SUB.BDCLASSEVENC = 0 AND VLRGIA.BDVLRCAMPO21 > 0.00) THEN GERR.BDREFERENCIA || LPAD(SUB.BDDIAVCTO, 2, 0)
                    WHEN (SUB.BDCLASSEVENC = 1 AND VLRGIA.BDVLRCAMPO21 > 0.00) THEN (SELECT BDREFERENCIA FROM INC_REFERENCIA(GERR.BDREFERENCIA, 1))  || LPAD(SUB.BDDIAVCTO, 2, 0)
                    WHEN (SUB.BDCLASSEVENC = 2 AND VLRGIA.BDVLRCAMPO21 > 0.00) THEN (SELECT BDREFERENCIA FROM INC_REFERENCIA(GERR.BDREFERENCIA, 2))  || LPAD(SUB.BDDIAVCTO, 2, 0)
                    ELSE LPAD('', 8, 0)
                END || --Data do 1º Vencimento do ICMS-ST – Formato: AAAAMMDD
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO21 AS NUMERIC(15, 2)), 0)), 0), 15, 0) || --Valor do ICMS-ST Referente ao 1º Vencimento
                LPAD('', 8, 0) || --Data do 2º Vencimento do ICMS-ST – Formato: AAAAMMDD
                LPAD('', 15, 0)|| --Valor do ICMS-ST Referente ao 2º Vencimento
                LPAD('', 8, 0) || --Data do 3º Vencimento do ICMS-ST – Formato: AAAAMMDD
                LPAD('', 15, 0)|| --Valor do ICMS-ST Referente ao 3º Vencimento
                LPAD('', 8, 0) || --Data do 4º Vencimento do ICMS-ST – Formato: AAAAMMDD
                LPAD('', 15, 0)|| --Valor do ICMS-ST Referente ao 4º Vencimento
                LPAD('', 8, 0) || --Data do 5º Vencimento do ICMS-ST – Formato: AAAAMMDD
                LPAD('', 15, 0)|| --Valor do ICMS-ST Referente ao 5º Vencimento
                LPAD('', 8, 0) || --Data do 6º Vencimento do ICMS-ST – Formato: AAAAMMDD
                LPAD('', 15, 0)|| --Valor do ICMS-ST Referente ao 6º Vencimento
                COALESCE(UF.BDSIGLAUF, RPAD('', 2, ' ')) || --Sigla da UF Favorecida
                --SUBSTRING(GER.BDREFERENCIA FROM 5 FOR 2) || SUBSTRING(GER.BDREFERENCIA FROM 1 FOR 4) || --Período de referência – informar o MM/AAAA conforme apuração
                --RPAD(IIF(SUB.BDIEEMPSUB = 'ISENTO', SUB.BDIEEMPSUB,(SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(SUB.BDIEEMPSUB, 14))), 14, ' ') || --Inscrição Estadual na UF favorecida – I.E. do estado Favorecido
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO07 AS NUMERIC(15, 2)), 0)), 0), 15, 0) || --Valor dos Produtos
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO08 AS NUMERIC(15, 2)), 0)), 0), 15, 0) || --Valor do IPI
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO09 AS NUMERIC(15, 2)), 0)), 0), 15, 0) || --Despesas Acessórias
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO10 AS NUMERIC(15, 2)), 0)), 0), 15, 0) || --Base de Cálculo do ICMS Próprio
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO11 AS NUMERIC(15, 2)), 0)), 0), 15, 0) || --ICMS Próprio
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO12 AS NUMERIC(15, 2)), 0)), 0), 15, 0) || --Base de Cálculo do ICMS ST
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO13 AS NUMERIC(15, 2)), 0)), 0), 15, 0) || --ICMS Retido por ST
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO14 AS NUMERIC(15, 2)), 0)), 0), 15, 0) || --ICMS de Devoluções de Mercadorias
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO15 AS NUMERIC(15, 2)), 0)), 0), 15, 0) || --ICMS de Ressarcimentos
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO16 AS NUMERIC(15, 2)), 0)), 0), 15, 0) || --Crédito do Período Anterior
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO17 AS NUMERIC(15, 2)), 0)), 0), 15, 0) || --Pagamentos Antecipados
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO18 AS NUMERIC(15, 2)), 0)), 0), 15, 0) || --ICMS-ST Devido
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO19 AS NUMERIC(15, 2)), 0)), 0), 15, 0) || --Repasse – ICMS Retido por Refinarias/Complementos
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO20 AS NUMERIC(15, 2)), 0)), 0), 15, 0) || --Crédito para Período Seguinte
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO21 AS NUMERIC(15, 2)), 0)), 0), 15, 0) || --Total do ICMS-ST a Recolher
                LPAD((SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(EMP.BDCNPJEMP, 14)), 14, 0) || --CNPJ da empresa declaradora
                RPAD(COALESCE(CONT.BDNOMECONT, ''), 46, ' ') || --Nome do Declarante – Nome do contador responsável
                LPAD((SELECT BDNUMERO FROM SP_RETORNA_ALFANUMERICO(CONT.BDCPFCONT, 11)), 11, 0)|| --CPF do Declarante – CPF do contador responsável
                RPAD('CONTADOR', 30, ' ')|| --Cargo do Declarante na Empresa – Fixo Contador
                LPAD(COALESCE(CONT.BDDDDCONT, ''), 4, 0)     || --Telefone DDD – DDD do contador
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CONT.BDFONECONT, 9)), ''), 9, 0)|| --Telefone Número – telefone do contador
                LPAD(COALESCE(CONT.BDDDDFAXCONT, ''), 4, 0)  || --Fax DDD – DDD fax do contador
                LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CONT.BDFAXCONT, 9)), ''), 9, 0)    || --Fax Número – fax do contador
                RPAD(COALESCE(CONT.BDEMAILCONT, ''), 80, ' ')|| --E-mail do Declarante – E-mail do contador
                RPAD(COALESCE(CID.BDNOMCID, ''), 30, ' ')    || --Local – Local da declaração
               (SELECT BDDATA FROM SP_PARSE_DATE((SELECT CURRENT_DATE AS DATA_ATUAL FROM RDB$DATABASE), 'YYYYMMDD')) || --Data – AAAAMMDD – pegar o dia/mês/ano que gerou a exportação
                RPAD('', 65, ' ') || --Informações Complementares – 1ª linha – reservado
                RPAD('', 60, ' ') || --Informações Complementares – 2ª linha – reservado
                RPAD('', 60, ' ') || --Informações Complementares – 3ª linha – reservado
                CASE
                    WHEN (EMPEST.BDDISTRIBUIDORCOMB = 'TRUE') THEN 'S'
                    ELSE ('N')
                END || --Distribuidor de Combustíveis – SIM/NÃO conforme parâmetro do cadastro da empresa
                'N' || --Efetuou Transferências para UF Favorecida – SIM/NÃO – Vamos levar sempre Não
                RPAD('', 6, ' ') || --Código Entrega GIA—Reservado para uso Futuro
          LPAD((SELECT COUNT(E.BDLINHA) A1 FROM TEXPORTA_GIAST E WHERE E.BDCODEMP = :PRCODEMP AND ((E.BDORDEMREG IN(1) AND SUBSTRING(E.BDORDEM FROM 4 FOR 2) = UF.BDSIGLAUF) or (substring(E.BDORDEM from 4 for 2) = UF.BDSIGLAUF) and substring(E.BDLINHA from 2 for 1) = 1)), 6, 0) || --Quantidade Total de Linhas do Anexo I
                LPAD((SELECT COUNT(E.BDLINHA) A1 FROM TEXPORTA_GIAST E WHERE E.BDCODEMP = :PRCODEMP AND E.BDORDEMREG IN(2) AND SUBSTRING(E.BDORDEM FROM 4 FOR 2) = UF.BDSIGLAUF), 6, 0) || --Quantidade Total de Linhas do Anexo II
                LPAD('', 6, 0)           || --Quantidade Total de Linhas do Anexo II
                LPAD('', 15, 0) --Repasse – ICMS Retido por Outros Contribuintes

       ||
       iif((Coalesce(EMPEST.bdec8715, 'FALSE') = 'TRUE'),
       ( (SELECT CASE WHEN BDNUMERO > 0 THEN 'S' ELSE 'N' END FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO28 AS NUMERIC(15, 2)), 0)) -- 1 - EC N° 87/15 com Movimento Posição 866
       || LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO22 AS NUMERIC(15, 2)), 0)), 0), 15, 0) -- Valor do ICMSST FCP Referente ao 1º Vencimento (Posição 867 a 881) - valor do campo novo 22 da apuração.
       || rpad(0,15,'0') --3 Valor do ICMSST FCP Referente ao 2º Vencimento (Posição 882 a 896)
       || rpad(0,15,'0') --4 Valor do ICMSST FCP Referente ao 3º Vencimento (Posição 896 a 911)
       || rpad(0,15,'0') --5 Valor do ICMSST FCP Referente ao 4º Vencimento (Posição 912 a 926)
       || rpad(0,15,'0') --6 Valor do ICMSST FCP Referente ao 5º Vencimento (Posição 927 a 941)
       || rpad(0,15,'0') --7 Valor do ICMSST FCP Referente ao 5º Vencimento (Posição 927 a 941)
       || LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO23 AS NUMERIC(15, 2)), 0)), 0), 15, 0) --8 Valor do ICMS Devido à UF de Destino (Posição 957 a 971)
       || LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO24 AS NUMERIC(15, 2)), 0)), 0), 15, 0) --9 Devoluções ou Anulações (Posição 972 a 986)
       || LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO25 AS NUMERIC(15, 2)), 0)), 0), 15, 0) --10 Pagamentos Antecipados (Posição 987 a 1001)
       || LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO26 AS NUMERIC(15, 2)), 0)), 0), 15, 0) --11 Total do ICMS Devido à UF de Destino (Posição 1002 a 1016)
       || LPAD(COALESCE((SELECT BDNUMERO FROM SP_RETORNA_NUMEROS(CAST(VLRGIA.BDVLRCAMPO27 AS NUMERIC(15, 2)), 0)), 0), 15, 0) --12 Total ICMS FCP (Posição 1017 a 1031)
       ),'')

            )BDLINHAA0
    FROM(
            SELECT GER.BDRETIFICADORA, GER.BDCODCONTADOR, GER.BDREFERENCIA, GER.BDCODEMP
            FROM VEF_EMP_TGIASTGER GER
            WHERE GER.BDCODEMP = :PRCODEMP AND GER.BDREFERENCIA BETWEEN :PRDATAINI AND :PRDATAFIM
        )GER
    --LEFT JOIN VW_TEMPRESAS_REF_MAX REFMAX        ON(REFMAX.BDCODEMP = GER.BDCODEMP)
    LEFT JOIN VEF_EMP_TCONSUB SUB                ON(SUB.BDCODEMP = GER.BDCODEMP)
    LEFT JOIN VEF_EMP_TGIASTGERREG GERR          ON(GERR.BDCODEMP = GER.BDCODEMP AND GERR.BDCODUF = SUB.BDCODUFCONSUB AND GERR.BDREFERENCIA = GER.BDREFERENCIA)
    LEFT JOIN TEMPRESAS EMP                      ON(EMP.BDCODEMP = GER.BDCODEMP)
    --LEFT JOIN TEMPRESAS_REF EREF                 ON(EREF.BDCODEMP = GER.BDCODEMP AND EREF.BDREFEMP = REFMAX.BDREFEMP)
    LEFT JOIN VW_TEMPRESAS_REF_ATUAL EREF        ON(EREF.BDCODEMP = GER.BDCODEMP AND EREF.BDCODCONT = GER.BDCODCONTADOR)
    LEFT JOIN TCONTADOR_PADRAO CONT              ON(CONT.BDCODCONT = GER.BDCODCONTADOR)
    LEFT JOIN TUF UF                             ON(UF.BDCODUF = GERR.BDCODUF)
    LEFT JOIN (select first 1 * from VEF_BASE_TEMPPAREST EMPEST  where EMPEST.BDCODEMP = :PRCODEMP  and EMPEST.bdrefemp <= :prdataini order by EMPEST.bdREFEMP desc) EMPEST ON(EMPEST.BDCODEMP = GER.BDCODEMP and EMPEST.bdREFEMP <= GER.BDREFERENCIA) /*#200465 -- trocado o join normal pelo join select pois só estava levando os valores na exportacao quando o parametro EMPEST.bdec8715 era marcado e salvo na mesma REF da exportação*/
    LEFT JOIN TMP_VEF_EMP_TVALCAMPOSGIAST VLRGIA ON(VLRGIA.BDCODEMP = GER.BDCODEMP AND VLRGIA.BDCODUF = GERR.BDCODUF AND VLRGIA.BDREFERENCIA = GER.BDREFERENCIA)
    LEFT JOIN TCIDADE CID                        ON(CID.BDCODCID = EREF.BDCODCID)
 )
    GROUP BY ID, EMP, REG, ORDEM, BDLINHAA0;

 /******************************************************************************
   *                           EXPORTANDO ARQUIVO                              *
 ******************************************************************************/

  OPENARQ(:PRARQUIVO,:PRCODEMP);

  FOR SELECT E.BDLINHA
      FROM TEXPORTA_GIAST E
      WHERE E.BDID = :PRARQUIVO
      ORDER BY E.BDORDEM
      INTO :WLINHA
  DO
  BEGIN
    WRITELNOA(:WLINHA,:PRCODEMP);
  END

  CLOSEARQ(:PRARQUIVO,:PRCODEMP);
END^

CREATE OR ALTER TRIGGER tmp_vef_emp_tc500sai_temp_bu0 FOR tmp_vef_emp_tc500sai_temp
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  IF (COALESCE(NEW.BDCODCIDDEST, 0) <> COALESCE(OLD.BDCODCIDDEST, 0)) THEN
    SELECT BDNOMCID FROM TCIDADE WHERE BDCODCID = NEW.BDCODCIDDEST INTO NEW.BDNOMECIDDEST;
end^

CREATE OR ALTER TRIGGER vef_dashboard_tarquivo_bi0 FOR vef_dashboard_tarquivo
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  IF (COALESCE(NEW.BDCODARQ, 0) = 0) THEN
    BEGIN
      SELECT MAX(DA.BDCODARQ) + 1
      FROM VEF_DASHBOARD_TARQUIVO DA
      WHERE DA.BDCODEMP = NEW.BDCODEMP
      INTO NEW.BDCODARQ;
      NEW.BDCODARQ = COALESCE(NEW.BDCODARQ, 1);
    END
end^

CREATE OR ALTER trigger VEF_EMP_TMOVOPIMOBI_F200_BI for VEF_EMP_TMOVOPIMOBILIARIA_F200
active before insert position 0
AS
declare variable VCODIGO integer;
begin
  IF (NEW.BDTIPOCONTABILIZACAO IS NULL) THEN
    NEW.BDTIPOCONTABILIZACAO = 0;

  if (new.BDCODUSU is null) then
  begin
    select BDCODUSU from VW_VARIAVEIS_SESSAO_BANCO into VCODIGO;
    new.BDCODUSU = VCODIGO;
  end

  if (new.BDCODUSUINCLU is null) then
  begin
    select BDCODUSU from VW_VARIAVEIS_SESSAO_BANCO into VCODIGO;
    new.BDCODUSUINCLU = VCODIGO;
  end
end^

create  OR ALTER trigger VEF_EMP_TMOVEXP_BU0 for VEF_EMP_TMOVEXP
active before update position 0
as
declare variable VCODIGO integer;
begin
  select BDCODUSU from VW_VARIAVEIS_SESSAO_BANCO into VCODIGO;
  if ((VCODIGO <> 0) and (VCODIGO is not null)) then
    new.BDCODUSU = VCODIGO;
end^

create  OR ALTER trigger VEF_EMP_TMOVEXP_BI0 for VEF_EMP_TMOVEXP
active before insert position 0
as
declare variable VCODIGO integer;
begin
  if (new.BDCODUSU is null) then
  begin
    select BDCODUSU from VW_VARIAVEIS_SESSAO_BANCO into VCODIGO;
    new.BDCODUSU = VCODIGO;
  end

  if (new.BDCODUSUINCLU is null) then
  begin
    select BDCODUSU from VW_VARIAVEIS_SESSAO_BANCO into VCODIGO;
    new.BDCODUSUINCLU = VCODIGO;
  end
end^

create  OR ALTER trigger VEF_EMP_TMOVFINI100_BU0 for VEF_EMP_TMOVFINI100
active before update position 0
as
declare variable VCODIGO integer;
begin
  select BDCODUSU from VW_VARIAVEIS_SESSAO_BANCO into VCODIGO;
  if ((VCODIGO <> 0) and (VCODIGO is not null)) then
    new.BDCODUSU = VCODIGO;
end^

create  OR ALTER trigger VEF_EMP_TMOVFINI100_BI0 for VEF_EMP_TMOVFINI100
active before insert position 0
as
declare variable VCODIGO integer;
begin
  if (new.BDCODUSU is null) then
  begin
    select BDCODUSU from VW_VARIAVEIS_SESSAO_BANCO into VCODIGO;
    new.BDCODUSU = VCODIGO;
  end

  if (new.BDCODUSUINCLU is null) then
  begin
    select BDCODUSU from VW_VARIAVEIS_SESSAO_BANCO into VCODIGO;
    new.BDCODUSUINCLU = VCODIGO;
  end
end^

create  OR ALTER trigger VEF_EMP_TMOVOREC_BU0 for VEF_EMP_TMOVOREC
active before update position 0
as
declare variable VCODIGO integer;
begin
  select BDCODUSU from VW_VARIAVEIS_SESSAO_BANCO into VCODIGO;
  if ((VCODIGO <> 0) and (VCODIGO is not null)) then
    new.BDCODUSU = VCODIGO;
end^

create  OR ALTER trigger VEF_EMP_TMOVOPIMOBILIARIA_F200_BU0 for VEF_EMP_TMOVOPIMOBILIARIA_F200
active before update position 0
as
declare variable VCODIGO integer;
begin
  select BDCODUSU from VW_VARIAVEIS_SESSAO_BANCO into VCODIGO;
  if ((VCODIGO <> 0) and (VCODIGO is not null)) then
    new.BDCODUSU = VCODIGO;
end^

CREATE OR ALTER TRIGGER TMP_VEF_BASE_TLOG_TEMP_BI0 FOR TMP_VEF_BASE_TLOG_TEMP
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (NEW.bddata IS NULL) then
    NEW.BDDATA = (select cast('NOW' as timestamp) from rdb$database);

  if (NEW.BDDATACOMP IS NULL) then
    NEW.BDDATACOMP = (select cast('NOW' as time) from rdb$database);

end^

/* Trigger: VEF_EMP_TPARIMPPAR_BI0 */
CREATE OR ALTER TRIGGER VEF_EMP_TPARIMPPAR_BI0 FOR VEF_EMP_TPARIMPPAR
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEM)+1), 1) FROM vef_emp_tparimppar WHERE (bdcodemp = NEW.bdcodemp)  AND (bdChave = NEW.bdchave) INTO NEW.BDORDEM;
    END
end
^

/* Trigger: VEF_EMP_TPARIMPDARF_AD0 */
CREATE OR ALTER TRIGGER VEF_EMP_TPARIMPDARF_AD0 FOR VEF_EMP_TPARIMPDARF
ACTIVE AFTER DELETE POSITION 0
AS
begin
  update tdarfpadrao darf set darf.bdstatusparcela = 0 where darf.bdcodemp = old.bdcodempdarf and darf.bdchavedarf = old.bdchavedarf;
end
^

/* Trigger: VEF_EMP_TPARIMPDARF_AI0 */
CREATE OR ALTER TRIGGER VEF_EMP_TPARIMPDARF_AI0 FOR VEF_EMP_TPARIMPDARF
ACTIVE AFTER INSERT POSITION 0
AS
begin
  update tdarfpadrao darf set darf.bdstatusparcela = 1 where darf.bdcodemp = new.bdcodempdarf and darf.bdchavedarf = new.bdchavedarf;
end
^

/* Trigger: TPARCELAIMPOSTOPGTO_AD0 */
CREATE OR ALTER TRIGGER TPARCELAIMPOSTOPGTO_AD0 FOR TPARCELAIMPOSTOPGTO
ACTIVE AFTER DELETE POSITION 0
AS
begin
  UPDATE TPARCELAIMPOSTO PAR
  SET PAR.BDQTDPGTO = PAR.BDQTDPGTO - 1
  WHERE PAR.BDCODEMP = OLD.BDCODEMP AND
        PAR.BDCHAVE = OLD.BDCHAVE AND
        PAR.BDCODPAR = OLD.BDCODPAR;
end
^

/* Trigger: TPARCELAIMPOSTOPGTO_AI0 */
CREATE OR ALTER TRIGGER TPARCELAIMPOSTOPGTO_AI0 FOR TPARCELAIMPOSTOPGTO
ACTIVE AFTER INSERT POSITION 0
AS
BEGIN
  UPDATE TPARCELAIMPOSTO PAR
  SET PAR.BDQTDPGTO = PAR.BDQTDPGTO + 1
  WHERE PAR.BDCODEMP = NEW.BDCODEMP AND
        PAR.BDCHAVE = NEW.BDCHAVE AND
        PAR.BDCODPAR = NEW.BDCODPAR;
END
^

CREATE OR ALTER TRIGGER vef_dashboard_tincon_bi0 FOR vef_dashboard_tinconsistencia
ACTIVE BEFORE INSERT POSITION 0
AS
declare variable wRef INTEGER;
declare variable wCodTipo INTEGER;
begin
  IF (COALESCE(NEW.BDORDEMINCO, 0) = 0) THEN
    BEGIN
      SELECT MAX(DI.BDORDEMINCO) + 1
      FROM VEF_DASHBOARD_TINCONSISTENCIA DI
      WHERE DI.BDCODEMP = NEW.BDCODEMP
      AND DI.BDCODARQ = NEW.BDCODARQ
      INTO NEW.BDORDEMINCO;

      NEW.BDORDEMINCO = COALESCE(NEW.BDORDEMINCO, 1);
    END

   /*Empresa não existe na web, não pode gravar na tabela de arquivos enviados porque senão no próximo envio vai tentar enviar como alteração...*/
   IF (POSITION('NÃO EXISTENTE', UPPER(NEW.BDINCONSISTENCIA)) > 0) THEN
     BEGIN
       SELECT FIRST 1 DA.BDREF, DA.BDCODTIPO
       FROM VEF_DASHBOARD_TARQUIVO DA
       WHERE DA.BDCODEMP = NEW.BDCODEMP
       AND DA.BDCODARQ = NEW.BDCODARQ
       INTO :wRef, :wCodTipo;

       DELETE FROM VEF_DASHBOARD_INFO_ENVIADOS IE
       WHERE IE.BDCODEMP = NEW.BDCODEMP
       AND IE.BDCODTIPO = :wCodTipo
       AND IE.BDREFERENCIA = :wRef;

       NEW.BDINCONSISTENCIA = 'Empresa ' || NEW.BDCODEMP || ' não possui SCI Report habilitado na SCI Web!';
     END
end^

CREATE OR ALTER TRIGGER vef_dashboard_info_enviados_bi0 FOR vef_dashboard_info_enviados
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  IF (COALESCE(NEW.BDCODARQ, 0) = 0) THEN
    BEGIN
      SELECT MAX(DIE.BDCODARQ) + 1
      FROM VEF_DASHBOARD_INFO_ENVIADOS DIE
      WHERE DIE.BDCODEMP = NEW.BDCODEMP
      INTO NEW.BDCODARQ;

      NEW.BDCODARQ = COALESCE(NEW.BDCODARQ, 1);
    END

  IF (NEW.BDCODTIPO = 2) THEN /*Impostos*/
    BEGIN
      UPDATE OR INSERT INTO VEF_DASHBOARD_ALERTA(BDCODEMP, BDREFERENCIA, BDCLASSIFICACAO, BDENVIADO)
      VALUES (NEW.BDCODEMP, NEW.BDREFERENCIA, NEW.BDCLASSIMP, 'TRUE') MATCHING(BDCODEMP, BDREFERENCIA, BDCLASSIFICACAO);
    END
end^


/* Restore proc. body: VRHF_SP_TFOLHACOMPINT */
create or alter procedure VRHF_SP_TFOLHACOMPINT (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(28000),
    PRREFINICOMP integer,
    PRREFFIMCOMP integer,
    PRREFINIPAG integer,
    PRREFFIMPAG integer,
    PRAGRUPATOMADOR integer,
    PRTIPOFC integer = 0,
    PRSEPARCALC integer = 0,
    PRCODTPCC varchar(20000) = null,
    PRPUXAFILIAIS integer = 0,
    PRFILIAIS varchar(772) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDREFFN integer,
    BDREFFC integer,
    BDCODCONTTI integer,
    BDREFCOMP integer,
    BDDATAPAGFC date,
    BDDATABAIXAFC date,
    BDBFGTSFC numeric(15,6),
    BDFGTSFC numeric(15,6),
    BDFGTSCSFC numeric(15,6),
    BDBFGTS13FC numeric(15,6),
    BDFGTS13FC numeric(15,6),
    BDFGTS13CSFC numeric(15,6),
    BDMAIORREMFC numeric(15,6),
    BDBINSSFC numeric(15,6),
    BDALIQINSSFC numeric(15,6),
    BDINSSFC numeric(15,6),
    BDBIRRFFC numeric(15,6),
    BDALIQIRRFFC numeric(15,6),
    BDIRRFFC numeric(15,6),
    BDBINSS13FC numeric(15,6),
    BDALIQINSS13FC numeric(15,6),
    BDINSS13FC numeric(15,6),
    BDBIRRF13FC numeric(15,6),
    BDALIQIRRF13FC numeric(15,6),
    BDIRRF13FC numeric(15,6),
    BDBSALFAMFC numeric(15,6),
    BDSALFAMFC numeric(15,6),
    BDBRAISFC numeric(15,6),
    BDSALBASEFC numeric(15,6),
    BDDEPFC numeric(15,6),
    BDBASEPISFC numeric(15,6),
    BDBASEPISFEFC numeric(15,6),
    BDBASEPIS13FC numeric(15,6),
    BDBSALMATEMPFC numeric(15,6),
    BDSALMATEMPFC numeric(15,6),
    BDBRATAPOFC numeric(15,6),
    BDBRATAPOFEFC numeric(15,6),
    BDBRATAPO13FC numeric(15,6),
    BDBINSSFEFOLFC numeric(15,6),
    BDINSSFEFOLFC numeric(15,6),
    BDALIQINSSFEFOLFC numeric(15,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCALCTOMADOR varchar(5),
    BDCREDITO numeric(15,6),
    BDDEBITO numeric(15,6),
    BDBFGTSFEFC numeric(15,6),
    BDFGTSFEFC numeric(15,6),
    BDCODTIPOFC integer,
    BDBINSSMVFC numeric(18,6),
    BDBINSSMV13FC numeric(18,6),
    BDINSSMVFC numeric(18,6),
    BDINSSMV13FC numeric(18,6),
    BDBINSSAPFC numeric(18,6),
    BDBINSS13APFC numeric(18,6),
    BDINSSAPFC numeric(18,6),
    BDINSS13APFC numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDINSSFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDINSS13FN numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDLIQUIDOFC numeric(18,6),
    BDDATAGRRF date)
as
declare variable WDATAPAG varchar(50);
declare variable WORDEMDATAPAG varchar(50);
declare variable WAUXWHERETOM varchar(10);
declare variable WSQL varchar(32700);
declare variable WWHEREN varchar(32700);
declare variable WWHERET varchar(32000);
BEGIN
  /* pragrupatomador
     0 = Nao agrupa
     1 = Agrupa por referencia
     2 = Agrupo por referencia e centro/Tomador
     3 = Agrupa por referencia e Tomador (se nao for tomador verifica pela classificacao e nao encontrando considera empresa)
     4 = Agrupa por referencia e Tipo Tomador (so vai criar mais registros pra empresa se for tomador 155)
     5 = Agrupa por calculo
  */

  IF (prpuxafiliais = 1) THEN
     BEGIN
       IF (coalesce(prcodemp, '') <> '') THEN
          BEGIN
            prcodemp = UPPER(prcodemp);
     
            IF (coalesce(prfiliais, '') <> '') THEN
               BEGIN
                 SELECT bdresult FROM strtran(:prcodemp,'COLCON.BDCODEMP','EMP.BDCODMATRIZ') INTO wwheren;
                 prcodemp = '('||prcodemp||' or (('||wwheren||') and (emp.bdcodemp in ('||prfiliais||'))))';
               END
            ELSE
               BEGIN
                 SELECT bdresult FROM strtran(:prcodemp,'COLCON.BDCODEMP','coalesce(emp.bdcodmatriz,emp.bdcodemp)') INTO prcodemp;
               END
          END
     END

  /* Procedure Text */
  wsql = 'select COLCON.bdcodemp,'||
         ' COLCON.BDCODEMP,'||
         ' COLCON.BDCODCOL,'||
         ' COLCON.BDREFFN,'||
         ' COLCON.BDREFCOMP,'||
         ' COLCON.BDCODCONTTI,'||
         ' COLCON.BDDATAPAGFC,'||
         ' COLCON.BDDATABAIXAFC,'||
         ' COLCON.BDBFGTSFC,'||
         ' COLCON.BDFGTSFC,'||
         ' COLCON.BDFGTSCSFC,'||
         ' COLCON.BDBFGTS13FC,'||
         ' COLCON.BDFGTS13FC,'||
         ' COLCON.BDFGTS13CSFC,'||
         ' COLCON.BDMAIORREMFC,'||
         ' COLCON.BDBINSSFC,'||
         ' COLCON.BDALIQINSSFC,'||
         ' COLCON.BDINSSFC,'||
         ' COLCON.BDBIRRFFC,'||
         ' COLCON.BDALIQIRRFFC,'||
         ' COLCON.BDIRRFFC,'||
         ' COLCON.BDBINSS13FC,'||
         ' COLCON.BDALIQINSS13FC,'||
         ' COLCON.BDINSS13FC,'||
         ' COLCON.BDBIRRF13FC,'||
         ' COLCON.BDALIQIRRF13FC,'||
         ' COLCON.BDIRRF13FC,'||
         ' COLCON.BDBSALFAMFC,'||
         ' COLCON.BDSALFAMFC,'||
         ' COLCON.BDBRAISFC,'||
         ' COLCON.BDSALBASEFC,'||
         ' COLCON.BDDEPFC,'||
         ' COLCON.BDBASEPISFC,'||
         ' COLCON.BDBASEPISFEFC,'||
         ' COLCON.BDBASEPIS13FC,'||
         ' COLCON.BDBSALMATEMPFC,'||
         ' COLCON.BDSALMATEMPFC,'||
         ' COLCON.BDBRATAPOFC,'||
         ' COLCON.BDBRATAPOFEFC,'||
         ' COLCON.BDBRATAPO13FC,'||
         ' COLCON.BDBINSSFEFOLFC,'||
         ' COLCON.BDINSSFEFOLFC,'||
         ' COLCON.BDALIQINSSFEFOLFC,'||
         ' COLCON.BDCREDITOFC,'||
         ' COLCON.BDDEBITOFC,'||
         ' COLCON.bdbfgtsfefc,'||
         ' COLCON.bdfgtsfefc,'||
         ' COLCON.BDREFFC,'||
         ' COLCON.BDCODTIPOFC,'||
         ' COLCON.BDBINSSMVFC,'||
         ' COLCON.BDBINSSMV13FC, '||
         ' COLCON.BDINSSMVFC,'||
         ' COLCON.BDINSSMV13FC, '||
         ' COLCON.BDBINSSAPFC, '||
         ' COLCON.BDBINSS13APFC, '||
         ' COLCON.BDINSSAPFC, '||
         ' COLCON.BDINSS13APFC, '||
         ' FOLN.BDBINSSFN, '||
         ' FOLN.BDINSSFN, '||
         ' FOLN.BDBINSS13FN, '||
         ' FOLN.BDINSS13FN, '||
         ' FOLN.BDBINSSAPFN, '||
         ' FOLN.BDBINSS13APFN, '||
         ' FOLN.BDINSSAPFN, '||
         ' FOLN.BDINSS13APFN, '||
         ' ((select coalesce(sum(BDVALVFC), 0) BDLIQUIDO ' ||
         '   from VRHF_EMP_TVERBAFCINT FCV ' ||
         '   join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and ' ||
         '                                  V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) ' ||
         '   where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and ' ||
         '         FCV.BDREFFN = COLCON.BDREFFN and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDCODCONTTI = COLCON.BDCODCONTTI) - ' ||
         '  (select coalesce(sum(BDVALVFC), 0) BDLIQUIDO ' ||
         '   from VRHF_EMP_TVERBAFCINT FCV ' ||
         '   join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and ' ||
         '                                  V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) ' ||
         '   where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and ' ||
         '         FCV.BDREFFN = COLCON.BDREFFN and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDCODCONTTI = COLCON.BDCODCONTTI)) BDLIQUIDO, '||
         ' COLCON.BDDATAGRRFFC '||
         ' from vrhf_emp_tfolhacompint COLCON'||
         ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
         ' join VRHF_EMP_TFOLHAINT FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFFN = COLCON.BDREFFN and FOLN.BDCODCONTTI = COLCON.BDCODCONTTI) ';

  wwheren = '';
  wwheret = '';

  pragrupatomador = coalesce(pragrupatomador, 0);

  IF (((pragrupatomador >= 3) AND (pragrupatomador <= 4)) OR (pragrupatomador = 1)) THEN
     wauxwheretom = ' where ';
  ELSE
     wauxwheretom = ' and ';

  IF (coalesce(prcodemp, '') <> '') THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||wauxwheretom;
          END

       wwheren = wwheren||prcodemp;
       wwheret = wwhereT||prcodemp;
     END

  IF (coalesce(prcodcol, '') <> '') THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||wauxwheretom;
          END

       wwheren = wwheren||prcodcol;
       wwheret = wwhereT||prcodcol;
     END

  IF ((prrefinicomp IS NOT NULL) AND (prreffimcomp IS NOT NULL)) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||wauxwheretom;
          END

       wwheren = wwheren||'COLCON.BDREFFN >= '||prrefinicomp||' and '||'COLCON.BDREFFN <= '||prreffimcomp;
       wwheret = wwhereT||'COLCON.BDREFTOMADOR >= '||prrefinicomp||' and '||'COLCON.BDREFTOMADOR <= '||prreffimcomp;
     END
  ELSE
     BEGIN
       IF (prrefinicomp IS NOT NULL) THEN
          BEGIN
            IF (wwheren <> '') THEN
               BEGIN
                 wwheren = wwheren||' and ';
                 wwheret = wwheret||' and ';
               END
            ELSE
               BEGIN
                 wwheren = wwheren||' where ';
                 wwheret = wwheret||wauxwheretom;
               END

            wwheren = wwheren||'COLCON.BDREFFN = '||prrefinicomp;
            wwheret = wwhereT||'COLCON.BDREFTOMADOR = '||prrefinicomp;
          END
       ELSE
          BEGIN
            IF (prreffimcomp IS NOT NULL) THEN
               BEGIN
                 IF (wwheren <> '') THEN
                    BEGIN
                      wwheren = wwheren||' and ';
                      wwheret = wwheret||' and ';
                    END
                 ELSE
                    BEGIN
                      wwheren = wwheren||' where ';
                      wwheret = wwheret||wauxwheretom;
                    END

                 wwheren = wwheren||'COLCON.BDREFFN = '||prreffimcomp;
                 wwheret = wwhereT||'COLCON.BDREFTOMADOR = '||prreffimcomp;
               END
          END
     END

  IF (coalesce(prrefinipag, 0) <> 0 AND coalesce(prreffimpag, 0) <> 0) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||wauxwheretom;
          END

       wwheren = wwheren||'COLCON.BDREFCOMP >= '||prrefinipag||' and '||'COLCON.BDREFCOMP <= '||prreffimpag;
       wwheret = wwhereT||'COLCON.BDREFCOMP >= '||prrefinipag||' and '||'COLCON.BDREFCOMP <= '||prreffimpag;
     END
  ELSE
     BEGIN
       IF (coalesce(prrefinipag, 0) <> 0) THEN
          BEGIN
            IF (wwheren <> '') THEN
               BEGIN
                 wwheren = wwheren||' and ';
                 wwheret = wwheret||' and ';
               END
            ELSE
               BEGIN
                 wwheren = wwheren||' where ';
                 wwheret = wwheret||wauxwheretom;
               END

            wwheren = wwheren||'COLCON.BDREFCOMP = '||prrefinipag;
            wwheret = wwhereT||'COLCON.BDREFCOMP = '||prrefinipag;
          END
       ELSE
          BEGIN
            IF (coalesce(prreffimpag, 0) <> 0) THEN
               BEGIN
                 IF (wwheren <> '') THEN
                    BEGIN
                      wwheren = wwheren||' and ';
                      wwheret = wwheret||' and ';
                    END
                 ELSE
                    BEGIN
                      wwheren = wwheren||' where ';
                      wwheret = wwheret||wauxwheretom;
                    END

                 wwheren = wwheren||'COLCON.BDREFCOMP = '||prreffimpag;
                 wwheret = wwhereT||'COLCON.BDREFCOMP = '||prreffimpag;
               END
          END
     END

  IF (prtipofc > 0) THEN
     BEGIN
       IF (wwheren <> '') THEN
          BEGIN
            wwheren = wwheren||' and ';
            wwheret = wwheret||' and ';
          END
       ELSE
          BEGIN
            wwheren = wwheren||' where ';
            wwheret = wwheret||wauxwheretom;
          END

       wwheren = wwheren||'coalesce(COLCON.BDCODTIPOFC,1) = '||prtipofc;
       wwheret = wwhereT||'coalesce(COLCON.BDCODTIPOFC,1) = '||prtipofc;
     END

  IF ((prcodtpcc IS NULL) OR (prcodtpcc = '')) THEN
     BEGIN
       bdcalctomador = 'False';
     
       FOR EXECUTE STATEMENT wsql||wwheren
       INTO
         :bdcodemp,
         :BDCODEMP,
         :BDCODCOL,
         :BDREFFN,
         :BDREFCOMP,
         :BDCODCONTTI,
         :BDDATAPAGFC,
         :BDDATABAIXAFC,
         :BDBFGTSFC,
         :BDFGTSFC,
         :BDFGTSCSFC,
         :BDBFGTS13FC,
         :BDFGTS13FC,
         :BDFGTS13CSFC,
         :BDMAIORREMFC,
         :BDBINSSFC,
         :BDALIQINSSFC,
         :BDINSSFC,
         :BDBIRRFFC,
         :BDALIQIRRFFC,
         :BDIRRFFC,
         :BDBINSS13FC,
         :BDALIQINSS13FC,
         :BDINSS13FC,
         :BDBIRRF13FC,
         :BDALIQIRRF13FC,
         :BDIRRF13FC,
         :BDBSALFAMFC,
         :BDSALFAMFC,
         :BDBRAISFC,
         :BDSALBASEFC,
         :BDDEPFC,
         :BDBASEPISFC,
         :BDBASEPISFEFC,
         :BDBASEPIS13FC,
         :BDBSALMATEMPFC,
         :BDSALMATEMPFC,
         :BDBRATAPOFC,
         :BDBRATAPOFEFC,
         :BDBRATAPO13FC,
         :BDBINSSFEFOLFC,
         :BDINSSFEFOLFC,
         :BDALIQINSSFEFOLFC,
         :bdcredito,
         :bddebito,
         :bdbfgtsfefc,
         :bdfgtsfefc,
         :BDREFFC,
         :BDCODTIPOFC,
         :BDBINSSMVFC,
         :BDBINSSMV13FC,
         :BDINSSMVFC,
         :BDINSSMV13FC,
         :BDBINSSAPFC,
         :BDBINSS13APFC,
         :BDINSSAPFC,
         :BDINSS13APFC,
         :BDBINSSFN,
         :BDINSSFN,
         :BDBINSS13FN,
         :BDINSS13FN,
         :BDBINSSAPFN,
         :BDBINSS13APFN,
         :BDINSSAPFN,
         :BDINSS13APFN,
         :BDLIQUIDOFC,
         :BDDATAGRRF
       DO
         BEGIN
           SUSPEND;
         END
     END

            WDATAPAG = 'colcon.BDDATAPAGFC';
            wordemdatapag = '';
  IF ((prseparcalc = 0) OR (prseparcalc IS NULL)) THEN
     BEGIN
       IF (coalesce(pragrupatomador, 0) >= 1) THEN
          BEGIN
            WDATAPAG = 'max(colcon.BDDATAPAGFC)';
            wordemdatapag = '';
          END
       ELSE
          BEGIN
            WDATAPAG = 'colcon.BDDATAPAGFC';
            wordemdatapag = '';
          END
     END
  ELSE
     BEGIN
       WDATAPAG = 'colcon.BDDATAPAGFC';
       wordemdatapag = ', colcon.BDDATAPAGFC';
     END

  IF (coalesce(pragrupatomador, 0) = 5) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                WDATAPAG||','||
                'cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
                'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), '||
                'sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
                'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), '||
                'sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
                'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), '||
                'sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
                'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), '||
                'sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC), sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
                'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
                'cast(null as integer), cast(null as integer), '||
                'sum(colcon.bdcreditofc), sum(colcon.bddebitofc), '||
                'sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc), '||
                'colcon.BDREFFC, max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
                'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc), '||
                'sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
                'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13apft), '||
                'sum(COLCON.bdliquido), max(COLCON.bddatagrrffc) '||
              'from (';
              
       wsql = wsql||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                'COLCON.BDBFGTSFC, '||
                'COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, '||
                'COLCON.BDFGTS13CSFC,COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, '||
                'COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, '||
                'COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
                'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, '||
                'COLCON.BDSALFAMFC, COLCON.BDBRAISFC,COLCON.BDSALBASEFC, '||
                'COLCON.BDDEPFC, COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, '||
                'COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC, COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, '||
                'COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, '||
                'colcon.bdcreditofc, colcon.bddebitofc, colcon.bddatapagfc, '||
                'colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc, '||
                'colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
                'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc, '||
                'FOLN.bdbinssft, FOLN.bdinssft, FOLN.bdbinss13ft, FOLN.bdinss13ft, '||
                'foln.bdbinssapft, foln.bdbinss13apft, foln.bdinssapft, foln.bdinss13apft, '||
                '((select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMINT FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and ' ||
                '                                V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM and FCV.BDCODCONTTI = COLCON.BDCODCONTTI) - ' ||
                ' (select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMINT FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and ' ||
                '                                 V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM and FCV.BDCODCONTTI = COLCON.BDCODCONTTI)) BDLIQUIDO, '||
                'case when pf.BDCODTPCC is null then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC, COLCON.BDDATAGRRFFC, '||
                'COLCON.BDCODCONTTI '||
              'from VRHF_EMP_TFOLTOMCOMPINT COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join VRHF_EMP_TFOLHATOMINT FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLN.BDORDEM = COLCON.BDORDEM and FOLN.BDCODCONTTI = COLCON.BDCODCONTTI) '||
              'join vrhf_emp_tprepfn pf on (pf.BDCODEMP = COLCON.BDCODEMP and pf.BDCODCOL = COLCON.BDCODCOL and pf.BDORDEM = COLCON.BDORDEM) '||
              'where colcon.bdcodemp is not null '||
              wwheret||') COLCON ';

       IF (coalesce(prcodtpcc, '') <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.bdcodemp,colcon.bdcodcol,colcon.BDCODCONTTI,colcon.BDREFTOMADOR, colcon.BDREFFC, COLCON.BDREFCOMP'||wordemdatapag;
     END
  ELSE IF (coalesce(pragrupatomador, 0) = 4) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                WDATAPAG||','||
                'CAST(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
                'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), '||
                'sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
                'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), '||
                'sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
                'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), '||
                'sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
                'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), '||
                'sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC),sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
                'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
                'case when COLCON.bdCODTPCCtoma is null then null else COLCON.bdCodCentrotoma end bdCodCentro, COLCON.bdCODTPCCtoma bdCODTPCC, '||
                'sum(colcon.bdcreditofc), sum(colcon.bddebitofc), '||
                'sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc), '||
                'max(colcon.BDREFFC), max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
                'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc), '||
                'sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
                'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13ft), '||
                'sum(COLCON.bdliquido), max(COLCON.BDDATAGRRFFC) '||
              'from (';
              
       wsql = wsql||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                'COLCON.BDBFGTSFC, '||
                'COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, '||
                'COLCON.BDFGTS13CSFC,COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, '||
                'COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, '||
                'COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
                'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, '||
                'COLCON.BDSALFAMFC, COLCON.BDBRAISFC, COLCON.BDSALBASEFC, '||
                'COLCON.BDDEPFC, COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, '||
                'COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC,COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, '||
                'COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, '||
                'case when toma.bdCODTPCC is null then null else pf.bdCodCentro end bdCodCentrotoma, toma.bdCODTPCC bdCODTPCCtoma, '||
                'case when pf.BDCODTPCC is null then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC, '||
                'colcon.bdcreditofc, colcon.bddebitofc, COLCON.bddatapagfc, '||
                'colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc, '||
                'colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
                'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc, '||
                'FOLN.bdbinssft, FOLN.bdinssft, FOLN.bdbinss13ft, FOLN.bdinss13ft, '||
                'foln.bdbinssapft, foln.bdbinss13apft, foln.bdinssapft, foln.bdinss13apft, '||
                '((select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMINT FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and ' ||
                '                                V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM and FCV.BDCODCONTTI = COLCON.BDCODCONTTI) - ' ||
                ' (select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMINT FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and ' ||
                '                                 V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM and FCV.BDCODCONTTI = COLCON.BDCODCONTTI)) BDLIQUIDO, '||
                ' COLCON.BDDATAGRRFFC, '||
                ' COLCON.BDCODCONTTI '||
              'from VRHF_EMP_TFOLTOMCOMPINT COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join VRHF_EMP_TFOLHATOMINT FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLN.BDORDEM = COLCON.BDORDEM and FOLN.BDCODCONTTI = COLCON.BDCODCONTTI) '||
              'left outer join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join VRHF_SP_TIPO_TOMADOR_GPS(pf.bdcodtpcc,pf.bdcodcentro,'||prrefinicomp||') toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              wwheret||') COLCON ';

       IF (coalesce(prcodtpcc, '') <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.bdcodemp,colcon.bdcodcol,colcon.BDCODCONTTI,colcon.BDREFTOMADOR,COLCON.BDREFCOMP, COLCON.bdCodCentrotoma, COLCON.bdCODTPCCtoma '||wordemdatapag;
     END
  ELSE IF (coalesce(pragrupatomador, 0) = 3) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                WDATAPAG||', '||
                'cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
                'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), '||
                'sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
                'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), '||
                'sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
                'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), '||
                'sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
                'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), '||
                'sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC),sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
                'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
                'case when COLCON.bdCODTPCCtoma is null then null else COLCON.bdCodCentrotoma end bdCodCentro, COLCON.bdCODTPCCtoma bdCODTPCC, '||
                'sum(colcon.bdcreditofc), sum(colcon.bddebitofc), '||
                'sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc), '||
                'max(colcon.BDREFFC), max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
                'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc), '||
                'sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
                'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13apft), '||
                'sum(COLCON.bdliquido), max(COLCON.BDDATAGRRFFC) '||
              'from (';
 
       wsql = wsql||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                'COLCON.BDBFGTSFC, '||
                'COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, '||
                'COLCON.BDFGTS13CSFC, COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, '||
                'COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, '||
                'COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
                'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, '||
                'COLCON.BDSALFAMFC, COLCON.BDBRAISFC, COLCON.BDSALBASEFC, '||
                'COLCON.BDDEPFC, COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, '||
                'COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC,COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, '||
                'COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, '||
                'case when toma.bdCODTPCC is null then null else pf.bdCodCentro end bdCodCentrotoma, toma.bdCODTPCC bdCODTPCCtoma, '||
                'case when pf.BDCODTPCC is null then null else pf.BDCODCENTRO end BDCODCENTRO, pf.BDCODTPCC, '||
                'colcon.bdcreditofc, colcon.bddebitofc, colcon.bddatapagfc, '||
                'colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc, '||
                'colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
                'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc, '||
                'FOLN.bdbinssft, FOLN.bdinssft, FOLN.bdbinss13ft, FOLN.bdinss13ft, '||
                'foln.bdbinssapft, foln.bdbinss13apft, foln.bdinssapft, foln.bdinss13apft, '||
                '((select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMINT FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and ' ||
                '                                V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM and FCV.BDCODCONTTI = COLCON.BDCODCONTTI) - ' ||
                ' (select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMINT FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and ' ||
                '                                 V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM and FCV.BDCODCONTTI = COLCON.BDCODCONTTI)) BDLIQUIDO, '||
                ' COLCON.BDDATAGRRFFC, '||
                ' COLCON.BDCODCONTTI '||
              'from VRHF_EMP_TFOLTOMCOMPINT COLCON '||
              ' join tempresas emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join VRHF_EMP_TFOLHATOMINT FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLN.BDORDEM = COLCON.BDORDEM and FOLN.BDCODCONTTI = COLCON.BDCODCONTTI) '||
              'left outer join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              'left outer join vrhf_sp_tomador(pf.bdcodtpcc,pf.bdcodcentro) toma on (toma.bdcodcencus = pf.bdcodtpcc and toma.bdcodcentro = pf.bdcodcentro) '||
              wwheret||') COLCON ';
            
       IF (coalesce(prcodtpcc, '') <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.bdcodemp,colcon.bdcodcol,colcon.BDCODCONTTI,colcon.BDREFTOMADOR, COLCON.BDREFCOMP, COLCON.bdCodCentrotoma, COLCON.bdCODTPCCtoma'||wordemdatapag;
     END
  ELSE IF (coalesce(pragrupatomador, 0) = 2) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                WDATAPAG||','||
                'cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
                'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), '||
                'sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
                'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), '||
                'sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
                'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), '||
                'sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
                'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), '||
                'sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC),sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
                'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
                'case when COLCON.bdCODTPCC is null then null else COLCON.bdCodCentro end bdCodCentro, COLCON.bdCODTPCC, '||
                'sum(colcon.bdcreditofc), sum(colcon.bddebitofc), '||
                'sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc), '||
                'max(colcon.BDREFFC), max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
                'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc), '||
                'sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
                'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13apft), '||
                'sum(COLCON.bdliquido), max(COLCON.bddatagrrffc) '||
              'from (';

       wsql = wsql||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                'COLCON.BDBFGTSFC, '||
                'COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, '||
                'COLCON.BDFGTS13CSFC,COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, '||
                'COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, '||
                'COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
                'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, '||
                'COLCON.BDSALFAMFC, COLCON.BDBRAISFC, COLCON.BDSALBASEFC, '||
                'COLCON.BDDEPFC, COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, '||
                'COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC,COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, '||
                'COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, '||
                'case when pf.bdCODTPCC is null then null else pf.bdCodCentro end bdCodCentro, pf.bdCODTPCC, COLCON.bddatapagfc, '||
                'colcon.bdcreditofc, colcon.bddebitofc, '||
                'colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc, '||
                'colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
                'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc, '||
                'FOLN.bdbinssft, FOLN.bdinssft, FOLN.bdbinss13ft, FOLN.bdinss13ft, '||
                'foln.bdbinssapft, foln.bdbinss13apft, foln.bdinssapft,  foln.bdinss13apft, '||
                '((select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMINT FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and ' ||
                '                                V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM and FCV.BDCODCONTTI = COLCON.BDCODCONTTI) - ' ||
                ' (select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMINT FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and ' ||
                '                                 V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM and FCV.BDCODCONTTI = COLCON.BDCODCONTTI)) BDLIQUIDO, '||
                ' COLCON.BDDATAGRRFFC, '||
                ' COLCON.BDCODCONTTI '||
              'from VRHF_EMP_TFOLTOMCOMPINT COLCON '||
              'join VRHF_EMP_TFOLHATOMINT FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDCODCONTTI = COLCON.BDCODCONTTI and FOLN.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLN.BDORDEM = COLCON.BDORDEM ) '||
              'join TEMPRESAS emp on (emp.BDCODEMP = COLCON.BDCODEMP) '||
              'left outer join vrhf_emp_tprepfn pf on (COLCON.BDCODEMP = PF.BDCODEMP and COLCON.BDCODCOL = PF.BDCODCOL and COLCON.BDORDEM = PF.BDORDEM) '||
              wwheret||') COLCON ';
            
       IF (coalesce(prcodtpcc, '') <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.bdcodemp,colcon.bdcodcol,colcon.BDCODCONTTI,colcon.BDREFTOMADOR, COLCON.BDREFCOMP, COLCON.bdCodCentro, COLCON.bdCODTPCC '||wordemdatapag;
     END
  ELSE IF (coalesce(pragrupatomador, 0) = 1) THEN
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                WDATAPAG||', '||
                'cast(null as integer), cast(null as date), sum(COLCON.BDBFGTSFC), '||
                'sum(COLCON.BDFGTSFC), sum(COLCON.BDFGTSCSFC), sum(COLCON.BDBFGTS13FC), sum(COLCON.BDFGTS13FC), '||
                'sum(COLCON.BDFGTS13CSFC),sum(COLCON.BDMAIORREMFC), sum(COLCON.BDBINSSFC), max(COLCON.BDALIQINSSFC), '||
                'sum(COLCON.BDINSSFC), sum(COLCON.BDBIRRFFC), max(COLCON.BDALIQIRRFFC), sum(COLCON.BDIRRFFC), '||
                'sum(COLCON.BDBINSS13FC), max(COLCON.BDALIQINSS13FC), sum(COLCON.BDINSS13FC), '||
                'sum(COLCON.BDBIRRF13FC), max(COLCON.BDALIQIRRF13FC), sum(COLCON.BDIRRF13FC), sum(COLCON.BDBSALFAMFC), '||
                'sum(COLCON.BDSALFAMFC), sum(COLCON.BDBRAISFC), max(COLCON.BDSALBASEFC), '||
                'sum(COLCON.BDDEPFC), sum(COLCON.BDBASEPISFC), sum(COLCON.BDBASEPISFEFC), sum(COLCON.BDBASEPIS13FC), sum(COLCON.BDBSALMATEMPFC), '||
                'sum(COLCON.BDSALMATEMPFC), sum(COLCON.BDBRATAPOFC), sum(COLCON.BDBRATAPOFEFC), sum(COLCON.BDBRATAPO13FC), '||
                'sum(COLCON.BDBINSSFEFOLFC), sum(COLCON.BDINSSFEFOLFC), max(COLCON.BDALIQINSSFEFOLFC), '||
                'cast(null as integer), cast(null as integer), '||
                'sum(colcon.bdcreditofc), sum(colcon.bddebitofc), '||
                'sum(colcon.bdBFGTSFEfc), sum(colcon.bdFGTSFEfc), '||
                'max(colcon.BDREFFC), max(colcon.BDCODTIPOFC), sum(COLCON.BDBINSSMVFC), sum(COLCON.BDBINSSMV13FC), sum(COLCON.BDINSSMVFC), sum(COLCON.BDINSSMV13FC), '||
                'sum(colcon.bdbinssapfc), sum(colcon.bdbinss13apfc), sum(colcon.bdinssapfc), sum(colcon.bdinss13apfc), '||
                'sum(COLCON.bdbinssft), sum(COLCON.bdinssft), sum(COLCON.bdbinss13ft), sum(COLCON.bdinss13ft), '||
                'sum(colcon.bdbinssapft), sum(colcon.bdbinss13apft), sum(colcon.bdinssapft), sum(colcon.bdinss13apft), '||
                'sum(COLCON.bdliquido), max(COLCON.BDDATAGRRFFC) '||
              'from (';

       wsql = wsql||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                'COLCON.BDBFGTSFC, COLCON.bddatapagfc, '||
                'COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, '||
                'COLCON.BDFGTS13CSFC,COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, '||
                'COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, '||
                'COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
                'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, '||
                'COLCON.BDSALFAMFC, COLCON.BDBRAISFC, COLCON.BDSALBASEFC, '||
                'COLCON.BDDEPFC, COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, '||
                'COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC, COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, '||
                'COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, '||
                'colcon.bdcreditofc, colcon.bddebitofc, case when pf.bdcodtpcc is null then null else pf.bdcodcentro end bdcodcentro, pf.bdcodtpcc, '||
                'colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc, '||
                'colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
                'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc, '||
                'FOLN.bdbinssft, FOLN.bdinssft, FOLN.bdbinss13ft, FOLN.bdinss13ft, '||
                'foln.bdbinssapft, foln.bdbinss13apft, foln.bdinssapft, foln.bdinss13apft, '||
                '((select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMINT FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and ' ||
                '                                V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM and FCV.BDCODCONTTI = COLCON.BDCODCONTTI) - ' ||
                ' (select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMINT FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and ' ||
                '                                 V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM and FCV.BDCODCONTTI = COLCON.BDCODCONTTI)) BDLIQUIDO, '||
                ' COLCON.BDDATAGRRFFC, '||
                ' COLCON.BDCODCONTTI '||
              'from VRHF_EMP_TFOLTOMCOMPINT COLCON '||
              'join TEMPRESAS emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join VRHF_EMP_TFOLHATOMINT FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLN.BDORDEM = COLCON.BDORDEM and FOLN.BDCODCONTTI = COLCON.BDCODCONTTI) '||
              'join vrhf_emp_tprepfn pf on (pf.bdcodemp = colcon.bdcodemp and pf.bdcodcol = colcon.bdcodcol and pf.bdordem = colcon.bdordem) '||
              wwheret||') COLCON ';

       IF (coalesce(prcodtpcc, '') <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

       wsql = wsql||' group by colcon.bdcodemp,colcon.bdcodcol,colcon.BDCODCONTTI,colcon.BDREFTOMADOR, COLCON.BDREFCOMP'||wordemdatapag;
     END
  ELSE
     BEGIN
       wsql = 'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDCODCONTTI, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                WDATAPAG||', '||
                'COLCON.BDORDEM, COLCON.BDDATABAIXAFC, COLCON.BDBFGTSFC, COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, COLCON.BDFGTS13CSFC, '||
                'COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
                'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, COLCON.BDSALFAMFC, COLCON.BDBRAISFC, COLCON.BDSALBASEFC, COLCON.BDDEPFC, '||
                'COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, '||
                'COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC, COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, '||
                'COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, case when COLCON.bdCODTPCC is null then null else COLCON.bdCodCentro end bdCodCentro, COLCON.bdCODTPCC, '||
                'colcon.bdcreditofc, colcon.bddebitofc, '||
                'colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc, '||
                'colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
                'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc, '||
                'COLCON.bdbinssft, COLCON.bdinssft, COLCON.bdbinss13ft, COLCON.bdinss13ft, '||
                'colcon.bdbinssapft, colcon.bdbinss13apft, colcon.bdinssapft, colcon.bdinss13apft, '||
                'COLCON.bdliquido, COLCON.BDDATAGRRFFC '||
              'from (';

       wsql = wsql||
              'select '||
                'COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFTOMADOR, COLCON.BDREFCOMP, '||
                'COLCON.bddatapagfc, '||
                'COLCON.BDORDEM, COLCON.BDDATABAIXAFC, COLCON.BDBFGTSFC, COLCON.BDFGTSFC, COLCON.BDFGTSCSFC, COLCON.BDBFGTS13FC, COLCON.BDFGTS13FC, COLCON.BDFGTS13CSFC, '||
                'COLCON.BDMAIORREMFC, COLCON.BDBINSSFC, COLCON.BDALIQINSSFC, COLCON.BDINSSFC, COLCON.BDBIRRFFC, COLCON.BDALIQIRRFFC, COLCON.BDIRRFFC, COLCON.BDBINSS13FC, COLCON.BDALIQINSS13FC, COLCON.BDINSS13FC, '||
                'COLCON.BDBIRRF13FC, COLCON.BDALIQIRRF13FC, COLCON.BDIRRF13FC, COLCON.BDBSALFAMFC, COLCON.BDSALFAMFC, COLCON.BDBRAISFC, COLCON.BDSALBASEFC, COLCON.BDDEPFC, '||
                'COLCON.BDBASEPISFC, COLCON.BDBASEPISFEFC, COLCON.BDBASEPIS13FC, COLCON.BDBSALMATEMPFC, '||
                'COLCON.BDSALMATEMPFC, COLCON.BDBRATAPOFC, COLCON.BDBRATAPOFEFC, COLCON.BDBRATAPO13FC, '||
                'COLCON.BDBINSSFEFOLFC, COLCON.BDINSSFEFOLFC, COLCON.BDALIQINSSFEFOLFC, case when pf.bdCODTPCC is null then null else pf.bdCodCentro end bdCodCentro, pf.bdCODTPCC, '||
                'colcon.bdcreditofc, colcon.bddebitofc, '||
                'colcon.bdBFGTSFEfc, colcon.bdFGTSFEfc, '||
                'colcon.BDREFFC, colcon.BDCODTIPOFC, COLCON.BDBINSSMVFC, COLCON.BDBINSSMV13FC, COLCON.BDINSSMVFC, COLCON.BDINSSMV13FC, '||
                'colcon.bdbinssapfc, colcon.bdbinss13apfc, colcon.bdinssapfc, colcon.bdinss13apfc, '||
                'FOLN.bdbinssft, FOLN.bdinssft, FOLN.bdbinss13ft, FOLN.bdinss13ft, '||
                'foln.bdbinssapft, foln.bdbinss13apft, foln.bdinssapft, foln.bdinss13apft, '||
                '((select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMINT FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 0 and ' ||
                '                                V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM and FCV.BDCODCONTTI = COLCON.BDCODCONTTI) - ' ||
                ' (select coalesce(sum(BDVALVFC), 0) BDLIQUIDO '||
                '  from VRHF_EMP_TVERBAFCTOMINT FCV '||
                '  join VRH_BASE_TVERBAS_REF V on V.BDCODVER = FCV.BDCODVER and V.BDTIPOCODVER = 1 and ' ||
                '                                 V.BDREFVER = (select max(BDREFVER) from VRH_BASE_TVERBAS_REF V2 where V2.BDCODVER = V.BDCODVER and V2.BDREFVER <= COLCON.BDREFCOMP) '||
                '  where FCV.BDCODEMP = COLCON.BDCODEMP and FCV.BDCODCOL = COLCON.BDCODCOL and '||
                '        FCV.BDREFTOMADOR = COLCON.BDREFTOMADOR and FCV.BDREFFC = COLCON.BDREFFC and FCV.BDORDEM = COLCON.BDORDEM and FCV.BDCODCONTTI = COLCON.BDCODCONTTI)) BDLIQUIDO, '||
                ' COLCON.BDDATAGRRFFC, '||
                ' COLCON.BDCODCONTTI '||
              'from VRHF_EMP_TFOLTOMCOMPINT COLCON '||
              'join TEMPRESAS emp on (colcon.bdcodemp = emp.bdcodemp) '||
              'join VRHF_EMP_TFOLHATOMINT FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDREFTOMADOR = COLCON.BDREFTOMADOR and FOLN.BDORDEM = COLCON.BDORDEM and FOLN.BDCODCONTTI = COLCON.BDCODCONTTI) '||
              'join vrhf_emp_tprepfn pf on (colcon.bdcodemp = pf.bdcodemp and colcon.bdcodcol = pf.bdcodcol and colcon.bdordem = pf.bdordem) '||
              wwheret||') COLCON ';

       IF (coalesce(prcodtpcc, '') <> '') THEN
          wsql = wsql||' where '||prcodtpcc;

     END

  FOR EXECUTE STATEMENT wsql
  INTO
    :bdcodemp,
    :bdcodcol,
    :bdcodcontti,
    :bdreffn,
    :BDREFCOMP,
    :BDDATAPAGFC,
    :bdordem,
    :bddatabaixafC,
    :bdbfgtsfC,
    :bdfgtsfc,
    :bdfgtscsfc,
    :bdbfgts13fc,
    :bdfgts13fc,
    :bdfgts13csfc,
    :bdmaiorremfc,
    :bdbinssfc,
    :bdaliqinssfc,
    :bdinssfc,
    :bdbirrffc,
    :bdaliqirrffc,
    :bdirrffc,
    :bdbinss13fc,
    :bdaliqinss13fc,
    :bdinss13fc,
    :bdbirrf13fc,
    :bdaliqirrf13fc,
    :bdirrf13fc,
    :bdbsalfamfc,
    :bdsalfamfc,
    :bdbraisfc,
    :bdsalbasefc,
    :bddepfc,
    :bdbasepisfc,
    :bdbasepisFEfc,
    :bdbasepis13fc,
    :bdbsalmatempfc,
    :bdsalmatempfc,
    :bdbratapofc,
    :bdbratapoFEfc,
    :bdbratapo13fc,
    :bdbinssfefolfc,
    :bdinssfefolfc,
    :bdaliqinssfefolfc,
    :bdCodCentro,
    :bdCODTPCC,
    :bdcredito,
    :bddebito,
    :bdBFGTSFEfc,
    :bdFGTSFEfc,
    :BDREFFC,
    :BDCODTIPOFC,
    :BDBINSSMVFC,
    :BDBINSSMV13FC,
    :BDINSSMVFC,
    :BDINSSMV13FC,
    :BDBINSSAPFC,
    :BDBINSS13APFC,
    :BDINSSAPFC,
    :BDINSS13APFC,
    :BDBINSSFN,
    :BDINSSFN,
    :BDBINSS13FN,
    :BDINSS13FN,
    :BDBINSSAPFN,
    :BDBINSS13APFN,
    :BDINSSAPFN,
    :BDINSS13APFN,
    :BDLIQUIDOFC,
    :BDDATAGRRF
  DO
    BEGIN
      bdcalctomador = 'True';
      SUSPEND;
    END
END^

/* Restore proc. body: SP_ATU_FGTS_CONT_FC_INT */
create or alter procedure SP_ATU_FGTS_CONT_FC_INT (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCODCONTTI integer,
    PRREFERENCIA integer,
    PRREFCOMP integer,
    PRORDEM integer,
    PRVALOR numeric(15,6),
    PRFORMULA varchar(100),
    PRVALORANT numeric(15,6))
as
declare variable WSQLCC varchar(1000);
declare variable WSQL varchar(1000);
declare variable WWHERE varchar(1000);
declare variable WSQLINVERT varchar(1000);
BEGIN
  /* Procedure Text */
  wwhere = ' where lan.bdchave = tol.bdchave and tol.bdcodemp = lan.bdcodemp'||
              ' and tol.bdcodemp = '||prcodemp||
              ' and tol.bdcodcol = '||prcodcol||
              ' and tol.BDREFFC = '||prrefcomp||
              ' and tol.BDCODCONTTI = '||prcodcontti||
              ' and tol.BDFORMULA = '''||prformula||''' ';

  wsqlinvert = '';
  IF (((prvalor < 0) AND (prvalorant > 0)) OR ((prvalor > 0) AND (prvalorant < 0)))  THEN
     wsqlinvert = ', lan.bddebito = lan.bdcredito, lan.bdcredito = lan.bddebito ';

  IF (prvalor < 0) THEN
     prvalor = prvalor * -1;

  wsqlcc = NULL;
  IF (prordem IS NULL) THEN
     BEGIN
       IF (prvalor = 0) THEN
          wsql = 'delete from tol_vrhf_emp_tfgts_fc_int lan ';
       ELSE
          wsql = 'update vsuc_empresas_tlan lan set lan.bdvalor = '||prvalor||wsqlinvert;

       wsql = wsql||' where exists (select tol.bdcodcol from tol_vrhf_emp_tfgts_fc_int tol';
       wsql = wsql||wwhere||
                  ' and tol.BDREFFN = '||prreferencia||
                  ')';
     END
  ELSE
     BEGIN
       IF (prvalor = 0) THEN
          wsql = 'delete from tol_vrhf_emp_tfgts_ft_fc_int lan ';
       ELSE
          wsql = 'update vsuc_empresas_tlan lan set lan.bdvalor = '||prvalor||wsqlinvert;

       wsql = wsql||' where exists (select tol.bdcodcol from tol_vrhf_emp_tfgts_ft_fc_int tol';
    
       wsqlcc = 'update vsuc_empresas_tlcc lan set lan.bdvalor = '||prvalor||
              ' where exists (select tol.bdcodcol from tol_vrhf_emp_tfgts_ft_fc_int tol';

       wsql = wsql||wwhere;

       wsql = wsql||' and tol.bdordem = '||prordem||
                    ' and tol.BDREFTOMADOR = '||prreferencia;
       wsql = wsql||')';

       wsqlcc = wsqlcc||wwhere;
       wsqlcc = wsqlcc||' and tol.bdordem = '||prordem||
                        ' and tol.BDREFTOMADOR = '||prreferencia;
       wsqlcc = wsqlcc||')';
     END

   EXECUTE STATEMENT wsql;

   IF (wsqlcc IS NOT NULL) THEN
      BEGIN
        EXECUTE STATEMENT wsqlcc;
      END
END^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHACOMPINT_BI0 FOR VRHF_EMP_TFOLHACOMPINT
ACTIVE BEFORE INSERT POSITION 0
as
  declare variable wstr varchar(100);
  declare variable wano varchar(4);
  declare variable wmes varchar(2);
  declare variable wdia varchar(2);
  declare variable wdata integer;
  declare variable vdata date;
  declare variable vhora time;
  DECLARE VARIABLE VCODUSU INTEGER; /* Augusto - 02/04/2024 - #192435 */

begin
  wstr = 'select BDRETORNO from preenche_esquerda(EXTRACT(year from cast('||''''||new.bddatapagfc||''''||' as date)),4,'||''||'0'||''||') y';
  execute statement wstr into :wano;
  wstr = 'select BDRETORNO from preenche_esquerda(EXTRACT(month from cast('||''''||new.bddatapagfc||''''||' as date)),2,'||''||'0'||''||') y';
  execute statement wstr into :wMes;
  wstr = 'select BDRETORNO from preenche_esquerda(EXTRACT(day from cast('||''''||new.bddatapagfc||''''||' as date)),2,'||''||'0'||''||') y';
  execute statement wstr into :wDia;

  wdata = cast(wano||wMes as integer);
  new.bdrefcomp = wdata;

  wdata = cast(wano||wMes||wdia as integer);
  new.bdreffc = wdata;

  select current_date, current_time from rdb$database into :vdata, :vhora;

  if (new.bddataprocfc is null) then
     new.bddataprocfc = vdata;

  if (new.bdhoraprocfc is null) then
     new.bdhoraprocfc = vhora;

  /* Augusto - 02/04/2024 - #192435 */
  SELECT FIRST 1 BDCODUSU FROM VW_USUARIOS_SECAO INTO :VCODUSU;
  NEW.BDCODUSU = :VCODUSU;
end^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHACOMPINT_BU0 FOR VRHF_EMP_TFOLHACOMPINT
ACTIVE BEFORE UPDATE POSITION 0
as
  declare variable wstr varchar(100);
  declare variable wano varchar(4);
  declare variable wmes varchar(2);
  declare variable wdia varchar(2);
  declare variable wdata integer;
  declare variable vdata date;
  declare variable vhora time;

begin
  wstr = 'select BDRETORNO from preenche_esquerda(EXTRACT(year from cast('||''''||new.bddatapagfc||''''||' as date)),4,'||''||'0'||''||') y';
  execute statement wstr into :wano;
  wstr = 'select BDRETORNO from preenche_esquerda(EXTRACT(month from cast('||''''||new.bddatapagfc||''''||' as date)),2,'||''||'0'||''||') y';
  execute statement wstr into :wMes;
  wstr = 'select BDRETORNO from preenche_esquerda(EXTRACT(day from cast('||''''||new.bddatapagfc||''''||' as date)),2,'||''||'0'||''||') y';
  execute statement wstr into :wDia;

  wdata = cast(wano||wMes as integer);
  new.bdrefcomp = wdata;

  wdata = cast(wano||wMes||wdia as integer);
  new.bdreffc = wdata;

  select current_date, current_time from rdb$database into :vdata, :vhora;

  if (new.bddataprocfc is null) then
     new.bddataprocfc = vdata;

  if (new.bdhoraprocfc is null) then
     new.bdhoraprocfc = vhora;
end^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHACOMPINT_AU0 FOR VRHF_EMP_TFOLHACOMPINT
ACTIVE AFTER UPDATE POSITION 0
AS
DECLARE VARIABLE wstr VARCHAR(100);
BEGIN
  /* Trigger text */
  IF (OLD.bdfgtsfc <> NEW.bdfgtsfc) THEN
     BEGIN
       wstr = 'FGTSFCSEFIP';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc_int(NEW.bdcodemp,NEW.bdcodcol,NEW.bdcodcontti,NEW.bdreffn,NEW.bdreffc,NULL,NEW.bdfgtsfc,wstr,OLD.bdfgtsfc);
       wstr = 'FGTSFNGRRF';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc_int(NEW.bdcodemp,NEW.bdcodcol,NEW.bdcodcontti,NEW.bdreffn,NEW.bdreffc,NULL,NEW.bdfgtsfc,wstr,OLD.bdfgtsfc);
       wstr = 'FGTSFNRESCSEFIP';            
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc_int(NEW.bdcodemp,NEW.bdcodcol,NEW.bdcodcontti,NEW.bdreffn,NEW.bdreffc,NULL,NEW.bdfgtsfc,wstr,OLD.bdfgtsfc);
     END

  IF (OLD.bdfgtsfefc <> NEW.bdfgtsfefc) THEN
     BEGIN
       wstr = 'FGTSFESEFIP';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc_int(NEW.bdcodemp,NEW.bdcodcol,NEW.bdcodcontti,NEW.bdreffn,NEW.bdreffc,NULL,NEW.bdfgtsfefc,wstr,OLD.bdfgtsfefc);
       wstr = 'FGTSFERGRRF';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc_int(NEW.bdcodemp,NEW.bdcodcol,NEW.bdcodcontti,NEW.bdreffn,NEW.bdreffc,NULL,NEW.bdfgtsfefc,wstr,OLD.bdfgtsfefc);
       wstr = 'FGTSFERESCSEFIP';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc_int(NEW.bdcodemp,NEW.bdcodcol,NEW.bdcodcontti,NEW.bdreffn,NEW.bdreffc,NULL,NEW.bdfgtsfefc,wstr,OLD.bdfgtsfefc);
     END

  IF (OLD.bdfgts13fc <> NEW.bdfgts13fc) THEN
     BEGIN
       wstr = 'FGTS13RESCSEFIP';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc_int(NEW.bdcodemp,NEW.bdcodcol,NEW.bdcodcontti,NEW.bdreffn,NEW.bdreffc,NULL,NEW.bdfgts13fc,wstr,OLD.bdfgts13fc);
       wstr = 'FGTS13RESCGRRF';
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc_int(NEW.bdcodemp,NEW.bdcodcol,NEW.bdcodcontti,NEW.bdreffn,NEW.bdreffc,NULL,NEW.bdfgts13fc,wstr,OLD.bdfgts13fc);
     END
END^

CREATE OR ALTER TRIGGER VRHF_EMP_TFOLHACOMPINT_AD0 FOR VRHF_EMP_TFOLHACOMPINT
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  DELETE FROM VRHF_EMP_TFICHAIRRF WHERE BDCODEMP = OLD.BDCODEMP AND BDCODCOL = OLD.BDCODCOL AND BDREFFIR = OLD.BDREFFN AND BDDATAFIR = OLD.BDDATAPAGFC AND BDTIPOCALCFIR IN (1,13);
  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE bdtipocalc = 8 AND bdcodemp = OLD.bdcodemp AND
                                                               bdcodcol = OLD.bdcodcol AND
                                                               bdreferencia = OLD.BDREFFN AND
                                                               bdDATA = OLD.BDDATAPAGFC AND
                                                               bdcodcontti = OLD.BDCODCONTTI;
END
^

-- 27813 - Raphael Teodoro - 04/02/2020
CREATE OR ALTER TRIGGER VRHF_EMP_TFOLTOMCOMPINT_BIU0 FOR VRHF_EMP_TFOLTOMCOMPINT
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
  DECLARE VARIABLE VCODUSU INTEGER; /* Augusto - 02/04/2024 - #192435 */

BEGIN
  IF ((NEW.bdreffc IS NULL) OR (NEW.bdrefcomp IS NULL) OR (NEW.bddatapagfc <> OLD.bddatapagfc)) THEN
     BEGIN
       NEW.bdrefcomp = (EXTRACT(YEAR FROM NEW.bddatapagfc) * 100) + (EXTRACT(MONTH FROM NEW.bddatapagfc));
       NEW.bdreffc   = (NEW.bdrefcomp * 100) + (EXTRACT(DAY FROM NEW.bddatapagfc));
     END

  IF (NEW.bddataprocfc IS NULL) THEN
     NEW.bddataprocfc = CURRENT_DATE;

  IF (NEW.bdhoraprocfc IS NULL) THEN
     NEW.bdhoraprocfc = CURRENT_TIME;

  EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdreftomador, '1', 'BDPERFOLHACOMPLEMENTAR'); -- 1 - Calculado

  /* Augusto - 02/04/2024 - #192435 */
  SELECT FIRST 1 BDCODUSU FROM VW_USUARIOS_SECAO INTO :VCODUSU;
  NEW.BDCODUSU = :VCODUSU;
END
^

/* Augusto - #192435 - 03/04/2024 - Criada Trigger na folha para inserção do novo campo BDCODUSU */
CREATE OR ALTER TRIGGER VRHF_EMP_TPROVISAO13_BI0 FOR VRHF_EMP_TPROVISAO13
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE VCODUSU INTEGER;
BEGIN
   /* AUGUSTO - 02/04/2024 - #192435 */
  SELECT FIRST 1 BDCODUSU FROM VW_USUARIOS_SECAO INTO :VCODUSU;
  NEW.BDCODUSU = :VCODUSU;
END
^

/* Augusto - #192435 - 03/04/2024 - Criada Trigger na folha para inserção do novo campo BDCODUSU */
CREATE OR ALTER TRIGGER VRHF_EMP_TPROVISAOFERIAS_BI0 FOR VRHF_EMP_TPROVISAOFERIAS
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE VCODUSU INTEGER;
BEGIN
   /* AUGUSTO - 02/04/2024 - #192435 */
  SELECT FIRST 1 BDCODUSU FROM VW_USUARIOS_SECAO INTO :VCODUSU;
  NEW.BDCODUSU = :VCODUSU;
END
^

-- 27813 - Raphael Teodoro - 04/02/2020
CREATE OR ALTER TRIGGER VRHF_EMP_TFOLTOMCOMPINT_AU0 FOR VRHF_EMP_TFOLTOMCOMPINT
ACTIVE AFTER UPDATE POSITION 0
AS
BEGIN
  IF (OLD.bdfgtsfc <> NEW.bdfgtsfc) THEN
     BEGIN
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc_int(NEW.bdcodemp,NEW.bdcodcol,NEW.bdcodcontti,NEW.bdreftomador,NEW.bdreffc,NEW.bdordem,NEW.bdfgtsfc,'FGTSFCSEFIP',OLD.bdfgtsfc);
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc_int(NEW.bdcodemp,NEW.bdcodcol,NEW.bdcodcontti,NEW.bdreftomador,NEW.bdreffc,NEW.bdordem,NEW.bdfgtsfc,'FGTSFNGRRF',OLD.bdfgtsfc);
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc_int(NEW.bdcodemp,NEW.bdcodcol,NEW.bdcodcontti,NEW.bdreftomador,NEW.bdreffc,NEW.bdordem,NEW.bdfgtsfc,'FGTSFNRESCSEFIP',OLD.bdfgtsfc);
     END

  IF (OLD.bdfgtsfefc <> NEW.bdfgtsfefc) THEN
     BEGIN
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc_int(NEW.bdcodemp,NEW.bdcodcol,NEW.bdcodcontti,NEW.bdreftomador,NEW.bdreffc,NEW.bdordem,NEW.bdfgtsfefc,'FGTSFESEFIP',OLD.bdfgtsfefc);
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc_int(NEW.bdcodemp,NEW.bdcodcol,NEW.bdcodcontti,NEW.bdreftomador,NEW.bdreffc,NEW.bdordem,NEW.bdfgtsfefc,'FGTSFERGRRF',OLD.bdfgtsfefc);
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc_int(NEW.bdcodemp,NEW.bdcodcol,NEW.bdcodcontti,NEW.bdreftomador,NEW.bdreffc,NEW.bdordem,NEW.bdfgtsfefc,'FGTSFERESCSEFIP',OLD.bdfgtsfefc);
     END

  IF (OLD.bdfgts13fc <> NEW.bdfgts13fc) THEN
     BEGIN
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc_int(NEW.bdcodemp,NEW.bdcodcol,NEW.bdcodcontti,NEW.bdreftomador,NEW.bdreffc,NEW.bdordem,NEW.bdfgts13fc,'FGTS13RESCSEFIP',OLD.bdfgts13fc);
       EXECUTE PROCEDURE sp_atu_fgts_cont_fc_int(NEW.bdcodemp,NEW.bdcodcol,NEW.bdcodcontti,NEW.bdreftomador,NEW.bdreffc,NEW.bdordem,NEW.bdfgts13fc,'FGTS13RESCGRRF',OLD.bdfgts13fc);
     END
END
^

-- 27813 - Raphael Teodoro - 04/02/2020
CREATE OR ALTER TRIGGER VRHF_EMP_TFOLTOMCOMPINT_AD0 FOR VRHF_EMP_TFOLTOMCOMPINT
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  DELETE FROM VRHF_EMP_TFICHARV WHERE (BDCODEMP = OLD.BDCODEMP) AND (BDCODCOL = OLD.BDCODCOL) AND (BDREFFRV = OLD.BDREFTOMADOR) AND (BDTIPOFRV = 101) AND (BDCCFRV = OLD.BDORDEM);
  DELETE FROM VRHF_EMP_TFICHAHE WHERE (BDCODEMP = OLD.BDCODEMP) AND (BDCODCOL = OLD.BDCODCOL) AND (BDREFFHE = OLD.BDREFTOMADOR) AND (BDTIPOFHE = 101) AND (BDCCFHE = OLD.BDORDEM);
  DELETE FROM VRHF_EMP_TFICHAHN WHERE (BDCODEMP = OLD.BDCODEMP) AND (BDCODCOL = OLD.BDCODCOL) AND (BDREFFHN = OLD.BDREFTOMADOR) AND (BDTIPOFHN = 101) AND (BDCCFHN = OLD.BDORDEM);
  DELETE FROM VRHF_EMP_TFICHAOUTRAS WHERE (BDCODEMP = OLD.BDCODEMP) AND (BDCODCOL = OLD.BDCODCOL) AND (BDREFFOT = OLD.BDREFTOMADOR) AND (BDTIPOFOT = 101) AND (BDCCFOT = OLD.BDORDEM);
  DELETE FROM VRHF_EMP_TFICHAIRRF   WHERE (BDCODEMP = OLD.BDCODEMP) AND (BDCODCOL = OLD.BDCODCOL) AND (BDREFFIR = OLD.BDREFTOMADOR) AND (BDTIPOCALCFIR IN (101,301)) AND (BDCCFIR = OLD.BDORDEM);
  DELETE FROM VRHF_EMP_TDADOSCALC_BAIXA WHERE (BDCODEMP = OLD.BDCODEMP) AND (BDCODCOL = OLD.BDCODCOL) AND (BDTIPOCALC = 9) AND (BDREFERENCIA = OLD.BDREFTOMADOR) AND (bdDATA = OLD.BDDATAPAGFC) AND (bdCODCONTTI = OLD.BDCODCONTTI);

  EXECUTE PROCEDURE SP_VRH_PAINEL_UPDATE(OLD.bdcodemp, OLD.bdreftomador, '2', 'BDPERFOLHACOMPLEMENTAR'); -- 2 - Excluido
END
^

CREATE OR ALTER TRIGGER vrhf_emp_tverbafcint_biu0 for vrhf_emp_tverbafcint
active before insert or update position 0
AS
begin
  NEW.bdrefcomp = CAST(SUBSTRING(CAST(NEW.bdreffc AS VARCHAR(8)) FROM 1 FOR 6) AS INTEGER);
end^

-- 125979 - Raphael Teodoro - 15/01/2020
CREATE OR ALTER PROCEDURE SP_ARRAY_INT (
    PRINI integer,
    PRFIM integer)
returns (
    BDINT integer)
as
BEGIN
  -- Monta tabela com os numeros
  WHILE (prini <= prfim) DO
    BEGIN
      bdint = prini;
      SUSPEND;
      prini = prini + 1;
    END
END
^

-- 125979 - Raphael Teodoro - 04/02/2020
create or alter procedure SP_VRH_PAINEL_ESOCIAL (
    PRCODEMP varchar(10000) not null,
    PRANO integer = 0,
    PRGRUPO1 integer = 1,
    PRGRUPO2A integer = 1,
    PRGRUPO2B integer = 1,
    PRGRUPO3 integer = 1,
    PRGRUPOIND integer = 1,
    PRATIVAS integer = 1,
    PRINATIVAS integer = 1,
    PRRETORNAINTEGRADO integer = 1,
    PRRETORNANAOINTEGRADO integer = 1,
    PRRETORNAANTERIOROBRIG integer = 1,
    PRRETORNAANTERIORSINCR integer = 1,
    PRRETORNASEMCALCULO integer = 1,
    PRRETORNAINTMANUAL integer = 1,
    PRRETORNAINTOBRIG integer = 1,
    PRRETORNAINTSEMDADOS integer = 1)
returns (
    BDCODEMP integer,
    BDNOMEMP type of DM_BDNOMEMP,
    BDANO integer,
    BDMATRIZNAOCADSIS type of DM_BOOLEAN,
    BDPERIODICOS01 integer,
    BDPERIODICOS02 integer,
    BDPERIODICOS03 integer,
    BDPERIODICOS04 integer,
    BDPERIODICOS05 integer,
    BDPERIODICOS06 integer,
    BDPERIODICOS07 integer,
    BDPERIODICOS08 integer,
    BDPERIODICOS09 integer,
    BDPERIODICOS10 integer,
    BDPERIODICOS11 integer,
    BDPERIODICOS12 integer,
    BDPERIODICOS13 integer,
    BDDCTFWEB01 integer,
    BDDCTFWEB02 integer,
    BDDCTFWEB03 integer,
    BDDCTFWEB04 integer,
    BDDCTFWEB05 integer,
    BDDCTFWEB06 integer,
    BDDCTFWEB07 integer,
    BDDCTFWEB08 integer,
    BDDCTFWEB09 integer,
    BDDCTFWEB10 integer,
    BDDCTFWEB11 integer,
    BDDCTFWEB12 integer,
    BDDCTFWEB13 integer,
    BDPERMANUAL varchar(13),
    BDPERFOLHANORMAL varchar(13),
    BDPERFOLHAINTERMITENTE varchar(13),
    BDPERFOLHAAUTONOMO varchar(13),
    BDPERFOLHAADSALARIO varchar(13),
    BDPERFOLHACOMPLEMENTAR varchar(13),
    BDPERFOLHAFERIAS varchar(13),
    BDPERFOLHAAVULSA varchar(13),
    BDPERFOLHA13SALARIO varchar(13),
    BDPERFOLHAAD13SALARIO varchar(13),
    BDPERFOLHACOMP13SALARIO varchar(13),
    BDPERNFFUNRURAL varchar(13),
    BDDCTFMANUAL varchar(13),
    BDDCTFWEB varchar(13),
    BDEMPREINF integer,
    BDREINF01 integer,
    BDREINF02 integer,
    BDREINF03 integer,
    BDREINF04 integer,
    BDREINF05 integer,
    BDREINF06 integer,
    BDREINF07 integer,
    BDREINF08 integer,
    BDREINF09 integer,
    BDREINF10 integer,
    BDREINF11 integer,
    BDREINF12 integer,
    REINF01 integer,
    REINF02 integer,
    REINF03 integer,
    REINF04 integer,
    REINF05 integer,
    REINF06 integer,
    REINF07 integer,
    REINF08 integer,
    REINF09 integer,
    REINF10 integer,
    REINF11 integer,
    REINF12 integer,
    REINFTOTAL01 integer,
    REINFTOTAL02 integer,
    REINFTOTAL03 integer,
    REINFTOTAL04 integer,
    REINFTOTAL05 integer,
    REINFTOTAL06 integer,
    REINFTOTAL07 integer,
    REINFTOTAL08 integer,
    REINFTOTAL09 integer,
    REINFTOTAL10 integer,
    REINFTOTAL11 integer,
    REINFTOTAL12 integer,
    BDS01 integer,
    BDS02 integer,
    BDS03 integer,
    BDS04 integer,
    BDS05 integer,
    BDS06 integer,
    BDS07 integer,
    BDS08 integer,
    BDS09 integer,
    BDS10 integer,
    BDS11 integer,
    BDS12 integer,
    BDS13 integer,
    BDR01 integer,
    BDR02 integer,
    BDR03 integer,
    BDR04 integer,
    BDR05 integer,
    BDR06 integer,
    BDR07 integer,
    BDR08 integer,
    BDR09 integer,
    BDR10 integer,
    BDR11 integer,
    BDR12 integer,
    ESOCIALTOTAL01 integer,
    ESOCIALTOTAL02 integer,
    ESOCIALTOTAL03 integer,
    ESOCIALTOTAL04 integer,
    ESOCIALTOTAL05 integer,
    ESOCIALTOTAL06 integer,
    ESOCIALTOTAL07 integer,
    ESOCIALTOTAL08 integer,
    ESOCIALTOTAL09 integer,
    ESOCIALTOTAL10 integer,
    ESOCIALTOTAL11 integer,
    ESOCIALTOTAL12 integer,
    ESOCIALTOTAL13 integer)
as
declare variable C_STATUS_INTEGRADO integer = 1; /* Integrado */
declare variable C_STATUS_NAO_INTEGRADO integer = 2; /* Nao integrado */
declare variable C_STATUS_ANTERIOR_OBRIG integer = 3; /* Anterior a obrigatoriedade */
declare variable C_STATUS_ANTERIOR_SINCR integer = 4; /* Anterior a sincronizacao */
declare variable C_STATUS_SEM_CALCULO integer = 5; /* Sem calculo */
declare variable C_STATUS_INT_MANUAL integer = 6; /* Integrado manualmente */
declare variable C_STATUS_INT_OBRIG integer = 7; /* Integracao obrigatoria */
declare variable C_STATUS_INT_SEM_DADOS integer = 8;
declare variable C_PER_CALCULADO char(1) = 1; /* Calculado */
declare variable C_PER_EXCLUIDO char(1) = 2; /* Excluido */
declare variable C_PER_PROCESSADO char(1) = 3; /* Processado */
declare variable C_PER_RECUSADO char(1) = 4; /* Recusado */
declare variable C_PER_REABERTO char(1) = 5; /* Reaberto */
declare variable C_PER_PROC_SEM_DADOS char(1) = 6; /* Processado sem dados */
declare variable C_DCTF_PROCESSADO char(1) = 3; /* Processado */
declare variable WSQL varchar(32700);
declare variable WSQLREINF varchar(32700);
declare variable WRETORNAR integer;
declare variable WANOINI integer;
declare variable WANOFIM integer;
declare variable WMES integer;
declare variable WDATAMES date;
declare variable WPERCAMPOSMES char(11);
declare variable WMESFASE3 integer;
declare variable WMESFASE4 integer;
declare variable WPERDEVEINTEGRAR integer;
declare variable WDCTFCAMPOSMES char(1);
declare variable WREFINIDCTFWEB integer;
declare variable WSTATUSPER integer;
declare variable WSTATUSDCTF integer;
declare variable WFILTROGRUPO varchar(150);
declare variable WJOINFASEAMENTO varchar(250);
declare variable WDATAINIPERIOD date;
declare variable WDATAINIDCTFWEB date;
declare variable WDATASINCRONIZADA date;
declare variable WSITEMP type of DM_BOOLEAN;
declare variable WSITUACAOESOCIAL integer;
declare variable WANOREINF integer;
declare variable WANO varchar(50);
declare variable BDREF12 varchar(50);
declare variable BDREFDEZ integer;
BEGIN
  -- Inicializacao
  IF (prcodemp = '') THEN
     prcodemp = '1=1';

  wanoini = prano;
  wanofim = prano;
  IF (wanofim = 0) THEN
     BEGIN
       wanoini = 2018;
       prano   = 9999;
       wanofim = EXTRACT(YEAR FROM CURRENT_DATE) + 1;
     END

  wfiltrogrupo = '';
  IF (prgrupoind = 1)  THEN wfiltrogrupo = wfiltrogrupo || ',0';
  IF (prgrupo1 = 1) THEN wfiltrogrupo = wfiltrogrupo || ',1';
  IF ((prgrupo2a = 1) OR
      (prgrupo2b = 1)) THEN wfiltrogrupo = wfiltrogrupo || ',2';
  IF (prgrupo3 = 1) THEN wfiltrogrupo = wfiltrogrupo || ',3';

  IF (wfiltrogrupo <> '') THEN
     BEGIN
       wfiltrogrupo = '(COALESCE(FAS.BDGRUPO,0) IN (' || SUBSTRING(wfiltrogrupo FROM 2 FOR CHAR_LENGTH(wfiltrogrupo)) || '))';

       IF (prgrupo2a <> prgrupo2b) THEN
          BEGIN
            IF (prgrupo2a = 1) THEN
               wfiltrogrupo = wfiltrogrupo || ' AND ((COALESCE(FAS.BDGRUPO,0) <> 2) OR (COALESCE(FAS.BDREFINIDCTFWEB,0) = 201904))';
            ELSE
               wfiltrogrupo = wfiltrogrupo || ' AND ((COALESCE(FAS.BDGRUPO,0) <> 2) OR (COALESCE(FAS.BDREFINIDCTFWEB,0) <> 201904))';

            wfiltrogrupo = '(' || wfiltrogrupo || ')';
          END
     END

  IF (wfiltrogrupo <> '') THEN
     wfiltrogrupo = ' AND ' || wfiltrogrupo;

  IF (prgrupoind = 1) THEN
     BEGIN
       -- Valida por "where" para aceitar quem nao possui registro
       wjoinfaseamento = 'left outer join VRH_ESOCIAL_TFASEAMENTO FAS on (FAS.BDCODEMP = EMP.BDCODEMP)';
     END
  ELSE
     BEGIN
       -- Valida por "join" para otimizar busca
       wjoinfaseamento = 'INNER JOIN vrh_esocial_tfaseamento FAS ON (FAS.bdcodemp = EMP.bdcodemp)' || wfiltrogrupo;
       wfiltrogrupo = '';
     END

  -- Busca dados cadastrados
  wsql = 'SELECT EMP.bdcodemp, REF.BDNOMEMP, REF.BDSITEMP, PERIODO.bdint as bdano, EMP.BDMATRIZNAOCADSIS, EMP.BDSITUACAOESOCIAL,' ||
           ' PAINEL.bdpermanual, PAINEL.bdperfolhanormal, PAINEL.bdperfolhaintermitente, PAINEL.bdperfolhaautonomo, PAINEL.bdperfolhaadsalario, PAINEL.bdperfolhacomplementar,' ||
           ' PAINEL.bdperfolhaferias, PAINEL.bdperfolhaavulsa, PAINEL.bdperfolha13salario, PAINEL.bdperfolhaad13salario, PAINEL.bdperfolhacomp13salario, PAINEL.bdpernffunrural,' ||
           ' PAINEL.bddctfmanual, PAINEL.bddctfweb,' ||
           ' FAS.bddatainiperiod, FAS.bdrefinidctfweb,' ||
           ' SINC.bddatasincronizada AS bddatasincronizada' ||
       ' FROM TEMPRESAS EMP' ||
       ' INNER JOIN TEMPRESAS_REF REF' ||
             ' ON (REF.BDCODEMP = EMP.BDCODEMP)' ||
            ' AND (REF.BDREFEMP = (SELECT FIRST 1 AUX.BDREFEMP' ||
                                 ' FROM TEMPRESAS_REF AUX' ||
                                 ' WHERE (AUX.BDCODEMP = EMP.BDCODEMP)' ||
                                   ' AND (AUX.BDREFEMP <= ' || prano || '12)' ||
                                 ' ORDER BY AUX.BDCODEMP DESC, AUX.BDREFEMP DESC))' ||
       ' ' || wjoinfaseamento ||
       ' LEFT OUTER JOIN vrh_esocial_tsincronizacao SINC ON (SINC.bdcodemp = EMP.bdcodemp)' ||
       ' CROSS JOIN SP_ARRAY_INT(' || wanoini || ',' || wanofim || ') PERIODO' ||
       ' LEFT OUTER JOIN vrh_emp_painel PAINEL ON (PAINEL.bdcodemp = EMP.bdcodemp) AND (PAINEL.bdano = PERIODO.bdint)' ||
       ' WHERE (' || prcodemp || ')' ||
         ' AND ((COALESCE(EMP.BDCODMATRIZ,0) = 0) OR (EMP.BDMATRIZNAOCADSIS = ''TRUE''))' ||
         wfiltrogrupo ||
       ' ORDER BY EMP.bdcodemp, PERIODO.bdint';

  FOR EXECUTE STATEMENT wsql INTO :bdcodemp, :bdnomemp, :wsitemp, :bdano, :bdmatriznaocadsis, :wsituacaoesocial,
           :bdpermanual, :bdperfolhanormal, :bdperfolhaintermitente, :bdperfolhaautonomo, :bdperfolhaadsalario, :bdperfolhacomplementar,
           :bdperfolhaferias, :bdperfolhaavulsa, :bdperfolha13salario, :bdperfolhaad13salario, :bdperfolhacomp13salario, :bdpernffunrural,
           :bddctfmanual, :bddctfweb,
           :wdatainiperiod, :wrefinidctfweb,
           :wdatasincronizada
  DO
  BEGIN
    wretornar = 0;

    IF (((prativas = 1) AND (wsitemp <> 'TRUE') AND (wsituacaoesocial <> 0)) OR
        ((prinativas = 1) AND ((wsitemp = 'TRUE') OR (COALESCE(wsituacaoesocial,0) = 0)))) THEN
       BEGIN
         wanoini = EXTRACT(YEAR FROM wdatainiperiod);
         IF (bdano < wanoini) THEN
            wmesfase3 = 0;
         ELSE
         IF (bdano = wanoini) THEN
            wmesfase3 = EXTRACT(MONTH FROM wdatainiperiod);
         ELSE
            wmesfase3 = 1;

         IF (COALESCE(wrefinidctfweb,0) = 0) THEN
            wdatainidctfweb = NULL;
         ELSE
            BEGIN
              wanoini = TRUNC(wrefinidctfweb / 100.0);
              wdatainidctfweb = CAST(CAST(wrefinidctfweb - (wanoini * 100) AS VARCHAR(2)) || '-01-' || wanoini AS DATE);
            END

         wanoini = EXTRACT(YEAR FROM wdatainidctfweb);
         IF (bdano < wanoini) THEN
            wmesfase4 = 0;
         ELSE
         IF (wanoini = bdano) THEN
            wmesfase4 = EXTRACT(MONTH FROM wdatainidctfweb);
         ELSE
            wmesfase4 = 1;

         -- Loop de meses
         wperdeveintegrar = 0;
         wmes = 1;
         WHILE (wmes <= 13) DO
           BEGIN
             IF (wmes IN (12,13)) THEN
                wdatames = CAST('01-01-' || (bdano+1) AS DATE);
             ELSE
                wdatames = CAST((wmes+1) || '-01-' || bdano AS DATE);

             wdatames = DATEADD(-1 DAY TO wdatames);

             /*
               Periodicos
             */
             IF ((wdatainiperiod IS NULL) OR
                 (wdatames <= wdatainiperiod)) THEN
                BEGIN
                  -- Antes da obrigatoriedade
                  wstatusper = c_status_anterior_obrig;

                  IF (prretornaanteriorobrig = 1) THEN
                     wretornar = 1;
                END
             ELSE
             IF (TRIM(SUBSTRING(bdpermanual FROM wmes FOR 1)) <> '') THEN
                BEGIN
                  -- Confirmou manualmente
                  wstatusper = c_status_int_manual;

                  IF (prretornaintmanual = 1) THEN
                     wretornar = 1;
                END
             ELSE
                BEGIN
                  wpercamposmes = SUBSTRING(bdperfolhanormal        FROM wmes FOR 1) ||
                                  SUBSTRING(bdperfolhaintermitente  FROM wmes FOR 1) ||
                                  SUBSTRING(bdperfolhaautonomo      FROM wmes FOR 1) ||
                                  SUBSTRING(bdperfolhaadsalario     FROM wmes FOR 1) ||
                                  SUBSTRING(bdperfolhacomplementar  FROM wmes FOR 1) ||
                                  SUBSTRING(bdperfolhaferias        FROM wmes FOR 1) ||
                                  SUBSTRING(bdperfolhaavulsa        FROM wmes FOR 1) ||
                                  SUBSTRING(bdperfolha13salario     FROM wmes FOR 1) ||
                                  SUBSTRING(bdperfolhaad13salario   FROM wmes FOR 1) ||
                                  SUBSTRING(bdperfolhacomp13salario FROM wmes FOR 1) ||
                                  SUBSTRING(bdpernffunrural         FROM wmes FOR 1);

                  IF ((POSITION(c_per_calculado IN wpercamposmes) > 0) OR
                      (POSITION(c_per_excluido  IN wpercamposmes) > 0) OR
                      (POSITION(c_per_recusado  IN wpercamposmes) > 0) OR
                      (POSITION(c_per_reaberto  IN wpercamposmes) > 0)) THEN
                     BEGIN
                       IF (wdatames <= wdatasincronizada) THEN
                          BEGIN
                            -- Antes de sincronizar (1/2)
                            wstatusper = c_status_anterior_sincr;

                            IF (prretornaanteriorsincr = 1) THEN
                               wretornar = 1;
                          END
                       ELSE
                          BEGIN
                            -- Pendente de integracao (1/2)
                            wstatusper = c_status_nao_integrado;
                            wperdeveintegrar = 1;
    
                            IF (prretornanaointegrado = 1) THEN
                               wretornar = 1;
                          END
                     END
                  ELSE
                  IF (wpercamposmes = LPAD('', CHAR_LENGTH(wpercamposmes), c_per_proc_sem_dados)) THEN
                     BEGIN
                       -- Integrado sem dados
                       wstatusper = c_status_int_sem_dados;
                       wperdeveintegrar = 0;

                       IF (prretornaintsemdados = 1) THEN
                          wretornar = 1;
                     END
                  ELSE
                  IF ((POSITION(c_per_proc_sem_dados IN wpercamposmes) > 0) OR
                      (POSITION(c_per_processado     IN wpercamposmes) > 0)) THEN
                     BEGIN
                       -- Integrado com dados
                       wstatusper = c_status_integrado;
                       wperdeveintegrar = 1;

                       IF (prretornaintegrado = 1) THEN
                          wretornar = 1;
                     END
                  ELSE
                  IF (wdatames <= wdatasincronizada) THEN
                     BEGIN
                       -- Antes de sincronizar (2/2)
                       wstatusper = c_status_anterior_sincr;

                       IF (prretornaanteriorsincr = 1) THEN
                          wretornar = 1;
                     END
                  ELSE
                  IF (((wmesfase3 > 0) AND (wmes = 13)) OR -- Decimo apos periodicos
                      (wmes = wmesfase3) OR                -- Inicio de periodicos no ano
                      (wmes = wmesfase4)) THEN             -- Inicio de DCTF Web no ano
                     BEGIN
                       -- Integracao obrigatoria
                       wstatusper = c_status_int_obrig;

                       IF (prretornaintobrig = 1) THEN
                          wretornar = 1;
                     END
                  ELSE
                  IF (wperdeveintegrar = 1) THEN
                     BEGIN
                       -- Pendente de integracao (2/2)
                       wstatusper = c_status_nao_integrado;

                       IF (prretornanaointegrado = 1) THEN
                          wretornar = 1;
                     END
                  ELSE
                     BEGIN
                       -- Nao foi integrado
                       wstatusper = c_status_sem_calculo;
    
                       IF (prretornasemcalculo = 1) THEN
                          wretornar = 1;
                     END
                END
    
             /*
               DCTF WEB
             */
             IF ((wdatainidctfweb IS NULL) OR
                 (wdatames <= wdatainidctfweb)) THEN
                BEGIN
                  -- Antes da obrigatoriedade
                  wstatusdctf = c_status_anterior_obrig;
    
                  IF (prretornaanteriorobrig = 1) THEN
                     wretornar = 1;
                END
             ELSE
             IF (TRIM(SUBSTRING(bddctfmanual FROM wmes FOR 1)) <> '') THEN
                BEGIN
                  -- Confirmou manualmente
                  wstatusdctf = c_status_int_manual;
    
                  IF (prretornaintmanual = 1) THEN
                     wretornar = 1;
                END
             ELSE
                BEGIN
                  wdctfcamposmes = SUBSTRING(bddctfweb FROM wmes FOR 1);
    
                  IF (POSITION(c_dctf_processado IN wdctfcamposmes) > 0) THEN
                     BEGIN
                       -- Integrado com dados
                       wstatusdctf = c_status_integrado;
    
                       IF (prretornaintegrado = 1) THEN
                          wretornar = 1;
                     END
                  ELSE
                     BEGIN
                       wstatusdctf = c_status_nao_integrado;
    
                       IF (prretornanaointegrado = 1) THEN
                          wretornar = 1;
                     END
                END

             IF (wmes = 01) THEN BEGIN bdperiodicos01 = wstatusper; bddctfweb01 = wstatusdctf; END ELSE
             IF (wmes = 02) THEN BEGIN bdperiodicos02 = wstatusper; bddctfweb02 = wstatusdctf; END ELSE
             IF (wmes = 03) THEN BEGIN bdperiodicos03 = wstatusper; bddctfweb03 = wstatusdctf; END ELSE
             IF (wmes = 04) THEN BEGIN bdperiodicos04 = wstatusper; bddctfweb04 = wstatusdctf; END ELSE
             IF (wmes = 05) THEN BEGIN bdperiodicos05 = wstatusper; bddctfweb05 = wstatusdctf; END ELSE
             IF (wmes = 06) THEN BEGIN bdperiodicos06 = wstatusper; bddctfweb06 = wstatusdctf; END ELSE
             IF (wmes = 07) THEN BEGIN bdperiodicos07 = wstatusper; bddctfweb07 = wstatusdctf; END ELSE
             IF (wmes = 08) THEN BEGIN bdperiodicos08 = wstatusper; bddctfweb08 = wstatusdctf; END ELSE
             IF (wmes = 09) THEN BEGIN bdperiodicos09 = wstatusper; bddctfweb09 = wstatusdctf; END ELSE
             IF (wmes = 10) THEN BEGIN bdperiodicos10 = wstatusper; bddctfweb10 = wstatusdctf; END ELSE
             IF (wmes = 11) THEN BEGIN bdperiodicos11 = wstatusper; bddctfweb11 = wstatusdctf; END ELSE
             IF (wmes = 12) THEN BEGIN bdperiodicos12 = wstatusper; bddctfweb12 = wstatusdctf; END ELSE
             IF (wmes = 13) THEN BEGIN bdperiodicos13 = wstatusper; bddctfweb13 = wstatusdctf; END
    
             -- Autônomos e Produtor rural
             IF ((POSITION(c_per_calculado IN SUBSTRING(bdperfolhaautonomo FROM wmes FOR 1)) > 0) OR
                 (POSITION(c_per_excluido  IN SUBSTRING(bdperfolhaautonomo FROM wmes FOR 1)) > 0) OR
                 (POSITION(c_per_recusado  IN SUBSTRING(bdperfolhaautonomo FROM wmes FOR 1)) > 0) OR
                 (POSITION(c_per_reaberto  IN SUBSTRING(bdperfolhaautonomo FROM wmes FOR 1)) > 0) OR
                 (POSITION(c_per_calculado IN SUBSTRING(bdpernffunrural FROM wmes FOR 1)) > 0) OR
                 (POSITION(c_per_excluido  IN SUBSTRING(bdpernffunrural FROM wmes FOR 1)) > 0) OR
                 (POSITION(c_per_recusado  IN SUBSTRING(bdpernffunrural FROM wmes FOR 1)) > 0) OR
                 (POSITION(c_per_reaberto  IN SUBSTRING(bdpernffunrural FROM wmes FOR 1)) > 0)) THEN
                wperdeveintegrar = 0;

             wmes = wmes + 1;
           END
       END
       -- Inicio: Painel eSocial/Reinf/DCTFWeb -- Carlos Xavier 29062022 --
            -- Reinf - 2099
            :wanoreinf = :bdano + 1;
            :wano = :wanoreinf || '01';
            SETORDEMSEQUENCIAL(0);
            :WSQLREINF = 'select MESES.JAN, MESES.FEV, MESES.MAR, MESES.ABR, MESES.MAI, MESES.JUN, MESES.JUL, MESES.AGO, MESES.SETT, MESES.OUT, MESES.NOV, MESES.DEZ ' ||
            'from (select MES.BDCODEMP, max(MES.BDMES01) JAN, max(MES.BDMES02) FEV, max(MES.BDMES03) MAR, max(MES.BDMES04) ABR, max(MES.BDMES05) MAI, max(MES.BDMES06) JUN, max(MES.BDMES07) JUL, max(MES.BDMES08) AGO, ' ||
            'max(MES.BDMES09) SETT, max(MES.BDMES10) OUT, max(MES.BDMES11) NOV, max(MES.BDMES12) DEZ ' ||
            'from (select iif(EVT.BDREFERENCIA = 01, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES01, iif(EVT.BDREFERENCIA = 02, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES02, ' ||
            'iif(EVT.BDREFERENCIA = 03, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES03, iif(EVT.BDREFERENCIA = 04, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES04, ' ||
            'iif(EVT.BDREFERENCIA = 05, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES05, iif(EVT.BDREFERENCIA = 06, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES06, ' ||
            'iif(EVT.BDREFERENCIA = 07, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES07, iif(EVT.BDREFERENCIA = 08, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES08, ' ||
            'iif(EVT.BDREFERENCIA = 09, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES09, iif(EVT.BDREFERENCIA = 10, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES10, ' ||
            'iif(EVT.BDREFERENCIA = 11, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES11, iif(EVT.BDREFERENCIA = 12, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES12, EVT.BDREFERENCIA, ' ||
            'EVT.BDGERADO, EVT.BDCODEMP, EVT.R ' ||
            'from (select substring(EVT.BDREFERENCIA from 5 for 6) BDREFERENCIA, min(EVT.BDINTEGRADO) BDINTEGRADO, ' ||
            'max(EVT.BDGERADO) BDGERADO, EVT.BDCODEMP, iif(EVT.BDREFERENCIA >= cast(substring(BDDATAOBRIGREINF from 1 for 4) || substring(BDDATAOBRIGREINF from 6 for 2) as integer), 0, 1) as R ' ||
            'from VEF_REINF_EVT EVT ' ||
            'join TEMPRESAS EMP on (EVT.BDCODEMP = EMP.BDCODEMP) ' ||
            'where EVT.BDCODTIPO = 11 and EVT.BDCODAMB = 1 and EVT.BDCODEMP = '|| :bdcodemp || ' and (substring(EVT.BDREFERENCIA from 1 for 4) = '|| :bdano ||') ' ||
            'group by EVT.BDCODEMP, EVT.BDCODTIPO, EVT.BDREFERENCIA, R ' ||
            'union ' ||
            'select substring(C.BDREFERENCIA from 5 for 6) BDREFERENCIA, 0 BDINTEGRADO, cast('|| '''01/01/2020''' ||' as timestamp) BDGERADO, C.BDCODEMP, ' ||
            'iif(C.BDREFERENCIA >= cast(substring(BDDATAOBRIGREINF from 1 for 4) || substring(BDDATAOBRIGREINF from 6 for 2) as integer), 0, 1) as R ' ||
            'from (select (select BDREFERENCIA ' ||
            'from DEC_REFERENCIA('||:wano||', BDORDEM)), BDDATAOBRIGREINF, BDCODEMP ' ||
            'from (select first 12 GETORDEMSEQUENCIAL(0) BDORDEM, EMP.BDDATAOBRIGREINF, EMP.BDCODEMP ' ||
            'from VEF_REINF_EVT EVT ' ||
            'join TEMPRESAS EMP on ('|| :bdcodemp ||' = EMP.BDCODEMP) ' ||
            ')) C) EVT) MES ' ||
            'group by MES.BDCODEMP) MESES ';

            EXECUTE STATEMENT :WSQLREINF INTO reinf01, reinf02, reinf03, reinf04, reinf05, reinf06,
            reinf07, reinf08, reinf09, reinf10, reinf11, reinf12;

            if ((:reinf01 = 0) or (:reinf01 = 3) or (:reinf01 is null)) then BDREINF01 = C_STATUS_NAO_INTEGRADO; if (:reinf01 = 1) then BDREINF01 = C_STATUS_INTEGRADO; if (:reinf01 = 2) then BDREINF01 = C_STATUS_SEM_CALCULO; if (:reinf01 = 5) then BDREINF01 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinf02 = 0) or (:reinf02 = 3) or (:reinf02 is null)) then BDREINF02 = C_STATUS_NAO_INTEGRADO; if (:reinf02 = 1) then BDREINF02 = C_STATUS_INTEGRADO; if (:reinf02 = 2) then BDREINF02 = C_STATUS_SEM_CALCULO; if (:reinf02 = 5) then BDREINF02 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinf03 = 0) or (:reinf03 = 3) or (:reinf03 is null)) then BDREINF03 = C_STATUS_NAO_INTEGRADO; if (:reinf03 = 1) then BDREINF03 = C_STATUS_INTEGRADO; if (:reinf03 = 2) then BDREINF03 = C_STATUS_SEM_CALCULO; if (:reinf03 = 5) then BDREINF03 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinf04 = 0) or (:reinf04 = 3) or (:reinf04 is null)) then BDREINF04 = C_STATUS_NAO_INTEGRADO; if (:reinf04 = 1) then BDREINF04 = C_STATUS_INTEGRADO; if (:reinf04 = 2) then BDREINF04 = C_STATUS_SEM_CALCULO; if (:reinf04 = 5) then BDREINF04 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinf05 = 0) or (:reinf05 = 3) or (:reinf05 is null)) then BDREINF05 = C_STATUS_NAO_INTEGRADO; if (:reinf05 = 1) then BDREINF05 = C_STATUS_INTEGRADO; if (:reinf05 = 2) then BDREINF05 = C_STATUS_SEM_CALCULO; if (:reinf05 = 5) then BDREINF05 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinf06 = 0) or (:reinf06 = 3) or (:reinf06 is null)) then BDREINF06 = C_STATUS_NAO_INTEGRADO; if (:reinf06 = 1) then BDREINF06 = C_STATUS_INTEGRADO; if (:reinf06 = 2) then BDREINF06 = C_STATUS_SEM_CALCULO; if (:reinf06 = 5) then BDREINF06 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinf07 = 0) or (:reinf07 = 3) or (:reinf07 is null)) then BDREINF07 = C_STATUS_NAO_INTEGRADO; if (:reinf07 = 1) then BDREINF07 = C_STATUS_INTEGRADO; if (:reinf07 = 2) then BDREINF07 = C_STATUS_SEM_CALCULO; if (:reinf07 = 5) then BDREINF07 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinf08 = 0) or (:reinf08 = 3) or (:reinf08 is null)) then BDREINF08 = C_STATUS_NAO_INTEGRADO; if (:reinf08 = 1) then BDREINF08 = C_STATUS_INTEGRADO; if (:reinf08 = 2) then BDREINF08 = C_STATUS_SEM_CALCULO; if (:reinf08 = 5) then BDREINF08 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinf09 = 0) or (:reinf09 = 3) or (:reinf09 is null)) then BDREINF09 = C_STATUS_NAO_INTEGRADO; if (:reinf09 = 1) then BDREINF09 = C_STATUS_INTEGRADO; if (:reinf09 = 2) then BDREINF09 = C_STATUS_SEM_CALCULO; if (:reinf09 = 5) then BDREINF09 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinf10 = 0) or (:reinf10 = 3) or (:reinf10 is null)) then BDREINF10 = C_STATUS_NAO_INTEGRADO; if (:reinf10 = 1) then BDREINF10 = C_STATUS_INTEGRADO; if (:reinf10 = 2) then BDREINF10 = C_STATUS_SEM_CALCULO; if (:reinf10 = 5) then BDREINF10 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinf11 = 0) or (:reinf11 = 3) or (:reinf11 is null)) then BDREINF11 = C_STATUS_NAO_INTEGRADO; if (:reinf11 = 1) then BDREINF11 = C_STATUS_INTEGRADO; if (:reinf11 = 2) then BDREINF11 = C_STATUS_SEM_CALCULO; if (:reinf11 = 5) then BDREINF11 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinf12 = 0) or (:reinf12 = 3) or (:reinf12 is null)) then BDREINF12 = C_STATUS_NAO_INTEGRADO; if (:reinf12 = 1) then BDREINF12 = C_STATUS_INTEGRADO; if (:reinf12 = 2) then BDREINF12 = C_STATUS_SEM_CALCULO; if (:reinf12 = 5) then BDREINF12 = C_STATUS_ANTERIOR_OBRIG;


            -- Reinf - 5011
             SETORDEMSEQUENCIAL(0);
            :WSQLREINF = 'select MESES.JAN, MESES.FEV, MESES.MAR, MESES.ABR, MESES.MAI, MESES.JUN, MESES.JUL, MESES.AGO, MESES.SETT, MESES.OUT, MESES.NOV, MESES.DEZ ' ||
            'from (select MES.BDCODEMP, max(MES.BDMES01) JAN, max(MES.BDMES02) FEV, max(MES.BDMES03) MAR, max(MES.BDMES04) ABR, max(MES.BDMES05) MAI, max(MES.BDMES06) JUN, max(MES.BDMES07) JUL, max(MES.BDMES08) AGO, ' ||
            'max(MES.BDMES09) SETT, max(MES.BDMES10) OUT, max(MES.BDMES11) NOV, max(MES.BDMES12) DEZ ' ||
            'from (select iif(EVT.BDREFERENCIA = 01, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES01, iif(EVT.BDREFERENCIA = 02, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES02, ' ||
            'iif(EVT.BDREFERENCIA = 03, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES03, iif(EVT.BDREFERENCIA = 04, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES04, ' ||
            'iif(EVT.BDREFERENCIA = 05, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES05, iif(EVT.BDREFERENCIA = 06, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES06, ' ||
            'iif(EVT.BDREFERENCIA = 07, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES07, iif(EVT.BDREFERENCIA = 08, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES08, ' ||
            'iif(EVT.BDREFERENCIA = 09, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES09, iif(EVT.BDREFERENCIA = 10, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES10, ' ||
            'iif(EVT.BDREFERENCIA = 11, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES11, iif(EVT.BDREFERENCIA = 12, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES12, EVT.BDREFERENCIA, ' ||
            'EVT.BDGERADO, EVT.BDCODEMP, EVT.R ' ||
            'from (select substring(EVT.BDREFERENCIA from 5 for 6) BDREFERENCIA, min(EVT.BDINTEGRADO) BDINTEGRADO, ' ||
            'max(EVT.BDGERADO) BDGERADO, EVT.BDCODEMP, iif(EVT.BDREFERENCIA >= cast(substring(BDDATAOBRIGREINF from 1 for 4) || substring(BDDATAOBRIGREINF from 6 for 2) as integer), 0, 1) as R ' ||
            'from VEF_REINF_EVT EVT ' ||
            'join TEMPRESAS EMP on (EVT.BDCODEMP = EMP.BDCODEMP) ' ||
            'where EVT.BDCODTIPO = 15 and EVT.BDCODAMB = 1 and EVT.BDCODEMP = '|| :bdcodemp || ' and (substring(EVT.BDREFERENCIA from 1 for 4) = '|| :bdano ||') ' ||
            'group by EVT.BDCODEMP, EVT.BDCODTIPO, EVT.BDREFERENCIA, R ' ||
            'union ' ||
            'select substring(C.BDREFERENCIA from 5 for 6) BDREFERENCIA, 0 BDINTEGRADO, cast('|| '''01/01/2020''' ||' as timestamp) BDGERADO, C.BDCODEMP, ' ||
            'iif(C.BDREFERENCIA >= cast(substring(BDDATAOBRIGREINF from 1 for 4) || substring(BDDATAOBRIGREINF from 6 for 2) as integer), 0, 1) as R ' ||
            'from (select (select BDREFERENCIA ' ||
            'from DEC_REFERENCIA('||:wano||', BDORDEM)), BDDATAOBRIGREINF, BDCODEMP ' ||
            'from (select first 12 GETORDEMSEQUENCIAL(0) BDORDEM, EMP.BDDATAOBRIGREINF, EMP.BDCODEMP ' ||
            'from VEF_REINF_EVT EVT ' ||
            'join TEMPRESAS EMP on ('|| :bdcodemp ||' = EMP.BDCODEMP) ' ||
            ')) C) EVT) MES ' ||
            'group by MES.BDCODEMP) MESES ';
        
            EXECUTE STATEMENT :WSQLREINF INTO reinftotal01, reinftotal02, reinftotal03, reinftotal04, reinftotal05, reinftotal06,
            reinftotal07, reinftotal08, reinftotal09, reinftotal10, reinftotal11, reinftotal12;

            if ((:reinftotal01 = 0) or (:reinftotal01 is null)) then BDR01 = C_STATUS_NAO_INTEGRADO; if (:reinftotal01 = 1) then BDR01 = C_STATUS_INTEGRADO; if (:reinftotal01 = 5) then BDR01 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinftotal02 = 0) or (:reinftotal02 is null)) then BDR02 = C_STATUS_NAO_INTEGRADO; if (:reinftotal02 = 1) then BDR02 = C_STATUS_INTEGRADO; if (:reinftotal02 = 5) then BDR02 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinftotal03 = 0) or (:reinftotal03 is null)) then BDR03 = C_STATUS_NAO_INTEGRADO; if (:reinftotal03 = 1) then BDR03 = C_STATUS_INTEGRADO; if (:reinftotal03 = 5) then BDR03 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinftotal04 = 0) or (:reinftotal04 is null)) then BDR04 = C_STATUS_NAO_INTEGRADO; if (:reinftotal04 = 1) then BDR04 = C_STATUS_INTEGRADO; if (:reinftotal04 = 5) then BDR04 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinftotal05 = 0) or (:reinftotal05 is null)) then BDR05 = C_STATUS_NAO_INTEGRADO; if (:reinftotal05 = 1) then BDR05 = C_STATUS_INTEGRADO; if (:reinftotal05 = 5) then BDR05 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinftotal06 = 0) or (:reinftotal06 is null)) then BDR06 = C_STATUS_NAO_INTEGRADO; if (:reinftotal06 = 1) then BDR06 = C_STATUS_INTEGRADO; if (:reinftotal06 = 5) then BDR06 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinftotal07 = 0) or (:reinftotal07 is null)) then BDR07 = C_STATUS_NAO_INTEGRADO; if (:reinftotal07 = 1) then BDR07 = C_STATUS_INTEGRADO; if (:reinftotal07 = 5) then BDR07 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinftotal08 = 0) or (:reinftotal08 is null)) then BDR08 = C_STATUS_NAO_INTEGRADO; if (:reinftotal08 = 1) then BDR08 = C_STATUS_INTEGRADO; if (:reinftotal08 = 5) then BDR08 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinftotal09 = 0) or (:reinftotal09 is null)) then BDR09 = C_STATUS_NAO_INTEGRADO; if (:reinftotal09 = 1) then BDR09 = C_STATUS_INTEGRADO; if (:reinftotal09 = 5) then BDR09 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinftotal10 = 0) or (:reinftotal10 is null)) then BDR10 = C_STATUS_NAO_INTEGRADO; if (:reinftotal10 = 1) then BDR10 = C_STATUS_INTEGRADO; if (:reinftotal10 = 5) then BDR10 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinftotal11 = 0) or (:reinftotal11 is null)) then BDR11 = C_STATUS_NAO_INTEGRADO; if (:reinftotal11 = 1) then BDR11 = C_STATUS_INTEGRADO; if (:reinftotal11 = 5) then BDR11 = C_STATUS_ANTERIOR_OBRIG;
            if ((:reinftotal12 = 0) or (:reinftotal12 is null)) then BDR12 = C_STATUS_NAO_INTEGRADO; if (:reinftotal12 = 1) then BDR12 = C_STATUS_INTEGRADO; if (:reinftotal12 = 5) then BDR12 = C_STATUS_ANTERIOR_OBRIG;


            if (:bdano > EXTRACT(YEAR FROM CURRENT_DATE) ) then
               begin
                  BDR01 = C_STATUS_NAO_INTEGRADO; BDR02 = C_STATUS_NAO_INTEGRADO; BDR03 = C_STATUS_NAO_INTEGRADO; BDR04 = C_STATUS_NAO_INTEGRADO;
                  BDR05 = C_STATUS_NAO_INTEGRADO; BDR06 = C_STATUS_NAO_INTEGRADO; BDR07 = C_STATUS_NAO_INTEGRADO; BDR08 = C_STATUS_NAO_INTEGRADO;
                  BDR09 = C_STATUS_NAO_INTEGRADO; BDR10 = C_STATUS_NAO_INTEGRADO; BDR11 = C_STATUS_NAO_INTEGRADO; BDR12 = C_STATUS_NAO_INTEGRADO;

                  BDREINF01 = C_STATUS_NAO_INTEGRADO; BDREINF02 = C_STATUS_NAO_INTEGRADO; BDREINF03 = C_STATUS_NAO_INTEGRADO; BDREINF04 = C_STATUS_NAO_INTEGRADO;
                  BDREINF05 = C_STATUS_NAO_INTEGRADO; BDREINF06 = C_STATUS_NAO_INTEGRADO; BDREINF07 = C_STATUS_NAO_INTEGRADO; BDREINF08 = C_STATUS_NAO_INTEGRADO;
                  BDREINF09 = C_STATUS_NAO_INTEGRADO; BDREINF10 = C_STATUS_NAO_INTEGRADO; BDREINF11 = C_STATUS_NAO_INTEGRADO; BDREINF12 = C_STATUS_NAO_INTEGRADO;
               end


            -- eSocial - 5011
            SETORDEMSEQUENCIAL(0);
            :bdrefdez = :bdano ||'12';
            :bdref12 = :bdano + 1;
            :bdref12 = :bdref12 ||'01';
            :WSQLREINF = 'select MESES.JAN, MESES.FEV, MESES.MAR, MESES.ABR, MESES.MAI, MESES.JUN, MESES.JUL, MESES.AGO, MESES.SETT, MESES.OUT, MESES.NOV, MESES.DEZ, MESES.DECI ' ||
            'from (select MES.BDCODEMP, max(MES.BDMES01) JAN, max(MES.BDMES02) FEV, max(MES.BDMES03) MAR, max(MES.BDMES04) ABR, max(MES.BDMES05) MAI, max(MES.BDMES06) JUN, max(MES.BDMES07) JUL, max(MES.BDMES08) AGO, ' ||
            'max(MES.BDMES09) SETT, max(MES.BDMES10) OUT, max(MES.BDMES11) NOV, max(MES.BDMES12) DEZ, max(MES.BDMES13) DECI ' ||
            'from (select iif(EVT.BDREFERENCIA = 01, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES01, iif(EVT.BDREFERENCIA = 02, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES02, ' ||
            'iif(EVT.BDREFERENCIA = 03, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES03, iif(EVT.BDREFERENCIA = 04, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES04, ' ||
            'iif(EVT.BDREFERENCIA = 05, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES05, iif(EVT.BDREFERENCIA = 06, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES06, ' ||
            'iif(EVT.BDREFERENCIA = 07, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES07, iif(EVT.BDREFERENCIA = 08, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES08, ' ||
            'iif(EVT.BDREFERENCIA = 09, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES09, iif(EVT.BDREFERENCIA = 10, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES10, ' ||
            'iif(EVT.BDREFERENCIA = 11, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES11, iif(EVT.BDREFERENCIA = 12, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES12, ' ||
            'iif(EVT.BDREFERENCIA = 13, iif(EVT.R = 0, EVT.BDINTEGRADO, 5), 0) BDMES13, EVT.BDREFERENCIA, ' ||
            'EVT.BDGERADO, EVT.BDCODEMP, EVT.R '||
            'from (select substring(EVT.BDREFARQ from 5 for 6) BDREFERENCIA, min(EVT.BDSTATUS) BDINTEGRADO, max(EVT.BDDATAGERADO) BDGERADO, EVT.BDCODEMP, '||
            'iif(EVT.BDREFARQ >= cast(substring(BDDATAINIPERIOD from 1 for 4) || substring(BDDATAINIPERIOD from 6 for 2) as integer), 0, 1) as R '||
            'from VRH_ESOCIAL_TARQUIVO EVT '||
            'join VRH_ESOCIAL_TFASEAMENTO EMP on (EVT.BDCODEMP = EMP.BDCODEMP) '||
            'where EVT.BDCODTIPO = 42 and EVT.BDCODEMP = '|| :bdcodemp || ' and (substring(EVT.BDREFARQ from 1 for 4) = '|| :bdano ||') '||
            'group by EVT.BDCODEMP, EVT.BDCODTIPO, EVT.BDREFARQ, R '||
            'union '||
            'select 13 as BDREFERENCIA, min(EVT.BDSTATUS) BDINTEGRADO, max(EVT.BDDATAGERADO) BDGERADO, EVT.BDCODEMP, '||
            'iif(EVT.BDREFARQ >= cast(substring(BDDATAINIPERIOD from 1 for 4) || substring(BDDATAINIPERIOD from 6 for 2) as integer), 0, 1) as R '||
            'from VRH_ESOCIAL_TARQUIVO EVT '||
            'join VRH_ESOCIAL_TFASEAMENTO EMP on (EVT.BDCODEMP = EMP.BDCODEMP) '||
            'where EVT.BDCODTIPO = 42 and EVT.BDCODEMP = '|| :bdcodemp || ' and EVT.BDAPURACAOANUAL = '||'''TRUE'''||' and EVT.BDREFARQ = '|| :bdrefdez ||' '||
            'group by EVT.BDCODEMP, EVT.BDCODTIPO, EVT.BDREFARQ, R '||
            'union '||
            'select substring(C.BDREFERENCIA from 5 for 6) BDREFERENCIA, 0 BDINTEGRADO, cast('|| '''01/01/2020''' ||' as date) BDGERADO, C.BDCODEMP, '||
            'iif(C.BDREFERENCIA >= cast(substring(BDDATAINIPERIOD from 1 for 4) || substring(BDDATAINIPERIOD from 6 for 2) as integer), 0, 1) as R '||
            'from (select (select BDREFERENCIA from DEC_REFERENCIA('||:bdref12||', BDORDEM)), BDDATAINIPERIOD, BDCODEMP '||
            'from (select first 12 GETORDEMSEQUENCIAL(0) BDORDEM, EMP.BDDATAINIPERIOD, EMP.BDCODEMP '||
            'from VRH_ESOCIAL_TARQUIVO EVT '||
            'join VRH_ESOCIAL_TFASEAMENTO EMP on ('|| :bdcodemp ||' = EMP.BDCODEMP) '||
            ')) C) EVT) MES ' ||
            'group by MES.BDCODEMP) MESES';

        
            EXECUTE STATEMENT :WSQLREINF INTO ESOCIALTOTAL01, ESOCIALTOTAL02, ESOCIALTOTAL03, ESOCIALTOTAL04, ESOCIALTOTAL05, ESOCIALTOTAL06,
            ESOCIALTOTAL07, ESOCIALTOTAL08, ESOCIALTOTAL09, ESOCIALTOTAL10, ESOCIALTOTAL11, ESOCIALTOTAL12, ESOCIALTOTAL13;

            if (:ESOCIALTOTAL01 <> 2) then BDS01 = C_STATUS_NAO_INTEGRADO; if (:ESOCIALTOTAL01 = 2) then BDS01 = C_STATUS_INTEGRADO; if (:ESOCIALTOTAL01 = 5) then BDS01 = C_STATUS_ANTERIOR_OBRIG;
            if (:ESOCIALTOTAL02 <> 2) then BDS02 = C_STATUS_NAO_INTEGRADO; if (:ESOCIALTOTAL02 = 2) then BDS02 = C_STATUS_INTEGRADO; if (:ESOCIALTOTAL02 = 5) then BDS02 = C_STATUS_ANTERIOR_OBRIG;
            if (:ESOCIALTOTAL03 <> 2) then BDS03 = C_STATUS_NAO_INTEGRADO; if (:ESOCIALTOTAL03 = 2) then BDS03 = C_STATUS_INTEGRADO; if (:ESOCIALTOTAL03 = 5) then BDS03 = C_STATUS_ANTERIOR_OBRIG;
            if (:ESOCIALTOTAL04 <> 2) then BDS04 = C_STATUS_NAO_INTEGRADO; if (:ESOCIALTOTAL04 = 2) then BDS04 = C_STATUS_INTEGRADO; if (:ESOCIALTOTAL04 = 5) then BDS04 = C_STATUS_ANTERIOR_OBRIG;
            if (:ESOCIALTOTAL05 <> 2) then BDS05 = C_STATUS_NAO_INTEGRADO; if (:ESOCIALTOTAL05 = 2) then BDS05 = C_STATUS_INTEGRADO; if (:ESOCIALTOTAL05 = 5) then BDS05 = C_STATUS_ANTERIOR_OBRIG;
            if (:ESOCIALTOTAL06 <> 2) then BDS06 = C_STATUS_NAO_INTEGRADO; if (:ESOCIALTOTAL06 = 2) then BDS06 = C_STATUS_INTEGRADO; if (:ESOCIALTOTAL06 = 5) then BDS06 = C_STATUS_ANTERIOR_OBRIG;
            if (:ESOCIALTOTAL07 <> 2) then BDS07 = C_STATUS_NAO_INTEGRADO; if (:ESOCIALTOTAL07 = 2) then BDS07 = C_STATUS_INTEGRADO; if (:ESOCIALTOTAL07 = 5) then BDS07 = C_STATUS_ANTERIOR_OBRIG;
            if (:ESOCIALTOTAL08 <> 2) then BDS08 = C_STATUS_NAO_INTEGRADO; if (:ESOCIALTOTAL08 = 2) then BDS08 = C_STATUS_INTEGRADO; if (:ESOCIALTOTAL08 = 5) then BDS08 = C_STATUS_ANTERIOR_OBRIG;
            if (:ESOCIALTOTAL09 <> 2) then BDS09 = C_STATUS_NAO_INTEGRADO; if (:ESOCIALTOTAL09 = 2) then BDS09 = C_STATUS_INTEGRADO; if (:ESOCIALTOTAL09 = 5) then BDS09 = C_STATUS_ANTERIOR_OBRIG;
            if (:ESOCIALTOTAL10 <> 2) then BDS10 = C_STATUS_NAO_INTEGRADO; if (:ESOCIALTOTAL10 = 2) then BDS10 = C_STATUS_INTEGRADO; if (:ESOCIALTOTAL10 = 5) then BDS10 = C_STATUS_ANTERIOR_OBRIG;
            if (:ESOCIALTOTAL11 <> 2) then BDS11 = C_STATUS_NAO_INTEGRADO; if (:ESOCIALTOTAL11 = 2) then BDS11 = C_STATUS_INTEGRADO; if (:ESOCIALTOTAL11 = 5) then BDS11 = C_STATUS_ANTERIOR_OBRIG;
            if (:ESOCIALTOTAL12 <> 2) then BDS12 = C_STATUS_NAO_INTEGRADO; if (:ESOCIALTOTAL12 = 2) then BDS12 = C_STATUS_INTEGRADO; if (:ESOCIALTOTAL12 = 5) then BDS12 = C_STATUS_ANTERIOR_OBRIG;
            if (:ESOCIALTOTAL13 <> 2) then BDS13 = C_STATUS_NAO_INTEGRADO; if (:ESOCIALTOTAL13 = 2) then BDS13 = C_STATUS_INTEGRADO; if ((:ESOCIALTOTAL13 = 5) or (:ESOCIALTOTAL12 = 5)) then BDS13 = C_STATUS_ANTERIOR_OBRIG;
            -- Fim: Painel eSocial/Reinf/DCTFWeb - Carlos Xavier 29062022 --

    IF (wretornar <> 1) THEN
       BEGIN
         bdperiodicos01 = c_status_nao_integrado; bddctfweb01 = c_status_nao_integrado; BDS01 = c_status_nao_integrado;
         bdperiodicos02 = c_status_nao_integrado; bddctfweb02 = c_status_nao_integrado; BDS02 = c_status_nao_integrado;
         bdperiodicos03 = c_status_nao_integrado; bddctfweb03 = c_status_nao_integrado; BDS03 = c_status_nao_integrado;
         bdperiodicos04 = c_status_nao_integrado; bddctfweb04 = c_status_nao_integrado; BDS04 = c_status_nao_integrado;
         bdperiodicos05 = c_status_nao_integrado; bddctfweb05 = c_status_nao_integrado; BDS05 = c_status_nao_integrado;
         bdperiodicos06 = c_status_nao_integrado; bddctfweb06 = c_status_nao_integrado; BDS06 = c_status_nao_integrado;
         bdperiodicos07 = c_status_nao_integrado; bddctfweb07 = c_status_nao_integrado; BDS07 = c_status_nao_integrado;
         bdperiodicos08 = c_status_nao_integrado; bddctfweb08 = c_status_nao_integrado; BDS08 = c_status_nao_integrado;
         bdperiodicos09 = c_status_nao_integrado; bddctfweb09 = c_status_nao_integrado; BDS09 = c_status_nao_integrado;
         bdperiodicos10 = c_status_nao_integrado; bddctfweb10 = c_status_nao_integrado; BDS10 = c_status_nao_integrado;
         bdperiodicos11 = c_status_nao_integrado; bddctfweb11 = c_status_nao_integrado; BDS11 = c_status_nao_integrado;
         bdperiodicos12 = c_status_nao_integrado; bddctfweb12 = c_status_nao_integrado; BDS12 = c_status_nao_integrado;
         bdperiodicos13 = c_status_nao_integrado; bddctfweb13 = c_status_nao_integrado; BDS13 = c_status_nao_integrado;
         SUSPEND;
       END
    ELSE
       BEGIN
         SUSPEND;
  END
  END


END
^

-- 125979 - Raphael Teodoro - 15/01/2020
CREATE OR ALTER PROCEDURE SP_VRH_PAINEL_INFO_COMPL (
    PRCODEMP varchar(10000) not null)
returns (
    BDCODEMP integer,
    BDDATAINIATIVEMP date,
    BDMATRIZNAOCADSIS type of DM_BOOLEAN,
    BDSITEMPMAT type of DM_BOOLEAN,
    BDSITUACAOESOCIALMAT integer,
    BDDATAFASE1 date,
    BDDATAFASE2 date,
    BDTEMCOLABATIVO type of DM_BOOLEAN,
    BDSINCFASE1 date,
    BDSINCFASE2 date,
    BDREFDCTFWEB integer)
as
declare variable WDATAININAOPERIOD date;
declare variable WSINCRONIZADA type of DM_BOOLEAN;
declare variable WDATASINCRONIZADA date;
declare variable WEMPRESA type of DM_BOOLEAN;
declare variable WESTAB type of DM_BOOLEAN;
declare variable WCOLMOV type of DM_BOOLEAN;
declare variable WCONMOV type of DM_BOOLEAN;
declare variable WREFDCTFWEB integer;
BEGIN
  IF (prcodemp = '') THEN
     prcodemp = '1=1';

  FOR EXECUTE STATEMENT 'SELECT EMP.BDCODEMP, EMP.BDDATAINIATIVEMP, EMP.BDMATRIZNAOCADSIS, EMP.BDSINCRONIZADA,' ||
                         ' SINC.BDDATASINCRONIZADA, SINC.BDEMPRESA, SINC.BDESTAB, SINC.BDCOLMOV, SINC.BDCONMOV,' ||
                         ' MAT.bdsituacaoesocial, MATREF.bdsitemp,' ||
                         ' ( SELECT FIRST 1 TARQ.BDDATARETORNO' ||
                           ' FROM VRH_ESOCIAL_TARQUIVO TARQ' ||
                           ' WHERE (TARQ.BDCODEMP = EMP.BDCODEMP)' ||
                             ' AND (TARQ.BDSTATUS = 2)' ||
                             ' AND ((TARQ.BDCHAVE STARTING WITH ''S1000_'') OR' ||
                                  ' (TARQ.BDCHAVE STARTING WITH ''S1005_''))' ||
                           ' ORDER BY TARQ.BDCODEMP, TARQ.BDSTATUS, TARQ.BDDATAEVENTO' ||
                         ' ) AS BDDATAFASE1,' ||
                         ' ( SELECT FIRST 1 TARQ.BDDATARETORNO' ||
                           ' FROM VRH_ESOCIAL_TARQUIVO TARQ' ||
                           ' WHERE (TARQ.BDCODEMP = EMP.BDCODEMP)' ||
                             ' AND (TARQ.BDSTATUS = 2)' ||
                             ' AND ((TARQ.BDCHAVE STARTING WITH ''S2200_'') OR' ||
                                  ' (TARQ.BDCHAVE STARTING WITH ''S2300_''))' ||
                           ' ORDER BY TARQ.BDCODEMP, TARQ.BDSTATUS, TARQ.BDDATAEVENTO' ||
                         ' ) AS BDDATAFASE2,' ||
                         ' FAS.BDDATAININAOPERIOD, ' ||
                         ' COALESCE(FAS.BDREFINIDCTFWEB, 0) BDREFINIDCTFWEB '||
                       ' FROM TEMPRESAS EMP' ||
                       ' LEFT OUTER JOIN VRH_ESOCIAL_TFASEAMENTO FAS ON (FAS.BDCODEMP = EMP.BDCODEMP)' ||
                       ' LEFT OUTER JOIN TEMPRESAS MAT ON (MAT.BDCODEMP = EMP.BDCODMATRIZ)' ||
                       ' LEFT OUTER JOIN TEMPRESAS_REF MATREF ON (MATREF.BDCODEMP = EMP.BDCODMATRIZ)' ||
                            ' AND (MATREF.BDREFEMP = (SELECT FIRST 1 AUX.BDREFEMP' ||
                                                    ' FROM TEMPRESAS_REF AUX' ||
                                                    ' WHERE (AUX.BDCODEMP = EMP.BDCODMATRIZ)' ||
                                                    ' ORDER BY AUX.BDCODEMP DESC, AUX.BDREFEMP DESC))' ||
                       ' LEFT OUTER JOIN VRH_ESOCIAL_TSINCRONIZACAO SINC ON (SINC.bdcodemp = EMP.bdcodemp)' ||
                       ' WHERE (' || prcodemp || ')' ||
                       ' ORDER BY EMP.BDCODEMP'
  INTO :bdcodemp, :bddatainiativemp, :bdmatriznaocadsis, :wsincronizada,
       :wdatasincronizada, :wempresa, :westab, :wcolmov, :wconmov,
       :bdsituacaoesocialmat, :bdsitempmat,
       :bddatafase1,
       :bddatafase2,
       :wdataininaoperiod,
       :wrefdctfweb
  DO
  BEGIN
    IF ((bddatafase2 IS NOT NULL) OR
        (EXISTS(SELECT FIRST 1 *
                FROM VRH_EMP_TCOLCON COLCON
                LEFT OUTER JOIN VRH_EMP_TRESCISAO RES ON (RES.BDCODEMP = COLCON.BDCODEMP) AND (RES.BDCODCOL = COLCON.BDCODCOL)
                WHERE (COLCON.BDCODEMP = :bdcodemp)
                  AND (COLCON.BDDATAADMCOL <= :wdataininaoperiod)
                  AND ((RES.BDDATARESCISAO IS NULL) OR (RES.BDDATARESCISAO >= :wdataininaoperiod))))) THEN
       bdtemcolabativo = 'TRUE';
    ELSE
       bdtemcolabativo = 'FALSE';

    IF ((wdatasincronizada IS NULL) AND (wsincronizada = 'TRUE')) THEN
       wdatasincronizada = '01-01-1800';

    IF ((wempresa = 'TRUE') or (westab = 'TRUE')) THEN
       bdsincfase1 = wdatasincronizada;
    ELSE
       bdsincfase1 = NULL;

    IF ((wcolmov = 'TRUE') or (wconmov = 'TRUE')) THEN
       bdsincfase2 = wdatasincronizada;
    ELSE
       bdsincfase2 = NULL;

    bdrefdctfweb = wrefdctfweb;

    SUSPEND;
  END
END
^

-- 125979 - Raphael Teodoro - 11/02/2020
CREATE OR ALTER procedure SP_VRH_PAINEL_CALCULADO (
    PRCODEMP varchar(10000) not null,
    PRANOINI integer = 2018,
    PRANOFIM integer = 0)
returns (
    BDCODEMP integer,
    BDANO integer,
    BDPERFOLHANORMAL varchar(13),
    BDPERFOLHAINTERMITENTE varchar(13),
    BDPERFOLHAAUTONOMO varchar(13),
    BDPERFOLHAADSALARIO varchar(13),
    BDPERFOLHACOMPLEMENTAR varchar(13),
    BDPERFOLHAFERIAS varchar(13),
    BDPERFOLHAAVULSA varchar(13),
    BDPERFOLHA13SALARIO varchar(13),
    BDPERFOLHAAD13SALARIO varchar(13),
    BDPERFOLHACOMP13SALARIO varchar(13),
    BDPERNFFUNRURAL varchar(13),
    BDDCTFWEB varchar(13))
as
declare variable C_PER_CALCULADO char(1) = 1; /* Calculado */
declare variable C_PER_PROCESSADO char(1) = 3; /* Processado */
declare variable C_PER_RECUSADO char(1) = 4; /* Recusado */
declare variable C_PER_REABERTO char(1) = 5; /* Reaberto */
declare variable C_PER_PROC_SEM_DADOS char(1) = 6; /* Processado sem dados */
declare variable C_DCTF_DECLARADO char(1) = 1; /* Declarado */
declare variable C_DCTF_TRANSMITIDO char(1) = 3; /* Transmitido */
declare variable WMES integer;
declare variable WPERFOLHANORMAL char(1);
declare variable WPERFOLHAINTERMITENTE char(1);
declare variable WPERFOLHAAUTONOMO char(1);
declare variable WPERFOLHAADSALARIO char(1);
declare variable WPERFOLHACOMPLEMENTAR char(1);
declare variable WPERFOLHAFERIAS char(1);
declare variable WPERFOLHAAVULSA char(1);
declare variable WPERFOLHA13SALARIO char(1);
declare variable WPERFOLHAAD13SALARIO char(1);
declare variable WPERFOLHACOMP13SALARIO char(1);
declare variable WPERNFFUNRURAL char(1);
declare variable WDCTFWEB char(1);
declare variable WFECHAMENTO timestamp;
declare variable WREABERTURA timestamp;
declare variable WSEMMOVIMENTO type of DM_BOOLEAN;
declare variable WINTEGRADO type of DM_BOOLEAN;
declare variable WSTATUSFECHAMENTO char(1);
BEGIN
  IF (prcodemp = '') THEN
     prcodemp = '1=1';

  IF (pranofim = 0) THEN
     pranofim = EXTRACT(YEAR FROM CAST('Now' AS DATE));

  FOR EXECUTE STATEMENT 'SELECT EMP.bdcodemp, PERIODO.bdint AS bdano, MESES.bdint AS bdmes,' ||
                         ' CASE' ||
                           ' WHEN (MESES.bdint = 13) THEN '' ''' ||
                           ' WHEN (EXISTS(SELECT FIRST 1 CALC.bdcodemp' ||
                                        ' FROM VRHF_EMP_TFOLHANORMAL CALC' ||
                                        ' WHERE (CALC.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (CALC.bdreffn = (PERIODO.bdint * 100) + MESES.bdint)' ||
                           ' )) THEN ''' || c_per_calculado || '''' ||
                           ' WHEN (EXISTS(SELECT FIRST 1 CALC.bdcodemp' ||
                                        ' FROM VRHF_EMP_TFOLHATOMADOR CALC' ||
                                        ' WHERE (CALC.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (CALC.bdreftomador = (PERIODO.bdint * 100) + MESES.bdint)' ||
                           ' )) THEN ''' || c_per_calculado || '''' ||
                           ' ELSE '' ''' ||
                         ' END AS BDFOLHANORMAL,' ||
                         ' CASE' ||
                           ' WHEN (MESES.bdint = 13) THEN '' ''' ||
                           ' WHEN (EXISTS(SELECT FIRST 1 CALC.bdcodemp' ||
                                        ' FROM VRHF_EMP_TFOLHAINT CALC' ||
                                        ' WHERE (CALC.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (CALC.bdreffn = (PERIODO.bdint * 100) + MESES.bdint)' ||
                           ' )) THEN ''' || c_per_calculado || '''' ||
                           ' WHEN (EXISTS(SELECT FIRST 1 CALC.bdcodemp' ||
                                        ' FROM VRHF_EMP_TFOLHATOMINT CALC' ||
                                        ' WHERE (CALC.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (CALC.bdreftomador = (PERIODO.bdint * 100) + MESES.bdint)' ||
                           ' )) THEN ''' || c_per_calculado || '''' ||
                           ' ELSE '' ''' ||
                         ' END AS BDFOLHAINTERM,' ||
                         ' CASE' ||
                           ' WHEN (MESES.bdint = 13) THEN '' ''' ||
                           ' WHEN (EXISTS(SELECT FIRST 1 CALC.bdcodemp' ||
                                        ' FROM VRH_BASE_TSERVTERC CALC' ||
                                        ' WHERE (CALC.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (CALC.bdrefserv = (PERIODO.bdint * 100) + MESES.bdint)' ||
                           ' )) THEN ''' || c_per_calculado || '''' ||
                           ' ELSE '' ''' ||
                         ' END AS BDFOLHAAUT,' ||
                         ' CASE' ||
                           ' WHEN (MESES.bdint = 13) THEN '' ''' ||
                           ' WHEN (EXISTS(SELECT FIRST 1 CALC.bdcodemp' ||
                                        ' FROM VRHF_EMP_TADSAL CALC' ||
                                        ' WHERE (CALC.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (CALC.bdrefad = (PERIODO.bdint * 100) + MESES.bdint)' ||
                           ' )) THEN ''' || c_per_calculado || '''' ||
                           ' ELSE '' ''' ||
                         ' END AS BDFOLHAADSAL,' ||
                         ' CASE' ||
                           ' WHEN (MESES.bdint = 13) THEN '' ''' ||
                           ' WHEN (EXISTS(SELECT FIRST 1 CALC.bdcodemp' ||
                                        ' FROM VRHF_EMP_TFOLHACOMP CALC' ||
                                        ' WHERE (CALC.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (CALC.bdrefcomp = (PERIODO.bdint * 100) + MESES.bdint)' ||
                           ' )) THEN ''' || c_per_calculado || '''' ||
                           ' WHEN (EXISTS(SELECT FIRST 1 CALC.bdcodemp' ||
                                        ' FROM VRHF_EMP_TFOLTOMCOMP CALC' ||
                                        ' WHERE (CALC.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (CALC.bdreftomador = (PERIODO.bdint * 100) + MESES.bdint)' ||
                           ' )) THEN ''' || c_per_calculado || '''' ||
                           -- 27813 - Raphael Teodoro - 04/02/2020
                           ' WHEN (EXISTS(SELECT FIRST 1 CALC.bdcodemp' ||
                                        ' FROM VRHF_EMP_TFOLHACOMPINT CALC' ||
                                        ' WHERE (CALC.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (CALC.bdrefcomp = (PERIODO.bdint * 100) + MESES.bdint)' ||
                           ' )) THEN ''' || c_per_calculado || '''' ||
                           -- 27813 - Raphael Teodoro - 04/02/2020
                           ' WHEN (EXISTS(SELECT FIRST 1 CALC.bdcodemp' ||
                                        ' FROM VRHF_EMP_TFOLTOMCOMPINT CALC' ||
                                        ' WHERE (CALC.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (CALC.bdreftomador = (PERIODO.bdint * 100) + MESES.bdint)' ||
                           ' )) THEN ''' || c_per_calculado || '''' ||
                           ' ELSE '' ''' ||
                         ' END AS BDFOLHACOMP,' ||
                         ' CASE' ||
                           ' WHEN (MESES.bdint = 13) THEN '' ''' ||
                           ' WHEN (EXISTS(SELECT FIRST 1 CALC.bdcodemp' ||
                                        ' FROM VRH_EMP_TFERIAS CALC' ||
                                        ' WHERE (CALC.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (CALC.bdrefinife = (PERIODO.bdint * 100) + MESES.bdint)' || -- Busca rapida
                           ' )) THEN ''' || c_per_calculado || '''' ||
                           ' WHEN (EXISTS(SELECT FIRST 1 CALC.bdcodemp' ||
                                        ' FROM VRH_EMP_TFERIAS CALC' ||
                                        ' WHERE (CALC.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND ((PERIODO.bdint * 100) + MESES.bdint BETWEEN CALC.bdrefinife AND CALC.bdreffimfe)' || -- Busca lenta
                           ' )) THEN ''' || c_per_calculado || '''' ||
                           ' ELSE '' ''' ||
                         ' END AS BDFOLHAFERIAS,' ||
                         ' CASE' ||
                           ' WHEN (MESES.bdint = 13) THEN '' ''' ||
                           ' WHEN (EXISTS(SELECT FIRST 1 CALC.bdcodemp' ||
                                        ' FROM VRHF_EMP_TFOLHAAVULSA CALC' ||
                                        ' WHERE (CALC.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (CALC.bdref = (PERIODO.bdint * 100) + MESES.bdint)' ||
                           ' )) THEN ''' || c_per_calculado || '''' ||
                           ' ELSE '' ''' ||
                         ' END AS BDFOLHAAVULSA,' ||
                         ' CASE' ||
                           ' WHEN (MESES.bdint = 13) THEN '' ''' ||
                           ' WHEN (EXISTS(SELECT FIRST 1 CALC.bdcodemp' ||
                                        ' FROM VRHF_EMP_T13SAL CALC' ||
                                        ' WHERE (CALC.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (CALC.bdref13 = (PERIODO.bdint * 100) + MESES.bdint)' ||
                           ' )) THEN ''' || c_per_calculado || '''' ||
                           ' ELSE '' ''' ||
                         ' END AS BDFOLHA13SAL,' ||
                         ' CASE' ||
                           ' WHEN (MESES.bdint = 13) THEN '' ''' ||
                           ' WHEN (EXISTS(SELECT FIRST 1 CALC.bdcodemp' ||
                                        ' FROM VRHF_EMP_TA13SAL CALC' ||
                                        ' WHERE (CALC.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (CALC.bdrefa13 = (PERIODO.bdint * 100) + MESES.bdint)' ||
                           ' )) THEN ''' || c_per_calculado || '''' ||
                           ' ELSE '' ''' ||
                         ' END AS BDFOLHAAD13SAL,' ||
                         ' CASE' ||
                           ' WHEN (MESES.bdint = 13) THEN '' ''' ||
                           ' WHEN (EXISTS(SELECT FIRST 1 CALC.bdcodemp' ||
                                        ' FROM VRHF_EMP_TC13SAL CALC' ||
                                        ' WHERE (CALC.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (CALC.bdrefc13 = (PERIODO.bdint * 100) + MESES.bdint)' ||
                           ' )) THEN ''' || c_per_calculado || '''' ||
                           ' ELSE '' ''' ||
                         ' END AS BDFOLHACOMP13SAL,' ||
                         ' CASE' ||
                           ' WHEN (MESES.bdint = 13) THEN '' ''' ||
                           ' WHEN (EXISTS(SELECT FIRST 1 NF.bdcodemp' ||
                                        ' FROM VRHF_EMP_TNFPRODRURAL NF' ||
                                        ' WHERE (NF.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (NF.bdrefnf = (PERIODO.bdint * 100) + MESES.bdint)' ||
                           ' )) THEN ''' || c_per_calculado || '''' ||
                           ' ELSE '' ''' ||
                         ' END AS BDLANCFUNRURAL,' ||
                         -- 140108 - Raphael Teodoro - 06/08/2020
                         ' CASE' ||
                           ' WHEN (EXISTS(SELECT FIRST 1 DCTF.bdcodemp' ||
                                        ' FROM VRH_EMP_DCTFWEB DCTF' ||
                                        ' WHERE (DCTF.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (DCTF.bdref = (PERIODO.bdint * 100) + MESES.bdint)' ||
                                          ' AND (DCTF.bddatatransmissao IS NULL)' ||
                           ' )) THEN ''' || c_dctf_declarado || '''' ||
                           ' WHEN (EXISTS(SELECT FIRST 1 DCTF.bdcodemp' ||
                                        ' FROM VRH_EMP_DCTFWEB DCTF' ||
                                        ' WHERE (DCTF.bdcodemp = EMP.bdcodemp)' ||
                                          ' AND (DCTF.bdref = (PERIODO.bdint * 100) + MESES.bdint)' ||
                                          ' AND (DCTF.bddatatransmissao IS NOT NULL)' ||
                           ' )) THEN ''' || c_dctf_transmitido || '''' ||
                           ' ELSE '' ''' ||
                         ' END AS BDDCTFWEB,' ||

                         ' FECHAMENTO.bdgeracao,' ||
                         ' FECHAMENTO.bdreabertura,' ||
                         ' FECHAMENTO.bdsemmovimento,' ||
                         ' FECHAMENTO.bdintegrado' ||
                       ' FROM TEMPRESAS EMP' ||
                       ' INNER JOIN vrh_esocial_tfaseamento FAS ON (FAS.bdcodemp = EMP.bdcodemp) AND (FAS.bdopcaoesocial = 1)' ||
                       ' LEFT OUTER JOIN vrh_esocial_tsincronizacao SINC ON (SINC.bdcodemp = EMP.bdcodemp)' ||
                       ' CROSS JOIN SP_ARRAY_INT(' || pranoini || ',' || pranofim || ') PERIODO' ||
                       ' CROSS JOIN SP_ARRAY_INT(1,13) MESES' ||  -- 140108 - Raphael Teodoro - 06/08/2020 - "12" para "13"
                       ' LEFT OUTER JOIN ( SELECT FECH.bdcodemp, FECH.bdref, (FECH.bddata + FECH.bdhora) AS BDGERACAO, (FECH.bddatareab + FECH.bdhorareab) AS BDREABERTURA, FECH.bdsemmovimento, FECH.bdintegrado' ||
                                         ' FROM VRH_ESOCIAL_FECHAMENTO FECH' ||
                                         ' WHERE (FECH.bdcodigo IN (' ||
                                                ' SELECT MAX(ULT.bdcodigo)' ||
                                                ' FROM VRH_ESOCIAL_FECHAMENTO ULT' ||
                                                ' WHERE (ULT.bdcodemp = FECH.bdcodemp)' ||
                                                  ' AND (COALESCE(ULT.bdanual,''FALSE'') <> ''TRUE'')' ||
                                                  ' AND (ULT.bdref = FECH.bdref)))' ||
                                         ' ) FECHAMENTO ON (FECHAMENTO.bdcodemp = EMP.bdcodemp)' ||
                                                     ' AND ((FECHAMENTO.bdref = (PERIODO.bdint * 100) + MESES.bdint) OR' ||
                                                          ' ((MESES.bdint = 13) AND (FECHAMENTO.bdref = (PERIODO.bdint * 100) + 12)))' || -- 140108 - Raphael Teodoro - 06/08/2020 - Considerar fechamento de dezembro
                       ' WHERE (' || prcodemp || ')' ||
                       '   AND ((COALESCE(EMP.BDCODMATRIZ,0) = 0) OR (EMP.BDMATRIZNAOCADSIS = ''TRUE''))' ||
                       ' ORDER BY bdcodemp, bdano, bdmes'
   INTO :bdcodemp, :bdano, :wmes,
     :wperfolhanormal, :wperfolhaintermitente, :wperfolhaautonomo, :wperfolhaadsalario, :wperfolhacomplementar,
     :wperfolhaferias, :wperfolhaavulsa, :wperfolha13salario, :wperfolhaad13salario, :wperfolhacomp13salario, :wpernffunrural,
     :wdctfweb, :wfechamento, :wreabertura, :wsemmovimento, :wintegrado DO
  BEGIN
    IF (wmes = 1) THEN
       BEGIN
         bdperfolhanormal        = '';
         bdperfolhaintermitente  = '';
         bdperfolhaautonomo      = '';
         bdperfolhaadsalario     = '';
         bdperfolhacomplementar  = '';
         bdperfolhaferias        = '';
         bdperfolhaavulsa        = '';
         bdperfolha13salario     = '';
         bdperfolhaad13salario   = '';
         bdperfolhacomp13salario = '';
         bdpernffunrural         = '';
         bddctfweb               = '';
       END

    wstatusfechamento = NULL;
    IF (wfechamento IS NOT NULL) THEN
       BEGIN
         IF (wintegrado <> 'TRUE') THEN
            wstatusfechamento = c_per_recusado;
         ELSE
         IF (wreabertura > wfechamento) THEN
            wstatusfechamento = c_per_reaberto;
         ELSE
         IF (wsemmovimento = 'TRUE') THEN
            wstatusfechamento = c_per_proc_sem_dados;
         ELSE
            wstatusfechamento = c_per_processado;
       END

    bdperfolhanormal        = bdperfolhanormal        || COALESCE(wstatusfechamento, wperfolhanormal);
    bdperfolhaintermitente  = bdperfolhaintermitente  || COALESCE(wstatusfechamento, wperfolhaintermitente);
    bdperfolhaautonomo      = bdperfolhaautonomo      || COALESCE(wstatusfechamento, wperfolhaautonomo);
    bdperfolhaadsalario     = bdperfolhaadsalario     || COALESCE(wstatusfechamento, wperfolhaadsalario);
    bdperfolhacomplementar  = bdperfolhacomplementar  || COALESCE(wstatusfechamento, wperfolhacomplementar);
    bdperfolhaferias        = bdperfolhaferias        || COALESCE(wstatusfechamento, wperfolhaferias);
    bdperfolhaavulsa        = bdperfolhaavulsa        || COALESCE(wstatusfechamento, wperfolhaavulsa);
    bdperfolha13salario     = bdperfolha13salario     || COALESCE(wstatusfechamento, wperfolha13salario);
    bdperfolhaad13salario   = bdperfolhaad13salario   || COALESCE(wstatusfechamento, wperfolhaad13salario);
    bdperfolhacomp13salario = bdperfolhacomp13salario || COALESCE(wstatusfechamento, wperfolhacomp13salario);
    bdpernffunrural         = bdpernffunrural         || COALESCE(wstatusfechamento, wpernffunrural);
    bddctfweb               = bddctfweb               || wdctfweb;

    IF (wmes = 13) THEN
       SUSPEND;
  END
END
^

CREATE OR ALTER TRIGGER TMP_VSUC_EMPRESAS_TLAN_TEMP_BU0 FOR TMP_VSUC_EMPRESAS_TLAN_TEMP
ACTIVE BEFORE UPDATE POSITION 0
AS  
DECLARE VARIABLE wChave INTEGER;
begin
    IF (OLD.BDEDITCHAVE IS NULL) THEN
    BEGIN
      wChave = GETORDEMSEQUENCIAL(1);
      NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - :wChave)+1;
    END
end^
CREATE OR ALTER PROCEDURE SP_COMMIT_IMP_LANC_CONTABIL (
    PRSESSAO INTEGER)
AS
DECLARE VARIABLE WSQL VARCHAR(30000);
DECLARE VARIABLE WFIELDS VARCHAR(5000);
begin
  -- ** LANÇAMENTOS CONTÁBEIS **
  SELECT LIST(BDFIELD) -- Buscando os campos da tabela de lançamentos contábeis
  FROM (
         SELECT TRIM(RDB$FIELD_NAME) AS BDFIELD FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME = 'VSUC_EMPRESAS_TLAN' ORDER BY RDB$FIELD_POSITION
       )
  INTO :WFIELDS;

  wSQL = 'INSERT INTO VSUC_EMPRESAS_TLAN ('||:wFIELDS||') ';
  -- Chave da tabela temporária
  wFIELDS = REPLACE(:wFIELDS, ',BDCHAVE,', ',BDEDITCHAVE,');
  -- Apelido para a tabela temporária
  wFIELDS = REPLACE('TEMP.'||:wFIELDS, ',BD', ',TEMP.BD');

  wSQL = wSQL||'SELECT '||:wFIELDS||' ';
  wSQL = wSQL||'FROM ( ';
  wSQL = wSQL||'      SELECT TLAN_TEMP.* ';
  wSQL = wSQL||'      FROM TMP_VSUC_EMPRESAS_TLAN_TEMP TLAN_TEMP ';
  wSQL = wSQL||'      WHERE TLAN_TEMP.BDSESSAO = '||:PRSESSAO||' ';
  wSQL = wSQL||'      AND  (TLAN_TEMP.BDVINC_BAIXA IS NULL OR TLAN_TEMP.BDVINC_BAIXA collate win_ptbr <> ''TRUE'') ';
  wSQL = wSQL||'      AND NOT EXISTS ( ';
  wSQL = wSQL||'                      SELECT INCO.BDCODINCONSISTENCIA ';
  wSQL = wSQL||'                      FROM VSUC_INCON_TLAN INCO ';
  wSQL = wSQL||'                      WHERE ';
  wSQL = wSQL||'                      INCO.BDSESSAO = TLAN_TEMP.BDSESSAO AND ';
  wSQL = wSQL||'                      INCO.BDCODEMP = TLAN_TEMP.BDCODEMP AND ';
  wSQL = wSQL||'                      INCO.BDCHAVE  = TLAN_TEMP.BDCHAVE ';
  wSQL = wSQL||'                     ) ';
  wSQL = wSQL||'     ) TEMP ';
  EXECUTE STATEMENT :wSQL;

  -- ** LANÇAMENTOS CENTROS DE CUSTOS **

  SELECT LIST(BDFIELD) -- Buscando os campos da tabela de lançamentos dos centros de custos
  FROM (
         SELECT TRIM(RDB$FIELD_NAME) AS BDFIELD FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME = 'VSUC_EMPRESAS_TLCC' ORDER BY RDB$FIELD_POSITION
       )
  INTO :WFIELDS;

  wSQL = 'INSERT INTO VSUC_EMPRESAS_TLCC ('||:wFIELDS||') ';
  -- Chave da tabela temporária
  wFIELDS = REPLACE(:wFIELDS, ',BDCHAVE,', ',BDEDITCHAVE,');
  -- Apelido para a tabela temporária
  wFIELDS = REPLACE('TEMP.'||:wFIELDS, ',BD', ',TEMP.BD');

  wSQL = wSQL||'SELECT '||:wFIELDS||' ';
  wSQL = wSQL||'FROM ( ';
  wSQL = wSQL||'      SELECT TLCC_TEMP.* ';
  wSQL = wSQL||'      FROM TMP_VSUC_EMPRESAS_TLCC_TEMP TLCC_TEMP ';
  wSQL = wSQL||'      LEFT OUTER JOIN TMP_VSUC_EMPRESAS_TLAN_TEMP TLAN_TEMP '
                        ||'on (TLAN_TEMP.BDSESSAO = TLCC_TEMP.BDSESSAO AND '
                        ||' TLAN_TEMP.BDCODEMP    = TLCC_TEMP.BDCODEMP AND'
                        ||' TLAN_TEMP.BDCHAVE     = TLCC_TEMP.BDCHAVE) ';
  wSQL = wSQL||'      WHERE TLCC_TEMP.BDSESSAO = '||:PRSESSAO||' ';
  wSQL = wSQL||'      AND  (TLAN_TEMP.BDVINC_BAIXA IS NULL OR TLAN_TEMP.BDVINC_BAIXA collate win_ptbr <> ''TRUE'') ';
  wSQL = wSQL||'      AND NOT EXISTS ( ';
  wSQL = wSQL||'                      SELECT INCO.BDCODINCONSISTENCIA ';
  wSQL = wSQL||'                      FROM VSUC_INCON_TLAN INCO ';
  wSQL = wSQL||'                      WHERE ';
  wSQL = wSQL||'                      INCO.BDSESSAO = TLCC_TEMP.BDSESSAO AND ';
  wSQL = wSQL||'                      INCO.BDCODEMP = TLCC_TEMP.BDCODEMP AND ';
  wSQL = wSQL||'                      INCO.BDCHAVE  = TLCC_TEMP.BDCHAVE ';
  wSQL = wSQL||'                     ) ';
  wSQL = wSQL||'     ) TEMP ';
  EXECUTE STATEMENT :wSQL;

  -- ** LANÇAMENTOS INCORPORADORAS **

  SELECT LIST(BDFIELD) -- Buscando os campos da tabela de lançamentos das incorporadoras
  FROM (
         SELECT TRIM(RDB$FIELD_NAME) AS BDFIELD FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME = 'VSUC_EMPRESAS_TLINCORP' ORDER BY RDB$FIELD_POSITION
       )
  INTO :WFIELDS;

  wSQL = 'INSERT INTO VSUC_EMPRESAS_TLINCORP ('||:wFIELDS||') ';
  -- Chave da tabela temporária
  wFIELDS = REPLACE(:wFIELDS, ',BDCHAVE,', ',BDEDITCHAVE,');
  -- Apelido para a tabela temporária
  wFIELDS = REPLACE('TEMP.'||:wFIELDS, ',BD', ',TEMP.BD');

  wSQL = wSQL||'SELECT '||:wFIELDS||' ';
  wSQL = wSQL||'FROM ( ';
  wSQL = wSQL||'      SELECT TLINCORP_TEMP.* ';
  wSQL = wSQL||'      FROM TMP_VSUC_EMPRESAS_TLINCORP_TEMP TLINCORP_TEMP ';
  wSQL = wSQL||'      LEFT OUTER JOIN TMP_VSUC_EMPRESAS_TLAN_TEMP TLAN_TEMP '
                        ||'on (TLAN_TEMP.BDSESSAO = TLINCORP_TEMP.BDSESSAO AND '
                        ||' TLAN_TEMP.BDCODEMP    = TLINCORP_TEMP.BDCODEMP AND'
                        ||' TLAN_TEMP.BDCHAVE     = TLINCORP_TEMP.BDCHAVE) ';
  wSQL = wSQL||'      WHERE TLINCORP_TEMP.BDSESSAO = '||:PRSESSAO||' ';
  wSQL = wSQL||'      AND  (TLAN_TEMP.BDVINC_BAIXA IS NULL OR TLAN_TEMP.BDVINC_BAIXA collate win_ptbr <> ''TRUE'') ';
  wSQL = wSQL||'      AND NOT EXISTS ( ';
  wSQL = wSQL||'                      SELECT INCO.BDCODINCONSISTENCIA ';
  wSQL = wSQL||'                      FROM VSUC_INCON_TLAN INCO ';
  wSQL = wSQL||'                      WHERE ';
  wSQL = wSQL||'                      INCO.BDSESSAO = TLINCORP_TEMP.BDSESSAO AND ';
  wSQL = wSQL||'                      INCO.BDCODEMP = TLINCORP_TEMP.BDCODEMP AND ';
  wSQL = wSQL||'                      INCO.BDCHAVE  = TLINCORP_TEMP.BDCHAVE ';
  wSQL = wSQL||'                     ) ';
  wSQL = wSQL||'     ) TEMP ';

  EXECUTE STATEMENT :wSQL;

  -- ** LANÇAMENTOS OBSERVAÇÕES **

  SELECT LIST(BDFIELD) -- Buscando os campos da tabela de lançamentos das observações
  FROM (
         SELECT TRIM(RDB$FIELD_NAME) AS BDFIELD FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME = 'VSUC_EMPRESAS_TOBS' ORDER BY RDB$FIELD_POSITION
       )
  INTO :WFIELDS;

  wSQL = 'INSERT INTO VSUC_EMPRESAS_TOBS ('||:wFIELDS||') ';
  -- Chave da tabela temporária
  wFIELDS = REPLACE(:wFIELDS, ',BDCHAVE,', ',BDEDITCHAVE,');
  -- Apelido para a tabela temporária
  wFIELDS = REPLACE('TEMP.'||:wFIELDS, ',BD', ',TEMP.BD');

  wSQL = wSQL||'SELECT '||:wFIELDS||' ';
  wSQL = wSQL||'FROM ( ';
  wSQL = wSQL||'      SELECT TLOBS_TEMP.* ';
  wSQL = wSQL||'      FROM TMP_VSUC_EMPRESAS_TOBS_TEMP TLOBS_TEMP ';
  wSQL = wSQL||'      LEFT OUTER JOIN TMP_VSUC_EMPRESAS_TLAN_TEMP TLAN_TEMP '
                        ||'on (TLAN_TEMP.BDSESSAO = TLOBS_TEMP.BDSESSAO AND '
                        ||' TLAN_TEMP.BDCODEMP    = TLOBS_TEMP.BDCODEMP AND'
                        ||' TLAN_TEMP.BDCHAVE     = TLOBS_TEMP.BDCHAVE) ';
  wSQL = wSQL||'      WHERE TLOBS_TEMP.BDSESSAO = '||:PRSESSAO||' ';
  wSQL = wSQL||'      AND  (TLAN_TEMP.BDVINC_BAIXA IS NULL OR TLAN_TEMP.BDVINC_BAIXA collate win_ptbr <> ''TRUE'') ';
  wSQL = wSQL||'      AND NOT EXISTS ( ';
  wSQL = wSQL||'                      SELECT INCO.BDCODINCONSISTENCIA ';
  wSQL = wSQL||'                      FROM VSUC_INCON_TLAN INCO ';
  wSQL = wSQL||'                      WHERE ';
  wSQL = wSQL||'                      INCO.BDSESSAO = TLOBS_TEMP.BDSESSAO AND ';
  wSQL = wSQL||'                      INCO.BDCODEMP = TLOBS_TEMP.BDCODEMP AND ';
  wSQL = wSQL||'                      INCO.BDCHAVE  = TLOBS_TEMP.BDCHAVE ';
  wSQL = wSQL||'                     ) ';
  wSQL = wSQL||'     ) TEMP ';

  EXECUTE STATEMENT :wSQL;

 -- ** LANÇAMENTOS PRODUTOR RURAL **

  SELECT LIST(BDFIELD) -- Buscando os campos da tabela de lançamentos das observações
  FROM (
         SELECT TRIM(RDB$FIELD_NAME) AS BDFIELD FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME = 'VSUC_EMPRESAS_TLPR' ORDER BY RDB$FIELD_POSITION
       )
  INTO :WFIELDS;

  wSQL = 'INSERT INTO VSUC_EMPRESAS_TLPR ('||:wFIELDS||') ';
  -- Chave da tabela temporária
  wFIELDS = REPLACE(:wFIELDS, ',BDCHAVE,', ',BDEDITCHAVE,');
  -- Apelido para a tabela temporária
  wFIELDS = REPLACE('TEMP.'||:wFIELDS, ',BD', ',TEMP.BD');

  wSQL = wSQL||'SELECT '||:wFIELDS||' ';
  wSQL = wSQL||'FROM ( ';
  wSQL = wSQL||'      SELECT TLPR_TEMP.* ';
  wSQL = wSQL||'      FROM TMP_VSUC_EMPRESAS_TLPR_TEMP TLPR_TEMP ';
  wSQL = wSQL||'      LEFT OUTER JOIN TMP_VSUC_EMPRESAS_TLAN_TEMP TLAN_TEMP '
                        ||'on (TLAN_TEMP.BDSESSAO = TLPR_TEMP.BDSESSAO AND '
                        ||' TLAN_TEMP.BDCODEMP    = TLPR_TEMP.BDCODEMP AND'
                        ||' TLAN_TEMP.BDCHAVE     = TLPR_TEMP.BDCHAVE) ';
  wSQL = wSQL||'      WHERE TLAN_TEMP.BDSESSAO = '||:PRSESSAO||' ';
  wSQL = wSQL||'      AND  (TLAN_TEMP.BDVINC_BAIXA IS NULL OR TLAN_TEMP.BDVINC_BAIXA collate win_ptbr <> ''TRUE'') ';
  wSQL = wSQL||'      AND NOT EXISTS ( ';
  wSQL = wSQL||'                      SELECT INCO.BDCODINCONSISTENCIA ';
  wSQL = wSQL||'                      FROM VSUC_INCON_TLAN INCO ';
  wSQL = wSQL||'                      WHERE ';
  wSQL = wSQL||'                      INCO.BDSESSAO = TLPR_TEMP.BDSESSAO AND ';
  wSQL = wSQL||'                      INCO.BDCODEMP = TLPR_TEMP.BDCODEMP AND ';
  wSQL = wSQL||'                      INCO.BDCHAVE  = TLPR_TEMP.BDCHAVE ';
  wSQL = wSQL||'                     ) ';
  wSQL = wSQL||'     ) TEMP ';

  EXECUTE STATEMENT :wSQL;
  
  -- ** NOTAS EXPLICATIVAS** #196338 - Djonathan - Importação de lançamentos TXT com notas explicativas

  SELECT LIST(BDFIELD) -- Buscando os campos da tabela de nota explicativa
  FROM (
         SELECT TRIM(RDB$FIELD_NAME) AS BDFIELD FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME = 'VSUC_EMPRESAS_TLANNE' ORDER BY RDB$FIELD_POSITION
       )
  INTO :WFIELDS;

  wSQL = 'INSERT INTO VSUC_EMPRESAS_TLANNE ('||:wFIELDS||') ';
  -- Chave da tabela temporária
  wFIELDS = REPLACE(:wFIELDS, ',BDCHAVE,', ',BDEDITCHAVE,');
  -- Apelido para a tabela temporária
  wFIELDS = REPLACE('TEMP.'||:wFIELDS, ',BD', ',TEMP.BD');

  wSQL = wSQL||'SELECT '||:wFIELDS||' ';
  wSQL = wSQL||'FROM ( ';
  wSQL = wSQL||'      SELECT TLNE_TEMP.* ';
  wSQL = wSQL||'      FROM TMP_VSUC_EMPRESAS_TLANNE_TEMP TLNE_TEMP ';
  wSQL = wSQL||'      LEFT OUTER JOIN TMP_VSUC_EMPRESAS_TLAN_TEMP TLAN_TEMP '
                        ||'on (TLAN_TEMP.BDSESSAO = TLNE_TEMP.BDSESSAO AND '
                        ||' TLAN_TEMP.BDCODEMP    = TLNE_TEMP.BDCODEMP AND'
                        ||' TLAN_TEMP.BDCHAVE     = TLNE_TEMP.BDCHAVE) ';
  wSQL = wSQL||'      WHERE TLAN_TEMP.BDSESSAO = '||:PRSESSAO||' ';
  wSQL = wSQL||'      AND  (TLAN_TEMP.BDVINC_BAIXA IS NULL OR TLAN_TEMP.BDVINC_BAIXA collate win_ptbr <> ''TRUE'') ';
  wSQL = wSQL||'      AND NOT EXISTS ( ';
  wSQL = wSQL||'                      SELECT INCO.BDCODINCONSISTENCIA ';
  wSQL = wSQL||'                      FROM VSUC_INCON_TLAN INCO ';
  wSQL = wSQL||'                      WHERE ';
  wSQL = wSQL||'                      INCO.BDSESSAO = TLNE_TEMP.BDSESSAO AND ';
  wSQL = wSQL||'                      INCO.BDCODEMP = TLNE_TEMP.BDCODEMP AND ';
  wSQL = wSQL||'                      INCO.BDCHAVE  = TLNE_TEMP.BDCHAVE ';
  wSQL = wSQL||'                     ) ';
  wSQL = wSQL||'     ) TEMP ';

  EXECUTE STATEMENT :wSQL;
  
  -- ** COMPLEMENTO ** #225489 - Marcela - Importação de lançamentos TXT - Aumentar complemento.

  SELECT LIST(BDFIELD) -- Buscando os campos da tabela de lançamentos de complementos
  FROM (
         SELECT TRIM(RDB$FIELD_NAME) AS BDFIELD FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME = 'VSUC_EMPRESAS_TLAN_COMPL' ORDER BY RDB$FIELD_POSITION
       )
  INTO :WFIELDS;

  wSQL = 'INSERT INTO VSUC_EMPRESAS_TLAN_COMPL ('||:wFIELDS||') ';
  -- Chave da tabela temporária
  wFIELDS = REPLACE(:wFIELDS, ',BDCHAVE,', ',BDEDITCHAVE,');
  -- Apelido para a tabela temporária
  wFIELDS = REPLACE('TEMP.'||:wFIELDS, ',BD', ',TEMP.BD');

  wSQL = wSQL||'SELECT '||:wFIELDS||' ';
  wSQL = wSQL||'FROM ( ';
  wSQL = wSQL||'      SELECT TCOMPL_TEMP.* ';
  wSQL = wSQL||'      FROM TMP_VSUC_EMPRESAS_TLAN_COMPL_TEMP TCOMPL_TEMP ';
  wSQL = wSQL||'      LEFT JOIN TMP_VSUC_EMPRESAS_TLAN_TEMP TLAN_TEMP '
                        ||'on (TLAN_TEMP.BDSESSAO = TCOMPL_TEMP.BDSESSAO AND '
                        ||' TLAN_TEMP.BDCODEMP    = TCOMPL_TEMP.BDCODEMP AND'
                        ||' TLAN_TEMP.BDCHAVE     = TCOMPL_TEMP.BDCHAVE) ';
  wSQL = wSQL||'      WHERE TLAN_TEMP.BDSESSAO = '||:PRSESSAO||' ';
  wSQL = wSQL||'      AND  (TLAN_TEMP.BDVINC_BAIXA IS NULL OR TLAN_TEMP.BDVINC_BAIXA collate win_ptbr <> ''TRUE'') ';
  wSQL = wSQL||'      AND NOT EXISTS ( ';
  wSQL = wSQL||'                      SELECT INCO.BDCODINCONSISTENCIA ';
  wSQL = wSQL||'                      FROM VSUC_INCON_TLAN INCO ';
  wSQL = wSQL||'                      WHERE ';
  wSQL = wSQL||'                      INCO.BDSESSAO = TCOMPL_TEMP.BDSESSAO AND ';
  wSQL = wSQL||'                      INCO.BDCODEMP = TCOMPL_TEMP.BDCODEMP AND ';
  wSQL = wSQL||'                      INCO.BDCHAVE  = TCOMPL_TEMP.BDCHAVE ';
  wSQL = wSQL||'                     ) ';
  wSQL = wSQL||'     ) TEMP ';

  EXECUTE STATEMENT :wSQL;
end^

create or alter procedure SP_ATU_TMP_VSUC_COMPL_ASTERISCO (
    PRSESSAO integer)
as
begin
  update TMP_VSUC_EMPRESAS_TLAN_TEMP TMP
  set BDCOMPL = replace(BDCOMPL, '*PD', coalesce((select first 1 TER.BDNOME from VW_TTERCEIRO_SIMPLES TER
                                         where TER.BDCODTER = TMP.BDCODTERCEIROD), ''))
  where TMP.BDSESSAO = :PRSESSAO and
        TMP.BDTROCACOMPL = 1 and
        BDCOMPL containing '*PD';

  update TMP_VSUC_EMPRESAS_TLAN_TEMP TMP
  set BDCOMPL = replace(BDCOMPL, '*PC', coalesce((select first 1 TER.BDNOME from VW_TTERCEIRO_SIMPLES TER
                                         where TER.BDCODTER = TMP.BDCODTERCEIROC), ''))
  where TMP.BDSESSAO = :PRSESSAO and
        TMP.BDTROCACOMPL = 1 and
        BDCOMPL containing '*PC';

  update TMP_VSUC_EMPRESAS_TLAN_TEMP TMP
  set BDCOMPL = replace(BDCOMPL, '*CNPJCPF_PD', coalesce((select first 1 TER.BDCGCTER from TTERCEIRO TER
                                                 where TER.BDCODTER = TMP.BDCODTERCEIROD), ''))
  where TMP.BDSESSAO = :PRSESSAO and
        TMP.BDTROCACOMPL = 1 and
        BDCOMPL containing '*CNPJCPF_PD';

  update TMP_VSUC_EMPRESAS_TLAN_TEMP TMP
  set BDCOMPL = replace(BDCOMPL, '*CNPJCPF_PC', coalesce((select first 1 TER.BDCGCTER from TTERCEIRO TER
                                                 where TER.BDCODTER = TMP.BDCODTERCEIROC), ''))
  where TMP.BDSESSAO = :PRSESSAO and
        TMP.BDTROCACOMPL = 1 and
        BDCOMPL containing '*CNPJCPF_PC';
end^

create or alter procedure SP_ATUALIZAR_TMP_VSUC_TLAN (
    PRSESSAO integer,
    PREMPRESA integer,
    PRULTCHAVE integer,
    PRIDTERMINAL integer,
    PRVERIFICADUPLICADO integer)
as
declare variable WMATRIZ integer;
declare variable WCONTASEMPRESA integer;
declare variable WRATEIO DM_BOOLEAN;
begin
  select coalesce(T.BDCODMATRIZ, T.BDCODEMP)
  from TEMPRESAS T
  where T.BDCODEMP = :PREMPRESA
  into :WMATRIZ;

  if (:PRULTCHAVE > 0) then
  begin
    SETORDEMSEQUENCIAL(0);
    UPDATE TMP_VSUC_EMPRESAS_TLAN_TEMP T
    SET T.BDEDITCHAVE = :PRULTCHAVE
     WHERE T.BDSESSAO = :PRSESSAO
       AND T.BDCODEMP = :PREMPRESA
     ORDER BY COALESCE(T.BDCHAVEOWNER, T.BDCHAVE), T.BDSEQDAO;
  end

  --1  Não foi informado a conta débito e crédito.
  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select TMP.BDCODEMP, TMP.BDCHAVE, :PRSESSAO, 1, 1, 0
  from TMP_VSUC_EMPRESAS_TLAN_TEMP TMP
  where TMP.BDSESSAO = :PRSESSAO and
        TMP.BDCODEMP = :PREMPRESA and
        (coalesce(TMP.BDDEBITO, 0) = 0 and
        coalesce(TMP.BDCREDITO, 0) = 0);
  -- 2  Contas débito/crédito e/ou participantes iguais
  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select TMP.BDCODEMP, TMP.BDCHAVE, :PRSESSAO, 2, 1, 0
  from TMP_VSUC_EMPRESAS_TLAN_TEMP TMP
  where TMP.BDSESSAO = :PRSESSAO and
        TMP.BDCODEMP = :PREMPRESA and
        coalesce(TMP.BDDEBITO, 0) = coalesce(TMP.BDCREDITO, 0) and
        (coalesce(TMP.BDCODTERCEIROD, 0) = coalesce(TMP.BDCODTERCEIROC, 0)) and
        coalesce(TMP.BDCODEMPREEACAOD, 0) = 0 and
        coalesce(TMP.BDCODEMPREEACAOC, 0) = 0 and
        coalesce(TMP.BDCODUNIIMOBACAOD, 0) = 0 and
        coalesce(TMP.BDCODUNIIMOBACAOC, 0) = 0;
  -- 3  Campo data não informado.
  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select TMP.BDCODEMP, TMP.BDCHAVE, :PRSESSAO, 3, 1, 0
  from TMP_VSUC_EMPRESAS_TLAN_TEMP TMP
  where TMP.BDSESSAO = :PRSESSAO and
        TMP.BDCODEMP = :PREMPRESA and
        (BDDATA is null);
  -- 4  Valor do lançamento zerado ou negativo.
  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select TMP.BDCODEMP, TMP.BDCHAVE, :PRSESSAO, 4, 1, 0
  from TMP_VSUC_EMPRESAS_TLAN_TEMP TMP
  where TMP.BDSESSAO = :PRSESSAO and
        TMP.BDCODEMP = :PREMPRESA and
        ((coalesce(BDVALOR, 0) <= 0));
  -- 5  Conta débito do arquivo não cadastrada no plano de contas..
  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select TMP.BDCODEMP, TMP.BDCHAVE, :PRSESSAO, 5, 1, 0
  from TMP_VSUC_EMPRESAS_TLAN_TEMP TMP
  where TMP.BDSESSAO = :PRSESSAO and
        TMP.BDCODEMP = :PREMPRESA and
        (coalesce(BDDEBITO, 0) = 0 and
        trim(TMP.BDDEBITOARQ) <> '' and
        coalesce(BDDEBTROCA, 0) = 0);
  -- 6  Conta crédito do arquivo não cadastrada no plano de contas.
  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDDESCRICAOADC,
                               BDCATEGORIAINCONSISTENCIA)
  select TMP.BDCODEMP, TMP.BDCHAVE, :PRSESSAO, 6, 1, 'Conta: ' || TMP.BDCREDITOARQ, 0
  from TMP_VSUC_EMPRESAS_TLAN_TEMP TMP
  where TMP.BDSESSAO = :PRSESSAO and
        TMP.BDCODEMP = :PREMPRESA and
        (coalesce(BDCREDITO, 0) = 0 and
        trim(TMP.BDCREDITOARQ) <> '' and
        coalesce(BDCRETROCA, 0) = 0);
  -- 7  Lançamento sem histórico e complemento. Pelo menos um deve ser preenchido, pois é obrigatório para o Sped ECD.
  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDDESCRICAOADC,
                               BDCATEGORIAINCONSISTENCIA)
  select TMP.BDCODEMP, TMP.BDCHAVE, :PRSESSAO, 7, 1,
         case
           when coalesce(TMP.BDCHAVEOWNER, 0) > 0 then case
                                                         when coalesce(TMP.BDDEBITO, 0) > 0 then 'Conta: ' || TMP.BDDEBITO
                                                         else 'Conta: ' || TMP.BDCREDITO
                                                       end
           else 'Conta: ' || TMP.BDDEBITOARQ
         end, 0
  from TMP_VSUC_EMPRESAS_TLAN_TEMP TMP
  left join TMP_VSUC_EMPRESAS_TLAN_COMPL_TEMP COMPL on (TMP.BDCODEMP = COMPL.BDCODEMP and
        TMP.BDCHAVE = COMPL.BDCHAVE and TMP.BDSESSAO = COMPL.BDSESSAO)
  where TMP.BDSESSAO = :PRSESSAO and
        TMP.BDCODEMP = :PREMPRESA and
        (coalesce(TMP.BDCODTPHI, 0) = 0 and
        coalesce(trim(TMP.BDCOMPL), '') = '' and
        coalesce(trim(COMPL.BDCOMPL), '') = '');
  -- Débito e crédito
  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select S.BDCODEMP, S.BDCHAVE, S.BDSESSAO,
         case
           when P.BDCODTPLA is null then 8
           when P.BDTIPCTA <> 1 then 9
           when (coalesce(trim(P.BDFORMULA), '') <> '') then 10
           when (not(P.BDDATACADCTA is null or P.BDDATACADCTA <= S.BDDATA) and not(P.BDDATAINATIVACTA is null or P.BDDATAINATIVACTA > S.BDDATA)) then 12
           else null
         end,
         1 BDTIPOINCON, 0 BDCATEGORIAINCONSISTENCIA
  from TMP_VSUC_EMPRESAS_TLAN_TEMP S
  left outer join PLANOS_TPLA P on (S.BDCODPLAPADRAO = P.BDCODPLAPADRAO and
        S.BDDEBITO = P.BDCODTPLA)
  where S.BDSESSAO = :PRSESSAO and
        S.BDCODEMP = :PREMPRESA and
        S.BDDEBITO is not null and
        S.BDDEBITO > 0 and
        ((P.BDCODTPLA is null) or (P.BDTIPCTA <> 1) or (coalesce(trim(P.BDFORMULA), '') <> '') or (not(P.BDDATACADCTA is null or P.BDDATACADCTA <= S.BDDATA) and
        not(P.BDDATAINATIVACTA is null or P.BDDATAINATIVACTA > S.BDDATA)));

  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select S.BDCODEMP, S.BDCHAVE, S.BDSESSAO,
         case
           when P.BDCODTPLA is null then 13
           when P.BDTIPCTA <> 1 then 14
           when (coalesce(trim(P.BDFORMULA), '') <> '') then 15
           when (not(P.BDDATACADCTA is null or P.BDDATACADCTA <= S.BDDATA) and not(P.BDDATAINATIVACTA is null or P.BDDATAINATIVACTA > S.BDDATA)) then 17
           else null
         end,
         1 BDTIPOINCON, 0 BDCATEGORIAINCONSISTENCIA
  from TMP_VSUC_EMPRESAS_TLAN_TEMP S
  left outer join PLANOS_TPLA P on (S.BDCODPLAPADRAO = P.BDCODPLAPADRAO and
        S.BDCREDITO = P.BDCODTPLA)
  where S.BDSESSAO = :PRSESSAO and
        S.BDCODEMP = :PREMPRESA and
        S.BDCREDITO is not null and
        S.BDCREDITO > 0 and
        ((P.BDCODTPLA is null) or (P.BDTIPCTA <> 1) or (coalesce(trim(P.BDFORMULA), '') <> '') or (not(P.BDDATACADCTA is null or P.BDDATACADCTA <= S.BDDATA) and
        not(P.BDDATAINATIVACTA is null or P.BDDATAINATIVACTA > S.BDDATA)));
  --prepração de contas por empresa
  WCONTASEMPRESA = 0;
  select first 1 E.BDCODEMP
  from VSUC_CONTAS_EMPRESA E
  where E.BDCODEMP = :WMATRIZ
  into :WCONTASEMPRESA;
  if (WCONTASEMPRESA > 0) then
  begin
    insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON,
                                 BDCATEGORIAINCONSISTENCIA)
    select S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 11, 1, 0
    from TMP_VSUC_EMPRESAS_TLAN_TEMP S
    left outer join VSUC_CONTAS_EMPRESA E on (E.BDCODEMP = :WCONTASEMPRESA and
          E.BDCODPLAPADRAO = S.BDCODPLAPADRAO and
          (E.BDCODTPLA = S.BDDEBITO))
    where S.BDSESSAO = :PRSESSAO and
          S.BDCODEMP = :PREMPRESA and
          S.BDDEBITO > 0 and
          E.BDCODEMP is null;

    insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON,
                                 BDCATEGORIAINCONSISTENCIA)
    select S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 16, 1, 0
    from TMP_VSUC_EMPRESAS_TLAN_TEMP S
    left outer join VSUC_CONTAS_EMPRESA E on (E.BDCODEMP = :WCONTASEMPRESA and
          E.BDCODPLAPADRAO = S.BDCODPLAPADRAO and
          (E.BDCODTPLA = S.BDCREDITO))
    where S.BDSESSAO = :PRSESSAO and
          S.BDCODEMP = :PREMPRESA and
          S.BDCREDITO > 0 and
          E.BDCODEMP is null;
  end
  --18  Histórico não cadastrado.
  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 18, 1 BDTIPOINCON, 0 BDCATEGORIAINCONSISTENCIA
  from TMP_VSUC_EMPRESAS_TLAN_TEMP S
  left outer join HIST_TPHI P on (S.BDCODHIST = P.BDCODHIST and
        S.BDCODTPHI = P.BDCODTPHI)
  where S.BDSESSAO = :PRSESSAO and
        S.BDCODEMP = :PREMPRESA and
        S.BDCODTPHI is not null and
        S.BDCODTPHI > 0 and
        P.BDCODTPHI is null;

  --19  Para esta empresa não é permitido fazer o rateio nas contas de ativo, passivo e patrimônio líquido.
  select first 1 R.BDNAOPERMITERATEIOGRUPO
  from TEMPRESAS_REF R
  where BDCODEMP = :WMATRIZ and
        BDREFEMP <= (trim(rdb$get_context('USER_SESSION', 'W_ANOMES')))
  order by BDCODEMP desc, BDREFEMP desc
  into :WRATEIO;
  if (upper(coalesce(WRATEIO, 'FALSE')) = 'TRUE') then
  begin
    insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON,
                                 BDCATEGORIAINCONSISTENCIA)
    select S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 19, 1 BDTIPOINCON, 0 BDCATEGORIAINCONSISTENCIA
    from TMP_VSUC_EMPRESAS_TLAN_TEMP S
    left outer join PLANOS_TPLA D on (S.BDCODPLAPADRAO = D.BDCODPLAPADRAO and
          S.BDDEBITO = D.BDCODTPLA)
    left outer join PLANOS_TPLA C on (S.BDCODPLAPADRAO = C.BDCODPLAPADRAO and
          S.BDCREDITO = C.BDCODTPLA)
    where S.BDSESSAO = :PRSESSAO and
          S.BDCODEMP = :PREMPRESA and
          ((coalesce(D.BDGRUPOCTA, 99) in (0, 1, 2) and
          exists(select first 1 BDCHAVE
                 from TMP_VSUC_EMPRESAS_TLCC_TEMP CC
                 where CC.BDSESSAO = S.BDSESSAO and
                       CC.BDCODEMP = S.BDCODEMP and
                       CC.BDCHAVE = S.BDCHAVE and
                       CC.BDDEBCRE = 0)) or (coalesce(C.BDGRUPOCTA, 99) in (0, 1, 2) and
          exists(select first 1 BDCHAVE
                 from TMP_VSUC_EMPRESAS_TLCC_TEMP CC
                 where CC.BDSESSAO = S.BDSESSAO and
                       CC.BDCODEMP = S.BDCODEMP and
                       CC.BDCHAVE = S.BDCHAVE and
                       CC.BDDEBCRE = 1)));
  end

  ---------- inconsistencias de terceiros--------------
  --20  Participante não informado.
  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 20 BDCODINCONSISTENCIA, 1 BDTIPOINCON, 0 BDCATEGORIAINCONSISTENCIA
  from TMP_VSUC_EMPRESAS_TLAN_TEMP S
  where S.BDSESSAO = :PRSESSAO and
        S.BDCODEMP = :PREMPRESA and
        ((((coalesce(S.BDALTCODTERCEIROD, S.BDCODTERCEIROD) is null) or (coalesce(S.BDALTCODTERCEIROD, S.BDCODTERCEIROD) = 0)) and
        S.BDTIPOTERD = 1) or (((coalesce(S.BDALTCODTERCEIROC, S.BDCODTERCEIROC) is null) or (coalesce(S.BDALTCODTERCEIROC, S.BDCODTERCEIROC) = 0)) and
        S.BDTIPOTERC = 1));/*Este campo deve estar preenchido, é o código do banco no participante*/

  --21  O participante não existe.
  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 21 BDCODINCONSISTENCIA, 1 BDTIPOINCON, 0 BDCATEGORIAINCONSISTENCIA
  from TMP_VSUC_EMPRESAS_TLAN_TEMP S
  join VEF_INCON_TTERCEIROS T on (T.BDSESSAO = :PRSESSAO and
        (T.BDCODTER = coalesce(S.BDALTCODTERCEIROD, S.BDCODTERCEIROD) or T.BDCODTER = coalesce(S.BDALTCODTERCEIROC, S.BDCODTERCEIROC)))
  where S.BDSESSAO = :PRSESSAO and
        S.BDCODEMP = :PREMPRESA and
        T.BDCODTER > 0
  group by S.BDSESSAO, S.BDCODEMP, S.BDCHAVE;

  --22  Lançamento duplicado.
  if (PRVERIFICADUPLICADO > 0) then
  begin
    insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDDESCRICAOADC,
                                 BDCATEGORIAINCONSISTENCIA)
    select TMP.BDCODEMP, TMP.BDCHAVE, :PRSESSAO, 22, 1, 'Chave existente: ' || min(LAN.BDCHAVE),
           1 BDCATEGORIAINCONSISTENCIA
    from (select BDSESSAO, BDCODEMP, BDCHAVE, BDDATA, BDDEBITO, BDCODTERCEIROD, BDCREDITO, BDCODTERCEIROC, BDCODTPHI,
                 BDVALOR, BDLOTE
          from TMP_VSUC_EMPRESAS_TLAN_TEMP T
          where T.BDSESSAO = :PRSESSAO and
                T.BDCODEMP = :PREMPRESA) TMP
    --inner join VSUC_EMPRESAS_TLAN LAN on ((upper((coalesce(LAN.BDCODEMP, 0) || ';' || coalesce(LAN.BDDATA, '') || ';' || coalesce(LAN.BDDEBITO, 0) || ';' || coalesce(LAN.BDCODTERCEIROD, 0) || ';' || coalesce(LAN.BDCREDITO, 0) || ';' || coalesce(LAN.BDCODTERCEIROC, 0) || ';' || coalesce(LAN.BDCODTPHI, 0) || ';' || coalesce(LAN.BDVALOR, 0) || ';' || coalesce(LAN.BDLOTE, '')))) = (upper((coalesce(TMP.BDCODEMP, 0) || ';' || coalesce(TMP.BDDATA, '') || ';' || coalesce(TMP.BDDEBITO, 0) || ';' || coalesce(TMP.BDCODTERCEIROD, 0) || ';' || coalesce(TMP.BDCREDITO, 0) || ';' || coalesce(TMP.BDCODTERCEIROC, 0) || ';' || coalesce(TMP.BDCODTPHI, 0) || ';' || coalesce(TMP.BDVALOR, 0) || ';' || coalesce(TMP.BDLOTE, '')))))
    inner join VSUC_EMPRESAS_TLAN LAN on (LAN.BDCODEMP = TMP.BDCODEMP and
          LAN.BDDATA = TMP.BDDATA and
          LAN.BDVALOR = TMP.BDVALOR and
          (LAN.BDDEBITO is not distinct from TMP.BDDEBITO) and
          (LAN.BDCODTERCEIROD is not distinct from TMP.BDCODTERCEIROD) and
          (LAN.BDCREDITO is not distinct from TMP.BDCREDITO) and
          (LAN.BDCODTERCEIROC is not distinct from TMP.BDCODTERCEIROC) and
          (LAN.BDCODTPHI is not distinct from TMP.BDCODTPHI) and
          (LAN.BDLOTE is not distinct from TMP.BDLOTE or (LAN.BDLOTE = '' and
          TMP.BDLOTE is null)))
    group by BDCODEMP, BDCHAVE, BDSESSAO;
  end

  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_VSUC_TLCC(:PRSESSAO, :PREMPRESA, 0, :PRIDTERMINAL); -- 23,24,25,26 e 30(inativado)
  EXECUTE PROCEDURE SP_ATUALIZAR_TMP_VSUC_TLPR(:PRSESSAO, :PREMPRESA, 0, :PRIDTERMINAL); -- 27,28 e 29
  
--31 O participante está inativo e não pode ser selecionado!
  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDDESCRICAOADC, BDCATEGORIAINCONSISTENCIA)
  select S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 31 BDCODINCONSISTENCIA, 1 BDTIPOINCON, ' Participante: ' || T.bdcodter, 0 BDCATEGORIAINCONSISTENCIA
  from TMP_VSUC_EMPRESAS_TLAN_TEMP S
  join TTERCEIRO T on (T.bdcodter = S.BDCODTERCEIROD) or (T.BDCODTER = S.BDCODTERCEIROC)
  where S.BDSESSAO = :PRSESSAO AND
        S.BDCODEMP = :PREMPRESA AND
        T.BDCODTER > 0 AND
        T.bdinativo = TRUE;
  
  -- 32 Contas débito/crédito e/ou empreendimentos/unidades iguais.
  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select TMP.BDCODEMP, TMP.BDCHAVE, :PRSESSAO, 32, 1, 0
  from TMP_VSUC_EMPRESAS_TLAN_TEMP TMP
  where TMP.BDSESSAO = :PRSESSAO and
        TMP.BDCODEMP = :PREMPRESA and
        coalesce(TMP.BDDEBITO, 0) = coalesce(TMP.BDCREDITO, 0) and
        (coalesce(TMP.BDCODTERCEIROD, 0) = coalesce(TMP.BDCODTERCEIROC, 0)) and

        ((coalesce(TMP.BDCODEMPREEACAOD, 0) = coalesce(TMP.BDCODEMPREEACAOC, 0) and
        coalesce(TMP.BDCODEMPREEACAOD, 0) > 0 and
        coalesce(TMP.BDCODEMPREEACAOC, 0) > 0 and
        coalesce(TMP.BDCODUNIIMOBACAOD, 0) = 0 and
        coalesce(TMP.BDCODUNIIMOBACAOC, 0) = 0) or (coalesce(TMP.BDCODEMPREEACAOD, 0) = coalesce(TMP.BDCODEMPREEACAOC, 0) and
        coalesce(TMP.BDCODUNIIMOBACAOD, 0) = coalesce(TMP.BDCODUNIIMOBACAOC, 0) and
        coalesce(TMP.BDCODEMPREEACAOD, 0) > 0 and
        coalesce(TMP.BDCODEMPREEACAOC, 0) > 0 and
        coalesce(TMP.BDCODUNIIMOBACAOD, 0) > 0 and
        coalesce(TMP.BDCODUNIIMOBACAOC, 0) > 0));

  --33 conta contábil em apenas uma partida (débito ou crédito) e centro de custo a débito e a crédito {#201875 - Djonathan}
  INSERT INTO VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  SELECT S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 33 BDCODINCONSISTENCIA, 1 BDTIPOINCON, 0 BDCATEGORIAINCONSISTENCIA
  FROM TMP_VSUC_EMPRESAS_TLCC_TEMP S
  LEFT OUTER JOIN TMP_VSUC_EMPRESAS_TLAN_TEMP C ON (S.BDSESSAO = C.BDSESSAO AND
        S.BDCODEMP = C.BDCODEMP AND
        S.BDCHAVE = C.BDCHAVE)
  WHERE S.BDSESSAO = :PRSESSAO AND
        S.BDCODEMP = :PREMPRESA AND
        S.BDCHAVE  =  C.BDCHAVE
  GROUP BY S.BDCODEMP, S.BDCHAVE, S.BDSESSAO
  HAVING COUNT(*)> 1 AND
         (SUM(CASE WHEN C.BDDEBITO IS NULL THEN 1 ELSE 0 END) > 0 OR
          SUM(CASE WHEN C.BDCREDITO IS NULL THEN 1 ELSE 0 END) > 0);
  
  --34 Lancamentos com "Multiplos lançamentos - Multa/juros..." que tenham alguma inconsistencia {#192918 - Djonathan}
  INSERT INTO VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDDESCRICAOADC, BDCATEGORIAINCONSISTENCIA, BDCHAVEMULTLANC)
  select S2.BDCODEMP, S2.BDCHAVE, S2.BDSESSAO, S1.BDCODINCONSISTENCIA, 5 AS BDTIPOINCON, S1.BDDESCRICAOADC, S1.BDCATEGORIAINCONSISTENCIA, S1.BDSEQDAO
  from (select distinct I.bdsessao, i.bdcodemp, i.bdchave, S.BDCHAVEOWNER, I.BDCODINCONSISTENCIA, I.BDTIPOINCON, I.BDDESCRICAOADC, I.BDCATEGORIAINCONSISTENCIA, S.BDSEQDAO
        from VSUC_INCON_TLAN I
        join TMP_VSUC_EMPRESAS_TLAN_TEMP S on (S.BDSESSAO = I.BDSESSAO and
              S.BDCODEMP = I.BDCODEMP and
              S.BDCHAVE = I.BDCHAVE) where s.bdtemlanc is not null or s.BDCHAVEOWNER is not null) s1
  inner join TMP_VSUC_EMPRESAS_TLAN_TEMP s2 on (S1.BDSESSAO = s2.BDSESSAO and
              S1.BDCODEMP = s2.BDCODEMP and
              (s1.bdchave = s2.bdchave or s1.bdchaveowner = s2.bdchave or s1.bdchaveowner = s2.bdchaveowner or s2.bdchaveowner = s1.bdchave ))
  where s2.bdchave <> s1.bdchave and s1.bdsessao = :PRSESSAO;   

  execute procedure SP_ATUALIZAR_CAMPO_CHAVE_TEMP(:PRSESSAO, 'TMP_VSUC_EMPRESAS_TLAN_TEMP');
end^

create or alter procedure SP_ATUALIZAR_TMP_VSUC_TLCC (
    PRSESSAO integer,
    PREMPRESA integer,
    PRULTCHAVE integer,
    PRIDTERMINAL integer)
as
begin
  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 23 BDCODINCONSISTENCIA, 2 BDTIPOINCON, 0 BDCATEGORIAINCONSISTENCIA
  from TMP_VSUC_EMPRESAS_TLCC_TEMP S
  where S.BDSESSAO = :PRSESSAO AND S.BDCODEMP = :PREMPRESA and (s.BDCODCENTRO is null or s.BDCODCENTRO = 0);

  
  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 24 BDCODINCONSISTENCIA, 2 BDTIPOINCON, 0 BDCATEGORIAINCONSISTENCIA
  from TMP_VSUC_EMPRESAS_TLCC_TEMP S
  where S.BDSESSAO = :PRSESSAO AND S.BDCODEMP = :PREMPRESA and (s.BDCODTPCC is null or s.BDCODTPCC = 0);

  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 24 BDCODINCONSISTENCIA, 2 BDTIPOINCON, 0 BDCATEGORIAINCONSISTENCIA
  from TMP_VSUC_EMPRESAS_TLCC_TEMP S
  LEFT OUTER JOIN CENTROS_TPCC C on (S.BDCODCENTRO = C.BDCODCENTRO AND S.BDCODTPCC = C.BDCODTPCC)
  where S.BDSESSAO = :PRSESSAO AND S.BDCODEMP = :PREMPRESA AND S.BDCODTPCC > 0 and C.BDCODTPCC IS NULL;

  insert into vsuc_incon_tlan (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDDESCRICAOADC, BDCATEGORIAINCONSISTENCIA)
  select CC1.bdcodemp, CC1.bdchave, CC1.bdsessao,26 BDCODINCONSISTENCIA,  2 BDTIPOINCON,' Conta CC '||CC1.bdcodtpcc||'', 0 BDCATEGORIAINCONSISTENCIA
  from  TMP_VSUC_EMPRESAS_TLCC_TEMP CC1
  inner join TMP_VSUC_EMPRESAS_TLCC_TEMP CC2 on (CC1.BDCHAVE = CC2.BDCHAVE and CC1.BDSESSAO = CC2.BDSESSAO and CC1.BDCODEMP = CC2.BDCODEMP and
                                                 CC1.BDCODCENTRO = CC2.BDCODCENTRO and CC1.BDCODTPCC = CC2.BDCODTPCC and CC1.BDDEBCRE = CC2.BDDEBCRE and CC1.BDSEQ <> CC2.BDSEQ)
  where CC1.BDSESSAO = :PRSESSAO AND CC1.BDCODEMP = :PREMPRESA AND (CC1.BDCODTPCC > 0 or CC1.BDCODTPCC is not null);

  /*Guilherme Bauler. Alt: 151317 - 28/05/2021 - Inconsistencia para nao deixar importar CC Titulo.*/
  /* #alt:152548 - 07/07/2021 - Machado - Removida verificação de título para todo o contábil
  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 30 BDCODINCONSISTENCIA, 2 BDTIPOINCON, 0 BDCATEGORIAINCONSISTENCIA
  from TMP_VSUC_EMPRESAS_TLCC_TEMP S
  LEFT OUTER JOIN CENTROS_TPCC C on (S.BDCODCENTRO = C.BDCODCENTRO AND S.BDCODTPCC = C.BDCODTPCC)
  where S.BDSESSAO = :PRSESSAO AND S.BDCODEMP = :PREMPRESA AND C.BDTIPCTA = 0 and coalesce(C.BDTIPO, 0) = 0;
  */
end^

create or alter procedure SP_ATUALIZAR_TMP_VSUC_TLPR (
    PRSESSAO integer,
    PREMPRESA integer,
    PRULTCHAVE integer,
    PRIDTERMINAL integer)
as
begin

  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select BDCODEMP, BDCHAVE, BDSESSAO, 27 BDCODINCONSISTENCIA, 2 BDTIPOINCON, 0 BDCATEGORIAINCONSISTENCIA
  from (select S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 27 BDCODINCONSISTENCIA, 2 BDTIPOINCON,
       (select SP.BDISVALID from SP_VALIDA_CPF_CNPJ(s.bdcpfmanual) SP)
        from TMP_VSUC_EMPRESAS_TLPR_TEMP S
        where S.BDSESSAO = :PRSESSAO and
             S.BDCODEMP = :PREMPRESA and
            ((S.BDTIPOPARTICIPANTE = 0) and
            (S.BDCODTER <= 0)) or (S.BDTIPOPARTICIPANTE = 2)) where BDISVALID = 'FALSE';

  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 28 BDCODINCONSISTENCIA, 2 BDTIPOINCON, 0 BDCATEGORIAINCONSISTENCIA
  from TMP_VSUC_EMPRESAS_TLPR_TEMP S
  where S.BDSESSAO = :PRSESSAO AND S.BDCODEMP = :PREMPRESA and (s.bdtipmov = 2 and s.bdctacor <= 0);

  insert into VSUC_INCON_TLAN (BDCODEMP, BDCHAVE, BDSESSAO, BDCODINCONSISTENCIA, BDTIPOINCON, BDCATEGORIAINCONSISTENCIA)
  select S.BDCODEMP, S.BDCHAVE, S.BDSESSAO, 29 BDCODINCONSISTENCIA, 2 BDTIPOINCON, 0 BDCATEGORIAINCONSISTENCIA
  from TMP_VSUC_EMPRESAS_TLPR_TEMP S
  where S.BDSESSAO = :PRSESSAO AND S.BDCODEMP = :PREMPRESA and (s.bdcodimovrur <= 0);
end^

CREATE OR ALTER procedure SP_ATUALIZAVLRICMS_C425ALIQ (
    PRSESSAO integer)
as
declare variable WBDCODEMP integer;
declare variable WBDCHAVE integer;
declare variable WBDORDEMTOT integer;
declare variable WBDORDEMICMS integer;
declare variable WBDVLRICMS numeric(15,2);
declare variable WBDVLRICMSC420 numeric(15,2);
declare variable WBDORDEMC425 integer;
begin

  for
     select  Va.BDCODEMP, Va.BDCHAVE, Va.BDORDEMTOT, Va.BDORDEMICMS,va.bdvlricms,vl.bdvlricms bdvlricmsc420,
     (select first 1 o.BDORDEMC425 from TMP_VEF_EMP_TREDZC425ALIQ_TEMP o where o.BDSESSAO = vA.BDSESSAO and
                                           o.BDCODEMP = vA.BDCODEMP and
                                           o.BDCHAVE = vA.BDCHAVE and
                                           o.BDORDEMTOT = vA.BDORDEMTOT and
                                           o.BDORDEMICMS = vA.BDORDEMICMS
                                           order by o.bdvlricms desc  ) BDORDEMC425
    from (
          select V.BDSESSAO, V.BDCODEMP, V.BDCHAVE, V.BDORDEMTOT, V.BDORDEMICMS,sum(coalesce(V.BDVLRICMS, 0)) BDVLRICMS
          from TMP_VEF_EMP_TREDZC425ALIQ_TEMP V
          where V.BDSESSAO = :PRSESSAO
          group by V.BDSESSAO, V.BDCODEMP, V.BDCHAVE, V.BDORDEMTOT, V.BDORDEMICMS
       ) VA
    join TMP_VEF_EMP_TREDZVARALIQ_TEMP VL on (VL.BDSESSAO = VA.BDSESSAO and VL.BDCODEMP = VA.BDCODEMP and VL.BDCHAVE = VA.BDCHAVE and VL.BDORDEMICMS = VA.BDORDEMICMS)
    where va.bdvlricms <> vl.bdvlricms
   into :wBDCODEMP, :wBDCHAVE, :wBDORDEMTOT, :wBDORDEMICMS,:wbdvlricms,:wbdvlricmsc420,:wBDORDEMC425
  do
  begin

      update TMP_VEF_EMP_TREDZC425ALIQ_TEMP v set V.BDVLRICMS = (V.BDVLRICMS + (:wbdvlricmsc420 - :wBDVLRICMS))
      where V.BDSESSAO = :PRSESSAO and
            V.BDCODEMP = :wBDCODEMP and
            V.BDCHAVE = :wBDCHAVE and
            V.BDORDEMTOT = :wBDORDEMTOT and
            V.BDORDEMICMS = :wBDORDEMICMS and
            v.bdordemc425 = :wBDORDEMC425;

   end
end^

/* Restore proc. body: VRH_SP_DADOS_PREPSITUACAO */
create or alter procedure VRH_SP_DADOS_PREPSITUACAO (
    PRCODEMP varchar(15000),
    PRCODCOL varchar(32700),
    PRDATINI date,
    PRDATFIM date,
    PRRETONARSITEMPORIG varchar(5) = 'FALSE' /* COLLATE WIN1252 - default */ )
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODSIT integer,
    BDDATAINISEFIP date,
    BDDATAINISIT date,
    BDDATAFIMSIT date,
    BDDIASSIT integer,
    BDNBENEFICIOSIT varchar(20),
    BDDATAPERICIASIT date,
    BDDATAPARTOSIT date,
    BDDESCSIT varchar(70),
    BDGRUPOSIT integer,
    BDCODVER integer,
    BDCODMFGENT integer,
    BDCODMFGSAI integer,
    BDCARENSIT integer,
    BDCODVER15DIAS integer,
    BDTIPOPERDESIT integer,
    BDSALFAMSIT varchar(5),
    BDCODSEFENT varchar(5),
    BDCODSEFSAI varchar(5),
    BDRELSIT integer,
    BDINSSINTSIT DM_BOOLEAN,
    BDDIASATESTADO integer,
    BDNAOPRORROGAFERIAS varchar(5),
    BDSUSPENSAO DM_BOOLEAN,
    BDNAOALTPERAQUIMP936 DM_BOOLEAN,
    BDDIASPERDEPERAQUI integer,
    BDIMPRIMEDADOSSIT DM_BOOLEAN)
as
declare variable WSQL varchar(32700);
declare variable WWHERE varchar(15000);
declare variable WEMPORIG integer;
declare variable WCOLORIG integer;
declare variable WEMPX integer;
declare variable WCOLX integer;
declare variable WCODCONTROLE integer;
BEGIN
  wsql = 'select SIT.BDCODEMP, SIT.BDCODCOL, SIT.BDCODSITAUX, SIT.BDDATAINISEFIP, SIT.BDDATAINISIT, SIT.BDDATAFIMSIT, '||
                'SIT.BDDIASSIT, SIT.BDNBENEFICIOSIT, SIT.BDDATAPERICIASIT, SIT.BDDATAPARTOSIT, PSIT.BDDESCSIT, '||
                'PSIT.BDGRUPOSIT, PSITDIA.BDCODVER, PSITDIA.BDCODMFGENT, PSITDIA.BDCODMFGSAI, PSITDIA.BDCARENSIT, '||
                'PSITDIA.BDCODVER15DIAS, PSIT.BDTIPOPERDESIT, PSITDIA.BDSALFAMSIT, FGTSENT.BDCODSEFMFG BDCODSEFENT, '||
                'FGTSSAI.BDCODSEFMFG BDCODSEFSAI, PSIT.BDRELSIT, PSITDIA.BDINSSINTSIT, SIT.BDDIASATESTADO, PSITDIA.BDNAOPRORROGAFERIAS, ' ||
                'PSITDIA.BDIMPRIMEDADOSSIT,COALESCE(PSIT.BDSUSPMP,''FALSE'') BDSUSPMP, PSIT.BDDIASPERDEPERAQUI '||

         'from ';

  wsql = wsql||'VRH_EMP_TSITCOL sit ';
  wsql = wsql||'join VRH_BASE_TPREPSIT pSit on (psit.BDCODSIT = SIT.BDCODSIt) ';
  wsql = wsql||'join VRH_BASE_TPREPSIT_DIA PSITDIA on (PSITDIA.BDCODSIT = PSIT.BDCODSIT';

  wsql = wsql ||' and PSITDIA.BDDATASTD = (select MAX(X.BDDATASTD) from VRH_BASE_TPREPSIT_DIA X where X.BDCODSIT = SIT.BDCODSIt))';

  wsql = wsql||' left outer join VRH_BASE_TMOTFGTS fgtsent on (psit.BDCODMFGENT = fgtsent.BDCODMFG)';
  wsql = wsql||' left outer join VRH_BASE_TMOTFGTS fgtssai on (psit.BDCODMFGSAI = fgtssai.BDCODMFG)';

  wwhere = ' where bdcodemp is not null ';

  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
     wwhere = wwhere||' and '||prcodemp;

  IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
     wwhere = wwhere||' and '||prcodcol;

  IF (prdatini IS NOT NULL AND prdatfim IS NOT NULL) THEN
     BEGIN
       wwhere = wwhere||' and ';
       wwhere = wwhere||'((sit.BDDATAINISEFIP between '''||:PRDATINI||''' AND '''||:PRDATFIM||''') or ';
       wwhere = wwhere||'(sit.BDDATAFIMSIT between '''||:PRDATINI||''' AND '''||:PRDATFIM||''') or ';
       wwhere = wwhere||'(sit.BDDATAINISEFIP < '''||:PRDATINI||''' and (sit.BDDATAFIMSIT is null or sit.BDDATAFIMSIT > '''||:PRDATFIM||'''))) ';
     END

  wsql = wsql||wwhere||' ORDER by SIT.BDCODEMP, SIT.BDCODCOL, SIT.BDDATAINISEFIP ';

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP, :BDCODCOL, :BDCODSIT, :BDDATAINISEFIP,
    :BDDATAINISIT, :BDDATAFIMSIT, :BDDIASSIT, :BDNBENEFICIOSIT, :BDDATAPERICIASIT, :BDDATAPARTOSIT,
    :BDDESCSIT, :BDGRUPOSIT, :BDCODVER, :BDCODMFGENT, :BDCODMFGSAI, :BDCARENSIT, :BDCODVER15DIAS,
    :BDTIPOPERDESIT, :BDSALFAMSIT, :bdcodsefent, :bdcodsefsai, :bdrelsit, :BDINSSINTSIT, :BDDIASATESTADO,
    :BDNAOPRORROGAFERIAS, :BDIMPRIMEDADOSSIT ,:BDSUSPENSAO, :BDDIASPERDEPERAQUI
  DO
    begin
      execute statement 'select first 1 BDNAOALTPERAQUIMP936 from VRHF_BASE_TEMPPAR where bdcodemp = ' || :BDCODEMP into BDNAOALTPERAQUIMP936;
    SUSPEND;
    end


  IF (UPPER(PRRETONARSITEMPORIG) = 'TRUE') THEN
     begin
       wwhere = 'select BDCODEMPORIG, BDCODCOLORIG, BDCODEMPDEST, BDCODCOLDEST from VRH_EMP_TTRANSCOL';

       wwhere = wwhere||' where BDCODEMPDEST is not null and BDCODCOLDEST is not null ';

       IF (coalesce(prcodemp, '') <> '') THEN
          begin
            wwhere = wwhere||' and '||REPLACE(UPPER(prcodemp), 'BDCODEMP', 'BDCODEMPDEST');
     
            IF (coalesce(prcodcol, '') <> '') THEN
               wwhere = wwhere||' and '||REPLACE(UPPER(prcodcol), 'BDCODCOL', 'BDCODCOLDEST');
          end

       for execute statement wwhere into :wemporig, :wcolorig, :BDCODEMP, :BDCODCOL do
         begin
           while (coalesce(wemporig, 0) <> 0 and coalesce(wcolorig, 0) <> 0) do
             begin
               wsql = 'select SIT.BDCODSITAUX, SIT.BDDATAINISEFIP, SIT.BDDATAINISIT, SIT.BDDATAFIMSIT, '||
                             'SIT.BDDIASSIT, SIT.BDNBENEFICIOSIT, SIT.BDDATAPERICIASIT, SIT.BDDATAPARTOSIT, PSIT.BDDESCSIT, '||
                             'PSIT.BDGRUPOSIT, PSITDIA.BDCODVER, PSITDIA.BDCODMFGENT, PSITDIA.BDCODMFGSAI, PSITDIA.BDCARENSIT, '||
                             'PSITDIA.BDCODVER15DIAS, PSIT.BDTIPOPERDESIT, PSITDIA.BDSALFAMSIT, FGTSENT.BDCODSEFMFG BDCODSEFENT, '||
                             'FGTSSAI.BDCODSEFMFG BDCODSEFSAI, PSIT.BDRELSIT, PSITDIA.BDINSSINTSIT, SIT.BDDIASATESTADO, PSITDIA.BDNAOPRORROGAFERIAS, ' ||
                             'BDIMPRIMEDADOSSIT,COALESCE(PSIT.BDSUSPMP,''FALSE'') BDSUSPMP, PSIT.BDDIASPERDEPERAQUI '||
                      'from ';
             
               wsql = wsql||'VRH_EMP_TSITCOL sit ';
               wsql = wsql||'join VRH_BASE_TPREPSIT pSit on (psit.BDCODSIT = sit.BDCODSIT) ';
               wsql = wsql||'join VRH_BASE_TPREPSIT_DIA PSITDIA on (PSITDIA.BDCODSIT = PSIT.BDCODSIT ';
               wsql = wsql||'and PSITDIA.BDDATASTD = (select MAX(X.BDDATASTD) from VRH_BASE_TPREPSIT_DIA X where X.BDCODSIT = SIT.BDCODSIT)) ';
               wsql = wsql||'left outer join VRH_BASE_TMOTFGTS fgtsent on (psit.BDCODMFGENT = fgtsent.BDCODMFG) ';
               wsql = wsql||'left outer join VRH_BASE_TMOTFGTS fgtssai on (psit.BDCODMFGSAI = fgtssai.BDCODMFG) ';
             
               wsql = wsql||' where SIT.BDCODEMP = '||wemporig||' and SIT.BDCODCOL = '||wcolorig||' and';
               wsql = wsql||'       not exists(select *';
               wsql = wsql||'                  from VRH_EMP_TSITCOL SIT2';
               wsql = wsql||'                  where';

               IF (Coalesce(BDCODEMP,0) > 0) THEN
                 wsql = wsql||'                      SIT2.BDCODEMP = '||BDCODEMP||' and';

               IF (Coalesce(BDCODEMP,0) > 0) THEN
                 wsql = wsql||'                      SIT2.BDCODCOL = '||BDCODCOL||' and';

               wsql = wsql||'                        SIT2.BDDATAINISEFIP = SIT.BDDATAINISEFIP)';

             
               IF (prdatini IS NOT NULL AND prdatfim IS NOT NULL) THEN
                  BEGIN
                    wsql = wsql||' and ';
                    wsql = wsql||'((sit.BDDATAINISEFIP between '''||:PRDATINI||''' AND '''||:PRDATFIM||''') or ';
                    wsql = wsql||'(sit.BDDATAFIMSIT between '''||:PRDATINI||''' AND '''||:PRDATFIM||''') or ';
                    wsql = wsql||'(sit.BDDATAINISEFIP < '''||:PRDATINI||''' and (sit.BDDATAFIMSIT is null or sit.BDDATAFIMSIT > '''||:PRDATFIM||'''))) ';
                  END
             
               FOR EXECUTE STATEMENT wsql INTO
                 :BDCODSIT, :BDDATAINISEFIP,
                 :BDDATAINISIT, :BDDATAFIMSIT, :BDDIASSIT, :BDNBENEFICIOSIT, :BDDATAPERICIASIT, :BDDATAPARTOSIT,
                 :BDDESCSIT, :BDGRUPOSIT, :BDCODVER, :BDCODMFGENT, :BDCODMFGSAI, :BDCARENSIT, :BDCODVER15DIAS,
                 :BDTIPOPERDESIT, :BDSALFAMSIT, :bdcodsefent, :bdcodsefsai, :bdrelsit, :BDINSSINTSIT, :BDDIASATESTADO,
                 :BDNAOPRORROGAFERIAS, :BDIMPRIMEDADOSSIT ,:BDSUSPENSAO, :BDDIASPERDEPERAQUI
               DO
                 begin
                   execute statement 'select first 1 BDNAOALTPERAQUIMP936 from VRHF_BASE_TEMPPAR where bdcodemp = ' || :BDCODEMP into BDNAOALTPERAQUIMP936;
                 SUSPEND;
                 end

               wempx = null;
               wcolx = null;

               select bdcodemp from TMP_CONTROLE_PERAQUISFE where BDSPINSERIU=1 AND bdcodemp = :wemporig and bdcodcol = :wcolorig and bdsessao = current_connection into :wcodcontrole;
               if (wcodcontrole is null) then
                  begin
               select first 1 BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = :wemporig and BDCODCOLDEST = :wcolorig into :wempx, :wcolx;
               wemporig = wempx;
               wcolorig = wcolx;
                    insert into TMP_CONTROLE_PERAQUISFE (BDCODEMP,BDCODCOL,BDSESSAO,BDSPINSERIU) values (:wemporig,:wcolorig,current_connection,1);
             end
               else
                  begin
                    wemporig = null;
                    wcolorig = null;
         end
   end
         end
   end
  delete from TMP_CONTROLE_PERAQUISFE WHERE BDSPINSERIU = 1 AND BDSESSAO = current_connection;
END^

CREATE OR ALTER TRIGGER tol_vef_emp_tgiastger_ad0 FOR tol_vef_emp_tgiastger
ACTIVE AFTER DELETE POSITION 0
AS
begin
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.bdcodemp, OLD.bdchave);
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TPARIMP_AD0 FOR TOL_VEF_EMP_TPARIMP
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC, OLD.BDCHAVE);
END
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TPARIMPENC_AD0 FOR TOL_VEF_EMP_TPARIMPENC
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC, OLD.BDCHAVE);
END
^

/* Trigger: TOL_VEF_EMP_TPARIMPDARF_AD0 */
CREATE OR ALTER TRIGGER TOL_VEF_EMP_TPARIMPDARF_AD0 FOR TOL_VEF_EMP_TPARIMPDARF
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  DELETE FROM TDARFGERPGTO
  WHERE BDCODEMP = OLD.BDCODEMP AND
        BDCHAVEPGTODARF = OLD.BDCHAVEPGTODARF;
END
^

/* Trigger: TOL_TPARCELAIMPOSTOPGTO_AD0 */
CREATE OR ALTER TRIGGER TOL_TPARCELAIMPOSTOPGTO_AD0 FOR TOL_TPARCELAIMPOSTOPGTO
ACTIVE AFTER DELETE POSITION 0
AS
begin
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC, OLD.BDCHAVE);
end
^

CREATE OR ALTER trigger tol_vsuc_emp_tapuracaocmv_ad0 for tol_vsuc_emp_tapuracaocmv
active after delete position 0
AS
begin
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.bdchave);
end^

CREATE OR ALTER TRIGGER VSUC_EMP_TPREPVARCAMBIAL_BI0 FOR VSUC_EMP_TPREPVARCAMBIAL
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE WCODIGO INTEGER;
BEGIN
  WCODIGO = 0;
  IF ((NEW.BDCODPREP IS NULL) OR (NEW.BDCODPREP = 0)) THEN
  BEGIN
    SELECT COALESCE((MAX(BDCODPREP) + 1), 1)
    FROM VSUC_EMP_TPREPVARCAMBIAL
    WHERE BDCODEMP = NEW.BDCODEMP
    INTO WCODIGO;

    NEW.BDCODPREP = WCODIGO;
  END
END
^

CREATE OR ALTER TRIGGER TOL_VSUC_EMP_TVARCAMBIAL_AD0 FOR TOL_VSUC_EMP_TVARCAMBIAL
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC, OLD.BDCHAVE);
END
^

CREATE OR ALTER trigger tol_vef_emp_tmovent_ser_ad0 for tol_vef_emp_tmovent_ser
active after delete position 0
AS
BEGIN
  EXECUTE STATEMENT 'DELETE FROM VEF_EMP_TMOVSER WHERE BDCODEMP = '||OLD.BDCODEMP||' AND BDCHAVE = '||OLD.BDCHAVESER;
END^

CREATE OR ALTER TRIGGER VFIN_ESC_TCOBRANCAUTOMATICA_BI0 FOR VFIN_ESC_TCOBRANCAUTOMATICA
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
  declare variable vcodigo integer;
begin
  if ((new.bdcodcobaut is null) or (new.bdcodcobaut = 0)) then
  begin
    select first 1 coalesce(bdcodcobaut, 0)+1 from vfin_esc_tcobrancautomatica
    where bdcodesc = new.bdcodesc
    and bdcodcli = new.bdcodcli
    order by bdcodcobaut desc
    into :vcodigo;
    new.bdcodcobaut = vcodigo;
  end
end^

CREATE OR ALTER TRIGGER VSUC_EMPRESAS_TEXTRATOBAN_BI0 FOR VSUC_EMPRESAS_TEXTRATOBAN
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNova_chave INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM VSUC_EMPRESAS_TEXTRATOBAN WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
      NEW.BDCHAVE = vNova_Chave;
    END
  ELSE
    BEGIN
       SELECT BDCHAVE FROM VSUC_EMPRESAS_TEXTRATOBAN WHERE (BDCHAVE = NEW.BDCHAVE) AND (bdcodemp = NEW.bdcodemp) INTO vcodigo;

       IF (vcodigo > 0) THEN
         BEGIN
           SELECT COALESCE((MAX(BDCHAVE)+1), 1) FROM VSUC_EMPRESAS_TEXTRATOBAN WHERE bdcodemp = NEW.bdcodemp INTO vNova_Chave;
           NEW.BDCHAVE = vNova_Chave;
         END
    END
END
^


create or alter procedure SP_VRH_CONSULTA_AUT_RPA (
    PRREF integer,
    PRRESULDADOS integer = null,
    PRSOLETRADO varchar(10000) = null)
returns (
    BDCODTER integer,
    BDCPFTER DM_CNPJ_CPF,
    BDNOMTER varchar(100),
    BDCPFMEITER varchar(14),
    BDPISTER varchar(14),
    BDSTATUSQC integer,
    BDENQSIMPLESFEDTER integer,
    BDNOMESOCIALTER varchar(100),
    BDGERARNMSOCIALTER varchar(5),
    BDINATIVO varchar(5))
as
declare variable WSQL varchar(1000);
declare variable WACHOU smallint;
declare variable WCODTER integer;
begin
  wsql = 'select ';

  if (coalesce(prresuldados, 0) > 0) then
     wsql = wsql||'first '||prresuldados||' ';

  wsql = wsql||'TERC.BDCODTER, TERC.BDCGCTER, TERC_RH.BDCPFMEITER '||
         'from TTERCEIRO TERC '||
         'left outer join TTERCEIRO_RH TERC_RH on (TERC_RH.BDCODTER = TERC.BDCODTER) '||
         'where (char_length(TERC.BDCGCTER) = 14) or (char_length(TERC_RH.BDCPFMEITER) = 14) '||
         'order by TERC.BDCODTER ';

  for execute statement :wsql
  into :BDCODTER, :BDCPFTER, :BDCPFMEITER
  do
    begin
      wachou = 0;
    BDPISTER = null;
      BDNOMTER = null;
      BDENQSIMPLESFEDTER = null;
      BDSTATUSQC = null;

      if (coalesce(prsoletrado, '') <> '') then
         begin
           wcodter = null;
           select first 1 BDCODTER, BDNOMETER, BDENQSIMPLESFEDTER, BDNOMESOCIALTER, case BDGERARNMSOCIALTER when 'TRUE' then 'Sim' else 'Não' end BDGERARNMSOCIALTER, BDINATIVO from TTERCEIRO_REF where BDCODTER = :BDCODTER and BDREFEMP <= :prref and
           ((upper(BDNOMETER collate WIN_PTBR) like :prsoletrado||'%') or (BDENQSIMPLESFEDTER like :prsoletrado||'%'))
           order by BDREFEMP DESC into :wcodter, :BDNOMTER, :BDENQSIMPLESFEDTER, :BDNOMESOCIALTER, :BDGERARNMSOCIALTER, :BDINATIVO;

           if (wcodter is not null) then
              wachou = 1;
           else
             select first 1 BDCODTER, BDNOMETER, BDENQSIMPLESFEDTER, BDNOMESOCIALTER, case BDGERARNMSOCIALTER when 'TRUE' then 'Sim' else 'Não' end BDGERARNMSOCIALTER, BDINATIVO from TTERCEIRO_REF where BDCODTER = :BDCODTER and BDREFEMP <= :prref
             order by BDREFEMP DESC into :wcodter, :BDNOMTER, :BDENQSIMPLESFEDTER, :BDNOMESOCIALTER, :BDGERARNMSOCIALTER, :BDINATIVO;

           if (wachou = 1) then
              select first 1 BDSTATUSQC from VRH_BASE_TTERC_DOC where BDCODTER = :BDCODTER into :BDSTATUSQC;
           else
              begin
                wcodter = null;
                select first 1 BDCODTER, BDSTATUSQC from VRH_BASE_TTERC_DOC where BDCODTER = :BDCODTER and
                BDSTATUSQC like :prsoletrado||'%'
                into :wcodter, :BDSTATUSQC;

                if (wcodter is not null) then
                   wachou = 1;
                else
                   select first 1 BDSTATUSQC from VRH_BASE_TTERC_DOC where BDCODTER = :BDCODTER into :BDSTATUSQC;
              end

           if (wachou = 1) then
              select first 1 BDPISTER from VRH_BASE_TTERC_DOCREF where BDCODTER = :BDCODTER and BDREFTERC <= :prref
              order by BDREFTERC DESC
              into :BDPISTER;
           else
              begin
                wcodter = null;
                select first 1 BDCODTER, BDPISTER from VRH_BASE_TTERC_DOCREF where BDCODTER = :BDCODTER and BDREFTERC <= :prref and
                BDPISTER like :prsoletrado||'%'
                order by BDREFTERC DESC
                into :wcodter, :BDPISTER;

                if (wcodter is not null) then
                   wachou = 1;
                else
                   select first 1 BDPISTER from VRH_BASE_TTERC_DOCREF where BDCODTER = :BDCODTER and BDREFTERC <= :prref order by BDREFTERC DESC into :BDPISTER;
              end
         end
      else
         begin
           wachou = 1;
           select first 1 BDNOMETER, BDENQSIMPLESFEDTER, BDNOMESOCIALTER, case BDGERARNMSOCIALTER when 'TRUE' then 'Sim' else 'Não' end BDGERARNMSOCIALTER, BDINATIVO from TTERCEIRO_REF where BDCODTER = :BDCODTER and BDREFEMP <= :prref order by BDREFEMP DESC into :BDNOMTER, :BDENQSIMPLESFEDTER, :BDNOMESOCIALTER, :BDGERARNMSOCIALTER, :BDINATIVO;
           select first 1 BDSTATUSQC from VRH_BASE_TTERC_DOC where BDCODTER = :BDCODTER into :BDSTATUSQC;
           select first 1 BDPISTER from VRH_BASE_TTERC_DOCREF where BDCODTER = :BDCODTER and BDREFTERC <= :prref order by BDREFTERC DESC into :BDPISTER;
         end

      if (wachou = 1) then
         begin
           if (((char_length(BDCPFTER) = 14) or ((char_length(BDCPFMEITER) = 14) and (BDENQSIMPLESFEDTER = 3)))) then
              suspend;
         end

    end
end^

CREATE OR ALTER TRIGGER TR_BF_INSERT_TPCC_ECD_I157 FOR CENTROS_TPCC_ECD_I157
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF ((NEW.bdcodplapadraoi157 IS NULL) OR (NEW.bdcodplapadraoi157 = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodplapadraoi157)+1),1) FROM CENTROS_TPCC_ECD_I157 INTO vcodigo;
        NEW.bdcodplapadraoi157 = vcodigo;
     END
END
^

/* Trigger: TR_BF_INSERT_TPCC_ECD_I157 */
CREATE OR ALTER TRIGGER TR_BF_INSERT_EMP_TPCC_I157 FOR EMPRESAS_TPCC_ECD_I157
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  IF ((NEW.bdcodplapadraoi157 IS NULL) OR (NEW.bdcodplapadraoi157 = 0)) THEN
     BEGIN
        SELECT COALESCE((MAX(bdcodplapadraoi157)+1),1) FROM EMPRESAS_TPCC_ECD_I157 INTO vcodigo;
        NEW.bdcodplapadraoi157 = vcodigo;
     END
END
^

CREATE or ALTER trigger empresas_tmotivobai_bi0 for empresas_tmotivobai
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
BEGIN
  vcodigo = 0;
  IF ((NEW.bdcodmot IS NULL) OR (NEW.bdcodmot = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodmot)+1), 1) FROM empresas_tmotivobai INTO vCodigo;
      NEW.bdcodmot = vCodigo;
     END
END^

CREATE OR ALTER TRIGGER VEF_EMP_TBASELEGALISS_BI0 FOR VEF_EMP_TBASELEGALISS
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE wOrdem INTEGER;
  DECLARE VARIABLE wChave INTEGER;
BEGIN
  IF ((NEW.bdCHAVE IS NULL) OR (NEW.bdCHAVE = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdCHAVE)), 1) FROM VEF_EMP_TMOVSER WHERE (bdCODEMP = NEW.bdCODEMP) INTO wChave;
      NEW.bdCHAVE = wChave;
    END

  IF ((NEW.bdORDEM IS NULL) OR (NEW.bdORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(bdORDEM)), 1) FROM VEF_EMP_TMOVSERITENS WHERE (bdCODEMP = NEW.bdCODEMP)  AND (bdCHAVE = NEW.bdCHAVE) INTO wOrdem;
      NEW.bdORDEM = wOrdem;
    END
END
^

CREATE or alter trigger vef_emp_tmovserdsf_bi0 for vef_emp_tmovserdsf
active before insert position 0
as
  declare variable WORDEM integer;
  declare variable WCHAVE integer;
begin
  if ((new.BDCHAVE is null) or (new.BDCHAVE = 0)) then
    begin
      select coalesce((max(BDCHAVE)), 1)
      from VEF_EMP_TMOVSER
      where (BDCODEMP = new.BDCODEMP)
      into WCHAVE;

      new.BDCHAVE = WCHAVE;
    end

  if ((new.BDORDEM is null) or (new.BDORDEM = 0)) then
    begin
      select coalesce((max(BDORDEM)), 1)
      from VEF_EMP_TMOVSERITENS
      where (BDCODEMP = new.BDCODEMP) and
            (BDCHAVE = new.BDCHAVE)
      into WORDEM;

      new.BDORDEM = WORDEM;
    end
end
^

CREATE OR ALTER TRIGGER VRHP_BASE_CONF_DET_BI0 FOR VRHP_BASE_CONF_DET
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  NEW.BDTIPOTOTAL = 0;
  NEW.BDHORASAPOS = LPAD(TRIM(NEW.BDHORASAPOS), 6, '0');
END
^

CREATE OR ALTER TRIGGER VRHP_BASE_CONF_DET_BU0 FOR VRHP_BASE_CONF_DET
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  NEW.BDTIPOTOTAL = 0;
  NEW.BDHORASAPOS = LPAD(TRIM(NEW.BDHORASAPOS), 6, '0');
END^

CREATE OR ALTER TRIGGER VRHP_BASE_CONF_DET_REF_BI0 FOR VRHP_BASE_CONF_DET_REF
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  NEW.BDTIPOTOTAL = 0;
  NEW.BDHORASAPOS = LPAD(TRIM(NEW.BDHORASAPOS), 6, '0');
END^

CREATE OR ALTER TRIGGER VRHP_BASE_CONF_DET_REF_BU0 FOR VRHP_BASE_CONF_DET_REF
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  NEW.BDTIPOTOTAL = 0;
  NEW.BDHORASAPOS = LPAD(TRIM(NEW.BDHORASAPOS), 6, '0');
END^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_REF_AU0 FOR TCONF_CONTAS_ONLINE_REF
ACTIVE AFTER UPDATE POSITION 0
AS
 DECLARE VARIABLE vCount INTEGER;
 declare variable wnada BIGINT;

BEGIN
  /* Trigger text */

  SELECT first 1 GEN_ID(GEN_ALT_PLANOONLINE, 1) FROM RDB$DATABASE into :wnada;

  IF ((NEW.BDCOPYTITULO IS NULL) OR (NEW.BDCOPYTITULO <> 1)) THEN
     BEGIN
       SELECT COUNT(*) FROM tol_update_conta up
              WHERE up.bdcodplanoonline = NEW.bdcodplanoonline
                   AND (up.bdchave = NEW.bdchave OR
                        up.bdchavetitulo = NEW.bdchave) INTO vCount;
       IF (vCount > 0) THEN
          BEGIN
            EXECUTE PROCEDURE sp_atu_lancamentos_contabil(NEW.bdcodplanoonline,NEW.bdchave,0,
                                                          NEW.BDCONTADEBPROV,NEW.BDCONTACREDPROV,NEW.BDCODHISTPROV,
                                                          OLD.BDCONTADEBPROV,OLD.BDCONTACREDPROV,OLD.BDCODHISTPROV,
                                                          NEW.BDCODPLAPADRAO,NULL, NEW.BDREFCTA, 0,
                                                          NEW.BDCODCOMPHISTPROV, OLD.BDCODCOMPHISTPROV);
          
            EXECUTE PROCEDURE sp_atu_lancamentos_contabil(NEW.bdcodplanoonline,NEW.bdchave,1,
                                                          NEW.BDCONTADEBPGTO,NEW.BDCONTACREDPGTO,NEW.BDCODHISTPGTO,
                                                          OLD.BDCONTADEBPGTO,OLD.BDCONTACREDPGTO,OLD.bdcodhistpgto,
                                                          NEW.BDCODPLAPADRAO,NULL, NEW.BDREFCTA, 0,
                                                          NEW.BDCODCOMPHISTPGTO, OLD.BDCODCOMPHISTPGTO);
          END
   END
END
^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_AI0 FOR TCONF_CONTAS_ONLINE
ACTIVE AFTER INSERT POSITION 0
AS
begin
  if (NEW.BDCHAVEVINC IS NULL) then
      BEGIN
        INSERT INTO tconf_contas_online_ref (bdcodplanoonline, bdchave, bdrefcta, bdcodplapadrao, bdcodtphi, bdcontadebprov,
                                             bdcontacredprov, bdcodhistprov, bdcodcomphistprov, bdcontadebpgto, bdcontacredpgto,
                                             bdcodhistpgto, bdcodcomphistpgto, bdcopytitulo)
        VALUES (NEW.bdcodplanoonline, new.bdchave, 0, new.bdcodplapadrao, new.bdcodtphi, new.bdcontadebprov, new.bdcontacredprov,
                new.bdcodhistprov, new.bdcodcomphistprov, new.bdcontadebpgto, new.bdcontacredpgto, new.bdcodhistpgto, new.bdcodcomphistpgto,
                new.bdcopytitulo);
      END
END
^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_REF_BU0 FOR TCONF_CONTAS_ONLINE_REF
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
DECLARE VARIABLE wsql VARCHAR(1000);  
DECLARE VARIABLE wclassificacao VARCHAR(5000);
DECLARE VARIABLE wvalue VARCHAR(5);
DECLARE VARIABLE v1 INTEGER;
DECLARE VARIABLE v2 INTEGER;
DECLARE VARIABLE v3 INTEGER;
BEGIN
  /* Trigger text */
  IF ((NEW.bdcontacredprov <> OLD.bdcontacredprov) OR
     ((NEW.bdcontacredprov IS NULL) OR (OLD.bdcontacredprov IS NOT NULL)) OR
     ((NEW.bdcontacredprov IS NOT NULL) OR (OLD.bdcontacredprov IS NULL))) THEN
     BEGIN
       --#alt:155189 - 16/09/2021 - Machado - Lentidão na Cópia plano de contabilização ao usar SP
       SELECT FIRST 1 coalesce(i.bdconfigdebpag,t.bdconfigdebpag) bdconfigdebpag FROM TCONF_CONTAS_ONLINE c
       join ttipocontaonline t on (c.bdcodtipoconta = t.bdcodtipoconta) 
       left outer join titemconfigonline i on (c.bdcoditemonline = i.bdcoditemonline)
       WHERE c.bdcodplanoonline = NEW.BDCODPLANOONLINE AND c.BDCHAVE = NEW.BDCHAVE into :wvalue;
       wvalue = UPPER(wvalue);

       IF ((wvalue = 'INVCD') OR ((wvalue = 'IEDCD') AND (COALESCE(NEW.bdcontadebpgto, 0) = 0))) THEN
          BEGIN
            NEW.bdcontadebpgto = NEW.bdcontacredprov;
          END
     END

  IF ((NEW.bdcontadebprov <> OLD.bdcontadebprov) OR
     ((NEW.bdcontadebprov IS NULL) OR (OLD.bdcontadebprov IS NOT NULL)) OR
     ((NEW.bdcontadebprov IS NOT NULL) OR (OLD.bdcontadebprov IS NULL))) THEN
     BEGIN
       --#alt:155189 - 16/09/2021 - Machado - Lentidão na Cópia plano de contabilização ao usar SP
       SELECT FIRST 1 coalesce(i.BDCONFIGCREDPAG,t.BDCONFIGCREDPAG) BDCONFIGCREDPAG FROM TCONF_CONTAS_ONLINE c
       join ttipocontaonline t on (c.bdcodtipoconta = t.bdcodtipoconta) 
       left outer join titemconfigonline i on (c.bdcoditemonline = i.bdcoditemonline)
       WHERE c.bdcodplanoonline = NEW.BDCODPLANOONLINE AND c.BDCHAVE = NEW.BDCHAVE into :wvalue;
       wvalue = UPPER(wvalue);

--       if (wvalue = 'INVDC') then
       IF ((wvalue = 'INVDC') OR ((wvalue = 'IEDDC') AND (COALESCE(NEW.bdcontacredpgto, 0) = 0))) THEN
          BEGIN
            NEW.bdcontacredpgto = NEW.bdcontadebprov;
          END
     END

  IF ((NEW.BDCODPLAPADRAO IS NULL) OR (NEW.BDCODTPHI IS NULL))  THEN
     BEGIN
       SELECT BDCODPLAPADRAO,BDCODHIST,BDCODCENTRO FROM tplano_conf_online WHERE bdcodplanoonline = NEW.BDCODPLANOONLINE INTO v1,v2, v3;

       IF (NEW.BDCODPLAPADRAO IS NULL)  THEN
          NEW.BDCODPLAPADRAO = v1;
       IF (NEW.BDCODTPHI IS NULL) THEN
          NEW.BDCODTPHI = v2;

     END
END
^

CREATE OR ALTER procedure VSUC_SP_COPY_PREP_REL_LALUR (
    PRCODPARTEA integer,
    PRTIPAPU integer,
    PRDE_ANO integer,
    PRPARA_ANO integer,
    PROPCAO integer)
as
declare variable WSQL varchar(5000);
declare variable WCODPLAPADRAOREFLALUR integer;
declare variable WCODTPLAREFLALUR integer;
declare variable WCODPLAPADRAOREFLALURMENSAL integer;
declare variable WCODTPLAREFLALURMENSAL integer;
declare variable WCODLPA integer;
begin

   if (:propcao = 0) then
      begin
        wsql = 'delete from PLANOS_TPLA_ECF_LALUR where BDCODPARTEA = '||:prcodpartea||' and BDTIPAPU = '||prtipapu||' and BDANO = '||:prpara_ano;
      end
   wSQL = 'select BDCODLPA, BDCODPLAPADRAOREFLALUR, BDCODTPLAREFLALUR, BDCODPLAPADRAOREFLALURMENSAL, BDCODTPLAREFLALURMENSAL ';
   wsQL = wSQL||' from PLANOS_TPLA_ECF_LALUR L1 where BDCODPARTEA = '||:prcodpartea||' and BDTIPAPU = '||prtipapu||' and BDANO = '||:prde_ano;
   if (:propcao = 1) then
      begin
        wSQL = wSQL||'and not exists( select * ';
        wsQL = wSQL||' from PLANOS_TPLA_ECF_LALUR as L2 where L2.BDCODLPA = L1.BDCODLPA and  L2.BDCODPARTEA = L1.BDCODPARTEA and L2.BDTIPAPU = L1.BDTIPAPU and L2.BDANO = '||:prpara_ano||')';
      end

   FOR EXECUTE STATEMENT wSQL INTO :WCODLPA,:WCODPLAPADRAOREFLALUR,:WCODTPLAREFLALUR,:wCODPLAPADRAOREFLALURMENSAL,:WCODTPLAREFLALURMENSAL DO
       begin
           update or insert into PLANOS_TPLA_ECF_LALUR (BDCODPARTEA, BDCODLPA, BDCODPLAPADRAOREFLALUR, BDCODTPLAREFLALUR,
                                                        BDANO, BDTIPAPU, BDCODPLAPADRAOREFLALURMENSAL,BDCODTPLAREFLALURMENSAL)
           values (:prcodpartea,:WCODLPA,:WCODPLAPADRAOREFLALUR,:WCODTPLAREFLALUR,:prpara_ano,:prtipapu,:wCODPLAPADRAOREFLALURMENSAL,:WCODTPLAREFLALURMENSAL)
           matching(BDCODPARTEA,BDCODLPA, BDTIPAPU, BDANO);
       END
  ---suspend;
end^

CREATE OR ALTER procedure VSUC_SP_COPY_PREP_ECF_LALUR (
    PRCODPARTEB integer,
    PRCODPLAPADRAOREFLALUR integer,
    PRDE_ANO integer,
    PRPARA_ANO integer,
    PROPCAO integer)
as
declare variable WSQL varchar(10000);
declare variable WCODLPB integer;
declare variable WCODTPLAREFLALUR integer;
begin

  if (:PROPCAO = 0) then
      begin
        wSQL = 'delete from PLANOS_TPLA_ECF_LALUR_TLPB where BDCODPARTEB = '||:prcodparteb||' and BDCODPLAPADRAOREFLALUR = '||:prcodplapadraoreflalur||' and BDANO = '||prpara_ano;
        execute statement wsql;
      end

  wSQL = 'select BDCODLPB, BDCODTPLAREFLALUR from PLANOS_TPLA_ECF_LALUR_TLPB L where ';
  wSQL = WSQL||'BDCODPARTEB = '||:prcodparteb||' and BDCODPLAPADRAOREFLALUR = '||:prcodplapadraoreflalur||' and BDANO = '||prde_ano;
  if (:PROPCAO = 1) then
     begin
       wSQL = WSQL||' and not exists(select * ';
       wSQL = WSQL||' from PLANOS_TPLA_ECF_LALUR_TLPB LB where ';
       wSQL = WSQL||' LB.BDCODPARTEB = L.BDCODPARTEB and LB.BDCODPLAPADRAOREFLALUR = L.BDCODPLAPADRAOREFLALUR and LB.BDCODLPB = L.BDCODLPB and LB.BDANO =  '||:prpara_ano||')';
     end

  FOR EXECUTE STATEMENT wSQL INTO :wCODLPB, :WCODTPLAREFLALUR DO
  begin
    update or insert into PLANOS_TPLA_ECF_LALUR_TLPB (BDCODPARTEB, BDCODPLAPADRAOREFLALUR, BDCODLPB,BDANO, BDCODTPLAREFLALUR)
                                               values(:prcodparteb,:prcodplapadraoreflalur,:wCODLPB,:prpara_ano,:WCODTPLAREFLALUR) matching(BDCODPARTEB,BDCODLPB,BDANO);
  end
  ---suspend;
end^

CREATE OR ALTER procedure VSUC_SP_COPY_PREPARACAO_FOR_ECF (
    PRCODPLAPADRAOFORM integer,
    PRCODPLAPADRAO integer,
    PRDE_ANO integer,
    PRPARA_ANO integer,
    PROPCAO integer)
as
declare variable WTIPOFOR integer;
declare variable WSQL varchar(10000);
declare variable WCODTFORREF integer;
declare variable WFORMULA varchar(20000);
BEGIN

   if (:PROPCAO = 0) then
      begin
        wSQL = 'delete from PLANOS_TFOR_ECF where BDCODPLAFORPADRAOREF = '||:PRCODPLAPADRAOFORM||' and BDCODPLAPADRAO = '||:prCODPLAPADRAO||' and BDANO = '||:PRPARA_ANO;

        execute statement wsql;
      end

   wSQL = 'select BDCODTFORREF, BDDESCFOR, BDTIPOFOR from PLANOS_TFOR_ECF F1 where ';
   wSQL = wSQL||'BDCODPLAFORPADRAOREF = '||:prcodplapadraoform||' and BDCODPLAPADRAO = '||:prCODPLAPADRAO||' and BDANO = '||:PRDE_ANO;
   if (propcao = 1) then
      begin
        wSQL = wSQL||' and not exists(select *';
        wSQL = wSQL||'  from PLANOS_TFOR_ECF F2 where ';
        wSQL = wSQL||'  F2.BDCODPLAFORPADRAOREF = F1.BDCODPLAFORPADRAOREF and F2.BDCODPLAPADRAO = F1.BDCODPLAPADRAO and F2.BDCODTFORREF = F1.BDCODTFORREF and F2.BDANO =  '||:PRPARA_ANO||')';
      end

   FOR EXECUTE STATEMENT wSQL INTO :wCODTFORREF, :WFORMULA, :WTIPOFOR DO
     BEGIN
       update or insert into PLANOS_TFOR_ECF (BDCODPLAFORPADRAOREF, BDCODTFORREF, BDCODPLAPADRAO, BDANO, BDDESCFOR, BDTIPOFOR)
       values (:prcodplapadraoform,:wCODTFORREF,:prcodplapadrao,:prpara_ano,:wformula,:wtipofor) matching(BDCODPLAFORPADRAOREF, BDCODTFORREF, BDCODPLAPADRAO, BDANO);

    END

END^

CREATE OR ALTER procedure VSUC_SP_COPY_PREPARACAO_FOR_ECF_PAIS (
    PRCODPLAPADRAOFORM integer,
    PRCODPLAPADRAO integer,
    PRCODPAIS integer,
    PRDE_ANO integer,
    PRPARA_ANO integer,
    PROPCAO integer)
as
declare variable WTIPOFOR integer;
declare variable WSQL varchar(10000);
declare variable WCODTFORREF integer;
declare variable WFORMULA varchar(20000);
BEGIN

   if (:PROPCAO = 0) then
      begin
        wSQL = 'delete from PLANOS_TFOR_ECF_PAIS where BDCODPLAFORPADRAOREF = '||:PRCODPLAPADRAOFORM||' and BDCODPLAPADRAO = '||:prCODPLAPADRAO||' and BDCODPAIS = '||:prCODPAIS||' and BDANO = '||:PRPARA_ANO;

        execute statement wsql;
      end

   wSQL = 'select BDCODTFORREF, BDDESCFOR, BDTIPOFOR from PLANOS_TFOR_ECF_PAIS F1 where ';
   wSQL = wSQL||'BDCODPLAFORPADRAOREF = '||:prcodplapadraoform||' and BDCODPLAPADRAO = '||:prCODPLAPADRAO||' and BDCODPAIS = '||:prCODPAIS||' and BDANO = '||:PRDE_ANO;
   if (propcao = 1) then
      begin
        wSQL = wSQL||' and not exists(select *';
        wSQL = wSQL||'  from PLANOS_TFOR_ECF_PAIS F2 where ';
        wSQL = wSQL||'  F2.BDCODPLAFORPADRAOREF = F1.BDCODPLAFORPADRAOREF and F2.BDCODPLAPADRAO = F1.BDCODPLAPADRAO and F2.BDCODTFORREF = F1.BDCODTFORREF and F2.BDCODPAIS = F1.BDCODPAIS and F2.BDANO =  '||:PRPARA_ANO||')';
      end

   FOR EXECUTE STATEMENT wSQL INTO :wCODTFORREF, :WFORMULA, :WTIPOFOR DO
     BEGIN
       update or insert into PLANOS_TFOR_ECF_PAIS (BDCODPLAFORPADRAOREF, BDCODTFORREF, BDCODPLAPADRAO, BDCODPAIS, BDANO, BDDESCFOR, BDTIPOFOR)
       values (:prcodplapadraoform,:wCODTFORREF,:prcodplapadrao,:prcodpais,:prpara_ano,:wformula,:wtipofor) matching(BDCODPLAFORPADRAOREF, BDCODTFORREF, BDCODPLAPADRAO, BDCODPAIS, BDANO);

    END

END^


CREATE OR ALTER TRIGGER vrhp_base_impponto_bi0 for vrhp_base_impponto
active before insert position 0
AS
 declare variable vcod INTEGER;
begin
   if (COALESCE(new.BDCODIMPPONTO, 0) = 0) then
     begin
       select COALESCE(MAX(BDCODIMPPONTO) + 1, 1) from VRHP_BASE_IMPPONTO into :vcod;
       new.BDCODIMPPONTO = :vcod;
     end
end^


CREATE OR ALTER TRIGGER VRH_ARQ_EXP_SEFIP_BI0 FOR VRH_ARQ_EXP_SEFIP
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vchave INTEGER;
begin
  if (coalesce(new.bdchave, 0) = 0) then
     begin
       vchave = null;
       select coalesce(max(BDCHAVE), 0) + 1 from VRH_ARQ_EXP_SEFIP into :vchave;

       vchave = coalesce(vchave, 1);

       new.bdchave = :vchave;
     end
end
^

/* Trigger: VRH_EMP_ESOCIAL_BAIXAR_DATA_BI0 */
CREATE OR ALTER TRIGGER VRH_EMP_ESOCIAL_BAIXAR_DATA_BI0 FOR VRH_EMP_ESOCIAL_BAIXAR_DATA
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (NEW.BDORDEM IS NULL) THEN
    SELECT COALESCE(MAX(BDORDEM) + 1, 1)
    FROM VRH_EMP_ESOCIAL_BAIXAR_DATA B
    WHERE B.BDCHAVE = NEW.BDCHAVE
    INTO NEW.BDORDEM;
END
^

/* Trigger: VRH_EMP_ESOCIAL_BAIXAR_BI0 */
CREATE OR ALTER TRIGGER VRH_EMP_ESOCIAL_BAIXAR_BI0 FOR VRH_EMP_ESOCIAL_BAIXAR
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (NEW.BDCHAVE IS NULL OR NEW.BDCHAVE = 0) THEN
    SELECT COALESCE(MAX(BDCHAVE) + 1, 1)
    FROM VRH_EMP_ESOCIAL_BAIXAR B
    INTO NEW.BDCHAVE;
END
^

-- 140108 - Raphael Teodoro - 06/08/2020
CREATE OR ALTER TRIGGER VRH_EMP_DCTFWEB_BIU0 FOR VRH_EMP_DCTFWEB
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
as
begin
  /* Trigger text */
  IF ((COALESCE(OLD.bdtipo,0) <> COALESCE(NEW.bdtipo,0)) OR
      (COALESCE(OLD.bddatatransmissao,'01-01-2000') <> COALESCE(NEW.bddatatransmissao,'01-01-2000'))) THEN
     BEGIN
       IF (NEW.bdtipo IS NULL) THEN
          EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdref, '4', 'BDDCTFWEB'); -- 4 - Nao encontrado
       ELSE
       IF (NEW.bddatatransmissao IS NULL) THEN
          EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdref, '1', 'BDDCTFWEB'); -- 1 - Declarado
       ELSE
          EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdref, '3', 'BDDCTFWEB'); -- 3 - Transmitido
     END

  IF (COALESCE(OLD.bdintmanual,'') <> COALESCE(NEW.bdintmanual,'')) THEN
     BEGIN
       IF (NEW.bdintmanual = 'TRUE') THEN
          EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdref, '1', 'BDDCTFMANUAL'); -- 1 - Integrado manualmente
       ELSE
          EXECUTE PROCEDURE sp_vrh_painel_update(NEW.bdcodemp, NEW.bdref, ' ', 'BDDCTFMANUAL'); -- 0 - Sem integracao manual
     END
end
^

-- 140108 - Raphael Teodoro - 06/08/2020
CREATE OR ALTER TRIGGER VRH_EMP_DCTFWEB_AD0 FOR VRH_EMP_DCTFWEB
ACTIVE AFTER DELETE POSITION 0
as
begin
  /* Trigger text */
  EXECUTE PROCEDURE sp_vrh_painel_update(OLD.bdcodemp, OLD.bdref, '2', 'BDDCTFWEB'); -- 2 - Excluido
end
^

/* Restore proc. body: SP_VRHF_RESUMO_ADSAL */
create or alter procedure SP_VRHF_RESUMO_ADSAL (
    PREMP varchar(20000),
    PRCOL varchar(32700),
    PRDATAINI date,
    PRDATAFIM date,
    PRFUCDET smallint = 0,
    PRPUXAFILIAL smallint = 0)
returns (
    GRUPO_CLASSE integer,
    CODIGO_EMPRESA integer,
    CODIGO_FILIAL integer,
    NOME_EMPRESA DM_BDNOMEMP,
    ENDERECO_EMPRESA DM_BDENDERECO,
    NUMERO_EMPRESA DM_NUMEND,
    BAIRRO_EMPRESA DM_BDBAIRRO,
    CEP_EMPRESA DM_CEP,
    CNPJ_EMPRESA DM_CNPJ_CPF,
    CODIGO_COLABORADOR integer,
    NOME_COLABORADOR DM_BDNOMCOL,
    ADMISSAO_COLABORADOR date,
    FUNCAO_COLABORADOR varchar(100),
    CPF_COLABORADOR varchar(14),
    PIS_COLABORADOR varchar(14),
    CODIGO_VERBA integer,
    DESCRICAO_VERBA varchar(40),
    REFERENCIA_VERBA numeric(18,6),
    REFERENCIA_AUXILIAR_VERBA numeric(18,6),
    BDTIPOCODVER integer,
    PROVENTOS_FOLHA numeric(18,6),
    DESCONTOS_FOLHA numeric(18,6),
    SALARIO_BASE numeric(18,6),
    BDCODENQFED integer,
    BDSIMPLESGPS integer,
    CTPS_COL DM_BDCTPS,
    SERIE_CTPS DM_SERIECTPS,
    CBO_COL integer,
    HORAS_MENSAIS numeric(18,6),
    RAT_APO_COL numeric(18,6),
    REFERENCIA_FOLHA integer,
    BDORDEM integer,
    IRRF_FOLHA numeric(18,6),
    REFERENCIAAUX varchar(8),
    DESCRICAO_RED_VERBA varchar(20),
    CIDADE_EMPRESA varchar(40),
    UF_EMPRESA varchar(2),
    COMPL_EMPRESA DM_BDCOMPENDERECO,
    PISVER DM_BOOLEAN,
    BDORDEMTIPOCODVER integer,
    CLASSIFICA_VERBA varchar(20),
    RESCISAO_COLABORADOR date,
    MOTIVO_RESCISAO varchar(110),
    TIPO_RESCISAO integer,
    BDTEMGRRF integer,
    BDORDEMVER integer,
    DATA_PAG_IR date,
    BDTIPOREFVER integer,
    BDREFHOREMP DM_BOOLEAN,
    BDCCATVCONCOM DM_BOOLEAN,
    BDCATEGORIAESOCIAL integer,
    DEPSF integer,
    DEPIR integer,
    BDCONTRCOL integer,
    DATA_AD date,
    DATA_PAGAMENTO_FOLHA date,
    BDCODCENTROS integer,
    BDCODCLA integer,
    BDCODSINTRAB integer,
    BDCODTFUC integer)
as
declare variable WSQL varchar(32700);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WPLAFUC integer;
declare variable WCODTFUC integer;
declare variable WVALV numeric(18,6);
declare variable WCODCLA integer;
declare variable WREFRESCISAO integer;
declare variable WCODRES integer;
declare variable WGRRFPRES integer;
declare variable WFGTSMENSANT DM_BOOLEAN;
declare variable WDEPIR integer;
declare variable WDEPSF integer;
declare variable WEMPOK integer;
declare variable WCODCID integer;
declare variable WCODUF integer;
declare variable WREFAD integer;
declare variable WREFATU integer;
declare variable WHMES numeric(18,6);
begin
  if (trim(coalesce(premp, '')) <> '') then
     premp = upper(premp);

  if (trim(coalesce(prcol, '')) <> '') then
     prcol = upper(prcol);

  prpuxafilial = coalesce(prpuxafilial, 0);
  prfucdet = coalesce(prfucdet, 0);

   wsql = 'select COLCON.BDCODEMP,';

  if (prpuxafilial = 1) then
    wsql = wsql || ' coalesce(EMP.BDCODMATRIZ, COLCON.BDCODEMP),  ';
  else
    wsql = wsql || ' COLCON.BDCODEMP, ';

  wsql = wsql ||'COLCON.BDCODCOL, COLCON.BDCODVER, COLCON.BDREFAUXVAD, COLCON.BDREFVAD, COLCON.BDVALVAD, FOLN.BDORDEM, EMP.BDCNPJEMP, '||
                'VER.BDDESCVER, VERREF.BDTIPOCODVER, FOLN.BDSALBASEAD, FOLN.BDBASEIRAD, '||
                'VER.BDDESCREDVER, VERREF.BDPISVER, VERREF.BDORDEMTIPOCODVER, VER.BDCLAVER, '||
                'VER.BDORDEMVER, VERREF.BDTIPOREFVER, COLCON.BDDATAAD, COLCON.BDDATAAD, COLCON.BDDATAAD, FOLN.BDREFAD '||
         'from VRHF_EMP_TVERBAAD COLCON '||
         'join TEMPRESAS EMP on (EMP.BDCODEMP = COLCON.BDCODEMP) '||
         'join VRHF_EMP_TADSAL FOLN on (FOLN.BDCODEMP = COLCON.BDCODEMP and FOLN.BDCODCOL = COLCON.BDCODCOL and FOLN.BDDATAAD = COLCON.BDDATAAD) '||
         'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = COLCON.BDCODVER) '||
         'join VW_TVERBAS_REF VERREF on (VERREF.BDCODVER = COLCON.BDCODVER) ';

  wsql = wsql||'where COLCON.BDDATAAD between '''||prdataini||''' and '''||prdatafim||''' ' ;

  if (premp <> '') then
     begin
       if (prpuxafilial <> 0) then
          wsql = wsql||' and (('||premp||') or ('||replace(premp, 'COLCON.BDCODEMP', 'EMP.BDCODMATRIZ')||')) ';
       else
          begin
            wsql = wsql||' and '||premp||' ';

            if (prcol <> '') then
               wsql = wsql||' and '||prcol||' ';
          end
     end

  wsql = wsql||'order by COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDDATAAD, COLCON.BDCODVER ';

  wempatu = 0;
  wcolatu = 0;
  wempok  = 0;
  wrefatu = 0;

  for execute statement wsql into
    :CODIGO_FILIAL,
    :CODIGO_EMPRESA,
    :CODIGO_COLABORADOR,
    :CODIGO_VERBA,
    :REFERENCIA_AUXILIAR_VERBA,
    :REFERENCIA_VERBA,
    :wvalv,
    :BDORDEM,
    :CNPJ_EMPRESA,
    :DESCRICAO_VERBA,
    :BDTIPOCODVER,
    :SALARIO_BASE,
    :IRRF_FOLHA,
    :DESCRICAO_RED_VERBA,
    :PISVER,
    :BDORDEMTIPOCODVER,
    :CLASSIFICA_VERBA,
    :BDORDEMVER,
    :BDTIPOREFVER,
    :DATA_AD,
    :DATA_PAG_IR,
    :DATA_PAGAMENTO_FOLHA,
    :wrefad
  do
    begin
 --erro de conversão --> cast((substring(cast(:DATA_AD as varchar(10)) from 1 for 4)||substring(cast(:DATA_AD as varchar(10)) from 6 for 2)||substring(cast(:DATA_AD as varchar(10)) from 9 for 2)) as integer);
      REFERENCIA_FOLHA = cast((substring(cast(:DATA_AD as varchar(10)) from 1 for 4)||substring(cast(:DATA_AD as varchar(10)) from 6 for 2)) as integer);
      REFERENCIAAUX    = lpad(REFERENCIA_FOLHA, 8, '0');
      if ((wempatu <> CODIGO_FILIAL) or (wrefatu <> wrefad)) then
         begin
           wempatu = CODIGO_FILIAL;
           wrefatu = wrefad;
           wcolatu = 0;

           BDCODENQFED   = null;
           BDSIMPLESGPS  = null;
           BDCCATVCONCOM = null;

           select first 1 BDCODENQFED from TENQFED where BDCODEMP = :wempatu and BDREFEMP <= :wrefatu order by BDREFEMP DESC into :BDCODENQFED;
           select first 1 BDSIMPLESGPS, BDCCATVCONCOM from VRHF_BASE_TEMPGPS where BDCODEMP = :wempatu and BDREFEMP <= :wrefatu order by BDREFEMP DESC into :BDSIMPLESGPS, :BDCCATVCONCOM;
           select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = :wempatu and BDREFEMP <= :wrefatu order by BDREFEMP DESC into :BDREFHOREMP;

           BDREFHOREMP   = upper(coalesce(BDREFHOREMP, 'FALSE'));
           BDCCATVCONCOM = upper(coalesce(BDCCATVCONCOM, 'FALSE'));

           NOME_EMPRESA     = null;
           ENDERECO_EMPRESA = null;
           NUMERO_EMPRESA   = null;
           BAIRRO_EMPRESA   = null;
           CEP_EMPRESA      = null;
           COMPL_EMPRESA    = null;
           BDCODCENTROS     = null;
           wcodcid          = null;

           -- Sol.142437 | Leonardo Schwab | 15/12/2020 | Caso o parâmetro de puxar filiais estiver selecionado busca as informações da Matriz.
           if (prpuxafilial = 1) then
             begin
           select first 1 BDNOMEMP, trim(coalesce(BDENDEMP, '''')), BDNUMEMP, BDBAIEMP, BDCEPEMP, BDCOMPLEMP, BDCODCID, BDCODCENTROS
           from TEMPRESAS_REF
               where BDCODEMP = :CODIGO_EMPRESA
               order by BDREFEMP DESC
               into :NOME_EMPRESA, :ENDERECO_EMPRESA, :NUMERO_EMPRESA, :BAIRRO_EMPRESA, :CEP_EMPRESA, :COMPL_EMPRESA, :wcodcid, :BDCODCENTROS;
             end
           else
             begin
               select first 1 BDNOMEMP, trim(coalesce(BDENDEMP, '''')), BDNUMEMP, BDBAIEMP, BDCEPEMP, BDCOMPLEMP, BDCODCID, BDCODCENTROS
               from TEMPRESAS_REF
           where BDCODEMP = :wempatu
           order by BDREFEMP DESC
           into :NOME_EMPRESA, :ENDERECO_EMPRESA, :NUMERO_EMPRESA, :BAIRRO_EMPRESA, :CEP_EMPRESA, :COMPL_EMPRESA, :wcodcid, :BDCODCENTROS;
             end

           select first 1 E.BDCODEMP
           from SP_EMPRESAS_USU(:wempatu) E
           where E.BDCODEMP = :wempatu
           into :wempok;

           wempok = coalesce(wempok, 0);

           wcoduf         = null;
           CIDADE_EMPRESA = null;
           select first 1 BDNOMCID, BDCODUF from TCIDADE where BDCODCID = :wcodcid into :CIDADE_EMPRESA, :wcoduf;

           UF_EMPRESA = null;
           select first 1 BDSIGLAUF from TUF where BDCODUF = :wcoduf into :UF_EMPRESA;
         end

      if (wempok = wempatu) then
         begin
           if (wcolatu <> CODIGO_COLABORADOR) then
              begin
                wcolatu = CODIGO_COLABORADOR;
     
                NOME_COLABORADOR     = null;
                ADMISSAO_COLABORADOR = null;
                CPF_COLABORADOR      = null;
                PIS_COLABORADOR      = null;
                HORAS_MENSAIS        = null;
                CTPS_COL             = null;
                SERIE_CTPS           = null;
                RAT_APO_COL          = null;
                GRUPO_CLASSE         = null;
                BDCATEGORIAESOCIAL   = null;
                BDCONTRCOL           = null;
                wdepir               = 0;
                wdepsf               = 0;
                BDCODCLA             = null;
                BDCODSINTRAB         = null;
                BDCODTFUC            = null;

                select first 1 CASE WHEN (FIS.BDNMSOCIAL <> '' and PAR.bdusanomesocial = 'TRUE') THEN FIS.BDNMSOCIAL ELSE cad.BDNOMCOL END Nome_Colaborador from VRH_EMP_TCOLCON_CAD cad
                left outer join VRH_EMP_TCOLCON_FIS FIS ON (FIS.BDCODEMP = cad.BDCODEMP AND FIS.BDCODCOL = cad.BDCODCOL AND FIS.bdrefcol=cad.bdrefcol)
                left outer join(select a.bdcodemp,max(a.bdrefemp)bdrefemp from VRHF_BASE_TEMPPAR a group by a.bdcodemp) pmax on  (pmax.BDCODEMP = cad.BDCODEMP)
                left outer join VRHF_BASE_TEMPPAR PAR  on (par.bdcodemp=pmax.bdcodemp and par.bdrefemp=pmax.bdrefemp)  --Sol.162301 Estava puxando o nome social incorretamente feito ajuste.
                where cad.BDCODEMP = :wempatu and cad.BDCODCOL = :wcolatu and cad.BDREFCOL <= :wrefatu
                order by cad.BDREFCOL DESC into :NOME_COLABORADOR;     
                select first 1 BDDATAADMCOL, BDCPFCOL, BDCONTRCOL from VRH_EMP_TCOLCON where BDCODEMP = :wempatu and BDCODCOL = :wcolatu into :ADMISSAO_COLABORADOR, :CPF_COLABORADOR, :BDCONTRCOL;
                select first 1 BDPISCOL from VRH_EMP_TCOLCON_DOCREF where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :wrefatu order by BDREFCOL DESC into :PIS_COLABORADOR;
                select first 1 BDCTPSCOL, BDSERIECTPSCOL from VRH_EMP_TCOLCON_DOCREF where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :wrefatu order by BDREFCOL DESC into :CTPS_COL, :SERIE_CTPS;
                select first 1 BDHORASMENSAISCOL, BDNRODEPSALFAMCOL from VRHF_EMP_TCOL_CALC where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :wrefatu order by BDREFCOL DESC into :HORAS_MENSAIS, :wdepsf;
                select first 1 BDPERCRATCOL, BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :wrefatu order by BDREFCOL DESC into :RAT_APO_COL, :BDCATEGORIAESOCIAL;
                select first 1 BDNRODEPIRCOL from VRHF_EMP_TCOLCON_CALC where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :wrefatu order by BDREFCOL DESC into :wdepir;
                select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :wrefatu order by BDREFCOL DESC into :BDCODSINTRAB;
     
                CTPS_COL      = trim(coalesce(CTPS_COL, ''));
                SERIE_CTPS    = trim(coalesce(SERIE_CTPS, ''));
                HORAS_MENSAIS = coalesce(HORAS_MENSAIS, 0);
                RAT_APO_COL   = coalesce(RAT_APO_COL, 0);
                BDCONTRCOL    = coalesce(BDCONTRCOL, 0);
                wdepir        = coalesce(wdepir, 0);
                wdepsf        = coalesce(wdepsf, 0);
                whmes         = null;

                select first 1 BDMESREDSAL
                from VRH_EMP_TREDUCAOCOL
                where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDDATAINIREDSAL >= :prdataini and :prdatafim <= coalesce(BDDATAFIMREDSAL, :prdatafim) and
                     :prdatafim between BDDATAINIREDSAL and BDDATAFIMREDSAL
                into :whmes;
                whmes = coalesce(whmes, 0);

                if (whmes > 0) then
                   HORAS_MENSAIS = whmes;

                if (CTPS_COL = '' and SERIE_CTPS = '') then
                   begin
                     CTPS_COL   = substring(replace(replace(CPF_COLABORADOR, '.', ''), '-', '') from 1 for 7);
                     SERIE_CTPS = substring(replace(replace(CPF_COLABORADOR, '.', ''), '-', '') from 8 for 4);
                   end
     
                wplafuc  = null;
                wcodtfuc = null;                                                                                                      --(antes) <= :DATA_AD
                select first 1 BDCODPLAFUC, BDCODTFUC from VRH_EMP_TCOL_VINCDIA where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :wrefad
                order by BDDATACOL DESC into :wplafuc, :wcodtfuc;
                BDCODTFUC = coalesce(wcodtfuc,0);                                                                                     --(antes) <= :prdatafim  (Solicitação W150878 LuizCovre 14/09/21)
                                                                                                                                      --where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDDATACOL <= :prdatafim order by BDDATACOL DESC into :wplafuc, :wcodtfuc;

                                                                                                                                      --(agora) removi a relação "and BDDATACOL <= :prdatafim" pois com a ordem decrescente sempra virá a func mais recente (Solicitação W150878 LuizCovre 13/10/21)
                FUNCAO_COLABORADOR = null;
                CBO_COL            = null;
     
                if (wplafuc is not null and wcodtfuc is not null) then
                   begin
                     if (prfucdet <> 0) then
                        select first 1 BDDESCFUNCDET, BDCODCBO from VRH_FUNCOES_TFUC where BDCODPLAFUC = :wplafuc and BDCODTFUC = :wcodtfuc into :FUNCAO_COLABORADOR, :CBO_COL;
     
                     if (trim(coalesce(FUNCAO_COLABORADOR, '')) = '') then
                        select first 1 BDDESCTFUC, BDCODCBO from VRH_FUNCOES_TFUC where BDCODPLAFUC = :wplafuc and BDCODTFUC = :wcodtfuc into :FUNCAO_COLABORADOR, :CBO_COL;
                   end
     
                wcodcla = null;
                select first 1 BDCODCLA from VRH_EMP_TCOLCON_VINC where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and BDREFCOL <= :wrefatu order by BDREFCOL DESC into :wcodcla;
     
                BDCODCLA = coalesce(wcodcla, 0);
                if (coalesce(wcodcla, 0) <> 0) then
                   select first 1 BDGRUPOCLA from VRH_BASE_TCLASSE where BDCODCLA = :wcodcla into :GRUPO_CLASSE;
     
                GRUPO_CLASSE = coalesce(GRUPO_CLASSE, 0);
     
                RESCISAO_COLABORADOR = null;
                MOTIVO_RESCISAO      = null;
                TIPO_RESCISAO        = null;
                BDTEMGRRF            = null;
                wrefrescisao         = null;
                wgrrfpres            = null;
                wcodres              = null;
                wfgtsmensant         = null;
     
                select first 1 R.BDDATARESCISAO, R.BDREFRESCISAO, R.BDCODPRES, R.BDCALCFGTSMESANT, PR.BDGRRFPRES, substring(PR.BDDESCPRES from 1 for 110), PR.BDTIPOMOV
                from VRH_EMP_TRESCISAO R
                join VRH_BASE_TPREPRESC PR on (PR.BDCODPRES = R.BDCODPRES)
                where R.BDCODEMP = :wempatu and R.BDCODCOL = :wcolatu
                into :RESCISAO_COLABORADOR, :wrefrescisao, :wcodres, :wfgtsmensant, :wgrrfpres, :MOTIVO_RESCISAO, :TIPO_RESCISAO;
     
                wrefrescisao = coalesce(wrefrescisao, 0);
                wgrrfpres    = coalesce(wgrrfpres, 0);
                wcodres      = coalesce(wcodres, 0);
                wfgtsmensant = upper(coalesce(wfgtsmensant, 'FALSE'));
     
                if (wrefrescisao <> REFERENCIA_FOLHA) then
                   begin
                     RESCISAO_COLABORADOR = null;
                     MOTIVO_RESCISAO      = null;
                     TIPO_RESCISAO        = 0;
                   end
     
                if (wrefrescisao = REFERENCIA_FOLHA and wgrrfpres in (1,2)) then
                   BDTEMGRRF = 1;
                else
                   BDTEMGRRF = 0;
     
                select count(*)
                from VW_VRH_EMP_TDEP_REF
                where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and
                      upper(coalesce(BDSALFAMDPN, 'FALSE')) = 'TRUE' and
                      coalesce(BDPARENESCODPN, 0) in (0, 4, 5, 6, 11) and
                      coalesce(BDPARENESCODPN, 0) <> 3 and
                      ((select BDAAAAMM
                        from AAAAMM(coalesce(BDDATANASCDPN, BDDATAENTREDPN))) <= :REFERENCIA_FOLHA) and
                      ((BDDATABAUXADPN is null) or ((select BDAAAAMM
                                                     from AAAAMM(BDDATABAUXADPN)) > :REFERENCIA_FOLHA)) and
                      ((upper(coalesce(BDINVALIDODPN, 'FALSE')) = 'TRUE') or ((BDDATANASCDPN is not null) and
                      (:REFERENCIA_FOLHA - cast((select BDAAAAMM
                                                 from AAAAMM(BDDATANASCDPN)) as integer) <= 1400)))
                into :DEPSF;
     
                DEPSF = coalesce(DEPSF, 0);
     
                select count(*)
                from VW_VRH_EMP_TDEP_REF
                where BDCODEMP = :wempatu and BDCODCOL = :wcolatu and
                      upper(coalesce(BDDEPIRDPN, 'FALSE')) = 'TRUE' and
                      coalesce(BDPARENESCODPN, 0) <> 3 and
                      (select BDAAAAMM
                       from AAAAMM(coalesce(BDDATANASCDPN, BDDATAENTREDPN))) <= :REFERENCIA_FOLHA and
                      ((BDDATABAUXADPN is null) or ((select BDAAAAMM
                                                     from AAAAMM(BDDATABAUXADPN)) > :REFERENCIA_FOLHA)) and
                      ((BDREFIRDPN is null) or (coalesce(BDREFIRDPN, 0) = 0) or (coalesce(BDREFIRDPN, 0) >= :REFERENCIA_FOLHA)) and
                      ((upper(coalesce(BDINVALIDODPN, 'FALSE')) = 'TRUE') or (BDREFIRDPN >= :REFERENCIA_FOLHA) or ((coalesce(BDPARENESCODPN, 0) in (0, 4, 5, 6)) and
                      (:REFERENCIA_FOLHA - cast((select BDAAAAMM
                                                 from AAAAMM(BDDATANASCDPN)) as integer) < 2200)) or (coalesce(BDPARENESCODPN, 0) in (1, 2)))
                into :DEPIR;
     
                DEPIR = coalesce(DEPIR, 0);
     
                if (DEPSF + DEPIR <= 0) then
                   begin
                     DEPSF = wdepsf;
                     DEPIR = wdepir;
                   end
              end
     
           BDTIPOCODVER = coalesce(BDTIPOCODVER, 0);
           if (BDTIPOCODVER in (0, 2)) then
              PROVENTOS_FOLHA = wvalv;
           else
              DESCONTOS_FOLHA = wvalv;
     
           suspend;
         end
    end
end^


CREATE OR ALTER TRIGGER VFIN_BASE_TCONFCOBSERV_BI0 for VFIN_BASE_TCONFCOBSERV
active before insert position 0
as
declare variable WCOD integer;
begin
  if ((new.BDORDEMCONF is null) or (new.BDORDEMCONF = 0)) then
  begin
    select max(BDORDEMCONF) from VFIN_BASE_TCONFCOBSERV where BDCODESC = new.BDCODESC into :WCOD;
    new.BDORDEMCONF = coalesce(:WCOD, 0) + 1;
  end
end^

CREATE OR ALTER TRIGGER TPLANO_ORGANIZACIONAL_BI0 FOR TPLANO_ORGANIZACIONAL
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;
begin
  if (coalesce(new.bdcodplaorg, 0) <= 0) then
     begin
       vcod = null;
       select coalesce(max(BDCODPLAORG) + 1, 1) from TPLANO_ORGANIZACIONAL into :vcod;
       vcod = coalesce(vcod, 1);
       new.bdcodplaorg = vcod;
     end
end
^

CREATE OR ALTER TRIGGER TPLANO_ORGANIZACIONAL_ITENS_BI0 FOR TPLANO_ORGANIZACIONAL_ITENS
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;
begin
  if (coalesce(new.bdcodplaorgitem, 0) <= 0) then
     begin
       vcod = null;
       select coalesce(max(bdcodplaorgitem) + 1, 1) from TPLANO_ORGANIZACIONAL_ITENS where BDCODPLAORG = new.BDCODPLAORG into :vcod;
       vcod = coalesce(vcod, 1);
       new.bdcodplaorgitem = vcod;
     end
end
^



CREATE OR ALTER procedure SP_FICHA_REGISTROS_FALTAS (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRHISTTRANSF integer,
    PRPODE integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFAL integer,
    BDDATAFAL date,
    BDTIPOFAL integer,
    BDHORASFAL numeric(18,6),
    BDTIPODESCFAL integer,
    BDNOMCOL varchar(70),
    BDCODEMPORIG integer,
    BDCODCOLORIG integer)
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(20000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WSQL2 varchar(1000);
declare variable WSQL3 varchar(1000);
declare variable WSQLAUX varchar(1000);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  if (PRPODE = 1) then
     begin
       WSQL = 'SELECT T.BDCODEMP, T.BDCODCOL FROM VW_VRH_EMP_TCOLCON_CAD T ';

       wwhere = '';
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
            wwhere = prcodemp;
          END

       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';

            wwhere = wwhere||prcodcol;
          END

       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;

       WSQL = WSQL || wwhere || ' order by T.BDCODEMP, T.BDCODCOL';

       FOR EXECUTE STATEMENT wsql INTO :WCODEMP, :WCODCOL DO
         BEGIN
           if (PRHISTTRANSF = 1) then
              BEGIN
                WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = ' || WCODEMP || ' and BDCODCOLDEST = ' || WCODCOL;
                FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
                  BEGIN
                    IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
                      BEGIN
                    WSQL3 = 'SELECT * FROM SP_FICHA_REGISTROS_FALTAS(''T.BDCODEMP = '||wcodemporig||''', ''T.BDCODCOL = ' || wcodcolorig || ''',' || prhisttransf || ',' || prpode || ')';
                    FOR EXECUTE STATEMENT wsql3 INTO
                      :BDCODEMP,
                      :BDCODCOL,
                      :BDREFFAL,
                      :BDDATAFAL,
                      :BDTIPOFAL,
                      :BDHORASFAL,
                      :BDTIPODESCFAL,
                      :BDNOMCOL,
                      :BDCODEMPORIG,
                      :BDCODCOLORIG DO
                      begin
                        BDCODEMP = WCODEMP;
                        BDCODCOL = WCODCOL;
                        SUSPEND;
                      end
                  END
              END
              END


           WSQLAUX =  ' select FALTAS.BDCODEMP, FALTAS.BDCODCOL, FALTAS.BDREFFAL, FALTAS.BDDATAFAL, FALTAS.BDTIPOFAL, FALTAS.BDHORASFAL, FALTAS.BDTIPODESCFAL, COLCAD.BDNOMCOL ' ||
                      ' from VRH_EMP_TFALTAS_ITENS FALTAS ' ||
                      ' left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (FALTAS.BDCODEMP = COLCAD.BDCODEMP and FALTAS.BDCODCOL = COLCAD.BDCODCOL) ' ||
                      ' LEFT JOIN(SELECT FIRST 1 VERBAEMP.BDCODEMP, ' ||                  /*Solicitação 157925 - 06/06/2022- André Cursino - Adicionado subselect para saber se a empresa usa as verbas de suspensão*/
                      '                   CASE ' ||
                      '                     WHEN VERBAEMP.BDCODVER > 0 THEN ''TRUE'' ' ||
                      '                     WHEN (VERBAEMP.BDCODVER IS NULL) OR (VERBAEMP.BDCODVER = 0) THEN ''FALSE'' ' ||
                      '                     ELSE ''FALSE'' ' ||
                      '                   END BDVERBASUSP ' ||
                      '            FROM VRHF_BASE_TVERBASEMP VERBAEMP ' ||
                      '            WHERE VERBAEMP.BDCODEMP = ' || WCODEMP || ' AND ' ||
                      '                  VERBAEMP.BDCLASSIFVEREMP = ''0.007.3.0'') SUSP ON (FALTAS.BDCODEMP = SUSP.BDCODEMP) ' ||
                      ' where ((FALTAS.BDTIPOFAL = 1) OR ((FALTAS.BDTIPOFAL = 2) AND ' ||
                      '        (NOT SUSP.BDVERBASUSP IS NOT NULL))) AND ' ||
                      '       FALTAS.BDCODEMP = ' || WCODEMP || ' and ' ||
                      '       FALTAS.BDCODCOL = ' || WCODCOL;

          FOR EXECUTE STATEMENT wsqlaux INTO
             :BDCODEMP,
             :BDCODCOL,
             :BDREFFAL,
             :BDDATAFAL,
             :BDTIPOFAL,
             :BDHORASFAL,
             :BDTIPODESCFAL,
             :BDNOMCOL DO
             begin
               BDCODEMPORIG = WCODEMP;
               BDCODCOLORIG = WCODCOL;
               SUSPEND;
             end
         END
     end
  else
     begin
       BDCODEMP = 0;
       BDCODCOL = 0;
       suspend;
     end
end^


CREATE OR ALTER procedure SP_FICHA_REGISTROS_FERIAS (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRHISTTRANSF integer,
    PRPODE integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODFE integer,
    BDINIPERAQUISFE date,
    BDFIMPERAQUISFE date,
    BDINIPERGOZOFE date,
    BDFIMPERGOZOFE date,
    BDQTDGOZOFE numeric(18,6),
    BDDIASLICFE numeric(18,6),
    BDQTDABONOFE numeric(18,6),
    BDSALDOFIMFE numeric(18,6),
    BDNOMCOL varchar(70),
    BDRESC varchar(5),
    BDREFPAGABOFE integer,
    BDDATARESCISAO date,
    BDCODEMPORIG integer,
    BDCODCOLORIG integer)
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(20000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WSQL2 varchar(1000);
declare variable WSQL3 varchar(1000);
declare variable WSQLAUX varchar(1000);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  if (PRPODE = 1) then
     begin
       WSQL = 'SELECT T.BDCODEMP, T.BDCODCOL FROM VW_VRH_EMP_TCOLCON_CAD T ';

       wwhere = '';
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
            wwhere = prcodemp;
          END

       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';

            wwhere = wwhere||prcodcol;
          END

       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;

       WSQL = WSQL || wwhere || ' order by T.BDCODEMP, T.BDCODCOL';

       FOR EXECUTE STATEMENT wsql INTO :WCODEMP, :WCODCOL DO
         BEGIN
           if (PRHISTTRANSF = 1) then
              BEGIN
                WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = ' || WCODEMP || ' and BDCODCOLDEST = ' || WCODCOL;
                FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
                  BEGIN
                    IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
                      BEGIN
                    WSQL3 = 'SELECT * FROM SP_FICHA_REGISTROS_FERIAS(''T.BDCODEMP = '||wcodemporig||''', ''T.BDCODCOL = ' || wcodcolorig || ''',' || prhisttransf || ',' || prpode || ')';
                    FOR EXECUTE STATEMENT wsql3 INTO
                      :BDCODEMP,
                      :BDCODCOL,
                      :BDCODFE,
                      :BDINIPERAQUISFE,
                      :BDFIMPERAQUISFE,
                      :BDINIPERGOZOFE,
                      :BDFIMPERGOZOFE,
                      :BDQTDGOZOFE,
                      :BDDIASLICFE,
                      :BDQTDABONOFE,
                      :BDSALDOFIMFE,
                      :BDNOMCOL,
                      :BDRESC,
                      :BDREFPAGABOFE,
                      :BDDATARESCISAO,
                      :BDCODEMPORIG,
                      :BDCODCOLORIG DO
                          BEGIN
                        BDCODEMP = WCODEMP;
                        BDCODCOL = WCODCOL;
                        SUSPEND;
                  END
              END
                  END
              END


           WSQLAUX =  ' select FERIAS.bdcodemp, FERIAS.bdcodcol, FERIAS.bdcodfe, FERIAS.BDINIPERAQUISFE, FERIAS.BDFIMPERAQUISFE, FERIAS.BDINIPERGOZOFE, ' ||
                      ' FERIAS.BDFIMPERGOZOFE, FERIAS.BDQTDGOZOFE, coalesce(FERIAS.BDDIASLICFE, 0), FERIAS.BDQTDABONOFE, ' ||
                      ' case when RESC.BDDATARESCISAO = ''02/15/2017'' and FERIAS.BDSALDOFIMFE = 15 then 0 else FERIAS.BDSALDOFIMFE end BDSALDOFIMFE, ' ||
                      ' COLCAD.BDNOMCOL, CAST(null as VARCHAR(5)) as BDRESC, FERIAS.BDREFPAGABOFE, RESC.BDDATARESCISAO ' ||
                      ' from VRH_EMP_TFERIAS FERIAS ' ||
                      ' left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (FERIAS.bdcodemp = COLCAD.bdcodemp AND FERIAS.bdcodcol = COLCAD.bdcodcol) ' ||
                      ' left outer join VRH_EMP_TTRANSCOL TRF on (TRF.BDCODEMPDEST = FERIAS.BDCODEMP and TRF.BDCODCOLDEST = FERIAS.BDCODCOL) ' ||
                      ' left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FERIAS.BDCODEMP and RESC.BDCODCOL = FERIAS.BDCODCOL) ' ||
                   -- ' where ((FERIAS.BDDATAPAGFE >= TRF.BDDATATRF) or (TRF.BDDATATRF is null)) and ' || Sol.148163 LuizCovre 29/09/21
                      ' where ' ||
                      '       (FERIAS.BDCODEMP = ' || WCODEMP || ') and ' ||
                      '       (FERIAS.BDCODCOL = ' || WCODCOL || ')';

          FOR EXECUTE STATEMENT wsqlaux INTO
              :BDCODEMP,
              :BDCODCOL,
              :BDCODFE,
              :BDINIPERAQUISFE,
              :BDFIMPERAQUISFE,
              :BDINIPERGOZOFE,
              :BDFIMPERGOZOFE,
              :BDQTDGOZOFE,
              :BDDIASLICFE,
              :BDQTDABONOFE,
              :BDSALDOFIMFE,
              :BDNOMCOL,
              :BDRESC,
              :BDREFPAGABOFE,
              :BDDATARESCISAO DO
             begin
               BDCODEMPORIG = WCODEMP;
               BDCODCOLORIG = WCODCOL;
               SUSPEND;
             end
         END
     end
  else
     begin
       BDCODEMP = 0;
       BDCODCOL = 0;
       suspend;
     end
end^


CREATE OR ALTER procedure SP_FICHA_REGISTROS_AFASTAMENTOS (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRHISTTRANSF integer,
    PRPODE integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATAINISIT date,
    BDDATAFIMSIT date,
    BDCODSIT integer,
    BDDESCSIT varchar(70),
    BDNOMCOL varchar(70),
    BDCODEMPORIG integer,
    BDCODCOLORIG integer)
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(20000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WSQL2 varchar(1000);
declare variable WSQL3 varchar(1000);
declare variable WSQLAUX varchar(1000);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  if (PRPODE = 1) then
     begin
       WSQL = 'SELECT T.BDCODEMP, T.BDCODCOL FROM VW_VRH_EMP_TCOLCON_CAD T ';

       wwhere = '';
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
            wwhere = prcodemp;
          END

       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';

            wwhere = wwhere||prcodcol;
          END

       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;

       WSQL = WSQL || wwhere || ' order by T.BDCODEMP, T.BDCODCOL';

       FOR EXECUTE STATEMENT wsql INTO :WCODEMP, :WCODCOL DO
         BEGIN
           if (PRHISTTRANSF = 1) then
              BEGIN
                WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = ' || WCODEMP || ' and BDCODCOLDEST = ' || WCODCOL;
                FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
                  BEGIN
                    IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
                      BEGIN
                    WSQL3 = 'SELECT * FROM SP_FICHA_REGISTROS_AFASTAMENTOS(''T.BDCODEMP = '||wcodemporig||''', ''T.BDCODCOL = ' || wcodcolorig || ''',' || prhisttransf || ',' || prpode || ')';
                    FOR EXECUTE STATEMENT wsql3 INTO
                      :BDCODEMP,
                      :BDCODCOL,
                      :BDDATAINISIT,
                      :BDDATAFIMSIT,
                      :BDCODSIT,
                      :BDDESCSIT,
                      :BDNOMCOL,
                      :BDCODEMPORIG,
                      :BDCODCOLORIG DO
                          BEGIN
                        BDCODEMP = WCODEMP;
                        BDCODCOL = WCODCOL;
                        SUSPEND;
                  END
              END
                  END
              END


           WSQLAUX =  ' select T.BDCODEMP, T.BDCODCOL, T.BDDATAINISIT, T.BDDATAFIMSIT, T.BDCODSIT, X.BDDESCSIT , COLCAD.BDNOMCOL ' ||
                      ' from VRH_EMP_TSITCOL T ' ||
                      ' left outer join VRH_BASE_TPREPSIT X ON  (T.bdcodsit = X.bdcodsit) ' ||
                      ' left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (T.bdcodemp = COLCAD.bdcodemp AND T.bdcodcol = COLCAD.bdcodcol) ' ||
                      ' where T.BDCODEMP = ' || WCODEMP || ' and ' ||
                      '       T.BDCODCOL = ' || WCODCOL;

          FOR EXECUTE STATEMENT wsqlaux INTO
              :BDCODEMP,
              :BDCODCOL,
              :BDDATAINISIT,
              :BDDATAFIMSIT,
              :BDCODSIT,
              :BDDESCSIT,
              :BDNOMCOL DO
             begin
               BDCODEMPORIG = WCODEMP;
               BDCODCOLORIG = WCODCOL;
               SUSPEND;
             end
         END
     end
  else
     begin
       BDCODEMP = 0;
       BDCODCOL = 0;
       suspend;
     end
end^


CREATE OR ALTER procedure SP_FICHA_REGISTROS_SUSPENSOES (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRHISTTRANSF integer,
    PRPODE integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDCODNOTIF integer,
    BDTIPONOTIF integer,
    BDDATANOTIF date,
    BDDESCNOTIF varchar(5000),
    BDFALTASNOTIF varchar(5),
    BDDIASNOTIF integer,
    BDRETORNONOTIF date,
    BDCODEMPORIG integer,
    BDCODCOLORIG integer)
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(20000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WSQL2 varchar(1000);
declare variable WSQL3 varchar(1000);
declare variable WSQLAUX varchar(1000);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  if (PRPODE = 1) then
     begin
       WSQL = 'SELECT T.BDCODEMP, T.BDCODCOL FROM VW_VRH_EMP_TCOLCON_CAD T ';

       wwhere = '';
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
            wwhere = prcodemp;
          END

       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';

            wwhere = wwhere||prcodcol;
          END

       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;

       WSQL = WSQL || wwhere || ' order by T.BDCODEMP, T.BDCODCOL';

       FOR EXECUTE STATEMENT wsql INTO :WCODEMP, :WCODCOL DO
         BEGIN
           if (PRHISTTRANSF = 1) then
              BEGIN
                WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = ' || WCODEMP || ' and BDCODCOLDEST = ' || WCODCOL;
                FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
                  BEGIN
                    IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
                      BEGIN
                    WSQL3 = 'SELECT * FROM SP_FICHA_REGISTROS_SUSPENSOES(''T.BDCODEMP = '||wcodemporig||''', ''T.BDCODCOL = ' || wcodcolorig || ''',' || prhisttransf || ',' || prpode || ')';
                    FOR EXECUTE STATEMENT wsql3 INTO
                      :BDCODEMP,
                      :BDCODCOL,
                      :BDNOMCOL,
                      :BDCODNOTIF,
                      :BDTIPONOTIF,
                      :BDDATANOTIF,
                      :BDDESCNOTIF,
                      :BDFALTASNOTIF,
                      :BDDIASNOTIF,
                      :BDRETORNONOTIF,
                      :BDCODEMPORIG,
                      :BDCODCOLORIG DO
                          BEGIN
                        BDCODEMP = WCODEMP;
                        BDCODCOL = WCODCOL;
                        SUSPEND;
                  END
              END
                  END
              END


           WSQLAUX =  ' select COL.BDCODEMP, COL.BDCODCOL, COLCAD.BDNOMCOL, SUSP.BDCODNOTIF, SUSP.BDTIPONOTIF, SUSP.BDDATANOTIF, SUSP.BDDESCNOTIF, ' ||
                      ' SUSP.BDFALTASNOTIF, SUSP.BDDIASNOTIF, SUSP.BDRETORNONOTIF ' ||
                      ' from VRH_EMP_TCOLCON COL ' ||
                      ' left outer join VRH_EMP_TNOTIFICACOES SUSP on (SUSP.BDCODEMP = COL.BDCODEMP and SUSP.BDCODCOL = COL.BDCODCOL) ' ||
                      ' left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COL.BDCODEMP and COLCAD.BDCODCOL = COL.BDCODCOL) ' ||
                      ' where COL.BDCODEMP = ' || WCODEMP || ' and ' ||
                      '       COL.BDCODCOL = ' || WCODCOL || ' and ' ||
                      '       SUSP.BDTIPONOTIF = 1 ';

          FOR EXECUTE STATEMENT wsqlaux INTO
              :BDCODEMP,
              :BDCODCOL,
              :BDNOMCOL,
              :BDCODNOTIF,
              :BDTIPONOTIF,
              :BDDATANOTIF,
              :BDDESCNOTIF,
              :BDFALTASNOTIF,
              :BDDIASNOTIF,
              :BDRETORNONOTIF DO
             begin
               BDCODEMPORIG = WCODEMP;
               BDCODCOLORIG = WCODCOL;
               SUSPEND;
             end
         END
     end
  else
     begin
       BDCODEMP = 0;
       BDCODCOL = 0;
       suspend;
     end
end^


CREATE OR ALTER procedure SP_FICHA_REGISTROS_ADVERTENCIAS (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRHISTTRANSF integer,
    PRPODE integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDCODNOTIF integer,
    BDTIPONOTIF integer,
    BDDATANOTIF date,
    BDDESCNOTIF varchar(5000),
    BDFALTASNOTIF varchar(5),
    BDDIASNOTIF integer,
    BDRETORNONOTIF date,
    BDCODEMPORIG integer,
    BDCODCOLORIG integer)
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(20000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WSQL2 varchar(1000);
declare variable WSQL3 varchar(1000);
declare variable WSQLAUX varchar(1000);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  if (PRPODE = 1) then
     begin
       WSQL = 'SELECT T.BDCODEMP, T.BDCODCOL FROM VW_VRH_EMP_TCOLCON_CAD T ';

       wwhere = '';
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
            wwhere = prcodemp;
          END

       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';

            wwhere = wwhere||prcodcol;
          END

       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;

       WSQL = WSQL || wwhere || ' order by T.BDCODEMP, T.BDCODCOL';

       FOR EXECUTE STATEMENT wsql INTO :WCODEMP, :WCODCOL DO
         BEGIN
           if (PRHISTTRANSF = 1) then
              BEGIN
                WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = ' || WCODEMP || ' and BDCODCOLDEST = ' || WCODCOL;
                FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
                  BEGIN
                    IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
                      BEGIN
                    WSQL3 = 'SELECT * FROM SP_FICHA_REGISTROS_ADVERTENCIAS(''T.BDCODEMP = '||wcodemporig||''', ''T.BDCODCOL = ' || wcodcolorig || ''',' || prhisttransf || ',' || prpode || ')';
                    FOR EXECUTE STATEMENT wsql3 INTO
                      :BDCODEMP,
                      :BDCODCOL,
                      :BDNOMCOL,
                      :BDCODNOTIF,
                      :BDTIPONOTIF,
                      :BDDATANOTIF,
                      :BDDESCNOTIF,
                      :BDFALTASNOTIF,
                      :BDDIASNOTIF,
                      :BDRETORNONOTIF,
                      :BDCODEMPORIG,
                      :BDCODCOLORIG DO
                      begin
                        BDCODEMP = WCODEMP;
                        BDCODCOL = WCODCOL;
                        SUSPEND;
                      end
                  END
              END
              END


           WSQLAUX =  ' select COL.BDCODEMP, COL.BDCODCOL, COLCAD.BDNOMCOL, SUSP.BDCODNOTIF, SUSP.BDTIPONOTIF, SUSP.BDDATANOTIF, SUSP.BDDESCNOTIF, ' ||
                      ' SUSP.BDFALTASNOTIF, SUSP.BDDIASNOTIF, SUSP.BDRETORNONOTIF ' ||
                      ' from VRH_EMP_TCOLCON COL ' ||
                      ' left outer join VRH_EMP_TNOTIFICACOES SUSP on (SUSP.BDCODEMP = COL.BDCODEMP and SUSP.BDCODCOL = COL.BDCODCOL) ' ||
                      ' left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COL.BDCODEMP and COLCAD.BDCODCOL = COL.BDCODCOL) ' ||
                      ' where COL.BDCODEMP = ' || WCODEMP || ' and ' ||
                      '       COL.BDCODCOL = ' || WCODCOL || ' and ' ||
                      '       SUSP.BDTIPONOTIF <> 1 ';

          FOR EXECUTE STATEMENT wsqlaux INTO
              :BDCODEMP,
              :BDCODCOL,
              :BDNOMCOL,
              :BDCODNOTIF,
              :BDTIPONOTIF,
              :BDDATANOTIF,
              :BDDESCNOTIF,
              :BDFALTASNOTIF,
              :BDDIASNOTIF,
              :BDRETORNONOTIF DO
             begin
               BDCODEMPORIG = WCODEMP;
               BDCODCOLORIG = WCODCOL;
               SUSPEND;
             end
         END
     end
  else
     begin
       BDCODEMP = 0;
       BDCODCOL = 0;
       suspend;
     end
end^


CREATE OR ALTER procedure SP_FICHA_REGISTROS_OBSERVACOES (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRHISTTRANSF integer,
    PRPODE integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDOBSCOL varchar(5000),
    BDCODEMPORIG integer,
    BDCODCOLORIG integer)
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(20000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WSQL2 varchar(1000);
declare variable WSQL3 varchar(1000);
declare variable WSQLAUX varchar(1000);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  if (PRPODE = 1) then
     begin
       WSQL = 'SELECT T.BDCODEMP, T.BDCODCOL FROM VW_VRH_EMP_TCOLCON_CAD T ';

       wwhere = '';
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
            wwhere = prcodemp;
          END

       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';

            wwhere = wwhere||prcodcol;
          END

       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;

       WSQL = WSQL || wwhere || ' order by T.BDCODEMP, T.BDCODCOL';

       FOR EXECUTE STATEMENT wsql INTO :WCODEMP, :WCODCOL DO
         BEGIN
           if (PRHISTTRANSF = 1) then
              BEGIN
                WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = ' || WCODEMP || ' and BDCODCOLDEST = ' || WCODCOL;
                FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
                  BEGIN
                    IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
                      BEGIN
                    WSQL3 = 'SELECT * FROM SP_FICHA_REGISTROS_OBSERVACOES(''T.BDCODEMP = '||wcodemporig||''', ''T.BDCODCOL = ' || wcodcolorig || ''',' || prhisttransf || ',' || prpode || ')';
                    FOR EXECUTE STATEMENT wsql3 INTO
                      :BDCODEMP,
                      :BDCODCOL,
                      :BDNOMCOL,
                      :BDOBSCOL,
                      :BDCODEMPORIG,
                      :BDCODCOLORIG DO
                          BEGIN
                        BDCODEMP = WCODEMP;
                        BDCODCOL = WCODCOL;
                        SUSPEND;
                  END
              END
                  END
              END


           WSQLAUX =  ' select COL.BDCODEMP, COL.BDCODCOL, COLCAD.BDNOMCOL, OBS.BDOBSCOL ' ||
                      ' from VRH_EMP_TCOLCON COL ' ||
                      ' left outer join VRHF_EMP_TCOL_HIST OBS on (OBS.BDCODEMP = COL.BDCODEMP and OBS.BDCODCOL = COL.BDCODCOL) ' ||
                      ' left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COL.BDCODEMP and COLCAD.BDCODCOL = COL.BDCODCOL) ' ||
                      ' where COL.BDCODEMP = ' || WCODEMP || ' and ' ||
                      '       COL.BDCODCOL = ' || WCODCOL || ' and ' ||
                      '       OBS.BDOBSCOL is not null and TRIM(OBS.BDOBSCOL) <> '' ''';

          FOR EXECUTE STATEMENT wsqlaux INTO
              :BDCODEMP,
              :BDCODCOL,
              :BDNOMCOL,
              :BDOBSCOL DO
             begin
               BDCODEMPORIG = WCODEMP;
               BDCODCOLORIG = WCODCOL;
               SUSPEND;
             end
         END
     end
  else
     begin
       BDCODEMP = 0;
       BDCODCOL = 0;
       suspend;
     end
end^


CREATE OR ALTER procedure SP_FICHA_REGISTROS_ESTABILIDADE (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRHISTTRANSF integer,
    PRPODE integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDDATAINICIO date,
    BDDATAFIM date,
    BDMOTEST varchar(100),
    BDOBSERVACAO varchar(255),
    BDCODEMPORIG integer,
    BDCODCOLORIG integer)
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(20000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WSQL2 varchar(1000);
declare variable WSQL3 varchar(1000);
declare variable WSQLAUX varchar(1000);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  if (PRPODE = 1) then
     begin
       WSQL = 'SELECT T.BDCODEMP, T.BDCODCOL FROM VW_VRH_EMP_TCOLCON_CAD T ';

       wwhere = '';
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
            wwhere = prcodemp;
          END

       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';

            wwhere = wwhere||prcodcol;
          END

       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;

       WSQL = WSQL || wwhere || ' order by T.BDCODEMP, T.BDCODCOL';

       FOR EXECUTE STATEMENT wsql INTO :WCODEMP, :WCODCOL DO
         BEGIN
           if (PRHISTTRANSF = 1) then
              BEGIN
                WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = ' || WCODEMP || ' and BDCODCOLDEST = ' || WCODCOL;
                FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
                  BEGIN
                    IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
                      BEGIN
                    WSQL3 = 'SELECT * FROM SP_FICHA_REGISTROS_ESTABILIDADE(''T.BDCODEMP = '||wcodemporig||''', ''T.BDCODCOL = ' || wcodcolorig || ''',' || prhisttransf || ',' || prpode || ')';
                    FOR EXECUTE STATEMENT wsql3 INTO
                      :BDCODEMP,
                      :BDCODCOL,
                      :BDNOMCOL,
                      :BDDATAINICIO,
                      :BDDATAFIM,
                      :BDMOTEST,
                      :BDOBSERVACAO,
                      :BDCODEMPORIG,
                      :BDCODCOLORIG DO
                          BEGIN
                        BDCODEMP = WCODEMP;
                        BDCODCOL = WCODCOL;
                        SUSPEND;
                  END
              END
                  END
              END


           WSQLAUX =  ' select COL.BDCODEMP, COL.BDCODCOL, COLCAD.BDNOMCOL, EST.BDDATAINICIO, EST.BDDATAFIM, EST.BDCODMOTESTAB || ''-'' || MEST.BDDESCRICAO BDMOTEST, ' ||
                      '        EST.BDOBSERVACAO ' ||
                      ' from VRH_EMP_TCOLCON COL ' ||
                      ' left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COL.BDCODEMP and COLCAD.BDCODCOL = COL.BDCODCOL) ' ||
                      ' join VRH_EMP_TESTABILIDADE EST on (EST.BDCODEMP = COL.BDCODEMP and EST.BDCODCOL = COL.BDCODCOL) ' ||
                      ' left outer join VRH_BASE_TMOTESTAB_ESOCIAL MEST on (MEST.BDCODMOTESTAB = EST.BDCODMOTESTAB) ' ||
                      ' where COL.BDCODEMP = ' || WCODEMP || ' and ' ||
                      '       COL.BDCODCOL = ' || WCODCOL;

          FOR EXECUTE STATEMENT wsqlaux INTO
              :BDCODEMP,
              :BDCODCOL,
              :BDNOMCOL,
              :BDDATAINICIO,
              :BDDATAFIM,
              :BDMOTEST,
              :BDOBSERVACAO DO
             begin
               BDCODEMPORIG = WCODEMP;
               BDCODCOLORIG = WCODCOL;
               SUSPEND;
             end
         END
     end
  else
     begin
       BDCODEMP = 0;
       BDCODCOL = 0;
       suspend;
     end
end^


CREATE OR ALTER procedure SP_FICHA_REGISTROS_COLCON (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRHISTTRANSF integer,
    PRFILTROMES varchar(1000) = null,
    PRFILTROSINTRAB varchar(1000) = null,
    PRFILTROCC varchar(1000) = null,
    PRFILTROCLASSE varchar(1000) = null,
    PRFILTROFUNCAO varchar(1000) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDNOMCOLUPPER varchar(70),
    BDDATAADMCOL date,
    BDFICHAREGCOL varchar(12),
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP DM_CNPJ_CPF,
    BDDATARESCISAO date,
    BDPROJECAOAVISO date,
    BDPISCOL varchar(14),
    BDCODEMPORIG integer,
    BDCODCOLORIG integer)
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(20000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WSQL2 varchar(1000);
declare variable WSQL3 varchar(1000);
declare variable WSQLAUX varchar(2000);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  WSQL = 'SELECT T.BDCODEMP, T.BDCODCOL FROM VW_VRH_EMP_TCOLCON_CAD T ' ||
         'left outer join VRH_EMP_TCOLCON COL ON (T.BDCODEMP = COL.BDCODEMP and T.BDCODCOL = COL.BDCODCOL) ';

  -- Filtro por situacao do colaborador
  IF ((PRFILTROMES IS NOT NULL) AND (PRFILTROMES <> '')) THEN
     WSQL = WSQL || PRFILTROMES;

  -- Filtro por sindicato
  IF ((PRFILTROSINTRAB IS NOT NULL) AND (PRFILTROSINTRAB <> '')) THEN
     WSQL = WSQL || ' join VW_VRH_EMP_TCOL_VINC COL_VINC on (COL.BDCODEMP = COL_VINC.BDCODEMP and COL.BDCODCOL = COL_VINC.BDCODCOL and ' || PRFILTROSINTRAB || ') ';

  -- Filtro por Centro de Custo
  IF ((PRFILTROCC IS NOT NULL) AND (PRFILTROCC <> '')) THEN
     WSQL = WSQL || ' JOIN VRHF_EMP_TPREPFN COLVINC_CC ON (COL.BDCODEMP = COLVINC_CC.BDCODEMP AND COL.BDCODCOL = COLVINC_CC.BDCODCOL AND ' || PRFILTROCC || ') ';

  -- Filtro por classe
  IF ((PRFILTROCLASSE IS NOT NULL) AND (PRFILTROCLASSE <> '')) THEN
     WSQL = WSQL || ' join VW_VRH_EMP_TCOLCON_VINC COLCON_VINC on (COL.BDCODEMP = COLCON_VINC.BDCODEMP and COL.BDCODCOL = COLCON_VINC.BDCODCOL and ' || PRFILTROCLASSE || ') ';

  -- Filtro por funcao
  IF ((PRFILTROFUNCAO IS NOT NULL) AND (PRFILTROFUNCAO <> '')) THEN
     WSQL = WSQL || ' join VW_VRH_EMP_TCOL_VINCDIA COL_VINCDIA on (COL.BDCODEMP = COL_VINCDIA.BDCODEMP and COL.BDCODCOL = COL_VINCDIA.BDCODCOL and ' || PRFILTROFUNCAO || ') ';

  wwhere = '';
  IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
     wwhere = prcodemp;

  IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
     BEGIN
       IF (wwhere <> '') THEN
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodcol;
     END

  IF (wwhere <> '') THEN
     wwhere = ' where '||wwhere;

  WSQL = WSQL || wwhere || ' order by T.BDCODEMP, T.BDCODCOL';

  FOR EXECUTE STATEMENT wsql INTO :WCODEMP, :WCODCOL DO
    BEGIN
      if (PRHISTTRANSF = 1) then
         BEGIN
           WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = ' || WCODEMP || ' and BDCODCOLDEST = ' || WCODCOL;
           FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
             BEGIN
               IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
                 BEGIN
               WSQL3 = 'SELECT * FROM SP_FICHA_REGISTROS_COLCON(''T.BDCODEMP = '||wcodemporig||''', ''T.BDCODCOL = ' || wcodcolorig || ''', ' || prhisttransf || ')';
               FOR EXECUTE STATEMENT wsql3 INTO
                 :BDCODEMP,
                 :BDCODCOL,
                 :BDNOMCOL,
                 :BDNOMCOLUPPER,
                 :BDDATAADMCOL,
                 :BDFICHAREGCOL,
                 :BDNOMEMP,
                 :BDCNPJEMP,
                 :BDDATARESCISAO,
                 :BDPROJECAOAVISO,
                 :BDPISCOL,
                 :BDCODEMPORIG,
                 :BDCODCOLORIG DO
                     BEGIN
                   BDCODEMP = WCODEMP;
                   BDCODCOL = WCODCOL;
                   SUSPEND;
             END
         END
             END
         END

      WSQLAUX =  ' select COL.BDCODEMP, COL.BDCODCOL, COLCAD.BDNOMCOL, COLCAD.BDNOMCOLUPPER , coalesce (COL_ADM.BDNOVADATAADMRT, COL.BDDATAADMCOL) as BDDATAADMCOL, '||
                 ' COL_ADM.BDFICHAREGCOL, ' ||
                 ' EMP_REF.BDNOMEMP, EMP.BDCNPJEMP, res.BDDATARESCISAO, ' ||
                 ' case when (COALESCE(pres.BDAVPREPRES,0) in (0,1)) or (Upper(COALESCE(pres.BDINDFER13, ''FALSE'')) = ''TRUE'') then ' ||
                 ' res.BDPROJECAOAVISO else CAST(null as DATE) end BDPROJECAOAVISO, ' ||
                 ' DOCREF.BDPISCOL ' ||
                 ' from VRH_EMP_TCOLCON COL ' ||
                 ' left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COL.BDCODEMP and COLCAD.BDCODCOL = COL.BDCODCOL) ' ||
                 ' join VW_VRH_EMP_TCOL_ADM COL_ADM on (COL.BDCODEMP = COL_ADM.BDCODEMP and COL.BDCODCOL = COL_ADM.BDCODCOL) ' ||
                 ' join VW_TEMPRESAS_REF EMP_REF on (COL.BDCODEMP = EMP_REF.BDCODEMP) ' ||
                 ' join TEMPRESAS EMP on (COL.BDCODEMP = EMP.BDCODEMP) ' ||
                 ' left outer join VW_VRH_EMP_TCOLCON_DOCREF DOCREF on (COL.BDCODEMP = DOCREF.BDCODEMP and COL.BDCODCOL = DOCREF.BDCODCOL) ' ||
                 ' left outer join vrh_emp_trescisao res on (col.bdcodemp = res.bdcodemp and col.bdcodcol = res.bdcodcol) ' ||
                 ' left outer join vrh_base_tprepresc pres on (pres.bdcodpres = res.bdcodpres) ' ||
                 ' where (COL.BDCODEMP = ' || WCODEMP || ') and ' ||
                 '       (COL.BDCODCOL = ' || WCODCOL || ')';

     FOR EXECUTE STATEMENT wsqlaux INTO
         :BDCODEMP,
         :BDCODCOL,
         :BDNOMCOL,
         :BDNOMCOLUPPER,
         :BDDATAADMCOL,
         :BDFICHAREGCOL,
         :BDNOMEMP,
         :BDCNPJEMP,
         :BDDATARESCISAO,
         :BDPROJECAOAVISO,
         :BDPISCOL DO
        begin
          BDCODEMPORIG = WCODEMP;
          BDCODCOLORIG = WCODCOL;
          SUSPEND;
        end
    END
end^


CREATE OR ALTER procedure SP_FICHA_REGISTROS_TRANSF (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRHISTTRANSF integer,
    PRPODE integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCODEMPORIG integer,
    BDCODCOLORIG integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODPTRAN integer,
    BDDESCPRES varchar(110),
    BDTIPOADMCOL integer,
    BDDESCTIPOMOV varchar(100),
    BDDATATRF date,
    BDDATARESCISAO date,
    BDNOMEMPDEST DM_BDNOMEMP,
    BDCODEMPDEST varchar(20),
    BDCODCOLDEST varchar(20),
    BDDESCCOLDEST char(9))
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(20000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WSQL2 varchar(2000);
declare variable WSQL3 varchar(30000);
declare variable WSQLAUX varchar(30000);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  if (PRPODE = 1) then
     begin
       WSQL = 'SELECT T.BDCODEMP, T.BDCODCOL FROM VW_VRH_EMP_TCOLCON_CAD T ';

       wwhere = '';
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
            wwhere = prcodemp;
          END

       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';

            wwhere = wwhere||prcodcol;
          END

       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;

       WSQL = WSQL || wwhere || ' order by T.BDCODEMP, T.BDCODCOL';

       FOR EXECUTE STATEMENT wsql INTO :WCODEMP, :WCODCOL DO
         BEGIN
           if (PRHISTTRANSF = 1) then
              BEGIN
                WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = ' || WCODEMP || ' and BDCODCOLDEST = ' || WCODCOL;
                FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
                  BEGIN
                    IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
                      BEGIN
                    WSQL3 = 'SELECT * FROM SP_FICHA_REGISTROS_TRANSF(''T.BDCODEMP = '||wcodemporig||''', ''T.BDCODCOL = ' || wcodcolorig || ''',' || prhisttransf || ',' || prpode || ')';
                    FOR EXECUTE STATEMENT wsql3 INTO
                        :BDCODEMP,
                        :BDCODCOL,
                        :BDNOMCOL,
                        :BDCODEMPORIG,
                        :BDCODCOLORIG,
                        :BDNOMEMP,
                        :BDCODPTRAN,
                        :BDDESCPRES,
                        :BDTIPOADMCOL,
                        :BDDESCTIPOMOV,
                        :BDDATATRF,
                        :BDDATARESCISAO,
                        :BDNOMEMPDEST,
                        :BDCODEMPDEST,
                        :BDCODCOLDEST,
                        :BDDESCCOLDEST do
                          BEGIN
                        BDCODEMP = WCODEMP;
                        BDCODCOL = WCODCOL;
                        SUSPEND;
                  END
              END
                  END
              END

           WSQLAUX =  'select COL.BDCODEMP, COL.BDCODCOL, COLCAD.BDNOMCOL, TRF.BDCODEMPORIG, TRF.BDCODCOLORIG, ' ||
                      ' (select first 1 tempresas_ref.bdnomemp from tempresas_ref where tempresas_ref.bdcodemp = TRF.BDCODEMPORIG order by bdcodemp desc, bdrefemp desc) as BDNOMEMP, ' ||
                      ' TRF.BDCODPTRAN, PRES.BDDESCPRES, ADM.BDTIPOADMCOL, RHADM.BDDESCTIPOMOV, ' ||
                      ' TRF.BDDATATRF, RESC.BDDATARESCISAO, ' ||
                      ' coalesce((select first 1 tempresas_ref.bdnomemp from tempresas_ref where tempresas_ref.bdcodemp = TRF.BDCODEMPDEST order by bdcodemp desc, bdrefemp desc), ''Empresa nao cadastrada no sistema'') as BDNOMEMPDEST, ' ||
                      ' coalesce(TRF.BDCODEMPDEST || '' - '', '''') BDCODEMPDEST, case coalesce(TRF.BDCODEMPDEST, 0) when 0 then TRF.BDCNPJEMP else TRF.BDCODCOLDEST end BDCODCOLDEST, ' ||
                      'case coalesce(TRF.BDCODEMPDEST, 0) when 0 then ''CNPJ da'' else ''Codigo na'' end BDDESCCOLDEST ' ||
                      'from VRH_EMP_TCOLCON COL ' ||
                      'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COL.BDCODEMP and COLCAD.BDCODCOL = COL.BDCODCOL) ' ||
                      'left outer join VRH_EMP_TTRANSCOL TRF on (TRF.BDCODEMPORIG = COL.BDCODEMP and TRF.BDCODCOLORIG = COL.BDCODCOL) ' ||
                      'left outer join VW_VRH_EMP_TCOL_ADM ADM on (ADM.BDCODEMP = COL.BDCODEMP and ADM.BDCODCOL = COL.BDCODCOL) ' ||
                      'left outer join VRH_BASE_TTIPOMOV RHADM on (RHADM.BDCODTIPOMOV = ADM.BDTIPOADMCOL) ' ||
                      'left outer join VRH_BASE_TPREPRESC PRES on (PRES.BDCODPRES = TRF.BDCODPTRAN) ' ||
                      'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ' ||
                      'where TRF.BDDATATRF is not null and PRES.BDTIPOMOV = 1 and ' ||
                      '      COL.BDCODEMP = ' || WCODEMP || ' and ' ||
                      '      COL.BDCODCOL = ' || WCODCOL;

          FOR EXECUTE STATEMENT wsqlaux INTO
              :BDCODEMP,
              :BDCODCOL,
              :BDNOMCOL,
              :BDCODEMPORIG,
              :BDCODCOLORIG,
              :BDNOMEMP,
              :BDCODPTRAN,
              :BDDESCPRES,
              :BDTIPOADMCOL,
              :BDDESCTIPOMOV,
              :BDDATATRF,
              :BDDATARESCISAO,
              :BDNOMEMPDEST,
              :BDCODEMPDEST,
              :BDCODCOLDEST,
              :BDDESCCOLDEST do
             begin
               BDCODEMPORIG = WCODEMP;
               BDCODCOLORIG = WCODCOL;
               SUSPEND;
             end
         END
     end
  else
     begin
       BDCODEMP = 0;
       BDCODCOL = 0;
       BDCODEMPORIG = 0;
       BDCODCOLORIG = 0;
       suspend;
     end
end^


CREATE OR ALTER procedure SP_FICHA_REGISTROS_TRANSF_ENT (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRHISTTRANSF integer,
    PRPODE integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCODEMPORIG integer,
    BDCODCOLORIG integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODPTRAN integer,
    BDDESCPRES varchar(110),
    BDTIPOADMCOL integer,
    BDDESCTIPOMOV varchar(100),
    BDDATATRF date,
    BDDATARESCISAO date,
    BDNOMEMPDEST DM_BDNOMEMP,
    BDCODEMPDEST varchar(20),
    BDCODCOLDEST varchar(20),
    BDDESCCOLDEST char(9))
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(20000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WSQL2 varchar(2000);
declare variable WSQL3 varchar(30000);
declare variable WSQLAUX varchar(30000);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  if (PRPODE = 1) then
     begin
       WSQL = 'SELECT T.BDCODEMP, T.BDCODCOL FROM VW_VRH_EMP_TCOLCON_CAD T ';

       wwhere = '';
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
            wwhere = prcodemp;
          END

       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';

            wwhere = wwhere||prcodcol;
          END

       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;

       WSQL = WSQL || wwhere || ' order by T.BDCODEMP, T.BDCODCOL';

       FOR EXECUTE STATEMENT wsql INTO :WCODEMP, :WCODCOL DO
         BEGIN
           if (PRHISTTRANSF = 1) then
              BEGIN
                WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = ' || WCODEMP || ' and BDCODCOLDEST = ' || WCODCOL;
                FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
                  BEGIN
                    IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
                      BEGIN
                    WSQL3 = 'SELECT * FROM SP_FICHA_REGISTROS_TRANSF_ENT(''T.BDCODEMP = '||wcodemporig||''', ''T.BDCODCOL = ' || wcodcolorig || ''',' || prhisttransf || ',' || prpode || ')';
                    FOR EXECUTE STATEMENT wsql3 INTO
                        :BDCODEMP,
                        :BDCODCOL,
                        :BDNOMCOL,
                        :BDCODEMPORIG,
                        :BDCODCOLORIG,
                        :BDNOMEMP,
                        :BDCODPTRAN,
                        :BDDESCPRES,
                        :BDTIPOADMCOL,
                        :BDDESCTIPOMOV,
                        :BDDATATRF,
                        :BDDATARESCISAO,
                        :BDNOMEMPDEST,
                        :BDCODEMPDEST,
                        :BDCODCOLDEST,
                        :BDDESCCOLDEST do
                      begin
                        BDCODEMP = WCODEMP;
                        BDCODCOL = WCODCOL;
                        SUSPEND;
                      end
                  END
              END
              END

           WSQLAUX =  'select COL.BDCODEMP, COL.BDCODCOL, COLCAD.BDNOMCOL, TRF.BDCODEMPORIG, TRF.BDCODCOLORIG, ' ||
                      ' (select first 1 tempresas_ref.bdnomemp from tempresas_ref where tempresas_ref.bdcodemp = TRF.BDCODEMPORIG order by bdcodemp desc, bdrefemp desc) as BDNOMEMP, ' ||
                      ' TRF.BDCODPTRAN, PRES.BDDESCPRES, ADM.BDTIPOADMCOL, RHADM.BDDESCTIPOMOV, ' ||
                      ' TRF.BDDATATRF, RESC.BDDATARESCISAO, ' ||
                      ' coalesce((select first 1 tempresas_ref.bdnomemp from tempresas_ref where tempresas_ref.bdcodemp = TRF.BDCODEMPDEST order by bdcodemp desc, bdrefemp desc), ''Empresa nao cadastrada no sistema'') as BDNOMEMPDEST,' ||
                      ' coalesce(TRF.BDCODEMPDEST || '' -'', '''') BDCODEMPDEST, case coalesce(TRF.BDCODEMPDEST, 0) when 0 then TRF.BDCNPJEMP else TRF.BDCODCOLDEST end BDCODCOLDEST, ' ||
                      'case coalesce(TRF.BDCODEMPDEST, 0) when 0 then ''CNPJ da'' else ''Codigo na'' end BDDESCCOLDEST ' ||
                      'from VRH_EMP_TCOLCON COL ' ||
                      'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COL.BDCODEMP and COLCAD.BDCODCOL = COL.BDCODCOL) ' ||
                      'left outer join VRH_EMP_TTRANSCOL TRF on (TRF.BDCODEMPDEST = COL.BDCODEMP and TRF.BDCODCOLDEST = COL.BDCODCOL) ' ||
                      'left outer join VW_VRH_EMP_TCOL_ADM ADM on (ADM.BDCODEMP = COL.BDCODEMP and ADM.BDCODCOL = COL.BDCODCOL) ' ||
                      'left outer join VRH_BASE_TTIPOMOV RHADM on (RHADM.BDCODTIPOMOV = ADM.BDTIPOADMCOL) ' ||
                      'left outer join VRH_BASE_TPREPRESC PRES on (PRES.BDCODPRES = TRF.BDCODPTRAN) ' ||
                      'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = TRF.BDCODEMPORIG and RESC.BDCODCOL = TRF.BDCODCOLORIG) ' ||
                      'where TRF.BDDATATRF is not null and PRES.BDTIPOMOV = 1 and ' ||
                      '      COL.BDCODEMP = ' || WCODEMP || ' and ' ||
                      '      COL.BDCODCOL = ' || WCODCOL;

          FOR EXECUTE STATEMENT wsqlaux INTO
              :BDCODEMP,
              :BDCODCOL,
              :BDNOMCOL,
              :BDCODEMPORIG,
              :BDCODCOLORIG,
              :BDNOMEMP,
              :BDCODPTRAN,
              :BDDESCPRES,
              :BDTIPOADMCOL,
              :BDDESCTIPOMOV,
              :BDDATATRF,
              :BDDATARESCISAO,
              :BDNOMEMPDEST,
              :BDCODEMPDEST,
              :BDCODCOLDEST,
              :BDDESCCOLDEST do
             begin
               --BDCODEMPORIG = WCODEMP;
               --BDCODCOLORIG = WCODCOL;

               BDCODEMPORIG = wcodemporig;        --Solicitação W150280 LuizCovre
               BDCODCOLORIG = wcodcolorig;

               SUSPEND;
             end
         END
     end
  else
     begin
       BDCODEMP = 0;
       BDCODCOL = 0;
       BDCODEMPORIG = 0;
       BDCODCOLORIG = 0;
       suspend;
     end
end^


CREATE OR ALTER procedure SP_FICHA_REGISTROS_TRANSFENTCAD (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRHISTTRANSF integer,
    PRPODE integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDTIPOADMCOL integer,
    BDDATATRFCOL date,
    BDCNPJEMPANT DM_CNPJ_CPF,
    BDNOMEMP DM_BDNOMEMP,
    BDCODEMPANT DM_BDNOMEMP,
    BDCODEMPORIG integer,
    BDCODCOLORIG integer)
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(20000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WSQL2 varchar(2000);
declare variable WSQL3 varchar(30000);
declare variable WSQLAUX varchar(30000);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  if (PRPODE = 1) then
     begin
       WSQL = 'SELECT T.BDCODEMP, T.BDCODCOL FROM VW_VRH_EMP_TCOLCON_CAD T ';

       wwhere = '';
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
            wwhere = prcodemp;
          END

       IF ((prcodcol IS NOT NULL) AND (prcodcol <> '')) THEN
          BEGIN
            IF (wwhere <> '') THEN
               wwhere = wwhere||' and ';

            wwhere = wwhere||prcodcol;
          END

       IF (wwhere <> '') THEN
          wwhere = ' where '||wwhere;

       WSQL = WSQL || wwhere || ' order by T.BDCODEMP, T.BDCODCOL';

       FOR EXECUTE STATEMENT wsql INTO :WCODEMP, :WCODCOL DO
         BEGIN
           if (PRHISTTRANSF = 1) then
              BEGIN
                WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = ' || WCODEMP || ' and BDCODCOLDEST = ' || WCODCOL;
                FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
                  BEGIN
                    IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
                      BEGIN
                    WSQL3 = 'SELECT * FROM SP_FICHA_REGISTROS_TRANSFENTCAD(''T.BDCODEMP = '||wcodemporig||''', ''T.BDCODCOL = ' || wcodcolorig || ''',' || prhisttransf || ',' || prpode || ')';
                    FOR EXECUTE STATEMENT wsql3 INTO
                        :BDCODEMP,
                        :BDCODCOL,
                        :BDNOMCOL,
                        :BDTIPOADMCOL,
                        :BDDATATRFCOL,
                        :BDCNPJEMPANT,
                        :BDNOMEMP,
                        :BDCODEMPANT,
                        :BDCODEMPORIG,
                        :BDCODCOLORIG do
                      begin
                        BDCODEMP = WCODEMP;
                        BDCODCOL = WCODCOL;
                        SUSPEND;
                      end
                  END
              END
              END

           WSQLAUX =  ' select ADM.BDCODEMP, ADM.BDCODCOL, COLCAD.BDNOMCOL, ADM.BDTIPOADMCOL, PART.BDDATATRFCOL, ADM.BDCNPJEMPANT, REF.BDNOMEMP, EMP.BDCODEMP BDCODEMPANT ' ||
                      ' from VW_VRH_EMP_TCOL_ADM ADM ' ||
                      ' left outer join VRH_EMP_TCOLCON_PARTIDA PART on (PART.BDCODEMP = ADM.BDCODEMP and PART.BDCODCOL = ADM.BDCODCOL) ' ||
                      ' left outer join TEMPRESAS EMP on (EMP.BDCNPJEMP = ADM.BDCNPJEMPANT) ' ||
                      ' left outer join VW_TEMPRESAS_REF REF on (REF.BDCODEMP = EMP.BDCODEMP) ' ||
                      ' left outer join VRH_EMP_TTRANSCOL TRANS on (TRANS.BDCODEMPDEST = ADM.BDCODEMP and TRANS.BDCODCOLDEST = ADM.BDCODCOL) ' ||
                      ' left outer join VRH_EMP_TTRANSCOL TRANS2 on (TRANS2.BDCODEMPORIG = ADM.BDCODEMP and TRANS2.BDCODCOLORIG = ADM.BDCODCOL) ' ||
                      ' left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = ADM.BDCODEMP and COLCAD.BDCODCOL = ADM.BDCODCOL) ' ||
                      ' where ADM.BDTIPOADMCOL in (3,4,5,7) and ((TRANS.BDDATATRF is null) and (TRANS2.BDDATATRF is null)) and ' ||
                      '       ADM.BDCODEMP = ' || WCODEMP || ' and ' ||
                      '       ADM.BDCODCOL = ' || WCODCOL;

          FOR EXECUTE STATEMENT wsqlaux INTO
              :BDCODEMP,
              :BDCODCOL,
              :BDNOMCOL,
              :BDTIPOADMCOL,
              :BDDATATRFCOL,
              :BDCNPJEMPANT,
              :BDNOMEMP,
              :BDCODEMPANT do
             begin
               BDCODEMPORIG = WCODEMP;
               BDCODCOLORIG = WCODCOL;
               SUSPEND;
             end
         END
     end
  else
     begin
       BDCODEMP = 0;
       BDCODCOL = 0;
       BDCODEMPORIG = 0;
       BDCODCOLORIG = 0;
       suspend;
     end
end^

CREATE OR ALTER trigger vef_base_ttabinfad52_bi0 for vef_base_ttabinfad52
active before insert position 0
AS
  DECLARE VARIABLE vORDEM INTEGER;
BEGIN
  IF ((NEW.BDORDEM52 IS NULL) OR (NEW.BDORDEM52 = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEM52) + 1), 1) FROM VEF_BASE_TTABINFAD52 INTO vORDEM;
      NEW.BDORDEM52 = vORDEM;
    END
END^

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERDMEDBEM_BI0 FOR VEF_EMP_TMOVSERDMEDBEM
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE VORDEMLAN INTEGER;
BEGIN
  IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0)) THEN
    BEGIN
      SELECT COALESCE((MAX(BDORDEM) + 1), 1) FROM VEF_EMP_TMOVSERDMEDBEM WHERE (BDCODEMP = NEW.BDCODEMP AND BDCHAVE = NEW.BDCHAVE) INTO VORDEMLAN;
      NEW.BDORDEM = VORDEMLAN;
    END
END^

CREATE OR ALTER procedure SP_VRH_TREEVIEW_CONS_ANUAL_CONF (
    PRCODEMP varchar(10000),
    PRREFINI integer,
    PRREFFIN integer,
    PRCODPLANO integer,
    PRCODQUADRO integer,
    PRTIPOFOLHA integer,
    PRTOTALIZADOR integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDREF integer,
    BDCODQUADRO integer,
    BDDESCQUADRO varchar(80),
    BDORDEM integer,
    BDORDEMAUX integer,
    BDDESCRICAO varchar(80),
    BDVALOR numeric(15,6),
    BDTOTAL numeric(15,6),
    BDJAN numeric(15,6),
    BDFEV numeric(15,6),
    BDMAR numeric(15,6),
    BDABR numeric(15,6),
    BDMAI numeric(15,6),
    BDJUN numeric(15,6),
    BDJUL numeric(15,6),
    BDAGO numeric(15,6),
    BDSET numeric(15,6),
    BDOUT numeric(15,6),
    BDNOV numeric(15,6),
    BDDEZ numeric(15,6),
    BDREGAUX integer)
as
declare variable WCODEMPANTERIOR integer;
declare variable WNOMEEMPANTERIOR DM_BDNOMEMP;
declare variable WCODCOLANTERIOR integer;
declare variable WNOMECOLANTERIOR DM_BDNOMCOL;
declare variable WREFANTERIOR integer;
declare variable WCODQUADROANTERIOR integer;
declare variable WDESCQUADROANTERIOR varchar(80);
declare variable WORDEMANTERIOR integer;
declare variable WDESCRICAOANTERIOR varchar(80);
declare variable WCODEMPAUX integer;
declare variable WNOMEEMPAUX DM_BDNOMEMP;
declare variable WCODCOLAUX integer;
declare variable WNOMECOLAUX DM_BDNOMCOL;
declare variable WREFAUX integer;
declare variable WCODQUADROAUX integer;
declare variable WDESCQUADROAUX varchar(80);
declare variable WORDEMAUX integer;
declare variable WDESCRICAOAUX varchar(80);
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(32000);
declare variable WMES integer;
declare variable WORDEMTOT numeric(15,6);
declare variable WORDEMJAN numeric(15,6);
declare variable WORDEMFEV numeric(15,6);
declare variable WORDEMMAR numeric(15,6);
declare variable WORDEMABR numeric(15,6);
declare variable WORDEMMAI numeric(15,6);
declare variable WORDEMJUN numeric(15,6);
declare variable WORDEMJUL numeric(15,6);
declare variable WORDEMAGO numeric(15,6);
declare variable WORDEMSET numeric(15,6);
declare variable WORDEMOUT numeric(15,6);
declare variable WORDEMNOV numeric(15,6);
declare variable WORDEMDEZ numeric(15,6);
declare variable WCODQUADROANTERIOR_CONTROLE integer;
declare variable WCODEMPANTERIOR_CONTROLE integer;
declare variable WCODCOLANTERIOR_CONTROLE integer;
declare variable WORDEMAUXANTERIOR integer;
declare variable WORDEMAUX2 integer;
declare variable WORDEMAUXATUAL integer;
declare variable WCODCLA integer;
begin
  EXECUTE PROCEDURE sp_seta_competencia(prrefini, NULL, NULL);

  wsql = 'select T.BDCODEMP, ';
  wsql = wsql||'empresas.BDNOMEMP, ';
  wsql = WSQL||'T.BDCODCLA, ';
  wsql = wsql||'T.BDCODCOL, ';
  wsql = wsql||'COL.BDNOMCOL, ';
  wsql = wsql||'T.BDREF, ';
  wsql = wsql||'T.BDCODQPLACONSCONF, ';
  wsql = wsql||'QUADRO.BDDESCRICAO, ';
  wsql = wsql||'T.BDORDEM, ';
  wsql = wsql||'T.BDORDEMAUX, ';
  wsql = wsql||'T.BDDESCRICAO, ';
  wsql = wsql||'T.BDVALOR ';
  wsql = wsql||'from VRHF_REL_CONS_ANUAL_CONF T ';
  wsql = wsql||'LEFT OUTER JOIN TEMPRESAS_REF empresas ON empresas.BDCODEMP = T.BDCODEMP AND empresas.BDREFEMP = '||
                                'COALESCE('|| 
                                '(SELECT FIRST 1 x.BDREFEMP '|| 
                                ' FROM TEMPRESAS_REF x '|| 
                                ' WHERE x.BDCODEMP = T.BDCODEMP '|| 
                                ' AND x.BDREFEMP <= CAST(rdb$get_context(''USER_SESSION'',''W_ANOMES'') AS INTEGER) '|| 
                                ' ORDER BY x.BDREFEMP DESC) '|| 
                                ','|| 
                                '(SELECT FIRST 1 X.BDREFEMP '|| 
                                ' FROM TEMPRESAS_REF X '|| 
                                ' WHERE X.BDCODEMP = T.BDCODEMP '|| 
                                ' ORDER BY X.BDREFEMP)) ';
  wsql = wsql||'LEFT OUTER JOIN VRH_EMP_TCOLCON_CAD col ON col.BDCODEMP = T.BDCODEMP AND col.BDCODCOL = T.BDCODCOL AND col.BDREFCOL = '||
                                'COALESCE('||
                                '(SELECT FIRST 1 x.BDREFCOL '||
                                ' FROM VRH_EMP_TCOLCON_CAD x '||
                                ' WHERE x.BDCODEMP = T.BDCODEMP '||
                                ' AND x.BDCODCOL = T.BDCODCOL '||
                                ' AND x.BDREFCOL <= CAST(rdb$get_context(''USER_SESSION'',''W_ANOMES'') AS INTEGER) '||
                                ' ORDER BY x.BDREFCOL DESC)  '||
                                ','                           ||
                                '(SELECT FIRST 1 X.BDREFCOL  '||
                                ' FROM VRH_EMP_TCOLCON_CAD X '||
                                ' WHERE X.BDCODEMP = T.BDCODEMP '||
                                ' AND X.BDCODCOL = T.BDCODCOL '||
                                '  ORDER BY X.BDREFCOL))';

  wsql = wsql||' left outer join TPLANOCONSCONF_Q QUADRO on (QUADRO.BDCODQPLACONSCONF = t.BDCODQPLACONSCONF AND QUADRO.BDCODPLACONSCONF = T.BDCODPLACONSCONF) ';

  wwhere = '';

  IF (:prcodemp IS NOT NULL) THEN
    wwhere = :prcodemp;

  IF ((:prCodPlano IS NOT NULL) AND (:prCodPlano > 0)) THEN
    BEGIN
      IF (wWhere <> '') THEN
        wWhere = wWhere||' and ';
      ELSE
        wWhere = wWhere||' where ';

      wWhere = wWhere||'T.BDCODPLACONSCONF  = '||:prCodPlano;
    END

  IF ((:prcodquadro IS NOT NULL) and (:prcodquadro  > 0)) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      ELSE
        wwhere = wwhere||' where ';

      wwhere = wwhere||'T.BDCODQPLACONSCONF  = '||:prcodquadro;
    END

  IF (:prrefini IS NOT NULL) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      ELSE
        wwhere = wwhere||' where ';

      wwhere = wwhere||'T.BDREF Between '||:prrefini||' and '||:prreffin;
    END

  IF (:prtipofolha IS NOT NULL) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      ELSE
        wwhere = wwhere||' where ';

      wwhere = wwhere||'T.BDTIPOFOLHA = '||:prtipofolha;
    END

  IF (:prtotalizador IS NOT NULL) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      ELSE
        wwhere = wwhere||' where ';

      wwhere = wwhere||'T.BDTOTALIZADOR = '||:prtotalizador;
    END

  IF (wwhere <> '') THEN
    wwhere = wwhere||' and QUADRO.bdcodsis = 2';
  ELSE
    wwhere = wwhere||' QUADRO.bdcodsis = 2';

  IF (wwhere <> '') THEN
    wwhere = 'where '||wwhere||' and (NOT T.BDCODCLA in (2,31))';
  ELSE
    wwhere = wwhere||' where (NOT T.BDCODCLA in (2,31))';

  wsql = wsql||wwhere;
  wsql = wsql||' union all ';


  wsql = wsql||'select T.BDCODEMP, ';
  wsql = wsql||'empresas.BDNOMEMP, ';
  wsql = WSQL||'T.BDCODCLA, ';
  wsql = wsql||'COL.BDCODTER BDCODCOL, ';
  wsql = wsql||'COL.BDNOMETER BDNOMCOL, ';
  wsql = wsql||'T.BDREF, ';
  wsql = wsql||'T.BDCODQPLACONSCONF, ';
  wsql = wsql||'QUADRO.BDDESCRICAO, ';
  wsql = wsql||'T.BDORDEM, ';
  wsql = wsql||'T.BDORDEMAUX, ';
  wsql = wsql||'T.BDDESCRICAO, ';
  wsql = wsql||'T.BDVALOR ';
  wsql = wsql||'from VRHF_REL_CONS_ANUAL_CONF T ';
  wsql = wsql||' LEFT OUTER JOIN TEMPRESAS_REF empresas ON empresas.BDCODEMP = T.BDCODEMP AND empresas.BDREFEMP = '||
                                'COALESCE('||
                                '(SELECT FIRST 1 x.BDREFEMP '||
                                ' FROM TEMPRESAS_REF x '||
                                ' WHERE x.BDCODEMP = T.BDCODEMP '||
                                ' AND x.BDREFEMP <= CAST(rdb$get_context(''USER_SESSION'',''W_ANOMES'') AS INTEGER) '||
                                ' ORDER BY x.BDREFEMP DESC) '||
                                ','                           ||
                                '(SELECT FIRST 1 X.BDREFEMP '||
                                ' FROM TEMPRESAS_REF X '||
                                ' WHERE X.BDCODEMP = T.BDCODEMP '||
                                ' ORDER BY X.BDREFEMP)) ';
  wsql = wsql||' LEFT OUTER JOIN TTERCEIRO_REF col ON col.BDCODTER = T.BDCODCOL AND col.BDREFEMP = '||
                                'COALESCE('||
                                '(SELECT FIRST 1 x.BDREFEMP '||
                                ' FROM TTERCEIRO_REF x '||
                                ' WHERE x.BDCODTER = T.BDCODCOL '||
                                ' AND x.BDREFEMP <= CAST(rdb$get_context(''USER_SESSION'',''W_ANOMES'') AS INTEGER) '||
                                ' ORDER BY x.BDREFEMP DESC) '||
                                ','                           ||
                                '(SELECT FIRST 1 X.BDREFEMP '||
                                ' FROM TTERCEIRO_REF X '||
                                ' WHERE X.BDCODTER = T.BDCODCOL '||
                                ' ORDER BY X.BDREFEMP)) ';
  wsql = wsql||' left outer join TPLANOCONSCONF_Q QUADRO on (QUADRO.BDCODQPLACONSCONF = t.BDCODQPLACONSCONF AND QUADRO.BDCODPLACONSCONF = T.BDCODPLACONSCONF) ';

  wwhere = '';

  IF (:prcodemp IS NOT NULL) THEN
    wwhere = :prcodemp;

  IF ((:prCodPlano IS NOT NULL) AND (:prCodPlano > 0)) THEN
    BEGIN
      IF (wWhere <> '') THEN
        wWhere = wWhere||' and ';
      ELSE
        wWhere = wWhere||' where ';

      wWhere = wWhere||'T.BDCODPLACONSCONF  = '||:prCodPlano;
    END

  IF ((:prcodquadro IS NOT NULL) and (:prcodquadro  > 0)) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      ELSE
        wwhere = wwhere||' where ';

      wwhere = wwhere||'T.BDCODQPLACONSCONF  = '||:prcodquadro;
    END

  IF (:prrefini IS NOT NULL) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      ELSE
        wwhere = wwhere||' where ';

      wwhere = wwhere||'T.BDREF Between '||:prrefini||' and '||:prreffin;
    END

  IF (:prtipofolha IS NOT NULL) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      ELSE
        wwhere = wwhere||' where ';

      wwhere = wwhere||'T.BDTIPOFOLHA = '||:prtipofolha;
    END

  IF (:prtotalizador IS NOT NULL) THEN
    BEGIN
      IF (wwhere <> '') THEN
        wwhere = wwhere||' and ';
      ELSE
        wwhere = wwhere||' where ';

      wwhere = wwhere||'T.BDTOTALIZADOR = '||:prtotalizador;
    END

  IF (wwhere <> '') THEN
    wwhere = wwhere||' and QUADRO.bdcodsis = 2';
  ELSE
    wwhere = wwhere||' QUADRO.bdcodsis = 2';

  IF (wwhere <> '') THEN
    wwhere = 'where '||wwhere||' and (T.BDCODCLA in (2,31))';
  ELSE
    wwhere = wwhere||' where (T.BDCODCLA in (2,31))';

  wsql = wsql||wwhere||' order by 1, 3, 4, 7, 9, 10, 6 ';

  /*inicializa variaveis*/
  wcodempanterior = 0;
  wcodcolanterior = 0;
  wcodquadroanterior = 0;
  wordemanterior = 0;
  wordemauxanterior = 0;
  wcodquadroanterior_controle = 0;
  wcodempanterior_controle = 0;
  wcodcolanterior_controle = 0;

  wordemtot = 0;
  wordemjan = 0;
  wordemfev = 0;
  wordemmar = 0;
  wordemabr = 0;
  wordemmai = 0;
  wordemjun = 0;
  wordemjul = 0;
  wordemago = 0;
  wordemset = 0;
  wordemout = 0;
  wordemnov = 0;
  wordemdez = 0;

  FOR EXECUTE STATEMENT wsql
  INTO
    BDCODEMP,
    BDNOMEMP,
    WCODCLA,
    BDCODCOL,
    BDNOMCOL,
    BDREF,
    BDCODQUADRO,
    BDDESCQUADRO,
    BDORDEM,
    BDORDEMAUX,
    BDDESCRICAO,
    BDVALOR
  DO
    BEGIN
      WORDEMAUXATUAL = bdordemaux;

      IF ((wcodempanterior_controle = 0) OR (wcodempanterior_controle <> wcodempanterior)) THEN
        BEGIN
         wordemaux = :bdordem;
         wdescricaoaux = :bddescricao;
 
         bdordem = NULL;
         bddescricao = LPAD(:bdcodemp||' - '||:bdnomemp, 80);
 
         bdregaux = 2;
         bdordemaux = -1;
         SUSPEND;
 
         wcodempanterior_controle = :bdcodemp;
         bdordem = wordemaux;
         bddescricao = wdescricaoaux;
        END

      IF ((wcodquadroanterior_controle = 0) OR (wcodquadroanterior_controle <> wcodquadroanterior) ) THEN
        BEGIN
          wordemaux = :bdordem;
          wdescricaoaux = :bddescricao;
 
          bdordem = NULL;
          bddescricao = :bddescquadro;
 
          bdregaux = 1;
          bdordemaux = -1;
          SUSPEND;
 
          wcodquadroanterior_controle = :bdcodquadro;
          bdordem = wordemaux;
          bddescricao = wdescricaoaux;
        END

      IF ((wcodcolanterior_controle = 0) OR (wcodcolanterior_controle <> wcodcolanterior)) THEN
        BEGIN
          if (:bdcodcol > 0) then
             begin
               wordemaux = :bdordem;
               wdescricaoaux = :bddescricao;
 
               bdregaux = 3;
               bdordem = -1;
               bdordemaux = -1;
               bddescricao = null;
               suspend;
               
               bdordem = -1;
               if (WCODCOLANTERIOR = 0) then
                  bddescricao = :bdcodcol||' - '||:bdnomcol;
               else
                  bddescricao = :wcodcolanterior||' - '||:wnomecolanterior;
 
               bdregaux = 3;
               bdordemaux = -1;
               SUSPEND;

               if (WCODCOLANTERIOR = 0) then
                  wcodcolanterior_controle = :bdcodcol;
               else
                  wcodcolanterior_controle = :wcodcolanterior;

               bdordem = wordemaux;
               bddescricao = wdescricaoaux;
            end

          bdordemaux = wordemauxatual;
        END

      IF ((wordemanterior <> :bdordem) OR (wordemauxanterior <> :bdordemaux) OR (wcodquadroanterior <> :bdcodquadro) OR (wcodempanterior <> :bdcodemp) or (wcodcolanterior <> :bdcodcol)) THEN
        BEGIN
          IF (wordemanterior <> 0) THEN
            BEGIN
              wcodempaux = :bdcodemp;
              wnomeempaux = :bdnomemp;
              wcodcolaux = :bdcodcol;
              wnomecolaux = :bdnomcol;
              wrefaux = :bdref;
              wcodquadroaux = :bdcodquadro;
              wdescquadroaux = :bddescquadro;
              wordemaux = :bdordem;
              wordemaux2 = :bdordemaux;
              wdescricaoaux = :bddescricao;

              bdcodemp = wcodempanterior;
              bdnomemp = wnomeempanterior;
              bdcodcol = wcodcolanterior;
              bdnomcol = wnomecolanterior;
              bdref = wrefanterior;
              bdcodquadro = wcodquadroanterior;
              bddescquadro = wdescquadroanterior;
              bdordem = wordemanterior;
              bdordemaux = wordemauxanterior;
              bddescricao = wdescricaoanterior;

              bdtotal = wordemtot;
              bdjan = wordemjan;
              bdfev = wordemfev;
              bdmar = wordemmar;
              bdabr = wordemabr;
              bdmai = wordemmai;
              bdjun = wordemjun;
              bdjul = wordemjul;
              bdago = wordemago;
              bdset = wordemset;
              bdout = wordemout;
              bdnov = wordemnov;
              bddez = wordemdez;

              bdregaux = 0;

              SUSPEND;

              bdtotal = NULL;
              bdjan = NULL;
              bdfev = NULL;
              bdmar = NULL;
              bdabr = NULL;
              bdmai = NULL;
              bdjun = NULL;
              bdjul = NULL;
              bdago = NULL;
              bdset = NULL;
              bdout = NULL;
              bdnov = NULL;
              bddez = NULL;

              bdcodemp = wcodempaux;
              bdnomemp = wnomeempaux;
              bdcodcol = wcodcolaux;
              bdnomcol = wnomecolaux;
              bdref = wrefaux;
              bdcodquadro = wcodquadroaux;
              bddescquadro = wdescquadroaux;
              bdordem = wordemaux;
              bdordemaux = wordemaux2;
              bddescricao = wdescricaoaux;
            END

          wcodempanterior = :bdcodemp;
          wnomeempanterior = :bdnomemp;
          wcodcolanterior = :bdcodcol;
          wnomecolanterior = :bdnomcol;
          wrefanterior = :bdref;
          wcodquadroanterior = :bdcodquadro;
          wdescquadroanterior = :bddescquadro;
          wordemanterior = :bdordem;
          wordemauxanterior = :bdordemaux;
          wdescricaoanterior = :bddescricao;

          wordemtot = 0;
          wordemjan = 0;
          wordemfev = 0;
          wordemmar = 0;
          wordemabr = 0;
          wordemmai = 0;
          wordemjun = 0;
          wordemjul = 0;
          wordemago = 0;
          wordemset = 0;
          wordemout = 0;
          wordemnov = 0;
          wordemdez = 0;
        END

      wmes = CAST(SUBSTRING(:bdref FROM 5 FOR 2) AS INTEGER);

      wordemtot = wordemtot + :bdvalor;

      IF (wmes = 1) THEN
        wordemjan = :bdvalor;
      ELSE IF (wmes = 2) THEN
        wordemfev = :bdvalor;
      ELSE IF (wmes = 3) THEN
        wordemmar = :bdvalor;
      ELSE IF (wmes = 4) THEN
        wordemabr = :bdvalor;
      ELSE IF (wmes = 5) THEN
        wordemmai = :bdvalor;
      ELSE IF (wmes = 6) THEN
        wordemjun = :bdvalor;
      ELSE IF (wmes = 7) THEN
        wordemjul = :bdvalor;
      ELSE IF (wmes = 8) THEN
        wordemago = :bdvalor;
      ELSE IF (wmes = 9) THEN
        wordemset = :bdvalor;
      ELSE IF (wmes = 10) THEN
        wordemout = :bdvalor;
      ELSE IF (wmes = 11) THEN
        wordemnov = :bdvalor;
      ELSE IF (wmes = 12) THEN
        wordemdez = :bdvalor;
    END

    IF (:bdordem IS NOT NULL) THEN
      BEGIN
        IF (wcodempanterior_controle <> :bdcodemp) THEN
          BEGIN
            wordemaux = :bdordem;
            wdescricaoaux = :bddescricao;

            bdordem = NULL;
            bddescricao = :bdnomemp;

            bdregaux = 2;
            bdordemaux = -1;
            SUSPEND;

            bdordem = wordemaux;
            bddescricao = wdescricaoaux;
          END

        IF (wcodquadroanterior_controle <> :bdcodquadro) THEN
          BEGIN
            wordemaux = :bdordem;
            wdescricaoaux = :bddescricao;

            bdordem = NULL;
            bddescricao = :bddescquadro;

            bdregaux = 1;
            bdordemaux = -1;
            SUSPEND;

            bdordem = wordemaux;
            bddescricao = wdescricaoaux;
          END

      IF (wcodcolanterior_controle <> :bdcodcol) THEN
        BEGIN
            wordemaux = :bdordem;
            wdescricaoaux = :bddescricao;

            bdregaux = 3;
            bdordem = -1;
            bdordemaux = -1;
            bddescricao = null;
            suspend;

            bdordem = -1;
            bddescricao = :bdcodcol||' - '||:bdnomcol;

            bdregaux = 3;
            bdordemaux = -1;
            SUSPEND;

            bdordem = wordemaux;
            bddescricao = wdescricaoaux;
        END

        bdtotal = wordemtot;
        bdjan = wordemjan;
        bdfev = wordemfev;
        bdmar = wordemmar;
        bdabr = wordemabr;
        bdmai = wordemmai;
        bdjun = wordemjun;
        bdjul = wordemjul;
        bdago = wordemago;
        bdset = wordemset;
        bdout = wordemout;
        bdnov = wordemnov;
        bddez = wordemdez;

        bdregaux = 0;
        bdordemaux = wordemauxatual;

        SUSPEND;
      END
end^

create or alter procedure SP_VRH_PROVDESC_CONS_ANUAL_CONF (
    PRCODEMP varchar(1000),
    PRCODCOL varchar(1000),
    PRREFINI integer,
    PRREFFIN integer,
    PRTIPOFOLHA integer,
    PRTOTALIZADOR integer,
    PRPROVDESC integer,
    PRCODCLA varchar(1000))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDTIPOCODVER integer,
    BDDESCRICAO varchar(152),
    BDVALOR numeric(15,6))
as
declare variable WSQL varchar(32000);
declare variable WTOTALIZADOR varchar(20);
declare variable WCODVER integer;
declare variable WDESCVER varchar(40);
declare variable WFILTROCOL varchar(1000);
declare variable WFILTROTERC varchar(1000);
declare variable WFILTROPROVDESC varchar(40);
declare variable WWHERE varchar(6);
begin
/*
PRTIPOFOLHA - 0 = Folha normal
              1 = Ferias
              2 = Adiantamento de 13
              3 = 13 salario
              4 = Complemento de 13
              5 = Adiantamento salarial
              6 = Folha complementar
              7 = Folha avulsa
*/
/*
PRTOTALIZADOR - 0 = Empresa
                1 = Colaborador
*/
/*
PRPROVDESC - 0 = Provento
             1 = Desconto
             2 = Informativo Provento
             3 = Informativo Desconto
             4 = Não faz filtro por tipo
*/

  WTOTALIZADOR = 'null as BDCODCOL,';
  if (prtotalizador = 1) then
     WTOTALIZADOR = 'COLCON.BDCODCOL,';

  wfiltrocol = 'null';
  if (prcodcol <> '') then
     wfiltrocol = '''colcon.bdcodcol' || prcodcol || '''';

  wfiltroterc = 'null';
  if (prcodcol <> '') then
     wfiltroterc = '''colcon.bdcodter' || prcodcol || '''';

  if (PRPROVDESC = 4) then
     begin
       wfiltroprovdesc = '';
     end
  else
     begin
       wfiltroprovdesc = 'verbaref.bdtipocodver = ' || PRPROVDESC;
     end

  if ((prcodcla is not null) and (wfiltroprovdesc <> '')) then
     prcodcla = ' and ' || prcodcla || ' ';
  else
  if ((prcodcla is not null) and (prtipofolha not in (0,6)) and (wfiltroprovdesc = '')) then
     prcodcla = ' and ' || prcodcla || ' ';
  else
  if ((prcodcla is not null) and (prtipofolha in (0,6)) and (wfiltroprovdesc = '')) then
     prcodcla = prcodcla || ' ';
  else
     prcodcla = '';

  if (PRPROVDESC = 4 and prcodcla = '') then
     begin
       wwhere = '';
     end
  else
     begin
       wwhere = 'where ';
     end

  if (prtipofolha = 0) then  /*Folha normal*/
     begin
       wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREFFN, COLCON.BDCODVER, VERBAREF.bdtipocodver, VERBAREF.BDDESCVER, SUM(COLCON.BDVALVFN) BDVALOR ' ||
              'from VRHF_SP_TVERBAFN(''' || prcodemp || ''', ' || wfiltrocol || ', ' || prrefini || ',' || prreffin || ', 0) COLCON ' ||
              'left join VW_TVERBAS_REF VERBAREF on (verbaref.bdcodver = COLCON.bdcodver) ' ||
              'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
              wwhere || wfiltroprovdesc || ' ' || prcodcla ||
              'GROUP BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFFN, COLCON.BDCODVER, VERBAREF.bdtipocodver, VERBAREF.BDDESCVER ' ||

              'union all ' ||

              'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREFFN, COLCON.BDCODVER, VERBAREF.bdtipocodver, VERBAREF.BDDESCVER, ' ||
              'case when coalesce(sum(colcon.bdprovento), 0) > 0 then coalesce(sum(colcon.bdprovento), 0) else coalesce(sum(colcon.bddesconto), 0) end BDVALOR ' ||
              'from VRHF_SP_VERBAS_FOL_NORMAL_AUT(''' || prcodemp || ''', '''', ' || wfiltroterc || ', 2, ' || prrefini || ',' || prreffin || ', 0, '''', '''') COLCON ' ||
              'left join VW_TVERBAS_REF VERBAREF on (verbaref.bdcodver = COLCON.bdcodver)' ||
              'left join VW_VRH_BASE_TTERC_VINC vinc on (vinc.bdcodcol = colcon.bdcodcol) ' ||
              wwhere || wfiltroprovdesc || ' ' || prcodcla ||
              'GROUP BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFFN, COLCON.BDCODVER, VERBAREF.bdtipocodver, VERBAREF.BDDESCVER ' ||
              'ORDER BY 1,2,3,4';
     end
  else
  if (prtipofolha = 1) then  /*Ferias*/
     begin
       wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREFFE BDREFFN, COLCON.BDCODVER, VERBAREF.bdtipocodver, VERBAREF.BDDESCVER, SUM(COLCON.BDVALVRFE) BDVALOR ' ||
              'from VRHF_EMP_TVERBARFE COLCON ' ||
              'left join VW_TVERBAS_REF VERBAREF on (verbaref.bdcodver = COLCON.bdcodver)' ||
              'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
              'where ';
       if (PRPROVDESC <> 4) then
          wsql =  wsql || wfiltroprovdesc || ' and ' || prcodemp || prcodcla || ' and ';
       else
          wsql =  wsql || prcodemp || prcodcla || ' and ';

       if (prcodcol <> '') then
          wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';

       wsql = wsql || 'COLCON.bdreffe between ' || prrefini || ' and ' || prreffin || ' ' ||
                      'GROUP BY COLCON.BDCODEMP, BDCODCOL, BDREFFN, COLCON.BDCODVER, VERBAREF.bdtipocodver, VERBAREF.BDDESCVER ' ||
                      'ORDER BY COLCON.BDCODEMP, BDCODCOL, BDREFFN, COLCON.BDCODVER';
     end
  else
  if (prtipofolha = 2) then  /*Adiantamento de 13*/
     begin
       wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREFA13 BDREFFN, COLCON.BDCODVER, VERBAREF.bdtipocodver, VERBAREF.BDDESCVER, SUM(COLCON.BDVALVA13) BDVALOR ' ||
              'from VRHF_EMP_TVERBAA13 COLCON ' ||
              'left join VW_TVERBAS_REF VERBAREF on (verbaref.bdcodver = COLCON.bdcodver)' ||
              'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
              'where ';
       if (PRPROVDESC <> 4) then
          wsql =  wsql || wfiltroprovdesc || ' and ' || prcodemp || prcodcla || ' and ';
       else
          wsql =  wsql || prcodemp || prcodcla || ' and ';

       if (prcodcol <> '') then
          wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';

       wsql = wsql || 'COLCON.BDREFA13 between ' || prrefini || ' and ' || prreffin || ' ' ||
                      'GROUP BY COLCON.BDCODEMP, BDCODCOL, BDREFFN, COLCON.BDCODVER, VERBAREF.bdtipocodver, VERBAREF.BDDESCVER ' ||
                      'ORDER BY COLCON.BDCODEMP, BDCODCOL, BDREFFN, COLCON.BDCODVER';
     end
  else
  if (prtipofolha = 3) then  /*13 salario*/
     begin
       wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREF13 BDREFFN, COLCON.BDCODVER, VERBAREF.bdtipocodver, VERBAREF.BDDESCVER, SUM(COLCON.BDVALV13) BDVALOR ' ||
              'from VRHF_EMP_TVERBA13 COLCON ' ||
              'left join VW_TVERBAS_REF VERBAREF on (verbaref.bdcodver = COLCON.bdcodver)' ||
              'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
              'where ';
       if (PRPROVDESC <> 4) then
          wsql =  wsql || wfiltroprovdesc || ' and ' || prcodemp || prcodcla || ' and ';
       else
          wsql =  wsql || prcodemp || prcodcla || ' and ';

       if (prcodcol <> '') then
          wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';

       wsql = wsql || 'COLCON.BDREF13 between ' || prrefini || ' and ' || prreffin || ' ' ||
                      'GROUP BY COLCON.BDCODEMP, BDCODCOL, BDREFFN, COLCON.BDCODVER, VERBAREF.bdtipocodver, VERBAREF.BDDESCVER ' ||
                      'ORDER BY COLCON.BDCODEMP, BDCODCOL, BDREFFN, COLCON.BDCODVER';
     end
  else
  if (prtipofolha = 4) then  /*Complemento de 13*/
     begin
       wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREFC13 BDREFFN, COLCON.BDCODVER, VERBAREF.bdtipocodver, VERBAREF.BDDESCVER, SUM(COLCON.BDVALVC13) BDVALOR ' ||
              'from VRHF_EMP_TVERBAC13 COLCON ' ||
              'left join VW_TVERBAS_REF VERBAREF on (verbaref.bdcodver = COLCON.bdcodver)' ||
              'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
              'where ';
       if (PRPROVDESC <> 4) then
          wsql =  wsql || wfiltroprovdesc || ' and ' || prcodemp || prcodcla || ' and ';
       else
          wsql =  wsql || prcodemp || prcodcla || ' and ';

       if (prcodcol <> '') then
          wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';

       wsql = wsql || 'COLCON.BDREFC13 between ' || prrefini || ' and ' || prreffin || ' ' ||
                      'GROUP BY COLCON.BDCODEMP, BDCODCOL, BDREFFN, COLCON.BDCODVER, VERBAREF.bdtipocodver, VERBAREF.BDDESCVER ' ||
                      'ORDER BY COLCON.BDCODEMP, BDCODCOL, BDREFFN, COLCON.BDCODVER';
     end
  else
  if (prtipofolha = 5) then  /*Adiantamento salarial*/
     begin
       wsql = 'select BDCODEMP, bdcodcol, BDREFFN, BDCODVER,bdtipocodver, BDDESCVER, SUM(BDVALOR) BDVALOR from (' ||
              'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' (SELECT bdaaaamm FROM aaaamm(colcon.bddataad)) BDREFFN, COLCON.BDCODVER, VERBAREF.bdtipocodver, VERBAREF.BDDESCVER, COLCON.BDVALVAD BDVALOR ' ||
              'from VRHF_EMP_TVERBAAD COLCON ' ||
              'left join VW_TVERBAS_REF VERBAREF on (verbaref.bdcodver = COLCON.bdcodver)' ||
              'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
              'where ';

       if (PRPROVDESC <> 4) then
          wsql =  wsql || wfiltroprovdesc || ' and ' || prcodemp || prcodcla || ' and ';
       else
          wsql =  wsql || prcodemp || prcodcla || ' and ';

       if (prcodcol <> '') then
          wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';

       wsql = wsql || '(SELECT bdaaaamm FROM aaaamm(colcon.bddataad)) >= ' || prrefini || ' and (SELECT bdaaaamm FROM aaaamm(colcon.bddataad)) <= ' || prreffin || ') ' ||
                      'GROUP BY BDCODEMP, BDCODCOL, BDREFFN, BDCODVER, bdtipocodver, BDDESCVER ' ||
                      'ORDER BY BDCODEMP, BDCODCOL, BDREFFN, BDCODVER, BDDESCVER';
     end
  else
  if (prtipofolha = 6) then  /*Folha complementar*/
     begin
       wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREFFN, COLCON.BDCODVER, VERBAREF.bdtipocodver, VERBAREF.BDDESCVER, SUM(COLCON.BDVALVFC) BDVALOR ' ||
              'from VRHF_SP_TVERBAFC(''' || prcodemp || ''', ' || wfiltrocol || ', ' || prrefini || ',' || prreffin || ', null, null, 0) COLCON ' ||
              'left join VW_TVERBAS_REF VERBAREF on (verbaref.bdcodver = COLCON.bdcodver)' ||
              'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
              wwhere || wfiltroprovdesc || ' ' || prcodcla ||
              'GROUP BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFFN, COLCON.BDCODVER, VERBAREF.bdtipocodver, VERBAREF.BDDESCVER ' ||
              'ORDER BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFFN, COLCON.BDCODVER';
     end
  else
  if (prtipofolha = 7) then  /*Complemento de 13*/
     begin
       wsql = 'select BDCODEMP, bdcodcol, BDREFFN, BDCODVER, BDTIPOCODVER,  BDDESCVER, SUM(BDVALOR) BDVALOR from (' ||
              'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' (SELECT bdaaaamm FROM aaaamm(colcon.bddatafa)) BDREFFN, COLCON.BDCODVER, VERBAREF.bdtipocodver, VERBAREF.BDDESCVER, COLCON.BDVALVFA BDVALOR ' ||
              'from VRHF_EMP_TVERBAFA COLCON ' ||
              'left join VW_TVERBAS_REF VERBAREF on (verbaref.bdcodver = COLCON.bdcodver)' ||
              'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
              'where ';

       if (PRPROVDESC <> 4) then
          wsql =  wsql || wfiltroprovdesc || ' and ' || prcodemp || prcodcla || ' and ';
       else
          wsql =  wsql || prcodemp || prcodcla || ' and ';

       if (prcodcol <> '') then
          wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';

       wsql = wsql || '(SELECT bdaaaamm FROM aaaamm(colcon.bddatafa)) >= ' || prrefini || ' and (SELECT bdaaaamm FROM aaaamm(colcon.bddatafa)) <= ' || prreffin || ') ' ||
                      'GROUP BY BDCODEMP, BDCODCOL, BDREFFN, BDCODVER, BDTIPOCODVER, BDDESCVER ' ||
                      'ORDER BY BDCODEMP, BDCODCOL, BDREFFN, BDCODVER, BDDESCVER';
     end

  FOR EXECUTE STATEMENT wsql into
      :bdcodemp,
      :bdcodcol,
      :bdref,
      :wcodver,
      :bdtipocodver,
      :wdescver,
      :bdvalor do
      begin
        bddescricao = :wcodver||' - '||:wdescver;
        suspend;
      end
end^

CREATE OR ALTER procedure SP_VRH_LIQUIDO_CONS_ANUAL_CONF (
    PRCODEMP varchar(1000),
    PRCODCOL varchar(1000),
    PRREFINI integer,
    PRREFFIN integer,
    PRTIPOFOLHA integer,
    PRTOTALIZADOR integer,
    PRDESCRICAO varchar(152),
    PRCODCLA varchar(1000))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDDESCRICAO varchar(152),
    BDVALOR numeric(15,6))
as
declare variable WTOTALIZADOR varchar(20);
declare variable WSQL varchar(32000);
declare variable WFILTROCOL varchar(100);
declare variable WFILTROTERC varchar(100);
begin
/*
PRTIPOFOLHA - 0 = Folha normal
              1 = Ferias
              2 = Adiantamento de 13
              3 = 13 salario
              4 = Complemento de 13
              5 = Adiantamento salarial
              6 = Folha complementar
              7 = Folha avulsa
*/
/*
PRTOTALIZADOR - 0 = Empresa
                1 = Colaborador
*/

  WTOTALIZADOR = 'null as BDCODCOL,';
  if (prtotalizador = 1) then
     WTOTALIZADOR = 'COLCON.BDCODCOL,';

  wfiltrocol = 'null';
  if (prcodcol <> '') then
     wfiltrocol = '''colcon.bdcodcol' || prcodcol || '''';

  wfiltroterc = 'null';
  if (prcodcol <> '') then
     wfiltroterc = '''colcon.bdcodter' || prcodcol || '''';

  if (prcodcla <> '') then
     prcodcla = prcodcla || ' ';

  if (prtipofolha = 0) then  /*Folha normal*/
     begin
       wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREFFN, SUM(COLCON.BDLIQUIDOFN) AS VALOR, ''' || prdescricao || ''' DESCRICAO ' ||
              'from VRHF_SP_TFOLHA_NORMAL(''' || prcodemp || ''', ' || wfiltrocol || ', ' || prrefini || ',' || prreffin || ', 0) COLCON ' ||
              'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ';

              if (prcodcla <> '') then
                 wsql = wsql ||' where ' || prcodcla;

              wsql = wsql ||
              'GROUP BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFFN, DESCRICAO ' ||
              'union all ' ||

              'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREFFN, SUM(COLCON.BDPROVENTO - COLCON.BDDESCONTO) AS VALOR, ''' || prdescricao || ''' DESCRICAO ' ||
              'from VRHF_SP_VERBAS_FOL_NORMAL_AUT(''' || prcodemp || ''', '''', ' || wfiltroterc || ', 2, ' || prrefini || ',' || prreffin || ', 0, '''', '''') COLCON ' ||
              'left join VW_VRH_BASE_TTERC_VINC vinc on (vinc.bdcodcol = colcon.bdcodcol) ';

              if (prcodcla <> '') then
                 wsql = wsql ||' where ' || prcodcla;

              wsql = wsql ||
              'GROUP BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFFN, DESCRICAO ' ||
              'ORDER BY 1,2,3,4';

        if (prtotalizador = 0) then
           begin
             wsql = 'select bdcodemp, bdcodcol, bdreffn, sum(valor), descricao from (' || wsql || ') group by bdcodemp, bdcodcol, bdreffn, descricao';
           end
     end
  else
  if (prtipofolha = 1) then  /*Ferias*/
     begin
       wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' ' || PRREFINI || ' BDREFFN, SUM((FER.BDLIQUIDO / cast(FER.BDQTDGOZOFE as integer)) * COLCON.BDDIASFERFE), ''' || prdescricao || ''' DESCRICAO ' ||
              'from VRH_EMP_TFERIASREF COLCON ' ||
              'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
              'left join VRH_EMP_TFERIAS FER on (FER.BDCODEMP = COLCON.BDCODEMP AND FER.BDCODCOL = COLCON.BDCODCOL AND FER.BDINIPERAQUISFE = COLCON.BDINIPERAQUISFE AND FER.BDCODFE = COLCON.BDCODFE) ' ||
              'where ' || prcodemp || ' and ';

       if (prcodcla <> '') then
          wsql = wsql || prcodcla || ' and ';

       if (prcodcol <> '') then
          wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';

       wsql = wsql || '(COLCON.BDREFFE between ' || prrefini || ' and ' || prreffin || ') ' ||
                      'GROUP BY COLCON.BDCODEMP, BDCODCOL, BDREFFN, DESCRICAO ' ||
                      'ORDER BY COLCON.BDCODEMP, BDCODCOL, BDREFFN';
     end
  else
  if (prtipofolha = 2) then  /*Adiantamento de 13*/
     begin
       wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREFA13, SUM(COLCON.BDLIQUIDO), ''' || prdescricao || ''' DESCRICAO ' ||
              'from VRHF_EMP_TA13SAL COLCON ' ||
              'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
              'where ' || prcodemp || ' and ';

       if (prcodcla <> '') then
          wsql = wsql || prcodcla || ' and ';

       if (prcodcol <> '') then
          wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';

       wsql = wsql || 'COLCON.BDREFA13 between ' || prrefini || ' and ' || prreffin || ' ' ||
                      'GROUP BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFA13, DESCRICAO ' ||
                      'ORDER BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFA13';
     end
  else
  if (prtipofolha = 3) then  /*13 salario*/
     begin
       wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREF13, SUM(COLCON.BDLIQUIDO), ''' || prdescricao || ''' DESCRICAO ' ||
              'from VRHF_EMP_T13SAL COLCON ' ||
              'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
              'where ' || prcodemp || ' and ';

       if (prcodcla <> '') then
          wsql = wsql || prcodcla || ' and ';

       if (prcodcol <> '') then
          wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';

       wsql = wsql || 'COLCON.BDREF13 between ' || prrefini || ' and ' || prreffin || ' ' ||
                      'GROUP BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREF13, DESCRICAO ' ||
                      'ORDER BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREF13';
     end
  else
  if (prtipofolha = 4) then  /*Complemento de 13*/
     begin
       wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREFC13, SUM(COLCON.BDLIQUIDO), ''' || prdescricao || ''' DESCRICAO ' ||
              'from VRHF_EMP_TC13SAL COLCON ' ||
              'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
              'where ' || prcodemp || ' and ';

       if (prcodcla <> '') then
          wsql = wsql || prcodcla || ' and ';

       if (prcodcol <> '') then
          wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';

       wsql = wsql || 'COLCON.BDREFC13 between ' || prrefini || ' and ' || prreffin || ' ' ||
                      'GROUP BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFC13, DESCRICAO ' ||
                      'ORDER BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFC13';
     end
  else
  if (prtipofolha = 5) then  /*Adiantamento salarial*/
     begin
       wsql = 'select BDCODEMP, bdcodcol, BDREFFN, SUM(BDVALOR) BDVALOR, BDDESCRICAO from (' ||
              'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' (SELECT bdaaaamm FROM aaaamm(colcon.bddataad)) BDREFFN, COLCON.BDLIQUIDO BDVALOR, ''' || prdescricao || ''' BDDESCRICAO ' ||
              'from VRHF_EMP_TADSAL COLCON ' ||
              'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
              'where ' || prcodemp || ' and ';

       if (prcodcla <> '') then
          wsql = wsql || prcodcla || ' and ';

       if (prcodcol <> '') then
          wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';

       wsql = wsql || '(SELECT bdaaaamm FROM aaaamm(colcon.bddataad)) >= ' || prrefini || ' and (SELECT bdaaaamm FROM aaaamm(colcon.bddataad)) <= ' || prreffin || ') ' ||
                      'GROUP BY BDCODEMP, BDCODCOL, BDREFFN, BDDESCRICAO ' ||
                      'ORDER BY BDCODEMP, BDCODCOL, BDREFFN';
     end
  else
  if (prtipofolha = 6) then  /*Folha complementar*/
     begin
       wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREFFN, SUM(COLCON.BDLIQUIDOFC), ''' || prdescricao || ''' DESCRICAO ' ||
              'from VRHF_SP_TFOLHACOMP(''' || prcodemp || ''', ' || wfiltrocol || ', ' || prrefini || ',' || prreffin || ', null, null, 0) COLCON ' ||
              'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ';

              if (prcodcla <> '') then
                 wsql = wsql ||' where ' || prcodcla;

              wsql = wsql ||
              'GROUP BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFFN, DESCRICAO ' ||
              'ORDER BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFFN';
     end
  else
  if (prtipofolha = 7) then  /*Folha avulsa*/
     begin
       wsql = 'select BDCODEMP, bdcodcol, BDREFFN, SUM(BDVALOR) BDVALOR, BDDESCRICAO from (' ||
              'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' (SELECT bdaaaamm FROM aaaamm(colcon.bddatafa)) BDREFFN, COLCON.BDLIQUIDO BDVALOR, ''' || prdescricao || ''' BDDESCRICAO ' ||
              'from VRHF_EMP_TFOLHAAVULSA COLCON ' ||
              'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
              'where ' || prcodemp || ' and ';

       if (prcodcla <> '') then
          wsql = wsql || prcodcla || ' and ';

       if (prcodcol <> '') then
          wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';

       wsql = wsql || '(SELECT bdaaaamm FROM aaaamm(colcon.bddatafa)) >= ' || prrefini || ' and (SELECT bdaaaamm FROM aaaamm(colcon.bddatafa)) <= ' || prreffin || ') ' ||
                      'GROUP BY BDCODEMP, BDCODCOL, BDREFFN, BDDESCRICAO ' ||
                      'ORDER BY BDCODEMP, BDCODCOL, BDREFFN';
     end

  FOR EXECUTE STATEMENT wsql into
      :bdcodemp,
      :bdcodcol,
      :bdref,
      :bdvalor,
      :bddescricao do
     suspend;
end^

CREATE OR ALTER procedure SP_VRH_BASES_CONS_ANUAL_CONF (
    PRCODEMP varchar(1000),
    PRCODCOL varchar(1000),
    PRREFINI integer,
    PRREFFIN integer,
    PRTIPOFOLHA integer,
    PRTOTALIZADOR integer,
    PRCODCLA varchar(1000))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDVALOR numeric(15,6),
    BDDESCRICAO varchar(152),
    BDINDEX integer)
as
declare variable WTOTALIZADOR varchar(20);
declare variable WFILTROCOL varchar(100);
declare variable WSQL varchar(32000);
declare variable WBASEFGTS numeric(15,6);
declare variable WBASEINSS numeric(15,6);
declare variable WBASEIRRF numeric(15,6);
declare variable WSALBASE numeric(15,6);
declare variable WVALORINSS numeric(15,6);
declare variable WVALORFGTS numeric(15,6);
declare variable WVALORIRRF numeric(15,6);
declare variable WBASESALFAM numeric(15,6);
declare variable WVALORSALFAM numeric(15,6);
declare variable WFILTROTERC varchar(100);
declare variable WSQLCOL varchar(32000);
begin
/*
PRTIPOFOLHA - 0 = Folha normal
              1 = Ferias
              2 = Adiantamento de 13
              3 = 13 salario
              4 = Complemento de 13
              5 = Adiantamento salarial
              6 = Folha complementar
              7 = Folha avulsa
*/
/*
PRTOTALIZADOR - 0 = Empresa
                1 = Colaborador
*/

  WTOTALIZADOR = 'null as BDCODCOL,';
  if (prtotalizador = 1) then
     WTOTALIZADOR = 'COLCON.BDCODCOL,';

  wfiltrocol = 'null';
  if (prcodcol <> '') then
     wfiltrocol = '''colcon.bdcodcol' || prcodcol || '''';

  wfiltroterc = 'null';
  if (prcodcol <> '') then
     wfiltroterc = '''colcon.bdcodter' || prcodcol || '''';

  if (prcodcla <> '') then
     prcodcla = prcodcla || ' ';

  bdindex = 0;

       if (prtipofolha = 0) then  /*Folha normal*/
          begin
            wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREFFN, SUM(COLCON.BDBFGTSFN + COLCON.BDBFGTS13FN + COLCON.BDBFGTSFEFN) as BDBFGTS, SUM(COLCON.BDBINSSFN + COLCON.BDBINSS13FN + COLCON.BDBINSSFEFOLFN) as BDBINSS, ' ||
                   'SUM(COLCON.BDBIRRFFN + COLCON.BDBIRRF13FN) as BDBIRRF, SUM(COLCON.BDSALBASEFN) as BDSALBASE, SUM(COLCON.BDINSSFN + COLCON.BDINSS13FN + COLCON.BDINSSFEFOLFN) as BDINSS, SUM(COLCON.BDFGTSFN + COLCON.BDFGTS13FN + COLCON.BDFGTSFEFN) as BDFGTS, SUM(COLCON.BDIRRFFN) as BDIRRF, ' ||
                   'SUM(COLCON.BDBSALFAMFN) as BDBSALFAM, SUM(COLCON.BDSALFAMFN) as BDSALFAMFN ' ||
                   'from VRHF_SP_TFOLHA_NORMAL(''' || prcodemp || ''', ' || wfiltrocol || ', ' || prrefini || ',' || prreffin || ', 1) COLCON ' ||
                   'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ';
     
                   if (prcodcla <> '') then
                      wsql = wsql ||' where ' || prcodcla;
     
                   wsql = wsql ||
                   'GROUP BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFFN ' ||
     
                   'union all ' ||
     
                   'select BDCODEMP, BDCODCOL, BDREFFN, sum(BDBFGTS + BDBFGTS13 + BDBFGTSFEFOL) as BDBFGTS, ' ||
                   'sum(BDBINSS + BDBINSS13 + BDBINSSFEFOL) as BDBINSS, sum(BDBIRRF) as BDBIRRF, sum(BDSALBASE) as BDSALBASE, sum(BDINSSFN + BDINSS13FN + BDVINSSFEFOL) as BDINSS, ' ||
                   'sum(BDFGTS + BDVFGTS13 + BDVFGTSFEFOL) as BDFGTS, sum(BDIRRF) as BDIRRF, sum(BDBSALFAM) as BDBSALFAM, sum(BDSALFAMFN) as BDSALFAMFN ' ||
                   'from ( ' ||
                   'select DISTINCT COLCON.BDCODEMP, COLCON.BDCODCOL, COLCON.BDREFFN, COLCON.BDBFGTS, COLCON.BDBFGTS13, COLCON.BDBFGTSFEFOL, ' ||
                   'COLCON.BDBINSS, COLCON.BDBINSS13, COLCON.BDBINSSFEFOL, COLCON.BDBIRRF, ' ||
                   'COLCON.BDSALBASE, COLCON.BDINSSFN, COLCON.BDINSS13FN, COLCON.BDVINSSFEFOL, ' ||
                   'COLCON.BDFGTS, COLCON.BDVFGTS13, COLCON.BDVFGTSFEFOL, COLCON.BDIRRF, COLCON.BDBSALFAM, ' ||
                   '0 AS BDSALFAMFN ' ||
                   'from VRHF_SP_VERBAS_FOL_NORMAL_AUT(''' || prcodemp || ''', '''', ' || wfiltroterc || ', 2, ' || prrefini || ',' || prreffin || ', 0, '''', '''') COLCON ' ||
                   'left join VW_VRH_BASE_TTERC_VINC vinc on (vinc.bdcodcol = colcon.bdcodcol) ';
     
                   if (prcodcla <> '') then
                      wsql = wsql ||' where ' || prcodcla;
     
                   wsql = wsql ||
                   ') GROUP BY BDCODEMP, BDCODCOL, BDREFFN ';
     
            if (prtotalizador = 0) then
               begin
                 wsql = 'select bdcodemp, bdcodcol, bdreffn, sum(BDBFGTS), sum(BDBINSS), sum(BDBIRRF), sum(BDSALBASE), sum(BDINSS), sum(BDFGTS), sum(BDIRRF), sum(BDBSALFAM), sum(BDSALFAMFN) from (' || wsql ||
                        ') group by bdcodemp, bdcodcol, bdreffn';
               end
          end
       else
       if (prtipofolha = 1) then  /*Férias*/
          begin
            wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' ' || PRREFINI || 'PRREFFE, SUM(COLCON.BDBASEFGTSRFE), SUM(COLCON.BDBASEINSSRFE), ' ||
                   'SUM(COLCON.BDBASEIRRFE), FER.BDSALBASEFE, SUM(COLCON.BDVALORINSSRFE), SUM(COLCON.BDVALORFGTSRFE), SUM(COLCON.BDVALORIRRFE), ' ||
                   'SUM(FER.BDBSALFAMFE), SUM(FER.BDSALFAMFE) ' ||
                   'from VRH_EMP_TFERIASREF COLCON ' ||
                   'left join VRH_EMP_TFERIAS FER on (FER.BDCODEMP = COLCON.BDCODEMP AND FER.BDCODCOL = COLCON.BDCODCOL AND FER.BDINIPERAQUISFE = COLCON.BDINIPERAQUISFE AND FER.BDCODFE = COLCON.BDCODFE) ' ||
                   'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
                   'where ' || prcodemp || ' and ';
     
            if (prcodcla <> '') then
               wsql = wsql || prcodcla || ' and ';
     
            if (prcodcol <> '') then
               wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';
     
            wsql = wsql || '(COLCON.BDREFFE between ' || prrefini || ' and ' || prreffin || ') ' ||
                           'GROUP BY COLCON.BDCODEMP, BDCODCOL, PRREFFE, FER.BDSALBASEFE ' ||
                           'ORDER BY COLCON.BDCODEMP, BDCODCOL, PRREFFE';
          end
       else
       if (prtipofolha = 2) then  /*Adiantamento de 13º*/
          begin
            wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREFA13, SUM(COLCON.BDBASEFGTSA13), SUM(0) AS BASEINSS, ' ||
                   'SUM(COLCON.BDBASEIRA13), SUM(COLCON.BDSALBASEA13), SUM(0) VALORINSS, SUM(COLCON.BDFGTSA13), SUM(COLCON.BDVALORIRA13), ' ||
                   'SUM(COLCON.BDBSALFAMA13), SUM(COLCON.BDSALFAMA13) ' ||
                   'from VRHF_EMP_TA13SAL COLCON ' ||
                   'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
                   'where ' || prcodemp || ' and ';
     
            if (prcodcla <> '') then
               wsql = wsql || prcodcla || ' and ';
     
            if (prcodcol <> '') then
               wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';
     
            wsql = wsql || 'COLCON.BDREFA13 between ' || prrefini || ' and ' || prreffin || ' ' ||
                           'GROUP BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFA13 ' ||
                           'ORDER BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFA13';
          end
       else
       if (prtipofolha = 3) then  /*13º salário*/
          begin
            wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREF13, SUM(COLCON.BDBASEFGTS13), SUM(COLCON.BDBASEINSS13), ' ||
                   'SUM(COLCON.BDBASEIR13), SUM(COLCON.BDSALBASE13), SUM(COLCON.BDVALORINSS13), SUM(COLCON.BDFGTS13), SUM(COLCON.BDVALORIR13), ' ||
                   'SUM(COLCON.BDBSALFAM13), SUM(COLCON.BDSALFAM13) ' ||
                   'from VRHF_EMP_T13SAL COLCON ' ||
                   'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
                   'where ' || prcodemp || ' and ';
     
            if (prcodcla <> '') then
               wsql = wsql || prcodcla || ' and ';
     
            if (prcodcol <> '') then
               wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';
     
            wsql = wsql || 'COLCON.BDREF13 between ' || prrefini || ' and ' || prreffin || ' ' ||
                           'GROUP BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREF13 ' ||
                           'ORDER BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREF13';
          end
       else
       if (prtipofolha = 4) then  /*Complemento de 13º*/
          begin
            wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREFC13, SUM(COLCON.BDBASEFGTSC13), SUM(COLCON.BDBASEINSSC13), ' ||
                   'SUM(COLCON.BDBASEIRC13), SUM(COLCON.BDSALBASEC13), SUM(COLCON.BDVALORINSSC13), SUM(COLCON.BDFGTSC13), SUM(COLCON.BDVALORIRC13), ' ||
                   'SUM(COLCON.BDBSALFAMC13), SUM(COLCON.BDSALFAMC13) ' ||
                   'from VRHF_EMP_TC13SAL COLCON ' ||
                   'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
                   'where ' || prcodemp || ' and ';
     
            if (prcodcla <> '') then
               wsql = wsql || prcodcla || ' and ';
     
            if (prcodcol <> '') then
               wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';
     
            wsql = wsql || 'COLCON.BDREFC13 between ' || prrefini || ' and ' || prreffin || ' ' ||
                           'GROUP BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFC13 ' ||
                           'ORDER BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFC13';
          end
       else
       if (prtipofolha = 5) then  /*Adiantamento salarial*/
          begin
            wsql = 'select BDCODEMP, bdcodcol, BDREFFN, SUM(0), SUM(0), ' ||
                   'SUM(BDBASEIRAD), SUM(BDSALBASEAD), SUM(0), SUM(0), SUM(BDVALORIRAD), SUM(0), SUM(0) from (' ||
                   'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' (SELECT bdaaaamm FROM aaaamm(colcon.bddataad)) BDREFFN, COLCON.BDBASEIRAD, COLCON.BDVALORIRAD, COLCON.BDSALBASEAD ' ||
                   'from VRHF_EMP_TADSAL COLCON ' ||
                   'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
                   'where ' || prcodemp || ' and ';
     
            if (prcodcla <> '') then
               wsql = wsql || prcodcla || ' and ';
     
            if (prcodcol <> '') then
               wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';
     
            wsql = wsql || '(SELECT bdaaaamm FROM aaaamm(colcon.bddataad)) >= ' || prrefini || ' and (SELECT bdaaaamm FROM aaaamm(colcon.bddataad)) <= ' || prreffin || ') ' ||
                           'GROUP BY BDCODEMP, BDCODCOL, BDREFFN ' ||
                           'ORDER BY BDCODEMP, BDCODCOL, BDREFFN';
          end
       else
       if (prtipofolha = 6) then  /*Folha complementar*/
          begin
            wsql = 'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' COLCON.BDREFFC, SUM(COLCON.BDBFGTSFC + COLCON.BDBFGTS13FC + COLCON.BDBFGTSFEFC), SUM(COLCON.BDBINSSFC + COLCON.BDBINSS13FC + COLCON.BDBINSSFEFOLFC), ' ||
                   'SUM(COLCON.BDBIRRFFC + COLCON.BDBIRRF13FC), SUM(COLCON.BDSALBASEFC), SUM(COLCON.BDINSSFC + COLCON.BDINSS13FC + COLCON.BDINSSFEFOLFC), SUM(COLCON.BDFGTSFC + COLCON.BDFGTS13FC + COLCON.BDFGTSFEFC), SUM(COLCON.BDIRRFFC), ' ||
                   'SUM(COLCON.BDBSALFAMFC), SUM(COLCON.BDSALFAMFC) ' ||
                   'from VRHF_SP_TFOLHACOMP(''' || prcodemp || ''', ' || wfiltrocol || ', ' || prrefini || ',' || prreffin || ', null, null, 0) COLCON ' ||
                   'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ';
     
                   if (prcodcla <> '') then
                      wsql = wsql ||' where ' || prcodcla;
     
                   wsql = wsql ||
                   'GROUP BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFFC ' ||
                   'ORDER BY COLCON.BDCODEMP, BDCODCOL, COLCON.BDREFFC';
          end
       else
       if (prtipofolha = 7) then  /*Folha avulsa*/
          begin
            wsql = 'select BDCODEMP, bdcodcol, BDREFFN, SUM(BDBFGTSFA), SUM(BDBINSSFA), ' ||
                   'SUM(BDBIRRFFA), SUM(BDSALBASEFA), SUM(BDBINSSFA), SUM(BDFGTSFA), SUM(BDIRRFFA), ' ||
                   'SUM(BDBSALFAMFA), SUM(BDSALFAMFA) from (' ||
                   'select COLCON.BDCODEMP, ' || WTOTALIZADOR || ' (SELECT bdaaaamm FROM aaaamm(colcon.bddatafa)) BDREFFN, COLCON.BDBFGTSFA, COLCON.BDFGTSFA, ' ||
                   '       COLCON.BDBINSSFA, COLCON.BDINSSFA, COLCON.BDBIRRFFA, COLCON.BDIRRFFA, COLCON.BDBSALFAMFA, COLCON.BDSALFAMFA, COLCON.BDSALBASEFA ' ||
                   'from VRHF_EMP_TFOLHAAVULSA COLCON ' ||
                   'left join VW_VRH_EMP_TCOLCON_VINC vinc on (vinc.bdcodemp = colcon.bdcodemp and vinc.bdcodcol = colcon.bdcodcol) ' ||
                   'where ' || prcodemp || ' and ';
     
            if (prcodcla <> '') then
               wsql = wsql || prcodcla || ' and ';
     
            if (prcodcol <> '') then
               wsql = wsql || '' || 'colcon.bdcodcol' || prcodcol || ' and ';
     
            wsql = wsql || '(SELECT bdaaaamm FROM aaaamm(colcon.bddatafa)) >= ' || prrefini || ' and (SELECT bdaaaamm FROM aaaamm(colcon.bddatafa)) <= ' || prreffin || ') ' ||
                           'GROUP BY BDCODEMP, BDCODCOL, BDREFFN ' ||
                           'ORDER BY BDCODEMP, BDCODCOL, BDREFFN';
          end
     
     
       FOR EXECUTE STATEMENT wsql into
           :bdcodemp,
           :bdcodcol,
           :bdref,
           :wbasefgts,
           :wbaseinss,
           :wbaseirrf,
           :wsalbase,
           :wvalorinss,
           :wvalorfgts,
           :wvalorirrf,
           :wbasesalfam,
           :wvalorsalfam do
          begin
            /*Salario base*/
            if (wsalbase > 0) then
               begin
                 bdindex = 1;
                 bdvalor = wsalbase;
                 bddescricao = 'Salário base';
                 suspend;
               end
     
            /*Base INSS*/
            if (wbaseinss > 0) then
               begin
                 bdindex = 2;
                 bdvalor = wbaseinss;
                 bddescricao = 'Base de INSS';
                 suspend;
               end
     
            /*Valor INSS*/
            if (wvalorinss > 0) then
               begin
                 bdindex = 3;
                 bdvalor = wvalorinss;
                 bddescricao = 'Valor do INSS';
                 suspend;
               end
     
            /*Base FGTS*/
            if (wbasefgts > 0) then
               begin
                 bdindex = 4;
                 bdvalor = wbasefgts;
                 bddescricao = 'Base de FGTS';
                 suspend;
               end
     
            /*Valor FGTS*/
            if (wvalorfgts > 0) then
               begin
                 bdindex = 5;
                 bdvalor = wvalorfgts;
                 bddescricao = 'Valor do FGTS';
                 suspend;
               end
     
            /*Base IRRF*/
            if (wbaseirrf > 0) then
               begin
                 bdindex = 6;
                 bdvalor = wbaseirrf;
                 bddescricao = 'Base de IRRF';
                 suspend;
               end
     
            /*Valor IRRF*/
            if (wvalorirrf > 0) then
               begin
                 bdindex = 7;
                 bdvalor = wvalorirrf;
                 bddescricao = 'Dedução de IRRF';
                 suspend;
               end
     
            /*Base Salario Familia*/
            if (wbasesalfam > 0) then
               begin
                 bdindex = 8;
                 bdvalor = wbasesalfam;
                 bddescricao = 'Base salário família';
                 suspend;
               end
     
            /*Valor Salario Familia*/
            if (wvalorsalfam > 0) then
               begin
                 bdindex = 9;
                 bdvalor = wvalorsalfam;
                 bddescricao = 'Valor salário família';
                 suspend;
          end
     end
end^

CREATE OR ALTER TRIGGER VFIN_BASE_TLOGREMAPI_AI0 FOR VFIN_BASE_TLOGREMAPI
ACTIVE AFTER INSERT POSITION 0
as
declare variable VCOUNT integer;
declare variable VREF integer;
begin
  :VREF = (extract(year from new.BDDATA) * 100 + extract(month from new.BDDATA));
  select BDCOUNT + 1
  from VFIN_TCONT_REC_REMAPI REC
  where REC.BDCODESC = new.BDCODESC and
        REC.BDCODFEBRABAN = new.BDCODFEBRABAN and
        REC.BDNUMCON = coalesce(new.BDNUMCON,0) and
        REC.BDREFREC = :VREF
  into :VCOUNT;

  update or insert into VFIN_TCONT_REC_REMAPI (BDCODESC, BDCODFEBRABAN, BDNUMCON, BDREFREC, BDCOUNT)
  values (new.BDCODESC, new.BDCODFEBRABAN, coalesce(new.BDNUMCON,0), :VREF, coalesce(:VCOUNT, 1));
end^

CREATE OR ALTER TRIGGER VFIN_ESC_TLOGREM_BI0 FOR VFIN_ESC_TLOGREM
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (new.bdcodseq <= 0) then
  begin
    new.bdcodseq = coalesce((select first 1 bdcodseq from vfin_esc_tlogrem order by bdcodseq desc),0) + 1;
  end

  if (new.bddata is null) then
  begin
    new.bddata = current_date;
  end

  if (new.bdhora is null) then
  begin
    new.bdhora = current_time;
  end

  if (new.bdarqenv is not null) then
  begin
    new.bdarqenv = zipblob(new.bdarqenv);
  end

  delete from vfin_esc_tlogrem where datediff(day, bddata, CURRENT_TIMESTAMP) >= 120;
end^

CREATE OR ALTER TRIGGER VFIN_BASE_PLANOIMPORTCSV_BI0 FOR VFIN_BASE_PLANOIMPORTACAOCSV
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcodigo integer;
begin
  if ((new.bdcodplaimp = 0) or (new.bdcodplaimp is null)) then
  begin
    select coalesce(max(bdcodplaimp),0)+1 from vfin_base_planoimportacaocsv into :vcodigo;
    new.bdcodplaimp = vcodigo;
  end
end^

CREATE OR ALTER TRIGGER VFIN_ESC_TCABSERVICOFIXO_BI0 FOR VFIN_ESC_TCABSERVICOFIXO
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vCodigo integer;
begin
  if ((new.bdchaveserfix is null) or (new.bdchaveserfix is null)) then
  begin
    select coalesce(max(bdchaveserfix),0)+1 from vfin_esc_tcabservicofixo where bdcodesc = new.bdcodesc and bdcodcli = new.bdcodcli
    into :vcodigo;
    new.bdchaveserfix = vcodigo;
  end
end^

CREATE OR ALTER TRIGGER VFIN_BASE_CONFIGIMPORTOCSV_BI0 FOR VFIN_BASE_CONFIGIMPORTACAOCSV
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcodigo integer;
begin
  if ((new.bdsequencia is null) or (new.bdsequencia = 0)) then
  begin
    select first 1 bdsequencia from vfin_base_configimportacaocsv where bdcodplaimp = new.bdcodplaimp order by bdsequencia desc into :vcodigo;
    new.bdsequencia = coalesce(vcodigo, 0)+1;
  end
end^

CREATE or alter  trigger vsuc_exporta_brgaap_bi0 for vsuc_exporta_brgaap
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
  vCodigo = null;
  if (coalesce(NEW.bdcodbrgaap,0) = 0) then
     begin
       select max(BDCODBRGAAP) from VSUC_EXPORTA_BRGAAP into :vCodigo;
       new.bdcodbrgaap = coalesce(:vCodigo,0) +1;
     end
end^

/* Restore proc. body: VSUC_SP_BALANCO_MENSAL */
CREATE OR ALTER procedure VSUC_SP_BALANCO_MENSAL (
    PRCODEMP varchar(2048),
    PRDATAINI date,
    PRDATAFIN date,
    PRIGNZER integer,
    PRCTALONINI varchar(40),
    PRCTALONFIN varchar(40),
    PRCTALONPAS varchar(40),
    PRINDICE integer,
    PRLISTCC varchar(8192),
    PRNAOMOSTRACONTRAPART integer,
    PRREFEMP integer,
    PRCONSOLIDADA integer,
    PRDETALHAPART integer,
    PRCONCATENAPARTIC integer,
    PRNIVEISCONTAS varchar(50),
    PRCONTABILIZACAO integer,
    PRMATRIZFILIALCONSOLI integer,
    PRSEMCC integer)
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(20),
    BDCODPLAPADRAO integer,
    BDCODCTA integer,
    BDCTALON varchar(40),
    BDNOMCTA varchar(300),
    BDTIPCTA integer,
    BDSEQCTA varchar(40),
    BDCODCENTROS integer,
    BDCODTPCC integer,
    BDNOMTPCC varchar(80),
    BDSALANT numeric(15,2),
    BDSAL_ANT_DEB numeric(15,2),
    BDSAL_ANT_CRE numeric(15,2),
    BDSALMOV numeric(15,2),
    BDSALDO_DEB numeric(15,2),
    BDSALDO_CRE numeric(15,2),
    BDSALATU numeric(15,2),
    BDFORMULA varchar(1024),
    BDCODEMPFILIAL integer,
    BDGRPCTA integer,
    BDAPECTA varchar(20),
    BDPERTENCECONTA integer,
    BDREF integer)
as
declare variable WDATAATUAL date;
begin
  WDATAATUAL = prdataini;
  WHILE (WDATAATUAL <= prdatafin) DO
    BEGIN
      FOR select BDCODEMP, BDCODMATRIZ, BDNOMEMP, BDCNPJEMP, BDCODPLAPADRAO, BDCODCTA, BDCTALON, BDNOMCTA, BDTIPCTA, BDSEQCTA,
                 BDCODCENTROS, BDCODTPCC, BDNOMTPCC,BDSALANT,BDSAL_ANT_DEB,BDSAL_ANT_CRE,BDSALMOV,BDSALDO_DEB,BDSALDO_CRE,BDSALATU,BDFORMULA,BDCODEMPFILIAL,
                 BDGRPCTA, BDAPECTA,BDPERTENCECONTA
          from VSUC_SP_BALANCO_PATRIMONIAL(:prcodemp, :WDATAATUAL,addmonth(:WDATAATUAL, 1)-1, :prignzer,:prctalonini , :prctalonfin, :prctalonpas, :prindice,:prlistcc , :prnaomostracontrapart, :prrefemp, :prconsolidada, :prdetalhapart,:prconcatenapartic , :prniveiscontas ,:prcontabilizacao,:prmatrizfilialconsoli,:prsemcc) TLAN
          INTO :BDCODEMP, :BDCODMATRIZ, :BDNOMEMP, :BDCNPJEMP, :BDCODPLAPADRAO, :BDCODCTA, :BDCTALON, :BDNOMCTA, :BDTIPCTA, :BDSEQCTA,
               :BDCODCENTROS, :BDCODTPCC, :BDNOMTPCC, :BDSALANT, :BDSAL_ANT_DEB, :BDSAL_ANT_CRE, :BDSALMOV, :BDSALDO_DEB, :BDSALDO_CRE, :BDSALATU,
               :BDFORMULA, :BDCODEMPFILIAL, :BDGRPCTA, :BDAPECTA, :BDPERTENCECONTA  DO
               begin
                 bdref = cast((substring(WDATAATUAL from 1 for 4)||substring(WDATAATUAL from 6 for 2)) as integer);
                 SUSPEND;
               end
      WDATAATUAL = addmonth(WDATAATUAL, 1);
    END
end^

/* Restore proc. body: SP_VRHF_EMP_T13SAL_RAT_CC */
create or alter procedure SP_VRHF_EMP_T13SAL_RAT_CC (
    PREMP varchar(30000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDREF13 integer,
    BDCHAVE integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDMESESPROP13 integer,
    BDBASEIR13 numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDFGTSCS13 numeric(18,6),
    BDDATABAIXA13 date,
    BDREFBAIXA13 integer,
    BDPERCIR13 numeric(18,6),
    BDVALORIR13 numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDPERCINSS13 numeric(18,6),
    BDVALORINSS13 numeric(18,6),
    BDBRAIS13 numeric(18,6),
    BDSALBASE13 numeric(18,6),
    BDDEP13 numeric(18,6),
    BDARREPROV13 numeric(18,6),
    BDARREDESC13 numeric(18,6),
    BDVAL13 numeric(18,6),
    BDBSALFAM13 numeric(18,6),
    BDSALFAM13 numeric(18,6),
    BDANO13 integer,
    BDBASEPIS13 numeric(18,6),
    BDBSALMATEMP13 numeric(18,6),
    BDSALMATEMP13 numeric(18,6),
    BDBRATAPO13 numeric(18,6),
    BDRATAPO13 numeric(18,6),
    BDESTPROV13 numeric(18,6),
    BDCREDITO13 numeric(18,6),
    BDDEBITO13 numeric(18,6),
    BDLIQUIDO numeric(18,6),
    BDDATAPGTO13 date,
    BDBINSSMV13 numeric(18,6),
    BDJAN DM_BOOLEAN,
    BDFEV DM_BOOLEAN,
    BDMAR DM_BOOLEAN,
    BDABR DM_BOOLEAN,
    BDMAI DM_BOOLEAN,
    BDJUN DM_BOOLEAN,
    BDJUL DM_BOOLEAN,
    BDAGO DM_BOOLEAN,
    BDSET DM_BOOLEAN,
    BDOUT DM_BOOLEAN,
    BDNOV DM_BOOLEAN,
    BDDEZ DM_BOOLEAN,
    BDDATAPROC13 date,
    BDHORAPROC13 time,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCODTOMADOR integer)
as
declare variable WSQL varchar(32700);
declare variable WVAL13 numeric(18,6);
declare variable WGPSVER DM_BOOLEAN;
declare variable WTIPOVER integer;
declare variable WBASEINSS13 numeric(18,6);
begin
  wsql = 'SELECT COLCON.bdcodemp, COLCON.bdref13, MAX(COLCON.bdchave), COLCON.bdcodcol, MAX(COLCON.bdmesesprop13),'||
                'SUM(COLCON.bdbaseir13), SUM(COLCON.bdbasefgts13),'||
                'SUM(COLCON.bdfgts13), SUM(COLCON.bdfgtscs13), MAX(COLCON.bddatabaixa13), MAX(COLCON.bdrefbaixa13),'||
                'MAX(COLCON.bdpercir13), SUM(COLCON.bdvalorir13),'||
                'MAX(COLCON.bdpercinss13),'||
                'SUM(COLCON.bdvalorinss13), SUM(COLCON.bdbrais13),'||
                'MAX(COLCON.bdsalbase13), MAX(COLCON.bddep13),'||
                'MAX(COLCON.bdarreprov13), MAX(COLCON.bdarredesc13),'||
                'MAX(COLCON.bdval13), MAX(COLCON.bdbsalfam13),'||
                'MAX(COLCON.bdsalfam13), MAX(COLCON.bdano13), SUM(COLCON.bdbasepis13),'||
                'SUM(COLCON.bdbsalmatemp13), SUM(COLCON.bdsalmatemp13), SUM(COLCON.bdbratapo13),'||
                'SUM(COLCON.bdratapo13), MAX(COLCON.bdestprov13), MAX(COLCON.bdcredito13),'||
                'MAX(COLCON.bddebito13), SUM(COLCON.bdliquido), MAX(COLCON.bddatapgto13),'||
                'MAX(COLCON.bdbinssmv13), MAX(COLCON.bdjan), MAX(COLCON.bdfev),'||
                'MAX(COLCON.bdmar), MAX(COLCON.bdabr), MAX(COLCON.bdmai), MAX(COLCON.bdjun),'||
                'MAX(COLCON.bdjul), MAX(COLCON.bdago), MAX(COLCON.bdset), MAX(COLCON.bdout),'||
                'MAX(COLCON.bdnov), MAX(COLCON.bddez), MAX(COLCON.bddataproc13), MAX(COLCON.bdhoraproc13),SUM(bdbaseinss13),'||
                'cc.bdcodcentro, cc.bdcodtpcc, tom.bdcodtpcc bdcodtomador '||
         'FROM VRHF_EMP_T13SAL_RAT COLCON '||
         'LEFT OUTER JOIN vrhf_emp_tprepfn cc ON (COLCON.bdcodemp = cc.bdcodemp AND COLCON.bdcodcol = cc.bdcodcol AND COLCON.bdordem = cc.bdordem) '||
         'LEFT OUTER JOIN vrhf_sp_tomador(cc.bdcodtpcc,cc.bdcodcentro) tom ON (cc.bdcodcentro = tom.bdcodcentro AND cc.bdcodtpcc = tom.bdcodcencus) '||
         'WHERE SUBSTRING(COLCON.BDREF13 FROM 1 FOR 4) = SUBSTRING('||:prref||' FROM 1 FOR 4)';

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||' and '||premp;

       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;
     end

  wsql = wsql||
         'GROUP BY COLCON.bdcodemp,COLCON.bdcodcol,COLCON.bdref13,cc.bdcodcentro, cc.bdcodtpcc, tom.bdcodtpcc ';

  BDORDEM = null;

  for execute statement wsql into
    :BDCODEMP, :BDREF13, :BDCHAVE, :BDCODCOL, :BDMESESPROP13, :BDBASEIR13, :BDBASEFGTS13, :BDFGTS13, :BDFGTSCS13, :BDDATABAIXA13, :BDREFBAIXA13, :BDPERCIR13,
    :BDVALORIR13, :BDPERCINSS13, :BDVALORINSS13, :BDBRAIS13, :BDSALBASE13, :BDDEP13, :BDARREPROV13, :BDARREDESC13, :BDVAL13, :BDBSALFAM13, :BDSALFAM13,
    :BDANO13, :BDBASEPIS13, :BDBSALMATEMP13, :BDSALMATEMP13, :BDBRATAPO13, :BDRATAPO13, :BDESTPROV13, :BDCREDITO13, :BDDEBITO13, :BDLIQUIDO, :BDDATAPGTO13, :BDBINSSMV13,
    :BDJAN, :BDFEV, :BDMAR, :BDABR, :BDMAI, :BDJUN, :BDJUL, :BDAGO, :BDSET, :BDOUT, :BDNOV, :BDDEZ, :BDDATAPROC13, :BDHORAPROC13, :wbaseinss13, :BDCODCENTRO, :BDCODTPCC, :BDCODTOMADOR
  do
    begin
      if (prref >= 201508) then
         begin
           BDBASEINSS13 = 0;
     
           for select T13.BDVALV13, VR.BDBASEGPSVER, VR.BDTIPOCODVER
               from VRHF_EMP_TVERBA_13_RAT T13
               left outer join VW_TVERBAS_REF VR on (VR.BDCODVER = T13.BDCODVER)
               where T13.BDCODEMP = :BDCODEMP and T13.BDCODCOL = :BDCODCOL and T13.BDREF13 = :BDREF13 and  T13.BDCHAVE = :BDCHAVE
           into :wval13, :wgpsver, :wtipover do
             begin
               wval13   = coalesce(:wval13, 0);
               wgpsver  = upper(coalesce(:wgpsver, 'FALSE'));
               wtipover = coalesce(:wtipover, 0);
     
               if (wgpsver = 'TRUE') then
                  begin
                    if (wtipover = 0) then
                       BDBASEINSS13 = BDBASEINSS13 + :wval13;
                    else
                    if (wtipover = 1) then
                       BDBASEINSS13 = BDBASEINSS13 - :wval13;
                  end
             end
           end
        else
           BDBASEINSS13 = wbaseinss13;

        if (BDBASEINSS13 < 0) then
           BDBASEINSS13 = 0;
      suspend;
    end
end^

/* Restore proc. body: SP_VRHF_FGTSSEFIP_13 */
create or alter procedure SP_VRHF_FGTSSEFIP_13 (
    PREMP varchar(30000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODTPCC integer,
    BDCODCENTRO integer,
    BDBASEFGTS13 numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDINSS13 numeric(18,6),
    BDBINSS13 numeric(18,6),
    BDBASEFGTSFN numeric(18,6),
    BDFGTSFN numeric(18,6),
    BDINSSFN numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSS13R numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDBINSSC13 numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSS13DT numeric(18,6),
    BDINSSC13 numeric(18,6),
    BDINSSMV numeric(18,6))
as
declare variable WSQL varchar(32700);
declare variable WREF integer;
declare variable WVAL13 numeric(18,6);
declare variable WGPSVER DM_BOOLEAN;
declare variable WTIPOVER integer;
declare variable WBASEINSS13 numeric(18,6);
begin
  wsql = 'SELECT COLCON.bdcodemp,COLCON.bdcodcol,CAST(COLCON.bdano13||''12'' AS INTEGER),'||
                'COLCON.bdbasefgts13, COLCON.bdfgts13, COLCON.bdvalorinss13, COLCON.BDREF13, COALESCE(colcon.bdbaseinss13,0), '||
         'FROM VRHF_EMP_T13SAL COLCON '||
         'WHERE SUBSTRING(COLCON.BDREF13 FROM 1 FOR 4) = SUBSTRING('||prref||' FROM 1 FOR 4)';

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||' and '||premp;

       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;
     end

  BDCODTPCC     = null;
  BDCODCENTRO   = null;
  BDBASEFGTSFN  = 0;
  BDFGTSFN      = 0;
  BDINSSFN      = 0;
  BDBINSSFN     = 0;
  BDBINSS13R    = 0;
  BDSALFAMFN    = 0;
  BDBINSSC13    = 0;
  BDBINSSAPFN   = 0;
  BDBINSS13APFN = 0;
  BDINSSAPFN    = 0;
  BDINSS13APFN  = 0;
  BDINSS13DT    = 0;
  BDINSSC13     = 0;
  BDINSSMV      = 0;

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDREF, :BDBASEFGTS13, :BDFGTS13, :BDINSS13, :wref, :wbaseinss13 do
    begin
      BDBASEFGTS13 = coalesce(BDBASEFGTS13, 0);
      BDFGTS13     = coalesce(BDFGTS13, 0);

      if (BDBASEFGTS13 < 0) then
         BDBASEFGTS13 = 0;

      if (BDFGTS13 < 0) then
         BDFGTS13 = 0;

      if (prref >= 201508) then
         begin
           BDBINSS13 = 0;
     
           for select T13.BDVALV13, VR.BDBASEGPSVER, VR.BDTIPOCODVER
               from VRHF_EMP_TVERBA13 T13
               left outer join VW_TVERBAS_REF VR on (VR.BDCODVER = T13.BDCODVER)
               where T13.BDCODEMP = :BDCODEMP and T13.BDCODCOL = :BDCODCOL and T13.BDREF13 = :wref
           into :wval13, :wgpsver, :wtipover do
             begin
               wval13   = coalesce(:wval13, 0);
               wgpsver  = upper(coalesce(:wgpsver, 'FALSE'));
               wtipover = coalesce(:wtipover, 0);
     
               if (wgpsver = 'TRUE') then
                  begin
                    if (wtipover = 0) then
                       BDBINSS13 = BDBINSS13 + :wval13;
                    else
                    if (wtipover = 1) then
                       BDBINSS13 = BDBINSS13 - :wval13;
                  end
             end
         end
      else
         BDBINSS13 = wbaseinss13;

      if (BDBINSS13 < 0) then
         BDBINSS13 = 0;

      suspend;
    end
end^

/* Restore proc. body: SP_VRHF_FGTSSEFIP_13_CC */
create or alter procedure SP_VRHF_FGTSSEFIP_13_CC (
    PREMP varchar(30000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODTPCC integer,
    BDCODCENTRO integer,
    BDBASEFGTSFN numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDFGTSFN numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDINSSFN numeric(18,6),
    BDINSS13 numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSS13 numeric(18,6),
    BDBINSS13R numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDBINSSC13 numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSS13DT numeric(18,6),
    BDINSSC13 numeric(18,6),
    BDINSSMV numeric(18,6))
as
declare variable WSQL varchar(32700);
begin
  wsql = 'SELECT COLCON.bdcodemp,COLCON.bdcodcol,CAST(COLCON.bdano13||''12'' AS INTEGER), COLCON.bdcodtpcc, COLCON.bdcodcentro,'||
                '0 bdbasefgtsfn,'||
                'SUM(CASE WHEN (COLCON.bdbasefgts13 < 0) THEN 0 ELSE COALESCE(COLCON.bdbasefgts13,0) END) bdbasefgts13,'||
                '0 bdfgtsfn,'||
                'SUM(CASE WHEN (COLCON.bdfgts13 < 0) THEN 0 ELSE COALESCE(COLCON.bdfgts13,0) END) bdfgts13,'||
                '0 bdinssfn,'||
                'SUM(COALESCE(COLCON.bdvalorinss13,0)),'||
                '0 bdbinssfn,'||
                'SUM(COALESCE(COLCON.bdbaseinss13,0)),'||
                '0 bdbinss13r,'||
                '0 bdsalfamfn,'||
                '0 bdbinssc13,'||
                '0 bdbinssapfn,'||
                '0 bdbinss13apfn,'||
                '0 bdinssapfn,'||
                '0 bdinss13apfn,'||
                '0 BDINSS13DT,'||
                '0 bdinssc13,'||
                '0 bdinssmv '||
         'FROM SP_VRHF_EMP_T13SAL_RAT_CC(';

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||''''||premp||''',';

       if (coalesce(prcol, '') <> '') then
          wsql = wsql||''''||prcol||''',';
       else
          wsql = wsql||'null,';
     end
  else
     wsql = wsql||'null,null,';

  wsql = wsql||:prref||') COLCON '||
         'GROUP BY COLCON.bdcodemp,COLCON.bdcodcol,COLCON.bdano13,COLCON.bdcodcentro,COLCON.bdcodtpcc ';

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDREF, :BDCODTPCC, :BDCODCENTRO, :BDBASEFGTSFN, :BDBASEFGTS13, :BDFGTSFN, :BDFGTS13, :BDINSSFN,
    :BDINSS13, :BDBINSSFN, :BDBINSS13, :BDBINSS13R, :BDSALFAMFN, :BDBINSSC13, :BDBINSSAPFN, :BDBINSS13APFN, :BDINSSAPFN, :BDINSS13APFN, :BDINSS13DT,
    :BDINSSC13, :BDINSSMV
  do
    suspend;
end^

/* Restore proc. body: SP_VRHF_FGTSSEFIP */
create or alter procedure SP_VRHF_FGTSSEFIP (
    PREMP varchar(30000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDSOMA integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODTPCC integer,
    BDCODCENTRO integer,
    BDBASEFGTSFN numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDFGTSFN numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDINSSFN numeric(18,6),
    BDINSS13 numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSS13 numeric(18,6),
    BDBINSS13R numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDBINSSC13 numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSS13DT numeric(18,6),
    BDINSSC13 numeric(18,6),
    BDINSSMV numeric(18,6))
as
declare variable WSQL varchar(32700);
declare variable WREF integer;
declare variable WCHAVE integer;
declare variable WVAL13 numeric(18,6);
declare variable WGPSVER DM_BOOLEAN;
declare variable WTIPOVER integer;
declare variable WINSSVER integer;
declare variable WCODAUX integer;
declare variable WORDEM integer;
declare variable WBASEINSS numeric(18,6);
declare variable WBASEINSS13 numeric(18,6);
declare variable WDTGOZO date;
declare variable WREFAUX integer;
declare variable WEMP varchar(1000);
declare variable WCOL varchar(1000);
declare variable WCASEREF varchar(1000);
begin



  if (PRREF >= 202301) then
    begin
      wsql = 'SELECT 1 bdsoma, colcon.bdcodemp,colcon.bdcodcol,colcon.bdrefa13, NULL bdcodtpcc, NULL bdcodcentro, '||
                '0 bdbasefgtsfn, '||
                'CASE WHEN (colcon.bdbasefgtsa13 < 0) THEN 0 ELSE COALESCE(colcon.bdbasefgtsa13,0) END bdbasefgts13, '||
                '0 bdfgtsfn, '||
                'CASE WHEN (colcon.bdfgtsa13 < 0) THEN 0 ELSE COALESCE(colcon.bdfgtsa13,0) END bdfgts13, '||
                '0 bdinssfn, '||
                '0 bdinss13, '||
                '0 bdbinssfn, '||
                '0 bdbinss13, '||
                '0 bdbinss13r, '||
                '0 bdsalfamfn, '||
                '0 bdbinssc13, '||
                '0 bdbinssapfn, '||
                '0 bdbinss13apfn, '||
                '0 bdinssapfn, '||
                '0 bdinss13apfn, '||
                '0 BDINSS13DT, '||
                '0 BDINSSC13, '||
                '0 BDINSSMV '||
         'FROM vrhf_emp_ta13sal colcon '||
             'WHERE colcon.BDREFA13 = '||prref;

  if (coalesce(premp, '') <> '') then
    begin
      wsql = wsql||' and '||premp;
    
      if (coalesce(prcol, '') <> '') then
        wsql = wsql||' and '||prcol;
    end
    end
  else 
    begin
        wsql = 'SELECT 1 bdsoma, colcon.bdcodemp,colcon.bdcodcol,colcon.bdrefa13, NULL bdcodtpcc, NULL bdcodcentro, '||
                        '0 bdbasefgtsfn, '||
                        'CASE WHEN (colcon.bdbasefgtsa13 < 0) THEN 0 ELSE COALESCE(colcon.bdbasefgtsa13,0) END bdbasefgts13, '||
                        '0 bdfgtsfn, '||
                        'CASE WHEN (colcon.bdfgtsa13 < 0) THEN 0 ELSE COALESCE(colcon.bdfgtsa13,0) END bdfgts13, '||
                        '0 bdinssfn, '||
                        '0 bdinss13, '||
                        '0 bdbinssfn, '||
                        '0 bdbinss13, '||
                        '0 bdbinss13r, '||
                        '0 bdsalfamfn, '||
                        '0 bdbinssc13, '||
                        '0 bdbinssapfn, '||
                        '0 bdbinss13apfn, '||
                        '0 bdinssapfn, '||
                        '0 bdinss13apfn, '||
                        '0 BDINSS13DT, '||
                        '0 BDINSSC13, '||
                        '0 BDINSSMV '||
                 'FROM vrhf_emp_ta13sal colcon '||
                 'WHERE upper(coalesce(colcon.BDCALCFERA13, ''FALSE'')) <> ''TRUE'' and colcon.BDREFA13 = '||prref;

          if (coalesce(premp, '') <> '') then
            begin
              wsql = wsql||' and '||premp;
        
              if (coalesce(prcol, '') <> '') then
                wsql = wsql||' and '||prcol;
            end
      end

  for execute statement wsql into :BDSOMA, :BDCODEMP, :BDCODCOL, :BDREF, :BDCODTPCC, :BDCODCENTRO, :BDBASEFGTSFN, :BDBASEFGTS13, :BDFGTSFN, :BDFGTS13, :BDINSSFN, :BDINSS13,
     :BDBINSSFN, :BDBINSS13, :BDBINSS13R, :BDSALFAMFN, :BDBINSSC13, :BDBINSSAPFN, :BDBINSS13APFN, :BDINSSAPFN, :BDINSS13APFN, :BDINSS13DT, :BDINSSC13, :BDINSSMV
  do
    suspend;

  wsql =
         'SELECT 2 bdsoma, colcon.bdcodemp,colcon.bdcodcol,colcon.bdref13, cc.bdcodtpcc bdcodtpcc, CASE WHEN cc.bdcodtpcc IS NULL THEN NULL ELSE cc.bdcodcentro END bdcodcentro, '||
                '0 bdbasefgtsfn, '||
                'CASE WHEN (colcon.bdbasefgts13 < 0) THEN 0 ELSE COALESCE(colcon.bdbasefgts13,0) END bdbasefgts13, '||
                '0 bdfgtsfn, '||
                'CASE WHEN (colcon.bdfgts13 < 0) THEN 0 ELSE COALESCE(colcon.bdfgts13,0) END bdfgts13, '||
                '0 bdinssfn, '||
                '0 bdinss13, '||
                '0 bdbinssfn, '||
                '0 bdbinss13, '||
                '0 bdbinss13r, '||
                '0 bdsalfamfn, '||
                '0 bdbinssc13, '||
                '0 bdbinssapfn, '||
                '0 bdbinss13apfn, '||
                '0 bdinssapfn, '||
                '0 bdinss13apfn, '||
                '0 BDINSS13DT, '||
                '0 BDINSSC13, '||
                '0 BDINSSMV '||
         'FROM vrhf_emp_t13sal_rat colcon '||
         'LEFT OUTER JOIN vrhf_emp_tprepfn cc ON (colcon.bdcodemp = cc.bdcodemp AND colcon.bdcodcol = cc.bdcodcol AND colcon.bdordem = cc.bdordem) '||
         'where colcon.bdref13 = '||prref;

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||' and '||premp;

       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;
     end

  for execute statement wsql into :BDSOMA, :BDCODEMP, :BDCODCOL, :BDREF, :BDCODTPCC, :BDCODCENTRO, :BDBASEFGTSFN, :BDBASEFGTS13, :BDFGTSFN, :BDFGTS13, :BDINSSFN, :BDINSS13,
     :BDBINSSFN, :BDBINSS13, :BDBINSS13R, :BDSALFAMFN, :BDBINSSC13, :BDBINSSAPFN, :BDBINSS13APFN, :BDINSSAPFN, :BDINSS13APFN, :BDINSS13DT, :BDINSSC13, :BDINSSMV
  do
    suspend;

  wsql =
         'SELECT 2 bdsoma, ColCON.bdcodemp,ColCON.bdcodcol, '||
                'CASE WHEN CAST(ColCON.bdano13||''12'' AS INTEGER) < COALESCE(res.bdrefrescisao,999999) THEN CAST(ColCON.bdano13||''12'' AS INTEGER) ELSE res.bdrefrescisao END, '||
                ' cc.bdcodtpcc, CASE WHEN cc.bdcodtpcc IS NULL THEN NULL ELSE cc.bdcodcentro END bdcodcentro, '||
                '0 bdbasefgtsfn, '||
                '0 bdbasefgts13, '||
                '0 bdfgtsfn, '||
                '0 bdfgts13, '||
                '0 bdinssfn, '||
                'COALESCE(ColCON.bdvalorinss13,0), '||
                '0 bdbinssfn, '||
                '0 bdbinss13r, '||
                '0 bdsalfamfn, '||
                '0 bdbinssc13, '||
                '0 bdbinssapfn, '||
                '0 bdbinss13apfn, '||
                '0 bdinssapfn, '||
                '0 bdinss13apfn, '||
                'COALESCE(ColCON.bdvalorinss13,0), '||
                '0 BDINSSC13, '||
                '0 BDINSSMV, '||
                'colcon.bdref13, '||
                'colcon.bdchave, '||
                'COALESCE(colcon.bdbaseinss13,0) '||
         'FROM vrhf_emp_t13sal_rat colcon '||
         'LEFT OUTER JOIN vrh_emp_trescisao res ON (ColCON.bdcodemp = res.bdcodemp AND ColCON.bdcodcol = res.bdcodcol) '||
         'LEFT OUTER JOIN vrhf_emp_tprepfn cc ON (ColCON.bdcodemp = cc.bdcodemp AND ColCON.bdcodcol = cc.bdcodcol AND ColCON.bdordem = cc.bdordem) '||
         'where colcon.BDANO13 = SUBSTRING('||:prref||' FROM 1 FOR 4)';

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||' and '||premp;

       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;
     end

  for execute statement wsql into :BDSOMA, :BDCODEMP, :BDCODCOL, :BDREF, :BDCODTPCC, :BDCODCENTRO, :BDBASEFGTSFN, :BDBASEFGTS13, :BDFGTSFN, :BDFGTS13, :BDINSSFN, :BDINSS13,
     :BDBINSSFN, :BDBINSS13R, :BDSALFAMFN, :BDBINSSC13, :BDBINSSAPFN, :BDBINSS13APFN, :BDINSSAPFN, :BDINSS13APFN, :BDINSS13DT, :BDINSSC13, :BDINSSMV, :wref, :wchave, :wbaseinss
  do
    begin
      if (prref >= 201508) then
         begin
           BDBINSS13 = 0;
     
           for select T13.BDVALV13, VR.BDBASEGPSVER, VR.BDTIPOCODVER
               from VRHF_EMP_TVERBA_13_RAT T13
               left outer join VW_TVERBAS_REF VR on (VR.BDCODVER = T13.BDCODVER)
               where T13.BDCODEMP = :BDCODEMP and T13.BDCODCOL = :BDCODCOL and T13.BDREF13 = :wref and T13.BDCHAVE = :wchave
           into :wval13, :wgpsver, :wtipover do
             begin
               wval13   = coalesce(:wval13, 0);
               wgpsver  = upper(coalesce(:wgpsver, 'FALSE'));
               wtipover = coalesce(:wtipover, 0);
     
               if (wgpsver = 'TRUE') then
                  begin
                    if (wtipover = 0) then
                       BDBINSS13 = BDBINSS13 + :wval13;
                    else
                    if (wtipover = 1) then
                       BDBINSS13 = BDBINSS13 - :wval13;
                  end
             end
           end
        else
           BDBINSS13 = wbaseinss;

        if (BDBINSS13 < 0) then
           BDBINSS13 = 0;

      suspend;
    end

  wsql = 'SELECT 4 bdsoma, ColCON.bdcodemp,ColCON.bdcodcol,ColCON.bdrefc13, NULL bdcodtpcc, NULL bdcodcentro, '||
                '0 bdbasefgtsfn, '||
                'CASE WHEN (ColCON.bdbasefgtsc13 < 0) THEN 0 ELSE COALESCE(ColCON.bdbasefgtsc13,0) END bdbasefgts13, '||
                '0 bdfgtsfn, '||
                'CASE WHEN (ColCON.bdfgtsc13 < 0) THEN 0 ELSE COALESCE(ColCON.bdfgtsc13,0) END bdfgts13, '||
                '0 bdinssfn, '||
                '0 bdinss13, '||
                '0 bdbinssfn, '||
                '0 bdbinss13, '||
                '0 bdsalfamfn, '||
--                'case when (COALESCE(ColCON.bdvalorinssc13,0) = 0 and COALESCE(ColCON.bdbaseinssc13,0) = 0) then COALESCE(ColCON.bdbasefgtsc13,0) else COALESCE(ColCON.bdbaseinssc13,0) end, '||
                '0 bdbinssapfn, '||
                '0 bdbinss13apfn, '||
                '0 bdinssapfn, '||
                '0 bdinss13apfn, '||
                '0 BDINSS13DT, '||
                'COALESCE(ColCON.bdvalorinssc13,0) BDINSSC13, '||
                '0 BDINSSMV, '||
                'COALESCE(colcon.bdbaseinssc13,0) '||
         'FROM vrhf_emp_tc13sal colcon '||
         'where colcon.bdrefc13 = '||:prref;

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||' and '||premp;

       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;
     end

  for execute statement wsql into :BDSOMA, :BDCODEMP, :BDCODCOL, :BDREF, :BDCODTPCC, :BDCODCENTRO, :BDBASEFGTSFN, :BDBASEFGTS13, :BDFGTSFN, :BDFGTS13, :BDINSSFN, :BDINSS13,
     :BDBINSSFN, :BDBINSS13, :BDSALFAMFN, :BDBINSSAPFN, :BDBINSS13APFN, :BDINSSAPFN, :BDINSS13APFN, :BDINSS13DT, :BDINSSC13, :BDINSSMV, :wbaseinss
  do
    begin
      if (prref >= 201508) then
         begin
           BDBINSS13R = 0;
     
           for select T13.BDVALVC13, VR.BDBASEGPSVER, VR.BDTIPOCODVER
               from VRHF_EMP_TVERBAC13 T13
               left outer join VW_TVERBAS_REF VR on (VR.BDCODVER = T13.BDCODVER)
               where T13.BDCODEMP = :BDCODEMP and T13.BDCODCOL = :BDCODCOL and T13.BDREF13 = :BDREF
           into :wval13, :wgpsver, :wtipover do
             begin
               wval13   = coalesce(:wval13, 0);
               wgpsver  = upper(coalesce(:wgpsver, 'FALSE'));
               wtipover = coalesce(:wtipover, 0);
     
               if (wgpsver = 'TRUE') then
                  begin
                    if (wtipover = 0) then
                       BDBINSS13R = BDBINSS13R + :wval13;
                    else
                    if (wtipover = 1) then
                       BDBINSS13R = BDBINSS13R - :wval13;
                  end
             end
         end
      else
         BDBINSS13R = wbaseinss;

      if (BDBINSS13R < 0) then
         BDBINSS13R = 0;

      if (BDINSSC13 = 0 and BDBINSS13R = 0) then
         BDBINSSC13 = BDBASEFGTS13;
      else
         BDBINSSC13 = BDBINSS13R;

      suspend;
    end

  wsql = 'SELECT 10 bdsoma, ColCON.bdcodemp, ColCON.bdcodcol, ColCON.bdreffn, NULL bdcodtpcc, NULL bdcodcentro, '||
            'CASE WHEN (COALESCE(ColCON.bdbfgtsfn, 0) + COALESCE(ColCON.BDBFGTSFEFN, 0) < 0) THEN 0 ELSE COALESCE(ColCON.bdbfgtsfn,0) END +CASE WHEN (ColCON.BDBFGTSFEFN < 0) THEN 0 ELSE COALESCE(ColCON.BDBFGTSFEFN,0) END, '||
            'CASE WHEN (ColCON.bdbfgts13fn < 0) THEN 0 ELSE COALESCE(ColCON.bdbfgts13fn,0) END, '||
            'CASE WHEN (COALESCE(ColCON.bdfgtsfn, 0) + COALESCE(ColCON.BDFGTSFEFN, 0) < 0) THEN 0 ELSE COALESCE(ColCON.bdfgtsfn,0) END + CASE WHEN (ColCON.BDFGTSFEFN < 0) THEN 0 ELSE COALESCE(ColCON.BDFGTSFEFN,0) END, '||
            'CASE WHEN (ColCON.bdfgts13fn < 0) THEN 0 ELSE COALESCE(ColCON.bdfgts13fn,0) END, '||
            'COALESCE(ColCON.bdinssfn,0) + COALESCE(ColCON.bdinssfefolfn,0), '||
            'COALESCE(ColCON.bdinss13fn,0), '||
--            'case when coalesce(ColCON.bdbaseinssnmvnovo, 0) = 0 then (COALESCE(ColCON.bdbinssfn,0) + COALESCE(ColCON.bdbinssfefolfn,0)) - COALESCE(ColCON.bdbinssmvfn,0) else COALESCE(ColCON.bdbinssfn,0) + COALESCE(ColCON.bdbinssfefolfn,0) end, '||
            '0 bdbinss13, '||
--            'case when coalesce(ColCON.bdbaseinss13mvnovo, 0) = 0 then COALESCE(ColCON.bdbinss13fn,0) - COALESCE(ColCON.bdbinssmv13fn,0) else COALESCE(ColCON.bdbinss13fn,0) end, '||
            'COALESCE(ColCON.bdsalfamfn,0) + COALESCE(ColCON.bdcovid19fn,0) bdsalfamfn, '||
            '0 bdbinssc13, '||
            'CASE '||
              'WHEN (ColCON.bdbinssapfn IS NULL) OR (ColCON.bdbinssapfn = 0) THEN 0 '||
              'ELSE COALESCE(ColCON.bdbinssapfn,0) + COALESCE(ColCON.bdbinssfefolfn,0) '||
            'END, '||
            'COALESCE(ColCON.bdbinss13apfn,0), '||
            'CASE '||
              'WHEN (ColCON.bdinssapfn IS NULL) OR (ColCON.bdinssapfn = 0) THEN 0 '||
              'ELSE COALESCE(ColCON.bdinssapfn,0) + COALESCE(ColCON.bdinssfefolfn,0) '||
            'END, '||
            'COALESCE(ColCON.bdinss13apfn,0), '||
            '0 BDINSS13DT, '||
            '0 BDINSSC13, '||
            'colcon.BDBASEINSSNMVNOVO, '||
            'case when coalesce(ColCON.bdbaseinssnmvnovo, 0) = 0 then (COALESCE(ColCON.bdbinssfn,0) + COALESCE(ColCON.bdbinssfefolfn,0)) - COALESCE(ColCON.bdbinssmvfn,0) else COALESCE(ColCON.bdbinssfn,0) + COALESCE(ColCON.bdbinssfefolfn,0) end, '||
            'case when coalesce(ColCON.bdbaseinss13mvnovo, 0) = 0 then COALESCE(ColCON.bdbinss13fn,0) - COALESCE(ColCON.bdbinssmv13fn,0) else COALESCE(ColCON.bdbinss13fn,0) end '||
         'FROM vrhf_emp_tfolhanormal colcon '||
         'where colcon.BDREFFN = '||prref;

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||' and '||premp;

       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;
     end

  for execute statement wsql into :BDSOMA, :BDCODEMP, :BDCODCOL, :BDREF, :BDCODTPCC, :BDCODCENTRO, :BDBASEFGTSFN, :BDBASEFGTS13, :BDFGTSFN, :BDFGTS13, :BDINSSFN, :BDINSS13,
     :BDBINSS13, :BDSALFAMFN, :BDBINSSC13, :BDBINSSAPFN, :BDBINSS13APFN, :BDINSSAPFN, :BDINSS13APFN, :BDINSS13DT, :BDINSSC13, :BDINSSMV, :wbaseinss, :wbaseinss13
  do
    begin
      if (prref >= 201508) then
         begin
           BDBINSSFN  = 0;
           BDBINSS13R = 0;
     
           for select FN.BDVALVFN, VR.BDINSSVER, VR.BDBASEGPSVER, VR.BDTIPOCODVER
               from VRHF_EMP_TVERBAFN FN
               left outer join VW_TVERBAS_REF VR on (VR.BDCODVER = FN.BDCODVER)
               where FN.BDCODEMP = :BDCODEMP and FN.BDCODCOL = :BDCODCOL and FN.BDREFFN = :BDREF
           into :wval13, :winssver, :wgpsver, :wtipover do
             begin
               wval13   = coalesce(:wval13, 0);
               wgpsver  = upper(coalesce(:wgpsver, 'FALSE'));
               winssver = coalesce(:winssver, 0);
               wtipover = coalesce(:wtipover, 0);
     
               if (wgpsver = 'TRUE') then
                  begin
                    if (winssver = 3) then
                       begin
                         if (wtipover = 0) then
                            BDBINSS13R = BDBINSS13R + :wval13;
                         else
                         if (wtipover = 1) then
                            BDBINSS13R = BDBINSS13R - :wval13;
                       end
                    else
                       begin
                         if (wtipover = 0) then
                            BDBINSSFN = BDBINSSFN + :wval13;
                         else
                         if (wtipover = 1) then
                            BDBINSSFN = BDBINSSFN - :wval13;
                       end
                  end
             end
         end
      else
         begin
           BDBINSSFN  = wbaseinss;
           BDBINSS13R = wbaseinss13;
         end

      if (BDBINSSFN < 0) then
         BDBINSSFN = 0;

      if (BDBINSS13R < 0) then
         BDBINSS13R = 0;

      suspend;
    end

  wsql = 'SELECT 10 bdsoma, ColCON.bdcodemp, ColCON.bdcodcol, ColCON.bdreffn, NULL bdcodtpcc, NULL bdcodcentro, '||
            'CASE WHEN (COALESCE(ColCON.bdbfgtsfn, 0) + COALESCE(ColCON.BDBFGTSFEFN, 0) < 0) THEN 0 ELSE COALESCE(ColCON.bdbfgtsfn,0) END + MAXVALUE(0, COALESCE(ColCON.BDBFGTSFEFN,0)), '||
            'MAXVALUE(0, COALESCE(ColCON.bdbfgts13fn,0)), '||
            'CASE WHEN (COALESCE(ColCON.bdfgtsfn, 0) + COALESCE(ColCON.BDFGTSFEFN, 0) + COALESCE(ColCON.bdfgts13fn,0) < 0) THEN 0 ELSE COALESCE(ColCON.bdfgtsfn,0) + COALESCE(ColCON.bdfgts13fn,0) END + CASE WHEN (ColCON.BDFGTSFEFN < 0) THEN 0 ELSE COALESCE(ColCON.BDFGTSFEFN,0) END, '||
            '0, '||
            'COALESCE(ColCON.bdinssfn,0) + COALESCE(ColCON.bdinssfefolfn,0) + COALESCE(ColCON.bdinss13fn,0), '||
            '0, '||
--            'case when coalesce(ColCON.bdbaseinssnmvnovo, 0) = 0 then COALESCE(ColCON.bdbinssfn,0) + COALESCE(ColCON.bdbinssfefolfn,0) - COALESCE(ColCON.bdbinssmvfn,0) else COALESCE(ColCON.bdbinssfn,0) + COALESCE(ColCON.bdbinssfefolfn,0) end, '||
--            'case when coalesce(ColCON.bdbaseinssnmvnovo, 0) = 0 then COALESCE(ColCON.bdbinss13fn,0) - COALESCE(ColCON.bdbinssmv13fn,0) else COALESCE(ColCON.bdbinss13fn,0) end, '||
            '0, '||
            'COALESCE(ColCON.bdsalfamfn,0) + COALESCE(ColCON.bdcovid19fn,0) bdsalfamfn, '||
            '0 bdbinssc13, '||
            'CASE '||
              'WHEN (ColCON.bdbinssapfn IS NULL) OR (ColCON.bdbinssapfn = 0) THEN 0 '||
              'ELSE COALESCE(ColCON.bdbinssapfn,0) + COALESCE(ColCON.bdbinssfefolfn,0) + COALESCE(ColCON.bdbinss13apfn,0) '||
            'END, '||
            '0, '||
            'CASE '||
              'WHEN (ColCON.bdinssapfn IS NULL) OR (ColCON.bdinssapfn = 0) THEN 0 '||
              'ELSE COALESCE(ColCON.bdinssapfn,0) + COALESCE(ColCON.bdinssfefolfn,0) + COALESCE(ColCON.bdinss13apfn,0) '||
            'END, '||
            '0, '||
            '0 BDINSS13DT, '||
            '0 BDINSSC13, '||
            'COLCON.BDBASEINSSNMVNOVO, '||
            'colcon.bdcodcontti, '||
            'case when coalesce(ColCON.bdbaseinssnmvnovo, 0) = 0 then COALESCE(ColCON.bdbinssfn,0) + COALESCE(ColCON.bdbinssfefolfn,0) - COALESCE(ColCON.bdbinssmvfn,0) else COALESCE(ColCON.bdbinssfn,0) + COALESCE(ColCON.bdbinssfefolfn,0) end, '||
            'case when coalesce(ColCON.bdbaseinssnmvnovo, 0) = 0 then COALESCE(ColCON.bdbinss13fn,0) - COALESCE(ColCON.bdbinssmv13fn,0) else COALESCE(ColCON.bdbinss13fn,0) end '||
         'FROM vrhf_emp_tfolhaint colcon '||
         'where colcon.bdreffn = '||prref;

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||' and '||premp;

       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;
     end

  for execute statement wsql into :BDSOMA, :BDCODEMP, :BDCODCOL, :BDREF, :BDCODTPCC, :BDCODCENTRO, :BDBASEFGTSFN, :BDBASEFGTS13, :BDFGTSFN, :BDFGTS13, :BDINSSFN, :BDINSS13,
     :BDBINSS13R, :BDSALFAMFN, :BDBINSSC13, :BDBINSSAPFN, :BDBINSS13APFN, :BDINSSAPFN, :BDINSS13APFN, :BDINSS13DT, :BDINSSC13, :BDINSSMV, :wcodaux, :wbaseinss, :wbaseinss13
  do
    begin
      if (prref >= 201508) then
         begin
           BDBINSSFN  = 0;
           BDBINSS13 = 0;
     
           for select FN.BDVALVFN, VR.BDINSSVER, VR.BDBASEGPSVER, VR.BDTIPOCODVER
               from VRHF_EMP_TVERBAINT FN
               left outer join VW_TVERBAS_REF VR on (VR.BDCODVER = FN.BDCODVER)
               where FN.BDCODEMP = :BDCODEMP and FN.BDCODCOL = :BDCODCOL and FN.BDREFFN = :BDREF and FN.BDCODCONTTI = :wcodaux
           into :wval13, :winssver, :wgpsver, :wtipover do
             begin
               wval13   = coalesce(:wval13, 0);
               wgpsver  = upper(coalesce(:wgpsver, 'FALSE'));
               winssver = coalesce(:winssver, 0);
               wtipover = coalesce(:wtipover, 0);
     
               if (wgpsver = 'TRUE') then
                  begin
                    if (winssver = 3) then
                       begin
                         if (wtipover = 0) then
                            BDBINSS13 = BDBINSS13 + :wval13;
                         else
                         if (wtipover = 1) then
                            BDBINSS13 = BDBINSS13 - :wval13;
                       end
                    else
                       begin
                         if (wtipover = 0) then
                            BDBINSSFN = BDBINSSFN + :wval13;
                         else
                         if (wtipover = 1) then
                            BDBINSSFN = BDBINSSFN - :wval13;
                       end
                  end
             end
         end
      else
         begin
           BDBINSSFN  = wbaseinss;
           BDBINSS13  = wbaseinss13;
         end

      if (BDBINSSFN < 0) then
         BDBINSSFN = 0;

      if (BDBINSS13 < 0) then
         BDBINSS13 = 0;

      suspend;
    end

  wsql = 'SELECT 100 bdsoma, ColCON.bdcodemp, ColCON.bdcodcol, ColCON.bdreftomador, pf.bdcodtpcc, CASE WHEN pf.bdcodtpcc IS NULL THEN NULL ELSE pf.bdcodcentro END, '||
            'CASE WHEN (COALESCE(ColCON.bdbfgtsft, 0) + COALESCE(ColCON.bdbfgtsfeft, 0) < 0) THEN 0 ELSE COALESCE(ColCON.bdbfgtsft,0) END +CASE WHEN (ColCON.bdbfgtsfeft < 0) THEN 0 ELSE COALESCE(ColCON.bdbfgtsfeft,0) END, '||
            'CASE WHEN (ColCON.bdbfgts13ft < 0) THEN 0 ELSE COALESCE(ColCON.bdbfgts13ft,0) END, '||
            'CASE WHEN (COALESCE(ColCON.bdfgtsft, 0) + COALESCE(ColCON.bdfgtsfeft, 0) < 0) THEN 0 ELSE COALESCE(ColCON.bdfgtsft,0) END + CASE WHEN (ColCON.bdfgtsfeft < 0) THEN 0 ELSE COALESCE(ColCON.bdfgtsfeft,0) END, '||
            'CASE WHEN (ColCON.bdfgts13ft < 0) THEN 0 ELSE COALESCE(ColCON.bdfgts13ft,0) END, '||
            '(COALESCE(ColCON.bdinssft,0) + COALESCE(ColCON.bdinssfefolft,0)), '||
            'COALESCE(ColCON.bdinss13ft,0), '||
--            'case when coalesce(ColCON.bdbaseinssnmvnovo, 0) = 0 then COALESCE(ColCON.bdbinssft,0) + COALESCE(ColCON.bdbinssfefolft,0) - COALESCE(ColCON.bdbinssmvft,0) else COALESCE(ColCON.bdbinssft,0) + COALESCE(ColCON.bdbinssfefolft,0) end, '||
            '0 bdbinss13, '||
--            'case when coalesce(ColCON.bdbaseinss13mvnovo, 0) = 0 then COALESCE(ColCON.bdbinss13ft,0)  - COALESCE(ColCON.bdbinssmv13ft,0) else COALESCE(ColCON.bdbinss13ft,0) end, '||
            'COALESCE(ColCON.bdsalfamft,0) + COALESCE(ColCON.bdcovid19ft, 0) bdsalfamft, '||
            '0 bdbinssc13, '||
            'CASE '||
              'WHEN (ColCON.bdbinssapft IS NULL) OR (ColCON.bdbinssapft = 0) THEN 0 '||
              'ELSE COALESCE(ColCON.bdbinssapft,0) + COALESCE(ColCON.bdbinssfefolft,0) '||
            'END, '||
            'COALESCE(ColCON.bdbinss13apft,0), '||
            'CASE '||
              'WHEN (ColCON.bdinssapft IS NULL) OR (ColCON.bdinssapft = 0) THEN 0 '||
              'ELSE COALESCE(ColCON.bdinssapft,0) + COALESCE(ColCON.bdinssfefolft,0) '||
            'END, '||
            'COALESCE(ColCON.bdinss13apft,0), '||
            '0 BDINSS13DT, '||
            '0 BDINSSC13, '||
            'colcon.BDBASEINSSNMVNOVO, '||
            'colcon.bdordem, '||
            'case when coalesce(ColCON.bdbaseinssnmvnovo, 0) = 0 then COALESCE(ColCON.bdbinssft,0) + COALESCE(ColCON.bdbinssfefolft,0) - COALESCE(ColCON.bdbinssmvft,0) else COALESCE(ColCON.bdbinssft,0) + COALESCE(ColCON.bdbinssfefolft,0) end, '||
            'case when coalesce(ColCON.bdbaseinss13mvnovo, 0) = 0 then COALESCE(ColCON.bdbinss13ft,0)  - COALESCE(ColCON.bdbinssmv13ft,0) else COALESCE(ColCON.bdbinss13ft,0) end '||
         'FROM vrhf_emp_tfolhatomador colcon '||
         'join vrhf_emp_tprepfn pf on (pf.bdcodemp = colcon.bdcodemp and pf.bdcodcol = colcon.bdcodcol and pf.bdordem = colcon.bdordem) '||
         'WHERE colcon.bdreftomador = '||prref;

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||' and '||premp;

       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;
     end

  for execute statement wsql into :BDSOMA, :BDCODEMP, :BDCODCOL, :BDREF, :BDCODTPCC, :BDCODCENTRO, :BDBASEFGTSFN, :BDBASEFGTS13, :BDFGTSFN, :BDFGTS13, :BDINSSFN, :BDINSS13,
     :BDBINSS13, :BDSALFAMFN, :BDBINSSC13, :BDBINSSAPFN, :BDBINSS13APFN, :BDINSSAPFN, :BDINSS13APFN, :BDINSS13DT, :BDINSSC13, :BDINSSMV, :wordem, :wbaseinss, :wbaseinss13
  do
    begin
      if (prref >= 201508) then
         begin
           BDBINSSFN  = 0;
           BDBINSS13R = 0;
     
           for select FN.BDVALVFT, VR.BDINSSVER, VR.BDBASEGPSVER, VR.BDTIPOCODVER
               from VRHF_EMP_TVERBATOMADOR FN
               left outer join VW_TVERBAS_REF VR on (VR.BDCODVER = FN.BDCODVER)
               where FN.BDCODEMP = :BDCODEMP and FN.BDCODCOL = :BDCODCOL and FN.BDREFTOMADOR = :BDREF and FN.BDORDEM = :wordem
           into :wval13, :winssver, :wgpsver, :wtipover do
             begin
               wval13   = coalesce(:wval13, 0);
               wgpsver  = upper(coalesce(:wgpsver, 'FALSE'));
               winssver = coalesce(:winssver, 0);
               wtipover = coalesce(:wtipover, 0);
     
               if (wgpsver = 'TRUE') then
                  begin
                    if (winssver = 3) then
                       begin
                         if (wtipover = 0) then
                            BDBINSS13R = BDBINSS13R + :wval13;
                         else
                         if (wtipover = 1) then
                            BDBINSS13R = BDBINSS13R - :wval13;
                       end
                    else
                       begin
                         if (wtipover = 0) then
                            BDBINSSFN = BDBINSSFN + :wval13;
                         else
                         if (wtipover = 1) then
                            BDBINSSFN = BDBINSSFN - :wval13;
                       end
                  end
             end
         end
      else
         begin
           BDBINSSFN  = wbaseinss;
           BDBINSS13R = wbaseinss13;
         end

      if (BDBINSSFN < 0) then
         BDBINSSFN = 0;

      if (BDBINSS13R < 0) then
         BDBINSS13R = 0;

      suspend;
    end

  wsql = 'SELECT 100 bdsoma, ColCON.bdcodemp, ColCON.bdcodcol, ColCON.bdreftomador, pf.bdcodtpcc, CASE WHEN pf.bdcodtpcc IS NULL THEN NULL ELSE pf.bdcodcentro END, '||
            'CASE WHEN (COALESCE(ColCON.bdbfgtsft, 0) + COALESCE(ColCON.bdbfgtsfeft, 0) < 0) THEN 0 ELSE COALESCE(ColCON.bdbfgtsft,0) END + MAXVALUE(0, COALESCE(ColCON.bdbfgtsfeft,0)), '||
            'MAXVALUE(0, COALESCE(ColCON.bdbfgts13ft,0)), '||
            'CASE WHEN (COALESCE(ColCON.bdfgtsft, 0) + COALESCE(ColCON.bdfgtsfeft, 0) + COALESCE(ColCON.bdfgts13ft,0) < 0) THEN 0 ELSE COALESCE(ColCON.bdfgtsft,0) + COALESCE(ColCON.bdfgts13ft,0) END + CASE WHEN (ColCON.bdfgtsfeft < 0) THEN 0 ELSE COALESCE(ColCON.bdfgtsfeft,0) END, '||
            '0, '||
            '(COALESCE(ColCON.bdinssft,0) + COALESCE(ColCON.bdinssfefolft,0) + COALESCE(ColCON.bdinss13ft,0)), '||
            '0, '||
--            'case when coalesce(ColCON.bdbaseinssnmvnovo, 0) = 0 then COALESCE(ColCON.bdbinssft,0) + COALESCE(ColCON.bdbinssfefolft,0) - COALESCE(ColCON.bdbinssmvft,0) + COALESCE(ColCON.bdbinss13ft,0)  - COALESCE(ColCON.bdbinssmv13ft,0) else COALESCE(ColCON.bdbinssft,0) + COALESCE(ColCON.bdbinssfefolft,0) + COALESCE(ColCON.bdbinss13ft,0) end, '||
--            'case when coalesce(ColCON.bdbaseinssnmvnovo, 0) = 0 then COALESCE(ColCON.bdbinss13ft,0) - COALESCE(ColCON.bdbinssmv13ft,0) else COALESCE(ColCON.bdbinss13ft,0) end, '||
            '0, '||
            'COALESCE(ColCON.bdsalfamft,0) + COALESCE(ColCON.bdcovid19ft,0) bdsalfamft, '||
            '0 bdbinssc13, '||
            'CASE '||
              'WHEN (ColCON.bdbinssapft IS NULL) OR (ColCON.bdbinssapft = 0) THEN 0 '||
              'ELSE COALESCE(ColCON.bdbinssapft,0) + COALESCE(ColCON.bdbinssfefolft,0) + COALESCE(ColCON.bdbinss13apft,0) '||
            'END, '||
            '0, '||
            'CASE '||
              'WHEN (ColCON.bdinssapft IS NULL) OR (ColCON.bdinssapft = 0) THEN 0 '||
              'ELSE COALESCE(ColCON.bdinssapft,0) + COALESCE(ColCON.bdinssfefolft,0) + COALESCE(ColCON.bdinss13apft,0) '||
            'END, '||
            '0, '||
            '0 BDINSS13DT, '||
            '0 BDINSSC13, '||
            'colcon. BDBASEINSSNMVNOVO, '||
            'colcon.bdcodcontti, '||
            'colcon.bdordem, '||
            'case when coalesce(ColCON.bdbaseinssnmvnovo, 0) = 0 then COALESCE(ColCON.bdbinssft,0) + COALESCE(ColCON.bdbinssfefolft,0) - COALESCE(ColCON.bdbinssmvft,0) + COALESCE(ColCON.bdbinss13ft,0)  - COALESCE(ColCON.bdbinssmv13ft,0) else COALESCE(ColCON.bdbinssft,0) + COALESCE(ColCON.bdbinssfefolft,0) + COALESCE(ColCON.bdbinss13ft,0) end, '||
            'case when coalesce(ColCON.bdbaseinssnmvnovo, 0) = 0 then COALESCE(ColCON.bdbinss13ft,0) - COALESCE(ColCON.bdbinssmv13ft,0) else COALESCE(ColCON.bdbinss13ft,0) end '||
         'FROM vrhf_emp_tfolhatomint colcon '||
         'join vrhf_emp_tprepfn pf on (ColCON.bdcodemp = pf.bdcodemp AND ColCON.bdcodcol = pf.bdcodcol AND ColCON.bdordem = pf.bdordem) '||
         'where colcon.bdreftomador = '||prref;

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||' and '||premp;

       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;
     end

  for execute statement wsql into :BDSOMA, :BDCODEMP, :BDCODCOL, :BDREF, :BDCODTPCC, :BDCODCENTRO, :BDBASEFGTSFN, :BDBASEFGTS13, :BDFGTSFN, :BDFGTS13, :BDINSSFN, :BDINSS13,
     :BDBINSS13R, :BDSALFAMFN, :BDBINSSC13, :BDBINSSAPFN, :BDBINSS13APFN, :BDINSSAPFN, :BDINSS13APFN, :BDINSS13DT, :BDINSSC13, :BDINSSMV, :wcodaux, :wordem, :wbaseinss, :wbaseinss13
  do
    begin
      if (prref >= 201508) then
         begin
           BDBINSSFN  = 0;
           BDBINSS13 = 0;
     
           for select FN.BDVALVFT, VR.BDINSSVER, VR.BDBASEGPSVER, VR.BDTIPOCODVER
               from VRHF_EMP_TVERBATOMINT FN
               left outer join VW_TVERBAS_REF VR on (VR.BDCODVER = FN.BDCODVER)
               where FN.BDCODEMP = :BDCODEMP and FN.BDCODCOL = :BDCODCOL and FN.BDREFTOMADOR = :BDREF and FN.BDORDEM = :wordem and FN.BDCODCONTTI = :wcodaux
           into :wval13, :winssver, :wgpsver, :wtipover do
             begin
               wval13   = coalesce(:wval13, 0);
               wgpsver  = upper(coalesce(:wgpsver, 'FALSE'));
               winssver = coalesce(:winssver, 0);
               wtipover = coalesce(:wtipover, 0);
     
               if (wgpsver = 'TRUE') then
                  begin
                    if (winssver = 3) then
                       begin
                         if (wtipover = 0) then
                            BDBINSS13 = BDBINSS13 + :wval13;
                         else
                         if (wtipover = 1) then
                            BDBINSS13 = BDBINSS13 - :wval13;
                       end
                    else
                       begin
                         if (wtipover = 0) then
                            BDBINSSFN = BDBINSSFN + :wval13;
                         else
                         if (wtipover = 1) then
                            BDBINSSFN = BDBINSSFN - :wval13;
                       end
                  end
             end
         end
      else
         begin
           BDBINSSFN = wbaseinss;
           BDBINSS13 = wbaseinss13;
         end

      if (BDBINSSFN < 0) then
         BDBINSSFN = 0;

      if (BDBINSS13 < 0) then
         BDBINSS13 = 0;

      suspend;
    end
end^


/* Restore proc. body: SP_VRHF_FGTSSEFIP_AGRUPA_3 */
create or alter procedure SP_VRHF_FGTSSEFIP_AGRUPA_3 (
    PREMP varchar(30000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODTPCC integer,
    BDCODCENTRO integer,
    BDBASEFGTSFN numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDFGTSFN numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDINSSFN numeric(18,6),
    BDINSS13 numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSS13 numeric(18,6),
    BDBINSS13R numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDBINSSC13 numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSS13DT numeric(18,6),
    BDINSSC13 numeric(18,6),
    BDINSSMV numeric(18,6))
as
declare variable WSQL varchar(32700);
begin
  wsql = 'SELECT colCON.bdcodemp, colCON.bdcodcol, colCON.bdref, toma.bdcodtpcc, colCON.bdcodcentro, '||
                'SUM(colCON.bdbasefgtsfn) bdbasefgtsfn, '||
                'SUM(colCON.bdbasefgts13) bdbasefgts13, '||
                'SUM(colCON.bdfgtsfn) bdfgtsfn, '||
                'SUM(colCON.bdfgts13) bdfgts13, '||
                'SUM(colCON.bdinssfn) bdinssfn, '||
                'SUM(colCON.bdinss13) bdinss13, '||
                'SUM(colCON.bdbinssfn) bdbinssfn, '||
                'SUM(colCON.bdbinss13) bdbinss13, '||
                'SUM(colCON.bdbinss13r) bdbinss13r, '||
                'SUM(colCON.bdsalfamfn) bdsalfamfn, '||
                'SUM(colCON.bdbinssc13) bdbinssc13, '||
                'SUM(colCON.bdbinssapfn) bdbinssapfn, '||
                'SUM(colCON.bdbinss13apfn) bdbinss13apfn, '||
                'SUM(colCON.bdinssapfn) bdinssapfn, '||
                'SUM(colCON.bdinss13apfn) bdbinss13apfn, '||
                'SUM(colCON.bdinss13DT) bdinss13DT, '||
                'SUM(colCON.bdinssc13) bdinssc13, '||
                'SUM(bdinssmv) bdinssmv '||
         'FROM SP_VRHF_FGTSSEFIP(';

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||''''||premp||''',';

       if (coalesce(prcol, '') <> '') then
          wsql = wsql||''''||prcol||''',';
       else
          wsql = wsql||'null,';

     end
  else
     wsql = wsql||'null,null,';

  wsql = wsql||prref||') colcon '||
         'left outer join vrhf_sp_tomador(colCON.bdcodtpcc,colCON.bdcodcentro) toma ON (toma.bdcodcencus = colCON.bdcodtpcc AND toma.bdcodcentro = colCON.bdcodcentro) '||
         'GROUP BY colCON.bdcodemp, colCON.bdcodcol, colCON.bdref, colCON.bdcodcentro, toma.bdcodtpcc ';

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDREF, :BDCODTPCC, :BDCODCENTRO, :BDBASEFGTSFN, :BDBASEFGTS13, :BDFGTSFN, :BDFGTS13, :BDINSSFN, :BDINSS13,
     :BDBINSSFN, :BDBINSS13, :BDBINSS13R, :BDSALFAMFN, :BDBINSSC13, :BDBINSSAPFN, :BDBINSS13APFN, :BDINSSAPFN, :BDINSS13APFN, :BDINSS13DT, :BDINSSC13, :BDINSSMV
  do
    suspend;
end^

/* Restore proc body: SP_VRHF_FGTSSEFIP_AGRUPA_1 */
create or alter procedure SP_VRHF_FGTSSEFIP_AGRUPA_1 (
    PREMP varchar(30000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODTPCC integer,
    BDCODCENTRO integer,
    BDBASEFGTSFN numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDFGTSFN numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDINSSFN numeric(18,6),
    BDINSS13 numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSS13 numeric(18,6),
    BDBINSS13R numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDBINSSC13 numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSS13DT numeric(18,6),
    BDINSSC13 numeric(18,6),
    BDINSSMV numeric(18,6))
as
declare variable WSQL varchar(32700);
begin
  wsql = 'SELECT bdcodemp,bdcodcol, bdref, NULL bdcodtpcc, NULL bdcodcentro, '||
                'SUM(bdbasefgtsfn) bdbasefgtsfn, '||
                'SUM(bdbasefgts13) bdbasefgts13, '||
                'SUM(bdfgtsfn) bdfgtsfn, '||
                'SUM(bdfgts13) bdfgts13, '||
                'SUM(bdinssfn) bdinssfn, '||
                'SUM(bdinss13) bdinss13, '||
                'SUM(bdbinssfn) bdbinssfn, '||
                'SUM(bdbinss13) bdbinss13, '||
                'SUM(bdbinss13r) bdbinss13r, '||
                'SUM(bdsalfamfn) bdsalfamfn, '||
                'SUM(bdbinssc13) bdbinssc13, '||
                'SUM(bdbinssapfn) bdbinssapfn, '||
                'SUM(bdbinss13apfn) bdbinss13apfn, '||
                'SUM(bdinssapfn) bdinssapfn, '||
                'SUM(bdinss13apfn) bdinss13apfn, '||
                'SUM(bdinss13dt) bdinss13dt, '||
                'SUM(bdinssc13) bdinssc13, '||
                'SUM(bdinssmv) bdinssmv '||
         'FROM SP_VRHF_FGTSSEFIP(';

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||''''||premp||''',';

       if (coalesce(prcol, '') <> '') then
          wsql = wsql||''''||prcol||''',';
       else
          wsql = wsql||'null,';

     end
  else
     wsql = wsql||'null,null,';

  wsql = wsql||prref||') '||
         'GROUP BY bdcodemp,bdcodcol, bdref ';

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDREF, :BDCODTPCC, :BDCODCENTRO, :BDBASEFGTSFN, :BDBASEFGTS13, :BDFGTSFN, :BDFGTS13, :BDINSSFN, :BDINSS13,
     :BDBINSSFN, :BDBINSS13, :BDBINSS13R, :BDSALFAMFN, :BDBINSSC13, :BDBINSSAPFN, :BDBINSS13APFN, :BDINSSAPFN, :BDINSS13APFN, :BDINSS13DT, :BDINSSC13, :BDINSSMV
  do
    suspend;
end^

/* Restore proc. body: SP_VRHF_FGTSSEFIP_AGRUPA_CC_MES */
create or alter procedure SP_VRHF_FGTSSEFIP_AGRUPA_CC_MES (
    PREMP varchar(30000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCODTPCC integer,
    BDCODCENTRO integer,
    BDBASEFGTSFN numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDFGTSFN numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDINSSFN numeric(18,6),
    BDINSS13 numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDBINSS13 numeric(18,6),
    BDBINSS13R numeric(18,6),
    BDSALFAMFN numeric(18,6),
    BDBINSSC13 numeric(18,6),
    BDBINSSAPFN numeric(18,6),
    BDBINSS13APFN numeric(18,6),
    BDINSSAPFN numeric(18,6),
    BDINSS13APFN numeric(18,6),
    BDINSS13DT numeric(18,6),
    BDINSSC13 numeric(18,6),
    BDINSSMV numeric(18,6))
as
declare variable WSQL varchar(32700);
begin
  wsql = 'SELECT colCON.bdcodemp,colCON.bdcodcol, bdref, COALESCE(colCON.bdcodtpcc,a.bdcodtpcc) bdcodtpccx, '||
                'COALESCE(colCON.bdcodcentro,CASE WHEN a.bdcodtpcc IS NULL THEN NULL ELSE a.bdcodcentro END) bdcodcentrox, '||
                'SUM(bdbasefgtsfn) bdbasefgtsfn, '||
                'SUM(bdbasefgts13) bdbasefgts13, '||
                'SUM(bdfgtsfn) bdfgtsfn, '||
                'SUM(bdfgts13) bdfgts13, '||
                'SUM(bdinssfn) bdinssfn, '||
                'SUM(bdinss13) bdinss13, '||
                'SUM(bdbinssfn) bdbinssfn, '||
                'SUM(bdbinss13) bdbinss13, '||
                'SUM(bdbinss13r) bdbinss13r, '||
                'SUM(bdsalfamfn) bdsalfamfn, '||
                'SUM(bdbinssc13) bdbinssc13, '||
                'SUM(bdbinssapfn) bdbinssapfn, '||
                'SUM(bdbinss13apfn) bdbinss13apfn, '||
                'SUM(bdinssapfn) bdinssapfn, '||
                'SUM(bdinss13apfn) bdinss13apfn, '||
                'SUM(BDINSS13DT) BDINSS13DT, '||
                'SUM(BDINSSC13) BDINSSC13, '||
                'SUM(BDINSSMV) BDINSSMV '||
         'FROM SP_VRHF_FGTSSEFIP(';

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||''''||premp||''',';

       if (coalesce(prcol, '') <> '') then
          wsql = wsql||''''||prcol||''',';
       else
          wsql = wsql||'null,';

     end
  else
     wsql = wsql||'null,null,';

  wsql = wsql||prref||') colcon '||
         'LEFT OUTER JOIN sp_vrh_cc_data( '||
          'colCON.bdcodemp,colCON.bdcodcol,SUBSTRING(''''||colCON.bdref FROM 5 FOR 2)||''/''||(SELECT ultdia '||
          'FROM ULTIMO_DIA_MES(CAST(SUBSTRING(''''||colCON.bdref FROM 5 FOR 2) AS SMALLINT), '||
          'CAST(SUBSTRING(''''||colCON.bdref FROM 1 FOR 4) AS INTEGER)))||''/''||SUBSTRING(''''||colCON.bdref FROM 1 FOR 4)) a '||
          'ON (colCON.bdcodemp = a.bdcodemp AND colCON.bdcodcol = a.bdcodcol AND colCON.bdcodtpcc IS NULL AND colCON.bdsoma NOT IN (2,10,100)) '||
         'GROUP BY colCON.bdcodemp,colCON.bdcodcol, bdref, bdcodtpccx, bdcodcentrox ';


  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDREF, :BDCODTPCC, :BDCODCENTRO, :BDBASEFGTSFN, :BDBASEFGTS13, :BDFGTSFN, :BDFGTS13, :BDINSSFN, :BDINSS13,
     :BDBINSSFN, :BDBINSS13, :BDBINSS13R, :BDSALFAMFN, :BDBINSSC13, :BDBINSSAPFN, :BDBINSS13APFN, :BDINSSAPFN, :BDINSS13APFN, :BDINSS13DT, :BDINSSC13, :BDINSSMV
  do
    suspend;
end^

CREATE OR ALTER trigger vrh_base_plano_alerta_venc_bi0 for vrh_base_plano_alerta_venc
active before insert position 0
AS
 declare variable vcod INTEGER;
BEGIN
   if (COALESCE(new.BDCODPAV, 0) = 0) then
     begin
       select COALESCE(MAX(BDCODPAV) + 1, 1) from VRH_BASE_PLANO_ALERTA_VENC into :vcod;
       new.BDCODPAV = :vcod;
     end
END^

create or alter procedure SP_REPLICA_COMPETENCIAS (
    PRCODEMP integer,
    PRREFEMP integer,
    PRTABELA varchar(60) = 'TEMPRESAS_REF')
as
declare variable VTABELA varchar(60);
declare variable VFK_NAME varchar(60);
declare variable VFK_TABLE varchar(60);
declare variable VONFIELD varchar(60);
declare variable VFIELDS varchar(1000);
declare variable VINSERT varchar(3000);
declare variable VCOUNT integer;
declare variable WSQL varchar(200);
declare variable VCODEMP integer;
declare variable VREFEMP integer;
declare variable VORDERBY varchar(60);
declare variable VREFEMPAUX integer;
begin
  wsql = 'select bdcodemp, bdrefemp from '||prtabela;
  if ((prcodemp is not null) and (prcodemp > 0)) then
     wsql = wsql||' where(bdcodemp = '||prcodemp||')';
  if ((prrefemp is not null) and (prrefemp > 0)) then
     wsql = wsql||iif(position('WHERE', upper(wsql))=0,' where'||'(bdrefemp = '||prrefemp||')',' and'||'(bdrefemp = '||prrefemp||')');
  wsql = wsql||' order by bdcodemp, bdrefemp';
  for execute statement wsql into :vcodemp, :vrefemp do
  begin
    for select trim(A.RDB$RELATION_NAME) as TABELA, trim(A.RDB$CONSTRAINT_NAME) as FK_NAME,
        --       A.RDB$CONSTRAINT_TYPE as TIPO, B.RDB$CONST_NAME_UQ as UQ_NAME, B.RDB$UPDATE_RULE as UPDATE_RULE, B.RDB$DELETE_RULE as DELETE_RULE, A.RDB$INDEX_NAME as IDX,
               trim(C.RDB$RELATION_NAME) as FK_TABLE,
        --       list(distinct trim(D.RDB$FIELD_NAME)) as FK_FIELD,
               list(distinct trim(E.RDB$FIELD_NAME)) as ONFIELD
        from RDB$REF_CONSTRAINTS B, RDB$RELATION_CONSTRAINTS A, RDB$RELATION_CONSTRAINTS C, RDB$INDEX_SEGMENTS D, RDB$INDEX_SEGMENTS E, RDB$INDICES I
        where (A.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY') and
              (A.RDB$CONSTRAINT_NAME = B.RDB$CONSTRAINT_NAME) and
              (B.RDB$CONST_NAME_UQ = C.RDB$CONSTRAINT_NAME) and
              (C.RDB$INDEX_NAME = D.RDB$INDEX_NAME) and
              (A.RDB$INDEX_NAME = E.RDB$INDEX_NAME) and
              (A.RDB$INDEX_NAME = I.RDB$INDEX_NAME)
              and (C.RDB$RELATION_NAME = :prtabela)
        group by 1, 2, 3
        order by trim(A.RDB$RELATION_NAME), trim(A.RDB$CONSTRAINT_NAME)
        into :vtabela, :vfk_name, :vfk_table, :vonfield do
    begin
      if (position('BDREFEMP', vonfield) > 0) then
      begin
        execute statement 'select count(BDREFEMP) from '||vtabela||' where bdcodemp = '||vcodemp||' and bdrefemp = '||vrefemp into :vcount;
        if (vcount = 0) then
        begin
          for select list(trim(rdb$field_name)) from rdb$relation_fields where rdb$relation_name = :vtabela
              into :vfields do
          begin
            -- foi necessário adicionar o campo TBLOQCTA na ordenação, pois no FB3, a consulta na tabela TBLOQCTA estava vindo com a ordenação
            -- diferente da tabela TBLOQCTA_USUARIO, ocasionando erro de chave estrangeira ao inserir o novo registro
            vorderby = '';
            if (upper(vtabela) = 'TBLOQCTA' or upper(vtabela) = 'TBLOQCTA_USUARIO') then
                vorderby = ', bdcodblq';

            vinsert = 'insert into '||vtabela||'('||vfields||')';
            vfields = replace(vfields, 'BDREFEMP', vrefemp||' as BDNEWREFEMP');-- se colocar como BDREFEMP em algumas tabelas não traz o registro certo
            vinsert = vinsert||'select first 1 '||vfields||' from '||vtabela;
            vinsert = vinsert||' where bdcodemp = '||vcodemp;
            vinsert = vinsert||' and bdrefemp < '||vrefemp;
            vinsert = vinsert||' order by bdrefemp'||vorderby||' desc';
            execute statement vinsert;
--            bdsql = :vinsert;

--            execute statement 'select count(bdrefemp) from '||vtabela||' where bdcodemp = '||vcodemp||' and bdrefemp < '||vrefemp into :vcount;
--            if (vcount > 0) then
--            begin
--              bdtabela_pai = vfk_table;
--              bdtabela_filha = vtabela;
--              bdcodemp = vcodemp;
--              bdrefemp = vrefemp;
--              suspend;
--            end
          end
--          for select bdtabela_pai, bdtabela_filha from sp_replica_competencias(:vcodemp, :vrefemp, :vtabela)
--              into :bdtabela_pai, :bdtabela_filha do
--              suspend;

          -- Não estava trazendo o registro correto de TBLOQCTA ao inserir na tabela TBLOQCTA_USUARIO e ocorria erro de FK.
          vinsert = 'select first 1 BDREFEMP from '||vtabela;
          vinsert = vinsert||' where bdcodemp = '||vcodemp;
          vinsert = vinsert||' and bdrefemp < '||vrefemp;
          vinsert = vinsert||' order by bdrefemp'||vorderby||' desc';
          execute statement vinsert into :vrefempaux;

          if (coalesce(:vrefempaux,0) > 0) then
             execute procedure sp_replica_competencias(:vcodemp, :vrefemp, :vtabela);
        end
      end
    end
  end
end^

create or alter procedure SP_LISTA_COMPETENCIAS_QUEBRADAS (
    PRTABELA varchar(33) = 'TEMPRESAS_REF',
    PRAPENAS_ULTIMA_COMPETENCIA smallint = 1)
returns (
    BDCODEMP integer,
    BDREFEMP integer,
    BDTABELA varchar(33),
    BDDESCRIPTION varchar(256),
    BDDEPENDENCIES varchar(33))
as
declare variable WINDEX varchar(128);
declare variable WSQL varchar(512);
declare variable WTABELA varchar(33);
begin
  for select trim(A.RDB$RELATION_NAME) as TABELA, T.RDB$DESCRIPTION,
             list(distinct trim(E.RDB$FIELD_NAME)) as ONFIELD
      from RDB$REF_CONSTRAINTS B, RDB$RELATION_CONSTRAINTS A,
           RDB$RELATION_CONSTRAINTS C, RDB$INDEX_SEGMENTS D,
           RDB$INDEX_SEGMENTS E, RDB$INDICES I,
           RDB$RELATIONS T
      where (A.RDB$CONSTRAINT_TYPE = 'FOREIGN KEY')
      and(A.RDB$CONSTRAINT_NAME = B.RDB$CONSTRAINT_NAME)
      and(B.RDB$CONST_NAME_UQ = C.RDB$CONSTRAINT_NAME)
      and(T.RDB$RELATION_NAME = A.RDB$RELATION_NAME)
      and(C.RDB$INDEX_NAME = D.RDB$INDEX_NAME)
      and(A.RDB$INDEX_NAME = E.RDB$INDEX_NAME)
      and(A.RDB$INDEX_NAME = I.RDB$INDEX_NAME)
      and(C.RDB$RELATION_NAME = upper(:prtabela))
      group by 1, 2
      order by trim(A.RDB$RELATION_NAME)
  into :wtabela, :bddescription, :windex do
  begin
    bdtabela = prtabela;
    bddependencies = wtabela;
    if ((position('BDREFEMP', windex) > 0)and(position('BDCODEMP', windex) > 0)) then
    begin
      wsql = 'select bdcodemp, ';
      if (prapenas_ultima_competencia > 0) then
         wsql = wsql||' max(bdrefemp) as ';
      wsql = wsql||' bdrefemp from '||prtabela;
      wsql = wsql||' x where(not exists(select first 1 bdcodemp from '||wtabela;
      wsql = wsql||' where bdcodemp=x.bdcodemp and bdrefemp=x.bdrefemp))';
      wsql = wsql||'and(exists(select first 1 bdcodemp from '||wtabela;
      wsql = wsql||' where bdcodemp=x.bdcodemp and bdrefemp<x.bdrefemp))';
      if (prapenas_ultima_competencia > 0) then
         wsql = wsql||'group by bdcodemp ';
      wsql = wsql||'order by bdcodemp, bdrefemp desc';
      for execute statement wsql into :bdcodemp, :bdrefemp do
        suspend;

      for select bdcodemp, bdrefemp, bdtabela, bddescription from sp_lista_competencias_quebradas(:wtabela, :prapenas_ultima_competencia)
          into :bdcodemp, :bdrefemp, bdtabela, bddescription do
          suspend;
    end
  end
end^

CREATE OR ALTER procedure SP_VFIN_EMPRESACLIENTE_REF (
    PRCODEMP integer,
    PRNEWREFEMP integer)
as
declare variable VFIELDS varchar(1000);
declare variable VINSERT varchar(3000);
begin
  if ((select bdcodemp from tempresas_ref where bdcodemp = :prcodemp and bdrefemp = :prnewrefemp) is null) then
  begin
    for select list(trim(rdb$field_name)) from rdb$relation_fields where rdb$relation_name = upper('TEMPRESAS_REF') into :vfields do
    begin
      vinsert = 'insert into tempresas_ref('||vfields||')';
      vfields = replace(vfields, 'BDREFEMP', prnewrefemp||' as BDNEWREFEMP');-- se colocar como BDREFEMP em algumas tabelas não traz o registro certo
      vinsert = vinsert||'select first 1 '||vfields||' from tempresas_ref';
      vinsert = vinsert||' where bdcodemp = '||prcodemp;
      vinsert = vinsert||' and bdrefemp < '||prnewrefemp;
      vinsert = vinsert||' order by bdrefemp desc';
      execute statement vinsert;
    end

    for select list(trim(rdb$field_name)) from rdb$relation_fields where rdb$relation_name = upper('TENQFED') into :vfields do
    begin
      vinsert = 'insert into TENQFED('||vfields||')';
      vfields = replace(vfields, 'BDREFEMP', prnewrefemp||' as BDNEWREFEMP');-- se colocar como BDREFEMP em algumas tabelas não traz o registro certo
      vinsert = vinsert||'select first 1 '||vfields||' from TENQFED';
      vinsert = vinsert||' where bdcodemp = '||prcodemp;
      vinsert = vinsert||' and bdrefemp < '||prnewrefemp;
      vinsert = vinsert||' order by bdrefemp desc';
      execute statement vinsert;
    end

    for select list(trim(rdb$field_name)) from rdb$relation_fields where rdb$relation_name = upper('VEF_BASE_TEMPCADATV') into :vfields do
    begin
      vinsert = 'insert into VEF_BASE_TEMPCADATV('||vfields||')';
      vfields = replace(vfields, 'BDREFEMP', prnewrefemp||' as BDNEWREFEMP');-- se colocar como BDREFEMP em algumas tabelas não traz o registro certo
      vinsert = vinsert||'select first 1 '||vfields||' from VEF_BASE_TEMPCADATV';
      vinsert = vinsert||' where bdcodemp = '||prcodemp;
      vinsert = vinsert||' and bdrefemp < '||prnewrefemp;
      vinsert = vinsert||' order by bdrefemp desc';
      execute statement vinsert;
    end

    for select list(trim(rdb$field_name)) from rdb$relation_fields where rdb$relation_name = upper('VEF_BASE_TEMPITEMSATV') into :vfields do
    begin
      vinsert = 'insert into VEF_BASE_TEMPITEMSATV('||vfields||')';
      vfields = replace(vfields, 'BDREFEMP', prnewrefemp||' as BDNEWREFEMP');-- se colocar como BDREFEMP em algumas tabelas não traz o registro certo
      vinsert = vinsert||'select first 1 '||vfields||' from VEF_BASE_TEMPITEMSATV';
      vinsert = vinsert||' where bdcodemp = '||prcodemp;
      vinsert = vinsert||' and bdrefemp < '||prnewrefemp;
      vinsert = vinsert||' order by bdrefemp desc';
      execute statement vinsert;
    end

    for select list(trim(rdb$field_name)) from rdb$relation_fields where rdb$relation_name = upper('TEMP_SPED_FCONT_REF') into :vfields do
    begin
      vinsert = 'insert into TEMP_SPED_FCONT_REF('||vfields||')';
      vfields = replace(vfields, 'BDREFEMP', prnewrefemp||' as BDNEWREFEMP');-- se colocar como BDREFEMP em algumas tabelas não traz o registro certo
      vinsert = vinsert||'select first 1 '||vfields||' from TEMP_SPED_FCONT_REF';
      vinsert = vinsert||' where bdcodemp = '||prcodemp;
      vinsert = vinsert||' and bdrefemp < '||prnewrefemp;
      vinsert = vinsert||' order by bdrefemp desc';
      execute statement vinsert;
    end

    for select list(trim(rdb$field_name)) from rdb$relation_fields where rdb$relation_name = upper('VEF_BASE_TEMPPARFED') into :vfields do
    begin
      vinsert = 'insert into VEF_BASE_TEMPPARFED('||vfields||')';
      vfields = replace(vfields, 'BDREFEMP', prnewrefemp||' as BDNEWREFEMP');-- se colocar como BDREFEMP em algumas tabelas não traz o registro certo
      vinsert = vinsert||'select first 1 '||vfields||' from VEF_BASE_TEMPPARFED';
      vinsert = vinsert||' where bdcodemp = '||prcodemp;
      vinsert = vinsert||' and bdrefemp < '||prnewrefemp;
      vinsert = vinsert||' order by bdrefemp desc';
      execute statement vinsert;
    end

    for select list(trim(rdb$field_name)) from rdb$relation_fields where rdb$relation_name = upper('VLAL_BASE_TEMP') into :vfields do
    begin
      vinsert = 'insert into VLAL_BASE_TEMP('||vfields||')';
      vfields = replace(vfields, 'BDREFEMP', prnewrefemp||' as BDNEWREFEMP');-- se colocar como BDREFEMP em algumas tabelas não traz o registro certo
      vinsert = vinsert||'select first 1 '||vfields||' from VLAL_BASE_TEMP';
      vinsert = vinsert||' where bdcodemp = '||prcodemp;
      vinsert = vinsert||' and bdrefemp < '||prnewrefemp;
      vinsert = vinsert||' order by bdrefemp desc';
      execute statement vinsert;
    end

    execute procedure sp_replica_competencias(:prcodemp, :prnewrefemp);
  end

  if ((select bdcodcli from vfin_base_tcliente_ref where bdcodcli = :prcodemp and bdrefcli = :prnewrefemp) is null) then
  begin
    for select list(trim(rdb$field_name)) from rdb$relation_fields where rdb$relation_name = upper('vfin_base_tcliente_ref') into :vfields do
    begin
      vinsert = 'insert into vfin_base_tcliente_ref('||vfields||')';
      vfields = replace(vfields, 'BDREFCLI', prnewrefemp||' as BDNEWREFCLI');-- se colocar como BDREFEMP em algumas tabelas não traz o registro certo
      vinsert = vinsert||'select first 1 '||vfields||' from vfin_base_tcliente_ref';
      vinsert = vinsert||' where bdcodcli = '||prcodemp;
      vinsert = vinsert||' and bdrefcli < '||prnewrefemp;
      vinsert = vinsert||' order by bdrefcli desc';
      execute statement vinsert;
    end
  end
end^

-- 146010 - Raphael Teodoro - 20/03/2021 - Rotina recursiva de "VRH_EMP_TSITCOL"
CREATE OR ALTER procedure SP_VRH_EMP_TSITCOLDEC_RECURSIVO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRDATAINISEFIP date,
    PRANTERIORES DM_BOOLEAN,
    PRRECURSIVIDADE smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATAINISEFIP date,
    BDCODEMPDEC integer,
    BDCODCOLDEC integer,
    BDDATAINISEFIPDEC date)
as
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WDATAINISEFIP date;
declare variable WCODEMPDEC integer;
declare variable WCODCOLDEC integer;
declare variable WDATAINISEFIPDEC date;
begin
  prrecursividade = coalesce(prrecursividade,0) + 1;

  if (prrecursividade <= 5) then
     begin
       if (COALESCE(pranteriores,'FALSE') = 'TRUE') then
          begin
            for select BDCODEMP, BDCODCOL, BDDATAINISEFIP,
                       BDCODEMPDEC, BDCODCOLDEC, BDDATAINISEFIPDEC
                from VRH_EMP_TSITCOL_DEC
                where (BDCODEMP = :prcodemp)
                  and (BDCODCOL = :prcodcol)
                  and (BDDATAINISEFIP = :prdatainisefip)
            into :wcodemp, :wcodcol, :wdatainisefip,
                 :wcodempdec, :wcodcoldec, :wdatainisefipdec do
              begin
                -- Recursividade
                for select BDCODEMP, BDCODCOL, BDDATAINISEFIP,
                           BDCODEMPDEC, BDCODCOLDEC, BDDATAINISEFIPDEC
                    from SP_VRH_EMP_TSITCOLDEC_RECURSIVO(:wcodempdec, :wcodcoldec, :wdatainisefipdec, :pranteriores, :prrecursividade)
                    into :BDCODEMP, :BDCODCOL, :BDDATAINISEFIP,
                         :BDCODEMPDEC, :BDCODCOLDEC, :BDDATAINISEFIPDEC do
                    suspend;
                    
                -- Registro atual
                BDCODEMP = wcodemp;
                BDCODCOL = wcodcol;
                BDDATAINISEFIP = wdatainisefip;
                BDCODEMPDEC = wcodempdec;
                BDCODCOLDEC = wcodcoldec;
                BDDATAINISEFIPDEC = wdatainisefipdec;
                suspend;
              end
          end
       else
          begin
            for select BDCODEMP, BDCODCOL, BDDATAINISEFIP,
                       BDCODEMPDEC, BDCODCOLDEC, BDDATAINISEFIPDEC
                from VRH_EMP_TSITCOL_DEC
                where (BDCODEMPDEC = :prcodemp)
                  and (BDCODCOLDEC = :prcodcol)
                  and (BDDATAINISEFIPDEC = :prdatainisefip)
            into :wcodemp, :wcodcol, :wdatainisefip,
                 :wcodempdec, :wcodcoldec, :wdatainisefipdec do
              begin
                -- Registro atual
                BDCODEMP = wcodemp;
                BDCODCOL = wcodcol;
                BDDATAINISEFIP = wdatainisefip;
                BDCODEMPDEC = wcodempdec;
                BDCODCOLDEC = wcodcoldec;
                BDDATAINISEFIPDEC = wdatainisefipdec;
                suspend;

                -- Recursividade
                for select BDCODEMP, BDCODCOL, BDDATAINISEFIP,
                           BDCODEMPDEC, BDCODCOLDEC, BDDATAINISEFIPDEC
                    from SP_VRH_EMP_TSITCOLDEC_RECURSIVO(:wcodemp, :wcodcol, :wdatainisefip, :pranteriores, :prrecursividade)
                    into :BDCODEMP, :BDCODCOL, :BDDATAINISEFIP,
                         :BDCODEMPDEC, :BDCODCOLDEC, :BDDATAINISEFIPDEC do
                    suspend;
              end
          end
     end
end^

-- 146010 - Raphael Teodoro - 20/03/2021 - Rotina para busca de todos os vínculos do afastamento
CREATE OR ALTER procedure SP_VRH_EMP_TSITCOL_VINCULADOS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRDATAINISEFIP date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATAINISEFIP date)
as
begin
  -- Busca anteriores
  for select BDCODEMPDEC, BDCODCOLDEC, BDDATAINISEFIPDEC
      from SP_VRH_EMP_TSITCOLDEC_RECURSIVO(:prcodemp, :prcodcol, :prdatainisefip, 'TRUE')
  into :BDCODEMP, :BDCODCOL, :BDDATAINISEFIP do
    suspend;

  -- Busca posteriores
  for select BDCODEMP, BDCODCOL, BDDATAINISEFIP
      from SP_VRH_EMP_TSITCOLDEC_RECURSIVO(:prcodemp, :prcodcol, :prdatainisefip, 'FALSE')
  into :BDCODEMP, :BDCODCOL, :BDDATAINISEFIP do
    suspend;
end^

CREATE OR ALTER TRIGGER vrhf_mvaut_bi0 FOR vrhf_mvaut
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE wCodigo INTEGER;
begin
  if (COALESCE(NEW.BDCODMVAUT,0) = 0) then
     begin
       wCodigo = NULL;
       select first 1 BDCODMVAUT
       from VRHF_MVAUT
       where (BDCPF = NEW.BDCPF)
       order by BDCPF desc, BDCODMVAUT desc
       into :wCodigo;
       NEW.BDCODMVAUT = COALESCE(wCodigo,0)+1;
     end
end^

CREATE OR ALTER procedure SP_REF_DIF (
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDDIF integer)
as
begin
  BDDIF = 0;
  IF (:PRREFINI < :PRREFFIM) THEN
    BEGIN
      WHILE (:PRREFINI <> :PRREFFIM) DO
        BEGIN
          BDDIF = :BDDIF + 1;
    
          IF (SUBSTRING(:PRREFINI FROM 5 FOR 2) = '12') THEN
            PRREFINI = CAST(CAST(SUBSTRING(:PRREFINI FROM 1 FOR 4) AS INTEGER) + 1 AS VARCHAR(4)) || '01';
          ELSE
            PRREFINI = :PRREFINI + 1;
        END
    END

  SUSPEND;
end^

CREATE OR ALTER trigger vef_base_tvincplanocat42sp_bi0 for vef_base_tvincplanocat42sp
active before insert position 0
AS
DECLARE VARIABLE wOrdem INTEGER;
begin
  IF (NEW.BDORDEM IS NULL) THEN
    BEGIN
      SELECT MAX(BDORDEM) + 1 FROM VEF_BASE_TVINCPLANOCAT42SP VP WHERE VP.BDCODPLACAT42SP = NEW.BDCODPLACAT42SP AND VP.BDCHAVE = NEW.BDCHAVE INTO :wOrdem;
      NEW.BDORDEM = COALESCE(:wOrdem,  1);
    END
end^

CREATE OR ALTER PROCEDURE SP_BUSCAR_NFE_DEVOLUCAO (
    PRCODEMP INTEGER,
    PRCHAVE INTEGER,
    PRTIPOMOV CHAR(3))
RETURNS (
    BDCHAVE INTEGER,
    BDCHAVEC113 INTEGER)
AS
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WCODDOCFIS VARCHAR(2);
DECLARE VARIABLE WINDEMIT INTEGER;
DECLARE VARIABLE WSERIE VARCHAR(6);
DECLARE VARIABLE WSUBSERIE VARCHAR(6);
DECLARE VARIABLE WNUMDOC INTEGER;
DECLARE VARIABLE WDTEMISSAO DATE;
DECLARE VARIABLE WCHAVENFE DM_CHAVENFE;
DECLARE VARIABLE WSQL VARCHAR(1048);
BEGIN
  BDCHAVEC113 = NULL;
  wSQL =         'SELECT C113.BDORDEMDOCFREF, COALESCE(C113.BDCODTER, 0), COALESCE(D.BDDOCFIS, ''''), COALESCE(C113.BDINDEMIT, -1), COALESCE(C113.BDSERIE, ''''), ';
  wSQL = wSQL ||        'COALESCE(C113.BDSUBSERIE, ''''), COALESCE(C113.BDNUMDOC, 0), C113.BDDTEMISSAO, COALESCE(C113.BDCHAVENFE, '''') ';
  wSQL = wSQL || 'FROM VEF_EMP_TMOV'||:PRTIPOMOV||' M ';
  wSQL = wSQL || 'JOIN VEF_EMP_TC100'||:PRTIPOMOV||' C100 ON(C100.BDCODEMP = M.BDCODEMP AND C100.BDCHAVE = M.BDCHAVE) ';
  wSQL = wSQL || 'JOIN (';
  wSQL = wSQL ||       ' SELECT FIRST 1 I.BDCODEMP, I.BDCHAVE, I.BDORDEMIC ';
  wSQL = wSQL ||       ' FROM VEF_EMP_TMOV'||:PRTIPOMOV||'INFCOM I ';
  wSQL = wSQL ||       ' WHERE I.BDCODEMP = '||:PRCODEMP;
  wSQL = wSQL ||       ' AND I.BDCHAVE = '||:PRCHAVE;
  wSQL = wSQL ||      ') C110 ON(C110.BDCODEMP = M.BDCODEMP AND C110.BDCHAVE = M.BDCHAVE) ';
  wSQL = wSQL || 'JOIN VEF_EMP_TMOV'||:PRTIPOMOV||'DOCFREF C113 ON(C113.BDCODEMP = C110.BDCODEMP AND C113.BDCHAVE = C110.BDCHAVE AND C113.BDORDEMIC = C110.BDORDEMIC AND C113.BDORDEMDOCFREF = ( ';
  wSQL = wSQL ||    'SELECT FIRST 1 C.BDORDEMDOCFREF ';
  wSQL = wSQL ||    'FROM VEF_EMP_TMOV'||:PRTIPOMOV||'DOCFREF C ';
  wSQL = wSQL ||    'WHERE C.BDCODEMP = C113.BDCODEMP ';
  wSQL = wSQL ||    'AND C.BDCHAVE = C113.BDCHAVE ';
  wSQL = wSQL ||    'AND C.BDORDEMIC = C113.BDORDEMIC ';
  wSQL = wSQL ||    ' ORDER BY C.BDORDEMDOCFREF ';
  wSQL = wSQL ||  ')) ';
  wSQL = :wSQL || 'LEFT OUTER JOIN VEF_BASE_TTABDOCFIS D ON(D.BDCODDOCFIS = C113.BDCODDOCFIS) ';
  wSQL = wSQL ||  'WHERE M.BDCODEMP = '||:PRCODEMP;
  wSQL = wSQL ||  'AND M.BDCHAVE = '||:PRCHAVE;

  EXECUTE STATEMENT :wSQL
  INTO :BDCHAVEC113, :wCodTer, :wCodDocFis, :wIndEmit,
       :wSerie, :wSubSerie, :wNumDoc, :wDtEmissao, :wChaveNFe;

  IF (:wNumDoc > 0) THEN
    BEGIN
      wSQL =          'SELECT MOV.BDCHAVE ';
      wSQL = :wSQL || 'FROM VEF_EMP_TMOV'||IIF(:PRTIPOMOV = 'ENT', 'SAI', 'ENT')||' MOV ';
      wSQL = :wSQL || 'WHERE MOV.BDCODEMP = '||:PRCODEMP;
    
      IF (:wCodTer > 0) THEN
        wSQL = :wSQL || ' AND MOV.BDCODTER = '||:wCodTer;
    
      IF (:wCodDocFis <> '') THEN
        wSQL = :wSQL || ' AND MOV.BDMODELO =  '||:wCodDocFis;
    
      IF (:wIndEmit > -1) THEN
        wSQL = :wSQL || ' AND MOV.BDEMITENTE =  '||:wIndEmit;
    
      IF (:wSerie <> '') THEN
        wSQL = :wSQL || ' AND MOV.BDSERIE = CAST('||:wSerie||' AS VARCHAR(6)) ';
    
      IF (:wSubSerie <> '') THEN
        wSQL = :wSQL || ' AND MOV.BDSUBSERIE = CAST('||:wSubSerie||' AS VARCHAR(6)) ';
    
      IF (:wNumDoc > 0) THEN
        wSQL = :wSQL || ' AND MOV.BDNUMDOCINI =  '||:wNumDoc;
    
      IF (:wDtEmissao IS NOT NULL) THEN
        wSQL = :wSQL || ' AND MOV.BDDATAEMISSAO =  '||''''||:wDtEmissao||'''';
    
      IF (:wChaveNFe <> '') THEN
        wSQL = :wSQL || ' AND MOV.BDCHAVENFE =  '||''''||:wChaveNFe||'''';
    
      EXECUTE STATEMENT :wSQL INTO :BDCHAVE;
    END
  SUSPEND;
END^

CREATE OR ALTER procedure SP_BUSCAR_NF_COMPRA_CAT42SP (
    PRCODEMP integer,
    PRDATASAIDA date,
    PRCODPROD integer)
returns (
    BDVLRST DM_NUMERIC_15_2,
    BDCHAVEENT integer,
    BDCHAVEINV integer)
as
declare variable WCHAVEMVA integer;
BEGIN
  BDCHAVEENT = NULL;
  BDCHAVEINV = NULL;
  BDVLRST    = 0;

  SELECT FIRST 1 LAN.BDVLRST, LAN.BDCHAVE
  FROM (
        SELECT P.BDCHAVE,
               SUM(
                   COALESCE(P.BDVLRST, 0) + 
                   COALESCE(P.BDFCPRETIDO, 0) +
                   COALESCE(P.BDVLRICMSSTRET, 0) +
                   COALESCE(P.BDVLRFCPSTRET, 0)
                  )  BDVLRST
        FROM (
              SELECT MOV.BDCODEMP, MOV.BDCHAVE
              FROM VEF_EMP_TMOVENT MOV
              WHERE MOV.BDCODEMP = :PRCODEMP
              AND MOV.BDDATAEMISSAO <= :PRDATASAIDA
             ) M
        JOIN VEF_EMP_TMOVPROENT P ON(P.BDCODEMP = M.BDCODEMP AND P.BDCHAVE = M.BDCHAVE AND P.BDCODPROD = :PRCODPROD)
        GROUP BY P.BDCODEMP, P.BDCHAVE, P.BDCODPROD
       ) LAN
  ORDER BY LAN.BDVLRST DESC
  INTO :BDVLRST, :BDCHAVEENT;

  wChaveMVA = NULL;
  SELECT FIRST 1 IVA.BDCHAVE
  FROM (
        SELECT MOV.BDCODEMP, MOV.BDCHAVE
        FROM VEF_EMP_TMOVENT MOV
        WHERE MOV.BDCODEMP = :PRCODEMP
        AND MOV.BDDATAEMISSAO <= :PRDATASAIDA
       ) M
  JOIN VEF_EMP_TMOVENT_IVA IVA ON(IVA.BDCODEMP = M.BDCODEMP AND IVA.BDCHAVE = M.BDCHAVE AND IVA.BDCODPROD = :PRCODPROD)
  GROUP BY IVA.BDCODEMP, IVA.BDCHAVE, IVA.BDCODPROD
  INTO :wChaveMVA;

  IF ((COALESCE(:BDVLRST, 0) > 0) OR (:wChaveMVA IS NOT NULL)) THEN
    SUSPEND;
  ELSE
    BEGIN
      SELECT FIRST 1 I.BDCHAVE, COALESCE(I.BDVLRICMSST, 0) BDVLRST
      FROM VEF_EMP_TMOVINV I
      WHERE I.BDCODEMP = :PRCODEMP
      AND I.BDREFINV = (SELECT BDREF FROM DEC_REF((SELECT BDDATA FROM SP_PARSE_DATE(:PRDATASAIDA, 'YYYYMM'))))
      AND I.BDCODPROD = :PRCODPROD
      ORDER BY BDVLRST DESC
      INTO :BDCHAVEINV, :BDVLRST;

      IF (COALESCE(:BDVLRST, 0) > 0) THEN
        SUSPEND;
      ELSE
        BEGIN
          BDCHAVEENT = NULL;
          BDCHAVEINV = NULL;
          SUSPEND;
        END
    END
END^

CREATE OR ALTER procedure SP_CAT42SP_REGRAS_INTERNAS (
    PRCODENQLEG integer,
    PRVLRICMSEFET DM_NUMERIC_15_2,
    PRCONSFINAL integer)
returns (
    BDVALID DM_BOOLEAN)
as
begin
  BDVALID = 'TRUE';

  IF (:PRCONSFINAL = -1) THEN
    SUSPEND;
  ELSE
    BEGIN
      IF (:PRCODENQLEG = 1) THEN
        BEGIN
          IF ((:PRCONSFINAL = 1) AND (COALESCE(:PRVLRICMSEFET, 0) > 0)) THEN
            SUSPEND;
          ELSE
            BEGIN
              BDVALID = 'FALSE';
              SUSPEND;
            END
        END
      ELSE
        BEGIN
          IF (:PRCODENQLEG = 5) THEN
            BEGIN
              IF (:PRCONSFINAL = 0) THEN
                SUSPEND;
              ELSE
                BEGIN
                  BDVALID = 'FALSE';
                  SUSPEND;
                END
            END
          ELSE
            SUSPEND;
        END
    END
end^

CREATE OR ALTER PROCEDURE SP_GET_VALORES_DEV (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRCODPROD INTEGER,
    PRCHAVE INTEGER,
    PRTIPOMOV CHAR(3))
RETURNS (
    BDVL_ICMS_SUP_ENT DM_NUMERIC_15_2,
    BDCODENQ INTEGER,
    BDVL_CONFRONTO DM_NUMERIC_15_2,
    BDVL_ICMS_MEDIO_SUP DM_NUMERIC_15_2,
    BDQTDITEM NUMERIC(15,6))
AS
DECLARE VARIABLE WREFLAN INTEGER;
DECLARE VARIABLE WSQL VARCHAR(1048);
BEGIN
  BDCODENQ = 0;
  BDVL_CONFRONTO = 0;
  BDVL_ICMS_MEDIO_SUP = 0;
  BDQTDITEM = 0;
  BDVL_ICMS_SUP_ENT = 0;

  IF (:PRCHAVE IS NOT NULL) THEN
    BEGIN
      wSQL =          ' SELECT MOV.BDREFLAN ';
      wSQL = :wSQL || ' FROM VEF_EMP_TMOV'||:PRTIPOMOV||' MOV ';
      wSQL = :wSQL || ' WHERE MOV.BDCODEMP = '||:PRCODEMP;
      wSQL = :wSQL || ' AND MOV.BDCHAVE = '||:PRCHAVE;
      EXECUTE STATEMENT :wSQL INTO :wRefLan;
    
      IF (:PRSESSAO > 0 AND :wRefLan = :PRREFERENCIA) THEN
        BEGIN
          wSQL =          ' SELECT AP.BDCODENQ, AP.BDVL_ICMS_MEDIO_SUP, AP.BDVL_CONFRONTO, MOV_SP.BDQTDITEM, AP.BDVL_ICMS_SUP_ENT ';
          wSQL = :wSQL || ' FROM TMP_TOL_VEF_EMP_DRCST_1100_TEMP D ';
          wSQL = :wSQL || ' JOIN TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP ON(AP.BDSESSAO = D.BDSESSAO AND AP.BDCODEMP = D.BDCODEMP AND AP.BDREFERENCIA = D.BDREFERENCIA AND AP.BDCODPROD = D.BDCODPROD AND AP.BDORDEM = D.BDORDEM) ';
          wSQL = :wSQL || ' JOIN VEF_EMP_TMOVPRO'||:PRTIPOMOV||' MOV_SP ON(MOV_SP.BDCODEMP = D.BDCODEMP AND MOV_SP.BDCHAVE = D.BDCHAVE'||:PRTIPOMOV||' AND MOV_SP.BDORDEM = D.BDORDEM'||:PRTIPOMOV||' AND MOV_SP.BDORDEMPRO = D.BDORDEMPRO'||:PRTIPOMOV||') ';
          wSQL = :wSQL || ' WHERE D.BDSESSAO =  '||:PRSESSAO;
          wSQL = :wSQL || ' AND D.BDCODEMP = '||:PRCODEMP;
          wSQL = :wSQL || ' AND D.BDREFERENCIA = '||:PRREFERENCIA;
          wSQL = :wSQL || ' AND D.BDCODPROD = '||:PRCODPROD;
          wSQL = :wSQL || ' AND D.BDCHAVE'||:PRTIPOMOV||' = '||:PRCHAVE;
          EXECUTE STATEMENT :wSQL INTO :BDCODENQ, :BDVL_ICMS_MEDIO_SUP, :BDVL_CONFRONTO, :BDQTDITEM, :BDVL_ICMS_SUP_ENT;
        END
      ELSE
        BEGIN
          wSQL =          ' SELECT FIRST 1 AP.BDCODENQ, AP.BDVL_ICMS_MEDIO_SUP, AP.BDVL_CONFRONTO, MOV_SP.BDQTDITEM, AP.BDVL_ICMS_SUP_ENT ';
          wSQL = :wSQL || ' FROM TOL_VEF_EMP_DRCSTSP_1100 D ';
          wSQL = :wSQL || ' JOIN VEF_EMP_TDRCSTSP_1100 AP ON(AP.BDCODEMP = D.BDCODEMP AND AP.BDREFERENCIA = D.BDREFERENCIA AND AP.BDCODPROD = D.BDCODPROD AND AP.BDORDEM = D.BDORDEM) ';
          wSQL = :wSQL || ' JOIN VEF_EMP_TMOVPRO'||:PRTIPOMOV||' MOV_SP ON(MOV_SP.BDCODEMP = D.BDCODEMP AND MOV_SP.BDCHAVE = D.BDCHAVE'||:PRTIPOMOV||' AND MOV_SP.BDORDEM = D.BDORDEM'||:PRTIPOMOV||' AND MOV_SP.BDORDEMPRO = D.BDORDEMPRO'||:PRTIPOMOV||') ';
          wSQL = :wSQL || ' WHERE D.BDCODEMP = '||:PRCODEMP;
          wSQL = :wSQL || ' AND D.BDREFERENCIA <= '||:PRREFERENCIA;
          wSQL = :wSQL || ' AND D.BDCODPROD = '||:PRCODPROD;
          wSQL = :wSQL || ' AND D.BDCHAVE'||:PRTIPOMOV||' = '||:PRCHAVE;
          wSQL = :wSQL || ' ORDER BY D.BDREFERENCIA DESC';
          EXECUTE STATEMENT :wSQL INTO :BDCODENQ, :BDVL_ICMS_MEDIO_SUP, :BDVL_CONFRONTO, :BDQTDITEM, :BDVL_ICMS_SUP_ENT;
        END
    END

  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_GET_VALOR_CONFRONTO_SAIDA (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREFERENCIA INTEGER,
    PRCODPROD INTEGER,
    PRORDEM INTEGER,
    PRCODENQLEG INTEGER,
    PRDATAMOV DATE,
    PRQTDITEM NUMERIC(15,6),
    PRTIPOMOV CHAR(4))
RETURNS (
    BDVLRCONFRONTO DM_NUMERIC_15_2)
AS
DECLARE VARIABLE WQTDITEM NUMERIC(15,6);
DECLARE VARIABLE WQTDITEMUSADO NUMERIC(15,6);
DECLARE VARIABLE WVLRICMSEFET DM_NUMERIC_15_2;
BEGIN
  BDVLRCONFRONTO = 0;
  IF (:PRTIPOMOV = 'REDZ') THEN
    BEGIN
      SELECT IIF(A.BDVLRICMS > 0, A.BDVLRICMS, IIF(A.BDALIQICMS > 0, A.BDVLRTOTPRO * (A.BDALIQICMS / 100), IIF(A.BDALIQINT > 0, A.BDVLRTOTPRO * (A.BDALIQINT / 100), 0)))
      FROM (
            SELECT COALESCE(P.BDVLRICMS, 0) + COALESCE(P.BDICMSEFETIVO, 0) BDVLRICMS,
                   COALESCE(P.BDVLRTOTPRO, 0) BDVLRTOTPRO,
                   COALESCE(PRO.BDALIQICMS, 0) BDALIQICMS,
                   COALESCE(UF.BDALIQINT, 0) BDALIQINT
            FROM (
                  SELECT TOL.BDCODEMP, TOL.BDCHAVEREDZ BDCHAVE,
                         TOL.BDORDEMREDZ BDORDEM, TOL.BDORDEMPROREDZ BDORDEMPRO
                  FROM TMP_TOL_VEF_EMP_DRCST_1100_TEMP TOL
                  WHERE TOL.BDSESSAO = :PRSESSAO
                  AND TOL.BDCODEMP = :PRCODEMP
                  AND TOL.BDREFERENCIA = :PRREFERENCIA
                  AND TOL.BDCODPROD = :PRCODPROD
                  AND TOL.BDORDEM = :PRORDEM
                 ) T
            JOIN VEF_EMP_TITEMDOCECF P ON(P.BDCODEMP = T.BDCODEMP AND P.BDCHAVE = T.BDCHAVE AND P.BDORDEMDOCECF = T.BDORDEM AND P.BDORDEMITEM = T.BDORDEMPRO)
            JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
            LEFT OUTER JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = P.BDCODEMP)
            LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
            LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
           ) A
      INTO :BDVLRCONFRONTO;
    END
  ELSE
  IF (:PRCODENQLEG IN(1, 3)) THEN
    BEGIN
      SELECT P.BDVLRICMSEFET
      FROM (
            SELECT TOL.BDCODEMP, TOL.BDCHAVESAI BDCHAVE,
                   TOL.BDORDEMSAI BDORDEM, TOL.BDORDEMPROSAI BDORDEMPRO
            FROM TMP_TOL_VEF_EMP_DRCST_1100_TEMP TOL
            WHERE TOL.BDSESSAO = :PRSESSAO
            AND TOL.BDCODEMP = :PRCODEMP
            AND TOL.BDREFERENCIA = :PRREFERENCIA
            AND TOL.BDCODPROD = :PRCODPROD
            AND TOL.BDORDEM = :PRORDEM
            ) T
      JOIN VEF_EMP_TMOVPROSAI P ON(P.BDCODEMP = T.BDCODEMP AND P.BDCHAVE = T.BDCHAVE AND P.BDORDEM = T.BDORDEM AND P.BDORDEMPRO = T.BDORDEMPRO)
      INTO :BDVLRCONFRONTO;
    END
  ELSE
    IF (:PRCODENQLEG IN (2, 4)) THEN
    BEGIN
      FOR SELECT IIF(P.BDCODFATCON IS NOT NULL, FAT.BDFATORCONVER * P.BDQTDITEM, P.BDQTDITEM) BDQTDITEM,
                 -- 1 - Valor do ICMS Efetivo
                 IIF(COALESCE(P.BDVLRICMSEFET, 0) > 0, P.BDVLRICMSEFET,
                 -- 2 - Se não tiver valor do ICMS Efetivo, retornará a soma do ICMS Normal + FCP
                     IIF((COALESCE(P.BDVLRICMS, 0) + COALESCE(P.BDVLRFCP, 0)) > 0, COALESCE(P.BDVLRICMS, 0) + COALESCE(P.BDVLRFCP, 0),
                 -- 3 - Se não tiver ICMS Normal nem FCP, retornará (valor do produto + frete + despesas acessórias - desconto - ICMS ST - IPI) vezes a alíquota de ICMS normal da nota.
                         IIF((COALESCE(P.BDVLRITEM, 0) + COALESCE(P.BDVLRFRETE, 0) + COALESCE(P.BDVLRDESPACESSORIA, 0) /*+ COALESCE(P.BDVLRSEGURO, 0)*/
                              - COALESCE(P.BDVLRDESC, 0) /*- COALESCE(P.BDVLRST, 0) - COALESCE(P.BDVLRIPI, 0)*/)
                 -- 4 - Se não tiver alíquota de ICMS na nota, retornará vezes a alíquota de ICMS normal do cadastro do produto "PRO.BDALIQICMS"
                 -- 5 - Se não tiver alíquota de ICMS no cadastro de produto, retornará vezes a alíquota interna do cadastro do estado "MOV.BDALIQINT"
                              * (IIF(COALESCE(P.BDALIQICMS, 0) > 0, P.BDALIQICMS, IIF(COALESCE(PRO.BDALIQICMS, 0) > 0, PRO.BDALIQICMS, COALESCE(MOV.BDALIQINT, 0))) / 100) > 0,
                              (COALESCE(P.BDVLRITEM, 0) + COALESCE(P.BDVLRFRETE, 0) + COALESCE(P.BDVLRDESPACESSORIA, 0) /*+ COALESCE(P.BDVLRSEGURO, 0)*/
                              - COALESCE(P.BDVLRDESC, 0) /*- COALESCE(P.BDVLRST, 0) - COALESCE(P.BDVLRIPI, 0)*/)
                              * (IIF(COALESCE(P.BDALIQICMS, 0) > 0, P.BDALIQICMS, IIF(COALESCE(PRO.BDALIQICMS, 0) > 0, PRO.BDALIQICMS, COALESCE(MOV.BDALIQINT, 0))) / 100)
                             , 0
                             )
                         )
                     )
          FROM (
                SELECT E.BDCODEMP, E.BDCHAVE, E.BDDATAEMISSAO, UF.BDALIQINT
                FROM VEF_EMP_TMOVENT E
                JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = E.BDCODEMP)
                JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
                JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
                WHERE E.BDCODEMP = :PRCODEMP
                AND E.BDDATAEMISSAO <= :PRDATAMOV
               ) MOV
          JOIN VEF_EMP_TMOVPROENT P ON(P.BDCODEMP = MOV.BDCODEMP AND P.BDCHAVE = MOV.BDCHAVE AND P.BDCODPROD = :PRCODPROD)
          JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
          LEFT OUTER JOIN TFATCONV FAT ON(FAT.BDCODEMP = P.BDCODEMP AND FAT.BDCODPROD = P.BDCODPROD AND FAT.BDCODFATCON = P.BDCODFATCON)
          ORDER BY MOV.BDDATAEMISSAO DESC
          INTO :wQtdItem, :wVlrICMSEfet
      DO
        BEGIN
          IF (COALESCE(:wQtdItem, 0) > 0) THEN
            BEGIN
              wQtdItemUsado = IIF(:wQtdItem > :PRQTDITEM, :PRQTDITEM, :wQtdItem);
              PRQTDITEM = IIF(:wQtdItem > :PRQTDITEM, 0, :PRQTDITEM - :wQtdItem);
              BDVLRCONFRONTO = :BDVLRCONFRONTO + COALESCE((:wVlrICMSEfet / :wQtdItem) * :wQtdItemUsado, 0);
            END

          IF (:PRQTDITEM <= 0) THEN
            BREAK;
        END

      IF (:PRQTDITEM > 0) THEN
        BEGIN
          FOR SELECT I.BDQTDINV, COALESCE(I.BDVLRICMS, 0) + COALESCE(I.BDVLRICMSOP, 0) BDVLR
              FROM VEF_EMP_TMOVINV I
              WHERE I.BDCODEMP = :PRCODEMP
              AND I.BDREFINV < :PRREFERENCIA
              AND I.BDCODPROD = :PRCODPROD
              INTO :wQtdItem, :wVlrICMSEfet
          DO
            BEGIN
              wQtdItemUsado = IIF(:wQtdItem > :PRQTDITEM, :PRQTDITEM, :wQtdItem);
              PRQTDITEM = IIF(:wQtdItem > :PRQTDITEM, 0, :PRQTDITEM - :wQtdItem);
              BDVLRCONFRONTO = :BDVLRCONFRONTO + COALESCE((:wVlrICMSEfet / :wQtdItem) * :wQtdItemUsado, 0);
            END
        END
    END

  BDVLRCONFRONTO = COALESCE(:BDVLRCONFRONTO, 0);
  SUSPEND;
END
^

CREATE OR ALTER procedure SP_CALCULAR_RESS_COMPL_CAT42 (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer,
    PRFILTER varchar(25),
    PRVALUE integer,
    PRTIPO char(1))
returns (
    BDVALOR DM_NUMERIC_15_2)
as
declare variable WSQL varchar(1024);
declare variable WVALA DM_NUMERIC_15_2;
declare variable WVALB DM_NUMERIC_15_2;
declare variable WVALC DM_NUMERIC_15_2;
declare variable WVALD DM_NUMERIC_15_2;
BEGIN
  BDVALOR = 0;
  wSQL =          'SELECT SUM(A.BDVALA) BDVALA, ';
  wSQL = :wSQL ||        'SUM(A.BDVALB) BDVALB, ';
  wSQL = :wSQL ||        'SUM(A.BDVALC) BDVALC, ';
  wSQL = :wSQL ||        'SUM(A.BDVALD) BDVALD ';
  wSQL = :wSQL || 'FROM ( ';
  wSQL = :wSQL ||       'SELECT SUM(COALESCE(AP.BDVL_RESSARCIMENTO, 0)) BDVALA, ';
  wSQL = :wSQL ||              '0 BDVALB, ';
  wSQL = :wSQL ||              'SUM(COALESCE(AP.BDVL_COMPLEMENTO, 0)) BDVALC, ';
  wSQL = :wSQL ||              '0 BDVALD ';
  wSQL = :wSQL ||       'FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP ';
  wSQL = :wSQL ||       'WHERE AP.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL ||       'AND AP.BDCODEMP = '||:PRCODEMP;
  wSQL = :wSQL ||       'AND AP.BDREFERENCIA = '||:PRREF;
  wSQL = :wSQL ||       'AND AP.'||:PRFILTER||' = '||:PRVALUE;
  wSQL = :wSQL ||       'AND AP.BDCODMOV <> 3 ';
  wSQL = :wSQL ||       'GROUP BY AP.BDSESSAO, AP.BDCODEMP, AP.BDREFERENCIA, AP.BDCODPROD ';
  wSQL = :wSQL ||       'UNION ALL ';
  wSQL = :wSQL ||       'SELECT 0 BDVALA, ';
  wSQL = :wSQL ||              'SUM(COALESCE(AP.BDVL_RESSARCIMENTO, 0)) BDVALB, ';
  wSQL = :wSQL ||              '0 BDVALC, ';
  wSQL = :wSQL ||              'SUM(COALESCE(AP.BDVL_COMPLEMENTO, 0)) BDVALD ';
  wSQL = :wSQL ||       'FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP ';
  wSQL = :wSQL ||       'WHERE AP.BDSESSAO = '||:PRSESSAO;
  wSQL = :wSQL ||       'AND AP.BDCODEMP = '||:PRCODEMP;
  wSQL = :wSQL ||       'AND AP.BDREFERENCIA = '||:PRREF;
  wSQL = :wSQL ||       'AND AP.'||:PRFILTER||' = '||:PRVALUE;
  wSQL = :wSQL ||       'AND AP.BDCODMOV = 3 ';
  wSQL = :wSQL ||       'GROUP BY AP.BDSESSAO, AP.BDCODEMP, AP.BDREFERENCIA, AP.'||:PRFILTER;
  wSQL = :wSQL ||      ') A ';
  EXECUTE STATEMENT :wSQL INTO :wValA, :wValB, :wValC, :wValD;

  IF (:PRTIPO = 'R') THEN
    BDVALOR = (:wValA + :wValD) - (:wValB + :wValC);
  ELSE
    BDVALOR = (:wValC + :wValB) - (:wValD + :wValA);

  IF (BDVALOR < 0) THEN
    BDVALOR = 0;
  SUSPEND;
END^

CREATE OR ALTER procedure SP_APURAR_CAT42SP_1050 (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREFERENCIA integer)
as
begin
    DELETE FROM TMP_VEF_EMP_TDRCSTSP_1050_TEMP WHERE BDSESSAO = :PRSESSAO AND BDCODEMP = :PRCODEMP AND BDREFERENCIA = :PRREFERENCIA;

    INSERT INTO TMP_VEF_EMP_TDRCSTSP_1050_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCODTIPO)
    SELECT AP.BDSESSAO, AP.BDCODEMP, AP.BDREFERENCIA, AP.BDCODPROD, 399 BDCODTIPO
    FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
    WHERE AP.BDSESSAO = :PRSESSAO
    AND AP.BDCODEMP = :PRCODEMP
    AND AP.BDREFERENCIA = :PRREFERENCIA
    GROUP BY AP.BDSESSAO, AP.BDCODEMP, AP.BDREFERENCIA, AP.BDCODPROD;
    
    UPDATE TMP_VEF_EMP_TDRCSTSP_1050_TEMP R
    SET R.BDQTDE_INICIAL = (
                            SELECT AP.BDQTD_TOTAL
                            FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
                            WHERE AP.BDSESSAO = R.BDSESSAO
                            AND AP.BDCODEMP = R.BDCODEMP
                            AND AP.BDREFERENCIA = R.BDREFERENCIA
                            AND AP.BDCODPROD = R.BDCODPROD
                            AND AP.BDCODMOV = 1 /*Estoque inicial*/
                           ),
        R.BDVL_UNIT_INICIAL = (
                               SELECT AP.BDVL_UNIT_SALDO
                               FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
                               WHERE AP.BDSESSAO = R.BDSESSAO
                               AND AP.BDCODEMP = R.BDCODEMP
                               AND AP.BDREFERENCIA = R.BDREFERENCIA
                               AND AP.BDCODPROD = R.BDCODPROD
                               AND AP.BDCODMOV = 1 /*Estoque inicial*/
                              ),
        R.BDVL_TOT_INICIAL = (
                               SELECT AP.BDVL_TOT_SALDO
                               FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
                               WHERE AP.BDSESSAO = R.BDSESSAO
                               AND AP.BDCODEMP = R.BDCODEMP
                               AND AP.BDREFERENCIA = R.BDREFERENCIA
                               AND AP.BDCODPROD = R.BDCODPROD
                               AND AP.BDCODMOV = 1 /*Estoque inicial*/
                              ),
        R.BDQTDE_FINAL = (
                          SELECT FIRST 1 AP.BDQTD_TOTAL
                          FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
                          WHERE AP.BDSESSAO = R.BDSESSAO
                          AND AP.BDCODEMP = R.BDCODEMP
                          AND AP.BDREFERENCIA = R.BDREFERENCIA
                          AND AP.BDCODPROD = R.BDCODPROD
                          ORDER BY AP.BDORDEM DESC
                         ),
        R.BDVL_UNIT_FINAL = (
                             SELECT FIRST 1 AP.BDVL_UNIT_SALDO
                             FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
                             WHERE AP.BDSESSAO = R.BDSESSAO
                             AND AP.BDCODEMP = R.BDCODEMP
                             AND AP.BDREFERENCIA = R.BDREFERENCIA
                             AND AP.BDCODPROD = R.BDCODPROD
                             ORDER BY AP.BDORDEM DESC
                            ),
        R.BDVL_TOT_FINAL = (
                            SELECT FIRST 1 AP.BDVL_TOT_SALDO
                            FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
                            WHERE AP.BDSESSAO = R.BDSESSAO
                            AND AP.BDCODEMP = R.BDCODEMP
                            AND AP.BDREFERENCIA = R.BDREFERENCIA
                            AND AP.BDCODPROD = R.BDCODPROD
                            ORDER BY AP.BDORDEM DESC
                           ),
        R.BDVL_RESS_REST = (
--                            SELECT SUM(A.BDVL_RESSARCIMENTO_P) - SUM(A.BDVL_RESSARCIMENTO_N) BDVL_RESSARCIMENTO
--                            FROM (
--                                  SELECT AP.BDSESSAO, AP.BDCODEMP, AP.BDREFERENCIA, AP.BDCODPROD, SUM(COALESCE(AP.BDVL_RESSARCIMENTO, 0)) BDVL_RESSARCIMENTO_P, 0BDVL_RESSARCIMENTO_N
--                                  FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
--                                  WHERE AP.BDSESSAO = R.BDSESSAO
--                                  AND AP.BDCODEMP = R.BDCODEMP
--                                  AND AP.BDREFERENCIA = R.BDREFERENCIA
--                                  AND AP.BDCODPROD = R.BDCODPROD
--                                  AND AP.BDCODMOV IN(4, 5)
--                                  GROUP BY AP.BDSESSAO, AP.BDCODEMP, AP.BDREFERENCIA, AP.BDCODPROD
--                                  UNION ALL
--                                  SELECT AP.BDSESSAO, AP.BDCODEMP, AP.BDREFERENCIA, AP.BDCODPROD, 0 BDVL_RESSARCIMENTO_P, SUM(COALESCE(AP.BDVL_RESSARCIMENTO, 0)) BDVL_RESSARCIMENTO_N
--                                  FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
--                                  WHERE AP.BDSESSAO = R.BDSESSAO
--                                  AND AP.BDCODEMP = R.BDCODEMP
--                                  AND AP.BDREFERENCIA = R.BDREFERENCIA
--                                  AND AP.BDCODPROD = R.BDCODPROD
--                                  AND AP.BDCODMOV = 3
--                                  GROUP BY AP.BDSESSAO, AP.BDCODEMP, AP.BDREFERENCIA, AP.BDCODPROD
--                                 ) A
--                            GROUP BY A.BDSESSAO, A.BDCODEMP, A.BDREFERENCIA, A.BDCODPROD

--                            SELECT SUM(COALESCE(AP.BDVL_RESSARCIMENTO, 0)) - SUM(COALESCE(AP.BDVL_COMPLEMENTO, 0))
--                            FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
--                            WHERE AP.BDSESSAO = R.BDSESSAO
--                            AND AP.BDCODEMP = R.BDCODEMP
--                            AND AP.BDREFERENCIA = R.BDREFERENCIA
--                            AND AP.BDCODPROD = R.BDCODPROD
--                            GROUP BY AP.BDSESSAO, AP.BDCODEMP, AP.BDREFERENCIA, AP.BDCODPROD

                            SELECT BDVALOR FROM SP_CALCULAR_RESS_COMPL_CAT42(R.BDSESSAO, R.BDCODEMP , R.BDREFERENCIA, 'BDCODPROD', R.BDCODPROD, 'R')
                           )
    WHERE R.BDSESSAO = :PRSESSAO
    AND R.BDCODEMP = :PRCODEMP;
    
    
    UPDATE TMP_VEF_EMP_TDRCSTSP_1050_TEMP R
    SET
--        R.BDVL_COMPLEMENTO = (
--                              SELECT SUM(COALESCE(AP.BDVL_COMPLEMENTO, 0)) BDVL_COMPLEMENTO
--                              FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
--                              WHERE AP.BDSESSAO = R.BDSESSAO
--                              AND AP.BDCODEMP = R.BDCODEMP
--                              AND AP.BDREFERENCIA = R.BDREFERENCIA
--                              AND AP.BDCODPROD = R.BDCODPROD
--                              GROUP BY AP.BDSESSAO, AP.BDCODEMP, AP.BDREFERENCIA, AP.BDCODPROD
--                             ) - IIF(R.BDVL_RESS_REST > 0, R.BDVL_RESS_REST, 0)
--        R.BDVL_COMPLEMENTO = (
--                              SELECT SUM(COALESCE(AP.BDVL_COMPLEMENTO, 0)) - SUM(COALESCE(AP.BDVL_RESSARCIMENTO, 0))
--                              FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
--                              WHERE AP.BDSESSAO = R.BDSESSAO
--                              AND AP.BDCODEMP = R.BDCODEMP
--                              AND AP.BDREFERENCIA = R.BDREFERENCIA
--                              AND AP.BDCODPROD = R.BDCODPROD
--                              GROUP BY AP.BDSESSAO, AP.BDCODEMP, AP.BDREFERENCIA, AP.BDCODPROD
--                             )
        R.BDVL_COMPLEMENTO = (SELECT BDVALOR FROM SP_CALCULAR_RESS_COMPL_CAT42(R.BDSESSAO, R.BDCODEMP , R.BDREFERENCIA, 'BDCODPROD', R.BDCODPROD, 'C'))
    WHERE R.BDSESSAO = :PRSESSAO
    AND R.BDCODEMP = :PRCODEMP;

    /*Resumo*/
    DELETE FROM TMP_VEF_EMP_TDRCSTSP_RES_TEMP WHERE BDSESSAO = :PRSESSAO AND BDCODEMP = :PRCODEMP AND BDREFERENCIA = :PRREFERENCIA;
    INSERT INTO TMP_VEF_EMP_TDRCSTSP_RES_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODTIPO, BDCODENQLEG)
    SELECT :PRSESSAO BDSESSAO, :PRCODEMP BDCODEMP, :PRREFERENCIA BDREFERENCIA, 398 BDCODTIPO, E.BDCODENQ
    FROM VEF_BASE_TTABENQLEGALCAT42 E;

    UPDATE TMP_VEF_EMP_TDRCSTSP_RES_TEMP R
--    SET R.BDSD_ICMS_ST_RESS = COALESCE((
--                                        SELECT SUM(A.BDVL_RESSARCIMENTO_P) - SUM(A.BDVL_RESSARCIMENTO_N) BDVL_RESSARCIMENTO
--                                        FROM (
--                                              SELECT AP.BDSESSAO, AP.BDCODEMP, AP.BDREFERENCIA, AP.BDCODENQ, SUM(COALESCE(AP.BDVL_RESSARCIMENTO, 0)) BDVL_RESSARCIMENTO_P, 0BDVL_RESSARCIMENTO_N
--                                              FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
--                                              WHERE AP.BDSESSAO = R.BDSESSAO
--                                              AND AP.BDCODEMP = R.BDCODEMP
--                                              AND AP.BDREFERENCIA = R.BDREFERENCIA
--                                              AND AP.BDCODENQ = R.BDCODENQLEG
--                                              AND AP.BDCODMOV IN(4, 5)
--                                              GROUP BY AP.BDSESSAO, AP.BDCODEMP, AP.BDREFERENCIA, AP.BDCODENQ
--                                              UNION ALL
--                                              SELECT AP.BDSESSAO, AP.BDCODEMP, AP.BDREFERENCIA, AP.BDCODENQ, 0 BDVL_RESSARCIMENTO_P, SUM(COALESCE(AP.BDVL_RESSARCIMENTO, 0)) BDVL_RESSARCIMENTO_N
--                                              FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
--                                              WHERE AP.BDSESSAO = R.BDSESSAO
--                                              AND AP.BDCODEMP = R.BDCODEMP
--                                              AND AP.BDREFERENCIA = R.BDREFERENCIA
--                                              AND AP.BDCODENQ = R.BDCODENQLEG
--                                              AND AP.BDCODMOV = 3
--                                              GROUP BY AP.BDSESSAO, AP.BDCODEMP, AP.BDREFERENCIA, AP.BDCODENQ
--                                             ) A
--                                        GROUP BY A.BDSESSAO, A.BDCODEMP, A.BDREFERENCIA, A.BDCODENQ
--                                       ), 0)
    SET R.BDSD_ICMS_ST_RESS = (SELECT BDVALOR FROM SP_CALCULAR_RESS_COMPL_CAT42(R.BDSESSAO, R.BDCODEMP , R.BDREFERENCIA, 'BDCODENQ', R.BDCODENQLEG, 'R'))
    WHERE R.BDSESSAO = :PRSESSAO
    AND R.BDCODEMP = :PRCODEMP;
    
    UPDATE TMP_VEF_EMP_TDRCSTSP_RES_TEMP R
    SET R.BDSD_ICMS_ST_RESS = IIF(R.BDSD_ICMS_ST_RESS > 0, R.BDSD_ICMS_ST_RESS, 0),
--        R.BDSD_ICMS_ST_COMPL = COALESCE((
--                                         SELECT SUM(COALESCE(AP.BDVL_COMPLEMENTO, 0)) BDVL_COMPLEMENTO
--                                         FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
--                                         WHERE AP.BDSESSAO = R.BDSESSAO
--                                         AND AP.BDCODEMP = R.BDCODEMP
--                                         AND AP.BDREFERENCIA = R.BDREFERENCIA
--                                         AND AP.BDCODENQ = R.BDCODENQLEG
--                                         GROUP BY AP.BDSESSAO, AP.BDCODEMP, AP.BDREFERENCIA, AP.BDCODENQ
--                                        ) - IIF(R.BDSD_ICMS_ST_RESS > 0, R.BDSD_ICMS_ST_RESS, 0), 0)
        R.BDSD_ICMS_ST_COMPL = (SELECT BDVALOR FROM SP_CALCULAR_RESS_COMPL_CAT42(R.BDSESSAO, R.BDCODEMP , R.BDREFERENCIA, 'BDCODENQ', R.BDCODENQLEG, 'C'))
    WHERE R.BDSESSAO = :PRSESSAO
    AND R.BDCODEMP = :PRCODEMP;
    
    UPDATE TMP_VEF_EMP_TDRCSTSP_RES_TEMP R
    SET R.BDSD_ICMS_ST_COMPL = IIF(R.BDSD_ICMS_ST_COMPL > 0, R.BDSD_ICMS_ST_COMPL, 0)
    WHERE R.BDSESSAO = :PRSESSAO
    AND R.BDCODEMP = :PRCODEMP;

    UPDATE TMP_VEF_EMP_TDRCSTSP_RES_TEMP R
    SET R.BDSD_ICMS_ST_RESS = (
                               SELECT SUM(COALESCE(RES.BDSD_ICMS_ST_RESS, 0))
                               FROM TMP_VEF_EMP_TDRCSTSP_RES_TEMP RES
                               WHERE RES.BDSESSAO = R.BDSESSAO
                               AND RES.BDCODEMP = R.BDCODEMP
                               AND RES.BDREFERENCIA = R.BDREFERENCIA
                               AND RES.BDCODENQLEG <> 6
                              ),
        R.BDSD_ICMS_ST_COMPL = (
                               SELECT SUM(COALESCE(RES.BDSD_ICMS_ST_COMPL, 0))
                               FROM TMP_VEF_EMP_TDRCSTSP_RES_TEMP RES
                               WHERE RES.BDSESSAO = R.BDSESSAO
                               AND RES.BDCODEMP = R.BDCODEMP
                               AND RES.BDREFERENCIA = R.BDREFERENCIA
                               AND RES.BDCODENQLEG <> 6
                              )
    WHERE R.BDSESSAO = :PRSESSAO
    AND R.BDCODEMP = :PRCODEMP
    AND R.BDCODENQLEG = 6;

    UPDATE TMP_VEF_EMP_TDRCSTSP_RES_TEMP R
    SET R.BDSD_ICMS_ST_RECUP = IIF(R.BDSD_ICMS_ST_RESS - R.BDSD_ICMS_ST_COMPL > 0, R.BDSD_ICMS_ST_RESS - R.BDSD_ICMS_ST_COMPL, 0),
        R.BDSD_ICMS_ST_RECOL = IIF(R.BDSD_ICMS_ST_COMPL - R.BDSD_ICMS_ST_RESS > 0, R.BDSD_ICMS_ST_COMPL - R.BDSD_ICMS_ST_RESS, 0)
    WHERE R.BDSESSAO = :PRSESSAO
    AND R.BDCODEMP = :PRCODEMP
    AND R.BDCODENQLEG = 6;
end^

CREATE OR ALTER procedure SP_APURAR_CAT42SP_1100_REFRESH (
    PRSESSAO integer,
    PRCODEMP integer,
    PRREF integer)
as
begin
  /*Devolução de compra*/
  DELETE FROM TMP_TCAT42_CHAVE;
  INSERT INTO TMP_VEF_EMP_TDRCSTSP_1100_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCODMOV, BDQTDITEM, BDCHAVELAN)
  SELECT :PRSESSAO BDSESSAO, MOV.BDCODEMP, MOV.BDREFLAN, P.BDCODPROD, GETORDEMSEQUENCIAL_STR(:PRSESSAO||SP.BDCODEMP||MOV.BDREFLAN||P.BDCODPROD, :prCODEMP) BDORDEM, 5 BDCODMOV, COALESCE(P.BDQTDITEM, 0) BDQTDITEM, NFD.BDCHAVE
  FROM (
        SELECT SP.BDCODEMP, SP.BDCODPLACAT42SP, UF.BDALIQINT
        FROM (
              SELECT FIRST 1 BDCODPLACAT42SP, :PRCODEMP BDCODEMP
              FROM (
                    SELECT 1 BDORD, R.BDCODPLACAT42SP
                    FROM VW_VEF_BASE_TEMPPARESTSP R
                    WHERE R.BDCODEMP = :PRCODEMP
                    AND R.BDCODPLACAT42SP IS NOT NULL
                    UNION
                    SELECT 2 BDORD, P.BDCODPLACAT42SP
                    FROM VEF_BASE_TPLANOCAT42SP P
                    WHERE BDPLANODEFAULT = 'TRUE'
                   )
              ORDER BY BDORD
             ) SP
        LEFT OUTER JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = SP.BDCODEMP)
        LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
        LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
        WHERE SP.BDCODEMP = :PRCODEMP
        AND SP.BDCODPLACAT42SP IS NOT NULL
       ) SP
  JOIN VEF_EMP_TMOVSAI MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN = :PRREF)
  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDDEVOL = 'TRUE')
  JOIN VEF_EMP_TMOVPROSAI P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
  JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
  LEFT OUTER JOIN SP_BUSCAR_NFE_DEVOLUCAO(MOV.BDCODEMP, MOV.BDCHAVE, 'SAI') NFD ON(NFD.BDCHAVE IS NOT NULL) /*Busca a nota referenciada*/
  WHERE NFD.BDCHAVE IS NOT NULL
  ORDER BY MOV.BDDATAEMISSAO;

  INSERT INTO TMP_TOL_VEF_EMP_DRCST_1100_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCHAVESAI, BDORDEMSAI, BDORDEMPROSAI)
  SELECT :PRSESSAO BDSESSAO, SP.BDCODEMP, MOV.BDREFLAN BDREFERENCIA, P.BDCODPROD, GETORDEMSEQUENCIAL_STR('TOL'||:PRSESSAO||SP.BDCODEMP||MOV.BDREFLAN||P.BDCODPROD, :prCODEMP) BDORDEM,
         MOV.BDCHAVE, I.BDORDEM, P.BDORDEMPRO
  FROM (
        SELECT SP.BDCODEMP, SP.BDCODPLACAT42SP, UF.BDALIQINT
        FROM (
              SELECT FIRST 1 BDCODPLACAT42SP, :PRCODEMP BDCODEMP
              FROM (
                    SELECT 1 BDORD, R.BDCODPLACAT42SP
                    FROM VW_VEF_BASE_TEMPPARESTSP R
                    WHERE R.BDCODEMP = :PRCODEMP
                    AND R.BDCODPLACAT42SP IS NOT NULL
                    UNION
                    SELECT 2 BDORD, P.BDCODPLACAT42SP
                    FROM VEF_BASE_TPLANOCAT42SP P
                    WHERE BDPLANODEFAULT = 'TRUE'
                   )
              ORDER BY BDORD
             ) SP
        LEFT OUTER JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = SP.BDCODEMP)
        LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
        LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
        WHERE SP.BDCODEMP = :PRCODEMP
        AND SP.BDCODPLACAT42SP IS NOT NULL
       ) SP
  JOIN VEF_EMP_TMOVSAI MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN = :PRREF)
  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDDEVOL = 'TRUE')
  JOIN VEF_EMP_TMOVPROSAI P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
  JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
  LEFT OUTER JOIN SP_BUSCAR_NFE_DEVOLUCAO(MOV.BDCODEMP, MOV.BDCHAVE, 'SAI') NFD ON(NFD.BDCHAVE IS NOT NULL) /*Busca a nota referenciada*/
  WHERE NFD.BDCHAVE IS NOT NULL
  ORDER BY MOV.BDDATAEMISSAO;

  UPDATE TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
  SET AP.BDCODMOV = 2
  WHERE AP.BDSESSAO = :PRSESSAO
  AND AP.BDCODMOV = 2 /*Entrada*/
  ORDER BY AP.BDREFERENCIA, AP.BDCODPROD, AP.BDCODMOV, AP.BDDATAMOV, AP.BDORDEM;

  --rdb$set_context('USER_SESSION', 'ETAPA_'||:PRSESSAO, '1');
  UPDATE OR INSERT INTO TTHREAD (BDPARAM, BDVALORSTR) VALUES ('ETAPA_'||:PRSESSAO, '1'); -- Alt.: #201191 - Removida variavel de contexto...
  UPDATE TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
  SET AP.BDCODMOV = 3
  WHERE AP.BDSESSAO = :PRSESSAO
  AND AP.BDCODMOV = 3 /*Devolução de venda*/
  ORDER BY AP.BDREFERENCIA, AP.BDCODPROD, AP.BDCODMOV, AP.BDDATAMOV, AP.BDORDEM;

  UPDATE TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
  SET AP.BDCODMOV = 4
  WHERE AP.BDSESSAO = :PRSESSAO
  AND AP.BDCODMOV = 4 /*Saída*/
  ORDER BY AP.BDREFERENCIA, AP.BDCODPROD, AP.BDCODMOV, AP.BDDATAMOV, AP.BDORDEM;

  --rdb$set_context('USER_SESSION', 'ETAPA_'||:PRSESSAO, '2');
  UPDATE OR INSERT INTO TTHREAD (BDPARAM, BDVALORSTR) VALUES ('ETAPA_'||:PRSESSAO, '2'); -- Alt.: #201191 - Removida variavel de contexto...
  UPDATE TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
  SET AP.BDCODMOV = 3
  WHERE AP.BDSESSAO = :PRSESSAO
  AND AP.BDCODMOV = 3 /*Devolução de venda*/
  ORDER BY AP.BDREFERENCIA, AP.BDCODPROD, AP.BDCODMOV, AP.BDDATAMOV, AP.BDORDEM;

  UPDATE TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
  SET AP.BDCODMOV = 4
  WHERE AP.BDSESSAO = :PRSESSAO
  AND AP.BDCODMOV = 4 /*Saída*/
  ORDER BY AP.BDREFERENCIA, AP.BDCODPROD, AP.BDCODMOV, AP.BDDATAMOV, AP.BDORDEM;

  UPDATE TMP_VEF_EMP_TDRCSTSP_1100_TEMP AP
  SET AP.BDCODMOV = 5
  WHERE AP.BDSESSAO = :PRSESSAO
  AND AP.BDCODMOV = 5 /*Devolução de compra*/
  ORDER BY AP.BDREFERENCIA, AP.BDCODPROD, AP.BDCODMOV, AP.BDDATAMOV, AP.BDORDEM;
end^

CREATE OR ALTER PROCEDURE SP_BUSCAR_ENQ_FED_CAT42 (
    PRCHAVEMOV INTEGER,
    PRCODPLACAT42SP INTEGER,
    PRCHAVE INTEGER,
    PRCODTER INTEGER,
    PRCODPROD INTEGER,
    PRCODNAT INTEGER,
    PRCODCST INTEGER,
    PRNCMPROD INTEGER,
    PRMOV CHAR(4),
    PRCONSFINAL INTEGER,
    PRREGKEY VARCHAR(100),
    PRMOD CHAR(2))
RETURNS (
    BDCODENQLEG INTEGER)
AS
DECLARE VARIABLE WCONSFINAL INTEGER;
DECLARE VARIABLE WCODENQLEG INTEGER;
DECLARE VARIABLE WNCMPROD INTEGER;
DECLARE VARIABLE WCODCST INTEGER;
DECLARE VARIABLE WVALID DM_BOOLEAN;
DECLARE VARIABLE WCODNAT INTEGER;
DECLARE VARIABLE WCODPROD INTEGER;
DECLARE VARIABLE WCODTER INTEGER;
DECLARE VARIABLE WWITHCODNAT DM_BOOLEAN;
DECLARE VARIABLE WWITHCST DM_BOOLEAN;
DECLARE VARIABLE WWITHNCM DM_BOOLEAN;
DECLARE VARIABLE WCHAVE VARCHAR(100);
BEGIN
  wConsFinal = IIF(:PRCONSFINAL = -1, 0, :PRCONSFINAL);

  IF (:PRMOD = '02' OR :PRMOD = '59') THEN
    wConsFinal = 1;

  SELECT BDCHAVE FROM TMP_TCAT42_CHAVE WHERE BDCHAVE = :PRREGKEY AND BDMOV = :PRMOV INTO :wChave;

  IF (:wChave IS NOT NULL) THEN
    BEGIN
      BDCODENQLEG = NULL;
      SUSPEND;
    END
  ELSE
    BEGIN
      SELECT FIRST 1 BC.BDWITHCODNAT, BC.BDWITHCST, BC.BDWITHNCM, BC.BDCODTER, BC.BDCODPROD, BC.BDCODENQLEG
      FROM TMP_BUSCAR_CAT42 BC
      WHERE BC.BDCHAVE = :PRCHAVE
      INTO :wWithCodNat, :wWithCST, :wWithNCM, :wCodTer, :wCodProd, :wCodEnqLeg;
    
      IF (ROW_COUNT = 0) THEN
        BEGIN
          SELECT P.BDCODTER, P.BDCODPROD, P.BDCODENQ
          FROM VEF_BASE_TPLANOACOESCAT42SP P
          WHERE P.BDCODPLACAT42SP = :PRCODPLACAT42SP
          AND P.BDCHAVE = :PRCHAVE
          INTO :wCodTer, :wCodProd, :wCodEnqLeg;
    
          INSERT INTO TMP_BUSCAR_CAT42(BDCHAVE, BDWITHCODNAT, BDWITHCST, BDWITHNCM, BDCODPROD, BDCODTER, BDCODENQLEG) VALUES(:PRCHAVE,
            IIF(COALESCE((SELECT FIRST 1 P.BDCODNAT
                          FROM VEF_BASE_TVINCPLANOCAT42SP P
                          WHERE P.BDCODPLACAT42SP = :PRCODPLACAT42SP
                          AND P.BDCHAVE = :PRCHAVE
                          AND P.BDCODNAT IS NOT NULL), 0) > 0, 'TRUE', 'FALSE'),
            IIF(COALESCE((SELECT FIRST 1 P.BDCODCST
                          FROM VEF_BASE_TVINCPLANOCAT42SP P
                          WHERE P.BDCODPLACAT42SP = :PRCODPLACAT42SP
                          AND P.BDCHAVE = :PRCHAVE
                          AND P.BDCODCST IS NOT NULL), 0) > 0, 'TRUE', 'FALSE'),
            IIF(COALESCE((SELECT FIRST 1 P.BDNCMPROD
                          FROM VEF_BASE_TVINCPLANOCAT42SP P
                          WHERE P.BDCODPLACAT42SP = :PRCODPLACAT42SP
                          AND P.BDCHAVE = :PRCHAVE
                          AND P.BDNCMPROD IS NOT NULL), 0) > 0, 'TRUE', 'FALSE'), :wCodProd, :wCodTer, :wCodEnqLeg);
    
          SELECT FIRST 1 BC.BDWITHCODNAT, BC.BDWITHCST, BC.BDWITHNCM FROM TMP_BUSCAR_CAT42 BC WHERE BC.BDCHAVE = :PRCHAVE INTO :wWithCodNat, :wWithCST, :wWithNCM;
        END
    
      IF (:wCodTer IS NOT NULL AND :PRCODTER <> :wCodTer) THEN
        BEGIN
          BDCODENQLEG = NULL;
          SUSPEND;
        END
      ELSE
        BEGIN
          IF (:wCodProd IS NOT NULL AND :PRCODPROD <> :wCodProd) THEN
            BEGIN
              BDCODENQLEG = NULL;
              SUSPEND;
            END
          ELSE
            BEGIN
              wValid = 'TRUE';
              IF (:wWithCodNat = 'TRUE') THEN
                BEGIN
                  wCodNat = 0;
                  SELECT FIRST 1 P.BDCODNAT
                  FROM VEF_BASE_TVINCPLANOCAT42SP P
                  WHERE P.BDCODPLACAT42SP = :PRCODPLACAT42SP
                  AND P.BDCHAVE = :PRCHAVE
                  AND P.BDCODNAT = :PRCODNAT
                  INTO :wCodNat;
    
                  IF (COALESCE(:wCodNat, 0) = 0) THEN
                    wValid = 'FALSE';
                END
    
               IF (:wValid = 'TRUE') THEN
                 BEGIN
                   IF (:wWithCST = 'TRUE') THEN
                     BEGIN
                       wCodCST = 0;
                       SELECT FIRST 1 P.BDCODCST
                       FROM VEF_BASE_TVINCPLANOCAT42SP P
                       WHERE P.BDCODPLACAT42SP = :PRCODPLACAT42SP
                       AND P.BDCHAVE = :PRCHAVE
                       AND P.BDCODCST = :PRCODCST
                       INTO :wCodCst;
    
                       IF (COALESCE(:wCodCst, 0) = 0) THEN
                         wValid = 'FALSE';
                     END
    
                   IF (:wValid = 'TRUE') THEN
                     BEGIN
                       IF (:wWithNCM = 'TRUE') THEN
                         BEGIN
                           wNcmProd = 0;
                           SELECT FIRST 1 P.BDNCMPROD
                           FROM VEF_BASE_TVINCPLANOCAT42SP P
                           WHERE P.BDCODPLACAT42SP = :PRCODPLACAT42SP
                           AND P.BDCHAVE = :PRCHAVE
                           AND P.BDNCMPROD = :PRNCMPROD
                           INTO :wNcmProd;
        
                           IF (COALESCE(:wNcmProd, 0) = 0) THEN
                             wValid = 'FALSE';
                         END
    
                       IF (:wValid = 'TRUE') THEN
                         BEGIN
                           IF ((:PRMOV = 'SAI') OR (:PRMOV = 'TS'))  THEN
                             BEGIN
                               IF (:wCodEnqLeg = 1) THEN
                                 BEGIN
                                  IF (:wConsFinal = 1) THEN
                                    BEGIN
                                      INSERT INTO TMP_TCAT42_CHAVE(BDCHAVE, BDMOV) VALUES(:PRREGKEY, :PRMOV);
                                      BDCODENQLEG = :wCodEnqLeg;
                                      SUSPEND;
                                    END
                                 END
                               ELSE
                                 BEGIN
                                   INSERT INTO TMP_TCAT42_CHAVE(BDCHAVE, BDMOV) VALUES(:PRREGKEY, :PRMOV);
                                   BDCODENQLEG = :wCodEnqLeg;
                                   SUSPEND;
                                 END
                             END
                           ELSE
                             BEGIN
                               INSERT INTO TMP_TCAT42_CHAVE(BDCHAVE, BDMOV) VALUES(:PRREGKEY, :PRMOV);
                               BDCODENQLEG = :wCodEnqLeg;
                               SUSPEND;
                             END
                         END
                       ELSE
                         BEGIN
                           BDCODENQLEG = NULL;
                           SUSPEND;
                         END
                     END
                   ELSE
                     BEGIN
                       BDCODENQLEG = NULL;
                       SUSPEND;
                     END
                 END
               ELSE
                 BEGIN
                   BDCODENQLEG = NULL;
                   SUSPEND;
                 END
            END
        END
    END
END^

CREATE OR ALTER PROCEDURE SP_ESTOQUE_INICIAL_CAT42SP (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS
DECLARE VARIABLE WREFANT INTEGER;
BEGIN
  /*Apuração estoque inicial*/
  SETORDEMSEQUENCIAL_STR(:prCODEMP);

  wRefAnt = NULL;
  SELECT FIRST 1 A.BDREFERENCIA
  FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP A
  WHERE A.BDSESSAO = :PRSESSAO
  AND A.BDCODEMP = :PRCODEMP
  AND A.BDREFERENCIA = (SELECT BDREF FROM DEC_REF(:PRREF)) INTO :wRefAnt;

  IF (wRefAnt IS NULL) THEN /*Pega da tabela física*/
    BEGIN
      INSERT INTO TMP_VEF_EMP_TDRCSTSP_1100_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCODMOV, BDVL_TOT_SALDO, BDQTD_TOTAL, BDQTDITEM, BDVL_UNIT_SALDO)
      SELECT :PRSESSAO, A.BDCODEMP, :PRREF, A.BDCODPROD, GETORDEMSEQUENCIAL_STR(:prsessao || :PRCODEMP || :PRREF || A.BDCODPROD, :prCODEMP), 1 BDCODMOV, A.BDVL_TOT_SALDO, A.BDQTD_TOTAL, A.BDQTD_TOTAL,
             (A.BDVL_TOT_SALDO / IIF(COALESCE(A.BDQTD_TOTAL,0) > 0, A.BDQTD_TOTAL, 1)) BDVL_UNIT_SALDO -- Alt.: #153586 - Ajuste para não dividir por zero.
      FROM (
            SELECT SP.BDCODEMP, SP.BDVL_TOT_SALDO, SP.BDQTD_TOTAL, SP.BDCODPROD
            FROM VEF_EMP_TDRCSTSP_1100 SP
            WHERE SP.BDCODEMP = :PRCODEMP
            AND SP.BDREFERENCIA = (SELECT BDREF FROM DEC_REF(:PRREF))
            AND SP.BDORDEM = (SELECT MAX(O.BDORDEM) FROM VEF_EMP_TDRCSTSP_1100 O WHERE O.BDCODEMP = SP.BDCODEMP AND O.BDREFERENCIA = SP.BDREFERENCIA AND O.BDCODPROD = SP.BDCODPROD GROUP BY O.BDCODEMP, O.BDREFERENCIA, O.BDCODPROD)
           ) A;
    END
  ELSE
    BEGIN /*Pega da tabela temporária, está apurando a referência anterior na mesma apuração*/
      INSERT INTO TMP_VEF_EMP_TDRCSTSP_1100_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCODMOV, BDVL_TOT_SALDO, BDQTD_TOTAL, BDQTDITEM, BDVL_UNIT_SALDO)
      SELECT A.BDSESSAO, A.BDCODEMP, :PRREF, A.BDCODPROD, GETORDEMSEQUENCIAL_STR(:prsessao || :PRCODEMP || :PRREF || A.BDCODPROD, :prCODEMP), 1 BDCODMOV, A.BDVL_TOT_SALDO, A.BDQTD_TOTAL, A.BDQTD_TOTAL,
             (A.BDVL_TOT_SALDO / IIF(COALESCE(A.BDQTD_TOTAL,0) > 0, A.BDQTD_TOTAL, 1)) BDVL_UNIT_SALDO -- Alt.: #153586 - Ajuste para não dividir por zero.
      FROM (
            SELECT SP.BDSESSAO, SP.BDCODEMP, SP.BDVL_TOT_SALDO, SP.BDQTD_TOTAL, SP.BDCODPROD
            FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP SP
            WHERE SP.BDSESSAO = :PRSESSAO
            AND SP.BDCODEMP = :PRCODEMP
            AND SP.BDREFERENCIA = (SELECT BDREF FROM DEC_REF(:PRREF))
            AND SP.BDORDEM = (SELECT MAX(O.BDORDEM) FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP O WHERE O.BDSESSAO = SP.BDSESSAO AND O.BDCODEMP = SP.BDCODEMP AND O.BDREFERENCIA = SP.BDREFERENCIA AND O.BDCODPROD = SP.BDCODPROD GROUP BY O.BDCODEMP, O.BDREFERENCIA, O.BDCODPROD)
           ) A;
    END

  IF (ROW_COUNT = 0) THEN
    BEGIN
      SETORDEMSEQUENCIAL_STR(:prCODEMP);
      INSERT INTO TMP_VEF_EMP_TDRCSTSP_1100_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCODMOV, BDVL_TOT_SALDO, BDQTD_TOTAL, BDQTDITEM, BDVL_UNIT_SALDO)
      SELECT :PRSESSAO, :PRCODEMP, :PRREF, A.BDCODPROD, GETORDEMSEQUENCIAL_STR(:prsessao || :PRCODEMP || :PRREF || A.BDCODPROD, :prCODEMP), 1 BDCODMOV, A.BDVL_TOT_SALDO, A.BDQTD_TOTAL, A.BDQTD_TOTAL,
             (A.BDVL_TOT_SALDO / IIF(COALESCE(A.BDQTD_TOTAL,0) > 0, A.BDQTD_TOTAL, 1)) BDVL_UNIT_SALDO -- Alt.: #153586 - Ajuste para não dividir por zero.
      FROM (
            SELECT SUM(COALESCE(I.BDVL_TOT_SALDO, 0)) BDVL_TOT_SALDO, SUM(COALESCE(I.BDQTD_TOTAL, 0)) BDQTD_TOTAL, I.BDCODPROD
            FROM (
                  SELECT INV.BDCHAVE,  CAST((COALESCE(INV.BDVLRICMS, 0) +
                                             COALESCE(INV.BDVLRICMSST, 0) +
                                             COALESCE(INV.BDVLRICMSOP, 0) +
                                             COALESCE(INV.BDVLRFCP, 0)) * INV.BDQTDINV AS NUMERIC(15, 6)) BDVL_TOT_SALDO,
                                             COALESCE(INV.BDQTDINV, 0) BDQTD_TOTAL, INV.BDCODPROD
                  FROM VEF_EMP_TMOVINV INV
                  WHERE INV.BDCODEMP = :PRCODEMP
                  AND INV.BDREFINV = (SELECT BDREF FROM DEC_REF(:PRREF))
                  AND ((COALESCE(INV.BDVLRICMSST, 0) > 0) OR (COALESCE(INV.BDVLRFCP, 0) > 0))
                 ) I
            GROUP BY I.BDCODPROD
           ) A;

        INSERT INTO TMP_TOL_VEF_EMP_DRCST_1100_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCHAVEINV)
        SELECT :PRSESSAO, INV.BDCODEMP, :PRREF, INV.BDCODPROD, GETORDEMSEQUENCIAL_STR('TOL' || :PRSESSAO || INV.BDCODEMP || :PRREF || INV.BDCODPROD, :prCODEMP), INV.BDCHAVE
        FROM VEF_EMP_TMOVINV INV
        WHERE INV.BDCODEMP = :PRCODEMP
        AND INV.BDREFINV = (SELECT BDREF FROM DEC_REF(:PRREF))
        AND ((COALESCE(INV.BDVLRICMSST, 0) > 0) OR (COALESCE(INV.BDVLRFCP, 0) > 0));
    END
  ELSE
    BEGIN
      IF (:wRefAnt IS NULL) THEN
        BEGIN
          INSERT INTO TMP_TOL_VEF_EMP_DRCST_1100_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCHAVEINV)
          SELECT :PRSESSAO, TOL.BDCODEMP, :PRREF, TOL.BDCODPROD, GETORDEMSEQUENCIAL_STR('TOL' || :PRSESSAO || TOL.BDCODEMP || :PRREF || TOL.BDCODPROD, :prCODEMP), NULL
          FROM TOL_VEF_EMP_DRCSTSP_1100 TOL
          JOIN VEF_EMP_TDRCSTSP_1100 A ON(A.BDCODEMP = TOL.BDCODEMP AND A.BDREFERENCIA = TOL.BDREFERENCIA AND A.BDCODPROD = TOL.BDCODPROD AND A.BDORDEM = TOL.BDORDEM AND A.BDCODMOV = 1)
          WHERE TOL.BDCODEMP = :PRCODEMP
          AND TOL.BDREFERENCIA = (SELECT BDREF FROM DEC_REF(:PRREF));
        END
      ELSE
        BEGIN
          INSERT INTO TMP_TOL_VEF_EMP_DRCST_1100_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCHAVEINV)
          SELECT TOL.BDSESSAO, TOL.BDCODEMP, :PRREF, TOL.BDCODPROD, GETORDEMSEQUENCIAL_STR('TOL' || :PRSESSAO || TOL.BDCODEMP || :PRREF || TOL.BDCODPROD, :prCODEMP), NULL
          FROM TMP_TOL_VEF_EMP_DRCST_1100_TEMP TOL
          JOIN TMP_VEF_EMP_TDRCSTSP_1100_TEMP A ON(A.BDSESSAO = TOL.BDSESSAO AND A.BDCODEMP = TOL.BDCODEMP AND A.BDREFERENCIA = TOL.BDREFERENCIA AND A.BDCODPROD = TOL.BDCODPROD AND A.BDORDEM = TOL.BDORDEM AND A.BDCODMOV = 1)
          WHERE TOL.BDSESSAO = :PRSESSAO
          AND TOL.BDCODEMP = :PRCODEMP
          AND TOL.BDREFERENCIA = (SELECT BDREF FROM DEC_REF(:PRREF));
        END

      INSERT INTO TMP_TOL_VEF_EMP_DRCST_1100_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCHAVEINV)
      SELECT A.BDSESSAO, A.BDCODEMP, A.BDREFERENCIA, A.BDCODPROD, GETORDEMSEQUENCIAL_STR('TOL' || :PRSESSAO || A.BDCODEMP || :PRREF || A.BDCODPROD, :prCODEMP), NULL
      FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP A
      WHERE A.BDSESSAO = :PRSESSAO
      AND A.BDCODEMP = :PRCODEMP
      AND A.BDREFERENCIA = :PRREF
      AND A.BDCODMOV = 1
      AND NOT EXISTS (
                      SELECT TOL.BDCODEMP
                      FROM TMP_TOL_VEF_EMP_DRCST_1100_TEMP TOL
                      WHERE TOL.BDSESSAO = A.BDSESSAO
                      AND TOL.BDCODEMP = A.BDCODEMP
                      AND TOL.BDREFERENCIA = A.BDREFERENCIA
                      AND TOL.BDCODPROD = A.BDCODPROD
                      AND TOL.BDORDEM = A.BDORDEM
                     );
    END
END
^

CREATE OR ALTER PROCEDURE SP_APURAR_CAT42SP_1100 (
    PRSESSAO INTEGER,
    PRCODEMP INTEGER,
    PRREF INTEGER)
AS
BEGIN
  DELETE FROM TMP_TOL_VEF_EMP_DRCST_1100_TEMP WHERE BDSESSAO = :PRSESSAO AND BDCODEMP = :PRCODEMP AND BDREFERENCIA = :PRREF;
  DELETE FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP WHERE BDSESSAO = :PRSESSAO AND BDCODEMP = :PRCODEMP AND BDREFERENCIA = :PRREF;

  EXECUTE PROCEDURE SP_ESTOQUE_INICIAL_CAT42SP(:PRSESSAO, :PRCODEMP, :PRREF);

  DELETE FROM TMP_BUSCAR_CAT42;

  /*Compra - Entrada*/
  DELETE FROM TMP_TCAT42_CHAVE;
  INSERT INTO TMP_VEF_EMP_TDRCSTSP_1100_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCODMOV, BDCODENQ, BDVL_ICMS_SUP_ENT, BDQTD_TOTAL, BDVL_TOT_SALDO, BDVL_UNIT_SALDO, BDDATAMOV, BDQTDITEM)
  SELECT A.BDSESSAO, A.BDCODEMP, A.BDREFERENCIA, A.BDCODPROD, GETORDEMSEQUENCIAL_STR(:PRSESSAO||A.BDCODEMP||A.BDREFERENCIA||A.BDCODPROD, :prCODEMP),
         A.BDCODMOV, A.BDCODENQLEG, A.BDVL_ICMS_SUP_ENT, A.BDQTD_TOTAL, A.BDVL_TOT_SALDO, 0 BDVL_UNIT_SALDO, A.BDDATAEMISSAO, A.BDQTDITEM
  FROM (
        SELECT A.BDSESSAO, A.BDCODEMP, A.BDREFERENCIA, A.BDCODPROD, A.BDCODMOV, A.BDCODENQLEG, A.BDVL_ICMS_SUP_ENT, A.BDQTD_TOTAL,
               (COALESCE(A.BDVL_TOT_SALDO_ANT, 0) + COALESCE(A.BDVL_ICMS_SUP_ENT, 0)) BDVL_TOT_SALDO, A.BDDATAEMISSAO, A.BDQTDITEM
        FROM (
              SELECT AP.*
              FROM (
                    SELECT :PRSESSAO BDSESSAO, SP.BDCODEMP, MOV.BDREFLAN BDREFERENCIA, P.BDCODPROD, 2 BDCODMOV,
                           (
                            SELECT E.BDCODENQLEG
                            FROM VEF_BASE_TPLANOACOESCAT42SP A
                            LEFT OUTER JOIN SP_BUSCAR_ENQ_FED_CAT42(MOV.BDCHAVE, A.BDCODPLACAT42SP, A.BDCODPLACAT42SP, MOV.BDCODTER, P.BDCODPROD, I.BDCODNAT, P.BDCODCSTICMS, PRO.BDNCMPROD, 'ENT', 0, P.BDCHAVE||'|'||P.BDORDEM||'|'||P.BDORDEMPRO, M.BDMODELOSTR) E ON(E.BDCODENQLEG IS NOT NULL)
                            WHERE A.BDCODPLACAT42SP = SP.BDCODPLACAT42SP
                            AND E.BDCODENQLEG IS NOT NULL
                           ) BDCODENQLEG,
                           (SELECT BDVL_ICMS_SUP_ENT FROM SP_GET_VALOR_ICMS_SUP_ENT(P.BDCODEMP, P.BDCHAVE, P.BDORDEM, P.BDORDEMPRO, SP.BDALIQINT)) BDVL_ICMS_SUP_ENT,
                           0 BDQTD_TOTAL, 0 BDVL_TOT_SALDO_ANT, MOV.BDDATAEMISSAO, IIF(P.BDCODFATCON IS NOT NULL, FAT.BDFATORCONVER * P.BDQTDITEM, P.BDQTDITEM) BDQTDITEM,
                           (COALESCE(P.BDVLRST, 0) + COALESCE(P.BDFCPRETIDO, 0) + COALESCE(P.BDVLRICMSSTRET, 0) + COALESCE(P.BDVLRFCPSTRET, 0)) BDVLRST, IVA.BDCHAVE BDCHAVEIVA
                    FROM (
                          SELECT SP.BDCODEMP, SP.BDCODPLACAT42SP, UF.BDALIQINT
                          FROM (
                                SELECT FIRST 1 BDCODPLACAT42SP, :PRCODEMP BDCODEMP
                                FROM (
                                      SELECT 1 BDORD, R.BDCODPLACAT42SP
                                      FROM VW_VEF_BASE_TEMPPARESTSP R
                                      WHERE R.BDCODEMP = :PRCODEMP
                                      AND R.BDCODPLACAT42SP IS NOT NULL
                                      UNION
                                      SELECT 2 BDORD, P.BDCODPLACAT42SP
                                      FROM VEF_BASE_TPLANOCAT42SP P
                                      WHERE BDPLANODEFAULT = 'TRUE'
                                     )
                                ORDER BY BDORD
                               ) SP
                          LEFT OUTER JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = SP.BDCODEMP)
                          LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
                          LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
                         ) SP
                    JOIN VEF_EMP_TMOVENT MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN = :PRREF AND MOV.BDCODSITNF NOT IN(2, 3, 4, 5))
                    JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
                    JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDDEVOL = 'FALSE')
                    JOIN VEF_EMP_TMOVPROENT P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
                    LEFT OUTER JOIN TFATCONV FAT ON(FAT.BDCODEMP = P.BDCODEMP AND FAT.BDCODPROD = P.BDCODPROD AND FAT.BDCODFATCON = P.BDCODFATCON)
                    JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
                    LEFT OUTER JOIN (
                      SELECT IVA.BDCODEMP, IVA.BDCHAVE, IVA.BDORDEM, IVA.BDCODPROD, SUM(COALESCE(IVA.BDICMSRECOLHER, 0)) BDICMSRECOLHER
                      FROM VEF_EMP_TMOVENT_IVA IVA
                      WHERE IVA.BDCODEMP = :PRCODEMP
                      GROUP BY IVA.BDCODEMP, IVA.BDCHAVE, IVA.BDORDEM, IVA.BDCODPROD
                     ) IVA ON (IVA.BDCODEMP = P.BDCODEMP AND IVA.BDCHAVE = P.BDCHAVE AND IVA.BDORDEM = P.BDORDEM AND IVA.BDCODPROD = P.BDCODPROD)
                    LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN M ON(M.BDMODELO = MOV.BDMODELO)
                 ) AP
              WHERE ((AP.BDVLRST > 0) OR (AP.BDCHAVEIVA IS NOT NULL))
             ) A
       ) A
  ORDER BY A.BDDATAEMISSAO;

  INSERT INTO TMP_TOL_VEF_EMP_DRCST_1100_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCHAVEENT, BDORDEMENT, BDORDEMPROENT)
  SELECT :PRSESSAO BDSESSAO, SP.BDCODEMP, MOV.BDREFLAN BDREFERENCIA, P.BDCODPROD, GETORDEMSEQUENCIAL_STR('TOL'||:PRSESSAO||SP.BDCODEMP||MOV.BDREFLAN||P.BDCODPROD, :prCODEMP) BDORDEM, P.BDCHAVE, P.BDORDEM, P.BDORDEMPRO
  FROM (
        SELECT SP.BDCODEMP, SP.BDCODPLACAT42SP
        FROM (
              SELECT FIRST 1 BDCODPLACAT42SP, :PRCODEMP BDCODEMP
              FROM (
                    SELECT 1 BDORD, R.BDCODPLACAT42SP
                    FROM VW_VEF_BASE_TEMPPARESTSP R
                    WHERE R.BDCODEMP = :PRCODEMP
                    AND R.BDCODPLACAT42SP IS NOT NULL
                    UNION
                    SELECT 2 BDORD, P.BDCODPLACAT42SP
                    FROM VEF_BASE_TPLANOCAT42SP P
                    WHERE BDPLANODEFAULT = 'TRUE'
                   )
              ORDER BY BDORD
             ) SP
        WHERE SP.BDCODEMP = :PRCODEMP
        AND SP.BDCODPLACAT42SP IS NOT NULL
       ) SP
  LEFT OUTER JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = SP.BDCODEMP)
  LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
  LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
  JOIN VEF_EMP_TMOVENT MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN = :PRREF AND MOV.BDCODSITNF NOT IN(2, 3, 4, 5))
  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TMOVPROENT P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
  JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
  JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDDEVOL = 'FALSE')
  LEFT OUTER JOIN (
                   SELECT IVA.BDCODEMP, IVA.BDCHAVE, IVA.BDORDEM, IVA.BDCODPROD, SUM(COALESCE(IVA.BDICMSRECOLHER, 0)) BDICMSRECOLHER
                   FROM VEF_EMP_TMOVENT_IVA IVA
                   WHERE IVA.BDCODEMP = :PRCODEMP
                   GROUP BY IVA.BDCODEMP, IVA.BDCHAVE, IVA.BDORDEM, IVA.BDCODPROD
                  ) IVA ON (IVA.BDCODEMP = P.BDCODEMP AND IVA.BDCHAVE = P.BDCHAVE AND IVA.BDORDEM = P.BDORDEM AND IVA.BDCODPROD = P.BDCODPROD)
  WHERE (((COALESCE(P.BDVLRST, 0) + COALESCE(P.BDFCPRETIDO, 0) + COALESCE(P.BDVLRICMSSTRET, 0) + COALESCE(P.BDVLRFCPSTRET, 0)) > 0) OR (IVA.BDCHAVE) IS NOT NULL)
  ORDER BY MOV.BDDATAEMISSAO;

  /*Devolução de venda*/
  DELETE FROM TMP_TCAT42_CHAVE;
  INSERT INTO TMP_VEF_EMP_TDRCSTSP_1100_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCODMOV, BDQTDITEM, BDCHAVELAN)
  SELECT :PRSESSAO, MOV.BDCODEMP, MOV.BDREFLAN, P.BDCODPROD, GETORDEMSEQUENCIAL_STR(:PRSESSAO||SP.BDCODEMP||MOV.BDREFLAN||P.BDCODPROD, :prCODEMP) BDORDEM, 3 BDCODMOV, COALESCE(P.BDQTDITEM, 0) BDQTDITEM, NFD.BDCHAVE
  FROM (
        SELECT SP.BDCODEMP, SP.BDCODPLACAT42SP, UF.BDALIQINT
        FROM (
              SELECT FIRST 1 BDCODPLACAT42SP, :PRCODEMP BDCODEMP
              FROM (
                    SELECT 1 BDORD, R.BDCODPLACAT42SP
                    FROM VW_VEF_BASE_TEMPPARESTSP R
                    WHERE R.BDCODEMP = :PRCODEMP
                    AND R.BDCODPLACAT42SP IS NOT NULL
                    UNION
                    SELECT 2 BDORD, P.BDCODPLACAT42SP
                    FROM VEF_BASE_TPLANOCAT42SP P
                    WHERE BDPLANODEFAULT = 'TRUE'
                   )
              ORDER BY BDORD
             ) SP
        LEFT OUTER JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = SP.BDCODEMP)
        LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
        LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
        WHERE SP.BDCODEMP = :PRCODEMP
        AND SP.BDCODPLACAT42SP IS NOT NULL
       ) SP
  JOIN VEF_EMP_TMOVENT MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN = :PRREF)
  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDDEVOL = 'TRUE')
  JOIN VEF_EMP_TMOVPROENT P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
  JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
  LEFT OUTER JOIN SP_BUSCAR_NFE_DEVOLUCAO(MOV.BDCODEMP, MOV.BDCHAVE, 'ENT') NFD ON(NFD.BDCHAVE IS NOT NULL) /*Busca a nota referenciada*/
  WHERE NFD.BDCHAVE IS NOT NULL
  ORDER BY MOV.BDDATAEMISSAO;

  INSERT INTO TMP_TOL_VEF_EMP_DRCST_1100_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCHAVEENT, BDORDEMENT, BDORDEMPROENT)
  SELECT :PRSESSAO BDSESSAO, SP.BDCODEMP, MOV.BDREFLAN BDREFERENCIA, P.BDCODPROD, GETORDEMSEQUENCIAL_STR('TOL'||:PRSESSAO||SP.BDCODEMP||MOV.BDREFLAN||P.BDCODPROD, :prCODEMP) BDORDEM,
         MOV.BDCHAVE, I.BDORDEM, P.BDORDEMPRO
  FROM (
        SELECT SP.BDCODEMP, SP.BDCODPLACAT42SP, UF.BDALIQINT
        FROM (
              SELECT FIRST 1 BDCODPLACAT42SP, :PRCODEMP BDCODEMP
              FROM (
                    SELECT 1 BDORD, R.BDCODPLACAT42SP
                    FROM VW_VEF_BASE_TEMPPARESTSP R
                    WHERE R.BDCODEMP = :PRCODEMP
                    AND R.BDCODPLACAT42SP IS NOT NULL
                    UNION
                    SELECT 2 BDORD, P.BDCODPLACAT42SP
                    FROM VEF_BASE_TPLANOCAT42SP P
                    WHERE BDPLANODEFAULT = 'TRUE'
                   )
              ORDER BY BDORD
             ) SP
        LEFT OUTER JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = SP.BDCODEMP)
        LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
        LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
        WHERE SP.BDCODEMP = :PRCODEMP
        AND SP.BDCODPLACAT42SP IS NOT NULL
       ) SP
  JOIN VEF_EMP_TMOVENT MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN = :PRREF)
  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDDEVOL = 'TRUE')
  JOIN VEF_EMP_TMOVPROENT P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
  JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
  LEFT OUTER JOIN SP_BUSCAR_NFE_DEVOLUCAO(MOV.BDCODEMP, MOV.BDCHAVE, 'ENT') NFD ON(NFD.BDCHAVE IS NOT NULL) /*Busca a nota referenciada*/
  WHERE NFD.BDCHAVE IS NOT NULL
  ORDER BY MOV.BDDATAEMISSAO;

  /*Venda - Saída e Redução Z*/
  DELETE FROM TMP_TCAT42_CHAVE;
  INSERT INTO TMP_VEF_EMP_TDRCSTSP_1100_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDCODMOV, BDCODENQ, BDDATAMOV, BDQTDITEM, BDTIPOMOV, BDORDEM)
  SELECT D.BDSESSAO, D.BDCODEMP, D.BDREFERENCIA, D.BDCODPROD, D.BDCODMOV, D.BDCODENQLEG, D.BDDATA,
         D.BDQTDITEM, D.BDTIPOMOV, GETORDEMSEQUENCIAL_STR(:PRSESSAO||D.BDCODEMP||D.BDREFERENCIA||D.BDCODPROD, :prCODEMP) BDORDEM
  FROM (
        SELECT :PRSESSAO BDSESSAO, SP.BDCODEMP, MOV.BDREFLAN BDREFERENCIA, P.BDCODPROD,
               4 BDCODMOV, E.BDCODENQLEG, MOV.BDDATAEMISSAO BDDATA, IIF(P.BDCODFATCON IS NOT NULL, FAT.BDFATORCONVER * P.BDQTDITEM, P.BDQTDITEM) BDQTDITEM, 'SAI' BDTIPOMOV, MOV.BDCHAVE
        FROM (
              SELECT SP.BDCODEMP, SP.BDCODPLACAT42SP, PLA.BDCHAVE BDCHAVEPLANO, UF.BDALIQINT
              FROM (
                    SELECT FIRST 1 BDCODPLACAT42SP, :PRCODEMP BDCODEMP
                    FROM (
                          SELECT 1 BDORD, R.BDCODPLACAT42SP
                          FROM VW_VEF_BASE_TEMPPARESTSP R
                          WHERE R.BDCODEMP = :PRCODEMP
                          AND R.BDCODPLACAT42SP IS NOT NULL
                          UNION
                          SELECT 2 BDORD, P.BDCODPLACAT42SP
                          FROM VEF_BASE_TPLANOCAT42SP P
                          WHERE BDPLANODEFAULT = 'TRUE'
                         )
                    ORDER BY BDORD
                   ) SP
              JOIN VEF_BASE_TPLANOACOESCAT42SP PLA ON(PLA.BDCODPLACAT42SP = SP.BDCODPLACAT42SP)
              LEFT OUTER JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = SP.BDCODEMP)
              LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
              LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
              WHERE SP.BDCODEMP = :PRCODEMP
              AND SP.BDCODPLACAT42SP IS NOT NULL
             ) SP
        JOIN VEF_EMP_TMOVSAI MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN = :PRREF)
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDDEVOL = 'FALSE')
        JOIN VEF_EMP_TMOVPROSAI P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
        JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
        LEFT OUTER JOIN TFATCONV FAT ON(FAT.BDCODEMP = P.BDCODEMP AND FAT.BDCODPROD = P.BDCODPROD AND FAT.BDCODFATCON = P.BDCODFATCON)
        LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN M ON(M.BDMODELO = MOV.BDMODELO)
        LEFT OUTER JOIN SP_BUSCAR_ENQ_FED_CAT42(MOV.BDCHAVE, SP.BDCODPLACAT42SP, SP.BDCHAVEPLANO, MOV.BDCODTER, P.BDCODPROD, I.BDCODNAT, P.BDCODCSTICMS, PRO.BDNCMPROD, 'SAI', MOV.BDCONSUFINAL, P.BDCHAVE||'|'||P.BDORDEM||'|'||P.BDORDEMPRO, M.BDMODELOSTR) E ON(E.BDCODENQLEG IS NOT NULL)
        JOIN SP_BUSCAR_NF_COMPRA_CAT42SP(MOV.BDCODEMP, MOV.BDDATASAIDA, P.BDCODPROD) NC ON(NC.BDCHAVEENT IS NOT NULL OR NC.BDCHAVEINV IS NOT NULL)
        JOIN SP_CAT42SP_REGRAS_INTERNAS(E.BDCODENQLEG, P.BDVLRICMSEFET, MOV.BDCONSUFINAL) RI ON(RI.BDVALID = 'TRUE')
        WHERE E.BDCODENQLEG IS NOT NULL
        AND MOV.BDCODSITNF NOT IN(2, 3, 4 ,5, 9)
        UNION ALL
        SELECT :PRSESSAO BDSESSAO, SP.BDCODEMP, MOV.BDREFLAN BDREFERENCIA, P.BDCODPROD, 4 BDCODMOV, E.BDCODENQLEG, MOV.BDDATAREDZ BDDATA,
               IIF(P.BDCODFATCON IS NOT NULL, FAT.BDFATORCONVER * P.BDQTDITEM, P.BDQTDITEM) BDQTDITEM, 'REDZ' BDTIPOMOV, MOV.BDCHAVE
        FROM (
              SELECT SP.BDCODEMP, SP.BDCODPLACAT42SP, PLA.BDCHAVE BDCHAVEPLANO, UF.BDALIQINT
              FROM (
                    SELECT FIRST 1 BDCODPLACAT42SP, :PRCODEMP BDCODEMP
                    FROM (
                          SELECT 1 BDORD, R.BDCODPLACAT42SP
                          FROM VW_VEF_BASE_TEMPPARESTSP R
                          WHERE R.BDCODEMP = :PRCODEMP
                          AND R.BDCODPLACAT42SP IS NOT NULL
                          UNION
                          SELECT 2 BDORD, P.BDCODPLACAT42SP
                          FROM VEF_BASE_TPLANOCAT42SP P
                          WHERE BDPLANODEFAULT = 'TRUE'
                         )
                    ORDER BY BDORD
                   ) SP
              JOIN VEF_BASE_TPLANOACOESCAT42SP PLA ON(PLA.BDCODPLACAT42SP = SP.BDCODPLACAT42SP)
              LEFT OUTER JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = SP.BDCODEMP)
              LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
              LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
              WHERE SP.BDCODEMP = :PRCODEMP
              AND SP.BDCODPLACAT42SP IS NOT NULL
             ) SP
        JOIN VEF_EMP_TREDZ MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN = :PRREF)
        JOIN VEF_EMP_TDOCECF I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TITEMDOCECF P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEMDOCECF = I.BDORDEMDOCECF)
        JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = P.BDCODNAT AND NAT.BDDEVOL = 'FALSE')
        JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
        LEFT OUTER JOIN TFATCONV FAT ON(FAT.BDCODEMP = P.BDCODEMP AND FAT.BDCODPROD = P.BDCODPROD AND FAT.BDCODFATCON = P.BDCODFATCON)
        LEFT OUTER JOIN VEF_BASE_TTABDOCFIS M ON(M.BDCODDOCFIS = I.BDCODDOCFIS)
        LEFT OUTER JOIN SP_BUSCAR_ENQ_FED_CAT42(MOV.BDCHAVE, SP.BDCODPLACAT42SP, SP.BDCHAVEPLANO, I.BDCODTER, P.BDCODPROD, P.BDCODNAT, P.BDCODCSTICMS, PRO.BDNCMPROD, 'REDZ', 1, P.BDCHAVE||'|'||P.BDORDEMDOCECF||'|'||P.BDORDEMITEM, M.BDDOCFIS) E ON(E.BDCODENQLEG IS NOT NULL)
        JOIN SP_BUSCAR_NF_COMPRA_CAT42SP(MOV.BDCODEMP, MOV.BDDATAREDZ, P.BDCODPROD) NC ON(NC.BDCHAVEENT IS NOT NULL OR NC.BDCHAVEINV IS NOT NULL)
--        JOIN SP_CAT42SP_REGRAS_INTERNAS(E.BDCODENQLEG, P.BDICMSEFETIVO, 1) RI ON(RI.BDVALID = 'TRUE')
        WHERE E.BDCODENQLEG IS NOT NULL
        AND I.BDCODSITNF NOT IN(2, 3, 4 ,5)
       ) D
  ORDER BY D.BDDATA, D.BDTIPOMOV, D.BDCHAVE;

  INSERT INTO TMP_TOL_VEF_EMP_DRCST_1100_TEMP(BDSESSAO, BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCHAVESAI, BDORDEMSAI, BDORDEMPROSAI, BDCHAVEREDZ, BDORDEMREDZ, BDORDEMPROREDZ)
  SELECT :PRSESSAO BDSESSAO, D.BDCODEMP, D.BDREFERENCIA, D.BDCODPROD, GETORDEMSEQUENCIAL_STR('TOL'||:PRSESSAO||D.BDCODEMP||D.BDREFERENCIA||D.BDCODPROD, :prCODEMP) BDORDEM,
         D.BDCHAVESAI, D.BDORDEMSAI, D.BDORDEMPROSAI, D.BDCHAVEREDZ, D.BDORDEMREDZ, D.BDORDEMPROREDZ
  FROM (
        SELECT :PRSESSAO BDSESSAO, SP.BDCODEMP, MOV.BDREFLAN BDREFERENCIA, P.BDCODPROD,
               4 BDCODMOV, E.BDCODENQLEG, MOV.BDDATAEMISSAO BDDATA, IIF(P.BDCODFATCON IS NOT NULL, FAT.BDFATORCONVER * P.BDQTDITEM, P.BDQTDITEM) BDQTDITEM, 'SAI' BDTIPOMOV,
               MOV.BDCHAVE BDCHAVESAI, I.BDORDEM BDORDEMSAI, P.BDORDEMPRO BDORDEMPROSAI, NULL BDCHAVEREDZ, NULL BDORDEMREDZ, NULL BDORDEMPROREDZ, MOV.BDCHAVE
        FROM (
              SELECT SP.BDCODEMP, SP.BDCODPLACAT42SP, PLA.BDCHAVE BDCHAVEPLANO, UF.BDALIQINT
              FROM (
                    SELECT FIRST 1 BDCODPLACAT42SP, :PRCODEMP BDCODEMP
                    FROM (
                          SELECT 1 BDORD, R.BDCODPLACAT42SP
                          FROM VW_VEF_BASE_TEMPPARESTSP R
                          WHERE R.BDCODEMP = :PRCODEMP
                          AND R.BDCODPLACAT42SP IS NOT NULL
                          UNION
                          SELECT 2 BDORD, P.BDCODPLACAT42SP
                          FROM VEF_BASE_TPLANOCAT42SP P
                          WHERE BDPLANODEFAULT = 'TRUE'
                         )
                    ORDER BY BDORD
                   ) SP
              JOIN VEF_BASE_TPLANOACOESCAT42SP PLA ON(PLA.BDCODPLACAT42SP = SP.BDCODPLACAT42SP)
              LEFT OUTER JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = SP.BDCODEMP)
              LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
              LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
              WHERE SP.BDCODEMP = :PRCODEMP
              AND SP.BDCODPLACAT42SP IS NOT NULL
             ) SP
        JOIN VEF_EMP_TMOVSAI MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN = :PRREF)
        JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDDEVOL = 'FALSE')
        JOIN VEF_EMP_TMOVPROSAI P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
        JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
        LEFT OUTER JOIN TFATCONV FAT ON(FAT.BDCODEMP = P.BDCODEMP AND FAT.BDCODPROD = P.BDCODPROD AND FAT.BDCODFATCON = P.BDCODFATCON)
        LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN M ON(M.BDMODELO = MOV.BDMODELO)
        LEFT OUTER JOIN SP_BUSCAR_ENQ_FED_CAT42(MOV.BDCHAVE, SP.BDCODPLACAT42SP, SP.BDCHAVEPLANO, MOV.BDCODTER, P.BDCODPROD, I.BDCODNAT, P.BDCODCSTICMS, PRO.BDNCMPROD, 'TS', MOV.BDCONSUFINAL, P.BDCHAVE||'|'||P.BDORDEM||'|'||P.BDORDEMPRO, M.BDMODELOSTR) E ON(E.BDCODENQLEG IS NOT NULL)
        JOIN SP_BUSCAR_NF_COMPRA_CAT42SP(MOV.BDCODEMP, MOV.BDDATASAIDA, P.BDCODPROD) NC ON(NC.BDCHAVEENT IS NOT NULL OR NC.BDCHAVEINV IS NOT NULL)
        JOIN SP_CAT42SP_REGRAS_INTERNAS(E.BDCODENQLEG, P.BDVLRICMSEFET, MOV.BDCONSUFINAL) RI ON(RI.BDVALID = 'TRUE')
        WHERE E.BDCODENQLEG IS NOT NULL
        AND MOV.BDCODSITNF NOT IN(2, 3, 4 ,5, 9)
        UNION ALL
        SELECT :PRSESSAO BDSESSAO, SP.BDCODEMP, MOV.BDREFLAN BDREFERENCIA, P.BDCODPROD, 4 BDCODMOV, E.BDCODENQLEG, MOV.BDDATAREDZ BDDATA,
               IIF(P.BDCODFATCON IS NOT NULL, FAT.BDFATORCONVER * P.BDQTDITEM, P.BDQTDITEM) BDQTDITEM, 'REDZ' BDTIPOMOV,
               NULL BDCHAVESAI, NULL BDORDEMSAI, NULL BDORDEMPROSAI,
               MOV.BDCHAVE BDCHAVEREDZ, I.BDORDEMDOCECF BDORDEMREDZ, P.BDORDEMITEM BDORDEMPROREDZ, MOV.BDCHAVE
        FROM (
              SELECT SP.BDCODEMP, SP.BDCODPLACAT42SP, PLA.BDCHAVE BDCHAVEPLANO, UF.BDALIQINT
              FROM (
                    SELECT FIRST 1 BDCODPLACAT42SP, :PRCODEMP BDCODEMP
                    FROM (
                          SELECT 1 BDORD, R.BDCODPLACAT42SP
                          FROM VW_VEF_BASE_TEMPPARESTSP R
                          WHERE R.BDCODEMP = :PRCODEMP
                          AND R.BDCODPLACAT42SP IS NOT NULL
                          UNION
                          SELECT 2 BDORD, P.BDCODPLACAT42SP
                          FROM VEF_BASE_TPLANOCAT42SP P
                          WHERE BDPLANODEFAULT = 'TRUE'
                         )
                    ORDER BY BDORD
                   ) SP
              JOIN VEF_BASE_TPLANOACOESCAT42SP PLA ON(PLA.BDCODPLACAT42SP = SP.BDCODPLACAT42SP)
              LEFT OUTER JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = SP.BDCODEMP)
              LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
              LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
              WHERE SP.BDCODEMP = :PRCODEMP
              AND SP.BDCODPLACAT42SP IS NOT NULL
             ) SP
        JOIN VEF_EMP_TREDZ MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN = :PRREF)
        JOIN VEF_EMP_TDOCECF I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
        JOIN VEF_EMP_TITEMDOCECF P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEMDOCECF = I.BDORDEMDOCECF)
        JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = P.BDCODNAT AND NAT.BDDEVOL = 'FALSE')
        JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
        LEFT OUTER JOIN TFATCONV FAT ON(FAT.BDCODEMP = P.BDCODEMP AND FAT.BDCODPROD = P.BDCODPROD AND FAT.BDCODFATCON = P.BDCODFATCON)
        LEFT OUTER JOIN VEF_BASE_TTABDOCFIS M ON(M.BDCODDOCFIS = I.BDCODDOCFIS)
        LEFT OUTER JOIN SP_BUSCAR_ENQ_FED_CAT42(MOV.BDCHAVE, SP.BDCODPLACAT42SP, SP.BDCHAVEPLANO, I.BDCODTER, P.BDCODPROD, P.BDCODNAT, P.BDCODCSTICMS, PRO.BDNCMPROD, 'TRZ', 1, P.BDCHAVE||'|'||P.BDORDEMDOCECF||'|'||P.BDORDEMITEM, M.BDDOCFIS) E ON(E.BDCODENQLEG IS NOT NULL)
        JOIN SP_BUSCAR_NF_COMPRA_CAT42SP(MOV.BDCODEMP, MOV.BDDATAREDZ, P.BDCODPROD) NC ON(NC.BDCHAVEENT IS NOT NULL OR NC.BDCHAVEINV IS NOT NULL)
--        JOIN SP_CAT42SP_REGRAS_INTERNAS(E.BDCODENQLEG, P.BDICMSEFETIVO, 1) RI ON(RI.BDVALID = 'TRUE')
        WHERE E.BDCODENQLEG IS NOT NULL
        AND I.BDCODSITNF NOT IN(2, 3, 4 ,5)
       ) D
  ORDER BY D.BDDATA, D.BDTIPOMOV, D.BDCHAVE;

  EXECUTE PROCEDURE SP_APURAR_CAT42SP_1100_REFRESH(:PRSESSAO, :PRCODEMP, :PRREF);
END ^

CREATE OR ALTER procedure SP_GRAVAR_CAT42SP (
    PRSESSAO integer,
    PRCODCONT integer)
as
begin
  DELETE FROM VEF_EMP_TDRCSTSPGER D
  WHERE EXISTS (
                SELECT A.BDSESSAO
                FROM TMP_VEF_EMP_TDRCSTSP_RES_TEMP A
                WHERE A.BDSESSAO = :PRSESSAO
                AND A.BDCODEMP = D.BDCODEMP
                AND A.BDREFERENCIA = D.BDREFERENCIA
                GROUP BY BDSESSAO, BDCODEMP, BDREFERENCIA
               );

  INSERT INTO VEF_EMP_TDRCSTSPGER(BDCODEMP, BDREFERENCIA, BDCODCONT)
  SELECT BDCODEMP, BDREFERENCIA, :PRCODCONT
  FROM TMP_VEF_EMP_TDRCSTSP_RES_TEMP
  WHERE BDSESSAO = :PRSESSAO
  GROUP BY BDSESSAO, BDCODEMP, BDREFERENCIA;

  INSERT INTO VEF_EMP_TDRCSTSP_1050(BDCODEMP, BDREFERENCIA, BDCODPROD, BDCODTIPO, BDQTDE_INICIAL, BDVL_UNIT_INICIAL, BDVL_TOT_INICIAL,
                                    BDQTDE_FINAL, BDVL_UNIT_FINAL, BDVL_TOT_FINAL, BDVL_RESS_REST, BDVL_COMPLEMENTO)
  SELECT BDCODEMP, BDREFERENCIA, BDCODPROD, BDCODTIPO, BDQTDE_INICIAL, BDVL_UNIT_INICIAL, BDVL_TOT_INICIAL,
         BDQTDE_FINAL, BDVL_UNIT_FINAL, BDVL_TOT_FINAL, BDVL_RESS_REST, BDVL_COMPLEMENTO
  FROM TMP_VEF_EMP_TDRCSTSP_1050_TEMP
  WHERE BDSESSAO = :PRSESSAO;

  INSERT INTO VEF_EMP_TDRCSTSP_1100(BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCODMOV, BDVL_ICMS_SUP_ENT, BDVL_ICMS_MEDIO_SUP,
                                    BDCODENQ, BDVL_TOT_MEDIO_SUP, BDVL_CONFRONTO, BDVL_RESSARCIMENTO, BDVL_COMPLEMENTO, BDQTD_TOTAL,
                                    BDVL_UNIT_SALDO, BDVL_TOT_SALDO, BDQTDITEM)
  SELECT BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCODMOV, BDVL_ICMS_SUP_ENT, BDVL_ICMS_MEDIO_SUP,
         BDCODENQ, BDVL_TOT_MEDIO_SUP, BDVL_CONFRONTO, BDVL_RESSARCIMENTO, BDVL_COMPLEMENTO, BDQTD_TOTAL,
         BDVL_UNIT_SALDO, BDVL_TOT_SALDO, BDQTDITEM
  FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP
  WHERE BDSESSAO = :PRSESSAO;

  INSERT INTO TOL_VEF_EMP_DRCSTSP_1100(BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCHAVEENT, BDORDEMENT, BDORDEMPROENT,
                                       BDCHAVESAI, BDORDEMSAI, BDORDEMPROSAI, BDCHAVEINV, BDCHAVEREDZ, BDORDEMREDZ, BDORDEMPROREDZ)
  SELECT BDCODEMP, BDREFERENCIA, BDCODPROD, BDORDEM, BDCHAVEENT, BDORDEMENT, BDORDEMPROENT,
         BDCHAVESAI, BDORDEMSAI, BDORDEMPROSAI, BDCHAVEINV, BDCHAVEREDZ, BDORDEMREDZ, BDORDEMPROREDZ
  FROM TMP_TOL_VEF_EMP_DRCST_1100_TEMP
  WHERE BDSESSAO = :PRSESSAO;

  INSERT INTO VEF_EMP_TDRCSTSP_RESUMO (BDCODEMP, BDREFERENCIA, BDCODTIPO, BDCODENQLEG, BDSD_ICMS_ST_RESS,
                                       BDSD_ICMS_ST_COMPL, BDSD_ICMS_ST_RECUP, BDSD_ICMS_ST_RECOL)
  SELECT BDCODEMP, BDREFERENCIA, BDCODTIPO, BDCODENQLEG, BDSD_ICMS_ST_RESS,
         BDSD_ICMS_ST_COMPL, BDSD_ICMS_ST_RECUP, BDSD_ICMS_ST_RECOL
  FROM TMP_VEF_EMP_TDRCSTSP_RES_TEMP
  WHERE BDSESSAO = :PRSESSAO;
end^

CREATE OR ALTER PROCEDURE SP_VALIDAR_CAT42SP (
    PRREFINI INTEGER,
    PRREFFIM INTEGER)
AS
DECLARE VARIABLE WCODPLANODEFAULT INTEGER;
BEGIN
  SELECT P.BDCODPLACAT42SP
  FROM VEF_BASE_TPLANOCAT42SP P
  WHERE BDPLANODEFAULT = 'TRUE'
  INTO :wCodPlanoDefault;

  /*
    O item XXXX possui documento fiscal de saída parametrizado pelo plano da Portaria CAT 42/2018 mas não possui entrada com ST
=======  
    O item XXXX possui documento fiscal de saída parametrizado pelo plano da Portaria CAT 42/2018 mas não possui entrada com ST
>>>>>>> .theirs  */
  DELETE FROM TMP_TCAT42_CHAVE;
  INSERT INTO VEF_INCON_TDRCSTSP(BDCODEMP, BDREFERENCIA, BDCHAVESAI, BDDESCRICAO)
  SELECT MOV.BDCODEMP, MOV.BDREFLAN, MOV.BDCHAVE, 'Empresa: '||SP.BDCODEMP||' - O item '||COALESCE(PRO.BDCODSAIDA, PRO.BDCODPROD)||' possui documento fiscal de saída parametrizado pelo plano da Portaria CAT 42/2018 mas não possui entrada com ST'
  FROM (
        SELECT SP.BDCODEMP, COALESCE(SP.BDCODPLACAT42SP, :wCodPlanoDefault) BDCODPLACAT42SP, PLA.BDCHAVE BDCHAVEPLANO, UF.BDALIQINT
        FROM VW_VEF_BASE_TEMPPARESTSP SP
        LEFT OUTER JOIN VEF_BASE_TPLANOACOESCAT42SP PLA ON(PLA.BDCODPLACAT42SP = COALESCE(SP.BDCODPLACAT42SP, :wCodPlanoDefault))
        LEFT OUTER JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = SP.BDCODEMP)
        LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
        LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
        JOIN TMP_EMPRESAS_SELECT EMP ON(EMP.BDCODEMP = SP.BDCODEMP)
       ) SP
  JOIN VEF_EMP_TMOVSAI MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN BETWEEN :PRREFINI AND :PRREFFIM)
  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDDEVOL = 'FALSE')
  JOIN VEF_EMP_TMOVPROSAI P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
  JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
  LEFT OUTER JOIN TFATCONV FAT ON(FAT.BDCODEMP = P.BDCODEMP AND FAT.BDCODPROD = P.BDCODPROD AND FAT.BDCODFATCON = P.BDCODFATCON)
  LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN M ON(M.BDMODELO = MOV.BDMODELO)
  LEFT OUTER JOIN SP_BUSCAR_ENQ_FED_CAT42(MOV.BDCHAVE, SP.BDCODPLACAT42SP, SP.BDCHAVEPLANO, MOV.BDCODTER, P.BDCODPROD, I.BDCODNAT, P.BDCODCSTICMS, PRO.BDNCMPROD, 'SAI', MOV.BDCONSUFINAL, P.BDCHAVE||'|'||P.BDORDEM||'|'||P.BDORDEMPRO, M.BDMODELOSTR) E ON(E.BDCODENQLEG IS NOT NULL)
  JOIN SP_BUSCAR_NF_COMPRA_CAT42SP(MOV.BDCODEMP, MOV.BDDATASAIDA, P.BDCODPROD) NC ON(NC.BDCHAVEENT IS NULL AND NC.BDCHAVEINV IS NULL)
  JOIN SP_CAT42SP_REGRAS_INTERNAS(E.BDCODENQLEG, P.BDVLRICMSEFET, MOV.BDCONSUFINAL) RI ON(RI.BDVALID = 'TRUE')
  WHERE E.BDCODENQLEG IS NOT NULL
  AND MOV.BDCODSITNF NOT IN(2, 3, 4 ,5, 9)
  UNION ALL
  SELECT MOV.BDCODEMP, MOV.BDREFLAN, MOV.BDCHAVE, 'Empresa: '||SP.BDCODEMP||' - O item '||COALESCE(PRO.BDCODSAIDA, PRO.BDCODPROD)||' possui documento fiscal de saída parametrizado pelo plano da Portaria CAT 42/2018 mas não possui entrada com ST'
  FROM (
        SELECT SP.BDCODEMP, COALESCE(SP.BDCODPLACAT42SP, :wCodPlanoDefault) BDCODPLACAT42SP, PLA.BDCHAVE BDCHAVEPLANO, UF.BDALIQINT
        FROM VW_VEF_BASE_TEMPPARESTSP SP
        LEFT OUTER JOIN VEF_BASE_TPLANOACOESCAT42SP PLA ON(PLA.BDCODPLACAT42SP = COALESCE(SP.BDCODPLACAT42SP, :wCodPlanoDefault))
        LEFT OUTER JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = SP.BDCODEMP)
        LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
        LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
        JOIN TMP_EMPRESAS_SELECT EMP ON(EMP.BDCODEMP = SP.BDCODEMP)
       ) SP
  JOIN VEF_EMP_TREDZ MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN BETWEEN :PRREFINI AND :PRREFFIM)
  JOIN VEF_EMP_TDOCECF I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_EMP_TITEMDOCECF P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEMDOCECF = I.BDORDEMDOCECF)
  JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = P.BDCODNAT AND NAT.BDDEVOL = 'FALSE')
  JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
  LEFT OUTER JOIN TFATCONV FAT ON(FAT.BDCODEMP = P.BDCODEMP AND FAT.BDCODPROD = P.BDCODPROD AND FAT.BDCODFATCON = P.BDCODFATCON)
  LEFT OUTER JOIN VEF_BASE_TTABDOCFIS M ON(M.BDCODDOCFIS = I.BDCODDOCFIS)
  LEFT OUTER JOIN SP_BUSCAR_ENQ_FED_CAT42(MOV.BDCHAVE, SP.BDCODPLACAT42SP, SP.BDCHAVEPLANO, I.BDCODTER, P.BDCODPROD, P.BDCODNAT, P.BDCODCSTICMS, PRO.BDNCMPROD, 'REDZ', 1, P.BDCHAVE||'|'||P.BDORDEMDOCECF||'|'||P.BDORDEMITEM, M.BDDOCFIS) E ON(E.BDCODENQLEG IS NOT NULL)
  JOIN SP_BUSCAR_NF_COMPRA_CAT42SP(MOV.BDCODEMP, MOV.BDDATAREDZ, P.BDCODPROD) NC ON(NC.BDCHAVEENT IS NULL AND NC.BDCHAVEINV IS NULL)
--JOIN SP_CAT42SP_REGRAS_INTERNAS(E.BDCODENQLEG, P.BDICMSEFETIVO, 1) RI ON(RI.BDVALID = 'TRUE')
  WHERE E.BDCODENQLEG IS NOT NULL
  AND I.BDCODSITNF NOT IN(2, 3, 4 ,5);

  /*
     A quantidade das vendas para o item XXXX é maior que o saldo de aquisições, gerando saldo negativo em estoque
  */
  INSERT INTO VEF_INCON_TDRCSTSP(BDCODEMP, BDREFERENCIA, BDDESCRICAO)
  SELECT A.BDCODEMP, A.BDREFERENCIA, 'Empresa: '||A.BDCODEMP||' - A quantidade das vendas para o item '||COALESCE(A.BDCODSAIDA, A.BDCODPROD)||' - '||A.BDDESCPROD||' é maior que o saldo de aquisições, gerando saldo negativo em estoque'
  FROM (
        SELECT A.BDCODEMP, A.BDREFERENCIA, PRO.BDCODPROD, PRO.BDCODSAIDA, PRO.BDDESCPROD
        FROM VEF_EMP_TDRCSTSP_1100 A
        JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = A.BDCODEMP AND PRO.BDCODPROD = A.BDCODPROD)
        JOIN TMP_EMPRESAS_SELECT EMP ON(EMP.BDCODEMP = A.BDCODEMP)
        WHERE A.BDREFERENCIA BETWEEN :PRREFINI AND :PRREFFIM
        AND A.BDQTD_TOTAL < 0
        GROUP BY A.BDCODEMP, A.BDREFERENCIA, PRO.BDCODPROD, PRO.BDCODSAIDA, PRO.BDDESCPROD
       ) A;

  /*
     A nota fiscal de devolução do movimento XXX, numero ZZZ chave AAA não contém nota referenciada no C113
  */
  /*Devolução de venda*/
  DELETE FROM TMP_TCAT42_CHAVE;
  INSERT INTO VEF_INCON_TDRCSTSP(BDCODEMP, BDREFERENCIA, BDDESCRICAO)
  SELECT MOV.BDCODEMP, MOV.BDREFLAN, 'Empresa: '||SP.BDCODEMP||' - A nota fiscal de devolução do movimento de entrada, número '||MOV.BDNUMDOCINI||' chave '||MOV.BDCHAVE||' não contém nota referenciada no C113'
  FROM (
        SELECT SP.BDCODEMP
        FROM VW_VEF_BASE_TEMPPARESTSP SP
        JOIN TMP_EMPRESAS_SELECT EMP ON(EMP.BDCODEMP = SP.BDCODEMP)
        AND SP.BDCODPLACAT42SP IS NOT NULL
       ) SP
  JOIN VEF_EMP_TMOVENT MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN BETWEEN :PRREFINI AND :PRREFFIM)
  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDDEVOL = 'TRUE')
  JOIN VEF_EMP_TMOVPROENT P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
  JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
  LEFT OUTER JOIN SP_BUSCAR_NFE_DEVOLUCAO(MOV.BDCODEMP, MOV.BDCHAVE, 'ENT') NFD ON(1=1) /*Busca a nota referenciada*/
  WHERE NFD.BDCHAVEC113 IS NULL
  ORDER BY MOV.BDDATAEMISSAO;

  /*Devolução da compra*/
  DELETE FROM TMP_TCAT42_CHAVE;
  INSERT INTO VEF_INCON_TDRCSTSP(BDCODEMP, BDREFERENCIA, BDDESCRICAO)
  SELECT MOV.BDCODEMP, MOV.BDREFLAN, 'Empresa: '||SP.BDCODEMP||' - A nota fiscal de devolução do movimento de saída, número '||MOV.BDNUMDOCINI||' chave '||MOV.BDCHAVE||' não contém nota referenciada no C113'
  FROM (
        SELECT SP.BDCODEMP, COALESCE(SP.BDCODPLACAT42SP, :wCodPlanoDefault) BDCODPLACAT42SP, PLA.BDCHAVE BDCHAVEPLANO, UF.BDALIQINT
        FROM VW_VEF_BASE_TEMPPARESTSP SP
        JOIN VEF_BASE_TPLANOACOESCAT42SP PLA ON(PLA.BDCODPLACAT42SP = SP.BDCODPLACAT42SP)
        LEFT OUTER JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = SP.BDCODEMP)
        LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
        LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
        JOIN TMP_EMPRESAS_SELECT EMP ON(EMP.BDCODEMP = SP.BDCODEMP)
        AND SP.BDCODPLACAT42SP IS NOT NULL
       ) SP
  JOIN VEF_EMP_TMOVSAI MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN BETWEEN :PRREFINI AND :PRREFFIM)
  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDDEVOL = 'TRUE')
  JOIN VEF_EMP_TMOVPROSAI P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
  JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
  LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN M ON(M.BDMODELO = MOV.BDMODELO)
  LEFT OUTER JOIN SP_BUSCAR_ENQ_FED_CAT42(MOV.BDCHAVE, SP.BDCODPLACAT42SP, SP.BDCHAVEPLANO, MOV.BDCODTER, P.BDCODPROD, I.BDCODNAT, P.BDCODCSTICMS, PRO.BDNCMPROD, 'SAI', MOV.BDCONSUFINAL, P.BDCHAVE||'|'||P.BDORDEM||'|'||P.BDORDEMPRO, M.BDMODELOSTR) E ON(E.BDCODENQLEG IS NOT NULL)
  LEFT OUTER JOIN SP_BUSCAR_NFE_DEVOLUCAO(MOV.BDCODEMP, MOV.BDCHAVE, 'SAI') NFD ON(1=1) /*Busca a nota referenciada*/
  WHERE E.BDCODENQLEG IS NOT NULL
  AND NFD.BDCHAVEC113 IS NULL
  ORDER BY MOV.BDDATAEMISSAO;

  /*
     A nota fiscal de devolução do movimento XXX, numero ZZZ chave AAA contém nota referenciada no C113 que não existe no lançamento
  */
  /*Devolução de venda*/
  DELETE FROM TMP_TCAT42_CHAVE;
  INSERT INTO VEF_INCON_TDRCSTSP(BDCODEMP, BDREFERENCIA, BDDESCRICAO)
  SELECT MOV.BDCODEMP, MOV.BDREFLAN, 'Empresa: '||SP.BDCODEMP||' - A nota fiscal de devolução do movimento de entrada, número '||MOV.BDNUMDOCINI||' chave '||MOV.BDCHAVE||' contém nota referenciada no C113 que não existe no lançamento'
  FROM (
        SELECT SP.BDCODEMP
        FROM VW_VEF_BASE_TEMPPARESTSP SP
        JOIN TMP_EMPRESAS_SELECT EMP ON(EMP.BDCODEMP = SP.BDCODEMP)
        AND SP.BDCODPLACAT42SP IS NOT NULL
       ) SP
  JOIN VEF_EMP_TMOVENT MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN BETWEEN :PRREFINI AND :PRREFFIM)
  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDDEVOL = 'TRUE')
  JOIN VEF_EMP_TMOVPROENT P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
  JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
  LEFT OUTER JOIN SP_BUSCAR_NFE_DEVOLUCAO(MOV.BDCODEMP, MOV.BDCHAVE, 'ENT') NFD ON(NFD.BDCHAVE IS NULL) /*Busca a nota referenciada*/
  WHERE NFD.BDCHAVEC113 IS NOT NULL
  AND NFD.BDCHAVE IS NULL
  ORDER BY MOV.BDDATAEMISSAO;

  /*Devolução da compra*/
  DELETE FROM TMP_TCAT42_CHAVE;
  INSERT INTO VEF_INCON_TDRCSTSP(BDCODEMP, BDREFERENCIA, BDDESCRICAO)
  SELECT MOV.BDCODEMP, MOV.BDREFLAN, 'Empresa: '||SP.BDCODEMP||' - A nota fiscal de devolução do movimento de saída, número '||MOV.BDNUMDOCINI||' chave '||MOV.BDCHAVE||' contém nota referenciada no C113 que não existe no lançamento'
  FROM (
        SELECT SP.BDCODEMP, COALESCE(SP.BDCODPLACAT42SP, :wCodPlanoDefault) BDCODPLACAT42SP, PLA.BDCHAVE BDCHAVEPLANO, UF.BDALIQINT
        FROM VW_VEF_BASE_TEMPPARESTSP SP
        JOIN VEF_BASE_TPLANOACOESCAT42SP PLA ON(PLA.BDCODPLACAT42SP = SP.BDCODPLACAT42SP)
        LEFT OUTER JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = SP.BDCODEMP)
        LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
        LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
        JOIN TMP_EMPRESAS_SELECT EMP ON(EMP.BDCODEMP = SP.BDCODEMP)
        AND SP.BDCODPLACAT42SP IS NOT NULL
       ) SP
  JOIN VEF_EMP_TMOVSAI MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN BETWEEN :PRREFINI AND :PRREFFIM)
  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDDEVOL = 'TRUE')
  JOIN VEF_EMP_TMOVPROSAI P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
  JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
  LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN M ON(M.BDMODELO = MOV.BDMODELO)
  LEFT OUTER JOIN SP_BUSCAR_ENQ_FED_CAT42(MOV.BDCHAVE, SP.BDCODPLACAT42SP, SP.BDCHAVEPLANO, MOV.BDCODTER, P.BDCODPROD, I.BDCODNAT, P.BDCODCSTICMS, PRO.BDNCMPROD, 'SAI', MOV.BDCONSUFINAL, P.BDCHAVE||'|'||P.BDORDEM||'|'||P.BDORDEMPRO, M.BDMODELOSTR) E ON(E.BDCODENQLEG IS NOT NULL)
  LEFT OUTER JOIN SP_BUSCAR_NFE_DEVOLUCAO(MOV.BDCODEMP, MOV.BDCHAVE, 'SAI') NFD ON(NFD.BDCHAVE IS NULL) /*Busca a nota referenciada*/
  WHERE E.BDCODENQLEG IS NOT NULL
  AND NFD.BDCHAVEC113 IS NOT NULL
  AND NFD.BDCHAVE IS NULL
  ORDER BY MOV.BDDATAEMISSAO;

  /*
     A nota referenciada no documento de devolução movimento XXX, chave ZZZ, numero eee, não conta nas apurações de ressarcimento, restituição e complemento de ST
  */
  /*Devolução de venda*/
  DELETE FROM TMP_TCAT42_CHAVE;
  INSERT INTO VEF_INCON_TDRCSTSP(BDCODEMP, BDREFERENCIA, BDDESCRICAO)
  SELECT MOV.BDCODEMP, MOV.BDREFLAN, 'Empresa: '||SP.BDCODEMP||' - A nota referenciada no documento de devolução movimento entrada, chave '||MOV.BDCHAVE||', numero '||MOV.BDNUMDOCINI||', não consta nas apurações de ressarcimento, restituição e complemento de ST'
  FROM (
        SELECT SP.BDCODEMP, COALESCE(SP.BDCODPLACAT42SP, :wCodPlanoDefault) BDCODPLACAT42SP, UF.BDALIQINT
        FROM VW_VEF_BASE_TEMPPARESTSP SP
        LEFT OUTER JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = SP.BDCODEMP)
        LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
        LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
        JOIN TMP_EMPRESAS_SELECT EMP ON(EMP.BDCODEMP = SP.BDCODEMP)
       ) SP
  JOIN VEF_EMP_TMOVENT MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN BETWEEN :PRREFINI AND :PRREFFIM)
  JOIN VEF_EMP_TMOVENTITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDDEVOL = 'TRUE')
  JOIN VEF_EMP_TMOVPROENT P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
  JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
  LEFT OUTER JOIN SP_BUSCAR_NFE_DEVOLUCAO(MOV.BDCODEMP, MOV.BDCHAVE, 'ENT') NFD ON(NFD.BDCHAVE IS NOT NULL) /*Busca a nota referenciada*/
  LEFT OUTER JOIN SP_GET_VALORES_DEV(0, MOV.BDCODEMP, MOV.BDREFLAN, P.BDCODPROD, NFD.BDCHAVE, 'SAI') DEV ON(DEV.BDCODENQ = 0)
  WHERE NFD.BDCHAVE IS NOT NULL
  AND NOT EXISTS (
                  SELECT *
                  FROM VEF_EMP_TDRCSTSP_1100 A
                  JOIN TOL_VEF_EMP_DRCSTSP_1100 T ON(T.BDCODEMP = A.BDCODEMP AND T.BDREFERENCIA = A.BDREFERENCIA AND T.BDCODPROD = A.BDCODPROD AND
                                                     T.BDORDEM = A.BDORDEM AND T.BDCHAVESAI = NFD.BDCHAVE)
                  WHERE A.BDCODEMP = MOV.BDCODEMP
                  AND (A.BDREFERENCIA = (SELECT BDREF FROM DEC_REF(MOV.BDREFLAN)) OR A.BDREFERENCIA = MOV.BDREFLAN)
                  AND A.BDCODPROD =  P.BDCODPROD
                  AND A.BDCODMOV = 4
                 )
  ORDER BY MOV.BDDATAEMISSAO;

  /*Devolução da compra*/
  DELETE FROM TMP_TCAT42_CHAVE;
  INSERT INTO VEF_INCON_TDRCSTSP(BDCODEMP, BDREFERENCIA, BDDESCRICAO)
  SELECT MOV.BDCODEMP, MOV.BDREFLAN, 'Empresa: '||SP.BDCODEMP||' - A nota referenciada no documento de devolução movimento saída, chave '||MOV.BDCHAVE||', número '||MOV.BDNUMDOCINI||', não consta nas apurações de ressarcimento, restituição e complemento de ST'
  FROM (
        SELECT SP.BDCODEMP, COALESCE(SP.BDCODPLACAT42SP, :wCodPlanoDefault) BDCODPLACAT42SP, PLA.BDCHAVE BDCHAVEPLANO, UF.BDALIQINT
        FROM VW_VEF_BASE_TEMPPARESTSP SP
        JOIN VEF_BASE_TPLANOACOESCAT42SP PLA ON(PLA.BDCODPLACAT42SP = SP.BDCODPLACAT42SP)
        LEFT OUTER JOIN VW_TEMPRESAS_REF ER ON(ER.BDCODEMP = SP.BDCODEMP)
        LEFT OUTER JOIN TCIDADE C ON(C.BDCODCID = ER.BDCODCID)
        LEFT OUTER JOIN TUF UF ON(UF.BDCODUF = C.BDCODUF)
        JOIN TMP_EMPRESAS_SELECT EMP ON(EMP.BDCODEMP = SP.BDCODEMP)
       ) SP
  JOIN VEF_EMP_TMOVSAI MOV ON(MOV.BDCODEMP = SP.BDCODEMP AND MOV.BDREFLAN BETWEEN :PRREFINI AND :PRREFFIM)
  JOIN VEF_EMP_TMOVSAIITENS I ON(I.BDCODEMP = MOV.BDCODEMP AND I.BDCHAVE = MOV.BDCHAVE)
  JOIN VEF_BASE_TNATOP NAT ON(NAT.BDCODNAT = I.BDCODNAT AND NAT.BDDEVOL = 'TRUE')
  JOIN VEF_EMP_TMOVPROSAI P ON(P.BDCODEMP = I.BDCODEMP AND P.BDCHAVE = I.BDCHAVE AND P.BDORDEM = I.BDORDEM)
  JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = P.BDCODEMP AND PRO.BDCODPROD = P.BDCODPROD)
  LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN M ON(M.BDMODELO = MOV.BDMODELO)
  LEFT OUTER JOIN SP_BUSCAR_ENQ_FED_CAT42(MOV.BDCHAVE, SP.BDCODPLACAT42SP, SP.BDCHAVEPLANO, MOV.BDCODTER, P.BDCODPROD, I.BDCODNAT, P.BDCODCSTICMS, PRO.BDNCMPROD, 'SAI', MOV.BDCONSUFINAL, P.BDCHAVE||'|'||P.BDORDEM||'|'||P.BDORDEMPRO, M.BDMODELOSTR) E ON(E.BDCODENQLEG IS NOT NULL)
  LEFT OUTER JOIN SP_BUSCAR_NFE_DEVOLUCAO(MOV.BDCODEMP, MOV.BDCHAVE, 'SAI') NFD ON(NFD.BDCHAVE IS NOT NULL) /*Busca a nota referenciada*/
  LEFT OUTER JOIN SP_GET_VALORES_DEV(0, MOV.BDCODEMP, MOV.BDREFLAN, P.BDCODPROD, NFD.BDCHAVE, 'ENT') DEV ON(DEV.BDCODENQ = 0)
  WHERE E.BDCODENQLEG IS NOT NULL
  AND DEV.BDCODENQ = 0
  AND NFD.BDCHAVE IS NOT NULL
  AND NOT EXISTS (
                  SELECT *
                  FROM VEF_EMP_TDRCSTSP_1100 A
                  JOIN TOL_VEF_EMP_DRCSTSP_1100 T ON(T.BDCODEMP = A.BDCODEMP AND T.BDREFERENCIA = A.BDREFERENCIA AND T.BDCODPROD = A.BDCODPROD AND
                                                     T.BDORDEM = A.BDORDEM AND T.BDCHAVEENT = NFD.BDCHAVE)
                  WHERE A.BDCODEMP = MOV.BDCODEMP
                  AND (A.BDREFERENCIA = (SELECT BDREF FROM DEC_REF(MOV.BDREFLAN)) OR A.BDREFERENCIA = MOV.BDREFLAN)
                  AND A.BDCODPROD =  P.BDCODPROD
                  AND A.BDCODMOV = 2
                 )
  ORDER BY MOV.BDDATAEMISSAO;

  /*
    Empresa NNNNNN - Produto XXXX não possui estoque inicial informado! Caso exista ele deve ser informado no lançamento de inventário no mês anterior à referência desta apuração preenchendo valores de ST
  */
  INSERT INTO VEF_INCON_TDRCSTSP(BDCODEMP, BDREFERENCIA, BDDESCRICAO)
  SELECT A.BDCODEMP, A.BDREFERENCIA, 'Empresa: '||A.BDCODEMP||' - Produto '||COALESCE(PRO.BDCODSAIDA, PRO.BDCODPROD)||' não possui estoque inicial informado! Caso exista ele deve ser informado no lançamento de inventário no mês anterior à referência desta apuração preenchendo valores de ST'
  FROM VEF_EMP_TDRCSTSP_1050 A
  JOIN TMP_EMPRESAS_SELECT EMP ON(EMP.BDCODEMP = A.BDCODEMP)
  JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = A.BDCODEMP AND PRO.BDCODPROD = A.BDCODPROD)
  WHERE A.BDREFERENCIA BETWEEN :PRREFINI AND :PRREFFIM
  AND NOT EXISTS (
                  SELECT P.BDCODEMP
                  FROM VEF_EMP_TDRCSTSP_1100 P
                  WHERE P.BDCODEMP = A.BDCODEMP
                  AND P.BDREFERENCIA = A.BDREFERENCIA
                  AND P.BDCODPROD = A.BDCODPROD
                  AND P.BDCODMOV = 1
                 );
END^

CREATE OR ALTER PROCEDURE SP_APURAR_CAT42SP (
    PRSESSAO INTEGER,
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRCODCONT INTEGER)
AS
DECLARE VARIABLE WCODEMP INTEGER;
DECLARE VARIABLE WDIF INTEGER;
DECLARE VARIABLE WREF INTEGER;
DECLARE VARIABLE WCODPLANODEFAULT INTEGER;
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREFINI);

  SELECT P.BDCODPLACAT42SP
  FROM VEF_BASE_TPLANOCAT42SP P
  WHERE BDPLANODEFAULT = 'TRUE'
  INTO :wCodPlanoDefault;

  IF (:wCodPlanoDefault IS NULL) THEN
    BEGIN
      DELETE FROM TMP_EMPRESAS_APU_CAT42 A
      WHERE NOT EXISTS (
                        SELECT R.BDCODPLACAT42SP
                        FROM VW_VEF_BASE_TEMPPARESTSP R
                        WHERE R.BDCODEMP = A.BDCODEMP
                        AND R.BDCODPLACAT42SP IS NOT NULL
                       );

      DELETE FROM TMP_EMPRESAS_SELECT A
      WHERE NOT EXISTS (
                        SELECT R.BDCODPLACAT42SP
                        FROM VW_VEF_BASE_TEMPPARESTSP R
                        WHERE R.BDCODEMP = A.BDCODEMP
                        AND R.BDCODPLACAT42SP IS NOT NULL
                       );
    END

  FOR SELECT BDCODEMP FROM TMP_EMPRESAS_SELECT INTO :wCodEmp DO
  BEGIN
      SELECT R.BDDIF
      FROM (
            SELECT R.BDDIF
            FROM (
                  SELECT SP.BDCODEMP, MAX(SP.BDREFERENCIA) BDLASTREF
                  FROM VEF_EMP_TDRCSTSPGER SP
                  WHERE SP.BDCODEMP = :wCodEmp
                  GROUP BY SP.BDCODEMP
                 ) D
            JOIN SP_REF_DIF(D.BDLASTREF, :PRREFINI) R ON(R.BDDIF IS NOT NULL)
           ) R
      INTO :wDif;

      wDif = :wDif - 1;

      WHILE (:wDif > 0) DO
        BEGIN
          INSERT INTO TMP_EMPRESAS_APU_CAT42(BDCODEMP, BDREF, BDAPURAR) VALUES(:wCodEmp, (SELECT BDREF FROM DEC_REF(:PRREFINI, :wDif)), 'TRUE');
          wDif = :wDif - 1;
        END
  END

  FOR SELECT BDCODEMP, BDREF
      FROM TMP_EMPRESAS_APU_CAT42
      WHERE BDAPURAR = 'TRUE'
      ORDER BY BDCODEMP, BDREF
      INTO :wCodEmp, :wRef
  DO
  BEGIN
    EXECUTE PROCEDURE SP_APURAR_CAT42SP_1100(:PRSESSAO, :wCodEmp, :wRef);
    EXECUTE PROCEDURE SP_APURAR_CAT42SP_1050(:PRSESSAO, :wCodEmp, :wRef);
  END

  EXECUTE PROCEDURE SP_GRAVAR_CAT42SP(:PRSESSAO, :PRCODCONT);
  EXECUTE PROCEDURE SP_VALIDAR_CAT42SP(:PRREFINI, :PRREFFIM);

  DELETE FROM TMP_TOL_VEF_EMP_DRCST_1100_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP WHERE BDSESSAO = :PRSESSAO;
  DELETE FROM TMP_VEF_EMP_TDRCSTSP_1050_TEMP WHERE BDSESSAO = :PRSESSAO;
END^

CREATE OR ALTER trigger tmp_vef_rcstsp_1100_temp_bu0 for tmp_vef_emp_tdrcstsp_1100_temp
active before update position 0
AS
declare variable wEtapa CHAR(1);
begin
  --select rdb$get_context('USER_SESSION', 'ETAPA_'||NEW.BDSESSAO) from rdb$database INTO :wEtapa;
  SELECT BDVALORSTR FROM TTHREAD WHERE BDPARAM = 'ETAPA_'||NEW.BDSESSAO INTO :wEtapa; -- Alt.: #201191 - Removida variavel de contexto...

  IF (NEW.BDCODMOV = 2) THEN
    BEGIN
      NEW.BDQTD_TOTAL = (COALESCE(NEW.BDQTDITEM, 0) + COALESCE((
                  SELECT T.BDQTD_TOTAL
                  FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
                  WHERE T.BDSESSAO = NEW.BDSESSAO
                  AND T.BDCODEMP = NEW.BDCODEMP
                  AND T.BDCODPROD = NEW.BDCODPROD
                  AND T.BDREFERENCIA = NEW.BDREFERENCIA
                  AND T.BDORDEM = NEW.BDORDEM - 1
                  ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDCODMOV, T.BDDATAMOV
                 ), 0));

      NEW.BDVL_TOT_SALDO = (COALESCE((
                  SELECT T.BDVL_TOT_SALDO
                  FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
                  WHERE T.BDSESSAO = NEW.BDSESSAO
                  AND T.BDCODEMP = NEW.BDCODEMP
                  AND T.BDCODPROD = NEW.BDCODPROD
                  AND T.BDREFERENCIA = NEW.BDREFERENCIA
                  AND T.BDORDEM = NEW.BDORDEM - 1
                  ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDCODMOV, T.BDDATAMOV
                 ), 0) + COALESCE(NEW.BDVL_ICMS_SUP_ENT, 0));

      NEW.BDVL_UNIT_SALDO = ((COALESCE((
                  SELECT T.BDVL_TOT_SALDO
                  FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
                  WHERE T.BDSESSAO = NEW.BDSESSAO
                  AND T.BDCODEMP = NEW.BDCODEMP
                  AND T.BDCODPROD = NEW.BDCODPROD
                  AND T.BDREFERENCIA = NEW.BDREFERENCIA
                  AND T.BDORDEM = NEW.BDORDEM - 1
                  ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDCODMOV, T.BDDATAMOV
                 ), 0) + COALESCE(NEW.BDVL_ICMS_SUP_ENT, 0))) / (COALESCE(NEW.BDQTDITEM, 0) + COALESCE((
                  SELECT T.BDQTD_TOTAL
                  FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
                  WHERE T.BDSESSAO = NEW.BDSESSAO
                  AND T.BDCODEMP = NEW.BDCODEMP
                  AND T.BDCODPROD = NEW.BDCODPROD
                  AND T.BDREFERENCIA = NEW.BDREFERENCIA
                  AND T.BDORDEM = NEW.BDORDEM - 1
                  ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDCODMOV, T.BDDATAMOV
                 ), 0));

      NEW.BDVL_UNIT_SALDO = ((COALESCE((
                                        SELECT T.BDVL_TOT_SALDO
                                        FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
                                        WHERE T.BDSESSAO = NEW.BDSESSAO
                                        AND T.BDCODEMP = NEW.BDCODEMP
                                        AND T.BDCODPROD = NEW.BDCODPROD
                                        AND T.BDREFERENCIA = NEW.BDREFERENCIA
                                        AND T.BDORDEM = NEW.BDORDEM - 1
                                        ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDCODMOV, T.BDDATAMOV
                                       ), 0) + COALESCE(NEW.BDVL_ICMS_SUP_ENT, 0))
                            ) / (COALESCE(NEW.BDQTDITEM, 0) + COALESCE((
                                      SELECT T.BDQTD_TOTAL
                                      FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
                                      WHERE T.BDSESSAO = NEW.BDSESSAO
                                      AND T.BDCODEMP = NEW.BDCODEMP
                                      AND T.BDCODPROD = NEW.BDCODPROD
                                      AND T.BDREFERENCIA = NEW.BDREFERENCIA
                                      AND T.BDORDEM = NEW.BDORDEM - 1
                                      ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDCODMOV, T.BDDATAMOV
                                     ), 0));
    END

  IF (NEW.BDCODMOV = 4) THEN
    BEGIN
      IF (:wEtapa = '1') THEN
        BEGIN
          NEW.BDVL_UNIT_SALDO = COALESCE((
                                          SELECT FIRST 1 T.BDVL_UNIT_SALDO
                                          FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
                                          WHERE T.BDSESSAO = NEW.BDSESSAO
                                          AND T.BDCODEMP = NEW.BDCODEMP
                                          AND T.BDCODPROD = NEW.BDCODPROD
                                          AND T.BDREFERENCIA = NEW.BDREFERENCIA
                                          AND T.BDCODMOV <> 3
                                          AND T.BDORDEM < NEW.BDORDEM
                                          ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDORDEM DESC
                                         ), 0);

--          NEW.BDVL_ICMS_MEDIO_SUP = COALESCE((
--                                           SELECT FIRST 1 T.BDVL_UNIT_SALDO
--                                           FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
--                                           WHERE T.BDSESSAO = NEW.BDSESSAO
--                                           AND T.BDCODEMP = NEW.BDCODEMP
--                                           AND T.BDCODPROD = NEW.BDCODPROD
--                                           AND T.BDREFERENCIA = NEW.BDREFERENCIA
--                                           AND T.BDCODMOV = 2
--                                           ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDDATAMOV DESC, T.BDORDEM DESC
--                                          ), 0);

        NEW.BDVL_ICMS_MEDIO_SUP = COALESCE((
                                           SELECT T.BDVL_UNIT_SALDO
                                           FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
                                           WHERE T.BDSESSAO = NEW.BDSESSAO
                                           AND T.BDCODEMP = NEW.BDCODEMP
                                           AND T.BDCODPROD = NEW.BDCODPROD
                                           AND T.BDREFERENCIA = NEW.BDREFERENCIA
                                           AND T.BDORDEM = NEW.BDORDEM - 1
                                           ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDCODMOV, T.BDDATAMOV
                                          ), 0);
        NEW.BDVL_TOT_MEDIO_SUP = COALESCE((
                                           SELECT FIRST 1 T.BDVL_UNIT_SALDO
                                           FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
                                           WHERE T.BDSESSAO = NEW.BDSESSAO
                                           AND T.BDCODEMP = NEW.BDCODEMP
                                           AND T.BDCODPROD = NEW.BDCODPROD
                                           AND T.BDREFERENCIA = NEW.BDREFERENCIA
                                           AND T.BDCODMOV IN(2/*Entrada*/,1/*Estoque Inicial*/)/* Alt.: #167609 - Caso não tenha valor nas entradas, tenta obter no estoque inicial...*/
                                           ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDCODMOV DESC, T.BDDATAMOV DESC, T.BDORDEM DESC
                                          ), 0) * NEW.BDQTDITEM;
        NEW.BDVL_CONFRONTO = (SELECT BDVLRCONFRONTO FROM SP_GET_VALOR_CONFRONTO_SAIDA(NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDREFERENCIA, NEW.BDCODPROD, NEW.BDORDEM, NEW.BDCODENQ, NEW.BDDATAMOV, NEW.BDQTDITEM, NEW.BDTIPOMOV));
        NEW.BDVL_RESSARCIMENTO = IIF(COALESCE((
                                           SELECT FIRST 1 T.BDVL_UNIT_SALDO
                                           FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
                                           WHERE T.BDSESSAO = NEW.BDSESSAO
                                           AND T.BDCODEMP = NEW.BDCODEMP
                                           AND T.BDCODPROD = NEW.BDCODPROD
                                           AND T.BDREFERENCIA = NEW.BDREFERENCIA
                                           AND T.BDCODMOV IN(2/*Entrada*/,1/*Estoque Inicial*/)/* Alt.: #167609 - Caso não tenha valor nas entradas, tenta obter no estoque inicial...*/
                                           ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDCODMOV DESC, T.BDDATAMOV DESC, T.BDORDEM DESC
                                          ), 0) * NEW.BDQTDITEM - (SELECT BDVLRCONFRONTO FROM SP_GET_VALOR_CONFRONTO_SAIDA(NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDREFERENCIA, NEW.BDCODPROD, NEW.BDORDEM, NEW.BDCODENQ, NEW.BDDATAMOV, NEW.BDQTDITEM, NEW.BDTIPOMOV)) > 0, COALESCE((
                                           SELECT FIRST 1 T.BDVL_UNIT_SALDO
                                           FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
                                           WHERE T.BDSESSAO = NEW.BDSESSAO
                                           AND T.BDCODEMP = NEW.BDCODEMP
                                           AND T.BDCODPROD = NEW.BDCODPROD
                                           AND T.BDREFERENCIA = NEW.BDREFERENCIA
                                           AND T.BDCODMOV IN(2/*Entrada*/,1/*Estoque Inicial*/)/* Alt.: #167609 - Caso não tenha valor nas entradas, tenta obter no estoque inicial...*/
                                           ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDCODMOV DESC, T.BDDATAMOV DESC, T.BDORDEM DESC
                                          ), 0) * NEW.BDQTDITEM - (SELECT BDVLRCONFRONTO FROM SP_GET_VALOR_CONFRONTO_SAIDA(NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDREFERENCIA, NEW.BDCODPROD, NEW.BDORDEM, NEW.BDCODENQ, NEW.BDDATAMOV, NEW.BDQTDITEM, NEW.BDTIPOMOV)), 0);
    
        NEW.BDVL_COMPLEMENTO = IIF(NEW.BDCODENQ = 1, IIF((SELECT BDVLRCONFRONTO FROM SP_GET_VALOR_CONFRONTO_SAIDA(NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDREFERENCIA, NEW.BDCODPROD, NEW.BDORDEM, NEW.BDCODENQ, NEW.BDDATAMOV, NEW.BDQTDITEM, NEW.BDTIPOMOV)) -
                                   (COALESCE((
                                           SELECT FIRST 1 T.BDVL_UNIT_SALDO
                                           FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
                                           WHERE T.BDSESSAO = NEW.BDSESSAO
                                           AND T.BDCODEMP = NEW.BDCODEMP
                                           AND T.BDCODPROD = NEW.BDCODPROD
                                           AND T.BDREFERENCIA = NEW.BDREFERENCIA
                                           AND T.BDCODMOV IN(2/*Entrada*/,1/*Estoque Inicial*/)/* Alt.: #167609 - Caso não tenha valor nas entradas, tenta obter no estoque inicial...*/
                                           ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDCODMOV DESC, T.BDDATAMOV DESC, T.BDORDEM DESC
                                          ), 0) * NEW.BDQTDITEM) > 0,
                                   ((SELECT BDVLRCONFRONTO FROM SP_GET_VALOR_CONFRONTO_SAIDA(NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDREFERENCIA, NEW.BDCODPROD, NEW.BDORDEM, NEW.BDCODENQ, NEW.BDDATAMOV, NEW.BDQTDITEM, NEW.BDTIPOMOV)) -
                                    (COALESCE((
                                           SELECT FIRST 1 T.BDVL_UNIT_SALDO
                                           FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
                                           WHERE T.BDSESSAO = NEW.BDSESSAO
                                           AND T.BDCODEMP = NEW.BDCODEMP
                                           AND T.BDCODPROD = NEW.BDCODPROD
                                           AND T.BDREFERENCIA = NEW.BDREFERENCIA
                                           AND T.BDCODMOV IN(2/*Entrada*/,1/*Estoque Inicial*/)/* Alt.: #167609 - Caso não tenha valor nas entradas, tenta obter no estoque inicial...*/
                                           ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDCODMOV DESC, T.BDDATAMOV DESC, T.BDORDEM DESC
                                          ), 0) * NEW.BDQTDITEM)), 0), 0);
        END
      ELSE
        BEGIN
          NEW.BDQTD_TOTAL = (
                             SELECT A.BDQTD_TOTAL
                             FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP A
                             WHERE A.BDSESSAO = NEW.BDSESSAO
                             AND A.BDCODEMP = NEW.BDCODEMP
                             AND A.BDREFERENCIA = NEW.BDREFERENCIA
                             AND A.BDCODPROD = NEW.BDCODPROD
                             AND A.BDORDEM = NEW.BDORDEM - 1
                            ) - NEW.BDQTDITEM;
          NEW.BDVL_TOT_SALDO = COALESCE((
                                         SELECT FIRST 1 T.BDVL_UNIT_SALDO
                                         FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
                                         WHERE T.BDSESSAO = NEW.BDSESSAO
                                         AND T.BDCODEMP = NEW.BDCODEMP
                                         AND T.BDCODPROD = NEW.BDCODPROD
                                         AND T.BDREFERENCIA = NEW.BDREFERENCIA
                                         AND T.BDCODMOV <> 3
                                         AND T.BDORDEM < NEW.BDORDEM
                                         ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDDATAMOV DESC, T.BDORDEM DESC
                                        ), 0) *
                               ((SELECT A.BDQTD_TOTAL
                                 FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP A
                                 WHERE A.BDSESSAO = NEW.BDSESSAO
                                 AND A.BDCODEMP = NEW.BDCODEMP
                                 AND A.BDREFERENCIA = NEW.BDREFERENCIA
                                 AND A.BDCODPROD = NEW.BDCODPROD
                                 AND A.BDORDEM = NEW.BDORDEM - 1) - NEW.BDQTDITEM);
        END
    END

    IF (NEW.BDCODMOV = 3) THEN
      BEGIN
        IF (:wEtapa = '1') THEN
          BEGIN
            NEW.BDVL_UNIT_SALDO = (
                                   SELECT T.BDVL_UNIT_SALDO
                                   FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
                                   WHERE T.BDSESSAO = NEW.BDSESSAO
                                   AND T.BDCODEMP = NEW.BDCODEMP
                                   AND T.BDCODPROD = NEW.BDCODPROD
                                   AND T.BDREFERENCIA = NEW.BDREFERENCIA
                                   AND T.BDORDEM = NEW.BDORDEM - 1
                                   ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDCODMOV, T.BDDATAMOV
                                  );
          END
        ELSE
          BEGIN
            NEW.BDVL_ICMS_MEDIO_SUP = (SELECT BDVL_ICMS_MEDIO_SUP FROM SP_GET_VALORES_DEV(NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDREFERENCIA, NEW.BDCODPROD, NEW.BDCHAVELAN, 'SAI'));
            NEW.BDCODENQ = (SELECT IIF(BDCODENQ = 0, NULL, BDCODENQ) FROM SP_GET_VALORES_DEV(NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDREFERENCIA, NEW.BDCODPROD, NEW.BDCHAVELAN, 'SAI'));
            NEW.BDVL_TOT_MEDIO_SUP = (SELECT BDVL_ICMS_MEDIO_SUP FROM SP_GET_VALORES_DEV(NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDREFERENCIA, NEW.BDCODPROD, NEW.BDCHAVELAN, 'SAI')) * NEW.BDQTDITEM;
            NEW.BDVL_CONFRONTO = (SELECT (IIF(BDQTDITEM > 0, BDVL_CONFRONTO / BDQTDITEM, 0)) * NEW.BDQTDITEM FROM SP_GET_VALORES_DEV(NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDREFERENCIA, NEW.BDCODPROD, NEW.BDCHAVELAN, 'SAI'));
            NEW.BDVL_RESSARCIMENTO = IIF((((SELECT BDVL_ICMS_MEDIO_SUP FROM SP_GET_VALORES_DEV(NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDREFERENCIA, NEW.BDCODPROD, NEW.BDCHAVELAN, 'SAI')) * NEW.BDQTDITEM) - (SELECT (IIF(BDQTDITEM > 0, BDVL_CONFRONTO / BDQTDITEM, 0)) * NEW.BDQTDITEM FROM SP_GET_VALORES_DEV(NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDREFERENCIA, NEW.BDCODPROD, NEW.BDCHAVELAN, 'SAI'))) > 0, (((SELECT BDVL_ICMS_MEDIO_SUP FROM SP_GET_VALORES_DEV(NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDREFERENCIA, NEW.BDCODPROD, NEW.BDCHAVELAN, 'SAI')) * NEW.BDQTDITEM) - (SELECT (BDVL_CONFRONTO / BDQTDITEM) * NEW.BDQTDITEM FROM SP_GET_VALORES_DEV(NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDREFERENCIA, NEW.BDCODPROD, NEW.BDCHAVELAN, 'SAI'))), 0);
            NEW.BDQTD_TOTAL = (
                               SELECT T.BDQTD_TOTAL
                               FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
                               WHERE T.BDSESSAO = NEW.BDSESSAO
                               AND T.BDCODEMP = NEW.BDCODEMP
                               AND T.BDCODPROD = NEW.BDCODPROD
                               AND T.BDREFERENCIA = NEW.BDREFERENCIA
                               AND T.BDORDEM = NEW.BDORDEM - 1
                               ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDCODMOV, T.BDDATAMOV
                              ) + NEW.BDQTDITEM;

            NEW.BDVL_COMPLEMENTO = (SELECT IIF(BDCODENQ = 1 AND (NEW.BDVL_CONFRONTO - NEW.BDVL_TOT_MEDIO_SUP) > 0, NEW.BDVL_CONFRONTO - NEW.BDVL_TOT_MEDIO_SUP, 0) FROM SP_GET_VALORES_DEV(NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDREFERENCIA, NEW.BDCODPROD, NEW.BDCHAVELAN, 'SAI'));
            NEW.BDVL_TOT_SALDO = NEW.BDQTD_TOTAL * NEW.BDVL_UNIT_SALDO;
          END
      END

  IF (NEW.BDCODMOV = 5) THEN
    BEGIN
      NEW.BDVL_ICMS_SUP_ENT = (SELECT (IIF(BDQTDITEM > 0, BDVL_ICMS_SUP_ENT / BDQTDITEM, 0)) * NEW.BDQTDITEM FROM SP_GET_VALORES_DEV(NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDREFERENCIA, NEW.BDCODPROD, NEW.BDCHAVELAN, 'ENT'));
      NEW.BDQTD_TOTAL = (
        SELECT T.BDQTD_TOTAL
        FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
        WHERE T.BDSESSAO = NEW.BDSESSAO
        AND T.BDCODEMP = NEW.BDCODEMP
        AND T.BDCODPROD = NEW.BDCODPROD
        AND T.BDREFERENCIA = NEW.BDREFERENCIA
        AND T.BDORDEM = NEW.BDORDEM - 1
        ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDCODMOV, T.BDDATAMOV
       ) - NEW.BDQTDITEM;

       NEW.BDVL_TOT_SALDO = CAST(COALESCE((
                                           SELECT T.BDVL_TOT_SALDO
                                           FROM TMP_VEF_EMP_TDRCSTSP_1100_TEMP T
                                           WHERE T.BDSESSAO = NEW.BDSESSAO
                                           AND T.BDCODEMP = NEW.BDCODEMP
                                           AND T.BDCODPROD = NEW.BDCODPROD
                                           AND T.BDREFERENCIA = NEW.BDREFERENCIA
                                           AND T.BDORDEM = NEW.BDORDEM - 1
                                           ORDER BY T.BDREFERENCIA, T.BDCODPROD, T.BDCODMOV, T.BDDATAMOV
                                          ), 0) -
                                (SELECT (IIF(COALESCE(BDQTDITEM, 0) > 0, BDVL_ICMS_SUP_ENT / BDQTDITEM, 0)) * COALESCE(CAST(NEW.BDQTDITEM AS DM_NUMERIC_15_2), 0) FROM SP_GET_VALORES_DEV(NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDREFERENCIA, NEW.BDCODPROD, NEW.BDCHAVELAN, 'ENT')) AS DM_NUMERIC_15_2);

      NEW.BDVL_UNIT_SALDO = IIF(COALESCE(NEW.BDQTD_TOTAL, 0) > 0, NEW.BDVL_TOT_SALDO / NEW.BDQTD_TOTAL, 0);
    END
end^

CREATE OR ALTER trigger vef_incon_tdrcstsp_bi0 for vef_incon_tdrcstsp
active before insert position 0
AS
declare variable wOrdem INTEGER;
begin
  SELECT MAX(BDORDEM)
  FROM VEF_INCON_TDRCSTSP
  WHERE BDCODEMP = NEW.BDCODEMP
  AND BDREFERENCIA = NEW.BDREFERENCIA
  INTO :wOrdem;

  NEW.BDORDEM = COALESCE(:wOrdem + 1, 1);
end^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCSTSP_0150 (
    PRCODEMP INTEGER,
    PRREF INTEGER,
    PRREFINI INTEGER,
    PRFINALIDADE INTEGER,
    PRARQUIVO VARCHAR(260))
AS
BEGIN
      /*****************************************************************************
       *                                   0150                                    *
      *****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
      SELECT :PRARQUIVO,
             '0000.'||:PRCODEMP||'.0150.'||TER.BDCODTER AS bdCHAVEREG,
             '0150' AS BDREG,
             :PRCODEMP,
             (
              '0150'||
              '|'||(SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(TE.BDTIPOEXPCODPART, TER.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))||
              '|'||TER.BDNOMETER||
              '|'||COALESCE(P.BDCODSPED, COALESCE(PE.BDCODSPED, ''))||
              '|'||IIF(P.BDCODSPED = 1058, IIF(CHAR_LENGTH(TER.BDCGCTER) = 14, '', (SELECT RESULT FROM SP_TIRATODOSSINAIS(TER.BDCGCTER))), '')||
              '|'||IIF(P.BDCODSPED = 1058, IIF(CHAR_LENGTH(TER.BDCGCTER) = 14, (SELECT RESULT FROM SP_TIRATODOSSINAIS(TER.BDCGCTER)), ''), '')||
              '|'||IIF(P.BDCODSPED = 1058, COALESCE((SELECT RESULT FROM SP_TIRATODOSSINAIS(TER.BDIETER)), 'ISENTO'), 'ISENTO')||
              '|'||IIF(P.BDCODSPED = 1058, IIF(COALESCE(C.BDCODIBGE, 0) = 0, '', C.BDCODIBGE), '')
             )
      FROM (
            SELECT TOL.BDCODEMP, COALESCE(E.BDCODTER, S.BDCODTER, I.BDCODTER, Z.BDCODTER) BDCODTER
            FROM TOL_VEF_EMP_DRCSTSP_1100 TOL
            LEFT OUTER JOIN VEF_EMP_TMOVENT E ON(E.BDCODEMP = TOL.BDCODEMP AND E.BDCHAVE = TOL.BDCHAVEENT)
            LEFT OUTER JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = TOL.BDCODEMP AND S.BDCHAVE = TOL.BDCHAVESAI)
            LEFT OUTER JOIN VEF_EMP_TMOVINV I ON(I.BDCODEMP = TOL.BDCODEMP AND I.BDCHAVE = TOL.BDCHAVEINV)
            LEFT OUTER JOIN VEF_EMP_TDOCECF Z ON(Z.BDCODEMP = TOL.BDCODEMP AND Z.BDCHAVE = TOL.BDCHAVEREDZ AND Z.BDORDEMDOCECF = TOL.BDORDEMREDZ)
            WHERE TOL.BDCODEMP = :PRCODEMP
            AND TOL.BDREFERENCIA = :PRREF
            AND EXISTS (
                        SELECT FIRST 1 E.BDORDEM
                        FROM VEF_EMP_TDRCSTSP_1100 E
                        WHERE E.BDCODEMP = TOL.BDCODEMP
                        AND E.BDREFERENCIA = TOL.BDREFERENCIA
                        AND E.BDCODPROD = TOL.BDCODPROD
                        AND E.BDCODMOV NOT IN(1)
                       )
            GROUP BY TOL.BDCODEMP, BDCODTER
           ) A
      JOIN VW_TTERCEIRO TER ON(TER.BDCODTER = A.BDCODTER)
      JOIN TCIDADE C ON(C.BDCODCID = TER.BDCODCID)
      JOIN TPAIS P ON(P.BDCODPAIS = C.BDCODPAIS)
      JOIN TPAIS PE ON(PE.BDCODPAIS = TER.BDCODPAIS)
      LEFT OUTER JOIN VW_INT_SPEDICMS_REF TE ON(TE.BDCODEMP = A.BDCODEMP)
      LEFT OUTER JOIN (
                       SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                       FROM (
                             SELECT t.bdcodemp, t.bdcodter,
                                    COALESCE(
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= :PRREFINI) ORDER BY e.bdreferencia DESC),
                                             (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                            ) BDCODIGO
                             FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                            ) tt
                       LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                      ) TerEmp ON (TerEmp.bdcodter = TER.bdcodter);

      IF (ROW_COUNT > 0) THEN
        BEGIN
          INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
          SELECT :PRARQUIVO,
          '0000.'||:PRCODEMP||'.0150.'||TREF.BDCODEMP AS bdCHAVEREG,
          '0150' AS BDREG,
          :PRCODEMP,
          (
           '0150'||
           '|'||tref.BDCODEMP||
           '|'||tref.BDNOMEMP||
           '|'||IIF(P.BDCODSPED = 1058, P.BDCODSPED, '')||
           '|'||IIF(P.BDCODSPED = 1058, IIF(CHAR_LENGTH(tref.BDCNPJEMP) = 14, '', (SELECT RESULT FROM SP_TIRATODOSSINAIS(tref.BDCNPJEMP))), '')||
           '|'||IIF(P.BDCODSPED = 1058, IIF(CHAR_LENGTH(tref.BDCNPJEMP) = 14, (SELECT RESULT FROM SP_TIRATODOSSINAIS(tref.BDCNPJEMP)), ''), '')||
           '|'||IIF(P.BDCODSPED = 1058, (SELECT RESULT FROM SP_TIRATODOSSINAIS(tref.BDIEEMP)), '')||
           '|'||IIF(COALESCE(C.BDCODIBGE, 0) = 0, '', C.BDCODIBGE)
          )
          FROM SP_CONSULTAEMPRESAS_SIS(:PRREF, :PRCODEMP, 0) tref
          LEFT OUTER JOIN VW_EMP_REF_TOTAL trefsis ON (trefsis.bdCODEMP = tref.bdCODEMP)
          JOIN TCIDADE C ON(C.BDCODCID = tref.BDCODCID)
          JOIN TPAIS P ON(P.BDCODPAIS = C.BDCODPAIS);
        END
END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCSTSP_1200 (
    PRARQUIVO VARCHAR(260),
    PRCODEMP INTEGER,
    PRREFATU INTEGER,
    PRREFINI INTEGER)
AS
BEGIN
      /*****************************************************************************
       *                                   1200                                    *
      *****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
      SELECT :PRARQUIVO,
               '0000.'||:PRCODEMP||'.1050.'||A.BDCODPROD||'.1200.'||A.BDTIPOMOV||'.'||A.BDCHAVE||'_'||A.BDORDEMITEM||'_'||A.BDORDEMPRO AS bdCHAVEREG,
               '1200' AS BDREG,
               :PRCODEMP,
               (
                '1200'||
                '|'||(SELECT BDRETORNO FROM SP_GET_CODPARTICIPANTEEXP(TE.BDTIPOEXPCODPART, TER.BDCODTER, TER.BDCGCTER, TER.BDIETER, TerEmp.BDCODIGOARQUIVO))||
                '|'||COALESCE(A.BDMODELO, '')||
                '|'||IIF(COALESCE(A.BDSERIEMAQ, '') = '', '', RPAD(A.BDSERIEMAQ, 21, ' '))||
                '|'||A.BDSERIE||
                '|'||LPAD(COALESCE(A.BDNUMDOC, ''), 9, '0')||
                '|'||A.BDORDEMPRO||
                '|'||A.BDMOV||
                '|'||(SELECT BDDATA FROM SP_PARSE_DATE(A.BDDATA, 'DDMMYYYY'))||
                '|'||COALESCE(SUBSTRING(A.BDCODNAT FROM 1 FOR 4), '')||
                '|'||IIF(COALESCE(A.BDCODSAIDA, '') = '', A.BDCODPROD, A.BDCODSAIDA)||
                '|'||REPLACE(COALESCE(CAST(A.BDQTDITEM AS NUMERIC(15, 3)), 0.000), '.', ',')||
                '|'||REPLACE(COALESCE(CAST(A.BDVL_ICMS_SUP_ENT AS NUMERIC(15, 2)), 0.00), '.', ',')||
                '|'||REPLACE(COALESCE(CAST(A.BDVL_CONFRONTO AS NUMERIC(15, 2)), 0.00), '.', ',')||
                '|'||COALESCE(A.BDCODEXP, '')
               )
        FROM (
              SELECT TOL.*,
                     COALESCE(E.BDCHAVE, S.BDCHAVE, MOV.BDCHAVE) AS BDCHAVE,
                     COALESCE(EI.BDORDEM, SI.BDORDEM, I.BDORDEMDOCECF) AS BDORDEMITEM,
                     COALESCE(EP.BDORDEMPRO, SP.BDORDEMPRO, P.BDORDEMITEM) AS BDORDEMPRO,
                     COALESCE(E.BDCODTER, S.BDCODTER, I.BDCODTER) AS BDCODTER,
                     COALESCE(EM.BDMODELOSTR, SM.BDMODELOSTR, MOD_Z.BDDOCFIS) AS BDMODELO,
                     MAQ.BDSERIEMAQ,
                     COALESCE(E.BDSERIE, S.BDSERIE, '') BDSERIE,
                     COALESCE(E.BDNUMDOCINI, S.BDNUMDOCINI, I.BDNUMDOCCOO) BDNUMDOC,
                     IIF(E.BDCHAVE IS NOT NULL, 0, 1) BDMOV,
                     COALESCE(E.BDDATAEMISSAO, S.BDDATAEMISSAO, MOV.BDDATAREDZ) BDDATA,
                     COALESCE(EI.BDCODNAT, SI.BDCODNAT, P.BDCODNAT, '') BDCODNAT,
                     PRO.BDCODSAIDA,
                     COALESCE(A.BDQTDITEM, 0) BDQTDITEM,
                     COALESCE(A.BDVL_ICMS_SUP_ENT, 0) AS BDVL_ICMS_SUP_ENT,
                     COALESCE(A.BDVL_CONFRONTO, 0) BDVL_CONFRONTO,
                     A.BDCODENQ,
                     IIF(E.BDCHAVE IS NOT NULL, 'E', IIF(S.BDCHAVE IS NOT NULL, 'S', 'R')) BDTIPOMOV,
                     ENQ.BDCODEXP
              FROM TOL_VEF_EMP_DRCSTSP_1100 TOL
              JOIN VW_VEF_BASE_TEMPPARESTSP EMP ON(EMP.BDCODEMP = TOL.BDCODEMP)
              JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = TOL.BDCODEMP AND PRO.BDCODPROD = TOL.BDCODPROD)
              JOIN VEF_EMP_TDRCSTSP_1100 A ON(A.BDCODEMP = TOL.BDCODEMP AND A.BDREFERENCIA = TOL.BDREFERENCIA AND A.BDCODPROD = TOL.BDCODPROD AND A.BDORDEM = TOL.BDORDEM)
              LEFT OUTER JOIN VEF_EMP_TMOVENT E ON(E.BDCODEMP = TOL.BDCODEMP AND E.BDCHAVE = TOL.BDCHAVEENT)
              LEFT OUTER JOIN VEF_EMP_TMOVENTITENS EI ON(EI.BDCODEMP = TOL.BDCODEMP AND EI.BDCHAVE = TOL.BDCHAVEENT AND EI.BDORDEM = TOL.BDORDEMENT)
              LEFT OUTER JOIN VEF_EMP_TMOVPROENT EP ON(EP.BDCODEMP = TOL.BDCODEMP AND EP.BDCHAVE = TOL.BDCHAVEENT AND EP.BDORDEM = TOL.BDORDEMENT AND EP.BDORDEMPRO = TOL.BDORDEMPROENT)
              LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN EM ON(EM.BDMODELO = E.BDMODELO)
              LEFT OUTER JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = TOL.BDCODEMP AND S.BDCHAVE = TOL.BDCHAVESAI)
              LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS SI ON(SI.BDCODEMP = TOL.BDCODEMP AND SI.BDCHAVE = TOL.BDCHAVESAI AND SI.BDORDEM = TOL.BDORDEMSAI)
              LEFT OUTER JOIN VEF_EMP_TMOVPROSAI SP ON(SP.BDCODEMP = TOL.BDCODEMP AND SP.BDCHAVE = TOL.BDCHAVESAI AND SP.BDORDEM = TOL.BDORDEMSAI AND SP.BDORDEMPRO = TOL.BDORDEMPROSAI)
              LEFT OUTER JOIN VEF_BASE_TTABMODELOLAN SM ON(SM.BDMODELO = S.BDMODELO)
              LEFT OUTER JOIN VEF_EMP_TREDZ MOV ON(MOV.BDCODEMP = TOL.BDCODEMP AND MOV.BDCHAVE = TOL.BDCHAVEREDZ)
              LEFT OUTER JOIN VEF_EMP_TDOCECF I ON(I.BDCODEMP = TOL.BDCODEMP AND I.BDCHAVE = TOL.BDCHAVEREDZ AND I.BDORDEMDOCECF = TOL.BDORDEMREDZ)
              LEFT OUTER JOIN VEF_EMP_TITEMDOCECF P ON(P.BDCODEMP = TOL.BDCODEMP AND P.BDCHAVE = TOL.BDCHAVEREDZ AND P.BDORDEMDOCECF = TOL.BDORDEMREDZ AND P.BDORDEMITEM = TOL.BDORDEMPROREDZ)
              LEFT OUTER JOIN VEF_BASE_TCADMAQMRC MAQ ON(MAQ.BDCODEMP = MOV.BDCODEMP AND MAQ.BDORDEMMAQ = MOV.BDORDEMMAQ)
              LEFT OUTER JOIN VEF_BASE_TTABDOCFIS MOD_Z ON(MOD_Z.BDCODDOCFIS = I.BDCODDOCFIS)
              LEFT OUTER JOIN VEF_BASE_TTABENQLEGALCAT42 ENQ ON(ENQ.BDCODENQ = A.BDCODENQ)
              WHERE TOL.BDCODEMP = :PRCODEMP
              AND TOL.BDREFERENCIA = :PRREFATU
              AND ((COALESCE(E.BDCHAVE, S.BDCHAVE) IS NOT NULL) OR (MOV.BDCHAVE IS NOT NULL AND EMP.BDCONSOLIDAR1200 = 'FALSE'))
              AND ((COALESCE(E.BDMODELO, S.BDMODELO) IN(1, 2, 200) OR I.BDCODDOCFIS IN(1, 3, 4)))
              AND EXISTS (
                          SELECT FIRST 1 E.BDORDEM
                          FROM VEF_EMP_TDRCSTSP_1100 E
                          WHERE E.BDCODEMP = A.BDCODEMP
                          AND E.BDREFERENCIA = A.BDREFERENCIA
                          AND E.BDCODPROD = A.BDCODPROD
                          AND E.BDCODMOV NOT IN(1)
                         )
             ) A
        LEFT OUTER JOIN VW_TTERCEIRO TER ON(TER.BDCODTER = A.BDCODTER)
        LEFT OUTER JOIN VW_INT_SPEDICMS_REF TE ON(TE.BDCODEMP = A.BDCODEMP)
        LEFT OUTER JOIN (
                         SELECT tt.bdcodemp, tt.bdcodter, tt.bdcodigo, ee.bdreferencia, ee.bdcodigoarquivo
                         FROM (
                               SELECT t.bdcodemp, t.bdcodter,
                                      COALESCE(
                                               (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) AND (e.bdreferencia <= :PRREFINI) ORDER BY e.bdreferencia DESC),
                                               (SELECT FIRST 1 e.bdcodigo FROM TTERCEIRO_EMP e WHERE (e.bdcodemp = t.bdcodemp) AND (e.bdcodter = t.bdcodter) ORDER BY e.bdreferencia)
                                              ) BDCODIGO
                               FROM (SELECT te.bdcodemp, te.bdcodter FROM TTERCEIRO_EMP te WHERE (te.bdcodemp = :PRCODEMP) GROUP BY te.bdcodemp, te.bdcodter) t
                              ) tt
                         LEFT OUTER JOIN TTERCEIRO_EMP ee ON ee.bdcodemp = tt.bdcodemp AND ee.bdcodter = tt.bdcodter AND ee.bdcodigo = tt.bdcodigo
                        ) TerEmp ON (TerEmp.bdcodter = A.bdcodter);

      INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
      SELECT :PRARQUIVO,
               '0000.'||:PRCODEMP||'.1050.'||A.BDCODPROD||'.1200.R.999' AS bdCHAVEREG,
               '1200' AS BDREG,
               :PRCODEMP,
               (
                '1200'||
                '|'||COALESCE(A.BDCODTER, '')||
                '|'||COALESCE(A.BDMODELO, '')||
                '|'||IIF(COALESCE(A.BDSERIEMAQ, '') = '', '', RPAD(A.BDSERIEMAQ, 21, ' '))||
                '|'||A.BDSERIE||
                '|'||LPAD(COALESCE(A.BDNUMDOC, ''), 9, '0')||
                '|'||A.BDORDEM||
                '|'||A.BDMOV||
                '|'||(SELECT BDDATA FROM SP_PARSE_DATE(A.BDDATA, 'DDMMYYYY'))||
                '|'||COALESCE(SUBSTRING(A.BDCODNAT FROM 1 FOR 4), '')||
                '|'||IIF(COALESCE(A.BDCODSAIDA, '') = '', A.BDCODPROD, A.BDCODSAIDA)||
                '|'||REPLACE(COALESCE(CAST(A.BDQTDITEM AS NUMERIC(15, 3)), 0.000), '.', ',')||
                '|'||REPLACE(COALESCE(CAST(A.BDVL_ICMS_SUP_ENT AS NUMERIC(15, 2)), 0.00), '.', ',')||
                '|'||REPLACE(COALESCE(CAST(A.BDVL_CONFRONTO AS NUMERIC(15, 2)), 0.00), '.', ',')||
                '|'||COALESCE(A.BDCODEXP, '')
               )
        FROM (
              SELECT MOV.BDORDEMMAQ,
                     PRO.BDCODPROD,
                     PRO.BDCODSAIDA,
                     MOV.BDDATAREDZ BDDATA,
                     '' BDCODTER,
                     '' BDSERIE,
                     COALESCE((
                               SELECT FIRST 1 MOD_Z.BDDOCFIS
                               FROM TOL_VEF_EMP_DRCSTSP_1100 TOL
                               JOIN VEF_EMP_TREDZ M ON(M.BDCODEMP = TOL.BDCODEMP AND M.BDCHAVE = TOL.BDCHAVEREDZ)
                               JOIN VEF_EMP_TDRCSTSP_1100 AP ON(AP.BDCODEMP = TOL.BDCODEMP AND AP.BDREFERENCIA = TOL.BDREFERENCIA AND AP.BDCODPROD = TOL.BDCODPROD AND AP.BDORDEM = TOL.BDORDEM)
                               JOIN VEF_EMP_TDOCECF I ON(I.BDCODEMP = TOL.BDCODEMP AND I.BDCHAVE = TOL.BDCHAVEREDZ AND I.BDORDEMDOCECF = TOL.BDORDEMREDZ)
                               JOIN VEF_BASE_TTABDOCFIS MOD_Z ON(MOD_Z.BDCODDOCFIS = I.BDCODDOCFIS)
                               JOIN VEF_EMP_TITEMDOCECF PM ON(PM.BDCODEMP = TOL.BDCODEMP AND PM.BDCHAVE = TOL.BDCHAVEREDZ AND PM.BDORDEMDOCECF = TOL.BDORDEMREDZ AND PM.BDORDEMITEM = TOL.BDORDEMPROREDZ)
                               WHERE TOL.BDCODEMP = :PRCODEMP
                               AND TOL.BDREFERENCIA = :PRREFATU
                               AND TOL.BDCHAVEREDZ IS NOT NULL
                               AND M.BDORDEMMAQ = MOV.BDORDEMMAQ
                               AND M.BDDATAREDZ = MOV.BDDATAREDZ
                               AND PM.BDCODPROD = PRO.BDCODPROD
                               AND AP.BDCODENQ = A.BDCODENQ
                              ), '') BDMODELO,
                     0 BDNUMDOC,
                     999 BDORDEM,
                     1 BDMOV,
                     COALESCE((
                               SELECT FIRST 1 PM.BDCODNAT
                               FROM TOL_VEF_EMP_DRCSTSP_1100 TOL
                               JOIN VEF_EMP_TREDZ M ON(M.BDCODEMP = TOL.BDCODEMP AND M.BDCHAVE = TOL.BDCHAVEREDZ)
                               JOIN VEF_EMP_TDRCSTSP_1100 AP ON(AP.BDCODEMP = TOL.BDCODEMP AND AP.BDREFERENCIA = TOL.BDREFERENCIA AND AP.BDCODPROD = TOL.BDCODPROD AND AP.BDORDEM = TOL.BDORDEM)
                               JOIN VEF_EMP_TDOCECF I ON(I.BDCODEMP = TOL.BDCODEMP AND I.BDCHAVE = TOL.BDCHAVEREDZ AND I.BDORDEMDOCECF = TOL.BDORDEMREDZ)
                               JOIN VEF_EMP_TITEMDOCECF PM ON(PM.BDCODEMP = TOL.BDCODEMP AND PM.BDCHAVE = TOL.BDCHAVEREDZ AND PM.BDORDEMDOCECF = TOL.BDORDEMREDZ AND PM.BDORDEMITEM = TOL.BDORDEMPROREDZ)
                               WHERE TOL.BDCODEMP = :PRCODEMP
                               AND TOL.BDREFERENCIA = :PRREFATU
                               AND TOL.BDCHAVEREDZ IS NOT NULL
                               AND M.BDORDEMMAQ = MOV.BDORDEMMAQ
                               AND M.BDDATAREDZ = MOV.BDDATAREDZ
                               AND PM.BDCODPROD = PRO.BDCODPROD
                               AND AP.BDCODENQ = A.BDCODENQ
                              ), '') BDCODNAT,
                     SUM(COALESCE(A.BDQTDITEM, 0)) BDQTDITEM,
                     SUM(COALESCE(A.BDVL_CONFRONTO, 0)) BDVL_CONFRONTO,
                     MAQ.BDSERIEMAQ,
                     0 BDVL_ICMS_SUP_ENT,
                     E.BDCODEXP
              FROM TOL_VEF_EMP_DRCSTSP_1100 TOL
              JOIN VW_VEF_BASE_TEMPPARESTSP EMP ON(EMP.BDCODEMP = TOL.BDCODEMP)
              JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = TOL.BDCODEMP AND PRO.BDCODPROD = TOL.BDCODPROD)
              JOIN VEF_EMP_TDRCSTSP_1100 A ON(A.BDCODEMP = TOL.BDCODEMP AND A.BDREFERENCIA = TOL.BDREFERENCIA AND A.BDCODPROD = TOL.BDCODPROD AND A.BDORDEM = TOL.BDORDEM)
              LEFT OUTER JOIN VEF_EMP_TREDZ MOV ON(MOV.BDCODEMP = TOL.BDCODEMP AND MOV.BDCHAVE = TOL.BDCHAVEREDZ)
              LEFT OUTER JOIN VEF_EMP_TDOCECF I ON(I.BDCODEMP = TOL.BDCODEMP AND I.BDCHAVE = TOL.BDCHAVEREDZ AND I.BDORDEMDOCECF = TOL.BDORDEMREDZ)
              LEFT OUTER JOIN VEF_EMP_TITEMDOCECF P ON(P.BDCODEMP = TOL.BDCODEMP AND P.BDCHAVE = TOL.BDCHAVEREDZ AND P.BDORDEMDOCECF = TOL.BDORDEMREDZ AND P.BDORDEMITEM = TOL.BDORDEMPROREDZ)
              LEFT OUTER JOIN VEF_BASE_TTABDOCFIS M ON(M.BDCODDOCFIS = I.BDCODDOCFIS)
              LEFT OUTER JOIN VEF_BASE_TCADMAQMRC MAQ ON(MAQ.BDCODEMP = MOV.BDCODEMP AND MAQ.BDORDEMMAQ = MOV.BDORDEMMAQ)
              LEFT OUTER JOIN VEF_BASE_TTABENQLEGALCAT42 E ON(E.BDCODENQ = A.BDCODENQ)
              WHERE TOL.BDCODEMP = :PRCODEMP
              AND TOL.BDREFERENCIA = :PRREFATU
              AND EMP.BDCONSOLIDAR1200 = 'TRUE'
              AND TOL.BDCHAVEREDZ IS NOT NULL
              AND EXISTS (
                          SELECT FIRST 1 E.BDORDEM
                          FROM VEF_EMP_TDRCSTSP_1100 E
                          WHERE E.BDCODEMP = A.BDCODEMP
                          AND E.BDREFERENCIA = A.BDREFERENCIA
                          AND E.BDCODPROD = A.BDCODPROD
                          AND E.BDCODMOV NOT IN(1)
                         )
              GROUP BY MOV.BDORDEMMAQ, PRO.BDCODPROD, MOV.BDDATAREDZ, MAQ.BDSERIEMAQ, PRO.BDCODSAIDA, A.BDCODENQ, E.BDCODEXP
             ) A;
END^

CREATE OR ALTER PROCEDURE SP_EXPORTA_DRCSTSP (
    PRCODEMP INTEGER,
    PRREFINI INTEGER,
    PRREFFIM INTEGER,
    PRFINALIDADE INTEGER,
    PRARQUIVO VARCHAR(260))
AS
DECLARE VARIABLE WFOUND INTEGER;
DECLARE VARIABLE WANO INTEGER;
DECLARE VARIABLE WMES INTEGER;
DECLARE VARIABLE WCODCONFICMSSPED INTEGER;
DECLARE VARIABLE WI INTEGER;
DECLARE VARIABLE WDIF INTEGER;
DECLARE VARIABLE WREFATU INTEGER;
DECLARE VARIABLE WARQUIVOEMP VARCHAR(260);
DECLARE VARIABLE WLINHA BLOB SUB_TYPE 1 SEGMENT SIZE 200;
BEGIN
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREFINI);

  DELETE FROM TEXPORTACAO_SPED WHERE BDID = :prARQUIVO;

  IF (:PRREFINI = :PRREFFIM) THEN
    wDif = 1;
  ELSE
    SELECT BDDIF + 1 FROM SP_REF_DIF(:PRREFINI, :PRREFFIM) INTO :wDif;

  wI = 0;
  WHILE (:wI < :wDif) DO
    BEGIN
      SELECT BDREFERENCIA FROM INC_REFERENCIA(:PRREFINI, :wI) INTO :wRefAtu;
      wI = :wI + 1;

      SELECT SP.BDCODCONFICMSSPED FROM SP_CONSULTAEMPRESAS_SIS(:wRefAtu, :PRCODEMP, 0) SP INTO :wCodConfICMSSPED;

      wMes = SUBSTRING(:wRefAtu FROM 5 FOR 2);
      wAno = SUBSTRING(:wRefAtu FROM 1 FOR 4);

      /*Cria arquivo da empresa e referência que vai ser exportada*/
      wARQUIVOEMP = REPLACE(:prARQUIVO, '.tmp', '_e='||:PRCODEMP||'_r='||:wRefAtu||'_.tmp'); -- Precisa do "_" para conseguir exportar v?rias empresas em "TExternalFile.Exportar"

      DELETE FROM TEXPORTACAO_SPED WHERE BDID = :wArquivoEmp;

      /*****************************************************************************
       *                                   0150                                    *
      *****************************************************************************/
      EXECUTE PROCEDURE SP_EXPORTA_DRCSTSP_0150(:PRCODEMP, :wRefAtu, :PRREFINI, :PRFINALIDADE, :wArquivoEmp);

      /*****************************************************************************
       *                                   0200                                    *
      *****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
      SELECT :wArquivoEmp,
             '0000.'||:PRCODEMP||'.0200.'||PRO.BDCODPROD AS bdCHAVEREG,
             '0200' AS BDREG,
             :PRCODEMP,
             (
              '0200'||
              '|'||IIF(COALESCE(PRO.BDCODSAIDA, '') = '', PRO.BDCODPROD, PRO.BDCODSAIDA)||
              '|'||PRO.BDDESCPROD||
              '|'||COALESCE(P.BDCODIGOEAN, '')||
              '|'||UN.BDAPEUNIMED||
              '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(NCM.BDCLASSIFICACAO))||
              '|'||REPLACE(COALESCE(CAST(PRO.BDALIQICMS AS NUMERIC(7, 2)), 0.00), '.', ',')||
              '|'||IIF(CEST.BDCODCEST IS NULL, '', (SELECT RESULT FROM SP_TIRATODOSSINAIS(CEST.BDCLASSCEST)))
             )
      FROM VEF_EMP_TDRCSTSP_1050 A
      JOIN TCADPRO P ON(P.BDCODPROD = A.BDCODPROD)
      JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = A.BDCODEMP AND PRO.BDCODPROD = A.BDCODPROD)
      LEFT OUTER JOIN TUNIDADEMEDIDA UN ON(UN.BDCODUNIMED = PRO.BDCODUNIMED)
      LEFT OUTER JOIN TNCM NCM ON(NCM.BDNCMPROD = PRO.BDNCMPROD)
      LEFT OUTER JOIN TCEST CEST ON (CEST.BDCODCEST = PRO.BDCODCEST)
      WHERE A.BDCODEMP = :PRCODEMP
      AND A.BDREFERENCIA = :wRefAtu
      AND EXISTS (
                  SELECT FIRST 1 E.BDORDEM
                  FROM VEF_EMP_TDRCSTSP_1100 E
                  WHERE E.BDCODEMP = A.BDCODEMP
                  AND E.BDREFERENCIA = A.BDREFERENCIA
                  AND E.BDCODPROD = A.BDCODPROD
                  AND E.BDCODMOV NOT IN(1)
                 );

      /*****************************************************************************
       *                                   0205                                    *
      *****************************************************************************/
      IF (COALESCE(:wCodConfICMSSped, 0) = 0) THEN
        BEGIN
          /*Precisa reestruturar o produto por referência pra montar o 0205*/
        END

      /*****************************************************************************
       *                                   1050                                    *
      *****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
      SELECT :wArquivoEmp,
             '0000.'||:PRCODEMP||'.1050.'||P.BDCODPROD AS bdCHAVEREG,
             '1050' AS BDREG,
             :PRCODEMP,
             (
              '1050'||
              '|'||IIF(COALESCE(P.BDCODSAIDA, '') = '', P.BDCODPROD, P.BDCODSAIDA)||
              '|'||REPLACE(COALESCE(CAST(A.BDQTDE_INICIAL AS NUMERIC(15, 3)), 0.000), '.', ',')||
              '|'||REPLACE(COALESCE(CAST(A.BDVL_TOT_INICIAL AS NUMERIC(15, 2)), 0.00), '.', ',')||
              '|'||REPLACE(COALESCE(CAST(A.BDQTDE_FINAL AS NUMERIC(15, 3)), 0.000), '.', ',')||
              '|'||REPLACE(COALESCE(CAST(A.BDVL_TOT_FINAL AS NUMERIC(15, 2)), 0.00), '.', ',')
             )
      FROM VEF_EMP_TDRCSTSP_1050 A
      JOIN TCADPRO_VINC P ON(P.BDCODEMP = A.BDCODEMP AND A.BDCODPROD = P.BDCODPROD)
      WHERE A.BDCODEMP = :PRCODEMP
      AND A.BDREFERENCIA = :wRefAtu
      AND EXISTS (
                  SELECT FIRST 1 E.BDORDEM
                  FROM VEF_EMP_TDRCSTSP_1100 E
                  WHERE E.BDCODEMP = A.BDCODEMP
                  AND E.BDREFERENCIA = A.BDREFERENCIA
                  AND E.BDCODPROD = A.BDCODPROD
                  AND E.BDCODMOV NOT IN(1)
                 );

      /*****************************************************************************
       *                                   1100                                    *
      *****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
      SELECT :wArquivoEmp,
               '0000.'||:PRCODEMP||'.1050.'||A.BDCODPROD||'.1100.'||A.BDMOV||'.'||A.BDCHAVE||'_'||A.BDORDEMLAN||'_'||A.BDORDEMPRO AS bdCHAVEREG,
               '1100' AS BDREG,
               :PRCODEMP,
               (
                '1100'||
                '|'||LPAD((SELECT BDNUMERO FROM SP_RETORNA_SO_NUMEROS_CHAVENFE(A.BDCHAVENFE)), 44, '0')||
                '|'||(SELECT BDDATA FROM SP_PARSE_DATE(A.BDDATAEMISSAO, 'DDMMYYYY'))||
                '|'||A.BDORDEMPRO||
                '|'||IIF(A.BDMOV = 'E', 0, 1)||
                '|'||IIF(COALESCE(A.BDCODSAIDA, '') = '', A.BDCODPROD, A.BDCODSAIDA)||
                '|'||COALESCE(SUBSTRING(A.BDCODNAT FROM 1 FOR 4), '')||
                '|'||REPLACE(CAST(COALESCE(A.BDQTDITEM, 0.000) AS NUMERIC(15, 3)), '.', ',')||
                '|'||REPLACE(COALESCE(CAST(A.BDVL_ICMS_SUP_ENT AS NUMERIC(15, 2)), 0.00), '.', ',')||
                '|'||REPLACE(COALESCE(CAST(A.BDVL_CONFRONTO AS NUMERIC(15, 2)), 0.00), '.', ',')||
                '|'||COALESCE(A.BDCODEXP, '')
               )
        FROM (
              SELECT TOL.*,
                     COALESCE(E.BDMODELO, S.BDMODELO) BDMODELO,
                     IIF(TOL.BDCHAVEENT IS NOT NULL, 'E', IIF(TOL.BDCHAVESAI IS NOT NULL, 'S', '')) BDMOV,
                     COALESCE(TOL.BDCHAVEENT, TOL.BDCHAVESAI) BDCHAVE,
                     COALESCE(E.BDCHAVENFE, S.BDCHAVENFE) BDCHAVENFE,
                     COALESCE(E.BDDATAENTRADAENT, S.BDDATAEMISSAO) BDDATAEMISSAO,
                     A.BDQTDITEM,
                     PRO.BDCODSAIDA,
                     COALESCE(EI.BDCODNAT, SI.BDCODNAT) BDCODNAT,
                     A.BDVL_ICMS_SUP_ENT,
                     A.BDVL_CONFRONTO,
                     COALESCE(TOL.BDORDEMENT, TOL.BDORDEMSAI, '') BDORDEMLAN,
                     COALESCE(TOL.BDORDEMPROENT, TOL.BDORDEMPROSAI, '') BDORDEMPRO,
                     ENQ.BDCODEXP
              FROM TOL_VEF_EMP_DRCSTSP_1100 TOL
              JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = TOL.BDCODEMP AND PRO.BDCODPROD = TOL.BDCODPROD)
              JOIN VEF_EMP_TDRCSTSP_1100 A ON(A.BDCODEMP = TOL.BDCODEMP AND A.BDREFERENCIA = TOL.BDREFERENCIA AND A.BDCODPROD = TOL.BDCODPROD AND A.BDORDEM = TOL.BDORDEM)
              LEFT OUTER JOIN VEF_EMP_TMOVENT E ON(E.BDCODEMP = TOL.BDCODEMP AND E.BDCHAVE = TOL.BDCHAVEENT)
              LEFT OUTER JOIN VEF_EMP_TMOVENTITENS EI ON(EI.BDCODEMP = TOL.BDCODEMP AND EI.BDCHAVE = TOL.BDCHAVEENT AND EI.BDORDEM = TOL.BDORDEMENT)
              LEFT OUTER JOIN VEF_EMP_TMOVPROENT EP ON(EP.BDCODEMP = TOL.BDCODEMP AND EP.BDCHAVE = TOL.BDCHAVEENT AND EP.BDORDEM = TOL.BDORDEMENT AND EP.BDORDEMPRO = TOL.BDORDEMPROENT)
              LEFT OUTER JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = TOL.BDCODEMP AND S.BDCHAVE = TOL.BDCHAVESAI)
              LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS SI ON(SI.BDCODEMP = TOL.BDCODEMP AND SI.BDCHAVE = TOL.BDCHAVESAI AND SI.BDORDEM = TOL.BDORDEMSAI)
              LEFT OUTER JOIN VEF_EMP_TMOVPROSAI SP ON(SP.BDCODEMP = TOL.BDCODEMP AND SP.BDCHAVE = TOL.BDCHAVESAI AND SP.BDORDEM = TOL.BDORDEMSAI AND SP.BDORDEMPRO = TOL.BDORDEMPROSAI)
              LEFT OUTER JOIN VEF_BASE_TTABENQLEGALCAT42 ENQ ON(ENQ.BDCODENQ = A.BDCODENQ)
              WHERE TOL.BDCODEMP = :PRCODEMP
              AND TOL.BDREFERENCIA = :wRefAtu
              AND COALESCE(TOL.BDCHAVEENT, TOL.BDCHAVESAI, 0) > 0
              AND ((COALESCE(A.BDCODENQ, 0) <> 2) OR ((A.BDCODENQ = 2) AND (SELECT COUNT(A.BDCODENQ)
                                                               FROM VEF_EMP_TDRCSTSP_1100 A
                                                               WHERE A.BDCODEMP = TOL.BDCODEMP
                                                               AND A.BDREFERENCIA = TOL.BDREFERENCIA
                                                               AND A.BDCODPROD = TOL.BDCODPROD
                                                               AND A.BDCODENQ = 2
                                                               GROUP BY A.BDCODENQ) = 1))
             ) A
        WHERE A.BDMODELO NOT IN(1, 2, 200)
        AND EXISTS (
                    SELECT FIRST 1 E.BDORDEM
                    FROM VEF_EMP_TDRCSTSP_1100 E
                    WHERE E.BDCODEMP = A.BDCODEMP
                    AND E.BDREFERENCIA = A.BDREFERENCIA
                    AND E.BDCODPROD = A.BDCODPROD
                    AND E.BDCODMOV NOT IN(1)
                   );

        INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
        SELECT :wArquivoEmp,
               '0000.'||:PRCODEMP||'.1050.'||A.BDCODPROD||'.1100.'||'.S.'||999 AS bdCHAVEREG,
               '1100' AS BDREG,
               :PRCODEMP,
               (
                '1100'||
                '|'||LPAD('0', 44, '0')||
                '|'||(SELECT LPAD(ULTDIA, 2, '0') FROM ULTIMO_DIA_MES(:wMes, :wAno))||LPAD(:wMes, 2, '0')||:wAno||
                '|'||999||
                '|'||1||
                '|'||IIF(COALESCE(A.BDCODSAIDA, '') = '', A.BDCODPROD, A.BDCODSAIDA)||
                '|'||5927||
                '|'||REPLACE(COALESCE(CAST(A.BDQTDITEM AS NUMERIC(15, 3)), 0.000), '.', ',')||
                '|'||''||
                '|'||REPLACE(COALESCE(CAST(A.BDVL_CONFRONTO AS NUMERIC(15, 2)), 0.00), '.', ',')||
                '|'||2
               )
        FROM (
              SELECT SUM(COALESCE(A.BDQTDITEM, 0)) BDQTDITEM,
                     SUM(COALESCE(A.BDVL_CONFRONTO, 0)) BDVL_CONFRONTO,
                     PRO.BDCODSAIDA,
                     TOL.BDCODPROD
              FROM TOL_VEF_EMP_DRCSTSP_1100 TOL
              JOIN TCADPRO_VINC PRO ON(PRO.BDCODEMP = TOL.BDCODEMP AND PRO.BDCODPROD = TOL.BDCODPROD)
              JOIN VEF_EMP_TDRCSTSP_1100 A ON(A.BDCODEMP = TOL.BDCODEMP AND A.BDREFERENCIA = TOL.BDREFERENCIA AND A.BDCODPROD = TOL.BDCODPROD AND A.BDORDEM = TOL.BDORDEM)
              LEFT OUTER JOIN VEF_EMP_TMOVENT E ON(E.BDCODEMP = TOL.BDCODEMP AND E.BDCHAVE = TOL.BDCHAVEENT)
              LEFT OUTER JOIN VEF_EMP_TMOVENTITENS EI ON(EI.BDCODEMP = TOL.BDCODEMP AND EI.BDCHAVE = TOL.BDCHAVEENT AND EI.BDORDEM = TOL.BDORDEMENT)
              LEFT OUTER JOIN VEF_EMP_TMOVPROENT EP ON(EP.BDCODEMP = TOL.BDCODEMP AND EP.BDCHAVE = TOL.BDCHAVEENT AND EP.BDORDEM = TOL.BDORDEMENT AND EP.BDORDEMPRO = TOL.BDORDEMPROENT)
              LEFT OUTER JOIN VEF_EMP_TMOVSAI S ON(S.BDCODEMP = TOL.BDCODEMP AND S.BDCHAVE = TOL.BDCHAVESAI)
              LEFT OUTER JOIN VEF_EMP_TMOVSAIITENS SI ON(SI.BDCODEMP = TOL.BDCODEMP AND SI.BDCHAVE = TOL.BDCHAVESAI AND SI.BDORDEM = TOL.BDORDEMSAI)
              LEFT OUTER JOIN VEF_EMP_TMOVPROSAI SP ON(SP.BDCODEMP = TOL.BDCODEMP AND SP.BDCHAVE = TOL.BDCHAVESAI AND SP.BDORDEM = TOL.BDORDEMSAI AND SP.BDORDEMPRO = TOL.BDORDEMPROSAI)
              WHERE TOL.BDCODEMP = :PRCODEMP
              AND TOL.BDREFERENCIA = :wRefAtu
              AND COALESCE(TOL.BDCHAVEENT, TOL.BDCHAVESAI, 0) > 0
              AND COALESCE(E.BDMODELO, S.BDMODELO) NOT IN(1, 2, 200)
              AND ((A.BDCODENQ = 2) AND (SELECT COUNT(A.BDCODENQ)
                                         FROM VEF_EMP_TDRCSTSP_1100 A
                                         WHERE A.BDCODEMP = TOL.BDCODEMP
                                         AND A.BDREFERENCIA = TOL.BDREFERENCIA
                                         AND A.BDCODPROD = TOL.BDCODPROD
                                         AND A.BDCODENQ = 2
                                         GROUP BY A.BDCODENQ) > 1)
              AND EXISTS (
                          SELECT FIRST 1 E.BDORDEM
                          FROM VEF_EMP_TDRCSTSP_1100 E
                          WHERE E.BDCODEMP = A.BDCODEMP
                          AND E.BDREFERENCIA = A.BDREFERENCIA
                          AND E.BDCODPROD = A.BDCODPROD
                          AND E.BDCODMOV NOT IN(1)
                         )
              GROUP BY TOL.BDCODEMP, TOL.BDREFERENCIA, TOL.BDCODPROD, PRO.BDCODSAIDA
             ) A;

      /*****************************************************************************
       *                                   1200                                    *
      *****************************************************************************/
      EXECUTE PROCEDURE SP_EXPORTA_DRCSTSP_1200(:wArquivoEmp, :PRCODEMP, :wRefAtu, :PRREFINI);

      SELECT FIRST 1 E.bdcodemp FROM TEXPORTACAO_SPED E WHERE E.BDID = :wArquivoEmp INTO :wFound;
      IF (ROW_COUNT > 0) THEN
        BEGIN
          /*****************************************************************************
           *                                   0000                                    *
          *****************************************************************************/
          INSERT INTO TEXPORTACAO_SPED(bdID, bdCHAVEREG, bdREG, bdCODEMP, bdLINHA)
          SELECT :wArquivoEmp,
                 '0000.'||tref.bdCODEMP AS bdCHAVEREG,
                 '0000' AS BDREG,
                 tref.bdCODEMP,
                 ('0000'||
                  '|'||LPAD(:wMes, 2, '0')||:wAno||
                  '|'||tref.bdNOMEMP||
                  '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(tref.bdCNPJEMP))||
                  '|'||(SELECT RESULT FROM SP_TIRATODOSSINAIS(tref.bdIEEMP))||
                  '|'||tref.bdCODIBGE||
                  '|'||'01'||
                  '|'||(SELECT BDRETORNO FROM PREENCHE_ESQUERDA(:PRFINALIDADE, 2, '0')))
          FROM SP_CONSULTAEMPRESAS_SIS(:wRefAtu, :PRCODEMP, 0) tref
          LEFT OUTER JOIN VW_EMP_REF_TOTAL trefsis ON (trefsis.bdCODEMP = tref.bdCODEMP);
        END

      /*****************************************************************************
      *                           EXPORTANDO ARQUIVO                              *
      ****************************************************************************/

      IF (:wFound IS NOT NULL) THEN
        BEGIN
          NEWFILE_UTF8(:wARQUIVOEMP);

          FOR SELECT E.BDLINHA
              FROM TEXPORTACAO_SPED E
              WHERE E.BDID = :wArquivoEmp
              ORDER BY E.BDREG
              INTO :wLinha
          DO
            BEGIN
              WRITELN_UTF8(:wArquivoEmp, :wLinha);
            END
        END
    END
END^

CREATE OR ALTER procedure SP_REMOVER_ACENTOS (
    PRTEXTO varchar(9999))
returns (
    BDRETORNO varchar(9999))
AS
DECLARE VARIABLE VL_ASCII SMALLINT;
DECLARE VARIABLE ILOOP SMALLINT = 1;
BEGIN
  BDRETORNO = '';
  WHILE (ILOOP <= CHAR_LENGTH(:PRTEXTO)) DO
  BEGIN
    VL_ASCII = ASCII_VAL(SUBSTRING(:PRTEXTO FROM :ILOOP FOR 1));
    IF (:VL_ASCII BETWEEN 192 AND 196) THEN
      VL_ASCII = 65;
    IF (:VL_ASCII = 199) THEN
      VL_ASCII = 67;
    IF (:VL_ASCII BETWEEN 200 AND 203) THEN
      VL_ASCII = 69;
    IF (:VL_ASCII BETWEEN 204 AND 207) THEN
      VL_ASCII = 73;
    IF (:VL_ASCII = 209) THEN
      VL_ASCII = 78;
    IF (:VL_ASCII BETWEEN 210 AND 214) THEN
      VL_ASCII = 79;
    IF (:VL_ASCII BETWEEN 217 AND 220) THEN
      VL_ASCII = 85;
    IF (:VL_ASCII BETWEEN 224 AND 228) THEN
      VL_ASCII = 97;
    IF (:VL_ASCII = 231) THEN
      VL_ASCII = 99;
    IF (:VL_ASCII BETWEEN 232 AND 235) THEN
      VL_ASCII = 101;
    IF (:VL_ASCII BETWEEN 236 AND 239) THEN
      VL_ASCII = 105;
    IF (:VL_ASCII = 241) THEN
      VL_ASCII = 110;
    IF (:VL_ASCII BETWEEN 242 AND 246) THEN
      VL_ASCII = 111;
    IF (:VL_ASCII BETWEEN 249 AND 252) THEN
      VL_ASCII = 117;
    BDRETORNO = :BDRETORNO || ASCII_CHAR(:VL_ASCII);
    ILOOP = :ILOOP + 1;
  END
  SUSPEND;
END^

/* Carlos Xavier - 22/02/21 Importação Layout SCI - Anexo 68 Relacionamento produtos com fornecedor #143825 */

create or alter procedure SP_ATUALIZA_INCON_TCADPRO_PART (
    PRSESSAO integer)
as
BEGIN
  DELETE from VEF_INCON_TCADPRO_PART;

  --  inconsistencia do codiog do terceiro 194
  INSERT INTO VEF_INCON_TCADPRO_PART (bdcodemp,BDSESSAO, BDORDEM, BDCODINCONSISTENCIA)
  SELECT u.bdcodemp, u.BDSESSAO, U.BDORDEM, 194 FROM TMP_TCADPRO_PART_TEMP U WHERE u.bdsessao = :prSessao and  U.BDCODTER is NULL;

  --  inconsistencia do codiog do produto 195
  INSERT INTO VEF_INCON_TCADPRO_PART (bdcodemp,BDSESSAO, BDORDEM, BDCODINCONSISTENCIA)
  SELECT u.bdcodemp, u.BDSESSAO, U.BDORDEM, 195 FROM TMP_TCADPRO_PART_TEMP U WHERE u.bdsessao = :prSessao and  U.BDCODprod is NULL;
END^

/* Carlos Xavier - 22/02/21 Importação Layout SCI - Anexo 68 Relacionamento produtos com fornecedor #143825 */

create or alter procedure SP_COMMIT_TCADPRO_PART (
    PRSESSAO integer)
as
BEGIN

    SETORDEMSEQUENCIAL_PESQ(0);
    
    update TMP_TCADPRO_PART_TEMP U
    SET BDEDITCHAVE = GETORDEMSEQUENCIAL_PESQ(u.bdcodprod||'|'||u.bdordem) + (select COALESCE(max(bdordem),0) from tcadpro_part p where p.bdcodprod = u.bdcodprod)
    where u.bdsessao = :prSessao
      and u.bdcodter is not null
      and u.bdcodprod is not null
    ;
    
    INSERT INTO TCADPRO_PART (BDCODPROD, BDCODTER, BDORDEM, BDCODENTRADA, BDDESCPRODBUSCA)
    select t.BDCODPROD, t.BDCODTER,bdeditchave , t.BDCODENTRADA, BDDESCRICAO
    FROM TMP_TCADPRO_PART_TEMP t
    where t.bdsessao = :prSessao
     and t.bdeditchave is not null
     and not exists (select bdcodprod from tcadpro_part p
                     where p.BDCODPROD = t.bdcodprod
                       and p.BDCODTER = t.bdcodter
                       and p.BDDESCPRODBUSCA = t.bddescricao
                    )
     ;
    
    INSERT INTO TMP_TCADPRO_PART (BDSESSAO,BDCODPROD, BDCODTER, BDORDEM, BDCODENTRADA, BDDESCPRODBUSCA)
    select T.BDSESSAO,t.BDCODPROD, t.BDCODTER,bdeditchave , t.BDCODENTRADA, BDDESCRICAO
    FROM TMP_TCADPRO_PART_TEMP t
    where t.bdsessao = :prSessao
     and  t.bdeditchave is not null
     and not exists (select bdcodprod from TMP_TCADPRO_PART p
                     where p.BDCODPROD = t.bdcodprod
                       and p.BDCODTER = t.bdcodter
                       and p.BDDESCPRODBUSCA = t.bddescricao
                    )
     ;

END^

CREATE OR ALTER TRIGGER VRH_EMP_TSITCOL_AIU0 FOR VRH_EMP_TSITCOL
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
BEGIN
  IF (COALESCE(OLD.BDBENEFDEFERIDO,'') <> COALESCE(NEW.BDBENEFDEFERIDO,'')) THEN
     BEGIN
       -- 146010 - Raphael Teodoro - 15/04/2021 - Atualiza "BDBENEFDEFERIDO" de registros diretamente decorrentes (será executado em cascata)
       update VRH_EMP_TSITCOL
       set BDBENEFDEFERIDO = NEW.BDBENEFDEFERIDO
       where (BDCODEMP = NEW.BDCODEMP)
         and (BDCODCOL = NEW.BDCODCOL)
         and ((NEW.BDBENEFDEFERIDO <> 'TRUE') or        -- Desmarcar
              (BDDATAFIMATESTADOAUX >= '11-01-2020') or -- Término do atestado posterior à data inicial
              (BDDATAFIMSIT >= '11-01-2020') )          -- Término do afastamento posterior à data inicial
         and (BDDATAINISEFIP in (select TANT.BDDATAINISEFIPDEC
                                 from VRH_EMP_TSITCOL_DEC TANT
                                 where (TANT.BDCODEMP = NEW.BDCODEMP)
                                   and (TANT.BDCODCOL = NEW.BDCODCOL)
                                   and (TANT.BDDATAINISEFIP = NEW.BDDATAINISEFIP)
                                 union all
                                 select TPOST.BDDATAINISEFIP
                                 from VRH_EMP_TSITCOL_DEC TPOST
                                 where (TPOST.BDCODEMPDEC = NEW.BDCODEMP)
                                   and (TPOST.BDCODCOLDEC = NEW.BDCODCOL)
                                   and (TPOST.BDDATAINISEFIPDEC = NEW.BDDATAINISEFIP) ));
     END
END^

CREATE OR ALTER trigger vrh_emp_tsitcol_biu0 for vrh_emp_tsitcol
active before insert or update position 0
AS
DECLARE VARIABLE WCARENSIT Integer;
BEGIN
  -- 146010 - Raphael Teodoro - 09/04/2021 - Preenche campos novos caso seja uma integração antiga
  IF (NEW.BDCODSITAUX IS NULL) THEN
     BEGIN
       IF (NEW.BDCODSIT = 1) THEN
          NEW.BDCODSITAUX = 2;
       ELSE
       IF (NEW.BDCODSIT = 11) THEN
          NEW.BDCODSITAUX = 12;
       ELSE
          NEW.BDCODSITAUX = NEW.BDCODSIT;

       IF ((NEW.BDDATAINISEFIP = NEW.BDDATAINISIT) AND (NEW.BDCODSIT <> NEW.BDCODSITAUX)) THEN
          BEGIN
            -- Ajusta início da situação caso tenha mais dias que a carência
            wcarensit = NULL;
            SELECT PSITDIA.BDCARENSIT FROM VRH_BASE_TPREPSIT_DIA PSITDIA
            WHERE (PSITDIA.BDCODSIT  = NEW.BDCODSITAUX)
              AND (PSITDIA.BDDATASTD = (SELECT MAX(X.BDDATASTD)
                                        FROM VRH_BASE_TPREPSIT_DIA X
                                        WHERE (X.BDCODSIT = NEW.BDCODSITAUX) ))
            INTO wcarensit;

            IF ((COALESCE(wcarensit,0) > 0) AND
                (wcarensit < DATEDIFF(DAY FROM NEW.BDDATAINISEFIP TO NEW.BDDATAFIMSIT)+1)) THEN
               NEW.BDDATAINISIT = DATEADD(wcarensit-1 DAY TO NEW.BDDATAINISEFIP);
          END

       IF ((NEW.BDDATAINIATESTADOAUX IS NOT NULL) AND
           (NEW.BDDATAFIMATESTADOAUX IS NOT NULL) AND
           (NEW.BDDATAINIAFASTAUX IS NULL)) THEN
          NEW.BDDATAFIMSIT = NEW.BDDATAFIMATESTADOAUX;
       ELSE
       IF ((NEW.BDDATAINIATESTADOAUX is NOT NULL) AND
           (NEW.BDDATAFIMATESTADOAUX IS NOT NULL) AND
           (NEW.BDDATAINIAFASTAUX IS NOT NULL) AND
           (NEW.BDDATAFIMAFASTAUX IS NOT NULL)) THEN
          NEW.BDDATAFIMSIT = NEW.BDDATAFIMAFASTAUX;
       ELSE
       IF ((NEW.BDDATAINIATESTADOAUX IS NULL) AND
           (NEW.BDDATAFIMATESTADOAUX IS NULL) AND
           (NEW.BDDATAINIAFASTAUX IS NOT NULL) AND
           (NEW.BDDATAFIMAFASTAUX IS NOT NULL)) THEN
          NEW.BDDATAFIMSIT = NEW.BDDATAFIMAFASTAUX;
       ELSE
       IF ((NEW.BDDATAINIATESTADOAUX is NOT NULL) AND
           (NEW.BDDATAFIMATESTADOAUX IS NOT NULL) AND
           (NEW.BDDATAINIAFASTAUX IS NOT NULL) AND
           (NEW.BDDATAFIMAFASTAUX IS NULL)) THEN
          NEW.BDDATAFIMSIT = NULL;

       NEW.BDDIASDOCUMENTO      = NULL;
       NEW.BDDATAINIATESTADOAUX = NULL;
       NEW.BDDIASAFASTAUX       = NULL;
       NEW.BDDATAFIMATESTADOAUX = NULL;
       NEW.BDDATAINIAFASTAUX = NULL;
       NEW.BDDIASATESTADOAUX = NULL;
       NEW.BDDATAFIMAFASTAUX = NULL;

       IF (NEW.BDDATAINISEFIP < NEW.BDDATAINISIT) THEN
          BEGIN
            -- Atestado + Afastamento
            NEW.BDDATAINIATESTADOAUX = NEW.BDDATAINISEFIP;
            NEW.BDDATAFIMATESTADOAUX = DATEADD(-1 DAY TO NEW.BDDATAINISIT);

            NEW.BDDATAINIAFASTAUX = NEW.BDDATAINISIT;
            IF (NEW.BDDATAFIMSIT IS NOT NULL) THEN
               NEW.BDDATAFIMAFASTAUX = NEW.BDDATAFIMSIT;
          END
       ELSE
       IF ((NEW.BDCODSIT = 1) OR (NEW.BDCODSIT = 11)) THEN
          BEGIN
            -- Somente atestado
            NEW.BDDATAINIATESTADOAUX = NEW.BDDATAINISEFIP;
            NEW.BDDATAFIMATESTADOAUX = NEW.BDDATAFIMSIT;
          END
       ELSE
          BEGIN
            -- Somente afastamento
            NEW.BDDATAINIAFASTAUX = NEW.BDDATAINISIT;
            NEW.BDDATAFIMAFASTAUX = NEW.BDDATAFIMSIT;
          END

       IF (NEW.BDDATAFIMATESTADOAUX IS NOT NULL) THEN
          NEW.BDDIASATESTADOAUX = DATEDIFF(DAY FROM NEW.BDDATAINIATESTADOAUX TO NEW.BDDATAFIMATESTADOAUX)+1;

       IF (NEW.BDDATAFIMAFASTAUX IS NOT NULL) THEN
          NEW.BDDIASAFASTAUX = DATEDIFF(DAY FROM NEW.BDDATAINIAFASTAUX TO NEW.BDDATAFIMAFASTAUX)+1;

       IF ((NEW.BDDATAFIMSIT IS NULL) AND (COALESCE(NEW.BDDIASATESTADO,0) <> 0)) THEN
          NEW.BDDIASDOCUMENTO = NEW.BDDIASATESTADO;
       ELSE
          NEW.BDDIASDOCUMENTO = COALESCE(NEW.BDDIASATESTADOAUX,0) + COALESCE(NEW.BDDIASAFASTAUX,0);
     END
  ELSE
     IF ((NEW.BDDIASATESTADOAUX <= 15) AND (COALESCE(NEW.BDDIASAFASTAUX,0) = 0) AND (new.BDDATAINIAFASTAUX is null)) THEN
        BEGIN
          IF (NEW.BDCODSITAUX = 2) THEN
             NEW.BDCODSIT = 1;
          ELSE
          IF (NEW.BDCODSITAUX = 12) THEN
             NEW.BDCODSIT = 11;
        END

  IF (NEW.BDDATAFIMSIT IS NULL) THEN
     BEGIN
       IF ((NEW.BDDATAINIATESTADOAUX IS NOT NULL) AND
           (NEW.BDDATAFIMATESTADOAUX IS NOT NULL) AND
           (NEW.BDDATAINIAFASTAUX IS NULL)) THEN
          NEW.BDDATAFIMSIT = NEW.BDDATAFIMATESTADOAUX;
       ELSE
       IF ((NEW.BDDATAINIATESTADOAUX is NOT NULL) AND
           (NEW.BDDATAFIMATESTADOAUX IS NOT NULL) AND
           (NEW.BDDATAINIAFASTAUX IS NOT NULL) AND
           (NEW.BDDATAFIMAFASTAUX IS NOT NULL)) THEN
          NEW.BDDATAFIMSIT = NEW.BDDATAFIMAFASTAUX;
       ELSE
       IF ((NEW.BDDATAINIATESTADOAUX IS NULL) AND
           (NEW.BDDATAFIMATESTADOAUX IS NULL) AND
           (NEW.BDDATAINIAFASTAUX IS NOT NULL) AND
           (NEW.BDDATAFIMAFASTAUX IS NOT NULL)) THEN
          NEW.BDDATAFIMSIT = NEW.BDDATAFIMAFASTAUX;
       ELSE
       IF ((NEW.BDDATAINIATESTADOAUX is NOT NULL) AND
           (NEW.BDDATAFIMATESTADOAUX IS NOT NULL) AND
           (NEW.BDDATAINIAFASTAUX IS NOT NULL) AND
           (NEW.BDDATAFIMAFASTAUX IS NULL)) THEN
          NEW.BDDATAFIMSIT = NULL;
     END

  -- 146010 - Raphael Teodoro - 09/04/2021 - Atualiza campo escondido "BDDATAINISIT" para manter compatibilidade das rotinas existentes
  NEW.BDDATAINISIT   = COALESCE(NEW.BDDATAINIAFASTAUX, NEW.BDDATAINIATESTADOAUX, NEW.BDDATAINISEFIP);
  NEW.BDDIASATESTADO = NEW.BDDIASDOCUMENTO;

  if ((NEW.BDDATAINIATESTADOAUX = NEW.BDDATAINISIT) and (NEW.BDDATAFIMSIT IS NULL) and (NEW.BDDIASSIT IS NULL) and (NEW.BDDIASATESTADOAUX < 15)) then
     begin
       NEW.BDDATAFIMSIT = NEW.BDDATAFIMATESTADOAUX;
       NEW.BDDIASSIT    = NEW.BDDIASATESTADOAUX;
     end
END^

CREATE OR ALTER TRIGGER VRH_EMP_TSITCOL_DEC_AI0 FOR VRH_EMP_TSITCOL_DEC
ACTIVE AFTER INSERT POSITION 0
AS
declare variable WBENEFDEFERIDO DM_BOOLEAN;
BEGIN
  WBENEFDEFERIDO = NULL;
  SELECT BDBENEFDEFERIDO
  FROM VRH_EMP_TSITCOL
  WHERE (BDCODEMP = NEW.BDCODEMP)
    AND (BDCODCOL = NEW.BDCODCOL)
    AND (BDDATAINISEFIP = NEW.BDDATAINISEFIP)
  INTO :WBENEFDEFERIDO;

  IF (WBENEFDEFERIDO IS NOT NULL) THEN
     BEGIN
       -- 146010 - Raphael Teodoro - 15/04/2021 - Atualiza "Benefício deferido" da decorrência conforme registro atual (trigger de "VRH_EMP_TSITCOL" se encarrega dos vínculos)
       UPDATE VRH_EMP_TSITCOL
       SET BDBENEFDEFERIDO = :WBENEFDEFERIDO
       WHERE (BDCODEMP = NEW.BDCODEMPDEC)
         AND (BDCODCOL = NEW.BDCODCOLDEC)
         AND (BDDATAINISEFIP = NEW.BDDATAINISEFIPDEC)
         AND ( (:WBENEFDEFERIDO <> 'TRUE') or            -- Desmarcar
               (BDDATAFIMATESTADOAUX >= '11-01-2020') or -- Término do atestado posterior à data inicial
               (BDDATAFIMSIT >= '11-01-2020') );         -- Término do afastamento posterior à data inicial
     END
END^

CREATE OR ALTER TRIGGER VRH_EMP_TSITCOL_DEC_AD0 FOR VRH_EMP_TSITCOL_DEC
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  -- 146010 - Raphael Teodoro - 15/04/2021 - Remove "Benefício deferido" da decorrência (trigger de "VRH_EMP_TSITCOL" se encarrega dos vínculos)
  UPDATE VRH_EMP_TSITCOL
  SET BDBENEFDEFERIDO = 'FALSE'
  WHERE (BDCODEMP = OLD.BDCODEMPDEC)
    AND (BDCODCOL = OLD.BDCODCOLDEC)
    AND (BDDATAINISEFIP = OLD.BDDATAINISEFIPDEC);
END^


CREATE OR ALTER TRIGGER VRH_RHNET_TIMAGENS_EXP_BI0 FOR VRH_RHNET_TIMAGENS_EXP
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;

begin
  if (coalesce(new.bdcodigo, 0) = 0) then
     begin
       vcod = null;
       select coalesce(max(BDCODIGO) + 1, 1) from VRH_RHNET_TIMAGENS_EXP into :vcod;
       vcod = coalesce(vcod, 1);
       new.bdcodigo = :vcod;
     end

  new.bdstatusenvio = 0;
  select current_timestamp from rdb$database into new.bddatahora;
end
^

CREATE OR ALTER trigger vrh_esocial_infobasefgts_c_bi0 for vrh_esocial_infobasefgts_c
active before insert position 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDCODINFO is null) or (new.BDCODINFO = 0)) then
  begin
    select coalesce((max(BDCODINFO) + 1), 1)
    from VRH_ESOCIAL_INFOBASEFGTS_C
    where BDCODEMP = new.BDCODEMP and
          BDCODCOL = new.BDCODCOL and
          BDCODEVT = new.BDCODEVT
    into VCODIGO;

    new.BDCODINFO = VCODIGO;
  end
end^

create or alter procedure SP_APAGA_IMPORTACAO_VPRA
as
declare variable WINICIOU timestamp;
declare variable WTABELA varchar(100);
begin
  --execute statement 'select localtimestamp from rdb$database' into :wIniciou;
  wIniciou = localtimestamp;

  for execute statement
  ' SELECT first 200 a.RDB$RELATION_NAME ' ||
  ' FROM RDB$RELATIONS a ' ||
  ' WHERE COALESCE(RDB$SYSTEM_FLAG, 0) = 0 ' || --tabela
  ' AND RDB$RELATION_TYPE = 4 ' || --global temporary table
  ' and substring(a.RDB$RELATION_NAME from 1 for 4) <> ''TMP_'' ' || --TMP_ são prefixo de tabelas do Único
  ' and a.RDB$RELATION_NAME like ''T%'' ' || --tem que começar com T maiúsculo
  ' and character_length(trim(a.RDB$RELATION_NAME)) = 8  ' || --Por segurança só apaga tabelas com 8 de tamanho que é o que viria do Visual
  ' and a.rdb$relation_name not in (select rdb$relation_name from rdb$indices) ' --Apaga só tabelas que não tem índice nem chave secundária
  into :wTabela
  do
  begin
    execute statement 'drop table ' || wtabela;
    if (datediff(minute from wIniciou to localtimestamp) >= 1) then
    begin
      leave;
    end
  end
end^


CREATE OR ALTER TRIGGER TOL_VEF_EMP_TSERINSS_AI0 FOR TOL_VEF_EMP_TSERINSS
ACTIVE AFTER INSERT POSITION 0
AS
  declare variable wcodter INTEGER;
  declare variable wdtlanc DATE;
  declare variable wcodcentro INTEGER;
  declare variable wcodtpcc INTEGER;
  declare variable wref INTEGER;

begin
  wcodter = null;
  wdtlanc = null;
  select first 1 BDCODTER, BDDATAEMISSAO from VEF_EMP_TMOVSER where BDCODEMP = new.bdcodemp and BDCHAVE = new.bdchaveef into :wcodter, :wdtlanc;

  if (coalesce(wcodter, 0) > 0) then
     begin
       if (wdtlanc is null) then
          select localtimestamp from rdb$database into :wdtlanc;

       if (wdtlanc is not null) then
          begin
            wref = CAST((substring(cast(wdtlanc as varchar(10)) from 1 for 4)||substring(cast(wdtlanc as varchar(10)) from 6 for 2)) as integer);
            wcodcentro = null;
            wcodtpcc   = null;
            select first 1 BDCODCENTROS from TEMPRESAS_REF where BDCODEMP = new.bdcodemp and BDREFEMP <= :wref order by BDREFEMP desc into :wcodcentro;

            if (coalesce(wcodcentro, 0) > 0) then
               begin
                 select first 1 BDCODTPCC from VRH_BASE_TCUSTOM where BDCODCENTRO = :wcodcentro and BDCODTER = :wcodter into :wcodtpcc;

                 if (coalesce(wcodtpcc, 0) > 0) then
                    update VRHF_EMP_TNOTASFISCAIS set BDCODCENTRO = :wcodcentro, BDCODTPCC = :wcodtpcc where BDCODEMP = new.bdcodemp and BDCHAVE = new.bdchaverh;
               end
          end
     end
end
^

CREATE OR ALTER TRIGGER VINT_EMP_PROCESSOTROCA_BAL_BI0 FOR VINT_EMP_PROCESSOTROCA_BAL
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  IF ((NEW.bdordem = 0) OR (NEW.bdordem IS NULL)) THEN
     BEGIN
       SELECT MAX(bdordem) FROM vint_emp_processotroca WHERE bdcodemp = NEW.bdcodemp INTO NEW.bdordem;
     END
end^

CREATE OR ALTER TRIGGER VSUC_EMP_TLAN_SPED_K300_BI0 for VSUC_EMP_TLAN_SPED_K300
active before insert position 0
AS
begin
  if ((coalesce(NEW.bdcodk300,0) = 0) or (exists(SELECT bdcodk300 FROM VSUC_EMP_TLAN_SPED_K300
                                            WHERE BDCODEMPGRPECO = NEW.BDCODEMPGRPECO
                                              AND BDCODGRPECO = NEW.BDCODGRPECO
                                              AND bdcodk300 = NEW.bdcodk300)))  then
     begin
       SELECT COALESCE((MAX(bdcodk300)+1), 1) FROM VSUC_EMP_TLAN_SPED_K300
       WHERE BDCODEMPGRPECO = NEW.BDCODEMPGRPECO AND BDCODGRPECO = NEW.BDCODGRPECO
       INTO NEW.bdcodk300;
     end
end^



CREATE OR ALTER TRIGGER VSUC_EMP_TLAN_SPED_K315_BI0 for VSUC_EMP_TLAN_SPED_K315
active before insert position 0
AS
begin
  IF ((NEW.bdcodk310 IS NULL) OR (NEW.bdcodk310 = 0)) THEN
      BEGIN
        SELECT COALESCE((MAX(bdcodk310)), 1) FROM VSUC_EMP_TLAN_SPED_K310 WHERE (BDCODEMPGRPECO = NEW.BDCODEMPGRPECO
                                                                                 AND BDCODGRPECO = NEW.BDCODGRPECO
                                                                                 AND BDCODK300 = NEW.BDCODK300) INTO NEW.bdcodk310;
      END
  if ((coalesce(NEW.BDCODK315,0) = 0) or (exists(select BDCODK310 FROM VSUC_EMP_TLAN_SPED_K315
                                                        where BDCODEMPGRPECO = NEW.BDCODEMPGRPECO
                                                          AND BDCODGRPECO = NEW.BDCODGRPECO
                                                          AND BDCODK300 = NEW.BDCODK300
                                                          AND bdcodk310 = NEW.bdcodk310
                                                          AND bdcodk315 = NEW.bdcodk315))) then
     begin
       SELECT COALESCE((MAX(bdcodk315)+1), 1) FROM VSUC_EMP_TLAN_SPED_K315
       WHERE BDCODEMPGRPECO = NEW.BDCODEMPGRPECO AND BDCODGRPECO = NEW.BDCODGRPECO AND BDCODK300 = NEW.BDCODK300 AND bdcodk310 = NEW.bdcodk310
       into new.bdcodk315;
     end
end^

CREATE OR ALTER trigger tol_vsuc_emp_tlan_auto_ad0 for tol_vsuc_emp_tlan_auto
active after delete position 0
AS
begin
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.BDCHAVE);
end^

CREATE OR ALTER trigger tol_vsuc_tlan_autoparpgto_ad0 for tol_vsuc_emp_tlan_autoparpgto
active after delete position 0
AS
begin
  EXECUTE PROCEDURE SP_EXCLUI_ONLINE(OLD.BDCODEMPSUC,OLD.BDCHAVE);
end^

/* Trigger: VSH_EMP_TCONF_LANAUTO_INC_BI0 */
CREATE OR ALTER TRIGGER VSH_EMP_TCONF_LANAUTO_INC_BI0 FOR VSH_EMP_TCONF_LANAUTO_INC
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF (NEW.BDORDEMINC IS NULL OR NEW.BDORDEMINC = 0) THEN
  BEGIN
    SELECT COALESCE(MAX(BDORDEMINC) + 1, 1)
    FROM VSH_EMP_TCONF_LANAUTO_INC
    WHERE (BDCODAGENDAMENTO = NEW.BDCODAGENDAMENTO) AND
          (BDCODEMP = NEW.BDCODEMP) AND
          (BDCODPLANOSCHIP = NEW.BDCODPLANOSCHIP) AND
          (BDORDEMAGENDAMENTO = NEW.BDORDEMAGENDAMENTO) AND
          (BDCHAVE = NEW.BDCHAVE) AND
          (BDORDEMPAR = NEW.BDORDEMPAR)
    INTO NEW.BDORDEMINC;
  END
END
^

CREATE OR ALTER procedure SP_FILTER_REGIME_DEMDOC (
    PRIND_OPER integer,
    PRCONDPGTO integer,
    PRTIPOAPURACAORETIR integer,
    PRTIPOAPURACAORETIRTOM integer)
returns (
    BDISVALID DM_BOOLEAN)
as
declare variable WTIPO integer;
BEGIN
  BDISVALID = 'TRUE';

  /*
    1 - Aquisição
    2, 3 - Receita
  */
  IF (:PRIND_OPER = 1) THEN
    wTipo = :PRTIPOAPURACAORETIRTOM;
  ELSE
    wTipo = :PRTIPOAPURACAORETIR;

  IF (:wTipo = 1) THEN
    BDISVALID = IIF(:PRCONDPGTO <> 1, 'TRUE', 'FALSE');

  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_FILTER_REGIME_SERVICO (
    BDTIPLAN INTEGER,
    PRCONDPGTO INTEGER,
    PRTIPOAPURACAORETIR INTEGER,
    PRTIPOAPURACAORETIRTOM INTEGER)
RETURNS (
    BDISVALID DM_BOOLEAN)
AS
DECLARE VARIABLE WTIPO INTEGER;
BEGIN
  BDISVALID = 'TRUE';

  /*
    0 - Emitido
    1 - Recebido
  */
  IF (:BDTIPLAN = 0) THEN
    wTipo = :PRTIPOAPURACAORETIR;
  ELSE
    wTipo = :PRTIPOAPURACAORETIRTOM;

  IF (:wTipo = 1) THEN
    BDISVALID = IIF(:PRCONDPGTO <> 1, 'TRUE', 'FALSE');

  SUSPEND;
END^

create or alter procedure SP_FILTER_REGIME_SERVICO_EXP (
    BDTIPLAN integer,
    PRCONDPGTO integer,
    PRTIPOAPURACAORETIR integer,
    PRTIPOAPURACAORETIRTOM integer)
returns (
    BDISVALID DM_BOOLEAN)
as
declare variable WTIPO integer;
BEGIN
  BDISVALID = 'TRUE';

  /*
    0 - Emitido
    1 - Recebido
  */
  IF (:BDTIPLAN = 0) THEN
    wTipo = :PRTIPOAPURACAORETIR;
  ELSE
    wTipo = :PRTIPOAPURACAORETIRTOM;

  IF (:wTipo = 1) THEN
    BDISVALID = IIF(:PRCONDPGTO <> 1, 'TRUE', 'FALSE');

  SUSPEND;
END^

create or alter procedure SP_FILTER_REGIME_DEMDOC_EXP (
    PRIND_OPER integer,
    PRCONDPGTO integer,
    PRTIPOAPURACAORETIR integer,
    PRTIPOAPURACAORETIRTOM integer)
returns (
    BDISVALID DM_BOOLEAN)
as
declare variable WTIPO integer;
BEGIN
  BDISVALID = 'TRUE';

  /*
    1 - Aquisição
    2, 3 - Receita
  */
  IF (:PRIND_OPER = 1) THEN
    wTipo = :PRTIPOAPURACAORETIRTOM;
  ELSE
    wTipo = :PRTIPOAPURACAORETIR;

  IF (:wTipo = 1) THEN
    BDISVALID = IIF(:PRCONDPGTO = 0, 'TRUE', 'FALSE');

  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_FILTER_SER_RENDIMENTOS (
    PRTIPOAPURACAORETIR INTEGER,
    PRTIPOAPURACAORETIRTOM INTEGER,
    PRCOMBOREGIMEIR INTEGER,
    PRCOMBOREGIMEIRTOM INTEGER,
    PRTIPOLAN INTEGER,
    PRTIPO CHAR(5))
RETURNS (
    BDISVALID DM_BOOLEAN)
AS
DECLARE VARIABLE WIRTYPE INTEGER;
DECLARE VARIABLE WCOMBOTYPE INTEGER;
BEGIN
  BDISVALID = 'TRUE';

  IF (:PRTIPOLAN = 0) THEN
    wComboType = :PRCOMBOREGIMEIR; /*Emitido*/
  ELSE
    wComboType = :PRCOMBOREGIMEIRTOM; /*Recebido*/

  IF (:wComboType = 2) THEN /*Regime de caixa*/
    BEGIN
      IF (:PRTIPO = 'CAIXA') THEN
        BDISVALID = 'TRUE';
      ELSE
        BDISVALID = 'FALSE';
    END
  ELSE /*Cadastro da empresa ou Competência*/
    BEGIN
      wIRType = IIF(:PRTIPOLAN = 0, :PRTIPOAPURACAORETIR, :PRTIPOAPURACAORETIRTOM);
      IF (:PRTIPO = 'CAIXA') THEN
        BDISVALID = IIF(:wIRType = 1, 'TRUE', 'FALSE');
      ELSE
        BDISVALID = IIF(:wIRType = 0, 'TRUE', 'FALSE');
    END

  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_FILTER_SER_RENDIMENTOS (
    PRTIPOAPURACAORETIR INTEGER,
    PRTIPOAPURACAORETIRTOM INTEGER,
    PRCOMBOREGIMEIR INTEGER,
    PRCOMBOREGIMEIRTOM INTEGER,
    PRTIPOLAN INTEGER,
    PRTIPO CHAR(5))
RETURNS (
    BDISVALID DM_BOOLEAN)
AS
DECLARE VARIABLE WIRTYPE INTEGER;
DECLARE VARIABLE WCOMBOTYPE INTEGER;
BEGIN
  BDISVALID = 'TRUE';

  IF (:PRTIPOLAN = 0) THEN
    wComboType = :PRCOMBOREGIMEIR; /*Emitido*/
  ELSE
    wComboType = :PRCOMBOREGIMEIRTOM; /*Recebido*/

  IF (:wComboType = 2) THEN /*Regime de caixa*/
    BEGIN
      IF (:PRTIPO = 'CAIXA') THEN
        BDISVALID = 'TRUE';
      ELSE
        BDISVALID = 'FALSE';
    END
  ELSE /*Cadastro da empresa ou Competência*/
    BEGIN
      wIRType = IIF(:PRTIPOLAN = 0, :PRTIPOAPURACAORETIR, :PRTIPOAPURACAORETIRTOM);
      IF (:PRTIPO = 'CAIXA') THEN
        BDISVALID = IIF(:wIRType = 1, 'TRUE', 'FALSE');
      ELSE
        BDISVALID = IIF(:wIRType = 0, 'TRUE', 'FALSE');
    END

  SUSPEND;
END^

CREATE OR ALTER procedure SP_FILTER_DEM_RENDIMENTOS (
    PRTIPOAPURACAORETIR integer,
    PRTIPOAPURACAORETIRTOM integer,
    PRCOMBOREGIMEIR integer,
    PRCOMBOREGIMEIRTOM integer,
    PRTIPOLAN integer,
    PRTIPO char(5))
returns (
    BDISVALID DM_BOOLEAN)
as
declare variable WIRTYPE integer;
declare variable WCOMBOTYPE integer;
BEGIN
  BDISVALID = 'TRUE';

  IF (:PRTIPOLAN = 1) THEN
    wComboType = :PRCOMBOREGIMEIRTOM; /*Recebido*/
  ELSE
    wComboType = :PRCOMBOREGIMEIR; /*Emitido*/

  IF (:wComboType = 2) THEN /*Regime de caixa*/
    BEGIN
      IF (:PRTIPO = 'CAIXA') THEN
        BDISVALID = 'TRUE';
      ELSE
        BDISVALID = 'FALSE';
    END
  ELSE /*Cadastro da empresa ou Competência*/
    BEGIN
      wIRType = IIF(:PRTIPOLAN = 1, :PRTIPOAPURACAORETIRTOM, :PRTIPOAPURACAORETIR);
      IF (:PRTIPO = 'CAIXA') THEN
        BDISVALID = IIF(:wIRType = 1, 'TRUE', 'FALSE');
      ELSE
        BDISVALID = IIF(:wIRType = 0, 'TRUE', 'FALSE');
    END

  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_AJU_E111_E113_AUTO_PR (
    PRCODEMP INTEGER,
    PRORDEME111 INTEGER,
    PRREFLAN INTEGER,
    PRREFSIS INTEGER,
    PRCODPERIODO INTEGER)
AS
DECLARE VARIABLE WBDCREDPRESUMIDO VARCHAR(5);
DECLARE VARIABLE WOPINTERNA NUMERIC(7,4);
DECLARE VARIABLE WOPINTER12 NUMERIC(7,4);
DECLARE VARIABLE WOPINTER7 NUMERIC(7,4);
DECLARE VARIABLE WOPSP NUMERIC(7,4);
BEGIN
  /*Delete na tabela temporária E113*/
  DELETE FROM TMP_VEF_EMP_TAJUICMSE113;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREFSIS);

  /*Pega parâmetros no cadastro da empresa aba fiscal/estadual/PR*/
  SELECT
      EMPPR.BDCREDPRESUMIDOPR, EMPPR.BDOPINTERNA, EMPPR.BDOPINTER12, EMPPR.BDOPINTER7, EMPPR.BDOPSP
  FROM
      VW_VEF_BASE_TEMPPARESTPR EMPPR
  WHERE EMPPR.BDCODEMP = :PRCODEMP AND
        EMPPR.BDREFEMP <= :PRREFSIS
  INTO :WBDCREDPRESUMIDO, :WOPINTERNA, :WOPINTER12, :WOPINTER7, :WOPSP;


  /*Faz as inserções do E113 antes do E111, pois o valor total do E111 será a soma dos valores do E113*/
  INSERT INTO TMP_VEF_EMP_TAJUICMSE113 (BDCODEMP, BDORDEME111220, BDORDEME113240, BDCODTER, BDCODPROD, BDNUMDOC, BDSERIE,
                                        BDSUBSERIE, BDVLRAJUSTE, BDDATAEMISAO, BDCHAVENFE, BDCODDOCFIS)
  SELECT
      MOV.BDCODEMP, :PRORDEME111 BDORDEME111220, GETORDEMSEQUENCIAL_STR(MOV.BDCODEMP || '.' || :PRORDEME111, :prCODEMP) BDORDEME113240, MOV.BDCODTER, MOV.BDCODPROD, MOV.BDNUMDOCINI, MOV.BDSERIE,
      MOV.BDSUBSERIE,
      CASE
        WHEN MOV.BDTPOPERACAO = 'INTERNA'  THEN CAST((MOV.BDBCICMS * :WOPINTERNA / 100)AS NUMERIC(15,2))
        WHEN MOV.BDTPOPERACAO = 'INTER_12' THEN CAST((MOV.BDBCICMS * :WOPINTER12 / 100)AS NUMERIC(15,2))
        WHEN MOV.BDTPOPERACAO = 'INTER_7'  THEN CAST((MOV.BDBCICMS * :WOPINTER7  / 100)AS NUMERIC(15,2))
        WHEN MOV.BDTPOPERACAO = 'SP'       THEN CAST((MOV.BDBCICMS * :WOPSP      / 100)AS NUMERIC(15,2))
    END BDVLRAJUSTE, MOV.BDDATAEMISSAO, MOV.BDCHAVENFE, MODE113.BDCODDOCFIS
  FROM
      (SELECT
           SAI.BDCODEMP, SAI.BDCHAVENFE, SAI.BDDATAEMISSAO, MODLAN.BDMODELOSTR, SAI.BDNUMDOCINI, SAI.BDSERIE, SAI.BDSUBSERIE, SAI.BDCODTER,
           PRO.BDCODPROD, PRO.BDALIQICMS,
           CASE
             WHEN   (SUBSTRING(ITEM.BDCODNAT FROM 1 FOR 1) = 5)                                                                                                       THEN 'INTERNA'
             WHEN (((SUBSTRING(ITEM.BDCODNAT FROM 1 FOR 1) = 6) OR (SUBSTRING(ITEM.BDCODNAT FROM 1 FOR 1) = 7)) AND (PRO.BDALIQICMS = 12) AND (NOT CID.BDCODUF = 26)) THEN 'INTER_12'
             WHEN (((SUBSTRING(ITEM.BDCODNAT FROM 1 FOR 1) = 6) OR (SUBSTRING(ITEM.BDCODNAT FROM 1 FOR 1) = 7)) AND (PRO.BDALIQICMS = 7)  AND (NOT CID.BDCODUF = 26)) THEN 'INTER_7'
             WHEN    (CID.BDCODUF = 26)                                                                                                                               THEN 'SP'
           END BDTPOPERACAO,
           SUM(PRO.BDBCICMS) BDBCICMS
       FROM
           VEF_EMP_TMOVSAI SAI
       JOIN
           VEF_EMP_TMOVSAIITENS ITEM ON (ITEM.BDCODEMP = SAI.BDCODEMP AND
           ITEM.BDCHAVE = SAI.BDCHAVE)
       JOIN
           VEF_EMP_TMOVPROSAI PRO ON (PRO.BDCODEMP = ITEM.BDCODEMP AND
           PRO.BDCHAVE = ITEM.BDCHAVE AND
           PRO.BDORDEM = ITEM.BDORDEM)
       LEFT JOIN
         TCIDADE CID ON (CID.BDCODCID = SAI.BDCODCID)
       LEFT OUTER JOIN
         VEF_BASE_TTABMODELOLAN MODLAN ON (MODLAN.BDMODELO = SAI.BDMODELO)
       WHERE SAI.BDCODEMP = :PRCODEMP AND
             SAI.BDREFLAN = :PRREFLAN AND
              (((SUBSTRING(ITEM.BDCODNAT FROM 1 FOR 1) = 5) AND (:WOPINTERNA > 0))                                                                                                        OR
              (((SUBSTRING(ITEM.BDCODNAT FROM 1 FOR 1) = 6) OR (SUBSTRING(ITEM.BDCODNAT FROM 1 FOR 1) = 7)) AND (PRO.BDALIQICMS = 12) AND (:WOPINTER12 > 0) AND (NOT CID.BDCODUF = 26))  OR
              (((SUBSTRING(ITEM.BDCODNAT FROM 1 FOR 1) = 6) OR (SUBSTRING(ITEM.BDCODNAT FROM 1 FOR 1) = 7)) AND (PRO.BDALIQICMS = 7)  AND (:WOPINTER7  > 0) AND (NOT CID.BDCODUF = 26))  OR
              ((CID.BDCODUF = 26) AND (:WOPSP > 0))) AND
              PRO.BDBCICMS > 0
       GROUP BY
           BDCODEMP, BDCHAVENFE, BDNUMDOCINI, BDCODTER, BDCODPROD, BDALIQICMS, BDTPOPERACAO, BDSERIE, BDSUBSERIE, BDDATAEMISSAO, BDMODELOSTR) MOV
  LEFT OUTER JOIN
    VEF_BASE_TTABDOCFIS MODE113 ON (MODE113.BDDOCFIS = MOV.BDMODELOSTR)
  WHERE :WBDCREDPRESUMIDO = 'TRUE';

  /*Insere os ajustes do E111*/
  INSERT INTO VEF_EMP_TAJUICMSE111 (BDCODEMP, BDORDEME111220, BDCODAJUICMS, BDREFERENCIA, BDDESCCOMP, BDVLRAJU, BDCODTIPO)
  SELECT
    E113.BDCODEMP, E113.BDORDEME111220, --2353 BDCODAJUICMS,
    IIF(SUBSTRING(E113.BDDATAEMISAO FROM 1 FOR 4) || SUBSTRING(E113.BDDATAEMISAO FROM 6 FOR 2) <= 202212, 2353,
        COALESCE((SELECT FIRST 1 bdCODAJUICMS FROM VEF_BASE_TTABAJUICMS WHERE BDCODAJUPAD = 'PR021056'), 2353) -- #215932 - Vai buscar o código novo, caso não encontre, vai levar o antigo...
        ) BDCODAJUICMS,
    SUBSTRING(E113.BDDATAEMISAO FROM 1 FOR 4) || SUBSTRING(E113.BDDATAEMISAO FROM 6 FOR 2) BDREFERENCIA,
    'Crédito presumido têxtil' BDDESCCOMP, CAST(SUM(E113.BDVLRAJUSTE) AS NUMERIC(15,2)) BDVLRAJU, 141 BDCODTIPO
  FROM
      TMP_VEF_EMP_TAJUICMSE113 E113
  WHERE E113.BDCODEMP = :PRCODEMP
  GROUP BY
      BDCODEMP, BDORDEME111220, BDCODAJUICMS, BDREFERENCIA, BDDESCCOMP, BDCODTIPO;

  /*Insere os ajustes do E113*/
  INSERT INTO VEF_EMP_TAJUICMSE113 (BDCODEMP, BDORDEME111220, BDORDEME113240, BDCODTER, BDCODPROD, BDNUMDOC, BDSERIE,
                                    BDSUBSERIE, BDVLRAJUSTE, BDDATAEMISAO, BDCHAVENFE, BDCODDOCFIS)
  SELECT
      E113.BDCODEMP, E113.BDORDEME111220, E113.BDORDEME113240, E113.BDCODTER, E113.BDCODPROD, E113.BDNUMDOC, E113.BDSERIE,
      E113.BDSUBSERIE, E113.BDVLRAJUSTE, E113.BDDATAEMISAO, E113.BDCHAVENFE, E113.BDCODDOCFIS
  FROM
      TMP_VEF_EMP_TAJUICMSE113 E113
  WHERE E113.BDCODEMP = :PRCODEMP;

  /*Insere os dados na TOL*/
  INSERT INTO TOL_VEF_EMP_TICMSSPEDGER_E111 (BDCODEMP, BDORDEME111220, BDCODPERIODO, BDREFERENCIA)
  SELECT
      :PRCODEMP BDCODEMP, E111.BDORDEME111220, :PRCODPERIODO BDCODPERIODO, :PRREFLAN BDREFERENCIA
  FROM
      VEF_EMP_TAJUICMSE111 E111
      left outer join VEF_BASE_TTABAJUICMS AJU on AJU.BDCODAJUICMS = E111.BDCODAJUICMS
  WHERE E111.BDCODEMP = :PRCODEMP AND
        E111.BDREFERENCIA = :PRREFLAN AND
        (E111.BDCODAJUICMS = 2353 or AJU.BDCODAJUPAD = 'PR021056') AND
        E111.BDCODTIPO = 141;

  /*Delete na tabela temporária E113*/
  DELETE FROM TMP_VEF_EMP_TAJUICMSE113;
END^

create or alter procedure SP_REMOVE_INDICE_SE_EXISTE (
    PRNOMEINDICE varchar(32) collate WIN_PTBR)
as
declare variable WEXISTE integer;
begin
   select count(*) existe from rdb$indices where rdb$index_name = :prnomeindice into :wExiste;

   if(wExiste > 0) then
      begin
         in autonomous transaction do
            begin
               execute statement 'drop index '||:prNomeIndice;
            end
      end


end^

CREATE OR ALTER TRIGGER VRH_BASE_TEXPBENEFICIO_PAR_BI0 FOR VRH_BASE_TEXPBENEFICIO_PAR
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wcod INTEGER;
begin
  if (coalesce(new.bditemchave, 0) = 0) then
     begin
       select coalesce(max(BDITEMCHAVE) + 1, 1) from VRH_BASE_TEXPBENEFICIO_PAR where BDCHAVE = new.bdchave into :wcod;
       new.bditemchave = :wcod;
     end
end
^

/* Restore proc. body: SP_UNION_FN_FT_MES_BASES */
create or alter procedure SP_UNION_FN_FT_MES_BASES (
    PREMP varchar(25000),
    PRCOL varchar(25000),
    PRREF integer,
    PRFILTROCC varchar(15000),
    PRPUXAFILIAIS smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDDATABAIXA date,
    BDBFGTS numeric(18,2),
    BDFGTS numeric(18,2),
    BDFGTSCS numeric(18,2),
    BDBFGTS13 numeric(18,2),
    BDFGTS13 numeric(18,2),
    BDFGTS13CS numeric(18,2),
    BDMAIORREM numeric(18,2),
    BDBINSS numeric(18,2),
    BDALIQINSS numeric(18,2),
    BDINSS numeric(18,2),
    BDBIRRF numeric(18,2),
    BDALIQIRRF numeric(18,2),
    BDIRRF numeric(18,2),
    BDBINSS13 numeric(18,2),
    BDALIQINSS13 numeric(18,2),
    BDINSS13 numeric(18,2),
    BDBIRRF13 numeric(18,2),
    BDALIQIRRF13 numeric(18,2),
    BDIRRF13 numeric(18,2),
    BDBSALFAM numeric(18,2),
    BDSALFAM numeric(18,2),
    BDBRAIS numeric(18,2),
    BDSALBASE numeric(18,2),
    BDDEP numeric(18,2),
    BDBINSSFEFOL numeric(18,2),
    BDINSSFEFOL numeric(18,2),
    BDALIQINSSFEFOL numeric(18,2),
    BDCREDITO numeric(18,2),
    BDDEBITO numeric(18,2),
    BDBFGTSFEFOL numeric(18,2),
    BDFGTSFEFOL numeric(18,2),
    BDBIRRFFE numeric(18,2),
    BDIRRFFE numeric(18,2),
    BDLIQUIDO numeric(18,2),
    BDDATAPGTO date,
    BDCODEMPREENDIMENTO integer)
as
declare variable WSQL varchar(30000);
declare variable WDEVEINCLUIRFN smallint;
begin
  wdeveincluirfn = 1;

  if (coalesce(prfiltrocc, '') <> '') then
     begin
       if ((position('(0,', :prfiltrocc) <= 0) and (position('(0)', :prfiltrocc)  <= 0)) then
          wdeveincluirfn = 0;
     end

  if (wdeveincluirfn = 1) then
     begin
       wsql = 'SELECT X.BDCODEMP,X.BDCODCOL,X.BDREFFN,X.BDDATABAIXAFN,X.BDBFGTSFN,X.BDFGTSFN,X.BDFGTSCSFN,X.BDBFGTS13FN,'||
                 'X.BDFGTS13FN,X.BDFGTS13CSFN,X.BDMAIORREMFN,X.BDBINSSFN,X.BDALIQINSSFN,X.BDINSSFN,X.BDBIRRFFN,X.BDALIQIRRFFN,X.BDIRRFFN,X.BDBINSS13FN,X.BDALIQINSS13FN,'||
                 'X.BDINSS13FN,X.BDBIRRF13FN,X.BDALIQIRRF13FN,X.BDIRRF13FN,X.BDBSALFAMFN,X.BDSALFAMFN,X.BDBRAISFN,X.BDSALBASEFN,X.BDDEPFN,X.BDBINSSFEFOLFN,X.BDINSSFEFOLFN,'||
                 'X.BDALIQINSSFEFOLFN,X.BDCREDITOFN,X.BDDEBITOFN,X.BDBFGTSFEFN,X.BDFGTSFEFN,X.BDBIRRFFEFN,X.BDIRRFFEFN,X.BDLIQUIDO,X.BDDATAPGTOFN '||
              'FROM VRHF_EMP_TFOLHANORMAL X ';

       if (coalesce(prpuxafiliais, 0) > 0) then
          wsql = wsql||'join TEMPRESAS E on (E.BDCODEMP = X.BDCODEMP) ';


       wsql = wsql||'WHERE X.BDREFFN = '||prref;
     
       if (coalesce(premp, '') <> '') then
          begin
            if (coalesce(prpuxafiliais, 0) > 0) then
               wsql = wsql||' and (('||replace(upper(premp), 'BDCODEMP', 'E.BDCODEMP')||') or ('||replace(upper(premp), 'BDCODEMP', 'E.BDCODMATRIZ')||')) ';
            else
               begin
                 wsql = wsql||' and '||replace(upper(premp), 'BDCODEMP', 'X.BDCODEMP');
                 if (coalesce(prcol, '') <> '') then
                    wsql = wsql||' and '||replace(upper(prcol), 'BDCODCOL', 'X.BDCODCOL');
               end
          end
     
       for execute statement :wsql into :BDCODEMP,:BDCODCOL,:BDREFFN,:BDDATABAIXA,:BDBFGTS,:BDFGTS,:BDFGTSCS,:BDBFGTS13,
           :BDFGTS13,:BDFGTS13CS,:BDMAIORREM,:BDBINSS,:BDALIQINSS,:BDINSS,:BDBIRRF,:BDALIQIRRF,:BDIRRF,:BDBINSS13,:BDALIQINSS13,
           :BDINSS13,:BDBIRRF13,:BDALIQIRRF13,:BDIRRF13,:BDBSALFAM,:BDSALFAM,:BDBRAIS,:BDSALBASE,:BDDEP,:BDBINSSFEFOL,:BDINSSFEFOL,
           :BDALIQINSSFEFOL,:BDCREDITO,:BDDEBITO,:BDBFGTSFEFOL,:BDFGTSFEFOL,:BDBIRRFFE,:BDIRRFFE,:BDLIQUIDO,:BDDATAPGTO
       do
         begin
           BDCODTPCC           = null;
           BDCODEMPREENDIMENTO = null;
           select first 1 BDCODCENTROS from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :BDREFFN order by BDREFEMP DESC into :BDCODCENTRO;
     
           suspend;
         end
    end

  wsql = 'SELECT X.BDCODEMP,X.BDCODCOL,X.BDREFTOMADOR,MAX(Y.BDCODCENTRO),MAX(Y.BDCODTPCC),MAX(X.BDDATABAIXAFT),SUM(X.BDBFGTSFT),SUM(X.BDFGTSFT),SUM(X.BDFGTSCSFT),'||
             'SUM(X.BDBFGTS13FT),SUM(X.BDFGTS13FT),SUM(X.BDFGTS13CSFT),MAX(X.BDMAIORREMFT),SUM(X.BDBINSSFT),MAX(X.BDALIQINSSFT),SUM(X.BDINSSFT),SUM(X.BDBIRRFFT),'||
             'MAX(X.BDALIQIRRFFT),SUM(X.BDIRRFFT),SUM(X.BDBINSS13FT),MAX(X.BDALIQINSS13FT),SUM(X.BDINSS13FT),SUM(X.BDBIRRF13FT),MAX(X.BDALIQIRRF13FT),'||
             'SUM(X.BDIRRF13FT),SUM(X.BDBSALFAMFT),SUM(X.BDSALFAMFT),SUM(X.BDBRAISFT),MAX(X.BDSALBASEFT),SUM(X.BDDEPFT),SUM(X.BDBINSSFEFOLFT),SUM(X.BDINSSFEFOLFT),'||
             'MAX(X.BDALIQINSSFEFOLFT),SUM(X.BDCREDITOFT),SUM(X.BDDEBITOFT),SUM(X.BDBFGTSFEFT),SUM(X.BDFGTSFEFT),SUM(X.BDBIRRFFEFT),SUM(X.BDIRRFFEFT),'||
             'SUM(X.bdliquido),MAX(X.BDDATAPGTOFT),MAX(Z.BDCODEMPREENDIMENTO) '||
         'FROM VRHF_EMP_TFOLHATOMADOR X ';

  if (coalesce(prpuxafiliais, 0) > 0) then
     wsql = wsql||'join TEMPRESAS E on (E.BDCODEMP = X.BDCODEMP) ';

  wsql = wsql||
         'JOIN VRHF_EMP_TPREPFN Y on (Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDORDEM = X.BDORDEM) '||
         'LEFT OUTER JOIN VEF_EMP_TCADEMPREENDIMENTO Z on (Z.BDCODEMP = X.BDCODEMP and Z.BDCODCENTRO = Y.BDCODCENTRO and Z.BDCODTPCC = Y.BDCODTPCC) ';


  wsql = wsql||'WHERE X.BDREFTOMADOR = '||prref;

  if (coalesce(premp, '') <> '') then
     begin
       if (coalesce(prpuxafiliais, 0) > 0) then
          wsql = wsql||' and (('||replace(upper(premp), 'BDCODEMP', 'E.BDCODEMP')||') or ('||replace(upper(premp), 'BDCODEMP', 'E.BDCODMATRIZ')||')) ';
       else
          begin
            wsql = wsql||' and '||replace(upper(premp), 'BDCODEMP', 'X.BDCODEMP');
     
            if (coalesce(prcol, '') <> '') then
               wsql = wsql||' and '||replace(upper(prcol), 'BDCODCOL', 'X.BDCODCOL');
          end
     end

  if (coalesce(prfiltrocc, '') <> '') then
     begin
       wsql = wsql||' and '||replace(upper(:prfiltrocc), 'BDCODTPCC', 'coalesce(Y.BDCODTPCC, 0)');

     end

  wsql = wsql||'GROUP BY X.BDCODEMP,X.BDCODCOL,X.BDREFTOMADOR ';

  for execute statement :wsql into :BDCODEMP,:BDCODCOL,:BDREFFN,:BDCODCENTRO,:BDCODTPCC,:BDDATABAIXA,:BDBFGTS,:BDFGTS,:BDFGTSCS,:BDBFGTS13,
      :BDFGTS13,:BDFGTS13CS,:BDMAIORREM,:BDBINSS,:BDALIQINSS,:BDINSS,:BDBIRRF,:BDALIQIRRF,:BDIRRF,:BDBINSS13,:BDALIQINSS13,
      :BDINSS13,:BDBIRRF13,:BDALIQIRRF13,:BDIRRF13,:BDBSALFAM,:BDSALFAM,:BDBRAIS,:BDSALBASE,:BDDEP,:BDBINSSFEFOL,:BDINSSFEFOL,
      :BDALIQINSSFEFOL,:BDCREDITO,:BDDEBITO,:BDBFGTSFEFOL,:BDFGTSFEFOL,:BDBIRRFFE,:BDIRRFFE,:BDLIQUIDO,:BDDATAPGTO,:BDCODEMPREENDIMENTO
  do
    suspend;
end^

create or alter procedure SP_UNION_FC_FCT_MES_BASES (
    PREMP varchar(25000),
    PRCOL varchar(25000),
    PRREF integer,
    PRDATAPAGFC date,
    PRFILTROCC varchar(15000),
    PRPUXAFILIAIS smallint,
    PRFILTROSITCOL integer = -1,
    PRREFFILTRO integer = 0,
    PRCODADC integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFFC integer,
    BDREFCOMP integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDDATABAIXA date,
    BDBFGTS numeric(18,2),
    BDFGTS numeric(18,2),
    BDFGTSCS numeric(18,2),
    BDBFGTS13 numeric(18,2),
    BDFGTS13 numeric(18,2),
    BDFGTS13CS numeric(18,2),
    BDMAIORREM numeric(18,2),
    BDBINSS numeric(18,2),
    BDALIQINSS numeric(18,2),
    BDINSS numeric(18,2),
    BDBIRRF numeric(18,2),
    BDALIQIRRF numeric(18,2),
    BDIRRF numeric(18,2),
    BDBINSS13 numeric(18,2),
    BDALIQINSS13 numeric(18,2),
    BDINSS13 numeric(18,2),
    BDBIRRF13 numeric(18,2),
    BDALIQIRRF13 numeric(18,2),
    BDIRRF13 numeric(18,2),
    BDBSALFAM numeric(18,2),
    BDSALFAM numeric(18,2),
    BDBRAIS numeric(18,2),
    BDSALBASE numeric(18,2),
    BDDEP numeric(18,2),
    BDBINSSFEFOL numeric(18,2),
    BDINSSFEFOL numeric(18,2),
    BDALIQINSSFEFOL numeric(18,2),
    BDCREDITO numeric(18,2),
    BDDEBITO numeric(18,2),
    BDBFGTSFEFOL numeric(18,2),
    BDFGTSFEFOL numeric(18,2),
    BDLIQUIDO numeric(18,2),
    BDCODEMPREENDIMENTO integer,
    BDDATAPAGFC date)
as
declare variable WSQL varchar(30000);
declare variable WDEVEINCLUIRFC smallint;
declare variable WFILTROSITCOLFN varchar(300);
declare variable WFILTROSITCOLFT varchar(300);
declare variable WJOINFITROSITCOLFN varchar(300);
declare variable WJOINFITROSITCOLFT varchar(300);
declare variable WDATAINI date;
declare variable WDATAFIM date;
declare variable WULTDIA integer;
begin
  wdeveincluirfc = 1;

  WFILTROSITCOLFN = '';
  WFILTROSITCOLFT = '';
  WJOINFITROSITCOLFN = '';
  WJOINFITROSITCOLFT = '';

  if ((coalesce(PRFILTROSITCOL,-1) <> -1) and (prreffiltro > 0)) then
     begin
       wdataini = cast(substring(:prreffiltro from 1 for 4)||'-'||substring(:prreffiltro from 5 for 2)||'-01' as date);
       select ultdia from ULTIMO_DIA_MES(cast(substring(:prreffiltro from 5 for 2) as smallint),cast(substring(:prreffiltro from 1 for 4) as integer)) into :wultdia;
       wdatafim = cast(substring(:prreffiltro from 1 for 4)||'-'||substring(:prreffiltro from 5 for 2)||'-'||wultdia as date);

       if (prfiltrositcol = 0) then   --tcSomenteAtivos :
          WFILTROSITCOLFN = ' SP_SOMENTE_ATIVOS('||''''||wdataini||''''||', '||''''||wdatafim||''''||') ';
       else if (prfiltrositcol = 2) then --  tcSomenteDemitidos:
          WFILTROSITCOLFN = ' SP_SOMENTE_DEMITIDOS('||''''||wdatafim||''''||') ';
       else if (prfiltrositcol = 3) then --   tcSomenteAdmMes:
          WFILTROSITCOLFN = ' SP_SOMENTE_ADMITIDOS_MES('||''''||wdataini||''''||', '||''''||wdatafim||''''||') ';
       else if (prfiltrositcol = 4) then --      tcSomenteDemMes:
          WFILTROSITCOLFN = ' SP_SOMENTE_DEMITIDOS_MES('||''''||wdataini||''''||', '||''''||wdatafim||''''||') ';
       else if (prfiltrositcol = 5) then --      tcAtivosSemDemitidosMes:
          WFILTROSITCOLFN = ' SP_ATIVOS_SEM_DEMITIDOS_MES('||''''||wdataini||''''||', '||''''||wdatafim||''''||') ';
       else if (prfiltrositcol = 6) then --      tcAtivosSemDemComTransf:
           WFILTROSITCOLFN= ' SP_ATI_SEM_DEM_COM_TRANSF('||''''||wdataini||''''||', '||''''||wdatafim||''''||') ';
       else if (prfiltrositcol = 7) then --      tcAtivosSemAfastMesInteiro:
           WFILTROSITCOLFN= ' SP_ATI_SEM_AFAST_MES_INT('||''''||wdataini||''''||', '||''''||wdatafim||''''||') ';
       else if (prfiltrositcol = 8) then --      tcAfastadosMesInteiro:
           WFILTROSITCOLFN= ' SP_AFASTADOS_MES_INTEIRO('||''''||wdataini||''''||', '||''''||wdatafim||''''||') ';

       if (WFILTROSITCOLFN <> '') then
          begin
            WFILTROSITCOLFN = WFILTROSITCOLFN||' filtro join ';
            WFILTROSITCOLFT = WFILTROSITCOLFN;
            WJOINFITROSITCOLFN = ' on (FILTRO.BDCODEMP = x.BDCODEMP and  FILTRO.BDCODCOL = x.BDCODCOL) ';
            WJOINFITROSITCOLFT = WJOINFITROSITCOLFN;
          end
     end

  if (coalesce(prfiltrocc, '') <> '') then
     begin
       if ((position('(0,', :prfiltrocc) <= 0) and (position('(0)', :prfiltrocc)  <= 0)) then
          wdeveincluirfc = 0;
     end

  if (wdeveincluirfc = 1) then
     begin
       wsql = 'SELECT X.BDCODEMP, X.BDCODCOL, X.BDREFFN, X.BDREFFC, X.BDREFCOMP, X.BDDATABAIXAFC, X.BDBFGTSFC, X.BDFGTSFC,' ||
              '       X.BDFGTSCSFC, X.BDBFGTS13FC, X.BDFGTS13FC, X.BDFGTS13CSFC, X.BDMAIORREMFC, X.BDBINSSFC, X.BDALIQINSSFC,' ||
              '       X.BDINSSFC, X.BDBIRRFFC, X.BDALIQIRRFFC, X.BDIRRFFC, X.BDBINSS13FC, X.BDALIQINSS13FC, X.BDINSS13FC,' ||
              '       X.BDBIRRF13FC, X.BDALIQIRRF13FC, X.BDIRRF13FC, X.BDBSALFAMFC, X.BDSALFAMFC, X.BDBRAISFC, X.BDSALBASEFC,' ||
              '       X.BDDEPFC, X.BDBINSSFEFOLFC, X.BDINSSFEFOLFC, X.BDALIQINSSFEFOLFC, X.BDCREDITOFC, X.BDDEBITOFC, X.BDBFGTSFEFC,' ||
              '       X.BDFGTSFEFC, X.BDLIQUIDO, X.BDDATAPAGFC '||
              'FROM '||WFILTROSITCOLFN||' VRHF_EMP_TFOLHACOMP X '||WJOINFITROSITCOLFN||' ';

       if (coalesce(prpuxafiliais, 0) > 0) then
          wsql = wsql||'join TEMPRESAS E on (E.BDCODEMP = X.BDCODEMP) ';


       if (PRCODADC <> 0) then
          begin
                wsql = wsql||'WHERE X.bdcodacconv = '||PRCODADC;
          end
       else
          begin
       wsql = wsql||'WHERE X.BDREFFN = '||prref||' AND '||
                    '      X.BDDATAPAGFC = '||''''||prdatapagfc||''' AND '||
                    '     (COALESCE(X.BDREFVINCFN,0) = 0) ';
          end


       if (coalesce(premp, '') <> '') then
          begin
            if (coalesce(prpuxafiliais, 0) > 0) then
               wsql = wsql||' and (('||replace(upper(premp), 'BDCODEMP', 'E.BDCODEMP')||') or ('||replace(upper(premp), 'BDCODEMP', 'E.BDCODMATRIZ')||')) ';
            else
               begin
                 wsql = wsql||' and '||replace(upper(premp), 'BDCODEMP', 'X.BDCODEMP');
                 if (coalesce(prcol, '') <> '') then
                    wsql = wsql||' and '||replace(upper(prcol), 'BDCODCOL', 'X.BDCODCOL');
               end
          end
     
       for execute statement :wsql into :BDCODEMP, :BDCODCOL, :BDREFFN, :BDREFFC, :BDREFCOMP, :BDDATABAIXA, :BDBFGTS, :BDFGTS, :BDFGTSCS,
           :BDBFGTS13, :BDFGTS13, :BDFGTS13CS, :BDMAIORREM, :BDBINSS, :BDALIQINSS, :BDINSS, :BDBIRRF, :BDALIQIRRF, :BDIRRF, :BDBINSS13,
           :BDALIQINSS13, :BDINSS13, :BDBIRRF13, :BDALIQIRRF13, :BDIRRF13, :BDBSALFAM, :BDSALFAM, :BDBRAIS, :BDSALBASE, :BDDEP,
           :BDBINSSFEFOL, :BDINSSFEFOL, :BDALIQINSSFEFOL, :BDCREDITO, :BDDEBITO, :BDBFGTSFEFOL, :BDFGTSFEFOL, :BDLIQUIDO, :BDDATAPAGFC
       do
         begin
           BDCODTPCC           = null;
           BDCODEMPREENDIMENTO = null;
           select first 1 BDCODCENTROS from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :BDREFFN order by BDREFEMP DESC into :BDCODCENTRO;
     
           suspend;
         end
    end

  wsql = 'SELECT X.BDCODEMP, X.BDCODCOL, X.BDREFTOMADOR, X.BDREFFC, X.BDREFCOMP, MAX(Y.BDCODCENTRO), MAX(Y.BDCODTPCC),'||
         '       MAX(X.BDDATABAIXAFC), SUM(X.BDBFGTSFC), SUM(X.BDFGTSFC), SUM(X.BDFGTSCSFC), SUM(X.BDBFGTS13FC),'||
         '       SUM(X.BDFGTS13FC), SUM(X.BDFGTS13CSFC), MAX(X.BDMAIORREMFC), SUM(X.BDBINSSFC), MAX(X.BDALIQINSSFC),'||
         '       SUM(X.BDINSSFC), SUM(X.BDBIRRFFC), MAX(X.BDALIQIRRFFC), SUM(X.BDIRRFFC), SUM(X.BDBINSS13FC),'||
         '       MAX(X.BDALIQINSS13FC), SUM(X.BDINSS13FC), SUM(X.BDBIRRF13FC), MAX(X.BDALIQIRRF13FC), SUM(X.BDIRRF13FC),'||
         '       SUM(X.BDBSALFAMFC), SUM(X.BDSALFAMFC), SUM(X.BDBRAISFC), MAX(X.BDSALBASEFC), MAX(X.BDDEPFC),'||
         '       SUM(X.BDBINSSFEFOLFC), SUM(X.BDINSSFEFOLFC), MAX(X.BDALIQINSSFEFOLFC), SUM(X.BDCREDITOFC), SUM(X.BDDEBITOFC),'||
         '       SUM(X.BDBFGTSFEFC), SUM(X.BDFGTSFEFC), SUM(X.BDLIQUIDO), MAX(Z.BDCODEMPREENDIMENTO), X.BDDATAPAGFC '||
         'FROM '||wfiltrositcolft||' VRHF_EMP_TFOLTOMCOMP X '||WJOINFITROSITCOLFT||' ';

  if (coalesce(prpuxafiliais, 0) > 0) then
     wsql = wsql||'join TEMPRESAS E on (E.BDCODEMP = X.BDCODEMP) ';

  wsql = wsql||
         'JOIN VRHF_EMP_TPREPFN Y on (Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDORDEM = X.BDORDEM) '||
         'LEFT OUTER JOIN VEF_EMP_TCADEMPREENDIMENTO Z on (Z.BDCODEMP = X.BDCODEMP and Z.BDCODCENTRO = Y.BDCODCENTRO and Z.BDCODTPCC = Y.BDCODTPCC) ';

         if (PRCODADC <> 0) then
          begin
                wsql = wsql||'WHERE X.bdcodacconv = '||PRCODADC;
          end
       else
          begin
  wsql = wsql||'WHERE X.BDREFTOMADOR = '||prref||' AND '||
               '      X.BDDATAPAGFC = '||''''||prdatapagfc||''' AND '||
               '     (COALESCE(X.BDREFVINCFN,0) = 0) ';
          end

  if (coalesce(premp, '') <> '') then
     begin
       if (coalesce(prpuxafiliais, 0) > 0) then
          wsql = wsql||' and (('||replace(upper(premp), 'BDCODEMP', 'E.BDCODEMP')||') or ('||replace(upper(premp), 'BDCODEMP', 'E.BDCODMATRIZ')||')) ';
       else
          begin
            wsql = wsql||' and '||replace(upper(premp), 'BDCODEMP', 'X.BDCODEMP');
     
            if (coalesce(prcol, '') <> '') then
               wsql = wsql||' and '||replace(upper(prcol), 'BDCODCOL', 'X.BDCODCOL');
          end
     end

  if (coalesce(prfiltrocc, '') <> '') then
     begin
       wsql = wsql||' and '||replace(upper(:prfiltrocc), 'BDCODTPCC', 'coalesce(Y.BDCODTPCC, 0)');

     end

  wsql = wsql||'GROUP BY X.BDCODEMP, X.BDCODCOL, X.BDREFTOMADOR, X.BDREFFC, X.BDREFCOMP, x.BDDATAPAGFC, X.BDREFVINCFN ';

  for execute statement :wsql into :BDCODEMP, :BDCODCOL, :BDREFFN, :BDREFFC, :BDREFCOMP, :BDCODCENTRO, :BDCODTPCC, :BDDATABAIXA, :BDBFGTS, :BDFGTS, :BDFGTSCS,
      :BDBFGTS13, :BDFGTS13, :BDFGTS13CS, :BDMAIORREM, :BDBINSS, :BDALIQINSS, :BDINSS, :BDBIRRF, :BDALIQIRRF, :BDIRRF, :BDBINSS13,
      :BDALIQINSS13, :BDINSS13, :BDBIRRF13, :BDALIQIRRF13, :BDIRRF13, :BDBSALFAM, :BDSALFAM, :BDBRAIS, :BDSALBASE, :BDDEP,
      :BDBINSSFEFOL, :BDINSSFEFOL, :BDALIQINSSFEFOL, :BDCREDITO, :BDDEBITO, :BDBFGTSFEFOL, :BDFGTSFEFOL, :BDLIQUIDO,
      :BDCODEMPREENDIMENTO, :BDDATAPAGFC
  do
    suspend;
end^

create or alter procedure SP_UNION_FI_FTI_MES_BASES (
    PREMP varchar(25000),
    PRCOL varchar(25000),
    PRREF integer,
    PRDATAPGTO date,
    PRFILTROCC varchar(15000),
    PRPUXAFILIAIS integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODCONTTI integer,
    BDREFFN integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDDATABAIXA date,
    BDBFGTS numeric(18,2),
    BDFGTS numeric(18,2),
    BDFGTSCS numeric(18,2),
    BDBFGTS13 numeric(18,2),
    BDFGTS13 numeric(18,2),
    BDFGTS13CS numeric(18,2),
    BDMAIORREM numeric(18,2),
    BDBINSS numeric(18,2),
    BDALIQINSS numeric(18,2),
    BDINSS numeric(18,2),
    BDBIRRF numeric(18,2),
    BDALIQIRRF numeric(18,2),
    BDIRRF numeric(18,2),
    BDBINSS13 numeric(18,2),
    BDALIQINSS13 numeric(18,2),
    BDINSS13 numeric(18,2),
    BDBIRRF13 numeric(18,2),
    BDALIQIRRF13 numeric(18,2),
    BDIRRF13 numeric(18,2),
    BDBSALFAM numeric(18,2),
    BDSALFAM numeric(18,2),
    BDBRAIS numeric(18,2),
    BDSALBASE numeric(18,2),
    BDDEP numeric(18,2),
    BDBINSSFEFOL numeric(18,2),
    BDINSSFEFOL numeric(18,2),
    BDALIQINSSFEFOL numeric(18,2),
    BDCREDITO numeric(18,2),
    BDDEBITO numeric(18,2),
    BDBFGTSFEFOL numeric(18,2),
    BDFGTSFEFOL numeric(18,2),
    BDBIRRFFE numeric(18,2),
    BDIRRFFE numeric(18,2),
    BDLIQUIDO numeric(18,2),
    BDDATAPGTO date)
as
declare variable WSQL varchar(30000);
declare variable WDEVEINCLUIRFI integer;
begin
  wdeveincluirfi = 1;

  if (coalesce(prfiltrocc, '') <> '') then
     begin
       if ((position('(0,', :prfiltrocc) <= 0) and (position('(0)', :prfiltrocc)  <= 0)) then
          wdeveincluirfi = 0;
     end

  if (wdeveincluirfi = 1) then
     begin
       wsql = 'SELECT X.BDCODEMP, X.BDCODCOL, X.BDCODCONTTI, X.BDREFFN, MAX(X.BDDATABAIXAFN) BDDATABAIXAFN, SUM(X.BDBFGTSFN) BDBFGTSFN,'||
              '       SUM(X.BDFGTSFN) BDFGTSFN, SUM(X.BDFGTSCSFN) BDFGTSCSFN, SUM(X.BDBFGTS13FN) BDBFGTS13FN, SUM(X.BDFGTS13FN) BDFGTS13FN,'||
              '       SUM(X.BDFGTS13CSFN) BDFGTS13CSFN, SUM(X.BDMAIORREMFN) BDMAIORREMFN, SUM(X.BDBINSSFN) BDBINSSFN,'||
              '       MAX(X.BDALIQINSSFN) BDALIQINSSFN, SUM(X.BDINSSFN) BDINSSFN, SUM(X.BDBIRRFFN) BDBIRRFFN, MAX(X.BDALIQIRRFFN) BDALIQIRRFFN,'||
              '       SUM(X.BDIRRFFN) BDIRRFFN, SUM(X.BDBINSS13FN) BDBINSS13FN, MAX(X.BDALIQINSS13FN) BDALIQINSS13FN,'||
              '       SUM(X.BDINSS13FN) BDINSS13FN, SUM(X.BDBIRRF13FN) BDBIRRF13FN, MAX(X.BDALIQIRRF13FN) BDALIQIRRF13FN,'||
              '       SUM(X.BDIRRF13FN) BDIRRF13FN, SUM(X.BDBSALFAMFN) BDBSALFAMFN, SUM(X.BDSALFAMFN) BDSALFAMFN, SUM(X.BDBRAISFN) BDBRAISFN,'||
              '       MAX(X.BDSALBASEFN) BDSALBASEFN, MAX(X.BDDEPFN) BDDEPFN, SUM(X.BDBINSSFEFOLFN) BDBINSSFEFOLFN,'||
              '       SUM(X.BDINSSFEFOLFN) BDINSSFEFOLFN, MAX(X.BDALIQINSSFEFOLFN) BDALIQINSSFEFOLFN, SUM(X.BDCREDITOFN) BDCREDITOFN,'||
              '       SUM(X.BDDEBITOFN) BDDEBITOFN, SUM(X.BDBFGTSFEFN) BDBFGTSFEFN, SUM(X.BDFGTSFEFN) BDFGTSFEFN,'||
              '       SUM(X.BDBIRRFFEFN) BDBIRRFFEFN, SUM(X.BDIRRFFEFN) BDIRRFFEFN, SUM(X.BDLIQUIDO) BDLIQUIDO,'||
              '       MAX(X.BDDATAPGTOFN) BDDATAPGTOFN '||
              'FROM VRHF_EMP_TFOLHAINT X ';

       if (coalesce(prpuxafiliais, 0) > 0) then
          wsql = wsql||'join TEMPRESAS E on (E.BDCODEMP = X.BDCODEMP) ';


       wsql = wsql||'WHERE X.BDREFFN = '||prref||' AND '||
                    '      X.BDDATAPGTOFN = '||''''||PRDATAPGTO||'''';
     
       if (coalesce(premp, '') <> '') then
          begin
            if (coalesce(prpuxafiliais, 0) > 0) then
               wsql = wsql||' and (('||replace(upper(premp), 'BDCODEMP', 'E.BDCODEMP')||') or ('||replace(upper(premp), 'BDCODEMP', 'E.BDCODMATRIZ')||')) ';
            else
               begin
                 wsql = wsql||' and '||replace(upper(premp), 'BDCODEMP', 'X.BDCODEMP');
                 if (coalesce(prcol, '') <> '') then
                    wsql = wsql||' and '||replace(upper(prcol), 'BDCODCOL', 'X.BDCODCOL');
               end
          end

       wsql = wsql||'GROUP BY X.BDCODEMP, X.BDCODCOL, X.BDCODCONTTI, X.BDREFFN ';
     
       for execute statement :wsql into :BDCODEMP, :BDCODCOL, :BDCODCONTTI, :BDREFFN, :BDDATABAIXA, :BDBFGTS, :BDFGTS, :BDFGTSCS, :BDBFGTS13, :BDFGTS13,
       :BDFGTS13CS, :BDMAIORREM, :BDBINSS, :BDALIQINSS, :BDINSS, :BDBIRRF, :BDALIQIRRF, :BDIRRF, :BDBINSS13, :BDALIQINSS13,
       :BDINSS13, :BDBIRRF13, :BDALIQIRRF13, :BDIRRF13, :BDBSALFAM, :BDSALFAM, :BDBRAIS, :BDSALBASE, :BDDEP, :BDBINSSFEFOL,
       :BDINSSFEFOL, :BDALIQINSSFEFOL, :BDCREDITO, :BDDEBITO, :BDBFGTSFEFOL, :BDFGTSFEFOL, :BDBIRRFFE, :BDIRRFFE, :BDLIQUIDO, :BDDATAPGTO
       do
         begin
           BDCODTPCC           = null;
           select first 1 BDCODCENTROS from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :BDREFFN order by BDREFEMP DESC into :BDCODCENTRO;
     
           suspend;
         end
    end

  wsql = 'SELECT X.BDCODEMP, X.BDCODCOL, X.BDCODCONTTI, X.BDREFTOMADOR, MAX(Y.BDCODCENTRO), MAX(Y.BDCODTPCC),'||
         '       MAX(X.BDDATABAIXAFT), SUM(X.BDBFGTSFT), SUM(X.BDFGTSFT), SUM(X.BDFGTSCSFT), SUM(X.BDBFGTS13FT),'||
         '       SUM(X.BDFGTS13FT), SUM(X.BDFGTS13CSFT), MAX(X.BDMAIORREMFT), SUM(X.BDBINSSFT), MAX(X.BDALIQINSSFT),'||
         '       SUM(X.BDINSSFT), SUM(X.BDBIRRFFT), MAX(X.BDALIQIRRFFT), SUM(X.BDIRRFFT), SUM(X.BDBINSS13FT),'||
         '       MAX(X.BDALIQINSS13FT), SUM(X.BDINSS13FT), SUM(X.BDBIRRF13FT), MAX(X.BDALIQIRRF13FT), SUM(X.BDIRRF13FT),'||
         '       SUM(X.BDBSALFAMFT), SUM(X.BDSALFAMFT), SUM(X.BDBRAISFT), MAX(X.BDSALBASEFT), SUM(X.BDDEPFT),'||
         '       SUM(X.BDBINSSFEFOLFT), SUM(X.BDINSSFEFOLFT), MAX(X.BDALIQINSSFEFOLFT), SUM(X.BDCREDITOFT), SUM(X.BDDEBITOFT),'||
         '       SUM(X.BDBFGTSFEFT), SUM(X.BDFGTSFEFT), SUM(X.BDBIRRFFEFT), SUM(X.BDIRRFFEFT), SUM(X.BDLIQUIDO),'||
         '       MAX(X.BDDATAPGTOFT) '||
         'FROM VRHF_EMP_TFOLHATOMINT X ';

  if (coalesce(prpuxafiliais, 0) > 0) then
     wsql = wsql||'join TEMPRESAS E on (E.BDCODEMP = X.BDCODEMP) ';

  wsql = wsql||
         'JOIN VRHF_EMP_TPREPFN Y on (Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDORDEM = X.BDORDEM) ';

  wsql = wsql||'WHERE X.BDREFTOMADOR = '||prref||' AND '||
               '      X.BDDATAPGTOFT = '||''''||PRDATAPGTO||'''';

  if (coalesce(premp, '') <> '') then
     begin
       if (coalesce(prpuxafiliais, 0) > 0) then
          wsql = wsql||' and (('||replace(upper(premp), 'BDCODEMP', 'E.BDCODEMP')||') or ('||replace(upper(premp), 'BDCODEMP', 'E.BDCODMATRIZ')||')) ';
       else
          begin
            wsql = wsql||' and '||replace(upper(premp), 'BDCODEMP', 'X.BDCODEMP');
     
            if (coalesce(prcol, '') <> '') then
               wsql = wsql||' and '||replace(upper(prcol), 'BDCODCOL', 'X.BDCODCOL');
          end
     end

  if (coalesce(prfiltrocc, '') <> '') then
     begin
       wsql = wsql||' and '||replace(upper(:prfiltrocc), 'BDCODTPCC', 'coalesce(Y.BDCODTPCC, 0)');

     end

  wsql = wsql||'GROUP BY X.BDCODEMP, X.BDCODCOL, X.BDCODCONTTI, X.BDREFTOMADOR';

  for execute statement :wsql into :BDCODEMP, :BDCODCOL, :BDCODCONTTI, :BDREFFN, :BDCODCENTRO, :BDCODTPCC, :BDDATABAIXA, :BDBFGTS, :BDFGTS, :BDFGTSCS,
       :BDBFGTS13, :BDFGTS13, :BDFGTS13CS, :BDMAIORREM, :BDBINSS, :BDALIQINSS, :BDINSS, :BDBIRRF, :BDALIQIRRF, :BDIRRF, :BDBINSS13,
       :BDALIQINSS13, :BDINSS13, :BDBIRRF13, :BDALIQIRRF13, :BDIRRF13, :BDBSALFAM, :BDSALFAM, :BDBRAIS, :BDSALBASE, :BDDEP,
       :BDBINSSFEFOL, :BDINSSFEFOL, :BDALIQINSSFEFOL, :BDCREDITO, :BDDEBITO, :BDBFGTSFEFOL, :BDFGTSFEFOL, :BDBIRRFFE, :BDIRRFFE,
       :BDLIQUIDO, :BDDATAPGTO
  do
    suspend;
end^

create or alter procedure SP_UNION_FCI_FCTI_MESFN_BASES (
    PREMP varchar(25000),
    PRCOL varchar(25000),
    PRREF integer,
    PRDATAPAGFC date,
    PRFILTROCC varchar(15000),
    PRPUXAFILIAIS smallint)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFFN integer,
    BDREFFC integer,
    BDCODCONTTI integer,
    BDDATAGRRFFC date,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDDATABAIXA date,
    BDBFGTS numeric(18,2),
    BDFGTS numeric(18,2),
    BDFGTSCS numeric(18,2),
    BDBFGTS13 numeric(18,2),
    BDFGTS13 numeric(18,2),
    BDFGTS13CS numeric(18,2),
    BDMAIORREM numeric(18,2),
    BDBINSS numeric(18,2),
    BDALIQINSS numeric(18,2),
    BDINSS numeric(18,2),
    BDBIRRF numeric(18,2),
    BDALIQIRRF numeric(18,2),
    BDIRRF numeric(18,2),
    BDBINSS13 numeric(18,2),
    BDALIQINSS13 numeric(18,2),
    BDINSS13 numeric(18,2),
    BDBIRRF13 numeric(18,2),
    BDALIQIRRF13 numeric(18,2),
    BDIRRF13 numeric(18,2),
    BDBSALFAM numeric(18,2),
    BDSALFAM numeric(18,2),
    BDBRAIS numeric(18,2),
    BDSALBASE numeric(18,2),
    BDDEP numeric(18,2),
    BDBINSSFEFOL numeric(18,2),
    BDINSSFEFOL numeric(18,2),
    BDALIQINSSFEFOL numeric(18,2),
    BDCREDITO numeric(18,2),
    BDDEBITO numeric(18,2),
    BDBFGTSFEFOL numeric(18,2),
    BDFGTSFEFOL numeric(18,2),
    BDCODTIPOFC integer,
    BDBIRRFFE numeric(18,2),
    BDIRRFFE numeric(18,2),
    BDLIQUIDO numeric(18,2),
    BDBIRRFFEFOL numeric(18,2),
    BDIRRFFEFOL numeric(18,2),
    BDCODACCONV integer,
    BDDATAPAGFC date)
as
declare variable WSQL varchar(30000);
declare variable WDEVEINCLUIRFC integer;
begin
  wdeveincluirfc = 1;

  if (coalesce(prfiltrocc, '') <> '') then
     begin
       if ((position('(0,', :prfiltrocc) <= 0) and (position('(0)', :prfiltrocc)  <= 0)) then
          wdeveincluirfc = 0;
     end

  if (wdeveincluirfc = 1) then
     begin
       wsql = 'SELECT X.BDCODEMP, X.BDCODCOL, X.BDREFFN, X.BDREFFC, X.BDCODCONTTI, X.BDDATAGRRFFC, MAX(X.BDDATABAIXAFC), SUM(X.BDBFGTSFC),'||
              '       SUM(X.BDFGTSFC), SUM(X.BDFGTSCSFC), SUM(X.BDBFGTS13FC), SUM(X.BDFGTS13FC), SUM(X.BDFGTS13CSFC), MAX(X.BDMAIORREMFC),'||
              '       SUM(X.BDBINSSFC), MAX(X.BDALIQINSSFC), SUM(X.BDINSSFC), SUM(X.BDBIRRFFC), MAX(X.BDALIQIRRFFC), SUM(X.BDIRRFFC),'||
              '       SUM(X.BDBINSS13FC), MAX(X.BDALIQINSS13FC), SUM(X.BDINSS13FC), SUM(X.BDBIRRF13FC), MAX(X.BDALIQIRRF13FC), SUM(X.BDIRRF13FC),'||
              '       SUM(X.BDBSALFAMFC), SUM(X.BDSALFAMFC), SUM(X.BDBRAISFC), MAX(X.BDSALBASEFC), MAX(X.BDDEPFC), SUM(X.BDBINSSFEFOLFC),'||
              '       SUM(X.BDINSSFEFOLFC), MAX(X.BDALIQINSSFEFOLFC), SUM(X.BDCREDITOFC), SUM(X.BDDEBITOFC), SUM(X.BDBFGTSFEFC), SUM(X.BDFGTSFEFC),'||
              '       COALESCE(MAX(X.BDCODTIPOFC), 1), SUM(X.BDBIRRFFEFC), SUM(X.BDIRRFFEFC), SUM(X.BDLIQUIDO), SUM(X.BDBIRRFFEFC),'||
              '       SUM(X.BDIRRFFEFC), MAX(X.BDCODACCONV), X.BDDATAPAGFC '||
              'FROM VRHF_EMP_TFOLHACOMPINT X ';

       if (coalesce(prpuxafiliais, 0) > 0) then
          wsql = wsql||'join TEMPRESAS E on (E.BDCODEMP = X.BDCODEMP) ';


       wsql = wsql||'WHERE X.BDREFFN = '||prref||' AND '||
                    '      X.BDDATAPAGFC = '||''''||prdatapagfc||'''';
     
       if (coalesce(premp, '') <> '') then
          begin
            if (coalesce(prpuxafiliais, 0) > 0) then
               wsql = wsql||' and (('||replace(upper(premp), 'BDCODEMP', 'E.BDCODEMP')||') or ('||replace(upper(premp), 'BDCODEMP', 'E.BDCODMATRIZ')||')) ';
            else
               begin
                 wsql = wsql||' and '||replace(upper(premp), 'BDCODEMP', 'X.BDCODEMP');
                 if (coalesce(prcol, '') <> '') then
                    wsql = wsql||' and '||replace(upper(prcol), 'BDCODCOL', 'X.BDCODCOL');
               end
          end

       wsql = wsql||'GROUP BY X.BDCODEMP, X.BDCODCOL, X.BDREFFN, X.BDREFFC, X.BDCODCONTTI, X.BDDATAGRRFFC, X.BDDATAPAGFC ';
     
       for execute statement :wsql into :BDCODEMP, :BDCODCOL, :BDREFFN, :BDREFFC, :BDCODCONTTI, :BDDATAGRRFFC, :BDDATABAIXA, :BDBFGTS, :BDFGTS, :BDFGTSCS,
           :BDBFGTS13, :BDFGTS13, :BDFGTS13CS, :BDMAIORREM, :BDBINSS, :BDALIQINSS, :BDINSS, :BDBIRRF, :BDALIQIRRF, :BDIRRF, :BDBINSS13,
           :BDALIQINSS13, :BDINSS13, :BDBIRRF13, :BDALIQIRRF13, :BDIRRF13, :BDBSALFAM, :BDSALFAM, :BDBRAIS, :BDSALBASE, :BDDEP,
           :BDBINSSFEFOL, :BDINSSFEFOL, :BDALIQINSSFEFOL, :BDCREDITO, :BDDEBITO, :BDBFGTSFEFOL, :BDFGTSFEFOL, :BDCODTIPOFC,
           :BDBIRRFFE, :BDIRRFFE, :BDLIQUIDO, :BDBIRRFFEFOL, :BDIRRFFEFOL, :BDCODACCONV, :BDDATAPAGFC
       do
         begin
           BDCODTPCC           = null;
           select first 1 BDCODCENTROS from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :BDREFFN order by BDREFEMP DESC into :BDCODCENTRO;
     
           suspend;
         end
    end

  wsql = 'SELECT X.BDCODEMP, X.BDCODCOL, X.BDREFTOMADOR, X.BDREFFC, X.BDCODCONTTI, X.BDDATAGRRFFC, MAX(Y.BDCODCENTRO),'||
         '       MAX(Y.BDCODTPCC), MAX(X.BDDATABAIXAFC), SUM(X.BDBFGTSFC), SUM(X.BDFGTSFC), SUM(X.BDFGTSCSFC), SUM(X.BDBFGTS13FC),'||
         '       SUM(X.BDFGTS13FC), SUM(X.BDFGTS13CSFC), MAX(X.BDMAIORREMFC), SUM(X.BDBINSSFC), MAX(X.BDALIQINSSFC),'||
         '       SUM(X.BDINSSFC), SUM(X.BDBIRRFFC), MAX(X.BDALIQIRRFFC), SUM(X.BDIRRFFC), SUM(X.BDBINSS13FC),'||
         '       MAX(X.BDALIQINSS13FC), SUM(X.BDINSS13FC), SUM(X.BDBIRRF13FC), MAX(X.BDALIQIRRF13FC), SUM(X.BDIRRF13FC),'||
         '       SUM(X.BDBSALFAMFC), SUM(X.BDSALFAMFC), SUM(X.BDBRAISFC), MAX(X.BDSALBASEFC), MAX(X.BDDEPFC),'||
         '       SUM(X.BDBINSSFEFOLFC), SUM(X.BDINSSFEFOLFC), MAX(X.BDALIQINSSFEFOLFC), SUM(X.BDCREDITOFC), SUM(X.BDDEBITOFC),'||
         '       SUM(X.BDBFGTSFEFC), SUM(X.BDFGTSFEFC), COALESCE(MAX(X.BDCODTIPOFC), 1), SUM(X.BDBIRRFFEFC), SUM(X.BDIRRFFEFC),'||
         '       SUM(X.BDLIQUIDO), SUM(X.BDBIRRFFEFC), SUM(X.BDIRRFFEFC), MAX(BDCODACCONV), X.BDDATAPAGFC '||
         'FROM VRHF_EMP_TFOLTOMCOMPINT X ';

  if (coalesce(prpuxafiliais, 0) > 0) then
     wsql = wsql||'join TEMPRESAS E on (E.BDCODEMP = X.BDCODEMP) ';

  wsql = wsql||
         'JOIN VRHF_EMP_TPREPFN Y on (Y.BDCODEMP = X.BDCODEMP AND Y.BDCODCOL = X.BDCODCOL AND Y.BDORDEM = X.BDORDEM) ';

  wsql = wsql||'WHERE X.BDREFTOMADOR = '||prref||' AND '||
               '      X.BDDATAPAGFC = '||''''||prdatapagfc||'''';

  if (coalesce(premp, '') <> '') then
     begin
       if (coalesce(prpuxafiliais, 0) > 0) then
          wsql = wsql||' and (('||replace(upper(premp), 'BDCODEMP', 'E.BDCODEMP')||') or ('||replace(upper(premp), 'BDCODEMP', 'E.BDCODMATRIZ')||')) ';
       else
          begin
            wsql = wsql||' and '||replace(upper(premp), 'BDCODEMP', 'X.BDCODEMP');
     
            if (coalesce(prcol, '') <> '') then
               wsql = wsql||' and '||replace(upper(prcol), 'BDCODCOL', 'X.BDCODCOL');
          end
     end

  if (coalesce(prfiltrocc, '') <> '') then
     begin
       wsql = wsql||' and '||replace(upper(:prfiltrocc), 'BDCODTPCC', 'coalesce(Y.BDCODTPCC, 0)');

     end

  wsql = wsql||'GROUP BY X.BDCODEMP, X.BDCODCOL, X.BDREFTOMADOR, X.BDREFFC, X.BDCODCONTTI, X.BDDATAGRRFFC, X.BDDATAPAGFC ';

  for execute statement :wsql into :BDCODEMP, :BDCODCOL, :BDREFFN, :BDREFFC, :BDCODCONTTI, :BDDATAGRRFFC, :BDCODCENTRO, :BDCODTPCC, :BDDATABAIXA, :BDBFGTS,
      :BDFGTS, :BDFGTSCS, :BDBFGTS13, :BDFGTS13, :BDFGTS13CS, :BDMAIORREM, :BDBINSS, :BDALIQINSS, :BDINSS, :BDBIRRF, :BDALIQIRRF,
      :BDIRRF, :BDBINSS13, :BDALIQINSS13, :BDINSS13, :BDBIRRF13, :BDALIQIRRF13, :BDIRRF13, :BDBSALFAM, :BDSALFAM, :BDBRAIS,
      :BDSALBASE, :BDDEP, :BDBINSSFEFOL, :BDINSSFEFOL, :BDALIQINSSFEFOL, :BDCREDITO, :BDDEBITO, :BDBFGTSFEFOL, :BDFGTSFEFOL,
      :BDCODTIPOFC, :BDBIRRFFE, :BDIRRFFE, :BDLIQUIDO, :BDBIRRFFEFOL, :BDIRRFFEFOL, :BDCODACCONV, :BDDATAPAGFC
  do
    suspend;
end^

CREATE OR ALTER PROCEDURE SP_COPIA_PLANOCPRBREINF (
    PRCODPLANO INTEGER,
    PRCODPLANOCOPIADO INTEGER)
AS
DECLARE VARIABLE WCAMPO VARCHAR(64);
DECLARE VARIABLE WCAMPOSINSERT VARCHAR(5000);
DECLARE VARIABLE WSQL VARCHAR(10000);
BEGIN
  /* OBTÉM OS CAMPOS DA TABELA DE PLANO DE AÇÕES */
  WSQL = 'SELECT R.RDB$FIELD_NAME AS BDCAMPO '||
         'FROM RDB$RELATION_FIELDS R '||
         'WHERE R.RDB$RELATION_NAME = ''VEF_BASE_TCONFAJUCPRBREINF'' ';
  WCAMPOSINSERT = '';

  FOR EXECUTE STATEMENT WSQL
    INTO WCAMPO DO
      BEGIN
        IF (WCAMPO <> 'BDCODPLACPRB') THEN
          WCAMPOSINSERT = WCAMPOSINSERT||','||TRIM(WCAMPO);
      END
  /* CRIA INSERT DA TABELA DE PLANO DE AÇÕES A COPIAR PARA O NOVO PLANO */
  WSQL = 'INSERT INTO VEF_BASE_TCONFAJUCPRBREINF (BDCODPLACPRB'||WCAMPOSINSERT||') '||
         'SELECT '||prCODPLANO||WCAMPOSINSERT||' FROM VEF_BASE_TCONFAJUCPRBREINF WHERE BDCODPLACPRB = '||prCODPLANOCOPIADO;
  EXECUTE STATEMENT wSQL;
END^

create or alter procedure SP_REL_CAGED_ESOCIAL (
    PREMPRESAS varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRSOMENTEMOV varchar(5),
    PRFILTROMOV integer)
returns (
    BDTIPODETALHE integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDNOMEMP varchar(100),
    BDCODFILIAL integer,
    BDATIVOSINIMES integer,
    BDATIVOSFIMMES integer,
    BDADMITIDOSMES integer,
    BDDEMITIDOSMES integer,
    BDDATAADMCOL date,
    BDDATARESCISAO date,
    BDCPFCOL varchar(14),
    BDDATAINTEGRACAO date,
    BDHORAINTEGRACAO time,
    BDPROTOCOLO varchar(50),
    BDRECIBO varchar(30),
    BDEVENTO varchar(10),
    BDMOTIVO varchar(10),
    BDPCD integer,
    BDNOMCOL varchar(70),
    BDMOVIMENTACAO varchar(5))
as
declare variable WSQL varchar(10000);
declare variable WREF integer;
declare variable WWHERE varchar(5000);
declare variable WREFDEC integer;
declare variable WTEMADMPRELIM varchar(5);
declare variable WCODTIPO integer;
declare variable WCODPTRAN integer;
declare variable WTEMMOV varchar(5);
declare variable WFILTROMOV varchar(300);
declare variable WSQL3 varchar(10000);
declare variable WTEMMOVEMPRESA varchar(5);
declare variable WEMPATU integer;
declare variable WEMPRESA integer;
declare variable WREFRESC integer;
declare variable WREFADM integer;
declare variable WBDATIVOSINIMES integer;
declare variable WBDATIVOSFIMMES integer;
declare variable WBDADMITIDOSMES integer;
declare variable WBDDEMITIDOSMES integer;
declare variable WPRIDIAMESSEGUINTE varchar(10);
declare variable WREFSEGUINTE integer;
BEGIN
  /* PROCEDURE TEXT */
  if (PRFILTROMOV = 0) then   -- Todas as movimentações
    WFILTROMOV = ' ARQ.BDCODTIPO IN (23, 24, 33, 34) ';
  else if (PRFILTROMOV = 1) then -- Admissões
    WFILTROMOV = ' (TRANSFENT.BDDATATRF is null and (ARQ.BDCODTIPO = 23 or ARQ.BDCODTIPO = 24)) ';
  else if (PRFILTROMOV = 2) then -- Transferência de entrada
    WFILTROMOV = ' (TRANSFENT.BDDATATRF is not null and ARQ.BDCODTIPO = 24) ';
  else if (PRFILTROMOV = 3) then  -- Admissões e transferência de entrada
    WFILTROMOV = ' (TRANSFENT.BDDATATRF is null and (ARQ.BDCODTIPO = 23 or ARQ.BDCODTIPO = 24) or (TRANSFENT.BDDATATRF is not null and ARQ.BDCODTIPO = 24)) ';
  else if (PRFILTROMOV = 4) then -- Demissões
    WFILTROMOV = ' (TRANSFSAI.BDDATATRF is null and ARQ.BDCODTIPO = 34) ';
  else if (PRFILTROMOV = 5) then -- Transferência de saída
    WFILTROMOV = ' (TRANSFSAI.BDDATATRF is not null and ARQ.BDCODTIPO = 34) ';
  else if (PRFILTROMOV = 6) then -- Demissões e transferência de saída
    WFILTROMOV = ' ((TRANSFSAI.BDDATATRF is null and ARQ.BDCODTIPO = 34) or (TRANSFSAI.BDDATATRF is not null and ARQ.BDCODTIPO = 34)) ';
  else
    WFILTROMOV = ' ARQ.BDCODTIPO = 33 ';

  WSQL = '';
  WSQL3 = '';

  WREF = PRREFINI;
  WWHERE = '';
  WHILE (:WREF <= PRREFFIM) DO
    BEGIN
      wempatu = 0;
      WSQL = ' SELECT BDCODEMP FROM TEMPRESAS WHERE BDCODMATRIZ is null ';

      IF((PREMPRESAS IS NOT NULL) AND (PREMPRESAS <> '')) THEN
        WWHERE = ' and ('||PREMPRESAS||') ';

      WSQL = WSQL||WWHERE;
      WSQL = WSQL||' ORDER BY BDCODEMP';

      SELECT BDREFERENCIA
      FROM INC_REFERENCIA(:WREF)
      INTO :WREFSEGUINTE;

      WPRIDIAMESSEGUINTE = SUBSTRING(CAST(WREFSEGUINTE AS VARCHAR(6)) FROM 5 FOR 2) || '/' || '01' || '/' || SUBSTRING(CAST(WREFSEGUINTE AS VARCHAR(6)) FROM 1 FOR 4);

      FOR EXECUTE STATEMENT WSQL
          INTO :BDCODEMP
      DO
        BEGIN
          bdnomemp = NULL;
          WTEMMOVEMPRESA = 'FALSE';
          BDREF = :WREF;

          -- TOTAIS COLABORADORES ATIVOS -----------AGRUPADO(MATRIZ E FILIAL)
          SELECT BDREF
          FROM DEC_REF(:WREF)
          INTO :WREFDEC;

          wempatu = null;
          wempresa = BDCODEMP;
          BDTIPODETALHE = 0;
          wbdativosfimmes = 0;
          wbdativosinimes = 0;
          wbdadmitidosmes = 0;
          wbddemitidosmes = 0;

          for select BDCODEMP
              from TEMPRESAS
              where (BDCODEMP = :wempresa) or (BDCODMATRIZ = :wempresa)
              order by BDCODEMP, BDCODMATRIZ
          into :wempatu
          do
            begin
              if (wempresa = wempatu) then
                 BDCODFILIAL = null;
              else
                 BDCODFILIAL = wempatu;

              -- INFO EMPRESAS
              SELECT FIRST 1 REF.BDNOMEMP
              FROM TEMPRESAS EMP
              JOIN TEMPRESAS_REF REF ON (EMP.BDCODEMP = REF.BDCODEMP)
              WHERE REF.BDCODEMP = :wempatu AND
                    REF.BDREFEMP <= :WREF
              ORDER BY REF.BDREFEMP DESC
              INTO :BDNOMEMP;

              -- Verifica ativos conforme o mês
              BDATIVOSFIMMES = 0;
              BDATIVOSINIMES = 0;
              BDADMITIDOSMES = 0;
              BDDEMITIDOSMES = 0;

              for select C.BDCODCOL, R.BDREFRESCISAO, CAST((SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER)
                  from VRH_EMP_TCOLCON C
                  left outer join (select BDCODEMP, BDCODCOL, max(BDREFCOL) BDREFCOL
                                   from VRH_EMP_TCOLCON_VINC
                                   where BDCODEMP = :wempatu and BDREFCOL <= :wref
                                   group by BDCODEMP, BDCODCOL) V on (V.BDCODEMP = C.BDCODEMP and V.BDCODCOL = C.BDCODCOL)
                  left outer join VRH_EMP_TCOLCON_VINC VINC on (VINC.BDCODEMP = C.BDCODEMP and VINC.BDCODCOL = C.BDCODCOL and VINC.BDREFCOL = V.BDREFCOL)
                  left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
                  left outer join VRH_EMP_TRESCISAO R on (R.BDCODEMP = C.BDCODEMP and R.BDCODCOL = C.BDCODCOL)
                  where C.BDCODEMP = :wempatu and coalesce(CLA.BDCODCLA, 0) <> 5 and coalesce(C.BDCONTRCOL, 0) <> 1
              into :BDCODCOL, :wrefresc, :wrefadm
              do
                begin
                  wrefadm  = coalesce(wrefadm, 0);
                  wrefresc = coalesce(wrefresc, 0);

                  if (wrefadm <= :wref and ((wrefresc = 0) or (wrefresc > wref))) then
                     BDATIVOSFIMMES = BDATIVOSFIMMES + 1;

                  if (wrefadm <= :wrefdec and ((wrefresc = 0) or (wrefresc > wrefdec))) then
                     BDATIVOSINIMES = BDATIVOSINIMES + 1;

                  if (wrefadm <= :wref and ((wrefresc = 0) or (wrefresc >= wref))) then
                     begin
                       --WTEMMOV = 'FALSE';
                       bdcpfcol = NULL;
                       bddataadmcol = NULL;
                       bddataintegracao = NULL;
                       bddatarescisao = NULL;
                       bdevento = NULL;
                       bdhoraintegracao = NULL;
                       bdmotivo = NULL;
                       bdnomcol = NULL;
                       bdpcd = NULL;
                       bdprotocolo = NULL;
                       bdrecibo = NULL;
         
                       WSQL3 = ' SELECT ''TRUE'' BDMOVIMENTACAO, ';
                       WSQL3 = WSQL3||'    ARQ.BDDATARETORNO, ARQ.BDHORARETORNO, ';
                       WSQL3 = WSQL3||'    LOTE.BDPROTOCOLO, ARQ.BDRECIBO, ';
                       WSQL3 = WSQL3||'    CASE ';
                       WSQL3 = WSQL3||'      WHEN ARQ.BDCODTIPO = 23 THEN ''S-2190''';
                       WSQL3 = WSQL3||'      WHEN ARQ.BDCODTIPO = 24 THEN ''S-2200''';
                       WSQL3 = WSQL3||'      WHEN ARQ.BDCODTIPO = 33 THEN ''S-2298''';
                       WSQL3 = WSQL3||'      WHEN ARQ.BDCODTIPO = 34 THEN ''S-2299''';
                       WSQL3 = WSQL3||'    END BDEVENTO, ';
                       WSQL3 = WSQL3||'    CASE ';
                       WSQL3 = WSQL3||'      WHEN TRANSFENT.BDDATATRF IS NULL AND (ARQ.BDCODTIPO = 23 OR ARQ.BDCODTIPO = 24) THEN ''A''';
                       WSQL3 = WSQL3||'      WHEN TRANSFENT.BDDATATRF IS NOT NULL AND ARQ.BDCODTIPO = 24 THEN ''TE''';
                       WSQL3 = WSQL3||'      WHEN TRANSFSAI.BDDATATRF IS NULL AND ARQ.BDCODTIPO = 34 THEN ''D''';
                       WSQL3 = WSQL3||'      WHEN TRANSFSAI.BDDATATRF IS NOT NULL AND ARQ.BDCODTIPO = 34 THEN ''TS''';
                       WSQL3 = WSQL3||'      WHEN ARQ.BDCODTIPO = 33 THEN ''R''';
                       WSQL3 = WSQL3||'    END BDMOTIVO, ';
                       WSQL3 = WSQL3||'    ARQ.BDCODTIPO ';
                       WSQL3 = WSQL3||' FROM VRH_ESOCIAL_TARQUIVO ARQ ';
                       WSQL3 = WSQL3||' LEFT JOIN VRH_ESOCIAL_TARQUIVO EXC ON (ARQ.BDCODEMP = EXC.BDCODEMP AND ARQ.BDCODIGO = EXC.BDEVTEXCLUIDO) ';
                       WSQL3 = WSQL3||' LEFT JOIN VRH_ESOCIAL_TLOTE_ARQUIVOS LOTE ON (ARQ.BDCODEMP = LOTE.BDCODEMP AND ';
                       WSQL3 = WSQL3||'       ARQ.BDCODLOTE = LOTE.BDCODLOTE) ';
                       WSQL3 = WSQL3||' LEFT JOIN VRH_EMP_TTRANSCOL TRANSFENT ON (ARQ.BDCODEMP = TRANSFENT.BDCODEMPDEST AND ';
                       WSQL3 = WSQL3||'       ARQ.BDCODCOL = TRANSFENT.BDCODCOLDEST AND ';
                       WSQL3 = WSQL3||'       ((TRANSFENT.BDREFTRF = '||WREF||') OR (TRANSFENT.BDDATATRF = '''||WPRIDIAMESSEGUINTE||'''))) ';
                       WSQL3 = WSQL3||' LEFT JOIN VRH_EMP_TTRANSCOL TRANSFSAI ON (ARQ.BDCODEMP = TRANSFSAI.BDCODEMPORIG AND ';
                       WSQL3 = WSQL3||'       ARQ.BDCODCOL = TRANSFSAI.BDCODCOLORIG AND ';
                       WSQL3 = WSQL3||'       ((TRANSFSAI.BDREFTRF = '||WREF||') OR (TRANSFSAI.BDDATATRF = '''||WPRIDIAMESSEGUINTE||'''))) ';
                       WSQL3 = WSQL3||' JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = ARQ.BDCODEMP) ';
                       WSQL3 = WSQL3||' INNER JOIN TEMPRESAS MATRIZ ON (MATRIZ.BDCODEMP = ARQ.BDCODEMP) ';
                       WSQL3 = WSQL3||' LEFT OUTER JOIN VW_TEMPRESAS_REF_ATUAL REF ON (REF.BDCODEMP = MATRIZ.BDCODMATRIZ) ';
                       WSQL3 = WSQL3||' WHERE ARQ.BDCODEMP = '||:wempatu||' AND ';
                       WSQL3 = WSQL3||'       ARQ.BDCODCOL = '||BDCODCOL||' AND ';
                       WSQL3 = WSQL3||'       ARQ.BDREFARQ = '||WREF||' AND ';
                       WSQL3 = WSQL3||'       (ARQ.BDCODSTATUS >= 200 AND ';
                       WSQL3 = WSQL3||'       ARQ.BDCODSTATUS < 300) AND ';
                       WSQL3 = WSQL3||'       (UPPER(ARQ.BDMOTIVO) NOT CONTAINING ''RETIFICAÇÃO'') AND EXC.BDCODIGO IS NULL AND ';
                       WSQL3 = WSQL3||WFILTROMOV;
                       WSQL3 = WSQL3||' ORDER  BY ARQ.BDCODTIPO ';
     
                       -- INFORMAÇÕES EVENTOS
                       wTemAdmPrelim = 'FALSE';
                       FOR EXECUTE STATEMENT WSQL3
                       INTO :bdmovimentacao, :bddataintegracao, :bdhoraintegracao, :bdprotocolo, :bdrecibo, :bdevento, :bdmotivo, :WCODTIPO
                          DO
                            BEGIN
                              WTEMMOV = 'FALSE';

                              if (:bdmotivo = 'A') then
                                BEGIN
                                  if (:wcodtipo = 23) then
                                    BEGIN
                                      wtemadmprelim = 'TRUE';
                                      WTEMMOV = 'TRUE';
                                      BDADMITIDOSMES = BDADMITIDOSMES + 1;
                                    END
                                  ELSE if (NOT(wtemadmprelim = 'TRUE')) then
                                    BEGIN
                                      WTEMMOV = 'TRUE';
                                      BDADMITIDOSMES = BDADMITIDOSMES + 1;
                                    END
                                END
                              ELSE if ((:BDMOTIVO = 'TE') or (:BDMOTIVO = 'TS')) then
                                BEGIN
                                  SELECT FIRST 1 T.BDCODPTRAN FROM VRH_EMP_TTRANSCOL T
                                  WHERE ((T.BDCODEMPDEST = :WEMPATU) OR (T.BDCODEMPORIG = :WEMPATU))  AND
                                        ((T.BDCODCOLDEST = :BDCODCOL) OR (T.BDCODCOLORIG = :BDCODCOL))  AND
                                        ((T.BDREFTRF = :WREF) OR (T.BDDATATRF = :WPRIDIAMESSEGUINTE))  AND
                                        T.BDCODPTRAN NOT IN (302, 303)
                                  INTO :WCODPTRAN;
             
                                  if (WCODPTRAN IS NOT NULL) then
                                    BEGIN
                                      WTEMMOV = 'TRUE';

                                      if (:BDMOTIVO = 'TE') then
                                        begin
                                          BDADMITIDOSMES = BDADMITIDOSMES + 1;

                                          if (wrefadm <= :wrefdec and ((wrefresc = 0) or (wrefresc > wrefdec))) then
                                            BDATIVOSINIMES = BDATIVOSINIMES - 1;

                                        end
                                      else
                                        BDDEMITIDOSMES = BDDEMITIDOSMES + 1;

                                    END
                                END
                              ELSE       -- REINTEGRAÇÃO OU DEMISSÃO
                                BEGIN
                                  WTEMMOV = 'TRUE';

                                  if (:BDMOTIVO = 'R') then
                                    BDADMITIDOSMES = BDADMITIDOSMES + 1;
                                  else
                                    BDDEMITIDOSMES = BDDEMITIDOSMES + 1;
                                END
             

         
                              if (WTEMMOV = 'TRUE') then
                                BEGIN
                                  WTEMMOVEMPRESA = 'TRUE';
             
                                  -- INFORMAÇÕES COLABORADOR
                         
                                  SELECT FIRST 1 COL.BDDATAADMCOL, RESC.BDDATARESCISAO, DOC.BDCPFCOL
                                  FROM VRH_EMP_TCOLCON COL
                                  LEFT JOIN VRH_EMP_TRESCISAO RESC ON (COL.BDCODEMP = RESC.BDCODEMP AND
                                  COL.BDCODCOL = RESC.BDCODCOL)
                                  LEFT JOIN VRH_EMP_TCOLCON_DOC DOC ON (COL.BDCODEMP = DOC.BDCODEMP AND
                                  COL.BDCODCOL = DOC.BDCODCOL)
                                  WHERE COL.BDCODEMP = :wempatu AND
                                        COL.BDCODCOL = :BDCODCOL
                                  INTO :BDDATAADMCOL, :BDDATARESCISAO, :BDCPFCOL;
                         
                                  SELECT FIRST 1 BDCOTADEF
                                  FROM VRH_EMP_TCOLCON_FIS
                                  WHERE BDCODEMP = :wempatu AND
                                        BDCODCOL = :BDCODCOL AND
                                        BDREFCOL <= :WREF
                                  ORDER BY BDREFCOL DESC
                                  INTO :BDPCD;
                         
                                  SELECT FIRST 1 BDNOMCOL
                                  FROM VRH_EMP_TCOLCON_CAD
                                  WHERE BDCODEMP = :wempatu AND
                                        BDCODCOL = :BDCODCOL AND
                                        BDREFCOL <= :WREF
                                  ORDER BY BDREFCOL DESC
                                  INTO :BDNOMCOL;
                         
                                  SUSPEND;
                              END
                       END
                    end
                end

              wbdativosfimmes = wbdativosfimmes + BDATIVOSFIMMES;
              wbdativosinimes = wbdativosinimes + BDATIVOSINIMES;
              wbdadmitidosmes = wbdadmitidosmes + BDADMITIDOSMES;
              wbddemitidosmes = wbddemitidosmes + BDDEMITIDOSMES;
   
             -- EMPRESA SEM MOVIMENTAÇÃO
             if ((WTEMMOVEMPRESA = 'FALSE') AND (PRSOMENTEMOV = 'FALSE')) then
                 BEGIN
                   BDMOVIMENTACAO = 'FALSE';
                   BDCODCOL = null;
                   SUSPEND;
                 END
            end

        if ((PRSOMENTEMOV = 'FALSE') or ((WTEMMOVEMPRESA = 'TRUE') AND (PRSOMENTEMOV = 'TRUE'))) then
          BEGIN
            BDTIPODETALHE = 1;
            BDCODCOL = null;
            BDREF = wref;
    --        BDCODFILIAL = null;
            BDATIVOSINIMES = wbdativosinimes;
            BDATIVOSFIMMES = wbdativosfimmes;
            BDADMITIDOSMES = wbdadmitidosmes;
            BDDEMITIDOSMES = wbddemitidosmes;
            BDDATAADMCOL = null;
            BDDATARESCISAO = null;
            BDCPFCOL = null;
            BDDATAINTEGRACAO = null;
            BDHORAINTEGRACAO = null;
            BDPROTOCOLO = null;
            BDRECIBO = null;
            BDEVENTO = null;
            BDMOTIVO = null;
            BDPCD = null;
            BDNOMCOL = null;
            BDMOVIMENTACAO = null;
            suspend;
          END

      END

      SELECT BDREFERENCIA
      FROM INC_REFERENCIA(:WREF)
      INTO :WREF;
    END
END^

CREATE OR ALTER PROCEDURE SP_EXPORTACAO_VT_BLUMOB (
    PRCODEMP VARCHAR(10000),
    PRCODCOL VARCHAR(10000),
    PRREF INTEGER,
    PRCODCLA INTEGER = NULL,
    PRCODSINTRAB INTEGER = NULL)
RETURNS (
    BDCODEMP INTEGER,
    BDCODCOL INTEGER,
    BDNOMEMP VARCHAR(100),
    BDCPFCOL VARCHAR(14),
    BDNOMCOL VARCHAR(70),
    BDVALORDIARIO NUMERIC(18,6),
    BDQUANTIDADE INTEGER)
AS
DECLARE VARIABLE WJOIN VARCHAR(10000);
DECLARE VARIABLE WVALITI NUMERIC(18,6);
DECLARE VARIABLE WWHERE VARCHAR(10000);
DECLARE VARIABLE WSQL VARCHAR(10000);
BEGIN
  /* PROCEDURE TEXT */
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREF, NULL, NULL);

  WWHERE = '';
  WJOIN = '';

  WSQL = 'SELECT C.BDCODEMP, E2.BDNOMEMP, C.BDCODCOL, C.BDCPFCOL, COLCAD.BDNOMCOL ';
  WSQL = WSQL || 'FROM VRH_EMP_TCOLCON C ';
  WSQL = WSQL || 'JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON (COLCAD.BDCODEMP = C.BDCODEMP AND ';
  WSQL = WSQL || '      COLCAD.BDCODCOL = C.BDCODCOL) ';
  WSQL = WSQL || 'JOIN TEMPRESAS E ON (E.BDCODEMP = C.BDCODEMP) ';
  WSQL = WSQL || 'JOIN VW_TEMPRESAS_REF E2 ON (E2.BDCODEMP = E.BDCODEMP) ';

  IF (PRCODEMP IS NOT NULL AND PRCODEMP <> '') THEN
    BEGIN
        IF (WWHERE = '') THEN
          WWHERE = ' WHERE '||PRCODEMP;
        ELSE
          WWHERE = WWHERE||' AND '||PRCODEMP;
    END

  IF (PRCODCOL IS NOT NULL AND PRCODCOL <> '') THEN
    BEGIN
        IF (WWHERE = '') THEN
          WWHERE = ' WHERE '||PRCODCOL;
        ELSE
          WWHERE = WWHERE||' AND '||PRCODCOL;
    END

  IF (PRCODCLA IS NOT NULL AND PRCODCLA <> '') THEN
    BEGIN
        IF (WWHERE = '') THEN
          WWHERE = ' WHERE '||PRCODCLA;
        ELSE
          WWHERE = WWHERE||' AND ('||PRCODCLA||') ';

        WJOIN = ' JOIN VW_VRH_EMP_TCOLCON_VINC V2 ON (V2.BDCODEMP = C.BDCODEMP AND V2.BDCODCOL = C.BDCODCOL) ';
    END

  IF (PRCODSINTRAB IS NOT NULL AND PRCODSINTRAB <> '') THEN
    BEGIN
        IF (WWHERE = '') THEN
          WWHERE = ' WHERE '||PRCODSINTRAB;
        ELSE
          WWHERE = WWHERE||' AND ('||PRCODSINTRAB||') ';

        WJOIN = ' JOIN VW_VRH_EMP_TCOL_VINC V1 ON (V1.BDCODEMP = C.BDCODEMP AND V1.BDCODCOL = C.BDCODCOL) ';
    END

  WSQL = WSQL || WJOIN || WWHERE;

  WSQL = WSQL || 'ORDER BY C.BDCODEMP, C.BDCODCOL, E2.BDNOMEMP, C.BDCPFCOL, COLCAD.BDNOMCOL';

  FOR EXECUTE STATEMENT WSQL
  INTO :BDCODEMP, :BDNOMEMP, :BDCODCOL, :BDCPFCOL, :BDNOMCOL
  DO
  BEGIN
    BDQUANTIDADE = 0;
    BDVALORDIARIO = 0;

    SELECT MAX(BDQUANTIDADE) BDQUANTIDADE
    FROM VRHF_EMP_TAPVALTRANS
    WHERE BDCODEMP = :BDCODEMP AND
          BDCODCOL = :BDCODCOL AND
          BDCOMPETENCIA = :PRREF
    INTO :BDQUANTIDADE;

    BDVALORDIARIO = 0;
    WVALITI = 0;
    FOR SELECT ITIREF.BDVALITI
        FROM VW_VRHF_EMP_TITICOL ITICOL
        JOIN VW_VRHF_BASE_TITINERARIOS_REF ITIREF ON (ITIREF.BDCODITI = ITICOL.BDCODITI)
        WHERE ITICOL.BDCODEMP = :BDCODEMP AND
              ITICOL.BDCODCOL = :BDCODCOL
        GROUP BY 1
    INTO :WVALITI
    DO
    BEGIN
        BDVALORDIARIO = BDVALORDIARIO + WVALITI;
    END

    SUSPEND;
  END
END^

CREATE OR ALTER TRIGGER VRHF_EMP_TAPVALREF_BU0 FOR VRHF_EMP_TAPVALREF
ACTIVE BEFORE UPDATE POSITION 0
AS
  declare variable wdata DATE;
begin
  if (coalesce(new.bdperiodo, '') <> '') then
     begin
       wdata = CAST((SUBSTRING(new.bdperiodo from 1 for 4)||'-'||SUBSTRING(new.bdperiodo from 5 for 2)||'-'||SUBSTRING(new.bdperiodo from 7 for 2)) AS DATE);
       new.bdinicioapuracao = :wdata;
       wdata = CAST((SUBSTRING(new.bdperiodo from 9 for 4)||'-'||SUBSTRING(new.bdperiodo from 13 for 2)||'-'||SUBSTRING(new.bdperiodo from 15 for 2)) AS DATE);
       new.bdfinalapuracao = :wdata;
     end
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TAPVALREF_BI0 FOR VRHF_EMP_TAPVALREF
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wdata DATE;
begin
  if (coalesce(new.bdperiodo, '') <> '') then
     begin
       wdata = CAST((SUBSTRING(new.bdperiodo from 1 for 4)||'-'||SUBSTRING(new.bdperiodo from 5 for 2)||'-'||SUBSTRING(new.bdperiodo from 7 for 2)) AS DATE);
       new.bdinicioapuracao = :wdata;
       wdata = CAST((SUBSTRING(new.bdperiodo from 9 for 4)||'-'||SUBSTRING(new.bdperiodo from 13 for 2)||'-'||SUBSTRING(new.bdperiodo from 15 for 2)) AS DATE);
       new.bdfinalapuracao = :wdata;
     end
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TPLA_TCONTRATO_BI0 FOR VRH_BASE_TPLA_TCONTRATO
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wdata VARCHAR(10);

begin
  if (coalesce(new.bdcomplanc, 0) <= 0) then
     begin
       select first 1 CAST(BDDATAINISERVTI AS VARCHAR(10)) from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDCODCONTTI = new.bdcodcontti into :wdata;
       new.bdcomplanc = CAST((SUBSTRING(:wdata FROM 1 FOR 4)||SUBSTRING(:wdata FROM 6 FOR 2))  AS INTEGER);
     end
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TPLA_TCONTRATO_BU0 FOR VRH_BASE_TPLA_TCONTRATO
ACTIVE BEFORE UPDATE POSITION 0
AS
  declare variable wdata VARCHAR(10);

begin
  if (coalesce(new.bdcomplanc, 0) <= 0) then
     begin
       select first 1 CAST(BDDATAINISERVTI AS VARCHAR(10)) from VRH_EMP_TINTERMITENTE where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDCODCONTTI = new.bdcodcontti into :wdata;
       new.bdcomplanc = CAST((SUBSTRING(:wdata FROM 1 FOR 4)||SUBSTRING(:wdata FROM 6 FOR 2))  AS INTEGER);
     end
end
^

/* Restore proc. body: SP_VRHF_CODEMPREENDIMENTO */
create or alter procedure SP_VRHF_CODEMPREENDIMENTO (
    PREMP integer,
    PRREF integer,
    PRCODTPCC integer,
    PRPLANOCC integer = null)
returns (
    BDCODEMP integer,
    BDCODEMPREENDIMENTO integer)
as
declare variable WCODTPCC integer;
begin
  if (coalesce(prplanocc, 0) = 0) then
     select first 1 BDCODCENTROS from TEMPRESAS_REF where BDCODEMP = :premp and BDREFEMP <= :prref order by BDREFEMP DESC into :prplanocc;

  wcodtpcc = null;
  select first 1 BDCODTPCC from VRHF_SP_TOMADOR(:prcodtpcc, :prplanocc) into :wcodtpcc;

  BDCODEMP = premp;
  BDCODEMPREENDIMENTO = null;

  if (coalesce(wcodtpcc, 0) > 0) then
     select first 1 BDCODEMPREENDIMENTO from VEF_EMP_TCADEMPREENDIMENTO where BDCODEMP = :premp and BDCODCENTRO = :prplanocc and BDCODTPCC = :wcodtpcc into :BDCODEMPREENDIMENTO;



  suspend;
end^

SET TERM ; ^
COMMENT ON PARAMETER SP_FILTER_DEM_RENDIMENTOS.PRTIPO IS 'CAIXA/COMP';
COMMENT ON PARAMETER SP_FILTER_SER_RENDIMENTOS.PRTIPO IS 'CAIXA/COMP';


SET TERM ^ ;


CREATE OR ALTER trigger vrh_base_alerta_venc_bi0 for vrh_base_alerta_venc
active before insert position 0
AS
  declare variable vcodpav INTEGER;
BEGIN
  select BDCODPAVEMP from TEMPRESAS where BDCODEMP = new.BDCODEMP into :vcodpav;
  new.BDCODPAV = :vcodpav;
END^

create or alter procedure SP_VRH_ALERTA_VENCIMENTOS (
    PRDATA varchar(10),
    PRCODPLANO integer = 0)
returns (
    BDCODEMP integer,
    BDCOLCON integer,
    BDTIPOALERTA integer,
    BDDATAVENC date,
    BDCAMINHO varchar(255),
    BDDESCRICAO varchar(680),
    BDCADASTRO integer,
    BDCHAVECAD varchar(50),
    BDCAMPO varchar(30),
    BDTIPO integer,
    BDFERIASPRIMEIROVENC DM_BOOLEAN,
    BDDIASFERIASPRIMEIROVENC integer,
    BDFERIASSEGUNDOVENC DM_BOOLEAN,
    BDDIASFERIASSEGUNDOVENC integer)
as
declare variable WSQL varchar(30000);
declare variable WCODPAV integer;
declare variable WDESCRICAOPAV varchar(65);
declare variable WASOSPERIODICOS DM_BOOLEAN;
declare variable WDIASASOSPERIODICOS integer;
declare variable WCONTRATODETERMINADO DM_BOOLEAN;
declare variable WDIASCONTRATODETERMINADO integer;
declare variable WCONTRATOEXPERIENCIAPRI DM_BOOLEAN;
declare variable WDIASCONTRATOEXPERIENCIAPRI integer;
declare variable WCONTRATOEXPERIENCIASEG DM_BOOLEAN;
declare variable WDIASCONTRATOEXPERIENCIASEG integer;
declare variable WCONTRATOAPRENDIZ DM_BOOLEAN;
declare variable WDIASCONTRATOAPRENDIZ integer;
declare variable WCONTRATOESTAGIO DM_BOOLEAN;
declare variable WDIASCONTRATOESTAGIO integer;
declare variable WATESTADOESCOLADEP DM_BOOLEAN;
declare variable WDIASATESTADOESCOLADEP integer;
declare variable WCNHCOLCON DM_BOOLEAN;
declare variable WDIASCNHCOLCON integer;
declare variable WCNHMOTORISTA DM_BOOLEAN;
declare variable WDIASCNHMOTORISTA integer;
declare variable WCARTAOVACINADEP DM_BOOLEAN;
declare variable WDIASCARTAOVACINADEP integer;
declare variable WAFASTAMENTOESTABILIDADE DM_BOOLEAN;
declare variable WDIASAFASTAMENTOESTABILIDADE integer;
declare variable WANIVERSARIANTES DM_BOOLEAN;
declare variable WDIASANIVERSARIANTES integer;
declare variable WANIVERSARIOEMPRESA DM_BOOLEAN;
declare variable WDIASANIVERSARIOEMPRESA integer;
declare variable WAVISOPREVIO DM_BOOLEAN;
declare variable WDIASAVISOPREVIO integer;
declare variable WCERTIFICADODIGITAL DM_BOOLEAN;
declare variable WDIASCERTIFICADODIGITAL integer;
declare variable WDISSIDIOCOLETIVO DM_BOOLEAN;
declare variable WDIASDISSIDIOCOLETIVO integer;
declare variable WFERIASPRIMEIROVENC DM_BOOLEAN;
declare variable WDIASFERIASPRIMEIROVENC integer;
declare variable WFERIASSEGUNDOVENC DM_BOOLEAN;
declare variable WDIASFERIASSEGUNDOVENC integer;
declare variable WSQL2 varchar(10000);
declare variable WSTR varchar(100);
declare variable WCODIGO integer;
declare variable WPAGAMENTOFERIAS DM_BOOLEAN;
declare variable WDIASPAGAMENTOFERIAS integer;
declare variable WPAGAMENTORESCISAO DM_BOOLEAN;
declare variable WDIASPAGAMENTORESCISAO integer;
declare variable WORGAOCLASSE DM_BOOLEAN;
declare variable WDIASORGAOCLASSE integer;
declare variable WHORAEXECUCAO varchar(5);
declare variable WCONTRATODETERMINADO2 DM_BOOLEAN;
declare variable WDIASCONTRATODETERMINADO2 integer;
declare variable WDATA varchar(10);
declare variable WDATAVENC varchar(10);
declare variable WCONTRCOL integer;
declare variable WDATAINICIAL varchar(12);
declare variable WINIPERAQUIFER varchar(10);
declare variable WFIMPERAQUIFER varchar(10);
declare variable WREF integer;
declare variable WTIPO integer;
declare variable WDATAEXECUCAO date;
declare variable WINATIVO DM_BOOLEAN;
declare variable WAVISOS DM_BOOLEAN;
declare variable WINFORMATIVOS DM_BOOLEAN;
declare variable WDATAPARAM date;
declare variable WNOMECOLCON varchar(100);
declare variable WCATCOL integer;
declare variable WCODSIND integer;
declare variable WDESTABSIND integer;
declare variable WREFST integer;
declare variable WDATANASC date;
declare variable WANOBISEXTO integer;
begin
  EXECUTE STATEMENT 'select cast(''' || :PRDATA || ''' as date) from strzero(extract(year from cast(''' || :PRDATA || ''' as date)), 4)' into :WDATAPARAM;
  WDATA = substring(cast(PRDATA as varchar(10)) from 4 for 2)|| '/' ||substring(cast(PRDATA as varchar(10)) from 1 for 2)|| '/' ||substring(cast(PRDATA as varchar(10)) from 7 for 4);

  WDATAINICIAL = '''12/31/1899''';

  WREF = cast(substring(cast(PRDATA as varchar(10)) from 7 for 4)||substring(cast(PRDATA as varchar(10)) from 1 for 2) as integer);
  EXECUTE PROCEDURE sp_seta_competencia(WREF,  NULL, NULL);

  wsql = 'SELECT EMP.BDCODEMP, BDCODPAV, BDDESCRICAOPAV, BDASOSPERIODICOS, COALESCE(BDDIASASOSPERIODICOS, 0) BDDIASASOSPERIODICOS, ' ||
         'BDCONTRATODETERMINADO, COALESCE(BDDIASCONTRATODETERMINADO, 0) BDDIASCONTRATODETERMINADO, ' ||
         'BDCONTRATOEXPERIENCIAPRI, COALESCE(BDDIASCONTRATOEXPERIENCIAPRI, 0) BDDIASCONTRATOEXPERIENCIAPRI, ' ||
         'BDCONTRATOEXPERIENCIASEG, COALESCE(BDDIASCONTRATOEXPERIENCIASEG, 0) BDDIASCONTRATOEXPERIENCIASEG, ' ||
         'BDCONTRATOAPRENDIZ, COALESCE(BDDIASCONTRATOAPRENDIZ, 0) BDDIASCONTRATOAPRENDIZ, BDCONTRATOESTAGIO, ' ||
         'COALESCE(BDDIASCONTRATOESTAGIO, 0) BDDIASCONTRATOESTAGIO, BDATESTADOESCOLADEP, ' ||
         'COALESCE(BDDIASATESTADOESCOLADEP, 0) BDDIASATESTADOESCOLADEP, BDCNHCOLCON, ' ||
         'COALESCE(BDDIASCNHCOLCON, 0) BDDIASCNHCOLCON, BDCNHMOTORISTA, COALESCE(BDDIASCNHMOTORISTA, 0) BDDIASCNHMOTORISTA, ' ||
         'BDCARTAOVACINADEP, COALESCE(BDDIASCARTAOVACINADEP, 0) BDDIASCARTAOVACINADEP, BDAFASTAMENTOESTABILIDADE, ' ||
         'COALESCE(BDDIASAFASTAMENTOESTABILIDADE, 0) BDDIASAFASTAMENTOESTABILIDADE, BDANIVERSARIANTES, ' ||
         'COALESCE(BDDIASANIVERSARIANTES, 0) BDDIASANIVERSARIANTES, BDANIVERSARIOEMPRESA, ' ||
         'COALESCE(BDDIASANIVERSARIOEMPRESA, 0) BDDIASANIVERSARIOEMPRESA, BDAVISOPREVIO, ' ||
         'COALESCE(BDDIASAVISOPREVIO, 0) BDDIASAVISOPREVIO, BDCERTIFICADODIGITAL, ' ||
         'COALESCE(BDDIASCERTIFICADODIGITAL, 0) BDDIASCERTIFICADODIGITAL, BDDISSIDIOCOLETIVO, ' ||
         'COALESCE(BDDIASDISSIDIOCOLETIVO, 0) BDDIASDISSIDIOCOLETIVO, BDFERIASPRIMEIROVENC, ' ||
         'COALESCE(BDDIASFERIASPRIMEIROVENC, 0) BDDIASFERIASPRIMEIROVENC, BDFERIASSEGUNDOVENC, ' ||
         'COALESCE(BDDIASFERIASSEGUNDOVENC, 0) BDDIASFERIASSEGUNDOVENC, BDPAGAMENTOFERIAS, ' ||
         'COALESCE(BDDIASPAGAMENTOFERIAS, 0) BDDIASPAGAMENTOFERIAS, BDPAGAMENTORESCISAO, ' ||
         'COALESCE(BDDIASPAGAMENTORESCISAO, 0) BDDIASPAGAMENTORESCISAO, BDORGAOCLASSE, ' ||
         'COALESCE(BDDIASORGAOCLASSE, 0) BDDIASORGAOCLASSE, BDHORAEXECUCAO, BDCONTRATODETERMINADO2, ' ||
         'COALESCE(BDDIASCONTRATODETERMINADO2, 0) BDDIASCONTRATODETERMINADO2, BDDATAULTEXECUCAO, BDINATIVO, BDAVISO, ' ||
         'BDINFORMATIVO ' ||
         'FROM VRH_BASE_PLANO_ALERTA_VENC ALERTA ' ||
         'INNER JOIN TEMPRESAS EMP ON (EMP.BDCODPAVEMP = ALERTA.BDCODPAV) ' ||
         'JOIN TEMPRESAS_REF REF ON (REF.BDCODEMP = EMP.BDCODEMP AND REF.BDREFEMP = (SELECT MAX(R.BDREFEMP) FROM TEMPRESAS_REF R WHERE R.BDCODEMP = REF.BDCODEMP AND R.BDREFEMP <= '||WREF||')) '||
         'WHERE EMP.BDCODPAVEMP > 0 AND ' ||
         '      COALESCE(ALERTA.BDINATIVO, ''FALSE'') = ''FALSE'''||
         ' AND COALESCE(REF.BDSITEMP, ''FALSE'') = ''FALSE''';

  if (prcodplano > 0) then
     wsql = wsql || ' and emp.bdcodpavemp = ' || prcodplano;

  FOR EXECUTE STATEMENT wsql INTO :BDCODEMP, :WCODPAV, :WDESCRICAOPAV, :WASOSPERIODICOS, :WDIASASOSPERIODICOS,
                                  :WCONTRATODETERMINADO, :WDIASCONTRATODETERMINADO,
                                  :WCONTRATOEXPERIENCIAPRI, :WDIASCONTRATOEXPERIENCIAPRI, :WCONTRATOEXPERIENCIASEG, :WDIASCONTRATOEXPERIENCIASEG,
                                  :WCONTRATOAPRENDIZ, :WDIASCONTRATOAPRENDIZ, :WCONTRATOESTAGIO, :WDIASCONTRATOESTAGIO,
                                  :WATESTADOESCOLADEP, :WDIASATESTADOESCOLADEP, :WCNHCOLCON, :WDIASCNHCOLCON, :WCNHMOTORISTA, :WDIASCNHMOTORISTA,
                                  :WCARTAOVACINADEP, :WDIASCARTAOVACINADEP, :WAFASTAMENTOESTABILIDADE, :WDIASAFASTAMENTOESTABILIDADE,
                                  :WANIVERSARIANTES, :WDIASANIVERSARIANTES, :WANIVERSARIOEMPRESA, :WDIASANIVERSARIOEMPRESA,
                                  :WAVISOPREVIO, :WDIASAVISOPREVIO, :WCERTIFICADODIGITAL, :WDIASCERTIFICADODIGITAL,
                                  :WDISSIDIOCOLETIVO, :WDIASDISSIDIOCOLETIVO, :WFERIASPRIMEIROVENC, :WDIASFERIASPRIMEIROVENC,
                                  :WFERIASSEGUNDOVENC, :WDIASFERIASSEGUNDOVENC, :WPAGAMENTOFERIAS, :WDIASPAGAMENTOFERIAS,
                                  :WPAGAMENTORESCISAO, :WDIASPAGAMENTORESCISAO, :WORGAOCLASSE, :WDIASORGAOCLASSE, : WHORAEXECUCAO,
                                  :WCONTRATODETERMINADO2, :WDIASCONTRATODETERMINADO2, :WDATAEXECUCAO, :WINATIVO, :WAVISOS, :WINFORMATIVOS DO
    begin
      BDFERIASPRIMEIROVENC     = WFERIASPRIMEIROVENC;
      BDDIASFERIASPRIMEIROVENC = WDIASFERIASPRIMEIROVENC;
      BDFERIASSEGUNDOVENC      = WFERIASSEGUNDOVENC;
      BDDIASFERIASSEGUNDOVENC  = WDIASFERIASSEGUNDOVENC;

      for SELECT COL.BDCODCOL, COL.BDCONTRCOL
          FROM VRH_EMP_TCOLCON COL
          LEFT OUTER JOIN VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL)
          WHERE COL.BDCODEMP = :BDCODEMP and COL.BDREFADMCOL <= :wref and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO > :wdataparam))
      into :BDCOLCON, :WCONTRCOL
      do
        begin
          select first 1 bdnomcol from VRH_EMP_TCOLCON_CAD where bdcodemp = :BDCODEMP and bdcodcol = :BDCOLCON and BDREFCOL <= :wref order by BDREFCOL DESC into :WNOMECOLCON;

          wcatcol = 0;
          if ((coalesce(WCONTRATODETERMINADO,'FALSE') = 'TRUE') or (coalesce(WCONTRATODETERMINADO2,'FALSE') = 'TRUE') or
              (coalesce(WCONTRATOAPRENDIZ,'FALSE') = 'TRUE') or (coalesce(WCONTRATOESTAGIO,'FALSE') = 'TRUE')) then
             select first 1 BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS where bdcodemp = :BDCODEMP and bdcodcol = :BDCOLCON and BDREFCOL <= :wref order by BDREFCOL DESC into :wcatcol;

          WNOMECOLCON = coalesce(WNOMECOLCON, '');
          wcatcol = coalesce(wcatcol, 0);
          WCONTRCOL = coalesce(WCONTRCOL, 0);

          if (coalesce(WASOSPERIODICOS,'FALSE') = 'TRUE') then
             begin
               wsql2 = 'select aso.bdcodaso, aso.bddatavalidadeaso from VRH_EMP_TCOL_ASO aso ' ||
                       'where aso.bdcodemp = ' || :BDCODEMP || ' and aso.bdcodcol = ' || :BDCOLCON || '  and aso.bdcodaso = (select max(bdcodaso) from VRH_EMP_TCOL_ASO where bdcodemp = aso.bdcodemp and bdcodcol = aso.bdcodcol) and ' ||
                       ' aso.BDDATAVALIDADEASO between ' || :WDATAINICIAL || ' AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASASOSPERIODICOS || ')'; --158075 Valmor 03/02/2022
    
               FOR EXECUTE STATEMENT wsql2 INTO :WCODIGO, :BDDATAVENC DO
                  begin
                    WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);

                    BDTIPOALERTA = 1;
                    BDTIPO = 2;
                    BDCAMINHO = 'Lançamentos / eSocial / Atestado de saúde ocupacional (ASO) / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON ||
                                ' - Código ' || WCODIGO;
    
                    if (BDDATAVENC < WDATAPARAM) then
                       BDDESCRICAO = 'O colaborador está com ASO periódico vencido. ';
                    else
                       BDDESCRICAO = 'O colaborador está com ASO periódico para vencer nos próximos dias. ';
    
                    BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                 'Dias de antecedência para alertar: ' || WDIASASOSPERIODICOS || '. ' ||
                                                 'Data do alerta: ' || WDATA || '.';
                    BDCADASTRO = 12;
                    BDCHAVECAD = BDCODEMP || '.' || BDCOLCON || '.' || WCODIGO;
                    BDCAMPO = 'EDCODASO';
    
                    suspend;
                  end
             end
    
          if (coalesce(WCONTRATODETERMINADO,'FALSE') = 'TRUE' and wcatcol = 106) then
             begin
               wsql2 = 'SELECT trab.BDDATAFIMPRAZO1COL FROM VRH_EMP_TTRABTEMP trab ' ||
                       'where trab.bdcodemp = ' || :BDCODEMP || ' AND trab.bdcodcol = ' || :BDCOLCON || ' AND trab.BDDATAFIMPRAZO2COL is null and ' ||
                       '      trab.BDDATAFIMPRAZO1COL between ' || :WDATAINICIAL || ' AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASCONTRATODETERMINADO || ')';
    
               FOR EXECUTE STATEMENT wsql2 INTO :BDDATAVENC DO
                  begin
                    WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);
    
                    BDTIPOALERTA = 2;
                    BDTIPO = 2;
                    BDCAMINHO = 'Cadastros / Contrato de trabalho / Temporário / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON;
    
                    if (BDDATAVENC < WDATAPARAM) then
                       BDDESCRICAO = 'O colaborador está com o prazo do contrato de trabalho temporário vencido. ';
                    else
                       BDDESCRICAO = 'O colaborador está com o prazo do contrato de trabalho temporário para vencer nos próximos dias. ';
    
                    BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                 'Dias de antecedência para alertar: ' || WDIASCONTRATODETERMINADO || '. ' ||
                                                 'Data do alerta: ' || WDATA || '.';
    
                    BDCADASTRO = 16;
                    BDCHAVECAD = BDCODEMP || '.' || BDCOLCON;
                    BDCAMPO = 'DTDATAFIMPRAZO1COL';
    
                    suspend;
                  end
             end
    
          if (coalesce(WCONTRATODETERMINADO2,'FALSE') = 'TRUE' and wcatcol = 106) then
             begin
               wsql2 = 'SELECT trab.BDDATAFIMPRAZO2COL FROM VRH_EMP_TTRABTEMP trab ' ||
                       'where trab.bdcodemp = ' || :BDCODEMP || ' AND trab.bdcodcol = ' || :BDCOLCON || ' AND ' ||
                       '      trab.BDDATAFIMPRAZO2COL between ' || :WDATAINICIAL || ' AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASCONTRATODETERMINADO2 || ')';
    
               FOR EXECUTE STATEMENT wsql2 INTO :BDDATAVENC DO
                  begin
                    WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);
    
                    BDTIPOALERTA = 3;
                    BDTIPO = 2;
                    BDCAMINHO = 'Cadastros / Contrato de trabalho / Temporário / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON;
    
                    if (BDDATAVENC < WDATAPARAM) then
                       BDDESCRICAO = 'O colaborador está com a prorrogação do contrato de trabalho temporário vencido. ';
                    else
                       BDDESCRICAO = 'O colaborador está com a prorrogação do contrato de trabalho temporário para vencer nos próximos dias. ';
    
                    BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                 'Dias de antecedência para alertar: ' || WDIASCONTRATODETERMINADO2 || '. ' ||
                                                 'Data do alerta: ' || WDATA || '.';
    
                    BDCADASTRO = 16;
                    BDCHAVECAD = BDCODEMP || '.' || BDCOLCON;
                    BDCAMPO = 'DTDATAFIMPRAZO2COL';
    
                    suspend;
                  end
             end
    
          if (coalesce(WCONTRATOEXPERIENCIAPRI,'FALSE') = 'TRUE') then
             begin
               wsql2 = 'SELECT BDDATAFIMPRAZO1COL FROM VRH_EMP_TCOL_ADM ' ||
                       'where bdcodemp = ' || :BDCODEMP || ' and bdcodcol = ' || :BDCOLCON || ' and ' ||
                    --'      BDDATAFIMPRAZO1COL between ADDDAY(''' || :PRDATA || ''', 0) AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASCONTRATOEXPERIENCIAPRI || ')'; --#164935 LuizCovre 21/07/2022
                       ' BDDATAFIMPRAZO1COL between ADDDAY(''' || :PRDATA || ''', ' || '-' || :WDIASAFASTAMENTOESTABILIDADE || ') and ADDDAY(''' || :PRDATA || ''', ' || :WDIASAFASTAMENTOESTABILIDADE || ')';--#164935 LuizCovre 21/07/2022
    
               FOR EXECUTE STATEMENT wsql2 INTO :BDDATAVENC DO
                  begin
                    WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);
    
                    BDTIPOALERTA = 4;
                    BDTIPO = 3;
                    BDCAMINHO = 'Cadastros / Colaboradores / Admissão completa / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON ||
                                ' / Aba: "Contratuais" / Campo: "Fim prazo experiência"';
    
                    if (BDDATAVENC < WDATAPARAM) then
                       BDDESCRICAO = 'O colaborador está com o fim do prazo de experiência vencido. ';
                    else
                       BDDESCRICAO = 'O colaborador está com o fim do prazo de experiência para vencer nos próximos dias. ';
    
                    BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                 'Dias de antecedência para alertar: ' || WDIASCONTRATOEXPERIENCIAPRI || '. ' ||
                                                 'Data do alerta: ' || WDATA || '.';
                    BDCADASTRO = 4;
                    BDCHAVECAD = BDCODEMP || '.' || BDCOLCON;
                    BDCAMPO = 'DTDATAFIMPRAZO1COL';
    
                    suspend;
                  end
             end
    
          if (coalesce(WCONTRATOEXPERIENCIASEG,'FALSE') = 'TRUE') then
             begin
               wsql2 = 'SELECT BDDATAFIMPRAZO2COL FROM VRH_EMP_TCOL_ADM ' ||
                       'where bdcodemp = ' || :BDCODEMP || ' and bdcodcol = ' || :BDCOLCON || ' and BDDATAFIMPRAZO2COL is not null and ' ||
                     --'      BDDATAFIMPRAZO1COL between ADDDAY(''' || :PRDATA || ''', 0) AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASCONTRATOEXPERIENCIASEG || ')';   #164935 LuizCovre 21/07/2022
                       '      BDDATAFIMPRAZO2COL between ADDDAY(''' || :PRDATA || ''', 0) AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASCONTRATOEXPERIENCIASEG || ')'; --#164935 LuizCovre 21/07/2022
               FOR EXECUTE STATEMENT wsql2 INTO :BDDATAVENC DO
                  begin
                    WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);
    
                    BDTIPOALERTA = 5;
                    BDTIPO = 3;
                    BDCAMINHO = 'Cadastros / Colaboradores / Admissão completa / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON ||
                                ' / Aba: "Contratuais" / Campo: "Fim prorrogação experiência"';
    
                    if (BDDATAVENC < WDATAPARAM) then
                       BDDESCRICAO = 'O colaborador está com o fim da prorrogação da experiência vencido. ';
                    else
                       BDDESCRICAO = 'O colaborador está com o fim da prorrogação da experiência para vencer nos próximos dias. ';
    
                    BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                 'Dias de antecedência para alertar: ' || WDIASCONTRATOEXPERIENCIASEG || '. ' ||
                                                 'Data do alerta: ' || WDATA || '.';
                    BDCADASTRO = 4;
                    BDCHAVECAD = BDCODEMP || '.' || BDCOLCON;
                    BDCAMPO = 'DTDATAFIMPRAZO2COL';
    
                    suspend;
                  end
             end
    
          if (coalesce(WCONTRATOAPRENDIZ,'FALSE') = 'TRUE' and wcatcol = 103) then
             begin
               wsql2 = 'SELECT trab.BDFIMCONTRATO FROM VRH_EMP_TCOLCON_APRENDIZ trab ' ||
                       'where trab.bdcodemp = ' || :BDCODEMP || ' AND trab.bdcodcol = ' || :BDCOLCON || ' AND ' ||
                       '      trab.BDFIMCONTRATO between ' || :WDATAINICIAL || ' AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASCONTRATOAPRENDIZ || ')';
    
               FOR EXECUTE STATEMENT wsql2 INTO :BDDATAVENC DO
                  begin
                    WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);
    
                    BDTIPOALERTA = 6;
                    BDTIPO = 2;
                    BDCAMINHO = 'Cadastros / Colaboradores / Admissão completa / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON ||
                                ' / Botão: "Aprendiz"';
    
                    if (BDDATAVENC < WDATAPARAM) then
                       BDDESCRICAO = 'O colaborador está com o fim do contrato de aprendizagem vencido. ';
                    else
                       BDDESCRICAO = 'O colaborador está com o fim do contrato de aprendizagem para vencer nos próximos dias. ';
    
                    BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                 'Dias de antecedência para alertar: ' || WDIASCONTRATOAPRENDIZ || '. ' ||
                                                 'Data do alerta: ' || WDATA || '.';
                    BDCADASTRO = 4;
                    BDCHAVECAD = BDCODEMP || '.' || BDCOLCON;
                    BDCAMPO = 'EDINICIOCONTRATO';
    
                    suspend;
                  end
             end
    
          if (coalesce(WCONTRATOESTAGIO,'FALSE') = 'TRUE' and wcatcol = 901) then
             begin
               wsql2 = 'SELECT trab.BDCODEST, trab.BDDATATERMEST FROM VRH_EMP_TCOLCON_ESTAGIO trab ' ||
                       'where trab.bdcodemp = ' || :BDCODEMP || ' AND trab.bdcodcol = ' || :BDCOLCON || ' AND ' ||
                       '      trab.BDCODEST = (select max(BDCODEST) from VRH_EMP_TCOLCON_ESTAGIO where bdcodemp = trab.bdcodemp and bdcodcol = trab.bdcodcol) and ' ||
                       '      trab.BDDATATERMEST between ' || :WDATAINICIAL || ' AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASCONTRATOESTAGIO || ')';
    
               FOR EXECUTE STATEMENT wsql2 INTO :WCODIGO, :BDDATAVENC DO
                  begin
                    WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);
    
                    BDTIPOALERTA = 7;
                    BDTIPO = 2;
                    BDCAMINHO = 'Cadastros / Contrato de trabalho / Estágio / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON ||
                                ' / Código ' || WCODIGO;
    
                    if (BDDATAVENC < WDATAPARAM) then
                       BDDESCRICAO = 'O colaborador está com o término do contrato de estágio vencido. ';
                    else
                       BDDESCRICAO = 'O colaborador está com o término do contrato de estágio prevista para vencer nos próximos dias. ';
    
                    BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                 'Dias de antecedência para alertar: ' || WDIASCONTRATOESTAGIO || '. ' ||
                                                 'Data do alerta: ' || WDATA || '.';
                    BDCADASTRO = 10;
                    BDCHAVECAD = BDCODEMP || '.' || BDCOLCON || '.' || WCODIGO;
                    BDCAMPO = 'EDDATATERMEST';
    
                    suspend;
                  end
             end
    
          if (coalesce(WCNHCOLCON,'FALSE') = 'TRUE') then
             begin
               wsql2 = 'SELECT col.BDVENCCNHCOL from (select first 1 BDCODEMP, BDCODCOL, BDVENCCNHCOL '||
                                                     'from VRH_EMP_TCOLCON_DOCREF '||
                                                     'where BDCODEMP = '||:BDCODEMP||' and BDCODCOL = '||:BDCOLCON||' and BDREFCOL <= '||:wref||' order by BDREFCOL DESC) col ' ||
                       'inner join (select first 1 BDCODEMP, BDCODCOL, BDCODPLAFUC, BDCODTFUC '||
                                   'from VRH_EMP_TCOL_VINCDIA '||
                                   'where  BDCODEMP = '||:BDCODEMP||' and BDCODCOL = '||:BDCOLCON||' and BDDATACOL <= '''||prdata||''' order by BDDATACOL DESC) VINC ON (VINC.BDCODEMP = COL.BDCODEMP AND VINC.BDCODCOL = COL.BDCODCOL) ' ||
                       'inner join VRH_FUNCOES_TFUC TFUC on (TFUC.BDCODPLAFUC = VINC.BDCODPLAFUC and TFUC.BDCODTFUC = VINC.BDCODTFUC) ' ||
                       'inner join VRH_BASE_TCBO CBO on (CBO.BDCODCBO = TFUC.BDCODCBO) ' ||
                       'where col.bdcodemp = ' || :BDCODEMP || ' and col.bdcodcol = ' || :BDCOLCON || ' and coalesce(CBO.BDCNHOBRIGATORIA, ''FALSE'') = ''FALSE'' and ' ||
                       '      col.BDVENCCNHCOL between ' || :WDATAINICIAL || ' AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASCNHCOLCON || ')';
    
               FOR EXECUTE STATEMENT wsql2 INTO :BDDATAVENC DO
                  begin
                    WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);
    
                    BDTIPOALERTA = 9;
                    BDTIPO = 2;
    
                    if (WCONTRCOL = 0) then
                       begin
                         BDCAMINHO = 'Cadastros / Colaboradores / Admissão completa / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON ||
                                     ' / Aba: "Documentos" / Aba: "Principal" / Campo: "Vencimento da CNH"';
    
                         if (BDDATAVENC < WDATAPARAM) then
                            BDDESCRICAO = 'O colaborador está com a CNH vencida. ';
                         else
                            BDDESCRICAO = 'O colaborador está com a CNH para vencer nos próximos dias. ';
    
                         BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                      'Dias de antecedência para alertar: ' || WDIASCNHCOLCON || '. ' ||
                                                      'Data do alerta: ' || WDATA || '.';
    
                         BDCADASTRO = 4;
                         BDCHAVECAD = BDCODEMP || '.' || BDCOLCON;
                         BDCAMPO = 'DTVENCCNHCOL';
                       end
                    else
                       begin
                         BDCAMINHO = 'Cadastros / Contribuintes / Empresa ' || BDCODEMP || ' - Contribuinte ' || BDCOLCON || ': ' || WNOMECOLCON ||
                                     ' / Aba: "Documentos" / Aba: "Principal" / Campo: "Vencimento da CNH"';
    
                         if (BDDATAVENC < WDATAPARAM) then
                            BDDESCRICAO = 'O contribuinte está com a CNH vencida. ';
                         else
                            BDDESCRICAO = 'O contribuinte está com a CNH para vencer nos próximos dias. ';
    
                         BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                      'Dias de antecedência para alertar: ' || WDIASCNHCOLCON || '. ' ||
                                                      'Data do alerta: ' || WDATA || '.';
    
                         BDCADASTRO = 13;
                         BDCHAVECAD = BDCODEMP || '.' || BDCOLCON;
                         BDCAMPO = 'DTVENCCNHCOL';
                       end
    
                    suspend;
                  end
             end
    
          if (coalesce(WCNHMOTORISTA,'FALSE') = 'TRUE') then
             begin
               wsql2 = 'SELECT col.BDVENCCNHCOL from (select first 1 BDCODEMP, BDCODCOL, BDVENCCNHCOL '||
                                                     'from VRH_EMP_TCOLCON_DOCREF '||
                                                     'where BDCODEMP = '||:BDCODEMP||' and BDCODCOL = '||:BDCOLCON||' and BDREFCOL <= '||:wref||' order by BDREFCOL DESC) col ' ||
                       'inner join (select first 1 BDCODEMP, BDCODCOL, BDCODPLAFUC, BDCODTFUC '||
                                   'from VRH_EMP_TCOL_VINCDIA '||
                                   'where  BDCODEMP = '||:BDCODEMP||' and BDCODCOL = '||:BDCOLCON||' and BDDATACOL <= '''||prdata||''' order by BDDATACOL DESC) VINC ON (VINC.BDCODEMP = COL.BDCODEMP AND VINC.BDCODCOL = COL.BDCODCOL) ' ||
                       'inner join VRH_FUNCOES_TFUC TFUC on (TFUC.BDCODPLAFUC = VINC.BDCODPLAFUC and TFUC.BDCODTFUC = VINC.BDCODTFUC) ' ||
                       'inner join VRH_BASE_TCBO CBO on (CBO.BDCODCBO = TFUC.BDCODCBO) ' ||
                       'where col.bdcodemp = ' || :BDCODEMP || ' and col.bdcodcol = ' || :BDCOLCON || ' and coalesce(CBO.BDCNHOBRIGATORIA, ''FALSE'') = ''FALSE'' and ' ||
                       '      col.BDVENCCNHCOL between ' || :WDATAINICIAL || ' AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASCNHMOTORISTA || ')';

               FOR EXECUTE STATEMENT wsql2 INTO :BDDATAVENC DO
                  begin
                    WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);
    
                    BDTIPOALERTA = 10;
                    BDTIPO = 2;
    
                    if (WCONTRCOL = 0) then
                       begin
                         BDCAMINHO = 'Cadastros / Colaboradores / Admissão completa / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON ||
                                     ' / Aba: "Documentos" / Aba: "Principal" / Campo: "Vencimento da CNH"';
    
                         if (BDDATAVENC < WDATAPARAM) then
                            BDDESCRICAO = 'O colaborador está com a CNH vencida. ';
                         else
                            BDDESCRICAO = 'O colaborador está com a CNH para vencer nos próximos dias. ';
    
                         BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                      'Dias de antecedência para alertar: ' || WDIASCNHMOTORISTA || '. ' ||
                                                      'Data do alerta: ' || WDATA || '.';
                         BDCADASTRO = 4;
                         BDCHAVECAD = BDCODEMP || '.' || BDCOLCON;
                         BDCAMPO = 'DTVENCCNHCOL';
                       end
                    else
                       begin
                         BDCAMINHO = 'Cadastros / Contribuintes / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON ||
                                     ' / Aba: "Documentos" / Aba: "Principal" / Campo: "Vencimento da CNH"';
    
                         if (BDDATAVENC < WDATAPARAM) then
                            BDDESCRICAO = 'O contribuinte está com a CNH vencida. ';
                         else
                            BDDESCRICAO = 'O contribuinte está com a CNH para vencer nos próximos dias. ';
    
                         BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                      'Dias de antecedência para alertar: ' || WDIASCNHMOTORISTA || '. ' ||
                                                      'Data do alerta: ' || WDATA || '.';
                         BDCADASTRO = 13;
                         BDCHAVECAD = BDCODEMP || '.' || BDCOLCON;
                         BDCAMPO = 'DTVENCCNHCOL';
                       end
    
                    suspend;
                  end
             end
    
          if (coalesce(WORGAOCLASSE,'FALSE') = 'TRUE') then
             begin
               wsql2 = 'SELECT col.BDDATAVALOCCOL from (select first 1 BDCODEMP, BDCODCOL, BDDATAVALOCCOL '||
                                                       'from VRH_EMP_TCOLCON_DOCREF '||
                                                       'where BDCODEMP = '||:BDCODEMP||' and BDCODCOL = '||:BDCOLCON||' and BDREFCOL <= '||wref||' '||
                                                       'order by BDREFCOL DESC) col ' ||
                       'where col.bdcodemp = ' || :BDCODEMP || ' and col.bdcodcol = ' || :BDCOLCON || ' and ' ||
                       '      col.BDDATAVALOCCOL between ' || :WDATAINICIAL || ' AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASORGAOCLASSE || ')';
    
               FOR EXECUTE STATEMENT wsql2 INTO :BDDATAVENC DO
                  begin
                    WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);
    
                    BDTIPOALERTA = 12;
                    BDTIPO = 2;
                    BDCAMINHO = 'Cadastros / Colaboradores / Admissão completa / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON ||
                                ' / Aba: "Documentos" / Aba: "Auxiliar" / Campo: "Validade OC"';
    
                    if (BDDATAVENC < WDATAPARAM) then
                       BDDESCRICAO = 'O colaborador está com a OC vencida. ';
                    else
                       BDDESCRICAO = 'O colaborador está com a OC para vencer nos próximos dias. ';
    
                    BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                 'Dias de antecedência para alertar: ' || WDIASORGAOCLASSE || '. ' ||
                                                 'Data do alerta: ' || WDATA || '.';
    
                    BDCADASTRO = 4;
                    BDCHAVECAD = BDCODEMP || '.' || BDCOLCON;
                    BDCAMPO = 'EDDATAVALOCCOL';
    
                    suspend;
                  end
             end
    
          if (coalesce(WPAGAMENTOFERIAS,'FALSE') = 'TRUE') then
             begin
               wsql2 = 'select fer.bddatapagfe, fer.bdcodfe, fer.bdiniperaquisfe, fer.bdfimperaquisfe from VRH_EMP_TFERIAS fer ' ||
                       'where fer.bdcodemp = ' || :BDCODEMP || ' and fer.bdcodcol = ' || :BDCOLCON || ' and ' ||
                       'fer.bddatapagfe between ADDDAY(''' || :PRDATA || ''', 0) AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASPAGAMENTOFERIAS || ')';
    
               FOR EXECUTE STATEMENT wsql2 INTO :BDDATAVENC, :WCODIGO, WINIPERAQUIFER, WFIMPERAQUIFER DO
                  begin
                    WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);
                    WINIPERAQUIFER = substring(cast(WINIPERAQUIFER as varchar(10)) from 9 for 2)|| '/' ||substring(cast(WINIPERAQUIFER as varchar(10)) from 6 for 2)|| '/' ||substring(cast(WINIPERAQUIFER as varchar(10)) from 1 for 4);
                    WFIMPERAQUIFER = substring(cast(WFIMPERAQUIFER as varchar(10)) from 9 for 2)|| '/' ||substring(cast(WFIMPERAQUIFER as varchar(10)) from 6 for 2)|| '/' ||substring(cast(WFIMPERAQUIFER as varchar(10)) from 1 for 4);

                    BDTIPOALERTA = 15;
                    BDTIPO = 3;
                    BDCAMINHO = 'Cálculos / Férias individual / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON || ' - ' ||
                                'Período aquisito: ' || winiperaquifer || ' até ' || wfimperaquifer || ' - ' || 'Código férias ' || wcodigo;
    
                    if (BDDATAVENC < WDATAPARAM) then
                       BDDESCRICAO = 'O colaborador está com o pagamento de férias vencido. ';
                    else
                       BDDESCRICAO = 'O colaborador está com o pagamento de férias para vencer nos próximos dias. ';
    
                    BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                 'Dias de antecedência para alertar: ' || WDIASPAGAMENTOFERIAS || '. ' ||
                                                 'Data do alerta: ' || WDATA || '.';
                    BDCADASTRO = 17;
                    BDCHAVECAD = BDCODEMP || '.' || BDCOLCON || '.' || winiperaquifer || '.' || wfimperaquifer || '.' || wcodigo;
                    BDCAMPO = 'EDDATAPAGFE';
    
                    suspend;
                  end
             end
    
          if (coalesce(WAVISOPREVIO,'FALSE') = 'TRUE') then
             begin
               wsql2 = 'select res.bddatarescisao from VRH_EMP_TRESCISAO res ' ||
                       'inner join VRH_BASE_TPREPRESC pres on (pres.bdcodpres = res.bdcodpres) ' ||
                       'where res.bdcodemp = ' || :BDCODEMP || ' and res.bdcodcol = ' || :BDCOLCON || ' and pres.bdavprepres = 1 and ' ||
                       'res.bddatarescisao between ADDDAY(''' || :PRDATA || ''', 0) AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASAVISOPREVIO || ')';
    
               FOR EXECUTE STATEMENT wsql2 INTO :BDDATAVENC DO
                  begin
                    WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);
    
                    BDTIPOALERTA = 16;
                    BDTIPO = 3;
                    BDCAMINHO = 'Lançamentos / Rescisões / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON;
    
                    if (BDDATAVENC < WDATAPARAM) then
                       BDDESCRICAO = 'O colaborador está com o aviso prévio vencido. ';
                    else
                       BDDESCRICAO = 'O colaborador está com o aviso prévio para vencer nos próximos dias. ';
    
                    BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                 'Dias de antecedência para alertar: ' || WDIASAVISOPREVIO || '. ' ||
                                                 'Data do alerta: ' || WDATA || '.';
                    BDCADASTRO = 15;
                    BDCHAVECAD = BDCODEMP || '.' || BDCOLCON;
                    BDCAMPO = 'EDDATARESCISAO';
    
                    suspend;
                  end
             end
    
          if (coalesce(WPAGAMENTORESCISAO,'FALSE') = 'TRUE') then
             begin
               wsql2 = 'select res.bddatapagrescisao from VRH_EMP_TRESCISAO res ' ||
                       'where res.bdcodemp = ' || :BDCODEMP || ' and res.bdcodcol = ' || :BDCOLCON || ' and ' ||
                       'res.bddatapagrescisao between ADDDAY(''' || :PRDATA || ''', 0) AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASPAGAMENTORESCISAO || ')';
    
               FOR EXECUTE STATEMENT wsql2 INTO :BDDATAVENC DO
                  begin
                    WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);
    
                    BDTIPOALERTA = 17;
                    BDTIPO = 3;
                    BDCAMINHO = 'Lançamentos / Rescisões / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON;
    
                    if (BDDATAVENC < WDATAPARAM) then
                       BDDESCRICAO = 'O colaborador está com o pagamento de rescisão vencido. ';
                    else
                       BDDESCRICAO = 'O colaborador está com o pagamento de rescisão para vencer nos próximos dias. ';
    
                    BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                 'Dias de antecedência para alertar: ' || WDIASPAGAMENTORESCISAO || '. ' ||
                                                 'Data do alerta: ' || WDATA || '.';
                    BDCADASTRO = 15;
                    BDCHAVECAD = BDCODEMP || '.' || BDCOLCON;
                    BDCAMPO = 'EDDATAPAGRESCISAO';
    
                    suspend;
                  end
             end
    
          if (coalesce(WAFASTAMENTOESTABILIDADE,'FALSE') = 'TRUE') then
             begin
               wcodsind = null;
               select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCOLCON and BDREFCOL <= :wref order by BDREFCOL desc into :wcodsind;
               wcodsind = coalesce(wcodsind, 0);

               for select first 1 BDESTABST
                   from VRH_BASE_TSINDTREF
                   where BDCODSINTRAB = :wcodsind and BDREFST <= :wref
                   order by BDREFST desc
               into :wdestabsind
               do
                 begin
                   if (coalesce(wdestabsind, 0) > 0) then
                      begin
                      --for select cast((afa.bddatafimsit + :wdestabsind) as date) BDDATAFIM, :wcodsind as BDCHAVE, 1 as BDTIPO #164935 LuizCovre 21/07/2022
                        for select cast((afa.bddataestab) as date) BDDATAFIM, :wcodsind as BDCHAVE, 1 as BDTIPO               --#164935 LuizCovre 21/07/2022
                            from VRH_EMP_TSITCOL afa
                            where afa.bdcodemp = :BDCODEMP and afa.bdcodcol = :BDCOLCON and
                                 (afa.bddataestab) between ADDDAY(:PRDATA, -:WDIASAFASTAMENTOESTABILIDADE) AND ADDDAY(:PRDATA, :WDIASAFASTAMENTOESTABILIDADE) --#164935 LuizCovre 25/07/2022
                               --ADDDAY(:PRDATA, 0) between(afa.bddataestab) and ADDDAY(:PRDATA, :WDIASAFASTAMENTOESTABILIDADE)    --#164935 LuizCovre 21/07/2022
                        into :BDDATAVENC, :WCODIGO, :WTIPO
                        do
                          begin
                            WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);
            
                            BDTIPOALERTA = 18;
                            BDTIPO = 3;
                            BDCAMINHO = 'Cadastros / Sindicato dos trabalhadores / Código ' || WCODIGO ||
                                        ' / Aba: "Dados cálculo" / Campo: "Estabilidade"';
       
                            if (BDDATAVENC < WDATAPARAM) then
                               BDDESCRICAO = 'O colaborador está com estabilidade de afastamento vencido. ';
                            else
                               BDDESCRICAO = 'O colaborador está com estabilidade de afastamento para vencer nos próximos dias. ';
       
                            BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                         'Dias de antecedência para alertar: ' || WDIASAFASTAMENTOESTABILIDADE || '. ' ||
                                                         'Data do alerta: ' || WDATA || '.';
                            BDCADASTRO = 9;
                            BDCHAVECAD = WCODIGO;
                            BDCAMPO = 'EDESTABST';
                            suspend;
                          end

                      end
                   else
                      begin
                        for select estab.bddatafim, estab.bdchave, 2 as BDTIPO
                            from VRH_EMP_TESTABILIDADE estab
                            where estab.bdcodemp = :BDCODEMP and estab.bdcodcol = :BDCOLCON and estab.bddatafim between ADDDAY(:PRDATA, 0) AND ADDDAY(:PRDATA, :WDIASAFASTAMENTOESTABILIDADE)
                        into :BDDATAVENC, :WCODIGO, :WTIPO
                        do
                          begin
                            WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);
            
                            BDTIPOALERTA = 18;
                            BDTIPO = 3;
                            BDCAMINHO = 'Lançamentos / Períodos de estabilidade / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ' - Código ' || WCODIGO;
       
                            if (BDDATAVENC < WDATAPARAM) then
                               BDDESCRICAO = 'O colaborador está com estabilidade de afastamento vencido. ';
                            else
                               BDDESCRICAO = 'O colaborador está com estabilidade de afastamento para vencer nos próximos dias. ';
       
                            BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                         'Dias de antecedência para alertar: ' || WDIASAFASTAMENTOESTABILIDADE || '. ' ||
                                                         'Data do alerta: ' || WDATA || '.';
       
                            BDCADASTRO = 18;
                            BDCHAVECAD = BDCODEMP || '.' || BDCOLCON || '.' || WCODIGO;
                            BDCAMPO = 'EDDATAFIM';
                            suspend;
                          end
                      end
                  end
             end
    
          if (coalesce(WANIVERSARIANTES,'FALSE') = 'TRUE') then
             begin
               select COL_NASC.BDDATANASCCOL from VRH_EMP_TCOLCON COL_NASC where COL_NASC.BDCODEMP = :BDCODEMP and COL_NASC.BDCODCOL = :BDCOLCON into wdatanasc;
               wanobisexto = 0;

               if ((extract (month from wdatanasc) = 2) and (extract (day from wdatanasc) = 29)) then
                  select prbisexto from ANO_BISEXTO(extract(year from :wdatanasc)) into wanobisexto;

               if (wanobisexto = 1) then --Quando o aniversariante é dia 29 de fev da erro nesses case when, isso quando faz comparação com ano que não é bisexto
                 begin
                   wsql2 = 'select ' ||
                           '       case ' ||
                           '         when cast(''28.'' || extract(month from COL.BDDATANASCCOL) || ''.'' || extract(year from cast(''' || :PRDATA || ''' as date)) as date) > cast(''' || :PRDATA || ''' as date) then ' ||
                           '              cast(''28.'' || extract(month from COL.BDDATANASCCOL) || ''.'' || extract(year from cast(''' || :PRDATA || ''' as date)) as date) else ' ||
                           '              cast(''28.'' || extract(month from COL.BDDATANASCCOL) || ''.'' || extract(year from ADDDAY(''' || :PRDATA || ''', 365)) as date) ' ||
                           '       end ' ||
                           'from VRH_EMP_TCOLCON col ' ||
                           'where col.bdcodemp = ' || :BDCODEMP || ' and col.bdcodcol = ' || :BDCOLCON || ' and ' ||
                           '       case ' ||
                           '         when cast(''28.'' || extract(month from COL.BDDATANASCCOL) || ''.'' || extract(year from cast(''' || :PRDATA || ''' as date)) as date) > cast(''' || :PRDATA || ''' as date) then ' ||
                           '              cast(''28.'' || extract(month from COL.BDDATANASCCOL) || ''.'' || extract(year from cast(''' || :PRDATA || ''' as date)) as date) else ' ||
                           '              cast(''28.'' || extract(month from COL.BDDATANASCCOL) || ''.'' || extract(year from ADDDAY(''' || :PRDATA || ''', 365)) as date) ' ||
                           '       end between ADDDAY(''' || :PRDATA || ''', 0) AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASANIVERSARIANTES || ')'; 
                 end
               else
                 begin
                   wsql2 = 'select ' ||
                           '       case ' ||
                           '         when cast(extract(day from COL.BDDATANASCCOL) || ''.'' || extract(month from COL.BDDATANASCCOL) || ''.'' || extract(year from cast(''' || :PRDATA || ''' as date)) as date) > cast(''' || :PRDATA || ''' as date) then ' ||
                           '              cast(extract(day from COL.BDDATANASCCOL) || ''.'' || extract(month from COL.BDDATANASCCOL) || ''.'' || extract(year from cast(''' || :PRDATA || ''' as date)) as date) else ' ||
                           '              cast(extract(day from COL.BDDATANASCCOL) || ''.'' || extract(month from COL.BDDATANASCCOL) || ''.'' || extract(year from ADDDAY(''' || :PRDATA || ''', 365)) as date) ' ||
                           '       end ' ||
                           'from VRH_EMP_TCOLCON col ' ||
                           'where col.bdcodemp = ' || :BDCODEMP || ' and col.bdcodcol = ' || :BDCOLCON || ' and ' ||
                           '       case ' ||
                           '         when cast(extract(day from COL.BDDATANASCCOL) || ''.'' || extract(month from COL.BDDATANASCCOL) || ''.'' || extract(year from cast(''' || :PRDATA || ''' as date)) as date) > cast(''' || :PRDATA || ''' as date) then ' ||
                           '              cast(extract(day from COL.BDDATANASCCOL) || ''.'' || extract(month from COL.BDDATANASCCOL) || ''.'' || extract(year from cast(''' || :PRDATA || ''' as date)) as date) else ' ||
                           '              cast(extract(day from COL.BDDATANASCCOL) || ''.'' || extract(month from COL.BDDATANASCCOL) || ''.'' || extract(year from ADDDAY(''' || :PRDATA || ''', 365)) as date) ' ||
                           '       end between ADDDAY(''' || :PRDATA || ''', 0) AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASANIVERSARIANTES || ')';
                 end
               FOR EXECUTE STATEMENT wsql2 INTO :BDDATAVENC DO
                  begin
                    WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);

                    BDTIPOALERTA = 19;
                    BDTIPO = 3;
                    if (WCONTRCOL = 0) then
                        begin
                          BDCAMINHO = 'Cadastros / Colaboradores / Admissão completa / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON ||
                                     ' / Aba: "Admissionais/Histórico" / Campo: "Data de nascimento"';
    
                          if (BDDATAVENC < WDATAPARAM) then
                             BDDESCRICAO = 'O colaborador esteve de aniversário. ';
                          else
                             BDDESCRICAO = 'O colaborador está de aniversário nos próximos dias. ';
    
                          BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                       'Dias de antecedência para alertar: ' || WDIASANIVERSARIANTES || '. ' ||
                                                       'Data do alerta: ' || WDATA || '.';
                          BDCADASTRO = 4;
                        end
                     else
                        begin
                          BDCAMINHO = 'Cadastros / Contribuintes / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON ||
                                     ' / Aba: "Adicionais" / Campo: "Data de nascimento"';
    
                          if (BDDATAVENC < WDATAPARAM) then
                             BDDESCRICAO = 'O contribuinte esteve de aniversário. ';
                          else
                             BDDESCRICAO = 'O contribuinte está de aniversário nos próximos dias. ';
    
                          BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                       'Dias de antecedência para alertar: ' || WDIASANIVERSARIANTES || '. ' ||
                                                       'Data do alerta: ' || WDATA || '.';
                          BDCADASTRO = 13;
                        end
    
                    BDCHAVECAD = BDCODEMP || '.' || BDCOLCON;
                    BDCAMPO = 'DTDATANASCCOL';
    
                    suspend;
                  end
             end
    
      if (coalesce(WDISSIDIOCOLETIVO,'FALSE') = 'TRUE') then
         begin
           wcodsind = 0;
           select BDCODSINTRAB from VRH_EMP_TCOL_VINC where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCOLCON and BDREFCOL = (select max(BDREFCOL) from vrh_emp_tcol_vinc where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCOLCON and BDREFCOL <= :wref)
           into :wcodsind;

           if ((wcodsind is not null) and (wcodsind <> 0)) then
           begin
               for select BDCODSINTRAB
                   from (select BDCODCOL, BDCODSINTRAB, max(BDREFCOL) BDREFCOL
                         from VRH_EMP_TCOL_VINC
                         where BDCODEMP = :BDCODEMP and BDCODSINTRAB is not null and BDREFCOL <= :wref
                         group by BDCODCOL, BDCODSINTRAB
                   )
                   group by BDCODSINTRAB
               into :wcodsind
               do
                  begin
                   for select BDDATABASE
                       from (select first 1
                                case when cast((substring(lpad(BDDATBASEST, 4, '0') from 1 for 2)||'.'||substring(lpad(BDDATBASEST, 4, '0') from 3 for 2)||'.'||substring(:prdata from 7 for 4)) as date) > cast(:prdata as date)
                                  then cast((substring(lpad(BDDATBASEST, 4, '0') from 1 for 2)||'.'||substring(lpad(BDDATBASEST, 4, '0') from 3 for 2)||'.'||substring(:prdata from 7 for 4)) as date)
                                  else cast((substring(lpad(BDDATBASEST, 4, '0') from 1 for 2)||'.'||substring(lpad(BDDATBASEST, 4, '0') from 3 for 2)||'.'||extract(year from ADDDAY(:PRDATA, :WDIASDISSIDIOCOLETIVO))) as date)
                                end bddatabase
                             from VRH_BASE_TSINDTREF
                             where BDCODSINTRAB = :wcodsind and BDREFST <= :wref and coalesce(BDDATBASEST, 0) > 0 and BDDATBASEST<>100
                             order by BDREFST desc
                             )
                   where BDDATABASE between ADDDAY(:PRDATA , 0) AND ADDDAY(:PRDATA, :WDIASDISSIDIOCOLETIVO)
                   into :BDDATAVENC
                   do
                     begin
                    WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);
    
                    BDTIPOALERTA = 22;
                    BDTIPO = 3;
                    BDCAMINHO = 'Cadastros / Sindicato dos trabalhadores / Código ' || WCODSIND ||
                                ' / Aba: "Dados cálculo" / Campo: "Data base (dd/mm)"';
       
                    if (BDDATAVENC < WDATAPARAM) then
                       BDDESCRICAO = 'O sindicato dos trabalhadores está com a data base vencida. ';
                    else
                       BDDESCRICAO = 'O sindicato dos trabalhadores está com a data base para vencer nos próximos dias. ';
       
                    BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                 'Dias de antecedência para alertar: ' || WDIASDISSIDIOCOLETIVO || '. ' ||
                                                 'Data do alerta: ' || WDATA || '.';
                    BDCADASTRO = 9;
       
       
                    BDCHAVECAD = WCODSIND||'.'||BDCODEMP;
                    BDCAMPO = 'EDDATBASEST';
       
                       suspend;
                     end
                 end
           end
         end
      end
    
          if (coalesce(WANIVERSARIOEMPRESA,'FALSE') = 'TRUE') then
             begin
               wsql2 =
                       'select ' ||
                       '       case ' ||
                       '         when cast(extract(day from COL.bddataadmcol) || ''.'' || extract(month from COL.bddataadmcol) || ''.'' || extract(year from cast(''' || :PRDATA || ''' as date)) as date) > cast(''' || :PRDATA || ''' as date) then ' ||
                       '              cast(extract(day from COL.bddataadmcol) || ''.'' || extract(month from COL.bddataadmcol) || ''.'' || extract(year from cast(''' || :PRDATA || ''' as date)) as date) else ' ||
                       '              cast(extract(day from COL.bddataadmcol) || ''.'' || extract(month from COL.bddataadmcol) || ''.'' || extract(year from ADDDAY(''' || :PRDATA || ''', 365)) as date) ' ||
                       '       end ' ||
                       'from VRH_EMP_TCOLCON col ' ||
                       'left join VRH_EMP_TRESCISAO resc on (resc.bdcodemp = col.bdcodemp and resc.bdcodcol = col.bdcodcol) ' ||
                       'where col.bdcodemp = ' || :BDCODEMP || ' and col.bdcodcol = ' || :BDCOLCON || ' and ' ||
                       '       case ' ||
                       '         when cast(extract(day from COL.bddataadmcol) || ''.'' || extract(month from COL.bddataadmcol) || ''.'' || extract(year from cast(''' || :PRDATA || ''' as date)) as date) > cast(''' || :PRDATA || ''' as date) then ' ||
                       '              cast(extract(day from COL.bddataadmcol) || ''.'' || extract(month from COL.bddataadmcol) || ''.'' || extract(year from cast(''' || :PRDATA || ''' as date)) as date) else ' ||
                       '              cast(extract(day from COL.bddataadmcol) || ''.'' || extract(month from COL.bddataadmcol) || ''.'' || extract(year from ADDDAY(''' || :PRDATA || ''', 365)) as date) ' ||
                       '       end between ADDDAY(''' || :PRDATA || ''', 0) AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASANIVERSARIOEMPRESA || ') and ' ||
                       '((resc.bddatarescisao >= cast(''' || :PRDATA || ''' as date)) or (resc.bddatarescisao is null))';
    
               FOR EXECUTE STATEMENT wsql2 INTO :BDDATAVENC DO
                  begin
                    WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);

                    BDTIPOALERTA = 20;
                    BDTIPO = 3;
                    if (WCONTRCOL = 0) then
                        begin
                          BDCAMINHO = 'Cadastros / Colaboradores / Admissão completa / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON ||
                                      ' / Aba: "Admissionais/Histórico" / Campo: "Data de admissão"';
    
                          if (BDDATAVENC < WDATAPARAM) then
                             BDDESCRICAO = 'O colaborador esteve de aniversário por tempo de serviço. ';
                          else
                             BDDESCRICAO = 'O colaborador está de aniversário por tempo de serviço nos próximos dias. ';
    
                          BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                       'Dias de antecedência para alertar: ' || WDIASANIVERSARIOEMPRESA || '. ' ||
                                                       'Data do alerta: ' || WDATA || '.';
                          BDCADASTRO = 4;
                        end
                     else
                        begin
                          BDCAMINHO = 'Cadastros / Contribuintes / Empresa ' || BDCODEMP || ' - Colaborador ' || BDCOLCON || ': ' || WNOMECOLCON ||
                                     ' / Aba: "Adicionais" / Campo: "Data de entrada"';
    
                          if (BDDATAVENC < WDATAPARAM) then
                             BDDESCRICAO = 'O contribuinte esteve de aniversário por tempo de serviço. ';
                          else
                             BDDESCRICAO = 'O contribuinte está de aniversário por tempo de serviço nos próximos dias. ';
    
                          BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                                       'Dias de antecedência para alertar: ' || WDIASANIVERSARIANTES || '. ' ||
                                                       'Data do alerta: ' || WDATA || '.';
                          BDCADASTRO = 13;
                        end
    
                    BDCHAVECAD = BDCODEMP || '.' || BDCOLCON;
                    BDCAMPO = 'DTDATAADMCOL';
    
                    suspend;
                  end
             end


      if (coalesce(WCERTIFICADODIGITAL,'FALSE') = 'TRUE') then
         begin
           wsql2 = 'select cad.bdcodigo, cad.bdsubjectname, cad.bddatadevalidade from TCADCERTIFICADO cad ' ||
                   'inner join TCADCERTIFICADOVINC vinc on (vinc.bdcodigo = cad.bdcodigo) ' ||
                   'where vinc.bdcodemp = ' || :BDCODEMP || ' and vinc.bdcodigo = (select max(bdcodigo) from TCADCERTIFICADOVINC where BDCODEMP = vinc.BDCODEMP) and ' ||
                   '      cad.bddatadevalidade between ' || :WDATAINICIAL || ' AND ADDDAY(''' || :PRDATA || ''', ' || :WDIASCERTIFICADODIGITAL || ')';


           FOR EXECUTE STATEMENT wsql2 INTO :WCODIGO, :WSTR, :BDDATAVENC DO
              begin
                WDATAVENC = substring(cast(BDDATAVENC as varchar(10)) from 9 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 6 for 2)|| '/' ||substring(cast(BDDATAVENC as varchar(10)) from 1 for 4);

                BDCOLCON = 0;
                BDTIPOALERTA = 21;
                BDTIPO = 2;
                BDCAMINHO = 'Configurações / Configuração WEB / Configuração de certificados digitais / Código ' || wcodigo;

                if (BDDATAVENC < WDATAPARAM) then
                   BDDESCRICAO = 'A empresa está com certificado digital vencido. ';
                else
                   BDDESCRICAO = 'A empresa está com certificado digital para vencer nos próximos dias. ';

                BDDESCRICAO = BDDESCRICAO || 'Data de vencimento: ' || WDATAVENC || '. ' ||
                                             'Dias de antecedência para alertar: ' || WDIASCERTIFICADODIGITAL || '. ' ||
                                             'Data do alerta: ' || WDATA || '.';
                BDCADASTRO = 14;
                BDCHAVECAD = wcodigo;
                BDCAMPO = 'EDVENCIMENTO';

                suspend;
              end
         end
                 end
end^

CREATE OR ALTER trigger tmp_tdarf_ret_temp_bi0 for tmp_tdarf_ret_temp
active before insert position 0
AS
declare variable wOrd INTEGER;
begin
  SELECT COUNT(BDORD) + 1 FROM TMP_TDARF_RET_TEMP INTO :wOrd;

  NEW.BDORD = COALESCE(:wOrd, 1);
end^

CREATE OR ALTER procedure SP_SET_EMPRESAS_DARF_RETENCAO (
    PRCODEMP integer)
as
declare variable WCONSOLIDARMATRIZFILIAL DM_BOOLEAN;
BEGIN
  DELETE FROM TMP_TDARF_RET_TEMP;
  
  SELECT BDVALOR
  FROM TPARGER
  WHERE BDCAMPO = 'BDCONSOLIDARMATRIZFILIAL'
  INTO :wConsolidarMatrizFilial;

  wConsolidarMatrizFilial = UPPER(COALESCE(:wConsolidarMatrizFilial, 'FALSE'));

  INSERT INTO TMP_TDARF_RET_TEMP(BDCODEMP) VALUES(:PRCODEMP);
  IF (:wConsolidarMatrizFilial = 'TRUE') THEN
    BEGIN
      INSERT INTO TMP_TDARF_RET_TEMP(BDCODEMP)
      SELECT BDCODEMP
      FROM TEMPRESAS
      WHERE BDCODMATRIZ = :PRCODEMP;
    END
END^

CREATE OR ALTER PROCEDURE SP_FILTER_EMP_DARF_RET (
    PREDITEMP INTEGER,
    PRCODEMP INTEGER)
RETURNS (
    BDFILTER DM_BOOLEAN)
AS
DECLARE VARIABLE WFILIAL INTEGER;
DECLARE VARIABLE WCONSOLIDARMATRIZFILIAL DM_BOOLEAN;
BEGIN
  BDFILTER = 'TRUE';

  IF (:PRCODEMP <> :PREDITEMP) THEN
    BEGIN
      SELECT BDVALOR
      FROM TPARGER
      WHERE BDCAMPO = 'BDCONSOLIDARMATRIZFILIAL'
      INTO :wConsolidarMatrizFilial;
    
      wConsolidarMatrizFilial = UPPER(COALESCE(:wConsolidarMatrizFilial, 'FALSE'));

      IF (:wConsolidarMatrizFilial = 'TRUE') THEN
        BEGIN
          SELECT BDCODEMP
          FROM TEMPRESAS
          WHERE BDCODMATRIZ = :PREDITEMP
          AND BDCODEMP = :PRCODEMP
          INTO :wFilial;

          IF (ROW_COUNT = 0) THEN
            BDFILTER = 'FALSE';
        END
      ELSE
        BDFILTER = 'FALSE';
    END

  SUSPEND;
END^

CREATE OR ALTER procedure CARREGAR_EMPRESAS_DARF_RET (
    PRCODEMP integer)
as
declare variable WCODEMP integer;
declare variable WCODMATRIZ integer;
BEGIN
  DELETE FROM TMP_TEMPRESAS;

  SELECT E.BDCODMATRIZ
  FROM TEMPRESAS E
  WHERE E.BDCODEMP = :PRCODEMP
  INTO :wCodMatriz;

  wCodEmp = IIF(:wCodMatriz IS NULL, :PRCODEMP, :wCodMatriz);

  INSERT INTO TMP_TEMPRESAS(BDCODEMP) VALUES(:wCodEmp);

  INSERT INTO TMP_TEMPRESAS(BDCODEMP)
  SELECT E.BDCODEMP
  FROM TEMPRESAS E
  WHERE E.BDCODMATRIZ = :wCodEmp;
END^

/* Restore proc. body: SP_VRH_CONS_NOVO_MV */
CREATE OR ALTER procedure SP_VRH_CONS_NOVO_MV (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRTIPOCALC integer = 0)
returns (
    BDCODEMP varchar(20),
    BDCODCOL varchar(30),
    BDNOMEMP DM_BDNOMEMP,
    BDNOMCOL DM_BDNOMCOL,
    BDBINSSFN numeric(18,6),
    BDINSSFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDINSS13FN numeric(18,6))
as
declare variable WEMP integer;
declare variable WCOL integer;
declare variable WTERC integer;
declare variable WBINSS numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WCNPJ DM_CNPJ_CPF;
declare variable WTEMRESCISAO DM_BOOLEAN;
begin
  for select BDCODEMPVINC, BDCODCOLVINC, BDCODTERVINC, BDBASEINSSNCOL, BDVALORINSSNCOL, BDCNPJRESP
      from VRHF_EMP_TCOLCON_MVINC
      where BDCODEMP = :premp and
            BDCODCOL = :prcol and
            BDTIPOCALC = :prtipocalc and
            BDREFCOL <= :prref and
            ((coalesce(BDREFFIM, 0) >= :prref) or (coalesce(BDREFFIM, 0) = 0))
  into :wemp, :wcol, :wterc, :wbinss, :winss, :wcnpj
  do
    begin
      WTEMRESCISAO = 'FALSE';

      -- Rescisão
      if (coalesce(wemp,  0) > 0 and coalesce(wcol, 0) > 0) then
         begin
           for select FN.BDCODEMP, FN.BDCODCOL, FN.BDBINSSFN, FN.BDINSSFN, FN.BDBINSS13FN, FN.BDINSS13FN
               from (
                  SELECT
                    Y.BDCODEMP,
                    Y.BDCODCOL,
                    Y.BDREFFN BDREF,
                    Y.BDBINSSFN, -- + Y.BDBINSS13FN BDBINSSFN,
                    Y.BDINSSFN,  -- + Y.BDINSS13FN BDINSSFN,
                    Y.BDBINSS13FN /*0.0*/ BDBINSS13FN,
                    Y.BDINSS13FN  /*0.0*/ BDINSS13FN,
                    0.0 BDBASEINSSC13,
                    0.0 BDINSSC13,
                    0 BDTIPO
                  FROM VRHF_EMP_TFOLHANORMAL Y
                  where y.BDCODEMP = :wemp and y.BDCODCOL = :wcol and y.BDREFFN = :prref
                  UNION
                  SELECT
                    x.bdcodemp,
                    x.bdcodcol,
                    x.bdreftomador BDREF,
                    SUM(x.bdbinssft) /*+ SUM(x.bdbinss13ft)*/ BDBINSSFN,
                    SUM(x.bdinssft)  /*+ SUM(x.bdbinss13ft)*/ BDINSSFN,
                    SUM(x.bdbinss13ft) /*0.0*/ BDBINSS13FN,
                    SUM(x.bdinss13ft) /*0.0*/ BDINSS13FN,
                    0.0 BDBASEINSSC13,
                    0.0 BDINSSC13,
                    0 BDTIPO
                  FROM vrhf_emp_tfolhatomador x
                  where x.BDCODEMP = :wemp and x.BDCODCOL = :wcol and x.BDREFTOMADOR = :prref
                  GROUP BY x.bdcodemp, x.bdcodcol, x.bdreftomador
                  UNION
                  SELECT
                    Y.BDCODEMP,
                    Y.BDCODCOL,
                    Y.BDREFFN BDREF,
                    SUM(Y.BDBINSSFN) BDBINSSFN,
                    SUM(Y.BDINSSFN) BDINSSFN,
                    SUM(Y.BDBINSS13FN) BDBINSS13FN,
                    SUM(Y.BDINSS13FN) BDINSS13FN,
                    0.0 BDBASEINSSC13,
                    0.0 BDINSSC13,
                    0 BDTIPO
                  FROM VRHF_EMP_TFOLHAINT Y
                  where y.BDCODEMP = :wemp and y.BDCODCOL = :wcol and y.BDREFFN = :prref
                  GROUP BY  Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN
                  UNION
                  SELECT
                    x.bdcodemp,
                    x.bdcodcol,
                    x.bdreftomador BDREF,
                    SUM(x.bdbinssft) BDBINSSFN,
                    SUM(x.bdinssft) BDINSSFN,
                    SUM(x.bdbinss13ft) BDBINSS13FN,
                    SUM(x.bdinss13ft) BDINSS13FN,
                    0.0 BDBASEINSSC13,
                    0.0 BDINSSC13,
                    0 BDTIPO
                  FROM vrhf_emp_tfolhatomint x
                  where x.BDCODEMP = :wemp and x.BDCODCOL = :wcol and x.BDREFTOMADOR = :prref
                  GROUP BY x.bdcodemp, x.bdcodcol, x.bdreftomador )  FN
               join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FN.BDCODEMP and RESC.BDCODCOL = FN.BDCODCOL and RESC.BDREFRESCISAO = FN.BDREF)
               where FN.BDCODEMP = :wemp and FN.BDCODCOL = :wcol and RESC.BDREFRESCISAO = :prref
           into :BDCODEMP, :BDCODCOL, :BDBINSSFN, :BDINSSFN, :BDBINSS13FN, :BDINSS13FN
           do
             begin
               WTEMRESCISAO = 'TRUE';
               select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :wemp and BDREFEMP <= :prref order by BDREFEMP DESC into :BDNOMEMP;
               select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :wemp and BDCODCOL = :wcol and BDREFCOL <= :prref order by BDREFCOL DESC into :BDNOMCOL;
               suspend;
             end

         end

      if (coalesce(wemp,  0) > 0 and coalesce(wcol, 0) > 0 and WTEMRESCISAO = 'FALSE') then
         begin
           for select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFAUXVFN, FN.BDVALVFN, 0, 0
               from
                  (SELECT
                    FN.BDCODVER,
                    FN.BDCODEMP,
                    FN.BDCODCOL,
                    FN.BDREFFN,
                    FN.BDREFVFN,
                    FN.BDREFAUXVFN,
                    FN.BDVALVFN,
                    FN.BDIGNREFVFN,
                    FN.BDIGNVALVFN
                  FROM VRHF_EMP_TVERBAFN FN
                  where FN.BDCODEMP = :wemp and FN.BDCODCOL = :wcol and FN.BDREFFN = :prref 

                  UNION

                  SELECT
                    FNT.BDCODVER,
                    FNT.BDCODEMP,
                    FNT.BDCODCOL,
                    FNT.BDREFTOMADOR BDREFFN,
                    FNT.BDREFVFT BDREFVFN,
                    FNT.BDREFAUXVFT BDREFAUXVFN,
                    FNT.BDVALVFT BDVALVFN,
                    FNT.BDIGNREFVFT BDIGNREFVFN,
                    FNT.BDIGNVALVFT BDIGNVALVFN
                  FROM VRHF_EMP_TVERBATOMADOR FNT
                  where FNT.BDCODEMP = :wemp and FNT.BDCODCOL = :wcol and FNT.BDREFTOMADOR = :prref
                 ) FN
               join VRH_BASE_TVERBAS V on (V.BDCODVER = FN.BDCODVER)
               where V.BDCLAVER starting with '9.010.0.0'
           into :BDCODEMP, :BDCODCOL, :BDBINSSFN, :BDINSSFN, :BDBINSS13FN, :BDINSS13FN
           do
             begin
               select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :wemp and BDREFEMP <= :prref order by BDREFEMP DESC into :BDNOMEMP;
               select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :wemp and BDCODCOL = :wcol and BDREFCOL <= :prref order by BDREFCOL DESC into :BDNOMCOL;
               suspend;
             end
     
           for select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFAUXVFN_SUM, FN.BDVALVIFN,0 ,0
               from SP_VRHF_UNION_INT_INTTOM_MES('FN.BDCODEMP = '||:wemp, 'FN.BDCODCOL = '||:wcol, null, :prref, 1) FN
               where FN.BDCODEMP = :wemp and FN.BDCODCOL = :wcol and FN.BDREFFN = :prref and fn.BDCLAVER starting with '9.010.0.0'
           into :BDCODEMP, :BDCODCOL, :BDBINSSFN, :BDINSSFN, :BDBINSS13FN, :BDINSS13FN
           do
             begin
               select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :wemp and BDREFEMP <= :prref order by BDREFEMP DESC into :BDNOMEMP;
               select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :wemp and BDCODCOL = :wcol and BDREFCOL <= :prref order by BDREFCOL DESC into :BDNOMCOL;
               suspend;
             end
         end

      if (coalesce(wterc, 0) > 0) then
         begin
           for select FN.BDCODEMP, FN.BDCODTER, FN.BDBASEINSS, FN.BDVALORINSS,0 ,0
               from VRHF_BASE_CALC_TERC FN
               where FN.BDCODTER = :wterc and FN.BDREFINSSSERV = :prref
           into :BDCODEMP, :BDCODCOL, :BDBINSSFN, :BDINSSFN, :BDBINSS13FN, :BDINSS13FN
           do
             begin
               select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :wemp and BDREFEMP <= :prref order by BDREFEMP DESC into :BDNOMEMP;
               select first 1 SUBSTRING(BDNOMETER from 1 for 70) from TTERCEIRO_REF where BDCODTER = :wcol and BDREFEMP <= :prref order by BDREFEMP DESC into :BDNOMCOL;
               suspend;
             end
         end

      -- Lançamento manual
      if (coalesce(wemp,  0) = 0 and coalesce(wcol, 0) = 0 and coalesce(wterc, 0) = 0) then
         begin
           BDCODEMP  = 'Lançamento manual';
           BDNOMEMP  = null;
           BDCODCOL  = 'CNPJ: '||wcnpj;
           BDNOMCOL  = null;
           BDBINSSFN = :wbinss;
           BDINSSFN  = :winss;
           BDBINSS13FN = 0;
           BDINSS13FN  = 0;
           suspend;
         end
    end

  for select BDCODEMP, BDCODCOL, 0, BDBASEINSSNCOL, BDVALORINSSNCOL, BDCNPJRESP
      from VRHF_EMP_TCOLCON_MVINC
      where BDCODEMPVINC = :premp and
            BDCODCOLVINC = :prcol and
            BDTIPOCALC = :prtipocalc and
            BDREFCOL <= :prref and
            ((coalesce(BDREFFIM, 0) >= :prref) or (coalesce(BDREFFIM, 0) = 0))
  into :wemp, :wcol, :wterc, :wbinss, :winss, :wcnpj
  do
    begin
      -- Rescisão
      if (coalesce(wemp,  0) > 0 and coalesce(wcol, 0) > 0) then
         begin
           for select BDCODEMP, BDCODCOL, sum(BDREFAUXVFN), sum(BDVALVFN), 0, 0 from (
                 select VERB_FN.BDCODEMP, VERB_FN.BDCODCOL, VERB_FN.BDREFAUXVFN, VERB_FN.BDVALVFN
                 FROM
                    (  SELECT
                          FN.BDCODVER,
                          FN.BDCODEMP,
                          FN.BDCODCOL,
                          FN.BDREFFN,
                          FN.BDREFVFN,
                          FN.BDREFAUXVFN,
                          FN.BDVALVFN,
                          FN.BDIGNREFVFN,
                          FN.BDIGNVALVFN
                        FROM VRHF_EMP_TVERBAFN FN
                        where (FN.BDCODEMP = :wemp) and (FN.BDCODCOL = :wcol) and (FN.BDREFFN = :prref)

                        UNION

                        SELECT
                          FNT.BDCODVER,
                          FNT.BDCODEMP,
                          FNT.BDCODCOL,
                          FNT.BDREFTOMADOR BDREFFN,
                          FNT.BDREFVFT BDREFVFN,
                          FNT.BDREFAUXVFT BDREFAUXVFN,
                          FNT.BDVALVFT BDVALVFN,
                          FNT.BDIGNREFVFT BDIGNREFVFN,
                          FNT.BDIGNVALVFT BDIGNVALVFN
                        FROM VRHF_EMP_TVERBATOMADOR FNT
                        where (FNT.BDCODEMP = :wemp) and (FNT.BDCODCOL = :wcol) and (FNT.BDREFTOMADOR = :prref)
                    ) VERB_FN

                 join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = VERB_FN.BDCODVER)
                 where SUBSTRING(VERB.BDCLAVER FROM 1 FOR 7) = '9.010.0'
           ) group by BDCODEMP, BDCODCOL
           into :BDCODEMP, :BDCODCOL, :BDBINSSFN, :BDINSSFN, :BDBINSS13FN, :BDINSS13FN
           do
             begin
               select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :wemp and BDREFEMP <= :prref order by BDREFEMP DESC into :BDNOMEMP;
               select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :wemp and BDCODCOL = :wcol and BDREFCOL <= :prref order by BDREFCOL DESC into :BDNOMCOL;
               suspend;
             end



           for select BDCODEMP, BDCODCOL, sum(BDREFAUXVFN_SUM), sum(BDVALVIFN), 0, 0 from (
                 select VERB_FN.BDCODEMP, VERB_FN.BDCODCOL, VERB_FN.BDREFAUXVFN_SUM, VERB_FN.BDVALVIFN
                 FROM SP_VRHF_UNION_INT_INTTOM_MES('FN.BDCODEMP = ' || :wemp, 'FN.BDCODCOL = ' || :wcol, null, :prref, 1) VERB_FN
                 where (VERB_FN.BDCODEMP = :wemp) and (VERB_FN.BDCODCOL = :wcol) and (VERB_FN.BDREFFN = :prref) and SUBSTRING(VERB_FN.BDCLAVER FROM 1 FOR 7) = '9.010.0'
           ) group by BDCODEMP, BDCODCOL
           into :BDCODEMP, :BDCODCOL, :BDBINSSFN, :BDINSSFN, :BDBINSS13FN, :BDINSS13FN
           do
             begin
               select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :wemp and BDREFEMP <= :prref order by BDREFEMP DESC into :BDNOMEMP;
               select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :wemp and BDCODCOL = :wcol and BDREFCOL <= :prref order by BDREFCOL DESC into :BDNOMCOL;
               suspend;
             end
         end
    end

  if (coalesce(prtipocalc, 0) = 1) then
     begin
       for select MV.BDCODEMPVINC, MV.BDCODCOLVINC
           from VRHF_EMP_TCOLCON_MVINC MV
           inner join VRH_EMP_TCOLCON COL on (MV.BDCODEMP = COL.BDCODEMP and MV.BDCODCOL = COL.BDCODCOL)
           inner join VRHF_MVAUT MVAUT on (MVAUT.BDCPF = COL.BDCPFCOL)
           where (COL.BDCODEMP = :premp)
             and (COL.BDCODCOL = :prcol)
             and (MVAUT.BDREFINI <= :prref)
             and (case when (coalesce(MVAUT.BDREFFIM, 0) = 0) then 999999
                       else MVAUT.BDREFFIM
                  end >= :prref)
       into :wemp, :wcol do
         begin
           for select VERB_FN.BDCODEMP, VERB_FN.BDCODCOL, sum(VERB_FN.BDREFAUXV13), sum(VERB_FN.BDVALV13),
                      (select first 1 x.BDNOMEMP from TEMPRESAS_REF x
                        where x.BDCODEMP = VERB_FN.BDCODEMP and x.BDREFEMP <= :prref
                        order by x.BDREFEMP DESC),
                     (select first 1 y.BDNOMCOL from VRH_EMP_TCOLCON_CAD y
                       where y.BDCODEMP = VERB_FN.BDCODEMP and y.BDCODCOL = VERB_FN.BDCODCOL and y.BDREFCOL <= :prref
                       order by y.BDREFCOL DESC)
                 FROM VRHF_EMP_TVERBA13 VERB_FN
                 JOIN VRH_BASE_TVERBAS VERB ON (VERB.BDCODVER = VERB_FN.BDCODVER)
                 where (VERB_FN.BDCODEMP = :wemp) and (VERB_FN.BDCODCOL = :wcol) and (VERB_FN.BDREF13 = :prref) and VERB.BDCLAVER STARTING WITH '9.010.0'
                 group by  VERB_FN.BDCODEMP, VERB_FN.BDCODCOL
           into :BDCODEMP, :BDCODCOL, :BDBINSSFN, :BDINSSFN, :BDNOMEMP, :BDNOMCOL
           do
            begin
               :BDBINSS13FN = 0;
               :BDINSS13FN = 0;
               suspend;
            end
       end
     end
end^

/* Restore proc. body: SP_VRH_CONS_NOVO_MV_FC */
CREATE OR ALTER procedure SP_VRH_CONS_NOVO_MV_FC (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRTIPOCALC integer = 0)
returns (
    BDCODEMP varchar(20),
    BDCODCOL varchar(30),
    BDNOMEMP DM_BDNOMEMP,
    BDNOMCOL DM_BDNOMCOL,
    BDBINSSFN numeric(18,6),
    BDINSSFN numeric(18,6),
    BDBINSS13FN numeric(18,6),
    BDINSS13FN numeric(18,6))
as
declare variable WEMP integer;
declare variable WCOL integer;
declare variable WBINSS numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WBINSS13 numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WCNPJ DM_CNPJ_CPF;
declare variable WACHOU DM_BOOLEAN;
begin

  BDBINSSFN = 0;
  BDINSSFN = 0;
  BDBINSS13FN = 0;
  BDINSS13FN = 0;

  for select BDCODEMPVINC, BDCODCOLVINC, BDBASEINSSNCOL, BDVALORINSSNCOL, BDBASEINSS13COL, BDVALORINSS13COL, BDCNPJRESP
      from VRHF_EMP_TCOLCON_MVINC
      where BDCODEMP = :premp and
            BDCODCOL = :prcol and
            BDTIPOCALC = :prtipocalc and
            BDREFCOL <= :prref and
            ((coalesce(BDREFFIM, 0) >= :prref) or (coalesce(BDREFFIM, 0) = 0))
  into :wemp, :wcol, :wbinss, :winss, :wbinss13, :winss13, :wcnpj
  do
    begin
      if (coalesce(wemp,  0) > 0 and coalesce(wcol, 0) > 0) then
         begin
           for select FN.BDCODEMP, FN.BDCODCOL,
                      SUM(coalesce(FN.BDBINSSFN,0) + coalesce(COMP.BDBINSSFN,0)),
                      SUM(coalesce(FN.BDINSSFN,0) + coalesce(COMP.BDINSSFN,0)),
                      SUM(coalesce(FN.BDBINSS13FN,0) + coalesce(COMP.BDBINSS13FN,0)),
                      SUM(coalesce(FN.BDINSS13FN,0) + coalesce(COMP.BDINSS13FN,0))
               from (SELECT BDCODEMP, BDCODCOL, BDREF, BDBINSSFN, BDINSSFN, BDBINSS13FN, BDINSS13FN, BDBASEINSSC13, BDINSSC13, BDTIPO
                      FROM (
                        SELECT
                          Y.BDCODEMP,
                          Y.BDCODCOL,
                          Y.BDREFFN BDREF,
                          Y.BDBINSSFN,
                          Y.BDINSSFN,
                          Y.BDBINSS13FN BDBINSS13FN,
                          Y.BDINSS13FN BDINSS13FN,
                          0.0 BDBASEINSSC13,
                          0.0 BDINSSC13,
                          0 BDTIPO
                        FROM VRHF_EMP_TFOLHANORMAL Y
                        where Y.BDCODEMP = :wemp and Y.BDCODCOL = :wcol and Y.BDREFFN = :prref
                        UNION
                        SELECT
                          x.bdcodemp,
                          x.bdcodcol,
                          x.bdreftomador BDREF,
                          SUM(x.bdbinssft) BDBINSSFN,
                          SUM(x.bdinssft) BDINSSFN,
                          SUM(x.bdbinss13ft) BDBINSS13FN,
                          SUM(x.bdinss13ft) BDINSS13FN,
                          0.0 BDBASEINSSC13,
                          0.0 BDINSSC13,
                          0 BDTIPO
                        FROM vrhf_emp_tfolhatomador x
                        where X.BDCODEMP = :wemp and X.BDCODCOL = :wcol and X.BDREFTOMADOR = :prref
                        GROUP BY x.bdcodemp, x.bdcodcol, x.bdreftomador
                        UNION
                        SELECT
                          Y.BDCODEMP,
                          Y.BDCODCOL,
                          Y.BDREFFN BDREF,
                          SUM(Y.BDBINSSFN) BDBINSSFN,
                          SUM(Y.BDINSSFN) BDINSSFN,
                          SUM(Y.BDBINSS13FN) BDBINSS13FN,
                          SUM(Y.BDINSS13FN) BDINSS13FN,
                          0.0 BDBASEINSSC13,
                          0.0 BDINSSC13,
                          0 BDTIPO
                        FROM VRHF_EMP_TFOLHAINT Y
                        where Y.BDCODEMP = :wemp and Y.BDCODCOL = :wcol and Y.BDREFFN = :prref
                        GROUP BY  Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN
                        UNION
                        SELECT
                          x.bdcodemp,
                          x.bdcodcol,
                          x.bdreftomador BDREF,
                          SUM(x.bdbinssft) BDBINSSFN,
                          SUM(x.bdinssft) BDINSSFN,
                          SUM(x.bdbinss13ft) BDBINSS13FN,
                          SUM(x.bdinss13ft) BDINSS13FN,
                          0.0 BDBASEINSSC13,
                          0.0 BDINSSC13,
                          0 BDTIPO
                        FROM vrhf_emp_tfolhatomint x
                        GROUP BY x.bdcodemp, x.bdcodcol, x.bdreftomador
                    )) FN
               left outer join (
                   SELECT BDCODEMP, BDCODCOL, BDREF, BDBINSSFN, BDINSSFN, BDBINSS13FN, BDINSS13FN, BDBASEINSSC13, BDINSSC13, BDTIPO
                      FROM ( SELECT
                             X.BDCODEMP,
                             X.BDCODCOL,
                             X.BDREFFN BDREF,
                             X.BDBINSSFC BDBINSSFN,
                             X.BDINSSFC BDINSSFN,
                             X.BDBINSS13FC BDBINSS13FN,
                             X.BDINSS13FC BDINSS13FN,
                             0.0 BDBASEINSSC13,
                             0.0 BDINSSC13,
                             1 BDTIPO
                           FROM VRHF_EMP_TFOLHACOMP X
                           where X.BDCODEMP = :wemp and X.BDCODCOL = :wcol and X.BDREFFN= :prref
                           UNION
                           SELECT
                             x.bdcodemp,
                             x.bdcodcol,
                             x.bdreftomador BDREF,
                             SUM(x.bdbinssfc) BDBINSSFN,
                             SUM(x.bdinssfc) BDINSSFN,
                             SUM(x.bdbinss13fc) BDBINSS13FN,
                             SUM(x.bdinss13fc) BDINSS13FN,
                             0.0 BDBASEINSSC13,
                             0.0 BDINSSC13,
                             1 BDTIPO
                           FROM vrhf_emp_tfoltomcomp x
                           where X.BDCODEMP = :wemp and X.BDCODCOL = :wcol and X.BDREFTOMADOR = :prref
                           GROUP BY x.bdcodemp, x.bdcodcol, x.bdreftomador
               ) ) COMP on (COMP.BDCODEMP = FN.BDCODEMP and COMP.BDCODCOL = FN.BDCODCOL and COMP.BDREF = FN.BDREF)
               group by FN.BDCODEMP, FN.BDCODCOL
           into :BDCODEMP, :BDCODCOL, :BDBINSSFN, :BDINSSFN, :BDBINSS13FN, :BDINSS13FN
           do
             begin
               select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :wemp and BDREFEMP <= :prref order by BDREFEMP DESC into :BDNOMEMP;
               select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :wemp and BDCODCOL = :wcol and BDREFCOL <= :prref order by BDREFCOL DESC into :BDNOMCOL;
               suspend;
             end
         end

      -- Lançamento manual
      if (coalesce(wemp,  0) = 0 and coalesce(wcol, 0) = 0) then
         begin
           BDCODEMP     = 'Lançamento manual';
           BDNOMEMP     = null;
           BDCODCOL     = 'CNPJ: '||wcnpj;
           BDNOMCOL     = null;
           BDBINSSFN    = :wbinss;
           BDINSSFN     = :winss;
           BDBINSS13FN  = :wbinss13;
           BDINSS13FN   = :winss13;
           suspend;
         end

    end

  WACHOU = 'FALSE';
  if (coalesce(prtipocalc, 0) = 1) then
     begin
       for select MV.BDCODEMPVINC, MV.BDCODCOLVINC
           from VRHF_EMP_TCOLCON_MVINC MV
           inner join VRH_EMP_TCOLCON COL on (MV.BDCODEMP = COL.BDCODEMP and MV.BDCODCOL = COL.BDCODCOL)
           inner join VRHF_MVAUT MVAUT on (MVAUT.BDCPF = COL.BDCPFCOL)
           where (COL.BDCODEMP = :premp)
             and (COL.BDCODCOL = :prcol)
             and (MVAUT.BDREFINI <= :prref)
             and (case when (coalesce(MVAUT.BDREFFIM, 0) = 0) then 999999
                       else MVAUT.BDREFFIM
                  end >= :prref)
       into :wemp, :wcol do
         begin
           for select BDCODEMP, BDCODCOL, sum(coalesce(BDBASEINSS,0)), sum(coalesce(BDVALORINSS,0)), 0 , 0 from (
                 select VERB_FN.BDCODEMP, VERB_FN.BDCODCOL, 0 BDBINSSFN, 0 BDINSSFN, VERB_FN.BDREFAUXVC13 BDBASEINSS, VERB_FN.BDVALVC13 BDVALORINSS
                 FROM VRHF_EMP_TVERBAC13 VERB_FN
                 JOIN VW_TVERBAS VERB ON (VERB.BDCODVER = VERB_FN.BDCODVER)
                 where (VERB_FN.BDCODEMP = :wemp) and (VERB_FN.BDCODCOL = :wcol) and (VERB_FN.BDREFC13 = :prref) and SUBSTRING(VERB.BDCLAVER FROM 1 FOR 7) = '9.010.0'
           ) group by BDCODEMP, BDCODCOL
           into :BDCODEMP, :BDCODCOL, :BDBINSSFN, :BDINSSFN, :BDBINSS13FN, :BDINSS13FN
           do
             begin
               WACHOU = 'TRUE';
               select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :wemp and BDREFEMP <= :prref order by BDREFEMP DESC into :BDNOMEMP;
               select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :wemp and BDCODCOL = :wcol and BDREFCOL <= :prref order by BDREFCOL DESC into :BDNOMCOL;
               suspend;
             end

           if (WACHOU = 'FALSE') then
              begin
                for select BDCODEMP, BDCODCOL, sum(coalesce(BDBASEINSS,0)), sum(coalesce(BDVALORINSS,0)), 0, 0 from (
                      select VERB_FN.BDCODEMP, VERB_FN.BDCODCOL, VERB_FN.BDREFAUXV13 BDBASEINSS, VERB_FN.BDVALV13 BDVALORINSS
                      FROM VRHF_EMP_TVERBA13 VERB_FN
                      JOIN VW_TVERBAS VERB ON (VERB.BDCODVER = VERB_FN.BDCODVER)
                      where (VERB_FN.BDCODEMP = :wemp) and (VERB_FN.BDCODCOL = :wcol) and (VERB_FN.BDREF13 = :prref) and SUBSTRING(VERB.BDCLAVER FROM 1 FOR 7) = '9.010.0'
                ) group by BDCODEMP, BDCODCOL
                into :BDCODEMP, :BDCODCOL, :BDBINSSFN, :BDINSSFN, :BDBINSS13FN, :BDINSS13FN
                do
                  begin
                    select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :wemp and BDREFEMP <= :prref order by BDREFEMP DESC into :BDNOMEMP;
                    select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :wemp and BDCODCOL = :wcol and BDREFCOL <= :prref order by BDREFCOL DESC into :BDNOMCOL;
                    suspend;
                  end
              end
         end
     end
end^

/* Restore proc. body: SP_VRHM_EMP_VAL_TOD_OP_ATU2 */
create or alter procedure SP_VRHM_EMP_VAL_TOD_OP_ATU2 (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer,
    PRPLANO integer = 0,
    PROPER integer = 0,
    PRCONV integer = 0)
returns (
    BDTIPO integer,
    BDCODPLACONVSAU integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREF integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDNOME varchar(70),
    BDCPF varchar(14),
    BDVALORMENSALIDADE numeric(18,6),
    BDVALORCOPAR numeric(18,6),
    BDCODTIPOCONV integer,
    BDTIPOFAIXA integer,
    BDCODTIPO integer,
    BDMENSFORMULA DM_BOOLEAN,
    BDCODVERTITMENS integer,
    BDCODVERTITCOP integer,
    BDCODVERDEPMENS integer,
    BDCODVERDEPCOP integer)
as
declare variable WSQL varchar(32700);
begin
  prplano = coalesce(prplano, 0);
  proper  = coalesce(proper, 0);
  prconv  = coalesce(prconv, 0);

  wsql = 'SELECT colcon.bdcodemp, colcon.bdcodcol, '||
                'colcon.bdcpfcol bdcpf '||
         'FROM vrh_emp_tcolcon colcon '||
         'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = colcon.BDCODEMP and RESC.BDCODCOL = colcon.BDCODCOL) '||
         'where colcon.BDREFADMCOL <= '||prref||
             ' and ((RESC.BDDATARESCISAO is null) or (RESC.BDREFRESCISAO >= '||prref||'))';

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||' and '|| REPLACE(upper(premp), 'BDCODEMP', 'COLCON.BDCODEMP');

       if ((coalesce(prcol, '') <> '') and (not position('TEMP_FILTRO_COLCON_REL', prcol) > 0)) then
          wsql = wsql||' and '||REPLACE(upper(prcol), 'BDCODCOL', 'COLCON.BDCODCOL');
       else if (position('TEMP_FILTRO_COLCON_REL', prcol) > 0) then
          wsql = wsql||' and '||'COLCON.'||prcol;
     end

  for execute statement wsql into :BDCODEMP,:BDCODCOL,:BDCPF do
    begin
      BDCODDPN = null;
      BDTIPO   = 0;
      select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prref order by BDREFCOL DESC into :BDNOME;

      for select SAUDE.BDCODPLACONVSAU,
                 SAUDE.BDCODOPERADORA,
                 SAUDE.BDCODCONVENIO,
                 SAUDE.BDREFVCS,
                 COALESCE(SAUDE.BDVALORMENSALIDADEFUN,0),
                 SAUDE.bdvalorcoparfun,
                 COALESCE(SAUDE.bdtipo, 0),
                 SAUDE.bdcodtipo,
                 CONV_OP.bdcodtipoconv,
                 upper(coalesce(CONV_OP.bdmensformula, 'FALSE')),
                 CONV_OP.BDCODVERTITMENS,
                 CONV_OP.BDCODVERTITCOP,
                 CONV_OP.BDCODVERDEPMENS,
                 CONV_OP.BDCODVERDEPCOP
          from SP_VRHM_EMP_VAL_COL_OP_ATU(:BDCODEMP, :BDCODCOL, :prref, :prplano, :proper, :prconv) SAUDE
          left outer join VRH_BASE_CONVENIO_OPERADORAS CONV_OP on (CONV_OP.bdcodplaconvsau = SAUDE.bdcodplaconvsau AND CONV_OP.bdcodoperadora = SAUDE.bdcodoperadora AND CONV_OP.bdcodconvenio = SAUDE.bdcodconvenio)
      into :BDCODPLACONVSAU,
           :BDCODOPERADORA,
           :BDCODCONVENIO,
           :BDREF,
           :BDVALORMENSALIDADE,
           :BDVALORCOPAR,
           :BDCODTIPOCONV,
           :BDTIPOFAIXA,
           :BDCODTIPO,
           :BDMENSFORMULA,
           :BDCODVERTITMENS,
           :BDCODVERTITCOP,
           :BDCODVERDEPMENS,
           :BDCODVERDEPCOP
      do
        suspend;

      BDTIPO = 1;

      for select BDCODDPN
          from VRH_EMP_TDEP
          where ((BDDATABAUXADPN is null) or (substring(BDDATABAUXADPN from 1 for 4) || substring(BDDATABAUXADPN from 6 for 2) > :prref)) and
                BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL
      into :BDCODDPN
      do
        begin
          select first 1 BDNOMEDPN, BDCPFDPN from VRH_EMP_TDEP_REF where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDCODDPN = :BDCODDPN and BDREFDPN <= :prref order by BDREFDPN DESC into :BDNOME, :BDCPF;

          for select SAUDE.bdcodplaconvsau,
                     SAUDE.bdcodoperadora,
                     SAUDE.bdcodconvenio,
                     SAUDE.bdrefvcs,
                     SAUDE.bdvalormensalidadedep,
                     SAUDE.bdvalorcopardep,
                     COALESCE(SAUDE.bdtipo, 0),
                     SAUDE.bdcodtipo,
                     CONV_OP.bdcodtipoconv,
                     upper(coalesce(CONV_OP.BDMENSFORMULA, 'FALSE')),
                     CONV_OP.BDCODVERTITMENS,
                     CONV_OP.BDCODVERTITCOP,
                     CONV_OP.BDCODVERDEPMENS,
                     CONV_OP.BDCODVERDEPCOP
              from SP_VRHM_EMP_VAL_DEP_OP_ATU(:BDCODEMP, :prref, :BDCODCOL, :BDCODDPN, :prplano, :proper, :prconv) SAUDE
              LEFT OUTER JOIN VRH_BASE_CONVENIO_OPERADORAS CONV_OP ON (CONV_OP.bdcodplaconvsau = SAUDE.bdcodplaconvsau AND CONV_OP.bdcodoperadora = SAUDE.bdcodoperadora AND CONV_OP.bdcodconvenio = SAUDE.bdcodconvenio)
          into :BDCODPLACONVSAU,
               :BDCODOPERADORA,
               :BDCODCONVENIO,
               :BDREF,
               :BDVALORMENSALIDADE,
               :BDVALORCOPAR,
               :BDCODTIPOCONV,
               :BDTIPOFAIXA,
               :BDCODTIPO,
               :BDMENSFORMULA,
               :BDCODVERTITMENS,
               :BDCODVERTITCOP,
               :BDCODVERDEPMENS,
               :BDCODVERDEPCOP
          do
            suspend;
        end
    end
end^

/* Restore proc. body: SP_VRHF_MV_VINCSEMCALC */
CREATE OR ALTER procedure SP_VRHF_MV_VINCSEMCALC (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer,
    PRTIPOCALC integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODMV integer,
    BDREFCOL integer,
    BDBASEINSSNCOL numeric(15,6),
    BDVALORINSSNCOL numeric(15,6),
    BDBASEIRRFNCOL numeric(15,6),
    BDVALORIRRFNCOL numeric(15,6),
    BDBASEINSS13COL numeric(15,6),
    BDVALORINSS13COL numeric(15,6),
    BDBASEIRRF13COL numeric(15,6),
    BDVALORIRRF13COL numeric(15,6),
    BDCNPJRESP DM_CNPJ_CPF,
    BDCATEGORIAESOCIAL integer,
    BDTIPOCALC integer,
    BDREFFIM integer,
    BDCODEMPVINC integer,
    BDCODCOLVINC integer,
    BDCODTERVINC integer)
as
declare variable WSQL varchar(32700);
declare variable WACHOU integer;
begin
  wsql = 'select MVC.BDCODEMP, MVC.BDCODCOL, MVC.BDCODMV, MVC.BDREFCOL, MVC.BDBASEINSSNCOL, MVC.BDVALORINSSNCOL, MVC.BDBASEIRRFNCOL, MVC.BDVALORIRRFNCOL, MVC.BDBASEINSS13COL, '||
                'MVC.BDVALORINSS13COL, MVC.BDBASEIRRF13COL, MVC.BDVALORIRRF13COL, MVC.BDCNPJRESP, MVC.BDCATEGORIAESOCIAL, MVC.BDTIPOCALC, MVC.BDREFFIM, MVC.BDCODEMPVINC, '||
                'MVC.BDCODCOLVINC, MVC.BDCODTERVINC '||
         'from VRHF_EMP_TCOLCON_MVINC MVC '||
         'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = MVC.BDCODEMPVINC and RESC.BDCODCOL = MVC.BDCODCOLVINC) '||
         'where ((RESC.BDDATARESCISAO is null) or (RESC.BDREFRESCISAO > '||prref||')) and '||
               '(MVC.BDREFCOL <= '||prref||') and '||
               '((coalesce(MVC.BDREFFIM, 0) = 0) or (MVC.BDREFFIM >= '||prref||')) ';

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||' and '||replace(upper(premp), 'BDCODEMP', 'MVC.BDCODEMP');

       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||replace(upper(prcol), 'BDCODCOL', 'MVC.BDCODCOL');
     end
         
  for execute statement wsql
  into :BDCODEMP, :BDCODCOL, :BDCODMV, :BDREFCOL, :BDBASEINSSNCOL, :BDVALORINSSNCOL, :BDBASEIRRFNCOL, :BDVALORIRRFNCOL, :BDBASEINSS13COL,
       :BDVALORINSS13COL, :BDBASEIRRF13COL, :BDVALORIRRF13COL, :BDCNPJRESP, :BDCATEGORIAESOCIAL, :BDTIPOCALC, :BDREFFIM, :BDCODEMPVINC,
       :BDCODCOLVINC, :BDCODTERVINC
  do
    begin
      wachou = null;
      if (coalesce(:BDCODEMPVINC, 0) > 0 and coalesce(:BDCODCOLVINC, 0) > 0) then
         begin
           if (coalesce(PRTIPOCALC, 0) = 0) then
              begin
                select first 1 BDCODEMP from VRHF_EMP_TFOLHANORMAL where BDREFFN = :prref and BDCODEMP = :BDCODEMPVINC and BDCODCOL = :BDCODCOLVINC into :wachou;
     
                if (coalesce(wachou, 0) <= 0) then
                   select first 1 BDCODEMP from VRHF_EMP_TFOLHATOMADOR where BDREFTOMADOR = :prref and BDCODEMP = :BDCODEMPVINC and BDCODCOL = :BDCODCOLVINC into :wachou;
     
                if (coalesce(wachou, 0) <= 0) then
                   select first 1 BDCODEMP from VRHF_EMP_TFOLHAINT where BDREFFN = :prref and BDCODEMP = :BDCODEMPVINC and BDCODCOL = :BDCODCOLVINC into :wachou;
     
                if (coalesce(wachou, 0) <= 0) then
                   select first 1 BDCODEMP from VRHF_EMP_TFOLHATOMINT where BDREFTOMADOR = :prref and BDCODEMP = :BDCODEMPVINC and BDCODCOL = :BDCODCOLVINC into :wachou;
     
                if (coalesce(wachou, 0) <= 0) then
                   suspend;
                else
                   begin
                     wachou = null;
                     if (coalesce(:BDCODTERVINC, 0) > 0) then
                        begin
                          select first 1 CALC.BDCODEMP
                          from VRHF_BASE_CALC_TERC CALC
                          join VRH_BASE_TSERVTERC SERV on (SERV.BDCODEMP = CALC.BDCODEMP and SERV.BDCODTER = CALC.BDCODTER and SERV.BDCODSERV = CALC.BDCODSERV)
                          where CALC.BDCODTER = :BDCODTERVINC and SERV.BDREFPAGSERV = :prref into :wachou;
          
                          if (coalesce(wachou, 0) <= 0) then
                             suspend;
                        end
                   end
              end
           else
              begin
                select first 1 BDCODEMP from VRHF_EMP_T13SAL where BDREF13 = :prref and BDCODEMP = :BDCODEMPVINC and BDCODCOL = :BDCODCOLVINC into :wachou;
     
                if (coalesce(wachou, 0) <= 0) then
                   select first 1 BDCODEMP from VRHF_EMP_T13SAL_RAT where BDREF13 = :prref and BDCODEMP = :BDCODEMPVINC and BDCODCOL = :BDCODCOLVINC into :wachou;
     
                if (coalesce(wachou, 0) <= 0) then
                   suspend;
              end
         end
      else
         begin
           wachou = null;
           if (coalesce(:BDCODTERVINC, 0) > 0) then
              begin
                select first 1 CALC.BDCODEMP
                from VRHF_BASE_CALC_TERC CALC
                join VRH_BASE_TSERVTERC SERV on (SERV.BDCODEMP = CALC.BDCODEMP and SERV.BDCODTER = CALC.BDCODTER and SERV.BDCODSERV = CALC.BDCODSERV)
                where CALC.BDCODTER = :BDCODTERVINC and SERV.BDREFPAGSERV = :prref into :wachou;

                if (coalesce(wachou, 0) <= 0) then
                   suspend;
              end
         end
    end
end^

/* Restore proc. body: SP_VRH_BASE_TSALHORESP */
create or alter procedure SP_VRH_BASE_TSALHORESP (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer,
    PRULTDIA date = null)
returns (
    BDCODEMPSHE integer,
    BDCODCOL integer,
    BDCODEMP integer,
    BDCODSHE integer,
    BDCODMAS integer,
    BDSALSHE numeric(18,6),
    BDDATASHE date,
    BDCODVER integer,
    BDSALINISHE numeric(18,6),
    BDDESCVERBASHE DM_BOOLEAN,
    BDDESCSHE varchar(50))
as
declare variable WSQL varchar(25000);
declare variable WSQLCOL varchar(32700);
declare variable WULTDAT date;
declare variable WULTDIA integer;
begin
  if (prultdia is not null) then
     begin
       wultdia = CAST((substring(cast(prultdia as varchar(10)) from 9 for 2)) as integer);
       wultdat = prultdia;
     end
  else
     begin
       select ULTDIA from ULTIMO_DIA_MES(CAST(SUBSTRING(:prref FROM 5 FOR 2) AS SMALLINT), CAST(SUBSTRING(:prref FROM 1 FOR 4) AS INTEGER)) into :wultdia;
       wultdat = CAST((SUBSTRING(:prref FROM 5 FOR 2)||'-'||LPAD(:wultdia, 2, '0')||'-'||SUBSTRING(:prref FROM 1 FOR 4)) AS DATE);
     end

  wsql = 'select BDCODEMP, BDCODSHE, BDCODVER, BDSALINISHE, BDDESCVERBASHE, BDDESCSHE '||
         'from VRH_BASE_TSALHORESP ';

  if (coalesce(premp, '') <> '') then
     wsql = wsql||' where '||premp;

  for execute statement wsql
  into :BDCODEMP, :BDCODSHE, :BDCODVER, :BDSALINISHE, :BDDESCVERBASHE, :BDDESCSHE
  do
    begin
      BDCODEMPSHE = BDCODEMP;

      if (trim(coalesce(BDDESCSHE, '')) = '') then
         select first 1 BDDESCVER from VRH_BASE_TVERBAS where BDCODVER = :BDCODVER into :BDDESCSHE;

      wsqlcol = 'select BDCODCOL, max(BDDATASHE) '||
                'from VRH_EMP_TCOL_SHE '||
                'where BDCODEMP = '||:BDCODEMP||' and BDDATASHE <= '''||:wultdat||''' '||
                       ' and BDCODSHE = '||:BDCODSHE;

      if (coalesce(prcol, '') <> '') then
         wsqlcol = wsqlcol||' and '||prcol;

      wsqlcol = wsqlcol||' group by BDCODCOL ';

      for execute statement wsqlcol
      into :BDCODCOL, :BDDATASHE
      do
        for select BDCODMAS, BDSALSHE
        from VRH_EMP_TCOL_SHE
        where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDCODSHE = :BDCODSHE and BDDATASHE = :BDDATASHE
        into :BDCODMAS, :BDSALSHE
        do
          suspend;
    end
end^


/* Restore proc. body: SP_VRH_BASE_TSALHORESP_COMP */
create or alter procedure SP_VRH_BASE_TSALHORESP_COMP (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMPSHE integer,
    BDCODCOL integer,
    BDCODEMP integer,
    BDCODSHE integer,
    BDCODMAS integer,
    BDSALSHE numeric(18,6),
    BDDATASHE date,
    BDDATAEFEITOHE date,
    BDCODVER integer,
    BDSALINISHE numeric(18,6),
    BDDESCVERBASHE DM_BOOLEAN,
    BDDESCSHE varchar(50))
as
declare variable WSQL varchar(25000);
declare variable WSQLCOL varchar(32700);
declare variable WULTDAT date;
declare variable WULTDIA integer;
begin
  select ULTDIA from ULTIMO_DIA_MES(CAST(SUBSTRING(:prref FROM 5 FOR 2) AS SMALLINT), CAST(SUBSTRING(:prref FROM 1 FOR 4) AS INTEGER)) into :wultdia;
  wultdat = CAST((SUBSTRING(:prref FROM 5 FOR 2)||'-'||LPAD(:wultdia, 2, '0')||'-'||SUBSTRING(:prref FROM 1 FOR 4)) AS DATE);



  wsql = 'select BDCODEMP, BDCODSHE, BDCODVER, BDSALINISHE, BDDESCVERBASHE, BDDESCSHE '||
         'from VRH_BASE_TSALHORESP ';

  if (coalesce(premp, '') <> '') then
     wsql = wsql||' where '||premp;

  for execute statement wsql
  into :BDCODEMP, :BDCODSHE, :BDCODVER, :BDSALINISHE, :BDDESCVERBASHE, :BDDESCSHE
  do
    begin
      BDCODEMPSHE = BDCODEMP;

      if (trim(coalesce(BDDESCSHE, '')) = '') then
         select first 1 BDDESCVER from VRH_BASE_TVERBAS where BDCODVER = :BDCODVER into :BDDESCSHE;

      wsqlcol = 'select first 1 BDCODCOL,BDDATASHE, BDDATAEFEITOHE '||
                'from VRH_EMP_TCOL_SHE '||
                'where BDCODEMP = '||:BDCODEMP||' and BDDATAEFEITOHE <= '''||:wultdat||''' '||
                       ' and BDCODSHE = '||:BDCODSHE;

      if (coalesce(prcol, '') <> '') then
         wsqlcol = wsqlcol||' and '||prcol;

      wsqlcol = wsqlcol||' order by BDDATASHE desc ';

      for execute statement wsqlcol
      into :BDCODCOL, :BDDATASHE, :BDDATAEFEITOHE
      do
        for select BDCODMAS, BDSALSHE
        from VRH_EMP_TCOL_SHE
        where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDCODSHE = :BDCODSHE and BDDATASHE = :BDDATASHE and BDDATAEFEITOHE = :BDDATAEFEITOHE
        into :BDCODMAS, :BDSALSHE
        do
          suspend;
    end
end^

/* Restore proc; body: SP_QUALIFICA_ESOCIAL */
create or alter procedure SP_QUALIFICA_ESOCIAL (
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(100),
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDDATANASCCOL date,
    BDCERTDIGITAL varchar(200))
as
declare variable WCERT varchar(200);
declare variable WCONT integer;
declare variable WEMPATU integer;
begin
  BDCODEMP = 0;
  BDCERTDIGITAL = null;
  select first 1 BDCERTDIGITAL from TCONTADOR_PADRAO where BDCERTDIGITAL > '' order by BDCODCONT into :BDCERTDIGITAL;

  if (coalesce(BDCERTDIGITAL, '') > '') then
     begin
       for select first 15 T.BDCODTER, T.BDCGCTER
           from TTERCEIRO T
           join VRH_BASE_TTERC_DOC D on (D.BDCODTER = T.BDCODTER)
           where char_length(T.BDCGCTER) = 14 and ((D.BDSTATUSQC not in (2, 3, 4)) or (D.BDSTATUSQC is null))
           order by T.BDCODTER
       into :BDCODCOL, :BDCPFCOL
       do
         begin
           select first 1 BDNOMETER from TTERCEIRO_REF where BDCODTER = :BDCODCOL and BDREFEMP <= :prref order by BDREFEMP DESC into :BDNOMCOL;
           select first 1 BDPISTER from VRH_BASE_TTERC_DOCREF where BDCODTER = :BDCODCOL and BDREFTERC <= :prref order by BDREFTERC DESC into :BDPISCOL;
           select first 1 BDDATANASCTER from TTERCEIRO_RH where BDCODTER = :BDCODCOL into :BDDATANASCCOL;
           suspend;
         end
     end

   wempatu = 0;

  for select first 15 C.BDCODEMP, C.BDCODCOL, C.BDCPFCOL, C.BDDATANASCCOL, E.BDCERTDIGITAL
      from VRH_EMP_TCOLCON C
      join TEMPRESAS E on (E.BDCODEMP = C.BDCODEMP)
      where (C.BDSTATUSQC not in (2, 3, 4)) or (C.BDSTATUSQC is null)
      order by C.BDCODEMP, C.BDCODCOL
  into :BDCODEMP, :BDCODCOL, :BDCPFCOL, :BDDATANASCCOL, :wcert
  do
    begin
      select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prref order by BDREFCOL DESC into :BDNOMCOL;

      if (wempatu <> BDCODEMP) then
         begin
           if (coalesce(wcert, '') > '') then
              BDCERTDIGITAL = wcert;
           else
              begin
                BDCERTDIGITAL = '';
                wcont = null;
                select first 1 BDCODCONTRH from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :prref order by BDREFEMP DESC into :wcont;

                if (coalesce(wcont, 0) > 0) then
                   select first 1 BDCERTDIGITAL from TCONTADOR_PADRAO where BDCODCONT = :wcont into :BDCERTDIGITAL;

                BDCERTDIGITAL = coalesce(BDCERTDIGITAL, '');
              end

           wempatu = BDCODEMP;
         end

      if (coalesce(BDCERTDIGITAL, '') <> '') then
         suspend;
    end
end^

CREATE OR ALTER PROCEDURE SP_FILTRA_PART_TROCA (
    PRCODTER INTEGER)
RETURNS (
    BDVALID DM_BOOLEAN)
AS
DECLARE VARIABLE WCODTER INTEGER;
BEGIN
  SELECT FIRST 1 BDCODTER FROM TMP_TPLANO_TROCA_TER INTO :wCodTer;

  IF (ROW_COUNT = 0) THEN
    BDVALID = 'TRUE';
  ELSE
    BEGIN
      SELECT BDCODTER
      FROM TMP_TPLANO_TROCA_TER
      WHERE BDCODTER = :PRCODTER
      INTO :wCodTer;

      BDVALID = IIF(ROW_COUNT > 0, 'TRUE', 'FALSE');
    END

  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_FILTER_TER_TROCA_GLOBAL (
    PRCODTER INTEGER)
RETURNS (
    BDFOUND DM_BOOLEAN)
AS
DECLARE VARIABLE WCODTER INTEGER;
BEGIN
  BDFOUND = 'FALSE';

  SELECT FIRST 1 TER.BDCODTER
  FROM TMP_TPLANO_TROCA_TER TER
  INTO :wCodTer;

  IF (ROW_COUNT > 0) THEN
    BEGIN
      SELECT FIRST 1 TER.BDCODTER
      FROM TMP_TPLANO_TROCA_TER TER
      WHERE TER.BDCODTER = :PRCODTER
      INTO :wCodTer;

      BDFOUND = IIF(ROW_COUNT > 0, 'TRUE', 'FALSE');
    END
  ELSE
    BDFOUND = 'TRUE';

  SUSPEND;
END^

CREATE OR ALTER PROCEDURE SP_FILTER_DOC_TROCA_GLOBAL (
    PRNUMDOCINI NUMERIC(15,0))
RETURNS (
    BDFOUND DM_BOOLEAN)
AS
DECLARE VARIABLE WNUMDOCINI NUMERIC(15,0);
BEGIN
  BDFOUND = 'TRUE';

  SELECT FIRST 1 DOC.BDNUMDOCINI
  FROM TMP_TPLANO_TROCA_DOC DOC
  INTO :wNumDocIni;

  IF (ROW_COUNT > 0) THEN
    BEGIN
      SELECT FIRST 1 DOC.BDNUMDOCINI
      FROM TMP_TPLANO_TROCA_DOC DOC
      WHERE DOC.BDNUMDOCINI = :PRNUMDOCINI
      INTO :wNumDocIni;

      BDFOUND = IIF(ROW_COUNT > 0, 'TRUE', 'FALSE');
    END

  SUSPEND;
END^

create or alter procedure SP_FILTRA_PART_TROCA_PLANO (
    PRCODPLATROCA integer,
    PRCHAVE integer,
    PRCODTER integer)
returns (
    BDVALID DM_BOOLEAN)
as
declare variable WTERPJPF integer;
declare variable WCGCTER varchar(18);
declare variable WCODTER integer;
BEGIN
  SELECT FIRST 1 BDTERPJPF
  FROM VEF_BASE_TPLANOACOESTROCA
  WHERE BDCODPLATROCA = :PRCODPLATROCA
  AND BDCHAVE = :PRCHAVE
  INTO :WTERPJPF;

  IF (:WTERPJPF IN (1,2)) THEN
     BEGIN
       SELECT FIRST 1 BDCGCTER
       FROM VW_TTERCEIRO
       WHERE BDCODTER = :PRCODTER
       INTO :WCGCTER;

       IF (:WTERPJPF = 1) THEN
         BDVALID = IIF(CHAR_LENGTH(:WCGCTER) = 18, 'TRUE', 'FALSE');
       ELSE
         BDVALID = IIF(CHAR_LENGTH(:WCGCTER) = 14, 'TRUE', 'FALSE');
     END
  ELSE
    BEGIN
      SELECT FIRST 1 BDCODTER
      FROM VEF_BASE_TPLANOACOESTROCA_TER TP
      WHERE TP.BDCODPLATROCA = :PRCODPLATROCA
      AND TP.BDCHAVE = :PRCHAVE
      INTO :wCodTer;
    
      IF (ROW_COUNT = 0) THEN
        BDVALID = 'TRUE';
      ELSE
        BEGIN
          SELECT FIRST 1 BDCODTER
          FROM VEF_BASE_TPLANOACOESTROCA_TER TP
          WHERE TP.BDCODPLATROCA = :PRCODPLATROCA
          AND TP.BDCHAVE = :PRCHAVE
          AND TP.BDCODTER = :PRCODTER
          INTO :wCodTer;
    
          BDVALID = IIF(ROW_COUNT > 0, 'TRUE', 'FALSE');
        END
    END

  SUSPEND;
END^

CREATE OR ALTER procedure SP_GET_PART_TROCA_CONSULTA (
    PRCODPLATROCA integer,
    PRCHAVE integer)
returns (
    BDCODTER integer,
    BDNOMETER varchar(100))
as
declare variable WCODTER integer;
declare variable WNOMETER varchar(100);
BEGIN
  wCodTer = NULL;

  SELECT COUNT(TER.BDCODTER)
  FROM VEF_BASE_TPLANOACOESTROCA_TER TER
  WHERE TER.BDCODPLATROCA = :PRCODPLATROCA
  AND TER.BDCHAVE = :PRCHAVE
  INTO :wCodTer;

  BDCODTER = NULL;
  BDNOMETER = NULL;

  IF (:wCodTer = 1) THEN
    BEGIN
      SELECT FIRST 1 T.BDCODTER, T.BDNOME
      FROM VEF_BASE_TPLANOACOESTROCA_TER TER
      LEFT OUTER JOIN VW_TTERCEIRO_SIMPLES T ON (T.BDCODTER = TER.BDCODTER)
      WHERE TER.BDCODPLATROCA = :PRCODPLATROCA
      AND TER.BDCHAVE = :PRCHAVE
      INTO :wCodTer, :wNomeTer;

      BDCODTER = :wCodTer;
      BDNOMETER = :wNomeTer;
    END


  SUSPEND;
END^

CREATE OR ALTER procedure SP_VAUD_INTRANET_INCONFORMIDADE (
    PRDESCRICAO varchar(5000))
returns (
    BDACAO varchar(5000),
    BDDESCRICAO varchar(5000))
as
declare variable WPOS integer;
declare variable WAUX varchar(5000);
declare variable WSEGSTR varchar(5000);
BEGIN
  wAux = prdescricao;
  wPos = 1;
  SELECT pos.pos FROM pos('Ação:', :waux) INTO :wpos;
  IF (wPos > 0) THEN
    BEGIN
      wSegStr = SUBSTRING(wAux FROM 1 FOR wPos - 1);
      waux = SUBSTRING(wAux FROM wPos + 0 FOR CHARACTER_LENGTH(prdescricao));
      IF (SUBSTRING(waux FROM 1 FOR 5) = 'Ação:') THEN
        BEGIN
          bdacao = :waux;
          bddescricao = :wsegstr;
        END
    END
SUSPEND;
END^

CREATE OR ALTER trigger vaud_intranet_inc_bi0 for vaud_intranet_inconformidade
active before insert or update position 0
AS
declare variable wacao VARCHAR(5000);
declare variable wdescricao VARCHAR(5000);
begin
  if (NEW.bdacao IS null) then
    BEGIN
      select BDDESCRICAO, BDACAO FROM sp_vaud_intranet_inconformidade(NEW.bddescricao) INTO wdescricao,wacao;
      NEW.bddescricao = wdescricao;
      NEW.bdacao = wacao;
    END
end^

-- XXXXXX - Raphael Teodoro - 22/07/2021
CREATE OR ALTER procedure SP_VRH_QUADRO_NOTURNO (
    PRCODPQUA integer,
    PRCODQH integer,
    PRHORAININOT time,
    PRHORAFIMNOT time,
    PRFIRST1 type of DM_BOOLEAN = 'TRUE')
returns (
    BDCODPQUA integer,
    BDCODQH integer,
    BDCODQHH integer,
    BDQHHSENT time,
    BDQHHSSAI time)
as
declare variable WSQL varchar(1300);
declare variable WHORAINISTR varchar(50);
declare variable WHORAFIMSTR varchar(70);
declare variable WFIRST1 varchar(10);
BEGIN
  IF ((prhoraininot is not NULL) and
      (prhorafimnot is not NULL)) THEN
     BEGIN
       IF (prfirst1 is distinct from 'TRUE') THEN
          wfirst1 = '';
       ELSE
          wfirst1 = ' first 1';

       whorainistr = 'CAST(CAST('''||prhoraininot||''' as TIME) as TIMESTAMP)';

       IF (prhorafimnot < prhoraininot) THEN
          whorafimstr = 'DATEADD(1 day to CAST(CAST('''||prhorafimnot||''' as TIME) as TIMESTAMP))';
       ELSE
          whorafimstr = 'CAST(CAST('''||prhorafimnot||''' as TIME) as TIMESTAMP)';

       -- Busca campos do quadro
       wsql = 'select QD.BDCODPQUA, QD.BDCODQH, QD.BDCODQHH,'||
                    ' CAST((select first 1 BDQHHSENT from VRH_BASE_TQH_HORAS where (BDCODQHH = QD.BDCODQHH) order by BDCODQHH'|| ', BDCODQHHS'|| ') as TIMESTAMP) BDQHHSENT,'||
                    ' CAST((select first 1 BDQHHSSAI from VRH_BASE_TQH_HORAS where (BDCODQHH = QD.BDCODQHH) order by BDCODQHH desc, BDCODQHHS desc) as TIMESTAMP) BDQHHSSAI'||
             ' from VRH_BASE_TQH_DIAS QD'||
             ' where (QD.BDCODPQUA = '||prcodpqua||')'||
               ' and (QD.BDCODQH = '||prcodqh||')'||
               ' and (QD.BDCODQHH is not NULL)';

       -- Ajusta dia quando passa da meia-noite
       wsql = 'select Q1.BDCODPQUA, Q1.BDCODQH, Q1.BDCODQHH,'||
                    ' Q1.BDQHHSENT,'||
                    ' CASE'||
                      ' WHEN (Q1.BDQHHSSAI <= Q1.BDQHHSENT) THEN DATEADD(1 day to Q1.BDQHHSSAI)'||
                      ' ELSE Q1.BDQHHSSAI'||
                    ' END BDQHHSSAI,'||
                    ' '||whorainistr||' BDINIHORANOTST,'||
                    ' '||whorafimstr||' BDFIMHORANOTST'||
             ' from ('||wsql||') Q1';

       -- Compara quadro com parametro
       wsql = 'select'||wfirst1||' Q2.BDCODPQUA, Q2.BDCODQH, Q2.BDCODQHH, Q2.BDQHHSENT, Q2.BDQHHSSAI'||
             ' from ('||wsql||') Q2'||
             ' where ((Q2.BDQHHSENT < Q2.BDFIMHORANOTST) and (Q2.BDQHHSSAI > Q2.BDINIHORANOTST))'||                                     -- Noite do mesmo dia
                ' or ((DATEADD(1 day to Q2.BDQHHSENT) < Q2.BDFIMHORANOTST) and (DATEADD(1 day to Q2.BDQHHSSAI) > Q2.BDINIHORANOTST))'|| -- Manha do proximo dia
                ' or ((Q2.BDQHHSENT < dateadd(1 day to Q2.BDFIMHORANOTST)) and (Q2.BDQHHSSAI > dateadd(1 day to Q2.BDINIHORANOTST)))';  -- Somente proximo dia

       FOR EXECUTE STATEMENT wsql into :BDCODPQUA, :BDCODQH, :BDCODQHH, :BDQHHSENT, :BDQHHSSAI DO
       BEGIN
         SUSPEND;
       END
     END
END^

-- XXXXXX - Raphael Teodoro - 25/06/2021
CREATE OR ALTER procedure SP_VAUD_PREAUD_INDHORARIONOT (
    PREMP varchar(15000))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATACOL date,
    BDINDHORARIONOTANT integer,
    BDINDHORARIONOT integer)
as
declare variable WAND varchar(7);
declare variable WSQL varchar(20000);
declare variable WKEY char(8);
BEGIN
  wand = ' where ';
  premp = coalesce(premp,'');
  IF (premp <> '') THEN
     BEGIN
       premp = wand||premp;
       wand = ' and ';
     END

  premp = premp||wand||'(COALESCE(BDINDHORARIONOT,0) = 0)';

  -- Busca dado diario do colaborador
  wsql = 'select RDB$DB_KEY as BDKEY, BDCODEMP, BDCODCOL, BDDATACOL, BDCODPQUA, BDCODQH,'||
               ' CAST((select BDAAAAMM from AAAAMM(BDDATACOL)) AS INTEGER) BDREFCOL, BDINDHORARIONOT'||
        ' from VRH_EMP_TCOL_VINCDIA'||
          premp||
           ' and (BDCODPQUA is not null)'||
           ' and (BDCODQH is not null)';

  -- Busca dado mensal do colaborador
  wsql = 'select T1.*,'||
               ' COALESCE((select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where (BDCODEMP = T1.BDCODEMP) and (BDCODCOL = T1.BDCODCOL) and (BDREFCOL <= T1.BDREFCOL) order by BDCODEMP desc, BDCODCOL desc, BDREFCOL desc),'||
                        ' (select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where (BDCODEMP = T1.BDCODEMP) and (BDCODCOL = T1.BDCODCOL)'||                          ' order by BDCODEMP desc, BDCODCOL desc, BDREFCOL desc)) BDCODSINTRAB'||
        ' from ('||wsql||') T1';

  -- Busca referencia do sindicato
  wsql = 'select T2.*,'||
               ' COALESCE((select first 1 BDREFST from VRH_BASE_TSINDTREF where (BDCODSINTRAB = T2.BDCODSINTRAB) and (BDREFST <= T2.BDREFCOL) order by BDCODSINTRAB desc, BDREFST desc),'||
                        ' (select first 1 BDREFST from VRH_BASE_TSINDTREF where (BDCODSINTRAB = T2.BDCODSINTRAB)'||                         ' order by BDCODSINTRAB desc, BDREFST desc)) BDREFST'||
        ' from ('||wsql||') T2'||
        ' where (T2.BDCODSINTRAB is not NULL)';

  -- Busca se o quadro de horarios noturno
  wsql = 'select T3.*,'||
               ' CASE'||
                 ' WHEN (exists(select * from SP_VRH_QUADRO_NOTURNO(T3.BDCODPQUA, T3.BDCODQH, S.BDINIHORANOTST, S.BDFIMHORANOTST))) THEN 1'|| -- Sim
                 ' ELSE 2'|| -- Nao
               ' END BDNOVOINDHORARIONOT'||
        ' from ('||wsql||') T3'||
        ' left outer join VRH_BASE_TSINDTREF S on (S.BDCODSINTRAB = T3.BDCODSINTRAB) and (S.BDREFST = T3.BDREFST)'||
        ' where (S.BDINIHORANOTST is not NULL)'||
          ' and (S.BDFIMHORANOTST is not NULL)';

  -- Aplica alteracao somente nas diferencas
  wsql = 'select T4.BDKEY, T4.BDCODEMP, T4.BDCODCOL, T4.BDDATACOL, T4.BDINDHORARIONOT, T4.BDNOVOINDHORARIONOT'||
        ' from ('||wsql||') T4'||
        ' where (T4.BDINDHORARIONOT is distinct from T4.BDNOVOINDHORARIONOT)';

  -- Ordenacao
  wsql = wsql||' order by BDCODEMP, BDCODCOL, BDDATACOL';

  FOR EXECUTE STATEMENT wsql into :wkey, :BDCODEMP, :BDCODCOL, :BDDATACOL, :BDINDHORARIONOTANT, :BDINDHORARIONOT DO
  BEGIN
    update VRH_EMP_TCOL_VINCDIA set BDINDHORARIONOT = :BDINDHORARIONOT where (RDB$DB_KEY = :wkey);

    SUSPEND;
  END
END^

-- XXXXXX - Raphael Teodoro - 16/07/2021
CREATE OR ALTER procedure SP_VRH_SINDREF_INDHORARIONOT (
    PRSINTRAB varchar(15000),
    BDREFST integer,
    PRUPDATE type of DM_BOOLEAN,
    PRSOMENTEVAZIO type of DM_BOOLEAN = 'FALSE')
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATACOL date,
    BDINDHORARIONOTANT integer,
    BDINDHORARIONOT integer)
as
declare variable WAND varchar(7);
declare variable WINDHORARIONOT varchar(100);
declare variable WSQL varchar(20000);
declare variable WKEY char(8);
BEGIN
  windhorarionot = '';
  wand = ' where ';
  IF (COALESCE(prsomentevazio,'FALSE') = 'TRUE') THEN
     BEGIN
       windhorarionot = windhorarionot||wand||'(COALESCE(BDINDHORARIONOT,0) = 0)';
       wand = ' and ';
     END

  -- Busca dado diario do colaborador
  wsql = 'select RDB$DB_KEY as BDKEY, BDCODEMP, BDCODCOL, BDDATACOL, BDCODPQUA, BDCODQH,'||
               ' CAST((select BDAAAAMM from AAAAMM(BDDATACOL)) AS INTEGER) BDREFCOL, BDINDHORARIONOT'||
        ' from VRH_EMP_TCOL_VINCDIA'||
          windhorarionot||
          wand||'(BDCODPQUA is not null)'||
           ' and (BDCODQH is not null)';

  -- Busca dado mensal do colaborador
  wsql = 'select T1.*,'||
               ' COALESCE((select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where (BDCODEMP = T1.BDCODEMP) and (BDCODCOL = T1.BDCODCOL) and (BDREFCOL <= '||bdrefst||') order by BDCODEMP desc, BDCODCOL desc, BDREFCOL desc),'||
                        ' (select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where (BDCODEMP = T1.BDCODEMP) and (BDCODCOL = T1.BDCODCOL)'||                            ' order by BDCODEMP desc, BDCODCOL desc, BDREFCOL desc)) BDCODSINTRAB'||
        ' from ('||wsql||') T1';

  prsintrab = coalesce(prsintrab,'');
  IF (prsintrab <> '') THEN
     prsintrab = ' and '||REPLACE(prsintrab,'BDCODSINTRAB','T2.BDCODSINTRAB');

  -- Busca referencia do sindicato
  wsql = 'select T2.*,'||
               ' COALESCE((select first 1 BDREFST from VRH_BASE_TSINDTREF where (BDCODSINTRAB = T2.BDCODSINTRAB) and (BDREFST <= T2.BDREFCOL) order by BDCODSINTRAB desc, BDREFST desc),'||
                        ' (select first 1 BDREFST from VRH_BASE_TSINDTREF where (BDCODSINTRAB = T2.BDCODSINTRAB)'||                         ' order by BDCODSINTRAB desc, BDREFST desc)) BDREFST'||
        ' from ('||wsql||') T2'||
        ' where (T2.BDCODSINTRAB is not NULL)'||
          prsintrab;

  -- Busca se o quadro de horarios noturno
  wsql = 'select T3.*,'||
               ' CASE'||
                 ' WHEN (exists(select * from SP_VRH_QUADRO_NOTURNO(T3.BDCODPQUA, T3.BDCODQH, S.BDINIHORANOTST, S.BDFIMHORANOTST))) THEN 1'|| -- Sim
                 ' ELSE 2'|| -- Nao
               ' END BDNOVOINDHORARIONOT'||
        ' from ('||wsql||') T3'||
        ' left outer join VRH_BASE_TSINDTREF S on (S.BDCODSINTRAB = T3.BDCODSINTRAB) and (S.BDREFST = T3.BDREFST)'||
        ' where (S.BDINIHORANOTST is not NULL)'||
          ' and (S.BDFIMHORANOTST is not NULL)';

  -- Aplica alteracao somente nas diferencas
  wsql = 'select T4.BDKEY, T4.BDCODEMP, T4.BDCODCOL, T4.BDDATACOL, T4.BDINDHORARIONOT, T4.BDNOVOINDHORARIONOT'||
        ' from ('||wsql||') T4'||
        ' where (T4.BDINDHORARIONOT is distinct from T4.BDNOVOINDHORARIONOT)';

  -- Ordenacao
  wsql = wsql||' order by BDCODEMP, BDCODCOL, BDDATACOL';

  FOR EXECUTE STATEMENT wsql into :wkey, :BDCODEMP, :BDCODCOL, :BDDATACOL, :BDINDHORARIONOTANT, :BDINDHORARIONOT DO
  BEGIN
    IF (COALESCE(PRUPDATE,'FALSE') = 'TRUE') THEN
       update VRH_EMP_TCOL_VINCDIA set BDINDHORARIONOT = :BDINDHORARIONOT where (RDB$DB_KEY = :wkey);

    SUSPEND;
  END
END^

-- XXXXXX - Raphael Teodoro - 28/06/2021
CREATE OR ALTER procedure SP_VAUD_PREAUD_VERBAPADRAO
returns (
    BDCODVER integer,
    BDREFVER integer)
as
declare variable WKEY char(8);
BEGIN
  FOR select VER.RDB$DB_KEY, VER.BDCODVER, MIN(MINVALUE(COALESCE(TINC.BDREFVERPD, REF.BDREFVER),REF.BDREFVER))
      from VRH_BASE_TVERBAS VER
      left outer join VRH_BASE_TRUBRICAESOCIAL_VER ES on (ES.BDCODVER = VER.BDCODVER)
      left outer join VRH_BASE_TVERBAS_REF REF on (REF.BDCODVER = VER.BDCODVER)
      left outer join VRH_BASE_TVERBAS_PADRAO PD on (PD.BDCODVERPD = VER.BDCODVER) and (PD.BDREFVERPD = (COALESCE((select first 1 X.BDREFVERPD from VRH_BASE_TVERBAS_PADRAO X where (X.BDCODVERPD = REF.BDCODVER) and (X.BDREFVERPD <= REF.BDREFVER) order by X.BDCODVERPD desc, X.BDREFVERPD desc),
                                                                                                                  (select first 1 X.BDREFVERPD from VRH_BASE_TVERBAS_PADRAO X where (X.BDCODVERPD = REF.BDCODVER)                                    order by X.BDCODVERPD desc, X.BDREFVERPD desc) )))
      left outer join VRH_BASE_TRUBRICAES_VER_PD ESPD on ESPD.BDCODVER = PD.BDCODVERPD
      left outer join (select TP.BDCODVERPD, TP.BDREFVERPD
                       from VRH_BASE_TVERBAS_PADRAO TP
                       left outer join VRH_BASE_TVERBAS_REF TR on (TR.BDCODVER = TP.BDCODVERPD) and (TR.BDREFVER = TP.BDREFVERPD)
                       where (TR.BDCODVER is null)) TINC on (TINC.BDCODVERPD = VER.BDCODVER)
      where (VER.BDTIPOVER = 1)
        and (CHAR_LENGTH(VER.BDCLAVER) >= 13)
        and ((PD.BDCODVERPD is NULL) or
             (TINC.BDCODVERPD is not NULL) or
             (coalesce(PD.BDTIPOCODVERPD, 0) <> coalesce(REF.BDTIPOCODVER, 0)) or
             (coalesce(PD.BDINSSVERPD, 0) <> coalesce(REF.BDINSSVER, 0)) or
             (coalesce(PD.BDFGTSVERPD, 0) <> coalesce(REF.BDFGTSVER, 0)) or
             (coalesce(PD.BDIRVERPD, 0) <> coalesce(REF.BDIRVER, 0)) or
             (coalesce(PD.BDTIPOREFVERPD, 0) <> coalesce(REF.BDTIPOREFVER, 0)) or
             (coalesce(PD.BDBASESFVERPD, 0) <> coalesce(REF.BDBASESFVER, 0)) or
             ((CASE WHEN (PD.BDPISVERPD           = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDPISVER           = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDBASEHEVERPD        = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDBASEHEVER        = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDBASEMAIORVERPD     = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDBASEMAIORVER     = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDRAISVERPD          = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDRAISVER          = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDBASEGPSVERPD       = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDBASEGPSVER       = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDMENORESVERPD       = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDMENORESVER       = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDPROPVERPD          = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDPROPVER          = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDBASEVTVERPD        = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDBASEVTVER        = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDREEMBGPSVERPD      = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDREEMBGPSVER      = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             (coalesce(PD.BDHEVERPD, 0) <> coalesce(REF.BDHEVER, 0)) or
             ((CASE WHEN (PD.BDGRAVAFICHAHNVERPD  = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDGRAVAFICHAHNVER  = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             (coalesce(PD.BDCCPRINCIPALVERPD, '') <> coalesce(REF.BDCCPRINCIPALVER, '')) or
             (coalesce(PD.BDFORMREFVERPD, '') <> coalesce(REF.BDFORMREFVER, '')) or
             (coalesce(PD.BDFORMVALVERPD, '') <> coalesce(REF.BDFORMVALVER, '')) or
             ((CASE WHEN (PD.BDBASEDSRHEVERPD     = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDBASEDSRHEVER     = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDBASEDSRRVVERPD     = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDBASEDSRRVVER     = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             (coalesce(PD.BDFORMREFAUXVERPD, '') <> coalesce(REF.BDFORMREFAUXVER, '')) or
             ((CASE WHEN (PD.BDDEDFORMREFAUXVERPD = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDDEDFORMREFAUXVER = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDDEDFORMREFVERPD    = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDDEDFORMREFVER    = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDDEDFORMVALVERPD    = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDDEDFORMVALVER    = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDRENDISENTOIRVERPD  = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDRENDISENTOIRVER  = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             (coalesce(PD.BDFORMINTVERPD, '') <> coalesce(REF.BDFORMINTVER, '')) or
             ((CASE WHEN (PD.BDPAGAESTOUROVERPD   = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDPAGAESTOUROVER   = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDSIMPLESNACIONALPD  = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDSIMPLESNACIONAL  = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDBASE13HNPD         = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDBASE13HN         = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDBASEFERHNPD        = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDBASEFERHN        = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDBASEAVHNPD         = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDBASEAVHN         = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDGARANTIAMINVERPD   = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDGARANTIAMINVER   = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDNAOCONVHORASVERPD  = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDNAOCONVHORASVER  = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDBASEDSRHNVERPD     = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDBASEDSRHNVER     = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDBASEDSROUVERPD     = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDBASEDSROUVER     = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             ((CASE WHEN (PD.BDREMINTERMVERPD     = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (REF.BDREMINTERMVER     = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
             (coalesce(PD.BDCODINCIDINSS, 0) <> coalesce(REF.BDCODINCIDINSS, 0)) or
             (coalesce(PD.BDCODINCIDFGTS, 0) <> coalesce(REF.BDCODINCIDFGTS, 0)) or
             (coalesce(PD.BDCODINCIDIRRF, 0) <> coalesce(REF.BDCODINCIDIRRF, 0)) or
             ((REF.BDREFVER = (select first 1 BDREFVERPD
                               from VRH_BASE_TVERBAS_PADRAO
                               where (BDCODVERPD = VER.BDCODVER)
                               order by BDCODVERPD desc, BDREFVERPD desc)) and
              ((coalesce(PD.BDAPEVERPD, '') <> coalesce(VER.BDAPEVER, '')) or
               (coalesce(PD.BDDESCVERPD, '') <> coalesce(VER.BDDESCVER, '')) or
               (coalesce(PD.BDDESCREDVERPD, '') <> coalesce(VER.BDDESCREDVER, '')) or
               (coalesce(PD.BDCLAVERPD, '') <> coalesce(VER.BDCLAVER, '')) or
               (coalesce(PD.BDSITVERPD,  0) <> coalesce(VER.BDSITVER, 0)) or
               ((CASE WHEN (PD.BDSITMATVERPD        = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (VER.BDSITMATVER        = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
               ((CASE WHEN (PD.BDSITDOEVERPD        = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (VER.BDSITDOEVER        = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
               ((CASE WHEN (PD.BDSITACITRABVERPD    = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (VER.BDSITACITRABVER    = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
               ((CASE WHEN (PD.BDSITMILITARVERPD    = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (VER.BDSITMILITARVER    = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
               ((CASE WHEN (PD.BDSITMATEMPVERPD     = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (VER.BDSITMATEMPVER     = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
               ((CASE WHEN (PD.BDSITACITRAB15VERPD  = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (VER.BDSITACITRAB15VER  = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
               ((CASE WHEN (PD.BDSITDOETRABVERPD    = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (VER.BDSITDOETRABVER    = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
               ((CASE WHEN (PD.BDSITLICVENCVERPD    = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (VER.BDSITLICVENCVER    = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
               ((CASE WHEN (PD.BDSITDOE15VERPD      = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (VER.BDSITDOE15VER      = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
               ((CASE WHEN (PD.BDSITSINDICALVERPD   = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (VER.BDSITSINDICALVER   = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
               ((CASE WHEN (PD.BDSITAPOINVVERPD     = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (VER.BDSITAPOINVVER     = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
               ((CASE WHEN (PD.BDSITOUTRASPD        = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (VER.BDSITOUTRASVER     = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
               ((CASE WHEN (PD.BDBASESALRAISPD      = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END) <> (CASE WHEN (VER.BDBASESALRAIS      = 'TRUE') THEN 'TRUE' ELSE 'FALSE' END)) or
               (coalesce(PD.BDCODRESPD, ESPD.BDCHAVE, 0) not in (0, coalesce(ES.BDCHAVE, 0)))
              )
             )
            )
      group by 1, 2
      order by BDCODVER
  into :wkey, :BDCODVER, :BDREFVER DO
  BEGIN
    update VRH_BASE_TVERBAS set BDTIPOVER = 0 where (RDB$DB_KEY = :wkey);

    SUSPEND;
  END
END^

-- XXXXXX - Raphael Teodoro - 01/07/2021
CREATE OR ALTER procedure SP_VAUD_PREAUD_TIPOJORNADA (
    PREMP varchar(15000))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATACOL date,
    BDTIPOJORNADA integer,
    BDTIPOJORNADAANT integer)
as
declare variable WAND varchar(7);
declare variable WSQL varchar(20000);
declare variable WKEY char(8);
BEGIN
  wand = ' where ';
  premp = coalesce(premp,'');
  IF (premp <> '') THEN
     BEGIN
       premp = wand||premp;
       wand = ' and ';
     END

  -- Busca dado de partida do colaborador
  wsql = 'select RDB$DB_KEY as BDKEY, BDCODEMP, BDCODCOL, NULL as BDDATACOL, BDCODPQUA, BDCODQH, BDTIPOJORNADA,'||
               ' 4 as BDNOVOTIPOJORNADA'|| -- tjDiarioFolgaVarDom
        ' from VRH_EMP_TCOLCON_PARTIDA'||
          premp||
          wand||'(COALESCE(BDTIPOJORNADA,0) = 1)'|| -- tjDiarioFolgaFixa
           ' and (COALESCE(BDREGJORTRAB,0) = 0)'||  -- trjtHOR
           ' and (BDCODPQUA is not null)'||
           ' and (BDCODQH is not null)';

  -- Busca dado diario do colaborador
  wsql = wsql||
        ' union all'||
        ' select RDB$DB_KEY as BDKEY, BDCODEMP, BDCODCOL, BDDATACOL, BDCODPQUA, BDCODQH, BDTIPOJORNADA,'||
               ' 4 as BDNOVOTIPOJORNADA'|| -- tjDiarioFolgaVarDom
        ' from VRH_EMP_TCOL_VINCDIA'||
          premp||
          wand||'(COALESCE(BDTIPOJORNADA,0) = 1)'|| -- tjDiarioFolgaFixa
           ' and (COALESCE(BDREGJORTRAB,0) = 0)'||  -- trjtHOR
           ' and (BDCODPQUA is not null)'||
           ' and (BDCODQH is not null)';

  -- Busca campos do quadro
  wsql = 'select T1.BDKEY, T1.BDCODEMP, T1.BDCODCOL, T1.BDDATACOL, T1.BDTIPOJORNADA, T1.BDNOVOTIPOJORNADA'||
        ' from ('||wsql||') T1'||
        ' left outer join VRH_BASE_TQH_DIAS QD on (QD.BDCODPQUA = T1.BDCODPQUA) and (QD.BDCODQH = T1.BDCODQH) and (QD.BDDIASEMQH = 0)'||
        ' where ((QD.BDCODQHH is NULL) or (QD.BDDSR = ''TRUE''))';

  -- Ordenacao
  wsql = wsql||' order by BDCODEMP, BDCODCOL, BDDATACOL';

  FOR EXECUTE STATEMENT wsql INTO :wkey, :BDCODEMP, :BDCODCOL, :BDDATACOL, :BDTIPOJORNADAANT, :BDTIPOJORNADA DO
  BEGIN
    IF (BDDATACOL is not NULL) THEN
       update VRH_EMP_TCOL_VINCDIA set BDTIPOJORNADA = :BDTIPOJORNADA where (RDB$DB_KEY = :wkey);
    ELSE
       update VRH_EMP_TCOLCON_PARTIDA set BDTIPOJORNADA = :BDTIPOJORNADA where (RDB$DB_KEY = :wkey);

    SUSPEND;
  END
END^

-- XXXXXX - Raphael Teodoro - 12/07/2021
CREATE OR ALTER procedure SP_VAUD_PREAUD_VERBASEMINCID_IR
returns (
    BDCODVER integer,
    BDREFVER integer,
    BDCODINCIDIRRFANT integer,
    BDCODINCIDIRRF integer)
as
declare variable WKEY char(8);
BEGIN
  FOR select *
      from (select REF.rdb$db_key as BDKEY, REF.BDCODVER, REF.BDREFVER, REF.BDCODINCIDIRRF,
                   CASE
                     -- Remuneração INSS, Remuneração sem incidência
                     WHEN (VER.BDCODVER in (121001, 121003)) THEN 701
                     -- Ajuda de custo sem "Indenizações por rescisão" ou "Rendimento isento para IR"
                     WHEN ((coalesce(REF.BDCODINCIDIRRF, 0) = 0) and
                           (SUBSTRING(VER.BDCLAVER FROM 1 FOR 9) in ('0.040.0.1')) and
                           (REF.BDINDRESC is distinct from 'TRUE') and
                           (REF.BDRENDISENTOIRVER is distinct from 'TRUE')) THEN 73
                     -- "Indenizacao por rescisao" (ou fer.resc. em dobro) sem "Rendimento isento para IR"
                     WHEN ((coalesce(REF.BDCODINCIDIRRF, 0) = 0) and
                           ((REF.BDINDRESC = 'TRUE') or (SUBSTRING(VER.BDCLAVER FROM 1 FOR 5) in ('7.032', '7.033'))) and
                           (REF.BDRENDISENTOIRVER is distinct from 'TRUE')) THEN 74
                     -- Abono
                     WHEN ((coalesce(REF.BDCODINCIDIRRF, 0) = 0) and
                           (SUBSTRING(VER.BDCLAVER FROM 1 FOR 5) in ('3.003', '3.004', '3.007'))) THEN 75
                     -- Complemento de abono
                     WHEN (SUBSTRING(VER.BDCLAVER FROM 1 FOR 7) in ('0.210.2', '0.210.3')) THEN 75
                     -- "Rendimento isento para IR" sem "Indenização por rescisão"
                     WHEN ((coalesce(REF.BDCODINCIDIRRF, 0) = 0) and
                           (REF.BDRENDISENTOIRVER = 'TRUE') and
                           (REF.BDINDRESC is distinct from 'TRUE')) THEN 79
                     -- Aluguéis sem "Indenizações por rescisão" ou "Rendimento isento para IR"
                     WHEN ((coalesce(REF.BDCODINCIDIRRF, 0) = 0) and
                           (SUBSTRING(VER.BDCLAVER FROM 1 FOR 9) in ('0.030.1.1')) and
                           (REF.BDINDRESC is distinct from 'TRUE') and
                           (REF.BDRENDISENTOIRVER is distinct from 'TRUE')) THEN 700
                     -- Diária sem "Indenizações por rescisão" ou "Rendimento isento para IR"
                     WHEN ((coalesce(REF.BDCODINCIDIRRF, 0) = 0) and
                           (SUBSTRING(VER.BDCLAVER FROM 1 FOR 9) in ('0.040.0.0')) and
                           (REF.BDINDRESC is distinct from 'TRUE') and
                           (REF.BDRENDISENTOIRVER is distinct from 'TRUE')) THEN 72
                     -- Informativas
                     WHEN ((coalesce(REF.BDCODINCIDIRRF, 0) = 0) and
                           (REF.BDTIPOCODVER in (2,3))) THEN 09
                     -- Sem "Indenização por rescisão" e sem "Rendimento isento para IR"
                     WHEN ((coalesce(REF.BDCODINCIDIRRF, 0) = 0) and
                           (REF.BDRENDISENTOIRVER is distinct from 'TRUE') and
                           (REF.BDINDRESC is distinct from 'TRUE') and
                           (SUBSTRING(VER.BDCLAVER FROM 1 FOR 5) not in ('3.003', '3.004', '3.007')) and
                           (SUBSTRING(VER.BDCLAVER FROM 1 FOR 7) not in ('0.210.2', '0.210.3')) and
                           (SUBSTRING(VER.BDCLAVER FROM 1 FOR 9) not in ('0.030.1.1', '0.040.0.0', '0.040.0.1')) and
                           (SUBSTRING(VER.BDCLAVER FROM 1 FOR 9) not in ('0.001.0.0', '0.003.0.0', '0.003.0.1', '0.180.0.0', '0.180.1.0', '0.420.0.0', '0.420.0.1')) and
                           (SUBSTRING(VER.BDCLAVER FROM 1 FOR 9) not in ('0.800.6.0', '0.800.6.1', '0.900.3.0', '7.001.1.4')) ) THEN 09
                     ELSE REF.BDCODINCIDIRRF
                   END BDNOVOCODINCIDIRRF
            from VRH_BASE_TVERBAS_REF REF
            left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = REF.BDCODVER)
            where (coalesce(REF.BDCODINCIDIRRF, 0) in (0,79))
           )
      where (BDCODINCIDIRRF <> BDNOVOCODINCIDIRRF)
      order by BDCODVER, BDREFVER
  into :wkey, :BDCODVER, :BDREFVER, :BDCODINCIDIRRFANT, :BDCODINCIDIRRF DO
  BEGIN
    update VRH_BASE_TVERBAS_REF set BDCODINCIDIRRF = :BDCODINCIDIRRF where (RDB$DB_KEY = :wkey);

    SUSPEND;
  END
END^

-- XXXXXX - Raphael Teodoro - 05/07/2021
CREATE OR ALTER procedure SP_VAUD_PREAUD_VERBA_INSSFGTS
returns (
    BDCODVER integer,
    BDREFVER integer,
    BDCODINCIDINSSANT integer,
    BDCODINCIDINSS integer,
    BDCODINCIDFGTSANT integer,
    BDCODINCIDFGTS integer)
as
declare variable WKEY char(8);
BEGIN
  FOR select *
      from (select REF.rdb$db_key as BDKEY, REF.BDCODVER, REF.BDREFVER,
                   REF.BDCODINCIDINSS,
                   CASE
                     -- INSS Férias
                     WHEN (coalesce(REF.BDCODINCIDINSS, 0) = 11) THEN 00
                     WHEN (REF.BDCODVER = 91015) THEN 00
                     ELSE REF.BDCODINCIDINSS
                   END BDNOVOCODINCIDINSS,
                   REF.BDCODINCIDFGTS,
                   CASE
                     -- FGTS Férias
                     WHEN (coalesce(REF.BDCODINCIDFGTS, 0) = 11) THEN 00
                     ELSE REF.BDCODINCIDFGTS
                   END BDNOVOCODINCIDFGTS
            from VRH_BASE_TVERBAS_REF REF
            left outer join VRH_BASE_TVERBAS VER on (VER.BDCODVER = REF.BDCODVER)
            where (REF.BDCODVER = 91015)
               or ((SUBSTRING(VER.BDCLAVER FROM 1 FOR 7) in ('3.001.0', '3.001.1', '3.001.2', '3.002.0')) and
                   ((coalesce(REF.BDCODINCIDINSS, 0) = 11) or (coalesce(REF.BDCODINCIDFGTS, 0) = 11)))
           )
      where (BDCODINCIDINSS <> BDNOVOCODINCIDINSS)
         or (BDCODINCIDFGTS <> BDNOVOCODINCIDFGTS)
      order by BDCODVER, BDREFVER
  into :wkey, :BDCODVER, :BDREFVER, :BDCODINCIDINSSANT, :BDCODINCIDINSS, :BDCODINCIDFGTSANT, :BDCODINCIDFGTS DO
  BEGIN
    update VRH_BASE_TVERBAS_REF
    set BDCODINCIDINSS = :BDCODINCIDINSS,
        BDCODINCIDFGTS = :BDCODINCIDFGTS
    where (RDB$DB_KEY = :wkey);

    SUSPEND;
  END
END^

create or alter procedure VRHF_SP_ESTAB_ESOCIAL_OBRA (
    PRCENCUS integer,
    PRPLANOCUS integer)
returns (
    BDCODCENCUS integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDTIPOTOM integer,
    BDCNPJTOM varchar(18),
    BDCODLOT integer,
    BDNOMTOM varchar(40))
as
declare variable WCLASSIFICACAO varchar(80);
declare variable WSQL varchar(1000);
declare variable WTIPO integer;
declare variable WSQLRETORNO varchar(1000);
declare variable WPOS integer;
BEGIN
  /*
    bdtipo = 1 Tomador
   */
  IF (prplanocus IS NULL) THEN
     prplanocus = 0;

  IF (prcencus IS NULL) THEN
     prcencus = 0;
  bdcodcencus = prcencus;
  wsql = 'select cla.BDCTALON,cla.BDTIPO from centros_tpcc cla where cla.bdcodcentro = '||CAST(prplanocus AS VARCHAR(20))||' and cla.bdcodtpcc = '||CAST(prcencus AS VARCHAR(20));
  EXECUTE STATEMENT wsql INTO wclassificacao,wtipo;

  SELECT pos FROM pos('.',:wclassificacao) INTO wpos;

  IF (wPos > 0) THEN
     BEGIN
       IF (wtipo <> 1) THEN
          BEGIN
            prcencus = NULL;
            SELECT FIRST 1 cla.BDCTALON,cla.BDTIPO,cla.bdcodtpcc FROM centros_tpcc cla
                   join VRH_BASE_TCUSTOM CUS on (CUS.BDCODCENTRO = cla.BDCODCENTRO and CUS.BDCODTPCC = cla.BDCODTPCC)
                   WHERE cla.bdcodcentro = :prplanocus
                   AND cla.bdctalon = SUBSTRING(:wclassificacao FROM 1 FOR CHAR_LENGTH(cla.bdctalon))
                   and cus.bdcodlot in (1,21) -- Apenas obra própria deve retornar
                   AND cla.bdtipo = 1  ORDER BY cla.BDCTALON DESC
            INTO :wclassificacao,:wtipo,:prcencus;
     
            IF (prcencus IS NULL) THEN
               prcencus = 0;
          END
     END
  ELSE
     BEGIN
       IF (wtipo <> 1) THEN
          BEGIN
            prcencus = 0;
          END
     END

  wsqlretorno = 'select TPCC.BDCODCENTRO, TPCC.BDCODTPCC, TOM.BDTIPOTOM, TOM.BDCNPJTOM, TOM.BDCODLOT, PCC.BDNOME '||
                ' from centros_tpcc TPCC'||
                ' left outer join vrh_base_tcustom TOM on (TOM.BDCODCENTRO = TPCC.BDCODCENTRO and TOM.BDCODTPCC = TPCC.BDCODTPCC)'||
                ' left outer join tcentros PCC on (PCC.BDCODCENTRO = TPCC.BDCODCENTRO)'||
                ' where TPCC.bdcodcentro = '||CAST(prplanocus AS VARCHAR(20))||' and TPCC.bdcodtpcc = '||CAST(prcencus AS VARCHAR(20))||
                ' and TOM.bdcodlot in (1,21)';

  EXECUTE STATEMENT wsqlretorno INTO
    :bdcodcentro ,
    :bdcodtpcc ,
    :BDTIPOTOM ,
    :BDCNPJTOM ,
    :BDCODLOT ,
    :BDNOMTOM;
  SUSPEND;
END^

create or alter procedure SP_VRHF_ESOCIAL_EVT_ENVIADO_ULT (
    PRCODEMP integer,
    PRCODIGO integer,
    PRCODVINC integer)
returns (
    BDCODEMP integer,
    BDCODIGO integer,
    BDCODVINC integer,
    BDSTATUSVINC integer,
    BDRECIBOVINC varchar(30))
as
begin
  /* Procedure Text */
  BDCODEMP = prCodemp;
  BDCODIGO = prCodigo;
  BDCODVINC = null;
  BDSTATUSVINC = null;
  BDRECIBOVINC = null;

  if (coalesce(PRCODVINC,0) > 0) then
     begin
       select arq.bdeventovinc,arq.bdstatus,arq.bdrecibo from vrh_esocial_tarquivo arq
           where arq.bdcodemp = :prcodemp and arq.bdcodigo = :prcodvinc into bdcodvinc, bdstatusvinc, bdrecibovinc;

       if ((bdcodvinc is not null) and (bdrecibovinc is null)) then
          begin
            select bdcodvinc, bdstatusvinc, bdrecibovinc from sp_vrhf_esocial_evt_enviado_ult(:prcodemp,0,:bdcodvinc) a into bdcodvinc, bdstatusvinc, bdrecibovinc;
          end
     end
  suspend;
end^

CREATE OR ALTER trigger vsst_emp_condamb_bi0 for vsst_emp_condamb
active before insert position 0
as
declare variable VNOVA_CHAVE integer;
begin
  if ((new.BDCHAVE is null) or (new.BDCHAVE = 0)) then
  begin
    select coalesce((max(BDCHAVE) + 1), 1)
    from VSST_EMP_CONDAMB
    where (BDCODEMP = new.BDCODEMP) and
          (BDCODCOL = new.BDCODCOL)
    into VNOVA_CHAVE;
    new.BDCHAVE = VNOVA_CHAVE;
  end
end^

CREATE OR ALTER TRIGGER VSST_EMP_AGENTENOCIVO_BI0 FOR VSST_EMP_AGENTENOCIVO
ACTIVE BEFORE INSERT POSITION 0
as
declare variable VNOVA_ORDEM integer;
begin
  if ((new.BDORDEM is null) or (new.BDORDEM = 0)) then
  begin
    select coalesce((max(BDORDEM) + 1), 1)
    from VSST_EMP_AGENTENOCIVO
    where (BDCODEMP = new.BDCODEMP) and
          (BDCODCOL = new.BDCODCOL) and
          (BDCHAVE = new.BDCHAVE)
    into VNOVA_ORDEM;
    new.BDORDEM = VNOVA_ORDEM;
  end

  if (new.bdcoduni=0) then
     new.bdcoduni = null;
end^

CREATE OR ALTER trigger vsst_emp_agentenocivo_epi_bi0 for vsst_emp_agentenocivo_epi
active before insert position 0
as
declare variable VNOVA_ORDEMEPI integer;
begin
  if ((new.BDORDEMEPI is null) or (new.BDORDEMEPI = 0)) then
  begin
    select coalesce((max(BDORDEMEPI) + 1), 1)
    from VSST_EMP_AGENTENOCIVO_EPI
    where (BDCODEMP = new.BDCODEMP) and
          (BDCODCOL = new.BDCODCOL) and
          (BDCHAVE  = new.BDCHAVE) and
          (BDORDEM  = new.BDORDEM)
    into VNOVA_ORDEMEPI;
    new.BDORDEMEPI = VNOVA_ORDEMEPI;
  end
end^

CREATE OR ALTER trigger vsst_emp_respregamb_bi0 for vsst_emp_respregamb
active before insert position 0
as
declare variable VNOVA_ORDEM integer;
begin
  if ((new.BDORDEM is null) or (new.BDORDEM = 0)) then
  begin
    select coalesce((max(BDORDEM) + 1), 1)
    from VSST_EMP_RESPREGAMB
    where (BDCODEMP = new.BDCODEMP) and
          (BDCODCOL = new.BDCODCOL) and
          (BDCHAVE  = new.BDCHAVE)
    into VNOVA_ORDEM;
    new.BDORDEM = VNOVA_ORDEM;
  end
end^

CREATE OR ALTER trigger vsst_emp_respregamb_biu0 for vsst_emp_respregamb
active before insert or update position 0
AS
begin
  if (coalesce(new.BDTIPORESPONSAVEL,0) = 0) then
  begin
    new.BDRESPONSAVELEMP = null;
  end
  else
  begin
    new.BDCODRESP = null;
  end
end^

CREATE OR ALTER trigger vsst_base_epi_bi0 for vsst_base_epi
active before insert position 0
as
declare variable VCODEPI integer;
begin
  if ((new.BDCODEPI is null) or (new.BDCODEPI = 0)) then
  begin
    select coalesce((max(BDCODEPI) + 1), 1)
    from VSST_BASE_EPI
    into VCODEPI;
    new.BDCODEPI = VCODEPI;
  end
end^

create or alter procedure SP_CONTABILIZACAO_CALCULOS (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXAFILIAIS smallint = 0)
returns (
    BDCODEMP integer,
    BDCODEMPSUC integer,
    BDCHAVE integer,
    BDCODCOL integer,
    BDCODTER integer,
    BDREFFN integer,
    BDTIPOFOL integer,
    BDORDEM integer)
as
declare variable WSQL varchar(32700);
declare variable WSQLEMP varchar(25000);
begin
  if (coalesce(premp,  '') <> '') then
     begin
       if (coalesce(prpuxafiliais, 0) = 1) then
          wsqlemp = 'select bdcodemp from TEMPRESAS where ('||premp||') or ('||replace(upper(premp), 'BDCODEMP', 'BDCODMATRIZ')||')';
       else
          wsqlemp = 'select bdcodemp from TEMPRESAS where '||premp;
     end
  else
     wsqlemp = 'select bdcodemp from TEMPRESAS ';

  for execute statement wsqlemp into :BDCODEMP do
    begin
       wsql = 'select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, BDREFFN, 0 BDTIPOFOL, cast(null as integer) BDORDEM '||
              'from TOL_VRHF_EMP_TCALC_FN where BDREFFN between '||prrefini||' and '||prreffim||' and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, BDREFTOMADOR, 0 BDTIPOFOL, BDORDEM '||
              'from TOL_VRHF_EMP_TCALC_FT where BDREFTOMADOR between '||prrefini||' and '||prreffim||' and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, BDREFFN, 0 BDTIPOFOL, cast(null as integer) BDORDEM '||
              'from TOL_VRHF_EMP_TCALC_INT where BDREFFN between '||prrefini||' and '||prreffim||' and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, BDREFTOMADOR, 0 BDTIPOFOL, BDORDEM '||
              'from TOL_VRHF_EMP_TCALC_TOMINT where BDREFTOMADOR between '||prrefini||' and '||prreffim||' and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       -- FOLHA COMPLEMENTAR/TOMADOR COMPLEMENTAR/INTERMITENTE COMPLEMENTAR/INTERMITENTE TOMADOR COMPLEMENTAR --
     
       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, SUBSTRING(BDREFFC FROM 1 FOR 6), 1 BDTIPOFOL, cast(null as integer) BDORDEM '||
              'from TOL_VRHF_EMP_TCALC_FN_FC where BDREFFC between '||prrefini||'01 and '||prreffim||'31 and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, SUBSTRING(BDREFFC FROM 1 FOR 6), 1 BDTIPOFOL, BDORDEM '||
              'from TOL_VRHF_EMP_TCALC_FT_FC where BDREFFC between '||prrefini||'01 and '||prreffim||'31 and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, SUBSTRING(BDREFFC FROM 1 FOR 6), 1 BDTIPOFOL, cast(null as integer) BDORDEM '||
              'from TOL_VRHF_EMP_TCALC_FN_FC_INT where BDREFFC between '||prrefini||'01 and '||prreffim||'31 and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, SUBSTRING(BDREFFC FROM 1 FOR 6), 1 BDTIPOFOL, BDORDEM '||
              'from TOL_VRHF_EMP_TCALC_FT_FC_INT where BDREFFC between '||prrefini||'01 and '||prreffim||'31 and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       -- FÉRIAS --
     
       wsql = wsql||' union all select FE.BDCODEMP, FE.BDCODEMPSUC, FE.BDCHAVE, FE.BDCODCOL, FER.BDREFINIFE, 2 BDTIPOFOL, FER.BDORDEM '||
              'from TOL_VRHF_EMP_TCALC_FER FE '||
              'join VRH_EMP_TFERIAS FER on (FER.BDCODEMP = FE.BDCODEMP and FER.BDCODCOL = FE.BDCODCOL and FER.BDINIPERAQUISFE = FE.BDINIPERAQUISFE and FER.BDCODFE = FE.BDCODFE) '||
              'where FER.BDREFPAGFE between '||prrefini||' and '||prreffim||' and FE.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(prcol), 'BDCODCOL', 'FE.BDCODCOL');

       -- ADIANTAMENTO SALARIAL --
     
       wsql = wsql||' union all select AD.BDCODEMP, AD.BDCODEMPSUC, AD.BDCHAVE, AD.BDCODCOL, ADS.BDREFAD, 3 BDTIPOFOL, ADS.BDORDEM '||
              'from TOL_VRHF_EMP_TCALC_AD AD '||
              'join VRHF_EMP_TADSAL ADS on (ADS.BDCODEMP = AD.BDCODEMP and ADS.BDCODCOL = AD.BDCODCOL and ADS.BDDATAAD = AD.BDDATAAD) '||
              'where ADS.BDREFAD between '||prrefini||' and '||prreffim||' and AD.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(prcol), 'BDCODCOL', 'AD.BDCODCOL');

       -- ADIANTAMENTO 13º SALÁRIO --
     
       wsql = wsql||' union all select AD13.BDCODEMP, AD13.BDCODEMPSUC, AD13.BDCHAVE, AD13.BDCODCOL, ADS13.BDREFA13, 4 BDTIPOFOL, ADS13.BDORDEM '||
              'from TOL_VRHF_EMP_TCALC_A13 AD13 '||
              'join VRHF_EMP_TA13SAL ADS13 on (ADS13.BDCODEMP = AD13.BDCODEMP and ADS13.BDCODCOL = AD13.BDCODCOL and ADS13.BDREFA13 = AD13.BDREFA13) '||
              'where AD13.BDREFA13 between '||prrefini||' and '||prreffim||' and AD13.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(prcol), 'BDCODCOL', 'AD13.BDCODCOL');

       -- 13º SALÁRIO --
     
       wsql = wsql||' union all select S13.BDCODEMP, S13.BDCODEMPSUC, S13.BDCHAVE, S13.BDCODCOL, SS13.BDREF13, 5 BDTIPOFOL, SS13.BDORDEM '||
              'from TOL_VRHF_EMP_TCALC_13 S13 '||
              'join VRHF_EMP_T13SAL SS13 on (SS13.BDCODEMP = S13.BDCODEMP and SS13.BDCODCOL = S13.BDCODCOL and SS13.BDREF13 = S13.BDREF13) '||
              'where S13.BDREF13 between '||prrefini||' and '||prreffim||' and S13.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(prcol), 'BDCODCOL', 'S13.BDCODCOL');

       -- COMPLEMENTO 13º SALÁRIO --
     
       wsql = wsql||' union all select C13.BDCODEMP, C13.BDCODEMPSUC, C13.BDCHAVE, C13.BDCODCOL, CS13.BDREFC13, 6 BDTIPOFOL, CS13.BDORDEM '||
              'from TOL_VRHF_EMP_TCALC_C13 C13 '||
              'join VRHF_EMP_TC13SAL CS13 on (CS13.BDCODEMP = C13.BDCODEMP and CS13.BDCODCOL = C13.BDCODCOL and CS13.BDREF13 = C13.BDREF13 and CS13.BDREFC13 = C13.BDREFC13) '||
              'where C13.BDREFC13 between '||prrefini||' and '||prreffim||' and C13.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(prcol), 'BDCODCOL', 'C13.BDCODCOL');

       -- FOLHA AVULSA --
     
       wsql = wsql||' union all select FA.BDCODEMP, FA.BDCODEMPSUC, FA.BDCHAVE, FA.BDCODCOL, FAS.BDREF, 7 BDTIPOFOL, FAS.BDORDEM '||
              'from TOL_VRHF_EMP_TCALC_FA FA '||
              'join VRHF_EMP_TFOLHAAVULSA FAS on (FAS.BDCODEMP = FA.BDCODEMP and FAS.BDCODCOL = FA.BDCODCOL and FAS.BDCODTCA = FA.BDCODTCA and FAS.BDDATAFA = FA.BDDATAFA) '||
              'where FAS.BDREF between '||prrefini||' and '||prreffim||' and FA.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(prcol), 'BDCODCOL', 'FA.BDCODCOL');

       BDCODTER = null;
       for execute statement wsql into :BDCODEMP, :BDCODEMPSUC, :BDCHAVE, :BDCODCOL, :BDREFFN, :BDTIPOFOL, :BDORDEM
       do
         suspend;
     
     
       -- SERVIÇOS AUTÔNOMOS --
     
       wsql = 'select SER.BDCODEMP, SER.BDCODEMPSUC, SER.BDCHAVE, SER.BDCODTER, SERV.BDREFINSSSERV, 8 BDTIPOFOL '||
              'from TOL_VRHF_EMP_TCALC_AUT SER '||
              'join VRHF_BASE_CALC_TERC SERV on (SERV.BDCODEMP = SER.BDCODEMPSUC and SERV.BDCODTER = SER.BDCODTER and SERV.BDCODSERV = SER.BDCODSERV) '||
              'join VRH_BASE_TSERVTERC S on (S.BDCODEMP = SER.BDCODEMP and S.BDCODTER = SER.BDCODTER) '||
              'where SERV.BDREFINSSSERV between '||prrefini||' and '||prreffim||' and SER.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(premp, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(premp), 'BDCODEMP', 'SER.BDCODEMP');
     
     
       BDCODCOL = null;
       BDORDEM = null;
       for execute statement wsql into  :BDCODEMP, :BDCODEMPSUC, :BDCHAVE, :BDCODTER, :BDREFFN, :BDTIPOFOL
       do
         suspend;
  end

end^

create or alter procedure SP_CONTABILIZACAO_VERBAS (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXAFILIAIS smallint = 0)
returns (
    BDCODEMP integer,
    BDCODEMPSUC integer,
    BDCHAVE integer,
    BDCODCOL integer,
    BDCODTER integer,
    BDREFFN integer,
    BDTIPOFOL integer,
    BDORDEM integer,
    BDCODVER integer)
as
declare variable WSQL varchar(32700);
declare variable WSQLEMP varchar(25000);
begin
  if (coalesce(premp,  '') <> '') then
     begin
       if (coalesce(prpuxafiliais, 0) = 1) then
          wsqlemp = 'select bdcodemp from TEMPRESAS where ('||premp||') or ('||replace(upper(premp), 'BDCODEMP', 'BDCODMATRIZ')||')';
       else
          wsqlemp = 'select bdcodemp from TEMPRESAS where '||premp;
     end
  else
     wsqlemp = 'select bdcodemp from TEMPRESAS ';

  for execute statement wsqlemp into :BDCODEMP do
    begin
       wsql = 'select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, BDREFFN, 0 BDTIPOFOL, cast(null as integer) BDORDEM, BDCODVER '||
              'from TOL_VRHF_EMP_TVERBA_FN where BDREFFN between '||prrefini||' and '||prreffim||' and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, BDREFTOMADOR, 0 BDTIPOFOL, BDORDEM, BDCODVER '||
              'from TOL_VRHF_EMP_TVERBA_FT where BDREFTOMADOR between '||prrefini||' and '||prreffim||' and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, BDREFFN, 0 BDTIPOFOL, cast(null as integer) BDORDEM, BDCODVER '||
              'from TOL_VRHF_EMP_TVERBA_INT where BDREFFN between '||prrefini||' and '||prreffim||' and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, BDREFTOMADOR, 0 BDTIPOFOL, BDORDEM, BDCODVER '||
              'from TOL_VRHF_EMP_TVERBA_TOMINT where BDREFTOMADOR between '||prrefini||' and '||prreffim||' and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       -- FOLHA COMPLEMENTAR/TOMADOR COMPLEMENTAR/INTERMITENTE COMPLEMENTAR/INTERMITENTE TOMADOR COMPLEMENTAR --
     
       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, SUBSTRING(BDREFFC FROM 1 FOR 6), 1 BDTIPOFOL, cast(null as integer) BDORDEM, BDCODVER '||
              'from TOL_VRHF_EMP_TVERBA_FN_FC where BDREFFC between '||prrefini||'01 and '||prreffim||'31 and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, SUBSTRING(BDREFFC FROM 1 FOR 6), 1 BDTIPOFOL, BDORDEM, BDCODVER '||
              'from TOL_VRHF_EMP_TVERBA_FT_FC where BDREFFC between '||prrefini||'01 and '||prreffim||'31 and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, SUBSTRING(BDREFFC FROM 1 FOR 6), 1 BDTIPOFOL, cast(null as integer) BDORDEM, BDCODVER '||
              'from TOL_VRHF_EMP_TVERBA_FCINT where BDREFFC between '||prrefini||'01 and '||prreffim||'31 and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, SUBSTRING(BDREFFC FROM 1 FOR 6), 1 BDTIPOFOL, BDORDEM, BDCODVER '||
              'from TOL_VRHF_EMP_TVERBA_FT_FC_INT where BDREFFC between '||prrefini||'01 and '||prreffim||'31 and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       -- FÉRIAS --
     
       wsql = wsql||' union all select FE.BDCODEMP, FE.BDCODEMPSUC, FE.BDCHAVE, FE.BDCODCOL, FER.BDREFINIFE, 2 BDTIPOFOL, FER.BDORDEM, FE.BDCODVER '||
              'from TOL_VRHF_EMP_TVERBA_FER FE '||
              'join VRH_EMP_TFERIAS FER on (FER.BDCODEMP = FE.BDCODEMP and FER.BDCODCOL = FE.BDCODCOL and FER.BDINIPERAQUISFE = FE.BDINIPERAQUISFE and FER.BDCODFE = FE.BDCODFE) '||
              'where FER.BDREFPAGFE between '||prrefini||' and '||prreffim||' and FE.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(prcol), 'BDCODCOL', 'FE.BDCODCOL');

       -- ADIANTAMENTO SALARIAL --
     
       wsql = wsql||' union all select AD.BDCODEMP, AD.BDCODEMPSUC, AD.BDCHAVE, AD.BDCODCOL, ADS.BDREFAD, 3 BDTIPOFOL, ADS.BDORDEM, AD.BDCODVER '||
              'from TOL_VRHF_EMP_TVERBA_AD AD '||
              'join VRHF_EMP_TADSAL ADS on (ADS.BDCODEMP = AD.BDCODEMP and ADS.BDCODCOL = AD.BDCODCOL and ADS.BDDATAAD = AD.BDDATAAD) '||
              'where ADS.BDREFAD between '||prrefini||' and '||prreffim||' and AD.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(prcol), 'BDCODCOL', 'AD.BDCODCOL');

       -- ADIANTAMENTO 13º SALÁRIO --
     
       wsql = wsql||' union all select AD13.BDCODEMP, AD13.BDCODEMPSUC, AD13.BDCHAVE, AD13.BDCODCOL, ADS13.BDREFA13, 4 BDTIPOFOL, ADS13.BDORDEM, AD13.BDCODVER '||
              'from TOL_VRHF_EMP_TVERBA_A13 AD13 '||
              'join VRHF_EMP_TA13SAL ADS13 on (ADS13.BDCODEMP = AD13.BDCODEMP and ADS13.BDCODCOL = AD13.BDCODCOL and ADS13.BDREFA13 = AD13.BDREFA13) '||
              'where AD13.BDREFA13 between '||prrefini||' and '||prreffim||' and AD13.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(prcol), 'BDCODCOL', 'AD13.BDCODCOL');

       -- 13º SALÁRIO --
     
       wsql = wsql||' union all select S13.BDCODEMP, S13.BDCODEMPSUC, S13.BDCHAVE, S13.BDCODCOL, SS13.BDREF13, 5 BDTIPOFOL, SS13.BDORDEM, S13.BDCODVER '||
              'from TOL_VRHF_EMP_TVERBA_13 S13 '||
              'join VRHF_EMP_T13SAL SS13 on (SS13.BDCODEMP = S13.BDCODEMP and SS13.BDCODCOL = S13.BDCODCOL and SS13.BDREF13 = S13.BDREF13) '||
              'where S13.BDREF13 between '||prrefini||' and '||prreffim||' and S13.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(prcol), 'BDCODCOL', 'S13.BDCODCOL');

       -- COMPLEMENTO 13º SALÁRIO --
     
       wsql = wsql||' union all select C13.BDCODEMP, C13.BDCODEMPSUC, C13.BDCHAVE, C13.BDCODCOL, CS13.BDREFC13, 6 BDTIPOFOL, CS13.BDORDEM, C13.BDCODVER '||
              'from TOL_VRHF_EMP_TVERBA_C13 C13 '||
              'join VRHF_EMP_TC13SAL CS13 on (CS13.BDCODEMP = C13.BDCODEMP and CS13.BDCODCOL = C13.BDCODCOL and CS13.BDREF13 = C13.BDREF13 and CS13.BDREFC13 = C13.BDREFC13) '||
              'where C13.BDREFC13 between '||prrefini||' and '||prreffim||' and C13.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(prcol), 'BDCODCOL', 'C13.BDCODCOL');

       -- FOLHA AVULSA --
     
       wsql = wsql||' union all select FA.BDCODEMP, FA.BDCODEMPSUC, FA.BDCHAVE, FA.BDCODCOL, FAS.BDREF, 7 BDTIPOFOL, FAS.BDORDEM, FA.BDCODVER '||
              'from TOL_VRHF_EMP_TVERBA_FA FA '||
              'join VRHF_EMP_TFOLHAAVULSA FAS on (FAS.BDCODEMP = FA.BDCODEMP and FAS.BDCODCOL = FA.BDCODCOL and FAS.BDCODTCA = FA.BDCODTCA and FAS.BDDATAFA = FA.BDDATAFA) '||
              'where FAS.BDREF between '||prrefini||' and '||prreffim||' and FA.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(prcol), 'BDCODCOL', 'FA.BDCODCOL');

       BDCODTER = null;
       for execute statement wsql into :BDCODEMP, :BDCODEMPSUC, :BDCHAVE, :BDCODCOL, :BDREFFN, :BDTIPOFOL, :BDORDEM, :BDCODVER
       do
         suspend;
     
     
       -- SERVIÇOS AUTÔNOMOS --
     
       wsql = 'select SER.BDCODEMP, SER.BDCODEMPSUC, SER.BDCHAVE, SER.BDCODTER, SERV.BDREFINSSSERV, 8 BDTIPOFOL, SER.BDCODVER '||
              'from TOL_VRHF_EMP_TVERBA_AUT SER '||
              'join VRHF_BASE_CALC_TERC SERV on (SERV.BDCODEMP = SER.BDCODEMPSUC and SERV.BDCODTER = SER.BDCODTER and SERV.BDCODSERV = SER.BDCODSERV) '||
              'join VRH_BASE_TSERVTERC S on (S.BDCODEMP = SER.BDCODEMP and S.BDCODTER = SER.BDCODTER) '||
              'where SERV.BDREFINSSSERV between '||prrefini||' and '||prreffim||' and SER.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(premp, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(premp), 'BDCODEMP', 'SER.BDCODEMP');
     
     
       BDCODCOL = null;
       BDORDEM = null;
       for execute statement wsql into  :BDCODEMP, :BDCODEMPSUC, :BDCHAVE, :BDCODTER, :BDREFFN, :BDTIPOFOL, :BDCODVER
       do
         suspend;
  end

end^

create or alter procedure SP_CONTABILIZACAO_FGTS (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXAFILIAIS smallint = 0)
returns (
    BDCODEMP integer,
    BDCODEMPSUC integer,
    BDCHAVE integer,
    BDCODCOL integer,
    BDCODTER integer,
    BDREFFN integer,
    BDTIPOFOL integer,
    BDORDEM integer)
as
declare variable WSQL varchar(32700);
declare variable WSQLEMP varchar(25000);
begin
  if (coalesce(premp,  '') <> '') then
     begin
       if (coalesce(prpuxafiliais, 0) = 1) then
          wsqlemp = 'select bdcodemp from TEMPRESAS where ('||premp||') or ('||replace(upper(premp), 'BDCODEMP', 'BDCODMATRIZ')||')';
       else
          wsqlemp = 'select bdcodemp from TEMPRESAS where '||premp;
     end
  else
     wsqlemp = 'select bdcodemp from TEMPRESAS ';

  for execute statement wsqlemp into :BDCODEMP do
    begin
       wsql = 'select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, BDREFFN, 0 BDTIPOFOL, cast(null as integer) BDORDEM '||
              'from TOL_VRHF_EMP_TFGTS_FN where BDREFFN between '||prrefini||' and '||prreffim||' and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, BDREFTOMADOR, 0 BDTIPOFOL, BDORDEM '||
              'from TOL_VRHF_EMP_TFGTS_FT where BDREFTOMADOR between '||prrefini||' and '||prreffim||' and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, BDREFFN, 0 BDTIPOFOL, cast(null as integer) BDORDEM '||
              'from TOL_VRHF_EMP_TFGTS_INT where BDREFFN between '||prrefini||' and '||prreffim||' and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, BDREFTOMADOR, 0 BDTIPOFOL, BDORDEM '||
              'from TOL_VRHF_EMP_TFGTS_TOMINT where BDREFTOMADOR between '||prrefini||' and '||prreffim||' and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       -- FOLHA COMPLEMENTAR/TOMADOR COMPLEMENTAR/INTERMITENTE COMPLEMENTAR/INTERMITENTE TOMADOR COMPLEMENTAR --
     
       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, SUBSTRING(BDREFFC FROM 1 FOR 6), 1 BDTIPOFOL, cast(null as integer) BDORDEM '||
              'from TOL_VRHF_EMP_TFGTS_FC where BDREFFC between '||prrefini||'01 and '||prreffim||'31 and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, SUBSTRING(BDREFFC FROM 1 FOR 6), 1 BDTIPOFOL, BDORDEM '||
              'from TOL_VRHF_EMP_TFGTS_FT_FC where BDREFFC between '||prrefini||'01 and '||prreffim||'31 and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, SUBSTRING(BDREFFC FROM 1 FOR 6), 1 BDTIPOFOL, cast(null as integer) BDORDEM '||
              'from TOL_VRHF_EMP_TFGTS_FC_INT where BDREFFC between '||prrefini||'01 and '||prreffim||'31 and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, SUBSTRING(BDREFFC FROM 1 FOR 6), 1 BDTIPOFOL, BDORDEM '||
              'from TOL_VRHF_EMP_TFGTS_FT_FC_INT where BDREFFC between '||prrefini||'01 and '||prreffim||'31 and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       -- ADIANTAMENTO 13º SALÁRIO --
     
       wsql = wsql||' union all select AD13.BDCODEMP, AD13.BDCODEMPSUC, AD13.BDCHAVE, AD13.BDCODCOL, ADS13.BDREFA13, 4 BDTIPOFOL, ADS13.BDORDEM '||
              'from TOL_VRHF_EMP_TFGTS_A13 AD13 '||
              'join VRHF_EMP_TA13SAL ADS13 on (ADS13.BDCODEMP = AD13.BDCODEMP and ADS13.BDCODCOL = AD13.BDCODCOL and ADS13.BDREFA13 = AD13.BDREFA13) '||
              'where AD13.BDREFA13 between '||prrefini||' and '||prreffim||' and AD13.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(prcol), 'BDCODCOL', 'AD13.BDCODCOL');

       -- 13º SALÁRIO --
     
       wsql = wsql||' union all select S13.BDCODEMP, S13.BDCODEMPSUC, S13.BDCHAVE, S13.BDCODCOL, SS13.BDREF13, 5 BDTIPOFOL, SS13.BDORDEM '||
              'from TOL_VRHF_EMP_TFGTS_13 S13 '||
              'join VRHF_EMP_T13SAL SS13 on (SS13.BDCODEMP = S13.BDCODEMP and SS13.BDCODCOL = S13.BDCODCOL and SS13.BDREF13 = S13.BDREF13) '||
              'where S13.BDREF13 between '||prrefini||' and '||prreffim||' and S13.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(prcol), 'BDCODCOL', 'S13.BDCODCOL');

       -- COMPLEMENTO 13º SALÁRIO --
     
       wsql = wsql||' union all select C13.BDCODEMP, C13.BDCODEMPSUC, C13.BDCHAVE, C13.BDCODCOL, CS13.BDREFC13, 6 BDTIPOFOL, CS13.BDORDEM '||
              'from TOL_VRHF_EMP_TFGTS_C13 C13 '||
              'join VRHF_EMP_TC13SAL CS13 on (CS13.BDCODEMP = C13.BDCODEMP and CS13.BDCODCOL = C13.BDCODCOL and CS13.BDREF13 = C13.BDREF13 and CS13.BDREFC13 = C13.BDREFC13) '||
              'where C13.BDREFC13 between '||prrefini||' and '||prreffim||' and C13.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(prcol), 'BDCODCOL', 'C13.BDCODCOL');

       -- FOLHA AVULSA --
     
       wsql = wsql||' union all select FA.BDCODEMP, FA.BDCODEMPSUC, FA.BDCHAVE, FA.BDCODCOL, FAS.BDREF, 7 BDTIPOFOL, FAS.BDORDEM '||
              'from TOL_VRHF_EMP_TFGTS_FA FA '||
              'join VRHF_EMP_TFOLHAAVULSA FAS on (FAS.BDCODEMP = FA.BDCODEMP and FAS.BDCODCOL = FA.BDCODCOL and FAS.BDCODTCA = FA.BDCODTCA and FAS.BDDATAFA = FA.BDDATAFA) '||
              'where FAS.BDREF between '||prrefini||' and '||prreffim||' and FA.BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||REPLACE(UPPER(prcol), 'BDCODCOL', 'FA.BDCODCOL');

       BDCODTER = null;
       for execute statement wsql into :BDCODEMP, :BDCODEMPSUC, :BDCHAVE, :BDCODCOL, :BDREFFN, :BDTIPOFOL, :BDORDEM
       do
         suspend;
  end
end^

create or alter procedure SP_CONTABILIZACAO_PROVISOES (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXAFILIAIS smallint = 0)
returns (
    BDCODEMP integer,
    BDCODEMPSUC integer,
    BDCHAVE integer,
    BDCODCOL integer,
    BDCODTER integer,
    BDREFFN integer,
    BDTIPOFOL integer,
    BDORDEM integer)
as
declare variable WSQL varchar(32700);
declare variable WSQLEMP varchar(25000);
begin
  if (coalesce(premp,  '') <> '') then
     begin
       if (coalesce(prpuxafiliais, 0) = 1) then
          wsqlemp = 'select bdcodemp from TEMPRESAS where ('||premp||') or ('||replace(upper(premp), 'BDCODEMP', 'BDCODMATRIZ')||')';
       else
          wsqlemp = 'select bdcodemp from TEMPRESAS where '||premp;
     end
  else
     wsqlemp = 'select bdcodemp from TEMPRESAS ';

  for execute statement wsqlemp into :BDCODEMP do
    begin
       wsql = 'select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, BDREFP13, 20 BDTIPOFOL, BDORDEM '||
              'from TOL_VRHF_EMP_TPROV13_DET where BDREFP13 between '||prrefini||' and '||prreffim||' and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       wsql = wsql||' union all select BDCODEMP, BDCODEMPSUC, BDCHAVE, BDCODCOL, BDREFPFER, 21 BDTIPOFOL, BDORDEM '||
              'from TOL_VRHF_EMP_TPROVFER_DET where BDREFPFER between '||prrefini||' and '||prreffim||' and BDCODEMP = '||BDCODEMP;
     
       if (coalesce(prcol, '') <> '') then
          wsql = wsql||' and '||prcol;

       BDCODTER = null;
       for execute statement wsql into :BDCODEMP, :BDCODEMPSUC, :BDCHAVE, :BDCODCOL, :BDREFFN, :BDTIPOFOL, :BDORDEM
       do
         suspend;
  end
end^

create or alter procedure SP_TEMCPFCADASTRADO (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRCPF varchar(14))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDTPCOL varchar(20),
    BDNOMEMP DM_BDNOMEMP)
as
declare variable WSITEMP DM_BOOLEAN;
declare variable WCAT integer;
begin
  for select COL.BDCODEMP, COL.BDCODCOL, COL.BDDTPCOL
      from VRH_EMP_TCOLCON COL
      left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL)
      where COL.BDCPFCOL = :prcpf and
      (((COL.BDCODEMP <> :premp) and
       (COL.BDCODCOL <> :prcol)) or ((COL.BDCODEMP = :prcol) and
       (COL.BDCODCOL <> :prcol)) or ((COL.BDCODEMP <> :premp) and
       (COL.BDCODCOL = :prcol))) and
       ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO < COL.BDDATAADMCOL))
  into :BDCODEMP, :BDCODCOL, :BDDTPCOL
  do
    begin
      wsitemp = 'FALSE';
      select first 1 BDSITEMP, BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :prref order by BDREFEMP desc into :wsitemp, :BDNOMEMP;
    
      if (upper(wsitemp) <> 'TRUE') then
         begin
           wcat = null;
           select first 1 BDCATEGORIAESOCIAL from VRHF_EMP_TCOLCON_FGTSGPS where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prref order by BDREFCOL DESC into :wcat;
           wcat = coalesce(wcat, 0);

           if (wcat <> 111) then
              suspend;
         end
    end

  for select BDCODTER, 'Autônomo'
      from TTERCEIRO
      where BDCGCTER = :prcpf
  into :BDCODCOL, :BDDTPCOL
  do
    begin
      BDCODEMP = null;
      BDNOMEMP = null;
      suspend;
    end
end^

CREATE OR ALTER TRIGGER VRH_EMP_TFERIAS_BIU0 FOR VRH_EMP_TFERIAS
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  if ((new.BDSALDOFIMFE > 0) AND ((new.BDSALDOFIMFE = new.BDSALDOINIFE) AND (new.BDQTDGOZOFE > 0))) then
     new.BDSALDOFIMFE = (new.BDSALDOINIFE - (new.BDQTDGOZOFE + new.BDQTDABONOFE));

  if (new.bdistransferencia is null) then
     new.bdistransferencia = False;
end
^

CREATE OR ALTER trigger vrh_esocial_tarquivo_xml_biu0 for vrh_esocial_tarquivo_xml
active before insert or update position 0
AS
begin
  new.BDXML = zipblob(new.BDXML);
  new.BDGUIADCTFWEB = zipblob(new.BDGUIADCTFWEB);
end^

CREATE OR ALTER TRIGGER VEF_BASE_TLOGJSONIMENDES_BI0 FOR VEF_BASE_TLOGJSONIMENDES
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  /* TRIGGER TEXT */
  NEW.BDLOGENVIO = ZIPBLOB(NEW.BDLOGENVIO);
  NEW.BDLOGRETORNO = ZIPBLOB(NEW.BDLOGRETORNO);
END
^

CREATE OR ALTER TRIGGER VEF_BASE_TLOGERROIMENDES_BI0 FOR VEF_BASE_TLOGERROIMENDES
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  /* TRIGGER TEXT */
  NEW.BDLOG = ZIPBLOB(NEW.BDLOG);
  NEW.BDLOGENVIO = ZIPBLOB(NEW.BDLOGENVIO);  
END^

CREATE OR ALTER trigger vrh_esocial_tlote_arquivos_biu0 for vrh_esocial_tlote_arquivos
active before insert or update position 0
AS
begin
  new.BDXML = zipblob(new.BDXML);
end^

CREATE OR ALTER procedure SP_SELECT_POSTERIORES_AUDITOR (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODSINTRAB integer,
    BDINIHORANOTST time,
    BDFIMHORANOTST time,
    BDDATBASEST integer,
    BDDATACOL date)
as
declare variable WINIHORANOT time;
declare variable WINIHORANOT_ANT time;
declare variable WFIMHORANOT time;
declare variable WFIMHORANOT_ANT time;
declare variable WDATBASE integer;
declare variable WDATBASE_ANT integer;
declare variable WSQL varchar(30000);
declare variable WINICIOU boolean = false;
declare variable WCODSIND integer;
declare variable WCODSIND_ANT integer;
BEGIN
  wsql = 'select V.BDCODEMP, V.BDCODCOL, V.BDCODSINTRAB, STR.BDINIHORANOTST, STR.BDFIMHORANOTST, STR.BDDATBASEST, ';
  wsql = wsql||'cast((right(STR.BDREFST, 2) || ''-01-'' || left(STR.BDREFST, 4)) as date) BDDATACOL ';
  wsql = wsql||'from VRH_BASE_TSINDTREF STR ';
  wsql = wsql||'join VRH_EMP_TCOL_VINC V on V.BDCODSINTRAB = STR.BDCODSINTRAB ';
  wsql = wsql||'join VRH_EMP_TCOLCON COL on COL.BDCODEMP = V.BDCODEMP and COL.BDCODCOL = V.BDCODCOL ';
  wsql = wsql||'where V.BDCODEMP = '||prcodemp||' and COL.BDCODCOL = '||prcodcol||' and ';
  wsql = wsql||'STR.BDREFST > 0 and V.BDREFCOL >= '||prref;
  wsql = wsql||' order by BDDATACOL';
  FOR EXECUTE STATEMENT wsql INTO
    :bdcodemp, :bdcodcol, :bdcodsintrab, :bdinihoranotst, :bdfimhoranotst, :bddatbasest, :bddatacol DO
  BEGIN
    if (not winiciou) then
      begin
        wdatbase    = :bddatbasest;
        winihoranot = :bdinihoranotst;
        wfimhoranot = :bdfimhoranotst;
        wcodsind    = :bdcodsintrab;
        wdatbase_ant    = 0;
        wcodsind_ant    = 0;
        winihoranot_ant = winihoranot - 1;
        wfimhoranot_ant = wfimhoranot - 1;
        winiciou = true;
      end
    if ((winihoranot <> winihoranot_ant) or (wfimhoranot <> wfimhoranot_ant)
           or (wdatbase <> wdatbase_ant) or (wcodsind <> wcodsind_ant) ) then
      begin
        SUSPEND;
        wdatbase_ant    = wdatbase;
        wcodsind_ant    = wcodsind;
        winihoranot_ant = winihoranot;
        wfimhoranot_ant = wfimhoranot;
      end

  END
END^

/* Restore proc. body: SP_VRH_RELATORIOPLANOSAUDE_NOVO */
create or alter procedure SP_VRH_RELATORIOPLANOSAUDE_NOVO (
    PREMP varchar(15000),
    PRCOL varchar(30000),
    PRCOMPETENCIA integer,
    PRCODTIPOCONV varchar(15000),
    PRSITUACAO integer,
    PRORDERBY varchar(30))
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDNOMEMP varchar(100),
    BDCODCOL integer,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDCODDPN integer,
    BDNOMDEP varchar(70),
    BDPARENTESCO varchar(500),
    BDDATANASC date,
    BDCPF varchar(14),
    BDDATAADMCOL varchar(10),
    BDDESCTFUC varchar(40),
    BDREFINI integer,
    BDREFFIM integer,
    BDCOPARTICIPACAO numeric(18,6),
    BDMENSALIDADE numeric(18,6),
    BDIDADE integer,
    BDVALORFAIXA numeric(18,6),
    BDREF integer,
    BDCODOPERADORA integer,
    BDOPERADORA varchar(200),
    BDCODCONVENIO integer,
    BDCONVENIO varchar(80),
    BDCODPLAN integer,
    BDPLANO varchar(200),
    BDCODTIPOCONV integer,
    BDTIPOCONVENIO varchar(200),
    BDCNPJ varchar(18),
    BDREGISTROANS integer)
as
declare variable WUMAEMP integer;
declare variable WSQL varchar(30000);
declare variable WDIA varchar(10);
declare variable WMES varchar(10);
declare variable WANO varchar(10);
declare variable WPRIDIA varchar(10);
declare variable WULTDIA varchar(10);
declare variable WPRCOL varchar(30000);
declare variable WPREMP varchar(30000);
declare variable WCOLANT integer;
declare variable WCODDPN integer;
declare variable WNOMDEP varchar(70);
declare variable WPARENTESCO varchar(500);
declare variable WCPF varchar(14);
declare variable WREF integer;
declare variable WCONVANT integer;
BEGIN

  wMES = SUBSTRING(CAST(:prCOMPETENCIA AS VARCHAR(6)) FROM 5 FOR 2) ;
  wANO = CAST(SUBSTRING(CAST(:prCOMPETENCIA AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  SELECT ULTDIA FROM ultimo_DIA_MES(:wMES, :wANO) INTO :wDIA;
  wPRIDIA = wMES||'/'||'01'||'/'||wANO;
  wULTDIA = wMES||'/'||wDIA||'/'||wANO;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:prCOMPETENCIA,wPRIDIA,wULTDIA);

  wUMAEMP = 0; --(0)-False, (1)-True

  WCOLANT = 0;
  wconvant = 0;

  if (prCOL is not null and prCOL <> '') then
    wPRCOL = replace(upper(prCOL),'COL.BDCODCOL','BDCODCOL');
  else
    wPRCOL = 'null';

  if (prEMP is not null and prEMP <> '') then
    begin
      wPREMP = replace(upper(prEMP),'COL.BDCODEMP','BDCODEMP');
      if (character_length(wPREMP) < 20) then -- se o tamanho da string for menor que 20, o filtro é só de uma empresa(usado nos "SP_SOMENTE_ATIVOS").
        wUMAEMP = 1;
    end
  else
    wPREMP = 'null';


--         wSQL = 'select COL.BDCODEMP, COL.BDCODEMP BDCODMATRIZ, EMP.BDNOMEMP, COL.BDCODCOL, BDNOMCOLUPPER, COL.BDCODDPN, ';
--  wSQL = wSQL|| 'case COL.BDCODDPN when 0 then null else BDNOMDEP end as BDNOMDEP, ';
--  wSQL = wSQL|| 'COL.BDPARENTESCO, BDDATANASC, BDCPF, BDDATAADMCOL, TFUC.BDDESCTFUC, COL.BDREFINI, ';
--  wSQL = wSQL|| 'coalesce(COL.BDREFFIM, 0) BDREFFIM, OPSAU.BDCODCONVENIO BDCODOPERADORA, OPSAU.BDDESCRICAO BDOPERADORA, ';
--  wSQL = wSQL|| 'SAUDE.BDCODCONVENIO, SAUDE.BDRAZAOSOCIAL BDCCONVENIO, PLA.BDCODPLACONVSAU BDCODPLAN, PLA.BDDESCRICAO BDPLANO, ';
--  wSQL = wSQL|| 'TCONV.BDCODTIPOCONV, TCONV.BDDESCTIPOCONV BDTIPOCONVENIO, SAUDE.BDCNPJ, SAUDE.BDREGISTROANS ';


  /*{167460 Nathan de Faria - 03/10/2022}*/
  wSQL = 'SELECT COL.BDCODEMP, COL.BDCODEMP BDCODMATRIZ, COL.BDCODCOL, EMP.BDNOMEMP, COL.BDNOMCOLUPPER, COL.BDCODDPN, ';
  wSQL = wSQL|| 'case COL.BDCODDPN when 0 then null else BDNOMDEP end as BDNOMDEP, ';
  wSQL = wSQL|| 'COL.BDPARENTESCO, COL.BDDATANASC, COL.BDCPF, COL.BDDATAADMCOL, TFUC.BDDESCTFUC, ';
  wSQL = wSQL|| 'PLA.BDCODPLACONVSAU BDCODPLAN, PLA.BDDESCRICAO BDPLANO, TCONV.BDCODTIPOCONV, TCONV.BDDESCTIPOCONV BDTIPOCONVENIO, ';
  wSQL = wSQL|| 'OPSAU.BDCODCONVENIO, OPSAU.BDDESCRICAO BDCONVENIO, COL.BDCODOPERADORA, SAUDE.BDRAZAOSOCIAL BDOPERADORA, SAUDE.BDCNPJ, SAUDE.BDREGISTROANS, COL.BDREFINI, coalesce(COL.BDREFFIM, 0) BDREFFIM ';


  wSQL = wSQL|| 'from (select COL.BDCODEMP, COL.BDCODCOL, 0 BDCODDPN, COLCAD.BDNOMCOL BDNOMDEP, COLCAD.BDNOMCOLUPPER, ';
  wSQL = wSQL||              'COLCON.BDDATANASCCOL BDDATANASC, COLCON.BDCPFCOL BDCPF, COLCON.BDDATAADMCOL BDDATAADMCOL, ';
  wSQL = wSQL||              'CONVCOL.BDCODPLACONVSAU, CONVCOL.BDCODCONVENIO, CONVCOL.BDCODOPERADORA, CONVCOL.BDREFINI, CONVCOL.BDREFFIM, ';
  wSQL = wSQL||              'cast(null as varchar(100)) BDPARENTESCO ';

  wSQL = wSQL|| 'from VRH_EMP_TCOLCON COL ';
  wSQL = wSQL|| 'join VW_VRH_EMP_TCOLCON_CAD COLCAD on  (COLCAD.BDCODEMP = COL.BDCODEMP and  COLCAD.BDCODCOL = COL.BDCODCOL) ';
  wSQL = wSQL|| 'join VRH_EMP_TCOLCON        COLCON on  (COLCON.BDCODEMP = COL.BDCODEMP and  COLCON.BDCODCOL = COL.BDCODCOL) ';
  wSQL = wSQL|| 'join VRH_EMP_VINC_COL_CONV CONVCOL on (CONVCOL.BDCODEMP = COL.BDCODEMP and CONVCOL.BDCODCOL = COL.BDCODCOL) ';

  if (prSITUACAO = 1) then -- (0)Todos, (1)Somente ativos, (2)Somente demitidos
    begin                  -- se for apenas uma empresa nas duas situações, executa o somente ativos com todos os paramêtros, senão sem o paramêtro CODEMP
      if (wUMAEMP = 1) then
        wSQL = wSQL|| 'join SP_SOMENTE_ATIVOS('''||wPRIDIA||''', '''||wULTDIA||''', '||substring(prEMP from 16)||') SMA on (SMA.BDCODEMP = COL.BDCODEMP and SMA.BDCODCOL = COL.BDCODCOL) ';
      else
        wSQL = wSQL|| 'join SP_SOMENTE_ATIVOS('''||wPRIDIA||''', '''||wULTDIA||''') SMA on (SMA.BDCODEMP = COL.BDCODEMP and SMA.BDCODCOL = COL.BDCODCOL) ';
    end
  if (prSITUACAO = 2) then
    begin
      if (wUMAEMP = 1) then
        wSQL = wSQL|| 'join SP_SOMENTE_DEMITIDOS('''||wULTDIA||''', '||substring(prEMP from 16)||') SMD on (SMD.BDCODEMP = COL.BDCODEMP and SMD.BDCODCOL = COL.BDCODCOL) ';
      else
        wSQL = wSQL|| 'join SP_SOMENTE_DEMITIDOS('''||wULTDIA||''') SMD on (SMD.BDCODEMP = COL.BDCODEMP and SMD.BDCODCOL = COL.BDCODCOL) ';
    end

--  wSQL = wSQL|| 'where ((CONVCOL.BDREFINI <= '||prCOMPETENCIA||') and ';
--  wSQL = wSQL||'((CONVCOL.BDREFFIM >= '||prCOMPETENCIA||') or ';
--  wSQL = wSQL||        '(coalesce(CONVCOL.BDREFFIM, 0) = 0))) ';

  /*{167460 Nathan de Faria - 03/10/2022}*/
  wSQL = wSQL|| 'where ';
  wSQL = wSQL|| '((coalesce(CONVCOL.BDREFFIM, 0) = 0) or (coalesce(CONVCOL.BDREFFIM, 0)>='||prCOMPETENCIA||'))';

  IF (prEMP IS NOT NULL AND prEMP <> '') THEN
    BEGIN
      wSQL = wSQL||' and '||prEMP;

      IF (prCOL IS NOT NULL AND prCOL <> '') THEN
        wSQL = wSQL||' and '||prCOL;
    END

  wSQL = wSQL|| 'union all ';
  wSQL = wSQL|| 'select COL.BDCODEMP, COL.BDCODCOL, COL.BDCODDPN, COL.BDNOMEDPN BDNOMDEP, COLCAD.BDNOMCOLUPPER BDNOMCOLUPPER, ';
  wSQL = wSQL||        'COL.BDDATANASCDPN BDDATANASC, COL.BDCPFDPN BDCPF, cast(null as varchar(10)) BDDATAADMCOL, ';
  wSQL = wSQL||        'CONVDEP.BDCODPLACONVSAU, CONVDEP.BDCODCONVENIO, CONVDEP.BDCODOPERADORA, CONVDEP.BDREFINI, CONVDEP.BDREFFIM, ';
  wSQL = wSQL||        'GRAUPARENTE.BDDESCTIPODEP ';

  wSQL = wSQL|| 'from VW_VRH_EMP_TDEP_REF COL ';
  wSQL = wSQL|| 'join VW_VRH_EMP_TCOLCON_CAD COLCAD on  (COLCAD.BDCODEMP = COL.BDCODEMP and  COLCAD.BDCODCOL = COL.BDCODCOL) ';
  wSQL = wSQL|| 'join VRH_EMP_VINC_DEP_CONV CONVDEP on (CONVDEP.BDCODEMP = COL.BDCODEMP and CONVDEP.BDCODCOL = COL.BDCODCOL and CONVDEP.BDCODDPN = COL.BDCODDPN) ';

  if (prSITUACAO = 1) then -- (0)Todos, (1)Somente ativos, (2)Somente demitidos
    begin                  -- se for apenas uma empresa nas duas situações, executa o somente ativos com todos os paramêtros, senão sem o paramêtro CODEMP
      if (wUMAEMP = 1) then
        wSQL = wSQL|| 'join SP_SOMENTE_ATIVOS('''||wPRIDIA||''', '''||wULTDIA||''', '||substring(prEMP from 16)||') SMA on (SMA.BDCODEMP = COL.BDCODEMP and SMA.BDCODCOL = COL.BDCODCOL) ';
      else
        wSQL = wSQL|| 'join SP_SOMENTE_ATIVOS('''||wPRIDIA||''', '''||wULTDIA||''') SMA on (SMA.BDCODEMP = COL.BDCODEMP and SMA.BDCODCOL = COL.BDCODCOL) ';
    end
  if (prSITUACAO = 2) then
    begin
      if (wUMAEMP = 1) then
        wSQL = wSQL|| 'join SP_SOMENTE_DEMITIDOS('''||wULTDIA||''', '||substring(prEMP from 16)||') SMD on (SMD.BDCODEMP = COL.BDCODEMP and SMD.BDCODCOL = COL.BDCODCOL) ';
      else
        wSQL = wSQL|| 'join SP_SOMENTE_DEMITIDOS('''||wULTDIA||''') SMD on (SMD.BDCODEMP = COL.BDCODEMP and SMD.BDCODCOL = COL.BDCODCOL) ';
    end

  wSQL = wSQL|| 'left outer join VRH_TTIPO_DEP_ESOCIAL GRAUPARENTE on (GRAUPARENTE.BDCODTIPODEP = COL.BDPARENESCODPN) ';


--  wSQL = wSQL|| 'where ((CONVDEP.BDREFINI <= '||prCOMPETENCIA||') and ';
--  wSQL = wSQL||       '((CONVDEP.BDREFFIM >= '||prCOMPETENCIA||') or ';
--  wSQL = wSQL||        '(coalesce(CONVDEP.BDREFFIM, 0) = 0))) ';

  /*{167460 Nathan de Faria - 03/10/2022}*/
  wSQL = wSQL|| 'where ';
  wSQL = wSQL|| '((coalesce(CONVDEP.BDREFFIM, 0) = 0) or (coalesce(CONVDEP.BDREFFIM, 0)>='||prCOMPETENCIA||'))';

  IF (prEMP IS NOT NULL AND prEMP <> '') THEN
    BEGIN
      wSQL = wSQL||' and '||prEMP;

      IF (prCOL IS NOT NULL AND prCOL <> '') THEN
        wSQL = wSQL||' and '||prCOL;
    END

  wSQL = wSQL|| ')COL ';

  wSQL = wSQL|| 'join VW_EMPRESAS_REF_ATUAL     EMP on (  EMP.BDCODEMP        =   COL.BDCODEMP) ';

  wSQL = wSQL|| 'join VRHF_BASE_TEMPVINC EMPVINC ON  (EMPVINC.BDCODEMP = EMP.BDCODEMP and EMPVINC.BDREFEMP = EMP.BDEMPREF ) ';

  wSQL = wSQL|| 'join VRH_BASE_CONVENIO_OPERADORAS OPSAU on (OPSAU.BDCODCONVENIO   = COL.BDCODCONVENIO ';
  wSQL = wSQL||                                         'and OPSAU.BDCODOPERADORA  = COL.BDCODOPERADORA ';
  wSQL = wSQL||                                         'and OPSAU.BDCODPLACONVSAU = COL.BDCODPLACONVSAU) ';

  wSQL = wSQL|| 'join VRH_BASE_TCONVSAUDE SAUDE     on (SAUDE.BDCODCONVENIO   = OPSAU.BDCODOPERADORA) ';
  wSQL = wSQL|| 'join VRH_BASE_TPLANO_CONVSAUDE PLA on (  PLA.BDCODPLACONVSAU = OPSAU.BDCODPLACONVSAU) ';
  wSQL = wSQL|| '                                   and ( PLA.BDCODPLACONVSAU =  EMPVINC.BDCODPLACONVSAU  ) ';
  wSQL = wSQL|| 'join VRHM_BASE_TTIPOCONVENIO TCONV on (TCONV.BDCODTIPOCONV   = OPSAU.BDCODTIPOCONV) ';

  wSQL = wSQL|| 'join(select DIA.BDCODEMP, DIA.BDCODCOL, max(DIA.BDDATACOL) BDDATACOL ';
  wSQL = wSQL||      'from VRH_EMP_TCOLCON_DIA DIA ';

  IF (prEMP IS NOT NULL AND prEMP <> '') THEN
    BEGIN
      wSQL = wSQL||'where '||replace(prEMP,'COL.','DIA.');

      IF (prCOL IS NOT NULL AND prCOL <> '') THEN
        wSQL = wSQL||' and '||replace(prCOL,'COL.','DIA.');
    END
  wSQL = wSQL|| 'group by DIA.BDCODEMP, DIA.BDCODCOL) DIA_X on (DIA_X.BDCODEMP = COL.BDCODEMP and DIA_X.BDCODCOL = COL.BDCODCOL) ';

  wSQL = wSQL|| 'join VRH_EMP_TCOLCON_DIA  DIA on (DIA.BDCODEMP  =   COL.BDCODEMP ';
  wSQL = wSQL||                               'and DIA.BDCODCOL  =   COL.BDCODCOL ';
  wSQL = wSQL||                               'and DIA.BDDATACOL = DIA_X.BDDATACOL) ';

  wSQL = wSQL|| 'join VRH_EMP_TCOL_VINCDIA FUC on (FUC.BDCODEMP  =   COL.BDCODEMP ';
  wSQL = wSQL||                               'and FUC.BDCODCOL  =   COL.BDCODCOL ';
  wSQL = wSQL||                               'and FUC.BDDATACOL = DIA_X.BDDATACOL) ';

  wSQL = wSQL|| 'join VRH_FUNCOES_TFUC   TFUC on (TFUC.BDCODPLAFUC = FUC.BDCODPLAFUC ';
  wSQL = wSQL||                              'and TFUC.BDCODTFUC   = FUC.BDCODTFUC) ';

  IF (prCODTIPOCONV IS NOT NULL AND prCODTIPOCONV <> '') THEN
    wSQL = wSQL||'where '||prCODTIPOCONV;

  if (prORDERBY = 'codigo') then
    wSQL = wSQL|| 'order by BDCODEMP, BDCODMATRIZ, BDCODOPERADORA, BDCODCONVENIO, BDCODPLAN, BDCODCOL, BDCODDPN';
  if (prORDERBY = 'alfabetica') then
    wSQL = wSQL|| 'order by BDCODEMP, BDCODMATRIZ, BDCODOPERADORA, BDCODCONVENIO, BDCODPLAN, BDNOMCOLUPPER, BDCODDPN ';


--  FOR EXECUTE STATEMENT wSQL INTO
--    :BDCODEMP, :BDCODMATRIZ, :BDNOMEMP, :BDCODCOL, :BDNOMCOLUPPER, :BDCODDPN, :BDNOMDEP, :BDPARENTESCO, :BDDATANASC, :BDCPF, :BDDATAADMCOL, :BDDESCTFUC,
--    :BDREFINI, :BDREFFIM, :BDCODOPERADORA, :BDOPERADORA, :BDCODCONVENIO, :BDCONVENIO, :BDCODPLAN, :BDPLANO, :BDCODTIPOCONV, :BDTIPOCONVENIO, :BDCNPJ, :BDREGISTROANS DO

  /*{167460 Nathan de Faria - 03/10/2022}*/
  FOR EXECUTE STATEMENT wSQL INTO
    :BDCODEMP, :BDCODMATRIZ, :BDCODCOL, :BDNOMEMP, :BDNOMCOLUPPER, :BDCODDPN, :BDNOMDEP, :BDPARENTESCO, :BDDATANASC, :BDCPF, :BDDATAADMCOL, :BDDESCTFUC, :BDCODPLAN, :BDPLANO,
    :BDCODTIPOCONV, :BDTIPOCONVENIO, :BDCODCONVENIO, :BDCONVENIO, :BDCODOPERADORA, :BDOPERADORA, :BDCNPJ, :BDREGISTROANS, :BDREFINI, :BDREFFIM DO
  BEGIN
    if( ((WCOLANT <> BDCODCOL) and (BDCODDPN <> 0)) or ((WCOLANT = BDCODCOL) and (WCONVANT <> BDCODCONVENIO) and (BDCODDPN <> 0)) ) then
       begin
         WCODDPN = BDCODDPN;
         WNOMDEP = BDNOMDEP;
         WPARENTESCO = BDPARENTESCO;
         WCPF = BDCPF;
         WREF = BDREFINI;

         BDCODDPN = null;
         BDNOMDEP = null;
         BDPARENTESCO = null;
         select C.BDCPFCOL from VRH_EMP_TCOLCON_DOC C where C.BDCODEMP = :BDCODEMP and C.BDCODCOL = :BDCODCOL into :BDCPF;
         BDREFINI = null;
         BDIDADE = 0;
         BDCOPARTICIPACAO = 0;
         BDMENSALIDADE    = 0;
         BDVALORFAIXA = 0;

         suspend;

         BDCODDPN = WCODDPN;
         BDNOMDEP = WNOMDEP;
         BDPARENTESCO = WPARENTESCO;
         BDCPF = WCPF;
         BDREFINI = WREF;
       end


    :BDIDADE = 0;
    if (:BDCODDPN = 0) then
      select BDIDADE from SP_VRH_EMP_IDADE_COL('BDCODEMP = '||:BDCODEMP, 'BDCODCOL = '||:BDCODCOL, :prCOMPETENCIA, 1) into :BDIDADE;
    else
      select BDIDADE from SP_VRH_EMP_IDADE_COL_DEP('BDCODEMP = '||:BDCODEMP, 'BDCODCOL = '||:BDCODCOL, 'BDCODDPN = '||:BDCODDPN, :prCOMPETENCIA, 1) into :BDIDADE;

    :BDVALORFAIXA = 0;
    select first 1 Z.BDVALOR from VW_VRHM_FAIXA_CONV_OP_SAU_ATU Z
    where Z.BDCODPLACONVSAU = :BDCODPLAN and
     z.BDCODOPERADORA =  :BDCODOPERADORA  and
     z.BDCODCONVENIO = :BDCODCONVENIO and
     Z.BDREF <= :prCOMPETENCIA and
     z.BDIDADE <= :BDIDADE order by Z.BDIDADE desc into :BDVALORFAIXA;

    :BDCOPARTICIPACAO = 0;
    :BDMENSALIDADE    = 0;

    if (:BDCODDPN = 0) then
      select BDREF, coalesce(BDVALORCOPARFUN,0), coalesce(BDVALORMENSALIDADE,0) from SP_VRHM_EMP_COL_COP_OP_SAU(:BDCODEMP, :BDCODCOL, :prCOMPETENCIA, :BDCODPLAN, :BDCODOPERADORA, :BDCODCONVENIO) into :BDREF, :BDCOPARTICIPACAO, :BDMENSALIDADE;
    else
      select BDREF, coalesce(BDVALORCOPARDEP,0), coalesce(BDVALORMENSALIDADE,0) from SP_VRHM_EMP_DEP_COP_OP_SAU(:BDCODEMP, :prCOMPETENCIA, :BDCODCOL, :BDCODDPN) where BDCODPLACONVSAU = :BDCODPLAN and BDCODOPERADORA = :BDCODOPERADORA and BDCODCONVENIO = :BDCODCONVENIO into :BDREF, :BDCOPARTICIPACAO, :BDMENSALIDADE;

    WCONVANT = BDCODCONVENIO;
    WCOLANT = BDCODCOL;
    suspend;
  END

END^


create or alter procedure SP_VRH_SELECT_CALCULO13AD (
    PREMP varchar(25000),
    PRCOL varchar(32700),
    PRREF integer,
    PRPROVISAO DM_BOOLEAN,
    PRAPENASTRANS DM_BOOLEAN = 'FALSE' /* COLLATE WIN1252 - default */ )
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFA13 integer,
    BDCODVER integer,
    BDREFVA13 numeric(15,6),
    BDREFAUXVA13 numeric(15,6),
    BDVALVA13 numeric(15,6),
    BDPERCA13 numeric(15,6),
    BDVALA13 numeric(15,6),
    BDTIPOPROPA13 integer,
    BDMESESPROPA13 integer,
    BDBASEIRA13 numeric(15,6),
    BDFGTSA13 numeric(15,6),
    BDFGTSCSA13 numeric(15,6),
    BDBASEFGTSA13 numeric(15,6),
    BDDATABAIXAA13 date,
    BDREFBAIXAA13 integer,
    BDPERCIRA13 numeric(15,6),
    BDVALORIRA13 numeric(15,6),
    BDBSALFAMA13 numeric(15,6),
    BDSALFAMA13 numeric(15,6),
    BDBRAISA13 numeric(15,6),
    BDDEPA13 numeric(15,6),
    BDSALBASEA13 numeric(15,6),
    BDARREPROVA13 numeric(15,6),
    BDARREDESCA13 numeric(15,6),
    BDANOA13 integer,
    BDESTPROVA13 numeric(15,6),
    BDBASEPISA13 numeric(15,6),
    BDCLAVER varchar(20),
    BDINSSVER integer,
    BDFGTSVER integer,
    BDIRVER integer,
    BDTRANSFERIDO integer)
as
declare variable WSQL varchar(30000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WSQL1 varchar(30000);
declare variable WSQL2 varchar(30000);
declare variable WWHERE varchar(20000);
begin
  wsql = 'select BDCODEMP, BDCODCOL
      from VRH_EMP_TCOLCON COL ';

  if (:prEmp <> '') then
     begin
       wwhere = 'where ' || :premp;
       if (:prCol <> '') then
          wwhere = wwhere || ' and ' || :prcol;

       wsql = wsql || wwhere;
     end

  for execute statement wsql
  into :BDCODEMP, :BDCODCOL do
     begin
       wcodemp = 0;
       wcodcol = 0;

       BDTRANSFERIDO = 0;

       if (coalesce(:PRAPENASTRANS, 'FALSE') = 'FALSE') then
          begin
            if (PRREF < 202301) then
              wsql1 = 'select '||
                      'case when ((COALESCE(A13B.BDCALCFERA13, ''FALSE'') = ''TRUE'') and (FER.BDINIPERGOZOFE is not null)) '||
                      '     then (select str from strZero(extract(year from FER.BDINIPERGOZOFE),4)) || (select str from strZero(extract(month from FER.BDINIPERGOZOFE),2)) else A13V.BDREFA13 end BDREFA13, ';
            else
              wsql1 = 'select '||
                      'A13V.BDREFA13, ';

            wsql1 = wsql1||
                    'A13V.BDCODVER, ' ||
                    'A13V.BDREFVA13, ' ||
                    'A13V.BDREFAUXVA13, ' ||
                    'A13V.BDVALVA13, ' ||
                    'A13B.BDPERCA13, ' ||
                    'A13B.BDVALA13, ' ||
                    'A13B.BDTIPOPROPA13, ' ||
                    'A13B.BDMESESPROPA13, ' ||
                    'A13B.BDBASEIRA13, ' ||
                    'A13B.BDFGTSA13, ' ||
                    'A13B.BDFGTSCSA13, ' ||
                    'A13B.BDBASEFGTSA13, ' ||
                    'A13B.BDDATABAIXAA13, ' ||
                    'A13B.BDREFBAIXAA13, ' ||
                    'A13B.BDPERCIRA13, ' ||
                    'A13B.BDVALORIRA13, ' ||
                    'A13B.BDBSALFAMA13, ' ||
                    'A13B.BDSALFAMA13, ' ||
                    'A13B.BDBRAISA13, ' ||
                    'A13B.BDDEPA13, ' ||
                    'A13B.BDSALBASEA13, ' ||
                    'A13B.BDARREPROVA13, ' ||
                    'A13B.BDARREDESCA13, ' ||
                    'A13B.BDANOA13, ' ||
                    'A13B.BDESTPROVA13, ' ||
                    'A13B.BDBASEPISA13, ' ||
                    'VERB.BDCLAVER, ' ||
                    'VERREF.BDINSSVER, ' ||
                    'VERREF.BDFGTSVER, ' ||
                    'VERREF.BDIRVER ' ||
                    'from VRHF_EMP_TVERBAA13 A13V ' ||
                    'join VRHF_EMP_TA13SAL A13B on (A13V.BDCODEMP = A13B.BDCODEMP and A13V.BDCODCOL = A13B.BDCODCOL and A13V.BDREFA13 = A13B.BDREFA13) ' ||
                    'join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = A13V.BDCODVER) ' ||
                    'left join VRH_EMP_TFERIAS FER on (FER.BDCODEMP = A13B.BDCODEMP and FER.BDCODCOL = A13B.BDCODCOL and FER.BDDATAPAGFE = A13B.BDDATAPGTOA13) ' ||
                    'join VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = A13V.BDCODVER and VERREF.BDREFVER = (select max(BDREFVER) BDREFVER ' ||
                                                                                                                ' from VRH_BASE_TVERBAS_REF ' ||
                                                                                                                ' where BDCODVER = VERREF.BDCODVER and ' ||
                                                                                                                ' BDREFVER <= ' || :prref || ')) ' ||
                    'where A13B.BDCODEMP = ' || :BDCODEMP || ' and A13B.BDCODCOL = ' || :BDCODCOL || ' and A13B.BDANOA13 = ' || SUBSTRING(:prref FROM 1 FOR 4) || ' and A13B.bdrefa13<='||:prref;
     
            for execute statement wsql1 into
               :BDREFA13,
               :BDCODVER,
               :BDREFVA13,
               :BDREFAUXVA13,
               :BDVALVA13,
               :BDPERCA13,
               :BDVALA13,
               :BDTIPOPROPA13,
               :BDMESESPROPA13,
               :BDBASEIRA13,
               :BDFGTSA13,
               :BDFGTSCSA13,
               :BDBASEFGTSA13,
               :BDDATABAIXAA13,
               :BDREFBAIXAA13,
               :BDPERCIRA13,
               :BDVALORIRA13,
               :BDBSALFAMA13,
               :BDSALFAMA13,
               :BDBRAISA13,
               :BDDEPA13,
               :BDSALBASEA13,
               :BDARREPROVA13,
               :BDARREDESCA13,
               :BDANOA13,
               :BDESTPROVA13,
               :BDBASEPISA13,
               :BDCLAVER,
               :BDINSSVER,
               :BDFGTSVER,
               :BDIRVER DO
            suspend;
          end

       if (coalesce(PRPROVISAO, 'FALSE') = 'FALSE') then
          begin
            BDTRANSFERIDO = 1;
            --Transferidos
            wsql2 = 'select BDCODEMPORIG, BDCODCOLORIG
                    from vrh_emp_ttranscol COL
                    where BDCODEMPDEST = ' || :BDCODEMP || ' and BDCODCOLDEST = ' || :BDCODCOL || ' and BDCODEMPORIG is not null and BDCODCOLORIG is not null ';
     
            for execute statement wsql2
            into :WCODEMP, :WCODCOL do
               begin
                 wsql1 = 'select ' ||
                        'case when ((COALESCE(A13B.BDCALCFERA13, ''FALSE'') = ''TRUE'') and (FER.BDINIPERGOZOFE is not null)) ' ||
                        '     then (select str from strZero(extract(year from FER.BDINIPERGOZOFE),4)) || (select str from strZero(extract(month from FER.BDINIPERGOZOFE),2)) else A13V.BDREFA13 end BDREFA13, ' ||
                        'A13V.BDCODVER, ' ||
                        'A13V.BDREFVA13, ' ||
                        'A13V.BDREFAUXVA13, ' ||
                        'A13V.BDVALVA13, ' ||
                        'A13B.BDPERCA13, ' ||
                        'A13B.BDVALA13, ' ||
                        'A13B.BDTIPOPROPA13, ' ||
                        'A13B.BDMESESPROPA13, ' ||
                        'A13B.BDBASEIRA13, ' ||
                        'A13B.BDFGTSA13, ' ||
                        'A13B.BDFGTSCSA13, ' ||
                        'A13B.BDBASEFGTSA13, ' ||
                        'A13B.BDDATABAIXAA13, ' ||
                        'A13B.BDREFBAIXAA13, ' ||
                        'A13B.BDPERCIRA13, ' ||
                        'A13B.BDVALORIRA13, ' ||
                        'A13B.BDBSALFAMA13, ' ||
                        'A13B.BDSALFAMA13, ' ||
                        'A13B.BDBRAISA13, ' ||
                        'A13B.BDDEPA13, ' ||
                        'A13B.BDSALBASEA13, ' ||
                        'A13B.BDARREPROVA13, ' ||
                        'A13B.BDARREDESCA13, ' ||
                        'A13B.BDANOA13, ' ||
                        'A13B.BDESTPROVA13, ' ||
                        'A13B.BDBASEPISA13, ' ||
                        'VERB.BDCLAVER, ' ||
                        'VERREF.BDINSSVER, ' ||
                        'VERREF.BDFGTSVER, ' ||
                        'VERREF.BDIRVER ' ||
                        'from VRHF_EMP_TVERBAA13 A13V ' ||
                        'join VRHF_EMP_TA13SAL A13B on (A13V.BDCODEMP = A13B.BDCODEMP and A13V.BDCODCOL = A13B.BDCODCOL and A13V.BDREFA13 = A13B.BDREFA13) ' ||
                        'join VRH_BASE_TVERBAS VERB on (VERB.BDCODVER = A13V.BDCODVER) ' ||
                        'left join VRH_EMP_TFERIAS FER on (FER.BDCODEMP = A13B.BDCODEMP and FER.BDCODCOL = A13B.BDCODCOL and FER.BDDATAPAGFE = A13B.BDDATAPGTOA13) ' ||
                        'join VRH_BASE_TVERBAS_REF VERREF on (VERREF.BDCODVER = A13V.BDCODVER and VERREF.BDREFVER = (select max(BDREFVER) BDREFVER ' ||
                                                                                                                    ' from VRH_BASE_TVERBAS_REF ' ||
                                                                                                                    ' where BDCODVER = VERREF.BDCODVER and ' ||
                                                                                                                    ' BDREFVER <= ' || :prref || ')) ' ||
                        'where A13B.BDCODEMP = ' || :WCODEMP || ' and A13B.BDCODCOL = ' || :WCODCOL || ' and A13B.BDANOA13 = ' || SUBSTRING(:prref FROM 1 FOR 4);
          
                 for execute statement wsql1 into
                    :BDREFA13,
                    :BDCODVER,
                    :BDREFVA13,
                    :BDREFAUXVA13,
                    :BDVALVA13,
                    :BDPERCA13,
                    :BDVALA13,
                    :BDTIPOPROPA13,
                    :BDMESESPROPA13,
                    :BDBASEIRA13,
                    :BDFGTSA13,
                    :BDFGTSCSA13,
                    :BDBASEFGTSA13,
                    :BDDATABAIXAA13,
                    :BDREFBAIXAA13,
                    :BDPERCIRA13,
                    :BDVALORIRA13,
                    :BDBSALFAMA13,
                    :BDSALFAMA13,
                    :BDBRAISA13,
                    :BDDEPA13,
                    :BDSALBASEA13,
                    :BDARREPROVA13,
                    :BDARREDESCA13,
                    :BDANOA13,
                    :BDESTPROVA13,
                    :BDBASEPISA13,
                    :BDCLAVER,
                    :BDINSSVER,
                    :BDFGTSVER,
                    :BDIRVER do
                 suspend;
     
                 --Faz recursividade, pra verificar se tem mais transferências
                 wsql1 = 'select BDCODEMP, BDCODCOL, BDREFA13, BDCODVER, BDREFVA13, BDREFAUXVA13, BDVALVA13, BDPERCA13, BDVALA13, BDTIPOPROPA13, BDMESESPROPA13, BDBASEIRA13, BDFGTSA13, BDFGTSCSA13, '||
                               ' BDBASEFGTSA13, BDDATABAIXAA13, BDREFBAIXAA13, BDPERCIRA13, BDVALORIRA13, BDBSALFAMA13, BDSALFAMA13, BDBRAISA13, BDDEPA13, BDSALBASEA13, BDARREPROVA13, BDARREDESCA13,'||
                               ' BDANOA13, BDESTPROVA13, BDBASEPISA13, BDCLAVER, BDINSSVER, BDFGTSVER, BDIRVER, BDTRANSFERIDO '||
                               ' from SP_VRH_SELECT_CALCULO13AD(''BDCODEMP = ' || :WCODEMP || ''',''BDCODCOL = ' || :WCODCOL || ''',' || :PRREF || ',' || '''' || :PRPROVISAO || ''', ''TRUE'')';
                 for execute statement wsql1 into
                    :WCODEMP,
                    :WCODCOL,
                    :BDREFA13,
                    :BDCODVER,
                    :BDREFVA13,
                    :BDREFAUXVA13,
                    :BDVALVA13,
                    :BDPERCA13,
                    :BDVALA13,
                    :BDTIPOPROPA13,
                    :BDMESESPROPA13,
                    :BDBASEIRA13,
                    :BDFGTSA13,
                    :BDFGTSCSA13,
                    :BDBASEFGTSA13,
                    :BDDATABAIXAA13,
                    :BDREFBAIXAA13,
                    :BDPERCIRA13,
                    :BDVALORIRA13,
                    :BDBSALFAMA13,
                    :BDSALFAMA13,
                    :BDBRAISA13,
                    :BDDEPA13,
                    :BDSALBASEA13,
                    :BDARREPROVA13,
                    :BDARREDESCA13,
                    :BDANOA13,
                    :BDESTPROVA13,
                    :BDBASEPISA13,
                    :BDCLAVER,
                    :BDINSSVER,
                    :BDFGTSVER,
                    :BDIRVER,
                    :BDTRANSFERIDO DO
                    suspend;
               end
          end
     end
end^

CREATE OR ALTER TRIGGER VRHM_EMP_COPAR_COL_BI0 FOR VRHM_EMP_COPAR_COL
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (new.bdnaopagamensalidade is not null and trim(new.bdnaopagamensalidade) = 'NULO') then
     begin
       new.bdvalormensalidade = null;
       new.bdnaopagamensalidade = null;
     end
end
^

CREATE OR ALTER TRIGGER VRH_RHNET_TTIPO_ARQ_BI0 FOR VRH_RHNET_TTIPO_ARQ
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE VNOVOCOD INTEGER;
begin
  IF ((NEW.BDCODTIPO IS NULL) OR (NEW.BDCODTIPO = 0)) THEN
    BEGIN
      SELECT COALESCE(MAX(BDCODTIPO) + 1, 1)
      FROM VRH_RHNET_TTIPO_ARQ  
      INTO : VNOVOCOD;

      NEW.BDCODTIPO = :VNOVOCOD;
    end
end
^

CREATE OR ALTER TRIGGER VRHM_EMP_COPAR_COL_BU0 FOR VRHM_EMP_COPAR_COL
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  if (new.bdnaopagamensalidade is not null and trim(new.bdnaopagamensalidade) = 'NULO') then
     begin
       new.bdvalormensalidade = null;
       new.bdnaopagamensalidade = null;
     end
end
^

CREATE OR ALTER TRIGGER VRHM_EMP_COPAR_DEP_BI0 FOR VRHM_EMP_COPAR_DEP
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (new.bdnaopagamensalidade is not null and trim(new.bdnaopagamensalidade) = 'NULO') then
     begin
       new.bdvalormensalidade = null;
       new.bdnaopagamensalidade = null;
     end
end
^

CREATE OR ALTER TRIGGER VRHM_EMP_COPAR_DEP_BU0 FOR VRHM_EMP_COPAR_DEP
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  if (new.bdnaopagamensalidade is not null and trim(new.bdnaopagamensalidade) = 'NULO') then
     begin
       new.bdvalormensalidade = null;
       new.bdnaopagamensalidade = null;
     end
end
^

CREATE OR ALTER procedure SP_VAUD_INTRANET_INCONFORMIDADE (
    PRDESCRICAO varchar(5000))
returns (
    BDACAO varchar(5000),
    BDDESCRICAO varchar(5000))
as
declare variable WPOS integer;
declare variable WAUX varchar(5000);
declare variable WSEGSTR varchar(5000);
BEGIN
  wAux = prdescricao;
  wPos = 1;
  SELECT pos.pos FROM pos('Ação:', :waux) INTO :wpos;
  IF (wPos > 0) THEN
    BEGIN
      wSegStr = SUBSTRING(wAux FROM 1 FOR wPos - 1);
      waux = SUBSTRING(wAux FROM wPos + 0 FOR CHARACTER_LENGTH(prdescricao));
      IF (SUBSTRING(waux FROM 1 FOR 5) = 'Ação:') THEN
        BEGIN
          bdacao = :waux;
          bddescricao = :wsegstr;
        END
    END
  ELSE
    BEGIN
      bddescricao = prdescricao;
    END
SUSPEND;
END
^

create or alter procedure SP_VRH_EXP_DADOS_DA_FOLHA_SQL (
    PRCODEMP varchar(2000),
    PRCODCOL varchar(2000),
    PRCODSINDICATO varchar(1000),
    PRCODCLASSE varchar(1000),
    PRCOMPETENCIA integer,
    PRMODELO integer,
    PRTIPOFOLHA integer)
returns (
    BDSQL varchar(30000))
as
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(10000);
declare variable WORDERBY varchar(100);
declare variable WCOMPETENCIA varchar(10);
declare variable WCAMPOFILTROREF varchar(20);
declare variable WCAMPOVALV varchar(20);
declare variable WJOINTABELACALCVERBA varchar(10000);
declare variable WTABELACALC varchar(100);
declare variable WTABELAVERBA varchar(100);
declare variable WJOINAUX varchar(10000);
declare variable WTABELATOL varchar(50);
declare variable WJOINAUXTOL varchar(3000);
declare variable WTABELAPROV varchar(50);
declare variable WTABELATOLPROV varchar(50);
declare variable WJOINPROV varchar(10000);
declare variable WCALCFN varchar(50);
declare variable WCALCFT varchar(50);
declare variable WCALCFI varchar(50);
declare variable WCALCFTI varchar(50);
declare variable WVERBAFN varchar(50);
declare variable WVERBAFT varchar(50);
declare variable WVERBAFI varchar(50);
declare variable WVERBAFTI varchar(50);
declare variable WTOLFN varchar(50);
declare variable WTOLFT varchar(50);
declare variable WTOLFI varchar(50);
declare variable WTOLFTI varchar(50);
declare variable WCODCOLAUX varchar(1000);
declare variable WSQLIMPOSTOS varchar(10000);
declare variable WANO integer;
declare variable WDIA integer;
declare variable WMES integer;
declare variable WULTDIACOMP date;
declare variable WPRIDIACOMP date;
declare variable WCAMPOSIMPOSTOS varchar(10000);
declare variable WCAMPOSVALGPS varchar(4000);
declare variable WCAMPOSVALRAT varchar(4000);
declare variable WCAMPOSVALRATAPO varchar(4000);
declare variable WCAMPOSVALFPAS varchar(4000);
declare variable WTABELATOLCALC varchar(50);
declare variable WTOLCALCFN varchar(50);
declare variable WTOLCALCFT varchar(50);
declare variable WTOLCALCFI varchar(50);
declare variable WTOLCALCFTI varchar(50);
declare variable WCAMPOVALFGTS varchar(20);
declare variable WTABELATOLFGTS varchar(50);
declare variable WTOLFGTSFN varchar(50);
declare variable WTOLFGTSFT varchar(50);
declare variable WTOLFGTSFI varchar(50);
declare variable WTOLFGTSFTI varchar(50);
BEGIN
  /*
  PRMODELO
  1 - Verbas da Folha, 2 - Provisão 13º, 3 - Provisão Férias

  PRTIPOFOLHA
  1 - Folha normal, 2 - Férias, 3 - Adiantamento 13º, 4 - 13º Salário, 5 - Comp. 13º, 6 - Adiantamento salarial, 7 - Folha compl., 8 - Folha avulsa
  */

  WCOMPETENCIA = CAST(prcompetencia AS VARCHAR(6));

  wano = CAST(SUBSTRING(CAST(prcompetencia AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wmes = CAST(SUBSTRING(CAST(prcompetencia AS VARCHAR(6)) FROM 5 FOR 6) AS INTEGER);
  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  WULTDIACOMP = cast(wmes || '/' || cast(wdia as varchar(2)) || '/'||wano as date);
  WPRIDIACOMP = cast(wmes||'/01/'||wano as date);

  EXECUTE PROCEDURE sp_seta_competencia(prcompetencia, wPriDiaComp, wUltDiaComp);

  wSql = '';
  wWhere = '';
  worderby = '';

  PRCODEMP = UPPER(PRCODEMP);
  PRCODCOL = UPPER(PRCODCOL);
  PRCODSINDICATO = UPPER(PRCODSINDICATO);
  PRCODCLASSE = UPPER(PRCODCLASSE);

  wCampoFiltroRef = '';
  wCampoValV = '';

  wTabelaCalc = '';
  wTabelaVerba = '';
  wJoinAux  = '';
  wJoinTabelaCalcVerba = '';

  wTabelaTol = '';
  wTabelaTolCalc = '';
  wJoinAuxTol = '';
  wCalcFN    = '';
  wCalcFT    = '';
  wCalcFI    = '';
  wcalcFTI   = '';
  wVerbaFN   = '';
  wVerbaFT   = '';
  wVerbaFI   = '';
  wVerbaFTI  = '';
  wTolFN     = '';
  wTolFT     = '';
  wTolFI     = '';
  wTolFTI    = '';
  wTolCalcfn = '';
  wTolCalcft = '';
  wTolCalcfi = '';
  wTolCalcfti = '';
  WCODCOLAUX = '';
  wTabelaProv    = '';
  wTabelaTolProv = '';
  wJoinProv      = '';

  wsqlimpostos = '';
  wCamposImpostos = '';
  wCamposValGPS = '';
  wCamposValRat = '';
  wCamposValRatApo = '';
  wCamposValFPas = '';

  WCAMPOVALFGTS = '';
  WTABELATOLFGTS = '';
  WTOLFGTSFN = '';
  WTOLFGTSFT = '';
  WTOLFGTSFI = '';
  WTOLFGTSFTI = '';

  IF ((PRCODEMP IS NOT NULL) AND (PRCODEMP <> '')) THEN
    wWhere = wWhere||' AND '||REPLACE(PRCODEMP, 'BDCODEMP', 'CALC1.BDCODEMP');

  IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
    wWhere = wWhere||' AND '||REPLACE(PRCODCOL, 'BDCODCOL', 'CALC1.BDCODCOL');


  if (prmodelo = 1) then
  begin
      if (prTipoFolha = 1) then --folha normal
        begin
          wCamposValGPS = '  gpsind.BDVALFUNEMPFN+gpsind.BDVALPROEMPFN+gpsind.BDVALAUTEMPFN+' ||
                    ' gpsind.BDVALFUNEMPFERFN+gpsind.BDVALPROEMPFERFN+gpsind.BDVALAUTEMPFERFN+' ||
                    ' gpsind.BDVALFUNEMPFERFC+gpsind.BDVALPROEMPFERFC+gpsind.BDVALAUTEMPFERFC+' ||
                    --13º
                    ' gpsind.BDVALFUNEMP13+gpsind.BDVALFUNEMP13FN+gpsind.BDVALFUNEMP13FC+' ||
                    ' gpsind.BDVALPROEMP13+gpsind.BDVALPROEMP13FN+gpsind.BDVALPROEMP13FC+' ||
                    ' gpsind.BDVALAUTEMP13+gpsind.BDVALAUTEMP13FN+gpsind.BDVALAUTEMP13FC  ';
            
          wCamposValRat = '  gpsind.BDVALRATEMPFN+gpsind.BDVALRATEMPFERFN+gpsind.BDVALRATEMPFERFC+' ||
                          --13º
                          '  gpsind.BDVALRATEMP13+gpsind.BDVALRATEMP13FN+gpsind.BDVALRATEMP13FC  ';
          
          wCamposValRatApo = '  gpsind.BDVALRATAPOEMPFN+gpsind.BDVALRATAPOEMPFERFN+gpsind.BDVALRATAPOEMPFERFC+' ||
                              --13º
                              '  gpsind.BDVALRATAPOEMP13+gpsind.BDVALRATAPOEMP13FN+gpsind.BDVALRATAPOEMP13FC  ';
        
          wCamposValFPas = ' gpsind.BDVALFPASEMPFN+gpsind.BDVALFPASEMPFERFN+gpsind.BDVALFPASEMPFERFC+' ||
                     '  gpsind.BDVALSALEDUEMPFN+gpsind.BDVALSALEDUEMPFERFN+gpsind.BDVALSALEDUEMPFERFC+' ||
                     '  gpsind.BDVALINCRAEMPFN+gpsind.BDVALINCRAEMPFERFN+gpsind.BDVALINCRAEMPFERFC+' ||
                     '  gpsind.BDVALSENAIEMPFN+gpsind.BDVALSENAIEMPFERFN+gpsind.BDVALSENAIEMPFERFC+' ||
                     '  gpsind.BDVALSESIEMPFN+gpsind.BDVALSESIEMPFERFN+gpsind.BDVALSESIEMPFERFC+' ||
                     '  gpsind.BDVALSENACEMPFN+gpsind.BDVALSENACEMPFERFN+gpsind.BDVALSENACEMPFERFC+' ||
                     '  gpsind.BDVALSESCEMPFN+gpsind.BDVALSESCEMPFERFN+gpsind.BDVALSESCEMPFERFC+' ||
                     '  gpsind.BDVALSEBRAEEMPFN+gpsind.BDVALSEBRAEEMPFERFN+gpsind.BDVALSEBRAEEMPFERFC+' ||
                     '  gpsind.BDVALDPCEMPFN+gpsind.BDVALDPCEMPFERFN+gpsind.BDVALDPCEMPFERFC+' ||
                     '  gpsind.BDVALFUNAEROEMPFN+gpsind.BDVALFUNAEROEMPFERFN+gpsind.BDVALFUNAEROEMPFERFC+' ||
                     '  gpsind.BDVALSENAREMPFN+gpsind.BDVALSENAREMPFERFN+gpsind.BDVALSENAREMPFERFC+' ||
                     '  gpsind.BDVALSESTEMPFN+gpsind.BDVALSESTEMPFERFN+gpsind.BDVALSESTEMPFERFC+' ||
                     '  gpsind.BDVALSENATEMPFN+gpsind.BDVALSENATEMPFERFN+gpsind.BDVALSENATEMPFERFC+' ||
                     '  gpsind.BDVALSESCOOPEMPFN+gpsind.BDVALSESCOOPEMPFERFN+gpsind.BDVALSESCOOPEMPFERFC+' ||
                     --13º
                     '  gpsind.BDVALFPASEMP13+gpsind.BDVALFPASEMP13FN+gpsind.BDVALFPASEMP13FC+' ||
                    ' gpsind.BDVALSALEDUEMP13+gpsind.BDVALSALEDUEMP13FN+gpsind.BDVALSALEDUEMP13FC+' ||
                    ' gpsind.BDVALINCRAEMP13+gpsind.BDVALINCRAEMP13FN+gpsind.BDVALINCRAEMP13FC+' ||
                    ' gpsind.BDVALSENAIEMP13+gpsind.BDVALSENAIEMP13FN+gpsind.BDVALSENAIEMP13FC+' ||
                    ' gpsind.BDVALSESIEMP13+gpsind.BDVALSESIEMP13FN+gpsind.BDVALSESIEMP13FC+' ||
                    ' gpsind.BDVALSENACEMP13+gpsind.BDVALSENACEMP13FN+gpsind.BDVALSENACEMP13FC+' ||
                    ' gpsind.BDVALSESCEMP13+gpsind.BDVALSESCEMP13FN+gpsind.BDVALSESCEMP13FC+' ||
                    ' gpsind.BDVALSEBRAEEMP13+gpsind.BDVALSEBRAEEMP13FN+gpsind.BDVALSEBRAEEMP13FC+' ||
                    ' gpsind.BDVALDPCEMP13+gpsind.BDVALDPCEMP13FN+gpsind.BDVALDPCEMP13FC+' ||
                    ' gpsind.BDVALFUNAEROEMP13+gpsind.BDVALFUNAEROEMP13FN+gpsind.BDVALFUNAEROEMP13FC+' ||
                    ' gpsind.BDVALSENAREMP13+gpsind.BDVALSENAREMP13FN+gpsind.BDVALSENAREMP13FC+' ||
                    ' gpsind.BDVALSESTEMP13+gpsind.BDVALSESTEMP13FN+gpsind.BDVALSESTEMP13FC+' ||
                    ' gpsind.BDVALSENATEMP13+gpsind.BDVALSENATEMP13FN+gpsind.BDVALSENATEMP13FC+' ||
                    ' gpsind.BDVALSESCOOPEMP13+gpsind.BDVALSESCOOPEMP13FN+gpsind.BDVALSESCOOPEMP13FC  ';
        end
      else if (prTipoFolha = 3) then --Adiantamento 13º 
        begin
          wCamposValGPS = '  gpsind.BDVALFUNEMP13+gpsind.BDVALPROEMP13+gpsind.BDVALAUTEMP13  ';
          
          wCamposValRat = '  gpsind.BDVALRATEMP13  ';
          
          wCamposValRatApo = '  gpsind.BDVALRATAPOEMP13  ';
          
          wCamposValFPas = '  gpsind.BDVALFPASEMP13+gpsind.BDVALSALEDUEMP13+gpsind.BDVALINCRAEMP13+' ||
                     ' gpsind.BDVALSENAIEMP13+gpsind.BDVALSESIEMP13+gpsind.BDVALSENACEMP13+' ||
                     ' gpsind.BDVALSESCEMP13+gpsind.BDVALSEBRAEEMP13+gpsind.BDVALDPCEMP13+' ||
                     ' gpsind.BDVALFUNAEROEMP13+gpsind.BDVALSENAREMP13+gpsind.BDVALSESTEMP13+' ||
                     ' gpsind.BDVALSENATEMP13+gpsind.BDVALSESCOOPEMP13  ';
        end
      else if (prTipoFolha = 4) then --13º
        begin
          wCamposValGPS = '  gpsind.BDVALFUNEMP13+gpsind.BDVALFUNEMP13FN+gpsind.BDVALFUNEMP13FC+' ||
                    ' gpsind.BDVALPROEMP13+gpsind.BDVALPROEMP13FN+gpsind.BDVALPROEMP13FC+' ||
                    ' gpsind.BDVALAUTEMP13+gpsind.BDVALAUTEMP13FN+gpsind.BDVALAUTEMP13FC  ';
          
          wCamposValRat = '  gpsind.BDVALRATEMP13+gpsind.BDVALRATEMP13FN+gpsind.BDVALRATEMP13FC  ';
          
          wCamposValRatApo = '  gpsind.BDVALRATAPOEMP13+gpsind.BDVALRATAPOEMP13FN+gpsind.BDVALRATAPOEMP13FC  ';
          
          wCamposValFPas ='  gpsind.BDVALFPASEMP13+gpsind.BDVALFPASEMP13FN+gpsind.BDVALFPASEMP13FC+' ||
                    ' gpsind.BDVALSALEDUEMP13+gpsind.BDVALSALEDUEMP13FN+gpsind.BDVALSALEDUEMP13FC+' ||
                    ' gpsind.BDVALINCRAEMP13+gpsind.BDVALINCRAEMP13FN+gpsind.BDVALINCRAEMP13FC+' ||
                    ' gpsind.BDVALSENAIEMP13+gpsind.BDVALSENAIEMP13FN+gpsind.BDVALSENAIEMP13FC+' ||
                    ' gpsind.BDVALSESIEMP13+gpsind.BDVALSESIEMP13FN+gpsind.BDVALSESIEMP13FC+' ||
                    ' gpsind.BDVALSENACEMP13+gpsind.BDVALSENACEMP13FN+gpsind.BDVALSENACEMP13FC+' ||
                    ' gpsind.BDVALSESCEMP13+gpsind.BDVALSESCEMP13FN+gpsind.BDVALSESCEMP13FC+' ||
                    ' gpsind.BDVALSEBRAEEMP13+gpsind.BDVALSEBRAEEMP13FN+gpsind.BDVALSEBRAEEMP13FC+' ||
                    ' gpsind.BDVALDPCEMP13+gpsind.BDVALDPCEMP13FN+gpsind.BDVALDPCEMP13FC+' ||
                    ' gpsind.BDVALFUNAEROEMP13+gpsind.BDVALFUNAEROEMP13FN+gpsind.BDVALFUNAEROEMP13FC+' ||
                    ' gpsind.BDVALSENAREMP13+gpsind.BDVALSENAREMP13FN+gpsind.BDVALSENAREMP13FC+' ||
                    ' gpsind.BDVALSESTEMP13+gpsind.BDVALSESTEMP13FN+gpsind.BDVALSESTEMP13FC+' ||
                    ' gpsind.BDVALSENATEMP13+gpsind.BDVALSENATEMP13FN+gpsind.BDVALSENATEMP13FC+' ||
                    ' gpsind.BDVALSESCOOPEMP13+gpsind.BDVALSESCOOPEMP13FN+gpsind.BDVALSESCOOPEMP13FC  ';
        end        
      else if (prTipoFolha = 5) then --comp 13º
        begin
          wCamposValGPS = '  gpsind.BDVALFUNEMPC13+gpsind.BDVALPROEMPC13+gpsind.BDVALAUTEMPC13  ';
          
          wCamposValRat = '  gpsind.BDVALRATEMPc13  ';
          
          wCamposValRatApo = '  gpsind.BDVALRATAPOEMPc13  ';
          
          wCamposValFPas = '  gpsind.BDVALFPASEMPc13+gpsind.BDVALSALEDUEMPc13+gpsind.BDVALINCRAEMPc13+' ||
                    ' gpsind.BDVALSENAIEMPc13+gpsind.BDVALSESIEMPc13+gpsind.BDVALSENACEMPc13+' ||
                    ' gpsind.BDVALSESCEMPc13+gpsind.BDVALSEBRAEEMPc13+gpsind.BDVALDPCEMPc13+' ||
                    ' gpsind.BDVALFUNAEROEMPc13+gpsind.BDVALSENAREMPc13+gpsind.BDVALSESTEMPc13+' ||
                    ' gpsind.BDVALSENATEMPc13+gpsind.BDVALSESCOOPEMPc13  ';
        end
      else if ((prTipoFolha = 6) or (prTipoFolha = 8)) then --adiantamento salarial e folha avulsa
        begin
          wCamposValGPS = '  gpsind.BDVALFUNEMPFN+gpsind.BDVALPROEMPFN+gpsind.BDVALAUTEMPFN+' ||
                    ' gpsind.BDVALFUNEMPFERFN+gpsind.BDVALPROEMPFERFN+gpsind.BDVALAUTEMPFERFN+' ||
                    ' gpsind.BDVALFUNEMPFERFC+gpsind.BDVALPROEMPFERFC+gpsind.BDVALAUTEMPFERFC  ';
            
          wCamposValRat = '  gpsind.BDVALRATEMPFN  ';
          
          wCamposValRatApo = '  gpsind.BDVALRATAPOEMPFN  ';
        
          wCamposValFPas = '  gpsind.BDVALFPASEMPFN+gpsind.BDVALSALEDUEMPFN+gpsind.BDVALINCRAEMPFN+' ||
                     ' gpsind.BDVALSENAIEMPFN+gpsind.BDVALSESIEMPFN+gpsind.BDVALSENACEMPFN+' ||
                     ' gpsind.BDVALSESCEMPFN+gpsind.BDVALSEBRAEEMPFN+gpsind.BDVALDPCEMPFN+' ||
                     ' gpsind.BDVALFUNAEROEMPFN+gpsind.BDVALSENAREMPFN+gpsind.BDVALSESTEMPFN+' ||
                     ' gpsind.BDVALSENATEMPFN +gpsind.BDVALSESCOOPEMPFN  ';
        end
      else if (prTipoFolha = 7) then --folha complementar
        begin
          wCamposValGPS = '  gpsIND.BDVALFUNEMPFC +GPSIND.BDVALPROEMPFC+GPSIND.BDVALAUTEMPFC  ';
      
          wCamposValRat = '  GPSIND.BDVALRATEMPFC  ';
        
          wCamposValRatApo = '  GPSIND.BDVALRATAPOEMPFC  ';
      
          wCamposValFPas = '  GPSIND.BDVALFPASEMPFC+GPSIND.BDVALSALEDUEMPFC+GPSIND.BDVALINCRAEMPFC+' ||
                     '  GPSIND.BDVALSENAIEMPFC+GPSIND.BDVALSESIEMPFC+GPSIND.BDVALSENACEMPFC+' ||
                     '  GPSIND.BDVALSESCEMPFC+GPSIND.BDVALSEBRAEEMPFC+GPSIND.BDVALDPCEMPFC+' ||
                     '  GPSIND.BDVALFUNAEROEMPFC+GPSIND.BDVALSENAREMPFC+GPSIND.BDVALSESTEMPFC+' ||
                     '  GPSIND.BDVALSENATEMPFC+GPSIND.BDVALSESCOOPEMPFC  ';
        end

      wCamposImpostos = wCamposValGPS || ' BDVALGPS, ' || wCamposValRat || ' BDVALRAT, ' || wCamposValRatApo || ' BDVALRATAPO, ' || wCamposValFPas || 'BDVALFPASTERCEIROS ';
    end

  wSqlImpostos = 'select DISTINCT DARF.BDCODEMP BDCODEMP, ' ||
                       'GPSIND.BDCODCOL BDCODCOL, ' ||
                       'DARF.BDREFERENCIA BDREF, ' ||
                       'NULL AS BDTIPOREFVER, ' ||
                       'LAN.BDCOMPL AS BDDESCVER, ' ||
                       'NULL AS BDCODVER, ' ||
                       '100 AS BDTIPOCODVER, ' ||
                       'NULL AS BDREFV, ' ||
                       'NULL AS BDVALV, ' ||
                       'PLADEB.BDCODTPLA BDCODTPLADEB, ' ||
                       'PLADEB.BDCTALON BDCTALONDEB, ' ||
                       'PLADEB.BDNOMCTA BDNOMCTADEB, ' ||
                       'PLACRE.BDCODTPLA BDCODTPLACRE, ' ||
                       'PLACRE.BDCTALON BDCTALONCRE, ' ||
                       'PLACRE.BDNOMCTA BDNOMCTACRE, ' ||
                       'TLCC.BDCODCENTRO, ' ||
                       'TLCC.BDCODTPCC , ' ||
                       wCamposImpostos ||
                       ' , 3 as BDORDEMVER ' ||
                   'FROM (SELECT * ' ||
                           'FROM VSUC_EMPRESAS_TLAN LAN ' ||
                          'WHERE ' || REPLACE(PRCODEMP, 'BDCODEMP', 'LAN.BDCODEMP') ||
                           ' AND LAN.BDDATA BETWEEN ''' || WPRIDIACOMP || ''' AND ''' || WULTDIACOMP ||''' AND LAN.BDTIPOLAN = 200) LAN ' ||
                   'JOIN TOL_UNICO_PROV_DARF TOL ON (TOL.BDCODEMPSUC = LAN.BDCODEMP ' ||
                                                    'AND TOL.BDCHAVE = LAN.BDCHAVE) ' ||
                   'LEFT JOIN PLANOS_TPLA PLADEB ON (PLADEB.BDCODPLAPADRAO = LAN.BDCODPLAPADRAO ' ||
                                                    'AND PLADEB.BDCODTPLA = LAN.BDDEBITO) ' ||
                   'LEFT JOIN PLANOS_TPLA PLACRE ON (PLACRE.BDCODPLAPADRAO = LAN.BDCODPLAPADRAO ' ||
                                                    'AND PLACRE.BDCODTPLA = LAN.BDCREDITO) ' ||
                   'LEFT JOIN VSUC_EMPRESAS_TLCC TLCC ON (LAN.BDCODEMP = TLCC.BDCODEMP ' ||
                                                        'AND LAN.BDCHAVE = TLCC.BDCHAVE) ' ||
                   'JOIN TDARFPADRAO DARF ON (TOL.BDCODEMP = DARF.BDCODEMP ' ||
                                             'AND TOL.BDCHAVEDARF = DARF.BDCHAVEDARF) ' ||
                   'JOIN VRHF_EMP_GPS_IND GPSIND ON (DARF.BDCODEMP = GPSIND.BDCODEMPCOL ' ||
                                                    'AND DARF.BDCHAVEDARF = GPSIND.BDCHAVEDARF) ' ||
                   'WHERE ' || REPLACE(PRCODEMP, 'BDCODEMP', 'DARF.BDCODEMP') || ' ' ||
                    iif(PRCODCOL <> '', ' AND ' || REPLACE(PRCODCOL, 'BDCODCOL', 'GPSIND.BDCODCOL'), ' ') || ' ' ||
                     ' AND DARF.BDREFERENCIA = ' || CAST(PRCOMPETENCIA AS VARCHAR(6)) ||
                   'GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20, 21) CALC1 ';



  IF (PRMODELO = 1) THEN  --Verbas da folha
    BEGIN
      IF (PRTIPOFOLHA IN (1, 7)) THEN       --Folha normal
        BEGIN
          wCampoFiltroRef = 'BDREF';
          wCampoValV      = 'BDVALV';
        END
      ELSE IF (PRTIPOFOLHA = 2) THEN  --Férias
        BEGIN
          wCampoFiltroRef = 'BDREFINIFE';
          wCampoValV      = 'BDVALVFE';
          WCAMPOVALFGTS   = 'BDVALORFGTSFE';

          wTabelaCalc     = ' VRH_EMP_TFERIAS';
          wTabelaVerba    = ' VRHF_EMP_TVERBAFE';
          wJoinAux        = ' AND CalcFol.BDINIPERAQUISFE = VERBAAUX.BDINIPERAQUISFE AND CalcFol.BDCODFE = VERBAAUX.BDCODFE) ';

          wTabelaTol      = ' TOL_VRHF_EMP_TVERBA_FER';
          wTabelaTolCalc  = ' TOL_VRHF_EMP_TCALC_FER';
          wJoinAuxTol     = ' AND TOL.BDINIPERAQUISFE = VERBAAUX.BDINIPERAQUISFE AND TOL.BDCODFE = VERBAAUX.BDCODFE) ';
        END
      ELSE IF (PRTIPOFOLHA = 3) THEN  --Adiantamento 13º
        BEGIN
          wCampoFiltroRef = 'BDREFA13';
          wCampoValV      = 'BDVALVA13';
          WCAMPOVALFGTS   = 'BDFGTSA13';

          wTabelaCalc     = 'VRHF_EMP_TA13SAL';
          wTabelaVerba    = 'VRHF_EMP_TVERBAA13';
          wJoinAux        = ' AND CalcFol.BDREFA13 = VERBAAUX.BDREFA13) ';

          wTabelaTol      = ' TOL_VRHF_EMP_TVERBA_A13';
          wTabelaTolCalc  = ' TOL_VRHF_EMP_TCALC_A13';
          wTabelaTolFGTS = ' TOL_VRHF_EMP_TFGTS_A13';
          wJoinAuxTol     = '  AND TOL.BDREFA13 = VERBAAUX.BDREFA13) ';
        END
      ELSE IF (PRTIPOFOLHA = 4) THEN  --13º salario
        BEGIN
          wCampoFiltroRef = 'BDREF13';
          wCampoValV      = 'BDVALV13';
          WCAMPOVALFGTS   = 'BDFGTS13';

          wTabelaCalc     = 'VRHF_EMP_T13SAL';
          wTabelaVerba    = 'VRHF_EMP_TVERBA13';
          wJoinAux        = ' AND CalcFol.BDREF13 = VERBAAUX.BDREF13) ';

          wTabelaTol      = ' TOL_VRHF_EMP_TVERBA_13';
          wTabelaTolCalc  = ' TOL_VRHF_EMP_TCALC_13';
          wTabelaTolFGTS = ' TOL_VRHF_EMP_TFGTS_13';
          wJoinAuxTol     = ' AND TOL.BDREF13 = VERBAAUX.BDREF13) ';
        END
      ELSE IF (PRTIPOFOLHA = 5) THEN  --Complemento 13º
        BEGIN
          wCampoFiltroRef = 'BDREFC13';
          wCampoValV      = 'BDVALVC13';
          WCAMPOVALFGTS   = 'BDFGTSC13';

          wTabelaCalc     = 'VRHF_EMP_TC13SAL';
          wTabelaVerba    = 'VRHF_EMP_TVERBAC13';
          wJoinAux        = ' AND CalcFol.BDREF13 =  VERBAAUX.BDREF13 AND CalcFol.BDREFC13 = VERBAAUX.BDREFC13) ';

          wTabelaTol      = ' TOL_VRHF_EMP_TVERBA_C13';
          wTabelaTolCalc  = ' TOL_VRHF_EMP_TCALC_C13';
          wTabelaTolFGTS = ' TOL_VRHF_EMP_TFGTS_C13';
          wJoinAuxTol     = '  AND TOL.BDREF13 = VERBAAUX.BDREF13 AND TOL.BDREFC13 = VERBAAUX.BDREFC13) ';
        END
      ELSE IF (PRTIPOFOLHA = 6) THEN  --Adiantamento Salarial
        BEGIN
          wCampoFiltroRef = 'BDREFAD';
          wCampoValV      = 'BDVALVAD';

          wTabelaCalc     = 'VRHF_EMP_TADSAL';
          wTabelaVerba    = 'VRHF_EMP_TVERBAAD';
          wJoinAux        = ' AND CalcFol.BDDATAAD = VERBAAUX.BDDATAAD) ';

          wTabelaTol      = ' TOL_VRHF_EMP_TVERBA_AD';
          wTabelaTolCalc  = ' TOL_VRHF_EMP_TCALC_AD';
          wJoinAuxTol     = '  AND TOL.BDDATAAD = VERBAAUX.BDDATAAD) ';
        END
      ELSE IF (PRTIPOFOLHA = 8) THEN  --Folha avulsa
        BEGIN
          wCampoFiltroRef = 'BDREF';
          wCampoValV      = 'BDVALVFA';
          WCAMPOVALFGTS   = 'BDFGTSFA';

          wTabelaCalc     = 'VRHF_EMP_TFOLHAAVULSA';
          wTabelaVerba    = 'VRHF_EMP_TVERBAFA';
          wJoinAux        = ' AND CalcFol.BDCODTCA = VERBAAUX.BDCODTCA AND CalcFol.BDDATAFA = VERBAAUX.BDDATAFA) ';

          wTabelaTol      = ' TOL_VRHF_EMP_TVERBA_FA';
          wTabelaTolCalc  = ' TOL_VRHF_EMP_TCALC_FA';
          wTabelaTolFGTS = ' TOL_VRHF_EMP_TFGTS_FA';
          wJoinAuxTol     = ' AND TOL.BDDATAFA = VERBAAUX.BDDATAFA) ';
        END
      --monta os joins
                                  --verbas
        wJoinTabelaCalcVerba = ' ( SELECT CalcFol.BDCODEMP, ' ||
                                         'CalcFol.BDCODCOL, ' ||
                                         'CalcFol.' || WCAMPOFILTROREF || ' BDREF, ' ||
                                         'VERBAAUX.BDCODVER, ' ||
                                         'VERBAAUX.' || wCampoValV || ' BDVALV, ' ||
                                         'TOL.BDCHAVE, ' ||
                                         'TOL.BDCODEMPSUC, ' ||
                                         'CalcFol.BDORDEM, ' ||
                                         '1 AS BDORDEMVER ' ||
                                   ' FROM ' || wTabelaCalc || ' CalcFol ' ||
                                  ' left join ' || wTabelaVerba || ' VERBAAUX ON (CalcFol.BDCODEMP = VERBAAUX.BDCODEMP ' ||
                                                                                ' AND CalcFol.BDCODCOL = VERBAAUX.BDCODCOL ' ||
                                                                                wJoinAux ||
                                  ' left join ' || wTabelaTol || ' TOL ON (TOL.BDCODVER = VERBAAUX.BDCODVER ' ||
                                                                          'AND TOL.BDCODEMP = VERBAAUX.BDCODEMP ' ||
                                                                          'AND TOL.BDCODCOL = VERBAAUX.BDCODCOL ' ||
                                                                          wJoinAuxTol ||
                                  ' WHERE ' || REPLACE(PRCODEMP, 'BDCODEMP', 'CalcFol.BDCODEMP') ||
                                  IIF(WCODCOLAUX = '', '', ' AND CalcFol.' || WCODCOLAUX || ' ') ||
                                  '   AND CalcFol.' || WCAMPOFILTROREF || ' = ' || WCOMPETENCIA ||

                                  ' UNION ALL ' ||
                                  --liquido
                                  'SELECT CALCFOL.BDCODEMP, ' ||
                                         'CALCFOL.BDCODCOL, ' ||
                                         'CalcFol.' || WCAMPOFILTROREF || ' BDREF, ' ||
                                         '0 BDCODVER, ' ||
                                         'CALCFOL.BDLIQUIDO as BDVALV, ' ||
                                         'TOL.BDCHAVE, ' ||
                                         'TOL.BDCODEMPSUC, ' ||
                                         'CalcFol.BDORDEM, ' ||
                                         '2 AS BDORDEMVER ' ||
                                  'FROM ' || wTabelaCalc || ' CALCFOL ' ||
                                  'LEFT JOIN '|| WTABELATOLCALC || ' TOL ON (TOL.BDCODEMP = CALCFOL.BDCODEMP ' ||
                                                                           'AND TOL.BDCODCOL = CALCFOL.BDCODCOL ' ||
                                                                           replace(wJoinAuxTol, 'VERBAAUX', 'CALCFOL') ||
                                  ' WHERE ' || REPLACE(PRCODEMP, 'BDCODEMP', 'CalcFol.BDCODEMP') ||
                                  IIF(WCODCOLAUX = '', '', ' AND CalcFol.' || WCODCOLAUX || ' ') ||
                                  '   AND CalcFol.' || WCAMPOFILTROREF || ' = ' || WCOMPETENCIA ||
                                  --fgts
                                  iif(prtipofolha in (2,6), '/*', '') ||
                                  ' UNION  ALL ' ||
                                  ' SELECT CALCFOL.BDCODEMP, ' ||
                                         'CALCFOL.BDCODCOL, ' ||
                                         'CalcFol.' || WCAMPOFILTROREF || ' BDREF, ' ||
                                         '0 BDCODVER, ' ||
                                         'CALCFOL.' || WCAMPOVALFGTS || ' as BDVALV, ' ||
                                         'TOL.BDCHAVE, ' ||
                                         'TOL.BDCODEMPSUC, ' ||
                                         'CalcFol.BDORDEM, ' ||
                                         '2 AS BDORDEMVER ' ||
                                  'FROM ' || wTabelaCalc || ' CALCFOL ' ||
                                  'LEFT JOIN '|| wTabelaTolFGTS || ' TOL ON (TOL.BDCODEMP = CALCFOL.BDCODEMP ' ||
                                                                           'AND TOL.BDCODCOL = CALCFOL.BDCODCOL ' ||
                                                                           replace(wJoinAuxTol, 'VERBAAUX', 'CALCFOL') ||
                                  ' WHERE ' || REPLACE(PRCODEMP, 'BDCODEMP', 'CalcFol.BDCODEMP') ||
                                  IIF(WCODCOLAUX = '', '', ' AND CalcFol.' || WCODCOLAUX || ' ') ||
                                  '   AND CalcFol.' || WCAMPOFILTROREF || ' = ' || WCOMPETENCIA ||

                                  iif(prtipofolha in (2,6), '*/', '') ||

                             ') CALC LEFT JOIN VW_TVERBAS_REF VERBA ON (CALC.BDCODVER = VERBA.BDCODVER) ' ||
                             'LEFT OUTER JOIN VRHF_EMP_TPREPFN CC ON (CC.BDCODEMP = CALC.BDCODEMP ' ||
                                                                    ' AND CC.BDCODCOL = CALC.BDCODCOL ' ||
                                                                    ' AND CC.BDORDEM = CALC.BDORDEM) ' ||
                              'LEFT JOIN VSUC_EMPRESAS_TLAN LAN ON (LAN.BDCODEMP = CALC.BDCODEMPSUC ' ||
                                                                  ' AND LAN.BDCHAVE = CALC.BDCHAVE) ' ||
                             'LEFT JOIN PLANOS_TPLA PLADEB ON (PLADEB.BDCODPLAPADRAO = LAN.BDCODPLAPADRAO ' ||
                                                              'AND PLADEB.BDCODTPLA = LAN.BDDEBITO) ' ||
                             'LEFT JOIN PLANOS_TPLA PLACRE ON (PLACRE.BDCODPLAPADRAO = LAN.BDCODPLAPADRAO ' ||
                                                              'AND PLACRE.BDCODTPLA = LAN.BDCREDITO) '||
                             ' WHERE CALC.BDREF = ' || CAST(PRCOMPETENCIA AS VARCHAR(6)) || replace(wWhere, 'CALC1', 'CALC') ||
                             iif(prtipofolha = 2, ') CALC1', ' UNION ALL ' || wSqlImpostos); --se for férias não apresenta valores de impostos
    END
  ELSE       --provisoes
    BEGIN
      IF ((PRCODCOL <> '') OR (PRCODCOL IS NOT NULL))  THEN
            WCODCOLAUX = REPLACE(PRCODCOL, 'BDCODCOL', 'P.BDCODCOL');

      IF (prModelo = 2) THEN
        BEGIN
          wTabelaProv     = 'VRHF_EMP_TPROVISAO13_DET';
          wTabelaTolProv  = 'TOL_VRHF_EMP_TPROV13_DET';
          wCampoFiltroRef = 'BDREFP13';
        END
      ELSE IF (prModelo = 3) THEN
        BEGIN
          wTabelaProv     = 'VRHF_EMP_TPROVISAOFERIAS_DET';
          wTabelaTolProv  = 'TOL_VRHF_EMP_TPROVFER_DET';
          wCampoFiltroRef = 'BDREFPFER';
        END

      wJoinProv = 'SELECT P.BDCODEMP, ' ||
                         'P.BDCODCOL, ' ||
                         'P.' || IIF(prModelo = 3, 'BDLINHAPFER', 'BDLINHAP13') || ' BDLINHA, ' ||
                         'P.' || IIF(prModelo = 3, 'BDREFPFER', 'BDREFP13') || ' BDREF, ' ||
                         'P.' || IIF(prModelo = 3, 'BDORDEMCCPFER', 'BDORDEMCCP13') || ' BDORDEMCC, ' ||
                         'P.BDPLANOCC, ' ||
                         'P.BDORDEM, ' ||
                         'P.BDCODHIST, ' ||
                         'P.' || IIF(prModelo = 3, 'BDFERIAS, P.BDUMTERCO', 'BD13SAL') || ', ' ||
                         'P.BDFGTS, ' ||
                         'P.BDINSS, ' ||
                         'P.BDFPAS, ' ||
                         'P.BDCNAE, ' ||
                         'P.BDRATAPO, ' ||
                         'P.BDPIS, ' ||
                         'TOLP.BDCHAVE, ' ||
                         'TOLP.BDCODEMPSUC ' ||
              ' FROM ' || wTabelaProv || ' P ' ||
              ' JOIN ' || wTabelaTolProv || ' TOLP ON (P.BDCODEMP = TOLP.BDCODEMP ' ||
                                            ' AND P.BDCODCOL = TOLP.BDCODCOL ' ||
                                            ' AND P.' || IIF(prModelo = 3, 'BDLINHAPFER', 'BDLINHAP13') || ' = TOLP.' || IIF(prModelo = 3, 'BDLINHAPFER', 'BDLINHAP13') || ' ' ||
                                            ' AND P.' || IIF(prModelo = 3, 'BDREFPFER', 'BDREFP13') || ' = TOLP.' || IIF(prModelo = 3, 'BDREFPFER', 'BDREFP13') || ' ' ||
                                            ' AND P.' || IIF(prModelo = 3, 'BDORDEMCCPFER', 'BDORDEMCCP13') || ' = TOLP.' || IIF(prModelo = 3, 'BDORDEMCCPFER', 'BDORDEMCCP13') || ' ' ||
                                            ' AND P.BDPLANOCC = TOLP.BDPLANOCC ' ||
                                            ' AND P.BDORDEM = TOLP.BDORDEM) ' ||
         '     WHERE ' || REPLACE(PRCODEMP, 'BDCODEMP', 'P.BDCODEMP') ||
               ' AND P.' || IIF(prModelo = 3, 'BDREFPFER', 'BDREFP13') || ' = ' || WCOMPETENCIA ||
         IIF(WCODCOLAUX = '', '', ' AND ' || WCODCOLAUX || ' ') || ' ';
         /*' ORDER BY P.BDCODEMP, ' ||
                  ' P.BDCODCOL, ' ||
                  ' P.' || IIF(prModelo = 3, 'BDREFPFER', 'BDREFP13') || ' DESC, ' ||
                  ' P.BDPLANOCC, ' ||
                  ' P.' || IIF(prModelo = 3, 'BDORDEMCCPFER', 'BDORDEMCCP13') || ', ' ||
                  ' P.' || IIF(prModelo = 3, 'BDLINHAPFER', 'BDLINHAP13') || ' ';*/
    END

  --inicio SQL principal
  if (prmodelo = 1) then
    begin
      wSql = 'SELECT CALC1.BDCODEMP, ' ||
                    'CALC1.BDCODCOL, ' ||
                    'COLCAD.BDNOMCOL, ' ||
                    'TPCC.BDNOMCTA, ' ||
                    'CARGO.BDDESCTFUC, ' ||
                    'CALCDIA.BDSALBASECOL, ' ||
                    'COLCON.BDDATAADMCOL, ' ||
                    'CALC1.BDTIPOREFVER, ' ||
                    'CALC1.BDDESCVER, ' ||
                    'CALC1.BDCODVER, ' ||
                    'CALC1.BDREFV, ' ||
                    'CALC1.BDVALV, ' ||
                    'CALC1.BDCODTPLADEB, ' ||
                    'CALC1.BDCTALONDEB, ' ||
                    'CALC1.BDNOMCTADEB, ' ||
                    'CALC1.BDCODTPLACRE, ' ||
                    'CALC1.BDCTALONCRE, ' ||
                    'CALC1.BDNOMCTACRE, ' ||
                    'CALC1.BDCODCENTRO, ' ||
                    'CALC1.BDCODTPCC, ' ||
                    'CALC1.BDVALGPS, ' ||
                    'CALC1.BDVALRAT, ' ||
                    'CALC1.BDVALRATAPO, ' ||
                    'CALC1.BDVALFPASTERCEIROS, ' ||
                    'CALC1.BDORDEMVER ' ||
               'FROM (';
    end
  else
    begin
       wSql = 'SELECT COLCAD.BDCODEMP,' ||
                    ' COLCAD.BDCODCOL,' ||
                    ' COLCAD.BDNOMCOL,' ||
                    ' TPCC.BDCODTPCC, ' ||
                    ' TPCC.BDNOMCTA,' ||
                    ' CARGO.BDDESCTFUC,' ||
                    ' CALCDIA.BDSALBASECOL,' ||
                    ' COLCON.BDDATAADMCOL, ';
    end

  --condi??o para nomes dos campos de verbas
  IF (PRMODELO = 1) THEN --calculos
    BEGIN
      wSql = wSql ||
             'select calc.bdcodemp, ' ||
                    'calc.bdcodcol, ' ||
                    'calc.bdref, ' ||
                    'verba.bdtiporefver, ' ||
                    'CASE ' ||
                     ' WHEN CALC.BDORDEMVER = 1 THEN VERBA.BDDESCVER ' ||
                     ' ELSE LAN.BDCOMPL ' ||
                    'END AS BDDESCVER,' ||
                    'CALC.BDCODVER, ' ||
                    'verba.bdtipocodver bdtipocodver, ' ||
                    IIF(prtipofolha in (1,7), 'calc.BDREFV ', 'verba.bdrefver') || ' bdrefv,  ' ||
                    'CALC.BDVALV, ';
    END
  ELSE  --provis?es
    BEGIN
      wSql = wSql ||
             ' CALC1.BDLINHA , ' ||
             ' CALC1.BDREF, ' ||
             ' CALC1.' || IIF(PRMODELO = 3, 'BDFERIAS, CALC1.BDUMTERCO', 'BD13SAL') || ', ' ||
             ' CALC1.BDFGTS, ' ||
             ' CALC1.BDINSS, ' ||
             ' CALC1.BDFPAS, ' ||
             ' CALC1.BDCNAE, ' ||
             ' CALC1.BDRATAPO, ' ||
             ' CALC1.BDPIS, ';
    END

  --resto dos campos
  if (prmodelo = 1) then
    begin
      wSql = wSql || 'PLADEB.BDCODTPLA BDCODTPLADEB, ' ||
                     'PLADEB.BDCTALON BDCTALONDEB, ' ||
                     'PLADEB.BDNOMCTA BDNOMCTADEB, ' ||
                     'PLACRE.BDCODTPLA BDCODTPLACRE, ' ||
                     'PLACRE.BDCTALON BDCTALONCRE, ' ||
                     'PLACRE.BDNOMCTA BDNOMCTACRE, ' ||
                     'cc.bdcodcentro bdcodcentro, ' ||
                     'cc.bdcodtpcc bdcodtpcc, ' ||
                     'NULL AS BDVALGPS, ' ||
                     'NULL AS BDVALRAT, ' ||
                     'NULL AS BDVALRATAPO, ' ||
                     'NULL AS BDVALFPASTERCEIROS, ' ||
                     'CALC.BDORDEMVER ' ||
                     'FROM ';
    end
  else
    begin
        wSql = wSql || 'PLADEB.BDCODTPLA BDCODTPLADEB, ' ||
                       'PLADEB.BDCTALON BDCTALONDEB, ' ||
                       'PLADEB.BDNOMCTA BDNOMCTADEB, ' ||
                       'PLACRE.BDCODTPLA BDCODTPLACRE, ' ||
                       'PLACRE.BDCTALON BDCTALONCRE, ' ||
                       'PLACRE.BDNOMCTA BDNOMCTACRE, ' ||
                       'LAN.BDVALOR ' ||
                       'FROM ';
    end

  IF (PRMODELO = 1) THEN --calculos
    BEGIN
      IF (NOT PRTIPOFOLHA IN (1, 7)) THEN --demais calculos
        BEGIN
          wSql = wSql || wJoinTabelaCalcVerba;
        END
      ELSE --folha normal e folha complementar
        BEGIN
          IF ((PRCODCOL <> '') OR (PRCODCOL IS NOT NULL))  THEN
            WCODCOLAUX = REPLACE(PRCODCOL, 'CALC.', '');

          IF (PRTIPOFOLHA = 1) THEN
            BEGIN
              wCalcFN  = 'VRHF_EMP_TFOLHANORMAL';
              wCalcFT  = 'VRHF_EMP_TFOLHATOMADOR';
              wCalcFI  = 'VRHF_EMP_TFOLHAINT';
              wcalcFTI = 'VRHF_EMP_TFOLHATOMINT';
      
              wVerbaFN  = 'VRHF_EMP_TVERBAFN';
              wVerbaFT  = 'VRHF_EMP_TVERBATOMADOR';
              wVerbaFI  = 'VRHF_EMP_TVERBAINT';
              wVerbaFTI = 'VRHF_EMP_TVERBATOMINT';
      
              wTolFN  = 'TOL_VRHF_EMP_TVERBA_FN';
              wTolFT  = 'TOL_VRHF_EMP_TVERBA_FT';
              wTolFI  = 'TOL_VRHF_EMP_TVERBA_INT';
              wTolFTI = 'TOL_VRHF_EMP_TVERBA_TOMINT';

              wTolCalcfn = 'TOL_VRHF_EMP_TCALC_FN';
              wTolCalcft = 'TOL_VRHF_EMP_TCALC_FT';
              wTolCalcfi = 'TOL_VRHF_EMP_TCALC_INT';
              wTolCalcfti = 'TOL_VRHF_EMP_TCALC_TOMINT';

              WTOLFGTSFN = 'TOL_VRHF_EMP_TFGTS_FN';
              WTOLFGTSFT = 'TOL_VRHF_EMP_TFGTS_FT';
              WTOLFGTSFI = 'TOL_VRHF_EMP_TFGTS_INT';
              WTOLFGTSFTI = 'TOL_VRHF_EMP_TFGTS_TOMINT';
            END
          ELSE IF (PRTIPOFOLHA = 7) THEN
            BEGIN
              wCalcFN  = 'VRHF_EMP_TFOLHACOMP';
              wCalcFT  = 'VRHF_EMP_TFOLTOMCOMP';
              wCalcFI  = 'VRHF_EMP_TFOLHACOMPINT';
              wcalcFTI = 'VRHF_EMP_TFOLTOMCOMPINT';
      
              wVerbaFN  = 'VRHF_EMP_TVERBAFC';
              wVerbaFT  = 'VRHF_EMP_TVERBAFCTOMADOR';
              wVerbaFI  = 'VRHF_EMP_TVERBAFCINT';
              wVerbaFTI = 'VRHF_EMP_TVERBAFCTOMINT';
      
              wTolFN  = 'TOL_VRHF_EMP_TVERBA_FN_FC';
              wTolFT  = 'TOL_VRHF_EMP_TVERBA_FT_FC';
              wTolFI  = 'TOL_VRHF_EMP_TVERBA_FCINT';
              wTolFTI = 'TOL_VRHF_EMP_TVERBA_FT_FC_INT';

              wTolCalcfn = 'TOL_VRHF_EMP_TCALC_FN_FC';
              wTolCalcft = 'TOL_VRHF_EMP_TCALC_FT_FC';
              wTolCalcfi = 'TOL_VRHF_EMP_TCALC_FN_FC_INT';
              wTolCalcfti = 'TOL_VRHF_EMP_TCALC_FT_FC_INT';

              WTOLFGTSFN = 'TOL_VRHF_EMP_TFGTS_FC';
              WTOLFGTSFT = 'TOL_VRHF_EMP_TFGTS_FT_FC';
              WTOLFGTSFI = 'TOL_VRHF_EMP_TFGTS_FC_INT';
              WTOLFGTSFTI = 'TOL_VRHF_EMP_TFGTS_FT_FC_INT';
            END


        --subselect com union all para folha normal e complementar - normal, tomadores, intermitentes e tomadores intermitentes

        --folha normal/folha complementar
        --verbas
        wSql = wSql || '( SELECT FN.BDCODEMP, ' ||
                  'FN.BDCODCOL, ' ||
                  'FN.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFFN') || ' BDREF, ' ||
                  'VERBAFN.BDCODVER, ' ||
                  'VERBAFN.BDREFV' || IIF(PRTIPOFOLHA = 1, 'FN', 'FC') || ' BDREFV, ' ||
                  'VERBAFN.BDVALV' || IIF(PRTIPOFOLHA = 1, 'FN', 'FC') || ' BDVALV, ' ||
                  'TOLFN.BDCHAVE, ' ||
                  'TOLFN.BDCODEMPSUC, ' ||
                  '0 as BDORDEM, ' ||
                  '1 AS BDORDEMVER ' ||
            ' FROM ' || wCalcFN || ' FN ' ||
            ' LEFT JOIN ' || wVerbaFN || ' VERBAFN ON (FN.BDCODEMP = VERBAFN.BDCODEMP ' ||
                                                      ' AND FN.BDCODCOL = VERBAFN.BDCODCOL  ' ||
                                                      ' AND FN.BDREFFN = VERBAFN.BDREFFN ' ||
                                                      IIF(PRTIPOFOLHA = 7, 'AND FN.BDREFFC = VERBAFN.BDREFFC)', ') ') ||
            ' LEFT JOIN ' || wTolFN || ' TOLFN ON (VERBAFN.BDCODVER = TOLFN.BDCODVER ' ||
                                                 ' AND VERBAFN.BDCODEMP = TOLFN.BDCODEMP ' ||
                                                 ' AND VERBAFN.BDCODCOL = TOLFN.BDCODCOL ' ||
                                                 ' AND VERBAFN.BDREFFN = TOLFN.BDREFFN ' ||
                                                 IIF(PRTIPOFOLHA = 7, 'AND VERBAFN.BDREFFC = TOLFN.BDREFFC)', ') ') ||
            ' WHERE ' || REPLACE(PRCODEMP, 'BDCODEMP', 'FN.BDCODEMP') ||
            IIF(WCODCOLAUX = '', '', ' AND FN.' || WCODCOLAUX || ' ') ||
            '   AND FN.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFFN') || ' = ' || WCOMPETENCIA ||
          ' UNION ALL ' ||
          --fgts
          'SELECT FN.BDCODEMP, ' ||
                  'FN.BDCODCOL, ' ||
                  'FN.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFFN') || ' BDREF, ' ||
                  '-1 BDCODVER, ' ||
                  '0 BDREFV, ' ||
                  --'FN.BDFGTS' || IIF(PRTIPOFOLHA = 1, 'FN', 'FC') || ' BDVALV, ' ||
                  'LAN.BDVALOR BDVALV, ' ||
                  'TOLFN.BDCHAVE, ' ||
                  'TOLFN.BDCODEMPSUC, ' ||
                  '0 as BDORDEM, ' ||
                  '2 AS BDORDEMVER ' ||
            ' FROM ' || wCalcFN || ' FN ' ||
            ' JOIN ' || WTOLFGTSFN || ' TOLFN ON (FN.BDCODEMP = TOLFN.BDCODEMP ' ||
                                                     ' AND FN.BDCODCOL = TOLFN.BDCODCOL ' ||
                                                     ' AND FN.BDREFFN = TOLFN.BDREFFN ' ||
                                                 IIF(PRTIPOFOLHA = 7, 'AND FN.BDREFFC = TOLFN.BDREFFC)', ') ') ||
            ' LEFT JOIN VSUC_EMPRESAS_TLAN LAN ON (TOLFN.BDCODEMPSUC = LAN.BDCODEMP ' ||
                                                 ' AND TOLFN.BDCHAVE = LAN.BDCHAVE) ' ||
            ' WHERE ' || REPLACE(PRCODEMP, 'BDCODEMP', 'FN.BDCODEMP') ||
            IIF(WCODCOLAUX = '', '', ' AND FN.' || WCODCOLAUX || ' ') ||
            '   AND FN.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFFN') || ' = ' || WCOMPETENCIA ||
         ' UNION ALL ' ||
         --liquido
         'SELECT FN.BDCODEMP, ' ||
                  'FN.BDCODCOL, ' ||
                  'FN.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFFN') || ' BDREF, ' ||
                  '-1 BDCODVER, ' ||
                  '0 BDREFV, ' ||
                  'FN.BDLIQUIDO BDVALV, ' ||
                  'TOLFN.BDCHAVE, ' ||
                  'TOLFN.BDCODEMPSUC, ' ||
                  '0 as BDORDEM, ' ||
                  '2 AS BDORDEMVER ' ||
            ' FROM ' || wCalcFN || ' FN ' ||
            ' JOIN ' || wtolcalcfn || ' TOLFN ON (FN.BDCODEMP = TOLFN.BDCODEMP ' ||
                                                     ' AND FN.BDCODCOL = TOLFN.BDCODCOL ' ||
                                                     ' AND FN.BDREFFN = TOLFN.BDREFFN ' ||
                                                 IIF(PRTIPOFOLHA = 7, 'AND FN.BDREFFC = TOLFN.BDREFFC)', ') ') ||
            ' WHERE ' || REPLACE(PRCODEMP, 'BDCODEMP', 'FN.BDCODEMP') ||
            IIF(WCODCOLAUX = '', '', ' AND FN.' || WCODCOLAUX || ' ') ||
            '   AND FN.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFFN') || ' = ' || WCOMPETENCIA ||
          ' UNION ALL ' ||

          --folha tomador/folha tomador complementar
          --verbas
          'SELECT FT.BDCODEMP, ' ||
                ' FT.BDCODCOL, ' ||
                ' FT.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFTOMADOR') || ' BDREF, ' ||
                ' VERBAFT.BDCODVER, ' ||
                ' VERBAFT.BDREFV' || IIF(PRTIPOFOLHA = 1, 'FT', 'FC') || ' BDREFV, ' ||
                ' VERBAFT.BDVALV' || IIF(PRTIPOFOLHA = 1, 'FT', 'FC') || ' BDVALV, ' ||
                ' TOLFT.BDCHAVE, ' ||
                ' TOLFT.BDCODEMPSUC, ' ||
                ' FT.BDORDEM, ' ||
                ' 1 AS BDORDEMVER ' ||
          ' FROM ' || wCalcFT || ' FT ' ||
          ' LEFT JOIN ' || wVerbaFT || ' VERBAFT ON (FT.BDCODEMP = VERBAFT.BDCODEMP ' ||
                                                   ' AND FT.BDCODCOL = VERBAFT.BDCODCOL ' ||
                                                   ' AND FT.BDORDEM = VERBAFT.BDORDEM ' ||
                                                   ' AND FT.BDREFTOMADOR = VERBAFT.BDREFTOMADOR ' ||
          IIF(PRTIPOFOLHA = 7, 'AND FT.BDREFFC = VERBAFT.BDREFFC)', ') ') ||
          ' LEFT JOIN ' || wTolFT || ' TOLFT ON (VERBAFT.BDCODEMP = TOLFT.BDCODEMP ' ||
                                             ' AND VERBAFT.BDCODCOL = TOLFT.BDCODCOL ' ||
                                             ' AND VERBAFT.BDORDEM = TOLFT.BDORDEM ' ||
                                             ' AND VERBAFT.BDREFTOMADOR = TOLFT.BDREFTOMADOR ' ||
                                             ' AND VERBAFT.BDCODVER = TOLFT.BDCODVER ' ||
                         IIF(PRTIPOFOLHA = 7, 'AND VERBAFT.BDREFFC = TOLFT.BDREFFC)', ') ') ||
          '  WHERE ' || REPLACE(PRCODEMP, 'BDCODEMP', 'FT.BDCODEMP') ||
          IIF(WCODCOLAUX = '', '', ' AND FT.' || WCODCOLAUX || ' ') ||
          '    AND FT.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFTOMADOR') || ' = ' || WCOMPETENCIA ||
          ' UNION ALL ' ||
          --fgts
          'SELECT FT.BDCODEMP, ' ||
                ' FT.BDCODCOL, ' ||
                ' FT.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFTOMADOR') || ' BDREF, ' ||
                ' -1 BDCODVER, ' ||
                ' 0 BDREFV, ' ||
                --' FT.BDFGTS' || IIF(PRTIPOFOLHA = 1, 'FT', 'FC') || ' BDVALV, ' ||
                ' LAN.BDVALOR BDVALV, ' ||
                ' TOLFT.BDCHAVE, ' ||
                ' TOLFT.BDCODEMPSUC, ' ||
                ' FT.BDORDEM, ' ||
                ' 2 AS BDORDEMVER ' ||
          ' FROM ' || wCalcFT || ' FT ' ||
          ' JOIN ' || wtolfgtsft || ' TOLFT ON (FT.BDCODEMP = TOLFT.BDCODEMP ' ||
                                             ' AND FT.BDCODCOL = TOLFT.BDCODCOL ' ||
                                             ' AND FT.BDORDEM = TOLFT.BDORDEM ' ||
                                             ' AND FT.BDREFTOMADOR = TOLFT.BDREFTOMADOR ' ||
                         IIF(PRTIPOFOLHA = 7, 'AND FT.BDREFFC = TOLFT.BDREFFC)', ') ') ||
          ' LEFT JOIN VSUC_EMPRESAS_TLAN LAN ON (TOLFT.BDCODEMPSUC = LAN.BDCODEMP ' ||
                                                 ' AND TOLFT.BDCHAVE = LAN.BDCHAVE) ' ||
          '  WHERE ' || REPLACE(PRCODEMP, 'BDCODEMP', 'FT.BDCODEMP') ||
          IIF(WCODCOLAUX = '', '', ' AND FT.' || WCODCOLAUX || ' ') ||
          '    AND FT.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFTOMADOR') || ' = ' || WCOMPETENCIA ||
          ' UNION ALL ' ||
          --liquido
          'SELECT FT.BDCODEMP, ' ||
                ' FT.BDCODCOL, ' ||
                ' FT.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFTOMADOR') || ' BDREF, ' ||
                ' -1 BDCODVER, ' ||
                ' 0 BDREFV, ' ||
                ' FT.BDLIQUIDO as BDVALV, ' ||
                ' TOLFT.BDCHAVE, ' ||
                ' TOLFT.BDCODEMPSUC, ' ||
                ' FT.BDORDEM, ' ||
                ' 2 AS BDORDEMVER ' ||
          ' FROM ' || wCalcFT || ' FT ' ||
          ' JOIN ' || wtolcalcft || ' TOLFT ON (FT.BDCODEMP = TOLFT.BDCODEMP ' ||
                                             ' AND FT.BDCODCOL = TOLFT.BDCODCOL ' ||
                                             ' AND FT.BDORDEM = TOLFT.BDORDEM ' ||
                                             ' AND FT.BDREFTOMADOR = TOLFT.BDREFTOMADOR ' ||
                         IIF(PRTIPOFOLHA = 7, 'AND FT.BDREFFC = TOLFT.BDREFFC)', ') ') ||
          '  WHERE ' || REPLACE(PRCODEMP, 'BDCODEMP', 'FT.BDCODEMP') ||
          IIF(WCODCOLAUX = '', '', ' AND FT.' || WCODCOLAUX || ' ') ||
          '    AND FT.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFTOMADOR') || ' = ' || WCOMPETENCIA ||
          ' UNION ALL ' ||

          --folha intermitente/intermitente complementar
          --verbas
          'SELECT FI.BDCODEMP, ' ||
                 'FI.BDCODCOL, ' ||
                 'FI.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFFN') || ' BDREF, ' ||
                 'VERBAFI.BDCODVER, ' ||
                 'VERBAFI.BDREFV' || IIF(PRTIPOFOLHA = 1, 'FN', 'FC') || ' BDREFV, ' ||
                 'VERBAFI.BDVALV' || IIF(PRTIPOFOLHA = 1, 'FN', 'FC') || ' BDVALV, ' ||
                 'TOLFI.BDCHAVE, ' ||
                 'TOLFI.BDCODEMPSUC, ' ||
                 '0 as BDORDEM, ' ||
                 '1 AS BDORDEMVER ' ||
          '  FROM ' || wCalcFI || ' FI ' ||
          '  LEFT JOIN ' || wVerbaFI || ' VERBAFI ON (FI.BDCODEMP = VERBAFI.BDCODEMP ' ||
                                                    ' AND FI.BDCODCOL = VERBAFI.BDCODCOL ' ||
                                                    ' AND FI.BDCODCONTTI = VERBAFI.BDCODCONTTI ' ||
                                                    ' AND FI.BDREFFN = VERBAFI.BDREFFN ' ||
                                IIF(PRTIPOFOLHA = 7, 'AND FI.BDREFFC = VERBAFI.BDREFFC)', ') ') ||
          '  LEFT JOIN ' || wTolFI || ' TOLFI ON (VERBAFI.BDCODEMP = TOLFI.BDCODEMP ' ||
                                              ' AND VERBAFI.BDCODCOL = TOLFI.BDCODCOL ' ||
                                              ' AND VERBAFI.BDCODCONTTI = TOLFI.BDCODCONTTI ' ||
                                              ' AND VERBAFI.BDREFFN = TOLFI.BDREFFN ' ||
                                              ' AND VERBAFI.BDCODVER = TOLFI.BDCODVER ' ||
                         IIF(PRTIPOFOLHA = 7, ' AND VERBAFI.BDREFFC = TOLFI.BDREFFC)', ') ') ||
          ' WHERE ' || REPLACE(PRCODEMP, 'BDCODEMP', 'FI.BDCODEMP') ||
          IIF(WCODCOLAUX = '', '', ' AND FI.' || WCODCOLAUX || ' ') ||
          '  AND FI.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFFN') || ' = ' || WCOMPETENCIA ||
          ' UNION ALL ' ||
          --fgts
          'SELECT FI.BDCODEMP, ' ||
                 'FI.BDCODCOL, ' ||
                 'FI.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFFN') || ' BDREF, ' ||
                 '-1 BDCODVER, ' ||
                 '0 BDREFV, ' ||
                 --'FI.BDFGTS' || IIF(PRTIPOFOLHA = 1, 'FN', 'FC') || ' BDVALV, ' ||
                 'LAN.BDVALOR BDVALV, ' ||
                 'TOLFI.BDCHAVE, ' ||
                 'TOLFI.BDCODEMPSUC, ' ||
                 '0 as BDORDEM, ' ||
                 '2 AS BDORDEMVER ' ||
          '  FROM ' || wCalcFI || ' FI ' ||
          '  JOIN ' || wtolfgtsfi || ' TOLFI ON (FI.BDCODEMP = TOLFI.BDCODEMP ' ||
                                              ' AND FI.BDCODCOL = TOLFI.BDCODCOL ' ||
                                              ' AND FI.BDCODCONTTI = TOLFI.BDCODCONTTI ' ||
                                              ' AND FI.BDREFFN = TOLFI.BDREFFN ' ||
                         IIF(PRTIPOFOLHA = 7, ' AND FI.BDREFFC = TOLFI.BDREFFC)', ') ') ||
          ' LEFT JOIN VSUC_EMPRESAS_TLAN LAN ON (TOLFI.BDCODEMPSUC = LAN.BDCODEMP ' ||
                                                 ' AND TOLFI.BDCHAVE = LAN.BDCHAVE) ' ||
          ' WHERE ' || REPLACE(PRCODEMP, 'BDCODEMP', 'FI.BDCODEMP') ||
          IIF(WCODCOLAUX = '', '', ' AND FI.' || WCODCOLAUX || ' ') ||
          '  AND FI.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFFN') || ' = ' || WCOMPETENCIA ||
          --liquido
          ' UNION ALL ' ||
           'SELECT FI.BDCODEMP, ' ||
                 'FI.BDCODCOL, ' ||
                 'FI.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFFN') || ' BDREF, ' ||
                 '-1 BDCODVER, ' ||
                 '0 BDREFV, ' ||
                 'FI.BDLIQUIDO AS BDVALV, ' ||
                 'TOLFI.BDCHAVE, ' ||
                 'TOLFI.BDCODEMPSUC, ' ||
                 '0 as BDORDEM, ' ||
                 '2 AS BDORDEMVER ' ||
          '  FROM ' || wCalcFI || ' FI ' ||
          '  JOIN ' || wtolcalcfi || ' TOLFI ON (FI.BDCODEMP = TOLFI.BDCODEMP ' ||
                                              ' AND FI.BDCODCOL = TOLFI.BDCODCOL ' ||
                                              ' AND FI.BDCODCONTTI = TOLFI.BDCODCONTTI ' ||
                                              ' AND FI.BDREFFN = TOLFI.BDREFFN ' ||
                         IIF(PRTIPOFOLHA = 7, ' AND FI.BDREFFC = TOLFI.BDREFFC)', ') ') ||
          ' WHERE ' || REPLACE(PRCODEMP, 'BDCODEMP', 'FI.BDCODEMP') ||
          IIF(WCODCOLAUX = '', '', ' AND FI.' || WCODCOLAUX || ' ') ||
          '  AND FI.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFFN') || ' = ' || WCOMPETENCIA ||
          ' UNION ALL ' ||

          --folha tomador intermitente/tomador intermitente complementar
          --verbas
          'SELECT FTI.BDCODEMP, ' ||
                 'FTI.BDCODCOL, ' ||
                 'FTI.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFTOMADOR') || ' BDREF, ' ||
                 'VERBAFTI.BDCODVER, ' ||
                 'VERBAFTI.BDREFV' || IIF(PRTIPOFOLHA = 1, 'FT', 'FC') || ' BDREFV, ' ||
                 'VERBAFTI.BDVALV' || IIF(PRTIPOFOLHA = 1, 'FT', 'FC') || ' BDVALV, ' ||
                 'TOLFTI.BDCHAVE, ' ||
                 'TOLFTI.BDCODEMPSUC, ' ||
                 'FTI.BDORDEM, ' ||
                 '1 AS BDORDEMVER ' ||
          'FROM ' || wcalcFTI || ' FTI ' ||
          'LEFT JOIN ' || wVerbaFTI || ' VERBAFTI ON (FTI.BDCODEMP = VERBAFTI.BDCODEMP ' ||
                                                     'AND FTI.BDCODCOL = VERBAFTI.BDCODCOL ' ||
                                                     'AND FTI.BDCODCONTTI = VERBAFTI.BDCODCONTTI ' ||
                                                     'AND FTI.BDORDEM = VERBAFTI.BDORDEM ' ||
                                                     'and fti.BDREFTOMADOR = VERBAFTI.BDREFTOMADOR ' ||
          IIF(PRTIPOFOLHA = 7, ' AND FTI.BDREFFC = VERBAFTI.BDREFFC)', ') ') ||
          'LEFT JOIN ' || wTolFTI || ' TOLFTI ON (VERBAFTI.BDCODEMP = TOLFTI.BDCODEMP ' ||
                                                 'AND VERBAFTI.BDCODCOL = TOLFTI.BDCODCOL ' ||
                                                 'AND VERBAFTI.BDCODCONTTI = TOLFTI.BDCODCONTTI ' ||
                                                 'AND VERBAFTI.BDCODVER = TOLFTI.BDCODVER ' ||
                                                 'and VERBAFTI.BDORDEM = TOLFTI.BDORDEM ' ||
                                                 'and VERBAFTI.BDREFTOMADOR = TOLFTI.BDREFTOMADOR '||
                           IIF(PRTIPOFOLHA = 7, ' AND VERBAFTI.BDREFFC = TOLFTI.BDREFFC)', ') ') ||
          'WHERE  ' || REPLACE(PRCODEMP, 'BDCODEMP', 'fti.BDCODEMP') ||
          IIF(WCODCOLAUX = '', '', ' AND FTI.' || WCODCOLAUX || ' ') ||
          'AND FTI.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFTOMADOR') || ' = ' || WCOMPETENCIA ||
          ' UNION ALL ' ||
          --fgts
          'SELECT FTI.BDCODEMP, ' ||
                 'FTI.BDCODCOL, ' ||
                 'FTI.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFTOMADOR') || ' BDREF, ' ||
                 '-1 BDCODVER, ' ||
                 '0 BDREFV, ' ||
                 --'FTI.BDFGTS' || IIF(PRTIPOFOLHA = 1, 'FT', 'FC') || ' BDVALV, ' ||
                 'LAN.BDVALOR BDVALV, ' ||
                 'TOLFTI.BDCHAVE, ' ||
                 'TOLFTI.BDCODEMPSUC, ' ||
                 'FTI.BDORDEM, ' ||
                 '2 AS BDORDEMVER ' ||
          'FROM ' || wcalcFTI || ' FTI ' ||
          'JOIN ' || wtolfgtsfti || ' TOLFTI ON (FTI.BDCODEMP = TOLFTI.BDCODEMP ' ||
                                                 'AND FTI.BDCODCOL = TOLFTI.BDCODCOL ' ||
                                                 'AND FTI.BDCODCONTTI = TOLFTI.BDCODCONTTI ' ||
                                                 'and FTI.BDORDEM = TOLFTI.BDORDEM ' ||
                                                 'and FTI.BDREFTOMADOR = TOLFTI.BDREFTOMADOR '||
                           IIF(PRTIPOFOLHA = 7, ' AND FTI.BDREFFC = TOLFTI.BDREFFC)', ') ') ||
          ' LEFT JOIN VSUC_EMPRESAS_TLAN LAN ON (TOLFTI.BDCODEMPSUC = LAN.BDCODEMP ' ||
                                                 ' AND TOLFTI.BDCHAVE = LAN.BDCHAVE) ' ||
          'WHERE  ' || REPLACE(PRCODEMP, 'BDCODEMP', 'fti.BDCODEMP') ||
          IIF(WCODCOLAUX = '', '', ' AND FTI.' || WCODCOLAUX || ' ') ||
          'AND FTI.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFTOMADOR') || ' = ' || WCOMPETENCIA ||
          ' UNION ALL ' ||
          --liquido
          'SELECT FTI.BDCODEMP, ' ||
                 'FTI.BDCODCOL, ' ||
                 'FTI.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFTOMADOR') || ' BDREF, ' ||
                 '-1 BDCODVER, ' ||
                 '0 BDREFV, ' ||
                 'FTI.BDLIQUIDO BDVALV, ' ||
                 'TOLFTI.BDCHAVE, ' ||
                 'TOLFTI.BDCODEMPSUC, ' ||
                 'FTI.BDORDEM, ' ||
                 '2 AS BDORDEMVER ' ||
          'FROM ' || wcalcFTI || ' FTI ' ||
          'JOIN ' || wtolcalcfti || ' TOLFTI ON (FTI.BDCODEMP = TOLFTI.BDCODEMP ' ||
                                                 'AND FTI.BDCODCOL = TOLFTI.BDCODCOL ' ||
                                                 'AND FTI.BDCODCONTTI = TOLFTI.BDCODCONTTI ' ||
                                                 'and FTI.BDORDEM = TOLFTI.BDORDEM ' ||
                                                 'and FTI.BDREFTOMADOR = TOLFTI.BDREFTOMADOR '||
                           IIF(PRTIPOFOLHA = 7, ' AND FTI.BDREFFC = TOLFTI.BDREFFC)', ') ') ||
          'WHERE  ' || REPLACE(PRCODEMP, 'BDCODEMP', 'fti.BDCODEMP') ||
          IIF(WCODCOLAUX = '', '', ' AND FTI.' || WCODCOLAUX || ' ') ||
          'AND FTI.' || IIF(PRTIPOFOLHA = 7, 'BDREFCOMP', 'BDREFTOMADOR') || ' = ' || WCOMPETENCIA ||
          ' ) CALC ' ||
          --fim do subselect
          ' LEFT JOIN VW_TVERBAS_REF VERBA ON (' || IIF(PRTIPOFOLHA IN (1,7), 'CALC', 'VERBAAUX') || '.BDCODVER = VERBA.BDCODVER) ' ||
          'LEFT OUTER JOIN VRHF_EMP_TPREPFN CC ON (CC.BDCODEMP = CALC.BDCODEMP ' ||
                                                 ' AND CC.BDCODCOL = CALC.BDCODCOL ' ||
                                                 ' AND CC.BDORDEM = CALC.' || IIF(NOT PRMODELO = 1, 'BDCODHIST', 'BDORDEM') || ') ' ||
           'LEFT JOIN VSUC_EMPRESAS_TLAN LAN ON (LAN.BDCODEMP = ' || IIF(((PRMODELO <> 1) OR (PRTIPOFOLHA IN (1,7))), 'CALC', 'TOL') || '.BDCODEMPSUC ' ||
                                               ' AND LAN.BDCHAVE = ' || IIF(((PRMODELO <> 1) OR (PRTIPOFOLHA IN (1,7))), 'CALC', 'TOL') || '.BDCHAVE) ' ||
          'LEFT JOIN PLANOS_TPLA PLADEB ON (PLADEB.BDCODPLAPADRAO = LAN.BDCODPLAPADRAO ' ||
                                           'AND PLADEB.BDCODTPLA = LAN.BDDEBITO) ' ||
          'LEFT JOIN PLANOS_TPLA PLACRE ON (PLACRE.BDCODPLAPADRAO = LAN.BDCODPLAPADRAO ' ||
                                           'AND PLACRE.BDCODTPLA = LAN.BDCREDITO) '||
          ' WHERE CALC.' || WCAMPOFILTROREF || ' = ' || CAST(PRCOMPETENCIA AS VARCHAR(6)) || replace(wWhere, 'CALC1', 'CALC') ||
          ' UNION ALL ' || wSqlImpostos;
        END
    END
  ELSE
    BEGIN --provis?es
      wSql = wSql || '( ' || wJoinProv || ') CALC1 ';
    END

  wSql = wSql ||
   ' LEFT JOIN VW_VRH_EMP_TCOLCON_CAD COLCAD ON (CALC1.BDCODEMP = COLCAD.BDCODEMP ' ||
                                              ' AND CALC1.BDCODCOL = COLCAD.BDCODCOL)' ||
   'JOIN VRH_EMP_TCOLCON COLCON ON (COLCAD.BDCODEMP = COLCON.BDCODEMP ' ||
                                  ' AND COLCAD.BDCODCOL = COLCON.BDCODCOL) ' ||
   'LEFT JOIN VW_VRH_EMP_TCOL_VINCDIA VINCDIA ON (COLCAD.BDCODEMP = VINCDIA.BDCODEMP ' ||
                                             ' AND COLCAD.BDCODCOL = VINCDIA.BDCODCOL) ' ||

   'left join(select BDCODEMP, BDCODCOL, BDDATACOL, max(BDDATAEFEITO)BDDATAEFEITO' ||
   '       from VRH_EMP_TCOLCON_CALCDIA  ' ||
   '       group by BDCODEMP, BDCODCOL, BDDATACOL) CALCMAX on (VINCDIA.BDCODEMP = CALCMAX.BDCODEMP and ' ||
   '  VINCDIA.BDCODCOL = CALCMAX.BDCODCOL and ' ||
   '   VINCDIA.BDDATACOL = CALCMAX.BDDATACOL) ' ||
   'LEFT JOIN VRH_EMP_TCOLCON_CALCDIA CALCDIA ON (CALCMAX.BDCODEMP = CALCDIA.BDCODEMP ' ||
                                                ' AND CALCMAX.BDCODCOL = CALCDIA.BDCODCOL ' ||
                                                ' AND CALCMAX.BDDATACOL = CALCDIA.BDDATACOL AND CALCMAX.BDDATAEFEITO = CALCDIA.BDDATAEFEITO) ' ||
   'LEFT JOIN VRH_FUNCOES_TFUC CARGO ON (VINCDIA.BDCODPLAFUC = CARGO.BDCODPLAFUC ' ||
                                       ' AND VINCDIA.BDCODTFUC = CARGO.BDCODTFUC) ';

   if (prmodelo <> 1) then
     begin
       wSql = wSql || 'LEFT JOIN VSUC_EMPRESAS_TLAN LAN ON (LAN.BDCODEMP = CALC1.BDCODEMPSUC ' ||
                                                         ' AND LAN.BDCHAVE = CALC1.BDCHAVE) ' ||
                     'LEFT JOIN PLANOS_TPLA PLADEB ON (PLADEB.BDCODPLAPADRAO = LAN.BDCODPLAPADRAO ' ||
                                                    ' AND PLADEB.BDCODTPLA = LAN.BDDEBITO) ' ||
                     'LEFT JOIN PLANOS_TPLA PLACRE ON (PLACRE.BDCODPLAPADRAO = LAN.BDCODPLAPADRAO ' ||
                                                     ' AND PLACRE.BDCODTPLA = LAN.BDCREDITO) ' ||
                     'LEFT JOIN VSUC_EMPRESAS_TLCC TLCC ON (LAN.BDCODEMP = TLCC.BDCODEMP ' ||
                                                        'AND LAN.BDCHAVE = TLCC.BDCHAVE) ' ||
                     'LEFT JOIN CENTROS_TPCC TPCC ON (TPCC.BDCODCENTRO = TLCC.BDCODCENTRO ' ||
                                                    ' AND TPCC.BDCODTPCC = TLCC.BDCODTPCC) ';
     end
   else
     wSql = wSql || 'LEFT JOIN CENTROS_TPCC TPCC ON (TPCC.BDCODCENTRO = CALC1.BDCODCENTRO ' ||
                                   ' AND TPCC.BDCODTPCC = CALC1.BDCODTPCC) ';

   wSql = wSql ||
   'LEFT JOIN VW_VRH_EMP_TCOLCON_REF REF ON (COLCON.BDCODEMP = REF.BDCODEMP ' ||
                                           ' AND COLCON.BDCODCOL = REF.BDCODCOL) ' ||
   'LEFT JOIN VRH_EMP_TCOL_VINC VINC ON (REF.BDCODCOL = VINC.BDCODCOL ' ||
                                       ' AND REF.BDCODEMP = VINC.BDCODEMP ' ||
                                       ' AND REF.BDREFCOL = VINC.BDREFCOL) ' ||
   'LEFT JOIN VRH_EMP_TCOLCON_VINC REF1 ON (REF.BDCODCOL = REF1.BDCODCOL ' ||
                                          ' AND REF.BDCODEMP = REF1.BDCODEMP ' ||
                                          ' AND REF.BDREFCOL = REF1.BDREFCOL) ';

  IF ((PRCODSINDICATO IS NOT NULL) AND (PRCODSINDICATO <> '')) THEN
    wWhere = wWhere || ' AND ' || REPLACE(PRCODSINDICATO,'BDCODSINTRAB', 'VINC.BDCODSINTRAB');

  IF ((PRCODCLASSE IS NOT NULL) AND (PRCODCLASSE <> '')) THEN
    wWhere = wWhere || ' AND ' || REPLACE(PRCODCLASSE, 'BDCODCLA', 'REF1.BDCODCLA');

  wWhere = ' WHERE CALC1.BDREF = ' || CAST(PRCOMPETENCIA AS VARCHAR(6)) || ' ' || wWhere;
  wOrderBy = ' ORDER BY BDCODEMP,BDCODCOL ' || iif(prmodelo <> 1, ',TPCC.BDCODTPCC,BDREF desc, BDPLANOCC, BDORDEMCC, BDLINHA', ',BDORDEMVER,TPCC.BDCODTPCC, BDTIPOCODVER,BDCODVER,BDDESCVER desc ');
  
  wSql = wSql || wWhere || wOrderBy;

  BDSQL = wSql;

  suspend;
end^

create or alter procedure SP_VRH_EXP_DADOS_DA_FOLHA (
    PRCODEMP varchar(2000),
    PRCODCOL varchar(2000),
    PRCODSINDICATO varchar(1000),
    PRCODCLASSE varchar(1000),
    PRCOMPETENCIA integer,
    PRMODELO integer,
    PRTIPOFOLHA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMECOL varchar(100),
    BDPERIODO varchar(10),
    BDFUNCAO varchar(100),
    BDCODTPCC integer,
    BDCENTROCUSTO varchar(100),
    BDSALBASE numeric(15,2),
    BDDTADM date,
    BDCODVERBA integer,
    BDDESCVERBA varchar(200),
    BDTIPOREFVER integer,
    BDREFV numeric(15,2),
    BDREFVERBA varchar(20),
    BDREFVERBA2 varchar(100),
    BDREFVERBAPROV varchar(100),
    BDVALOR numeric(15,2),
    BDCONTADEB varchar(100),
    BDCONTACRE varchar(100),
    BDMODELOREL integer,
    BDPBM integer,
    BDGPS integer,
    BDORDEMVER integer)
as
declare variable WSQL varchar(32000);
declare variable WCODCOLANT integer;
declare variable WCODTPLADEB integer;
declare variable WCTALONDEB varchar(100);
declare variable WNOMCTADEB varchar(100);
declare variable WCODTPLACRE integer;
declare variable WCTALONCRE varchar(100);
declare variable WNOMCTACRE varchar(100);
declare variable WREFP integer;
declare variable WFERIAS numeric(15,2);
declare variable WUMTERCO numeric(15,2);
declare variable W13SAL numeric(15,2);
declare variable WFGTS numeric(15,2);
declare variable WINSS numeric(15,2);
declare variable WFPAS numeric(15,2);
declare variable WCNAE numeric(15,2);
declare variable WRATAPO numeric(15,2);
declare variable WPIS numeric(15,2);
declare variable WLINHA integer;
declare variable WDESCLINHAPROVAUX varchar(100);
declare variable WDEBAUX varchar(100);
declare variable WCREDAUX varchar(100);
declare variable WANO integer;
declare variable WDIA integer;
declare variable WMES integer;
declare variable WULTDIACOMP date;
declare variable WCODCENTRO integer;
declare variable WCODTPCC integer;
declare variable WVALGPS numeric(15,2);
declare variable WVALRAT numeric(15,2);
declare variable WVALRATAPO numeric(15,2);
declare variable WVALFPAS numeric(15,2);
declare variable WCODTPCCCOL varchar(100);
declare variable WCODCOLAUX integer;
declare variable WCODTPCCAUX integer;
declare variable WCODEMPAUX integer;
declare variable WTEMCALC DM_BOOLEAN;
declare variable WDESCVERBAAUX varchar(100);
declare variable WVALORLANPROV numeric(15,2);
declare variable WQTDADECCGPS integer;
declare variable WQTDADECCPBM integer;
declare variable WNOMCTAFER DM_BOOLEAN;
declare variable WAFORCA DM_BOOLEAN; /* a força */
declare variable WDESCCENTROCUSTOAUX varchar(100);
declare variable wContaDebAux varchar(100);
declare variable wContaCreAux varchar(100);
BEGIN
  wSql = '';

  WCODCOLANT = 0;
  WCODTPLADEB = 0;
  WCTALONDEB = '';
  WNOMCTADEB = '';
  WCODTPLACRE = 0;
  WCTALONCRE = '';
  WNOMCTACRE = '';
  WREFP = 0;
  WFERIAS = 0;
  WUMTERCO = 0;
  W13SAL = 0;
  WFGTS = 0;
  WINSS = 0;
  WFPAS = 0;
  WCNAE = 0;
  WRATAPO = 0;
  WPIS = 0;
  WLINHA = 0;
  WDESCLINHAPROVAUX = '';
  WDEBAUX = '';
  WCREDAUX = '';
  WANO = 0;
  WDIA = 0;
  WMES = 0;
  WCODCENTRO = 0;
  WCODTPCC = 0;
  WVALGPS = 0;
  WVALRAT = 0;
  WVALRATAPO = 0;
  WVALFPAS = 0;
  WCODTPCCCOL = '';
  wcodcolaux = 0;
  wcodtpccaux = 0;
  WCODTPCCAUX = 0;
  WCODEMPAUX = 0;
  wTemCalc = 'FALSE';
  wDescVerbaAux = '';
  wValorLanProv = 0;
  bdPBM = 0;
  bdGPS = 0;
  wQtdadeCCGPS = 0;
  wQtdadeCCPBM = 0;
  wNomCtaFer = 'FALSE';
  wAForca = 'FALSE';
  wDescCentroCustoAux = '';
  wContaCreAux = '';
  wContaDebAux = '';

  if (prcodcol is null) then
    prcodcol = '';

  if (prcodsindicato is null) then
    prcodsindicato = '';

  if (prcodclasse is null) then
    prcodclasse = '';

  if (prcodsindicato is null) then
    prcodsindicato = '';

  wano = CAST(SUBSTRING(CAST(prcompetencia AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wmes = CAST(SUBSTRING(CAST(prcompetencia AS VARCHAR(6)) FROM 5 FOR 6) AS INTEGER);
  SELECT ultdia FROM ultimo_dia_mes(:wmes, :wano) INTO :wdia;

  WULTDIACOMP = cast(wmes || '/' || cast(wdia as varchar(2)) || '/'||wano as date);

  wSql = 'select bdSql from SP_VRH_EXP_DADOS_DA_FOLHA_SQL('''||prCodEmp||''','''||PRCODCOL||''','''||PRCODSINDICATO||''','''||PRCODCLASSE||''','||PRCOMPETENCIA||','||PRMODELO||','||PRTIPOFOLHA||')';

  execute statement wsql into :wSql;

  IF (prModelo = 1) THEN --folhas
    BEGIN
      FOR EXECUTE STATEMENT wSql INTO :BDCODEMP, :BDCODCOL, :BDNOMECOL, :BDCENTROCUSTO, :BDFUNCAO, :BDSALBASE, :BDDTADM,
                                      :BDTIPOREFVER, :BDDESCVERBA, :BDCODVERBA, :BDREFV, :BDVALOR, :wCODTPLADEB,
                                      :wCTALONDEB, :wNOMCTADEB, :wCODTPLACRE, :wCTALONCRE, :wNOMCTACRE, :wcodcentro, :BDCODTPCC,
                                      :wvalgps, :wvalrat, :wvalratapo, :wValFPAS, :BDORDEMVER
      DO
        BEGIN
          /*BDORDEMVER
            1 - verba
            2 - fgts/liquido
            3 - GPS*/

          BDPERIODO = cast(WULTDIACOMP as date);
          if (bdvalor is null) then
            bdValor = 0;

          if (wcodcolaux <> bdcodcol) then -- quando mudar de colaborador zerar a variável
            begin
            wcodtpcccol = '';
              wcodtpccaux =  0;
              wTemCalc = 'FALSE';
              wQtdadeCCGPS = 1;
              wQtdadeCCPBM = 1;
            end

          IF ((wCODTPLADEB > 0) OR (wCODTPLADEB IS NOT NULL)) THEN
            bdcontadeb = CAST(wCODTPLADEB AS VARCHAR(50)) || ' - ' || wCTALONDEB || ' - ' || wNOMCTADEB;
          ELSE
            bdcontadeb = '-';

          IF ((wCODTPLACRE > 0) OR (wCODTPLACRE IS NOT NULL)) THEN
            BDCONTACRE = CAST(wCODTPLACRE AS VARCHAR(50)) || ' - ' || wCTALONCRE || ' - ' || wNOMCTACRE;
          ELSE
            bdcontacre = '-';

          if (BDORDEMVER = 1) then --verba
            begin
              if (coalesce(wcodtpccaux, 0) <> coalesce(BDCODTPCC, 0)) then --verbas
                BEGIN
                  if (wcodtpcccol = '') then
                    wcodtpcccol = '\' || Trim(cast(BDCODTPCC as varchar(10))) || '\';
                  else if (position(cast(BDCODTPCC as varchar(10)), wcodtpcccol) = 0) then --se já tem o cc não adiciona novo
                    begin
                    wcodtpcccol = wcodtpcccol || ' - ' || cast(BDCODTPCC as varchar(10));
                      wQtdadeCCGPS = wQtdadeCCGPS + 1;
                      wQtdadeCCPBM = wQtdadeCCPBM + 1;
                    end
                END

              wcodempaux = bdcodemp;
              wcodcolaux = bdcodcol;
              wcodtpccaux = BDCODTPCC;
              wDescCentroCustoAux = BDCENTROCUSTO;
              wTemCalc = 'TRUE';
              suspend;
            end

          if (BDORDEMVER = 2) then --fgts/liquido
            begin
              BDCODVERBA = 0;
              if (position('COL', upper(BDDESCVERBA)) > 0) then
                BDDESCVERBA = SUBSTRING(BDDESCVERBA from 1 for (position('COL', upper(BDDESCVERBA))) - 1);
              if (BDVALOR > 0) then
              suspend;
            end

          if ((BDORDEMVER = 3) and (prtipofolha = 1)) then
            begin
              if ((position('FERIAS', upper(wNOMCTACRE)) > 0) or
                 (position('FÉRIAS', upper(wNOMCTACRE)) > 0) or
                 (position('FERIAS', upper(wNOMCTADEB)) > 0) or
                 (position('FÉRIAS', upper(wNOMCTADEB)) > 0) or
                 (position('13', upper(wNOMCTACRE)) > 0) or
                 (position('13', upper(wNOMCTADEB)) > 0))
              then
                wNomCtaFer = 'TRUE';
              else
                wNomCtaFer = 'FALSE';
            end


          if (((BDORDEMVER = 3) and (prtipofolha = 1) and (wTemCalc = 'TRUE')) and
             (wNomCtaFer = 'FALSE'))
          then -- imposto e é a linha de imposto correspondente a esse colaborador
                begin
              if ((position('\' || Trim(cast(BDCODTPCC as varchar(10))) || '\', wcodtpcccol) > 0) or  --verifica se o colaborador tem alocação nesse CC
                 ((BDCODTPCC is null) and (wcodtpcccol = '')))                                        --caso não tenha centro de custos
              then
                begin
                  BDDESCVERBA = Trim(REPLACE(upper(BDDESCVERBA), upper('líquido'), ''));
                  BDDESCVERBA = Trim(REPLACE(upper(BDDESCVERBA), upper('liquido'), ''));

                  if ((position('FOLHA NORMAL', upper(BDDESCVERBA)) > 0) and
                     ((wQtdadeCCGPS > 0) or (wQtdadeCCPBM > 0)))
                  then --folha normal
                   begin
                     if ((position('COLABORADORES', upper(BDDESCVERBA)) > 0) and (wvalgps > 0)) then
                       BDVALOR = wValGPS;
                     if ((position('EMPREGADORES', upper(BDDESCVERBA)) > 0) and (wvalgps > 0)) then
                       BDVALOR = wValGPS;
                     if ((position('AUTÔNOMOS', upper(BDDESCVERBA)) > 0) and (wvalgps > 0)) then
                       BDVALOR = wValGPS;  
                     if ((position('RAT', upper(BDDESCVERBA)) > 0) and (wvalrat > 0)) then
                       BDVALOR = wValRat;
                     if ((position('RAT APO', upper(BDDESCVERBA)) > 0) and (wvalratapo > 0)) then
                       BDVALOR = wValRatApo;  
                     if ((position('FPAS', upper(BDDESCVERBA)) > 0) and (wValFPAS > 0)) then
                       BDVALOR = wValFPAS;
                     if (BDVALOR > 0) then
                       suspend;

                     if ((position('GPS', upper(BDDESCVERBA)) > 0) and
                        (bdvalor = 0) and
                        ((wValGPS > 0) or (wvalrat > 0) or (wvalratapo > 0) or (wValFPAS > 0)) and
                        (wQtdadeCCGPS > 0))
                     then
                       begin
                         wContaCreAux = bdcontacre;
                         wContaDebAux = bdcontadeb;
                         wDescVerbaAux = BDDESCVERBA;
                         if (wValGPS > 0) then 
                           begin
                             bdValor = wValGPS;
                             bdGPS = 1;
                             suspend;
                             bdGPS = 0;
                   end

                         if (wvalrat > 0) then
                           begin
                             bdValor = wvalrat;
                             bdDescVerba = wDescVerbaAux || ' - RAT';
                             suspend;
               end

                         if (wvalratapo > 0) then
                           begin
                             bdValor = wvalratapo;
                             bdDescVerba = wDescVerbaAux || ' - RAT Aposentadoria';
                             suspend;
            end

                         if (wValFPAS > 0) then
            begin
                             bdValor = wValFPAS;
                             bdDescVerba = wDescVerbaAux || ' - FPAS/Terceiros';
                             suspend;
                           end

                         if (bdValor > 0) then
                           wQtdadeCCGPS = wQtdadeCCGPS - 1;
                       end
                     else
                     if ((position('PBM', upper(BDDESCVERBA)) > 0) and
                        (bdvalor = 0) and
                        (wQtdadeCCPBM > 0))
                     then
                       begin
                         bdPBM = 1;
                         BDDESCVERBA = 'GPS ' || iif(wmes < 10, '0', '') || cast(wmes as varchar(2)) || '/' || cast(wano as varchar(4)) || ' - FOLHA NORMAL (PBM)';
                         bdcontacre = wContaCreAux;
                         bdcontadeb = wContaDebAux;
                         suspend;
                         bdPBM = 0;
                         wQtdadeCCPBM = wQtdadeCCPBM -1;
                   end
               end
            end
            end

            if ((BDORDEMVER = 3) and (prtipofolha in (3,4,5)) and (wTemCalc = 'TRUE')) then -- imposto e é a linha de imposto correspondente a esse colaborador
                begin
              if ((position('\' || Trim(cast(BDCODTPCC as varchar(10))) || '\', wcodtpcccol) is null) and
                  ((BDCODTPCC is null) and (wcodtpcccol <> '')) and
                  ((wQtdadeCCGPS = 1) or (wQtdadeCCPBM = 1)))
              then
                wAForca = 'TRUE';
              else
                wAForca = 'FALSE';

              if (((position('\' || Trim(cast(BDCODTPCC as varchar(10))) || '\', wcodtpcccol) > 0) or
                 ((BDCODTPCC is null) and (wcodtpcccol = ''))) or (wAForca = 'TRUE')) /* and
                 (wEhPBM = 'FALSE'))                            */
              then
                begin
                  BDDESCVERBA = Trim(REPLACE(upper(BDDESCVERBA), upper('líquido'), ''));
                  BDDESCVERBA = Trim(REPLACE(upper(BDDESCVERBA), upper('liquido'), ''));

                  if ((position('13º', upper(BDDESCVERBA)) > 0) and
                     ((wQtdadeCCGPS > 0) or (wQtdadeCCPBM > 0)))
                  then
                   begin
                     if (wAForca = 'TRUE') then
                       begin
                         BDCODTPCC = wcodtpccaux;
                         BDCENTROCUSTO = wDescCentroCustoAux;
                       end

                     if ((position('COLABORADORES', upper(BDDESCVERBA)) > 0) and (wvalgps > 0)) then
                       BDVALOR = wValGPS;
                     if ((position('EMPREGADORES', upper(BDDESCVERBA)) > 0) and (wvalgps > 0)) then
                       BDVALOR = wValGPS;
                     if ((position('AUTÔNOMOS', upper(BDDESCVERBA)) > 0) and (wvalgps > 0)) then
                       BDVALOR = wValGPS;  
                     if ((position('RAT', upper(BDDESCVERBA)) > 0) and (wvalrat > 0)) then
                       BDVALOR = wValRat;
                     if ((position('RAT APO', upper(BDDESCVERBA)) > 0) and (wvalratapo > 0)) then
                       BDVALOR = wValRatApo;  
                     if ((position('FPAS', upper(BDDESCVERBA)) > 0) and (wValFPAS > 0)) then
                       BDVALOR = wValFPAS;
                     if (BDVALOR > 0) then
                       suspend;

                     if (((position('GPS', upper(BDDESCVERBA)) > 0) and
                        (bdvalor = 0) and
                        ((wValGPS > 0) or (wvalrat > 0) or (wvalratapo > 0) or (wValFPAS > 0))) and
                        (wQtdadeCCGPS > 0))
                     then
                       begin
                         wContaCreAux = bdcontacre;
                         wContaDebAux = bdcontadeb;
                         wDescVerbaAux = BDDESCVERBA;
                         if (wValGPS > 0) then 
                           begin
                             bdValor = wValGPS;
                             bdGPS = 1;
                             suspend;
                             bdGPS = 0;
                   end

                         if (wvalrat > 0) then
                           begin
                             bdValor = wvalrat;
                             bdDescVerba = wDescVerbaAux || ' - RAT';
                             suspend;
                end

                         if (wvalratapo > 0) then
                           begin
                             bdValor = wvalratapo;
                             bdDescVerba = wDescVerbaAux || ' - RAT Aposentadoria';
                             suspend;
            end

                         if (wValFPAS > 0) then
                           begin
                             bdValor = wValFPAS;
                             bdDescVerba = wDescVerbaAux || ' - FPAS/Terceiros';
                             suspend;
        end

                         if (bdValor > 0) then
                           wQtdadeCCGPS = wQtdadeCCGPS - 1;
                       end
                       else
                       if (((position('PBM', upper(BDDESCVERBA)) > 0) and
                          (bdvalor = 0)) and
                          (wQtdadeCCPBM > 0))
                       then
                         begin
                           bdPBM = 1;
                           BDDESCVERBA = 'GPS ' || iif(wmes < 10, '0', '') || cast(wmes as varchar(2)) || '/' || cast(wano as varchar(4)) || ' - 13º SALÁRIO (PBM)';
                           bdcontacre = wContaCreAux;
                           bdcontadeb = wContaDebAux;
                           suspend;
                           bdPbm = 0;
                           wQtdadeCCPBM = wQtdadeCCPBM -1;
                   end
                end
            end
        end
        end
    END
  ELSE IF (prModelo = 2) THEN --prov 13º
    BEGIN
      FOR EXECUTE STATEMENT wSql INTO :BDCODEMP, :BDCODCOL, :BDNOMECOL, :BDCODTPCC, :BDCENTROCUSTO, :BDFUNCAO, :BDSALBASE, :BDDTADM,
                                      :wLINHA, :WREFP, :w13SAL, :wFGTS, :wINSS, :wFPAS, :wCNAE, :wRATAPO, :wPIS, :wCODTPLADEB,
                                      :wCTALONDEB, :wNOMCTADEB, :wCODTPLACRE, :wCTALONCRE, :wNOMCTACRE, :wValorLanProv
      DO
        BEGIN
          BDPERIODO = cast(WULTDIACOMP as date);

          IF (wLINHA = 0) THEN
            BDREFVERBA2 = 'Provisão 13º salário';
          ELSE IF (wLINHA = 1) THEN
            BDREFVERBA2 = 'Pago';
          ELSE IF (wLinha = 2) THEN
            BDREFVERBA2 = 'Pago adiantamento 13º salário';
          ELSE IF (wLinha = 3) THEN
            BDREFVERBA2 = 'Pago 13º salário';
          ELSE IF (wLinha = 4) THEN
            BDREFVERBA2 = 'Pago rescisão';
          ELSE IF (wLinha = 5) THEN
            BDREFVERBA2 = 'Saldo';
          ELSE IF (wLinha = 6) THEN
            BDREFVERBA2 = '1/12 avos';
          ELSE IF (wLinha = 7) THEN
            BDREFVERBA2 = 'Acerto';
          ELSE IF (wLinha = 8) THEN
            BDREFVERBA2 = 'Acerto transf.';
          ELSE IF (wLinha = 9) THEN
            BDREFVERBA2 = 'Acerto transf. emp.';
          ELSE IF (wLinha = 10) THEN
            BDREFVERBA2 = 'Acerto pagto.';
          ELSE IF (wLinha = 11) THEN
            BDREFVERBA2 = 'Acerto pagto. transf.';
          ELSE IF (wLinha = 12) THEN
            BDREFVERBA2 = 'Acerto pagto. transf. empresas';
          ELSE IF (wlinha = 13) THEN
            BDREFVERBA2 = 'Baixa de pagto';
          ELSE IF (wLinha = 14) THEN
            BDREFVERBA2 = 'Saldo inícial';
          ELSE IF (wLinha = 15) THEN
            BDREFVERBA2 = 'Adiantamento 13º salário pago no mês';
          ELSE IF (wLinha = 16) THEN
            BDREFVERBA2 = '13º salário pago no mês';
          ELSE IF (wLinha = 17) THEN
            BDREFVERBA2 = 'Rescisão pago no mês';
          ELSE IF (wLinha = 18) THEN
            BDREFVERBA2 = '13º pago em messes anteriores';
          ELSE IF (wLinha = 19) THEN
            BDREFVERBA2 = 'Acerto tributação';
          ELSE IF (wLinha = 20) THEN
            BDREFVERBA2 = '13º zerado';
          ELSE
            BDREFVERBA2 = 'Não informado';

          BDDESCVERBA = '13º Salário';

          IF ((wCODTPLADEB > 0) OR (wCODTPLADEB IS NOT NULL)) THEN
            bdcontadeb = CAST(wCODTPLADEB AS VARCHAR(50)) || ' - ' || wCTALONDEB || ' - ' || wNOMCTADEB;
          ELSE
            bdcontadeb = '-';

          IF ((wCODTPLACRE > 0) OR (wCODTPLACRE IS NOT NULL)) THEN
            BDCONTACRE = CAST(wCODTPLACRE AS VARCHAR(50)) || ' - ' || wCTALONCRE || ' - ' || wNOMCTACRE;
          ELSE
            bdcontacre = '-';

          IF (wCodColAnt <> BDCODCOL) THEN
            BEGIN
              BDREFVERBAPROV = 'Salário Base';
              BDVALOR = BDSALBASE;

              WDESCLINHAPROVAUX = BDREFVERBA2;
              BDREFVERBA2 = BDREFVERBAPROV;

              WDEBAUX  = bdcontadeb;
              WCREDAUX = bdcontacre;
              bdcontadeb = '-';
              bdcontacre = '-';

              SUSPEND;

              BDREFVERBA2 = WDESCLINHAPROVAUX;
              bdcontadeb = WDEBAUX;
              bdcontacre = WCREDAUX;
            END

          IF ((w13SAL IS NOT NULL) AND (w13SAL <> 0) and (wValorLanProv = ABS(w13SAL)))THEN
            BEGIN
              BDREFVERBAPROV = '13º Salário';
              BDVALOR = w13SAL;
              SUSPEND;
            END

          IF ((wFGTS IS NOT NULL) AND (wFGTS <> 0) and (wValorLanProv = ABS(wFGTS)))THEN
            BEGIN
              BDREFVERBAPROV = 'FGTS';
              BDVALOR = wFGTS;
              SUSPEND;
            END

          IF ((wINSS IS NOT NULL) AND (wINSS <> 0) and (wValorLanProv = ABS(wINSS)))THEN
            BEGIN
              BDREFVERBAPROV = 'INSS';
              BDVALOR = wINSS;
              SUSPEND;
            END

          IF ((wFPAS IS NOT NULL) AND (wFPAS <> 0) and (wValorLanProv = ABS(wFPAS)))THEN
            BEGIN
              BDREFVERBAPROV = 'TERC';
              BDVALOR = wFPAS;
              SUSPEND;
            END

          IF ((wCNAE IS NOT NULL) AND (wCNAE <> 0) and (wValorLanProv = ABS(wCNAE)))THEN
            BEGIN
              BDREFVERBAPROV = 'RAT';
              BDVALOR = wCNAE;
              SUSPEND;
            END

          IF ((wRATAPO IS NOT NULL) AND (wRATAPO <> 0) and (wValorLanProv = ABS(wRATAPO)))THEN
            BEGIN
              BDREFVERBAPROV = 'RAT APO';
              BDVALOR = wRATAPO;
              SUSPEND;
            END

          IF ((wPIS IS NOT NULL) AND (wPIS <> 0) and (wValorLanProv = ABS(wPIS)))THEN
            BEGIN
              BDREFVERBAPROV = 'PIS';
              BDVALOR = wPIS;
              SUSPEND;
            END
          wCodColAnt = BDCODCOL;
        END
    END
  ELSE --prov Férias
    BEGIN
      FOR EXECUTE STATEMENT wSql INTO :BDCODEMP, :BDCODCOL, :BDNOMECOL, :BDCODTPCC, :BDCENTROCUSTO, :BDFUNCAO, :BDSALBASE, :BDDTADM,
                                      :wLINHA, :WREFP, :wFERIAS, :wUMTERCO, :wFGTS, :wINSS, :wFPAS, :wCNAE, :wRATAPO, :wPIS, :wCODTPLADEB,
                                      :wCTALONDEB, :wNOMCTADEB, :wCODTPLACRE, :wCTALONCRE, :wNOMCTACRE, :wValorLanProv
      DO
        BEGIN
          BDPERIODO = cast(WULTDIACOMP as date);

          IF (wLINHA = 0) THEN
            BDREFVERBA2 = 'Provisão férias';
          ELSE IF (wLINHA = 1) THEN
            BDREFVERBA2 = 'Pago férias';
          ELSE IF (wLinha = 2) THEN
            BDREFVERBA2 = 'Pago rescisão';
          ELSE IF (wLinha = 3) THEN
            BDREFVERBA2 = 'Saldo';
          ELSE IF (wLinha = 4) THEN
            BDREFVERBA2 = '1/12 avos';
          ELSE IF (wLinha = 5) THEN
            BDREFVERBA2 = 'Acerto';
          ELSE IF (wLinha = 6) THEN
            BDREFVERBA2 = 'Acerto transf.';
          ELSE IF (wLinha = 7) THEN
            BDREFVERBA2 = 'Acerto transf. empresas';
          ELSE IF (wLinha = 8) THEN
            BDREFVERBA2 = 'Acerto pagto.';
          ELSE IF (wLinha = 9) THEN
            BDREFVERBA2 = 'Acerto pagto. transf.';
          ELSE IF (wLinha = 10) THEN
            BDREFVERBA2 = 'Acerto pagto. transf. empresas';
          ELSE IF (wLinha = 11) THEN
            BDREFVERBA2 = 'Pago no mês';
          ELSE IF (wLinha = 12) THEN
            BDREFVERBA2 = 'Saldo inicial';
          ELSE IF (wlinha = 13) THEN
            BDREFVERBA2 = 'Férias pagas em meses anteriores';
          ELSE IF (wLinha = 14) THEN
            BDREFVERBA2 = 'Acerto tributação';
          ELSE IF (wLinha = 15) THEN
            BDREFVERBA2 = 'Férias zeradas';
          ELSE IF (wLinha = 16) THEN
            BDREFVERBA2 = 'Férias pagas no mês da rescisão';
          ELSE
            BDREFVERBA2 = 'Não informado';

          BDDESCVERBA = 'Férias';

          IF ((wCODTPLADEB > 0) OR (wCODTPLADEB IS NOT NULL)) THEN
            bdcontadeb = CAST(wCODTPLADEB AS VARCHAR(50)) || ' - ' || wCTALONDEB || ' - ' || wNOMCTADEB;
          ELSE
            bdcontadeb = '-';

          IF ((wCODTPLACRE > 0) OR (wCODTPLACRE IS NOT NULL)) THEN
            BDCONTACRE = CAST(wCODTPLACRE AS VARCHAR(50)) || ' - ' || wCTALONCRE || ' - ' || wNOMCTACRE;
          ELSE
            bdcontacre = '-';

          IF (wCodColAnt <> BDCODCOL) THEN
            BEGIN
              BDREFVERBAPROV = 'Salário Base';
              BDVALOR = BDSALBASE;

              WDESCLINHAPROVAUX = BDREFVERBA2;
              BDREFVERBA2 = BDREFVERBAPROV;

              WDEBAUX  = bdcontadeb;
              WCREDAUX = bdcontacre;
              bdcontadeb = '-';
              bdcontacre = '-';

              SUSPEND;

              BDREFVERBA2 = WDESCLINHAPROVAUX;
              bdcontadeb = WDEBAUX;
              bdcontacre = WCREDAUX;
            END

          IF ((wFERIAS IS NOT NULL) AND (wFERIAS <> 0) and (wValorLanProv = ABS(wFERIAS))) THEN
            BEGIN
              BDREFVERBAPROV = 'Férias';
              BDVALOR = wFERIAS;
              SUSPEND;
            END

          IF ((wUMTERCO IS NOT NULL) AND (wUMTERCO <> 0) and (wValorLanProv = ABS(wUMTERCO))) THEN
            BEGIN
              BDREFVERBAPROV = 'ABONO';
              BDVALOR = wUMTERCO;
              SUSPEND;
            END

          IF ((wFGTS IS NOT NULL) AND (wFGTS <> 0) and (wValorLanProv = ABS(wFGTS))) THEN
            BEGIN
              BDREFVERBAPROV = 'FGTS';
              BDVALOR = wFGTS;
              SUSPEND;
            END

          IF ((wINSS IS NOT NULL) AND (wINSS <> 0) and (wValorLanProv = ABS(wINSS))) THEN
            BEGIN
              BDREFVERBAPROV = 'INSS';
              BDVALOR = wINSS;
              SUSPEND;
            END

          IF ((wFPAS IS NOT NULL) AND (wFPAS <> 0) and (wValorLanProv = ABS(wFPAS))) THEN
            BEGIN
              BDREFVERBAPROV = 'TERC';
              BDVALOR = wFPAS;
              SUSPEND;
            END

          IF ((wCNAE IS NOT NULL) AND (wCNAE <> 0) and (wValorLanProv = ABS(wCNAE))) THEN
            BEGIN
              BDREFVERBAPROV = 'RAT';
              BDVALOR = wCNAE;
              SUSPEND;
            END

          IF ((wRATAPO IS NOT NULL) AND (wRATAPO <> 0) and (wValorLanProv = ABS(wRATAPO))) THEN
            BEGIN
              BDREFVERBAPROV = 'RAT APO';
              BDVALOR = wRATAPO;
              SUSPEND;
            END

          IF ((wPIS IS NOT NULL) AND (wPIS <> 0) and (wValorLanProv = ABS(wPIS))) THEN
            BEGIN
              BDREFVERBAPROV = 'PIS';
              BDVALOR = wPIS;
              SUSPEND;
            END
          wCodColAnt = BDCODCOL;
        END
    END
END^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_TCPRP_BI0 FOR VRH_ESOCIAL_TCPRP
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;
BEGIN
  IF ((NEW.bdcodcprp IS NULL) OR (NEW.bdcodcprp = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODCPRP), 0) + 1 FROM VRH_ESOCIAL_TCPRP INTO :vcod;
       NEW.bdcodcprp = :vcod;
     END
END
^

create or alter procedure SP_VRHF_GETFERIADOS (
    PRCODEMP integer,
    PRANOMESINI integer,
    PRANOMESFIM integer,
    PRFERIADOSBANCARIOS smallint = 0)
returns (
    BDCODUF integer,
    BDCODCID integer,
    BDDESCFERI varchar(50),
    BDMESDIAFERI varchar(4),
    BDCODSINTRAB integer,
    BDCODFERI integer,
    BDFERIBANC DM_BOOLEAN,
    BDDATAFERI date,
    BDDATAFER date,
    BDREFFER integer)
as
declare variable WDTINI date;
declare variable WDTFIM date;
declare variable WULTDIA integer;
declare variable WANOI integer;
declare variable WANOF integer;
declare variable WOK smallint;
declare variable WCODUF integer;
declare variable WCODCID integer;
declare variable WREFEMP integer;
begin
  wdtini = cast((substring(:pranomesini from 1 for 4)||'-'||substring(:pranomesini from 5 for 2)||'-01') as date);
  select first 1 ULTDIA from ULTIMO_DIA_MES(cast((substring(:pranomesfim from 5 for 2)) as smallint), cast((substring(:pranomesfim from 1 for 4)) as integer)) into :wultdia;
  wdtfim = cast((substring(:pranomesfim from 1 for 4)||'-'||substring(:pranomesfim from 5 for 2)||'-'||lpad(trim(cast(:wultdia as varchar(2))), 2, '0')) as date);

  wrefemp = 0;
  wcoduf  = null;
  wcodcid = null;

  for select BDCODUF, BDCODCID, BDDESCFERI, BDMESDIAFERI, BDCODSINTRAB, BDCODFERI, BDFERIBANC, BDDATAFERI
      from TFERIADOSNOVO
      where (BDMESDIAFERI is null and BDDATAFERI is not null and BDDATAFERI between :wdtini and :wdtfim) or
            (BDDATAFERI is null and BDMESDIAFERI is not null)
  into :BDCODUF, :BDCODCID, :BDDESCFERI, :BDMESDIAFERI, :BDCODSINTRAB, :BDCODFERI, :BDFERIBANC, :BDDATAFERI
  do
    begin
      wok = 1;

      if (coalesce(:prferiadosbancarios, 0) = 1 and trim(upper(coalesce(:BDFERIBANC, 'FALSE'))) = 'FALSE') then
         wok = 0;

      if (wok = 1) then
         begin
           if (BDMESDIAFERI is not null) then
              begin
                wanoi = cast((substring(:pranomesini from 1 for 4)) as integer);
                wanof = cast((substring(:pranomesfim from 1 for 4)) as integer);
     
                while (wanoi <= wanof) do
                  begin
                    wrefemp = wanoi||substring(:BDMESDIAFERI from 3 for 2);

                    wcodcid = null;
                    wcoduf  = null;

                    select first 1 E.BDCODCID, C.BDCODUF
                    from TEMPRESAS_REF E
                    left outer join TCIDADE C on (C.BDCODCID = E.BDCODCID)
                    where BDCODEMP = :prcodemp and BDREFEMP <= :wrefemp
                    order by E.BDREFEMP
                    into :wcodcid, :wcoduf;

                    if (((coalesce(:BDCODCID, 0) = coalesce(:wcodcid, 0)) or (coalesce(:BDCODCID, 0) = 0)) and
                        ((coalesce(:BDCODUF, 0) = coalesce(:wcoduf, 0)) or (coalesce(:BDCODUF, 0) = 0))) then
                        begin
                          BDDATAFERI = cast((substring(:BDMESDIAFERI from 3 for 2)||'-'||substring(:BDMESDIAFERI from 1 for 2)||'-'||cast(:wanoi as varchar(4))) as date);
                          BDREFFER = cast((substring(cast(:BDDATAFERI as varchar(10)) from 1 for 4)||substring(cast(:BDDATAFERI as varchar(10)) from 6 for 2)) as integer);
                          BDDATAFER = BDDATAFERI;
                          if (BDDATAFERI between :wdtini and :wdtfim) then
                             suspend;
                        end
                    wanoi = wanoi + 1;
                  end
              end
           else
              begin
                wrefemp = cast((substring(cast(:BDDATAFERI as varchar(10)) from 1 for 4)||substring(cast(:BDDATAFERI as varchar(10)) from 6 for 2)) as integer);

                wcodcid = null;
                wcoduf  = null;

                select first 1 E.BDCODCID, C.BDCODUF
                from TEMPRESAS_REF E
                left outer join TCIDADE C on (C.BDCODCID = E.BDCODCID)
                where BDCODEMP = :prcodemp and BDREFEMP <= :wrefemp
                order by E.BDREFEMP
                into :wcodcid, :wcoduf;

                if (((coalesce(:BDCODCID, 0) = coalesce(:wcodcid, 0)) or (coalesce(:BDCODCID, 0) = 0)) and
                    ((coalesce(:BDCODUF, 0) = coalesce(:wcoduf, 0)) or (coalesce(:BDCODUF, 0) = 0))) then
                    begin
                      BDREFFER = cast((substring(cast(:BDDATAFERI as varchar(10)) from 1 for 4)||substring(cast(:BDDATAFERI as varchar(10)) from 6 for 2)) as integer);
                      BDDATAFER = BDDATAFERI;
                      suspend;
                    end
              end
         end
    end
end^

create or alter procedure SP_VRHF_GETCACHEANUAL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANO integer)
returns (
    BDREF integer,
    BDCATEGORIACOL integer,
    BDCATEGORIAESOCIAL integer)
as
declare variable WREFINI integer;
declare variable WREFFIM integer;
declare variable WREFATU integer;
begin
  wrefini = cast((cast(prano as varchar(4))||'01') as integer);
  wreffim = cast((cast(prano as varchar(4))||'12') as integer);
  wrefatu = 999999;

  while (wreffim >= wrefini) do
    begin
      BDREF          = wreffim;
      if (wrefatu > BDREF) then
         begin
           select first 1 BDREFCOL, BDCATEGORIACOL, BDCATEGORIAESOCIAL
           from VRHF_EMP_TCOLCON_FGTSGPS
           where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFCOL <= :wreffim order by BDREFCOL desc
           into :wrefatu, :BDCATEGORIACOL, :BDCATEGORIAESOCIAL;
         end

      suspend;
      select BDREFERENCIA from dec_referencia(:wreffim) into :wreffim;
    end
end^

/* Restore proc. body: SP_VRHF_GETCOLABCONTR */
create or alter procedure SP_VRHF_GETCOLABCONTR (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCOMPETENCIA integer,
    PRDATAULTIMODIAMES date)
returns (
    BDCODEMP integer,
    BDEXPINIESOCIAL DM_BOOLEAN,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDSALBASECOL DM_NUMERIC_15_2,
    BDFORMAPAGTOCOL integer,
    BDNRODEPIRCOL integer,
    BDBASEIRRFADCOL DM_NUMERIC_15_2,
    BDVALORPREVPRIVNCOL DM_NUMERIC_15_2,
    BDVALORPREVPRIV13COL DM_NUMERIC_15_2,
    BDCATEGORIACOL integer,
    BDCATEGORIAESOCIAL integer,
    BDPERCFGTSCOL DM_NUMERIC_15_2,
    BDOCORRENCIACOL integer,
    BDPERCRATCOL DM_NUMERIC_15_2,
    BDPERCDESCFPASCOL DM_NUMERIC_15_2,
    BDSEXOCOL integer,
    BDDATANASCCOL date,
    BDDATACADCOL date,
    BDDATAADMCOL date,
    BDDATAADICCOL date,
    BDESTCIVCOL integer,
    BDGRAUINSTCOL integer,
    BDCONTRCOL integer,
    BDGRUPOCLA integer,
    BDCODSINTRAB integer,
    BDTIPOCOL integer,
    BDHORASMENSAISCOL numeric(15,4),
    BDHORASSEMANAISCOL numeric(15,4),
    BDHORASDIARIASCOL numeric(15,4),
    BDPERCADISAL DM_NUMERIC_15_2,
    BDPERCINSALUBCOL DM_NUMERIC_15_2,
    BDINCIDINSALUBCOL integer,
    BDPERCPERCULCOL DM_NUMERIC_15_2,
    BDINCIDPERICULCOL integer,
    BDPERCNOTURNOCOL DM_NUMERIC_15_2,
    BDINCIDNOTURNOCOL integer,
    BDNRODEPSALFAMCOL integer,
    BDIGNORAFALTASFERCOL DM_BOOLEAN,
    BDCALCADIANTACOL DM_BOOLEAN,
    BDNAOARREDONDARCOL DM_BOOLEAN,
    BDIMPETIQUETACOL DM_BOOLEAN,
    BDCALCDSRRVCOL DM_BOOLEAN,
    BDCALCDSRHECOL DM_BOOLEAN,
    BDCALCDSRSALCOL DM_BOOLEAN,
    BDCALCVALTRANSCOL DM_BOOLEAN,
    BDCALCVALREFCOL DM_BOOLEAN,
    BDFICHAREGCOL varchar(12),
    BDTIPOADMCOL integer,
    BDNATUOCUPCOL integer,
    BDDATAINIAQUICOL date,
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDCODCBO integer,
    BDCODQH integer,
    BDDESCTFUC varchar(40),
    BDSALINICOL DM_NUMERIC_15_2,
    BDDIASPRAZO1COL integer,
    BDDATAFIMPRAZO1COL date,
    BDDIASPRAZO2COL integer,
    BDDATAFIMPRAZO2COL date,
    BDDESCCONTSINCOL DM_BOOLEAN,
    BDVINCEMPCOL integer,
    BDALVARACOL DM_BOOLEAN,
    BDSINDICALIZADOCOL DM_BOOLEAN,
    BDREGIMEPARCIALCOL DM_BOOLEAN,
    BDDESCCONTASSCOL DM_BOOLEAN,
    BDDATATRF date,
    BDDATAALTSAL date,
    BDSITEMP DM_BOOLEAN,
    BDINATIVO DM_BOOLEAN,
    BDPERCGORJ DM_NUMERIC_15_2,
    BDCODEMPRHNET integer,
    BDCODMULTVINC integer,
    BDCODPTRAN integer,
    BDDATACALC date,
    BDCODCENTROS integer,
    BDCODPQUA integer,
    BDCALCC13NAFNEMP DM_BOOLEAN,
    BDREFADMCOL integer)
as
declare variable WUSANOMESOCIAL DM_BOOLEAN;
declare variable WSIMPLES integer;
declare variable WDATA1 date;
declare variable WDATA2 date;
begin
  wusanomesocial = 'FALSE';
  wsimples = 0;
  wdata1 = null;
  wdata2 = null;

  BDDATACALC = null;

  -- Faz filtro da tabela principal e somente ativos
  for select COL.BDCODEMP, COL.BDCODCOL, COL.BDDATAADMCOL, COL.BDDATANASCCOL, COL.BDDATACADCOL, COL.BDDATAADICCOL, COL.BDCPFCOL, COL.BDCONTRCOL, COL.BDREFADMCOL
      from VRH_EMP_TCOLCON COL
      where COL.BDCODEMP = :prcodemp and BDCODCOL = :prcodcol
      order by COL.BDCODEMP, COL.BDCODCOL
  into :BDCODEMP, :BDCODCOL, :bddataadmcol, :bddatanasccol, :bddatacadcol, :bddataadiccol, :bdcpfcol, :bdcontrcol, :bdrefadmcol
  do
    begin
      BDDATACALC = PRDATAULTIMODIAMES;
      select BDEXPINIESOCIAL, coalesce(BDCODWEB, BDCODEMP)
        from TEMPRESAS
        where BDCODEMP = :BDCODEMP
        into :BDEXPINIESOCIAL, :BDCODEMPRHNET;
      select first 1 BDCODCENTROS, BDSITEMP
        from TEMPRESAS_REF
        where BDCODEMP = :BDCODEMP and BDREFEMP <= :prcompetencia
        order by BDREFEMP desc
        into :BDCODCENTROS, :BDSITEMP;
      select first 1 BDUSANOMESOCIAL, BDCALCC13NAFNEMP
        from VRHF_BASE_TEMPPAR
        where BDCODEMP = :BDCODEMP and BDREFEMP <= :prcompetencia
        order by BDREFEMP desc
        into :wusanomesocial, :BDCALCC13NAFNEMP;
      select first 1 BDSIMPLESGPS
        from VRHF_BASE_TEMPGPS
        where BDCODEMP = :BDCODEMP and BDREFEMP <= :prcompetencia
        order by BDREFEMP desc
        into :wsimples;

      if (upper(trim(coalesce(:wusanomesocial, 'FALSE'))) = 'TRUE') then
         begin
           select first 1 BDNMSOCIAL
             from VRH_EMP_TCOLCON_FIS
             where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prcompetencia
             order by BDREFCOL desc
             into :BDNOMCOL;
           select first 1 coalesce(BDSEXOCOL, 0), coalesce(BDESTCIVCOL, 0), coalesce(BDGRAUINSTCOL, 0)
             from VRH_EMP_TCOLCON_CAD
             where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prcompetencia
             order by BDREFCOL desc
             into :BDSEXOCOL, :BDESTCIVCOL, :BDGRAUINSTCOL;
         end
      else
         select first 1 BDNOMCOL, coalesce(BDSEXOCOL, 0), coalesce(BDESTCIVCOL, 0), coalesce(BDGRAUINSTCOL, 0)
           from VRH_EMP_TCOLCON_CAD
           where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prcompetencia
           order by BDREFCOL desc
           into :BDNOMCOL, :BDSEXOCOL, :BDESTCIVCOL, :BDGRAUINSTCOL;

      select first 1 BDPISCOL
        from VRH_EMP_TCOLCON_DOCREF
        where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prcompetencia
        order by BDREFCOL desc
        into :BDPISCOL;
      select first 1 CAST(BDSALBASECOL as dm_numeric_15_2), BDDATACOL
        from VRH_EMP_TCOLCON_CALCDIA
        where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDDATACOL <= :prdataultimodiames
        order by BDDATACOL desc
        into :BDSALBASECOL, :BDDATAALTSAL;
      select first 1 coalesce(BDFORMAPAGTOCOL, 0), coalesce(BDNRODEPIRCOL, 0), CAST(coalesce(BDBASEIRRFADCOL, 0.00) as dm_numeric_15_2)
        from VRHF_EMP_TCOLCON_CALC
        where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prcompetencia
        order by BDREFCOL desc
        into :BDFORMAPAGTOCOL, :BDNRODEPIRCOL, :BDBASEIRRFADCOL;

      select cast(coalesce(sum(BDVALMENSAL), 0.00) as dm_numeric_15_2), cast(coalesce(sum(BDVAL13SAL), 0.00) as dm_numeric_15_2)
        from VRH_EMP_TLANCPREVCOMP
        where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFINI <= :prcompetencia and ((coalesce(BDREFFIN, 0) = 0) or (BDREFFIN >= :prcompetencia))
        into :BDVALORPREVPRIVNCOL, :BDVALORPREVPRIV13COL;

      select first 1 BDCATEGORIACOL, BDCATEGORIAESOCIAL, BDPERCFGTSCOL, BDOCORRENCIACOL, cast(coalesce(BDPERCRATCOL, 0.00) as dm_numeric_15_2),
          cast(coalesce(BDPERCDESCFPASCOL, 0.00) as dm_numeric_15_2), BDCODMULTVINC
        from VRHF_EMP_TCOLCON_FGTSGPS
        where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prcompetencia
        order by BDREFCOL desc
        into :BDCATEGORIACOL, :BDCATEGORIAESOCIAL, :BDPERCFGTSCOL, :BDOCORRENCIACOL, :BDPERCRATCOL, :BDPERCDESCFPASCOL, :BDCODMULTVINC;

      if (coalesce(wsimples, 0) in (1, 2, 5)) then
         BDPERCRATCOL = 0.00;

      select first 1 CLA.BDGRUPOCLA
        from VRH_EMP_TCOLCON_VINC C
        join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = C.BDCODCLA)
        where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prcompetencia
        order by BDREFCOL desc
        into :BDGRUPOCLA;

      select first 1 BDCODSINTRAB
        from VRH_EMP_TCOL_VINC
        where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prcompetencia
        order by BDREFCOL desc
        into :BDCODSINTRAB;

      select first 1 BDTIPOCOL, cast(coalesce(BDHORASMENSAISCOL, 0.00) as numeric(15,4)), cast(coalesce(BDHORASSEMANAISCOL, 0.00) as numeric(15,4)),
           cast(coalesce(BDHORASDIARIASCOL, 0.00) as numeric(15,4)), cast(coalesce(BDPERCADISAL, 0.00) as dm_numeric_15_2),
           cast(coalesce(BDPERCINSALUBCOL, 0.00) as dm_numeric_15_2), coalesce(BDINCIDINSALUBCOL, 0),
           cast(coalesce(BDPERCPERCULCOL, 0.00) as dm_numeric_15_2), coalesce(BDINCIDPERICULCOL, 0),
           cast(coalesce(BDPERCNOTURNOCOL, 0.00) as dm_numeric_15_2), coalesce(BDINCIDNOTURNOCOL, 0),
           coalesce(BDNRODEPSALFAMCOL, 0), upper(trim(coalesce(BDIGNORAFALTASFERCOL, 'FALSE'))),
           upper(trim(coalesce(BDCALCADIANTACOL, 'FALSE'))), upper(trim(coalesce(BDNAOARREDONDARCOL, 'FALSE'))),
           upper(trim(coalesce(BDIMPETIQUETACOL, 'FALSE'))), upper(trim(coalesce(BDCALCDSRRVCOL, 'FALSE'))),
           upper(trim(coalesce(BDCALCDSRHECOL, 'FALSE'))), upper(trim(coalesce(BDCALCDSRSALCOL, 'FALSE'))),
           upper(trim(coalesce(BDCALCVALTRANSCOL, 'FALSE'))), upper(trim(coalesce(BDCALCVALREFCOL, 'FALSE'))),
           upper(trim(coalesce(BDREGIMEPARCIALCOL, 'FALSE'))), cast(coalesce(BDPERCGORJ, 0.00) as dm_numeric_15_2)
        from VRHF_EMP_TCOL_CALC
        where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prcompetencia
        order by BDREFCOL desc
        into :BDTIPOCOL, :BDHORASMENSAISCOL, :BDHORASSEMANAISCOL, :BDHORASDIARIASCOL, :BDPERCADISAL, :BDPERCINSALUBCOL, :BDINCIDINSALUBCOL,
             :BDPERCPERCULCOL, :BDINCIDPERICULCOL, :BDPERCNOTURNOCOL, :BDINCIDNOTURNOCOL, :BDNRODEPSALFAMCOL, :BDIGNORAFALTASFERCOL, :BDCALCADIANTACOL,
             :BDNAOARREDONDARCOL, :BDIMPETIQUETACOL, :BDCALCDSRRVCOL, :BDCALCDSRHECOL, :BDCALCDSRSALCOL, :BDCALCVALTRANSCOL, :BDCALCVALREFCOL, :BDREGIMEPARCIALCOL,
             :BDPERCGORJ;

      wdata1 = null;
      wdata2 = null;
      BDDATAFIMPRAZO1COL = null;
      BDDATAFIMPRAZO2COL = null;

      select first 1 BDDATAFIMPRAZO1COL, BDDATAFIMPRAZO2COL
        from SP_PRAZO_EXPERIENCIA_SITUACAO('BDCODEMP = '||:BDCODEMP, 'BDCODCOL = '||:BDCODCOL, null, null)
        into :BDDATAFIMPRAZO1COL, :BDDATAFIMPRAZO2COL;

      if (BDDATAFIMPRAZO1COL is null) then
         begin
           select BDFICHAREGCOL, BDTIPOADMCOL, BDNATUOCUPCOL, BDDATAINIAQUICOL, BDDIASPRAZO1COL, BDDIASPRAZO2COL, BDDESCCONTSINCOL, BDDESCCONTASSCOL,
                BDDATAFIMPRAZO1COL, BDDATAFIMPRAZO2COL
             from VRH_EMP_TCOL_ADM
             where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL
             into :BDFICHAREGCOL, :BDTIPOADMCOL, :BDNATUOCUPCOL, :BDDATAINIAQUICOL, :BDDIASPRAZO1COL, :BDDIASPRAZO2COL, :BDDESCCONTSINCOL, :BDDESCCONTASSCOL,
                  :wdata1, :wdata2;

           if (coalesce(BDDIASPRAZO1COL, 0) > 0) then
              wdata1 = BDDATAADMCOL + BDDIASPRAZO1COL - 1;
      
           if (coalesce(BDDIASPRAZO2COL, 0) > 0) then
              wdata1 = BDDATAADMCOL + coalesce(BDDIASPRAZO1COL, 0) + BDDIASPRAZO2COL - 1;
      
           BDDATAFIMPRAZO1COL = wdata1;
           BDDATAFIMPRAZO2COL = wdata2;
         end
      else
         begin
           select BDFICHAREGCOL, BDTIPOADMCOL, BDNATUOCUPCOL, BDDATAINIAQUICOL, BDDIASPRAZO1COL, BDDIASPRAZO2COL, BDDESCCONTSINCOL, BDDESCCONTASSCOL
             from VRH_EMP_TCOL_ADM
             where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL
             into :BDFICHAREGCOL, :BDTIPOADMCOL, :BDNATUOCUPCOL, :BDDATAINIAQUICOL, :BDDIASPRAZO1COL, :BDDIASPRAZO2COL, :BDDESCCONTSINCOL, :BDDESCCONTASSCOL;
         end

      BDCODPLAFUC = null;
      BDCODTFUC = null;
      BDCODPQUA = null;
      BDCODQH = null;
      BDDESCTFUC = null;

      select first 1 BDCODPLAFUC, BDCODTFUC, BDCODQH, BDCODPQUA
        from VRH_EMP_TCOL_VINCDIA
        where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDDATACOL <= :prdataultimodiames
        order by BDDATACOL desc
        into :BDCODPLAFUC, :BDCODTFUC, BDCODQH, :BDCODPQUA;

      select first 1 BDVINCEMPCOL, upper(trim(coalesce(BDALVARACOL, 'FALSE'))), upper(trim(coalesce(BDSINDICALIZADOCOL, 'FALSE')))
        from VRH_EMP_TCOL_ADMREF
        where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prcompetencia
        order by BDREFCOL desc
        into :BDVINCEMPCOL, :BDALVARACOL, BDSINDICALIZADOCOL;

      wdata1 = null;
      wdata2 = null;
      select BDDATATRFCOL, cast(coalesce(BDSALINICOL, 0.00) as dm_numeric_15_2)
        from VRH_EMP_TCOLCON_PARTIDA
        where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL
        into :wdata1, :BDSALINICOL;

      BDCODPTRAN = null;
      select first 1 BDDATATRF, BDCODPTRAN
        from VRH_EMP_TTRANSCOL
        where BDCODEMPDEST  = :BDCODEMP and BDCODCOLDEST = :BDCODCOL
        into :wdata2, :BDCODPTRAN;

      if (wdata2 is not null) then
         BDDATATRF = wdata2;
      else
         BDDATATRF = wdata1;

      select first 1 upper(trim(coalesce(BDINATIVO, 'FALSE')))
        from VRH_EMP_TCOLCON_REF
        where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prcompetencia
        order by BDREFCOL desc
        into :BDINATIVO;

      BDCODCBO = null;
      if (coalesce(BDCODPLAFUC, 0) > 0 and coalesce(BDCODTFUC, 0) > 0) then
         select first 1 BDCODCBO, BDDESCTFUC from VRH_FUNCOES_TFUC where BDCODPLAFUC = :BDCODPLAFUC and BDCODTFUC = :BDCODTFUC into :BDCODCBO, :BDDESCTFUC;

      suspend;
    end
end^

create or alter procedure SP_VRHF_GETDEPENDENTE (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDCODDPN integer,
    BDREFDPN integer,
    BDNOMEDPN DM_BDNOMDPN,
    BDPARENESCODPN integer,
    BDDATANASCDPN date,
    BDCPFDPN varchar(14),
    BDINVALIDODPN DM_BOOLEAN,
    BDCONVMEDDPN DM_BOOLEAN,
    BDSALFAMDPN DM_BOOLEAN,
    BDDEPIRDPN DM_BOOLEAN,
    BDCODCID integer,
    BDCARTDPN varchar(20),
    BDREGDPN integer,
    BDLIVDPN varchar(10),
    BDFOLDPN varchar(10),
    BDDATAENTREDPN date,
    BDDATABAUXADPN date,
    BDDPN integer,
    BDREFIRDPN integer,
    BDMATRICULADPN varchar(200),
    BDCODTIPO integer,
    BDTIPODEPESOCIAL integer,
    BDUNIVERSITARIO varchar(35),
    BDIDRHNET integer,
    BDSTATUS_ES integer,
    BDDATA_ES date)
as
begin
  for select BDCODDPN,BDCODCID,BDCARTDPN,BDREGDPN,BDLIVDPN,BDFOLDPN,BDDATAENTREDPN,BDDATABAUXADPN,BDDPN,BDREFIRDPN,BDMATRICULADPN,BDCODTIPO,BDTIPODEPESOCIAL,
             BDUNIVERSITARIO,BDIDRHNET,BDSTATUS_ES,BDDATA_ES
      from VRH_EMP_TDEP
      where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol
  into :BDCODDPN,:BDCODCID,:BDCARTDPN,:BDREGDPN,:BDLIVDPN,:BDFOLDPN,:BDDATAENTREDPN,:BDDATABAUXADPN,:BDDPN,:BDREFIRDPN,:BDMATRICULADPN,:BDCODTIPO,:BDTIPODEPESOCIAL,
       :BDUNIVERSITARIO,:BDIDRHNET,:BDSTATUS_ES,:BDDATA_ES
  do
    begin
      select first 1 BDREFDPN,BDPARENESCODPN,BDNOMEDPN,BDDATANASCDPN,BDCPFDPN,BDINVALIDODPN,BDCONVMEDDPN,BDSALFAMDPN,BDDEPIRDPN
      from VRH_EMP_TDEP_REF
      where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDCODDPN = :BDCODDPN and BDREFDPN <= :pranomes
      order by BDREFDPN desc
      into :BDREFDPN,:BDPARENESCODPN,:BDNOMEDPN,:BDDATANASCDPN,:BDCPFDPN,:BDINVALIDODPN,:BDCONVMEDDPN,:BDSALFAMDPN,:BDDEPIRDPN;
      suspend;
    end
end^

create or alter procedure SP_VRHF_GETDEPPENSAO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer,
    PRTIPOSCALC varchar(100))
returns (
    BDCODDPN integer,
    BDREFDEPP integer,
    BDCODCTP integer,
    BDCODVER integer,
    BDFORMREFDEPP varchar(1000),
    BDFORMREFAUXDEPP varchar(1000),
    BDFORMVALDEPP varchar(1000),
    BDNOMBENEF varchar(70),
    BDFIMBENEF integer,
    BDDEDREFAUXDEPP DM_BOOLEAN,
    BDDEDREFDEPP DM_BOOLEAN,
    BDDEDVALDEPP DM_BOOLEAN,
    BDPERCDEPP DM_NUMERIC_15_2,
    BDPERCDEPPTOT DM_NUMERIC_15_2)
as
declare variable WSQL varchar(2000);
begin
  for select DEP.BDCODBENEF, substring(DEP.BDNOMBENEF from 1 for 70), DEP.BDFIMBENEF
      from VRH_EMP_TCOLCON_BENEF DEP
      where DEP.BDCODEMP = :prcodemp and DEP.BDCODCOL = :prcodcol and ((coalesce(DEP.BDFIMBENEF, 0) = 0) or (coalesce(DEP.BDFIMBENEF, 0) >= :pranomes))
  into :BDCODDPN, :BDNOMBENEF, :BDFIMBENEF
  do
    begin
      wsql = 'select BDCODCTP, max(BDREFDEPP) '||
             'from VRH_EMP_TDEP_PENSAO '||
             'where BDCODEMP = '||:prcodemp||' and BDCODCOL = '||:prcodcol||' and BDCODDPN = '||:BDCODDPN||
                  ' and ((coalesce(BDREFFIMDEPP, 0) = 0) or (coalesce(BDREFFIMDEPP, 0) >= '||:pranomes||')) ';

      if (trim(coalesce(prtiposcalc, '')) <> '') then
         wsql = wsql||' and BDCODCTP in ('||prtiposcalc||') ';

      wsql = wsql||'group by BDCODCTP ';

      for execute statement wsql into :BDCODCTP, :BDREFDEPP do
        begin
          for select PEN.BDCODVER, PEN.BDFORMREFDEPP, PEN.BDFORMREFAUXDEPP, PEN.BDFORMVALDEPP, PEN.BDDEDREFAUXDEPP,
                     PEN.BDDEDREFDEPP, PEN.BDDEDVALDEPP, cast(PEN.BDPERCDEPP as dm_numeric_15_2)
              from VRH_EMP_TDEP_PENSAO PEN
              join VRH_BASE_TVERBAS VER on (VER.BDCODVER = PEN.BDCODVER)
              where PEN.BDCODEMP = :prcodemp and PEN.BDCODCOL = :prcodcol and PEN.BDCODDPN = :BDCODDPN and PEN.BDCODCTP = :BDCODCTP and PEN.BDREFDEPP = :BDREFDEPP and
                    VER.BDCLAVER not starting with '0.601.8.1'
          into :BDCODVER, :BDFORMREFDEPP, :BDFORMREFAUXDEPP, :BDFORMVALDEPP, :BDDEDREFAUXDEPP, :BDDEDREFDEPP, :BDDEDVALDEPP, :BDPERCDEPP
          do
            begin
              select CAST(SUM(BDPERCDEPP) as dm_numeric_15_2)
              from VRH_EMP_TDEP_PENSAO 
              where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDCODCTP = :BDCODCTP and BDREFDEPP <= :pranomes and
                    ((coalesce(BDREFFIMDEPP, 0) = 0) or (coalesce(BDREFFIMDEPP, 0) >= :pranomes))
              into :BDPERCDEPPTOT;
              suspend;
            end
        end
    end
end^

/* Restore proc. body: SP_VRHF_GETEMPRESA */
create or alter procedure SP_VRHF_GETEMPRESA (
    PRCODEMP integer,
    PRANOMES integer)
returns (
    BDCODEMP integer,
    BDREFEMP integer,
    BDPAGEMP integer,
    BDFECHAMESEMP integer,
    BDFECHAVTEMP integer,
    BDARREMP integer,
    BDTIPOARREMP integer,
    BDTIPOFEREMP integer,
    BDSOMSALFEREMP DM_BOOLEAN,
    BDTIPOAD13EMP integer,
    BDSOMSALAD13EMP DM_BOOLEAN,
    BDPERCADSALEMP DM_NUMERIC_15_2,
    BDREFHOREMP DM_BOOLEAN,
    BDLICREMFEREMP DM_BOOLEAN,
    BDESTOUROEMP DM_BOOLEAN,
    BDESTOURORESEMP DM_BOOLEAN,
    BDFALFEREMP DM_BOOLEAN,
    BDFALHORFEREMP DM_BOOLEAN,
    BDDEPIRRESCEMP DM_BOOLEAN,
    BDCODSINPAT integer,
    BDCAPSOCEMP DM_NUMERIC_15_2,
    BDTAXSEREMP DM_NUMERIC_15_2,
    BDPROPADMEMP integer,
    BDPROPRESEMP integer,
    BDPROPFEREMP integer,
    BDPROPSITEMP integer,
    BDCALCMEDIASTEMP integer,
    BDMESDSREMP integer,
    BDNATESTEMP integer,
    BDDATABASEEMP integer,
    BDPATEMP DM_BOOLEAN,
    BDNROPROPEMP integer,
    BDSERPROPRIOPATEMP integer,
    BDPATREFCONVENIOEMP integer,
    BDPATCESTAALIMENTOEMP integer,
    BDPATADMCOZINHAEMP integer,
    BDPATREFTRANSPEMP integer,
    BDPATALICONVENIOEMP integer,
    BDSINDICALIZEMP DM_BOOLEAN,
    BDCODIR integer,
    BDCODINSS integer,
    BDCODMEN integer,
    BDCALCFCNAFNEMP DM_BOOLEAN,
    BDCALCC13NAFNEMP DM_BOOLEAN,
    BDPERTERC DM_NUMERIC_17_4,
    BDCODFPAS integer,
    BDPROPTOMEMP integer,
    BDANOSAVPREVIOIND integer,
    BDCODPLACONVSAU integer,
    BDDIASTRABADI integer,
    BDCODCENTROS integer,
    BDCODPLAFUC integer,
    BDCODUF integer,
    BDCODCID integer,
    BDTIPCALCFERCOLINF integer,
    BDTIPCALCFERCOLSUP integer,
    BDLIMINARAVPREVEMP integer,
    BDARREDONDAFN DM_BOOLEAN,
    BDARREDONDAFC DM_BOOLEAN,
    BDARREDONDAFE DM_BOOLEAN,
    BDARREDONDAA13 DM_BOOLEAN,
    BDARREDONDA13 DM_BOOLEAN,
    BDARREDONDAC13 DM_BOOLEAN,
    BDARREDONDAAD DM_BOOLEAN,
    BDARREDONDAAU DM_BOOLEAN,
    BDARREDONDAFA DM_BOOLEAN,
    BDARREDONDAFTINT DM_BOOLEAN,
    BDPAGEMPCONTR integer,
    BDDESCFALHORASDIAS DM_BOOLEAN,
    BDPERCLIMIDESCPAR DM_NUMERIC_15_2,
    BDCNPJEMP DM_CNPJ_CPF,
    BDOPCAOESOCIAL integer,
    BDCODNATJUR integer,
    BDCODMATRIZ integer,
    BDCODCLATRI integer,
    BDCALCC13FNNEGEMP DM_BOOLEAN,
    BDCATSEFIPEMP integer,
    BDDSRMEDATUSAL DM_BOOLEAN,
    BDIDADESAUDEEMP DM_BOOLEAN,
    BDCONTABILIZASCP DM_BOOLEAN,
    BDDESCCOMPL13NEG DM_BOOLEAN,
    BDDATAINITABELA date,
    BDDATAININAOPERIOD date,
    BDDATAINIPERIOD date,
    BDDATAINISST date,
    BDREFINITABELA integer,
    BDREFININAOPERIOD integer,
    BDREFINIPERIOD integer,
    BDREFINISST integer,
    BDGRUPO integer,
    BDREFINIDCTFWEB integer,
    BDCODCONFBLOCOP integer,
    BDCODBAIXA integer,
    BDCODPLANOONLINE integer,
    BDRATEIO13SAL integer)
as
declare variable WNAOAPLICAMP932 DM_BOOLEAN;
declare variable WCODFPASTERC integer;
declare variable WSALEDU numeric(18,6);
declare variable WINCRA numeric(18,6);
declare variable WSENAI numeric(18,6);
declare variable WSESI numeric(18,6);
declare variable WSENAC numeric(18,6);
declare variable WSESC numeric(18,6);
declare variable WSEBRAE numeric(18,6);
declare variable WDPC numeric(18,6);
declare variable WFUNAERO numeric(18,6);
declare variable WSENAR numeric(18,6);
declare variable WSEST numeric(18,6);
declare variable WSENAT numeric(18,6);
declare variable WSESCOOP numeric(18,6);
declare variable WNROPROP integer;
begin
  for select BDCODEMP, BDCNPJEMP, BDCODMATRIZ from TEMPRESAS where BDCODEMP = :prcodemp into :BDCODEMP, :BDCNPJEMP, :BDCODMATRIZ do
    begin
      select first 1 BDPAGEMP, BDFECHAMESEMP, BDFECHAVTEMP, BDARREMP, BDTIPOARREMP, BDTIPOFEREMP,
         BDSOMSALFEREMP, BDTIPOAD13EMP, BDSOMSALAD13EMP, BDPERCADSALEMP, BDREFHOREMP, BDLICREMFEREMP,
         BDESTOUROEMP, BDESTOURORESEMP, BDFALFEREMP, BDFALHORFEREMP, BDDEPIRRESCEMP,
         BDMESDSREMP,
         BDANOSAVPREVIOIND,
         BDTIPCALCFERCOLINF, BDTIPCALCFERCOLSUP, BDLIMINARAVPREVEMP, BDARREDONDAFN, BDARREDONDAFC,
         BDARREDONDAFE, BDARREDONDAA13, BDARREDONDA13, BDARREDONDAC13, BDARREDONDAAD, BDARREDONDAAU,
         BDARREDONDAFA, BDARREDONDAFTINT, BDPAGEMPCONTR, BDDESCFALHORASDIAS, BDPERCLIMIDESCPAR,
         BDDSRMEDATUSAL, BDIDADESAUDEEMP
      from VRHF_BASE_TEMPCALC
      where BDCODEMP = :BDCODEMP and BDREFEMP <= :pranomes
      order by BDREFEMP desc
      into :BDPAGEMP, :BDFECHAMESEMP, :BDFECHAVTEMP, :BDARREMP, :BDTIPOARREMP, :BDTIPOFEREMP,
         :BDSOMSALFEREMP, :BDTIPOAD13EMP, :BDSOMSALAD13EMP, :BDPERCADSALEMP, :BDREFHOREMP, :BDLICREMFEREMP,
         :BDESTOUROEMP, :BDESTOURORESEMP, :BDFALFEREMP, :BDFALHORFEREMP, :BDDEPIRRESCEMP,
         :BDMESDSREMP,
         :BDANOSAVPREVIOIND,
         :BDTIPCALCFERCOLINF, :BDTIPCALCFERCOLSUP, :BDLIMINARAVPREVEMP, :BDARREDONDAFN, :BDARREDONDAFC,
         :BDARREDONDAFE, :BDARREDONDAA13, :BDARREDONDA13, :BDARREDONDAC13, :BDARREDONDAAD, :BDARREDONDAAU,
         :BDARREDONDAFA, :BDARREDONDAFTINT, :BDPAGEMPCONTR, :BDDESCFALHORASDIAS, :BDPERCLIMIDESCPAR,
         :BDDSRMEDATUSAL, :BDIDADESAUDEEMP;

      select first 1 BDCODSINPAT, BDCAPSOCEMP
      from VRHF_BASE_TEMPGRCS
      where BDCODEMP = :BDCODEMP and BDREFEMP <= :pranomes
      order by BDREFEMP desc
      into :BDCODSINPAT, :BDCAPSOCEMP;

      select first 1 BDTAXSEREMP, BDCALCFCNAFNEMP, BDCALCC13NAFNEMP, BDCALCC13FNNEGEMP, BDDESCCOMPL13NEG
      from VRHF_BASE_TEMPPAR
      where BDCODEMP = :BDCODEMP and BDREFEMP <= :pranomes
      order by BDREFEMP desc
      into :BDTAXSEREMP, :BDCALCFCNAFNEMP, :BDCALCC13NAFNEMP, :BDCALCC13FNNEGEMP, :BDDESCCOMPL13NEG;

      select first 1 BDPROPADMEMP, BDPROPRESEMP, BDPROPFEREMP, BDPROPSITEMP, BDCALCMEDIASTEMP, BDPROPTOMEMP, BDDIASTRABADI
      from VRHF_BASE_TEMPPROP
      where BDCODEMP = :BDCODEMP and BDREFEMP <= :pranomes
      order by BDREFEMP desc
      into :BDPROPADMEMP, :BDPROPRESEMP, :BDPROPFEREMP, :BDPROPSITEMP, :BDCALCMEDIASTEMP, :BDPROPTOMEMP, :BDDIASTRABADI;

      select first 1 BDNATESTEMP, BDDATABASEEMP, BDPATEMP, BDSERPROPRIOPATEMP, BDPATREFCONVENIOEMP, BDPATCESTAALIMENTOEMP, BDPATADMCOZINHAEMP, BDPATREFTRANSPEMP, BDPATALICONVENIOEMP, BDSINDICALIZEMP, BDNROPROPEMP
      from VRHF_BASE_TEMPRAIS
      where BDCODEMP = :BDCODEMP and BDREFEMP <= :pranomes
      order by BDREFEMP desc
      into :BDNATESTEMP, :BDDATABASEEMP, :BDPATEMP, :BDSERPROPRIOPATEMP, :BDPATREFCONVENIOEMP, :BDPATCESTAALIMENTOEMP, :BDPATADMCOZINHAEMP, :BDPATREFTRANSPEMP, :BDPATALICONVENIOEMP, :BDSINDICALIZEMP, :wnroprop;

      select first 1 BDCODPLAFUC
      from VRH_BASE_TEMPVINC
      where BDCODEMP = :BDCODEMP and BDREFEMP <= :pranomes
      order by BDREFEMP desc
      into :BDCODPLAFUC;

      select first 1 BDCODIR, BDCODINSS, BDCODMEN, BDCODPLACONVSAU, BDCODBAIXA
      from VRHF_BASE_TEMPVINC
      where BDCODEMP = :BDCODEMP and BDREFEMP <= :pranomes
      order by BDREFEMP desc
      into :BDCODIR, :BDCODINSS, :BDCODMEN, :BDCODPLACONVSAU, :BDCODBAIXA;

      select first 1 BDCODCONFBLOCOP
      from VEF_BASE_TEMPPARGER
      where BDCODEMP = :BDCODEMP and BDREFEMP <= :pranomes
      order by BDREFEMP desc
      into :BDCODCONFBLOCOP;

      wnaoaplicamp932 = null;
      select BDNAOAPLICAMP932 from VRHF_BASE_TEMPMP932 where BDCODEMP = :BDCODEMP into :wnaoaplicamp932;
      wnaoaplicamp932 = trim(upper(coalesce(wnaoaplicamp932, 'FALSE')));

      wcodfpasterc = null;
      select first 1 BDCODFPASTERC, BDRATEIO13SAL
      from VRHF_BASE_TEMPGPS
      where BDCODEMP = :BDCODEMP and BDREFEMP <= :pranomes
      order by BDREFEMP desc
      into :wcodfpasterc, :BDRATEIO13SAL;
      wcodfpasterc = coalesce(wcodfpasterc, 0);

      BDPERTERC = 0;
      BDCODFPAS = null;
      if (wcodfpasterc > 0) then
         begin
           select BDSALEDU,BDINCRA,BDSENAI,BDSESI,BDSENAC,BDSESC,BDSEBRAE,BDDPC,BDFUNAERO,BDSENAR,BDSEST,BDSENAT,BDSESCOOP,BDCODFPAS
           from VRH_BASE_TFPAS_TERCEIROS
           where BDCODFPASTERC = :wcodfpasterc
           into :wsaledu, :wincra, :wsenai, :wsesi, :wsenac, :wsesc, :wsebrae, :wdpc, :wfunaero, :wsenar, :wsest, :wsenat, :wsescoop, :BDCODFPAS;

           wsaledu  = coalesce(wsaledu, 0);
           wincra   = coalesce(wincra, 0);
           wsenai   = coalesce(wsenai, 0);
           wsesi    = coalesce(wsesi, 0);
           wsenac   = coalesce(wsenac, 0);
           wsesc    = coalesce(wsesc, 0);
           wsebrae  = coalesce(wsebrae, 0);
           wdpc     = coalesce(wdpc, 0);
           wfunaero = coalesce(wfunaero, 0);
           wsenar   = coalesce(wsenar, 0);
           wsest    = coalesce(wsest, 0);
           wsenat   = coalesce(wsenat, 0);
           wsescoop = coalesce(wsescoop, 0);

           if (pranomes between 202004 and 202006 and wnaoaplicamp932 = 'FALSE') then
              begin
                wsenai   = wsenai * 0.5;
                wsesi    = wsesi * 0.5;
                wsenac   = wsenac * 0.5;
                wsesc    = wsesc * 0.5;
                wsenar   = wsenar * 0.5;
                wsest    = wsest * 0.5;
                wsenat   = wsenat * 0.5;
                wsescoop = wsescoop * 0.5;
              end

           BDPERTERC = CAST((wsaledu+wincra+wsenai+wsesi+wsenac+wsesc+wsebrae+wdpc+wfunaero+wsenar+wsest+wsenat+wsescoop) AS DM_NUMERIC_15_2);
         end

      BDCODCID = null;
      select first 1 BDCODCENTROS, BDCODCID, BDCODNATJUR, BDCONTABILIZASCP, BDCODPLANOONLINE, BDREFEMP
      from TEMPRESAS_REF
      where BDCODEMP = :BDCODEMP and BDREFEMP <= :pranomes
      order by BDREFEMP desc
      into :BDCODCENTROS, :BDCODCID, :BDCODNATJUR, :BDCONTABILIZASCP, :BDCODPLANOONLINE, :BDREFEMP;

      if (BDCODCID is not null) then
         select BDCODUF from TCIDADE where BDCODCID = :BDCODCID into :BDCODUF;

      select BDOPCAOESOCIAL, BDDATAINITABELA, BDDATAININAOPERIOD, BDDATAINIPERIOD, BDDATAINISST, BDREFINITABELA, BDREFININAOPERIOD, BDREFINIPERIOD,
             BDREFINISST, BDGRUPO, BDREFINIDCTFWEB
      from VRH_ESOCIAL_TFASEAMENTO where BDCODEMP = :BDCODEMP
      into :BDOPCAOESOCIAL, :BDDATAINITABELA, :BDDATAININAOPERIOD, :BDDATAINIPERIOD, :BDDATAINISST, :BDREFINITABELA, :BDREFININAOPERIOD, :BDREFINIPERIOD,
           :BDREFINISST, :BDGRUPO, :BDREFINIDCTFWEB;

      select first 1 BDCODCLATRI
      from VRHF_BASE_TEMPESOCIAL
      where BDCODEMP = :BDCODEMP and BDREFEMP <= :pranomes
      order by BDREFEMP desc
      into :BDCODCLATRI;

      select first 1 BDCATSEFIPEMP
      from VRHF_BASE_TEMPSEFIP
      where BDCODEMP = :BDCODEMP and BDREFEMP <= :pranomes
      order by BDREFEMP desc
      into :BDCATSEFIPEMP;

      BDNROPROPEMP = null;
      select first 1 BDNROPROPSOC from SP_SOCIOPROPRIETARIO('EMP.BDCODEMP = '||:BDCODEMP, :pranomes) into :BDNROPROPEMP;
      BDNROPROPEMP = coalesce(BDNROPROPEMP, 0);

      if (BDNROPROPEMP <= 0) then
         BDNROPROPEMP = wnroprop;

      suspend;
    end
end^


create or alter procedure SP_VRHF_GETESTABILIDADE (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCODSINTRAB integer,
    PRANOMES integer,
    PRDATARESC date = null,
    PRPREVIADEDESCISAO smallint = 0)
returns (
    BDDATAETB date,
    BDDIASETB integer,
    BDGRUPOSITETB integer,
    BDCODVER integer,
    BDTIPOETB integer,
    BDDIASFERETB DM_BOOLEAN)
as
declare variable WDATARESC date;
declare variable WDATAPARTO date;
declare variable WDATAINI date;
declare variable WDATAFIM date;
declare variable WGRUPOSIT integer;
declare variable WDIAS integer;
declare variable WEMP integer;
declare variable WCOL integer;
begin
  wdataresc = null;

  if (prdataresc is null) then
     begin
       if (coalesce(:prpreviadedescisao, 0) > 0) then
          select first 1 BDDATANOTIFPREV from VRH_EMP_TRESCISAO_PREVIA where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFRESCISAOPREV = :pranomes into :wdataresc;
       else
          select first 1 BDDATANOTIF from VRH_EMP_TRESCISAO where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFRESCISAO = :pranomes into :wdataresc;
     end
  else
     wdataresc = prdataresc;

  for select BDDIASETB, BDGRUPOSITETB, BDCODVER, BDTIPOETB, BDDIASFERETB
      from VRH_BASE_TPREPESTAB
      where BDCODSINTRAB = :prcodsintrab
  into :BDDIASETB, :BDGRUPOSITETB, :BDCODVER, :BDTIPOETB, :BDDIASFERETB
  do
    begin
      BDDIASETB     = coalesce(:BDDIASETB, 0);
      BDGRUPOSITETB = coalesce(:BDGRUPOSITETB, 0);
      BDTIPOETB     = coalesce(:BDTIPOETB, 0);
      BDDIASFERETB  = trim(upper(coalesce(:BDDIASFERETB, 'FALSE')));

      BDDATAETB  = null;
      wdataparto = null;
      wdataini   = null;
      wdatafim   = null;
      wgruposit  = null;

      if (wdataresc is not null) then
         begin
           -- Afastamento
           if (BDTIPOETB = 0) then
              begin
                for select SIT.BDDATAPARTOSIT, SIT.BDDATAINISIT, SIT.BDDATAFIMSIT, PSIT.BDGRUPOSIT
                    from VRH_EMP_TSITCOL SIT
                    join VRH_BASE_TPREPSIT PSIT on (PSIT.BDCODSIT = SIT.BDCODSIT)
                    where SIT.BDCODEMP = :prcodemp and SIT.BDCODCOL = :prcodcol and SIT.BDDATAINISIT is not null and
                       PSIT.BDGRUPOSIT = :BDGRUPOSITETB and DATEADD(DAY,:BDDIASETB,SIT.BDDATAFIMSIT) >= :wdataresc
                into :wdataparto, :wdataini, :wdatafim, :wgruposit
                do
                  begin
                    if (coalesce(wgruposit, 0) in (0, 4)) then
                       BDDATAETB = COALESCE(:wdataparto, :wdataini) + :BDDIASETB - 1;
                    else
                       BDDATAETB = :wdatafim + :BDDIASETB - 1;
                    suspend;
                  end
              end
           else
           -- Mandato CIPA
           if (BDTIPOETB = 1) then
              begin
                for select BDFIMCIPA
                    from VRH_EMP_TMANDCIPA
                    where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and ((BDFIMCIPA IS NULL) or (BDFIMCIPA + :BDDIASETB >= :wdataresc))
                into :wdatafim
                do
                  begin
                    if (wdatafim is not null) then
                       BDDATAETB = :wdatafim + :BDDIASETB;

                    suspend;
                  end
              end
           else
           -- Férias
           if (BDTIPOETB = 2) then
              begin
                for select BDFIMPERGOZOFE, BDQTDGOZOFE
                    from VRH_EMP_TFERIAS
                    where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDFIMPERGOZOFE is not null and
                          ((BDFIMPERGOZOFE + :BDDIASETB >= :wdataresc) OR (BDFIMPERGOZOFE + BDQTDGOZOFE >= :wdataresc))
                into :wdatafim, :wdias
                do
                  begin
                    if (BDDIASFERETB = 'TRUE') then
                       BDDATAETB = :wdatafim + :wdias;
                    else
                       BDDATAETB = :wdatafim + :BDDIASETB;

                    suspend;
                  end
              end
         end
    end

  /* Verifica estabilidades de Transferido */
  for select BDCODEMPORIG, BDCODCOLORIG
      from VRH_EMP_TTRANSCOL
      where BDCODEMPDEST = :prcodemp and BDCODCOLDEST = :prcodcol
  into :wemp, :wcol
  do
    begin
      for select BDDATAETB, BDDIASETB, BDGRUPOSITETB, BDCODVER, BDTIPOETB, BDDIASFERETB
          from SP_VRHF_GETESTABILIDADE(:wemp, :wcol, :prcodsintrab, :pranomes, :wdataresc, :prpreviadedescisao)
      into :BDDATAETB, :BDDIASETB, :BDGRUPOSITETB, :BDCODVER, :BDTIPOETB, :BDDIASFERETB
      do
        suspend;
    end
end^

/* Restore proc. body: SP_VRHF_GETFAIXASSAUDE */
create or alter procedure SP_VRHF_GETFAIXASSAUDE (
    PRPLANOSAUDE integer,
    PRANOMES integer)
returns (
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDORDEM integer,
    BDIDADE integer,
    BDVALOR DM_NUMERIC_15_2)
as
declare variable WREFFAIXA integer;
begin
  if (coalesce(prplanosaude, 0) > 0) then
     begin
       for select BDCODOPERADORA, BDCODCONVENIO, max(BDREF)
           from VRH_BASE_FAIXAS_CONVENIOS
           where BDCODPLACONVSAU = :prplanosaude and BDREF <= :pranomes
           group by BDCODOPERADORA, BDCODCONVENIO
       into :BDCODOPERADORA, :BDCODCONVENIO, :wreffaixa do
         begin
           for select BDORDEM, BDIDADE, cast(BDVALOR as dm_numeric_15_2)
               from VRH_BASE_FAIXAS_CONVENIOS
               where BDCODPLACONVSAU = :prplanosaude and BDCODOPERADORA = :BDCODOPERADORA and BDCODCONVENIO = :BDCODCONVENIO and BDREF = :wreffaixa
               order by BDIDADE, BDORDEM
           into :BDORDEM, :BDIDADE, :BDVALOR do
             suspend;
         end
    end
end^

create or alter procedure SP_VRHF_GETFERIASSEMUMTERCORESC (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer,
    PRPREVIARESCISAO smallint = 0)
returns (
    BDTIPOFER integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDCODVER integer,
    BDREFAUXVFE DM_NUMERIC_15_2,
    BDREFVFE DM_NUMERIC_15_2,
    BDVALVFE DM_NUMERIC_15_2,
    BDVALIFE DM_NUMERIC_15_2,
    BDIGNREFAVFE DM_BOOLEAN,
    BDIGNREFVFE DM_BOOLEAN,
    BDIGNVALVFE DM_BOOLEAN,
    BDORVERBAFE integer,
    BDCOMPESP varchar(300),
    BDFORMREFAUX varchar(5000),
    BDFORMREF varchar(5000),
    BDFORMVAL varchar(5000),
    BDCLAVER varchar(20))
as
declare variable WSQL varchar(2000);
declare variable WDATARESC date;
begin
  if (coalesce(prpreviarescisao, 0) > 0) then
     wsql = 'select BDDATARESCISAOPREV from VRH_EMP_TRESCISAO_PREVIA where BDCODEMP = '||prcodemp||' and BDCODCOL = '||prcodcol||' and BDREFRESCISAOPREV = '||pranomes;
  else
     wsql = 'select BDDATARESCISAO from VRH_EMP_TRESCISAO where BDCODEMP = '||prcodemp||' and BDCODCOL = '||prcodcol||' and BDREFRESCISAO = '||pranomes;


  for execute statement wsql
  into :wdataresc
  do
    begin
      for select BDINIPERAQUISFE, BDCODFE
          from VRH_EMP_TFERIAS
          where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDINIPERGOZOFE >= '03-01-2020'
      into :BDINIPERAQUISFE, :BDCODFE
      do
        begin
          -- Férias normais
          for select 0, FER.BDCODVER, cast(FER.BDREFVFE as dm_numeric_15_2), cast(FER.BDVALVFE as dm_numeric_15_2), FER.BDIGNREFVFE, FER.BDIGNVALVFE,
                     cast(FER.BDREFAUXVFE as dm_numeric_15_2), FER.BDORVERBAFE, cast(FER.BDVALIFE as dm_numeric_15_2), FER.BDIGNREFAVFE, FER.BDCOMPESP, FER.BDFORMREFAUX,
                     FER.BDFORMREF, FER.BDFORMVAL, V.BDCLAVER
              from VRHF_EMP_TVERBAFE FER
              join VRH_BASE_TVERBAS V on (V.BDCODVER = FER.BDCODVER)
              where FER.BDCODEMP = :prcodemp and FER.BDCODCOL = :prcodcol and FER.BDINIPERAQUISFE = :BDINIPERAQUISFE and FER.BDCODFE = :BDCODFE and
                    not exists (select first 1 FERUMTERCO.BDCODEMP, FERUMTERCO.BDCODCOL
                                from VRHF_EMP_TVERBAFE FERUMTERCO
                                join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FERUMTERCO.BDCODVER)
                                where VER.BDCLAVER starting with '3.002' and FERUMTERCO.BDCODEMP = FER.BDCODEMP and FERUMTERCO.BDCODCOL = FER.BDCODCOL and
                                      FERUMTERCO.BDINIPERAQUISFE = FER.BDINIPERAQUISFE and FERUMTERCO.BDCODFE = FER.BDCODFE)
          into :BDTIPOFER, :BDCODVER, :BDREFVFE, :BDVALVFE, :BDIGNREFVFE, :BDIGNVALVFE, :BDREFAUXVFE, :BDORVERBAFE,
               :BDVALIFE, :BDIGNREFAVFE, :BDCOMPESP, :BDFORMREFAUX, :BDFORMREF, :BDFORMVAL, :BDCLAVER
          do
            suspend;
        end

      for select BDINIPERAQUISFE, BDCODFE
          from VRH_EMP_TFERIAS
          where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and ((BDINIPERGOZOFE >= '03-01-2020') or (coalesce(BDREFPAGABOFE, 0) >= 202003))
      into :BDINIPERAQUISFE, :BDCODFE
      do
        begin
          -- Abono pecuniário
          for select 1, FER.BDCODVER, cast(FER.BDREFVFE as dm_numeric_15_2), cast(FER.BDVALVFE as dm_numeric_15_2), FER.BDIGNREFVFE, FER.BDIGNVALVFE,
                     cast(FER.BDREFAUXVFE as dm_numeric_15_2), FER.BDORVERBAFE, cast(FER.BDVALIFE as dm_numeric_15_2), FER.BDIGNREFAVFE, FER.BDCOMPESP, FER.BDFORMREFAUX,
                     FER.BDFORMREF, FER.BDFORMVAL, V.BDCLAVER
              from VRHF_EMP_TVERBAFE FER
              join VRH_BASE_TVERBAS V on (V.BDCODVER = FER.BDCODVER)
              where FER.BDCODEMP = :prcodemp and FER.BDCODCOL = :prcodcol and FER.BDINIPERAQUISFE = :BDINIPERAQUISFE and FER.BDCODFE = :BDCODFE and
                    not exists (select first 1 FERUMTERCO.BDCODEMP, FERUMTERCO.BDCODCOL
                                from VRHF_EMP_TVERBAFE FERUMTERCO
                                join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FERUMTERCO.BDCODVER)
                                where VER.BDCLAVER starting with '3.004' and FERUMTERCO.BDCODEMP = FER.BDCODEMP and FERUMTERCO.BDCODCOL = FER.BDCODCOL and
                                      FERUMTERCO.BDINIPERAQUISFE = FER.BDINIPERAQUISFE and FERUMTERCO.BDCODFE = FER.BDCODFE)
          into :BDTIPOFER, :BDCODVER, :BDREFVFE, :BDVALVFE, :BDIGNREFVFE, :BDIGNVALVFE, :BDREFAUXVFE, :BDORVERBAFE,
               :BDVALIFE, :BDIGNREFAVFE, :BDCOMPESP, :BDFORMREFAUX, :BDFORMREF, :BDFORMVAL, :BDCLAVER
          do
            suspend;
        end



      for select BDINIPERAQUISFE, BDCODFE
          from VRH_EMP_TFERIAS
          where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDINIPERGOZOFE >= '03-01-2020'
      into :BDINIPERAQUISFE, :BDCODFE
      do
        begin
          -- Férias em dobro
          for select 2, FER.BDCODVER, cast(FER.BDREFVFE as dm_numeric_15_2), cast(FER.BDVALVFE as dm_numeric_15_2), FER.BDIGNREFVFE, FER.BDIGNVALVFE,
                     cast(FER.BDREFAUXVFE as dm_numeric_15_2), FER.BDORVERBAFE, cast(FER.BDVALIFE as dm_numeric_15_2), FER.BDIGNREFAVFE, FER.BDCOMPESP, FER.BDFORMREFAUX,
                     FER.BDFORMREF, FER.BDFORMVAL, V.BDCLAVER
              from VRHF_EMP_TVERBAFE FER
              join VRH_BASE_TVERBAS V on (V.BDCODVER = FER.BDCODVER)
              where FER.BDCODEMP = :prcodemp and FER.BDCODCOL = :prcodcol and FER.BDINIPERAQUISFE = :BDINIPERAQUISFE and FER.BDCODFE = :BDCODFE and
                    exists (select first 1 DOB.BDCODEMP, DOB.BDCODCOL
                            from VRHF_EMP_TVERBAFE DOB
                            join VRH_BASE_TVERBAS VER on (VER.BDCODVER = DOB.BDCODVER)
                            where VER.BDCLAVER starting with '3.005' and DOB.BDCODEMP = FER.BDCODEMP and DOB.BDCODCOL = FER.BDCODCOL and
                                  DOB.BDINIPERAQUISFE = FER.BDINIPERAQUISFE and DOB.BDCODFE = FER.BDCODFE) and
                    not exists (select first 1 FERUMTERCO.BDCODEMP, FERUMTERCO.BDCODCOL
                                from VRHF_EMP_TVERBAFE FERUMTERCO
                                join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FERUMTERCO.BDCODVER)
                                where VER.BDCLAVER starting with '3.006' and FERUMTERCO.BDCODEMP = FER.BDCODEMP and FERUMTERCO.BDCODCOL = FER.BDCODCOL and
                                      FERUMTERCO.BDINIPERAQUISFE = FER.BDINIPERAQUISFE and FERUMTERCO.BDCODFE = FER.BDCODFE)
          into :BDTIPOFER, :BDCODVER, :BDREFVFE, :BDVALVFE, :BDIGNREFVFE, :BDIGNVALVFE, :BDREFAUXVFE, :BDORVERBAFE,
               :BDVALIFE, :BDIGNREFAVFE, :BDCOMPESP, :BDFORMREFAUX, :BDFORMREF, :BDFORMVAL, :BDCLAVER
          do
            suspend;
        end

      for select BDINIPERAQUISFE, BDCODFE
          from VRH_EMP_TFERIAS
          where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and ((BDINIPERGOZOFE >= '03-01-2020') or (coalesce(BDREFPAGABOFE, 0) >= 202003))
      into :BDINIPERAQUISFE, :BDCODFE
      do
        begin
          -- Abono pecuniário
          for select 3, FER.BDCODVER, cast(FER.BDREFVFE as dm_numeric_15_2), cast(FER.BDVALVFE as dm_numeric_15_2), FER.BDIGNREFVFE, FER.BDIGNVALVFE,
                     cast(FER.BDREFAUXVFE as dm_numeric_15_2), FER.BDORVERBAFE, cast(FER.BDVALIFE as dm_numeric_15_2), FER.BDIGNREFAVFE, FER.BDCOMPESP, FER.BDFORMREFAUX,
                     FER.BDFORMREF, FER.BDFORMVAL, V.BDCLAVER
              from VRHF_EMP_TVERBAFE FER
              join VRH_BASE_TVERBAS V on (V.BDCODVER = FER.BDCODVER)
              where FER.BDCODEMP = :prcodemp and FER.BDCODCOL = :prcodcol and FER.BDINIPERAQUISFE = :BDINIPERAQUISFE and FER.BDCODFE = :BDCODFE and
                    exists (select first 1 DOB.BDCODEMP, DOB.BDCODCOL
                            from VRHF_EMP_TVERBAFE DOB
                            join VRH_BASE_TVERBAS VER on (VER.BDCODVER = DOB.BDCODVER)
                            where VER.BDCLAVER starting with '3.007' and DOB.BDCODEMP = FER.BDCODEMP and DOB.BDCODCOL = FER.BDCODCOL and
                                  DOB.BDINIPERAQUISFE = FER.BDINIPERAQUISFE and DOB.BDCODFE = FER.BDCODFE) and
                    not exists (select first 1 FERUMTERCO.BDCODEMP, FERUMTERCO.BDCODCOL
                                from VRHF_EMP_TVERBAFE FERUMTERCO
                                join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FERUMTERCO.BDCODVER)
                                where VER.BDCLAVER starting with '3.008' and FERUMTERCO.BDCODEMP = FER.BDCODEMP and FERUMTERCO.BDCODCOL = FER.BDCODCOL and
                                      FERUMTERCO.BDINIPERAQUISFE = FER.BDINIPERAQUISFE and FERUMTERCO.BDCODFE = FER.BDCODFE)
          into :BDTIPOFER, :BDCODVER, :BDREFVFE, :BDVALVFE, :BDIGNREFVFE, :BDIGNVALVFE, :BDREFAUXVFE, :BDORVERBAFE,
               :BDVALIFE, :BDIGNREFAVFE, :BDCOMPESP, :BDFORMREFAUX, :BDFORMREF, :BDFORMVAL, :BDCLAVER
          do
            suspend;
        end
    end
end^

create or alter procedure SP_VRHF_GETFUNCOESCOL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRDATAULTDIA date)
returns (
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDDATAINI date,
    BDDATAFIM date)
as
begin
  BDCODPLAFUC = null;
  BDCODTFUC   = null;
  BDDATAINI   = null;
  BDDATAFIM   = null;

  for select BDCODPLAFUC, BDCODTFUC, BDDATACOL
      from VRH_EMP_TCOL_VINCDIA
      where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDDATACOL <= :prdataultdia
      group by BDCODPLAFUC, BDCODTFUC, BDDATACOL
      order by BDDATACOL
  into :BDCODPLAFUC, :BDCODTFUC, :BDDATAINI
  do
    begin
      BDDATAFIM = null;
      select first 1 BDDATACOL
      from VRH_EMP_TCOL_VINCDIA
      where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDDATACOL > :BDDATAINI and BDDATACOL <= :prdataultdia
      order by BDDATACOL
      into :BDDATAFIM;

      if (BDDATAFIM is not null) then
         begin
           BDDATAFIM = BDDATAFIM - 1;
           suspend;
         end
    end

  if (BDCODPLAFUC is not null and BDDATAINI is not null and BDDATAFIM is null) then
     begin
       BDDATAFIM = :prdataultdia;
       suspend;
     end
end^

/* Restore proc. body: SP_VRHF_GETHORARIOCOL */
create or alter procedure SP_VRHF_GETHORARIOCOL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRULTDIA date)
returns (
    BDDATACOL date,
    BDDIASEMQH integer,
    BDTIPODSR integer,
    BDCODQHH integer,
    BDDESQHH varchar(50),
    BDCODQHHS integer,
    BDQHHSENT time,
    BDQHHSSAI time,
    BDHORFLEXIVEL integer)
as
declare variable WPRIDIA date;
declare variable WDATAINI date;
declare variable WDATAFIM date;
declare variable WDT varchar(10);
declare variable WCODPQUA integer;
declare variable WCODQH integer;
begin
  wdt = cast(prultdia as varchar(10));
  wpridia = cast((substring(wdt from 1 for 8)||'01') as DATE);
  select first 1 BDDATACOL from VRH_EMP_TCOL_VINCDIA where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDDATACOL <= :prultdia order by BDDATACOL desc into :wdatafim;
  select first 1 BDDATACOL from VRH_EMP_TCOL_VINCDIA where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDDATACOL <= :wpridia order by BDDATACOL desc into :wdataini;

  for select BDDATACOL, BDCODPQUA, BDCODQH
      from VRH_EMP_TCOL_VINCDIA
      where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDDATACOL between :wdataini and :wdatafim
      order by BDDATACOL DESC
  into :BDDATACOL, :wcodpqua, :wcodqh
  do
    begin
      for select TQH.BDDIASEMQH,TQH.BDTIPODSR, coalesce(TQH.BDCODQHH, -1), HORARIO.BDDESQHH, HORAS.BDCODQHHS, HORAS.BDQHHSENT,
                 HORAS.BDQHHSSAI, HORARIO.BDHORFLEXIVEL
          from VRH_BASE_TQH_DIAS TQH
          left outer join VRH_BASE_TQH_HORARIO HORARIO on (HORARIO.BDCODQHH = TQH.BDCODQHH)
          left outer join VRH_BASE_TQH_HORAS HORAS on (HORAS.BDCODQHH = TQH.BDCODQHH)
          where TQH.BDCODPQUA = :wcodpqua and TQH.BDCODQH = :wcodqh
      into :BDDIASEMQH, :BDTIPODSR, :BDCODQHH, :BDDESQHH, :BDCODQHHS, :BDQHHSENT, :BDQHHSSAI, :BDHORFLEXIVEL
      do
        suspend;
    end
end^

create or alter procedure SP_VRHF_GETINSSMULTVINC (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDDATATRF date,
    BDBINSS DM_NUMERIC_15_2,
    BDBINSSFEFOL DM_NUMERIC_15_2,
    BDINSSFEFOL DM_NUMERIC_15_2,
    BDINSS DM_NUMERIC_15_2,
    BDBIRRF DM_NUMERIC_15_2,
    BDIRRF DM_NUMERIC_15_2,
    BDDEP DM_NUMERIC_15_2,
    BDBINSS13 DM_NUMERIC_15_2,
    BDINSS13 DM_NUMERIC_15_2,
    BDCODPTRAN integer)
as
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  for select BDCODEMPORIG, BDCODCOLORIG, BDCODPTRAN, BDDATATRF
      from VRH_EMP_TTRANSCOL
      where BDCODEMPDEST = :prcodemp and BDCODCOLDEST = :prcodcol
  into :wcodemporig, :wcodcolorig, :BDCODPTRAN, :BDDATATRF
  do 
    begin
      for select BDBINSSFN, BDBINSSFEFOLFN, BDINSSFEFOLFN, BDINSSFN,
                 BDBIRRFFN, BDIRRFFN, BDDEPFN, BDBINSS13FN, BDINSS13FN
          from VRHF_EMP_TFOLHANORMAL 
          where BDCODEMP = :wcodemporig and BDCODCOL = :wcodcolorig and BDREFFN = :pranomes
      into :BDBINSS, :BDBINSSFEFOL, :BDINSSFEFOL, :BDINSS, :BDBIRRF, :BDIRRF, :BDDEP, :BDBINSS13, :BDINSS13
      do
        suspend;

      for select sum(BDBINSSFT), sum(BDBINSSFEFOLFT), sum(BDINSSFEFOLFT), sum(BDINSSFT),
                 sum(BDBIRRFFT), sum(BDIRRFFT), sum(BDDEPFT), sum(BDBINSS13FT), sum(BDINSS13FT) 
          from VRHF_EMP_TFOLHATOMADOR
          where BDCODEMP = :wcodemporig and BDCODCOL = :wcodcolorig and BDREFTOMADOR = :pranomes
      into :BDBINSS, :BDBINSSFEFOL, :BDINSSFEFOL, :BDINSS, :BDBIRRF, :BDIRRF, :BDDEP, :BDBINSS13, :BDINSS13
      do
        suspend;


      for select sum(BDBINSSFN), sum(BDBINSSFEFOLFN), sum(BDINSSFEFOLFN), sum(BDINSSFN),
                 sum(BDBIRRFFN), sum(BDIRRFFN), sum(BDDEPFN), sum(BDBINSS13FN), sum(BDINSS13FN)
          from VRHF_EMP_TFOLHAINT
          where BDCODEMP = :wcodemporig and BDCODCOL = :wcodcolorig and bdreffn = :pranomes
      into :BDBINSS, :BDBINSSFEFOL, :BDINSSFEFOL, :BDINSS, :BDBIRRF, :BDIRRF, :BDDEP, :BDBINSS13, :BDINSS13
      do
        suspend;

      for select sum(BDBINSSFT), sum(BDBINSSFEFOLFT), sum(BDINSSFEFOLFT), sum(BDINSSFT),
                 sum(BDBIRRFFT), sum(BDIRRFFT), sum(BDDEPFT), sum(BDBINSS13FT), sum(BDINSS13FT)
          from VRHF_EMP_TFOLHATOMINT
          where BDCODEMP = :wcodemporig and BDCODCOL = :wcodcolorig and BDREFTOMADOR = :pranomes
      into :BDBINSS, :BDBINSSFEFOL, :BDINSSFEFOL, :BDINSS, :BDBIRRF, :BDIRRF, :BDDEP, :BDBINSS13, :BDINSS13
      do
        suspend;

      for select BDDATATRF, BDBINSS, BDBINSSFEFOL, BDINSSFEFOL, BDINSS, BDBIRRF, BDIRRF, BDDEP, BDBINSS13, BDINSS13, BDCODPTRAN
          from SP_VRHF_GETINSSMULTVINC(:wcodemporig, :wcodcolorig, :pranomes)
      into :BDDATATRF, :BDBINSS, :BDBINSSFEFOL, :BDINSSFEFOL, :BDINSS, :BDBIRRF, :BDIRRF, :BDDEP, :BDBINSS13, :BDINSS13, :BDCODPTRAN
      do
        suspend;
    end
end^

create or alter procedure SP_VRHF_GETITINERARIO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDCODITI integer,
    BDDIASEMITF integer,
    BDREFITF integer,
    BDHORARIOITF time,
    BDQTDITF integer,
    BDVALITI DM_NUMERIC_15_2)
as
begin
  for select max(BDREFITF)
      from VRHF_EMP_TITICOL
      where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFITF <= :pranomes
  into :BDREFITF
  do
    begin
      for select BDCODITI, BDDIASEMITF, BDHORARIOITF, BDQTDITF
          from VRHF_EMP_TITICOL
          where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFITF = :BDREFITF
      into :BDCODITI, :BDDIASEMITF, :BDHORARIOITF, :BDQTDITF
      do
        begin
          BDVALITI = 0;
          select first 1 cast(BDVALITI as dm_numeric_15_2)
          from VRHF_BASE_TITINERARIO_REF
          where BDCODITI = :BDCODITI and BDREFERENCIA <= :pranomes
          order by BDREFERENCIA desc
          into :BDVALITI;
          BDVALITI = coalesce(BDVALITI, 0.00);
          suspend;
        end
    end
end^

create or alter procedure SP_VRHF_GETPERIODOSFERIAS (
    PRCODEMP integer,
    PRCODCOL integer)
returns (
    BDINIPERAQUISFE date,
    BDFIMPERAQUISFE date,
    BDCODFE integer,
    BDINIPERGOZOFE date,
    BDFIMPERGOZOFE date,
    BDDATAPAGFE date,
    BDQTDGOZOFE numeric(18,6),
    BDQTDABONOFE numeric(18,6),
    BDSALDOINIFE numeric(18,6),
    BDSALDOFIMFE numeric(18,6),
    BDBASEIRFE numeric(18,6),
    BDALIQIRFE numeric(18,6),
    BDVALORIRFE numeric(18,6),
    BDBASEINSSFE numeric(18,6),
    BDALIQINSSFE numeric(18,6),
    BDVALORINSSFE numeric(18,6),
    BDDEPFE numeric(18,6),
    BDSALBASEFE numeric(18,6),
    BDSALBASEHEFE numeric(18,6),
    BDDATABAIXAFE date,
    BDCOLETIVASFE DM_BOOLEAN,
    BDREFPAGABOFE integer,
    BDBASEFGTSFE numeric(18,6),
    BDVALORFGTSFE numeric(18,6),
    BDVALORFGTSCSFE numeric(18,6),
    BDMAIORREMFE numeric(18,6),
    BDBSALFAMFE numeric(18,6),
    BDSALFAMFE numeric(18,6),
    BDCOMPETENCIAFE varchar(7),
    BDFALTASFE numeric(18,6),
    BDFERIADOSFE integer,
    BDBASEIROUTFE numeric(18,6),
    BDVALORIROUTFE numeric(18,6),
    BDDEPIROUTFE numeric(18,6),
    BDESTPROVFE numeric(18,6),
    BDBASEPISFE numeric(18,6),
    BDBRATAPOFE numeric(18,6),
    BDCREDITOFE numeric(18,6),
    BDDEBITOFE numeric(18,6),
    BDLIQUIDO numeric(18,6),
    BDREFINIFE integer,
    BDREFFIMFE integer,
    BDCALCA13FE DM_BOOLEAN,
    BDTIPOA13FE integer,
    BDPERCA13FE numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDDATAPROCFE date,
    BDHORAPROCFE time,
    BDORDEM integer,
    BDDATAAVISO date,
    BDSALDOFINALSINDFE numeric(18,6),
    BDDIASLICFE numeric(18,6),
    BDTEMPOSERVFE integer,
    BDVALSALMINVIGENTE numeric(18,6),
    BDENVIOUESOCIAL DM_BOOLEAN,
    BDENVIOUPGTOESOCIAL DM_BOOLEAN,
    BDIDDEMONSTRATIVO varchar(30),
    BDFOLHAAUTOMATICA DM_BOOLEAN,
    BDRECIBOESOCIAL varchar(30),
    BDCODEVT integer,
    BDCODEVTFIM integer,
    BDREFPAGFE integer)
as
begin
  for select BDINIPERAQUISFE, BDCODFE, BDINIPERGOZOFE, BDFIMPERAQUISFE, BDFIMPERGOZOFE, BDDATAPAGFE, BDQTDGOZOFE, BDQTDABONOFE, BDSALDOINIFE, BDSALDOFIMFE,
             BDBASEIRFE, BDALIQIRFE, BDVALORIRFE, BDBASEINSSFE, BDALIQINSSFE, BDVALORINSSFE, BDDEPFE, BDSALBASEFE, BDSALBASEHEFE, BDDATABAIXAFE, BDCOLETIVASFE,
             BDREFPAGABOFE, BDBASEFGTSFE, BDVALORFGTSFE, BDVALORFGTSCSFE, BDMAIORREMFE, BDBSALFAMFE, BDSALFAMFE, BDCOMPETENCIAFE, BDFALTASFE, BDFERIADOSFE,
             BDBASEIROUTFE, BDVALORIROUTFE, BDDEPIROUTFE, BDESTPROVFE, BDBASEPISFE, BDBRATAPOFE, BDCREDITOFE, BDDEBITOFE, BDLIQUIDO, BDREFINIFE, BDREFFIMFE,
             BDCALCA13FE, BDTIPOA13FE, BDPERCA13FE, BDBFGTS13, BDFGTS13, BDDATAPROCFE, BDHORAPROCFE, BDORDEM, BDDATAAVISO, BDSALDOFINALSINDFE, BDDIASLICFE,
             BDTEMPOSERVFE, BDVALSALMINVIGENTE, BDENVIOUESOCIAL, BDENVIOUPGTOESOCIAL, BDIDDEMONSTRATIVO, BDFOLHAAUTOMATICA, BDRECIBOESOCIAL, BDCODEVT,
             BDCODEVTFIM, BDREFPAGFE
      from VRH_EMP_TFERIAS
      where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol
      order by BDINIPERAQUISFE, BDCODFE
  into :BDINIPERAQUISFE, :BDCODFE, :BDINIPERGOZOFE, :BDFIMPERAQUISFE, :BDFIMPERGOZOFE, :BDDATAPAGFE, :BDQTDGOZOFE, :BDQTDABONOFE, :BDSALDOINIFE, :BDSALDOFIMFE,
       :BDBASEIRFE, :BDALIQIRFE, :BDVALORIRFE, :BDBASEINSSFE, :BDALIQINSSFE, :BDVALORINSSFE, :BDDEPFE, :BDSALBASEFE, :BDSALBASEHEFE, :BDDATABAIXAFE, :BDCOLETIVASFE,
       :BDREFPAGABOFE, :BDBASEFGTSFE, :BDVALORFGTSFE, :BDVALORFGTSCSFE, :BDMAIORREMFE, :BDBSALFAMFE, :BDSALFAMFE, :BDCOMPETENCIAFE, :BDFALTASFE, :BDFERIADOSFE,
       :BDBASEIROUTFE, :BDVALORIROUTFE, :BDDEPIROUTFE, :BDESTPROVFE, :BDBASEPISFE, :BDBRATAPOFE, :BDCREDITOFE, :BDDEBITOFE, :BDLIQUIDO, :BDREFINIFE, :BDREFFIMFE,
       :BDCALCA13FE, :BDTIPOA13FE, :BDPERCA13FE, :BDBFGTS13, :BDFGTS13, :BDDATAPROCFE, :BDHORAPROCFE, :BDORDEM, :BDDATAAVISO, :BDSALDOFINALSINDFE, :BDDIASLICFE,
       :BDTEMPOSERVFE, :BDVALSALMINVIGENTE, :BDENVIOUESOCIAL, :BDENVIOUPGTOESOCIAL, :BDIDDEMONSTRATIVO, :BDFOLHAAUTOMATICA, :BDRECIBOESOCIAL, :BDCODEVT,
       :BDCODEVTFIM, :BDREFPAGFE
   do
    suspend;
end^

create or alter procedure SP_VRHF_GETREDUCAOSALARIAL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRDTINI date,
    PRDTFIM date)
returns (
    BDCODREDSAL integer,
    BDDATAINIREDSAL date,
    BDDATAFIMREDSAL date,
    BDCODMAS integer,
    BDPERCREDSAL DM_NUMERIC_15_2,
    BDREDSAL DM_BOOLEAN,
    BDREDJOR DM_BOOLEAN,
    BDMESREDSAL DM_NUMERIC_15_2,
    BDSEMREDSAL DM_NUMERIC_15_2,
    BDDIAREDSAL DM_NUMERIC_15_2,
    BDSALBASEREDUZIDO DM_NUMERIC_15_2,
    BDQTDDIASREDSAL integer,
    BDDIASACORDOINI integer,
    BDREFINIREDSAL integer,
    BDREFFIMREDSAL integer)
as
begin
  for select BDCODREDSAL, BDDATAINIREDSAL, BDDATAFIMREDSAL, BDCODMAS, BDPERCREDSAL, BDREDSAL, BDREDJOR, BDMESREDSAL, BDSEMREDSAL, BDDIAREDSAL,
             BDSALBASEREDUZIDO, BDQTDDIASREDSAL, BDDIASACORDOINI, BDREFINIREDSAL, BDREFFIMREDSAL
      from VRH_EMP_TREDUCAOCOL
      where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDDATAINIREDSAL <= :prdtfim and BDDATAFIMREDSAL >= :prdtini
  into :BDCODREDSAL, :BDDATAINIREDSAL, :BDDATAFIMREDSAL, :BDCODMAS, :BDPERCREDSAL, :BDREDSAL, :BDREDJOR, :BDMESREDSAL, :BDSEMREDSAL, :BDDIAREDSAL,
       :BDSALBASEREDUZIDO, :BDQTDDIASREDSAL, :BDDIASACORDOINI, :BDREFINIREDSAL, :BDREFFIMREDSAL
  do
    suspend;
end^

create or alter procedure SP_VRHF_GETREFEICAO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDCODCONVREF integer,
    BDDIASEMCONVREF integer,
    BDREFCONVREF integer,
    BDQTDCONVREF integer,
    BDVALUNI DM_NUMERIC_15_2)
as
begin
  for select max(BDREFCONVREF)
      from VRHF_EMP_TCONVREFCOL
      where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFCONVREF <= :pranomes
  into :BDREFCONVREF
  do
    begin
      for select BDCODCONVREF, BDDIASEMCONVREF, BDQTDCONVREF
          from VRHF_EMP_TCONVREFCOL
          where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFCONVREF = :BDREFCONVREF
      into :BDCODCONVREF, :BDDIASEMCONVREF, :BDQTDCONVREF
      do
        begin
          BDVALUNI = 0;
          select first 1 cast(BDVALUNI as dm_numeric_15_2)
          from VRHF_BASE_TCONVREFEICAO_REF
          where BDCODCONVREF = :BDCODCONVREF and BDREF <= :pranomes
          order by BDREF desc
          into :BDVALUNI;
          BDVALUNI = coalesce(BDVALUNI, 0.00);
          suspend;
        end
    end
end^

create or alter procedure SP_VRHF_GETSINDICALANO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDTIPOPGTOSIND integer,
    BDREFSIND integer)
as
declare variable WREF integer;
declare variable WREFINI integer;
declare variable WCLAVER varchar(20);
declare variable WTEMCS smallint;
declare variable WTEMTX smallint;
declare variable WREFCS integer;
declare variable WREFTX integer;
declare variable WVALCS numeric(18,6);
declare variable WVALTX numeric(18,6);
begin
  wrefini = CAST((SUBSTRING(:pranomes from 1 for 4)||'01') AS INTEGER);
  wref    = null;
  wclaver = null;

  BDTIPOPGTOSIND  = null;
  BDREFSIND       = null;
  wtemcs          = 0;
  wtemtx          = 0;

  for select max(FN.BDREFFN), case when VER.BDCLAVER starting with '0.710.0.1' then '0.004.0.1'
                                   when VER.BDCLAVER starting with '0.710.0.3' then '0.004.0.3'
                                   else substring(VER.BDCLAVER from 1 for 9)
                              end BDCLAVER
      from (select BDREFFN, BDCODVER
            from VRHF_EMP_TVERBAFN
            where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFFN between :wrefini and :pranomes
            union all
            select BDREFTOMADOR, BDCODVER
            from VRHF_EMP_TVERBATOMADOR
            where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFTOMADOR between :wrefini and :pranomes
            union all
            select BDREFFN, BDCODVER
            from VRHF_EMP_TVERBAINT
            where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFFN between :wrefini and :pranomes
            union all
            select BDREFTOMADOR, BDCODVER
            from VRHF_EMP_TVERBATOMINT
            where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFTOMADOR between :wrefini and :pranomes
            ) FN
      join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER)
      where ((VER.BDCLAVER starting with '0.004.0.1') or (VER.BDCLAVER starting with '0.710.0.1') or
             (VER.BDCLAVER starting with '0.004.0.3') or (VER.BDCLAVER starting with '0.710.0.3'))
      group by BDCLAVER
  into :wref, :wclaver
  do
    begin
      if ((wclaver = '0.004.0.1') or (wclaver = '0.710.0.1')) then
         begin
           BDTIPOPGTOSIND  = 0;   -- Contribuição sindical
           BDREFSIND       = wref;
           wtemcs          = 1;
           suspend;
         end
      else
      if ((wclaver = '0.004.0.3') or (wclaver = '0.710.0.3')) then
         begin
           BDTIPOPGTOSIND  = 1;   -- Taxa assistencial
           BDREFSIND       = wref;
           wtemtx          = 1;
           suspend;
         end
    end

  /* FICHA FINANCEIRA */
  if ((wtemcs = 0) or (wtemtx = 0)) then
     begin
       BDTIPOPGTOSIND  = null;
       BDREFSIND       = null;
       wrefcs          = null;
       wreftx          = null;

       for select BDREFFRAIS, BDCONTRSINDFRAIS, BDCONTASSISTFRAIS
           from VRHF_EMP_TFICHARAIS
           where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFFRAIS between :wrefini and :pranomes and ((BDCONTRSINDFRAIS > 0) or (BDCONTASSISTFRAIS > 0))
       into :wref, :wvalcs, :wvaltx
       do
         begin
           if (coalesce(wvalcs, 0) > 0) then
              wrefcs = wref;
           if (coalesce(wvaltx, 0) > 0) then
              wreftx = wref;
         end

       if (wtemcs = 0 and coalesce(wrefcs, 0) > 0) then
          begin
            BDTIPOPGTOSIND = 0;
            BDREFSIND      = wrefcs;
            wtemcs         = 1;
            suspend;
          end

       if (wtemtx = 0 and coalesce(wreftx, 0) > 0) then
          begin
            BDTIPOPGTOSIND = 1;
            BDREFSIND      = wreftx;
            wtemtx         = 1;
            suspend;
          end
     end

  /* TRANSFERÊNCIAS */
  if ((wtemcs = 0) or (wtemtx = 0)) then
     begin
       BDTIPOPGTOSIND  = null;
       BDREFSIND       = null;

       for select max(FN.BDREFFN), case when VER.BDCLAVER starting with '0.710.0.1' then '0.004.0.1'
                                        when VER.BDCLAVER starting with '0.710.0.3' then '0.004.0.3'
                                        else substring(VER.BDCLAVER from 1 for 9)
                                   end BDCLAVER
           from (select FN.BDREFFN, FN.BDCODVER
                 from VRHF_EMP_TVERBAFN FN
                 join VRH_EMP_TTRANSCOL TRANS on (TRANS.BDCODEMPORIG = FN.BDCODEMP and TRANS.BDCODCOLORIG = FN.BDCODCOL)
                 where TRANS.BDCODEMPDEST = :prcodemp and TRANS.BDCODCOLDEST = :prcodcol and FN.BDREFFN between :wrefini and :pranomes
                 union all
                 select FN.BDREFTOMADOR, FN.BDCODVER
                 from VRHF_EMP_TVERBATOMADOR FN
                 join VRH_EMP_TTRANSCOL TRANS on (TRANS.BDCODEMPORIG = FN.BDCODEMP and TRANS.BDCODCOLORIG = FN.BDCODCOL)
                 where TRANS.BDCODEMPDEST = :prcodemp and TRANS.BDCODCOLDEST = :prcodcol and FN.BDREFTOMADOR between :wrefini and :pranomes
                 union all
                 select FN.BDREFFN, FN.BDCODVER
                 from VRHF_EMP_TVERBAINT FN
                 join VRH_EMP_TTRANSCOL TRANS on (TRANS.BDCODEMPORIG = FN.BDCODEMP and TRANS.BDCODCOLORIG = FN.BDCODCOL)
                 where TRANS.BDCODEMPDEST = :prcodemp and TRANS.BDCODCOLDEST = :prcodcol and FN.BDREFFN between :wrefini and :pranomes
                 union all
                 select FN.BDREFTOMADOR, FN.BDCODVER
                 from VRHF_EMP_TVERBATOMINT FN
                 join VRH_EMP_TTRANSCOL TRANS on (TRANS.BDCODEMPORIG = FN.BDCODEMP and TRANS.BDCODCOLORIG = FN.BDCODCOL)
                 where TRANS.BDCODEMPDEST = :prcodemp and TRANS.BDCODCOLDEST = :prcodcol and FN.BDREFTOMADOR between :wrefini and :pranomes
                 ) FN
           join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER)
           where ((VER.BDCLAVER starting with '0.004.0.1') or (VER.BDCLAVER starting with '0.710.0.1') or
                  (VER.BDCLAVER starting with '0.004.0.3') or (VER.BDCLAVER starting with '0.710.0.3'))
           group by BDCLAVER
       into :wref, :wclaver
       do
         begin
           if ((wtemcs = 0) and ((wclaver = '0.004.0.1') or (wclaver = '0.710.0.1'))) then
              begin
                BDTIPOPGTOSIND  = 0;   -- Contribuição sindical
                BDREFSIND       = wref;
                suspend;
              end
           else
           if ((wtemtx = 0) and ((wclaver = '0.004.0.3') or (wclaver = '0.710.0.3'))) then
              begin
                BDTIPOPGTOSIND  = 1;   -- Taxa assistencial
                BDREFSIND       = wref;
                wtemtx          = 1;
                suspend;
              end
         end
     end
end^

/* Restore proc. body: SP_VRHF_GETSINDICATO */
create or alter procedure SP_VRHF_GETSINDICATO (
    PRCODSINTRAB integer,
    PRANOMES integer)
returns (
    BDCODSINTRAB integer,
    BDDESCSINTRAB DM_BDDESCSINTRAB,
    BDMEDSITSINTRAB DM_BOOLEAN,
    BDMESESMEDSITSINTRAB integer,
    BDREFST integer,
    BDVERFERIST integer,
    BDVERMULRESST integer,
    BDCODPMS integer,
    BDPERABFERST DM_NUMERIC_7_4_ALIQ,
    BDDATBASEST integer,
    BDESTABST integer,
    BDPERCNOTST DM_NUMERIC_15_2,
    BDMESCSST integer,
    BDFERRESCST integer,
    BDFERDOBST integer,
    BDFERJCST integer,
    BDTIPODESCCONTRST integer,
    BDBASEADICST DM_NUMERIC_15_2,
    BDLIMITE13ST integer,
    BDPISOSAL DM_NUMERIC_15_2,
    BDSALMINGAR DM_NUMERIC_15_2,
    BDMESTXASST integer,
    BDTIPODESCTXASST integer,
    BDMESRESCMEDIASST DM_BOOLEAN,
    BDTIPOMESRESCMEDIASST integer,
    BDINIHORANOTST time,
    BDFIMHORANOTST time,
    BDLIMINARAVPREVST integer,
    BDQTDDIASANTPAG integer,
    BDINATIVO DM_BOOLEAN)
as
begin
  prcodsintrab = coalesce(prcodsintrab, 0);

       for select bdcodsintrab, BDDESCSINTRAB, BDMEDSITSINTRAB, BDMESESMEDSITSINTRAB
           from VRH_BASE_TSINDTRAB
           where BDCODSINTRAB = :prcodsintrab
       into :BDCODSINTRAB, :BDDESCSINTRAB, :BDMEDSITSINTRAB, :BDMESESMEDSITSINTRAB
       do
         begin
           select first 1 bdrefst, bdverferist, bdvermulresst, bdcodpms, bdperabferst, bddatbasest, bdestabst, bdpercnotst, bdmescsst, bdferrescst, bdferdobst,
                  bdferjcst, bdtipodesccontrst, bdbaseadicst, bdlimite13st, BDPISOSAL, BDSALMINGAR, bdmestxasst, bdtipodesctxasst, bdmesrescmediasst, bdtipomesrescmediasst,
                  bdinihoranotst, bdfimhoranotst, bdliminaravprevst, bdqtddiasantpag, bdinativo
           from VRH_BASE_TSINDTREF where BDCODSINTRAB = :PRCODSINTRAB and BDREFST <= :pranomes order by BDREFST desc
           into :BDREFST, :BDVERFERIST, :BDVERMULRESST, :BDCODPMS, :BDPERABFERST, :BDDATBASEST, :BDESTABST, :BDPERCNOTST, :BDMESCSST, :BDFERRESCST, :BDFERDOBST,
                :BDFERJCST, :BDTIPODESCCONTRST, :BDBASEADICST, :BDLIMITE13ST, :BDPISOSAL, :BDSALMINGAR, :BDMESTXASST, :BDTIPODESCTXASST, :BDMESRESCMEDIASST, :BDTIPOMESRESCMEDIASST,
                :BDINIHORANOTST, :BDFIMHORANOTST, :BDLIMINARAVPREVST, :BDQTDDIASANTPAG, :BDINATIVO;
     
           suspend;
         end
end^

create or alter procedure SP_VRHF_GETTABELAINSS (
    PRTABINSS integer,
    PRANOMES integer)
returns (
    BDMINGPSINSS DM_NUMERIC_15_2,
    BDORDEM integer,
    BDFAIXAINSS DM_NUMERIC_15_2,
    BDALIQINSS DM_NUMERIC_15_2,
    BDPARCELADEDUZIR DM_NUMERIC_15_2)
as
declare variable WREFINSS integer;
begin
  if (coalesce(prtabinss, 0) = 0) then
     prtabinss = 1;

  for select first 1 BDREFINSS, cast(BDMINGPSINSS as dm_numeric_15_2)
      from VRHF_TABELAS_TINSSDADOS
      where BDCODINSS = :prtabinss and BDREFINSS <= :pranomes
      order by BDREFINSS desc
  into :wrefinss, :BDMINGPSINSS
  do
    begin
      for select BDORDEM, cast(BDFAIXAINSS as dm_numeric_15_2), cast(BDALIQINSS as dm_numeric_15_2), cast(BDPARCELADEDUZIR as dm_numeric_15_2)
          from VRHF_TABELAS_TINSSFAIXAS
          where BDCODINSS = :prtabinss and BDREFINSS = :wrefinss
          order by BDFAIXAINSS
      into :BDORDEM, :BDFAIXAINSS, :BDALIQINSS, :BDPARCELADEDUZIR
        do
          suspend;
    end
end^

create or alter procedure SP_VRHF_GETTABELAIR (
    PRCODIR integer,
    PRTIPOCALCIR integer,
    PRANOMES integer,
    PRANOMESSEGUINTE integer,
    PRCODTCA integer = 0)
returns (
    BDTIPOTABIR integer,
    BDREFIR integer,
    BDVALDEPIR DM_NUMERIC_15_2,
    BDDESCMINIR DM_NUMERIC_15_2,
    BDTIPOCALCFIR integer,
    BDCODTCA integer,
    BDORDEMIR integer,
    BDFAIXAIR DM_NUMERIC_15_2,
    BDALIQIR DM_NUMERIC_15_2,
    BDPARCDEDIR DM_NUMERIC_15_2,
    BDDESCONTOSIMPLIFICADO DM_NUMERIC_15_2)
as
declare variable WCODDIR integer;
begin
  -- BDTIPOTABIR: 0 = Mês atual específica considerando PLR; 1 = Mês seguinte específica considerando PLR; 2 = Genérica mês atual; 3 = Genérica mês seguinte

  if (coalesce(prtipocalcir, 0) <= 0) then
     prtipocalcir = 0;

  if (coalesce(prcodir, 0) <= 0) then
     prcodir = 0;

  if (coalesce(prcodtca, 0) <= 0) then
     prcodtca = 0;

  for select first 1 BDCODDIR, BDREFIR, cast(BDVALDEPIR as dm_numeric_15_2), cast(BDDESCMINIR as dm_numeric_15_2), BDTIPOCALCFIR, BDCODTCA, BDDESCONTOSIMPLIFICADO
      from VRHF_TABELAS_TIRDADOS
      where BDCODIR = :prcodir and BDTIPOCALCFIR = :prtipocalcir and BDCODTCA = :prcodtca and BDREFIR <= :pranomes
      order by BDREFIR desc
  into :wcoddir, :BDREFIR, :BDVALDEPIR, :BDDESCMINIR, :BDTIPOCALCFIR, :BDCODTCA, :BDDESCONTOSIMPLIFICADO
  do
    begin
      for select BDORDEMIR, cast(BDFAIXAIR as dm_numeric_15_2), cast(BDALIQIR as dm_numeric_15_2), cast(BDPARCDEDIR as dm_numeric_15_2)
          from VRHF_TABELAS_TIRFAIXAS
          where BDCODDIR = :wcoddir and BDCODIR = :prcodir
          order by BDFAIXAIR
      into :BDORDEMIR, :BDFAIXAIR, :BDALIQIR, :BDPARCDEDIR
      do
        begin
          bdtipotabir = 0;
          suspend;
        end
    end

  for select first 1 BDCODDIR, BDREFIR, cast(BDVALDEPIR as dm_numeric_15_2), cast(BDDESCMINIR as dm_numeric_15_2), BDTIPOCALCFIR, BDCODTCA, BDDESCONTOSIMPLIFICADO
      from VRHF_TABELAS_TIRDADOS
      where BDCODIR = :prcodir and coalesce(BDTIPOCALCFIR, 0) = :prtipocalcir and coalesce(BDCODTCA, 0) = :prcodtca and BDREFIR <= :pranomesseguinte
      order by BDREFIR desc
  into :wcoddir, :BDREFIR, :BDVALDEPIR, :BDDESCMINIR, :BDTIPOCALCFIR, :BDCODTCA, :BDDESCONTOSIMPLIFICADO
  do
    begin
      for select BDORDEMIR, cast(BDFAIXAIR as dm_numeric_15_2), cast(BDALIQIR as dm_numeric_15_2), cast(BDPARCDEDIR as dm_numeric_15_2)
          from VRHF_TABELAS_TIRFAIXAS
          where BDCODDIR = :wcoddir and BDCODIR = :prcodir
          order by BDFAIXAIR
      into :BDORDEMIR, :BDFAIXAIR, :BDALIQIR, :BDPARCDEDIR
      do
        begin
          bdtipotabir = 1;
          suspend;
        end
    end

  for select first 1 BDCODDIR, BDREFIR, cast(BDVALDEPIR as dm_numeric_15_2), cast(BDDESCMINIR as dm_numeric_15_2), BDTIPOCALCFIR, BDCODTCA, BDDESCONTOSIMPLIFICADO
      from VRHF_TABELAS_TIRDADOS
      where BDCODIR = :prcodir and coalesce(BDTIPOCALCFIR, 0) = 0 and coalesce(BDCODTCA, 0) = 0 and BDREFIR <= :pranomes
      order by BDREFIR desc
  into :wcoddir, :BDREFIR, :BDVALDEPIR, :BDDESCMINIR, :BDTIPOCALCFIR, :BDCODTCA, :BDDESCONTOSIMPLIFICADO
  do
    begin
      for select BDORDEMIR, cast(BDFAIXAIR as dm_numeric_15_2), cast(BDALIQIR as dm_numeric_15_2), cast(BDPARCDEDIR as dm_numeric_15_2)
          from VRHF_TABELAS_TIRFAIXAS
          where BDCODDIR = :wcoddir and BDCODIR = :prcodir
          order by BDFAIXAIR
      into :BDORDEMIR, :BDFAIXAIR, :BDALIQIR, :BDPARCDEDIR
      do
        begin
          bdtipotabir = 2;
          suspend;
        end
    end

  for select first 1 BDCODDIR, BDREFIR, cast(BDVALDEPIR as dm_numeric_15_2), cast(BDDESCMINIR as dm_numeric_15_2), BDTIPOCALCFIR, BDCODTCA, BDDESCONTOSIMPLIFICADO
      from VRHF_TABELAS_TIRDADOS
      where BDCODIR = :prcodir and coalesce(BDTIPOCALCFIR, 0) = 0 and coalesce(BDCODTCA, 0) = 0 and BDREFIR <= :pranomesseguinte
      order by BDREFIR desc
  into :wcoddir, :BDREFIR, :BDVALDEPIR, :BDDESCMINIR, :BDTIPOCALCFIR, :BDCODTCA, :BDDESCONTOSIMPLIFICADO
  do
    begin
      for select BDORDEMIR, cast(BDFAIXAIR as dm_numeric_15_2), cast(BDALIQIR as dm_numeric_15_2), cast(BDPARCDEDIR as dm_numeric_15_2)
          from VRHF_TABELAS_TIRFAIXAS
          where BDCODDIR = :wcoddir and BDCODIR = :prcodir
          order by BDFAIXAIR
      into :BDORDEMIR, :BDFAIXAIR, :BDALIQIR, :BDPARCDEDIR
      do
        begin
          bdtipotabir = 3;
          suspend;
        end
    end
end^

create or alter procedure SP_VRHF_GETTABSALFAM (
    PRANOMES integer)
returns (
    BDREFSF integer,
    BDBASESF DM_NUMERIC_15_2,
    BDVALSF DM_NUMERIC_15_2,
    BDORDEM integer)
as
begin
  for select first 1 BDREFSF
      from VRHF_TABELAS_TSALFAMFAIXAS
      where BDREFSF <= :pranomes
      order by BDREFSF desc
  into :BDREFSF
  do
    begin
      for select cast(BDBASESF as dm_numeric_15_2), cast(BDVALSF as dm_numeric_15_2), BDORDEM
          from VRHF_TABELAS_TSALFAMFAIXAS
          where BDREFSF = :BDREFSF
          order by BDBASESF
      into :BDBASESF, :BDVALSF, BDORDEM
      do
        suspend;
    end
end^

create or alter procedure SP_VRHF_GETVERBAS (
    PRANOMES integer)
returns (
    BDCODVER integer,
    BDCLAVER varchar(20),
    BDAPEVER varchar(20),
    BDDESCVER varchar(40),
    BDDESCREDVER varchar(20),
    BDORDEMVER integer,
    BDINATIVAVER DM_BOOLEAN,
    BDSITVER integer,
    BDSITMATVER DM_BOOLEAN,
    BDSITDOEVER DM_BOOLEAN,
    BDSITACITRABVER DM_BOOLEAN,
    BDSITMILITARVER DM_BOOLEAN,
    BDSITMATEMPVER DM_BOOLEAN,
    BDSITACITRAB15VER DM_BOOLEAN,
    BDSITDOETRABVER DM_BOOLEAN,
    BDSITLICVENCVER DM_BOOLEAN,
    BDSITDOE15VER DM_BOOLEAN,
    BDSITSINDICALVER DM_BOOLEAN,
    BDSITAPOINVVER DM_BOOLEAN,
    BDSITOUTRASVER DM_BOOLEAN,
    BDNIVELVER smallint,
    BDCHAVE integer,
    BDTIPOCODVER integer,
    BDINSSVER integer,
    BDIRVER integer,
    BDFGTSVER integer,
    BDTIPOREFVER integer,
    BDBASESFVER integer,
    BDPISVER DM_BOOLEAN,
    BDBASEHEVER DM_BOOLEAN,
    BDBASEMAIORVER DM_BOOLEAN,
    BDRAISVER DM_BOOLEAN,
    BDBASEGPSVER DM_BOOLEAN,
    BDMENORESVER DM_BOOLEAN,
    BDPROPVER DM_BOOLEAN,
    BDBASEVTVER DM_BOOLEAN,
    BDREEMBGPSVER DM_BOOLEAN,
    BDHEVER DM_NUMERIC_15_2,
    BDGRAVAFICHAHNVER DM_BOOLEAN,
    BDCCPRINCIPALVER DM_BOOLEAN,
    BDFORMREFVER varchar(5000),
    BDFORMVALVER varchar(5000),
    BDBASEDSRHEVER DM_BOOLEAN,
    BDBASEDSRRVVER DM_BOOLEAN,
    BDREFVER integer,
    BDFORMREFAUXVER varchar(5000),
    BDDEDFORMREFAUXVER DM_BOOLEAN,
    BDDEDFORMREFVER DM_BOOLEAN,
    BDGARANTIAMINVER DM_BOOLEAN,
    BDDEDFORMVALVER DM_BOOLEAN,
    BDRENDISENTOIRVER DM_BOOLEAN,
    BDFORMINTVER varchar(5000),
    BDPAGAESTOUROVER DM_BOOLEAN,
    BDNAOCONVHORASVER DM_BOOLEAN,
    BDBASEDSRHNVER DM_BOOLEAN,
    BDBASEDSROUVER DM_BOOLEAN,
    BDREMINTERMVER DM_BOOLEAN)
as
declare variable WCLAVER varchar(20);
declare variable WPOS integer;
declare variable WCHAVE integer;
declare variable WCODVER integer;
begin
  for select VER.BDCODVER, VER.BDCLAVER, VER.BDAPEVER, VER.BDDESCVER, VER.BDDESCREDVER, VER.BDORDEMVER, VER.BDINATIVAVER, VER.BDSITVER,
             VER.BDSITMATVER, VER.BDSITDOEVER, VER.BDSITACITRABVER, VER.BDSITMILITARVER, VER.BDSITMATEMPVER,
             VER.BDSITACITRAB15VER, VER.BDSITDOETRABVER, VER.BDSITLICVENCVER, VER.BDSITDOE15VER, VER.BDSITSINDICALVER, VER.BDSITAPOINVVER,
             VER.BDSITOUTRASVER, VER.BDNIVELVER, RB.BDCHAVE
      from VRH_BASE_TVERBAS VER
      left outer join VRH_BASE_TRUBRICAESOCIAL_VER RB on (RB.BDCODVER = VER.BDCODVER)
      where BDNIVELVER > 9
  into :BDCODVER, :BDCLAVER, :BDAPEVER, :BDDESCVER, :BDDESCREDVER, :BDORDEMVER, :BDINATIVAVER, :BDSITVER,
       :BDSITMATVER, :BDSITDOEVER, :BDSITACITRABVER, :BDSITMILITARVER, :BDSITMATEMPVER,
       :BDSITACITRAB15VER, :BDSITDOETRABVER, :BDSITLICVENCVER, :BDSITDOE15VER, :BDSITSINDICALVER, :BDSITAPOINVVER,
       :BDSITOUTRASVER, :BDNIVELVER, :BDCHAVE
  do
    begin
      select first 1 BDTIPOCODVER, BDINSSVER, BDIRVER, BDFGTSVER, BDTIPOREFVER, BDBASESFVER, BDPISVER,
             BDBASEHEVER, BDBASEMAIORVER, BDRAISVER, BDBASEGPSVER, BDMENORESVER, BDPROPVER, BDBASEVTVER,
             BDREEMBGPSVER, BDHEVER, BDGRAVAFICHAHNVER, BDCCPRINCIPALVER, BDFORMREFVER, BDFORMVALVER,
             BDBASEDSRHEVER, BDBASEDSRRVVER, BDREFVER, BDFORMREFAUXVER, BDDEDFORMREFAUXVER, BDDEDFORMREFVER,
             BDGARANTIAMINVER, BDDEDFORMVALVER, BDRENDISENTOIRVER, BDFORMINTVER, BDPAGAESTOUROVER,
             BDNAOCONVHORASVER, BDBASEDSRHNVER, BDBASEDSROUVER, BDREMINTERMVER
      from VRH_BASE_TVERBAS_REF
      where BDREFVER <= :pranomes and BDCODVER = :BDCODVER
      order by BDREFVER desc
      into :BDTIPOCODVER, :BDINSSVER, :BDIRVER, :BDFGTSVER, :BDTIPOREFVER, :BDBASESFVER, :BDPISVER,
           :BDBASEHEVER, :BDBASEMAIORVER, :BDRAISVER, :BDBASEGPSVER, :BDMENORESVER, :BDPROPVER, :BDBASEVTVER,
           :BDREEMBGPSVER, :BDHEVER, :BDGRAVAFICHAHNVER, :BDCCPRINCIPALVER, :BDFORMREFVER, :BDFORMVALVER,
           :BDBASEDSRHEVER, :BDBASEDSRRVVER, :BDREFVER, :BDFORMREFAUXVER, :BDDEDFORMREFAUXVER, :BDDEDFORMREFVER,
           :BDGARANTIAMINVER, :BDDEDFORMVALVER, :BDRENDISENTOIRVER, :BDFORMINTVER, :BDPAGAESTOUROVER,
           :BDNAOCONVHORASVER, :BDBASEDSRHNVER, :BDBASEDSROUVER, :BDREMINTERMVER;


      -- Tenta buscar a configuração para eSocial da verba título
      if (coalesce(BDCHAVE, 0) = 0) then
         begin
           wchave = 0;
           wclaver = reverse(BDCLAVER);
           wpos = position('.', wclaver);
           while (wpos > 0 and wchave = 0) do
             begin
               wclaver = substring(wclaver from :wpos + 1 for 20);
               wclaver = reverse(wclaver);

               select first 1 BDCODVER from VRH_BASE_TVERBAS where BDCLAVER = :wclaver into :wcodver;
               if (coalesce(wcodver, 0) > 0) then
                  begin
                    select first 1 BDCHAVE from VRH_BASE_TRUBRICAESOCIAL_VER where BDCODVER = :wcodver into :wchave;
                    wchave = coalesce(wchave, 0);
                  end

               wclaver = reverse(wclaver);
               wpos = position('.', wclaver);
             end

           if (coalesce(wchave, 0) > 0) then
              BDCHAVE = wchave;
         end

      suspend;
    end
end^

create or alter procedure SP_VRHF_GETVERBASESPELHO (
    PRLISTATIPOCALCULO varchar(200) = null)
returns (
    BDCODCTP integer,
    BDCODCIT integer,
    BDCODVER integer,
    BDCODVERCVE integer,
    BDFORMULABASECVE DM_BOOLEAN,
    BDFORMCIT varchar(350),
    BDCLASSCIT varchar(20))
as
declare variable WSQL varchar(5000);
begin
  wSql = 'select BDCODCTP,BDCODCIT,BDFORMCIT,BDCLASSCIT '||
         'from VRH_BASE_TCALCITENS '||
         'where BDCODTCA is null ';

  if (trim(coalesce(prlistatipocalculo, '')) <> '') then
     wsql = wsql||' and BDCODCTP in ('||:prlistatipocalculo||') ';

  for execute statement wsql
  into :BDCODCTP, :BDCODCIT, :BDFORMCIT, :BDCLASSCIT
  do
    begin
      for select BDCODVER, BDCODVERCVE, trim(upper(coalesce(BDFORMULABASECVE, 'FALSE')))
          from VRH_BASE_TCALCVESP
          where BDCODCTP = :BDCODCTP and BDCODCIT = :BDCODCIT
      into :BDCODVER, :BDCODVERCVE, :BDFORMULABASECVE
      do
        suspend;
    end
end^

/* Restore proc. body: SP_VRHF_GETVERBASNAO */
create or alter procedure SP_VRHF_GETVERBASNAO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRPLANOCC integer,
    PRPLANOFUNCAO integer,
    PRCODSINDICATO integer,
    PRCODPRES integer,
    PRULTDIA date)
returns (
    BDTIPOVN integer,
    BDCODVER integer,
    BDANOINI integer,
    BDMESINI integer,
    BDDIAINI integer,
    BDANOFIM integer,
    BDMESFIM integer,
    BDDIAFIM integer,
    BDFORMULAREF varchar(2000),
    BDFERIASVN DM_BOOLEAN,
    BD13VN DM_BOOLEAN,
    BDDATAINI DM_COMP_8,
    BDDATAFIM DM_COMP_8,
    BDCODSINTRAB integer,
    BDCODTPCC integer,
    BDCODTFUC integer,
    BDCODPRES integer,
    BDFORMULAVAL varchar(10))
as
declare variable WCOMPINI DM_COMP_8;
declare variable WCOMPFIM DM_COMP_8;
begin
  wcompini = substring(cast(prultdia as varchar(10)) from 1 for 4)||substring(cast(prultdia as varchar(10)) from 6 for 2)||'01';
  wcompfim = substring(cast(prultdia as varchar(10)) from 1 for 4)||substring(cast(prultdia as varchar(10)) from 6 for 2)||substring(cast(prultdia as varchar(10)) from 9 for 2);

  BDCODSINTRAB = null;
  BDCODTFUC    = null;
  BDCODPRES    = null;
  BDCODTPCC    = null;
  BDFORMULAVAL = null;

  if (coalesce(prcodpres, 0) > 0) then
     begin
       for select BDCODPRES, BDCODVER, BDANOINIVNPRES, BDMESINIVNPRES, BDANOFIMVNPRES, BDMESFIMVNPRES, BDDIAINIVNPRES, BDDIAFIMVNPRES, BDFERIASVNPRES, BD13VNPRES,
           SUBSTRING(BDDESCCONDPRES FROM 1 FOR 2000)
           from VRHF_BASE_TVNPRES
           where BDCODPRES = :prcodpres and BDCOMPINI <= :wcompfim and BDCOMPFIM >= :wcompini
       into :BDCODPRES, :BDCODVER, :BDANOINI, :BDMESINI, :BDANOFIM, :BDMESFIM, :BDDIAINI, :BDDIAFIM, :BDFERIASVN, :BD13VN, :BDFORMULAREF
       do
         begin
           BDTIPOVN = 6;
           BDDATAINI = wcompini;
           BDDATAFIM = wcompfim;
           suspend;
         end
     end

  BDCODPRES = null;

  if (coalesce(prcodsindicato, 0) > 0) then
     begin
       for select BDCODSINTRAB, BDCODVER, BDANOINIVNSIND, BDMESINIVNSIND, BDANOFIMVNSIND, BDMESFIMVNSIND, BDDIAINIVNSIND, BDDIAFIMVNSIND, BDFERIASVNSIND, BD13VNSIND,
           SUBSTRING(BDDESCCONDSIND FROM 1 FOR 2000)
           from VRHF_BASE_TVNSIND
           where BDCODSINTRAB = :prcodsindicato and BDCOMPINI <= :wcompfim and BDCOMPFIM >= :wcompini
       into :BDCODSINTRAB, :BDCODVER, :BDANOINI, :BDMESINI, :BDANOFIM, :BDMESFIM, :BDDIAINI, :BDDIAFIM, :BDFERIASVN, :BD13VN, :BDFORMULAREF
       do
         begin
           BDTIPOVN = 1;
           BDDATAINI = wcompini;
           BDDATAFIM = wcompfim;
           suspend;
         end
     end

  BDCODSINTRAB = null;

  if (coalesce(prcodemp, 0) > 0) then
     begin
       for select BDCODVER, BDANOINIVNEMP, BDMESINIVNEMP, BDANOFIMVNEMP, BDMESFIMVNEMP, BDDIAINIVNEMP, BDDIAFIMVNEMP, BDFERIASVNEMP, BD13VNEMP,
           CAST(BDDESCCONDEMP AS VARCHAR(2000))
           from VRHF_EMP_TVNEMP
           where BDCODEMP = :prcodemp and BDCOMPINI <= :wcompfim and BDCOMPFIM >= :wcompini
       into :BDCODVER, :BDANOINI, :BDMESINI, :BDANOFIM, :BDMESFIM, :BDDIAINI, :BDDIAFIM, :BDFERIASVN, :BD13VN, :BDFORMULAREF
       do
         begin
           BDTIPOVN = 4;
           BDDATAINI = wcompini;
           BDDATAFIM = wcompfim;
           suspend;
         end
     end

  if (coalesce(prplanocc, 0) > 0) then
     begin
       for select BDCODTPCC, BDCODVER, BDANOINIVNCUSTO, BDMESINIVNCUSTO, BDANOFIMVNCUSTO, BDMESFIMVNCUSTO, BDDIAINIVNCUSTO, BDDIAFIMVNCUSTO, BDFERIASVNCUSTO, BD13VNCUSTO,
           CAST(BDDESCCONDCUSTO AS VARCHAR(2000))
           from VRHF_CUSTOS_TVNCUSTO
           where BDCODCENTRO = :prplanocc and BDCOMPINI <= :wcompfim and BDCOMPFIM >= :wcompini
       into :BDCODTPCC, :BDCODVER, :BDANOINI, :BDMESINI, :BDANOFIM, :BDMESFIM, :BDDIAINI, :BDDIAFIM, :BDFERIASVN, :BD13VN, :BDFORMULAREF
       do
         begin
           BDTIPOVN = 2;
           BDDATAINI = wcompini;
           BDDATAFIM = wcompfim;
           suspend;
         end
     end

  BDCODTPCC = null;

  if (coalesce(prplanofuncao, 0) > 0) then
     begin
       for select BDCODTFUC, BDCODVER, BDANOINIVNFUC, BDMESINIVNFUC, BDANOFIMVNFUC, BDMESFIMVNFUC, BDDIAINIVNFUC, BDDIAFIMVNFUC, BDFERIASVNFUC, BD13VNFUC,
           CAST(BDDESCCONDFUC AS VARCHAR(2000))
           from VRHF_FUNCOES_TVNFUC
           where BDCODPLAFUC = :prplanofuncao and BDCOMPINI <= :wcompfim and BDCOMPFIM >= :wcompini
       into :BDCODTFUC, :BDCODVER, :BDANOINI, :BDMESINI, :BDANOFIM, :BDMESFIM, :BDDIAINI, :BDDIAFIM, :BDFERIASVN, :BD13VN, :BDFORMULAREF
       do
         begin
           BDTIPOVN = 3;
           BDDATAINI = wcompini;
           BDDATAFIM = wcompfim;
           suspend;
         end
     end

  BDCODTFUC = null;

  if (coalesce(prcodemp, 0) > 0 and coalesce(prcodcol, 0) > 0) then
     begin
       for select BDCODVER, BDANOINIVNCOL, BDMESINIVNCOL, BDANOFIMVNCOL, BDMESFIMVNCOL, BDDIAINIVNCOL, BDDIAFIMVNCOL, BDFERIASVNCOL, BD13VNCOL,
           CAST(BDDESCCONDCOL AS VARCHAR(2000))
           from VRHF_EMP_TVNCOL
           where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDCOMPINI <= :wcompfim and BDCOMPFIM >= :wcompini
       into :BDCODVER, :BDANOINI, :BDMESINI, :BDANOFIM, :BDMESFIM, :BDDIAINI, :BDDIAFIM, :BDFERIASVN, :BD13VN, :BDFORMULAREF
       do
         begin
           BDTIPOVN = 5;
           BDDATAINI = wcompini;
           BDDATAFIM = wcompfim;
           suspend;
         end
     end
end^

/* Restore proc. body: SP_VRHF_GETVERBASSIM */
create or alter procedure SP_VRHF_GETVERBASSIM (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCODSIND integer,
    PRPLANOFUNCAO integer,
    PRCODPRES integer,
    PRPLANOCUSTOS integer,
    PRULTDIA date)
returns (
    BDTIPOVS integer,
    BDCODVER integer,
    BDANOINI integer,
    BDMESINI integer,
    BDDIAINI integer,
    BDANOFIM integer,
    BDMESFIM integer,
    BDDIAFIM integer,
    BDFORMULAREFAUX varchar(800),
    BDFORMULAREF varchar(800),
    BDFORMULAVAL varchar(800),
    BDDATAINI DM_COMP_8,
    BDDATAFIM DM_COMP_8,
    BDCODSINTRAB integer,
    BDCODTFUC integer,
    BDCODPRES integer,
    BDCODTPCC integer)
as
declare variable WCOMPINI varchar(8);
declare variable WCOMPFIM varchar(8);
begin
  wcompini = substring(cast(prultdia as varchar(10)) from 1 for 4)||substring(cast(prultdia as varchar(10)) from 6 for 2)||'01';
  wcompfim = substring(cast(prultdia as varchar(10)) from 1 for 4)||substring(cast(prultdia as varchar(10)) from 6 for 2)||substring(cast(prultdia as varchar(10)) from 9 for 2);

  BDCODSINTRAB = null;
  BDCODTFUC    = null;
  BDCODPRES    = null;
  BDCODTPCC    = null;

  if (coalesce(prcodpres, 0) > 0) then
     begin
       for select BDCODPRES, BDCODVER, BDANOINIVSPRES, BDMESINIVSPRES, BDDIAINIVSPRES, BDANOFIMVSPRES, BDMESFIMVSPRES, BDDIAFIMVSPRES, BDFORMULAREFPRES, BDFORMULAVALPRES, BDFORMULAREFAUXPRES
           from VRHF_BASE_TVSPRES
           where BDCODPRES = :prcodpres and BDCOMPINI <= :wcompfim and BDCOMPFIM >= :wcompini
       into :BDCODPRES, :BDCODVER, :BDANOINI, :BDMESINI, :BDDIAINI, :BDANOFIM, :BDMESFIM, :BDDIAFIM, :BDFORMULAREF, :BDFORMULAVAL, :BDFORMULAREFAUX
       do
         begin
           BDTIPOVS = 6;
           BDDATAINI = wcompini;
           BDDATAFIM = wcompfim;
           suspend;
         end
    end

  BDCODPRES = null;

  if (coalesce(prcodsind, 0) > 0) then
     begin
       for select BDCODSINTRAB, BDCODVER, BDANOINIVSSIND, BDMESINIVSSIND, BDDIAINIVSSIND, BDANOFIMVSSIND, BDMESFIMVSSIND, BDDIAFIMVSSIND, BDFORMULAREFSIND, BDFORMULAVALSIND, BDFORMULAREFAUXSIND
           from VRHF_BASE_TVSSIND
           where BDCODSINTRAB = :prcodsind and BDCOMPINI <= :wcompfim and BDCOMPFIM >= :wcompini
       into :BDCODSINTRAB, :BDCODVER, :BDANOINI, :BDMESINI, :BDDIAINI, :BDANOFIM, :BDMESFIM, :BDDIAFIM, :BDFORMULAREF, :BDFORMULAVAL, :BDFORMULAREFAUX
       do
         begin
           BDTIPOVS = 1;
           BDDATAINI = wcompini;
           BDDATAFIM = wcompfim;
           suspend;
         end
    end

  BDCODSINTRAB = null;

  if (coalesce(prcodemp, 0) > 0) then
     begin
       for select BDCODVER, BDANOINIVSEMP, BDMESINIVSEMP, BDDIAINIVSEMP, BDANOFIMVSEMP, BDMESFIMVSEMP, BDDIAFIMVSEMP, BDFORMULAREFEMP, BDFORMULAVALEMP, BDFORMULAREFAUXEMP
           from VRHF_EMP_TVSEMP
           where BDCODEMP = :prcodemp and BDCOMPINI <= :wcompfim and BDCOMPFIM >= :wcompini
       into :BDCODVER, :BDANOINI, :BDMESINI, :BDDIAINI, :BDANOFIM, :BDMESFIM, :BDDIAFIM, :BDFORMULAREF, :BDFORMULAVAL, :BDFORMULAREFAUX
       do
         begin
           BDTIPOVS = 4;
           BDDATAINI = wcompini;
           BDDATAFIM = wcompfim;
           suspend;
         end
     end

  if (coalesce(prplanocustos, 0) > 0) then
     begin
       for select BDCODTPCC, BDCODVER, BDANOINIVSCUSTO, BDMESINIVSCUSTO, BDDIAINIVSCUSTO, BDANOFIMVSCUSTO, BDMESFIMVSCUSTO, BDDIAFIMVSCUSTO, BDFORMULAREFCUSTO, BDFORMULAVALCUSTO, BDFORMULAREFAUXCUSTO
           from VRHF_CUSTOS_TVSCUSTO
           where BDCODCENTRO = :prplanocustos and BDCOMPINI <= :wcompfim and BDCOMPFIM >= :wcompini
       into :BDCODTPCC, :BDCODVER, :BDANOINI, :BDMESINI, :BDDIAINI, :BDANOFIM, :BDMESFIM, :BDDIAFIM, :BDFORMULAREF, :BDFORMULAVAL, :BDFORMULAREFAUX
       do
         begin
           BDTIPOVS = 2;
           BDDATAINI = wcompini;
           BDDATAFIM = wcompfim;
           suspend;
         end
    end

  BDCODTPCC = null;

  if (coalesce(prplanofuncao, 0) > 0) then
     begin
       for select BDCODTFUC, BDCODVER, BDANOINIVSFUC, BDMESINIVSFUC, BDDIAINIVSFUC, BDANOFIMVSFUC, BDMESFIMVSFUC, BDDIAFIMVSFUC, BDFORMULAREFFUC, BDFORMULAVALFUC, BDFORMULAREFAUXFUC
           from VRHF_FUNCOES_TVSFUC
           where BDCODPLAFUC = :prplanofuncao and BDCOMPINI <= :wcompfim and BDCOMPFIM >= :wcompini
       into :BDCODTFUC, :BDCODVER, :BDANOINI, :BDMESINI, :BDDIAINI, :BDANOFIM, :BDMESFIM, :BDDIAFIM, :BDFORMULAREF, :BDFORMULAVAL, :BDFORMULAREFAUX
       do
         begin
           BDTIPOVS = 3;
           BDDATAINI = wcompini;
           BDDATAFIM = wcompfim;
           suspend;
         end
    end

  BDCODTFUC = null;

  if (coalesce(prcodemp, 0) > 0 and coalesce(prcodcol, 0) > 0) then
     begin
       for select BDCODVER, BDANOINIVSCOL, BDMESINIVSCOL, BDDIAINIVSCOL, BDANOFIMVSCOL, BDMESFIMVSCOL, BDDIAFIMVSCOL, BDFORMULAREFCOL, BDFORMULAVALCOL, BDFORMULAREFAUXCOL
           from VRHF_EMP_TVSCOL
           where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDCOMPINI <= :wcompfim and BDCOMPFIM >= :wcompini
       into :BDCODVER, :BDANOINI, :BDMESINI, :BDDIAINI, :BDANOFIM, :BDMESFIM, :BDDIAFIM, :BDFORMULAREF, :BDFORMULAVAL, :BDFORMULAREFAUX
       do
         begin
           BDTIPOVS = 5;
           BDDATAINI = wcompini;
           BDDATAFIM = wcompfim;
           suspend;
         end
    end
end^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_HE_AI0 FOR VRH_BASE_TCONF_FICHA_HE
ACTIVE AFTER INSERT POSITION 0
AS
  declare variable wcodver INTEGER;
begin
  for select BDCODVER from VRH_BASE_TVERBAS where BDCLAVER starting with new.bdclaver into :wcodver do
    begin
      update or insert into VRH_BASE_TCONFMEDIAS (BDCODVER, BDTIPOFICHA) values (:wcodver, 0) matching(BDCODVER);
    end
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_HE_AD0 FOR VRH_BASE_TCONF_FICHA_HE
ACTIVE AFTER DELETE POSITION 0
AS
  declare variable wcodver INTEGER;
begin
  for select BDCODVER from VRH_BASE_TVERBAS where BDCLAVER starting with old.bdclaver into :wcodver do
    begin
      delete from VRH_BASE_TCONFMEDIAS where BDCODVER = :wcodver;
    end
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_RV_AI0 FOR VRH_BASE_TCONF_FICHA_RV
ACTIVE AFTER INSERT POSITION 0
AS
  declare variable wcodver INTEGER;
begin
  for select BDCODVER from VRH_BASE_TVERBAS where BDCLAVER starting with new.bdclaver into :wcodver do
    begin
      update or insert into VRH_BASE_TCONFMEDIAS (BDCODVER, BDTIPOFICHA) values (:wcodver, 1) matching(BDCODVER);
    end
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_RV_AD0 FOR VRH_BASE_TCONF_FICHA_RV
ACTIVE AFTER DELETE POSITION 0
AS
  declare variable wcodver INTEGER;
begin
  for select BDCODVER from VRH_BASE_TVERBAS where BDCLAVER starting with old.bdclaver into :wcodver do
    begin
      delete from VRH_BASE_TCONFMEDIAS where BDCODVER = :wcodver;
    end
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_HN_AI0 FOR VRH_BASE_TCONF_FICHA_HN
ACTIVE AFTER INSERT POSITION 0
AS
  declare variable wcodver INTEGER;
begin
  for select BDCODVER from VRH_BASE_TVERBAS where BDCLAVER starting with new.bdclaver into :wcodver do
    begin
      update or insert into VRH_BASE_TCONFMEDIAS (BDCODVER, BDTIPOFICHA) values (:wcodver, 2) matching(BDCODVER);
    end
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_HN_AD0 FOR VRH_BASE_TCONF_FICHA_HN
ACTIVE AFTER DELETE POSITION 0
AS
  declare variable wcodver INTEGER;
begin
  for select BDCODVER from VRH_BASE_TVERBAS where BDCLAVER starting with old.bdclaver into :wcodver do
    begin
      delete from VRH_BASE_TCONFMEDIAS where BDCODVER = :wcodver;
    end
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_OUT_AI0 FOR VRH_BASE_TCONF_FICHA_OUT
ACTIVE AFTER INSERT POSITION 0
AS
  declare variable wcodver INTEGER;
begin
  for select BDCODVER from VRH_BASE_TVERBAS where BDCLAVER starting with new.bdclaver into :wcodver do
    begin
      update or insert into VRH_BASE_TCONFMEDIAS (BDCODVER, BDTIPOFICHA) values (:wcodver, 3) matching(BDCODVER);
    end
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONF_FICHA_OUT_AD0 FOR VRH_BASE_TCONF_FICHA_OUT
ACTIVE AFTER DELETE POSITION 0
AS
  declare variable wcodver INTEGER;
begin
  for select BDCODVER from VRH_BASE_TVERBAS where BDCLAVER starting with old.bdclaver into :wcodver do
    begin
      delete from VRH_BASE_TCONFMEDIAS where BDCODVER = :wcodver;
    end
end
^

create or alter procedure SP_INSEREVERBA_CONFMEDIAS (
    PRCODVER integer,
    PRCLAVER varchar(20),
    PRTABELACONFFICHA varchar(300),
    PRTIPOFICHA smallint)
as
declare variable WCLAVER varchar(20);
declare variable WCODVER integer;
declare variable WSQL varchar(2000);
declare variable WOK smallint;
begin
  wok = 0;
  wclaver = substring(prclaver from 1 for 9);    -- nível 4 da classificação
  wcodver = null;
  wsql = 'select first 1 BDCODVER from '||prtabelaconfficha||' where BDCLAVER = '''||wclaver||'''';
  execute statement wsql into :wcodver;

  if (coalesce(wcodver, 0) > 0) then
     begin
       update or insert into VRH_BASE_TCONFMEDIAS (BDCODVER, BDTIPOFICHA) values (:prcodver, :prtipoficha);
       wok = 1;
     end

  if (wok = 0) then
     begin
       wclaver = substring(prclaver from 1 for 7);    -- nível 3 da classificação
       wcodver = null;
       wsql = 'select first 1 BDCODVER from '||prtabelaconfficha||' where BDCLAVER = '''||wclaver||'''';
       execute statement wsql into :wcodver;
      
       if (coalesce(wcodver, 0) > 0) then
          begin
            update or insert into VRH_BASE_TCONFMEDIAS (BDCODVER, BDTIPOFICHA) values (:prcodver, :prtipoficha);
            wok = 1;
          end
     end

  if (wok = 0) then
     begin
       wclaver = substring(prclaver from 1 for 5);    -- nível 2 da classificação
       wcodver = null;
       wsql = 'select first 1 BDCODVER from '||prtabelaconfficha||' where BDCLAVER = '''||wclaver||'''';
       execute statement wsql into :wcodver;
      
       if (coalesce(wcodver, 0) > 0) then
          begin
            update or insert into VRH_BASE_TCONFMEDIAS (BDCODVER, BDTIPOFICHA) values (:prcodver, :prtipoficha);
            wok = 1;
          end
     end

  if (wok = 0) then
     begin
       wclaver = substring(prclaver from 1 for 1);    -- nível 1 da classificação
       wcodver = null;
       wsql = 'select first 1 BDCODVER from '||prtabelaconfficha||' where BDCLAVER = '''||wclaver||'''';
       execute statement wsql into :wcodver;
      
       if (coalesce(wcodver, 0) > 0) then
          begin
            update or insert into VRH_BASE_TCONFMEDIAS (BDCODVER, BDTIPOFICHA) values (:prcodver, :prtipoficha);
            wok = 1;
          end
     end
end^

create or alter procedure SP_APAGAVERBA_CONFMEDIAS (
    PRCODVER integer,
    PRCLAVER varchar(20),
    PRTABELACONFFICHA varchar(300))
as
declare variable WCLAVER varchar(20);
declare variable WSQL varchar(2000);
declare variable WCODVER integer;
declare variable WOK smallint;
begin
  wok = 0;
  wclaver = prclaver;
  wcodver = null;
  wsql = 'select first 1 bdcodver from '||prtabelaconfficha||' where BDCLAVER = '''||wclaver||'''';
  execute statement wsql into :wcodver;
  if (coalesce(wcodver, 0) > 0) then
     begin
       delete from VRH_BASE_TCONFMEDIAS where BDCODVER = :prcodver;
       wok = 1;
     end

  if (wok = 0) then
     begin
       wclaver = substring(prclaver from 1 for 9);
       wcodver = null;
       wsql = 'select first 1 bdcodver from '||prtabelaconfficha||' where BDCLAVER = '''||wclaver||'''';
       execute statement wsql into :wcodver;
       if (coalesce(wcodver, 0) > 0) then
          begin
            delete from VRH_BASE_TCONFMEDIAS where BDCODVER = :prcodver;
            wok = 1;
          end
     end

  if (wok = 0) then
     begin
       wclaver = substring(prclaver from 1 for 7);
       wcodver = null;
       wsql = 'select first 1 bdcodver from '||prtabelaconfficha||' where BDCLAVER = '''||wclaver||'''';
       execute statement wsql into :wcodver;
       if (coalesce(wcodver, 0) > 0) then
          begin
            delete from VRH_BASE_TCONFMEDIAS where BDCODVER = :prcodver;
            wok = 1;
          end
     end

  if (wok = 0) then
     begin
       wclaver = substring(prclaver from 1 for 5);
       wcodver = null;
       wsql = 'select first 1 bdcodver from '||prtabelaconfficha||' where BDCLAVER = '''||wclaver||'''';
       execute statement wsql into :wcodver;
       if (coalesce(wcodver, 0) > 0) then
          begin
            delete from VRH_BASE_TCONFMEDIAS where BDCODVER = :prcodver;
            wok = 1;
          end
     end

  if (wok = 0) then
     begin
       wclaver = substring(prclaver from 1 for 1);
       wcodver = null;
       wsql = 'select first 1 bdcodver from '||prtabelaconfficha||' where BDCLAVER = '''||wclaver||'''';
       execute statement wsql into :wcodver;
       if (coalesce(wcodver, 0) > 0) then
          begin
            delete from VRH_BASE_TCONFMEDIAS where BDCODVER = :prcodver;
            wok = 1;
          end
     end
end^

create or alter procedure SP_VRHF_GETMEDIAS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDCODVER integer,
    BDREF integer,
    BDTIPO integer,
    BDCC integer,
    BDVREF numeric(18,6),
    BDVREFAUX numeric(18,6),
    BDVVAL numeric(18,6))
as
declare variable WCODEMP integer;
declare variable WCODCOL integer;
BEGIN
  /* Verifica se tem configuração de verbas ficha financeira */
  for select PL.BDCODVER, PL.BDREFFN, PL.BDTIPOCALC, PL.BDCCFN, PL.BDREFVFN, PL.BDREFAUXVFN, PL.BDVALVFN
      from (select BDCODVER, BDREFFN, 0 BDTIPOCALC, 0 BDCCFN, BDREFVFN, BDREFAUXVFN, BDVALVFN
            from VRHF_EMP_TVERBAFN
            where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFFN between :prrefini and :prreffim
            union all
            select BDCODVER, BDREFFN, 0 BDTIPOCALC, 0 BDCCFN, BDREFVFN, BDREFAUXVFN, BDVALVFN
            from VRHF_EMP_TVERBAINT
            where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFFN between :prrefini and :prreffim
            union all
            select BDCODVER, BDREFTOMADOR, 100 BDTIPOCALC, BDORDEM, BDREFVFT, BDREFAUXVFT, BDVALVFT
            from VRHF_EMP_TVERBATOMADOR
            where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFTOMADOR between :prrefini and :prreffim
            union all
            select BDCODVER, BDREFTOMADOR, 100 BDTIPOCALC, BDORDEM, BDREFVFT, BDREFAUXVFT, BDVALVFT
            from VRHF_EMP_TVERBATOMINT
            where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFTOMADOR between :prrefini and :prreffim
            union all
            select BDCODVER, BDREFFN, 1 BDTIPOCALC, 0 BDCCFC, BDREFVFC, BDREFAUXVFC, BDVALVFC
            from VRHF_EMP_TVERBAFC
            where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFFN between :prrefini and :prreffim
            union all
            select BDCODVER, BDREFFN, 1 BDTIPOCALC, 0 BDCCFC, BDREFVFC, BDREFAUXVFC, BDVALVFC
            from VRHF_EMP_TVERBAFCINT
            where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFFN between :prrefini and :prreffim
            union all
            select BDCODVER, BDREFTOMADOR, 101 BDTIPOCALC, BDORDEM, BDREFVFC, BDREFAUXVFC, BDVALVFC
            from VRHF_EMP_TVERBAFCTOMADOR
            where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFTOMADOR between :prrefini and :prreffim
            union all
            select BDCODVER, BDREFTOMADOR, 101 BDTIPOCALC, BDORDEM, BDREFVFC, BDREFAUXVFC, BDVALVFC
            from VRHF_EMP_TVERBAFCTOMINT
            where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFTOMADOR between :prrefini and :prreffim
            union all
            select BDCODVER, CAST((SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER), 200 BDTIPOCALC,
                   0 BDCCFHE, BDREFVFA, BDREFAUXVFA, BDVALVFA
            from VRHF_EMP_TVERBAFA
            where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and
                  CAST((SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFA AS VARCHAR(10)) FROM 6 FOR 2)) AS INTEGER) between :prrefini and :prreffim
           ) PL
      join VRH_BASE_TCONFMEDIAS C on (C.BDCODVER = PL.BDCODVER)

  into :BDCODVER, :BDREF, :BDTIPO, :BDCC, :BDVREF, :BDVREFAUX, :BDVVAL
  do
    suspend;


  for select PL.BDCODVER, PL.BDREFFHE, 9999 BDTIPOCALC, 0 BDCCF, PL.BDVREFFHE, cast(null as numeric(18, 6)) BDREFAUXFHE, PL.BDVVALFHE
      from (select BDCODVER, BDREFFHE, BDVREFFHE, BDVVALFHE
            from VRHF_EMP_TFICHAHE
            where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFFHE between :prrefini and :prreffim
            union all
            select BDCODVER, BDREFFRV, BDVREFFRV, BDVVALFRV
            from VRHF_EMP_TFICHARV
            where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFFRV between :prrefini and :prreffim
            union all
            select BDCODVER, BDREFFHN, BDVREFFHN, BDVVALFHN
            from VRHF_EMP_TFICHAHN
            where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFFHN between :prrefini and :prreffim
            union all
            select BDCODVER, BDREFFOT, BDVREFFOT, BDVVALFOT
            from VRHF_EMP_TFICHAOUTRAS
            where BDCODEMP = :prcodemp and BDCODCOL = :prcodcol and BDREFFOT between :prrefini and :prreffim
           ) PL
      where not exists (select Y.BDCODEMP from VRHF_EMP_TFOLHANORMAL Y where Y.BDCODEMP = :prcodemp and Y.BDCODCOL = :prcodcol and Y.BDREFFN = PL.BDREFFHE) and
            not exists (select Y.BDCODEMP from VRHF_EMP_TFOLHAINT Y where Y.BDCODEMP = :prcodemp and Y.BDCODCOL = :prcodcol and Y.BDREFFN = PL.BDREFFHE) and
            not exists (select Y.BDCODEMP from VRHF_EMP_TFOLHATOMADOR Y where Y.BDCODEMP = :prcodemp and Y.BDCODCOL = :prcodcol and Y.BDREFTOMADOR = PL.BDREFFHE) and
            not exists (select Y.BDCODEMP from VRHF_EMP_TFOLHATOMINT Y where Y.BDCODEMP = :prcodemp and Y.BDCODCOL = :prcodcol and Y.BDREFTOMADOR = PL.BDREFFHE) and
            not exists (select Y.BDCODEMP from VRHF_EMP_TFOLHACOMP Y where Y.BDCODEMP = :prcodemp and Y.BDCODCOL = :prcodcol and Y.BDREFFN = PL.BDREFFHE) and
            not exists (select Y.BDCODEMP from VRHF_EMP_TFOLHACOMPINT Y where Y.BDCODEMP = :prcodemp and Y.BDCODCOL = :prcodcol and Y.BDREFFN = PL.BDREFFHE) and
            not exists (select Y.BDCODEMP from VRHF_EMP_TFOLTOMCOMP Y where Y.BDCODEMP = :prcodemp and Y.BDCODCOL = :prcodcol and Y.BDREFTOMADOR = PL.BDREFFHE) and
            not exists (select Y.BDCODEMP from VRHF_EMP_TFOLTOMCOMPINT Y where Y.BDCODEMP = :prcodemp and Y.BDCODCOL = :prcodcol and Y.BDREFTOMADOR = PL.BDREFFHE)
  into :BDCODVER, :BDREF, :BDTIPO, :BDCC, :BDVREF, :BDVREFAUX, :BDVVAL
  do
    suspend;

  -- VERIFICA DADOS DE TRANSFERÊNCIAS
  for select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = :prcodemp and BDCODCOLDEST = :prcodcol into :wcodemp, :wcodcol do
    begin
      for select BDCODVER, BDREF, BDTIPO, BDCC, BDVREF, BDVREFAUX, BDVVAL from SP_VRHF_GETMEDIAS(:wcodemp, :wcodcol, :prrefini, :prreffim)
      into :BDCODVER, :BDREF, :BDTIPO, :BDCC, :BDVREF, :BDVREFAUX, :BDVVAL
      do
        suspend;
    end

END^

create or alter procedure SP_VRHF_GETCACHEEMPMEDIAS (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDREF integer,
    BDREFHOREMP DM_BOOLEAN)
as
declare variable WREFFIM integer;
declare variable WREFATU integer;
begin
  wreffim = prreffim;
  wrefatu = 999999;

  while (wreffim >= :prrefini) do
    begin
      BDREF = wreffim;
      if (wrefatu > BDREF) then
         begin
           select first 1 BDREFHOREMP, BDREFEMP
           from VRHF_BASE_TEMPCALC
           where BDCODEMP = :prcodemp and BDREFEMP <= :wreffim
           order by BDREFEMP DESC
           into :BDREFHOREMP, :wrefatu;
           BDREFHOREMP = upper(coalesce(BDREFHOREMP, 'FALSE'));
         end

      suspend;
      select BDREFERENCIA from dec_referencia(:wreffim) into :wreffim;
    end
end^

/* Restore proc. body: SP_VRHF_GETAFASTAMENTOS */
create or alter procedure SP_VRHF_GETAFASTAMENTOS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCOMPETENCIA integer,
    PRSITEMPTRANSF smallint = 0,
    PRPREVIARESC smallint = 0,
    PRCALC13INTEGRALMP963 smallint = 0)
returns (
    BDTIPOSIT integer,
    BDCODSIT integer,
    BDDATAINISEFIP date,
    BDDATAINISIT date,
    BDDATAFIMSIT date,
    BDDIASSIT integer,
    BDNBENEFICIOSIT varchar(20),
    BDDATAPERICIASIT date,
    BDDATAPARTOSIT date,
    BDDESCSIT varchar(70),
    BDGRUPOSIT integer,
    BDCODVER integer,
    BDCODMFGENT integer,
    BDCODMFGSAI integer,
    BDCARENSIT integer,
    BDCODVER15DIAS integer,
    BDTIPOPERDESIT integer,
    BDSALFAMSIT DM_BOOLEAN,
    BDCODSEFENT varchar(5),
    BDCODSEFSAI varchar(5),
    BDRELSIT integer,
    BDINSSINTSIT DM_BOOLEAN,
    BDDIASATESTADO integer,
    BDNAOPRORROGAFERIAS DM_BOOLEAN,
    BDCOVID19 DM_BOOLEAN,
    BDSUSPENSAO DM_BOOLEAN,
    BDNAOALTPERAQUIMP936 DM_BOOLEAN,
    BDBENEFDEFERIDO DM_BOOLEAN,
    BDDATAINIATESTADOAUX date,
    BDDATAFIMATESTADOAUX date,
    BDDATAINIAFASTAUX date,
    BDDATAFIMAFASTAUX date,
    BDDIASPERDEPERAQUI integer,
    BDDIASATESTADOAUX integer,
    BDCODSITAUX integer,
    BDSUBGRUPOSIT integer)
as
declare variable WSQL varchar(10000);
declare variable WRETSIT DM_BOOLEAN;
declare variable WPREVRESC DM_BOOLEAN;
declare variable WPRIDIACOMP date;
declare variable WULTDIACOMP date;
declare variable WINICOVID date;
begin
  /* BDTIPOSIT = 0 São todas as situações
     BDTIPOSIT = 1 Apenas situações de suspensão de trabalho conforme legislação da pandemia COVID-19
  */

  wpridiacomp = cast((substring(cast(prcompetencia as varchar(6)) from 1 for 4)||'-'||substring(cast(prcompetencia as varchar(6)) from 5 for 2)||'-01') as DATE);

  wultdiacomp = wpridiacomp + 32;
  wultdiacomp = cast((substring(cast(wpridiacomp as varchar(10)) from 1 for 4)||'-'||substring(cast(wpridiacomp as varchar(10)) from 6 for 2)||'-01') as DATE);
  wultdiacomp = wultdiacomp - 1;

  if (coalesce(prsitemptransf, 0) > 0) then
     wretsit = 'TRUE';
  else
     wretsit = 'FALSE';

  if (coalesce(prpreviaresc, 0) > 0) then
     wprevresc = 'TRUE';
  else
     wprevresc = 'FALSE';

  wsql = 'select BDCODSIT,BDDATAINISEFIP,BDDATAINISIT,BDDATAFIMSIT,BDDIASSIT,BDNBENEFICIOSIT,BDDATAPERICIASIT,BDDATAPARTOSIT,BDDESCSIT,BDGRUPOSIT,'||
                'BDCODVER,BDCODMFGENT,BDCODMFGSAI,BDCARENSIT,BDCODVER15DIAS,BDTIPOPERDESIT,BDSALFAMSIT,BDCODSEFENT,BDCODSEFSAI,BDRELSIT,BDINSSINTSIT,'||
                'BDDIASATESTADO,BDNAOPRORROGAFERIAS,BDCOVID19,BDSUSPENSAO,BDNAOALTPERAQUIMP936,BDBENEFDEFERIDO,BDDATAINIATESTADOAUX,BDDATAFIMATESTADOAUX,'||
                'BDDATAINIAFASTAUX,BDDATAFIMAFASTAUX,BDDIASPERDEPERAQUI,BDDIASATESTADOAUX,BDCODSITAUX,BDSUBGRUPOSIT '||
         'from VRH_SP_DADOS_SITUACAO(''SIT.BDCODEMP = '||prCodEmp||''',''SIT.BDCODCOL = '||prCodCol||''','||
                                      'null, null,'||
                                      ''''||wretsit||''','||
                                      ''''||wprevresc||''')';



  if (coalesce(prcalc13integralmp963, 0) > 0) then
     wsql = wsql||' where trim(upper(coalesce(BDSUSPENSAO, ''FALSE''))) = ''FALSE'' and '||
                        'BDCODSIT not in (select bdcodsit from VRH_BASE_TPREPSIT where bddescsit = ''Bolsa de qualificação profissional - Art. 476-A da CLT'') ';

  BDTIPOSIT = 0;

  for execute statement wsql
  into :BDCODSIT,:BDDATAINISEFIP,:BDDATAINISIT,:BDDATAFIMSIT,:BDDIASSIT,:BDNBENEFICIOSIT,:BDDATAPERICIASIT,:BDDATAPARTOSIT,:BDDESCSIT,:BDGRUPOSIT,
       :BDCODVER,:BDCODMFGENT,:BDCODMFGSAI,:BDCARENSIT,:BDCODVER15DIAS,:BDTIPOPERDESIT,:BDSALFAMSIT,:BDCODSEFENT,:BDCODSEFSAI,:BDRELSIT,:BDINSSINTSIT,
       :BDDIASATESTADO,:BDNAOPRORROGAFERIAS,:BDCOVID19,:BDSUSPENSAO,:BDNAOALTPERAQUIMP936,:BDBENEFDEFERIDO,:BDDATAINIATESTADOAUX,:BDDATAFIMATESTADOAUX,
       :BDDATAINIAFASTAUX,:BDDATAFIMAFASTAUX,:BDDIASPERDEPERAQUI,:BDDIASATESTADOAUX,:BDCODSITAUX,:BDSUBGRUPOSIT
  do
    begin
      BDTIPOSIT = 0;
    suspend;

      if ((upper(coalesce(BDCOVID19, 'FALSE')) = 'TRUE') and (BDDATAINISEFIP >= '2020-03-19')) then
         begin
           if (prcompetencia > 202004) then
              begin
                winicovid = BDDATAINISEFIP;

                if (winicovid < wpridiacomp) then
                    winicovid = wpridiacomp;

                for select BDCODSIT,BDDATAINISEFIP,BDDATAINISIT,BDDATAFIMSIT,BDDIASSIT,BDNBENEFICIOSIT,BDDATAPERICIASIT,BDDATAPARTOSIT,BDDESCSIT,BDGRUPOSIT,
                           BDCODVER,BDCODMFGENT,BDCODMFGSAI,BDCARENSIT,BDCODVER15DIAS,BDTIPOPERDESIT,BDSALFAMSIT,BDCODSEFENT,BDCODSEFSAI,BDRELSIT,BDINSSINTSIT,
                           BDDIASATESTADO,BDNAOPRORROGAFERIAS,BDCOVID19,BDSUSPENSAO,BDNAOALTPERAQUIMP936,BDBENEFDEFERIDO,BDDATAINIATESTADOAUX,BDDATAFIMATESTADOAUX,
                           BDDATAINIAFASTAUX,BDDATAFIMAFASTAUX,BDDIASPERDEPERAQUI,BDDIASATESTADOAUX,BDCODSITAUX,BDSUBGRUPOSIT
                    from VRH_SP_DADOS_SITUACAO('BDCODEMP = '||:prcodemp, 'BDCODCOL = '||:prcodcol, :winicovid, :wultdiacomp, 'FALSE')
                    where BDDATAINISEFIP >= '2020-04-19' and upper(coalesce(BDCOVID19, 'FALSE')) = 'TRUE'
                    order by BDCODEMP, BDCODCOL, BDDATAINISEFIP
                into :BDCODSIT,:BDDATAINISEFIP,:BDDATAINISIT,:BDDATAFIMSIT,:BDDIASSIT,:BDNBENEFICIOSIT,:BDDATAPERICIASIT,:BDDATAPARTOSIT,:BDDESCSIT,:BDGRUPOSIT,
                     :BDCODVER,:BDCODMFGENT,:BDCODMFGSAI,:BDCARENSIT,:BDCODVER15DIAS,:BDTIPOPERDESIT,:BDSALFAMSIT,:BDCODSEFENT,:BDCODSEFSAI,:BDRELSIT,:BDINSSINTSIT,
                     :BDDIASATESTADO,:BDNAOPRORROGAFERIAS,:BDCOVID19,:BDSUSPENSAO,:BDNAOALTPERAQUIMP936,:BDBENEFDEFERIDO,:BDDATAINIATESTADOAUX,:BDDATAFIMATESTADOAUX,
                     :BDDATAINIAFASTAUX,:BDDATAFIMAFASTAUX,:BDDIASPERDEPERAQUI,:BDDIASATESTADOAUX,:BDCODSITAUX,:BDSUBGRUPOSIT
                do
                  begin
                    BDTIPOSIT = 1;
                    suspend;
                  end
    
              end
         end
    end
end^

create or alter procedure SP_VRHF_GETFERIAS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer,
    PRDATAPREVRESC date = null)
returns (
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDINIPERGOZOFE date,
    BDFIMPERAQUISFE date,
    BDFIMPERGOZOFE date,
    BDDATAPAGFE date,
    BDQTDGOZOFE numeric(15,2),
    BDQTDABONOFE numeric(15,2),
    BDSALDOINIFE numeric(18,6),
    BDSALDOFIMFE numeric(18,6),
    BDBASEIRFE numeric(18,6),
    BDALIQIRFE numeric(18,6),
    BDVALORIRFE numeric(18,6),
    BDBASEINSSFE numeric(18,6),
    BDALIQINSSFE numeric(18,6),
    BDVALORINSSFE numeric(18,6),
    BDDEPFE numeric(18,6),
    BDSALBASEFE numeric(18,6),
    BDSALBASEHEFE numeric(18,6),
    BDDATABAIXAFE date,
    BDCOLETIVASFE DM_BOOLEAN,
    BDREFPAGABOFE numeric(18,6),
    BDFALTASFE numeric(18,6),
    BDFERIADOSFE integer,
    BDVALSALMINVIGENTE numeric(18,6),
    BDMIGRACAO DM_BOOLEAN,
    BDPAGO DM_BOOLEAN,
    BDCALCA13FE DM_BOOLEAN,
    BDTEMPOSERVFE integer)
as
declare variable WSQL varchar(10000);
begin
  wsql = 'select BDINIPERAQUISFE,BDCODFE,max(BDINIPERGOZOFE) BDINIPERGOZOFE,max(BDFIMPERAQUISFE) BDFIMPERAQUISFE,max(BDFIMPERGOZOFE) BDFIMPERGOZOFE,'||
                'max(BDDATAPAGFE) BDDATAPAGFE,max(BDQTDGOZOFE) BDQTDGOZOFE,max(BDQTDABONOFE) BDQTDABONOFE,max(BDSALDOINIFE) BDSALDOINIFE,'||
                'max(BDSALDOFIMFE) BDSALDOFIMFE,max(BDBASEIRFE) BDBASEIRFE,max(BDALIQIRFE) BDALIQIRFE,max(BDVALORIRFE) BDVALORIRFE,max(BDBASEINSSFE) BDBASEINSSFE,'||
                'max(BDALIQINSSFE) BDALIQINSSFE,max(BDVALORINSSFE) BDVALORINSSFE,max(BDDEPFE) BDDEPFE,max(BDSALBASEFE) BDSALBASEFE,max(BDSALBASEHEFE) BDSALBASEHEFE,'||
                'max(BDDATABAIXAFE) BDDATABAIXAFE,max(BDCOLETIVASFE) BDCOLETIVASFE,max(BDREFPAGABOFE) BDREFPAGABOFE,max(BDFALTASFE) BDFALTASFE,'||
                'max(BDFERIADOSFE) BDFERIADOSFE,max(BDVALSALMINVIGENTE) BDVALSALMINVIGENTE,max(BDMIGRACAO) BDMIGRACAO,max(BDPAGO) BDPAGO,max(BDCALCA13FE) BDCALCA13FE,'||
                'max(BDTEMPOSERVFE) BDTEMPOSERVFE '||
         'from VRH_SP_FERIAS_PER_AQUIS(''BDCODEMP = '||prCodEmp||''', ''BDCODCOL = '||prCodCol||''', '||pranomes;


  if (prdataprevresc is not null) then
     wsql = wsql||','''||prdataprevresc||'''';

  wsql = wsql||') group by BDINIPERAQUISFE, BDCODFE  order by BDINIPERAQUISFE, BDCODFE, BDINIPERGOZOFE, BDREFPAGABOFE ';

  for execute statement wsql
  into :BDINIPERAQUISFE, :BDCODFE, :BDINIPERGOZOFE, :BDFIMPERAQUISFE, :BDFIMPERGOZOFE, :BDDATAPAGFE, :BDQTDGOZOFE, :BDQTDABONOFE, :BDSALDOINIFE, :BDSALDOFIMFE,
       :BDBASEIRFE, :BDALIQIRFE, :BDVALORIRFE, :BDBASEINSSFE, :BDALIQINSSFE, :BDVALORINSSFE, :BDDEPFE, :BDSALBASEFE, :BDSALBASEHEFE, :BDDATABAIXAFE, :BDCOLETIVASFE,
       :BDREFPAGABOFE, :BDFALTASFE, :BDFERIADOSFE, :BDVALSALMINVIGENTE, :BDMIGRACAO, :BDPAGO, :BDCALCA13FE, :BDTEMPOSERVFE
  do
    suspend;
end
^

/* Restore proc. body: SP_VRHF_GETFERIASREFERENCIA */
create or alter procedure SP_VRHF_GETFERIASREFERENCIA (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDREFFE integer,
    BDDIASFERFE numeric(18,6),
    BDDIASABOFE numeric(18,6),
    BDDIASSINDFE numeric(18,6),
    BDDIASLICFE numeric(18,6),
    BDBASEINSSRFE numeric(18,6),
    BDALIQINSSRFE numeric(18,6),
    BDVALORINSSRFE numeric(18,6),
    BDBASEIRRFE numeric(18,6),
    BDALIQIRRFE numeric(18,6),
    BDVALORIRRFE numeric(18,6),
    BDDIASFERDOBRFE numeric(18,6),
    BDDIASABODOBRFE numeric(18,6),
    BDBASEIROUTRFE numeric(18,6),
    BDVALORIROUTRFE numeric(18,6),
    BDDEPIRRFE numeric(18,6),
    BDBASEPISRFE numeric(18,6),
    BDBRATAPORFE numeric(18,6),
    BDBASEFGTSRFE numeric(18,6),
    BDVALORFGTSRFE numeric(18,6),
    BDBFGTS13RFE numeric(18,6),
    BDFGTS13RFE numeric(18,6),
    BDINIPERGOZOFE date,
    BDFIMPERGOZOFE date,
    BDREFPAGABOFE integer,
    BDDATAPAGFE date,
    BDFIMPERAQUISFE date)
as
begin
  for select RFER.BDINIPERAQUISFE,RFER.BDCODFE,RFER.BDREFFE,RFER.BDDIASFERFE,RFER.BDDIASABOFE,RFER.BDDIASSINDFE,RFER.BDDIASLICFE,RFER.BDBASEINSSRFE,RFER.BDALIQINSSRFE,
             RFER.BDVALORINSSRFE,RFER.BDBASEIRRFE,RFER.BDALIQIRRFE,RFER.BDVALORIRRFE,RFER.BDDIASFERDOBRFE,RFER.BDDIASABODOBRFE,RFER.BDBASEIROUTRFE,RFER.BDVALORIROUTRFE,
             RFER.BDDEPIRRFE,RFER.BDBASEPISRFE,RFER.BDBRATAPORFE,RFER.BDBASEFGTSRFE,RFER.BDVALORFGTSRFE,RFER.BDBFGTS13RFE,RFER.BDFGTS13RFE, FER.BDINIPERGOZOFE,
             FER.BDFIMPERGOZOFE, FER.BDREFPAGABOFE, FER.BDDATAPAGFE, FER.BDFIMPERAQUISFE
      from VRH_EMP_TFERIASREF RFER
      join VRH_EMP_TFERIAS FER on (FER.BDCODEMP = RFER.BDCODEMP and FER.BDCODCOL = RFER.BDCODCOL and FER.BDINIPERAQUISFE = RFER.BDINIPERAQUISFE and FER.BDCODFE = RFER.BDCODFE)
      where RFER.BDCODEMP = :prCodEmp and RFER.BDCODCOL = :prCodCol
             and ((RFER.BDREFFE = :pranomes) or (RFER.BDREFFE = :pranomes) or (FER.BDREFINIFE < :pranomes and FER.BDREFFIMFE > :pranomes))
  into :BDINIPERAQUISFE,:BDCODFE,:BDREFFE,:BDDIASFERFE,:BDDIASABOFE, :BDDIASSINDFE, :BDDIASLICFE, :BDBASEINSSRFE, :BDALIQINSSRFE,
       :BDVALORINSSRFE, :BDBASEIRRFE, :BDALIQIRRFE, :BDVALORIRRFE, :BDDIASFERDOBRFE, :BDDIASABODOBRFE, :BDBASEIROUTRFE, :BDVALORIROUTRFE,
       :BDDEPIRRFE, :BDBASEPISRFE, :BDBRATAPORFE, :BDBASEFGTSRFE, :BDVALORFGTSRFE, :BDBFGTS13RFE, :BDFGTS13RFE, :BDINIPERGOZOFE,
       :BDFIMPERGOZOFE, :BDREFPAGABOFE, :BDDATAPAGFE, :BDFIMPERAQUISFE
  do
    suspend;
end^

create or alter procedure SP_VRHF_GETRESCISAO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRULTDIA date,
    PRPREVIA smallint = 0,
    PRTODASATEFIMMES smallint = 0)
returns (
    BDTIPOMOV integer,
    BDDATARESCISAO date,
    BDDIASINDENIZADOS integer,
    BDDIASTRABALHADOS integer,
    BDDATANOTIF date,
    BDPROJECAOAVISO date,
    BDCODPRES integer,
    BDDATAAVPREVIO date,
    BDDATAHOM date,
    BDDATAPAGRESCISAO date,
    BDSALDOFGTS numeric(18,2),
    BDCALCFGTSMESANT DM_BOOLEAN,
    BDMAIORREMUNERACAO numeric(18,2),
    BDDATAPAGGRFC date,
    BDREPOSICAOVAGA DM_BOOLEAN,
    BDDISSIDIO DM_BOOLEAN,
    BDDATADISSIDIO date,
    BDDESCANSOINDENIZADO DM_BOOLEAN,
    BDREFRESCISAO integer,
    BDDISPAVPREVRESC DM_BOOLEAN,
    BDNOVOEMPRESC DM_BOOLEAN,
    BDPERTRCTRESC numeric(18,2),
    BDPERFGTSRESC numeric(18,2),
    BDREFPROJECAOAVISO integer,
    BDCODMFG integer,
    BDCODSAQUE integer,
    BDCODMRAIS integer,
    BDCODMCAG integer,
    BDDESCPRES varchar(110),
    BDINIPRES integer,
    BDJCPRES DM_BOOLEAN,
    BDAVPREPRES integer,
    BDGRRFPRES integer,
    BDESTPRES DM_BOOLEAN,
    BDINDFER13 DM_BOOLEAN,
    BDTERMCONTRPRES DM_BOOLEAN,
    BDMULTAPRES DM_BOOLEAN,
    BDDIASAVPREPRES integer,
    BDDIASPAGPRES integer,
    BDCODHNET integer,
    BDMULTA10PRES DM_BOOLEAN,
    BDPERCMULTAFGTS numeric(18,2),
    BDPERCMULTAFGTSCS numeric(18,2),
    BDCODMOTESRESC integer)
as
declare variable WSQL varchar(5000);
begin
  if (coalesce(prprevia, 0) > 0) then
     wsql = 'select PRESC.BDTIPOMOV,RESC.BDDATARESCISAOPREV,RESC.BDDIASINDENIZADOSPREV,'||
                   'RESC.BDDIASTRABALHADOSPREV,RESC.BDDATANOTIFPREV,RESC.BDPROJECAOAVISOPREV,RESC.BDCODPRES,'||
                   'RESC.BDDATAAVPREVIOPREV,RESC.BDDATAHOMPREV,RESC.BDDATAPAGRESCISAOPREV,RESC.BDSALDOFGTSPREV,'||
                   'RESC.BDCALCFGTSMESANTPREV,RESC.BDMAIORREMUNERACAOPREV,RESC.BDDATAPAGGRFCPREV,RESC.BDREPOSICAOVAGAPREV,'||
                   'RESC.BDDISSIDIOPREV,RESC.BDDATADISSIDIOPREV,RESC.BDDESCANSOINDENIZADOPREV,RESC.BDREFRESCISAOPREV,'||
                   'RESC.BDDISPAVPREVRESCPREV,RESC.BDNOVOEMPRESCPREV,RESC.BDPERTRCTRESCPREV,0 BDREFPROJECAOAVISO,'||
                   'RESC.BDPERFGTSRESCPREV,PRESC.BDCODMFG,PRESC.BDCODSAQUE,PRESC.BDCODMRAIS,PRESC.BDCODMCAG,PRESC.BDDESCPRES,'||
                   'PRESC.BDINIPRES,PRESC.BDJCPRES,PRESC.BDAVPREPRES,PRESC.BDGRRFPRES,PRESC.BDESTPRES,PRESC.BDINDFER13,'||
                   'PRESC.BDTERMCONTRPRES,PRESC.BDMULTAPRES,PRESC.BDDIASAVPREPRES,PRESC.BDDIASPAGPRES,PRESC.BDCODHNET,'||
                   'PRESC.BDMULTA10PRES,PRESC.BDPERCMULTAFGTS, PRESC.BDPERCMULTAFGTSCS, PRESC.BDCODMOTESRESC '||
            'from VRH_EMP_TRESCISAO_PREVIA RESC ';
  else
     wsql = 'select PRESC.BDTIPOMOV,RESC.BDDATARESCISAO,RESC.BDDIASINDENIZADOS,'||
                   'RESC.BDDIASTRABALHADOS, RESC.BDDATANOTIF, RESC.BDPROJECAOAVISO,RESC.BDCODPRES,'||
                   'RESC.BDDATAAVPREVIO,RESC.BDDATAHOM,RESC.BDDATAPAGRESCISAO,RESC.BDSALDOFGTS,'||
                   'RESC.BDCALCFGTSMESANT,RESC.BDMAIORREMUNERACAO,RESC.BDDATAPAGGRFC,RESC.BDREPOSICAOVAGA,'||
                   'RESC.BDDISSIDIO,RESC.BDDATADISSIDIO,RESC.BDDESCANSOINDENIZADO,RESC.BDREFRESCISAO,'||
                   'RESC.BDDISPAVPREVRESC,RESC.BDNOVOEMPRESC,RESC.BDPERTRCTRESC,RESC.BDREFPROJECAOAVISO,'||
                   'RESC.BDPERFGTSRESC,PRESC.BDCODMFG,PRESC.BDCODSAQUE,PRESC.BDCODMRAIS,PRESC.BDCODMCAG,PRESC.BDDESCPRES,'||
                   'PRESC.BDINIPRES,PRESC.BDJCPRES,PRESC.BDAVPREPRES,PRESC.BDGRRFPRES,PRESC.BDESTPRES,PRESC.BDINDFER13,'||
                   'PRESC.BDTERMCONTRPRES,PRESC.BDMULTAPRES,PRESC.BDDIASAVPREPRES,PRESC.BDDIASPAGPRES,PRESC.BDCODHNET,'||
                   'PRESC.BDMULTA10PRES,PRESC.BDPERCMULTAFGTS,PRESC.BDPERCMULTAFGTSCS,PRESC.BDCODMOTESRESC '||
            'from VRH_EMP_TRESCISAO RESC ';

  wsql = wsql||'join VRH_BASE_TPREPRESC PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES) '||
         'where RESC.BDCODEMP = '||prcodemp||' and RESC.BDCODCOL = '||prCodCol;


  if (coalesce(prprevia, 0) > 0) then
     wsql = wsql||' and RESC.BDDATARESCISAOPREV >= '''||substring(cast(prultdia as varchar(10)) from 6 for 2)||'-01-'||substring(cast(prultdia as varchar(10)) from 1 for 4)||''' ';
  else
  if (coalesce(prtodasatefimmes, 0) > 0) then
     wsql = wsql||' and RESC.BDDATARESCISAO <= '''||prultdia||''' ';
  else
     wsql = wsql||' and RESC.BDDATARESCISAO >= '''||substring(cast(prultdia as varchar(10)) from 6 for 2)||'-01-'||substring(cast(prultdia as varchar(10)) from 1 for 4)||''' ';

  for execute statement wsql
  into :BDTIPOMOV,:BDDATARESCISAO,:BDDIASINDENIZADOS,:BDDIASTRABALHADOS,:BDDATANOTIF,:BDPROJECAOAVISO,
       :BDCODPRES,:BDDATAAVPREVIO,:BDDATAHOM,:BDDATAPAGRESCISAO,:BDSALDOFGTS,:BDCALCFGTSMESANT,:BDMAIORREMUNERACAO,
       :BDDATAPAGGRFC,:BDREPOSICAOVAGA,:BDDISSIDIO,:BDDATADISSIDIO,:BDDESCANSOINDENIZADO,:BDREFRESCISAO,
       :BDDISPAVPREVRESC,:BDNOVOEMPRESC,:BDPERTRCTRESC,:BDREFPROJECAOAVISO,:BDPERFGTSRESC,:BDCODMFG,:BDCODSAQUE,
       :BDCODMRAIS,:BDCODMCAG,:BDDESCPRES,:BDINIPRES,:BDJCPRES,:BDAVPREPRES,:BDGRRFPRES,:BDESTPRES,:BDINDFER13,
       :BDTERMCONTRPRES,:BDMULTAPRES,:BDDIASAVPREPRES,:BDDIASPAGPRES,:BDCODHNET,:BDMULTA10PRES,:BDPERCMULTAFGTS,
       :BDPERCMULTAFGTSCS,:BDCODMOTESRESC
  do
    suspend;
end^

create or alter procedure SP_VRHF_GETCOOPARTDEPFORMULAS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer,
    PRPLANOSAUDE integer)
returns (
    BDTIPO integer,
    BDCODOPERADORA integer,
    BDCODCONVENIO integer,
    BDREF integer,
    BDCODDPN integer,
    BDNOME DM_BDNOMCOL,
    BDCPF varchar(14),
    BDVALORMENSALIDADE numeric(18,2),
    BDVALORCOPAR numeric(18,2),
    BDCODTIPOCONV integer,
    BDTIPOFAIXA integer,
    BDCODTIPO integer,
    BDMENSFORMULA DM_BOOLEAN,
    BDCODVERTITMENS integer,
    BDCODVERTITCOP integer,
    BDCODVERDEPMENS integer,
    BDCODVERDEPCOP integer,
    BDRAZAOSOCIAL varchar(80))
as
declare variable WSQL varchar(5000);
begin
  wsql = 'select OPSAU.BDTIPO,OPSAU.BDCODOPERADORA,OPSAU.BDCODCONVENIO,OPSAU.BDREF,OPSAU.BDCODDPN,OPSAU.BDNOME,OPSAU.BDCPF,OPSAU.BDVALORMENSALIDADE,'||
                'OPSAU.BDVALORCOPAR,OPSAU.BDCODTIPOCONV,OPSAU.BDTIPOFAIXA,OPSAU.BDCODTIPO,OPSAU.BDMENSFORMULA,OPSAU.BDCODVERTITMENS,OPSAU.BDCODVERTITCOP,'||
                'OPSAU.BDCODVERDEPMENS,OPSAU.BDCODVERDEPCOP,CONVSAU.BDRAZAOSOCIAL '||
         'from SP_VRHM_EMP_VAL_TOD_OP_ATU2(''BDCODEMP = '||prCodEmp||''', ''BDCODCOL = '||prCodCol||''', '||pranomes||', '||prplanosaude||', 0) OPSAU '||
         'left outer join VRH_BASE_TCONVSAUDE CONVSAU on (CONVSAU.BDCODCONVENIO = OPSAU.BDCODOPERADORA) '||
         'where coalesce(OPSAU.BDCODPLACONVSAU, 0) > 0 ';

  for execute statement wsql
  into :BDTIPO,:BDCODOPERADORA,:BDCODCONVENIO,:BDREF,:BDCODDPN,:BDNOME,:BDCPF,:BDVALORMENSALIDADE,
       :BDVALORCOPAR,:BDCODTIPOCONV,:BDTIPOFAIXA,:BDCODTIPO,:BDMENSFORMULA,:BDCODVERTITMENS,:BDCODVERTITCOP,
       :BDCODVERDEPMENS,:BDCODVERDEPCOP,:BDRAZAOSOCIAL
  do
    suspend;
end^

/* Restore proc. body: SP_VRHF_GETCONTRATOINTERMITENTE */
create or alter procedure SP_VRHF_GETCONTRATOINTERMITENTE (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCONTRATOINTERMITENTE integer)
returns (
    BDCODCONTTI integer,
    BDDESCCONTRATOTI varchar(2000),
    BDDATACONVTI date,
    BDHORACONVTI time,
    BDCOMUNICCONVTI varchar(500),
    BDDATAINISERVTI date,
    BDDATAFIMSERVTI date,
    BDDATAPAGTI date,
    BDTIPOHORARIOTI integer,
    BDCODQHH integer,
    BDLOCALTI integer,
    BDCEPTI DM_CEP,
    BDLOGRTI DM_LOGRADOURO,
    BDENDTI DM_BDENDERECO,
    BDNUMENDTI DM_BDENDERECO_NR,
    BDCOMPLTI DM_BDCOMPENDERECO,
    BDBAITI DM_BDBAIRRO,
    BDCODCID integer,
    BDDIADESCANSO integer,
    BDDIACOMPENSADO integer,
    BDAPENASRESCISAO DM_BOOLEAN,
    BDCONVRESCTI DM_BOOLEAN,
    BDCODCONTESOCIAL varchar(30),
    BDLANCSITUACAO DM_BOOLEAN)
as
begin
  for select CONT.BDCODCONTTI, CONT.BDDESCCONTRATOTI, CONT.BDDATACONVTI, CONT.BDHORACONVTI, CONT.BDCOMUNICCONVTI,
             CONT.BDDATAINISERVTI, CONT.BDDATAFIMSERVTI, CONT.BDDATAPAGTI, CONT.BDTIPOHORARIOTI, CONT.BDCODQHH,
             CONT.BDLOCALTI, CONT.BDCEPTI, CONT.BDLOGRTI, CONT.BDENDTI, CONT.BDNUMENDTI, CONT.BDCOMPLTI, CONT.BDBAITI,
             CONT.BDCODCID, CONT.BDDIADESCANSO, CONT.BDDIACOMPENSADO, CONT.BDAPENASRESCISAO, CONT.BDCONVRESCTI,
             CONT.BDCODCONTESOCIAL, CONT.BDLANCSITUACAO
      from VRH_EMP_TINTERMITENTE CONT
      join VRH_EMP_TINTERMITENTE_ACEI ACEITE on (ACEITE.BDCODEMP = CONT.BDCODEMP and ACEITE.BDCODCOL = CONT.BDCODCOL and ACEITE.BDCODCONTTI = CONT.BDCODCONTTI)
      where coalesce(ACEITE.BDSTATUSACEITETI, 0) = 2 and
            CONT.BDCODEMP = :prCodEmp and CONT.BDCODCOL = :prCodCol and CONT.BDCODCONTTI = :prcontratointermitente
  into :BDCODCONTTI, :BDDESCCONTRATOTI, :BDDATACONVTI, :BDHORACONVTI, :BDCOMUNICCONVTI,
       :BDDATAINISERVTI, :BDDATAFIMSERVTI, :BDDATAPAGTI, :BDTIPOHORARIOTI, :BDCODQHH,
       :BDLOCALTI, :BDCEPTI, :BDLOGRTI, :BDENDTI, :BDNUMENDTI, :BDCOMPLTI, :BDBAITI,
       :BDCODCID, :BDDIADESCANSO, :BDDIACOMPENSADO, :BDAPENASRESCISAO, :BDCONVRESCTI,
       :BDCODCONTESOCIAL, :BDLANCSITUACAO
  do
    suspend;
end^

/* Restore proc. body: SP_VRHF_GETINTERMITENTEQH */
create or alter procedure SP_VRHF_GETINTERMITENTEQH (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCONTRATOINTERMITENTE integer)
returns (
    BDCODCONTTI integer,
    BDDATADTI date,
    BDCODQHH integer,
    BDCODQHHS integer,
    BDQHHSENT time,
    BDQHHSSAI time)
as
begin
  for select BDCODCONTTI, BDDATADTI, BDCODQHH, BDCODQHHS, BDQHHSENT, BDQHHSSAI
      from (select DIAS.BDCODCONTTI, DIAS.BDDATADTI, DIAS.BDCODQHH, HORA.BDCODQHHS, HORA.BDQHHSENT, HORA.BDQHHSSAI
            from VRH_EMP_TINTERMITENTE CONT
            join VRH_EMP_TINTERMITENTE_ACEI ACEITE on (ACEITE.BDCODEMP = CONT.BDCODEMP and ACEITE.BDCODCOL = CONT.BDCODCOL and ACEITE.BDCODCONTTI = CONT.BDCODCONTTI)
            join VRH_EMP_TINTERMITENTE_QHDIAS DIAS on (DIAS.BDCODEMP = CONT.BDCODEMP and DIAS.BDCODCOL = CONT.BDCODCOL and DIAS.BDCODCONTTI = CONT.BDCODCONTTI)
            join VRH_BASE_TQH_HORAS HORA on (HORA.BDCODQHH = DIAS.BDCODQHH)
            where coalesce(ACEITE.BDSTATUSACEITETI, 0) = 2 and
                  CONT.BDCODEMP = :prCodEmp and CONT.BDCODCOL = :prCodCol and CONT.BDCODCONTTI = :prcontratointermitente
            union all
            select CONT.BDCODCONTTI, cast(null as date) BDDATADTI, CONT.BDCODQHH, HORA.BDCODQHHS, HORA.BDQHHSENT, HORA.BDQHHSSAI
            from VRH_EMP_TINTERMITENTE CONT
            join VRH_EMP_TINTERMITENTE_ACEI ACEITE on (ACEITE.BDCODEMP = CONT.BDCODEMP and ACEITE.BDCODCOL = CONT.BDCODCOL and ACEITE.BDCODCONTTI = CONT.BDCODCONTTI)
            join VRH_BASE_TQH_HORAS HORA on (HORA.BDCODQHH = CONT.BDCODQHH)
            where coalesce(ACEITE.BDSTATUSACEITETI, 0) = 2 and
                  CONT.BDCODEMP = :prCodEmp and CONT.BDCODCOL = :prcodcol and CONT.BDCODCONTTI = :prcontratointermitente
           )
  into :BDCODCONTTI, :BDDATADTI, :BDCODQHH, :BDCODQHHS, :BDQHHSENT, :BDQHHSSAI
  do
    suspend;
end^

/* Restore proc. body: SP_VRHF_GETAPURACAOREFEICAO */
create or alter procedure SP_VRHF_GETAPURACAOREFEICAO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDCODCONVREF integer,
    BDCOMPETENCIA integer,
    BDQUANTIDADE integer,
    BDTPAPURACAO integer,
    BDPERIODO varchar(16),
    BDINICIOAPURACAO date,
    BDFINALAPURACAO date,
    BDVALUNI DM_NUMERIC_15_2)
as
declare variable WVALUNI DM_NUMERIC_15_2;
begin
  for select BDCODCONVREF,BDCOMPETENCIA,BDQUANTIDADE,BDTPAPURACAO,BDPERIODO,BDINICIOAPURACAO,BDFINALAPURACAO
      from VRHF_EMP_TAPVALREF
      where BDCODEMP = :prCodEmp and BDCODCOL = :prCodCol and BDCOMPETENCIA = :pranomes
  into :BDCODCONVREF,:BDCOMPETENCIA,:BDQUANTIDADE,:BDTPAPURACAO,:BDPERIODO,:BDINICIOAPURACAO,:BDFINALAPURACAO
  do
    begin
      wvaluni = null;
      select first 1 CAST(BDVALUNI as DM_NUMERIC_15_2) from VRHF_BASE_TCONVREFEICAO_REF where BDCODCONVREF = :BDCODCONVREF and BDREF <= :pranomes
      order by BDREF DESC into :wvaluni;

      BDVALUNI = coalesce(:wvaluni, 0);

    suspend;
    end
end^

/* Restore proc. body: SP_VRHF_GETAPURACAOTRANSPORTE */
create or alter procedure SP_VRHF_GETAPURACAOTRANSPORTE (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDCODITI integer,
    BDCOMPETENCIA integer,
    BDQUANTIDADE integer,
    BDTPAPURACAO integer,
    BDVALITI DM_NUMERIC_18_3)
as
declare variable WVALITI DM_NUMERIC_18_3;
begin
  for select BDCODITI,BDCOMPETENCIA,BDQUANTIDADE,BDTPAPURACAO
      from VRHF_EMP_TAPVALTRANS
      where BDCODEMP = :prCodEmp and BDCODCOL = :prCodCol and BDCOMPETENCIA = :pranomes
  into :BDCODITI,:BDCOMPETENCIA,:BDQUANTIDADE,:BDTPAPURACAO
  do
    begin
      wvaliti = null;
      select first 1 CAST(BDVALITI AS dm_numeric_18_3)
      from VRHF_BASE_TITINERARIO_REF
      where BDCODITI = :BDCODITI and BDREFERENCIA <= :pranomes
      order by BDREFERENCIA DESC
      into :wvaliti;
      BDVALITI = coalesce(wvaliti, 0);
    suspend;

    end
end^

create or alter procedure SP_VRHF_GETESTORNOFGTS13 (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDMES integer,
    BDREF integer,
    BDTIPO integer,
    BDVALORFGTS numeric(18,2),
    BDCODTPCC integer)
as
declare variable WMESANT integer;
begin
  select BDREFERENCIA from dec_referencia(:pranomes, 1) into :wmesant;

  for select FOL.BDMES, FOL.BDREF, FOL.BDTIPO, FOL.BDVALORFGTS, HIS.BDCODTPCC
      from (select case when BDREFA13 < :pranomes then 1 else 0 end BDMES, BDCODEMP, BDCODCOL, BDREFA13 BDREF, 0 BDTIPO, BDFGTSA13 BDVALORFGTS, BDORDEM
            from VRHF_EMP_TA13SAL
            where BDCODEMP = :prCodEmp and BDCODCOL = :prCodCol and BDREFA13 between :wmesant and :pranomes
            union all
            select case when BDREF13 < :pranomes then 1 else 0 end BDMES, BDCODEMP, BDCODCOL, BDREF13, 1 BDTIPO, BDFGTS13, BDORDEM
            from VRHF_EMP_T13SAL
            where BDCODEMP = :prCodEmp and BDCODCOL = :prCodCol and BDREF13 between :wmesant and :pranomes
            union all
            select case when BDREFC13 < :pranomes then 1 else 0 end BDMES, BDCODEMP, BDCODCOL, BDREFC13, 2 BDTIPO, BDFGTSC13, BDORDEM
            from VRHF_EMP_TC13SAL
            where BDCODEMP = :prCodEmp and BDCODCOL = :prCodCol and BDREFC13 between :wmesant and :pranomes
      ) FOL
      left outer join VRHF_EMP_TPREPFN HIS on (HIS.BDCODEMP = FOL.BDCODEMP and HIS.BDCODCOL = FOL.BDCODCOL and HIS.BDORDEM = FOL.BDORDEM)
  into :BDMES, :BDREF, :BDTIPO, :BDVALORFGTS, :BDCODTPCC
  do
    suspend;
end^

create or alter procedure SP_VRHF_GETBASEIRFN (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer,
    PRCOMPETENCIA integer)
returns (
    BDREFFIR integer,
    BDREFIRFIR integer,
    BDTIPOCALCFIR integer,
    BDBASEIRFIR numeric(18,2),
    BDVALINSSFIR numeric(18,2),
    BDVALIRFIR numeric(18,2),
    BDDESCBASEIRFIR numeric(18,2),
    BDPREVPRIVFIR numeric(18,2),
    BDDATAFIR date,
    BDDATAPROC date,
    BDHORAPROC time)
as
declare variable WEMP varchar(50);
declare variable WCOL varchar(50);
begin
  wEmp = 'FOL.BDCODEMP = '||:prCodEmp;
  wCol = 'FOL.BDCODCOL = '||:prCodCol;

  pranomes = coalesce(pranomes, 0);
  prcompetencia = coalesce(prcompetencia, 0);

  if (pranomes <> prcompetencia) then
     begin
       for select FOL.BDREF BDREFFIR,FOL.BDREFPAG BDREFIRFIR,FOL.BDTIPO BDTIPOCALCFIR,FOL.BDRENDTRIBUTAVEL - FOL.BDPENJUD - FOL.BDPENALIM BDBASEIRFIR,FOL.BDINSS BDVALINSSFIR,
                  FOL.BDIR BDVALIRFIR,0 BDDESCBASEIRFIR,FOL.BDPREVPRIV BDPREVPRIVFIR,FOL.BDDATAPGTO BDDATAFIR,FOL.BDDATAPROC,FOL.BDHORAPROC
           from SP_VRHF_DADOS_IR_FN(:wEmp, :wCol, :pranomes, :pranomes) FOL
           left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL)
           where ((RESC.BDREFRESCISAO > 0) and (not FOL.BDREF = RESC.BDREFRESCISAO)) or (RESC.BDREFRESCISAO is null)
           union all
           select FOL.BDREF BDREFFIR,FOL.BDREFPAG BDREFIRFIR,FOL.BDTIPO BDTIPOCALCFIR,FOL.BDRENDTRIBUTAVEL - FOL.BDPENJUD - FOL.BDPENALIM BDBASEIRFIR,FOL.BDINSS BDVALINSSFIR,
             FOL.BDIR BDVALIRFIR,0 BDDESCBASEIRFIR,FOL.BDPREVPRIV BDPREVPRIVFIR,FOL.BDDATAPGTO BDDATAFIR,FOL.BDDATAPROC,FOL.BDHORAPROC
           from SP_VRHF_DADOS_IR_FC(:wEmp, :wCol, :pranomes, :pranomes) FOL
           left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL)
           where ((RESC.BDREFRESCISAO > 0) and (not FOL.BDREF = RESC.BDREFRESCISAO)) or (RESC.BDREFRESCISAO is null)
           union all
           select FOL.BDREF BDREFFIR,FOL.BDREFPAG BDREFIRFIR,FOL.BDTIPO BDTIPOCALCFIR,FOL.BDRENDTRIBUTAVEL - FOL.BDPENJUD - FOL.BDPENALIM BDBASEIRFIR,FOL.BDINSS BDVALINSSFIR,
             FOL.BDIR BDVALIRFIR,0 BDDESCBASEIRFIR,FOL.BDPREVPRIV BDPREVPRIVFIR,FOL.BDDATAPGTO BDDATAFIR,FOL.BDDATAPROC,FOL.BDHORAPROC
           from SP_VRHF_DADOS_IR_AD(:wEmp, :wCol, :pranomes, :pranomes) FOL
           left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL)
           where ((RESC.BDREFRESCISAO > 0) and (not FOL.BDREF = RESC.BDREFRESCISAO)) or (RESC.BDREFRESCISAO is null)
       into :BDREFFIR,:BDREFIRFIR,:BDTIPOCALCFIR,:BDBASEIRFIR,:BDVALINSSFIR,:BDVALIRFIR,:BDDESCBASEIRFIR,:BDPREVPRIVFIR,:BDDATAFIR,:BDDATAPROC,:BDHORAPROC
       do
         suspend;
     end
  else
     begin
       for select FOL.BDREF BDREFFIR,FOL.BDREFPAG BDREFIRFIR,FOL.BDTIPO BDTIPOCALCFIR,FOL.BDRENDTRIBUTAVEL - FOL.BDPENJUD - FOL.BDPENALIM BDBASEIRFIR,FOL.BDINSS BDVALINSSFIR,
                  FOL.BDIR BDVALIRFIR,0 BDDESCBASEIRFIR,FOL.BDPREVPRIV BDPREVPRIVFIR,FOL.BDDATAPGTO BDDATAFIR,FOL.BDDATAPROC,FOL.BDHORAPROC
           from SP_VRHF_DADOS_IR_FN(:wEmp, :wCol, :pranomes, :pranomes) FOL
           left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL)
           where ((RESC.BDREFRESCISAO > 0) and (not FOL.BDREF = RESC.BDREFRESCISAO)) or (RESC.BDREFRESCISAO is null)
           union all
           select FOL.BDREF BDREFFIR,FOL.BDREFPAG BDREFIRFIR,FOL.BDTIPO BDTIPOCALCFIR,FOL.BDRENDTRIBUTAVEL - FOL.BDPENJUD - FOL.BDPENALIM BDBASEIRFIR,FOL.BDINSS BDVALINSSFIR,
             FOL.BDIR BDVALIRFIR,0 BDDESCBASEIRFIR,FOL.BDPREVPRIV BDPREVPRIVFIR,FOL.BDDATAPGTO BDDATAFIR,FOL.BDDATAPROC,FOL.BDHORAPROC
           from SP_VRHF_DADOS_IR_FC(:wEmp, :wCol, :pranomes, :pranomes) FOL
           left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL)
           where ((RESC.BDREFRESCISAO > 0) and (not FOL.BDREF = RESC.BDREFRESCISAO)) or (RESC.BDREFRESCISAO is null)
           union all
           select FOL.BDREF BDREFFIR,FOL.BDREFPAG BDREFIRFIR,FOL.BDTIPO BDTIPOCALCFIR,FOL.BDRENDTRIBUTAVEL - FOL.BDPENJUD - FOL.BDPENALIM BDBASEIRFIR,FOL.BDINSS BDVALINSSFIR,
             FOL.BDIR BDVALIRFIR,0 BDDESCBASEIRFIR,FOL.BDPREVPRIV BDPREVPRIVFIR,FOL.BDDATAPGTO BDDATAFIR,FOL.BDDATAPROC,FOL.BDHORAPROC
           from SP_VRHF_DADOS_IR_AD(:wEmp, :wCol, :pranomes, :pranomes) FOL
       into :BDREFFIR,:BDREFIRFIR,:BDTIPOCALCFIR,:BDBASEIRFIR,:BDVALINSSFIR,:BDVALIRFIR,:BDDESCBASEIRFIR,:BDPREVPRIVFIR,:BDDATAFIR,:BDDATAPROC,:BDHORAPROC
       do
         suspend;
     end

  for select FOL.BDREF BDREFFIR,FOL.BDREFPAG BDREFIRFIR,FOL.BDTIPO BDTIPOCALCFIR,FOL.BDRENDTRIBUTAVEL - FOL.BDPENJUD - FOL.BDPENALIM BDBASEIRFIR,FOL.BDINSS BDVALINSSFIR,
        FOL.BDIR BDVALIRFIR,0 BDDESCBASEIRFIR,FOL.BDPREVPRIV BDPREVPRIVFIR,FOL.BDDATAPGTO BDDATAFIR,FOL.BDDATAPROC,FOL.BDHORAPROC
      from SP_VRHF_DADOS_IR_13(:wEmp, :wCol, :pranomes, :pranomes) FOL
      left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL)
      where ((RESC.BDREFRESCISAO > 0) and (not FOL.BDREF = RESC.BDREFRESCISAO)) or (RESC.BDREFRESCISAO is null)
      union all
      select FOL.BDREF BDREFFIR,FOL.BDREFPAG BDREFIRFIR,FOL.BDTIPO BDTIPOCALCFIR,FOL.BDRENDTRIBUTAVEL - FOL.BDPENJUD - FOL.BDPENALIM BDBASEIRFIR,FOL.BDINSS BDVALINSSFIR,
        FOL.BDIR BDVALIRFIR,0 BDDESCBASEIRFIR,FOL.BDPREVPRIV BDPREVPRIVFIR,FOL.BDDATAPGTO BDDATAFIR,FOL.BDDATAPROC,FOL.BDHORAPROC
      from SP_VRHF_DADOS_IR_C13(:wEmp, :wCol, :pranomes, :pranomes) FOL
      left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP) and (RESC.BDCODCOL = FOL.BDCODCOL)
      where ((RESC.BDREFRESCISAO > 0) and (not FOL.BDREF = RESC.BDREFRESCISAO)) or (RESC.BDREFRESCISAO is null)
  into :BDREFFIR,:BDREFIRFIR,:BDTIPOCALCFIR,:BDBASEIRFIR,:BDVALINSSFIR,:BDVALIRFIR,:BDDESCBASEIRFIR,:BDPREVPRIVFIR,:BDDATAFIR,:BDDATAPROC,:BDHORAPROC
  do
    suspend;

  if (pranomes <> prcompetencia) then
     begin
       for select FOL.BDREF BDREFFIR,FOL.BDREFPAG BDREFIRFIR,FOL.BDTIPO BDTIPOCALCFIR,FOL.BDRENDTRIBUTAVEL - FOL.BDPENJUD - FOL.BDPENALIM BDBASEIRFIR,FOL.BDINSS BDVALINSSFIR,
             FOL.BDIR BDVALIRFIR,0 BDDESCBASEIRFIR,FOL.BDPREVPRIV BDPREVPRIVFIR,FOL.BDDATAPGTO BDDATAFIR,FOL.BDDATAPROC,FOL.BDHORAPROC
           from SP_VRHF_DADOS_IR_FN(:wEmp, :wCol, :prcompetencia, :prcompetencia) FOL
           join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL and RESC.BDREFPAGRESCISAO = :prcompetencia and RESC.BDREFRESCISAO = FOL.BDREF)
           union all
           select FOL.BDREF BDREFFIR,FOL.BDREFPAG BDREFIRFIR,FOL.BDTIPO BDTIPOCALCFIR,FOL.BDRENDTRIBUTAVEL - FOL.BDPENJUD - FOL.BDPENALIM BDBASEIRFIR,FOL.BDINSS BDVALINSSFIR,
             FOL.BDIR BDVALIRFIR,0 BDDESCBASEIRFIR,FOL.BDPREVPRIV BDPREVPRIVFIR,FOL.BDDATAPGTO BDDATAFIR,FOL.BDDATAPROC,FOL.BDHORAPROC
           from SP_VRHF_DADOS_IR_FC(:wEmp, :wCol, :prcompetencia, :prcompetencia) FOL
           join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL and RESC.BDREFPAGRESCISAO = :prcompetencia and RESC.BDREFRESCISAO = FOL.BDREF)
           union all
           select FOL.BDREF BDREFFIR,FOL.BDREFPAG BDREFIRFIR,FOL.BDTIPO BDTIPOCALCFIR,FOL.BDRENDTRIBUTAVEL - FOL.BDPENJUD - FOL.BDPENALIM BDBASEIRFIR,FOL.BDINSS BDVALINSSFIR,
             FOL.BDIR BDVALIRFIR,0 BDDESCBASEIRFIR,FOL.BDPREVPRIV BDPREVPRIVFIR,FOL.BDDATAPGTO BDDATAFIR,FOL.BDDATAPROC,FOL.BDHORAPROC
           from SP_VRHF_DADOS_IR_AD(:wEmp, :wCol, :prcompetencia, :prcompetencia) FOL
           join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP         = FOL.BDCODEMP and
                                           RESC.BDCODCOL         = FOL.BDCODCOL and
                                           RESC.BDREFPAGRESCISAO = :prcompetencia and
                                           RESC.BDREFRESCISAO = FOL.BDREF AND
                                           NOT EXISTS(SELECT
                                                          X.BDCODTRANS
                                                      FROM VRH_EMP_TTRANSCOL X
                                                      WHERE
                                                          X.BDCODEMPORIG = FOL.BDCODEMP AND
                                                          X.BDCODCOLORIG = FOL.BDCODCOL AND
                                                          X.BDDATATRF-1  = RESC.BDDATARESCISAO))
           union all
           select FOL.BDREF BDREFFIR,FOL.BDREFPAG BDREFIRFIR,FOL.BDTIPO BDTIPOCALCFIR,FOL.BDRENDTRIBUTAVEL - FOL.BDPENJUD - FOL.BDPENALIM BDBASEIRFIR,FOL.BDINSS BDVALINSSFIR,
             FOL.BDIR BDVALIRFIR,0 BDDESCBASEIRFIR,FOL.BDPREVPRIV BDPREVPRIVFIR,FOL.BDDATAPGTO BDDATAFIR,FOL.BDDATAPROC,FOL.BDHORAPROC
           from SP_VRHF_DADOS_IR_13(:wEmp, :wCol, :prcompetencia, :prcompetencia) FOL
           join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL and RESC.BDREFPAGRESCISAO = :prcompetencia and RESC.BDREFRESCISAO = FOL.BDREF)
           union all
           select FOL.BDREF BDREFFIR,FOL.BDREFPAG BDREFIRFIR,FOL.BDTIPO BDTIPOCALCFIR,FOL.BDRENDTRIBUTAVEL - FOL.BDPENJUD - FOL.BDPENALIM BDBASEIRFIR,FOL.BDINSS BDVALINSSFIR,
             FOL.BDIR BDVALIRFIR,0 BDDESCBASEIRFIR,FOL.BDPREVPRIV BDPREVPRIVFIR,FOL.BDDATAPGTO BDDATAFIR,FOL.BDDATAPROC,FOL.BDHORAPROC
           from SP_VRHF_DADOS_IR_C13(:wEmp, :wCol, :prcompetencia, :prcompetencia) FOL
           join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = FOL.BDCODEMP and RESC.BDCODCOL = FOL.BDCODCOL and RESC.BDREFPAGRESCISAO = :prcompetencia and RESC.BDREFRESCISAO = FOL.BDREF)
       into :BDREFFIR,:BDREFIRFIR,:BDTIPOCALCFIR,:BDBASEIRFIR,:BDVALINSSFIR,:BDVALIRFIR,:BDDESCBASEIRFIR,:BDPREVPRIVFIR,:BDDATAFIR,:BDDATAPROC,:BDHORAPROC
       do
         suspend;
     end

end^

create or alter procedure SP_FICHA_REGISTROS_SALARIOS2 (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(20000),
    PRREF integer,
    PRRETORNAVAZIO integer,
    PRTRAZERSALINI integer,
    PRHISTTRANSF integer,
    PRSALARIOFUNCAO integer,
    PRMOSTRADTALTERACAO integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDDATAADMCOL date,
    BDSALINICOL numeric(18,6),
    BDDATACOL date,
    BDSALBASECOL numeric(18,6),
    BDCODMAS integer,
    BDDESCMAS varchar(50),
    BDCODTFUC integer,
    BDDESCTFUC varchar(40),
    BDCODSHE integer,
    BDDESCSHE varchar(50),
    BDSALBASEANT numeric(18,6),
    BDDATAEFEITO date,
    BDSALREDUZIDO DM_BOOLEAN,
    BDCODEMPORIG integer,
    BDCODCOLORIG integer,
    BDTIPOCOL integer,
    BDTROCATIPO DM_BOOLEAN)
as
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WDATAADMCOL date;
declare variable WSALINICOL numeric(18,6);
declare variable WDATACOL date;
declare variable WSALBASECOL numeric(18,6);
declare variable WCODMAS integer;
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(30000);
declare variable WCONT integer;
declare variable WDESCMAS varchar(50);
declare variable WCODTFUC integer;
declare variable WCODSHE integer;
declare variable WTIPOCOL integer;
declare variable WDESCSHE varchar(50);
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WDATAEFEITO date;
declare variable WWHERE varchar(500);
declare variable WSQL3 varchar(2000);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
declare variable WCODTFUCANT integer;
declare variable WI integer;
declare variable WDESCTFUC varchar(40);
declare variable WREFEFEITO integer;
declare variable WTIPOCOLATU integer;
declare variable WTIPOCOLANT integer;
declare variable WDATAEFEITOCONVCOLETIVA date;
declare variable WSALBASECOLCONVCOLETIVA numeric(18,6);
declare variable WSALARIOMENORULTCONVENCAO integer;
BEGIN
  BDSALBASEANT = 0;

  IF (PRRETORNAVAZIO = 1) THEN
     BEGIN
       EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRREF);
       WSQL = ' select BDCODEMP, BDCODCOL, BDTIPOCOL from VW_VRHF_EMP_TCOL_CALC COL ';

       -- 14269 - Marcelo B. M. - 23/06/2016: Ajustado para aceitar mais de uma empresa e/ou colaborador
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '')) THEN
          BEGIN
             WSQL = WSQL || ' where '||prcodemp;
             IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
                WSQL = WSQL || ' and '||PRCODCOL;
          END
       ELSE
          BEGIN
             IF ((PRCODCOL IS NOT NULL) AND (PRCODCOL <> '')) THEN
                WSQL = WSQL || ' where '||PRCODCOL;
          END

       FOR EXECUTE STATEMENT wsql INTO
         WCODEMP,
         WCODCOL,
         WTIPOCOL
       DO
       BEGIN
         if (PRHISTTRANSF = 1) then
            BEGIN
              WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = ' || WCODEMP || ' and BDCODCOLDEST = ' || WCODCOL;
              FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
                BEGIN
                  IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
                    BEGIN
                  WSQL3 = 'SELECT * FROM SP_FICHA_REGISTROS_SALARIOS2(''COL.BDCODEMP = '||wcodemporig||''', ''COL.BDCODCOL = ' || wcodcolorig || ''',' || PRREF || ',' || PRRETORNAVAZIO || ',' || PRTRAZERSALINI || ',' || PRHISTTRANSF || ',0, 0)';
                  FOR EXECUTE STATEMENT wsql3 INTO
                    :BDCODEMP,
                    :BDCODCOL,
                    :BDNOMCOL,
                    :BDDATAADMCOL,
                    :BDSALINICOL,
                    :BDDATACOL,
                    :BDSALBASECOL,
                    :BDCODMAS,
                    :BDDESCMAS,
                    :BDCODTFUC,
                    :BDDESCTFUC,
                    :BDCODSHE,
                    :BDDESCSHE,
                    :BDSALBASEANT,
                    :BDDATAEFEITO,
                    :BDSALREDUZIDO,
                    :BDCODEMPORIG,
                    :BDCODCOLORIG,
                    :BDTIPOCOL,
                    :BDTROCATIPO DO
                        BEGIN
                      BDCODEMP = WCODEMP;
                      BDCODCOL = WCODCOL;
                      SUSPEND;
                END
            END
                END
            END

         --Sol. 17643 - Bruno L. R. - 01/08/2017
--         IF (WTIPOCOL = 4) THEN
  --          BEGIN

              WSQL2 = 'Select * from (select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, SHE.BDSALSHE bdsalinicol, SHE.BDDATASHE BDDATACOL, SHE.BDSALSHE BDSALBASECOL, SHE.bdcodshe bdcodmas, '||
                      'MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, 0 bdcodshe,  CAST(null as varchar(50)) BDDESCSHE, SHE.BDDATAEFEITOHE, ''FALSE'' BDREDUZIDO,  '||
                      'TCOLFUNC.BDDESCTFUC, SUBSTRING(Coalesce(SHE.BDDATAEFEITOHE,BDDATAADMCOL) from 1 for 4)||SUBSTRING(Coalesce(SHE.BDDATAEFEITOHE,BDDATAADMCOL) FROM 6 for 2) BDREFEFEITO, COLCALC.BDTIPOCOL';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_SHE SHE on (SHE.bdcodemp = COL.bdcodemp and SHE.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = SHE.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VW_VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = SHE.bdcodemp and VINCDIA.bdcodcol = SHE.bdcodcol and VINCDIA.BDDATACOL = SHE.BDDATASHE) ';
              WSQL2 = WSQL2 || ' left outer join VRH_FUNCOES_TFUC TCOLFUNC on (TCOLFUNC.BDCODPLAFUC = VINCDIA.BDCODPLAFUC and TCOLFUNC.BDCODTFUC = VINCDIA.BDCODTFUC) ';
              WSQL2 = WSQL2 || ' left outer join VRHF_EMP_TCOL_CALC COLCALC on (COLCALC.BDCODEMP = COL.BDCODEMP and COLCALC.BDCODCOL = COL.BDCODCOL and COLCALC.BDREFCOL = (SELECT FIRST 1 BDREFCOL FROM VRHF_EMP_TCOL_CALC '||
                                                                                                                                                                            'WHERE BDCODEMP = COL.BDCODEMP AND '||
                                                                                                                                                                            '      BDCODCOL = COL.BDCODCOL AND '||
                                                                                                                                                                            '      BDREFCOL <= substring(Coalesce(SHE.BDDATAEFEITOHE,BDDATAADMCOL) from 1 for 4) || substring(Coalesce(SHE.BDDATAEFEITOHE,BDDATAADMCOL) from 6 for 2) '||
                                                                                                                                                                            'ORDER BY BDREFCOL DESC)) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;

              WSQL2 = WSQL2 || ' union select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, ADM.bdsalinicol, HIST.BDDATAHAUMHE BDDATACOL, '||
                      ' HIST.BDSALBASEHAUMHE,  HIST.bdcodshe bdcodmas, MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, HIST.BDCODSHE, BSHE.BDDESCSHE, HIST.BDDATAEFEITOHAUMHE, ''FALSE'' BDREDUZIDO, '||
                      'TCOLFUNC.BDDESCTFUC, SUBSTRING(Coalesce(HIST.BDDATAEFEITOHAUMHE,BDDATAADMCOL) from 1 for 4)||SUBSTRING(Coalesce(HIST.BDDATAEFEITOHAUMHE,BDDATAADMCOL) FROM 6 for 2) BDREFEFEITO, COLCALC.BDTIPOCOL';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
              WSQL2 = WSQL2 || ' join VRH_EMP_THIST_AUMHE HIST on (HIST.bdcodemp = COL.bdcodemp and HIST.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = hist.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VW_VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TSALHORESP BSHE on (BSHE.bdcodemp = HIST.bdcodemp and BSHE.bdcodshe = HIST.bdcodshe) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = col.bdcodemp and VINCDIA.bdcodcol = col.bdcodcol and VINCDIA.BDDATACOL = HIST.BDDATAHAUMHE) ';
              WSQL2 = WSQL2 || ' left outer join VRH_FUNCOES_TFUC TCOLFUNC on (TCOLFUNC.BDCODPLAFUC = VINCDIA.BDCODPLAFUC and TCOLFUNC.BDCODTFUC = VINCDIA.BDCODTFUC) ';
              WSQL2 = WSQL2 || ' left outer join VRHF_EMP_TCOL_CALC COLCALC on (COLCALC.BDCODEMP = COL.BDCODEMP and COLCALC.BDCODCOL = COL.BDCODCOL and COLCALC.BDREFCOL = (SELECT FIRST 1 BDREFCOL FROM VRHF_EMP_TCOL_CALC '||
                                                                                                                                                                            'WHERE BDCODEMP = COL.BDCODEMP AND '||
                                                                                                                                                                            '      BDCODCOL = COL.BDCODCOL AND '||
                                                                                                                                                                            '      BDREFCOL <= substring(HIST.BDDATAEFEITOHAUMHE from 1 for 4) || substring(HIST.BDDATAEFEITOHAUMHE from 6 for 2) '||
                                                                                                                                                                            'ORDER BY BDREFCOL DESC)) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;
--              WSQL2 = WSQL2 || ' order by 1, 2, 6, 12 '; /*order by bdcodemp, bdcodcol, bdsalbasecol, bddataefeitohaumhe
 ---                                                         Solicitação: 155817 - André Cursino - 22/11/2021 */

              /*
              WCAMPOSSHE = ' HIST.BDSALBASEANTHAUMHE bdsalinicol, HIST.BDDATAHAUMHE BDDATACOL, HIST.BDSALBASEHAUMHE BDSALBASECOL, HIST.bdcodmas, MAUMSAL.BDDESCMAS,'||
                           ' VINCDIA.BDCODTFUC, HIST.BDCODSHE, BSHE.BDDESCSHE ';
              WJOINSHE = ' left outer join VRH_EMP_THIST_AUMHE HIST on (HIST.bdcodemp = COL.bdcodemp and HIST.bdcodcol = COL.bdcodcol) '||
                         ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = HIST.bdcodmas) '||
                         ' left outer join VRH_BASE_TSALHORESP BSHE on (BSHE.bdcodemp = HIST.bdcodemp and BSHE.bdcodshe = HIST.bdcodshe) ';
              WCAMPODATA = 'HIST.BDDATAHAUMHE';      */
              wSQL2 = wSQL2 || ' union all ';
                --158776 Valmor H Junior 01/02/2022
--              wSQL2 = wSQL2 || 'Select * from (';
              WSQL2 =  wSQL2 ||'select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, ADM.bdsalinicol, CALC.BDDATACOL, CALC.BDSALBASECOL, CALC.bdcodmas, '||
                      'MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, 0 bdcodshe, CAST(null as varchar(50)) BDDESCSHE, CALC.BDDATAEFEITO, ''FALSE'' BDREDUZIDO, TCOLFUNC.BDDESCTFUC, '||
                      'SUBSTRING(CALC.BDDATAEFEITO from 1 for 4)||SUBSTRING(CALC.BDDATAEFEITO FROM 6 for 2) BDREFEFEITO, COLCALC.BDTIPOCOL ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
--              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOLCON_CALCDIA CALC on (CALC.bdcodemp = COL.bdcodemp and CALC.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' join VRH_EMP_TCOLCON_CALCDIA CALC on (CALC.bdcodemp = COL.bdcodemp and CALC.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = CALC.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VW_VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
--              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = CALC.bdcodemp and VINCDIA.bdcodcol = CALC.bdcodcol and VINCDIA.BDDATACOL = CALC.BDDATACOL) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.BDCODEMP = COL.BDCODEMP and VINCDIA.BDCODCOL = COL.BDCODCOL and VINCDIA.BDDATACOL = (SELECT FIRST 1 BDDATACOL FROM VRH_EMP_TCOL_VINCDIA '||
                                                                                                                                                                               'WHERE BDCODEMP = COL.BDCODEMP AND '||
                                                                                                                                                                               '      BDCODCOL = COL.BDCODCOL AND '||
                                                                                                                                                                               '      BDDATACOL <= CALC.BDDATAEFEITO '||
                                                                                                                                                                               'ORDER BY BDDATACOL DESC)) ';
              WSQL2 = WSQL2 || ' left outer join VRH_FUNCOES_TFUC TCOLFUNC on (TCOLFUNC.BDCODPLAFUC = VINCDIA.BDCODPLAFUC and TCOLFUNC.BDCODTFUC = VINCDIA.BDCODTFUC) ';
              WSQL2 = WSQL2 || ' left outer join VRHF_EMP_TCOL_CALC COLCALC on (COLCALC.BDCODEMP = COL.BDCODEMP and COLCALC.BDCODCOL = COL.BDCODCOL and COLCALC.BDREFCOL = (SELECT FIRST 1 BDREFCOL FROM VRHF_EMP_TCOL_CALC '||
                                                                                                                                                                            'WHERE BDCODEMP = COL.BDCODEMP AND '||
                                                                                                                                                                            '      BDCODCOL = COL.BDCODCOL AND '||
                                                                                                                                                                            '      BDREFCOL <= substring(CALC.BDDATAEFEITO from 1 for 4) || substring(CALC.BDDATAEFEITO from 6 for 2) '||
                                                                                                                                                                            'ORDER BY BDREFCOL DESC)) ';
              WSQL2 = WSQL2 || ' where COL.bdcodemp = '||wcodemp||' and COL.bdcodcol = '||wcodcol;

              WSQL2 = WSQL2 || ' union select COL.bdcodemp, COL.bdcodcol, COL.bddataadmcol, ADM.bdsalinicol, HIST.BDDATAHAUM BDDATACOL, HIST.BDSALBASEHAUM, '||
                      ' HIST.bdcodmas, MAUMSAL.BDDESCMAS, VINCDIA.BDCODTFUC, 0 bdcodshe, CAST(null as varchar(50)) BDDESCSHE, HIST.BDDATAEFEITOHAUM, ''FALSE'' BDREDUZIDO, TCOLFUNC.BDDESCTFUC, '||
                      ' SUBSTRING(HIST.BDDATAEFEITOHAUM from 1 for 4)||SUBSTRING(HIST.BDDATAEFEITOHAUM FROM 6 for 2) BDREFEFEITO, COLCALC.BDTIPOCOL ';
              WSQL2 = WSQL2 || ' from VRH_EMP_TCOLCON COL ';
--              WSQL2 = WSQL2 || ' left outer join VRH_EMP_THIST_AUM HIST on (HIST.bdcodemp = COL.bdcodemp and HIST.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' join VRH_EMP_THIST_AUM HIST on (HIST.bdcodemp = COL.bdcodemp and HIST.bdcodcol = COL.bdcodcol) ';
              WSQL2 = WSQL2 || ' left outer join VRH_BASE_TMOTAUMSAL MAUMSAL on (MAUMSAL.bdcodmas = hist.bdcodmas) ';
              WSQL2 = WSQL2 || ' left outer join VW_VRH_EMP_TCOL_ADM ADM ON (ADM.bdcodemp = COL.bdcodemp AND ADM.bdcodcol = COL.bdcodcol) ';
            /*WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = COL.bdcodemp and VINCDIA.bdcodcol = COL.bdcodcol and VINCDIA.BDDATACOL = HIST.BDDATAHAUM) ';
     Sol.144936 LuizCovre 19/11/2021*/
--              WSQL2 = WSQL2 || ' join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.bdcodemp = COL.bdcodemp and VINCDIA.bdcodcol = COL.bdcodcol and VINCDIA.BDDATACOL = HIST.BDDATAHAUM) ';
              WSQL2 = WSQL2 || ' left outer join VRH_EMP_TCOL_VINCDIA VINCDIA on (VINCDIA.BDCODEMP = COL.BDCODEMP and VINCDIA.BDCODCOL = COL.BDCODCOL and VINCDIA.BDDATACOL = (SELECT FIRST 1 BDDATACOL FROM VRH_EMP_TCOL_VINCDIA '||
                                                                                                                                                                               'WHERE BDCODEMP = COL.BDCODEMP AND '||
                                                                                                                                                                               '      BDCODCOL = COL.BDCODCOL AND '||
                                                                                                                                                                               '      BDDATACOL <= HIST.BDDATAEFEITOHAUM '||
                                                                                                                                                                               'ORDER BY BDDATACOL DESC)) ';
              WSQL2 = WSQL2 || ' left outer join VRH_FUNCOES_TFUC TCOLFUNC on (TCOLFUNC.BDCODPLAFUC = VINCDIA.BDCODPLAFUC and TCOLFUNC.BDCODTFUC = VINCDIA.BDCODTFUC) ';
              WSQL2 = WSQL2 || ' left outer join VRHF_EMP_TCOL_CALC COLCALC on (COLCALC.BDCODEMP = COL.BDCODEMP and COLCALC.BDCODCOL = COL.BDCODCOL and COLCALC.BDREFCOL = (SELECT FIRST 1 BDREFCOL FROM VRHF_EMP_TCOL_CALC '||
                                                                                                                                                                            'WHERE BDCODEMP = COL.BDCODEMP AND '||
                                                                                                                                                                            '      BDCODCOL = COL.BDCODCOL AND '||
                                                                                                                                                                            '      BDREFCOL <= substring(HIST.BDDATAEFEITOHAUM from 1 for 4) || substring(HIST.BDDATAEFEITOHAUM from 6 for 2) '||
                                                                                                                                                                            'ORDER BY BDREFCOL DESC)) ';

              WSQL2 = WSQL2 || ' where COL.bdcodemp = ' || WCODEMP || ' and COL.bdcodcol = ' || WCODCOL;

                  --WSQL2 = WSQL2 || ') a order by bdcodemp,bdcodcol,bdsalbasecol,bdcodmas desc';
              if (PRMOSTRADTALTERACAO = 0) then
                begin
                  if (prsalariofuncao = 0) then
                      WSQL2 = WSQL2 || ') a order by BDCODEMP, BDCODCOL, BDDATAEFEITOHE, BDSALBASECOL desc, BDDATACOL';
                  else
                      WSQL2 = WSQL2 || ') a order by BDCODEMP, BDCODCOL, BDSALBASECOL desc, BDDATACOL';
                end
              else
                  WSQL2 = WSQL2 || ') a order by BDCODEMP, BDCODCOL, BDDATAEFEITOHE, BDSALBASECOL, BDDATACOL';
--            END
         --Sol. 17643 - Bruno L. R. - 01/08/2017

           wempatu = 0;
           wcolatu = 0;

           WCONT = 0;

           /* 183829 - Isabella 31/07/2023 - se existe convenção coletiva;  não apresenta salário igual ou menor*/
           WSALBASECOLCONVCOLETIVA = 0;
           WSALARIOMENORULTCONVENCAO = 0;
           WDATAEFEITOCONVCOLETIVA = NULL; 

           FOR EXECUTE STATEMENT WSQL2 INTO
             WCODEMP,
             WCODCOL,
             WDATAADMCOL,
             WSALINICOL,
             WDATACOL,
             WSALBASECOL,
             WCODMAS,
             WDESCMAS,
             WCODTFUC,
             WCODSHE,
             WDESCSHE,
             WDATAEFEITO,
             :BDSALREDUZIDO,
             WDESCTFUC,
             WREFEFEITO,
             WTIPOCOLATU
           DO
           BEGIN
             if (WTIPOCOLATU is null) then
               WTIPOCOLATU = -1;
             else if (WTIPOCOLANT = -1) then
               begin
                 WTIPOCOLANT = WTIPOCOLATU;
               end

             if (BDCODCOL<>WCODCOL) then
                WTIPOCOLANT = WTIPOCOLATU;
             /* 183829 - Isabella 31/07/2023 - se existe convenção coletiva;  não apresenta salário igual ou menor; considerando a data efeito da convencao */
             IF (WCODMAS = 2) then
                BEGIN
                   IF (((WDATAEFEITOCONVCOLETIVA IS NULL) or  (WDATAEFEITO > WDATAEFEITOCONVCOLETIVA)) AND (WSALBASECOL > WSALBASECOLCONVCOLETIVA))  THEN
                      BEGIN
                         WDATAEFEITOCONVCOLETIVA = WDATAEFEITO;
                         WSALBASECOLCONVCOLETIVA = WSALBASECOL;
                      END
                END
             IF (WSALBASECOLCONVCOLETIVA >= WSALBASECOL)  THEN
                BEGIN
                   WSALARIOMENORULTCONVENCAO = 1;
                END

             IF (wcont = 0) THEN
                BEGIN
                   BDCODEMP = WCODEMP;
                   BDCODCOL = WCODCOL;
                   BDDATAADMCOL = WDATAADMCOL;
                   IF (WSALINICOL IS NULL) THEN
                      BDSALINICOL = 0;
                   ELSE
                      BDSALINICOL = WSALINICOL;
                   BDDATACOL = WDATACOL;
                   BDSALBASEANT = 0;--NULL;   --Sol. 17798 - Bruno L. R. - 05/04/2017
                   BDSALBASECOL = WSALBASECOL;
                   BDDATAEFEITO = WDATAEFEITO;
                   BDTIPOCOL = WTIPOCOLATU;
                   BDTROCATIPO=FALSE;

                   IF ((WDATACOL = WDATAADMCOL) OR (((BDSALBASEANT IS NULL) or (BDSALBASEANT = 0)) and ((WCODMAS IS NULL) or (WCODMAS = 0)))) THEN   --Sol. 18509 - Bruno L. R. - 26/07/2017
                      BEGIN
                        BDCODMAS = 0;
                        BDDESCMAS = 'Admissão';

                        --IF ((BDSALINICOL <= BDSALBASECOL) OR (BDSALBASECOL IS NULL)) THEN
                          -- BDSALBASECOL = BDSALINICOL;

                       -- IF (BDSALBASECOL IS NOT NULL) THEN
                         --  BDSALINICOL = BDSALBASECOL;
                      END
                   ELSE
                     BEGIN
                       BDCODMAS = WCODMAS;
                       BDDESCMAS = WDESCMAS;
                     END

                   IF (BDDATACOL IS NULL) THEN
                      BDDATACOL = BDDATAADMCOL;

                   IF (BDDATAEFEITO IS NULL) THEN
                      BDDATAEFEITO = BDDATACOL;

                   IF (BDSALBASEANT = BDSALINICOL) THEN
                      BEGIN
                        BDCODMAS = 0;
                        BDDESCMAS = 'Admissão';
                        BDDATACOL = WDATAADMCOL;
                      END

                   BDCODSHE = WCODSHE;
                   BDDESCSHE = WDESCSHE;

                   BDCODTFUC = WCODTFUC;
                   BDDESCTFUC = WDESCTFUC;
                   --IF ((PRTRAZERSALINI = 1) AND ((BDSALBASECOL = BDSALINICOL) AND (WTIPOCOL = 4))) THEN
                   --IF ((PRTRAZERSALINI = 1) AND ((BDSALBASECOL <> BDSALINICOL) OR (BDSALBASECOL IS NULL))) THEN
                   IF ((PRTRAZERSALINI = 1) AND (BDSALINICOL <> 0)) THEN
                      begin
                        if ((wempatu <> wcodemp) or (wcolatu <> wcodcol)) then
                           begin
                             wwhere = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||
                                      ' and BDREFCOL <= '||prref||
                                      ' order by BDREFCOL DESC';
                             execute statement wwhere into :BDNOMCOL;
           
                             wempatu = wcodemp;
                             wcolatu = wcolatu;
                           end

                        bdcodemporig = bdcodemp;
                        bdcodcolorig = bdcodcol;

                        SUSPEND;
                      end
                END
             ELSE
                BEGIN
                --  IF ((BDCODEMP <> WCODEMP) OR (BDCODCOL <> WCODCOL) OR (BDSALBASECOL <> WSALBASECOL) OR (BDCODMAS <> WCODMAS)) THEN   --Sol. 18509 - Bruno L. R. - 03/07/2017
                 -- BEGIN
                        BDCODEMP = WCODEMP;
                        BDCODCOL = WCODCOL;
                        BDDATAADMCOL = WDATAADMCOL;
                        IF (WSALINICOL IS NULL) THEN
                           BDSALINICOL = 0;
                        ELSE
                           BDSALINICOL = WSALINICOL;
                        BDDATACOL = WDATACOL;

                        if (BDSALBASEANT IS NULL) then
                           BDSALBASEANT = 0;

                        if ((WTIPOCOLATU <> WTIPOCOLANT) and (WTIPOCOLATU<>-1)) then
                           bdtrocatipo = true;
                        else
                           bdtrocatipo = False;

                        if (((BDSALBASECOL > BDSALBASEANT) OR (BDSALBASEANT IS NULL) or (WTIPOCOLATU <> WTIPOCOLANT)) and (BDSALBASECOL IS NOT NULL)) then
                           BDSALBASEANT = BDSALBASECOL;     --Sol. 17798 - Bruno L. R. - 04/04/2017
                        BDSALBASECOL = WSALBASECOL;
                        BDDATAEFEITO = WDATAEFEITO;
                        wi=0;

                         begin --158776 Valmor H Junior 01/02/2022
                               --183829 Isabella 31/07/2023 - se existe convenção coletiva; não apresenta salário igual ou menor 
                          if ((bdsalbaseant>=bdsalbasecol) and (WSALARIOMENORULTCONVENCAO = 1)) then
                              wi=1;
                         end

                       IF ((WDATACOL = WDATAADMCOL) OR ((BDSALBASEANT IS NULL) or (BDSALBASEANT = 0))) THEN    --Sol. 18509 - Bruno L. R. - 10/07/2017
                          BEGIN
                            BDCODMAS = 0;
                            BDDESCMAS = 'Admissão';

                         --   IF ((BDSALINICOL <= BDSALBASECOL) OR (BDSALBASECOL IS NULL)) THEN
                           --    BDSALBASECOL = BDSALINICOL;
                          END
                       ELSE
                         BEGIN
                           BDCODMAS = WCODMAS;
                           BDDESCMAS = WDESCMAS;
                         END

                        WCODTFUCANT = BDCODTFUC;
                        BDCODTFUC = WCODTFUC;
                        BDDESCTFUC = WDESCTFUC;
                        BDCODSHE = WCODSHE;
                        BDDESCSHE = WDESCSHE;

                        WTIPOCOLANT = BDTIPOCOL;
                        BDTIPOCOL = WTIPOCOLATU;

                        IF (BDDATACOL IS NULL) THEN
                           BDDATACOL = BDDATAADMCOL;

                        IF (BDDATAEFEITO IS NULL) THEN
                           BDDATAEFEITO = BDDATACOL;

                      --IF (BDSALBASEANT = BDSALINICOL) THEN
                        IF (BDDATACOL = WDATAADMCOL) THEN -- Sol.150948 acontece do Colab ter mudança de cargo sem alteração salárial.
                           BEGIN
                             BDCODMAS = 0;
                             BDDESCMAS = 'Admissão';
                       --      BDDATACOL = WDATAADMCOL;
                           END

                        /*Não estava retornando quando alterava apenas a função, tive que validar se é outra função - #144930 - Paulo Nunes - 21/12/2020*/
                       -- IF ((BDSALBASEANT <> BDSALBASECOL) OR (WCODTFUCANT IS NULL))  THEN
                      --     BEGIN
                         --    BDCODMAS = WCODMAS;
                         --    BDDESCMAS = WDESCMAS;
                        --   END

                       --IF ((PRTRAZERSALINI = 1) AND (((BDSALBASECOL <> BDSALINICOL) AND ((BDSALBASECOL <> BDSALBASEANT) OR (BDSALBASEANT IS NULL))) OR
                       --   ((WTIPOCOL = 4) AND (BDSALBASECOL <> BDSALBASEANT)))) THEN -
                       --IF ((PRTRAZERSALINI = 1) AND ((((BDSALBASECOL >= BDSALBASEANT) OR (BDSALBASEANT IS NULL))) OR -- Sol. 30767 - Paulo Nunes - 26/07/2019 - Retirado a verificação se o salario atual é diferente do inicial
                       --   ((WTIPOCOL = 4) AND (BDSALBASECOL <> BDSALBASEANT)))) THEN
                       --IF ((PRTRAZERSALINI = 1) AND (((BDSALBASECOL <> BDSALINICOL) AND (BDDATAADMCOL <> BDDATACOL) AND ((BDSALBASECOL > BDSALBASEANT) OR (BDSALBASEANT IS NULL))) OR -- Sol. 127578 - Jarde - 05/11/2019 - Estava duplicando a informação se o colaborador tivesse apenas o dado diário da admissão.
                       --   ((WTIPOCOL = 4) AND (BDSALBASECOL <> BDSALBASEANT)))) THEN
                       --IF ((PRTRAZERSALINI = 1) AND (((BDSALBASECOL <> BDSALINICOL) AND (BDDATAADMCOL <> BDDATACOL) AND ((BDSALBASECOL <> BDSALBASEANT) OR (BDSALBASEANT IS NULL) OR (WCODTFUCANT <> WCODTFUC))) OR -- Sol. 136718 - Peterson - 28/05/2020 - Nao estava demonstrando valores reduzidos no processo de alteração salarial.
                       --   ((WTIPOCOL = 4) AND (BDSALBASECOL <> BDSALBASEANT)))) THEN

                       --168404 Isabella 20/07/2023 - apresentar reduções de salários na Ficha de registro auxiliar 
                       --183829 Isabella 31/07/2023 - se existe convenção coletiva; não apresenta salário igual ou menor 
                       IF ((PRTRAZERSALINI = 1) AND ((((BDSALBASECOL >= BDSALINICOL) AND (BDDATAADMCOL <> BDDATACOL) AND ((BDSALBASECOL >= BDSALBASEANT) OR (BDSALBASEANT IS NULL) OR (WCODTFUCANT <> WCODTFUC))) OR -- Sol.: 152121 - André Cursino - 10/11/2021 - Alterado verificação de salários anteriores e atuais, pois quando há somente alteração de função não sai no relatório.
                                                        ((WTIPOCOL = 4) AND (BDSALBASECOL >= BDSALBASEANT)) OR (WTIPOCOLANT <> WTIPOCOLATU))
                                                    OR (WSALARIOMENORULTCONVENCAO = 0) )) THEN
                          begin
                            if ((wempatu <> wcodemp) or (wcolatu <> wcodcol)) then
                               begin
                                 wwhere = 'select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||
                                          ' and BDREFCOL <= '||prref||
                                          ' order by BDREFCOL DESC';
                                 execute statement wwhere into :BDNOMCOL;
               
                                 wempatu = wcodemp;
                                 wcolatu = wcolatu;
                               end

                            bdcodemporig = bdcodemp;
                            bdcodcolorig = bdcodcol;
       
                            /*if ((BDSALBASECOL <> BDSALBASEANT) and (BDDATAEFEITO = WDATAEFEITO)) then Adicionado verificação para não levar registros duplicados.
                                                                                   Solicitação: 155817 - André Cursino - 22/11/2021*/
                            --183829 Isabella 17/08/2023 - se existe convenção coletiva; não apresenta salário igual ou menor
                            if (((BDSALBASECOL > BDSALBASEANT) and (BDDATAEFEITO = WDATAEFEITO)) or
                               ((WCODTFUCANT <> WCODTFUC) and (prSalarioFuncao = 1)) or    /*Sol.: 162323 - André Cursino - Adicionado parametro para verificar se deseja levar alterações de cargo*/
                               (WTIPOCOLANT <> WTIPOCOLATU) or
                               ((WSALARIOMENORULTCONVENCAO = 0) and (NOT ((BDSALBASECOL = BDSALBASEANT) and (BDDATAEFEITO = WDATAEFEITO))))) then          /*Sol.: 168404 21/07/23 - Isabella - Adicionado parametro para Ficha registro auxiliar apresentar redução salário*/
                               SUSPEND;
                          end
                        ELSE
     --SUSPEND; --Sol.150948 LuizCovre, quando tem mais de um registro. (Comentei esse SUSPEND. Sol.156194).
                   --  END
                     if (wi<>1) then
                   SUSPEND;
                END
    
             WCONT = 1;
           END
       END
     END
   ELSE
       if (wi<>1) then
     SUSPEND;
end^

create or alter procedure SP_VRHF_CONS_AUMSAL (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRCODACCONV integer = 0,
    PRCODMAS integer = 0,
    PRDETALHE integer = 2)
returns (
    BDDETALHE smallint,
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDDATAHAUM date,
    BDCODMAS integer,
    BDDESCMAS varchar(50),
    BDDATAEFEITOHAUM date,
    BDSALBASEHAUM numeric(18,6),
    BDSALBASEANTHAUM numeric(18,6),
    BDCODACCONV integer,
    BDDTEFACCONV date,
    BDCONVCOLETIVA DM_BOOLEAN,
    BDDSCACCONV varchar(255),
    BDDESCTPACCONV varchar(100),
    BDCODHAUM integer)
as
declare variable WSQL varchar(10000);
declare variable WWHERE varchar(10000);
declare variable WCODMAS integer;
declare variable WDESCMAS varchar(50);
declare variable WDATAHAUM date;
declare variable WEMPANTERIOR integer;
declare variable WCOLABANTERIOR integer;
declare variable WREFHAUM integer;
declare variable WCODTPACCONV integer;
declare variable WCODMASANT integer;
declare variable WCODEMP varchar(9);
begin
  /* Procedure Text */

  /*
      BDDETALHE
      0 = Registros principais
      1 = Registros secundários
  */

  wsql = 'SELECT HIST.BDCODEMP, HIST.BDCODCOL, HIST.BDDATAHAUM, HIST.BDCODMAS, HIST.BDDATAEFEITOHAUM, HIST.BDSALBASEHAUM, HIST.BDSALBASEANTHAUM, HIST.BDCODACCONV, HIST.BDCONVCOLETIVA, HIST.BDCODHAUM ';
  wsql = wsql||'FROM VRH_EMP_THIST_AUM HIST ';

  if ((position(',' in :prcodemp) > 0) or (position('OR' in upper(:prcodemp)) > 0) or (prcodemp is null))   then
     wsql = wsql||' join VW_EMPRESAS_USU usu on hist.bdcodemp = usu.bdcodemp ';
  else
     begin
       if ((prcodemp is null) or (prcodemp = '')) then
        begin
          wsql = wsql||' join (SELECT BDCODEMP from SP_EMPRESAS_USU) USU on USU.BDCODEMP = HIST.BDCODEMP ';
        end
       else
        begin
          wcodemp = trim(substring(:prcodemp from position('=' in :prcodemp) + 1));
          wsql = wsql||' join (SELECT FIRST 1 BDCODEMP from SP_EMPRESAS_USU('||wcodemp||') )USU on USU.BDCODEMP = HIST.BDCODEMP ';
        end

     end

  wwhere = '';
  IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
    begin
      prcodemp = replace(upper(prcodemp),'HIST.BDCODEMP','BDCODEMP');
      prcodemp = replace(upper(prcodemp),'BDCODEMP','HIST.BDCODEMP');

        wwhere = 'where '|| prcodemp;

        IF (prcodcol IS NOT NULL AND prcodcol <> '') THEN
            begin
                wwhere = wwhere||' and '|| prcodcol;

                if (prdetalhe = 1 and PRCODACCONV <> 0) then
                    begin
                        wwhere = wwhere||' and HIST.BDCODACCONV = '|| PRCODACCONV;

                        if (prcodmas <> 0) then
                            wwhere = wwhere||' and HIST.BDCODMAS = '|| prcodmas;
                    end
            end
    end

  wsql = wsql||wwhere;
  wsql = wsql||'ORDER BY HIST.BDCODEMP, HIST.BDCODCOL, HIST.BDDATAHAUM, HIST.BDCODACCONV, HIST.BDCODMAS, HIST.BDSALBASEANTHAUM ';

  BDCODMAS = 0;
  wdatahaum = NULL;
  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDDATAHAUM,
--    :BDCODMAS,
    WCODMAS,
--    :BDDESCMAS,
    :BDDATAEFEITOHAUM,
    :BDSALBASEHAUM,
    :BDSALBASEANTHAUM,
    :BDCODACCONV,
    :BDCONVCOLETIVA,
    :BDCODHAUM
  DO
  BEGIN
    BDDTEFACCONV = null;
    BDDSCACCONV = null;
    BDDESCMAS = null;
    wdescmas = null;
    wrefhaum = 0;
    BDNOMCOL = null;
    BDDESCTPACCONV = null;
    WCODMASANT = BDCODMAS;
    BDCODMAS = WCODMAS;

--  SOLICITAÇÃO #184326 - LEONARDO MATHEUS
    if (((wcolabanterior <> BDCODCOL) or (wempanterior <> BDCODEMP)) or ((wempanterior is null) or (wcolabanterior is null)))  then
        BEGIN
          WDATAHAUM = NULL;
          WCODMAS   = NULL;
          wcolabanterior = BDCODCOL;
          wempanterior   = BDCODEMP;
        end


    wrefhaum = CAST((SUBSTRING(BDDATAHAUM from 1 for 4)||SUBSTRING(BDDATAHAUM from 6 for 2)) AS INTEGER);
    SELECT FIRST 1 BDNOMCOL FROM VRH_EMP_TCOLCON_CAD
    WHERE BDCODEMP = :BDCODEMP AND BDCODCOL = :BDCODCOL AND BDREFCOL <= :wrefhaum
    ORDER BY BDCODEMP,BDCODCOL,BDREFCOL DESC
    INTO :BDNOMCOL;

    if ((BDNOMCOL IS NULL) OR (BDNOMCOL = ''))then
        SELECT FIRST 1 BDNOMCOL FROM VRH_EMP_TCOLCON_CAD
        WHERE BDCODEMP = :BDCODEMP AND BDCODCOL = :BDCODCOL
        ORDER BY BDCODEMP,BDCODCOL,BDREFCOL DESC
        INTO :BDNOMCOL;

    if (BDCODMAS <> 0) then
        begin
            SELECT BDDESCMAS FROM VRH_BASE_TMOTAUMSAL WHERE BDCODMAS = :BDCODMAS INTO :wdescmas;
            BDDESCMAS = wdescmas;
        end

    if (COALESCE(BDCODACCONV,0) = 0) then
        begin
            if (PRDETALHE <> 1) then
                begin
                    BDDETALHE = 0;
                    SUSPEND;
                end
        end
    else
        begin
            IF (((WDATAHAUM <> BDDATAHAUM) or (WDATAHAUM IS NULL) or (WCODMAS <> WCODMASANT)) and (PRDETALHE <> 1)) THEN
                begin
                    SELECT AC.BDDTEFACCONV, AC.BDDSC, TPAC.BDDESCTPACCONV FROM VRH_EMP_TACCONV AC
                    LEFT JOIN VRH_BASE_TTPACCONV TPAC ON (AC.BDCODTPACCONV = TPAC.BDCODTPACCONV)
                    WHERE AC.BDCODEMP = :BDCODEMP AND AC.BDCODACCONV = :BDCODACCONV
                    INTO :BDDATAEFEITOHAUM,:BDDSCACCONV,BDDESCTPACCONV ;

                    SELECT MAX(BDSALBASEHAUM) FROM VRH_EMP_THIST_AUM WHERE BDCODEMP = :BDCODEMP AND BDCODCOL = :BDCODCOL AND BDDATAHAUM = :BDDATAHAUM AND BDCODACCONV = :BDCODACCONV INTO :BDSALBASEHAUM;
                    BDDETALHE = 0;
                    wdatahaum = BDDATAHAUM;
                    SUSPEND;
                end
            ELSE IF ((PRDETALHE <> 0) AND ((PRCODACCONV = BDCODACCONV) and (bdcodmas = prcodmas))) THEN
                begin
                    BDDETALHE = 1;
                    SUSPEND;
                end
        end
  END
end^

create or alter procedure SP_VRHF_GETPLANLANC (
    PRCODEMP integer,
    PRCODCOL integer,
    PRDATAINI date,
    PRDATAFIM date)
returns (
    BDCODVER integer,
    BDDATALANC date,
    BDREFLANC numeric(18,2),
    BDVALLANC numeric(18,2),
    BDREFCONGLANC DM_BOOLEAN,
    BDVALCONGLANC DM_BOOLEAN,
    BDORIGEMLANC integer,
    BDCOMPLANC integer,
    BDCODTIPO integer,
    BDZERAR DM_BOOLEAN)
as
declare variable WREFINI integer;
declare variable WREFFIM integer;
begin
  wrefini = cast((substring(cast(:prdataini as varchar(10)) from 1 for 4)||substring(cast(:prdataini as varchar(10)) from 6 for 2)) as integer);
  wreffim = cast((substring(cast(:prdatafim as varchar(10)) from 1 for 4)||substring(cast(:prdatafim as varchar(10)) from 6 for 2)) as integer);

  for select BDCODVER,BDDATALANC,BDREFLANC,BDVALLANC,BDREFCONGLANC,BDVALCONGLANC,BDORIGEMLANC,BDCOMPLANC,BDCODTIPO,BDZERAR
      from VRHF_EMP_TPLANLANC
      where BDCOMPLANC between :wrefini and :wreffim and BDCODEMP = :prCodEmp and BDCODCOL = :prCodCol
      union all
      select X.BDCODVER,I.BDDATAINISERVTI,X.BDREFERENCIA,X.BDVALOR,X.BDIGNFORREF,X.BDIGNFORVAL,0,
             SUBSTRING(CAST(I.BDDATAINISERVTI AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(I.BDDATAINISERVTI AS VARCHAR(10)) FROM 6 FOR 2),
             0, 'FALSE'
      from VRH_BASE_TPLA_TCONTRATO X
      join VRH_EMP_TINTERMITENTE I on (I.BDCODEMP = X.BDCODEMP and I.BDCODCOL = X.BDCODCOL and I.BDCODCONTTI = X.BDCODCONTTI)
      where I.BDDATAINISERVTI <= :prdatafim and I.BDDATAFIMSERVTI >= :prdataini and
             X.BDCODEMP = :prCodEmp and X.BDCODCOL = :prCodCol
  into :BDCODVER,:BDDATALANC,:BDREFLANC,:BDVALLANC,:BDREFCONGLANC,:BDVALCONGLANC,:BDORIGEMLANC,:BDCOMPLANC,:BDCODTIPO,:BDZERAR
  do
    suspend;
end^

/* Restore proc. body: SP_VRH_EMP_TCOLCON_CAD */
CREATE OR ALTER procedure SP_VRH_EMP_TCOLCON_CAD (
    PRWHERE varchar(10000))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDTPCOL varchar(20),
    BDREFCOL integer,
    BDCONTRCOL integer,
    BDNOMCOL varchar(70),
    BDNOMCOLUPPER varchar(70),
    BDCODPAISRES integer,
    BDCEPCOL varchar(9),
    BDLOGRCOL DM_LOGRADOURO,
    BDENDCOL DM_BDENDERECO,
    BDNUMCOL DM_NUMEND,
    BDCOMPLCOL DM_BDCOMPENDERECO,
    BDBAICOL DM_BDBAIRRO,
    BDCODCID integer,
    BDDDDCOL integer,
    BDFONECOL DM_BDTELEFONE,
    BDDDDCELCOL integer,
    BDCELCOL DM_BDTELEFONE,
    BDEMAILCOL DM_BDEMAIL,
    BDEMAIL2COL varchar(100),
    BDGRAUINSTCOL integer,
    BDESTCIVCOL integer,
    BDSEXOCOL integer,
    BDDATACHEBRASILCOL date,
    BDCASADOBR DM_BOOLEAN,
    BDFILHOSBR DM_BOOLEAN,
    BDCODCLE integer,
    BDTEMPORESIDENCIA integer,
    BDCONDICAOINGRESSO integer,
    BDCPFCOL varchar(14))
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(1000);
BEGIN
  wwhere = '';
         wsql = 'select first 99 BASE.BDCODEMP, BASE.BDCODCOL, BASE.BDDTPCOL, BASE.BDREFCOL, CAD.BDCONTRCOL, ';
  wsql = wsql|| 'case when (FIS.BDNMSOCIAL <> '''' and PAR.BDUSANOMESOCIAL = ''TRUE'') then FIS.BDNMSOCIAL ';
  wsql = wsql|| 'else CAD.BDNOMCOL end BDNOMCOL, ';
  wsql = wsql|| 'case when (FIS.BDNMSOCIAL <> '''' and PAR.BDUSANOMESOCIAL = ''TRUE'') then upper(FIS.BDNMSOCIAL) ';
  wsql = wsql|| 'else CAD.BDNOMCOLUPPER end BDNOMCOLUPPER, ';
  wsql = wsql|| 'CAD.BDCODPAISRES, CAD.BDCEPCOL, CAD.BDLOGRCOL, CAD.BDENDCOL, CAD.BDNUMCOL, CAD.BDCOMPLCOL, CAD.BDBAICOL, ';
  wsql = wsql|| 'CAD.BDCODCID, CAD.BDDDDCOL, CAD.BDFONECOL, CAD.BDDDDCELCOL, CAD.BDCELCOL, CAD.BDEMAILCOL, BASE.BDEMAIL2COL, ';
  wsql = wsql|| 'CAD.BDGRAUINSTCOL, CAD.BDESTCIVCOL, CAD.BDSEXOCOL, CAD.BDDATACHEBRASILCOL, CAD.BDCASADOBR, CAD.BDFILHOSBR, ';
  wsql = wsql|| 'CAD.BDCODCLE, CAD.BDTEMPORESIDENCIA, CAD.BDCONDICAOINGRESSO, BASE.BDCPFCOL ';
  wsql = wsql|| 'from (select X.BDCODEMP, X.BDCODCOL, X.BDDTPCOL, X.BDEMAIL2COL, X.BDCPFCOL, ';
  wsql = wsql|| 'coalesce((select max(D1.BDREFCOL) from VRH_EMP_TCOLCON_CAD D1 ';
  wsql = wsql|| 'where D1.BDCODEMP = X.BDCODEMP and D1.BDCODCOL = X.BDCODCOL and ';
  wsql = wsql|| 'cast(D1.BDREFCOL as varchar(6)) <= (select trim(rdb$get_context(''USER_SESSION'', ''W_ANOMES'')) from RDB$DATABASE)), ';
  wsql = wsql|| '(select min(D1.BDREFCOL) from VRH_EMP_TCOLCON_CAD D1 ';
  wsql = wsql|| 'where D1.BDCODEMP = X.BDCODEMP and D1.BDCODCOL = X.BDCODCOL)) as BDREFCOL ';
  wsql = wsql|| 'from VRH_EMP_TCOLCON X) as BASE ';
  wsql = wsql|| 'join VRH_EMP_TCOLCON_CAD CAD on (CAD.BDCODEMP = BASE.BDCODEMP and CAD.BDCODCOL = BASE.BDCODCOL and CAD.BDREFCOL = BASE.BDREFCOL) ';
  wsql = wsql|| 'left join VRH_EMP_TCOLCON_FIS FIS on (FIS.BDCODEMP = BASE.BDCODEMP and FIS.BDCODCOL = BASE.BDCODCOL and FIS.BDREFCOL = ';
  wsql = wsql|| '(select max(BDREFCOL) from VRH_EMP_TCOLCON_FIS ';
  wsql = wsql|| 'where BDCODEMP = CAD.BDCODEMP and BDCODCOL = CAD.BDCODCOL and BDREFCOL <= BASE.BDREFCOL)) ';
  wsql = wsql|| 'left join VRHF_BASE_TEMPPAR PAR on (CAD.BDCODEMP = PAR.BDCODEMP and PAR.BDREFEMP = ';
  wsql = wsql|| '(select max(BDREFEMP) from VRHF_BASE_TEMPPAR ';
  wsql = wsql|| 'where BDCODEMP = PAR.BDCODEMP and BDREFEMP <= BASE.BDREFCOL)) ';
  wwhere = upper(prwhere);
  wwhere = upper(replace(prwhere,'''''',''''));
  wwhere = replace(wwhere,'BDCODEMP','BASE.BDCODEMP');
  wwhere = replace(wwhere,'BDCONTRCOL','CAD.BDCONTRCOL');
  wwhere = replace(wwhere,'BDCODCOL','BASE.BDCODCOL');
  wwhere = replace(wwhere,'BDNOMCOL','CAD.BDNOMCOL');
  wsql = wsql|| wwhere;
  FOR EXECUTE STATEMENT wsql
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDDTPCOL,
    :BDREFCOL,
    :BDCONTRCOL,
    :BDNOMCOL,
    :BDNOMCOLUPPER,
    :BDCODPAISRES,
    :BDCEPCOL,
    :BDLOGRCOL,
    :BDENDCOL,
    :BDNUMCOL,
    :BDCOMPLCOL,
    :BDBAICOL,
    :BDCODCID,
    :BDDDDCOL,
    :BDFONECOL,
    :BDDDDCELCOL,
    :BDCELCOL,
    :BDEMAILCOL,
    :BDEMAIL2COL,
    :BDGRAUINSTCOL,
    :BDESTCIVCOL,
    :BDSEXOCOL,
    :BDDATACHEBRASILCOL,
    :BDCASADOBR,
    :BDFILHOSBR,
    :BDCODCLE,
    :BDTEMPORESIDENCIA,
    :BDCONDICAOINGRESSO,
    :BDCPFCOL
  DO
  SUSPEND;
END^

/*163200 - André Cursino - 19/07/2022 - implementacao da SP*/
/*163206 - André Crusino - 18/07/2022 - Alteração da SP para acomodar novo modelo de relatório*/
create or alter procedure SP_VRHF_MOVIMENTACAO_COL (
    PRREFINI integer,
    PRREFFIM integer,
    PRCODEMP varchar(2000),
    PRLISTACOLS integer = 0,
    PRORDEM integer = 0,
    PRCODCOL varchar(1000) = '',
    PRCODCLASSE integer = 0,
    PRCODFUNCAO integer = 0,
    PRCODSINDICATO integer = 0,
    PRCODTPCC integer = 0,
    PRLISTAESTAGIARIARIOS integer = 1,
    PRSOMATERC integer = 0)              /*173775 - André Cursino - 31/01/2023*/
returns (
    BDCODEMP integer,
    BDNOMEMP varchar(100),
    BDCODMOV integer,
    BDDESC varchar(100),
    BDQTDADE integer,
    BDREF integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDNOMCTA varchar(100),
    BDCTALON varchar(20),                  /*sol 170786 - André Cursino - 07/11/2022 - Alterado tipo do retorno, devido a erro de conversão*/
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDDESCTFUC varchar(40),
    BDSIGLAUF varchar(2))
as
declare variable WANOINI integer;
declare variable WMESINI integer;
declare variable WREFATU integer;
declare variable WLISTAREFS varchar(1000);
declare variable WANOATU integer;
declare variable WMESATU integer;
declare variable WULTDIAMES integer;
declare variable WDATAULTDIAMES varchar(10);
declare variable WDATAPRIDIAMES varchar(10);
declare variable WSQL varchar(9000);
declare variable WWHERECODEMP varchar(1000);
declare variable WWHERECODCOL varchar(1000);
declare variable WWHERECLASSE varchar(200);
declare variable WWHERESINDICATO varchar(100);
declare variable WWHEREFUNCAO varchar(100);
declare variable WWHERECODTPCC varchar(100);
declare variable WWHEREFINAL varchar(100);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREFAUX integer;
declare variable WCODTPCC integer;
declare variable WCODMOV integer;                 /*sol 170786 - André Cursino - 07/11/2022*/
declare variable WSUBSELECTQTDADETERC varchar(500);
BEGIN
  /* Procedure Text */
  wAnoIni = CAST(SUBSTRING(CAST(prrefini AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wMesIni = CAST(SUBSTRING(CAST(prrefini AS VARCHAR(6)) FROM 5) AS INTEGER);
  wRefAtu = 0;
  wAnoAtu = 0;
  wMesAtu = 0;
  wUltDiaMes = 0;
  wDataUltDiaMes = '';
  wDataPriDiaMes = '';
  wListaRefs = '';
  wSql = '';
  wWhereCodEmp = '';
  wWhereCodCol = '';
  wWhereClasse = '';
  wWhereSindicato = '';
  wWhereFuncao = '';
  wWhereCodTPCC = '';
  wWhereFinal = '';
  wCodEmp = 0;
  wCodCol = 0;
  wRefAux = 0;
  wCodTpcc = 0;
  wCodMov = 0;                /*sol 170786 - André Cursino - 07/11/2022*/
  wSubSelectQtdadeTerc = '';  /*173775 - André Cursino - 31/01/2023*/

  IF ((PRCODEMP <> '') AND (PRCODEMP IS NOT NULL)) THEN
    BEGIN
      wWhereCodEmp = UPPER(PRCODEMP);
      wWhereCodEmp = REPLACE(wWhereCodEmp, 'BDCODEMP', 'COL.BDCODEMP');
      wWhereCodEmp = wWhereCodEmp || ' AND ';
    END

  if ((prCodCol <> '') and (prCodCol is not null) and (prListaCols <> 0) ) then
    begin
      wWhereCodCol = upper(prCodCol);
      wWhereCodCol = replace(wWhereCodCol, 'BDCODCOL', 'COL.BDCODCOL');
      wWhereCodCol = wWhereCodCol || ' AND ';
    end

  if (prsomaterc = 1) then                                          /*173775 - André Cursino - 31/01/2023*/
    wWhereClasse = ' NOT CLASSE.BDGRUPOCLA IN (3,12) ';             /*173775 - André Cursino - 31/01/2023*/
  else
  --por padrão não considerar os grupos autonomos, empregadores e socios
  wWhereClasse = ' NOT CLASSE.BDGRUPOCLA IN (2,3,12) ';

  if (prListaEstagiariarios <> 1) then
    wWhereClasse = ' NOT CLASSE.BDGRUPOCLA IN (2,3,5,12) ';

  if (prCodClasse <> 0) then
    begin
      wWhereClasse = ' (CLASSE.BDCODCLA = ' || cast(prCodClasse as varchar(5));
      if (prListaEstagiariarios = 1) then
        wWhereClasse = wWhereClasse || ' OR CLASSE.BDCODCLA IN(SELECT BDCODCLA FROM VRH_BASE_TCLASSE CLASSE WHERE CLASSE.BDGRUPOCLA = 5)) ';
      else
        wWhereClasse = wWhereClasse || ')';
    end

  if ((prCodFuncao <> 0) and (prListaCols <> 0)) then
    wWhereFuncao = ' FUNCAO.BDCODTFUC = ' || cast(prCodFuncao as varchar(5));

  if (prCodSindicato <> 0) then
    wWhereSindicato = ' SINDICATO.BDCODSINTRAB = ' || cast(prCodSindicato as varchar(5));

  if ((prCodTPCC <> 0) and (prCodTPCC is not null)) then
    wWhereCodTPCC = ' AND CC.BDCODTPCC = ' || cast(prCodTpcc as varchar(10));

  if ((wWhereFuncao <> '') or (wWhereSindicato <> '')) then
    begin
      if (wWhereFuncao <> '') then
        wWhereFinal = wWhereFuncao;

      if ((wWhereFinal <> '') and (wWhereSindicato <> '')) then
        wWhereFinal = wWhereFinal || ' AND ';

      if (wWhereSindicato <> '') then
        wWhereFinal = wWhereFinal || wWhereSindicato;

      wWhereFinal = ' WHERE ' || wWhereFinal || ' ';
    end

  --desmembra o período em competências e adiciona na wListaRefs
  WHILE (wRefAtu < prRefFim) DO
    BEGIN
      wrefatu = CAST(CAST(wAnoIni AS VARCHAR(4)) || IIF(wMesIni > 9, CAST(wMesIni AS VARCHAR(2)), '0' || CAST(wMesIni AS VARCHAR(2))) AS INTEGER);

      IF (wListaRefs = '') THEN
        wListaRefs = CAST(wRefAtu AS VARCHAR(6));
      ELSE
        wListaRefs = wListaRefs || ';' || CAST(wRefAtu AS VARCHAR(6));

      IF (wMesIni = 12) THEN
        BEGIN
          wMesIni = 1;
          wAnoIni = wAnoIni + 1;
        END
      ELSE
        wMesIni = wMesIni + 1;
    END

  wRefAtu = 0;
  WHILE (wRefAtu <= prRefFim)DO
    BEGIN
      IF (wRefAtu = 0) THEN
        wRefAtu = prRefIni;

      EXECUTE PROCEDURE sp_seta_competencia(wRefAtu);
      wAnoAtu = CAST(SUBSTRING(CAST(wRefAtu AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
      wMesAtu = CAST(SUBSTRING(CAST(wRefAtu AS VARCHAR(6)) FROM 5) AS INTEGER);
      wSql =  'select ULTDIA from ULTIMO_DIA_MES(' || wMesAtu || ',' || wAnoAtu ||')';
      EXECUTE STATEMENT wSql INTO :wUltDiaMes;
      wDataUltDiaMes = wUltDiaMes || '.' || wMesAtu || '.' || wAnoAtu;
      wDataPriDiaMes = '01.' || wMesAtu || '.' || wAnoAtu;

      wSql = 'SELECT distinct MOVIMENTOS.* , EMP.BDNOMEMP, TPCC.BDNOMCTA, TPCC.BDCTALON ';

      /*173775 - André Cursino - 31/01/2023*/
      wSubSelectQtdadeTerc = ' + Coalesce((select count(serv.bdcodter) ' ||
                                            'from VRH_BASE_TSERVTERC serv ' ||
                                           'where serv.bdcodemp = COL.BDCODEMP ' ||
                                             'and serv.bdcodtpcc = CC.BDCODTPCC ' ||
                                             'and serv.bdcodcentro = CC.BDCODCENTRO ' ||
                                             'and (serv.bddataserv between ''' || wDataPriDiaMes || ''' and ''' || wDataUltDiaMes || ''') ' ||
                                             'group by serv.BDCODEMP, serv.BDCODTPCC, serv.BDCODCENTRO), 0)';

      if (prListaCols <> 0) then
        begin
          --wSql = wSql || ',CAD.BDNOMCOL, FUNCAO.BDDESCTFUC, UF.BDSIGLAUF ';                             /*sol 170786 - André Cursino - 07/11/2022*/
          wSql = wSql || ',CAD.BDNOMCOL, FUNCAO.BDDESCTFUC, COALESCE(UF.BDSIGLAUF, UFEMP.BDSIGLAUF) ';    /*sol 170786 - André Cursino - 07/11/2022 - deve trazer o UF da empresa quando não houve no centro de custos*/
        end

      wSql = wSql || ' FROM (';
      wSql = wSql || 'SELECT * FROM ( ';

      if (prListaCols = 0) then
        begin
          --nº de cols até a competência
          wSql = wSql || 'SELECT COL.BDCODEMP, ' ||
                       '''Nº EMPREGADOS'' BDDESC, ' ||
                       'COUNT(COL.BDCODCOL) ' || iif(prsomaterc = 0, '', wSubSelectQtdadeTerc) || ' BDQTDADE, '||   /*173775 - André Cursino - 31/01/2023*/
                     --'COUNT(COL.BDCODCOL) BDQTDADE, ' ||                                                          /*173775 - André Cursino - 31/01/2023*/
                       wRefAtu || ' AS BDCOMPETENCIA, ' ||
                       'CC.BDCODTPCC, ' ||
                       'CC.BDCODCENTRO, ' ||
                       '90 BDCODMOV ' ||
                  'FROM VRH_EMP_TCOLCON COL ' ||
                  'JOIN VW_VRH_EMP_TCOLCON_VINC VINC ON (COL.BDCODEMP = VINC.BDCODEMP ' ||
                                                        'AND COL.BDCODCOL = VINC.BDCODCOL) ' ||
                  'JOIN VRH_BASE_TCLASSE CLASSE ON (VINC.BDCODCLA = CLASSE.BDCODCLA) ' ||
             'LEFT JOIN VRH_EMP_TRESCISAO RESC ON (COL.BDCODEMP = RESC.BDCODEMP ' ||
                                                  'AND COL.BDCODCOL = RESC.BDCODCOL) ' ||
             'LEFT JOIN SP_VRH_CC_DATA(COL.BDCODEMP, COL.BDCODCOL, ''' || wDataUltDiaMes || ''') CC ON (COL.BDCODEMP = CC.BDCODEMP ' ||
                                                                                       'AND COL.BDCODCOL = CC.BDCODCOL) ' ||
                 'WHERE ' || wWhereCodEmp || wWhereCodCol || wWhereClasse || wWhereCodTPCC ||
                  ' AND ((RESC.BDDATARESCISAO IS NULL) OR (NOT RESC.BDDATARESCISAO < ''' || wDataPriDiaMes || ''')) ' ||
                 'GROUP BY COL.BDCODEMP, CC.BDCODTPCC, CC.BDCODCENTRO ' ||
                 'ORDER BY COL.BDCODEMP, CC.BDCODTPCC) TRABALAHNDO ';
    
          wSql = wSql || ' UNION ALL ';
          wSql = wSql || ' SELECT * FROM ( ';
        end

      --trabalhando
      wSql = wSql || 'SELECT COL.BDCODEMP, ' ||
                   '''TRABALHANDO'' BDDESC, ';
                     --iif(prListaCols = 0, 'COUNT(COL.BDCODCOL)', '0') || ' BDQTDADE, ' ||          /*173775 - André Cursino - 31/01/2023*/
      if (prListaCols = 0) then                                                                      /*173775 - André Cursino - 31/01/2023*/
          wSql = wSql || 'COUNT(COL.BDCODCOL) ' || iif(prsomaterc = 0, '', wSubSelectQtdadeTerc);    /*173775 - André Cursino - 31/01/2023*/
      else                                                                                           /*173775 - André Cursino - 31/01/2023*/
        wSql = wSql || '0';                                                                          /*173775 - André Cursino - 31/01/2023*/
      wSql = wSql || ' BDQTDADE, ' ||                                                                /*173775 - André Cursino - 31/01/2023*/
                   wRefAtu || ' AS BDCOMPETENCIA, ' ||
                   'CC.BDCODTPCC, ' ||
                   'CC.BDCODCENTRO, ' ||
                   '91 BDCODMOV ' ||
                   iif(prlistacols = 0, '', ', COL.BDCODCOL ') ||
              'FROM SP_SOMENTE_ATIVOS(''' || wDataPriDiaMes || ''' , ''' || wDataUltDiaMes || ''') COL ' ||
              'JOIN VW_VRH_EMP_TCOLCON_VINC VINC ON (COL.BDCODEMP = VINC.BDCODEMP ' ||
                                                    'AND COL.BDCODCOL = VINC.BDCODCOL) ' ||
              'JOIN VRH_BASE_TCLASSE CLASSE ON (VINC.BDCODCLA = CLASSE.BDCODCLA) ' ||
          iif(prListaCols = 0, '', 'LEFT JOIN VRH_EMP_TRESCISAO RESC ON (COL.BDCODEMP = RESC.BDCODEMP AND COL.BDCODCOL = RESC.BDCODCOL) ') ||
         'LEFT JOIN SP_VRH_CC_DATA(COL.BDCODEMP, COL.BDCODCOL, ''' || wDataUltDiaMes || ''') CC ON (COL.BDCODEMP = CC.BDCODEMP ' ||
                                                                                   'AND COL.BDCODCOL = CC.BDCODCOL) ' ||
             'WHERE ' || wWhereCodEmp || wWhereCodCol || wWhereClasse || wWhereCodTPCC ||
             iif(prListaCols = 0, '', ' AND ((RESC.BDDATARESCISAO IS NULL) OR (RESC.BDDATARESCISAO > ''' || wDataPriDiaMes || ''')) ') ||
             iif(prListaCols = 0, 'GROUP BY COL.BDCODEMP, CC.BDCODTPCC, CC.BDCODCENTRO  ', ' ') ||
             'ORDER BY COL.BDCODEMP, ' ||
             iif(prListaCols = 0, '', 'COL.BDCODCOL, ') ||
                      'CC.BDCODTPCC) TRABALAHNDO ';

      wSql = wSql || ' UNION ALL ';
      wSql = wSql || ' SELECT * FROM ( ';

      --if (prListaCols = 0) then  /*sol 170786 - André Cursino - 07/11/2022 - informação de demitidos também para o relatório de movimentação*/
        --begin
          --demitidos
          wSql = wSql || 'SELECT COL.BDCODEMP, ' ||
                       '''DEMITIDOS'' BDDESC, ' ||
                       iif(prListaCols = 0, 'COUNT(COL.BDCODCOL)', '0') || ' BDQTDADE, ' ||
                       wRefAtu || ' AS BDCOMPETENCIA, ' ||
                       'CC.BDCODTPCC, ' ||
                       'CC.BDCODCENTRO, ' ||
                       '92 BDCODMOV ' ||
                       iif(prlistacols = 0, '', ', COL.BDCODCOL ') ||
                  'FROM VRH_EMP_TCOLCON COL ' ||
                  'JOIN VW_VRH_EMP_TCOLCON_VINC VINC ON (COL.BDCODEMP = VINC.BDCODEMP ' ||
                                                        'AND COL.BDCODCOL = VINC.BDCODCOL) ' ||
                  'JOIN VRH_BASE_TCLASSE CLASSE ON (VINC.BDCODCLA = CLASSE.BDCODCLA) ' ||
             'LEFT JOIN VRH_EMP_TRESCISAO RESC ON (COL.BDCODEMP = RESC.BDCODEMP ' ||
                                                  'AND COL.BDCODCOL = RESC.BDCODCOL) ' ||
             'LEFT JOIN SP_VRH_CC_DATA(COL.BDCODEMP, COL.BDCODCOL, ''' || wDataUltDiaMes || ''') CC ON (COL.BDCODEMP = CC.BDCODEMP ' ||
                                                                                       'AND COL.BDCODCOL = CC.BDCODCOL) ' ||
                 'WHERE ' || wWhereCodEmp || wWhereCodCol || wWhereClasse || wWhereCodTPCC ||
                  ' AND RESC.BDDATARESCISAO IS NOT NULL ' ||
                  ' AND RESC.BDDATARESCISAO BETWEEN ''' || wDataPriDiaMes || ''' AND ''' || wDataUltDiaMes || ''' ' ||
                 iif(prListaCols = 0, 'GROUP BY COL.BDCODEMP, CC.BDCODTPCC, CC.BDCODCENTRO  ', ' ') ||
                 'ORDER BY COL.BDCODEMP, ' ||
                          iif(prListaCols = 0, '', 'COL.BDCODCOL, ') ||
                          'CC.BDCODTPCC) DEMITIDOS ';
    
          wSql = wSql || ' UNION ALL ';
          wSql = wSql || ' SELECT * FROM ( ';
        --end
      --admitidos
      wSql = wSql || 'SELECT COL.BDCODEMP, ' ||
                   '''ADMITIDOS'' BDDESC, ' ||
                   iif(prListaCols = 0, 'COUNT(COL.BDCODCOL)', '0') || ' BDQTDADE, ' ||
                   wRefAtu || ' AS BDCOMPETENCIA, ' ||
                   'CC.BDCODTPCC, ' ||
                   'CC.BDCODCENTRO, ' ||
                   '93 BDCODMOV ' ||
                   iif(prlistacols = 0, '', ', COL.BDCODCOL ') ||
              'FROM VRH_EMP_TCOLCON COL ' ||
              'JOIN VW_VRH_EMP_TCOLCON_VINC VINC ON (COL.BDCODEMP = VINC.BDCODEMP ' ||
                                                    'AND COL.BDCODCOL = VINC.BDCODCOL) ' ||
              'JOIN VRH_BASE_TCLASSE CLASSE ON (VINC.BDCODCLA = CLASSE.BDCODCLA) ' ||
         'LEFT JOIN SP_VRH_CC_DATA(COL.BDCODEMP, COL.BDCODCOL, ''' || wDataUltDiaMes || ''') CC ON (COL.BDCODEMP = CC.BDCODEMP ' ||
                                                                                   'AND COL.BDCODCOL = CC.BDCODCOL) ' ||
             'WHERE ' || wWhereCodEmp || wWhereCodCol || wWhereClasse || wWhereCodTPCC ||
              ' AND COL.BDDATAADMCOL BETWEEN ''' || wDataPriDiaMes || ''' AND ''' || wDataUltDiaMes || ''' ' ||
             iif(prListaCols = 0,'GROUP BY COL.BDCODEMP, CC.BDCODTPCC, CC.BDCODCENTRO  ', ' ') ||
             'ORDER BY COL.BDCODEMP, ' ||
                      iif(prListaCols = 0, '', 'COL.BDCODCOL, ') ||
                      'CC.BDCODTPCC) ADMITIDOS ';

      wSql = wSql || ' UNION ALL ';
      wSql = wSql || ' SELECT * FROM ( ';

      --situacao
       wSql = wSql || 'SELECT COL.BDCODEMP, ' ||
                   iif(prListaCols = 0, '''DOENÇA''', 'PREP.BDDESCSIT') || ' BDDESC, ' ||
                   iif(prListaCols = 0, 'COUNT(COL.BDCODCOL)', '0') || ' BDQTDADE, ' ||
                   wRefAtu || ' AS BDCOMPETENCIA, ' ||
                   'CC.BDCODTPCC, ' ||
                   'CC.BDCODCENTRO, ' ||
                   '94 BDCODMOV ' ||
                   iif(prlistacols = 0, '', ', COL.BDCODCOL ') ||
              'FROM VRH_EMP_TCOLCON COL ' ||
              'JOIN VW_VRH_EMP_TCOLCON_VINC VINC ON (COL.BDCODEMP = VINC.BDCODEMP ' ||
                                                    'AND COL.BDCODCOL = VINC.BDCODCOL) ' ||
              'JOIN VRH_BASE_TCLASSE CLASSE ON (VINC.BDCODCLA = CLASSE.BDCODCLA) ' ||
              'JOIN VRH_EMP_TSITCOL SIT ON (COL.BDCODEMP = SIT.BDCODEMP ' ||
                                           'AND COL.BDCODCOL = SIT.BDCODCOL) ' ||
              iif(prListaCols = 0, '', 'JOIN VRH_BASE_TPREPSIT PREP ON (SIT.BDCODSIT = PREP.BDCODSIT) ') ||
              iif(prListaCols = 0, '', 'LEFT JOIN VRH_EMP_TRESCISAO RESC ON (COL.BDCODEMP = RESC.BDCODEMP AND COL.BDCODCOL = RESC.BDCODCOL) ') ||
         'LEFT JOIN SP_VRH_CC_DATA(COL.BDCODEMP, COL.BDCODCOL, ''' || wDataUltDiaMes || ''') CC ON (COL.BDCODEMP = CC.BDCODEMP ' ||
                                                                                   'AND COL.BDCODCOL = CC.BDCODCOL) ' ||
         'LEFT JOIN VRH_EMP_TFERIAS FER ON (COL.BDCODEMP = FER.BDCODEMP AND ' ||                            /*171454 - André Cursino - 09/12/2022*/
                                           'COL.BDCODCOL = FER.BDCODCOL AND ' ||                            /*171454 - André Cursino - 09/12/2022*/
                                           'FER.BDREFINIFE = ' || wRefAtu ||')  ' ||                        /*171454 - André Cursino - 09/12/2022*/
             'WHERE ' || wWhereCodEmp || wWhereCodCol || wWhereClasse || wWhereCodTPCC ||
              iif(prListaCols = 0, '', ' AND ((RESC.BDDATARESCISAO IS NULL) OR (RESC.BDDATARESCISAO > ''' || wDataUltDiaMes || ''')) ') ||
              ' AND SIT.BDDATAINISIT IS NOT NULL ' ||
              --' AND ((SIT.BDDATAINISIT BETWEEN ''' || wDataPriDiaMes || ''' AND ''' || wDataUltDiaMes || ''') OR (SIT.BDDATAFIMSIT IS NULL) OR (SIT.BDDATAFIMSIT >= ''' || wDataPriDiaMes || ''')) ' ||       /*sol 170786 - André Cursino - 07/11/2022 - ajuste no filtro das situações, estava trazendo qualquer registro que tenha data fim maior que a ultima data da competência*/
              ' AND (((SIT.BDDATAINISIT BETWEEN ''' || wDataPriDiaMes || ''' AND ''' || wDataUltDiaMes || ''') OR (SIT.BDDATAINISIT <= ''' || wDataPriDiaMes || ''')) AND ' ||                                  /*sol 170786 - André Cursino - 07/11/2022*/
              '      ((SIT.BDDATAFIMSIT IS NULL) OR (SIT.BDDATAFIMSIT >= ''' || wDataPriDiaMes || '''))) ' ||                                                                                                   /*sol 170786 - André Cursino - 07/11/2022*/
              ' AND (SIT.BDDATAINISIT > coalesce(FER.BDINIPERGOZOFE, ''31.12.1899'')) ' ||                         /*171454 - André Cursino - 09/12/2022*/
             iif(prListaCols = 0, 'GROUP BY COL.BDCODEMP, CC.BDCODTPCC, CC.BDCODCENTRO  ', ' ') ||
             'ORDER BY COL.BDCODEMP, ' ||
                      iif(prlistacols = 0, '', 'COL.BDCODCOL, ') ||
                      'CC.BDCODTPCC) SITUACAO ';

      wSql = wSql || ' UNION ALL ';
      wSql = wSql || ' SELECT * FROM ( ';

      --ferias
      wSql = wSql || 'SELECT COL.BDCODEMP, ' ||
                   '''FÉRIAS'' BDDESC, ' ||
                   iif(prListaCols = 0, 'COUNT(COL.BDCODCOL)', '0') || ' BDQTDADE, ' ||
                   wRefAtu || ' AS BDCOMPETENCIA, ' ||
                   'CC.BDCODTPCC, ' ||
                   'CC.BDCODCENTRO, ' ||
                   '95 BDCODMOV ' ||
                   iif(prlistacols = 0, '', ', COL.BDCODCOL ') ||
              'FROM VRH_EMP_TCOLCON COL ' ||
              'JOIN VW_VRH_EMP_TCOLCON_VINC VINC ON (COL.BDCODEMP = VINC.BDCODEMP ' ||
                                                    'AND COL.BDCODCOL = VINC.BDCODCOL) ' ||
              'JOIN VRH_BASE_TCLASSE CLASSE ON (VINC.BDCODCLA = CLASSE.BDCODCLA) ' ||
              'JOIN VRH_EMP_TFERIAS FERIAS ON (COL.BDCODEMP = FERIAS.BDCODEMP ' ||
                                         'AND COL.BDCODCOL = FERIAS.BDCODCOL)' ||
         iif(prListaCols = 0, '', 'LEFT JOIN VRH_EMP_TRESCISAO RESC ON (COL.BDCODEMP = RESC.BDCODEMP AND COL.BDCODCOL = RESC.BDCODCOL) ') ||
         'LEFT JOIN SP_VRH_CC_DATA(COL.BDCODEMP, COL.BDCODCOL, ''' || wDataUltDiaMes || ''') CC ON (COL.BDCODEMP = CC.BDCODEMP ' ||
                                                                                   'AND COL.BDCODCOL = CC.BDCODCOL) ' ||
         'LEFT JOIN VRH_EMP_TSITCOL SIT ON (COL.BDCODEMP = SIT.BDCODEMP AND ' ||                                                                                                                          /*171454 - André Cursino - 09/12/2022*/
                                           'COL.BDCODCOL = SIT.BDCODCOL AND ' ||                                                                                                                          /*171454 - André Cursino - 09/12/2022*/
                                           'SIT.BDDATAINISIT IS NOT NULL AND ' ||                                                                                                                         /*171454 - André Cursino - 09/12/2022*/
                                           '(((SIT.BDDATAINISIT BETWEEN ''' || wDataPriDiaMes || ''' AND ''' || wDataUltDiaMes || ''') OR (SIT.BDDATAINISIT <= ''' || wDataPriDiaMes || ''')) AND ' ||    /*171454 - André Cursino - 09/12/2022*/
                                           '((SIT.BDDATAFIMSIT IS NULL) OR (SIT.BDDATAFIMSIT >= ''' || wDataPriDiaMes || ''')))) ' ||                                                                     /*171454 - André Cursino - 09/12/2022*/
             'WHERE ' || wWhereCodEmp || wWhereCodCol || wWhereClasse || wWhereCodTPCC ||
              ' AND FERIAS.BDINIPERGOZOFE IS NOT NULL ' ||
              ' AND FERIAS.BDINIPERGOZOFE BETWEEN ''' || wDataPriDiaMes || ''' AND ''' || wDataUltDiaMes || ''' ' ||
              ' AND FERIAS.BDINIPERGOZOFE > coalesce(SIT.BDDATAINISIT, ''31.12.1899'') ' ||                                 /*171454 - André Cursino - 09/12/2022*/
              iif(prListaCols = 0, '', ' AND ((RESC.BDDATARESCISAO IS NULL) OR (RESC.BDDATARESCISAO > ''' || wDataUltDiaMes || ''')) ') ||
             iif(prlistacols = 0, 'GROUP BY COL.BDCODEMP, CC.BDCODTPCC, CC.BDCODCENTRO  ', ' ') ||
             'ORDER BY COL.BDCODEMP, ' ||
                      iif(prlistacols = 0, '', 'COL.BDCODCOL, ') ||
                      'CC.BDCODTPCC) FERIAS ';

      wSql = wSql || ' ) MOVIMENTOS ';

      wSql = wsql || 'JOIN VW_TEMPRESAS_REF EMP ON (EMP.BDCODEMP = MOVIMENTOS.BDCODEMP) ' ||
      'LEFT JOIN TCIDADE CIDEMP ON (CIDEMP.BDCODCID = EMP.BDCODCID) ' ||                       /*sol 170786 - André Cursino - 07/11/2022 - JOIN PARA PEGAR O UF DA EMPRESA*/
      'LEFT JOIN TUF UFEMP ON (CIDEMP.BDCODUF = UFEMP.BDCODUF) ' ||                            /*sol 170786 - André Cursino - 07/11/2022*/
      'LEFT JOIN CENTROS_TPCC TPCC ON (TPCC.BDCODCENTRO = MOVIMENTOS.BDCODCENTRO ' ||
                                      'AND TPCC.BDCODTPCC = MOVIMENTOS.BDCODTPCC) ' ||
      'LEFT JOIN VW_VRH_BASE_TCUSTOM_END ENDCC ON (TPCC.BDCODCENTRO = ENDCC.BDCODCENTRO ' ||
                                                  'AND TPCC.BDCODTPCC = ENDCC.BDCODTPCC) ' ||
      'LEFT JOIN TCIDADE CID ON (CID.BDCODCID = ENDCC.BDCODCID) ' ||
      'LEFT JOIN TUF UF ON (CID.BDCODUF = UF.BDCODUF) ';

      if (prListaCols <> 0) then
        begin
          wSql = wSql || 'LEFT JOIN VW_VRH_EMP_TCOLCON_CAD CAD ON (MOVIMENTOS.BDCODCOL = CAD.BDCODCOL ' ||
                                                                  'AND MOVIMENTOS.BDCODEMP = CAD.BDCODEMP) ' ||
         'LEFT JOIN VW_VRH_EMP_TCOL_VINCDIA VINCDIA ON (MOVIMENTOS.BDCODCOL = VINCDIA.BDCODCOL ' ||
                                                        'AND MOVIMENTOS.BDCODEMP = VINCDIA.BDCODEMP) ' ||
         'LEFT JOIN VRH_FUNCOES_TFUC FUNCAO ON (VINCDIA.BDCODPLAFUC = FUNCAO.BDCODPLAFUC ' ||
                                               'AND VINCDIA.BDCODTFUC = FUNCAO.BDCODTFUC) ' ||
         'LEFT JOIN VW_VRH_EMP_TCOL_VINC SINDICATO ON (SINDICATO.BDCODEMP = MOVIMENTOS.BDCODEMP ' ||
                                                      'AND SINDICATO.BDCODCOL = MOVIMENTOS.BDCODCOL) ';
          wSql = wSql || wWhereFinal;
        end

      wSql = wSql || ' ORDER BY BDCODEMP, BDCOMPETENCIA, ';

      if (prlistacols <> 0) then
        begin
          if (prOrdem = 0) then
            wSql = wSql || 'BDCODCOL,';
          else if (prOrdem = 1) then
            wSql = wSql || 'BDNOMCOL, BDCODCOL,';
        end

      wSql = wSql || 'BDCODTPCC, BDCODMOV';

      if (prListaCols <> 0) then
        wSql = wSql || ' desc ';

      if (prListaCols = 0) then
        begin
          for execute statement wsql into :BDCODEMP, :BDDESC, :BDQTDADE, :BDREF, :BDCODTPCC, :BDCODCENTRO, :BDCODMOV, :BDNOMEMP, :BDNOMCTA, :BDCTALON  do
            SUSPEND;
        end
      else
        begin
          for execute statement wsql into :BDCODEMP, :BDDESC, :BDQTDADE, :BDREF, :BDCODTPCC, :BDCODCENTRO, :BDCODMOV,  :BDCODCOL, :BDNOMEMP, :BDNOMCTA, :BDCTALON, :BDNOMCOL, :BDDESCTFUC, :BDSIGLAUF  do
            begin
              --if (BDCODMOV = 91) then       /*171454 - André Cursino - 09/12/2022*/
              if (BDCODMOV in (91, 93)) then  /*171454 - André Cursino - 09/12/2022*/
                begin
                  if ((wCodCol <> bdCodcol) or
                     ((wCodCol = bdCodcol) and ((wCodEmp <> BDCODEMP) or (wCodTPcc <> BDCODTPCC) or (wRefAux <> BDREF))))                                /*sol 170786 - André Cursino - 07/11/2022*/
                  then
                    SUSPEND;
                end
              else
                SUSPEND;

              wCodEmp = BDCODEMP;
              wCodCol = BDCODCOL;
              wCodTPcc = BDCODTPCC;
              wRefAux = BDREF;
              wCodMov = bdCodMov;
            end
        end

      IF (POSITION(';' IN wListaRefs) > 0) THEN
        BEGIN
          wListaRefs = REPLACE(wListaRefs, CAST(wRefAtu AS VARCHAR(6)) || ';', '');
          wRefAtu = CAST(SUBSTRING(wListaRefs FROM 1 FOR 6) AS INTEGER);
        END
      ELSE
        BREAK;
    END
END^

CREATE OR ALTER procedure SP_VRHF_EMP_TVERBAFN_DET (
    WWHERE varchar(500))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(70),
    BDDATAINI date,
    BDDATAFIM date,
    BDDETALHE varchar(70) collate WIN_PTBR)
as
declare variable WCASTFN varchar(500);
declare variable WSQL varchar(30000);
declare variable WSQL2 varchar(30000);
BEGIN
  wsql =  'select V.BDCODEMP, V.BDCODCOL, COLCAD.BDNOMCOL, V.BDDETALHEFND BDDETALHE ';
  wsql = wsql || 'from VRHF_EMP_TVERBAFN_DET V ';
  wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = V.BDCODEMP and COLCAD.BDCODCOL = V.BDCODCOL) ';
  wsql = wsql || 'where V.BDTIPODETFND = 3 and substring(V.BDDETALHEFND from 1 for 17) = ''Per. aquisitivo: ''';
  if (wwhere <> '') then
    begin
      wsql2 = ' and ' || SUBSTRING(wwhere FROM 7 FOR 1000);
      wsql = wsql || wsql2;
    end

  wsql = wsql || 'union ';
  wsql = wsql || 'select V.BDCODEMP, V.BDCODCOL, COLCAD.BDNOMCOL, V.BDDETALHEFTD BDDETALHE ';
  wsql = wsql || 'from VRHF_EMP_TVERBAFT_DET V ';
  wsql = wsql || 'left outer join VW_VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = V.BDCODEMP and COLCAD.BDCODCOL = V.BDCODCOL) ';
  wsql = wsql || 'where V.BDTIPODETFTD = 3 and substring(V.BDDETALHEFTD from 1 for 17) = ''Per. aquisitivo: ''';
  if (wwhere <> '') then
    begin
      wsql2 = ' and ' || SUBSTRING(wwhere FROM 7 FOR 1000);
      wsql = wsql || wsql2;
    end

  FOR EXECUTE STATEMENT wSQL INTO :bdcodemp, :bdcodcol, :bdnomcol, :bddetalhe do
  BEGIN
    wcastfn = substring(:bddetalhe from 29 for 4);
    if (wcastfn = 'até ') then
      begin
        :bddataini = CAST((SUBSTRING(:bddetalhe FROM 21 FOR 2)||'/'||SUBSTRING(:bddetalhe FROM 18 FOR 2)||'/'||SUBSTRING(:bddetalhe FROM 24 FOR 4)) AS DATE);
        :bddatafim = CAST((SUBSTRING(:bddetalhe FROM 36 FOR 2)||'/'||SUBSTRING(:bddetalhe FROM 33 FOR 2)||'/'||SUBSTRING(:bddetalhe FROM 39 FOR 4)) AS DATE);
      end
    else
      begin
        :bddataini = CAST((SUBSTRING(:bddetalhe FROM 21 FOR 2)||'/'||SUBSTRING(:bddetalhe FROM 18 FOR 2)||'/'||SUBSTRING(:bddetalhe FROM 24 FOR 4)) AS DATE);
        :bddatafim = CAST((SUBSTRING(:bddetalhe FROM 37 FOR 2)||'/'||SUBSTRING(:bddetalhe FROM 34 FOR 2)||'/'||SUBSTRING(:bddetalhe FROM 40 FOR 4)) AS DATE);
      end
    suspend;
  END

END^

CREATE OR ALTER procedure SP_TOMADOR_COM_ENDERECO
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDORDEM integer,
    BDREFENTRADA integer,
    BDDATAENTRADA date,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDSIGLAUF varchar(2),
    BDDESCUF varchar(40))
as
declare variable WSQL varchar(10000);
BEGIN
--SP criada para ser usada na tabela 01 do gerador de relatórios.
--wsql = 'select COL.BDCODEMP, COL.BDCODCOL, PREP.BDCODCENTRO, PREP.BDCODTPCC, CUST.BDCODCID, CID.BDNOMCID, UF.BDSIGLAUF, UF.BDDESCUF ' ||
--       'from VRH_EMP_TCOLCON COL ' ||
--       'left join VRHF_EMP_TPREPFN PREP on (PREP.BDCODEMP = COL.BDCODEMP and PREP.BDCODCOL = COL.BDCODCOL) ' ||
--       'left join VW_VRH_BASE_TCUSTOM_END CUST on (CUST.BDCODCENTRO = PREP.BDCODCENTRO and CUST.BDCODTPCC = PREP.BDCODTPCC) ' ||
--       'left outer join TCIDADE CID on (CUST.BDCODCID = CID.BDCODCID) ' ||
--       'left outer join TUF UF on (UF.BDCODUF = CID.BDCODUF) ';
  wsql = 'select COL.BDCODEMP, COL.BDCODCOL, max(PREP.BDORDEM) as BDORDEM, PREP.BDREFENTRADA, PREP.BDDATAENTRADA, ' ||
         'PREP.BDCODCENTRO, PREP.BDCODTPCC, CUST.BDCODCID, CID.BDNOMCID, UF.BDSIGLAUF, UF.BDDESCUF ' ||
         'from VRH_EMP_TCOLCON COL ' ||
         'left join(select X.BDCODEMP, X.BDCODCOL, max(X.BDORDEM) as BDORDEM ' ||
         'from VRHF_EMP_TPREPFN X ' ||
         'group by X.BDCODEMP, X.BDCODCOL) PREPX on (PREPX.BDCODEMP = COL.BDCODEMP and ' ||
         'PREPX.BDCODCOL = COL.BDCODCOL) ' ||
         'left join VRHF_EMP_TPREPFN PREP on (PREP.BDCODEMP = PREPX.BDCODEMP and ' ||
         'PREP.BDCODCOL = PREPX.BDCODCOL and ' ||
         'PREP.BDORDEM = PREPX.BDORDEM) ' ||
         'left join VW_VRH_BASE_TCUSTOM_END CUST on (CUST.BDCODCENTRO = PREP.BDCODCENTRO and ' ||
         'CUST.BDCODTPCC = PREP.BDCODTPCC) ' ||
         'left outer join TCIDADE CID on (CUST.BDCODCID = CID.BDCODCID) ' ||
         'left outer join TUF UF on (UF.BDCODUF = CID.BDCODUF) ' ||
         'group by COL.BDCODEMP, COL.BDCODCOL, PREP.BDREFENTRADA, PREP.BDDATAENTRADA, PREP.BDCODCENTRO, PREP.BDCODTPCC, CUST.BDCODCID, CID.BDNOMCID, UF.BDSIGLAUF, UF.BDDESCUF ';
  FOR EXECUTE STATEMENT wSQL INTO
    :BDCODEMP, :BDCODCOL, :BDORDEM, :BDREFENTRADA, :BDDATAENTRADA, :BDCODCENTRO, :BDCODTPCC, :BDCODCID, :BDNOMCID, :BDSIGLAUF, :BDDESCUF DO
  BEGIN
    SUSPEND;
  END
END^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_ADMPREL_AU0 FOR VRH_EMP_TCOL_ADMPREL
ACTIVE AFTER UPDATE POSITION 0
AS
--  declare variable wcontrcol INTEGER;
--  declare variable wref INTEGER;
--  declare variable wtipoadm INTEGER;
--  declare variable wcodplafuc INTEGER;
--  declare variable wcodtfuc INTEGER;
--  declare variable wcategoriacol INTEGER;
--  declare variable wtipocol INTEGER;
--  declare variable wMatricula varchar(30);
--  declare variable wMatriculaSemVinc varchar(30);
begin
/*  if (TRIM(UPPER(coalesce(new.bdcadcolcon, 'FALSE'))) = 'FALSE') then
     begin
       if (coalesce(new.BDCODCLA, 0) in (2, 3)) then
          wcontrcol = 1;
       else
          wcontrcol = 0;
     
       if (coalesce(new.bdtipoadmcol, 0) > 0) then
          wtipoadm = new.bdtipoadmcol;
       else
          wtipoadm = null;
     
       wref = cast((substring(cast(new.bddataadmcol as varchar(10)) from 1 for 4)||substring(cast(new.bddataadmcol as varchar(10)) from 6 for 2)) as integer);
     
       wcodplafuc = null;
       select first 1 BDCODPLAFUC from VRH_BASE_TEMPVINC where BDCODEMP = new.bdcodemp and BDREFEMP <= :wref order by BDREFEMP desc into :wcodplafuc;
     
       wcodtfuc = null;
       if (coalesce(wcodplafuc, 0) > 0) then
          wcodtfuc = new.bdcodtfuc;
     
       wcategoriacol = null;

       wtipocol = new.bdtipocol;

       if (coalesce(:wtipocol, 0) > 0) then
          wtipocol = wtipocol - 1;
     
       select first 1 BDCATEGORIACOL from VRH_ESOCIAL_TCATEGORIA where BDCODIGO = new.bdcategoriaesocial into :wcategoriacol;
     
       wmatriculasemvinc = null;
       wMatricula = null;
       if ((new.bdcategoriaesocial in (901)) or (wcontrcol <> 0))  then
          wmatriculasemvinc = new.bdmatricula;
       else
          wMatricula = new.bdmatricula;

       update or insert into VRH_EMP_TCOLCON (BDCODEMP, BDCODCOL, BDDATANASCCOL, BDDATAADMCOL, BDDATAADICCOL, BDCPFCOL, BDMATRICULA, BDMATRICULASEMVINC, BDSTATUSQC, BDADMPRELIDRHNET, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, new.bddatanasccol, new.bddataadmcol, new.bddataadmcol, new.bdcpfcol, :wMatricula, :wmatriculasemvinc, new.bdstatusqc, new.bdidrhnet, :wcontrcol) matching(BDCODEMP, BDCODCOL);
     
       update or insert into VRH_EMP_TCOLCON_DOC (BDCODEMP, BDCODCOL, BDCPFCOL, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, new.bdcpfcol, :wcontrcol) matching(BDCODEMP, BDCODCOL);
     
       update or insert into VRH_EMP_TCOLCON_REF (BDCODEMP, BDCODCOL, BDREFCOL, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, :wref, :wcontrcol) matching(BDCODEMP, BDCODCOL, BDREFCOL);
     
       update or insert into VRH_EMP_TCOLCON_CAD (BDCODEMP, BDCODCOL, BDREFCOL, BDNOMCOL, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, :wref, new.bdnomcol, :wcontrcol) matching(BDCODEMP, BDCODCOL, BDREFCOL);
     
       update or insert into VRH_EMP_TCOLCON_VINC (BDCODEMP, BDCODCOL, BDREFCOL, BDCODCLA, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, :wref, new.bdcodcla, :wcontrcol) matching(BDCODEMP, BDCODCOL, BDREFCOL);
     
       update or insert into VRH_EMP_TCOLCON_DOCREF (BDCODEMP, BDCODCOL, BDREFCOL, BDPISCOL, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, :wref, new.bdpiscol, :wcontrcol) matching(BDCODEMP, BDCODCOL, BDREFCOL);
     
       update or insert into VRHF_EMP_TCOLCON_FGTSGPS (BDCODEMP, BDCODCOL, BDREFCOL, BDCATEGORIACOL, BDCATEGORIAESOCIAL, BDDATAOPCAOFGTSCOL, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, :wref, :wcategoriacol, new.bdcategoriaesocial, new.bddataadmcol, :wcontrcol) matching(BDCODEMP, BDCODCOL, BDREFCOL);
     
       update or insert into VRH_EMP_TCOL_ADM (BDCODEMP, BDCODCOL, BDTIPOADMCOL, BDDIASPRAZO1COL,BDDATAFIMPRAZO1COL, BDSALINICOL, BDESTATUTARIO, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, :wtipoadm, new.bddiasprazo1col, new.bddatafimprazo1col, new.bdsalbasecol, new.bdestatutario, :wcontrcol) matching(BDCODEMP, BDCODCOL);
     
       update or insert into VRH_EMP_TCOLCON_PARTIDA (BDCODEMP, BDCODCOL, BDCODPLAFUC, BDCODTFUC, BDSALINICOL, BDCODTIPOCONTRATO, BDDATAADMCOL, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, :wcodplafuc, :wcodtfuc, new.bdsalbasecol, new.bdcodtipocontrato, new.bddataadmcol, :wcontrcol) matching(BDCODEMP, BDCODCOL);
     
       update or insert into VRHF_EMP_TCOL_CALC (BDCODEMP, BDCODCOL, BDREFCOL, BDTIPOCOL, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, :wref, :wtipocol, :wcontrcol) matching(BDCODEMP, BDCODCOL, BDREFCOL);
     end */
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_ADMPREL_AI0 FOR VRH_EMP_TCOL_ADMPREL
ACTIVE AFTER INSERT POSITION 0
AS
--  declare variable wcontrcol INTEGER;
--  declare variable wref INTEGER;
--  declare variable wtipoadm INTEGER;
--  declare variable wcodplafuc INTEGER;
--  declare variable wcodtfuc INTEGER;
--  declare variable wcategoriacol INTEGER;
--  declare variable wtipocol INTEGER;
--  declare variable wMatricula varchar(30);
--  declare variable wMatriculaSemVinc varchar(30);
begin
/*  wcontrcol = null;
  select first 1 BDCODCOL from VRH_EMP_TCOLCON where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol into :wcontrcol;


  if (coalesce(wcontrcol, 0) = 0) then
     begin
       if (coalesce(new.BDCODCLA, 0) in (2, 3)) then
          wcontrcol = 1;
       else
          wcontrcol = 0;
     
       if (coalesce(new.bdtipoadmcol, 0) > 0) then
          wtipoadm = new.bdtipoadmcol;
       else
          wtipoadm = null;
     
       wref = cast((substring(cast(new.bddataadmcol as varchar(10)) from 1 for 4)||substring(cast(new.bddataadmcol as varchar(10)) from 6 for 2)) as integer);
     
       wcodplafuc = null;
       select first 1 BDCODPLAFUC from VRH_BASE_TEMPVINC where BDCODEMP = new.bdcodemp and BDREFEMP <= :wref order by BDREFEMP desc into :wcodplafuc;
     
       wcodtfuc = null;
       if (coalesce(wcodplafuc, 0) > 0) then
          wcodtfuc = new.bdcodtfuc;
     
       wtipocol = new.bdtipocol;

       if (coalesce(:wtipocol, 0) > 0) then
          wtipocol = wtipocol - 1;

       wcategoriacol = null;
       select first 1 BDCATEGORIACOL from VRH_ESOCIAL_TCATEGORIA where BDCODIGO = new.bdcategoriaesocial into :wcategoriacol;
     
       wMatricula = null;
       wmatriculasemvinc = null;
       if ((new.bdcategoriaesocial in (901)) or (wcontrcol <> 0))  then
          wmatriculasemvinc = new.bdmatricula;
       else
          wMatricula = new.bdmatricula;

       update or insert into VRH_EMP_TCOLCON (BDCODEMP, BDCODCOL, BDDATANASCCOL, BDDATAADMCOL, BDDATAADICCOL, BDCPFCOL, BDMATRICULA, BDMATRICULASEMVINC, BDSTATUSQC, BDADMPRELIDRHNET, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, new.bddatanasccol, new.bddataadmcol, new.bddataadmcol, new.bdcpfcol, :wMatricula, :wmatriculasemvinc, new.bdstatusqc, new.bdidrhnet, :wcontrcol) matching(BDCODEMP, BDCODCOL);
     
       update or insert into VRH_EMP_TCOLCON_DOC (BDCODEMP, BDCODCOL, BDCPFCOL, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, new.bdcpfcol, :wcontrcol) matching(BDCODEMP, BDCODCOL);
     
       update or insert into VRH_EMP_TCOLCON_REF (BDCODEMP, BDCODCOL, BDREFCOL, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, :wref, :wcontrcol) matching(BDCODEMP, BDCODCOL, BDREFCOL);
     
       update or insert into VRH_EMP_TCOLCON_CAD (BDCODEMP, BDCODCOL, BDREFCOL, BDNOMCOL, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, :wref, new.bdnomcol, :wcontrcol) matching(BDCODEMP, BDCODCOL, BDREFCOL);
     
       update or insert into VRH_EMP_TCOLCON_VINC (BDCODEMP, BDCODCOL, BDREFCOL, BDCODCLA, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, :wref, new.bdcodcla, :wcontrcol) matching(BDCODEMP, BDCODCOL, BDREFCOL);
     
       update or insert into VRH_EMP_TCOLCON_DOCREF (BDCODEMP, BDCODCOL, BDREFCOL, BDPISCOL, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, :wref, new.bdpiscol, :wcontrcol) matching(BDCODEMP, BDCODCOL, BDREFCOL);
     
       update or insert into VRHF_EMP_TCOLCON_FGTSGPS (BDCODEMP, BDCODCOL, BDREFCOL, BDCATEGORIACOL, BDCATEGORIAESOCIAL, BDDATAOPCAOFGTSCOL, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, :wref, :wcategoriacol, new.bdcategoriaesocial, new.bddataadmcol, :wcontrcol) matching(BDCODEMP, BDCODCOL, BDREFCOL);
     
       update or insert into VRH_EMP_TCOL_ADM (BDCODEMP, BDCODCOL, BDTIPOADMCOL, BDDIASPRAZO1COL,BDDATAFIMPRAZO1COL, BDSALINICOL, BDESTATUTARIO, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, :wtipoadm, new.bddiasprazo1col, new.bddatafimprazo1col, new.bdsalbasecol, new.bdestatutario, :wcontrcol) matching(BDCODEMP, BDCODCOL);
     
       update or insert into VRH_EMP_TCOLCON_PARTIDA (BDCODEMP, BDCODCOL, BDCODPLAFUC, BDCODTFUC, BDSALINICOL, BDCODTIPOCONTRATO, BDDATAADMCOL, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, :wcodplafuc, :wcodtfuc, new.bdsalbasecol, new.bdcodtipocontrato, new.bddataadmcol, :wcontrcol) matching(BDCODEMP, BDCODCOL);
     
       update or insert into VRHF_EMP_TCOL_CALC (BDCODEMP, BDCODCOL, BDREFCOL, BDTIPOCOL, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, :wref, :wtipocol, :wcontrcol) matching(BDCODEMP, BDCODCOL, BDREFCOL);

       update or insert into VRH_EMP_TCOLCON_DIA (BDCODEMP, BDCODCOL, BDDATACOL, BDCONTRCOL) values
         (new.bdcodemp, new.bdcodcol, new.bddataadmcol, :wcontrcol) matching(BDCODEMP, BDCODCOL, BDDATACOL);
     end        */
end
^

CREATE OR ALTER procedure SP_ANONIMIZA
as
declare variable WCPF varchar(50);
declare variable WKEY varchar(18);
declare variable I integer = 0;
declare variable WSEGURANCA varchar(200);
begin
  /* Procedure Text */
  select bdVALORSTR from TPARAMETRO where bdPARAM='ANONIMIZADO' into :wseguranca;
  if (wseguranca is not null) then
  begin
    for select RDB$DB_KEY, BDCPFBENEF from VRH_EMP_TCOLCON_BENEF into :wKey, :wCPF do
    begin
      select CPF from DIGITOCPF(:wCPF) into :wCPF;
      update VRH_EMP_TCOLCON_BENEF set BDCPFBENEF=:wCPF where RDB$DB_KEY=:wKey;
    end

    for select RDB$DB_KEY, BDCPFDPNTERC from VRH_BASE_TTERC_TDEP_REF into :wKey, :wCPF do
    begin
      select CPF from DIGITOCPF(:wCPF) into :wCPF;
      update VRH_BASE_TTERC_TDEP_REF set BDCPFDPNTERC=:wCPF where RDB$DB_KEY=:wKey;
    end

    for select RDB$DB_KEY, BDCPFMEITER from TTERCEIRO_RH into :wKey, :wCPF do
    begin
      select CPF from DIGITOCPF(:wCPF) into :wCPF;
      update TTERCEIRO_RH set BDCPFMEITER=:wCPF where RDB$DB_KEY=:wKey;
    end

    for select RDB$DB_KEY, BDCPFBENEF from VRH_EMP_TCOLCON_BENEF into :wKey, :wCPF do
    begin
      select CPF from DIGITOCPF(:wCPF) into :wCPF;
      update VRH_EMP_TCOLCON_BENEF set BDCPFBENEF=:wCPF where RDB$DB_KEY=:wKey;
    end

    for select RDB$DB_KEY, BDCPFDPN from VRH_EMP_TDEP_REF into :wKey, :wCPF do
    begin
      select CPF from DIGITOCPF(:wCPF) into :wCPF;
      update VRH_EMP_TDEP_REF set BDCPFDPN=:wCPF where RDB$DB_KEY=:wKey;
    end

    for select RDB$DB_KEY, BDCPFCOL from VRH_EMP_TCOL_ADMPREL into :wKey, :wCPF do
    begin
      select CPF from DIGITOCPF(:wCPF) into :wCPF;
      update VRH_EMP_TCOL_ADMPREL set bdCPFCOL=:wCPF where RDB$DB_KEY=:wKey;
    end

    for select RDB$DB_KEY, BDCPFCOL from VRH_EMP_TCOLCON_DOC into :wKey, :wCPF do
    begin
      select CPF from DIGITOCPF(:wCPF) into :wCPF;
      update VRH_EMP_TCOLCON_DOC set bdCPFCOL=:wCPF where RDB$DB_KEY=:wKey;
    end

    for select RDB$DB_KEY, BDCPFRESPLEGALSOC from EMPRESAS_TSOC into :wKey, :wCPF do
    begin
      select CPF from DIGITOCPF(:wCPF) into :wCPF;
      update EMPRESAS_TSOC set BDCPFRESPLEGALSOC=:wCPF where RDB$DB_KEY=:wKey;
    end

    for select RDB$DB_KEY, BDCPFINVENTARIANTE from EMPRESAS_TSOC_REF into :wKey, :wCPF do
    begin
      select CPF from DIGITOCPF(:wCPF) into :wCPF;
      update EMPRESAS_TSOC_REF set BDCPFINVENTARIANTE=:wCPF where RDB$DB_KEY=:wKey;
    end

    for select bdCODTER from SP_VRH_CONSULTA_AUT_RPA(202208) into :i do
    begin
      update TTERCEIRO ter set ter.bdCODTIPO=1, bdCGCTER = '999.999.999-99' where ter.bdCODTER=:i;
      update TTERCEIRO_REF RF set BDAPELIDOTER = 'ANONIMIZADO', BDNOMETER = 'ANONIMIZADO', BDNUMTER = '', BDCODCID = null, BDENDTER = '', BDCOMPTER = '', BDCEPTER = '', BDBAITER = '', BDDDDTER = 0, BDFONETER = '', BDFAXTER = '', BDEMAILTER = '', BDIETER = '', BDIMTER = '', BDINSCSUFRAMATER = '', BDDDDFAXTER = 0, BDDDDCELULARTER = 0, BDCELULARTER = '', BDCGCTER = '', BDNUMERONIF = '', BDCPFPROD = '', BDNOMESOCIALTER = '', BDEMAIL2TER = '' where rf.bdCODTER=:i;
      update VRH_BASE_TTERC_DOCREF DOCREF set BDRGTER = '', BDORGEMIRGTER = '', BDPISTER = '', BDNROCONSPROTER = '', BDSIGLACONSPROTER = '', BDCODCCMPROTER = '', BDCNHTER = '', BDCATCNHTER = '', BDORGAOCNH = '', BDCTPSTER = '', BDSERIECTPSTER = '' where DOCREF.BDCODTER = :i;
      update VRH_BASE_TTERC_PARENT PAR set BDNOMEPAITER = '', BDNOMEMAETER = '', BDNOMECONJTER = '' where par.BDCODTER = :i;
      update VRH_BASE_TTERC_DOC doc set BDRESERVISTATER='', bdSUS='' where doc.bdcodter= :i;
      update VRH_BASE_TTERC_VINC vin set BDCODCBO=null where vin.bdcodter= :i;
    end
  end
end^

/* Restore proc. body: SP_FILA_QUALIFICA_ESOCIAL */
create or alter procedure SP_FILA_QUALIFICA_ESOCIAL (
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL varchar(100),
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDDATANASCCOL date,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP DM_CNPJ_CPF,
    BDTIPO integer,
    BDIDRHNETADMPRE integer)
as
declare variable WNOME varchar(100);
declare variable WCPF varchar(14);
declare variable WPIS varchar(14);
declare variable WDTNASC date;
declare variable WCODIGO integer;
begin
  BDCODEMP        = 0;
  BDNOMEMP        = null;
  BDCNPJEMP       = null;
  BDTIPO          = 2;
  BDIDRHNETADMPRE = null;

  for select T.BDCODTER, T.BDCGCTER
      from TTERCEIRO T
      join VRH_BASE_TTERC_DOC D on (D.BDCODTER = T.BDCODTER)
      where char_length(T.BDCGCTER) = 14 and ((D.BDSTATUSQC not in (2, 3, 4)) or (D.BDSTATUSQC is null))
  into :BDCODCOL, :BDCPFCOL
  do
    begin
      BDPISCOL = null;
      select first 1 BDPISTER from VRH_BASE_TTERC_DOCREF where BDCODTER = :BDCODCOL and BDREFTERC <= :prref order by BDREFTERC DESC into :BDPISCOL;

      -- Se não houver PIS não é possível realizar a qualificação cadastral
--      if (trim(replace(replace(coalesce(BDPISCOL, ''), '.', ''), '-', '')) <> '') then
--         begin
           select first 1 BDNOMETER from TTERCEIRO_REF where BDCODTER = :BDCODCOL and BDREFEMP <= :prref order by BDREFEMP DESC into :BDNOMCOL;
           select first 1 BDDATANASCTER from TTERCEIRO_RH where BDCODTER = :BDCODCOL into :BDDATANASCCOL;

           wcodigo = null;
           select first 1 BDCODTER, BDNOMEORIGINAL, BDCPF, BDPIS, BDDATANASC from VRH_BASE_TFILAQUALIFICA where BDCODTER = :BDCODCOL into :wcodigo, :wnome, :wcpf, :wpis, :wdtnasc;
           if ((coalesce(wcodigo, 0) <= 0) or (BDNOMCOL <> wnome) or (BDCPFCOL <> wcpf) or (BDPISCOL <> wpis) or (BDDATANASCCOL <> wdtnasc))   then
              suspend;
--         end
    end

  BDTIPO = 0;

  for select C.BDCODEMP, C.BDCODCOL, C.BDCPFCOL, C.BDDATANASCCOL, E.BDCNPJEMP, C.BDPISCOL, C.BDNOMCOL, C.BDIDRHNET
      from VRH_EMP_TCOL_ADMPREL C
      join TEMPRESAS E on (E.BDCODEMP = C.BDCODEMP)
      left outer join VRH_EMP_TRESCISAO R on (R.BDCODEMP = C.BDCODEMP and R.BDCODCOL = C.BDCODCOL)
      where ((C.BDSTATUSQC not in (2, 3, 4)) or (C.BDSTATUSQC is null)) and
            ((R.BDDATARESCISAO is null) or (R.BDREFRESCISAO >= :prref))
  into :BDCODEMP, :BDCODCOL, :BDCPFCOL, :BDDATANASCCOL, :BDCNPJEMP, :BDPISCOL, :BDNOMCOL, :BDIDRHNETADMPRE
  do
    begin
--      if (trim(replace(replace(coalesce(BDPISCOL, ''), '.', ''), '-', '')) <> '') then
--         begin
           select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :prref order by BDREFEMP desc into :BDNOMEMP;

           wcodigo = null;
           select first 1 BDCODCOL, BDNOMEORIGINAL, BDCPF, BDPIS, BDDATANASC from VRH_BASE_TFILAQUALIFICA where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL into :wcodigo, :wnome, :wcpf, :wpis, :wdtnasc;
           if ((coalesce(wcodigo, 0) <= 0) or (BDNOMCOL <> wnome) or (BDCPFCOL <> wcpf) or (BDPISCOL <> wpis) or (BDDATANASCCOL <> wdtnasc))   then
              suspend;
--         end
    end

  BDTIPO = 1;
  for select C.BDCODEMP, C.BDCODCOL, C.BDCPFCOL, C.BDDATANASCCOL, E.BDCNPJEMP, C.BDADMPRELIDRHNET
      from VRH_EMP_TCOLCON C
      join TEMPRESAS E on (E.BDCODEMP = C.BDCODEMP)
      left outer join VRH_EMP_TRESCISAO R on (R.BDCODEMP = C.BDCODEMP and R.BDCODCOL = C.BDCODCOL)
      where ((C.BDSTATUSQC not in (2, 3, 4)) or (C.BDSTATUSQC is null)) and
            ((R.BDDATARESCISAO is null) or (R.BDREFRESCISAO >= :prref))
  into :BDCODEMP, :BDCODCOL, :BDCPFCOL, :BDDATANASCCOL, :BDCNPJEMP, :BDIDRHNETADMPRE
  do
    begin
      BDPISCOL = null;
      select first 1 BDPISCOL from VRH_EMP_TCOLCON_DOCREF where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prref order by BDREFCOL desc into :BDPISCOL;

--      if (trim(replace(replace(coalesce(BDPISCOL, ''), '.', ''), '-', '')) <> '') then
--         begin
           select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :prref order by BDREFEMP desc into :BDNOMEMP;
           select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :prref order by BDREFCOL DESC into :BDNOMCOL;
     
           wcodigo = null;
           select first 1 BDCODCOL, BDNOMEORIGINAL, BDCPF, BDPIS, BDDATANASC from VRH_BASE_TFILAQUALIFICA where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL into :wcodigo, :wnome, :wcpf, :wpis, :wdtnasc;
           if ((coalesce(wcodigo, 0) <= 0) or (BDNOMCOL <> wnome) or (BDCPFCOL <> wcpf) or (BDPISCOL <> wpis) or (BDDATANASCCOL <> wdtnasc))   then
              suspend;
--         end
    end
end^

CREATE OR ALTER TRIGGER VRH_BASE_TFILAQUALIFICA_BI0 FOR VRH_BASE_TFILAQUALIFICA
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wcod INTEGER;
begin
  if (coalesce(new.bdcodigo, 0) = 0) then
     begin
       select coalesce(max(BDCODIGO), 0) + 1 from VRH_BASE_TFILAQUALIFICA into :wcod;
       new.bdcodigo = :wcod;
     end
end
^

/* Restore proc. body: SP_EXCLUI_CHAVES_TOL_FOLHA */
create or alter procedure SP_EXCLUI_CHAVES_TOL_FOLHA (
    PREMPRESA integer,
    PRTABELATOL varchar(256))
as
declare variable WCHAVEINI integer;
declare variable WSQL varchar(25000);
declare variable WCHAVEATU integer;
declare variable WTIPO integer;
declare variable WSQLEXEC varchar(25000);
declare variable WEMPFILTRO varchar(200);
declare variable WCODEMP integer;
begin
  wchaveini = 999999000;

  if (coalesce(prempresa, 0 ) > 0) then
     wempfiltro = ' where M.BDCODEMP = '||prempresa||' ';
  else
     wempfiltro = ' ';

  wSql= 'select X.* '||
        'from (select 0 bdtipo, M.BDCODEMPSUC, M.BDCHAVE '||
              'from tol_vef_emp_tmovser M '||
              'join '||prtabelatol||' p on (p.bdchave=m.bdchave and p.bdcodemp=m.bdcodemp) '||
              wempfiltro||
              'union all '||
              'select 1 bdtipo, M.BDCODEMPSUC, M.BDCHAVE '||
              'from tol_vef_emp_tmovent M '||
              'join '||prtabelatol||' p on (p.bdchave=m.bdchave and p.bdcodemp=m.bdcodemp) '||
              wempfiltro||
              'union all '||
              'select 2 bdtipo, M.BDCODEMPSUC, M.BDCHAVE '||
              'from tol_vef_emp_tmovsai M '||
              'join '||prtabelatol||' p on (p.bdchave=m.bdchave and p.bdcodemp=m.bdcodemp) '||
              wempfiltro||
        ') X';

  for execute statement wSql into :wtipo,:wCodEmp,:wChaveAtu do
  begin
    insert into vsuc_empresas_tlan(bdcodemp,bdchave,bdcodplapadrao,bdcodusu,bddebito,bdcredito,bdvalor,BDDATA) values(:wCodEmp,:wChaveIni,90132,1,null,277,1,'01/01/1999');

    wsqlexec = 'update '||prtabelatol||' set bdchave = '||wChaveIni||' where bdcodemp='||wCodEmp||' and bdchave = '||wChaveAtu;
    execute statement wsqlexec;

    wsqlexec = 'delete from '||prtabelatol||' where bdcodemp='||wCodEmp||' and bdchave = '||wChaveIni;
    execute statement wsqlexec;

    wChaveIni = wChaveIni +1;
  end
end^

CREATE OR ALTER trigger on_connect
active on connect position 0
AS
  DECLARE VARIABLE wId varchar(1024);
  DECLARE VARIABLE wUsu varchar(1024);
  declare variable wConTime timestamp; 
  declare variable wTem integer;
begin
  select trim(mon$remote_process), trim(mon$user), MON$TIMESTAMP from mon$attachments where mon$attachment_id=current_connection into :wId, :wUsu, :wConTime;

  select coalesce(count(*), 0) from TCE where ID=:wId and bdUSU=:wUsu into :wTem;
  if (wTem = 0 and wId is not null and wusu is not null) then
    UPDATE OR insert into TCE(ID, bdUSU, BDDATAHORA) values (:wId, :wUsu, :wcontime);

  wId = coalesce(wId, '');
  --Se não tiver aqui é bi parceiro
  if (upper(wusu) not in ('SYSDBA', 'PUBLIC', 'INTEGRACOES') AND NOT EXISTS(SELECT FIRST 1 1 FROM TPARCEIRO_BI
                                                                             WHERE BDUSU = :wusu AND
                                                                             BDDATA = CURRENT_DATE AND
                                                                             BDPROCESSO = :wId)) then
    BEGIN
      UPDATE OR INSERT INTO TPARCEIRO_BI (BDUSU, BDDATA, BDPROCESSO) VALUES (:wusu, CURRENT_DATE, :wId);
    END
end^

CREATE OR ALTER TRIGGER ON_DISCONNECT
ACTIVE ON DISCONNECT POSITION 0
AS
  declare variable wcodusuatual integer;
  declare variable wcodtelasis integer;
  declare variable wCONNECTID integer;
BEGIN
  select first 1 bdcodconf from vtpo_tconf
  where bdrefconf <= cast(extract(year from current_date)||lpad(extract(month from current_date), 2, 0) as integer)
  and bdinifimsessao = true  
  into :wcodusuatual;
  if (wcodusuatual is null) then
     exit;

   -- Gilberto - 23/02/2026 - #236745 - Criado para controlar o usuário fechar o único de forma normal, 
   --                                   desconeção da rede, finalização do servidor sci, 
   --                                   e finalizar o único pelo gerenciador de tarefas do windows, 
   --                                   incluindo quando o sistema é abortado expontâneamente pelo windows
  select first 1 bdcodusu from SP_GET_USUARIO into :wcodusuatual;-- Buscar usuário conectado

  SELECT first 1 CAST((TRIM(rdb$get_context('USER_SESSION', 'W_CONNECTID'))) AS INTEGER)
  FROM rdb$database into :wCONNECTID;

  -- Retornar o código da tela do único
  select first 1 bdcodtelasis from ttela_sistema where bdnometela = 'TFRUNICO' into :wcodtelasis;
  if (wcodusuatual <> 0) then
  begin
    -- Registrando troca de usuário na mesma seção
    insert into vtpo_atividade_exe_registro (bdcodusu, bdcodati, bddataini, bdhoraini, bddatafin, bdhorafin,
                                             bdcodsis, bdtiporegistro, bdcodtelasis)
    -- wcodusuatual - Usuário desconectando
    -- 4 - Encerramento de Sessão
    -- 1 - Único (seria o login no sistema)
    -- 1- Automático
    select first 1 usu.BDCODUSU, 4 as BDCODATI, current_date, current_time, current_date, current_time,
           1 as bdcodsis, 0 as BDTIPOREGISTRO, :wcodtelasis as BDCODTELASIS
    from tusuario usu
    where usu.bdcodusu = :wcodusuatual
    and not exists(select first 1 bdchave from vtpo_atividade_exe_registro
                   where bdcodusu = usu.bdcodusu
                   and bddataini = current_date
                   and lpad(extract(hour from bdhoraini),2,0)||lpad(extract(minute from bdhoraini),2,0) =
                       lpad(extract(hour from current_time),2,0)||lpad(extract(minute from current_time),2,0)
                   and bdconnectid = :wconnectid
                   and bdcodati = 4)
    and (select first 1 bdcodati from vtpo_atividade_exe_registro
         where bdcodusu = usu.bdcodusu
         and bddataini = current_date
         and bdhoraini <= current_time
         and bdconnectid = :wconnectid
         and bdcodati in (3,4)
         order by bdhoraini desc) = 3;
  end
END
^

create or alter procedure VTPO_INICIO_SESSAO (
    PRCODUSUATUAL integer,
    PRCODUSUNOVO integer)
as
declare variable VCODTELASIS integer;
declare variable VCONNECTID integer;
begin
  select first 1 bdcodconf from vtpo_tconf
  where bdrefconf <= cast(extract(year from current_date)||lpad(extract(month from current_date), 2, 0) as integer)
  and bdinifimsessao = true  
  into :VCONNECTID;
  if (VCONNECTID is null) then
     exit;

  -- Gilberto - 23/02/2026 - #236745 - Criado para exclusivamente para controle de login pelo usuário
  if ((coalesce(prcodusunovo,0) <> 0) and (coalesce(prcodusunovo,0) <> coalesce(prcodusuatual,0))) then
  begin
    execute procedure vtpo_gethostid;
    SELECT first 1 CAST((TRIM(rdb$get_context('USER_SESSION', 'W_CONNECTID'))) AS INTEGER)
    FROM rdb$database into :vconnectid;

    -- Gilberto - 23/02/2026 - #236745
    -- Retornar o código da tela do único
    select first 1 bdcodtelasis from ttela_sistema where bdnometela = 'TFRUNICO' into :vcodtelasis;
    if ((prcodusuatual <> 0) and (coalesce(prcodusunovo,0) <> 0)) then
    begin
      -- Registrando troca de usuário na mesma seção
      insert into vtpo_atividade_exe_registro (bdcodusu, bdcodati, bddataini, bdhoraini, bddatafin, bdhorafin,
                                               bdcodsis, bdtiporegistro, bdcodtelasis, bdobservacao)
      -- wcodusuatual - Usuário desconectando
      -- 4 - Encerramento de Sessão
      -- 1 - Único (seria o login no sistema)
      -- 1- Automático
      select first 1 usu.BDCODUSU, 4 as BDCODATI, current_date, current_time, current_date, current_time,
             1 as bdcodsis, 0 as BDTIPOREGISTRO, :vcodtelasis as BDCODTELASIS, 'Troca de usuário'
      from tusuario usu
      where usu.bdcodusu = :prcodusuatual
      and not exists(select first 1 bdchave from vtpo_atividade_exe_registro
                     where bdcodusu = usu.bdcodusu
                     and bddataini = current_date
                     and lpad(extract(hour from bdhoraini),2,0)||lpad(extract(minute from bdhoraini),2,0) =
                         lpad(extract(hour from current_time),2,0)||lpad(extract(minute from current_time),2,0)
                     and bdconnectid = :vconnectid
                     and bdcodati = 4)
      and (select first 1 bdcodati from vtpo_atividade_exe_registro
               where bdcodusu = usu.bdcodusu
               and bddataini = current_date
               and bdhoraini <= current_time
               and bdconnectid = :vconnectid
               and bdcodati in (3,4)
               order by bdhoraini desc) = 3;
    end
    -- Registrando entrada/Login no sistema
    insert into vtpo_atividade_exe_registro (bdcodusu, bdcodati, bddataini, bdhoraini, bddatafin, bdhorafin,
                                             bdcodsis, bdtiporegistro, bdcodtelasis)
    -- prcodusuario - Usuário fazendo login
    -- 3 - Início de Sessão
    -- 1 - Único (seria o login no sistema)
    -- 1 - Automático
    select first 1 usu.BDCODUSU, 3 as BDCODATI, current_date, current_time, current_date, current_time,
           1 as bdcodsis, 0 as BDTIPOREGISTRO, :vcodtelasis as BDCODTELASIS
    from tusuario usu
    where usu.bdcodusu = :prcodusunovo
    and not exists(select first 1 bdchave from vtpo_atividade_exe_registro
                   where bdcodusu = usu.bdcodusu
                   and bddataini = current_date
                   and lpad(extract(hour from bdhoraini),2,0)||lpad(extract(minute from bdhoraini),2,0) =
                       lpad(extract(hour from current_time),2,0)||lpad(extract(minute from current_time),2,0)
                   and bdconnectid = :vconnectid
                   and bdcodati = 3);
  end
end^


CREATE OR ALTER TRIGGER TFOLHAPGTOESOCIAL_AIU1 FOR TFOLHAPGTOESOCIAL
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;
begin
  if ((NEW.bdcodigo IS NULL) OR (NEW.bdcodigo = 0)) then
     begin
       select coalesce(max(bdcodigo) + 1, 1) from TFOLHAPGTOESOCIAL into :vcod;
       new.bdcodigo = :vcod;
     end
end^

CREATE OR ALTER TRIGGER VRH_CAD_TIPOREVEZAMENTO_BI0 FOR VRH_CAD_TIPOREVEZAMENTO
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  IF ((NEW.BDCODREVEZAMENTO IS NULL) OR (NEW.BDCODREVEZAMENTO = 0)) THEN
     BEGIN
       SELECT coalesce(MAX(BDCODREVEZAMENTO), 0) + 1 FROM VRH_CAD_TIPOREVEZAMENTO INTO :vNovoCod;
       NEW.BDCODREVEZAMENTO = :vNovoCod;
     END
END
^


create or alter procedure SP_CONS_INTEGRACAO_ESOCIAL (
    PRCODEMP integer,
    PRCODCOL integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODIGO integer,
    BDDATACONS date,
    BDNOMCOL varchar(70),
    BDDATANASC date,
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDRECIBO varchar(30))
as
declare variable WSQL varchar(30000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WCODMATRIZATU integer;
declare variable WCODMATRIZ integer;
begin
  /* Procedure Text */
  WSQL = 'SELECT FIRST 1 ES.*, AR.BDRECIBO FROM VRH_EMP_TCOLCON_ES ES ';
  WSQL = WSQL||' JOIN VRH_ESOCIAL_TARQUIVO AR ON ES.BDCODEMP = AR.BDCODEMP AND ES.BDCODCOL = AR.BDCODCOL AND AR.BDSTATUS = 2 AND AR.BDCODTIPO IN (24,35) ';
  WSQL = WSQL||' WHERE ES.BDCODEMP = '||PRCODEMP||' AND ES.BDCODCOL = '||PRCODCOL||' ';
  WSQL = WSQL||' ORDER BY BDCODEMP, BDCODCOL, BDRECIBO ';

  BDCODEMP = 0;
  BDCODCOL = 0;
  BDCODIGO = 0;
  BDDATACONS = NULL;
  BDNOMCOL = '';
  BDDATANASC = NULL;
  BDCPFCOL = '';
  BDPISCOL = '';
  BDRECIBO = '';

  EXECUTE STATEMENT WSQL INTO
  BDCODEMP,
  BDCODCOL,
  BDCODIGO,
  BDDATACONS,
  BDNOMCOL,
  BDDATANASC,
  BDCPFCOL,
  BDPISCOL,
  BDRECIBO;

  IF (BDCODEMP = 0) then
    BEGIN
      WSQL = 'SELECT BDCODEMPORIG, BDCODCOLORIG FROM VRH_EMP_TTRANSCOL ';
      WSQL = WSQL||' WHERE BDCODEMPDEST = '||PRCODEMP||' AND ';
      WSQL = WSQL||'       BDCODCOLDEST = '||PRCODCOL;

      WCODEMP = 0;
      WCODCOL = 0;
      EXECUTE STATEMENT WSQL INTO :WCODEMP, WCODCOL;

      IF (WCODEMP > 0) THEN
        BEGIN
          WCODMATRIZ = 0;
          WCODMATRIZATU = 0;
          SELECT BDCODMATRIZ FROM TEMPRESAS WHERE BDCODEMP = :PRCODEMP INTO :WCODMATRIZATU;
          SELECT BDCODMATRIZ FROM TEMPRESAS WHERE BDCODEMP = :WCODEMP INTO :WCODMATRIZ;

          if ((WCODMATRIZ <> 0 AND WCODMATRIZ = WCODMATRIZATU) or  -- FILIAL PARA FILIAL
              (WCODMATRIZ <> 0 AND WCODMATRIZ = PRCODEMP) or       -- FILIAL PARA MATRIZ
              (WCODMATRIZATU = WCODEMP)) THEN                      -- MATRIZ PARA FILIAL
            BEGIN
              WSQL = 'SELECT * FROM SP_CONS_INTEGRACAO_ESOCIAL('||WCODEMP||','||WCODCOL||')';
    
              EXECUTE STATEMENT WSQL INTO
              BDCODEMP,
              BDCODCOL,
              BDCODIGO,
              BDDATACONS,
              BDNOMCOL,
              BDDATANASC,
              BDCPFCOL,
              BDPISCOL,
              BDRECIBO;
            END
        END
    END

  suspend;
end^

-- Sol.183659 - Nathan de Faria - 02/08/2023
CREATE OR ALTER trigger vrh_esocial_tarquivo_bi0 for vrh_esocial_tarquivo
active before insert position 0
AS
DECLARE VARIABLE WCODIGO INTEGER;
DECLARE VARIABLE WINT INTEGER;
BEGIN
  --CRIA UM NOVO CODIGO, DEVIDO A IMPORTAÇÃO DO VPRA PARA O UNICO (SER MAIS RÁPIDO).
  IF ((NEW.BDCODIGO IS NULL) OR (NEW.BDCODIGO = 0)) THEN --IMPORTAÇÃO DO VISUAL PARA O UNICO
  BEGIN
    SELECT MAX(BDCODIGO) FROM VRH_ESOCIAL_TARQUIVO WHERE BDCODEMP=NEW.BDCODEMP INTO :WCODIGO;
    IF (WCODIGO IS NULL) THEN
      WCODIGO = 0;

    WCODIGO = WCODIGO + 1;

    NEW.BDCODIGO = WCODIGO;
  END

  IF (NEW.BDMOTIVO<>'') THEN
     BEGIN
       SELECT POS FROM POS('ALTERAÇÃO',upper(NEW.BDMOTIVO)) INTO :WINT;
       IF (:WINT>0) THEN
         new.BDMOTIVOINT=1;
        ELSE
          BEGIN
              SELECT POS FROM POS('EXCLUSÃO',upper(NEW.BDMOTIVO)) INTO :WINT;
              IF (:WINT>0) THEN
                 new.BDMOTIVOINT=2;
              else
                 begin
                   SELECT POS FROM POS('RETIFICAÇÃO',upper(NEW.BDMOTIVO)) INTO :WINT;
                    IF (:WINT>0) THEN
                       new.BDMOTIVOINT=3;
                    ELSE
                       new.BDMOTIVOINT=0;
                 end


          end
     END
END^

-- Sol.182136 - Isabella - 16/08/2023 - não considerar empresas marcadas para excluir das 20:00 as 06:00
CREATE OR ALTER trigger TDEFESTABDOWN_BI10 for TDEFESTABDOWN
active before insert position 0
AS
  declare variable vEncontrou varchar(1);
  declare variable vcod integer;
  declare variable vcodestab integer;
  declare variable vcont integer;
  declare variable vCNPJ varchar(20);
  declare variable vCAPEF varchar(20);
begin
  vEncontrou = 0;
  vcont = 0;

  if (new.bdtipinsc = 3) then
     begin
       :vCAPEF = substring(new.BDINSCRICAO from 1 for 3)||'.'||substring(new.BDINSCRICAO from 4 for 3)||'.'||substring(new.BDINSCRICAO from 7 for 3)||'/'||substring(new.BDINSCRICAO from 10 for 3)||'-'||substring(new.BDINSCRICAO from 13 for 2);
       :vcnpj = substring(new.BDRAIZ from 1 for 3)||'.'||substring(new.BDRAIZ from 4 for 3)||'.'||substring(new.BDRAIZ from 7 for 3)||'-'||substring(new.BDRAIZ from 10 for 2);

       select first 1 EMP.BDCODEMP from TEMPRESAS EMP
       JOIN tempresas_ref EMPREF ON (EMPREF.bdcodemp = emp.bdCODEMP AND EMPREF.bdrefemp = COALESCE(
                                               (SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x WHERE x.bdcodemp = emp.bdcodemp AND
                                                     X.BDREFEMP <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
                                                     ORDER BY x.bdcodemp DESC, x.bdrefemp DESC),
                                               (SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x
                                                      WHERE x.bdcodemp = emp.bdcodemp
                                                      AND x.bdcodplapadrao IS NOT NULL
                                                      AND x.bdcodhist IS NOT NULL
                                                      ORDER BY x.bdcodemp, x.bdrefemp),
                                               (SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x
                                                      WHERE x.bdcodemp = emp.bdcodemp
                                                      ORDER BY x.bdcodemp, x.bdrefemp)))

       where EMP.BDCNPJEMP = :vcnpj and EMPREF.BDSITEMP <> 'TRUE' and (BDEXCLUIR_QDO is null) and
             ((BDDOCAUXILIARCAEPF = :vCAPEF) or ((new.bdestabunico = 'T') and (BDDOCAUXILIARCAEPF is null))) order by EMP.BDCODEMP desc into :vcod;
     --194628 LuizCovre 18/01/2024 traz a empresa ativa caso tenham dois CNPJs iguais cadastrados no sistema
     --select first 1  EMP.BDCODEMP from TEMPRESAS EMP where EMP.BDCNPJEMP = :vcnpj and (BDEXCLUIR_QDO IS NULL) and ((BDDOCAUXILIARCAEPF = :vCAPEF) or ((new.bdestabunico = 'T') and (BDDOCAUXILIARCAEPF is null))) into :vcod;

       if (vcod is null) then
          begin
            select first 1 EMP.BDCODEMP from TEMPRESAS EMP
            join TEMPRESAS_REF REF on EMP.BDCODEMP = REF.BDCODEMP
            where REF.BDDOCAUXILIAR = :vcnpj and (BDEXCLUIR_QDO IS NULL) and ((BDDOCAUXILIARCAEPF = :vCAPEF) or ((new.bdestabunico = 'T') and (BDDOCAUXILIARCAEPF is null))) into :vcod;
          end
     end
  else
     begin
  :vcnpj = substring(new.BDINSCRICAO from 1 for 2)||'.'||substring(new.BDINSCRICAO from 3 for 3)||'.'||substring(new.BDINSCRICAO from 6 for 3)||'/'||substring(new.BDINSCRICAO from 9 for 4)||'-'||substring(new.BDINSCRICAO from 13 for 2);

       select first 1 EMP.BDCODEMP from TEMPRESAS EMP
       JOIN tempresas_ref EMPREF ON (EMPREF.bdcodemp = emp.bdCODEMP AND EMPREF.bdrefemp = COALESCE(
                                               (SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x WHERE x.bdcodemp = emp.bdcodemp AND
                                                     X.BDREFEMP <= (SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ANOMES')) FROM rdb$database)
                                                     ORDER BY x.bdcodemp DESC, x.bdrefemp DESC),
                                               (SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x
                                                      WHERE x.bdcodemp = emp.bdcodemp
                                                      AND x.bdcodplapadrao IS NOT NULL
                                                      AND x.bdcodhist IS NOT NULL
                                                      ORDER BY x.bdcodemp, x.bdrefemp),
                                               (SELECT FIRST 1 x.bdrefemp FROM tempresas_ref x
                                                      WHERE x.bdcodemp = emp.bdcodemp
                                                      ORDER BY x.bdcodemp, x.bdrefemp)))
       where EMP.BDCNPJEMP = :vcnpj and (EMPREF.BDSITEMP <> 'TRUE' or EMPREF.BDSITEMP is null) and (BDEXCLUIR_QDO is null) order by EMP.BDCODEMP desc into :vcod;
     --194628 LuizCovre 18/01/2024 traz a empresa ativa caso tenham dois CNPJs iguais cadastrados no sistema
     --select first 1  EMP.BDCODEMP from TEMPRESAS EMP where EMP.BDCNPJEMP = :vcnpj and (BDEXCLUIR_QDO IS NULL) into :vcod;
     end

  if (:vcod is null) then
    begin
      select first 1 EMP.BDCODEMP from TEMPRESAS EMP order by EMP.BDCODEMP desc into :vcod;
      vcod = coalesce(:vcod,0)+1;
      new.bdcad = 'F';
      
      for select EMP.BDCODESTAB from TDEFESTABDOWN EMP where EMP.bdcodestab >= :vcod order by EMP.bdcodestab into :vcodestab do
        begin
          if ((:vcodestab > :vcod) and (:vcodestab <> :vcod)) then
             begin
               new.bdcodestab = :vcod;
               break;
             end
          else
             vcod = vcodestab + 1;
        end
      new.bdcodestab = coalesce(:vcod,0);
    end
  else
    begin
      new.bdcodestab = :vcod;
      new.bdcad = 'T';
    end

  if (new.bdcodestab is null) then
    select coalesce(max(EMP.BDCODESTAB),0) + 1 BDCODESTAB from TDEFESTABDOWN EMP into new.bdcodestab;

  if (NEW.bdcodestab > 999999) then
    SELECT * FROM sp_get_codemp_download into NEW.bdcodestab;
end^

CREATE OR ALTER trigger tdefestabdown_bu0 for tdefestabdown
active before update position 0
AS
declare variable vOrganizacao integer;
begin
  /* Trigger text */

  SELECT TRIM(rdb$get_context('USER_SESSION', 'W_ORGANIZACAO')) FROM rdb$database into :vOrganizacao;

  if (coalesce(vOrganizacao,0) = 1) then
     begin
       if (new.bdcodestab is null) then
          new.bdcodestab = old.bdcodestab;
     
       if (new.bdcad is null) then
          new.bdcad = old.bdcad;
     end
end^

CREATE OR ALTER TRIGGER VEF_EMP_TDIMEGERREGESP_AD0 FOR VEF_EMP_TDIMEGERREGESP
ACTIVE AFTER DELETE POSITION 0
AS
begin
  delete from TOL_VEF_EMP_TDIMEGERREGESP where bdcodemp = OLD.bdcodemp and bdchavelan = OLD.bdordemregesp;
end
^

CREATE OR ALTER trigger tdefestabdown_biu0 for tdefestabdown
active before insert or update position 0
AS
  declare variable vCodMatriz varchar(15);
begin
  if (new.bdtipo = 'FILIAL') then
    begin
      select first 1 bdcodestab from TDEFESTABDOWN where bdraiz = new.bdraiz order by bdcodmatriz,bdcodestab into :vCodMatriz;
      if (:vCodMatriz <> :new.bdcodestab) then
         new.bdcodmatriz = :vCodMatriz;
    end

  if (new.bdcodfiltro is null) then
     begin
       select first 1 a.bdcodemp from TESTRUTURADOWN a where a.bdraiz = :new.bdraiz into new.bdcodfiltro;
     end
end^

CREATE OR ALTER TRIGGER TDEFFUNCIONARIODOWN_BU0 FOR TDEFFUNCIONARIODOWN
INACTIVE BEFORE UPDATE POSITION 0
AS
  declare variable vCodEmp integer;
  declare variable vCodCol integer;
  declare variable vCPFdown varchar(20);
  declare variable vdataadm varchar(20);
  declare variable wCodigosTentados varchar(1000);
  declare variable wvinculou integer;
  declare variable vCodColUnico integer;
  declare variable wsql varchar(30000);
  declare variable wCodTentou integer;
  declare variable vnovocod integer;
begin

 /*197173 Antonio J Brogni 27/02/2024 COMENTADA TRIGGER POIS O VINCULO DE CÓDIGOS FOI PASSADO PARA O SISTEMA(TGravaTabelaTempFuncionariosUnico.pVinculaEmpresaDownload)*/
  /*select first 1 BDCODEMP from TEMPRESAS where BDCODEMP = old.bdcodestab into :vCodEmp;

  if (((new.bdcodestab is not null) and (old.bdcodestab is null)) or (new.bdcodestab <> old.bdcodestab)) then --Empresa est?? no UNICO, vai pegar o BDCODEMP.
    begin

      :vCPFdown = substring(new.BDCPF from 1 for 3)||'.'||substring(new.BDCPF from 4 for 3)||'.'||substring(new.BDCPF from 7 for 3)||'-'||substring(new.BDCPF from 10 for 2);
      :vdataadm = substring(new.BDDATADM from 1 for 2)||'.'||substring(new.BDDATADM from 4 for 2)||'.'||substring(new.BDDATADM from 7 for 4);

      wCodigosTentados = '';
      wvinculou = 0;
      while (wvinculou = 0) do
        begin
          vCodColUnico = null;
          wsql = 'select first 1 bdcodcol from VRH_EMP_TCOLCON where BDCODEMP = '||:new.bdcodestab||' and BDCPFCOL = '''||:vcpfdown||''' and BDDATAADMCOL = '''||:vdataadm||'''';
    
          if (wCodigosTentados <> '') then
             wsql = wsql||' and bdcodcol not in ('||wcodigostentados||')';

          execute statement wsql into :vCodColUnico;
    
          if (vCodColUnico is not null) then
             begin
                wCodTentou = null;
                SELECT first 1 C.bdcodigo FROM TDEFFUNCIONARIODOWN C WHERE C.bdcodestab = new.bdcodestab AND C.bdcodigo = :vCodColUnico INTO :wCodTentou;
    
                if (wCodTentou is null) then
                   wvinculou = 1;
                else
                   begin
                     if (wCodigosTentados <> '') then
                        wCodigosTentados = wCodigosTentados||',';

                     wCodigosTentados = wCodigosTentados||vCodColUnico;
                   end
             end
          else
             begin
               wvinculou = 1;
             end
        end

      if (vCodColUnico is not null) then --Colab est?? no UNICO, vai pegar o BDCODCOL.
        begin
          new.bdcodigo = :vCodColUnico;
          new.bdcad = 'T';
        end
      else --Colab novo, precisa olhar o pr??ximo c??digo dispon??vel no UNICO dependendo se ?? Colaborador ou Contribuinte e tamb?? olhar nesta tabela(TDEFFUNCIONARIODOWN) se este novo c??digo est?? dispon??vel.
        begin
          if (new.bdpro = 'T') then --Se for Contribuinte, Autonomo ou Estagiario.
            begin
              if ((coalesce(new.bdcodestab,0) > 0)) then
                 begin
              select coalesce(max(X.bdcodcol) + 1, 1) from vrh_emp_tcolcon X where X.bdcodemp = new.bdcodestab AND coalesce(bdcontrcol, 0) = 1 into :vnovocod;
            
              if ((vnovocod is null) or (vnovocod = 0) or (vnovocod = 1)) then
                begin
                  vnovocod = 900000;
                end

                 select first 1 bdcodigo from SP_EXISTE_COLABORADOR_DOWNLOAD(:vnovocod,new.bdcodestab) into :vnovocod;
              end
                 end
            else --se for Funcionario/Colaborador.
              begin
                select coalesce(max(X.bdcodcol) + 1, 1) from vrh_emp_tcolcon X where X.bdcodemp = new.bdcodestab and coalesce(bdcontrcol, 0) <> 1 into :vnovocod;
            
                select first 1 bdcodigo from SP_EXISTE_COLABORADOR_DOWNLOAD(:vnovocod,new.bdcodestab) into :vnovocod;
              end
          new.bdcodigo = :vnovocod;
          new.bdcad = 'F';
        end

    end
  else if (:vCodEmp is null) then --empresa n??o est?? cadastrada no UNICO.
    begin
      select first 1 BDCODIGO from TDEFFUNCIONARIODOWN where BDCODESTAB = old.bdcodestab and BDCODIGO = new.bdcodigo into :vCodCol;

      if (:vCodCol is null) then --novo código do colab não está sendo utilizado na tabela, pode ser trocado.
        begin
          new.bdcodigo = new.bdcodigo;
        end
      else
        begin
          new.bdcodigo = old.bdcodigo;
        end
    end
  else --empresa está cadastrada no UNICO, portanto, os colabs que já estiverem também no UNICO, não podem trocar o código.
    begin
      if (old.bdcad = 'T') then --esses colabs estão no UNICO, não podem trocar o código.
        begin
          new.bdcodigo = old.bdcodigo;
        end
      else
        begin
          select first 1 BDCODCOL from VRH_EMP_TCOLCON where BDCODEMP = old.bdcodestab and BDCODCOL = new.bdcodigo into :vCodCol;

          if (:vCodCol is null) then --novo código do colab não está sendo utilizado na tabela, pode ser trocado.
            begin
              new.bdcodigo = new.bdcodigo;
            end
          else
            begin
              new.bdcodigo = old.bdcodigo;
            end

        end
    end */

end^

CREATE OR ALTER TRIGGER TDEFFUNCIONARIODOWN_BIU0 FOR TDEFFUNCIONARIODOWN
INACTIVE BEFORE INSERT POSITION 0
as
  declare variable vCodColUnico integer;
  declare variable vCodestab integer;
  declare variable vCodestabUnico integer;
  declare variable vCPFdown varchar(15);
  declare variable vDataAdm varchar(10);
  declare variable vcnpj varchar (30);
  declare variable vNovoCod integer;
  declare variable wsql varchar(10000);
  declare variable wvinculou integer;
  declare variable wCodTentou integer;
  declare variable wCodigosTentados varchar(100);
  /*197173 Antonio J Brogni 27/02/2024 COMENTADA TRIGGER POIS O VINCULO DE CÓDIGOS FOI PASSADO PARA O SISTEMA(TGravaTabelaTempFuncionariosUnico.pVinculaEmpresaDownload)*/
begin
  /*if ((new.bdinscestab = '') or (new.bdinscestab is null))  then --se o colaborador vier sem vinculo e a empresa for matriz sem filiais, pega a incrição(cnpj) e o código através da raiz e seta.
    begin
      select first 1 X.bdcodestab, X.bdinscricao from TDEFESTABDOWN X where X.bdraiz = new.bdraiz and X.bdestabunico = 'T' into :vCodestab, :vcnpj;
      if (new.bdtipo <> 1) then
        begin
      new.bdinscestab = :vcnpj;
      new.bdcodestab  = :vCodestab;
    end
    end
  else                       -- se veirem estabelecimentos CNO, vincula os colaboradores a matriz( 192721 Covre 05/12/2023 )
  if ((new.bdinscestab <> '' or new.bdinscestab is not null) and (CHAR_LENGTH(new.bdinscestab) = 12)) then
    begin
      select first 1 X.bdcodestab, X.bdinscricao from TDEFESTABDOWN X where X.bdraiz = new.bdraiz into :vCodestab, :vcnpj;
      if (new.bdtipo <> 1) then
        begin
          new.bdinscestab = :vcnpj;
          new.bdcodestab  = :vCodestab;
        end
    end
  else 
    begin
      select first 1 X.bdcodestab from TDEFESTABDOWN X where X.bdraiz = new.bdraiz and X.bdinscricao = new.bdinscestab into :vCodestab;
      new.bdcodestab  = :vCodestab;
    end

  :vcnpj = substring(new.bdinscestab from 1 for 2)||'.'||substring(new.bdinscestab from 3 for 3)||'.'||substring(new.bdinscestab from 6 for 3)||'/'||substring(new.bdinscestab from 9 for 4)||'-'||substring(new.BDINSCESTAB from 13 for 2);
--select first 1 EMP.BDCODEMP from TEMPRESAS EMP where EMP.BDCNPJEMP = :vcnpj  and (BDEXCLUIR_QDO IS NULL) into :vCodestabUnico;
  select first 1 EMP.BDCODEMP from VW_TEMPRESAS_REF EMP where EMP.BDCNPJEMP = :vcnpj and EMP.BDSITEMP <> 'TRUE' and (BDEXCLUIR_QDO IS NULL) order by EMP.BDCODEMP desc into :vCodestabUnico;

  if (vCodestabUnico is not null) then --Empresa está no UNICO, vai pegar o BDCODEMP.
    begin
      new.bdcodestab = :vCodestabUnico;

      :vCPFdown = substring(new.BDCPF from 1 for 3)||'.'||substring(new.BDCPF from 4 for 3)||'.'||substring(new.BDCPF from 7 for 3)||'-'||substring(new.BDCPF from 10 for 2);
      :vdataadm = substring(new.BDDATADM from 1 for 2)||'.'||substring(new.BDDATADM from 4 for 2)||'.'||substring(new.BDDATADM from 7 for 4);

      wCodigosTentados = '';
      wvinculou = 0;
      while (wvinculou = 0) do
        begin
          vCodColUnico = null;
          wsql = 'select first 1 bdcodcol from VRH_EMP_TCOLCON where BDCODEMP = '||:vCodestabUnico||' and BDCPFCOL = '''||:vcpfdown||''' and BDDATAADMCOL = '''||:vdataadm||'''';
    
          if (wCodigosTentados <> '') then
             wsql = wsql||' and bdcodcol not in ('||wcodigostentados||')';

    --      if (new.bdpro = 'T') then
    --         wsql = wsql||' and BDMATRICULASEMVINC = '''||new.bdmatricula||'''';
    --      else
    --         wsql = wsql||' and BDMATRICULA = '''||new.bdmatricula||'''';
    
          execute statement wsql into :vCodColUnico;
    
          -- Verifica se este código já não está vinculado em outro registro da importação e set tem outro cadastro que pode ser vinculado automáticamente
          if (vCodColUnico is not null) then
             begin
                wCodTentou = null;
                SELECT first 1 C.bdcodigo FROM TDEFFUNCIONARIODOWN C WHERE C.bdcodestab = new.bdcodestab AND C.bdcodigo = :vCodColUnico INTO :wCodTentou;
    
                if (wCodTentou is null) then
                   wvinculou = 1;
                else
                   begin
                     if (wCodigosTentados <> '') then
                        wCodigosTentados = wCodigosTentados||',';

                     wCodigosTentados = wCodigosTentados||vCodColUnico;
                   end
             end
          else
             begin
               wvinculou = 1;
             end
        end

      if (vCodColUnico is not null) then --Colab está no UNICO, vai pegar o BDCODCOL.
        begin
          new.bdcodigo = :vCodColUnico;
          new.bdcad = 'T';
        end
      else --Colab novo, precisa olhar o próximo código disponível no UNICO dependendo se é Colaborador ou Contribuinte e també olhar nesta tabela(TDEFFUNCIONARIODOWN) se este novo código está disponível.
        begin
          if (new.bdpro = 'T') then --Se for Contribuinte, Autonomo ou Estagiario.
            begin
              if ((coalesce(new.bdcodestab,0) > 0)) then
                 begin
              select coalesce(max(X.bdcodcol) + 1, 1) from vrh_emp_tcolcon X where X.bdcodemp = new.bdcodestab AND coalesce(bdcontrcol, 0) = 1 into :vnovocod;
            
              if ((vnovocod is null) or (vnovocod = 0) or (vnovocod = 1)) then
                begin
                  vnovocod = 900000;
                end

                 select first 1 bdcodigo from SP_EXISTE_COLABORADOR_DOWNLOAD(:vnovocod,new.bdcodestab) into :vnovocod;
              end
                 end
            else --se for Funcionario/Colaborador.
              begin
                select coalesce(max(X.bdcodcol) + 1, 1) from vrh_emp_tcolcon X where X.bdcodemp = new.bdcodestab and coalesce(bdcontrcol, 0) <> 1 into :vnovocod;
            
                select first 1 bdcodigo from SP_EXISTE_COLABORADOR_DOWNLOAD(:vnovocod,new.bdcodestab) into :vnovocod;
              end
          new.bdcodigo = :vnovocod;
          new.bdcad = 'F';
        end

    end
--  else if ((new.bdinscestab is not null) and (new.bdcodestab is not null)) then  --Empresa não está no UNICO, vai setar um novo código válido.
--    begin  --Colaborador sem vínculo e com a raiz com matriz e filial(is).
--      if ((new.bdpro = 'T')) then --Se for Contribuinte, Autonomo ou Estagiario.
--        begin
--          select coalesce(max(bdcodigo) + 1, 1) from TDEFFUNCIONARIODOWN where bdinscestab = NEW.bdinscestab and bdpro = 'T' into :vnovocod;
--            select coalesce(max(bdcodigo) + 1, 1) from TDEFFUNCIONARIODOWN where bdinscestab = NEW.bdinscestab into :vnovocod;
            
--          if ((vnovocod is null) or (vnovocod = 0) or (vnovocod = 1)) then
--            begin
--              vnovocod = 900000;
--            end
--            
--          select bdcodigo from SP_EXISTE_COLABORADOR_DOWNLOAD(:vnovocod,new.bdcodestab) into :vnovocod;
--        end
--      else --se for Funcionario/Colaborador.
--        begin
--          select coalesce(max(bdcodigo) + 1, 1) from TDEFFUNCIONARIODOWN where bdinscestab = NEW.bdinscestab and bdpro = 'F' into :vnovocod;

--          select bdcodigo from SP_EXISTE_COLABORADOR_DOWNLOAD(:vnovocod,new.bdcodestab) into :vnovocod;
--        end
            
--      new.bdcodigo = :vnovocod;
--      new.bdcad    = 'F';
--    end
  else --setar os códigos válidos de acordo com a tabela(TDEFFUNCIONARIODOWN) dos colabs ou contribuintes somente com raiz(matriz e filial(is)).
    begin
--      if ((new.bdpro = 'T')) then --Se for Contribuinte, Autonomo ou Estagiario.
--        begin
--          select coalesce(max(bdcodigo) + 1, 1) from TDEFFUNCIONARIODOWN where bdraiz = NEW.bdraiz and bdpro = 'T' into :vnovocod;
            select coalesce(max(bdcodigo) + 1, 1) from TDEFFUNCIONARIODOWN where bdraiz = NEW.bdraiz into :vnovocod;
            
--          if ((vnovocod is null) or (vnovocod = 0) or (vnovocod = 1)) then
--            begin
--              vnovocod = 900000;
--            end
--        end
--      else --se for Funcionario/Colaborador.
--        begin
--          select coalesce(max(bdcodigo) + 1, 1) from TDEFFUNCIONARIODOWN where bdraiz = NEW.bdraiz and bdpro = 'F' into :vnovocod;
--        end
            
      new.bdcodigo = :vnovocod;
      new.bdcad    = 'F';
    end


--  if (new.bdchave is null) then
--     begin
--       select coalesce(max(bdchave),0)+1 from tdeffuncionariodown into new.bdchave;
--     end*/
end^

CREATE OR ALTER trigger tdeflotacaodown_aiu0 for tdeflotacaodown
active before insert or update position 0
as
  declare variable vInscricao varchar(20);
  declare variable vCodEstab integer;
  declare variable vRaiz varchar(15);
  declare variable vCodLot varchar(50);
begin
  select first 1 BDINSCRICAO, BDRAIZ from TDEFESTABDOWN where bdcodestab = new.bdcodestab into :vinscricao, :vraiz;
  new.BDINSCESTAB = :vInscricao;

  if (new.bdlotunica = 'T') then
    begin
      select X.BDINSCRICAO, X.BDCODESTAB from TDEFESTABDOWN X
      where X.BDRAIZ = new.bdraiz and X.BDESTABUNICO = 'T' into :vInscricao, :vCodEstab;
      if (vCodEstab is not null) then
         begin
      new.bdcodestab  = :vCodEstab;
      new.bdinscestab = :vInscricao;
    end
    end

    if (new.bdtipo in (1, 10, 21, 24, 90, 91)) then
        new.bdordenacao = 0;
    else
        new.bdordenacao = 1;

  /*Feito agora na TDEFLOTACAODOWN_AIU1 (after)*/
--  for select BDCODLOT from TDEFLOTACAODOWN where BDCODESTAB = new.bdcodestab into :vcodlot DO
--    begin
--      update TLOTACAODOWN set BDINSCESTAB = :vInscricao where BDRAIZ = :vraiz and BDCODLOT = :vcodlot;
--    end
end^

CREATE OR ALTER trigger TDEFLOTACAODOWN_AIU1 for TDEFLOTACAODOWN
active after insert or update position 0
as
  declare variable vInscricao varchar(20);
  declare variable vRaiz varchar(15);
  declare variable vCodLot varchar(50);
begin
  select first 1 BDINSCRICAO, BDRAIZ from TDEFESTABDOWN where bdcodestab = new.bdcodestab into :vinscricao, :vraiz;

  for select BDCODLOT from TDEFLOTACAODOWN where BDCODESTAB = new.bdcodestab into :vcodlot DO
    begin
      update TLOTACAODOWN set BDINSCESTAB = :vInscricao where BDRAIZ = :vraiz and BDCODLOT = :vcodlot;
    end

  if ((old.bdcodcc is distinct from new.bdcodcc) or
     (old.bdinscestab is distinct from new.bdinscestab) or
     (old.bdimporta is distinct from new.bdimporta) or
     (old.bdtomaserv is distinct from new.bdtomaserv) or
     (old.bddoccontr is distinct from new.bddoccontr)) then
     begin
       update tlotacaodown
       set
         bdcodcc = new.bdcodcc,
         bdinscestab = new.bdinscestab,
         bdimporta = new.bdimporta,
         bdcnpjtomador = new.bdtomaserv,
         bdcnpjcontratante = new.bddoccontr
       where
         bdcodlot = new.bdcodlot and bdraiz = new.bdraiz;
     end
end^

CREATE OR ALTER trigger TESTRUTURADOWN_BI0 for TESTRUTURADOWN
active before insert position 0
AS
  declare variable vcod INTEGER;
  declare variable vRaiz varchar(15);
begin
  select first 1 BDRAIZ from TESTRUTURADOWN where BDRAIZ = new.bdraiz into :vraiz;

  if (:vraiz = new.bdraiz) then
    begin
       select first 1 BDCODEMP from TESTRUTURADOWN where BDRAIZ = :vraiz into :vcod;
       new.BDCODEMP = :vcod;
    end
  else
  if ((NEW.BDCODEMP IS NULL) OR (NEW.BDCODEMP = 0)) then
     begin
       select coalesce(max(BDCODEMP) + 1, 1) from TESTRUTURADOWN into :vcod;
       new.BDCODEMP = :vcod;
     end
end^

/* Restore proc. body: SP_VRHF_GETBAIXAAUTOMATICA */
create or alter procedure SP_VRHF_GETBAIXAAUTOMATICA (
    PRCODPLANOONLINE integer,
    PRCODBAIXA integer,
    PRANOMES integer)
returns (
    BDCHAVEFN integer,
    BDCHAVEFC integer,
    BDCHAVESERV integer,
    BDCHAVEADSAL integer,
    BDCHAVEFER integer,
    BDCHAVEAD13 integer,
    BDCHAVE13 integer,
    BDCHAVECOMP13 integer,
    BDCHAVERESC integer,
    BDCHAVEFA integer,
    BDDESCRICAO varchar(200),
    BDCREDFN integer,
    BDCREDFC integer,
    BDCREDSERV integer,
    BDCREDADSAL integer,
    BDCREDFER integer,
    BDCREDAD13 integer,
    BDCRED13 integer,
    BDCREDCOMP13 integer,
    BDCREDRESC integer,
    BDCREDFA integer)
as
begin
  for select BDCHAVEFN, BDCHAVEFC, BDCHAVESERV, BDCHAVEADSAL,
             BDCHAVEFER, BDCHAVEAD13, BDCHAVE13, BDCHAVECOMP13, BDCHAVERESC, BDCHAVEFA, BDDESCRICAO
      from VRH_BASE_BAIXA_CALC_AUTO
      where BDCODPLANOONLINE = :PRCODPLANOONLINE and BDCODBAIXA = :prcodbaixa
  into :BDCHAVEFN, :BDCHAVEFC, :BDCHAVESERV, :BDCHAVEADSAL,
       :BDCHAVEFER, :BDCHAVEAD13, :BDCHAVE13, :BDCHAVECOMP13, :BDCHAVERESC, :BDCHAVEFA, :BDDESCRICAO
  do
    begin
      select first 1 BDCONTACREDPGTO from TCONF_CONTAS_ONLINE_REF where BDCODPLANOONLINE = :prcodplanoonline and BDCHAVE = :BDCHAVEFN and BDREFCTA <= :pranomes order by BDREFCTA desc into :BDCREDFN;
      select first 1 BDCONTACREDPGTO from TCONF_CONTAS_ONLINE_REF where BDCODPLANOONLINE = :prcodplanoonline and BDCHAVE = :BDCHAVEFC and BDREFCTA <= :pranomes order by BDREFCTA desc into :BDCREDFC;
      select first 1 BDCONTACREDPGTO from TCONF_CONTAS_ONLINE_REF where BDCODPLANOONLINE = :prcodplanoonline and BDCHAVE = :BDCHAVESERV and BDREFCTA <= :pranomes order by BDREFCTA desc into :BDCREDSERV;
      select first 1 BDCONTACREDPGTO from TCONF_CONTAS_ONLINE_REF where BDCODPLANOONLINE = :prcodplanoonline and BDCHAVE = :BDCHAVEADSAL and BDREFCTA <= :pranomes order by BDREFCTA desc into :BDCREDADSAL;
      select first 1 BDCONTACREDPGTO from TCONF_CONTAS_ONLINE_REF where BDCODPLANOONLINE = :prcodplanoonline and BDCHAVE = :BDCHAVEFER and BDREFCTA <= :pranomes order by BDREFCTA desc into :BDCREDFER;
      select first 1 BDCONTACREDPGTO from TCONF_CONTAS_ONLINE_REF where BDCODPLANOONLINE = :prcodplanoonline and BDCHAVE = :BDCHAVEAD13 and BDREFCTA <= :pranomes order by BDREFCTA desc into :BDCREDAD13;
      select first 1 BDCONTACREDPGTO from TCONF_CONTAS_ONLINE_REF where BDCODPLANOONLINE = :prcodplanoonline and BDCHAVE = :BDCHAVE13 and BDREFCTA <= :pranomes order by BDREFCTA desc into :BDCRED13;
      select first 1 BDCONTACREDPGTO from TCONF_CONTAS_ONLINE_REF where BDCODPLANOONLINE = :prcodplanoonline and BDCHAVE = :BDCHAVECOMP13 and BDREFCTA <= :pranomes order by BDREFCTA desc into :BDCREDCOMP13;
      select first 1 BDCONTACREDPGTO from TCONF_CONTAS_ONLINE_REF where BDCODPLANOONLINE = :prcodplanoonline and BDCHAVE = :BDCHAVERESC and BDREFCTA <= :pranomes order by BDREFCTA desc into :BDCREDRESC;
      select first 1 BDCONTACREDPGTO from TCONF_CONTAS_ONLINE_REF where BDCODPLANOONLINE = :prcodplanoonline and BDCHAVE = :BDCHAVEFA and BDREFCTA <= :pranomes order by BDREFCTA desc into :BDCREDFA;

      suspend;
    end
end^

create or alter procedure SP_GET_MONTA_COMP_VERBA (
    PRDIA integer,
    PRMES integer,
    PRANO integer,
    PRINICIAL smallint = 0)
returns (
    BDCOMPETENCIA DM_COMP_8)
as
begin
  bdcompetencia = '';
  -- formata para Competência final
  if (coalesce(prinicial, 0) <> 0) then
     begin
       if (coalesce(prano, 0) > 0) then
          bdcompetencia = bdcompetencia||lpad(trim(cast(prano as varchar(4))), 4, '0');
       else
          bdcompetencia = bdcompetencia||'9999';

       if (coalesce(prmes, 0) > 0) then
          bdcompetencia = bdcompetencia||lpad(trim(cast(prmes as varchar(2))), 2, '0');
       else
          bdcompetencia = bdcompetencia||'99';

       if (coalesce(prdia, 0) > 0) then
          bdcompetencia = bdcompetencia||lpad(trim(cast(prdia as varchar(2))), 2, '0');
       else
          bdcompetencia = bdcompetencia||'99';
     end
  else
  -- formata para Competência inicial
     begin
       if (coalesce(prano, 0) > 0) then
          bdcompetencia = bdcompetencia||lpad(trim(cast(prano as varchar(4))), 4, '0');
       else
          bdcompetencia = bdcompetencia||'0000';

       if (coalesce(prmes, 0) > 0) then
          bdcompetencia = bdcompetencia||lpad(trim(cast(prmes as varchar(2))), 2, '0');
       else
          bdcompetencia = bdcompetencia||'00';

       if (coalesce(prdia, 0) > 0) then
          bdcompetencia = bdcompetencia||lpad(trim(cast(prdia as varchar(2))), 2, '0');
       else
          bdcompetencia = bdcompetencia||'00';
     end

  suspend;
end^


create or alter procedure SP_VRHF_GETVERBFERIASREF (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDTIPOFE integer,
    BDINIPERAQUISFE date,
    BDCODFE integer,
    BDCODVER integer,
    BDREFFE integer,
    BDREFVRFE DM_NUMERIC_15_2,
    BDREFAUXVRFE DM_NUMERIC_15_2,
    BDVALVRFE DM_NUMERIC_15_2,
    BDIGNREFVRFE DM_BOOLEAN,
    BDIGNVALVRFE DM_BOOLEAN,
    BDCODVERFN integer,
    BDDETALHERFE varchar(500),
    BDORDEMDETALHE integer,
    BDVALIRFE DM_NUMERIC_15_2,
    BDIGNREFAVRFE DM_BOOLEAN,
    BDCALCA13FE DM_BOOLEAN,
    BDTEMPOSERVFE integer,
    BDCLAVER varchar(20))
as
declare variable WCODFE integer;
declare variable WQTDABONOFE DM_NUMERIC_15_2;
begin
 /*
   BDTIPOFE = 0; indica são verbas de férias de períodos que estão sendo pagos no mês. Pode ser o início ou o final das férias
   BDTIPOFE = 1; indica férias normais que foram pagas SEM a verba de 1/3, devido ao COVID-19.
   BDTIPOFE = 2; indica ABONO normal que foi pago SEM a verba de 1/3, devido ao COVID-19.
   BDTIPOFE = 3; indica férias em DOBRO que foram pagas SEM a verba de 1/3, devido ao COVID-19.
   BDTIPOFE = 4; indica ABONO em DOBRO que foi pago SEM a verba de 1/3, devido ao COVID-19.
  */


  BDTIPOFE = 0;


  for select FR.BDINIPERAQUISFE, FR.BDCODFE, FR.BDCODVER, FR.BDREFFE, FR.BDREFVRFE, FR.BDREFAUXVRFE, FR.BDVALVRFE, FR.BDIGNREFVRFE, FR.BDIGNVALVRFE,
             FR.BDCODVERFN, FR.BDDETALHERFE, FR.BDORDEMDETALHE, FR.BDVALIRFE, FR.BDIGNREFAVRFE, FER.BDCALCA13FE, FER.BDTEMPOSERVFE, VER.BDCLAVER
      from VRHF_EMP_TVERBARFE FR
      join VRH_EMP_TFERIAS FER on (FER.BDCODEMP = FR.BDCODEMP and FER.BDCODCOL = FR.BDCODCOL and FER.BDINIPERAQUISFE = FR.BDINIPERAQUISFE and FER.BDCODFE = FR.BDCODFE)
      join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FR.BDCODVER)
      where (FR.BDCODEMP = :prcodemp) and (FR.BDCODCOL = :prcodcol) and (FR.BDREFFE = :pranomes)
  into :BDINIPERAQUISFE, :BDCODFE, :BDCODVER, :BDREFFE, :BDREFVRFE, :BDREFAUXVRFE, :BDVALVRFE, :BDIGNREFVRFE, :BDIGNVALVRFE,
       :BDCODVERFN, :BDDETALHERFE, :BDORDEMDETALHE, :BDVALIRFE, :BDIGNREFAVRFE, :BDCALCA13FE, :BDTEMPOSERVFE, :BDCLAVER
  do
    suspend;


  for select FER.BDINIPERAQUISFE, FER.BDCODFE, FER.BDCALCA13FE, FER.BDTEMPOSERVFE, FER.BDQTDABONOFE
      from VRH_EMP_TFERIAS FER
      where (FER.BDCODEMP = :prcodemp) and (FER.BDCODCOL = :prcodcol) and ((FER.BDINIPERGOZOFE >= '2020-03-01') or (FER.BDREFPAGABOFE >= 202203))
  into :BDINIPERAQUISFE, :BDCODFE, :BDCALCA13FE, :BDTEMPOSERVFE, :wqtdabonofe
  do
    begin
      /* FÉRIAS NORMAIS */
      wcodfe = null;
      select first 1 REF.BDCODFE
      from VRHF_EMP_TVERBARFE REF
      join VRH_BASE_TVERBAS VER on (VER.BDCODVER = REF.BDCODVER)
      where REF.BDCODEMP = :prcodemp and REF.BDCODCOL = :prcodcol and REF.BDINIPERAQUISFE = :BDINIPERAQUISFE and REF.BDCODFE = :BDCODFE
         and VER.BDCLAVER starting with '3.002'
      into :wcodfe;

      if (wcodfe is null) then
         begin
           BDTIPOFE = 1;

           for select FR.BDCODVER, FR.BDREFFE, FR.BDREFVRFE, FR.BDREFAUXVRFE, FR.BDVALVRFE, FR.BDIGNREFVRFE, FR.BDIGNVALVRFE,
                      FR.BDCODVERFN, FR.BDDETALHERFE, FR.BDORDEMDETALHE, FR.BDVALIRFE, FR.BDIGNREFAVRFE, VER.BDCLAVER
               from VRHF_EMP_TVERBARFE FR
               join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FR.BDCODVER)
               where (FR.BDCODEMP = :prcodemp) and (FR.BDCODCOL = :prcodcol) and (FR.BDINIPERAQUISFE = :BDINIPERAQUISFE) and (FR.BDCODFE = :BDCODFE)
           into :BDCODVER, :BDREFFE, :BDREFVRFE, :BDREFAUXVRFE, :BDVALVRFE, :BDIGNREFVRFE, :BDIGNVALVRFE,
                :BDCODVERFN, :BDDETALHERFE, :BDORDEMDETALHE, :BDVALIRFE, :BDIGNREFAVRFE, :BDCLAVER
           do
             suspend;
         end


      /* ABONO PECUNIÁRIO */
      if (coalesce(wqtdabonofe, 0) > 0) then
         begin
           wcodfe = null;
           select first 1 REF.BDCODFE
           from VRHF_EMP_TVERBARFE REF
           join VRH_BASE_TVERBAS VER on (VER.BDCODVER = REF.BDCODVER)
           where REF.BDCODEMP = :prcodemp and REF.BDCODCOL = :prcodcol and REF.BDINIPERAQUISFE = :BDINIPERAQUISFE and REF.BDCODFE = :BDCODFE
              and VER.BDCLAVER starting with '3.004'
           into :wcodfe;
     
           if (wcodfe is null) then
              begin
                BDTIPOFE = 2;
     
                for select FR.BDCODVER, FR.BDREFFE, FR.BDREFVRFE, FR.BDREFAUXVRFE, FR.BDVALVRFE, FR.BDIGNREFVRFE, FR.BDIGNVALVRFE,
                           FR.BDCODVERFN, FR.BDDETALHERFE, FR.BDORDEMDETALHE, FR.BDVALIRFE, FR.BDIGNREFAVRFE, VER.BDCLAVER
                    from VRHF_EMP_TVERBARFE FR
                    join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FR.BDCODVER)
                    where (FR.BDCODEMP = :prcodemp) and (FR.BDCODCOL = :prcodcol) and (FR.BDINIPERAQUISFE = :BDINIPERAQUISFE) and (FR.BDCODFE = :BDCODFE)
                into :BDCODVER, :BDREFFE, :BDREFVRFE, :BDREFAUXVRFE, :BDVALVRFE, :BDIGNREFVRFE, :BDIGNVALVRFE,
                     :BDCODVERFN, :BDDETALHERFE, :BDORDEMDETALHE, :BDVALIRFE, :BDIGNREFAVRFE, :BDCLAVER
                do
                  suspend;
              end
         end



      /* FÉRIAS EM DOBRO */
      wcodfe = null;
      select first 1 REF.BDCODFE
      from VRHF_EMP_TVERBARFE REF
      join VRH_BASE_TVERBAS VER on (VER.BDCODVER = REF.BDCODVER)
      where REF.BDCODEMP = :prcodemp and REF.BDCODCOL = :prcodcol and REF.BDINIPERAQUISFE = :BDINIPERAQUISFE and REF.BDCODFE = :BDCODFE
         and VER.BDCLAVER starting with '3.006'
      into :wcodfe;

      if (wcodfe is null) then
         begin
           wcodfe = null;
           select first 1 REF.BDCODFE
           from VRHF_EMP_TVERBARFE REF
           join VRH_BASE_TVERBAS VER on (VER.BDCODVER = REF.BDCODVER)
           where REF.BDCODEMP = :prcodemp and REF.BDCODCOL = :prcodcol and REF.BDINIPERAQUISFE = :BDINIPERAQUISFE and REF.BDCODFE = :BDCODFE
              and VER.BDCLAVER starting with '3.005' -- Verba de férias em dobro.
           into :wcodfe;

           if (wcodfe is not null) then
              begin
                BDTIPOFE = 3;
     
                for select FR.BDCODVER, FR.BDREFFE, FR.BDREFVRFE, FR.BDREFAUXVRFE, FR.BDVALVRFE, FR.BDIGNREFVRFE, FR.BDIGNVALVRFE,
                           FR.BDCODVERFN, FR.BDDETALHERFE, FR.BDORDEMDETALHE, FR.BDVALIRFE, FR.BDIGNREFAVRFE, VER.BDCLAVER
                    from VRHF_EMP_TVERBARFE FR
                    join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FR.BDCODVER)
                    where (FR.BDCODEMP = :prcodemp) and (FR.BDCODCOL = :prcodcol) and (FR.BDINIPERAQUISFE = :BDINIPERAQUISFE) and (FR.BDCODFE = :BDCODFE)
                into :BDCODVER, :BDREFFE, :BDREFVRFE, :BDREFAUXVRFE, :BDVALVRFE, :BDIGNREFVRFE, :BDIGNVALVRFE,
                     :BDCODVERFN, :BDDETALHERFE, :BDORDEMDETALHE, :BDVALIRFE, :BDIGNREFAVRFE, :BDCLAVER
                do
                  suspend;
              end
         end


      /* ABONO EM DOBRO */
      if (coalesce(wqtdabonofe, 0) <> 0) then
         begin
           wcodfe = null;
           select first 1 REF.BDCODFE
           from VRHF_EMP_TVERBARFE REF
           join VRH_BASE_TVERBAS VER on (VER.BDCODVER = REF.BDCODVER)
           where REF.BDCODEMP = :prcodemp and REF.BDCODCOL = :prcodcol and REF.BDINIPERAQUISFE = :BDINIPERAQUISFE and REF.BDCODFE = :BDCODFE
              and VER.BDCLAVER starting with '3.008'
           into :wcodfe;
     
           if (wcodfe is null) then
              begin
                wcodfe = null;
                select first 1 REF.BDCODFE
                from VRHF_EMP_TVERBARFE REF
                join VRH_BASE_TVERBAS VER on (VER.BDCODVER = REF.BDCODVER)
                where REF.BDCODEMP = :prcodemp and REF.BDCODCOL = :prcodcol and REF.BDINIPERAQUISFE = :BDINIPERAQUISFE and REF.BDCODFE = :BDCODFE
                   and VER.BDCLAVER starting with '3.007' -- Verba de abono em dobro.
                into :wcodfe;
     
                if (wcodfe is not null) then
                   begin
                     BDTIPOFE = 4;
          
                     for select FR.BDCODVER, FR.BDREFFE, FR.BDREFVRFE, FR.BDREFAUXVRFE, FR.BDVALVRFE, FR.BDIGNREFVRFE, FR.BDIGNVALVRFE,
                                FR.BDCODVERFN, FR.BDDETALHERFE, FR.BDORDEMDETALHE, FR.BDVALIRFE, FR.BDIGNREFAVRFE, VER.BDCLAVER
                         from VRHF_EMP_TVERBARFE FR
                         join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FR.BDCODVER)
                         where (FR.BDCODEMP = :prcodemp) and (FR.BDCODCOL = :prcodcol) and (FR.BDINIPERAQUISFE = :BDINIPERAQUISFE) and (FR.BDCODFE = :BDCODFE)
                     into :BDCODVER, :BDREFFE, :BDREFVRFE, :BDREFAUXVRFE, :BDVALVRFE, :BDIGNREFVRFE, :BDIGNVALVRFE,
                          :BDCODVERFN, :BDDETALHERFE, :BDORDEMDETALHE, :BDVALIRFE, :BDIGNREFAVRFE, :BDCLAVER
                     do
                       suspend;
                   end
              end
         end
    end
end^


/* Restore proc. body: SP_VRHF_GETCONTRSINDICAISNOANO */
create or alter procedure SP_VRHF_GETCONTRSINDICAISNOANO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRANOMES integer)
returns (
    BDCONTRSINDICAL DM_BOOLEAN,
    BDCONTRASSISTENCIAL DM_BOOLEAN)
as
declare variable WCODVER integer;
declare variable WANOMESINI integer;
declare variable WCODEMPATU integer;
declare variable WCODCOLATU integer;
declare variable WCONTRSIND DM_BOOLEAN;
declare variable WTAXASSIST DM_BOOLEAN;
begin
  /* busca contribuição sindical */
  BDCONTRSINDICAL = 'FALSE';
  wcodver         = null;

  wanomesini = cast((substring(:pranomes from 1 for 4)||'01') as integer);

  select first 1 FN.BDCODVER
  from VRHF_EMP_TVERBAFN FN
  join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER)
  where FN.BDCODEMP = :prcodemp and FN.BDCODCOL = :prcodcol and FN.BDREFFN >= :wanomesini and FN.BDREFFN < :pranomes
        and ((VER.BDCLAVER starting with '0.004.0.1') or (VER.BDCLAVER starting with '0.710.0.1'))
  into :wcodver;

  if (wcodver is not null) then
     BDCONTRSINDICAL = 'TRUE';
  else
     begin
       select first 1 FN.BDCODVER
       from VRHF_EMP_TVERBATOMADOR FN
       join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER)
       where FN.BDCODEMP = :prcodemp and FN.BDCODCOL = :prcodcol and FN.BDREFTOMADOR >= :wanomesini and FN.BDREFTOMADOR < :pranomes
             and ((VER.BDCLAVER starting with '0.004.0.1') or (VER.BDCLAVER starting with '0.710.0.1'))
       into :wcodver;

       if (wcodver is not null) then
          BDCONTRSINDICAL = 'TRUE';
       else
          begin
            select first 1 FN.BDCODVER
            from VRHF_EMP_TVERBAINT FN
            join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER)
            where FN.BDCODEMP = :prcodemp and FN.BDCODCOL = :prcodcol and FN.BDREFFN >= :wanomesini and FN.BDREFFN < :pranomes
                  and ((VER.BDCLAVER starting with '0.004.0.1') or (VER.BDCLAVER starting with '0.710.0.1'))
            into :wcodver;

            if (wcodver is not null) then
               BDCONTRSINDICAL = 'TRUE';
            else
               begin
                 select first 1 FN.BDCODVER
                 from VRHF_EMP_TVERBATOMINT FN
                 join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER)
                 where FN.BDCODEMP = :prcodemp and FN.BDCODCOL = :prcodcol and FN.BDREFTOMADOR >= :wanomesini and FN.BDREFTOMADOR < :pranomes
                       and ((VER.BDCLAVER starting with '0.004.0.1') or (VER.BDCLAVER starting with '0.710.0.1'))
                 into :wcodver;

                 if (wcodver is not null) then
                    BDCONTRSINDICAL = 'TRUE';
                 else
                    begin
                      select first 1 FN.BDCODCOL
                      from VRHF_EMP_TFICHARAIS FN
                      where FN.BDCODEMP = :prcodemp and FN.BDCODCOL = :prcodcol and FN.BDREFFRAIS >= :wanomesini and FN.BDREFFRAIS < :pranomes
                            and FN.BDCONTRSINDFRAIS > 0
                      into :wcodver;
     
                      if (wcodver is not null) then
                         BDCONTRSINDICAL = 'TRUE';
                    end
               end
          end
     end


  /* busca taxa assistencial */
  BDCONTRASSISTENCIAL = 'FALSE';
  wcodver             = null;

  select first 1 FN.BDCODVER
  from VRHF_EMP_TVERBAFN FN
  join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER)
  where FN.BDCODEMP = :prcodemp and FN.BDCODCOL = :prcodcol and FN.BDREFFN between :wanomesini and :pranomes
        and ((VER.BDCLAVER starting with '0.004.0.3') or (VER.BDCLAVER starting with '0.710.0.3'))
  order by FN.BDREFFN desc
  into :wcodver;

  if (wcodver is not null) then
     BDCONTRASSISTENCIAL = 'TRUE';
  else
     begin
       select first 1 FN.BDCODVER
       from VRHF_EMP_TVERBATOMADOR FN
       join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER)
       where FN.BDCODEMP = :prcodemp and FN.BDCODCOL = :prcodcol and FN.BDREFTOMADOR between :wanomesini and :pranomes
             and ((VER.BDCLAVER starting with '0.004.0.3') or (VER.BDCLAVER starting with '0.710.0.3'))
       order by FN.BDREFTOMADOR desc
       into :wcodver;

       if (wcodver is not null) then
          BDCONTRASSISTENCIAL = 'TRUE';
       else
          begin
            select first 1 FN.BDCODVER
            from VRHF_EMP_TVERBAINT FN
            join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER)
            where FN.BDCODEMP = :prcodemp and FN.BDCODCOL = :prcodcol and FN.BDREFFN between :wanomesini and :pranomes
                  and ((VER.BDCLAVER starting with '0.004.0.3') or (VER.BDCLAVER starting with '0.710.0.3'))
            order by FN.BDREFFN desc
            into :wcodver;

            if (wcodver is not null) then
               BDCONTRASSISTENCIAL = 'TRUE';
            else
               begin
                 select first 1 FN.BDCODVER
                 from VRHF_EMP_TVERBATOMINT FN
                 join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FN.BDCODVER)
                 where FN.BDCODEMP = :prcodemp and FN.BDCODCOL = :prcodcol and FN.BDREFTOMADOR between :wanomesini and :pranomes
                       and ((VER.BDCLAVER starting with '0.004.0.3') or (VER.BDCLAVER starting with '0.710.0.3'))
                 order by FN.BDREFTOMADOR desc
                 into :wcodver;

                 if (wcodver is not null) then
                    BDCONTRASSISTENCIAL = 'TRUE';
                 else
                    begin
                      select first 1 FN.BDCODCOL
                      from VRHF_EMP_TFICHARAIS FN
                      where FN.BDCODEMP = :prcodemp and FN.BDCODCOL = :prcodcol and FN.BDREFFRAIS between :wanomesini and :pranomes
                            and FN.BDCONTASSISTFRAIS > 0
                      order by FN.BDREFFRAIS desc
                      into :wcodver;
     
                      if (wcodver is not null) then
                         BDCONTRASSISTENCIAL = 'TRUE';
                    end
               end
          end
     end

  if ((BDCONTRSINDICAL = 'FALSE') or (BDCONTRASSISTENCIAL = 'FALSE')) then
     begin
       /* Procura por pagamentos feitos na empresa origem, em caso de transferido */
       for select BDCODEMPORIG, BDCODCOLORIG
           from VRH_EMP_TTRANSCOL
           where BDCODEMPDEST = :prcodemp and BDCODCOLDEST = :prcodcol
       into :wcodempatu, :wcodcolatu
       do
         begin
           if ((BDCONTRASSISTENCIAL = 'FALSE') or (BDCONTRSINDICAL = 'FALSE')) then
              begin
                select first 1 BDCONTRASSISTENCIAL, BDCONTRSINDICAL from SP_VRHF_GETCONTRSINDICAISNOANO(:wcodempatu, :wcodcolatu, :pranomes)
                into :wtaxassist, :wcontrsind;

                if (coalesce(:wtaxassist, 'FALSE') = 'TRUE') then
                   BDCONTRASSISTENCIAL = wtaxassist;

                if (coalesce(:wcontrsind, 'FALSE') = 'TRUE') then
                   BDCONTRSINDICAL = wcontrsind;
              end
         end
     end

  suspend;
end^

/* Restore proc. body: SP_CONS_FILA_RHNET */
CREATE OR ALTER procedure SP_CONS_FILA_RHNET (
    PRDATA varchar(10),
    PRANOMES integer,
    PRSTATUS varchar(30))
returns (
    BDCODARQ integer,
    BDCHAVEARQIND varchar(40),
    BDNOMARQJSON varchar(500),
    BDJSONVALUE blob sub_type 0 segment size 80,
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDDATAHORA timestamp,
    BDORIGEM varchar(500),
    BDSTATUS integer,
    BDRETORNO blob sub_type 1 segment size 16384,
    BDQTDAGUARDANDO integer,
    BDQTDENVIADO integer,
    BDQTDERROENVIO integer,
    BDSTATUSEXP varchar(15),
    BDTIPOJSON varchar(25))
as
declare variable WEMPATU integer;
declare variable WTIPOJSON integer;
declare variable WSQL varchar(300);
begin
  select count(*) from VRH_RHNET_TARQUIVO_EXP where BDSTATUS = 0 and BDDATAHORA >= :prdata into :BDQTDAGUARDANDO;
  select count(*) from VRH_RHNET_TARQUIVO_EXP where BDSTATUS = 1 and BDDATAHORA >= :prdata into :BDQTDENVIADO;
  select count(*) from VRH_RHNET_TARQUIVO_EXP where BDSTATUS = 2 and BDDATAHORA >= :prdata into :BDQTDERROENVIO;

  wempatu = 0;

  WSQL = 'select BDCODARQ, BDCHAVEARQIND, BDNOMARQJSON, BDJSONVALUE, BDCODEMP, BDDATAHORA, BDORIGEM, BDSTATUS, BDRETORNO, BDTIPOJSON ' ||
         'from VRH_RHNET_TARQUIVO_EXP ' ||
         'where BDSTATUS < 10 and BDDATAHORA >= ''' || :prdata ||'''';
  /*
  STATUS = 0 - Aguardando
  STATUS = 1 - Enviado
  STATUS = 2..9 - Erro
  */
  if (PRSTATUS <> '') then
     WSQL = WSQL || ' and BDSTATUS in ('|| :PRSTATUS ||')';

  WSQL = WSQL || ' order by BDDATAHORA desc, BDSTATUS, BDCODARQ';

  for execute statement WSQL
  into :BDCODARQ, :BDCHAVEARQIND, :BDNOMARQJSON, :BDJSONVALUE, :BDCODEMP, :BDDATAHORA,
       :BDORIGEM, :BDSTATUS, :BDRETORNO, :wtipojson
  do
    begin
      BDSTATUSEXP = '';

      if (BDSTATUS = 0) then
         BDSTATUSEXP = 'Aguardando';
      else
      if (BDSTATUS = 1) then
         BDSTATUSEXP = 'Enviado';
      else
      if (BDSTATUS > 1) then
         BDSTATUSEXP = 'Erro Envio';

      BDTIPOJSON = '';

      if (wtipojson = 0) then
         BDTIPOJSON = 'Exportação geral';

      if (wtipojson = 1) then
         BDTIPOJSON = 'Exclusão';
      else
      if (wtipojson = 3) then
         BDTIPOJSON = 'Bloqueio/desbloqueio';
      else
      if (wtipojson = 4) then
         BDTIPOJSON = 'Importação completa';
      else
      if (wtipojson = 5) then
         BDTIPOJSON = 'Atualização';

      if (coalesce(BDCODEMP, 0) > 0 and wempatu <> BDCODEMP) then
         begin
           select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :pranomes order by BDREFEMP desc into :BDNOMEMP;
           wempatu = BDCODEMP;
         end
      else
      if (coalesce(BDCODEMP, 0) <= 0) then
         begin
           BDNOMEMP = '';
           wempatu = 0;
         end

      suspend;
    end
end^

create or alter procedure SP_RETORNA_BASE_FGTS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRCATEGORIAESOCIAL integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBFGTS numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDBFGTSRES numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDFGTS numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDFGTSRES numeric(18,6),
    BDAVPREV numeric(18,6),
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDTIPOFOLHA integer,
    BDBASEFGTS13RESC numeric(18,6),
    BDFGTS13RESC numeric(18,6))
as
declare variable WSQL varchar(500);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WDATARESC date;
declare variable WBASEFGTS numeric(18,6);
declare variable WBASEFGTS13 numeric(18,6);
declare variable WVALOR numeric(18,6);
declare variable WCLAVER varchar(30000);
declare variable WBINSSAPFN numeric(18,6);
declare variable WFGTSFN numeric(18,6);
declare variable WFGTS13FN numeric(18,6);
declare variable WBASEFGTSFN numeric(18,6);
declare variable WCALCULOS integer;
declare variable WCALCAFER integer;
declare variable WREFRESC integer;
declare variable WREFFER integer;
declare variable WANORESC integer;
declare variable WREFA13 integer;
declare variable WCOUNT integer;
declare variable WMOTIVORESCISAO integer;
declare variable WEXPORTAGRRF integer;
declare variable WREFFGTSDIGITAL integer;
declare variable WSQLVERBAS varchar(800);
begin

  wCount = 0;
  wsql = 'select RES.BDDATARESCISAO, RES.BDCODPRES, X.BDGRRFPRES '||
         '   from VRH_EMP_TRESCISAO RES '||
         '   left join VRH_BASE_TPREPRESC X on (X.BDCODPRES = RES.bdcodpres) '||
         '   where RES.BDCODEMP = '||:PRCODEMP||' and '||
         '   RES.BDCODCOL = '||:PRCODCOL||' and '||
         '   RES.BDREFRESCISAO = '||:PRREF||' and '||
         '   X.BDTIPOMOV <> 1';

  execute statement WSQL into :WDATARESC, :WMOTIVORESCISAO, :WEXPORTAGRRF;

    BDBFGTS = 0;
    BDFGTS = 0;
    BDBFGTS13 = 0;
    BDFGTS13 = 0;
    BDBFGTSRES = 0;
    BDFGTSRES = 0;
    BDBAVPREV = 0;
    BDAVPREV = 0;
    BDCALCULOS = 0;
    BDBASEFGTS13RESC = 0;
    bdfgts13resc     = 0;

  for select 0 BDTIPOFOLHA, FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFN BDREF, FN.BDBFGTSFN + FN.BDBFGTSFEFN BDBFGTS,
             FN.BDBFGTS13FN BDBFGTS13, FN.BDBINSSAPFN BDBINSS, FN.BDFGTSFN + FN.BDFGTSFEFN BDFGTS, FN.BDFGTS13FN BDFGTS13, FN.BDBFGTSFN BDBASEFGTSFOL, 1 as BDCALCULOS, 0 as BDCOUNTFC, 0 as BDCALCAFER
      from VRHF_EMP_TFOLHANORMAL FN           --FOLHA NORMAL
      where FN.BDCODEMP = :PRCODEMP and
            FN.BDREFFN = :PRREF and
            FN.BDCODCOL = :PRCODCOL
     union all
      select 1 BDTIPOFOLHA, FT.BDCODEMP, FT.BDCODCOL, FT.BDREFTOMADOR BDREF, FT.BDBFGTSFT + FT.BDBFGTSFEFT BDBFGTS,
             FT.BDBFGTS13FT BDBFGTS13, FT.BDBINSSAPFT BDBINSS, FT.BDFGTSFT + FT.BDFGTSFEFT BDFGTS, FT.BDFGTS13FT BDFGTS13, FT.BDBFGTSFT BDBASEFGTSFOL, 1 as BDCALCULOS, 0 as BDCOUNTFC, 0 as BDCALCAFER
      from VRHF_EMP_TFOLHATOMADOR FT         --FOLHA TOMADOR
      where FT.BDCODEMP = :PRCODEMP and
            FT.BDREFTOMADOR = :PRREF and
            FT.BDCODCOL = :PRCODCOL
     union all
      select -1 BDTIPOFOLHA, FA13.BDCODEMP, FA13.BDCODCOL, FA13.BDREFA13 BDREF, 0, FA13.BDBASEFGTSA13 BDBFGTS13, 0, 0, FA13.BDFGTSA13 BDFGTS13, 0,
             0 as BDCALCULOS, 0 as BDCOUNTFC, case when coalesce(FA13.BDCALCFERA13, 'FALSE') = 'TRUE' then 1 else 0 end BDCALCAFER
      from VRHF_EMP_TA13SAL FA13             --ADIANTAMENTO 13
      where FA13.BDCODEMP = :PRCODEMP and
            FA13.BDREFA13 = :PRREF AND
            FA13.BDCODCOL = :PRCODCOL
     union all
      select -1 BDTIPOFOLHA, C13.BDCODEMP, C13.BDCODCOL, C13.BDREF13 BDREF, 0, C13.BDBASEFGTSC13 BDBFGTS13, 0, 0, C13.BDFGTSC13 BDFGTS13, 0,
             1 as BDCALCULOS, 0 as BDCOUNTFC, 0 as BDCALCAFER
      from VRHF_EMP_TC13SAL C13              --COMPLEMENTO 13
      where C13.BDCODEMP = :PRCODEMP and
            c13.BDREF13 = :PRREF and
            C13.BDCODCOL = :PRCODCOL
     union all
      select -1 BDTIPOFOLHA, FC.BDCODEMP, FC.BDCODCOL, FC.BDREFFN BDREF, FC.BDBFGTSFC BDBFGTS, FC.BDBFGTS13FC BDBFGTS13, 0, FC.BDFGTSFC BDFGTS,
             FC.BDFGTS13FC BDFGTS13, 0, 1 as BDCALCULOS, 1 as BDCOUNTFC, 0 as BDCALCAFER
      from VRHF_EMP_TFOLHACOMP FC           --FOLHA COMPLEMENTAR
      left outer join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and FC.BDCODACCONV = AC.BDCODACCONV
      where FC.BDCODEMP = :PRCODEMP and
            FC.BDCODCOL = :PRCODCOL and
           ((FC.BDCODTIPOFC = 3 and AC.BDCODACCONV is not null and
           ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = :PRREF)) or (FC.BDCODTIPOFC <> 3 and FC.BDREFFN = :PRREF))

     union all
      select  -1 BDTIPOFOLHA, FC.BDCODEMP, FC.BDCODCOL, FC.BDREFCOMP BDREF, FC.BDBFGTSFC BDBFGTS, FC.BDBFGTS13FC BDBFGTS13, 0, FC.BDFGTSFC BDFGTS,
             FC.BDFGTS13FC BDFGTS13, 0, 1 as BDCALCULOS, 1 as BDCOUNTFC, 0 as BDCALCAFER
      from VRHF_EMP_TFOLTOMCOMP FC          --FOLHA TOMADOR COMPLEMENTAR
      left outer join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and FC.BDCODACCONV = AC.BDCODACCONV
      where FC.BDCODEMP = :PRCODEMP and FC.BDCODCOL = :PRCODCOL and
           ((FC.BDCODTIPOFC = 3 and AC.BDCODACCONV is not null and
           ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = :PRREF)) or (FC.BDCODTIPOFC <> 3 and FC.BDREFTOMADOR = :PRREF))
     union all
      select  -1 BDTIPOFOLHA, FAV.BDCODEMP, FAV.BDCODCOL, FAV.BDREF, FAV.BDBFGTSFA BDBFGTS, FAV.BDBFGTS13FA BDBFGTS13, 0, FAV.BDFGTSFA BDFGTS,
             FAV.BDFGTS13FA BDFGTS13, 0, 1 as BDCALCULOS, 0 as BDCOUNTFC, 0 as BDCALCAFER
      from VRHF_EMP_TFOLHAAVULSA FAV        --FOLHA AVULSA
      where FAV.BDCODEMP = :PRCODEMP and
            FAV.BDREF = :PRREF and
           FAV.BDCODCOL = :PRCODCOL
     union all
      select  3 BDTIPOFOLHA, FINT.BDCODEMP, FINT.BDCODCOL, FINT.BDREFFN BDREF, FINT.BDBFGTSFN BDBFGTS, FINT.BDBFGTS13FN BDBFGTS13, 0, FINT.BDFGTSFN + FINT.BDFGTSFEFN BDFGTS,
             FINT.BDFGTS13FN + FINT.BDBFGTSFEFN BDFGTS13, FINT.BDBFGTSFN, 1 as BDCALCULOS, 0 as BDCOUNTFC, 0 as BDCALCAFER
      from VRHF_EMP_TFOLHAINT FINT         --FOLHA INTERMITENTE
      where FINT.BDCODEMP = :PRCODEMP and
            FINT.BDREFFN = :PRREF and
            FINT.BDCODCOL = :PRCODCOL
     union all
      select  4 BDTIPOFOLHA, FMINT.BDCODEMP, FMINT.BDCODCOL, FMINT.BDREFTOMADOR BDREF, FMINT.BDBFGTSFT BDBFGTS, FMINT.BDBFGTS13FT BDBFGTS13, 0, FMINT.BDFGTSFT + FMINT.BDFGTSFEFT BDFGTS,
             FMINT.BDFGTS13FT + FMINT.BDBFGTSFEFT BDFGTS13, FMINT.BDBFGTSFT, 1 as BDCALCULOS, 0 as BDCOUNTFC, 0 as BDCALCAFER
      from VRHF_EMP_TFOLHATOMINT FMINT      --FOLHA TOMADOR INTERMITENTE
      where FMINT.BDCODEMP = :PRCODEMP and
            FMINT.BDREFTOMADOR = :PRREF and
            FMINT.BDCODCOL = :PRCODCOL

  into :BDTIPOFOLHA, :WCODEMP, :WCODCOL, :WREF, :WBASEFGTS, :WBASEFGTS13, :WBINSSAPFN, :WFGTSFN, :WFGTS13FN, :WBASEFGTSFN, :WCALCULOS, :BDCOUNTFC, :WCALCAFER
  do
    begin
      if (BDTIPOFOLHA = 3) then --Intermitente normal
         begin
           WSQLVERBAS = 'select FOL.BDVALVFN, VER.BDCLAVER '||
                        'from VRHF_EMP_TVERBAINT FOL '||
                        'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                        'join VRH_BASE_TVERBAS_REF VerRef on (VerRef.bdcodver = VER.BDCODVER)';

           WSQLVERBAS = WSQLVERBAS || 'where (FOL.BDCODEMP = '||:PRCODEMP||') and ';
           WSQLVERBAS = WSQLVERBAS || '(FOL.BDCODCOL in ('||:WCODCOL||')) and ';
           WSQLVERBAS = WSQLVERBAS || '(FOL.BDREFFN = '||:PRREF||') and ';
           WSQLVERBAS = WSQLVERBAS || '(VerRef.bdfgtsver <> 0) and ';
           WSQLVERBAS = WSQLVERBAS || '(VerRef.bdrefver = (Select Max(x.bdrefVer) from VRH_BASE_TVERBAS_REF X where X.bdcodver = VER.BDCODVER))';

         end
      else if (BDTIPOFOLHA = 0) then --Folha normal
         begin
           WSQLVERBAS = 'select FOL.BDVALVFN, VER.BDCLAVER '||
                        'from VRHF_EMP_TVERBAFN FOL '||
                        'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                        'join VRH_BASE_TVERBAS_REF VerRef on (VerRef.bdcodver = VER.BDCODVER)';

           WSQLVERBAS = WSQLVERBAS || 'where (FOL.BDCODEMP = '||:PRCODEMP||') and ';
           WSQLVERBAS = WSQLVERBAS || '(FOL.BDCODCOL in ('||:WCODCOL||')) and ';
           WSQLVERBAS = WSQLVERBAS || '(FOL.BDREFFN = '||:PRREF||') and ';
           WSQLVERBAS = WSQLVERBAS || '(VerRef.bdfgtsver <> 0) and ';
           WSQLVERBAS = WSQLVERBAS || '(VerRef.bdrefver = (Select Max(x.bdrefVer) from VRH_BASE_TVERBAS_REF X where X.bdcodver = VER.BDCODVER))';
         end
      else if (BDTIPOFOLHA = 4) then --Tomador intermitente
    begin
           WSQLVERBAS = 'select FOL.BDVALVFT, VER.BDCLAVER '||
                        'from VRHF_EMP_TVERBATOMINT FOL '||
                        'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                        'join VRH_BASE_TVERBAS_REF VerRef on (VerRef.bdcodver = VER.BDCODVER)';

           WSQLVERBAS = WSQLVERBAS || 'where (FOL.BDCODEMP = '||:PRCODEMP||') and ';
           WSQLVERBAS = WSQLVERBAS || '(FOL.BDCODCOL in ('||:WCODCOL||')) and ';
           WSQLVERBAS = WSQLVERBAS || '(FOL.BDREFTOMADOR = '||:PRREF||') and ';
           WSQLVERBAS = WSQLVERBAS || '(VerRef.bdfgtsver <> 0) and ';
           WSQLVERBAS = WSQLVERBAS || '(VerRef.bdrefver = (Select Max(x.bdrefVer) from VRH_BASE_TVERBAS_REF X where X.bdcodver = VER.BDCODVER))';
         end
      else  --Tomador
         begin
           WSQLVERBAS = 'select FOL.BDVALVFT, VER.BDCLAVER '||
                        'from VRHF_EMP_TVERBATOMADOR FOL '||
                        'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER) '||
                        'join VRH_BASE_TVERBAS_REF VerRef on (VerRef.bdcodver = VER.BDCODVER)';

           WSQLVERBAS = WSQLVERBAS || 'where (FOL.BDCODEMP = '||:PRCODEMP||') and ';
           WSQLVERBAS = WSQLVERBAS || '(FOL.BDCODCOL in ('||:WCODCOL||')) and ';
           WSQLVERBAS = WSQLVERBAS || '(FOL.BDREFTOMADOR = '||:PRREF||') and ';
           WSQLVERBAS = WSQLVERBAS || '(VerRef.bdfgtsver <> 0) and ';
           WSQLVERBAS = WSQLVERBAS || '(VerRef.bdrefver = (Select Max(x.bdrefVer) from VRH_BASE_TVERBAS_REF X where X.bdcodver = VER.BDCODVER))';
         end

      if ((BDCODCOL <> WCODCOL) and (BDCODCOL <> 0)) then
         begin
           suspend;
           BDBFGTS = 0;
           BDFGTS = 0;
           BDBFGTS13 = 0;
           BDFGTS13 = 0;
           BDBFGTSRES = 0;
           BDFGTSRES = 0;
           BDBAVPREV = 0;
           BDAVPREV = 0;
           BDBASEFGTS13RESC = 0;
           bdfgts13resc     = 0;
         end

      BDCODEMP = WCODEMP;
      BDCODCOL = WCODCOL;
      BDREF = WREF;
      if (WCALCULOS = 1) then BDCALCULOS = 1;

      --Valida se tem data de rescisão.
      if (WDATARESC is null) then
        begin
          BDBFGTS = BDBFGTS + WBASEFGTS;
          BDFGTS = BDFGTS + WFGTSFN;
          BDBFGTS13 = BDBFGTS13 + WBASEFGTS13;
          BDFGTS13 = BDFGTS13+ WFGTS13FN;

          if (BDTIPOFOLHA = 0) then
             begin
               for select FOL.BDVALVFN, VER.BDCLAVER
                   from VRHF_EMP_TVERBAFN FOL
                   join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER)
                   left outer join VRH_BASE_TVERBAS_REF REF on REF.BDCODVER = VER.BDCODVER and
                                                               REF.BDREFVER = (select max(BDREFVER)
                                                                               from VRH_BASE_TVERBAS_REF
                                                                               where BDCODVER = VER.BDCODVER and BDREFVER <= :PRREF)
                   where (FOL.BDCODEMP = :PRCODEMP) and
                            (FOL.BDCODCOL in (:WCODCOL)) and
                            (FOL.BDREFFN = :PRREF) and
                            (VER.BDCLAVER like '0.191%') and (REF.BDFGTSVER = 3)
                  into :WVALOR, :WCLAVER
                  do
                    begin
                     -- BDBFGTS = BDBFGTS - WVALOR;
                      BDBFGTS13 = BDBFGTS13 - wvalor;
                      select BDVALOR from TRUNCAR(:BDBFGTS * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :BDFGTS;
                    end
             end

          if (BDTIPOFOLHA = 1) then
             begin
               for select FOL.BDVALVFT, VER.BDCLAVER
                   from VRHF_EMP_TVERBATOMADOR FOL
                   join VRH_BASE_TVERBAS VER on (VER.BDCODVER = FOL.BDCODVER)
                   left outer join VRH_BASE_TVERBAS_REF REF on REF.BDCODVER = VER.BDCODVER and
                                                               REF.BDREFVER = (select max(BDREFVER)
                                                                               from VRH_BASE_TVERBAS_REF
                                                                               where BDCODVER = VER.BDCODVER and BDREFVER <= :PRREF)
                   where (FOL.BDCODEMP = :PRCODEMP) and
                         (FOL.BDCODCOL in (:WCODCOL)) and
                         (FOL.BDREFTOMADOR = :PRREF) and
                         (VER.BDCLAVER like '0.191%') and (REF.BDFGTSVER = 3)
                  into :WVALOR, :WCLAVER
                  do
                    begin
                      BDBFGTS = BDBFGTS - WVALOR;
                      BDBFGTS13 = BDBFGTS13 - WVALOR;
                      select BDVALOR from TRUNCAR(:BDBFGTS * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :BDFGTS;
                    end
             end

          if (WCALCAFER = 1) then               /*isso é pra não adicionar na base a verba de adiantamento de 13 quando pago nas ferias */
           begin
             select BDREFA13 from VRHF_EMP_TA13SAL where BDCODEMP = :PRCODEMP and BDCODCOL = :PRCODCOL and BDREFA13 = :PRREF
             into :WREFFER;
             if (:WREFFER is null) then
               BDBFGTS13 = BDBFGTS13 - WBASEFGTS13;
           end 

          select BDVALOR from TRUNCAR(:BDBFGTS13 * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
          BDFGTS13 = WVALOR;
          select BDVALOR from TRUNCAR(:BDBFGTSRES * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
          BDFGTSRES = WVALOR;
          select BDVALOR from TRUNCAR(:BDBAVPREV * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
          BDAVPREV = WVALOR;
       end
     else
       begin
         WREFRESC = extract(year from WDATARESC) * 100 + extract(month from WDATARESC);

         if ((BDTIPOFOLHA = 0) or (BDTIPOFOLHA = 3))  then                  /*FOLHA NORMAL*/
           begin

            if (WEXPORTAGRRF <= 0) then
              --Base FGTS Mensal
              BDBFGTS = BDBFGTS + :WBASEFGTSFN;
             else
              --Base FGTS Rescisório
               BDBFGTSRES = BDBFGTSRES + :WBASEFGTSFN;

             for execute statement WSQLVERBAS into :WVALOR, :WCLAVER do
               begin
                if ((((wmotivorescisao is null) or (wmotivorescisao = 0)) and (WEXPORTAGRRF <= 0)) or
                   (((wmotivorescisao > 0)) and (WEXPORTAGRRF <= 0))) then
                   begin
                      --Base 13º Mensal
                 if (WCLAVER like '7.050%') then
                   BDBFGTS13 = BDBFGTS13 + WVALOR;
                 else
                   if ((WCLAVER like '0.191%') and (WREFRESC <> :PRREF)) then
                     BDBFGTS13 = BDBFGTS13 + WVALOR;
                 else
                      if (((WCLAVER like '7.061.1.0%') or (WCLAVER like '7.070%') or (WCLAVER like '0.800.6.2%'))  and (WDATARESC is not null) and (WCALCAFER = 0)) then --Solicitação #200083 inclusão da classificação '7.070';
                      BDBFGTS13 = BDBFGTS13 + WVALOR;
                  else
                      if (((WCLAVER like '7.061.0.2%') or (WCLAVER like '7.061.0.1%') or (WCLAVER like '0.800.6.2%'))  and (WDATARESC is not null) and (WCALCAFER = 0)) then
      BDBFGTS13 = BDBFGTS13 - WVALOR;
   
                      --Quando o motivo de rescisão não exporta GRRF aviso prévio é somado a base de FGTS Mensal
                      --if (((WCLAVER like '7.001.3%') or (WCLAVER like '7.060%'))) then
                      --    BDBFGTS = BDBFGTS + WVALOR;
               end
                else if (WEXPORTAGRRF = 2) then
                   begin
                     if ((WCLAVER like '7.001.3%')) then
                        BDBFGTSRES = BDBFGTSRES - WVALOR;

                     --Base 13º Rescisório
                     if (WCLAVER like '7.050%') then
                        BDBASEFGTS13RESC = BDBASEFGTS13RESC + WVALOR;
                     else
                     if ((WCLAVER like '0.191%') and (WREFRESC <> :PRREF)) then
                         BDBASEFGTS13RESC = BDBASEFGTS13RESC + WVALOR;
                     else
                     if (((WCLAVER like '7.061.1.0%') or (WCLAVER like '7.070%') or (WCLAVER like '0.800.6.2%'))  and (WDATARESC is not null) and (WCALCAFER = 0)) then --Solicitação #200083 inclusão da classificação '7.070';
                         BDBASEFGTS13RESC = BDBASEFGTS13RESC + WVALOR;
                     else
                     if (((WCLAVER like '7.061.0.2%') or (WCLAVER like '7.061.0.1%') or (WCLAVER like '0.800.6.2%'))  and (WDATARESC is not null) and (WCALCAFER = 0)) then
                         BDBASEFGTS13RESC = BDBASEFGTS13RESC - WVALOR;

                     --Aviso prévio
                     if ((WCLAVER like '7.001.3%') or (WCLAVER like '7.060%')) then
                        BDBAVPREV = BDBAVPREV + WVALOR;
            end
                end
           end

         if ((BDTIPOFOLHA = 1) or (BDTIPOFOLHA = 4))  then                     /*FOLHA TOMADOR*/
           begin
             if (WEXPORTAGRRF <= 0) then
               --Base FGTS Mensal
               BDBFGTS = BDBFGTS + :WBASEFGTSFN;
             else
               --Base FGTS Rescisório
               BDBFGTSRES = BDBFGTSRES + :WBASEFGTSFN;

             if (wCount < 1) then
             begin
                for execute statement WSQLVERBAS into :WVALOR, :WCLAVER do
                begin
                     if ((((wmotivorescisao is null) or (wmotivorescisao = 0)) and (WEXPORTAGRRF <= 0)) or
                        (((wmotivorescisao > 0)) and (WEXPORTAGRRF <= 0))) then
                        begin
                           --Base 13º Mensal
                  if (WCLAVER like '7.050%') then
                    BDBFGTS13 = BDBFGTS13 + WVALOR;
                 else
                   if ((WCLAVER like '0.191%') and (WREFRESC <> :PRREF)) then
                     BDBFGTS13 = BDBFGTS13 + WVALOR;
                  else
                           if (((WCLAVER like '7.061.1.0%') or (WCLAVER like '7.070%') or (WCLAVER like '0.800.6.2%')) and (WDATARESC is not null) and (WCALCAFER = 0)) then --Solicitação #200083 inclusão da classificação '7.070';
                          BDBFGTS13 = BDBFGTS13 + WVALOR;
                      else
                           if (((WCLAVER like '7.061.0.2%') or (WCLAVER like '7.061.0.1%') or (WCLAVER like '0.800.6.2%'))  and (WDATARESC is not null) and (WCALCAFER = 0)) then
                          BDBFGTS13 = BDBFGTS13 - WVALOR;
  
                          --Quando o motivo de rescisão não exporta GRRF aviso prévio é somado a base de FGTS Mensal
                          --if (((WCLAVER like '7.001.3%') or (WCLAVER like '7.060%'))) then
                          --    BDBFGTS = BDBFGTS + WVALOR;
                end
                     else if (WEXPORTAGRRF = 2) then
                        begin
                           if ((WCLAVER like '7.001.3%')) then
                              BDBFGTSRES = BDBFGTSRES - WVALOR;

                           --Base 13º Rescisório
                           if (WCLAVER like '7.050%') then
                              BDBASEFGTS13RESC = BDBASEFGTS13RESC + WVALOR;
                           else
                           if ((WCLAVER like '0.191%') and (WREFRESC <> :PRREF)) then
                               BDBASEFGTS13RESC = BDBASEFGTS13RESC + WVALOR;
                           else
                           if (((WCLAVER like '7.061.1.0%') or (WCLAVER like '7.070%') or (WCLAVER like '0.800.6.2%')) and (WDATARESC is not null) and (WCALCAFER = 0)) then --Solicitação #200083 inclusão da classificação '7.070';
                               BDBASEFGTS13RESC = BDBASEFGTS13RESC + WVALOR;
                           else
                           if (((WCLAVER like '7.061.0.2%') or (WCLAVER like '7.061.0.1%') or (WCLAVER like '0.800.6.2%'))  and (WDATARESC is not null) and (WCALCAFER = 0)) then
                               BDBASEFGTS13RESC = BDBASEFGTS13RESC - WVALOR;
  
                           --Aviso prévio
                           if ((WCLAVER like '7.001.3%') or (WCLAVER like '7.060%')) then
                              BDBAVPREV  = BDBAVPREV + WVALOR;
             end
           end
               end
           end

           if (BDTIPOFOLHA = -1) then -- OUTRAS FOLHAS
           begin
                if (wrefresc <= 0) then
           begin
             BDBFGTS = BDBFGTS + WBASEFGTS;
                    BDBFGTS13 = BDBFGTS13 + WBASEFGTS13;
               end
                else
                  begin
                     BDBFGTSRES       = BDBFGTSRES       + WBASEFGTS;
                     BDBASEFGTS13RESC = BDBASEFGTS13RESC + WBASEFGTS13;
                   end
  
             if (WCALCAFER = 1) then               /*isso é pra não adicionar na base a verba de adiantamento de 13 quando pago nas ferias */
               BDBFGTS13 = BDBFGTS13 - WBASEFGTS13;
           end

         --Valor 13º Mensal e Rescisório
         select BDVALOR from TRUNCAR(:BDBFGTS13 * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
         BDFGTS13 = WVALOR;
         select BDVALOR from TRUNCAR(:BDBASEFGTS13RESC * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
         bdfgts13resc = WVALOR;

         --Valor FGTS Mensal e Rescisório
         select BDVALOR from TRUNCAR(:BDBFGTS * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
         BDFGTS = WVALOR;
         select BDVALOR from TRUNCAR(:BDBFGTSRES * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
         BDFGTSRES = WVALOR;

         --Valor de aviso prévio
         select BDVALOR from TRUNCAR(:BDBAVPREV * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
         BDAVPREV = WVALOR;
       end
  end
  suspend;
end^

create or alter procedure SP_RETORNA_BASE_FGTS_2 (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRCATEGORIAESOCIAL integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBFGTS numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDBFGTSRES numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDFGTS numeric(18,6),
    BDFGTS13 numeric(18,6),
    BDFGTSRES numeric(18,6),
    BDAVPREV numeric(18,6),
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDTIPOFOLHA integer,
    BDBASEFGTS13RESC numeric(18,6),
    BDFGTS13RESC numeric(18,6),
    BDECONSIGNADO numeric(18,6),
    BDECONSIGNADORESC numeric(18,6))
as
declare variable WSQL varchar(30000);
declare variable WDATARESC date;
declare variable WMOTIVORESCISAO integer;
declare variable WEXPORTAGRRF integer;
declare variable WDATAPGTORESC date;
declare variable WBFGTS numeric(15,2);
declare variable WBFGTSRESC numeric(15,2);
declare variable WBFGTS13 numeric(15,2);
declare variable WBFGTS13RESC numeric(15,2);
declare variable WBAVISO numeric(15,2);
declare variable WVALOR numeric(15,2);
declare variable WBDCODEMP integer;
declare variable WBDCODCOL integer;
declare variable WBDREF integer;
declare variable WBDLOTACAO varchar(50);
declare variable WBDBFGTS numeric(18,6);
declare variable WBDBFGTS13 numeric(18,6);
declare variable WBDBFGTSRES numeric(18,6);
declare variable WBDBAVPREV numeric(18,6);
declare variable WBDBASEFGTS13RESC numeric(18,6);
declare variable WTOTBDBFGTS numeric(18,6);
declare variable WTOTBDBFGTS13 numeric(18,6);
declare variable WTOTBDBFGTSRES numeric(18,6);
declare variable WTOTBDBAVPREV numeric(18,6);
declare variable WTOTBDBASEFGTS13RESC numeric(18,6);
declare variable WLOTANT varchar(50);
begin

  wsql = ' select bdcodemp, bdcodcol, bdref, bdlotacao, bdbfgts, bdbfgts13, bdbfgtsres, bdbavprev, bdbasefgts13resc, BDECONSIGNADO, BDECONSIGNADORESC '||
         ' from SP_SEPARARBASEFGTS_LOTACAO_5003('||:prcodemp||','||:prcodcol||','||:prref||') WHERE BDCALCULOS > 0 order by bdlotacao';


  BDFGTS13 = 0;
  bdfgts13resc = 0;
  BDFGTS = 0;
  BDFGTSRES = 0;
  BDAVPREV = 0;
  BDBFGTS = 0;
  BDBFGTS13 = 0;
  BDBFGTSRES = 0;
  BDBASEFGTS13RESC = 0;
  BDBAVPREV = 0;
  BDCALCULOS = 0;
  BDECONSIGNADO = 0;
  BDECONSIGNADORESC = 0;

  WTOTBDBFGTS = 0;
  WTOTBDBFGTS13 = 0;
  WTOTBDBFGTSRES = 0;
  WTOTBDBAVPREV = 0;
  WTOTBDBASEFGTS13RESC = 0;
  WLOTANT = '-1';

  for execute statement wsql into :BDCODEMP, :BDCODCOL, :BDREF, :WBDLOTACAO, :WBDBFGTS, :WBDBFGTS13, :WBDBFGTSRES, :WBDBAVPREV, :WBDBASEFGTS13RESC, :BDECONSIGNADO, :BDECONSIGNADORESC do
    begin
      BDCALCULOS = 1;
      if ((WLOTANT <> '-1') and (WLOTANT <> wbdlotacao)) then
         begin
           if (WTOTBDBFGTS < 0) then
              WTOTBDBFGTS = 0;

           if (WTOTBDBFGTS13 < 0) then
              WTOTBDBFGTS13 = 0;

           if (WTOTBDBFGTSRES < 0) then
              WTOTBDBFGTSRES = 0;

           if (WTOTBDBAVPREV < 0) then
              WTOTBDBAVPREV = 0;

           if (WTOTBDBASEFGTS13RESC < 0) then
              WTOTBDBASEFGTS13RESC = 0;

           if (BDBFGTS < 0) then
               BDBFGTS = 0;

           if (BDBFGTS13 < 0) then
               BDBFGTS13 = 0;

           if (BDBFGTSRES < 0) then
               BDBFGTSRES = 0;
               
           if (BDBASEFGTS13RESC < 0) then
              BDBASEFGTS13RESC = 0;
               
           if (BDBAVPREV < 0) then
              BDBAVPREV = 0;

           select BDVALOR from TRUNCAR(:WTOTBDBFGTS13 * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
           BDFGTS13 = BDFGTS13 + coalesce(WVALOR,0);
           select BDVALOR from TRUNCAR(:WTOTBDBASEFGTS13RESC * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
           bdfgts13resc = bdfgts13resc + coalesce(WVALOR,0);
         
           --Valor FGTS Mensal e Rescisório
           select BDVALOR from TRUNCAR(:WTOTBDBFGTS * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
           BDFGTS = BDFGTS + coalesce(WVALOR,0);
           select BDVALOR from TRUNCAR(:WTOTBDBFGTSRES * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
           BDFGTSRES = BDFGTSRES + coalesce(WVALOR,0);
         
           --Valor de aviso prévio
           select BDVALOR from TRUNCAR(:WTOTBDBAVPREV * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
           BDAVPREV = BDAVPREV + coalesce(WVALOR,0);

           WTOTBDBFGTS = 0;
           WTOTBDBFGTS13 = 0;
           WTOTBDBFGTSRES = 0;
           WTOTBDBAVPREV = 0;
           WTOTBDBASEFGTS13RESC = 0;
         end

     WLOTANT = wbdlotacao;

     WTOTBDBFGTS = WTOTBDBFGTS + WBDBFGTS;
     WTOTBDBFGTS13 = WTOTBDBFGTS13 + WBDBFGTS13;
     WTOTBDBFGTSRES = WTOTBDBFGTSRES + WBDBFGTSRES;
     WTOTBDBASEFGTS13RESC = WTOTBDBASEFGTS13RESC + WBDBASEFGTS13RESC;
     WTOTBDBAVPREV = WTOTBDBAVPREV + WBDBAVPREV;

     BDBFGTS = BDBFGTS + WBDBFGTS;
     BDBFGTS13 = BDBFGTS13 + WBDBFGTS13;
     BDBFGTSRES = BDBFGTSRES + WBDBFGTSRES;
     BDBASEFGTS13RESC = BDBASEFGTS13RESC + WBDBASEFGTS13RESC;
     BDBAVPREV = BDBAVPREV + WBDBAVPREV;
    end

  -- Calcular os valores de FGTS
  if (WTOTBDBFGTS < 0) then
     WTOTBDBFGTS = 0;

  if (WTOTBDBFGTS13 < 0) then
     WTOTBDBFGTS13 = 0;

  if (WTOTBDBFGTSRES < 0) then
     WTOTBDBFGTSRES = 0;

  if (WTOTBDBAVPREV < 0) then
     WTOTBDBAVPREV = 0;

  if (WTOTBDBASEFGTS13RESC < 0) then
     WTOTBDBASEFGTS13RESC = 0;

  if (BDBFGTS < 0) then
      BDBFGTS = 0;

  if (BDBFGTS13 < 0) then
      BDBFGTS13 = 0;

  if (BDBFGTSRES < 0) then
      BDBFGTSRES = 0;
      
  if (BDBASEFGTS13RESC < 0) then
     BDBASEFGTS13RESC = 0;
      
  if (BDBAVPREV < 0) then
     BDBAVPREV = 0;

  --Valor 13º Mensal e Rescisório
  select BDVALOR from TRUNCAR(:WTOTBDBFGTS13 * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
  BDFGTS13 = BDFGTS13 + coalesce(WVALOR,0);
  select BDVALOR from TRUNCAR(:WTOTBDBASEFGTS13RESC * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
  bdfgts13resc = bdfgts13resc + coalesce(WVALOR,0);

  --Valor FGTS Mensal e Rescisório
  select BDVALOR from TRUNCAR(:WTOTBDBFGTS * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
  BDFGTS = BDFGTS + coalesce(WVALOR,0);
  select BDVALOR from TRUNCAR(:WTOTBDBFGTSRES * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
  BDFGTSRES = BDFGTSRES + coalesce(WVALOR,0);

  --Valor de aviso prévio
  select BDVALOR from TRUNCAR(:WTOTBDBAVPREV * iif(:prcategoriaesocial = 103, 0.02, 0.08), 2) into :WVALOR;
  BDAVPREV = BDAVPREV + coalesce(WVALOR,0);

  suspend;
end^

create or alter procedure SP_SEPARARBASEFGTS_LOTACAO_5003 (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDLOTACAO varchar(50),
    BDBFGTS numeric(18,6),
    BDBFGTS13 numeric(18,6),
    BDBFGTSRES numeric(18,6),
    BDBAVPREV numeric(18,6),
    BDBASEFGTS13RESC numeric(18,6),
    BDCALCULOS integer,
    BDECONSIGNADO numeric(18,6),
    BDECONSIGNADORESC numeric(18,6))
as
declare variable WSQL varchar(30000);
declare variable WDATARESC date;
declare variable WMOTIVORESCISAO integer;
declare variable WEXPORTAGRRF integer;
declare variable WDATAPGTORESC date;
declare variable WBFGTS numeric(15,2);
declare variable WBFGTSRESC numeric(15,2);
declare variable WBFGTS13 numeric(15,2);
declare variable WBFGTS13RESC numeric(15,2);
declare variable WBAVISO numeric(15,2);
declare variable WVALOR numeric(15,2);
declare variable WDATAPGTORESCSTR varchar(50);
declare variable WMOTIVORESCISAOSTR varchar(50);
declare variable WEXPORTAGRRFSTR varchar(50);
begin
  /* Procedure Text */

  bdcodemp = prcodemp;
  bdcodcol = prcodcol;
  bdref = prref;

  BDBFGTS = 0;
  BDBFGTS13 = 0;
  BDBFGTSRES = 0;
  BDBAVPREV = 0;
  BDBASEFGTS13RESC = 0;
  BDECONSIGNADO = 0;
  BDECONSIGNADORESC = 0;


  wsql = 'select RES.BDDATARESCISAO, RES.BDCODPRES, X.BDGRRFPRES, BDDATAPAGRESCISAO '||
         '   from VRH_EMP_TRESCISAO RES '||
         '   left join VRH_BASE_TPREPRESC X on (X.BDCODPRES = RES.bdcodpres) '||
         '   where RES.BDCODEMP = '||:PRCODEMP||' and '||
         '   RES.BDCODCOL = '||:PRCODCOL||' and '||
         '   RES.BDREFRESCISAO = '||:PRREF||' and '||
         '   X.BDTIPOMOV <> 1';

  execute statement WSQL into :WDATARESC, :WMOTIVORESCISAO, :WEXPORTAGRRF, :WDATAPGTORESC;

  if (WDATAPGTORESC is not null) then
     wdatapgtorescstr = ''''||:wdatapgtoresc||'''';
  else
     wdatapgtorescstr = 'null';

  if (WMOTIVORESCISAO is not null) then
     WMOTIVORESCISAOstr = wmotivorescisao;
  else
     WMOTIVORESCISAOstr = 'null';

  if (WEXPORTAGRRF is not null) then
     WEXPORTAGRRFstr = WEXPORTAGRRF;
  else
     WEXPORTAGRRFstr = 'null';


  -- Folha normal
  wsql = 'select /*CAMPOSVERBAS*/, null bddatapgto ,CALC.BDVALVFN '||
                ', case '||
                ' when coalesce(EMPLOT.BDCODLOTACAO, null) is not null and coalesce(EMPLOT.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then EMPLOT.BDCODLOTACAO '||
                ' else MAT.BDCODLOTACAO '||
                ' end BDCODLOTACAO, -1 BDCODTIPOFC, -1 BDTIPOEVT_COMP '||
               ' from VRHF_EMP_TVERBAFN CALC  '||
                ' left outer join TEMPRESAS EMPLOT on (CALC.BDCODEMP = EMPLOT.BDCODEMP)'||
                ' left outer join TEMPRESAS MAT on MAT.BDCODEMP = coalesce(EMPLOT.BDCODMATRIZ, EMPLOT.BDCODEMP) '||
                ' /*JOINVERBAS*/ '||
                ' where (CALC.BDCODEMP = '||:PRCODEMP||') and '||
                ' (CALC.BDCODCOL in ('||:prcodcol||')) and '||
                ' (CALC.BDREFFN = '||:PRREF||') '||
                ' /*WHEREVERBAS*/';

  wsql = ' select bdbasefgts, bdbfgtsres, bdbfgts13, bdbasefgts13resc, bdbavprev, BDLOTACAO,BDCALCULOS, BDECONSIGNADO, BDECONSIGNADORESC '||
         ' from SP_VRH_SEPARABASES_FGTS_5003('''||:wsql||''','||:wdatapgtorescstr||','||:wmotivorescisaostr||','||:wexportagrrfstr||')';
  for execute statement wsql into :bdbfgts, :bdbfgtsres, :bdbfgts13, :bdbasefgts13resc, :bdbavprev, :BDLOTACAO, :BDCALCULOS, :BDECONSIGNADO, :BDECONSIGNADORESC do
    suspend;

  -- Folha por tomador
  wsql = 'select /*CAMPOSVERBAS*/, null bddatapgto ,CALC.BDVALVFT '||
                ', case '||
                ' when TPCC.BDCODLOT > 0 and coalesce(TPCC.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then TPCC.BDCODLOTACAO '||
                ' when coalesce(EMPLOT.BDCODLOTACAO, null) is not null and coalesce(EMPLOT.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then EMPLOT.BDCODLOTACAO '||
                ' else MAT.BDCODLOTACAO '||
                ' end BDCODLOTACAO, -1 BDCODTIPOFC, -1 BDTIPOEVT_COMP  '||
                ' from vrhf_emp_tverbatomador CALC /*JOINVERBAS*/ '||
                ' left outer join VRHF_EMP_TPREPFN PFN on PFN.BDCODEMP = CALC.BDCODEMP and PFN.BDCODCOL = CALC.BDCODCOL and PFN.BDORDEM = CALC.BDORDEM '||
                ' left outer join VRHF_SP_TOMADOR(PFN.BDCODTPCC, PFN.BDCODCENTRO) TPCC on TPCC.BDCODCENTRO = PFN.BDCODCENTRO and TPCC.bdcodcencus = PFN.BDCODTPCC '||

                ' left outer join TEMPRESAS EMPLOT on (CALC.BDCODEMP = EMPLOT.BDCODEMP)'||
                ' left outer join TEMPRESAS MAT on MAT.BDCODEMP = coalesce(EMPLOT.BDCODMATRIZ, EMPLOT.BDCODEMP) '||

                ' where (CALC.BDCODEMP = '||:PRCODEMP||') and '||
                ' (CALC.BDCODCOL in ('||:prcodcol||')) and '||
                ' (CALC.BDREFTOMADOR = '||:PRREF||') '||
                ' /*WHEREVERBAS*/';

  wsql = ' select bdbasefgts, bdbfgtsres, bdbfgts13, bdbasefgts13resc, bdbavprev, BDLOTACAO,BDCALCULOS, BDECONSIGNADO, BDECONSIGNADORESC '||
         ' from SP_VRH_SEPARABASES_FGTS_5003('''||:wsql||''','||:wdatapgtorescstr||','||:wmotivorescisaostr||','||:wexportagrrfstr||')';
  for execute statement wsql into :bdbfgts, :bdbfgtsres, :bdbfgts13, :bdbasefgts13resc, :bdbavprev, :BDLOTACAO, :BDCALCULOS, :BDECONSIGNADO, :BDECONSIGNADORESC do
    suspend;

  -- Adiantamento de 13º
  wsql = 'select /*CAMPOSVERBAS*/, null bddatapgto ,CALC.bdvalva13 '||
                ', case '||
                ' when TPCC.BDCODLOT > 0 and coalesce(TPCC.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then TPCC.BDCODLOTACAO '||
                ' when coalesce(EMPLOT.BDCODLOTACAO, null) is not null and coalesce(EMPLOT.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then EMPLOT.BDCODLOTACAO '||
                ' else MAT.BDCODLOTACAO '||
                ' end BDCODLOTACAO, -1 BDCODTIPOFC, -1 BDTIPOEVT_COMP  '||
                ' from VRHF_EMP_TVERBAA13 CALC /*JOINVERBAS*/ '||
                ' left outer join VRHF_EMP_TA13SAL AD13 on (CALC.bdcodemp = AD13.BDCODEMP AND CALC.BDCODCOL = AD13.BDCODCOL AND CALC.BDREFA13 = AD13.BDREFA13) '||
                ' left outer join VRHF_EMP_TPREPFN PFN on PFN.BDCODEMP = AD13.BDCODEMP and PFN.BDCODCOL = AD13.BDCODCOL and PFN.BDORDEM = AD13.BDORDEM '||
                ' left outer join VRHF_SP_TOMADOR(PFN.BDCODTPCC, PFN.BDCODCENTRO) TPCC on TPCC.BDCODCENTRO = PFN.BDCODCENTRO and TPCC.bdcodcencus = PFN.BDCODTPCC '||

                ' left outer join TEMPRESAS EMPLOT on (CALC.BDCODEMP = EMPLOT.BDCODEMP)'||
                ' left outer join TEMPRESAS MAT on MAT.BDCODEMP = coalesce(EMPLOT.BDCODMATRIZ, EMPLOT.BDCODEMP) '||

                ' where (CALC.BDCODEMP = '||:PRCODEMP||') and '||
                ' (CALC.BDCODCOL in ('||:prcodcol||')) and '||
                ' (CALC.bdrefa13 = '||:PRREF||') '||
                ' /*WHEREVERBAS*/';

  wsql = ' select bdbasefgts, bdbfgtsres, bdbfgts13, bdbasefgts13resc, bdbavprev, BDLOTACAO,BDCALCULOS, BDECONSIGNADO, BDECONSIGNADORESC  '||
         ' from SP_VRH_SEPARABASES_FGTS_5003('''||:wsql||''','||:wdatapgtorescstr||','||:wmotivorescisaostr||','||:wexportagrrfstr||')';
  for execute statement wsql into :bdbfgts, :bdbfgtsres, :bdbfgts13, :bdbasefgts13resc, :bdbavprev, :BDLOTACAO, :BDCALCULOS, :BDECONSIGNADO, :BDECONSIGNADORESC do
    suspend;

  -- Complemento de 13º SAlário
  wsql = 'select /*CAMPOSVERBAS*/, null bddatapgto ,CALC.BDVALVC13 '||
                ', case '||
                ' when TPCC.BDCODLOT > 0 and coalesce(TPCC.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then TPCC.BDCODLOTACAO '||
                ' when coalesce(EMPLOT.BDCODLOTACAO, null) is not null and coalesce(EMPLOT.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then EMPLOT.BDCODLOTACAO '||
                ' else MAT.BDCODLOTACAO '||
                ' end BDCODLOTACAO, -1 BDCODTIPOFC, -1 BDTIPOEVT_COMP  '||
                ' from VRHF_EMP_TVERBAC13 CALC /*JOINVERBAS*/ '||
                ' left outer join VRHF_EMP_TC13SAL C13 ON (CALC.BDCODEMP = C13.BDCODEMP AND CALC.BDCODCOL = C13.BDCODCOL AND CALC.bdref13 = C13.BDREF13 AND CALC.bdrefc13 = C13.BDREFC13)'||
                ' left outer join VRHF_EMP_TPREPFN PFN on PFN.BDCODEMP = C13.BDCODEMP and PFN.BDCODCOL = C13.BDCODCOL and PFN.BDORDEM = C13.BDORDEM '||
                ' left outer join VRHF_SP_TOMADOR(PFN.BDCODTPCC, PFN.BDCODCENTRO) TPCC on TPCC.BDCODCENTRO = PFN.BDCODCENTRO and TPCC.bdcodcencus = PFN.BDCODTPCC '||

                ' left outer join TEMPRESAS EMPLOT on (CALC.BDCODEMP = EMPLOT.BDCODEMP)'||
                ' left outer join TEMPRESAS MAT on MAT.BDCODEMP = coalesce(EMPLOT.BDCODMATRIZ, EMPLOT.BDCODEMP) '||

                ' where (CALC.BDCODEMP = '||:PRCODEMP||') and '||
                ' (CALC.BDCODCOL in ('||:prcodcol||')) and '||
                ' (CALC.BDREFC13 = '||:PRREF||') '||
                ' /*WHEREVERBAS*/';

  wsql = ' select bdbasefgts, bdbfgtsres, bdbfgts13, bdbasefgts13resc, bdbavprev, BDLOTACAO,BDCALCULOS, BDECONSIGNADO, BDECONSIGNADORESC  '||
         ' from SP_VRH_SEPARABASES_FGTS_5003('''||:wsql||''','||:wdatapgtorescstr||','||:wmotivorescisaostr||','||:wexportagrrfstr||')';
  for execute statement wsql into :bdbfgts, :bdbfgtsres, :bdbfgts13, :bdbasefgts13resc, :bdbavprev, :BDLOTACAO, :BDCALCULOS, :BDECONSIGNADO, :BDECONSIGNADORESC do
    suspend;

  -- Folha Complementar
  wsql = 'select /*CAMPOSVERBAS*/, case when FC.BDCODTIPOFC = 3 then AC.BDDTPGTOBRICONV else null end bddatapgto ,CALC.BDVALVFC '||
                ', case '||
                ' when coalesce(EMPLOT.BDCODLOTACAO, null) is not null and coalesce(EMPLOT.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then EMPLOT.BDCODLOTACAO '||
                ' else MAT.BDCODLOTACAO '||
                ' end BDCODLOTACAO, FC.BDCODTIPOFC, FC.BDTIPOEVT BDTIPOEVT_COMP  '||
               ' from VRHF_EMP_TVERBAFC CALC '||
               ' join VRHF_EMP_TFOLHACOMP FC on (CALC.BDCODEMP = FC.BDCODEMP and FC.BDCODCOL = CALC.BDCODCOL and FC.BDREFFN = CALC.BDREFFN and FC.BDREFFC = CALC.BDREFFC )'||
               ' left outer join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and FC.BDCODACCONV = AC.BDCODACCONV '||
                ' left outer join TEMPRESAS EMPLOT on (CALC.BDCODEMP = EMPLOT.BDCODEMP)'||
                ' left outer join TEMPRESAS MAT on MAT.BDCODEMP = coalesce(EMPLOT.BDCODMATRIZ, EMPLOT.BDCODEMP) '||

               ' /*JOINVERBAS*/ '||
               ' where (CALC.BDCODEMP = '||:PRCODEMP||') and '||
               ' (CALC.BDCODCOL in ('||:prcodcol||')) and '||
               ' ((FC.BDCODTIPOFC = 3 and AC.BDCODACCONV is not null and '||
               ' ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = '||:PRREF||
               ')) or (FC.BDCODTIPOFC <> 3 and FC.BDREFFN = '||:PRREF||'))'||
               ' /*WHEREVERBAS*/';

  wsql = ' select bdbasefgts, bdbfgtsres, bdbfgts13, bdbasefgts13resc, bdbavprev, BDLOTACAO,BDCALCULOS, BDECONSIGNADO, BDECONSIGNADORESC  '||
         ' from SP_VRH_SEPARABASES_FGTS_5003('''||:wsql||''','||:wdatapgtorescstr||','||:wmotivorescisaostr||','||:wexportagrrfstr||')';
  for execute statement wsql into :bdbfgts, :bdbfgtsres, :bdbfgts13, :bdbasefgts13resc, :bdbavprev, :BDLOTACAO, :BDCALCULOS, :BDECONSIGNADO, :BDECONSIGNADORESC do
    suspend;

   -- Folha Complementar por tomador
  wsql = 'select /*CAMPOSVERBAS*/, case when FC.BDCODTIPOFC = 3 then AC.BDDTPGTOBRICONV else null end bddatapgto ,CALC.BDVALVFC '||
                ', case '||
                ' when TPCC.BDCODLOT > 0 and coalesce(TPCC.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then TPCC.BDCODLOTACAO '||
                ' when coalesce(EMPLOT.BDCODLOTACAO, null) is not null and coalesce(EMPLOT.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then EMPLOT.BDCODLOTACAO '||
                ' else MAT.BDCODLOTACAO '||
                ' end BDCODLOTACAO, FC.BDCODTIPOFC, FC.BDTIPOEVT BDTIPOEVT_COMP  '||
               ' from VRHF_EMP_TVERBAFCTOMADOR CALC '||
               ' join VRHF_EMP_TFOLTOMCOMP FC on (CALC.BDCODEMP = FC.BDCODEMP and FC.BDCODCOL = CALC.BDCODCOL and FC.BDORDEM = CALC.BDORDEM and FC.BDREFTOMADOR = CALC.BDREFTOMADOR and FC.BDREFFC = CALC.BDREFFC )'||
               ' left outer join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and FC.BDCODACCONV = AC.BDCODACCONV '||

                ' left outer join VRHF_EMP_TPREPFN PFN on PFN.BDCODEMP = FC.BDCODEMP and PFN.BDCODCOL = FC.BDCODCOL and PFN.BDORDEM = FC.BDORDEM '||
                ' left outer join VRHF_SP_TOMADOR(PFN.BDCODTPCC, PFN.BDCODCENTRO) TPCC on TPCC.BDCODCENTRO = PFN.BDCODCENTRO and TPCC.bdcodcencus = PFN.BDCODTPCC '||

                ' left outer join TEMPRESAS EMPLOT on (CALC.BDCODEMP = EMPLOT.BDCODEMP)'||
                ' left outer join TEMPRESAS MAT on MAT.BDCODEMP = coalesce(EMPLOT.BDCODMATRIZ, EMPLOT.BDCODEMP) '||

               ' /*JOINVERBAS*/ '||
               ' where (CALC.BDCODEMP = '||:PRCODEMP||') and '||
               ' (CALC.BDCODCOL in ('||:prcodcol||')) and '||
               ' ((FC.BDCODTIPOFC = 3 and AC.BDCODACCONV is not null and '||
               ' ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = '||:PRREF||
               ')) or (FC.BDCODTIPOFC <> 3 and FC.BDREFTOMADOR = '||:PRREF||'))'||
               ' /*WHEREVERBAS*/';

  wsql = ' select bdbasefgts, bdbfgtsres, bdbfgts13, bdbasefgts13resc, bdbavprev, BDLOTACAO,BDCALCULOS, BDECONSIGNADO, BDECONSIGNADORESC  '||
         ' from SP_VRH_SEPARABASES_FGTS_5003('''||:wsql||''','||:wdatapgtorescstr||','||:wmotivorescisaostr||','||:wexportagrrfstr||')';
  for execute statement wsql into :bdbfgts, :bdbfgtsres, :bdbfgts13, :bdbasefgts13resc, :bdbavprev, :BDLOTACAO, :BDCALCULOS, :BDECONSIGNADO, :BDECONSIGNADORESC do
    suspend;

  -- Folha Avulsa
  wsql = 'select /*CAMPOSVERBAS*/, CALC.BDDATAFA bddatapgto ,CALC.BDVALVFA '||
                ', case '||
                ' when TPCC.BDCODLOT > 0 and coalesce(TPCC.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then TPCC.BDCODLOTACAO '||
                ' when coalesce(EMPLOT.BDCODLOTACAO, null) is not null and coalesce(EMPLOT.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then EMPLOT.BDCODLOTACAO '||
                ' else MAT.BDCODLOTACAO '||
                ' end BDCODLOTACAO, -1 BDCODTIPOFC, -1 BDTIPOEVT_COMP  '||
               ' from VRHF_EMP_TVERBAFA CALC '||
               ' join VRHF_EMP_TFOLHAAVULSA FAV on (CALC.BDCODEMP = FAV.BDCODEMP AND CALC.BDCODCOL = FAV.BDCODCOL AND CALC.BDCODTCA = FAV.BDCODTCA AND CALC.BDDATAFA = FAV.BDDATAFA)'||
                ' left outer join VRHF_EMP_TPREPFN PFN on PFN.BDCODEMP = FAV.BDCODEMP and PFN.BDCODCOL = FAV.BDCODCOL and PFN.BDORDEM = FAV.BDORDEM '||
                ' left outer join VRHF_SP_TOMADOR(PFN.BDCODTPCC, PFN.BDCODCENTRO) TPCC on TPCC.BDCODCENTRO = PFN.BDCODCENTRO and TPCC.bdcodcencus = PFN.BDCODTPCC '||

                ' left outer join TEMPRESAS EMPLOT on (CALC.BDCODEMP = EMPLOT.BDCODEMP)'||
                ' left outer join TEMPRESAS MAT on MAT.BDCODEMP = coalesce(EMPLOT.BDCODMATRIZ, EMPLOT.BDCODEMP) '||

               ' /*JOINVERBAS*/ '||
               ' where (FAV.BDCODEMP = '||:PRCODEMP||') and '||
               ' (FAV.BDCODCOL in ('||:prcodcol||')) and '||
               ' ( FAV.BDREF = '||:PRREF||') '||
               ' /*WHEREVERBAS*/';

  wsql = ' select bdbasefgts, bdbfgtsres, bdbfgts13, bdbasefgts13resc, bdbavprev, BDLOTACAO,BDCALCULOS, BDECONSIGNADO, BDECONSIGNADORESC  '||
         ' from SP_VRH_SEPARABASES_FGTS_5003('''||:wsql||''','||:wdatapgtorescstr||','||:wmotivorescisaostr||','||:wexportagrrfstr||')';
  for execute statement wsql into :bdbfgts, :bdbfgtsres, :bdbfgts13, :bdbasefgts13resc, :bdbavprev, :BDLOTACAO, :BDCALCULOS, :BDECONSIGNADO, :BDECONSIGNADORESC do
    suspend;

  -- Folha intermitente
  wsql = 'select /*CAMPOSVERBAS*/, NULL bddatapgto ,CALC.BDVALVFN '||
                ', case '||
                ' when coalesce(EMPLOT.BDCODLOTACAO, null) is not null and coalesce(EMPLOT.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then EMPLOT.BDCODLOTACAO '||
                ' else MAT.BDCODLOTACAO '||
                ' end BDCODLOTACAO, -1 BDCODTIPOFC, -1 BDTIPOEVT_COMP  '||
               ' from VRHF_EMP_TVERBAINT CALC '||
               ' join VRHF_EMP_TFOLHAINT FINT on (CALC.BDCODEMP = FINT.BDCODEMP AND CALC.BDCODCOL = FINT.BDCODCOL AND CALC.BDCODCONTTI = FINT.BDCODCONTTI AND CALC.BDREFFN = FINT.BDREFFN)'||
                ' left outer join TEMPRESAS EMPLOT on (CALC.BDCODEMP = EMPLOT.BDCODEMP)'||
                ' left outer join TEMPRESAS MAT on MAT.BDCODEMP = coalesce(EMPLOT.BDCODMATRIZ, EMPLOT.BDCODEMP) '||
               ' /*JOINVERBAS*/ '||
               ' where (FINT.BDCODEMP = '||:PRCODEMP||') and '||
               ' (FINT.BDCODCOL in ('||:prcodcol||')) and '||
               ' (FINT.BDREFFN = '||:PRREF||') '||
               ' /*WHEREVERBAS*/';

  wsql = ' select bdbasefgts, bdbfgtsres, bdbfgts13, bdbasefgts13resc, bdbavprev, BDLOTACAO,BDCALCULOS, BDECONSIGNADO, BDECONSIGNADORESC  '||
         ' from SP_VRH_SEPARABASES_FGTS_5003('''||:wsql||''','||:wdatapgtorescstr||','||:wmotivorescisaostr||','||:wexportagrrfstr||')';
  for execute statement wsql into :bdbfgts, :bdbfgtsres, :bdbfgts13, :bdbasefgts13resc, :bdbavprev, :BDLOTACAO, :BDCALCULOS, :BDECONSIGNADO, :BDECONSIGNADORESC do
    suspend;

  -- Intermitente por tomador
  wsql = 'select /*CAMPOSVERBAS*/, NULL bddatapgto ,CALC.BDVALVFT '||
                ', case '||
                ' when TPCC.BDCODLOT > 0 and coalesce(TPCC.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then TPCC.BDCODLOTACAO '||
                ' when coalesce(EMPLOT.BDCODLOTACAO, null) is not null and coalesce(EMPLOT.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then EMPLOT.BDCODLOTACAO '||
                ' else MAT.BDCODLOTACAO '||
                ' end BDCODLOTACAO, -1 BDCODTIPOFC, -1 BDTIPOEVT_COMP  '||
               ' from VRHF_EMP_TVERBATOMINT CALC '||
               ' join VRHF_EMP_TFOLHATOMINT FINT on (CALC.BDCODEMP = FINT.BDCODEMP AND CALC.BDCODCOL = FINT.BDCODCOL AND CALC.BDCODCONTTI = FINT.BDCODCONTTI AND CALC.BDORDEM = FINT.BDORDEM AND CALC.BDREFTOMADOR = FINT.BDREFTOMADOR)'||

                ' left outer join VRHF_EMP_TPREPFN PFN on PFN.BDCODEMP = FINT.BDCODEMP and PFN.BDCODCOL = FINT.BDCODCOL and PFN.BDORDEM = FINT.BDORDEM '||
                ' left outer join VRHF_SP_TOMADOR(PFN.BDCODTPCC, PFN.BDCODCENTRO) TPCC on TPCC.BDCODCENTRO = PFN.BDCODCENTRO and TPCC.bdcodcencus = PFN.BDCODTPCC '||

                ' left outer join TEMPRESAS EMPLOT on (CALC.BDCODEMP = EMPLOT.BDCODEMP)'||
                ' left outer join TEMPRESAS MAT on MAT.BDCODEMP = coalesce(EMPLOT.BDCODMATRIZ, EMPLOT.BDCODEMP) '||

               ' /*JOINVERBAS*/ '||
               ' where (FINT.BDCODEMP = '||:PRCODEMP||') and '||
               ' (FINT.BDCODCOL in ('||:prcodcol||')) and '||
               ' (FINT.BDREFTOMADOR = '||:PRREF||') '||
               ' /*WHEREVERBAS*/';

  wsql = ' select bdbasefgts, bdbfgtsres, bdbfgts13, bdbasefgts13resc, bdbavprev, BDLOTACAO,BDCALCULOS, BDECONSIGNADO, BDECONSIGNADORESC  '||
         ' from SP_VRH_SEPARABASES_FGTS_5003('''||:wsql||''','||:wdatapgtorescstr||','||:wmotivorescisaostr||','||:wexportagrrfstr||')';
  for execute statement wsql into :bdbfgts, :bdbfgtsres, :bdbfgts13, :bdbasefgts13resc, :bdbavprev, :BDLOTACAO, :BDCALCULOS, :BDECONSIGNADO, :BDECONSIGNADORESC do
    suspend;


  -- Folha Complementar Intermitente
  wsql = 'select /*CAMPOSVERBAS*/, case when FC.BDCODTIPOFC = 3 then AC.BDDTPGTOBRICONV else null end bddatapgto ,CALC.BDVALVFC '||
                ', case '||
                ' when coalesce(EMPLOT.BDCODLOTACAO, null) is not null and coalesce(EMPLOT.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then EMPLOT.BDCODLOTACAO '||
                ' else MAT.BDCODLOTACAO '||
                ' end BDCODLOTACAO, FC.BDCODTIPOFC, FC.BDTIPOEVT BDTIPOEVT_COMP  '||
               ' from VRHF_EMP_TVERBAFCINT CALC '||
               ' join VRHF_EMP_TFOLHACOMPINT FC on (CALC.BDCODEMP = FC.BDCODEMP and FC.BDCODCOL = CALC.BDCODCOL and FC.BDREFFN = CALC.BDREFFN and FC.BDREFFC = CALC.BDREFFC )'||
               ' left outer join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and FC.BDCODACCONV = AC.BDCODACCONV '||
                ' left outer join TEMPRESAS EMPLOT on (CALC.BDCODEMP = EMPLOT.BDCODEMP)'||
                ' left outer join TEMPRESAS MAT on MAT.BDCODEMP = coalesce(EMPLOT.BDCODMATRIZ, EMPLOT.BDCODEMP) '||

               ' /*JOINVERBAS*/ '||
               ' where (CALC.BDCODEMP = '||:PRCODEMP||') and '||
               ' (CALC.BDCODCOL in ('||:prcodcol||')) and '||
               ' ((FC.BDCODTIPOFC = 3 and AC.BDCODACCONV is not null and '||
               ' ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = '||:PRREF||
               ')) or (FC.BDCODTIPOFC <> 3 and FC.BDREFFN = '||:PRREF||'))'||
               ' /*WHEREVERBAS*/';

  wsql = ' select bdbasefgts, bdbfgtsres, bdbfgts13, bdbasefgts13resc, bdbavprev, BDLOTACAO,BDCALCULOS, BDECONSIGNADO, BDECONSIGNADORESC  '||
         ' from SP_VRH_SEPARABASES_FGTS_5003('''||:wsql||''','||:wdatapgtorescstr||','||:wmotivorescisaostr||','||:wexportagrrfstr||')';
  for execute statement wsql into :bdbfgts, :bdbfgtsres, :bdbfgts13, :bdbasefgts13resc, :bdbavprev, :BDLOTACAO, :BDCALCULOS, :BDECONSIGNADO, :BDECONSIGNADORESC do
    suspend;

   -- Folha Complementar Intermitente por tomador
  wsql = 'select /*CAMPOSVERBAS*/, case when FC.BDCODTIPOFC = 3 then AC.BDDTPGTOBRICONV else null end bddatapgto ,CALC.BDVALVFC '||
                ', case '||
                ' when TPCC.BDCODLOT > 0 and coalesce(TPCC.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then TPCC.BDCODLOTACAO '||
                ' when coalesce(EMPLOT.BDCODLOTACAO, null) is not null and coalesce(EMPLOT.BDCODLOTACAO, /*AspasDuplas*/) <> /*AspasDuplas*/ then EMPLOT.BDCODLOTACAO '||
                ' else MAT.BDCODLOTACAO '||
                ' end BDCODLOTACAO, FC.BDCODTIPOFC, FC.BDTIPOEVT BDTIPOEVT_COMP  '||
               ' from VRHF_EMP_TVERBAFCTOMINT CALC '||
               ' join VRHF_EMP_TFOLTOMCOMPINT FC on (CALC.BDCODEMP = FC.BDCODEMP and FC.BDCODCOL = CALC.BDCODCOL and FC.BDORDEM = CALC.BDORDEM and FC.BDREFTOMADOR = CALC.BDREFTOMADOR and FC.BDREFFC = CALC.BDREFFC )'||
               ' left outer join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and FC.BDCODACCONV = AC.BDCODACCONV '||

                ' left outer join VRHF_EMP_TPREPFN PFN on PFN.BDCODEMP = FC.BDCODEMP and PFN.BDCODCOL = FC.BDCODCOL and PFN.BDORDEM = FC.BDORDEM '||
                ' left outer join VRHF_SP_TOMADOR(PFN.BDCODTPCC, PFN.BDCODCENTRO) TPCC on TPCC.BDCODCENTRO = PFN.BDCODCENTRO and TPCC.bdcodcencus = PFN.BDCODTPCC '||

                ' left outer join TEMPRESAS EMPLOT on (CALC.BDCODEMP = EMPLOT.BDCODEMP)'||
                ' left outer join TEMPRESAS MAT on MAT.BDCODEMP = coalesce(EMPLOT.BDCODMATRIZ, EMPLOT.BDCODEMP) '||

               ' /*JOINVERBAS*/ '||
               ' where (CALC.BDCODEMP = '||:PRCODEMP||') and '||
               ' (CALC.BDCODCOL in ('||:prcodcol||')) and '||
               ' ((FC.BDCODTIPOFC = 3 and AC.BDCODACCONV is not null and '||
               ' ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = '||:PRREF||
               ')) or (FC.BDCODTIPOFC <> 3 and FC.BDREFTOMADOR = '||:PRREF||'))'||
               ' /*WHEREVERBAS*/';

  wsql = ' select bdbasefgts, bdbfgtsres, bdbfgts13, bdbasefgts13resc, bdbavprev, BDLOTACAO,BDCALCULOS, BDECONSIGNADO, BDECONSIGNADORESC  '||
         ' from SP_VRH_SEPARABASES_FGTS_5003('''||:wsql||''','||:wdatapgtorescstr||','||:wmotivorescisaostr||','||:wexportagrrfstr||')';
  for execute statement wsql into :bdbfgts, :bdbfgtsres, :bdbfgts13, :bdbasefgts13resc, :bdbavprev, :BDLOTACAO, :BDCALCULOS, :BDECONSIGNADO, :BDECONSIGNADORESC do
    suspend;
end^

create or alter procedure SP_VRH_SEPARABASES_FGTS_5003 (
    PRSQL varchar(10000),
    PRDATAPGTRESC date,
    PRMOTIVORESCICAO integer,
    PREXPORTAGRRF integer)
returns (
    BDLOTACAO varchar(50),
    BDBASEFGTS numeric(15,6),
    BDBFGTSRES numeric(15,6),
    BDBFGTS13 numeric(15,6),
    BDBASEFGTS13RESC numeric(15,6),
    BDBAVPREV numeric(15,6),
    BDCALCULOS integer,
    BDECONSIGNADO numeric(15,6),
    BDECONSIGNADORESC numeric(15,6))
as
declare variable WSQL varchar(30000);
declare variable WCLAVER varchar(50);
declare variable WVALOR numeric(15,6);
declare variable WTIPVER integer;
declare variable WINCFGTS integer;
declare variable WRESCISORIO integer;
declare variable WDATAPGTOCALC date;
declare variable WLOTANT varchar(50);
declare variable WLOT varchar(50);
declare variable WCODTIPOFC varchar(50);
declare variable WTIPOEVT_COMP varchar(50);
begin

--  suspend;

  wsql =  'join VRH_BASE_TVERBAS VER on (VER.BDCODVER = CALC.BDCODVER) '||
          'join VRH_BASE_TVERBAS_REF VerRef on (VerRef.bdcodver = VER.BDCODVER';
  wsql = wsql||' and (VerRef.bdrefver = (Select Max(x.bdrefVer) from VRH_BASE_TVERBAS_REF X where X.bdcodver = VER.BDCODVER)))';

  wsql = replace(prsql,'/*JOINVERBAS*/',wsql);
  wsql = replace(wsql,'/*CAMPOSVERBAS*/','VER.BDCLAVER, VERREF.BDTIPOCODVER, VERREF.BDFGTSVER ');
  wsql = replace(wsql,'/*WHEREVERBAS*/','');
  wsql = replace(wsql,'/*AspasDuplas*/',''''||'''');

  BDBASEFGTS = 0;
  BDBFGTSRES = 0;
  BDBFGTS13 = 0;
  BDBASEFGTS13RESC = 0;
  BDBAVPREV = 0;
  BDECONSIGNADO = 0;
  BDECONSIGNADORESC = 0;

  WLOTANT = '-1';
  wlot = '';
  BDCALCULOS = 0;

  for execute statement wsql INTO WCLAVER,WTIPVER,WINCFGTS,WDATAPGTOCALC,WVALOR,WLOT,WCODTIPOFC,WTIPOEVT_COMP DO
    begin
      if ((WLOTANT <> '-1') and (wlot <> wlotant)) then
         begin
           bdlotacao = wlotant;
           suspend;

           BDBASEFGTS = 0;
           BDBFGTSRES = 0;
           BDBFGTS13 = 0;
           BDBASEFGTS13RESC = 0;
           BDBAVPREV = 0;
           BDECONSIGNADO = 0;
           BDECONSIGNADORESC = 0;
         end

      BDCALCULOS = 1;

      wlotant = wlot;

      if ((WDATAPGTOCALC is null) and (prdatapgtresc is not null)) then
         WDATAPGTOCALC = prdatapgtresc;

      if (WTIPVER in (1,3)) then
         WVALOR = WVALOR * -1;

      wrescisorio = 0;
      -- Realiza a Validação de rescisório pra ser em apenas um local essa validação
      if ((coalesce(prmotivorescicao,0) > 0) and (coalesce(prexportagrrf,0) > 0)
          and (prdatapgtresc is not null )
          and (WDATAPGTOCALC <= prdatapgtresc)) then
          begin
            wrescisorio = 1;
            
            /*226178 - Complementar ADC (CODTIPOFC = 3), com evento gerado S-1200 (TIPOEVT = 11) */
            if ((WCODTIPOFC = 3) and (WTIPOEVT_COMP = 11)) then 
              wrescisorio = 0;
          end

      --Aviso prévio
      if (((WCLAVER like '7.001.3%') or
           (WCLAVER like '7.060%') -- or
--           (WCLAVER like '7.061.0.2%') or
--           (WCLAVER like '7.061.0.1%') or
--           (WCLAVER like '0.800.6.2%')
           ) and (WINCFGTS > 0)) then
         begin
           -- Se não for rescisório deve retornar como mensal
           if (WRESCISORIO = 1) then
              BDBAVPREV = BDBAVPREV + WVALOR;
           else
              begin
                bdbasefgts = bdbasefgts + wvalor;
              end
         end
      -- FGTS Normal
      else if (WINCFGTS in (1,2)) then
         begin
           -- Sera o rescisório do Normal
           if (wrescisorio = 1) then
              bdbfgtsres = bdbfgtsres + wvalor;
           else
              bdbasefgts = bdbasefgts + wvalor;
         end
      else if (WINCFGTS in (3)) then
         begin
           -- Sera o rescisório do Normal
           if (wrescisorio = 1) then
              bdbasefgts13resc = bdbasefgts13resc + wvalor;
            else
              bdbfgts13 = bdbfgts13 + wvalor;
         end
      else if ((WCLAVER like '0.070.1%') or (WCLAVER like '0.100.4%') or ((WCLAVER like '7.001.4%')) or (WCLAVER like '0.009.1.1%') or (WCLAVER like '0.009.1.2%') ) then
        begin
           -- Sera o rescisório do Normal
           if (wrescisorio = 1) then
              bdeconsignadoresc = bdeconsignadoresc + wvalor * -1;
            else
              bdeconsignado = bdeconsignado + wvalor * -1;
        end
    end

  if (wlotant = '-1') then
     wlotant = '';
  bdlotacao = wlotant;
  suspend;
end^

create or alter procedure SP_RETORNA_BASE_ESOCIAL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PR13 integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBFGTSES numeric(18,6),
    BDBFGTS13ES numeric(18,6),
    BDBFGTSRESES numeric(18,6),
    BDBAVPREVES numeric(18,6),
    BDFGTSES numeric(18,6),
    BDFGTS13ES numeric(18,6),
    BDFGTSRESES numeric(18,6),
    BDAVPREVES numeric(18,6),
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDBASEFGTS13RESCES numeric(18,6),
    BDVALORFGTS13RESCES numeric(18,6),
    BDINSTITUICAOFINANCES integer,
    BDNROCONTRATOECONSIGNADOES varchar(30),
    BDVALORECONSIGNADOES numeric(15,6))
as
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WBFGTSES numeric(18,6);
declare variable WBFGTS13ES numeric(18,6);
declare variable WBFGTSRESES numeric(18,6);
declare variable WBAVPREVES numeric(18,6);
declare variable WFGTSES numeric(18,6);
declare variable WFGTS13ES numeric(18,6);
declare variable WFGTSRESES numeric(18,6);
declare variable WAVPREVES numeric(18,6);
declare variable WCODTIPO integer;
declare variable WTIPOVALOR integer;
declare variable WVALOR numeric(18,6);
declare variable WVALORDEP numeric(18,6);
--declare variable WMOTIVODESLIG integer;
--declare variable WCODMOTESRESC integer;
--declare variable WEHMOTESRESC integer;
declare variable WSQL varchar(500);
declare variable WEXPORTAGRRF integer;
declare variable WREFFGTSDIGITAL integer;
declare variable WDATAFGTSDIGITAL date;
begin
  /* Procedure Text */
  BDBFGTSES = 0;
  BDBFGTS13ES = 0;
  BDBFGTSRESES = 0;
  BDBAVPREVES = 0;
  BDFGTSES = 0;
  BDFGTS13ES = 0;
  BDFGTSRESES = 0;
  BDAVPREVES = 0;
--  WMOTIVODESLIG = 0;
--  WCODMOTESRESC = 0;
--  WEHMOTESRESC = 0;
  BDBASEFGTS13RESCES  = 0;
  BDVALORFGTS13RESCES = 0;
  BDINSTITUICAOFINANCES = 0;
  BDNROCONTRATOECONSIGNADOES = '';
  BDVALORECONSIGNADOES = 0;

  if (PR13 = 0) then
    begin
       /* 226178 - Isabella - 27/08/2025 : retiradas condições que consideravam o motivo de desligamento e grrf
       WSQL = 'select RES.BDCODPRES, X.BDGRRFPRES, X.BDCODMOTESRESC ' || '   from VRH_EMP_TRESCISAO RES ' || '   left join VRH_BASE_TPREPRESC X on (X.BDCODPRES = RES.bdcodpres) ' || '   where RES.BDCODEMP = ' || :PRCODEMP || ' and ' || '   RES.BDCODCOL = ' || :PRCODCOL || ' and ' || '   RES.BDREFRESCISAO = ' || :PRREF || ' and ' || '   X.BDTIPOMOV <> 1';
       execute statement WSQL
           into :WMOTIVODESLIG, :WEXPORTAGRRF, :WCODMOTESRESC;
   
         -- 226178 - WCODMOTESRESC para compl. ADC com S-1200 GFD Mensal
         if (WCODMOTESRESC in (02, -- Rescisão sem justa causa, por iniciativa do empregador.
                       03, -- Rescisão antecipada do contrato a termo por iniciativa do empregador.
                       05, -- Rescisão por culpa recíproca.
                       14, -- Rescisão do contrato de trabalho por encerramento da empresa, de seus
                       17, -- Rescisão indireta do contrato de trabalho.
                       26, -- Rescisão do contrato de trabalho por paralisação temporária ou definitiva da
                       27, -- Rescisão por motivo de força maior.
                       33, -- Rescisão por acordo entre as partes (art. 484-A da CLT).
                       47, -- Rescisão do contrato de trabalho por encerramento da empresa, de seus
                       48)) then  -- Falecimento do empregador individual sem continuação da atividade. );
             begin
                WEHMOTESRESC = 1;
             end
          else
             WEHMOTESRESC = 0;
             */
--       select BDDATAFGTSDIGITAL from VRH_ESOCIAL_TFASEAMENTO where bdcodemp = :PRCODEMP into :WDATAFGTSDIGITAL;
--   
--       if (WDATAFGTSDIGITAL is not null) then
--          select * from AAAAMM(:WDATAFGTSDIGITAL) into :WREFFGTSDIGITAL;
   
       --      for select F.BDCODEMP, F.BDCODCOL, F.BDTPVALOR, F.BDVALOR, F.BDDEPFGTS
       --          from VRH_ESOCIAL_INFOBASEFGTS_C F
       --          inner join VRH_ESOCIAL_TARQUIVO AF on (AF.BDCODEMP = F.BDCODEMP) and
       --                                      (AF.BDCODCOL = F.BDCODCOL) and
       --                                      (AF.BDCODIGO = coalesce((select first 1 X.BDCODIGO
       --                                                               from VRH_ESOCIAL_TARQUIVO X
       --                                                               where F.BDCODEVT = X.BDCODEVENTOORIG and
       --                                                                     X.BDCODEMP = :PRCODEMP and
       --                                                                     X.BDCODCOL = :PRCODCOL and
       --                                                                     X.BDREFARQ = :PRREF and
       --                                                                     X.BDSTATUS = 2 and
       --                                                                     X.BDCODTIPO = 46 order by x.bdcodigo desc), F.BDCODEVT)) and
       --                                      (AF.BDREFARQ = :PRREF) and
       --                                      (AF.BDSTATUS = 2) and
       --                                      (coalesce(AF.BDAPURACAOANUAL, 'FALSE') = 'FALSE')
       --          where F.BDCODEMP = :PRCODEMP and
       --                F.BDCODCOL = :PRCODCOL and
       --                AF.BDCODIGO = (select A.BDCODIGO
       --                               from vrh_esocial_tarquivo A
       --                               left outer join VRH_EMP_TCOLCON C on C.BDCODEMP = A.BDCODEMP and C.BDCODCOL = A.BDCODCOL
       --                               left outer join VRH_EMP_TCOLCON P on P.BDCPFCOL = C.BDCPFCOL
       --                               where P.BDCODEMP = :PRCODEMP and P.BDCODCOL = :PRCODCOL and A.BDREFARQ = :PRREF and A.BDCODTIPO = 46 and A.BDSTATUS = 2
       --                               order by A.BDCODIGO desc
       --                               fetch first 1 row only)
       --           order by BDCODEMP
         for select F.BDCODEMP, F.BDCODCOL, F.BDTPVALOR, F.BDVALOR, F.BDDEPFGTS--, F.bdinstituicaofinanc, f.bdnrocontratoeconsignado, f.bdvaloreconsignado
             from VRH_ESOCIAL_INFOBASEFGTS_C F
           where F.BDCODEMP = :PRCODEMP and
                 F.BDCODCOL = :PRCODCOL and
                 F.BDCODEVT = (select first 1 X.BDCODEVENTOORIG
                                                                  from VRH_ESOCIAL_TARQUIVO X
                               where X.BDCODEMP = :PRCODEMP and
                                     X.BDCODCOL = :PRCODCOL and
                                                                        X.BDREFARQ = :PRREF and
                                                                        X.BDSTATUS = 2 and
                                     X.BDCODTIPO = 46 and
                                     (coalesce(X.BDAPURACAOANUAL, 'FALSE') = 'FALSE')
                               order by X.BDDATARETORNO desc, X.BDHORARETORNO desc)
              order by BDCODEMP
        into  :WCODEMP, :WCODCOL, :WCODTIPO, :WVALOR, :WVALORDEP --, :BDINSTITUICAOFINANCES, :BDNROCONTRATOECONSIGNADOES, :BDVALORECONSIGNADOES
        do
        begin
           if ((BDCODCOL <> WCODCOL) and
               (BDCODCOL <> 0)) then
                   begin
                     suspend;
                     BDBFGTSES = 0;
                     BDBFGTS13ES = 0;
                     BDBFGTSRESES = 0;
                     BDBAVPREVES = 0;
                     BDFGTSES = 0;
                     BDFGTS13ES = 0;
                     BDFGTSRESES = 0;
                     BDAVPREVES = 0;
                     BDBASEFGTS13RESCES  = 0;
                     BDVALORFGTS13RESCES = 0;
                   end
                 BDCODEMP = WCODEMP;
                 BDCODCOL = WCODCOL;
                 BDREF    = :PRREF;
     
--           if (PRREF < WREFFGTSDIGITAL) then
--              begin
--                 if ((WCODTIPO in (11, 13, 15, 17)) and (WMOTIVODESLIG = 0)) then --(WCODTIPO not in (34, 37))) then
--                   begin
--                     BDBFGTSES = BDBFGTSES + WVALOR;
--                     BDFGTSES = BDFGTSES + WVALORDEP;
--                   end
--       
--                 if ((WCODTIPO in (21, 24, 27, 30)) or (WCODTIPO in (11, 13, 15, 17) and (WMOTIVODESLIG > 0))) then --(WCODTIPO in (34, 37)))) then
--                   begin
--                     BDBFGTSRESES = BDBFGTSRESES + WVALOR;
--                     BDFGTSRESES = BDFGTSRESES + WVALORDEP;
--                   end
--     
--                 if ((WCODTIPO in (23, 26, 29, 32)) and (WMOTIVODESLIG <> 0)) then
--                   begin
--                     BDBAVPREVES = BDBAVPREVES + WVALOR;
--                     BDAVPREVES = BDAVPREVES + WVALORDEP;
--                   end
--     
--                 if ((WCODTIPO in (12, 14, 16, 18, 22, 25, 28, 31)) and (WMOTIVODESLIG = 0)) then
--                   begin
--                     BDBFGTS13ES = BDBFGTS13ES + WVALOR;
--                     BDFGTS13ES = BDFGTS13ES + WVALORDEP;
--                   end
--                 if ((WCODTIPO in (22, 28) or WCODTIPO in (12, 14, 16)) and (WMOTIVODESLIG > 0)) then
--                   begin
--                     BDBASEFGTS13RESCES  = BDBASEFGTS13RESCES  + WVALOR;
--                     BDVALORFGTS13RESCES = BDVALORFGTS13RESCES + WVALORDEP;
--                   end
--              end
--           else
--              begin
                --Base fgts mensal e rescisório
                if (WCODTIPO in (11, 13, 15)) then
                   /* 226178 - retirado: and (WMOTIVODESLIG = 0)) or ((WCODTIPO in (11, 13, 15)) and (WEXPORTAGRRF <= 0))) */
                   begin
                      BDBFGTSES = BDBFGTSES + WVALOR;
                      BDFGTSES  = BDFGTSES  + WVALORDEP;
                   end
                else
                if (WCODTIPO in (21, 24, 27)) then
                   /* 226178 - retirado: or WCODTIPO in (11, 13, 15)) and (WMOTIVODESLIG <> 0))
                             - incluido: 24 - FGTS (período anterior) mês da rescisão */
                   begin
                     BDBFGTSRESES = BDBFGTSRESES + WVALOR;
                     BDFGTSRESES  = BDFGTSRESES  + WVALORDEP;
                   end
                --Base de aviso prévio
                if (WCODTIPO in (23, 26, 29)) then
                   /* 226178 - retirado: and (WMOTIVODESLIG <> 0))
                             - incluido: 26 - FGTS (período anterior) aviso prévio indenizado */
                  begin
                    BDBAVPREVES = BDBAVPREVES + WVALOR;
                    BDAVPREVES = BDAVPREVES + WVALORDEP;
                  end
                --Base fgts 13º mensal e rescisório
                if (WCODTIPO in (12, 14, 16)) then
                    /* 226178 -  retirado: and (WMOTIVODESLIG = 0)) or ((WCODTIPO in (12, 14, 16)) and (WEXPORTAGRRF <= 0))) */
                  begin
                    BDBFGTS13ES = BDBFGTS13ES + WVALOR;
                    BDFGTS13ES  = BDFGTS13ES  + WVALORDEP;
                  end
                else
                if (WCODTIPO in (22, 25, 28)) then
                    /* 226178 - retirado: or WCODTIPO in (12, 14, 16)) and (WMOTIVODESLIG > 0))
                              - incluido: 25 - FGTS (período anterior) 13º salário rescisório */
                    begin
                      BDBASEFGTS13RESCES  = BDBASEFGTS13RESCES  + WVALOR;
                      BDVALORFGTS13RESCES = BDVALORFGTS13RESCES + WVALORDEP;
                    end
--              end
              end
        end
   if (PR13 = 1) then
     begin
      for select F.BDCODEMP, F.BDCODCOL, F.BDTPVALOR, F.BDVALOR, F.BDDEPFGTS
          from VRH_ESOCIAL_INFOBASEFGTS_C F
--          inner join VRH_ESOCIAL_TARQUIVO AF on (AF.BDCODEMP = F.BDCODEMP) and
--                                      (AF.BDCODCOL = F.BDCODCOL) and
--                                      (AF.BDCODIGO = coalesce((select first 1 X.BDCODIGO
--                                                               from VRH_ESOCIAL_TARQUIVO X
--                                                               where F.BDCODEVT = X.BDCODEVENTOORIG and
--                                                                     F.BDCODEMP = X.BDCODEMP and
--                                                                     F.BDCODCOL = X.BDCODCOL and
--                                                                     X.BDREFARQ = :PRREF and
--                                                                     X.BDSTATUS = 2 and
--                                             X.BDCODTIPO = 46
--                                       order by X.BDCODIGO desc), F.BDCODEVT)) and
--                                      (AF.BDREFARQ = :PRREF) and
--                                      (AF.BDSTATUS = 2) and
--                                      (coalesce(AF.BDAPURACAOANUAL, 'FALSE') = 'TRUE')
----        inner join VRH_ESOCIAL_TARQUIVO ORI on (ORI.BDCODEMP = AF.BDCODEMP and
----              ORI.BDCODCOL = AF.BDCODCOL and
----              ORI.BDCODIGO = AF.BDCODEVENTOORIG)
          where F.BDCODEMP = :PRCODEMP and
                F.BDCODCOL = :PRCODCOL and
               F.BDCODEVT = (select first 1 X.BDCODEVENTOORIG
                                                               from VRH_ESOCIAL_TARQUIVO X
               where X.BDCODEMP = :PRCODEMP and
                     X.BDCODCOL = :PRCODCOL and
                                                                     X.BDREFARQ = :PRREF and
                                                                     X.BDSTATUS = 2 and
                     X.BDCODTIPO = 46 and
                     (coalesce(X.BDAPURACAOANUAL, 'FALSE') = 'TRUE')
               order by X.BDDATARETORNO desc, X.BDHORARETORNO desc)
           order by BDCODEMP
        into  :WCODEMP, :WCODCOL,  :WTIPOVALOR, :WVALOR, :WVALORDEP
        do
          begin
      if ((BDCODCOL <> WCODCOL) and
          (BDCODCOL <> 0)) then
              begin
                suspend;
                BDBFGTSES = 0;
                BDBFGTS13ES = 0;
                BDBFGTSRESES = 0;
                BDBAVPREVES = 0;
                BDFGTSES = 0;
                BDFGTS13ES = 0;
                BDFGTSRESES = 0;
                BDAVPREVES = 0;
              end
            BDCODEMP = WCODEMP;
            BDCODCOL = WCODCOL;
            BDREF    = :PRREF;

            if (WTIPOVALOR in (12, 14, 16, 18)) then
              begin
                BDBFGTS13ES = BDBFGTSES + WVALOR;
                BDFGTS13ES = BDFGTSES + WVALORDEP;
              end

          end

     end
  suspend;
end^

create or alter procedure SP_RETORNA_BASE_INSS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRTEMCONFIGIMPOSTO integer,
    PRSEPARAFOLHAS integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBINSS numeric(18,6),
    BDBINSSFEFOL numeric(18,6),
    BDBINSS13 numeric(18,6),
    BDINSS numeric(18,6),
    BDINSS13 numeric(18,6),
    BDINSSFEFOL numeric(18,6),
    BDVALORSALFAM numeric(18,6),
    BDVALORSALMATEMP numeric(18,6),
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDVALORPISPASEP numeric(18,6),
    BDVALORPISPASEP13 numeric(18,6),
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOCALCULO integer)
as
declare variable WSQL varchar(500);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WBINSS numeric(18,6);
declare variable WBINSSFEFOL numeric(18,6);
declare variable WBINSS13 numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WINSSFEFOL numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WVALORSALFAM numeric(18,6);
declare variable WVALORSALMATEMP numeric(18,6);
declare variable WCALCULOS integer;
declare variable WCOUNTFC integer;
declare variable WVALOR numeric(18,6);
declare variable WTIPOFOL integer;
declare variable WVALORPISPASEP numeric(18,6);
declare variable WVALORPISPASEP13 numeric(18,6);
declare variable WTAGSTR varchar(10000);
declare variable WDIFERENCIADORDATE date;
declare variable WDIFERENCIADORINTEGER integer;
declare variable WDESCRICAOFOLHA varchar(10000);
declare variable WTIPOFOLANTERIOR integer;
declare variable WORDEMANTERIOR integer;
begin
    BDBINSS = 0;
    BDINSS = 0;
    BDBINSS13 = 0;
    BDINSS13 = 0;
    BDBINSSFEFOL = 0;
    BDINSSFEFOL = 0;
    BDVALORSALFAM = 0;
    BDVALORSALMATEMP = 0;
    BDCOUNTFC = 0;
    BDCALCULOS = 0;
    BDVALORPISPASEP = 0;
    BDVALORPISPASEP13 = 0;
    BDTAGSTR = '';
    WTIPOFOLANTERIOR = 0;
    BDTIPOCALCULO = 0;
    WORDEMANTERIOR = 0;


  for select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFN BDREF, FN.BDBINSSFN BDBINSS,
             FN.BDBINSSFEFOLFN BDBINSSFEFOL, FN.BDBINSS13FN BDBINSS13, FN.BDINSSFN BDINSS, FN.BDINSSFEFOLFN BDINSSFEFOL, FN.BDINSS13FN BDINSS13, FN.BDSALFAMFN as BDVALORSALFAM, (coalesce(FN.BDSALMATEMPFN, 0) + coalesce(FN.BDVSALMATEMP13FN, 0)) as BDVALORSALMATEMP, 1 as BDCALCULOS,
             0 as BDCOUNTFC, 1 as BDTIPO, FN.BDDATAPGTOFN AS BDDIFERENCIADORDATA, 0 AS BDDIFERENCIADORINTEGER
      from VRHF_EMP_TFOLHANORMAL FN           --FOLHA NORMAL
      where FN.BDCODEMP = :PRCODEMP and
            FN.BDREFFN = :PRREF and
            FN.BDCODCOL = :PRCODCOL
      union all
      select FT.BDCODEMP, FT.BDCODCOL, FT.BDREFTOMADOR BDREF, FT.BDBINSSFT, FT.BDBINSSFEFOLFT, FT.BDBINSS13FT,
             FT.BDINSSFT, FT.BDINSSFEFOLFT, FT.BDINSS13FT, FT.BDSALFAMFT,
             (coalesce(FT.BDSALMATEMPFT, 0) + coalesce(FT.BDVSALMATEMP13FT, 0)), 1 as BDCALCULOS, 0 as BDCOUNTFC, 2 as BDTIPO, FT.BDDATAPGTOFT AS BDDIFERENCIADORDATA, FT.BDORDEM AS BDDIFERENCIADORINTEGER
      from VRHF_EMP_TFOLHATOMADOR FT         --FOLHA TOMADOR
      where FT.BDCODEMP = :PRCODEMP and
            FT.BDREFTOMADOR = :PRREF and
            FT.BDCODCOL = :PRCODCOL
     union all
      select FA13.BDCODEMP, FA13.BDCODCOL, FA13.BDREFA13 BDREF, 0, 0, 0, 0, 0, 0, FA13.BDSALFAMA13,
             FA13.BDSALMATEMPA13,
             case
               when (FA13.BDSALFAMA13 + FA13.BDSALMATEMPA13 > 0) then 1
               else 0
             end BDCALCULOS,
             0 as BDCOUNTFC, 3 as BDTIPO, FA13.BDDATAPGTOA13 AS BDDIFERENCIADORDATA, 0 AS BDDIFERENCIADORINTEGER
      from VRHF_EMP_TA13SAL FA13             --ADIANTAMENTO 13
      where FA13.BDCODEMP = :PRCODEMP and
            FA13.BDREFA13 = :PRREF AND
            FA13.BDCODCOL = :PRCODCOL
     union all
      select C13.BDCODEMP, C13.BDCODCOL, C13.BDREF13 BDREF, 0, 0, C13.BDBASEINSSC13, 0, 0, C13.BDVALORINSSC13,
             C13.BDSALFAMC13, C13.BDSALMATEMPC13, 1 as BDCALCULOS, 0 as BDCOUNTFC, 4 as BDTIPO, C13.BDDATAPGTOC13 AS BDDIFERENCIADORDATA, 0 AS BDDIFERENCIADORINTEGER
      from VRHF_EMP_TC13SAL C13              --COMPLEMENTO 13
      where C13.BDCODEMP = :PRCODEMP and
            c13.BDREF13 = :PRREF and
            C13.BDCODCOL = :PRCODCOL
     union all
      select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFFN BDREF, FC.BDBINSSFC, 0, FC.BDBINSS13FC, FC.BDINSSFC,
             FC.BDINSSFEFOLFC, FC.BDINSS13FC, FC.BDSALFAMFC,
             (coalesce(FC.BDSALMATEMPFC, 0) + coalesce(FC.BD13SALMATPAGEMP, 0)), 1 as BDCALCULOS, 1 as BDCOUNTFC, 5 as BDTIPO, FC.BDDATAPAGFC AS BDDIFERENCIADORDATA, FC.BDREFFC AS BDDIFERENCIADORINTEGER
      from VRHF_EMP_TFOLHACOMP FC           --FOLHA COMPLEMENTAR
      where FC.BDCODEMP = :PRCODEMP and
            FC.BDCODTIPOFC <> 3 and
            FC.BDCODCOL = :PRCODCOL and 
            FC.BDREFFN = :PRREF
     union all
      select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFTOMADOR BDREF, FC.BDBINSSFC, 0, FC.BDBINSS13FC, FC.BDINSSFC,
             FC.BDINSSFEFOLFC, FC.BDINSS13FC, FC.BDSALFAMFC,
             (coalesce(FC.BDSALMATEMPFC, 0) + coalesce(FC.BD13SALMATPAGEMP, 0)), 1 as BDCALCULOS, 1 as BDCOUNTFC, 6 as BDTIPO, FC.BDDATAPAGFC AS BDDIFERENCIADORDATA, FC.BDREFFC AS BDDIFERENCIADORINTEGER
      from VRHF_EMP_TFOLTOMCOMP FC          --FOLHA TOMADOR COMPLEMENTAR
      where FC.BDCODEMP = :PRCODEMP and
            FC.BDCODCOL = :PRCODCOL and
            FC.BDCODTIPOFC <> 3 and
            FC.BDREFTOMADOR = :PRREF
     union all
       select  :PRCODEMP BDCODEMP,:PRCODCOL BDCODCOL, FC.BDREFFN BDREF, FC.BDBINSSFC, 0, FC.BDBINSS13FC, FC.BDINSSFC, FC.BDINSSFEFOLFC,
               FC.BDINSS13FC, FC.BDSALFAMFC,
               (coalesce(FC.BDSALMATEMPFC, 0) + coalesce(FC.BD13SALMATPAGEMP, 0)), 1 as BDCALCULOS, 1 as BDCOUNTFC, 7 as BDTIPO, FC.BDDATAPAGFC AS BDDIFERENCIADORDATA, FC.BDREFFC AS BDDIFERENCIADORINTEGER
       --from (select C.BDCODEMP, C.BDCODCOL from VRH_EMP_TCOLCON S join VRH_EMP_TCOLCON C on C.BDCPFCOL = S.BDCPFCOL where S.BDCODEMP = :PRCODEMP and S.BDCODCOL = :PRCODCOL) C
       from VRH_EMP_TCOLCON C
       join VRHF_EMP_TFOLHACOMP FC on FC.BDCODEMP = C.bdcodemp and FC.BDCODCOL = C.bdcodcol
       left outer join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and  FC.BDCODACCONV = AC.BDCODACCONV
       where C.BDCODEMP = :PRCODEMP and C.BDCODCOL = :PRCODCOL and
             FC.BDCODEMP = C.BDCODEMP and
            FC.BDCODTIPOFC = 3 and
             FC.BDCODCOL = C.BDCODCOL and
            AC.BDCODACCONV is not null and
            ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = :PRREF)
     union all
       select  :PRCODEMP BDCODEMP,:PRCODCOL BDCODCOL, FC.BDREFTOMADOR BDREF, FC.BDBINSSFC, 0, FC.BDBINSS13FC, FC.BDINSSFC, FC.BDINSSFEFOLFC,
               FC.BDINSS13FC, FC.BDSALFAMFC,
               (coalesce(FC.BDSALMATEMPFC, 0) + coalesce(FC.BD13SALMATPAGEMP, 0)), 1 as BDCALCULOS, 1 as BDCOUNTFC, 8 as BDTIPO, FC.BDDATAPAGFC AS BDDIFERENCIADORDATA, FC.BDREFFC AS BDDIFERENCIADORINTEGER
       --from (select C.BDCODEMP, C.BDCODCOL from VRH_EMP_TCOLCON S join VRH_EMP_TCOLCON C on C.BDCPFCOL = S.BDCPFCOL where S.BDCODEMP = :PRCODEMP and S.BDCODCOL = :PRCODCOL) C
       from VRH_EMP_TCOLCON C
       join VRHF_EMP_TFOLTOMCOMP FC on FC.BDCODEMP = C.bdcodemp and FC.BDCODCOL = C.bdcodcol
       left outer join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and  FC.BDCODACCONV = AC.BDCODACCONV
       where C.BDCODEMP = :PRCODEMP and C.BDCODCOL = :PRCODCOL and
             FC.BDCODEMP = C.BDCODEMP and
            FC.BDCODTIPOFC = 3 and
             FC.BDCODCOL = C.BDCODCOL and
            AC.BDCODACCONV is not null and
            ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = :PRREF)
     union all
      select FAV.BDCODEMP, FAV.BDCODCOL, FAV.BDREF, FAV.BDBINSSFA, FAV.BDBINSSFEFOLFA, FAV.BDBINSS13FA,
             FAV.BDINSS13FA, FAV.BDINSSFEFOLFA, FAV.BDINSS13FA, FAV.BDSALFAMFA,
             (coalesce(FAV.BDSALMATEMPFA, 0) + coalesce(FAV.BDVSALMATEMP13FA, 0)), 1 as BDCALCULOS, 0 as BDCOUNTFC, 9 as BDTIPO, FAV.BDDATAFA AS BDDIFERENCIADORDATA, FAV.BDCODTCA AS BDDIFERENCIADORINTEGER
      from VRHF_EMP_TFOLHAAVULSA FAV        --FOLHA AVULSA
      where FAV.BDCODEMP = :PRCODEMP and
            FAV.BDREF = :PRREF and
            FAV.BDCODCOL = :PRCODCOL
     union all
      select FINT.BDCODEMP, FINT.BDCODCOL, FINT.BDREFFN BDREF, FINT.BDBINSSFN, FINT.BDBINSSFEFOLFN,
             FINT.BDBINSS13FN, FINT.BDINSSFN, FINT.BDINSSFEFOLFN, FINT.BDINSS13FN, FINT.BDSALFAMFN,
             (coalesce(FINT.BDSALMATEMPFN, 0) + coalesce(FINT.BDVSALMATEMP13FN, 0)), 1 as BDCALCULOS, 0 as BDCOUNTFC, 10 as BDTIPO, FINT.BDDATAPGTOFN AS BDDIFERENCIADORDATA, FINT.BDCODCONTTI AS BDDIFERENCIADORINTEGER
      from VRHF_EMP_TFOLHAINT FINT         --FOLHA INTERMITENTE
      where FINT.BDCODEMP = :PRCODEMP and
            FINT.BDREFFN = :PRREF and
            FINT.BDCODCOL = :PRCODCOL
     union all
      select FMINT.BDCODEMP, FMINT.BDCODCOL, FMINT.BDREFTOMADOR, FMINT.BDBINSSFT, FMINT.BDBINSSFEFOLFT,
             FMINT.BDBINSS13FT, FMINT.BDINSSFT, FMINT.BDINSSFEFOLFT, FMINT.BDINSS13FT, FMINT.BDSALFAMFT,
             (coalesce(FMINT.BDSALMATEMPFT, 0) + coalesce(FMINT.BDVSALMATEMP13FT, 0)), 1 as BDCALCULOS, 0 as BDCOUNTFC, 11 as BDTIPO, FMINT.BDDATAPGTOFT AS BDDIFERENCIADORDATA, FMINT.BDCODCONTTI AS BDDIFERENCIADORINTEGER
      from VRHF_EMP_TFOLHATOMINT FMINT      --FOLHA TOMADOR INTERMITENTE
      where FMINT.BDCODEMP = :PRCODEMP and
            FMINT.BDREFTOMADOR = :PRREF and
            FMINT.BDCODCOL = :PRCODCOL
     union all
      select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFFN as BDREF, FC.BDBINSSFC, 0, FC.BDBINSS13FC, FC.BDINSSFC,
             FC.BDINSSFEFOLFC, FC.BDINSS13FC, FC.BDSALFAMFC,
             (coalesce(FC.BDSALMATEMPFC, 0) + coalesce(FC.BD13SALMATPAGEMP, 0)), 1 as BDCALCULOS, 1 as BDCOUNTFC, 12 as BDTIPO, FC.BDDATAPAGFC AS BDDIFERENCIADORDATA, FC.BDCODCONTTI AS BDDIFERENCIADORINTEGER
      from VRHF_EMP_TFOLHACOMPINT FC
      where FC.BDCODEMP = :PRCODEMP and
            FC.BDCODTIPOFC <> 3 and
            FC.BDCODCOL = :PRCODCOL and
            FC.BDREFFN = :PRREF
     union all
      select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFTOMADOR as BDREF, FC.BDBINSSFC, 0, FC.BDBINSS13FC, FC.BDINSSFC,
             FC.BDINSSFEFOLFC, FC.BDINSS13FC, FC.BDSALFAMFC,
             (coalesce(FC.BDSALMATEMPFC, 0) + coalesce(FC.BD13SALMATPAGEMP, 0)), 1 as BDCALCULOS, 1 as BDCOUNTFC, 13 as BDTIPO, FC.BDDATAPAGFC AS BDDIFERENCIADORDATA, FC.BDCODCONTTI AS BDDIFERENCIADORINTEGER
      from VRHF_EMP_TFOLTOMCOMPINT FC
      where FC.BDCODEMP = :PRCODEMP and
            FC.BDCODCOL = :PRCODCOL and
            FC.BDCODTIPOFC <> 3 and
            FC.BDREFTOMADOR = :PRREF
     union all
      select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFFN as BDREF, FC.BDBINSSFC, 0, FC.BDBINSS13FC, FC.BDINSSFC,
             FC.BDINSSFEFOLFC, FC.BDINSS13FC, FC.BDSALFAMFC,
             (coalesce(FC.BDSALMATEMPFC, 0) + coalesce(FC.BD13SALMATPAGEMP, 0)), 1 as BDCALCULOS, 1 as BDCOUNTFC, 14 as BDTIPO, FC.BDDATAPAGFC AS BDDIFERENCIADORDATA, FC.BDCODCONTTI AS BDDIFERENCIADORINTEGER
      from VRHF_EMP_TFOLHACOMPINT FC
      left outer join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and
            FC.BDCODACCONV = AC.BDCODACCONV
      where FC.BDCODEMP = :PRCODEMP and
            FC.BDCODTIPOFC = 3 and
            FC.BDCODCOL = :PRCODCOL and
            AC.BDCODACCONV is not null and
            ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = :PRREF)
     union all
      select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFTOMADOR as BDREF, FC.BDBINSSFC, 0, FC.BDBINSS13FC, FC.BDINSSFC,
             FC.BDINSSFEFOLFC, FC.BDINSS13FC, FC.BDSALFAMFC,
             (coalesce(FC.BDSALMATEMPFC, 0) + coalesce(FC.BD13SALMATPAGEMP, 0)), 1 as BDCALCULOS, 1 as BDCOUNTFC, 15 as BDTIPO, FC.BDDATAPAGFC AS BDDIFERENCIADORDATA, FC.BDCODCONTTI AS BDDIFERENCIADORINTEGER
      from VRHF_EMP_TFOLTOMCOMPINT FC
      left outer join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and
            FC.BDCODACCONV = AC.BDCODACCONV
      where FC.BDCODEMP = :PRCODEMP and
            FC.BDCODTIPOFC = 3 and
            FC.BDCODCOL = :PRCODCOL and
            AC.BDCODACCONV is not null and
            ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = :PRREF)

  into :WCODEMP, :WCODCOL, :WREF, :WBINSS, :WBINSSFEFOL, :WBINSS13, :WINSS, :WINSSFEFOL, :WINSS13, :WVALORSALFAM, :WVALORSALMATEMP, :WCALCULOS, :WCOUNTFC, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER
  do
    begin
      if (((BDCODCOL <> WCODCOL) and (BDCODCOL <> 0))) then
         begin
           suspend;
           BDBINSS = 0;
           BDINSS = 0;
           BDBINSS13 = 0;
           BDINSS13 = 0;
           BDBINSSFEFOL = 0;
           BDINSSFEFOL = 0;
           BDCALCULOS = 0;
           BDCOUNTFC = 0;
           BDVALORPISPASEP = 0;
           BDVALORPISPASEP13 = 0;
           BDTAGSTR = '';
         end
      else if ((PRSEPARAFOLHAS = 1) and (WTIPOFOLANTERIOR <> WTIPOFOL) and (WTIPOFOLANTERIOR in (7,8)) and (WTIPOFOLANTERIOR <> 0)) then
         begin
           suspend;
           BDBINSS = 0;
           BDINSS = 0;
           BDBINSS13 = 0;
           BDINSS13 = 0;
           BDBINSSFEFOL = 0;
           BDINSSFEFOL = 0;
           BDCALCULOS = 0;
           BDCOUNTFC = 0;
           BDVALORPISPASEP = 0;
           BDVALORPISPASEP13 = 0;
           BDTAGSTR = '';
         end

      if (WTIPOFOL <> WTIPOFOLANTERIOR) then
         WTIPOFOLANTERIOR = WTIPOFOL;

      BDTIPOCALCULO = WTIPOFOL;

      if (((WORDEMANTERIOR = 0) and (WTIPOFOL = 2)) or ((WDIFERENCIADORINTEGER <> WORDEMANTERIOR) and (WTIPOFOL = 2))) then
         BEGIN
           WORDEMANTERIOR = WDIFERENCIADORINTEGER;
           BDVALORPISPASEP = 0;
           BDVALORPISPASEP13 = 0;
         END

      if (PRTEMCONFIGIMPOSTO = 1) then
          select BDBDVALORPISPASEP,BDVALORPISPASEP13 from SP_BUSCA_VALOR_PIS_VERBAS(:WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER)
          into :WVALORPISPASEP, :WVALORPISPASEP13;

      select BDDESCRICAOCALCULO,BDTAGSTR from SP_RETORNA_TAGSTR_TOTALIZADORES(:WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER)
      into :WDESCRICAOFOLHA,:WTAGSTR;

      if (WTIPOFOL = 4) then
        begin
          wSQL = 'select COALESCE(V13.BDVALVC13, 0) '||
                 'from VRHF_EMP_TC13SAL C13 '||
                 'left outer join VRHF_EMP_TVERBAC13 V13 on (V13.BDCODEMP = C13.bdcodemp and V13.BDCODCOL = C13.bdcodcol and V13.BDREF13 = C13.bdref13 and V13.bdrefc13 = C13.bdrefc13) '||
                 'left outer join VRH_BASE_TVERBAS V on (V.BDCODVER = V13.BDCODVER) '||
                 'where C13.BDCODEMP = '||:PRCODEMP||' and '||
                       'C13.BDREF13 = '||:PRREF||' and '||
                       'C13.BDCODCOL = '||:PRCODCOL||' and '||
                       'V.BDCLAVER = ''6.080.0.0.002''';  -- verba 68003
          execute statement wsql into :wvalor;
          WVALORSALMATEMP = WVALORSALMATEMP - coalesce(wvalor,0);
        end

      BDCODEMP = WCODEMP;
      BDCODCOL = WCODCOL;
      BDREF = WREF;
      BDBINSS = BDBINSS + coalesce(WBINSS,0);
      BDBINSSFEFOL = BDBINSSFEFOL + coalesce(WBINSSFEFOL, 0);
      BDBINSS13 = BDBINSS13 + coalesce(WBINSS13, 0);
      BDINSS13 = BDINSS13 + coalesce(WINSS13, 0);
      BDINSS = BDINSS + coalesce(WINSS, 0);
      BDINSSFEFOL = BDINSSFEFOL + coalesce(WINSSFEFOL, 0);
      BDVALORSALFAM = BDVALORSALFAM + coalesce(WVALORSALFAM, 0);
      BDVALORSALMATEMP =BDVALORSALMATEMP +  coalesce(WVALORSALMATEMP, 0);


      BDCOUNTFC = BDCOUNTFC + WCOUNTFC;
      BDVALORPISPASEP = BDVALORPISPASEP + WVALORPISPASEP;
      BDVALORPISPASEP13 = BDVALORPISPASEP13 + WVALORPISPASEP13;
      BDTAGSTR = WTAGSTR;
      BDDESCRICAOFOLHA = WDESCRICAOFOLHA;

      if (WCALCULOS = 1) then
        BDCALCULOS = 1;

      if ((PRSEPARAFOLHAS = 1) and (not(WTIPOFOL in (7,8)))) then
         begin
           suspend;

           BDBINSS = 0;
           BDINSS = 0;
           BDBINSS13 = 0;
           BDINSS13 = 0;
           BDBINSSFEFOL = 0;
           BDINSSFEFOL = 0;
           BDCALCULOS = 0;
           BDCOUNTFC = 0;
           BDVALORPISPASEP = 0;
           BDVALORPISPASEP13 = 0;
           BDVALORSALFAM  = 0;
           BDVALORSALMATEMP =0;
           BDTAGSTR = '';
           BDDESCRICAOFOLHA = '';
         end
    end

  if ((PRSEPARAFOLHAS = 0) or (WTIPOFOL in (7,8))) then
    suspend;
end^

create or alter procedure SP_RETORNA_BASE_INSS_ES (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PR13 integer,
    PRCPFCOL varchar(18))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDBASEINSSES numeric(18,6),
    BDBASEINSS13ES numeric(18,6),
    BDVALORINSSES numeric(18,6),
    BDVALORINSS13ES numeric(18,6),
    BDVALORSALFAMES numeric(18,6),
    BDVALORSALMATEMPES numeric(18,6),
    BDVRCPSEG numeric(18,6),
    BDIND13PIS integer,
    BDTPVALORPISPASEP integer,
    BDVALORPISPASEP numeric(18,6),
    BDVERSAOLAYOUTESOCIAL varchar(10),
    BDVALORPISPASEP13 numeric(18,6))
as
declare variable WBASEINSSES numeric(18,6);
declare variable WBASEINSS13ES numeric(18,6);
declare variable WVALORINSSES numeric(18,6);
declare variable WVALORINSS13ES numeric(18,6);
declare variable WVALORSALFAMES numeric(18,6);
declare variable WVALORSALFAM13ES numeric(18,6);
declare variable WVALORSALMATEMPES numeric(18,6);
declare variable WVALORSALMATEMP13ES numeric(18,6);
declare variable WVRCPSEG numeric(18,6);
declare variable WVRCPSEG13 numeric(18,6);
declare variable WCODEVT integer;
declare variable WIND13PIS integer;
declare variable WTPVALORPISPASEP integer;
declare variable WVALORPISPASEP numeric(18,6);
declare variable WVERSAOLAYOUTESOCIAL varchar(10);
declare variable WVALORPISPASEP13 numeric(18,6);
begin

  BDBASEINSSES          = 0;
  BDBASEINSS13ES        = 0;
  BDVALORINSSES         = 0;
  BDVALORINSS13ES       = 0;
  BDVALORSALFAMES       = 0;
  BDVALORSALMATEMPES    = 0;
  BDVRCPSEG             = 0;
  BDIND13PIS            = 0;
  BDTPVALORPISPASEP     = 0;
  BDVALORPISPASEP       = 0;
  BDVALORPISPASEP13     = 0;
  BDVERSAOLAYOUTESOCIAL = '';

  WBASEINSSES          = 0;
  WBASEINSS13ES        = 0;
  WVALORINSSES         = 0;
  WVALORINSS13ES       = 0;
  WVALORSALFAMES       = 0;
  WVALORSALFAM13ES     = 0;
  WVALORSALMATEMPES    = 0;
  WVALORSALMATEMP13ES  = 0;
  WVRCPSEG             = 0;
  WVRCPSEG13           = 0;
  WCODEVT              = 0;
  WIND13PIS            = -111;
  WTPVALORPISPASEP     = -111;
  WVALORPISPASEP       = 0;
  WVERSAOLAYOUTESOCIAL = '';
  WVALORPISPASEP13     = 0;

  if (PR13 = 0) then
    begin
      select first 1 ACP.BDCODIGO
      from VRH_ESOCIAL_TARQUIVO ACP
      join VRH_EMP_TCOLCON CC on (ACP.BDCODEMP = CC.BDCODEMP and
            ACP.BDCODCOL = CC.BDCODCOL and
            ((ACP.BDCODTER is null) or (ACP.BDCODTER <> ACP.BDCODCOL)) and
            CC.BDCPFCOL = :prcpfcol)
      where ACP.BDCODEMP = :prcodemp and
            ACP.BDREFARQ = :prref and
            ACP.BDSTATUS = 2 and
            ACP.bdcodtipo = 40
      order by ACP.bdcodigo desc

      into :WCODEVT;
      ----------------------------------BASE INSS e VRCPSEG----------------------------------------
      select SUM(cp.BDVALOR) BDVALOR , max(coalesce(
             case
               when (ACP.BDCODCOL is distinct from ACP.BDCODTER) then CP.BDVRCPSEG
               else 0
             end, 0)) BDVRCPSEG
      from VRH_ESOCIAL_INFOBASECS_C CP
      inner join VRH_ESOCIAL_TARQUIVO ACP on (ACP.BDCODEMP = CP.BDCODEMP) and
            (ACP.BDCODIGO = CP.BDCODEVT) and
            (ACP.BDREFARQ = :PRREF) and
            (ACP.BDSTATUS = 2) and
            (coalesce(ACP.BDAPURACAOANUAL, 'FALSE') = 'FALSE')
       join vrh_emp_tcolcon cc on (acp.bdcodemp = cc.bdcodemp and acp.bdcodcol = cc.bdcodcol
        and cc.bdcpfcol = :PRCPFCOL)
      left outer join VRH_ESOCIAL_TARQUIVO RETIF on (RETIF.BDCODEMP = ACP.BDCODEMP) and
            (RETIF.BDEVENTOVINC = ACP.BDCODEVENTOORIG) and
            (RETIF.BDSTATUS = 2)
      where CP.BDCODEMP = :PRCODEMP and
            (coalesce(CP.BDTPVALOR, 0) in (0, 11, 12, 13, 14, 19)) and
            (coalesce(CP.BDIND13, 0) = 0) and
            (RETIF.BDCODEMP is null)
            and ACP.BDCODIGO = :WCODEVT
    
      into :WBASEINSSES, :WVRCPSEG;
      --------------------------------------VALOR INSS-------------------------------------------
      select sum(CP.BDVALOR) BDVALOR
      from VRH_ESOCIAL_INFOBASECS_C CP
      inner join VRH_ESOCIAL_TARQUIVO ACP on (ACP.BDCODEMP = CP.BDCODEMP) and
            (ACP.BDCODIGO = CP.BDCODEVT) and
            (ACP.BDREFARQ = :PRREF) and
            (ACP.BDSTATUS = 2) and
            (coalesce(ACP.BDAPURACAOANUAL, 'FALSE') = 'FALSE')
       join vrh_emp_tcolcon cc on (acp.bdcodemp = cc.bdcodemp and acp.bdcodcol = cc.bdcodcol
        and cc.bdcpfcol = :prcpfcol)
      left outer join VRH_ESOCIAL_TARQUIVO RETIF on (RETIF.BDCODEMP = ACP.BDCODEMP) and
            (RETIF.BDEVENTOVINC = ACP.BDCODEVENTOORIG) and
            (RETIF.BDSTATUS = 2)
      where CP.BDCODEMP = :PRCODEMP and
            (coalesce(CP.BDTPVALOR, 0) in (21, 23)) and
            (coalesce(CP.BDIND13, 0) = 0) and
            (RETIF.BDCODEMP is null)
            and ACP.BDCODIGO = :WCODEVT
    
      into :WVALORINSSES;
      ------------------------------BASE INSS 13 e VRCPSEG13-------------------------------------------
      select sum(CP.BDVALOR) BDVALOR, max(coalesce(
             case
               when (ACP.BDCODCOL is distinct from ACP.BDCODTER) then CP.BDVRCPSEG
               else 0
             end, 0)) BDVRCPSEG
      from VRH_ESOCIAL_INFOBASECS_C CP
      inner join VRH_ESOCIAL_TARQUIVO ACP on (ACP.BDCODEMP = CP.BDCODEMP) and
            (ACP.BDCODIGO = CP.BDCODEVT) and
            (ACP.BDREFARQ = :PRREF) and
            (ACP.BDSTATUS = 2) and
            (coalesce(ACP.BDAPURACAOANUAL, 'FALSE') = 'FALSE')
       join vrh_emp_tcolcon cc on (acp.bdcodemp = cc.bdcodemp and acp.bdcodcol = cc.bdcodcol
        and cc.bdcpfcol = :prcpfcol)
      left outer join VRH_ESOCIAL_TARQUIVO RETIF on (RETIF.BDCODEMP = ACP.BDCODEMP) and
            (RETIF.BDEVENTOVINC = ACP.BDCODEVENTOORIG) and
            (RETIF.BDSTATUS = 2)
      where CP.BDCODEMP = :PRCODEMP and
            (coalesce(CP.BDTPVALOR, 0) in (0, 11, 12, 13, 14, 19)) and
            (coalesce(CP.BDIND13, 0) = 1) and
            (RETIF.BDCODEMP is null)
            and ACP.BDCODIGO = :WCODEVT
    
      into :WBASEINSS13ES, :WVRCPSEG13;
      --------------------------------VALOR INSS 13-----------------------------------------------
      select sum(CP.BDVALOR) BDVALOR
      from VRH_ESOCIAL_INFOBASECS_C CP
      inner join VRH_ESOCIAL_TARQUIVO ACP on (ACP.BDCODEMP = CP.BDCODEMP) and
            (ACP.BDCODIGO = CP.BDCODEVT) and
            (ACP.BDREFARQ = :PRREF) and
            (ACP.BDSTATUS = 2) and
            (coalesce(ACP.BDAPURACAOANUAL, 'FALSE') = 'FALSE')
       join vrh_emp_tcolcon cc on (acp.bdcodemp = cc.bdcodemp and acp.bdcodcol = cc.bdcodcol
        and cc.bdcpfcol = :prcpfcol)
      left outer join VRH_ESOCIAL_TARQUIVO RETIF on (RETIF.BDCODEMP = ACP.BDCODEMP) and
            (RETIF.BDEVENTOVINC = ACP.BDCODEVENTOORIG) and
            (RETIF.BDSTATUS = 2)
      where CP.BDCODEMP = :PRCODEMP and
            (coalesce(CP.BDTPVALOR, 0) in (21, 23)) and
            (coalesce(CP.BDIND13, 0) = 1) and
            (RETIF.BDCODEMP is null)
            and ACP.BDCODIGO = :WCODEVT
    
      into :WVALORINSS13ES;
      ---------------------------------VALOR SAL FAM------------------------------------------------
      select sum(CP.BDVALOR) BDVALOR
      from VRH_ESOCIAL_INFOBASECS_C CP
      inner join VRH_ESOCIAL_TARQUIVO ACP on (ACP.BDCODEMP = CP.BDCODEMP) and
            (ACP.BDCODIGO = CP.BDCODEVT) and
            (ACP.BDREFARQ = :PRREF) and
            (ACP.BDSTATUS = 2) and
            (coalesce(ACP.BDAPURACAOANUAL, 'FALSE') = 'FALSE')
       join vrh_emp_tcolcon cc on (acp.bdcodemp = cc.bdcodemp and acp.bdcodcol = cc.bdcodcol
        and cc.bdcpfcol = :prcpfcol)
      left outer join VRH_ESOCIAL_TARQUIVO RETIF on (RETIF.BDCODEMP = ACP.BDCODEMP) and
            (RETIF.BDEVENTOVINC = ACP.BDCODEVENTOORIG) and
            (RETIF.BDSTATUS = 2)
      where CP.BDCODEMP = :PRCODEMP and
            (coalesce(CP.BDTPVALOR, 0) in (31)) and
            (coalesce(CP.BDIND13, 0) = 0) and
            (RETIF.BDCODEMP is null)
            and ACP.BDCODIGO = :WCODEVT
    
      into :WVALORSALFAMES;
      ----------------------------------VALOR SAL FAM 13----------------------------------------------
      select sum(CP.BDVALOR) BDVALOR
      from VRH_ESOCIAL_INFOBASECS_C CP
      inner join VRH_ESOCIAL_TARQUIVO ACP on (ACP.BDCODEMP = CP.BDCODEMP) and
            (ACP.BDCODIGO = CP.BDCODEVT) and
            (ACP.BDREFARQ = :PRREF) and
            (ACP.BDSTATUS = 2) and
            (coalesce(ACP.BDAPURACAOANUAL, 'FALSE') = 'FALSE')
       join vrh_emp_tcolcon cc on (acp.bdcodemp = cc.bdcodemp and acp.bdcodcol = cc.bdcodcol
        and cc.bdcpfcol = :prcpfcol)
      left outer join VRH_ESOCIAL_TARQUIVO RETIF on (RETIF.BDCODEMP = ACP.BDCODEMP) and
            (RETIF.BDEVENTOVINC = ACP.BDCODEVENTOORIG) and
            (RETIF.BDSTATUS = 2)
      where CP.BDCODEMP = :PRCODEMP and
            (coalesce(CP.BDTPVALOR, 0) in (31)) and
            (coalesce(CP.BDIND13, 0) = 1) and
            (RETIF.BDCODEMP is null)
            and ACP.BDCODIGO = :WCODEVT
    
      into :WVALORSALFAM13ES;
      ------------------------------------VALOR SAL MAT-----------------------------------------------
      select sum(CP.BDVALOR) BDVALOR
      from VRH_ESOCIAL_INFOBASECS_C CP
      inner join VRH_ESOCIAL_TARQUIVO ACP on (ACP.BDCODEMP = CP.BDCODEMP) and
            (ACP.BDCODIGO = CP.BDCODEVT) and
            (ACP.BDREFARQ = :PRREF) and
            (ACP.BDSTATUS = 2) and
            (coalesce(ACP.BDAPURACAOANUAL, 'FALSE') = 'FALSE')
       join vrh_emp_tcolcon cc on (acp.bdcodemp = cc.bdcodemp and acp.bdcodcol = cc.bdcodcol
        and cc.bdcpfcol = :prcpfcol)
      left outer join VRH_ESOCIAL_TARQUIVO RETIF on (RETIF.BDCODEMP = ACP.BDCODEMP) and
            (RETIF.BDEVENTOVINC = ACP.BDCODEVENTOORIG) and
            (RETIF.BDSTATUS = 2)
      where CP.BDCODEMP = :PRCODEMP and
            (coalesce(CP.BDTPVALOR, 0) in (32)) and
            (coalesce(CP.BDIND13, 0) = 0) and
            (RETIF.BDCODEMP is null)
            and ACP.BDCODIGO = :WCODEVT
    
      into :WVALORSALMATEMPES;
      ------------------------------------VALOR SAL MAT 13---------------------------------------------
      select sum(CP.BDVALOR) BDVALOR
      from VRH_ESOCIAL_INFOBASECS_C CP
      inner join VRH_ESOCIAL_TARQUIVO ACP on (ACP.BDCODEMP = CP.BDCODEMP) and
            (ACP.BDCODIGO = CP.BDCODEVT) and
            (ACP.BDREFARQ = :PRREF) and
            (ACP.BDSTATUS = 2) and
            (coalesce(ACP.BDAPURACAOANUAL, 'FALSE') = 'FALSE')
       join vrh_emp_tcolcon cc on (acp.bdcodemp = cc.bdcodemp and acp.bdcodcol = cc.bdcodcol
        and cc.bdcpfcol = :prcpfcol)
      left outer join VRH_ESOCIAL_TARQUIVO RETIF on (RETIF.BDCODEMP = ACP.BDCODEMP) and
            (RETIF.BDEVENTOVINC = ACP.BDCODEVENTOORIG) and
            (RETIF.BDSTATUS = 2)
      where CP.BDCODEMP = :PRCODEMP and
            (coalesce(CP.BDTPVALOR, 0) in (32)) and
            (coalesce(CP.BDIND13, 0) = 1) and
            (RETIF.BDCODEMP is null)
            and ACP.BDCODIGO = :WCODEVT
    
      into :WVALORSALMATEMP13ES;
      -----------------------------------------------------------------------------------------------------

      ------------------------------------VALOR BASE PIS---------------------------------------------------
      select first 1 CP.BDIND13PIS, CP.BDTPVALORPISPASEP, CP.BDVALORPISPASEP, CP.BDVERSAOLAYOUTESOCIAL
      from VRH_ESOCIAL_INFOBASECS_C CP
      inner join VRH_ESOCIAL_TARQUIVO ACP on (ACP.BDCODEMP = CP.BDCODEMP) and
            (ACP.BDCODCOL = CP.BDCODCOL) and
            (ACP.BDCODIGO = CP.BDCODEVT) and
            (ACP.BDREFARQ = :PRREF) and
            (ACP.BDSTATUS = 2)
      join VRH_EMP_TCOLCON CC on (ACP.BDCODEMP = CC.BDCODEMP and
            ACP.BDCODCOL = CC.BDCODCOL and
            CC.BDCPFCOL = :PRCPFCOL)
      left outer join VRH_ESOCIAL_TARQUIVO RETIF on (RETIF.BDCODEMP = ACP.BDCODEMP) and
            (RETIF.BDEVENTOVINC = ACP.BDCODEVENTOORIG) and
            (RETIF.BDSTATUS = 2)
      where CP.BDCODEMP = :PRCODEMP and
            COALESCE(CP.BDIND13PIS, 0) = 0 and
            (RETIF.BDCODEMP is null)
            and ACP.BDCODIGO = :WCODEVT

      into  :WIND13PIS, :WTPVALORPISPASEP, :WVALORPISPASEP, :WVERSAOLAYOUTESOCIAL;
      -----------------------------------------------------------------------------------------------------

    end

  else if (PR13 = 1) then
    begin
      -----------------------------------------------------------------------------------------------------
      select sum(CP.BDVALOR) BDVALOR, max(coalesce(
                       case
                         when (ACP.BDCODCOL is distinct from ACP.BDCODTER) then CP.BDVRCPSEG
                         else 0
                       end, 0)) BDVRCPSEG
                from VRH_ESOCIAL_INFOBASECS_C CP
                inner join VRH_ESOCIAL_TARQUIVO ACP on (ACP.BDCODEMP = CP.BDCODEMP) and
                      (ACP.BDCODCOL = CP.BDCODCOL) and
                      (ACP.BDCODIGO = CP.BDCODEVT) and
                      (ACP.BDREFARQ = :PRREF) and
                      (ACP.BDSTATUS = 2) and
                      (coalesce(ACP.BDAPURACAOANUAL, 'FALSE') = 'TRUE')
                left outer join VRH_ESOCIAL_TARQUIVO RETIF on (RETIF.BDCODEMP = ACP.BDCODEMP) and
                      (RETIF.BDEVENTOVINC = ACP.BDCODEVENTOORIG) and
                      (RETIF.BDSTATUS = 2)
                where CP.BDCODEMP = :PRCODEMP and
                      CP.BDCODCOL = :PRCODCOL and
                      (coalesce(CP.BDTPVALOR, 0) in (0, 11, 12, 13, 14, 19)) and
                      (coalesce(CP.BDIND13, 0) = 1) and
                      (RETIF.BDCODEMP is null)

       into :WBASEINSS13ES, :WVRCPSEG;

       ---------------------------------------------------------------------------------------------------
       select sum(CP.BDVALOR) BDVALOR
                from VRH_ESOCIAL_INFOBASECS_C CP
                inner join VRH_ESOCIAL_TARQUIVO ACP on (ACP.BDCODEMP = CP.BDCODEMP) and
                      (ACP.BDCODCOL = CP.BDCODCOL) and
                      (ACP.BDCODIGO = CP.BDCODEVT) and
                      (ACP.BDREFARQ = :PRREF) and
                      (ACP.BDSTATUS = 2) and
                      (coalesce(ACP.BDAPURACAOANUAL, 'FALSE') = 'TRUE')
                left outer join VRH_ESOCIAL_TARQUIVO RETIF on (RETIF.BDCODEMP = ACP.BDCODEMP) and
                      (RETIF.BDEVENTOVINC = ACP.BDCODEVENTOORIG) and
                      (RETIF.BDSTATUS = 2)
                where CP.BDCODEMP = :PRCODEMP and
                      CP.BDCODCOL = :PRCODCOL and
                      (coalesce(CP.BDTPVALOR, 0) in (21, 23)) and
                      (coalesce(CP.BDIND13, 0) = 1) and
                      (RETIF.BDCODEMP is null)

         into :WVALORINSS13ES;
        --------------------------------------------------------------------------------------------------
        select  sum(CP.BDVALOR) BDVALOR
                from VRH_ESOCIAL_INFOBASECS_C CP
                inner join VRH_ESOCIAL_TARQUIVO ACP on (ACP.BDCODEMP = CP.BDCODEMP) and
                      (ACP.BDCODCOL = CP.BDCODCOL) and
                      (ACP.BDCODIGO = CP.BDCODEVT) and
                      (ACP.BDREFARQ = :PRREF) and
                      (ACP.BDSTATUS = 2) and
                      (coalesce(ACP.BDAPURACAOANUAL, 'FALSE') = 'TRUE')
                left outer join VRH_ESOCIAL_TARQUIVO RETIF on (RETIF.BDCODEMP = ACP.BDCODEMP) and
                      (RETIF.BDEVENTOVINC = ACP.BDCODEVENTOORIG) and
                      (RETIF.BDSTATUS = 2)
                where CP.BDCODEMP = :PRCODEMP and
                      CP.BDCODCOL = :PRCODCOL and 
                      (coalesce(CP.BDTPVALOR, 0) in (31)) and
                      (coalesce(CP.BDIND13, 0) = 1) and
                      (RETIF.BDCODEMP is null)

        into :WVALORSALFAMES;

        ---------------------------------------------------------------------------------------------------
        select sum(CP.BDVALOR) BDVALOR
                from VRH_ESOCIAL_INFOBASECS_C CP
                inner join VRH_ESOCIAL_TARQUIVO ACP on (ACP.BDCODEMP = CP.BDCODEMP) and
                      (ACP.BDCODCOL = CP.BDCODCOL) and
                      (ACP.BDCODIGO = CP.BDCODEVT) and
                      (ACP.BDREFARQ = :PRREF) and
                      (ACP.BDSTATUS = 2) and
                      (coalesce(ACP.BDAPURACAOANUAL, 'FALSE') = 'TRUE')
                left outer join VRH_ESOCIAL_TARQUIVO RETIF on (RETIF.BDCODEMP = ACP.BDCODEMP) and
                      (RETIF.BDEVENTOVINC = ACP.BDCODEVENTOORIG) and
                      (RETIF.BDSTATUS = 2)
                where CP.BDCODEMP = :PRCODEMP and
                      CP.BDCODCOL = :PRCODCOL and
                      (coalesce(CP.BDTPVALOR, 0) in (32)) and
                      (coalesce(CP.BDIND13, 0) = 1) and
                      (RETIF.BDCODEMP is null)
        into :WVALORSALMATEMPES;

     ------------------------------------VALOR BASE PIS 13-------------------------------------------------
      select first 1 CP.BDIND13PIS, CP.BDTPVALORPISPASEP, CP.BDVALORPISPASEP, CP.BDVERSAOLAYOUTESOCIAL
      from VRH_ESOCIAL_INFOBASECS_C CP
      inner join VRH_ESOCIAL_TARQUIVO ACP on (ACP.BDCODEMP = CP.BDCODEMP) and
            (ACP.BDCODCOL = CP.BDCODCOL) and
            (ACP.BDCODIGO = CP.BDCODEVT) and
            (ACP.BDREFARQ = :PRREF) and
            (ACP.BDSTATUS = 2)
      join VRH_EMP_TCOLCON CC on (ACP.BDCODEMP = CC.BDCODEMP and
            ACP.BDCODCOL = CC.BDCODCOL and
            CC.BDCPFCOL = :PRCPFCOL)
      left outer join VRH_ESOCIAL_TARQUIVO RETIF on (RETIF.BDCODEMP = ACP.BDCODEMP) and
            (RETIF.BDEVENTOVINC = ACP.BDCODEVENTOORIG) and
            (RETIF.BDSTATUS = 2)
      where CP.BDCODEMP = :PRCODEMP and
            COALESCE(CP.BDIND13PIS, 1) = 1 and
            (RETIF.BDCODEMP is null)
            and ACP.BDCODIGO = :WCODEVT

      into  :WIND13PIS, :WTPVALORPISPASEP, :WVALORPISPASEP13, :WVERSAOLAYOUTESOCIAL;
      -----------------------------------------------------------------------------------------------------

        ----------------------------------------------------------------------------------------------------
    end
  BDCODEMP = :PRCODEMP;
  BDCODCOL = :PRCODCOL;
  BDBASEINSSES = :WBASEINSSES;
  BDVALORINSSES = :WVALORINSSES;
  BDBASEINSS13ES = :WBASEINSS13ES;
  BDVALORINSS13ES = :WVALORINSS13ES;
  BDVALORSALFAMES = coalesce(:WVALORSALFAMES, 0) + coalesce(:WVALORSALFAM13ES, 0);
  BDVALORSALMATEMPES = coalesce(:WVALORSALMATEMPES, 0) + coalesce(:WVALORSALMATEMP13ES, 0);

  -- Valores base pis
  BDIND13PIS            = :WIND13PIS; -- -111 - Não existe registro / 0 - Folha normal / 1 - Décimo terceiro
  BDTPVALORPISPASEP     = :WTPVALORPISPASEP;
  BDVALORPISPASEP       = coalesce(:WVALORPISPASEP, 0);
  BDVALORPISPASEP13     = coalesce(:WVALORPISPASEP13, 0);
  BDVERSAOLAYOUTESOCIAL = coalesce(:WVERSAOLAYOUTESOCIAL, '');

  if (coalesce(:WVRCPSEG, 0) > 0) then
    BDVRCPSEG = :WVRCPSEG;
  else
  if (coalesce(:WVRCPSEG13, 0) > 0) then
    BDVRCPSEG = :WVRCPSEG13;

  suspend;
end^

/* Restore proc. body: SP_REL_TOT_5001 */
create or alter procedure SP_REL_TOT_5001 (
    PRCODEMP varchar(30000),
    PRREF integer,
    PR13 integer,
    PRFILTROCPF varchar(30000),
    PRSEPARARFOLHAS integer)
returns (
    BDCODEMPORD integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCOLTER integer,
    BDCONTRCOL integer,
    BDGRUPOCLA integer,
    BDNOMCOL varchar(70),
    BDCPFCOL varchar(14),
    BDCNPJEMP varchar(18),
    BDNOMEMP varchar(100),
    BDBASEINSS numeric(18,6),
    BDBASEINSSES numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEINSS13ES numeric(18,6),
    BDVALORINSS numeric(18,6),
    BDVALORINSSES numeric(18,6),
    BDVALORINSS13 numeric(18,6),
    BDVALORINSS13ES numeric(18,6),
    BDVALORSALFAM numeric(18,6),
    BDVALORSALFAMES numeric(18,6),
    BDVALORSALMATEMP numeric(18,6),
    BDVALORSALMATEMPES numeric(18,6),
    BDVRCPSEG numeric(18,6),
    BDVRDEDDEP numeric(18,6),
    BDVRDEDDEPES numeric(18,6),
    BDBASEPENSAO numeric(18,6),
    BDBASEPENSAOES numeric(18,6),
    BDBASEIRRF numeric(18,6),
    BDBASEIRRFES numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDBASEIRRF13ES numeric(18,6),
    BDBASEIRRFFERIAS numeric(18,6),
    BDBASEIRRFFERIASES numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDBASEIRRFPLRES numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDVALORIRRFES numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDVALORIRRF13ES numeric(18,6),
    BDVALORIRRFFERIAS numeric(18,6),
    BDVALORIRRFFERIASES numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDVALORIRRFPLRES numeric(18,6),
    BDBASEFGTS numeric(18,6),
    BDBASEFGTSES numeric(18,6),
    BDVALORFGTS numeric(18,6),
    BDVALORFGTSES numeric(18,6),
    BDBASEFGTSRES numeric(18,6),
    BDBASEFGTSRESES numeric(18,6),
    BDVALORFGTSRES numeric(18,6),
    BDVALORFGTSRESES numeric(18,6),
    BDBASEAVPREV numeric(18,6),
    BDBASEAVPREVES numeric(18,6),
    BDVALORAVPREV numeric(18,6),
    BDVALORAVPREVES numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDBASEFGTS13ES numeric(18,6),
    BDVALORFGTS13 numeric(18,6),
    BDVALORFGTS13ES numeric(18,6),
    BDVALORINSSPLR numeric(18,6),
    BDVALORINSSRRA numeric(18,6),
    BDVRDEDDEP13 numeric(18,6),
    BDVRDEDDEPES13 numeric(18,6),
    BDVRDEDDEPPLR numeric(18,6),
    BDVRDEDDEPRRA numeric(18,6),
    BDBASEPENSAO13 numeric(18,6),
    BDBASEPENSAO13ES numeric(18,6),
    BDBASEPENSAOPLR numeric(18,6),
    BDBASEPENSAOPLRES numeric(18,6),
    BDBASEPENSAORRA numeric(18,6),
    BDBASEPENSAORRAES numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDBASEIRRFRRAES numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDVALORIRRFRRAES numeric(18,6),
    BDVRDEDDEPPLRES numeric(18,6),
    BDVRDEDDEPRRAES numeric(18,6),
    BDVALORINSSRRAES numeric(18,6),
    BDBASEPREV numeric(18,6),
    BDBASEPREV13 numeric(18,6),
    BDBASEPREVPLR numeric(18,6),
    BDBASEPREVRRA numeric(18,6),
    BDBASEPREVES numeric(18,6),
    BDBASEPREV13ES numeric(18,6),
    BDTIPO integer,
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDCATEGORIAESOCIAL integer,
    BDCODCLATRI integer,
    BDSEST numeric(18,6),
    BDSENAT numeric(18,6),
    BDSESTES numeric(18,6),
    BDSENATES numeric(18,6),
    BDCTS5001 integer,
    BDBASEFGTS13RESC numeric(9,2),
    BDVALORFGTS13RESC numeric(9,2),
    BDBASEFGTS13RESCES numeric(9,2),
    BDVALORFGTS13RESCES numeric(9,2),
    BDECONSIGNADO numeric(18,6),
    BDECONSIGNADORESC numeric(18,6),
    BDINSTITUICAOFINANC integer,
    BDNROCONTRATOECONSIGNADO varchar(30),
    BDINSTITUICAOFINANCES integer,
    BDNROCONTRATOECONSIGNADOES varchar(30),
    BDVALORECONSIGNADOES numeric(18,6),
    BDIND13PISES integer,
    BDTPVALORPISPASEPES integer,
    BDVALORPISPASEPES numeric(18,6),
    BDVALORPISPASEP13ES numeric(18,6),
    BDVALORPISPASEP numeric(18,6),
    BDVALORPISPASEP13 numeric(18,6),
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000))
as
declare variable WSQLPRINCIPAL varchar(30000);
declare variable WLISTAEMP varchar(30000);
declare variable WCPFANTERIOR varchar(14);
declare variable WULTDIA varchar(2);
declare variable WMES smallint;
declare variable WANO integer;
declare variable WCALCULOS integer;
declare variable WTEMEVENTO integer;
declare variable WTEMCALCFN integer;
declare variable WTEMCALCFT integer;
declare variable WSQL2 varchar(30000);
declare variable WTPADM integer;
declare variable WTEMCONFIGIMPOSTO integer;
declare variable WVERSAOLAYOUTESOCIAL varchar(10);
declare variable WCONTROLESUSPEND integer;
declare variable WEMPANTERIOR integer;
declare variable WVALVERBA13 numeric(18,6);
declare variable WINCIDENCIAPIS integer;
declare variable WCONTRATOTERC integer;
declare variable WCOLCONANTERIOR integer;
declare variable WCONTROLARETORNOVALPIS integer;
declare variable WTIPOCALCULOANT integer;
declare variable WTIPOCALC integer;
begin
  BDCODEMPORD = 0;
  BDCODEMP = 0;
  BDCODCOL = 0;
  BDCOLTER = 0;
  BDCONTRCOL = 0;
  BDGRUPOCLA = 0;
  BDNOMCOL = '';
  BDCPFCOL = '';
  BDCNPJEMP = '';
  BDNOMEMP = '';
  BDBASEINSS = 0;
  BDBASEINSSES = 0;
  BDBASEINSS13 = 0;
  BDBASEINSS13ES = 0;
  BDVALORINSS = 0;
  BDVALORINSSES = 0;
  BDVALORINSS13 = 0;
  BDVALORINSS13ES = 0;
  BDVALORSALFAM = 0;
  BDVALORSALFAMES = 0;
  BDVALORSALMATEMP = 0;
  BDVALORSALMATEMPES = 0;
  BDVRCPSEG = 0;
  BDVRDEDDEP = 0;
  BDVRDEDDEPES = 0;
  BDBASEPENSAO = 0;
  BDBASEPENSAOES = 0;
  BDBASEIRRF = 0;
  BDBASEIRRFES = 0;
  BDBASEIRRF13 = 0;
  BDBASEIRRF13ES = 0;
  BDBASEIRRFFERIAS = 0;
  BDBASEIRRFFERIASES = 0;
  BDBASEIRRFPLR = 0;
  BDBASEIRRFPLRES = 0;
  BDVALORIRRF = 0;
  BDVALORIRRFES = 0;
  BDVALORIRRF13 = 0;
  BDVALORIRRF13ES = 0;
  BDVALORIRRFFERIAS = 0;
  BDVALORIRRFFERIASES = 0;
  BDVALORIRRFPLR = 0;
  BDVALORIRRFPLRES = 0;
  BDBASEFGTS = 0;
  BDBASEFGTSES = 0;
  BDBASEFGTSRES = 0;
  BDBASEFGTSRESES = 0;
  BDBASEAVPREV = 0;
  BDBASEAVPREVES = 0;
  BDBASEFGTS13 = 0;
  BDBASEFGTS13ES = 0;
  BDVALORFGTS = 0;
  BDVALORFGTSES = 0;
  BDVALORFGTSRES = 0;
  BDVALORFGTSRESES = 0;
  BDVALORAVPREV = 0;
  BDVALORAVPREVES = 0;
  BDVALORFGTS13 = 0;
  BDVALORFGTS13ES = 0;
  BDBASEFGTS13RESC = 0;
  BDVALORFGTS13RESC = 0;
  BDBASEFGTS13RESCES = 0;
  BDVALORFGTS13RESCES = 0;

  --#206247 - Início - É preciso criar os campos com valores zero pois somente é feito o select all da SP para a emissão do relatório;
  BDECONSIGNADO = 0;
  BDECONSIGNADORESC = 0;
  BDINSTITUICAOFINANC = 0;
  BDNROCONTRATOECONSIGNADO = 'só no S-5003';
  BDINSTITUICAOFINANCES = 0;
  BDNROCONTRATOECONSIGNADOES = 'só no S-5003';
  BDVALORECONSIGNADOES = 0;
  --#206247 - Fim;

  BDTIPO = 5001;
  BDCALCULOS = 0;
  BDCOUNTFC = 0;
  BDCATEGORIAESOCIAL = 0;
  BDCODCLATRI = 0;
  BDSEST = 0;
  BDSENAT = 0;
  BDSESTES = 0;
  BDSENATES = 0;
  BDCTS5001 = 0;
  BDVALORINSSPLR = 0;
  BDVALORINSSRRA = 0;
  BDVRDEDDEP13 = 0;
  BDVRDEDDEPES13 = 0;
  BDVRDEDDEPPLR = 0;
  BDVRDEDDEPRRA = 0;
  BDBASEPENSAO13 = 0;
  BDBASEPENSAO13ES = 0;
  BDBASEPENSAOPLR = 0;
  BDBASEPENSAOPLRES = 0;
  BDBASEPENSAORRA = 0;
  BDBASEPENSAORRAES = 0;
  BDBASEIRRFRRA = 0;
  BDBASEIRRFRRAES = 0;
  BDVALORIRRFRRA = 0;
  BDVALORIRRFRRAES = 0;
  BDVRDEDDEPPLRES = 0;
  BDVRDEDDEPRRAES = 0;
  BDVALORINSSRRAES = 0;
  BDBASEPREV = 0;
  BDBASEPREV13 = 0;
  BDBASEPREVPLR = 0;
  BDBASEPREVRRA = 0;
  BDBASEPREVES = 0;
  BDBASEPREV13ES = 0;
  WCPFANTERIOR = '';
  WEMPANTERIOR = -1;
  WCOLCONANTERIOR = -1;
  WCONTROLARETORNOVALPIS = -1;
  WTEMCONFIGIMPOSTO = 0;

  WSQLPRINCIPAL = 'SELECT * from ( ' ||
                  'SELECT COALESCE(E.BDCODMATRIZ, COL.BDCODEMP) BDCODMATRIZ, E.BDCNPJEMP, EREF.BDNOMEMP ,COL.BDCODEMP,COL.BDCODCOL, COL.BDCPFCOL, COLCAD.BDNOMCOL, COL.BDCONTRCOL ' ||
                  'FROM VRH_EMP_TCOLCON COL ' ||
                  ' INNER JOIN TEMPRESAS E ON E.BDCODEMP = COL.BDCODEMP ' ||
                  ' inner join TEMPRESAS_REF EREF on EREF.BDCODEMP = E.BDCODEMP and EREF.BDREFEMP = (select max(BDREFEMP) from TEMPRESAS_REF WHERE BDCODEMP = E.BDCODEMP)' ||
                  ' inner join VRH_EMP_TCOLCON_CAD COLCAD on COLCAD.BDCODEMP = COL.BDCODEMP and COLCAD.BDCODCOL = COL.BDCODCOL and COLCAD.BDREFCOL = (select max(BDREFCOL) from VRH_EMP_TCOLCON_CAD WHERE BDCODEMP = COL.BDCODEMP and BDCODCOL = COL.BDCODCOL and BDREFCOL <= ' || PRREF || ')' ||
                  'where UPPER(E.BDEXPINIESOCIAL) = ' || '''' || 'TRUE' || '''';

  if ((PRCODEMP is not null) and (PRCODEMP <> '')) then
     begin
       WSQLPRINCIPAL = WSQLPRINCIPAL || ' and (((((not exists(select DOC.BDCODEMP ' || /*Contribuinte com baixa*/
                                               'from VRH_EMP_TCON_DOC DOC ' ||
                                               'where (DOC.BDCODEMP = COLCAD.BDCODEMP) and ' ||
                                                     '(DOC.BDCODCOL = COLCAD.BDCODCOL) and ' ||
                                                     '(DOC.BDDATABAIXACOL < ''' || substring(cast(PRREF as varchar(6)) from 1 for 4) || '/' || substring(cast(PRREF as varchar(6)) from 5 for 2) || '/01' || '''))) ' ||
                                         'and (not exists(select RESC.BDCODEMP ' || /*Colaborador com rescisão*/
                                               'from VRH_EMP_TRESCISAO RESC ' ||
                                               'where (RESC.BDCODEMP = COLCAD.BDCODEMP) and ' ||
                                                     '(RESC.BDCODCOL = COLCAD.BDCODCOL) and ' ||
                                                     '(RESC.BDREFRESCISAO < ' || PRREF || ')))' ||
                                         ' and (not exists(select TRAN.BDCODEMPORIG ' || /*Colaborador transferido*/
                                               'from VRH_EMP_TTRANSCOL TRAN ' ||
                                               'where (TRAN.BDCODEMPORIG = COLCAD.BDCODEMP) and ' ||
                                                     '(TRAN.BDCODCOLORIG = COLCAD.BDCODCOL) and ' ||
                                                     '(TRAN.BDREFTRF < ' || PRREF || ')))) or exists(Select bdcodcol from SP_VRHF_EXISTE_COMPLEMENTAR(COLCAD.BDCODEMP, COLCAD.BDCODCOL,' || PRREF || ')))) or '||
                                         '(exists (select FF.BDCODEMP from VRHF_EMP_TFICHAIRRF FF where FF.BDCODEMP = COL.BDCODEMP and FF.BDCODCOL = COL.BDCODCOL and FF.BDREFIRFIR = '||PRREF||'))) ';
   
       if (position('=', PRCODEMP) > 0) then
          WLISTAEMP = substring(PRCODEMP from position('=', PRCODEMP) + 1 for char_length(PRCODEMP));
       if (position('in', PRCODEMP) > 0) then
          WLISTAEMP = substring(PRCODEMP from position('in', PRCODEMP) + 3 for char_length(PRCODEMP));
   
       if (position('(', WLISTAEMP) > 0) then
          WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ((E.BDCODMATRIZ in ' || WLISTAEMP || ') OR (COL.BDCODEMP in ' || WLISTAEMP || '))';
       else
          WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ((E.BDCODMATRIZ in (' || WLISTAEMP || ')) OR (COL.BDCODEMP in (' || WLISTAEMP || ')))';
     end

  if ((PRREF is not null) and (PRREF <> 0)) then
     begin
       WMES = cast(substring(cast(PRREF as varchar(6)) from 5 for 2) as integer);
       WANO = cast(substring(cast(PRREF as varchar(6)) from 1 for 4) as integer);

       select ULTDIA
       from ULTIMO_DIA_MES(:WMES, :WANO)
       into WULTDIA;
       WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND (COL.BDDATAADMCOL <=''' || substring(cast(PRREF as varchar(6)) from 5 for 2) || '/' || WULTDIA || '/' || substring(cast(PRREF as varchar(6)) from 1 for 4) || ''')';
     end

  ---***FILTRO DE CPF***---
  if ((PRFILTROCPF is not null) and  (PRFILTROCPF <> '')) then
     WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ' || PRFILTROCPF;

  if (PR13 = 0) then
     begin
       WSQLPRINCIPAL = WSQLPRINCIPAL || ' union all ';
       WSQLPRINCIPAL = WSQLPRINCIPAL || 'select coalesce(E.BDCODMATRIZ, TERC.BDCODEMP) BDCODMATRIZ, E.BDCNPJEMP, EREF.BDNOMEMP, TERC.BDCODEMP, TERC.BDCODTER BDCODCOL,' ||
                                        ' coalesce(case '||
                                                   ' when char_length(TER.BDCGCTER) = 14 then TER.BDCGCTER ' ||
                                                   ' when char_length(TERR.bdcgcter) = 14 then TERR.bdcgcter ' ||
                                                   ' when char_length(terrh.BDCPFMEITER) = 14 then terrh.BDCPFMEITER ' ||
                                                 ' end, ' || '''''' || ') as BDCPFCOL,' ||
                                                 ' TERR.BDNOMETER BDNOMCOL ,2 BDCONTRCOL ' ||
                                        ' from VRHF_BASE_CALC_TERC TERC  ' ||
                                        ' inner join TTERCEIRO TER on TER.BDCODTER = TERC.BDCODTER ' ||
                                        ' inner join TTERCEIRO_RH terrh on terrh.bdcodter = TERC.BDCODTER ' ||
                                        ' inner join TTERCEIRO_REF TERR on TERR.BDCODTER = TER.BDCODTER and TERR.BDREFEMP = (select max(TERR2.BDREFEMP) from TTERCEIRO_REF TERR2 where TERR2.BDCODTER = TERR.BDCODTER and TERR2.BDREFEMP <= ' || :PRREF || ')' ||
                                        ' inner join TEMPRESAS E on E.BDCODEMP = TERC.BDCODEMP and ' || ' upper(E.BDEXPINIESOCIAL) = ''TRUE'' ' ||
                                        ' inner join TEMPRESAS_REF EREF on EREF.BDCODEMP = E.BDCODEMP and  ' || ' EREF.BDREFEMP = (select max(BDREFEMP) ' ||
                                        'from TEMPRESAS_REF  ' || ' where BDCODEMP = E.BDCODEMP) ' ||
                                        'where ((select BDDATA ' || ' from SP_PARSE_DATE(TERC.BDDATASERV, ''yyyymm'')) = ' || :PRREF || ') ';
   
       if ((PRCODEMP is not null) and (PRCODEMP <> '')) then
          begin
            if (position('(', WLISTAEMP) > 0) then
              WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ((E.BDCODMATRIZ in ' || WLISTAEMP || ') OR (TERC.BDCODEMP in ' || WLISTAEMP || '))';
            else
              WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ((E.BDCODMATRIZ in (' || WLISTAEMP || ')) OR (TERC.BDCODEMP in (' || WLISTAEMP || ')))';
          end
      
       ---***FILTRO DE CPF***---
       if ((PRFILTROCPF is not null) and (PRFILTROCPF <> '')) then
          WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ' || replace(PRFILTROCPF, 'COL.BDCPFCOL', 'TER.BDCGCTER');

       WSQLPRINCIPAL = WSQLPRINCIPAL || ' group by BDCODMATRIZ, E.BDCNPJEMP, EREF.BDNOMEMP, TERC.BDCODEMP, TERC.BDCODTER, BDCPFCOL , TERR.BDNOMETER , BDCONTRCOL ';
     end

  WSQLPRINCIPAL = WSQLPRINCIPAL || ') ORDER BY COALESCE(BDCODMATRIZ,BDCODEMP), BDCPFCOL, BDCODCOL';

  --Nesse SQL principal foi adicionado uma parte pra buscar cadastros de autonomos.
  --Dentro do laço, deve verificar o WCONTRCOL, se for 2, é autônomo, então deve entrar na rotina de busca de autonomo.
  for execute statement WSQLPRINCIPAL into :BDCODEMPORD, :bdCNPJEMP, :bdNOMEMP, :bdCODEMP, :bdCODCOL, :bdCPFCOL, :bdNOMCOL, :bdCONTRCOL do
  begin
    BDBASEINSS = 0;
    BDBASEINSS13 = 0;
    BDBASEAVPREV = 0;
    BDVALORINSS = 0;
    BDVALORINSS13 = 0;
    BDVALORAVPREV = 0;
    BDVALORSALFAM = 0;
    BDVALORSALMATEMP = 0;

    BDBASEINSSES = 0;
    BDBASEINSS13ES = 0;
    BDBASEAVPREVES = 0;
    BDVALORINSSES = 0;
    BDVALORINSS13ES = 0;
    BDVALORAVPREVES = 0;

    BDSEST = 0;
    BDSENAT = 0;
    BDSESTES = 0;
    BDSENATES = 0;

    BDVALORPISPASEPES = 0;
    BDVALORPISPASEP13ES = 0;
    BDVALORPISPASEP = 0;
    BDVALORPISPASEP13 = 0;
    BDTAGSTR = '';
    BDDESCRICAOFOLHA = '';

    BDCALCULOS = 0;
    WCALCULOS = 0;
    BDCOUNTFC = 0;
    bdGRUPOCLA = 0;
    BDCATEGORIAESOCIAL = 0;
    BDCOLTER = 0;
    WTIPOCALCULOANT = 0;

    ---***FILTRO DO IMPOSTO VÍNCULADO A EMPRESA***---
    if (WEMPANTERIOR <> BDCODEMP) then
      BEGIN
         WEMPANTERIOR = BDCODEMP;

         select IMP.BDCODIMP AS BDTEMCONFIGIMP
         from TEMPRESAIMPOSTO EMPTRIB
         inner join TIMPOSTO IMP on (EMPTRIB.BDCODIMP = IMP.BDCODIMP)
         where EMPTRIB.BDCODEMP = :BDCODEMP and
               EMPTRIB.BDREFEMP <= :PRREF and
               ((coalesce(BDREFFIMIMP, 0) = 0) or (BDREFFIMIMP >= :PRREF)) and
               IMP.BDTIPORETENCAO = 1 and
               IMP.BDDOCARRECADACAO = 1 and
               IMP.BDCODSIS = 2 and
               IMP.BDTIPOIMPDOC = 2
         INTO :WTEMCONFIGIMPOSTO;

         if (COALESCE(WTEMCONFIGIMPOSTO,0) <> 0) then
            WTEMCONFIGIMPOSTO = 1;
      END

    --***CLASSIFICAÇÃO TRIBUTÁRIA***--
    select first 1 BDCODCLATRI
    from VRHF_BASE_TEMPESOCIAL ES
    where ES.BDCODEMP in (:bdCODEMP) and
          (ES.BDREFEMP <= :PRREF)
    order by BDREFEMP desc
    into :bdCODCLATRI;

    --***BUSCA DA CATEGORIA ESOCIAL E GRUPO DE CLASSE***--
    if (bdCONTRCOL <> 2) then ---***SE FOR DIFERENTE DE AUTONÔMOS***---
       begin
         select first 1 FGTS.BDCATEGORIAESOCIAL, CLA.BDGRUPOCLA
         from VRHF_EMP_TCOLCON_FGTSGPS FGTS
         left outer join VRH_EMP_TCOLCON_VINC VINC on VINC.BDCODEMP = FGTS.BDCODEMP and
               VINC.BDCODCOL = FGTS.BDCODCOL and
               VINC.BDREFCOL <= :PRREF
         left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
         where FGTS.BDCODEMP in (:bdCODEMP) and
               FGTS.BDCODCOL = :bdCODCOL and
               (FGTS.BDREFCOL <= :PRREF)
         order by FGTS.BDREFCOL desc
         into :BDCATEGORIAESOCIAL, :bdGRUPOCLA;
       end

    WCONTROLESUSPEND = 0;

    if (WCONTROLARETORNOVALPIS = 1) then
       WCONTROLARETORNOVALPIS = -1;

    ---***DADOS DE APURAÇÃO MENSAL***---
    if (PR13 = 0) then
       begin
         if (bdCONTRCOL <> 2) then
            begin
              --***BUSCA DE VALORES DO ÚNICO***--
              for select coalesce(BDBINSS,0)+coalesce(BDBINSSFEFOL,0),coalesce(BDINSS,0)+coalesce(BDINSSFEFOL,0),BDBINSS13,BDINSS13,coalesce(BDCOUNTFC, 0),BDCALCULOS,BDVALORSALFAM,BDVALORSALMATEMP,BDVALORPISPASEP,BDVALORPISPASEP13,BDTAGSTR,BDDESCRICAOFOLHA,BDTIPOCALCULO
              from SP_RETORNA_BASE_INSS(:bdCODEMP, :bdCODCOL, :PRREF, :WTEMCONFIGIMPOSTO, :PRSEPARARFOLHAS)
              into :BDBASEINSS,:BDVALORINSS,:BDBASEINSS13,:BDVALORINSS13,:BDCOUNTFC,:WCALCULOS,:BDVALORSALFAM,:BDVALORSALMATEMP,:BDVALORPISPASEP,:BDVALORPISPASEP13,:BDTAGSTR,:BDDESCRICAOFOLHA, :WTIPOCALC do
                begin
                  if (WCONTROLESUSPEND = 1) then
                     WCONTROLESUSPEND = 0;

                  if (WTIPOCALCULOANT = 0) then
                     WTIPOCALCULOANT = WTIPOCALC;

                  if ((bdCPFCOL <> WCPFANTERIOR)) then
                     begin
                        WCPFANTERIOR = BDCPFCOL;
                        bdBASEINSSES = 0;
                        bdVALORINSSES = 0;
                        bdBASEINSS13ES = 0;
                        bdVALORINSS13ES = 0;
                        bdVALORSALFAMES = 0;
                        bdVALORSALMATEMPES = 0;
                        bdVRCPSEG = 0;
              
                        --***BUSCA DE VALORES DO ESOCIAL***--
                        select BDBASEINSSES,BDVALORINSSES,BDBASEINSS13ES,BDVALORINSS13ES,BDVALORSALFAMES,BDVALORSALMATEMPES,BDVRCPSEG,BDIND13PIS,BDTPVALORPISPASEP,BDVALORPISPASEP,BDVALORPISPASEP13,BDVERSAOLAYOUTESOCIAL
                        from SP_RETORNA_BASE_INSS_ES(:bdCODEMP, :bdCODCOL, :PRREF, 0, :bdCPFCOL)
                        into :bdBASEINSSES,:bdVALORINSSES,:bdBASEINSS13ES,:bdVALORINSS13ES,:bdVALORSALFAMES,:bdVALORSALMATEMPES,:bdVRCPSEG,:bdIND13PISES,:bdTPVALORPISPASEPES,:bdVALORPISPASEPES,:bdVALORPISPASEP13ES,:wVERSAOLAYOUTESOCIAL;
                     end
                  else
                     begin
                       WSQL2 = 'select BDTIPOADMCOL from VRH_EMP_TCOL_ADM where BDCODEMP = ' || :bdCODEMP || ' and BDCODCOL = ' || :bdCODCOL;
                       execute statement WSQL2 into WTPADM;
             
                       --***TRANSFERÊNCIAS***--
                       if (WTPADM = 7) then
                          begin
                             select BDBASEINSSES,BDVALORINSSES,BDBASEINSS13ES,BDVALORINSS13ES,BDVALORSALFAMES,BDVALORSALMATEMPES,BDVRCPSEG,BDIND13PIS,BDTPVALORPISPASEP,BDVALORPISPASEP,BDVALORPISPASEP13,BDVERSAOLAYOUTESOCIAL
                             from SP_RETORNA_BASE_INSS_ES(:bdCODEMP, :bdCODCOL, :PRREF, 0, :bdCPFCOL)
                             into :bdBASEINSSES,:bdVALORINSSES,:bdBASEINSS13ES,:bdVALORINSS13ES,:bdVALORSALFAMES,:bdVALORSALMATEMPES,:bdVRCPSEG,:bdIND13PISES,:bdTPVALORPISPASEPES,:bdVALORPISPASEPES,:bdVALORPISPASEP13ES,:wVERSAOLAYOUTESOCIAL;
                          end
                       else
                          begin
                            if (bdBASEINSSES = null) then
                               begin
                                  bdBASEINSSES = 0;
                                  bdVALORINSSES = 0;
                                  bdBASEINSS13ES = 0;
                                  bdVALORINSS13ES = 0;
                                  bdVALORSALFAMES = 0;
                                  bdVALORSALMATEMPES = 0;
                                  bdVRCPSEG = 0;
                               end
                          end
                     end

                  BDCALCULOS = coalesce(BDCALCULOS, 0) + coalesce(WCALCULOS, 0);
                  BDCOLTER = 1;
              
                  if (bdCONTRCOL = 2) then
                    BDCOLTER = 2;
              
                  if (BDCTS5001 = 0) then
                    BDCTS5001 = -10;
              
                  --***TRATAMENTO PARA ZERAR AS BASES DE INSS QUANDO NEGATIVAS***--
                  if (BDBASEINSS < 0) then
                    BDBASEINSS = 0;
              
                  if (BDBASEINSS13 < 0) then
                    BDBASEINSS13 = 0;
              
                  if (BDVALORINSS < 0) then
                    BDVALORINSS = 0;
              
                  if (BDVALORINSS13 < 0) then
                    BDVALORINSS13 = 0;
              
                  --**SOMA DOS VALORES ESOCIAL***--
                  BDBASEINSSES = coalesce(bdBASEINSSES, 0);
                  BDBASEINSS13ES = coalesce(bdBASEINSS13ES, 0);
              
                  BDVALORINSSES = coalesce(bdVALORINSSES, 0);
                  BDVALORINSS13ES = coalesce(bdVALORINSS13ES, 0);
              
                  BDVALORSALFAMES = coalesce(bdVALORSALFAMES, 0);
                  BDVALORSALMATEMPES = coalesce(bdVALORSALMATEMPES, 0);
              
                  BDVRCPSEG = coalesce(bdVRCPSEG, 0);
              
                  ---***Solicitação #206764 | Título: Versão S-1.3 - Totalizador do trabalhador S-5001 - VALORES DE PIS***---
                  if (WTEMCONFIGIMPOSTO = 1) then
                    begin
                      if ((WVERSAOLAYOUTESOCIAL <> '') and (CAST(WVERSAOLAYOUTESOCIAL as Integer) >= 1300)) then
                         begin
                           BDVALORPISPASEP     = coalesce(BDVALORPISPASEP, 0);
                           BDVALORPISPASEP13   = coalesce(BDVALORPISPASEP13, 0);
              
                           BDVALORPISPASEPES   = coalesce(bdVALORPISPASEPES, 0);
                           BDVALORPISPASEP13ES = coalesce(bdVALORPISPASEP13ES, 0);
                         end
                      else
                         begin
                           BDVALORPISPASEP     = coalesce(BDBASEINSS, 0);
                           BDVALORPISPASEP13   = coalesce(BDBASEINSS13, 0);
              
                           BDVALORPISPASEPES   = coalesce(bdBASEINSSES, 0);
                           BDVALORPISPASEP13ES = coalesce(bdBASEINSS13ES, 0);
                         end
                    end
                  else
                    begin
                      BDVALORPISPASEP     = 0;
                      BDVALORPISPASEP13   = 0;
         
                      BDVALORPISPASEPES   = 0;
                      BDVALORPISPASEP13ES = 0;
                    end
              
                  if (PR13 = 0) then
                     begin
                       select count(EVT.BDCODIGO), count(FN.BDREFFN), count(FT.BDORDEM)
                       from VRH_ESOCIAL_TARQUIVO EVT
                       left outer join VRHF_EMP_TFOLHANORMAL FN on FN.BDCODEMP = EVT.BDCODEMP and
                             FN.BDCODCOL = EVT.BDCODCOL and
                             FN.BDREFFN = EVT.BDREFARQ
                       left outer join VRHF_EMP_TFOLHATOMADOR FT on FT.BDCODEMP = EVT.BDCODEMP and
                             FT.BDCODCOL = EVT.BDCODCOL and
                             FT.BDREFTOMADOR = EVT.BDREFARQ
                       where EVT.BDCODEMP = :bdCODEMP and
                             EVT.BDCODCOL = :bdCODCOL and
                             EVT.BDSTATUS = 2 and
                             EVT.BDCODTIPO in (11) and
                             EVT.BDREFARQ = :PRREF
                       into :WTEMEVENTO, :WTEMCALCFN, :WTEMCALCFT;
                     end
                  else
                     begin
                       WTEMEVENTO = 1;
                       WTEMCALCFN = 1;
                       WTEMCALCFT = 1;
                     end

                  ---***CONTROLE DO VALOR DE PIS, QUANDO TEM MAIS DE UMA ALOCAÇÃO NÃO É PRECISO RETORNAR EM TODOS OS REGISTROS***---
                  if (WCONTROLARETORNOVALPIS <> -1) then
                     if ((WCOLCONANTERIOR = BDCODCOL) and (WCOLCONANTERIOR <> -1)) then
                         if (BDCATEGORIAESOCIAL <> 111) then
                            if (WTIPOCALCULOANT = WTIPOCALC) then
                               BEGIN
                                  WTIPOCALCULOANT = WTIPOCALC;
                                  BDVALORPISPASEP = 0;
                                  BDVALORPISPASEP13 = 0;
                               END

                  ---***CONTROLE DE SUSPEND QUANDO HÁ UM REGISTRO RETORNADO NA SP_RETORNA_BASE_INSS***---
                  if (WCONTROLESUSPEND = 0) then
                     begin
                       suspend;

                       WCONTROLESUSPEND = 1;
                       WCOLCONANTERIOR = BDCODCOL;
                       WCONTROLARETORNOVALPIS = 1;

                       BDBASEINSS = 0;
                       BDBASEINSS13 = 0;
                       BDBASEAVPREV = 0;
                       BDVALORINSS = 0;
                       BDVALORINSS13 = 0;
                       BDVALORAVPREV = 0;
                       BDVALORSALFAM = 0;
                       BDVALORSALMATEMP = 0;
                 
                       BDBASEINSSES = 0;
                       BDBASEINSS13ES = 0;
                       BDBASEAVPREVES = 0;
                       BDVALORINSSES = 0;
                       BDVALORINSS13ES = 0;
                       BDVALORAVPREVES = 0;
                       BDVALORSALFAMES = 0;
                       BDVALORSALMATEMPES = 0;
                 
                       BDSEST = 0;
                       BDSENAT = 0;
                       BDSESTES = 0;
                       BDSENATES = 0;
             
                       BDVALORPISPASEPES = 0;
                       BDVALORPISPASEP13ES = 0;
                       BDVALORPISPASEP = 0;
                       BDVALORPISPASEP13 = 0;
                       BDTAGSTR = '';
                       BDDESCRICAOFOLHA = '';
                       BDVRCPSEG = 0;
                    end
                end

              ---***QUANDO NÃO HÁ REGISTRO É FEITO O SUSPEND ZERADO***---
              if (WCONTROLESUSPEND = 0) then
                 suspend;
            end
         else
            begin
               BDBASEINSS13ES = 0;
               BDVALORINSS13ES = 0;

               if (:prsepararfolhas=0) then
               --***BUSCA DE VALORES DO ÚNICO AUTONÔMOS***--
               WSQL2 = 'SELECT SUM(C.BDBASEINSS) AS BDBASEINSS, SUM(C.BDVALORINSS) AS BDVALORINSS, F.BDCATEGORIAESOCIAL,  Count(*) BDCALCULOS, 0 BDCODCONTRATO ' ||
                       'FROM VRHF_EMP_MV_AUT_CALC C ' ||
                       'LEFT OUTER JOIN TTERCEIRO_REF T ON (T.BDCODTER = C.BDCODTER AND T.BDREFEMP = (SELECT MAX(R.BDREFEMP) FROM TTERCEIRO_REF R WHERE R.BDCODTER = C.BDCODTER AND R.BDREFEMP <= C.BDREFAPUINSS)) ' ||
                       'LEFT OUTER JOIN VRHF_BASE_TTERC_FGTSGPS F ON (C.BDCODTER = F.BDCODTER AND F.BDREFTERC = T.BDREFEMP) ' ||
                       'WHERE ' || 'C.BDCODEMP = ' || :bdCODEMP || '  AND ' ||
                                   'C.BDCODTER = ' || :bdCODCOL || '  AND ' ||
                                   'C.BDREFAPUINSS = ' || :PRREF ||
                       'GROUP BY F.BDCATEGORIAESOCIAL,BDCODCONTRATO';
                else
               --***BUSCA DE VALORES DO ÚNICO AUTONÔMOS***--
               WSQL2 = 'SELECT SUM(C.BDBASEINSS) AS BDBASEINSS, SUM(C.BDVALORINSS) AS BDVALORINSS, F.BDCATEGORIAESOCIAL, 1 BDCALCULOS, C.BDCODCONTRATO ' ||
                       'FROM VRHF_EMP_MV_AUT_CALC C ' ||
                       'LEFT OUTER JOIN TTERCEIRO_REF T ON (T.BDCODTER = C.BDCODTER AND T.BDREFEMP = (SELECT MAX(R.BDREFEMP) FROM TTERCEIRO_REF R WHERE R.BDCODTER = C.BDCODTER AND R.BDREFEMP <= C.BDREFAPUINSS)) ' ||
                       'LEFT OUTER JOIN VRHF_BASE_TTERC_FGTSGPS F ON (C.BDCODTER = F.BDCODTER AND F.BDREFTERC = T.BDREFEMP) ' ||
                       'WHERE ' || ' C.BDCODEMP = ' || :bdCODEMP || '  AND ' ||
                                   'C.BDCODTER = ' || :bdCODCOL || '  AND ' ||
                                   'C.BDREFAPUINSS = ' || :PRREF ||
                       'GROUP BY F.BDCATEGORIAESOCIAL, BDCALCULOS, C.BDCODCONTRATO';


               for execute statement WSQL2 into :bdBASEINSS, :bdVALORINSS, :bdcategoriaesocial, :BDCALCULOS, :WCONTRATOTERC do
                  begin
                    if (WCONTROLESUSPEND = 1) then
                       WCONTROLESUSPEND = 0;

                    if (WTEMCONFIGIMPOSTO = 1) then
                        select BDBDVALORPISPASEP,BDVALORPISPASEP13 from SP_BUSCA_VALOR_PIS_VERBAS(:BDCODEMP, :BDCODCOL, :PRREF, 16, NULL, :WCONTRATOTERC)
                        into :BDVALORPISPASEP, :BDVALORPISPASEP13;
              
                    select BDDESCRICAOCALCULO,BDTAGSTR from SP_RETORNA_TAGSTR_TOTALIZADORES(:BDCODEMP, :BDCODCOL, :PRREF, 17, NULL, :WCONTRATOTERC)
                    into :BDDESCRICAOFOLHA,:BDTAGSTR;
     

                    if ((bdCPFCOL <> WCPFANTERIOR) or (WCONTROLARETORNOVALPIS = -1) or (WCOLCONANTERIOR <> BDCODCOL)) then
                     begin
                        WCPFANTERIOR = BDCPFCOL;
                        WCOLCONANTERIOR = BDCODCOL;

                        bdBASEINSSES = 0;
                        bdVALORINSSES = 0;
                        bdBASEINSS13ES = 0;
                        bdVALORINSS13ES = 0;
                        bdVALORSALFAMES = 0;
                        bdVALORSALMATEMPES = 0;
                        bdVRCPSEG = 0;

                        --***BUSCA DE VALORES DO ESOCIAL AUTONÔMOS***--
                        select BDBASEINSSES,BDVALORINSSES,BDVRCPSEG,BDSESTES,BDSENATES,BDCTS5001,BDIND13PIS,BDTPVALORPISPASEP,BDVALORPISPASEP,BDVALORPISPASEP13,BDVERSAOLAYOUTESOCIAL
                        from SP_RETORNA_INSS_ES_AUT(:bdCODEMP, :bdCODCOL, :PRREF)
                        into :bdBASEINSSES,:bdVALORINSSES,:bdVRCPSEG,:BDSESTES,:BDSENATES,:BDCTS5001,:bdIND13PISES,:bdTPVALORPISPASEPES,:bdVALORPISPASEPES,:bdVALORPISPASEP13ES,:WVERSAOLAYOUTESOCIAL;

                        --***SEST***--
                         select sum(
                                case
                                  when VER.BDCLAVER starting '9.010.0.9' then CALC.BDVALOR
                                  else 0
                                end) BDSEST
                         from VRHF_BASE_ITEMS_CALCTERC CALC
                         join VRHF_BASE_CALC_TERC CAL on (CALC.BDCODTER = CAL.BDCODTER and
                               CALC.BDCODEMP = CAL.BDCODEMP and
                               CALC.BDCODSERV = CAL.BDCODSERV)
                         join VRH_BASE_TVERBAS VER on CALC.BDCODVER = VER.BDCODVER
                         where (VER.BDCLAVER starting '9.010.0.9') and
                               CALC.BDCODEMP = :bdCODEMP and
                               CALC.BDCODTER = :bdCODCOL and
                               ((select BDDATA
                                 from SP_PARSE_DATE(CAL.BDDATASERV, 'yyyymm')) = :PRREF)
                         into :BDSEST;
          
                         --***SENAT***--
                         select sum(
                                case
                                  when VER.BDCLAVER starting '9.010.0.A' then CALC.BDVALOR
                                  else 0
                                end) BDSEST
                         from VRHF_BASE_ITEMS_CALCTERC CALC
                         join VRHF_BASE_CALC_TERC CAL on (CALC.BDCODTER = CAL.BDCODTER and
                               CALC.BDCODEMP = CAL.BDCODEMP and
                               CALC.BDCODSERV = CAL.BDCODSERV)
                         join VRH_BASE_TVERBAS VER on CALC.BDCODVER = VER.BDCODVER
                         where (VER.BDCLAVER starting '9.010.0.A') and
                               CALC.BDCODEMP = :bdCODEMP and
                               CALC.BDCODTER = :bdCODCOL and
                               ((select BDDATA
                                 from SP_PARSE_DATE(CAL.BDDATASERV, 'yyyymm')) = :PRREF)
                         into :BDSENAT;

                        if (WCONTROLARETORNOVALPIS = -1) then
                          BEGIN
                             WCONTROLARETORNOVALPIS = 1;
                             bdVALORPISPASEPES = 0;
                             bdVALORPISPASEP13ES = 0;
                          END
                     end

     

                   ---***CONTROLE DE SUSPEND QUANDO HÁ UM REGISTRO RETORNADO NA SP_RETORNA_BASE_INSS***---
                   if (WCONTROLESUSPEND = 0) then
                      begin
                        if (bdCONTRCOL = 2) then
                          BDCOLTER = 2;

                        suspend;
                        WCONTROLESUSPEND = 1;
     
                        BDBASEINSS = 0;
                        BDBASEINSS13 = 0;
                        BDBASEAVPREV = 0;
                        BDVALORINSS = 0;
                        BDVALORINSS13 = 0;
                        BDVALORAVPREV = 0;
                        BDVALORSALFAM = 0;
                        BDVALORSALMATEMP = 0;
                  
                        BDVALORSALFAMES = 0;
                        BDVALORSALMATEMPES = 0;
                        BDBASEINSSES = 0;
                        BDBASEINSS13ES = 0;
                        BDBASEAVPREVES = 0;
                        BDVALORINSSES = 0;
                        BDVALORINSS13ES = 0;
                        BDVALORAVPREVES = 0;
                  
                        BDSEST = 0;
                        BDSENAT = 0;
                        BDSESTES = 0;
                        BDSENATES = 0;
              
                        BDVALORPISPASEPES = 0;
                        BDVALORPISPASEP13ES = 0;
                        BDVALORPISPASEP = 0;
                        BDVALORPISPASEP13 = 0;
                        BDTAGSTR = '';
                        BDDESCRICAOFOLHA = '';
                        BDVRCPSEG = 0;
                      end
                  end
            end
       end

    ---***DADOS DE APURAÇÃO ANUAL***---
    if (PR13 = 1) then
       begin
         select F13.BDBASEINSS13 BDBINSS13,F13.BDVALORINSS13 BDINSS13,F13.BDSALFAM13 as BDVALORSALFAM,F13.BDSALMATEMP13 as BDVALORSALMATEMP,1 as BDCALCULOS
         from VRHF_EMP_T13SAL F13
         where F13.BDCODEMP = :bdCODEMP and
               F13.BDCODCOL = :bdCODCOL and
               F13.BDANO13 = :WANO
         into :bdBASEINSS13, :bdVALORINSS13, :bdVALORSALFAM, :bdVALORSALMATEMP, :WCALCULOS;

         ---***BUSCA VALORES DE PIS NAS VERBAS DO CÁLCULO DE DÉCIMO TERCEIRO***---
         if (WTEMCONFIGIMPOSTO = 1) then
            begin
              for select VF13.BDVALV13, B.BDINCIDPISVER
              from VRHF_EMP_TVERBA13 VF13
              join VRH_BASE_TVERBAS_REF B on (B.BDCODVER = VF13.BDCODVER) and
                                             (B.BDREFVER = (select max(C.BDREFVER) from VRH_BASE_TVERBAS_REF C where C.BDCODVER = VF13.BDCODVER and C.BDREFVER <= VF13.BDREF13))
              where  VF13.BDCODEMP = :bdCODEMP and
                     VF13.BDCODCOL = :bdCODCOL and
                     VF13.BDREF13 = :PRREF
              into :WVALVERBA13, :WINCIDENCIAPIS do

              if (WINCIDENCIAPIS <> 0) then
                begin
                  if (WINCIDENCIAPIS = 3) then
                     BDVALORPISPASEP13 = BDVALORPISPASEP13 + WVALVERBA13;
                end
            end
   
         select BDTAGSTR, BDDESCRICAOCALCULO from SP_RETORNA_TAGSTR_TOTALIZADORES(:bdCODEMP, :bdCODCOL, :PRREF, 16, null, null) into :BDTAGSTR, :BDDESCRICAOFOLHA;

         if (bdCPFCOL <> WCPFANTERIOR) then
            begin
              select BDBASEINSS13ES,BDVALORINSS13ES,BDVALORSALFAMES,BDVALORSALMATEMPES,BDVRCPSEG,BDIND13PIS,BDTPVALORPISPASEP,BDVALORPISPASEP,BDVALORPISPASEP13,BDVERSAOLAYOUTESOCIAL
              from SP_RETORNA_BASE_INSS_ES(:bdCODEMP, :bdCODCOL, :PRREF, 1, :bdCPFCOL)
              into :bdBASEINSS13ES,:bdVALORINSS13ES,:bdVALORSALFAMES,:bdVALORSALMATEMPES,:bdVRCPSEG,:bdIND13PISES,:bdTPVALORPISPASEPES,:bdVALORPISPASEPES,:bdVALORPISPASEP13ES,:WVERSAOLAYOUTESOCIAL;
            end

         BDCALCULOS = coalesce(BDCALCULOS, 0) + coalesce(WCALCULOS, 0);
         BDCOLTER = 1;
     
         if (bdCONTRCOL = 2) then
           BDCOLTER = 2;
     
         if (BDCTS5001 = 0) then
           BDCTS5001 = -10;
     
         --***TRATAMENTO PARA ZERAR AS BASES DE INSS QUANDO NEGATIVAS***--
         if (BDBASEINSS < 0) then
           BDBASEINSS = 0;
     
         if (BDBASEINSS13 < 0) then
           BDBASEINSS13 = 0;
     
         if (BDVALORINSS < 0) then
           BDVALORINSS = 0;
     
         if (BDVALORINSS13 < 0) then
           BDVALORINSS13 = 0;
     
         --**SOMA DOS VALORES ESOCIAL***--
         BDBASEINSSES = coalesce(bdBASEINSSES, 0);
         BDBASEINSS13ES = coalesce(bdBASEINSS13ES, 0);
     
         BDVALORINSSES = coalesce(bdVALORINSSES, 0);
         BDVALORINSS13ES = coalesce(bdVALORINSS13ES, 0);
     
         BDVALORSALFAMES = coalesce(bdVALORSALFAMES, 0);
         BDVALORSALMATEMPES = coalesce(bdVALORSALMATEMPES, 0);
     
         BDVRCPSEG = coalesce(bdVRCPSEG, 0);
     
         ---***Solicitação #206764 | Título: Versão S-1.3 - Totalizador do trabalhador S-5001 - VALORES DE PIS***---
         if (WTEMCONFIGIMPOSTO = 1) then
           begin
             if ((WVERSAOLAYOUTESOCIAL <> '') and (CAST(WVERSAOLAYOUTESOCIAL as Integer) >= 1300)) then
                begin
                  BDVALORPISPASEP     = coalesce(BDVALORPISPASEP, 0);
                  BDVALORPISPASEP13   = coalesce(BDVALORPISPASEP13, 0);
     
                  BDVALORPISPASEPES   = coalesce(bdVALORPISPASEPES, 0);
                  BDVALORPISPASEP13ES = coalesce(bdVALORPISPASEP13ES, 0);
                end
             else
                begin
                  BDVALORPISPASEP     = coalesce(BDBASEINSS, 0);
                  BDVALORPISPASEP13   = coalesce(BDBASEINSS13, 0);
     
                  BDVALORPISPASEPES   = coalesce(bdBASEINSSES, 0);
                  BDVALORPISPASEP13ES = coalesce(bdBASEINSS13ES, 0);
                end
           end
         else
           begin
             BDVALORPISPASEP     = 0;
             BDVALORPISPASEP13   = 0;

             BDVALORPISPASEPES   = 0;
             BDVALORPISPASEP13ES = 0;
           end

         if (PR13 = 0) then
            begin
              select count(EVT.BDCODIGO), count(FN.BDREFFN), count(FT.BDORDEM)
              from VRH_ESOCIAL_TARQUIVO EVT
              left outer join VRHF_EMP_TFOLHANORMAL FN on FN.BDCODEMP = EVT.BDCODEMP and
                    FN.BDCODCOL = EVT.BDCODCOL and
                    FN.BDREFFN = EVT.BDREFARQ
              left outer join VRHF_EMP_TFOLHATOMADOR FT on FT.BDCODEMP = EVT.BDCODEMP and
                    FT.BDCODCOL = EVT.BDCODCOL and
                    FT.BDREFTOMADOR = EVT.BDREFARQ
              where EVT.BDCODEMP = :bdCODEMP and
                    EVT.BDCODCOL = :bdCODCOL and
                    EVT.BDSTATUS = 2 and
                    EVT.BDCODTIPO in (11) and
                    EVT.BDREFARQ = :PRREF
              into :WTEMEVENTO, :WTEMCALCFN, :WTEMCALCFT;
            end
         else
            begin
              WTEMEVENTO = 1;
              WTEMCALCFN = 1;
              WTEMCALCFT = 1;
            end

         suspend;
       end
  end ---ESSE É O "END" DO LAÇO SOBRE O "WSQLPRINCIPAL"
end^

create or alter procedure SP_ESOCIAL_TVINCULO_FOLHA (
    PRBDMULTIEMP varchar(5000),
    PRBDCODEMP integer,
    PRBDCODCOL integer,
    PRBDCODTER integer,
    PRBDREF integer,
    PRBDCODTIPO varchar(10),
    PRDATAEVENTO varchar(10) = '')
returns (
    BDCODTERINI integer,
    BDCODCOLINI integer,
    BDCODEMPINI integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODTER integer)
as
declare variable VBDCPFCOL varchar(15);
declare variable VBDCPFTER varchar(15);
declare variable VSQL varchar(30000);
declare variable VSQLSELECT varchar(30000);
declare variable VMEITER DM_BOOLEAN;
declare variable WPAGAMENTO integer;
declare variable WTRANSFERENCIA integer;
declare variable WDTPAG varchar(15);
declare variable WDTRESC varchar(15);
declare variable WTEMTRANS integer;
declare variable WCODEMP integer;
begin
  bdcodcolini = coalesce(prbdcodcol,0);
  bdcodempini = coalesce(prbdcodemp,0);
  BDCODTERINI = coalesce(prbdcodter,0);


  WTRANSFERENCIA = 0;
  VSQL = ' select BDPAGEMP from VW_VRHF_BASE_TEMPCALC where BDCODEMP = '||:PRBDCODEMP;
  execute statement VSQL into :WPAGAMENTO;

  if ((WPAGAMENTO = 0) and (PRBDCODTIPO = '14')) then
    begin
      VSQL = ' select BDCODCOL, BDCODCOLORIG from VW_VRH_EMP_TTRANSCOL_DESTINO where BDCODEMPORIG = '||:PRBDCODEMP||' and BDCODCOLORIG = '||:PRBDCODCOL;
      execute statement VSQL into :WTRANSFERENCIA, :WTEMTRANS;

      if (COALESCE(WTRANSFERENCIA, 0) > 0) then
        begin
          VSQL = 'select BDDATAPAG from '||
                 ' (select BDDATAPGTOFN as BDDATAPAG '||
                 ' from VRHF_EMP_TFOLHANORMAL '||
                 ' where BDCODEMP = '||:PRBDCODEMP||' and BDCODCOL = '||:PRBDCODCOL||' and EXTRACT(YEAR FROM BDDATAPGTOFN) * 100 + EXTRACT(MONTH FROM BDDATAPGTOFN) = '||:PRBDREF||
                 ' union all '||
                 ' select first 1 BDDATAPGTOFT as BDDATAPAG '||
                 ' from VRHF_EMP_TFOLHATOMADOR '||
                 ' where BDCODEMP = '||:PRBDCODEMP||' and BDCODCOL = '||:PRBDCODCOL||' and EXTRACT(YEAR FROM BDDATAPGTOFT) * 100 + EXTRACT(MONTH FROM BDDATAPGTOFT) = '||:PRBDREF||')';
          execute statement VSQL into :WDTPAG;

          if (WDTPAG is not null) then
            WDTPAG = ''''||WDTPAG||'''';
        end

    end

  vmeiter = 'FALSE';
  if (PRBDCODTER <> 0) then
    begin
      vsql = 'select first 1 RH.BDCPFMEITER from TTERCEIRO_RH RH where RH.BDCODTER = ' || PRBDCODTER || ' and char_length(RH.BDCPFMEITER) = 14';
      execute statement VSQL into VBDCPFCOL;

      if (VBDCPFCOL <> '') then
        vmeiter = 'TRUE';
      else
        begin
          vsql = 'select first 1 C.BDCGCTER from TTERCEIRO C where C.BDCODTER = ' || PRBDCODTER;
          execute statement VSQL into VBDCPFCOL;
        end
    end

  if (VBDCPFCOL is null) then
    begin
      if ((PRBDMULTIEMP <> '') and (PRBDCODCOL <> 0)) then
        begin
          vsql = 'select first 1 C.BDCPFCOL from VRH_EMP_TCOLCON C where C.BDCODEMP = ' || PRBDCODEMP || ' and C.BDCODCOL = ' || PRBDCODCOL;
          execute statement VSQL into VBDCPFCOL;
        end
  end

  if (VBDCPFCOL <> '') then
      begin
        --A regra ?oda definida pelo order by 
          
        vsql = 'select first 1 V.BDCODEMP, V.BDCODCOL ';

               vsql = vsql ||'from (select C.BDCODEMP, C.BDCODCOL, coalesce(TRANSDE.BDDATATRF, R.BDDATARESCISAO,C.BDDATAADMCOL)BDDATAADMCOL, 0 BDCODIGO, 1 BDTIPO, R.BDDATARESCISAO, coalesce(Cast (bddatarescisao as date),Cast (current_timestamp as date)+1)BDDATARESCISAOorder ' ||
                             'from VRH_EMP_TCOLCON C ' ||
                             'left outer join VRH_EMP_TRESCISAO R on R.BDCODEMP = C.BDCODEMP and R.BDCODCOL = C.BDCODCOL ' ||
                             'left outer join VRH_EMP_TTRANSCOL TRANS on TRANS.BDCODEMPORIG = C.BDCODEMP and TRANS.BDCODCOLORIG = C.BDCODCOL ' ||
                             'left outer join VRH_EMP_TTRANSCOL TRANSDE on TRANSDE.BDCODEMPDEST = C.BDCODEMP and TRANSDE.bdcodcoldest = C.BDCODCOL ' ||
                             'left outer join VRH_BASE_TPREPRESC P on P.BDCODPRES = TRANS.BDCODPTRAN or P.BDCODPRES = R.BDCODPRES ' ||
                             'left outer join VRH_EMP_TCOLCON_PARTIDA PR on PR.BDCODEMP = C.BDCODEMP and PR.BDCODCOL = C.BDCODCOL ' ||
                             'left outer join VRH_EMP_TCOLCON_VINC CLA on (CLA.BDCODEMP = C.BDCODEMP and CLA.BDCODCOL = C.BDCODCOL and ' ||
                                                                           'CLA.BDREFCOL = (select max(BDREFCOL) BDREFCOL ' ||
                                                                                           'from VRH_EMP_TCOLCON_VINC ' ||
                                                                                           'where BDCODEMP = C.BDCODEMP and ' ||
                                                                                                 'BDCODCOL = C.BDCODCOL and ' ||
                                                                                                 'BDREFCOL <= '||PRBDREF||')) ' ||
                             'left outer join VRH_BASE_TCLASSE CLASS on (CLASS.BDCODCLA = CLA.BDCODCLA) ' ||
                             'left outer join TEMPRESAS E ON C.BDCODEMP=E.BDCODEMP '||

                             'where C.BDCODEMP in (' || PRBDMULTIEMP || ') and ' ||
                                   'C.BDCPFCOL like '''|| VBDCPFCOL ||''' and ' ||
                                   'Coalesce(CLASS.BDGRUPOCLA,0) <> 12 and '  ||

                             iif(PRDATAEVENTO<>'','((e.bddatafimativemp is null) or (e.bddatafimativemp)>='''||PRDATAEVENTO||''') and ','')||
               /*158821 - Paulo - 23/03/2022 - Se ?ocio Cotista (GRUPOCLA = 12) ele n?retorna, pois ele n?gera nada para o eSocial*/
               -- Data de Admiss?
               ' ((select BDDATA from SP_PARSE_DATE(C.BDDATAADMCOL, ''YYYYMM'')) <= '||PRBDREF||') and ' ||
               -- Data de Transfer?ia
               ' ((select BDDATA from SP_PARSE_DATE(PR.BDDATATRFCOL,''YYYYMM'')) <= '||PRBDREF||' or (PR.BDDATATRFCOL is null)) and ' ||
               -- Data de Rescis?
               ' ((R.BDDATARESCISAO is null) or ((select BDDATA from SP_PARSE_DATE('||COALESCE(WDTPAG,'R.BDDATAPAGRESCISAO')||', ''YYYYMM'')) >= '||PRBDREF||') or ';
               -- Transferência para matriz não cadastrada no sistema
               if (coalesce(WTEMTRANS, 0) > 0) then
                 vsql = vsql||' (exists(select T.BDCODEMPORIG, T.BDCODCOLORIG from VRH_EMP_TTRANSCOL T left outer join TEMPRESAS E on E.BDCODEMP = T.BDCODEMPORIG where T.BDCODEMPORIG = C.BDCODEMP and T.BDCODCOLORIG = C.BDCODCOL and coalesce(E.BDMATRIZNAOCADSIS, ''FALSE'') = ''TRUE'' and ((select BDDATA from SP_PARSE_DATE(T.BDDATATRF, ''YYYYMM'')) <='||PRBDREF||'))) or ';
               -- Folhas posteriores ao desligamento
            vsql = vsql||' (((exists(select first 1 FC.BDCODCOL from VRHF_EMP_TFOLHACOMP FC where FC.BDCODEMP = C.BDCODEMP and FC.BDCODCOL = C.BDCODCOL and FC.BDDATAPAGFC > R.BDDATAPAGRESCISAO and FC.BDCODTIPOFC <> 3 and FC.BDREFCOMP = '||PRBDREF||
                         ' union all '||
                         ' select first 1 FC.BDCODCOL from VRHF_EMP_TFOLTOMCOMP FC where FC.BDCODEMP = C.BDCODEMP and FC.BDCODCOL = C.BDCODCOL and FC.BDDATAPAGFC > R.BDDATAPAGRESCISAO and FC.BDCODTIPOFC <> 3 and FC.BDREFCOMP = '||PRBDREF||
                         ' union all '||
                         ' select first 1 FC.BDCODCOL from VRHF_EMP_TFOLHACOMPINT FC where FC.BDCODEMP = C.BDCODEMP and FC.BDCODCOL = C.BDCODCOL and FC.BDDATAPAGFC > R.BDDATAPAGRESCISAO and FC.BDCODTIPOFC <> 3 and FC.BDREFCOMP = '||PRBDREF||
                         ' union all '||
                         ' select first 1 FC.BDCODCOL from VRHF_EMP_TFOLTOMCOMPINT FC where FC.BDCODEMP = C.BDCODEMP and FC.BDCODCOL = C.BDCODCOL and FC.BDDATAPAGFC > R.BDDATAPAGRESCISAO and FC.BDCODTIPOFC <> 3 and FC.BDREFCOMP = '||PRBDREF||
                         ' union all '||
                         ' select first 1 ES.BDCODCOL from TFOLHAPGTOESOCIAL ES '||
                         ' join VRH_ESOCIAL_TSINCRONIZACAO e on ES.BDCODEMP = E.BDCODEMP '||
                         ' where ES.BDCODEMP = C.BDCODEMP and ES.BDCODCOL = C.BDCODCOL and '||
                         '       E.BDREFINISINC <= '||PRBDREF||
                         '       and ((es.BDDATAPGTO is null) or '||
                         '            ((select BDDATA from SP_PARSE_DATE(es.BDDATAPGTO, ''YYYYMM'')) >= '||PRBDREF||'))'||
                         ' union all '||
                         ' select first 1 FC.BDCODCOL ' ||
                         ' from VRHF_EMP_TFOLHACOMP FC ' ||
                         ' left join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and ' ||
                         '       FC.BDCODACCONV = AC.BDCODACCONV ' ||
                         ' where FC.BDCODEMP = C.BDCODEMP and ' ||
                         '       FC.BDCODCOL = C.BDCODCOL and ' ||
                         '       FC.BDDATAPAGFC > R.BDDATAPAGRESCISAO and ' ||
                         '       FC.BDCODTIPOFC = 3 and ' ||
                         '       AC.BDCODACCONV is not null and ' ||
                         '       ((extract(year from '||iif(PRBDCODTIPO = 14, 'AC.BDCOMPACCONV', 'AC.BDDTPGTOBRICONV')||') * 100) + extract(month from '||iif(PRBDCODTIPO = 14, 'AC.BDCOMPACCONV', 'AC.BDDTPGTOBRICONV')||') = '||PRBDREF||') ' ||
                         ' union all ' ||
                         ' select first 1 FC.BDCODCOL ' ||
                         ' from VRHF_EMP_TFOLTOMCOMP FC ' ||
                         ' left join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and ' ||
                         '       FC.BDCODACCONV = AC.BDCODACCONV ' ||
                         ' where FC.BDCODEMP = C.BDCODEMP and ' ||
                         '       FC.BDCODCOL = C.BDCODCOL and ' ||
                         '       FC.BDDATAPAGFC > R.BDDATAPAGRESCISAO and ' ||
                         '       FC.BDCODTIPOFC = 3 and ' ||
                         '       AC.BDCODACCONV is not null and ' ||
                         '       ((extract(year from '||iif(PRBDCODTIPO = 14, 'AC.BDCOMPACCONV', 'AC.BDDTPGTOBRICONV')||') * 100) + extract(month from '||iif(PRBDCODTIPO = 14, 'AC.BDCOMPACCONV', 'AC.BDDTPGTOBRICONV')||') = '||PRBDREF||') ' ||
                         ' union all ' ||
                         ' select first 1 FC.BDCODCOL ' ||
                         ' from  VRHF_EMP_TFOLHACOMPINT FC ' ||
                         ' left join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and ' ||
                         '       FC.BDCODACCONV = AC.BDCODACCONV ' ||
                         ' where FC.BDCODEMP = C.BDCODEMP and ' ||
                         '       FC.BDCODCOL = C.BDCODCOL and ' ||
                         '       FC.BDDATAPAGFC > R.BDDATAPAGRESCISAO and ' ||
                         '       FC.BDCODTIPOFC in (1,3) and ' ||
                         '       AC.BDCODACCONV is not null and ' ||
                         '       ((extract(year from '||iif(PRBDCODTIPO = 14, 'AC.BDCOMPACCONV', 'AC.BDDTPGTOBRICONV')||') * 100) + extract(month from '||iif(PRBDCODTIPO = 14, 'AC.BDCOMPACCONV', 'AC.BDDTPGTOBRICONV')||') = '||PRBDREF||') ' ||
                         ' union all ' ||
                         ' select first 1 FC.BDCODCOL ' ||
                         ' from  VRHF_EMP_TFOLTOMCOMPINT FC ' ||
                         ' left join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and ' ||
                         '       FC.BDCODACCONV = AC.BDCODACCONV ' ||
                         ' where FC.BDCODEMP = C.BDCODEMP and ' ||
                         '       FC.BDCODCOL = C.BDCODCOL and ' ||
                         '       FC.BDDATAPAGFC > R.BDDATAPAGRESCISAO and ' ||
                         '       FC.BDCODTIPOFC in (1,3) and ' ||
                         '       AC.BDCODACCONV is not null and ' ||
                         '       ((extract(year from '||iif(PRBDCODTIPO = 14, 'AC.BDCOMPACCONV', 'AC.BDDTPGTOBRICONV')||') * 100) + extract(month from '||iif(PRBDCODTIPO = 14, 'AC.BDCOMPACCONV', 'AC.BDDTPGTOBRICONV')||') = '||PRBDREF||') ' ||
                         ' union all ' ||
                         ' select first 1 FA.BDCODCOL from VRHF_EMP_TFOLHAAVULSA FA where FA.BDCODEMP = C.BDCODEMP and FA.BDCODCOL = C.BDCODCOL and FA.BDDATAFA > R.BDDATAPAGRESCISAO and FA.BDREF = '||PRBDREF||')) and'||
               ' ((P.BDCODMOTESRESC <> 99) or '||
               ' (exists (select * from VRH_EMP_TRESCISAO RESC where RESC.BDCODEMP = TRANS.BDCODEMPDEST and RESC.BDCODCOL = TRANS.BDCODCOLDEST and '||
                                                                  ' (select BDDATA from SP_PARSE_DATE(R.BDDATAPAGRESCISAO, ''YYYYMM'')) <='||PRBDREF||'))))))'||
               '       union all ' ||
               '       select A.BDCODEMP, A.BDCODCOL, C.BDDATAADMCOL, A.BDCODIGO, 1, null , null ' ||
               '       from VRH_ESOCIAL_TARQUIVO A ' ||
               '       inner join VRH_EMP_TCOLCON C on C.BDCODEMP = A.BDCODEMP and C.BDCODCOL = A.BDCODCOL ' ||
               '       where A.BDCODEMP in (' || PRBDMULTIEMP || ') and ' ||
               '             C.BDCPFCOL like '''|| VBDCPFCOL ||''' and ' ||
               '             (select BDDATA from SP_PARSE_DATE(C.BDDATAADMCOL, ''YYYYMM'')) <= '||PRBDREF||' and '||
               '             A.BDREFARQ = '||PRBDREF||' and ' ||
               '             A.BDSTATUS = 2 and ' ||
               '             A.BDCODTIPO = '||PRBDCODTIPO||' ' ||') V ' ||
               'inner join TEMPRESAS E on E.BDCODEMP = V.BDCODEMP '||
               'left join VW_TEMPRESAS_REF EMPREF on E.BDCODEMP = EMPREF.BDCODEMP ';

        vsql = vsql || 'where COALESCE(E.BDSITUACAOESOCIAL, 0) = 1';
                vsql = vsql||' order by ';

           vsql = vsql || ' v.BDDATARESCISAOorder desc, V.BDDATAADMCOL desc, V.BDCODIGO desc, BDTIPO, coalesce(E.BDCODMATRIZ, 0), V.BDCODCOL desc, E.BDDATAINIATIVEMP';

      execute statement VSQL into :WCODEMP, BDCODCOL;
  end

  BDCODEMP = :WCODEMP;

  VSQLSelect =   'select first 1 V.BDCODEMP BDCODEMP,  V.BDCODTER BDCODTER '||
                  '  from TEMPRESAS E ';

--  if (BDCODEMP is null) then
      begin
      --Ao procurar os autônomos, verifica se já tem evento pra aquele CPF na referência. Se tiver, utiliza o código de autônomo do evento

       vsql = vsqlselect ||        ' left outer join  (select A.BDCODEMP, A.BDCODTER ' ||
               '       from VRH_ESOCIAL_TARQUIVO A ';

               if (vmeiter = 'FALSE') then
                 vsql = vsql || '       inner join TTERCEIRO T on T.BDCODTER = A.BDCODTER ';
               else
                 vsql = vsql || '       inner join TTERCEIRO_RH RH on RH.bdcodter = A.BDCODTER ';

               vsql = vsql || '      where A.BDCODEMP in (' || PRBDMULTIEMP || ') and ';

               if (vmeiter = 'FALSE') then
                 vsql = vsql || '             T.BDCGCTER like '''|| VBDCPFCOL ||''' and ';
               else
                 vsql = vsql || '             RH.BDCPFMEITER like '''|| VBDCPFCOL ||''' and ';

         vsql = vsql || '             A.BDREFARQ = '||PRBDREF||' and ' ||
               '             A.BDSTATUS = 2 and ' ||
               '             A.BDCODTIPO = '||PRBDCODTIPO||') V on V.BDCODEMP = E.BDCODEMP ';
      execute statement VSQL into :WCODEMP, BDCODTER;
      if (BDCODEMP is null) then
          BDCODEMP = :WCODEMP;
      end

   if (BDCODTER is null) then
      begin
        vsql = vsqlselect || ' left outer join(select TC.BDCODTER, TC.BDCODEMP  '||
                                        ' from VRHF_BASE_CALC_TERC TC ';

       if (vmeiter = 'FALSE') then
             vsql = vsql ||' join TTERCEIRO T on T.BDCODTER = TC.BDCODTER and T.BDCGCTER like '''|| VBDCPFCOL ||''' ';
       else
             vsql = vsql ||' join TTERCEIRO_RH RH on RH.BDCODTER = TC.BDCODTER and RH.BDCPFMEITER like '''|| VBDCPFCOL ||''' ';

         vsql = vsql || ' where TC.BDCODEMP in (' || PRBDMULTIEMP || ') and  '||
                        ' TC.BDREFINSSSERV = '||PRBDREF||') V on V.BDCODEMP = E.BDCODEMP  '||
                        'where COALESCE(E.BDSITUACAOESOCIAL, 0) = 1 and V.BDCODEMP in ('||PRBDMULTIEMP||')';
         execute statement VSQL into :WCODEMP, BDCODTER;
--         BDCODEMP = :WCODEMP;
       end


  if (BDCODEMP is null) then
    BDCODEMP = WCODEMP;

  if ((bdcodemp is null) and (bdcodcol is null) and (bdcodter is null))  then
    begin
       bdcodemp=bdcodempini;
       bdcodcol=bdcodcolini;
       bdcodter=bdcodterini;
        end

  suspend;
end^

create or alter procedure SP_VALIDA_VALORES_1_3_FERIAS (
    PRCODIGOEMP varchar(32000),
    PRCODIGOCOL varchar(32000),
    PRANOCALCULO varchar(4))
returns (
    BDAPRESENTAMENSAGEM varchar(5),
    BDCODEMP integer,
    BDCODCOL integer)
as
declare variable WCODIGOEMP integer;
declare variable WCODIGOCOL integer;
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(32000);
begin
  BDAPRESENTAMENSAGEM = 'FALSE';
  WWHERE = '';



  if (PRCODIGOEMP <> '') then
     begin
       PRCODIGOEMP = '('||PRCODIGOEMP||') and ';
         if (prcodigocol <> '') then
         prcodigocol = '('||prcodigocol||') and ';
       WWHERE =   PRCODIGOEMP ||  prcodigocol;
     end



   WSQL = 'select ferx.bdcodemp, ferx.bdcodcol from VRH_EMP_TFERIAS ferx ' || 'where ' ||WWHERE|| ' (not exists (select FER.BDCODEMP, VERBAS.BDCLAVER ' || 'from VRH_EMP_TFERIAS FER ' || 'left join VRHF_EMP_TVERBAFE VERBAFER on (VERBAFER.BDCODEMP = FER.BDCODEMP) and ' || '(VERBAFER.BDCODCOL = FER.BDCODCOL) and ' || '(VERBAFER.BDINIPERAQUISFE = FER.BDINIPERAQUISFE) and ' || '(VERBAFER.BDCODFE = FER.BDCODFE) ' || 'left join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = VERBAFER.BDCODVER) ' || 'where ' || wWhere ||'((FER.BDINIPERGOZOFE >= ''01/01/' || :PRANOCALCULO || ''') or (FER.BDINIPERGOZOFE <= ''12/31/' || :PRANOCALCULO || ''')) and ' || 'VERBAS.BDCLAVER starting ''3.002.0'' and FERX.bdcodemp = Fer.bdcodemp and FERX.bdcodcol = fer.bdcodcol and FERX.BDINIPERAQUISFE = FER.BDINIPERAQUISFE and FERX.BDCODFE = FER.BDCODFE)) group by  FERX.BDCODEMP, FERX.BDCODCOL';

  for execute statement WSQL
          into :WCODIGOEMP, :WCODIGOCOL
  do
  begin
    BDCODEMP = WCODIGOEMP;
    BDCODCOL = WCODIGOCOL;
    BDAPRESENTAMENSAGEM = 'TRUE';

    for select FOLHANORMAL.BDCODEMP, FOLHANORMAL.BDCODCOL
        from VRHF_EMP_TVERBAFN FOLHANORMAL
        left join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOLHANORMAL.BDCODVER)
        where (FOLHANORMAL.BDCODEMP = :WCODIGOEMP) and
              (FOLHANORMAL.BDCODCOL = :WCODIGOCOL) and
              ((FOLHANORMAL.BDREFFN >= CAST(:pranocalculo||'01' as integer)) and (FOLHANORMAL.BDREFFN <= CAST(:pranocalculo||'12' as integer))) and
              (VERBAS.BDCLAVER starting '0.180.1.0')
        union all
        select FOLHATOMADOR.BDCODEMP, FOLHATOMADOR.BDCODCOL
        from VRHF_EMP_TVERBATOMADOR FOLHATOMADOR
        left join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOLHATOMADOR.BDCODVER)
        where (FOLHATOMADOR.BDCODEMP = :WCODIGOEMP) and
              (FOLHATOMADOR.BDCODCOL = :WCODIGOCOL) and
              ((FOLHATOMADOR.BDREFTOMADOR >= CAST(:pranocalculo||'01' as integer)) and (FOLHATOMADOR.BDREFTOMADOR <= CAST(:pranocalculo||'12' as integer))) and
              (VERBAS.BDCLAVER starting '0.180.1.0')
        union all
        select FOLHACOMP.BDCODEMP, FOLHACOMP.BDCODCOL
        from VRHF_EMP_TVERBAFC FOLHACOMP
        left join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOLHACOMP.BDCODVER)
        where (FOLHACOMP.BDCODEMP = :WCODIGOEMP) and
              (FOLHACOMP.BDCODCOL = :WCODIGOCOL) and
              ((FOLHACOMP.BDREFFN >= CAST(:pranocalculo||'01' as integer)) and (FOLHACOMP.BDREFFN <= CAST(:pranocalculo||'12' as integer))) and
              (VERBAS.BDCLAVER starting '0.180.1.0')
        union all
        select FOLHATOMCOMP.BDCODEMP, FOLHATOMCOMP.BDCODCOL
        from VRHF_EMP_TVERBAFCTOMADOR FOLHATOMCOMP
        left join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = FOLHATOMCOMP.BDCODVER)
        where (FOLHATOMCOMP.BDCODEMP = :WCODIGOEMP) and
              (FOLHATOMCOMP.BDCODCOL = :WCODIGOCOL) and
              ((FOLHATOMCOMP.BDREFTOMADOR >= CAST(:pranocalculo||'01' as integer)) and (FOLHATOMCOMP.BDREFTOMADOR <= CAST(:pranocalculo||'12' as integer))) and
              (VERBAS.BDCLAVER starting '0.180.1.0')
        into :WCODIGOEMP, :WCODIGOCOL
    do
    begin
      BDAPRESENTAMENSAGEM = 'FALSE';
      BDCODEMP = WCODIGOEMP;
      BDCODCOL = WCODIGOCOL;
      suspend;
    end
  end
  /* Procedure Text */
  suspend;
end^



            
create or alter procedure SP_REL_TOT_5003 (
    PRCODEMP varchar(30000),
    PRREF integer,
    PR13 integer,
    PRFILTROCPF varchar(30000))
returns (
    BDCODEMPORD integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCOLTER integer,
    BDCONTRCOL integer,
    BDGRUPOCLA integer,
    BDNOMCOL varchar(70),
    BDCPFCOL varchar(14),
    BDCNPJEMP varchar(18),
    BDNOMEMP varchar(100),
    BDBASEINSS numeric(18,6),
    BDBASEINSSES numeric(18,6),
    BDVALORINSS numeric(18,6),
    BDVALORINSSES numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEINSS13ES numeric(18,6),
    BDVALORINSS13 numeric(18,6),
    BDVALORINSS13ES numeric(18,6),
    BDVALORSALFAM numeric(18,6),
    BDVALORSALFAMES numeric(18,6),
    BDVALORSALMATEMP numeric(18,6),
    BDVALORSALMATEMPES numeric(18,6),
    BDVRCPSEG numeric(18,6),
    BDVRDEDDEP numeric(18,6),
    BDVRDEDDEPES numeric(18,6),
    BDBASEPENSAO numeric(18,6),
    BDBASEPENSAOES numeric(18,6),
    BDBASEIRRF numeric(18,6),
    BDBASEIRRFES numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDBASEIRRF13ES numeric(18,6),
    BDBASEIRRFFERIAS numeric(18,6),
    BDBASEIRRFFERIASES numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDBASEIRRFPLRES numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDVALORIRRFES numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDVALORIRRF13ES numeric(18,6),
    BDVALORIRRFFERIAS numeric(18,6),
    BDVALORIRRFFERIASES numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDVALORIRRFPLRES numeric(18,6),
    BDBASEFGTS numeric(18,6),
    BDBASEFGTSES numeric(18,6),
    BDVALORFGTS numeric(18,6),
    BDVALORFGTSES numeric(18,6),
    BDBASEFGTSRES numeric(18,6),
    BDBASEFGTSRESES numeric(18,6),
    BDVALORFGTSRES numeric(18,6),
    BDVALORFGTSRESES numeric(18,6),
    BDBASEAVPREV numeric(18,6),
    BDBASEAVPREVES numeric(18,6),
    BDVALORAVPREV numeric(18,6),
    BDVALORAVPREVES numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDBASEFGTS13ES numeric(18,6),
    BDVALORFGTS13 numeric(18,6),
    BDVALORFGTS13ES numeric(18,6),
    BDVALORINSSPLR numeric(18,6),
    BDVALORINSSRRA numeric(18,6),
    BDVRDEDDEP13 numeric(18,6),
    BDVRDEDDEPES13 numeric(18,6),
    BDVRDEDDEPPLR numeric(18,6),
    BDVRDEDDEPRRA numeric(18,6),
    BDBASEPENSAO13 numeric(18,6),
    BDBASEPENSAO13ES numeric(18,6),
    BDBASEPENSAOPLR numeric(18,6),
    BDBASEPENSAOPLRES numeric(18,6),
    BDBASEPENSAORRA numeric(18,6),
    BDBASEPENSAORRAES numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDBASEIRRFRRAES numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDVALORIRRFRRAES numeric(18,6),
    BDVRDEDDEPPLRES numeric(18,6),
    BDVRDEDDEPRRAES numeric(18,6),
    BDVALORINSSRRAES numeric(18,6),
    BDBASEPREV numeric(18,6),
    BDBASEPREV13 numeric(18,6),
    BDBASEPREVPLR numeric(18,6),
    BDBASEPREVRRA numeric(18,6),
    BDBASEPREVES numeric(18,6),
    BDBASEPREV13ES numeric(18,6),
    BDTIPO integer,
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDCATEGORIAESOCIAL integer,
    BDCODCLATRI integer,
    BDSEST integer,
    BDSENAT integer,
    BDSESTES integer,
    BDSENATES integer,
    BDCTS5001 integer,
    BDBASEFGTS13RESCES numeric(18,6),
    BDVALORFGTS13RESCES numeric(18,6),
    BDBASEFGTS13RESC numeric(18,6),
    BDVALORFGTS13RESC numeric(18,6),
    BDECONSIGNADO numeric(18,6),
    BDECONSIGNADORESC numeric(18,6),
    BDINSTITUICAOFINANC integer,
    BDNROCONTRATOECONSIGNADO varchar(30),
    BDINSTITUICAOFINANCES integer,
    BDNROCONTRATOECONSIGNADOES varchar(30),
    BDVALORECONSIGNADOES numeric(18,6),
    BDIND13PISES integer,
    BDTPVALORPISPASEPES integer,
    BDVALORPISPASEPES numeric(18,6),
    BDVALORPISPASEP13ES numeric(18,6),
    BDVALORPISPASEP numeric(18,6),
    BDVALORPISPASEP13 numeric(18,6),
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000))
as
declare variable WSQLPRINCIPAL varchar(30000);
declare variable WEMPCARREGADA integer;
declare variable WCPFANTERIOR varchar(14);
declare variable WCODMATRIZ integer;
declare variable WCNPJEMP varchar(18);
declare variable WCODEMP integer;
declare variable WLISTAEMP varchar(30000);
declare variable WNOMEMP varchar(100);
declare variable WCODCOL integer;
declare variable WNOMCOL varchar(100);
declare variable WCPFCOL varchar(14);
declare variable WCONTRCOL integer;
declare variable WULTDIA varchar(2);
declare variable WMES smallint;
declare variable WANO integer;
declare variable WCATESOCIAL integer;
declare variable WCODCLATRI integer;
declare variable WGRUPOCLA integer;
declare variable WBASEFGTS numeric(18,6);
declare variable WBASEFGTS13 numeric(18,6);
declare variable WBASEFGTSRES numeric(18,6);
declare variable WBASEAVPREV numeric(18,6);
declare variable WVALORFGTS numeric(18,6);
declare variable WVALORFGTS13 numeric(18,6);
declare variable WVALORFGTSRES numeric(18,6);
declare variable WVALORAVPREV numeric(18,6);
declare variable WBASEFGTSES numeric(18,6);
declare variable WBASEFGTS13ES numeric(18,6);
declare variable WBASEFGTSRESES numeric(18,6);
declare variable WBASEAVPREVES numeric(18,6);
declare variable WVALORFGTSES numeric(18,6);
declare variable WVALORFGTS13ES numeric(18,6);
declare variable WVALORFGTSRESES numeric(18,6);
declare variable WVALORAVPREVES numeric(18,6);
declare variable WCALCULOS integer;
declare variable WTEMEVENTO integer;
declare variable WTEMCALCFN integer;
declare variable WTEMCALCFT integer;
declare variable WSQL2 varchar(30000);
declare variable WCATEGORIAESOCIAL integer;
declare variable WCATESOCIALCARREGADA integer;
declare variable WMATRICULAATUAL varchar(30);
declare variable WMATRICULAANTERIOR varchar(30);
declare variable WBASEFGTS13RESC numeric(18,6);
declare variable WVALORFGTS13RESC numeric(18,6);
declare variable WBASEFGTS13RESCES numeric(18,6);
declare variable WVALORFGTS13RESCES numeric(18,6);
begin
  DELETE FROM VRHF_TEMP_EMP_TECONSIGNADO5003 WHERE BDSESSAO = CURRENT_CONNECTION;

  BDCODEMPORD = 0;
  BDCODEMP = 0;
  BDCODCOL = 0;
  BDCOLTER = 0;
  BDCONTRCOL = 0;
  BDGRUPOCLA = 0;
  BDNOMCOL =  '';
  BDCPFCOL =  '';
  BDCNPJEMP = '';
  BDNOMEMP =  '';
  BDBASEINSS = 0;
  BDBASEINSSES = 0;
  BDBASEINSS13 = 0;
  BDBASEINSS13ES = 0;
  BDVALORINSS = 0;
  BDVALORINSSES = 0;
  BDVALORINSS13 = 0;
  BDVALORINSS13ES = 0;
  BDVALORSALFAM = 0;
  BDVALORSALFAMES = 0;
  BDVALORSALMATEMP = 0;
  BDVALORSALMATEMPES = 0;
  BDVRCPSEG = 0;
  BDVRDEDDEP = 0;
  BDVRDEDDEPES = 0;
  BDBASEPENSAO = 0;
  BDBASEPENSAOES = 0;
  BDBASEIRRF = 0;
  BDBASEIRRFES = 0;
  BDBASEIRRF13 = 0;
  BDBASEIRRF13ES = 0;
  BDBASEIRRFFERIAS = 0;
  BDBASEIRRFFERIASES = 0;
  BDBASEIRRFPLR = 0;
  BDBASEIRRFPLRES = 0;
  BDVALORIRRF = 0;
  BDVALORIRRFES = 0;
  BDVALORIRRF13 = 0;
  BDVALORIRRF13ES = 0;
  BDVALORIRRFFERIAS = 0;
  BDVALORIRRFFERIASES = 0;
  BDVALORIRRFPLR = 0;
  BDVALORIRRFPLRES = 0;
  BDBASEFGTS = 0;
  BDBASEFGTSES = 0;
  BDBASEFGTSRES = 0;
  BDBASEFGTSRESES = 0;
  BDBASEAVPREV = 0;
  BDBASEAVPREVES = 0;
  BDBASEFGTS13 = 0;
  BDBASEFGTS13ES = 0;
  BDVALORFGTS = 0;
  BDVALORFGTSES = 0;
  BDVALORFGTSRES = 0;
  BDVALORFGTSRESES = 0;
  BDVALORAVPREV = 0;
  BDVALORAVPREVES = 0;
  BDVALORFGTS13 = 0;
  BDVALORFGTS13ES = 0;
  BDTIPO = 5003;
  BDCALCULOS = 0;
  BDCOUNTFC = 0;
  BDCATEGORIAESOCIAL = 0;
  BDCODCLATRI = 0;
  BDSEST = 0;
  BDSENAT = 0;
  BDSESTES = 0;
  BDSENATES = 0;
  BDCTS5001 = 0;
  BDVALORINSSPLR = 0;
  BDVALORINSSRRA = 0;
  BDVRDEDDEP13 = 0;
  BDVRDEDDEPES13 = 0;
  BDVRDEDDEPPLR = 0;
  BDVRDEDDEPRRA = 0;
  BDBASEPENSAO13 = 0;
  BDBASEPENSAO13ES = 0;
  BDBASEPENSAOPLR = 0;
  BDBASEPENSAOPLRES = 0;
  BDBASEPENSAORRA = 0;
  BDBASEPENSAORRAES = 0;
  BDBASEIRRFRRA = 0;
  BDBASEIRRFRRAES = 0;
  BDVALORIRRFRRA = 0;
  BDVALORIRRFRRAES = 0;
  BDVRDEDDEPPLRES = 0;
  BDVRDEDDEPRRAES = 0;
  BDVALORINSSRRAES = 0;
  BDBASEPREV = 0;
  BDBASEPREV13 = 0;
  BDBASEPREVPLR = 0;
  BDBASEPREVRRA = 0;
  BDBASEPREVES = 0;
  BDBASEPREV13ES = 0;
  BDBASEFGTS13RESCES = 0;
  BDVALORFGTS13RESCES = 0;
  BDBASEFGTS13RESC = 0;
  BDVALORFGTS13RESC = 0;
  WSQL2 = '';
  BDINSTITUICAOFINANC = 0;
  BDNROCONTRATOECONSIGNADO = '';
  BDINSTITUICAOFINANCES = 0;
  BDNROCONTRATOECONSIGNADOES = '';
  BDVALORECONSIGNADOES = 0;

  --#206764 - Início - É preciso criar os campos com valores zero pois somente é feito o select all da SP para a emissão do relatório;
  BDIND13PISES = 0;
  BDTPVALORPISPASEPES = 0;
  BDVALORPISPASEPES = 0;
  BDVALORPISPASEP13ES = 0;
  BDVALORPISPASEP = 0;
  BDVALORPISPASEP13 = 0;
  BDTAGSTR = '';
  BDDESCRICAOFOLHA = '';
  --#206764 - Fim;


  WSQLPRINCIPAL = 'SELECT COALESCE(E.BDCODMATRIZ, COL.BDCODEMP) BDCODMATRIZ, E.BDCNPJEMP, EREF.BDNOMEMP ,COL.BDCODEMP,COL.BDCODCOL, COL.BDCPFCOL, COLCAD.BDNOMCOL, COL.BDCONTRCOL, FGTS.bdcategoriaesocial, COL.BDMATRICULA ' ||
                  ' FROM VRH_EMP_TCOLCON COL ' ||
                  ' INNER JOIN TEMPRESAS E ON E.BDCODEMP = COL.BDCODEMP ' ||
                  ' inner join TEMPRESAS_REF EREF on EREF.BDCODEMP = E.BDCODEMP and EREF.BDREFEMP = (select max(BDREFEMP) from TEMPRESAS_REF WHERE BDCODEMP = E.BDCODEMP)' ||
                  ' inner join VRH_EMP_TCOLCON_CAD COLCAD on COLCAD.BDCODEMP = COL.BDCODEMP and COLCAD.BDCODCOL = COL.BDCODCOL and COLCAD.BDREFCOL = (select max(BDREFCOL) from VRH_EMP_TCOLCON_CAD WHERE BDCODEMP = COL.BDCODEMP and BDCODCOL = COL.BDCODCOL and BDREFCOL <= '||PRREF||')' ||
                  ' inner join VRHF_EMP_TCOLCON_FGTSGPS FGTS on FGTS.BDCODEMP = COL.BDCODEMP and FGTS.BDCODCOL = COL.BDCODCOL and FGTS.BDREFCOL = (select max(BDREFCOL) from VRHF_EMP_TCOLCON_FGTSGPS WHERE BDCODEMP = COL.BDCODEMP and BDCODCOL = COL.BDCODCOL and BDREFCOL <= '||PRREF||')' ||
                  ' where UPPER(E.BDEXPINIESOCIAL) = ' || '''' || 'TRUE' || '''';


  if ((PRCODEMP is not null) and (PRCODEMP <> '')) then
    begin
    WSQLPRINCIPAL = WSQLPRINCIPAL ||' and (not exists(select DOC.BDCODEMP '|| /*Contribuinte com baixa*/
                                                     'from VRH_EMP_TCON_DOC DOC '||
                                                     'where (DOC.BDCODEMP = COLCAD.BDCODEMP) and '||
                                                           '(DOC.BDCODCOL = COLCAD.BDCODCOL) and '||
                                                           '(DOC.BDDATABAIXACOL < '''|| substring(cast(PRREF as varchar(6)) from 1 for 4)||'/'||substring(cast(PRREF as varchar(6)) from 5 for 2)||'/01'''|| '))) '||
                                          ' and (not exists(select RESC.BDCODEMP '|| /*Rescisão*/
                                                      'from VRH_EMP_TRESCISAO RESC '||
                                                      'where (RESC.BDCODEMP = COLCAD.BDCODEMP) and '||
                                                            '(RESC.BDCODCOL = COLCAD.BDCODCOL) and '||
                                                            '(RESC.BDREFRESCISAO < '||PRREF||')) or '||
                                          -- Complementar normal e complementar intermitente normal
                                          'exists(select FOLCOMP.BDCODEMP '||
                                                 'from VRHF_EMP_TFOLHACOMP FOLCOMP '||
                                                 'where (FOLCOMP.BDCODEMP = COLCAD.BDCODEMP) and '||
                                                       '(FOLCOMP.BDCODCOL = COLCAD.BDCODCOL) and '||
                                                       '(FOLCOMP.BDREFCOMP = '||PRREF||')) or '||
                                          'exists(select FOLCOMPADC.BDCODEMP '||
                                                 'from VRHF_EMP_TFOLHACOMP FOLCOMPADC '||
                                                 'left outer join VRH_EMP_TACCONV ADC on (ADC.BDCODEMP = FOLCOMPADC.BDCODEMP) and '||
                                                 '(ADC.BDCODACCONV = FOLCOMPADC.BDCODACCONV) '||
                                                 'where (FOLCOMPADC.BDCODEMP = COLCAD.BDCODEMP) and '||
                                                       '(FOLCOMPADC.BDCODCOL = COLCAD.BDCODCOL) and '||
                                                       '((FOLCOMPADC.BDCODTIPOFC=3 and FOLCOMPADC.bdcodacconv is not null and ( '||PRREF||' = (select * from AAAAMM(coalesce(ADC.BDDTPGTOBRICONV, ''1900-01-01''))))) or '||
                                                       '((FOLCOMPADC.BDCODTIPOFC=1 and '||PRREF||'=(select * from AAAAMM(coalesce(ADC.BDDTACCONV, ''1900-01-01''))))))) or ' ||
                                          'exists(select COMPINT.BDCODEMP '||
                                                 'from VRHF_EMP_TFOLHACOMPINT COMPINT '||
                                                 'where (COMPINT.BDCODEMP = COLCAD.BDCODEMP) and '||
                                                       '(COMPINT.BDCODCOL = COLCAD.BDCODCOL) and '||
                                                       '(COMPINT.BDREFFC = '||PRREF||')) or '||
                                          'exists(select COMPINTADC.BDCODEMP '||
                                                 'from VRHF_EMP_TFOLHACOMPINT COMPINTADC '||
                                                 'left outer join VRH_EMP_TACCONV ADC on (ADC.BDCODEMP = COMPINTADC.BDCODEMP) and (ADC.BDCODACCONV = COMPINTADC.BDCODACCONV) '||
                                                 'where (COMPINTADC.BDCODEMP = COLCAD.BDCODEMP) and '||
                                                       '(COMPINTADC.BDCODCOL = COLCAD.BDCODCOL) and '||
                                                       '((COMPINTADC.BDCODTIPOFC=3 and COMPINTADC.bdcodacconv is not null and ( '||PRREF||' = (select * from AAAAMM(coalesce(ADC.BDDTPGTOBRICONV, ''1900-01-01''))))) or '||
                                                       '((COMPINTADC.BDCODTIPOFC=1 and '||PRREF||'=(select * from AAAAMM(coalesce(ADC.BDDTACCONV, ''1900-01-01''))))))) or ' ||
                                          -- Complementar tomador e complementar tomador intermitente
                                          'exists(select FOLTOMCOMP.BDCODEMP '||
                                                 'from VRHF_EMP_TFOLTOMCOMP FOLTOMCOMP '||
                                                 'where (FOLTOMCOMP.BDCODEMP = COLCAD.BDCODEMP) and '||
                                                       '(FOLTOMCOMP.BDCODCOL = COLCAD.BDCODCOL) and '||
                                                       '(FOLTOMCOMP.BDREFCOMP = '||PRREF||')) or '||
                                          'exists(select FOLTOMCOMPADC.BDCODEMP '||
                                                 'from VRHF_EMP_TFOLTOMCOMP FOLTOMCOMPADC '||
                                                 'left outer join VRH_EMP_TACCONV ADC on (ADC.BDCODEMP = FOLTOMCOMPADC.BDCODEMP) and (ADC.BDCODACCONV = FOLTOMCOMPADC.BDCODACCONV) '||
                                                 'where (FOLTOMCOMPADC.BDCODEMP = COLCAD.BDCODEMP) and '||
                                                       '(FOLTOMCOMPADC.BDCODCOL = COLCAD.BDCODCOL) and '||
                                                       '((FOLTOMCOMPADC.BDCODTIPOFC=3 and FOLTOMCOMPADC.bdcodacconv is not null and ( '||PRREF||' = (select * from AAAAMM(coalesce(ADC.BDDTPGTOBRICONV, ''1900-01-01''))))) or '||
                                                       '((FOLTOMCOMPADC.BDCODTIPOFC=1 and '||PRREF||'=(select * from AAAAMM(coalesce(ADC.BDDTACCONV, ''1900-01-01''))))))) or ' ||
                                          'exists(select COMPTOMINT.BDCODEMP '||
                                                'from VRHF_EMP_TFOLTOMCOMPINT COMPTOMINT '||
                                                'where (COMPTOMINT.BDCODEMP = COLCAD.BDCODEMP) and '||
                                                      '(COMPTOMINT.BDCODCOL = COLCAD.BDCODCOL) and '||
                                                      '(COMPTOMINT.BDREFFC = '||PRREF||')) or '||
                                          'exists(select COMPTOMINTADC.BDCODEMP '||
                                                'from VRHF_EMP_TFOLTOMCOMPINT COMPTOMINTADC '||
                                                'left outer join VRH_EMP_TACCONV ADC on (ADC.BDCODEMP = COMPTOMINTADC.BDCODEMP) and (ADC.BDCODACCONV = COMPTOMINTADC.BDCODACCONV) '||
                                                'where (COMPTOMINTADC.BDCODEMP = COLCAD.BDCODEMP) and '||
                                                      '(COMPTOMINTADC.BDCODCOL = COLCAD.BDCODCOL) and '||
                                                      '((COMPTOMINTADC.BDCODTIPOFC=3 and COMPTOMINTADC.bdcodacconv is not null and ( '||PRREF||' = (select * from AAAAMM(coalesce(ADC.BDDTPGTOBRICONV, ''1900-01-01''))))) or '||
                                                      '((COMPTOMINTADC.BDCODTIPOFC=1 and '||PRREF||'=(select * from AAAAMM(coalesce(ADC.BDDTACCONV, ''1900-01-01''))))))))  ' ||
                                          ' and (not exists(select TRAN.BDCODEMPORIG '||  /*Colaborador transferido*/
                                                            'from VRH_EMP_TTRANSCOL TRAN '||
                                                            'where (TRAN.BDCODEMPORIG = COLCAD.BDCODEMP) and '||
                                                                  '(TRAN.BDCODCOLORIG = COLCAD.BDCODCOL) and '||
                                                                  '(TRAN.BDREFTRF < '||PRREF||')))';
                                    
      if (position('=', PRCODEMP) > 0) then
        WLISTAEMP = SUBSTRING(PRCODEMP from position('=', PRCODEMP)+1 for CHAR_LENGTH(PRCODEMP));
      if (position('in', PRCODEMP) > 0) then
        WLISTAEMP = SUBSTRING(PRCODEMP from position('in', PRCODEMP)+2 for CHAR_LENGTH(PRCODEMP));

      if (position('(', WLISTAEMP) > 0) then
        WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ((E.BDCODMATRIZ in ' || WLISTAEMP || ') OR (COL.BDCODEMP in ' || WLISTAEMP || '))';
      else
        WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ((E.BDCODMATRIZ in (' || WLISTAEMP || ')) OR (COL.BDCODEMP in (' || WLISTAEMP || ')))';
    end

  if ((PRREF is not null) and (PRREF <> 0)) then
  begin
    WMES = cast(substring(cast(PRREF as varchar(6)) from 5 for 2) as integer);
    WANO = cast(substring(cast(PRREF as varchar(6)) from 1 for 4) as integer);
    select ULTDIA from ULTIMO_DIA_MES(:WMES, :WANO) into WULTDIA;
    WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND (COL.BDDATAADMCOL <=''' || substring(cast(PRREF as varchar(6)) from 5 for 2) || '/' || WULTDIA || '/' || substring(cast(PRREF as varchar(6)) from 1 for 4) || ''')';
  end

  if ((PRFILTROCPF is not null) and (PRFILTROCPF <> '')) then
    WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ' ||PRFILTROCPF;

  WEMPCARREGADA = 0;
  WCPFANTERIOR = '';
  WSQLPRINCIPAL = WSQLPRINCIPAL || ' ORDER BY COALESCE(E.BDCODMATRIZ,COL.BDCODEMP), COL.BDCPFCOL, COL.BDCODCOL';
  for execute statement WSQLPRINCIPAL
      into :WCODMATRIZ, :WCNPJEMP, :WNOMEMP, :WCODEMP, :WCODCOL, :WCPFCOL, :WNOMCOL, :WCONTRCOL, :wcategoriaesocial, :wmatriculaatual
  do
  begin
    if ((WCPFANTERIOR <> WCPFCOL) or ((WCPFANTERIOR = WCPFCOL) and (WEMPCARREGADA <> WCODEMP)) or (wcatesocialcarregada <> wcategoriaesocial) or (wmatriculaanterior <> wmatriculaatual))  then
      begin
        if ((WCPFANTERIOR <> '') and ((WTEMEVENTO > 0) or (WTEMCALCFN > 0) or (WTEMCALCFT > 0))) then
          suspend;

          WCPFANTERIOR         = WCPFCOL;
          WEMPCARREGADA        = WCODEMP;
          WCATESOCIALCARREGADA = wcategoriaesocial;
          wmatriculaanterior   = wmatriculaatual;

          BDBASEFGTS = 0;
          BDBASEFGTS13 = 0;
          BDBASEFGTSRES = 0;
          BDBASEAVPREV = 0;
          BDVALORFGTS = 0;
          BDVALORFGTS13 = 0;
          BDVALORFGTSRES = 0;
          BDVALORAVPREV = 0;
    
          BDBASEFGTSES = 0;
          BDBASEFGTS13ES = 0;
          BDBASEFGTSRESES = 0;
          BDBASEAVPREVES = 0;
          BDVALORFGTSES = 0;
          BDVALORFGTS13ES = 0;
          BDVALORFGTSRESES = 0;
          BDVALORAVPREVES = 0;

          WBASEFGTS = 0;
          WBASEFGTS13 = 0;
          WBASEFGTSRES = 0;
          WBASEAVPREV = 0;
          WVALORFGTS = 0;
          WVALORFGTS13 = 0;
          WVALORFGTSRES = 0;
          WVALORAVPREV = 0;

          WBASEFGTSES = 0;
          WBASEFGTS13ES = 0;
          WBASEFGTSRESES = 0;
          WBASEAVPREVES = 0;
          WVALORFGTSES = 0;
          WVALORFGTS13ES = 0;
          WVALORFGTSRESES = 0;
          WVALORAVPREVES = 0;

          WCALCULOS = 0;
          BDCOUNTFC =0;
          BDBASEFGTS13RESC = 0;
          BDVALORFGTS13RESC = 0;
          BDVALORFGTS13RESCES = 0;
          BDBASEFGTS13RESCES = 0;
          BDINSTITUICAOFINANCES = 0;
          BDNROCONTRATOECONSIGNADOES = '';
          BDVALORECONSIGNADOES = 0;
          BDINSTITUICAOFINANC = 0;
          BDNROCONTRATOECONSIGNADO = '';
      end

    if (PR13 = 0) then
      begin
        select BDBFGTS, BDBFGTS13, BDBFGTSRES, BDBAVPREV, BDFGTS, BDFGTS13, BDFGTSRES, BDAVPREV, BDCALCULOS, COALESCE(BDCOUNTFC, 0), BDBASEFGTS13RESC, BDFGTS13RESC, BDECONSIGNADO, BDECONSIGNADORESC
        from SP_RETORNA_BASE_FGTS_2(:WCODEMP, :WCODCOL, :PRREF, :wcategoriaesocial)
        into :WBASEFGTS, :WBASEFGTS13, :WBASEFGTSRES, :WBASEAVPREV, :WVALORFGTS, :WVALORFGTS13, :WVALORFGTSRES,
             :WVALORAVPREV, :WCALCULOS, :BDCOUNTFC, :WBASEFGTS13RESC, :WVALORFGTS13RESC, :BDECONSIGNADO, :BDECONSIGNADORESC;

         if ((BDECONSIGNADO <> 0) or (BDECONSIGNADORESC <> 0)) then
            begin
               WSQL2 = 'select first 1 coalesce(parc.BDCODBANECONSIGNADO,parc.bdcodban) bdcodban, parc.bdcontratopar from vrh_emp_tparcelamentos parc '||
                           'join vrh_emp_tparcelamentos_itens it on (it.bdcodemp = parc.bdcodemp and it.bdcodcol = parc.bdcodcol and it.bdcodparc = parc.bdcodparc) '||
                           'where parc.bdcodemp = '||CAST(WCODEMP AS VARCHAR(10))||
                           '      and parc.bdcodcol = '||CAST(WCODCOL AS VARCHAR(10))||
                           '      and it.bdrefpi = '||PRREF||
                           '      and parc.bdeconsignado = true';

               execute statement WSQL2 into :BDINSTITUICAOFINANC, :BDNROCONTRATOECONSIGNADO;
            end
        
        
        select BDBFGTSES, BDBFGTS13ES, BDBFGTSRESES, BDBAVPREVES, BDFGTSES, BDFGTS13ES, BDFGTSRESES, BDAVPREVES, BDBASEFGTS13RESCES, BDVALORFGTS13RESCES, BDINSTITUICAOFINANCES, BDNROCONTRATOECONSIGNADOES, BDVALORECONSIGNADOES
        from SP_RETORNA_BASE_ESOCIAL(:WCODEMP, :WCODCOL, :PRREF, 0)
        into :WBASEFGTSES, :WBASEFGTS13ES, :WBASEFGTSRESES, :WBASEAVPREVES, :WVALORFGTSES, :WVALORFGTS13ES,
             :WVALORFGTSRESES, :WVALORAVPREVES, :WBASEFGTS13RESCES, :WVALORFGTS13RESCES, :BDINSTITUICAOFINANCES, :BDNROCONTRATOECONSIGNADOES, :BDVALORECONSIGNADOES;
      end

    if (PR13 = 1) then
      begin
        select 0 BDBFGTS, COALESCE(F13.BDBASEFGTS13, 0) BDBFGTS13, 0 BDBFGTSRES, 0 BDBAVISOPREV, 0 BDFGTS, COALESCE(F13.BDFGTS13, 0) BDFGTS13, 0 BDFGTSRES, 0 BDAVISOPREV, 1 as BDCALCULOS, 0 as BDCOUNTFC
        from VRHF_EMP_T13SAL F13
        inner join VRH_EMP_TCOLCON COLF on COLF.BDCODEMP = F13.BDCODEMP and COLF.BDCODCOL = F13.BDCODCOL
        where F13.BDCODEMP = :WCODEMP and F13.BDCODCOL = :WCODCOL and F13.BDANO13 = :WANO
        into :WBASEFGTS, :WBASEFGTS13, :WBASEFGTSRES, :WBASEAVPREV, :WVALORFGTS, :WVALORFGTS13, :WVALORFGTSRES,
             :WVALORAVPREV, :WCALCULOS, :BDCOUNTFC;

        select BDBFGTSES, BDBFGTS13ES, BDBFGTSRESES, BDBAVPREVES, BDFGTSES, BDFGTS13ES, BDFGTSRESES, BDAVPREVES
        from SP_RETORNA_BASE_ESOCIAL(:WCODEMP, :WCODCOL, :PRREF, 1)
        into :WBASEFGTSES, :WBASEFGTS13ES, :WBASEFGTSRESES, :WBASEAVPREVES, :WVALORFGTSES, :WVALORFGTS13ES,
             :WVALORFGTSRESES, :WVALORAVPREVES;

      end


    select first 1 FGTS.BDCATEGORIAESOCIAL, CLA.BDGRUPOCLA
    from VRHF_EMP_TCOLCON_FGTSGPS FGTS
    left outer join VRH_EMP_TCOLCON_VINC VINC on VINC.BDCODEMP = FGTS.BDCODEMP and VINC.BDCODCOL = FGTS.BDCODCOL and VINC.BDREFCOL <= :PRREF
    left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
    where FGTS.BDCODEMP in (:WCODEMP) and
          FGTS.BDCODCOL = :WCODCOL and
          (FGTS.BDREFCOL <= :PRREF)
    order by FGTS.BDREFCOL desc
    into :WCATESOCIAL, :WGRUPOCLA;

    select first 1 BDCODCLATRI
    from VRHF_BASE_TEMPESOCIAL ES
    where ES.BDCODEMP in (:WCODEMP) and
                    (ES.BDREFEMP <= :PRREF)
    order by BDREFEMP desc
    into :WCODCLATRI;

    if (PR13 = 0) then
       begin
         EXECUTE PROCEDURE SP_ADD_CONSIGNADO_5003(:WCODEMP, :WCODCOL, :WCPFCOL, :PRREF, :WCODMATRIZ, :WGRUPOCLA, :WCONTRCOL, :WCNPJEMP, :WCATEGORIAESOCIAL);
       end

    IF (((WCONTRCOL = 1) AND (WCATESOCIAL = 721)) OR (WCONTRCOL <> 1)) THEN
        BEGIN
            --VALORES ÚNICO
            --Base FGTS Mensal e Rescisório
            BDBASEFGTS     = BDBASEFGTS     + WBASEFGTS;
            BDBASEFGTSRES  = BDBASEFGTSRES  + WBASEFGTSRES;
            --Base FGTS 13º Mensal e rescisório
            BDBASEFGTS13     = BDBASEFGTS13     + WBASEFGTS13;
            BDBASEFGTS13RESC = BDBASEFGTS13RESC + wbasefgts13resc;
            --Base aviso prévio
            BDBASEAVPREV   = BDBASEAVPREV   + WBASEAVPREV;
            --Valores FGTS Mensal e Rescisório
            BDVALORFGTS    = BDVALORFGTS    + WVALORFGTS;
            BDVALORFGTSRES = BDVALORFGTSRES + WVALORFGTSRES;
            --Valores FGTS 13º Mensal e Rescisório
            BDVALORFGTS13     = BDVALORFGTS13     + WVALORFGTS13;
            BDVALORFGTS13RESC = BDVALORFGTS13RESC + wvalorfgts13resc;
            --Valor de aviso prévio
            BDVALORAVPREV  = BDVALORAVPREV  + WVALORAVPREV;

            --VALORES ESOCIAL
            --Base FGTS Mensal e Rescisório eSocial
            BDBASEFGTSES     = BDBASEFGTSES + WBASEFGTSES;
            BDBASEFGTSRESES  = BDBASEFGTSRESES + WBASEFGTSRESES;
            --Base FGTS 13º Mensal e Rescisório eSocial
            BDBASEFGTS13ES     = BDBASEFGTS13ES     + WBASEFGTS13ES;
            BDBASEFGTS13RESCES = BDBASEFGTS13RESCES + WBASEFGTS13RESCES;
            --Base Aviso Prévio
            BDBASEAVPREVES   = BDBASEAVPREVES + WBASEAVPREVES;
            --Valor FGTS Mensal e Rescisório eSocial
            BDVALORFGTSES    = BDVALORFGTSES + WVALORFGTSES;
            BDVALORFGTSRESES = BDVALORFGTSRESES + WVALORFGTSRESES;
            --Valor FGTS 13º Mensal e Rescisório
            BDVALORFGTS13ES    = BDVALORFGTS13ES      + WVALORFGTS13ES;
            BDVALORFGTS13RESCES = BDVALORFGTS13RESCES + WVALORFGTS13RESCES;
            --Valor de aviso prévio
            BDVALORAVPREVES  = BDVALORAVPREVES + WVALORAVPREVES;
        END
    ELSE
        BEGIN
            BDBASEFGTS = 0;
            BDBASEFGTS13 = 0;
            BDBASEFGTSRES = 0;
            BDBASEAVPREV = BDBASEAVPREV + WBASEAVPREV;
            BDVALORFGTS = 0;
            BDVALORFGTS13 = 0;
            BDVALORFGTSRES = 0;
            BDVALORAVPREV = BDVALORAVPREV + WVALORAVPREV;
        
            BDBASEFGTSES = 0;
            BDBASEFGTS13ES = 0;
            BDBASEFGTSRESES = 0;
            BDBASEAVPREVES = BDBASEAVPREVES + WBASEAVPREVES;
            BDVALORFGTSES = 0;
            BDVALORFGTS13ES = 0;
            BDVALORFGTSRESES = 0;
            BDVALORAVPREVES = BDVALORAVPREVES + WVALORAVPREVES;
        END

    BDCODEMPORD = WCODMATRIZ;
    BDCNPJEMP = WCNPJEMP;
    BDNOMEMP = WNOMEMP;
    BDCODEMP = WCODEMP;
    BDCODCOL = WCODCOL;
    BDCPFCOL = WCPFCOL;
    BDNOMCOL = WNOMCOL;
    BDCONTRCOL = WCONTRCOL;
    BDCATEGORIAESOCIAL = WCATESOCIAL;
    BDCODCLATRI = WCODCLATRI;
    BDGRUPOCLA = WGRUPOCLA;
    BDCALCULOS = WCALCULOS;
    BDCOLTER = 1;
    BDCTS5001 = -10;

    WTEMEVENTO = 0;
    WTEMCALCFN = 0;
    WTEMCALCFT = 0;

    if (PR13 = 0) then
      begin
        select count (EVT.BDCODIGO), count(FN.BDREFFN), count(FT.BDORDEM)
        from VRH_ESOCIAL_TARQUIVO EVT
        left outer join VRHF_EMP_TFOLHANORMAL FN ON FN.BDCODEMP = EVT.BDCODEMP and FN.BDCODCOL = EVT.BDCODCOL and FN.BDREFFN = EVT.BDREFARQ
        left outer join VRHF_EMP_TFOLHATOMADOR FT ON FT.BDCODEMP = EVT.BDCODEMP and FT.BDCODCOL = EVT.BDCODCOL and FT.BDREFTOMADOR = EVT.BDREFARQ
        where EVT.BDCODEMP = :WCODEMP and EVT.BDCODCOL = :WCODCOL and EVT.BDSTATUS = 2 and EVT.BDCODTIPO in (11, 34, 37) and EVT.BDREFARQ = :PRREF
          into :WTEMEVENTO, :WTEMCALCFN, :WTEMCALCFT;
      end
    else 
      WTEMEVENTO = 1;
      WTEMCALCFN = 1;
      WTEMCALCFT = 1;

  end

  if (WCPFANTERIOR = WCPFCOL) then
  begin
    if (WCPFANTERIOR <> '') then
      suspend;
  end
end^

create or alter procedure VRH_SP_ATUALIZA_IR_EVENTO
returns(
BDCODEMP integer,
BDCODEVTATUALIZADO integer
)
as
declare variable WSQL varchar(10000);
declare variable WCODEVT integer;
declare variable WCODEMP integer;
declare variable WVALOR numeric(18,2);
declare variable WXML blob;
declare variable WSTR blob;
begin
  WSQL = 'select XML.BDCODIGO, XML.BDCODEMP, XML.VALOR '||
         'from (select ARQ.BDCODIGO, ARQ.BDCODEMP, cast(UNZIPBLOB(XML.BDXML) as blob) VALOR '||
               'from VRH_ESOCIAL_TARQUIVO ARQ '||
               'left outer join VRH_ESOCIAL_TARQUIVO_XML XML on (ARQ.BDCODIGO = XML.BDCODIGO and '||
               'ARQ.BDCODEMP = XML.BDCODEMP) '||
               'where ARQ.BDCODTIPO = 41 and (ARQ.BDVERSAOXML >= 1000 and ARQ.BDVERSAOXML <= 2000) and '||
               'ARQ.BDENVVALORTOTAL = 0) XML '||
               'where XML.VALOR containing ''<tpInfoIR>''';

  for execute statement WSQL
          into :WCODEVT, :WCODEMP, :WXML
  do
  begin
    WVALOR = 0;
    WSTR = '';
    WSTR = WXML;

    while (position('<tpInfoIR>', WSTR) > 0) do
      begin
        if (CAST(SUBSTRING(WSTR FROM POSITION('<tpInfoIR>' IN WSTR) + 10 FOR POSITION('</tpInfoIR>' IN WSTR) - POSITION('<tpInfoIR>' IN WSTR) - 10) AS INTEGER) IN (31,32,34)) then
          begin
            WVALOR = WVALOR + CAST(SUBSTRING(WSTR FROM POSITION('<valor>' IN WSTR) + 7 FOR POSITION('</valor>' IN WSTR) - POSITION('<valor>' IN WSTR) - 7) AS numeric(18,3));
          end
        WSTR = SUBSTRING(WSTR from position('</valor>' IN WSTR) + 8 for char_length(WSTR));
      end

    update VRH_ESOCIAL_TARQUIVO ARQ
    set BDENVVALORTOTAL = :WVALOR
    where ARQ.BDCODIGO = :WCODEVT and
          ARQ.BDCODEMP = :WCODEMP;

    BDCODEMP = :WCODEMP;
    BDCODEVTATUALIZADO = :WCODEVT;
  end




  WSQL = 'select XML.BDCODIGO, XML.BDCODEMP ,substring(XML.VALOR from position(''<vrCRMen>'' in XML.VALOR) + 9 for position(''</vrCRMen>'' in XML.VALOR) -          position(''<vrCRMen>'' in XML.VALOR) - 9) as VALOR '||
         'from (select ARQ.BDCODIGO, ARQ.BDCODEMP, cast(UNZIPBLOB(XML.BDXML) as blob) VALOR '||
               'from VRH_ESOCIAL_TARQUIVO ARQ '||
               'join VRH_ESOCIAL_TARQUIVO_XML XML on (ARQ.BDCODIGO = XML.BDCODIGO and ARQ.BDCODEMP = XML.BDCODEMP) '||
               'where ARQ.BDCODTIPO = 43 and ARQ.BDENVVALORTOTAL = 0 and (ARQ.BDVERSAOXML >= 1000 and ARQ.BDVERSAOXML <= 2000)) XML '||
         'where XML.VALOR containing ''<vrCRMen>''';

  for execute statement WSQL
          into :WCODEVT, :WCODEMP, :WVALOR
  do
  begin
    update VRH_ESOCIAL_TARQUIVO ARQ
    set BDENVVALORTOTAL = :WVALOR
    where ARQ.BDCODIGO = :WCODEVT and
          ARQ.BDCODEMP = :WCODEMP;

    BDCODEMP = :WCODEMP;
    BDCODEVTATUALIZADO = :WCODEVT;
  end
end^

create or alter procedure SP_VRH_ATU_REGTRAB
returns(
BDCODEMP integer,
BDCODCOL integer,
BDREF integer
)
as
declare variable WSQL varchar(10000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WREGTRAB integer;
declare variable WCATESOCIAL integer;
begin

  WSQL = 'select FGTS.BDCODEMP, FGTS.BDCODCOL, FGTS.BDREFCOL, FGTS.BDCATEGORIAESOCIAL '||
         'from VRHF_EMP_TCOLCON_FGTSGPS FGTS '||
         'where (FGTS.BDREGIMETRAB is null) or  (FGTS.BDREGIMETRAB = 0)';

  for execute statement WSQL
          into :WCODEMP, :WCODCOL, :WREF, :WCATESOCIAL
  do
  begin
    :WREGTRAB = 0;

    if (:WCATESOCIAL in (101, 102 ,103, 104, 105, 106, 107, 108,111)) then
      :WREGTRAB = 1;

    update VRHF_EMP_TCOLCON_FGTSGPS FGTSGPS
    set BDREGIMETRAB = :WREGTRAB
    where FGTSGPS.BDCODEMP = :WCODEMP and
          FGTSGPS.BDCODCOL = :WCODCOL and
          FGTSGPS.BDREFCOL = :WREF;
  end
end^

create or alter procedure SP_ATU_PARAMCONTCC
as
declare variable WCODMAT integer;
declare variable WCODEMP integer;
declare variable WREFEMP integer;
declare variable WNAOCONTCENTROCUSTO VARCHAR(5);
begin
    for select EMP.BDCODMATRIZ, EMP.BDCODEMP
    from TEMPRESAS EMP
    where EMP.BDCODMATRIZ is not NULL
    into
     :WCODMAT, :WCODEMP
    do 
      begin
        select coalesce(BDNAOCONTCENTROCUSTO, 'FALSE'), BDREFEMP
        from TEMPRESAS_REF 
        where BDCODEMP = :WCODMAT and BDREFEMP = (select min(BDREFEMP) from TEMPRESAS_REF where BDCODEMP = :WCODMAT and coalesce(BDNAOCONTCENTROCUSTO, 'FALSE') = 'TRUE')
        into :WNAOCONTCENTROCUSTO, :WREFEMP;

        if (:WNAOCONTCENTROCUSTO = 'TRUE') then
          update TEMPRESAS_REF set BDNAOCONTCENTROCUSTO = 'TRUE' where BDCODEMP = :WCODEMP;
      end
end^

/* Restore proc. body: SP_VRHF_PBM_GPS */
create or alter procedure SP_VRHF_PBM_GPS (
    PREMP varchar(30000),
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDCODEMP integer,
    BDCODMATRIZ integer,
    BDREF integer,
    BDCODREC integer,
    BDPERC numeric(15,4),
    BDBASEPBM numeric(18,2),
    BDBASEFAT numeric(18,2),
    BDBASEFATMES numeric(18,2))
as
declare variable WSQL varchar(32700);
declare variable WBASEFAT numeric(15,6);
declare variable WBLOCOP integer;
declare variable WEMPATU integer;
declare variable WSQL2 varchar(32700);
begin
  wsql = 'select P.BDCODEMP, P.BDREF, P.BDBASEFAT '||
         'from VRH_EMP_TPBM P '||
         'join TEMPRESAS EMP on (EMP.BDCODEMP = P.BDCODEMP) '||
         'where P.BDREF between '||prrefini||' and '||prreffim;

  if (coalesce(premp, '') <> '') then
     begin
       wsql = wsql||' and (('||replace(upper(premp), 'BDCODEMP', 'EMP.BDCODEMP')||') or (';

       wsql = wsql||replace(upper(premp), 'BDCODEMP', 'EMP.BDCODMATRIZ')||'))';
     end

  wsql = wsql||' order by P.BDCODEMP, P.BDREF';

  BDBASEFAT = 0;
  wblocop = 0;
  wempatu = 0;

  for execute statement wsql
  into :BDCODEMP, :BDREF, :wbasefat
  do
    begin
      --select first 1 BDCODCONFBLOCOP from VEF_BASE_TEMPPARGER where BDCODEMP = :BDCODEMP and BDREFEMP <= :BDREF order by BDREFEMP desc into :wblocop;
      wsql2 = 'select first 1 BDCODCONFBLOCOP from VW_VEF_BASE_TEMPPARGER where BDCODEMP = '||:BDCODEMP||' and BDCODCONFBLOCOP is not null ';
      execute statement wsql2 into :wblocop;

      if (wempatu <> BDCODEMP) then
         begin
           BDBASEFAT = 0;
           wempatu = BDCODEMP;
         end

      if (coalesce(wblocop, 0) > 0) then
         begin
           BDBASEFAT = BDBASEFAT + wbasefat;
           BDBASEFATMES = wbasefat;

           for select BDCODREC, BDPERC, BDBASE
               from VRH_EMP_TPBM_REC
               where BDCODEMP = :BDCODEMP and BDREF = :BDREF
           into :BDCODREC, :BDPERC, :BDBASEPBM
           do
             begin
               select first 1 coalesce(BDCODMATRIZ, BDCODEMP) from TEMPRESAS where BDCODEMP = :BDCODEMP into :BDCODMATRIZ;
               suspend;
             end
         end
    end
end^

CREATE OR ALTER TRIGGER VRH_BASE_TRECLAMATORIA_BI0 FOR VRH_BASE_TRECLAMATORIA
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;
begin
  if (coalesce(new.bdcodrt, 0) <= 0) then
     begin
       SELECT coalesce(max(BDCODRT), 0) + 1 from VRH_BASE_TRECLAMATORIA into :vcod;
       new.bdcodrt = :vcod;
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_BI0 FOR VRH_EMP_TRECLAMATORIA
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vchave INTEGER;
begin
  if (coalesce(new.bdchave, 0) <= 0) then
     begin
       select coalesce(max(BDCHAVE), 0) + 1 from VRH_EMP_TRECLAMATORIA where BDCODEMP = new.bdcodemp into :vchave;
       new.bdchave = :vchave;
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_DEP_BI0 FOR VRH_EMP_TRECLAMATORIA_DEP
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wcod INTEGER;
begin
  if (coalesce(new.bdchave, 0) = 0) then
     begin
       wcod = null;
       select max(BDCHAVE) from VRH_EMP_TRECLAMATORIA where BDCODEMP = new.bdcodemp into :wcod;
       new.bdchave = :wcod;
     end

  if (coalesce(new.bdcoddep, 0) = 0) then
     begin
       wcod = null;
       select coalesce(max(BDCODDEP), 0) + 1 from VRH_EMP_TRECLAMATORIA_DEP where BDCODEMP = new.bdcodemp and BDCHAVE = new.bdchave into :wcod;
       new.bdcoddep = :wcod;
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_VINC_BI0 FOR VRH_EMP_TRECLAMATORIA_VINC
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wcod INTEGER;
begin
  if (coalesce(new.bdchave, 0) = 0) then
     begin
       wcod = null;
       select max(BDCHAVE) from VRH_EMP_TRECLAMATORIA where BDCODEMP = new.bdcodemp into :wcod;
       new.bdchave = :wcod;
     end

  if (coalesce(new.bdcodvinc, 0) = 0) then
     begin
       wcod = null;
       select coalesce(max(BDCODVINC), 0) + 1 from VRH_EMP_TRECLAMATORIA_VINC where BDCODEMP = new.bdcodemp and BDCHAVE = new.bdchave into :wcod;
       new.bdcodvinc = :wcod;
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRT_VICCAT_BI0 FOR VRH_EMP_TRECLAMATORIA_VICCAT
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wcod INTEGER;
begin
  if (coalesce(new.bdchave, 0) = 0) then
     begin
       wcod = null;
       select max(BDCHAVE) from VRH_EMP_TRECLAMATORIA where BDCODEMP = new.bdcodemp into :wcod;
       new.bdchave = :wcod;
     end

  if (coalesce(new.bdcodvinc, 0) = 0) then
     begin
       wcod = null;
       select coalesce(max(BDCODVINC), 0) from VRH_EMP_TRECLAMATORIA_VINC where BDCODEMP = new.bdcodemp and BDCHAVE = new.bdchave into :wcod;
       new.bdcodvinc = :wcod;
     end

  if (coalesce(new.bdcodcat, 0) = 0) then
     begin
       wcod = null;
       select coalesce(max(BDCODCAT), 0) + 1 from VRH_EMP_TRECLAMATORIA_VICCAT where BDCODEMP = new.bdcodemp and BDCHAVE = new.bdchave and BDCODVINC = new.bdcodvinc into :wcod;
       new.bdcodcat = :wcod;
     end

end
^

CREATE OR ALTER TRIGGER VRHF_TINFO_TEMP_RENDTRIBRRA_BU0 FOR VRHF_TINFO_TEMP_RENDTRIBRRA
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  IF (OLD.BDSESSAO = NEW.BDSESSAO AND OLD.BDCODEMP = NEW.BDCODEMP AND OLD.BDCODCOL = NEW.BDCODCOL) THEN
     BEGIN
       if (coalesce(NEW.BDRENDIMENTOTRIBUTAVEL,0) <> 0) then
          NEW.BDRENDIMENTOTRIBUTAVEL = coalesce(OLD.BDRENDIMENTOTRIBUTAVEL,0) + NEW.BDRENDIMENTOTRIBUTAVEL;
       else
          NEW.BDRENDIMENTOTRIBUTAVEL = coalesce(OLD.BDRENDIMENTOTRIBUTAVEL,0);

       if (coalesce(NEW.BDIR,0) <> 0) then
          NEW.BDIR = coalesce(OLD.BDIR,0) + NEW.BDIR;
       else
          NEW.BDIR = coalesce(OLD.BDIR,0);

       if (coalesce(NEW.bdrendtribnormal,0) <> 0) then
          NEW.bdrendtribnormal = coalesce(OLD.bdrendtribnormal,0) + NEW.bdrendtribnormal;
       else
          NEW.bdrendtribnormal = coalesce(OLD.bdrendtribnormal,0);

       if (coalesce(NEW.bdirnormal,0) <> 0) then
          NEW.bdirnormal = coalesce(OLD.bdirnormal,0) + NEW.bdirnormal;
       else
          NEW.bdirnormal = coalesce(OLD.bdirnormal,0);

       if (coalesce(NEW.bdrendtribrt,0) <> 0) then
          NEW.bdrendtribrt = coalesce(OLD.bdrendtribrt,0) + NEW.bdrendtribrt;
       else
          NEW.bdrendtribrt = coalesce(OLD.bdrendtribrt,0);

       if (coalesce(NEW.bdirrt,0) <> 0) then
          NEW.bdirrt = coalesce(OLD.bdirrt,0) + NEW.bdirrt;
       else
          NEW.bdirrt = coalesce(OLD.bdirrt,0);
     END
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TREPERCUSSAOPROC_BI0 FOR VRH_BASE_TREPERCUSSAOPROC
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wcod INTEGER;
begin
  if (coalesce(new.bdcodrepercproc, 0) <= 0) then
     begin
       select coalesce(max(bdcodrepercproc), -1) + 1 from VRH_BASE_TREPERCUSSAOPROC into :wcod;
       new.bdcodrepercproc = :wcod;
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMA_CONTRATO_BI0 FOR VRH_EMP_TRECLAMA_CONTRATO
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wchave INTEGER;
begin
  if (coalesce(new.bdchave, 0) <= 0) then
     begin
       select coalesce(max(BDCHAVE), 1) from VRH_EMP_TRECLAMATORIA where BDCODEMP = new.bdcodemp into :wchave;
       new.bdchave = :wchave;
     end

  if (coalesce(new.bdcodvinc,0) <= 0) then
     begin
       select first 1 x.bdcodvinc from VRH_EMP_TRECLAMATORIA_vinc x
       where x.bdcodemp = new.bdcodemp and x.bdchave = new.bdchave order by x.bdcodvinc desc into wChave;
       new.bdcodvinc = :wChave;
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMA_IDPGTO_BI0 FOR VRH_EMP_TRECLAMATORIA_IDPGTO
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wcod INTEGER;
begin
  if (coalesce(new.bdchave, 0) <= 0) then
     begin
     wcod = null;
     select coalesce(max(BDCHAVE), 1) from VRH_EMP_TRECLAMATORIA where BDCODEMP = new.bdcodemp into :wcod;
     new.bdchave = :wcod;
     end

  if (coalesce(new.bdcodvinc,0) <= 0) then
     begin
       select first 1 x.bdcodvinc from VRH_EMP_TRECLAMATORIA_vinc x
       where x.bdcodemp = new.bdcodemp and x.bdchave = new.bdchave order by x.bdcodvinc desc into wcod;
       new.bdcodvinc = :wcod;
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_PGMES_BI0 FOR VRH_EMP_TRECLAMATORIA_PGMES
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wcod INTEGER;

begin
  if (coalesce(new.bdchave, 0) <= 0) then
     begin
       wcod = null;
       select coalesce(max(BDCHAVE), 1) from VRH_EMP_TRECLAMATORIA where BDCODEMP = new.bdcodemp into :wcod;
       new.bdchave = :wcod;
     end

  if (coalesce(new.bdcodvinc,0) <= 0) then
     begin
       select first 1 x.bdcodvinc from VRH_EMP_TRECLAMATORIA_vinc x
       where x.bdcodemp = new.bdcodemp and x.bdchave = new.bdchave order by x.bdcodvinc desc into wcod;
       new.bdcodvinc = :wcod;
     end

end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_REM_BI0 FOR VRH_EMP_TRECLAMATORIA_REM
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wcod INTEGER;
begin
  if (coalesce(new.bdchave, 0) <= 0) then
     begin
       wcod = null;
       select coalesce(max(BDCHAVE), 1) from VRH_EMP_TRECLAMATORIA where BDCODEMP = new.bdcodemp into :wcod;
       new.bdchave = :wcod;
     end

  if (coalesce(new.bdcodvinc, 0) <= 0) then
     begin
       wcod = null;
       select coalesce(max(BDCODVINC), 1) from VRH_EMP_TRECLAMATORIA_VINC where BDCODEMP = new.bdcodemp and BDCHAVE = new.bdchave into :wcod;
       new.bdcodvinc = :wcod;
     end

  if (coalesce(new.bdcodrem, 0) <= 0) then
     begin
       wcod = null;
       select coalesce(max(BDCODREM), 0) + 1 from VRH_EMP_TRECLAMATORIA_REM where BDCODEMP = new.bdcodemp and BDCHAVE = new.bdchave and BDCODVINC = new.bdcodvinc into :wcod;
       new.bdcodrem = :wcod;
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_ADM_BI0 FOR VRH_EMP_TRECLAMATORIA_ADM
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wcod INTEGER;
begin
  if (coalesce(new.bdchave, 0) <= 0) then
     begin
       wcod = null;
       select coalesce(max(BDCHAVE), 1) from VRH_EMP_TRECLAMATORIA where BDCODEMP = new.bdcodemp into :wcod;
       new.bdchave = :wcod;
     end

  if (coalesce(new.bdcodvinc, 0) <= 0) then
     begin
       wcod = null;
       select coalesce(max(BDCODVINC), 1) from VRH_EMP_TRECLAMATORIA_VINC where BDCODEMP = new.bdcodemp and BDCHAVE = new.bdchave into :wcod;
       new.bdcodvinc = :wcod;
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_RESC_BI0 FOR VRH_EMP_TRECLAMATORIA_RESC
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wcod INTEGER;
begin
  if (coalesce(new.bdchave, 0) <= 0) then
     begin
       wcod = null;
       select coalesce(max(BDCHAVE), 1) from VRH_EMP_TRECLAMATORIA where BDCODEMP = new.bdcodemp into :wcod;
       new.bdchave = :wcod;
     end

  if (coalesce(new.bdcodvinc, 0) <= 0) then
     begin
       wcod = null;
       select coalesce(max(BDCODVINC), 1) from VRH_EMP_TRECLAMATORIA_VINC where BDCODEMP = new.bdcodemp and BDCHAVE = new.bdchave into :wcod;
       new.bdcodvinc = :wcod;
     end
end
^
CREATE OR ALTER TRIGGER VRH_ESOCIAL_TTIPO_ARQ_BI0 FOR VRH_ESOCIAL_TTIPO_ARQ
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (coalesce(new.bdcodtipo, 0) <= 0) then
     select coalesce(max(BDCODTIPO), 0) + 1 from VRH_ESOCIAL_TTIPO_ARQ into new.bdcodtipo;
end
^

create or alter procedure SP_CONSULTA_PLANO_TROCA (
    PRCODEMP integer,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDREFEMP integer,
    BDCODPLATROCA integer,
    BDORDEM integer)
as
begin
  FOR SELECT V.BDCODEMP, V.BDREFEMP, V.BDCODPLATROCA, V.BDORDEM
      FROM VEF_BASE_TEMPVINCPLAN V
      WHERE V.BDCODEMP = :PRCODEMP                
--        AND V.BDREFEMP = (SELECT MAX(BDREFEMP) FROM TEMPRESAS_REF A
--                          WHERE A.BDCODEMP = V.BDCODEMP AND
--                                A.BDREFEMP <= Coalesce(:PRREF, A.BDREFEMP))
      /* Alt.: #224878 - Estava buscando a referencia, olhando a referencia da empresa, mas nem sempre vai ter esses dados na mesma referencia.
         Por isso vai fazer igual as views, olhar a referencia da tabela e pegar a menor ou a proxima valida... */
        AND V.BDREFEMP = (COALESCE(
                            (SELECT MAX(x.bdREFEMP)
                             FROM VEF_BASE_TEMPVINCPLAN x
                             WHERE x.bdCODEMP = v.bdCODEMP AND
                                   x.bdREFEMP <= Coalesce(:prREF, v.bdREFEMP)),
                            (SELECT FIRST 1 x.bdREFEMP
                             FROM VEF_BASE_TEMPVINCPLAN x
                             WHERE x.bdCODEMP = v.bdCODEMP
                             ORDER BY x.bdREFEMP)
                           ))
--        AND V.BDREFEMP = Coalesce((SELECT MAX(BDREFEMP) FROM VEF_BASE_TEMPVINCPLAN A
--                                   WHERE A.BDCODEMP = V.BDCODEMP AND
--                                         A.BDREFEMP <= Coalesce(:PRREF, A.BDREFEMP)),
--                                  (SELECT MAX(BDREFEMP) FROM VEF_BASE_TEMPVINCPLAN A WHERE A.BDCODEMP = V.BDCODEMP))
        AND V.BDCODPLATROCA > 0
      ORDER BY V.BDORDEM
  INTO :BDCODEMP, :BDREFEMP, :BDCODPLATROCA, :BDORDEM DO
  begin
    SUSPEND;
  end 
end
^

/* Restore proc. body: SP_CONSULTA_TERCEIROREF */
create or alter procedure SP_CONSULTA_TERCEIROREF (
    PRREF integer,
    PRCODTER integer)
returns (
    BDCODTER integer,
    BDCGCTER varchar(18),
    BDREFEMP integer,
    BDAPELIDOTER varchar(20),
    BDNOMETER varchar(100),
    BDLOGRTER varchar(15),
    BDENDTER DM_BDENDERECO,
    BDNUMTER DM_NUMEND,
    BDCOMPTER DM_BDCOMPENDERECO,
    BDCEPTER varchar(9),
    BDBAITER varchar(60),
    BDDDDTER varchar(3),
    BDFONETER DM_BDTELEFONE,
    BDFAXTER DM_BDTELEFONE,
    BDEMAILTER DM_BDEMAIL,
    BDIETER varchar(20),
    BDDATACADTER date,
    BDIMTER varchar(16),
    BDPRURALTER varchar(5),
    BDENQSIMPLESFEDTER integer,
    BDINSCSUFRAMATER varchar(10),
    BDCODGPS integer,
    BDCODCID integer,
    BDCODPAIS integer,
    BDDESCPAIS varchar(60),
    BDDDDFAXTER varchar(3),
    BDCODUF integer,
    BDSIGLAUF varchar(2),
    BDNOMCID varchar(40),
    BDORGAOPUBLICO varchar(5),
    BDCODIBGE integer,
    BDCODAQUIRUR integer,
    BDPRODPF varchar(5),
    BDCPFPROD varchar(18),
    BDPISTER varchar(18))
as
begin
  if (PRCODTER is not null) then
  begin
    select first 1 TER.BDCODTER, TER.BDCGCTER, TER.BDREFEMP, TER.BDAPELIDOTER, TER.BDNOMETER, TER.BDLOGRTER,
                   TER.BDENDTER, TER.BDNUMTER, TER.BDCOMPTER, TER.BDCEPTER, TER.BDBAITER, TER.BDDDDTER, TER.BDFONETER,
                   TER.BDFAXTER, TER.BDEMAILTER, TER.BDIETER, TER.BDDATACADTER, TER.BDIMTER, TER.BDPRURALTER,
                   TER.BDENQSIMPLESFEDTER, TER.BDINSCSUFRAMATER, TER.BDCODGPS, TER.BDCODCID, TER.BDCODPAIS,
                   TER.BDDDDFAXTER, TER.BDORGAOPUBLICO, TER.BDCODAQUIRUR, CID.BDCODUF, CID.BDNOMCID, CID.BDCODIBGE,
                   UF.BDSIGLAUF, TER.BDPRODPF, TER.BDCPFPROD, DOC.BDPISTER
    from TTERCEIRO_REF TER
    left outer join VRH_BASE_TTERC_DOCREF DOC on (DOC.BDCODTER = TER.BDCODTER and DOC.BDREFTERC = TER.BDREFEMP)
    join TCIDADE CID on (CID.BDCODCID = TER.BDCODCID)
    join TUF UF on (CID.BDCODUF = UF.BDCODUF)
    where
    TER.BDREFEMP = coalesce((select first 1 BDREFEMP from TTERCEIRO_REF TER2 where TER2.BDCODTER = :prcodter and TER2.BDREFEMP <= :prref order by TER2.BDREFEMP desc),
                              (select first 1 BDREFEMP from TTERCEIRO_REF TER2 where TER2.BDCODTER = :prcodter order by TER2.BDCODTER, TER2.BDREFEMP))
   and
   TER.BDCODTER = :prcodter

    into :BDCODTER, :BDCGCTER, :BDREFEMP, :BDAPELIDOTER, :BDNOMETER, :BDLOGRTER, :BDENDTER, :BDNUMTER, :BDCOMPTER,
         :BDCEPTER, :BDBAITER, :BDDDDTER, :BDFONETER, :BDFAXTER, :BDEMAILTER, :BDIETER, :BDDATACADTER, :BDIMTER,
         :BDPRURALTER, :BDENQSIMPLESFEDTER, :BDINSCSUFRAMATER, :BDCODGPS, :BDCODCID, :BDCODPAIS, :BDDDDFAXTER,
         :BDORGAOPUBLICO, :BDCODAQUIRUR, :BDCODUF, :BDNOMCID, :BDCODIBGE, :BDSIGLAUF, :BDPRODPF, :BDCPFPROD, :BDPISTER;
    suspend;
  end
end^

create or alter procedure SP_CONSULTA_EFPARGER (
    PRREF integer,
    PRCODEMP integer)
returns (
    BDCODEMP integer,
    BDTIPOAPURACAORETIR integer,
    BDTIPOAPURACAORET integer,
    BDTIPOAPURACAORETIRTOM integer,
    BDTIPOAPURACAO integer)
as
begin
  if ((:PRREF is not null) AND (:PRCODEMP is not null)) then
     begin
      Select first 1 PARGER.BDCODEMP ,PARGER.BDTIPOAPURACAORETIR, PARGER.BDTIPOAPURACAORET, PARGER.BDTIPOAPURACAORETIRTOM, PARGER.BDTIPOAPURACAO from VEF_BASE_TEMPPARGER PARGER
      where PARGER.BDREFEMP <= :PRREF and parger.bdcodemp = :prcodemp
      order by parger.bdrefemp desc
      INTO :BDCODEMP,:BDTIPOAPURACAORETIR, :BDTIPOAPURACAORET, :BDTIPOAPURACAORETIRTOM, :BDTIPOAPURACAO;
      suspend;
     end
end^

CREATE OR ALTER procedure SP_CONSULTA_EMPRESA_REF (
    PRCODEMP integer,
    PRREFEMP integer)
returns (
    BDIEEMP varchar(20),
    BDCODEMP integer,
    BDREFEMP integer,
    BDNOMEMP varchar(255),
    BDCODCID integer,
    BDSITEMP varchar(5),
    BDIAT_PISCOF_SEM_ICMS DM_BOOLEAN,
    BDCARACTRIBUTARIA integer,
    BDSUBSTRIB integer,
    BDCODENQFED integer,
    BDFORMATRIBUTACAO integer,
    BDCNPJEMP varchar(18),
    BDCODCNAE integer,
    BDCODPLAPADRAO integer)
as
begin
  if (PRCODEMP is not null) then
  begin
    --Inicialmente feito pra retornar somente esses campos, mas fique a vontade pra fazer retornar os campos que quiser.
    select first 1 EMP.BDCODEMP, EMP.BDREFEMP, EMP.BDNOMEMP, EMP.BDIEEMP, EMP.BDCODCID, EMP.BDSITEMP,
                   EMP.BDIAT_PISCOF_SEM_ICMS, EMP.BDCARACTRIBUTARIA, X.BDSUBSTRIB, ENQ.BDCODENQFED,
                   ENQ.BDFORMATRIBUTACAO, EMP2.BDCNPJEMP, EMP.bdcodcnae, EMP.BDCODPLAPADRAO
    from TEMPRESAS_REF EMP
    JOIN TEMPRESAS EMP2 ON (EMP.BDCODEMP = EMP2.BDCODEMP)
    left join VEF_BASE_TEMPPAREST X on EMP.BDCODEMP = X.BDCODEMP and
          X.BDREFEMP = coalesce((select first 1 BDREFEMP
                                 from TEMPRESAS_REF EMP2
                                 where EMP2.BDCODEMP = :PRCODEMP and
                                       EMP2.BDREFEMP <= :PRREFEMP
                                 order by EMP2.BDREFEMP desc), (select first 1 BDREFEMP
                                                                from TEMPRESAS_REF EMP2
                                                                where EMP2.BDCODEMP = :PRCODEMP
                                                                order by EMP2.BDCODEMP, EMP2.BDREFEMP))
    left join TENQFED ENQ on EMP.BDCODEMP = ENQ.BDCODEMP and
          ENQ.BDREFEMP = coalesce((select first 1 BDREFEMP
                                   from TEMPRESAS_REF EMP2
                                   where EMP2.BDCODEMP = :PRCODEMP and
                                         EMP2.BDREFEMP <= :PRREFEMP
                                   order by EMP2.BDREFEMP desc), (select first 1 BDREFEMP
                                                                  from TEMPRESAS_REF EMP2
                                                                  where EMP2.BDCODEMP = :PRCODEMP
                                                                  order by EMP2.BDCODEMP, EMP2.BDREFEMP))
    where EMP.BDCODEMP = :PRCODEMP and
          EMP.BDREFEMP = coalesce((select first 1 BDREFEMP
                                   from TEMPRESAS_REF EMP2
                                   where EMP2.BDCODEMP = :PRCODEMP and
                                         EMP2.BDREFEMP <= :PRREFEMP
                                   order by EMP2.BDREFEMP desc), (select first 1 BDREFEMP
                                                                  from TEMPRESAS_REF EMP2
                                                                  where EMP2.BDCODEMP = :PRCODEMP
                                                                  order by EMP2.BDCODEMP, EMP2.BDREFEMP))

    into :BDCODEMP, :BDREFEMP, :BDNOMEMP, :BDIEEMP, :BDCODCID, :BDSITEMP, :BDIAT_PISCOF_SEM_ICMS, :BDCARACTRIBUTARIA,
         :BDSUBSTRIB, :BDCODENQFED, :BDFORMATRIBUTACAO, :BDCNPJEMP, :BDCODCNAE, :BDCODPLAPADRAO;
    suspend;
  end

end^ 

create or alter procedure SP_EMPRESA_UF (
    PRCODEMP integer,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDSIGLAUF char(2))
as
begin
  if (PRCODEMP is not null) then
    begin
      select EMP.BDCODEMP, UF.BDSIGLAUF
      from (select X.BDCODEMP, X.BDCODCID
            from TEMPRESAS_REF X
            where X.BDCODEMP = :PRCODEMP and
                  X.BDREFEMP = (select first 1 Y.BDREFEMP
                                from TEMPRESAS_REF Y
                                where X.BDCODEMP = Y.BDCODEMP and
                                      Y.BDREFEMP <= :PRREF
                                order by Y.BDREFEMP desc)) EMP
      inner join TCIDADE CID on (EMP.BDCODCID = CID.BDCODCID)
      inner join TUF UF on (UF.BDCODUF = CID.BDCODUF)
      into :BDCODEMP, :BDSIGLAUF;

      suspend;
    end
end^

/*Restore proc. body: VRH_SP_REL_RECIBO_INT
  Solicitação 174872 - André Cursino - 08/05/2023 - Implementação inicial da SP*/
create or alter procedure VRH_SP_REL_RECIBO_INT (
    PRCODEMP varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRCODCOL varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PRCODCONTRATO varchar(1000) = '' /* COLLATE WIN1252 - default */ ,
    PRDATAINICIAL varchar(10) = '' /* COLLATE WIN1252 - default */ ,
    PRDATAFINAL varchar(10) = '' /* COLLATE WIN1252 - default */ ,
    PRVERBASDEM smallint = 1,
    PRFILTROCOL varchar(500) = '' /* COLLATE WIN1252 - default */ ,
    PRCODTPCC varchar(1000) = '' /* COLLATE WIN1252 - default */ ,
    PRCODSINTRAB varchar(1000) = '' /* COLLATE WIN1252 - default */ ,
    PRCODCLA varchar(500) = '' /* COLLATE WIN1252 - default */ ,
    PRCODFUNCAO varchar(1000) = '' /* COLLATE WIN1252 - default */ ,
    PREMISSAO smallint = 0,
    PRORDEM smallint = 0,
    PRIMPRIMICC smallint = 0,
    PRFOLHACOMP smallint = 0,
    PRDATAPGTOINICIAL varchar(10) = '' /* COLLATE WIN1252 - default */ ,
    PRDATAPGTOFINAL varchar(10) = '' /* COLLATE WIN1252 - default */ )
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP varchar(18),
    BDLOGREMP DM_LOGRADOURO,
    BDENDEMP DM_BDENDERECO,
    BDNUMEMP DM_NUMEND,
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDCEPEMP varchar(9),
    BDUFEMP varchar(2),
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDRGCOL varchar(13),
    BDCTPSCOL varchar(11),
    BDSERIECTPSCOL varchar(11),
    BDDSERIECTPSCOL varchar(1),
    BDCODCBO integer,
    BDDESCTFUC varchar(40),
    BDSALBASECOL numeric(18,6),
    BDCODCONTTI integer,
    BDDESCCONTRATOTI varchar(2000),
    BDDATACONVTI date,
    BDHORACONVTI time,
    BDDATAINISERVTI date,
    BDDATAFIMSERVTI date,
    BDDATAPAGTI date,
    BDLIQUIDO numeric(18,6),
    BDBINSSFN numeric(18,6),
    BDDATAPGTOFN date,
    BDFGTSFN numeric(18,6),
    BDFGTS13FN numeric(18,6),
    BDCODCOL integer,
    BDCODVER integer,
    BDREFFN integer,
    BDREFVFN numeric(18,6),
    BDREFAUXVFN numeric(18,6),
    BDVALVFN numeric(18,6),
    BDVALIFN numeric(18,6),
    BDDESCVER varchar(50),
    BDTIPOCODVER integer,
    BDORDEMVER integer,
    BDORDEMTIPOCODVER integer,
    BDCLAVER varchar(20),
    BDCONVRESCTI DM_BOOLEAN,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDNOMCTA varchar(40),
    BDCODTOM integer,
    BDNOMTOM varchar(70),
    BDTXTMENS varchar(2000))
as
declare variable WSQLNORMAL varchar(11000);
declare variable WSELECTFN varchar(700);
declare variable WCALCFN varchar(30);
declare variable WVERBAFN varchar(30);
declare variable WJOINAUXCOMPFN varchar(200);
declare variable WWHERENORMAL varchar(5000);
declare variable WSQLTOMADOR varchar(11000);
declare variable WSELECTTOM varchar(700);
declare variable WCALCTOM varchar(30);
declare variable WVERBATOM varchar(30);
declare variable WWHERETOMADOR varchar(5000);
declare variable WSQL varchar(20000);
declare variable WSQLJOINS varchar(5000);
declare variable WWHERE varchar(5000);
declare variable WORDERBY varchar(200);
declare variable WJOINAUXCOMPTOM varchar(200);
declare variable WREFINI integer;
declare variable WREFFIM integer;
declare variable WIMPRIMICC integer;
declare variable WFGTSFNAUX numeric(18,6);
declare variable WFGTS13FNAUX numeric(18,6);
declare variable WPARCELAPI integer;
declare variable WQTDMESESPAR integer;
declare variable WCONTRATOPAR varchar(30);
declare variable WECONSIGNADO boolean;
begin
  wSqlNormal = '';
  wWhereNormal = '';

  wSqlTomador = '';
  wWhereTomador = '';

  wSQL = '';
  wSQLJoins = '';
  wWhere = '';
  worderby = '';

  wCalcFN = 'VRHF_EMP_TFOLHAINT';
  wVerbaFN = 'VRHF_EMP_TVERBAINT';
  wCalcTOM = 'VRHF_EMP_TFOLHATOMINT';
  wVerbaTOM = 'VRHF_EMP_TVERBATOMINT';
  wJoinAuxCompFN = '';
  wJoinAuxCompTOM = '';

  wSelectFN = 'CALC_FN.BDCODEMP, CALC_FN.BDCODCONTTI, CALC_FN.BDLIQUIDO, CALC_FN.BDBINSSFN, CALC_FN.BDDATAPGTOFN, ' ||
              'CALC_FN.BDFGTSFN, CALC_FN.BDFGTS13FN, VERBAS_FN_INT.BDCODCOL, VERBAS_FN_INT.BDCODVER, ' ||
              'VERBAS_FN_INT.BDREFFN, VERBAS_FN_INT.BDREFVFN, VERBAS_FN_INT.BDREFAUXVFN, VERBAS_FN_INT.BDVALVFN, ' ||
              'VERBAS_FN_INT.BDVALIFN ';

  wselectTOM = 'FN_TOMINT.BDCODCONTTI, sum(FN_TOMINT.BDLIQUIDO) as BDLIQUIDO, sum(FN_TOMINT.BDBINSSFT) as BDBINSSFN, ' ||
                'FN_TOMINT.BDDATAPGTOFT as BDDATAPGTOFN, sum(FN_TOMINT.BDFGTSFT) as BDFGTSFN, ' ||
                'sum(FN_TOMINT.BDFGTS13FT) as BDFGTS13FN, VERBAS_FN_TOMINT.BDCODEMP, VERBAS_FN_TOMINT.BDCODCOL, ' ||
                'VERBAS_FN_TOMINT.BDCODVER, VERBAS_FN_TOMINT.BDREFTOMADOR as BDREFFN, ' ||
                'sum(VERBAS_FN_TOMINT.BDREFVFT) as BDREFVFNSUM, max(VERBAS_FN_TOMINT.BDREFVFT) as BDREFVFNMAX, ' ||
                'sum(VERBAS_FN_TOMINT.BDREFAUXVFT) as BDREFAUXVFN, sum(VERBAS_FN_TOMINT.BDVALVFT) as BDVALVFN, ' ||
                'sum(VERBAS_FN_TOMINT.BDVALIFT) as BDVALIFN ';


  wRefIni = 0;
  wRefFim = 0;
  wImprimiCC = 0;

  if (PRFOLHACOMP > 0) then
    begin
      wCalcFN = 'VRHF_EMP_TFOLHACOMPINT';
      wVerbaFN = 'VRHF_EMP_TVERBAFCINT';
      wCalcTOM = 'VRHF_EMP_TFOLTOMCOMPINT';
      wVerbaTOM = 'VRHF_EMP_TVERBAFCTOMINT';
      wJoinAuxCompFN = ' AND CALC_FN.BDREFFC = VERBAS_FN_INT.BDREFFC ';
      wJoinAuxCompTOM = ' AND FN_TOMINT.BDREFFC = VERBAS_FN_TOMINT.BDREFFC ';

      wSelectFN = 'CALC_FN.BDCODEMP, CALC_FN.BDCODCONTTI, CALC_FN.BDLIQUIDO, CALC_FN.BDBINSSFC BDBINSSFN, CALC_FN.BDDATAPAGFC BDDATAPGTOFN, ' ||
                  'CALC_FN.BDFGTSFC BDFGTSFN, CALC_FN.BDFGTS13FC BDFGTS13FN, VERBAS_FN_INT.BDCODCOL, VERBAS_FN_INT.BDCODVER, ' ||
                  'VERBAS_FN_INT.BDREFFN, VERBAS_FN_INT.BDREFVFC BDREFVFN, VERBAS_FN_INT.BDREFAUXVFC BDREFAUXVFN, VERBAS_FN_INT.BDVALVFC BDVALVFN, ' ||
                  'VERBAS_FN_INT.BDVALVIFC BDVALIFN ';

      wselectTOM = 'FN_TOMINT.BDCODCONTTI, sum(FN_TOMINT.BDLIQUIDO) as BDLIQUIDO, sum(FN_TOMINT.BDBINSSFC) as BDBINSSFN, ' ||
                   'FN_TOMINT.BDDATAPAGFC as BDDATAPGTOFN, sum(FN_TOMINT.BDFGTSFC) as BDFGTSFN, ' ||
                   'sum(FN_TOMINT.BDFGTS13FC) as BDFGTS13FN, VERBAS_FN_TOMINT.BDCODEMP, VERBAS_FN_TOMINT.BDCODCOL, ' ||
                   'VERBAS_FN_TOMINT.BDCODVER, VERBAS_FN_TOMINT.BDREFTOMADOR as BDREFFN, ' ||
                   'sum(VERBAS_FN_TOMINT.BDREFVFC) as BDREFVFNSUM, max(VERBAS_FN_TOMINT.BDREFVFC) as BDREFVFNMAX, ' ||
                   'sum(VERBAS_FN_TOMINT.BDREFAUXVFC) as BDREFAUXVFN, sum(VERBAS_FN_TOMINT.BDVALVFC) as BDVALVFN, ' ||
                   'sum(VERBAS_FN_TOMINT.BDVALVIFC) as BDVALIFN';
    end

  if ((Trim(PRCODTPCC) <> '') or (PREMISSAO > 0) or (prImprimiCC > 0)) then
    wImprimiCC = 1;

  if (Trim(PRFILTROCOL) <> '') then
     PRFILTROCOL = REPLACE(PRFILTROCOL, '''''', '''');

  if (Trim(PRCODCONTRATO) <> '') then
    wWhere = PRCODCONTRATO;
  else if ((prdatainicial is not null) and (Trim(prdatainicial) <> '')) then
    begin
      wRefIni = CAST(SUBSTRING(CAST(prdatainicial as VARCHAR(10)) FROM 7)||SUBSTRING(CAST(prdatainicial as VARCHAR(10)) FROM 1 FOR 2) as integer);
      wRefFim = cast(SUBSTRING(CAST(prdatafinal as VARCHAR(10)) FROM 7)||SUBSTRING(CAST(prdatafinal as VARCHAR(10)) FROM 1 FOR 2) as integer);
    end

  IF (TRIM(PRCODEMP) <> '') THEN
    begin
      if (trim(wWhere) <> '') then
        wWhere = wWhere || ' AND ';
      wWhere =  wWhere || PRCODEMP;
    end

  if (trim(PRCODCOL) <> '') then
    begin
      if (trim(wWhere) <> '') then
        wWhere = wWhere || ' AND ';
      wWhere = wWhere || PRCODCOL;
    end

  if (wRefIni > 0) then
    begin
      if (trim(wWhere) <> '') then
        wWhere = wWhere || ' AND ';
      wwhere = wWhere || ' BDREF between ' || cast(wRefIni as varchar(6)) || ' and '|| cast(wRefFim as varchar(6));
    end

  if ((Trim(PRDATAPGTOFINAL) <> '') and (trim(PRDATAPGTOINICIAL) <> '')) then
    begin
      if (trim(wWhere) <> '') then
        wWhere = wWhere || ' AND ';
      wWhere = wWhere || ' BDDATAPAGFC between '''||PRDATAPGTOINICIAL||''' and '''||PRDATAPGTOFINAL||''' ';
    end

  if (Trim(wWhere) <> '') then
    wWhere = ' WHERE ' || wWhere;

  wSQL = 'select CALC.BDCODEMP, EMP_REF.BDNOMEMP, EMP.BDCNPJEMP, EMP_REF.BDLOGREMP, EMP_REF.BDENDEMP, EMP_REF.BDNUMEMP, ' ||
         '      EMP_REF.BDCODCID, EMP_CID.BDNOMCID, EMP_REF.BDCEPEMP, EMP_UF.BDSIGLAUF BDUFEMP, COLCON_CAD.BDNOMCOL, COLCON_DOC.BDCPFCOL, COLCON_DOC_REF.BDPISCOL, ' ||
         '      COLCON_DOC_REF.BDRGCOL, COLCON_DOC_REF.BDCTPSCOL, COLCON_DOC_REF.BDSERIECTPSCOL, COLCON_DOC_REF.BDDSERIECTPSCOL, ' ||
         '      FUNCAO.BDCODCBO, FUNCAO.BDDESCTFUC, COLCON_CALCDIA.BDSALBASECOL, CONTRATO_INT.BDCODCONTTI, ' ||
         '      CONTRATO_INT.BDDESCCONTRATOTI, CONTRATO_INT.BDDATACONVTI, CONTRATO_INT.BDHORACONVTI, ' ||
         '      CONTRATO_INT.BDDATAINISERVTI, CONTRATO_INT.BDDATAFIMSERVTI, CONTRATO_INT.BDDATAPAGTI, CALC.BDLIQUIDO, ' ||
         '      CALC.BDBINSSFN, CALC.BDDATAPGTOFN, CALC.BDFGTSFN, CALC.BDFGTS13FN, CALC.BDCODCOL, CALC.BDCODVER, CALC.BDREFFN, ' ||
         '      CALC.BDREFVFN, CALC.BDREFAUXVFN, CALC.BDVALVFN, CALC.BDVALIFN, VERBAS.BDDESCVER, VERBA_REF.BDTIPOCODVER, ' ||
         '      VERBAS.BDORDEMVER, VERBA_REF.BDORDEMTIPOCODVER, VERBAS.BDCLAVER, CONTRATO_INT.BDCONVRESCTI, ' ||
         iif(wImprimiCC > 0, ' CC.BDCODCENTRO, CC.BDCODTPCC, CC.BDNOMCTA, ',' 0 BDCODCENTRO, 0 BDCODTPCC, '''' BDNOMCTA, ');

  if (premissao = 2) then
    wSQL = wSQL || ' COALESCE(TOM.BDCODTPCC, 0) BDCODTOM, COALESCE(TOM.BDNOMETOM, EMP_REF.BDNOMEMP) BDNOMETOM ';
  else
    wSQL = wSQL || '0 BDCODTOM, '''' BDNOMETOM ';

  wSql = wSQL || 'from (';
  
  wSqlNormal =  'select ' || wSelectFN ||
                iif(wImprimiCC > 0, ', cast(null as integer) as BDCODCENTRO, cast(null as integer) as BDCODTPCC ','') ||
                'from ' || wCalcFN || ' CALC_FN ';

  if ((Trim(PRFILTROCOL) <> '') and (PRFILTROCOL is not null)) then
    wSqlNormal = wSqlNormal || REPLACE(PRFILTROCOL, 'CALC'   , 'CALC_FN');

  wSqlNormal = wSqlNormal ||
                'left join ' || wVerbaFN || ' VERBAS_FN_INT on (CALC_FN.BDCODEMP = VERBAS_FN_INT.BDCODEMP and ' ||
                '      CALC_FN.BDCODCOL = VERBAS_FN_INT.BDCODCOL and ' ||
                '      CALC_FN.BDCODCONTTI = VERBAS_FN_INT.BDCODCONTTI and ' ||
                '      CALC_FN.BDREFFN = VERBAS_FN_INT.BDREFFN ' || wJoinAuxCompFN ||') ';

  if (Trim(wWhere) <> '') then
    begin
      wWhereNormal = REPLACE(      wWhere, 'BDCODEMP'   , 'CALC_FN.BDCODEMP');
      wWhereNormal = REPLACE(wWhereNormal, 'BDCODCOL'   , 'CALC_FN.BDCODCOL');
      wWhereNormal = REPLACE(wWhereNormal, 'BDREF'      , 'CALC_FN.BDREFFN');
      wWhereNormal = REPLACE(wWhereNormal, 'BDCODCONTTI', 'CALC_FN.BDCODCONTTI');
      wWhereNormal = REPLACE(wWhereNormal, 'BDDATAPAGFC', 'CALC_FN.BDDATAPAGFC');
    end

  wSqlNormal = wSqlNormal || wWhereNormal;

  wSqlTomador = 'select CALC_FT.BDCODEMP, CALC_FT.BDCODCONTTI, CALC_FT.BDLIQUIDO, CALC_FT.BDBINSSFN, CALC_FT.BDDATAPGTOFN, ' ||
                '       CALC_FT.BDFGTSFN, CALC_FT.BDFGTS13FN, CALC_FT.BDCODCOL, CALC_FT.BDCODVER, CALC_FT.BDREFFN, ' ||
                '       case ' ||
                '         when VERBAS.BDCLAVER starting with ''9'' then CALC_FT.BDREFVFNMAX ' ||
                '         else CALC_FT.BDREFVFNSUM ' ||
                '       end BDREFVFN, ' ||
                '       CALC_FT.BDREFAUXVFN, CALC_FT.BDVALVFN, CALC_FT.BDVALIFN ' ||
                        iif(wImprimiCC > 0, ', CALC_FT.BDCODCENTRO, CALC_FT.BDCODTPCC ','') ||
                'from (select ' || wSelectTOM ||
                       iif(wImprimiCC > 0, ', PFN.BDCODCENTRO, PFN.BDCODTPCC ','') ||
                '      from ' || wCalcTOM || ' FN_TOMINT ';

  if ((Trim(PRFILTROCOL) <> '') and (PRFILTROCOL is not null)) then
    wSqlTomador = wSqlTomador || REPLACE(PRFILTROCOL, 'CALC'   , 'FN_TOMINT');

  wSqlTomador = wSqlTomador ||' join VRHF_EMP_TPREPFN PFN on (PFN.BDCODEMP = FN_TOMINT.BDCODEMP and PFN.BDCODCOL = FN_TOMINT.BDCODCOL and PFN.BDORDEM = FN_TOMINT.BDORDEM) ';
  wSqlTomador = wSqlTomador ||
                '      left join ' || wVerbaTOM || ' VERBAS_FN_TOMINT on (FN_TOMINT.BDCODEMP = VERBAS_FN_TOMINT.BDCODEMP and ' ||
                '            FN_TOMINT.BDCODCOL = VERBAS_FN_TOMINT.BDCODCOL and ' ||
                '            FN_TOMINT.BDCODCONTTI = VERBAS_FN_TOMINT.BDCODCONTTI and ' ||
                '            FN_TOMINT.BDREFTOMADOR = VERBAS_FN_TOMINT.BDREFTOMADOR and ' ||
                '            FN_TOMINT.BDORDEM = VERBAS_FN_TOMINT.BDORDEM ' || wJoinAuxCompTOM || ') ';

  if (Trim(wWhere) <> '') then
    begin
      wWhereTomador = REPLACE(       wWhere, 'BDCODEMP'   , 'FN_TOMINT.BDCODEMP');
      wWhereTomador = REPLACE(wWhereTomador, 'BDCODCOL'   , 'FN_TOMINT.BDCODCOL');
      wWhereTomador = REPLACE(wWhereTomador, 'BDREF'      , 'FN_TOMINT.BDREFTOMADOR');
      wWhereTomador = REPLACE(wWhereTomador, 'BDCODCONTTI', 'FN_TOMINT.BDCODCONTTI');
      wWhereTomador = REPLACE(wWhereTomador, 'BDDATAPAGFC', 'FN_TOMINT.BDDATAPAGFC');
    end

  wSqlTomador = wSqlTomador || wWhereTomador ||
                ' group by FN_TOMINT.BDCODCONTTI, ' ||
                           iif(PRFOLHACOMP > 0, 'FN_TOMINT.BDDATAPAGFC','FN_TOMINT.BDDATAPGTOFT') ||
                           ', VERBAS_FN_TOMINT.BDCODEMP, VERBAS_FN_TOMINT.BDCODCOL, VERBAS_FN_TOMINT.BDCODVER, VERBAS_FN_TOMINT.BDREFTOMADOR' ||
                           iif(wImprimiCC > 0, ', PFN.BDCODCENTRO, PFN.BDCODTPCC ','') || ' ) CALC_FT ' ||
                'left join VRH_BASE_TVERBAS VERBAS on (CALC_FT.BDCODVER = VERBAS.BDCODVER)';
  
  wSQLJoins = ') CALC ' ||
              'join VW_TEMPRESAS_REF EMP_REF on (CALC.BDCODEMP = EMP_REF.BDCODEMP) ' ||
              'join TEMPRESAS EMP on (CALC.BDCODEMP = EMP.BDCODEMP) ' ||
              'join VRH_EMP_TINTERMITENTE CONTRATO_INT on (CALC.BDCODEMP = CONTRATO_INT.BDCODEMP and ' ||
              '      CALC.BDCODCOL = CONTRATO_INT.BDCODCOL and ' ||
              '      CALC.BDCODCONTTI = CONTRATO_INT.BDCODCONTTI) ' ||
              'left join VRH_BASE_TVERBAS VERBAS on (CALC.BDCODVER = VERBAS.BDCODVER) ' ||
              'left join VW_VERBAS_REF_ATUAL VERBA_REF on (VERBAS.BDCODVER = VERBA_REF.BDCODVER) ' ||
              'left join TCIDADE EMP_CID on (EMP_REF.BDCODCID = EMP_CID.BDCODCID) ' ||
              'left join TUF EMP_UF on (EMP_CID.BDCODUF = EMP_UF.BDCODUF) ' ||
              'left join VW_VRH_EMP_TCOLCON_CAD COLCON_CAD on (CALC.BDCODEMP = COLCON_CAD.BDCODEMP and ' ||
              '      CALC.BDCODCOL = COLCON_CAD.BDCODCOL) ' ||
              'left join VRH_EMP_TCOLCON_DOC COLCON_DOC on (CALC.BDCODEMP = COLCON_DOC.BDCODEMP and ' ||
              '      CALC.BDCODCOL = COLCON_DOC.BDCODCOL) ' ||
              'left join VW_VRH_EMP_TCOLCON_DOCREF COLCON_DOC_REF on (CALC.BDCODEMP = COLCON_DOC_REF.BDCODEMP and ' ||
              '      CALC.BDCODCOL = COLCON_DOC_REF.BDCODCOL) ' ||
              'left join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = CALC.BDCODEMP and ' ||
              '      RESC.BDCODCOL = CALC.BDCODCOL) ' ||
              'left join VW_VRH_EMP_TCOLCON_CALCDIA COLCON_CALCDIA on (CALC.BDCODEMP = COLCON_CALCDIA.BDCODEMP and ' ||
              '      CALC.BDCODCOL = COLCON_CALCDIA.BDCODCOL) ' ||
              'left join VW_VRH_EMP_TCOL_VINCDIA COL_VINCDIA on (CALC.BDCODEMP = COL_VINCDIA.BDCODEMP and ' ||
              '      CALC.BDCODCOL = COL_VINCDIA.BDCODCOL) ' ||
              'left join VRH_FUNCOES_TFUC FUNCAO on (COL_VINCDIA.BDCODPLAFUC = FUNCAO.BDCODPLAFUC and ' ||
              '      COL_VINCDIA.BDCODTFUC = FUNCAO.BDCODTFUC) ';

  wwhere = '';

  if ((prdatainicial is not null) and (Trim(prdatainicial) <> '')) then
    begin
      wwhere = ' ((CONTRATO_INT.BDDATAINISERVTI between ''' || prDataInicial || ''' AND ' || '''' || prDataFinal || ''') or ' ||
               '  (CONTRATO_INT.BDDATAFIMSERVTI between ''' || prDataInicial || ''' AND ' || '''' || prDataFinal || ''')) ';
    end

  IF (coalesce(prverbasdem, 0) = 0) then
    BEGIN
      IF (wWhere <> '') THEN
         wWhere = wWhere || ' AND ';
      wWhere = wWhere || 'COALESCE(VERBA_REF.BDTIPOCODVER, 0) in (0,1) ';
    END

  IF (Trim(prCodFuncao) <> '') then
    BEGIN
      IF (wWhere <> '') THEN
         wWhere = wWhere || ' AND ';
      wWhere = wWhere || prCodFuncao;
    END

  if (Trim(prCodSinTrab) <> '') then
    begin
      wSQLJoins = wSQLJoins || ' LEFT JOIN VRH_EMP_TCOL_VINC COL_VINC ON (COLCON_CAD.BDCODEMP = COL_VINC.BDCODEMP ' ||
                               '                                         AND COLCON_CAD.BDCODCOL = COL_VINC.BDCODCOL ' ||
                               '                                         AND COLCON_CAD.BDREFCOL = COL_VINC.BDREFCOL) ';
      IF (wWhere <> '') THEN
         wWhere = wWhere || ' AND ';
      wWhere = wWhere || prCodSinTrab;
    end

  if (Trim(prCodCla) <> '') then
    begin
      wSQLJoins = wSQLJoins || 'LEFT JOIN VRH_EMP_TCOLCON_VINC COLCON_VINC ON (COLCON_CAD.BDCODEMP = COLCON_VINC.BDCODEMP ' ||
                               '                                              AND COLCON_CAD.BDCODCOL = COLCON_VINC.BDCODCOL ' ||
                               '                                              AND COLCON_CAD.BDREFCOL = COLCON_VINC.BDREFCOL) ';
      IF (wWhere <> '') THEN
         wWhere = wWhere || ' AND ';
      wWhere = wWhere || prCodCla;
    end

   if (wImprimiCC > 0) then
     begin
        wSQLJoins = wSQLJoins || 'LEFT JOIN CENTROS_TPCC CC ON (CALC.BDCODCENTRO = CC.BDCODCENTRO ' ||
                                 '                             AND CALC.BDCODTPCC = CC.BDCODTPCC) ';
        if (prEmissao = 2) then
          wSQLJoins = wSQLJoins || 'LEFT JOIN VRHF_SP_TOMADOR(CC.BDCODTPCC, CC.BDCODCENTRO) TOM ON (TOM.BDCODCENTRO = CC.BDCODCENTRO ' ||
                                   '                                                               AND TOM.BDCODCENCUS = CC.BDCODTPCC) ';

        if (Trim(prCodTPCC) <> '') then
          begin
            IF (wWhere <> '') THEN
              wWhere = wWhere || ' AND ';
            wWhere = wWhere || prCodTPCC;
          end
     end

  if (Trim(wwhere) <> '') then
    wwhere = ' WHERE ' || wwhere;

  wOrderBy = ' ORDER BY CALC.BDCODEMP,';
  if (prEmissao > 0) then
    begin
      if (prEmissao = 2) then
        wOrderBy = wOrderBy || 'TOM.BDCODTPCC,';
      wOrderBy = wOrderBy || 'CC.BDCODTPCC,';
    end
  if (prOrdem = 1) then
    wOrderBy = wOrderBy || 'COLCON_CAD.BDNOMCOL,';
  wOrderBy = wOrderBy || 'CALC.BDCODCOL, CONTRATO_INT.BDCODCONTTI ';

  wSql = wSql || wSqlNormal || ' union all ' || wSqlTomador || wSQLJoins || wWhere || wOrderBy;
  FOR EXECUTE STATEMENT wSQL
    INTO
      :BDCODEMP,
      :BDNOMEMP,
      :BDCNPJEMP,
      :BDLOGREMP,
      :BDENDEMP,
      :BDNUMEMP,
      :BDCODCID,
      :BDNOMCID,
      :BDCEPEMP,
      :BDUFEMP,
      :BDNOMCOL,
      :BDCPFCOL,
      :BDPISCOL,
      :BDRGCOL,
      :BDCTPSCOL,
      :BDSERIECTPSCOL,
      :BDDSERIECTPSCOL,
      :BDCODCBO,
      :BDDESCTFUC,
      :BDSALBASECOL,
      :BDCODCONTTI,
      :BDDESCCONTRATOTI,
      :BDDATACONVTI,
      :BDHORACONVTI,
      :BDDATAINISERVTI,
      :BDDATAFIMSERVTI,
      :BDDATAPAGTI,
      :BDLIQUIDO,
      :BDBINSSFN,
      :BDDATAPGTOFN,
      :BDFGTSFN,
      :BDFGTS13FN,
      :BDCODCOL,
      :BDCODVER,
      :BDREFFN,
      :BDREFVFN,
      :BDREFAUXVFN,
      :BDVALVFN,
      :BDVALIFN,
      :BDDESCVER,
      :BDTIPOCODVER,
      :BDORDEMVER,
      :BDORDEMTIPOCODVER,
      :BDCLAVER,
      :BDCONVRESCTI,
      :BDCODCENTRO,
      :BDCODTPCC,
      :BDNOMCTA,
      :BDCODTOM,
      :BDNOMTOM
    DO
      begin
        if (premissao = 0) then
          begin
            select max(BDLIQUIDO) BDLIQUIDO, max(BDFGTSFT) BDFGTSFT, max(BDFGTS13FT) BDFGTS13FT
            from (select sum(FN_TOMINT.BDLIQUIDO) as BDLIQUIDO, sum(FN_TOMINT.BDFGTSFT) as BDFGTSFT,
                         sum(FN_TOMINT.BDFGTS13FT) as BDFGTS13FT
                  from VRHF_EMP_TFOLHATOMINT FN_TOMINT
                  left join VRHF_EMP_TVERBATOMINT VERBAS_FN_TOMINT on (FN_TOMINT.BDCODEMP = VERBAS_FN_TOMINT.BDCODEMP and
                                                                       FN_TOMINT.BDCODCOL = VERBAS_FN_TOMINT.BDCODCOL and
                                                                       FN_TOMINT.BDCODCONTTI = VERBAS_FN_TOMINT.BDCODCONTTI and
                                                                       FN_TOMINT.BDREFTOMADOR = VERBAS_FN_TOMINT.BDREFTOMADOR and
                                                                       FN_TOMINT.BDORDEM = VERBAS_FN_TOMINT.BDORDEM)
                  where FN_TOMINT.BDCODCONTTI = :BDCODCONTTI and
                        FN_TOMINT.BDCODEMP = :BDCODEMP and
                        FN_TOMINT.BDCODCOL = :BDCODCOL
                  group by FN_TOMINT.BDCODCONTTI, FN_TOMINT.BDDATAPGTOFT, VERBAS_FN_TOMINT.BDCODEMP,
                           VERBAS_FN_TOMINT.BDCODCOL, VERBAS_FN_TOMINT.BDCODVER, VERBAS_FN_TOMINT.BDREFTOMADOR
                  ) into :BDLIQUIDO, :WFGTSFNAUX, :WFGTS13FNAUX;

            if (coalesce(:BDLIQUIDO,0)=0) then
            begin
              select max(BDLIQUIDO) BDLIQUIDO, max(BDFGTSFT) BDFGTSFT, max(BDFGTS13FT) BDFGTS13FT
              from (select sum(FN_INT.BDLIQUIDO) as BDLIQUIDO, sum(FN_INT.bdfgtsfN) as BDFGTSFT,
                           sum(FN_INT.BDFGTS13FN) as BDFGTS13FT
                    from VRHF_EMP_TFOLHAINT FN_INT
                    left join VRHF_EMP_TVERBAINT VERBAS_FN_INT on (FN_INT.BDCODEMP = VERBAS_FN_INT.BDCODEMP and
                                                                   FN_INT.BDCODCOL = VERBAS_FN_INT.BDCODCOL and
                                                                   FN_INT.BDCODCONTTI = VERBAS_FN_INT.BDCODCONTTI and
                                                                     FN_INT.BDREFFN = VERBAS_FN_INT.BDREFFN )
                      where FN_INT.BDCODCONTTI = :BDCODCONTTI and
                            FN_INT.BDCODEMP = :BDCODEMP and
                            FN_INT.BDCODCOL = :BDCODCOL
                      group by FN_INT.BDCODCONTTI, FN_INT.BDDATAPGTOFN, VERBAS_FN_INT.BDCODEMP,
                               VERBAS_FN_INT.BDCODCOL, VERBAS_FN_INT.BDCODVER, VERBAS_FN_INT.BDREFFN
                      ) into :BDLIQUIDO, :WFGTSFNAUX, :WFGTS13FNAUX;        
            end

            if (prfolhacomp = 0) then
               begin
                 :BDFGTSFN   = :WFGTSFNAUX;
                 :BDFGTS13FN = :WFGTS13FNAUX;
               end
          end

        select first 1 BDTXTMEN from SPRH_MENSAGENS_RECIBO(:BDREFFN, 'COL.BDCODEMP = '||:BDCODEMP, 'COL.BDCODCOL = '||:BDCODCOL, 0) into :BDTXTMENS;

        -- Parcelamentos
        if (substring(BDCLAVER from 1 for 5) = '0.070') then
           begin
             for select first 1 PARCI.BDPARCELAPI, COALESCE(E.BDTOTALPAR, PARC.BDQTDMESESPAR) AS BDQTDMESESPAR, PARC.BDCONTRATOPAR, COALESCE(PARC.BDECONSIGNADO, FALSE) AS BDECONSIGNADO
                 from VRH_EMP_TPARCELAMENTOS_ITENS PARCI
                 join VRH_EMP_TPARCELAMENTOS PARC on (PARC.BDCODEMP = PARCI.BDCODEMP and PARC.BDCODCOL = PARCI.BDCODCOL and PARC.BDCODPARC = PARCI.BDCODPARC)
                 left outer join VRH_IMP_ECONSIGNADO E on (PARC.BDCODEMP = E.BDCODEMP AND PARC.BDCODCOL = E.BDCODCOL AND PARC.BDCONTRATOPAR = E.BDCONTRATOPAR)
                 where PARCI.BDCODEMP = :BDCODEMP and PARCI.BDCODCOL = :BDCODCOL and PARC.BDCODVER = :BDCODVER and PARCI.BDREFPI = :BDREFFN
             into :wparcelapi, :wqtdmesespar, :wcontratopar, :weconsignado
             do
               begin
                 if (coalesce(weconsignado, FALSE)) then
                    BDDESCVER = substring((BDDESCVER||'-'||wcontratopar||'-'||wparcelapi||'/'||wqtdmesespar) from 1 for 50);
                 else
                    BDDESCVER = substring((BDDESCVER||' '||wparcelapi||'/'||wqtdmesespar) from 1 for 50);
               end
           end

        SUSPEND;
      end
end^


create or alter procedure SP_CERTIFICADO (
    PRENTRADA integer)
as
begin
  rdb$set_context('USER_SESSION', 'W_VAR',PRENTRADA);
end^

CREATE OR ALTER VIEW VW_VRH_SISQUAL_COLABORADOR(
    CODEMPREGADO,
    NOME,
    NOMEABREVIADO,
    DATAINICIOACTIVIDADE,
    DATAFIMACTIVIDADE,
    CODEMPRESASALARIO,
    CODTIPOSALARIO,
    CODFUNCAO,
    CODDEPARTAMENTO,
    CODCONTRATO,
    DATANASCIMENTO,
    SEXO,
    CPF,
    CODPIS,
    CEDULAPROFISSIONAL,
    TELEFONE,
    EMAIL)
AS
select COLCON.BDCODCOL CODEMPREGADO,
       cast(COLCON_CAD.BDNOMCOL as varchar(80)) NOME,
       cast(COLCON_CAD.BDNOMCOL as varchar(80)) NOMEABREVIADO,
       COLCON.BDDATAADMCOL DATAINICIOACTIVIDADE,
       RESC.BDDATARESCISAO DATAFIMACTIVIDADE,
       cast(COLCON.BDCODEMP as varchar(10)) CODEMPRESASALARIO,
       cast(COL_CALC.BDTIPOCOL + 1 as varchar(10)) CODTIPOSALARIO,
       cast(COLCON_VINCDIA.BDCODTFUC as varchar(10)) CODFUNCAO,
       cast(COL_VINC.BDCODSINTRAB as varchar(10)) CODDEPARTAMENTO,
       cast(COLCON_VINCDIA.BDCODQH as varchar(10)) CODCONTRATO,
       COLCON.BDDATANASCCOL DATANASCIMENTO,
       cast(COLCON_CAD.BDSEXOCOL as varchar(1)) SEXO,
       cast(COLCON.BDCPFCOL as varchar(20)) CPF,
       cast(COLCON_DOCREF.BDPISCOL as varchar(50)) CODPIS,
       cast(COLCON_DOCREF.BDNUMOCCOL as varchar(20)) CEDULAPROFISSIONAL,
       cast(coalesce(COLCON_CAD.BDDDDCOL, '') || ' ' || coalesce(COLCON_CAD.BDFONECOL, '') || ' / ' || coalesce(COLCON_CAD.BDDDDCELCOL, '') || ' ' || coalesce(COLCON_CAD.BDCELCOL, '') as varchar(30)) TELEFONE,
       cast(COLCON_CAD.BDEMAILCOL as varchar(255)) EMAIL
from VRH_EMP_TCOLCON COLCON
join VW_VRH_EMP_TCOLCON_REF COLCON_REF on (COLCON.BDCODEMP = COLCON_REF.BDCODEMP and
      COLCON.BDCODCOL = COLCON_REF.BDCODCOL)
join VRH_EMP_TCOLCON_CAD COLCON_CAD on (COLCON_REF.BDCODEMP = COLCON_CAD.BDCODEMP and
      COLCON_REF.BDCODCOL = COLCON_CAD.BDCODCOL and
      COLCON_REF.BDREFCOL = COLCON_CAD.BDREFCOL)
left join VRH_EMP_TRESCISAO RESC on (COLCON.BDCODEMP = RESC.BDCODEMP and
      COLCON.BDCODCOL = RESC.BDCODCOL)
left join VRHF_EMP_TCOL_CALC COL_CALC on (COLCON_REF.BDCODEMP = COL_CALC.BDCODEMP and
      COLCON_REF.BDCODCOL = COL_CALC.BDCODCOL and
      COLCON_REF.BDREFCOL = COL_CALC.BDREFCOL)
join VW_TCOLCON_VINCDIA COLCON_VINCDIA on (COLCON.BDCODEMP = COLCON_VINCDIA.BDCODEMP and
      COLCON.BDCODCOL = COLCON_VINCDIA.BDCODCOL)
left join VRH_EMP_TCOL_VINC COL_VINC on (COLCON_REF.BDCODEMP = COL_VINC.BDCODEMP and
      COLCON_REF.BDCODCOL = COL_VINC.BDCODCOL and
      COLCON_REF.BDREFCOL = COL_VINC.BDREFCOL)
join VRH_EMP_TCOLCON_DOCREF COLCON_DOCREF on (COLCON_REF.BDCODEMP = COLCON_DOCREF.BDCODEMP and
      COLCON_REF.BDCODCOL = COLCON_DOCREF.BDCODCOL and
      COLCON_REF.BDREFCOL = COLCON_DOCREF.BDREFCOL)^

CREATE OR ALTER VIEW VW_VRH_SISQUAL_FUNCAO(
    CODEMPRESASALARIO,
    CODFUNCAO,
    DESCRICAO)
AS
SELECT EMPVINC.BDCODEMP,
       FUNC.BDCODTFUC,
       FUNC.BDDESCTFUC
  FROM VW_VRH_BASE_TEMPVINC EMPVINC
  JOIN VRH_FUNCOES_TFUC FUNC ON FUNC.BDCODPLAFUC = EMPVINC.BDCODPLAFUC^   


CREATE OR ALTER VIEW VW_VRH_SISQUAL_CENTRO_CUSTO(
    CODCENTROCUSTO,
    DESCRICAO,
    CODREDUZIDO,
    CODEMPRESACENTROCUSTO)
AS
select cast(TPCC.BDCODTPCC as varchar(10)) CODCENTROCUSTO,
       cast(TPCC.BDNOMCTA as varchar(200)) DESCRICAO,
       cast(TPCC.BDCTALON as varchar(10)) CODREDUZIDO,
       cast(EMP.BDCODEMP as varchar(10)) CODEMPRESACENTROCUSTO
from CENTROS_TPCC TPCC
join VW_TEMPRESAS_REF EMP on EMP.BDCODCENTROS = TPCC.BDCODCENTRO^


CREATE OR ALTER VIEW VW_VRH_SISQUAL_EMPRESA_SALARIO(
    CODEMPRESASALARIO,
    DESCRICAO,
    CNPJ,
    CEI,
    RAZAOSOCIAL,
    ENDERECO)
AS
select cast(EMP.BDCODEMP as varchar(10)) CODEMPRESASALARIO,
       cast(EMP_REF.BDNOMREDUZEMP as varchar(50)) DESCRICAO,
       cast(EMP.BDCNPJEMP as varchar(150)) CNPJ,
       cast(EMP.BDCEIEMP as varchar(150)) CEI,
       cast(EMP_REF.BDNOMEMP as varchar(150)) RAZAOSOCIAL,
       cast(coalesce(EMP_REF.BDLOGREMP, '') || ' ' || coalesce(EMP_REF.BDENDEMP, '') || ' ' || coalesce(EMP_REF.BDNUMEMP, '') as varchar(150)) ENDERECO
from TEMPRESAS EMP
join VW_TEMPRESAS_REF EMP_REF on (EMP.BDCODEMP = EMP_REF.BDCODEMP)^


CREATE OR ALTER VIEW VW_VRH_SISQUAL_FERI_NACIONAL(
    CODFERIADO,
    DESCRICAO,
    TIPO)
AS
select feri.bddataferi CODFERIADO,
       cast(FERI.BDDESCFERI as varchar(80)) DESCRICAO,
       cast(0 as varchar(1)) TIPO
from TFERIADOSNOVO FERI
where feri.bddataferi is not null^


CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_CONTRATO(
    CODEMPREGADO,
    CODEMPRESASALARIO,
    DATAINICIO,
    CODCONTRATO)
AS
select COLCON_VINCDIA.BDCODCOL CODEMPREGADO,
       cast(COLCON_VINCDIA.BDCODEMP as varchar(10)) CODEMPRESASALARIO,
       min(COLCON_VINCDIA.BDDATACOL) DATAINICIO,
       cast(COLCON_VINCDIA.BDCODQH as varchar(10)) CODCONTRATO
from VRH_EMP_TCOL_VINCDIA COLCON_VINCDIA
where COLCON_VINCDIA.BDCODQH is not null
group by COLCON_VINCDIA.BDCODCOL, COLCON_VINCDIA.BDCODQH, COLCON_VINCDIA.BDCODEMP^


CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_FUNCAO(
    CODEMPREGADO,
    CODEMPRESASALARIO,
    DATAINICIO,
    CODFUNCAO)
AS
select COLCON_VINCDIA.BDCODCOL CODEMPREGADO,
       cast(COLCON_VINCDIA.BDCODEMP as varchar(10)) CODEMPRESASALARIO,
       min(COLCON_VINCDIA.BDDATACOL) DATAINICIO,
       cast(COLCON_VINCDIA.BDCODTFUC as varchar(10)) CODFUNCAO
from VRH_EMP_TCOL_VINCDIA COLCON_VINCDIA
where COLCON_VINCDIA.BDCODTFUC is not null
group by COLCON_VINCDIA.BDCODEMP, COLCON_VINCDIA.BDCODCOL, COLCON_VINCDIA.BDCODTFUC^


CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_CENTROCUSTO(
    CODEMPREGADO,
    CODEMPRESASALARIO,
    DATAINICIO,
    CODCENTROCUSTO)
AS
select CC.BDCODCOL CODEMPREGADO,
       cast(CC.BDCODEMP as varchar(10)) CODEMPRESASALARIO,
       CC.BDDATAENTRADA DATAINICIO,
       cast(CC.BDCODTPCC as varchar(50)) CODCENTROCUSTO
from VRHF_EMP_TPREPFN CC
where CC.BDCODTPCC is not null
order by BDCODEMP, BDCODCOL, BDORDEM^


CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_TPSAL_VINC(
    CODEMPREGADO,
    CODEMPRESASALARIO,
    DATAINICIO,
    CODTIPOSALARIO)
AS
select COL_CALC.BDCODCOL CODEMPREGADO,
       cast(COL_CALC.BDCODEMP as varchar(10)) CODEMPRESASALARIO,
       cast(substring(min(COL_CALC.BDREFCOL) from 1 for 4) || '/' || substring(min(COL_CALC.BDREFCOL) from 5 for 6) || '/01' as date) DATAINICIO,
       cast(COL_CALC.BDTIPOCOL + 1 as varchar(50)) CODTIPOSALARIO
from VRHF_EMP_TCOL_CALC COL_CALC
where COL_CALC.BDTIPOCOL is not null
  and COL_CALC.BDREFCOL is not null
group by COL_CALC.BDCODEMP, COL_CALC.BDCODCOL, COL_CALC.BDTIPOCOL^


CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_EMP_SAL(
    CODEMPREGADO,
    DATAINICIO,
    CODEMPRESASALARIO)
AS
select COLCON.BDCODCOL,
       coalesce(TRANSF.BDDATATRF, COLCON.BDDATAADMCOL) DATAINICIO,
       cast(COLCON.BDCODEMP as varchar(50)) CODEMPRESASALARIO
from VRH_EMP_TCOLCON COLCON
left join VRH_EMP_TTRANSCOL TRANSF on (COLCON.BDCODEMP = TRANSF.BDCODEMPDEST and
      COLCON.BDCODCOL = TRANSF.BDCODCOLDEST)^


CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_SINDICATO(
    CODEMPREGADO,
    CODEMPRESASALARIO,
    DATAINICIO,
    CODDEPARTAMENTO)
AS
select VINC.BDCODCOL,
       cast(VINC.BDCODEMP as varchar(10)) CODEMPRESASALARIO,
       cast(substring(min(VINC.BDREFCOL) from 1 for 4) || '/' || substring(min(VINC.BDREFCOL) from 5 for 6) || '/01' as date) DATAINICIO,
       cast(VINC.BDCODSINTRAB as varchar(10)) CODDEPARTAMENTO
from VRH_EMP_TCOL_VINC VINC
where vinc.bdcodsintrab is not null
group by VINC.BDCODEMP, VINC.BDCODCOL, VINC.BDCODSINTRAB^



CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_HIST_FER(
    CODEMPREGADO,
    CODEMPRESASALARIO,
    DATAINICIO,
    DATAFIM)
AS
select FER.BDCODCOL,
       cast(FER.BDCODEMP as varchar(10)) CODEMPRESASALARIO,
       FER.BDINIPERGOZOFE DATAINICIO,
       FER.BDFIMPERGOZOFE DATAFIM
from VRH_EMP_TFERIAS FER^


CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_HIST_AFAST(
    CODEMPREGADO,
    CODEMPRESASALARIO,
    DATAINICIO,
    DATAFIM,
    CODAFASTAMENTO)
AS
select SIT.BDCODCOL,
       cast(SIT.BDCODEMP as varchar(10)) CODEMPRESASALARIO,
       coalesce(SIT.BDDATAINISEFIP, SIT.BDDATAINIATESTADOAUX, SIT.BDDATAINIAFASTAUX) DATAINICIO,
       coalesce(SIT.BDDATAFIMATESTADOAUX, SIT.BDDATAFIMAFASTAUX) DATAFIM,
       cast(SIT.BDCODSIT as varchar(10)) CODAFASTAMENTO
from VRH_EMP_TSITCOL SIT^


CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_SALDO_FER(
    CODEMPREGADO,
    CODEMPRESASALARIO,
    DATAINICIO,
    DATAFIM,
    SALDO)
AS
select SALDOFER.BDCODCOL,
       cast(SALDOFER.BDCODEMP as varchar(10)) CODEMPRESASALARIO,
       SALDOFER.BDINIPERCONCESSIVO DATAINICIO,
       SALDOFER.BDFIMPERCONCESSIVO DATAFIM,
       cast(SALDOFER.BDSALDO as numeric(4,2)) SALDO
from (select REF.BDCODEMP, REF.BDCODCOL, max(REF.BDREFSALDO) BDREFSALDO, REF.BDINIPERAQUIS
      from VRH_EMP_TSALDOFERIAS REF
      where current_date between REF.BDINIPERAQUIS and REF.BDFIMPERAQUIS
      group by 1, 2, 4) REFE, VRH_EMP_TSALDOFERIAS SALDOFER
where REFE.BDCODEMP = SALDOFER.BDCODEMP and
      REFE.BDCODCOL = SALDOFER.BDCODCOL and
      REFE.BDREFSALDO = SALDOFER.BDREFSALDO and
      REFE.BDINIPERAQUIS = SALDOFER.BDINIPERAQUIS
order by SALDOFER.BDCODEMP, SALDOFER.BDCODCOL, SALDOFER.BDINIPERAQUIS^



CREATE OR ALTER VIEW VW_VRH_SISQUAL_COL_FER_ATUAIS(
    CODEMPREGADO,
    CODEMPRESASALARIO,
    DATAVENCIMENTO,
    QUER_ABONO_DE_FERIAS,
    DIAS_DE_DIREITO_A_FERIAS,
    DIAS_DE_ABONO)
AS
select SALDOFER.BDCODCOL,
       cast(SALDOFER.BDCODEMP as varchar(10)) CODEMPRESASALARIO,
       SALDOFER.BDFIMPERCONCESSIVO DATAVENCIMENTO,
       cast(case
         when FERIAS.BDQTDABONOFE > 0 then 'SIM'
         else 'NAO'
       end as varchar(10)) QUER_ABONO_DE_FERIAS,
       cast(SALDOFER.BDSALDO + coalesce(FERIAS.BDQTDGOZOFE, 0) as integer) DIAS_DE_DIREITO_A_FERIAS,
       cast(coalesce(FERIAS.BDQTDABONOFE, 0) as integer) DIAS_DE_ABONO
from (select SALDOREF.BDCODEMP, SALDOREF.BDCODCOL, max(SALDOREF.BDREFSALDO) BDREFSALDO, SALDOREF.BDINIPERAQUIS,
             SALDOREF.BDFIMPERAQUIS, SALDOREF.BDINIPERCONCESSIVO, SALDOREF.BDFIMPERCONCESSIVO, SALDOREF.BDSALDO
      from VRH_EMP_TSALDOFERIAS SALDOREF
      where current_date between SALDOREF.BDINIPERCONCESSIVO and SALDOREF.BDFIMPERCONCESSIVO
      group by 1, 2, 4, 5, 6, 7, 8) SALDOFER

left join(select FERIASSUM.BDCODEMP, FERIASSUM.BDCODCOL, sum(FERIASSUM.BDQTDGOZOFE) BDQTDGOZOFE,
                 sum(FERIASSUM.BDQTDABONOFE) BDQTDABONOFE, FERIASSUM.BDINIPERAQUISFE
          from VRH_EMP_TFERIAS FERIASSUM
          group by 1, 2, 5) FERIAS on SALDOFER.BDCODEMP = FERIAS.BDCODEMP and
      SALDOFER.BDCODCOL = FERIAS.BDCODCOL and
      SALDOFER.BDINIPERAQUIS = FERIAS.BDINIPERAQUISFE
order by SALDOFER.BDCODEMP, SALDOFER.BDCODCOL, SALDOFER.BDINIPERAQUIS^

/* Restore proc. body: SP_VRHF_GETFALTAS */
create or alter procedure SP_VRHF_GETFALTAS (
    PREMP integer,
    PRCOL integer,
    PRULTDIAMES date)
returns (
    BDREFFAL integer,
    BDDATAFAL date,
    BDTIPOFAL integer,
    BDHORASFAL numeric(18,6),
    BDTIPODSRFAL integer,
    BDTIPODESCFAL integer,
    BDCODTIPO integer,
    BDCODNOTIF integer,
    BDINDEVIDAFAL DM_BOOLEAN,
    BDDESCINDEVIDA varchar(100),
    BDNOFECHAMENTO DM_BOOLEAN)
as
declare variable WANOMES integer;
declare variable WDIAF integer;
declare variable WPRIDIAMES date;
declare variable WULTDIAMESANT date;
declare variable WDTINIFECHA date;
declare variable WDTFIMFECHA date;
begin
  -- substring(cast(prultdiames as varchar(10)) from 1 for 4) = ano
  -- substring(cast(prultdiames as varchar(10)) from 6 for 2) = mês

  wanomes = cast((substring(cast(prultdiames as varchar(10)) from 1 for 4)||substring(cast(prultdiames as varchar(10)) from 6 for 2)) as INTEGER);

  wpridiames = cast((substring(wanomes from 1 for 4)||'-'||substring(wanomes from 5 for 2)||'-01') as DATE); -- primeiro dia do mês

  -- Essa regra verifica se a falta está dentro do período de fechamento.
  select first 1 BDFECHAMESEMP from VRHF_BASE_TEMPCALC where BDCODEMP = :premp and BDREFEMP <= :wanomes order by BDREFEMP DESC into :wdiaf;
  wdiaf = coalesce(wdiaf, 0);

  if (wdiaf > 0 and wdiaf < 30) then
     begin
       wultdiamesant = wpridiames - 1;  -- último dia do mês anterior

       if (extract(day from :wultdiamesant) <= :wdiaf) then
          wdtinifecha = wpridiames;
       else
          begin
            wdtinifecha = cast((substring(cast(wultdiamesant as varchar(10)) from 1 for 4)||'-'||substring(cast(wultdiamesant as varchar(10)) from 6 for 2)||'-'||lpad(wdiaf, 2, '0')) as DATE);
            wdtinifecha = wdtinifecha + 1;
          end


       if (extract(day from :prultdiames) <= :wdiaf) then
          wdtfimfecha = prultdiames;
       else
          wdtfimfecha = cast((substring(cast(prultdiames as varchar(10)) from 1 for 4)||'-'||substring(cast(prultdiames as varchar(10)) from 6 for 2)||'-'||lpad(wdiaf, 2, '0')) as DATE);
     end
  else
     begin
       wdtinifecha = wpridiames;
       wdtfimfecha = prultdiames;
     end


  for select BDREFFAL, BDDATAFAL, BDTIPOFAL, BDHORASFAL, BDTIPODSRFAL, BDTIPODESCFAL, BDCODTIPO, BDCODNOTIF, BDINDEVIDAFAL, BDDESCINDEVIDA
      from VRH_EMP_TFALTAS_ITENS
      where BDCODEMP = :premp and BDCODCOL = :prcol
      order by BDTIPODSRFAL, BDDATAFAL
  into :BDREFFAL, :BDDATAFAL, :BDTIPOFAL, :BDHORASFAL, :BDTIPODSRFAL, :BDTIPODESCFAL, :BDCODTIPO, :BDCODNOTIF, :BDINDEVIDAFAL, :BDDESCINDEVIDA
  do
    begin
      if (BDDATAFAL between :wdtinifecha and :wdtfimfecha) then
         BDNOFECHAMENTO = 'TRUE';
      else
         BDNOFECHAMENTO = 'FALSE';
      suspend;
    end

end^

/* Restore proc. body: SP_VRHF_GETPISOSIND */
create or alter procedure SP_VRHF_GETPISOSIND (
    PRCODSINTRAB integer,
    PRANOMES integer)
returns (
    BDCODSINTRAB integer,
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDREFPISO integer,
    BDSALPISO numeric(15,6))
as
begin
  for select BDCODSINTRAB, BDCODPLAFUC, BDCODTFUC, max(BDREFPISO) REFPISO
      from VRH_BASE_TPISOSSIND
      where(:prcodsintrab <= 0 or BDCODSINTRAB = :prcodsintrab) and BDREFPISO <= :pranomes
      group by BDCODSINTRAB, BDCODPLAFUC, BDCODTFUC
      order by BDCODPLAFUC, BDCODTFUC, REFPISO DESC
  into :bdcodsintrab, :bdcodplafuc, :bdcodtfuc, :bdrefpiso
  do
    begin
      for select BDSALPISO
          from VRH_BASE_TPISOSSIND
          where (:prcodsintrab <= 0 or BDCODSINTRAB = :prcodsintrab) and BDCODPLAFUC = :bdcodplafuc and BDCODTFUC = :bdcodtfuc and BDREFPISO = :bdrefpiso
      into :BDSALPISO
      do
        suspend;
    end
end^

create or alter procedure SP_APLICA_PLANO_CC_AUTO (
    PRMOVIMENTO varchar(4),
    PRCODEMP integer,
    PRREF integer,
    PRAPENASVERIFICARCC integer,
    PRWHERE varchar(5000),
    PRHUGEFILE integer,
    PRARQUIVO varchar(260),
    PREXCLUIRMESMOSEMAPLICAR integer)
returns (
    BDAPLICOU DM_BOOLEAN)
as
declare variable WSQL varchar(5000);
declare variable WCHAVEPLANO integer;
declare variable WPLANO integer;
declare variable WCODTIPODOC integer;
declare variable WTIPOOPERIMOB integer;
declare variable WCONDPGTO integer;
declare variable WCODCID integer;
declare variable WCODATVM integer;
declare variable WCODNAT integer;
declare variable WCODTER integer;
declare variable WTIPOTER integer;
declare variable WTOTALFILTROS integer;
declare variable WCGCTERFIL integer;
declare variable WCODTIPODOCFIL integer;
declare variable WCONDPGTOFIL integer;
declare variable WCODCIDFIL integer;
declare variable WCODATVMFIL integer;
declare variable WCODNATFIL integer;
declare variable WCODTERFIL integer;
declare variable WVARIOSCODNATFIL integer;
declare variable WVARIOSCODTERFIL integer;
declare variable WCHAVECORRETA integer;
declare variable WFILTROSAPLICADOS integer;
declare variable WCODCENTRO integer;
declare variable WLANCACONFORMEMOV boolean;
declare variable WLANCADEB boolean;
declare variable WLANCACRED boolean;
declare variable WPERCENT numeric(7,4);
declare variable WCODTPCC integer;
declare variable WCHAVENOTA integer;
declare variable WORDEMNOTA integer;
declare variable WORDEMCC integer;
declare variable WVLRCONTABIL numeric(15,2);
declare variable WTABELAMOV varchar(40);
declare variable WTABELAITENS varchar(40);
declare variable WDEBCRED integer;
declare variable WTABELAMOVCC varchar(40);
declare variable WSESSAO integer;
declare variable WNOMCTA varchar(50);
declare variable WMOVENTFIL boolean;
declare variable WMOVSAIFIL boolean;
declare variable WMOVSERFIL boolean;
declare variable WREDZFIL boolean;
declare variable WDEMAISDOCFIL boolean;
declare variable WCAMPOCNPJTER varchar(20);
declare variable WABRIUARQ boolean;
declare variable WCAMPOSESSAO varchar(12);
declare variable WCGCTER varchar(18);
declare variable WDEBCREDMOV integer;
declare variable WNAOPERMITERATEIOGRUPO boolean;
declare variable WQTDACOES integer;
declare variable WCODCENTROS integer;
begin
  :BDAPLICOU = 'FALSE';

  /* Busca campos da empresa por referência */
  SELECT FIRST 1 COALESCE(EMP.BDNAOPERMITERATEIOGRUPO, FALSE) BDNAOPERMITERATEIOGRUPO, COALESCE(EMP.BDCODCENTROS, 0) BDCODCENTROS
  FROM TEMPRESAS_REF EMP
  WHERE (EMP.BDCODEMP = :PRCODEMP) AND (EMP.BDREFEMP <= :PRREF)
  ORDER BY EMP.BDREFEMP DESC
  INTO :wNaoPermiteRateioGrupo, :wCodCentros;

  /* Busca o plano de CC automático vinculado na empresa.
     Se o plano do CC que está na empresa é diferente do plano do CC que está no plano do CC automático, não deve aplicar */
  select coalesce(EMP.BDCODPLANOCCAUTO, 0) BDPLANO
  from (select FIRST 1 EMP.BDCODPLANOCCAUTO
        from VEF_BASE_TEMPPARINTEG EMP
        where (EMP.BDCODEMP = :PRCODEMP) and
              (EMP.BDREFEMP <= :PRREF)
        order by EMP.BDREFEMP desc) EMP
  inner join VEF_BASE_TPLANOCCAUTOMATICO CC on (EMP.BDCODPLANOCCAUTO = CC.BDCODPLANOCCAUTO)
  where (CC.BDCODCENTRO = :WCODCENTROS)
  INTO :wPlano;

  if ((wPlano is null) or (wPlano = 0)) then
    begin
      suspend;
      Exit;
    end

  wChavePlano = 0;

  prMOVIMENTO = UPPER(prMOVIMENTO);

  wMOVENTFIL = (prMOVIMENTO = 'ENT');
  wMOVSAIFIL = (prMOVIMENTO = 'SAI');
  wMOVSERFIL = (prMOVIMENTO = 'SER');
  wREDZFIL = (prMOVIMENTO = 'REDZ');
  wDEMAISDOCFIL = (prMOVIMENTO = 'DOC');

  if (prHUGEFILE = 1) then
    begin
      if (prMOVIMENTO = 'REDZ') then
        wCampoCNPJTer = 'ITEM.BDCGCTER';
      else
        wCampoCNPJTer = 'MOV.BDCNPJ';
    end
  else
    begin
      wCampoCNPJTer = 'TER.BDCGCTER';
    end

  /* Saídas */
  if (prMOVIMENTO = 'SAI') then
    begin
      if (prHUGEFILE = 1) then
         begin
           wTabelaMov = 'TMP_VEF_EMP_TMOVSAI_TEMP';
           wTabelaItens = 'TMP_VEF_EMP_TMOVSAIITENS_TEMP';
           wTabelaMovCC = 'TMP_VEF_EMP_TMOVCCSAI_TEMP';
           wCAMPOSESSAO = 'MOV.BDSESSAO';
         end
      else
         begin
           wTabelaMov = 'VEF_EMP_TMOVSAI';
           wTabelaItens = 'VEF_EMP_TMOVSAIITENS';
           wTabelaMovCC = 'VEF_EMP_TMOVCCSAI';
           wCAMPOSESSAO = '0';
         end
    end
  else
  /* Entradas */
  if (prMOVIMENTO = 'ENT') then
    begin
      wTabelaMov = 'VEF_EMP_TMOVENT';
      wTabelaItens = 'VEF_EMP_TMOVENTITENS';
      wTabelaMovCC = 'VEF_EMP_TMOVCCENT';
      wCAMPOSESSAO = '0';
    end

  /* Pega os campos necessários das tabelas de movimento */
  if ((prMOVIMENTO = 'SAI') or (prMOVIMENTO = 'ENT')) then
    begin
      wSQL = ' SELECT MOV.BDCHAVE, ITEM.BDORDEM, ITEM.BDVLRCONTAB, IIF(CHAR_LENGTH('|| :wCampoCNPJTer ||') = 14, 2, IIF(CHAR_LENGTH('|| :wCampoCNPJTer ||') = 18, 1,Null)) AS BDTIPOTER ,0 AS BDCODTIPODOC, 0 AS BDTIPOOPERIMOB, ';
      wSQL = wSQL || ' MOV.BDCONDPGTO, 0 AS BDCODCID, 0 AS BDCODATVM, ITEM.BDCODNAT, ' || :wCampoCNPJTer || ' AS BDCGCTER, MOV.BDCODTER, '|| :wCAMPOSESSAO ||' AS BDSESSAO, ';

      if (prMOVIMENTO = 'SAI') then
        wSQL = wSQL || ' 1 AS BDDEBCRED ';
      else
        wSQL = wSQL || ' 0 AS BDDEBCRED ';

      wSQL = wSQL || ' FROM ' || :wTabelaMov || ' MOV ';
      wSQL = wSQL || ' INNER JOIN ' || :wTabelaItens || ' ITEM ON ITEM.BDCODEMP = MOV.BDCODEMP AND ITEM.BDCHAVE = MOV.BDCHAVE ';

      if (prHUGEFILE = 1) then
        wSQL = wSQL || ' AND ITEM.BDSESSAO = MOV.BDSESSAO ';
      else
        wSQL = wSQL || ' INNER JOIN TTERCEIRO TER ON TER.BDCODTER = MOV.BDCODTER ';

      if (prApenasVerificarCC = 1) then
        wSQL = wSQL || ' INNER JOIN ' || :wTabelaMovCC || ' CC ON CC.BDCODEMP = ITEM.BDCODEMP AND CC.BDCHAVE = ITEM.BDCHAVE AND CC.BDORDEM = ITEM.BDORDEM ';
    end
  else
  if (prMOVIMENTO = 'SER') then
    begin
      wSQL = ' SELECT MOV.BDCHAVE, ITEM.BDORDEM, ITEM.BDVLRCONTAB, IIF(CHAR_LENGTH('|| :wCampoCNPJTer ||') = 14, 2, IIF(CHAR_LENGTH('|| :wCampoCNPJTer ||') = 18, 1,Null)) AS BDTIPOTER, 0 AS BDCODTIPODOC, 0 AS BDTIPOOPERIMOB, ';
      wSQL = wSQL || ' MOV.BDCONDPGTO, MOV.BDCODCID, ITEM.BDCODATVM, ITEM.BDCODNAT, TER.bdcgcter AS BDCGCTER, MOV.BDCODTER, 0 AS BDSESSAO, IIF(MOV.BDTIPLAN = 0, 1, 0) AS BDDEBCRED ';
      wSQL = wSQL || ' FROM VEF_EMP_TMOVSER MOV ';
      wSQL = wSQL || ' INNER JOIN VEF_EMP_TMOVSERITENS ITEM ON ITEM.BDCODEMP = MOV.BDCODEMP AND ITEM.BDCHAVE = MOV.BDCHAVE ';
      wSQL = wSQL || ' INNER JOIN TTERCEIRO TER ON TER.BDCODTER = MOV.BDCODTER ';

      if (prApenasVerificarCC = 1) then
        wSQL = wSQL || ' INNER JOIN VEF_EMP_TMOVCCSER CC ON CC.BDCODEMP = ITEM.BDCODEMP AND CC.BDCHAVE = ITEM.BDCHAVE AND CC.BDORDEM = ITEM.BDORDEM ';
    end
  else
  if (prMovimento = 'REDZ') then
    begin
       if (prHUGEFILE = 1) then
         begin
           :wTabelaMov = 'TMP_VEF_EMP_TREDZ_TEMP';
           :wTabelaItens = 'TMP_VEF_EMP_TREDZVARCFOP_TEMP';
           :wTabelaMovCC = 'TMP_VEF_EMP_TMOVCCREDZ_TEMP';
           :wCAMPOSESSAO = 'MOV.BDSESSAO';
         end
       else
         begin
           :wTabelaMov = 'VEF_EMP_TREDZ';
           :wTabelaItens = 'VEF_EMP_TREDZVARCFOP';
           :wTabelaMovCC = 'VEF_EMP_TMOVCCREDZ';
           :wCAMPOSESSAO = '0';
         end

      wSQL = ' SELECT MOV.BDCHAVE, ITEM.BDORDEMVARCFOP, ITEM.BDVLRCONTAB, IIF(CHAR_LENGTH('|| :wCampoCNPJTer ||') = 14, 2, IIF(CHAR_LENGTH('|| :wCampoCNPJTer ||') = 18, 1,Null)) AS BDTIPOTER, 0 AS BDCODTIPODOC, 0 AS BDTIPOOPERIMOB, ';
      wSQL = wSQL || ' ITEM.BDCONDPGTO, 0 AS BDCODCID, 0 AS BDCODATVM, ITEM.BDCODNAT, '|| :wCampoCNPJTer ||' AS BDCGCTER, ITEM.BDCODTER, '|| :wCAMPOSESSAO ||' AS BDSESSAO, 1 AS BDDEBCRED ';
      wSQL = wSQL || ' FROM ' || :wTabelaMov || ' MOV ';
      wSQL = wSQL || ' INNER JOIN ' || :wTabelaItens || ' ITEM ON ITEM.BDCODEMP = MOV.BDCODEMP AND ITEM.BDCHAVE = MOV.BDCHAVE ';

      if (prHUGEFILE = 1) then
        wSQL = wSQL || ' AND ITEM.BDSESSAO = MOV.BDSESSAO ';
      else
        wSQL = wSQL || ' INNER JOIN TTERCEIRO TER ON TER.BDCODTER = ITEM.BDCODTER '; /* Se for HugeFile tem que pegar da TTerceiro também, porque o usuário informa o participante na tela de importação, ou seja, já vai estar cadastrado */

      if (prApenasVerificarCC = 1) then
        wSQL = wSQL || ' INNER JOIN ' || :wTabelaMovCC || ' CC ON CC.BDCODEMP = ITEM.BDCODEMP AND CC.BDCHAVE = ITEM.BDCHAVE AND CC.BDORDEMVARCFOP = ITEM.BDORDEMVARCFOP ';
    end
  else
  if (prMovimento = 'DOC') then
    begin
      wSQL = ' SELECT MOV.BDCHAVE, 0 AS BDORDEM, MOV.BDVL_OPER, IIF(CHAR_LENGTH('|| :wCampoCNPJTer ||') = 14, 2, IIF(CHAR_LENGTH('|| :wCampoCNPJTer ||') = 18, 1,Null)) AS BDTIPOTER, MOV.BDCODTIPODOC, 0 AS BDTIPOOPERIMOB, ';
      wSQL = wSQL || ' MOV.BDCONDPGTO, 0 AS BDCODCID, 0 AS BDCODATVM, 0 AS BDCODNAT, TER.BDCGCTER AS BDCGCTER, MOV.BDCODTER, 0 AS BDSESSAO, IIF(BDIND_OPER = 1, 0, 1) AS BDDEBCRED ';
      wSQL = wSQL || ' FROM VEF_EMP_TMOVDEMAISDOC_F100 MOV ';
      wSQL = wSQL || ' INNER JOIN TTERCEIRO TER ON TER.BDCODTER = MOV.BDCODTER ';

      if (prApenasVerificarCC = 1) then
        wSQL = wSQL || ' INNER JOIN VEF_EMP_TMOVCCDEMDOCF100 CC ON CC.BDCODEMP = MOV.BDCODEMP AND CC.BDCHAVE = MOV.BDCHAVE ';
    end
  else
    begin
      suspend;
      Exit;
    end

  if (prMovimento = 'DOC') then
    wSQL = wSQL || ' WHERE MOV.BDVL_OPER > 0 ' || IIF(:prWHERE <> '', 'AND (' || :prWHERE || ')', '');
  else
    wSQL = wSQL || ' WHERE ITEM.BDVLRCONTAB > 0 ' || IIF(:prWHERE <> '', 'AND (' || :prWHERE || ')', '');

  wABRIUARQ = False;

  for execute statement wSQL into :wChaveNota, :wOrdemNota, :wVlrContabil, :wTIPOTER, :wCODTIPODOC, :wTIPOOPERIMOB, :wCONDPGTO, :wCODCID, :wCODATVM, :wCODNAT, :wCGCTER, :wCODTER, :wSESSAO, :wDEBCRED
  do
    begin
       wChaveCorreta = 0;
       wTotalFiltros = 0;

       FOR
         /* Verifica se a nota se encaixa em algum filtro do plano */
         SELECT FIL.BDCHAVE, FIL.BDCGCTERFIL, FIL.BDCODTIPODOCFIL, FIL.BDCONDPGTOFIL, FIL.BDCODCIDFIL, FIL.BDCODATVMFIL, FIL.BDCODNATFIL, FIL.BDCODTERFIL, CFOP.BDCODNAT, TER.BDCODTER
         FROM VEF_BASE_TPLANOFILTROSCCAUTO FIL
         LEFT OUTER JOIN VEF_BASE_TPLANOACOESCCAUTO_CFOP CFOP ON (FIL.BDCODPLANOCCAUTO = CFOP.BDCODPLANOCCAUTO) AND (FIL.BDCHAVE = CFOP.BDCHAVE)
         LEFT OUTER JOIN VEF_BASE_TPLANOACOESCCAUTO_TER TER ON (FIL.BDCODPLANOCCAUTO = TER.BDCODPLANOCCAUTO) AND (FIL.BDCHAVE = TER.BDCHAVE)
         LEFT OUTER JOIN TTERCEIRO T ON (TER.BDCODTER = T.BDCODTER)
         WHERE (FIL.BDCODPLANOCCAUTO = :wPlano) AND
               ((FIL.BDCGCTERFIL = :wTIPOTER) or (FIL.BDCGCTERFIL = 0)) AND
               ((FIL.BDCODTIPODOCFIL = :wCODTIPODOC) or (FIL.BDCODTIPODOCFIL IS NULL)) AND
               ((FIL.BDTIPOOPERIMOBFIL = :wTIPOOPERIMOB) or (FIL.BDTIPOOPERIMOBFIL = 0)) AND
               ((FIL.BDCONDPGTOFIL = (:wCONDPGTO + 1)) or (FIL.BDCONDPGTOFIL = 0)) AND
               ((FIL.BDCODCIDFIL = :wCODCID) or (FIL.BDCODCIDFIL IS NULL)) AND
               ((FIL.BDCODATVMFIL = :wCODATVM) or (FIL.BDCODATVMFIL IS NULL)) AND
               (((FIL.BDCODNATFIL = :wCODNAT) or (CFOP.BDCODNAT = :wCODNAT)) or ((FIL.BDCODNATFIL IS NULL) AND (CFOP.BDCODNAT IS NULL))) AND
               /* Se for HugeFile, tem que usar o CPF/CNPJ */
               (((:prHugeFile = 0) and (((FIL.BDCODTERFIL = :wCODTER) or (TER.BDCODTER = :wCODTER)) or ((FIL.BDCODTERFIL IS NULL) AND (TER.BDCODTER IS NULL)))) or
               ((:prHugeFile = 1) and (((T.BDCGCTER = :wCGCTER) /*or (TER.BDCODTER = :wCODTER)*/) or ((FIL.BDCODTERFIL IS NULL) AND (TER.BDCODTER IS NULL))))) AND
                ((FIL.BDMOVENTFIL = :wMOVENTFIL AND FIL.BDMOVENTFIL = TRUE) OR (FIL.BDMOVSAIFIL = :wMOVSAIFIL AND FIL.BDMOVSAIFIL = TRUE) OR
                 (FIL.BDMOVSEREMITFIL = :wMOVSERFIL AND FIL.BDMOVSEREMITFIL = TRUE AND :wDEBCRED = 1) OR (FIL.BDMOVSERRECFIL = :wMOVSERFIL AND FIL.BDMOVSERRECFIL = TRUE AND :wDEBCRED = 0) OR
                 (FIL.BDDEMAISDOCRECFIL = :wDEMAISDOCFIL AND FIL.BDDEMAISDOCRECFIL = TRUE AND :wDEBCRED = 0) OR (FIL.BDDEMAISDOCAQFIL = :wDEMAISDOCFIL AND FIL.BDDEMAISDOCAQFIL = TRUE AND :wDEBCRED = 1) OR
                 (FIL.BDREDZFIL = :wREDZFIL AND FIL.BDREDZFIL = TRUE))
         INTO :wChavePlano, :wCGCTERFIL, :wCODTIPODOCFIL, :wCONDPGTOFIL, :wCODCIDFIL, :wCODATVMFIL, :wCODNATFIL, :wCODTERFIL, :wVARIOSCODNATFIL, :wVARIOSCODTERFIL
       DO
         begin
           if (wChavePlano > 0) then
             begin
               if (wNaoPermiteRateioGrupo) then
                 begin
                   wQtdAcoes = 0;

                   SELECT FIRST 1 COUNT(*)
                   FROM VEF_BASE_TPLANOACOESCCAUTO AC
                   WHERE AC.BDCODPLANOCCAUTO = :wPlano AND
                         AC.BDCHAVE = :wChavePlano AND
                         ((:wDEBCRED = 0 AND AC.BDLANCACRED = TRUE) or -- Se a nota é a crédito, não pode lançar CC a débito
                         (:wDEBCRED = 1 AND AC.BDLANCADEB = TRUE)) -- Se a nota é a débito, não pode lançar CC a crédito
                   INTO :wQtdAcoes;

                   if (wQtdAcoes > 0) then
                     continue;
                 end

               /* Verifica se tem pelo menos uma ação informada nessa chave do plano */
               select first 1 count(*)
               from VEF_BASE_TPLANOACOESCCAUTO AC
               where AC.BDCODPLANOCCAUTO = :WPLANO and
                     AC.BDCHAVE = :WCHAVEPLANO
               INTO :wQtdAcoes;

               if (wQtdAcoes = 0) then
                 continue;

               /* Verifica se a chave está com os percentuais corretos. Se não estiver fechando 100%, não pode aplicar essa chave */
               select first 1 count(*)
               from (select sum(AC.BDPERCENT) BDPERCTOTAL
                     from VEF_BASE_TPLANOACOESCCAUTO AC
                     where AC.BDCODPLANOCCAUTO = :WPLANO and
                           AC.BDCHAVE = :WCHAVEPLANO and
                           AC.BDLANCACONFORMEMOV = true
                     union all
                     select sum(AC.BDPERCENT) BDPERCTOTAL
                     from VEF_BASE_TPLANOACOESCCAUTO AC
                     where AC.BDCODPLANOCCAUTO = :WPLANO and
                           AC.BDCHAVE = :WCHAVEPLANO and
                           AC.BDLANCADEB = true
                     union all
                     select sum(AC.BDPERCENT) BDPERCTOTAL
                     from VEF_BASE_TPLANOACOESCCAUTO AC
                     where AC.BDCODPLANOCCAUTO = :WPLANO and
                           AC.BDCHAVE = :WCHAVEPLANO and
                           AC.BDLANCACRED = true) S
               where (S.BDPERCTOTAL > 0) and
                     (S.BDPERCTOTAL <> 100)
               INTO :wQtdAcoes;

               if (wQtdAcoes > 0) then
                 continue;

               :BDAPLICOU = 'TRUE';

               /* Se está apenas verificando se o CC automático vai ser aplicado em alguma nota com CC já lançado, pode sair fora aqui mesmo */
               if (prApenasVerificarCC = 1) then
                 begin
                   suspend;
                   Exit;
                 end

               wFiltrosAplicados = 1;

               if (wCGCTERFIL > 0) then
                 wFiltrosAplicados = wFiltrosAplicados + 1;

               if (wCODTIPODOCFIL > 0) then
                 wFiltrosAplicados = wFiltrosAplicados + 1;

               if (wCONDPGTOFIL > 0) then
                 wFiltrosAplicados = wFiltrosAplicados + 1;

               if (wCODCIDFIL > 0) then
                 wFiltrosAplicados = wFiltrosAplicados + 1;

               if (wCODATVMFIL > 0) then
                 wFiltrosAplicados = wFiltrosAplicados + 1;

               if ((wCODNATFIL > 0) or (wVARIOSCODNATFIL > 0)) then
                 wFiltrosAplicados = wFiltrosAplicados + 1;

               if ((wCODTERFIL > 0) or (wVARIOSCODTERFIL > 0)) then
                 wFiltrosAplicados = wFiltrosAplicados + 1;

               /* Caso a nota se encaixe em mais de um filtro, deve usar o filtro mais específico */
               if (wFiltrosAplicados > wTotalFiltros) then
                 begin
                   wTotalFiltros = wFiltrosAplicados;
                   wChaveCorreta = wChavePlano;
                 end
             end
         end

       if ((wChaveCorreta > 0) or (prExcluirMesmoSemAplicar = 1)) then
         begin
           if ((prApenasVerificarCC = 1) and (prExcluirMesmoSemAplicar = 1)) then
             begin
               /* Retorna no BDAPLICOU se iria excluir algum CC ou não */
               if (prMOVIMENTO = 'SAI') then
                 begin
                   if (prhugefile = 1) then
                     SELECT FIRST 1 IIF(COUNT(*) > 0, 'TRUE', 'FALSE') FROM TMP_VEF_EMP_TMOVCCSAI_TEMP WHERE BDCODEMP = :prCodEmp AND BDCHAVE = :wChaveNota AND BDORDEM = :wOrdemNota AND BDSESSAO = :wSESSAO INTO :BDAPLICOU;
                   else
                     SELECT FIRST 1 IIF(COUNT(*) > 0, 'TRUE', 'FALSE') FROM VEF_EMP_TMOVCCSAI WHERE BDCODEMP = :prCodEmp AND BDCHAVE = :wChaveNota AND BDORDEM = :wOrdemNota INTO :BDAPLICOU;
                 end
               else
               if (prMOVIMENTO = 'ENT') then
                 SELECT FIRST 1 IIF(COUNT(*) > 0, 'TRUE', 'FALSE') FROM VEF_EMP_TMOVCCENT WHERE BDCODEMP = :prCodEmp AND BDCHAVE = :wChaveNota AND BDORDEM = :wOrdemNota INTO :BDAPLICOU;
               else
               if (prMOVIMENTO = 'SER') then
                 SELECT FIRST 1 IIF(COUNT(*) > 0, 'TRUE', 'FALSE') FROM VEF_EMP_TMOVCCSER WHERE BDCODEMP = :prCodEmp AND BDCHAVE = :wChaveNota AND BDORDEM = :wOrdemNota INTO :BDAPLICOU;
               else
               if (prmovimento = 'REDZ') then
                 begin
                   if (prhugefile = 1) then
                     SELECT FIRST 1 IIF(COUNT(*) > 0, 'TRUE', 'FALSE') FROM TMP_VEF_EMP_TMOVCCREDZ_TEMP WHERE BDCODEMP = :prCodEmp AND BDCHAVE = :wChaveNota AND BDORDEMVARCFOP = :wOrdemNota AND BDSESSAO = :wSESSAO INTO :BDAPLICOU;
                   else
                     SELECT FIRST 1 IIF(COUNT(*) > 0, 'TRUE', 'FALSE') FROM VEF_EMP_TMOVCCREDZ WHERE BDCODEMP = :prCodEmp AND BDCHAVE = :wChaveNota AND BDORDEMVARCFOP = :wOrdemNota INTO :BDAPLICOU;
                 end
               else
               if (prMovimento = 'DOC') then
                 SELECT FIRST 1 IIF(COUNT(*) > 0, 'TRUE', 'FALSE') FROM VEF_EMP_TMOVCCDEMDOCF100 WHERE BDCODEMP = :prCodEmp AND BDCHAVE = :wChaveNota INTO :BDAPLICOU;

               /* Se aplicou, sai fora, se não aplicou, verifica a próxima nota */
               if (:BDAPLICOU = 'TRUE') then
                 begin
                   suspend;
                   exit;
                 end
               else
                 continue;
             end

           /* Exclui os CCs que já existiam na nota antes de lançar os novos */
           if (prMOVIMENTO = 'SAI') then
             begin
               if (prhugefile = 1) then
                 DELETE FROM TMP_VEF_EMP_TMOVCCSAI_TEMP WHERE BDCODEMP = :prCodEmp AND BDCHAVE = :wChaveNota AND BDORDEM = :wOrdemNota AND BDSESSAO = :wSESSAO;
               else
                 DELETE FROM VEF_EMP_TMOVCCSAI WHERE BDCODEMP = :prCodEmp AND BDCHAVE = :wChaveNota AND BDORDEM = :wOrdemNota;
             end
           else
           if (prMOVIMENTO = 'ENT') then
             DELETE FROM VEF_EMP_TMOVCCENT WHERE BDCODEMP = :prCodEmp AND BDCHAVE = :wChaveNota AND BDORDEM = :wOrdemNota;
           else
           if (prMOVIMENTO = 'SER') then
             DELETE FROM VEF_EMP_TMOVCCSER WHERE BDCODEMP = :prCodEmp AND BDCHAVE = :wChaveNota AND BDORDEM = :wOrdemNota;
           else
           if (prmovimento = 'REDZ') then
             begin
               if (prhugefile = 1) then
                 DELETE FROM TMP_VEF_EMP_TMOVCCREDZ_TEMP WHERE BDCODEMP = :prCodEmp AND BDCHAVE = :wChaveNota AND BDORDEMVARCFOP = :wOrdemNota AND BDSESSAO = :wSESSAO;
               else
                 DELETE FROM VEF_EMP_TMOVCCREDZ WHERE BDCODEMP = :prCodEmp AND BDCHAVE = :wChaveNota AND BDORDEMVARCFOP = :wOrdemNota;
             end
           else
           if (prMovimento = 'DOC') then
             DELETE FROM VEF_EMP_TMOVCCDEMDOCF100 WHERE BDCODEMP = :prCodEmp AND BDCHAVE = :wChaveNota;

           /* Se entrou no IF acima só pra excluir o CC já existente, já pode ir pra próxima nota. */
           /* Isso irá acontecer quando o plano do CC automático for aplicado por causa de alteração pelo grid ou pela troca global nas importações, */
           /* porque nesse caso tem que remover o CC gerado anteriormente pelo plano caso a nova CFOP não se encaixar em nenhum plano, por exemplo*/
           if (wChaveCorreta <= 0) then
             continue;

           /* Cria e abre o arquivo de log */
           if ((not :wABRIUARQ) and (:prArquivo <> '')) then
             begin
               NEWFILE(:prArquivo);
               OPENARQ(:prArquivo, :prCODEMP);

               wABRIUARQ = True;
             end

           /* Grava o log no arquivo */
           WRITELNOA('Plano: ' || :wPlano || ' - Lançamento de ' || :prMOVIMENTO || ': Chave ' || :wChaveNota || '(CFOP: ' || :wCODNAT || ', ordem: ' || :wOrdemNota || ') - Chave de troca aplicada: ' || wChaveCorreta, :prCODEMP);

           wOrdemCC = 1;

           FOR
             /* Busca as ações cadastradas na chave do plano */
             SELECT AC.BDCODCENTRO, AC.BDLANCACONFORMEMOV, AC.BDLANCADEB, AC.BDLANCACRED, AC.BDPERCENT, AC.BDCODTPCC
             FROM VEF_BASE_TPLANOACOESCCAUTO AC
             WHERE AC.BDCODPLANOCCAUTO = :wPlano AND
                   AC.BDCHAVE = :wChaveCorreta
             INTO :wCODCENTRO, :wLANCACONFORMEMOV, :wLANCADEB, :wLANCACRED, :wPERCENT, :wCODTPCC
           DO
             begin

               if (prHUGEFILE = 1) then
                 begin
                   /* Busca o nome da conta */
                   Execute statement 'SELECT FIRST 1 BDNOMCTA FROM CENTROS_TPCC TPCC WHERE TPCC.BDCODCENTRO = ' || :wCODCENTRO || ' AND TPCC.BDCODTPCC = ' || :wCODTPCC || ' AND TPCC.BDTIPCTA = 1' into :wNOMCTA;
                 end

               if (wLANCACONFORMEMOV) then
                 wDEBCREDMOV = wDebCred;
               else
               if (wLANCADEB and wLANCACRED) then
                 wDEBCREDMOV = 2;
               else
               if (wLANCADEB) then
                 wDEBCREDMOV = 0;
               else
               if (wLANCACRED) then
                 wDEBCREDMOV = 1;
               else
                 continue;

               /* Lança os novos CCs conforme as ações do plano */
               if ((prMOVIMENTO = 'SAI')) then
                 begin
                   if (prHUGEFILE = 1) then
                     begin
                       INSERT INTO TMP_VEF_EMP_TMOVCCSAI_TEMP (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMCC, BDSESSAO, BDCODCENTRO, BDCODTPCC, BDVALOR, BDPERCENTUAL, BDVLRIMP, BDDEBCRED, BDNOMCTA)
                       VALUES (:prCodEmp, :wChaveNota, :wOrdemNota, :wOrdemCC, :wSESSAO, :wCODCENTRO, :wCODTPCC, :wVlrContabil * :wPERCENT / 100, :wPERCENT, 0, :wDEBCREDMOV, :wNOMCTA);
                     end
                   else
                     begin
                       INSERT INTO VEF_EMP_TMOVCCSAI (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMCC, BDCODCENTRO, BDCODTPCC, BDVALOR, BDPERCENTUAL, BDVLRIMP, BDDEBCRED)
                       VALUES (:prCodEmp, :wChaveNota, :wOrdemNota, :wOrdemCC, :wCODCENTRO, :wCODTPCC, :wVlrContabil * :wPERCENT / 100, :wPERCENT, 0, :wDEBCREDMOV);
                     end
                 end
               else
               if (prMOVIMENTO = 'ENT') then
                 begin
                   INSERT INTO VEF_EMP_TMOVCCENT (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMCC, BDCODCENTRO, BDCODTPCC, BDVALOR, BDPERCENTUAL, BDVLRIMP, BDDEBCRED)
                   VALUES (:prCodEmp, :wChaveNota, :wOrdemNota, :wOrdemCC, :wCODCENTRO, :wCODTPCC, :wVlrContabil * :wPERCENT / 100, :wPERCENT, 0, :wDEBCREDMOV);
                 end
               else
               if (prMOVIMENTO = 'SER') then
                 begin
                   INSERT INTO VEF_EMP_TMOVCCSER (BDCODEMP, BDCHAVE, BDORDEM, BDORDEMCC, BDCODCENTRO, BDCODTPCC, BDVALOR, BDPERCENTUAL, BDVLRIMP, BDDEBCRED)
                   VALUES (:prCodEmp, :wChaveNota, :wOrdemNota, :wOrdemCC, :wCODCENTRO, :wCODTPCC, :wVlrContabil * :wPERCENT / 100, :wPERCENT, 0, :wDEBCREDMOV);
                 end
               else
               if (prMOVIMENTO = 'REDZ') then
                 begin
                   if (prHUGEFILE = 1) then
                     begin
                       INSERT INTO TMP_VEF_EMP_TMOVCCREDZ_TEMP (BDCODEMP, BDCHAVE, BDORDEMVARCFOP, BDORDEMCC, BDSESSAO, BDCODCENTRO, BDCODTPCC, BDVALOR, BDPERCENTUAL, BDVLRIMP, BDDEBCRED, BDNOMCTA/*, BDCODNAT, BDCONDPGTO, BDCODTER*/)
                       VALUES (:prCodEmp, :wChaveNota, :wOrdemNota, :wOrdemCC, :wSessao, :wCODCENTRO, :wCODTPCC, :wVlrContabil * :wPERCENT / 100, :wPERCENT, 0, :wDEBCREDMOV, :wNOMCTA/*, :wCODNAT, :wCONDPGTO, :wCODTER*/);
                     end
                   else
                     begin
                       INSERT INTO VEF_EMP_TMOVCCREDZ (BDCODEMP, BDCHAVE, BDORDEMVARCFOP, BDORDEMCC, BDCODCENTRO, BDCODTPCC, BDVALOR, BDPERCENTUAL, BDVLRIMP, BDDEBCRED/*, BDCODNAT, BDCONDPGTO, BDCODTER*/)
                       VALUES (:prCodEmp, :wChaveNota, :wOrdemNota, :wOrdemCC, :wCODCENTRO, :wCODTPCC, :wVlrContabil * :wPERCENT / 100, :wPERCENT, 0, :wDEBCREDMOV/*, :wCODNAT, :wCONDPGTO, :wCODTER*/);
                     end
                 end
               else
               if (prMovimento = 'DOC') then
                 begin
                   INSERT INTO VEF_EMP_TMOVCCDEMDOCF100 (BDCODEMP, BDCHAVE, BDORDEMCC, BDCODCENTRO, BDCODTPCC, BDVALOR, BDPERCENTUAL, BDDEBCRED)
                   VALUES (:prCodEmp, :wChaveNota, :wOrdemCC, :wCODCENTRO, :wCODTPCC, :wVlrContabil * :wPERCENT / 100, :wPERCENT, IIF(:wLANCACONFORMEMOV, :wDEBCRED, IIF(:wLANCADEB, 0, 1)));
                 end

               wOrdemCC = wOrdemCC + 1;
             end
         end
    end

  /* Fecha o arquivo de log */
  if (:wABRIUARQ) then
    CLOSEARQ(:prArquivo, :prCODEMP);

  Suspend;
end^

SET TERM ; ^

COMMENT ON PARAMETER SP_APLICA_PLANO_CC_AUTO.PRAPENASVERIFICARCC IS
'0 = Aplica o plano, 1 = Apenas verifica se o plano vai ser aplicado em algum nota que já tem CC lançado';

COMMENT ON PARAMETER SP_APLICA_PLANO_CC_AUTO.PRHUGEFILE IS
'0 = Não, 1 = Sim';

COMMENT ON PARAMETER SP_APLICA_PLANO_CC_AUTO.PREXCLUIRMESMOSEMAPLICAR IS
'0 = Não, 1 = Sim';

SET TERM ^ ;


CREATE OR ALTER TRIGGER VRH_BASE_TLISTAJSONRHNET_BI0 FOR VRH_BASE_TLISTAJSONRHNET
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wcod INTEGER;
begin
  if (coalesce(new.bdcodrhnet, 0) <= 0) then
     begin
       select coalesce(max(bdcodrhnet), 0) + 1  from vrh_base_tlistajsonrhnet into :wcod;
       new.bdcodrhnet = :wcod;
     end

end
^


/* Restore proc. body: SP_VRHF_GETRESCISAOESTABRED */
create or alter procedure SP_VRHF_GETRESCISAOESTABRED (
    PREMP integer,
    PRCOL integer,
    PRLISTAANOS varchar(500))
returns (
    ANO integer,
    DATAINICIO date,
    DATAFIM date,
    SUSPENSAO DM_BOOLEAN,
    PERCREDUCAO numeric(18,6),
    DIASREDSUSP integer,
    BDDIASACORDOINI integer)
as
declare variable WSQL varchar(20000);
begin
  wsql = 'select ANO, DATAINICIO, DATAFIM, SUSPENSAO, PERCREDUCAO, DIASREDSUSP, BDDIASACORDOINI '||
         'from '||
           '(select (extract(year from (SIT.BDDATAINISEFIP))) ANO, SIT.BDDATAINISEFIP DATAINICIO, SIT.BDDATAFIMSIT DATAFIM, '||
               'PREP.BDSUSPMP SUSPENSAO, 100 PERCREDUCAO, SIT.BDDIASSIT DIASREDSUSP, SIT.BDDIASACORDOINI '||
            'from VRH_EMP_TSITCOL SIT '||
            'join VRH_BASE_TPREPSIT PREP on SIT.BDCODSIT = PREP.BDCODSIT and PREP.BDSUSPMP = ''TRUE'' '||
            'where SIT.BDCODEMP = '||premp||' and '||
                  'SIT.BDCODCOL = '||prcol||' and '||
                  '(extract(year from (SIT.BDDATAINISEFIP)) in ('||prlistaanos||')) '||
            'union all '||
            'select (extract(year from (RED.BDDATAINIREDSAL))), RED.BDDATAINIREDSAL, RED.BDDATAFIMREDSAL, '||
               '''FALSE'', RED.BDPERCREDSAL, RED.BDQTDDIASREDSAL, RED.BDDIASACORDOINI '||
            'from VRH_EMP_TREDUCAOCOL RED '||
            'where RED.BDCODEMP = '||premp||' and '||
                  'RED.BDCODCOL = '||prcol||' and '||
                  '(extract(year from (RED.BDDATAINIREDSAL)) in ('||prlistaanos||')) '||
            'union all '||
            'select (extract(year from (coalesce(SIT.BDDATAPARTOSIT, SIT.BDDATAINISEFIP)))), coalesce(SIT.BDDATAPARTOSIT, SIT.BDDATAINISEFIP) DATAINICIO, '||
              'coalesce(SIT.BDDATAESTAB, SIT.BDDATAFIMSIT), ''FALSE'', 0, SIT.BDDIASSIT, SIT.BDDIASACORDOINI '||
            'from VRH_EMP_TSITCOL SIT '||
            'join VRH_BASE_TPREPSIT PREP on SIT.BDCODSIT = PREP.BDCODSIT and PREP.BDGRUPOSIT in (0,4) '||
            'where SIT.BDCODEMP = '||premp||' and '||
                  'SIT.BDCODCOL = '||prcol||' and '||
                  '(extract(year from (coalesce(SIT.BDDATAPARTOSIT, SIT.BDDATAINISEFIP))) in ('||prlistaanos||'))'||
            ') order by ANO, DATAINICIO';


  for execute statement wsql
  into :ANO, :DATAINICIO, :DATAFIM, :SUSPENSAO, :PERCREDUCAO, :DIASREDSUSP, :BDDIASACORDOINI
  do
    suspend;
end^

CREATE OR ALTER TRIGGER VRHF_EMP_TFCTPENSAO_DEP_BI0 FOR VRHF_EMP_TFCTPENSAO_DEP
ACTIVE BEFORE INSERT POSITION 0
AS
begin
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFCTPENSAO_DEP_BI0 FOR VRHF_EMP_TFCTPENSAO_DEP
ACTIVE BEFORE INSERT POSITION 0
AS
declare variable wcodigopk Integer;
begin
  /* Trigger text */
  Select max(bdcodigopk) bdcodigopk  from VRHF_EMP_TFCTPENSAO_DEP where (BDCODEMP = new.bdcodemp) and
      (BDORDEM = new.bdordem) and
      (BDREFTOMADOR = new.BDREFTOMADOR) and
      (BDCODCOL = new.BDCODCOL) and
      (BDCODBENEF = new.BDCODBENEF) and
      (BDREFFC = new.BDREFFC) into :wcodigopk;
  if (coalesce(wcodigopk,0)<>0) then
     begin
      new.bdcodigopk = :wcodigopk +1;
     end
end
^



/* Trigger: TOL_VEF_EMP_TDIMEGERREGESP_BI0 */
CREATE OR ALTER trigger tol_vef_emp_tdimegerregesp_bi0 for tol_vef_emp_tdimegerregesp
active before insert position 0
AS
  DECLARE VARIABLE WCHAVE INTEGER;
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((new.bdchavelan is null)  or (new.bdchavelan = 0) )  then
    begin
      SELECT Max(BDORDEMREGESP)+1 FROM VEF_EMP_TDIMEGERREGESP INTO :WCHAVE;
      New.bdchavelan = :WCHAVE;
    end
  end
end^

CREATE OR ALTER TRIGGER VRH_EMP_TACCONV_PARC_BI0 FOR VRH_EMP_TACCONV_PARC
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;
begin
  if ((NEW.bdparcela IS NULL) OR (NEW.bdparcela = 0)) then
     begin
       select coalesce(max(bdparcela) + 1, 1) from VRH_EMP_TACCONV_PARC where BDCODEMP = new.bdcodemp and BDCODACCONV = new.bdcodacconv into :vcod;
       new.bdparcela = :vcod;
     end
end^

CREATE OR ALTER TRIGGER VRH_EMP_TACCONV_ADV_BI0 FOR VRH_EMP_TACCONV_ADV
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcod INTEGER;
begin
  if ((NEW.bdcodigo IS NULL) OR (NEW.bdcodigo = 0)) then
     begin
       select coalesce(max(bdcodigo) + 1, 1) from VRH_EMP_TACCONV_ADV where BDCODEMP = new.bdcodemp and BDCODACCONV = new.bdcodacconv into :vcod;
       new.bdcodigo = :vcod;
     end
end^

--#183582 - Anexar protocolo assinado - Julio Cesar 12/09/2023
CREATE OR ALTER TRIGGER VCT_EMPRESA_PROTOSAIDAFILE_BI0 FOR VCT_EMPRESA_PROTOCOLOSAIDAFILE
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcodigo integer;
begin
  if ((new.bdid is null) or (new.bdid = 0)) then
  begin
    select first 1 bdid from VCT_EMPRESA_PROTOCOLOSAIDAFILE
    where bdcodemp = new.bdcodemp
    and bdcodpts = new.bdcodpts
    order by bdid desc
    into :vcodigo;
    new.bdid = coalesce(:vcodigo,0)+1;
  end
end
^

--#183582 - Anexar protocolo assinado - Julio Cesar 12/09/2023
CREATE OR ALTER TRIGGER VCT_EMPRESA_PROTOENTRAFILE_BI0 FOR VCT_EMPRESA_PROTOCOLOENTRAFILE
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcodigo integer;
begin
  if ((new.bdid is null) or (new.bdid = 0)) then
  begin
    select first 1 bdid from VCT_EMPRESA_PROTOCOLOENTRAFILE
    where bdcodemp = new.bdcodemp
    and bdcodpte = new.bdcodpte
    order by bdid desc
    into :vcodigo;
    new.bdid = coalesce(:vcodigo,0)+1;
  end
end
^

/* Restore proc. body: SP_VRH_PREV_CONTRATO_EXP */
create or alter procedure SP_VRH_PREV_CONTRATO_EXP (
    PRTEMEMP smallint,
    PRFILTROATIVOS smallint,
    PRDATAINI date,
    PRDATAFIM date,
    PRCOMCC smallint = 0,
    PRMODELO smallint = 0,
    PRCODEMP varchar(20) = '')
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDDATAFIMPRAZO1COL date,
    BDDIASPRAZO1COL integer,
    BDDATAFIMPRAZO2COL date,
    BDDIASPRAZO2COL integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDNOMCC DM_BDNOMEMP,
    BDCODSINTRAB integer)
as
declare variable WSQL varchar(10000);
declare variable WWHERE varchar(10000);
declare variable WREF integer;
declare variable WCODEMP integer;
declare variable WNOMEMP DM_BDNOMEMP;
declare variable WSQLTEMP varchar(1000);
declare variable WCODEMPATU integer;
declare variable WCODCOLATU integer;
declare variable WENTROU boolean;
begin
  prfiltroativos = coalesce(prfiltroativos, 0);
  wref = cast((substring(cast(prdatafim as varchar(10)) from 1 for 4)||substring(cast(prdatafim as varchar(10)) from 6 for 2)) as integer);
  prmodelo = coalesce(prmodelo, 0);
  prcomcc = coalesce(prcomcc, 0);
  prtememp = coalesce(prtememp, 0);
  wentrou = false;

  wsqltemp = 'select col.bdcodemp, col.bdcodcol from VRH_EMP_TCOLCON COL ' ||
             'join TMP_EMPRESAS_SELECT EF on (EF.BDCODEMP = COL.BDCODEMP) '||
             'join TEMP_FILTRO_COLCON_REL REL on (REL.BDCODEMP = COL.BDCODEMP and REL.BDCODCOL = COL.BDCODCOL)';
  for execute statement wsqltemp into :wcodempatu, :wcodcolatu do
  begin
    execute statement 'select * from SP_PRAZO_EXPERIENCIA_SITUACAO(''BDCODEMP = '||cast(:wcodempatu as varchar(16))||''',''BDCODCOL = '|| cast(:wcodcolatu as varchar(16)) ||''', null, null, '''||cast(:prdatafim as varchar(10))||''', 0, 1)';
    wentrou = true;
  end

  if (wentrou) then
    execute statement 'select * from SP_PRAZO_EXPERIENCIA_SITUACAO('''||prcodemp||''', null, null, null,'''||cast(:prdatafim as varchar(10))||''', 0, 1)';

  wsql = 'select COL.BDCODEMP, COL.BDCODCOL, COL.BDDATAADMCOL, ADM.BDDIASPRAZO1COL, ADM.BDDIASPRAZO2COL, coalesce(FILTRO.BDDATAFIMPRAZO1COL, ADM.BDDATAFIMPRAZO1COL), coalesce(FILTRO.BDDATAFIMPRAZO2COL, ADM.BDDATAFIMPRAZO2COL) '||
         'from VRH_EMP_TCOLCON COL ';

  wsql = wsql||'join TMP_EMPRESAS_SELECT EF on (EF.BDCODEMP = COL.BDCODEMP) ';

  if (prtememp > 0) then
     wsql = wsql||'join TEMP_FILTRO_COLCON_REL REL on (REL.BDCODEMP = COL.BDCODEMP and REL.BDCODCOL = COL.BDCODCOL) ';

  -- Aplica filtro somente ativos sem demitidos no mês
  if (prfiltroativos = 5) then /* 190866 LuizCovre 23/11/2023 */
     wsql = wsql||'join SP_ATIVOS_SEM_DEMITIDOS_MES('''||cast(prdataini as varchar(10))||''','''||cast(prdatafim as varchar(10))||''') FL on (FL.BDCODEMP = COL.BDCODEMP and FL.BDCODCOL = COL.BDCODCOL) ';
  else
  -- Aplica filtro ativos sem demitidos com transferidos
  if (prfiltroativos = 6) then
     wsql = wsql||'join SP_ATI_SEM_DEM_COM_TRANSF('''||cast(prdataini as varchar(10))||''','''||cast(prdatafim as varchar(10))||''', null, 1) FL on (FL.BDCODEMP = COL.BDCODEMP and FL.BDCODCOL = COL.BDCODCOL) ';
  else
  -- Aplica filtro ativos sem afastados o mês inteiro
  if (prfiltroativos = 7) then
     wsql = wsql||'join SP_ATI_SEM_AFAST_MES_INT('''||cast(prdataini as varchar(10))||''','''||cast(prdatafim as varchar(10))||''', 1) FL on (FL.BDCODEMP = COL.BDCODEMP and FL.BDCODCOL = COL.BDCODCOL) ';
  else
  -- Aplica filtro afastados o mês inteiro
  if (prfiltroativos = 8) then
     wsql = wsql||'join SP_AFASTADOS_MES_INTEIRO('''||cast(prdataini as varchar(10))||''','''||cast(prdatafim as varchar(10))||''', 1) FL on (FL.BDCODEMP = COL.BDCODEMP and FL.BDCODCOL = COL.BDCODCOL) ';


  wsql = wsql||
         'left outer join TEMP_PRAZO_EXP_COL FILTRO on (FILTRO.BDCODEMP = COL.BDCODEMP and FILTRO.BDCODCOL = COL.BDCODCOL) '||
         'left outer join VRH_EMP_TCOL_ADM ADM on (ADM.BDCODEMP = COL.BDCODEMP and ADM.BDCODCOL = COL.BDCODCOL) ';

  -- Somente ativos, Somente demitidos, Somente demitidos no mês, Ativos sem demitidos no mês
  if (prfiltroativos in (0, 2, 4, 5)) then
     wsql = wsql||'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = COL.BDCODEMP and RESC.BDCODCOL = COL.BDCODCOL) ';


  wwhere = ' where ';

  if (prmodelo = 1) then
     wwhere = wwhere||' (coalesce(FILTRO.BDDATAFIMPRAZO2COL, ADM.BDDATAFIMPRAZO2COL) between '''||cast(prdataini as varchar(10))||''' and '''||cast(prdatafim as varchar(10))||''') ';
  else
  if (prmodelo = 2) then
     wwhere = wwhere||' (coalesce(FILTRO.BDDATAFIMPRAZO1COL, ADM.BDDATAFIMPRAZO1COL) between '''||cast(prdataini as varchar(10))||''' and '''||cast(prdatafim as varchar(10))||''') ';
  else
  if (prmodelo = 3) then
     wwhere = wwhere||' ((coalesce(FILTRO.BDDATAFIMPRAZO1COL, ADM.BDDATAFIMPRAZO1COL) >= '''||cast(prdataini as varchar(10))||''') or (coalesce(FILTRO.BDDATAFIMPRAZO2COL, ADM.BDDATAFIMPRAZO2COL) >= '''||cast(prdataini as varchar(10))||''')) ';
  else
     wwhere = wwhere||' ((coalesce(FILTRO.BDDATAFIMPRAZO1COL, ADM.BDDATAFIMPRAZO1COL) between '''||cast(prdataini as varchar(10))||''' and '''||cast(prdatafim as varchar(10))||''') or '||
                        '(coalesce(FILTRO.BDDATAFIMPRAZO2COL, ADM.BDDATAFIMPRAZO2COL) between '''||cast(prdataini as varchar(10))||''' and '''||cast(prdatafim as varchar(10))||''')) ';

  -- Aplica filtro somente ativos
  if (prfiltroativos = 0) then
     begin
       wwhere = wwhere||' and (COL.BDDATAADMCOL <= '''||cast(prdatafim as varchar(10))||''' '||
                'and ((RESC.BDDATARESCISAO is null) or (RESC.BDDATARESCISAO >= '''||cast(prdataini as varchar(10))||'''))) ';
     end
  else
  -- Aplica filtro somente demitidos
  if (prfiltroativos = 2) then
     begin
       wwhere = wwhere||' and (RESC.BDDATARESCISAO is not null and RESC.BDDATARESCISAO <= '''||cast(prdatafim as varchar(10))||''') ';
     end
  else
  -- Aplica filtro somente admitidos no mês
  if (prfiltroativos = 3) then
     begin
       wwhere = wwhere||' and (COL.BDDATAADMCOL between '''||cast(prdataini as varchar(10))||''' and '''||cast(prdatafim as varchar(10))||''') ';
     end
  else
  -- Aplica filtro somente demitidos no mês
  if (prfiltroativos = 4) then
     begin
       wwhere = wwhere||' and (RESC.BDDATARESCISAO between '''||cast(prdataini as varchar(10))||''' and '''||cast(prdatafim as varchar(10))||''') ';
     end

  wcodemp = 0;

  for execute statement wsql||wwhere
  into :BDCODEMP, :BDCODCOL, :BDDATAADMCOL, :BDDIASPRAZO1COL, :BDDIASPRAZO2COL, :BDDATAFIMPRAZO1COL, :BDDATAFIMPRAZO2COL
  do
    begin
      select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :wref order by BDREFCOL desc into :BDNOMCOL;

      select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :wref order by BDREFCOL desc into :BDCODSINTRAB;

      BDCODCENTRO = null;
      BDCODTPCC   = null;
      BDNOMCC     = null;

      if (prcomcc > 0) then
         begin
           select first 1 CC.BDCODCENTRO, CC.BDCODTPCC, CCX.BDNOMCTA from SP_VRH_CC_DATA(:BDCODEMP, :BDCODCOL, :prdatafim) CC
           left outer join CENTROS_TPCC CCX on (CC.BDCODCENTRO = CCX.BDCODCENTRO and CC.BDCODTPCC = CCX.BDCODTPCC)
           into :BDCODCENTRO, :BDCODTPCC, :BDNOMCC;

           if (BDCODTPCC is null) then
              begin
                if (wcodemp <> BDCODEMP) then
                   begin
                     select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :wref order by BDREFEMP desc into :wnomemp;
                     wcodemp = BDCODEMP;
                   end
                BDNOMCC = '(Empresa) '||wnomemp;
              end
           else
              begin
                BDNOMCC = BDCODTPCC||' - '||coalesce(BDNOMCC, '');
              end
         end
      suspend;
    end
end^

--#183264 - Ajuste sobre erro de PK dos generators - Gabriel Berlanda 29/09/2023
CREATE OR ALTER TRIGGER TTABELAS_LOG_BI0 FOR TTABELAS_LOG
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
    NEW.BDCODTABLOG = Gen_Id(gen_ttabelas_log,1);
END^

-- Augusto - #185637 - Criando nova tabela para criação de Seleções de Processos/Atividades no F11
CREATE OR ALTER trigger ttela_selsis_bi0 for ttela_selsis
active before insert position 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM TTELA_SELECOESIS order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0);
  end
END^

CREATE OR ALTER trigger ttela_selrelcons_bi0 for ttela_selrelcons
active before insert position 0
AS
  declare variable vCodigo integer;
begin
  if ((new.bdcodigosel is null) or (new.bdcodigosel = 0)) then
  begin
    select max(bdcodigosel) from ttela_selrelcons into :vcodigo;
    new.bdcodigosel = vcodigo + 1;
  end
  else
  begin
    select bdcodigosel from ttela_selrelcons where bdcodigosel = :vcodigo into :vcodigo;
    if (vcodigo is not null) then
    begin
      select max(bdcodigosel) from ttela_selrelcons into :vcodigo;
      new.bdcodigosel = vcodigo + 1;
    end
  end
end^

CREATE OR ALTER trigger ttela_selrelconsitem_bi0 for ttela_selrelconsitem
active before insert position 0
AS
  declare variable vcodigo integer;
begin
  if (new.bdcodigosel is null) then
  begin
    select max(bdcodigosel) from ttela_selrelcons into :vcodigo;
    new.bdcodigosel = :vcodigo;
  end

  if (new.bdordem is null) then
  begin
    select max(bdordem) from ttela_selrelconsitem where bdcodigosel = new.bdcodigosel into :vcodigo;
    new.bdordem = coalesce(vcodigo, 0) + 1;
  end
end^

CREATE OR ALTER trigger ttela_selecoesis_bi0 for ttela_selecoesis
active before insert position 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM TTELA_SELECOESIS order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0) + 1;
  end
END^


CREATE OR ALTER trigger ttela_selatividade_bi0 for ttela_selatividade
active before insert position 0
AS
  DECLARE VARIABLE VNOVOCOD INTEGER;

BEGIN
  IF (COALESCE(NEW.BDCODIGOSEL, 0) = 0) THEN
  BEGIN
    SELECT FIRST 1 BDCODIGOSEL FROM TTELA_SELECOEATIVIDADE ORDER BY BDCODIGOSEL DESC INTO :VNOVOCOD;
    NEW.BDCODIGOSEL = COALESCE(VNOVOCOD, 0);
  END
END^

CREATE OR ALTER trigger ttela_selecoeatividade_bi0 for ttela_selecoeatividade
active before insert position 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM TTELA_SELECOEATIVIDADE order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0) + 1;
  end
END^

/* Augusto - 16/10/2023 - #185637 - seleçao de f11 para colaboradores  */ 
CREATE OR ALTER TRIGGER TTELA_SELECOECOLCON_BI0 FOR TTELA_SELECOECOLCON
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM ttela_selecoecolcon order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0) + 1;
  end
END^

CREATE OR ALTER TRIGGER TTELA_SELCOLCON_BI0 FOR TTELA_SELCOLCON
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE VNOVOCOD INTEGER;

BEGIN
  IF (COALESCE(NEW.BDCODIGOSEL, 0) = 0) THEN
  BEGIN
    SELECT FIRST 1 BDCODIGOSEL FROM TTELA_SELECOECOLCON ORDER BY BDCODIGOSEL DESC INTO :VNOVOCOD;
    NEW.BDCODIGOSEL = COALESCE(VNOVOCOD, 0);
  END
END^

/* Augusto - 22/12/2023 - #191012 - seleçao de f11 para módulos  */
CREATE OR ALTER TRIGGER TTELA_SELECOEMODULO_BI0 FOR TTELA_SELECOEMODULO
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM ttela_selecoemodulo order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0) + 1;
  end
END^

 CREATE OR ALTER TRIGGER TTELA_SELMODULO_BI0 FOR TTELA_SELMODULO
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE VNOVOCOD INTEGER;

BEGIN
  IF (COALESCE(NEW.BDCODIGOSEL, 0) = 0) THEN
  BEGIN
    SELECT FIRST 1 BDCODIGOSEL FROM ttela_selecoemodulo ORDER BY BDCODIGOSEL DESC INTO :VNOVOCOD;
    NEW.BDCODIGOSEL = COALESCE(VNOVOCOD, 0);
  END
END^

/* Restore proc. body: SP_VRH_RECLAMA_CONTRATO */
create or alter procedure SP_VRH_RECLAMA_CONTRATO (
    PREMPRESA integer,
    PRCHAVE integer)
returns (
    BDCODEMP integer,
    BDCODVINC integer,
    BDCODCOL integer,
    BDDATAADMCOL date,
    BDMATRICULA varchar(30) collate WIN_PTBR,
    BDCATEGORIAESOCIAL integer,
    BDCODCBO integer,
    BDNATATIV integer,
    BDREGTRAB integer,
    BDREGPREV integer,
    BDDURACAOCONTRATO integer,
    BDDATATERMINO date,
    BDTIPOCONTRPARC integer,
    BDOSERVACAO varchar(300) collate WIN_PTBR)
as
declare variable WCOLVINC integer;
declare variable WMATRIC varchar(30) collate WIN_PTBR;
declare variable WMATRIC2 varchar(30) collate WIN_PTBR;
declare variable WCONTRCOL integer;
declare variable WPLAFUC integer;
declare variable WTFUC integer;
declare variable WVINCEMP integer;
begin
  for select BDCODEMP, BDCODVINC, BDCODCOLVINC
      from VRH_EMP_TRECLAMATORIA_VINC
      where BDCODEMP = :prempresa and BDCHAVE = :prchave
  into
    :BDCODEMP, :BDCODVINC, :wcolvinc
  do
    begin
      if (coalesce(wcolvinc, 0) > 0) then
         begin
           for select BDCODCOL, BDDATAADMCOL, BDMATRICULA, BDMATRICULASEMVINC, BDCONTRCOL
               from VRH_EMP_TCOLCON
               where BDCODEMP = :BDCODEMP and BDCODCOL = :wcolvinc
           into
             :BDCODCOL, :BDDATAADMCOL, :wmatric, :wmatric2, :wcontrcol
           do
             begin
               BDCATEGORIAESOCIAL = null;
               select first 1 BDCATEGORIAESOCIAl, BDREGIMETRAB, BDREGPREV
               from VRHF_EMP_TCOLCON_FGTSGPS
               where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL order by BDREFCOL DESC
               into :BDCATEGORIAESOCIAL, :BDREGTRAB, :BDREGPREV;

               if ((BDCATEGORIAESOCIAL in (901,401)) or (coalesce(wcontrcol, 0) <> 0)) then
                  BDMATRICULA = wmatric2;
               else
                  BDMATRICULA = wmatric;

               BDDURACAOCONTRATO = null;
               select first 1 BDCODTIPOCONTRATO from VRH_EMP_TCOLCON_PARTIDA where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL into :BDDURACAOCONTRATO;

               wplafuc = null;
               wtfuc = null;
               BDCODCBO = null;
               select first 1 BDCODPLAFUC, BDCODTFUC from VRH_EMP_TCOL_VINCDIA where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL order by BDDATACOL DESC into :wplafuc, :wtfuc;
               select first 1 BDCODCBO from VRH_FUNCOES_TFUC where BDCODPLAFUC = :wplafuc and BDCODTFUC = :wtfuc into :BDCODCBO;

               wvincemp = null;
               select first 1 BDVINCEMPCOL from VRH_EMP_TCOL_ADMREF where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL order by BDREFCOL DESC into :wvincemp;

               if (coalesce(wvincemp, 0) in (2, 3, 12, 13)) then
                  BDNATATIV = 2;
               else
                  BDNATATIV = 1;

               BDTIPOCONTRPARC = 0;
               BDOSERVACAO = null;
               BDDATATERMINO = null;

               if (coalesce(BDDURACAOCONTRATO, 0) <> 1) then
                  select first 1 coalesce(BDDATAFIMPRAZO2COL, BDDATAFIMPRAZO1COL) from VRH_EMP_TCOL_ADM where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL into :BDDATATERMINO;

               suspend;
             end
         end
      else
         begin
           BDCODCOL = null;

           for select BDMATRICULA, BDCATEGORIAESOCIAL, BDCODCBO, BDNATATIV, BDREGTRAB, BDREGPREV, BDDATAADMCOL, BDTIPOCONTRPARC, BDDURACAOCONTRATO, BDDATATERMINO, BDOSERVACAO
               from VRH_EMP_TRECLAMA_CONTRATO
               where BDCODEMP = :prempresa and BDCHAVE = :prchave and BDCODVINC = :BDCODVINC
           into
             :BDMATRICULA, :BDCATEGORIAESOCIAL, :BDCODCBO, :BDNATATIV, :BDREGTRAB, :BDREGPREV, :BDDATAADMCOL, :BDTIPOCONTRPARC, :BDDURACAOCONTRATO, :BDDATATERMINO, :BDOSERVACAO
           do
             suspend;
         end
    end

end^

/* Restore proc. body: SP_VRH_RECLAMA_RESC */
create or alter procedure SP_VRH_RECLAMA_RESC (
    PREMPRESA integer,
    PRCHAVE integer)
returns (
    BDCODEMP integer,
    BDCODVINC integer,
    BDCODCOL integer,
    BDCODPRES integer,
    BDDATARESCISAO date,
    BDDATAAVPREV date,
    BDCODMOTESRESC integer,
    BDINDPENALIM integer,
    BDVALFGTSRESC numeric(18,6),
    BDPERFGTSRESC numeric(18,6))
as
declare variable WCOLVINC integer;
begin
  for select BDCODEMP, BDCODVINC, BDCODCOLVINC
      from VRH_EMP_TRECLAMATORIA_VINC
      where BDCODEMP = :prempresa and BDCHAVE = :prchave
  into
    :BDCODEMP, :BDCODVINC, :wcolvinc
  do
    begin
      if (coalesce(wcolvinc, 0) > 0) then
         begin
           for select BDCODCOL, BDCODPRES, BDDATARESCISAO, BDPROJECAOAVISO
               from VRH_EMP_TRESCISAO
               where BDCODEMP = :BDCODEMP and BDCODCOL = :wcolvinc
           into
             :BDCODCOL, :BDCODPRES, :BDDATARESCISAO, :BDDATAAVPREV
           do
             begin
               select first 1 BDCODMOTESRESC from VRH_BASE_TPREPRESC where BDCODPRES = :BDCODPRES into :BDCODMOTESRESC;

               select BDINDPENALIM, BDVALFGTSRESC, BDPERFGTSRESC from VRH_EMP_TRECLAMATORIA_RESC where BDCODEMP = :prempresa and BDCHAVE = :prchave and BDCODVINC = :BDCODVINC
               into :BDINDPENALIM, :BDVALFGTSRESC, :BDPERFGTSRESC;

               suspend;
             end
         end
      else
         begin
           BDCODCOL = null;

           for select BDCODPRES, BDDATARESCISAO, BDDATAAVPREV
               from VRH_EMP_TRECLAMA_RESC
               where BDCODEMP = :prempresa and BDCHAVE = :prchave and BDCODVINC = :BDCODVINC
           into
             :BDCODPRES, :BDDATARESCISAO, :BDDATAAVPREV
           do
             begin
               select first 1 BDCODMOTESRESC from VRH_BASE_TPREPRESC where BDCODPRES = :BDCODPRES into :BDCODMOTESRESC;

               select BDINDPENALIM, BDVALFGTSRESC, BDPERFGTSRESC from VRH_EMP_TRECLAMATORIA_RESC where BDCODEMP = :prempresa and BDCHAVE = :prchave and BDCODVINC = :BDCODVINC
               into :BDINDPENALIM, :BDVALFGTSRESC, :BDPERFGTSRESC;

               suspend;
             end
         end
    end

end^

/* Restory proc. body: SP_VRH_RECLAMATORIA */
create or alter procedure SP_VRH_RECLAMATORIA (
    PREMPRESA integer,
    PRCHAVE integer)
returns (
    BDCODEMP integer,
    BDCHAVE integer,
    BDRESPDIRETO DM_BOOLEAN,
    BDNOMRESPDIRETO DM_BDNOMRESPDIRETO,
    BDCNPJRESPDIRETO DM_CNPJ_CPF,
    BDCODRT integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL DM_CNPJ_CPF,
    BDDATANASCCOL date,
    BDCODCOL integer,
    BDTIPOPROCRT integer,
    BDNUMEROPROCESSO DM_BDNUMPROCJUD,
    BDDATASENTENCA date,
    BDCODCID integer,
    BDCODVARA integer,
    BDDATACONCILIACAO date,
    BDAMBITO integer,
    BDCNPJNINTER DM_CNPJ_CPF,
    BDCODSINTRAB integer,
    BDOBSERVACOES blob sub_type 1 segment size 80,
    BDCODIBGE integer,
    BDSIGLAUF varchar(2),
    BDMATRESPDIRETO varchar(30))
as
declare variable WNOMESOCIAL DM_BOOLEAN;
declare variable WNOMCOL DM_BDNOMCOL;
declare variable WCODUF integer;
begin
  for select BDCODEMP, BDCHAVE, BDRESPDIRETO, BDNOMRESPDIRETO, BDCNPJRESPDIRETO, BDCODRT, BDNOMCOL, BDCPFCOL, BDDATANASCCOL, BDCODCOL, BDMATRESPDIRETO
      from VRH_EMP_TRECLAMATORIA
      where BDCODEMP = :prempresa and BDCHAVE = :prchave
  into
    :BDCODEMP, :BDCHAVE, :BDRESPDIRETO, :BDNOMRESPDIRETO, :BDCNPJRESPDIRETO, :BDCODRT, :BDNOMCOL, :BDCPFCOL, :BDDATANASCCOL, :BDCODCOL, :BDMATRESPDIRETO
  do
    begin
      if (trim(UPPER(coalesce(BDRESPDIRETO, 'FALSE'))) <> 'TRUE') then
         begin
           BDNOMRESPDIRETO = null;
           BDCNPJRESPDIRETO = null;
           BDMATRESPDIRETO = null;
         end

      if (coalesce(BDCODCOL,  0) > 0) then
         begin
           select first 1 BDCPFCOL, BDDATANASCCOL from VRH_EMP_TCOLCON where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL into :BDCPFCOL, :BDDATANASCCOL;
           select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL order by BDREFCOL DESC into :BDNOMCOL;

           wnomesocial = null;
           select first 1 BDUSANOMESOCIAL from VRHF_BASE_TEMPPAR where BDCODEMP = :BDCODEMP order by BDREFEMP DESC into :wnomesocial;

           if (trim(upper(coalesce(wnomesocial, 'FALSE'))) = 'TRUE') then
              begin
                wnomcol = null;
                select first 1 BDNMSOCIAL from VRH_EMP_TCOLCON_FIS where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL order by BDREFCOL DESC into :wnomcol;

                if (trim(coalesce(wnomcol, '')) <> '') then
                   BDNOMCOL = wnomcol;
              end
         end

      select first 1 BDTIPOPROCRT, BDNUMEROPROCESSO, BDDATASENTENCA, BDCODCID, BDCODVARA, BDDATACONCILIACAO, BDAMBITO, BDCNPJNINTER, BDCODSINTRAB, BDOBSERVACOES
      from VRH_BASE_TRECLAMATORIA
      where BDCODRT = :BDCODRT
      into
        :BDTIPOPROCRT, :BDNUMEROPROCESSO, :BDDATASENTENCA, :BDCODCID, :BDCODVARA, :BDDATACONCILIACAO, :BDAMBITO, :BDCNPJNINTER, :BDCODSINTRAB, :BDOBSERVACOES;

      if (coalesce(BDCODSINTRAB, 0) > 0) then
         select first 1 BDCNPJSINTRAB from VRH_BASE_TSINDTRAB where BDCODSINTRAB = :BDCODSINTRAB into :BDCNPJNINTER;

      BDCODIBGE = null;
      BDSIGLAUF = null;
      wcoduf    = null;

      if (coalesce(BDCODCID, 0) > 0) then
         begin

           select first 1 BDCODIBGE, BDCODUF from TCIDADE where BDCODCID = :BDCODCID into :BDCODIBGE, :wcoduf;

           if (coalesce(wcoduf, 0) > 0) then
              select first 1 BDSIGLAUF from TUF where BDCODUF = :wcoduf into :BDSIGLAUF;
         end

      suspend;
    end
end^

/* Restore proc. body: SP_VRH_RECLAMATORIA_DEP */
create or alter procedure SP_VRH_RECLAMATORIA_DEP (
    PREMPRESA integer,
    PRCHAVE integer)
returns (
    BDCODEMP integer,
    BDCHAVE integer,
    BDCODDEP integer,
    BDCPFDEP DM_CNPJ_CPF,
    BDNOMDEP varchar(68) collate WIN_PTBR,
    BDPARENESCODPN integer,
    BDDESCDEP varchar(30) collate WIN_PTBR)
as
declare variable WCOL integer;
declare variable WDEP integer;
declare variable WPARENT integer;
begin
  for select BDCODEMP, BDCHAVE, BDCODCOL
      from VRH_EMP_TRECLAMATORIA
      where BDCODEMP = :prempresa and BDCHAVE = :prchave
  into
    :BDCODEMP, :BDCHAVE, :wcol
  do
    begin
      if (coalesce(wcol, 0) > 0) then
         begin
           BDCODDEP = null;
           BDDESCDEP = null;
           for select BDCODDPN from VRH_EMP_TDEP where BDCODEMP = :BDCODEMP and BDCODCOL = :wcol
           into
             :wdep
           do
             begin
               select first 1 BDCPFDPN, BDPARENESCODPN, BDNOMEDPN from VRH_EMP_TDEP_REF where BDCODEMP = :BDCODEMP and BDCODCOL = :wcol and BDCODDPN = :wdep order by BDREFDPN DESC
               into :BDCPFDEP, :wparent, :BDNOMDEP;

               wparent = coalesce(wparent, 0);

               select first 1 BDCODESOCIAL from VRH_TTIPO_DEP_ESOCIAL where BDCODTIPODEP = :wparent into :BDPARENESCODPN;

               suspend;
             end
         end

      for select BDCODDEP, BDCPFDEP, BDPARENESCODPN, BDNOMDEP, BDDESCDEP
          from VRH_EMP_TRECLAMATORIA_DEP
          where BDCODEMP = :BDCODEMP and BDCHAVE = :BDCHAVE
      into
        :BDCODDEP, :BDCPFDEP, :wparent, :BDNOMDEP, :BDDESCDEP
      do
        begin
          wparent = coalesce(wparent, 0);

          select first 1 BDCODESOCIAL from VRH_TTIPO_DEP_ESOCIAL where BDCODTIPODEP = :wparent into :BDPARENESCODPN;

          suspend;
        end
    end
end^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMA_RESC_BI0 FOR VRH_EMP_TRECLAMA_RESC
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wchave INTEGER;
begin
  if (coalesce(new.bdchave, 0) <= 0) then
     begin
       select coalesce(max(BDCHAVE), 1) from VRH_EMP_TRECLAMATORIA where BDCODEMP = new.bdcodemp into :wchave;
       new.bdchave = :wchave;
     end

  if (coalesce(new.bdcodvinc,0) <= 0) then
     begin
       select first 1 x.bdcodvinc from VRH_EMP_TRECLAMATORIA_vinc x
       where x.bdcodemp = new.bdcodemp and x.bdchave = new.bdchave order by x.bdcodvinc desc into wChave;
       new.bdcodvinc = :wChave;
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECL_CONTR_OBS_BI0 FOR VRH_EMP_TRECLAMA_CONTRATO_OBS
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (coalesce(new.bdchave, 0) <= 0) then
     begin
       select coalesce(max(BDCHAVE), 1) from VRH_EMP_TRECLAMATORIA_VINC where BDCODEMP = new.bdcodemp into new.bdchave;
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECL_CONTR_SUC_BI0 FOR VRH_EMP_TRECLAMA_CONTRATO_SUC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (coalesce(new.bdchave, 0) <= 0) then
     begin
       select coalesce(max(BDCHAVE), 1) from VRH_EMP_TRECLAMATORIA where BDCODEMP = new.bdcodemp into new.bdchave;
     end
end
^
CREATE OR ALTER TRIGGER TDIC_ESOCIAL_REL_FIXO_BI0 FOR TDICIONARIO_ESOCIAL_REL_FIXO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (coalesce(new.bdcodigorelfixo, 0) <= 0) then
     select coalesce(max(BDCODIGORELFIXO), 0) + 1 from TDICIONARIO_ESOCIAL_REL_FIXO into new.bdcodigorelfixo;
end
^

CREATE OR ALTER TRIGGER TDIC_ESOCIAL_REL_TAB_BI0 FOR TDICIONARIO_ESOCIAL_REL_TAB
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (coalesce(new.bdcodigoreltab, 0) <= 0) then
     select coalesce(max(BDCODIGORELTAB), 0) + 1 from TDICIONARIO_ESOCIAL_REL_TAB into new.bdcodigoreltab;
end
^
/* Restore proc. body: SP_RECLAMATORIA_PGMES */
create or alter procedure SP_RECLAMATORIA_PGMES (
    PREMP integer,
    PRCHAVE integer)
returns (
    BDCODEMP integer,
    BDCHAVE integer,
    BDCODVINC integer,
    BDANOMES integer,
    BDBINSS DM_NUMERIC_18_3,
    BDBINSS13 DM_NUMERIC_18_3,
    BDBFGTSNAODEC DM_NUMERIC_18_3,
    BDBFGTSDECSEFIP DM_NUMERIC_18_3,
    BDOCORRENCIA integer,
    BDBFGTSDECESOCIAL DM_NUMERIC_18_3)
as
declare variable WREFATU integer;
declare variable WREFFIM integer;
begin
  for select BDCODEMP, BDCHAVE, BDCODVINC, BDINIPROC, BDFIMPROC
      from VRH_EMP_TRECLAMATORIA_IDPGTO
      where BDCODEMP = :premp and BDCHAVE = :prchave
      order by BDCODEMP, BDCHAVE, BDCODVINC, BDINIPROC
  into :BDCODEMP, :BDCHAVE, :BDCODVINC, :wrefatu, :wreffim
  do
    begin
      while (wrefatu <= wreffim) do
        begin
          BDANOMES = wrefatu;
          BDBINSS = 0;
          BDBINSS13 = 0;
          BDBFGTSNAODEC = 0;
          BDBFGTSDECSEFIP = 0;
          BDBFGTSDECESOCIAL = 0;
          BDOCORRENCIA = 0;

--          select first 1 BDBINSS, BDBINSS13, BDBFGTS, BDBFGTS13, BDOCORRENCIA
          select first 1 BDBINSS, BDBINSS13, BDBFGTSNAODEC, BDBFGTSDECSEFIP, BDBFGTSDECESOCIAL, BDOCORRENCIA
          from VRH_EMP_TRECLAMATORIA_PGMES
          where BDCODEMP = :BDCODEMP and BDCHAVE = :BDCHAVE and BDCODVINC = :BDCODVINC and BDANOMES = :wrefatu
          into :BDBINSS, :BDBINSS13, :BDBFGTSNAODEC, :BDBFGTSDECSEFIP, :BDBFGTSDECESOCIAL, :BDOCORRENCIA;

          suspend;

          if (substring(wrefatu from 5 for 2) = '12') then
             wrefatu = cast((cast(substring(wrefatu from 1 for 4) as integer) + 1) as varchar(4))||'01';
          else
             wrefatu = cast((substring(wrefatu from 1 for 4)||lpad(cast(substring(wrefatu from 5 for 2) as integer) + 1, 2, '0')) as integer);
        end
    end
end^

/* Trigger: TARQUIVAMENTO_JOB_BI0 */
CREATE OR ALTER TRIGGER TARQUIVAMENTO_JOB_BI0 FOR TARQUIVAMENTO_JOB
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  /* Trigger text */
  if (new.bdordem is null) then
  begin
    select max(bdORDEM) from TARQUIVAMENTO_JOB into new.bdordem;
    if (new.bdordem is null) then
    begin
      new.bdordem = 0;
    end

    new.bdordem = new.bdordem + 1;
  end
end
^

CREATE OR ALTER procedure SP_VRHF_EMP_TCOLCON_MVINC_RFIM (
    PREMP varchar(32700),
    PRCOL varchar(32000),
    PRREF integer,
    PRREFFIM integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDBASEINSSNCOL numeric(18,6),
    BDBASEINSS13COL numeric(18,6))
as
declare variable WBASEINSSNCOL numeric(18,6);
declare variable WBASEINSS13COL numeric(18,6);
declare variable WDATEATU integer;
begin
wdateatu = PRREF;
while (wdateatu<=PRREFFIM) do
  begin
    select coalesce(bdbaseinssncol,0),coalesce(bdbaseinss13col,0) from SP_VRHF_EMP_TCOLCON_MVINC(:PREMP,:PRCOL,:PRREF) into :wbaseinssncol,:wbaseinss13col;
    BDBASEINSSNCOL = BDBASEINSSNCOL +:wbaseinssncol;
    BDBASEINSS13COL = BDBASEINSS13COL + :wbaseinss13col;
    select bdreferencia from inc_referencia(:wdateatu) into :wdateatu;
  end
  Suspend;
end^

CREATE OR ALTER TRIGGER VRHF_EMP_TADSALPENSAO_DEP_BIU0 FOR VRHF_EMP_TADSALPENSAO_DEP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  new.BDREFCALCPEN = cast((substring(cast(new.bddataad as varchar(10)) from 1 for 4)||substring(cast(new.bddataad as varchar(10)) from 6 for 2)) as integer);
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFEPENSAO_DEP_BIU0 FOR VRHF_EMP_TFEPENSAO_DEP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
  declare variable wdatafer DATE;
  declare variable wrefabo INTEGER;
begin
  select BDINIPERGOZOFE, BDREFPAGABOFE
  from VRH_EMP_TFERIAS
  where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDINIPERAQUISFE = new.bdiniperaquisfe and BDCODFE = new.bdcodfe
  into :wdatafer, :wrefabo;

  if (wdatafer is not null) then
     new.BDREFCALCPEN = cast((substring(cast(wdatafer as varchar(10)) from 1 for 4)||substring(cast(wdatafer as varchar(10)) from 6 for 2)) as integer);
  else
     new.BDREFCALCPEN = wrefabo;

end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFAPENSAO_DEP_BIU0 FOR VRHF_EMP_TFAPENSAO_DEP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  new.BDREFCALCPEN = cast((substring(cast(new.bddatafa as varchar(10)) from 1 for 4)||substring(cast(new.bddatafa as varchar(10)) from 6 for 2)) as integer);
end
^

/* Restore proc. body: SP_VRHF_PENSAO_MES */
create or alter procedure SP_VRHF_PENSAO_MES (
    PRREFINI integer,
    PRREFFIM integer,
    PRTEMEMP smallint,
    PRFN smallint = 0,
    PRADSAL smallint = 0,
    PRFER smallint = 0,
    PRAD13 smallint = 0,
    PR13SAL smallint = 0,
    PRC13 smallint = 0,
    PRFA smallint = 0,
    PRFC smallint = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODDPN integer,
    BDREF integer,
    BDREFPAGTO integer,
    BDTIPO integer,
    BDCODVER integer,
    BDDESCVER varchar(40),
    BDNOMBENEF varchar(70),
    BDCPFBENEF varchar(14),
    BDCTACORRETE varchar(15),
    BDDCTACORRETE varchar(2),
    BDCODBAN integer,
    BDCODAG integer,
    BDDATANASCBENEF date,
    BDNOMAG varchar(40),
    BDNOMBAN varchar(60),
    BDCODAGBAN varchar(5),
    BDCODAGBANDV varchar(2),
    BDVALPENSAO numeric(18,6),
    BDNOMBENEFUPPER varchar(70),
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDDATARESCISAO date,
    BDCPFCOL varchar(14),
    BDCODFEBRABAN varchar(4))
as
declare variable WSQL varchar(32000);
declare variable WCODFEBRABAN integer;
begin
  wsql = '';


  if (coalesce(prfn, 0) > 0) then
     begin
       /* FOLHA NORMAL */

       wsql = 'select 0 as BDTIPO, P.BDCODEMP, P.BDCODCOL, P.BDCODDPN as BDCODBENEF, P.BDREFFN as BDREF, P.BDCODVER, P.BDREFPAGPEND, P.BDVALPEND '||
              'from VRHF_EMP_TFNPENSAO_DEP P '||
              'join TMP_EMPRESAS_SELECT ES on (ES.BDCODEMP = P.BDCODEMP) ';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||'join TEMP_FILTRO_COLCON_REL FR on (FR.BDCODEMP = P.BDCODEMP and FR.BDCODCOL = P.BDCODCOL) ';

       wsql = wsql||
              'where P.BDREFFN between '||:prrefini||' and '||:prreffim;

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||' and FR.BDCOMP = ''EDCODCOLCON'' ';


       /* FOLHA CONTRATO INTERMITENTE NORMAL */
       wsql = wsql||' union all ';
       wsql = wsql||
              'select 0, P.BDCODEMP, P.BDCODCOL, P.BDCODBENEF, P.BDREFFN, P.BDCODVER, P.BDREFPAGPEND, P.BDVALPEND '||
              'from VRHF_EMP_TINTPENSAO_DEP P '||
              'join TMP_EMPRESAS_SELECT ES on (ES.BDCODEMP = P.BDCODEMP) ';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||'join TEMP_FILTRO_COLCON_REL FR on (FR.BDCODEMP = P.BDCODEMP and FR.BDCODCOL = P.BDCODCOL) ';

       wsql = wsql||
              'where P.BDREFFN between '||:prrefini||' and '||:prreffim;

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||' and FR.BDCOMP = ''EDCODCOLCON'' ';


       /* FOLHA POR TOMADOR */
       wsql = wsql||' union all ';
       wsql = wsql||
              'select 0, P.BDCODEMP, P.BDCODCOL, P.BDCODDPN, P.BDREFTOMADOR, P.BDCODVER, P.BDREFPAGPEND, P.BDVALPEND '||
              'from VRHF_EMP_TFTPENSAO_DEP P '||
              'join TMP_EMPRESAS_SELECT ES on (ES.BDCODEMP = P.BDCODEMP) ';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||'join TEMP_FILTRO_COLCON_REL FR on (FR.BDCODEMP = P.BDCODEMP and FR.BDCODCOL = P.BDCODCOL) ';

       wsql = wsql||
              'where P.BDREFTOMADOR between '||:prrefini||' and '||:prreffim;

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||' and FR.BDCOMP = ''EDCODCOLCON'' ';

       /* FOLHA CONTRATO INTERMITENTE POR TOMADOR */
       wsql = wsql||' union all ';
       wsql = wsql||
              'select 0, P.BDCODEMP, P.BDCODCOL, P.BDCODBENEF, P.BDREFTOMADOR, P.BDCODVER, P.BDREFPAGPEND, P.BDVALPEND '||
              'from VRHF_EMP_TTOMINTPENSAO_DEP P '||
              'join TMP_EMPRESAS_SELECT ES on (ES.BDCODEMP = P.BDCODEMP) ';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||'join TEMP_FILTRO_COLCON_REL FR on (FR.BDCODEMP = P.BDCODEMP and FR.BDCODCOL = P.BDCODCOL) ';

       wsql = wsql||
              'where P.BDREFTOMADOR between '||:prrefini||' and '||:prreffim;

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||' and FR.BDCOMP = ''EDCODCOLCON'' ';
     end

  if (coalesce(pradsal, 0) > 0) then
     begin
       /* ADIANTAMENTO SALARIAL */
       if (wsql <> '') then
          wsql = wsql||' union all ';

       wsql = wsql||
              'select 1 as BDTIPO, P.BDCODEMP, P.BDCODCOL, P.BDCODDPN as BDCODBENEF, P.BDREFCALCPEN as BDREF, P.BDCODVER, P.BDREFPAGPEND, P.BDVALPEND '||
              'from VRHF_EMP_TADSALPENSAO_DEP P '||
              'join TMP_EMPRESAS_SELECT ES on (ES.BDCODEMP = P.BDCODEMP) ';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||'join TEMP_FILTRO_COLCON_REL FR on (FR.BDCODEMP = P.BDCODEMP and FR.BDCODCOL = P.BDCODCOL) ';

       wsql = wsql||
              'where P.BDREFCALCPEN between '||:prrefini||' and '||:prreffim;

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||' and FR.BDCOMP = ''EDCODCOLCON'' ';
     end


  if (coalesce(prfer, 0) > 0) then
     begin
       /* FÉRIAS */
       if (wsql <> '') then
          wsql = wsql||' union all ';

       wsql = wsql||
              'select 2 as BDTIPO, P.BDCODEMP, P.BDCODCOL, P.BDCODBENEF, P.BDREFCALCPEN as BDREF, P.BDCODVER, P.BDREFPAGPEND, P.BDVALPEND '||
              'from VRHF_EMP_TFEPENSAO_DEP P '||
              'join TMP_EMPRESAS_SELECT ES on (ES.BDCODEMP = P.BDCODEMP) ';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||'join TEMP_FILTRO_COLCON_REL FR on (FR.BDCODEMP = P.BDCODEMP and FR.BDCODCOL = P.BDCODCOL) ';

       wsql = wsql||
              'where P.BDREFCALCPEN between '||:prrefini||' and '||:prreffim;

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||' and FR.BDCOMP = ''EDCODCOLCON'' ';
     end

  if (coalesce(prad13, 0) > 0) then
     begin
       /* ADIANTAMENTO DE 13º SALÁRIO */
       if (wsql <> '') then
          wsql = wsql||' union all ';

       wsql = wsql||
              'select 3 as BDTIPO, P.BDCODEMP, P.BDCODCOL, P.BDCODDPN as BDCODBENEF, P.BDREFA13 as BDREF, P.BDCODVER, P.BDREFPAGPEND, P.BDVALPEND '||
              'from VRHF_EMP_TA13PENSAO_DEP P '||
              'join TMP_EMPRESAS_SELECT ES on (ES.BDCODEMP = P.BDCODEMP) ';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||'join TEMP_FILTRO_COLCON_REL FR on (FR.BDCODEMP = P.BDCODEMP and FR.BDCODCOL = P.BDCODCOL) ';

       wsql = wsql||
              'where P.BDREFA13 between '||:prrefini||' and '||:prreffim;

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||' and FR.BDCOMP = ''EDCODCOLCON'' ';

     end

  if (coalesce(pr13sal, 0) > 0) then
     begin
       /* 13º SALÁRIO */
       if (wsql <> '') then
          wsql = wsql||' union all ';

       wsql = wsql||
              'select 4 as BDTIPO, P.BDCODEMP, P.BDCODCOL, P.BDCODDPN as BDCODBENEF, P.BDREF13 as BDREF, P.BDCODVER, P.BDREFPAGPEND, P.BDVALPEND '||
              'from VRHF_EMP_T13PENSAO_DEP P '||
              'join TMP_EMPRESAS_SELECT ES on (ES.BDCODEMP = P.BDCODEMP) ';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||'join TEMP_FILTRO_COLCON_REL FR on (FR.BDCODEMP = P.BDCODEMP and FR.BDCODCOL = P.BDCODCOL) ';

       wsql = wsql||
              'where P.BDREF13 between '||:prrefini||' and '||:prreffim;

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||' and FR.BDCOMP = ''EDCODCOLCON'' ';
     end

  if (coalesce(prc13, 0) > 0) then
     begin
       /* COMPLEMENTO DE 13º SALÁRIO */
       if (wsql <> '') then
          wsql = wsql||' union all ';

       wsql = wsql||
              'select 5 as BDTIPO, P.BDCODEMP, P.BDCODCOL, P.BDCODBENEF, P.BDREFC13 as BDREF, P.BDCODVER, P.BDREFPAGPEND, P.BDVALPEND '||
              'from VRHF_EMP_TC13PENSAO_DEP P '||
              'join TMP_EMPRESAS_SELECT ES on (ES.BDCODEMP = P.BDCODEMP) ';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||'join TEMP_FILTRO_COLCON_REL FR on (FR.BDCODEMP = P.BDCODEMP and FR.BDCODCOL = P.BDCODCOL) ';

       wsql = wsql||
              'where P.BDREFC13 between '||:prrefini||' and '||:prreffim;

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||' and FR.BDCOMP = ''EDCODCOLCON'' ';

     end

  if (coalesce(prfa, 0) > 0) then
     begin
       /* FOLHA AVULSA */
       if (wsql <> '') then
          wsql = wsql||' union all ';

       wsql = wsql||
              'select 7 as BDTIPO, P.BDCODEMP, P.BDCODCOL, P.BDCODDPN as BDCODBENEF, P.BDREFCALCPEN as BDREF, P.BDCODVER, P.BDREFPAGPEND, P.BDVALPEND '||
              'from VRHF_EMP_TFAPENSAO_DEP P '||
              'join TMP_EMPRESAS_SELECT ES on (ES.BDCODEMP = P.BDCODEMP) ';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||'join TEMP_FILTRO_COLCON_REL FR on (FR.BDCODEMP = P.BDCODEMP and FR.BDCODCOL = P.BDCODCOL) ';

       wsql = wsql||
              'where P.BDREFCALCPEN between '||:prrefini||' and '||:prreffim;

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||' and FR.BDCOMP = ''EDCODCOLCON'' ';
     end



  if (coalesce(prfc, 0) > 0) then
     begin
       /* FOLHA COMPLEMENTAR NORMAL */
       if (wsql <> '') then
          wsql = wsql||' union all ';

       wsql = wsql||
              'select 8 as BDTIPO, P.BDCODEMP, P.BDCODCOL, P.BDCODBENEF, substring(P.BDREFFC from 1 for 6) as BDREF, P.BDCODVER, P.BDREFPAGPEND, P.BDVALPEND '||
              'from VRHF_EMP_TFCPENSAO_DEP P '||
              'join TMP_EMPRESAS_SELECT ES on (ES.BDCODEMP = P.BDCODEMP) ';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||'join TEMP_FILTRO_COLCON_REL FR on (FR.BDCODEMP = P.BDCODEMP and FR.BDCODCOL = P.BDCODCOL) ';

       wsql = wsql||
              'where P.BDREFFC between '||:prrefini||'01 and '||:prreffim||'99';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||' and FR.BDCOMP = ''EDCODCOLCON'' ';


       /* FOLHA COMPLEMENTAR CONTRATO INTERMITENTE NORMAL */
       wsql = wsql||' union all ';
       wsql = wsql||
              'select 8, P.BDCODEMP, P.BDCODCOL, P.BDCODBENEF, substring(P.BDREFFC from 1 for 6), P.BDCODVER, P.BDREFPAGPEND, P.BDVALPEND '||
              'from VRHF_EMP_TFCINTPENSAO_DEP P '||
              'join TMP_EMPRESAS_SELECT ES on (ES.BDCODEMP = P.BDCODEMP) ';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||'join TEMP_FILTRO_COLCON_REL FR on (FR.BDCODEMP = P.BDCODEMP and FR.BDCODCOL = P.BDCODCOL) ';

       wsql = wsql||
              'where P.BDREFFC between '||:prrefini||'01 and '||:prreffim||'99';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||' and FR.BDCOMP = ''EDCODCOLCON'' ';


       /* FOLHA COMPLEMENTAR POR TOMADOR */
       wsql = wsql||' union all ';
       wsql = wsql||
              'select 8, P.BDCODEMP, P.BDCODCOL, P.BDCODBENEF, substring(P.BDREFFC from 1 for 6), P.BDCODVER, P.BDREFPAGPEND, P.BDVALPEND '||
              'from VRHF_EMP_TFCTPENSAO_DEP P '||
              'join TMP_EMPRESAS_SELECT ES on (ES.BDCODEMP = P.BDCODEMP) ';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||'join TEMP_FILTRO_COLCON_REL FR on (FR.BDCODEMP = P.BDCODEMP and FR.BDCODCOL = P.BDCODCOL) ';

       wsql = wsql||
              'where P.BDREFFC between '||:prrefini||'01 and '||:prreffim||'99';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||' and FR.BDCOMP = ''EDCODCOLCON'' ';

       /* FOLHA CONTRATO INTERMITENTE POR TOMADOR */
       wsql = wsql||' union all ';
       wsql = wsql||
              'select 8, P.BDCODEMP, P.BDCODCOL, P.BDCODBENEF, substring(P.BDREFFC from 1 for 6), P.BDCODVER, P.BDREFPAGPEND, P.BDVALPEND '||
              'from VRHF_EMP_TFCTINTPENSAO_DEP P '||
              'join TMP_EMPRESAS_SELECT ES on (ES.BDCODEMP = P.BDCODEMP) ';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||'join TEMP_FILTRO_COLCON_REL FR on (FR.BDCODEMP = P.BDCODEMP and FR.BDCODCOL = P.BDCODCOL) ';

       wsql = wsql||
              'where P.BDREFFC between '||:prrefini||'01 and '||:prreffim||'99';

       if (coalesce(prtememp, 0) > 0) then
          wsql = wsql||' and FR.BDCOMP = ''EDCODCOLCON'' ';
     end

  if (wsql <> '') then
     begin
       wsql = 'select P.BDTIPO, P.BDCODEMP, P.BDCODCOL, P.BDCODBENEF, P.BDREF, P.BDCODVER, P.BDREFPAGPEND, '||
                     'V.BDDESCVER, B.BDNOMBENEF, B.BDCPFBENEF, B.BDCTACORRETE, B.BDDCTACORRETE, '||
                     'B.BDCODBAN, B.BDCODAG, B.BDDATANASCBENEF, BA.BDNOMAG, BAN.BDNOMBAN, BA.BDCODAGBAN, '||
                     'BA.BDCODAGBANDV, P.BDVALPEND, '||
                     'COL.BDDATAADMCOL, COL.BDCPFCOL, RESC.BDDATARESCISAO, BANF.BDCODFEBRABAN '||
              'from ('||
                  'select P.BDTIPO, P.BDCODEMP, P.BDCODCOL, P.BDCODBENEF, P.BDREF, P.BDCODVER, P.BDREFPAGPEND, SUM(P.BDVALPEND) as BDVALPEND '||
                  'from ('||wsql||') P '||
                  'group by P.BDTIPO, P.BDCODEMP, P.BDCODCOL, P.BDCODBENEF, P.BDREF, P.BDCODVER, P.BDREFPAGPEND '||
              ') P ';

       wsql = wsql||
              'left outer join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = P.BDCODEMP and COL.BDCODCOL = P.BDCODCOL) ';

       wsql = wsql||
              'left outer join VRH_EMP_TCOLCON_BENEF B on (B.BDCODEMP = P.BDCODEMP and B.BDCODCOL = P.BDCODCOL and B.BDCODBENEF = P.BDCODBENEF) ';

       wsql = wsql||
              'left outer join VRH_BASE_TVERBAS V on (V.BDCODVER = P.BDCODVER) ';

       wsql = wsql||
              'left outer join TBANCOS_AG BA on (BA.BDCODBAN = B.BDCODBAN and BA.BDCODAG = B.BDCODAG) ';

       wsql = wsql||
              'left outer join TBANCOS BAN on (BAN.BDCODBAN = B.BDCODBAN) ';

       wsql = wsql||
              'left outer join TBANCOS_FEBRABAN BANF on (BANF.BDCODFEBRABAN = BAN.BDCODFEBRABAN) ';

       wsql = wsql||
              'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = P.BDCODEMP and RESC.BDCODCOL = P.BDCODCOL) ';

       for execute statement wsql
       into :BDTIPO, :BDCODEMP, :BDCODCOL, :BDCODDPN, :BDREF, :BDCODVER, :BDREFPAGTO,
            :BDDESCVER, :BDNOMBENEF, :BDCPFBENEF, :BDCTACORRETE, :BDDCTACORRETE,
            :BDCODBAN, :BDCODAG, :BDDATANASCBENEF, :BDNOMAG, :BDNOMBAN, :BDCODAGBAN,
            :BDCODAGBANDV, :BDVALPENSAO, :BDDATAADMCOL, :BDCPFCOL, :BDDATARESCISAO, :wcodfebraban
       do
         begin
           select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :BDREF order by BDREFCOL desc into :BDNOMCOL;
           BDNOMCOLUPPER = upper(BDNOMCOL);
           BDNOMBENEFUPPER = upper(BDNOMBENEF);
           BDNOMBAN = coalesce(BDNOMBAN, '');
           BDCODAGBAN = coalesce(BDCODAGBAN, '');
           BDCODAGBANDV = coalesce(BDCODAGBANDV, '');

           BDCODFEBRABAN = '';
           if (coalesce(wcodfebraban, 0) > 0) then
              BDCODFEBRABAN = lpad(:wcodfebraban, 3, '0');

           suspend;
         end
     end
end^

CREATE OR ALTER procedure SP_VRH_UPDATE_DATAIRRFESOCIAL (
    PRCODEMP integer,
    PRCHAVE integer)
returns (
    RDATAIRRFESOCIAL date,
    RREFIRRFESOCIAL integer)
as
declare variable WINIPERAQUI date;
declare variable WDATAPAGTO date;
declare variable WDATAIRRFESOCIAL date;
declare variable WREFIRRFESOCIAL integer;
declare variable WCODSERV integer;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WTIPOCAL integer;
declare variable WINTERMITENTE boolean;
declare variable WEMPREGADOR integer;
declare variable WPAGEMP integer;
declare variable WPAGEMPCONTR integer;
declare variable WDATAREF date;
declare variable WEP integer;
declare variable WDIASEMANA integer;
declare variable WFERIADO boolean;
declare variable WCONT integer;
declare variable WDATARESC date;
declare variable WCODFERIAS integer;
declare variable WCODCONTTI integer;
declare variable WDATACALCULO date;
declare variable WPAGOFERIAS boolean;
declare variable WPAGOFNC13 varchar(5);
declare variable WREFFIM integer;
BEGIN

  SELECT DISTINCT CB.BDCODEMP, CASE WHEN CB.BDTIPOCALC = 1 THEN CB.BDCODTER ELSE CB.BDCODCOL END AS CODCOL, CB.BDREFERENCIA, CB.BDTIPOCALC,
                  CASE WHEN CB.BDCODCONTTI IS NULL THEN FALSE ELSE TRUE END AS BDINTERMITENTE, CB.BDCODFER, CB.BDCODCONTTI, CB.BDDATA, CB.BDCODSERV,
                  cb.bdiniperaqui,CB.BDREFERENCIAFIM
  FROM VRHF_EMP_TDADOSCALC_BAIXA CB
  LEFT OUTER JOIN VRHF_EMP_TPGTO_CALC PG ON PG.BDCHAVEPGTO = CB.BDCHAVE AND PG.BDCODEMP = CB.BDCODEMP
  WHERE CB.BDCHAVE = :PRCHAVE AND CB.BDCODEMP = :PRCODEMP
  INTO :WCODEMP, :WCODCOL, :WREF, :WTIPOCAL, :WINTERMITENTE, :WCODFERIAS, :WCODCONTTI, :WDATACALCULO, :WCODSERV, :WINIPERAQUI, :WREFFIM;

  IF (WCODEMP IS NULL) THEN EXIT;

  IF ((WTIPOCAL IN (5,6,7)) AND (WINTERMITENTE = FALSE)) THEN
    BEGIN
      SELECT FIRST 1 CASE WHEN BDCODCLA = 3 THEN 1 ELSE 0 END EMPREGADOR
      FROM VRH_EMP_TCOLCON_VINC
      WHERE BDCODEMP = :WCODEMP AND BDCODCOL = :WCODCOL AND BDREFCOL <= :WREF

      ORDER BY BDREFCOL DESC
      INTO :WEMPREGADOR;

      SELECT FIRST 1 BDPAGEMP, BDPAGEMPCONTR
      FROM VRHF_BASE_TEMPCALC
      WHERE BDCODEMP = :WCODEMP
        AND BDREFEMP <= :WREF
      ORDER BY BDREFEMP DESC
      INTO :WPAGEMP, :WPAGEMPCONTR;

      IF (WEMPREGADOR = 1) THEN
        WEP = WPAGEMPCONTR;
      ELSE
        WEP = WPAGEMP;

      IF (WEP = 1) THEN
        BEGIN
          WCONT = 0;

          SELECT CAST(SUBSTRING(:WREF FROM 1 FOR 4)||'/'||SUBSTRING(:WREF FROM 5 FOR 2)||'/'||ULTDIA AS DATE) AS ULTIMODIA
          FROM ULTIMO_DIA_MES(SUBSTRING(:WREF FROM 5 FOR 2),SUBSTRING(:WREF FROM 1 FOR 4))
          INTO :WDATAREF;

          WHILE (WCONT = 0) DO
            BEGIN
              SELECT CAST(EXTRACT(WEEKDAY FROM :WDATAREF) AS INTEGER) AS DIA_SEMANA
              FROM RDB$DATABASE
              INTO :WDIASEMANA;

              SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:WCODEMP, :WDATAREF)
              INTO :WFERIADO;

              IF ((WDIASEMANA = 0) OR (WDIASEMANA = 6) OR (WFERIADO = TRUE))  THEN
                WDATAREF = WDATAREF - 1;
              ELSE
                WCONT = 1;
            END
        END
      ELSE
        BEGIN
          SELECT CAST(SUBSTRING(BDREFERENCIA FROM 1 FOR 4)||'/'||SUBSTRING(BDREFERENCIA FROM 5 FOR 2)||'/01' AS DATE) AS DATA
          FROM INC_REFERENCIA(:WREF,1)
          INTO :WDATAREF;

          WCONT = 0;

          WHILE (WCONT < 5) DO
            BEGIN
              SELECT FIRST 1 EXTRACT(WEEKDAY FROM :WDATAREF) FROM RDB$DATABASE
              INTO :WDIASEMANA;

              SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:WCODEMP, :WDATAREF)
              INTO :WFERIADO;

              IF ((WDIASEMANA <> 0) AND (WFERIADO = FALSE)) THEN
                WCONT = WCONT + 1;

              IF (WCONT < 5) THEN
                WDATAREF = WDATAREF + 1;
            END

          SELECT FIRST 1 EXTRACT(WEEKDAY FROM :WDATAREF) FROM RDB$DATABASE
          INTO :WDIASEMANA;

          IF (WDIASEMANA = 6) THEN
            WDATAREF = WDATAREF - 1;

          SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:WCODEMP, :WDATAREF)
          INTO :WFERIADO;

          IF (WFERIADO = TRUE) THEN
            WDATAREF = WDATAREF - 1;

        END
    END

  IF (WTIPOCAL = 2) THEN
    BEGIN
     IF (WREF < 12) THEN
       BEGIN
         SELECT CAST(SUBSTRING(:WREF FROM 1 FOR 4)||'/'||SUBSTRING(:WREF FROM 5 FOR 2)||'/'||ULTDIA AS DATE) AS ULTIMODIA
         FROM ULTIMO_DIA_MES(SUBSTRING(:WREF FROM 5 FOR 2),SUBSTRING(:WREF FROM 1 FOR 4))
         INTO :WDATAREF;
       END
     ELSE
       BEGIN
         SELECT CAST(SUBSTRING(:WREF FROM 1 FOR 4)||'/'||SUBSTRING(:WREF FROM 5 FOR 2)||'/'||20 AS DATE) AS DATAPGTO
          FROM RDB$DATABASE
         INTO :WDATAREF;
       END

     WCONT = 0;

     WHILE (WCONT = 0) DO
       BEGIN
         SELECT CAST(EXTRACT(WEEKDAY FROM :WDATAREF) AS INTEGER) AS DIA_SEMANA
         FROM RDB$DATABASE
         INTO :WDIASEMANA;

         SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:WCODEMP, :WDATAREF)
         INTO :WFERIADO;

         IF ((WDIASEMANA = 0) OR (WDIASEMANA = 6) OR (WFERIADO = TRUE))  THEN
           WDATAREF = WDATAREF - 1;
         ELSE
           WCONT = 1;
       END
    END

  IF (WTIPOCAL = 3) THEN
    BEGIN

      SELECT BDCALCFERA13, BDDATAPGTOA13
        FROM VRHF_EMP_TA13SAL
       WHERE BDCODEMP = :WCODEMP
         AND BDCODCOL = :WCODCOL
         AND BDREFA13 = :WREF
      INTO :WPAGOFERIAS, :WDATAREF;


      if (WPAGOFERIAS = FALSE) then
        BEGIN

          SELECT CAST(SUBSTRING(:WREF FROM 1 FOR 4)||'/'||SUBSTRING(:WREF FROM 5 FOR 2)||'/'||ULTDIA AS DATE) AS ULTIMODIA
          FROM ULTIMO_DIA_MES(SUBSTRING(:WREF FROM 5 FOR 2),SUBSTRING(:WREF FROM 1 FOR 4))
          INTO :WDATAREF;

          WCONT = 0;

          WHILE (WCONT = 0) DO
            BEGIN
              SELECT CAST(EXTRACT(WEEKDAY FROM :WDATAREF) AS INTEGER) AS DIA_SEMANA
              FROM RDB$DATABASE
              INTO :WDIASEMANA;

              SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:WCODEMP, :WDATAREF)
              INTO :WFERIADO;

              IF ((WDIASEMANA = 0) OR (WDIASEMANA = 6) OR (WFERIADO = TRUE))  THEN
                WDATAREF = WDATAREF - 1;
              ELSE
                WCONT = 1;
            END
        END
    END


  IF (WTIPOCAL = 1) THEN
    BEGIN
      SELECT MAX(BDDATAPAGSERV) AS DATAPAGTO
        FROM VRHF_BASE_CALC_TERC
       WHERE BDCODEMP = :WCODEMP
         AND BDCODTER = :WCODCOL
         AND BDCODSERV = :WCODSERV
         AND BDDATASERV = :WDATACALCULO
      INTO :WDATAPAGTO;
    END
  ELSE IF (WTIPOCAL = 2) THEN
    WDATAPAGTO = WDATAREF;
  ELSE IF (WTIPOCAL = 3) THEN
    WDATAPAGTO = WDATAREF;
  ELSE IF (WTIPOCAL = 4) THEN
    BEGIN
      SELECT MAX(BDDATAAD) AS DATAPAGTO
        FROM VRHF_EMP_TADSAL
       WHERE BDCODEMP = :WCODEMP
         AND BDCODCOL = :WCODCOL
         AND BDREFAD = :WREF
         AND BDDATAAD = :WDATACALCULO
      INTO :WDATAPAGTO;
    END
  ELSE IF (WTIPOCAL = 5) THEN
    WDATAPAGTO = WDATAREF;
  ELSE IF (WTIPOCAL = 6) THEN
    BEGIN
      IF (WINTERMITENTE = 'TRUE') THEN
        BEGIN
          SELECT MAX(BDDATAPGTOFN) AS DATAPAGTO
            FROM VRHF_EMP_TFOLHAINT
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFFN  = :WREF
             AND BDCODCONTTI = :WCODCONTTI
          INTO :WDATAPAGTO;
        END
      ELSE
        WDATAPAGTO = WDATAREF;
    END
  ELSE IF (WTIPOCAL = 7) THEN
    BEGIN
      IF (WINTERMITENTE = 'TRUE') THEN
        BEGIN
          SELECT MAX(BDDATAPGTOFT) AS DATAPAGTO
            FROM VRHF_EMP_TFOLHATOMINT
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFTOMADOR  = :WREF
             AND BDCODCONTTI = :WCODCONTTI
          INTO :WDATAPAGTO;
        END
      ELSE
        WDATAPAGTO = WDATAREF;
    END
  ELSE IF (WTIPOCAL = 8) THEN
    BEGIN
      IF (WINTERMITENTE = 'TRUE') THEN
        BEGIN
          SELECT MAX(BDDATAPAGFC) AS DATAPAGTO
            FROM VRHF_EMP_TFOLHACOMPINT
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFFN  = :WREF
             AND BDCODCONTTI = :WCODCONTTI
             AND BDDATAPAGFC = :WDATACALCULO
          INTO :WDATAPAGTO;
        END
      ELSE
        BEGIN
          SELECT MAX(BDDATAPAGFC) AS DATAPAGTO
            FROM VRHF_EMP_TFOLHACOMP
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFFN  = :WREF
             AND BDDATAPAGFC = :WDATACALCULO
          INTO :WDATAPAGTO;
        END
    END
  ELSE IF (WTIPOCAL = 9) THEN
    BEGIN
      IF (WINTERMITENTE = 'TRUE') THEN
        BEGIN
          SELECT MAX(BDDATAPAGFC) AS DATAPAGTO
            FROM VRHF_EMP_TFOLTOMCOMPINT
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFTOMADOR  = :WREF
             AND BDCODCONTTI = :WCODCONTTI
             AND BDDATAPAGFC = :WDATACALCULO
          INTO :WDATAPAGTO;
        END
      ELSE
        BEGIN
          SELECT MAX(BDDATAPAGFC) AS DATAPAGTO
            FROM VRHF_EMP_TFOLTOMCOMP
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFTOMADOR  = :WREF
             AND BDDATAPAGFC = :WDATACALCULO
          INTO :WDATAPAGTO;
        END
    END
  ELSE IF (WTIPOCAL = 10) THEN
    BEGIN
      SELECT MAX(BDDATAPAGFE) AS DATAPAGTO
        FROM VRH_EMP_TFERIAS
       WHERE BDCODEMP = :WCODEMP
         AND BDCODCOL = :WCODCOL
         AND BDINIPERAQUISFE = :WINIPERAQUI
         AND BDCODFE =:WCODFERIAS
      INTO :WDATAPAGTO;
    END
  ELSE IF (WTIPOCAL = 15) THEN
    BEGIN
      SELECT MAX(BDDATAPGTOFA) AS DATAPAGTO
        FROM VRHF_EMP_TFOLHAAVULSA
       WHERE BDCODEMP = :WCODEMP
         AND BDCODCOL = :WCODCOL
         AND BDREF = :WREF
         AND BDDATAPGTOFA = :WDATACALCULO
      INTO :WDATAPAGTO;
    END
  ELSE IF (WTIPOCAL = 16) THEN
    BEGIN
      IF (WINTERMITENTE = 'FALSE') THEN
        BEGIN
          SELECT MAX(A.DATAPAGTO) AS DATAPAGTO FROM (
          SELECT MAX(BDDATAPAGFC) AS DATAPAGTO
            FROM vrhf_emp_tfoltomcomp
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFFNINI  = :WREF AND BDREFFNFIM = :wreffim
             AND BDDATAPAGFC = :WDATACALCULO
          UNION ALL
          SELECT MAX(BDDATAPAGFC) AS DATAPAGTO
            FROM VRHF_EMP_TFOLHACOMP
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFFNINI  = :WREF AND BDREFFNFIM = :wreffim
             AND BDDATAPAGFC = :WDATACALCULO) a
          INTO :WDATAPAGTO;
        END
    END

  IF (WTIPOCAL IN (6,7)) THEN
    BEGIN
      SELECT BDDATAPAGRESCISAO
      FROM VRH_EMP_TRESCISAO
      WHERE BDCODEMP = :WCODEMP AND BDCODCOL = :WCODCOL AND BDREFRESCISAO = :WREF
      INTO :WDATARESC;

      IF (WDATARESC IS NOT NULL) THEN
        WDATAPAGTO = WDATARESC;

      WDATARESC = NULL;
    END

  IF (WDATAPAGTO IS NULL) THEN EXIT;

--  IF (WREF < 202301) THEN
--    BEGIN
      WDATAIRRFESOCIAL = WDATAPAGTO;
      SELECT BDAAAAMM FROM AAAAMM(:WDATAIRRFESOCIAL) INTO :WREFIRRFESOCIAL;

--    END
--  ELSE
--    BEGIN
      WDATAIRRFESOCIAL = WDATAPAGTO;

      SELECT MAX(BDDATAPGTO) AS DATABAIXA
      FROM VRHF_EMP_TPGTO_CALC
      WHERE BDCHAVEPGTO = :PRCHAVE
        AND BDCODEMP = :PRCODEMP
       INTO :WDATAPAGTO;

       /* Apenas deve Aplicar a regra de utilizar a baixa de pagamento para baixas apartir de 01/01/2024 */
      IF ((WDATAPAGTO IS NOT NULL) and (WDATAPAGTO >= '2024-01-01')) THEN
         begin
        WDATAIRRFESOCIAL = WDATAPAGTO;

      SELECT BDAAAAMM FROM AAAAMM(:WDATAIRRFESOCIAL) INTO :WREFIRRFESOCIAL;
         end
      else
         begin
            WDATAPAGTO = WDATAIRRFESOCIAL;
         end
--    END

  IF (WTIPOCAL = 1) THEN
    BEGIN
      UPDATE VRHF_BASE_CALC_TERC
         SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
             BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
       WHERE BDCODEMP = :WCODEMP
         AND BDCODTER = :WCODCOL
         AND BDCODSERV =  :WCODSERV
         AND BDDATASERV = :WDATACALCULO;
    END
  ELSE IF (WTIPOCAL = 2) THEN
    BEGIN
      UPDATE VRHF_EMP_T13SAL
         SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
             BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
       WHERE BDCODEMP = :WCODEMP
         AND BDCODCOL = :WCODCOL
         AND BDREF13 =  :WREF;
    END
  ELSE IF (WTIPOCAL = 3) THEN
    BEGIN
      UPDATE VRHF_EMP_TA13SAL
         SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
             BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
       WHERE BDCODEMP = :WCODEMP
         AND BDCODCOL = :WCODCOL
         AND BDREFA13 = :WREF;
    END
  ELSE IF (WTIPOCAL = 4) THEN
    BEGIN
      UPDATE VRHF_EMP_TADSAL
         SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
             BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
       WHERE BDCODEMP = :WCODEMP
         AND BDCODCOL = :WCODCOL
         AND BDREFAD  = :WREF
         AND BDDATAAD = :WDATACALCULO;
    END
  ELSE IF (WTIPOCAL = 5) THEN
    BEGIN
      UPDATE VRHF_EMP_TC13SAL
         SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
             BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
       WHERE BDCODEMP = :WCODEMP
          AND BDCODCOL = :WCODCOL
          AND BDREFC13  =  :WREF;
    END
  ELSE IF (WTIPOCAL = 6) THEN
    BEGIN
      IF (WINTERMITENTE = TRUE) THEN
        BEGIN
          UPDATE VRHF_EMP_TFOLHAINT
             SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
                 BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFFN  = :WREF
             AND BDCODCONTTI = :WCODCONTTI;
        END
      ELSE
        BEGIN
          UPDATE VRHF_EMP_TFOLHANORMAL
             SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
                 BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFFN  = :WREF;
        END

      SELECT BDPAGOFNC13
        FROM VRHF_EMP_TC13SAL
       WHERE BDCODEMP = :WCODEMP
         AND BDCODCOL = :WCODCOL
         AND BDREFC13  =  :WREF
        INTO :WPAGOFNC13;

      IF (WPAGOFNC13 = 'TRUE') THEN
        BEGIN
          UPDATE VRHF_EMP_TC13SAL
             SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
                 BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFC13 = :WREF;
        END

      if (WINTERMITENTE = FALSE) then
         begin
           UPDATE VRHF_EMP_TFOLHACOMP
              SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
                  BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
            WHERE BDCODEMP = :WCODEMP
              AND BDCODCOL = :WCODCOL
              AND BDREFVINCFN  = :WREF;


          UPDATE VRHF_EMP_TFOLTOMCOMP
             SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
                 BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFVINCFN  = :WREF;
         end

    END
  ELSE IF (WTIPOCAL = 7) THEN
    BEGIN
      IF (WINTERMITENTE = TRUE) THEN
        BEGIN
          UPDATE VRHF_EMP_TFOLHATOMINT
             SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
                 BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFTOMADOR  = :WREF
             AND BDCODCONTTI = :WCODCONTTI;
        END
      ELSE
        BEGIN
          UPDATE VRHF_EMP_TFOLHATOMADOR
             SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
                 BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFTOMADOR  = :WREF;
        END

      SELECT BDPAGOFNC13
        FROM VRHF_EMP_TC13SAL
       WHERE BDCODEMP = :WCODEMP
         AND BDCODCOL = :WCODCOL
         AND BDREFC13  =  :WREF
        INTO :WPAGOFNC13;

      IF (WPAGOFNC13 = 'TRUE') THEN
        BEGIN
          UPDATE VRHF_EMP_TC13SAL
             SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
                 BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFC13 = :WREF;
        END

      if (WINTERMITENTE = FALSE) then
         begin
           UPDATE VRHF_EMP_TFOLHACOMP
              SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
                  BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
            WHERE BDCODEMP = :WCODEMP
              AND BDCODCOL = :WCODCOL
              AND BDREFVINCFN  = :WREF;


          UPDATE VRHF_EMP_TFOLTOMCOMP
             SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
                 BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFVINCFN  = :WREF;
         end
    END
  ELSE IF (WTIPOCAL = 8) THEN
    BEGIN
      IF (WINTERMITENTE = TRUE) THEN
        BEGIN
          UPDATE VRHF_EMP_TFOLHACOMPINT
             SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
                 BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFFN  = :WREF
             AND BDCODCONTTI = :WCODCONTTI
             AND BDDATAPAGFC = :WDATACALCULO;
        END
      ELSE
        BEGIN
          UPDATE VRHF_EMP_TFOLHACOMP
             SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
                 BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFFN  = :WREF
             AND BDDATAPAGFC = :WDATACALCULO;
        END
    END
  ELSE IF (WTIPOCAL = 9) THEN
    BEGIN
      IF (WINTERMITENTE = TRUE) THEN
        BEGIN
          UPDATE VRHF_EMP_TFOLTOMCOMPINT
             SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
                 BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFTOMADOR  = :WREF
             AND BDCODCONTTI = :WCODCONTTI
             AND BDDATAPAGFC = :WDATACALCULO;
        END
      ELSE
        BEGIN
          UPDATE VRHF_EMP_TFOLTOMCOMP
             SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
                 BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFTOMADOR  = :WREF
             AND BDDATAPAGFC = :WDATACALCULO;
        END
    END
  ELSE IF (WTIPOCAL = 10) THEN
    BEGIN
      UPDATE VRH_EMP_TFERIAS
         SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
             BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
       WHERE BDCODEMP = :WCODEMP
         AND BDCODCOL = :WCODCOL
         AND BDINIPERAQUISFE = :WINIPERAQUI
         AND BDCODFE =:WCODFERIAS;
    END
  ELSE IF (WTIPOCAL = 15) THEN
    BEGIN
      UPDATE VRHF_EMP_TFOLHAAVULSA
         SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
             BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL

       WHERE BDCODEMP = :WCODEMP
         AND BDCODCOL = :WCODCOL
         AND BDREF  = :WREF
         AND BDDATAPGTOFA = :WDATACALCULO;
    END
  ELSE IF (WTIPOCAL = 16) THEN
    BEGIN
      IF (WINTERMITENTE = FALSE) THEN
        BEGIN
          UPDATE VRHF_EMP_TFOLHACOMP
             SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
                 BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFFNINI  = :WREF AND BDREFFNFIM = :wreffim
             AND BDDATAPAGFC = :WDATACALCULO;

          UPDATE VRHF_EMP_TFOLTOMCOMP
             SET BDDATAIRRFESOCIAL = :WDATAIRRFESOCIAL,
                 BDREFIRRFESOCIAL  = :WREFIRRFESOCIAL
           WHERE BDCODEMP = :WCODEMP
             AND BDCODCOL = :WCODCOL
             AND BDREFTOMADOR  = :WREF AND BDREFTOMADOR= :wreffim
             AND BDDATAPAGFC = :WDATACALCULO;
        END
    END

  RDATAIRRFESOCIAL = :WDATAIRRFESOCIAL;
  RREFIRRFESOCIAL  = :WREFIRRFESOCIAL;

  SUSPEND;
END^

CREATE OR ALTER TRIGGER VRHF_EMP_TPGTO_CALC_AIU0 FOR VRHF_EMP_TPGTO_CALC
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
  DECLARE VARIABLE WDATAIRRFESOCIAL DATE;
  DECLARE VARIABLE WREFIRRFESOCIAL  INTEGER;
BEGIN
  SELECT RDATAIRRFESOCIAL, RREFIRRFESOCIAL FROM SP_VRH_UPDATE_DATAIRRFESOCIAL (NEW.BDCODEMP, NEW.BDCHAVEPGTO)
  INTO :WDATAIRRFESOCIAL, :WREFIRRFESOCIAL;
END^

CREATE OR ALTER TRIGGER VRHF_EMP_TPGTO_CALC_AD0 FOR VRHF_EMP_TPGTO_CALC
ACTIVE AFTER DELETE POSITION 0
AS
  DECLARE VARIABLE WDATAIRRFESOCIAL DATE;
  DECLARE VARIABLE WREFIRRFESOCIAL  INTEGER;
BEGIN
  SELECT RDATAIRRFESOCIAL, RREFIRRFESOCIAL FROM SP_VRH_UPDATE_DATAIRRFESOCIAL (OLD.BDCODEMP, OLD.BDCHAVEPGTO)
  INTO :WDATAIRRFESOCIAL, :WREFIRRFESOCIAL;
END^

CREATE OR ALTER TRIGGER VRHF_EMP_TDADOSCALC_BAIXA_AI0 FOR VRHF_EMP_TDADOSCALC_BAIXA
ACTIVE AFTER INSERT POSITION 0
AS
  DECLARE VARIABLE WDATAIRRFESOCIAL DATE;
  DECLARE VARIABLE WREFIRRFESOCIAL  INTEGER;
BEGIN
  SELECT RDATAIRRFESOCIAL, RREFIRRFESOCIAL FROM SP_VRH_UPDATE_DATAIRRFESOCIAL (NEW.BDCODEMP, NEW.BDCHAVE)
  INTO :WDATAIRRFESOCIAL, :WREFIRRFESOCIAL;
END^

create or alter procedure SP_VRH_UPDATE_DATAIR_INICIAL
returns (
    RSTATUS boolean)
as
declare variable FCODEMP integer;
declare variable FCODCOL integer;
declare variable FREF integer;
declare variable FANO integer;
declare variable FMES integer;
declare variable FEMPREGADOR integer;
declare variable FPAGEMP integer;
declare variable FPAGEMPCONTR integer;
declare variable FEP integer;
declare variable FDATA date;
declare variable FDIASEMANA integer;
declare variable FCONT integer;
declare variable FFERIADO boolean;
declare variable FDATARESC date;
declare variable FPAGOFERIAS boolean;
declare variable FCODCONTTI integer;
declare variable FPAGOFNC13 varchar(5);
declare variable FCODFERIAS integer;
BEGIN
  RSTATUS = FALSE;
  FOR SELECT BDCODEMP, BDCODCOL, BDREFTOMADOR, CAST(SUBSTRING(BDREFTOMADOR FROM 1 FOR 4) AS INTEGER) ANO, CAST(SUBSTRING(BDREFTOMADOR FROM 5 FOR 2) AS INTEGER) MES
      FROM VRHF_EMP_TFOLHATOMADOR
      INTO :FCODEMP, :FCODCOL, :FREF, :FANO, :FMES DO
    BEGIN
      SELECT FIRST 1 CASE WHEN V.BDCODCLA = 3 THEN 1 ELSE 0 END EMPREGADOR
      FROM VRH_EMP_TCOLCON_VINC V
      WHERE V.BDCODEMP = :FCODEMP AND V.BDCODCOL = :FCODCOL AND V.BDREFCOL <= :FREF
      ORDER BY V.BDREFCOL DESC
      INTO :FEMPREGADOR;

      SELECT FIRST 1 X.BDPAGEMP, X.BDPAGEMPCONTR
      FROM VRHF_BASE_TEMPCALC X
      WHERE X.BDCODEMP = :FCODEMP
        AND X.BDREFEMP <= :FREF
      ORDER BY X.BDREFEMP DESC
      INTO :FPAGEMP, :FPAGEMPCONTR;

      IF (FEMPREGADOR = 1) THEN
        FEP = FPAGEMPCONTR;
      ELSE
        FEP = FPAGEMP;

     IF (FEP = 1) THEN
       BEGIN
         FCONT = 0;

         SELECT CAST(SUBSTRING(:FREF FROM 1 FOR 4)||'/'||SUBSTRING(:FREF FROM 5 FOR 2)||'/'||ULTDIA AS DATE) AS ULTIMODIA
         FROM ULTIMO_DIA_MES(SUBSTRING(:FREF FROM 5 FOR 2),SUBSTRING(:FREF FROM 1 FOR 4))
         INTO :FDATA;

         WHILE (FCONT = 0) DO
           BEGIN
             SELECT CAST(EXTRACT(WEEKDAY FROM :FDATA) AS INTEGER) AS DIA_SEMANA
             FROM RDB$DATABASE
             INTO :FDIASEMANA;

             SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:FCODEMP, :FDATA)
             INTO :FFERIADO;

             IF ((FDIASEMANA = 0) OR (FDIASEMANA = 6) OR (FFERIADO = TRUE))  THEN
               FDATA = FDATA - 1;
             ELSE
               FCONT = 1;
           END
       END
     ELSE
       BEGIN
         SELECT CAST(SUBSTRING(BDREFERENCIA FROM 1 FOR 4)||'-'||SUBSTRING(BDREFERENCIA FROM 5 FOR 2)||'-01' AS DATE) AS DATA
         FROM INC_REFERENCIA(:FREF,1)
         INTO :FDATA;

         FCONT = 0;

         WHILE (FCONT < 5) DO
           BEGIN

             SELECT FIRST 1 EXTRACT(WEEKDAY FROM :FDATA) FROM RDB$DATABASE
             INTO :FDIASEMANA;

             SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:FCODEMP, :FDATA)
             INTO :FFERIADO;

             IF ((FDIASEMANA <> 0) AND (FFERIADO = FALSE)) THEN
               FCONT = FCONT + 1;

             IF (FCONT < 5) THEN
               FDATA = FDATA + 1;

           END

         SELECT FIRST 1 EXTRACT(WEEKDAY FROM :FDATA) FROM RDB$DATABASE
         INTO :FDIASEMANA;

         IF (FDIASEMANA = 6) THEN
           FDATA = FDATA - 1;

         SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:FCODEMP, :FDATA)
         INTO :FFERIADO;

         IF (FFERIADO = TRUE) THEN
           FDATA = FDATA - 1;

         SELECT BDDATAPAGRESCISAO
         FROM VRH_EMP_TRESCISAO
         WHERE BDCODEMP = :FCODEMP AND BDCODCOL = :FCODCOL AND BDREFRESCISAO = :FREF
         INTO :FDATARESC;

         IF (FDATARESC IS NOT NULL) THEN
           FDATA = FDATARESC;

         FDATARESC = NULL;
       END

     UPDATE VRHF_EMP_TFOLHATOMADOR F
        SET BDDATAPREVCALCULO = :FDATA,
            BDDATAIRRFESOCIAL = :FDATA,
            BDREFIRRFESOCIAL = (SELECT BDAAAAMM FROM AAAAMM(:FDATA))
      WHERE BDCODEMP = :FCODEMP
        AND BDCODCOL = :FCODCOL
        AND BDREFTOMADOR = :FREF;

      SELECT BDPAGOFNC13
        FROM VRHF_EMP_TC13SAL
       WHERE BDCODEMP = :FCODEMP
         AND BDCODCOL = :FCODCOL
         AND BDREFC13 = :FREF
        INTO :FPAGOFNC13;

      IF (FPAGOFNC13 = 'TRUE') THEN
        BEGIN
          UPDATE VRHF_EMP_TC13SAL
             SET BDDATAIRRFESOCIAL = :FDATA,
                 BDREFIRRFESOCIAL  = (SELECT BDAAAAMM FROM AAAAMM(:FDATA))
           WHERE BDCODEMP = :FCODEMP
             AND BDCODCOL = :FCODCOL
             AND BDREFC13 = :FREF;
        END

      RSTATUS = TRUE;
    END

  FOR SELECT BDCODEMP, BDCODCOL, BDREFFN, CAST(SUBSTRING(BDREFFN FROM 1 FOR 4) AS INTEGER) ANO, CAST(SUBSTRING(BDREFFN FROM 5 FOR 2) AS INTEGER) MES
      FROM VRHF_EMP_TFOLHANORMAL
      INTO :FCODEMP, :FCODCOL, :FREF, :FANO, :FMES DO
    BEGIN
      SELECT FIRST 1 CASE WHEN V.BDCODCLA = 3 THEN 1 ELSE 0 END EMPREGADOR
      FROM VRH_EMP_TCOLCON_VINC V
      WHERE V.BDCODEMP = :FCODEMP AND V.BDCODCOL = :FCODCOL AND V.BDREFCOL <= :FREF
      ORDER BY V.BDREFCOL DESC
      INTO :FEMPREGADOR;

      SELECT FIRST 1 X.BDPAGEMP, X.BDPAGEMPCONTR
      FROM VRHF_BASE_TEMPCALC X
      WHERE X.BDCODEMP = :FCODEMP
        AND X.BDREFEMP <= :FREF
      ORDER BY X.BDREFEMP DESC
      INTO :FPAGEMP, :FPAGEMPCONTR;

      IF (FEMPREGADOR = 1) THEN
        FEP = FPAGEMPCONTR;
      ELSE
        FEP = FPAGEMP;

     IF (FEP = 1) THEN
       BEGIN
          FCONT = 0;

          SELECT CAST(SUBSTRING(:FREF FROM 1 FOR 4)||'/'||SUBSTRING(:FREF FROM 5 FOR 2)||'/'||ULTDIA AS DATE) AS ULTIMODIA
          FROM ULTIMO_DIA_MES(SUBSTRING(:FREF FROM 5 FOR 2),SUBSTRING(:FREF FROM 1 FOR 4))
          INTO :FDATA;

          WHILE (FCONT = 0) DO
            BEGIN
              SELECT CAST(EXTRACT(WEEKDAY FROM :FDATA) AS INTEGER) AS DIA_SEMANA
              FROM RDB$DATABASE
              INTO :FDIASEMANA;

              SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:FCODEMP, :FDATA)
              INTO :FFERIADO;

              IF ((FDIASEMANA = 0) OR (FDIASEMANA = 6) OR (FFERIADO = TRUE))  THEN
                FDATA = FDATA - 1;
              ELSE
                FCONT = 1;
            END
       END
     ELSE
       BEGIN
         SELECT CAST(SUBSTRING(BDREFERENCIA FROM 1 FOR 4)||'-'||SUBSTRING(BDREFERENCIA FROM 5 FOR 2)||'-01' AS DATE) AS DATA
         FROM INC_REFERENCIA(:FREF,1)
         INTO :FDATA;

         FCONT = 0;

         WHILE (FCONT < 5) DO
           BEGIN

             SELECT FIRST 1 EXTRACT(WEEKDAY FROM :FDATA) FROM RDB$DATABASE
             INTO :FDIASEMANA;

             SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:FCODEMP, :FDATA)
             INTO :FFERIADO;

             IF ((FDIASEMANA <> 0) AND (FFERIADO = FALSE)) THEN
               FCONT = FCONT + 1;

             IF (FCONT < 5) THEN
               FDATA = FDATA + 1;

           END

         SELECT FIRST 1 EXTRACT(WEEKDAY FROM :FDATA) FROM RDB$DATABASE
         INTO :FDIASEMANA;

         IF (FDIASEMANA = 6) THEN
           FDATA = FDATA - 1;

         SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:FCODEMP, :FDATA)
         INTO :FFERIADO;

         IF (FFERIADO = TRUE) THEN
           FDATA = FDATA - 1;

         SELECT BDDATAPAGRESCISAO
         FROM VRH_EMP_TRESCISAO
         WHERE BDCODEMP = :FCODEMP AND BDCODCOL = :FCODCOL AND BDREFRESCISAO = :FREF
         INTO :FDATARESC;

         IF (FDATARESC IS NOT NULL) THEN
           FDATA = FDATARESC;

         FDATARESC = NULL;
       END

     UPDATE VRHF_EMP_TFOLHANORMAL F
        SET BDDATAPREVCALCULO = :FDATA,
            BDDATAIRRFESOCIAL = :FDATA,
            BDREFIRRFESOCIAL = (SELECT BDAAAAMM FROM AAAAMM(:FDATA))
      WHERE BDCODEMP = :FCODEMP
        AND BDCODCOL = :FCODCOL
        AND BDREFFN = :FREF;

      SELECT BDPAGOFNC13
        FROM VRHF_EMP_TC13SAL
       WHERE BDCODEMP = :FCODEMP
         AND BDCODCOL = :FCODCOL
         AND BDREFC13 = :FREF
        INTO :FPAGOFNC13;

      IF (FPAGOFNC13 = 'TRUE') THEN
        BEGIN
          UPDATE VRHF_EMP_TC13SAL
             SET BDDATAIRRFESOCIAL = :FDATA,
                 BDREFIRRFESOCIAL  = (SELECT BDAAAAMM FROM AAAAMM(:FDATA))
           WHERE BDCODEMP = :FCODEMP
             AND BDCODCOL = :FCODCOL
             AND BDREFC13 = :FREF;
        END

      RSTATUS = TRUE;

    END

  FOR SELECT BDCODEMP, BDCODCOL, BDREFC13, CAST(SUBSTRING(BDREFC13 FROM 1 FOR 4) AS INTEGER) ANO, CAST(SUBSTRING(BDREFC13 FROM 5 FOR 2) AS INTEGER) MES
      FROM VRHF_EMP_TC13SAL 
      INTO :FCODEMP, :FCODCOL, :FREF, :FANO, :FMES DO
    BEGIN
      SELECT FIRST 1 CASE WHEN V.BDCODCLA = 3 THEN 1 ELSE 0 END EMPREGADOR
      FROM VRH_EMP_TCOLCON_VINC V
      WHERE V.BDCODEMP = :FCODEMP AND V.BDCODCOL = :FCODCOL AND V.BDREFCOL <= :FREF
      ORDER BY V.BDREFCOL DESC
      INTO :FEMPREGADOR;

      SELECT FIRST 1 X.BDPAGEMP, X.BDPAGEMPCONTR
      FROM VRHF_BASE_TEMPCALC X
      WHERE X.BDCODEMP = :FCODEMP
        AND X.BDREFEMP <= :FREF
      ORDER BY X.BDREFEMP DESC
      INTO :FPAGEMP, :FPAGEMPCONTR;

      IF (FEMPREGADOR = 1) THEN
        FEP = FPAGEMPCONTR;
      ELSE
        FEP = FPAGEMP;

     IF (FEP = 1) THEN
       BEGIN
          FCONT = 0;

          SELECT CAST(SUBSTRING(:FREF FROM 1 FOR 4)||'/'||SUBSTRING(:FREF FROM 5 FOR 2)||'/'||ULTDIA AS DATE) AS ULTIMODIA
          FROM ULTIMO_DIA_MES(SUBSTRING(:FREF FROM 5 FOR 2),SUBSTRING(:FREF FROM 1 FOR 4))
          INTO :FDATA;

          WHILE (FCONT = 0) DO
            BEGIN
              SELECT CAST(EXTRACT(WEEKDAY FROM :FDATA) AS INTEGER) AS DIA_SEMANA
              FROM RDB$DATABASE
              INTO :FDIASEMANA;

              SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:FCODEMP, :FDATA)
              INTO :FFERIADO;

              IF ((FDIASEMANA = 0) OR (FDIASEMANA = 6) OR (FFERIADO = TRUE))  THEN
                FDATA = FDATA - 1;
              ELSE
                FCONT = 1;
            END
       END
     ELSE
       BEGIN
         SELECT CAST(SUBSTRING(BDREFERENCIA FROM 1 FOR 4)||'-'||SUBSTRING(BDREFERENCIA FROM 5 FOR 2)||'-01' AS DATE) AS DATA
         FROM INC_REFERENCIA(:FREF,1)
         INTO :FDATA;

         FCONT = 0;

         WHILE (FCONT < 5) DO
           BEGIN

             SELECT FIRST 1 EXTRACT(WEEKDAY FROM :FDATA) FROM RDB$DATABASE
             INTO :FDIASEMANA;

             SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:FCODEMP, :FDATA)
             INTO :FFERIADO;

             IF ((FDIASEMANA <> 0) AND (FFERIADO = FALSE)) THEN
               FCONT = FCONT + 1;

             IF (FCONT < 5) THEN
               FDATA = FDATA + 1;

           END

         SELECT FIRST 1 EXTRACT(WEEKDAY FROM :FDATA) FROM RDB$DATABASE
         INTO :FDIASEMANA;

         IF (FDIASEMANA = 6) THEN
           FDATA = FDATA - 1;

         SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:FCODEMP, :FDATA)
         INTO :FFERIADO;

         IF (FFERIADO = TRUE) THEN
           FDATA = FDATA - 1;

       END

     UPDATE VRHF_EMP_TC13SAL F
        SET BDDATAPREVCALCULO = :FDATA,
            BDDATAIRRFESOCIAL = :FDATA,
            BDREFIRRFESOCIAL = (SELECT BDAAAAMM FROM AAAAMM(:FDATA))
      WHERE BDCODEMP = :FCODEMP
        AND BDCODCOL = :FCODCOL
        AND BDREFC13 = :FREF;
      RSTATUS = TRUE;
    END

  FOR SELECT BDCODEMP, BDCODSERV, BDREFIRSERV, BDDATAPAGSERV, CAST(SUBSTRING(BDREFIRSERV FROM 1 FOR 4) AS INTEGER) ANO, CAST(SUBSTRING(BDREFIRSERV FROM 5 FOR 2) AS INTEGER) MES
      FROM VRHF_BASE_CALC_TERC
      INTO :FCODEMP, :FCODCOL, :FREF, :FDATA, :FANO, :FMES DO
    BEGIN
     UPDATE VRHF_BASE_CALC_TERC
        SET BDDATAIRRFESOCIAL = :FDATA,
            BDREFIRRFESOCIAL = (SELECT BDAAAAMM FROM AAAAMM(:FDATA))
      WHERE BDCODEMP = :FCODEMP
        AND BDCODSERV = :FCODCOL
        AND BDREFIRSERV = :FREF
        AND BDDATAPAGSERV = :FDATA;
      RSTATUS = TRUE;
    END

  FOR SELECT BDCODEMP, BDCODCOL, BDREF13, CAST(SUBSTRING(BDREF13 FROM 1 FOR 4) AS INTEGER) ANO, CAST(SUBSTRING(BDREF13 FROM 5 FOR 2) AS INTEGER) MES
      FROM VRHF_EMP_T13SAL
      INTO :FCODEMP, :FCODCOL, :FREF, :FANO, :FMES DO
    BEGIN
     IF (FREF < 12) THEN
       BEGIN
         SELECT CAST(:FANO||'/'||:FMES||'/'||ULTDIA AS DATE) AS ULTIMODIA
         FROM ULTIMO_DIA_MES(:FMES,:FANO)
         INTO :FDATA;
       END
     ELSE
       BEGIN
         SELECT CAST(:FANO||'/'||:FMES||'/'||20 AS DATE) AS DATAPGTO
          FROM RDB$DATABASE
         INTO :FDATA;
       END

       FCONT = 0;

       WHILE (FCONT = 0) DO
         BEGIN
           SELECT CAST(EXTRACT(WEEKDAY FROM :FDATA) AS INTEGER) AS DIA_SEMANA
           FROM RDB$DATABASE
           INTO :FDIASEMANA;

           SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:FCODEMP, :FDATA)
           INTO :FFERIADO;

           IF ((FDIASEMANA = 0) OR (FDIASEMANA = 6) OR (FFERIADO = TRUE))  THEN
             FDATA = FDATA - 1;
           ELSE
             FCONT = 1;
         END

     UPDATE VRHF_EMP_T13SAL F
        SET BDDATAIRRFESOCIAL = :FDATA,
            BDREFIRRFESOCIAL = (SELECT BDAAAAMM FROM AAAAMM(:FDATA))
      WHERE BDCODEMP = :FCODEMP
        AND BDCODCOL = :FCODCOL
        AND BDREF13 = :FREF;
      RSTATUS = TRUE;
    END

  FOR SELECT BDCODEMP, BDCODCOL, BDREFA13, CAST(SUBSTRING(BDREFA13 FROM 1 FOR 4) AS INTEGER) ANO, CAST(SUBSTRING(BDREFA13 FROM 5 FOR 2) AS INTEGER) MES,
              COALESCE(BDCALCFERA13,'FALSE'), BDDATAPGTOA13
      FROM VRHF_EMP_TA13SAL
      INTO :FCODEMP, :FCODCOL, :FREF, :FANO, :FMES, :FPAGOFERIAS, :FDATA  DO
    BEGIN
      if ((FPAGOFERIAS = FALSE) or (FDATA is null))  then
        BEGIN
          SELECT CAST(:FANO||'/'||:FMES||'/'||ULTDIA AS DATE) AS ULTIMODIA
            FROM ULTIMO_DIA_MES(:FMES,:FANO)
            INTO :FDATA;

          FCONT = 0;

          WHILE (FCONT = 0) DO
            BEGIN
              SELECT CAST(EXTRACT(WEEKDAY FROM :FDATA) AS INTEGER) AS DIA_SEMANA
                FROM RDB$DATABASE
                INTO :FDIASEMANA;

              SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:FCODEMP, :FDATA)
                INTO :FFERIADO;

              IF ((FDIASEMANA = 0) OR (FDIASEMANA = 6) OR (FFERIADO = TRUE))  THEN
                FDATA = FDATA - 1;
              ELSE
                FCONT = 1;
            END
        END
     UPDATE VRHF_EMP_TA13SAL
        SET BDDATAIRRFESOCIAL = :FDATA,
            BDREFIRRFESOCIAL = (SELECT BDAAAAMM FROM AAAAMM(:FDATA))
      WHERE BDCODEMP = :FCODEMP
        AND BDCODCOL = :FCODCOL
        AND BDREFA13 = :FREF;
      RSTATUS = TRUE;
    END

  FOR SELECT BDCODEMP, BDCODCOL, BDREFAD, BDDATAAD, CAST(SUBSTRING(BDREFAD FROM 1 FOR 4) AS INTEGER) ANO, CAST(SUBSTRING(BDREFAD FROM 5 FOR 2) AS INTEGER) MES
      FROM VRHF_EMP_TADSAL
      INTO :FCODEMP, :FCODCOL, :FREF, :FDATA, :FANO, :FMES DO
    BEGIN
     UPDATE VRHF_EMP_TADSAL
        SET BDDATAIRRFESOCIAL = :FDATA,
            BDREFIRRFESOCIAL = (SELECT BDAAAAMM FROM AAAAMM(:FDATA))
      WHERE BDCODEMP = :FCODEMP
        AND BDCODCOL = :FCODCOL
        AND BDREFAD = :FREF
        AND BDDATAAD = :FDATA;
      RSTATUS = TRUE;
    END

  FOR SELECT BDCODEMP, BDCODCOL, BDREFFN, BDDATAPGTOFN, CAST(SUBSTRING(BDREFFN FROM 1 FOR 4) AS INTEGER) ANO,
  CAST(SUBSTRING(BDREFFN FROM 5 FOR 2) AS INTEGER) MES, BDCODCONTTI
      FROM VRHF_EMP_TFOLHAINT
      INTO :FCODEMP, :FCODCOL, :FREF, :FDATA, :FANO, :FMES, :FCODCONTTI DO
    BEGIN

     SELECT BDDATAPAGRESCISAO
     FROM VRH_EMP_TRESCISAO
     WHERE BDCODEMP = :FCODEMP AND BDCODCOL = :FCODCOL AND BDREFRESCISAO = :FREF
     INTO :FDATARESC;

     IF (FDATARESC IS NOT NULL) THEN
       FDATA = FDATARESC;

     FDATARESC = NULL;

     UPDATE VRHF_EMP_TFOLHAINT
        SET BDDATAIRRFESOCIAL = :FDATA,
            BDREFIRRFESOCIAL = (SELECT BDAAAAMM FROM AAAAMM(:FDATA))
      WHERE BDCODEMP = :FCODEMP
        AND BDCODCOL = :FCODCOL
        AND BDREFFN = :FREF
        AND BDCODCONTTI = :FCODCONTTI;
      RSTATUS = TRUE;
    END

  FOR SELECT BDCODEMP, BDCODCOL, BDREFTOMADOR, BDDATAPGTOFT, CAST(SUBSTRING(BDREFTOMADOR FROM 1 FOR 4) AS INTEGER) ANO,
             CAST(SUBSTRING(BDREFTOMADOR FROM 5 FOR 2) AS INTEGER) MES, BDCODCONTTI
      FROM VRHF_EMP_TFOLHATOMINT
      INTO :FCODEMP, :FCODCOL, :FREF, :FDATA, :FANO, :FMES, :FCODCONTTI DO
    BEGIN
     SELECT BDDATAPAGRESCISAO
     FROM VRH_EMP_TRESCISAO
     WHERE BDCODEMP = :FCODEMP AND BDCODCOL = :FCODCOL AND BDREFRESCISAO = :FREF
     INTO :FDATARESC;

     IF (FDATARESC IS NOT NULL) THEN
       FDATA = FDATARESC;

     FDATARESC = NULL;

     UPDATE VRHF_EMP_TFOLHATOMINT
        SET BDDATAIRRFESOCIAL = :FDATA,
            BDREFIRRFESOCIAL = (SELECT BDAAAAMM FROM AAAAMM(:FDATA))
      WHERE BDCODEMP = :FCODEMP
        AND BDCODCOL = :FCODCOL
        AND BDREFTOMADOR = :FREF
        AND BDCODCONTTI = :FCODCONTTI;
      RSTATUS = TRUE;
    END

  FOR SELECT BDCODEMP, BDCODCOL, BDREFTOMADOR, BDDATAPAGFC, CAST(SUBSTRING(BDREFTOMADOR FROM 1 FOR 4) AS INTEGER) ANO,
             CAST(SUBSTRING(BDREFTOMADOR FROM 5 FOR 2) AS INTEGER) MES, BDCODCONTTI
      FROM VRHF_EMP_TFOLTOMCOMPINT
      INTO :FCODEMP, :FCODCOL, :FREF, :FDATA, :FANO, :FMES, :FCODCONTTI DO
    BEGIN
     UPDATE VRHF_EMP_TFOLTOMCOMPINT
        SET BDDATAIRRFESOCIAL = :FDATA,
            BDREFIRRFESOCIAL = (SELECT BDAAAAMM FROM AAAAMM(:FDATA))
      WHERE BDCODEMP = :FCODEMP
        AND BDCODCOL = :FCODCOL
        AND BDREFTOMADOR = :FREF
        AND BDCODCONTTI = :FCODCONTTI
        AND BDDATAPAGFC = :FDATA;
      RSTATUS = TRUE;
    END

  FOR SELECT BDCODEMP, BDCODCOL, BDREFTOMADOR, BDDATAPAGFC, CAST(SUBSTRING(BDREFTOMADOR FROM 1 FOR 4) AS INTEGER) ANO, CAST(SUBSTRING(BDREFTOMADOR FROM 5 FOR 2) AS INTEGER) MES
      FROM VRHF_EMP_TFOLTOMCOMP
      INTO :FCODEMP, :FCODCOL, :FREF, :FDATA, :FANO, :FMES DO
    BEGIN
     UPDATE VRHF_EMP_TFOLTOMCOMP
        SET BDDATAIRRFESOCIAL = :FDATA,
            BDREFIRRFESOCIAL = (SELECT BDAAAAMM FROM AAAAMM(:FDATA))
      WHERE BDCODEMP = :FCODEMP
        AND BDCODCOL = :FCODCOL
        AND BDREFTOMADOR = :FREF
        AND BDDATAPAGFC = :FDATA;
      RSTATUS = TRUE;
    END

  FOR SELECT BDCODEMP, BDCODCOL, BDREFCOMP, BDDATAPAGFC, CAST(SUBSTRING(BDREFCOMP FROM 1 FOR 4) AS INTEGER) ANO,
             CAST(SUBSTRING(BDREFCOMP FROM 5 FOR 2) AS INTEGER) MES, BDCODCONTTI
      FROM VRHF_EMP_TFOLHACOMPINT
      INTO :FCODEMP, :FCODCOL, :FREF, :FDATA, :FANO, :FMES, :FCODCONTTI DO
    BEGIN
     UPDATE VRHF_EMP_TFOLHACOMPINT
        SET BDDATAIRRFESOCIAL = :FDATA,
            BDREFIRRFESOCIAL = (SELECT BDAAAAMM FROM AAAAMM(:FDATA))
      WHERE BDCODEMP = :FCODEMP
        AND BDCODCOL = :FCODCOL
        AND BDREFCOMP = :FREF
        AND BDCODCONTTI = :FCODCONTTI
        AND BDDATAPAGFC = :FDATA;
      RSTATUS = TRUE;
    END

  FOR SELECT BDCODEMP, BDCODCOL, BDREFCOMP, BDDATAPAGFC, CAST(SUBSTRING(BDREFFN FROM 1 FOR 4) AS INTEGER) ANO,
             CAST(SUBSTRING(BDREFFN FROM 5 FOR 2) AS INTEGER) MES
      FROM VRHF_EMP_TFOLHACOMP
      INTO :FCODEMP, :FCODCOL, :FREF, :FDATA, :FANO, :FMES DO
    BEGIN
     UPDATE VRHF_EMP_TFOLHACOMP
        SET BDDATAIRRFESOCIAL = :FDATA,
            BDREFIRRFESOCIAL = (SELECT BDAAAAMM FROM AAAAMM(:FDATA))
      WHERE BDCODEMP = :FCODEMP
        AND BDCODCOL = :FCODCOL
        AND BDREFFN = :FREF
        AND BDDATAPAGFC = :FDATA;
      RSTATUS = TRUE;
    END

  FOR SELECT BDCODEMP, BDCODCOL, BDREFINIFE, COALESCE(BDDATAPAGFE,BDINIPERGOZOFE), CAST(SUBSTRING(BDREFINIFE FROM 1 FOR 4) AS INTEGER) ANO,
             CAST(SUBSTRING(BDREFINIFE FROM 5 FOR 2) AS INTEGER) MES, BDCODFE
      FROM VRH_EMP_TFERIAS
      where BDREFINIFE > 99999
      INTO :FCODEMP, :FCODCOL, :FREF, :FDATA, :FANO, :FMES, FCODFERIAS DO
    BEGIN
      if (FDATA IS NOT NULL) then
         BEGIN
           UPDATE VRH_EMP_TFERIAS
              SET BDDATAIRRFESOCIAL = :FDATA,
                  BDREFIRRFESOCIAL = (SELECT BDAAAAMM FROM AAAAMM(:FDATA))
            WHERE BDCODEMP = :FCODEMP
              AND BDCODCOL = :FCODCOL
              AND BDREFINIFE = :FREF
              AND BDCODFE =:FCODFERIAS;
         END
      RSTATUS = TRUE;
    END

  FOR SELECT BDCODEMP, BDCODCOL, BDREF, BDDATAPGTOFA, CAST(SUBSTRING(BDREF FROM 1 FOR 4) AS INTEGER) ANO, CAST(SUBSTRING(BDREF FROM 5 FOR 2) AS INTEGER) MES
      FROM VRHF_EMP_TFOLHAAVULSA
      INTO :FCODEMP, :FCODCOL, :FREF, :FDATA, :FANO, :FMES DO
    BEGIN
     UPDATE VRHF_EMP_TFOLHAAVULSA
        SET BDDATAIRRFESOCIAL = :FDATA,
            BDREFIRRFESOCIAL = (SELECT BDAAAAMM FROM AAAAMM(:FDATA))
      WHERE BDCODEMP = :FCODEMP
        AND BDCODCOL = :FCODCOL
        AND BDREF = :FREF
        AND BDDATAPGTOFA = :FDATA;
      RSTATUS = TRUE;
    END

  SUSPEND;
END^

CREATE OR ALTER procedure SP_VRH_UPDATE_DATAIR_FN
as
declare variable WCODEMP integer;
declare variable WREF integer;
declare variable WEMPANT integer;
declare variable WREFMENSAL integer;
declare variable WPGTMESPOST integer;
declare variable WPGTMESPOSTPRO integer;
declare variable WDATAPGTO date;
declare variable WREFPGT integer;
declare variable WDATAPGTOPRO date;
declare variable WREFPGTPRO integer;
declare variable FDIASEMANA integer;
declare variable FFERIADO boolean;
declare variable FCONT integer;
declare variable WSQLNORMAL varchar(3000);
declare variable WSQLTOMADOR varchar(3000);
declare variable WSQLCOMP13FOLHA varchar(3000);
begin
  /* Procedure Text */
  --  suspend;

 update VRHF_EMP_TFOLHANORMAL FN set fn.bddataprevcalculo = null;
 update VRHF_EMP_TFOLHATOMADOR FT set ft.bddataprevcalculo = null;
 update vrhf_emp_tc13sal c13 set c13.bddataprevcalculo = null;

  -- Antes de fazer os calculos deve fazer as rescisões
  update VRHF_EMP_TFOLHANORMAL FN set
    fn.bddatairrfesocial = (select first 1 coalesce(R.BDDATAPAGRESCISAO, R.BDDATARESCISAO) from VRH_EMP_TRESCISAO r where (FN.BDCODEMP = R.BDCODEMP and FN.BDCODCOL = R.BDCODCOL and FN.BDREFFN = R.BDREFRESCISAO)),
    fn.bdrefirrfesocial = (select first 1 coalesce(R.bdrefpagrescisao, R.bdrefrescisao) from VRH_EMP_TRESCISAO r where (FN.BDCODEMP = R.BDCODEMP and FN.BDCODCOL = R.BDCODCOL and FN.BDREFFN = R.BDREFRESCISAO)),
    fn.bddataprevcalculo = (select first 1 coalesce(R.BDDATAPAGRESCISAO, R.BDDATARESCISAO) from VRH_EMP_TRESCISAO r where (FN.BDCODEMP = R.BDCODEMP and FN.BDCODCOL = R.BDCODCOL and FN.BDREFFN = R.BDREFRESCISAO))
  where exists(select *
               from VRH_EMP_TRESCISAO R
               where (FN.BDCODEMP = R.BDCODEMP and
                     FN.BDCODCOL = R.BDCODCOL and
                     FN.BDREFFN = R.BDREFRESCISAO and
                     coalesce(R.BDDATAPAGRESCISAO, R.BDDATARESCISAO) is not null));


  update vrhf_emp_tfolhatomador FN set
    fn.bddatairrfesocial = (select first 1 coalesce(R.BDDATAPAGRESCISAO, R.BDDATARESCISAO) from VRH_EMP_TRESCISAO r where (FN.BDCODEMP = R.BDCODEMP and FN.BDCODCOL = R.BDCODCOL and FN.bdreftomador = R.BDREFRESCISAO)),
    fn.bdrefirrfesocial = (select first 1 coalesce(R.bdrefpagrescisao, R.bdrefrescisao) from VRH_EMP_TRESCISAO r where (FN.BDCODEMP = R.BDCODEMP and FN.BDCODCOL = R.BDCODCOL and FN.bdreftomador = R.BDREFRESCISAO)),
    fn.bddataprevcalculo = (select first 1 coalesce(R.BDDATAPAGRESCISAO, R.BDDATARESCISAO) from VRH_EMP_TRESCISAO r where (FN.BDCODEMP = R.BDCODEMP and FN.BDCODCOL = R.BDCODCOL and FN.bdreftomador = R.BDREFRESCISAO))
  where exists(select *
               from VRH_EMP_TRESCISAO R
               where (FN.BDCODEMP = R.BDCODEMP and
                     FN.BDCODCOL = R.BDCODCOL and
                     FN.bdreftomador = R.BDREFRESCISAO and
                     coalesce(R.BDDATAPAGRESCISAO, R.BDDATARESCISAO) is not null));

  -- Não deve carregar as tabelas que já tiverem registros
  wempant = 0;
  wrefmensal = 999999;
  for select BDCODEMP, BDREFFN
      from (select FN.BDCODEMP, FN.BDREFFN
            from VRHF_EMP_TFOLHANORMAL FN
            where fn.bddataprevcalculo is null
            union
            select FT.BDCODEMP, FT.BDREFTOMADOR
            from VRHF_EMP_TFOLHATOMADOR FT
            where ft.bddataprevcalculo is null
            union
            select c13.bdcodemp, c13.bdrefc13
            from vrhf_emp_tc13sal c13
            where c13.bddataprevcalculo is null
            )
            group by BDCODEMP, BDREFFN
            order by BDCODEMP, BDREFFN desc
     into :wcodemp, :wref do
     BEGIN
       if ((wcodemp <> wempant) or (wref < wrefmensal)) then
          begin
            wempant = wcodemp;

            SELECT FIRST 1 X.BDREFEMP, X.BDPAGEMP, X.BDPAGEMPCONTR
            FROM VRHF_BASE_TEMPCALC X
            WHERE X.BDCODEMP = :wcodemp  AND X.BDREFEMP <= :wref
            ORDER BY X.BDREFEMP DESC
              INTO :wrefmensal, :wpgtmespost, :wpgtmespostpro;
          end

        -- colaboradores
       if (wpgtmespost = 1) then
          begin
            SELECT CAST(SUBSTRING(:wref FROM 1 FOR 4)||'/'||SUBSTRING(:wref FROM 5 FOR 2)||'/'||ULTDIA AS DATE) AS ULTIMODIA
            FROM ULTIMO_DIA_MES(SUBSTRING(:wref FROM 5 FOR 2),SUBSTRING(:wref FROM 1 FOR 4))
            INTO :wdatapgto;
   
            FCONT = 0;
            WHILE (FCONT = 0) DO
              BEGIN
                SELECT CAST(EXTRACT(WEEKDAY FROM :wdatapgto) AS INTEGER) AS DIA_SEMANA
                FROM RDB$DATABASE
                INTO :FDIASEMANA;
   
                SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wcodemp, :wdatapgto)
                INTO :FFERIADO;
   
                IF ((FDIASEMANA = 0) OR (FDIASEMANA = 6) OR (FFERIADO = TRUE))  THEN
                  wdatapgto = wdatapgto - 1;
                ELSE
                  FCONT = 1;
              END
          end
       else
          begin
            SELECT CAST(SUBSTRING(BDREFERENCIA FROM 1 FOR 4)||'-'||SUBSTRING(BDREFERENCIA FROM 5 FOR 2)||'-01' AS DATE) AS DATA
            FROM INC_REFERENCIA(:wref,1)
            INTO :wdatapgto;
   
            FCONT = 0;
   
            WHILE (FCONT < 5) DO
              BEGIN
   
                SELECT FIRST 1 EXTRACT(WEEKDAY FROM :wdatapgto) FROM RDB$DATABASE
                INTO :FDIASEMANA;
   
                SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wcodemp, :wdatapgto)
                INTO :FFERIADO;
   
                IF ((FDIASEMANA <> 0) AND (FFERIADO = FALSE)) THEN
                  FCONT = FCONT + 1;
   
                IF (FCONT < 5) THEN
                  wdatapgto = wdatapgto + 1;
   
              END
   
            SELECT FIRST 1 EXTRACT(WEEKDAY FROM :wdatapgto) FROM RDB$DATABASE
            INTO :FDIASEMANA;
   
            IF (FDIASEMANA = 6) THEN
              wdatapgto = wdatapgto - 1;
   
            SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wcodemp, :wdatapgto)
            INTO :FFERIADO;
   
            IF (FFERIADO = TRUE) THEN
              wdatapgto = wdatapgto - 1;
          end
   
       select bdAAAAMM from AAAAMM(:wdatapgto) into :wrefpgt;
   
       if (wpgtmespost = wpgtmespostpro) then
          begin
            wdatapgtopro = wdatapgto;
            wrefpgtpro = wrefpgt;
          end
       else if (wpgtmespostpro = 1) then
          begin
            SELECT CAST(SUBSTRING(:wref FROM 1 FOR 4)||'/'||SUBSTRING(:wref FROM 5 FOR 2)||'/'||ULTDIA AS DATE) AS ULTIMODIA
            FROM ULTIMO_DIA_MES(SUBSTRING(:wref FROM 5 FOR 2),SUBSTRING(:wref FROM 1 FOR 4))
            INTO :wdatapgtopro;
   
            FCONT = 0;
            WHILE (FCONT = 0) DO
              BEGIN
                SELECT CAST(EXTRACT(WEEKDAY FROM :wdatapgtopro) AS INTEGER) AS DIA_SEMANA
                FROM RDB$DATABASE
                INTO :FDIASEMANA;
   
                SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wcodemp, :wdatapgtopro)
                INTO :FFERIADO;
   
                IF ((FDIASEMANA = 0) OR (FDIASEMANA = 6) OR (FFERIADO = TRUE))  THEN
                  wdatapgtopro = wdatapgtopro - 1;
                ELSE
                  FCONT = 1;
              END
          end
       else
          begin
            SELECT CAST(SUBSTRING(BDREFERENCIA FROM 1 FOR 4)||'-'||SUBSTRING(BDREFERENCIA FROM 5 FOR 2)||'-01' AS DATE) AS DATA
            FROM INC_REFERENCIA(:wref,1)
            INTO :wdatapgtopro;
   
            FCONT = 0;
   
            WHILE (FCONT < 5) DO
              BEGIN
   
                SELECT FIRST 1 EXTRACT(WEEKDAY FROM :wdatapgtopro) FROM RDB$DATABASE
                INTO :FDIASEMANA;
   
                SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wcodemp, :wdatapgtopro)
                INTO :FFERIADO;
   
                IF ((FDIASEMANA <> 0) AND (FFERIADO = FALSE)) THEN
                  FCONT = FCONT + 1;
   
                IF (FCONT < 5) THEN
                  wdatapgtopro = wdatapgtopro + 1;
   
              END
   
            SELECT FIRST 1 EXTRACT(WEEKDAY FROM :wdatapgtopro) FROM RDB$DATABASE
            INTO :FDIASEMANA;
   
            IF (FDIASEMANA = 6) THEN
              wdatapgtopro = wdatapgtopro - 1;
   
            SELECT BDFERIADO FROM SP_FERIADO_EMPRESA(:wcodemp, :wdatapgtopro)
            INTO :FFERIADO;
   
            IF (FFERIADO = TRUE) THEN
              wdatapgtopro = wdatapgtopro - 1;
          end

       select bdAAAAMM from AAAAMM(:wdatapgtopro) into :wrefpgtpro;

       wsqlnormal = 'update vrhf_emp_tfolhanormal fn set fn.bddatairrfesocial = '||''''||:wdatapgto||''''||
                                              ', fn.bdrefirrfesocial = '||:wrefpgt||
                                              ', fn.bddataprevcalculo = '||''''||:wdatapgto||''''||
                                              ' where fn.bddataprevcalculo is null'||
                                              ' and fn.bdcodemp ='||:wcodemp||
                                              ' and fn.bdreffn = '||:wref;
       wsqltomador = 'update vrhf_emp_tfolhatomador ft set ft.bddatairrfesocial = '||''''||:wdatapgto||''''||
                                              ', ft.bdrefirrfesocial = '||:wrefpgt||
                                              ', ft.bddataprevcalculo ='||''''||:wdatapgto||''''||
                                              ' where ft.bddataprevcalculo is null'||
                                              ' and ft.bdcodemp ='||:wcodemp||
                                              ' and ft.bdreftomador = '||:wref;

       wsqlcomp13folha = 'update VRHF_EMP_TC13SAL c13 set c13.bddatairrfesocial = '||''''||:wdatapgto||''''||
                                              ', c13.bdrefirrfesocial = '||:wrefpgt||
                                              ', c13.bddataprevcalculo ='||''''||:wdatapgto||''''||
                                              ' where c13.bddataprevcalculo is null'||
                                              ' and c13.bdcodemp ='||:wcodemp||
                                              ' and c13.BDREFC13 = '||:wref;

       if (wpgtmespost <> wpgtmespostpro) then
          begin
            /* Aplica Filtro Diferente prolaboristas */
           wsqlnormal = wsqlnormal||' and not exists ('||
                      '                  SELECT * FROM VRH_EMP_TCOLCON_VINC V'||
                      '                  join VRH_BASE_TCLASSE c on (v.bdcodcla = c.bdcodcla)'||
                      '                  WHERE V.BDCODEMP = '||:wcodemp||' and V.BDCODEMP = fn.bdcodemp AND V.BDCODCOL = fn.bdcodcol'||
                      '                  and c.BDGRUPOCLA = 2) ';

           wsqltomador = wsqltomador||' and not exists ('||
                      '                  SELECT * FROM VRH_EMP_TCOLCON_VINC V'||
                      '                  join VRH_BASE_TCLASSE c on (v.bdcodcla = c.bdcodcla)'||
                      '                  WHERE V.BDCODEMP = '||:wcodemp||' and V.BDCODEMP = ft.bdcodemp AND V.BDCODCOL = ft.bdcodcol'||
                      '                  and c.BDGRUPOCLA = 2) ';

           wsqlcomp13folha = wsqlcomp13folha||' and not exists ('||
                      '                  SELECT * FROM VRH_EMP_TCOLCON_VINC V'||
                      '                  join VRH_BASE_TCLASSE c on (v.bdcodcla = c.bdcodcla)'||
                      '                  WHERE V.BDCODEMP = '||:wcodemp||' and V.BDCODEMP = c13.bdcodemp AND V.BDCODCOL = c13.bdcodcol'||
                      '                  and c.BDGRUPOCLA = 2) ';
          end

       execute statement wsqlnormal;
       execute statement wsqltomador;
       execute statement wsqlcomp13folha;

       if (wpgtmespost <> wpgtmespostpro) then
          begin
            wsqlnormal = 'update vrhf_emp_tfolhanormal fn set fn.bddatairrfesocial = '||''''||:wdatapgtopro||''''||
                                                   ', fn.bdrefirrfesocial = '||:wrefpgtpro||
                                                   ', fn.bddataprevcalculo ='||''''||:wdatapgtopro||''''||
                                                   ' where fn.bddataprevcalculo is null'||
                                                   ' and fn.bdcodemp ='||:wcodemp||
                                                   ' and fn.bdreffn = '||:wref;
            wsqltomador = 'update vrhf_emp_tfolhatomador ft set ft.bddatairrfesocial = '||''''||:wdatapgtopro||''''||
                                                   ', ft.bdrefirrfesocial = '||:wrefpgtpro||
                                                   ', ft.bddataprevcalculo ='||''''||:wdatapgtopro||''''||
                                                   ' where ft.bddataprevcalculo is null'||
                                                   ' and ft.bdcodemp ='||:wcodemp||
                                                   ' and ft.bdreftomador = '||:wref;


            wsqlcomp13folha = 'update VRHF_EMP_TC13SAL c13 set c13.bddatairrfesocial = '||''''||:wdatapgto||''''||
                                                   ', c13.bdrefirrfesocial = '||:wrefpgt||
                                                   ', c13.bddataprevcalculo ='||''''||:wdatapgto||''''||
                                                   ' where c13.bddataprevcalculo is null'||
                                                   ' and c13.bdcodemp ='||:wcodemp||
                                                   ' and c13.BDREFC13 = '||:wref;
            -- Aplica Filtro prolaboristas
            /* Aplica Filtro Diferente prolaboristas */
           wsqlnormal = wsqlnormal||' and exists ('||
                      '                  SELECT * FROM VRH_EMP_TCOLCON_VINC V'||
                      '                  join VRH_BASE_TCLASSE c on (v.bdcodcla = c.bdcodcla)'||
                      '                  WHERE V.BDCODEMP = '||:wcodemp||' and V.BDCODEMP = fn.bdcodemp AND V.BDCODCOL = fn.bdcodcol'||
                      '                  and c.BDGRUPOCLA = 2) ';

           wsqltomador = wsqltomador||' and exists ('||
                      '                  SELECT * FROM VRH_EMP_TCOLCON_VINC V'||
                      '                  join VRH_BASE_TCLASSE c on (v.bdcodcla = c.bdcodcla)'||
                      '                  WHERE V.BDCODEMP = '||:wcodemp||' and V.BDCODEMP = ft.bdcodemp AND V.BDCODCOL = ft.bdcodcol'||
                      '                  and c.BDGRUPOCLA = 2) ';

           wsqlcomp13folha = wsqlcomp13folha||' and exists ('||
                      '                  SELECT * FROM VRH_EMP_TCOLCON_VINC V'||
                      '                  join VRH_BASE_TCLASSE c on (v.bdcodcla = c.bdcodcla)'||
                      '                  WHERE V.BDCODEMP = '||:wcodemp||' and V.BDCODEMP = c13.bdcodemp AND V.BDCODCOL = c13.bdcodcol'||
                      '                  and c.BDGRUPOCLA = 2) ';

            execute statement wsqlnormal;
            execute statement wsqltomador;
            execute statement wsqlcomp13folha;
          end

     END
end
^

create or alter procedure SP_VRH_UPDATE_DATA_IR_13
as
declare variable FDIASEMANA integer;
declare variable FCONT integer;
declare variable FFERIADO boolean;
declare variable WREFPGT integer;
declare variable WSQLNORMAL varchar(3000);
declare variable WDATAPGTO date;
declare variable WREF integer;
declare variable WCODEMP integer;
begin
  /* Procedure Text */
  --  suspend;
  -- N?o deve carregar as tabelas que j? tiverem registros
  for select BDCODEMP, BDREF13
      from (select FN.BDCODEMP, FN.BDREF13
            from VRHF_EMP_T13SAL FN)
      group by BDCODEMP, BDREF13
      order by BDCODEMP, BDREF13 desc
      into :WCODEMP, :WREF
  do
  begin
    -- colaboradores

    if (substring(:WREF from 5 for 2) = '12') then
       begin
         SELECT CAST(substring(:WREF from 1 for 4)||'/'||substring(:WREF from 5 for 2)||'/'||20 AS DATE) AS DATAPGTO
          FROM RDB$DATABASE
         INTO :wdatapgto;
       end
    else
       begin
         select cast(substring(:WREF from 1 for 4) || '/' || substring(:WREF from 5 for 2) || '/' || ULTDIA as date) as ULTIMODIA
         from ULTIMO_DIA_MES(substring(:WREF from 5 for 2), substring(:WREF from 1 for 4))
         into :WDATAPGTO;
       end

    FCONT = 0;
    while (FCONT = 0) do
    begin
      select cast(extract(weekday from :WDATAPGTO) as integer) as DIA_SEMANA
      from RDB$DATABASE
      into :FDIASEMANA;

      select BDFERIADO
      from SP_FERIADO_EMPRESA(:WCODEMP, :WDATAPGTO)
      into :FFERIADO;

      if ((FDIASEMANA = 0) or (FDIASEMANA = 6) or (FFERIADO = true)) then
        WDATAPGTO = WDATAPGTO - 1;
      else
        FCONT = 1;
    end

    select BDAAAAMM
    from AAAAMM(:WDATAPGTO)
    into :WREFPGT;

    WSQLNORMAL = 'update vrhf_emp_t13sal fn set fn.bddatairrfesocial = ' || '''' || :WDATAPGTO || '''' ||
                  ', fn.bdrefirrfesocial = ' || :WREFPGT ||
                  ' where fn.bddatairrfesocial is null' || ' and fn.bdcodemp =' || :WCODEMP || ' and fn.BDREF13 = ' || :WREF;

    execute statement WSQLNORMAL;
  end
end
^

/*#191959 | Título: S-1210 PELA BAIXA DE CALCULO em competencia posterior - Nathan de Faria */
create or alter procedure SP_ESOCIAL_TVINCULO_FOL_S1210 (
    PRBDMULTIEMP varchar(5000),
    PRBDCODEMP integer,
    PRBDCODCOL integer,
    PRBDCODTER integer,
    PRBDREF integer,
    PRCPF DM_CNPJ_CPF = null /* COLLATE WIN1252 - default */ ,
    PRIMPORTACAOFICHA boolean = false,
    PREXPORTACAOMANUAL boolean = false,
    PRDOWNLOAD boolean = false)
returns (
    BDCODTERINI integer,
    BDCODCOLINI integer,
    BDCODEMPINI integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODTER integer)
as
declare variable VBDCPFCOL varchar(15);
declare variable VBDCPFTER varchar(15);
declare variable VSQL varchar(30000);
declare variable VSQLSELECT varchar(30000);
declare variable VMEITER DM_BOOLEAN;
declare variable WPAGAMENTO integer;
declare variable WTRANSFERENCIA integer;
declare variable WDTPAG varchar(15);
declare variable WDTRESC varchar(15);
declare variable WTEMTRANS integer;
declare variable WCPFSEMCARAC varchar(14);
declare variable WCODEMP integer;
begin
    bdcodcolini = coalesce(prbdcodcol,0);
    bdcodempini = coalesce(prbdcodemp,0);
    BDCODTERINI = coalesce(prbdcodter,0);
    

    vmeiter = 'FALSE';

    if (PRCPF IS NOT NULL) then
       begin
         VBDCPFCOL = prcpf;
       end
    else
       begin
         WTRANSFERENCIA = 0;
         VSQL = ' select BDPAGEMP from VW_VRHF_BASE_TEMPCALC where BDCODEMP = '||:PRBDCODEMP;
         execute statement VSQL into :WPAGAMENTO;
     
         if (WPAGAMENTO = 0) then
         begin
             VSQL = ' select BDCODCOL, BDCODCOLORIG from VW_VRH_EMP_TTRANSCOL_DESTINO where BDCODEMPORIG = '||:PRBDCODEMP||' and BDCODCOLORIG = '||:PRBDCODCOL;
             execute statement VSQL into :WTRANSFERENCIA, :WTEMTRANS;
         
             if (COALESCE(WTRANSFERENCIA, 0) > 0) then
             begin
                VSQL =  'select first 1  BDDATAPAG from '||
                        ' (select  first 1  BDDATAPGTOFN as BDDATAPAG '||
                         ' from VRHF_EMP_TFOLHANORMAL '||
                         ' where BDCODEMP = '||:PRBDCODEMP||' and BDCODCOL = '||:PRBDCODCOL||' and EXTRACT(YEAR FROM BDDATAPGTOFN) * 100 + EXTRACT(MONTH FROM BDDATAPGTOFN) = '||:PRBDREF||
                         ' union all '||
                         ' select first 1 BDDATAPGTOFT as BDDATAPAG '||
                         ' from VRHF_EMP_TFOLHATOMADOR '||
                         ' where BDCODEMP = '||:PRBDCODEMP||' and BDCODCOL = '||:PRBDCODCOL||' and EXTRACT(YEAR FROM BDDATAPGTOFT) * 100 + EXTRACT(MONTH FROM BDDATAPGTOFT) = '||:PRBDREF||')';
                 execute statement VSQL into :WDTPAG;
     
                 if (WDTPAG is not null) then
                     WDTPAG = ''''||WDTPAG||'''';
             end
         end
     
     
         VSQL = 'select BDDATARESCISAO from VW_RESCISAO '||
                'where BDCODEMP = '||PRBDCODEMP||' and BDCODCOL ='||PRBDCODCOL||' and EXTRACT(YEAR FROM BDDATAPAGRESCISAO) || RIGHT(''0'' || EXTRACT(MONTH FROM BDDATAPAGRESCISAO), 2)= '||PRBDREF;
         execute statement VSQL into:WDTRESC;
     
     
         if (PRBDCODTER <> 0) then
         begin
             vsql = 'select first 1 RH.BDCPFMEITER from TTERCEIRO_RH RH where RH.BDCODTER = ' || PRBDCODTER || ' and char_length(RH.BDCPFMEITER) = 14';
             execute statement VSQL into VBDCPFCOL;
         
                if (WDTPAG is not null) then
                    WDTPAG = ''''||WDTPAG||'''';
            end

         
         
        VSQL = 'select BDDATARESCISAO from VW_RESCISAO '||
               'where BDCODEMP = '||PRBDCODEMP||' and BDCODCOL ='||PRBDCODCOL||' and EXTRACT(YEAR FROM BDDATAPAGRESCISAO) || RIGHT(''0'' || EXTRACT(MONTH FROM BDDATAPAGRESCISAO), 2)<= '||PRBDREF;
        execute statement VSQL into:WDTRESC;
       end
         
        if ((PRBDCODTER <> 0) and (VBDCPFCOL is null)) then
        begin
            vsql = 'select first 1 RH.BDCPFMEITER from TTERCEIRO_RH RH where RH.BDCODTER = ' || PRBDCODTER || ' and char_length(RH.BDCPFMEITER) = 14';
            execute statement VSQL into VBDCPFCOL;
        
             if (VBDCPFCOL <> '') then
                 vmeiter = 'TRUE';
             else
             begin
               vsql = 'select first 1 C.BDCGCTER from TTERCEIRO C where C.BDCODTER = ' || PRBDCODTER;
               execute statement VSQL into VBDCPFCOL;
             end
         end

    if ((VBDCPFCOL is null) or (VBDCPFCOL=''))  then
    begin
        if ((PRBDMULTIEMP <> '') and (PRBDCODCOL <> 0)) then
        begin
          vsql = 'select first 1 C.BDCPFCOL from VRH_EMP_TCOLCON C where C.BDCODEMP = ' || PRBDCODEMP || ' and C.BDCODCOL = ' || PRBDCODCOL;
          execute statement VSQL into VBDCPFCOL;
        end
    end

    if (VBDCPFCOL <> '') then
    begin
        --A regra toda definida pelo order by
          
        vsql = 'select first 1 V.BDCODEMP, V.BDCODCOL ';

--        if (vmeiter = 'FALSE') then
--            vsql = vsql ||' T.BDCODTER ';
--        else
--            vsql = vsql ||' RH.BDCODTER ';
        
        vsql = vsql ||'from (select C.BDCODEMP, C.BDCODCOL, coalesce(TRANSDE.BDDATATRF, R.BDDATARESCISAO,C.BDDATAADMCOL)BDDATAADMCOL, 0 BDCODIGO, 1 BDTIPO, R.BDDATARESCISAO, coalesce(Cast (bddatarescisao as date),Cast (current_timestamp as date)+1)BDDATARESCISAOorder ' ||
                      'from VRH_EMP_TCOLCON C ' ||
                      'left outer join VRH_EMP_TRESCISAO R on R.BDCODEMP = C.BDCODEMP and R.BDCODCOL = C.BDCODCOL ' ||
                      'left outer join VRH_EMP_TTRANSCOL TRANS on TRANS.BDCODEMPORIG = C.BDCODEMP and TRANS.BDCODCOLORIG = C.BDCODCOL ' ||
                      'left outer join VRH_EMP_TTRANSCOL TRANSDE on TRANSDE.BDCODEMPDEST = C.BDCODEMP and TRANSDE.bdcodcoldest = C.BDCODCOL ' ||
                      'left outer join VRH_BASE_TPREPRESC P on P.BDCODPRES = TRANS.BDCODPTRAN or P.BDCODPRES = R.BDCODPRES ' ||
                      'left outer join VRH_EMP_TCOLCON_PARTIDA PR on PR.BDCODEMP = C.BDCODEMP and PR.BDCODCOL = C.BDCODCOL ' ||
                      'left outer join VRH_EMP_TCOLCON_VINC CLA on (CLA.BDCODEMP = C.BDCODEMP and CLA.BDCODCOL = C.BDCODCOL and ' ||
                                                                           'CLA.BDREFCOL = (select max(BDREFCOL) BDREFCOL ' ||
                                                                                           'from VRH_EMP_TCOLCON_VINC ' ||
                                                                                           'where BDCODEMP = C.BDCODEMP and ' ||
                                                                                                 'BDCODCOL = C.BDCODCOL and ' ||
                                                                                                 'BDREFCOL <= '||PRBDREF||')) ' ||
                      'left outer join VRH_BASE_TCLASSE CLASS on (CLASS.BDCODCLA = CLA.BDCODCLA) ' ||
                      'where C.BDCODEMP in (' || PRBDMULTIEMP || ') and ' ||
                      'C.BDCPFCOL like '''|| VBDCPFCOL ||''' and ' ||
                      'Coalesce(CLASS.BDGRUPOCLA,0) <> 12 and '  ||

        -- Data de Admiss?
        ' ((select BDDATA from SP_PARSE_DATE(C.BDDATAADMCOL, ''YYYYMM'')) <= '||PRBDREF||')  ';
        if (not PRDOWNLOAD) then
           begin
       -- Data de Transfer?ia
        vsql = vsql||  ' and ((select BDDATA from SP_PARSE_DATE(PR.BDDATATRFCOL,''YYYYMM'')) <= '||PRBDREF||' or (PR.BDDATATRFCOL is null))  '
         -- Data de Rescis?
              ||' and ((R.BDDATARESCISAO is null) or ((select BDDATA from SP_PARSE_DATE('||COALESCE(WDTPAG,'R.BDDATAPAGRESCISAO')||', ''YYYYMM'')) >= '||PRBDREF||') or ';
        -- Transferência para matriz não cadastrada no sistema
        if (coalesce(WTEMTRANS, 0) > 0)  then
            vsql = vsql||' (exists(select T.BDCODEMPORIG, T.BDCODCOLORIG from VRH_EMP_TTRANSCOL T left outer join TEMPRESAS E on E.BDCODEMP = T.BDCODEMPORIG where T.BDCODEMPORIG = C.BDCODEMP and T.BDCODCOLORIG = C.BDCODCOL and coalesce(E.BDMATRIZNAOCADSIS, ''FALSE'') = ''TRUE'' and ((select BDDATA from SP_PARSE_DATE(T.BDDATATRF, ''YYYYMM'')) <='||PRBDREF||'))) or ';

        -- Folhas posteriores ao desligamento
        vsql = vsql||'((';
        if (not primportacaoficha) then
           begin
             vsql = vsql||' (exists(select first 1 FC.BDCODCOL from VRHF_EMP_TFOLHACOMP FC where FC.BDCODEMP = C.BDCODEMP and FC.BDCODCOL = C.BDCODCOL and FC.BDREFIRRFESOCIAL = '||PRBDREF||
                     ' union all '||
                     ' select first 1 FC.BDCODCOL from VRHF_EMP_TFOLTOMCOMP FC where FC.BDCODEMP = C.BDCODEMP and FC.BDCODCOL = C.BDCODCOL and FC.BDREFIRRFESOCIAL = '||PRBDREF||
                     ' union all '||
                     ' select first 1 FC.BDCODCOL from VRHF_EMP_TFOLHACOMPINT FC where FC.BDCODEMP = C.BDCODEMP and FC.BDCODCOL = C.BDCODCOL  and FC.BDREFIRRFESOCIAL = '||PRBDREF||
                     ' union all '||
                     ' select first 1 FC.BDCODCOL from VRHF_EMP_TFOLTOMCOMPINT FC where FC.BDCODEMP = C.BDCODEMP and FC.BDCODCOL = C.BDCODCOL and FC.BDREFIRRFESOCIAL = '||PRBDREF||
                     ' union all '||
                     ' select first 1 ES.BDCODCOL from TFOLHAPGTOESOCIAL ES '||
                     ' left join VRH_ESOCIAL_TSINCRONIZACAO e on ES.BDCODEMP = E.BDCODEMP '||
                     ' left outer join VRH_EMP_TRESCISAO R on R.BDCODEMP = C.BDCODEMP and R.BDCODCOL = C.BDCODCOL '||
                     ' left join VRH_BASE_TPREPRESC P on R.bdcodpres=p.bdcodpres ' ||
                     ' where ES.BDCODEMP = C.BDCODEMP and ES.BDCODCOL = C.BDCODCOL and '||
                     '       (E.BDREFINISINC is null or E.BDREFINISINC <= '||PRBDREF|| ')'||
                     '       and ((es.BDDATAPGTO is null) or '||
                     '            ((select BDDATA from SP_PARSE_DATE(es.BDDATAPGTO, ''YYYYMM'')) >= '||PRBDREF||')) and'||
                     '        ((R.BDDATARESCISAO is null) or ((select BDDATA ' ||
                     '                        from SP_PARSE_DATE(R.BDDATAPAGRESCISAO, ''YYYYMM'')) >= '||PRBDREF||') or  (p.bdcodmcag=80)) ' ||
                     ' union all ' ||
                          ' select first 1 FA.BDCODCOL from VRHF_EMP_TFOLHAAVULSA FA where FA.BDCODEMP = C.BDCODEMP and FA.BDCODCOL = C.BDCODCOL and FA.BDDATAFA > R.BDDATAPAGRESCISAO and FA.BDREF = '||PRBDREF||')) and';
           end

        vsql = vsql||' ((P.BDCODMOTESRESC <> 99) or '||
                     ' (exists (select * from VRH_EMP_TRESCISAO RESC where RESC.BDCODEMP = TRANS.BDCODEMPDEST and RESC.BDCODCOL = TRANS.BDCODCOLDEST and '||
                                                                  ' (select BDDATA from SP_PARSE_DATE(R.BDDATAPAGRESCISAO, ''YYYYMM'')) <='||PRBDREF||'))))))       ' ;
         end

           vsql = vsql||   '     union all   select A.BDCODEMP, A.BDCODCOL, C.BDDATAADMCOL, A.BDCODIGO, 1, 0,0 ' ||
                     '       from VRH_ESOCIAL_TARQUIVO A ' ||
                     '       inner join VRH_EMP_TCOLCON C on C.BDCODEMP = A.BDCODEMP and C.BDCODCOL = A.BDCODCOL ' ||
                     '       left outer join VRH_EMP_TRESCISAO R on R.BDCODEMP = C.BDCODEMP and R.BDCODCOL = C.BDCODCOL' ||
                     '       where A.BDCODEMP in (' || PRBDMULTIEMP || ') and ' ||
                     '             C.BDCPFCOL like '''|| VBDCPFCOL ||''' and ' ||
                     '             (select BDDATA from SP_PARSE_DATE(C.BDDATAADMCOL, ''YYYYMM'')) <= '||PRBDREF||' and '||
                     '             A.BDREFARQ = '||PRBDREF||' and ' ||
                     '             A.BDSTATUS = 2 and A.bdcodtipo = 14 and' ||
                     '           ((R.BDDATARESCISAO is null) or '||
                     '            ((select BDDATA from SP_PARSE_DATE(R.BDDATAPAGRESCISAO, ''YYYYMM'')) >= '||PRBDREF||')) '||
                     '             union all '||
                     '             select TIMP.BDCODEMP, 0, null, 0, 2, 0, 0 '||
                     '             from TFOLHAPGTOESOCIAL TIMP '||
                     '             inner join TTERCEIRO T on T.BDCODTER = TIMP.BDCODTER and '||
                     '             T.BDCGCTER like '''|| VBDCPFCOL ||''' '||
                     '             where TIMP.BDCODEMP in (' || PRBDMULTIEMP || ') and ' ||
                     '             TIMP.bdrefevtpagto = '|| PRBDREF||
                     '       union all ' ||
                     '       select TC.BDCODEMP, 0, null, 0, 2, 0 ,0' ||
                     '       from VRHF_BASE_CALC_TERC TC ' ||
                     '       left join VRH_BASE_TSERVTERC SER on TC.BDCODEMP = SER.BDCODEMP and TC.BDCODTER = SER.BDCODTER and TC.BDCODSERV = SER.BDCODSERV';

        if (vmeiter = 'FALSE') then
            vsql = vsql || '       inner join TTERCEIRO T on T.BDCODTER = TC.BDCODTER and T.BDCGCTER like '''|| VBDCPFCOL ||''' ';
        else
            vsql = vsql || '       inner join TTERCEIRO_RH RH on RH.BDCODTER = TC.BDCODTER and RH.BDCPFMEITER like '''|| VBDCPFCOL ||''' ';
        
        vsql = vsql || '       where TC.BDCODEMP in (' || PRBDMULTIEMP || ') and ';
        vsql = vsql || '          TC.BDREFIRRFESOCIAL = '||PRBDREF||' ';
        vsql = vsql || '       union all ' ||
                       '       select A.BDCODEMP, A.BDCODCOL, null, A.BDCODIGO, 2, 0,0 ' ||
                       '       from VRH_ESOCIAL_TARQUIVO A ';

        if (vmeiter = 'FALSE') then
            vsql = vsql || '       inner join TTERCEIRO T on T.BDCODTER = A.BDCODTER ';
        else
            vsql = vsql || '       inner join TTERCEIRO_RH RH on RH.bdcodter = A.BDCODTER ';
        
        vsql = vsql || '      where A.BDCODEMP in (' || PRBDMULTIEMP || ') and ';
        
        if (vmeiter = 'FALSE') then
            vsql = vsql || '             T.BDCGCTER like '''|| VBDCPFCOL ||''' and ';
        else
            vsql = vsql || '             RH.BDCPFMEITER like '''|| VBDCPFCOL ||''' and ';

        vsql = vsql || '             A.BDREFARQ = '||PRBDREF||' and ' ||
                       '             A.BDSTATUS = 2 and A.BDCODTIPO = 14) V ' ||
                       'inner join TEMPRESAS E on E.BDCODEMP = V.BDCODEMP '||
                       'left join VW_TEMPRESAS_REF EMPREF on E.BDCODEMP = EMPREF.BDCODEMP ';

--        if (vmeiter = 'FALSE') then
--            vsql = vsql || 'left outer join TTERCEIRO T on T.BDCGCTER like '''|| VBDCPFCOL ||'''' ||
--                           ' join VRHF_BASE_CALC_TERC TC on T.BDCODTER = TC.BDCODTER and TC.BDCODEMP in (' || PRBDMULTIEMP || ') ';
--
--        else
--            vsql = vsql || 'left outer join TTERCEIRO_RH RH on RH.BDCPFMEITER like '''|| VBDCPFCOL ||'''' ||
--                           ' join VRHF_BASE_CALC_TERC TC on RH.BDCODTER = TC.BDCODTER and TC.BDCODEMP in (' || PRBDMULTIEMP || ') ';
--
--        vsql = vsql || '       and TC.BDREFIRRFESOCIAL = '||PRBDREF||' ';
--        vsql = vsql || 'left join VRH_BASE_TSERVTERC SER on TC.BDCODEMP = SER.BDCODEMP and TC.BDCODTER = SER.BDCODTER and TC.BDCODSERV = SER.BDCODSERV ';
--        vsql = vsql || '          and SER.BDREFSERV = '||PRBDREF||' ';

        if (not prexportacaomanual) then
           vsql = vsql || 'where COALESCE(E.BDSITUACAOESOCIAL, 0) = 1 ';

        vsql = vsql || ' order by v.BDDATARESCISAOORDER desc, V.BDDATAADMCOL desc, V.BDCODIGO desc, BDTIPO, coalesce(E.BDCODMATRIZ, 0), V.BDCODCOL desc, E.BDDATAINIATIVEMP';

        execute statement VSQL into BDCODEMP, BDCODCOL;
    end

--Ao procurar os autônomos, verifica se já tem evento pra aquele CPF na referência. Se tiver, utiliza o código de autônomo do evento
    VSQLSelect =   'select first 1 Coalesce(V.BDCODEMP,PGT.BDCODEMP) BDCODEMP,  Coalesce(V.BDCODTER,PGT.bdcodter) BDCODTER '||
                   '  from TEMPRESAS E ';
 Select BDRETORNO from RETIRA_CHAR_ESPECIAL(:VBDCPFCOL) into :WCPFSEMCARAC;

    vsql = vsqlselect ||' left outer join (select A.BDCODEMP, A.BDCODTER ' ||
                                         ' from VRH_ESOCIAL_TARQUIVO A ';
    
                   if (vmeiter = 'FALSE') then
                     vsql = vsql || ' inner join TTERCEIRO T on T.BDCODTER = A.BDCODTER ';
                   else
                     vsql = vsql || ' inner join TTERCEIRO_RH RH on RH.bdcodter = A.BDCODTER ';
    
                   vsql = vsql || ' where A.BDCODEMP in (' || PRBDMULTIEMP || ') and ';
    
                   if (vmeiter = 'FALSE') then
                     vsql = vsql || ' T.BDCGCTER like '''|| VBDCPFCOL ||''' and ';
                   else
                     vsql = vsql || ' RH.BDCPFMEITER like '''|| VBDCPFCOL ||''' and ';
    
             vsql = vsql || '  A.BDREFARQ = '||PRBDREF||' and ' ||
                   '  A.BDSTATUS = 2 and ' ||
                   '  A.BDCODTIPO = 14 ) V on V.BDCODEMP = E.BDCODEMP ';

             vsql = vsql || 'left outer join(select first 1 PGTO.BDCODEMP, coalesce(PGTO.BDCODTER, T.BDCODTER) BDCODTER '||
                ' from TFOLHAPGTOESOCIAL PGTO'||
                ' join TTERCEIRO T on T.BDCGCTER like '''|| VBDCPFCOL ||''' '||
                ' where BDCODEMP in ('||PRBDMULTIEMP||') and '||
                '      ((BDCPF = '''||WCPFSEMCARAC||''') or (BDCPF = '''||VBDCPFCOL||''')) and ' ||
                '      ((BDDATAPGTO is null) or ((select *'||
                '                                 from SP_PARSE_DATE(BDDATAPGTO, ''YYYYMM'')) = '||PRBDREF||')) '||
                ' order by BDCODTER desc) PGT on PGT.BDCODEMP = E.BDCODEMP ';
          execute statement VSQL into :WCODEMP, BDCODTER;

   if (BDCODEMP is null) then
     BDCODEMP = :WCODEMP;


   if (BDCODTER is null) then
      begin
        vsql = ' select first 1 V.BDCODEMP BDCODEMP, V.BDCODTER BDCODTER '||
                              '  from ( select TC.BDCODTER, TC.BDCODEMP  '||
                                            ' from VRHF_BASE_CALC_TERC TC ';
        
        if (vmeiter = 'FALSE') then
          vsql = vsql ||' join TTERCEIRO T on T.BDCODTER = TC.BDCODTER and T.BDCGCTER like '''|| VBDCPFCOL ||''' ';
        else
          vsql = vsql ||' join TTERCEIRO_RH RH on RH.BDCODTER = TC.BDCODTER and RH.BDCPFMEITER like '''|| VBDCPFCOL ||''' ';
          vsql = vsql ||' where TC.BDCODEMP in (' || PRBDMULTIEMP || ') and  '||
                                ' TC.BDREFIRRFESOCIAL = '||PRBDREF||') V '||
                                ' left outer join TEMPRESAS E on V.BDCODEMP = E.BDCODEMP  '||
                                ' where COALESCE(E.BDSITUACAOESOCIAL, 0) = 1 and V.BDCODEMP in ('||PRBDMULTIEMP||')';

        execute statement VSQL into :WCODEMP, BDCODTER;

       end


    if (BDCODEMP is null) then
      BDCODEMP = WCODEMP;


    if ((PRBDCODTER <> 0) and (PRBDCODCOL <> 0)) then
    begin
        vsql = 'select first 1 RH.BDCPFMEITER from TTERCEIRO_RH RH where RH.BDCODTER = ' || PRBDCODTER || ' and char_length(RH.BDCPFMEITER) = 14';
        execute statement VSQL into VBDCPFTER;
        
        if (VBDCPFTER is null) then
        begin
            vsql = 'select first 1 C.BDCGCTER from TTERCEIRO C where C.BDCODTER = ' || PRBDCODTER;
            execute statement VSQL into VBDCPFTER;
        end
        
        vsql = 'select first 1 C.BDCPFCOL from VRH_EMP_TCOLCON C where C.BDCODEMP = ' || PRBDCODEMP || ' and C.BDCODCOL = ' || PRBDCODCOL;
        execute statement VSQL into VBDCPFCOL;
        
        if (VBDCPFTER <> VBDCPFCOL) then
            BDCODCOL = 0;
    end

   if (bdcodemp is null) then
      bdcodemp = prbdcodemp;

   if ((primportacaoficha) and (BDCODTER is null)) then
      begin
        vsql = 'select first 1 t.bdcodter from TTERCEIRO T where t.bdcgcter like '''|| VBDCPFCOL ||''' ';
        execute statement vsql into bdcodter;
      end

  -- #238506 Feito o tratamento abaixo para quando a referência de pagamento da rescisão for anterior a baixa de cálculo ele retornar os códigos que foram passados por parâmetro porque os selects acima não encontram registro
  if ((COALESCE(BDCODCOL, 0) = 0) and (COALESCE(BDCODTER, 0) = 0)) then
     begin
       BDCODCOL = PRBDCODCOL;
       BDCODTER = PRBDCODTER;
     end

  suspend;
end^


create or alter procedure VRH_SP_CALC_TERC (
    PRCODEMP varchar(10000),
    PRCPFTER varchar(18),
    PRREF integer)
returns (
    BDTIPO varchar(2),
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDREFAUXV numeric(18,6),
    BDREFVR numeric(18,6),
    BDVAL numeric(18,6),
    BDCLAVER varchar(20),
    BDTIPOREFVER integer,
    BDHEVER numeric(18,6),
    BDINSCLOTACAO varchar(50),
    BDMATRICULA varchar(50),
    BDCODLOTACAO varchar(50),
    BDTIPOESTAB integer,
    BDINDSIMPLES integer,
    BDCODCLATRI integer,
    BDREFDEMONSTRATIVO integer,
    BDDATASERV date,
    BDDATAFOLHA date,
    BDDATAINISERVTI date,
    BDCODSERV integer,
    BDCATEGORIAESOCIAL integer,
    BDGRAUEXP integer,
    BDNATOCUP integer,
    BDCODCONTTI integer,
    BDDATARESCISAO date,
    BDDOCPRINCIPAL varchar(50),
    BDDOCAUX varchar(50),
    BDTIPOCAEPF integer,
    BDCAEPF varchar(50),
    BDTRIBUTACAOEXTERIOR integer,
    BDCODINCIDIRRF integer)
as
declare variable WSQL varchar(32700);
declare variable WSQL2 varchar(32700);
declare variable WDIA integer;
declare variable WMES integer;
declare variable WANO integer;
declare variable WPRIDIA date;
declare variable WULTDIA date;
declare variable WCODTER integer;
declare variable WCPFTER varchar(18);
begin
  /*SP criada pra melhoria de performance ao buscar os c??lculos de aut??nomos pra gera????o de eventos de remunera????o*/

  wMES = SUBSTRING(CAST(:prREF AS VARCHAR(6)) FROM 5 FOR 2) ;
  wANO = CAST(SUBSTRING(CAST(:prREF AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
  wsql = 'SELECT ULTDIA FROM ultimo_DIA_MES('||:wMES||', '||:wANO||')';
  execute statement wsql INTO :wDIA;
  wCpfTer =  PRCPFTER;

  wPRIDIA = wMES||'/'||'01'||'/'||wANO;
  wULTDIA = wMES||'/'||wDIA||'/'||wANO;

  WSQL = ' select BDCODTER  '||
           ' from TTERCEIRO_RH '||
           ' where BDCPFMEITER = '''|| wCpfTer ||''''||
           ' union '||
           ' select BDCODTER '||
           ' from TTERCEIRO '||
           ' where BDCGCTER = '''||wCpfTer||''''||
           ' union '||
           ' select BDCODTER '||
           ' from TTERCEIRO_REF  '||
           ' where ((BDCGCTER = '''||wCpfTer||''') or (BDCPFPROD = '''||wCpfTer||''')) and '||
           '       BDREFEMP = (select max(BDREFEMP)  '||
           '                   from TTERCEIRO_REF    '||
           '                   where ((BDCGCTER = '''||wCpfTer||''') or (BDCPFPROD = '''||wCpfTer||''')) and '||
           '                         BDREFEMP <= '||:prREF||')';


  for execute statement WSQL into wCODTER do
  begin
    wsql2 =    'select ''FN'' BDTIPO, SER.BDCODEMP, SER.BDCODTER BDCODCOL, CAL.BDCODVER, CAL.BDREFAUXILIAR BDREFAUXV,  '||
               ' CAL.BDREFERENCIA BDREFVR, CAL.BDVALOR BDVAL, VER.BDCLAVER, VERR.BDTIPOREFVER, VERR.BDHEVER, '||
               ' coalesce(TPCC.BDCODESTAB, EMP.BDCODESTAB, MAT.BDCODESTAB) BDINSCLOTACAO, RH.BDMATRICULATERC BDMATRICULA, '||
               ' case '||
                 ' when TPCC.BDCODLOTACAO is not null and TPCC.BDCODLOTACAO <> '''' then TPCC.BDCODLOTACAO '||
                 ' when EMP.BDCODLOTACAO is not null and EMP.BDCODLOTACAO <> '''' then EMP.BDCODLOTACAO  '||
                 ' else MAT.BDCODLOTACAO '||
               ' end BDCODLOTACAO, '||
               ' case '||
                 ' when TPCC.BDCODLOTACAO is not null and TPCC.BDCODLOTACAO <> '''' then 3 '||
                 ' when EMP.BDCODLOTACAO is not null and EMP.BDCODLOTACAO <> '''' then 2 '||
                 ' else 1 '||
               ' end BDTIPOESTAB, '||
               ' case '||
                 ' when (TPCC.BDCODLOT > 0 and coalesce(TPCC.BDCODLOTACAO, '''') <> '''') or (TPCC.BDCNPJTOM = coalesce(MAT.BDCNPJEMP, EMP.BDCNPJEMP)) then case '||
                                                                                                                                                       ' when coalesce(GPSTOM.BDANEXOIV, ''FALSE'') = ''TRUE'' and coalesce(GPSTOM.BDCOMERCIO, ''FALSE'') = ''FALSE'' and coalesce(GPSTOM.BDINDUSTRIA, ''FALSE'') = ''FALSE'' and coalesce(GPSTOM.BDANEXOIII, ''FALSE'') = ''FALSE'' and coalesce(GPSTOM.BDANEXOV, ''FALSE'') = ''FALSE'' and coalesce(GPSTOM.BDANEXOVI, ''FALSE'') = ''FALSE'' then 2  '||
                                                                                                                                                       ' when coalesce(GPSTOM.BDANEXOIV, ''FALSE'') = ''TRUE'' and (coalesce(GPSTOM.BDCOMERCIO, ''FALSE'') = ''TRUE'' or coalesce(GPSTOM.BDINDUSTRIA, ''FALSE'') = ''TRUE'' or coalesce(GPSTOM.BDANEXOIII, ''FALSE'') = ''TRUE'' or coalesce(GPSTOM.BDANEXOV, ''FALSE'') = ''TRUE'' or coalesce(GPSTOM.BDANEXOVI, ''FALSE'') = ''TRUE'') then 3 '||
                                                                                                                                                       ' when coalesce(GPSTOM.BDANEXOIV, ''FALSE'') = ''FALSE'' and (coalesce(GPSTOM.BDCOMERCIO, ''FALSE'') = ''TRUE'' or coalesce(GPSTOM.BDINDUSTRIA, ''FALSE'') = ''TRUE'' or coalesce(GPSTOM.BDANEXOIII, ''FALSE'') = ''TRUE'' or coalesce(GPSTOM.BDANEXOV, ''FALSE'') = ''TRUE'' or coalesce(GPSTOM.BDANEXOVI, ''FALSE'') = ''TRUE'') then 1 '||
                                                                                                                                                      ' end '||
                 ' when coalesce(EMP.BDCODLOTACAO, '''') <> '''' then case '||
                                                                 ' when coalesce(GPSA.BDANEXOIV, ''FALSE'') = ''TRUE'' and coalesce(GPSA.BDCOMERCIO, ''FALSE'') = ''FALSE'' and coalesce(GPSA.BDINDUSTRIA, ''FALSE'') = ''FALSE'' and coalesce(GPSA.BDANEXOIII, ''FALSE'') = ''FALSE'' and coalesce(GPSA.BDANEXOV, ''FALSE'') = ''FALSE'' and coalesce(GPSA.BDANEXOVI, ''FALSE'') = ''FALSE'' then 2 '||
                                                                 ' when coalesce(GPSA.BDANEXOIV, ''FALSE'') = ''TRUE'' and (coalesce(GPSA.BDCOMERCIO, ''FALSE'') = ''TRUE'' or coalesce(GPSA.BDINDUSTRIA, ''FALSE'') = ''TRUE'' or coalesce(GPSA.BDANEXOIII, ''FALSE'') = ''TRUE'' or coalesce(GPSA.BDANEXOV, ''FALSE'') = ''TRUE'' or coalesce(GPSA.BDANEXOVI, ''FALSE'') = ''TRUE'') then 3 '||
                                                                 ' when coalesce(GPSA.BDANEXOIV, ''FALSE'') = ''FALSE'' and (coalesce(GPSA.BDCOMERCIO, ''FALSE'') = ''TRUE'' or coalesce(GPSA.BDINDUSTRIA, ''FALSE'') = ''TRUE'' or coalesce(GPSA.BDANEXOIII, ''FALSE'') = ''TRUE'' or coalesce(GPSA.BDANEXOV, ''FALSE'') = ''TRUE'' or coalesce(GPSA.BDANEXOVI, ''FALSE'') = ''TRUE'') then 1 '||
                                                                ' end '||
                 ' else case '||
                        ' when coalesce(GPSAM.BDANEXOIV, ''FALSE'') = ''TRUE'' and coalesce(GPSAM.BDCOMERCIO, ''FALSE'') = ''FALSE'' and coalesce(GPSAM.BDINDUSTRIA, ''FALSE'') = ''FALSE'' and coalesce(GPSAM.BDANEXOIII, ''FALSE'') = ''FALSE'' and coalesce(GPSAM.BDANEXOV, ''FALSE'') = ''FALSE'' and coalesce(GPSAM.BDANEXOVI, ''FALSE'') = ''FALSE'' then 2 '||
                        ' when coalesce(GPSAM.BDANEXOIV, ''FALSE'') = ''TRUE'' and (coalesce(GPSAM.BDCOMERCIO, ''FALSE'') = ''TRUE'' or coalesce(GPSAM.BDINDUSTRIA, ''FALSE'') = ''TRUE'' or coalesce(GPSAM.BDANEXOIII, ''FALSE'') = ''TRUE'' or coalesce(GPSAM.BDANEXOV, ''FALSE'') = ''TRUE'' or coalesce(GPSAM.BDANEXOVI, ''FALSE'') = ''TRUE'') then 3 '||
                        ' when coalesce(GPSAM.BDANEXOIV, ''FALSE'') = ''FALSE'' and (coalesce(GPSAM.BDCOMERCIO, ''FALSE'') = ''TRUE'' or coalesce(GPSAM.BDINDUSTRIA, ''FALSE'') = ''TRUE'' or coalesce(GPSAM.BDANEXOIII, ''FALSE'') = ''TRUE'' or coalesce(GPSAM.BDANEXOV, ''FALSE'') = ''TRUE'' or coalesce(GPSAM.BDANEXOVI, ''FALSE'') = ''TRUE'') then 1 '||
                       ' end '||
               ' end BDINDSIMPLES, '||
               ' ESOC.BDCODCLATRI, SER.BDREFSERV BDREFDEMONSTRATIVO, SER.BDDATASERV, SER.BDDATASERV BDDATAFOLHA, '||
               ' null BDDATAINISERVTI, SER.BDCODSERV, FGTS.BDCATEGORIAESOCIAL, '||
               '(select first 1 OC.BDCODESOCIAL '||
               ' from VRH_BASE_TOCORRENCIAFGTS OC '||
               ' where OC.BDCODIGO = FGTS.BDOCORRENCIATER) BDGRAUEXP, '||
               ' case '||
                 ' when FGTS.BDVINCEMPTER in (0, 1, 4, 5, 6, 7, 8, 9, 10, 11, 14, 15, 16, 17, 18) then 1 '||
                 ' when FGTS.BDVINCEMPTER in (2, 3, 12, 13) then 2 '||
                 ' else 0 '||
               ' end BDNATOCUP, '||
               ' null BDCODCONTTI, null BDDATARESCISAO, EMP.BDCNPJEMP BDDOCPRINCIPAL, E.BDDOCAUXILIAR BDDOCAUX, EMP.BDTIPOCAEPF, '||
               ' EMP.BDDOCAUXILIARCAEPF BDCAEPF, RH.BDTRIBUTACAOEXTERIOR, VERR.BDCODINCIDIRRF '||
              ' from VRH_BASE_TSERVTERC SER '||
              ' left outer join TEMPRESAS EMP on EMP.BDCODEMP = SER.BDCODEMP '||
              ' join TEMPRESAS_REF E on E.BDCODEMP = EMP.BDCODEMP and '||
                     ' E.BDREFEMP = (select max(REF2.BDREFEMP) '||
                                    ' from TEMPRESAS_REF REF2 '||
                                    ' where REF2.BDCODEMP = E.BDCODEMP and '||
                                         ' REF2.BDREFEMP <= '||:PRREF||')'||
                ' left outer join TEMPRESAS MAT on MAT.BDCODEMP = EMP.BDCODMATRIZ '||
                ' inner join VRHF_BASE_ITEMS_CALCTERC CAL on CAL.BDCODEMP = SER.BDCODEMP and '||
                      ' CAL.BDCODTER = SER.BDCODTER and '||
                      ' CAL.BDCODSERV = SER.BDCODSERV '||
                ' left outer join VRH_BASE_TVERBAS VER on VER.BDCODVER = CAL.BDCODVER '||
                ' left outer join VRH_BASE_TVERBAS_REF VERR on VERR.BDCODVER = CAL.BDCODVER and  '||
                      ' VERR.BDREFVER = (select first 1 BDREFVER '||
                                       ' from VRH_BASE_TVERBAS_REF '||
                                       ' where BDCODVER = VERR.BDCODVER and '||
                                             ' BDREFVER <= '||:PRREF||
                                       ' order by BDCODVER desc, BDREFVER desc) '||
                ' left outer join VRH_BASE_TCUSTOM TPCC on TPCC.BDCODCENTRO = SER.BDCODCENTRO and '||
                      ' TPCC.BDCODTPCC = SER.BDCODTPCC '||
                ' left outer join VW_VEF_BASE_TEMPITEMSATV GPSA on GPSA.BDCODEMP = SER.BDCODEMP  '||
                ' left outer join VW_VEF_BASE_TEMPITEMSATV GPSAM on GPSAM.BDCODEMP = MAT.BDCODEMP '||
                ' left outer join VW_VRH_BASE_TCUSTOM_GPS GPSTOM on GPSTOM.BDCODCENTRO = TPCC.BDCODCENTRO and '||
                     ' GPSTOM.BDCODTPCC = TPCC.BDCODTPCC '||
                ' left outer join VRHF_BASE_TEMPESOCIAL ESOC on ESOC.BDCODEMP = coalesce(MAT.BDCODEMP, SER.BDCODEMP) and '||
                      ' ESOC.BDREFEMP = (select max(BDREFEMP) BDREFEMP '||
                                       ' from VRHF_BASE_TEMPESOCIAL '||
                                       ' where BDCODEMP = ESOC.BDCODEMP and '||
                                            ' BDREFEMP <= '||:PRREF||') '||
                ' left outer join VRHF_BASE_TTERC_FGTSGPS FGTS on FGTS.BDCODTER = SER.BDCODTER and '||
                      ' FGTS.BDREFTERC = (select max(BDREFTERC) BDREFTERC '||
                                        ' from VRHF_BASE_TTERC_FGTSGPS '||
                                        '  where BDCODTER = FGTS.BDCODTER and '||
                                             ' BDREFTERC <= '||:PRREF||')'||
                ' left outer join TTERCEIRO_RH RH on RH.BDCODTER = SER.BDCODTER '||
                ' join TTERCEIRO TERC on TERC.BDCODTER = SER.BDCODTER '||
                ' where SER.BDDATASERV between '''||:wPriDIA||''' and '''||:wUltDia||''' and '||
                     ' (SER.BDCODTER = '||wcodter||')'||
                     ' and SER.BDCODEMP in ('||:prcodemp||')';

      for execute statement wSQL2 into
        :BDTIPO,
        :BDCODEMP,
        :BDCODCOL,
        :BDCODVER,
        :BDREFAUXV,
        :BDREFVR ,
        :BDVAL ,
        :BDCLAVER ,
        :BDTIPOREFVER,
        :BDHEVER ,
        :BDINSCLOTACAO ,
        :BDMATRICULA ,
        :BDCODLOTACAO ,
        :BDTIPOESTAB ,
        :BDINDSIMPLES  ,
        :BDCODCLATRI ,
        :BDREFDEMONSTRATIVO,
        :BDDATASERV ,
        :BDDATAFOLHA ,
        :BDDATAINISERVTI ,
        :BDCODSERV ,
        :BDCATEGORIAESOCIAL ,
        :BDGRAUEXP ,
        :BDNATOCUP ,
        :BDCODCONTTI ,
        :BDDATARESCISAO ,
        :BDDOCPRINCIPAL ,
        :BDDOCAUX ,
        :BDTIPOCAEPF ,
        :BDCAEPF,
        :BDTRIBUTACAOEXTERIOR,
        :BDCODINCIDIRRF
      do
       suspend;
  end
end^

create or alter procedure SP_VRH_UPDATE_DATAIR_AD13
as
declare variable FDIASEMANA integer;
declare variable FCONT integer;
declare variable FFERIADO boolean;
declare variable WREFPGT integer;
declare variable WSQLNORMAL varchar(3000);
declare variable WDATAPGTO date;
declare variable WREF integer;
declare variable WCODEMP integer;
begin
  /* Procedure Text */
--  suspend;
  UPDATE VRHF_EMP_TA13SAL A13 SET A13.bddatairrfesocial = A13.bddatapgtoa13,
                                  a13.bdrefirrfesocial = (select BDAAAAMM from aaaamm(a13.bddatapgtoa13))
                            where A13.bddatapgtoa13 is not null;


  for select BDCODEMP, bdrefa13
      from (select FN.BDCODEMP, FN.bdrefa13
            from VRHF_EMP_TA13SAL FN
            )
      group by BDCODEMP, bdrefa13
      into :WCODEMP, :WREF
  do
  begin
    -- colaboradores

    select cast(substring(:WREF from 1 for 4) || '/' || substring(:WREF from 5 for 2) || '/' || ULTDIA as date) as ULTIMODIA
    from ULTIMO_DIA_MES(substring(:WREF from 5 for 2), substring(:WREF from 1 for 4))
    into :WDATAPGTO;

    FCONT = 0;
    while (FCONT = 0) do
    begin
      select cast(extract(weekday from :WDATAPGTO) as integer) as DIA_SEMANA
      from RDB$DATABASE
      into :FDIASEMANA;

      select BDFERIADO
      from SP_FERIADO_EMPRESA(:WCODEMP, :WDATAPGTO)
      into :FFERIADO;

      if ((FDIASEMANA = 0) or (FDIASEMANA = 6) or (FFERIADO = true)) then
        WDATAPGTO = WDATAPGTO - 1;
      else
        FCONT = 1;
    end

    select BDAAAAMM
    from AAAAMM(:WDATAPGTO)
    into :WREFPGT;

    WSQLNORMAL = 'update VRHF_EMP_TA13SAL fn set fn.bddatairrfesocial = ' || '''' || :WDATAPGTO || '''' ||
                  ', fn.bdrefirrfesocial = ' || :WREFPGT ||
                  ' where fn.bddatairrfesocial is null' || ' and fn.bdcodemp =' || :WCODEMP || ' and fn.bdrefa13 = ' || :WREF;

    execute statement WSQLNORMAL;
  end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TCOL_VINCDIA_BU0 FOR VRH_EMP_TCOL_VINCDIA
ACTIVE BEFORE UPDATE POSITION 0
AS
  declare variable vAnoMes varchar(6);
begin
  vAnoMes =  SUBSTRING(CAST(NEW.BDDATACOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(NEW.BDDATACOL AS VARCHAR(10)) FROM 6 FOR 2);

  new.bdrefcol = cast(vanomes as integer);
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_ABONO_BI0 FOR VRH_EMP_TRECLAMATORIA_ABONO
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wcod INTEGER;
begin
  if (coalesce(new.bdchave, 0) <= 0) then
     begin
       wcod = null;
       select coalesce(max(BDCHAVE), 1) from VRH_EMP_TRECLAMATORIA where BDCODEMP = new.bdcodemp into :wcod;
       new.bdchave = :wcod;
     end

  if (coalesce(new.bdcodvinc,0) <= 0) then
     begin
       select first 1 x.bdcodvinc from VRH_EMP_TRECLAMATORIA_vinc x
       where x.bdcodemp = new.bdcodemp and x.bdchave = new.bdchave order by x.bdcodvinc desc into wcod;
       new.bdcodvinc = :wcod;
     end

end
^

create or alter procedure FILTRO_DOWNLOAD_ESOCIAL (
    WFILTRO integer)
returns (
    BDNO varchar(100),
    BDCLASSIFICACAO varchar(30),
    BDCODEMP integer,
    BDRAIZ varchar(15),
    BDCODESTAB integer,
    BDTIPINSC integer,
    BDCNPJRESP varchar(15),
    BDCODCC integer,
    BDDESCRICAO varchar(100),
    BDMATRIZ varchar(15),
    BDCODMATRIZ integer,
    BDTIPO varchar(8),
    BDIMPORTA varchar(15),
    BDCAD varchar(15),
    BDESTABUNICO varchar(15),
    BDINSCRICAO varchar(20),
    BDESTAB varchar(15),
    BDLOTTRIB varchar(15),
    BDFUNCOES varchar(15),
    BDHORARIOS varchar(15),
    BDCOLMOV varchar(15),
    BDCONMOV varchar(15))
as
declare variable WWHERE varchar(1000);
declare variable WSQL varchar(30000);
BEGIN
    wsql         = 'select distinct X.BDNO, X.BDCLASSIFICACAO, X.BDCODEMP, ';
    wsql = wsql || 'Y.BDRAIZ, Y.BDCODESTAB, Y.BDTIPINSC, Y.BDCNPJRESP, Y.BDCODCC, Y.BDDESCRICAO, Y.BDMATRIZ, Y.BDCODMATRIZ, Y.BDTIPO, Y.BDIMPORTA, Y.BDCAD, Y.BDESTABUNICO, ';
    wsql = wsql || 'replace(replace(replace(replace(replace(replace(replace(X.BDNO, ''.'', ''''), ''/'', ''''), ''-'', ''''), ''_'', ''''), ''CNPJ '', ''''), ''CPF '', ''''), ''CAEPF '', '''') BDINSCRICAO, ';
    wsql = wsql || 'coalesce(SINC.BDESTAB,    false) BDESTAB, ';
    wsql = wsql || 'coalesce(SINC.BDLOTTRIB,  false) BDLOTTRIB, ';
    wsql = wsql || 'coalesce(SINC.BDFUNCOES,  false) BDFUNCOES, ';
    wsql = wsql || 'coalesce(SINC.BDHORARIOS, false) BDHORARIOS, ';
    wsql = wsql || 'coalesce(SINC.BDCOLMOV,   false) BDCOLMOV, ';
    wsql = wsql || 'coalesce(SINC.BDCONMOV,   false) BDCONMOV ';
    wsql = wsql || 'from TESTRUTURADOWN X ';
    wsql = wsql || 'join TDEFESTABDOWN Y on (Y.BDRAIZ = X.BDRAIZ and ';
    wsql = wsql || 'Y.BDINSCRICAO = replace(replace(replace(replace(replace(replace(replace(X.BDNO, ''.'', ''''), ''/'', ''''), ''-'', ''''), ''_'', ''''), ''CNPJ '', ''''), ''CPF '', ''''), ''CAEPF '', '''')) ';
    wsql = wsql || 'left join VRH_ESOCIAL_TSINCRONIZACAO SINC on (SINC.BDCODEMP = Y.BDCODESTAB) ';

    if (wfiltro > 0) then
      begin
        wwhere = 'where ';

        if (wfiltro = 1) then
          begin
            wwhere = wwhere || 'SINC.BDESTAB    = true and ';
            wwhere = wwhere || 'SINC.BDLOTTRIB  = true and ';
            wwhere = wwhere || 'SINC.BDFUNCOES  = true and ';
            wwhere = wwhere || 'SINC.BDHORARIOS = true and ';
            wwhere = wwhere || 'SINC.BDCOLMOV   = true and ';
            wwhere = wwhere || 'SINC.BDCONMOV   = true ';
          end
        else
        if (wfiltro = 2) then
          begin
            wwhere = wwhere || 'SINC.BDESTAB    is null or ';
            wwhere = wwhere || 'SINC.BDLOTTRIB  is null or ';
            wwhere = wwhere || 'SINC.BDFUNCOES  is null or ';
            wwhere = wwhere || 'SINC.BDHORARIOS is null or ';
            wwhere = wwhere || 'SINC.BDCOLMOV   is null or ';
            wwhere = wwhere || 'SINC.BDCONMOV   is null';
          end

        wsql = wsql || wwhere;
      end


    FOR EXECUTE STATEMENT wSQL INTO
         :BDNO,
         :BDCLASSIFICACAO,
         :BDCODEMP,
         :BDRAIZ,
         :BDCODESTAB,
         :BDTIPINSC,
         :BDCNPJRESP,
         :BDCODCC,
         :BDDESCRICAO,
         :BDMATRIZ,
         :BDCODMATRIZ,
         :BDTIPO,
         :BDIMPORTA,
         :BDCAD,
         :BDESTABUNICO,
         :BDINSCRICAO,
         :BDESTAB,
         :BDLOTTRIB,
         :BDFUNCOES,
         :BDHORARIOS,
         :BDCOLMOV,
         :BDCONMOV
  DO
  BEGIN
    SUSPEND;
  END
END^




create or alter procedure SP_VRH_RELATORIOCONFCOL_FN (
    PREMP varchar(10000),
    PRCOL varchar(20000),
    PRAUT varchar(10000),
    PRREFINI integer,
    PRREFFIM integer,
    PRAGRUPACC smallint = 0,
    PRCC varchar(10000) = null,
    PRAGRUPASETOR smallint = 0,
    PRSETOR varchar(10000) = null,
    PRCCPAGTOIR smallint = 0)
returns (
    BDCODEMP integer,
    BDCODFILIAL integer,
    BDREF integer,
    BDTIPOCOL integer,
    BDCODCOL integer,
    BDVALOR numeric(18,6),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDCODCENTROSETOR integer,
    BDCODSETOR integer)
as
declare variable WSQL varchar(32700);
declare variable WSQLBASE varchar(32700);
declare variable WSQLFINAL varchar(32700);
declare variable WWHEREBASE varchar(10000);
declare variable WCAMPOSELECTREF varchar(1000);
declare variable WCAMPOSELECTREFPAGTOIRRF varchar(10000);
BEGIN
/* pragrupacc
    0 = sem centro de custos (não retorna o centro de custos)
    1 = por centro de custos (retorna o centro de custos)
   */

  /* pragrupasetor    192311 - Isabella - 10/07/2024
    0 = sem setor (não retorna o setor)
    1 = por setor (retorna o setor)
    pode não apresentar a informação, ou seja, não agrupar , mas usar o campo (cc e setor) como filtro, conforrme disponibilidade da tela de emissão
    192311 informação: o setor é um novo campo do cadastro de colaborador/contrib e de uma nova tela de vinculo de autonomo por empresa,
                       obtido da mesma tabela de ccusto/tomador

   */

  wsql = '';
  WSQLBASE = '' ;
  WSQLFINAL = '' ;
  WWHEREBASE  = '';
  wCampoSelectRef  = '';
  wCampoSelectRefPagtoIRRF = '';

  premp = upper(premp);
  prcol = upper(prcol);


       wsql = 'select COL.BDCODEMP, COL.BDREF, COL.BDTIPOCOL, COL.BDCODCOL, COL.BDVALV, ' ||
            ' COL.BDCODCENTRO, COL.BDCODTPCC, ';

             IF (pragrupasetor = 0) THEN
                wsql = wsql||'cast(null as integer) BDCODCENTROSETOR, cast(null as integer) BDCODSETOR ';
             ELSE
                wsql = wsql||' VINC.BDCODCENTRO BDCODCENTROSETOR, VINC.BDCODTPCC BDCODSETOR ';

       wsql = wsql || ' from ( ';

      wwherebase = '';
        IF (premp IS NOT NULL AND premp <> '') THEN
            BEGIN
                 wwherebase = wwherebase||' and '||replace(premp, 'BDCODEMP', 'V.BDCODEMP');
        
                 IF (prcol IS NOT NULL AND prcol <> '') THEN
                     wwherebase = wwherebase||' and '||replace(PRCOL, 'BDCODCOL', 'V.BDCODCOL');
             END


       wCampoSelectRefPagtoIRRF = 'select F.bdcodemp, f.BDREFIRRFESOCIAL BDREF, ';

        if (prcc = '') then
          begin
                 wCampoSelectRef = 'select v.bdcodemp, v.BDREFFN BDREF, ';
                 wsqlbase =  ' 0 BDTIPOCOL, v.BDCODCOL, v.BDVALVFN BDVALV, cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBAFN v' ||
                          ' JOIN  VRHF_EMP_TFOLHANORMAL F on V.BDCODEMP = f.BDCODEMP AND V.BDCODCOL = F.BDCODCOL AND V.BDREFFN = F.BDREFFN '   ;


                 wsql = wsql||  wCampoSelectRef || wsqlbase || ' where (v.BDREFFN BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;

                 if (PRCCPAGTOIR = 1) then
                    wsql = wsql|| ' UNION ' || wCampoSelectRefPagtoIRRF || wsqlbase || ' where (f.BDREFIRRFESOCIAL BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;


                 wsql = wsql||' union ';
                 wsqlbase =  ' 0 BDTIPOCOL, v.BDCODCOL, v.BDVALVFC BDVALV, cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBAFC v' ||
                          ' JOIN  VRHF_EMP_TFOLHACOMP F on V.BDCODEMP = f.BDCODEMP AND V.BDCODCOL = F.BDCODCOL AND V.BDREFFN = F.BDREFFN and v.BDREFFC = f.BDREFFC '   ;

                 wCampoSelectRef = 'select v.bdcodemp, v.BDREFCOMP BDREF, ';
                 wsql = wsql||  wCampoSelectRef || wsqlbase || ' where (v.BDREFCOMP BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;

                 if (PRCCPAGTOIR = 1) then
                    wsql = wsql|| ' UNION ' ||  wCampoSelectRefPagtoIRRF || wsqlbase || ' where (f.BDREFIRRFESOCIAL BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;




                 wsql = wsql||' union ';
                 wsqlbase =  ' 0 BDTIPOCOL, v.BDCODCOL, v.BDVALVFN BDVALV, cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC '||
                          'from VRHF_EMP_TVERBAINT v' ||
                          ' JOIN  VRHF_EMP_TFOLHAINT F on V.BDCODEMP = f.BDCODEMP AND V.BDCODCOL = F.BDCODCOL and v.BDCODCONTTI = f.BDCODCONTTI AND V.BDREFFN = F.BDREFFN '   ;

                 wCampoSelectRef = 'select v.bdcodemp, v.BDREFFN BDREF, ';
                 wsql = wsql||  wCampoSelectRef || wsqlbase || ' where (v.BDREFFN BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;

                 if (PRCCPAGTOIR = 1) then
                    wsql = wsql|| ' UNION ' ||  'select F.bdcodemp,EXTRACT(YEAR FROM F.BDDATAPGTOFN) || case when EXTRACT(MONTH FROM F.BDDATAPGTOFN) < 10 then ' ||  '''0''' || ' ||  EXTRACT(MONTH FROM F.BDDATAPGTOFN) else EXTRACT(MONTH FROM F.BDDATAPGTOFN) end  BDREF, ' ||
                                wsqlbase || ' where ( EXTRACT(YEAR FROM F.BDDATAPGTOFN) || case when EXTRACT(MONTH FROM F.BDDATAPGTOFN) < 10 then ' ||  '''0''' || ' ||  EXTRACT(MONTH FROM F.BDDATAPGTOFN) else EXTRACT(MONTH FROM F.BDDATAPGTOFN) end '
                                                || '  BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;

              wsql = wsql||' union  ';

          end
      -- folha tomador

             wCampoSelectRef = 'select v.bdcodemp,  v.BDREFTOMADOR BDREF,  ';

            wsqlbase = ' 0 BDTIPOCOL, v.BDCODCOL, v.BDVALVFT BDVALV,  ' ;

            IF (pragrupacc = 0) THEN
                wsqlbase = wsqlbase||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
             ELSE
                wsqlbase = wsqlbase||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

            wsqlbase = wsqlbase || 'from VRHF_EMP_TVERBATOMADOR v' ||
                        ' JOIN  VRHF_EMP_TFOLHATOMADOR F on v.BDCODEMP = f.BDCODEMP AND v.BDCODCOL = F.BDCODCOL and v.BDORDEM = f.BDORDEM AND v.BDREFTOMADOR = F.BDREFTOMADOR '   ;
    
            if ((prcc is not null) or (prcc <> '') OR (pragrupacc = 1))  then
                begin
                    if (prcc = '') then
                        wsqlbase = wsqlbase|| ' left outer ';
                     wsqlbase = wsqlbase|| 'join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = F.BDCODEMP and prepft.BDCODCOL = F.BDCODCOL and prepft.BDORDEM = F.BDORDEM) ';
                end


             wsql = wsql||  wCampoSelectRef || wsqlbase || ' where (v.BDREFTOMADOR BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;
             if  ((prcc is not null) and (prcc <> '')) then
                  wsql = wsql|| ' and ' || replace(prcc, 'BDCODTPCC', 'prepft.BDCODTPCC')  ;

             if (PRCCPAGTOIR = 1) then
               begin
                     wsql = wsql|| ' UNION '  ||  wCampoSelectRefPagtoIRRF || wsqlbase || ' where (f.BDREFIRRFESOCIAL BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;
                     if  ((prcc is not null) and (prcc <> '')) then
                          wsql = wsql|| ' and ' || replace(prcc, 'BDCODTPCC', 'prepft.BDCODTPCC')  ;
                end





      -- folha intermitente
            wsql = wsql||
                     'union ';

            wCampoSelectRef = 'select v.bdcodemp, v.BDREFTOMADOR BDREF,  ';

            wsqlbase = ' 0 BDTIPOCOL, v.BDCODCOL, v.BDVALVFT BDVALV , ';
     
                     IF (pragrupacc = 0) THEN
                        wsqlbase = wsqlbase||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                     ELSE
                        wsqlbase = wsqlbase||'prepft.BDCODCENTRO, prepft.BDCODTPCC ';

            wsqlbase = wsqlbase||  ' from VRHF_EMP_TVERBATOMINT V '
                     || ' JOIN  VRHF_EMP_TFOLHATOMINT F ON V.BDCODEMP = F.BDCODEMP AND V.BDCODCONTTI = F.BDCODCONTTI '
                     || '                                 and  V.BDORDEM = F.BDORDEM AND V.BDCODCOL = F.BDCODCOL AND V.BDREFTOMADOR = F.BDREFTOMADOR ';
     

            if ((prcc is not null) or (prcc <> '') OR (pragrupacc = 1))  then
                begin
                    if (prcc = '') then
                        wsqlbase = wsqlbase|| ' left outer ';
                     wsqlbase = wsqlbase|| 'join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = F.BDCODEMP and prepft.BDCODCOL = F.BDCODCOL and prepft.BDORDEM = F.BDORDEM) ';
                end

             wsql = wsql||  wCampoSelectRef || wsqlbase || ' where (v.BDREFTOMADOR BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;
             if  ((prcc is not null) and (prcc <> '')) then
                  wsql = wsql|| ' and ' || replace(prcc, 'BDCODTPCC', 'prepft.BDCODTPCC')  ;

             if (PRCCPAGTOIR = 1) then
                begin
                    wsql = wsql|| ' UNION ' || wCampoSelectRefPagtoIRRF || wsqlbase || ' where (f.BDREFIRRFESOCIAL BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;
                    if  ((prcc is not null) and (prcc <> '')) then
                        wsql = wsql|| ' and ' || replace(prcc, 'BDCODTPCC', 'prepft.BDCODTPCC')  ;
                end





      -- folha tomador complementar
            wsql = wsql||' union ';

            wCampoSelectRef = 'select v.bdcodemp, v.BDREFCOMP BDREF, ';

            wsqlbase = '0 BDTIPOCOL, v.BDCODCOL, v.BDVALVFC BDVALV, ';

             IF (pragrupacc = 0) THEN
                wsqlbase = wsqlbase||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
             ELSE
                wsqlbase = wsqlbase||' prepft.BDCODCENTRO, prepft.BDCODTPCC ';

            wsqlbase =  wsqlbase || 'from VRHF_EMP_TVERBAFCTOMADOR V '
                        || ' JOIN VRHF_EMP_TFOLTOMCOMP F ON F.BDCODEMP = V.BDCODEMP AND F.BDCODCOL = V.BDCODCOL AND F.BDORDEM = V.BDORDEM AND F.BDREFTOMADOR = V.BDREFTOMADOR AND F.BDREFFC = V.BDREFFC ';

            if ((prcc is not null) or (prcc <> '') OR (pragrupacc = 1))  then
                 begin
                    wsqlbase = wsqlbase || ' LEFT OUTER JOIN VRHF_EMP_TFOLHATOMADOR FTT ON FTT.BDCODEMP = F.BDCODEMP AND FTT.BDCODCOL = F.BDCODCOL AND FTT.BDORDEM = F.BDORDEM AND FTT.BDREFTOMADOR = F.BDREFTOMADOR ';

                    if (prcc = '') then
                        wsqlbase = wsqlbase|| ' left outer ';
                     wsqlbase = wsqlbase|| 'join VRHF_EMP_TPREPFN prepft on (prepft.BDCODEMP = FTT.BDCODEMP and prepft.BDCODCOL = FTT.BDCODCOL and prepft.BDORDEM = FTT.BDORDEM) ';
                 end

             wsql = wsql||  wCampoSelectRef || wsqlbase || ' where (v.BDREFCOMP BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;
             if  ((prcc is not null) and (prcc <> '')) then
                  wsql = wsql|| ' and ' || replace(prcc, 'BDCODTPCC', 'prepft.BDCODTPCC')  ;


             if (PRCCPAGTOIR = 1) then
                begin
                    wsql = wsql|| ' UNION ' || wCampoSelectRefPagtoIRRF || wsqlbase || ' where (f.BDREFIRRFESOCIAL BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;
                    if  ((prcc is not null) and (prcc <> '')) then
                        wsql = wsql|| ' and ' || replace(prcc, 'BDCODTPCC', 'prepft.BDCODTPCC')  ;
                end



     -- adiantamento de 13º salário
      wsql = wsql||
             ' union  ';

          wCampoSelectRef = ' select V.bdcodemp, V.BDREFA13 BDREF,  ';

            wsqlbase = ' 0 BDTIPOCOL, V.BDCODCOL, V.BDVALVA13 BDVALV, ';

              IF (pragrupacc = 0) THEN
                 wsqlbase = wsqlbase||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
              ELSE
                 wsqlbase = wsqlbase||'PREPA13.BDCODCENTRO, PREPA13.BDCODTPCC ';

          wsqlbase = wsqlbase || 'from VRHF_EMP_TVERBAA13  V ' ||
                    'JOIN VRHF_EMP_TA13SAL F ON (V.BDCODEMP = F.BDCODEMP AND ' ||
                    '      V.BDCODCOL = F.BDCODCOL AND ' ||
                    '      V.BDREFA13 = F.BDREFA13) ';
     

            if ((prcc is not null) or (prcc <> '') OR (pragrupacc = 1))  then
                begin
                    if (prcc = '') then
                        wsqlbase = wsqlbase|| ' left outer ';
                     wsqlbase = wsqlbase|| 'JOIN VRHF_EMP_TPREPFN PREPA13 ON (F.BDCODEMP = PREPA13.BDCODEMP AND ' ||
                    '      F.BDCODCOL = PREPA13.BDCODCOL AND ' ||
                    '      F.BDORDEM = PREPA13.BDORDEM) ';
                 end

                 wsql = wsql||  wCampoSelectRef || wsqlbase || ' where (v.BDREFA13 BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;

                if  ((prcc is not null) and (prcc <> '')) then
                  wsql = wsql|| ' and ' || replace(prcc, 'BDCODTPCC', 'prepa13.BDCODTPCC')  ;

                 if (PRCCPAGTOIR = 1) then
                    begin
                        wsql = wsql|| ' UNION ' || wCampoSelectRefPagtoIRRF || wsqlbase || ' where (f.BDREFIRRFESOCIAL BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;
                        if  ((prcc is not null) and (prcc <> '')) then
                             wsql = wsql|| ' and ' || replace(prcc, 'BDCODTPCC', 'prepa13.BDCODTPCC')  ;
                    end


      -- 13º salário
      wsql = wsql||
             ' union  ';

            wCampoSelectRef = 'select v.BDCODEMP,  V.BDREF13 BDREF,   ';

            wsqlbase =  '0 BDTIPOCOL, V.BDCODCOL, V.BDVALV13 BDVALV,  ' ;

                  IF (pragrupacc = 0) THEN
                     wsqlbase = wsqlbase||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                  ELSE
                     wsqlbase = wsqlbase||'PREP13.BDCODCENTRO, PREP13.BDCODTPCC ';

            wsqlbase =  wsqlbase || 'from  VRHF_EMP_TVERBA13 V ' ||
                    ' JOIN VRHF_EMP_T13SAL F ON (V.BDCODEMP = F.BDCODEMP AND ' ||
                    '      V.BDCODCOL = F.BDCODCOL AND ' ||
                    '      V.BDREF13 = F.BDREF13)  ';
                  
            if ((prcc is not null) or (prcc <> '') OR (pragrupacc = 1))  then
                begin
                    if (prcc = '') then
                        wsqlbase = wsqlbase|| ' left outer ';
                     wsqlbase = wsqlbase|| 'JOIN VRHF_EMP_TPREPFN PREP13 ON (F.BDCODEMP = PREP13.BDCODEMP AND ' ||
                    '      F.BDCODCOL = PREP13.BDCODCOL AND ' ||
                    '      F.BDORDEM = PREP13.BDORDEM) ';
                 end


             wsql = wsql||  wCampoSelectRef || wsqlbase || ' where (v.BDREF13 BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;
             if  ((prcc is not null) and (prcc <> '')) then
                  wsql = wsql|| ' and ' || replace(prcc, 'BDCODTPCC', 'prep13.BDCODTPCC')  ;

             if (PRCCPAGTOIR = 1) then
                begin
                    wsql = wsql|| ' UNION ' || wCampoSelectRefPagtoIRRF || wsqlbase || ' where (f.BDREFIRRFESOCIAL BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;
                    if  ((prcc is not null) and (prcc <> '')) then
                        wsql = wsql|| ' and ' || replace(prcc, 'BDCODTPCC', 'prep13.BDCODTPCC')  ;
                end


      -- Complemento de 13º salário
      wsql = wsql||
             ' union  ';

          wCampoSelectRef = 'select V.BDCODEMP, V.BDREFC13,  ';
          wsqlbase = '0 BDTIPOCOL, V.BDCODCOL, V.BDVALVC13 BDVALV, ';

                IF (pragrupacc = 0) THEN
                     wsqlbase = wsqlbase||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                  ELSE
                     wsqlbase = wsqlbase||'PREPC13.BDCODCENTRO, PREPC13.BDCODTPCC ';

          wsqlbase = wsqlbase || ' from  VRHF_EMP_TVERBAC13 V ' ||
                    'join VRHF_EMP_TC13SAL F on (V.BDCODEMP = F.BDCODEMP and ' ||
                    '      V.BDCODCOL = F.BDCODCOL and ' ||
                    '      V.BDREF13 = F.BDREF13) ';

           if ((prcc is not null) or (prcc <> '') OR (pragrupacc = 1))  then
                begin
                    if (prcc = '') then
                        wsqlbase = wsqlbase|| ' left outer ';
                     wsqlbase = wsqlbase|| 'join VRHF_EMP_TPREPFN PREPC13 on (F.BDCODEMP = PREPC13.BDCODEMP and ' ||
                    '      F.BDCODCOL = PREPC13.BDCODCOL and ' ||
                    '      F.BDORDEM = PREPC13.BDORDEM) ';
                end

             wsql = wsql||  wCampoSelectRef || wsqlbase || ' where (v.BDREF13 BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;
             if  ((prcc is not null) and (prcc <> '')) then
                  wsql = wsql|| ' and ' || replace(prcc, 'BDCODTPCC', 'prepc13.BDCODTPCC')  ;

             if (PRCCPAGTOIR = 1) then
                begin
                    wsql = wsql|| ' UNION ' || wCampoSelectRefPagtoIRRF || wsqlbase || ' where (f.BDREFIRRFESOCIAL BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;
                    if  ((prcc is not null) and (prcc <> '')) then
                        wsql = wsql|| ' and ' || replace(prcc, 'BDCODTPCC', 'prepC13.BDCODTPCC')  ;

                 end



      -- ferias
      wsql = wsql||
             ' union  ';

            wCampoSelectRef = 'select f.BDCODEMP, EXTRACT(YEAR FROM F.BDINIPERGOZOFE) || case when EXTRACT(MONTH FROM F.BDINIPERGOZOFE) < 10 then ' ||  '''0''' || ' ||  EXTRACT(MONTH FROM F.BDINIPERGOZOFE) else EXTRACT(MONTH FROM F.BDINIPERGOZOFE) end BDREF,' ;

            wsqlbase = '  0 BDTIPOCOL, f.BDCODCOL, v.BDVALVFE BDVALV, ' ;

                  IF (pragrupacc = 0) THEN
                     wsqlbase = wsqlbase||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC ';
                  ELSE
                     wsqlbase = wsqlbase||'PREPF.BDCODCENTRO, PREPF.BDCODTPCC ';

           wsqlbase =  wsqlbase||   ' from VRHF_EMP_TVERBAFE V ' ||
                         ' JOIN VRH_EMP_TFERIAS F on F.BDCODEMP = V.BDCODEMP and F.BDCODCOL = V.BDCODCOL and F.BDINIPERAQUISFE = V.BDINIPERAQUISFE and F.BDCODFE = V.BDCODFE ';

           if ((prcc is not null) or (prcc <> '') OR (pragrupacc = 1))  then
               begin
                    if (prcc = '') then
                        wsqlbase = wsqlbase|| ' left outer ';
                     wsqlbase = wsqlbase|| 'join VRHF_EMP_TPREPFN PREPF on (F.BDCODEMP = PREPF.BDCODEMP and ' ||
                    '      F.BDCODCOL = PREPF.BDCODCOL and ' ||
                    '      F.BDORDEM = PREPF.BDORDEM) ';
               end

                 wsql = wsql||  wCampoSelectRef || wsqlbase || ' where (EXTRACT(YEAR FROM F.BDINIPERGOZOFE) || case when EXTRACT(MONTH FROM F.BDINIPERGOZOFE) < 10 then ' ||  '''0''' || ' ||  EXTRACT(MONTH FROM F.BDINIPERGOZOFE) else EXTRACT(MONTH FROM F.BDINIPERGOZOFE) end ' ||
                                                               '           BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;
                 if  ((prcc is not null) and (prcc <> '')) then
                     wsql = wsql|| ' and ' || replace(prcc, 'BDCODTPCC', 'prepf.BDCODTPCC')  ;

                 wsql = wsql|| ' UNION ' || wCampoSelectRefPagtoIRRF || wsqlbase || ' where (F.BDREFIRRFESOCIAL BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;
                 if  ((prcc is not null) and (prcc <> '')) then
                   wsql = wsql|| ' and ' || replace(prcc, 'BDCODTPCC', 'prepf.BDCODTPCC')  ;




      -- Folha avulsa

           wsql = wsql||
                  ' union  ';

            wCampoSelectRef = 'select V.BDCODEMP,   EXTRACT(YEAR FROM F.BDDATAFA) || case when EXTRACT(MONTH FROM F.BDDATAFA) < 10 then ' ||  '''0''' || ' ||  EXTRACT(MONTH FROM F.BDDATAFA) else EXTRACT(MONTH FROM F.BDDATAFA) end BDREF, ' ;

            wsqlbase = '  0 BDTIPOCOL, f.BDCODCOL, v.BDVALVFA BDVALV, ';

           if (coalesce(pragrupacc, 0) = 0) then
              wsqlbase = wsqlbase||' cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODPTCC ';
           else
              wsqlbase = wsqlbase||'PREPF.BDCODCENTRO, PREPF.BDCODTPCC ';

           wsqlbase = wsqlbase || 'from VRHF_EMP_TVERBAFA V '||
                  'join VRHF_EMP_TFOLHAAVULSA F on (F.BDCODEMP = v.BDCODEMP and F.BDCODCOL = v.BDCODCOL and F.BDCODTCA = v.BDCODTCA and F.BDDATAFA = v.BDDATAFA)  ';

            if ((prcc is not null) or (prcc <> '') OR (pragrupacc = 1))  then
               begin
                    if (prcc = '') then
                        wsqlbase = wsqlbase|| ' left outer ';
                     wsqlbase = wsqlbase|| 'join VRHF_EMP_TPREPFN PREPF on (F.BDCODEMP = PREPF.BDCODEMP and ' ||
                    '      F.BDCODCOL = PREPF.BDCODCOL and ' ||
                    '      F.BDORDEM = PREPF.BDORDEM) ';
                end

                 wsql = wsql||  wCampoSelectRef || wsqlbase || ' where (EXTRACT(YEAR FROM v.BDDATAFA) || case when EXTRACT(MONTH FROM v.BDDATAFA) < 10 then ' ||  '''0''' || ' ||  EXTRACT(MONTH FROM v.BDDATAFA) else EXTRACT(MONTH FROM v.BDDATAFA) end ' ||
                                                               '       BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;
                 if  ((prcc is not null) and (prcc <> '')) then
                  wsql = wsql|| ' and ' || replace(prcc, 'BDCODTPCC', 'prepf.BDCODTPCC')  ;

                 if (PRCCPAGTOIR = 1) then
                   begin
                        wsql = wsql|| ' UNION ' || wCampoSelectRefPagtoIRRF || wsqlbase || ' where (f.BDREFIRRFESOCIAL BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;
                        if  ((prcc is not null) and (prcc <> '')) then
                            wsql = wsql|| ' and ' || replace(prcc, 'BDCODTPCC', 'prepf.BDCODTPCC')  ;
                   end



       wsql = wsql|| ') col ';

     IF ((pragrupasetor = 1) or (prsetor is not null) and (prsetor <> '')) THEN
        wsql = wsql||' LEFT OUTER JOIN VRH_EMP_TCOLCON_VINC VINC ON VINC.BDCODEMP = COL.BDCODEMP AND VINC.BDCODCOL = COL.BDCODCOL ' ||
                     '         AND VINC.BDREFCOL = (SELECT MAX(X.BDREFCOL) FROM VRH_EMP_TCOLCON_VINC X ' ||
                     '                              WHERE X.BDCODEMP = COL.BDCODEMP AND X.BDCODCOL = COL.BDCODCOL  '  ||
                     '                              AND X.BDREFCOL <= COL.BDREF )'      ;

    if ((prsetor is not null) and (prsetor <> '')) then
        wsql = wsql||' where '||replace(prsetor, 'BDCODTPCC', 'VINC.BDCODTPCC');




  IF (UPPER(COALESCE(prAut, '')) <> 'NENHUM') THEN
     BEGIN
        IF (wsql <> '') THEN
          wsql = wsql||' union  ';

            wCampoSelectRef = 'select F.BDCODEMP,  f.bdrefinssserv   BDREF, ' ;

            wsqlbase =  ' 2 BDTIPOCOL,  f.BDCODTER BDCODCOL, fn.BDVALOR BDVALV,  ';


               IF (pragrupacc = 0) THEN
                  wsqlbase = wsqlbase||'cast(null as integer) BDCODCENTRO, cast(null as integer) BDCODTPCC, ';
               ELSE
                  wsqlbase = wsqlbase||'SERV.BDCODCENTRO, SERV.BDCODTPCC, ';


                IF (pragrupasetor = 0) THEN
                wsqlbase = wsqlbase||'cast(null as integer) BDCODCENTROSETOR, cast(null as integer) BDCODSETOR ';
             ELSE
                 wsqlbase= wsqlbase||' VINC.BDCODCENTRO BDCODCENTROSETOR, VINC.BDCODTPCC BDCODSETOR ';

         wsqlbase = wsqlbase || ' from VRHF_BASE_CALC_TERC F '||
                                  'join VRHF_BASE_ITEMS_CALCTERC FN on (FN.BDCODTER = f.BDCODTER and FN.BDCODEMP = f.BDCODEMP and FN.BDCODSERV = f.BDCODSERV) ';

            if ((prcc is not null) or (prcc <> '') OR (pragrupacc = 1))  then
                wsqlbase = wsqlbase|| 'left outer join VRH_BASE_TSERVTERC SERV ON SERV.BDCODTER = f.BDCODTER AND SERV.BDCODEMP = F.BDCODEMP AND SERV.BDCODSERV = F.BDCODSERV   ' ;

         IF ((pragrupasetor = 1) or (prsetor is not null) and (prsetor <> '')) THEN
            wsqlbase = wsqlbase||' LEFT OUTER JOIN TTERCEIRO_EMP_CENTROS_TPCC VINC ON VINC.BDCODEMP = F.BDCODEMP AND VINC.BDCODTER = F.BDCODTER ' ||
                         '         AND VINC.BDREFERENCIA = (SELECT MAX(X.BDREFERENCIA) FROM TTERCEIRO_EMP_CENTROS_TPCC X ' ||
                         '                                  WHERE X.BDCODEMP = F.BDCODEMP AND X.BDCODTER = F.BDCODTER  '  ||
                         '                                  AND X.BDREFERENCIA <=F.bdrefinssserv )'      ;

            wwherebase = '';
            IF (premp IS NOT NULL AND premp <> '') THEN
                BEGIN
                    wwherebase = wwherebase||' and '||replace(premp, 'BDCODEMP', 'F.BDCODEMP');
        
                    IF (praut IS NOT NULL AND praut <> '') THEN
                        wwherebase = wwherebase||' and '||replace(PRAUT, 'BDCODTER', 'F.BDCODTER');
                END

        if ((prsetor is not null) and (prsetor <> '')) then
            wsqlbase = wsqlbase||' AND '||replace(prsetor, 'BDCODTPCC', 'VINC.BDCODTPCC');
 


        if ((prsetor is not null) and (prsetor <> '')) then
            wwherebase = wwherebase||' and '||replace(prsetor, 'BDCODTPCC', 'VINC.BDCODTPCC');


        if  ((prcc is not null) and (prcc <> '')) then
            wwherebase = wwherebase|| ' and ' || replace(prcc, 'BDCODTPCC', 'SERV.BDCODTPCC')  ;

                 wsql = wsql||  wCampoSelectRef || wsqlbase || ' where (F.bdrefinssserv BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;

                 wsql = wsql|| ' UNION ' ;
                 wCampoSelectRef = 'select F.bdcodemp, F.BDREFIRRFESOCIAL BDREF, ';
                 wsql = wsql|| wCampoSelectRef || wsqlbase || ' where (F.BDREFIRRFESOCIAL BETWEEN '||prrefini||' AND '||prreffim||' )  ' || wwherebase;


     END

     wsqlFinal = 'select FOLHA.BDCODEMP, FOLHA.BDCODEMP BDCODFILIAL, FOLHA.BDREF, FOLHA.BDTIPOCOL, FOLHA.BDCODCOL, FOLHA.BDVALV, ' ||
            ' COALESCE(FOLHA.BDCODCENTRO,0) BDCODCENTRO, COALESCE(FOLHA.BDCODTPCC, 0) BDCODTPCC, ' ||
            ' COALESCE(FOLHA.BDCODCENTROSETOR,0) BDCODCENTROSETOR, COALESCE(FOLHA.BDCODSETOR,0) BDCODSETOR ';

     wsqlFinal = wsqlFinal || 'from ('||wsql||') FOLHA '||
            'order by FOLHA.BDCODEMP, FOLHA.BDREF, FOLHA.BDCODCOL, FOLHA.BDCODTPCC';
                                                                         

  FOR EXECUTE STATEMENT wsqlFinal INTO
    :BDCODEMP, :BDCODFILIAL, :BDREF, :BDTIPOCOL, :BDCODCOL, :BDVALOR, :BDCODCENTRO, :BDCODTPCC, :BDCODCENTROSETOR, :BDCODSETOR
  DO
    SUSPEND;
END^



create or alter procedure SP_VRH_RELATORIOCONFIGURAVEL_COL (
    PREMP varchar(10000),
    PRCOL varchar(20000),
    PRAUT varchar(10000),
    PRCLA varchar(5000),
    PRSIND varchar(5000),
    PRFUC varchar(5000),
    PRREFINI integer,
    PRREFFIM integer,
    PRSITCOL smallint,
    PRAGRUPACC smallint = 0,
    PRCC varchar(10000) = null,
    PRAGRUPASETOR smallint = 0,
    PRSETOR varchar(10000) = null,
    PRPAGTOIR smallint = 0)
returns (
    BDCODEMP integer,
    BDREF integer,
    BDTIPOCOL integer,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDDATACADTER date,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDNOMTPCC DM_BDNOMEMP,
    BDCODFILIAL integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCODCENTROSETOR integer,
    BDCODSETOR integer,
    BDNOMSETOR DM_BDNOMEMP)
as
declare variable WCLAVER varchar(20);
declare variable WSQL varchar(32700);
declare variable WWHEREFILTRO varchar(32000);
declare variable WVERBA integer;
declare variable WCODEMP integer;
declare variable WEMPATU integer;
declare variable WTIPOCOL integer;
declare variable WTIPOCOLATU integer;
declare variable WREF integer;
declare variable WREFATU integer;
declare variable WCODCOL integer;
declare variable WCOLATU integer;
declare variable WRAUX integer;
declare variable WAAUX integer;
declare variable WTAUX integer;
declare variable WCODCENTRO integer;
declare variable WCENTROATU integer;
declare variable WCODTPCC integer;
declare variable WTPCCATU integer;
declare variable WCODCENTROSETOR integer;
declare variable WCENTROSETORATU integer;
declare variable WCODSETOR integer;
declare variable WSETORATU integer;
declare variable WSQLAUX varchar(1000);
declare variable WRETORNA smallint;
declare variable WNOMEMP DM_BDNOMEMP;
declare variable WPRIVEZ smallint;
declare variable WCODFILIAL integer;
declare variable WFILIALATU integer;
declare variable WOK integer;
declare variable WOKREGANT integer;
declare variable WDTAUX varchar(10);
BEGIN
  /* prsitcol
     0 = Somente ativos
     1 = Todos
     2 = Somente os demitidos
     3 = Somente admitidos no mês
     4 = Somente demitidos no mês
     5 = Ativos sem os demitidos no mês
     6 = Ativos sem demitidos com transferência
     7 = Ativos sem afastados o mês inteiro
     8 = Afastados o mês inteiro
   */

  wsql = '';

  premp = upper(premp);
  prcol = upper(prcol);

  wsql = 'select FOLHA.BDCODEMP, FOLHA.BDREF, FOLHA.BDTIPOCOL, FOLHA.BDCODCOL,  COALESCE(FOLHA.BDCODCENTRO,0), COALESCE(FOLHA.BDCODTPCC, 0), FOLHA.BDCODFILIAL, COALESCE(FOLHA.BDCODCENTROSETOR, 0), COALESCE(FOLHA.BDCODSETOR, 0) '||
         'from SP_VRH_RELATORIOCONFCOL_FN(';

  if (premp is null) then
     wsql = wsql||'null,';
  else
     wsql = wsql||''''||premp||''',';

  if (prcol is null) then
     wsql = wsql||'null,';
  else
     wsql = wsql||''''||prcol||''',';

  if (coalesce(prfuc, '') <> '') then
     begin
       wsql = wsql||'null,';
     end
  else
     begin
       if (praut is null) then
          wsql = wsql||'null,';
       else
          wsql = wsql||''''||praut||''',';
     end

  wsql = wsql||prrefini||',';
  wsql = wsql||prreffim||',';
  wsql = wsql||pragrupacc||',';

  if (prcc is null) then
     wsql = wsql||'null,';
  else
     wsql = wsql||''''||prcc||''', ';

  wsql = wsql||pragrupasetor||',';

  if (prsetor is null) then
     wsql = wsql||'null, ';
  else
     wsql = wsql||''''||prsetor||''', ';

  if (PRPAGTOIR is null) then
     wsql = wsql||'0, ';
  else
     wsql = wsql||''''||PRPAGTOIR||''' ';

  wsql = wsql||') FOLHA ';


  BDCODCENTRO = NULL;
  BDCODTPCC = NULL;
  BDCODCENTROSETOR = NULL;
  BDCODSETOR = NULL;
  BDDATACADTER = NULL;

  wempatu = 0;
  wcolatu = 0;
  wtipocolatu = -1;
  wrefatu = 0;
  wcentroatu = -1;
  wtpccatu = -1;
  wcentrosetoratu = -1;
  wsetoratu = -1;
  wprivez = 0;
  wfilialatu = 0;

  FOR EXECUTE STATEMENT wsql INTO :wcodemp, :wref, :wtipocol, :wcodcol,  :wcodcentro, :wcodtpcc, :wcodfilial, :wcodcentrosetor, :wcodsetor DO
    BEGIN
      BDDATACADTER = NULL;
      IF ((wempatu <> wcodemp) OR (wrefatu <> wref) OR (wcolatu <> wcodcol) OR (wtpccatu <> wcodtpcc)  OR (wsetoratu <> wcodsetor) or (wfilialatu <> wcodfilial)) THEN
         begin
      wok = 1;

           if ((coalesce(prcla,  '') <> '') or
              (coalesce(prsind,  '') <> '') or
              (coalesce(prfuc,  '') <> '') or
              (coalesce(prcc,  '') <> '')) then
         begin
           if (coalesce(wtipocol, 0) = 2) then
                   begin
                     /* terceiro */
                     wsqlaux = 'select first 1 * from VRH_BASE_TTERC_VINC where BDCODTER = '||wcodcol||' and BDREFTERC <= '||wref||' order by BDREFTERC DESC';
                     wsqlaux = 'select first 1 coalesce(BDCODTER,0) from ('||wsqlaux||') ';
                   end
           else
                   begin
                     /* Colaboradores */
                     wsqlaux = 'select first 1 * from VRH_EMP_TCOLCON_VINC where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||' and BDREFCOL <= '||wref||' order by BDREFCOL DESC';
                     wsqlaux = 'select first 1 coalesce(bdcodcol,0) from ('||wsqlaux||') ';
         end
        
                wwherefiltro = '';
                if (coalesce(prcla,  '') <> '') then
         begin
                     wwherefiltro = ' where '||prcla;
                   end
           
                if (wwherefiltro <> '') then
                   begin
                     wok = 0;
                     execute statement wsqlaux||wwherefiltro into :wok;
              wok = coalesce(wok, 0);
         end

                wwherefiltro = '';
      if (coalesce(prsind,  '') <> '') then
         begin
                     if (coalesce(wtipocol, 0) <> 2) then
                        begin
                          wsqlaux = 'select first 1 * from VRH_EMP_TCOL_VINC where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||' and BDREFCOL <= '||wref||' order by BDREFCOL DESC';
                          wsqlaux = 'select first 1 coalesce(bdcodcol,0) from ('||wsqlaux||') ';
                        end
                     wwherefiltro = ' where ';
                     wwherefiltro = wwherefiltro||prsind;
                   end
        
                if ((wok > 0) and (wwherefiltro <> '')) then
                   begin
                     wok = 0;
                     execute statement wsqlaux||wwherefiltro into :wok;
              wok = coalesce(wok, 0);
         end
        
                select first 1 ULTDIA from ULTIMO_DIA_MES(CAST(SUBSTRING(:wref FROM 5 FOR 2) AS SMALLINT), CAST(SUBSTRING(:wref FROM 1 FOR 4) AS INTEGER)) into :wdtaux;
                wdtaux = SUBSTRING(:wref FROM 5 FOR 2)||'-'||lpad(wdtaux,  2, '0')||'-'||SUBSTRING(:wref FROM 1 FOR 4);

                wwherefiltro = '';
                if ((wok > 0) and (coalesce(wtipocol, 0) <> 2)) then
                   begin
                     wsqlaux = 'select first 1 * from VRH_EMP_TCOL_VINCDIA where BDCODEMP = '||wcodemp||' and BDCODCOL = '||wcodcol||' and BDDATACOL <= '''||wdtaux||''' order by BDDATACOL DESC';
                     wsqlaux = 'select first 1 coalesce(bdcodcol,0) from ('||wsqlaux||') ';
      if (coalesce(prfuc,  '') <> '') then
         begin
                          if (wwherefiltro <> '') then
                             wwherefiltro = wwherefiltro||' and ';
                          else
                             wwherefiltro = ' where ';
                          wwherefiltro = wwherefiltro||prfuc;
                        end
        
                     if (wwherefiltro <> '') then
                        begin
                          wok = 0;
                          execute statement wsqlaux||wwherefiltro into :wok;
              wok = coalesce(wok, 0);
         end
                   end
              end
         end

      if (wOk = 0) then
        wOKRegAnt = 0;

      if ((coalesce(wOK, 0) > 0) or (coalesce(wOKRegAnt, 0) > 0)) then
         begin
           wOKRegAnt = wOk;
           IF (wempatu = 0) THEN
              wempatu = wcodemp;
           IF (wrefatu = 0) THEN
              wrefatu = wref;
           IF (wtipocolatu = -1) THEN
              wtipocolatu = wtipocol;
           IF (wcolatu = 0) THEN
              wcolatu = wcodcol;
           IF (wcentroatu = -1) THEN
              wcentroatu = wcodcentro;
           IF (wtpccatu = -1) THEN
              wtpccatu = wcodtpcc;
           IF (wcentrosetoratu = -1) THEN
              wcentrosetoratu = wcodcentrosetor;
           IF (wsetoratu = -1) THEN
              wsetoratu = wcodsetor;
           IF (wfilialatu = 0) THEN
              wfilialatu = wcodfilial;
          
           IF ((wempatu <> wcodemp) OR (wrefatu <> wref) OR (wcolatu <> wcodcol) OR (wtpccatu <> wcodtpcc)  OR (wsetoratu <> wcodsetor) or (wfilialatu <> wcodfilial)) THEN
              BEGIN
                BDCODEMP    = wempatu;
                BDREF       = wrefatu;
                BDCODCOL    = wcolatu;
                BDCODCENTRO = wcentroatu;
                BDCODTPCC   = wtpccatu;
                BDCODFILIAL = wfilialatu;
                BDCODCENTROSETOR = wcentrosetoratu;
                BDCODSETOR  = wsetoratu;

                 IF (BDCODCENTRO > 0 AND BDCODTPCC > 0) THEN
                    BEGIN
                      wsqlaux = 'select first 1 case when TRIM(COALESCE(CCRH.BDNOMETOM, '''')) <> '''' then CCRH.BDNOMETOM else CC.BDNOMCTA end BDNOMCC from CENTROS_TPCC CC '||
                                'left outer join VRH_BASE_TCUSTOM CCRH on (CCRH.BDCODCENTRO = CC.BDCODCENTRO and CCRH.BDCODTPCC = CC.BDCODTPCC) '||
                                'where CC.BDCODCENTRO = '||BDCODCENTRO||' and CC.BDCODTPCC = '||BDCODTPCC;
                      EXECUTE STATEMENT wsqlaux INTO :BDNOMTPCC;
                    END
                 ELSE
                    BDNOMTPCC = wnomemp;

                 IF (BDCODCENTROSETOR > 0 AND BDCODSETOR > 0) THEN
                    BEGIN
                      wsqlaux = 'select first 1 case when TRIM(COALESCE(CCRH.BDNOMETOM, '''')) <> '''' then CCRH.BDNOMETOM else CC.BDNOMCTA end BDNOMCC from CENTROS_TPCC CC '||
                                'left outer join VRH_BASE_TCUSTOM CCRH on (CCRH.BDCODCENTRO = CC.BDCODCENTRO and CCRH.BDCODTPCC = CC.BDCODTPCC) '||
                                'where CC.BDCODCENTRO = '||BDCODCENTROSETOR||' and CC.BDCODTPCC = '||BDCODSETOR;
                      EXECUTE STATEMENT wsqlaux INTO :BDNOMSETOR;
                    END
                 ELSE
                    BDNOMSETOR = wnomemp;

                IF (wtipocolatu = 2) THEN
                   BEGIN
                     SELECT FIRST 1 SUBSTRING(T.BDNOMETER FROM 1 FOR 70), SUBSTRING(UPPER(T.BDNOMETER) FROM 1 FOR 70), T.BDDATACADTER from TTERCEIRO TER
                        left outer join  TTERCEIRO_REF T on TER.BDCODTER = T.BDCODTER
                        and t.bdrefemp = (select FIRST 1 tr.bdrefemp from TTERCEIRO_REF tr where tr.bdcodter = ter.bdcodter order by tr.bdrefemp desc)
                     WHERE TER.BDCODTER = :wcolatu INTO :BDNOMCOL, :BDNOMCOLUPPER, :BDDATACADTER;

                   END
                ELSE
                   BEGIN
                     SELECT CAD.BDNOMCOL, UPPER(CAD.BDNOMCOL),  SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 6 FOR 2) BDREFADMCOL, R.BDREFRESCISAO, PR.BDTIPOMOV
                     FROM VRH_EMP_TCOLCON C
                     LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD CAD ON (CAD.BDCODEMP = C.BDCODEMP AND CAD.BDCODCOL = C.BDCODCOL)
                     LEFT OUTER JOIN VRH_EMP_TRESCISAO R ON (R.BDCODEMP = C.BDCODEMP AND R.BDCODCOL = C.BDCODCOL)
                     LEFT OUTER JOIN VRH_BASE_TPREPRESC PR ON (PR.BDCODPRES = R.BDCODPRES)
                     WHERE C.BDCODEMP = :wfilialatu AND C.BDCODCOL = :wcolatu INTO :BDNOMCOL, :BDNOMCOLUPPER, :waaux, :wraux, :wtaux;
                    
                   END
          
                wsqlaux = 'select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC';
                EXECUTE STATEMENT wsqlaux INTO: BDNOMEMP;
                BDTIPOCOL   = wtipocolatu;
                wretorna = 0;
                IF (wtipocolatu IN (0,1)) THEN
                   BEGIN
                     IF (prsitcol = 0) THEN   -- somente ativos
                        BEGIN
                          IF (COALESCE(waaux,0) > wrefatu) THEN
                             wretorna = 1;
          
                          IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) < wrefatu) THEN
                             wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 2) THEN   -- somente os demitidos
                        BEGIN
                          IF (COALESCE(waaux,0) > wrefatu) THEN
                             wretorna = 1;
          
                          IF ((COALESCE(wraux,0) = 0) OR (COALESCE(wraux,0) > wrefatu)) THEN
                             wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 3) THEN   -- admitidos no mês
                        BEGIN
                          IF (COALESCE(waaux,0) <> wrefatu) THEN
                             wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 4) THEN   -- somente os demitidos no mês
                        BEGIN
                          IF (COALESCE(waaux,0) > wrefatu) THEN
                             wretorna = 1;
          
                          IF (COALESCE(wraux,0) <> wrefatu) THEN
                             wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 5) THEN   -- ativos sem os demitidos no mês
                        BEGIN
                          IF (COALESCE(waaux,0) > wrefatu) THEN
                             wretorna = 1;
          
                          IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) <= wrefatu) THEN
                             wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 6) THEN   -- ativos sem os demitidos com transferência
                        BEGIN
                          IF (COALESCE(waaux,0) > wrefatu) THEN
                             wretorna = 1;
          
                          IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) <= wrefatu AND COALESCE(wtaux,0) = 0) THEN
                             wretorna = 1;
          
                          IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) < wrefatu AND COALESCE(wtaux,0) = 1) THEN
                             wretorna = 1;
                        END
                     ELSE
                     IF (prsitcol = 7) THEN   -- ativos sem os afastados o mês inteiro
                        BEGIN
                          IF (COALESCE(waaux,0) > wrefatu) THEN
                             wretorna = 1;
          
                          IF (wretorna = 0) THEN
                             BEGIN
                               wsqlaux = 'select first 1 BDCODCOL from VRH_EMP_TSITCOL where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||
                                         ' and SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                                         ' and ((BDDATAFIMSIT is null) or (SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';
          
                               EXECUTE STATEMENT wsqlaux INTO :wretorna;
          
                               IF (COALESCE(wretorna,0) > 0) THEN
                                  wretorna = 1;
                               ELSE
                                  wretorna = 0;
                             END
                        END
                     ELSE
                     IF (prsitcol = 8) THEN   -- afastados o mês inteiro
                        BEGIN
                          IF (COALESCE(waaux,0) > wrefatu) THEN
                             wretorna = 1;
          
                          IF (wretorna = 0) THEN
                             BEGIN
                               wsqlaux = 'select first 1 BDCODCOL from VRH_EMP_TSITCOL where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||
                                         ' and SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                                         ' and ((BDDATAFIMSIT is null) or (SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';
          
                               EXECUTE STATEMENT wsqlaux INTO :wretorna;
          
                               IF (COALESCE(wretorna,0) = 0) THEN
                                  wretorna = 1;
                               ELSE
                                  wretorna = 0;
                             END
                        END
          
                   END
          
                IF (wretorna = 0) THEN
                   BEGIN
                     IF ((wempatu <> wcodemp) OR (wrefatu <> wref) OR (wprivez = 0) or (wfilialatu <> wcodfilial)) THEN
                        BEGIN
                          wsqlaux = 'select first 1 BDAUTEMP, BDEMPEMP, BDFUNEMP, BDCODFPASTERC, BDFAP, BDSIMPLESGPS from VRHF_BASE_TEMPGPS where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC ';

                          wsqlaux = 'select first 1  ';
          
                          IF ((pragrupacc = 1) or (pragrupasetor = 1 )) THEN
                             wsqlaux = wsqlaux||' BDCODCENTROS ';
                          ELSE
                             wsqlaux = wsqlaux||' 0 BDCODCENTROS ';
          
                          wsqlaux = wsqlaux||', BDNOMEMP ';
          
          
                          wsqlaux = wsqlaux||' from TEMPRESAS_REF where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC ';
                          EXECUTE STATEMENT wsqlaux INTO :BDCODCENTRO, :wnomemp;
               
                        END
          
                     wprivez = 1;
          

                     SUSPEND;
                   END
          
                wempatu          = wcodemp;
                wrefatu          = wref;
                wtipocolatu      = wtipocol;
                wcolatu          = wcodcol;
                wcentroatu       = wcodcentro;
                wtpccatu         = wcodtpcc;
                wcentrosetoratu  = wcodcentrosetor;
                wsetoratu        = wcodsetor;
                wfilialatu       = wcodfilial;

              END
          
           wcentroatu = wcodcentro;
           wcentrosetoratu = wcodcentrosetor;
          
         end
    END


 IF ((coalesce(wok, 0) > 0) and (wempatu <> 0) AND (wrefatu <> 0) AND (wcolatu <> 0) AND (wtpccatu <> -1) and (wfilialatu <> 0)) THEN
    BEGIN
      BDCODEMP    = wempatu;
      BDREF       = wrefatu;
      BDCODCOL    = wcolatu;
      BDCODCENTRO = wcentroatu;
      BDCODTPCC   = wtpccatu;
      BDCODFILIAL = wfilialatu;
      BDCODCENTROSETOR = wcentrosetoratu;
      BDCODSETOR   = wsetoratu;
      waaux       = 0;
      wraux       = 0;
      wtaux       = 0;

     IF (BDCODCENTRO > 0 AND BDCODTPCC > 0) THEN
        BEGIN
          wsqlaux = 'select first 1 case when TRIM(COALESCE(CCRH.BDNOMETOM, '''')) <> '''' then CCRH.BDNOMETOM else CC.BDNOMCTA end BDNOMCC from CENTROS_TPCC CC '||
                    'left outer join VRH_BASE_TCUSTOM CCRH on (CCRH.BDCODCENTRO = CC.BDCODCENTRO and CCRH.BDCODTPCC = CC.BDCODTPCC) '||
                    'where CC.BDCODCENTRO = '||BDCODCENTRO||' and CC.BDCODTPCC = '||BDCODTPCC;
          EXECUTE STATEMENT wsqlaux INTO :BDNOMTPCC;
        END
     ELSE
        BDNOMTPCC = wnomemp;

     IF (BDCODCENTROSETOR > 0 AND BDCODSETOR > 0) THEN
        BEGIN
          wsqlaux = 'select first 1 case when TRIM(COALESCE(CCRH.BDNOMETOM, '''')) <> '''' then CCRH.BDNOMETOM else CC.BDNOMCTA end BDNOMCC from CENTROS_TPCC CC '||
                    'left outer join VRH_BASE_TCUSTOM CCRH on (CCRH.BDCODCENTRO = CC.BDCODCENTRO and CCRH.BDCODTPCC = CC.BDCODTPCC) '||
                    'where CC.BDCODCENTRO = '||BDCODCENTROSETOR||' and CC.BDCODTPCC = '||BDCODSETOR;
          EXECUTE STATEMENT wsqlaux INTO :BDNOMSETOR;
        END
     ELSE
        BDNOMSETOR = wnomemp;

      IF (wtipocolatu = 2) THEN
         BEGIN
             SELECT FIRST 1 SUBSTRING(T.BDNOMETER FROM 1 FOR 70), SUBSTRING(UPPER(T.BDNOMETER) FROM 1 FOR 70), T.BDDATACADTER from TTERCEIRO TER
                 left outer join  TTERCEIRO_REF T on TER.BDCODTER = T.BDCODTER
                 and t.bdrefemp = (select FIRST 1 tr.bdrefemp from TTERCEIRO_REF tr where tr.bdcodter = ter.bdcodter order by tr.bdrefemp desc)
             WHERE TER.BDCODTER = :wcolatu INTO :BDNOMCOL, :BDNOMCOLUPPER, :BDDATACADTER;
         END
      ELSE
         BEGIN
           SELECT CAD.BDNOMCOL, UPPER(CAD.BDNOMCOL), SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(C.BDDATAADMCOL AS VARCHAR(10)) FROM 6 FOR 2) BDREFADMCOL, R.BDREFRESCISAO, PR.BDTIPOMOV
           FROM VRH_EMP_TCOLCON C
           LEFT OUTER JOIN VW_VRH_EMP_TCOLCON_CAD CAD ON (CAD.BDCODEMP = C.BDCODEMP AND CAD.BDCODCOL = C.BDCODCOL)
           LEFT OUTER JOIN VRH_EMP_TRESCISAO R ON (R.BDCODEMP = C.BDCODEMP AND R.BDCODCOL = C.BDCODCOL)
           LEFT OUTER JOIN VRH_BASE_TPREPRESC PR ON (PR.BDCODPRES = R.BDCODPRES)
           WHERE C.BDCODEMP = :wfilialatu AND C.BDCODCOL = :wcolatu INTO :BDNOMCOL, :BDNOMCOLUPPER, :waaux, :wraux, :wtaux;

         END

      wsqlaux = 'select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC';
      EXECUTE STATEMENT wsqlaux INTO: BDNOMEMP;
      BDTIPOCOL = wtipocolatu;
      wretorna  = 0;
      IF (wtipocolatu IN (0,1)) THEN
         BEGIN
           IF (prsitcol = 0) THEN   -- somente ativos
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) < wrefatu) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 2) THEN   -- somente os demitidos
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF ((COALESCE(wraux,0) = 0) OR (COALESCE(wraux,0) > wrefatu)) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 3) THEN   -- admitidos no mês
              BEGIN
                IF (COALESCE(waaux,0) <> wrefatu) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 4) THEN   -- somente os demitidos no mês
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) <> wrefatu) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 5) THEN   -- ativos sem os demitidos no mês
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) <= wrefatu) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 6) THEN   -- ativos sem os demitidos com transferência
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) <= wrefatu AND COALESCE(wtaux,0) = 0) THEN
                   wretorna = 1;

                IF (COALESCE(wraux,0) > 0 AND COALESCE(wraux,0) < wrefatu AND COALESCE(wtaux,0) = 1) THEN
                   wretorna = 1;
              END
           ELSE
           IF (prsitcol = 7) THEN   -- ativos sem os afastados o mês inteiro
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (wretorna = 0) THEN
                   BEGIN
                     wsqlaux = 'select first 1 BDCODCOL from VRH_EMP_TSITCOL where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||
                               ' and SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                               ' and ((BDDATAFIMSIT is null) or (SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';

                     EXECUTE STATEMENT wsqlaux INTO :wretorna;

                     IF (COALESCE(wretorna,0) > 0) THEN
                        wretorna = 1;
                     ELSE
                        wretorna = 0;
                   END
              END
           ELSE
           IF (prsitcol = 8) THEN   -- afastados o mês inteiro
              BEGIN
                IF (COALESCE(waaux,0) > wrefatu) THEN
                   wretorna = 1;

                IF (wretorna = 0) THEN
                   BEGIN
                     wsqlaux = 'select first 1 BDCODCOL from VRH_EMP_TSITCOL where BDCODEMP = '||wfilialatu||' and BDCODCOL = '||wcolatu||
                               ' and SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAINISIT AS VARCHAR(10)) FROM 6 FOR 2) <= '||wrefatu||
                               ' and ((BDDATAFIMSIT is null) or (SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 1 FOR 4)||SUBSTRING(CAST(BDDATAFIMSIT AS VARCHAR(10)) FROM 6 FOR 2) >= '||wrefatu||'))';

                     EXECUTE STATEMENT wsqlaux INTO :wretorna;

                     IF (COALESCE(wretorna,0) = 0) THEN
                        wretorna = 1;
                     ELSE
                        wretorna = 0;
                   END
              END

         END

      IF (wretorna = 0) THEN
         BEGIN
           IF ((wempatu <> wcodemp) OR (wrefatu <> wref) OR (wprivez = 0) or (wfilialatu <> wcodemp)) THEN
              BEGIN

                wsqlaux = 'select first 1  ';

                IF ((pragrupacc = 1) or (pragrupasetor = 1)) THEN
                   wsqlaux = wsqlaux||' BDCODCENTROS ';
                ELSE                   
                   wsqlaux = wsqlaux||' 0 BDCODCENTROS ';

                wsqlaux = wsqlaux||', BDNOMEMP ';


                wsqlaux = wsqlaux||' from TEMPRESAS_REF where BDCODEMP = '||wfilialatu||' and BDREFEMP <= '||wrefatu||' order by BDREFEMP DESC ';
                EXECUTE STATEMENT wsqlaux INTO :BDCODCENTRO, :wnomemp;
     
              END

           wprivez = 1;

           SUSPEND;
         END
    END
END^



CREATE OR ALTER TRIGGER VRH_BASE_TRELCONF_BI0 FOR  VRH_BASE_TRELCONF
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vNumero INTEGER;
  DECLARE VARIABLE vCount INTEGER;
BEGIN
  IF ((NEW.BDCODRELCONF IS NULL) OR (NEW.BDCODRELCONF = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODRELCONF), 0) + 1 FROM VRH_BASE_TRELCONF WHERE BDCODRELCONF < 10000 INTO :vCodigo;

       IF (vCodigo > 9999) THEN
          BEGIN
            vNumero = 1;
            vCount = 1;

            WHILE (vCount <> 0) DO
              BEGIN
                SELECT COUNT(*) FROM VRH_BASE_TRELCONF WHERE BDCODRELCONF = :vNumero AND BDCODRELCONF <= 9999 INTO :vCount;
                vCodigo = vNumero;
                vNumero = vNumero + 1;
                IF (vCodigo > 9999) THEN
                   vCodigo = NULL;
              END
          END
       NEW.BDCODRELCONF = :vCodigo;
     END
END^



CREATE OR ALTER TRIGGER VRH_BASE_TRELCONF_ITENS_BI0 FOR VRH_BASE_TRELCONF_ITENS
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vColuna INTEGER;
BEGIN
  IF ((NEW.BDCODIGO IS NULL) OR (NEW.BDCODIGO = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodigo), 0) + 1 FROM VRH_BASE_TRELCONF_ITENS INTO :vCodigo;
       NEW.BDCODIGO = :vCodigo;
     END

  IF ((NEW.BDCOLUNA IS NULL) OR (NEW.BDCOLUNA = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcoluna), 0) + 1 FROM VRH_BASE_TRELCONF_ITENS
       WHERE BDCODRELCONF = new.BDCODRELCONF INTO :vColuna;
       NEW.BDCOLUNA = :vColuna;
     END
END^

CREATE OR ALTER TRIGGER VCT_DASHBOARD_GRF_USUARIO_BI0 FOR VCT_DASHBOARD_GRF_USUARIO
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vid integer;
begin
  if (coalesce(new.bdusuid, 0) = 0) then
  begin
    select max(bdusuid) from VCT_DASHBOARD_GRF_USUARIO
    where bdgrfid = new.bdgrfid
    into :vid;
    new.bdusuid = coalesce(vid, 0) +1;
  end
  else
  begin
    select bdgrfid from VCT_DASHBOARD_GRF_USUARIO
    where bdgrfid = new.bdgrfid and bdusuid = new.bdusuid
    into :vid;

    if (coalesce(vid, 0) > 0) then
    begin
      select max(bdgrfid) from VCT_DASHBOARD_GRF_USUARIO
      where bdgrfid = new.bdgrfid
      into :vid;
      new.bdusuid = coalesce(vid, 0) +1;
    end
  end
end
^

create or alter procedure SP_RETORNA_BASE_IRRF (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRTIPO integer,
    PRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBASEIRRFMENSAL numeric(18,6),
    BDVALORIRRFMENSAL numeric(18,6),
    BDINSSMENSAL numeric(18,6),
    BDDEPMENSAL numeric(18,6),
    BDPENSAOMENSAL numeric(18,6),
    BDPREVMENSAL numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDINSS13 numeric(18,6),
    BDDEP13 numeric(18,6),
    BDPENSAO13 numeric(18,6),
    BDPREV13 numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDINSSPLR numeric(18,6),
    BDDEPPLR numeric(18,6),
    BDPENSAOPLR numeric(18,6),
    BDPREVPLR numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDINSSRRA numeric(18,6),
    BDDEPRRA numeric(18,6),
    BDPENSAORRA numeric(18,6),
    BDPREVRRA numeric(18,6),
    BDCALCULOS integer)
as
declare variable WBASEIRRFMENSAL numeric(18,6);
declare variable WVALORIRRFMENSAL numeric(18,6);
declare variable WINSSMENSAL numeric(18,6);
declare variable WDEPMENSAL numeric(18,6);
declare variable WPENSAOMENSAL numeric(18,6);
declare variable WPREVMENSAL numeric(18,6);
declare variable WBASEIRRF13 numeric(18,6);
declare variable WVALORIRRF13 numeric(18,6);
declare variable WINSS13 numeric(18,6);
declare variable WDEP13 numeric(18,6);
declare variable WPENSAO13 numeric(18,6);
declare variable WPREV13 numeric(18,6);
declare variable WBASEIRRFPLR numeric(18,6);
declare variable WVALORIRRFPLR numeric(18,6);
declare variable WINSSPLR numeric(18,6);
declare variable WDEPPLR numeric(18,6);
declare variable WPENSAOPLR numeric(18,6);
declare variable WPREVPLR numeric(18,6);
declare variable WBASEIRRFRRA numeric(18,6);
declare variable WVALORIRRFRRA numeric(18,6);
declare variable WINSSRRA numeric(18,6);
declare variable WDEPRRA numeric(18,6);
declare variable WPENSAORRA numeric(18,6);
declare variable WPREVRRA numeric(18,6);
declare variable WCALCULOS integer;
begin
  BDBASEIRRFMENSAL = 0;
  BDVALORIRRFMENSAL = 0;
  BDINSSMENSAL = 0;
  BDDEPMENSAL = 0;
  BDPENSAOMENSAL = 0;
  BDPREVMENSAL = 0;
  BDBASEIRRF13 = 0;
  BDVALORIRRF13 = 0;
  BDINSS13 = 0;
  BDDEP13 = 0;
  BDPENSAO13 = 0;
  BDPREV13 = 0;
  BDBASEIRRFPLR = 0;
  BDVALORIRRFPLR = 0;
  BDINSSPLR = 0;
  BDDEPPLR = 0;
  BDPENSAOPLR = 0;
  BDPREVPLR = 0;
  BDBASEIRRFRRA = 0;
  BDVALORIRRFRRA = 0;
  BDINSSRRA = 0;
  BDDEPRRA = 0;
  BDPENSAORRA = 0;
  BDPREVRRA = 0;
  BDCALCULOS = 0;

  if (prtipo = 1) then
   BEGIN
       for
          SELECT SUM(Q2.BDRENDTRIBUTAVEL) BDRENDTRIBUTAVEL, SUM(Q2.BDIR) BDIR, IIF(SUM(Q2.BDINSS) > 0, SUM(Q2.BDINSS), 0) as BDINSS, IIF(:prveiodototalizador = 0, CASE WHEN SUM(Q2.BDRENDTRIBUTAVEL) > 0 THEN SUM(Q2.BDDEP) ELSE 0 END, SUM(Q2.BDDEP)) as BDDEP, SUM(Q2.BDPENALIM) BDPENALIM, SUM(Q2.BDPREVPRIV) BDPREVPRIV, SUM(Q2.BDCALCULOS) BDCALCULOS
          FROM
          (
            SELECT SUM(Q1.BDRENDTRIBUTAVEL) BDRENDTRIBUTAVEL, SUM(Q1.BDIR) BDIR, SUM(Q1.BDINSS) BDINSS, MAX(Q1.BDDEP) BDDEP, SUM(Q1.BDPENALIM) BDPENALIM, SUM(Q1.BDPREVPRIV) BDPREVPRIV, SUM(Q1.BDCALCULOS) BDCALCULOS
            FROM
            (
                SELECT FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDDEP, COALESCE(FT.BDPENJUD, 0) + COALESCE(FT.bdpenalim, 0) bdpenalim, FT.BDPREVPRIV, 1 as BDCALCULOS
                FROM SP_VRHF_DADOS_IR_FN('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 0, 0, 0, TRUE, FALSE, :prveiodototalizador) FT
            
                UNION ALL
            
                SELECT FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDDEP, COALESCE(FT.BDPENJUD, 0) + COALESCE(FT.bdpenalim, 0) bdpenalim, FT.BDPREVPRIV, 1 as BDCALCULOS
                FROM SP_VRHF_DADOS_IR_FC('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 0, 0, 0, TRUE, FALSE,0, :prveiodototalizador) FT

                UNION ALL
            
                SELECT FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDDEP, COALESCE(FT.BDPENJUD, 0) + COALESCE(FT.bdpenalim, 0) bdpenalim, FT.BDPREVPRIV, 1 as BDCALCULOS
                FROM SP_VRHF_DADOS_IR_FC_INT('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 0, 0, 0, TRUE) FT
            
            
                UNION ALL
            
                SELECT FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDDEP, COALESCE(FT.BDPENJUD, 0) + COALESCE(FT.bdpenalim, 0) bdpenalim, FT.BDPREVPRIV, 1 as BDCALCULOS
                FROM SP_VRHF_DADOS_IR_INT('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 0, 0, 0, TRUE, FALSE,:prveiodototalizador) FT
            
                UNION ALL
            
                SELECT FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDDEP, COALESCE(FT.BDPENJUD, 0) + COALESCE(FT.bdpenalim, 0) bdpenalim, FT.BDPREVPRIV, 1 as BDCALCULOS
                FROM SP_VRHF_DADOS_IR_AD('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', TRUE, FALSE) FT
                WHERE FT.BDRENDTRIBUTAVEL > 0
            
                UNION ALL
            
                SELECT FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDDEP, COALESCE(FT.BDPENJUD, 0) + COALESCE(FT.bdpenalim, 0) bdpenalim, FT.BDPREVPRIV, 1 as BDCALCULOS
                FROM SP_VRHF_DADOS_IR_FA('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 0, 1, TRUE, FALSE, :prveiodototalizador) FT
            ) Q1
    
            UNION ALL
        
            SELECT FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDDEP, COALESCE(FT.BDPENJUD, 0) + COALESCE(FT.bdpenalim, 0) bdpenalim, FT.BDPREVPRIV, 1 as BDCALCULOS
            FROM SP_VRHF_DADOS_IR_FE('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 0, TRUE) FT
    
           ) Q2
    
        into :WBASEIRRFMENSAL, :WVALORIRRFMENSAL, :WINSSMENSAL, :WDEPMENSAL, :WPENSAOMENSAL, :WPREVMENSAL, :WCALCULOS
    
      do
       begin
          BDBASEIRRFMENSAL = BDBASEIRRFMENSAL + COALESCE(:WBASEIRRFMENSAL, 0);
          BDVALORIRRFMENSAL = BDVALORIRRFMENSAL + COALESCE(:WVALORIRRFMENSAL, 0);
          BDINSSMENSAL = BDINSSMENSAL + COALESCE(:WINSSMENSAL, 0);
          BDDEPMENSAL = BDDEPMENSAL + COALESCE(:WDEPMENSAL, 0);
          BDPENSAOMENSAL = BDPENSAOMENSAL + COALESCE(:WPENSAOMENSAL, 0);
          BDPREVMENSAL = BDPREVMENSAL + COALESCE(:WPREVMENSAL, 0);
          BDCALCULOS = BDCALCULOS + COALESCE(:WCALCULOS, 0);
       end
   END
   ELSE BEGIN
       for
        SELECT FT.bdbaseir, FT.bdvalorir, IIF(FT.bdvalorinss > 0, FT.bdvalorinss , 0) as bdvalorinss, FT.bdvalordep, 0 AS BDPENSAOMENSAL, 0 AS BDPREVMENSALES, 1 as BDCALCULOS
        FROM VRHF_SP_CONS_IR_TERCEIROS('CALC_TERC.BDCODEMP='||:PRCODEMP, 'CALC_TERC.BDCODTER='||:PRCODCOL, :PRREF, :PRREF, TRUE) FT

        into :WBASEIRRFMENSAL, :WVALORIRRFMENSAL, :WINSSMENSAL, :WDEPMENSAL, :WPENSAOMENSAL, :WPREVMENSAL, :WCALCULOS
    
      do
       begin
          BDBASEIRRFMENSAL = BDBASEIRRFMENSAL + COALESCE(:WBASEIRRFMENSAL, 0);
          BDVALORIRRFMENSAL = BDVALORIRRFMENSAL + COALESCE(:WVALORIRRFMENSAL, 0);
          BDINSSMENSAL = BDINSSMENSAL + COALESCE(:WINSSMENSAL, 0);
          BDDEPMENSAL = BDDEPMENSAL + COALESCE(:WDEPMENSAL, 0);
          BDPENSAOMENSAL = BDPENSAOMENSAL + COALESCE(:WPENSAOMENSAL, 0);
          BDPREVMENSAL = BDPREVMENSAL + COALESCE(:WPREVMENSAL, 0);
          BDCALCULOS = BDCALCULOS + COALESCE(:WCALCULOS, 0);
       end

   END
  -----------------------------------------------------------------------------------------------------------------
  if (prtipo = 1) then
   BEGIN
       for
        SELECT SUM(Q1.BDRENDTRIBUTAVEL) BDRENDTRIBUTAVEL, SUM(Q1.BDIR) BDIR, IIF(SUM(Q1.BDINSS) > 0, SUM(Q1.BDINSS), 0) as BDINSS, AVG(Q1.BDDEP) BDDEP, SUM(Q1.BDPENALIM) BDPENALIM, SUM(Q1.BDPREVPRIV) BDPREVPRIV
        FROM
        (
            SELECT FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDDEP, COALESCE(FT.BDPENJUD, 0) + COALESCE(FT.BDPENALIM, 0) BDPENALIM, FT.BDPREVPRIV
            FROM SP_VRHF_DADOS_IR_13('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', TRUE, FALSE, TRUE, :prveiodototalizador) FT
            WHERE FT.BDTIPO NOT IN (111)
        
            UNION ALL
        
            SELECT FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDDEP, COALESCE(FT.BDPENJUD, 0) + COALESCE(FT.BDPENALIM, 0) BDPENALIM, FT.BDPREVPRIV
            FROM SP_VRHF_DADOS_IR_13FC('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', TRUE, 0) FT
        
            UNION ALL
        
            SELECT FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDDEP, COALESCE(FT.BDPENJUD, 0) + COALESCE(FT.BDPENALIM, 0) BDPENALIM, FT.BDPREVPRIV
            FROM SP_VRHF_DADOS_IR_13FC_INT('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', TRUE) FT
        
            UNION ALL
        
            SELECT FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, S13.BDDEP13, COALESCE(FT.BDPENJUD, 0) + COALESCE(FT.BDPENALIM, 0) BDPENALIM, FT.BDPREVPRIV
            FROM SP_VRHF_DADOS_IR_C13('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', TRUE, FALSE, 0) FT
            INNER JOIN VRHF_EMP_T13SAL S13 ON FT.BDCODEMP = S13.BDCODEMP AND FT.BDCODCOL = S13.BDCODCOL AND FT.BDREF = S13.BDREF13
        
            UNION ALL
        
            SELECT FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDDEP, COALESCE(FT.BDPENJUD, 0) + COALESCE(FT.BDPENALIM, 0) BDPENALIM, FT.BDPREVPRIV
            FROM SP_VRHF_DADOS_IR_INT13('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 1, TRUE, FALSE, :prveiodototalizador) FT
            WHERE FT.BDTIPO NOT IN (111)
        
            UNION ALL
        
            SELECT FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDDEP, COALESCE(FT.BDPENJUD, 0) + COALESCE(FT.BDPENALIM, 0) BDPENALIM, FT.BDPREVPRIV
            FROM SP_VRHF_DADOS_IR_AD13('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '') FT
        ) Q1

        into :WBASEIRRF13, :WVALORIRRF13, :WINSS13, :WDEP13, :WPENSAO13, :WPREV13
    
      do
       begin
          BDBASEIRRF13 = BDBASEIRRF13 + COALESCE(:WBASEIRRF13, 0);
          BDVALORIRRF13 = BDVALORIRRF13 + COALESCE(:WVALORIRRF13, 0);
          BDINSS13 = BDINSS13 + COALESCE(:WINSS13, 0);
          BDDEP13 = BDDEP13 + COALESCE(:WDEP13, 0);
          BDPENSAO13 = BDPENSAO13 + COALESCE(:WPENSAO13, 0);
          BDPREV13 = BDPREV13 + COALESCE(:WPREV13, 0);
       end
    
      -----------------------------------------------------------------------------------------------------------------
      for
        SELECT FT.BDRENDTRIBUTAVEL, FT.BDIR, IIF(FT.BDINSS > 0,FT.BDINSS,0) as BDINSS , CASE WHEN FT.BDTIPO <> 100 THEN FT.BDDEP ELSE 0 END, COALESCE(FT.BDPENALIM, 0) + COALESCE(FT.BDPENJUD, 0), FT.BDPREVPRIV
        FROM SP_VRHF_DADOS_IR_FA('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 1, 0, TRUE, FALSE, :prveiodototalizador) FT
        into :WBASEIRRFPLR, :WVALORIRRFPLR, :WINSSPLR, :WDEPPLR, :WPENSAOPLR, :WPREVPLR
    
      -----------------------------------------------------------------------------------------------------------------
      do
       begin
          BDBASEIRRFPLR = BDBASEIRRFPLR + COALESCE(:WBASEIRRFPLR, 0);
          BDVALORIRRFPLR = BDVALORIRRFPLR + COALESCE(:WVALORIRRFPLR, 0);
          BDINSSPLR = BDINSSPLR + COALESCE(:WINSSPLR, 0);
          BDDEPPLR = BDDEPPLR + COALESCE(:WDEPPLR, 0);
          BDPENSAOPLR = BDPENSAOPLR + COALESCE(:WPENSAOPLR, 0);
          BDPREVPLR = BDPREVPLR + COALESCE(:WPREVPLR, 0);
       end

      for
        SELECT FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDDEP, COALESCE(FT.BDPENJUD, 0) + COALESCE(FT.bdpenalim, 0) bdpenalim, FT.BDPREVPRIV
        FROM SP_VRHF_DADOS_IR_FC('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 0, 0, 0, TRUE, FALSE, 1, :prveiodototalizador) FT

        UNION ALL

        SELECT FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDDEP, COALESCE(FT.BDPENJUD, 0) + COALESCE(FT.BDPENALIM, 0) BDPENALIM, FT.BDPREVPRIV
        FROM SP_VRHF_DADOS_IR_13FC('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', TRUE, 1) FT

--        UNION ALL     {217416 - Comentado esse trecho pois valores do complemento de 13º já é demonstrado no campo do 13º então traz indevido esses valores}
--        
--        SELECT FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, S13.BDDEP13, COALESCE(FT.BDPENJUD, 0) + COALESCE(FT.BDPENALIM, 0) BDPENALIM, FT.BDPREVPRIV
--        FROM SP_VRHF_DADOS_IR_C13('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', TRUE, FALSE, 1) FT
--        INNER JOIN VRHF_EMP_T13SAL S13 ON FT.BDCODEMP = S13.BDCODEMP AND FT.BDCODCOL = S13.BDCODCOL AND FT.BDREF = S13.BDREF13

        into :WBASEIRRFRRA, :WVALORIRRFRRA, :WINSSRRA, :WDEPRRA, :WPENSAORRA, :WPREVRRA
    
      -----------------------------------------------------------------------------------------------------------------
      do
       begin
          BDBASEIRRFRRA = BDBASEIRRFRRA + COALESCE(:WBASEIRRFRRA, 0);
          BDVALORIRRFRRA = BDVALORIRRFRRA + COALESCE(:WVALORIRRFRRA, 0);
          if (:WINSSRRA > 0) then
            BDINSSRRA = BDINSSRRA + COALESCE(:WINSSRRA, 0);
          BDDEPRRA = BDDEPRRA + COALESCE(:WDEPRRA, 0);
          BDPENSAORRA = BDPENSAORRA + COALESCE(:WPENSAORRA, 0);
          BDPREVRRA = BDPREVRRA + COALESCE(:WPREVRRA, 0);
  end

  end
suspend;
end^

create or alter procedure SP_RETORNA_BASE_IRRF_ES (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRTERCEIRO varchar(5))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDINSSMENSALES numeric(18,6),
    BDINSS13ES numeric(18,6),
    BDDEPES numeric(18,6),
    BDDEP13ES numeric(18,6),
    BDBASEIRRFMENSALES numeric(18,6),
    BDBASEIRRF13ES numeric(18,6),
    BDBASEIRRFPLRES numeric(18,6),
    BDBASEIRRFRRAES numeric(18,6),
    BDPREVMENSALES numeric(18,6),
    BDPREV13ES numeric(18,6),
    BDPENSAOMENSALES numeric(18,6),
    BDPENSAO13ES numeric(18,6),
    BDPENSAOPLRES numeric(18,6),
    BDPENSAORRAES numeric(18,6),
    BDVALORIRRFMENSALES numeric(18,6),
    BDVALORIRRF13ES numeric(18,6),
    BDVALORIRRFPLRES numeric(18,6),
    BDVALORIRRFRRAES numeric(18,6),
    BDDEPES13 numeric(18,6),
    BDDEPPLRES numeric(18,6),
    BDDEPRRAES numeric(18,6),
    BDINSSRRAES numeric(18,6),
    BDTEMEVENTO integer)
as
declare variable WSQL varchar(1000);
declare variable WVALOR numeric(18,3);
declare variable WTPVALOR numeric(18,3);
declare variable WVLRDEP numeric(18,3);
declare variable WEVT integer;
declare variable WEVTANT integer;
declare variable WRRA DM_BOOLEAN;
begin
  BDBASEIRRFMENSALES = 0;
  BDBASEIRRF13ES = 0;
  BDBASEIRRFPLRES = 0;
  BDBASEIRRFRRAES = 0;

  BDINSSMENSALES = 0;
  BDINSS13ES = 0;
  BDINSSRRAES = 0;

  BDPREVMENSALES = 0;
  BDPREV13ES = 0;
  BDPENSAOMENSALES = 0;
  BDPENSAO13ES = 0;
  BDPENSAOPLRES = 0;
  BDPENSAORRAES = 0;

  BDVALORIRRFMENSALES = 0;
  BDVALORIRRF13ES = 0;
  BDVALORIRRFPLRES = 0;
  BDVALORIRRFRRAES = 0;
  BDDEPES = 0;
  BDDEP13ES = 0;
  BDDEPRRAES = 0;
  BDTEMEVENTO = 0;

  wevtant = -1;

  if (prterceiro = 'FALSE') then -- Parâmetro passado dentro da "SP_REL_TOT_5002" com base nela é feita a consulta na tabela correta.
     begin
        wsql = 'select CP.BDVALOR, CP.BDTPVALOR, CP.BDVRDEDDEP, CP.BDCODEVT, CAST(COALESCE(CP.BDRRA, FALSE) AS BOOLEAN) '||
               'from VRH_ESOCIAL_INFOIRRF_C CP '||
               'where CP.BDCODEMP = '||prcodemp||' and '||
                     'CP.BDCODCOL = '||prcodcol ||' and '||
                     'CP.BDREFEVT =  '||prref||
               ' order by CP.BDCODEVT desc, CP.BDTPVALOR ';
     end
  else
     begin
        wsql = 'select CP.BDVALOR, CP.BDTPVALOR, CP.BDVRDEDDEP, CP.BDCODEVT, CAST(COALESCE(CP.BDRRA, FALSE) AS BOOLEAN) '||
               'from VRH_ESOCIAL_INFOIRRF_TER CP '||
               'where CP.BDCODEMP = '||prcodemp||' and '||
                     'CP.bdcodter = '||prcodcol ||' and '||
                     'CP.BDREFEVT =  '||prref||
               ' order by CP.BDCODEVT desc, CP.BDTPVALOR ';
     end


  for execute statement wsql into :wvalor,:wtpvalor,:wvlrdep, :wevt, :wrra do
    begin
      BDTEMEVENTO = 1;

      if (wevtant = -1) then
         wevtant = wevt;
      else if (wevt <> wevtant) then
         break;

      if (wrra = FALSE) then
         begin
      if (wtpvalor = 11) then
         begin
           BDBASEIRRFMENSALES  = BDBASEIRRFMENSALES  + wvalor;
           BDDEPES = BDDEPES + wvlrdep;
         end
      else if (wtpvalor = 12) then
         begin
           BDBASEIRRF13ES  = BDBASEIRRF13ES  + wvalor;
           BDDEP13ES = BDDEP13ES + wvlrdep;
         end
      else if (wtpvalor = 14) then
         begin
           BDBASEIRRFPLRES  = BDBASEIRRFPLRES  + wvalor;
           BDDEPPLRES = BDDEPPLRES + wvlrdep;
         end
      else if (wtpvalor = 31) then
         begin
           BDVALORIRRFMENSALES = BDVALORIRRFMENSALES + wvalor;
         end
      else if (wtpvalor = 32) then
         begin
           BDVALORIRRF13ES = BDVALORIRRF13ES + wvalor;
               BDDEP13ES = BDDEP13ES + wvlrdep;
         end
      else if (wtpvalor = 34) then
         begin
           BDVALORIRRFPLRES = BDVALORIRRFPLRES + wvalor;
         end
      else if (wtpvalor = 41) then
         begin
           BDINSSMENSALES = BDINSSMENSALES + wvalor;
         end
      else if (wtpvalor = 42) then
         begin
           BDINSS13ES = BDINSS13ES + wvalor;
               BDDEP13ES = BDDEP13ES + wvlrdep;
         end
      else if (wtpvalor in (46, 61, 63)) then
         begin
           BDPREVMENSALES = BDPREVMENSALES + wvalor;
         end
      else if (wtpvalor in (47, 62, 64)) then
         begin
           BDPREV13ES = BDPREV13ES + wvalor;
         end
      else if (wtpvalor = 51) then
         begin
           BDPENSAOMENSALES = BDPENSAOMENSALES + wvalor;
           BDDEPES = BDDEPES + wvlrdep;
         end
      else if (wtpvalor = 52) then
         begin
           BDPENSAO13ES = BDPENSAO13ES + wvalor;
               BDDEP13ES = BDDEP13ES + wvlrdep;
         end
      else if (wtpvalor = 54) then
         begin
           BDPENSAOPLRES = BDPENSAOPLRES + wvalor;
         end
      else if (wtpvalor = 7900) then
         begin
           BDDEPES = BDDEPES + wvlrdep;
         end
         end
      else
         begin
           if (wtpvalor in (11, 12, 13)) then
             begin
           BDBASEIRRFRRAES = BDBASEIRRFRRAES + wvalor;
               BDDEPRRAES = BDDEPRRAES + wvlrdep;
         end
           else if (wtpvalor in (31, 32, 34)) then
           BDVALORIRRFRRAES = BDVALORIRRFRRAES + wvalor;
           else if (wtpvalor in (41, 42)) then
           BDINSSRRAES = BDINSSRRAES + wvalor;
           else if (wtpvalor in (51, 52, 54)) then
           BDPENSAORRAES = BDPENSAORRAES + wvalor;
         end
   end

  BDCODEMP = :PRCODEMP;
  BDCODCOL = :PRCODCOL;
  suspend;
end^

create or alter procedure SP_VRH_VALORES_TOT_IRRF (
    PRCODEMP varchar(30000),
    PRREFARQ integer,
    PRTIPOEVT integer,
    PRVERSAO integer,
    PRCPF varchar(30000))
returns (
    BDCODIGO integer,
    BDREFARQ integer,
    BDCODEMP integer,
    BDCODTER integer,
    BDCODCOL integer,
    BDXML blob sub_type 0 segment size 80,
    BDVERSAO integer,
    BDXMLLOTE blob sub_type 0 segment size 80,
    BDIDLOTE varchar(100))
as
declare variable WSQL varchar(32000);
declare variable WSQLAUX varchar(500);
declare variable WCOUNT integer;
declare variable WCODEVT integer;
declare variable WREFARQ integer;
declare variable WCODEMP integer;
declare variable WCODTER integer;
declare variable WCODCOL integer;
declare variable WCODEVTORIG integer;
declare variable WCPF varchar(14);
declare variable WCOUNT2 integer;
declare variable WVER integer;
declare variable WLISTAEMP varchar(30000);
declare variable WCOUNT3 integer;
declare variable WSTATUS integer;
declare variable WDATARETORNO date;
declare variable WHORARETORNO time;
declare variable WDATARETORNOULTPROCESSADO date;
declare variable WHORAULTPROCESSADO time;
declare variable WLISTAMATRIZ varchar(30000);
declare variable WMATRIZ integer;
declare variable WAUXMATRIZ integer;
declare variable WCODCOLAUX integer;
declare variable WXMLLOTE blob sub_type 0 segment size 80;
declare variable WIDLOTE varchar(100);
begin

  if (position('=', PRCODEMP) > 0) then
     WLISTAEMP = SUBSTRING(PRCODEMP from position('=', PRCODEMP)+1 for CHAR_LENGTH(PRCODEMP));
  if (position('in', PRCODEMP) > 0) then
     WLISTAEMP = SUBSTRING(PRCODEMP from position('in', PRCODEMP)+2 for CHAR_LENGTH(PRCODEMP));

  if (position('(', WLISTAEMP) > 0) then
     WLISTAEMP = ' ((coalesce(E.BDCODMATRIZ, E.BDCODEMP) in ' || WLISTAEMP || ')) ';
  else
     WLISTAEMP = ' (coalesce(E.BDCODMATRIZ, E.BDCODEMP) in (' || WLISTAEMP || '))) ';

                                           --COLABORADORES
  wsql = ' select ARQ.BDCODIGO, ARQ.BDREFARQ, ARQ.BDCODEMP, ARQ.BDCODTER, ARQ.BDCODCOL,XML.BDXML, ARQ.BDCODEVENTOORIG, ARQ.BDSTATUS, ARQ.BDDATARETORNO, ARQ.BDHORARETORNO '||
         ' from VRH_ESOCIAL_TARQUIVO ARQ '||
         ' inner join VRH_ESOCIAL_TARQUIVO_XML XML on (ARQ.BDCODIGO = XML.BDCODIGO and ARQ.BDCODEMP = XML.BDCODEMP)' ||
         ' join VRH_EMP_TCOLCON C on C.BDCODEMP = ARQ.BDCODEMP and C.BDCODCOL = ARQ.BDCODCOL '||
         ' left outer join VRH_EMP_TCOLCON_DOC DOC on (DOC.BDCODEMP = ARQ.BDCODEMP and DOC.BDCODCOL = ARQ.BDCODCOL) '||
         ' where ARQ.BDCODEMP in (select E.BDCODEMP from TEMPRESAS E where '||WLISTAEMP||' '||
         ' and ARQ.BDSTATUS in (2,7) and ARQ.BDCODTIPO = '||prtipoevt||' and ARQ.BDREFARQ = '||prrefarq;

  if (prcpf <> '') then
     wsql = wsql||' and (doc.bdcpfcol '||prcpf||') ';

  wsql = wsql||' union '||
                                           --AUTONOMOS
         ' select ARQ.BDCODIGO, ARQ.BDREFARQ, ARQ.BDCODEMP, ARQ.BDCODTER, ARQ.BDCODCOL,XML.BDXML, ARQ.BDCODEVENTOORIG, ARQ.BDSTATUS, ARQ.BDDATARETORNO, ARQ.BDHORARETORNO '||
         ' from VRH_ESOCIAL_TARQUIVO ARQ '||
         ' inner join VRH_ESOCIAL_TARQUIVO_XML XML on (ARQ.BDCODIGO = XML.BDCODIGO and ARQ.BDCODEMP = XML.BDCODEMP)' ||
         ' left outer join TTERCEIRO TER on (TER.BDCODTER = ARQ.BDCODTER) '||
         ' where ARQ.BDCODTER > 0 and ARQ.BDCODEMP in (select E.BDCODEMP from TEMPRESAS E where '||WLISTAEMP||' '||
         ' and ARQ.BDSTATUS in (2,7) and ARQ.BDCODTIPO = '||prtipoevt||' and ARQ.BDREFARQ = '||prrefarq;

  if (prcpf <> '') then
     wsql = wsql||' and (ter.bdcgcter '||prcpf||') ';

  for execute statement wsql into :wcodevt, :wrefarq, :wcodemp, :wcodter, :wcodcol, :BDXML, :wcodevtorig, :wstatus, :wdataretorno, :whoraretorno do
    begin
       bdcodigo                  = null;
       bdrefarq                  = null;
       bdcodemp                  = null;
       bdcodter                  = null;
       bdcodcol                  = null;
       bdversao                  = null;
       wver                      = 0;
       wcodevtorig               = COALESCE(wcodevtorig, 0);
       wdataretornoultprocessado = null;
       whoraultprocessado        = null;
       BDXMLLOTE                 = null;
       BDIDLOTE                  = null;

       if ((COALESCE(wcodter, 0) = 0) and (COALESCE(wcodcol, 0) > 0)) then
         begin
           if (wstatus = 7) then
              begin
                select first 1 X.bddataretorno, X.bdhoraretorno from VRH_ESOCIAL_TARQUIVO X where X.BDCODEMP = :wcodemp and X.bdcodcol = :wcodcol and X.BDSTATUS = 2 and X.BDCODTIPO = 41 and X.BDREFARQ = :wrefarq
                order by X.bddataretorno desc, X.bdhoraretorno desc
                into :wdataretornoultprocessado, :whoraultprocessado;

                if (((wdataretornoultprocessado is null) and (whoraultprocessado is null)) or ((wdataretornoultprocessado < wdataretorno) or ((wdataretornoultprocessado = wdataretorno) and (whoraultprocessado < whoraretorno)))) then
                     delete from VRH_ESOCIAL_CONSOLIDAPURMEN_C where BDCODEMP = :wcodemp and BDCODCOL = :wcodcol and BDREFEVT = :wrefarq;

                continue;
              end

           wsqlaux = 'select first 1 1, BDVERSAO from VRH_ESOCIAL_CONSOLIDAPURMEN_C '||
                     'where BDCODEMP = '||wcodemp||' and '||
                           'BDCODCOL = '||wcodcol||' and '||
                           'BDREFEVT = '||wrefarq||' and '||
                           'BDCODEVT in ('||wcodevtorig||','||wcodevt||')';

           execute statement wsqlaux into :wcount, :wver;

           if (wver is null) then
              wver = 0;

           if ((wcount is null) or (prversao > wver)) then
              begin
                delete from VRH_ESOCIAL_CONSOLIDAPURMEN_C
                where BDCODEMP = :wcodemp and
                      BDCODCOL = :wcodcol and
                      BDREFEVT = :wrefarq;

                bdcodigo = wcodevt;
                bdrefarq = wrefarq;
                bdcodemp = wcodemp;
                bdcodcol = wcodcol;
                bdversao = wver + prversao;

                select FIRST 1 A.BDXML,arq.bdidevento
                from VRH_ESOCIAL_TLOTE_ARQUIVOS A
                join VRH_ESOCIAL_TARQUIVO ARQ on A.BDCODLOTE = ARQ.BDCODLOTE
                where ARQ.BDCODTIPO in (14) and ARQ.BDCODIGO = :wcodevtorig
                order by A.BDCODLOTE desc
                into :wxmllote, :widlote;

                bdxmllote = wxmllote;
                bdidlote = widlote;

                suspend;
              end
         end
       else if (wcodter > 0) then
         begin
           if (wstatus = 7) then
              begin
                select first 1 X.bddataretorno, X.bdhoraretorno from VRH_ESOCIAL_TARQUIVO X where X.BDCODEMP = :wcodemp and X.bdcodter = :wcodter and X.BDSTATUS = 2 and X.BDCODTIPO = 41 and X.BDREFARQ = :wrefarq
                order by X.bddataretorno desc, X.bdhoraretorno desc
                into :wdataretornoultprocessado, :whoraultprocessado;

                if (((wdataretornoultprocessado is null) and (whoraultprocessado is null)) or ((wdataretornoultprocessado < wdataretorno) or ((wdataretornoultprocessado = wdataretorno) and (whoraultprocessado < whoraretorno)))) then
                     delete from VRH_ESOCIAL_CONSOLIDAPURMEN_C_TERC where BDCODEMP = :wcodemp and BDCODTER = :wcodter and BDREFEVT = :wrefarq;

                continue;
              end

           -- Busca o CPF do autônomo
               select first 1 C.BDCGCTER from TTERCEIRO C where C.BDCODTER = :wcodter and char_length(C.BDCGCTER) = 14 into wcpf;

           if (wcpf is null) then
             begin
               select first 1 RH.BDCPFMEITER from TTERCEIRO_RH RH where RH.BDCODTER = :wcodter and char_length(RH.BDCPFMEITER) = 14 into wcpf;
             end

           if (wcount is null) then
             wcount = 0;

           if (wcount3 is null) then
             wcount3 = 0;

           -- Confirma se tem código de colaborador
           for select BDCODCOL from VRH_EMP_TCOLCON_DOC where bdcodemp = :wcodemp and bdcpfcol = :wcpf into :wcodcol do
             begin
               wsqlaux = ' select count(BDCODCOL) from VRH_ESOCIAL_CONSOLIDAPURMEN_C '||
                         ' where BDCODEMP = '||wcodemp||' and '||
                                'BDCODCOL = '||wcodcol||' and '||
                                'BDREFEVT = '||wrefarq||' and '||
                                'BDCODEVT in ('||wcodevtorig||','||wcodevt||')';
    
               for execute statement wsqlaux into :wcount3 do
                 begin
                   wcount = wcount + wcount3;
                 end
             end

           if (wcodcol is not null) then
              begin
                wlistamatriz = '';

                select coalesce(bdcodmatriz,bdcodemp) from tempresas where bdcodemp = :wcodemp into :wmatriz;

                for select bdcodemp from tempresas where bdcodemp = :wmatriz or bdcodmatriz = :wmatriz into :WAUXMATRIZ do
                  begin
                    if (wlistamatriz <> '') then
                       wlistamatriz = wlistamatriz||',';

                    wlistamatriz = wlistamatriz||WAUXMATRIZ;
                  end

                wcodcolaux = NULL;
                select bdcodcol from SP_ESOCIAL_TVINCULO_FOL_S1210(:wlistamatriz,:wcodemp,null,:wcodter,:wrefarq,:wcpf) into :WCODCOLAUX;

                if (WCODCOLAUX IS NOT null) then
                   wcodcol = wcodcolaux;
              end


           wsqlaux = 'select first 1 1, BDVERSAO from VRH_ESOCIAL_CONSOLIDAPURMEN_C_TERC '||
                     'where BDCODEMP = '||wcodemp||' and '||
                           'BDCODTER = '||wcodter||' and '||
                           'BDREFEVT = '||wrefarq||' and '||
                           'BDCODEVT in ('||wcodevtorig||','||wcodevt||')';

           execute statement wsqlaux into :wcount2, :wver;

           if (wcount2 is null) then
              wcount2 = 0;

           if (wver is null) then
              wver = 0;

           wcount = wcount + wcount2;

           if ((wcount = 0) or (prversao > wver)) then
              begin
                delete from VRH_ESOCIAL_CONSOLIDAPURMEN_C_TERC
                where BDCODEMP = :wcodemp and
                      BDCODTER = :wcodter and
                      BDREFEVT = :wrefarq;

                bdcodigo = wcodevt;
                bdrefarq = wrefarq;
                bdcodemp = wcodemp;
                bdcodter = wcodter;
                bdcodcol = wcodcol;
                bdversao = prversao + wver;

                select FIRST 1 A.BDXML,arq.bdidevento
                from VRH_ESOCIAL_TLOTE_ARQUIVOS A
                join VRH_ESOCIAL_TARQUIVO ARQ on A.BDCODLOTE = ARQ.BDCODLOTE
                where ARQ.BDCODTIPO in (14) and ARQ.BDCODIGO = :wcodevtorig
                order by A.BDCODLOTE desc
                into :wxmllote, :widlote;

                bdxmllote = wxmllote;
                bdidlote = widlote;

                suspend;
              end

         end

    end
end^

create or alter procedure SP_REL_TOT_5002_DIRF (
    PRCODEMP varchar(30000),
    PRREF integer,
    PRFILTROCPF varchar(30000),
    PRPRVEIODOTOTALIZADOR integer = 0,
    PRSEPARAFOLHAS integer = 0,
    PRRECTRAB integer = 0,
    PRGRAVACODIGORECEITA integer = 0,
    PRREFFIM integer = 0)
returns (
    BDCODEMPORD integer,
    BDREF integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCOLTER integer,
    BDCONTRCOL integer,
    BDGRUPOCLA integer,
    BDNOMCOL varchar(70),
    BDCPFCOL varchar(18),
    BDCNPJEMP varchar(18),
    BDNOMEMP varchar(100),
    BDBASEIRRF numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDVALORINSS numeric(18,6),
    BDTIPO integer,
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDCATEGORIAESOCIAL integer,
    BDCODCLATRI integer,
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOCALCULO integer,
    BDAJCUSTOS numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDUNICO integer,
    BDCODREC varchar(6),
    BDTRIBUTACAOEXTERIOR integer)
as
declare variable WFILTROCPFAUTONOMO varchar(30000);
begin
/* Procedure Text */
  if (prreffim = 0) then
     prreffim = prref;

  delete from VRHF_TEMP_EMP_TVAL5002 where bdsessao = current_connection;
  delete from VRHF_TEMP_EMP_TPLANSAU5002 where bdsessao = current_connection;
  delete from VRHF_TEMP_EMP_TPREVIDCOMPL5002 where bdsessao = current_connection;
  delete from VRHF_TEMP_EMP_TREEMBMED5002 where bdsessao = current_connection;
  delete from vrhf_temp_emp_trra5002 where bdsessao = current_connection;
  delete from vrhf_temp_emp_trra5002_adv where bdsessao = current_connection;
  delete from VRHF_TEMP_EMP_CONTROLE_REF_5002 where bdsessao = current_connection;
  delete from VRHF_TEMP_EMP_TRUBICA5002 where bdsessao = current_connection;
--  WFILTROCPFAUTONOMO = '';
--  if (prfiltrocpf <> '') then
  prfiltrocpf = REPLACE(prfiltrocpf, 'FOL.BDCPFCOL', 'COL.BDCPFCOL');
  WFILTROCPFAUTONOMO = REPLACE(prfiltrocpf, 'COL.BDCPFCOL', 'TER.BDCGCTER');

  for select BDREF, BDCODEMPORD, BDCODEMP, BDCODCOL, BDCOLTER, BDCONTRCOL, BDGRUPOCLA, BDNOMCOL, BDCPFCOL, BDCNPJEMP, BDNOMEMP, BDBASEIRRF, BDVALORIRRF, BDVALORINSS, BDTIPO, BDCALCULOS,
             BDCOUNTFC, BDCATEGORIAESOCIAL, BDCODCLATRI, BDTAGSTR, BDDESCRICAOFOLHA, BDTIPOCALCULO, BDAJCUSTOS, BDINDRESC, BDVALABO, BDRENDISENTOS, BDDRENDISENTOS, BDAUXILIOMORADIA, BDDIARIA,
             BDBOLSAMEDICO, BDJUROSMORA, BDUNICO, BDCODREC, BDTRIBUTACAOEXTERIOR
      from (select BDREF, BDCODEMPORD, BDCODEMP, BDCODCOL, BDCOLTER, BDCONTRCOL, BDGRUPOCLA, BDNOMCOL, BDCPFCOL, BDCNPJEMP, BDNOMEMP, BDBASEIRRF, BDVALORIRRF, BDVALORINSS, BDTIPO, BDCALCULOS,
            BDCOUNTFC, BDCATEGORIAESOCIAL, BDCODCLATRI, BDTAGSTR, BDDESCRICAOFOLHA, BDTIPOCALCULO, BDAJCUSTOS, BDINDRESC, BDVALABO, BDRENDISENTOS, BDDRENDISENTOS, BDAUXILIOMORADIA, BDDIARIA,
            BDBOLSAMEDICO, BDJUROSMORA, BDUNICO, BDCODREC, BDTRIBUTACAOEXTERIOR
            from SP_REL_TOT_5002_CONSOLID(:prcodemp, :prref, :prreffim, :prfiltrocpf, false, :prprveiodototalizador, :prseparafolhas,:prrectrab, :PRGRAVACODIGORECEITA)
            union
            select BDREF, BDCODEMPORD, BDCODEMP, BDCODCOL, BDCOLTER, BDCONTRCOL, BDGRUPOCLA, BDNOMCOL, BDCPFCOL, BDCNPJEMP, BDNOMEMP, BDBASEIRRF, BDVALORIRRF, BDVALORINSS, BDTIPO, BDCALCULOS,
            BDCOUNTFC, BDCATEGORIAESOCIAL, BDCODCLATRI, BDTAGSTR, BDDESCRICAOFOLHA, BDTIPOCALCULO, BDAJCUSTOS, BDINDRESC, BDVALABO, BDRENDISENTOS, BDDRENDISENTOS, BDAUXILIOMORADIA, BDDIARIA,
            BDBOLSAMEDICO, BDJUROSMORA, BDUNICO, BDCODREC, BDTRIBUTACAOEXTERIOR
            from SP_REL_TOT_5002_CONSOLID(:prcodemp, :prref, :prreffim, :wfiltrocpfautonomo, true, :prprveiodototalizador, :prseparafolhas,:prrectrab, :PRGRAVACODIGORECEITA)
            )
      order by BDCODEMPORD, BDCPFCOL, BDTIPOCALCULO, BDUNICO, BDCODCOL
      into :BDREF, :BDCODEMPORD, :BDCODEMP, :BDCODCOL, :BDCOLTER, :BDCONTRCOL, :BDGRUPOCLA, :BDNOMCOL, :BDCPFCOL, :BDCNPJEMP, :BDNOMEMP, :BDBASEIRRF, :BDVALORIRRF, :BDVALORINSS, :BDTIPO, :BDCALCULOS,
           :BDCOUNTFC, :BDCATEGORIAESOCIAL, :BDCODCLATRI, :BDTAGSTR, :BDDESCRICAOFOLHA, :BDTIPOCALCULO, :BDAJCUSTOS, :BDINDRESC, :BDVALABO, :BDRENDISENTOS, :BDDRENDISENTOS, :BDAUXILIOMORADIA, :BDDIARIA,
           :BDBOLSAMEDICO, :BDJUROSMORA, :BDUNICO, :BDCODREC, :BDTRIBUTACAOEXTERIOR
      do
      begin

        suspend;
      end
end^

create or alter procedure SP_RETORNA_BASE_IRRF_CONSOLID_13 (
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRREFFIM integer,
    PRTIPO integer,
    PRVEIODOTOTALIZADOR integer,
    PRSEPARAFOLHAS integer,
    PRGRAVACODIGORECEITA integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBASEIRRFMENSAL numeric(18,6),
    BDVALORIRRFMENSAL numeric(18,6),
    BDINSSMENSAL numeric(18,6),
    BDAJCUSTOSMENSAL numeric(18,6),
    BDINDRESCMENSAL numeric(18,6),
    BDVALABOMENSAL numeric(18,6),
    BDRENDISENTOSMENSAL numeric(18,6),
    BDDRENDISENTOSMENSAL varchar(999),
    BDAUXILIOMORADIAMENSAL numeric(18,6),
    BDDIARIAMENSAL numeric(18,6),
    BDBOLSAMEDICOMENSAL numeric(18,6),
    BDJUROSMORAMENSAL numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDINSS13 numeric(18,6),
    BDAJCUSTOS13 numeric(18,6),
    BDINDRESC13 numeric(18,6),
    BDVALABO13 numeric(18,6),
    BDRENDISENTOS13 numeric(18,6),
    BDDRENDISENTOS13 varchar(999),
    BDAUXILIOMORADIA13 numeric(18,6),
    BDDIARIA13 numeric(18,6),
    BDBOLSAMEDICO13 numeric(18,6),
    BDJUROSMORA13 numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDINSSPLR numeric(18,6),
    BDAJCUSTOSPLR numeric(18,6),
    BDINDRESCPLR numeric(18,6),
    BDVALABOPLR numeric(18,6),
    BDRENDISENTOSPLR numeric(18,6),
    BDDRENDISENTOSPLR varchar(999),
    BDAUXILIOMORADIAPLR numeric(18,6),
    BDDIARIAPLR numeric(18,6),
    BDBOLSAMEDICOPLR numeric(18,6),
    BDJUROSMORAPLR numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDINSSRRA numeric(18,6),
    BDAJCUSTOSRRA numeric(18,6),
    BDINDRESCRRA numeric(18,6),
    BDVALABORRA numeric(18,6),
    BDRENDISENTOSRRA numeric(18,6),
    BDDRENDISENTOSRRA varchar(999),
    BDAUXILIOMORADIARRA numeric(18,6),
    BDDIARIARRA numeric(18,6),
    BDBOLSAMEDICORRA numeric(18,6),
    BDJUROSMORARRA numeric(18,6),
    BDCALCULOS integer,
    BDTIPOCALCULO integer,
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOFOLHA integer,
    BDCODREC varchar(6))
as
declare variable WREFPLANSAUANT integer;
declare variable WREFREEMBMEDANT integer;
declare variable WREFPREVIDCOMPLANT integer;
declare variable WCODCLATRI integer;
declare variable WMATRIZ integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WINTERMITENTE integer;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WCODEMPATU integer;
declare variable WCODCOLATU integer;
declare variable WSUSPEND integer;
declare variable WORDEM integer;
declare variable WREF integer;
declare variable WREFREEMBOLSO integer;
declare variable WREFPLANOSAUDE integer;
declare variable WREFPREVPRIVADA integer;
declare variable WTIPOFOL integer;
declare variable WDIFERENCIADORDATE date;
declare variable WDIFERENCIADORINTEGER integer;
declare variable WREFPAG integer;
declare variable WBASEIRRF numeric(18,6);
declare variable WVALORIRRF numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WAJCUSTOS numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDISENTOS numeric(18,6);
declare variable WDRENDISENTOS varchar(999);
declare variable WAUXILIOMORADIA numeric(18,6);
declare variable WDIARIA numeric(18,6);
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WJUROSMORA numeric(18,6);
declare variable WCALCULOS integer;
declare variable WINCIDESOCIAL integer;
declare variable WCODFIR integer;
begin
  bdbaseirrfmensal = 0; bdvalorirrfmensal  = 0;
  bdinssmensal = 0; bdajcustosmensal = 0; bdindrescmensal = 0;
  bdvalabomensal = 0;bdrendisentosmensal = 0;bddrendisentosmensal = '';
  bdauxiliomoradiamensal = 0;bddiariamensal = 0;
  bdbolsamedicomensal = 0; bdjurosmoramensal = 0;
  bdcalculos = 0;
  bddescricaofolha = '';
  bdtagstr = '';
  bdcodrec = '';
  BDTIPOCALCULO = 2;
  WREFPLANSAUANT = 0;
  WREFREEMBMEDANT = 0;
  WREFPREVIDCOMPLANT = 0;

  if (prtipo = 1) then
   BEGIN
       wcodempatu = 0;
       wcodcolatu = 0;
       wrefirrfesocialatu = 0;
       if (prref = prreffim) then
          begin
            update TEMP_FILTRO_COLCON_REL set bdcpf = '' where coalesce(bdcpf,'') <> '';
          end

       for
          SELECT Q2.BDCODEMP, Q2.BDCODCOL, Q2.BDREFIRRFESOCIAL, Q2.BDINTERMITENTE, Q2.BDORDEM, Q2.bdref,
                 Q2.BDTIPO, Q2.BDDIFERENCIADORDATE, Q2.BDDIFERENCIADORINTEGER,
                 Q2.BDREFPAG, Q2.BDRENDTRIBUTAVEL, Q2.BDIR,
                 Q2.BDINSS, Q2.BDAJCUSTOS, Q2.BDINDRESC, Q2.BDVALABO, Q2.BDRENDISENTOS, Q2.BDDRENDISENTOS, Q2.BDAUXILIOMORADIA, Q2.BDDIARIA,
                 Q2.BDBOLSAMEDICO, Q2.BDJUROSMORA, Q2.BDCALCULOS, Q2.BDINCIDESOCIAL, Q2.BDCODFIR FROM (
            SELECT FT.BDREFIRRFESOCIAL, 0 BDINTERMITENTE, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, cast(null as date) BDDIFERENCIADORDATE, cast(null as integer) BDDIFERENCIADORINTEGER, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDCODFIR
            FROM SP_VRHF_DADOS_IR_13(:PRCODEMP, :PRCODCOL, :PRREF, :prreffim, 0, '', TRUE, FALSE, TRUE, :prveiodototalizador, 0) FT
            WHERE FT.BDTIPO NOT IN (111)
            UNION ALL
            SELECT FT.BDREFIRRFESOCIAL, 0 BDINTERMITENTE, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.bddatapgto BDDIFERENCIADORDATE, ft.bdrefpag BDDIFERENCIADORINTEGER, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                   FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, 0 BDCODFIR
            FROM SP_VRHF_DADOS_IR_13FC(:PRCODEMP, :PRCODCOL, :PRREF, :prreffim, 0, '', TRUE, 0, 0) FT
            UNION ALL
            SELECT FT.BDREFIRRFESOCIAL, 1 BDINTERMITENTE, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.bddatapgto BDDIFERENCIADORDATE, ft.BDCODCONTTI BDDIFERENCIADORINTEGER, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                   FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, 0 BDCODFIR
            FROM SP_VRHF_DADOS_IR_13FC_INT(:PRCODEMP, :PRCODCOL, :PRREF, :prreffim, 0, '', TRUE, 0) FT
            UNION ALL
            SELECT FT.BDREFIRRFESOCIAL, 0 BDINTERMITENTE, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, cast(null as date) BDDIFERENCIADORDATE, cast(null as integer) BDDIFERENCIADORINTEGER, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                   FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDCODFIR
            FROM SP_VRHF_DADOS_IR_C13(:PRCODEMP, :PRCODCOL, :PRREF, :prreffim, 0, '', TRUE, FALSE, 0, :prveiodototalizador) FT
            where exists(select first 1 BDCODCOL
                   from VRHF_EMP_T13SAL S13
                   where FT.BDCODEMP = S13.BDCODEMP and
                         FT.BDCODCOL = S13.BDCODCOL and
                         FT.BDREF = S13.BDREF13) or exists(select first 1 BDCODCOL
                                                           from VRHF_EMP_TFICHAIRRF S13
                                                           where FT.BDCODEMP = S13.BDCODEMP and
                                                                 FT.BDCODCOL = S13.BDCODCOL and
                                                                 FT.BDREF = S13.BDREFFIR)
            UNION ALL
            SELECT FT.BDREFIRRFESOCIAL, 1 BDINTERMITENTE, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, cast(null as date) BDDIFERENCIADORDATE, ft.BDCODCONTTI BDDIFERENCIADORINTEGER, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                   FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDCODFIR
            FROM SP_VRHF_DADOS_IR_INT13(:PRCODEMP, :PRCODCOL, :PRREF, :prreffim, 0, '', 0, TRUE, FALSE, :prveiodototalizador, 0) FT
            WHERE FT.BDTIPO NOT IN (111)
            UNION ALL
            SELECT FT.BDREFIRRFESOCIAL, 0 BDINTERMITENTE, 0 BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, cast(null as date) BDDIFERENCIADORDATE, cast(null as integer) BDDIFERENCIADORINTEGER, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                   FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, 0 BDCODFIR
            FROM SP_VRHF_DADOS_IR_AD13(:PRCODEMP, :PRCODCOL, :PRREF, :prreffim, 0, '') FT ) Q2
                ORDER BY Q2.BDREFIRRFESOCIAL, Q2.BDCODEMP, Q2.BDCODCOL, Q2.BDREF
        into :wcodemp, :wcodcol, :wRefIRRFESOCIAL, :wintermitente, :wordem, :wref, :wtipofol, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, :WREFPAG,
             :WBASEIRRF, :WVALORIRRF, :WINSS, :WAJCUSTOS, :WINDRESC, :WVALABO, :WRENDISENTOS, :WDRENDISENTOS, :WAUXILIOMORADIA, :WDIARIA,
             :WBOLSAMEDICO, :WJUROSMORA, :WCALCULOS, :WINCIDESOCIAL, :WCODFIR do
       begin
         if (prref = prreffim) then
            update TEMP_FILTRO_COLCON_REL set bdcpf = '1' where coalesce(bdcpf,'') = '' and bdcodemp = :wcodemp and bdcodcol = :wcodcol;

         WSUSPEND = 0;
         if (COALESCE(WTIPOFOL, 0) >= 9000) then
            WDIFERENCIADORINTEGER = WCODFIR;

         if ((wcodempatu <> wcodemp) or (wrefirrfesocialatu <> wrefirrfesocial))  then
            begin
              if (prseparafolhas = 1) then
                 begin
                   select first 1 BDCODCLATRI from VRHF_BASE_TEMPESOCIAL ES
                   where ES.BDCODEMP in (:WCODEMP) and(ES.BDREFEMP <= :wrefirrfesocial) and BDCODCLATRI is not null
                   order by BDREFEMP desc  into :WCODCLATRI;

                   if (:WCODCLATRI is null) then /*Se não encontrar pega o proximo para a competencia seguinte.*/
                     begin
                       select first 1 BDCODCLATRI from VRHF_BASE_TEMPESOCIAL ES
                       where ES.BDCODEMP in (:WCODEMP) and (ES.BDREFEMP >= :wrefirrfesocial) and BDCODCLATRI is not null
                       order by BDREFEMP into :WCODCLATRI;
                     end

                   if (:WCODCLATRI is null) then /*Caso ainda seja null, deve considerar como 99 pois significa que no cadastro não tem nenhuma classificação em nenhuma referência*/
                     begin
                       :WCODCLATRI = 99;
                     end
                 end

               select first 1 coalesce(bdcodmatriz,bdcodemp) from tempresas where bdcodemp = :wcodemp into :wMatriz;
            end

         if (wcodempatu = 0) then wcodempatu = wcodemp;
         if (wcodcolatu = 0) then wcodcolatu = wcodcol;
         if (wrefirrfesocialatu = 0) then wrefirrfesocialatu = wrefirrfesocial;

         if ((wcodempatu <> wcodemp) or (wcodcolatu <> wcodcol) or (wrefirrfesocialatu <> wrefirrfesocial)) then
            begin
              WREFPLANSAUANT = 0;
              WREFREEMBMEDANT = 0;
              WREFPREVIDCOMPLANT = 0;
            end

         if ((prseparafolhas <> 1) and ((wcodempatu <> wcodemp) or (wcodcolatu <> wcodcol) or (wrefirrfesocialatu <> wrefirrfesocial))) then
            begin
              WSUSPEND = 1;
            end

         if (WSUSPEND = 1) then
            begin
              suspend;
              bddescricaofolha = '';
              bdcodrec = '';

              -- Zera valores que seram somados
              bdbaseirrfmensal = 0; bdvalorirrfmensal  = 0;
              bdinssmensal = 0; bdajcustosmensal = 0; bdindrescmensal = 0;
              bdvalabomensal = 0;bdrendisentosmensal = 0;bddrendisentosmensal = '';
              bdauxiliomoradiamensal = 0;bddiariamensal = 0;
              bdbolsamedicomensal = 0; bdjurosmoramensal = 0;
              bdcalculos = 0;
            end

         wcodempatu = wcodemp;
         wcodcolatu = wcodcol;
         wrefirrfesocialatu = wrefirrfesocial;

         bdcodemp = wcodemp;
         bdcodcol = wcodcol;
         bdref = wrefirrfesocial;


         bdbaseirrfmensal = bdbaseirrfmensal + coalesce(WBASEIRRF,0);
         bdvalorirrfmensal =  bdvalorirrfmensal + coalesce(WVALORIRRF,0);
         bdinssmensal = bdinssmensal + coalesce(WINSS,0);
         bdajcustosmensal = bdajcustosmensal + coalesce(WAJCUSTOS,0);
         bdindrescmensal = bdindrescmensal + coalesce(WINDRESC,0);
         bdvalabomensal = bdvalabomensal + coalesce(WVALABO,0);
         bdrendisentosmensal = bdrendisentosmensal + coalesce(WRENDISENTOS,0);
          if (WDRENDISENTOS <> '') then
             begin
               if (BDDRENDISENTOSMENSAL <> '') then
                  begin
                    if (prveiodototalizador = 1) then
                       BDDRENDISENTOSMENSAL = substring(BDDRENDISENTOSMENSAL||';' from 1 for 999);
                    else
                       BDDRENDISENTOSMENSAL = substring(BDDRENDISENTOSMENSAL||', ' from 1 for 999);
                  end
               BDDRENDISENTOSMENSAL = substring(BDDRENDISENTOSMENSAL||WDRENDISENTOS from 1 for 999);
               if (prveiodototalizador = 1) then
                  BDDRENDISENTOSMENSAL = REPLACE(BDDRENDISENTOSMENSAL, ', ', ';');
             end
         bdauxiliomoradiamensal = bdauxiliomoradiamensal + coalesce(WAUXILIOMORADIA,0);
         bddiariamensal = bddiariamensal + coalesce(WDIARIA,0);
         bdbolsamedicomensal = bdbolsamedicomensal + coalesce(WBOLSAMEDICO,0);
         bdjurosmoramensal = bdjurosmoramensal + coalesce(WJUROSMORA,0);
         bdcalculos = bdcalculos + coalesce(WCALCULOS,0);

         if (prseparafolhas = 1) then
            begin
              if ((PRGRAVACODIGORECEITA = 0) and (bdcodrec = '')) then
                 select BDCODREC FROM sp_vrh_getcodreceita_5002(:WCODEMP,:WCODCOL,:wrefirrfesocialatu,:PRTIPO,:WTIPOFOL,2,:wCODCLATRI) INTO :bdcodrec;

              select BDDESCRICAOCALCULO,BDTAGSTR from SP_RETORNA_TAGSTR_TOTALIZADORES(:WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, 1, :WINTERMITENTE, :WORDEM)
              into :bddescricaofolha,:bdtagstr;
            end

         /* dependente pensão */
         execute procedure sp_vrhf_add_val_dep_pen_5002(:wcodemp,:wcodcol,null,:wref,wdiferenciadordate,wdiferenciadorinteger,2,wtipofol,wcodemp,:bdtagstr,:bddescricaofolha, WINCIDESOCIAL, 1, 2, 0, null, wrefpag, 0, :wMatriz, 0, :WREFIRRFESOCIAL,:bdcodrec);

         execute procedure SP_REL_TOT_5002_RUBRICAS(:wcodemp,:wcodcol,:wref,:wMatriz,:wREFIRRFESOCIAL,0);

         /* Busca valores plano saude, reembolso, previdencia */
         if (wtipofol in (0, 4, 100, 101, 9000, 9001, 9002)) then -- Folha normal, férias folha normal
            begin
              if (wref <> WREFPLANSAUANT) then
                 begin
                   EXECUTE PROCEDURE SP_REL_TOT_5002_PLANSAU(:WCODEMP, :WCODCOL, :WREF, 1, :BDTAGSTR, :BDDESCRICAOFOLHA, :wMatriz, :wREFIRRFESOCIAL);
                   WREFPLANSAUANT = wref;
                 end
              if (wref <> WREFREEMBMEDANT) then
                 begin
                   EXECUTE PROCEDURE SP_REL_TOT_5002_REEMBMED(:WCODEMP, :WCODCOL, :WREF, 1, :BDTAGSTR, :BDDESCRICAOFOLHA, :wMatriz, :wREFIRRFESOCIAL);
                   WREFREEMBMEDANT = wref;
                 end
              if (wref <> WREFPREVIDCOMPLANT) then
                 begin
                   EXECUTE PROCEDURE SP_REL_TOT_5002_PREVIDCOMPL(:WCODEMP, :WCODCOL, :WREF, :BDTAGSTR, :BDDESCRICAOFOLHA, 1, 2, :wMatriz, :wREFIRRFESOCIAL,:bdcodrec);
                   WREFPREVIDCOMPLANT = wref;
                 end
            end
         else if ((wref <> WREFPREVIDCOMPLANT) and (wtipofol in (10, 9100))) then  -- Folha 13º
            begin
              EXECUTE PROCEDURE SP_REL_TOT_5002_PREVIDCOMPL(:WCODEMP, :WCODCOL, :WREF, :BDTAGSTR, :BDDESCRICAOFOLHA, 1, 2, :wMatriz, :wREFIRRFESOCIAL,:bdcodrec);
              WREFPREVIDCOMPLANT = wref;
            end

         /* realiza o suspendo quando é separado por folha com ecessão de ACD que o sustend é agrupado*/
         if (prseparafolhas = 1) then
            begin
              suspend;
              bddescricaofolha = '';
              bdcodrec = '';
              wsuspend = 0;
              bdbaseirrfmensal = 0; bdvalorirrfmensal  = 0;
              bdinssmensal = 0; bdajcustosmensal = 0; bdindrescmensal = 0;
              bdvalabomensal = 0;bdrendisentosmensal = 0;bddrendisentosmensal = '';
              bdauxiliomoradiamensal = 0;bddiariamensal = 0;
              bdbolsamedicomensal = 0; bdjurosmoramensal = 0;
              bdcalculos = 0;
            end
         else
            begin
              /* Se sair do laço por ser o ultimo registro processa dar suspend*/
              WSUSPEND = 1;
            end
       end

     if (WSUSPEND = 1) then
        suspend;

     if (prref = prreffim) then
        begin
          bddescricaofolha = '';
          bdtagstr = '';
          bdcodrec = '';
          wsuspend = 0;
          bdbaseirrfmensal = 0; bdvalorirrfmensal  = 0;
          bdinssmensal = 0; bdajcustosmensal = 0; bdindrescmensal = 0;
          bdvalabomensal = 0;bdrendisentosmensal = 0;bddrendisentosmensal = '';
          bdauxiliomoradiamensal = 0;bddiariamensal = 0;
          bdbolsamedicomensal = 0; bdjurosmoramensal = 0;
          bdcalculos = 0;
          bdref = prref;
          for select bdcodemp,bdcodcol from TEMP_FILTRO_COLCON_REL where coalesce(bdcpf,'') = '' into bdcodemp,bdcodcol do
            begin
              suspend;
            end
        end
   END

end
^

create or alter procedure SP_RETORNA_BASE_IRRF_CONSOLID_PLR (
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRREFFIM integer,
    PRTIPO integer,
    PRVEIODOTOTALIZADOR integer,
    PRSEPARAFOLHAS integer,
    PRGRAVACODIGORECEITA integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBASEIRRFMENSAL numeric(18,6),
    BDVALORIRRFMENSAL numeric(18,6),
    BDINSSMENSAL numeric(18,6),
    BDAJCUSTOSMENSAL numeric(18,6),
    BDINDRESCMENSAL numeric(18,6),
    BDVALABOMENSAL numeric(18,6),
    BDRENDISENTOSMENSAL numeric(18,6),
    BDDRENDISENTOSMENSAL varchar(999),
    BDAUXILIOMORADIAMENSAL numeric(18,6),
    BDDIARIAMENSAL numeric(18,6),
    BDBOLSAMEDICOMENSAL numeric(18,6),
    BDJUROSMORAMENSAL numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDINSS13 numeric(18,6),
    BDAJCUSTOS13 numeric(18,6),
    BDINDRESC13 numeric(18,6),
    BDVALABO13 numeric(18,6),
    BDRENDISENTOS13 numeric(18,6),
    BDDRENDISENTOS13 varchar(999),
    BDAUXILIOMORADIA13 numeric(18,6),
    BDDIARIA13 numeric(18,6),
    BDBOLSAMEDICO13 numeric(18,6),
    BDJUROSMORA13 numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDINSSPLR numeric(18,6),
    BDAJCUSTOSPLR numeric(18,6),
    BDINDRESCPLR numeric(18,6),
    BDVALABOPLR numeric(18,6),
    BDRENDISENTOSPLR numeric(18,6),
    BDDRENDISENTOSPLR varchar(999),
    BDAUXILIOMORADIAPLR numeric(18,6),
    BDDIARIAPLR numeric(18,6),
    BDBOLSAMEDICOPLR numeric(18,6),
    BDJUROSMORAPLR numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDINSSRRA numeric(18,6),
    BDAJCUSTOSRRA numeric(18,6),
    BDINDRESCRRA numeric(18,6),
    BDVALABORRA numeric(18,6),
    BDRENDISENTOSRRA numeric(18,6),
    BDDRENDISENTOSRRA varchar(999),
    BDAUXILIOMORADIARRA numeric(18,6),
    BDDIARIARRA numeric(18,6),
    BDBOLSAMEDICORRA numeric(18,6),
    BDJUROSMORARRA numeric(18,6),
    BDCALCULOS integer,
    BDTIPOCALCULO integer,
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOFOLHA integer,
    BDCODREC varchar(6))
as
declare variable WREFPLANSAUANT integer;
declare variable WREFREEMBMEDANT integer;
declare variable WREFPREVIDCOMPLANT integer;
declare variable WCODCLATRI integer;
declare variable WMATRIZ integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WCODEMPATU integer;
declare variable WCODCOLATU integer;
declare variable WSUSPEND integer;
declare variable WORDEM integer;
declare variable WREF integer;
declare variable WREFREEMBOLSO integer;
declare variable WREFPLANOSAUDE integer;
declare variable WREFPREVPRIVADA integer;
declare variable WTIPOFOL integer;
declare variable WDIFERENCIADORDATE date;
declare variable WDIFERENCIADORINTEGER integer;
declare variable WREFFC integer;
declare variable WREFPAG integer;
declare variable WBASEIRRF numeric(18,6);
declare variable WVALORIRRF numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WAJCUSTOS numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDISENTOS numeric(18,6);
declare variable WDRENDISENTOS varchar(999);
declare variable WAUXILIOMORADIA numeric(18,6);
declare variable WDIARIA numeric(18,6);
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WJUROSMORA numeric(18,6);
declare variable WCALCULOS integer;
declare variable WINCIDESOCIAL integer;
declare variable WINCIDESOCIALFER integer;
declare variable WCODFIR integer;
begin
  bdbaseirrfmensal = 0; bdvalorirrfmensal  = 0;
  bdinssmensal = 0; bdajcustosmensal = 0; bdindrescmensal = 0;
  bdvalabomensal = 0;bdrendisentosmensal = 0;bddrendisentosmensal = '';
  bdauxiliomoradiamensal = 0;bddiariamensal = 0;
  bdbolsamedicomensal = 0; bdjurosmoramensal = 0;
  bdcalculos = 0;
  bddescricaofolha = '';
  bdtagstr = '';
  bdcodrec = '';
  BDTIPOCALCULO = 3;
  WREFPLANSAUANT = 0;
  WREFREEMBMEDANT = 0;
  WREFPREVIDCOMPLANT = 0;

  if (prtipo = 1) then
   BEGIN
       wcodempatu = 0;
       wcodcolatu = 0;
       wrefirrfesocialatu = 0;
       if (prref = prreffim) then
          begin
            update TEMP_FILTRO_COLCON_REL set bdcpf = '' where coalesce(bdcpf,'') <> '';
          end

       for
          SELECT Q2.BDCODEMP, Q2.BDCODCOL, Q2.BDREFIRRFESOCIAL, Q2.BDORDEM, Q2.bdref,
                 Q2.BDTIPO, Q2.BDDATAPGTO, Q2.BDCODTCA, Q2.BDREFPAG, Q2.BDRENDTRIBUTAVEL, Q2.BDIR,
                 Q2.BDINSS, Q2.BDAJCUSTOS, Q2.BDINDRESC, Q2.BDVALABO, Q2.BDRENDISENTOS, Q2.BDDRENDISENTOS, Q2.BDAUXILIOMORADIA, Q2.BDDIARIA,
                 Q2.BDBOLSAMEDICO, Q2.BDJUROSMORA, Q2.BDCALCULOS, Q2.BDINCIDESOCIAL, Q2.BDCODFIR
          FROM (
              SELECT FT.BDREFIRRFESOCIAL, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.BDDATAPGTO, ft.BDCODTCA, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, IIF(FT.BDINSS > 0,FT.BDINSS,0) as BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                     FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDCODFIR
              FROM SP_VRHF_DADOS_IR_FA(:PRCODEMP, :PRCODCOL, :PRREF, :prreffim, 0, '', 1, 0, TRUE, FALSE, :prveiodototalizador) FT ) Q2
              ORDER BY Q2.BDREFIRRFESOCIAL, Q2.BDCODEMP, Q2.BDCODCOL, Q2.BDREF
        into :wcodemp, :wcodcol, :wRefIRRFESOCIAL, :wordem, :wref, :wtipofol, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, :WREFPAG,
             :WBASEIRRF, :WVALORIRRF, :WINSS, :WAJCUSTOS, :WINDRESC, :WVALABO, :WRENDISENTOS, :WDRENDISENTOS, :WAUXILIOMORADIA, :WDIARIA,
             :WBOLSAMEDICO, :WJUROSMORA, :WCALCULOS, :WINCIDESOCIAL, :WCODFIR do
       begin
         if (prref = prreffim) then
            update TEMP_FILTRO_COLCON_REL set bdcpf = '1' where coalesce(bdcpf,'') = '' and bdcodemp = :wcodemp and bdcodcol = :wcodcol;

         WSUSPEND = 0;
         if (COALESCE(WTIPOFOL, 0) >= 9000) then
            WDIFERENCIADORINTEGER = WCODFIR;

         if ((wcodempatu <> wcodemp) or (wrefirrfesocialatu <> wrefirrfesocial))  then
            begin
              if (prseparafolhas = 1) then
                 begin
                   select first 1 BDCODCLATRI from VRHF_BASE_TEMPESOCIAL ES
                   where ES.BDCODEMP in (:WCODEMP) and(ES.BDREFEMP <= :wrefirrfesocial) and BDCODCLATRI is not null
                   order by BDREFEMP desc  into :WCODCLATRI;

                   if (:WCODCLATRI is null) then /*Se não encontrar pega o proximo para a competencia seguinte.*/
                     begin
                       select first 1 BDCODCLATRI from VRHF_BASE_TEMPESOCIAL ES
                       where ES.BDCODEMP in (:WCODEMP) and (ES.BDREFEMP >= :wrefirrfesocial) and BDCODCLATRI is not null
                       order by BDREFEMP into :WCODCLATRI;
                     end

                   if (:WCODCLATRI is null) then /*Caso ainda seja null, deve considerar como 99 pois significa que no cadastro não tem nenhuma classificação em nenhuma referência*/
                     begin
                       :WCODCLATRI = 99;
                     end
                 end

               select first 1 coalesce(bdcodmatriz,bdcodemp) from tempresas where bdcodemp = :wcodemp into :wMatriz;
            end

         if (wcodempatu = 0) then wcodempatu = wcodemp;
         if (wcodcolatu = 0) then wcodcolatu = wcodcol;
         if (wrefirrfesocialatu = 0) then wrefirrfesocialatu = wrefirrfesocial;

         if ((wcodempatu <> wcodemp) or (wcodcolatu <> wcodcol) or (wrefirrfesocialatu <> wrefirrfesocial)) then
            begin
              WREFPLANSAUANT = 0;
              WREFREEMBMEDANT = 0;
              WREFPREVIDCOMPLANT = 0;
            end

         if ((prseparafolhas <> 1) and ((wcodempatu <> wcodemp) or (wcodcolatu <> wcodcol) or (wrefirrfesocialatu <> wrefirrfesocial)))  then
            begin
              WSUSPEND = 1;
            end

         if (WSUSPEND = 1) then
            begin
              suspend;
              bddescricaofolha = '';
              bdcodrec = '';

              -- Zera valores que seram somados
              bdbaseirrfmensal = 0; bdvalorirrfmensal  = 0;
              bdinssmensal = 0; bdajcustosmensal = 0; bdindrescmensal = 0;
              bdvalabomensal = 0;bdrendisentosmensal = 0;bddrendisentosmensal = '';
              bdauxiliomoradiamensal = 0;bddiariamensal = 0;
              bdbolsamedicomensal = 0; bdjurosmoramensal = 0;
              bdcalculos = 0;
            end

         wcodempatu = wcodemp;
         wcodcolatu = wcodcol;
         wrefirrfesocialatu = wrefirrfesocial;

         bdcodemp = wcodemp;
         bdcodcol = wcodcol;
         bdref = wrefirrfesocial;


         bdbaseirrfmensal = bdbaseirrfmensal + coalesce(WBASEIRRF,0);
         bdvalorirrfmensal =  bdvalorirrfmensal + coalesce(WVALORIRRF,0);
         bdinssmensal = bdinssmensal + coalesce(WINSS,0);
         bdajcustosmensal = bdajcustosmensal + coalesce(WAJCUSTOS,0);
         bdindrescmensal = bdindrescmensal + coalesce(WINDRESC,0);
         bdvalabomensal = bdvalabomensal + coalesce(WVALABO,0);
         bdrendisentosmensal = bdrendisentosmensal + coalesce(WRENDISENTOS,0);
          if (WDRENDISENTOS <> '') then
             begin
               if (BDDRENDISENTOSMENSAL <> '') then
                  begin
                    if (prveiodototalizador = 1) then
                       BDDRENDISENTOSMENSAL = substring(BDDRENDISENTOSMENSAL||';' from 1 for 999);
                    else
                       BDDRENDISENTOSMENSAL = substring(BDDRENDISENTOSMENSAL||', ' from 1 for 999);
                  end
               BDDRENDISENTOSMENSAL = substring(BDDRENDISENTOSMENSAL||WDRENDISENTOS from 1 for 999);
               if (prveiodototalizador = 1) then
                  BDDRENDISENTOSMENSAL = REPLACE(BDDRENDISENTOSMENSAL, ', ', ';');
             end
         bdauxiliomoradiamensal = bdauxiliomoradiamensal + coalesce(WAUXILIOMORADIA,0);
         bddiariamensal = bddiariamensal + coalesce(WDIARIA,0);
         bdbolsamedicomensal = bdbolsamedicomensal + coalesce(WBOLSAMEDICO,0);
         bdjurosmoramensal = bdjurosmoramensal + coalesce(WJUROSMORA,0);
         bdcalculos = bdcalculos + coalesce(WCALCULOS,0);

         if (prseparafolhas = 1) then
            begin
              if ((PRGRAVACODIGORECEITA = 0) and (bdcodrec = '')) then
                 select BDCODREC FROM sp_vrh_getcodreceita_5002(:WCODEMP,:WCODCOL,:wrefirrfesocialatu,:PRTIPO,:WTIPOFOL,:bdtipocalculo,:WCODCLATRI) INTO :bdcodrec;

              select BDDESCRICAOCALCULO,BDTAGSTR from SP_RETORNA_TAGSTR_TOTALIZADORES(:WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, 1, 0, :WORDEM)
              into :bddescricaofolha,:bdtagstr;
            end

         /* dependente pensão */
         execute procedure sp_vrhf_add_val_dep_pen_5002(:wcodemp,:wcodcol,null,:wref,wdiferenciadordate,wdiferenciadorinteger,3,wtipofol,wcodemp,:bdtagstr,:bddescricaofolha, WINCIDESOCIAL, 1, 3, 0, null, wrefpag, 0, :wMatriz, 0, :wREFIRRFESOCIAL,:bdcodrec);

         execute procedure SP_REL_TOT_5002_RUBRICAS(:wcodemp,:wcodcol,:wref,:wMatriz,:wREFIRRFESOCIAL,0);

         /* realiza o suspendo quando é separado por folha com ecessão de ACD que o sustend é agrupado*/
         if (prseparafolhas = 1) then
            begin
              suspend;
              bddescricaofolha = '';
              bdcodrec = '';
              wsuspend = 0;
              bdbaseirrfmensal = 0; bdvalorirrfmensal  = 0;
              bdinssmensal = 0; bdajcustosmensal = 0; bdindrescmensal = 0;
              bdvalabomensal = 0;bdrendisentosmensal = 0;bddrendisentosmensal = '';
              bdauxiliomoradiamensal = 0;bddiariamensal = 0;
              bdbolsamedicomensal = 0; bdjurosmoramensal = 0;
              bdcalculos = 0;
            end
         else
            begin
              /* Se sair do laço por ser o ultimo registro processa dar suspend*/
              WSUSPEND = 1;
            end
       end

     if (WSUSPEND = 1) then
        suspend;

     if (prref = prreffim) then
        begin
          bddescricaofolha = '';
          bdtagstr = '';
          bdcodrec = '';
          wsuspend = 0;
          bdbaseirrfmensal = 0; bdvalorirrfmensal  = 0;
          bdinssmensal = 0; bdajcustosmensal = 0; bdindrescmensal = 0;
          bdvalabomensal = 0;bdrendisentosmensal = 0;bddrendisentosmensal = '';
          bdauxiliomoradiamensal = 0;bddiariamensal = 0;
          bdbolsamedicomensal = 0; bdjurosmoramensal = 0;
          bdcalculos = 0;
          bdref = prref;
          for select bdcodemp,bdcodcol from TEMP_FILTRO_COLCON_REL where coalesce(bdcpf,'') = '' into bdcodemp,bdcodcol do
            begin
              suspend;
            end
        end

   END
end
^

create or alter procedure SP_RETORNA_BASE_IRRF_CONSOLID_RRA (
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRREFFIM integer,
    PRTIPO integer,
    PRVEIODOTOTALIZADOR integer,
    PRSEPARAFOLHAS integer,
    PRGRAVACODIGORECEITA integer = 0,
    PRSEPARAISENTOS integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBASEIRRFMENSAL numeric(18,6),
    BDVALORIRRFMENSAL numeric(18,6),
    BDINSSMENSAL numeric(18,6),
    BDAJCUSTOSMENSAL numeric(18,6),
    BDINDRESCMENSAL numeric(18,6),
    BDVALABOMENSAL numeric(18,6),
    BDRENDISENTOSMENSAL numeric(18,6),
    BDDRENDISENTOSMENSAL varchar(999),
    BDAUXILIOMORADIAMENSAL numeric(18,6),
    BDDIARIAMENSAL numeric(18,6),
    BDBOLSAMEDICOMENSAL numeric(18,6),
    BDJUROSMORAMENSAL numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDINSS13 numeric(18,6),
    BDAJCUSTOS13 numeric(18,6),
    BDINDRESC13 numeric(18,6),
    BDVALABO13 numeric(18,6),
    BDRENDISENTOS13 numeric(18,6),
    BDDRENDISENTOS13 varchar(999),
    BDAUXILIOMORADIA13 numeric(18,6),
    BDDIARIA13 numeric(18,6),
    BDBOLSAMEDICO13 numeric(18,6),
    BDJUROSMORA13 numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDINSSPLR numeric(18,6),
    BDAJCUSTOSPLR numeric(18,6),
    BDINDRESCPLR numeric(18,6),
    BDVALABOPLR numeric(18,6),
    BDRENDISENTOSPLR numeric(18,6),
    BDDRENDISENTOSPLR varchar(999),
    BDAUXILIOMORADIAPLR numeric(18,6),
    BDDIARIAPLR numeric(18,6),
    BDBOLSAMEDICOPLR numeric(18,6),
    BDJUROSMORAPLR numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDINSSRRA numeric(18,6),
    BDAJCUSTOSRRA numeric(18,6),
    BDINDRESCRRA numeric(18,6),
    BDVALABORRA numeric(18,6),
    BDRENDISENTOSRRA numeric(18,6),
    BDDRENDISENTOSRRA varchar(999),
    BDAUXILIOMORADIARRA numeric(18,6),
    BDDIARIARRA numeric(18,6),
    BDBOLSAMEDICORRA numeric(18,6),
    BDJUROSMORARRA numeric(18,6),
    BDCALCULOS integer,
    BDTIPOCALCULO integer,
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOFOLHA integer,
    BDCODREC varchar(6))
as
declare variable WREFPLANSAUANT integer;
declare variable WREFREEMBMEDANT integer;
declare variable WREFPREVIDCOMPLANT integer;
declare variable WCODCLATRI integer;
declare variable WMATRIZ integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WINTERMITENTE integer;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WCODEMPATU integer;
declare variable WCODCOLATU integer;
declare variable WSUSPEND integer;
declare variable WFC integer;
declare variable WORDEM integer;
declare variable WREF integer;
declare variable WREFREEMBOLSO integer;
declare variable WREFPLANOSAUDE integer;
declare variable WREFPREVPRIVADA integer;
declare variable WTIPOFOL integer;
declare variable WDIFERENCIADORDATE date;
declare variable WDIFERENCIADORINTEGER integer;
declare variable WREFFC integer;
declare variable WREFPAG integer;
declare variable WDATAPGTO date;
declare variable WBASEIRRF numeric(18,6);
declare variable WVALORIRRF numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WAJCUSTOS numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDISENTOS numeric(18,6);
declare variable WDRENDISENTOS varchar(999);
declare variable WAUXILIOMORADIA numeric(18,6);
declare variable WDIARIA numeric(18,6);
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WJUROSMORA numeric(18,6);
declare variable WCALCULOS integer;
declare variable WINCIDESOCIAL integer;
declare variable WINCIDESOCIALFER integer;
declare variable WCODACCONV integer;
declare variable WCODACCONVATU integer;
declare variable WCODFIR integer;
declare variable WQTDMESESRRA numeric(18,6);
begin
  bdbaseirrfmensal = 0; bdvalorirrfmensal  = 0;
  bdinssmensal = 0; bdajcustosmensal = 0; bdindrescmensal = 0;
  bdvalabomensal = 0;bdrendisentosmensal = 0;bddrendisentosmensal = '';
  bdauxiliomoradiamensal = 0;bddiariamensal = 0;
  bdbolsamedicomensal = 0; bdjurosmoramensal = 0;
  bdcalculos = 0; WCODACCONVatu = -1;
  bddescricaofolha = '';
  bdtagstr = '';
  bdcodrec = '';
  BDTIPOCALCULO = 4;
  WQTDMESESRRA = 0;
  WREFPLANSAUANT = 0;
  WREFREEMBMEDANT = 0;
  WREFPREVIDCOMPLANT = 0;

  if (prtipo = 1) then
   BEGIN
       wcodempatu = 0;
       wcodcolatu = 0;
       wrefirrfesocialatu = 0;
       if ((prref = prreffim) and (PRSEPARAISENTOS <> 1)) then
          begin
            update TEMP_FILTRO_COLCON_REL set bdcpf = '' where coalesce(bdcpf,'') <> '';
          end

       for
          SELECT Q2.BDCODEMP, Q2.BDCODCOL, Q2.BDREFIRRFESOCIAL, Q2.BDORDEM, Q2.bdref,
                 Q2.BDTIPO, Q2.BDDIFERENCIADORDATE, Q2.BDDIFERENCIADORINTEGER, Q2.BDREFFC,
                 Q2.BDDATAPGTO, Q2.BDREFPAG, Q2.BDRENDTRIBUTAVEL, Q2.BDIR,
                 Q2.BDINSS, Q2.BDAJCUSTOS, Q2.BDINDRESC, Q2.BDVALABO, Q2.BDRENDISENTOS, Q2.BDDRENDISENTOS, Q2.BDAUXILIOMORADIA, Q2.BDDIARIA,
                 Q2.BDBOLSAMEDICO, Q2.BDJUROSMORA, Q2.BDCALCULOS, Q2.BDINCIDESOCIAL, Q2.BDCODACCONV, Q2.BDCODFIR, Q2.BDMESESRRA
          FROM (SELECT FT.BDREFIRRFESOCIAL, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.bddatapgto BDDIFERENCIADORDATE, ft.bdrefpag BDDIFERENCIADORINTEGER, ft.bdreffc, ft.bddatapgto, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, 0 BDINCIDESOCIAL, FT.BDCODACCONV, FT.BDCODFIR, FT.BDMESESRRA
              FROM SP_VRHF_DADOS_IR_FC_RRA(:PRCODEMP, :PRCODCOL, :PRREF, :prreffim, 0, '', 0, 0, 0, TRUE, FALSE, 1, FALSE, :prveiodototalizador) FT
               ) Q2
                ORDER BY Q2.BDREFIRRFESOCIAL, Q2.BDCODEMP, Q2.BDCODCOL, Q2.BDCODACCONV, Q2.BDREF
        into :wcodemp, :wcodcol, :wRefIRRFESOCIAL, :wordem, :wref, :wtipofol, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, :WREFFC, :WDATAPGTO, :WREFPAG,
             :WBASEIRRF, :WVALORIRRF, :WINSS, :WAJCUSTOS, :WINDRESC, :WVALABO, :WRENDISENTOS, :WDRENDISENTOS, :WAUXILIOMORADIA, :WDIARIA,
             :WBOLSAMEDICO, :WJUROSMORA, :WCALCULOS, :WINCIDESOCIAL, :WCODACCONV, :WCODFIR, :WQTDMESESRRA do
       begin
         if (prseparaisentos = 1) then -- Retorna Apenas isentos
            begin
              bdtipocalculo = 1;
              WBASEIRRF = 0;
              WVALORIRRF = 0;
              WINSS = 0;
              WJUROSMORA = 0;
              WQTDMESESRRA = 0;
              WBOLSAMEDICO = 0;
            end
         else if (prseparaisentos = 2) then -- Retorna Apenas RRA Sem isentos
            begin
              WDIARIA = 0;
              WVALABO = 0;
              WAUXILIOMORADIA = 0;
              WAJCUSTOS = 0;
              WRENDISENTOS = 0;
              WDRENDISENTOS = '';
              WINDRESC = 0;
            end


         if ((prref = prreffim) and (PRSEPARAISENTOS <> 1)) then
            update TEMP_FILTRO_COLCON_REL set bdcpf = '1' where coalesce(bdcpf,'') = '' and bdcodemp = :wcodemp and bdcodcol = :wcodcol;

         WSUSPEND = 0;
         if (COALESCE(WTIPOFOL, 0) >= 9000) then
            WDIFERENCIADORINTEGER = WCODFIR;

         if ((wcodempatu <> wcodemp) or (wrefirrfesocialatu <> wrefirrfesocial))  then
            begin
              if (prseparafolhas = 1) then
                 begin
                   select first 1 BDCODCLATRI from VRHF_BASE_TEMPESOCIAL ES
                   where ES.BDCODEMP in (:WCODEMP) and(ES.BDREFEMP <= :wrefirrfesocial) and BDCODCLATRI is not null
                   order by BDREFEMP desc  into :WCODCLATRI;

                   if (:WCODCLATRI is null) then /*Se não encontrar pega o proximo para a competencia seguinte.*/
                     begin
                       select first 1 BDCODCLATRI from VRHF_BASE_TEMPESOCIAL ES
                       where ES.BDCODEMP in (:WCODEMP) and (ES.BDREFEMP >= :wrefirrfesocial) and BDCODCLATRI is not null
                       order by BDREFEMP into :WCODCLATRI;
                     end

                   if (:WCODCLATRI is null) then /*Caso ainda seja null, deve considerar como 99 pois significa que no cadastro não tem nenhuma classificação em nenhuma referência*/
                     begin
                       :WCODCLATRI = 99;
                     end

                 end

               select first 1 coalesce(bdcodmatriz,bdcodemp) from tempresas where bdcodemp = :wcodemp into :wMatriz;
            end

         if (wcodempatu = 0) then wcodempatu = wcodemp;
         if (wcodcolatu = 0) then wcodcolatu = wcodcol;
         if (wrefirrfesocialatu = 0) then wrefirrfesocialatu = wrefirrfesocial;
         if (WCODACCONVatu = -1) then WCODACCONVatu = WCODACCONV;

         if ((wcodempatu <> wcodemp) or (wcodcolatu <> wcodcol) or (wrefirrfesocialatu <> wrefirrfesocial)) then
            begin
              WREFPLANSAUANT = 0;
              WREFREEMBMEDANT = 0;
              WREFPREVIDCOMPLANT = 0;
            end

         if (((prseparafolhas <> 1) and ((wcodempatu <> wcodemp) or (wcodcolatu <> wcodcol) or (wrefirrfesocialatu <> wrefirrfesocial))) or
            ((prseparafolhas = 1) and (((wcodempatu <> wcodemp) or (wcodcolatu <> wcodcol) or (wrefirrfesocialatu <> wrefirrfesocial) or (WCODACCONV <> WCODACCONVatu)) and WCODACCONVatu > 0)))  then
            begin
              WSUSPEND = 1;
            end

         if (WSUSPEND = 1) then
            begin
              suspend;
              bddescricaofolha = '';
              bdcodrec = '';

              -- Zera valores que seram somados
              bdbaseirrfmensal = 0; bdvalorirrfmensal  = 0;
              bdinssmensal = 0; bdajcustosmensal = 0; bdindrescmensal = 0;
              bdvalabomensal = 0;bdrendisentosmensal = 0;bddrendisentosmensal = '';
              bdauxiliomoradiamensal = 0;bddiariamensal = 0;
              bdbolsamedicomensal = 0; bdjurosmoramensal = 0;
              bdcalculos = 0;
            end

         WCODACCONVatu = WCODACCONV;
         wcodempatu = wcodemp;
         wcodcolatu = wcodcol;
         wrefirrfesocialatu = wrefirrfesocial;

         bdcodemp = wcodemp;
         bdcodcol = wcodcol;
         bdref = wrefirrfesocial;


         bdbaseirrfmensal = bdbaseirrfmensal + coalesce(WBASEIRRF,0);
         bdvalorirrfmensal =  bdvalorirrfmensal + coalesce(WVALORIRRF,0);
         bdinssmensal = bdinssmensal + coalesce(WINSS,0);
         bdajcustosmensal = bdajcustosmensal + coalesce(WAJCUSTOS,0);
         bdindrescmensal = bdindrescmensal + coalesce(WINDRESC,0);
         bdvalabomensal = bdvalabomensal + coalesce(WVALABO,0);
         bdrendisentosmensal = bdrendisentosmensal + coalesce(WRENDISENTOS,0);
          if (WDRENDISENTOS <> '') then
             begin
               if (BDDRENDISENTOSMENSAL <> '') then
                  begin
                    if (prveiodototalizador = 1) then
                       BDDRENDISENTOSMENSAL = substring(BDDRENDISENTOSMENSAL||';' from 1 for 999);
                    else
                       BDDRENDISENTOSMENSAL = substring(BDDRENDISENTOSMENSAL||', ' from 1 for 999);
                  end
               BDDRENDISENTOSMENSAL = substring(BDDRENDISENTOSMENSAL||WDRENDISENTOS from 1 for 999);
               if (prveiodototalizador = 1) then
                  BDDRENDISENTOSMENSAL = REPLACE(BDDRENDISENTOSMENSAL, ', ', ';');
             end
         bdauxiliomoradiamensal = bdauxiliomoradiamensal + coalesce(WAUXILIOMORADIA,0);
         bddiariamensal = bddiariamensal + coalesce(WDIARIA,0);
         bdbolsamedicomensal = bdbolsamedicomensal + coalesce(WBOLSAMEDICO,0);
         bdjurosmoramensal = bdjurosmoramensal + coalesce(WJUROSMORA,0);
         bdcalculos = bdcalculos + coalesce(WCALCULOS,0);

         if (prseparafolhas = 1) then
            begin
              if ((PRGRAVACODIGORECEITA = 0) and (bdcodrec = '')) then
                 select BDCODREC FROM sp_vrh_getcodreceita_5002(:WCODEMP,:WCODCOL,:wrefirrfesocialatu,:PRTIPO,:WTIPOFOL,:bdtipocalculo,:WCODCLATRI) INTO :bdcodrec;

               select BDDESCRICAOCALCULO,BDTAGSTR from SP_RETORNA_TAGSTR_TOTALIZADORES(:WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, 1, 0, :WORDEM, 1, :WREFFC) into :bddescricaofolha,:bdtagstr;
            end

         /* dependente pensão */
         execute procedure sp_vrhf_add_val_dep_pen_5002(:wcodemp,:wcodcol,null,:wref,wdiferenciadordate,wdiferenciadorinteger,4,wtipofol,wcodemp,:bdtagstr,:bddescricaofolha, WINCIDESOCIAL, 1, 4, wreffc, wdatapgto, wrefpag, 0, :wMatriz, 0, :wREFIRRFESOCIAL,:bdcodrec);

         execute procedure SP_REL_TOT_5002_RRA(:WCODEMP,:WCODCOL,:wREFIRRFESOCIAL,1,:BDTAGSTR,:BDDESCRICAOFOLHA,:wMatriz,:wcodacconv,:wqtdmesesrra);

         execute procedure SP_REL_TOT_5002_RUBRICAS(:wcodemp,:wcodcol,:wref,:wMatriz,:wREFIRRFESOCIAL,0);

         /* realiza o suspendo quando é separado por folha com ecessão de ACD que o sustend é agrupado*/
         if ((prseparafolhas = 1) and (COALESCE(WCODACCONVatu, 0) = 0)) then
            begin
              suspend;
              bddescricaofolha = '';
              bdcodrec = '';
              wsuspend = 0;
              bdbaseirrfmensal = 0; bdvalorirrfmensal  = 0;
              bdinssmensal = 0; bdajcustosmensal = 0; bdindrescmensal = 0;
              bdvalabomensal = 0;bdrendisentosmensal = 0;bddrendisentosmensal = '';
              bdauxiliomoradiamensal = 0;bddiariamensal = 0;
              bdbolsamedicomensal = 0; bdjurosmoramensal = 0;
              bdcalculos = 0;
            end
         else
            begin
              /* Se sair do laço por ser o ultimo registro processa dar suspend*/
              WSUSPEND = 1;
            end
       end

     if (WSUSPEND = 1) then
        suspend;

     if (prref = prreffim) then
        begin
          bddescricaofolha = '';
          bdtagstr = '';
          bdcodrec = '';
          wsuspend = 0;
          bdbaseirrfmensal = 0; bdvalorirrfmensal  = 0;
          bdinssmensal = 0; bdajcustosmensal = 0; bdindrescmensal = 0;
          bdvalabomensal = 0;bdrendisentosmensal = 0;bddrendisentosmensal = '';
          bdauxiliomoradiamensal = 0;bddiariamensal = 0;
          bdbolsamedicomensal = 0; bdjurosmoramensal = 0;
          bdcalculos = 0;
          bdref = prref;
          for select bdcodemp,bdcodcol from TEMP_FILTRO_COLCON_REL where coalesce(bdcpf,'') = '' into bdcodemp,bdcodcol do
            begin
              suspend;
            end
        end
   END

end
^

create or alter procedure SP_RETORNA_BASE_IRRF_CONSOLID_MENSAL (
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRREFFIM integer,
    PRTIPO integer,
    PRVEIODOTOTALIZADOR integer,
    PRSEPARAFOLHAS integer,
    PRGRAVACODIGORECEITA integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBASEIRRFMENSAL numeric(18,6),
    BDVALORIRRFMENSAL numeric(18,6),
    BDINSSMENSAL numeric(18,6),
    BDAJCUSTOSMENSAL numeric(18,6),
    BDINDRESCMENSAL numeric(18,6),
    BDVALABOMENSAL numeric(18,6),
    BDRENDISENTOSMENSAL numeric(18,6),
    BDDRENDISENTOSMENSAL varchar(999),
    BDAUXILIOMORADIAMENSAL numeric(18,6),
    BDDIARIAMENSAL numeric(18,6),
    BDBOLSAMEDICOMENSAL numeric(18,6),
    BDJUROSMORAMENSAL numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDINSS13 numeric(18,6),
    BDAJCUSTOS13 numeric(18,6),
    BDINDRESC13 numeric(18,6),
    BDVALABO13 numeric(18,6),
    BDRENDISENTOS13 numeric(18,6),
    BDDRENDISENTOS13 varchar(999),
    BDAUXILIOMORADIA13 numeric(18,6),
    BDDIARIA13 numeric(18,6),
    BDBOLSAMEDICO13 numeric(18,6),
    BDJUROSMORA13 numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDINSSPLR numeric(18,6),
    BDAJCUSTOSPLR numeric(18,6),
    BDINDRESCPLR numeric(18,6),
    BDVALABOPLR numeric(18,6),
    BDRENDISENTOSPLR numeric(18,6),
    BDDRENDISENTOSPLR varchar(999),
    BDAUXILIOMORADIAPLR numeric(18,6),
    BDDIARIAPLR numeric(18,6),
    BDBOLSAMEDICOPLR numeric(18,6),
    BDJUROSMORAPLR numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDINSSRRA numeric(18,6),
    BDAJCUSTOSRRA numeric(18,6),
    BDINDRESCRRA numeric(18,6),
    BDVALABORRA numeric(18,6),
    BDRENDISENTOSRRA numeric(18,6),
    BDDRENDISENTOSRRA varchar(999),
    BDAUXILIOMORADIARRA numeric(18,6),
    BDDIARIARRA numeric(18,6),
    BDBOLSAMEDICORRA numeric(18,6),
    BDJUROSMORARRA numeric(18,6),
    BDCALCULOS integer,
    BDTIPOCALCULO integer,
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOFOLHA integer,
    BDCODREC varchar(6))
as
declare variable WREFPLANSAUANT integer;
declare variable WREFREEMBMEDANT integer;
declare variable WREFPREVIDCOMPLANT integer;
declare variable WCODCLATRI integer;
declare variable WMATRIZ integer;
declare variable WREFIRRFESOCIAL integer;
declare variable WREFIRRFESOCIALATU integer;
declare variable WINTERMITENTE integer;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WCODEMPATU integer;
declare variable WCODCOLATU integer;
declare variable WSUSPEND integer;
declare variable WFC integer;
declare variable WORDEM integer;
declare variable WREF integer;
declare variable WREFREEMBOLSO integer;
declare variable WREFPLANOSAUDE integer;
declare variable WREFPREVPRIVADA integer;
declare variable WTIPOFOL integer;
declare variable WDIFERENCIADORDATE date;
declare variable WDIFERENCIADORINTEGER integer;
declare variable WREFFC integer;
declare variable WREFPAG integer;
declare variable WDATAPGTO date;
declare variable WBASEIRRF numeric(18,6);
declare variable WVALORIRRF numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WAJCUSTOS numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDISENTOS numeric(18,6);
declare variable WDRENDISENTOS varchar(999);
declare variable WAUXILIOMORADIA numeric(18,6);
declare variable WDIARIA numeric(18,6);
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WJUROSMORA numeric(18,6);
declare variable WCALCULOS integer;
declare variable WINCIDESOCIAL integer;
declare variable WINCIDESOCIALFER integer;
declare variable WCODACCONV integer;
declare variable WCODACCONVATU integer;
declare variable WCODFIR integer;
declare variable WRRA integer;
begin
  bdbaseirrfmensal = 0; bdvalorirrfmensal  = 0;
  bdinssmensal = 0; bdajcustosmensal = 0; bdindrescmensal = 0;
  bdvalabomensal = 0;bdrendisentosmensal = 0;bddrendisentosmensal = '';
  bdauxiliomoradiamensal = 0;bddiariamensal = 0;
  bdbolsamedicomensal = 0; bdjurosmoramensal = 0;
  bdcalculos = 0; WCODACCONVatu = -1;
  bddescricaofolha = '';
  bdtagstr = '';
  bdcodrec = '';
  BDTIPOCALCULO = 1;
  WREFPLANSAUANT = 0;
  WREFREEMBMEDANT = 0;
  WREFPREVIDCOMPLANT = 0;

  if (prtipo = 1) then
   BEGIN
       wcodempatu = 0;
       wcodcolatu = 0;
       wrefirrfesocialatu = 0;
       if (prref = prreffim) then
          begin
            update TEMP_FILTRO_COLCON_REL set bdcpf = '' where coalesce(bdcpf,'') <> '';
          end

       for
          SELECT Q2.BDCODEMP, Q2.BDCODCOL, Q2.BDREFIRRFESOCIAL, Q2.BDINTERMITENTE, Q2.BDFC, Q2.BDORDEM, Q2.bdref,
                 Q2.BDTIPO, Q2.BDDIFERENCIADORDATE, Q2.BDDIFERENCIADORINTEGER, Q2.BDREFFC,
                 Q2.BDDATAPGTO, Q2.BDREFPAG, Q2.BDRENDTRIBUTAVEL, Q2.BDIR,
                 Q2.BDINSS, Q2.BDAJCUSTOS, Q2.BDINDRESC, Q2.BDVALABO, Q2.BDRENDISENTOS, Q2.BDDRENDISENTOS, Q2.BDAUXILIOMORADIA, Q2.BDDIARIA,
                 Q2.BDBOLSAMEDICO, Q2.BDJUROSMORA, Q2.BDCALCULOS, Q2.BDINCIDESOCIAL, Q2.BDINCIDESOCIALFER, Q2.BDCODACCONV, Q2.BDCODFIR, Q2.BDRRA
          FROM (SELECT FT.BDREFIRRFESOCIAL, 0 BDINTERMITENTE, 0 BDFC, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.bddatapgto BDDIFERENCIADORDATE, cast(null as integer) bdDIFERENCIADORINTEGER, cast(null as integer) BDREFFC, FT.bddatapgto, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                       FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDINCIDESOCIALFER, 0 BDCODACCONV, FT.BDCODFIR, 0 BDRRA
                FROM SP_VRHF_DADOS_IR_FN(:PRCODEMP, :PRCODCOL, :PRREF, :prreffim, 0, '', 0, 0, 0, TRUE, FALSE, :prveiodototalizador) FT
                UNION ALL
                SELECT FT.BDREFIRRFESOCIAL, 0 BDINTERMITENTE, 1 BDFC, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.BDDATAPGTO BDDIFERENCIADORDATE, ft.bdrefpag BDDIFERENCIADORINTEGER, ft.BDREFFC BDREFFC, FT.bddatapgto, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                       FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDINCIDESOCIALFER, COALESCE(FT.BDCODACCONV, 0) BDCODACCONV, FT.BDCODFIR, 0 BDRRA
                FROM SP_VRHF_DADOS_IR_FC(:PRCODEMP, :PRCODCOL, :PRREF, :prreffim, 0, '', 0, 0, 0, TRUE, FALSE,0, :prveiodototalizador) FT
                UNION ALL
                SELECT FT.BDREFIRRFESOCIAL, 0 BDINTERMITENTE, 1 BDFC, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.BDDATAPGTO BDDIFERENCIADORDATE, ft.bdrefpag BDDIFERENCIADORINTEGER, ft.BDREFFC BDREFFC, FT.bddatapgto, FT.BDREFPAG, cast(0 as numeric(15,2)) BDRENDTRIBUTAVEL, cast(0 as numeric(15,2)) BDIR, cast(0 as numeric(15,2)) BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                       0 BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, cast(0 as integer) BDINCIDESOCIAL, cast(0 as integer) BDINCIDESOCIALFER, COALESCE(FT.BDCODACCONV, 0) BDCODACCONV, FT.BDCODFIR, 1 BDRRA
                FROM SP_VRHF_DADOS_IR_FC_RRA(:PRCODEMP, :PRCODCOL, :PRREF, :prreffim, 0, '', 0, 0, 0, TRUE, FALSE, 1, FALSE, :prveiodototalizador) FT
                UNION ALL
                SELECT FT.BDREFIRRFESOCIAL, 1 BDINTERMITENTE, 1 BDFC, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.BDDATAPGTO BDDIFERENCIADORDATE, ft.BDCODCONTTI BDDIFERENCIADORINTEGER, ft.BDREFFC BDREFFC, FT.bddatapgto, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                       FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDINCIDESOCIALFER, 0 BDCODACCONV, FT.BDCODFIR, 0 BDRRA
                FROM SP_VRHF_DADOS_IR_FC_INT(:PRCODEMP, :PRCODCOL, :PRREF, :prreffim, 0, '', 0, 0, 0, TRUE, :prveiodototalizador) FT
                UNION ALL
                SELECT FT.BDREFIRRFESOCIAL, 1 BDINTERMITENTE, 0 BDFC, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.bddatapgto BDDIFERENCIADORDATE, ft.BDCODCONTTI BDDIFERENCIADORINTEGER, cast(null as integer) BDREFFC, FT.bddatapgto, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                       FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDINCIDESOCIALFER, 0 BDCODACCONV, 0 BDCODFIR, 0 BDRRA
                FROM SP_VRHF_DADOS_IR_INT(:PRCODEMP, :PRCODCOL, :PRREF, :prreffim, 0, '', 0, 0, 0, TRUE, FALSE,:prveiodototalizador) FT
                UNION ALL
                SELECT FT.BDREFIRRFESOCIAL, 0 BDINTERMITENTE, 0 BDFC, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.BDDATAPGTO BDDIFERENCIADORDATE, cast(null as integer) BDDIFERENCIADORINTEGER, cast(null as integer) BDREFFC, FT.bddatapgto, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                       FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDINCIDESOCIALFER, 0 BDCODACCONV, FT.BDCODFIR, 0 BDRRA
                FROM SP_VRHF_DADOS_IR_AD(:PRCODEMP, :PRCODCOL, :PRREF, :prreffim, 0, '', TRUE, FALSE, :prveiodototalizador) FT
                WHERE FT.BDRENDTRIBUTAVEL > 0
                UNION ALL
                SELECT FT.BDREFIRRFESOCIAL, 0 BDINTERMITENTE, 0 BDFC, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.BDDATAPGTO BDDIFERENCIADORDATE, ft.BDCODTCA BDDIFERENCIADORINTEGER, cast(null as integer) BDREFFC, FT.bddatapgto, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                       FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDINCIDESOCIALFER, 0 BDCODACCONV, FT.BDCODFIR, 0 BDRRA
                FROM SP_VRHF_DADOS_IR_FA(:PRCODEMP, :PRCODCOL, :PRREF, :prreffim, 0, '', 0, 1, TRUE, FALSE, :prveiodototalizador) FT
                UNION ALL
                SELECT FT.BDREFIRRFESOCIAL, 0 BDINTERMITENTE, 0 BDFC, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, FT.BDINIPERAQUIS BDDIFERENCIADORDATE, FT.BDCODFE BDDIFERENCIADORINTEGER, cast(null as integer) BDREFFC, FT.bddatapgto, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                       FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDINCIDESOCIALFER, 0 BDCODACCONV, FT.BDCODFIR, 0 BDRRA
                FROM SP_VRHF_DADOS_IR_FE(:PRCODEMP, :PRCODCOL, :PRREF, :prreffim, 0, '', 0, TRUE, FALSE, :PRVEIODOTOTALIZADOR) FT) Q2
                ORDER BY Q2.BDREFIRRFESOCIAL, Q2.BDCODEMP, Q2.BDCODCOL, Q2.BDFC DESC, Q2.BDINTERMITENTE, Q2.BDCODACCONV, Q2.BDREF
        into :wcodemp, :wcodcol, :wRefIRRFESOCIAL, :wintermitente, :wfc, :wordem, :wref, :wtipofol, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, :WREFFC, :WDATAPGTO, :WREFPAG,
             :WBASEIRRF, :WVALORIRRF, :WINSS, :WAJCUSTOS, :WINDRESC, :WVALABO, :WRENDISENTOS, :WDRENDISENTOS, :WAUXILIOMORADIA, :WDIARIA,
             :WBOLSAMEDICO, :WJUROSMORA, :WCALCULOS, :WINCIDESOCIAL, :WINCIDESOCIALFER, :WCODACCONV, :WCODFIR, :WRRA do
       begin
         if (prref = prreffim) then
            update TEMP_FILTRO_COLCON_REL set bdcpf = '1' where coalesce(bdcpf,'') = '' and bdcodemp = :wcodemp and bdcodcol = :wcodcol;

         WSUSPEND = 0;
         if (COALESCE(WTIPOFOL, 0) >= 9000) then
            WDIFERENCIADORINTEGER = WCODFIR;

         if ((wcodempatu <> wcodemp) or (wrefirrfesocialatu <> wrefirrfesocial))  then
            begin
              if (prseparafolhas = 1) then
                 begin
                   select first 1 BDCODCLATRI from VRHF_BASE_TEMPESOCIAL ES
                   where ES.BDCODEMP in (:WCODEMP) and(ES.BDREFEMP <= :wrefirrfesocial) and BDCODCLATRI is not null
                   order by BDREFEMP desc  into :WCODCLATRI;

                   if (:WCODCLATRI is null) then /*Se não encontrar pega o proximo para a competencia seguinte.*/
                     begin
                       select first 1 BDCODCLATRI from VRHF_BASE_TEMPESOCIAL ES
                       where ES.BDCODEMP in (:WCODEMP) and (ES.BDREFEMP >= :wrefirrfesocial) and BDCODCLATRI is not null
                       order by BDREFEMP into :WCODCLATRI;
                     end

                   if (:WCODCLATRI is null) then /*Caso ainda seja null, deve considerar como 99 pois significa que no cadastro não tem nenhuma classificação em nenhuma referência*/
                     begin
                       :WCODCLATRI = 99;
                     end
                 end

               select first 1 coalesce(bdcodmatriz,bdcodemp) from tempresas where bdcodemp = :wcodemp into :wMatriz;
            end

         if (wcodempatu = 0) then wcodempatu = wcodemp;
         if (wcodcolatu = 0) then wcodcolatu = wcodcol;
         if (wrefirrfesocialatu = 0) then wrefirrfesocialatu = wrefirrfesocial;
         if (WCODACCONVatu = -1) then WCODACCONVatu = WCODACCONV;

         if ((wcodempatu <> wcodemp) or (wcodcolatu <> wcodcol) or (wrefirrfesocialatu <> wrefirrfesocial)) then
            begin
              WREFPLANSAUANT = 0;
              WREFREEMBMEDANT = 0;
              WREFPREVIDCOMPLANT = 0;
            end

         if (((prseparafolhas <> 1) and ((wcodempatu <> wcodemp) or (wcodcolatu <> wcodcol) or (wrefirrfesocialatu <> wrefirrfesocial))) or
            ((prseparafolhas = 1) and (((wcodempatu <> wcodemp) or (wcodcolatu <> wcodcol) or (wrefirrfesocialatu <> wrefirrfesocial) or (WCODACCONV <> WCODACCONVatu)) and WCODACCONVatu > 0)))  then
            begin
              WSUSPEND = 1;
            end

         if (WSUSPEND = 1) then
            begin
              suspend;
              bddescricaofolha = '';
              bdcodrec = '';

              -- Zera valores que seram somados
              bdbaseirrfmensal = 0; bdvalorirrfmensal  = 0;
              bdinssmensal = 0; bdajcustosmensal = 0; bdindrescmensal = 0;
              bdvalabomensal = 0;bdrendisentosmensal = 0;bddrendisentosmensal = '';
              bdauxiliomoradiamensal = 0;bddiariamensal = 0;
              bdbolsamedicomensal = 0; bdjurosmoramensal = 0;
              bdcalculos = 0;
            end

         WCODACCONVatu = WCODACCONV;
         wcodempatu = wcodemp;
         wcodcolatu = wcodcol;
         wrefirrfesocialatu = wrefirrfesocial;

         bdcodemp = wcodemp;
         bdcodcol = wcodcol;
         bdref = wrefirrfesocial;


         bdbaseirrfmensal = bdbaseirrfmensal + coalesce(WBASEIRRF,0);
         bdvalorirrfmensal =  bdvalorirrfmensal + coalesce(WVALORIRRF,0);
         bdinssmensal = bdinssmensal + coalesce(WINSS,0);
         bdajcustosmensal = bdajcustosmensal + coalesce(WAJCUSTOS,0);
         bdindrescmensal = bdindrescmensal + coalesce(WINDRESC,0);
         bdvalabomensal = bdvalabomensal + coalesce(WVALABO,0);
         bdrendisentosmensal = bdrendisentosmensal + coalesce(WRENDISENTOS,0);
          if (WDRENDISENTOS <> '') then
             begin
               if (BDDRENDISENTOSMENSAL <> '') then
                  begin
                    if (prveiodototalizador = 1) then
                       BDDRENDISENTOSMENSAL = substring(BDDRENDISENTOSMENSAL||';' from 1 for 999);
                    else
                       BDDRENDISENTOSMENSAL = substring(BDDRENDISENTOSMENSAL||', ' from 1 for 999);
                  end
               BDDRENDISENTOSMENSAL = substring(BDDRENDISENTOSMENSAL||WDRENDISENTOS from 1 for 999);
               if (prveiodototalizador = 1) then
                  BDDRENDISENTOSMENSAL = REPLACE(BDDRENDISENTOSMENSAL, ', ', ';');
             end
         bdauxiliomoradiamensal = bdauxiliomoradiamensal + coalesce(WAUXILIOMORADIA,0);
         bddiariamensal = bddiariamensal + coalesce(WDIARIA,0);
         bdbolsamedicomensal = bdbolsamedicomensal + coalesce(WBOLSAMEDICO,0);
         bdjurosmoramensal = bdjurosmoramensal + coalesce(WJUROSMORA,0);
         bdcalculos = bdcalculos + coalesce(WCALCULOS,0);

         if (prseparafolhas = 1) then
            begin
              if ((PRGRAVACODIGORECEITA = 0) and (bdcodrec = '')) then
                 select BDCODREC FROM sp_vrh_getcodreceita_5002(:WCODEMP,:WCODCOL,:wrefirrfesocialatu,:PRTIPO,:WTIPOFOL,1,:WCODCLATRI) INTO :bdcodrec;

               if (COALESCE(WCODACCONVatu, 0) = 0) then
                  begin
                    select BDDESCRICAOCALCULO,BDTAGSTR from SP_RETORNA_TAGSTR_TOTALIZADORES(:WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, 1, :WINTERMITENTE, :WORDEM, :WFC)
                    into :bddescricaofolha,:bdtagstr;
                  end
               else
                  begin
                    if (bddescricaofolha = '') then
                       begin
                          -- Quando for ADC o suspende é agrupado pelo código do ADC
                          select BDDESCRICAOCALCULO,BDTAGSTR from SP_RETORNA_TAGSTR_TOTALIZADORES(:WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, 1, :WINTERMITENTE, :WORDEM, :WFC, :WREFFC)
                          into :bddescricaofolha,:bdtagstr;
                       end
                  end
            end

         if (WRRA = 0) then
         begin
           /* dependente pensão */
           execute procedure sp_vrhf_add_val_dep_pen_5002(:wcodemp,:wcodcol,null,:wref,wdiferenciadordate,wdiferenciadorinteger,1,wtipofol,wcodemp,bdtagstr,bddescricaofolha, WINCIDESOCIAL, 1, 1, wreffc, wdatapgto, wrefpag, wfc, :wMatriz, :wincidesocialfer, :wREFIRRFESOCIAL,:bdcodrec);
     
           execute procedure SP_REL_TOT_5002_RUBRICAS(:wcodemp,:wcodcol,:wref,:wMatriz,:wREFIRRFESOCIAL,0);

           /* Busca valores plano saude, reembolso, previdencia */
           if (wtipofol in (0, 4, 100, 101, 9000, 9001, 9002)) then -- Folha normal, férias folha normal
              begin
                if (wref <> WREFPLANSAUANT) then
                   begin
                     EXECUTE PROCEDURE SP_REL_TOT_5002_PLANSAU(:WCODEMP, :WCODCOL, :WREF, 1, :BDTAGSTR, :BDDESCRICAOFOLHA, :wMatriz, :wREFIRRFESOCIAL);
                     WREFPLANSAUANT = wref;
                   end
                if (wref <> WREFREEMBMEDANT) then
                   begin
                     EXECUTE PROCEDURE SP_REL_TOT_5002_REEMBMED(:WCODEMP, :WCODCOL, :WREF, 1, :BDTAGSTR, :BDDESCRICAOFOLHA, :wMatriz, :wREFIRRFESOCIAL);
                     WREFREEMBMEDANT = wref;
                   end
                if (wref <> WREFPREVIDCOMPLANT) then
                   begin
                     EXECUTE PROCEDURE SP_REL_TOT_5002_PREVIDCOMPL(:WCODEMP, :WCODCOL, :WREF, :BDTAGSTR, :BDDESCRICAOFOLHA, 1, 1, :wMatriz, :wREFIRRFESOCIAL,:bdcodrec);
                     WREFPREVIDCOMPLANT = wref;
                   end
              end
           else if ((wref <> WREFPREVIDCOMPLANT) and (wtipofol in (10, 9100))) then  -- Folha 13º
              begin
                EXECUTE PROCEDURE SP_REL_TOT_5002_PREVIDCOMPL(:WCODEMP, :WCODCOL, :WREF, :BDTAGSTR, :BDDESCRICAOFOLHA, 1, 1, :wMatriz, :wREFIRRFESOCIAL,:bdcodrec);
                WREFPREVIDCOMPLANT = wref;
              end
            end
         /* realiza o suspendo quando é separado por folha com ecessão de ACD que o sustend é agrupado*/
         if ((prseparafolhas = 1) and (COALESCE(WCODACCONVatu, 0) = 0)) then
            begin
              suspend;
              bddescricaofolha = '';
              bdcodrec = '';
              wsuspend = 0;
              bdbaseirrfmensal = 0; bdvalorirrfmensal  = 0;
              bdinssmensal = 0; bdajcustosmensal = 0; bdindrescmensal = 0;
              bdvalabomensal = 0;bdrendisentosmensal = 0;bddrendisentosmensal = '';
              bdauxiliomoradiamensal = 0;bddiariamensal = 0;
              bdbolsamedicomensal = 0; bdjurosmoramensal = 0;
              bdcalculos = 0;
            end
         else
            begin
              /* Se sair do laço por ser o ultimo registro processa dar suspend*/
              WSUSPEND = 1;
            end
       end

     if (WSUSPEND = 1) then
        suspend;

     if (prref = prreffim) then
        begin
          bddescricaofolha = '';
          bdtagstr = '';
          bdcodrec = '';
          wsuspend = 0;
          bdbaseirrfmensal = 0; bdvalorirrfmensal  = 0;
          bdinssmensal = 0; bdajcustosmensal = 0; bdindrescmensal = 0;
          bdvalabomensal = 0;bdrendisentosmensal = 0;bddrendisentosmensal = '';
          bdauxiliomoradiamensal = 0;bddiariamensal = 0;
          bdbolsamedicomensal = 0; bdjurosmoramensal = 0;
          bdcalculos = 0;
          bdref = prref;
          for select bdcodemp,bdcodcol from TEMP_FILTRO_COLCON_REL where coalesce(bdcpf,'') = '' into bdcodemp,bdcodcol do
            begin
              suspend;
            end
        end

   END
   ELSE
     BEGIN
       wcodempatu = 0;
       wcodcolatu = 0;
       wrefirrfesocialatu = 0;
       bddescricaofolha = '';
       BDTAGSTR = '';
--       if (prref = prreffim) then
--          begin
--            update TEMP_FILTRO_COLCON_REL set bdcpf = '' where coalesce(bdcpf,'') <> '';
--          end

       for
        SELECT ft.bdrefirrfesocial, FT.BDCODEMP, FT.BDCODTER, FT.BDTIPO, FT.BDCODSERV, FT.BDDATAPAGSERV, FT.bdbaseirbruta, FT.bdvalorir, IIF(FT.bdvalorinss > 0, FT.bdvalorinss , 0) as bdvalorinss, 1 as BDCALCULOS,FT.BDINCIDESOCIAL
        FROM VRHF_SP_CONS_IR_TERCEIROS(:PRCODEMP, :PRCODCOL, :PRREF, :PRREFFIM, TRUE) FT
        into :wrefirrfesocial, :WCODEMP, :WCODCOL, :WTIPOFOL, :WDIFERENCIADORINTEGER, :WDATAPGTO, :WBASEIRRF, :WVALORIRRF, :WINSS, :WCALCULOS, :WINCIDESOCIAL  do
       begin
         wsuspend = 0;
--         if (prref = prreffim) then
--            update TEMP_FILTRO_COLCON_REL set bdcpf = '1' where coalesce(bdcpf,'') = '' and bdcodemp = :wcodemp and bdcodter = :wcodcol;

         if ((wcodempatu <> wcodemp) or (wrefirrfesocialatu <> wrefirrfesocial))  then
            begin
              if (prseparafolhas = 1) then
                 begin
                   select first 1 BDCODCLATRI from VRHF_BASE_TEMPESOCIAL ES
                   where ES.BDCODEMP in (:WCODEMP) and (ES.BDREFEMP <= :wrefirrfesocial) and BDCODCLATRI is not null
                   order by BDREFEMP desc  into :WCODCLATRI;

                   if (:WCODCLATRI is null) then /*Se não encontrar pega o proximo para a competencia seguinte.*/
                     begin
                       select first 1 BDCODCLATRI from VRHF_BASE_TEMPESOCIAL ES
                       where ES.BDCODEMP in (:WCODEMP) and (ES.BDREFEMP >= :wrefirrfesocial) and BDCODCLATRI is not null
                       order by BDREFEMP into :WCODCLATRI;
                     end

                   if (:WCODCLATRI is null) then /*Caso ainda seja null, deve considerar como 99 pois significa que no cadastro não tem nenhuma classificação em nenhuma referência*/
                     begin
                       :WCODCLATRI = 99;
                     end
                 end

               select first 1 coalesce(bdcodmatriz,bdcodemp) from tempresas where bdcodemp = :wcodemp into :wMatriz;
            end

         if (wcodempatu = 0) then wcodempatu = wcodemp;
         if (wcodcolatu = 0) then wcodcolatu = wcodcol;
         if (wrefirrfesocialatu = 0) then wrefirrfesocialatu = wrefirrfesocial;
         if (WCODACCONVatu = -1) then WCODACCONVatu = WCODACCONV;

         if ((wcodempatu <> wcodemp) or (wcodcolatu <> wcodcol) or (wrefirrfesocialatu <> wrefirrfesocial)) then
            begin
              WREFPLANSAUANT = 0;
              WREFREEMBMEDANT = 0;
              WREFPREVIDCOMPLANT = 0;
            end

         if ((prseparafolhas <> 1) and ((wcodempatu <> wcodemp) or (wcodcolatu <> wcodcol) or (wrefirrfesocialatu <> wrefirrfesocial))) then
            begin
              WSUSPEND = 1;
            end

         if (WSUSPEND = 1) then
            begin
              suspend;
              bddescricaofolha = '';
              bdcodrec = '';

              -- Zera valores que seram somados
              bdbaseirrfmensal = 0; bdvalorirrfmensal  = 0;
              bdinssmensal = 0; bdajcustosmensal = 0; bdindrescmensal = 0;
              bdvalabomensal = 0;bdrendisentosmensal = 0;bddrendisentosmensal = '';
              bdauxiliomoradiamensal = 0;bddiariamensal = 0;
              bdbolsamedicomensal = 0; bdjurosmoramensal = 0;
              bdcalculos = 0;
            end

          wcodempatu = wcodemp;
          wcodcolatu = wcodcol;
          wrefirrfesocialatu = wrefirrfesocial;

          bdcodcol = wcodcol;
          bdcodemp = wcodemp;
          bdref = wrefirrfesocial;

          BDBASEIRRFMENSAL = BDBASEIRRFMENSAL + COALESCE(:WBASEIRRF, 0);
          BDVALORIRRFMENSAL = BDVALORIRRFMENSAL + COALESCE(:WVALORIRRF, 0);
          BDINSSMENSAL = BDINSSMENSAL + COALESCE(:WINSS, 0);
          BDCALCULOS = BDCALCULOS + COALESCE(:WCALCULOS, 0);
          BDTIPOCALCULO = 1;
          BDTIPOFOLHA = WTIPOFOL;

          if (COALESCE(PRSEPARAFOLHAS, 0) = 1) then
             select BDDESCRICAOCALCULO,BDTAGSTR from SP_RETORNA_TAGSTR_TOTALIZADORES(:WCODEMP, :WCODCOL, /*:WREF*/ 0, :WTIPOFOL, /*:WDIFERENCIADORDATE*/ null, :WDIFERENCIADORINTEGER, 2) into :bddescricaofolha,:bdtagstr;

          if (PRGRAVACODIGORECEITA = 0) then
             select BDCODREC FROM sp_vrh_getcodreceita_5002(:WCODEMP,:WCODCOL,:prreffim,:PRTIPO,:bdtipofolha,:bdtipocalculo,:WCODCLATRI) INTO :bdcodrec;

          execute procedure sp_vrhf_add_val_dep_pen_5002(:wcodemp, null,:wcodcol,/*:wref*/ 0,/*wdiferenciadordate*/ null,wdiferenciadorinteger,1,wtipofol,wcodemp,bdtagstr,bddescricaofolha, wincidesocial, 1, 1, 0, wdatapgto, 0, 0, :wmatriz, 0, :wrefirrfesocial,:bdcodrec);

          execute procedure SP_REL_TOT_5002_RUBRICAS(:wcodemp,:wcodcol,:wref,:wMatriz,:wREFIRRFESOCIAL,1);

          if (COALESCE(PRSEPARAFOLHAS, 0) = 1) then
             begin
               SUSPEND;
               bddescricaofolha = '';
               BDTAGSTR = '';
               BDBASEIRRFMENSAL = 0; BDVALORIRRFMENSAL = 0;
               BDINSSMENSAL = 0; BDCALCULOS = 0;
               WBASEIRRF = 0; WVALORIRRF = 0;
               WINSS = 0; WCALCULOS = 0;
               WSUSPEND = 0;
             end
          else
             WSUSPEND = 1;
       end

     if (WSUSPEND = 1) then
        suspend;

   END
end
^

create or alter procedure SP_RETORNA_BASE_IRRF_CONSOLID (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRTIPO integer,
    PRVEIODOTOTALIZADOR integer,
    PRSEPARAFOLHAS integer,
    PRCODEMPORD integer,
    PRCODCLATRI integer = 0,
    PRGRAVACODIGORECEITA integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDBASEIRRFMENSAL numeric(18,6),
    BDVALORIRRFMENSAL numeric(18,6),
    BDINSSMENSAL numeric(18,6),
    BDAJCUSTOSMENSAL numeric(18,6),
    BDINDRESCMENSAL numeric(18,6),
    BDVALABOMENSAL numeric(18,6),
    BDRENDISENTOSMENSAL numeric(18,6),
    BDDRENDISENTOSMENSAL varchar(999),
    BDAUXILIOMORADIAMENSAL numeric(18,6),
    BDDIARIAMENSAL numeric(18,6),
    BDBOLSAMEDICOMENSAL numeric(18,6),
    BDJUROSMORAMENSAL numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDINSS13 numeric(18,6),
    BDAJCUSTOS13 numeric(18,6),
    BDINDRESC13 numeric(18,6),
    BDVALABO13 numeric(18,6),
    BDRENDISENTOS13 numeric(18,6),
    BDDRENDISENTOS13 varchar(999),
    BDAUXILIOMORADIA13 numeric(18,6),
    BDDIARIA13 numeric(18,6),
    BDBOLSAMEDICO13 numeric(18,6),
    BDJUROSMORA13 numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDINSSPLR numeric(18,6),
    BDAJCUSTOSPLR numeric(18,6),
    BDINDRESCPLR numeric(18,6),
    BDVALABOPLR numeric(18,6),
    BDRENDISENTOSPLR numeric(18,6),
    BDDRENDISENTOSPLR varchar(999),
    BDAUXILIOMORADIAPLR numeric(18,6),
    BDDIARIAPLR numeric(18,6),
    BDBOLSAMEDICOPLR numeric(18,6),
    BDJUROSMORAPLR numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDINSSRRA numeric(18,6),
    BDAJCUSTOSRRA numeric(18,6),
    BDINDRESCRRA numeric(18,6),
    BDVALABORRA numeric(18,6),
    BDRENDISENTOSRRA numeric(18,6),
    BDDRENDISENTOSRRA varchar(999),
    BDAUXILIOMORADIARRA numeric(18,6),
    BDDIARIARRA numeric(18,6),
    BDBOLSAMEDICORRA numeric(18,6),
    BDJUROSMORARRA numeric(18,6),
    BDCALCULOS integer,
    BDTIPOCALCULO integer,
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOFOLHA integer,
    BDCODREC varchar(6))
as
declare variable WBASEIRRF numeric(18,6);
declare variable WVALORIRRF numeric(18,6);
declare variable WINSS numeric(18,6);
declare variable WAJCUSTOS numeric(18,6);
declare variable WINDRESC numeric(18,6);
declare variable WVALABO numeric(18,6);
declare variable WRENDISENTOS numeric(18,6);
declare variable WDRENDISENTOS varchar(999);
declare variable WAUXILIOMORADIA numeric(18,6);
declare variable WDIARIA numeric(18,6);
declare variable WBOLSAMEDICO numeric(18,6);
declare variable WJUROSMORA numeric(18,6);
declare variable WCALCULOS integer;
declare variable WTEMINFOCALCULO integer;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREFREEMBMED integer;
declare variable WTIPOFOL integer;
declare variable WDIFERENCIADORDATE date;
declare variable WDIFERENCIADORINTEGER integer;
declare variable WINTERMITENTE integer;
declare variable WINCIDESOCIAL integer;
declare variable WREFFC integer;
declare variable WDATAPGTO date;
declare variable WFC integer;
declare variable WREFPAG integer;
declare variable WREFREEMBMEDANT integer;
declare variable WORDEM integer;
declare variable WCODACCONV integer;
declare variable WCODACCONVANT integer;
declare variable WPRIMEIROREGADC integer;
declare variable WINCIDESOCIALFER integer;
declare variable WREFPLANSAU integer;
declare variable WREFPLANSAUANT integer;
declare variable WREFPREVIDCOMPL integer;
declare variable WREFPREVIDCOMPLANT integer;
declare variable WREF integer;
declare variable WCODFIR integer;
declare variable WQTDMESESRRA numeric(18,6);
begin
  BDCODEMP = 0;
  BDCODCOL = 0;
  BDREF = 0;
  BDBASEIRRFMENSAL = 0;
  BDVALORIRRFMENSAL = 0;
  BDINSSMENSAL = 0;
  BDAJCUSTOSMENSAL = 0;
  BDINDRESCMENSAL = 0;
  BDVALABOMENSAL = 0;
  BDRENDISENTOSMENSAL = 0;
  BDDRENDISENTOSMENSAL = '';
  BDAUXILIOMORADIAMENSAL = 0;
  BDDIARIAMENSAL = 0;
  BDTIPOFOLHA = 0;
  BDBOLSAMEDICOMENSAL = 0;
  BDJUROSMORAMENSAL = 0;

  BDCALCULOS = 0;
  BDTIPOCALCULO = 0;
  BDCODREC = '';
  WBASEIRRF = 0;
  WVALORIRRF = 0;
  WINSS = 0;
  WAJCUSTOS = 0;
  WINDRESC = 0;
  WVALABO = 0;
  WRENDISENTOS = 0;
  WDRENDISENTOS = '';
  WAUXILIOMORADIA = 0;
  WDIARIA = 0;
  WBOLSAMEDICO = 0;
  WJUROSMORA = 0;
  WCALCULOS = 0;
  WTEMINFOCALCULO = 0;
  WINCIDESOCIAL = 0;
  WREFREEMBMEDANT = -1;
  WREFPLANSAUANT = -1;
  WREFPREVIDCOMPLANT = -1;
  WCODACCONV = 0;
  WCODACCONVANT = -1;
  WPRIMEIROREGADC = 0;
  WCODFIR = 0;
  if (prtipo = 1) then
   BEGIN
       for
          SELECT Q2.BDINTERMITENTE, Q2.BDFC, Q2.BDORDEM, Q2.BDCODEMP, Q2.BDCODCOL, Q2.bdref, Q2.BDTIPO, Q2.BDDIFERENCIADORDATE, Q2.BDDIFERENCIADORINTEGER, Q2.BDREFFC, Q2.BDDATAPGTO, Q2.BDREFPAG, Q2.BDRENDTRIBUTAVEL, Q2.BDIR, Q2.BDINSS, Q2.BDAJCUSTOS, Q2.BDINDRESC, Q2.BDVALABO, Q2.BDRENDISENTOS, Q2.BDDRENDISENTOS, Q2.BDAUXILIOMORADIA, Q2.BDDIARIA,
                 Q2.BDBOLSAMEDICO, Q2.BDJUROSMORA, Q2.BDCALCULOS, Q2.BDINCIDESOCIAL, Q2.BDINCIDESOCIALFER, Q2.BDCODACCONV, Q2.BDCODFIR
          FROM (SELECT 0 BDINTERMITENTE, 0 BDFC, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.bddatapgto BDDIFERENCIADORDATE, cast(null as integer) bdDIFERENCIADORINTEGER, cast(null as integer) BDREFFC, FT.bddatapgto, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                       FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDINCIDESOCIALFER, 0 BDCODACCONV, FT.BDCODFIR
                FROM SP_VRHF_DADOS_IR_FN('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 0, 0, 0, TRUE, FALSE, :prveiodototalizador) FT
                UNION ALL
                SELECT 0 BDINTERMITENTE, 1 BDFC, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.BDDATAPGTO BDDIFERENCIADORDATE, ft.bdrefpag BDDIFERENCIADORINTEGER, ft.BDREFFC BDREFFC, FT.bddatapgto, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                       FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDINCIDESOCIALFER, COALESCE(FT.BDCODACCONV, 0) BDCODACCONV, FT.BDCODFIR
                FROM SP_VRHF_DADOS_IR_FC('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 0, 0, 0, TRUE, FALSE,0, :prveiodototalizador) FT
                UNION ALL
                SELECT 1 BDINTERMITENTE, 1 BDFC, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.BDDATAPGTO BDDIFERENCIADORDATE, ft.BDCODCONTTI BDDIFERENCIADORINTEGER, ft.BDREFFC BDREFFC, FT.bddatapgto, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                       FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDINCIDESOCIALFER, 0 BDCODACCONV, FT.BDCODFIR
                FROM SP_VRHF_DADOS_IR_FC_INT('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 0, 0, 0, TRUE, :prveiodototalizador) FT
                UNION ALL
                SELECT 1 BDINTERMITENTE, 0 BDFC, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.bddatapgto BDDIFERENCIADORDATE, ft.BDCODCONTTI BDDIFERENCIADORINTEGER, cast(null as integer) BDREFFC, FT.bddatapgto, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                       FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDINCIDESOCIALFER, 0 BDCODACCONV, 0 BDCODFIR
                FROM SP_VRHF_DADOS_IR_INT('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 0, 0, 0, TRUE, FALSE,:prveiodototalizador) FT
                UNION ALL
                SELECT 0 BDINTERMITENTE, 0 BDFC, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.BDDATAPGTO BDDIFERENCIADORDATE, cast(null as integer) BDDIFERENCIADORINTEGER, cast(null as integer) BDREFFC, FT.bddatapgto, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                       FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDINCIDESOCIALFER, 0 BDCODACCONV, FT.BDCODFIR
                FROM SP_VRHF_DADOS_IR_AD('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', TRUE, FALSE, :prveiodototalizador) FT
                WHERE FT.BDRENDTRIBUTAVEL > 0
                UNION ALL
                SELECT 0 BDINTERMITENTE, 0 BDFC, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.BDDATAPGTO BDDIFERENCIADORDATE, ft.BDCODTCA BDDIFERENCIADORINTEGER, cast(null as integer) BDREFFC, FT.bddatapgto, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                       FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDINCIDESOCIALFER, 0 BDCODACCONV, FT.BDCODFIR
                FROM SP_VRHF_DADOS_IR_FA('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 0, 1, TRUE, FALSE, :prveiodototalizador) FT
                UNION ALL
                SELECT 0 BDINTERMITENTE, 0 BDFC, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, FT.BDINIPERAQUIS BDDIFERENCIADORDATE, FT.BDCODFE BDDIFERENCIADORINTEGER, cast(null as integer) BDREFFC, FT.bddatapgto, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                       FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDINCIDESOCIALFER, 0 BDCODACCONV, FT.BDCODFIR
                FROM SP_VRHF_DADOS_IR_FE('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 0, TRUE, FALSE, :PRVEIODOTOTALIZADOR) FT) Q2 ORDER BY Q2.BDCODEMP, Q2.BDCODCOL, Q2.BDFC DESC, Q2.BDINTERMITENTE, Q2.BDCODACCONV, Q2.BDREF
        into :WINTERMITENTE, :WFC, :WORDEM, :WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, :WREFFC, :WDATAPGTO, :WREFPAG, :WBASEIRRF, :WVALORIRRF, :WINSS, :WAJCUSTOS, :WINDRESC, :WVALABO, :WRENDISENTOS, :WDRENDISENTOS, :WAUXILIOMORADIA, :WDIARIA,
             :WBOLSAMEDICO, :WJUROSMORA, :WCALCULOS, :WINCIDESOCIAL, :WINCIDESOCIALFER, :WCODACCONV, :WCODFIR
      do
       begin
          WREFREEMBMED = WREF;
          WREFPLANSAU = WREF;
          WREFPREVIDCOMPL = WREF;
          if (COALESCE(WTIPOFOL, 0) >= 9000) then
             WDIFERENCIADORINTEGER = WCODFIR;
          if (COALESCE(WCODACCONVANT, -1) = -1 and COALESCE(WCODACCONV, 0) > 0) then
             begin
               WCODACCONVANT = WCODACCONV;
               WPRIMEIROREGADC = 1;
             end
          if ((PRSEPARAFOLHAS = 1) and (COALESCE(WCODACCONV, 0) <> COALESCE(WCODACCONVANT, 0)) and (WCODACCONVANT > 0)) then
             begin
               SUSPEND;
               bddescricaofolha = '';
               bdtagstr = '';
               BDBASEIRRFMENSAL = 0;
               BDVALORIRRFMENSAL = 0;
               BDINSSMENSAL = 0;
               BDAJCUSTOSMENSAL = 0;
               BDINDRESCMENSAL = 0;
               BDVALABOMENSAL = 0;
               BDRENDISENTOSMENSAL = 0;
               BDDRENDISENTOSMENSAL = '';
               BDAUXILIOMORADIAMENSAL = 0;
               BDDIARIAMENSAL = 0;
               BDTIPOFOLHA = 0;
               BDBOLSAMEDICOMENSAL = 0;
               BDJUROSMORAMENSAL = 0;
               BDTIPOCALCULO = 0;
               BDCODREC = '';
               WCODACCONVANT = WCODACCONV;
               WPRIMEIROREGADC = 0;
               if (coalesce(wcodacconv, 0) > 0) then
                  begin
                    select BDDESCRICAOCALCULO,BDTAGSTR from SP_RETORNA_TAGSTR_TOTALIZADORES(:WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, 1, :WINTERMITENTE, :WORDEM, :WFC)
                    into :bddescricaofolha,:bdtagstr;
                  end
             end
          else if (PRSEPARAFOLHAS = 1 and WPRIMEIROREGADC = 1) then
             begin
               select BDDESCRICAOCALCULO,BDTAGSTR from SP_RETORNA_TAGSTR_TOTALIZADORES(:WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, 1, :WINTERMITENTE, :WORDEM, :WFC)
               into :bddescricaofolha,:bdtagstr;
               WPRIMEIROREGADC = 0;
             end
          BDBASEIRRFMENSAL = BDBASEIRRFMENSAL + COALESCE(:WBASEIRRF, 0);
          BDVALORIRRFMENSAL = BDVALORIRRFMENSAL + COALESCE(:WVALORIRRF, 0);
          BDINSSMENSAL = BDINSSMENSAL + COALESCE(:WINSS, 0);
          BDCALCULOS = BDCALCULOS + COALESCE(:WCALCULOS, 0);
          BDAJCUSTOSMENSAL = BDAJCUSTOSMENSAL + COALESCE(:WAJCUSTOS, 0);
          BDINDRESCMENSAL = BDINDRESCMENSAL + COALESCE(:WINDRESC, 0);
          BDVALABOMENSAL = BDVALABOMENSAL + COALESCE(:WVALABO, 0);
          BDRENDISENTOSMENSAL = BDRENDISENTOSMENSAL + COALESCE(:WRENDISENTOS, 0);
          if (WDRENDISENTOS <> '') then
             begin
               if (BDDRENDISENTOSMENSAL <> '') then
                  begin
                    if (prveiodototalizador = 1) then
                       BDDRENDISENTOSMENSAL = BDDRENDISENTOSMENSAL||';';
                    else
                       BDDRENDISENTOSMENSAL = BDDRENDISENTOSMENSAL||', ';
                  end
               BDDRENDISENTOSMENSAL = BDDRENDISENTOSMENSAL||WDRENDISENTOS;
               if (prveiodototalizador = 1) then
                  BDDRENDISENTOSMENSAL = REPLACE(BDDRENDISENTOSMENSAL, ', ', ';');
             end
          BDAUXILIOMORADIAMENSAL = BDAUXILIOMORADIAMENSAL + COALESCE(:WAUXILIOMORADIA, 0);
          BDDIARIAMENSAL = BDDIARIAMENSAL + COALESCE(:WDIARIA, 0);
          BDBOLSAMEDICOMENSAL = BDBOLSAMEDICOMENSAL + COALESCE(:WBOLSAMEDICO, 0);
          BDJUROSMORAMENSAL = BDJUROSMORAMENSAL + COALESCE(:WJUROSMORA, 0);
          BDTIPOCALCULO = 1;
          BDTIPOFOLHA = WTIPOFOL;
          if ( (COALESCE(PRSEPARAFOLHAS, 0) = 1) and (COALESCE(WCODACCONV, 0) = 0) ) then
             begin
                if (PRGRAVACODIGORECEITA = 0) then
                   select BDCODREC FROM sp_vrh_getcodreceita_5002(:WCODEMP,:WCODCOL,:prref,:PRTIPO,:bdtipofolha,:bdtipocalculo,:PRCODCLATRI) INTO :bdcodrec;
                -- Olhar o tipo de folha descrição e tagstr
                select BDDESCRICAOCALCULO,BDTAGSTR from SP_RETORNA_TAGSTR_TOTALIZADORES(:WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, 1, :WINTERMITENTE, :WORDEM, :WFC)
                into :bddescricaofolha,:bdtagstr;
                execute procedure sp_vrhf_add_val_dep_pen_5002(:wcodemp,:wcodcol,null,:wref,wdiferenciadordate,wdiferenciadorinteger,1,wtipofol,wcodemp,bdtagstr,bddescricaofolha, WINCIDESOCIAL, 1, 1, wreffc, wdatapgto, wrefpag, wfc, :prcodempord, :wincidesocialfer, :PRREF,:bdcodrec);
                if (wtipofol in (0, 4, 100, 101, 9000, 9001, 9002)) then -- Folha normal, férias folha normal
                   begin
                     if (WREFPLANSAU <> WREFPLANSAUANT) then
                        begin
                          EXECUTE PROCEDURE SP_REL_TOT_5002_PLANSAU(:WCODEMP, :WCODCOL, :WREF, 1, :BDTAGSTR, :BDDESCRICAOFOLHA, :prcodempord, :PRREF);
                          WREFPLANSAUANT = WREFPLANSAU;
                        end
                     if (WREFREEMBMED <> WREFREEMBMEDANT) then
                        begin
                          EXECUTE PROCEDURE SP_REL_TOT_5002_REEMBMED(:WCODEMP, :WCODCOL, :WREF, 1, :BDTAGSTR, :BDDESCRICAOFOLHA, :PRCODEMPORD, :PRREF);
                          WREFREEMBMEDANT = WREFREEMBMED;
                        end
                     if (WREFPREVIDCOMPL <> WREFPREVIDCOMPLANT) then
                        begin
                          EXECUTE PROCEDURE SP_REL_TOT_5002_PREVIDCOMPL(:WCODEMP, :WCODCOL, :WREF, :BDTAGSTR, :BDDESCRICAOFOLHA, 1, 1, :PRCODEMPORD, :PRREF,:bdcodrec);
                          WREFPREVIDCOMPLANT = WREFPREVIDCOMPL;
                        end
                   end
                else if ((WREFPREVIDCOMPL <> WREFPREVIDCOMPLANT) and (wtipofol in (10, 9100))) then  -- Folha 13º
                   begin
                     EXECUTE PROCEDURE SP_REL_TOT_5002_PREVIDCOMPL(:WCODEMP, :WCODCOL, :WREF, :BDTAGSTR, :BDDESCRICAOFOLHA, 1, 1, :PRCODEMPORD, :PRREF,:bdcodrec);
                     WREFPREVIDCOMPLANT = WREFPREVIDCOMPL;
                   end
                SUSPEND;
                bddescricaofolha = '';
                bdtagstr = '';
                WBASEIRRF = 0;
                WVALORIRRF = 0;
                WINSS = 0;
                WAJCUSTOS = 0;
                WINDRESC = 0;
                WVALABO = 0;
                WRENDISENTOS = 0;
                WDRENDISENTOS = '';
                WAUXILIOMORADIA = 0;
                WDIARIA = 0;
                WBOLSAMEDICO = 0;
                WJUROSMORA = 0;
                WCALCULOS = 0;
                BDBASEIRRFMENSAL = 0;
                BDVALORIRRFMENSAL = 0;
                BDINSSMENSAL = 0;
                BDAJCUSTOSMENSAL = 0;
                BDINDRESCMENSAL = 0;
                BDVALABOMENSAL = 0;
                BDRENDISENTOSMENSAL = 0;
                BDDRENDISENTOSMENSAL = '';
                BDAUXILIOMORADIAMENSAL = 0;
                BDDIARIAMENSAL = 0;
                BDTIPOFOLHA = 0;
                BDBOLSAMEDICOMENSAL = 0;
                BDJUROSMORAMENSAL = 0;
                BDTIPOCALCULO = 0;
                BDCODREC = '';
             end
          else
             begin
               if (PRGRAVACODIGORECEITA = 0) then
                  select BDCODREC FROM sp_vrh_getcodreceita_5002(:WCODEMP,:WCODCOL,:prref,:PRTIPO,:bdtipofolha,:bdtipocalculo,:PRCODCLATRI) INTO :bdcodrec;
               execute procedure sp_vrhf_add_val_dep_pen_5002(:wcodemp,:wcodcol,null,:wref,wdiferenciadordate,wdiferenciadorinteger,1,wtipofol,wcodemp,bdtagstr,bddescricaofolha, WINCIDESOCIAL, 1, 1, wreffc, wdatapgto, wrefpag, wfc, :prcodempord, :wincidesocialfer, :PRREF,:bdcodrec);
               if (wtipofol in (0, 4, 100, 101, 9000, 9001, 9002)) then -- Folha normal, férias folha normal
                  begin
                    if (WREFPLANSAU <> WREFPLANSAUANT) then
                       begin
                         EXECUTE PROCEDURE SP_REL_TOT_5002_PLANSAU(:WCODEMP, :WCODCOL, :WREF, 1, :BDTAGSTR, :BDDESCRICAOFOLHA, :prcodempord, :PRREF);
                         WREFPLANSAUANT = WREFPLANSAU;
                       end
                    if (WREFREEMBMED <> WREFREEMBMEDANT) then
                       begin
                         EXECUTE PROCEDURE SP_REL_TOT_5002_REEMBMED(:WCODEMP, :WCODCOL, :WREF, 1, :BDTAGSTR, :BDDESCRICAOFOLHA, :PRCODEMPORD, :PRREF);
                         WREFREEMBMEDANT = WREFREEMBMED;
                       end
                    if (WREFPREVIDCOMPL <> WREFPREVIDCOMPLANT) then
                       begin
                         EXECUTE PROCEDURE SP_REL_TOT_5002_PREVIDCOMPL(:WCODEMP, :WCODCOL, :WREF, :BDTAGSTR, :BDDESCRICAOFOLHA, 1, 1, :PRCODEMPORD, :PRREF,:bdcodrec);
                         WREFPREVIDCOMPLANT = WREFPREVIDCOMPL;
                       end
                  end
               else if ((WREFPREVIDCOMPL <> WREFPREVIDCOMPLANT) and (wtipofol in (10, 9100))) then  -- Folha 13º
                  begin
                    EXECUTE PROCEDURE SP_REL_TOT_5002_PREVIDCOMPL(:WCODEMP, :WCODCOL, :WREF, :BDTAGSTR, :BDDESCRICAOFOLHA, 1, 1, :PRCODEMPORD, :PRREF,:bdcodrec);
                    WREFPREVIDCOMPLANT = WREFPREVIDCOMPL;
                  end
             end
          WTEMINFOCALCULO = 1;
       end
     if ( (COALESCE(PRSEPARAFOLHAS, 0) = 1) and (COALESCE(WCODACCONV, 0) <> 0) and (COALESCE(WCODACCONV, 0) = COALESCE(WCODACCONVANT, 0))) then
        begin
          SUSPEND;
          bddescricaofolha = '';
          bdtagstr = '';
          WBASEIRRF = 0;
          WVALORIRRF = 0;
          WINSS = 0;
          WAJCUSTOS = 0;
          WINDRESC = 0;
          WVALABO = 0;
          WRENDISENTOS = 0;
          WDRENDISENTOS = '';
          WAUXILIOMORADIA = 0;
          WDIARIA = 0;
          WBOLSAMEDICO = 0;
          WJUROSMORA = 0;
          WCALCULOS = 0;
          BDBASEIRRFMENSAL = 0;
          BDVALORIRRFMENSAL = 0;
          BDINSSMENSAL = 0;
          BDAJCUSTOSMENSAL = 0;
          BDINDRESCMENSAL = 0;
          BDVALABOMENSAL = 0;
          BDRENDISENTOSMENSAL = 0;
          BDDRENDISENTOSMENSAL = '';
          BDAUXILIOMORADIAMENSAL = 0;
          BDDIARIAMENSAL = 0;
          BDTIPOFOLHA = 0;
          BDBOLSAMEDICOMENSAL = 0;
          BDJUROSMORAMENSAL = 0;
          BDTIPOCALCULO = 0;
          BDCODREC = '';
        end
     else if ((COALESCE(PRSEPARAFOLHAS, 0) = 0) and (WTEMINFOCALCULO = 1)) then
        begin
           SUSPEND;
           bddescricaofolha = '';
           bdtagstr = '';
           WBASEIRRF = 0;
           WVALORIRRF = 0;
           WINSS = 0;
           WAJCUSTOS = 0;
           WINDRESC = 0;
           WVALABO = 0;
           WRENDISENTOS = 0;
           WDRENDISENTOS = '';
           WAUXILIOMORADIA = 0;
           WDIARIA = 0;
           WBOLSAMEDICO = 0;
           WJUROSMORA = 0;
           WCALCULOS = 0;
           BDBASEIRRFMENSAL = 0;
           BDVALORIRRFMENSAL = 0;
           BDINSSMENSAL = 0;
           BDAJCUSTOSMENSAL = 0;
           BDINDRESCMENSAL = 0;
           BDVALABOMENSAL = 0;
           BDRENDISENTOSMENSAL = 0;
           BDDRENDISENTOSMENSAL = '';
           BDAUXILIOMORADIAMENSAL = 0;
           BDDIARIAMENSAL = 0;
           BDTIPOFOLHA = 0;
           BDBOLSAMEDICOMENSAL = 0;
           BDJUROSMORAMENSAL = 0;
           BDTIPOCALCULO = 0;
           BDCODREC = '';
        end
     else if (WTEMINFOCALCULO = 0) then
        begin
           WBASEIRRF = 0;
           WVALORIRRF = 0;
           WINSS = 0;
           WAJCUSTOS = 0;
           WINDRESC = 0;
           WVALABO = 0;
           WRENDISENTOS = 0;
           WDRENDISENTOS = '';
           WAUXILIOMORADIA = 0;
           WDIARIA = 0;
           WBOLSAMEDICO = 0;
           WJUROSMORA = 0;
           WCALCULOS = 0;
           BDBASEIRRFMENSAL = 0;
           BDVALORIRRFMENSAL = 0;
           BDINSSMENSAL = 0;
           BDAJCUSTOSMENSAL = 0;
           BDINDRESCMENSAL = 0;
           BDVALABOMENSAL = 0;
           BDRENDISENTOSMENSAL = 0;
           BDDRENDISENTOSMENSAL = '';
           BDAUXILIOMORADIAMENSAL = 0;
           BDDIARIAMENSAL = 0;
           BDTIPOFOLHA = 0;
           BDBOLSAMEDICOMENSAL = 0;
           BDJUROSMORAMENSAL = 0;
           BDTIPOCALCULO = 1;
           BDCODREC = '';
           BDCALCULOS = 0;
           bddescricaofolha = '';
           bdtagstr = '';
           SUSPEND;
        end
     WTEMINFOCALCULO = 0;
   END
   ELSE
   BEGIN
       for
        SELECT FT.BDCODEMP, FT.BDCODTER, FT.BDTIPO, FT.BDCODSERV, FT.BDDATAPAGSERV, FT.bdbaseirbruta, FT.bdvalorir, IIF(FT.bdvalorinss > 0, FT.bdvalorinss , 0) as bdvalorinss, 1 as BDCALCULOS,FT.BDINCIDESOCIAL
        FROM VRHF_SP_CONS_IR_TERCEIROS('CALC_TERC.BDCODEMP='||:PRCODEMP, 'CALC_TERC.BDCODTER='||:PRCODCOL, :PRREF, :PRREF, TRUE) FT
        into :WCODEMP, :WCODCOL, :WTIPOFOL, :WDIFERENCIADORINTEGER, :WDATAPGTO, :WBASEIRRF, :WVALORIRRF, :WINSS, :WCALCULOS, :WINCIDESOCIAL
      do
       begin
          BDBASEIRRFMENSAL = BDBASEIRRFMENSAL + COALESCE(:WBASEIRRF, 0);
          BDVALORIRRFMENSAL = BDVALORIRRFMENSAL + COALESCE(:WVALORIRRF, 0);
          BDINSSMENSAL = BDINSSMENSAL + COALESCE(:WINSS, 0);
          BDCALCULOS = BDCALCULOS + COALESCE(:WCALCULOS, 0);
          BDTIPOCALCULO = 1;
          BDTIPOFOLHA = WTIPOFOL;
          if (COALESCE(PRSEPARAFOLHAS, 0) = 1) then
             begin
               if (PRGRAVACODIGORECEITA = 0) then
                  select BDCODREC FROM sp_vrh_getcodreceita_5002(:WCODEMP,:WCODCOL,:prref,:PRTIPO,:bdtipofolha,:bdtipocalculo,:PRCODCLATRI) INTO :bdcodrec;
               select BDDESCRICAOCALCULO,BDTAGSTR from SP_RETORNA_TAGSTR_TOTALIZADORES(:WCODEMP, :WCODCOL, /*:WREF*/ 0, :WTIPOFOL, /*:WDIFERENCIADORDATE*/ null, :WDIFERENCIADORINTEGER, 2)
               into :bddescricaofolha,:bdtagstr;
               execute procedure sp_vrhf_add_val_dep_pen_5002(:wcodemp, null,:wcodcol,/*:wref*/ 0,/*wdiferenciadordate*/ null,wdiferenciadorinteger,1,wtipofol,wcodemp,bdtagstr,bddescricaofolha, wincidesocial, 1, 1, 0, wdatapgto, 0, 0, :prcodempord, 0, :PRREF,:bdcodrec);
               SUSPEND;
               BDBASEIRRFMENSAL = 0; BDVALORIRRFMENSAL = 0;
               BDINSSMENSAL = 0; BDCALCULOS = 0;
               WBASEIRRF = 0; WVALORIRRF = 0;
               WINSS = 0; WCALCULOS = 0;
             end
          else
             begin
               if (PRGRAVACODIGORECEITA = 0) then
                  select BDCODREC FROM sp_vrh_getcodreceita_5002(:WCODEMP,:WCODCOL,:prref,:PRTIPO,:bdtipofolha,:bdtipocalculo,:PRCODCLATRI) INTO :bdcodrec;
               execute procedure sp_vrhf_add_val_dep_pen_5002(:wcodemp,null,:wcodcol,0,null,wdiferenciadorinteger,1,wtipofol,wcodemp,'','', wincidesocial, 1, 1, 0, wdatapgto, 0, 0, :prcodempord, 0, :PRREF,:bdcodrec);
             end
          WTEMINFOCALCULO = 1;
       end
       if ((COALESCE(PRSEPARAFOLHAS, 0) = 0) and (WTEMINFOCALCULO = 1)) then
        begin
           SUSPEND;
           BDBASEIRRFMENSAL = 0;
           BDVALORIRRFMENSAL = 0;
           BDINSSMENSAL = 0;
           BDCALCULOS = 0;
           WBASEIRRF = 0;
           WVALORIRRF = 0;
           WINSS = 0;
           WCALCULOS = 0;
        end
      else if (WTEMINFOCALCULO = 0) then
        begin
           BDBASEIRRFMENSAL = 0;
           BDVALORIRRFMENSAL = 0;
           BDINSSMENSAL = 0;
           BDCALCULOS = 0;
           WBASEIRRF = 0;
           WVALORIRRF = 0;
           WINSS = 0;
           WCALCULOS = 0;
           SUSPEND;
        end
   END
  WBASEIRRF = 0;  WVALORIRRF = 0;
  WINSS = 0;  WAJCUSTOS = 0;
  WINDRESC = 0;  WVALABO = 0;
  WRENDISENTOS = 0;  WDRENDISENTOS = '';
  WAUXILIOMORADIA = 0;  WDIARIA = 0;
  WBOLSAMEDICO = 0;  WJUROSMORA = 0;
  WCALCULOS = 0;  WREFREEMBMEDANT = -1;
  WREFPLANSAU = -1;  WREFPREVIDCOMPLANT = -1;
  if (prtipo = 1) then
   BEGIN
       for
        SELECT Q1.BDINTERMITENTE, Q1.BDORDEM, Q1.BDCODEMP, Q1.BDCODCOL, Q1.bdref, Q1.BDTIPO, Q1.BDDIFERENCIADORDATE, Q1.BDDIFERENCIADORINTEGER, Q1.BDREFPAG, Q1.BDRENDTRIBUTAVEL, Q1.BDIR, Q1.BDINSS, Q1.BDAJCUSTOS, Q1.BDINDRESC, Q1.BDVALABO, Q1.BDRENDISENTOS, Q1.BDDRENDISENTOS, Q1.BDAUXILIOMORADIA, Q1.BDDIARIA,
               Q1.BDBOLSAMEDICO, Q1.BDJUROSMORA, Q1.BDCALCULOS, Q1.BDINCIDESOCIAL, Q1.BDCODFIR
        FROM (SELECT 0 BDINTERMITENTE, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, cast(null as date) BDDIFERENCIADORDATE, cast(null as integer) BDDIFERENCIADORINTEGER, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDCODFIR
            FROM SP_VRHF_DADOS_IR_13('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', TRUE, FALSE, TRUE, :prveiodototalizador, 0) FT
            WHERE FT.BDTIPO NOT IN (111)
            UNION ALL
            SELECT 0 BDINTERMITENTE, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.bddatapgto BDDIFERENCIADORDATE, ft.bdrefpag BDDIFERENCIADORINTEGER, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                   FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, 0 BDCODFIR
            FROM SP_VRHF_DADOS_IR_13FC('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', TRUE, 0, 0) FT
            UNION ALL
            SELECT 1 BDINTERMITENTE, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.bddatapgto BDDIFERENCIADORDATE, ft.BDCODCONTTI BDDIFERENCIADORINTEGER, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                   FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, 0 BDCODFIR
            FROM SP_VRHF_DADOS_IR_13FC_INT('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', TRUE, 0) FT
            UNION ALL
            SELECT 0 BDINTERMITENTE, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, cast(null as date) BDDIFERENCIADORDATE, cast(null as integer) BDDIFERENCIADORINTEGER, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                   FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDCODFIR
            FROM SP_VRHF_DADOS_IR_C13('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', TRUE, FALSE, 0, :prveiodototalizador) FT
            INNER JOIN VRHF_EMP_T13SAL S13 ON FT.BDCODEMP = S13.BDCODEMP AND FT.BDCODCOL = S13.BDCODCOL AND FT.BDREF = S13.BDREF13
            UNION ALL
            SELECT 1 BDINTERMITENTE, FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, cast(null as date) BDDIFERENCIADORDATE, ft.BDCODCONTTI BDDIFERENCIADORINTEGER, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                   FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDCODFIR
            FROM SP_VRHF_DADOS_IR_INT13('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 1, TRUE, FALSE, :prveiodototalizador, 0) FT
            WHERE FT.BDTIPO NOT IN (111)
            UNION ALL
            SELECT 0 BDINTERMITENTE, 0 BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, cast(null as date) BDDIFERENCIADORDATE, cast(null as integer) BDDIFERENCIADORINTEGER, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
                   FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, 0 BDCODFIR
            FROM SP_VRHF_DADOS_IR_AD13('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '') FT) Q1
        ORDER BY Q1.BDCODEMP, Q1.BDCODCOL, Q1.BDREF

        into :WINTERMITENTE, :WORDEM, :WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, :WREFPAG, :WBASEIRRF, :WVALORIRRF, :WINSS, :WAJCUSTOS, :WINDRESC, :WVALABO, :WRENDISENTOS, :WDRENDISENTOS, :WAUXILIOMORADIA, :WDIARIA,:WBOLSAMEDICO, :WJUROSMORA, :WCALCULOS, :WINCIDESOCIAL, :WCODFIR
      do
       begin
         WREFREEMBMED = WREF;
         WREFPLANSAU = WREF;
         WREFPREVIDCOMPL = WREF;

         if (COALESCE(WTIPOFOL, 0) >= 9000) then
            WDIFERENCIADORINTEGER = WCODFIR;

          BDBASEIRRFMENSAL = BDBASEIRRFMENSAL + COALESCE(:WBASEIRRF, 0);
          BDVALORIRRFMENSAL = BDVALORIRRFMENSAL + COALESCE(:WVALORIRRF, 0);
          BDINSSMENSAL = BDINSSMENSAL + COALESCE(:WINSS, 0);
          BDCALCULOS = BDCALCULOS + COALESCE(:WCALCULOS, 0);
          BDAJCUSTOSMENSAL = BDAJCUSTOSMENSAL + COALESCE(:WAJCUSTOS, 0);
          BDINDRESCMENSAL = BDINDRESCMENSAL + COALESCE(:WINDRESC, 0);
          BDVALABOMENSAL = BDVALABOMENSAL + COALESCE(:WVALABO, 0);
          BDRENDISENTOSMENSAL = BDRENDISENTOSMENSAL + COALESCE(:WRENDISENTOS, 0);

          if (WDRENDISENTOS <> '') then
             begin
               if (BDDRENDISENTOSMENSAL <> '') then
                  begin
                    if (prveiodototalizador = 1) then
                       BDDRENDISENTOSMENSAL = BDDRENDISENTOSMENSAL||';';
                    else
                       BDDRENDISENTOSMENSAL = BDDRENDISENTOSMENSAL||', ';
                  end
               BDDRENDISENTOSMENSAL = BDDRENDISENTOSMENSAL||WDRENDISENTOS;
               if (prveiodototalizador = 1) then
                  BDDRENDISENTOSMENSAL = REPLACE(BDDRENDISENTOSMENSAL, ', ', ';');
             end
          BDAUXILIOMORADIAMENSAL = BDAUXILIOMORADIAMENSAL + COALESCE(:WAUXILIOMORADIA, 0);
          BDDIARIAMENSAL = BDDIARIAMENSAL + COALESCE(:WDIARIA, 0);
          BDBOLSAMEDICOMENSAL = BDBOLSAMEDICOMENSAL + COALESCE(:WBOLSAMEDICO, 0);
          BDJUROSMORAMENSAL = BDJUROSMORAMENSAL + COALESCE(:WJUROSMORA, 0);
          BDTIPOCALCULO = 2;
          BDTIPOFOLHA = WTIPOFOL;

          if (COALESCE(PRSEPARAFOLHAS, 0) = 1) then
             begin
                if (PRGRAVACODIGORECEITA = 0) then
                   select BDCODREC FROM sp_vrh_getcodreceita_5002(:WCODEMP,:WCODCOL,:prref,:PRTIPO,:bdtipofolha,:bdtipocalculo,:PRCODCLATRI) INTO :bdcodrec;
                -- Olhar o tipo de folha descrição e tagstr
                select BDDESCRICAOCALCULO,BDTAGSTR from SP_RETORNA_TAGSTR_TOTALIZADORES(:WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, 1, :WINTERMITENTE, :WORDEM)
                into :bddescricaofolha,:bdtagstr;
                execute procedure sp_vrhf_add_val_dep_pen_5002(:wcodemp,:wcodcol,null,:wref,wdiferenciadordate,wdiferenciadorinteger,2,wtipofol,wcodemp,:bdtagstr,:bddescricaofolha, WINCIDESOCIAL, 1, 2, 0, null, wrefpag, 0, :prcodempord, 0, :PRREF,:bdcodrec);
                if (wtipofol in (0, 4, 100, 101, 9000, 9001, 9002)) then -- Folha normal, férias folha normal
                   begin
                     if (WREFPLANSAU <> WREFPLANSAUANT) then
                        begin
                          EXECUTE PROCEDURE SP_REL_TOT_5002_PLANSAU(:WCODEMP, :WCODCOL, :WREF, 1, :BDTAGSTR, :BDDESCRICAOFOLHA, :prcodempord, :PRREF);
                          WREFPLANSAUANT = WREFPLANSAU;
                        end
                     if (WREFREEMBMED <> WREFREEMBMEDANT) then
                        begin
                          EXECUTE PROCEDURE SP_REL_TOT_5002_REEMBMED(:WCODEMP, :WCODCOL, :WREF, 1, :BDTAGSTR, :BDDESCRICAOFOLHA, :PRCODEMPORD, :PRREF);
                          WREFREEMBMEDANT = WREFREEMBMED;
                        end
                     if (WREFPREVIDCOMPL <> WREFPREVIDCOMPLANT) then
                        begin
                          EXECUTE PROCEDURE SP_REL_TOT_5002_PREVIDCOMPL(:WCODEMP, :WCODCOL, :WREF, :BDTAGSTR, :BDDESCRICAOFOLHA, 1, 2, :PRCODEMPORD, :PRREF,:bdcodrec);
                          WREFPREVIDCOMPLANT = WREFPREVIDCOMPL;
                        end
                   end
                else if ((WREFPREVIDCOMPL <> WREFPREVIDCOMPLANT) and (wtipofol in (10, 9100))) then  -- Folha 13º
                   begin
                     EXECUTE PROCEDURE SP_REL_TOT_5002_PREVIDCOMPL(:WCODEMP, :WCODCOL, :WREF, :BDTAGSTR, :BDDESCRICAOFOLHA, 1, 2, :PRCODEMPORD, :PRREF,:bdcodrec);
                     WREFPREVIDCOMPLANT = WREFPREVIDCOMPL;
                   end
                SUSPEND;
                bddescricaofolha = '';
                bdtagstr = '';
                bddescricaofolha = '';
                bdtagstr = '';
                WBASEIRRF = 0;
                WVALORIRRF = 0;
                WINSS = 0;
                WAJCUSTOS = 0;
                WINDRESC = 0;
                WVALABO = 0;
                WRENDISENTOS = 0;
                WDRENDISENTOS = '';
                WAUXILIOMORADIA = 0;
                WDIARIA = 0;
                WBOLSAMEDICO = 0;
                WJUROSMORA = 0;
                WCALCULOS = 0;

                BDBASEIRRFMENSAL = 0;
                BDVALORIRRFMENSAL = 0;
                BDINSSMENSAL = 0;
                BDAJCUSTOSMENSAL = 0;
                BDINDRESCMENSAL = 0;
                BDVALABOMENSAL = 0;
                BDRENDISENTOSMENSAL = 0;
                BDDRENDISENTOSMENSAL = '';
                BDAUXILIOMORADIAMENSAL = 0;
                BDDIARIAMENSAL = 0;
                BDTIPOFOLHA = 0;
                BDBOLSAMEDICOMENSAL = 0;
                BDJUROSMORAMENSAL = 0;
                BDTIPOCALCULO = 0;
                BDCODREC = '';
             end
          else
             begin
                if (PRGRAVACODIGORECEITA = 0) then
                   select BDCODREC FROM sp_vrh_getcodreceita_5002(:WCODEMP,:WCODCOL,:prref,:PRTIPO,:bdtipofolha,:bdtipocalculo,:PRCODCLATRI) INTO :bdcodrec;
                execute procedure sp_vrhf_add_val_dep_pen_5002(:wcodemp,:wcodcol,null,:wref,wdiferenciadordate,wdiferenciadorinteger,2,wtipofol,wcodemp,'','', WINCIDESOCIAL, 1, 2, 0, null, wrefpag, 0, :prcodempord, 0, :PRREF,:bdcodrec);

                if (wtipofol in (0, 4, 100, 101, 9000, 9001, 9002)) then -- Folha normal, férias folha normal
                   begin
                     if (WREFPLANSAU <> WREFPLANSAUANT) then
                        begin
                          EXECUTE PROCEDURE SP_REL_TOT_5002_PLANSAU(:WCODEMP, :WCODCOL, :WREF, 1, :BDTAGSTR, :BDDESCRICAOFOLHA, :prcodempord, :PRREF);
                          WREFPLANSAUANT = WREFPLANSAU;
                        end
                     if (WREFREEMBMED <> WREFREEMBMEDANT) then
                        begin
                          EXECUTE PROCEDURE SP_REL_TOT_5002_REEMBMED(:WCODEMP, :WCODCOL, :WREF, 1, :BDTAGSTR, :BDDESCRICAOFOLHA, :PRCODEMPORD, :PRREF);
                          WREFREEMBMEDANT = WREFREEMBMED;
                        end
                     if (WREFPREVIDCOMPL <> WREFPREVIDCOMPLANT) then
                        begin
                          EXECUTE PROCEDURE SP_REL_TOT_5002_PREVIDCOMPL(:WCODEMP, :WCODCOL, :WREF, :BDTAGSTR, :BDDESCRICAOFOLHA, 1, 2, :PRCODEMPORD, :PRREF,:bdcodrec);
                          WREFPREVIDCOMPLANT = WREFPREVIDCOMPL;
                        end
                   end
                else if ((WREFPREVIDCOMPL <> WREFPREVIDCOMPLANT) and (wtipofol in (10, 9100))) then  -- Folha 13º
                   begin
                     EXECUTE PROCEDURE SP_REL_TOT_5002_PREVIDCOMPL(:WCODEMP, :WCODCOL, :WREF, :BDTAGSTR, :BDDESCRICAOFOLHA, 1, 2, :PRCODEMPORD, :PRREF,:bdcodrec);
                     WREFPREVIDCOMPLANT = WREFPREVIDCOMPL;
                   end
             end
          WTEMINFOCALCULO = 1;
       end

      if ((COALESCE(PRSEPARAFOLHAS, 0) = 0) and (WTEMINFOCALCULO = 1)) then
         begin
            SUSPEND;
            bddescricaofolha = '';
            bdtagstr = '';
            WBASEIRRF = 0;
            WVALORIRRF = 0;
            WINSS = 0;
            WAJCUSTOS = 0;
            WINDRESC = 0;
            WVALABO = 0;
            WRENDISENTOS = 0;
            WDRENDISENTOS = '';
            WAUXILIOMORADIA = 0;
            WDIARIA = 0;
            WBOLSAMEDICO = 0;
            WJUROSMORA = 0;
            WCALCULOS = 0;

            BDBASEIRRFMENSAL = 0;
            BDVALORIRRFMENSAL = 0;
            BDINSSMENSAL = 0;
            BDAJCUSTOSMENSAL = 0;
            BDINDRESCMENSAL = 0;
            BDVALABOMENSAL = 0;
            BDRENDISENTOSMENSAL = 0;
            BDDRENDISENTOSMENSAL = '';
            BDAUXILIOMORADIAMENSAL = 0;
            BDDIARIAMENSAL = 0;
            BDTIPOFOLHA = 0;
            BDBOLSAMEDICOMENSAL = 0;
            BDJUROSMORAMENSAL = 0;
            BDTIPOCALCULO = 0;
            BDCODREC = '';
         end
      else if (WTEMINFOCALCULO = 0) then
        begin
           WBASEIRRF = 0;
           WVALORIRRF = 0;
           WINSS = 0;
           WAJCUSTOS = 0;
           WINDRESC = 0;
           WVALABO = 0;
           WRENDISENTOS = 0;
           WDRENDISENTOS = '';
           WAUXILIOMORADIA = 0;
           WDIARIA = 0;
           WBOLSAMEDICO = 0;
           WJUROSMORA = 0;
           WCALCULOS = 0;
           BDBASEIRRFMENSAL = 0;
           BDVALORIRRFMENSAL = 0;
           BDINSSMENSAL = 0;
           BDAJCUSTOSMENSAL = 0;
           BDINDRESCMENSAL = 0;
           BDVALABOMENSAL = 0;
           BDRENDISENTOSMENSAL = 0;
           BDDRENDISENTOSMENSAL = '';
           BDAUXILIOMORADIAMENSAL = 0;
           BDDIARIAMENSAL = 0;
           BDTIPOFOLHA = 0;
           BDBOLSAMEDICOMENSAL = 0;
           BDJUROSMORAMENSAL = 0;
           BDTIPOCALCULO = 2;
           BDCODREC = '';
           BDCALCULOS = 0;
           bddescricaofolha = '';
           bdtagstr = '';
           SUSPEND;
        end

      WTEMINFOCALCULO = 0;
      for
        SELECT FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.BDDATAPGTO, ft.BDCODTCA, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, IIF(FT.BDINSS > 0,FT.BDINSS,0) as BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,
               FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, FT.BDINCIDESOCIAL, FT.BDCODFIR
        FROM SP_VRHF_DADOS_IR_FA('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 1, 0, TRUE, FALSE, :prveiodototalizador) FT
        into :WORDEM, :WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, :WREFPAG, :WBASEIRRF, :WVALORIRRF, :WINSS, :WAJCUSTOS, :WINDRESC, :WVALABO, :WRENDISENTOS, :WDRENDISENTOS, :WAUXILIOMORADIA, :WDIARIA,:WBOLSAMEDICO, :WJUROSMORA, :WCALCULOS, :WINCIDESOCIAL, :WCODFIR
      do
       begin
         if (COALESCE(WTIPOFOL, 0) >= 9000) then
            WDIFERENCIADORINTEGER = WCODFIR;

          BDBASEIRRFMENSAL = BDBASEIRRFMENSAL + COALESCE(:WBASEIRRF, 0);
          BDVALORIRRFMENSAL = BDVALORIRRFMENSAL + COALESCE(:WVALORIRRF, 0);
          BDINSSMENSAL = BDINSSMENSAL + COALESCE(:WINSS, 0);
          BDCALCULOS = BDCALCULOS + COALESCE(:WCALCULOS, 0);
          BDAJCUSTOSMENSAL = BDAJCUSTOSMENSAL + COALESCE(:WAJCUSTOS, 0);
          BDINDRESCMENSAL = BDINDRESCMENSAL + COALESCE(:WINDRESC, 0);
          BDVALABOMENSAL = BDVALABOMENSAL + COALESCE(:WVALABO, 0);
          BDRENDISENTOSMENSAL = BDRENDISENTOSMENSAL + COALESCE(:WRENDISENTOS, 0);

          if (WDRENDISENTOS <> '') then
             begin
               if (BDDRENDISENTOSMENSAL <> '') then
                  begin
                    if (prveiodototalizador = 1) then
                       BDDRENDISENTOSMENSAL = BDDRENDISENTOSMENSAL||';';
                    else
                       BDDRENDISENTOSMENSAL = BDDRENDISENTOSMENSAL||', ';
                  end
               BDDRENDISENTOSMENSAL = BDDRENDISENTOSMENSAL||WDRENDISENTOS;
               if (prveiodototalizador = 1) then
                  BDDRENDISENTOSMENSAL = REPLACE(BDDRENDISENTOSMENSAL, ', ', ';');
             end
          BDAUXILIOMORADIAMENSAL = BDAUXILIOMORADIAMENSAL + COALESCE(:WAUXILIOMORADIA, 0);
          BDDIARIAMENSAL = BDDIARIAMENSAL + COALESCE(:WDIARIA, 0);
          BDBOLSAMEDICOMENSAL = BDBOLSAMEDICOMENSAL + COALESCE(:WBOLSAMEDICO, 0);
          BDJUROSMORAMENSAL = BDJUROSMORAMENSAL + COALESCE(:WJUROSMORA, 0);
          BDTIPOCALCULO = 3;
          BDTIPOFOLHA = WTIPOFOL;

          if (COALESCE(PRSEPARAFOLHAS, 0) = 1) then
             begin
                if (PRGRAVACODIGORECEITA = 0) then
                   select BDCODREC FROM sp_vrh_getcodreceita_5002(:WCODEMP,:WCODCOL,:prref,:PRTIPO,:bdtipofolha,:bdtipocalculo,:PRCODCLATRI) INTO :bdcodrec;
                -- Olhar o tipo de folha descrição e tagstr
                select BDDESCRICAOCALCULO,BDTAGSTR from SP_RETORNA_TAGSTR_TOTALIZADORES(:WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, 1, 0, :WORDEM) into :bddescricaofolha,:bdtagstr;
                execute procedure sp_vrhf_add_val_dep_pen_5002(:wcodemp,:wcodcol,null,:wref,wdiferenciadordate,wdiferenciadorinteger,3,wtipofol,wcodemp,:bdtagstr,:bddescricaofolha, WINCIDESOCIAL, 1, 3, 0, null, wrefpag, 0, :prcodempord, 0, :PRREF,:bdcodrec);
                SUSPEND;
                bddescricaofolha = '';
                bdtagstr = '';
                WBASEIRRF = 0;
                WVALORIRRF = 0;
                WINSS = 0;
                WAJCUSTOS = 0;
                WINDRESC = 0;
                WVALABO = 0;
                WRENDISENTOS = 0;
                WDRENDISENTOS = '';
                WAUXILIOMORADIA = 0;
                WDIARIA = 0;
                WBOLSAMEDICO = 0;
                WJUROSMORA = 0;
                WCALCULOS = 0;

                BDBASEIRRFMENSAL = 0;
                BDVALORIRRFMENSAL = 0;
                BDINSSMENSAL = 0;
                BDAJCUSTOSMENSAL = 0;
                BDINDRESCMENSAL = 0;
                BDVALABOMENSAL = 0;
                BDRENDISENTOSMENSAL = 0;
                BDDRENDISENTOSMENSAL = '';
                BDAUXILIOMORADIAMENSAL = 0;
                BDDIARIAMENSAL = 0;
                BDTIPOFOLHA = 0;
                BDBOLSAMEDICOMENSAL = 0;
                BDJUROSMORAMENSAL = 0;
                BDTIPOCALCULO = 0;
                BDCODREC = '';
             end
          else
             begin
               if (PRGRAVACODIGORECEITA = 0) then
                  select BDCODREC FROM sp_vrh_getcodreceita_5002(:WCODEMP,:WCODCOL,:prref,:PRTIPO,:bdtipofolha,:bdtipocalculo,:PRCODCLATRI) INTO :bdcodrec;
               execute procedure sp_vrhf_add_val_dep_pen_5002(:wcodemp,:wcodcol,null,:wref,wdiferenciadordate,wdiferenciadorinteger,3,wtipofol,wcodemp,'','', WINCIDESOCIAL, 1, 3, 0, null, wrefpag, 0, :prcodempord, 0, :PRREF,:bdcodrec);
             end
          WTEMINFOCALCULO = 1;
       end

      if ((COALESCE(PRSEPARAFOLHAS, 0) = 0) and (WTEMINFOCALCULO = 1)) then
         begin
            SUSPEND;
            bddescricaofolha = '';
            bdtagstr = '';
            WBASEIRRF = 0;
            WVALORIRRF = 0;
            WINSS = 0;
            WAJCUSTOS = 0;
            WINDRESC = 0;
            WVALABO = 0;
            WRENDISENTOS = 0;
            WDRENDISENTOS = '';
            WAUXILIOMORADIA = 0;
            WDIARIA = 0;
            WBOLSAMEDICO = 0;
            WJUROSMORA = 0;
            WCALCULOS = 0;

            BDBASEIRRFMENSAL = 0;
            BDVALORIRRFMENSAL = 0;
            BDINSSMENSAL = 0;
            BDAJCUSTOSMENSAL = 0;
            BDINDRESCMENSAL = 0;
            BDVALABOMENSAL = 0;
            BDRENDISENTOSMENSAL = 0;
            BDDRENDISENTOSMENSAL = '';
            BDAUXILIOMORADIAMENSAL = 0;
            BDDIARIAMENSAL = 0;
            BDTIPOFOLHA = 0;
            BDBOLSAMEDICOMENSAL = 0;
            BDJUROSMORAMENSAL = 0;
            BDTIPOCALCULO = 0;
            BDCODREC = '';
         end
      else if (WTEMINFOCALCULO = 0) then
        begin
           WBASEIRRF = 0;
           WVALORIRRF = 0;
           WINSS = 0;
           WAJCUSTOS = 0;
           WINDRESC = 0;
           WVALABO = 0;
           WRENDISENTOS = 0;
           WDRENDISENTOS = '';
           WAUXILIOMORADIA = 0;
           WDIARIA = 0;
           WBOLSAMEDICO = 0;
           WJUROSMORA = 0;
           WCALCULOS = 0;
           BDBASEIRRFMENSAL = 0;
           BDVALORIRRFMENSAL = 0;
           BDINSSMENSAL = 0;
           BDAJCUSTOSMENSAL = 0;
           BDINDRESCMENSAL = 0;
           BDVALABOMENSAL = 0;
           BDRENDISENTOSMENSAL = 0;
           BDDRENDISENTOSMENSAL = '';
           BDAUXILIOMORADIAMENSAL = 0;
           BDDIARIAMENSAL = 0;
           BDTIPOFOLHA = 0;
           BDBOLSAMEDICOMENSAL = 0;
           BDJUROSMORAMENSAL = 0;
           BDTIPOCALCULO = 3;
           BDCODREC = '';
           BDCALCULOS = 0;
           bddescricaofolha = '';
           bdtagstr = '';
           SUSPEND;
        end

      WTEMINFOCALCULO = 0;

      WCODACCONV = 0;
      WCODACCONVANT = -1;
      WPRIMEIROREGADC = 0;
      WQTDMESESRRA = 0;

      for
        SELECT Q1.BDORDEM, Q1.BDCODEMP, Q1.BDCODCOL, Q1.bdref, Q1.BDTIPO, Q1.BDDIFERENCIADORDATE, Q1.BDDIFERENCIADORINTEGER, Q1.bdreffc, Q1.bddatapgto, Q1.BDREFPAG, Q1.BDRENDTRIBUTAVEL, Q1.BDIR, Q1.BDINSS, Q1.BDAJCUSTOS, Q1.BDINDRESC, Q1.BDVALABO, Q1.BDRENDISENTOS, Q1.BDDRENDISENTOS, Q1.BDAUXILIOMORADIA, Q1.BDDIARIA,
               Q1.BDBOLSAMEDICO, Q1.BDJUROSMORA, Q1.BDCALCULOS, Q1.BDINCIDESOCIAL, Q1.BDCODACCONV, Q1.BDCODFIR, Q1.BDMESESRRA
        FROM (SELECT FT.BDORDEM, FT.BDCODEMP, FT.BDCODCOL, FT.bdref, FT.BDTIPO, ft.bddatapgto BDDIFERENCIADORDATE, ft.bdrefpag BDDIFERENCIADORINTEGER, ft.bdreffc, ft.bddatapgto, FT.BDREFPAG, FT.BDRENDTRIBUTAVEL, FT.BDIR, FT.BDINSS, FT.BDAJCUSTOS, FT.BDINDRESC, FT.BDVALABO, FT.BDRENDISENTOS, FT.BDDRENDISENTOS, FT.BDAUXILIOMORADIA, FT.BDDIARIA,FT.BDBOLSAMEDICO, FT.BDJUROSMORA, 1 as BDCALCULOS, 0 BDINCIDESOCIAL, FT.BDCODACCONV, FT.BDCODFIR, FT.BDMESESRRA
              FROM SP_VRHF_DADOS_IR_FC_RRA('FOL.BDCODEMP = '||:PRCODEMP, 'FOL.BDCODCOL = '||:PRCODCOL, :PRREF, :PRREF, 0, '', 0, 0, 0, TRUE, FALSE, 1, FALSE, :prveiodototalizador) FT) Q1
        ORDER BY Q1.BDCODEMP, Q1.BDCODCOL, Q1.BDCODACCONV, Q1.BDREF
        into :WORDEM, :WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, :WREFFC, :WDATAPGTO, :WREFPAG, :WBASEIRRF, :WVALORIRRF, :WINSS, :WAJCUSTOS, :WINDRESC, :WVALABO, :WRENDISENTOS, :WDRENDISENTOS, :WAUXILIOMORADIA, :WDIARIA,:WBOLSAMEDICO, :WJUROSMORA, :WCALCULOS, :WINCIDESOCIAL, :WCODACCONV, :WCODFIR, :WQTDMESESRRA
      do
       begin
         if (COALESCE(WTIPOFOL, 0) >= 9000) then
            WDIFERENCIADORINTEGER = WCODFIR;

         if (COALESCE(WCODACCONVANT, -1) = -1 and COALESCE(WCODACCONV, 0) > 0) then
            begin
              WCODACCONVANT = WCODACCONV;
              WPRIMEIROREGADC = 1;
            end

         if ((PRSEPARAFOLHAS = 1) and (COALESCE(WCODACCONV, 0) <> COALESCE(WCODACCONVANT, 0)) and (WCODACCONVANT > 0)) then
            begin
              SUSPEND;
              bddescricaofolha = '';
              bdtagstr = '';

              BDBASEIRRFMENSAL = 0;
              BDVALORIRRFMENSAL = 0;
              BDINSSMENSAL = 0;
              BDAJCUSTOSMENSAL = 0;
              BDINDRESCMENSAL = 0;
              BDVALABOMENSAL = 0;
              BDRENDISENTOSMENSAL = 0;
              BDDRENDISENTOSMENSAL = '';
              BDAUXILIOMORADIAMENSAL = 0;
              BDDIARIAMENSAL = 0;
              BDTIPOFOLHA = 0;
              BDBOLSAMEDICOMENSAL = 0;
              BDJUROSMORAMENSAL = 0;
              BDTIPOCALCULO = 0;
              BDCODREC = '';
              WCODACCONVANT = WCODACCONV;

              WPRIMEIROREGADC = 0;
              if (coalesce(wcodacconv, 0) > 0) then
                 begin
                   select BDDESCRICAOCALCULO,BDTAGSTR from SP_RETORNA_TAGSTR_TOTALIZADORES(:WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, 1, :WINTERMITENTE, :WORDEM, :WFC)
                   into :bddescricaofolha,:bdtagstr;
                 end
            end
         else if (PRSEPARAFOLHAS = 1 and WPRIMEIROREGADC = 1) then
            begin
              select BDDESCRICAOCALCULO,BDTAGSTR from SP_RETORNA_TAGSTR_TOTALIZADORES(:WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, 1, :WINTERMITENTE, :WORDEM, :WFC) into :bddescricaofolha,:bdtagstr;
              WPRIMEIROREGADC = 0;
            end
          BDBASEIRRFMENSAL = BDBASEIRRFMENSAL + COALESCE(:WBASEIRRF, 0);
          BDVALORIRRFMENSAL = BDVALORIRRFMENSAL + COALESCE(:WVALORIRRF, 0);

          if (:WINSS > 0) then
             BDINSSMENSAL = BDINSSMENSAL + COALESCE(:WINSS, 0);

          BDCALCULOS = BDCALCULOS + COALESCE(:WCALCULOS, 0);
          BDAJCUSTOSMENSAL = BDAJCUSTOSMENSAL + COALESCE(:WAJCUSTOS, 0);
          BDINDRESCMENSAL = BDINDRESCMENSAL + COALESCE(:WINDRESC, 0);
          BDVALABOMENSAL = BDVALABOMENSAL + COALESCE(:WVALABO, 0);
          BDRENDISENTOSMENSAL = BDRENDISENTOSMENSAL + COALESCE(:WRENDISENTOS, 0);
          if (WDRENDISENTOS <> '') then
             begin
               if (BDDRENDISENTOSMENSAL <> '') then
                  begin
                    if (prveiodototalizador = 1) then
                       BDDRENDISENTOSMENSAL = BDDRENDISENTOSMENSAL||';';
                    else
                       BDDRENDISENTOSMENSAL = BDDRENDISENTOSMENSAL||', ';
                  end
               BDDRENDISENTOSMENSAL = BDDRENDISENTOSMENSAL||WDRENDISENTOS;
               if (prveiodototalizador = 1) then
                  BDDRENDISENTOSMENSAL = REPLACE(BDDRENDISENTOSMENSAL, ', ', ';');
             end
          BDAUXILIOMORADIAMENSAL = BDAUXILIOMORADIAMENSAL + COALESCE(:WAUXILIOMORADIA, 0);
          BDDIARIAMENSAL = BDDIARIAMENSAL + COALESCE(:WDIARIA, 0);
          BDBOLSAMEDICOMENSAL = BDBOLSAMEDICOMENSAL + COALESCE(:WBOLSAMEDICO, 0);
          BDJUROSMORAMENSAL = BDJUROSMORAMENSAL + COALESCE(:WJUROSMORA, 0);
          BDTIPOCALCULO = 4;
          BDTIPOFOLHA = WTIPOFOL;
          if (COALESCE(PRSEPARAFOLHAS, 0) = 1 and COALESCE(WCODACCONV, 0) = 0) then
             begin
                if (PRGRAVACODIGORECEITA = 0) then
                   select BDCODREC FROM sp_vrh_getcodreceita_5002(:WCODEMP,:WCODCOL,:prref,:PRTIPO,:bdtipofolha,:bdtipocalculo,:PRCODCLATRI) INTO :bdcodrec;
                -- Olhar o tipo de folha descrição e tagstr
                select BDDESCRICAOCALCULO,BDTAGSTR from SP_RETORNA_TAGSTR_TOTALIZADORES(:WCODEMP, :WCODCOL, :WREF, :WTIPOFOL, :WDIFERENCIADORDATE, :WDIFERENCIADORINTEGER, 1, 0, :WORDEM, 1) into :bddescricaofolha,:bdtagstr;
                execute procedure sp_vrhf_add_val_dep_pen_5002(:wcodemp,:wcodcol,null,:wref,wdiferenciadordate,wdiferenciadorinteger,4,wtipofol,wcodemp,:bdtagstr,:bddescricaofolha, WINCIDESOCIAL, 1, 4, wreffc, wdatapgto, wrefpag, 0, :prcodempord, 0, :PRREF,:bdcodrec);
                SUSPEND;
                bddescricaofolha = '';
                bdtagstr = '';
                WBASEIRRF = 0;
                WVALORIRRF = 0;
                WINSS = 0;
                WAJCUSTOS = 0;
                WINDRESC = 0;
                WVALABO = 0;
                WRENDISENTOS = 0;
                WDRENDISENTOS = '';
                WAUXILIOMORADIA = 0;
                WDIARIA = 0;
                WBOLSAMEDICO = 0;
                WJUROSMORA = 0;
                WCALCULOS = 0;

                BDBASEIRRFMENSAL = 0;
                BDVALORIRRFMENSAL = 0;
                BDINSSMENSAL = 0;
                BDAJCUSTOSMENSAL = 0;
                BDINDRESCMENSAL = 0;
                BDVALABOMENSAL = 0;
                BDRENDISENTOSMENSAL = 0;
                BDDRENDISENTOSMENSAL = '';
                BDAUXILIOMORADIAMENSAL = 0;
                BDDIARIAMENSAL = 0;
                BDTIPOFOLHA = 0;
                BDBOLSAMEDICOMENSAL = 0;
                BDJUROSMORAMENSAL = 0;
                BDTIPOCALCULO = 0;
                BDCODREC = '';
             end
          else
             begin
               if (PRGRAVACODIGORECEITA = 0) then
                  select BDCODREC FROM sp_vrh_getcodreceita_5002(:WCODEMP,:WCODCOL,:prref,:PRTIPO,:bdtipofolha,:bdtipocalculo,:PRCODCLATRI) INTO :bdcodrec;
               execute procedure sp_vrhf_add_val_dep_pen_5002(:wcodemp,:wcodcol,null,:wref,wdiferenciadordate,wdiferenciadorinteger,4,wtipofol,wcodemp,bdtagstr,bddescricaofolha, WINCIDESOCIAL, 1, 4, wreffc, wdatapgto, wrefpag, 0, :prcodempord, 0, :PRREF,:bdcodrec);
               execute procedure SP_REL_TOT_5002_RRA(:WCODEMP,:WCODCOL,:prref,1,:BDTAGSTR,:BDDESCRICAOFOLHA,:prcodempord,:wcodacconv,:wqtdmesesrra);
             end
          WTEMINFOCALCULO = 1;
       end
    if ( (COALESCE(PRSEPARAFOLHAS, 0) = 1) and (COALESCE(WCODACCONV, 0) <> 0) and (COALESCE(WCODACCONV, 0) = COALESCE(WCODACCONVANT, 0))) then
        begin
          SUSPEND;
          bddescricaofolha = '';
          bdtagstr = '';
          WBASEIRRF = 0;
          WVALORIRRF = 0;
          WINSS = 0;
          WAJCUSTOS = 0;
          WINDRESC = 0;
          WVALABO = 0;
          WRENDISENTOS = 0;
          WDRENDISENTOS = '';
          WAUXILIOMORADIA = 0;
          WDIARIA = 0;
          WBOLSAMEDICO = 0;
          WJUROSMORA = 0;
          WCALCULOS = 0;
          BDBASEIRRFMENSAL = 0;
          BDVALORIRRFMENSAL = 0;
          BDINSSMENSAL = 0;
          BDAJCUSTOSMENSAL = 0;
          BDINDRESCMENSAL = 0;
          BDVALABOMENSAL = 0;
          BDRENDISENTOSMENSAL = 0;
          BDDRENDISENTOSMENSAL = '';
          BDAUXILIOMORADIAMENSAL = 0;
          BDDIARIAMENSAL = 0;
          BDTIPOFOLHA = 0;
          BDBOLSAMEDICOMENSAL = 0;
          BDJUROSMORAMENSAL = 0;
          BDTIPOCALCULO = 0;
          BDCODREC = '';
        end
    else if ((COALESCE(PRSEPARAFOLHAS, 0) = 0) and (WTEMINFOCALCULO = 1)) then
       begin
          SUSPEND;
          bddescricaofolha = '';
          bdtagstr = '';
          WBASEIRRF = 0;
          WVALORIRRF = 0;
          WINSS = 0;
          WAJCUSTOS = 0;
          WINDRESC = 0;
          WVALABO = 0;
          WRENDISENTOS = 0;
          WDRENDISENTOS = '';
          WAUXILIOMORADIA = 0;
          WDIARIA = 0;
          WBOLSAMEDICO = 0;
          WJUROSMORA = 0;
          WCALCULOS = 0;

          BDBASEIRRFMENSAL = 0;
          BDVALORIRRFMENSAL = 0;
          BDINSSMENSAL = 0;
          BDAJCUSTOSMENSAL = 0;
          BDINDRESCMENSAL = 0;
          BDVALABOMENSAL = 0;
          BDRENDISENTOSMENSAL = 0;
          BDDRENDISENTOSMENSAL = '';
          BDAUXILIOMORADIAMENSAL = 0;
          BDDIARIAMENSAL = 0;
          BDTIPOFOLHA = 0;
          BDBOLSAMEDICOMENSAL = 0;
          BDJUROSMORAMENSAL = 0;
          BDTIPOCALCULO = 0;
          BDCODREC = '';
       end
    else if (WTEMINFOCALCULO = 0) then
        begin
           WBASEIRRF = 0;
           WVALORIRRF = 0;
           WINSS = 0;
           WAJCUSTOS = 0;
           WINDRESC = 0;
           WVALABO = 0;
           WRENDISENTOS = 0;
           WDRENDISENTOS = '';
           WAUXILIOMORADIA = 0;
           WDIARIA = 0;
           WBOLSAMEDICO = 0;
           WJUROSMORA = 0;
           WCALCULOS = 0;
           BDBASEIRRFMENSAL = 0;
           BDVALORIRRFMENSAL = 0;
           BDINSSMENSAL = 0;
           BDAJCUSTOSMENSAL = 0;
           BDINDRESCMENSAL = 0;
           BDVALABOMENSAL = 0;
           BDRENDISENTOSMENSAL = 0;
           BDDRENDISENTOSMENSAL = '';
           BDAUXILIOMORADIAMENSAL = 0;
           BDDIARIAMENSAL = 0;
           BDTIPOFOLHA = 0;
           BDBOLSAMEDICOMENSAL = 0;
           BDJUROSMORAMENSAL = 0;
           BDTIPOCALCULO = 4;
           BDCODREC = '';
           BDCALCULOS = 0;
           bddescricaofolha = '';
           bdtagstr = '';
           SUSPEND;
        end
    WTEMINFOCALCULO = 0;
  end
end^

create or alter procedure SP_RETORNA_BASE_IRRF_CONSOLID_ES (
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000),
    PRREF integer,
    PRREFFIM integer,
    PRTERCEIRO varchar(5),
    PRGRAVACODIGORECEITA integer = 0,
    PRCODCLA integer = 0,
    PRTRIBUTACAOEXTERIOR integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDINSSMENSALES numeric(18,6),
    BDBASEIRRFMENSALES numeric(18,6),
    BDVALORIRRFMENSALES numeric(18,6),
    BDAJCUSTOSMENSALES numeric(18,6),
    BDINDRESCMENSALES numeric(18,6),
    BDVALABOMENSALES numeric(18,6),
    BDRENDISENTOSMENSALES numeric(18,6),
    BDDRENDISENTOSMENSALES varchar(999),
    BDAUXILIOMORADIAMENSALES numeric(18,6),
    BDDIARIAMENSALES numeric(18,6),
    BDBOLSAMEDICOMENSALES numeric(18,6),
    BDJUROSMORAMENSALES numeric(18,6),
    BDTEMEVENTO integer,
    BDTIPOCALCULO integer)
as
declare variable WSQL varchar(1000);
declare variable WEVT integer;
declare variable WEVTANT integer;
declare variable WMATRIZ integer;
declare variable WTIPOCALCFIR integer;
declare variable WCRMEN varchar(6);
declare variable WBASEIRFIR numeric(18,6);
declare variable WVALINSSFIR numeric(18,6);
declare variable WVALIRFIR numeric(18,6);
declare variable WVALINDFIR numeric(18,6);
declare variable WAJUDACUSTOFIR numeric(18,6);
declare variable WRENDISENTOSFIR numeric(18,6);
declare variable WDESCRENDISENTOSFIR varchar(999);
declare variable WVALABOFIR numeric(18,6);
declare variable WAUXILIOMORADIAFIR numeric(18,6);
declare variable WDIARIAFIR numeric(18,6);
declare variable WBOLSAMEDICOFIR numeric(18,6);
declare variable WJUROSMORAFIR numeric(18,6);
declare variable WTIPOCALCULO integer;
declare variable WTIPOCALCULOANT integer;
declare variable WTEMTIPOCALCULO1 integer;
declare variable WTEMTIPOCALCULO2 integer;
declare variable WTEMTIPOCALCULO3 integer;
declare variable WTEMTIPOCALCULO4 integer;
declare variable WUSARTMP_EMP_SELECT integer;
declare variable WUSARTMP_COL_SELECT integer;
declare variable WCODEMP integer;
declare variable WCODEMPANT integer;
declare variable WCODCOL integer;
declare variable WCODCOLANT integer;
declare variable WREF integer;
declare variable WREFANT integer;
declare variable WCONTROLE varchar(20);
begin
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(:PRREF);

  BDBASEIRRFMENSALES = 0;
  BDINSSMENSALES = 0;
  BDVALORIRRFMENSALES = 0;
  BDAJCUSTOSMENSALES = 0;
  BDINDRESCMENSALES = 0;
  BDVALABOMENSALES = 0;
  BDRENDISENTOSMENSALES = 0;
  BDDRENDISENTOSMENSALES = '';
  BDAUXILIOMORADIAMENSALES = 0;
  BDDIARIAMENSALES = 0;
  BDBOLSAMEDICOMENSALES = 0;
  BDJUROSMORAMENSALES = 0;
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;
  IF (UPPER(prcodcol) = 'TEMP_FILTRO_COLCON_REL') THEN
     WUSARTMP_COL_SELECT = 1;

  BDTEMEVENTO = 0;

  BDTIPOCALCULO = 9999;

  update TEMP_FILTRO_COLCON_REL set bdcpf = '';

  wevtant = -1;

  if (prterceiro = 'FALSE') then -- Parâmetro passado dentro da "SP_REL_TOT_5002" com base nela é feita a consulta na tabela correta.
     begin
        wsql = 'select CP.BDCODEMP, CP.BDCODCOL, CP.bdrefevt, CP.BDCODEVT, CP.BDTIPOCALCFIR, CP.BDCRMEN, '||
               'CP.BDBASEIRFIR, CP.BDVALINSSFIR, CP.BDVALIRFIR, CP.BDVALINDFIR, CP.BDAJUDACUSTOFIR, '||
               'CP.BDRENDISENTOSFIR, CP.BDDESCRENDISENTOSFIR, '||
               'CP.BDVALABOFIR, CP.BDAUXILIOMORADIAFIR, CP.BDDIARIAFIR, CP.BDBOLSAMEDICOFIR, CP.BDJUROSMORAFIR, '||
               'CP.BDTIPOCALCULO '||
               'from VRH_ESOCIAL_CONSOLIDAPURMEN_C CP ';

        if (WUSARTMP_EMP_SELECT = 1) then
           wsql = wsql||' join TMP_EMPRESAS_SELECT TEMP on (CP.BDCODEMP = TEMP.BDCODEMP)'   ;

        if (WUSARTMP_COL_SELECT = 1) then
           wsql = wsql||' join TEMP_FILTRO_COLCON_REL FCOL on (CP.BDCODEMP = FCOL.BDCODEMP AND CP.BDCODCOL = FCOL.BDCODCOL)';

        wsql = wsql||' where CP.BDREFEVT >= '||prref||' and CP.BDREFEVT <= '||prreffim;

        if ((WUSARTMP_EMP_SELECT = 0) and (prcodemp <> '')) then
           wsql = wsql||' and '||replace(:prcodemp,'FOL.','CP.');

        if ((WUSARTMP_COL_SELECT = 0) and (prcodcol <> '')) then
           wsql = wsql||' and '||replace(:prcodcol,'FOL.','CP.');

        wsql = wsql||' order by CP.BDCODEMP, CP.BDCODCOL, CP.bdrefevt, CP.BDCODEVT desc, CP.BDTIPOCALCULO ';
     end
  else
     begin
        wsql = 'select CP.BDCODEMP, CP.BDCODTER, CP.bdrefevt, CP.BDCODEVT, CP.BDTIPOCALCFIR, CP.BDCRMEN, '||
               'CP.BDBASEIRFIR, CP.BDVALINSSFIR, CP.BDVALIRFIR, CP.BDVALINDFIR, CP.BDAJUDACUSTOFIR, '||
               'CP.BDRENDISENTOSFIR, CP.BDDESCRENDISENTOSFIR, '||
               'CP.BDVALABOFIR, CP.BDAUXILIOMORADIAFIR, CP.BDDIARIAFIR, CP.BDBOLSAMEDICOFIR, CP.BDJUROSMORAFIR, '||
               'CP.BDTIPOCALCULO '||
               'from VRH_ESOCIAL_CONSOLIDAPURMEN_C_TERC CP ';

        if (WUSARTMP_EMP_SELECT = 1) then
           wsql = wsql||' join TMP_EMPRESAS_SELECT TEMP on (CP.BDCODEMP = TEMP.BDCODEMP)'   ;

        if (WUSARTMP_COL_SELECT = 1) then
           wsql = wsql||' join TEMP_FILTRO_COLCON_REL FCOL on (CP.BDCODEMP = FCOL.BDCODEMP AND CP.BDCODTER = FCOL.BDCODTER)';

        wsql = wsql||' where CP.BDREFEVT >= '||prref||' and CP.BDREFEVT <= '||prreffim;

        if ((WUSARTMP_EMP_SELECT = 0) and (prcodemp <> '')) then
           wsql = wsql||' and '||replace(:prcodemp,'FOL.','CP.');

        if ((WUSARTMP_COL_SELECT = 0) and (prcodcol <> '')) then
           wsql = wsql||' and '||replace(:prcodcol,'FOL.BDCODCOL','CP.BDCODTER');

       wsql = wsql||' order by CP.BDCODEMP, CP.BDCODTER, CP.bdrefevt, CP.BDCODEVT desc, CP.BDTIPOCALCULO ';
     end

--  BDCODEMP = :PRCODEMP;
--  BDCODCOL = :PRCODCOL;

  WTIPOCALCULO = 0;
  WTIPOCALCULOANT = -1;
  WTEMTIPOCALCULO1 = 0;
  WTEMTIPOCALCULO2 = 0;
  WTEMTIPOCALCULO3 = 0;
  WTEMTIPOCALCULO4 = 0;
  wcodcolant = -1;
  wcodempant = -1;
  wrefant = -1;

  for execute statement wsql
  into :wcodemp,:wcodcol, :wref, :WEVT, :WTIPOCALCFIR, :WCRMEN,
       :WBASEIRFIR, :WVALINSSFIR, :WVALIRFIR, :WVALINDFIR, :WAJUDACUSTOFIR,
       :WRENDISENTOSFIR, :WDESCRENDISENTOSFIR,
       :WVALABOFIR, :WAUXILIOMORADIAFIR, :WDIARIAFIR, :WBOLSAMEDICOFIR, :WJUROSMORAFIR,
       :WTIPOCALCULO
  do
    begin
      BDTEMEVENTO = 1;

      if ((prtributacaoexterior > 0) and (F_IR_ISENTO_ESTRANGEIRO(prcodcla, prtributacaoexterior) = TRUE)) then
      begin
         WBASEIRFIR = 0;
         WVALIRFIR = 0;
      end

      if (wtipocalculoant = -1) then wtipocalculoant = wtipocalculo;
      if (wcodcolant = -1) then  wcodcolant = wcodcol;
      if (wcodempant = -1) then  wcodempant = wcodemp;
      if (wrefant = -1) then wrefant = wref;

      if ((WTIPOCALCULOANT <> WTIPOCALCULO) or (wcodcolant <> wcodcol) or (wcodempant <> wcodemp) or (wrefant <> wref)) then
         begin
            if (PRGRAVACODIGORECEITA = 1) then
               WCRMEN = '';

            if ((wcodcolant <> wcodcol) or (wcodempant <> wcodemp) or (wrefant <> wref)) then
               begin
                 if (prterceiro = 'FALSE') then
                    begin
                      execute procedure sp_vrhf_add_val_dep_pen_5002(:bdcodemp,:BDcodcol,null,:BDref,NULL,0,4,:wtipocalculoant,:bdcodemp,'','', 0, 2, 0, 0, null, 0, 0, :WMATRIZ, 0, :BDref,:WCRMEN);
                    end
                 ELSE
                    execute procedure sp_vrhf_add_val_dep_pen_5002(:bdcodemp,NULL,:BDcodcol,:BDref,NULL,0,4,:wtipocalculoant,:bdcodemp,'','', 0, 2, 0, 0, null, 0, 0, :WMATRIZ, 0, :BDref,:WCRMEN);
         
                 if (prterceiro = 'FALSE') then
                    begin
                      EXECUTE PROCEDURE SP_REL_TOT_5002_PLANSAU(:bdcodemp, :BDcodcol, :BDref, 2, '', '', :WMATRIZ, :BDref);
         
                      EXECUTE PROCEDURE SP_REL_TOT_5002_REEMBMED(:bdcodemp, :BDcodcol, :BDref, 2, '', '', :WMATRIZ, :BDref);
         
                      EXECUTE PROCEDURE SP_REL_TOT_5002_PREVIDCOMPL(:bdcodemp, :BDcodcol, :BDref, '', '', 2, :wtipocalculoant, :WMATRIZ, :BDref,:WCRMEN);
                    end
               end

           suspend;

           BDBASEIRRFMENSALES = 0;
           BDINSSMENSALES = 0;
           BDVALORIRRFMENSALES = 0;
           BDINDRESCMENSALES = 0;
           BDAJCUSTOSMENSALES = 0;
           BDRENDISENTOSMENSALES = 0;
           BDDRENDISENTOSMENSALES = '';
           BDVALABOMENSALES = 0;
           BDAUXILIOMORADIAMENSALES = 0;
           BDDIARIAMENSALES = 0;
           BDBOLSAMEDICOMENSALES = 0;
           BDJUROSMORAMENSALES = 0;
           BDTIPOCALCULO = 0;

           /*Se trocou colaborador */
           if ((wcodcolant <> wcodcol) or (wcodempant <> wcodemp) or (wrefant <> wref)) then
              begin
                wevtant = -1;
                if (WTEMTIPOCALCULO1 = 0) then
                   begin
                      BDTIPOCALCULO = 1;
                      if (prterceiro = 'TRUE') then
                         update TEMP_FILTRO_COLCON_REL set bdcpf = bdcpf||'1' where bdcodemp = :bdcodemp and bdcodter = :bdcodcol;
                      else
                         update TEMP_FILTRO_COLCON_REL set bdcpf = bdcpf||'1' where bdcodemp = :bdcodemp and bdcodcol = :bdcodcol;
                      SUSPEND;
                   end
             
                if (WTEMTIPOCALCULO2 = 0) then
                   begin
                      BDTIPOCALCULO = 2;
                      if (prterceiro = 'TRUE') then
                         update TEMP_FILTRO_COLCON_REL set bdcpf = bdcpf||'2' where bdcodemp = :bdcodemp and bdcodter = :bdcodcol;
                      else
                         update TEMP_FILTRO_COLCON_REL set bdcpf = bdcpf||'2' where bdcodemp = :bdcodemp and bdcodcol = :bdcodcol;
                      SUSPEND;
                   end
             
                if (WTEMTIPOCALCULO3 = 0) then
                   begin
                      if (prterceiro = 'TRUE') then
                         update TEMP_FILTRO_COLCON_REL set bdcpf = bdcpf||'3' where bdcodemp = :bdcodemp and bdcodter = :bdcodcol;
                      else
                         update TEMP_FILTRO_COLCON_REL set bdcpf = bdcpf||'3' where bdcodemp = :bdcodemp and bdcodcol = :bdcodcol;
                      BDTIPOCALCULO = 3;
                      SUSPEND;
                   end
             
                if (WTEMTIPOCALCULO4 = 0) then
                   begin
                      if (prterceiro = 'TRUE') then
                         update TEMP_FILTRO_COLCON_REL set bdcpf = bdcpf||'4' where bdcodemp = :bdcodemp and bdcodter = :bdcodcol;
                      else
                         update TEMP_FILTRO_COLCON_REL set bdcpf = bdcpf||'4' where bdcodemp = :bdcodemp and bdcodcol = :bdcodcol;
                      BDTIPOCALCULO = 4;
                      SUSPEND;
                   end

                WTEMTIPOCALCULO1 = 0;
                WTEMTIPOCALCULO2 = 0;
                WTEMTIPOCALCULO3 = 0;
                WTEMTIPOCALCULO4 = 0;
              end

           WTIPOCALCULOANT = WTIPOCALCULO;
         end

      if ((wcodempant <> wcodemp) or (wrefant <> wref) or (wmatriz is null) ) then
         begin
           select first 1 coalesce(bdcodmatriz,bdcodemp) from tempresas where bdcodemp = :wcodemp into :wmatriz;
         end

      wcodempant = wcodemp;
      wcodcolant = wcodcol;
      wrefant = wref;
      if (wevtant = -1) then
         wevtant = wevt;
      else if (wevt <> wevtant) then
         continue;

      BDBASEIRRFMENSALES = BDBASEIRRFMENSALES + COALESCE(WBASEIRFIR, 0);
      BDINSSMENSALES = BDINSSMENSALES + COALESCE(WVALINSSFIR, 0);
      BDVALORIRRFMENSALES = BDVALORIRRFMENSALES + COALESCE(WVALIRFIR, 0);
      BDINDRESCMENSALES = BDINDRESCMENSALES + COALESCE(WVALINDFIR, 0);
      BDAJCUSTOSMENSALES = BDAJCUSTOSMENSALES + COALESCE(WAJUDACUSTOFIR, 0);
      BDRENDISENTOSMENSALES = BDRENDISENTOSMENSALES + COALESCE(WRENDISENTOSFIR, 0);

      if (WDESCRENDISENTOSFIR <> '') then
         begin
            if (BDDRENDISENTOSMENSALES <> '') then
               BDDRENDISENTOSMENSALES = BDDRENDISENTOSMENSALES||',';

            BDDRENDISENTOSMENSALES = BDDRENDISENTOSMENSALES||WDESCRENDISENTOSFIR;
         end

      BDVALABOMENSALES = BDVALABOMENSALES + COALESCE(WVALABOFIR, 0);
      BDAUXILIOMORADIAMENSALES = BDAUXILIOMORADIAMENSALES + COALESCE(:WAUXILIOMORADIAFIR, 0);
      BDDIARIAMENSALES = BDDIARIAMENSALES + COALESCE(:WDIARIAFIR, 0);
      BDBOLSAMEDICOMENSALES = BDBOLSAMEDICOMENSALES + COALESCE(:WBOLSAMEDICOFIR, 0);
      BDJUROSMORAMENSALES = BDJUROSMORAMENSALES + COALESCE(:WJUROSMORAFIR, 0);

--      BDTIPOCALCULO = 1;
--      if (COALESCE(WTIPOCALCULO, 0) > 0) then
      BDTIPOCALCULO = WTIPOCALCULO;
      bdcodemp = wcodemp;
      bdcodcol = wcodcol;
      bdref = wref;

     if (BDTIPOCALCULO = 1) then
        WTEMTIPOCALCULO1 = 1;
     else if (BDTIPOCALCULO = 2) then
        WTEMTIPOCALCULO2 = 1;
     else if (BDTIPOCALCULO = 3) then
        WTEMTIPOCALCULO3 = 1;
     else if (BDTIPOCALCULO = 4) then
        WTEMTIPOCALCULO4 = 1;
   end

   bdcodemp = wcodemp;
   bdcodcol = wcodcol;
   bdref = wref;

   if (BDTEMEVENTO = 1) then
      begin
        if (PRGRAVACODIGORECEITA = 1) then
           WCRMEN = '';
 
        if ((wcodempant <> wcodemp) or (wrefant <> wref)) then
           begin
             select first 1 coalesce(bdcodmatriz,bdcodemp) from tempresas where bdcodemp = :bdcodemp into :wmatriz;
           end
 
        if (prterceiro = 'FALSE') then
           execute procedure sp_vrhf_add_val_dep_pen_5002(:bdcodemp,:BDcodcol,null,:BDref,NULL,0,4,:wtipocalculoant,:bdcodemp,'','', 0, 2, 0, 0, null, 0, 0, :WMATRIZ, 0, :BDref,:WCRMEN);
        ELSE
           execute procedure sp_vrhf_add_val_dep_pen_5002(:bdcodemp,NULL,:BDcodcol,:BDref,NULL,0,4,:wtipocalculoant,:bdcodemp,'','', 0, 2, 0, 0, null, 0, 0, :WMATRIZ, 0, :BDref,:WCRMEN);
 
        if (prterceiro = 'FALSE') then
           begin
             EXECUTE PROCEDURE SP_REL_TOT_5002_PLANSAU(:bdcodemp, :BDcodcol, :BDref, 2, '', '', :WMATRIZ, :BDref);
 
             EXECUTE PROCEDURE SP_REL_TOT_5002_REEMBMED(:bdcodemp, :BDcodcol, :BDref, 2, '', '', :WMATRIZ, :BDref);
 
             EXECUTE PROCEDURE SP_REL_TOT_5002_PREVIDCOMPL(:bdcodemp, :BDcodcol, :BDref, '', '', 2, :wtipocalculoant, :WMATRIZ, :BDref,:WCRMEN);
           end


        suspend;
      end

   BDBASEIRRFMENSALES = 0;
   BDINSSMENSALES = 0;
   BDVALORIRRFMENSALES = 0;
   BDINDRESCMENSALES = 0;
   BDAJCUSTOSMENSALES = 0;
   BDRENDISENTOSMENSALES = 0;
   BDDRENDISENTOSMENSALES = '';
   BDVALABOMENSALES = 0;
   BDAUXILIOMORADIAMENSALES = 0;
   BDDIARIAMENSALES = 0;
   BDBOLSAMEDICOMENSALES = 0;
   BDJUROSMORAMENSALES = 0;
   BDTIPOCALCULO = 0;

   WBASEIRFIR = 0;
   WVALINSSFIR = 0;
   WVALIRFIR = 0;
   WVALINDFIR = 0;
   WAJUDACUSTOFIR = 0;
   WRENDISENTOSFIR = 0;

   WDESCRENDISENTOSFIR = '';

   WVALABOFIR = 0;
   WAUXILIOMORADIAFIR = 0;
   WDIARIAFIR = 0;
   WBOLSAMEDICOFIR = 0;
   WJUROSMORAFIR = 0;

   WTIPOCALCULOANT = 0;
   WTIPOCALCULO = 0;
   bdref = prref;

   if (prterceiro = TRUE) then
      begin
        for select bdcodemp, bdcodter, BDCPF from TEMP_FILTRO_COLCON_REL into :bdcodemp,:bdcodcol,:wCONTROLE do
          begin
            if (position(wCONTROLE,'1') > 0) then
               begin
                 BDTIPOCALCULO = 1;
                 SUSPEND;
               end
            if (position(wCONTROLE,'2') > 0) then
               begin
                 BDTIPOCALCULO = 2;
                 SUSPEND;
               end
            if (position(wCONTROLE,'3') > 0) then
               begin
                 BDTIPOCALCULO = 3;
                 SUSPEND;
               end
            if (position(wCONTROLE,'4') > 0) then
               begin
                 BDTIPOCALCULO = 4;
                 SUSPEND;
               end
          end
      end
  else
      begin
        for select bdcodemp, bdcodcol, BDCPF from TEMP_FILTRO_COLCON_REL into :bdcodemp,:bdcodcol,:wCONTROLE do
          begin
            if (position(wCONTROLE,'1') > 0) then
               begin
                 BDTIPOCALCULO = 1;
                 SUSPEND;
               end
            if (position(wCONTROLE,'2') > 0) then
               begin
                 BDTIPOCALCULO = 2;
                 SUSPEND;
               end
            if (position(wCONTROLE,'3') > 0) then
               begin
                 BDTIPOCALCULO = 3;
                 SUSPEND;
               end
            if (position(wCONTROLE,'4') > 0) then
               begin
                 BDTIPOCALCULO = 4;
                 SUSPEND;
               end
          end
      end

end^

create or alter procedure SP_REL_TOT_5002 (
    PRCODEMP varchar(30000),
    PRREF integer,
    PRFILTROCPF varchar(30000),
    PRAUTONOMO boolean = false,
    PRPRVEIODOTOTALIZADOR integer = 0)
returns (
    BDCODEMPORD integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCOLTER integer,
    BDCONTRCOL integer,
    BDGRUPOCLA integer,
    BDNOMCOL varchar(70),
    BDCPFCOL varchar(18),
    BDCNPJEMP varchar(18),
    BDNOMEMP varchar(100),
    BDBASEIRRF numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDVALORINSS numeric(18,6),
    BDVRDEDDEP numeric(18,6),
    BDBASEPENSAO numeric(18,6),
    BDBASEPREV numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDVALORINSS13 numeric(18,6),
    BDVRDEDDEP13 numeric(18,6),
    BDBASEPENSAO13 numeric(18,6),
    BDBASEPREV13 numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDVALORINSSPLR numeric(18,6),
    BDVRDEDDEPPLR numeric(18,6),
    BDBASEPENSAOPLR numeric(18,6),
    BDBASEPREVPLR numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDVALORINSSRRA numeric(18,6),
    BDVRDEDDEPRRA numeric(18,6),
    BDBASEPENSAORRA numeric(18,6),
    BDBASEPREVRRA numeric(18,6),
    BDBASEIRRFES numeric(18,6),
    BDVALORIRRFES numeric(18,6),
    BDVALORINSSES numeric(18,6),
    BDVRDEDDEPES numeric(18,6),
    BDVRDEDDEPES13 numeric(18,6),
    BDBASEPENSAOES numeric(18,6),
    BDBASEPREVES numeric(18,6),
    BDBASEIRRF13ES numeric(18,6),
    BDVALORIRRF13ES numeric(18,6),
    BDVALORINSS13ES numeric(18,6),
    BDBASEPENSAO13ES numeric(18,6),
    BDBASEPREV13ES numeric(18,6),
    BDBASEIRRFPLRES numeric(18,6),
    BDVALORIRRFPLRES numeric(18,6),
    BDBASEPENSAOPLRES numeric(18,6),
    BDBASEIRRFRRAES numeric(18,6),
    BDVALORIRRFRRAES numeric(18,6),
    BDBASEPENSAORRAES numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSSES numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEINSS13ES numeric(18,6),
    BDVALORSALFAM numeric(18,6),
    BDVALORSALFAMES numeric(18,6),
    BDVALORSALMATEMP numeric(18,6),
    BDVALORSALMATEMPES numeric(18,6),
    BDVRCPSEG numeric(18,6),
    BDVALORIRRFFERIAS numeric(18,6),
    BDVALORIRRFFERIASES numeric(18,6),
    BDBASEIRRFFERIAS numeric(18,6),
    BDBASEIRRFFERIASES numeric(18,6),
    BDBASEFGTS numeric(18,6),
    BDBASEFGTSES numeric(18,6),
    BDVALORFGTS numeric(18,6),
    BDVALORFGTSES numeric(18,6),
    BDBASEFGTSRES numeric(18,6),
    BDBASEFGTSRESES numeric(18,6),
    BDVALORFGTSRES numeric(18,6),
    BDVALORFGTSRESES numeric(18,6),
    BDBASEAVPREV numeric(18,6),
    BDBASEAVPREVES numeric(18,6),
    BDVALORAVPREV numeric(18,6),
    BDVALORAVPREVES numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDBASEFGTS13ES numeric(18,6),
    BDVALORFGTS13 numeric(18,6),
    BDVALORFGTS13ES numeric(18,6),
    BDVRDEDDEPPLRES numeric(18,6),
    BDVRDEDDEPRRAES numeric(18,6),
    BDVALORINSSRRAES numeric(18,6),
    BDTIPO integer,
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDCATEGORIAESOCIAL integer,
    BDCODCLATRI integer,
    BDSEST integer,
    BDSENAT integer,
    BDSESTES integer,
    BDSENATES integer,
    BDCTS5001 integer,
    BDBASEFGTS13RESC numeric(9,2),
    BDBASEFGTS13RESCES numeric(9,2),
    BDVALORFGTS13RESC numeric(9,2),
    BDVALORFGTS13RESCES numeric(9,2),
    BDECONSIGNADO numeric(18,6),
    BDECONSIGNADORESC numeric(18,6),
    BDINSTITUICAOFINANC integer,
    BDNROCONTRATOECONSIGNADO varchar(30),
    BDINSTITUICAOFINANCES integer,
    BDNROCONTRATOECONSIGNADOES varchar(30),
    BDVALORECONSIGNADOES numeric(18,6),
    BDIND13PISES integer,
    BDTPVALORPISPASEPES integer,
    BDVALORPISPASEPES numeric(18,6),
    BDVALORPISPASEP13ES numeric(18,6),
    BDVALORPISPASEP numeric(18,6),
    BDVALORPISPASEP13 numeric(18,6),
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000))
as
declare variable WSQLPRINCIPAL varchar(30000);
declare variable WEMPCARREGADA integer;
declare variable WCPFANTERIOR varchar(18);
declare variable WCODMATRIZ integer;
declare variable WCNPJEMP varchar(18);
declare variable WCODEMP integer;
declare variable WLISTAEMP varchar(30000);
declare variable WNOMEMP varchar(100);
declare variable WCODCOL integer;
declare variable WNOMCOL varchar(100);
declare variable WCPFCOL varchar(18);
declare variable WCONTRCOL integer;
declare variable WULTDIA varchar(2);
declare variable WMES smallint;
declare variable WANO integer;
declare variable WCATESOCIAL integer;
declare variable WCODCLATRI integer;
declare variable WGRUPOCLA integer;
declare variable WVALORINSSES numeric(18,6);
declare variable WVALORINSS13ES numeric(18,6);
declare variable WVRDEDDEPES numeric(18,6);
declare variable WVRDEDDEP13ES numeric(18,6);
declare variable WBASEIRRFES numeric(18,6);
declare variable WBASEIRRF13ES numeric(18,6);
declare variable WBASEIRRFPLRES numeric(18,6);
declare variable WBASEIRRFRRAES numeric(18,6);
declare variable WBASEPREVES numeric(18,6);
declare variable WBASEPREV13ES numeric(18,6);
declare variable WBASEPENSAOES numeric(18,6);
declare variable WBASEPENSAO13ES numeric(18,6);
declare variable WBASEPENSAOPLRES numeric(18,6);
declare variable WBASEPENSAORRAES numeric(18,6);
declare variable WVALORIRRFES numeric(18,6);
declare variable WVALORIRRF13ES numeric(18,6);
declare variable WVALORIRRFPLRES numeric(18,6);
declare variable WVALORIRRFRRAES numeric(18,6);
declare variable WBASEIRRF numeric(18,6);
declare variable WVALORIRRF numeric(18,6);
declare variable WVALORINSS numeric(18,6);
declare variable WVRDEDDEP numeric(18,6);
declare variable WBASEPENSAO numeric(18,6);
declare variable WBASEPREV numeric(18,6);
declare variable WBASEIRRF13 numeric(18,6);
declare variable WVALORIRRF13 numeric(18,6);
declare variable WVALORINSS13 numeric(18,6);
declare variable WVRDEDDEP13 numeric(18,6);
declare variable WBASEPENSAO13 numeric(18,6);
declare variable WBASEPREV13 numeric(18,6);
declare variable WBASEIRRFPLR numeric(18,6);
declare variable WVALORIRRFPLR numeric(18,6);
declare variable WVALORINSSPLR numeric(18,6);
declare variable WVRDEDDEPPLR numeric(18,6);
declare variable WBASEPENSAOPLR numeric(18,6);
declare variable WBASEPREVPLR numeric(18,6);
declare variable WBASEIRRFRRA numeric(18,6);
declare variable WVALORIRRFRRA numeric(18,6);
declare variable WVALORINSSRRA numeric(18,6);
declare variable WVRDEDDEPRRA numeric(18,6);
declare variable WBASEPENSAORRA numeric(18,6);
declare variable WBASEPREVRRA numeric(18,6);
declare variable WVRDEDDEPPLRES numeric(18,6);
declare variable WVRDEDDEPRRAES numeric(18,6);
declare variable WVALORINSSRRAES numeric(18,6);
declare variable WTEMEVENTO integer;
declare variable WTEMCALCFN integer;
declare variable WCALCULOS integer;
declare variable WTEMCALCFT integer;
declare variable WCODCOLANT integer;
declare variable WREFEMP integer;
begin
  BDCODEMPORD = 0;
  BDCODEMP = 0;
  BDCODCOL = 0;
  BDCOLTER = 0;
  BDCONTRCOL = 0;
  BDGRUPOCLA = 0;
  BDNOMCOL =  '';
  BDCPFCOL =  '';
  BDCNPJEMP = '';
  BDNOMEMP =  '';

  BDBASEIRRF = 0;
  BDVALORIRRF = 0;
  BDVALORINSS = 0;
  BDVRDEDDEP = 0;
  BDBASEPENSAO = 0;
  BDBASEPREV = 0;

  BDBASEIRRF13 = 0;
  BDVALORIRRF13 = 0;
  BDVALORINSS13 = 0;
  BDVRDEDDEP13 = 0;
  BDBASEPENSAO13 = 0;
  BDBASEPREV13 = 0;

  BDBASEIRRFPLR = 0;
  BDVALORIRRFPLR = 0;
  BDVALORINSSPLR = 0;
  BDVRDEDDEPPLR = 0;
  BDBASEPENSAOPLR = 0;
  BDBASEPREVPLR = 0;

  BDBASEIRRFRRA = 0;
  BDVALORIRRFRRA = 0;
  BDVALORINSSRRA = 0;
  BDVRDEDDEPRRA = 0;
  BDBASEPENSAORRA = 0;
  BDBASEPREVRRA = 0;


  BDBASEIRRFES = 0;
  BDVALORIRRFES = 0;
  BDVALORINSSES = 0;
  BDVRDEDDEPES = 0;
  BDBASEPENSAOES = 0;
  BDBASEPREVES = 0;

  BDBASEIRRF13ES = 0;
  BDVALORIRRF13ES = 0;
  BDVALORINSS13ES = 0;
  BDBASEPENSAO13ES = 0;
  BDBASEPREV13ES = 0;

  BDBASEIRRFPLRES = 0;
  BDVALORIRRFPLRES = 0;
  BDBASEPENSAOPLRES = 0;

  BDBASEIRRFRRAES = 0;
  BDVALORIRRFRRAES = 0;
  BDBASEPENSAORRAES = 0;

  BDBASEINSS = 0;
  BDBASEINSSES = 0;
  BDBASEINSS13 = 0;
  BDBASEINSS13ES = 0;
  BDVALORSALFAM = 0;
  BDVALORSALFAMES = 0;
  BDVALORSALMATEMP = 0;
  BDVALORSALMATEMPES = 0;
  BDVRCPSEG = 0;
  BDVALORIRRFFERIAS = 0;
  BDVALORIRRFFERIASES = 0;
  BDBASEIRRFFERIAS = 0;
  BDBASEIRRFFERIASES = 0;
  BDBASEFGTS = 0;
  BDBASEFGTSES = 0;
  BDVALORFGTS = 0;
  BDVALORFGTSES = 0;
  BDBASEFGTSRES = 0;
  BDBASEFGTSRESES = 0;
  BDVALORFGTSRES = 0;
  BDVALORFGTSRESES = 0;
  BDBASEFGTS13RESC = 0;
  BDBASEFGTS13RESCES = 0;
  BDVALORFGTS13RESC = 0;
  BDVALORFGTS13RESCES = 0;

  --#206247 - Início - É preciso criar os campos com valores zero pois somente é feito o select all da SP para a emissão do relatório;
  BDECONSIGNADO              = 0;
  BDECONSIGNADORESC          = 0;
  BDINSTITUICAOFINANC        = 0;
  BDNROCONTRATOECONSIGNADO   = 'só no S-5003';
  BDINSTITUICAOFINANCES      = 0;
  BDNROCONTRATOECONSIGNADOES = 'só no S-5003';
  BDVALORECONSIGNADOES       = 0;
  --#206247 - Fim;

  --#206764 - Início - É preciso criar os campos com valores zero pois somente é feito o select all da SP para a emissão do relatório;
  BDIND13PISES = 0;
  BDTPVALORPISPASEPES = 0;
  BDVALORPISPASEPES = 0;
  BDVALORPISPASEP13ES = 0;
  BDVALORPISPASEP = 0;
  BDVALORPISPASEP13 = 0;
  BDTAGSTR = '';
  BDDESCRICAOFOLHA = '';
  --#206764 - Fim;

  BDBASEAVPREV = 0;
  BDBASEAVPREVES = 0;
  BDVALORAVPREV = 0;
  BDVALORAVPREVES = 0;
  BDBASEFGTS13 = 0;
  BDBASEFGTS13ES = 0;
  BDVALORFGTS13 = 0;
  BDVALORFGTS13ES = 0;
  BDCALCULOS = 0;
  BDTIPO = 5002;
  WSQLPRINCIPAL = '';

  if (PRAUTONOMO = FALSE) then
    begin
      BDCOLTER = 1;
      WSQLPRINCIPAL = WSQLPRINCIPAL||'SELECT COALESCE(E.BDCODMATRIZ, COL.BDCODEMP) BDCODMATRIZ, E.BDCNPJEMP, EREF.BDNOMEMP ,COL.BDCODEMP,COL.BDCODCOL, COL.BDCPFCOL, COLCAD.BDNOMCOL, COL.BDCONTRCOL, EREF.BDREFEMP ' ||
                      ' FROM VRH_EMP_TCOLCON COL ' ||
                      ' INNER JOIN TEMPRESAS E ON E.BDCODEMP = COL.BDCODEMP ' ||
                      ' inner join TEMPRESAS_REF EREF on EREF.BDCODEMP = E.BDCODEMP and EREF.BDREFEMP = (select max(BDREFEMP) from TEMPRESAS_REF WHERE BDCODEMP = E.BDCODEMP)' ||
                      ' inner join VRH_EMP_TCOLCON_CAD COLCAD on COLCAD.BDCODEMP = COL.BDCODEMP and COLCAD.BDCODCOL = COL.BDCODCOL and COLCAD.BDREFCOL = (select max(BDREFCOL) from VRH_EMP_TCOLCON_CAD WHERE BDCODEMP = COL.BDCODEMP and BDCODCOL = COL.BDCODCOL and BDREFCOL <= '||PRREF||')' ||
                      ' where UPPER(E.BDEXPINIESOCIAL) = ' || '''' || 'TRUE' || '''';


      if ((PRCODEMP is not null) and (PRCODEMP <> '')) then
        begin
          WSQLPRINCIPAL = WSQLPRINCIPAL ||' and (not exists(select DOC.BDCODEMP '||
                                                           'from VRH_EMP_TCON_DOC DOC '||
                                                           'where (DOC.BDCODEMP = COLCAD.BDCODEMP) and '||
                                                           '(DOC.BDCODCOL = COLCAD.BDCODCOL) and '||
                                                           '(DOC.BDDATABAIXACOL < '''|| substring(cast(PRREF as varchar(6)) from 1 for 4)||'/'||substring(cast(PRREF as varchar(6)) from 5 for 2)||'/01'''|| '))) '||
                                     'and ((not exists(select RESC.BDCODEMP '||
                                                    'from VRH_EMP_TRESCISAO RESC '||
                                                    'where (RESC.BDCODEMP = COLCAD.BDCODEMP) and '||
                                                    '(RESC.BDCODCOL = COLCAD.BDCODCOL) and '||
                                                    '(RESC.BDDATAPAGRESCISAO < '''|| substring(cast(PRREF as varchar(6)) from 1 for 4)||'/'||substring(cast(PRREF as varchar(6)) from 5 for 2)||'/01'''||')))'||
                                     '       or (exists(select fc.bdcodemp '||
                                                      'from VRHF_EMP_TFOLHACOMP fc '||
                                                      'where fc.BDCODEMP = COLCAD.BDCODEMP and '||
                                                      'fc.BDCODCOL = COLCAD.BDCODCOL and '||
                                                      'fc.BDREFIRRFESOCIAL = '|| PRREF ||'))'||
                                      '       or (exists(select fc.bdcodemp '||
                                                      'from VRHF_EMP_TFOLHACOMPINT fc '||
                                                      'where fc.BDCODEMP = COLCAD.BDCODEMP and '||
                                                      'fc.BDCODCOL = COLCAD.BDCODCOL and '||
                                                      'fc.BDREFIRRFESOCIAL = '|| PRREF ||'))'||
                                      '       or (exists(select fc.bdcodemp '||
                                                      'from VRHF_EMP_TFOLTOMCOMP fc '||
                                                      'where fc.BDCODEMP = COLCAD.BDCODEMP and '||
                                                      'fc.BDCODCOL = COLCAD.BDCODCOL and '||
                                                      'fc.BDREFIRRFESOCIAL = '|| PRREF ||'))'||
                                      '       or (exists(select fc.bdcodemp '||
                                                      'from VRHF_EMP_TFOLTOMCOMPINT fc '||
                                                      'where fc.BDCODEMP = COLCAD.BDCODEMP and '||
                                                      'fc.BDCODCOL = COLCAD.BDCODCOL and '||
                                                      'fc.BDREFIRRFESOCIAL = '|| PRREF ||')))';

          if (position('=', PRCODEMP) > 0) then
            WLISTAEMP = SUBSTRING(PRCODEMP from position('=', PRCODEMP)+1 for CHAR_LENGTH(PRCODEMP));
          if (position('in', PRCODEMP) > 0) then
            WLISTAEMP = SUBSTRING(PRCODEMP from position('in', PRCODEMP)+2 for CHAR_LENGTH(PRCODEMP));

          if (position('(', WLISTAEMP) > 0) then
            WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ((E.BDCODMATRIZ in ' || WLISTAEMP || ') OR (COL.BDCODEMP in ' || WLISTAEMP || '))';
          else
            WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ((E.BDCODMATRIZ in (' || WLISTAEMP || ')) OR (COL.BDCODEMP in (' || WLISTAEMP || ')))';
        end

      if ((PRREF is not null) and (PRREF <> 0)) then
        begin
          WMES = cast(substring(cast(PRREF as varchar(6)) from 5 for 2) as integer);
          WANO = cast(substring(cast(PRREF as varchar(6)) from 1 for 4) as integer);
          select ULTDIA from ULTIMO_DIA_MES(:WMES, :WANO) into WULTDIA;
          WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND (COL.BDDATAADMCOL <=''' || substring(cast(PRREF as varchar(6)) from 5 for 2) || '/' || WULTDIA || '/' || substring(cast(PRREF as varchar(6)) from 1 for 4) || ''')';
        end

      if ((PRFILTROCPF is not null) and (PRFILTROCPF <> '')) then
        WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ' ||PRFILTROCPF;
    END

  if (PRAUTONOMO = TRUE) then
    BEGIN
      BDCOLTER = 2;
      if (WSQLPRINCIPAL <> '') then
         WSQLPRINCIPAL = WSQLPRINCIPAL ||'UNION ';
      WLISTAEMP = '';

      if (position('=', PRCODEMP) > 0) then
        WLISTAEMP = '=' || SUBSTRING(PRCODEMP from position('=', PRCODEMP)+1 for CHAR_LENGTH(PRCODEMP));
      if (position('in', PRCODEMP) > 0) then
        WLISTAEMP = 'in' || SUBSTRING(PRCODEMP from position('in', PRCODEMP)+2 for CHAR_LENGTH(PRCODEMP));

      WSQLPRINCIPAL = WSQLPRINCIPAL ||'SELECT COALESCE(EMP.BDCODMATRIZ, TERC.BDCODEMP) BDCODMATRIZ, EMP.BDCNPJEMP, EREF.BDNOMEMP, TERC.BDCODEMP, TER.BDCODTER,'||
                                      'TER.BDCGCTER, TRF.BDNOMETER, 0 BDCONTRCOL, TRF.BDREFEMP '||
                                      'FROM TTERCEIRO TER '||
                                      'INNER JOIN TTERCEIRO_REF TRF ON TRF.BDCODTER = TER.BDCODTER AND TRF.BDREFEMP = (SELECT MAX(TRF1.BDREFEMP) FROM TTERCEIRO_REF TRF1 WHERE TRF1.BDCODTER = TRF.BDCODTER AND TRF1.BDREFEMP <= '|| PRREF ||') '||
                                      'INNER JOIN(SELECT TERC.BDCODEMP, TERC.BDCODTER, SUM(TERC.BDBASEINSS) BDBASEINSS, SUM(TERC.BDVALORINSS) BDVALORINSS'||
                                      '           FROM VRHF_BASE_CALC_TERC TERC '||
                                      '           INNER JOIN TEMPRESAS E ON E.BDCODEMP = TERC.BDCODEMP AND '||
                                      '                                    UPPER(E.BDEXPINIESOCIAL) = ''TRUE'''||
                                      '           WHERE ((SELECT BDDATA FROM SP_PARSE_DATE(TERC.BDDATASERV, ''YYYYMM'')) = '|| PRREF ||') AND'||
                                      '                 (coalesce(E.BDCODMATRIZ, E.BDCODEMP)  ' || WLISTAEMP || ') '||
                                      '           GROUP BY TERC.BDCODEMP, TERC.BDCODTER) TERC ON TERC.BDCODTER = TER.BDCODTER '||
                                      'INNER JOIN TEMPRESAS EMP ON EMP.BDCODEMP = TERC.BDCODEMP '||
                                      'INNER JOIN TEMPRESAS_REF EREF ON EREF.BDCODEMP = EMP.BDCODEMP AND EREF.BDREFEMP = (SELECT MAX(BDREFEMP) '||
                                      '                                                                                   FROM TEMPRESAS_REF '||
                                      '                                                                                  WHERE BDCODEMP = EMP.BDCODEMP) '||
                                      'WHERE UPPER(EMP.BDEXPINIESOCIAL) = ''TRUE'' ';

      if (position('=', WLISTAEMP) > 0) then
        WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ((EMP.BDCODMATRIZ  ' || WLISTAEMP || ') OR (TERC.BDCODEMP  ' || WLISTAEMP || '))';
      else
        WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ((EMP.BDCODMATRIZ  ' || WLISTAEMP || ') OR (TERC.BDCODEMP  ' || WLISTAEMP || '))';

      if ((PRREF is not null) and (PRREF <> 0)) then
        begin
          WMES = cast(substring(cast(PRREF as varchar(6)) from 5 for 2) as integer);
          WANO = cast(substring(cast(PRREF as varchar(6)) from 1 for 4) as integer);
          select ULTDIA from ULTIMO_DIA_MES(:WMES, :WANO) into WULTDIA;
          WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND (TRF.BDDATACADTER <=''' || substring(cast(PRREF as varchar(6)) from 5 for 2) || '/' || WULTDIA || '/' || substring(cast(PRREF as varchar(6)) from 1 for 4) || ''')';
        end

      if ((PRFILTROCPF is not null) and (PRFILTROCPF <> '')) then
        WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ' ||PRFILTROCPF;
    END

  WEMPCARREGADA = 0;
  WCPFANTERIOR = '';

  WSQLPRINCIPAL = WSQLPRINCIPAL || ' ORDER BY 1, 6, 5, 9 DESC ';

  for execute statement WSQLPRINCIPAL
      into :WCODMATRIZ, :WCNPJEMP, :WNOMEMP, :WCODEMP, :WCODCOL, :WCPFCOL, :WNOMCOL, :WCONTRCOL, :WREFEMP
  do
  begin
    if ((WCPFANTERIOR <> WCPFCOL) or ((WCPFANTERIOR = WCPFCOL) and (WEMPCARREGADA <> WCODEMP)) or ((WCPFANTERIOR = WCPFCOL)))  then
      begin
        if ((WCPFANTERIOR <> '') and ((WTEMEVENTO > 0) or (WTEMCALCFN > 0) or (WTEMCALCFT > 0))) then
          suspend;

          WCPFANTERIOR = WCPFCOL;
          WEMPCARREGADA = WCODEMP;
          WCODCOLANT = WCODCOL;
          BDCALCULOS = 0;
          BDBASEIRRF = 0;
          BDVALORIRRF = 0;
          BDVALORINSS = 0;
          BDVRDEDDEP = 0;
          BDBASEPENSAO = 0;
          BDBASEPREV = 0;

          BDBASEIRRF13 = 0;
          BDVALORIRRF13 = 0;
          BDVALORINSS13 = 0;
          BDVRDEDDEP13 = 0;
          BDBASEPENSAO13 = 0;
          BDBASEPREV13 = 0;

          BDBASEIRRFPLR = 0;
          BDVALORIRRFPLR = 0;
          BDVALORINSSPLR = 0;
          BDVRDEDDEPPLR = 0;
          BDBASEPENSAOPLR = 0;
          BDBASEPREVPLR = 0;

          BDBASEIRRFRRA = 0;
          BDVALORIRRFRRA = 0;
          BDVALORINSSRRA = 0;
          BDVRDEDDEPRRA = 0;
          BDBASEPENSAORRA = 0;
          BDBASEPREVRRA = 0;


          BDBASEIRRFES = 0;
          BDVALORIRRFES = 0;
          BDVALORINSSES = 0;
          BDVRDEDDEPES = 0;
          BDBASEPENSAOES = 0;
          BDBASEPREVES = 0;

          BDBASEIRRF13ES = 0;
          BDVALORIRRF13ES = 0;
          BDVALORINSS13ES = 0;
          BDBASEPENSAO13ES = 0;
          BDBASEPREV13ES = 0;
          BDVRDEDDEPES13 = 0;


          BDBASEIRRFPLRES = 0;
          BDVALORIRRFPLRES = 0;
          BDBASEPENSAOPLRES = 0;

          BDBASEIRRFRRAES = 0;
          BDVALORIRRFRRAES = 0;
          BDBASEPENSAORRAES = 0;
          BDVRDEDDEPPLRES = 0;
          BDVRDEDDEPRRAES = 0;
          BDVALORINSSRRAES = 0;


          WBASEIRRF = 0;
          WVALORIRRF = 0;
          WVALORINSS = 0;
          WVRDEDDEP = 0;
          WBASEPENSAO = 0;
          WBASEPREV = 0;

          WBASEIRRF13 = 0;
          WVALORIRRF13 = 0;
          WVALORINSS13 = 0;
          WVRDEDDEP13 = 0;
          WBASEPENSAO13 = 0;
          WBASEPREV13 = 0;
          WVRDEDDEP13ES = 0;

          WBASEIRRFPLR = 0;
          WVALORIRRFPLR = 0;
          WVALORINSSPLR = 0;
          WVRDEDDEPPLR = 0;
          WBASEPENSAOPLR = 0;
          WBASEPREVPLR = 0;

          WBASEIRRFRRA = 0;
          WVALORIRRFRRA = 0;
          WVALORINSSRRA = 0;
          WVRDEDDEPRRA = 0;
          WBASEPENSAORRA = 0;
          WBASEPREVRRA = 0;


          WBASEIRRFES = 0;
          WVALORIRRFES = 0;
          WVALORINSSES = 0;
          WVRDEDDEPES = 0;
          WBASEPENSAOES = 0;
          WBASEPREVES = 0;

          WBASEIRRF13ES = 0;
          WVALORIRRF13ES = 0;
          WVALORINSS13ES = 0;
          WBASEPENSAO13ES = 0;
          WBASEPREV13ES = 0;

          WBASEIRRFPLRES = 0;
          WVALORIRRFPLRES = 0;
          WBASEPENSAOPLRES = 0;

          WBASEIRRFRRAES = 0;
          WVALORIRRFRRAES = 0;
          WBASEPENSAORRAES = 0;

          WVRDEDDEPPLRES = 0;
          WVRDEDDEPRRAES = 0;
          WVALORINSSRRAES = 0;


          WCALCULOS = 0;
      end

    select BDBASEIRRFMENSAL, BDVALORIRRFMENSAL, BDINSSMENSAL, BDDEPMENSAL, BDPENSAOMENSAL, BDPREVMENSAL, BDBASEIRRF13,
         BDVALORIRRF13, BDINSS13, BDDEP13, BDPENSAO13, BDPREV13, BDBASEIRRFPLR, BDVALORIRRFPLR, BDINSSPLR, BDDEPPLR,
         BDPENSAOPLR, BDPREVPLR, BDBASEIRRFRRA, BDVALORIRRFRRA, BDINSSRRA, BDDEPRRA, BDPENSAORRA, BDPREVRRA, BDCALCULOS
    from SP_RETORNA_BASE_IRRF(:WCODEMP, :WCODCOL, :PRREF, :BDCOLTER, :PRPRVEIODOTOTALIZADOR)
    into :WBASEIRRF, :WVALORIRRF, :WVALORINSS, :WVRDEDDEP, :WBASEPENSAO, :WBASEPREV, :WBASEIRRF13,
         :WVALORIRRF13, :WVALORINSS13, :WVRDEDDEP13, :WBASEPENSAO13, :WBASEPREV13, :WBASEIRRFPLR, :WVALORIRRFPLR, :WVALORINSSPLR, :WVRDEDDEPPLR,
         :WBASEPENSAOPLR, :WBASEPREVPLR, :WBASEIRRFRRA, :WVALORIRRFRRA, :WVALORINSSRRA, :WVRDEDDEPRRA, :WBASEPENSAORRA, :WBASEPREVRRA, :WCALCULOS;

    select BDBASEIRRFMENSALES, BDVALORIRRFMENSALES, BDINSSMENSALES, BDDEPES, BDPENSAOMENSALES, BDPREVMENSALES,
         BDBASEIRRF13ES, BDVALORIRRF13ES, BDINSS13ES, BDDEP13ES, BDPENSAO13ES, BDPREV13ES, BDBASEIRRFPLRES, BDVALORIRRFPLRES,
         BDPENSAOPLRES, BDBASEIRRFRRAES, BDVALORIRRFRRAES, BDPENSAORRAES, BDDEPPLRES, BDDEPRRAES, BDINSSRRAES
    from SP_RETORNA_BASE_IRRF_ES(:WCODEMP, :WCODCOL, :PRREF, :prautonomo)
    into :WBASEIRRFES, :WVALORIRRFES, :WVALORINSSES, :WVRDEDDEPES, :WBASEPENSAOES, :WBASEPREVES,
         :WBASEIRRF13ES, :WVALORIRRF13ES, :WVALORINSS13ES, :WVRDEDDEP13ES, :WBASEPENSAO13ES, :WBASEPREV13ES, :WBASEIRRFPLRES, :WVALORIRRFPLRES,
         :WBASEPENSAOPLRES, :WBASEIRRFRRAES, :WVALORIRRFRRAES, :WBASEPENSAORRAES, :WVRDEDDEPPLRES, :WVRDEDDEPRRAES, :WVALORINSSRRAES;


    select first 1 FGTS.BDCATEGORIAESOCIAL, CLA.BDGRUPOCLA
    from VRHF_EMP_TCOLCON_FGTSGPS FGTS
    left outer join VRH_EMP_TCOLCON_VINC VINC on VINC.BDCODEMP = :WCODEMP and VINC.BDCODCOL = :WCODCOL and VINC.BDREFCOL <= :PRREF
    left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
    where FGTS.BDCODEMP in (:WCODEMP) and
          FGTS.BDCODCOL = :WCODCOL and
          (FGTS.BDREFCOL <= :PRREF)
    order by FGTS.BDREFCOL desc
    into :WCATESOCIAL, :WGRUPOCLA;

    select first 1 BDCODCLATRI
    from VRHF_BASE_TEMPESOCIAL ES
    where ES.BDCODEMP in (:WCODEMP) and
                    (ES.BDREFEMP <= :PRREF)
    order by BDREFEMP desc
    into :WCODCLATRI;

    BDBASEIRRF = BDBASEIRRF + COALESCE(WBASEIRRF, 0);
    BDVALORIRRF = BDVALORIRRF + COALESCE(WVALORIRRF, 0);
    BDVALORINSS = BDVALORINSS + COALESCE(WVALORINSS, 0);
    BDVRDEDDEP = BDVRDEDDEP + COALESCE(WVRDEDDEP, 0);
    BDBASEPENSAO = BDBASEPENSAO + COALESCE(WBASEPENSAO, 0);
    BDBASEPREV = BDBASEPREV + COALESCE(WBASEPREV, 0);
    BDCALCULOS = BDCALCULOS + COALESCE(WCALCULOS, 0);
    BDBASEIRRF13 = BDBASEIRRF13 + COALESCE(WBASEIRRF13, 0);
    BDVALORIRRF13 = BDVALORIRRF13 + COALESCE(WVALORIRRF13, 0);
    BDVALORINSS13 = BDVALORINSS13 + COALESCE(WVALORINSS13, 0);
    BDVRDEDDEP13 = BDVRDEDDEP13 + COALESCE(WVRDEDDEP13, 0);
    BDBASEPENSAO13 = BDBASEPENSAO13 + COALESCE(WBASEPENSAO13, 0);
    BDBASEPREV13 = BDBASEPREV13 + COALESCE(WBASEPREV13, 0);
    
    BDBASEIRRFPLR = BDBASEIRRFPLR + COALESCE(WBASEIRRFPLR, 0);
    BDVALORIRRFPLR = BDVALORIRRFPLR + COALESCE(WVALORIRRFPLR, 0);
    BDVALORINSSPLR = BDVALORINSSPLR + COALESCE(WVALORINSSPLR, 0);
    BDVRDEDDEPPLR = BDVRDEDDEPPLR + COALESCE(WVRDEDDEPPLR, 0);
    BDBASEPENSAOPLR = BDBASEPENSAOPLR + COALESCE(WBASEPENSAOPLR, 0);
    BDBASEPREVPLR = BDBASEPREVPLR + COALESCE(WBASEPREVPLR, 0);

    BDBASEIRRFRRA = BDBASEIRRFRRA + COALESCE(WBASEIRRFRRA, 0);
    BDVALORIRRFRRA = BDVALORIRRFRRA + COALESCE(WVALORIRRFRRA, 0);
    BDVALORINSSRRA = BDVALORINSSRRA + COALESCE(WVALORINSSRRA, 0);
    BDVRDEDDEPRRA = BDVRDEDDEPRRA + COALESCE(WVRDEDDEPRRA, 0);
    BDBASEPENSAORRA = BDBASEPENSAORRA + COALESCE(WBASEPENSAORRA, 0);
    BDBASEPREVRRA = BDBASEPREVRRA + COALESCE(WBASEPREVRRA, 0);
    
    
    BDBASEIRRFES = BDBASEIRRFES + COALESCE(WBASEIRRFES, 0);
    BDVALORIRRFES = BDVALORIRRFES + COALESCE(WVALORIRRFES, 0);
    BDVALORINSSES = BDVALORINSSES + COALESCE(WVALORINSSES, 0);
    BDVRDEDDEPES = BDVRDEDDEPES + COALESCE(WVRDEDDEPES, 0);
    BDBASEPENSAOES = BDBASEPENSAOES + COALESCE(WBASEPENSAOES, 0);
    BDBASEPREVES = BDBASEPREVES + COALESCE(WBASEPREVES, 0);
    
    BDBASEIRRF13ES = BDBASEIRRF13ES + COALESCE(WBASEIRRF13ES, 0);
    BDVALORIRRF13ES = BDVALORIRRF13ES + COALESCE(WVALORIRRF13ES, 0);
    BDVALORINSS13ES = BDVALORINSS13ES + COALESCE(WVALORINSS13ES, 0);
    BDBASEPENSAO13ES = BDBASEPENSAO13ES + COALESCE(WBASEPENSAO13ES, 0);
    BDBASEPREV13ES = BDBASEPREV13ES + COALESCE(WBASEPREV13ES, 0);
    BDVRDEDDEPES13 = BDVRDEDDEPES13 + COALESCE(WVRDEDDEP13ES, 0);

    
    BDBASEIRRFPLRES = BDBASEIRRFPLRES + COALESCE(WBASEIRRFPLRES, 0);
    BDVALORIRRFPLRES = BDVALORIRRFPLRES + COALESCE(WVALORIRRFPLRES, 0);
    BDBASEPENSAOPLRES = BDBASEPENSAOPLRES + COALESCE(WBASEPENSAOPLRES, 0);
    
    BDBASEIRRFRRAES = BDBASEIRRFRRAES + COALESCE(WBASEIRRFRRAES, 0);
    BDVALORIRRFRRAES = BDVALORIRRFRRAES + COALESCE(WVALORIRRFRRAES, 0);
    BDBASEPENSAORRAES = BDBASEPENSAORRAES + COALESCE(WBASEPENSAORRAES, 0);

    BDVRDEDDEPPLRES = BDVRDEDDEPPLRES + COALESCE(WVRDEDDEPPLRES, 0);
    BDVRDEDDEPRRAES = BDVRDEDDEPRRAES + COALESCE(WVRDEDDEPRRAES, 0);
    BDVALORINSSRRAES = BDVALORINSSRRAES + COALESCE(WVALORINSSRRAES, 0);

    BDCODEMPORD = WCODMATRIZ;
    BDCNPJEMP = WCNPJEMP;
    BDNOMEMP = WNOMEMP;
    BDCODEMP = WCODEMP;
    BDCODCOL = WCODCOL;
    BDCPFCOL = WCPFCOL;
    BDNOMCOL = WNOMCOL;
    BDCONTRCOL = WCONTRCOL;
    BDCATEGORIAESOCIAL = WCATESOCIAL;
    BDCODCLATRI = WCODCLATRI;
    BDGRUPOCLA = WGRUPOCLA;


    WTEMEVENTO = 0;

    select count (EVT.BDCODIGO), count(FN.BDREFFN), count(FT.BDORDEM)
    from VRH_ESOCIAL_TARQUIVO EVT
    left outer join VRHF_EMP_TFOLHANORMAL FN ON FN.BDCODEMP = EVT.BDCODEMP and FN.BDCODCOL = EVT.BDCODCOL and FN.BDREFFN = EVT.BDREFARQ
    left outer join VRHF_EMP_TFOLHATOMADOR FT ON FT.BDCODEMP = EVT.BDCODEMP and FT.BDCODCOL = EVT.BDCODCOL and FT.BDREFTOMADOR = EVT.BDREFARQ
    where EVT.BDCODEMP = :WCODEMP and EVT.BDCODCOL = :WCODCOL and EVT.BDSTATUS = 2 and EVT.BDCODTIPO in (11, 34, 37) and EVT.BDREFARQ = :PRREF
     into :WTEMEVENTO, :WTEMCALCFN, :WTEMCALCFT;

    WTEMCALCFN = 1;
    WTEMCALCFT = 1;

  end

  if (WCPFANTERIOR = WCPFCOL) then
  begin
    if (WCPFANTERIOR <> '') then
      suspend;
  end
end^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_ABONO_BI0 FOR VRH_EMP_TRECLAMATORIA_ABONO
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wcod INTEGER;
begin
  if (coalesce(new.bdchave, 0) <= 0) then
     begin
     wcod = null;
     select coalesce(max(BDCHAVE), 1) from VRH_EMP_TRECLAMATORIA_ABONO where BDCODEMP = new.bdcodemp into :wcod;
     new.bdchave = :wcod;
     end

  if (coalesce(new.bdcodvinc, 0) <= 0) then
     begin
       wcod = null;
       select coalesce(max(BDCODVINC), 1) from VRH_EMP_TRECLAMATORIA_VINC where BDCODEMP = new.bdcodemp and BDCHAVE = new.bdchave into :wcod;
       new.bdcodvinc = :wcod;
     end

end
^

create or alter procedure FILTRO_DOWNLOAD_ESOCIAL (
    WFILTRO integer)
returns (
    BDNO varchar(100),
    BDCLASSIFICACAO varchar(30),
    BDCODEMP integer,
    BDRAIZ varchar(15),
    BDCODESTAB integer,
    BDTIPINSC integer,
    BDCNPJRESP varchar(15),
    BDCODCC integer,
    BDDESCRICAO varchar(100),
    BDMATRIZ varchar(15),
    BDCODMATRIZ integer,
    BDTIPO varchar(8),
    BDIMPORTA varchar(15),
    BDCAD varchar(15),
    BDESTABUNICO varchar(15),
    BDINSCRICAO varchar(20),
    BDESTAB varchar(15),
    BDLOTTRIB varchar(15),
    BDFUNCOES varchar(15),
    BDHORARIOS varchar(15),
    BDCOLMOV varchar(15),
    BDCONMOV varchar(15))
as
declare variable WWHERE varchar(1000);
declare variable WSQL varchar(30000);
BEGIN
    wsql         = 'select distinct X.BDNO, X.BDCLASSIFICACAO, X.BDCODEMP, ';
    wsql = wsql || 'Y.BDRAIZ, Y.BDCODESTAB, Y.BDTIPINSC, Y.BDCNPJRESP, Y.BDCODCC, Y.BDDESCRICAO, Y.BDMATRIZ, Y.BDCODMATRIZ, Y.BDTIPO, Y.BDIMPORTA, Y.BDCAD, Y.BDESTABUNICO, ';
    wsql = wsql || 'replace(replace(replace(replace(replace(replace(replace(X.BDNO, ''.'', ''''), ''/'', ''''), ''-'', ''''), ''_'', ''''), ''CNPJ '', ''''), ''CPF '', ''''), ''CAEPF '', '''') BDINSCRICAO, ';
    wsql = wsql || 'coalesce(SINC.BDESTAB,    false) BDESTAB, ';
    wsql = wsql || 'coalesce(SINC.BDLOTTRIB,  false) BDLOTTRIB, ';
    wsql = wsql || 'coalesce(SINC.BDFUNCOES,  false) BDFUNCOES, ';
    wsql = wsql || 'coalesce(SINC.BDHORARIOS, false) BDHORARIOS, ';
    wsql = wsql || 'coalesce(SINC.BDCOLMOV,   false) BDCOLMOV, ';
    wsql = wsql || 'coalesce(SINC.BDCONMOV,   false) BDCONMOV ';
    wsql = wsql || 'from TESTRUTURADOWN X ';
    wsql = wsql || 'join TDEFESTABDOWN Y on (Y.BDRAIZ = X.BDRAIZ and ';
    wsql = wsql || 'Y.BDINSCRICAO = replace(replace(replace(replace(replace(replace(replace(X.BDNO, ''.'', ''''), ''/'', ''''), ''-'', ''''), ''_'', ''''), ''CNPJ '', ''''), ''CPF '', ''''), ''CAEPF '', '''')) ';
    wsql = wsql || 'left join VRH_ESOCIAL_TSINCRONIZACAO SINC on (SINC.BDCODEMP = Y.BDCODESTAB) ';

    if (wfiltro > 0) then
      begin
        wwhere = 'where ';

        if (wfiltro = 1) then
          begin
            wwhere = wwhere || 'SINC.BDESTAB    = true and ';
            wwhere = wwhere || 'SINC.BDLOTTRIB  = true and ';
            wwhere = wwhere || 'SINC.BDFUNCOES  = true and ';
            wwhere = wwhere || 'SINC.BDHORARIOS = true and ';
            wwhere = wwhere || 'SINC.BDCOLMOV   = true and ';
            wwhere = wwhere || 'SINC.BDCONMOV   = true ';
          end
        else
        if (wfiltro = 2) then
          begin
            wwhere = wwhere || 'SINC.BDESTAB    is null or ';
            wwhere = wwhere || 'SINC.BDLOTTRIB  is null or ';
            wwhere = wwhere || 'SINC.BDFUNCOES  is null or ';
            wwhere = wwhere || 'SINC.BDHORARIOS is null or ';
            wwhere = wwhere || 'SINC.BDCOLMOV   is null or ';
            wwhere = wwhere || 'SINC.BDCONMOV   is null';
          end

        wsql = wsql || wwhere;
      end


    FOR EXECUTE STATEMENT wSQL INTO
         :BDNO,
         :BDCLASSIFICACAO,
         :BDCODEMP,
         :BDRAIZ,
         :BDCODESTAB,
         :BDTIPINSC,
         :BDCNPJRESP,
         :BDCODCC,
         :BDDESCRICAO,
         :BDMATRIZ,
         :BDCODMATRIZ,
         :BDTIPO,
         :BDIMPORTA,
         :BDCAD,
         :BDESTABUNICO,
         :BDINSCRICAO,
         :BDESTAB,
         :BDLOTTRIB,
         :BDFUNCOES,
         :BDHORARIOS,
         :BDCOLMOV,
         :BDCONMOV
  DO
  BEGIN
    SUSPEND;
  END
END^

CREATE OR ALTER TRIGGER VRH_BASE_TRELCONF_ITENS_BI0 FOR VRH_BASE_TRELCONF_ITENS
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
  DECLARE VARIABLE vColuna INTEGER;
BEGIN
  IF ((NEW.BDCODIGO IS NULL) OR (NEW.BDCODIGO = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcodigo), 0) + 1 FROM VRH_BASE_TRELCONF_ITENS INTO :vCodigo;
       NEW.BDCODIGO = :vCodigo;
     END

  IF ((NEW.BDCOLUNA IS NULL) OR (NEW.BDCOLUNA = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdcoluna), 0) + 1 FROM VRH_BASE_TRELCONF_ITENS
       WHERE BDCODRELCONF = new.BDCODRELCONF INTO :vColuna;
       NEW.BDCOLUNA = :vColuna;
     END
END^

CREATE OR ALTER TRIGGER VCT_DASHBOARD_GRF_USUARIO_BI0 FOR VCT_DASHBOARD_GRF_USUARIO
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vid integer;
begin
  if (coalesce(new.bdusuid, 0) = 0) then
  begin
    select max(bdusuid) from VCT_DASHBOARD_GRF_USUARIO
    where bdgrfid = new.bdgrfid
    into :vid;
    new.bdusuid = coalesce(vid, 0) +1;
  end
  else
  begin
    select bdgrfid from VCT_DASHBOARD_GRF_USUARIO
    where bdgrfid = new.bdgrfid and bdusuid = new.bdusuid
    into :vid;

    if (coalesce(vid, 0) > 0) then
    begin
      select max(bdgrfid) from VCT_DASHBOARD_GRF_USUARIO
      where bdgrfid = new.bdgrfid
      into :vid;
      new.bdusuid = coalesce(vid, 0) +1;
    end
  end
end
^

CREATE OR ALTER TRIGGER VCT_DASHBOARD_QUADRO_BI0 FOR VCT_DASHBOARD_QUADRO
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vid integer;
  declare variable vordem integer;
begin
  if (coalesce(new.bdqdrid, 0) = 0) then
  begin
    select max(bdqdrid) from vct_dashboard_quadro
    into :vid;
    new.bdqdrid = coalesce(vid, 0) +1;
  end
  else
  begin
    select bdqdrid from vct_dashboard_quadro
    where bdqdrid = new.bdqdrid
    into :vid;

    if (coalesce(vid, 0) > 0) then
    begin
      select max(bdqdrid) from vct_dashboard_quadro
      into :vid;
      new.bdqdrid = coalesce(vid, 0) +1;
    end
  end

  if (coalesce(new.bdordem, 0) = 0) then
  begin
    select max(bdordem) from vct_dashboard_quadro
    into :vordem;
    new.bdordem = coalesce(vordem, 0) +1;
  end
end
^

CREATE OR ALTER TRIGGER VCT_DASHBOARD_QUADROGRAFICO_BI0 FOR VCT_DASHBOARD_QUADROGRAFICO
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vid integer;
begin
  if (coalesce(new.bdqdrid, 0) = 0) then
  begin
    select max(bdqdrid) from vct_dashboard_quadro
    into new.bdqdrid;
  end

  if (coalesce(new.bdid, 0) = 0) then
  begin
    select max(bdid) from vct_dashboard_quadrografico
    where bdqdrid = new.bdqdrid
    into :vid;
    new.bdid = coalesce(vid, 0) +1;
  end
  else
  begin
    select bdid from vct_dashboard_quadrografico
    where bdid = new.bdid
    and bdqdrid = new.bdqdrid
    into :vid;

    if (coalesce(vid, 0) > 0) then
    begin
      select max(bdid) from vct_dashboard_quadrografico
      where bdqdrid = new.bdqdrid
      into :vid;
      new.bdid = coalesce(vid, 0) +1;
    end
  end
end
^

CREATE OR ALTER TRIGGER TTELA_SELECOEEMPRESA_BI0 FOR TTELA_SELECOEEMPRESA
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM TTELA_SELECOEEMPRESA order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0) + 1;
  end
END
^

CREATE OR ALTER TRIGGER TTELA_SELEMPRESA_BI0 FOR TTELA_SELEMPRESA
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM TTELA_SELECOEEMPRESA order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0);
  end
END
^

CREATE OR ALTER trigger ttela_selecaotipohisttarefa_bi0 for ttela_selecaotipohistoricotarefa
active before insert position 0
AS
  DECLARE VARIABLE VNOVOCOD INTEGER;
BEGIN
  IF (COALESCE(NEW.BDCODIGOSEL, 0) = 0) THEN
  BEGIN
    SELECT FIRST 1 BDCODIGOSEL FROM TTELA_SELECAOTIPOHISTORICOTAREFA ORDER BY BDCODIGOSEL DESC INTO :VNOVOCOD;
    NEW.BDCODIGOSEL = COALESCE(VNOVOCOD, 0)+1;
  END
END^

CREATE  OR ALTER trigger ttela_seltipohistoricotarefa_bi0 for ttela_seltipohistoricotarefa
active before insert position 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;
BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM TTELA_SELTIPOHISTORICOTAREFA order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0) + 1;
  end
END^

CREATE OR ALTER TRIGGER TTELA_SELECOEGRPUSU_BI0 FOR TTELA_SELECOEGRPUSU
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM TTELA_SELECOEGRPUSU order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0) + 1;
  end
END
^

CREATE OR ALTER TRIGGER TTELA_SELGRPUSU_BI0 FOR TTELA_SELGRPUSU
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;
   DECLARE VARIABLE vNovaChave INTEGER;
BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM TTELA_SELECOEGRPUSU order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0)+1;
  end

  if (coalesce(NEW.bdchave, 0) = 0) then
  begin
    SELECT first 1 bdchave FROM TTELA_SELGRPUSU where bdcodigosel = NEW.bdcodigosel
    order by bdchave desc into :vNovaChave;
    NEW.bdchave = coalesce(vNovaChave, 0) + 1;
  end
END
^

CREATE OR ALTER TRIGGER TTELA_SELECOEIMPOSTOBASE_BI0 FOR TTELA_SELECOEIMPOSTOBASE
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM TTELA_SELECOEIMPOSTOBASE order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0) + 1;
  end
END
^

CREATE OR ALTER TRIGGER TTELA_SELIMPOSTOBASE_BI0 FOR TTELA_SELIMPOSTOBASE
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM TTELA_SELECOEIMPOSTOBASE order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0)+1;
  end
END
^

CREATE OR ALTER TRIGGER TTELA_SELECOESERVICOBASE_BI0 FOR TTELA_SELECOESERVICOBASE
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM TTELA_SELECOESERVICOBASE order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0) + 1;
  end
END
^

CREATE OR ALTER TRIGGER TTELA_SELSERVICOBASE_BI0 FOR TTELA_SELSERVICOBASE
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM TTELA_SELECOESERVICOBASE order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0)+1;
  end
END
^

CREATE OR ALTER TRIGGER TTELA_SELECOEOBRIGABASE_BI0 FOR TTELA_SELECOEOBRIGACAOBASE
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM TTELA_SELECOEOBRIGACAOBASE order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0) + 1;
  end
END
^

CREATE OR ALTER TRIGGER TTELA_SELOBRIGACAOBASE_BI0 FOR TTELA_SELOBRIGACAOBASE
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
  if (coalesce(NEW.bdcodigosel, 0) = 0) then
  begin
    SELECT first 1 bdcodigosel FROM TTELA_SELECOEOBRIGACAOBASE order by bdcodigosel desc into :vNovoCod;
    NEW.bdcodigosel = coalesce(vNovoCod, 0)+1;
  end
END
^

CREATE OR ALTER TRIGGER TEMPRESAS_CODMATRIZ FOR TEMPRESAS
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
declare variable vcodigoempmatriz integer;
declare variable vcodemp integer;
begin

  if (new.bdcodmatriz is distinct from Old.bdcodmatriz) then
  begin
    if (new.bdcodemp is null) then
    begin
      vcodemp = old.bdcodemp;
    end
    else
      vcodemp = new.bdcodemp;

      select first 1 count(bdcodemp) from tempresas emp where (emp.bdcodmatriz = :vcodemp)
      into :vcodigoempmatriz;
    
      if ((vcodigoempmatriz > 0) and (coalesce(NEW.bdcodmatriz, 0) <> 0)) then
      begin
        EXCEPTION EX_CUSTOM 'Não é possível preencher o código de matriz de uma empresa que já é matriz.';
      end
   end
end
^
CREATE OR ALTER TRIGGER VSH_EMP_TRETORNO_IC_BI0 FOR VSH_EMP_TRETORNO_IC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  /* Trigger text */
IF (COALESCE(NEW.bdordem, 0) = 0) THEN
    BEGIN
      SELECT MAX(bdordem) + 1
      FROM VSH_EMP_TRETORNO_IC IC
      WHERE IC.BDCODAGENDAMENTO = NEW.BDCODAGENDAMENTO
      AND IC.BDCODEMP           = NEW.BDCODEMP
      AND IC.BDCODPLANOSCHIP    = NEW.BDCODPLANOSCHIP
      AND IC.BDORDEMAGENDAMENTO = NEW.BDORDEMAGENDAMENTO
      INTO NEW.bdordem;
      NEW.bdordem = COALESCE(NEW.bdordem, 1);
    END
end
^

CREATE OR ALTER TRIGGER VEF_EMP_TIMPOSTOS_IC_BI0 FOR VEF_EMP_TIMPOSTOS_IC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  DELETE FROM VEF_EMP_TIMPOSTOS_IC WHERE BDCODEMP = NEW.BDCODEMP AND BDCODREC = NEW.BDCODREC AND BDDTEMISSAO = NEW.BDDTEMISSAO AND BDDATAVCTO = NEW.BDDATAVCTO AND BDVALOR = NEW.BDVALOR;
end
^

create or alter procedure SP_FGTS_DIGITAL_COMP (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRPUXAFILIAL boolean,
    PRANUAL boolean)
returns (
    BDNOME_MATRIZ varchar(200),
    BDCODFILIAL integer,
    BDCODEMP integer,
    BDNOMEMP varchar(200),
    BDCNPJEMP varchar(20),
    BDCOMP varchar(20),
    BDREF integer,
    BDNOMECOL varchar(200),
    BDCODCOL integer,
    BDCPFCOL varchar(20),
    BDMATCOL varchar(50),
    BDCATEGORIA integer,
    BDBASE_FGTS_DIGITAL numeric(18,6),
    BDBASE_FGTS_DIGITAL_RES numeric(18,6),
    BDBASE_FGTS_DIGITAL_13 numeric(18,6),
    BDBASE_FGTS_DIGITAL_IND numeric(18,6),
    BDVALOR_FGTS_DIGITAL numeric(18,6),
    BDVALOR_FGTS_DIGITAL_RES numeric(18,6),
    BDVALOR_FGTS_DIGITAL_13 numeric(18,6),
    BDVALOR_FGTS_DIGITAL_IND numeric(18,6),
    BDBASE_FGTS_UNICO numeric(18,6),
    BDBASE_FGTS_UNICO_RES numeric(18,6),
    BDBASE_FGTS_UNICO_13 numeric(18,6),
    BDBASE_FGTS_UNICO_IND numeric(18,6),
    BDVALOR_FGTS_UNICO numeric(18,6),
    BDVALOR_FGTS_UNICO_RES numeric(18,6),
    BDVALOR_FGTS_UNICO_13 numeric(18,6),
    BDVALOR_FGTS_UNICO_IND numeric(18,6),
    BDBASE_MULTA_UNICO numeric(15,2),
    BDBASE_MULTA_FD numeric(15,2),
    BDVALOR_MULTA_UNICO numeric(15,2),
    BDVALOR_MULTA_FD numeric(15,2),
    BDCALCFGTSMESANT boolean,
    BDEXISTEDIFERENCA smallint)
as
declare variable WSQLLISTA varchar(30000);
declare variable WSQLFD varchar(30000);
declare variable WSQLMULTA varchar(30000);
declare variable WBASE_FGTS_DIGITAL numeric(18,6);
declare variable WBASE_FGTS_DIGITAL_RES numeric(18,6);
declare variable WBASE_FGTS_DIGITAL_13 numeric(18,6);
declare variable WBASE_FGTS_DIGITAL_IND numeric(18,6);
declare variable WVALOR_FGTS_DIGITAL numeric(18,6);
declare variable WVALOR_FGTS_DIGITAL_RES numeric(18,6);
declare variable WVALOR_FGTS_DIGITAL_13 numeric(18,6);
declare variable WVALOR_FGTS_DIGITAL_IND numeric(18,6);
declare variable WBASE_FGTS_UNICO numeric(18,6);
declare variable WBASE_FGTS_UNICO_RES numeric(18,6);
declare variable WBASE_FGTS_UNICO_13 numeric(18,6);
declare variable WBASE_FGTS_UNICO_IND numeric(18,6);
declare variable WVALOR_FGTS_UNICO numeric(18,6);
declare variable WVALOR_FGTS_UNICO_RES numeric(18,6);
declare variable WVALOR_FGTS_UNICO_13 numeric(18,6);
declare variable WVALOR_FGTS_UNICO_IND numeric(18,6);
declare variable WTEMRESCISAO integer;
declare variable WBASE_MULTA numeric(15,2);
declare variable WVALOR_MULTA numeric(15,2);
declare variable WBASE_MULTA_FD numeric(15,2);
declare variable WVALOR_MULTA_FD numeric(15,2);
declare variable WGRRFPRES smallint;
declare variable WBASE_FGTS_GRRF numeric(15,2);
declare variable WVALOR_FGTS_GRRF numeric(15,2);
declare variable WFGTS_ANTERIOR numeric(15,2);
declare variable WTIPOEVT integer;
declare variable WCODPRES integer;
declare variable WREFINI integer;
declare variable WREFFIM integer;
declare variable WCALCFGTSANT boolean;
declare variable WREFRESCISAO integer;
declare variable WBASE_SALDO numeric(15,2);
declare variable WVALOR_SALDO numeric(15,2);
begin
    BDBASE_FGTS_DIGITAL      = 0;
    BDBASE_FGTS_DIGITAL_RES  = 0;
    BDBASE_FGTS_DIGITAL_13   = 0;
    BDBASE_FGTS_DIGITAL_IND  = 0;
    BDVALOR_FGTS_DIGITAL     = 0;
    BDVALOR_FGTS_DIGITAL_RES = 0;
    BDVALOR_FGTS_DIGITAL_13  = 0;
    BDVALOR_FGTS_DIGITAL_IND = 0;
    BDBASE_FGTS_UNICO        = 0;
    BDBASE_FGTS_UNICO_RES    = 0;
    BDBASE_FGTS_UNICO_13     = 0;
    BDBASE_FGTS_UNICO_IND    = 0;
    BDVALOR_FGTS_UNICO       = 0;
    BDVALOR_FGTS_UNICO_RES   = 0;
    BDVALOR_FGTS_UNICO_13    = 0;
    BDVALOR_FGTS_UNICO_IND   = 0;
    BDBASE_MULTA_UNICO       = 0;
    BDVALOR_MULTA_UNICO      = 0;
    BDBASE_MULTA_FD          = 0;
    BDVALOR_MULTA_FD         = 0;


    BDCOMP = SUBSTRING(PRREF FROM 5 FOR 2)||'/'||SUBSTRING(PRREF FROM 1 FOR 4);
    BDREF  = PRREF;
    WSQLLista = '';

    WSQLLista = 'SELECT '||
                '  (SELECT FIRST 1 MAT.BDNOMEMP FROM TEMPRESAS_REF MAT  WHERE MAT.BDCODEMP = EMP.BDCODEMP AND MAT.BDREFEMP <= '||PRREF||' ORDER BY MAT.BDREFEMP DESC) AS NOME_MATRIZ, '||
                '  EMP.BDCODEMP AS BDCODFILIAL,'||
                '  COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP,'||
                '  EMPR.BDNOMEMP,'||
                '  EMP.BDCNPJEMP, '||
                '  (SELECT * FROM SP_REMOVER_ACENTOS(CCD.BDNOMCOL)) AS BDNOMECOL, '||
                '  COL.BDCODCOL, '||
                '  COL.BDCPFCOL, '||
                '  COL.BDMATRICULA,'||
                '  FG.BDCATEGORIAESOCIAL '||
                'FROM TEMPRESAS EMP '||
                'INNER JOIN TEMPRESAS_REF EMPR ON (EMPR.BDCODEMP = EMP.BDCODEMP AND'||
                '                                  EMPR.BDREFEMP = (SELECT MAX(EMPR1.BDREFEMP)'||
                '                                                   FROM TEMPRESAS_REF EMPR1 '||
                '                                                   WHERE EMPR1.BDCODEMP = EMPR.BDCODEMP AND '||
                '                                                         EMPR1.BDREFEMP <= '||PRREF||')) '||
                'INNER JOIN VRH_EMP_TCOLCON COL ON (COL.BDCODEMP = EMP.BDCODEMP) '||
                'INNER JOIN VRH_EMP_TCOLCON_CAD CCD ON (CCD.BDCODEMP = EMP.BDCODEMP AND'||
                '                                       COL.BDCODCOL = CCD.BDCODCOL AND '||
                '                                       CCD.BDREFCOL = (SELECT MAX(CCD1.BDREFCOL) '||
                '                                                       FROM VRH_EMP_TCOLCON_CAD CCD1  '||
                '                                                       WHERE CCD1.BDCODEMP = EMP.BDCODEMP AND '||
                '                                                             CCD1.BDCODCOL = COL.BDCODCOL AND  '||
                '                                                             CCD1.BDREFCOL <= '||PRREF||'))'||
                'INNER JOIN VRHF_EMP_TCOLCON_FGTSGPS FG ON (FG.BDCODCOL = COL.BDCODCOL AND '||
                '                             FG.BDCODEMP = EMP.BDCODEMP AND '||
                '                             FG.BDREFCOL = (SELECT MAX(FG1.BDREFCOL) '||
                '                                            FROM VRHF_EMP_TCOLCON_FGTSGPS FG1  '||
                '                                            WHERE FG1.BDCODEMP = EMP.BDCODEMP AND  '||
                '                                                  FG1.BDCODCOL = FG.BDCODCOL AND '||
                '                                                  FG1.BDREFCOL <= '||PRREF||')) '||
                'WHERE EMP.BDCODEMP IN (SELECT FD.BDCODEMP FROM VRHF_EMP_FGTSDIG_TRAB FD WHERE FD.BDCODEMP <> 0 AND FD.BDCOMPAPU = '||PRREF||') AND CHAR_LENGTH(COL.BDCPFCOL) = 14 ';

     IF (PRCODEMP <> 0) THEN
       BEGIN
         IF (PRPUXAFILIAL = TRUE) THEN
           WSQLLISTA = WSQLLISTA || ' AND COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) = ' || PRCODEMP;
         ELSE
           WSQLLISTA = WSQLLISTA || ' AND EMP.BDCODEMP = ' || PRCODEMP;
       END

     IF (PRCODCOL <> '0') THEN
        WSQLLISTA = WSQLLISTA || ' AND COL.BDCODCOL  = '||PRCODCOL;
     ELSE
       BEGIN
         WSQLLISTA = WSQLLISTA || 'UNION  '||
                                  'SELECT '||
                                  '  (SELECT FIRST 1 MAT.BDNOMEMP FROM TEMPRESAS_REF MAT  WHERE MAT.BDCODEMP = EMP.BDCODEMP AND MAT.BDREFEMP <= '||PRREF||' ORDER BY MAT.BDREFEMP DESC) AS NOME_MATRIZ, '||
                                  '  EMP.BDCODEMP AS BDCODFILIAL, '||
                                  '  COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) BDCODEMP, '||
                                  '  FD.BDNOMEMP, '||
                                  '  FD.BDCNPJEMP, '||
                                  '  FD.BDNOMECOL, '||
                                  '  FD.BDCODCOL, '||
                                  '  FD.BDCPFCOL, '||
                                  '  FD.BDMATCOL, '||
                                  '  FD.BDCATEGORIA '||
                                  'FROM VRHF_EMP_FGTSDIG_TRAB FD '||
                                  'inner join TEMPRESAS EMP on (EMP.BDCODEMP = FD.BDCODEMP) '||
                                  'WHERE FD.BDCODEMP <> 0 AND FD.BDCOMPAPU = '||PRREF||' AND FD.BDCODCOL = 0';

         IF (PRCODEMP <> 0) THEN
           BEGIN
             IF (PRPUXAFILIAL = TRUE) THEN
               WSQLLISTA = WSQLLISTA || ' AND COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) = ' || PRCODEMP;
             ELSE
               WSQLLISTA = WSQLLISTA || ' AND EMP.BDCODEMP = ' || PRCODEMP;
           END
       END

  for execute statement WSQLLISTA
      into :BDNOME_MATRIZ, :BDCODFILIAL, :BDCODEMP, :BDNOMEMP, :BDCNPJEMP, :BDNOMECOL, :BDCODCOL, :BDCPFCOL, :BDMATCOL, :BDCATEGORIA
  do
  begin

    WBASE_FGTS_DIGITAL = 0;
    WBASE_FGTS_DIGITAL_RES = 0;
    WBASE_FGTS_DIGITAL_13 = 0;
    WBASE_FGTS_DIGITAL_IND = 0;
    WVALOR_FGTS_DIGITAL = 0;
    WVALOR_FGTS_DIGITAL_RES = 0;
    WVALOR_FGTS_DIGITAL_13 = 0;
    WVALOR_FGTS_DIGITAL_IND = 0;
    WBASE_FGTS_UNICO = 0;
    WBASE_FGTS_UNICO_RES = 0;
    WBASE_FGTS_UNICO_13 = 0;
    WBASE_FGTS_UNICO_IND = 0;
    WVALOR_FGTS_UNICO = 0;
    WVALOR_FGTS_UNICO_RES = 0;
    WVALOR_FGTS_UNICO_13 = 0;
    WVALOR_FGTS_UNICO_IND = 0;
    WBASE_MULTA = 0;
    WVALOR_MULTA = 0;
    WBASE_MULTA_FD = 0;
    WVALOR_MULTA_FD = 0;
    WGRRFPRES = -1;
    BDEXISTEDIFERENCA = -1;
    WCALCFGTSANT = FALSE;
    WTEMRESCISAO = 0;
    WREFRESCISAO = 0;

    SELECT BDCALCFGTSMESANT, BDREFRESCISAO FROM VRH_EMP_TRESCISAO WHERE BDCODEMP = :BDCODFILIAL AND BDCODCOL = :BDCODCOL AND BDREFRESCISAO between :PRREF and (:PRREF + 1)
    INTO :WCALCFGTSANT, :WREFRESCISAO;

    if (WREFRESCISAO > 0) then
      WTEMRESCISAO = 1;

    IF (WTEMRESCISAO > 0) THEN
      BEGIN
        WREFFIM = PRREF;

        IF (WCALCFGTSANT = TRUE) THEN
          WREFINI = PRREF - 1;
        ELSE
          WREFINI = PRREF;

        if (WREFRESCISAO = (PRREF + 1)) then
          BEGIN
            WREFINI = 0;
            WREFFIM = 0;
          END
      END
    ELSE
      BEGIN
        WREFINI = PRREF;
        WREFFIM = PRREF;
      END


    if (PRANUAL = TRUE) THEN
      BEGIN
        SELECT SUM(BDBFGTS) AS BDBFGTS, SUM(BDFGTS) AS BDFGTS, SUM(BDBFGTSRESC) AS BDBFGTSRESC, SUM(BDFGTSRESC) AS BDFGTSRESC, SUM(BDBFGTS13) AS BDBFGTS13, SUM(BDFGTS13) AS BDFGTS13
        FROM
        (
            SELECT 0 BDBFGTS, 0 BDFGTS, 0 BDBFGTSRESC, 0 BDFGTSRESC, SUM(F.BDBFGTS) BDBFGTS13, SUM(F.BDFGTS) BDFGTS13
            FROM SP_VRHF_DADOS_FGTS_13('FOL.BDCODEMP = '||:BDCODFILIAL, 'FOL.BDCODCOL = '||:BDCODCOL, :PRREF, :PRREF, 0, '') F
            
            UNION ALL

            SELECT 0 BDBFGTS, 0 BDFGTS, 0 BDBFGTSRESC, 0 BDFGTSRESC, SUM(F.BDBFGTS) BDBFGTS13, SUM(F.BDFGTS) BDFGTS13
            FROM SP_VRHF_DADOS_FGTS_C13('FOL.BDCODEMP = '||:BDCODFILIAL, 'FOL.BDCODCOL = '||:BDCODCOL, :PRREF, :PRREF, 0, '') F
        ) Q
    
        into :WBASE_FGTS_UNICO, :WVALOR_FGTS_UNICO, :WBASE_FGTS_UNICO_RES, :WVALOR_FGTS_UNICO_RES, :WBASE_FGTS_UNICO_13, :WVALOR_FGTS_UNICO_13;
      END
    ELSE
      BEGIN

        SELECT SUM(BDBFGTS) AS BDBFGTS, SUM(BDFGTS) AS BDFGTS, SUM(BDBFGTSRESC) AS BDBFGTSRESC, SUM(BDFGTSRESC) AS BDFGTSRESC, SUM(BDBFGTSIND) AS BDBFGTSIND, SUM(BDFGTSIND) AS BDFGTSIND, SUM(BDBFGTS13) AS BDBFGTS13, SUM(BDFGTS13) AS BDFGTS13, SUM(BDBFGTSGRRF) as BDBFGTSGRRF, SUM(BDFGTSGRRF) AS BDFGTSGRRF,  SUM(BDTIPOEVT) AS BDTIPOEVT
        FROM
        (
            SELECT SUM(F.BDBFGTS) BDBFGTS, SUM(F.BDFGTS) AS BDFGTS,  SUM(CASE WHEN F.bdbfgts <> F.BDBFGTSMESESOCIAL THEN F.BDBFGTSMESESOCIAL ELSE 0 END) AS BDBFGTSRESC, SUM(CASE WHEN F.BDFGTS <> F.BDFGTSMESESOCIAL THEN F.BDFGTSMESESOCIAL ELSE 0 END) AS BDFGTSRESC, SUM(F.BDBFGTSINDESOCIAL) + SUM(F.BDBFGTS13ESOCIAL) AS BDBFGTSIND, SUM(F.BDFGTSINDESOCIAL) + SUM(F.BDFGTS13ESOCIAL) AS BDFGTSIND, SUM(F.BDBFGTS13) AS BDBFGTS13, SUM(F.BDFGTS13) AS BDFGTS13, 0 as BDBFGTSGRRF, 0 AS BDFGTSGRRF, 0 AS BDTIPOEVT
            FROM SP_VRHF_DADOS_FGTS_FC('FOL.BDCODEMP = '||:BDCODFILIAL, 'FOL.BDCODCOL = '||:BDCODCOL, :WREFINI, :WREFFIM, 0, '', TRUE) F

            UNION ALL
            
            SELECT SUM(F.BDBFGTS) BDBFGTS, SUM(F.BDFGTS) AS BDFGTS,  0 BDBFGTSRESC, 0 BDFGTSRESC, 0 AS BDBFGTSIND, 0 AS BDFGTSIND, 0 BDBFGTS13, 0 BDFGTS13, 0 as BDBFGTSGRRF, 0 AS BDFGTSGRRF, 0 AS BDTIPOEVT
            FROM SP_VRHF_DADOS_FGTS_FER('FOL.BDCODEMP = '||:BDCODFILIAL, 'FOL.BDCODCOL = '||:BDCODCOL, :WREFINI, :WREFFIM, 0, '') F
            
            UNION ALL

            SELECT SUM(F.BDBFGTS) BDBFGTS, SUM(F.BDFGTS) AS BDFGTS,  SUM(CASE WHEN F.bdbfgts <> F.BDBFGTSMESESOCIAL THEN F.BDBFGTSMESESOCIAL ELSE 0 END) AS BDBFGTSRESC, SUM(CASE WHEN F.BDFGTS <> F.BDFGTSMESESOCIAL THEN F.BDFGTSMESESOCIAL ELSE 0 END) AS BDFGTSRESC, SUM(F.BDBFGTSINDESOCIAL) + SUM(F.BDBFGTS13ESOCIAL) AS BDBFGTSIND, SUM(F.BDFGTSINDESOCIAL) + SUM(F.BDFGTS13ESOCIAL) AS BDFGTSIND, SUM(F.BDBFGTS13) AS BDBFGTS13, SUM(F.BDFGTS13) AS BDFGTS13, 0 as BDBFGTSGRRF, 0 AS BDFGTSGRRF, 0 AS BDTIPOEVT
            FROM SP_VRHF_DADOS_FGTS_FN('FOL.BDCODEMP = '||:BDCODFILIAL, 'FOL.BDCODCOL = '||:BDCODCOL, :WREFINI, :WREFFIM, 0, '') F

            UNION ALL

            SELECT 0 BDBFGTS, 0 BDFGTS, 0 BDBFGTSRESC, 0 BDFGTSRESC, 0 AS BDBFGTSIND, 0 AS BDFGTSIND, SUM(F.BDBFGTS) BDBFGTS13, SUM(F.BDFGTS) BDFGTS13, 0 as BDBFGTSGRRF, 0 AS BDFGTSGRRF, 0 AS BDTIPOEVT
            FROM SP_VRHF_DADOS_FGTS_A13('FOL.BDCODEMP = '||:BDCODFILIAL, 'FOL.BDCODCOL = '||:BDCODCOL, :WREFINI, :WREFFIM, 0, '') F

            UNION ALL

            SELECT 0 BDBFGTS, 0 BDFGTS, 0 BDBFGTSRESC, 0 BDFGTSRESC, 0 AS BDBFGTSIND, 0 AS BDFGTSIND, SUM(F.BDBFGTS) BDBFGTS13, SUM(F.BDFGTS) BDFGTS13, 0 as BDBFGTSGRRF, 0 AS BDFGTSGRRF, 0 AS BDTIPOEVT
            FROM SP_VRHF_DADOS_FGTS_C13('FOL.BDCODEMP = '||:BDCODFILIAL, 'FOL.BDCODCOL = '||:BDCODCOL, :WREFINI, :WREFFIM, 0, '') F

        ) Q
    
        into :WBASE_FGTS_UNICO, :WVALOR_FGTS_UNICO, :WBASE_FGTS_UNICO_RES, :WVALOR_FGTS_UNICO_RES, :WBASE_FGTS_UNICO_IND, :WVALOR_FGTS_UNICO_IND, :WBASE_FGTS_UNICO_13, :WVALOR_FGTS_UNICO_13, :WBASE_FGTS_GRRF, :WVALOR_FGTS_GRRF, :WTIPOEVT;

      END

    if ((WTEMRESCISAO > 0) AND (WREFRESCISAO = PRREF)) then
      BEGIN
        if (WCALCFGTSANT = TRUE) then
           BEGIN
             SELECT SUM(BDFGTS) AS BDFGTS
             FROM
             (
                SELECT SUM(F.BDFGTS) AS BDFGTS,  SUM(CASE WHEN F.bdbfgts <> F.BDBFGTSMESESOCIAL THEN F.BDBFGTSMESESOCIAL ELSE 0 END) AS BDBFGTSRESC, SUM(CASE WHEN F.BDFGTS <> F.BDFGTSMESESOCIAL THEN F.BDFGTSMESESOCIAL ELSE 0 END) AS BDFGTSRESC, SUM(F.BDBFGTSINDESOCIAL) + SUM(F.BDBFGTS13ESOCIAL) AS BDBFGTSIND, SUM(F.BDFGTSINDESOCIAL) + SUM(F.BDFGTS13ESOCIAL) AS BDFGTSIND, SUM(F.BDBFGTS13) AS BDBFGTS13, SUM(F.BDFGTS13) AS BDFGTS13, 0 as BDBFGTSGRRF, 0 AS BDFGTSGRRF, 0 AS BDTIPOEVT
                FROM SP_VRHF_DADOS_FGTS_FC('FOL.BDCODEMP = '||:BDCODFILIAL, 'FOL.BDCODCOL = '||:BDCODCOL, :WREFINI, :WREFFIM, 0, '', TRUE) F
    
                UNION ALL
                
                SELECT SUM(F.BDFGTS) AS BDFGTS,  0 BDBFGTSRESC, 0 BDFGTSRESC, 0 AS BDBFGTSIND, 0 AS BDFGTSIND, 0 BDBFGTS13, 0 BDFGTS13, 0 as BDBFGTSGRRF, 0 AS BDFGTSGRRF, 0 AS BDTIPOEVT
                FROM SP_VRHF_DADOS_FGTS_FER('FOL.BDCODEMP = '||:BDCODFILIAL, 'FOL.BDCODCOL = '||:BDCODCOL, :WREFINI, :WREFFIM, 0, '') F
                
                UNION ALL
    
                SELECT SUM(F.BDFGTS) AS BDFGTS,  SUM(CASE WHEN F.bdbfgts <> F.BDBFGTSMESESOCIAL THEN F.BDBFGTSMESESOCIAL ELSE 0 END) AS BDBFGTSRESC, SUM(CASE WHEN F.BDFGTS <> F.BDFGTSMESESOCIAL THEN F.BDFGTSMESESOCIAL ELSE 0 END) AS BDFGTSRESC, SUM(F.BDBFGTSINDESOCIAL) + SUM(F.BDBFGTS13ESOCIAL) AS BDBFGTSIND, SUM(F.BDFGTSINDESOCIAL) + SUM(F.BDFGTS13ESOCIAL) AS BDFGTSIND, SUM(F.BDBFGTS13) AS BDBFGTS13, SUM(F.BDFGTS13) AS BDFGTS13, 0 as BDBFGTSGRRF, 0 AS BDFGTSGRRF, 0 AS BDTIPOEVT
                FROM SP_VRHF_DADOS_FGTS_FN('FOL.BDCODEMP = '||:BDCODFILIAL, 'FOL.BDCODCOL = '||:BDCODCOL, :WREFINI, :WREFFIM, 0, '') F
             ) Q
             INTO :WFGTS_ANTERIOR;
           END
        ELSE
          WFGTS_ANTERIOR = 0;
        WSQLMULTA = 'SELECT CASE WHEN SUM(BDPERCMULTAFGTS) = 0 THEN 0 ELSE SUM(BASEMULTA) END + '||:WFGTS_ANTERIOR||' AS BASEMULTA, CAST((SUM(BASEMULTA) + '||:WFGTS_ANTERIOR||') * (SUM(BDPERCMULTAFGTS) / 100) AS NUMERIC(15,2)) AS VALORMULTA, MAX(BDGRRFPRES) AS BDGRRFPRES, BDCODPRES '||
                    'FROM (SELECT FIRST 1 CAST((FNB.BDFGTSFN + FNB.BDFGTS13FN + FNB.BDFGTSCSFN + RESC.BDSALDOFGTS) AS NUMERIC(15,2)) BASEMULTA, PRESC.BDPERCMULTAFGTS, PRESC.BDGRRFPRES, RESC.BDCODPRES '||
                    '      FROM VRHF_SP_TFOLHA_NORMAL(''COLCON.BDCODEMP = '||:BDCODFILIAL||''',''COLCON.BDCODCOL = '||:BDCODCOL||''', '||:PRREF||', '||:PRREF||', 1) FNB  '||
                    '      left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = '||:BDCODFILIAL||' and RESC.BDCODCOL = '||:BDCODCOL||')  '||
                    '      left outer join VRH_BASE_TPREPRESC PRESC on (PRESC.BDCODPRES = RESC.BDCODPRES)  '||
                    '      UNION '||
                    '      SELECT CAST((F.BDFGTSFC + F.BDFGTS13FC + F.BDFGTSCSFC) AS NUMERIC(15,2)) BASEMULTA, '||
                    '      (SELECT P.BDPERCMULTAFGTS '||
                    '       FROM VRH_BASE_TPREPRESC P '||
                    '       INNER JOIN VRH_EMP_TRESCISAO R ON P.BDCODPRES = R.BDCODPRES '||
                    '       WHERE R.BDCODEMP = '||:BDCODFILIAL||' AND R.BDCODCOL = '||:BDCODCOL||') AS BDPERCMULTAFGTS, '||
                    '       NULL AS BDGRRFPRES, (SELECT BDCODPRES from VRH_EMP_TRESCISAO where BDCODEMP = '||:BDCODFILIAL||' AND BDCODCOL = '||:BDCODCOL||') AS BDCODPRES '||
                    '      FROM VRHF_EMP_TFOLHACOMP F '||
                    '      WHERE F.BDCODEMP = '||:BDCODFILIAL||' AND '||
                    '            F.BDCODCOL = '||:BDCODCOL||' AND  '||
                    '           CASE WHEN F.BDCODACCONV IS NOT NULL '||
                    '                THEN cast(F.BDCODACCONV = (SELECT A.BDCODACCONV '||
                    '                                             FROM VRH_EMP_TACCONV A '||
                    '                                            WHERE A.BDCODEMP = '||:BDCODFILIAL||
                    '                                              AND A.BDCODACCONV = F.BDCODACCONV '||
                    '                                              AND (SELECT * FROM AAAAMM(A.BDDTPGTOBRICONV)) = '||:PRREF||') as boolean) '||
                    '                ELSE cast(F.BDREFFN ='||:PRREF||' as boolean) '||
                    '           END '||
                    '     ) Q  '||
                    'GROUP BY BDCODPRES ';

        execute statement WSQLMULTA
        INTO :WBASE_MULTA, :WVALOR_MULTA, :WGRRFPRES, :wcodpres;
      END
    else
      begin
        WBASE_FGTS_UNICO_RES  = 0;
        WVALOR_FGTS_UNICO_RES = 0;
        WBASE_FGTS_UNICO_IND  = 0;
        WVALOR_FGTS_UNICO_IND = 0;
      end

    WSQLFD = 'SELECT '||
             '  SUM(COALESCE(FD.BDBASEREMUNTOTAL, 0)) AS BASE_FGTS_DIGITAL, '||
             '  SUM(COALESCE(FD.BDBASEREMUNTOTAL_RES, 0)) AS BASE_FGTS_DIGITAL_RES, '||
             '  SUM(COALESCE(FD.BDBASEREMUNTOTAL_13, 0)) AS BASE_FGTS_DIGITAL_13, '||
             '  SUM(COALESCE(FD.BDBASEFGTS_IND, 0)) AS BASE_FGTS_DIGITAL_IND, '||
             '  SUM(COALESCE(FD.BDVALORFGTS, 0)) AS VALOR_FGTS_DIGITAL, '||
             '  SUM(COALESCE(FD.BDVALORFGTS_RES, 0)) AS VALOR_FGTS_DIGITAL_RES, '||
             '  SUM(COALESCE(FD.BDVALORFGTS_13, 0)) AS VALOR_FGTS_DIGITAL_13, '||
             '  SUM(COALESCE(FD.BDVALORFGTS_IND, 0)) AS VALOR_FGTS_DIGITAL_IND, '||
             '  SUM(COALESCE(BDBMULTA40, 0)) AS BASE_MULTA, '||
             '  SUM(COALESCE(BDMULTA40, 0)) AS VALOR_MULTA '||
             'FROM VRHF_EMP_FGTSDIG_TRAB FD '||
             'WHERE  FD.BDCOMPAPU BETWEEN '||WREFINI||' AND '||WREFFIM||
             '   AND FD.BDCPFCOL  = '''||BDCPFCOL||''''||
             '   AND FD.BDCODCOL  = '||BDCODCOL||
             '   AND FD.BDCODEMP  = '||BDCODFILIAL;

     if (PRANUAL = TRUE) THEN
       WSQLFD = WSQLFD || '  AND FD.BDTIPODEP = ''13º''';
     else 
       WSQLFD = WSQLFD || '  AND FD.BDTIPODEP <> ''13º''';


     execute statement WSQLFD
      into :WBASE_FGTS_DIGITAL, :WBASE_FGTS_DIGITAL_RES, :WBASE_FGTS_DIGITAL_13, :WBASE_FGTS_DIGITAL_IND, :WVALOR_FGTS_DIGITAL, :WVALOR_FGTS_DIGITAL_RES, :WVALOR_FGTS_DIGITAL_13, :WVALOR_FGTS_DIGITAL_IND, :WBASE_MULTA_FD, :WVALOR_MULTA_FD;

     if ((COALESCE(WBASE_FGTS_UNICO, 0) > 0) AND (COALESCE(WVALOR_FGTS_UNICO, 0) = 0)) then
       select BDVALOR from TRUNCAR(:WBASE_FGTS_UNICO * iif(:BDCATEGORIA = 103, 0.02, 0.08), 2) into :WVALOR_FGTS_UNICO;

     if ((COALESCE(WBASE_FGTS_UNICO_RES, 0) > 0) AND (COALESCE(WVALOR_FGTS_UNICO_RES, 0) = 0)) then
       select BDVALOR from TRUNCAR(:WBASE_FGTS_UNICO_RES * iif(:BDCATEGORIA = 103, 0.02, 0.08), 2) into :WVALOR_FGTS_UNICO_RES;

     if ((COALESCE(WBASE_FGTS_UNICO_13, 0) > 0) AND (COALESCE(WVALOR_FGTS_UNICO_13, 0) = 0)) then
       select BDVALOR from TRUNCAR(:WBASE_FGTS_UNICO_13 * iif(:BDCATEGORIA = 103, 0.02, 0.08), 2) into :WVALOR_FGTS_UNICO_13;
 
     if (coalesce(wcodpres, 0) in (31, 103, 104, 105, 141)) then
        begin
          WBASE_MULTA = 0;
          WVALOR_MULTA = 0;
        end

     if (PRANUAL = TRUE) THEN
       begin
         WBASE_FGTS_DIGITAL      = 0;
         WVALOR_FGTS_DIGITAL     = 0;
         WBASE_FGTS_UNICO        = 0;
         WVALOR_FGTS_UNICO       = 0;
         WBASE_FGTS_DIGITAL_RES  = 0;
         WVALOR_FGTS_DIGITAL_RES = 0;
         WBASE_FGTS_UNICO_RES    = 0;
         WVALOR_FGTS_UNICO_RES   = 0;
         WBASE_FGTS_UNICO_IND    = 0;
         WVALOR_FGTS_UNICO_IND   = 0;
       end
     else
       BEGIN
         WBASE_FGTS_UNICO        = WBASE_FGTS_UNICO  + WBASE_FGTS_UNICO_13;
         WVALOR_FGTS_UNICO       = WVALOR_FGTS_UNICO + WVALOR_FGTS_UNICO_13;
         WBASE_FGTS_DIGITAL_13   = 0;
         WVALOR_FGTS_DIGITAL_13  = 0;
         WBASE_FGTS_UNICO_13     = 0;
         WVALOR_FGTS_UNICO_13    = 0;

         if (WGRRFPRES = 0) then
           BEGIN
             WBASE_FGTS_UNICO      = WBASE_FGTS_UNICO  + WBASE_FGTS_UNICO_RES + WBASE_FGTS_GRRF;
             WVALOR_FGTS_UNICO     = WVALOR_FGTS_UNICO + WVALOR_FGTS_UNICO_RES + WVALOR_FGTS_GRRF;
             WBASE_FGTS_UNICO_RES  = 0;
             WVALOR_FGTS_UNICO_RES = 0;
             WBASE_MULTA = 0;
             WVALOR_MULTA = 0;
           END
         if (WGRRFPRES = 2) then
           BEGIN
             if (WTIPOEVT = 34) then
               BEGIN
                 WBASE_FGTS_UNICO_RES  = WBASE_FGTS_UNICO_RES  + WBASE_FGTS_GRRF;
                 WVALOR_FGTS_UNICO_RES = WVALOR_FGTS_UNICO_RES + WVALOR_FGTS_GRRF;
               END
             if (WTIPOEVT = 11) then
               BEGIN
                 WBASE_FGTS_UNICO      = WBASE_FGTS_UNICO  + WBASE_FGTS_GRRF;
                 WVALOR_FGTS_UNICO     = WVALOR_FGTS_UNICO + WVALOR_FGTS_GRRF;
               END
           END
       END

     WBASE_SALDO  = (COALESCE(WBASE_FGTS_UNICO,0)  + COALESCE(WBASE_FGTS_UNICO_RES,0)  + COALESCE(WBASE_FGTS_UNICO_13,0)  + COALESCE(WBASE_FGTS_UNICO_IND,0)  + COALESCE(WBASE_MULTA,0))  - (COALESCE(WBASE_FGTS_DIGITAL,0)  + COALESCE(WBASE_FGTS_DIGITAL_RES,0)  + COALESCE(WBASE_FGTS_DIGITAL_13,0)  + COALESCE(WBASE_FGTS_DIGITAL_IND,0)  + COALESCE(WBASE_MULTA_FD,0));
     WVALOR_SALDO = (COALESCE(WVALOR_FGTS_UNICO,0) + COALESCE(WVALOR_FGTS_UNICO_RES,0) + COALESCE(WVALOR_FGTS_UNICO_13,0) + COALESCE(WVALOR_FGTS_UNICO_IND,0) + COALESCE(WVALOR_MULTA,0)) - (COALESCE(WVALOR_FGTS_DIGITAL,0) + COALESCE(WVALOR_FGTS_DIGITAL_RES,0) + COALESCE(WVALOR_FGTS_DIGITAL_13,0) + COALESCE(WVALOR_FGTS_DIGITAL_IND,0) + COALESCE(WVALOR_MULTA_FD,0));

     --Solicitação #201548
     if ((WBASE_SALDO > 0) or (WVALOR_SALDO > 0)) THEN
       BDEXISTEDIFERENCA = 1;

     BDCALCFGTSMESANT = COALESCE(WCALCFGTSANT, FALSE);
     BDBASE_FGTS_DIGITAL = COALESCE(WBASE_FGTS_DIGITAL,0);
     BDBASE_FGTS_DIGITAL_RES = COALESCE(WBASE_FGTS_DIGITAL_RES,0);
     BDBASE_FGTS_DIGITAL_13 = COALESCE(WBASE_FGTS_DIGITAL_13,0);
     BDBASE_FGTS_DIGITAL_IND = COALESCE(WBASE_FGTS_DIGITAL_IND,0);
     BDBASE_FGTS_UNICO_13 = COALESCE(WBASE_FGTS_UNICO_13,0);
     BDVALOR_FGTS_UNICO_13 = COALESCE(WVALOR_FGTS_UNICO_13,0);

     if ((BDBASE_FGTS_DIGITAL_RES > 0) or (BDBASE_FGTS_DIGITAL_IND > 0))  then
       BEGIN
         BDBASE_FGTS_UNICO = COALESCE(WBASE_FGTS_UNICO,0);
         BDBASE_FGTS_UNICO_RES = COALESCE(WBASE_FGTS_UNICO_RES,0);
         BDBASE_FGTS_UNICO_IND = COALESCE(WBASE_FGTS_UNICO_IND,0);
         BDVALOR_FGTS_UNICO = COALESCE(WVALOR_FGTS_UNICO,0);
         BDVALOR_FGTS_UNICO_RES = COALESCE(WVALOR_FGTS_UNICO_RES,0);
         BDVALOR_FGTS_UNICO_IND = COALESCE(WVALOR_FGTS_UNICO_IND,0);
       END
     ELSE
       BEGIN
         BDBASE_FGTS_UNICO = COALESCE(WBASE_FGTS_UNICO,0)+COALESCE(WBASE_FGTS_UNICO_RES,0)+COALESCE(WBASE_FGTS_UNICO_IND,0);
         BDBASE_FGTS_UNICO_RES = 0;
         BDBASE_FGTS_UNICO_IND = 0;
         BDVALOR_FGTS_UNICO = COALESCE(WVALOR_FGTS_UNICO,0)+COALESCE(WVALOR_FGTS_UNICO_RES,0)+COALESCE(WVALOR_FGTS_UNICO_IND,0);
         BDVALOR_FGTS_UNICO_RES = 0;
         BDVALOR_FGTS_UNICO_IND = 0;
       END


     BDVALOR_FGTS_DIGITAL = COALESCE(WVALOR_FGTS_DIGITAL,0);
     BDVALOR_FGTS_DIGITAL_RES = COALESCE(WVALOR_FGTS_DIGITAL_RES,0);
     BDVALOR_FGTS_DIGITAL_IND = COALESCE(WVALOR_FGTS_DIGITAL_IND,0);
     BDVALOR_FGTS_DIGITAL_13 = COALESCE(WVALOR_FGTS_DIGITAL_13,0);

     BDBASE_MULTA_FD = COALESCE(WBASE_MULTA_FD,0);
     BDVALOR_MULTA_FD = COALESCE(WVALOR_MULTA_FD,0);


     BDBASE_MULTA_UNICO = COALESCE(WBASE_MULTA,0);
     BDVALOR_MULTA_UNICO = COALESCE(WVALOR_MULTA,0);

     suspend;
  end
end^

create or alter procedure SP_RETORNA_INSS_ES_AUT (
    PRCODEMP integer,
    PRCODTER integer,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODTER integer,
    BDBASEINSSES numeric(18,2),
    BDVALORINSSES numeric(18,2),
    BDVRCPSEG numeric(18,2),
    BDSESTES numeric(18,2),
    BDSENATES numeric(18,2),
    BDCTS5001 integer,
    BDIND13PIS integer,
    BDTPVALORPISPASEP integer,
    BDVALORPISPASEP numeric(18,6),
    BDVALORPISPASEP13 numeric(18,6),
    BDVERSAOLAYOUTESOCIAL varchar(10))
as
declare variable WSQL varchar(8000);
declare variable WVALOR numeric(18,2);
declare variable WTPVALOR integer;
declare variable WIND13PIS integer;
declare variable WTPVALORPISPASEP integer;
declare variable WVALORPISPASEP numeric(18,6);
declare variable WVERSAOLAYOUTESOCIAL varchar(10);
begin
  BDCODEMP = PRCODEMP;
  BDCODTER = PRCODTER;
  BDBASEINSSES = 0;
  BDVALORINSSES = 0;
  BDVRCPSEG = 0;
  BDSESTES = 0;
  BDSENATES = 0;
  BDCTS5001 = 100;

  WIND13PIS = -111;
  WTPVALORPISPASEP = -111;
  WVALORPISPASEP = 0;
  WVERSAOLAYOUTESOCIAL = '';

  WSQL = ' select CP.BDVALOR, '||
                 ' case '||
                 '   when (ACP.BDCODCOL is not distinct from ACP.BDCODTER) then CP.BDVRCPSEG '||
                 '   else 0  '||
                 ' end BDVRCPSEG, CP.BDTPVALOR, CP.BDCTS5001, CP.BDIND13PIS, CP.BDTPVALORPISPASEP, CP.BDVALORPISPASEP, CP.BDVERSAOLAYOUTESOCIAL '||
          ' from VRH_ESOCIAL_INFOBASECS_TER CP  '||
          ' inner join VRH_ESOCIAL_TARQUIVO ACP on ACP.BDCODEMP = CP.BDCODEMP and '||
                ' ACP.BDCODTER = CP.BDCODTER and  '||
                '  ACP.BDCODIGO = CP.BDCODEVT  '||
          ' where CP.BDIND13 = 0 and '||
                 '(ACP.BDREFARQ = '||:PRREF||') and '||
                 ' ACP.BDSTATUS = 2 and '||
                 ' coalesce(ACP.BDAPURACAOANUAL, ''FALSE'') = ''FALSE'' and '||
                 '(CP.BDCODEMP = '||:PRCODEMP||') and (CP.BDCODTER = '||:PRCODTER||')'||
          ' order by ACP.BDCODIGO desc ';


   for execute statement wSQL into :wvalor, :BDVRCPSEG, :wtpvalor, :BDCTS5001, :WIND13PIS, :WTPVALORPISPASEP, :WVALORPISPASEP, :WVERSAOLAYOUTESOCIAL do
     begin
       if (wTPVALOR in (11, 12, 13, 14, 19)) then
          BDBASEINSSES = BDBASEINSSES + wvalor;
       else if (wTPVALOR = 21) then
          BDVALORINSSES = BDVALORINSSES + wvalor;
       else if (WtpValor = 22) then
          bdsestes = bdsestes + wvalor;
       else if (wtpvalor = 23) then
          bdsenates = bdsenates + wvalor;

       BDIND13PIS        = WIND13PIS;
       BDTPVALORPISPASEP = WTPVALORPISPASEP;

       if (WIND13PIS = 0) then
          BDVALORPISPASEP = coalesce(WVALORPISPASEP, 0);
       else
          BDVALORPISPASEP13 = coalesce(WVALORPISPASEP, 0);

       BDVERSAOLAYOUTESOCIAL = coalesce(WVERSAOLAYOUTESOCIAL, '');
     end

  suspend;
end^


CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_REF_AI0 FOR TCONF_CONTAS_ONLINE_REF
ACTIVE AFTER INSERT POSITION 0
AS
  declare variable wnada BIGINT;
begin
  SELECT first 1 GEN_ID(GEN_ALT_PLANOONLINE, 1) FROM RDB$DATABASE into :wnada;
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBAS_REF_AU0 FOR VRH_BASE_TVERBAS_REF
ACTIVE AFTER UPDATE POSITION 0
AS
  declare variable wnada BIGINT;
begin
  SELECT first 1 GEN_ID(GEN_ALTVERBAS, 1) FROM RDB$DATABASE into :wnada;
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBAS_REF_AD0 FOR VRH_BASE_TVERBAS_REF
ACTIVE AFTER DELETE POSITION 0
AS
  declare variable wnada BIGINT;
begin
  SELECT first 1 GEN_ID(GEN_ALTVERBAS, 1) FROM RDB$DATABASE into :wnada;
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TVERBAS_AD0 FOR VRH_BASE_TVERBAS
ACTIVE AFTER DELETE POSITION 0
AS
  declare variable wnada BIGINT;
begin
  wnada = GEN_ID(GEN_ALTVERBAS, 1);
end
^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_REF_AD0 FOR TCONF_CONTAS_ONLINE_REF
ACTIVE AFTER DELETE POSITION 0
AS
  declare variable wnada BIGINT;
begin
  SELECT first 1 GEN_ID(GEN_ALT_PLANOONLINE, 1) FROM RDB$DATABASE into :wnada;
end
^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_AD0 FOR TCONF_CONTAS_ONLINE
ACTIVE AFTER DELETE POSITION 0
AS
  declare variable wnada BIGINT;
begin
  wnada = GEN_ID(GEN_ALT_PLANOONLINE, 1);
end
^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_CC_BI0 FOR TCONF_CONTAS_ONLINE_CC
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable wnada BIGINT;
begin
  SELECT first 1 GEN_ID(GEN_ALT_PLANOONLINE, 1) FROM RDB$DATABASE into :wnada;
end
^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_CC_AU0 FOR TCONF_CONTAS_ONLINE_CC
ACTIVE AFTER UPDATE POSITION 0
AS
  declare variable wnada BIGINT;
begin
  SELECT first 1 GEN_ID(GEN_ALT_PLANOONLINE, 1) FROM RDB$DATABASE into :wnada;
end
^

CREATE OR ALTER TRIGGER TCONF_CONTAS_ONLINE_CC_AD0 FOR TCONF_CONTAS_ONLINE_CC
ACTIVE AFTER DELETE POSITION 0
AS
  declare variable wnada BIGINT;
begin
  SELECT first 1 GEN_ID(GEN_ALT_PLANOONLINE, 1) FROM RDB$DATABASE into :wnada;
end
^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_INFOIRRF_5002_BI0 FOR VRH_ESOCIAL_INFOIRRF_5002
ACTIVE BEFORE INSERT POSITION 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDSEQ is null) or (new.BDSEQ = 0)) then
  begin
    select coalesce((max(BDSEQ) + 1), 1)
    from VRH_ESOCIAL_INFOIRRF_5002
    where BDCODMATRIZ = new.BDCODMATRIZ and
          BDCPF = new.BDCPF and
          BDREF = new.BDREF

    into VCODIGO;

    new.BDSEQ = VCODIGO;
  end
end
^

CREATE OR ALTER TRIGGER VRHF_BASE_TPERIODORRA_BI0 FOR VRHF_BASE_TPERIODORRA
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE vi INTEGER;
begin
  /* Trigger text */
  IF ((NEW.BDCODPERRRA IS NULL) OR (NEW.BDCODPERRRA = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODPERRRA) + 1, 1) FROM VRHF_BASE_TPERIODORRA INTO :vi;
       NEW.BDCODPERRRA = vi;
     END
end^

CREATE OR ALTER TRIGGER VRHF_BASE_TPERIODORRA_ADV_BI0 FOR VRHF_BASE_TPERIODORRA_ADV
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE vi INTEGER;
begin
  /* Trigger text */
  IF ((NEW.BDCODADV IS NULL) OR (NEW.BDCODADV = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODADV) + 1, 1) FROM VRHF_BASE_TPERIODORRA_ADV WHERE BDCODPERRRA = NEW.BDCODPERRRA INTO :vi;
       NEW.BDCODADV = vi;
     END
end
^


/* Trigger: VSH_EMP_TCONF_TSEQREL_SEQ_BI */
CREATE OR ALTER TRIGGER VSH_EMP_TCONF_TSEQREL_SEQ_BI FOR VSH_EMP_TCONF_TSEQREL_SEQ
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  SELECT COALESCE(MAX(BDORDEM), 0) + 1
  FROM VSH_EMP_TCONF_TSEQREL_SEQ
  WHERE (BDCODAGENDAMENTO = NEW.BDCODAGENDAMENTO) AND
        (BDCODEMP = NEW.BDCODEMP) AND
        (BDCODPLANOSCHIP = NEW.BDCODPLANOSCHIP) AND
        (BDORDEMAGENDAMENTO = NEW.BDORDEMAGENDAMENTO)
  INTO NEW.BDORDEM;
END
^

CREATE OR ALTER trigger vrh_tassverb_biu0 for vrh_tassverb
active before insert or update position 0
AS
declare variable vQtd integer;
declare variable vSQL varchar(3000);
declare variable vnumcod varchar(10);
begin
  if (new.bddescori is not null) then
     begin
       select BDRETORNO from retira_acento(:new.bddescori) into new.bddescori;
       --select BDRETORNO from RETIRA_CHAR_ESPECIAL(:new.bddescori) into new.bddescori;
     end

  /* Trigger text */
  if ((new.bdclassvisual is null) and (new.bdcodori is not null)) then
     begin
       -- Verifica se tem a tabela de verbas auxiliar do visual convertida
       select count(*) bdqtd
       from RDB$RELATION_FIELDS
       where RDB$FIELD_NAME = 'BDCODIGO' and
             RDB$RELATION_NAME = 'TVERBAUX' into :vqtd;


       if ((vqtd > 0) and (upper(new.bdlayout) = upper('FOLHA SCI Visual Practice'))) then
          begin
            select BDNUMERO from SP_RETORNA_NUMEROS(new.bdcodori) into :vnumcod;

            vSQL = ' select first 1 v.bdclassificacao,va.bdcodnatureza, va.bdinss,va.bdcodinccp, va.bdfgts,va.bdcodincfgts, va.bdir,va.bdcodincirrf, v.bdmedadicnothoras, va.BDTIPOCODIGO '||
                   ' from tverbas v '||
                   ' join tverbaux va on (v.bdcodigo = va.bdcodigo and va.bdanomes = (select first 1 x.bdanomes from tverbaux x where x.bdcodigo = v.bdcodigo order by x.bdanomes desc)) '||
                   ' where v.bdcodigo = '||vnumcod;

            execute statement vSql into new.bdclassvisual, new.bdnatureza, new.bdinss, new.bdinssesocial, new.bdfgts, new.bdfgtsesocial, new.bdirrf, new.bdirrfesocial, new.BDMEDHORASADICNOT, new.BDTIPOCODVEER;

            if (coalesce(new.bdclassvisual,'') <> '') then
               begin
                 vSQL = ' select first 1 BDDESCRICAO from tverbas v  where v.bdclassificacao = '||''''||substring(new.bdclassvisual from 1 for 4)||'''';

                 execute statement vSql into new.bddesctitulo;
               end
          end
     end
end^

CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_BD2 FOR VRH_EMP_TCOLCON
ACTIVE BEFORE DELETE POSITION 0
as
begin
  /*Sol: #199518 - Julio Cesar - 19/04/2024
  A tabela VCT_EMPRESA_TSOLICITATAREFA possue campos (BDCODEMP, BDCODCOLVINC e BDCODCOL)
  para vincular uma tarefa a um colaborador.
  Ao excluir um colaborador, o processo vai setar os campo na VCT_EMPRESA_TSOLICITATAREFA para null
  sendo que o campo BDCODEMP faz parte da primary key da tabela VCT_EMPRESA_TSOLICITATAREFA.
  para contornar, antes da exclusão, a trigger vai setar apenas os campo BDCODCOLVINC e BDCODCOL para null*/
  
  update VCT_EMPRESA_TSOLICITATAREFA set BDCODCOLVINC = null where BDCODEMP = old.BDCODEMP and BDCODCOLVINC = old.BDCODCOL;
  update VCT_EMPRESA_TSOLICITATAREFA set BDCODCOL = null where BDCODEMP = old.BDCODEMP and BDCODCOL = old.BDCODCOL;

  update vct_empresa_docsgerados set bdcodcol = null where bdcodemp = old.bdcodemp and bdcodcol = old.bdcodcol;
  update vct_empresa_protodocsaida set bdcodcol = null where bdcodemp = old.bdcodemp and bdcodcol = old.bdcodcol;
end
^

CREATE OR ALTER trigger vrhf_emp_mv_aut_calc_bi0 for vrhf_emp_mv_aut_calc
active before insert position 0
AS
begin
  /* Trigger text */
  if (coalesce(new.bdsequencial,0) = 0) then
     begin
       new.bdsequencial = 1;
       select first 1 coalesce(bdsequencial,0)+1 from vrhf_emp_mv_aut_calc where bdcpf = :new.bdcpf order by bdsequencial desc into new.bdsequencial;
     end
end
^

CREATE OR ALTER procedure SP_ATU_DADOS_MV_ATU (
    PRCPF varchar(14),
    PRREFINI integer,
    PRREFIM integer)
as
declare variable WSQLSELECT varchar(3000);
declare variable WCODTER integer;
declare variable WCODEMP integer;
declare variable WCODSERV integer;
declare variable WDATASERV date;
declare variable WDATAPGT date;
declare variable WCODVER integer;
declare variable WVALOR numeric(15,6);
declare variable WTROCACHAVE varchar(100);
declare variable WCPF varchar(14);
declare variable WCPFANT varchar(14);
declare variable WCODEMPANT integer;
declare variable WCODTERANT integer;
declare variable WCODSERVANT integer;
declare variable WREFAPUINSS integer;
declare variable WREFAPUIRRF integer;
declare variable WBASEINSS numeric(15,6);
declare variable WTIPOVERBA integer;
declare variable WINCINSS integer;
declare variable WINCIRRF integer;
declare variable WBASEIRRF numeric(15,6);
declare variable WVALORSOMA numeric(15,6);
declare variable WCLASSVERBA varchar(20);
declare variable WVALORINSS numeric(15,6);
declare variable WVALORIR numeric(15,6);
declare variable WVALORDEP numeric(15,6);
declare variable WVALORDEPANT numeric(15,6);
declare variable WVALORPENSAO numeric(15,6);
declare variable WVALORSEST numeric(15,6);
declare variable WVALORSENAT numeric(15,6);
begin
/*
CPF PK
Sequencial PK
DATA PAGAMENTO
TIPO DE CALCULO (Campo inteiro que serve para saber que tipo de calculo é, como temos hoje na baixa de cálculos)
   {0 = Folha/Rescisão normal (BDCODEMP, BDCODCOL, BDREFERENCIA)
    1 = Folha/Rescisão por tomador (BDCODEMP, BDCODCOL, BDREFERENCIA, BDORDEM)
    2 = Intermitente (BDCODEMP, BDCODCOL, BDREFERENCIA, BDCODCONTRATO)
    3 = Intermitente por tomador (BDCODEMP, BDCODCOL, BDREFERENCIA, BDCODCONTRATO, BDORDEM)
    4 = Autonomos (BDCODEMP, BDCODCOL, BDCODCONTRATO)
    5 = Ferias (BDCODEMP, BDCODCOL, BDDATA, BDORDEM)
    6 = Adiantamento Salárial (BDCODEMP, BDCODCOL, BDDATA)
    7 = Folha/Rescisão complementar (BDCODEMP, BDCODCOL, BDREFERENCIA, BDREFCOMPLEMENTAR)
    8 = Folha/Rescisão complementar por tomador (BDCODEMP, BDCODCOL, BDREFERENCIA, BDREFCOMPLEMENTAR, BDORDEM)
    9 = Intermitente complementar (BDCODEMP, BDCODCOL, BDREFERENCIA, BDREFCOMPLEMENTAR, BDCODCONTRATO)
    10 = Intermitente complementar por tomador (BDCODEMP, BDCODCOL, BDREFERENCIA, BDREFCOMPLEMENTAR, BDCODCONTRATO, BDORDEM)
    11 = Folha Avulsa (BDCODEMP, BDCODCOL, BDORDEM, BDDATA)
    12 = ADIANTAMENTO 13º (BDCODEMP, BDCODCOL, BDREFERENCIA)
    13 = 13º SALÁRIO (BDCODEMP, BDCODCOL, BDREFERENCIA)
    14 = Complemento de 13º (BDCODEMP, BDCODCOL, BDREFERENCIA, BDREFCOMPLEMENTAR) 
   } 
bdCODEMP integer            - Código da empresa (Usado para identificar o calculo respectivo)
bdCODCOL integer          - Código do colaborador ou autonomos conforme cada calculo (Usado para identificar o calculo respectivo)
bdREFERENCIA integer        - Compentecia relacionada conforme cada calculo - representa chave da tabela do calculo (Usado para identificar o calculo respectivo)
bdORDEM integer            - Representar um sequencial para os calculos que precisão conforme detamento acima (Usado para identificar o calculo respectivo)
bdCODCONTRATO integer        - Representar o código de contrato para os calculos que precisão conforme detamento acima (Usado para identificar o calculo respectivo)
bdDATA date                - Representa a data para chave relacionada aos calculos quando necessários (Usado para identificar o calculo respectivo)
bdREFCOMPLEMENTAR integer    - Compentecia/Data complementar para os calculos complementares (Usado para identificar o calculo respectivo) 
bdREFAPUINSS integer        - Deve gravar neste campo qual a compentecia referente a apuração de INSS do calculo que deve ser usado nos multiplos vinculos ou multiplos contratos
bdREFAPUIRRF integer          - Deve gravar neste campo qual a compentecia referente a apuração de IRRF do calculo que deve ser usado nos multiplos vinculos ou multiplos contratos
bdBASEINSS numeric            - Vai gravar a base de INSS do calculo se tiver (Deve gravar o valor a base seja negativa ou possitiva)
bdVALORINSS numeric        - Vai gravar o valor de INSS do calculo se tiver (Deve gravar o valor a base seja negativa ou possitiva)
bdBASEIRRFBruta numeric    - Vai gravar a base de IRRF BRUTA sem descontar as deduções legais do calculo se tiver (Deve gravar o valor a base seja negativa ou possitiva)
bdVALORIRRF numeric        - Vai gravar o valor de IRRF sem descontar as deduções legais do calculo se tiver (Deve gravar o valor a base seja negativa ou possitiva)
bdDEPENDENTES numeric        - Vai gravar o valor de dependentes utilizado no calculo de IRRF (Deve gravar o valor a base seja negativa ou possitiva)
bdPENSAOALIM numeric        - Vai gravar o valor de pensão utilizado no calculo de IRRF (Deve gravar o valor a base seja negativa ou possitiva)
bdBASEINSS13 numeric       - Vai gravar a base de INSS 13 do calculo se tiver (Deve gravar o valor a base seja negativa ou possitiva)
bdVALORINSS13 numeric      - Vai gravar o valor de INSS 13 do calculo se tiver (Deve gravar o valor a base seja negativa ou possitiva)
bdBASEIRRFBruta13 numeric  - Vai gravar a base de IRRF 13 BRUTA sem descontar as deduções legais do calculo se tiver (Deve gravar o valor a base seja negativa ou possitiva)
bdVALORIRRF13 numeric      - Vai gravar o valor de IRRF 13 sem descontar as deduções legais do calculo se tiver (Deve gravar o valor a base seja negativa ou possitiva)
bdDEPENDENTES13 numeric    - Vai gravar o valor de dependentes 13 utilizado no calculo de IRRF (Deve gravar o valor a base seja negativa ou possitiva)
bdPENSAOALIM13 numeric    - Vai gravar o valor de pensão 13 utilizado no calculo de IRRF (Deve gravar o valor a base seja negativa ou possitiva)


*/  /* Procedure Text */
  wsqlselect = 'select case when char_length(TER.BDCGCTER) > 14 then  TERRH.bdcpfmeiter else TER.BDCGCTER end, CALC.BDCODTER, CALC.BDCODEMP, CALC.BDCODSERV, serv.BDDATASERV, serv.BDDATAPAGSERV, VERBAS.BDCODVER, VERBAS.BDVALOR, '||
               ' calc.BDVALORDEP '||
               ' from VRHF_BASE_CALC_TERC CALC '||
               ' join VRH_BASE_TSERVTERC serv on  (CALC.BDCODTER = serv.BDCODTER and CALC.BDCODEMP = serv.BDCODEMP and CALC.BDCODSERV = serv.BDCODSERV) '||
               ' join VRHF_BASE_ITEMS_CALCTERC VERBAS on (CALC.BDCODTER = VERBAS.BDCODTER and CALC.BDCODEMP = VERBAS.BDCODEMP and CALC.BDCODSERV = VERBAS.BDCODSERV) '||
               ' JOIN TTERCEIRO TER ON (TER.BDCODTER = CALC.BDCODTER)'||
               ' JOIN TTERCEIRO_RH TERRH on (TERRH.BDCODTER = CALC.BDCODTER)'||

               ' LEFT JOIN vrhf_emp_mv_aut_calc AUT ON (AUT.bdcodter = CALC.bdcodter AND AUT.bdcodemp = CALC.bdcodemp AND AUT.bdcodcontrato = CALC.bdcodserv)';

  wsqlselect = wsqlselect||' WHERE AUT.bdcodter IS NULL';

  if (prcpf is not null) then
     begin
       wsqlselect = wsqlselect||'where ter.BDCGCTER = '||''''||prcpf||'''';

       if (prRefIni is not null) then
          begin
             -- filtros para INSS
             wsqlselect = wsqlselect||' and (((calc.bdrefinssserv >= '||prRefIni||')';

             if (prrefim is not null) then
                wsqlselect = wsqlselect||' and (calc.bdrefinssserv <= '||prrefim||')';
             wsqlselect = wsqlselect||') or ';

             wsqlselect = wsqlselect||' and ((calc.bdrefirserv >= '||prRefIni||')';

             if (prrefim is not null) then
                wsqlselect = wsqlselect||' and (calc.bdrefirserv <= '||prrefim||')';
             wsqlselect = wsqlselect||'))';
          end

     end

  wsqlselect = wsqlselect||' order by CALC.BDCODEMP, serv.BDDATASERV, serv.BDDATAPAGSERV, CALC.BDCODTER, CALC.BDCODSERV ';
--  suspend;

  WTROCACHAVE = '';
  WBASEINSS = 0;
  wbaseirrf = 0;
  wvalorinss = 0;
  wvalorir = 0;
  wvalorpensao = 0;
  wvalorsest = 0;
  wvalorsenat = 0;
  for execute statement wsqlselect into
     :wcpf, :wCODTER, :wCODEMP, :wCODSERV, :wDATASERV, :wdatapgt, :wCODVER, :wVALOR, :wvalordep  do
    begin
       if ((WTROCACHAVE <> wcodter||'.'||wcodserv||'.'||wcodemp)) then
          begin
             if (WTROCACHAVE <> '') then
                begin
                   UPDATE OR INSERT INTO VRHF_EMP_MV_AUT_CALC
                     (BDCPF, BDDATAPAGAMENTO, BDTIPOCALC, BDCODEMP, BDCODTER, BDCODCONTRATO,
                      BDREFAPUINSS, BDBASEINSS, BDVALORINSS,
                      BDREFAPUIRRF, BDBASEBRUTAIR, BDVALORIR, BDDEPENDENTES, BDPENSAO, BDVALSEST, BDVALSENAT)
                   VALUES (
                      :wcpfant, :wdatapgt, 4, :wcodempant, :wcodterant, :wcodservant, -- Chaves
                      :wrefapuinss, :wbaseinss, :wvalorinss, -- INSS
                      :wrefapuirrf, :wbaseirrf, :wvalorir, :wvalordepant, :wvalorpensao, :wvalorsest, :wvalorsenat) -- IR
                   matching (bdcpf,BDTIPOCALC,bdcodemp,bdcodter,BDCODCONTRATO);
                end

            select bdaaaamm from AAAAMM(:wdataserv) into :wrefapuinss;
            select bdaaaamm from AAAAMM(:wdatapgt) into :wrefapuirrf;

            wcpfant = wcpf;
            wcodempant = wcodemp;
            wcodterant = wcodter;
            wcodservant = wcodserv;
            wvalordepant = wvalordep;
            wbaseinss = 0;
            wbaseirrf = 0;
            wvalorinss = 0;
            wvalorir = 0;
            wvalorpensao = 0;
            wvalorsest = 0;
            wvalorsenat = 0;
            WTROCACHAVE = wcodter||'.'||wcodserv||'.'||wcodemp;
          end

       select first 1 vr.bdtipocodver,vr.bdinssver,vr.bdirver, v.bdclaver
       from vrh_base_tverbas_ref vr
       join vrh_base_tverbas v on (vr.bdcodver = v.bdcodver)
       where vr.bdcodver = :wcodver and vr.bdrefver <= :wrefapuinss into
       :wtipoverba, :wincinss, :wincirrf, :wclassverba;

       wvalorsoma = wvalor;
       if (wtipoverba in (1,3)) then
          wvalorsoma = wvalor * -1;

       if (wincinss = 1) then
          wbaseinss = wbaseinss + wvalorsoma;

       if (substring(wclassverba from 1 for 9) = '9.010.0.A') then
          wvalorsenat = wvalorsenat + wvalor;
       else
       if (substring(wclassverba from 1 for 9) = '9.010.0.9') then
          wvalorsest = wvalorsest + wvalor;
       else
       if (substring(wclassverba from 1 for 9) = '9.010.0.0') then
          wvalorinss = wvalorinss + wvalor;
       else
       if (substring(wclassverba from 1 for 9) = '9.010.1.0') then
          wvalorir = wvalorir + wvalor;
       else
       if (substring(wclassverba from 1 for 7) = '0.030.0') then
          wvalorpensao = wvalorpensao + wvalor;
       else
       if (wincirrf = 1) then
          wbaseirrf = wbaseirrf + wvalorsoma;

    end


    if ((WTROCACHAVE <> '')) then
      begin
         if (WTROCACHAVE <> '') then
            begin
              UPDATE OR INSERT INTO VRHF_EMP_MV_AUT_CALC
                (BDCPF, BDDATAPAGAMENTO, BDTIPOCALC, BDCODEMP, BDCODTER, BDCODCONTRATO,
                 BDREFAPUINSS, BDBASEINSS, BDVALORINSS,
                 BDREFAPUIRRF, BDBASEBRUTAIR, BDVALORIR, BDDEPENDENTES, BDPENSAO, BDVALSEST, BDVALSENAT)
              VALUES (
                 :wcpfant, :wdatapgt, 4, :wcodempant, :wcodterant, :wcodservant, -- Chaves
                 :wrefapuinss, :wbaseinss, :wvalorinss, -- INSS
                 :wrefapuirrf, :wbaseirrf, :wvalorir, :wvalordepant, :wvalorpensao, :wvalorsest, :wvalorsenat) -- IR
              matching (bdcpf,BDTIPOCALC,bdcodemp,bdcodter,BDCODCONTRATO);
            end
      end

end^

/* Restore proc. body: SP_VRHF_PROCESSO_AUMENTO */
create or alter procedure SP_VRHF_PROCESSO_AUMENTO (
    PREMP varchar(30000),
    PRCOL varchar(30000),
    PRDATAHAUM date,
    PRDATAEFEITO date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATAHAUM date,
    BDDATAEFEITOHAUM date,
    BDSALBASEAUMSAUM numeric(18,6),
    BDCODMAS integer,
    BDDESCMAS varchar(50),
    BDSALBASEDESCAUM numeric(18,6))
as
declare variable WSQL varchar(32000);
declare variable WSQL2 varchar(6000);
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WJOINCOL varchar(300);
begin
  /* Procedure Text */

  wJOINCOL = '';

  if (trim(PRCOL) = 'TEMP_FILTRO_COLCON_REL') then
    wJOINCOL = ' join TEMP_FILTRO_COLCON_REL FCOL on FCOL.BDCODEMP = C.BDCODEMP and FCOL.BDCODCOL = C.BDCODCOL ';


  WSQL = 'select C.BDCODEMP, C.BDCODCOL '||
         'from VRH_EMP_TCOLCON C '||
         wJOINCOL||
         'inner join VW_EMPRESAS_USU USU on USU.BDCODEMP = C.BDCODEMP ';
  --         'join TEMPRESAS E on (E.BDCODEMP = C.BDCODEMP) ';

  if ((PREMP is not null) and (PREMP <> '')) then
     begin
       WSQL = WSQL||' WHERE '||PREMP;

       if ((PRCOL is not null) and (PRCOL <> '') and (wJOINCOL = '')) then
          WSQL = WSQL||' AND '||PRCOL;
     end

  WSQL = WSQL||' ORDER BY C.BDCODEMP, C.BDCODCOL ';

  BDCODEMP = 0;
  BDCODCOL = 0;
  BDDATAHAUM = null;
  BDDATAEFEITOHAUM = null;
  BDSALBASEAUMSAUM = 0;
  BDSALBASEDESCAUM = 0;
  BDCODMAS = 0;
  BDDESCMAS = null;

  for execute statement WSQL
  into :WCODEMP, :WCODCOL
     do
     begin
        BDCODEMP = 0;
        BDCODCOL = 0;
        BDDATAHAUM = null;
        BDDATAEFEITOHAUM = null;
        BDSALBASEAUMSAUM = 0;
        BDSALBASEDESCAUM = 0;
        BDCODMAS = 0;
        BDDESCMAS = null;

        -- AUMENTO SOBRE AUMENTO
        WSQL2 = ' SELECT FIRST 1 BDCODEMP, BDCODCOL, BDDATAHAUM, BDDATAEFEITOHAUM, BDSALBASEHAUM, BDCODMAS, BDDESCMAS FROM ( '||

                'select H.BDCODEMP, H.BDCODCOL, H.BDDATACOL BDDATAHAUM, H.BDDATAEFEITO BDDATAEFEITOHAUM, H.BDSALBASECOL BDSALBASEHAUM, H.BDCODMAS, M.BDDESCMAS '||
                'from VRH_EMP_TCOLCON_CALCDIA H '||

                'JOIN (SELECT X.BDCODEMP, X.BDCODCOL, X.BDDATACOL, X.BDDATAEFEITO FROM VRH_EMP_TCOLCON_CALCDIA X '||
                '      WHERE X.BDCODEMP = '||WCODEMP||' and '||
                '            X.BDCODCOL = '||WCODCOL||' and '||
                '            X.BDDATACOL <= (SELECT COALESCE((SELECT MAX(D1.BDDATACOL) '||
                '                                             FROM VRH_EMP_TCOLCON_CALCDIA D1 '||
                '                                             WHERE D1.BDCODEMP = COL.BDCODEMP AND '||
                '                                                   D1.BDCODCOL = COL.BDCODCOL AND '||
                '                                                   D1.BDDATACOL <= '''||PRDATAHAUM||'''), '||
                '                                            (SELECT MIN(D2.BDDATACOL) '||
                '                                             FROM VRH_EMP_TCOLCON_CALCDIA D2 '||
                '                                             WHERE D2.BDCODEMP = COL.BDCODEMP AND '||
                '                                                   D2.BDCODCOL = COL.BDCODCOL)) '||
                '                            FROM VRH_EMP_TCOLCON COL '||
                '                            WHERE COL.BDCODEMP = X.BDCODEMP AND '||
                '                                  COL.BDCODCOL = X.BDCODCOL) '||
                '      ORDER BY X.BDDATACOL DESC '||
                ') FILTRO_DATAHAUM ON (H.BDCODEMP = FILTRO_DATAHAUM.BDCODEMP AND H.BDCODCOL = FILTRO_DATAHAUM.BDCODCOL AND H.BDDATACOL = FILTRO_DATAHAUM.BDDATACOL AND H.BDDATAEFEITO = FILTRO_DATAHAUM.BDDATAEFEITO) '||

                'left outer join VRH_BASE_TMOTAUMSAL M on M.BDCODMAS = H.BDCODMAS '||
                'where H.BDCODEMP = '||WCODEMP||' and '||
                '      H.BDCODCOL = '||WCODCOL||'  '||

                ' UNION '||

                'select H.BDCODEMP, H.BDCODCOL, H.BDDATAHAUM, H.BDDATAEFEITOHAUM, H.BDSALBASEHAUM, H.BDCODMAS, M.BDDESCMAS '||
                'from VRH_EMP_THIST_AUM H '||

                'JOIN (SELECT X.BDCODEMP, X.BDCODCOL, X.BDDATAHAUM, X.BDDATAEFEITOHAUM, X.BDCODHAUM FROM VRH_EMP_THIST_AUM X '||
                '      WHERE X.BDCODEMP = '||WCODEMP||' and '||
                '            X.BDCODCOL = '||WCODCOL||' and '||
                '            X.BDDATAHAUM <= (SELECT COALESCE((SELECT MAX(D1.BDDATAHAUM) '||
                '                                              FROM VRH_EMP_THIST_AUM D1 '||
                '                                              WHERE D1.BDCODEMP = COL.BDCODEMP AND '||
                '                                                    D1.BDCODCOL = COL.BDCODCOL AND '||
                '                                                    D1.BDDATAHAUM <= '''||PRDATAHAUM||'''), '||
                '                                             (SELECT MIN(D2.BDDATAHAUM) '||
                '                                              FROM VRH_EMP_THIST_AUM D2 '||
                '                                              WHERE D2.BDCODEMP = COL.BDCODEMP AND '||
                '                                                    D2.BDCODCOL = COL.BDCODCOL)) '||
                '                             FROM VRH_EMP_TCOLCON COL '||
                '                             WHERE COL.BDCODEMP = X.BDCODEMP AND '||
                '                                   COL.BDCODCOL = X.BDCODCOL) '||
                '      ORDER BY X.BDDATAHAUM DESC '||
                ') FILTRO_DATAHAUM ON (H.BDCODEMP = FILTRO_DATAHAUM.BDCODEMP AND H.BDCODCOL = FILTRO_DATAHAUM.BDCODCOL AND H.BDDATAHAUM = FILTRO_DATAHAUM.BDDATAHAUM AND H.BDDATAEFEITOHAUM = FILTRO_DATAHAUM.BDDATAEFEITOHAUM AND H.bdcodhaum = FILTRO_DATAHAUM.BDCODHAUM) '||

                'left outer join VRH_BASE_TMOTAUMSAL M on M.BDCODMAS = H.BDCODMAS '||
                'where H.BDCODEMP = '||WCODEMP||' and '||
                '      H.BDCODCOL = '||WCODCOL||'  '||

                ' ) '||
                -- Buscar os aumentos com efeitos posteriores ao aumento atual
                ' WHERE BDDATAEFEITOHAUM >= '''||PRDATAEFEITO||''' '||
                ' ORDER BY BDCODEMP, BDCODCOL, BDDATAHAUM, BDDATAEFEITOHAUM DESC, BDSALBASEHAUM DESC ';


        EXECUTE STATEMENT WSQL2 INTO :BDCODEMP, :BDCODCOL, :BDDATAHAUM, :BDDATAEFEITOHAUM, :BDSALBASEAUMSAUM, :BDCODMAS, :BDDESCMAS;

        IF (BDDATAHAUM IS NOT NULL) THEN
           BEGIN
            -- DESCONTO SOBRE AUMENTO
            WSQL2 = ' select FIRST 1 BDSALBASEHAUM from ( '||
                    
                    'select H.BDCODEMP, H.BDCODCOL, H.BDDATACOL BDDATAHAUM, H.BDDATAEFEITO BDDATAEFEITOHAUM, H.BDSALBASECOL BDSALBASEHAUM, H.BDCODMAS, M.BDDESCMAS '||
                    'from VRH_EMP_TCOLCON_CALCDIA H '||
                    'left outer join VRH_BASE_TMOTAUMSAL M on M.BDCODMAS = H.BDCODMAS '||
                    'where H.BDCODEMP = '||WCODEMP||' and '||
                    '      H.BDCODCOL = '||WCODCOL||'  '||

                    ' UNION '||
    
                    'select H.BDCODEMP, H.BDCODCOL, H.BDDATAHAUM, H.BDDATAEFEITOHAUM, H.BDSALBASEHAUM, H.BDCODMAS, M.BDDESCMAS '||
                    'from VRH_EMP_THIST_AUM H '||
                    'left outer join VRH_BASE_TMOTAUMSAL M on M.BDCODMAS = H.BDCODMAS '||
                    'where H.BDCODEMP = '||WCODEMP||' and '||
                    '      H.BDCODCOL = '||WCODCOL||'  '||

                    ') A '||
                    'where A.BDCODEMP = '||WCODEMP||' and '||
                    '      A.BDCODCOL = '||WCODCOL||' and '||
                    '      A.BDDATAHAUM < '''||BDDATAEFEITOHAUM||''' '||
                    ' ORDER BY BDCODEMP, BDCODCOL, BDDATAHAUM DESC, BDDATAEFEITOHAUM DESC, BDSALBASEHAUM DESC ';
    
            EXECUTE STATEMENT WSQL2 INTO :BDSALBASEDESCAUM;

            IF (BDSALBASEDESCAUM = 0) THEN
               BEGIN
                 WSQL2 = 'SELECT FIRST 1 CALC.BDSALBASECOL '||
                         'FROM VRH_EMP_TCOLCON_CALCDIA CALC '||
                         'left outer join VRH_BASE_TMOTAUMSAL M on M.BDCODMAS = CALC.BDCODMAS '||
                         'where CALC.BDCODEMP = '||WCODEMP||' and '||
                         '      CALC.BDCODCOL = '||WCODCOL||' '||
                         'ORDER BY CALC.BDCODEMP, CALC.BDCODCOL, CALC.BDDATAEFEITO, CALC.BDSALBASECOL, CALC.BDDATACOL ';

                 EXECUTE STATEMENT WSQL2 INTO :BDSALBASEDESCAUM;
               END

           END
        ELSE
           BEGIN
             WSQL2 = 'SELECT FIRST 1 CALC.BDCODEMP, CALC.BDCODCOL, CALC.BDDATACOL, CALC.BDDATAEFEITO, CALC.BDSALBASECOL, CALC.BDCODMAS, M.BDDESCMAS '||
                     'FROM VRH_EMP_TCOLCON_CALCDIA CALC '||
                     'left outer join VRH_BASE_TMOTAUMSAL M on M.BDCODMAS = CALC.BDCODMAS '||
                     'where CALC.BDCODEMP = '||WCODEMP||' and '||
                     '      CALC.BDCODCOL = '||WCODCOL||' '||
                     'ORDER BY CALC.BDCODEMP, CALC.BDCODCOL, CALC.BDDATAEFEITO, CALC.BDSALBASECOL, CALC.BDDATACOL ';

             EXECUTE STATEMENT WSQL2 INTO :BDCODEMP, :BDCODCOL, :BDDATAHAUM, :BDDATAEFEITOHAUM, :BDSALBASEAUMSAUM, :BDCODMAS, :BDDESCMAS;

             BDSALBASEDESCAUM = BDSALBASEAUMSAUM;
           END

        SUSPEND;
     end
end^

create or alter procedure SP_REL_PROVISAO13 (
    PRTABELAPRINCIPAL varchar(50),
    PRSEMAD13 integer,
    PRSITCOL integer,
    PRREF integer,
    PRDATAINI date,
    PRDATAFIM date,
    PREMP varchar(30000),
    PRCOL varchar(30000),
    PRCC varchar(10000) = null,
    PRCLASSE varchar(1000) = null,
    PRSINDICATO varchar(10000) = null,
    PRFUNCAO varchar(10000) = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDLINHAP13 integer,
    BDREFP13 integer,
    BDORDEMCCP13 integer,
    BDPLANOCC integer,
    BDCODCENTRO integer,
    BDORDEMDET integer,
    BDSALBASEP13 numeric(18,6),
    BDADICIONAISP13 numeric(18,6),
    BDMEDIASP13 numeric(18,6),
    BDOUTRASBASESP13 numeric(18,6),
    BDCODTPCC integer,
    BDVLR13SALP13 numeric(18,6),
    BDFGTSP13 numeric(18,6),
    BDINSSP13 numeric(18,6),
    BDTERCFPASP13 numeric(18,6),
    BDCNAERATP13 numeric(18,6),
    BDRATAPOP13 numeric(18,6),
    BDPISP13 numeric(18,6),
    BDBASEFGTSP13 numeric(18,6),
    BDBASEINSSP13 numeric(18,6),
    BDRESCISAOP13 varchar(5),
    BDBASEPISP13 numeric(18,6),
    BDPROPP13 integer,
    BDOBSERVACAO varchar(3000),
    BDTOTP13 numeric(18,6),
    BDPORTOMADORP13 varchar(5),
    BDORDEM varchar(5),
    BDNOMEMP DM_BDNOMEMP,
    BDTIPOEMIGUIAS integer,
    BDNOMCOLUPPER DM_BDNOMCOL,
    BDNOMCOL DM_BDNOMCOL,
    BDDATAADMCOL date,
    BDDATARESCISAO date,
    BDCODCLA integer,
    BDCODSINTRAB integer,
    BDCODTFUC integer,
    BDNOMETOM varchar(70),
    BDCTALON varchar(20),
    BDNOMCTA varchar(40),
    BDCENTROTPCC varchar(10))
as
declare variable WSQL varchar(30000);
declare variable WWHERE varchar(30000);
declare variable WEMPANT varchar(20);
declare variable WCOLANT varchar(20);
declare variable WCCANT varchar(20);
declare variable WREFTRF integer;
declare variable WREFTRFSAI integer;
declare variable WBDVLR13SALP13_S13_MES numeric(15,6);
declare variable WBQTD_S13_MES integer;
declare variable WBDVLR13SALP13_RESC13_MES numeric(15,6);
declare variable WBQTD_RESC13_MES integer;
declare variable WBDVLR13SALP13_A13 numeric(15,6);
declare variable WBDVLR13SALP13_A13MES numeric(15,6);
declare variable WBQTD_A13 integer;
declare variable WBDVLR13SALP13_A13_MES numeric(15,6);
declare variable WBQTD_A13_MES integer;
declare variable WVAL_A13_CALC numeric(15,6);
declare variable WVAL_ARRE_PROV_A13_CALC numeric(15,6);
declare variable WVAL_ARRE_DESC_A13_CALC numeric(15,6);
declare variable WVAL_A13_CALCMES numeric(15,6);
declare variable WVAL_ARRE_PROV_A13_CALCMES numeric(15,6);
declare variable WVAL_ARRE_DESC_A13_CALCMES numeric(15,6);
declare variable WVAL_A13_QTD_CALC integer;
declare variable WVAL_A13_QTD_CALCMES integer;
declare variable WVAL_A13_FICHA numeric(15,6);
declare variable WVAL_A13_FICHA_QTD integer;
declare variable WVAL_A13_MAT numeric(15,6);
declare variable WVALORAJUSTE_LINHA numeric(15,6);
declare variable WVALOR_LINHA numeric(15,6);
declare variable WPORCC varchar(5) = 'FALSE';
declare variable WORDEMCC integer;
declare variable WCODHIST INTEGER;
declare variable WLISTACODHIST varchar(5000);
declare variable WPERCENTCC numeric(15,6);
declare variable WTEMPOTRAB integer;
declare variable WSQLAUX varchar(30000);
begin
  /* Procedure Text */

  if (upper(PRTABELAPRINCIPAL) = 'VW_VRHF_EMP_TPROVISAO13_CC') then
    WPORCC = 'TRUE';

  wSql = 'select P13.BDCODEMP, '||
                 'P13.BDCODCOL, '||
                 'P13.BDLINHAP13, ' ||
                 'P13.BDREFP13, ' ||
                 'P13.BDORDEMCCP13, ' ||
                 'P13.BDPLANOCC, ' ||
                 'P13.BDCODCENTRO, ' ||
                 'SUM(P13.BDSALBASEP13) BDSALBASEP13, ' ||
                 'SUM(P13.BDADICIONAISP13) BDADICIONAISP13, ' ||
                 'SUM(P13.BDMEDIASP13) BDMEDIASP13, ' ||
                 'SUM(P13.BDOUTRASBASESP13) BDOUTRASBASESP13, ' ||
                 'P13.BDCODTPCC, ' ||
                 'SUM(P13.BDVLR13SALP13) BDVLR13SALP13, '||
                 'SUM(P13.BDFGTSP13) BDFGTSP13, ' ||
                 'SUM(P13.BDINSSP13) BDINSSP13, ' ||
                 'SUM(P13.BDTERCFPASP13) BDTERCFPASP13, ' ||
                 'SUM(P13.BDCNAERATP13) BDCNAERATP13, ' ||
                 'SUM(P13.BDRATAPOP13) BDRATAPOP13, ' ||
                 'SUM(P13.BDPISP13) BDPISP13, ' ||
                 'SUM(P13.BDBASEFGTSP13) BDBASEFGTSP13, ' ||
                 'SUM(P13.BDBASEINSSP13) BDBASEINSSP13, ' ||
                 'P13.BDRESCISAOP13, ' ||
                 'SUM(P13.BDBASEPISP13) BDBASEPISP13, ' ||
                 'P13.BDPROPP13, ' ||
                 'p13.BDOBSERVACAO, ' ||
                 'SUM(P13.BDTOTP13) BDTOTP13, ' ||
                 'P13.BDPORTOMADORP13 ';



  wSql = wSql || ' from ' || prtabelaprincipal || ' P13 ';

  if (coalesce(premp,'') <> '') then
     wSql = wSql || ' where ' || replace(upper(prEmp), 'BDCODEMP', 'P13.BDCODEMP');

  if (coalesce(prCol,'') <> '') then
     wSql = wSql || ' and ' || replace(upper(prCol), 'BDCODCOL', 'P13.BDCODCOL');

  wsql = wsql||' group by P13.BDCODEMP, '||
                 'P13.BDCODCOL, '||
                 'P13.BDLINHAP13, ' ||
                 'P13.BDREFP13, ' ||
                 'P13.BDORDEMCCP13, ' ||
                 'P13.BDPLANOCC, ' ||
                 'P13.BDCODCENTRO, ' ||
                 'P13.BDCODTPCC, ' ||
                 'P13.BDRESCISAOP13, ' ||
                 'P13.BDPROPP13, ' ||
                 'p13.BDOBSERVACAO, ' ||
                 'P13.BDPORTOMADORP13 ';


  wSql = 'select P13.*, EMP.BDNOMEMP from ('||wSql||') P13 ';

  if (prsitcol = 0) then
     begin
       wSql = wSql || 'left outer join SP_SOMENTE_ATIVOS(cast(' ||''''|| :prdataini || ''''||' as date), cast(' ||''''|| :prdatafim ||''''|| ' as date), P13.BDCODEMP) SA ' ||
               'on (SA.BDCODEMP = P13.BDCODEMP and SA.BDCODCOL = P13.BDCODCOL and SA.BDCODEMP is not null) ';
     end
   else if (prsitcol = 2) then
     begin
       wSql = wSql || 'join SP_SOMENTE_DEMITIDOS(cast(' ||''''|| :prdatafim ||''''|| ' as date)) SD ' ||
               'on (SD.BDCODEMP = P13.BDCODEMP and SD.BDCODCOL = P13.BDCODCOL) ';
     end
   else if (prsitcol = 3) then
     begin
       wSql = wSql || 'join SP_SOMENTE_ADMITIDOS_MES(cast(' ||''''|| :prdataini ||''''|| ' as date), cast(' ||''''|| :prdatafim ||''''|| ' as date)) SAM ' ||
               'on (SAM.BDCODEMP = P13.BDCODEMP and SAM.BDCODCOL = P13.BDCODCOL) ';
     end
   else if (prsitcol = 4) then
     begin
       wSql = wSql || 'join SP_SOMENTE_DEMITIDOS_MES(cast(' ||''''|| :prdataini ||''''|| ' as date), cast(' ||''''|| :prdatafim ||''''|| ' as date)) SDM ' ||
               'on (SDM.BDCODEMP = P13.BDCODEMP and SDM.BDCODCOL = P13.BDCODCOL) ';
     end
   else if (prsitcol = 5) then
     begin
       wSql = wSql || 'join SP_ATIVOS_SEM_DEMITIDOS_MES(cast(' ||''''|| :prdataini ||''''|| ' as date), cast(' ||''''|| :prdatafim ||''''|| ' as date)) ASDM ' ||
               'on (ASDM.BDCODEMP = P13.BDCODEMP and ASDM.BDCODCOL = P13.BDCODCOL) ';
     end
   else if (prsitcol = 6) then
     begin
       wSql = wSql || 'join SP_ATI_SEM_DEM_COM_TRANSF(cast(' ||''''|| :prdataini ||''''|| ' as date), cast(' ||''''|| :prdatafim ||''''|| ' as date)) ASDMT ' ||
               'on (ASDMT.BDCODEMP = P13.BDCODEMP and ASDMT.BDCODCOL = P13.BDCODCOL) ';
     end
   else if (prsitcol = 7) then
     begin
       wSql = wSql || 'join SP_ATI_SEM_AFAST_MES_INT(cast(' ||''''|| :prdataini ||''''|| ' as date), cast(' ||''''|| :prdatafim ||''''|| ' as date)) ASAMI ' ||
               'on (ASAMI.BDCODEMP = P13.BDCODEMP and ASAMI.BDCODCOL = P13.BDCODCOL) ';
     end
   else if (prsitcol = 8) then
     begin
       wSql = wSql || 'join SP_AFASTADOS_MES_INTEIRO(cast(' ||''''|| :prdataini ||''''|| ' as date), cast(' ||''''|| :prdatafim||''''|| ' as date)) AMI ' ||
               'on (AMI.BDCODEMP = P13.BDCODEMP and AMI.BDCODCOL = P13.BDCODCOL) ';
     end

  wSql = wSql || ' join VW_TEMPRESAS_REF EMP on (EMP.BDCODEMP = P13.BDCODEMP) ';


  wWhere = ' WHERE P13.BDLINHAP13 in (0, 1, 5, 6, 7, 8, 9, 10, 11, 12, 13, 19) ';

  if (prref <> 0) then
     begin
       wWhere = wWhere || ' and P13.BDREFP13 = ' || prref;
       execute procedure sp_seta_competencia(prref);
     end

  if (coalesce(PRCC,'') <> '') then
     wWhere = wWhere || ' and ' || replace(upper(PRcc), 'BDCODTPCC', 'P13.BDCODTPCC');

  if (coalesce(prclasse,'') <> '') then
     begin
       wsql = wsql || ' left outer join VW_VRH_EMP_TCOLCON_VINC CVINC on (CVINC.BDCODEMP = P13.BDCODEMP and CVINC.BDCODCOL = P13.BDCODCOL) ';
       wWhere = wWhere || ' and ' || replace(upper(prclasse), 'BDCODCLA', 'CVINC.BDCODCLA');
     end

  if (coalesce(prsindicato,'') <> '') then
     begin
       wsql = wsql || ' left outer join VW_VRH_EMP_TCOL_VINC CV on (CV.BDCODEMP = P13.BDCODEMP and CV.BDCODCOL = P13.BDCODCOL) ';
       wWhere = wWhere || ' and ' || replace(upper(prsindicato), 'BDCODSINTRAB', 'CV.BDCODSINTRAB');
     end

  if (coalesce(PRFUNCAO,'') <> '') then
     begin
       wsql = wsql || ' left outer join VW_VRH_EMP_TCOL_VINCDIA CVD on (CVD.BDCODEMP = P13.BDCODEMP and CVD.BDCODCOL = P13.BDCODCOL) ';
       wWhere = wWhere || ' and ' || replace(upper(prfuncao), 'BDCODTFUC', 'CVD.BDCODTFUC');
     end

  wWhere = wWhere || ' and P13.BDLINHAP13 <> 20' ;

  wempant = '-1';
  wcolant = '-1';
  wccant = '-1';

  wsql = wsql ||' '||wwhere||' order by P13.BDCODEMP, P13.BDCODCOL, P13.BDREFP13';

 
  for execute statement wsql into
    :BDCODEMP,
    :BDCODCOL,
    :BDLINHAP13,
    :BDREFP13,
    :BDORDEMCCP13,
    :BDPLANOCC,
    :BDCODCENTRO,
    :BDSALBASEP13,
    :BDADICIONAISP13,
    :BDMEDIASP13,
    :BDOUTRASBASESP13,
    :BDCODTPCC,
    :BDVLR13SALP13,
    :BDFGTSP13,
    :BDINSSP13,
    :BDTERCFPASP13,
    :BDCNAERATP13,
    :BDRATAPOP13,
    :BDPISP13,
    :BDBASEFGTSP13,
    :BDBASEINSSP13,
    :BDRESCISAOP13,
    :BDBASEPISP13,
    :BDPROPP13,
    :BDOBSERVACAO,
    :BDTOTP13,
    :BDPORTOMADORP13,
    :BDNOMEMP
  do
    begin

      WLISTACODHIST = ' IS NULL ';
      if ((WPORCC = 'TRUE') and (not (bdcodtpcc is null))) then
        begin
            WLISTACODHIST = '';
           /* 229583 - para não duplicar registros com mesmo cc no mesmo mes mais de uma vez:carrega lista de BDCODHIST de um mesmo ccusto, evitando busca repetidas para esta informação  */
           FOR EXECUTE STATEMENT
               'SELECT det.bdcodhist
               FROM VRHF_EMP_TPROVISAO13_DET det
               JOIN vrhf_emp_tprepfn cccol
                    ON (det.bdcodemp = cccol.bdcodemp
                       AND det.bdcodcol = cccol.bdcodcol
                       AND det.bdcodhist = cccol.bdordem)
              WHERE (det.bdcodemp = '|| :bdcodemp ||
                     ' AND det.bdcodcol = '|| :bdcodcol ||
                     ' AND det.bdlinhap13 = '|| :BDLINHAP13 ||
                     ' AND det.bdrefp13 = '|| :bdrefp13 ||
                     ' AND det.bdplanocc = '|| :bdplanocc ||
                     ' AND cccol.bdcodtpcc = '|| :bdcodtpcc ||')'
          INTO :WCODHIST
          DO
            BEGIN
                if (WLISTACODHIST <> '') then
                    WLISTACODHIST = WLISTACODHIST || ',';
                else
                   WLISTACODHIST = ' IN (';
                WLISTACODHIST = WLISTACODHIST  ||:WCODHIST;
            END
         WLISTACODHIST = WLISTACODHIST || ')';

        end

      /*Campos que precis?o ser carregados fora do SQL principal para otimiza??o*/
      if (BDLINHAP13 = 19) then
         bdordem = '09.1';
      else
         bdordem = lpad(cast(BDLINHAP13 as varchar(5)),2,0);


      if (wempant <> cast(BDCODEMP as varchar(10))) then
         begin
           select first 1 BDTIPOEMIGUIAS from VW_VRHF_BASE_TEMPPAR EMPPAR where (EMPPAR.BDCODEMP = :BDCODEMP) into BDTIPOEMIGUIAS;
           wempant = cast(BDCODEMP as varchar(10));
         end

      if (wcolant <> cast(BDCODEMP as varchar(10))||'.'||cast(bdcodcol as varchar(10))) then
         begin
           select first 1 BDNOMCOLUPPER,BDNOMCOL from VW_VRH_EMP_TCOLCON_CAD COLCAD where (COLCAD.BDCODEMP = :BDCODEMP and COLCAD.BDCODCOL = :BDCODCOL) into BDNOMCOLUPPER,BDNOMCOL;

           select first 1 BDDATAADMCOL from VRH_EMP_TCOLCON COL where (COL.BDCODEMP = :BDCODEMP and COL.BDCODCOL = :BDCODCOL) into BDDATAADMCOL;

           BDDATARESCISAO = null;
           select first 1 BDDATARESCISAO from VRH_EMP_TRESCISAO RESC where (RESC.BDCODEMP = :BDCODEMP and RESC.BDCODCOL = :BDCODCOL and RESC.BDREFRESCISAO <= :BDREFP13) into BDDATARESCISAO;

           select first 1 BDCODCLA from VW_VRH_EMP_TCOLCON_VINC CVINC where (CVINC.BDCODEMP = :BDCODEMP and CVINC.BDCODCOL = :BDCODCOL) into :BDCODCLA;

           select first 1 BDCODSINTRAB from VW_VRH_EMP_TCOL_VINC CV where (CV.BDCODEMP = :BDCODEMP and CV.BDCODCOL = :BDCODCOL) into BDCODSINTRAB;

           select first 1 BDCODTFUC from VW_VRH_EMP_TCOL_VINCDIA CVD where (CVD.BDCODEMP = :BDCODEMP and CVD.BDCODCOL = :BDCODCOL) into BDCODTFUC;

           wREFTRF = 0; -- Carregar quando trocar colaborador se o parametro tiver marcado para otimizar
           wreftrfsai = 0;

           select first 1 t.bdreftrf from VRH_EMP_TTRANSCOL T where (T.BDCODEMPDEST = :BDCODEMP and T.BDCODCOLDEST = :BDCODCOL and T.BDCODEMPORIG is not null and T.BDCODCOLORIG is not null) into :wREFTRF;
           wreftrf = coalesce(wreftrf,0);
           select first 1  (select bdaaaamm from aaaamm(t.bddatatrf-1)) from VRH_EMP_TTRANSCOL T where (T.bdcodemporig = :BDCODEMP and T.bdcodcolorig = :BDCODCOL) into :wreftrfsai;
           wreftrfsai = coalesce(wreftrfsai,0);

           WBDVLR13SALP13_A13 = 0;
           WBQTD_A13 = 0;
           WBDVLR13SALP13_A13_MES = 0;
           WBQTD_A13_MES = 0;
           WBDVLR13SALP13_S13_MES = 0;
           WBQTD_S13_MES = 0;
           WVAL_A13_QTD_CALC = 0;
           WVAL_A13_CALC = 0;
           WVAL_ARRE_PROV_A13_CALC = 0;
           WVAL_ARRE_DESC_A13_CALC = 0;
           WVAL_A13_QTD_CALCMES = 0;
           WVAL_A13_CALCMES = 0;
           WVAL_ARRE_PROV_A13_CALCMES = 0;
           WVAL_ARRE_DESC_A13_CALCMES = 0;
           WVAL_A13_FICHA_QTD = 0;
           WVAL_A13_FICHA = 0;
           WVAL_A13_MAT = 0;
           WBDVLR13SALP13_Resc13_MES = 0;
           WBQTD_Resc13_MES = 0;
           WBDVLR13SALP13_A13MES = 0;
           WTEMPOTRAB = 0; /*#238505*/

           if ((prsemad13 = 1) and (BDDATARESCISAO is null))  then
              begin
                if (not (WPORCC = 'TRUE')) then    /*Busca o valores por alocação*/
                  begin
                      -- Valor pago como Adiantamento 13? Sal?rio em qualquer m?s anterior
                      select max(A.bdvlr13salp13), count(*)  from VRHF_EMP_TPROVISAO13 A
                      where A.BDLINHAP13 = 2 and A.BDCODEMP = :bdcodemp and A.BDCODCOL = :bdcodcol and A.BDREFP13 = :bdrefp13  into WBDVLR13SALP13_A13, WBQTD_A13;

                      -- Valor pago no m?s como Adiantamento 13? Sal?rio no m?s
                      select max(A.bdvlr13salp13), count(*)  from VRHF_EMP_TPROVISAO13 A
                      where A.BDLINHAP13 = 15 and A.BDCODEMP = :bdcodemp and A.BDCODCOL = :bdcodcol and A.BDREFP13 = :bdrefp13 into WBDVLR13SALP13_A13_MES, WBQTD_A13_MES;

                      -- Valor pago no m?s como 13? Sal?rio S13
                      select max(A.bdvlr13salp13), count(*) bdqtd from VRHF_EMP_TPROVISAO13 A
                      where A.BDLINHAP13 = 16 and A.BDCODEMP = :bdcodemp and A.BDCODCOL = :bdcodcol and A.BDREFP13 = :bdrefp13 into WBDVLR13SALP13_S13_MES, WBQTD_S13_MES;

                      -- Valor pago no m?s como Rescisao 13? Sal?rio S13
                      select max(A.bdvlr13salp13), count(*) bdqtd from VRHF_EMP_TPROVISAO13 A
                      where A.BDLINHAP13 = 17 and A.BDCODEMP = :bdcodemp and A.BDCODCOL = :bdcodcol and A.BDREFP13 = :bdrefp13 into WBDVLR13SALP13_Resc13_MES, WBQTD_Resc13_MES;



                      -- Valor existente no calculo de adiantamento de 13?
                      select count(*) BDQTD, sum(BDVALA13) BDVALA13, sum(BDARREPROVA13) BDARREPROVA13, sum(BDARREDESCA13) BDARREDESCA13
                      from VRHF_EMP_TA13SAL
                      where cast(BDANOA13 as varchar(4)) = substring(cast(:bdrefp13 as varchar(6)) from 1 for 4)
                        and BDCODEMP = :bdcodemp and BDCODCOL = :bdcodcol
                        and BDREFA13 <= :bdrefp13
                      into WVAL_A13_QTD_CALC, WVAL_A13_CALC, WVAL_ARRE_PROV_A13_CALC, WVAL_ARRE_DESC_A13_CALC;

                      -- Valor existente no calculo de adiantamento de 13? NO MêS
                      select count(*) BDQTD, sum(BDVALA13) BDVALA13, sum(BDARREPROVA13) BDARREPROVA13, sum(BDARREDESCA13) BDARREDESCA13
                      from VRHF_EMP_TA13SAL 
                     where cast(BDANOA13 as varchar(4)) = substring(cast(:bdrefp13 as varchar(6)) from 1 for 4)
                       and BDCODEMP = :bdcodemp and BDCODCOL = :bdcodcol and BDREFA13 = :bdrefp13
                      into WVAL_A13_QTD_CALCMES, WVAL_A13_CALCMES, WVAL_ARRE_PROV_A13_CALCMES, WVAL_ARRE_DESC_A13_CALCMES;
     
                      -- Valor existente importado na ficha financeira com Adiantamento 13?
                      select count(*) BDQTD, sum(BDA13FRAIS) from VRHF_EMP_TFICHARAIS 
                       where BDREFFRAIS like substring(cast(:bdrefp13 as varchar(6)) from 1 for 4)||'%'
                         and BDCODEMP = :bdcodemp and BDCODCOL = :bdcodcol and BDREFFRAIS < :bdrefp13 and BDA13FRAIS > 0
                      into :WVAL_A13_FICHA_QTD, :WVAL_A13_FICHA;


                  end
                else
                  begin
                      -- Valor pago como Adiantamento 13? Sal?rio em qualquer m?s anterior
                     execute statement
                     '  select sum(A.BD13SAL), count(*) ' ||
                     '  from  VRHF_EMP_TPROVISAO13_DET A ' ||
                     '   where A.BDLINHAP13 = 2 and A.BDCODEMP = ' || :bdcodemp ||
                     '     and A.BDCODCOL = ' || :bdcodcol ||
                     '     and A.BDREFP13 = ' || :bdrefp13 ||
                     '     and A.BDCODHIST ' || :WLISTACODHIST
                     into WBDVLR13SALP13_A13, WBQTD_A13;

                      -- Valor pago no m?s como Adiantamento 13? Sal?rio no m?s
                      execute statement
                      '  select sum(A.BD13SAL), count(*)  from VRHF_EMP_TPROVISAO13_DET A ' ||
                      '   where A.BDLINHAP13 = 15 and A.BDCODEMP = ' ||:bdcodemp ||
                      '     and A.BDCODCOL = ' || :bdcodcol ||
                      '     and A.BDREFP13 = ' || :bdrefp13 ||
                      '     and A.BDCODHIST ' || :WLISTACODHIST
                      into WBDVLR13SALP13_A13_MES, WBQTD_A13_MES;

                      -- Valor pago no m?s como 13? Sal?rio S13
                      execute statement
                      '  select sum(A.BD13SAL), count(*) bdqtd from VRHF_EMP_TPROVISAO13_DET A ' ||
                      '   where A.BDLINHAP13 = 16 and A.BDCODEMP = ' ||:bdcodemp ||
                      '     and A.BDCODCOL = ' ||:bdcodcol ||
                      '     and A.BDREFP13 = ' ||:bdrefp13 ||
                      '     and A.BDCODHIST ' || :WLISTACODHIST
                      into WBDVLR13SALP13_S13_MES, WBQTD_S13_MES;

                      -- Valor pago no m?s como Rescisao 13? Sal?rio S13
                      execute statement
                      '  select sum(A.BD13SAL), count(*) bdqtd from VRHF_EMP_TPROVISAO13_DET A ' ||
                      '  where A.BDLINHAP13 = 17 and A.BDCODEMP = ' || :bdcodemp ||
                      '  and A.BDCODCOL = ' || :bdcodcol ||
                      '  and A.BDREFP13 = ' || :bdrefp13 ||
                      '  and A.BDCODHIST ' || :WLISTACODHIST
                      into WBDVLR13SALP13_Resc13_MES, WBQTD_Resc13_MES;

                      -- Valor existente no calculo de adiantamento de 13?
                      select count(*) BDQTD, sum(BDVALA13) BDVALA13, sum(BDARREPROVA13) BDARREPROVA13, sum(BDARREDESCA13) BDARREDESCA13
                      from VRHF_EMP_TA13SAL where cast(BDANOA13 as varchar(4)) = substring(cast(:bdrefp13 as varchar(6)) from 1 for 4)
                                                  and BDCODEMP = :bdcodemp and BDCODCOL = :bdcodcol and BDREFA13 <= :bdrefp13
                      into WVAL_A13_QTD_CALC, WVAL_A13_CALC, WVAL_ARRE_PROV_A13_CALC, WVAL_ARRE_DESC_A13_CALC;

                      /*#238505*/
                      select SUM(CC.BDTEMPO)
                      from  VRHF_SP_TPREPFN_CC_REF(:bdrefp13, 'COLCON.BDCODEMP ='||:BDCODEMP, 'COLCON.BDCODCOL = '||:BDCODCOL, 1,:PRDATAINI,:PRDATAFIM, 0, 'TRUE', 0, 'FALSE') CC
                      where CC.BDCODTPCC = :BDCODTPCC
                      INTO  wTempoTrab;
                      if (wTempoTrab > 0) then
                         WPERCENTCC = WVAL_A13_CALC / wTempoTrab; --Visto que essa proporcionalidade por centro de custo deveria ter o Tempo Trabalhado como Base pra divisão deste cálculo e não o Salário Mensal.
                      /*#238505*/

                      WVAL_A13_CALC     = WVAL_A13_CALC * WPERCENTCC;
                      WVAL_ARRE_PROV_A13_CALC = WVAL_ARRE_PROV_A13_CALC * WPERCENTCC;
                      WVAL_ARRE_DESC_A13_CALC = WVAL_ARRE_DESC_A13_CALC * WPERCENTCC;

                      -- Valor existente no calculo de adiantamento de 13? NO MêS
                      select count(*) BDQTD, sum(BDVALA13) BDVALA13, sum(BDARREPROVA13) BDARREPROVA13, sum(BDARREDESCA13) BDARREDESCA13
                      from VRHF_EMP_TA13SAL where cast(BDANOA13 as varchar(4)) = substring(cast(:bdrefp13 as varchar(6)) from 1 for 4)
                                                  and BDCODEMP = :bdcodemp and BDCODCOL = :bdcodcol and BDREFA13 = :bdrefp13
                      into WVAL_A13_QTD_CALCMES, WVAL_A13_CALCMES, WVAL_ARRE_PROV_A13_CALCMES, WVAL_ARRE_DESC_A13_CALCMES;

                      WVAL_A13_CALCMES     = WVAL_A13_CALCMES * WPERCENTCC;
                      WVAL_ARRE_PROV_A13_CALCMES = WVAL_ARRE_PROV_A13_CALCMES * WPERCENTCC;
                      WVAL_ARRE_DESC_A13_CALCMES = WVAL_ARRE_DESC_A13_CALCMEs * WPERCENTCC;
     
                      -- Valor existente importado na ficha financeira com Adiantamento 13?
                      select count(*) BDQTD, sum(BDA13FRAIS) from VRHF_EMP_TFICHARAIS where BDREFFRAIS like substring(cast(:bdrefp13 as varchar(6)) from 1 for 4)||'%'
                                                                                      and BDCODEMP = :bdcodemp and BDCODCOL = :bdcodcol and BDREFFRAIS < :bdrefp13 and BDA13FRAIS > 0
                      into :WVAL_A13_FICHA_QTD, :WVAL_A13_FICHA;

                      WVAL_A13_FICHA = WVAL_A13_FICHA * WPERCENTCC;

                  end

                  -- Adiantamento de 13? se n?o tiver provis?o porem tiver calculo ou ficha deve buscar respectivamente
                  if (WBDVLR13SALP13_A13 = 0) then
                   begin
                     if ((WVAL_A13_QTD_CALC > 0) or (WVAL_A13_QTD_CALCMES > 0))  then
                        begin
                          WBDVLR13SALP13_A13 = coalesce(WVAL_A13_CALC,0) + coalesce(WVAL_ARRE_PROV_A13_CALC,0) - coalesce(WVAL_ARRE_DESC_A13_CALC,0);
                          WBDVLR13SALP13_A13MES = coalesce(WVAL_A13_CALCMES,0) + coalesce(WVAL_ARRE_PROV_A13_CALCMES,0) - coalesce(WVAL_ARRE_DESC_A13_CALCMES,0);
                        end
                     else if (WVAL_A13_FICHA_QTD > 0) then
                        WBDVLR13SALP13_A13 = WVAL_A13_FICHA;
                   end

              end
           else
              begin
                 select SUM(case when coalesce(V.BDTIPOCODVER, 0) = 1 then A13.BDVALVA13 * - 1 when coalesce(V.BDTIPOCODVER, 0) = 0 then A13.BDVALVA13 else 0 end) BDVALVA13
                 from VRHF_EMP_TVERBAA13 A13
                 join vrhf_emp_ta13sal C13 on (A13.bdcodemp = C13.bdcodemp and A13.bdcodcol = C13.bdcodcol and A13.bdrefa13 = C13.bdrefa13)
                 join vw_tverbas_ref V on (V.BDCODVER = A13.BDCODVER)
                 where A13.BDREFA13 <= :bdrefp13 and cast(c13.BDANOA13 as varchar(4)) = substring(cast(:bdrefp13 as varchar(6)) from 1 for 4) and
                      ((V.BDCLAVER starting with '4.012')) and a13.bdcodemp = :bdcodemp and a13.bdcodcol = :bdcodcol
                 into WVAL_A13_MAT;
                 WVAL_A13_MAT = 0;

              end

           WBDVLR13SALP13_A13 = coalesce(WBDVLR13SALP13_A13,0);
           WBQTD_A13 = coalesce(WBQTD_A13,0);
           WBDVLR13SALP13_A13_MES = coalesce(WBDVLR13SALP13_A13_MES,0);
           WBQTD_A13_MES = coalesce(WBQTD_A13_MES,0);
           WBDVLR13SALP13_S13_MES = coalesce(WBDVLR13SALP13_S13_MES,0);
           WBQTD_S13_MES = coalesce(WBQTD_S13_MES,0);
           WVAL_A13_QTD_CALC = coalesce(WVAL_A13_QTD_CALC,0);
           WVAL_A13_CALC = coalesce(WVAL_A13_CALC,0);
           WVAL_ARRE_PROV_A13_CALC = coalesce(WVAL_ARRE_PROV_A13_CALC,0);
           WVAL_ARRE_DESC_A13_CALC = coalesce(WVAL_ARRE_DESC_A13_CALC,0);
           WVAL_A13_QTD_CALCMES = coalesce(WVAL_A13_QTD_CALC,0);
           WVAL_A13_CALCMES = coalesce(WVAL_A13_CALC,0);
           WVAL_ARRE_PROV_A13_CALCMES = coalesce(WVAL_ARRE_PROV_A13_CALC,0);
           WVAL_ARRE_DESC_A13_CALCMES = coalesce(WVAL_ARRE_DESC_A13_CALC,0);
           WVAL_A13_FICHA_QTD = coalesce(WVAL_A13_FICHA_QTD,0);
           WVAL_A13_FICHA = coalesce(WVAL_A13_FICHA,0);
           WVAL_A13_MAT = coalesce(WVAL_A13_MAT,0);
           WBDVLR13SALP13_Resc13_MES = coalesce(WBDVLR13SALP13_Resc13_MES,0);
           WBQTD_Resc13_MES = coalesce(WBQTD_Resc13_MES,0);

           wcolant = cast(BDCODEMP as varchar(10))||'.'||cast(bdcodcol as varchar(10));
         end


      if (wccant <> cast(coalesce(BDCODCENTRO,'') as varchar(10))||'.'||cast(coalesce(BDCODTPCC,'') as varchar(10))) then
         begin
           BDNOMETOM  = null;
           BDCTALON  = null;
           BDNOMCTA = null;
           BDCENTROTPCC = '';

           select first 1 CC.BDNOMETOM
           from VRH_BASE_TCUSTOM CC
           where cc.bdcodcentro = :bdcodcentro and cc.bdcodtpcc = :bdcodtpcc into BDNOMETOM;

           Select first 1 TPCC.BDCTALON, TPCC.BDNOMCTA from CENTROS_TPCC TPCC
           where (TPCC.BDCODCENTRO = :bdcodcentro and TPCC.BDCODTPCC = :bdcodtpcc)
           Into :BDCTALON, :BDNOMCTA;

           select BDRETORNO from PREENCHE_ESQUERDA(CAST(COALESCE(:BDCODTPCC, 0) as VARCHAR(10)), 10, '0') into BDCENTROTPCC;

           wccant = cast(coalesce(BDCODCENTRO,'') as varchar(10))||'.'||cast(coalesce(BDCODTPCC,'') as varchar(10));
         end


      /* Ajustes para quando tive necessidade de mudan?a de informa??es devido compara??o com o cont?bil*/
      if ((PRSEMAD13 = 1)  and (BDDATARESCISAO is null)) then
         begin
           -- Valor pago como Adiantamento 13? Sal?rio em qualquer m?s anterior
--           WBDVLR13SALP13_A13 = 0;
--           WBQTD_A13 = 0;
           -- Valor pago no m?s como Adiantamento 13? Sal?rio no m?s
--           WBDVLR13SALP13_A13_MES = 0;
--           WBQTD_A13_MES = 0;
           -- Valor pago no m?s como 13? Sal?rio S13
--           WBDVLR13SALP13_S13_MES = 0;
--           WBQTD_S13_MES = 0;
           -- Valor existente no calculo de adiantamento de 13?
--           WVAL_A13_QTD_CALC = 0;
--           WVAL_A13_CALC = 0;
--           WVAL_ARRE_PROV_A13_CALC = 0;
--           WVAL_ARRE_DESC_A13_CALC = 0;
           -- Valor existente importado na ficha financeira com Adiantamento 13?
--           WVAL_A13_FICHA_QTD = 0;
--           WVAL_A13_FICHA = 0;

--  TTipoProvisao13 = ({0} tp13Principal, {1}tp13Pago, {2}tp13PagoAd13, {3}tp13Pago13Sal, {4}tp13PagoRescisao, {5}tp13Saldo, {6}tp13_1_12Avos, {7}tp13Acerto, {8}tp13AcertoTransf, {9}tp13AcertoTransfEmp,
--                     {10}tp13AcertoPagto, {11}tp13AcertoPagtoTransf, {12}tp13AcertoPagtoTransfEmp, {13}tp13PagoMes, {14}tp13SaldoInicial,
--                     {15}tp13PagoMesAd13, {16}tp13PagoMes13Sal, {17}tp13PagoMesRescisao, {18}tp13PagoMesesAnteriores, {19}tp13AcertoTributacao, 
--                     {20}tp13Zerado);

           /* ******* Uma Breve explica??o do que deve acontecer quando o parametro estiver para conferir o cont?bil *******

              Valores que foram pagos como adiantamento de 13? devem ser desconsiderados das informa??es de pagamentos e de saldos da mesma forma que os acertos de pagamentos
              isso se Aplica apenas a coluna de valor do 13?,
              FGTS n?o tem necessidade pois a baixa da contabiliza??o ? feita j? no momento do calculo e
              Impostos s?o pagos apenas no 13? integral
            */
           WVALORAJUSTE_LINHA = 0;
           WVALOR_LINHA = 0;

           if (bdlinhap13 = 1) then /* Total Pago todos os meses */
              begin
                if (WBQTD_S13_MES+WBQTD_Resc13_MES = 0) then /* Se n?o tem valor de 13? pago deve remover o adiantamento pago */
                 begin
                   if ((WPORCC = 'TRUE') and (BDDATARESCISAO is null)) then    /*Busca o valor pra ajustar o valor pago naquela alocação*/
                     begin
                        execute statement
                        '  select SUM((coalesce(A.BD13SAL, 0) * -1)) from VRHF_EMP_TPROVISAO13_DET A ' ||
                        '  where A.BDLINHAP13 = 1 and A.BDCODEMP = ' ||:BDCODEMP ||
                        '  and A.BDCODCOL = ' ||:BDCODCOL ||
                        '  and A.BDREFP13 = ' ||:BDREFP13 ||
                        '  and A.BDCODHIST ' || :WLISTACODHIST
                        into WVALORAJUSTE_LINHA;
                     end
                   else
                   if ((WPORCC = 'TRUE') and (BDDATARESCISAO is not null)) then    /*Busca o valor pra ajustar o valor pago naquela alocação*/
                     begin
                        WVALORAJUSTE_LINHA = 0;
                     end
                   else
                      wvalorajuste_linha = WBDVLR13SALP13_A13 * -1; /* Soma o adiantamento como pago no m?s */
                 end
              end
           else if ((bdlinhap13 = 5) )  then /* Saldo atual*/
              begin
                if (WBQTD_S13_MES+WBQTD_Resc13_MES = 0)  then /* Se n?o tem valor de 13? pago deve remover o adiantamento pago */
                   begin
                   if ((WPORCC = 'TRUE') and (BDDATARESCISAO is null)) then    /*Busca o valor pra ajustar o valor pago naquela alocação*/
                     begin
                        execute statement
                        '  select SUM(coalesce(A.BD13SAL, 0))  from VRHF_EMP_TPROVISAO13_DET A ' ||
                        '  where A.BDLINHAP13 = 0 and A.BDCODEMP = ' ||:BDCODEMP ||
                        '  and A.BDCODCOL = ' ||:BDCODCOL ||
                        '  and A.BDREFP13 = ' ||:BDREFP13 ||
                        '  and A.BDCODHIST ' || :WLISTACODHIST
                        into bdvlr13salp13;
        
                        execute statement
                        '  select SUM(coalesce(A.BD13SAL, 0))  from VRHF_EMP_TPROVISAO13_DET A ' ||
                        '  where A.BDLINHAP13 = 1 and A.BDCODEMP = ' ||:BDCODEMP ||
                        '    and A.BDCODCOL = ' ||:BDCODCOL ||
                        '    and A.BDREFP13 = ' ||:BDREFP13 ||
                        '    and A.BDCODHIST ' || :WLISTACODHIST
                        into WVALOR_LINHA;
                     end
                   else
                   if ((WPORCC = 'TRUE') and (BDDATARESCISAO is not null)) then    /*Busca o valor pra ajustar o valor pago naquela alocação*/
                     begin
                        bdvlr13salp13 = 0;
                        WVALOR_LINHA = 0;
                     end
                   else
                      wvalorajuste_linha = WBDVLR13SALP13_A13; /* Soma o adiantamento como pago no m?s */
              end
              end
           else if (bdlinhap13 = 11) then /* Acerto de pagamento transferencia */
              begin
                if (wreftrf = :bdrefp13) then
                   WVALORAJUSTE_LINHA = (bdvlr13salp13 * -1); /* remove do acerto de pagamento o valor que est? nele */
              end
           else if (bdlinhap13 = 13) then /* Pago no m?s */
              begin
                /*
                  Deve somar para ajuste de baixa o Adiantamento quando o mêsmo não for pago no mês caso contrário a baixa já tem o valor do adiantamento de 13º
                */
                if (((WBQTD_S13_MES > 0) or ((WBQTD_Resc13_MES > 0) and (wreftrfsai = 0))) and ((WBQTD_A13_MES = 0) and (wreftrf < bdrefp13))) then
                   wvalorajuste_linha = WBDVLR13SALP13_A13; /* Soma o adiantamento como pago no m?s para baixa total*/
                else
                if (((WBQTD_S13_MES+WBQTD_Resc13_MES = 0)) and (((WBQTD_A13 > 0) and (wreftrf = bdrefp13)) or (WBQTD_A13_MES > 0))) then
                   begin
                      wvalorajuste_linha = (WBDVLR13SALP13_A13MES) * -1; /* Remove do pago no mês o adiantamento se foi transferido no mês */

                      if (prsemad13 = 1) then
                        wvalorajuste_linha = (WBDVLR13SALP13_A13) * -1; /* Remove do pago o adiantamento se estiver marcado sem adto  */
                   end
                else
                if (WBQTD_Resc13_MES>0) then
                   wvalorajuste_linha =WBDVLR13SALP13_A13- WBDVLR13SALP13_A13MES;
              end

           bdvlr13salp13 = bdvlr13salp13 + WVALORAJUSTE_LINHA;
           bdtotp13 = bdtotp13 + WVALORAJUSTE_LINHA + WVALOR_LINHA;

         end                                                        
      else
         begin
           WVALORAJUSTE_LINHA = 0;

           if (bdlinhap13 = 10) then
              begin
                if (BDVLR13SALP13 <> 0) then
                   BDVLR13SALP13 = BDVLR13SALP13 + WVAL_A13_MAT;
              end
           else
           if (bdlinhap13 = 13)  then
              begin
                WSQLAUX = '  select SUM(coalesce(A.BD13SAL, 0))  from VRHF_EMP_TPROVISAO13_DET A ' ||
                          ' where A.BDLINHAP13 = 2 '|| --linha 2: adiantamento de salario
                          '   and A.BDCODEMP = ' ||:BDCODEMP ||
                          '   and A.BDCODCOL = ' ||:BDCODCOL ||
                          '   and A.BDREFP13 = ' ||:BDREFP13;

                if (wporcc = 'TRUE') then
                   WSQLAUX = WSQLAUX||'   and A.BDCODHIST ' || :WLISTACODHIST;

                execute statement wsqlaux into WVALORAJUSTE_LINHA;

                BDVLR13SALP13 = BDVLR13SALP13 + coalesce(WVALORAJUSTE_LINHA, 0);
         end
         end
      suspend;
    end
end^

create or alter procedure SP_GET_CODEMP_DOWNLOAD
returns (
    BDCODEMP integer)
as
declare variable WCODIGOVALIDO integer;
declare variable WCODIGOEMPRESA integer;
declare variable WSQL varchar(100);
BEGIN
  /* PROCEDURE TEXT */
  WSQL = 'SELECT BDCODESTAB FROM TDEFESTABDOWN UNION SELECT BDCODEMP FROM TEMPRESAS ORDER BY 1';
  WCODIGOVALIDO = 1;
  FOR EXECUTE STATEMENT :WSQL INTO :WCODIGOEMPRESA
    DO
      BEGIN
        IF (WCODIGOEMPRESA = WCODIGOVALIDO) THEN
           :WCODIGOVALIDO = :WCODIGOVALIDO+1;
        ELSE
           BREAK;
      END
  bdcodemp = wcodigovalido;
  SUSPEND;
END^


/* Restore proc. body: SP_SIT_DEC_RHNET */
create or alter procedure SP_SIT_DEC_RHNET (
    PREMP integer,
    PRCOL integer,
    PRDATAINISEFIP date)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATAINISEFIP date,
    BDCODSITDEC integer,
    BDDESCSITDEC varchar(70),
    BDQTDDIASATESTADO integer,
    BDDATAINIATES date,
    BDDATAFIMATES date,
    BDIDRHNETDEC integer)
as
begin
  BDCODEMP = premp;
  BDCODCOL = prcol;

  for select first 1 SD.BDDATAINISEFIP, SD.BDDATAINISEFIPDEC, SC.BDCODSIT, PSIT.BDDESCSIT, SC.BDDIASATESTADO, SC.BDDATAFIMATESTADOAUX, SC.BDIDRHNET
      from VRH_EMP_TSITCOL_DEC SD
      join VRH_EMP_TSITCOL SC on (SC.BDCODEMP = SD.BDCODEMP and SC.BDCODCOL = SD.BDCODCOL and SC.BDDATAINISEFIP = SD.BDDATAINISEFIPDEC)
      join VRH_BASE_TPREPSIT PSIT on (PSIT.BDCODSIT = SC.BDCODSIT)
      where SD.BDCODEMP = :premp and SD.BDCODCOL = :prcol and SD.BDDATAINISEFIP = :prdatainisefip
      order by SD.BDCODEMP desc, SD.BDCODCOL desc, SD.BDDATAINISEFIPDEC desc
  into
    :BDDATAINISEFIP, :BDDATAINIATES, :BDCODSITDEC, :BDDESCSITDEC, :BDQTDDIASATESTADO, :BDDATAFIMATES, :BDIDRHNETDEC
  do
    suspend;
end^


CREATE OR ALTER trigger vrhf_emp_tvscol_au0 for vrhf_emp_tvscol
active after update position 0
AS
declare variable VMSGLOG varchar(500);
begin
  VMSGLOG = '** Alterações de verbas associadas por colaborador (sim) **';

  --Empresa
  if (new.bdcodemp <> old.bdcodemp) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Empresa mudou [De: '||COALESCE(old.bdcodemp, 'VAZIO')||'] <-> [Para: '||new.bdcodemp||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Empresa: '||COALESCE(old.bdcodemp, 'VAZIO');

  --Colaborador
  if (new.bdcodcol <> old.bdcodcol) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Colaborador mudou [De: '||COALESCE(old.bdcodcol, 'VAZIO')||'] <-> [Para: '||new.bdcodcol||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Colaborador: '||COALESCE(old.bdcodcol, 'VAZIO');

  --Verba
  if (new.BDCODVER <> old.BDCODVER) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba mudou [De: '||COALESCE(old.BDCODVER, 'VAZIO')||'] <-> [Para: '||new.BDCODVER||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba: '||COALESCE(old.BDCODVER, 'VAZIO');

  --Data inicial
  if ((new.BDDIAINIVSCOL <> old.BDDIAINIVSCOL) or
     (new.BDMESINIVSCOL <> old.BDMESINIVSCOL) or
     (new.BDANOINIVSCOL <> old.BDANOINIVSCOL)) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial mudou [De: '||COALESCE(NULLIF(old.BDDIAINIVSCOL, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINIVSCOL, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINIVSCOL, 0), '0000')||'] <-> [Para: '||COALESCE(NULLIF(new.BDDIAINIVSCOL, 0), '00')||'/'||COALESCE(NULLIF(new.BDMESINIVSCOL, 0), '00')||'/'||COALESCE(NULLIF(new.BDANOINIVSCOL, 0), '0000')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Dia inicial: '||COALESCE(NULLIF(old.BDDIAINIVSCOL, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINIVSCOL, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINIVSCOL, 0), '0000');

  --Data final
  if ((new.BDDIAFIMVSCOL <> old.BDDIAFIMVSCOL) or
     (new.BDMESFIMVSCOL <> old.BDMESFIMVSCOL) or
     (new.BDANOFIMVSCOL <> old.BDANOFIMVSCOL)) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data final mudou [De: '||COALESCE(NULLIF(old.BDDIAFIMVSCOL, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESFIMVSCOL, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOFIMVSCOL, 0), '0000')||'] <-> [Para: '||COALESCE(NULLIF(new.BDDIAFIMVSCOL, 0), '00')||'/'||COALESCE(NULLIF(new.BDMESFIMVSCOL, 0), '00')||'/'||COALESCE(NULLIF(new.BDANOFIMVSCOL, 0), '0000')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Dia final: '||COALESCE(NULLIF(old.BDDIAFIMVSCOL, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESFIMVSCOL, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOFIMVSCOL, 0), '0000');

  --Referência auxiliar
  if (new.BDFORMULAREFAUXCOL <> old.BDFORMULAREFAUXCOL) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência auxiliar mudou [De: '||COALESCE(NULLIF(old.BDFORMULAREFAUXCOL, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAREFAUXCOL, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência auxiliar: '||COALESCE(NULLIF(old.BDFORMULAREFAUXCOL, ''), 'VAZIO');

  --Referência
  if (new.BDFORMULAREFCOL <> old.BDFORMULAREFCOL) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência mudou [De: '||COALESCE(NULLIF(old.BDFORMULAREFCOL, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAREFCOL, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência: '||COALESCE(NULLIF(old.BDFORMULAREFCOL, ''), 'VAZIO');

  --Valor
  if (new.BDFORMULAVALCOL <> old.BDFORMULAVALCOL) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Valor mudou [De: '||COALESCE(NULLIF(old.BDFORMULAVALCOL, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAVALCOL, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Valor: '||COALESCE(NULLIF(old.BDFORMULAVALCOL, ''), 'VAZIO');

  --Compl. inicial
  if (new.BDCOMPINI <> old.BDCOMPINI) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento inicial mudou [De: '||COALESCE(old.BDCOMPINI, 'VAZIO')||'] <-> [Para: '||COALESCE(new.BDCOMPINI, 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento inicial: '||COALESCE(old.BDCOMPINI, 'VAZIO');

  --Compl. final
  if (new.BDCOMPFIM <> old.BDCOMPFIM) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento final mudou [De: '||COALESCE(old.BDCOMPFIM, 'VAZIO')||'] <-> [Para: '||COALESCE(new.BDCOMPFIM, 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento final: '||COALESCE(old.BDCOMPFIM, 'VAZIO');

  EXECUTE PROCEDURE SP_INSERIR_LOG(old.bdcodemp,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   old.bdcodcol,
                                   NULL,
                                   NULL,
                                   VMSGLOG,
                                   0,
                                   1,
                                   NULL,
                                   NULL,
                                   upper('TfrLancaVerbasSimCol'),
                                   'Lançamento de verbas por colaborador (sim)',
                                   NULL,
                                   'VRHF_EMP_TVSCOL',
                                   NULL,
                                   'FALSE',
                                   NULL);

end^

CREATE OR ALTER trigger vrhf_emp_tvscol_ad0 for vrhf_emp_tvscol
active after delete position 0
AS
declare variable VMSGLOG varchar(500);
begin
  VMSGLOG = '** Exclusão de verbas associadas por colaborador (sim) **';

  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba: ' || COALESCE(old.BDCODVER, 'VAZIO');
  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Empresa: ' ||COALESCE(old.BDCODEMP, 'VAZIO') ;
  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Colaborador: ' || COALESCE(old.BDCODCOL, 'VAZIO');
  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial: ' ||COALESCE(NULLIF(old.BDDIAINIVSCOL, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINIVSCOL, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINIVSCOL, 0), '0000');

  EXECUTE PROCEDURE SP_INSERIR_LOG(old.bdcodemp,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   old.bdcodcol,
                                   NULL,
                                   NULL,
                                   VMSGLOG,
                                   0,
                                   2,
                                   NULL,
                                   NULL,
                                   upper('TfrLancaVerbasSimCol'),
                                   'Lançamento de verbas por colaborador (sim)',
                                   NULL,
                                   'VRHF_EMP_TVSCOL',
                                   NULL,
                                   'FALSE',
                                   NULL);
end^


CREATE OR ALTER trigger vrhf_emp_tvsemp_au0 for vrhf_emp_tvsemp
active after update position 0
AS
declare variable VMSGLOG varchar(5000);
begin
  VMSGLOG = '** Alterações de verbas associadas para empresa (sim) **';

  --EMPRESA
  if (new.BDCODEMP <> old.BDCODEMP) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Empresa mudou [De: '||COALESCE(old.BDCODEMP, 'VAZIO')||'] <-> [Para: '||new.BDCODEMP||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Empresa: '||COALESCE(old.BDCODEMP, 'VAZIO');

  --VERBA
  if (new.BDCODVER <> old.BDCODVER) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba mudou [De: '||COALESCE(old.BDCODVER, 'VAZIO')||'] <-> [Para: '||new.BDCODVER||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba: '||COALESCE(old.BDCODVER, 'VAZIO');

   --Data inicial
  if ((new.BDDIAINIVSEMP <> old.BDDIAINIVSEMP) or
     (new.BDMESINIVSEMP <> old.BDMESINIVSEMP) or
     (new.BDANOINIVSEMP <> old.BDANOINIVSEMP)) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial mudou [De: '||COALESCE(NULLIF(old.BDDIAINIVSEMP, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINIVSEMP, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINIVSEMP, 0), '0000')||'] <-> [Para: '||COALESCE(NULLIF(new.BDDIAINIVSEMP, 0), '00')||'/'||COALESCE(NULLIF(new.BDMESINIVSEMP, 0), '00')||'/'||COALESCE(NULLIF(new.BDANOINIVSEMP, 0), '0000')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial: '||COALESCE(NULLIF(old.BDDIAINIVSEMP, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINIVSEMP, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINIVSEMP, 0), '0000');

  --Data final
  if ((new.BDDIAFIMVSEMP <> old.BDDIAFIMVSEMP) or
     (new.BDMESFIMVSEMP <> old.BDMESFIMVSEMP) or
     (new.BDANOFIMVSEMP <> old.BDANOFIMVSEMP)) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data final mudou [De: '||COALESCE(NULLIF(old.BDDIAFIMVSEMP, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESFIMVSEMP, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOFIMVSEMP, 0), '0000')||'] <-> [Para: '||COALESCE(NULLIF(new.BDDIAFIMVSEMP, 0), '00')||'/'||COALESCE(NULLIF(new.BDMESFIMVSEMP, 0), '00')||'/'||COALESCE(NULLIF(new.BDANOFIMVSEMP, 0), '0000')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data final: '||COALESCE(NULLIF(old.BDDIAFIMVSEMP, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESFIMVSEMP, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOFIMVSEMP, 0), '0000');

    --Referência auxiliar
  if (new.BDFORMULAREFAUXEMP <> old.BDFORMULAREFAUXEMP) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência auxiliar mudou [De: '||COALESCE(NULLIF(old.BDFORMULAREFAUXEMP, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAREFAUXEMP, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência auxiliar: '||COALESCE(NULLIF(old.BDFORMULAREFAUXEMP, ''), 'VAZIO');

  --Referência
  if (new.BDFORMULAREFEMP <> old.BDFORMULAREFEMP) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência mudou [De: '||COALESCE(NULLIF(old.BDFORMULAREFEMP, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAREFEMP, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência: '||COALESCE(NULLIF(old.BDFORMULAREFEMP, ''), 'VAZIO');

  --Valor
  if (new.BDFORMULAVALEMP <> old.BDFORMULAVALEMP) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Valor mudou [De: '||COALESCE(NULLIF(old.BDFORMULAVALEMP, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAVALEMP, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Valor: '||COALESCE(NULLIF(old.BDFORMULAVALEMP, ''), 'VAZIO');

  --Compl. inicial
  if (new.BDCOMPINI <> old.BDCOMPINI) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento inicial mudou [De: '||COALESCE(old.BDCOMPINI, 'VAZIO')||'] <-> [Para: '||COALESCE(new.BDCOMPINI, 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento inicial: '||COALESCE(old.BDCOMPINI, 'VAZIO');

  --Compl. final
  if (new.BDCOMPFIM <> old.BDCOMPFIM) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento final mudou [De: '||COALESCE(old.BDCOMPFIM, 'VAZIO')||'] <-> [Para: '||COALESCE(new.BDCOMPFIM, 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento final: '||COALESCE(old.BDCOMPFIM, 'VAZIO');

  EXECUTE PROCEDURE SP_INSERIR_LOG(old.bdcodemp,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   VMSGLOG,
                                   0,
                                   1,
                                   NULL,
                                   NULL,
                                   upper('TfrLancaVerbasSimEmp'),
                                   'Lançamento de Verbas por Empresa (Sim)',
                                   NULL,
                                   'VRHF_EMP_TVSEMP',
                                   NULL,
                                   'FALSE',
                                   NULL);

end^

CREATE OR ALTER trigger vrhf_emp_tvsemp_ad0 for vrhf_emp_tvsemp
active after delete position 0
AS
declare variable VMSGLOG varchar(500);
begin
  VMSGLOG = '** Exclusão de verbas associadas para empresa (sim) **';

  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba: ' || COALESCE(old.BDCODVER, 'VAZIO');
  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Empresa: ' ||COALESCE(old.BDCODEMP, 'VAZIO') ;
  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial: ' ||COALESCE(NULLIF( old.BDDIAINIVSEMP, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINIVSEMP, 0), '00') ||'/'||COALESCE(NULLIF(old.BDANOINIVSEMP, 0), '0000');

  EXECUTE PROCEDURE SP_INSERIR_LOG(old.bdcodemp,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   VMSGLOG,
                                   0,
                                   2,
                                   NULL,
                                   NULL,
                                   upper('TfrLancaVerbasSimEmp'),
                                   'Lançamento de Verbas por Empresa (Sim)',
                                   NULL,
                                   'VRHF_EMP_TVSEMP',
                                   NULL,
                                   'FALSE',
                                   NULL);
end^

CREATE OR ALTER trigger vrhf_funcoes_tvsfuc_au0 for vrhf_funcoes_tvsfuc
active after update position 0
AS
declare variable VMSGLOG varchar(500);
begin
  VMSGLOG = '** Alterações de verbas associadas para função (sim) **';

  --PLANO
  if (new.BDCODPLAFUC <> old.BDCODPLAFUC) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Plano de função mudou [De: '||COALESCE(old.BDCODPLAFUC, 'VAZIO')||'] <-> [Para: '||new.BDCODPLAFUC||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Plano de função: '||COALESCE(old.BDCODPLAFUC, 'VAZIO');

  --FUNÇÃO
  if (new.BDCODTFUC <> old.BDCODTFUC) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Função mudou [De: '||COALESCE(old.BDCODTFUC, 'VAZIO')||'] <-> [Para: '||new.BDCODTFUC||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Função: '||COALESCE(old.BDCODTFUC, 'VAZIO');

  --VERBA
  if (new.BDCODVER <> old.BDCODVER) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba mudou [De: '||COALESCE(old.BDCODVER, 'VAZIO')||'] <-> [Para: '||new.BDCODVER||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba: '||COALESCE(old.BDCODVER, 'VAZIO');

   --Data inicial
  if ((new.BDDIAINIVSFUC <> old.BDDIAINIVSFUC) or
     (new.BDMESINIVSFUC <> old.BDMESINIVSFUC) or
     (new.BDANOINIVSFUC <> old.BDANOINIVSFUC)) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial mudou [De: '||COALESCE(NULLIF(old.BDDIAINIVSFUC, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINIVSFUC, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINIVSFUC, 0), '0000')||'] <-> [Para: '||COALESCE(NULLIF(new.BDDIAINIVSFUC, 0), '00')||'/'||COALESCE(NULLIF(new.BDMESINIVSFUC, 0), '00')||'/'||COALESCE(NULLIF(new.BDANOINIVSFUC, 0), '0000')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial: '||COALESCE(NULLIF(old.BDDIAINIVSFUC, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINIVSFUC, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINIVSFUC, 0), '0000');

  --Data final
  if ((new.BDDIAFIMVSFUC <> old.BDDIAFIMVSFUC) or
     (new.BDMESFIMVSFUC <> old.BDMESFIMVSFUC) or
     (new.BDANOFIMVSFUC <> old.BDANOFIMVSFUC)) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data final mudou [De: '||COALESCE(NULLIF(old.BDDIAFIMVSFUC, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESFIMVSFUC, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOFIMVSFUC, 0), '0000')||'] <-> [Para: '||COALESCE(NULLIF(new.BDDIAFIMVSFUC, 0), '00')||'/'||COALESCE(NULLIF(new.BDMESFIMVSFUC, 0), '00')||'/'||COALESCE(NULLIF(new.BDANOFIMVSFUC, 0), '0000')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data final: '||COALESCE(NULLIF(old.BDDIAFIMVSFUC, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESFIMVSFUC, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOFIMVSFUC, 0), '0000');

    --Referência auxiliar
  if (new.BDFORMULAREFAUXFUC <> old.BDFORMULAREFAUXFUC) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência auxiliar mudou [De: '||COALESCE(NULLIF(old.BDFORMULAREFAUXFUC, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAREFAUXFUC, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência auxiliar: '||COALESCE(NULLIF(old.BDFORMULAREFAUXFUC, ''), 'VAZIO');

  --Referência
  if (new.BDFORMULAREFFUC <> old.BDFORMULAREFFUC) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência mudou [De: '||COALESCE(NULLIF(old.BDFORMULAREFFUC, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAREFFUC, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência: '||COALESCE(NULLIF(old.BDFORMULAREFFUC, ''), 'VAZIO');

  --Valor
  if (new.BDFORMULAVALFUC <> old.BDFORMULAVALFUC) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Valor mudou [De: '||COALESCE(NULLIF(old.BDFORMULAVALFUC, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAVALFUC, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Valor: '||COALESCE(NULLIF(old.BDFORMULAVALFUC, ''), 'VAZIO');

  --Compl. inicial
  if (new.BDCOMPINI <> old.BDCOMPINI) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento inicial mudou [De: '||COALESCE(old.BDCOMPINI, 'VAZIO')||'] <-> [Para: '||COALESCE(new.BDCOMPINI, 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento inicial: '||COALESCE(old.BDCOMPINI, 'VAZIO');

  --Compl. final
  if (new.BDCOMPFIM <> old.BDCOMPFIM) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento final mudou [De: '||COALESCE(old.BDCOMPFIM, 'VAZIO')||'] <-> [Para: '||COALESCE(new.BDCOMPFIM, 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento final: '||COALESCE(old.BDCOMPFIM, 'VAZIO');

  EXECUTE PROCEDURE SP_INSERIR_LOG(NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   VMSGLOG,
                                   0,
                                   1,
                                   NULL,
                                   NULL,
                                   upper('TfrLancaVerbasSimFuc'),
                                   'Lançamento de verbas sim para função',
                                   NULL,
                                   'VRHF_FUNCOES_TVSFUC',
                                   NULL,
                                   'FALSE',
                                   NULL);
end^

CREATE OR ALTER trigger vrhf_funcoes_tvsfuc_ad0 for vrhf_funcoes_tvsfuc
active after delete position 0
AS
declare variable VMSGLOG varchar(500);
begin
  VMSGLOG = '** Exclusão de verbas associadas para função (sim) **';

  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Plano de funções: ' ||COALESCE(old.BDCODPLAFUC, 'VAZIO') ;
  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Função: ' || COALESCE(old.BDCODTFUC, 'VAZIO');
  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba: ' ||COALESCE(old.BDCODVER, 'VAZIO') ;
  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial: ' ||COALESCE(NULLIF( old.BDDIAINIVSFUC, 0), '00')||'/'||COALESCE(NULLIF( old.BDMESINIVSFUC, 0), '00')||'/'||COALESCE(NULLIF( old.BDANOINIVSFUC, 0), '0000');

  EXECUTE PROCEDURE SP_INSERIR_LOG(NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   VMSGLOG,
                                   0,
                                   2,
                                   NULL,
                                   NULL,
                                   upper('TfrLancaVerbasSimFuc'),
                                   'Lançamento de verbas sim para função',
                                   NULL,
                                   'VRHF_FUNCOES_TVSFUC',
                                   NULL,
                                   'FALSE',
                                   NULL);
end^



CREATE OR ALTER trigger vrhf_custos_tvscusto_au0 for vrhf_custos_tvscusto
active after update position 0
AS
declare variable VMSGLOG varchar(500);
begin
  VMSGLOG = '** Alterações de verbas associadas para centros de custos (sim) **';

  --PLANO
  if (new.BDCODTPCC <> old.BDCODTPCC) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Plano mudou [De: '||COALESCE(old.BDCODTPCC, 'VAZIO')||'] <-> [Para: '||new.BDCODTPCC||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Plano: '||COALESCE(old.BDCODTPCC, 'VAZIO');

  --CENTRO DE CUSTO
  if (new.BDCODCENTRO <> old.BDCODCENTRO) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Centro de custo mudou [De: '||COALESCE(old.BDCODCENTRO, 'VAZIO')||'] <-> [Para: '||new.BDCODCENTRO||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Centro de custo: '||COALESCE(old.BDCODCENTRO, 'VAZIO');

  --VERBA
  if (new.BDCODVER <> old.BDCODVER) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba mudou [De: '||COALESCE(old.BDCODVER, 'VAZIO')||'] <-> [Para: '||new.BDCODVER||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba: '||COALESCE(old.BDCODVER, 'VAZIO');

   --Data inicial
  if ((new.BDDIAINIVSCUSTO <> old.BDDIAINIVSCUSTO) or
     (new.BDMESINIVSCUSTO <> old.BDMESINIVSCUSTO) or
     (new.BDANOINIVSCUSTO <> old.BDANOINIVSCUSTO)) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial mudou [De: '||COALESCE(NULLIF(old.BDDIAINIVSCUSTO, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINIVSCUSTO, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINIVSCUSTO, 0), '0000')||'] <-> [Para: '||COALESCE(NULLIF(new.BDDIAINIVSCUSTO, 0), '00')||'/'||COALESCE(NULLIF(new.BDMESINIVSCUSTO, 0), '00')||'/'||COALESCE(NULLIF(new.BDANOINIVSCUSTO, 0), '0000')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial: '||COALESCE(NULLIF(old.BDDIAINIVSCUSTO, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINIVSCUSTO, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINIVSCUSTO, 0), '0000');

  --Data final
  if ((new.BDDIAFIMVSCUSTO <> old.BDDIAFIMVSCUSTO) or
     (new.BDMESFIMVSCUSTO <> old.BDMESFIMVSCUSTO) or
     (new.BDANOFIMVSCUSTO <> old.BDANOFIMVSCUSTO)) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data final mudou [De: '||COALESCE(NULLIF(old.BDDIAFIMVSCUSTO, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESFIMVSCUSTO, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOFIMVSCUSTO, 0), '0000')||'] <-> [Para: '||COALESCE(NULLIF(new.BDDIAFIMVSCUSTO, 0), '00')||'/'||COALESCE(NULLIF(new.BDMESFIMVSCUSTO, 0), '00')||'/'||COALESCE(NULLIF(new.BDANOFIMVSCUSTO, 0), '0000')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data final: '||COALESCE(NULLIF(old.BDDIAFIMVSCUSTO, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESFIMVSCUSTO, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOFIMVSCUSTO, 0), '0000');

    --Referência auxiliar
  if (new.BDFORMULAREFAUXCUSTO <> old.BDFORMULAREFAUXCUSTO) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência auxiliar mudou [De: '||COALESCE(NULLIF(old.BDFORMULAREFAUXCUSTO, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAREFAUXCUSTO, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência auxiliar: '||COALESCE(NULLIF(old.BDFORMULAREFAUXCUSTO, ''), 'VAZIO');

  --Referência
  if (new.BDFORMULAREFCUSTO <> old.BDFORMULAREFCUSTO) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência mudou [De: '||COALESCE(NULLIF(old.BDFORMULAREFCUSTO, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAREFCUSTO, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência: '||COALESCE(NULLIF(old.BDFORMULAREFCUSTO, ''), 'VAZIO');

  --Valor
  if (new.BDFORMULAVALCUSTO <> old.BDFORMULAVALCUSTO) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Valor mudou [De: '||COALESCE(NULLIF(old.BDFORMULAVALCUSTO, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAVALCUSTO, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Valor: '||COALESCE(NULLIF(old.BDFORMULAVALCUSTO, ''), 'VAZIO');

  --Compl. inicial
  if (new.BDCOMPINI <> old.BDCOMPINI) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento inicial mudou [De: '||COALESCE(old.BDCOMPINI, 'VAZIO')||'] <-> [Para: '||COALESCE(new.BDCOMPINI, 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento inicial: '||COALESCE(old.BDCOMPINI, 'VAZIO');

  --Compl. final
  if (new.BDCOMPFIM <> old.BDCOMPFIM) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento final mudou [De: '||COALESCE(old.BDCOMPFIM, 'VAZIO')||'] <-> [Para: '||COALESCE(new.BDCOMPFIM, 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento final: '||COALESCE(old.BDCOMPFIM, 'VAZIO');

  EXECUTE PROCEDURE SP_INSERIR_LOG(NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   VMSGLOG,
                                   0,
                                   1,
                                   NULL,
                                   NULL,
                                   upper('TfrLancaVerbasSimCusto'),
                                   'Lançamento de verbas sim para centros de custos',
                                   NULL,
                                   'VRHF_CUSTOS_TVSCUSTO',
                                   NULL,
                                   'FALSE',
                                   NULL);
end^

CREATE OR ALTER trigger vrhf_custos_tvscusto_ad0 for vrhf_custos_tvscusto
active after delete position 0
AS
declare variable VMSGLOG varchar(500);
begin
  VMSGLOG = '** Exclusão de verbas associadas para centros de custos (sim) **';

  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Plano: ' || COALESCE(old.BDCODTPCC, 'VAZIO');
  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Centro de custo: ' ||COALESCE(old.BDCODCENTRO, 'VAZIO') ;
  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba: ' || COALESCE(old.BDCODVER, 'VAZIO');
  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial: ' ||COALESCE(NULLIF(old.BDDIAINIVSCUSTO, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINIVSCUSTO, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINIVSCUSTO, 0), '0000');

  EXECUTE PROCEDURE SP_INSERIR_LOG(NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   VMSGLOG,
                                   0,
                                   2,
                                   NULL,
                                   NULL,
                                   upper('TfrLancaVerbasSimCusto'),
                                   'Lançamento de verbas sim para centros de custos',
                                   NULL,
                                   'VRHF_CUSTOS_TVSCUSTO',
                                   NULL,
                                   'FALSE',
                                   NULL);
end^



CREATE OR ALTER trigger vrhf_base_tvssind_au0 for vrhf_base_tvssind
active after update position 0
AS
declare variable VMSGLOG varchar(5000);
begin
  VMSGLOG = '** Alterações de verbas associadas para sindicato (sim) **';

  --SINDICATO
  if (new.BDCODSINTRAB <> old.BDCODSINTRAB) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Sindicato mudou [De: '||COALESCE(old.BDCODSINTRAB, 'VAZIO')||'] <-> [Para: '||new.BDCODSINTRAB||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Sindicato: '||COALESCE(old.BDCODSINTRAB, 'VAZIO');

  --VERBA
  if (new.BDCODVER <> old.BDCODVER) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba mudou [De: '||COALESCE(old.BDCODVER, 'VAZIO')||'] <-> [Para: '||new.BDCODVER||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba: '||COALESCE(old.BDCODVER, 'VAZIO');

   --Data inicial
  if ((new.BDDIAINIVSSIND <> old.BDDIAINIVSSIND) or
     (new.BDMESINIVSSIND <> old.BDMESINIVSSIND) or
     (new.BDANOINIVSSIND <> old.BDANOINIVSSIND)) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial mudou [De: '||COALESCE(NULLIF(old.BDDIAINIVSSIND, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINIVSSIND, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINIVSSIND, 0), '0000')||'] <-> [Para: '||COALESCE(NULLIF(new.BDDIAINIVSSIND, 0), '00')||'/'||COALESCE(NULLIF(new.BDMESINIVSSIND, 0), '00')||'/'||COALESCE(NULLIF(new.BDANOINIVSSIND, 0), '0000')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial: '||COALESCE(NULLIF(old.BDDIAINIVSSIND, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINIVSSIND, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINIVSSIND, 0), '0000');

  --Data final
  if ((new.BDDIAFIMVSSIND <> old.BDDIAFIMVSSIND) or
     (new.BDMESFIMVSSIND <> old.BDMESFIMVSSIND) or
     (new.BDANOFIMVSSIND <> old.BDANOFIMVSSIND)) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data final mudou [De: '||COALESCE(NULLIF(old.BDDIAFIMVSSIND, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESFIMVSSIND, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOFIMVSSIND, 0), '0000')||'] <-> [Para: '||COALESCE(NULLIF(new.BDDIAFIMVSSIND, 0), '00')||'/'||COALESCE(NULLIF(new.BDMESFIMVSSIND, 0), '00')||'/'||COALESCE(NULLIF(new.BDANOFIMVSSIND, 0), '0000')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data final: '||COALESCE(NULLIF(old.BDDIAFIMVSSIND, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESFIMVSSIND, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOFIMVSSIND, 0), '00');

    --Referência auxiliar
  if (new.BDFORMULAREFAUXSIND <> old.BDFORMULAREFAUXSIND) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência auxiliar mudou [De: '||COALESCE(NULLIF(old.BDFORMULAREFAUXSIND, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAREFAUXSIND, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência auxiliar: '||COALESCE(NULLIF(old.BDFORMULAREFAUXSIND, ''), 'VAZIO');

  --Referência
  if (new.BDFORMULAREFSIND <> old.BDFORMULAREFSIND) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência mudou [De: '||COALESCE(NULLIF(old.BDFORMULAREFSIND, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAREFSIND, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência: '||COALESCE(NULLIF(old.BDFORMULAREFSIND, ''), 'VAZIO');

  --Valor
  if (new.BDFORMULAVALSIND <> old.BDFORMULAVALSIND) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Valor mudou [De: '||COALESCE(NULLIF(old.BDFORMULAVALSIND, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAVALSIND, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Valor: '||COALESCE(NULLIF(old.BDFORMULAVALSIND, ''), 'VAZIO');

  --Compl. inicial
  if (new.BDCOMPINI <> old.BDCOMPINI) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento inicial mudou [De: '||COALESCE(old.BDCOMPINI, 'VAZIO')||'] <-> [Para: '||COALESCE(new.BDCOMPINI, 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento inicial: '||COALESCE(old.BDCOMPINI, 'VAZIO');

  --Compl. final
  if (new.BDCOMPFIM <> old.BDCOMPFIM) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento final mudou [De: '||COALESCE(old.BDCOMPFIM, 'VAZIO')||'] <-> [Para: '||COALESCE(new.BDCOMPFIM, 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento final: '||COALESCE(old.BDCOMPFIM, 'VAZIO');

  EXECUTE PROCEDURE SP_INSERIR_LOG(NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   VMSGLOG,
                                   0,
                                   1,
                                   NULL,
                                   NULL,
                                   upper('TfrLancaVerbasSimSind'),
                                   'Lançamento de verbas sim para sindicato',
                                   NULL,
                                   'VRHF_BASE_TVSSIND',
                                   NULL,
                                   'FALSE',
                                   NULL);
end^

CREATE OR ALTER trigger vrhf_base_tvssind_ad0 for vrhf_base_tvssind
active after delete position 0
AS
declare variable VMSGLOG varchar(500);
begin
  VMSGLOG = '** Exclusão de verbas associadas para sindicato (sim) **';

  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Sindicato: ' || COALESCE(old.BDCODSINTRAB, 'VAZIO');
  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba: ' || COALESCE(old.BDCODVER, 'VAZIO');
  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial: ' ||COALESCE(NULLIF(old.BDDIAINIVSSIND, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINIVSSIND, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINIVSSIND, 0), '0000');

  EXECUTE PROCEDURE SP_INSERIR_LOG(NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   VMSGLOG,
                                   0,
                                   2,
                                   NULL,
                                   NULL,
                                   upper('TfrLancaVerbasSimSind'),
                                   'Lançamento de verbas sim para sindicato',
                                   NULL,
                                   'VRHF_BASE_TVSSIND',
                                   NULL,
                                   'FALSE',
                                   NULL);
end^

CREATE OR ALTER trigger vrhf_base_tvspres_au0 for vrhf_base_tvspres
active after update position 0
AS
declare variable VMSGLOG varchar(500);
begin
  VMSGLOG = '** Alterações de verbas associadas para preparação de rescisão (sim) **';

  --PREPARAÇÃO RESCISÃO
  if (new.BDCODPRES <> old.BDCODPRES) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Preparação rescisão mudou [De: '||COALESCE(old.BDCODPRES, 'VAZIO')||'] <-> [Para: '||new.BDCODPRES||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Preparação rescisão: '||COALESCE(old.BDCODPRES, 'VAZIO');

  --VERBA
  if (new.BDCODVER <> old.BDCODVER) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba mudou [De: '||COALESCE(old.BDCODVER, 'VAZIO')||'] <-> [Para: '||new.BDCODVER||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba: '||COALESCE(old.BDCODVER, 'VAZIO');

   --Data inicial
  if ((new.BDDIAINIVSPRES <> old.BDDIAINIVSPRES) or
     (new.BDMESINIVSPRES <> old.BDMESINIVSPRES) or
     (new.BDANOINIVSPRES <> old.BDANOINIVSPRES)) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial mudou [De: '||COALESCE(NULLIF(old.BDDIAINIVSPRES, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINIVSPRES, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINIVSPRES, 0), '0000')||'] <-> [Para: '||COALESCE(NULLIF(new.BDDIAINIVSPRES, 0), '00')||'/'||COALESCE(NULLIF(new.BDMESINIVSPRES, 0), '00')||'/'||COALESCE(NULLIF(new.BDANOINIVSPRES, 0), '0000')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial: '||COALESCE(NULLIF(old.BDDIAINIVSPRES, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINIVSPRES, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINIVSPRES, 0), '0000');

  --Data final
  if ((new.BDDIAFIMVSPRES <> old.BDDIAFIMVSPRES) or
     (new.BDMESFIMVSPRES <> old.BDMESFIMVSPRES) or
     (new.BDANOFIMVSPRES <> old.BDANOFIMVSPRES)) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data final mudou [De: '||COALESCE(NULLIF(old.BDDIAFIMVSPRES, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESFIMVSPRES, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOFIMVSPRES, 0), '0000')||'] <-> [Para: '||COALESCE(NULLIF(new.BDDIAFIMVSPRES, 0), '00')||'/'||COALESCE(NULLIF(new.BDMESFIMVSPRES, 0), '00')||'/'||COALESCE(NULLIF(new.BDANOFIMVSPRES, 0), '0000')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data final: '||COALESCE(NULLIF(old.BDDIAFIMVSPRES, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESFIMVSPRES, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOFIMVSPRES, 0), '0000');

    --Referência auxiliar
  if (new.BDFORMULAREFAUXPRES <> old.BDFORMULAREFAUXPRES) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência auxiliar mudou [De: '||COALESCE(NULLIF(old.BDFORMULAREFAUXPRES, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAREFAUXPRES, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência auxiliar: '||COALESCE(NULLIF(old.BDFORMULAREFAUXPRES, ''), 'VAZIO');

  --Referência
  if (new.BDFORMULAREFPRES <> old.BDFORMULAREFPRES) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência mudou [De: '||COALESCE(NULLIF(old.BDFORMULAREFPRES, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAREFPRES, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência: '||COALESCE(NULLIF(old.BDFORMULAREFPRES, ''), 'VAZIO');

  --Valor
  if (new.BDFORMULAVALPRES <> old.BDFORMULAVALPRES) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Valor mudou [De: '||COALESCE(NULLIF(old.BDFORMULAVALPRES, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAVALPRES, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Valor: '||COALESCE(NULLIF(old.BDFORMULAVALPRES, ''), 'VAZIO');

  --Compl. inicial
  if (new.BDCOMPINI <> old.BDCOMPINI) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento inicial mudou [De: '||COALESCE(old.BDCOMPINI, 'VAZIO')||'] <-> [Para: '||COALESCE(new.BDCOMPINI, 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento inicial: '||COALESCE(old.BDCOMPINI, 'VAZIO');

  --Compl. final
  if (new.BDCOMPFIM <> old.BDCOMPFIM) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento final mudou [De: '||COALESCE(old.BDCOMPFIM, 'VAZIO')||'] <-> [Para: '||COALESCE(new.BDCOMPFIM, 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Complemento final: '||COALESCE(old.BDCOMPFIM, 'VAZIO');

  EXECUTE PROCEDURE SP_INSERIR_LOG(NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   VMSGLOG,
                                   0,
                                   1,
                                   NULL,
                                   NULL,
                                   upper('TfrLancaVerbasSimPRes'),
                                   'Lançamento de verbas sim para preparação de rescisão',
                                   NULL,
                                   'VRHF_BASE_TVSPRES',
                                   NULL,
                                   'FALSE',
                                   NULL);
end^

CREATE OR ALTER trigger vrhf_base_tvspres_ad0 for vrhf_base_tvspres
active after delete position 0
AS
declare variable VMSGLOG varchar(500);
begin
  VMSGLOG = '** Exclusão de verbas associadas para preparação de rescisão (sim) **';

  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Preparação rescisão: ' || COALESCE(old.BDCODPRES, 'VAZIO');
  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba: ' || COALESCE(old.BDCODVER, 'VAZIO');
  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial: ' ||COALESCE(NULLIF(old.BDDIAINIVSPRES, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINIVSPRES, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINIVSPRES, 0), '0000');

  EXECUTE PROCEDURE SP_INSERIR_LOG(NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   VMSGLOG,
                                   0,
                                   2,
                                   NULL,
                                   NULL,
                                   upper('TfrLancaVerbasSimPRes'),
                                   'Lançamento de verbas sim para preparação de rescisão',
                                   NULL,
                                   'VRHF_BASE_TVSPRES',
                                   NULL,
                                   'FALSE',
                                   NULL);
end^

CREATE OR ALTER trigger vrhf_base_tvster_au0 for vrhf_base_tvster
active after update position 0
AS
declare variable VMSGLOG varchar(500);
begin
  VMSGLOG = '** Alterações de verbas associadas para autônomo (sim) **';

  --AUTÔNOMO
  if (new.BDCODTER <> old.BDCODTER) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Autônomo mudou [De: '||COALESCE(old.BDCODTER, 'VAZIO')||'] <-> [Para: '||new.BDCODTER||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Autônomo: '||COALESCE(old.BDCODTER, 'VAZIO');

  --CHAVE
  if (new.BDCHAVE <> old.BDCHAVE) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Chave mudou [De: '||COALESCE(old.BDCHAVE, 'VAZIO')||'] <-> [Para: '||new.BDCHAVE||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Chave: '||COALESCE(old.BDCHAVE, 'VAZIO');

  --VERBA
  if (new.BDCODVER <> old.BDCODVER) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba mudou [De: '||COALESCE(old.BDCODVER, 'VAZIO')||'] <-> [Para: '||new.BDCODVER||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Verba: '||COALESCE(old.BDCODVER, 'VAZIO');

   --Data inicial
  if ((new.BDDIAINI <> old.BDDIAINI) or
     (new.BDMESINI <> old.BDMESINI) or
     (new.BDANOINI <> old.BDANOINI)) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial mudou [De: '||COALESCE(NULLIF(old.BDDIAINI, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINI, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINI, 0), '0000')||'] <-> [Para: '||COALESCE(NULLIF(new.BDDIAINI, 0), '00')||'/'||COALESCE(NULLIF(new.BDMESINI, 0), '00')||'/'||COALESCE(NULLIF(new.BDANOINI, 0), '0000')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data inicial: '||COALESCE(NULLIF(old.BDDIAINI, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESINI, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOINI, 0), '0000');

  --Data final
  if ((new.BDDIAFIM <> old.BDDIAFIM) or
     (new.BDMESFIM <> old.BDMESFIM) or
     (new.BDANOFIM <> old.BDANOFIM)) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data final mudou [De: '||COALESCE(NULLIF(old.BDDIAFIM, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESFIM, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOFIM, 0), '0000')||'] <-> [Para: '||COALESCE(NULLIF(new.BDDIAFIM, 0), '00')||'/'||COALESCE(NULLIF(new.BDMESFIM, 0), '00')||'/'||COALESCE(NULLIF(new.BDANOFIM, 0), '0000')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Data final: '||COALESCE(NULLIF(old.BDDIAFIM, 0), '00')||'/'||COALESCE(NULLIF(old.BDMESFIM, 0), '00')||'/'||COALESCE(NULLIF(old.BDANOFIM, 0), '0000');

    --Referência auxiliar
  if (new.BDFORMULAREFAUXILIAR <> old.BDFORMULAREFAUXILIAR) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência auxiliar mudou [De: '||COALESCE(NULLIF(old.BDFORMULAREFAUXILIAR, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAREFAUXILIAR, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência auxiliar: '||COALESCE(NULLIF(old.BDFORMULAREFAUXILIAR, ''), 'VAZIO');

  --Referência
  if (new.BDFORMULAREFERENCIA <> old.BDFORMULAREFERENCIA) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência mudou [De: '||COALESCE(NULLIF(old.BDFORMULAREFERENCIA, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAREFERENCIA, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Referência: '||COALESCE(NULLIF(old.BDFORMULAREFERENCIA, ''), 'VAZIO');

  --Valor
  if (new.BDFORMULAVALOR <> old.BDFORMULAVALOR) then
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Valor mudou [De: '||COALESCE(NULLIF(old.BDFORMULAVALOR, ''), 'VAZIO')||'] <-> [Para: '||COALESCE(NULLIF(new.BDFORMULAVALOR, ''), 'VAZIO')||']';
  else
     VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Valor: '||COALESCE(NULLIF(old.BDFORMULAVALOR, ''), 'VAZIO');

  EXECUTE PROCEDURE SP_INSERIR_LOG(NULL,
                                   old.bdcodter,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   VMSGLOG,
                                   0,
                                   1,
                                   NULL,
                                   NULL,
                                   upper('TfrLancamentoVerbasSimAutonomos'),
                                   'Lançamento de verbas sim para autônomo',
                                   NULL,
                                   'VRHF_BASE_TVSTER',
                                   NULL,
                                   'FALSE',
                                   NULL);
end^

CREATE OR ALTER trigger vrhf_base_tvster_ad0 for vrhf_base_tvster
active after delete position 0
AS
declare variable VMSGLOG varchar(500);
begin
  VMSGLOG = '** Exclusão de verbas associadas para autônomo (sim) **';

  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Autônomo: ' ||COALESCE(old.BDCODTER, 'VAZIO') ;
  VMSGLOG = VMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Chave: ' || COALESCE(old.BDCHAVE, 'VAZIO');

  EXECUTE PROCEDURE SP_INSERIR_LOG(NULL,
                                   old.bdcodter,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   NULL,
                                   VMSGLOG,
                                   0,
                                   2,
                                   NULL,
                                   NULL,
                                   upper('TfrLancamentoVerbasSimAutonomos'),
                                   'Lançamento de verbas sim para autônomo',
                                   NULL,
                                   'VRHF_BASE_TVSTER',
                                   NULL,
                                   'FALSE',
                                   NULL);
end^

create or alter procedure SP_VRHF_EXISTE_COMPLEMENTAR (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREFCOMP integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOMP integer)
as
begin
FOR   select C13.BDCODEMP, C13.BDCODCOL, C13.BDREF13 BDREF
      from VRHF_EMP_TC13SAL C13              --COMPLEMENTO 13
      where C13.BDCODEMP = :PRCODEMP and
            c13.BDREF13 = :PRREFCOMP and
            C13.BDCODCOL = :PRCODCOL
     union all
      select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFFN BDREF
      from VRHF_EMP_TFOLHACOMP FC           --FOLHA COMPLEMENTAR
      where FC.BDCODEMP = :PRCODEMP and
            FC.BDCODTIPOFC <> 3 and
            FC.BDCODCOL = :PRCODCOL and 
            FC.BDREFFN = :PRREFCOMP
     union all
      select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFCOMP BDREF
      from VRHF_EMP_TFOLTOMCOMP FC          --FOLHA TOMADOR COMPLEMENTAR
      where FC.BDCODEMP = :PRCODEMP and
            FC.BDCODCOL = :PRCODCOL and
            FC.BDCODTIPOFC <> 3 and
            FC.BDREFTOMADOR = :PRREFCOMP
     union all
       select  :PRCODEMP BDCODEMP,:PRCODCOL BDCODCOL, FC.BDREFCOMP BDREF
       from VRH_EMP_TCOLCON C
       join VRHF_EMP_TFOLHACOMP FC on FC.BDCODEMP = C.bdcodemp and FC.BDCODCOL = C.bdcodcol
       left outer join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and  FC.BDCODACCONV = AC.BDCODACCONV
       where C.BDCODEMP = :PRCODEMP and C.BDCODCOL = :PRCODCOL and
             FC.BDCODEMP = C.BDCODEMP and
            FC.BDCODTIPOFC = 3 and
             FC.BDCODCOL = C.BDCODCOL and
            AC.BDCODACCONV is not null and
            ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = :PRREFCOMP)
     union all
       select  :PRCODEMP BDCODEMP,:PRCODCOL BDCODCOL, FC.BDREFCOMP BDREF
       from VRH_EMP_TCOLCON C
       join VRHF_EMP_TFOLTOMCOMP FC on FC.BDCODEMP = C.bdcodemp and FC.BDCODCOL = C.bdcodcol
       left outer join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and  FC.BDCODACCONV = AC.BDCODACCONV
       where C.BDCODEMP = :PRCODEMP and C.BDCODCOL = :PRCODCOL and
             FC.BDCODEMP = C.BDCODEMP and
            FC.BDCODTIPOFC = 3 and
             FC.BDCODCOL = C.BDCODCOL and
            AC.BDCODACCONV is not null and
            ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = :PRREFCOMP)
     union all
      select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFFN
      from VRHF_EMP_TFOLHACOMPINT FC
      where FC.BDCODEMP = :PRCODEMP and
            FC.BDCODTIPOFC <> 3 and
            FC.BDCODCOL = :PRCODCOL and
            FC.BDREFFN = :PRREFCOMP
     union all
      select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFCOMP
      from VRHF_EMP_TFOLTOMCOMPINT FC
      where FC.BDCODEMP = :PRCODEMP and
            FC.BDCODCOL = :PRCODCOL and
            FC.BDCODTIPOFC <> 3 and
            FC.BDREFTOMADOR = :PRREFCOMP
     union all
      select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFCOMP
      from VRHF_EMP_TFOLHACOMPINT FC
      left outer join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and
            FC.BDCODACCONV = AC.BDCODACCONV
      where FC.BDCODEMP = :PRCODEMP and
            FC.BDCODTIPOFC = 3 and
            FC.BDCODCOL = :PRCODCOL and
            AC.BDCODACCONV is not null and
            ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = :PRREFCOMP)
     union all
      select FC.BDCODEMP, FC.BDCODCOL, FC.BDREFCOMP
      from VRHF_EMP_TFOLTOMCOMPINT FC
      left outer join VRH_EMP_TACCONV AC on FC.BDCODEMP = AC.BDCODEMP and
            FC.BDCODACCONV = AC.BDCODACCONV
      where FC.BDCODEMP = :PRCODEMP and
            FC.BDCODTIPOFC = 3 and
            FC.BDCODCOL = :PRCODCOL and
            AC.BDCODACCONV is not null and
            ((extract(year from AC.BDDTPGTOBRICONV) * 100) + extract(month from AC.BDDTPGTOBRICONV) = :PRREFCOMP) into :bdcodemp,:bdcodcol,:bdrefcomp do
     begin
       suspend;
     end
end^

CREATE or alter trigger tmenu_novos_bi0 for tmenu_novos
active before insert position 0
AS
begin
  if (NEW.bddatacadastro is null) then
    NEW.bddatacadastro = CURRENT_DATE;
end^

CREATE OR ALTER trigger tmenu_biu0 for tmenu
active before insert or update position 0
AS
begin
  if (new.bdcodigo is null) then
    select coalesce(max(bdcodigo), 0) + 1 from tmenu into new.bdcodigo;
end^

CREATE OR ALTER procedure SP_EXPORTA_BLOCOC500 (
    PRCODEMP integer,
    PRDTINI date,
    PRDTFIM date,
    PRCODPLAPADRAOREF integer,
    PRVALIDAREXPORTACAO boolean,
    PRARQUIVO varchar(260),
    PREXPSER varchar(5),
    PRSESSAOSEGREG integer,
    PRMOV integer,
    PREXPORTARC170EMISSAOPROPRIA varchar(5),
    PRCHAVENF integer)
as
declare variable WLINHA blob sub_type 1 segment size 200;
declare variable WSEGREGACAO varchar(5);
declare variable WFCPOP varchar(5);
BEGIN
  DELETE FROM TEXPORTACAO_SPED WHERE BDID = :PRARQUIVO;

  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(CAST((EXTRACT(YEAR FROM :PRDTINI) || LPAD(EXTRACT(MONTH FROM :PRDTINI),2,'0')) AS INTEGER));

  SELECT COALESCE(RDB$GET_CONTEXT('USER_SESSION', 'W_SEGREGACAO_FISCAL'),'FALSE') FROM RDB$DATABASE INTO WSEGREGACAO;

  IF (:PRMOV = 0) THEN
  BEGIN
      /********************************  ENTRADA  **********************************/
      /*****************************************************************************
       *                                  C595                                     *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS, BDCHAVE, BDCODEMP)
      SELECT :PRARQUIVO BDID,
             LPAD(MOV.BDCODEMP, 6, '0')||'.0.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C500.C595.'||LPAD(C595.BDORDEMOBS, 6, '0'),
             'C595' BDREG,
             '|C595'||
             '|'||COALESCE(OBS.BDCODEXP, '')|| --COD_OBS
             '|'||TRIM(COALESCE(REPLACE(C595.BDDESCCOMPL, '|', ''), ''))|| --TXT_COMPL
             '|',
              C595.BDCODOBS,
              MOV.BDCHAVE,
              MOV.BDCODEMP
      FROM (
            SELECT ENT.BDCODEMP, ENT.BDCHAVE
            FROM VEF_EMP_TMOVENT ENT
            LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = ENT.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
            WHERE ENT.BDCODEMP = :PRCODEMP AND ENT.BDCHAVE = :PRCHAVENF
            AND ENT.BDCHAVE = IIF(SEG.BDCHAVE IS NOT NULL AND :WSEGREGACAO = 'TRUE', SEG.BDCHAVE, ENT.BDCHAVE)
            AND ENT.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM
            AND ENT.BDMODELO IN (6, 28, 29, 66)
            AND ENT.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
           ) MOV
      JOIN VEF_EMP_TC195ENT C595 ON(C595.BDCODEMP = MOV.BDCODEMP AND C595.BDCHAVE = MOV.BDCHAVE AND (C595.BDTIPOOPERACAO = 'C595') )
      JOIN VEF_BASE_TOBSERVACAO OBS ON(OBS.BDCODOBS = C595.BDCODOBS);
      /*****************************************************************************
       *                                   C597                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD, BDCHAVE, BDCODEMP)
      SELECT :PRARQUIVO BDID,
           LPAD(MOV.BDCODEMP, 6, '0') || '.0.' || LPAD(MOV.BDCHAVE, 10, '0') || '.C500.C595.' || LPAD(MOV.BDORDEMOBS, 6, '0') || '.C597.' || LPAD(MOV.BDORDEMOUTOBR, 6, '0'),
           'C597' BDREG, '|C597' || '|' || COALESCE(AJU.BDCODAJUPAD, '') || --COD_AJ
           '|' || TRIM(COALESCE(REPLACE(MOV.BDDESCCOMPL, '|', ''), '')) || --DESCR_COMPL_AJ
           '|' || COALESCE(IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')), VINC.BDCODPROD, VINC.BDCODSAIDA), '') || --COD_ITEM
           '|' || REPLACE(COALESCE(MOV.BDBICMS, 0.00), '.', ',') || --VL_BC_ICMS
           '|' || REPLACE(CAST(COALESCE(MOV.BDALIQICMS, 0.00) AS DM_NUMERIC_15_2), '.', ',') || --ALIQ_ICMS
           '|' || REPLACE(COALESCE(MOV.BDVLRICMS, 0.00), '.', ',') || --VL_ICMS
           '|' || REPLACE(COALESCE(MOV.BDOUTVLR, 0.00), '.', ',') || --VL_OUTROS
           '|', MOV.BDCODPROD, MOV.BDCHAVE, MOV.BDCODEMP
     FROM (
          SELECT ENT.BDCODEMP, ENT.BDCHAVE, C597.BDCODPROD, C597.BDCODAJU, C597.BDORDEMOBS,
          MIN(C597.BDORDEMOUTOBR) BDORDEMOUTOBR,
          MAX(C597.BDDESCCOMPL) BDDESCCOMPL,
          C597.BDALIQICMS,
          SUM(C597.BDBICMS) BDBICMS,
          SUM(C597.BDVLRICMS) BDVLRICMS,
          SUM(C597.BDOUTVLR) BDOUTVLR
    
          FROM VEF_EMP_TMOVENT ENT
          LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = ENT.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
          JOIN VEF_EMP_TC195ENT C595 ON (C595.BDCODEMP = ENT.BDCODEMP AND
                C595.BDCHAVE = ENT.BDCHAVE AND
                C595.BDCODOBS IS NOT NULL AND (C595.BDTIPOOPERACAO = 'C595') )
          JOIN VEF_EMP_TC197ENT C597 ON (C597.BDCODEMP = C595.BDCODEMP AND
                C597.BDCHAVE = C595.BDCHAVE AND
                C597.BDORDEMOBS = C595.BDORDEMOBS)
          WHERE ENT.BDCODEMP = :PRCODEMP AND ENT.BDCHAVE = :PRCHAVENF AND
                ENT.BDCHAVE = IIF(SEG.BDCHAVE IS NOT NULL AND :WSEGREGACAO = 'TRUE', SEG.BDCHAVE, ENT.BDCHAVE) AND
                ENT.BDDATAENTRADAENT BETWEEN :PRDTINI AND :PRDTFIM AND
                ENT.BDMODELO IN (6, 28, 29, 66) AND
                ENT.BDCODSITNF NOT IN (2, 3, 4, 5, 10, 11)
          GROUP BY ENT.BDCODEMP, ENT.BDCHAVE, C597.BDCODPROD, C597.BDCODAJU, C597.BDORDEMOBS, C597.BDALIQICMS
     ) MOV
     LEFT OUTER JOIN VEF_BASE_TTABCODAJU AJU ON (AJU.BDCODAJU = MOV.BDCODAJU)
     LEFT OUTER JOIN TCADPRO_VINC VINC ON (VINC.BDCODEMP = MOV.BDCODEMP AND VINC.BDCODPROD = MOV.BDCODPROD);
 END
 ELSE
 BEGIN
      /********************************  SAIDA   **********************************/
      /*****************************************************************************
       *                                 C595                                      *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODOBS)
      SELECT :PRARQUIVO BDID,
             LPAD(MOV.BDCODEMP, 6, '0')||'.1.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C500.C595.'||LPAD(C595.BDORDEMOBS, 6, '0'),
             'C595' BDREG,
             '|C595'||
             '|'||COALESCE(OBS.BDCODEXP, '')|| --COD_OBS
             '|'||TRIM(COALESCE(REPLACE(C595.BDDESCCOMPL, '|', ''), ''))|| --TXT_COMPL
             '|',
              C595.BDCODOBS
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE
            FROM VEF_EMP_TMOVSAI SAI
            LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = SAI.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
            WHERE SAI.BDCODEMP = :PRCODEMP AND SAI.BDCHAVE = :PRCHAVENF
            AND SAI.BDCHAVE = IIF(SEG.BDCHAVE IS NOT NULL AND :WSEGREGACAO = 'TRUE', SEG.BDCHAVE, SAI.BDCHAVE)
            AND SAI.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND SAI.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
    
           ) MOV
      JOIN VEF_EMP_TC195SAI C595 ON(C595.BDCODEMP = MOV.BDCODEMP AND C595.BDCHAVE = MOV.BDCHAVE AND (C595.BDTIPOOPERACAO = 'C595'))
      JOIN VEF_BASE_TOBSERVACAO OBS ON(OBS.BDCODOBS = C595.BDCODOBS);
    
      /*****************************************************************************
       *                                   C597                                    *
       ****************************************************************************/
      INSERT INTO TEXPORTACAO_SPED(BDID, BDCHAVEREG, BDREG, BDLINHA, BDCODPROD)
      SELECT :PRARQUIVO BDID,
             LPAD(MOV.BDCODEMP, 6, '0')||'.1.'||LPAD(MOV.BDCHAVE, 10, '0')||'.C500.C595.'||LPAD(C597.BDORDEMOBS, 6, '0')||'.C597.'||LPAD(C597.BDORDEMOUTOBR, 6, '0'),
             'C597' BDREG,
             '|C597'||
             '|'||COALESCE(AJU.BDCODAJUPAD, '')|| --COD_AJ
             '|'||TRIM(COALESCE(REPLACE(C597.BDDESCCOMPL, '|', ''), ''))|| --DESCR_COMPL_AJ
             '|'||COALESCE(IIF(((VINC.BDCODSAIDA IS NULL) OR (VINC.BDCODSAIDA = '')), VINC.BDCODPROD, VINC.BDCODSAIDA), '')|| --COD_ITEM
             '|'||REPLACE(COALESCE(C597.BDBICMS, 0.00), '.', ',')|| --VL_BC_ICMS
             '|'||REPLACE(CAST(COALESCE(C597.BDALIQICMS, 0.00) AS DM_NUMERIC_15_2), '.', ',')|| --ALIQ_ICMS
             '|'||REPLACE(COALESCE(C597.BDVLRICMS, 0.00), '.', ',')|| --VL_ICMS
             '|'||REPLACE(COALESCE(C597.BDOUTVLR, 0.00), '.', ',')|| --VL_OUTROS
             '|', C597.BDCODPROD
      FROM (
            SELECT SAI.BDCODEMP, SAI.BDCHAVE
            FROM VEF_EMP_TMOVSAI SAI
            LEFT OUTER JOIN TMP_CHAVE_SEGREG_CFOP SEG ON (SEG.BDCODEMP = SAI.BDCODEMP AND SEG.BDSESSAO = :PRSESSAOSEGREG)
            WHERE SAI.BDCODEMP = :PRCODEMP AND SAI.BDCHAVE = :PRCHAVENF
            AND SAI.BDCHAVE = IIF(SEG.BDCHAVE IS NOT NULL AND :WSEGREGACAO = 'TRUE', SEG.BDCHAVE, SAI.BDCHAVE)
            AND SAI.BDDATAEMISSAO BETWEEN :PRDTINI AND :PRDTFIM
            AND SAI.BDCODSITNF NOT IN(2, 3, 4, 5, 10, 11)
    
           ) MOV
      JOIN VEF_EMP_TC195SAI C595 ON(C595.BDCODEMP = MOV.BDCODEMP AND C595.BDCHAVE = MOV.BDCHAVE AND C595.BDCODOBS IS NOT NULL AND (C595.BDTIPOOPERACAO = 'C595') )
      JOIN VEF_EMP_TC197SAI C597 ON(C597.BDCODEMP = C595.BDCODEMP AND C597.BDCHAVE = C595.BDCHAVE AND C597.BDORDEMOBS = C595.BDORDEMOBS)
      LEFT OUTER JOIN VEF_BASE_TTABCODAJU AJU ON(AJU.BDCODAJU = C597.BDCODAJU)
      LEFT OUTER JOIN TCADPRO_VINC VINC ON(VINC.BDCODEMP = MOV.BDCODEMP AND VINC.BDCODPROD = C597.BDCODPROD); 
END
  /*****************************************************************************
   *                           EXPORTANDO ARQUIVO                              *
   ****************************************************************************/
  OPENARQ(:PRARQUIVO,:PRCODEMP);
  FOR SELECT E.BDLINHA
      FROM TEXPORTACAO_SPED E
      WHERE E.BDID = :PRARQUIVO
      ORDER BY E.BDCHAVEREG
      INTO :WLINHA
  DO
    BEGIN
      WRITELNOA(:WLINHA,:PRCODEMP);
    END
  CLOSEARQ(:PRARQUIVO,:PRCODEMP);
END
^

CREATE OR ALTER TRIGGER EMPRESAS_TSOC_REF_AUD0 FOR EMPRESAS_TSOC_REF
ACTIVE AFTER UPDATE OR DELETE POSITION 0
AS
  DECLARE VARIABLE wProcesso varchar(255);
  DECLARE VARIABLE wEndereco varchar(255);
  DECLARE VARIABLE wPID INTEGER;
  DECLARE VARIABLE wHost varchar(255);
  DECLARE VARIABLE wOSUser varchar(255);  
  DECLARE VARIABLE wTipoACAO Integer;
begin

  IF (NEW.bdcodsoc IS NULL) THEN
    BEGIN
      wTipoAcao = 2;
    END
  ELSE
    BEGIN
      wTipoAcao = 1;
    END

  IF ((wTipoAcao = 2) OR ((NEW.BDCODSOC <> OLD.BDCODSOC) OR (NEW.BDREFSOC <> OLD.BDREFSOC) OR (TRIM(NEW.BDNOMSOC) = ''))) THEN
    BEGIN
      select
        trim(mon$remote_process),
        trim(MON$REMOTE_ADDRESS),
        MON$REMOTE_PID,
        TRIM(MON$REMOTE_HOST),
        TRIM(MON$REMOTE_OS_USER)
      from mon$attachments where mon$attachment_id=current_connection into :wProcesso, :wEndereco, :wPID, :wHost, :wosuser;

      EXECUTE PROCEDURE sp_inserir_log(OLD.bdcodemp, NULL,NULL, NULL,rdb$get_context('USER_SESSION', 'W_CODSIS'), NULL, null, null,
      BLOB_APPEND(
                    'Registro sócio REF excluído ou alterado: ', ASCII_CHAR(13) || ASCII_CHAR(10),
                    'Código: ', OLD.bdcodsoc, ' Referência: ', old.bdrefsoc, ASCII_CHAR(13) || ASCII_CHAR(10),
                    'Nome antigo: ', old.bdnomsoc, ' Nome novo: ', new.bdnomsoc, ASCII_CHAR(13) || ASCII_CHAR(10),
                    'Hora: ', current_timestamp, ASCII_CHAR(13) || ASCII_CHAR(10),
                    'Conexão/Usuário: ', current_connection, ' - ', current_user, ASCII_CHAR(13) || ASCII_CHAR(10),
                    'PID/Processo: ', :wPID, ' - ', :wProcesso, ASCII_CHAR(13) || ASCII_CHAR(10),
                    'Endereço/HOST/Usuário: ', :wEndereco, ' - ', :wHost, ' - ', :wosuser, ASCII_CHAR(13) || ASCII_CHAR(10),
                    'Dados Único:', ASCII_CHAR(13) || ASCII_CHAR(10),
                    'Tela: ', rdb$get_context('USER_SESSION', 'W_NOMETELA'), ' - ', rdb$get_context('USER_SESSION', 'W_CAPTIONTELA'), ASCII_CHAR(13) || ASCII_CHAR(10),
                    'Usuário/Sistema: ', rdb$get_context('USER_SESSION', 'W_USUARIO'), ' - ', rdb$get_context('USER_SESSION', 'W_CODSIS'), ASCII_CHAR(13) || ASCII_CHAR(10),
                    'Usuário Internet: ', rdb$get_context('USER_SESSION', 'W_CODUSU_INTRANET'), ' - ', rdb$get_context('USER_SESSION', 'W_NOMUSU_INTRANET') , ASCII_CHAR(13) || ASCII_CHAR(10),
                    'IP Máquina/Máquina: ', rdb$get_context('USER_SESSION', 'W_IPMICRO'), ' - ', rdb$get_context('USER_SESSION', 'W_NOMEMICRO'), ASCII_CHAR(13) || ASCII_CHAR(10),
                    'Ultimo log da conexão: ', rdb$get_context('USER_SESSION', 'W_ULT_ID_LOG')), 0, wTipoAcao,CURRENT_USER, rdb$get_context('USER_SESSION', 'W_NOMEMICRO'), rdb$get_context('USER_SESSION', 'W_NOMETELA'), rdb$get_context('USER_SESSION', 'W_CAPTIONTELA'), NULL, 'TTERCEIRO_REF', NULL, 'FALSE', null);
    END
end^

CREATE OR ALTER TRIGGER TTERCEIRO_REF_AUD0 FOR TTERCEIRO_REF
ACTIVE AFTER UPDATE OR DELETE POSITION 0
AS
  DECLARE VARIABLE wProcesso varchar(255);
  DECLARE VARIABLE wEndereco varchar(255);
  DECLARE VARIABLE wPID INTEGER;
  DECLARE VARIABLE wHost varchar(255);
  DECLARE VARIABLE wOSUser varchar(255);  
  DECLARE VARIABLE wTipoACAO Integer;
begin
  IF (NEW.bdcodter IS NULL) THEN
      BEGIN
        wTipoAcao = 2;
      END
  ELSE
      BEGIN
        wTipoAcao = 1;
      END

  if ((wTipoAcao = 2) or (((Trim(NEW.bdnometer) = '') or (NEW.bdcodter <> OLD.bdcodter) or (NEW.bdrefemp <> OLD.bdrefemp)))) then
     BEGIN
      select
        trim(mon$remote_process),
        trim(MON$REMOTE_ADDRESS),
        MON$REMOTE_PID,
        TRIM(MON$REMOTE_HOST),
        TRIM(MON$REMOTE_OS_USER)
      from mon$attachments where mon$attachment_id=current_connection into :wProcesso, :wEndereco, :wPID, :wHost, :wosuser;

      EXECUTE PROCEDURE sp_inserir_log(null, OLD.bdcodter,1, 0,  rdb$get_context('USER_SESSION', 'W_CODSIS'), NULL, null, null,
      BLOB_APPEND(
                  'Registro terceiro REF excluído ou alterado: ', ASCII_CHAR(13) || ASCII_CHAR(10),
                  'Código: ', OLD.BDCODTER, ' Referência: ', old.bdrefemp, ASCII_CHAR(13) || ASCII_CHAR(10),
                  'Nome antigo: ', old.bdnometer, ' Nome novo: ', new.bdnometer, ASCII_CHAR(13) || ASCII_CHAR(10),
                  'Hora: ', current_timestamp, ASCII_CHAR(13) || ASCII_CHAR(10),
                  'Conexão/Usuário: ', current_connection, ' - ', current_user, ASCII_CHAR(13) || ASCII_CHAR(10),
                  'PID/Processo: ', :wPID, ' - ', :wProcesso, ASCII_CHAR(13) || ASCII_CHAR(10),
                  'Endereço/HOST/Usuário: ', :wEndereco, ' - ', :wHost, ' - ', :wosuser, ASCII_CHAR(13) || ASCII_CHAR(10),
                  'Dados Único:', ASCII_CHAR(13) || ASCII_CHAR(10),
                  'Tela: ', rdb$get_context('USER_SESSION', 'W_NOMETELA'), ' - ', rdb$get_context('USER_SESSION', 'W_CAPTIONTELA'), ASCII_CHAR(13) || ASCII_CHAR(10),
                  'Usuário/Sistema: ', rdb$get_context('USER_SESSION', 'W_USUARIO'), ' - ', rdb$get_context('USER_SESSION', 'W_CODSIS'), ASCII_CHAR(13) || ASCII_CHAR(10),
                  'Usuário Internet: ', rdb$get_context('USER_SESSION', 'W_CODUSU_INTRANET'), ' - ', rdb$get_context('USER_SESSION', 'W_NOMUSU_INTRANET') , ASCII_CHAR(13) || ASCII_CHAR(10),
                  'IP Máquina/Máquina: ', rdb$get_context('USER_SESSION', 'W_IPMICRO'), ' - ', rdb$get_context('USER_SESSION', 'W_NOMEMICRO'), ASCII_CHAR(13) || ASCII_CHAR(10),
                  'Ultimo log da conexão: ', rdb$get_context('USER_SESSION', 'W_ULT_ID_LOG')), 0, wTipoAcao,CURRENT_USER, rdb$get_context('USER_SESSION', 'W_NOMEMICRO'), rdb$get_context('USER_SESSION', 'W_NOMETELA'), rdb$get_context('USER_SESSION', 'W_CAPTIONTELA'), NULL, 'TTERCEIRO_REF', NULL, 'FALSE', null);
       END
end^

-- Gestão - Gerenciamento de processos Início
CREATE OR ALTER TRIGGER VCT_BASE_PROCESSOS_BI0 FOR VCT_BASE_PROCESSOS
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcodproc integer;
begin
  if (coalesce(new.bdcodproc, 0) = 0) then
  begin
    select max(bdcodproc) from VCT_BASE_PROCESSOS
    into :vcodproc;
    new.bdcodproc = coalesce(vcodproc, 0) +1;
  end
  else
  begin
    select bdcodproc from VCT_BASE_PROCESSOS
    where bdcodproc = new.bdcodproc
    into :vcodproc;    if (coalesce(vcodproc, 0) > 0) then
    begin
      select max(bdcodproc) from VCT_BASE_PROCESSOS
      into :vcodproc;
      new.bdcodproc = coalesce(vcodproc, 0) +1;
    end
  end
end^

create or alter trigger VCT_BASE_PROCESSOS_AI0 for VCT_BASE_PROCESSOS
active after insert or update position 0
as
declare variable VEXTINTO integer;
begin
  if (:new.BDEXTINTO is not null) then
  begin
    VEXTINTO = cast((extract(year from new.BDEXTINTO) || lpad(extract(month from new.BDEXTINTO), 2, 0)) as integer);

    update VCT_TRIBUTARIO_EMPRESA Y
    set Y.BDREFFINPROC = :VEXTINTO
    where (Y.BDCODPROC = :new.BDCODPROC) and
          ((Y.BDREFFINPROC is null) or (Y.BDREFFINPROC > :VEXTINTO));
  end
  else
  begin
    VEXTINTO = cast((extract(year from old.BDEXTINTO) || lpad(extract(month from old.BDEXTINTO), 2, 0)) as integer);

    if (:old.BDEXTINTO is not null) then
    begin
      update VCT_TRIBUTARIO_EMPRESA Y
      set Y.BDREFFINPROC = null
      where (Y.BDCODPROC = :new.BDCODPROC) and
            (coalesce(Y.BDREFFINPROC, 0) = coalesce(:VEXTINTO, 0));
    end
  end
end^


CREATE OR ALTER TRIGGER TR_VEF_EMP_TLANDESIFSER_DEL FOR VEF_EMP_TLANDESIFSER
ACTIVE BEFORE DELETE POSITION 0
AS
BEGIN
    DELETE FROM VSUC_EMPRESAS_TLDESIF 
    WHERE BDCODEMP = OLD.BDCODEMP AND
          BDCHAVE NOT IN (
                        select DES.BDCHAVE
                        from (select *
                              from VEF_EMP_TLANDESIFSER EF
                              where EF.BDCODEMP = old.bdcodemp and
                                    EF.BDCHAVE = old.bdchave and
                                    EF.BDORDEM = old.bdordem and
                                    EF.BDDEBCRE = old.bddebcre) SER
                        join TOL_VEF_EMP_TMOVSER TOL on TOL.BDCHAVESER = SER.BDCHAVE and TOL.BDCODEMPSUC = SER.BDCODEMP and TOL.BDORDEM = SER.BDORDEM
                        join VSUC_EMPRESAS_TLAN TLAN on TLAN.BDCODEMP = SER.BDCODEMP and TLAN.BDCHAVE = TOL.BDCHAVE
                        JOIN VSUC_EMPRESAS_TLDESIF DES ON DES.BDCODEMP = TLAN.BDCODEMP AND DES.BDCHAVE = TLAN.BDCHAVE);
END^

CREATE OR ALTER TRIGGER VCT_BASE_PROCESSOTAREFAS_BI0 FOR VCT_BASE_PROCESSOTAREFAS
ACTIVE BEFORE INSERT POSITION 0
AS
  declare variable vcodproctar integer;
  declare variable vsequencia integer;
begin
  if (coalesce(new.bdcodproc, 0) = 0) then
  begin
    select max(bdcodproc) from VCT_BASE_PROCESSOS
    into new.bdcodproc;
  end
  if (coalesce(new.bdcodproctar, 0) = 0) then
  begin
    select max(bdcodproctar) from VCT_BASE_PROCESSOTAREFAS
    where bdcodproc = new.bdcodproc
    into :vcodproctar;
    new.bdcodproctar = coalesce(vcodproctar, 0) +1;
  end
  else
  begin
    select bdcodproctar from VCT_BASE_PROCESSOTAREFAS
    where bdcodproc = new.bdcodproc and bdcodproctar = new.bdcodproctar
    into :vcodproctar;

    if (coalesce(vcodproctar, 0) > 0) then
    begin
      select max(bdcodproctar) from VCT_BASE_PROCESSOTAREFAS
      where bdcodproc = new.bdcodproc
      into :vcodproctar;
      new.bdcodproctar = coalesce(vcodproctar, 0) +1;
    end
  end
  if (coalesce(new.bdsequencia, 0) = 0) then
  begin
    select max(bdsequencia) from VCT_BASE_PROCESSOTAREFAS
    where bdcodproc = new.bdcodproc
    into :vsequencia;
    new.bdsequencia = coalesce(vsequencia, 0) +1;
  end
end^

CREATE OR ALTER TRIGGER TGRUPOUSUARIO_USUARIO_AD0 FOR TGRUPOUSUARIO_USUARIO
ACTIVE AFTER DELETE POSITION 1
AS
begin
  DELETE FROM VCT_DEPARTAMENTO_USUARIO
  WHERE BDCODUSU = OLD.BDCODUSU
    AND EXISTS(SELECT FIRST 1 X.BDCODDEP FROM VCT_DEPARTAMENTO_GRUPOS X
               JOIN TGRUPOUSUARIO_USUARIO Y ON (Y.BDCODGRUPO = X.BDCODGRUPO AND Y.BDCODUSU = OLD.BDCODUSU)
               WHERE X.BDCODGRUPO = OLD.BDCODGRUPO)
    AND NOT EXISTS(SELECT FIRST 1 X.BDCODDEP FROM VCT_DEPARTAMENTO_GRUPOS X
                   JOIN TGRUPOUSUARIO_USUARIO Y ON (Y.BDCODGRUPO = X.BDCODGRUPO AND Y.BDCODUSU = OLD.BDCODUSU)
                   WHERE X.BDCODGRUPO <> OLD.BDCODGRUPO)
    AND COALESCE(BDGESTOR, FALSE) = FALSE;
end
^

CREATE OR ALTER TRIGGER TGRUPOUSUARIO_USUARIO_AI0 FOR TGRUPOUSUARIO_USUARIO
ACTIVE AFTER INSERT POSITION 0
AS
begin
  INSERT INTO VCT_DEPARTAMENTO_USUARIO (BDCODDEP, BDCODUSU, BDGESTOR)
  SELECT FIRST 1 BDCODDEP, NEW.BDCODUSU, FALSE
  FROM VCT_DEPARTAMENTO_GRUPOS X
  WHERE X.BDCODGRUPO = NEW.BDCODGRUPO
    AND NOT EXISTS(SELECT 1 FROM VCT_DEPARTAMENTO_USUARIO WHERE BDCODUSU = NEW.BDCODUSU);
end
^

CREATE OR ALTER trigger vct_departamento_bi0 for vct_departamento
active before insert position 0
AS
  DECLARE VARIABLE vBDCODDEP INTEGER;
BEGIN
  IF ((NEW.BDCODDEP IS NULL) OR (NEW.BDCODDEP = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODDEP) + 1, 1)
       FROM VCT_DEPARTAMENTO
       INTO :vBDCODDEP;

       NEW.BDCODDEP = :vBDCODDEP;
     END
END
^

CREATE OR ALTER TRIGGER VCT_DEPARTAMENTO_GRUPOS_AD0 FOR VCT_DEPARTAMENTO_GRUPOS
ACTIVE AFTER DELETE POSITION 0
AS
begin
  DELETE FROM VCT_DEPARTAMENTO_USUARIO
  WHERE BDCODUSU IN (SELECT BDCODUSU FROM TGRUPOUSUARIO_USUARIO WHERE BDCODGRUPO = OLD.BDCODGRUPO)
    AND BDCODDEP = OLD.BDCODDEP
    AND BDGESTOR = FALSE;
end
^

CREATE OR ALTER TRIGGER VCT_DEPARTAMENTO_GRUPOS_AI0 FOR VCT_DEPARTAMENTO_GRUPOS
ACTIVE AFTER INSERT POSITION 0
AS
begin
  INSERT INTO VCT_DEPARTAMENTO_USUARIO (BDCODUSU, BDCODDEP, BDGESTOR)
  SELECT BDCODUSU, NEW.BDCODDEP, FALSE
  FROM TGRUPOUSUARIO_USUARIO GRP
  WHERE BDCODGRUPO = NEW.BDCODGRUPO
    AND NOT EXISTS(SELECT 1 FROM VCT_DEPARTAMENTO_USUARIO
                   WHERE BDCODUSU = GRP.BDCODUSU
                     AND BDCODDEP = NEW.BDCODDEP);
end
^


create or alter trigger VCT_EMPRESA_TSOLICITATAREFA_BI1 for VCT_EMPRESA_TSOLICITATAREFA
active before insert position 0
as
declare variable VCODIMP integer;
declare variable VCODOBRIGACAO integer;
declare variable VCODSERVICO integer;
declare variable VCOUNT integer;
declare variable VTIPOSOLICITACAO integer;
begin
  if (new.BDCODPROC is not null) then
  begin
    if (new.BDCODIMP is null and
        new.BDCODOBRIGACAO is null and
        new.BDCODSERVICO is null) then
    begin
      VCOUNT = 0;
      for select BDCODIMP, BDCODOBRIGACAO, BDCODSERVICO
          from (select PROCTAR.BDCODIMP, PROCTAR.BDCODOBRIGACAO, PROCTAR.BDCODSERVICO, PROCTAR.BDCODPROC,
                       PROCTAR.BDSEQUENCIA
                from VCT_BASE_PROCESSOTAREFAS PROCTAR
                inner join TIMPOSTO IMP on (IMP.BDCODIMP = PROCTAR.BDCODIMP)
                where (IMP.BDDATAEXTINTO is null) or (IMP.BDDATAEXTINTO >= current_date)
                union
                select PROCTAR.BDCODIMP, PROCTAR.BDCODOBRIGACAO, PROCTAR.BDCODSERVICO, PROCTAR.BDCODPROC,
                       PROCTAR.BDSEQUENCIA
                from VCT_BASE_PROCESSOTAREFAS PROCTAR
                inner join VCT_BASE_OBRIGACAO OBR on (OBR.BDCODOBRSER = PROCTAR.BDCODOBRIGACAO)
                where (OBR.BDEXTINTO is null) or (OBR.BDEXTINTO >= current_date)
                union
                select PROCTAR.BDCODIMP, PROCTAR.BDCODOBRIGACAO, PROCTAR.BDCODSERVICO, PROCTAR.BDCODPROC,
                       PROCTAR.BDSEQUENCIA
                from VCT_BASE_PROCESSOTAREFAS PROCTAR
                inner join VCT_BASE_SERVICO SER on (SER.BDCODOBRSER = PROCTAR.BDCODSERVICO)
                where (SER.BDEXTINTO is null) or (SER.BDEXTINTO >= current_date))
          where BDCODPROC = new.BDCODPROC
          order by BDSEQUENCIA
          into :VCODIMP, :VCODOBRIGACAO, :VCODSERVICO
      do
      begin
        VTIPOSOLICITACAO = null;
        if (VCODIMP is not null and
            VCODOBRIGACAO is null and
            VCODSERVICO is null) then
          VTIPOSOLICITACAO = 0;
        else
        if (VCODIMP is null and
            VCODOBRIGACAO is not null and
            VCODSERVICO is null) then
          VTIPOSOLICITACAO = 1;
        else
        if (VCODIMP is null and
            VCODOBRIGACAO is null and
            VCODSERVICO is not null) then
          VTIPOSOLICITACAO = 2;

        if (VCOUNT = 0) then
        begin
          new.BDCODIMP = :VCODIMP;
          new.BDCODOBRIGACAO = :VCODOBRIGACAO;
          new.BDCODSERVICO = :VCODSERVICO;
          new.BDCODSTVINCPROCESSO = new.BDCODST;
          new.BDTIPOSOLICITACAO = :VTIPOSOLICITACAO;
        end
        else
        begin
          insert into VCT_EMPRESA_TSOLICITATAREFA (BDCODEMP, BDCODST, BDCODUSU, BDCODCOL, BDCODIMP, BDCODOBRIGACAO,
                                                   BDCODSERVICO, BDCODTIPO, BDDATASOL, BDFATURAR, BDDATASOLICITADA,
                                                   BDDATAPREVISAO, BDDATAFIM, BDVENCIMENTO, BDENTREGA, BDSERIE,
                                                   BDREFSOL, BDQUANTIDADE, BDVALORUNITARIO, BDVALORDESCONTO,
                                                   BDTIPODESCONTO, BDPARCELAS, BDTIPOSOLICITACAO, BDCHAVEWEB, BDCODPROC,
                                                   BDCODSTVINCPROCESSO)
          values (new.BDCODEMP, null, new.BDCODUSU, new.BDCODCOL, :VCODIMP, :VCODOBRIGACAO, :VCODSERVICO, new.BDCODTIPO,
                  new.BDDATASOL, new.BDFATURAR, new.BDDATASOLICITADA, new.BDDATAPREVISAO, new.BDDATAFIM,
                  new.BDVENCIMENTO, new.BDENTREGA, new.BDSERIE, new.BDREFSOL, new.BDQUANTIDADE, new.BDVALORUNITARIO,
                  new.BDVALORDESCONTO, new.BDTIPODESCONTO, new.BDPARCELAS, :VTIPOSOLICITACAO, new.BDCHAVEWEB,
                  new.BDCODPROC, new.BDCODST);
        end
        VCOUNT = VCOUNT + 1;
      end
      if (VCOUNT = 0) then
        exception EX_CUSTOM 'Não foram encontradas tarefas vigentes para o processo';
    end
    else
    if (new.BDCODSTVINCPROCESSO is null and
        new.BDCODTIPO = 501) then
    begin
      new.BDCODSTVINCPROCESSO = new.BDCODST;
    end
  end
end^


create or alter procedure VCT_PROCESSOS_AUTOMATICOS (
    CODEMP integer = 0,
    data date = current_date,
    PERIODICIDADE integer = null,
    PROCESSO integer = null,
    "MANUAL" boolean = false)
returns (
    TOTAL integer,
    IMPOSTOS integer,
    OBRIGACOES integer,
    SERVICOS integer,
    PROCESSOS integer)
as
declare variable WSQL varchar(8192);
declare variable WCONFIG_EMP smallint;
declare variable WBDCODPROC integer;
declare variable WBDPERIODICIDADE integer;
declare variable WCURRENT_DATE date = current_date;
declare variable WCURRENT_REF integer;
declare variable WRECONTABILIZANDO DM_BOOLEAN;
declare variable WBDREFSOL integer;
declare variable WIMPOSTOS integer;
declare variable WOBRIGACOES integer;
declare variable WSERVICOS integer;
declare variable WTOTAL integer;
declare variable WBDCODEMP integer;
declare variable WBDCODSER integer;
declare variable WBDCODOBR integer;
declare variable WBDCODIMP integer;
begin
  WCURRENT_DATE = data;
  WCURRENT_REF = cast(extract(year from data)||lpad(extract(month from data),2,0) as integer);

  -- não gerar tarefas automáticas para clientes que não estejam personalizados para o controles
  if (((select BDCODIGO
        from TPERSONALIZACAO
        where (BDSISTEMAS containing '58') or (BDSISTEMAS containing '1506')) is null) or
      -- caso houver uma data de finalização anterior a data atual
      ((select first 1 BDDATAFINAL
        from TPESSOATOSISTEMA
        where (BDSISTEMA in (1506, 58)) and
              ((BDDATAFINAL is not null) and
              (BDDATAFINAL <= current_date))) is not null) or
      -- não gerar tarefas antes da data configurada
      ((select BDDATATAREFA
        from VCT_CONFIG_DATAS
        where BDDATATAREFA <= :WCURRENT_DATE) is null) or
      -- não deixar gerar tarefas automáticas no cadastro de empresas
      (coalesce((select cast((trim(rdb$get_context('USER_SESSION', 'W_CADEMPRESA'))) as integer)
                 from RDB$DATABASE), 0) <> 0)) then
    exit;

  select trim(upper(coalesce(rdb$get_context('USER_SESSION', 'W_RECONTABILIZA'), '')))
  from RDB$DATABASE
  into :WRECONTABILIZANDO;
  if (WRECONTABILIZANDO = 'TRUE') then
    exit;

  WCONFIG_EMP = 0;
  if ((select first 1 BDCODEMP
       from VCT_CONFIG_TAREFA_EMPRESA) is not null) then
    WCONFIG_EMP = 1;

  TOTAL = 0;
  IMPOSTOS = 0;
  OBRIGACOES = 0;
  SERVICOS = 0;

  --Lívia - 29/04/2025 - #213605 - Tela gerar tarefas recorrentes - adicionar campos dos tipos de tarefas e dos processos
  WSQL = 'select TRIB.BDCODEMP, TPROC.BDCODPROC, TPROC.BDPERIODICIDADE, ';
  WSQL = WSQL || WCURRENT_REF || ' as BDREFSOL, TRIB.BDCODSER, TRIB.BDCODOBR, TRIB.BDCODIMP ';
  WSQL = WSQL || 'from VCT_TRIBUTARIO_EMPRESA TRIB ';
  WSQL = WSQL || 'join VCT_BASE_PROCESSOS TPROC on (TPROC.BDCODPROC = TRIB.BDCODPROC) ';
--  WSQL = WSQL || 'join TEMPRESAS TEMP on (TEMP.BDCODEMP = TRIB.BDCODEMP and TEMP.BDDATAINIATIVEMP < ''' || WCURRENT_DATE || ''' and ((TEMP.BDDATAFIMATIVEMP > ''' || WCURRENT_DATE || ''') or (TEMP.BDDATAFIMATIVEMP is null))) ';
  WSQL=WSQL||'JOIN tempresas temp ON(temp.bdcodemp=trib.bdcodemp AND ';
  if(manual)then
  begin
    WSQL=WSQL||'(cast(extract(year from TEMP.BDDATAINIATIVEMP)||lpad(extract(month from TEMP.BDDATAINIATIVEMP),2,0)as integer)< '||WCURRENT_REF||' and ';
    WSQL=WSQL||'(cast(extract(year from TEMP.BDDATAINIATIVEMP)||lpad(extract(month from TEMP.BDDATAINIATIVEMP),2,0)as integer)> '||WCURRENT_REF||')';
  end
  else
    WSQL=WSQL||'temp.bddatainiativemp<'''||WCURRENT_DATE||''' AND((temp.bddatafimativemp>'''||WCURRENT_DATE||''')';
  WSQL=WSQL||'OR(temp.bddatafimativemp IS NULL)))';

  if (WCONFIG_EMP = 1) then
    WSQL = WSQL || 'join VCT_CONFIG_TAREFA_EMPRESA X on (X.BDCODEMP=TRIB.BDCODEMP)';

  WSQL = WSQL || 'where ((TPROC.BDEXTINTO >= ''' || WCURRENT_DATE || ''') or (TPROC.BDEXTINTO IS NULL)) ';
  WSQL = WSQL || 'and coalesce(TPROC.BDPERIODICIDADE, 0) <> 11 '; -- indefinido

  if (PROCESSO is not null) then
    WSQL = WSQL || ' and TPROC.BDCODPROC=' || PROCESSO;

  if (coalesce(CODEMP, 0) <> 0) then
    WSQL = WSQL || 'and TRIB.BDCODEMP = ' || CODEMP;

  if (PERIODICIDADE is not null) then
    WSQL = WSQL || 'and(TPROC.BDPERIODICIDADE=' || :PERIODICIDADE || ')';

  WSQL = WSQL || 'and((TRIB.BDREFINI <= ' || WCURRENT_REF || ') and (COALESCE(TRIB.BDREFFINPROC, ' || WCURRENT_REF || ')>=' || WCURRENT_REF || '))';
  PROCESSOS = 0;


  for execute statement WSQL into :WBDCODEMP, :WBDCODPROC, :WBDPERIODICIDADE, :WBDREFSOL, :WBDCODSER, :WBDCODOBR, :WBDCODIMP do
  begin
    WCURRENT_DATE = data; -- Resetar data antes de gerar
        -- mensal - vencimento conforme parâmetros
    if ((WBDPERIODICIDADE in (0, 1, 2, 3, 4, 5, 6)) or
        -- trimestral - gera março, junho, setembro, dezembro com vencimento conforme parametros
        ((WBDPERIODICIDADE = 7) and
        (substring(WBDREFSOL from 5 for 2) in (3, 6, 9, 12))) or
        -- trimestral parcelado
        ((WBDPERIODICIDADE = 8) and
        (substring(WBDREFSOL from 5 for 2) in (3, 6, 9, 12))) or
        -- trimestral antecipado - gera em janeiro com vencimento em fevereiro, março e abril
        --                       - gera em abril com vencimento em maio,junho e julho
        --                       - gera em julho com vencimento em agosto,setembro e outubro
        --                       - gera em outubro com vencimento em novembro,dezembro e janeiro do próximo ano
        ((WBDPERIODICIDADE = 9) and
        (substring(WBDREFSOL from 5 for 2) in (1, 4, 7, 10))) or
        -- anual - gera no primeiro mês do ano com vencimento no ano seguinte
        ((WBDPERIODICIDADE = 10) and
        (extract(month from :WCURRENT_DATE) = 1)) or
        -- diária
        (WBDPERIODICIDADE = 12) or
        -- semestral - gera junho,dezembro
        ((WBDPERIODICIDADE = 13) and
        (substring(WBDREFSOL from 5 for 2) in (6, 12)))
        ) then
    begin
      select TOTAL, IMPOSTOS, OBRIGACOES, SERVICOS
      from VCT_TAREFAS_AUTOMATICAS(:WBDCODEMP, :DATA, :WBDCODIMP, :WBDCODOBR, :WBDCODSER, null,null,:WBDPERIODICIDADE, :WBDCODPROC, :manual)
      into :WTOTAL, :WIMPOSTOS, :WOBRIGACOES, :WSERVICOS;
  
      IMPOSTOS = IMPOSTOS + WIMPOSTOS;
      OBRIGACOES = OBRIGACOES + WOBRIGACOES;
      SERVICOS = SERVICOS + WSERVICOS;
      TOTAL = TOTAL + WTOTAL;
  
      if ((IMPOSTOS + OBRIGACOES + SERVICOS) > 0) then
        PROCESSOS = PROCESSOS + 1;
    end
  end

  suspend;
  execute procedure SP_INSERIR_LOG(:CODEMP, null, coalesce((select BDCODUSU from SP_GET_USUARIO), 1), null, 8, null,
      :WCURRENT_DATE, current_time,
      'O servidor executou a rotina de geração dos processos automáticos' || ascii_char(13) || 'Processos: ' || :PROCESSOS || ascii_char(13) || 'Impostos: ' || :IMPOSTOS || ascii_char(13) || 'Obrigações: ' || :OBRIGACOES || ascii_char(13) || 'Serviços: ' || :SERVICOS || ascii_char(13) || 'Total: ' || :TOTAL,
      0, 0, 'Servidor', 'Servidor', 'ServidorSCI', 'Thread de tarefas automáticas', null, 'VCT_TAREFAS_AUTOMATICAS',
      null, 'FALSE', :WCURRENT_DATE);
end^

CREATE OR ALTER TRIGGER TARQUIVAMENTO_CONTABIL_JOB_BI0 FOR TARQUIVAMENTO_CONTABIL_JOB
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (new.bdordem is null) then
  begin
    select max(bdORDEM) from TARQUIVAMENTO_CONTABIL_JOB into new.bdordem;
    if (new.bdordem is null) then
    begin
      new.bdordem = 0;
    end

    new.bdordem = new.bdordem + 1;
  end
end^


create or alter trigger TTELA_SELECOPROCESSOSBASE_BI0 for TTELA_SELECOEPROCESSOSBASE
active before insert position 0
as
declare variable VNOVOCOD integer;

begin
  if (coalesce(new.BDCODIGOSEL, 0) = 0) then
  begin
    select first 1 BDCODIGOSEL
    from TTELA_SELECOEPROCESSOSBASE
    order by BDCODIGOSEL desc
    into :VNOVOCOD;
    new.BDCODIGOSEL = coalesce(VNOVOCOD, 0) + 1;
  end
end^

create or alter trigger TTELA_SELPROCESSOSBASE_BI0 for TTELA_SELPROCESSOSBASE
active before insert position 0
as
declare variable VNOVOCOD integer;

begin
  if (coalesce(new.BDCODIGOSEL, 0) = 0) then
  begin
    select first 1 BDCODIGOSEL
    from TTELA_SELPROCESSOSBASE
    order by BDCODIGOSEL desc
    into :VNOVOCOD;
    new.BDCODIGOSEL = coalesce(VNOVOCOD, 0);
  end
end^

-- Gestão - Gerenciamento de processos Fim


CREATE OR ALTER trigger tautomatizacoes_bi for tautomatizacoes
active before insert position 0
AS
  DECLARE VARIABLE wProxSeq INTEGER;
  DECLARE VARIABLE wEliminaAnterior varchar(5000);
BEGIN
    SELECT FIRST 1 BDSEQUENCIAL FROM tautomatizacoes ORDER BY BDSEQUENCIAL DESC INTO wProxSeq;

    NEW.BDSEQUENCIAL = coalesce(wProxSeq, 0) + 1;
 
   wEliminaAnterior = 'delete from tautomatizacoes where BDSEQUENCIAL < '||NEW.BDSEQUENCIAL||' and bdstatus = 0'||
                      ' and bdprocesso = '||new.bdprocesso;
 
   if (new.bdempresa is null) then
      wEliminaAnterior = wEliminaAnterior||' and bdempresa is null';
   else
      wEliminaAnterior = wEliminaAnterior||' and bdempresa ='||new.bdempresa;
 
   if (new.bdplano is null) then
      wEliminaAnterior = wEliminaAnterior||' and bdplano is null';
   else
      wEliminaAnterior = wEliminaAnterior||' and bdplano ='||new.bdplano;
 
   if (new.bdcodigoplano is null) then
      wEliminaAnterior = wEliminaAnterior||' and bdcodigoplano is null';
   else
      wEliminaAnterior = wEliminaAnterior||' and bdcodigoplano ='||new.bdcodigoplano;
 
   if (new.bdref is null) then
      wEliminaAnterior = wEliminaAnterior||' and bdref is null';
   else
      wEliminaAnterior = wEliminaAnterior||' and bdref ='||new.bdref;
 
   if (new.bdcodcol is null) then
      wEliminaAnterior = wEliminaAnterior||' and bdcodcol is null';
   else
      wEliminaAnterior = wEliminaAnterior||' and bdcodcol ='||new.bdcodcol;
 
   if (new.bdcodevento is null) then
      wEliminaAnterior = wEliminaAnterior||' and bdcodevento is null';
   else
      wEliminaAnterior = wEliminaAnterior||' and bdcodevento ='||new.bdcodevento;
 
   if (new.bdapuranual is null) then
      wEliminaAnterior = wEliminaAnterior||' and bdapuranual is null';
   else
      wEliminaAnterior = wEliminaAnterior||' and bdapuranual ='||''''||new.bdapuranual||'''';

   execute statement wEliminaAnterior;
END^

/* Restore proc. body: SP_CONSULTA_DADOS_DIARIOS */
create or alter procedure SP_CONSULTA_DADOS_DIARIOS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATACOL date,
    BDCODMAS integer,
    BDSALBASECOL numeric(18,6),
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDCODQH integer,
    BDREGJORTRAB integer,
    BDDESCMAS varchar(50),
    BDDESCTFUC varchar(40),
    BDDESCQH DM_BDDESCQH,
    BDDESCSALVAR varchar(255),
    BDTIPOJORNADA integer,
    BDDESCTPJORNADA varchar(100),
    BDINDHORARIONOT integer,
    BDACUMCARGO integer,
    BDCODTIPOCONTRATO varchar(300),
    BDDATAFIMPRAZO1COL date,
    BDDATAFIMPRAZO2COL date,
    BDDATAFIMPRAZO date,
    BDCODCARGOCOMIS integer,
    BDDESCTFUCCOMIS varchar(40),
    BDTIPOESCALA varchar(20),
    BDCODREVEZAMENTO integer,
    BDDESCRICAO varchar(100),
    BDDATAINICIALESCALA date,
    BDATUAL boolean,
    BDDTAINICIALFOLGA date)
as
declare variable WSQL varchar(30000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
  /* Procedure Text */

  WSQL = 'select COLCON_DIA.BDCODEMP, COLCON_DIA.BDCODCOL, COLCON_DIA.BDDATACOL, COLCON_CALCDIA.BDCODMAS, '||
         '       COLCON_CALCDIA.BDSALBASECOL, COL_VINCDIA.BDCODPLAFUC, COL_VINCDIA.BDCODTFUC, COL_VINCDIA.BDCODQH, '||
         '       COL_VINCDIA.BDREGJORTRAB, MOTAUM.BDDESCMAS, FUNCOES.BDDESCTFUC, HORARIOS.BDDESCQH, '||
         '       COLCON_CALCDIA.BDDESCSALVAR, COL_VINCDIA.BDTIPOJORNADA, COL_VINCDIA.BDDESCTPJORNADA, '||
         '       coalesce(COL_VINCDIA.BDINDHORARIONOT, 0) BDINDHORARIONOT, coalesce(COL_VINCDIA.BDACUMCARGO, 0) BDACUMCARGO, '||
         '       (TPCONT.BDCODTIPOCONTRATO || '' - '' || TPCONT.BDDESCRICAO) BDCODTIPOCONTRATO, BDDATAFIMPRAZO1COL, '||
         '       BDDATAFIMPRAZO2COL, '||
         '       case '||
         '         when BDDATAFIMPRAZO2COL is not null then BDDATAFIMPRAZO2COL '||
         '         else BDDATAFIMPRAZO1COL '||
         '       end BDDATAFIMPRAZO, '||
         '       COL_VINCDIA.BDCODCARGOCOMIS, FUNCOES_COMIS.BDDESCTFUC BDDESCTFUCCOMIS, '||
         '       case '||
         '         when coalesce(COL_VINCDIA.BDTIPOESCALA, 0) = 0 then ''0 - Normal'' '||
         '         when coalesce(COL_VINCDIA.BDTIPOESCALA, 0) = 1 then ''1 - Revezamento'' '||
         '         else ''Nenhuma'' '||
         '       end BDTIPOESCALA, '||
         '       COL_VINCDIA.BDCODREVEZAMENTO, CAD_TIPOREVEZAMENTO.BDDESCRICAO, COL_VINCDIA.BDDATAINICIALESCALA, '||
         '       true as BDATUAL, '||
         '       COL_VINCDIA.BDDTAINICIALFOLGA '||
         'from VRH_EMP_TCOLCON_DIA COLCON_DIA '||
         'inner join(select BDCODEMP, BDCODCOL, BDDATACOL, max(BDDATAEFEITO) BDDATAEFEITO '||
         '           from VRH_EMP_TCOLCON_CALCDIA '||
         '           where BDCODEMP = '||:PRCODEMP||' and '||
         '                 BDCODCOL = '||:PRCODCOL||' '||
         '           group by BDCODEMP, BDCODCOL, BDCODMAS, BDDATACOL) COLCON_CALCDIA_MAX on (COLCON_CALCDIA_MAX.BDCODEMP = COLCON_DIA.BDCODEMP and '||
         '      COLCON_CALCDIA_MAX.BDCODCOL = COLCON_DIA.BDCODCOL and '||
         '      COLCON_CALCDIA_MAX.BDDATACOL = COLCON_DIA.BDDATACOL) '||
         'inner join VRH_EMP_TCOLCON_CALCDIA COLCON_CALCDIA on (COLCON_CALCDIA.BDCODEMP = COLCON_CALCDIA_MAX.BDCODEMP and '||
         '      COLCON_CALCDIA.BDCODCOL = COLCON_CALCDIA_MAX.BDCODCOL and '||
         '      COLCON_CALCDIA.BDDATACOL = COLCON_CALCDIA_MAX.BDDATACOL and '||
         '      COLCON_CALCDIA.BDDATAEFEITO = COLCON_CALCDIA_MAX.BDDATAEFEITO) '||
         'left outer join VRH_EMP_TCOL_VINCDIA COL_VINCDIA on (COL_VINCDIA.BDCODEMP = COLCON_DIA.BDCODEMP and '||
         '      COL_VINCDIA.BDCODCOL = COLCON_DIA.BDCODCOL and '||
         '      COL_VINCDIA.BDDATACOL = COLCON_DIA.BDDATACOL) '||
         'left outer join VRH_CAD_TIPOREVEZAMENTO CAD_TIPOREVEZAMENTO on (COL_VINCDIA.BDCODREVEZAMENTO = CAD_TIPOREVEZAMENTO.BDCODREVEZAMENTO) '||
         'left outer join VRHF_BASE_TEMPVINC EMP_VINC on (EMP_VINC.BDCODEMP = COLCON_DIA.BDCODEMP and '||
         '      EMP_VINC.BDREFEMP = (select max(BDREFEMP) '||
         '                           from TEMPRESAS_REF '||
         '                           where BDCODEMP = EMP_VINC.BDCODEMP and '||
         '                                 BDREFEMP <= substring(COLCON_DIA.BDDATACOL from 1 for 4) || substring(COLCON_DIA.BDDATACOL from 6 for 2))) '||
         'left outer join VRH_BASE_TMOTAUMSAL MOTAUM on (MOTAUM.BDCODMAS = COLCON_CALCDIA.BDCODMAS) '||
         'left outer join VRH_FUNCOES_TFUC FUNCOES on (FUNCOES.BDCODPLAFUC = COL_VINCDIA.BDCODPLAFUC and '||
         '      FUNCOES.BDCODTFUC = COL_VINCDIA.BDCODTFUC) '||
         'left outer join VRH_FUNCOES_TFUC FUNCOES_COMIS on (FUNCOES_COMIS.BDCODPLAFUC = COL_VINCDIA.BDCODPLAFUC and '||
         '      FUNCOES_COMIS.BDCODTFUC = COL_VINCDIA.BDCODCARGOCOMIS) '||
         'left outer join VRH_BASE_TQH HORARIOS on (HORARIOS.BDCODPQUA = coalesce(COL_VINCDIA.BDCODPQUA, EMP_VINC.BDCODPQUA) and '||
         '      HORARIOS.BDCODQH = COL_VINCDIA.BDCODQH) '||
         'left outer join VRH_EMP_TCOLCON_PARTIDA PAR on (PAR.BDCODEMP = COLCON_DIA.BDCODEMP and '||
         '      PAR.BDCODCOL = COLCON_DIA.BDCODCOL) '||
         'left outer join VRH_TIPO_CONTRATO_EXP TPCONT on (TPCONT.BDCODTIPOCONTRATO = PAR.BDCODTIPOCONTRATO) '||
         'left outer join VW_VRH_EMP_TCOL_ADM ADM on (ADM.BDCODEMP = COLCON_DIA.BDCODEMP) and '||
         '      (ADM.BDCODCOL = COLCON_DIA.BDCODCOL) '||
         'where COLCON_DIA.BDCODEMP = '||:PRCODEMP||' and '||
         '      COLCON_DIA.BDCODCOL = '||:PRCODCOL||' '||
         'order by BDDATACOL desc ';

  FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDDATACOL,
    :BDCODMAS,
    :BDSALBASECOL,
    :BDCODPLAFUC,
    :BDCODTFUC,
    :BDCODQH,
    :BDREGJORTRAB,
    :BDDESCMAS,
    :BDDESCTFUC,
    :BDDESCQH,
    :BDDESCSALVAR,
    :BDTIPOJORNADA,
    :BDDESCTPJORNADA,
    :BDINDHORARIONOT,
    :BDACUMCARGO,
    :BDCODTIPOCONTRATO,
    :BDDATAFIMPRAZO1COL,
    :BDDATAFIMPRAZO2COL,
    :BDDATAFIMPRAZO,
    :BDCODCARGOCOMIS,
    :BDDESCTFUCCOMIS,
    :BDTIPOESCALA,
    :BDCODREVEZAMENTO,
    :BDDESCRICAO,
    :BDDATAINICIALESCALA,
    :BDATUAL,
    :BDDTAINICIALFOLGA
  DO
  SUSPEND;

  if (COALESCE(PRMOSTRATRANSF, 0) = 1) then
     begin
       WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = '||PRCODEMP||' and BDCODCOLDEST = '||PRCODCOL;
       FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
          BEGIN
            IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
               BEGIN
                 WSQL3 = 'SELECT * FROM SP_CONSULTA_DADOS_DIARIOS('||wcodemporig||', '||wcodcolorig||', '||prmostratransf||')';
                 FOR EXECUTE STATEMENT wsql3 INTO
                 :BDCODEMP,
                 :BDCODCOL,
                 :BDDATACOL,
                 :BDCODMAS,
                 :BDSALBASECOL,
                 :BDCODPLAFUC,
                 :BDCODTFUC,
                 :BDCODQH,
                 :BDREGJORTRAB,
                 :BDDESCMAS,
                 :BDDESCTFUC,
                 :BDDESCQH,
                 :BDDESCSALVAR,
                 :BDTIPOJORNADA,
                 :BDDESCTPJORNADA,
                 :BDINDHORARIONOT,
                 :BDACUMCARGO,
                 :BDCODTIPOCONTRATO,
                 :BDDATAFIMPRAZO1COL,
                 :BDDATAFIMPRAZO2COL,
                 :BDDATAFIMPRAZO,
                 :BDCODCARGOCOMIS,
                 :BDDESCTFUCCOMIS,
                 :BDTIPOESCALA,
                 :BDCODREVEZAMENTO,
                 :BDDESCRICAO,
                 :BDDATAINICIALESCALA,
                 :BDATUAL,
                 :BDDTAINICIALFOLGA
                 do
                    BEGIN
                      BDATUAL = FALSE;
                      SUSPEND;
                    END
               END
          END
     end
end^


create or alter procedure SP_DADOS_MENSAIS_ESTRANGEIRO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDDATACHEBRASILCOL date,
    BDDESCCLE varchar(300),
    BDCASADOBR DM_BOOLEAN,
    BDFILHOSBR DM_BOOLEAN,
    BDTEMPORESIDENCIA integer,
    BDCONDICAOINGRESSO integer,
    BDNUMRNECOL varchar(14),
    BDORGAORNECOL DM_ORGAOEMISSOR,
    BDDATAEMIRNECOL date,
    BDATUAL boolean)
as
declare variable WSQL varchar(10000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
declare variable WWHERE varchar(500);
begin
    /* Procedure Text */
  WWHERE = '';
  if (COALESCE(PRCODEMP, 0) > 0) then
     begin
       WWHERE = 'where COL.BDCODEMP = '||PRCODEMP;

       if (COALESCE(PRCODCOL, 0) > 0) then
          WWHERE = WWHERE||' and COL.BDCODCOL = '||PRCODCOL;
     end

  WSQL = 'select COL.BDCODEMP, COL.BDCODCOL, COL.BDREFCOL, COL.BDDATACHEBRASILCOL, '||
         '       cast(COL.BDCODCLE as varchar(2)) || '' - '' || CLE.BDDESCCLE BDDESCCLE, COL.BDCASADOBR, COL.BDFILHOSBR, '||
         '       COL.BDTEMPORESIDENCIA, COL.BDCONDICAOINGRESSO, DOC.BDNUMRNECOL, DOC.BDORGAORNECOL, DOC.BDDATAEMIRNECOL, '||
         '       true as BDATUAL '||
         'from VRH_EMP_TCOLCON_CAD COL '||
         'left outer join VRH_EMP_TCOLCON_DOCREF DOC on DOC.BDCODEMP = COL.BDCODEMP and '||
         '      DOC.BDCODCOL = COL.BDCODCOL and '||
         '      DOC.BDREFCOL = COL.BDREFCOL '||
         'left outer join VRH_BASE_TCLASSE_ESTRANGEIRO CLE on CLE.BDCODCLE = COL.BDCODCLE '||
         WWHERE||
         ' order by COL.BDREFCOL DESC ';

  FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFCOL,
    :BDDATACHEBRASILCOL,
    :BDDESCCLE,
    :BDCASADOBR,
    :BDFILHOSBR,
    :BDTEMPORESIDENCIA,
    :BDCONDICAOINGRESSO,
    :BDNUMRNECOL,
    :BDORGAORNECOL,
    :BDDATAEMIRNECOL,
    :BDATUAL
  DO
  SUSPEND;

  if (COALESCE(PRMOSTRATRANSF, 0) = 1) then
     begin
       WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = '||PRCODEMP||' and BDCODCOLDEST = '||PRCODCOL;
       FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
          BEGIN
            IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
               BEGIN
                 WSQL3 = 'SELECT * FROM SP_DADOS_MENSAIS_ESTRANGEIRO('||wcodemporig||', '||wcodcolorig||', '||PRMOSTRATRANSF||')';
                 FOR EXECUTE STATEMENT wsql3 INTO
                 :BDCODEMP,
                 :BDCODCOL,
                 :BDREFCOL,
                 :BDDATACHEBRASILCOL,
                 :BDDESCCLE,
                 :BDCASADOBR,
                 :BDFILHOSBR,
                 :BDTEMPORESIDENCIA,
                 :BDCONDICAOINGRESSO,
                 :BDNUMRNECOL,
                 :BDORGAORNECOL,
                 :BDDATAEMIRNECOL,
                 :BDATUAL do
                    BEGIN
                      BDATUAL = FALSE;
                      SUSPEND;
                    END
               END
          END
     end
end^

create or alter procedure SP_DADOS_MENSAIS_CADASTRAIS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCODPAISRES integer,
    BDDESCPAIS varchar(60),
    BDCEPCOL varchar(9),
    BDLOGRCOL DM_LOGRADOURO,
    BDENDCOL DM_BDENDERECO,
    BDNUMCOL DM_NUMEND,
    BDCOMPLCOL DM_BDCOMPENDERECO,
    BDBAICOL DM_BDBAIRRO,
    BDCODCID integer,
    BDNOMCID varchar(40),
    BDDDDCOL integer,
    BDFONECOL varchar(15),
    BDDDDCELCOL integer,
    BDCELCOL DM_BDTELEFONE,
    BDEMAILCOL DM_BDEMAIL,
    BDGERARNMSOCIAL varchar(5),
    BDNMSOCIAL varchar(70),
    BDATUAL boolean)
as
declare variable WSQL varchar(10000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
declare variable WWHERE varchar(500);
begin
    /* Procedure Text */
  WWHERE = '';
  if (COALESCE(PRCODEMP, 0) > 0) then
     begin
       WWHERE = 'where COL.BDCODEMP = '||PRCODEMP;

       if (COALESCE(PRCODCOL, 0) > 0) then
          WWHERE = WWHERE||' and COL.BDCODCOL = '||PRCODCOL;
     end

  WSQL = 'select COL.BDCODEMP, COL.BDCODCOL, COL.BDREFCOL, COL.BDNOMCOL, COL.BDCODPAISRES, PRES.BDDESCPAIS, COL.BDCEPCOL, '||
         '       COL.BDLOGRCOL, COL.BDENDCOL, COL.BDNUMCOL, COL.BDCOMPLCOL, COL.BDBAICOL, COL.BDCODCID, CID.BDNOMCID, '||
         '       COL.BDDDDCOL, COL.BDFONECOL, COL.BDDDDCELCOL, COL.BDCELCOL, COL.BDEMAILCOL, '||
         '       case '||
         '         when FIS.BDGERARNMSOCIAL = ''TRUE'' then ''Sim'' '||
         '         else ''Não'' '||
         '       end as BDGERARNMSOCIAL, '||
         '       FIS.BDNMSOCIAL, true as BDATUAL '||
         'from VRH_EMP_TCOLCON_CAD COL '||
         'left outer join VRH_EMP_TCOLCON_FIS FIS on FIS.BDCODEMP = COL.BDCODEMP and '||
         '      FIS.BDCODCOL = COL.BDCODCOL and '||
         '      FIS.BDREFCOL = COL.BDREFCOL '||
         'left outer join TPAIS PRES on PRES.BDCODPAIS = COL.BDCODPAISRES '||
         'left outer join TCIDADE CID on CID.BDCODCID = COL.BDCODCID '||
         WWHERE||
         ' order by COL.BDREFCOL DESC ';

  FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFCOL,
    :BDNOMCOL,
    :BDCODPAISRES,
    :BDDESCPAIS,
    :BDCEPCOL,
    :BDLOGRCOL,
    :BDENDCOL,
    :BDNUMCOL,
    :BDCOMPLCOL,
    :BDBAICOL,
    :BDCODCID,
    :BDNOMCID,
    :BDDDDCOL,
    :BDFONECOL,
    :BDDDDCELCOL,
    :BDCELCOL,
    :BDEMAILCOL,
    :BDGERARNMSOCIAL,
    :BDNMSOCIAL,
    :BDATUAL
  DO
  SUSPEND;

  if (COALESCE(PRMOSTRATRANSF, 0) = 1) then
     begin
       WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = '||PRCODEMP||' and BDCODCOLDEST = '||PRCODCOL;
       FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
          BEGIN
            IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
               BEGIN
                 WSQL3 = 'SELECT * FROM SP_DADOS_MENSAIS_CADASTRAIS('||wcodemporig||', '||wcodcolorig||', '||PRMOSTRATRANSF||')';
                 FOR EXECUTE STATEMENT wsql3 INTO
                 :BDCODEMP,
                 :BDCODCOL,
                 :BDREFCOL,
                 :BDNOMCOL,
                 :BDCODPAISRES,
                 :BDDESCPAIS,
                 :BDCEPCOL,
                 :BDLOGRCOL,
                 :BDENDCOL,
                 :BDNUMCOL,
                 :BDCOMPLCOL,
                 :BDBAICOL,
                 :BDCODCID,
                 :BDNOMCID,
                 :BDDDDCOL,
                 :BDFONECOL,
                 :BDDDDCELCOL,
                 :BDCELCOL,
                 :BDEMAILCOL,
                 :BDGERARNMSOCIAL,
                 :BDNMSOCIAL,
                 :BDATUAL do
                    BEGIN
                      BDATUAL = FALSE;
                      SUSPEND;
                    END
               END
          END
     end
end^

create or alter procedure SP_DADOS_MENSAIS_ADM_HIST (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDGRAUINSTCOL integer,
    BDATUAL boolean)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
declare variable WWHERE varchar(500);
begin
    /* Procedure Text */
  WWHERE = '';
  if (COALESCE(PRCODEMP, 0) > 0) then
     begin
       WWHERE = 'where COL.BDCODEMP = '||PRCODEMP;

       if (COALESCE(PRCODCOL, 0) > 0) then
          WWHERE = WWHERE||' and COL.BDCODCOL = '||PRCODCOL;
     end

  WSQL = 'select COL.BDCODEMP, COL.BDCODCOL, COL.BDREFCOL, COL.BDGRAUINSTCOL, true as BDATUAL '||
         'from VRH_EMP_TCOLCON_CAD COL '||
         WWHERE||
         ' order by COL.BDREFCOL desc';

  FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFCOL,
    :BDGRAUINSTCOL,
    :BDATUAL
  DO
  SUSPEND;

  if (COALESCE(PRMOSTRATRANSF, 0) = 1) then
     begin
       WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = '||PRCODEMP||' and BDCODCOLDEST = '||PRCODCOL;
       FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
          BEGIN
            IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
               BEGIN
                 WSQL3 = 'SELECT * FROM SP_DADOS_MENSAIS_ADM_HIST('||wcodemporig||', '||wcodcolorig||', '||PRMOSTRATRANSF||')';
                 FOR EXECUTE STATEMENT wsql3 INTO
                 :BDCODEMP,
                 :BDCODCOL,
                 :BDREFCOL,
                 :BDGRAUINSTCOL,
                 :BDATUAL do
                    BEGIN
                      BDATUAL = FALSE;
                      SUSPEND;
                    END
               END
          END
     end
end^

create or alter procedure SP_DADOS_MENSAIS_DOC_PRINCIPAL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDPISCOL varchar(14),
    BDDATAEMIPISCOL date,
    BDRGCOL varchar(13),
    BDORGEMIRGCOL DM_ORGAOEMISSOR,
    BDDATAEMIRGCOL date,
    BDUFRG varchar(2),
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDSERIECTPSCOL varchar(1),
    BDDATAEMICTPSCOL date,
    BDUFCTPS varchar(2),
    BDCNHCOL varchar(11),
    BDVENCCNHCOL date,
    BDCATCNHCOL varchar(2),
    BDDATAEMICNH date,
    BDUFCNH varchar(2),
    BDATUAL boolean)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
    /* Procedure Text */
  WWHERE = '';
  if (COALESCE(PRCODEMP, 0) > 0) then
     begin
       WWHERE = 'where DOC.BDCODEMP = '||PRCODEMP;

       if (COALESCE(PRCODCOL, 0) > 0) then
          WWHERE = WWHERE||' and DOC.BDCODCOL = '||PRCODCOL;
     end

  WSQL = 'select DOC.BDCODEMP, DOC.BDCODCOL, DOC.BDREFCOL, DOC.BDPISCOL, DOC.BDDATAEMIPISCOL, DOC.BDRGCOL, DOC.BDORGEMIRGCOL, '||
         '       DOC.BDDATAEMIRGCOL, UFRG.BDSIGLAUF BDUFRG, DOC.BDCTPSCOL, DOC.BDSERIECTPSCOL, DOC.BDDSERIECTPSCOL, '||
         '       DOC.BDDATAEMICTPSCOL, UFCTPS.BDSIGLAUF BDUFCTPS, DOC.BDCNHCOL, DOC.BDVENCCNHCOL, DOC.BDCATCNHCOL, '||
         '       DOC.BDDATAEMICNH, UFCNH.BDSIGLAUF BDUFCNH, true as BDATUAL '||
         'from VRH_EMP_TCOLCON_DOCREF DOC '||
         'left outer join TUF UFRG on UFRG.BDCODUF = DOC.BDCODUFRG '||
         'left outer join TUF UFCTPS on UFCTPS.BDCODUF = DOC.BDCODUF '||
         'left outer join TUF UFCNH on UFCNH.BDCODUF = DOC.BDUFCNH '||
         WWHERE||
         ' order by DOC.BDREFCOL desc';

  FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFCOL,
    :BDPISCOL,
    :BDDATAEMIPISCOL,
    :BDRGCOL,
    :BDORGEMIRGCOL,
    :BDDATAEMIRGCOL,
    :BDUFRG,
    :BDCTPSCOL,
    :BDSERIECTPSCOL,
    :BDDSERIECTPSCOL,
    :BDDATAEMICTPSCOL,
    :BDUFCTPS,
    :BDCNHCOL,
    :BDVENCCNHCOL,
    :BDCATCNHCOL,
    :BDDATAEMICNH,
    :BDUFCNH,
    :BDATUAL
  DO
  SUSPEND;

  if (COALESCE(PRMOSTRATRANSF, 0) = 1) then
     begin
       WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = '||PRCODEMP||' and BDCODCOLDEST = '||PRCODCOL;
       FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
          BEGIN
            IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
               BEGIN
                 WSQL3 = 'SELECT * FROM SP_DADOS_MENSAIS_DOC_PRINCIPAL('||wcodemporig||', '||wcodcolorig||', '||PRMOSTRATRANSF||')';
                 FOR EXECUTE STATEMENT wsql3 INTO
                 :BDCODEMP,
                 :BDCODCOL,
                 :BDREFCOL,
                 :BDPISCOL,
                 :BDDATAEMIPISCOL,
                 :BDRGCOL,
                 :BDORGEMIRGCOL,
                 :BDDATAEMIRGCOL,
                 :BDUFRG,
                 :BDCTPSCOL,
                 :BDSERIECTPSCOL,
                 :BDDSERIECTPSCOL,
                 :BDDATAEMICTPSCOL,
                 :BDUFCTPS,
                 :BDCNHCOL,
                 :BDVENCCNHCOL,
                 :BDCATCNHCOL,
                 :BDDATAEMICNH,
                 :BDUFCNH,
                 :BDATUAL do
                    BEGIN
                      BDATUAL = FALSE;
                      SUSPEND;
                    END
               END
          END
     end
end^

create or alter procedure SP_DADOS_MENSAIS_DOC_AUXILIAR (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDNUMRICCOL varchar(14),
    BDORGAORICCOL DM_ORGAOEMISSOR,
    BDDATAEMIRICCOL date,
    BDCODCIDRIC integer,
    BDNOMCID varchar(40),
    BDNUMOCCOL varchar(14),
    BDORGAOOCCOL DM_ORGAOEMISSOR,
    BDDATAEMIOCCOL date,
    BDDATAVALOCCOL date,
    BDATUAL boolean)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
    /* Procedure Text */
  WWHERE = '';
  if (COALESCE(PRCODEMP, 0) > 0) then
     begin
       WWHERE = 'where DOC.BDCODEMP = '||PRCODEMP;

       if (COALESCE(PRCODCOL, 0) > 0) then
          WWHERE = WWHERE||' and DOC.BDCODCOL = '||PRCODCOL;
     end

  WSQL = 'select DOC.BDCODEMP, DOC.BDCODCOL, DOC.BDREFCOL, DOC.BDNUMRICCOL, DOC.BDORGAORICCOL, DOC.BDDATAEMIRICCOL, '||
         '       DOC.BDCODCIDRIC, CRIC.BDNOMCID, DOC.BDNUMOCCOL, DOC.BDORGAOOCCOL, DOC.BDDATAEMIOCCOL, DOC.BDDATAVALOCCOL, '||
         '       true as BDATUAL '||
         'from VRH_EMP_TCOLCON_DOCREF DOC '||
         'left outer join TCIDADE CRIC on CRIC.BDCODCID = DOC.BDCODCIDRIC '||
         WWHERE||
         ' order by DOC.BDREFCOL desc';

  FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFCOL,
    :BDNUMRICCOL,
    :BDORGAORICCOL,
    :BDDATAEMIRICCOL,
    :BDCODCIDRIC,
    :BDNOMCID,
    :BDNUMOCCOL,
    :BDORGAOOCCOL,
    :BDDATAEMIOCCOL,
    :BDDATAVALOCCOL,
    :BDATUAL
  DO
  SUSPEND;

  if (COALESCE(PRMOSTRATRANSF, 0) = 1) then
     begin
       WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = '||PRCODEMP||' and BDCODCOLDEST = '||PRCODCOL;
       FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
          BEGIN
            IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
               BEGIN
                 WSQL3 = 'SELECT * FROM SP_DADOS_MENSAIS_DOC_AUXILIAR('||wcodemporig||', '||wcodcolorig||', '||PRMOSTRATRANSF||')';
                 FOR EXECUTE STATEMENT wsql3 INTO
                 :BDCODEMP,
                 :BDCODCOL,
                 :BDREFCOL,
                 :BDNUMRICCOL,
                 :BDORGAORICCOL,
                 :BDDATAEMIRICCOL,
                 :BDCODCIDRIC,
                 :BDNOMCID,
                 :BDNUMOCCOL,
                 :BDORGAOOCCOL,
                 :BDDATAEMIOCCOL,
                 :BDDATAVALOCCOL,
                 :BDATUAL do
                    BEGIN
                      BDATUAL = FALSE;
                      SUSPEND;
                    END
               END
          END
     end
end^

create or alter procedure SP_DADOS_MENSAIS_FISICOS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDSEXOCOL integer,
    BDCORCOL integer,
    BDDEFCOL DM_BOOLEAN,
    BDDEFFIS DM_BOOLEAN,
    BDDEFVIS DM_BOOLEAN,
    BDDEFAUD DM_BOOLEAN,
    BDDEFMEN DM_BOOLEAN,
    BDDEFINT DM_BOOLEAN,
    BDREAB DM_BOOLEAN,
    BDCOTADEF integer,
    BDOBSDEFFISCOL varchar(300),
    BDATUAL boolean)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
    /* Procedure Text */
  WWHERE = '';
  if (COALESCE(PRCODEMP, 0) > 0) then
     begin
       WWHERE = 'where FIS.BDCODEMP = '||PRCODEMP;

       if (COALESCE(PRCODCOL, 0) > 0) then
          WWHERE = WWHERE||' and FIS.BDCODCOL = '||PRCODCOL;
     end

  WSQL = 'select FIS.BDCODEMP, FIS.BDCODCOL, FIS.BDREFCOL, COLCAD.BDSEXOCOL, FIS.BDCORCOL, FIS.BDDEFCOL, FIS.BDDEFFIS, '||
         '       FIS.BDDEFVIS, FIS.BDDEFAUD, FIS.BDDEFMEN, FIS.BDDEFINT, FIS.BDREAB, FIS.BDCOTADEF, FIS.BDOBSDEFFISCOL, '||
         '       true as BDATUAL '||
         'from VRH_EMP_TCOLCON_FIS FIS '||
         'left outer join VRH_EMP_TCOLCON_CAD COLCAD on COLCAD.BDCODEMP = FIS.BDCODEMP and '||
         '      COLCAD.BDCODCOL = FIS.BDCODCOL and '||
         '      COLCAD.BDREFCOL = FIS.BDREFCOL '||
         WWHERE||
         ' order by FIS.BDREFCOL desc';

  FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFCOL,
    :BDSEXOCOL,
    :BDCORCOL,
    :BDDEFCOL,
    :BDDEFFIS,
    :BDDEFVIS,
    :BDDEFAUD,
    :BDDEFMEN,
    :BDDEFINT,
    :BDREAB,
    :BDCOTADEF,
    :BDOBSDEFFISCOL,
    :BDATUAL
  DO
  SUSPEND;

  if (COALESCE(PRMOSTRATRANSF, 0) = 1) then
     begin
       WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = '||PRCODEMP||' and BDCODCOLDEST = '||PRCODCOL;
       FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
          BEGIN
            IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
               BEGIN
                 WSQL3 = 'SELECT * FROM SP_DADOS_MENSAIS_FISICOS('||wcodemporig||', '||wcodcolorig||', '||PRMOSTRATRANSF||')';
                 FOR EXECUTE STATEMENT wsql3 INTO
                 :BDCODEMP,
                 :BDCODCOL,
                 :BDREFCOL,
                 :BDSEXOCOL,
                 :BDCORCOL,
                 :BDDEFCOL,
                 :BDDEFFIS,
                 :BDDEFVIS,
                 :BDDEFAUD,
                 :BDDEFMEN,
                 :BDDEFINT,
                 :BDREAB,
                 :BDCOTADEF,
                 :BDOBSDEFFISCOL,
                 :BDATUAL do
                    BEGIN
                      BDATUAL = FALSE;
                      SUSPEND;
                    END
               END
          END
     end
end^

create or alter procedure SP_DADOS_MENSAIS_PARENTES (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDESTCIVCOL integer,
    BDATUAL boolean)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
    /* Procedure Text */
  WWHERE = '';
  if (COALESCE(PRCODEMP, 0) > 0) then
     begin
       WWHERE = 'where COL.BDCODEMP = '||PRCODEMP;

       if (COALESCE(PRCODCOL, 0) > 0) then
          WWHERE = WWHERE||' and COL.BDCODCOL = '||PRCODCOL;
     end

  WSQL = 'select COL.BDCODEMP, COL.BDCODCOL, COL.BDREFCOL, COL.BDESTCIVCOL, true as BDATUAL '||
         'from VRH_EMP_TCOLCON_CAD COL '||
         WWHERE||
         ' order by COL.BDREFCOL desc';

  FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFCOL,
    :BDESTCIVCOL,
    :BDATUAL
  DO
  SUSPEND;

  if (COALESCE(PRMOSTRATRANSF, 0) = 1) then
     begin
       WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = '||PRCODEMP||' and BDCODCOLDEST = '||PRCODCOL;
       FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
          BEGIN
            IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
               BEGIN
                 WSQL3 = 'SELECT * FROM SP_DADOS_MENSAIS_PARENTES('||wcodemporig||', '||wcodcolorig||', '||PRMOSTRATRANSF||')';
                 FOR EXECUTE STATEMENT wsql3 INTO
                 :BDCODEMP,
                 :BDCODCOL,
                 :BDREFCOL,
                 :BDESTCIVCOL,
                 :BDATUAL do
                    BEGIN
                      BDATUAL = FALSE;
                      SUSPEND;
                    END
               END
          END
     end
end^

/* Restore proc. body: SP_DADOS_MENSAIS_VINCULOS */
create or alter procedure SP_DADOS_MENSAIS_VINCULOS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDCODCLA integer,
    BDDESCCLA varchar(40),
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDNOMSETOR varchar(100),
    BDCODSINTRAB integer,
    BDDESCSINTRAB varchar(60),
    BDCODSINTRABCLA integer,
    BDDESCSINTRABCLA varchar(60),
    BDATUAL boolean)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
declare variable WCODCONTROLE integer;
begin
  delete from TMP_CONTROLE_PERAQUISFE where BDSPINSERIU = 9;

  WWHERE = '';
  if (COALESCE(PRCODEMP, 0) > 0) then
     begin
       WWHERE = 'where COL.BDCODEMP = '||PRCODEMP;

       if (COALESCE(PRCODCOL, 0) > 0) then
          WWHERE = WWHERE||' and COL.BDCODCOL = '||PRCODCOL;
     end


  WSQL = 'select COL.BDCODEMP, COL.BDCODCOL, COL.BDREFCOL from VRH_EMP_TCOLCON_REF COL '||WWHERE ||
         'order by COL.BDCODEMP desc, COL.BDCODCOL desc, COL.BDREFCOL desc ';

  for execute statement wsql
  into :BDCODEMP, :BDCODCOL, :BDREFCOL
  do
    begin
      select first 1 VINC.BDCODCLA, VINC.BDCODCENTRO, VINC.BDCODTPCC,
          CLA.BDDESCCLA,
          case
            when trim(coalesce(TOM.BDNOMETOM, '')) = '' then CEN.BDNOMCTA
            else TOM.BDNOMETOM
          end as BDNOMSETOR
      from VRH_EMP_TCOLCON_VINC VINC
      left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
      left outer join CENTROS_TPCC CEN on (CEN.BDCODCENTRO = VINC.BDCODCENTRO and CEN.BDCODTPCC = VINC.BDCODTPCC)
      left outer join VRH_BASE_TCUSTOM TOM on (TOM.BDCODCENTRO = VINC.BDCODCENTRO and TOM.BDCODTPCC = VINC.BDCODTPCC)
      where VINC.BDCODEMP = :BDCODEMP and VINC.BDCODCOL = :BDCODCOL and VINC.BDREFCOL <= :BDREFCOL
      order by VINC.BDCODEMP desc, VINC.BDCODCOL desc, VINC.BDREFCOL desc
      into :BDCODCLA, :BDCODCENTRO, :BDCODTPCC,
           :BDDESCCLA,
           :BDNOMSETOR;

      select first 1 VINCCOL.BDCODSINTRAB, VINCCOL.BDCODSINTRABCLA,
           SIND.BDDESCSINTRAB,
           SINDCLA.BDDESCSINTRAB
      from VRH_EMP_TCOL_VINC VINCCOL
      left outer join VRH_BASE_TSINDTRAB SIND on (SIND.BDCODSINTRAB = VINCCOL.BDCODSINTRAB)
      left outer join VRH_BASE_TSINDTRAB SINDCLA on (SINDCLA.BDCODSINTRAB = VINCCOL.BDCODSINTRABCLA)
      where VINCCOL.BDCODEMP = :BDCODEMP and VINCCOL.BDCODCOL = :BDCODCOL and VINCCOL.BDREFCOL <= :BDREFCOL
      order by VINCCOL.BDCODEMP desc, VINCCOL.BDCODCOL desc, VINCCOL.BDREFCOL desc
      into :BDCODSINTRAB, :BDCODSINTRABCLA,
           :BDDESCSINTRAB,
           :BDDESCSINTRABCLA;

      BDATUAL = TRUE;
      suspend;
    end

  if (COALESCE(PRMOSTRATRANSF, 0) = 1) then
     begin
       WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = '||PRCODEMP||' and BDCODCOLDEST = '||PRCODCOL;
       FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
          BEGIN
            IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
               BEGIN
                 wcodcontrole = null;
                 select bdcodemp from TMP_CONTROLE_PERAQUISFE where BDSPINSERIU = 3 AND bdcodemp = :wcodemporig and bdcodcol = :wcodcolorig and bdsessao = current_connection into :wcodcontrole;
                 if (wcodcontrole IS NULL) then
                    begin
                      insert into TMP_CONTROLE_PERAQUISFE (BDCODEMP,BDCODCOL,BDSESSAO,BDSPINSERIU) values (:wcodemporig,:wcodcolorig,current_connection,9);

                      WSQL3 = 'SELECT * FROM SP_DADOS_MENSAIS_VINCULOS('||wcodemporig||', '||wcodcolorig||', '||PRMOSTRATRANSF||')';
                      FOR EXECUTE STATEMENT wsql3 INTO
                      :BDCODEMP,
                      :BDCODCOL,
                      :BDREFCOL,
                      :BDCODCLA,
                      :BDDESCCLA,
                      :BDCODTPCC,
                      :BDNOMSETOR,
                      :BDCODSINTRAB,
                      :BDDESCSINTRAB,
                      :BDCODSINTRABCLA,
                      :BDDESCSINTRABCLA,
                      :BDATUAL do
                        BEGIN
                          BDATUAL = FALSE;
                          SUSPEND;
                        END
                    end
               END
          END
     end


  delete from TMP_CONTROLE_PERAQUISFE where BDSPINSERIU = 9;
end^

create or alter procedure SP_DADOS_MENSAIS_FGTS_GPS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDCATEGORIACOL integer,
    BDDESCCATEGORIA varchar(300),
    BDOCORRENCIACOL integer,
    BDDATAOPCAOFGTSCOL date,
    BDCTAFGTSCOL varchar(11),
    BDPERCFGTSCOL numeric(15,6),
    BDPERCRATCOL numeric(15,6),
    BDPERCDESCFPASCOL numeric(15,6),
    BDCATEGORIAESOCIAL integer,
    BDDESCCATESOCIAL varchar(300),
    BDREGPREV integer,
    BDCODMULTVINC integer,
    BDDESCMULTVINC varchar(300),
    BDDESCOCORRENCIA varchar(80),
    BDATUAL boolean,
    BDREGIMETRAB integer)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(3000);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
    /* Procedure Text */
  WWHERE = '';
  if (COALESCE(PRCODEMP, 0) > 0) then
     begin
       WWHERE = 'where FGTS.BDCODEMP = '||PRCODEMP;

       if (COALESCE(PRCODCOL, 0) > 0) then
          WWHERE = WWHERE||' and FGTS.BDCODCOL = '||PRCODCOL;
     end

  WSQL = 'select FGTS.BDCODEMP, FGTS.BDCODCOL, FGTS.BDREFCOL, FGTS.BDCATEGORIACOL, CAT.BDDESCCATEGORIA, FGTS.BDOCORRENCIACOL, '||
         '       FGTS.BDDATAOPCAOFGTSCOL, FGTS.BDCTAFGTSCOL, FGTS.BDPERCFGTSCOL, FGTS.BDPERCRATCOL, FGTS.BDPERCDESCFPASCOL, '||
         '       FGTS.BDCATEGORIAESOCIAL, CATESOCIAL.BDDESCRICAO BDDESCCATESOCIAL, FGTS.BDREGPREV, FGTS.BDCODMULTVINC, '||
         '       MVINC.BDDESCMULTVINC, FGTSOCOR.BDDESCRICAO BDDESCOCORRENCIA, true as BDATUAL, FGTS.BDREGIMETRAB '||
         'from VRHF_EMP_TCOLCON_FGTSGPS FGTS '||
         'left outer join VRH_BASE_TCATEGORIA CAT on (CAT.BDCODCATEGORIA = FGTS.BDCATEGORIACOL) '||
         'left outer join VRH_ESOCIAL_TCATEGORIA CATESOCIAL on (CATESOCIAL.BDCODIGO = FGTS.BDCATEGORIAESOCIAL) '||
         'left outer join VRH_ESOCIAL_TINDMULTVINC MVINC on (MVINC.BDCODMULTVINC = FGTS.BDCODMULTVINC) '||
         'left outer join VRH_BASE_TOCORRENCIAFGTS FGTSOCOR on (FGTSOCOR.BDCODIGO = FGTS.BDOCORRENCIACOL) '||
         WWHERE||
         ' order by FGTS.BDREFCOL desc';

  FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFCOL,
    :BDCATEGORIACOL,
    :BDDESCCATEGORIA,
    :BDOCORRENCIACOL,
    :BDDATAOPCAOFGTSCOL,
    :BDCTAFGTSCOL,
    :BDPERCFGTSCOL,
    :BDPERCRATCOL,
    :BDPERCDESCFPASCOL,
    :BDCATEGORIAESOCIAL,
    :BDDESCCATESOCIAL,
    :BDREGPREV,
    :BDCODMULTVINC,
    :BDDESCMULTVINC,
    :BDDESCOCORRENCIA,
    :BDATUAL,
    :BDREGIMETRAB
  DO
  SUSPEND;

  if (COALESCE(PRMOSTRATRANSF, 0) = 1) then
     begin
       WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = '||PRCODEMP||' and BDCODCOLDEST = '||PRCODCOL;
       FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
          BEGIN
            IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
               BEGIN
                 WSQL3 = 'SELECT BDCODEMP, BDCODCOL, BDREFCOL, BDCATEGORIACOL, BDDESCCATEGORIA, BDOCORRENCIACOL, BDDATAOPCAOFGTSCOL, BDCTAFGTSCOL, BDPERCFGTSCOL, '||
                           'BDPERCRATCOL, BDPERCDESCFPASCOL, BDCATEGORIAESOCIAL, BDDESCCATESOCIAL, BDREGPREV, BDCODMULTVINC, BDDESCMULTVINC, BDDESCOCORRENCIA, '||
                            'BDATUAL, BDREGIMETRAB '||
                         'FROM SP_DADOS_MENSAIS_FGTS_GPS('||wcodemporig||', '||wcodcolorig||', '||PRMOSTRATRANSF||')';
                 FOR EXECUTE STATEMENT wsql3 INTO
                 :BDCODEMP,
                 :BDCODCOL,
                 :BDREFCOL,
                 :BDCATEGORIACOL,
                 :BDDESCCATEGORIA,
                 :BDOCORRENCIACOL,
                 :BDDATAOPCAOFGTSCOL,
                 :BDCTAFGTSCOL,
                 :BDPERCFGTSCOL,
                 :BDPERCRATCOL,
                 :BDPERCDESCFPASCOL,
                 :BDCATEGORIAESOCIAL,
                 :BDDESCCATESOCIAL,
                 :BDREGPREV,
                 :BDCODMULTVINC,
                 :BDDESCMULTVINC,
                 :BDDESCOCORRENCIA,
                 :BDATUAL,
                 :BDREGIMETRAB
                 do
                    BEGIN
                      BDATUAL = FALSE;
                      SUSPEND;
                    END
               END
          END
     end
end^

create or alter procedure SP_DADOS_MENSAIS_DIRIGENTE (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDPLANOSEGREGACAO integer,
    BDTETORGPS integer,
    BDABONOPERMANENCIA integer,
    BDINICIOABONO date,
    BDATUAL boolean)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
    /* Procedure Text */
  WWHERE = '';
  if (COALESCE(PRCODEMP, 0) > 0) then
     begin
       WWHERE = 'where FGTS.BDCODEMP = '||PRCODEMP;

       if (COALESCE(PRCODCOL, 0) > 0) then
          WWHERE = WWHERE||' and FGTS.BDCODCOL = '||PRCODCOL;
     end

  WSQL = 'select FGTS.BDCODEMP, FGTS.BDCODCOL, FGTS.BDREFCOL, FGTS.BDPLANOSEGREGACAO, FGTS.BDTETORGPS, '||
         '       FGTS.BDABONOPERMANENCIA, FGTS.BDINICIOABONO, true as BDATUAL '||
         'from VRHF_EMP_TCOLCON_FGTSGPS FGTS '||
         WWHERE||
         ' order by FGTS.BDREFCOL desc';

  FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFCOL,
    :BDPLANOSEGREGACAO,
    :BDTETORGPS,
    :BDABONOPERMANENCIA,
    :BDINICIOABONO,
    :BDATUAL
  DO
  SUSPEND;

  if (COALESCE(PRMOSTRATRANSF, 0) = 1) then
     begin
       WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = '||PRCODEMP||' and BDCODCOLDEST = '||PRCODCOL;
       FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
          BEGIN
            IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
               BEGIN
                 WSQL3 = 'SELECT * FROM SP_DADOS_MENSAIS_DIRIGENTE('||wcodemporig||', '||wcodcolorig||', '||PRMOSTRATRANSF||')';
                 FOR EXECUTE STATEMENT wsql3 INTO
                 :BDCODEMP,
                 :BDCODCOL,
                 :BDREFCOL,
                 :BDPLANOSEGREGACAO,
                 :BDTETORGPS,
                 :BDABONOPERMANENCIA,
                 :BDINICIOABONO,
                 :BDATUAL do
                    BEGIN
                      BDATUAL = FALSE;
                      SUSPEND;
                    END
               END
          END
     end
end^

create or alter procedure SP_DADOS_MENSAIS_ADMISSIONAIS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDVINCEMPCOL integer,
    BDSINDICALIZADOCOL varchar(5),
    BDALVARACOL DM_BOOLEAN,
    BDCODPROCESSO integer,
    BDNROPROCESSO varchar(21),
    BDATUAL boolean)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
    /* Procedure Text */
  WWHERE = '';
  if (COALESCE(PRCODEMP, 0) > 0) then
     begin
       WWHERE = 'where ADMREF.BDCODEMP = '||PRCODEMP;

       if (COALESCE(PRCODCOL, 0) > 0) then
          WWHERE = WWHERE||' and ADMREF.BDCODCOL = '||PRCODCOL;
     end

  WSQL = 'select ADMREF.BDCODEMP, ADMREF.BDCODCOL, ADMREF.BDREFCOL, ADMREF.BDVINCEMPCOL, ADMREF.BDSINDICALIZADOCOL, '||
         '       ADMREF.BDALVARACOL, ADMREF.BDCODPROCESSO, PROC.BDNROPROCESSO, true as BDATUAL '||
         'from VRH_EMP_TCOL_ADMREF ADMREF '||
         'left outer join TPROCESSO_JUDADM PROC on PROC.BDCODEMP = ADMREF.BDCODEMP and '||
         '      PROC.BDCODPROCESSO = ADMREF.BDCODPROCESSO '||
         WWHERE||
         ' order by ADMREF.BDREFCOL desc';

  FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFCOL,
    :BDVINCEMPCOL,
    :BDSINDICALIZADOCOL,
    :BDALVARACOL,
    :BDCODPROCESSO,
    :BDNROPROCESSO,
    :BDATUAL
  DO
  SUSPEND;

  if (COALESCE(PRMOSTRATRANSF, 0) = 1) then
     begin
       WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = '||PRCODEMP||' and BDCODCOLDEST = '||PRCODCOL;
       FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
          BEGIN
            IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
               BEGIN
                 WSQL3 = 'SELECT * FROM SP_DADOS_MENSAIS_ADMISSIONAIS('||wcodemporig||', '||wcodcolorig||', '||PRMOSTRATRANSF||')';
                 FOR EXECUTE STATEMENT wsql3 INTO
                 :BDCODEMP,
                 :BDCODCOL,
                 :BDREFCOL,
                 :BDVINCEMPCOL,
                 :BDSINDICALIZADOCOL,
                 :BDALVARACOL,
                 :BDCODPROCESSO,
                 :BDNROPROCESSO,
                 :BDATUAL do
                    BEGIN
                      BDATUAL = FALSE;
                      SUSPEND;
                    END
               END
          END
     end
end^

create or alter procedure SP_DADOS_MENSAIS_BANCO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDCODBAN integer,
    BDNOMBAN varchar(60),
    BDCODAG integer,
    BDNOMAG varchar(40),
    BDCTADEPCOL varchar(15),
    BDDIGCTADEPCOL varchar(2),
    BDTIPOCTACOL integer,
    BDMODOPAGTOCOL integer,
    BDCARTAOSALCOL varchar(7),
    BDCONTRCOL integer,
    BDMODOPAGTOCOLPIXTPCH integer,
    BDMODOPAGTOCOLPIXCH varchar(200),
    BDATUAL boolean)
as
declare variable WSQL varchar(2000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
    /* Procedure Text */
  WWHERE = '';
  if (COALESCE(PRCODEMP, 0) > 0) then
     begin
       WWHERE = 'where BANCOL.BDCODEMP = '||PRCODEMP;

       if (COALESCE(PRCODCOL, 0) > 0) then
          WWHERE = WWHERE||' and BANCOL.BDCODCOL = '||PRCODCOL;
     end

  WSQL = 'select BANCOL.BDCODEMP, BANCOL.BDCODCOL, BANCOL.BDREFCOL, BANCOL.BDCODBAN, BAN.BDNOMBAN, BANCOL.BDCODAG, AG.BDNOMAG, '||
         '       BANCOL.BDCTADEPCOL, BANCOL.BDDIGCTADEPCOL, BANCOL.BDTIPOCTACOL, BANCOL.BDMODOPAGTOCOL, BANCOL.BDCARTAOSALCOL, '||
         '       BANCOL.BDCONTRCOL, BANCOL.BDMODOPAGTOCOLPIXTPCH, BANCOL.BDMODOPAGTOCOLPIXCH, true as BDATUAL '||
         'from VRHF_EMP_TCOLCON_BANCO BANCOL '||
         'left outer join TBANCOS BAN on (BAN.BDCODBAN = BANCOL.BDCODBAN) '||
         'left outer join TBANCOS_AG AG on (AG.BDCODBAN = BANCOL.BDCODBAN and '||
         '      AG.BDCODAG = BANCOL.BDCODAG) '||
         WWHERE||
         ' order by BANCOL.BDREFCOL desc';

  FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFCOL,
    :BDCODBAN,
    :BDNOMBAN,
    :BDCODAG,
    :BDNOMAG,
    :BDCTADEPCOL,
    :BDDIGCTADEPCOL,
    :BDTIPOCTACOL,
    :BDMODOPAGTOCOL,
    :BDCARTAOSALCOL,
    :BDCONTRCOL,
    :BDMODOPAGTOCOLPIXTPCH,
    :BDMODOPAGTOCOLPIXCH,
    :BDATUAL
  DO
  SUSPEND;

  if (COALESCE(PRMOSTRATRANSF, 0) = 1) then
     begin
       WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = '||PRCODEMP||' and BDCODCOLDEST = '||PRCODCOL;
       FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
          BEGIN
            IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
               BEGIN
                 WSQL3 = 'SELECT * FROM SP_DADOS_MENSAIS_BANCO('||wcodemporig||', '||wcodcolorig||', '||PRMOSTRATRANSF||')';
                 FOR EXECUTE STATEMENT wsql3 INTO
                 :BDCODEMP,
                 :BDCODCOL,
                 :BDREFCOL,
                 :BDCODBAN,
                 :BDNOMBAN,
                 :BDCODAG,
                 :BDNOMAG,
                 :BDCTADEPCOL,
                 :BDDIGCTADEPCOL,
                 :BDTIPOCTACOL,
                 :BDMODOPAGTOCOL,
                 :BDCARTAOSALCOL,
                 :BDCONTRCOL,
                 :BDMODOPAGTOCOLPIXTPCH,
                 :BDMODOPAGTOCOLPIXCH,
                 :BDATUAL do
                    BEGIN
                      BDATUAL = FALSE;
                      SUSPEND;
                    END
               END
          END
     end
end^

/* Restore proc. body: SP_DADOS_MENSAIS_CALCULO */
create or alter procedure SP_DADOS_MENSAIS_CALCULO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDFORMAPAGTOCOL integer,
    BDTIPOCOL integer,
    BDHORASMENSAISCOL numeric(15,6),
    BDHORASSEMANAISCOL numeric(15,6),
    BDHORASDIARIASCOL numeric(15,6),
    BDBASEIRRFADCOL numeric(15,6),
    BDPERCADISAL numeric(15,6),
    BDCALCVALREFCOL varchar(5),
    BDCALCVALTRANSCOL varchar(5),
    BDIMPETIQUETACOL varchar(5),
    BDPERCINSALUBCOL numeric(15,6),
    BDINCIDINSALUBCOL integer,
    BDPERCPERCULCOL numeric(15,6),
    BDINCIDPERICULCOL integer,
    BDPERCNOTURNOCOL numeric(15,6),
    BDINCIDNOTURNOCOL integer,
    BDNRODEPSALFAMCOL integer,
    BDNRODEPIRCOL integer,
    BDVALORPREVPRIVNCOL numeric(15,6),
    BDVALORPREVPRIV13COL numeric(15,6),
    BDREGIMEPARCIALCOL DM_BOOLEAN,
    BDPERCGORJ numeric(15,6),
    BDCARTAOVA varchar(20),
    BDCARTAOVR varchar(20),
    BDCARTAOVT varchar(20),
    BDCONTSINDICAL DM_BOOLEAN,
    BDUTILIZADESCSIMPLIFICADO DM_BOOLEAN,
    BDATUAL boolean,
    BDAULISTA boolean)
as
declare variable WSQL varchar(5000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
    /* Procedure Text */
  EXECUTE PROCEDURE SP_SETA_COMPETENCIA(PRREF);

  WWHERE = '';
  if (COALESCE(PRCODEMP, 0) > 0) then
     begin
       WWHERE = 'where COL.BDCODEMP = '||PRCODEMP;

       if (COALESCE(PRCODCOL, 0) > 0) then
          WWHERE = WWHERE||' and COL.BDCODCOL = '||PRCODCOL;
     end

  WSQL = 'select COL.BDCODEMP, COL.BDCODCOL, COL.BDREFCOL, COLCON.BDFORMAPAGTOCOL, COL.BDTIPOCOL, COL.BDHORASMENSAISCOL, '||
         '       COL.BDHORASSEMANAISCOL, COL.BDHORASDIARIASCOL, COLCON.BDBASEIRRFADCOL, COL.BDPERCADISAL, COL.BDCALCVALREFCOL, '||
         '       COL.BDCALCVALTRANSCOL, COL.BDIMPETIQUETACOL, COL.BDPERCINSALUBCOL, COL.BDINCIDINSALUBCOL, COL.BDPERCPERCULCOL, '||
         '       COL.BDINCIDPERICULCOL, COL.BDPERCNOTURNOCOL, COL.BDINCIDNOTURNOCOL, '||
         '       case '||
         '         when coalesce(DEPCALC.DEPSF, 0) > 0 then DEPCALC.DEPSF '||
         '         else coalesce(COL.BDNRODEPSALFAMCOL, 0) '||
         '       end BDNRODEPSALFAMCOL, '||
         '       case '||
         '         when coalesce(DEPCALC.DEPIR, 0) > 0 then DEPCALC.DEPIR '||
         '         else coalesce(COLCON.BDNRODEPIRCOL, 0) '||
         '       end BDNRODEPIRCOL, '||
         '       COLCON.BDVALORPREVPRIVNCOL, COLCON.BDVALORPREVPRIV13COL, COL.BDREGIMEPARCIALCOL, COL.BDPERCGORJ, COL.BDCARTAOVA, '||
         '       COL.BDCARTAOVR, COL.BDCARTAOVT, COL.BDCONTSINDICAL, '||
         '       coalesce(COLREF.BDUTILIZADESCSIMPLIFICADO, ''FALSE'') BDUTILIZADESCSIMPLIFICADO, true as BDATUAL, COL.BDAULISTA '||
         'from VRHF_EMP_TCOL_CALC COL '||
         'left outer join VRH_EMP_TCOLCON_REF COLREF on (COL.BDCODEMP = COLREF.BDCODEMP) and '||
         '      (COL.BDCODCOL = COLREF.BDCODCOL) and '||
         '      (COL.BDREFCOL = COLREF.BDREFCOL) '||
         'left outer join VRHF_EMP_TCOLCON_CALC COLCON on (COL.BDCODEMP = COLCON.BDCODEMP and '||
         '      COL.BDCODCOL = COLCON.BDCODCOL and '||
         '      COL.BDREFCOL = COLCON.BDREFCOL) '||
         'left outer join(select BDCODEMP, BDCODCOL, coalesce(max(DEPSF), 0) DEPSF, coalesce(max(DEPIR), 0) DEPIR '||
         '                from (select COLCON.BDCODEMP, COLCON.BDCODCOL, count(*) DEPSF, 0 DEPIR '||
         '                      from VW_VRH_EMP_TDEP_REF COLCON '||
         '                      join VRH_EMP_TDEP DEP on (DEP.BDCODEMP = COLCON.BDCODEMP and '||
         '                            DEP.BDCODCOL = COLCON.BDCODCOL and '||
         '                            DEP.BDCODDPN = COLCON.BDCODDPN) '||
         '                      where upper(coalesce(COLCON.BDSALFAMDPN, ''FALSE'')) = ''TRUE'' and '||
                                      REPLACE(REPLACE(wwhere, 'COL.', 'COLCON.'), 'where', '') || ' and '||
         '                            COLCON.BDPARENESCODPN in (0, 4) and '||
         '                            COLCON.BDPARENESCODPN <> 3 and '||
         '                            ((select BDAAAAMM '||
         '                              from AAAAMM(coalesce(COLCON.BDDATANASCDPN, DEP.BDDATAENTREDPN))) <= 202410) and '||
         '                            ((DEP.BDDATABAUXADPN is null) or ((select BDAAAAMM '||
         '                                                               from AAAAMM(DEP.BDDATABAUXADPN)) > 202410)) and '||
         '                            ((upper(COLCON.BDINVALIDODPN) = ''TRUE'') or ((not COLCON.BDDATANASCDPN is null) and '||
         '                            (202410 - cast((select BDAAAAMM '||
         '                                            from AAAAMM(COLCON.BDDATANASCDPN)) as integer) <= 1400))) '||
         '                      group by COLCON.BDCODEMP, COLCON.BDCODCOL '||
         '                      union all '||
         '                      select COLCON.BDCODEMP, COLCON.BDCODCOL, 0 DEPSF, count(*) DEPIR '||
         '                      from VW_VRH_EMP_TDEP_REF COLCON '||
         '                      join VRH_EMP_TDEP DEP on (DEP.BDCODEMP = COLCON.BDCODEMP and '||
         '                            DEP.BDCODCOL = COLCON.BDCODCOL and '||
         '                            DEP.BDCODDPN = COLCON.BDCODDPN) '||
         '                      where upper(coalesce(COLCON.BDDEPIRDPN, ''FALSE'')) = ''TRUE'' and '||
                                      REPLACE(REPLACE(wwhere, 'COL.', 'COLCON.'), 'where', '') || ' and '||
         '                            COLCON.BDPARENESCODPN <> 3 and '||
         '                            (select BDAAAAMM '||
         '                             from AAAAMM(coalesce(COLCON.BDDATANASCDPN, DEP.BDDATAENTREDPN))) <= 202410 and '||
         '                            ((DEP.BDDATABAUXADPN is null) or ((select BDAAAAMM '||
         '                                                               from AAAAMM(DEP.BDDATABAUXADPN)) > 202410)) and '||
         '                            ((DEP.BDREFIRDPN is null) or (DEP.BDREFIRDPN = 0) or (DEP.BDREFIRDPN >= 202410)) and '||
         '                            ((upper(COLCON.BDINVALIDODPN) = ''TRUE'') or (DEP.BDREFIRDPN >= 202410) or ((COLCON.BDPARENESCODPN in (0, 4, 5, 6)) and '||
         '                            (202410 - cast((select BDAAAAMM '||
         '                                            from AAAAMM(COLCON.BDDATANASCDPN)) as integer) < 2200)) or (COLCON.BDPARENESCODPN in (1, 2))) '||
         '                      group by COLCON.BDCODEMP, COLCON.BDCODCOL) '||
         '                group by BDCODEMP, BDCODCOL) DEPCALC on (DEPCALC.BDCODEMP = COL.BDCODEMP and '||
         '      DEPCALC.BDCODCOL = COL.BDCODCOL) '||
         WWHERE||
         ' order by COL.BDREFCOL desc';

  FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFCOL,
    :BDFORMAPAGTOCOL,
    :BDTIPOCOL,
    :BDHORASMENSAISCOL,
    :BDHORASSEMANAISCOL,
    :BDHORASDIARIASCOL,
    :BDBASEIRRFADCOL,
    :BDPERCADISAL,
    :BDCALCVALREFCOL,
    :BDCALCVALTRANSCOL,
    :BDIMPETIQUETACOL,
    :BDPERCINSALUBCOL,
    :BDINCIDINSALUBCOL,
    :BDPERCPERCULCOL,
    :BDINCIDPERICULCOL,
    :BDPERCNOTURNOCOL,
    :BDINCIDNOTURNOCOL,
    :BDNRODEPSALFAMCOL,
    :BDNRODEPIRCOL,
    :BDVALORPREVPRIVNCOL,
    :BDVALORPREVPRIV13COL,
    :BDREGIMEPARCIALCOL,
    :BDPERCGORJ,
    :BDCARTAOVA,
    :BDCARTAOVR,
    :BDCARTAOVT,
    :BDCONTSINDICAL,
    :BDUTILIZADESCSIMPLIFICADO,
    :BDATUAL,
    :BDAULISTA
  DO
  SUSPEND;

  if (COALESCE(PRMOSTRATRANSF, 0) = 1) then
     begin
       WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = '||PRCODEMP||' and BDCODCOLDEST = '||PRCODCOL;
       FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
          BEGIN
            IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
               BEGIN
                 WSQL3 = 'SELECT * FROM SP_DADOS_MENSAIS_CALCULO('||wcodemporig||', '||wcodcolorig||', '||prref||', '||PRMOSTRATRANSF||')';
                 FOR EXECUTE STATEMENT wsql3 INTO
                 :BDCODEMP,
                 :BDCODCOL,
                 :BDREFCOL,
                 :BDFORMAPAGTOCOL,
                 :BDTIPOCOL,
                 :BDHORASMENSAISCOL,
                 :BDHORASSEMANAISCOL,
                 :BDHORASDIARIASCOL,
                 :BDBASEIRRFADCOL,
                 :BDPERCADISAL,
                 :BDCALCVALREFCOL,
                 :BDCALCVALTRANSCOL,
                 :BDIMPETIQUETACOL,
                 :BDPERCINSALUBCOL,
                 :BDINCIDINSALUBCOL,
                 :BDPERCPERCULCOL,
                 :BDINCIDPERICULCOL,
                 :BDPERCNOTURNOCOL,
                 :BDINCIDNOTURNOCOL,
                 :BDNRODEPSALFAMCOL,
                 :BDNRODEPIRCOL,
                 :BDVALORPREVPRIVNCOL,
                 :BDVALORPREVPRIV13COL,
                 :BDREGIMEPARCIALCOL,
                 :BDPERCGORJ,
                 :BDCARTAOVA,
                 :BDCARTAOVR,
                 :BDCARTAOVT,
                 :BDCONTSINDICAL,
                 :BDUTILIZADESCSIMPLIFICADO,
                 :BDATUAL,
                 :BDAULISTA do
                    BEGIN
                      BDATUAL = FALSE;
                      SUSPEND;
                    END
               END
          END
     end
end^

create or alter procedure SP_DADOS_MENSAIS_HISTORICO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRMOSTRATRANSF integer = 0)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFCOL integer,
    BDGERARNMSOCIAL varchar(5),
    BDNMSOCIAL varchar(70),
    BDATUAL boolean)
as
declare variable WSQL varchar(1000);
declare variable WSQL2 varchar(200);
declare variable WSQL3 varchar(200);
declare variable WWHERE varchar(500);
declare variable WCODEMPORIG integer;
declare variable WCODCOLORIG integer;
begin
    /* Procedure Text */
  WWHERE = '';
  if (COALESCE(PRCODEMP, 0) > 0) then
     begin
       WWHERE = 'where COL.BDCODEMP = '||PRCODEMP;

       if (COALESCE(PRCODCOL, 0) > 0) then
          WWHERE = WWHERE||' and COL.BDCODCOL = '||PRCODCOL;
     end

  WSQL = 'select COL.BDCODEMP, COL.BDCODCOL, COL.BDREFCOL, COL.BDGERARNMSOCIAL, COL.BDNMSOCIAL, TRUE AS BDATUAL '||
         'from VRH_EMP_TCOLCON_FIS COL '||
         WWHERE||
         ' order by COL.BDREFCOL desc';

  FOR EXECUTE STATEMENT WSQL
  INTO
    :BDCODEMP,
    :BDCODCOL,
    :BDREFCOL,
    :BDGERARNMSOCIAL,
    :BDNMSOCIAL,
    :BDATUAL
  DO
  SUSPEND;

  if (COALESCE(PRMOSTRATRANSF, 0) = 1) then
     begin
       WSQL2 = 'select BDCODEMPORIG, BDCODCOLORIG from VRH_EMP_TTRANSCOL where BDCODEMPDEST = '||PRCODEMP||' and BDCODCOLDEST = '||PRCODCOL;
       FOR EXECUTE STATEMENT wsql2 INTO :wcodemporig, :wcodcolorig DO
          BEGIN
            IF ((wcodemporig IS NOT NULL) OR (wcodcolorig IS NOT NULL))  THEN
               BEGIN
                 WSQL3 = 'SELECT * FROM SP_DADOS_MENSAIS_HISTORICO('||wcodemporig||', '||wcodcolorig||', '||PRMOSTRATRANSF||')';
                 FOR EXECUTE STATEMENT wsql3 INTO
                 :BDCODEMP,
                 :BDCODCOL,
                 :BDREFCOL,
                 :BDGERARNMSOCIAL,
                 :BDNMSOCIAL,
                 :BDATUAL do
                    BEGIN
                      BDATUAL = FALSE;
                      SUSPEND;
                    END
               END
          END
     end
end^

create or alter procedure SP_VRH_GET_SOMA_GPS_IND (
    PRCODEMP integer,
    PRCHAVE integer)
returns (
    BDCHAVE integer,
    BDCODEMP integer,
    BDCODCENTRO integer,
    BDCODTPCC integer,
    BDLIQUIDO numeric(15,2))
as
BEGIN
    BDLIQUIDO = 0;
    FOR
        SELECT BDCHAVEDARF,BDCODEMP, BDCODCENTRO,BDCODTPCC ,Sum(bdliquido) from ( Select BDCHAVEDARF,
            BDCODEMP,
            BDCODCENTRO,
            Coalesce(BDCODTPCCCOL,BDCODTPCC,0) BDCODTPCC,
            COALESCE(BDVALFUNEMPFN, 0) + COALESCE(BDVALFUNEMPFC, 0) + COALESCE(BDVALFUNEMPFERFN, 0) +
            COALESCE(BDVALFUNEMPFERFC, 0) + COALESCE(BDVALFUNEMP13FN, 0) + COALESCE(BDVALFUNEMP13FC, 0) +
            COALESCE(BDVALFUNEMP13, 0) + COALESCE(BDVALFUNEMPC13, 0) + COALESCE(BDVALPROEMPFN, 0) +
            COALESCE(BDVALPROEMPFC, 0) + COALESCE(BDVALPROEMPFERFN, 0) + COALESCE(BDVALPROEMPFERFC, 0) +
            COALESCE(BDVALPROEMP13FN, 0) + COALESCE(BDVALPROEMP13FC, 0) + COALESCE(BDVALPROEMP13, 0) +
            COALESCE(BDVALPROEMPC13, 0) + COALESCE(BDVALAUTEMPFN, 0) + COALESCE(BDVALAUTEMPFC, 0) +
            COALESCE(BDVALAUTEMPFERFN, 0) + COALESCE(BDVALAUTEMPFERFC, 0) + COALESCE(BDVALAUTEMP13FN, 0) +
            COALESCE(BDVALAUTEMP13FC, 0) + COALESCE(BDVALAUTEMP13, 0) + COALESCE(BDVALAUTEMPC13, 0) +
            COALESCE(BDVALFPASEMPFN, 0) + COALESCE(BDVALFPASEMPFC, 0) + COALESCE(BDVALFPASEMPFERFN, 0) +
            COALESCE(BDVALFPASEMPFERFC, 0) + COALESCE(BDVALFPASEMP13FN, 0) + COALESCE(BDVALFPASEMP13FC, 0) +
            COALESCE(BDVALFPASEMP13, 0) + COALESCE(BDVALFPASEMPC13, 0) + COALESCE(BDVALRATEMPFN, 0) +
            COALESCE(BDVALRATEMPFC, 0) + COALESCE(BDVALRATEMPFERFN, 0) + COALESCE(BDVALRATEMPFERFC, 0) +
            COALESCE(BDVALRATEMP13FN, 0) + COALESCE(BDVALRATEMP13FC, 0) + COALESCE(BDVALRATEMP13, 0) +
            COALESCE(BDVALRATEMPC13, 0) + COALESCE(BDVALRATAPOEMPFN, 0) + COALESCE(BDVALRATAPOEMPFC, 0) +
            COALESCE(BDVALRATAPOEMPFERFN, 0) + COALESCE(BDVALRATAPOEMPFERFC, 0) + COALESCE(BDVALRATAPOEMP13FN, 0) +
            COALESCE(BDVALRATAPOEMP13FC, 0) + COALESCE(BDVALRATAPOEMP13, 0) + COALESCE(BDVALRATAPOEMPC13, 0) +
            COALESCE(BDVALPBM13INDFN, 0) + COALESCE(BDVALAC13INDFN, 0) + COALESCE(BDVALPROEMP13INDFC, 0) +
            COALESCE(BDVALFUNEMP13INDFC, 0) + COALESCE(BDVALAUTEMP13INDFC, 0) + COALESCE(BDVALFPASEMP13INDFC, 0) +
            COALESCE(BDVALRATEMP13INDFC, 0) + COALESCE(BDVALRATAPOEMP13INDFC, 0) + COALESCE(BDVALPBM13INDFC, 0) +
            COALESCE(BDVALAC13INDFC, 0) + COALESCE(BDVALSALEDUEMPFN, 0) + COALESCE(BDVALSALEDUEMPFC, 0) +
            COALESCE(BDVALSALEDUEMPFERFN, 0) + COALESCE(BDVALSALEDUEMPFERFC, 0) + COALESCE(BDVALSALEDUEMP13FN, 0) +
            COALESCE(BDVALSALEDUEMP13FC, 0) + COALESCE(BDVALSALEDUEMP13, 0) + COALESCE(BDVALSALEDUEMPC13, 0) +
            COALESCE(BDVALINCRAEMPFN, 0) + COALESCE(BDVALINCRAEMPFC, 0) + COALESCE(BDVALINCRAEMPFERFN, 0) +
            COALESCE(BDVALINCRAEMPFERFC, 0) + COALESCE(BDVALINCRAEMP13FN, 0) + COALESCE(BDVALINCRAEMP13FC, 0) +
            COALESCE(BDVALINCRAEMP13, 0) + COALESCE(BDVALINCRAEMPC13, 0) + COALESCE(BDVALSENAIEMPFN, 0) +
            COALESCE(BDVALSENAIEMPFC, 0) + COALESCE(BDVALSENAIEMPFERFN, 0) + COALESCE(BDVALSENAIEMPFERFC, 0) +
            COALESCE(BDVALSENAIEMP13FN, 0) + COALESCE(BDVALSENAIEMP13FC, 0) + COALESCE(BDVALSENAIEMP13, 0) +
            COALESCE(BDVALSENAIEMPC13, 0) + COALESCE(BDVALSESIEMPFN, 0) + COALESCE(BDVALSESIEMPFC, 0) +
            COALESCE(BDVALSESIEMPFERFN, 0) + COALESCE(BDVALSESIEMPFERFC, 0) + COALESCE(BDVALSESIEMP13FN, 0) +
            COALESCE(BDVALSESIEMP13FC, 0) + COALESCE(BDVALSESIEMP13, 0) + COALESCE(BDVALSESIEMPC13, 0) +
            COALESCE(BDVALSENACEMPFN, 0) + COALESCE(BDVALSENACEMPFC, 0) + COALESCE(BDVALSENACEMPFERFN, 0) +
            COALESCE(BDVALSENACEMPFERFC, 0) + COALESCE(BDVALSENACEMP13FN, 0) + COALESCE(BDVALSENACEMP13FC, 0) +
            COALESCE(BDVALSENACEMP13, 0) + COALESCE(BDVALSENACEMPC13, 0) + COALESCE(BDVALSESCEMPFN, 0) +
            COALESCE(BDVALSESCEMPFC, 0) + COALESCE(BDVALSESCEMPFERFN, 0) + COALESCE(BDVALSESCEMPFERFC, 0) +
            COALESCE(BDVALSESCEMP13FN, 0) + COALESCE(BDVALSESCEMP13FC, 0) + COALESCE(BDVALSESCEMP13, 0) +
            COALESCE(BDVALSESCEMPC13, 0) + COALESCE(BDVALSEBRAEEMPFN, 0) + COALESCE(BDVALSEBRAEEMPFC, 0) +
            COALESCE(BDVALSEBRAEEMPFERFN, 0) + COALESCE(BDVALSEBRAEEMPFERFC, 0) + COALESCE(BDVALSEBRAEEMP13FN, 0) +
            COALESCE(BDVALSEBRAEEMP13FC, 0) + COALESCE(BDVALSEBRAEEMP13, 0) + COALESCE(BDVALSEBRAEEMPC13, 0) +
            COALESCE(BDVALDPCEMPFN, 0) + COALESCE(BDVALDPCEMPFC, 0) + COALESCE(BDVALDPCEMPFERFN, 0) +
            COALESCE(BDVALDPCEMPFERFC, 0) + COALESCE(BDVALDPCEMP13FN, 0) + COALESCE(BDVALDPCEMP13FC, 0) +
            COALESCE(BDVALDPCEMP13, 0) + COALESCE(BDVALDPCEMPC13, 0) + COALESCE(BDVALFUNAEROEMPFN, 0) +
            COALESCE(BDVALFUNAEROEMPFC, 0) + COALESCE(BDVALFUNAEROEMPFERFN, 0) + COALESCE(BDVALFUNAEROEMPFERFC, 0) +
            COALESCE(BDVALFUNAEROEMP13FN, 0) + COALESCE(BDVALFUNAEROEMP13FC, 0) + COALESCE(BDVALFUNAEROEMP13, 0) +
            COALESCE(BDVALFUNAEROEMPC13, 0) + COALESCE(BDVALSENAREMPFN, 0) + COALESCE(BDVALSENAREMPFC, 0) +
            COALESCE(BDVALSENAREMPFERFN, 0) + COALESCE(BDVALSENAREMPFERFC, 0) + COALESCE(BDVALSENAREMP13FN, 0) +
            COALESCE(BDVALSENAREMP13FC, 0) + COALESCE(BDVALSENAREMP13, 0) + COALESCE(BDVALSENAREMPC13, 0) +
            COALESCE(BDVALSESTEMPFN, 0) + COALESCE(BDVALSESTEMPFC, 0) + COALESCE(BDVALSESTEMPFERFN, 0) +
            COALESCE(BDVALSESTEMPFERFC, 0) + COALESCE(BDVALSESTEMP13FN, 0) + COALESCE(BDVALSESTEMP13FC, 0) +
            COALESCE(BDVALSESTEMP13, 0) + COALESCE(BDVALSESTEMPC13, 0) + COALESCE(BDVALSENATEMPFN, 0) +
            COALESCE(BDVALSENATEMPFC, 0) + COALESCE(BDVALSENATEMPFERFN, 0) + COALESCE(BDVALSENATEMPFERFC, 0) +
            COALESCE(BDVALSENATEMP13FN, 0) + COALESCE(BDVALSENATEMP13FC, 0) + COALESCE(BDVALSENATEMP13, 0) +
            COALESCE(BDVALSENATEMPC13, 0) + COALESCE(BDVALSESCOOPEMPFN, 0) + COALESCE(BDVALSESCOOPEMPFC, 0) +
            COALESCE(BDVALSESCOOPEMPFERFN, 0) + COALESCE(BDVALSESCOOPEMPFERFC, 0) + COALESCE(BDVALSESCOOPEMP13FN, 0) +
            COALESCE(BDVALSESCOOPEMP13FC, 0) + COALESCE(BDVALSESCOOPEMP13, 0) + COALESCE(BDVALSESCOOPEMPC13, 0)+
            COALESCE(BDVALINSSFN, 0) + COALESCE(BDVALINSSFEFOL, 0) + COALESCE(BDVALINSS13FN, 0) bdliquido
        FROM VRHF_EMP_GPS_IND WHERE BDCHAVEDARF=:PRCHAVE AND BDCODEMP=:PRCODEMP AND BDVALINSSFN IS NOT NULL)
        group by BDCHAVEDARF,BDCODEMP, BDCODCENTRO,BDCODTPCC  into :BDCHAVE, :BDCODEMP, :BDCODCENTRO, :BDCODTPCC, :BDLIQUIDO do
        begin
          SUSPEND;
        end
END^

create or alter procedure SP_GET_DESC_CAMPOS_DOWNLOAD (
    PRCODTABELA integer = 0)
returns (
    BDCODTABELA integer,
    BDTABELA varchar(100),
    BDCAMPO varchar(100),
    BDDESC varchar(1000))
as
declare variable WSQL varchar(1000);
begin
  /* Procedure Text */
  wsql = 'select '||
         '   A.BDCODTABELA, '||
         '   A.BDTABELA, '||
         '   A.BDCAMPO, '||
         '   cast( '||
         '       substring(CM.RDB$DESCRIPTION from 1 for '||
         '           case when position(ASCII_CHAR(10) in CM.RDB$DESCRIPTION) > 0 then position(ASCII_CHAR(10) in CM.RDB$DESCRIPTION) - 1 '||
         '           else 1000 end '||
         '       ) as varchar(1000)) BDDESC '||
         ' from VRH_BASE_CAMPO_TTABELA A '||
         ' inner join RDB$RELATION_FIELDS CM on CM.RDB$FIELD_NAME = A.BDCAMPO and CM.RDB$RELATION_NAME = A.BDTABELA ';

  if (prcodtabela > 0) then
     wsql = wsql||' WHERE A.BDCODTABELA = '||:PRCODTABELA;

  for execute statement wsql
      into :BDCODTABELA, :BDTABELA, :BDCAMPO, :BDDESC
  do
  suspend;
end^

create or alter procedure SP_TEMPPARFED (
    PRCODEMP integer,
    PRREFEMP integer)
returns (
    BDCODEMP integer,
    BDREFEMP integer,
    BDCODCONFICMSSPED integer)
as
begin
    for select X.BDCODEMP, X.BDREFEMP, X.BDCODCONFICMSSPED
    from VEF_BASE_TEMPPARFED X
    where X.BDCODEMP = :PRCODEMP and
          X.BDREFEMP = (select first 1 Y.BDREFEMP
                        from VEF_BASE_TEMPPARFED Y
                        where X.BDCODEMP = Y.BDCODEMP and
                              Y.BDREFEMP <= :PRREFEMP
                        order by Y.BDREFEMP desc)
    into :BDCODEMP, :BDREFEMP, :BDCODCONFICMSSPED
    do
    suspend;
end^

CREATE OR ALTER TRIGGER VSH_TARQUIVO_SEQREL_BI0 FOR VSH_TARQUIVO_SEQREL
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  SELECT COALESCE(MAX(BDCODARQ), 0) + 1
  FROM VSH_TARQUIVO_SEQREL
  INTO NEW.BDCODARQ;
END^



CREATE OR ALTER procedure SP_NOVA_AUTOMATIZACAO (
    PRSEQUENCIA integer)
as
declare variable WSQLNOMECAMPOS1 varchar(120);
declare variable WSQLNOMECAMPOS2 varchar(150);
declare variable WNCAMPO varchar(300);
declare variable WSQL varchar(30000);
declare variable WSQLI varchar(30000);
declare variable wusu integer;
begin
  wusu = CAST((TRIM(rdb$get_context('USER_SESSION', 'W_USUARIO'))) AS INTEGER);

  /* Procedure Text */
  wsqlnomecampos1 = 'SELECT TRIM(A.RDB$FIELD_NAME) FROM RDB$RELATION_FIELDS A, RDB$FIELDS B, RDB$TYPES C WHERE ';
  wsqlnomecampos2 = ' (B.RDB$FIELD_NAME = A.RDB$FIELD_SOURCE) AND (C.RDB$TYPE = B.RDB$FIELD_TYPE) AND (C.RDB$FIELD_NAME = '''||'RDB$FIELD_TYPE'||''') ORDER BY RDB$FIELD_POSITION';

--  suspend;
  wsql  = 'insert into TAUTOMATIZACOES (BDSEQUENCIAL,BDSTATUS,BDINCLUSAO,BDPREVISAO,BDINICIO,BDFIM,BDUSUARIO';
  wsqli = 'select null,0,current_date+current_time,null,null,null,'||wusu;
  FOR EXECUTE STATEMENT wsqlnomecampos1||' (A.RDB$RELATION_NAME = '''||'TAUTOMATIZACOES'||''') AND ' ||wsqlnomecampos2 INTO :wncampo DO
  BEGIN
    IF ((wncampo <> 'BDSEQUENCIAL') AND
        (wncampo <> 'BDPREVISAO') AND
        (wncampo <> 'BDINICIO') AND
        (wncampo <> 'BDUSUARIO') and
        (wncampo <> 'BDFIM') AND
        (wncampo <> 'BDSTATUS') AND
        (wncampo <> 'BDINCLUSAO')) THEN
      BEGIN
        wsql  = wsql||','||wncampo;
        wsqli = wsqli||','||wncampo;
      END
  END
  wsql  = wsql||') ';
  wsqli = wsqli||' from TAUTOMATIZACOES where BDSEQUENCIAL = '||PRSEQUENCIA;
  EXECUTE STATEMENT wsql||wsqli;


end^

CREATE or alter trigger vrhf_emp_tconfverbas_reembolso_bi0 for vrhf_emp_tconfverbas_reembolso
active before insert position 0
AS
begin
  /* Trigger text */
  if (coalesce(new.bdordem,0) = 0) then
     begin
       select first 1 coalesce(bdordem,0)+1 from vrhf_emp_tconfverbas_reembolso into new.bdordem;

       if (coalesce(new.bdordem,0) = 0) then
          new.bdordem = 1;
     end

end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_CONSOLIDAPURMEN_C_BI0 FOR VRH_ESOCIAL_CONSOLIDAPURMEN_C
ACTIVE BEFORE INSERT POSITION 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDCODCONSOLID is null) or (new.BDCODCONSOLID = 0)) then
  begin
    select coalesce((max(BDCODCONSOLID) + 1), 1)
    from VRH_ESOCIAL_CONSOLIDAPURMEN_C
    where BDCODEMP = new.BDCODEMP and
          BDCODCOL = new.BDCODCOL and
          BDCODEVT = new.BDCODEVT and
          BDTIPOCALCFIR = new.BDTIPOCALCFIR
    into :VCODIGO;

    new.BDCODCONSOLID = :VCODIGO;
  end

  if (new.bdrefevt is null) then
     select first 1 x.bdrefarq from vrh_esocial_tarquivo x where x.bdcodemp = new.BDCODEMP and x.bdcodigo = new.bdcodevt into new.bdrefevt;
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_CONSOLIDAPURMEN_C_BU0 FOR VRH_ESOCIAL_CONSOLIDAPURMEN_C
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  /* Trigger text */
  if (new.bdrefevt is null) then
     select first 1 x.bdrefarq from vrh_esocial_tarquivo x where x.bdcodemp = new.BDCODEMP and x.bdcodigo = new.bdcodevt into new.bdrefevt;
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_CONSOLIDAPURMEN_C_TERC_BI0 FOR VRH_ESOCIAL_CONSOLIDAPURMEN_C_TERC
ACTIVE BEFORE INSERT POSITION 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDCODCONSOLID is null) or (new.BDCODCONSOLID = 0)) then
  begin
    select coalesce((max(BDCODCONSOLID) + 1), 1)
    from VRH_ESOCIAL_CONSOLIDAPURMEN_C_TERC
    where BDCODEMP = new.BDCODEMP and
          BDCODTER = new.BDCODTER and
          BDCODEVT = new.BDCODEVT and
          BDTIPOCALCFIR = new.BDTIPOCALCFIR
    into :VCODIGO;

    new.BDCODCONSOLID = :VCODIGO;
  end

  if (new.bdrefevt is null) then
     select first 1 x.bdrefarq from vrh_esocial_tarquivo x where x.bdcodemp = new.BDCODEMP and x.bdcodigo = new.bdcodevt into new.bdrefevt;
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_CONSOLIDAPURMEN_C_TERC_BU0 FOR VRH_ESOCIAL_CONSOLIDAPURMEN_C_TERC
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  /* Trigger text */
  if (new.bdrefevt is null) then
     select first 1 x.bdrefarq from vrh_esocial_tarquivo x where x.bdcodemp = new.BDCODEMP and x.bdcodigo = new.bdcodevt into new.bdrefevt;
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_INFOIRRF_DEP_BI0 FOR VRH_ESOCIAL_INFOIRRF_DEP
ACTIVE BEFORE INSERT POSITION 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDCODDEPSEQ is null) or (new.BDCODDEPSEQ = 0)) then
  begin
    select coalesce((max(BDCODDEPSEQ) + 1), 1)
    from VRH_ESOCIAL_INFOIRRF_DEP
    where BDCODEMP = new.BDCODEMP and
          BDCODCOL = new.BDCODCOL and
          BDCODEVT = new.BDCODEVT and
          BDCODCONSOLID = new.BDCODCONSOLID and
          BDTIPOCALCFIR = new.BDTIPOCALCFIR and
          BDTIPOREGISTRO = NEW.BDTIPOREGISTRO
    into VCODIGO;

    new.BDCODDEPSEQ = VCODIGO;
  end

end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_INFOIRRF_DEP_TERC_BI0 FOR VRH_ESOCIAL_INFOIRRF_DEP_TERC
ACTIVE BEFORE INSERT POSITION 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDCODDEPSEQ is null) or (new.BDCODDEPSEQ = 0)) then
  begin
    select coalesce((max(BDCODDEPSEQ) + 1), 1)
    from VRH_ESOCIAL_INFOIRRF_DEP_TERC
    where BDCODEMP = new.BDCODEMP and
          BDCODTER = new.BDCODTER and
          BDCODEVT = new.BDCODEVT and
          BDCODCONSOLID = new.BDCODCONSOLID and
          BDTIPOCALCFIR = new.BDTIPOCALCFIR and
          BDTIPOREGISTRO = NEW.BDTIPOREGISTRO
    into VCODIGO;

    new.BDCODDEPSEQ = VCODIGO;
  end

end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_INFOIRRF_PLANSAU_BI0 FOR VRH_ESOCIAL_INFOIRRF_PLANSAU
ACTIVE BEFORE INSERT POSITION 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDCODPLANSAU is null) or (new.BDCODPLANSAU = 0)) then
  begin
    select coalesce((max(BDCODPLANSAU) + 1), 1)
    from VRH_ESOCIAL_INFOIRRF_PLANSAU
    where BDCODEMP = new.BDCODEMP and
          BDCODCOL = new.BDCODCOL and
          BDCODEVT = new.BDCODEVT and
          BDCODCONSOLID = new.BDCODCONSOLID AND
          BDTIPOCALCFIR = NEW.BDTIPOCALCFIR AND
          BDTIPOREGISTRO = NEW.BDTIPOREGISTRO
    into VCODIGO;

    new.BDCODPLANSAU = VCODIGO;
  end
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_INFOIRRF_PREVIDCOMPL_BI0 FOR VRH_ESOCIAL_INFOIRRF_PREVIDCOMPL
ACTIVE BEFORE INSERT POSITION 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDCODPREVCOMPL is null) or (new.BDCODPREVCOMPL = 0)) then
  begin
    select coalesce((max(BDCODPREVCOMPL) + 1), 1)
    from VRH_ESOCIAL_INFOIRRF_PREVIDCOMPL
    where BDCODEMP = new.BDCODEMP and
          BDCODCOL = new.BDCODCOL and
          BDCODEVT = new.BDCODEVT and
          BDCODCONSOLID = new.BDCODCONSOLID and
          BDTIPOCALCFIR = new.BDTIPOCALCFIR
    into VCODIGO;

    new.BDCODPREVCOMPL = VCODIGO;
  end
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_INFOIRRF_REEMBMED_BI0 FOR VRH_ESOCIAL_INFOIRRF_REEMBMED
ACTIVE BEFORE INSERT POSITION 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDCODREEMBMED is null) or (new.BDCODREEMBMED = 0)) then
  begin
    select coalesce((max(BDCODREEMBMED) + 1), 1)
    from VRH_ESOCIAL_INFOIRRF_REEMBMED
    where BDCODEMP = new.BDCODEMP and
          BDCODCOL = new.BDCODCOL and
          BDCODEVT = new.BDCODEVT and
          BDCODCONSOLID = new.BDCODCONSOLID and
          BDTIPOCALCFIR = new.BDTIPOCALCFIR and
          BDTIPOREGISTRO = new.BDTIPOREGISTRO
    into VCODIGO;

    new.BDCODREEMBMED = VCODIGO;
  end
end^

CREATE OR ALTER trigger planos_tpla_ecf_lalur_padrao_bi0 for planos_tpla_ecf_lalur_padrao
active before insert position 0
AS             
  DECLARE VARIABLE  vNova_Chave INTEGER;
begin
  IF ((NEW.bdcodtplareflalur IS NULL) OR (NEW.bdcodtplareflalur = 0))  THEN
    BEGIN
      SELECT COALESCE((MAX(bdcodtplareflalur)+1), 1) FROM PLANOS_TPLA_ECF_LALUR_PADRAO
      WHERE BDCODPLAPADRAOREFLALUR = NEW.BDCODPLAPADRAOREFLALUR INTO vNova_Chave;
      NEW.bdcodtplareflalur = vNova_Chave;
    END
end^

CREATE OR ALTER TRIGGER VSUC_MIGRACAO_INCONSISTENCIAS_BI0 FOR VSUC_MIGRACAO_INCONSISTENCIAS
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE wCod INTEGER;
begin
  IF (NEW.BDCODIGO IS NULL OR NEW.BDCODIGO = 0) THEN
      BEGIN
        SELECT COALESCE(MAX(BDCODIGO), 0) + 1
        FROM VSUC_MIGRACAO_INCONSISTENCIAS
        WHERE BDCODPLANOONLINE = NEW.BDCODPLANOONLINE
          AND BDCODIGOMIGRACAO = NEW.BDCODIGOMIGRACAO
          AND BDCODEMP = NEW.BDCODEMP
          AND BDORDEM = NEW.BDORDEM
        INTO :wCod;
    
        NEW.BDCODIGO = :wCod;
      END
end^

CREATE OR ALTER TRIGGER VSUC_TERCEIRO_INCON_MIGRACAO_BI0 FOR VSUC_TERCEIRO_INCON_MIGRACAO
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE wCod INTEGER;
begin
  IF (NEW.BDCODIGO IS NULL OR NEW.BDCODIGO = 0) THEN
      BEGIN
        SELECT COALESCE(MAX(BDCODIGO), 0) + 1
        FROM VSUC_TERCEIRO_INCON_MIGRACAO
        WHERE BDCODPLANOONLINE = NEW.BDCODPLANOONLINE
          AND BDCODIGOMIGRACAO = NEW.BDCODIGOMIGRACAO
          AND BDCODEMP = NEW.BDCODEMP
          AND BDORDEM = NEW.BDORDEM
        INTO :wCod;
    
        NEW.BDCODIGO = :wCod;
      END
end^

CREATE OR ALTER TRIGGER TOL_VSUC_TDIST_LUCRO_TSOCCOTAS_PGTO_AD0 FOR TOL_VSUC_TDIST_LUCRO_TSOCCOTAS_PGTO
ACTIVE AFTER DELETE POSITION 0
AS 
  DECLARE VARIABLE wsql varchar(1000);
begin
  wsql = 'delete from EMPRESAS_TSOCCOTAS_PGTO x where x.bdcodemp = '||OLD.bdcodemp||' and x.bdordem = '||OLD.bdordem;
  wsql = wsql||' and x.bdcodsoc = '||old.bdcodsoc||' and x.bdrefcota = '||old.bdrefcota;
  EXECUTE STATEMENT wsql;

  wsql = 'update EMPRESAS_TSOCCOTAS set bdcompenvio = null, bdcodrec = null ';
  wsql = wsql||' where (not exists (select 1 from EMPRESAS_TSOCCOTAS_PGTO x where x.bdcodemp = '||OLD.bdcodemp||' and x.BDCODSOC = '||old.bdcodsoc||' and x.BDREFCOTA = '||old.bdrefcota||')) and ';
  wsql = wsql||' BDCODEMP = '||OLD.bdcodemp||' and BDCODSOC = '||old.bdcodsoc||' and BDREFCOTA = '||old.bdrefcota;
  EXECUTE STATEMENT wsql;

  wsql = 'update EMPRESAS_TSOCCOTAS set BDVALORDISTRIBLUCRO = (select sum(BDVALOR) from EMPRESAS_TSOCCOTAS_PGTO';
  wsql = wsql||' where BDCODEMP = '||OLD.bdcodemp||' and BDCODSOC = '||old.bdcodsoc||' and BDREFCOTA = '||old.bdrefcota||'),';

  wsql = wsql||' BDBASECALCULOIRRF= (select sum(BDBASECALCULOIRRF) from EMPRESAS_TSOCCOTAS_PGTO';
  wsql = wsql||' where BDCODEMP = '||OLD.bdcodemp||' and BDCODSOC = '||old.bdcodsoc||' and BDREFCOTA = '||old.bdrefcota||'),';
  
  wsql = wsql||' BDVALORIRRETIDO = (select sum(BDVALORIRRETIDO) from EMPRESAS_TSOCCOTAS_PGTO';
  wsql = wsql||' where BDCODEMP = '||OLD.bdcodemp||' and BDCODSOC = '||old.bdcodsoc||' and BDREFCOTA = '||old.bdrefcota||'),';

  wsql = wsql||' BDVALORCONVENIO = (select sum(BDCONVENIO) from EMPRESAS_TSOCCOTAS_PGTO';
  wsql = wsql||' where BDCODEMP = '||OLD.bdcodemp||' and BDCODSOC = '||old.bdcodsoc||' and BDREFCOTA = '||old.bdrefcota||')';
  wsql = wsql||' where BDCODEMP = '||OLD.bdcodemp||' and BDCODSOC = '||old.bdcodsoc||' and BDREFCOTA = '||old.bdrefcota;
  EXECUTE STATEMENT wsql;
end^

CREATE OR ALTER TRIGGER TTIPOPROCESSOSAUTOMATIZADOS_BI0 FOR TTIPOPROCESSOSAUTOMATIZADOS
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (coalesce(new.bdcodigo, 0) <= 0) then
     begin
       select coalesce(max(BDCODIGO), 0) + 1 from TTIPOPROCESSOSAUTOMATIZADOS into new.bdcodigo;
     end
end
^

CREATE OR ALTER TRIGGER TPROCESSOSAUTOMATIZADOS_BI0 FOR TPROCESSOSAUTOMATIZADOS
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (coalesce(new.bdcodigo, 0) < 0) then
     select coalesce(max(BDCODIGO), 0) + 1 from TPROCESSOSAUTOMATIZADOS into new.bdcodigo;
end
^

create or alter procedure VRH_SP_CONF_VER_REEMBOLSO
returns (
    BDCODEMP integer,
    BDOBS varchar(200),
    BDNOMEMP DM_BDNOMEMP,
    bdverbareembolsotitular integer,
    bdverbareembolsotitularrra integer,
    bdverbareembolsodependente integer,
    bdverbareembolsodependenterra integer,
    bddescverbatitular  varchar(200),
    bddescverbadep  varchar(200),
    bddescverbatitularrra  varchar(200),
    bddescverbadeprra  varchar(200)
                         )
as
declare variable WSQL varchar(3000);
declare variable WConta integer;
begin
  /* Procedure Text */
  wsql = ' select PD.BDCODEMP '||
         ' from VRHF_EMP_TCONFVERBAS_REEMBOLSO PD '||
         ' where PD.BDCODEMP = 0 '||
         ' union all '||
         ' select empx.bdcodemp '||
         ' from tempresas empx ';

  for execute statement wsql into bdcodemp do
    begin
      bdverbareembolsotitular = null;
      bdverbareembolsotitularrra = null;
      bdverbareembolsodependente = null;
      bdverbareembolsodependenterra = null;
      WConta = 0;

      select first 1 1, x.bdverbareembolsotitular,
                     x.bdverbareembolsotitularrra,
                     x.bdverbareembolsodependente,
                     x.bdverbareembolsodependenterra
      from VRHF_EMP_TCONFVERBAS_REEMBOLSO x where x.bdcodemp = :bdcodemp
      into WConta, bdverbareembolsotitular, bdverbareembolsotitularrra, bdverbareembolsodependente, bdverbareembolsodependenterra;

      if (bdcodemp = 0) then
         bdobs = 'Configuração padrão';
      else if (wconta = 0) then
         bdobs = 'Utiliza configuração padrão';
      else
         bdobs = 'Utiliza configuração própria';

      if (bdcodemp = 0) then
         bdnomemp = 'Configuração padrão';
      else
         begin
           select first 1 X.bdnomemp
           from TEMPRESAs_ref x where x.bdcodemp = :bdcodemp order by x.bdrefemp desc into :bdnomemp;
         end

      bddescverbatitular = null;
      bddescverbadep = null;
      bddescverbatitularrra = null;
      bddescverbadeprra = null;

      if (bdverbareembolsotitular is not null) then
         begin
           select v.bddescver from vrh_base_tverbas v
           where v.bdcodver = :bdverbareembolsotitular into :bddescverbatitular;
         end

      if (bdverbareembolsotitularrra is not null) then
         begin
           select v.bddescver from vrh_base_tverbas v
           where v.bdcodver = :bdverbareembolsotitularrra into :bddescverbatitularrra;
         end

      if (bdverbareembolsodependente is not null) then
         begin
           select v.bddescver from vrh_base_tverbas v
           where v.bdcodver = :bdverbareembolsodependente into :bddescverbadep;
         end

      if (bdverbareembolsodependenterra is not null) then
         begin
           select v.bddescver from vrh_base_tverbas v
           where v.bdcodver = :bdverbareembolsodependenterra into :bddescverbadeprra;
         end

      suspend;
    end
end^

CREATE OR ALTER TRIGGER VSH_BASE_EMP_TEXECMANUAL_BI0 FOR VSH_BASE_EMP_TEXECMANUAL
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE wCod INTEGER;
BEGIN
  SELECT COALESCE(MAX(BDORDEMEMP), 0)
  FROM VSH_BASE_EMP_TEXECMANUAL
  WHERE BDCODLISTAEMPMANUAL = NEW.BDCODLISTAEMPMANUAL
  INTO :wCod;
  NEW.BDORDEMEMP = wCod + 1;
END^

CREATE OR ALTER TRIGGER VRH_BASE_CAMPO_TTABELA_BI0 FOR VRH_BASE_CAMPO_TTABELA
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (new.bdcodtabela is null) then
     new.bdcodtabela = coalesce((select first 1 bdcodtabela from vrh_base_campo_ttabela order by bdcodtabela desc)+1, 1);
end
^

CREATE OR ALTER procedure SP_PROCESSO_AUMENTO_SAL (
    PRCODEMP varchar(30000) not null,
    PRCODCOL varchar(30000) not null,
    PRREFEF integer,
    PRULTDIA varchar(12),
    PRDATAEFEITO varchar(12),
    PRCODSIND varchar(2000),
    PRCODCLA varchar(2000),
    PRCODFUC varchar(2000))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDSALBASECOL numeric(18,6),
    BDCALCFCNAFNEMP varchar(5),
    BDCODSINTRAB integer,
    BDCODCLA integer,
    BDCODTFUC integer,
    BDDATAADMCOL date)
as
declare variable WSQL varchar(32000);
declare variable WSQL2 varchar(32000);
declare variable WWHERE varchar(32000);
declare variable WCODCOL integer;
declare variable WCODEMP integer;
declare variable WCALCFCNAFNEMP boolean;
declare variable WCODSINTRAB integer;
declare variable WCODCLA integer;
declare variable WCODTFUC integer;
declare variable WDATAADMCOL date;
declare variable WJOINCOL varchar(300);
BEGIN
  
  wwhere = '';
  wJOINCOL = '';

  if (trim(:prcodcol) = 'TEMP_FILTRO_COLCON_REL') then
    wJOINCOL = ' join TEMP_FILTRO_COLCON_REL FCOL on FCOL.BDCODEMP = COLCON.BDCODEMP and FCOL.BDCODCOL = COLCON.BDCODCOL ';

  if ((:prcodemp is not null) and (:prcodemp <> '''') and (:prcodemp <> '')) then
     begin
       wwhere = ' where '||prcodemp;

       
       if ((:prcodcol is not null) and (:prcodcol <> '''') and (:prcodcol <> '') and wJOINCOL = '') then
          wwhere = wwhere||' and '||prcodcol;
     end

  if ((:prcodsind is not null) and (:prcodsind <> '''') and (:prcodsind <> '')) then
     begin
       if (wwhere = '') then
          wwhere = ' where ';
       else
          wwhere = wwhere||' and ';

       wwhere = wwhere||prcodsind;
     end

  if ((:prcodcla is not null) and (:prcodcla <> '''') and (:prcodcla <> '')) then
     begin
       if (wwhere = '') then
          wwhere = ' where ';
       else
          wwhere = wwhere||' and ';
       wwhere = wwhere||prcodcla;
     end

  if ((:prcodfuc is not null) and (:prcodfuc <> '''') and (:prcodfuc <> '')) then
     begin
       if (wwhere = '') then
          wwhere = ' where ';
       else
         wwhere = wwhere||' and ';
       wwhere = wwhere||prcodfuc;
     end

  wsql2 = 'select COLCON.BDCODEMP, COLCON.BDCODCOL, EMPPAR.BDCALCFCNAFNEMP, COLVINC.BDCODSINTRAB, '||
                 'COLCONVINC.BDCODCLA, COLVINCDIA.BDCODTFUC, COLCON.BDDATAADMCOL '||
          'from VRH_EMP_TCOLCON COLCON '||
          wJOINCOL||
          'join (select BASE.BDCODEMP, REF.BDCALCFCNAFNEMP '||
                     'from (select X.BDCODEMP, coalesce((select max(D2.BDREFEMP) '||
                                                        'from VRHF_BASE_TEMPPAR D2 '||
                                                        'where D2.BDCODEMP = X.BDCODEMP and '||
                                                              'D2.BDREFEMP <= '||:prrefef||'), '||
                                                       '(select min(D1.BDREFEMP) '||
                                                        'from VRHF_BASE_TEMPPAR D1 '||
                                                        'where D1.BDCODEMP = X.BDCODEMP)) as BDREFEMP '||
                           'from TEMPRESAS X '||
                           'where ((X.BDEXCLUIREMP is null) or (upper(X.BDEXCLUIREMP) <> ''TRUE''))) as BASE, VRHF_BASE_TEMPPAR REF '||
                'where BASE.BDCODEMP = REF.BDCODEMP and '||
                      'BASE.BDREFEMP = REF.BDREFEMP) EMPPAR on (EMPPAR.BDCODEMP = COLCON.BDCODEMP) '||
          'left outer join (select BASE.BDCODEMP, BASE.BDCODCOL, VIN.BDCODSINTRAB '||
                           'from (select COL.BDCODEMP, COL.BDCODCOL, coalesce((select max(D1.BDREFCOL) '||
                                                                              'from VRH_EMP_TCOL_VINC D1 '||
                                                                              'where D1.BDCODEMP = COL.BDCODEMP and '||
                                                                                    'D1.BDCODCOL = COL.BDCODCOL and '||
                                                                                    'D1.BDREFCOL <= '||:prrefef||'), '||
                                                                             '(select min(D2.BDREFCOL) '||
                                                                              'from VRH_EMP_TCOL_VINC D2 '||
                                                                              'where D2.BDCODEMP = COL.BDCODEMP and '||
                                                                                    'D2.BDCODCOL = COL.BDCODCOL)) as BDREFCOL '||
                                 'from VRH_EMP_TCOLCON COL) as BASE, VRH_EMP_TCOL_VINC VIN '||
                           'where BASE.BDCODEMP = VIN.BDCODEMP and '||
                                 'BASE.BDCODCOL = VIN.BDCODCOL and '||
                                 'BASE.BDREFCOL = VIN.BDREFCOL) COLVINC on (COLVINC.BDCODEMP = COLCON.BDCODEMP and COLVINC.BDCODCOL = COLCON.BDCODCOL) '||
          'join (select BASE.BDCODEMP, BASE.BDCODCOL, V.BDCODCLA '||
                'from (select X.BDCODEMP, X.BDCODCOL, coalesce((select max(D2.BDREFCOL) '||
                                                               'from VRH_EMP_TCOLCON_VINC D2 '||
                                                               'where D2.BDCODEMP = X.BDCODEMP and '||
                                                                     'D2.BDCODCOL = X.BDCODCOL and '||
                                                                     'D2.BDREFCOL <= '||:prrefef||'), '||
                                                              '(select min(D1.BDREFCOL) '||
                                                               'from VRH_EMP_TCOLCON_VINC D1 '||
                                                               'where D1.BDCODEMP = X.BDCODEMP and '||
                                                                     'D1.BDCODCOL = X.BDCODCOL)) as BDREFCOL '||
                      'from VRH_EMP_TCOLCON X) as BASE, VRH_EMP_TCOLCON_VINC V '||
                'where BASE.BDCODEMP = V.BDCODEMP and '||
                      'BASE.BDCODCOL = V.BDCODCOL and '||
                      'BASE.BDREFCOL = V.BDREFCOL) COLCONVINC on (COLCONVINC.BDCODEMP = COLCON.BDCODEMP and COLCONVINC.BDCODCOL = COLCON.BDCODCOL) '||
          'left outer join (select BASE.BDCODEMP, BASE.BDCODCOL, BASE.BDDATACOL, VIN.BDCODTFUC '||
                           'from (select COL.BDCODEMP, COL.BDCODCOL, coalesce((select max(D1.BDDATACOL) '||
                                                                              'from VRH_EMP_TCOL_VINCDIA D1 '||
                                                                              'where D1.BDCODEMP = COL.BDCODEMP and '||
                                                                                    'D1.BDCODCOL = COL.BDCODCOL and '||
                                                                                    'D1.BDDATACOL <= '''||:prultdia||'''), '||
                                                                             '(select min(D2.BDDATACOL) '||
                                                                              'from VRH_EMP_TCOL_VINCDIA D2 '||
                                                                              'where D2.BDCODEMP = COL.BDCODEMP and '||
                                                                                    'D2.BDCODCOL = COL.BDCODCOL)) as BDDATACOL '||
                                 'from VRH_EMP_TCOLCON COL) as BASE, VRH_EMP_TCOL_VINCDIA VIN '||
                           'where BASE.BDCODEMP = VIN.BDCODEMP and '||
                                 'BASE.BDCODCOL = VIN.BDCODCOL and '||
                                 'BASE.BDDATACOL = VIN.BDDATACOL) COLVINCDIA on (COLVINCDIA.BDCODEMP = COLCON.BDCODEMP and COLVINCDIA.BDCODCOL = COLCON.BDCODCOL) '||
     wwhere||
     ' order by COLCON.bdcodemp, COLCON.BDCODCOL';

  for execute statement wsql2 into wcodemp, wcodcol, wcalcfcnafnemp, wcodsintrab, wcodcla, wcodtfuc, wdataadmcol do
    begin
      wwhere = ' where CALCDIA.BDCODEMP = '||wcodemp||' and '||
                      'CALCDIA.BDCODCOL = '||wcodcol||' and '||
                      'CALCDIA.BDDATAEFEITO <= '''||prdataefeito||'''';

      WSQL = 'select first 1 CALCDIA.BDSALBASECOL from VRH_EMP_TCOLCON_CALCDIA CALCDIA '||
             wwhere||
             ' order by CALCDIA.BDDATACOL desc, CALCDIA.BDDATAEFEITO desc, CALCDIA.BDSALBASECOL desc ';

      EXECUTE STATEMENT WSQL INTO :BDSALBASECOL;

      :BDCODEMP = wcodemp;
      :BDCODCOL = wcodcol;
      :BDCALCFCNAFNEMP = wcalcfcnafnemp;
      :BDCODSINTRAB = wcodsintrab;
      :BDCODCLA = wcodcla;
      :BDCODTFUC = wcodtfuc;
      :BDDATAADMCOL = wdataadmcol;

      SUSPEND;

    end
END^

/* Restore proc. body: SP_VRH_SIT_MES_INT */
create or alter procedure SP_VRH_SIT_MES_INT (
    PRCODEMP integer,
    PRCOMPETENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer)
as
declare variable WSQL varchar(10000);
declare variable WPRIDIA date;
declare variable WULTDIA date;
declare variable WDIA integer;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WEMPATU integer;
declare variable WCOLATU integer;
declare variable WDIASSIT integer;
declare variable WDTINI date;
declare variable WDTFIM date;
begin
  wpridia = cast((substring(cast(prcompetencia as VARCHAR(6)) from 1 for 4)||'-'||substring(cast(prcompetencia as VARCHAR(6)) from 5 for 2)||'-01') as DATE);

  select first 1 ULTDIA from ULTIMO_DIA_MES(cast((substring(cast(:prcompetencia as VARCHAR(6)) from 5 for 2)) as SMALLINT), CAST((substring(cast(:prcompetencia as VARCHAR(6)) from 1 for 4)) as INTEGER)) into :wdia;

  wultdia = cast((substring(cast(prcompetencia as VARCHAR(6)) from 1 for 4)||'-'||substring(cast(prcompetencia as VARCHAR(6)) from 5 for 2)||'-'||lpad(trim(cast(wdia as varchar(2))), 2, '0')) as DATE);

  wsql = 'select BDCODEMP, BDCODCOL, BDDATAINISIT, BDDATAFIMSIT '||
         'from VRH_EMP_TSITCOL '||
         'where BDDATAINISIT <= '''||cast(wultdia as varchar(10))||''' and '||
            '((BDDATAFIMSIT is null) or (BDDATAFIMSIT >= '''||cast(wpridia as varchar(10))||''')) ';

  if (coalesce(prcodemp, 0) > 0) then
     wsql = wsql||' and BDCODEMP = '||prcodemp||' ';

  wsql = wsql||'order by BDCODEMP,BDCODCOL,BDDATAINISIT';


  wempatu = 0;
  wcolatu = 0;
  wdiassit = 0;

  for execute statement wsql
  into :wcodemp, :wcodcol, :wdtini, :wdtfim
  do
    begin
      if (wempatu = 0) then
         wempatu = wcodemp;

      if (wcolatu = 0) then
         wcolatu = wcodcol;

      if ((wempatu <> wcodemp) or (wcolatu <> wcodcol)) then
         begin
           if (wdiassit >= wdia) then
              begin
                BDCODEMP = wempatu;
                BDCODCOL = wcolatu;
                suspend;
              end

           wempatu = wcodemp;
           wcolatu = wcodcol;
           wdiassit = 0;
         end


      if (wdtini < wpridia) then
         wdtini = wpridia;

      if ((wdtfim is null) or (wdtfim > wultdia)) then
         wdtfim = wultdia;

      wdiassit = wdiassit + (wdtfim - wdtini + 1);
    end


  if (wempatu > 0 and wcolatu > 0) then
     begin
       if (wdiassit >= wdia) then
          begin
            BDCODEMP = wempatu;
            BDCODCOL = wcolatu;
            suspend;
          end
     end
end^


create or alter procedure SP_RECLAMATORIA_CONV (
    PRCODEMP integer,
    PRCHAVE integer)
returns (
    BDCODEMP integer,
    BDCHAVE integer,
    BDCODVINC integer,
    BDDATASERV date,
    BDHORASTRAB time,
    BDCONSIDERAHORAS DM_BOOLEAN)
as
declare variable WREFATU integer;
declare variable WREFFIM integer;
declare variable WCLATRIB22 DM_BOOLEAN;
declare variable WREFATUAUX integer;
begin
  for select BDCODEMP, BDCHAVE, BDCODVINC, BDINIPROC, BDFIMPROC
      from VRH_EMP_TRECLAMATORIA_IDPGTO
      where BDCODEMP = :PRCODEMP and BDCHAVE = :PRCHAVE
      order by BDCODEMP, BDCHAVE, BDCODVINC, BDINIPROC
  into :BDCODEMP, :BDCHAVE, :BDCODVINC, :wrefatu, :wreffim
  do
    begin
      for select BDCODEMP, BDCHAVE, BDCODVINC, BDDATASERV, BDHORASTRAB
      from VRH_EMP_TRECLAMATORIA_CONV
      where BDCODEMP  = :BDCODEMP
        and BDCHAVE   = :BDCHAVE
        and BDCODVINC = :BDCODVINC
        and BDDATASERV between
        cast(substring(:wrefatu from 1 for 4) || '-' || substring(:wrefatu from 5 for 2) || '-01' as date)
        and
        DATEADD(-1 DAY TO DATEADD(1 MONTH TO cast(substring(:wreffim from 1 for 4) || '-' || substring(:wreffim from 5 for 2) || '-01' as date)))
      order by BDCODEMP, BDCHAVE, BDCODVINC, BDDATASERV
      into :BDCODEMP, :BDCHAVE, :BDCODVINC, :BDDATASERV, :BDHORASTRAB
      do
         begin
        if (WREFATUAUX IS NULL) then
          begin
            WREFATUAUX = 0;
          end

        if (WREFATUAUX <> WREFATU) then
          begin
            SELECT CASE WHEN SP.BDCODCLATRI = 22 THEN 'TRUE' ELSE 'FALSE' END CLATRIB22 FROM SP_VRHF_GETEMPRESA(:BDCODEMP,  :WREFATU) SP into :WCLATRIB22;
            WREFATUAUX = WREFATU;
          end

        :BDCONSIDERAHORAS = WCLATRIB22;
        suspend;
        end
    end
end^


CREATE OR ALTER TRIGGER VRH_EMP_TCOLCON_CALCDIA_BIU0 FOR VRH_EMP_TCOLCON_CALCDIA
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  if (new.bddataefeito is not null) then
     new.bdrefefeitocol = cast((substring(cast(new.bddataefeito as varchar(10)) from 1 for 4)||substring(cast(new.bddataefeito as varchar(10)) from 6 for 2)) as integer);
  else
     new.bdrefefeitocol = null;

  new.bdrefcol = cast((substring(cast(new.bddatacol as varchar(10)) from 1 for 4)||substring(cast(new.bddatacol as varchar(10)) from 6 for 2)) as integer);

end
^

create or alter procedure VRH_SP_GET_DATA_ULTIMA_ALTERACAO_CARGO(PRCODEMP integer, PRCODCOL integer, PRDATAMIN date, PRDATAMAX date) returns(BDCODEMP integer, BDCODCOL integer, BDDATAULTMOV date) as declare variable WSQL varchar(32700);
declare variable WCODTFUC integer;
declare variable WCODTFUC_ANT integer;
declare variable WDATAULTMOV date;
declare variable WDATACOL date;
begin
  WSQL = 'SELECT TCOL_VINCDIA.BDCODEMP, TCOL_VINCDIA.BDCODCOL, TCOL_VINCDIA.BDDATACOL, TCOL_VINCDIA.BDCODTFUC
          FROM VRH_EMP_TCOL_VINCDIA TCOL_VINCDIA
          WHERE
            TCOL_VINCDIA.BDCODEMP = ' || PRCODEMP || ' AND
            TCOL_VINCDIA.BDCODCOL = ' || PRCODCOL;
  if (PRDATAMIN <> '12/30/1899') then
    WSQL = WSQL || ' AND TCOL_VINCDIA.BDDATACOL >= ''' || PRDATAMIN || ''' ';
  if (PRDATAMAX <> '12/30/1899') then
    WSQL = WSQL || ' AND TCOL_VINCDIA.BDDATACOL <= ''' || PRDATAMAX || ''' ';

  WSQL = WSQL || ' ORDER BY TCOL_VINCDIA.BDDATACOL';

  WCODTFUC_ANT = 0;
  for execute statement WSQL
          into :BDCODEMP, :BDCODCOL, :WDATACOL, :WCODTFUC
  do
    if (WCODTFUC_ANT <> WCODTFUC) then
    begin
      WDATAULTMOV = WDATACOL;
      WCODTFUC_ANT = WCODTFUC;
    end

  BDDATAULTMOV = WDATAULTMOV;

  suspend;
end^

CREATE OR ALTER TRIGGER VRHF_EMP_TFIPENSAO_DEP_AIU0 FOR VRHF_EMP_TFIPENSAO_DEP
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
declare variable WTOTALPENSAODEP numeric(18,6);
begin
  /* Trigger text */
  IF (COALESCE(NEW.BDFICHA, FALSE) = FALSE) THEN
     BEGIN
        WTOTALPENSAODEP = 0;
        SELECT SUM(BDVALPEND)
        FROM VRHF_EMP_TFIPENSAO_DEP
        WHERE BDCODEMP = NEW.BDCODEMP AND
              BDCODCOL = NEW.BDCODCOL AND
              BDCOMPPEND = NEW.BDCOMPPEND AND
              BDTIPOPEND = NEW.BDTIPOPEND AND
              BDCODFIR = NEW.BDCODFIR
        INTO :WTOTALPENSAODEP;

        UPDATE VRHF_EMP_TFICHAIRRF SET BDPENALIMFIR = :WTOTALPENSAODEP
        WHERE BDCODEMP = NEW.BDCODEMP AND
              BDCODCOL = NEW.BDCODCOL AND
              BDCODFIR = NEW.BDCODFIR;
     END
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFIPENSAO_DEP_BIU0 FOR VRHF_EMP_TFIPENSAO_DEP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  /* Trigger text */

  IF (NEW.BDFICHA IS NULL) THEN
     NEW.BDFICHA = TRUE;
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TCONVSAUDE_BIU0 FOR VRH_BASE_TCONVSAUDE
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  /* Trigger text */

  if ((char_length(new.bdcodconvenio))>6) then
     begin
       exception ex_custom 'Não é possível fazer um cadastro com o código com mais de 6 digitos.';
     end
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TRECLAMATORIA_CONV_BI0 FOR VRH_EMP_TRECLAMATORIA_CONV
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE WCHAVE INTEGER;
BEGIN
  IF (COALESCE(NEW.BDCHAVE, 0) <= 0) THEN
     BEGIN
       SELECT COALESCE(MAX(BDCHAVE), 1) FROM VRH_EMP_TRECLAMATORIA WHERE BDCODEMP = NEW.BDCODEMP INTO :WCHAVE;
       NEW.BDCHAVE = :WCHAVE;
     END

  IF (COALESCE(NEW.BDCODVINC,0) <= 0) THEN
     BEGIN
       SELECT FIRST 1 X.BDCODVINC FROM VRH_EMP_TRECLAMATORIA_VINC X
       WHERE X.BDCODEMP = NEW.BDCODEMP AND X.BDCHAVE = NEW.BDCHAVE ORDER BY X.BDCODVINC DESC INTO WCHAVE;
       NEW.BDCODVINC = :WCHAVE;
     END
END^


CREATE OR ALTER TRIGGER VRHF_EMP_TFICHAIRRF_AI0 FOR VRHF_EMP_TFICHAIRRF
ACTIVE AFTER INSERT POSITION 0
AS
  DECLARE VARIABLE vcount INTEGER;
  DECLARE VARIABLE vi INTEGER;
  DECLARE VARIABLE vben INTEGER;
  DECLARE VARIABLE vtot NUMERIC(18, 6);
  DECLARE VARIABLE wtipoCalculo INTEGER;
  DECLARE VARIABLE WPOSSUITODOSPERCENTUAIS INTEGER;
  DECLARE VARIABLE WPERCDEP NUMERIC(18,2);
  DECLARE VARIABLE WPERCDEPTOTAL NUMERIC(18,2);
  DECLARE VARIABLE WVALORPENSAO NUMERIC(18,2);
begin
  /* Trigger text */
  IF (NEW.bdtipocalcfir >= 9000 AND NEW.bdpenalimfir > 0) THEN
     BEGIN
       DELETE FROM VRHF_EMP_TFIPENSAO_DEP WHERE BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol AND BDCOMPPEND = NEW.bdreffir and BDCODFIR = NEW.BDCODFIR;
       SELECT COUNT(*) FROM VRH_EMP_TCOLCON_BENEF WHERE BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol INTO :vcount;
       vi = 1;
       vtot = 0;

       if (NEW.bdtipocalcfir = 9000) then           -- Folha normal IMPORTACAO
          wtipocalculo = 1;                        -- Folha normal
       else
       if ((NEW.bdtipocalcfir = 9001) or (NEW.bdtipocalcfir = 9002)             -- Folha normal rescisão IMPORTACAO
           or (NEW.bdtipocalcfir = 9011) or (NEW.bdtipocalcfir = 9012))  then   -- Folha complementar rescisão IMPORTACAO
          wtipocalculo = 9;                         -- Rescisão
       else if (NEW.bdtipocalcfir = 9010) then      -- Folha complementar IMPORTACAO
          wtipocalculo = 8;                         -- Folha complementar
       else if (NEW.bdtipocalcfir = 9020) then      -- Ad. Sal. IMPORTACAO
          wtipocalculo = 2;                         -- Ad. Sal.
       else if (NEW.bdtipocalcfir = 9030) then      -- Férias IMPORTACAO
          wtipocalculo = 6;                         -- Férias
       else if (NEW.bdtipocalcfir = 9099) then      -- Ad. 13 IMPORTACAO
          wtipocalculo = 3;                         -- Ad. 13
       else if (NEW.bdtipocalcfir = 9100) then      -- 13 IMPORTACAO
          wtipocalculo = 4;                         -- 13
       else if (NEW.bdtipocalcfir = 9110) then      -- Comp. 13 IMPORTACAO
          wtipocalculo = 5;                         -- Comp. 13
       else if (NEW.bdtipocalcfir = 9500) then      -- Folha avulsa IMPORTACAO
          wtipocalculo = 7;                         -- Folha avulsa

       WPOSSUITODOSPERCENTUAIS = 0;
       SELECT COUNT(*), SUM(BDPERCDEPP) FROM VRH_EMP_TDEP_PENSAO
       WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL AND BDCODCTP = :wtipocalculo AND
             (BDREFDEPP <= NEW.BDREFFIR AND ((COALESCE(BDREFFIMDEPP, 0) = 0) or (BDREFFIMDEPP >= NEW.BDREFFIR))) AND
             COALESCE(BDPERCDEPP, 0) > 0
       INTO :WPOSSUITODOSPERCENTUAIS, :WPERCDEPTOTAL;

       FOR SELECT BDCODBENEF FROM VRH_EMP_TCOLCON_BENEF WHERE BDCODEMP = NEW.bdcodemp AND BDCODCOL = NEW.bdcodcol INTO :vben DO
       BEGIN
         IF (WPOSSUITODOSPERCENTUAIS = vcount) THEN
            BEGIN
              SELECT BDPERCDEPP FROM VRH_EMP_TDEP_PENSAO
              WHERE BDCODEMP = NEW.BDCODEMP AND BDCODCOL = NEW.BDCODCOL AND BDCODDPN = :VBEN AND BDCODCTP = :wtipocalculo AND
                    (BDREFDEPP <= NEW.BDREFFIR AND ((COALESCE(BDREFFIMDEPP, 0) = 0) or (BDREFFIMDEPP >= NEW.BDREFFIR))) AND
             COALESCE(BDPERCDEPP, 0) > 0
              INTO :WPERCDEP;

              IF (vi = vcount) THEN
                UPDATE OR INSERT  INTO VRHF_EMP_TFIPENSAO_DEP (BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDREFPAGPEND,BDREFPEND,BDREFAUXPEND,BDVALPEND,BDTIPOPEND,BDCODFIR,BDFICHA)
                VALUES (NEW.bdcodemp, NEW.bdcodcol, :vben, NEW.bdreffir, NEW.bdrefirfir, 0, 0, NEW.bdpenalimfir - :vtot, NEW.bdtipocalcfir, NEW.BDCODFIR, TRUE)
                MATCHING(BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDTIPOPEND,BDCODFIR);
              ELSE
                BEGIN
                  WVALORPENSAO = (NEW.bdpenalimfir * (:wpercdep / 100)) / (:wpercdeptotal / 100);

                  vtot = vtot + WVALORPENSAO;
                  UPDATE OR INSERT  INTO VRHF_EMP_TFIPENSAO_DEP (BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDREFPAGPEND,BDREFPEND,BDREFAUXPEND,BDVALPEND,BDTIPOPEND,BDCODFIR,BDFICHA)
                  VALUES (NEW.bdcodemp, NEW.bdcodcol, :vben, NEW.bdreffir, NEW.bdrefirfir, 0, 0, :WVALORPENSAO, NEW.bdtipocalcfir, NEW.BDCODFIR, TRUE)
                  MATCHING(BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDTIPOPEND,BDCODFIR);
                END
            END
         ELSE
         IF (vi = vcount) THEN
            UPDATE OR INSERT  INTO VRHF_EMP_TFIPENSAO_DEP (BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDREFPAGPEND,BDREFPEND,BDREFAUXPEND,BDVALPEND,BDTIPOPEND,BDCODFIR,BDFICHA)
            VALUES (NEW.bdcodemp, NEW.bdcodcol, :vben, NEW.bdreffir, NEW.bdrefirfir, 0, 0, NEW.bdpenalimfir - :vtot, NEW.bdtipocalcfir, NEW.BDCODFIR, TRUE)
            MATCHING(BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDTIPOPEND,BDCODFIR);
         ELSE
            BEGIN
              vtot = vtot + NEW.bdpenalimfir / :vcount;
              UPDATE OR INSERT  INTO VRHF_EMP_TFIPENSAO_DEP (BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDREFPAGPEND,BDREFPEND,BDREFAUXPEND,BDVALPEND,BDTIPOPEND,BDCODFIR,BDFICHA)
              VALUES (NEW.bdcodemp, NEW.bdcodcol, :vben, NEW.bdreffir, NEW.bdrefirfir, 0, 0, NEW.bdpenalimfir / :vcount, NEW.bdtipocalcfir, NEW.BDCODFIR, TRUE)
              MATCHING(BDCODEMP,BDCODCOL,BDCODBENEF,BDCOMPPEND,BDTIPOPEND,BDCODFIR);
            END
       END
     END
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TCOLCON_FGTSGPS_BIU0 FOR VRHF_EMP_TCOLCON_FGTSGPS
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
declare variable wcatsefip INTEGER;
begin
  if (new.bdcategoriacol is null and new.bdcategoriaesocial is not null) then
     begin
       wcatsefip = null;
       select first 1 BDCATEGORIACOL from VRH_ESOCIAL_TCATEGORIA where BDCODIGO = new.bdcategoriaesocial into :wcatsefip;
       new.bdcategoriacol = :wcatsefip;
     end
end
^

CREATE OR ALTER TRIGGER TMP_VEF_EMP_TMOVEXP_TEMP_BU0 FOR TMP_VEF_EMP_TMOVEXP_TEMP
ACTIVE BEFORE UPDATE POSITION 0
AS
BEGIN
  IF ((OLD.BDEDITCHAVE IS NULL) AND (NEW.BDEDITCHAVE > 0)) THEN
    BEGIN
      NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - OLD.BDCHAVE)+1;

      UPDATE TMP_VEF_EMP_TMOVEXPNFSAI_TEMP E
      SET E.bdEDITCHAVE = NEW.BDEDITCHAVE
      WHERE E.bdSESSAO = NEW.bdSESSAO
        AND E.bdCODEMP = NEW.bdCODEMP
        AND E.bdCHAVE  = NEW.BDCHAVE;
    END
END^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TGIAMGGER_070OCOMG_AD0 FOR TOL_VEF_EMP_TGIAMGGER_070OCOMG
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  DELETE FROM VEF_EMP_TOCOMG070 WHERE BDCODEMP = OLD.BDCODEMP AND BDCHAVE = OLD.BDCHAVE070OCO AND BDCODTPOCO = OLD.BDCODTPOCO;
END^

CREATE OR ALTER TRIGGER TMP_VEF_EMP_TMOVEXPNFSAI_TEMP_AU0 FOR TMP_VEF_EMP_TMOVEXPNFSAI_TEMP
ACTIVE AFTER UPDATE POSITION 0
AS
begin
  UPDATE TMP_VEF_EMP_TMOVEXPINDIRETA_TEMP E
  SET E.bdEDITCHAVE = NEW.BDEDITCHAVE
  WHERE E.bdSESSAO = NEW.bdSESSAO
    AND E.bdCODEMP = NEW.bdCODEMP
    AND E.bdCHAVE  = NEW.BDCHAVE
    AND E.BDORDEM  = NEW.BDORDEM;
end
^

CREATE OR ALTER procedure SP_CRIA_INCONF_S1010 (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCODEVT integer,
    PRTIPOEVT integer,
    PRREFEVT integer,
    PRCODVER integer)
as
declare variable WSQL varchar(5000);
declare variable WMSG varchar(380);
declare variable WSIGLA varchar(6);
declare variable WACAO varchar(200);
declare variable WCODCOL integer;
declare variable WCODTER integer;
declare variable WCODCOLAUX integer;
declare variable WCODUSU integer;
declare variable WEVTEXCLUIDO integer;
declare variable WTIPOEVT integer;
declare variable WSQLAUX varchar(5000);
declare variable WCHAVECAD varchar(40);
declare variable WREFSTR varchar(10);
declare variable WCAMPOCOL varchar(8);
declare variable WDESCVER varchar(40);
begin
  if (prtipoevt = 3) then
     begin
        -- Ao processar o S-1010, deve gerar inconformidade para os eventos S-1200/2299/2399 que já estão processados que tenham essa verba
        wsql = 'select DEM.BDTIPOEVT, DEM.BDCODCOL, DEM.BDCODAUT, TVER.BDDESCVER from VRH_ESOCIAL_DEMONS_EVT DEM '||
               'join VRH_ESOCIAL_RUBRICAS_EVT VER on (VER.BDCODEMP = DEM.BDCODEMP and VER.BDCODEVT = DEM.BDCODEVT and VER.BDSEQUENCIAL = DEM.BDSEQUENCIAL) '||
               'left outer join VRH_BASE_TVERBAS TVER on (TVER.BDCODVER = VER.BDCODVER) '||
               'where DEM.BDCODEMP = '||:PRCODEMP||' and '||
                     'DEM.BDREFEVT >= '||:PRREFEVT||' and '||
                     'DEM.BDSTATUS = 2 and '||
                     'VER.BDCODVER = '||:PRCODVER;

        wrefstr = substring(cast(prrefevt as varchar(6)) from 5 for 2)||'/'||substring(cast(prrefevt as varchar(6)) from 1 for 4);

        wmsg = 'Foi identificado no ambiente do eSocial um evento S-XXXX integrado para o #CODCOL# antes da retificação do S-1010 referente à verba "'||prcodver||'#DESCVER#" na competência '||wrefstr||'. Recomendamos a verificação do impacto dessa alteração no fechamento do eSocial.';
        wacao = 'Ação: Ressaltamos que a retificação do evento S-1010 pode influenciar os valores de impostos.' || ASCII_CHAR(13) || ASCII_CHAR(13) || ASCII_CHAR(10) ||
                'Assim, é essencial avaliar a necessidade de retificação do evento correspondente.';
      
        select bdcodusu FROM sp_get_usuario into :wcodusu;
      
        for execute statement wsql into :wtipoevt, :wcodcol, :wcodter, :wdescver do
          begin
            if (wtipoevt = 11) then
               wsigla = 'S-1200';
            else
            if (wtipoevt = 34) then
               wsigla = 'S-2299';
            else
               wsigla = 'S-2399';
      
            wmsg = replace(wmsg, 'S-XXXX', wsigla);
            wmsg = replace(wmsg, '#DESCVER#', ' - '||wdescver);

            if (wcodcol is not null) then
               wmsg = replace(wmsg, '#CODCOL#', 'colaborador '||wcodcol);
            else
               wmsg = replace(wmsg, '#CODCOL#', 'autônomo '||wcodter);

            if (wcodusu is null) then
               wcodusu = 1;

            wsqlaux = '';

            if (wcodcol is not null) then
               begin
                 wcampocol = 'BDCOLCON';
                 wsqlaux = 'select first 1 BDCODCOL from VRH_EMP_TCOLCON where bdcodemp = '||:prcodemp||' and bdcodcol = '||:wcodcol;
               end
            else if (wcodter is not null) then
               begin
                 wcampocol = 'BDCODTER';
                 wsqlaux = 'select first 1 SERV.BDCODTER from VRH_BASE_TSERVTERC SERV '||
                           'where SERV.BDCODTER = '||wcodter||' and '||
                                 'SERV.BDREFSERV = '||:prrefevt;
               end

            wcodcolaux = 0;
            if (wsqlaux <> '') then
               execute statement wsqlaux into wcodcolaux;

            if (wcodcolaux > 0) then
              begin
                wchavecad = prcodemp||'.'||wtipoevt||'.'||prcodevt;

            wsqlaux =  'insert into VRH_ESOCIAL_INCONFORMIDADES (BDCODEMP, BDEVENTO, BDCAMPO, BDCHAVE, BDDESCRICAO, BDTIPO, BDTITULO, '||
                                                                'BDCADASTRO, BDCHAVECAD, BDCAMINHO, BDREFINC, BDIGNORAINC, BDCODUSU, '||
                           'BDCODSIS, BDNUMEROINC, BDNOMEINC, '||wcampocol||', BDACAO, BDCODVER, '||
                                                                'BDCODSINDICATO, BDDATAINC) '||
                                                                'select '||:prcodemp||' BDCODEMP, '||:wtipoevt||' BDEVENTO, INC.BDCAMPO, cast(null as integer) BDCHAVE, '''||:wmsg||''' BDDESCRICAO, INC.BDTIPO, INC.BDTITULO, '||
                                                                '44 BDCADASTRO, '''||wchavecad||''' BDCHAVECAD, INC.BDCAMINHO, '||:prrefevt||' BDREFINC, cast(null as boolean) BDIGNORAINC, '||:wcodusu||' BDCODUSU, ' ||
                           '2 BDCODSIS, INC.BDCODINCONFINTER, ''Eventos periódicos'' BDNOMEINC, '||:wcodcolaux||' '||wcampocol||', '''||:wacao||''' BDACAO, '||:prcodver||' BDCODVER, ' ||
                                                                '0 BDCODSINDICATO, cast(current_date as date) BDDATAINC ' ||
                                                                'from VAUD_INTRANET_INCONFORMIDADE INC ' ||
                                                                'where INC.BDEVENTO = '||:wtipoevt||' and ' ||
                                                                      'INC.BDTIPO = 2 and ' ||
                                                                      'INC.BDTITULO = ''Fechamento divergente'' and '||
                                                                      'not exists(select 1 from VRH_ESOCIAL_INCONFORMIDADES I '||
                                                                                 'where I.BDCODEMP = '||:prcodemp||' and '||
                                                                                       'I.BDEVENTO = '||:wtipoevt||' and '||
                                                  'I.BDCODVER = '||:prcodver||' and '||
                                                                                       'I.BDCAMPO = INC.BDCAMPO and '||
                                                                                       'I.BDCHAVECAD = '''||wchavecad||''' and '||
                                                                                       'I.BDREFINC = '||:prrefevt||')';
            
               if ((wsqlaux <> '') and (wsqlaux is not null)) then
               execute statement wsqlaux;
          end
     end
     end
   else
   if (prtipoevt in (11, 34, 37)) then
      begin
         -- Aos processar os S-1200 / S-2299 / S-2399 deve limpar a tabela VRH_ESOCIAL_DEMONS_EVT os registro que não são do evento atual (empresa, referencia, tipo evento e codevt <> e status 2)
         -- Deve excluir as inconformidades referente a esse evento
         delete from VRH_ESOCIAL_DEMONS_EVT DEM
         where DEM.BDCODEMP  <> :PRCODEMP and
               (((DEM.BDCODCOL  =  :PRCODCOL) and (DEM.BDCODAUT is null)) or
               ((DEM.BDCODAUT  =  :PRCODCOL) and (DEM.BDCODCOL is null))) and
               DEM.BDREFEVT  <> :PRREFEVT and
               DEM.BDTIPOEVT <> :PRTIPOEVT and
               DEM.BDCODEVT  <> :PRCODEVT and
               DEM.BDSTATUS  =  2;

         delete from VRH_ESOCIAL_INCONFORMIDADES INC
         where INC.BDCODEMP = :PRCODEMP and
               (INC.BDCOLCON = :PRCODCOL or INC.BDCODTER = :PRCODCOL) and
               INC.BDEVENTO = :PRTIPOEVT and
               INC.BDREFINC = :PRREFEVT;
      end
   else
   if (prtipoevt = 38) then
      begin
         -- Aos processar o S-3000 dos eventos (S-1200 / S-2299 / S-2399) deve limpar a tabela VRH_ESOCIAL_DEMONS_EVT os registro que não são do evento atual (empresa, referencia, tipo evento e status 2)
         -- Deve excluir as inconformidades referente a esse evento
         wsql = 'select ARQ.BDEVTEXCLUIDO, ARQ.BDEVENTOEXCLUSAO from VRH_ESOCIAL_TARQUIVO ARQ '||
                'where ARQ.BDCODEMP = '||:PRCODEMP||' and '||
                      'ARQ.BDCODIGO = '||:PRCODEVT||' and '||
                      'ARQ.BDEVENTOEXCLUSAO in (11, 34, 37)';

         for execute statement wsql into :wevtexcluido, :wtipoevt do
           begin
             delete from VRH_ESOCIAL_DEMONS_EVT DEM
             where DEM.BDCODEMP  <> :PRCODEMP and
                   (((DEM.BDCODCOL  =  :PRCODCOL) and (DEM.BDCODAUT is null)) or
                   ((DEM.BDCODAUT  =  :PRCODCOL) and (DEM.BDCODCOL is null))) and
                   DEM.BDREFEVT  <> :PRREFEVT and
                   DEM.BDTIPOEVT <> :wtipoevt and
                   DEM.BDCODEVT  <> :wevtexcluido and
                   DEM.BDSTATUS  =  2;

             delete from VRH_ESOCIAL_INCONFORMIDADES INC
             where INC.BDCODEMP = :PRCODEMP and
                   (INC.BDCOLCON = :PRCODCOL or INC.BDCODTER = :PRCODCOL) and
                   INC.BDEVENTO = :wtipoevt and
                   INC.BDREFINC = :PRREFEVT;
           end
      end
end
^



CREATE OR ALTER VIEW VW_VRH_FUNCOES_TFUC_ATIVAS(
    BDCODEMP,
    BDCODPLAFUC,
    BDCODTFUC,
    BDDESCTFUC)
AS
    SELECT
        VINCPLAFUC.BDCODEMP,
        F.BDCODPLAFUC,
        F.BDCODTFUC,
        F.BDDESCTFUC
    FROM VRH_FUNCOES_TFUC F
    join vrh_base_tempvinc VINCPLAFUC on VINCPLAFUC.BDCODPLAFUC = F.BDCODPLAFUC
                                    AND  VINCPLAFUC.BDREFEMP =  (Select first 1 X.BDREFEMP from vrh_base_tempvinc  X
                                                                    WHERE X.BDCODEMP = VINCPLAFUC.BDCODEMP )
    AND F.BDCODTFUC IN  (SELECT DISTINCT PART.BDCODTFUC FROM VRH_EMP_TCOLCON COL
                        JOIN VRH_EMP_TCOLCON_PARTIDA PART ON COL.BDCODEMP = PART.BDCODEMP AND COL.BDCODCOL = PART.BDCODCOL
                        LEFT OUTER JOIN VRH_EMP_TRESCISAO RESC ON COL.BDCODEMP = RESC.BDCODEMP AND COL.BDCODCOL = RESC.BDCODCOL
                        WHERE COL.BDCODEMP = VINCPLAFUC.BDCODEMP
                        AND ((RESC.BDDATARESCISAO IS NULL) or (RESC.BDDATARESCISAO <= CURRENT_DATE - 365)) );
^

CREATE OR ALTER VIEW VW_TPAIS_NASC_ATIVOS(
    BDCODEMP,
    BDCODPAIS,
    BDDESCPAIS,
    BDNACIONALIDADE)
AS
SELECT DISTINCT
        COL.BDCODEMP,
        P.BDCODPAIS,
        P.BDDESCPAIS,
        P.BDNACIONALIDADE
    FROM TPAIS P
    JOIN VRH_EMP_TCOL_HIST  COL ON COL.BDCODPAISNAS = P.BDCODPAIS
    LEFT OUTER JOIN VRH_EMP_TRESCISAO RESC ON COL.BDCODEMP = RESC.BDCODEMP AND COL.BDCODCOL = RESC.BDCODCOL
    WHERE ((RESC.BDDATARESCISAO IS NULL) or (RESC.BDDATARESCISAO <= CURRENT_DATE - 365));
^

CREATE OR ALTER procedure SP_RETORNA_QTDECOLATIVOS (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer,
    PRFILIAIS boolean)
returns (
    BDREF integer,
    BDCODEMP integer,
    BDNOMEMP varchar(80),
    BDATIVOS integer,
    BDADMIT integer,
    BDTRANSF integer,
    BDREINT integer,
    BDTOTAL integer,
    BDMEDIA numeric(9,2),
    BDQTDEMES integer,
    BDMEDTOT numeric(9,2))
as
declare variable WSQL varchar(5000);
declare variable WATIVOS integer;
declare variable WADMIT integer;
declare variable WTRANSF integer;
declare variable WREINT integer;
declare variable WPRIDIA varchar(10);
declare variable WULTDIA varchar(10);
declare variable WREFATU integer;
declare variable WDIA integer;
declare variable WMES integer;
declare variable WANO integer;
declare variable WDIASTR varchar(2);
declare variable WQTDE integer;
declare variable WCODEMP integer;
declare variable WNOMEMP varchar(80);
declare variable WMATRIZ boolean;
declare variable WCODEMPATU integer;
declare variable WT_REF integer;
declare variable WT_ATIVOS integer;
declare variable WT_ADMIT integer;
declare variable WT_TRANSF integer;
declare variable WT_REINT integer;
declare variable WT_TOTAL integer;
declare variable WREFFIM integer;
begin
  -- Quantidade de colaboradores ativos no mês: Saldo inicial de ativos + admissões/transferência de entrada/reintegração do mês.
  -- Valida os cadastros com categoria eSocial que gera evento S-2200.
  wmatriz = exists(select 1 from TEMPRESAS where BDCODMATRIZ is not null and BDCODMATRIZ = :PRCODEMP);
  delete from TMP_RESUMO_TOTCOLATIVOS;

  if ((prreffim / 100) <> (prrefini / 100)) then
     WREFFIM = (((prrefini / 100) * 100) + 12);
  else
     WREFFIM = prreffim;

  for select EMP.BDCODEMP,
         case
           when ((:wmatriz) and (emp.bdcodmatriz is not null)) then 'Filial: '||EMP.bdcodemp||' - '||EMPREF.BDNOMEMP
           when ((:wmatriz) and (emp.bdcodmatriz is null)) then 'Matriz: '||EMP.bdcodemp||' - '||EMPREF.BDNOMEMP
           else EMP.bdcodemp||' - '||EMPREF.BDNOMEMP
         end as BDNOMEMP
      from TEMPRESAS EMP
      left outer join TEMPRESAS_REF EMPREF on (EMPREF.BDCODEMP = EMP.BDCODEMP and EMPREF.BDREFEMP = (select max(E.BDREFEMP) from TEMPRESAS_REF E
                                                                                                     where E.BDCODEMP = EMP.BDCODEMP and
                                                                                                           E.BDREFEMP <= :WREFFIM))
         where EMP.BDCODMATRIZ = :prcodemp or EMP.BDCODEMP = :prcodemp into :wcodemp, :wnomemp do
    begin
      wrefatu = prrefini;
      wativos = 0;
      wadmit  = 0;
      wtransf = 0;
      wreint  = 0;
      wqtde   = 0;
      bdativos = 0;
      bdadmit  = 0;
      bdtransf = 0;
      bdreint  = 0;
      bdmedia  = 0;
      bdmedtot = 0;

      while (wrefatu <= WREFFIM) do
        begin
          bdref    = wrefatu;
          wmes = (mod(wrefatu, 100));
          wano = (wrefatu / 100);
          select ULTDIA from ULTIMO_DIA_MES(:wmes, :wano) into :wdia;
          wdiastr = cast(wdia as varchar(2));
    
          wpridia = substring(cast(wrefatu as varchar(6)) from 5 for 2)||'/01/'||cast(wano as varchar(4));
          wultdia = substring(cast(wrefatu as varchar(6)) from 5 for 2)||'/'||wdiastr||'/'||cast(wano as varchar(4));
    
          wsql = 'select BDREF, BDCODEMP, sum(BDATIVOS) BDATIVOS, sum(BDADMITIDOS) BDADMITIDOS, sum(BDTRANSF) BDTRANSF, sum(BDREINT) BDREINT from ('||
                 'select '||wrefatu||' BDREF, COL.BDCODEMP, count(COL.BDCODCOL) BDATIVOS, 0 BDADMITIDOS, 0 BDTRANSF, 0 BDREINT from SP_SOMENTE_ATIVOS('''||wpridia||''', '''||wpridia||''') COL '||
                 'left outer join VRH_EMP_TTRANSCOL T on (T.BDCODEMPDEST = COL.BDCODEMP and T.BDCODCOLDEST = COL.BDCODCOL and T.BDDATATRF between '''||wpridia||''' and '''||wultdia||''') '||
                 'left outer join VRH_EMP_TCOL_REINTEGRACAO R on (R.BDCODEMP = COL.BDCODEMP and R.BDCODCOL = COL.BDCODCOL and R.BDDTEFEITORET between '''||wpridia||''' and '''||wultdia||''') '||
                 'left outer join SP_SOMENTE_ADMITIDOS_MES('''||wpridia||''', '''||wultdia||''') A on (A.BDCODEMP = COL.BDCODEMP and A.BDCODCOL = COL.BDCODCOL) '||
                 'join VRHF_EMP_TCOLCON_FGTSGPS CAT on (CAT.BDCODEMP = COL.BDCODEMP and CAT.BDCODCOL = COL.BDCODCOL and '||
                                                       'CAT.BDCATEGORIAESOCIAL in (101, 102, 103, 104, 105, 106, 107, 108, 111, 301, 302, 303, 306, 307, 309, 310, 312, 314) and '||
                                                       'CAT.BDREFCOL = (select max(F.BDREFCOL) from VRHF_EMP_TCOLCON_FGTSGPS F '||
                                                                       'where F.BDCODEMP = COL.BDCODEMP and '||
                                                                             'F.BDCODCOL = COL.BDCODCOL and '||
                                                                             'F.BDREFCOL <= '||wrefatu||')) '||
                 'where COL.BDCODEMP = '||wcodemp||' and '||
                       'T.BDCODCOLDEST is null and '||
                       'R.BDCODCOL is null and '||
                       'A.BDCODCOL is null '||
                 'group by BDREF, COL.BDCODEMP, BDADMITIDOS, BDTRANSF, BDREINT';
    
          wsql = wsql||' union all ';
    
          wsql = wsql||'select '||wrefatu||' BDREF, COL.BDCODEMP, 0 BDATIVOS, count(COL.BDCODCOL) BDADMITIDOS, 0 BDTRANSF, 0 BDREINT from SP_SOMENTE_ADMITIDOS_MES('''||wpridia||''', '''||wultdia||''') COL '||
                       'left outer join VRH_EMP_TTRANSCOL T on (T.BDCODEMPDEST = COL.BDCODEMP and T.BDCODCOLDEST = COL.BDCODCOL and T.BDDATATRF between '''||wpridia||''' and '''||wultdia||''') '||
                       'left outer join VRH_EMP_TCOL_REINTEGRACAO R on (R.BDCODEMP = COL.BDCODEMP and R.BDCODCOL = COL.BDCODCOL and R.BDDTEFEITORET between '''||wpridia||''' and '''||wultdia||''') '||
                       'join VRHF_EMP_TCOLCON_FGTSGPS CAT on (CAT.BDCODEMP = COL.BDCODEMP and CAT.BDCODCOL = COL.BDCODCOL and '||
                                                             'CAT.BDCATEGORIAESOCIAL in (101, 102, 103, 104, 105, 106, 107, 108, 111, 301, 302, 303, 306, 307, 309, 310, 312, 314) and '||
                                                             'CAT.BDREFCOL = (select max(F.BDREFCOL) from VRHF_EMP_TCOLCON_FGTSGPS F '||
                                                                             'where F.BDCODEMP = COL.BDCODEMP and '||
                                                                                   'F.BDCODCOL = COL.BDCODCOL and '||
                                                                                   'F.BDREFCOL <= '||wrefatu||')) '||
                        'where COL.BDCODEMP = '||wcodemp||' and '||
                              'T.BDCODCOLDEST is null and '||
                              'R.BDCODCOL is null '||
                        'group by BDREF, COL.BDCODEMP, BDATIVOS, BDTRANSF, BDREINT';
    
          wsql = wsql||' union all ';
    
          wsql = wsql||'select '||wrefatu||' BDREF, TRANS.BDCODEMPDEST BDCODEMP, 0 BDATIVOS, 0 BDADMITIDOS, count(TRANS.BDCODCOLDEST) BDTRANSF, 0 BDREINT from VRH_EMP_TTRANSCOL TRANS '||
                       'join VRHF_EMP_TCOLCON_FGTSGPS CAT on (CAT.BDCODEMP = TRANS.BDCODEMPDEST and CAT.BDCODCOL = TRANS.BDCODCOLDEST and '||
                                                             'CAT.BDCATEGORIAESOCIAL in (101, 102, 103, 104, 105, 106, 107, 108, 111, 301, 302, 303, 306, 307, 309, 310, 312, 314) and '||
                                                             'CAT.BDREFCOL = (select max(F.BDREFCOL) from VRHF_EMP_TCOLCON_FGTSGPS F '||
                                                                             'where F.BDCODEMP = TRANS.BDCODEMPDEST and '||
                                                                                   'F.BDCODCOL = TRANS.BDCODCOLDEST and '||
                                                                                   'F.BDREFCOL <= '||wrefatu||')) '||
                       'where TRANS.BDCODEMPDEST = '||wcodemp||' and '||
                             'TRANS.BDDATATRF between '''||wpridia||''' and '''||wultdia||''' '||
                       'group by BDREF, TRANS.BDCODEMPDEST, BDATIVOS, BDADMITIDOS, BDREINT';
    
          wsql = wsql||' union all ';
    
          wsql = wsql||'select '||wrefatu||' BDREF, REINT.BDCODEMP, 0 BDATIVOS, 0 BDADMITIDOS, 0 BDTRANSF, count(REINT.BDCODCOL) BDREINT from VRH_EMP_TCOL_REINTEGRACAO REINT '||
                       'join VRHF_EMP_TCOLCON_FGTSGPS CAT on (CAT.BDCODEMP = REINT.BDCODEMP and CAT.BDCODCOL = REINT.BDCODCOL and '||
                                                             'CAT.BDCATEGORIAESOCIAL in (101, 102, 103, 104, 105, 106, 107, 108, 111, 301, 302, 303, 306, 307, 309, 310, 312, 314) and '||
                                                             'CAT.BDREFCOL = (select max(F.BDREFCOL) from VRHF_EMP_TCOLCON_FGTSGPS F '||
                                                                             'where F.BDCODEMP = REINT.BDCODEMP and '||
                                                                                   'F.BDCODCOL = REINT.BDCODCOL and '||
                                                                                   'F.BDREFCOL <= '||wrefatu||')) '||
                       'where REINT.BDCODEMP = '||wcodemp||' and '||
                             'REINT.BDDTEFEITORET between '''||wpridia||''' and '''||wultdia||''' '||
                       'group by BDREF, REINT.BDCODEMP, BDATIVOS, BDADMITIDOS, BDTRANSF) '||
                       'group by BDREF, BDCODEMP';
    
          execute statement wsql into :wrefatu, :wcodemp, :wativos, :wadmit, :wtransf, :wreint;

          if (prfiliais) then
             begin
               if ((wcodempatu <> wcodemp) or (wt_total is null)) then
                  wt_total = 0;

               wqtde      = wqtde + 1;
               BDREF      = wrefatu;
               bdcodemp   = wcodemp;
               wcodempatu = bdcodemp;
               bdnomemp   = wnomemp;
               bdativos   = wativos;
               bdadmit    = wadmit;
               bdtransf   = wtransf;
               bdreint    = wreint;
               bdtotal    = wativos + wadmit + wtransf + wreint;
               bdqtdemes  = (WREFFIM - prrefini) + 1;
               wt_total   = wt_total + bdtotal;
               bdmedia    = cast((wt_total / cast(wqtde as numeric(9,2))) as numeric(9,2));
               bdmedtot   = cast((wt_total / cast(bdqtdemes as numeric(9,2))) as numeric(9,2));
               suspend;
             end

          wt_ref    = 0;
          wt_ativos = 0;
          wt_admit  = 0;
          wt_transf = 0;
          wt_reint  = 0;

          wsql = 'select BDREF, BDATIVOS, BDADMIT, BDTRANSF, BDREINT from TMP_RESUMO_TOTCOLATIVOS where BDREF = '||wrefatu;
          execute statement wsql into :wt_ref, :wt_ativos, :wt_admit, :wt_transf, :wt_reint;

          update or insert into TMP_RESUMO_TOTCOLATIVOS (BDREF,
                                                         BDATIVOS,
                                                         BDADMIT,
                                                         BDTRANSF,
                                                         BDREINT)
                                                 values (:wrefatu,
                                                        (:wt_ativos + :wativos),
                                                        (:wt_admit + :wadmit),
                                                        (:wt_transf + :wtransf),
                                                        (:wt_reint + :wreint))
          matching (BDREF);

          wrefatu = wrefatu + 1;
        end
    end

    wt_ref    = 0;
    wt_ativos = 0;
    wt_admit  = 0;
    wt_transf = 0;
    wt_reint  = 0;
    wqtde     = 0;
    wt_total  = 0;

    wsql = 'select BDREF, BDATIVOS, BDADMIT, BDTRANSF, BDREINT from TMP_RESUMO_TOTCOLATIVOS';
    for execute statement wsql into :wt_ref, :wt_ativos, :wt_admit, :wt_transf, :wt_reint do
    begin
      wqtde     = wqtde + 1;
      BDCODEMP  = null;
      BDNOMEMP  = 'Total geral';
      BDREF     = wt_ref;
      BDATIVOS  = wt_ativos;
      BDADMIT   = wt_admit;
      BDTRANSF  = wt_transf;
      BDREINT   = wt_reint;
      BDTOTAL   = wt_ativos + wt_admit + wt_transf + wt_reint;
      wt_total  = wt_total + bdtotal;
      bdqtdemes = (WREFFIM - prrefini) + 1;
      BDMEDIA   = cast((wt_total / cast(wqtde as numeric(9,2))) as numeric(9,2));
      bdmedtot  = cast((wt_total / cast(bdqtdemes as numeric(9,2))) as numeric(9,2));
      suspend;
    end
    delete from TMP_RESUMO_TOTCOLATIVOS;
end^

/* Restore proc. body: SP_VERIFICA_USU_PLAFUC */
create or alter procedure SP_VERIFICA_USU_PLAFUC (
    PRCODEMP integer,
    PRPLANOFUC integer)
returns (
    BDEMUSO DM_BOOLEAN)
as
declare variable WCODTFUC integer;
begin
  wcodtfuc = null;
  select first 1 BDCODTFUC from vrh_emp_tcol_vincdia where BDCODEMP = :prcodemp and BDCODPLAFUC = :prplanofuc into :wcodtfuc;

  if (coalesce(wcodtfuc,  0) > 0) then
     bdemuso = 'TRUE';
  else
     bdemuso = 'FALSE';

  suspend;
end^

/* Restore proc. body: SP_VERIFICA_USU_PLAHOR */
create or alter procedure SP_VERIFICA_USU_PLAHOR (
    PRCODEMP integer,
    PRPLANOHOR integer)
returns (
    BDEMUSO DM_BOOLEAN)
as
declare variable WCODQH integer;
begin
  wcodqh = null;
  select first 1 bdcodqh from vrh_emp_tcol_vincdia where BDCODEMP = :prcodemp and BDCODPQUA = :prplanohor into :wcodqh;

  if (coalesce(wcodqh, 0) > 0) then
     bdemuso = 'TRUE';
  else
     bdemuso = 'FALSE';

  suspend;
end^

/* Restore proc. body: SP_VRH_GR_PARCELAMENTOS */
create or alter procedure SP_VRH_GR_PARCELAMENTOS (
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDCNPJEMP DM_CNPJ_CPF,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDCPFCOL varchar(14),
    BDDSREF varchar(7),
    BDREFPI integer,
    BDDTREF date,
    BDDTREFSEG date,
    BDVALORPI DM_NUMERIC_15_2,
    BDVALORDESC DM_NUMERIC_15_2,
    BDDIFF DM_NUMERIC_15_2,
    BDNOMCID varchar(40),
    BDCONTRATOPAR varchar(30),
    BDCODBAN integer,
    BDNOMBAN varchar(300),
    BDCODFEBRABAN integer,
    BDTEMRESCISAO smallint,
    BDPAGTOPARCIAL smallint,
    BDCODPARC integer)
as
declare variable WDTSERV date;
declare variable WEMPATU integer;
declare variable WREFATU integer;
declare variable WCOLATU integer;
declare variable WMES smallint;
declare variable WANO integer;
declare variable WCODCID integer;
declare variable WREFRESC integer;
begin
  wempatu = 0;
  wrefatu = 0;
  wcolatu = 0;


  SELECT first 1 CURRENT_DATE FROM RDB$DATABASE into :wdtserv;

  if (coalesce(prrefini, 0) <= 0) then
     prrefini = cast((substring(cast(wdtserv as varchar(10)) from 1 for 4) || substring(cast(wdtserv as varchar(10)) from 6 for 2)) as integer);

  if (coalesce(prreffim, 0) <= 0) then
     prreffim = cast((substring(cast(wdtserv as varchar(10)) from 1 for 4) || substring(cast(wdtserv as varchar(10)) from 6 for 2)) as integer);

  for select P.BDCODEMP, P.BDCODCOL, P.BDCODPARC, P.BDCONTRATOPAR,
             coalesce(P.BDCODBANECONSIGNADO, B.BDCODBAN) BDCODBAN,
             coalesce(P.BDDESCBANCOECONSIGNADO, B.BDNOMBAN) BDNOMBAN, B.BDCODFEBRABAN,
             pi.BDREFPI, coalesce(cast(pi.BDVALORPI as dm_numeric_15_2), 0.00), coalesce(cast(pi.BDVALORDESC as dm_numeric_15_2), 0.00),
             C.BDCPFCOL,
             E.BDCNPJEMP,
             RESC.BDREFRESCISAO
      from VRH_EMP_TPARCELAMENTOS P
      join VRH_EMP_TCOLCON C on (P.BDCODEMP = C.BDCODEMP and P.BDCODCOL = C.BDCODCOL)
      join VRH_EMP_TPARCELAMENTOS_ITENS pi on (pi.BDCODEMP = C.BDCODEMP and pi.BDCODCOL = C.BDCODCOL and pi.BDCODPARC = P.BDCODPARC)
      join TEMPRESAS E on (E.BDCODEMP = P.BDCODEMP)
      left outer join TBANCOS B on (B.BDCODBAN = P.BDCODBAN)
      left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = P.BDCODEMP and RESC.BDCODCOL = P.BDCODCOL)
      where P.BDECONSIGNADO and
            PI.BDREFPI between :prrefini and :prreffim and
            exists(select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFN
                   from VRHF_EMP_TFOLHANORMAL FN
                   where FN.BDCODEMP = P.BDCODEMP and
                         FN.BDCODCOL = P.BDCODCOL and
                         FN.BDREFFN = pi.BDREFPI
                   union all
                   select FT.BDCODEMP, FT.BDCODCOL, FT.BDREFTOMADOR
                   from VRHF_EMP_TFOLHATOMADOR FT
                   where FT.BDCODEMP = P.BDCODEMP and
                         FT.BDCODCOL = P.BDCODCOL and
                         FT.BDREFTOMADOR = pi.BDREFPI)
      order by P.BDCODEMP, P.BDCODCOL, P.BDREFINIPAR, P.BDCODPARC, PI.BDREFPI
  into
    :BDCODEMP, :BDCODCOL, :BDCODPARC, :BDCONTRATOPAR,
    :BDCODBAN,
    :BDNOMBAN, :BDCODFEBRABAN,
    :BDREFPI, :BDVALORPI, :BDVALORDESC,
    :BDCPFCOL,
    :BDCNPJEMP,
    :wrefresc
  do
    begin
      if ((wempatu <> :BDCODEMP) or (wrefatu <> :BDREFPI)) then
         begin
           wcodcid = null;
           select first 1 BDNOMEMP, BDCODCID from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :BDREFPI order by BDCODEMP desc, BDREFEMP desc into :BDNOMEMP, :wcodcid;

           BDNOMCID = null;
           if (coalesce(wcodcid, 0) > 0) then
              select first 1 BDNOMCID from TCIDADE where BDCODCID = :wcodcid into :BDNOMCID;

           wempatu = BDCODEMP;
           wrefatu = BDREFPI;
           wcolatu = 0;
         end

      if ((wcolatu <> BDCODCOL) or (wrefatu <> BDREFPI)) then
         begin
           select first 1 BDNOMCOL from VRH_EMP_TCOLCON_CAD where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFCOL <= :BDREFPI order by BDCODEMP desc, BDCODCOL desc, BDREFCOL desc into :BDNOMCOL;

           wcodcid = null;
           select first 1 BDCODPARC from VRH_EMP_TPARCELAMENTOS_ITENS where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFPI = :BDREFPI and (coalesce(BDVALORPI, 0.00) - coalesce(BDVALORDESC, 0.00)) > 0 into :wcodcid;

           if (coalesce(wcodcid, 0) > 0) then
              BDPAGTOPARCIAL = 1;
           else
              BDPAGTOPARCIAL = 0;

           wcolatu = BDCODCOL;
           wrefatu = BDREFPI;
         end

      BDDSREF = substring(BDREFPI from 5 for 2) || '/' || substring(BDREFPI from 1 for 4);
      BDDTREF = cast(('01.' || substring(BDREFPI from 5 for 2) || '.' || substring(BDREFPI from 1 for 4)) as date);

      wmes = cast(substring(:BDREFPI from 5 for 2) as smallint);
      wano = cast(substring(:BDREFPI from 1 for 4) as integer);
      select first 1 MES, ANO from REF_SEGUINTE(:wmes, :wano) into :wmes, :wano;
      BDDTREFSEG = cast(('20.' || lpad(wmes, 2, '0') || '.' || wano) as date);

      BDDIFF = (coalesce(BDVALORPI, 0.00) - coalesce(BDVALORDESC, 0.00));

      if ((coalesce(wrefresc, 0) > 0) and (wrefresc <= BDREFPI)) then
         BDTEMRESCISAO = 1;
      else
         BDTEMRESCISAO = 0;

      if ((BDTEMRESCISAO > 0) or (BDPAGTOPARCIAL > 0)) then
         suspend;
    end
end^


CREATE OR ALTER TRIGGER VRH_EMP_TPARCELAMENTOS_ITENS_BD0 FOR VRH_EMP_TPARCELAMENTOS_ITENS
ACTIVE BEFORE DELETE POSITION 0
AS
begin
  delete from vrhf_emp_tparcdetcalc where BDCODEMP = old.bdcodemp and BDCODCOL = old.bdcodcol and BDCODPARC = old.bdcodparc and BDPARCELAPI = old.bdparcelapi;
end
^
CREATE OR ALTER trigger vrh_imp_econsignado_bi0 for vrh_imp_econsignado
active before insert position 0
AS
begin
  /* Trigger text */
  if (coalesce(new.bdordem,0) = 0) then
     begin
       select coalesce(max(bdordem),0)+1 from vrh_imp_econsignado
       where bdcodemp = new.bdcodemp and
             BDCODCOL = new.bdcodcol and
             BDCONTRATOPAR = new.bdcontratopar and
             BDREF          = new.bdref
       group by BDCODEMP, BDCODCOL, BDCONTRATOPAR, BDREF into new.bdordem;
     end

  if (coalesce(new.bdordem,0) = 0) then
     begin
       new.bdordem = 1;
     end
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TPARCDETCALC_BI0 FOR VRHF_EMP_TPARCDETCALC
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (coalesce(new.bdcodparccalc, 0) <= 0) then
     select coalesce(max(BDCODPARCCALC), 0) + 1 from vrhf_emp_tparcdetcalc into new.bdcodparccalc;
end
^



CREATE OR ALTER TRIGGER TAVISOS_EXIBIDOS_BI0 FOR TAVISOS_EXIBIDOS
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF ((NEW.BDIDEXIBIDO IS NULL) OR (NEW.BDIDEXIBIDO = 0)) THEN
  BEGIN
    NEW.BDIDEXIBIDO = (SELECT COALESCE(MAX(BDIDEXIBIDO), 0)+1 FROM TAVISOS_EXIBIDOS);
  END
END
^

/* Restore proc. body: SP_VRH_PARCELAMENTO_CREDTRAB_FERIAS */
create or alter procedure SP_VRH_PARCELAMENTO_CREDTRAB_FERIAS (
    PRCODEMP varchar(32700),
    PRCODCOL varchar(32700),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODPARC integer,
    BDPARCELAPI integer,
    BDVALORPI numeric(18,6),
    BDCODVER integer,
    BDREFPI integer,
    BDQTDMESESPAR integer,
    BDPROVDESCPAR integer,
    BDECONSIGNADO char(5),
    BDVALORDESC numeric(18,2),
    BDCODBAN integer,
    BDCONTRATOPAR varchar(30),
    BDNOMBAN varchar(60),
    BDVALORDESC_NOR numeric(18,2),
    BDDATAINI date,
    BDTOTALPAR integer,
    BDREFINIPAR integer,
    BDMENSAL varchar(5),
    BDRESCISORIO varchar(5),
    BDPERCENTUALGARANTIA numeric(18,2),
    BDVALORSALDODEVEDOR numeric(18,2))
as
declare variable WSQL varchar(32700);
declare variable WEXISTE_PROXIMO integer;
declare variable WPROXREF integer;
begin

  wsql = 'select PARCI.BDCODEMP, PARCI.BDCODCOL, PARCI.BDCODPARC, PARCI.BDPARCELAPI, PARCI.BDVALORPI, PARC.BDCODVER, '||
         '      PARCI.BDREFPI, PARC.BDQTDMESESPAR, PARC.BDPROVDESCPAR, PARC.BDECONSIGNADO, PARCI.BDVALORDESC, PARC.BDCODBAN, '||
         '      PARC.BDCONTRATOPAR, BAN.BDNOMBAN, PARCI.BDVALORDESC_NOR, IMP.BDDATAINI, '||
         '      IMP.BDTOTALPAR, PARC.BDREFINIPAR, PARC.BDMENSAL, PARC.BDRESCISORIO, PARCI.BDPERCENTUALGARANTIA, PARCI.BDVALORSALDODEVEDOR '||
         ' from VRH_EMP_TPARCELAMENTOS_ITENS PARCI '||
         ' join VRH_EMP_TPARCELAMENTOS PARC on (PARC.BDCODEMP = PARCI.BDCODEMP and '||
         '     PARC.BDCODCOL = PARCI.BDCODCOL and '||
         '     PARC.BDCODPARC = PARCI.BDCODPARC) '||
         ' left outer join VRH_IMP_ECONSIGNADO IMP on (IMP.BDCODEMP = PARC.BDCODEMP and '||
         '     IMP.BDCODCOL = PARC.BDCODCOL and '||
         '     IMP.BDCONTRATOPAR = PARC.BDCONTRATOPAR and '||
         '     IMP.BDREF = PARC.BDREFINIPAR) '||
         ' left outer join TBANCOS BAN on (BAN.BDCODBAN = PARC.BDCODBAN) ';

  wsql = wsql||' where PARC.BDECONSIGNADO = ''TRUE'' AND PARCI.BDREFPI >= '||prref;

  IF ((prcodemp IS NOT NULL) and (prcodemp <> '')) THEN
     wsql = wsql||' AND '||prcodemp;

  IF ((prcodcol IS NOT NULL) and (prcodcol <> '')) THEN
     wsql = wsql||' AND '||prcodcol;

  wsql = wsql||' order by PARC.BDECONSIGNADO desc, IMP.BDDATAINI, PARC.BDREFINIPAR, PARCI.BDREFPI, PARCI.BDCODPARC, PARC.BDCONTRATOPAR';

  for execute statement wsql into
    :BDCODEMP,
    :BDCODCOL,
    :BDCODPARC,
    :BDPARCELAPI,
    :BDVALORPI,
    :BDCODVER,
    :BDREFPI,
    :BDQTDMESESPAR,
    :BDPROVDESCPAR,
    :BDECONSIGNADO,
    :BDVALORDESC,
    :BDCODBAN,
    :BDCONTRATOPAR,
    :BDNOMBAN,
    :BDVALORDESC_NOR,
    :BDDATAINI,
    :BDTOTALPAR,
    :BDREFINIPAR,
    :BDMENSAL,
    :BDRESCISORIO,
    :BDPERCENTUALGARANTIA,
    :BDVALORSALDODEVEDOR
  do
  begin
    suspend;

    if ((BDREFPI = PRREF) and (BDPARCELAPI < BDTOTALPAR)) then
       begin
         select first 1 PARCI.BDCODPARC from VRH_EMP_TPARCELAMENTOS_ITENS PARCI
         join VRH_EMP_TPARCELAMENTOS PARC on (PARC.BDCODEMP = PARCI.BDCODEMP and
              PARC.BDCODCOL = PARCI.BDCODCOL and
              PARC.BDCODPARC = PARCI.BDCODPARC)
         where PARCI.BDCODEMP = :BDCODEMP and
               PARCI.BDCODCOL = :BDCODCOL and
               PARCI.BDREFPI > :PRREF and
               PARC.BDECONSIGNADO = 'TRUE'
         into :WEXISTE_PROXIMO;

         if (WEXISTE_PROXIMO is null) then
            begin
              SELECT BDREFERENCIA FROM inc_referencia(:prref, 1) INTO :WPROXREF;
              BDREFPI = WPROXREF;
              suspend;
            end
       end
  end
end^

CREATE OR ALTER TRIGGER VRH_ESOCIAL_CREDITOTRAB_C_BI0 FOR VRH_ESOCIAL_CREDITOTRAB_C
ACTIVE BEFORE INSERT POSITION 0
as
declare variable VCODIGO integer;
begin
  VCODIGO = 0;
  if ((new.BDCODCREDTRAB is null) or (new.BDCODCREDTRAB = 0)) then
  begin
    select coalesce((max(BDCODCREDTRAB) + 1), 1)
    from VRH_ESOCIAL_CREDITOTRAB_C
    where BDCODEMP = new.BDCODEMP and
          BDCODCOL = new.BDCODCOL and
          BDCODEVT = new.BDCODEVT
    into VCODIGO;

    new.BDCODCREDTRAB = VCODIGO;
  end
end
^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TC197IVASP_AD0 FOR TOL_VEF_EMP_TC197IVASP
ACTIVE AFTER DELETE POSITION 0
AS
BEGIN
  DELETE FROM VEF_EMP_TMOVOCO_GIASP WHERE BDCODEMP = OLD.BDCODEMP AND BDCHAVEOCOGIASP = OLD.BDCHAVEOCOGIASP AND BDCODTIPOOCOGIA = OLD.BDCODTIPOOCOGIA;
END^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TC195IVASP_AD0 FOR TOL_VEF_EMP_TC195IVASP
ACTIVE AFTER DELETE POSITION 0
AS
declare variable WCODIGO integer;
begin
  SELECT FIRST 1 BDCODEMP FROM TOL_VEF_EMP_TC195IVASP WHERE BDCODEMP = OLD.BDCODEMP AND BDCHAVE = OLD.BDCHAVE AND BDORDEMOBS = OLD.BDORDEMOBS AND (BDORDEM <> OLD.BDORDEM OR BDORDEMIVA <> OLD.BDORDEMIVA)
  INTO :WCODIGO;

  if (:WCODIGO IS NULL) then
    DELETE FROM VEF_EMP_TC195ENT c195
    WHERE c195.BDCODEMP = OLD.BDCODEMP
      AND c195.BDCHAVE = OLD.BDCHAVE
      AND c195.BDORDEMOBS = OLD.BDORDEMOBS
      AND (NOT EXISTS(SELECT *
                      FROM TOL_VEF_EMP_TC195ENT x
                      WHERE x.BDCODEMP = c195.BDCODEMP
                        AND x.BDCHAVE = c195.BDCHAVE
                        AND x.BDORDEMOBS = c195.BDORDEMOBS));
end^

CREATE OR ALTER TRIGGER TOL_VEF_EMP_TC195IVASP_BI0 FOR TOL_VEF_EMP_TC195IVASP
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
  IF ((NEW.bdchave IS NULL) OR (NEW.bdchave = 0)) THEN
     BEGIN
       SELECT COALESCE((MAX(bdchave)), 1)
       FROM vef_emp_tmovent
       WHERE (bdcodemp = NEW.bdcodemp)
       INTO vcodigo;
       NEW.bdchave = vcodigo;
     END

   IF ((NEW.BDORDEM IS NULL) OR (NEW.BDORDEM = 0))  THEN
     BEGIN
       SELECT COALESCE((MAX(BDORDEM)), 1)
       FROM VEF_EMP_TMOVENTITENS
       WHERE (bdcodemp = NEW.bdcodemp)
       AND (BDCHAVE = NEW.BDCHAVE)
       INTO vcodigo;
       NEW.BDORDEM = vcodigo;
     END
end^

create or alter procedure SP_ADD_CONSIGNADO_5003 (
    PRCODEMP integer,
    PRCODCOL integer,
    PRCPF varchar(14),
    PRREF integer,
    PRCODEMPORD integer,
    PRGRUPOCLA integer,
    PRCONTRCOL integer,
    PRCNPJEMP varchar(18),
    PRCATEGORIAESOCIAL integer)
as
declare variable WSQL varchar(1000);
declare variable WINSTITUICAOFINANC integer;
declare variable WNROCONTRATOECONSIGNADO varchar(30);
declare variable WVALOR numeric(18,6);
declare variable WEVT integer;
declare variable WEVTANT integer;
declare variable WEXISTEREGISTRO integer;
declare variable WTAGSTR varchar(100);
declare variable WCODPARC integer;
declare variable WMOTIVORESCISAO integer;
declare variable WEXPORTAGRRF integer;
declare variable WDATAPGTORESC date;
declare variable WRESCISORIO integer;
begin
  /* Procedure Text */

  WINSTITUICAOFINANC = 0;
  WNROCONTRATOECONSIGNADO = '';
  WVALOR = 0;

  WMOTIVORESCISAO = 0;
  WEXPORTAGRRF = 0;
  WDATAPGTORESC = null;
  wsql = 'select RES.BDCODPRES, X.BDGRRFPRES, BDDATAPAGRESCISAO '||
         '   from VRH_EMP_TRESCISAO RES '||
         '   left join VRH_BASE_TPREPRESC X on (X.BDCODPRES = RES.bdcodpres) '||
         '   where RES.BDCODEMP = '||:PRCODEMP||' and '||
         '   RES.BDCODCOL = '||:PRCODCOL||' and '||
         '   RES.BDREFRESCISAO = '||:PRREF||' and '||
         '   X.BDTIPOMOV <> 1';

  execute statement WSQL into :WMOTIVORESCISAO, :WEXPORTAGRRF, :WDATAPGTORESC;

  wrescisorio = 0;
  if ((coalesce(WMOTIVORESCISAO,0) > 0) and (coalesce(WEXPORTAGRRF,0) > 0) and (WDATAPGTORESC is not null))
      /*and (WDATAPGTOCALC <= WDATAPGTORESC))*/ then
      wrescisorio = 1;

  WSQL = 'select coalesce(parc.BDCODBANECONSIGNADO,parc.bdcodban) bdcodban, parc.bdcontratopar, it.BDVALORDESC, parc.bdcodparc '||
         'from vrh_emp_tparcelamentos parc '||
         'join vrh_emp_tparcelamentos_itens it on (it.bdcodemp = parc.bdcodemp and it.bdcodcol = parc.bdcodcol and it.bdcodparc = parc.bdcodparc) '||
         'where parc.bdcodemp = '||CAST(PRCODEMP AS VARCHAR(10))||
         '      and parc.bdcodcol = '||CAST(PRCODCOL AS VARCHAR(10))||
         '      and it.bdrefpi = '||PRREF||
         '      and parc.bdeconsignado = true '||
         '      and it.BDVALORDESC <> 0 '||
         'ORDER BY bdcodban, parc.bdcontratopar ';

  FOR EXECUTE STATEMENT WSQL INTO :WINSTITUICAOFINANC, :WNROCONTRATOECONSIGNADO, :WVALOR, :WCODPARC DO
  BEGIN
    WTAGSTR = PRCODEMP||'|'||PRCODCOL||'|'||WCODPARC;

    UPDATE OR INSERT INTO VRHF_TEMP_EMP_TECONSIGNADO5003
    (BDSESSAO, BDCODEMP, BDCPFCOL, BDCODCOL, BDUNICO, BDTAGSTR, BDDESCRICAOLINK, BDZERADO, BDCODEMPORD,
     BDINSTITUICAOFINANC, BDNROCONTRATOECONSIGNADO, BDVALOR,
     BDGRUPOCLA, BDCONTRCOL, BDCNPJEMP, BDCATEGORIAESOCIAL, BDRESCISORIO)
    VALUES
    (current_connection, :PRCODEMP, :PRCPF, :PRCODCOL, 1, :WTAGSTR, '', FALSE, :PRCODEMPORD,
     :WINSTITUICAOFINANC, :WNROCONTRATOECONSIGNADO, :WVALOR,
     :PRGRUPOCLA, :PRCONTRCOL, :PRCNPJEMP, :PRCATEGORIAESOCIAL, :WRESCISORIO)
    MATCHING (BDSESSAO, BDCODEMP, BDCPFCOL, BDCODCOL, BDUNICO, BDTAGSTR, BDINSTITUICAOFINANC, BDNROCONTRATOECONSIGNADO);

    WINSTITUICAOFINANC = 0;
    WNROCONTRATOECONSIGNADO = '';
    WVALOR = 0;
  END

  WEVT = 0;
  WEVTANT = -1;

  WSQL = 'select F.bdinstituicaofinanc, F.bdnrocontratoeconsignado, F.bdvaloreconsignado, F.BDCODEVT '||
         'from VRH_ESOCIAL_CREDITOTRAB_C F '||
         'WHERE F.BDCODEMP = '||:PRCODEMP||' AND '||
         '      F.BDCODCOL = '||:PRCODCOL||' AND '||
         '      F.BDCODEVT = (select first 1 X.BDCODEVENTOORIG '||
         '                    from VRH_ESOCIAL_TARQUIVO X '||
         '                    where X.BDCODEMP = '||:PRCODEMP||' and '||
         '                          X.BDCODCOL = '||:PRCODCOL||' and '||
         '                          X.BDREFARQ = '||:PRREF||' and '||
         '                          X.BDSTATUS = 2 and '||
         '                          X.BDCODTIPO = 46 '||
         '                    order by X.BDDATARETORNO desc, X.BDHORARETORNO desc) ';

  FOR EXECUTE STATEMENT WSQL INTO :WINSTITUICAOFINANC, :WNROCONTRATOECONSIGNADO, :WVALOR, :WEVT DO
  BEGIN
    IF (WEVTANT = -1) THEN
       WEVTANT = WEVT;
    ELSE IF (WEVT <> WEVTANT) THEN
       BREAK;

    UPDATE OR INSERT INTO VRHF_TEMP_EMP_TECONSIGNADO5003
    (BDSESSAO, BDCODEMP, BDCPFCOL, BDCODCOL, BDUNICO, BDTAGSTR, BDDESCRICAOLINK, BDZERADO, BDCODEMPORD,
     BDINSTITUICAOFINANC, BDNROCONTRATOECONSIGNADO, BDVALOR,
     BDGRUPOCLA, BDCONTRCOL, BDCNPJEMP, BDCATEGORIAESOCIAL, BDRESCISORIO)
    VALUES
    (current_connection, :PRCODEMP, :PRCPF, :PRCODCOL, 2, '', '', FALSE, :PRCODEMPORD,
     :WINSTITUICAOFINANC, :WNROCONTRATOECONSIGNADO, :WVALOR,
     :PRGRUPOCLA, :PRCONTRCOL, :PRCNPJEMP, :PRCATEGORIAESOCIAL, :WRESCISORIO)
    MATCHING (BDSESSAO, BDCODEMPORD, BDCPFCOL, BDUNICO, BDINSTITUICAOFINANC, BDNROCONTRATOECONSIGNADO);

    WINSTITUICAOFINANC = 0;
    WNROCONTRATOECONSIGNADO = '';
    WVALOR = 0;
    WEVT = 0;
  END
end
^

CREATE OR ALTER procedure SP_GENIMPORTACAO_SERVRPA
returns (
    BDLOTEIMPORTACAO integer)
as
declare variable WCONTINUARBUSCANDOGEN DM_BOOLEAN;
declare variable WLOTEIMPORTACAODOGEN integer;
declare variable WULTIMOLOTEIMPORTACAO integer;
BEGIN
  :BDLOTEIMPORTACAO = -1;
  :WULTIMOLOTEIMPORTACAO = -1;
  :WCONTINUARBUSCANDOGEN = 'TRUE';
  :WLOTEIMPORTACAODOGEN = -1;

  WHILE (WCONTINUARBUSCANDOGEN = 'TRUE') DO
    BEGIN

      IF (WULTIMOLOTEIMPORTACAO = -1) THEN
        BEGIN
            SELECT FIRST 1 COALESCE(SERV.BDLOTEIMPORTACAO, 0) BDLOTEIMPORTACAO FROM VRH_BASE_TSERVTERC SERV  ORDER BY SERV.BDLOTEIMPORTACAO DESC INTO :WULTIMOLOTEIMPORTACAO;
        END

      IF (WCONTINUARBUSCANDOGEN = 'TRUE') THEN
        BEGIN
          SELECT GEN_ID(GEN_LOTEIMPORTACAO_SERV_RPA, 1) BDLOTEIMPORTACAO FROM RDB$DATABASE INTO :BDLOTEIMPORTACAO;

          IF ((BDLOTEIMPORTACAO > WULTIMOLOTEIMPORTACAO) AND (BDLOTEIMPORTACAO > 0)) THEN
            BEGIN
               :WCONTINUARBUSCANDOGEN = 'FALSE';
            END
        END
    END
  SUSPEND;
END^

/* Restore proc. body: SP_VRH_COLCON_RHNET_EXP */
create or alter procedure SP_VRH_COLCON_RHNET_EXP (
    PRFILTRO varchar(32000),
    PRCOMPETENCIA integer,
    PRFILTROCOL smallint = 0,
    PRDADOSINICIAIS smallint = 0,
    PRSOMENTELEITURA smallint = 0)
returns (
    BDCODEMPRHNET integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDNOMCOL DM_BDNOMCOL,
    BDLOGRID integer,
    BDENDCOL DM_BDENDERECO,
    BDNUMCOL DM_NUMEND,
    BDCOMPLCOL DM_BDCOMPENDERECO,
    BDBAICOL DM_BDBAIRRO,
    BDCEPCOL varchar(9),
    BDCODCID integer,
    BDDDDCELCOL integer,
    BDCELCOL DM_BDTELEFONE,
    BDDDDCOL integer,
    BDFONECOL DM_BDTELEFONE,
    BDEMAILCOL DM_BDEMAIL,
    BDTIPOSANGUECOL integer,
    BDCORCOL integer,
    BDCABELOSCOL integer,
    BDOLHOSCOL integer,
    BDSEXOCOL integer,
    BDDEFFIS DM_BOOLEAN,
    BDDEFVIS DM_BOOLEAN,
    BDDEFAUD DM_BOOLEAN,
    BDDEFMEN DM_BOOLEAN,
    BDREAB DM_BOOLEAN,
    BDDEFINT DM_BOOLEAN,
    BDCOTADEF DM_BOOLEAN,
    BDDEFCOL DM_BOOLEAN,
    BDOBSDEFFISCOL varchar(300),
    BDNMSOCIAL DM_BDNOMCOL,
    BDALTURACOL DM_NUMERIC_20MILHOES_2CASAS,
    BDPESOCOL DM_NUMERIC_20MILHOES_2CASAS,
    BDSINAISCOL DM_BOOLEAN,
    BDCODCIDNASC integer,
    BDNOMCIDESTRANGEIRO varchar(40),
    BDCODPAIS integer,
    BDDATACHEBRASILCOL date,
    BDDATANASCCOL date,
    BDGRAUINSTCOL integer,
    BDESTCIVCOL integer,
    BDDATAADMCOL date,
    BDDATACADCOL date,
    BDRGCOL varchar(13),
    BDORGEMIRGCOL DM_ORGAOEMISSOR,
    BDDATAEMIRGCOL date,
    BDCODUFRG varchar(2),
    BDCPFCOL varchar(14),
    BDPISCOL varchar(14),
    BDDATAEMIPISCOL date,
    BDTITELEICOL varchar(13),
    BDZONAELEICOL integer,
    BDSECAOELEICOL integer,
    BDCTPSCOL DM_BDCTPS,
    BDSERIECTPSCOL DM_SERIECTPS,
    BDDATAEMICTPSCOL date,
    BDCODUF varchar(2),
    BDCNHCOL varchar(11),
    BDCATCNHCOL varchar(2),
    BDVENCCNHCOL date,
    BDRESERVISTACOL varchar(16),
    BDNOMPAICOL varchar(70),
    BDNOMMAECOL varchar(70),
    BDNOMCONJCOL varchar(70),
    BDDATANASCCONJCOL date,
    BDCODCLA integer,
    BDTIPOCOL integer,
    BDSALINICOL DM_NUMERIC_15_2,
    BDHORASMENSAISCOL numeric(15,6),
    BDHORASSEMANAISCOL numeric(15,6),
    BDHORASDIARIASCOL numeric(15,6),
    BDPERCINSALUBCOL numeric(15,6),
    BDINCIDINSALUBCOL integer,
    BDPERCPERCULCOL numeric(15,6),
    BDINCIDPERICULCOL integer,
    BDPERCNOTURNOCOL numeric(15,6),
    BDINCIDNOTURNOCOL integer,
    BDCALCVALREFCOL DM_BOOLEAN,
    BDDIASPRAZO1COL integer,
    BDDIASPRAZO2COL integer,
    BDOBSCOL blob sub_type 1 segment size 5000,
    BDDSERIECTPSCOL varchar(1),
    BDTIPOADMCOL integer,
    BDDESCCONTSINCOL DM_BOOLEAN,
    BDCODBAN integer,
    BDCTADEPCOL varchar(15),
    BDTIPOCTACOL integer,
    BDADIANTAMENTO integer,
    BDREGIMEPARCIALCOL DM_BOOLEAN,
    BDSINDICALIZADOCOL DM_BOOLEAN,
    BDCODSINTRAB integer,
    BDFICHAREGCOL varchar(12),
    BDLIVROREGCOL varchar(10),
    BDNROFOLHAREGCOL integer,
    BDDATAADICCOL date,
    BDNATUOCUPCOL integer,
    BDCODTIPOCONTRATO integer,
    BDDTAPOSENT date,
    BDNUMRICCOL varchar(14),
    BDORGAORICCOL varchar(20),
    BDDATAEMIRICCOL date,
    BDNUMRNECOL varchar(14),
    BDORGAORNECOL varchar(20),
    BDDATAEMIRNECOL date,
    BDNUMOCCOL varchar(14),
    BDORGAOOCCOL varchar(20),
    BDDATAEMIOCCOL date,
    BDCASADOBR DM_BOOLEAN,
    BDFILHOSBR DM_BOOLEAN,
    BDCODPAISRES integer,
    BDCODPOSTESTRCOL varchar(10),
    BDEMAIL2COL varchar(100),
    BDFOTOCOL_IMG blob sub_type 0 segment size 32700,
    BDCODAG integer,
    BDDATABAIXACOL date,
    BDDESLIGAMENTO date,
    BDDATAFIMPRAZO1COL date,
    BDDATAFIMPRAZO2COL date,
    BDDATAVALOCCOL date,
    BDSUS varchar(16),
    BDORGAOCNH varchar(20),
    BDDATAEMICNH date,
    BDDIGCTADEPCOL varchar(2),
    BDREGJORTRAB integer,
    BDCODPLAFUC integer,
    BDCODTFUC integer,
    BDCODQH integer,
    BDCODPQUA integer,
    BDCALCVALTRANSCOL DM_BOOLEAN,
    BDFORMAPAGTOCOL integer,
    BDTIPOCERTCIVILCOL integer,
    BDTERMOCERTCIVILCOL varchar(32),
    BDCARTORIOCERTCIVILCOL varchar(120),
    BDLIVROCERTCIVILCOL varchar(8),
    BDFOLHACERTCIVILCOL varchar(4),
    BDCODCIDCERTCIVIL integer,
    BDDATACERTCIVILCOL date,
    BDCATEGORIAESOCIAL integer,
    BDOCORRENCIACOL integer,
    BDCTAFGTSCOL varchar(11),
    BDSEGDESCOL DM_BOOLEAN,
    BDCARTAOSALCOL varchar(7),
    BDVALORPREVPRIVNCOL DM_NUMERIC_15_2,
    BDVALORPREVPRIV13COL DM_NUMERIC_15_2,
    BDDATATRFCOL date,
    BDCPF_IMG blob sub_type 0 segment size 32700,
    BDRG_IMG blob sub_type 0 segment size 32700,
    BDPIS_IMG blob sub_type 0 segment size 32700,
    BDTITELEITOR_IMG blob sub_type 0 segment size 32700,
    BDCNH_IMG blob sub_type 0 segment size 32700,
    BDCTPS_IMG blob sub_type 0 segment size 32700,
    BDCONTRCOL varchar(12),
    BDSTATUSQC integer,
    BDCODPAISNAS integer,
    BDREGPREV integer,
    BDMODOPAGTOCOL integer,
    BDUFCNH varchar(2),
    BDDTPRIMCNH date,
    BDCODCIDNASCCONJ integer,
    BDREGPROF varchar(20),
    BDCNPJEMPANT varchar(20),
    BDTRANSONUS DM_BOOLEAN,
    BDCODCLE integer,
    BDCARTAOVA varchar(20),
    BDCARTAOVR varchar(20),
    BDCARTAOVT varchar(20),
    BDPERCADISAL DM_NUMERIC_15_2,
    BDTIPOJORNADA integer,
    BDCODCOLPREL integer,
    BDFICHAREGANT varchar(30),
    BDCONDICAOINGRESSO integer,
    BDTEMPORESIDENCIA integer,
    BDMATRICULA varchar(30),
    BDDESCTPJORNADA varchar(100),
    BDINDHORARIONOT integer,
    BDDTEFEITO date,
    BDDESCPAIS varchar(60),
    BDREGIMETRAB integer,
    BDIDRHNET integer,
    BDADMPRELIDRHNET integer)
as
declare variable WSQL varchar(20000);
declare variable WFILTRO varchar(5000);
declare variable WCONTRCOL integer;
declare variable WCOTADEF integer;
declare variable WEMPTRANS integer;
declare variable WCOLTRANS integer;
declare variable WDESCJOR varchar(100);
declare variable WLOGRCOL DM_LOGRADOURO;
declare variable WCODCID integer;
declare variable WCODUFRG integer;
declare variable WCODUF integer;
declare variable WCODUFCNH integer;
declare variable WCODPAIS integer;
declare variable WCODPAISNAS integer;
begin
  prfiltro         = coalesce(prfiltro, '');
  prcompetencia    = coalesce(prcompetencia, 0);
  prfiltrocol      = coalesce(prfiltrocol, 0);
  prdadosiniciais  = coalesce(prdadosiniciais, 0);
  prsomenteleitura = coalesce(prsomenteleitura, 0);

  wsql = 'select ';

  if (prsomenteleitura = 1) then
     wsql = wsql||'C.BDCODEMP  ';
  else
     wsql = wsql||'coalesce(E.BDCODWEB, C.BDCODEMP) ';

  wsql = wsql||', C.BDCODEMP, C.BDCODCOL, C.BDDATANASCCOL, C.BDDATAADMCOL, C.BDDATACADCOL, C.BDCPFCOL, C.BDDATAADICCOL '||
               ', C.BDEMAIL2COL, C.BDCONTRCOL, C.BDSTATUSQC, C.BDMATRICULA'||
               ', C.BDCODCIDNASC';

  if (prdadosiniciais = 0) then
     begin
       wsql = wsql||', C.BDIDRHNET, COALESCE(C.BDADMPRELIDRHNET, AP.BDIDRHNET)';
     end
  else
     begin
       wsql = wsql||', case when (upper(coalesce(E.BDNOVORHNETSOCIAL, ''FALSE'')) = ''TRUE'') and '||
                                '(upper(coalesce(E.BDEXPDINIRHNET, ''FALSE'')) = ''TRUE'') '||
                     ' then C.BDIDRHNET else CAST(NULL AS INTEGER) end BDIDRHNET '||
                    ', case when (upper(coalesce(E.BDNOVORHNETSOCIAL, ''FALSE'')) = ''TRUE'') and '||
                                '(upper(coalesce(E.BDEXPDINIRHNET, ''FALSE'')) = ''TRUE'') '||
                     ' then COALESCE(C.BDADMPRELIDRHNET, AP.BDIDRHNET) else CAST(NULL AS INTEGER) end BDADMPRELIDRHNET';

     end

  wsql = wsql||', F.BDTIPOSANGUECOL, F.BDCABELOSCOL, F.BDOLHOSCOL, F.BDALTURACOL, F.BDPESOCOL, F.BDSINAISCOL';
  wsql = wsql||', D2.BDTITELEICOL, D2.BDZONAELEICOL, D2.BDSECAOELEICOL, D2.BDDTPRIMCNH';
  wsql = wsql||', P1.BDNOMPAICOL, P1.BDNOMMAECOL, P1.BDNOMCONJCOL, P1.BDDATANASCCONJCOL, P1.BDCODCIDNASCCONJ';
  wsql = wsql||', D1.BDRESERVISTACOL, D1.BDSUS, D1.BDTIPOCERTCIVILCOL, D1.BDTERMOCERTCIVILCOL, D1.BDCARTORIOCERTCIVILCOL, D1.BDLIVROCERTCIVILCOL'||
               ', D1.BDFOLHACERTCIVILCOL, D1.BDDATACERTCIVILCOL, D1.BDREGPROF, D1.BDCODCIDCERTCIVIL';
  wsql = wsql||', A.BDDIASPRAZO1COL, A.BDDIASPRAZO2COL, A.BDTIPOADMCOL, A.BDDESCCONTSINCOL, A.BDFICHAREGCOL, A.BDLIVROREGCOL, A.BDNROFOLHAREGCOL, A.BDNATUOCUPCOL'||
               ', A.BDDATAFIMPRAZO1COL, A.BDDATAFIMPRAZO2COL, case when COALESCE(A.BDREGJORTRAB, 0) <= 0 then 1 else A.BDREGJORTRAB end'||
               ', A.BDCNPJEMPANT, A.BDTRANSONUS, A.BDFICHAREGANT';
  wsql = wsql||', P2.BDSALINICOL, P2.BDCODTIPOCONTRATO, P2.BDCODPLAFUC, P2.BDCODTFUC, P2.BDCODQH, P2.BDCODPQUA, P2.BDSEGDESCOL, P2.BDDATATRFCOL, P2.BDDESCTPJORNADA';
  wsql = wsql||', H2.BDOBSCOL';
  wsql = wsql||', H1.BDDTAPOSENT, H1.BDCODPOSTESTRCOL, H1.BDCODPAIS, H1.BDCODPAISNAS';
  wsql = wsql||', COALESCE(D3.BDDATABAIXACOL, RESC.BDDATARESCISAO), RESC.BDDATARESCISAO';
  wsql = wsql||', RE.BDDTEFEITO';
  wsql = wsql||', IMG.BDFOTOCOL_IMG, IMG.BDCPF_IMG, IMG.BDRG_IMG, IMG.BDPIS_IMG, IMG.BDTITELEITOR_IMG, IMG.BDCNH_IMG, IMG.BDCTPS_IMG ';

  wsql = wsql||'from VRH_EMP_TCOLCON C '||
               'join TEMPRESAS E on (E.BDCODEMP = C.BDCODEMP) '||
               'left outer join VRH_EMP_TCOL_ADMPREL AP on (AP.BDCODEMP = C.BDCODEMP and AP.BDCODCOL = C.BDCODCOL) '||
               'left outer join VRH_EMP_TCOL_FIS F on (F.BDCODEMP = C.BDCODEMP and F.BDCODCOL = C.BDCODCOL) '||
               'left outer join VRH_EMP_TCOL_DOC D2 on (D2.BDCODEMP = C.BDCODEMP and D2.BDCODCOL = C.BDCODCOL) '||
               'left outer join VRH_EMP_TCOL_PARENT P1 on (P1.BDCODEMP = C.BDCODEMP and P1.BDCODCOL = C.BDCODCOL) '||
               'left outer join VRH_EMP_TCOLCON_DOC D1 on (D1.BDCODEMP = C.BDCODEMP and D1.BDCODCOL = C.BDCODCOL) '||
               'left outer join VRH_EMP_TCOL_ADM A on (A.BDCODEMP = C.BDCODEMP and A.BDCODCOL = C.BDCODCOL) '||
               'left outer join VRH_EMP_TCOLCON_PARTIDA P2 on (P2.BDCODEMP = C.BDCODEMP and P2.BDCODCOL = C.BDCODCOL) '||
               'left outer join VRHF_EMP_TCOL_HIST H2 on (H2.BDCODEMP = C.BDCODEMP and H2.BDCODCOL = C.BDCODCOL) '||
               'left outer join VRH_EMP_TCOL_HIST H1 on (H1.BDCODEMP = C.BDCODEMP and H1.BDCODCOL = C.BDCODCOL) '||
               'left outer join VRH_EMP_TCON_DOC D3 on (D3.BDCODEMP = C.BDCODEMP and D3.BDCODCOL = C.BDCODCOL) '||
               'left outer join VRH_EMP_TRESCISAO RESC on (RESC.BDCODEMP = C.BDCODEMP and RESC.BDCODCOL = C.BDCODCOL) '||
               'left outer join VRH_EMP_TCOL_REINTEGRACAO RE on (RE.BDCODEMP = C.BDCODEMP and RE.BDCODCOL = C.BDCODCOL) '||
               'left outer join VRH_EMP_TCOLCON_IMG IMG on (IMG.BDCODEMP = C.BDCODEMP and IMG.BDCODCOL = C.BDCODCOL) ';

  wfiltro = '';

  if (prfiltro <> '') then
     begin
       wfiltro = wfiltro||'('||prfiltro||')';
     end

  if (prdadosiniciais = 0) then
     begin
       if (wfiltro <> '') then
          wfiltro = wfiltro||' and ';

       wfiltro = wfiltro||'((upper(E.BDRHNET) = ''TRUE'') or (upper(E.BDSCIREPORT_COL) = ''TRUE''))';
     end
  else
     begin
       if (wfiltro <> '') then
          wfiltro = wfiltro||' and ';

       wfiltro = wfiltro||'(upper(coalesce(C.BDADMCOMPLETA, ''FALSE'')) = ''TRUE'')';
     end

  if (prfiltrocol > 0) then
     begin
       if (wfiltro <> '') then
          wfiltro = wfiltro||' and ';

       if (prfiltrocol = 1) then
          wfiltro = wfiltro||'(coalesce(C.BDCONTRCOL, 0) = 0)';
       else
          wfiltro = wfiltro||'(coalesce(C.BDCONTRCOL, 0) = 1)';
     end

  if (wfiltro <> '') then
     wfiltro = ' where '||wfiltro;


  for execute statement wsql||wfiltro
  into :BDCODEMPRHNET, :BDCODEMP, :BDCODCOL, :BDDATANASCCOL, :BDDATAADMCOL, :BDDATACADCOL, :BDCPFCOL, :BDDATAADICCOL,
       :BDEMAIL2COL, :wcontrcol, :BDSTATUSQC, :BDMATRICULA, :wcodcid, :BDIDRHNET, :BDADMPRELIDRHNET,
       :BDTIPOSANGUECOL, :BDCABELOSCOL, :BDOLHOSCOL, :BDALTURACOL, :BDPESOCOL, :BDSINAISCOL,
       :BDTITELEICOL, :BDZONAELEICOL, :BDSECAOELEICOL, :BDDTPRIMCNH,
       :BDNOMPAICOL, :BDNOMMAECOL, :BDNOMCONJCOL, :BDDATANASCCONJCOL, :BDCODCIDNASCCONJ,
       :BDRESERVISTACOL, :BDSUS, :BDTIPOCERTCIVILCOL, :BDTERMOCERTCIVILCOL, :BDCARTORIOCERTCIVILCOL, :BDLIVROCERTCIVILCOL,
       :BDFOLHACERTCIVILCOL, :BDDATACERTCIVILCOL, :BDREGPROF, :BDCODCIDCERTCIVIL,
       :BDDIASPRAZO1COL, :BDDIASPRAZO2COL, :BDTIPOADMCOL, :BDDESCCONTSINCOL, :BDFICHAREGCOL, :BDLIVROREGCOL, :BDNROFOLHAREGCOL, :BDNATUOCUPCOL,
       :BDDATAFIMPRAZO1COL, :BDDATAFIMPRAZO2COL, :BDREGJORTRAB,
       :BDCNPJEMPANT, :BDTRANSONUS, :BDFICHAREGANT,
       :BDSALINICOL, :BDCODTIPOCONTRATO, :BDCODPLAFUC, :BDCODTFUC, :BDCODQH, :BDCODPQUA, :BDSEGDESCOL, :BDDATATRFCOL, :BDDESCTPJORNADA,
       :BDOBSCOL,
       :BDDTAPOSENT, :BDCODPOSTESTRCOL, :wcodpais, :wcodpaisnas,
       :BDDATABAIXACOL, :BDDESLIGAMENTO,
       :BDDTEFEITO,
       :BDFOTOCOL_IMG, :BDCPF_IMG, :BDRG_IMG, :BDPIS_IMG, :BDTITELEITOR_IMG, :BDCNH_IMG, :BDCTPS_IMG
  do
    begin
      -- Verifica o salário inicial, em caso de transferido
      for select first 1 BDCODEMPORIG, BDCODCOLORIG, BDDATATRF
          from VRH_EMP_TTRANSCOL
          where BDCODEMPDEST = :BDCODEMP and BDCODCOLDEST = :BDCODCOL
      into :wemptrans, :wcoltrans, :BDDATATRFCOL
      do
        begin

          select first 1 CAST(BDSALBASECOL as dm_numeric_15_2)
          from VRH_EMP_TCOLCON_CALCDIA 
          where BDCODEMP = :wemptrans and BDCODCOL = :wcoltrans
          order by BDCODEMP, BDCODCOL, BDDATACOL
          into :BDSALINICOL;
        end

      BDCODCOLPREL = BDCODCOL;

      if (coalesce(wcontrcol, 0) = 1) then
         BDCONTRCOL = 'contribuinte';
      else
         BDCONTRCOL = 'funcionario';

      BDCODCIDNASC = null;
      if (coalesce(wcodcid, 0) > 0) then
         select first 1 BDCODIBGE from TCIDADE where BDCODCID = :wcodcid into BDCODCIDNASC;

      if (coalesce(BDCODCIDCERTCIVIL , 0) > 0) then
         select first 1 BDCODIBGE from TCIDADE where BDCODCID = :BDCODCIDCERTCIVIL into :BDCODCIDCERTCIVIL;

      if (coalesce(BDCODCIDNASCCONJ, 0) > 0) then
         select first 1 BDCODIBGE from TCIDADE where BDCODCID = :BDCODCIDNASCCONJ into :BDCODCIDNASCCONJ;

      BDCODPAIS = null;
      BDCODPAISNAS = null;
      if (coalesce(wcodpais, 0) > 0) then
         select first 1 BDCODPAISRHNET from TPAIS where BDCODPAIS = :wcodpais into :BDCODPAIS;

      if (coalesce(wcodpaisnas, 0) > 0) then
         select first 1 BDCODPAISRHNET from TPAIS where BDCODPAIS = :wcodpaisnas into :BDCODPAISNAS;


      -- Dados cadastrais por referência
      wlogrcol = null;
      BDLOGRID = null;
      wcodcid = null;
      wcodpais = null;
      select first 1 BDNOMCOL, BDENDCOL, BDNUMCOL, BDCOMPLCOL, BDBAICOL, BDCEPCOL,
                     BDDDDCELCOL, BDCELCOL, BDDDDCOL, BDFONECOL, BDEMAILCOL, BDSEXOCOL, BDDATACHEBRASILCOL,
                     BDGRAUINSTCOL, BDESTCIVCOL, BDCASADOBR, BDFILHOSBR, BDCODCLE, BDCONDICAOINGRESSO, BDTEMPORESIDENCIA,
                     BDLOGRCOL, BDCODCID, BDCODPAISRES
      from VRH_EMP_TCOLCON_CAD
      where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL
      order by BDCODEMP desc, BDCODCOL desc, BDREFCOL desc
      into :BDNOMCOL, :BDENDCOL, :BDNUMCOL, :BDCOMPLCOL, :BDBAICOL, :BDCEPCOL,
           :BDDDDCELCOL, :BDCELCOL, :BDDDDCOL, :BDFONECOL, :BDEMAILCOL, :BDSEXOCOL, :BDDATACHEBRASILCOL,
           :BDGRAUINSTCOL, :BDESTCIVCOL, :BDCASADOBR, :BDFILHOSBR, :BDCODCLE, :BDCONDICAOINGRESSO, :BDTEMPORESIDENCIA,
           :wlogrcol, :wcodcid, :wcodpais;

      if (coalesce(wlogrcol, '') <> '') then
         select first 1 BDCODLOGR from TLOGRADOURO where upper(BDDESCLOGR) = upper(:wlogrcol) into :BDLOGRID;


      BDNOMCIDESTRANGEIRO = null;
      BDCODCID = null;
      if (coalesce(wcodcid, 0) > 0) then
         select first 1 BDCODIBGE, BDNOMCID from TCIDADE where BDCODCID = :wcodcid into :BDCODCID, :BDNOMCIDESTRANGEIRO;

      BDCODPAISRES = null;
      BDDESCPAIS = null;
      if (coalesce(wcodpais, 0) > 0) then
         select first 1 BDCODPAISRHNET, BDDESCPAIS from TPAIS where BDCODPAIS = :wcodpais into :BDCODPAISRES, :BDDESCPAIS;

      -- Características físicas por referência
      wcotadef = null;
      select first 1 BDCORCOL, BDDEFFIS, BDDEFVIS, BDDEFAUD, BDDEFMEN, BDREAB, BDDEFINT, BDCOTADEF, BDDEFCOL, BDOBSDEFFISCOL, BDNMSOCIAL
      from VRH_EMP_TCOLCON_FIS
      where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL
      order by BDCODEMP desc, BDCODCOL desc, BDREFCOL desc
      into :BDCORCOL, :BDDEFFIS, :BDDEFVIS, :BDDEFAUD, :BDDEFMEN, :BDREAB, :BDDEFINT, :wcotadef, :BDDEFCOL, :BDOBSDEFFISCOL, :BDNMSOCIAL;

      if (coalesce(wcotadef, 0 ) = 2) then
         BDCOTADEF = 'TRUE';
      else
         BDCOTADEF = 'FALSE';

      -- Documentos por referência
      wcodufrg = null;
      wcoduf = null;
      wcodufcnh = null;
      select first 1 BDRGCOL, BDORGEMIRGCOL, BDDATAEMIRGCOL, BDPISCOL, BDDATAEMIPISCOL, BDCTPSCOL, BDSERIECTPSCOL, BDDATAEMICTPSCOL,
                     BDCNHCOL, BDCATCNHCOL, BDVENCCNHCOL, BDDSERIECTPSCOL, BDNUMRICCOL, BDORGAORICCOL, BDDATAEMIRICCOL, BDNUMRNECOL,
                     BDORGAORNECOL, BDDATAEMIRNECOL, BDNUMOCCOL, BDORGAOOCCOL, BDDATAEMIOCCOL, BDDATAVALOCCOL, BDORGAOCNH,
                     BDDATAEMICNH, BDCODUFRG, BDCODUF, BDUFCNH
      from VRH_EMP_TCOLCON_DOCREF
      where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL
      order by BDCODEMP desc, BDCODCOL desc, BDREFCOL desc
      into :BDRGCOL, :BDORGEMIRGCOL, :BDDATAEMIRGCOL, :BDPISCOL, :BDDATAEMIPISCOL, :BDCTPSCOL, :BDSERIECTPSCOL, :BDDATAEMICTPSCOL,
           :BDCNHCOL, :BDCATCNHCOL, :BDVENCCNHCOL, :BDDSERIECTPSCOL, :BDNUMRICCOL, :BDORGAORICCOL, :BDDATAEMIRICCOL, :BDNUMRNECOL,
           :BDORGAORNECOL, :BDDATAEMIRNECOL, :BDNUMOCCOL, :BDORGAOOCCOL, :BDDATAEMIOCCOL, :BDDATAVALOCCOL, :BDORGAOCNH,
           :BDDATAEMICNH, :wcodufrg, :wcoduf, :wcodufcnh;

      BDCODUFRG = null;
      BDCODUF = null;
      BDUFCNH = null;
      if (coalesce(wcodufrg, 0) > 0) then
         select first 1 BDSIGLAUF from TUF where BDCODUF = :wcodufrg into :BDCODUFRG;

      if (coalesce(wcoduf, 0) > 0) then
         select first 1 BDSIGLAUF from TUF where BDCODUF = :wcoduf into :BDCODUF;

      if (coalesce(wcodufcnh, 0) > 0) then
         select first 1 BDSIGLAUF from TUF where BDCODUF = :wcodufcnh into :BDUFCNH;

      -- Dados relavantes do para cálculo, por referência
      select first 1 BDTIPOCOL, BDHORASMENSAISCOL, BDHORASSEMANAISCOL, BDHORASDIARIASCOL, BDPERCINSALUBCOL, BDINCIDINSALUBCOL,
                     BDPERCPERCULCOL, BDINCIDPERICULCOL, BDPERCNOTURNOCOL, BDINCIDNOTURNOCOL, BDCALCVALREFCOL,
                     case when BDPERCADISAL > 0 then 1 else 0 end, BDREGIMEPARCIALCOL, BDCALCVALTRANSCOL,
                     BDCARTAOVA, BDCARTAOVR, BDCARTAOVT, BDPERCADISAL
      from VRHF_EMP_TCOL_CALC
      where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL
      order by BDCODEMP desc, BDCODCOL desc, BDREFCOL desc
      into :BDTIPOCOL, :BDHORASMENSAISCOL, :BDHORASSEMANAISCOL, :BDHORASDIARIASCOL, :BDPERCINSALUBCOL, :BDINCIDINSALUBCOL,
           :BDPERCPERCULCOL, :BDINCIDPERICULCOL, :BDPERCNOTURNOCOL, :BDINCIDNOTURNOCOL, :BDCALCVALREFCOL,
           :BDADIANTAMENTO, :BDREGIMEPARCIALCOL, :BDCALCVALTRANSCOL,
           :BDCARTAOVA, :BDCARTAOVR, :BDCARTAOVT, :BDPERCADISAL;

      -- Admissionais por referência
      select first 1 BDSINDICALIZADOCOL
      from VRH_EMP_TCOL_ADMREF
      where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL
      order by BDCODEMP desc, BDCODCOL desc, BDREFCOL desc
      into :BDSINDICALIZADOCOL;

      -- Vínculos por referência
      select first 1 CLA.BDGRUPOCLA 
      from VRH_EMP_TCOLCON_VINC V1
      join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = V1.BDCODCLA)
      where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL
      order by BDCODEMP desc, BDCODCOL desc, BDREFCOL desc
      into :BDCODCLA;

      -- Dados bancários
      select first 1 BDCODBAN, BDCTADEPCOL, BDTIPOCTACOL, BDCODAG, BDDIGCTADEPCOL, BDCARTAOSALCOL, BDMODOPAGTOCOL
      from VRHF_EMP_TCOLCON_BANCO
      where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL
      order by BDCODEMP desc, BDCODCOL desc, BDREFCOL desc
      into :BDCODBAN, :BDCTADEPCOL, :BDTIPOCTACOL, :BDCODAG, :BDDIGCTADEPCOL, :BDCARTAOSALCOL, :BDMODOPAGTOCOL;

      select first 1 BDCODSINTRAB
      from VRH_EMP_TCOL_VINC
      where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL
      order by BDCODEMP desc, BDCODCOL desc, BDREFCOL desc
      into :BDCODSINTRAB;

      select first 1 BDCATEGORIAESOCIAL, BDOCORRENCIACOL, BDCTAFGTSCOL, BDREGPREV, BDREGIMETRAB
      from VRHF_EMP_TCOLCON_FGTSGPS
      where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL
      order by BDCODEMP desc, BDCODCOL desc, BDREFCOL desc
      into :BDCATEGORIAESOCIAL, :BDOCORRENCIACOL, :BDCTAFGTSCOL, :BDREGPREV, :BDREGIMETRAB;

      select first 1 BDFORMAPAGTOCOL, BDVALORPREVPRIVNCOL, BDVALORPREVPRIV13COL
      from VRHF_EMP_TCOLCON_CALC
      where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL
      order by BDCODEMP desc, BDCODCOL desc, BDREFCOL desc
      into :BDFORMAPAGTOCOL, :BDVALORPREVPRIVNCOL, :BDVALORPREVPRIV13COL;

      select first 1 case when BDTIPOJORNADA = -1 then null else COALESCE(BDTIPOJORNADA, 0) end, BDDESCTPJORNADA
      from VRH_EMP_TCOL_VINCDIA
      where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL
      order by BDCODEMP desc, BDCODCOL desc, BDDATACOL desc
      into :BDTIPOJORNADA, :wdescjor;

      if (trim(coalesce(BDDESCTPJORNADA, '')) = '') then
         BDDESCTPJORNADA = wdescjor;

      select first 1 BDINDHORARIONOT
      from VRH_EMP_TCOL_VINCDIA
      where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL
      order by BDCODEMP, BDCODCOL, BDDATACOL
      into :BDINDHORARIONOT;

      BDINDHORARIONOT = coalesce(BDINDHORARIONOT, 0);
      if (BDINDHORARIONOT = 2) then
         BDINDHORARIONOT = 0;      -- Não
      else
      if (BDINDHORARIONOT = 1) then
         BDINDHORARIONOT = 1;      -- Sim
      else
         BDINDHORARIONOT = 2;      -- Nenhum


      suspend;
    end
end^

create or alter procedure SP_GRAVANFPRODRURAL (
    PRSESSAO integer,
    PRULTCHAVE integer)
as
declare variable WCODEMP integer;
declare variable WCHAVEEF integer;
declare variable WDATAEMISSAO date;
declare variable WNUMDOC integer;
declare variable WREFNF varchar(6);
declare variable WRETINSS numeric(15,2);
declare variable WVLRNF numeric(15,2);
declare variable WCHAVERH integer;
declare variable WTPCOMERC integer;
declare variable WCNPJTER varchar(18);
declare variable WSERIE varchar(15);
declare variable WVLRFUNRURAL numeric(15,2);
declare variable BDVLRGILRAT numeric(15,2);
declare variable BDVLRSENAR numeric(15,2);
begin
  For 
  SELECT MOV.BDCODEMP, MOV.BDEDITCHAVE BDCHAVE, (SELECT BDDATA FROM SP_PARSE_DATE(BDDATAEMISSAO, 'YYYYMM')) BDREFNF,
         MOV.BDNUMDOCINI, MOV.BDDATAEMISSAO, (MOV.BDVALORNOTA) BDVALNF,
         CASE RURAL.BDORDEMINDCOM
            WHEN 5 THEN '1'
            WHEN 4 THEN '3'
            WHEN 3 THEN '5'
            ELSE '0'
         END AS BDORDEMINDCOM,
         MOV.BDCNPJ, MOV.BDSERIE,
         RURAL.BDVLRFUNRURAL, RURAL.BDVLRGILRAT, RURAL.BDVLRSENAR
  FROM (SELECT *
        FROM TMP_VEF_EMP_TMOVSAI_TEMP S
        WHERE S.BDSESSAO = :PRSESSAO
        and (NOT S.BDCODSITNF IN(2, 3, 4, 5))
        AND NOT EXISTS (
                        SELECT INCO.BDCODINCONSISTENCIAMOVSAI
                        FROM VEF_INCON_TMOVSAI INCO
                        WHERE INCO.BDSESSAO = S.BDSESSAO
                        AND INCO.BDCODEMP = S.BDCODEMP
                        AND INCO.BDCHAVE = S.BDCHAVE
                       )
       ) MOV  
  LEFT OUTER JOIN TMP_VEF_TMOVSAIFUNRURAL_TEMP RURAL ON(RURAL.BDSESSAO = MOV.BDSESSAO AND RURAL.BDCODEMP = MOV.BDCODEMP AND RURAL.BDCHAVE = MOV.BDCHAVE)
--  WHERE RURAL.BDORDEMINDCOM in (3,4,5,6)
  INTO
  :WCODEMP, :WCHAVEEF, :WREFNF, :WNUMDOC, :WDATAEMISSAO, :WVLRNF, :WTPCOMERC, :WCNPJTER, :WSERIE, :WVLRFUNRURAL, :BDVLRGILRAT, :BDVLRSENAR do
  BEGIN
    delete from TOL_VEF_EMP_TCOMERCNFPRODRURAL where BDCODEMP = :WCODEMP AND bdchave_ef = :WCHAVEEF;

    /* o registro pode ter sido alterado entao vai excluir mas nao pode gerar outro lançamento */
    if ((CHAR_LENGTH(WCNPJTER) > 14) or (:WTPCOMERC = '0'))  then
       Continue;

    :WCHAVERH = 0;
    SELECT BDCHAVE_RH FROM TOL_VEF_EMP_TCOMERCNFPRODRURAL WHERE BDCODEMP = :WCODEMP AND BDCHAVE_EF = :WCHAVEEF
    INTO :WCHAVERH;

    IF (:WCHAVERH = 0) THEN
       :WCHAVERH = :PRULTCHAVE;

    UPDATE OR INSERT INTO VRH_EMP_TCOMERCNFPRODRURAL (BDCODEMP, BDCHAVE, BDREFNF, BDTPCOMERC, BDCNPJADQ, BDSERIENF, BDNOTAFISCAL, BDEMISSAONF, BDVALNF, BDINSS, BDGILRAT, BDSENAR, BDTIPOLAN)
    VALUES(:WCODEMP, :WCHAVERH, :WREFNF, :WTPCOMERC, :WCNPJTER, :WSERIE, :WNUMDOC, :WDATAEMISSAO, :WVLRNF, :WVLRFUNRURAL, :BDVLRGILRAT, :BDVLRSENAR, 100) MATCHING(BDCODEMP, BDCHAVE); -- Integra  o fiscal
    
    UPDATE OR INSERT INTO TOL_VEF_EMP_TCOMERCNFPRODRURAL (BDCODEMP, BDCHAVE_RH, BDCHAVE_EF)
    VALUES(:WCODEMP, :WCHAVERH, :WCHAVEEF)MATCHING(BDCODEMP, BDCHAVE_RH, BDCHAVE_EF);
    :PRULTCHAVE = :PRULTCHAVE - 1;
  END
end^

create or alter procedure SP_INATIVA_TERCEIROS_DUPLICADOS (
    P_TIPO_INATIVACAO integer,
    P_IGNORAR_ZERADOS DM_BOOLEAN,
    P_FILTRO_CODCNAE integer,
    P_FILTRO_PJPF varchar(20),
    P_FILTRO_CODCID integer,
    P_FILTRO_PRURAL DM_BOOLEAN,
    P_FILTRO_CGCTER varchar(18),
    P_FILTRO_CODUF integer,
    P_REFERENCIA integer)
returns (
    QNTINATIVOS integer)
as
declare variable WCODTERLIST varchar(30000);
declare variable WREFLIST varchar(30000);
declare variable WCOUNT integer;
declare variable WEXECUTE_STATEMENT integer;
declare variable WTABELA varchar(100);
declare variable VSQL varchar(32000);
declare variable VSQL_REF varchar(1000);
declare variable V_BDCODTER integer;
declare variable V_BDREFEMP integer;
BEGIN
  WEXECUTE_STATEMENT = 1;
  QNTINATIVOS = 0;

FOR 
WITH LISTA_BASE AS (
    SELECT * FROM (
        SELECT
            T1.BDCODTER,
            T1.BDREFEMP,
            T1.BDIETER,
            REPLACE(REPLACE(REPLACE(T1.BDCGCTER, '.', ''), '/', ''), '-', '') AS CNPJ_LIMPO
        FROM TTERCEIRO_REF T1
        WHERE
            (:P_FILTRO_CGCTER IS NULL OR T1.BDCGCTER = :P_FILTRO_CGCTER)

            AND (:P_FILTRO_CODCID IS NULL OR T1.BDCODCID = :P_FILTRO_CODCID)

            AND (:P_FILTRO_PRURAL IS NULL OR COALESCE(T1.BDPRURALTER, 'FALSE') = :P_FILTRO_PRURAL)

            AND (:P_FILTRO_CODCNAE IS NULL OR T1.BDCODCNAE = :P_FILTRO_CODCNAE)

            AND (
                :P_FILTRO_PJPF IS NULL OR
                (:P_FILTRO_PJPF = 'PF' AND CHAR_LENGTH(T1.BDCGCTER) <= 14) OR
                (:P_FILTRO_PJPF <> 'PF' AND CHAR_LENGTH(T1.BDCGCTER) > 14)
            )

            AND (
                :P_FILTRO_CODUF IS NULL OR
                EXISTS (
                    SELECT 1
                    FROM TCIDADE C
                    WHERE C.BDCODCID = T1.BDCODCID
                    AND C.BDCODUF = :P_FILTRO_CODUF
                )
            )

            AND (
                :P_REFERENCIA IS NULL OR
                T1.BDREFEMP = (
                    SELECT MAX(T2.BDREFEMP)
                    FROM TTERCEIRO_REF T2
                    WHERE T2.BDCODTER = T1.BDCODTER
                    AND T2.BDREFEMP <= :P_REFERENCIA
                )
            )

            AND (
                :P_IGNORAR_ZERADOS <> 'TRUE'
                OR (
                    T1.BDCGCTER IS NOT NULL
                    AND T1.BDCGCTER NOT IN (
                        '99.999.999/9999-99',
                        '00.000.000/0000-00',
                        ''
                    )
                    AND REPLACE(REPLACE(REPLACE(REPLACE(T1.BDCGCTER, '.', ''), '/', ''), '-', ''), '0', '') <> ''
                )
            )

            AND COALESCE(T1.BDINATIVO, 'FALSE') = 'FALSE'
            AND T1.BDCGCTER IS NOT NULL
            AND T1.BDCGCTER NOT IN ('99.999.999/9999-99', '00.000.000/0000-00', '')
    )
    WHERE CNPJ_LIMPO NOT IN ('99999999999999', '00000000000000', '', '00000000000','99999999999')
),

/* NOVA CTE PARA TRATAR IE */
LISTA_BASE_IE AS (
    SELECT LB.*
    FROM LISTA_BASE LB
    WHERE 
        :P_TIPO_INATIVACAO <> 1
        OR EXISTS (
            SELECT 1
            FROM LISTA_BASE X
            WHERE 
                X.CNPJ_LIMPO = LB.CNPJ_LIMPO
                AND COALESCE(X.BDIETER, '') = COALESCE(LB.BDIETER, '')
            GROUP BY 
                X.CNPJ_LIMPO,
                COALESCE(X.BDIETER, '')
            HAVING COUNT(*) > 1
        )
),

MINIMOS AS (
    SELECT 
        CNPJ_LIMPO, 
        IIF(:P_TIPO_INATIVACAO = 1,BDIETER,1) BDIETER,
        Min(BDCODTER) as MENOR_CODIGO
    FROM LISTA_BASE_IE
    GROUP BY 1,2
    HAVING COUNT(*) > 1
)

SELECT b.BDCODTER, b.BDREFEMP
FROM LISTA_BASE_IE B
JOIN MINIMOS M ON B.CNPJ_LIMPO = M.CNPJ_LIMPO and IIF(:P_TIPO_INATIVACAO = 1,B.BDIETER,1) = M.BDIETER
WHERE B.BDCODTER > M.MENOR_CODIGO

INTO :v_BDCODTER, :v_BDREFEMP
  DO
  BEGIN
    UPDATE TTERCEIRO 
    SET BDINATIVO = 'TRUE' 
    WHERE BDCODTER = :v_BDCODTER 
      AND COALESCE(BDINATIVO,'FALSE') = 'FALSE';

    UPDATE TTERCEIRO_REF 
    SET BDINATIVO = 'TRUE' 
    WHERE BDCODTER = :v_BDCODTER 
      AND BDREFEMP = :v_BDREFEMP  
      AND COALESCE(BDINATIVO,'FALSE') = 'FALSE';

    QNTINATIVOS = QNTINATIVOS + 1;
    DELETE FROM TMP_TTERCEIRO a WHERE BDCODTER = :v_BDCODTER;
  END

END^

create or alter procedure SP_TROCAGLOBAL_TERCEIROS (
    P_FILTRO_CODCNAE integer,
    P_FILTRO_PJPF varchar(20),
    P_FILTRO_CODCID integer,
    P_FILTRO_PRURAL DM_BOOLEAN,
    P_FILTRO_REF integer,
    P_FILTRO_CGCTER varchar(18),
    P_PRURAL_DE DM_BOOLEAN,
    P_PRURAL_PARA DM_BOOLEAN,
    P_CARAC_DE integer,
    P_CARAC_PARA integer,
    P_INATIVAR_REPETIDO DM_BOOLEAN,
    P_TIPO_INATIVACAO integer,
    P_IGNORAR_ZERADOS DM_BOOLEAN,
    P_FILTRO_CODUF integer)
returns (
    P_QTD_INATIVADOS integer)
as
declare variable W_QTD_INATIVADOS integer;
declare variable WSQL varchar(32000);
declare variable W_CAMPO_ATUALIZAR varchar(50);
declare variable W_VALOR_ATUALIZAR varchar(100);
BEGIN
    /* =========================================================
       1 - INATIVA PARTICIPANTES DUPLICADOS
       ========================================================= */
    P_QTD_INATIVADOS = 0;
    W_CAMPO_ATUALIZAR = '';
    IF (:P_INATIVAR_REPETIDO = 'TRUE') THEN
    BEGIN
        EXECUTE PROCEDURE SP_INATIVA_TERCEIROS_DUPLICADOS(
            :P_TIPO_INATIVACAO,
            :P_IGNORAR_ZERADOS,
            :P_FILTRO_CODCNAE,
            :P_FILTRO_PJPF,
            :P_FILTRO_CODCID,
            :P_FILTRO_PRURAL,
            :P_FILTRO_CGCTER,
            :P_FILTRO_CODUF,
            :P_FILTRO_REF
        )
        RETURNING_VALUES :W_QTD_INATIVADOS;

        P_QTD_INATIVADOS = :W_QTD_INATIVADOS;
    END

    /* =========================================================
       2 - TROCA CARACTERÍSTICA TRIBUTÁRIA - Como é o primeiro, fica fora do loop
       ========================================================= */
    IF (:P_CARAC_DE <> :P_CARAC_PARA AND :W_CAMPO_ATUALIZAR = '') THEN
    BEGIN
        W_CAMPO_ATUALIZAR = 'R.BDCARACTRIBUTARIATER';
        W_VALOR_ATUALIZAR = '''' ||:P_CARAC_PARA || '''';
    END

    WHILE (W_CAMPO_ATUALIZAR IS NOT NULL) DO
    BEGIN
        /* =========================================================
           3 - TROCA PRODUTOR RURAL
           ========================================================= */
        IF (:P_PRURAL_DE <> :P_PRURAL_PARA AND :W_CAMPO_ATUALIZAR = '') THEN
        BEGIN
            W_CAMPO_ATUALIZAR = 'R.BDPRURALTER';
            W_VALOR_ATUALIZAR = '''' || :P_PRURAL_PARA || '''';
        END

        IF (:W_CAMPO_ATUALIZAR <> '') Then
          Begin
            WSQL =
                'MERGE INTO TTERCEIRO_REF R ' ||
                'USING ( ' ||
                ' SELECT R2.BDCODTER, R2.BDREFEMP ' ||
                ' FROM TMP_TTERCEIRO T ' ||
                ' JOIN TTERCEIRO_REF R2 ON R2.BDCODTER = T.BDCODTER ';
    
            IF (:P_FILTRO_CODUF IS NOT NULL) THEN
                WSQL = WSQL || ' JOIN TCIDADE C ON C.BDCODCID = R2.BDCODCID ';
    
            WSQL = WSQL || ' WHERE 1=1 ';
    
            IF (:P_FILTRO_CGCTER IS NOT NULL) THEN
                WSQL = WSQL || ' AND T.BDCGCTER = ''' || :P_FILTRO_CGCTER || ''' ';
    
            IF (:P_FILTRO_PJPF IS NOT NULL) THEN
            BEGIN
                IF (:P_FILTRO_PJPF = 'PF') THEN
                    WSQL = WSQL || ' AND CHAR_LENGTH(T.BDCGCTER) <= 14 ';
                ELSE
                    WSQL = WSQL || ' AND CHAR_LENGTH(T.BDCGCTER) > 14 ';
            END
    
            IF (:P_CARAC_DE > 0 AND :W_CAMPO_ATUALIZAR = 'R.BDCARACTRIBUTARIATER') THEN
              WSQL = WSQL || ' AND BDCARACTRIBUTARIATER = '||:P_CARAC_DE|| ' ';

            IF (:P_PRURAL_DE <> '' AND :W_CAMPO_ATUALIZAR = 'R.BDPRURALTER') THEN
              WSQL = WSQL || ' AND COALESCE(BDPRURALTER,''FALSE'') = '||:P_PRURAL_DE|| ' ';

            IF (:P_FILTRO_CODCID IS NOT NULL) THEN
                WSQL = WSQL || ' AND R2.BDCODCID = ' || :P_FILTRO_CODCID;
    
            IF (:P_FILTRO_CODCNAE IS NOT NULL) THEN
                WSQL = WSQL || ' AND R2.BDCODCNAE = ' || :P_FILTRO_CODCNAE;
    
            IF (:P_FILTRO_PRURAL = 'TRUE') THEN
                WSQL = WSQL || ' AND COALESCE(BDPRURALTER,''FALSE'') = UPPER(''' || :P_FILTRO_PRURAL || ''') ';
    
            IF (:P_FILTRO_CODUF IS NOT NULL) THEN
                WSQL = WSQL || ' AND C.BDCODUF = ' || :P_FILTRO_CODUF;
    
            IF (:P_FILTRO_REF IS NOT NULL) THEN
                WSQL = WSQL ||
                    ' AND R2.BDREFEMP = COALESCE( ' ||
                    '   (SELECT FIRST 1 X.BDREFEMP FROM TTERCEIRO_REF X ' ||
                    '     WHERE X.BDCODTER = R2.BDCODTER ' ||
                    '       AND X.BDREFEMP <= ' || :P_FILTRO_REF ||
                    '     ORDER BY X.BDREFEMP DESC), ' ||
                    '   (SELECT FIRST 1 X.BDREFEMP FROM TTERCEIRO_REF X ' ||
                    '     WHERE X.BDCODTER = R2.BDCODTER ' ||
                    '     ORDER BY X.BDREFEMP) ) ';
    
            WSQL = WSQL || ' GROUP BY R2.BDCODTER, R2.BDREFEMP ';
            WSQL = WSQL || ') SRC ' ||
                   'ON (R.BDCODTER = SRC.BDCODTER AND R.BDREFEMP = SRC.BDREFEMP) ' ||
                   'WHEN MATCHED THEN UPDATE SET ' ||
                   W_CAMPO_ATUALIZAR || ' = ' || W_VALOR_ATUALIZAR;
    
            EXECUTE STATEMENT WSQL;

            if (:W_CAMPO_ATUALIZAR <> 'R.BDPRURALTER') then
              :W_CAMPO_ATUALIZAR = '';
            Else
              :W_CAMPO_ATUALIZAR = null;

          End
        Else
          W_CAMPO_ATUALIZAR = null;
    END
    suspend;
END^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TECONSIGNADO5003_BI0 FOR VRHF_TEMP_EMP_TECONSIGNADO5003
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE WEXISTEREGISTRO INTEGER;
DECLARE VARIABLE VCODIGO INTEGER;
begin
  /* Trigger text */
  VCODIGO = 0;
  if ((new.BDCODSEQ is null) or (new.BDCODSEQ = 0)) then
  begin
    select coalesce((max(BDCODSEQ) + 1), 1)
    from VRHF_TEMP_EMP_TECONSIGNADO5003
    where BDSESSAO = NEW.BDSESSAO
    into VCODIGO;

    new.BDCODSEQ = VCODIGO;
  end

  if (COALESCE(NEW.BDZERADO, 'FALSE') = 'FALSE') then
     begin
       if (NEW.BDUNICO = 2) then
         BEGIN
           WEXISTEREGISTRO = 0;
           select BDSESSAO from VRHF_TEMP_EMP_TECONSIGNADO5003
           where BDSESSAO = NEW.BDSESSAO and
                 BDCODEMP = NEW.BDCODEMP and
                 BDCPFCOL = NEW.BDCPFCOL and
                 BDCODCOL = NEW.BDCODCOL and
                 BDUNICO = 1 and
                 BDTAGSTR = NEW.BDTAGSTR and
                 BDINSTITUICAOFINANC = NEW.BDINSTITUICAOFINANC and
                 BDNROCONTRATOECONSIGNADO = NEW.BDNROCONTRATOECONSIGNADO
           INTO :WEXISTEREGISTRO;
        
           if (COALESCE(WEXISTEREGISTRO, 0) = 0) then
              BEGIN
                INSERT INTO VRHF_TEMP_EMP_TECONSIGNADO5003
                (BDSESSAO, BDCODSEQ, BDCODEMP, BDCPFCOL, BDCODCOL, BDUNICO, BDTAGSTR, BDDESCRICAOLINK, BDZERADO, BDCODEMPORD,
                 BDINSTITUICAOFINANC, BDNROCONTRATOECONSIGNADO, BDVALOR,
                 BDGRUPOCLA, BDCONTRCOL, BDCNPJEMP, BDCATEGORIAESOCIAL, BDRESCISORIO)
                VALUES
                (NEW.BDSESSAO, :VCODIGO+1, NEW.BDCODEMP, NEW.BDCPFCOL, NEW.BDCODCOL, 1, '', '', TRUE, NEW.BDCODEMPORD,
                 NEW.BDINSTITUICAOFINANC, NEW.BDNROCONTRATOECONSIGNADO, null,
                 NEW.BDGRUPOCLA, NEW.BDCONTRCOL, NEW.BDCNPJEMP, NEW.BDCATEGORIAESOCIAL, NEW.BDRESCISORIO);
              END

           DELETE from VRHF_TEMP_EMP_TECONSIGNADO5003
           where BDSESSAO = NEW.BDSESSAO and
                 BDCPFCOL = NEW.BDCPFCOL and
                 BDUNICO = 2 and
--                 BDTAGSTR = '' and
                 BDINSTITUICAOFINANC = NEW.BDINSTITUICAOFINANC and
                 BDNROCONTRATOECONSIGNADO = NEW.BDNROCONTRATOECONSIGNADO and
                 BDZERADO = TRUE AND
                 BDCODEMPORD = NEW.BDCODEMPORD;

         END
       ELSE if (NEW.BDUNICO = 1) then
         BEGIN
           WEXISTEREGISTRO = 0;
           select BDSESSAO from VRHF_TEMP_EMP_TECONSIGNADO5003
           where BDSESSAO = NEW.BDSESSAO and
--                 BDCODEMP = NEW.BDCODEMP and --
                 BDCPFCOL = NEW.BDCPFCOL and
--                 BDCODCOL = NEW.BDCODCOL and --
                 BDUNICO = 2 and
                 BDTAGSTR = '' and
                 BDINSTITUICAOFINANC = NEW.BDINSTITUICAOFINANC and
                 BDNROCONTRATOECONSIGNADO = NEW.BDNROCONTRATOECONSIGNADO
           INTO :WEXISTEREGISTRO;
        
           if (COALESCE(WEXISTEREGISTRO, 0) = 0) then
              BEGIN
                INSERT INTO VRHF_TEMP_EMP_TECONSIGNADO5003
                (BDSESSAO, BDCODSEQ, BDCODEMP, BDCPFCOL, BDCODCOL, BDUNICO, BDTAGSTR, BDDESCRICAOLINK, BDZERADO, BDCODEMPORD,
                 BDINSTITUICAOFINANC, BDNROCONTRATOECONSIGNADO, BDVALOR,
                 BDGRUPOCLA, BDCONTRCOL, BDCNPJEMP, BDCATEGORIAESOCIAL, BDRESCISORIO)
                VALUES
                (NEW.BDSESSAO, :VCODIGO+1, NEW.BDCODEMP, NEW.BDCPFCOL, NEW.BDCODCOL, 2, '', '', TRUE, NEW.BDCODEMPORD,
                 NEW.BDINSTITUICAOFINANC, NEW.BDNROCONTRATOECONSIGNADO, null,
                 NEW.BDGRUPOCLA, NEW.BDCONTRCOL, NEW.BDCNPJEMP, NEW.BDCATEGORIAESOCIAL, NEW.BDRESCISORIO);
              END

           DELETE from VRHF_TEMP_EMP_TECONSIGNADO5003
           where BDSESSAO = NEW.BDSESSAO and
                 BDCPFCOL = NEW.BDCPFCOL and
                 BDUNICO = 1 and
--                 BDTAGSTR = '' and
                 BDINSTITUICAOFINANC = NEW.BDINSTITUICAOFINANC and
                 BDNROCONTRATOECONSIGNADO = NEW.BDNROCONTRATOECONSIGNADO and
                 BDZERADO = TRUE AND
                 BDCODEMPORD = NEW.BDCODEMPORD;

         END
     end
end
^

create or alter procedure SP_VRH_VALORES_TOT_FGTS (
    PRCODEMP varchar(30000),
    PRREFARQ integer,
    PRTIPOEVT integer,
    PRVERSAO integer,
    PRCPF varchar(30000))
returns (
    BDCODIGO integer,
    BDREFARQ integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDXML blob sub_type 0 segment size 80,
    BDVERSAO integer,
    BDXMLLOTE blob sub_type 0 segment size 80,
    BDIDLOTE varchar(100))
as
declare variable WSQL varchar(32000);
declare variable WSQLAUX varchar(500);
declare variable WCOUNT integer;
declare variable WCODEVT integer;
declare variable WREFARQ integer;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WCODEVTORIG integer;
declare variable WVER integer;
declare variable WLISTAEMP varchar(30000);
declare variable WXMLLOTE blob sub_type 0 segment size 80;
declare variable WIDLOTE varchar(100);
begin

  if (position('=', PRCODEMP) > 0) then
     WLISTAEMP = SUBSTRING(PRCODEMP from position('=', PRCODEMP)+1 for CHAR_LENGTH(PRCODEMP));
  if (position('in', PRCODEMP) > 0) then
     WLISTAEMP = SUBSTRING(PRCODEMP from position('in', PRCODEMP)+2 for CHAR_LENGTH(PRCODEMP));

  if (position('(', WLISTAEMP) > 0) then
     WLISTAEMP = ' ((coalesce(E.BDCODMATRIZ, E.BDCODEMP) in ' || WLISTAEMP || ')) ';
  else
     WLISTAEMP = ' (coalesce(E.BDCODMATRIZ, E.BDCODEMP) in (' || WLISTAEMP || '))) ';

  wsql = ' select ARQ.BDCODIGO, ARQ.BDREFARQ, ARQ.BDCODEMP, ARQ.BDCODCOL, XML.BDXML, ARQ.BDCODEVENTOORIG '||
         ' from VRH_ESOCIAL_TARQUIVO ARQ '||
         ' inner join VRH_ESOCIAL_TARQUIVO_XML XML on (ARQ.BDCODIGO = XML.BDCODIGO and ARQ.BDCODEMP = XML.BDCODEMP)' ||
         ' join VRH_EMP_TCOLCON C on C.BDCODEMP = ARQ.BDCODEMP and C.BDCODCOL = ARQ.BDCODCOL '||
         ' left outer join VRH_EMP_TCOLCON_DOC DOC on (DOC.BDCODEMP = ARQ.BDCODEMP and DOC.BDCODCOL = ARQ.BDCODCOL) '||
         ' where ARQ.BDCODEMP in (select E.BDCODEMP from TEMPRESAS E where '||WLISTAEMP||' '||
         ' and ARQ.BDSTATUS = 2 and ARQ.BDCODTIPO = '||prtipoevt||' and ARQ.BDREFARQ = '||prrefarq;

  if (prcpf <> '') then
    begin
      wsql = wsql||' and (doc.bdcpfcol '||prcpf||') ';
    end


  for execute statement wsql into :wcodevt, :wrefarq, :wcodemp, :wcodcol, :BDXML, :wcodevtorig do
    begin
       bdcodigo = null;
       bdrefarq = null;
       bdcodemp = null;
       bdcodcol = null;
       bdversao = null;
       wver     = 0;
       wcount   = 0;
       bdxmllote = null;
       bdidlote = null;
       wxmllote = null;
       widlote = null;

       if (wcodcol > 0) then
         begin
           wsqlaux = 'select first 1 BDCODCOL, BDVERSAO from VRH_ESOCIAL_INFOBASEFGTS_C '||
                     'where BDCODEMP = '||wcodemp||' and '||
                           'BDCODCOL = '||wcodcol||' and '||
--                           'BDCODEVT in ('||wcodevtorig||','||wcodevt||')';
                           'BDCODEVT = '||wcodevtorig;

           execute statement wsqlaux into :wcount, :wver;

           if (wver is null) then
              wver = 0;

           if ((wcount is null) or (prversao > wver)) then
              begin
                wsqlaux = 'delete from VRH_ESOCIAL_INFOBASEFGTS_C '||
                          'where BDCODEMP = '||wcodemp||' and '||
                                'BDCODCOL = '||wcodcol||' and '||
--                                'BDCODEVT in ('||wcodevtorig||','||wcodevt||')';
                                'BDCODEVT = '||wcodevtorig;
                execute statement wsqlaux;

                wsqlaux = 'delete from VRH_ESOCIAL_CREDITOTRAB_C '||
                          'where BDCODEMP = '||wcodemp||' and '||
                                'BDCODCOL = '||wcodcol||' and '||
--                                'BDCODEVT in ('||wcodevtorig||','||wcodevt||')';
                                'BDCODEVT = '||wcodevtorig;
                execute statement wsqlaux;

                bdcodigo = wcodevtorig;
                bdrefarq = wrefarq;
                bdcodemp = wcodemp;
                bdcodcol = wcodcol;
                bdversao = wver + prversao;

                select FIRST 1 A.BDXML,arq.bdidevento
                from VRH_ESOCIAL_TLOTE_ARQUIVOS A
                join VRH_ESOCIAL_TARQUIVO ARQ on A.BDCODEMP = ARQ.BDCODEMP and A.BDCODLOTE = ARQ.BDCODLOTE
                where ARQ.BDCODTIPO in (11,34,37) and ARQ.BDCODIGO = :wcodevtorig
                order by A.BDCODLOTE desc
                into :wxmllote, :widlote;

                bdxmllote = wxmllote;
                bdidlote = widlote;

                suspend;
              end
         end
    end
end^

create or alter procedure SP_DET_CREDITO_TRABALHADOR_ADTO (
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000),
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODVER integer,
    BDDESCVER varchar(40),
    BDCLAVER varchar(20),
    BDVALORVERBA numeric(15,6),
    BDTIPOFOLHA integer,
    BDTIPOCODVER integer,
    BDDATA date)
as
declare variable WSQLAD varchar(30000);
declare variable WSQLFN varchar(30000);
declare variable WREFERENCIA varchar(6);
declare variable WCODCOLANT integer;
declare variable WCODEMPANT integer;
declare variable WTEMPARCELAMENTO integer;
declare variable WCODEMP varchar(30000);
declare variable WCODEMPCALC integer;
declare variable WCODCOL integer;
declare variable WCODVER integer;
declare variable WDESCVER varchar(40);
declare variable WCLAVER varchar(20);
declare variable WVALORVERBA numeric(15,6);
declare variable WTIPOFOLHA integer;
declare variable WTIPOCODVER integer;
declare variable WTIPOCODVERAUX integer;
declare variable WDATA date;
begin
  WREFERENCIA           = PRREF;
  WCODCOLANT            = 0;
  WCODEMPANT            = 0;

  /* Select folha de adiantamento salarial */
  WSQLAD = 'select CALC.BDDATAAD, CALC.BDCODEMP, CALC.BDCODCOL, VERBASAD.BDCODVER, VERBAS.BDDESCVER, VERBAS.BDCLAVER, VERBASAD.BDVALVAD, 0 BDTIPOFOLHA, VERBASREF.BDTIPOCODVER '||
           'from VRHF_EMP_TADSAL CALC '||
           'left outer join VRHF_EMP_TVERBAAD VERBASAD on (VERBASAD.BDCODEMP = CALC.BDCODEMP) and '||
                 '(VERBASAD.BDCODCOL = CALC.BDCODCOL) and '||
                 '(VERBASAD.BDDATAAD = CALC.BDDATAAD) '||
           'left outer join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = VERBASAD.BDCODVER) '||
           'left outer join VRH_BASE_TVERBAS_REF VERBASREF on (VERBAS.BDCODVER = VERBASREF.BDCODVER) and '||
                                                           '(VERBASREF.BDREFVER = (select max(X.BDREFVER) '||
                                                                                  'from VRH_BASE_TVERBAS_REF X '||
                                                                                  'where X.BDCODVER = VERBAS.BDCODVER and '||
                                                                                        'X.BDREFVER <= '||WREFERENCIA||')) '||
           'where ';

  if (PRCODEMP <> '') then
      WSQLAD = WSQLAD ||PRCODEMP||' and ';

  WSQLAD = WSQLAD ||'CALC.BDREFAD = '||prref||
                    ' AND VERBASREF.BDTIPOCODVER in (0, 1) ';

  if (PRCODCOL <> '') then
     WSQLAD = WSQLAD || ' and '||:PRCODCOL;

  for execute statement WSQLAD into :WDATA,:WCODEMP, :WCODCOL, :WCODVER, :WDESCVER, :WCLAVER, :WVALORVERBA, :WTIPOFOLHA, :WTIPOCODVER
  do
   begin
     if (((WCODCOLANT = 0) and (WCODEMPANT = 0)) or ((WCODCOLANT <> WCODCOL) or (WCODEMPANT <> WCODEMP))) then
        begin
           if (WTEMPARCELAMENTO = 1) then
              begin
                /* Select folha de folha normal/tomador */
                WSQLFN = 'select FN.BDCODEMP, FN.BDCODCOL, VERBAFN.BDCODVER, VERBAS.BDDESCVER, VERBAS.BDCLAVER, VERBAFN.BDVALVFN, 1 BDTIPOFOLHA, VERBASREF.BDTIPOCODVER '||
                         'from VRHF_EMP_TFOLHANORMAL FN '||
                         'left outer join VRHF_EMP_TVERBAFN VERBAFN on (VERBAFN.BDCODEMP = FN.BDCODEMP) and '||
                             '(VERBAFN.BDCODCOL = FN.BDCODCOL) and '||
                             '(VERBAFN.BDREFFN = FN.BDREFFN) '||
                         'left outer join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = VERBAFN.BDCODVER) '||
                         'left outer join VRH_BASE_TVERBAS_REF VERBASREF on (VERBAS.BDCODVER = VERBASREF.BDCODVER) and '||
                                                                         '(VERBASREF.BDREFVER = (select max(X.BDREFVER) '||
                                                                                                'from VRH_BASE_TVERBAS_REF X '||
                                                                                                'where X.BDCODVER = VERBAS.BDCODVER and '||
                                                                                                      'X.BDREFVER <= '||WREFERENCIA||')) '||
                       'where FN.BDCODEMP = '||:WCODEMPANT||' and '||
                             'FN.BDREFFN = '||WREFERENCIA||
                             ' AND VERBASREF.BDTIPOCODVER in (0, 1) ';
              
                WSQLFN = WSQLFN || ' and FN.BDCODCOL = '||:WCODCOLANT;
              
                WSQLFN = WSQLFN ||'union all '||
                       'select FT.BDCODEMP, FT.BDCODCOL, VERBAFT.BDCODVER, VERBAS.BDDESCVER, VERBAS.BDCLAVER, SUM(VERBAFT.BDVALVFT), 1 BDTIPOFOLHA, VERBASREF.BDTIPOCODVER '||
                       'from VRHF_EMP_TFOLHATOMADOR FT '||
                       'left outer join VRHF_EMP_TVERBATOMADOR VERBAFT on (VERBAFT.BDCODEMP = FT.BDCODEMP) and '||
                             '(VERBAFT.BDCODCOL = FT.BDCODCOL) and '||
                             '(VERBAFT.BDREFTOMADOR = FT.BDREFTOMADOR) and '||
                             '(VERBAFT.BDORDEM = FT.BDORDEM) '||
                       'left outer join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = VERBAFT.BDCODVER) '||
                       'left outer join VRH_BASE_TVERBAS_REF VERBASREF on (VERBAS.BDCODVER = VERBASREF.BDCODVER) and '||
                                                                         '(VERBASREF.BDREFVER = (select max(X.BDREFVER) '||
                                                                                                'from VRH_BASE_TVERBAS_REF X '||
                                                                                                'where X.BDCODVER = VERBAS.BDCODVER and '||
                                                                                                      'X.BDREFVER <= '||WREFERENCIA||')) '||
                       'where FT.BDCODEMP = '||:WCODEMPANT||' and '||
                             'FT.BDREFTOMADOR = '||WREFERENCIA||
                             ' AND VERBASREF.BDTIPOCODVER in (0, 1) ';
              
                WSQLFN = WSQLFN || ' and FT.BDCODCOL = '||:WCODCOLANT;
              
                WSQLFN = WSQLFN || 'group by FT.BDCODEMP, FT.BDCODCOL, VERBAFT.BDCODVER, VERBAS.BDDESCVER, VERBAS.BDCLAVER, VERBASREF.BDTIPOCODVER ';
              
                for execute statement WSQLFN into :BDCODEMP, :BDCODCOL, :BDCODVER, :BDDESCVER, :BDCLAVER, :BDVALORVERBA, :BDTIPOFOLHA, :WTIPOCODVERAUX
                do
                begin
                   BDTIPOCODVER = -1;
            
                   if (BDCLAVER starting '0.070') then
                      begin
                        if (WTIPOCODVERAUX = 0) then
                           BDTIPOCODVER = 2;
                        else if (WTIPOCODVERAUX = 1) then
                                BDTIPOCODVER = 3;
                      end
                   else
                     BDTIPOCODVER = WTIPOCODVERAUX;
            
                   suspend;
                end
              end

           WTEMPARCELAMENTO = 0;
           WCODCOLANT       = WCODCOL;
           WCODEMPANT       = WCODEMP;

           if (exists(select first 1 PARC.BDCODPARC from VRH_EMP_TPARCELAMENTOS PARC where PARC.BDCODEMP = :WCODEMP and PARC.BDCODCOL = :WCODCOL and PARC.bdeconsignado = 'TRUE' and PARC.bdrefinipar = :WREFERENCIA)) then
               WTEMPARCELAMENTO = 1;
        end

     if ((WCLAVER starting '2.003') or (WCLAVER starting '2.002.2.1')) then
        begin
          if (WTIPOCODVER = 0) then
             BDTIPOCODVER = 2;
          else if (WTIPOCODVER = 1) then
                  BDTIPOCODVER = 3;
        end
     else
       BDTIPOCODVER = WTIPOCODVER;

     if (WTEMPARCELAMENTO = 1) then
        begin
          BDCODEMP     = WCODEMP;
          BDCODCOL     = WCODCOL;
          BDCODVER     = WCODVER;
          BDDESCVER    = WDESCVER;
          BDCLAVER     = WCLAVER;
          BDVALORVERBA = WVALORVERBA;
          BDTIPOFOLHA  = WTIPOFOLHA;
          BDDATA = WDATA;

          suspend;
        end
    end

    BDDATA = NULL;
    if (WTEMPARCELAMENTO = 1) then
       begin
          /* Select folha de folha normal/tomador */
          WSQLFN = 'select FN.BDCODEMP, FN.BDCODCOL, VERBAFN.BDCODVER, VERBAS.BDDESCVER, VERBAS.BDCLAVER, VERBAFN.BDVALVFN, 1 BDTIPOFOLHA, VERBASREF.BDTIPOCODVER '||
                   'from VRHF_EMP_TFOLHANORMAL FN '||
                   'left outer join VRHF_EMP_TVERBAFN VERBAFN on (VERBAFN.BDCODEMP = FN.BDCODEMP) and '||
                       '(VERBAFN.BDCODCOL = FN.BDCODCOL) and '||
                       '(VERBAFN.BDREFFN = FN.BDREFFN) '||
                   'left outer join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = VERBAFN.BDCODVER) '||
                   'left outer join VRH_BASE_TVERBAS_REF VERBASREF on (VERBAS.BDCODVER = VERBASREF.BDCODVER) and '||
                                                                   '(VERBASREF.BDREFVER = (select max(X.BDREFVER) '||
                                                                                          'from VRH_BASE_TVERBAS_REF X '||
                                                                                          'where X.BDCODVER = VERBAS.BDCODVER and '||
                                                                                                'X.BDREFVER <= '||WREFERENCIA||')) '||
                 'where FN.BDCODEMP = '||:BDCODEMP||' and '||
                       'FN.BDREFFN = '||WREFERENCIA||
                       ' AND VERBASREF.BDTIPOCODVER in (0, 1) ';
        
          WSQLFN = WSQLFN || ' and FN.BDCODCOL = '||:BDCODCOL;
        
          WSQLFN = WSQLFN ||'union all '||
                 'select FT.BDCODEMP, FT.BDCODCOL, VERBAFT.BDCODVER, VERBAS.BDDESCVER, VERBAS.BDCLAVER, SUM(VERBAFT.BDVALVFT), 1 BDTIPOFOLHA, VERBASREF.BDTIPOCODVER '||
                 'from VRHF_EMP_TFOLHATOMADOR FT '||
                 'left outer join VRHF_EMP_TVERBATOMADOR VERBAFT on (VERBAFT.BDCODEMP = FT.BDCODEMP) and '||
                       '(VERBAFT.BDCODCOL = FT.BDCODCOL) and '||
                       '(VERBAFT.BDREFTOMADOR = FT.BDREFTOMADOR) and '||
                       '(VERBAFT.BDORDEM = FT.BDORDEM) '||
                 'left outer join VRH_BASE_TVERBAS VERBAS on (VERBAS.BDCODVER = VERBAFT.BDCODVER) '||
                 'left outer join VRH_BASE_TVERBAS_REF VERBASREF on (VERBAS.BDCODVER = VERBASREF.BDCODVER) and '||
                                                                   '(VERBASREF.BDREFVER = (select max(X.BDREFVER) '||
                                                                                          'from VRH_BASE_TVERBAS_REF X '||
                                                                                          'where X.BDCODVER = VERBAS.BDCODVER and '||
                                                                                                'X.BDREFVER <= '||WREFERENCIA||')) '||
                 'where FT.BDCODEMP = '||:BDCODEMP||' and '||
                       'FT.BDREFTOMADOR = '||WREFERENCIA||
                       ' AND VERBASREF.BDTIPOCODVER in (0, 1) ';
        
          WSQLFN = WSQLFN || ' and FT.BDCODCOL = '||:BDCODCOL;
        
          WSQLFN = WSQLFN || 'group by FT.BDCODEMP, FT.BDCODCOL, VERBAFT.BDCODVER, VERBAS.BDDESCVER, VERBAS.BDCLAVER, VERBASREF.BDTIPOCODVER ';
        
          for execute statement WSQLFN into :BDCODEMP, :BDCODCOL, :BDCODVER, :BDDESCVER, :BDCLAVER, :BDVALORVERBA, :BDTIPOFOLHA, :WTIPOCODVERAUX
          do
          begin
             BDTIPOCODVER = -1;
      
             if (BDCLAVER starting '0.070') then
                begin
                  if (WTIPOCODVERAUX = 0) then
                     BDTIPOCODVER = 2;
                  else if (WTIPOCODVERAUX = 1) then
                          BDTIPOCODVER = 3;
                end
             else
               BDTIPOCODVER = WTIPOCODVERAUX;
      
             suspend;
          end
       end
end^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TECONSIGNADO5003_BU0 FOR VRHF_TEMP_EMP_TECONSIGNADO5003
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  /* Trigger text */

  if (NEW.BDUNICO = 2) then
     begin
       NEW.BDVALOR = COALESCE(NEW.BDVALOR, 0) + COALESCE(OLD.BDVALOR, 0);
     end
end
^

create or alter procedure SP_VRHF_RECLAMATORIA_IDESEQPROC (
    PRCODEMP integer,
    PRCHAVE integer,
    PRREFPAGTO integer,
    PRCONSULTALOADFIELDS DM_BOOLEAN = TRUE,
    PREVTGERACAOMANUAL DM_BOOLEAN = FALSE)
returns (
    BDCODEMP integer,
    BDCHAVE integer,
    BDREFPGTO integer,
    BDCPF varchar(14),
    BDIDESEQPROC integer,
    BDCAMPOCHAVE integer,
    BDNOMCOL varchar(100),
    BDINIPROC integer,
    BDFIMPROC integer,
    BDCODREPERCPROC integer,
    BDCODCOL integer,
    BDNUMEROPROCESSO varchar(25))
as
declare variable WSQL varchar(3000);
declare variable WCODEMP integer;
declare variable WCHAVE integer;
declare variable WIDESEQPROC integer;
declare variable WCPF varchar(14);
declare variable WCAMPOCHAVE integer;
declare variable WNOMCOL varchar(300);
BEGIN

  WSQL = ' SELECT VINC.BDCODEMP, VINC.BDCHAVE AS BDCAMPOCHAVE, RT.BDCODRT AS BDCHAVE, RT.BDCODCOL, RT.BDNOMCOL, RT.BDCPFCOL, PG.BDCODREPERCPROC, BASE.BDNUMEROPROCESSO, ' ||
         ' MAX((SELECT FIRST 1 X.BDINIPROC FROM VRH_EMP_TRECLAMATORIA_IDPGTO X ' ||
         '                                      WHERE X.BDCODEMP = VINC.BDCODEMP AND X.BDCHAVE  = VINC.BDCHAVE ORDER BY X.BDINIPROC DESC)) AS BDINIPROC, ' ||
         ' MAX((SELECT FIRST 1 X.BDFIMPROC FROM VRH_EMP_TRECLAMATORIA_IDPGTO X ' ||
         '                                      WHERE X.BDCODEMP = VINC.BDCODEMP AND X.BDCHAVE  = VINC.BDCHAVE ORDER BY X.BDFIMPROC)) AS BDFIMPROC ';

  IF (:PRCONSULTALOADFIELDS = 'TRUE') THEN
    WSQL = WSQL || ' , ENC.BDREFPGTO ';
  ELSE
    WSQL = WSQL || ', ' || :PRREFPAGTO || ' AS BDREFPGTO ';
    
  WSQL = WSQL || ' FROM VRH_EMP_TRECLAMATORIA_VINC VINC ' ||
         ' JOIN VRH_EMP_TRECLAMATORIA RT ON (VINC.BDCODEMP = RT.BDCODEMP AND ' ||
         '        VINC.BDCHAVE = RT.BDCHAVE) ';
         
  IF (:PRCONSULTALOADFIELDS = 'TRUE') THEN
    WSQL = WSQL || ' JOIN VRH_TENCARGOS_RT ENC ON (RT.BDCODEMP = ENC.BDCODEMP AND RT.BDCODRT = ENC.BDCHAVE AND ENC.BDREFPGTO = ' || :PRREFPAGTO ||') ';
  
  WSQL = WSQL || ' JOIN VRH_BASE_TRECLAMATORIA BASE ON (RT.BDCODRT = BASE.BDCODRT) ' ||
         ' LEFT OUTER JOIN VRH_EMP_TRECLAMATORIA_PGMES PGMES ON (PGMES.BDCODEMP = VINC.BDCODEMP ' ||
         '         AND PGMES.BDCHAVE = VINC.BDCHAVE ' ||
         '         AND PGMES.BDCODVINC = VINC.BDCODVINC) ' ||
         ' JOIN VRH_EMP_TRECLAMATORIA_IDPGTO PG ON (VINC.BDCODEMP = PG.BDCODEMP ' ||
         '         AND VINC.BDCHAVE = PG.BDCHAVE ' ||
         '         AND PG.BDCODVINC = VINC.BDCODVINC) ' ||
         ' WHERE VINC.BDCODEMP = ' || :PRCODEMP || ' AND RT.BDCODRT = ' || :PRCHAVE || ' AND PG.BDCODREPERCPROC IN (1, 3) ';

  IF (:PREVTGERACAOMANUAL = 'TRUE') THEN /* Verifica se existe lançamento de RT, usado apenas para lançamentos de eventos */
    BEGIN
      WSQL = WSQL || ' AND EXISTS (' ||
      ' SELECT FIRST 1 RT.BDCODEMP ' ||
      ' FROM ' ||
      ' (SELECT FIRST 1 BASE.BDCODEMP ' ||
      ' FROM VRH_EMP_BASES_TENCARGOS_RT BASE ' ||
      ' WHERE BASE.BDCODEMP = VINC.BDCODEMP AND ' ||
            ' BASE.BDCHAVE = RT.BDCODRT AND ' ||
            ' BASE.BDREFPGTO = ' || :PRREFPAGTO || ' AND ' ||
            ' BASE.BDCPF = RT.BDCPFCOL ' ||
      ' UNION ALL ' ||
      ' SELECT FIRST 1 CR.BDCODEMP FROM VRH_EMP_CR_TENCARGOS_RT CR ' ||
      ' WHERE CR.BDCODEMP = VINC.BDCODEMP AND ' ||
            ' CR.BDCHAVE = RT.BDCODRT AND ' ||
            ' CR.BDREFPGTO = ' || :PRREFPAGTO || ' AND ' ||
            ' CR.BDCPF = RT.BDCPFCOL ' ||
      ' UNION ALL ' ||
      ' SELECT FIRST 1 DEP.BDCODEMP FROM  VRH_EMP_DEPENDENTES_TENCARGOS_RT DEP ' ||
      ' WHERE DEP.BDCODEMP = VINC.BDCODEMP AND ' ||
            ' DEP.BDCHAVE = RT.BDCODRT AND ' ||
            ' DEP.BDREFPGTO = ' || :PRREFPAGTO || ' AND ' ||
            ' DEP.BDCPF = RT.BDCPFCOL ' ||
      ' UNION ALL ' ||
      ' SELECT FIRST 1 IRRF.BDCODEMP FROM  VRH_EMP_IRRF_TENCARGOS_RT IRRF ' ||
      ' WHERE IRRF.BDCODEMP = VINC.BDCODEMP AND ' ||
            ' IRRF.BDCHAVE = RT.BDCODRT AND ' ||
            ' IRRF.BDREFPGTO = ' || :PRREFPAGTO || ' AND ' ||
            ' IRRF.BDCPF = RT.BDCPFCOL ' ||
      ' UNION ALL ' ||
      ' SELECT FIRST 1 PEN.BDCODEMP FROM  VRH_EMP_PENSAO_TENCARGOS_RT PEN ' ||
      ' WHERE PEN.BDCODEMP = VINC.BDCODEMP AND ' ||
            ' PEN.BDCHAVE = RT.BDCODRT AND ' ||
            ' PEN.BDREFPGTO = ' || :PRREFPAGTO || ' AND ' ||
            ' PEN.BDCPF = RT.BDCPFCOL ' ||
      ' UNION ALL ' ||
      ' SELECT FIRST 1 RRA.BDCODEMP FROM  VRH_EMP_RRA_TENCARGOS_RT RRA ' ||
      ' WHERE RRA.BDCODEMP = VINC.BDCODEMP AND ' ||
            ' RRA.BDCHAVE = RT.BDCODRT AND ' ||
            ' RRA.BDREFPGTO = ' || :PRREFPAGTO || ' AND ' ||
            ' RRA.BDCPF = RT.BDCPFCOL ' ||
      ' UNION ALL ' ||
      ' SELECT FIRST 1 ADV.BDCODEMP FROM  VRH_EMP_ADVOGADOS_TENCARGOS_RT ADV ' ||
      ' WHERE ADV.BDCODEMP = VINC.BDCODEMP AND ' ||
            ' ADV.BDCHAVE = RT.BDCODRT AND ' ||
            ' ADV.BDREFPGTO = ' || :PRREFPAGTO || ' AND ' ||
            ' ADV.BDCPF = RT.BDCPFCOL  ' ||
      '  ) AS RT )';
   END
   
   WSQL = WSQL || ' GROUP BY VINC.BDCODEMP, VINC.BDCHAVE, RT.BDCODRT, RT.BDCPFCOL, RT.BDCODCOL, RT.BDNOMCOL, PG.BDCODREPERCPROC, BASE.BDNUMEROPROCESSO ';

  IF (:PRCONSULTALOADFIELDS = 'TRUE') THEN
    WSQL = WSQL || ', ENC.BDREFPGTO ';

  FOR EXECUTE STATEMENT WSQL INTO
    :BDCODEMP,
    :BDCAMPOCHAVE,
    :BDCHAVE,
    :BDCODCOL, 
    :BDNOMCOL,
    :BDCPF,
    :BDCODREPERCPROC,
    :BDNUMEROPROCESSO,
    :BDINIPROC, 
    :BDFIMPROC,
    :BDREFPGTO

  DO
    BEGIN
      :WIDESEQPROC = 0;

      SELECT FIRST 1 BDCODEMP, BDCHAVE, BDCPF, BDIDESEQPROC FROM VRH_EMP_IDESEQPROC
      WHERE BDCODEMP = :PRCODEMP AND BDCHAVE = :PRCHAVE AND BDCPF = :BDCPF
      INTO WCODEMP, WCHAVE, WCPF, WIDESEQPROC;

      :BDIDESEQPROC  = WIDESEQPROC;
    
      SUSPEND;
    END

END^

CREATE OR ALTER PROCEDURE SP_VRHF_GERA_S2501_TESTE (
    PRCODEMP integer,
    PRQTDCADASTROS integer,
	PRCODRT integer)
AS
DECLARE VARIABLE WI INTEGER;
DECLARE VARIABLE WULTCHAVE INTEGER;
DECLARE VARIABLE WCHAVE INTEGER;

DECLARE VARIABLE WBASENUM BIGINT;
DECLARE VARIABLE WBASECPF VARCHAR(9);
DECLARE VARIABLE WCPFFORMATADO VARCHAR(14);
DECLARE VARIABLE WNOME VARCHAR(100);

DECLARE VARIABLE WCPFOK INTEGER;
DECLARE VARIABLE WTENTATIVAS INTEGER;
BEGIN
    SELECT COALESCE(MAX(BDCHAVE), 0)
      FROM VRH_EMP_TRECLAMATORIA
     WHERE BDCODEMP = :PRCODEMP
      INTO :WULTCHAVE;

    WI = 1;

    WHILE (WI <= :PRQTDCADASTROS) DO
    BEGIN
        WCHAVE = WULTCHAVE + WI;

        WNOME = LPAD(CAST(WI AS VARCHAR(10)), 6, '0') || ' COLABORADOR TESTE';

        WCPFOK = 0;
        WTENTATIVAS = 0;

        WHILE (WCPFOK = 0) DO
        BEGIN
            WTENTATIVAS = WTENTATIVAS + 1;

            WBASENUM = MOD(
                CAST(FLOOR(RAND() * 1000000) AS BIGINT)
                + CAST(WI AS BIGINT) * 7919
                + CAST(WTENTATIVAS AS BIGINT) * 104729
                + CAST(WULTCHAVE AS BIGINT),
                1000000
            );

            WBASECPF = '999' || LPAD(CAST(WBASENUM AS VARCHAR(6)), 6, '0');

            SELECT CPF
              FROM DIGITOCPF(:WBASECPF)
              INTO :WCPFFORMATADO;

            IF (
                WCPFFORMATADO IS NOT NULL
                AND WCPFFORMATADO <> ''
                AND WCPFFORMATADO <> '000.000.000-00'
                AND NOT EXISTS (
                    SELECT 1
                      FROM VRH_EMP_TRECLAMATORIA
                     WHERE BDCPFCOL = :WCPFFORMATADO
                )
            ) THEN
            BEGIN
                WCPFOK = 1;
            END
        END

        INSERT INTO VRH_EMP_TRECLAMATORIA (
            BDCODEMP,
            BDCHAVE,
            BDRESPDIRETO,
            BDNOMRESPDIRETO,
            BDCNPJRESPDIRETO,
            BDCODRT,
            BDNOMCOL,
            BDCPFCOL,
            BDDATANASCCOL,
            BDCODCOL,
            BDMATRESPDIRETO
        ) VALUES (
            :PRCODEMP,
            :WCHAVE,
            'FALSE',
            NULL,
            NULL,
            :PRCODRT,
            :WNOME,
            :WCPFFORMATADO,
            DATE '1995-07-17',
            NULL,
            '47311716935'
        );

        INSERT INTO VRH_EMP_TRECLAMATORIA_VINC (
            BDCODEMP,
            BDCHAVE,
            BDCODVINC,
            BDCODCONTRATO,
            BDINDCONTR,
            BDCATDIFERENTE,
            BDNATATIDIFERENTE,
            BDMOTRESCDIFERENTE,
            BDUNICIDADE,
            BDINDREINT,
            BDCODCOLVINC,
            BDSUCESSAOVINC,
            BDINFOESOCIAL
        ) VALUES (
            :PRCODEMP,
            :WCHAVE,
            1,
            5,
            2,
            2,
            2,
            2,
            NULL,
            2,
            NULL,
            NULL,
            2
        );

        INSERT INTO VRH_EMP_TRECLAMATORIA_ADM (
            BDCODEMP,
            BDCHAVE,
            BDCODVINC,
            BDDATAADM
        ) VALUES (
            :PRCODEMP,
            :WCHAVE,
            1,
            NULL
        );

        INSERT INTO VRH_EMP_TRECLAMATORIA_IDPGTO (
            BDCODEMP,
            BDCHAVE,
            BDCODVINC,
            BDINSCRICAO,
            BDINIPROC,
            BDFIMPROC,
            BDCODREPERCPROC,
            BDVALTOTREM,
            BDVALAVPREV,
            BDVALAVPREV13,
            BDVALDEMAIS,
            BDCODREPERCPROCORI,
            BDDECISAOSD,
            BDDECISAOABONO,
            BDVALTOTFGTSNDECL,
            BDVALTOTFGTSNDECL13,
            BDVALTOTFGTSSEFIP,
            BDVALTOTFGTSSEFIP13,
            BDVALTOTFGTSESOCIAL,
            BDVALTOTFGTSESOCIAL13
        ) VALUES (
            :PRCODEMP,
            :WCHAVE,
            1,
            '05.429.120/0001-22',
            201604,
            202212,
            1,
            NULL,
            NULL,
            NULL,
            NULL,
            NULL,
            0,
            0,
            NULL,
            NULL,
            NULL,
            NULL,
            NULL,
            NULL
        );

        INSERT INTO VRH_EMP_TRECLAMATORIA_PGMES (
            BDCODEMP,
            BDCHAVE,
            BDCODVINC,
            BDANOMES,
            BDBINSS,
            BDBINSS13,
            BDBFGTS,
            BDBFGTS13,
            BDOCORRENCIA,
            BDBFGTSNAODEC,
            BDBFGTSDECSEFIP,
            BDBFGTSDECESOCIAL
        ) VALUES (
            :PRCODEMP,
            :WCHAVE,
            1,
            201807,
            135.29,
            0,
            NULL,
            NULL,
            0,
            0,
            0,
            0
        );

        INSERT INTO VRH_EMP_TRECLAMATORIA_REM (
            BDCODEMP,
            BDCHAVE,
            BDCODVINC,
            BDCODREM,
            BDDATAREM,
            BDSALCOL,
            BDTIPOREM,
            BDDESCSALVAR
        ) VALUES (
            :PRCODEMP,
            :WCHAVE,
            1,
            1,
            DATE '2016-04-19',
            3660,
            5,
            ''
        );

        INSERT INTO VRH_EMP_TRECLAMATORIA_RESC (
            BDCODEMP,
            BDCHAVE,
            BDCODVINC,
            BDDATARESCISAO,
            BDCODPRES,
            BDDATAAVPREV,
            BDDATAULTIMODIATRAB,
            BDINDPENALIM,
            BDVALFGTSRESC,
            BDPERFGTSRESC
        ) VALUES (
            :PRCODEMP,
            :WCHAVE,
            1,
            DATE '2022-12-19',
            9,
            DATE '2022-12-19',
            DATE '2022-12-19',
            0,
            0,
            0
        );

        INSERT INTO VRH_EMP_TRECLAMATORIA_VICCAT (
            BDCODEMP,
            BDCHAVE,
            BDCODVINC,
            BDCODCAT,
            BDCATEGORIAESOCIAL,
            BDNATATIV,
            BDDATAMUDANCA,
            BDMATRICULA
        ) VALUES (
            :PRCODEMP,
            :WCHAVE,
            1,
            1,
            1,
            1,
            DATE '2016-04-19',
            ''
        );

        WI = WI + 1;
    END
END^

CREATE OR ALTER trigger vrh_tencargos_rt_bd0 for vrh_tencargos_rt
active before delete position 0
AS
  declare variable VCOUNT INTEGER;
begin
  SELECT COUNT(BDREFPGTO) FROM VRH_TENCARGOS_RT WHERE BDCODEMP = OLD.BDCODEMP AND BDCHAVE = OLD.BDCHAVE INTO :VCOUNT;

  IF (:VCOUNT = 1) THEN
    BEGIN
      DELETE FROM VRH_EMP_IDESEQPROC WHERE BDCODEMP = OLD.BDCODEMP AND BDCHAVE = OLD.BDCHAVE;
    END
end^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TVAL5002_BU0 FOR VRHF_TEMP_EMP_TVAL5002
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  /* Trigger text */
  if (COALESCE(NEW.BDUNICO, 0) = 1) then
     BEGIN
       if (new.bdtipoval = 1) then /* Pensão */
          begin
            new.bdvalor = coalesce(new.bdvalor,0) + coalesce(old.bdvalor,0);
            new.bdvalorfer = coalesce(new.bdvalorfer,0) + coalesce(old.bdvalorfer,0);
          end
       else
          begin
            if ((new.bdtipcodrec = 1) and (coalesce(old.bdcodaut, 0) = 0) and (new.bdcodaut > 0)) then
               begin
                 new.bdvalor = coalesce(new.bdvalor,0) + coalesce(old.bdvalor,0);
                 new.bdvalorfer = coalesce(new.bdvalorfer,0) + coalesce(old.bdvalorfer,0);
               end
            else
               begin
                 if (coalesce(new.bdvalor,0) < coalesce(old.bdvalor,0)) then
                    new.bdvalor = coalesce(old.bdvalor,0);
    
                 if (coalesce(new.bdvalorfer,0) < coalesce(old.bdvalorfer,0)) then
                    new.bdvalorfer = coalesce(old.bdvalorfer,0);
               end
          end
     END
  ELSE
     BEGIN
       new.bdvalor = coalesce(new.bdvalor,0) + coalesce(old.bdvalor,0);
       new.bdvalorfer = coalesce(new.bdvalorfer,0) + coalesce(old.bdvalorfer,0);
     END
end
^

CREATE OR ALTER trigger vrhf_temp_emp_tval5002_bi0 for vrhf_temp_emp_tval5002
active before insert position 0
AS
DECLARE VARIABLE WEXISTEREGISTRO INTEGER;
DECLARE VARIABLE VCODIGO INTEGER;
begin
  /* Trigger text */
  VCODIGO = 0;
  if ((new.BDSEQUENCIAL is null) or (new.BDSEQUENCIAL = 0)) then
  begin
    select coalesce((max(BDSEQUENCIAL) + 1), 1)
    from VRHF_TEMP_EMP_TVAL5002
    where BDSESSAO = NEW.BDSESSAO AND
          BDCODEMPORD = NEW.BDCODEMPORD AND
          BDCPFCOL = NEW.BDCPFCOL
    into VCODIGO;

    new.BDSEQUENCIAL = VCODIGO;
  end

  if (COALESCE(NEW.BDZERADO, 'FALSE') = 'FALSE') then
     begin

      if (NEW.BDUNICO = 2) then
         BEGIN
           WEXISTEREGISTRO = 0;
           select BDSESSAO from VRHF_TEMP_EMP_TVAL5002
           where BDSESSAO = NEW.BDSESSAO and
                 BDCODEMP = NEW.BDCODEMP and
                 BDCPFCOL = NEW.BDCPFCOL and
                 BDCODCOL = NEW.BDCODCOL and
                 BDTIPOVAL = NEW.BDTIPOVAL and
                 BDUNICO = 1 and
                 BDCPFDEP = NEW.BDCPFDEP and
                 BDTIPCODREC = NEW.BDTIPCODREC and
                 BDTAGSTR = NEW.BDTAGSTR and
                 BDCODAUT = NEW.BDCODAUT and
                 BDREFEMISSAO = NEW.BDREFEMISSAO and
                 BDTPCR = NEW.BDTPCR
           INTO :WEXISTEREGISTRO;
        
           if (COALESCE(WEXISTEREGISTRO, 0) = 0) then
              BEGIN
                INSERT INTO VRHF_TEMP_EMP_TVAL5002
                (BDSESSAO, BDCODEMP, BDCPFCOL, BDTIPOVAL, BDCPFDEP, BDTIPCODREC, BDNOME, BDDATANAS, BDTIPODEP, BDDESCDEP, BDVALOR, BDVALORFER, BDUNICO, BDTAGSTR, BDDESCRICAOFOLHA,
                 BDCODCOL, BDCODAUT, BDCODDEP, BDZERADO, BDCODEMPORD, BDREFEMISSAO, BDTPCR, BDSEQUENCIAL)
                VALUES
                (NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDCPFCOL, NEW.BDTIPOVAL, NEW.BDCPFDEP, NEW.BDTIPCODREC, '', NULL, 0, '', 0, 0, 1, '', '',
                 NEW.BDCODCOL, NEW.BDCODAUT, 0, TRUE, NEW.BDCODEMPORD, NEW.BDREFEMISSAO, NEW.BDTPCR, new.BDSEQUENCIAL + 1);
              END
         END
      ELSE
      IF (COALESCE(NEW.BDCODDEP, 0) > 0) THEN
         BEGIN
           if (COALESCE(new.bdcodcol, 0) > 0) then
              begin

                /* CRIA REGISTRO ZERADO ESOCIAL */
    
                WEXISTEREGISTRO = 0;
                select BDSESSAO from VRHF_TEMP_EMP_TVAL5002
                where BDSESSAO = NEW.BDSESSAO and
                      BDCPFCOL = NEW.BDCPFCOL and
                      BDTIPOVAL = NEW.BDTIPOVAL and
                      BDUNICO = 2 and
                      BDCPFDEP = NEW.BDCPFDEP and
                      BDTIPCODREC = NEW.BDTIPCODREC and
                      BDTAGSTR = '' and
                      BDCODEMPORD = NEW.BDCODEMPORD and
                      BDREFEMISSAO = NEW.BDREFEMISSAO and
                      BDTPCR = NEW.BDTPCR
                INTO :WEXISTEREGISTRO;
    
                if (COALESCE(WEXISTEREGISTRO, 0) = 0) then
                   BEGIN
                     INSERT INTO VRHF_TEMP_EMP_TVAL5002
                     (BDSESSAO, BDCODEMP, BDCPFCOL, BDTIPOVAL, BDCPFDEP, BDTIPCODREC, BDNOME, BDDATANAS, BDTIPODEP, BDDESCDEP, BDVALOR, BDVALORFER, BDUNICO, BDTAGSTR, BDDESCRICAOFOLHA,
                      BDCODCOL, BDCODAUT, BDCODDEP, BDZERADO, BDCODEMPORD, BDREFEMISSAO, BDTPCR, BDSEQUENCIAL)
                     VALUES
                     (NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDCPFCOL, NEW.BDTIPOVAL, NEW.BDCPFDEP, NEW.BDTIPCODREC, '', NULL, 0, '', 0, 0, 2, '', '',
                      NEW.BDCODCOL, NEW.BDCODAUT, 0, TRUE, NEW.BDCODEMPORD, NEW.BDREFEMISSAO, NEW.BDTPCR, new.BDSEQUENCIAL + 1);
                   END
    
              DELETE FROM VRHF_TEMP_EMP_TVAL5002
              where BDSESSAO = NEW.BDSESSAO and
                    BDCPFCOL = NEW.BDCPFCOL and
                    BDTIPOVAL = NEW.BDTIPOVAL and
                    BDUNICO = 1 and
                    BDCPFDEP = NEW.BDCPFDEP and
                    BDTIPCODREC = NEW.BDTIPCODREC and
                    BDZERADO = TRUE and
                    BDCODEMPORD = NEW.BDCODEMPORD and
                    BDREFEMISSAO = NEW.BDREFEMISSAO and
                    BDTPCR = NEW.BDTPCR;
              end
           else if (COALESCE(new.bdcodaut, 0) > 0) then
              begin
                /* CRIA REGISTRO ZERADO ESOCIAL */
    
                WEXISTEREGISTRO = 0;
                select BDSESSAO from VRHF_TEMP_EMP_TVAL5002
                where BDSESSAO = NEW.BDSESSAO and
                      BDCPFCOL = NEW.BDCPFCOL and
                      BDTIPOVAL = NEW.BDTIPOVAL and
                      BDUNICO = 2 and
                      BDCPFDEP = NEW.BDCPFDEP and
                      BDTIPCODREC = NEW.BDTIPCODREC and
                      BDCODEMPORD = NEW.BDCODEMPORD and
                      BDREFEMISSAO = NEW.BDREFEMISSAO and
                      BDTPCR = NEW.BDTPCR
                INTO :WEXISTEREGISTRO;
    
                if (COALESCE(WEXISTEREGISTRO, 0) = 0) then
                   BEGIN
                     INSERT INTO VRHF_TEMP_EMP_TVAL5002
                     (BDSESSAO, BDCODEMP, BDCPFCOL, BDTIPOVAL, BDCPFDEP, BDTIPCODREC, BDNOME, BDDATANAS, BDTIPODEP, BDDESCDEP, BDVALOR, BDVALORFER, BDUNICO, BDTAGSTR, BDDESCRICAOFOLHA,
                      BDCODCOL, BDCODAUT, BDCODDEP, BDZERADO, BDCODEMPORD, BDREFEMISSAO, BDTPCR, BDSEQUENCIAL)
                     VALUES
                     (NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDCPFCOL, NEW.BDTIPOVAL, NEW.BDCPFDEP, NEW.BDTIPCODREC, '', NULL, 0, '', 0, 0, 2, '', '',
                      NEW.BDCODCOL, NEW.BDCODAUT, 0, TRUE, NEW.BDCODEMPORD, NEW.BDREFEMISSAO, NEW.BDTPCR, new.BDSEQUENCIAL + 1);
                   END

                delete from VRHF_TEMP_EMP_TVAL5002
                where BDSESSAO = NEW.BDSESSAO and
                      BDCPFCOL = NEW.BDCPFCOL and
                      BDTIPOVAL = NEW.BDTIPOVAL and
                      BDUNICO = 1 and
                      BDCPFDEP = NEW.BDCPFDEP and
                      BDTIPCODREC = NEW.BDTIPCODREC and
                      BDCODEMPORD = NEW.BDCODEMPORD and
                      BDZERADO = TRUE and
                      BDREFEMISSAO = NEW.BDREFEMISSAO and
                      BDTPCR = NEW.BDTPCR;
              end
         END
  end
end
^

create or alter procedure SP_VRHF_IMPORTAFICHA5002 (
    PREMPRESAS varchar(32700),
    PRCPFS varchar(32700),
    PREMPCOMEVENTOS varchar(32700),
    PRREFINICIAL integer,
    PRREFFINAL integer,
    PRTIPORETORNO integer,
    PRPESQUISASOLETRADA integer,
    PRFILTROSOLETRADO varchar(32700))
returns (
    BDCODIGO integer,
    BDXML blob sub_type 0 segment size 80,
    BDREFARQ integer,
    BDCODEMP integer,
    BDNOMEMP varchar(200),
    BDCODCOL integer,
    BDCODTER integer,
    BDCPF varchar(14),
    BDNOME varchar(200))
as
declare variable WSQL varchar(32700);
declare variable WFILTROCPF varchar(32700);
begin
  WFILTROCPF = '';

  WSQL = ' select BDCODIGO, BDXML, BDREFARQ, BDCODEMP, BDNOMEMP, BDCODCOL, BDCODTER, BDCPFCOL, BDNOMCOL from ( select ';

  IF (PRTIPORETORNO IN (0, 1)) THEN
    BEGIN
      WSQL = WSQL || ' ARQ.BDCODIGO, XML.BDXML, ARQ.BDREFARQ, REFEMP.BDCODEMP, REFEMP.BDNOMEMP, COL.BDCODCOL, 0 BDCODTER, ';
    END
  ELSE
    BEGIN
      WSQL = WSQL || ' 0 BDCODIGO, null BDXML, 0 BDREFARQ, 0 BDCODEMP, '''' BDNOMEMP, 0 BDCODCOL, 0 BDCODTER, ';
    END

      WSQL = WSQL || 'COL.BDCPFCOL, ' ||
                     'case ' ||
                     '  when (FIS.BDNMSOCIAL <> '''' and PAR.BDUSANOMESOCIAL = ''TRUE'') then upper(FIS.BDNMSOCIAL) ' ||
                     '  else upper(COLCAD.BDNOMCOL) ' ||
                     'end BDNOMCOL '||
                     'from VRH_ESOCIAL_TARQUIVO ARQ '||
                     'inner join VRH_ESOCIAL_TARQUIVO_XML XML on (ARQ.BDCODIGO = XML.BDCODIGO and ARQ.BDCODEMP = XML.BDCODEMP) '||
                     'join VRH_EMP_TCOLCON COL on (COL.BDCODEMP = ARQ.BDCODEMP and COL.BDCODCOL = ARQ.BDCODCOL) '||
                     'join VRH_EMP_TCOLCON_CAD COLCAD on (COLCAD.BDCODEMP = COL.BDCODEMP and '||
                     '                                    COLCAD.BDCODCOL = COL.BDCODCOL and '||
                     '                                    COLCAD.BDREFCOL = coalesce((select first 1 D1.BDREFCOL '||
                     '                                                                from VRH_EMP_TCOLCON_CAD D1 '||
                     '                                                                where D1.BDCODEMP = COL.BDCODEMP and '||
                     '                                                                      D1.BDCODCOL = COL.BDCODCOL and '||
                     '                                                                      cast(D1.BDREFCOL as varchar(6)) <= (select trim(rdb$get_context(''USER_SESSION'', ''W_ANOMES'')) '||
                     '                                                                                                          from RDB$DATABASE) '||
                     '                                                                     order by D1.BDCODEMP desc, D1.BDCODCOL desc, D1.BDREFCOL desc), '||
                     '                                                                    (select first 1 D1.BDREFCOL '||
                     '                                                                     from VRH_EMP_TCOLCON_CAD D1 '||
                     '                                                                     where D1.BDCODEMP = COL.BDCODEMP and '||
                     '                                                                           D1.BDCODCOL = COL.BDCODCOL '||
                     '                                                                     order by D1.BDCODEMP, D1.BDCODCOL, D1.BDREFCOL))) '||
                     'inner join TEMPRESAS EMP on (ARQ.BDCODEMP = EMP.BDCODEMP) '||
                     'join TEMPRESAS_REF REFEMP on (REFEMP.BDCODEMP = EMP.BDCODEMP and '||
                     '                              REFEMP.BDREFEMP = coalesce((select first 1 D1.BDREFEMP '||
                     '                                                          from TEMPRESAS_REF D1 '||
                     '                                                          where D1.BDCODEMP = EMP.BDCODEMP and '||
                     '                                                                cast(D1.BDREFEMP as varchar(6)) <= (select trim(rdb$get_context(''USER_SESSION'', ''W_ANOMES'')) '||
                     '                                                                                                    from RDB$DATABASE) '||
                     '                                                          order by D1.BDCODEMP desc, D1.BDREFEMP desc), (select first 1 D1.BDREFEMP '||
                     '                                                                                                         from TEMPRESAS_REF D1 '||
                     '                                                                                                         where D1.BDCODEMP = EMP.BDCODEMP '||
                     '                                                                                                         order by D1.BDCODEMP, D1.BDREFEMP))) '||
                     'left join VRH_EMP_TCOLCON_FIS FIS on (FIS.BDCODEMP = COLCAD.BDCODEMP and '||
                     '                                 FIS.BDCODCOL = COLCAD.BDCODCOL and '||
                     '                                 FIS.BDREFCOL = coalesce((select first 1 BDREFCOL '||
                     '                                                          from VRH_EMP_TCOLCON_FIS F '||
                     '                                                          where F.BDCODEMP = COLCAD.BDCODEMP and '||
                     '                                                                F.BDCODCOL = COLCAD.BDCODCOL and '||
                     '                                                                F.BDREFCOL <= COLCAD.BDREFCOL '||
                     '                                                          order by F.BDCODEMP desc, F.BDCODCOL desc, F.BDREFCOL desc), (select first 1 BDREFCOL '||
                     '                                                                                                                        from VRH_EMP_TCOLCON_FIS F '||
                     '                                                                                                                        where F.BDCODEMP = COL.BDCODEMP and '||
                     '                                                                                                                              F.BDCODCOL = COL.BDCODCOL and '||
                     '                                                                                                                              F.BDREFCOL = COLCAD.BDREFCOL '||
                     '                                                                                                                        order by F.BDCODEMP, F.BDCODCOL, F.BDREFCOL))) '||
                     'left join VRHF_BASE_TEMPPAR PAR on (REFEMP.BDCODEMP = PAR.BDCODEMP and '||
                     '                               PAR.BDREFEMP = coalesce((select first 1 P.BDREFEMP '||
                     '                                                        from VRHF_BASE_TEMPPAR P '||
                     '                                                        where P.BDCODEMP = PAR.BDCODEMP and '||
                     '                                                              P.BDREFEMP <= REFEMP.BDREFEMP '||
                     '                                                        order by P.BDCODEMP desc, P.BDREFEMP desc), (select first 1 P.BDREFEMP '||
                     '                                                                                                     from VRHF_BASE_TEMPPAR P '||
                     '                                                                                                     where P.BDCODEMP = P.BDCODEMP and '||
                     '                                                                                                           P.BDREFEMP = REFEMP.BDREFEMP '||
                     '                                                                                                     order by P.BDCODEMP, P.BDREFEMP))) '||
                     'where ARQ.BDCODTIPO = 41 and ARQ.BDSTATUS = 2 ';

      /*Os filtros são feitos encima dos eventos, se os CPFs não tiverem nenhum vinculo com S-5002 com status 2 não vai trazer retorno nenhum para esse CPF*/
      IF (((PREMPCOMEVENTOS IS NOT NULL) AND (PREMPCOMEVENTOS <> '')) AND (PRTIPORETORNO = 0))  THEN
        BEGIN
          WSQL = WSQL || ' and ' || :PREMPCOMEVENTOS;
        END
    
      IF (((PRREFINICIAL IS NOT NULL) AND (PRREFINICIAL > 0)) AND ((PRREFFINAL IS NOT NULL) AND (PRREFFINAL > 0))) THEN
        BEGIN
          WSQL = WSQL || ' and  ARQ.BDREFARQ between ' || :PRREFINICIAL || ' and ' || :PRREFFINAL || ' ';
        END
      ELSE
      IF ((PRREFINICIAL IS NOT NULL) AND (PRREFINICIAL > 0)) THEN
        BEGIN
          WSQL = WSQL || ' and  ARQ.BDREFARQ >= ' || :PRREFINICIAL || ' ';
        END
      ELSE
      IF ((PRREFFINAL IS NOT NULL) AND (PRREFFINAL > 0)) THEN
        BEGIN
          WSQL = WSQL || ' and  ARQ.BDREFARQ <= ' || :PRREFFINAL || ' ';
        END
    
      IF ((PREMPRESAS IS NOT NULL) AND (PREMPRESAS <> ''))  THEN
        BEGIN
          WSQL = WSQL || ' and ' || REPLACE(:PREMPRESAS, 'EMP.', 'ARQ.');
        END
    
      /* ----- Fim dos filtros dos eventos */
  IF (((PRPESQUISASOLETRADA IS NOT NULL) AND (PRPESQUISASOLETRADA = 1)) AND ((PRFILTROSOLETRADO IS NOT NULL) AND (PRFILTROSOLETRADO <> ''))) THEN
    BEGIN
      WFILTROCPF = ' AND COL.BDCPFCOL like ''%' || :PRFILTROSOLETRADO || '%''';
    END
  ELSE
  IF (((PRPESQUISASOLETRADA IS NOT NULL) AND (PRPESQUISASOLETRADA = 2)) AND ((PRFILTROSOLETRADO IS NOT NULL) AND (PRFILTROSOLETRADO <> ''))) THEN
    BEGIN
      WFILTROCPF = ' AND (((    (FIS.BDNMSOCIAL <> '''' and COALESCE(PAR.BDUSANOMESOCIAL, ''FALSE'') = ''TRUE'')  AND upper(FIS.BDNMSOCIAL)  collate WIN_PTBR like ''%' || :PRFILTROSOLETRADO || '%'') OR ' ||
                   '       ((NOT(FIS.BDNMSOCIAL <> '''' and COALESCE(PAR.BDUSANOMESOCIAL, ''FALSE'') = ''TRUE'')) AND upper(COLCAD.BDNOMCOL) collate WIN_PTBR like ''%' || :PRFILTROSOLETRADO || '%'')))';
    END
  ELSE
  IF (((PRCPFS IS NOT NULL) AND (PRCPFS <> '')) AND (PRTIPORETORNO <> 0))  THEN
    BEGIN
      WFILTROCPF = ' AND ' || REPLACE(:PRCPFS, 'BDCPF', 'COL.BDCPFCOL');
    END

  IF (WFILTROCPF <> '')  THEN
    BEGIN
      WSQL = WSQL || :WFILTROCPF;
      WFILTROCPF = '';
    END


  IF (PRTIPORETORNO = 2) THEN
    BEGIN
      WSQL = WSQL || 'GROUP BY BDCPFCOL, BDNOMCOL ';
    END

  wSQL = WSQL || 'union all select ';

  IF (PRTIPORETORNO IN (0, 1)) THEN
      WSQL = WSQL || ' ARQ.BDCODIGO, XML.BDXML, ARQ.BDREFARQ, EMP.BDCODEMP, REFEMP.BDNOMEMP, 0 BDCODCOL, TER.BDCODTER, ';
  ELSE
      WSQL = WSQL || ' 0 BDCODIGO, null BDXML, 0 BDREFARQ, 0 BDCODEMP, '''' BDNOMEMP, 0 BDCODCOL, 0 BDCODTER, ';


  WSQL = WSQL || 'case ' ||
                 '  when (position(''/'' in TER.BDCGCTER) > 0) then cast(RH.BDCPFMEITER as varchar(14)) ' ||
                 '  else cast(TER.BDCGCTER as varchar(14)) ' ||
                 'end BDCPFTER, '||
                 'TER_REF.BDNOMETER BDNOMCOL '||
                 'from VRH_ESOCIAL_TARQUIVO ARQ '||
                 'inner join VRH_ESOCIAL_TARQUIVO_XML XML on (ARQ.BDCODIGO = XML.BDCODIGO and ARQ.BDCODEMP = XML.BDCODEMP) '||
                 'join TTERCEIRO TER on (TER.BDCODTER = ARQ.BDCODTER) '||
                 'join TTERCEIRO_REF TER_REF on (TER_REF.BDCODTER = ARQ.BDCODTER and '||
                 '                               TER_REF.BDREFEMP = coalesce((select first 1 RF2.BDREFEMP '||
                 '                                                            from TTERCEIRO_REF RF2 '||
                 '                                                            where RF2.BDCODTER = TER.BDCODTER and '||
                 '                                                                  RF2.BDREFEMP <= (select trim(rdb$get_context(''USER_SESSION'', ''W_ANOMES'')) '||
                 '                                                                                   from RDB$DATABASE) '||
                 '                                                            order by RF2.BDCODTER desc, RF2.BDREFEMP desc), (select first 1 RF2.BDREFEMP '||
                 '                                                                                                             from TTERCEIRO_REF RF2 '||
                 '                                                                                                             where RF2.BDCODTER = TER.BDCODTER '||
                 '                                                                                                             order by RF2.BDCODTER, RF2.BDREFEMP))) '||
                 'left join TTERCEIRO_RH RH on (RH.BDCODTER = TER.BDCODTER) '||
                 'inner join TEMPRESAS EMP on (ARQ.BDCODEMP = EMP.BDCODEMP) '||
                 'join TEMPRESAS_REF REFEMP on (REFEMP.BDCODEMP = EMP.BDCODEMP and '||
                 '                              REFEMP.BDREFEMP = coalesce((select first 1 D1.BDREFEMP '||
                 '                                                          from TEMPRESAS_REF D1 '||
                 '                                                          where D1.BDCODEMP = EMP.BDCODEMP and '||
                 '                                                                cast(D1.BDREFEMP as varchar(6)) <= (select trim(rdb$get_context(''USER_SESSION'', ''W_ANOMES'')) '||
                 '                                                                                                    from RDB$DATABASE) '||
                 '                                                          order by D1.BDCODEMP desc, D1.BDREFEMP desc), (select first 1 D1.BDREFEMP '||
                 '                                                                                                         from TEMPRESAS_REF D1 '||
                 '                                                                                                         where D1.BDCODEMP = EMP.BDCODEMP '||
                 '                                                                                                         order by D1.BDCODEMP, D1.BDREFEMP))) '||
                 'where ARQ.BDCODTIPO = 41 and ARQ.BDSTATUS = 2 ';


  IF (((PREMPCOMEVENTOS IS NOT NULL) AND (PREMPCOMEVENTOS <> '')) AND (PRTIPORETORNO = 0))  THEN
        BEGIN
          WSQL = WSQL || ' and ' || :PREMPCOMEVENTOS;
        END
    
      IF (((PRREFINICIAL IS NOT NULL) AND (PRREFINICIAL > 0)) AND ((PRREFFINAL IS NOT NULL) AND (PRREFFINAL > 0))) THEN
        BEGIN
          WSQL = WSQL || ' and  ARQ.BDREFARQ between ' || :PRREFINICIAL || ' and ' || :PRREFFINAL || ' ';
        END
      ELSE
      IF ((PRREFINICIAL IS NOT NULL) AND (PRREFINICIAL > 0)) THEN
        BEGIN
          WSQL = WSQL || ' and  ARQ.BDREFARQ >= ' || :PRREFINICIAL || ' ';
        END
      ELSE
      IF ((PRREFFINAL IS NOT NULL) AND (PRREFFINAL > 0)) THEN
        BEGIN
          WSQL = WSQL || ' and  ARQ.BDREFARQ <= ' || :PRREFFINAL || ' ';
        END
    
      IF ((PREMPRESAS IS NOT NULL) AND (PREMPRESAS <> ''))  THEN
        BEGIN
          WSQL = WSQL || ' and ' || REPLACE(:PREMPRESAS, 'EMP.', 'ARQ.');
        END
    
      /* ----- Fim dos filtros dos eventos */
  IF (((PRPESQUISASOLETRADA IS NOT NULL) AND (PRPESQUISASOLETRADA = 1)) AND ((PRFILTROSOLETRADO IS NOT NULL) AND (PRFILTROSOLETRADO <> ''))) THEN
    BEGIN
      WFILTROCPF = ' AND case ' ||
                 '         when (position(''/'' in TER.BDCGCTER) > 0) then cast(RH.BDCPFMEITER as varchar(14)) ' ||
                 '         else cast(TER.BDCGCTER as varchar(14)) ' ||
                 '       end like ''%' || :PRFILTROSOLETRADO || '%''';
    END
  ELSE
  IF (((PRPESQUISASOLETRADA IS NOT NULL) AND (PRPESQUISASOLETRADA = 2)) AND ((PRFILTROSOLETRADO IS NOT NULL) AND (PRFILTROSOLETRADO <> ''))) THEN
    BEGIN
      WFILTROCPF = ' AND TER_REF.BDNOMETER collate WIN_PTBR like ''%' || :PRFILTROSOLETRADO || '%'' ';
    END
  ELSE
  IF (((PRCPFS IS NOT NULL) AND (PRCPFS <> '')) AND (PRTIPORETORNO <> 0))  THEN
    BEGIN
      WFILTROCPF = ' AND ( (position(''/'' in TER.BDCGCTER) > 0 and ' || REPLACE(:PRCPFS, 'BDCPF', 'RH.BDCPFMEITER') || ') OR '||
                   '        ( '|| REPLACE(:PRCPFS, 'BDCPF', 'TER.BDCGCTER') || ') ) ';
    END

  IF (WFILTROCPF <> '')  THEN
    BEGIN
      WSQL = WSQL || :WFILTROCPF;
      WFILTROCPF = '';
    END


  IF (PRTIPORETORNO = 2) THEN
    BEGIN
      WSQL = WSQL || 'GROUP BY BDCPFTER, BDNOMCOL) ';
      wSQL = wSQL || 'GROUP BY BDCODIGO, BDXML, BDREFARQ, BDCODEMP, BDNOMEMP, BDCODCOL, BDCODTER, BDCPFCOL, BDNOMCOL ';
    END
  else
   WSQL = WSQL || ') ';

  FOR EXECUTE STATEMENT WSQL INTO :BDCODIGO, :BDXML, :BDREFARQ, :BDCODEMP, :BDNOMEMP, :BDCODCOL, :BDCODTER, :BDCPF, :BDNOME DO
   begin
     suspend;
   end

end^

COMMENT ON PARAMETER SP_VRHF_IMPORTAFICHA5002.PRTIPORETORNO IS
'0=AmbienteESocial, 1=FichaFinanceiraIRRF, 2=EditCPFs'^

COMMENT ON PARAMETER SP_VRHF_IMPORTAFICHA5002.PRPESQUISASOLETRADA IS
'1=PORCPF, 2=PORNOME'^


create or alter procedure SP_VRHF_ADD_VAL_DEP_PEN_5002 (
    PRCODEMP integer,
    PRCODCOL integer,
    PRAUTONOMO integer,
    PRREF integer,
    PRDATACALC date,
    PRINTAUX integer,
    PRTIPOVAL integer,
    PRTIPOFOLHA integer,
    PRCODEMPPRINCIPAL integer,
    PRTAGSTR varchar(100),
    PRDESCRICAOFOLHA varchar(1000),
    PRINCIDESOCIAL integer,
    PRUNICO integer,
    PRTIPCODREC integer,
    PRREFFC integer,
    PRDATAPGTO date,
    PRREFPAG integer,
    PRFC integer,
    PRCODEMPORD integer,
    PRINCIDESOCIALFER integer,
    PRREFEMISSAO integer,
    PRCODREC varchar(6) = null /* COLLATE WIN1252 - default */ )
as
declare variable WCPFCOL varchar(14);
declare variable WTIPO integer;
declare variable WCODVER integer;
declare variable WCODDEP integer;
declare variable WVALOR numeric(15,2);
declare variable WTABIREMP integer;
declare variable WCPFDEP varchar(20);
declare variable WNOMEDEP varchar(300);
declare variable WTIPODEP varchar(2);
declare variable WDESCDEP varchar(500);
declare variable WDATANAS date;
declare variable WEVT integer;
declare variable WEVTANT integer;
declare variable WTIPOREND integer;
declare variable WVALORFER numeric(15,2);
declare variable WTIPOREGISTRO integer;
declare variable WSQL varchar(1000);
declare variable WDEPIRRF varchar(1);
declare variable WREFIR integer;
declare variable WPODEGRAVAR integer;
declare variable WPARENESCODPN integer;
declare variable WBDIRVER integer;
begin
  /* Procedure Text */
  WCPFCOL = '';
  WTIPO = 0;
  WCODVER = 0;
  WCODDEP = 0;
  WVALOR = 0;
  WTABIREMP = 0;
  WCPFDEP = '';
  WNOMEDEP = '';
  WTIPODEP = '';
  WDESCDEP = '';
  WDATANAS = null;
  WEVT = 0;
  WEVTANT = -1;
  WTIPOREND = 0;
  WVALORFER = 0;
  WTIPOREGISTRO = -1;
  WSQL = '';
  WDEPIRRF = '';
  WREFIR = 0;
  WPODEGRAVAR = 0;
  WPARENESCODPN = 0;
  wbdirver = 0;

  if (COALESCE(prcodcol, 0) > 0) then
     begin
       wcpfcol = '';
       select first 1 doc.bdcpfcol from vrh_emp_tcolcon_doc doc where doc.bdcodemp = :prcodemp and doc.bdcodcol = :prcodcol into :wcpfcol;

       if (COALESCE(PRUNICO, 0) = 2) then
          BEGIN
           WEVTANT = -1;
           WCPFDEP = '';
           WNOMEDEP = '';
           WTIPODEP = '';
           WDESCDEP = '';
           WDATANAS = null;
           WTIPOREGISTRO = -1;
           WEVT = 0;
           WVALOR = 0;
           WDEPIRRF = '';

           FOR SELECT DEP.BDCPFDEP, DEP.BDNOME, DEP.BDTPDEP, DEP.BDDESCRDEP, DEP.BDDTNASCTO, DEP.BDTIPOREGISTRO, CONSOLID.BDCODEVT, DEP.BDVLR, DEP.BDDEPIRRF, DEP.BDTPREND,
                      CONSOLID.BDTIPOCALCULO
               FROM VRH_ESOCIAL_CONSOLIDAPURMEN_C CONSOLID
               INNER JOIN VRH_ESOCIAL_INFOIRRF_DEP DEP ON (CONSOLID.BDCODEMP = DEP.BDCODEMP AND CONSOLID.BDCODCOL = DEP.BDCODCOL AND CONSOLID.BDCODEVT = DEP.BDCODEVT AND
                                                           CONSOLID.BDTIPOCALCFIR = DEP.BDTIPOCALCFIR AND CONSOLID.BDCODCONSOLID = DEP.BDCODCONSOLID)
               WHERE CONSOLID.BDCODEMP = :PRCODEMP AND
                     CONSOLID.BDCODCOL = :PRCODCOL AND
                     CONSOLID.BDREFEVT = :PRREFEMISSAO
               ORDER BY CONSOLID.BDCODEVT DESC, CONSOLID.BDTIPOCALCULO
           INTO :WCPFDEP, :WNOMEDEP, :WTIPODEP, :WDESCDEP, :WDATANAS, :WTIPOREGISTRO, :WEVT, :WVALOR, :WDEPIRRF, :WTIPOREND, :prtipcodrec DO
           BEGIN
             if (wevtant = -1) then
                wevtant = wevt;
             else if (wevt <> wevtant) then
                break;

--             if (((COALESCE(WTIPOREGISTRO, 0) = 1) and (COALESCE(WDEPIRRF, 'N') = 'S')) or
--                (COALESCE(WTIPOREGISTRO, 0) = 2)) then
                begin
                  WVALORFER = 0;
                  if ((WTIPOREND = 13)) then
                     BEGIN
                       WVALORFER = WVALOR;
                       WVALOR = 0;
                     END

                  if (WTIPOREGISTRO = 1) then
                     begin
                       WTIPOREGISTRO = 0;

                       if ((COALESCE(wtipodep,'') <> '') and (coalesce(wtipodep, '0') <> '99')) then
                          SELECT FIRST 1 BDDESCTIPODEP FROM VRH_TTIPO_DEP_ESOCIAL WHERE BDCODESOCIAL = COALESCE(:WTIPODEP, '0') ORDER BY BDCODTIPODEP INTO :WDESCDEP;
                       else if ((COALESCE(wtipodep,'') = '') and (COALESCE(WDEPIRRF, '') = '')) then
                          begin
                            SELECT FIRST 1 DES.BDCODESOCIAL, case when DES.BDCODESOCIAL <> 99 then DES.BDDESCTIPODEP else :WDESCDEP end BDDESCTIPODEP
                            FROM VRH_EMP_TDEP DEP
                            JOIN (
                                  SELECT X.bdcodemp, X.BDCODCOL, X.bdcoddpn,
                                         COALESCE
                                         (
                                          (SELECT MAX(d2.BDREFDPN) FROM vrh_emp_tdep_ref d2 WHERE d2.bdcodemp = x.bdcodemp AND d2.bdcodcol = x.bdcodcol AND d2.bdcoddpn = x.bdcoddpn AND CAST(d2.BDREFDPN AS VARCHAR(6)) <= :PRREFEMISSAO),
                                          (SELECT MIN(d1.BDREFDPN) FROM vrh_emp_tdep_ref d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol AND d1.bdcoddpn = x.bdcoddpn)
                                         ) AS BDREFDPN
                                  FROM  vrh_emp_tdep x
                            ) AS DEPREF_MAX ON (DEP.BDCODEMP = DEPREF_MAX.BDCODEMP AND DEP.BDCODCOL = DEPREF_MAX.BDCODCOL AND DEP.BDCODDPN = DEPREF_MAX.BDCODDPN)
                            JOIN VRH_EMP_TDEP_REF DEPREF ON (DEP.BDCODEMP = DEPREF.BDCODEMP AND
                                                             DEP.BDCODCOL = DEPREF.BDCODCOL AND
                                                             DEP.BDCODDPN = DEPREF.BDCODDPN AND
                                                             DEPREF.BDREFDPN = DEPREF_MAX.BDREFDPN)
                            LEFT OUTER JOIN VRH_TTIPO_DEP_ESOCIAL DES ON (DES.BDCODTIPODEP = DEPREF.BDPARENESCODPN)
                            WHERE DEP.BDCODEMP = :PRCODEMP AND
                                  DEP.BDCODCOL = :PRCODCOL AND
                                  DEPREF.BDCPFDPN = :WCPFDEP
                            INTO :wtipodep, :WDESCDEP;
                          end
                     end
                  ELSE
                     WTIPOREGISTRO = 1;

                  if (COALESCE(wtipodep,'') = '') then
                     wtipodep = '0';

                  PRTAGSTR = coalesce(:PRTAGSTR,'');
                  PRDESCRICAOFOLHA = coalesce(:PRDESCRICAOFOLHA,'');

                  update or insert into VRHF_TEMP_EMP_TVAL5002
                  (BDSESSAO, BDCODEMP, BDTIPOVAL, BDVALOR, BDVALORFER, BDUNICO, BDCODCOL, BDCODDEP, BDTIPCODREC, BDTAGSTR, BDDESCRICAOFOLHA,
                  BDCPFDEP, BDNOME, BDTIPODEP, BDDATANAS, BDDESCDEP, BDZERADO, BDCODEMPORD, BDCPFCOL, BDCODAUT, BDREFEMISSAO, BDTPCR)
                  values
                  (current_connection, :prcodempprincipal, :WTIPOREGISTRO, :wvalor, :WVALORFER, 2, :prcodcol, 0, :prtipcodrec,
                  :PRTAGSTR, :PRDESCRICAOFOLHA,
                  :WCPFDEP, :WNOMEDEP, :WTIPODEP, :WDATANAS, :WDESCDEP, FALSE, :PRCODEMPORD, :WCPFCOL, 0, :PRREFEMISSAO, :PRCODREC)
                  matching (BDSESSAO, BDCODEMPORD, BDCPFCOL, BDTIPOVAL, BDUNICO, BDCPFDEP, BDTIPCODREC, BDTAGSTR, BDREFEMISSAO, BDTPCR);
                end

             WCPFDEP = '';
             WNOMEDEP = '';
             WTIPODEP = '';
             WDESCDEP = '';
             WDATANAS = null;
             WTIPOREGISTRO = -1;
             WEVT = 0;
             WVALOR = 0;
             WDEPIRRF = '';
           END

          END
       ELSE
       IF ((PRTIPOFOLHA IN (0,100)) OR ((PRTIPOFOLHA = 4) AND (PRFC = 0))) THEN
          BEGIN
            --  C_FICHA_FN, C_FICHA_FN_RESC    = 0, 100;
            --  C_FICHA_FERIAS_FOLHA           = 4;       FN OU FC
            wcoddep = 0;
            wvalor = 0;
            for select val.bdcodver, val.bdcoddpn, val.bdvalpend, ver.bdirver from (
                   select a.bdcodver, a.bdcoddpn, a.bdcodemp, a.bdcodcol, a.bdvalpend  from VRHF_EMP_TFNPENSAO_DEP a where a.bdcodemp = : prcodemp and a.bdcodcol = :prcodcol and a.bdreffn = :prref
                   union all
                   select b.bdcodver, b.bdcoddpn, b.bdcodemp, b.bdcodcol, sum(b.bdvalpend) from VRHF_EMP_TFTPENSAO_DEP b where b.bdcodemp = :prcodemp and b.bdcodcol = :prcodcol and b.bdreftomador = :prref
                   group by b.bdcodver, b.bdcoddpn, b.bdcodemp, b.bdcodcol
                   union all
                   select a.bdcodver, a.bdcodbenef bdcoddpn, a.bdcodemp, a.bdcodcol, a.bdvalpend from VRHF_EMP_TINTPENSAO_DEP a where a.bdcodemp = :prcodemp and a.bdcodcol = :prcodcol and a.bdreffn = :prref and a.BDCODCONTTI = :printaux
                   union all
                   select b.bdcodver, b.bdcodbenef bdcoddpn, b.bdcodemp, b.bdcodcol, sum(b.bdvalpend) from VRHF_EMP_TTOMINTPENSAO_DEP b where b.bdcodemp = :prcodemp and b.bdcodcol = :prcodcol and b.bdreftomador = :prref and b.BDCODCONTTI = :printaux
                   group by b.bdcodver, b.bdcodbenef, b.bdcodemp, b.bdcodcol) val
            join vrh_base_tverbas_ref ver on (val.bdcodver = ver.bdcodver and ver.bdrefver = (select first 1 x.bdrefver from vrh_base_tverbas_ref x where x.bdcodver = ver.bdcodver and x.bdrefver <= :prRef order by x.bdrefver desc))
            where ver.bdirver in (1,2) and  /* folha e férias pois é considerado pensão normal */
                  val.bdvalpend > 0
            into :wcodver, :wcoddep, :wvalor, :wbdirver do
            begin
              select first 1 bene.bdcpfbenef, bene.bdnombenef, bene.bdparenescodpn, bene.bddatanascbenef from VRH_EMP_TCOLCON_BENEF bene
              where bene.bdcodemp = :prcodemp and bene.bdcodcol = :prcodcol and bene.bdcodbenef = :wcoddep into :wcpfdep, :wnomedep, :wtipodep, :wdatanas;

              PRTAGSTR = coalesce(:PRTAGSTR,'');
              PRDESCRICAOFOLHA = coalesce(:PRDESCRICAOFOLHA,'');

              wvalorfer = 0;
              if (:wbdirver = 2) then
                 begin
                   wvalorfer = wvalor;
                   wvalor = 0;
                 end

              update or insert into VRHF_TEMP_EMP_TVAL5002
              (BDSESSAO, BDCODEMP, BDTIPOVAL, BDVALOR, BDVALORFER, BDUNICO, BDCODCOL, BDCODDEP, BDTIPCODREC, BDTAGSTR, BDDESCRICAOFOLHA, BDZERADO, BDCODEMPORD, BDCPFCOL, BDCODAUT,
              BDCPFDEP, BDNOME, BDTIPODEP, BDDATANAS, BDREFEMISSAO, BDTPCR)
              values
              (current_connection, :prcodempprincipal, 1, :wvalor, :wvalorfer, 1, :prcodcol, :wcoddep, :prtipcodrec, :PRTAGSTR, :PRDESCRICAOFOLHA, FALSE, :PRCODEMPORD, :WCPFCOL, 0,
              :wcpfdep, :wnomedep, :wtipodep, :wdatanas, :PRREFEMISSAO, :PRCODREC)
              matching (BDSESSAO, BDCODEMP, BDCODCOL, BDCPFCOL, BDCPFDEP, BDTIPOVAL, BDUNICO, BDTAGSTR, BDTIPCODREC, BDCODAUT, BDREFEMISSAO, BDTPCR);

              wcoddep = 0; wvalor = 0; wcodver = 0; wcpfdep = ''; wnomedep = ''; wtipodep = ''; wdatanas = null;
            end
          end
       else if (prtipofolha in (101)) then
          begin
            --  C_FICHA_FN_RESC_13            = 101;
            for select val.bdcodver, val.bdcoddpn, val.bdvalpend from (
                   select a.bdcodver, a.bdcoddpn, a.bdcodemp, a.bdcodcol, a.bdvalpend from VRHF_EMP_TFNPENSAO_DEP a where a.bdcodemp = : prcodemp and a.bdcodcol = :prcodcol and a.bdreffn = :prref
                   union all
                   select b.bdcodver, b.bdcoddpn, b.bdcodemp, b.bdcodcol, sum(b.bdvalpend) from VRHF_EMP_TFTPENSAO_DEP b where b.bdcodemp = :prcodemp and b.bdcodcol = :prcodcol and b.bdreftomador = :prref
                   group by b.bdcodver, b.bdcoddpn, b.bdcodemp, b.bdcodcol
                   union all
                   select a.bdcodver, a.bdcodbenef bdcoddpn, a.bdcodemp, a.bdcodcol, a.bdvalpend from VRHF_EMP_TINTPENSAO_DEP a where a.bdcodemp = :prcodemp and a.bdcodcol = :prcodcol and a.bdreffn = :prref and a.BDCODCONTTI = :printaux
                   union all
                   select b.bdcodver, b.bdcodbenef bdcoddpn, b.bdcodemp, b.bdcodcol, sum(b.bdvalpend) from VRHF_EMP_TTOMINTPENSAO_DEP b where b.bdcodemp = :prcodemp and b.bdcodcol = :prcodcol and b.bdreftomador = :prref and b.BDCODCONTTI = :printaux
                   group by b.bdcodver, b.bdcodbenef, b.bdcodemp, b.bdcodcol) val
            join vrh_base_tverbas_ref ver on (val.bdcodver = ver.bdcodver and ver.bdrefver = (select first 1 x.bdrefver from vrh_base_tverbas_ref x where x.bdcodver = ver.bdcodver and x.bdrefver <= :prRef order by x.bdrefver desc))
            where ver.bdirver in (3) and  /* 13 */
                  val.bdvalpend > 0
            union all
            select AD.BDCODVER, AD.BDCODDPN, AD.BDVALPEND from VRHF_EMP_TA13PENSAO_DEP AD
            left join VRHF_EMP_T13PENSAO_DEP VAL on (VAL.BDCODEMP = AD.BDCODEMP and VAL.BDCODCOL = AD.BDCODCOL and VAL.BDREF13 BETWEEN (AD.BDREFA13/100)*100+1 AND (AD.BDREFA13/100)*100+12 and VAL.BDVALPEND > 0)
            where AD.BDCODEMP = :PRCODEMP and AD.BDCODCOL = :PRCODCOL and cast(AD.BDREFA13 as varchar(6)) starting with substring(cast(:PRREF as varchar(6)) from 1 for 4) and AD.BDVALPEND > 0 and VAL.BDCODVER is null
            into :wcodver, :wcoddep, :wvalor do
            begin
              select first 1 bene.bdcpfbenef, bene.bdnombenef, bene.bdparenescodpn, bene.bddatanascbenef from VRH_EMP_TCOLCON_BENEF bene
              where bene.bdcodemp = :prcodemp and bene.bdcodcol = :prcodcol and bene.bdcodbenef = :wcoddep into :wcpfdep, :wnomedep, :wtipodep, :wdatanas;

              PRTAGSTR = coalesce(:PRTAGSTR,'');
              PRDESCRICAOFOLHA = coalesce(:PRDESCRICAOFOLHA,'');

              update or insert into VRHF_TEMP_EMP_TVAL5002
               (BDSESSAO, BDCODEMP, BDTIPOVAL, BDVALOR, BDVALORFER, BDUNICO, bdcodcol, BDCODDEP, BDTIPCODREC, BDTAGSTR, BDDESCRICAOFOLHA, BDZERADO, BDCODEMPORD, BDCPFCOL, BDCODAUT,
                BDCPFDEP, BDNOME, BDTIPODEP, BDDATANAS, BDREFEMISSAO, BDTPCR)
              values
               (current_connection, :prcodempprincipal, 1, :wvalor, 0, 1, :prcodcol, :wcoddep, :prtipcodrec, :PRTAGSTR, :PRDESCRICAOFOLHA, FALSE, :PRCODEMPORD, :WCPFCOL, 0,
                :wcpfdep, :wnomedep, :wtipodep, :wdatanas, :PRREFEMISSAO, :PRCODREC)
              matching (BDSESSAO, BDCODEMP, BDCODCOL, BDCPFCOL, BDCPFDEP, BDTIPOVAL, BDUNICO, BDTAGSTR, BDTIPCODREC, BDCODAUT, BDREFEMISSAO, BDTPCR);

              wcoddep = 0; wvalor = 0; wcodver = 0; wcpfdep = ''; wnomedep = ''; wtipodep = ''; wdatanas = null;
            end
          end
       else if ((prtipofolha in (1,110)) OR ((PRTIPOFOLHA = 4) AND (PRFC = 0))) then
          begin
            --  C_FICHA_FC, C_FICHA_FC_RESC   = 1, 110;      irver = 1,2        NORMAL OU RRA
            --  C_FICHA_FERIAS_FOLHA          = 4;           irver = 2          FN OU FC
            for select val.bdcodver, val.bdcodbenef, val.bdvalpend,ver.bdirver from (
                   select a.bdcodver, a.bdcodbenef, a.bdcodemp, a.bdcodcol, a.bdvalpend from VRHF_EMP_TFCPENSAO_DEP a where a.bdcodemp = : prcodemp and a.bdcodcol = :prcodcol and a.bdreffn = :prref and a.bdreffc = :prreffc
                   union all
                   select b.bdcodver, b.bdcodbenef, b.bdcodemp, b.bdcodcol, sum(b.bdvalpend) from VRHF_EMP_TFCTPENSAO_DEP b where b.bdcodemp = :prcodemp and b.bdcodcol = :prcodcol and b.bdreftomador = :prref and b.bdreffc = :prreffc
                   group by b.bdcodver, b.bdcodbenef, b.bdcodemp, b.bdcodcol
                   union all
                   select a.bdcodver, a.bdcodbenef bdcoddpn, a.bdcodemp, a.bdcodcol, a.bdvalpend from VRHF_EMP_TFCINTPENSAO_DEP a where a.bdcodemp = :prcodemp and a.bdcodcol = :prcodcol and a.bdreffn = :prref and a.bdreffc = :prreffc and a.BDCODCONTTI = :printaux
                   union all
                   select b.bdcodver, b.bdcodbenef bdcoddpn, b.bdcodemp, b.bdcodcol, sum(b.bdvalpend) from VRHF_EMP_TFCTINTPENSAO_DEP b where b.bdcodemp = :prcodemp and b.bdcodcol = :prcodcol and b.bdreftomador = :prref and b.bdreffc = :prreffc and b.BDCODCONTTI = :printaux
                   group by b.bdcodver, b.bdcodbenef, b.bdcodemp, b.bdcodcol) val
            join vrh_base_tverbas_ref ver on (val.bdcodver = ver.bdcodver and ver.bdrefver = (select first 1 x.bdrefver from vrh_base_tverbas_ref x where x.bdcodver = ver.bdcodver and x.bdrefver <= :prRef order by x.bdrefver desc))
            where ver.bdirver in (1,2) and  /* folha e férias pois é considerado pensão normal */
                  val.bdvalpend > 0
            into :wcodver, :wcoddep, :wvalor, :wbdirver do
            begin
              select first 1 bene.bdcpfbenef, bene.bdnombenef, bene.bdparenescodpn, bene.bddatanascbenef from VRH_EMP_TCOLCON_BENEF bene
              where bene.bdcodemp = :prcodemp and bene.bdcodcol = :prcodcol and bene.bdcodbenef = :wcoddep into :wcpfdep, :wnomedep, :wtipodep, :wdatanas;

              PRTAGSTR = coalesce(:PRTAGSTR,'');
              PRDESCRICAOFOLHA = coalesce(:PRDESCRICAOFOLHA,'');

              wvalorfer = 0;
              if (:wbdirver = 2) then
                 begin
                   wvalorfer = wvalor;
                   wvalor = 0;
                 end

              update or insert into VRHF_TEMP_EMP_TVAL5002
               (BDSESSAO, BDCODEMP, BDTIPOVAL, BDVALOR, BDVALORFER, BDUNICO,  bdcodcol, BDCODDEP, BDTIPCODREC, BDTAGSTR, BDDESCRICAOFOLHA, BDZERADO, BDCODEMPORD, BDCPFCOL, BDCODAUT,
                BDCPFDEP, BDNOME, BDTIPODEP, BDDATANAS, BDREFEMISSAO, BDTPCR)
              values
               (current_connection, :prcodempprincipal, 1, :wvalor, :wvalorfer, 1, :prcodcol, :wcoddep, :prtipcodrec, :PRTAGSTR, :PRDESCRICAOFOLHA, FALSE, :PRCODEMPORD, :WCPFCOL, 0,
                :wcpfdep, :wnomedep, :wtipodep, :wdatanas, :PRREFEMISSAO, :PRCODREC)
              matching (BDSESSAO, BDCODEMP, BDCODCOL, BDCPFCOL, BDCPFDEP, BDTIPOVAL, BDUNICO, BDTAGSTR, BDTIPCODREC, BDCODAUT, BDREFEMISSAO, BDTPCR);

              wcoddep = 0; wvalor = 0; wcodver = 0; wcpfdep = ''; wnomedep = ''; wtipodep = ''; wdatanas = null;
            end
          end
       else if (prtipofolha in (111)) then
          begin
            --  C_FICHA_FC_RESC_13            = 111;         irver = 3              RRA
            for select val.bdcodver, val.bdcodbenef, val.bdvalpend from (
                   select a.bdcodver, a.bdcodbenef, a.bdcodemp, a.bdcodcol, a.bdvalpend from VRHF_EMP_TFCPENSAO_DEP a where a.bdcodemp = : prcodemp and a.bdcodcol = :prcodcol and a.bdreffn = :prref and a.bdreffc = :prreffc
                   union all
                   select b.bdcodver, b.bdcodbenef, b.bdcodemp, b.bdcodcol, sum(b.bdvalpend) from VRHF_EMP_TFCTPENSAO_DEP b where b.bdcodemp = :prcodemp and b.bdcodcol = :prcodcol and b.bdreftomador = :prref and b.bdreffc = :prreffc
                   group by b.bdcodver, b.bdcodbenef, b.bdcodemp, b.bdcodcol
                   union all
                   select a.bdcodver, a.bdcodbenef bdcoddpn, a.bdcodemp, a.bdcodcol, a.bdvalpend from VRHF_EMP_TFCINTPENSAO_DEP a where a.bdcodemp = :prcodemp and a.bdcodcol = :prcodcol and a.bdreffn = :prref and a.bdreffc = :prreffc and a.BDCODCONTTI = :printaux
                   union all
                   select b.bdcodver, b.bdcodbenef bdcoddpn, b.bdcodemp, b.bdcodcol, sum(b.bdvalpend) from VRHF_EMP_TFCTINTPENSAO_DEP b where b.bdcodemp = :prcodemp and b.bdcodcol = :prcodcol and b.bdreftomador = :prref and b.bdreffc = :prreffc and b.BDCODCONTTI = :printaux
                   group by b.bdcodver, b.bdcodbenef, b.bdcodemp, b.bdcodcol) val
            join vrh_base_tverbas_ref ver on (val.bdcodver = ver.bdcodver and ver.bdrefver = (select first 1 x.bdrefver from vrh_base_tverbas_ref x where x.bdcodver = ver.bdcodver and x.bdrefver <= :prRef order by x.bdrefver desc))
            where ver.bdirver in (3) and  /* 13 */
                  val.bdvalpend > 0
            into :wcodver, :wcoddep, :wvalor do
            begin
              select first 1 bene.bdcpfbenef, bene.bdnombenef, bene.bdparenescodpn, bene.bddatanascbenef from VRH_EMP_TCOLCON_BENEF bene
              where bene.bdcodemp = :prcodemp and bene.bdcodcol = :prcodcol and bene.bdcodbenef = :wcoddep into :wcpfdep, :wnomedep, :wtipodep, :wdatanas;

              PRTAGSTR = coalesce(:PRTAGSTR,'');
              PRDESCRICAOFOLHA = coalesce(:PRDESCRICAOFOLHA,'');

              update or insert into VRHF_TEMP_EMP_TVAL5002
               (BDSESSAO, BDCODEMP, BDTIPOVAL, BDVALOR, BDVALORFER, BDUNICO, bdcodcol, BDCODDEP, BDTIPCODREC, BDTAGSTR, BDDESCRICAOFOLHA, BDZERADO, BDCODEMPORD, BDCPFCOL, BDCODAUT,
                BDCPFDEP, BDNOME, BDTIPODEP, BDDATANAS, BDREFEMISSAO, BDTPCR)
              values
               (current_connection, :prcodempprincipal, 1, :wvalor, 0, 1, :prcodcol, :wcoddep, :prtipcodrec, :PRTAGSTR, :PRDESCRICAOFOLHA, FALSE, :PRCODEMPORD, :WCPFCOL, 0,
                :wcpfdep, :wnomedep, :wtipodep, :wdatanas, :PRREFEMISSAO, :PRCODREC)
              matching (BDSESSAO, BDCODEMP, BDCODCOL, BDCPFCOL, BDCPFDEP, BDTIPOVAL, BDUNICO, BDTAGSTR, BDTIPCODREC, BDCODAUT, BDREFEMISSAO, BDTPCR);

              wcoddep = 0; wvalor = 0; wcodver = 0; wcpfdep = ''; wnomedep = ''; wtipodep = ''; wdatanas = null;
            end
          end
       else if (prtipofolha in (2)) then
          begin
            --  C_FICHA_AD_SAL                = 2;           irver = 1
            for select val.bdcodver, val.bdcoddpn, val.bdvalpend
                from VRHF_EMP_TADSALPENSAO_DEP val
                join vrh_base_tverbas_ref ver on (val.bdcodver = ver.bdcodver and
                ver.bdrefver = (select first 1 x.bdrefver from vrh_base_tverbas_ref x where x.bdcodver = ver.bdcodver and x.bdrefver <= :prRef order by x.bdrefver desc))
                where val.bdcodemp = : prcodemp and val.bdcodcol = :prcodcol and val.bddataad = :prdatacalc and
                      ver.bdirver in (1) and  /* folha */
                      val.bdvalpend > 0
            into :wcodver, :wcoddep, :wvalor do
            begin
              select first 1 bene.bdcpfbenef, bene.bdnombenef, bene.bdparenescodpn, bene.bddatanascbenef
              from VRH_EMP_TCOLCON_BENEF bene
              where bene.bdcodemp = :prcodemp and bene.bdcodcol = :prcodcol and bene.bdcodbenef = :wcoddep
              into :wcpfdep, :wnomedep, :wtipodep, :wdatanas;

              PRTAGSTR = coalesce(:PRTAGSTR,'');
              PRDESCRICAOFOLHA = coalesce(:PRDESCRICAOFOLHA,'');

              update or insert into VRHF_TEMP_EMP_TVAL5002
               (BDSESSAO, BDCODEMP, BDTIPOVAL, BDVALOR, BDVALORFER, BDUNICO, bdcodcol, BDCODDEP, BDTIPCODREC, BDTAGSTR, BDDESCRICAOFOLHA, BDZERADO, BDCODEMPORD, BDCPFCOL, BDCODAUT,
                BDCPFDEP, BDNOME, BDTIPODEP, BDDATANAS, BDREFEMISSAO, BDTPCR)
              values
               (current_connection, :prcodempprincipal, 1, :wvalor, 0, 1, :prcodcol, :wcoddep, :prtipcodrec, :PRTAGSTR, :PRDESCRICAOFOLHA, FALSE, :PRCODEMPORD, :WCPFCOL, 0,
                :wcpfdep, :wnomedep, :wtipodep, :wdatanas, :PRREFEMISSAO, :PRCODREC)
              matching (BDSESSAO, BDCODEMP, BDCODCOL, BDCPFCOL, BDCPFDEP, BDTIPOVAL, BDUNICO, BDTAGSTR, BDTIPCODREC, BDCODAUT, BDREFEMISSAO, BDTPCR);

              wcoddep = 0;
              wvalor = 0;
              wcodver = 0;
              wcpfdep = '';
              wnomedep = '';
              wtipodep = '';
              wdatanas = null;
            end
          end
       else if (prtipofolha in (3)) then
          begin
            --  C_FICHA_FERIAS                = 3;           irver = 2
            for select val.bdcodver, val.bdcodbenef, val.bdvalpend,ver.bdirver
                from VRHF_EMP_TFEPENSAO_DEP val
                join vrh_base_tverbas_ref ver on (val.bdcodver = ver.bdcodver and
                     ver.bdrefver = (select first 1 x.bdrefver from vrh_base_tverbas_ref x where x.bdcodver = ver.bdcodver and x.bdrefver <= :prRef order by x.bdrefver desc))
                where val.bdcodemp = :prcodemp and val.bdcodcol = :prcodcol and val.BDINIPERAQUISFE = :prdatacalc and val.bdcodfe = :printaux and
                      ver.bdirver in (2) and  /* férias */
                      val.bdvalpend > 0
            into :wcodver, :wcoddep, :wvalor,:wbdirver do
            begin
              select first 1 bene.bdcpfbenef, bene.bdnombenef, bene.bdparenescodpn, bene.bddatanascbenef
              from VRH_EMP_TCOLCON_BENEF bene
              where bene.bdcodemp = :prcodemp and bene.bdcodcol = :prcodcol and bene.bdcodbenef = :wcoddep
              into :wcpfdep, :wnomedep, :wtipodep, :wdatanas;

              PRTAGSTR = coalesce(:PRTAGSTR,'');
              PRDESCRICAOFOLHA = coalesce(:PRDESCRICAOFOLHA,'');

              update or insert into VRHF_TEMP_EMP_TVAL5002
               (BDSESSAO, BDCODEMP, BDTIPOVAL, BDVALOR, BDVALORFER, BDUNICO, bdcodcol, BDCODDEP, BDTIPCODREC, BDTAGSTR, BDDESCRICAOFOLHA, BDZERADO, BDCODEMPORD, BDCPFCOL, BDCODAUT,
                BDCPFDEP, BDNOME, BDTIPODEP, BDDATANAS, BDREFEMISSAO, BDTPCR)
              values
               (current_connection, :prcodempprincipal, 1,0, :wvalor, 1, :prcodcol, :wcoddep, :prtipcodrec, :PRTAGSTR, :PRDESCRICAOFOLHA, FALSE, :PRCODEMPORD, :WCPFCOL, 0,
                :wcpfdep, :wnomedep, :wtipodep, :wdatanas, :PRREFEMISSAO, :PRCODREC)
              matching (BDSESSAO, BDCODEMP, BDCODCOL, BDCPFCOL, BDCPFDEP, BDTIPOVAL, BDUNICO, BDTAGSTR, BDTIPCODREC, BDCODAUT, BDREFEMISSAO, BDTPCR);

              wcoddep = 0;
              wvalor = 0;
              wcodver = 0;
              wcpfdep = '';
              wnomedep = '';
              wtipodep = '';
              wdatanas = null;
            end
          end
       /*else if (prtipofolha in (9)) then
          begin
            --  C_FICHA_AD13                  = 9;           irver = 3
            for select val.bdcodver, val.bdcoddpn, val.bdvalpend
                from VRHF_EMP_TA13PENSAO_DEP val
                join vrh_base_tverbas_ref ver on (val.bdcodver = ver.bdcodver and
                     ver.bdrefver = (select first 1 x.bdrefver from vrh_base_tverbas_ref x where x.bdcodver = ver.bdcodver and x.bdrefver <= :prRef order by x.bdrefver desc))
                where val.bdcodemp = :prcodemp and val.bdcodcol = :prcodcol and val.bdrefa13 = :prref and
                      ver.bdirver in (3) and  -- férias 
                      val.bdvalpend > 0
            into :wcodver, :wcoddep, :wvalor do
            begin
              select first 1 bene.bdcpfbenef, bene.bdnombenef, bene.bdparenescodpn, bene.bddatanascbenef
              from VRH_EMP_TCOLCON_BENEF bene
              where bene.bdcodemp = :prcodemp and bene.bdcodcol = :prcodcol and bene.bdcodbenef = :wcoddep
              into :wcpfdep, :wnomedep, :wtipodep, :wdatanas;

              PRTAGSTR = coalesce(:PRTAGSTR,'');
              PRDESCRICAOFOLHA = coalesce(:PRDESCRICAOFOLHA,'');

              update or insert into VRHF_TEMP_EMP_TVAL5002
               (BDSESSAO, BDCODEMP, BDTIPOVAL, BDVALOR, BDVALORFER, BDUNICO, bdcodcol, BDCODDEP, BDTIPCODREC, BDTAGSTR, BDDESCRICAOFOLHA, BDZERADO, BDCODEMPORD, BDCPFCOL, BDCODAUT,
                BDCPFDEP, BDNOME, BDTIPODEP, BDDATANAS, BDREFEMISSAO, BDTPCR)
              values
               (current_connection, :prcodempprincipal, 1, :wvalor, 0, 1, :prcodcol, :wcoddep, :prtipcodrec, :PRTAGSTR, :PRDESCRICAOFOLHA, FALSE, :PRCODEMPORD, :WCPFCOL, 0,
                :wcpfdep, :wnomedep, :wtipodep, :wdatanas, :PRREFEMISSAO, :PRCODREC)
              matching (BDSESSAO, BDCODEMP, BDCODCOL, BDCPFCOL, BDCPFDEP, BDTIPOVAL, BDUNICO, BDTAGSTR, BDTIPCODREC, BDCODAUT, BDREFEMISSAO, BDTPCR);

              wcoddep = 0;
              wvalor = 0;
              wcodver = 0;
              wcpfdep = '';
              wnomedep = '';
              wtipodep = '';
              wdatanas = null;
            end
          end*/
       else if (prtipofolha in (10)) then
          begin
            --  C_FICHA_13                    = 10;          irver = 3
            for select val.bdcodver, val.bdcoddpn, val.bdvalpend
                from VRHF_EMP_T13PENSAO_DEP val
                join vrh_base_tverbas_ref ver on (val.bdcodver = ver.bdcodver and
                     ver.bdrefver = (select first 1 x.bdrefver from vrh_base_tverbas_ref x where x.bdcodver = ver.bdcodver and x.bdrefver <= :prRef order by x.bdrefver desc))
                where val.bdcodemp = :prcodemp and val.bdcodcol = :prcodcol and val.bdref13 = :prref and
                      ver.bdirver in (3) and  /* férias */
                      val.bdvalpend > 0
                union all
                select ad.bdcodver,ad.bdcoddpn,ad.bdvalpend from VRHF_EMP_TA13PENSAO_DEP ad
                where ad.BDCODEMP = :prcodemp and ad.BDCODCOL = :prcodcol and cast(ad.BDREFA13 as varchar(6)) starting with substring(cast(:prref as varchar(6)) from 1 for 4) and ad.bdvalpend > 0
            into :wcodver, :wcoddep, :wvalor do
            begin
              select first 1 bene.bdcpfbenef, bene.bdnombenef, bene.bdparenescodpn, bene.bddatanascbenef
              from VRH_EMP_TCOLCON_BENEF bene
              where bene.bdcodemp = :prcodemp and bene.bdcodcol = :prcodcol and bene.bdcodbenef = :wcoddep
              into :wcpfdep, :wnomedep, :wtipodep, :wdatanas;

              PRTAGSTR = coalesce(:PRTAGSTR,'');
              PRDESCRICAOFOLHA = coalesce(:PRDESCRICAOFOLHA,'');

              update or insert into VRHF_TEMP_EMP_TVAL5002
               (BDSESSAO, BDCODEMP, BDTIPOVAL, BDVALOR, BDVALORFER, BDUNICO, bdcodcol, BDCODDEP, BDTIPCODREC, BDTAGSTR, BDDESCRICAOFOLHA, BDZERADO, BDCODEMPORD, BDCPFCOL, BDCODAUT,
                BDCPFDEP, BDNOME, BDTIPODEP, BDDATANAS, BDREFEMISSAO, BDTPCR)
              values
               (current_connection, :prcodempprincipal, 1, :wvalor, 0, 1, :prcodcol, :wcoddep, :prtipcodrec, :PRTAGSTR, :PRDESCRICAOFOLHA, FALSE, :PRCODEMPORD, :WCPFCOL, 0,
                :wcpfdep, :wnomedep, :wtipodep, :wdatanas, :PRREFEMISSAO, :PRCODREC)
              matching (BDSESSAO, BDCODEMP, BDCODCOL, BDCPFCOL, BDCPFDEP, BDTIPOVAL, BDUNICO, BDTAGSTR, BDTIPCODREC, BDCODAUT, BDREFEMISSAO, BDTPCR);

              wcoddep = 0;
              wvalor = 0;
              wcodver = 0;
              wcpfdep = '';
              wnomedep = '';
              wtipodep = '';
              wdatanas = null;
            end
          end
       else if (prtipofolha in (11)) then
          begin
            --  C_FICHA_C13                   = 11;          irver = 3
            for select val.bdcodver, val.bdcodbenef, val.bdvalpend
                from VRHF_EMP_TC13PENSAO_DEP val
                join vrh_base_tverbas_ref ver on (val.bdcodver = ver.bdcodver and
                     ver.bdrefver = (select first 1 x.bdrefver from vrh_base_tverbas_ref x where x.bdcodver = ver.bdcodver and x.bdrefver <= :prRef order by x.bdrefver desc))
                where val.bdcodemp = :prcodemp and val.bdcodcol = :prcodcol and val.bdref13 = :prref and
                      ver.bdirver in (3) and  /* férias */
                      val.bdvalpend > 0
            into :wcodver, :wcoddep, :wvalor do
            begin
              select first 1 bene.bdcpfbenef, bene.bdnombenef, bene.bdparenescodpn, bene.bddatanascbenef
              from VRH_EMP_TCOLCON_BENEF bene
              where bene.bdcodemp = :prcodemp and bene.bdcodcol = :prcodcol and bene.bdcodbenef = :wcoddep
              into :wcpfdep, :wnomedep, :wtipodep, :wdatanas;

              PRTAGSTR = coalesce(:PRTAGSTR,'');
              PRDESCRICAOFOLHA = coalesce(:PRDESCRICAOFOLHA,'');

              update or insert into VRHF_TEMP_EMP_TVAL5002
               (BDSESSAO, BDCODEMP, BDTIPOVAL, BDVALOR, BDVALORFER, BDUNICO, bdcodcol, BDCODDEP, BDTIPCODREC, BDTAGSTR, BDDESCRICAOFOLHA, BDZERADO, BDCODEMPORD, BDCPFCOL, BDCODAUT,
                BDCPFDEP, BDNOME, BDTIPODEP, BDDATANAS, BDREFEMISSAO, BDTPCR)
              values
               (current_connection, :prcodempprincipal, 1, :wvalor, 0, 1, :prcodcol, :wcoddep, :prtipcodrec, :PRTAGSTR, :PRDESCRICAOFOLHA, FALSE, :PRCODEMPORD, :WCPFCOL, 0,
                :wcpfdep, :wnomedep, :wtipodep, :wdatanas, :prrefemissao, :PRCODREC)
              matching (BDSESSAO, BDCODEMP, BDCODCOL, BDCPFCOL, BDCPFDEP, BDTIPOVAL, BDUNICO, BDTAGSTR, BDTIPCODREC, BDCODAUT, BDREFEMISSAO, BDTPCR);

              wcoddep = 0;
              wvalor = 0;
              wcodver = 0;
              wcpfdep = '';
              wnomedep = '';
              wtipodep = '';
              wdatanas = null;
            end
          end
       else if (prtipofolha in (50)) then
          begin
            --  C_FICHA_FA                    = 50;          irver = 1
            for select val.bdcodver, val.bdcoddpn, val.bdvalpend
                from VRHF_EMP_TFAPENSAO_DEP val
                join vrh_base_tverbas_ref ver on (val.bdcodver = ver.bdcodver and
                     ver.bdrefver = (select first 1 x.bdrefver from vrh_base_tverbas_ref x where x.bdcodver = ver.bdcodver and x.bdrefver <= :prRef order by x.bdrefver desc))
                where val.bdcodemp = :prcodemp and val.bdcodcol = :prcodcol and val.bddatafa = :prdatacalc and val.bdcodtca = :printaux and
                      ver.bdirver in (1) and  /* normal */
                      val.bdvalpend > 0
            into :wcodver, :wcoddep, :wvalor do
            begin
              select first 1 bene.bdcpfbenef, bene.bdnombenef, bene.bdparenescodpn, bene.bddatanascbenef
              from VRH_EMP_TCOLCON_BENEF bene
              where bene.bdcodemp = :prcodemp and bene.bdcodcol = :prcodcol and bene.bdcodbenef = :wcoddep
              into :wcpfdep, :wnomedep, :wtipodep, :wdatanas;

              PRTAGSTR = coalesce(:PRTAGSTR,'');
              PRDESCRICAOFOLHA = coalesce(:PRDESCRICAOFOLHA,'');

              update or insert into VRHF_TEMP_EMP_TVAL5002
               (BDSESSAO, BDCODEMP, BDTIPOVAL, BDVALOR, BDVALORFER, BDUNICO, bdcodcol, BDCODDEP, BDTIPCODREC, BDTAGSTR, BDDESCRICAOFOLHA, BDZERADO, BDCODEMPORD, BDCPFCOL, BDCODAUT,
                BDCPFDEP, BDNOME, BDTIPODEP, BDDATANAS, BDREFEMISSAO, BDTPCR)
              values
               (current_connection, :prcodempprincipal, 1, :wvalor, 0, 1, :prcodcol, :wcoddep, :prtipcodrec, :PRTAGSTR, :PRDESCRICAOFOLHA, FALSE, :PRCODEMPORD, :WCPFCOL, 0,
                :wcpfdep, :wnomedep, :wtipodep, :wdatanas, :prrefemissao, :PRCODREC)
              matching (BDSESSAO, BDCODEMP, BDCODCOL, BDCPFCOL, BDCPFDEP, BDTIPOVAL, BDUNICO, BDTAGSTR, BDTIPCODREC, BDCODAUT, BDREFEMISSAO, BDTPCR);

              wcoddep = 0;
              wvalor = 0;
              wcodver = 0;
              wcpfdep = '';
              wnomedep = '';
              wtipodep = '';
              wdatanas = null;
            end
          end
       else if (prtipofolha >= 9000) then
          begin
            -- FICHA FINANCEIRA
            for select val.bdcodbenef, val.bdvalpend
                from VRHF_EMP_TFIPENSAO_DEP val
                where val.bdcodemp = :prcodemp and val.bdcodcol = :prcodcol and val.bdcomppend = :prref and val.bdrefpagpend = :prrefpag and val.bdtipopend = :prtipofolha and val.bdvalpend > 0
            into :wcoddep, :wvalor do
            begin
              select first 1 bene.bdcpfbenef, bene.bdnombenef, bene.bdparenescodpn, bene.bddatanascbenef
              from VRH_EMP_TCOLCON_BENEF bene
              where bene.bdcodemp = :prcodemp and bene.bdcodcol = :prcodcol and bene.bdcodbenef = :wcoddep
              into :wcpfdep, :wnomedep, :wtipodep, :wdatanas;

              PRTAGSTR = coalesce(:PRTAGSTR,'');
              PRDESCRICAOFOLHA = coalesce(:PRDESCRICAOFOLHA,'');

              wvalorfer = 0;
              if (prtipofolha = 9030) then
                 begin
                   wvalorfer = wvalor;
                   wvalor = 0;
                 end

              update or insert into VRHF_TEMP_EMP_TVAL5002
               (BDSESSAO, BDCODEMP, BDTIPOVAL, BDVALOR, BDVALORFER, BDUNICO, bdcodcol, BDCODDEP, BDTIPCODREC, BDTAGSTR, BDDESCRICAOFOLHA, BDZERADO, BDCODEMPORD, BDCPFCOL, BDCODAUT,
                BDCPFDEP, BDNOME, BDTIPODEP, BDDATANAS, BDREFEMISSAO, BDTPCR)
              values
               (current_connection, :prcodempprincipal, 1, :wvalor, :wvalorfer, 1, :prcodcol, :wcoddep, :prtipcodrec, :PRTAGSTR, :PRDESCRICAOFOLHA, FALSE, :PRCODEMPORD, :WCPFCOL, 0,
                :wcpfdep, :wnomedep, :wtipodep, :wdatanas, :PRREFEMISSAO, :PRCODREC)
              matching (BDSESSAO, BDCODEMP, BDCODCOL, BDCPFCOL, BDCPFDEP, BDTIPOVAL, BDUNICO, BDTAGSTR, BDTIPCODREC, BDCODAUT, BDREFEMISSAO, BDTPCR);

              wcoddep = 0;
              wvalor = 0;
              wcodver = 0;
              wcpfdep = '';
              wnomedep = '';
              wtipodep = '';
              wdatanas = null;
            end
          end

       IF ((COALESCE(PRUNICO, 0) = 1) and (PRTIPOFOLHA<>11)) THEN
          BEGIN
            IF (((COALESCE(PRINCIDESOCIAL, 0) > 0) or (COALESCE(PRINCIDESOCIALFER, 0) > 0)) and (prtipcodrec <> 4) and (prtipcodrec <> 3)) THEN
               BEGIN
                 WTABIREMP = 0;
                 SELECT FIRST 1 BDCODIR FROM VRHF_BASE_TEMPVINC
                 WHERE BDCODEMP = :PRCODEMP AND
                       BDREFEMP <= :PRREFEMISSAO
                 ORDER BY BDREFEMP DESC
                 INTO :WTABIREMP;

                 WVALOR = 0;
                 WVALORFER = 0;
                 IF (COALESCE(WTABIREMP, 0) > 0) THEN
                    BEGIN
                      SELECT FIRST 1 BDVALDEPIR FROM VRHF_TABELAS_TIRDADOS
                      WHERE BDCODIR = :WTABIREMP AND
                            BDREFIR <= :PRREFEMISSAO and
                            BDTIPOCALCFIR = 0
                      ORDER BY BDREFIR DESC
                      INTO :WVALOR;

                      if (COALESCE(princidesocialfer, 0) > 0) then
                         WVALORFER = COALESCE(WVALOR, 0);

                      if (COALESCE(princidesocial, 0) <= 0) then
                         WVALOR = 0;
                    END
                 ELSE
                    BEGIN
                      SELECT FIRST 1 D.BDVALDEPIR
                      FROM VRHF_TABELAS_TIRDADOS D
                      LEFT OUTER JOIN VRHF_TABELAS_TIRFAIXAS F ON (D.BDCODIR = F.BDCODIR AND
                            D.BDCODDIR = F.BDCODDIR)
                      WHERE D.BDTIPOCALCFIR = 0 AND
                            COALESCE(D.BDCODTCA, 0) = 0 AND
                            (D.BDREFIR = (SELECT FIRST 1 BDREFIR
                                          FROM VRHF_TABELAS_TIRDADOS X
                                          WHERE X.BDCODIR = D.BDCODIR AND
                                                X.BDTIPOCALCFIR = 0 AND
                                                COALESCE(X.BDCODTCA, 0) = 0 AND
                                                X.BDREFIR <= :PRREFEMISSAO
                                          ORDER BY BDREFIR DESC))
                      ORDER BY D.BDCODIR, D.BDCODDIR, D.BDTIPOCALCFIR, D.BDREFIR, F.BDFAIXAIR
                      INTO :WVALOR;

                      if (COALESCE(princidesocialfer, 0) > 0) then
                         WVALORFER = COALESCE(WVALOR, 0);

                      if (COALESCE(princidesocial, 0) <= 0) then
                         WVALOR = 0;  
                    END

                 WCPFDEP = '';
                 WNOMEDEP = '';
                 WTIPODEP = '';
                 WDESCDEP = '';
                 WDATANAS = null;
                 WCODDEP = 0;
                 FOR
                    SELECT DEPREF.BDCPFDPN, DEPREF.BDNOMEDPN, DES.BDCODESOCIAL, DEPREF.BDDESCRDEPDPN,
                           DEPREF.BDDATANASCDPN, DEPREF.BDCODDPN
                    FROM VRH_EMP_TDEP DEP
                    JOIN (
                          SELECT X.bdcodemp, X.BDCODCOL, X.bdcoddpn,
                                 COALESCE
                                  (
                                      (SELECT MAX(d2.BDREFDPN) FROM vrh_emp_tdep_ref d2 WHERE d2.bdcodemp = x.bdcodemp AND d2.bdcodcol = x.bdcodcol AND d2.bdcoddpn = x.bdcoddpn AND CAST(d2.BDREFDPN AS VARCHAR(6)) <= :PRREFEMISSAO),
                                      (SELECT MIN(d1.BDREFDPN) FROM vrh_emp_tdep_ref d1 WHERE d1.bdcodemp = x.bdcodemp AND d1.bdcodcol = x.bdcodcol AND d1.bdcoddpn = x.bdcoddpn)
                                  ) AS BDREFDPN
                          FROM  vrh_emp_tdep x
                        ) AS DEPREF_MAX ON (DEP.BDCODEMP = DEPREF_MAX.BDCODEMP AND DEP.BDCODCOL = DEPREF_MAX.BDCODCOL AND DEP.BDCODDPN = DEPREF_MAX.BDCODDPN)
                    JOIN VRH_EMP_TDEP_REF DEPREF ON (DEP.BDCODEMP = DEPREF.BDCODEMP AND
                          DEP.BDCODCOL = DEPREF.BDCODCOL AND
                          DEP.BDCODDPN = DEPREF.BDCODDPN AND
                          DEPREF.BDREFDPN = DEPREF_MAX.BDREFDPN)
                    LEFT OUTER JOIN VRH_TTIPO_DEP_ESOCIAL DES ON (DES.BDCODTIPODEP = DEPREF.BDPARENESCODPN)
                    WHERE DEP.BDCODEMP = :PRCODEMP AND
                          DEP.BDCODCOL = :PRCODCOL AND
                          UPPER(COALESCE(DEPREF.BDDEPIRDPN, 'FALSE')) = 'TRUE' AND
                          DEPREF.BDPARENESCODPN <> 3 AND
                          (SELECT BDAAAAMM
                           FROM AAAAMM(CASE
                                         WHEN COALESCE(DEPREF.BDDATANASCDPN, DEP.BDDATAENTREDPN) < DEP.BDDATAENTREDPN THEN BDDATAENTREDPN
                                         ELSE COALESCE(DEPREF.BDDATANASCDPN, DEP.BDDATAENTREDPN)
                                       END)) <= :PRREFEMISSAO AND
                          ((DEP.BDDATABAUXADPN IS NULL) OR ((SELECT BDAAAAMM FROM AAAAMM(DEP.BDDATABAUXADPN)) > :PRREFEMISSAO)) AND
                          ((DEP.BDREFIRDPN IS NULL) OR (DEP.BDREFIRDPN = 0) OR (DEP.BDREFIRDPN >= :PRREFEMISSAO)) AND
                          ((UPPER(DEPREF.BDINVALIDODPN) = 'TRUE') OR (DEP.BDREFIRDPN >= :PRREFEMISSAO) OR (NOT DEPREF.BDDATANASCDPN IS NULL) AND
                          (((DEPREF.BDPARENESCODPN IN (0, 4, 5, 6, 10, 11)) AND
                          (:PRREFEMISSAO - CAST((SELECT BDAAAAMM
                                          FROM AAAAMM(DEPREF.BDDATANASCDPN)) AS INTEGER) < 2200)) OR (DEPREF.BDPARENESCODPN IN (1, 2, 7, 9))))
                     /* Verificar evento 1210 */
                 INTO :WCPFDEP, :WNOMEDEP, :WTIPODEP, :WDESCDEP, :WDATANAS, :WCODDEP DO
                 BEGIN
                   WDESCDEP = coalesce(WDESCDEP, '');
                   WNOMEDEP = coalesce(:WNOMEDEP, '');
                   WDATANAS = COALESCE(:WDATANAS, '');
                   WCPFDEP = coalesce(:WCPFDEP, '');
                   PRTAGSTR = COALESCE(:PRTAGSTR, '');
                   PRDESCRICAOFOLHA = COALESCE(:PRDESCRICAOFOLHA, '');

                   if (coalesce(wtipodep, '0') <> '99') then
                      SELECT FIRST 1 BDDESCTIPODEP FROM VRH_TTIPO_DEP_ESOCIAL WHERE BDCODESOCIAL = COALESCE(:WTIPODEP, '0')
                      ORDER BY BDCODTIPODEP
                      INTO :WDESCDEP;

                   update or insert into VRHF_TEMP_EMP_TVAL5002
                   (BDSESSAO, BDCODEMP, BDTIPOVAL, BDVALOR, BDVALORFER, BDUNICO, bdcodcol, BDCODDEP, BDTIPCODREC, BDTAGSTR, BDDESCRICAOFOLHA,
                   BDCPFDEP, BDNOME, BDTIPODEP, BDDATANAS, BDDESCDEP, BDZERADO, BDCODEMPORD, BDCPFCOL, BDCODAUT, BDREFEMISSAO, BDTPCR)
                   values
                   (current_connection, :prcodempprincipal, 0, :wvalor, :wvalorfer, 1, :prcodcol, :wcoddep, :prtipcodrec, '', '',
                   :WCPFDEP, :WNOMEDEP, :WTIPODEP, :WDATANAS, :WDESCDEP, FALSE, :PRCODEMPORD, :WCPFCOL, 0, :PRREFEMISSAO, :PRCODREC)
                   matching (BDSESSAO, BDCODEMPORD, BDCPFCOL, BDCPFDEP, BDTIPOVAL, BDUNICO, BDTAGSTR, BDTIPCODREC, BDREFEMISSAO, BDTPCR);

                   WCPFDEP = '';
                   WNOMEDEP = '';
                   WTIPODEP = '';
                   WDESCDEP = '';
                   WDATANAS = null;
                   WCODDEP = 0;
                 END
               END
          END
     end
  else if (COALESCE(prautonomo, 0) > 0) then
     begin
       WCPFCOL = '';
       select first 1 RH.BDCPFMEITER from TTERCEIRO_RH RH where RH.BDCODTER = :prautonomo and char_length(RH.BDCPFMEITER) = 14 into :WCPFCOL;

       if (COALESCE(WCPFCOL, '') = '') then
          select first 1 TER.BDCGCTER FROM TTERCEIRO TER where TER.BDCODTER = :prautonomo into :WCPFCOL;

       IF (COALESCE(PRUNICO, 0) = 2) THEN
          BEGIN
            WEVTANT = -1;
            WCPFDEP = '';
            WNOMEDEP = '';
            WTIPODEP = '';
            WDESCDEP = '';
            WDATANAS = null;
            WTIPOREGISTRO = -1;
            WEVT = 0;
            WVALOR = 0;
            WDEPIRRF = '';

           FOR SELECT DEP.BDCPFDEP, DEP.BDNOME, DEP.BDTPDEP, DEP.BDDESCRDEP, DEP.BDDTNASCTO, DEP.BDTIPOREGISTRO, CONSOLID.BDCODEVT, DEP.BDVLR, DEP.BDDEPIRRF, DEP.BDTPREND,
                      CONSOLID.BDTIPOCALCULO
               FROM VRH_ESOCIAL_CONSOLIDAPURMEN_C_TERC CONSOLID
               INNER JOIN VRH_ESOCIAL_INFOIRRF_DEP_TERC DEP ON (CONSOLID.BDCODEMP = DEP.BDCODEMP AND CONSOLID.BDCODTER = DEP.BDCODTER AND CONSOLID.BDCODEVT = DEP.BDCODEVT AND
                                                           CONSOLID.BDTIPOCALCFIR = DEP.BDTIPOCALCFIR AND CONSOLID.BDCODCONSOLID = DEP.BDCODCONSOLID)
               WHERE CONSOLID.BDCODEMP = :PRCODEMP AND
                     CONSOLID.BDCODTER = :PRAUTONOMO AND
                     CONSOLID.BDREFEVT = :PRREFEMISSAO
               ORDER BY CONSOLID.BDCODEVT DESC, CONSOLID.BDTIPOCALCULO
           INTO :WCPFDEP, :WNOMEDEP, :WTIPODEP, :WDESCDEP, :WDATANAS, :WTIPOREGISTRO, :WEVT, :WVALOR, :WDEPIRRF, :WTIPOREND, :prtipcodrec DO
           BEGIN
             if (wevtant = -1) then
                wevtant = wevt;
             else if (wevt <> wevtant) then
                break;

--             if (((COALESCE(WTIPOREGISTRO, 0) = 1) and (COALESCE(WDEPIRRF, 'N') = 'S')) or
--                (COALESCE(WTIPOREGISTRO, 0) = 2)) then
                begin
                  WVALORFER = 0;
                  if ((WTIPOREND = 13)) then
                     BEGIN
                       WVALORFER = WVALOR;
                       WVALOR = 0;
                     END

                  if (WTIPOREGISTRO = 1) then
                     begin
                       WTIPOREGISTRO = 0;
                       if ((COALESCE(wtipodep,'') <> '') and (coalesce(wtipodep, '0') <> '99')) then
                          SELECT FIRST 1 BDDESCTIPODEP FROM VRH_TTIPO_DEP_ESOCIAL WHERE BDCODESOCIAL = COALESCE(:WTIPODEP, '0')
                          ORDER BY BDCODTIPODEP
                          INTO :WDESCDEP;
                       else if ((COALESCE(wtipodep,'') = '') and (COALESCE(WDEPIRRF, '') = '')) then
                          begin
                            SELECT FIRST 1 DES.BDCODESOCIAL, case when DES.BDCODESOCIAL <> 99 then DES.BDDESCTIPODEP else :WDESCDEP end BDDESCTIPODEP
                            FROM VRH_BASE_TTERC_TDEP DEP
                            JOIN (SELECT BDCODTER, BDCODDPNTERC, COALESCE( (SELECT FIRST 1 BDREFDPN
                                                                            FROM VRH_BASE_TTERC_TDEP_REF
                                                                            WHERE BDCODTER = DEP.BDCODTER AND
                                                                                  BDCODDPNTERC = DEP.BDCODDPNTERC AND
                                                                                  BDREFDPN <= :PRREFEMISSAO
                                                                            ORDER BY BDREFDPN DESC),
                                                                           (SELECT MIN(BDREFDPN)
                                                                            FROM VRH_BASE_TTERC_TDEP_REF
                                                                            WHERE BDCODTER = DEP.BDCODTER AND
                                                                                  BDCODDPNTERC = DEP.BDCODDPNTERC)
                                                                            ) BDREFDPN
                            FROM VRH_BASE_TTERC_TDEP DEP) DEPREF_MAXMIN ON (DEP.BDCODTER = DEPREF_MAXMIN.BDCODTER AND DEP.BDCODDPNTERC = DEPREF_MAXMIN.BDCODDPNTERC)
                            JOIN VRH_BASE_TTERC_TDEP_REF DEPREF ON (DEP.BDCODTER = DEPREF.BDCODTER AND DEP.BDCODDPNTERC = DEPREF.BDCODDPNTERC AND DEPREF.BDREFDPN = DEPREF_MAXMIN.BDREFDPN)
                            LEFT OUTER JOIN VRH_TTIPO_DEP_ESOCIAL DES ON (DES.BDCODTIPODEP = DEPREF.BDPARENESCODPNTERC)
                            WHERE DEPREF.BDCODTER = :PRAUTONOMO AND
                                  DEPREF.BDCPFDPNTERC = :WCPFDEP
                            INTO :wtipodep, :WDESCDEP;
                          end
                     end
                  ELSE
                     WTIPOREGISTRO = 1;

                  if (COALESCE(wtipodep,'') = '') then
                     wtipodep = '0';

                  PRTAGSTR = coalesce(:PRTAGSTR,'');
                  PRDESCRICAOFOLHA = coalesce(:PRDESCRICAOFOLHA,'');

                  update or insert into VRHF_TEMP_EMP_TVAL5002
                  (BDSESSAO, BDCODEMP, BDTIPOVAL, BDVALOR, BDVALORFER, BDUNICO, BDCODAUT, BDCODDEP, BDTIPCODREC, BDTAGSTR, BDDESCRICAOFOLHA,
                  BDCPFDEP, BDNOME, BDTIPODEP, BDDATANAS, BDDESCDEP, BDZERADO, BDCODEMPORD, BDCPFCOL, BDCODCOL, BDREFEMISSAO, BDTPCR)
                  values
                  (current_connection, :prcodempprincipal, :WTIPOREGISTRO, :wvalor, :WVALORFER, 2, :prautonomo, 0, :prtipcodrec,
                  :PRTAGSTR, :PRDESCRICAOFOLHA,
                  :WCPFDEP, :WNOMEDEP, :WTIPODEP, :WDATANAS, :WDESCDEP, FALSE, :PRCODEMPORD, :WCPFCOL, 0, :PRREFEMISSAO, :PRCODREC)
                  matching (BDSESSAO, BDCODEMPORD, BDCPFCOL, BDTIPOVAL, BDUNICO, BDCPFDEP, BDTIPCODREC, BDTAGSTR, BDREFEMISSAO, BDTPCR);
                end

             WCPFDEP = '';
             WNOMEDEP = '';
             WTIPODEP = '';
             WDESCDEP = '';
             WDATANAS = null;
             WTIPOREGISTRO = -1;
             WEVT = 0;
             WVALOR = 0;
             WDEPIRRF = '';
           END
          END
       ELSE IF (COALESCE(PRUNICO, 0) = 1) THEN
          begin
            IF ((COALESCE(PRINCIDESOCIAL, 0) > 0) or (COALESCE(PRINCIDESOCIALFER, 0) > 0)) THEN
               BEGIN
                 WTABIREMP = 0;
                 SELECT FIRST 1 BDCODIR FROM VRHF_BASE_TEMPVINC
                 WHERE BDCODEMP = :PRCODEMP AND
                       BDREFEMP <= :PRREFEMISSAO
                 ORDER BY BDREFEMP DESC
                 INTO :WTABIREMP;

                 WVALOR = 0;
                 WVALORFER = 0;
                 IF (COALESCE(WTABIREMP, 0) > 0) THEN
                    BEGIN
                      SELECT FIRST 1 BDVALDEPIR FROM VRHF_TABELAS_TIRDADOS
                      WHERE BDCODIR = :WTABIREMP AND
                            BDREFIR <= :PRREFEMISSAO and
                            BDTIPOCALCFIR = 0
                      ORDER BY BDREFIR DESC
                      INTO :WVALOR;

                      if (COALESCE(princidesocialfer, 0) > 0) then
                         WVALORFER = COALESCE(WVALOR, 0);

                      if (COALESCE(princidesocial, 0) <= 0) then
                         WVALOR = 0;
                    END
                 ELSE
                    BEGIN
                      SELECT FIRST 1 D.BDVALDEPIR
                      FROM VRHF_TABELAS_TIRDADOS D
                      LEFT OUTER JOIN VRHF_TABELAS_TIRFAIXAS F ON (D.BDCODIR = F.BDCODIR AND
                            D.BDCODDIR = F.BDCODDIR)
                      WHERE D.BDTIPOCALCFIR = 0 AND
                            COALESCE(D.BDCODTCA, 0) = 0 AND
                            (D.BDREFIR = (SELECT FIRST 1 BDREFIR
                                          FROM VRHF_TABELAS_TIRDADOS X
                                          WHERE X.BDCODIR = D.BDCODIR AND
                                                X.BDTIPOCALCFIR = 0 AND
                                                COALESCE(X.BDCODTCA, 0) = 0 AND
                                                X.BDREFIR <= :PRREFEMISSAO
                                          ORDER BY BDREFIR DESC))
                      ORDER BY D.BDCODIR, D.BDCODDIR, D.BDTIPOCALCFIR, D.BDREFIR, F.BDFAIXAIR
                      INTO :WVALOR;

                      if (COALESCE(princidesocialfer, 0) > 0) then
                         WVALORFER = COALESCE(WVALOR, 0);

                      if (COALESCE(princidesocial, 0) <= 0) then
                         WVALOR = 0;  
                    END

                 WCPFDEP = '';
                 WNOMEDEP = '';
                 WTIPODEP = '';
                 WDESCDEP = '';
                 WDATANAS = null;
                 WCODDEP = 0;
                 WREFIR = null;
                 FOR SELECT DEPREF.BDCPFDPNTERC, DEPREF.BDNOMEDPNTERC, DES.BDCODESOCIAL, DEPREF.BDDESCRDEPTERC, DEPREF.BDDATANASCDPNTERC, DEPREF.BDCODDPNTERC,
                            DEP.BDREFIRDPNTERC
                     FROM VRH_BASE_TTERC_TDEP DEP
                     JOIN (SELECT BDCODTER, BDCODDPNTERC, COALESCE( (SELECT FIRST 1 BDREFDPN
                                                                     FROM VRH_BASE_TTERC_TDEP_REF
                                                                     WHERE BDCODTER = DEP.BDCODTER AND
                                                                           BDCODDPNTERC = DEP.BDCODDPNTERC AND
                                                                           BDREFDPN <= :PRREFEMISSAO
                                                                     ORDER BY BDREFDPN DESC),
                                            
                                                                     (SELECT MIN(BDREFDPN)
                                                                      FROM VRH_BASE_TTERC_TDEP_REF
                                                                      WHERE BDCODTER = DEP.BDCODTER AND
                                                                            BDCODDPNTERC = DEP.BDCODDPNTERC)
                                                                     ) BDREFDPN
                           FROM VRH_BASE_TTERC_TDEP DEP) DEPREF_MAXMIN ON (DEP.BDCODTER = DEPREF_MAXMIN.BDCODTER AND DEP.BDCODDPNTERC = DEPREF_MAXMIN.BDCODDPNTERC)
                     JOIN VRH_BASE_TTERC_TDEP_REF DEPREF ON (DEP.BDCODTER = DEPREF.BDCODTER AND DEP.BDCODDPNTERC = DEPREF.BDCODDPNTERC AND DEPREF.BDREFDPN = DEPREF_MAXMIN.BDREFDPN)
                     LEFT OUTER JOIN VRH_TTIPO_DEP_ESOCIAL DES ON (DES.BDCODTIPODEP = DEPREF.BDPARENESCODPNTERC)
                     WHERE DEPREF.BDCODTER = :PRAUTONOMO AND
                           DES.BDCODESOCIAL <> 99 AND
                           (DEP.BDDATAENTREDPNTERC IS NOT NULL AND DEP.BDDATAENTREDPNTERC <= :PRDATAPGTO) AND
                           ((DEP.BDDATABAUXADPNTERC IS NULL) OR (DEP.BDDATABAUXADPNTERC > :PRDATAPGTO))
                 INTO :WCPFDEP, :WNOMEDEP, :WTIPODEP, :WDESCDEP, :WDATANAS, :WCODDEP, :WREFIR DO
                 BEGIN
                   WPODEGRAVAR = 0;
                   if ((WREFIR IS NULL) OR (WREFIR >= :PRREFEMISSAO)) then
                      WPODEGRAVAR = 1;
                   else
                      begin
                        if ((WTIPODEP in (3,6,10)) and (WREFIR - CAST((SELECT CAST(BDDATA AS INTEGER) FROM SP_PARSE_DATE(:WDATANAS, 'YYYYMM')) AS INTEGER) < 2100)) then
                           WPODEGRAVAR = 1;
                        else
                           WPODEGRAVAR = 1;
                      end

                   if (WPODEGRAVAR = 1) then
                      begin
                        WDESCDEP = coalesce(WDESCDEP, '');
                        WCPFDEP = coalesce(:WCPFDEP, '');
                        WNOMEDEP = coalesce(:WNOMEDEP, '');
                        WDATANAS = COALESCE(:WDATANAS, '');
                        prtagstr = coalesce(:prtagstr, '');
                        prdescricaofolha = coalesce(:prdescricaofolha, '');

                        if (coalesce(wtipodep, '0') <> '99') then
                           SELECT FIRST 1 BDDESCTIPODEP FROM VRH_TTIPO_DEP_ESOCIAL WHERE BDCODESOCIAL = COALESCE(:WTIPODEP, '0')
                           ORDER BY BDCODTIPODEP
                           INTO :WDESCDEP;

                        update or insert into VRHF_TEMP_EMP_TVAL5002
                        (BDSESSAO, BDCODEMP, BDTIPOVAL, BDVALOR, BDVALORFER, BDUNICO, BDCODAUT, BDCODDEP, BDTIPCODREC, BDTAGSTR, BDDESCRICAOFOLHA,
                        BDCPFDEP, BDNOME, BDTIPODEP, BDDATANAS, BDDESCDEP, BDZERADO, BDCODEMPORD, BDCPFCOL, BDCODCOL, BDREFEMISSAO, BDTPCR)
                        values
                        (current_connection, :prcodempprincipal, 0, :wvalor, :wvalorfer, 1, :prautonomo, :wcoddep, :prtipcodrec, '', '',
                        :WCPFDEP, :WNOMEDEP, :WTIPODEP, :WDATANAS, :WDESCDEP, FALSE, :PRCODEMPORD, :WCPFCOL, 0, :PRREFEMISSAO, :PRCODREC)
                        matching (BDSESSAO, BDCODEMPORD, BDCPFCOL, BDCPFDEP, BDTIPOVAL, BDUNICO, BDTAGSTR, BDTIPCODREC, BDREFEMISSAO, BDTPCR);
                      end

                   WCPFDEP = '';
                   WNOMEDEP = '';
                   WTIPODEP = '';
                   WDESCDEP = '';
                   WDATANAS = null;
                   WCODDEP = 0;
                   WREFIR = null;
                 END
               END
          end
     end
end^

/* Restore proc.body: SP_REL_TOT_5002_CONSOLID */
create or alter procedure SP_REL_TOT_5002_CONSOLID (
    PRCODEMP varchar(30000),
    PRREF integer,
    PRREFFIM integer,
    PRFILTROCPF varchar(30000),
    PRAUTONOMO boolean = false,
    PRPRVEIODOTOTALIZADOR integer = 0,
    PRSEPARAFOLHAS integer = 0,
    PRRECTRAB integer = 0,
    PRGRAVACODIGORECEITA integer = 0)
returns (
    BDCODEMPORD integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCOLTER integer,
    BDREF integer,
    BDCONTRCOL integer,
    BDGRUPOCLA integer,
    BDNOMCOL varchar(70),
    BDCPFCOL varchar(18),
    BDCNPJEMP varchar(18),
    BDNOMEMP varchar(100),
    BDBASEIRRF numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDVALORINSS numeric(18,6),
    BDVRDEDDEP numeric(18,6),
    BDBASEPENSAO numeric(18,6),
    BDBASEPREV numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDVALORINSS13 numeric(18,6),
    BDVRDEDDEP13 numeric(18,6),
    BDBASEPENSAO13 numeric(18,6),
    BDBASEPREV13 numeric(18,6),
    BDBASEIRRFPLR numeric(18,6),
    BDVALORIRRFPLR numeric(18,6),
    BDVALORINSSPLR numeric(18,6),
    BDVRDEDDEPPLR numeric(18,6),
    BDBASEPENSAOPLR numeric(18,6),
    BDBASEPREVPLR numeric(18,6),
    BDBASEIRRFRRA numeric(18,6),
    BDVALORIRRFRRA numeric(18,6),
    BDVALORINSSRRA numeric(18,6),
    BDVRDEDDEPRRA numeric(18,6),
    BDBASEPENSAORRA numeric(18,6),
    BDBASEPREVRRA numeric(18,6),
    BDBASEIRRFES numeric(18,6),
    BDVALORIRRFES numeric(18,6),
    BDVALORINSSES numeric(18,6),
    BDVRDEDDEPES numeric(18,6),
    BDVRDEDDEPES13 numeric(18,6),
    BDBASEPENSAOES numeric(18,6),
    BDBASEPREVES numeric(18,6),
    BDBASEIRRF13ES numeric(18,6),
    BDVALORIRRF13ES numeric(18,6),
    BDVALORINSS13ES numeric(18,6),
    BDBASEPENSAO13ES numeric(18,6),
    BDBASEPREV13ES numeric(18,6),
    BDBASEIRRFPLRES numeric(18,6),
    BDVALORIRRFPLRES numeric(18,6),
    BDBASEPENSAOPLRES numeric(18,6),
    BDBASEIRRFRRAES numeric(18,6),
    BDVALORIRRFRRAES numeric(18,6),
    BDBASEPENSAORRAES numeric(18,6),
    BDBASEINSS numeric(18,6),
    BDBASEINSSES numeric(18,6),
    BDBASEINSS13 numeric(18,6),
    BDBASEINSS13ES numeric(18,6),
    BDVALORSALFAM numeric(18,6),
    BDVALORSALFAMES numeric(18,6),
    BDVALORSALMATEMP numeric(18,6),
    BDVALORSALMATEMPES numeric(18,6),
    BDVRCPSEG numeric(18,6),
    BDVALORIRRFFERIAS numeric(18,6),
    BDVALORIRRFFERIASES numeric(18,6),
    BDBASEIRRFFERIAS numeric(18,6),
    BDBASEIRRFFERIASES numeric(18,6),
    BDBASEFGTS numeric(18,6),
    BDBASEFGTSES numeric(18,6),
    BDVALORFGTS numeric(18,6),
    BDVALORFGTSES numeric(18,6),
    BDBASEFGTSRES numeric(18,6),
    BDBASEFGTSRESES numeric(18,6),
    BDVALORFGTSRES numeric(18,6),
    BDVALORFGTSRESES numeric(18,6),
    BDBASEAVPREV numeric(18,6),
    BDBASEAVPREVES numeric(18,6),
    BDVALORAVPREV numeric(18,6),
    BDVALORAVPREVES numeric(18,6),
    BDBASEFGTS13 numeric(18,6),
    BDBASEFGTS13ES numeric(18,6),
    BDVALORFGTS13 numeric(18,6),
    BDVALORFGTS13ES numeric(18,6),
    BDVRDEDDEPPLRES numeric(18,6),
    BDVRDEDDEPRRAES numeric(18,6),
    BDVALORINSSRRAES numeric(18,6),
    BDTIPO integer,
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDCATEGORIAESOCIAL integer,
    BDCODCLATRI integer,
    BDSEST integer,
    BDSENAT integer,
    BDSESTES integer,
    BDSENATES integer,
    BDCTS5001 integer,
    BDBASEFGTS13RESC numeric(9,2),
    BDBASEFGTS13RESCES numeric(9,2),
    BDVALORFGTS13RESC numeric(9,2),
    BDVALORFGTS13RESCES numeric(9,2),
    BDECONSIGNADO numeric(18,6),
    BDECONSIGNADORESC numeric(18,6),
    BDINSTITUICAOFINANC integer,
    BDNROCONTRATOECONSIGNADO varchar(30),
    BDINSTITUICAOFINANCES integer,
    BDNROCONTRATOECONSIGNADOES varchar(30),
    BDVALORECONSIGNADOES numeric(18,6),
    BDIND13PISES integer,
    BDTPVALORPISPASEPES integer,
    BDVALORPISPASEPES numeric(18,6),
    BDVALORPISPASEP13ES numeric(18,6),
    BDVALORPISPASEP numeric(18,6),
    BDVALORPISPASEP13 numeric(18,6),
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOCALCULO integer,
    BDAJCUSTOS numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDUNICO integer,
    BDCODREC varchar(6),
    BDTIPOFOLHA integer,
    BDCODCLA integer,
    BDTRIBUTACAOEXTERIOR integer)
as
declare variable WSQLPRINCIPAL varchar(30000);
declare variable WLISTAEMP varchar(30000);
declare variable WULTDIA varchar(2);
declare variable WMES smallint;
declare variable WANO integer;
declare variable WCALCULOS integer;
declare variable WTIPOCALCULO integer;
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WCPFMEI varchar(18);
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
begin
  if (coalesce(PRREFFIM,0) = 0) then
     PRREFFIM = prref;

  BDCODEMPORD = 0;
  BDCODEMP = 0;
  BDCODCOL = 0;
  BDCOLTER = 0;
  BDCONTRCOL = 0;
  BDGRUPOCLA = 0;
  BDNOMCOL =  '';
  BDCPFCOL =  '';
  BDCNPJEMP = '';
  BDNOMEMP =  '';
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  BDBASEIRRF = 0;
  BDVALORIRRF = 0;
  BDVALORINSS = 0;
  BDVRDEDDEP = 0;
  BDBASEPENSAO = 0;
  BDBASEPREV = 0;

  BDBASEIRRF13 = 0;
  BDVALORIRRF13 = 0;
  BDVALORINSS13 = 0;
  BDVRDEDDEP13 = 0;
  BDBASEPENSAO13 = 0;
  BDBASEPREV13 = 0;

  BDBASEIRRFPLR = 0;
  BDVALORIRRFPLR = 0;
  BDVALORINSSPLR = 0;
  BDVRDEDDEPPLR = 0;
  BDBASEPENSAOPLR = 0;
  BDBASEPREVPLR = 0;

  BDBASEIRRFRRA = 0;
  BDVALORIRRFRRA = 0;
  BDVALORINSSRRA = 0;
  BDVRDEDDEPRRA = 0;
  BDBASEPENSAORRA = 0;
  BDBASEPREVRRA = 0;


  BDBASEIRRFES = 0;
  BDVALORIRRFES = 0;
  BDVALORINSSES = 0;
  BDVRDEDDEPES = 0;
  BDBASEPENSAOES = 0;
  BDBASEPREVES = 0;

  BDBASEIRRF13ES = 0;
  BDVALORIRRF13ES = 0;
  BDVALORINSS13ES = 0;
  BDBASEPENSAO13ES = 0;
  BDBASEPREV13ES = 0;

  BDBASEIRRFPLRES = 0;
  BDVALORIRRFPLRES = 0;
  BDBASEPENSAOPLRES = 0;

  BDBASEIRRFRRAES = 0;
  BDVALORIRRFRRAES = 0;
  BDBASEPENSAORRAES = 0;

  BDBASEINSS = 0;
  BDBASEINSSES = 0;
  BDBASEINSS13 = 0;
  BDBASEINSS13ES = 0;
  BDVALORSALFAM = 0;
  BDVALORSALFAMES = 0;
  BDVALORSALMATEMP = 0;
  BDVALORSALMATEMPES = 0;
  BDVRCPSEG = 0;
  BDVALORIRRFFERIAS = 0;
  BDVALORIRRFFERIASES = 0;
  BDBASEIRRFFERIAS = 0;
  BDBASEIRRFFERIASES = 0;
  BDBASEFGTS = 0;
  BDBASEFGTSES = 0;
  BDVALORFGTS = 0;
  BDVALORFGTSES = 0;
  BDBASEFGTSRES = 0;
  BDBASEFGTSRESES = 0;
  BDVALORFGTSRES = 0;
  BDVALORFGTSRESES = 0;
  BDBASEFGTS13RESC = 0;
  BDBASEFGTS13RESCES = 0;
  BDVALORFGTS13RESC = 0;
  BDVALORFGTS13RESCES = 0;

  --#206247 - Início - É preciso criar os campos com valores zero pois somente é feito o select all da SP para a emissão do relatório;
  BDECONSIGNADO              = 0;
  BDECONSIGNADORESC          = 0;
  BDINSTITUICAOFINANC        = 0;
  BDNROCONTRATOECONSIGNADO   = 'só no S-5003';
  BDINSTITUICAOFINANCES      = 0;
  BDNROCONTRATOECONSIGNADOES = 'só no S-5003';
  BDVALORECONSIGNADOES       = 0;
  --#206247 - Fim;

  --#206764 - Início - É preciso criar os campos com valores zero pois somente é feito o select all da SP para a emissão do relatório;
  BDIND13PISES = 0;
  BDTPVALORPISPASEPES = 0;
  BDVALORPISPASEPES = 0;
  BDVALORPISPASEP13ES = 0;
  BDVALORPISPASEP = 0;
  BDVALORPISPASEP13 = 0;
  BDTAGSTR = '';
  BDDESCRICAOFOLHA = '';
  BDCODREC = '';
  BDCODCLA = 0;
  BDTRIBUTACAOEXTERIOR = 0;
  --#206764 - Fim;

  BDBASEAVPREV = 0;
  BDBASEAVPREVES = 0;
  BDVALORAVPREV = 0;
  BDVALORAVPREVES = 0;
  BDBASEFGTS13 = 0;
  BDBASEFGTS13ES = 0;
  BDVALORFGTS13 = 0;
  BDVALORFGTS13ES = 0;
  BDCALCULOS = 0;
  BDTIPO = 5002;
  WSQLPRINCIPAL = '';

  BDTIPOCALCULO = 0;
  BDUNICO = 0;

  /****************************/
  /* Valores De Colaboradores */
  if (PRAUTONOMO = FALSE) then
    begin
      BDCOLTER = 1;
      WSQLPRINCIPAL = WSQLPRINCIPAL||'SELECT '||''''||'consolid'||''''||',COL.BDCODEMP,COL.BDCODCOL ' ||
                      ' FROM VRH_EMP_TCOLCON COL ' ||
                      ' INNER JOIN TEMPRESAS E ON E.BDCODEMP = COL.BDCODEMP ' ||
                      ' inner join TEMPRESAS_REF EREF on EREF.BDCODEMP = E.BDCODEMP and EREF.BDREFEMP = (select max(BDREFEMP) from TEMPRESAS_REF WHERE BDCODEMP = E.BDCODEMP)' ||
                      ' inner join VRH_EMP_TCOLCON_CAD COLCAD on COLCAD.BDCODEMP = COL.BDCODEMP and COLCAD.BDCODCOL = COL.BDCODCOL and ' ||
                      '                                          COLCAD.BDREFCOL = COALESCE((select max(BDREFCOL) from VRH_EMP_TCOLCON_CAD WHERE BDCODEMP = COL.BDCODEMP and BDCODCOL = COL.BDCODCOL and BDREFCOL <= '||PRREFFIM||'), ' ||
                      '                                                                     (select FIRST 1 BDREFCOL from VRH_EMP_TCOLCON_CAD WHERE BDCODEMP = COL.BDCODEMP and BDCODCOL = COL.BDCODCOL ORDER BY BDREFCOL)) ';

      if (position('TMP_EMPRESAS_SELECT', PRCODEMP) > 0) then
         WSQLPRINCIPAL = WSQLPRINCIPAL||PRCODEMP||' SLC on (SLC.BDCODEMP = coalesce(E.BDCODMATRIZ, COL.BDCODEMP))';

      WSQLPRINCIPAL = WSQLPRINCIPAL||' where UPPER(E.BDEXPINIESOCIAL) = ' || '''' || 'TRUE' || '''';

      if ((PRCODEMP is not null) and (PRCODEMP <> '')) then
        begin
          WSQLPRINCIPAL = WSQLPRINCIPAL ||' and (not exists(select DOC.BDCODEMP '||
                                                           'from VRH_EMP_TCON_DOC DOC '||
                                                           'where (DOC.BDCODEMP = COLCAD.BDCODEMP) and '||
                                                           '(DOC.BDCODCOL = COLCAD.BDCODCOL) and '||
                                                           '(DOC.BDDATABAIXACOL < '''|| substring(cast(PRREF as varchar(6)) from 1 for 4)||'/'||substring(cast(PRREF as varchar(6)) from 5 for 2)||'/01'''|| '))) '||
                                     'and ((not exists(select RESC.BDCODEMP '||
                                                    'from VRH_EMP_TRESCISAO RESC '||
                                                    'where (RESC.BDCODEMP = COLCAD.BDCODEMP) and '||
                                                    '(RESC.BDCODCOL = COLCAD.BDCODCOL) and '||
                                                    '(RESC.BDDATAPAGRESCISAO < '''|| substring(cast(PRREF as varchar(6)) from 1 for 4)||'/'||substring(cast(PRREF as varchar(6)) from 5 for 2)||'/01'''||')))'||
                                     '       or (exists(select fc.bdcodemp '||
                                                      'from VRHF_EMP_TFOLHACOMP fc '||
                                                      'where fc.BDCODEMP = COLCAD.BDCODEMP and '||
                                                      'fc.BDCODCOL = COLCAD.BDCODCOL and '||
                                                      'fc.BDREFIRRFESOCIAL >= '|| PRREF ||' and fc.BDREFIRRFESOCIAL <='||PRREFFIM||'))'||
                                      '       or (exists(select fc.bdcodemp '||
                                                      'from VRHF_EMP_TFOLHACOMPINT fc '||
                                                      'where fc.BDCODEMP = COLCAD.BDCODEMP and '||
                                                      'fc.BDCODCOL = COLCAD.BDCODCOL and '||
                                                      'fc.BDREFIRRFESOCIAL >= '|| PRREF ||' and fc.BDREFIRRFESOCIAL <='||PRREFFIM||'))'||
                                      '       or (exists(select fc.bdcodemp '||
                                                      'from VRHF_EMP_TFOLTOMCOMP fc '||
                                                      'where fc.BDCODEMP = COLCAD.BDCODEMP and '||
                                                      'fc.BDCODCOL = COLCAD.BDCODCOL and '||
                                                      'fc.BDREFIRRFESOCIAL >= '|| PRREF ||' and fc.BDREFIRRFESOCIAL <='||PRREFFIM||'))'||
                                      '       or (exists(select fc.bdcodemp '||
                                                      'from VRHF_EMP_TFOLTOMCOMPINT fc '||
                                                      'where fc.BDCODEMP = COLCAD.BDCODEMP and '||
                                                      'fc.BDCODCOL = COLCAD.BDCODCOL and '||
                                                      'fc.BDREFIRRFESOCIAL >= '|| PRREF ||' and fc.BDREFIRRFESOCIAL <='||PRREFFIM||'))'||
                                      '       or (exists(select fc.bdcodemp '||
                                                      'from VRHF_EMP_TFOLHAAVULSA fc '||
                                                      'where fc.BDCODEMP = COLCAD.BDCODEMP and '||
                                                      'fc.BDCODCOL = COLCAD.BDCODCOL and '||
                                                      'fc.BDREFIRRFESOCIAL >= '|| PRREF ||' and fc.BDREFIRRFESOCIAL <='||PRREFFIM||'))'||
                                      '       or (exists(select ff.bdcodemp '||
                                                      'from VRHF_EMP_TFICHAIRRF ff '||
                                                      'where ff.BDCODEMP = COLCAD.BDCODEMP and '||
                                                      'ff.BDCODCOL = COLCAD.BDCODCOL and '||
                                                      'ff.BDREFIRFIR >= '|| PRREF ||' and ff.BDREFIRFIR <='||PRREFFIM||')))';

          if (position('TMP_EMPRESAS_SELECT', PRCODEMP) = 0) then
            begin
              if (position('=', PRCODEMP) > 0) then
                WLISTAEMP = SUBSTRING(PRCODEMP from position('=', PRCODEMP)+1 for CHAR_LENGTH(PRCODEMP));
              if (position('in', PRCODEMP) > 0) then
                WLISTAEMP = SUBSTRING(PRCODEMP from position('in', PRCODEMP)+2 for CHAR_LENGTH(PRCODEMP));
    
              if (position('(', WLISTAEMP) > 0) then
                WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ((E.BDCODMATRIZ in ' || WLISTAEMP || ') OR (COL.BDCODEMP in ' || WLISTAEMP || '))';
              else
                WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ((E.BDCODMATRIZ in (' || WLISTAEMP || ')) OR (COL.BDCODEMP in (' || WLISTAEMP || ')))';
            end
        end

      if ((PRREF is not null) and (PRREF <> 0)) then
        begin
          WMES = cast(substring(cast(PRREFFIM as varchar(6)) from 5 for 2) as integer);
          WANO = cast(substring(cast(PRREFFIM as varchar(6)) from 1 for 4) as integer);
          select ULTDIA from ULTIMO_DIA_MES(:WMES, :WANO) into WULTDIA;
          WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND (COL.BDDATAADMCOL <=''' || substring(cast(PRREFFIM as varchar(6)) from 5 for 2) || '/' || WULTDIA || '/' || substring(cast(PRREFFIM as varchar(6)) from 1 for 4) || ''')';
        end

      if ((PRFILTROCPF is not null) and (PRFILTROCPF <> '')) then
        WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ' ||PRFILTROCPF;

       -- limpa tabela temporária de filtro
       delete from TEMP_FILTRO_COLCON_REL;
       -- Incluir registros de colaboradores na tabela emporária de filtros
       WSQLPRINCIPAL = 'insert into TEMP_FILTRO_COLCON_REL (BDCOMP, BDCODEMP, BDCODCOL) '||WSQLPRINCIPAL;
       execute statement wsqlprincipal;

       for select tot.bdref, tot.BDCODEMP, tot.BDCODCOL, tot.BDBASEIRRFMENSAL, tot.BDVALORIRRFMENSAL, tot.BDINSSMENSAL,
                tot.BDAJCUSTOSMENSAL, tot.BDINDRESCMENSAL, tot.BDVALABOMENSAL, tot.BDRENDISENTOSMENSAL, tot.BDDRENDISENTOSMENSAL, tot.BDAUXILIOMORADIAMENSAL,
                tot.BDDIARIAMENSAL, tot.BDBOLSAMEDICOMENSAL, tot.BDJUROSMORAMENSAL, tot.BDCALCULOS, tot.BDTIPOCALCULO, tot.bdtagstr, tot.bddescricaofolha, tot.BDTIPOFOLHA, tot.BDCODREC,
                COALESCE(E.BDCODMATRIZ, COL.BDCODEMP) BDCODMATRIZ, E.BDCNPJEMP, EREF.BDNOMEMP, COL.BDCPFCOL, COLCAD.BDNOMCOL, COL.BDCONTRCOL, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR
              from (
              select tot.bdref, tot.BDCODEMP, tot.BDCODCOL, tot.BDBASEIRRFMENSAL, tot.BDVALORIRRFMENSAL, tot.BDINSSMENSAL,
                              tot.BDAJCUSTOSMENSAL, tot.BDINDRESCMENSAL, tot.BDVALABOMENSAL, tot.BDRENDISENTOSMENSAL, tot.BDDRENDISENTOSMENSAL, tot.BDAUXILIOMORADIAMENSAL,
                              tot.BDDIARIAMENSAL, tot.BDBOLSAMEDICOMENSAL, tot.BDJUROSMORAMENSAL, tot.BDCALCULOS, tot.BDTIPOCALCULO, tot.bdtagstr, tot.bddescricaofolha, tot.BDTIPOFOLHA, tot.BDCODREC
              from SP_RETORNA_BASE_IRRF_CONSOLID_MENSAL('', 'TEMP_FILTRO_COLCON_REL', :PRREF, :prreffim, 1, :PRPRVEIODOTOTALIZADOR, :PRSEPARAFOLHAS, :PRGRAVACODIGORECEITA) tot
              union all
              select tot.bdref, tot.BDCODEMP, tot.BDCODCOL, tot.BDBASEIRRFMENSAL, tot.BDVALORIRRFMENSAL, tot.BDINSSMENSAL,
                              tot.BDAJCUSTOSMENSAL, tot.BDINDRESCMENSAL, tot.BDVALABOMENSAL, tot.BDRENDISENTOSMENSAL, tot.BDDRENDISENTOSMENSAL, tot.BDAUXILIOMORADIAMENSAL,
                              tot.BDDIARIAMENSAL, tot.BDBOLSAMEDICOMENSAL, tot.BDJUROSMORAMENSAL, tot.BDCALCULOS, tot.BDTIPOCALCULO, tot.bdtagstr, tot.bddescricaofolha, tot.BDTIPOFOLHA, tot.BDCODREC
              from SP_RETORNA_BASE_IRRF_CONSOLID_13('', 'TEMP_FILTRO_COLCON_REL', :PRREF, :prreffim, 1, :PRPRVEIODOTOTALIZADOR, :PRSEPARAFOLHAS, :PRGRAVACODIGORECEITA) tot
              union all
              select tot.bdref, tot.BDCODEMP, tot.BDCODCOL, tot.BDBASEIRRFMENSAL, tot.BDVALORIRRFMENSAL, tot.BDINSSMENSAL,
                              tot.BDAJCUSTOSMENSAL, tot.BDINDRESCMENSAL, tot.BDVALABOMENSAL, tot.BDRENDISENTOSMENSAL, tot.BDDRENDISENTOSMENSAL, tot.BDAUXILIOMORADIAMENSAL,
                              tot.BDDIARIAMENSAL, tot.BDBOLSAMEDICOMENSAL, tot.BDJUROSMORAMENSAL, tot.BDCALCULOS, tot.BDTIPOCALCULO, tot.bdtagstr, tot.bddescricaofolha, tot.BDTIPOFOLHA, tot.BDCODREC
              from SP_RETORNA_BASE_IRRF_CONSOLID_PLR('', 'TEMP_FILTRO_COLCON_REL', :PRREF, :prreffim, 1, :PRPRVEIODOTOTALIZADOR, :PRSEPARAFOLHAS, :PRGRAVACODIGORECEITA) tot
              union all
              select tot.bdref, tot.BDCODEMP, tot.BDCODCOL, tot.BDBASEIRRFMENSAL, tot.BDVALORIRRFMENSAL, tot.BDINSSMENSAL,
                              tot.BDAJCUSTOSMENSAL, tot.BDINDRESCMENSAL, tot.BDVALABOMENSAL, tot.BDRENDISENTOSMENSAL, tot.BDDRENDISENTOSMENSAL, tot.BDAUXILIOMORADIAMENSAL,
                              tot.BDDIARIAMENSAL, tot.BDBOLSAMEDICOMENSAL, tot.BDJUROSMORAMENSAL, tot.BDCALCULOS, tot.BDTIPOCALCULO, tot.bdtagstr, tot.bddescricaofolha, tot.BDTIPOFOLHA, tot.BDCODREC
              from SP_RETORNA_BASE_IRRF_CONSOLID_RRA('', 'TEMP_FILTRO_COLCON_REL', :PRREF, :prreffim, 1, :PRPRVEIODOTOTALIZADOR, :PRSEPARAFOLHAS, :PRGRAVACODIGORECEITA, 2) tot

              ) tot
         join VRH_EMP_TCOLCON COL on (tot.bdcodemp = col.bdcodemp and tot.bdcodcol = col.bdcodcol)
         INNER JOIN TEMPRESAS E ON E.BDCODEMP = COL.BDCODEMP
         inner join TEMPRESAS_REF EREF on EREF.BDCODEMP = E.BDCODEMP and EREF.BDREFEMP = (select max(BDREFEMP) from TEMPRESAS_REF WHERE BDCODEMP = E.BDCODEMP)
         inner join VRH_EMP_TCOLCON_CAD COLCAD on COLCAD.BDCODEMP = COL.BDCODEMP and COLCAD.BDCODCOL = COL.BDCODCOL and
                                                  COLCAD.BDREFCOL = COALESCE((select max(BDREFCOL) from VRH_EMP_TCOLCON_CAD WHERE BDCODEMP = COL.BDCODEMP and BDCODCOL = COL.BDCODCOL and BDREFCOL <= tot.bdref),
                                                                             (select first 1 bdrefcol from vrh_emp_tcolcon_cad where bdcodemp = col.bdcodemp and bdcodcol = col.bdcodcol order by bdrefcol))

         left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = COL.BDCODEMP) and (HIST.BDCODCOL = COL.BDCODCOL)
         left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = COL.BDCODEMP) and (VINC.BDCODCOL = COL.BDCODCOL)
                        and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x
                                                       WHERE X.BDCODEMP = COL.BDCODEMP and x.BDCODCOL = COL.BDCODCOL
                                                        AND X.BDREFCOL <= tot.bdref ORDER BY X.BDREFCOL DESC)
                                                    ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x
                                                       WHERE X.BDCODEMP = COL.BDCODEMP and x.BDCODCOL = COL.BDCODCOL))
         into :bdref,  :BDCODEMP, :BDCODCOL, :BDBASEIRRF, :BDVALORIRRF, :BDVALORINSS,
              :BDAJCUSTOS, :BDINDRESC, :BDVALABO, :BDRENDISENTOS, :BDDRENDISENTOS, :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA,
              :WCALCULOS, :WTIPOCALCULO, :bdtagstr, :bddescricaofolha, :bdtipofolha,:bdcodrec, :bdcodempord, :BDCNPJEMP, :BDNOMEMP, :BDCPFCOL, :BDNOMCOL, :BDCONTRCOL,
              :BDCODCLA, :BDTRIBUTACAOEXTERIOR
         do
         begin
           select first 1 FGTS.BDCATEGORIAESOCIAL, CLA.BDGRUPOCLA from VRHF_EMP_TCOLCON_FGTSGPS FGTS
           left outer join VRH_EMP_TCOLCON_VINC VINC on VINC.BDCODEMP = :BDCODEMP and VINC.BDCODCOL = :BDCODCOL and VINC.BDREFCOL <= :bdref
           left outer join VRH_BASE_TCLASSE CLA on (CLA.BDCODCLA = VINC.BDCODCLA)
           where FGTS.BDCODEMP in (:BDCODEMP) and FGTS.BDCODCOL = :BDCODCOL and (FGTS.BDREFCOL <= :bdref)
           order by FGTS.BDREFCOL desc into :BDCATEGORIAESOCIAL, :bdgrupocla;
       
           select first 1 BDCODCLATRI from VRHF_BASE_TEMPESOCIAL ES
           where ES.BDCODEMP in (:BDCODEMP) and(ES.BDREFEMP <= :bdref)
           order by BDREFEMP desc into :BDCODCLATRI;

           BDCALCULOS = COALESCE(WCALCULOS, 0);
           BDTIPOCALCULO = COALESCE(WTIPOCALCULO, 0);
           BDUNICO = 1;
   
           SUSPEND;
         end
    END


  /****************************/
  /* Valores De Autonomos */
  if (PRAUTONOMO = TRUE) then
    BEGIN
      BDCOLTER = 2;
      WSQLPRINCIPAL = '';
      WLISTAEMP = '';
      WCPFMEI = '';

      if (position('TMP_EMPRESAS_SELECT', PRCODEMP) = 0) then
        begin
          if (position('=', PRCODEMP) > 0) then
            WLISTAEMP = '=' || SUBSTRING(PRCODEMP from position('=', PRCODEMP)+1 for CHAR_LENGTH(PRCODEMP));
          if (position('in', PRCODEMP) > 0) then
            WLISTAEMP = 'in' || SUBSTRING(PRCODEMP from position('in', PRCODEMP)+2 for CHAR_LENGTH(PRCODEMP));
        end

--      WSQLPRINCIPAL = WSQLPRINCIPAL ||'SELECT COALESCE(EMP.BDCODMATRIZ, TERC.BDCODEMP) BDCODMATRIZ, EMP.BDCNPJEMP, EREF.BDNOMEMP, TERC.BDCODEMP, TER.BDCODTER,'||
--                                      'TER.BDCGCTER, TRF.BDNOMETER, 0 BDCONTRCOL, TRF.BDREFEMP '||
      WSQLPRINCIPAL = WSQLPRINCIPAL ||'SELECT '||''''||'consolid'||''''||',TERC.BDCODEMP, 0 BDCODCOL, TER.BDCODTER FROM TTERCEIRO TER '||
                                      'INNER JOIN TTERCEIRO_REF TRF ON TRF.BDCODTER = TER.BDCODTER AND TRF.BDREFEMP = (SELECT MAX(TRF1.BDREFEMP) FROM TTERCEIRO_REF TRF1 WHERE TRF1.BDCODTER = TRF.BDCODTER AND TRF1.BDREFEMP <= '|| PRREFFIM ||') '||
                                      'INNER JOIN(SELECT TERC.BDCODEMP, TERC.BDCODTER '||
                                      '           FROM VRH_BASE_TSERVTERC TERC '||
                                      '           LEFT JOIN VRHF_BASE_CALC_TERC CALC ON (TERC.BDCODTER = CALC.BDCODTER and TERC.BDCODEMP = CALC.BDCODEMP and TERC.BDCODSERV = CALC.BDCODSERV) '||
                                      '           INNER JOIN TEMPRESAS E ON E.BDCODEMP = TERC.BDCODEMP AND '||
                                      '                                    UPPER(E.BDEXPINIESOCIAL) = ''TRUE''';

      if (position('TMP_EMPRESAS_SELECT', PRCODEMP) > 0) then
         WSQLPRINCIPAL = WSQLPRINCIPAL||PRCODEMP||' SL on (SL.BDCODEMP = COALESCE(E.BDCODMATRIZ, TERC.BDCODEMP)) ';

      WSQLPRINCIPAL = WSQLPRINCIPAL ||'           WHERE (COALESCE(CALC.BDREFIRRFESOCIAL, TERC.BDREFPAGSERV) >= '|| PRREF ||')'||
                                     '            and (COALESCE(CALC.BDREFIRRFESOCIAL, TERC.BDREFPAGSERV) <= '|| prreffim ||')';

     if (position('TMP_EMPRESAS_SELECT', PRCODEMP) = 0) then
        WSQLPRINCIPAL = WSQLPRINCIPAL ||'           and (coalesce(E.BDCODMATRIZ, E.BDCODEMP)  ' || WLISTAEMP || ')';

      WSQLPRINCIPAL = WSQLPRINCIPAL ||'           GROUP BY TERC.BDCODEMP, TERC.BDCODTER) TERC ON TERC.BDCODTER = TER.BDCODTER '||
                                      'INNER JOIN TEMPRESAS EMP ON EMP.BDCODEMP = TERC.BDCODEMP '||
                                      'INNER JOIN TEMPRESAS_REF EREF ON EREF.BDCODEMP = EMP.BDCODEMP AND EREF.BDREFEMP = (SELECT MAX(BDREFEMP) '||
                                      '                                                                                   FROM TEMPRESAS_REF '||
                                      '                                                                                  WHERE BDCODEMP = EMP.BDCODEMP) '||
                                      'INNER JOIN TTERCEIRO_RH RH ON (RH.BDCODTER = TER.BDCODTER) ';

      if (position('TMP_EMPRESAS_SELECT', PRCODEMP) > 0) then
         WSQLPRINCIPAL = WSQLPRINCIPAL||PRCODEMP||' SLT on (SLT.BDCODEMP = BDCODMATRIZ)';

      WSQLPRINCIPAL = WSQLPRINCIPAL ||'WHERE UPPER(EMP.BDEXPINIESOCIAL) = ''TRUE'' ';

      if (position('TMP_EMPRESAS_SELECT', PRCODEMP) = 0) then
        begin
          if (position('=', WLISTAEMP) > 0) then
            WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ((EMP.BDCODMATRIZ  ' || WLISTAEMP || ') OR (TERC.BDCODEMP  ' || WLISTAEMP || '))';
          else
            WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ((EMP.BDCODMATRIZ  ' || WLISTAEMP || ') OR (TERC.BDCODEMP  ' || WLISTAEMP || '))';
        end

--      if ((PRREF is not null) and (PRREF <> 0)) then
--        begin
--          WMES = cast(substring(cast(prreffim as varchar(6)) from 5 for 2) as integer);
--          WANO = cast(substring(cast(prreffim as varchar(6)) from 1 for 4) as integer);
--          select ULTDIA from ULTIMO_DIA_MES(:WMES, :WANO) into WULTDIA;
--          WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND (TRF.BDDATACADTER <=''' || substring(cast(prreffim as varchar(6)) from 5 for 2) || '/' || WULTDIA || '/' || substring(cast(PRREF as varchar(6)) from 1 for 4) || ''')';
--        end

      if ((PRFILTROCPF is not null) and (PRFILTROCPF <> '')) then
        WSQLPRINCIPAL = WSQLPRINCIPAL || ' AND ((' ||PRFILTROCPF||') OR ('||REPLACE(prfiltrocpf, 'TER.BDCGCTER','RH.BDCPFMEITER')||'))';

       -- limpa tabela temporária de filtro
       delete from TEMP_FILTRO_COLCON_REL;
       -- Incluir registros de colaboradores na tabela emporária de filtros
       WSQLPRINCIPAL = 'insert into TEMP_FILTRO_COLCON_REL (BDCOMP, BDCODEMP, BDCODCOL, BDCODTER) '||WSQLPRINCIPAL;
       execute statement wsqlprincipal;

       for select tot.bdref, tot.BDCODEMP, tot.BDCODCOL, tot.BDBASEIRRFMENSAL, tot.BDVALORIRRFMENSAL, tot.BDINSSMENSAL,
                tot.BDAJCUSTOSMENSAL, tot.BDINDRESCMENSAL, tot.BDVALABOMENSAL, tot.BDRENDISENTOSMENSAL, tot.BDDRENDISENTOSMENSAL, tot.BDAUXILIOMORADIAMENSAL,
                tot.BDDIARIAMENSAL, tot.BDBOLSAMEDICOMENSAL, tot.BDJUROSMORAMENSAL, tot.BDCALCULOS, tot.BDTIPOCALCULO, tot.bdtagstr, tot.bddescricaofolha, tot.BDTIPOFOLHA, tot.BDCODREC,
                COALESCE(E.BDCODMATRIZ, TOT.BDCODEMP) BDCODMATRIZ, E.BDCNPJEMP, EREF.BDNOMEMP, TER.bdcgcter,rh.bdcpfmeiter, TRF.bdnometer, 0 BDCONTRCOL,
                VINC.BDCODCLA, RH.BDTRIBUTACAOEXTERIOR
         from SP_RETORNA_BASE_IRRF_CONSOLID_MENSAL('', 'TEMP_FILTRO_COLCON_REL', :PRREF, :prreffim, 0, :PRPRVEIODOTOTALIZADOR, :PRSEPARAFOLHAS, :PRGRAVACODIGORECEITA) tot
         INNER JOIN TEMPRESAS E ON E.BDCODEMP = TOT.BDCODEMP
         inner join TEMPRESAS_REF EREF on EREF.BDCODEMP = E.BDCODEMP and EREF.BDREFEMP = (select max(BDREFEMP) from TEMPRESAS_REF WHERE BDCODEMP = E.BDCODEMP)
         INNER JOIN TTERCEIRO TER ON TOT.BDCODCOL = TER.bdcodter
         INNER JOIN TTERCEIRO_REF TRF ON TRF.BDCODTER = TER.BDCODTER AND TRF.BDREFEMP = (SELECT MAX(TRF1.BDREFEMP) FROM TTERCEIRO_REF TRF1 WHERE TRF1.BDCODTER = TRF.BDCODTER AND TRF1.BDREFEMP <= TOT.BDREF)
         INNER JOIN TTERCEIRO_RH RH ON (RH.BDCODTER = TER.BDCODTER)
         LEFT OUTER JOIN VRH_BASE_TTERC_VINC VINC ON (VINC.BDCODTER = TER.BDCODTER)
                        and VINC.BDREFTERC = COALESCE((SELECT FIRST 1 X.BDREFTERC FROM VRH_BASE_TTERC_VINC x
                                                       WHERE X.BDCODTER = TER.BDCODTER
                                                        AND X.BDREFTERC <= TOT.BDREF ORDER BY X.BDREFTERC DESC)
                                                    ,(SELECT FIRST 1 X.BDREFTERC FROM VRH_BASE_TTERC_VINC x
                                                       WHERE x.BDCODTER = TER.BDCODTER))
         into :bdref,  :BDCODEMP, :BDCODCOL, :BDBASEIRRF, :BDVALORIRRF, :BDVALORINSS,
              :BDAJCUSTOS, :BDINDRESC, :BDVALABO, :BDRENDISENTOS, :BDDRENDISENTOS, :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA,
              :WCALCULOS, :WTIPOCALCULO, :bdtagstr, :bddescricaofolha, :bdtipofolha,:bdcodrec, :bdcodempord, :BDCNPJEMP, :BDNOMEMP, :BDCPFCOL,:WCPFMEI, :BDNOMCOL, :BDCONTRCOL, :BDCODCLA, :BDTRIBUTACAOEXTERIOR
         do
         begin
           BDCALCULOS = COALESCE(WCALCULOS, 0);
           BDTIPOCALCULO = COALESCE(WTIPOCALCULO, 0);
           BDUNICO = 1;
   
           if (position('/',bdcpfcol) > 0) then
              bdcpfcol = WCPFMEI;

           if (F_IR_ISENTO_ESTRANGEIRO(BDCODCLA, BDTRIBUTACAOEXTERIOR) = TRUE) then
             begin
                BDBASEIRRF = 0;
               BDVALORIRRF = 0;
             end
           SUSPEND;
         end
    END

  if (prref = prreffim) then
     begin
       BDCONTRCOL = 0;
       BDCALCULOS = 0;
       BDUNICO = 2;
       wcodemp = 0;
       wcodcol = 0;
       wref = 0;
       WCPFMEI = '';
       for  select tot.bdref, tot.BDCODEMP, tot.BDCODCOL, tot.BDINSSMENSALES, tot.BDBASEIRRFMENSALES, tot.BDVALORIRRFMENSALES, tot.BDAJCUSTOSMENSALES, tot.BDINDRESCMENSALES, tot.BDVALABOMENSALES, tot.BDRENDISENTOSMENSALES, tot.BDDRENDISENTOSMENSALES,
                   tot.BDAUXILIOMORADIAMENSALES, tot.BDDIARIAMENSALES, tot.BDBOLSAMEDICOMENSALES, tot.BDJUROSMORAMENSALES, tot.BDTIPOCALCULO
                   from SP_RETORNA_BASE_IRRF_CONSOLID_ES('', 'TEMP_FILTRO_COLCON_REL', :PRREF, :prreffim, :prautonomo, :PRGRAVACODIGORECEITA, :BDCODCLA, :BDTRIBUTACAOEXTERIOR) tot
              into bdref, bdcodemp, bdcodcol, :BDVALORINSS, :BDBASEIRRF, :BDVALORIRRF,
                   :BDAJCUSTOS, :BDINDRESC, :BDVALABO, :BDRENDISENTOS, :BDDRENDISENTOS, :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA,
                   :BDTIPOCALCULO   do
              begin
                if (wcodemp <> bdcodemp) then
                   begin
                     select first 1 coalesce(e.bdcodmatriz,e.bdcodemp),e.bdcnpjemp,eref.bdnomemp from TEMPRESAS E
                     inner join TEMPRESAS_REF EREF on EREF.BDCODEMP = E.BDCODEMP and EREF.BDREFEMP = (select max(BDREFEMP) from TEMPRESAS_REF WHERE BDCODEMP = E.BDCODEMP)
                     where e.bdcodemp = :bdcodemp into :bdcodempord, :BDCNPJEMP, :BDNOMEMP;
                   end

                if (PRAUTONOMO = TRUE) then
                   begin
                     if (wcodcol <> bdcodcol) then
                        begin
                          select first 1 case
                                           when (position('/' in TER.BDCGCTER) > 0) then cast(RH.BDCPFMEITER as varchar(14))
                                           else cast(TER.BDCGCTER as varchar(14))
                                         end as BDCGCTER,
                                 trf.bdnometer, VINC.BDCODCLA, RH.BDTRIBUTACAOEXTERIOR
                          from TTERCEIRO TER
                          INNER JOIN TTERCEIRO_REF TRF ON TRF.BDCODTER = TER.BDCODTER AND TRF.BDREFEMP = (SELECT MAX(TRF1.BDREFEMP) FROM TTERCEIRO_REF TRF1 WHERE TRF1.BDCODTER = TRF.BDCODTER AND TRF1.BDREFEMP <= :PRREFFIM)
                          INNER JOIN TTERCEIRO_RH RH ON (RH.BDCODTER = TER.BDCODTER)
                          LEFT OUTER JOIN VRH_BASE_TTERC_VINC VINC ON (VINC.BDCODTER = TER.BDCODTER)
                                and VINC.BDREFTERC = COALESCE((SELECT FIRST 1 X.BDREFTERC FROM VRH_BASE_TTERC_VINC x
                                                       WHERE X.BDCODTER = TER.BDCODTER
                                                        AND X.BDREFTERC <= :PRREFFIM ORDER BY X.BDREFTERC DESC)
                                                    ,(SELECT FIRST 1 X.BDREFTERC FROM VRH_BASE_TTERC_VINC x
                                                       WHERE x.BDCODTER = TER.BDCODTER))
                          where ter.bdcodter = :bdcodcol into :BDCPFCOL, :BDNOMCOL, :WCODCLA, :WTRIBUTACAOEXTERIOR;
                        end
                   end
                else
                   begin
                     if ((wcodemp <> bdcodemp) or (wcodcol <> bdcodcol)) then
                        begin
                          select first 1 COL.bdcpfcol,COLCAD.bdnomcol,COL.bdcontrcol from VRH_EMP_TCOLCON COL
                          inner join VRH_EMP_TCOLCON_CAD COLCAD on COLCAD.BDCODEMP = COL.BDCODEMP and COLCAD.BDCODCOL = COL.BDCODCOL and COLCAD.BDREFCOL = (select max(BDREFCOL) from VRH_EMP_TCOLCON_CAD WHERE BDCODEMP = COL.BDCODEMP and BDCODCOL = COL.BDCODCOL and BDREFCOL <= :PRREFFIM)
                          where COL.bdcodemp = :bdcodemp AND COL.bdcodcol = :bdcodcol into :BDCPFCOL,:BDNOMCOL,:BDCONTRCOL;
                        end
                   end
                 wcodemp = bdcodemp;
                 wcodcol = bdcodcol;
                 wref = bdref;

                 if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
                    begin
                        BDBASEIRRF = 0;
                        BDVALORIRRF = 0;
                    end

                 SUSPEND;
              end
     end
end^

CREATE OR ALTER trigger vrhf_temp_emp_tplansau5002_bi0 for vrhf_temp_emp_tplansau5002
active before insert position 0
AS
declare variable WEXISTEREGISTRO INTEGER;
DECLARE VARIABLE VCODIGO INTEGER;
begin
  /* Trigger text */
  VCODIGO = 0;
  if ((new.BDSEQUENCIAL is null) or (new.BDSEQUENCIAL = 0)) then
  begin
    select coalesce((max(BDSEQUENCIAL) + 1), 1)
    from VRHF_TEMP_EMP_TPLANSAU5002
    where BDSESSAO = NEW.BDSESSAO AND
          BDCODEMPORD = NEW.BDCODEMPORD AND
          BDCPFCOL = NEW.BDCPFCOL
    into VCODIGO;

    new.BDSEQUENCIAL = VCODIGO;
  end

  IF (COALESCE(NEW.BDZERADO, 'FALSE') = 'FALSE') THEN
     BEGIN
        NEW.BDCNPJOPER = COALESCE(NEW.BDCNPJOPER, '');
        NEW.BDREGISTROANSOPER = COALESCE(NEW.BDREGISTROANSOPER, 0);

        IF (COALESCE(NEW.BDUNICO, 0) = 2) THEN
          BEGIN
            /* VERIFICAR SE JÁ EXISTE REGISTRO EQUIVALENTE DO ÚNICO E SE NÃO EXISTIR CRIAR */

            WEXISTEREGISTRO = 0;
            SELECT BDCODEMP FROM VRHF_TEMP_EMP_TPLANSAU5002
            WHERE BDSESSAO = NEW.BDSESSAO AND
                  BDCODEMP = NEW.BDCODEMP AND
                  BDTIPO   = NEW.BDTIPO AND
                  BDCPFCOL = NEW.BDCPFCOL AND
                  BDCPFDEP = NEW.BDCPFDEP AND
                  BDUNICO  = 1 AND
                  BDTAGSTR = NEW.BDTAGSTR AND
                  BDCNPJOPER = NEW.BDCNPJOPER AND
                  BDREGISTROANSOPER = NEW.BDREGISTROANSOPER AND
                  BDREFEMISSAO = NEW.BDREFEMISSAO
            INTO :WEXISTEREGISTRO;

            IF (COALESCE(WEXISTEREGISTRO, 0) = 0) THEN
               BEGIN
                 INSERT INTO VRHF_TEMP_EMP_TPLANSAU5002
                 (BDSESSAO, BDCODEMP, BDTIPO, BDCPFCOL, BDCPFDEP, BDUNICO, BDTAGSTR, BDDESCRICAOFOLHA, BDCODCOL, BDCODDPN, BDNOME, BDCNPJOPER, BDREGISTROANSOPER, BDVALOR, BDZERADO, BDCODEMPORD,
                  BDREFEMISSAO, BDSEQUENCIAL)
                 VALUES
                 (NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDTIPO, NEW.BDCPFCOL, NEW.BDCPFDEP, 1, '', '', NEW.BDCODCOL, NEW.BDCODDPN, NULL, NEW.BDCNPJOPER, NEW.BDREGISTROANSOPER, NULL, TRUE, NEW.BDCODEMPORD,
                  NEW.BDREFEMISSAO, new.BDSEQUENCIAL + 1);
               END
          END
       ELSE
          BEGIN
            /* VERIFICAR SE JÁ EXISTE REGISTRO EQUIVALENTE DO ESOCIAL E SE NÃO EXISTIR CRIAR */

            WEXISTEREGISTRO = 0;
            SELECT BDCODEMP FROM VRHF_TEMP_EMP_TPLANSAU5002
            WHERE BDSESSAO = NEW.BDSESSAO AND
                  BDCODEMPORD = NEW.BDCODEMPORD AND
                  BDTIPO   = NEW.BDTIPO   AND
                  BDCPFCOL = NEW.BDCPFCOL AND
                  BDCPFDEP = NEW.BDCPFDEP AND
                  BDUNICO  = 2 AND
                  BDCNPJOPER = NEW.BDCNPJOPER AND
                  BDREGISTROANSOPER = NEW.BDREGISTROANSOPER AND
                  BDREFEMISSAO = NEW.BDREFEMISSAO
            INTO :WEXISTEREGISTRO;

            IF (COALESCE(WEXISTEREGISTRO, 0) = 0) THEN
               BEGIN
                 INSERT INTO VRHF_TEMP_EMP_TPLANSAU5002
                 (BDSESSAO, BDCODEMP, BDTIPO, BDCPFCOL, BDCPFDEP, BDUNICO, BDTAGSTR, BDDESCRICAOFOLHA, BDCODCOL, BDCODDPN, BDNOME, BDCNPJOPER, BDREGISTROANSOPER, BDVALOR, BDZERADO, BDCODEMPORD,
                  BDREFEMISSAO, BDSEQUENCIAL)
                 VALUES
                 (NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDTIPO, NEW.BDCPFCOL, NEW.BDCPFDEP, 2, '', '', NEW.BDCODCOL, NEW.BDCODDPN, NULL, NEW.BDCNPJOPER, NEW.BDREGISTROANSOPER, NULL, TRUE, NEW.BDCODEMPORD,
                  NEW.BDREFEMISSAO, new.BDSEQUENCIAL + 1);
               END

            DELETE FROM VRHF_TEMP_EMP_TPLANSAU5002
            WHERE BDSESSAO = NEW.BDSESSAO AND
                  BDCODEMPORD = NEW.BDCODEMPORD AND
                  BDTIPO   = NEW.BDTIPO   AND
                  BDCPFCOL = NEW.BDCPFCOL AND
                  BDCPFDEP = NEW.BDCPFDEP AND
                  BDUNICO  = 1 AND
                  BDCNPJOPER = NEW.BDCNPJOPER AND
                  BDREGISTROANSOPER = NEW.BDREGISTROANSOPER AND
                  BDZERADO = TRUE AND
                  BDREFEMISSAO = NEW.BDREFEMISSAO;
          END
     END
end
^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TPLANSAU5002_BU0 FOR VRHF_TEMP_EMP_TPLANSAU5002
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  /* Trigger text */

  NEW.BDVALOR = COALESCE(NEW.BDVALOR, 0) + COALESCE(OLD.BDVALOR, 0);
end
^

create or alter procedure SP_REL_TOT_5002_PLANSAU (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRUNICO integer,
    PRTAGSTR varchar(100),
    PRDESCRICAOFOLHA varchar(1000),
    PRCODEMPORD integer,
    PRREFEMISSAO integer)
as
declare variable WCODEMP integer;
declare variable WCODCOL integer;
declare variable WREF integer;
declare variable WTEMPENSAOUNICO integer;
declare variable WCODDPN integer;
declare variable WNOME varchar(70);
declare variable WCPFDPN varchar(14);
declare variable WCNPJOPER varchar(18);
declare variable WREGISTROANSOPER integer;
declare variable WVALOR numeric(18,6);
declare variable WTIPO integer;
declare variable WEVT integer;
declare variable WEVTANT integer;
declare variable WVALORAUX numeric(18,6);
declare variable WCPFCOL varchar(14);
declare variable WCODPLACONVSAU integer;
declare variable WCODOPERADORA integer;
declare variable WCODCONVENIO integer;
declare variable WNOMEOPER varchar(80);
declare variable WEXECUTA integer;
BEGIN
  /* Procedure Text */

  if (COALESCE(PRUNICO, 0) = 1) then
     begin
       WEXECUTA = 0;
       SELECT REF.BDCODEMP FROM VRHF_TEMP_EMP_CONTROLE_REF_5002 REF
       WHERE BDSESSAO = CURRENT_CONNECTION AND BDCODEMP = :PRCODEMP AND BDCODCOL = :PRCODCOL AND BDREF = :PRREF AND BDTIPO = 0 INTO :WEXECUTA;
     
       IF (COALESCE(WEXECUTA, 0) > 0) THEN
          EXIT;
     
       INSERT INTO VRHF_TEMP_EMP_CONTROLE_REF_5002 (BDSESSAO, BDCODEMP, BDCODCOL, BDREF, BDTIPO) VALUES (CURRENT_CONNECTION, :PRCODEMP, :PRCODCOL, :PRREF, 0);
     end

  WCODEMP = 0;
  WCODCOL = 0;
  WREF = 0;
  WTEMPENSAOUNICO = 0;
  WCODDPN = 0;
  WNOME = '';
  WCPFDPN = '';
  WCNPJOPER = '';
  WREGISTROANSOPER = 0;
  WVALOR = 0;
  WTIPO = 0;
  WEVT = 0;
  WEVTANT = -1;
  WVALORAUX = 0;
  WCODPLACONVSAU = 0;
  WCODOPERADORA = 0;
  WCODCONVENIO = 0;
  WREF = 0;

  wcpfcol = '';
  select first 1 doc.bdcpfcol from vrh_emp_tcolcon_doc doc where doc.bdcodemp = :prcodemp and doc.bdcodcol = :prcodcol into :WCPFCOL;

  if (COALESCE(PRUNICO, 0) = 2) then
     BEGIN
        FOR
            SELECT CONSOLID.BDCODEMP, CONSOLID.BDCODCOL, CONSOLID.BDCODEVT, PLANSAU.BDTIPOREGISTRO, PLANSAU.BDCNPJOPER, PLANSAU.BDREGANS, PLANSAU.BDVLRSAUDE, PLANSAU.BDCPFDEP
            FROM VRH_ESOCIAL_CONSOLIDAPURMEN_C CONSOLID
            INNER JOIN VRH_ESOCIAL_INFOIRRF_PLANSAU PLANSAU ON (CONSOLID.BDCODEMP = PLANSAU.BDCODEMP AND CONSOLID.BDCODCOL = PLANSAU.BDCODCOL AND CONSOLID.BDCODEVT = PLANSAU.BDCODEVT AND
                                                                CONSOLID.BDTIPOCALCFIR = PLANSAU.BDTIPOCALCFIR AND CONSOLID.BDCODCONSOLID = PLANSAU.BDCODCONSOLID)
            WHERE CONSOLID.BDCODEMP = :PRCODEMP AND
                  CONSOLID.BDCODCOL = :PRCODCOL AND
                  CONSOLID.BDREFEVT = :PRREFEMISSAO
            ORDER BY BDCODEVT DESC
        INTO :WCODEMP, :WCODCOL, :WEVT, :WTIPO, :WCNPJOPER, :WREGISTROANSOPER, :WVALOR, :WCPFDPN
        DO
        BEGIN
          if (wevtant = -1) then
            wevtant = wevt;
          else if (wevt <> wevtant) then
            break;

          if (COALESCE(WTIPO, 0) = 1) then
             WTIPO = 0;
          ELSE IF (COALESCE(WTIPO, 0) = 2) then
             WTIPO = 1;

          WCPFDPN = COALESCE(WCPFDPN, '');
          PRTAGSTR = COALESCE(PRTAGSTR, '');
          WCNPJOPER = COALESCE(WCNPJOPER, '');
          WREGISTROANSOPER = COALESCE(WREGISTROANSOPER, 0);

          WNOME = '';
          if (WTIPO = 0) then
             SELECT FIRST 1 BDNOMCOL
             FROM VRH_EMP_TCOLCON_CAD
             WHERE BDCODEMP = :WCODEMP AND
                   BDCODCOL = :WCODCOL AND
                   BDREFCOL <= :PRREFEMISSAO
             ORDER BY BDREFCOL DESC
             INTO :WNOME;
          else
             SELECT FIRST 1 BDNOMEDPN
             FROM VRH_EMP_TDEP_REF
             WHERE BDCODEMP = :WCODEMP AND
                   BDCODCOL = :WCODCOL AND
                   BDCPFDPN = :WCPFDPN AND
                   BDREFDPN <= :PRREFEMISSAO
             ORDER BY BDREFDPN DESC
             INTO :WNOME;

          UPDATE OR INSERT INTO VRHF_TEMP_EMP_TPLANSAU5002
          (BDSESSAO, BDCODEMP, BDTIPO, BDCPFDEP, BDUNICO, BDTAGSTR, BDDESCRICAOFOLHA, BDCODCOL, BDNOME, BDCNPJOPER, BDREGISTROANSOPER, BDVALOR, BDZERADO, BDCODEMPORD, BDCPFCOL,
           BDREFEMISSAO)
          VALUES
          (CURRENT_CONNECTION, :WCODEMP, :WTIPO, :WCPFDPN, 2, :PRTAGSTR, :PRDESCRICAOFOLHA, :WCODCOL, :WNOME, :WCNPJOPER, :WREGISTROANSOPER, :WVALOR, FALSE, :PRCODEMPORD, :WCPFCOL,
           :PRREFEMISSAO)
          MATCHING (BDSESSAO, BDCODEMPORD, BDTIPO, BDCPFCOL, BDCPFDEP, BDUNICO, BDTAGSTR, BDCNPJOPER, BDREGISTROANSOPER, BDREFEMISSAO);

          WCODEMP = 0;
          WCODCOL = 0;
          WCODDPN = 0;
          WNOME = '';
          WCPFDPN = '';
          WCNPJOPER = '';
          WREGISTROANSOPER = 0;
          WVALOR = 0;
          WTIPO = -1;
        END
     END
  ELSE
     BEGIN
        FOR
            SELECT CONV.BDCODEMP, CONV.BDCODCOL, CONV.BDCODDPN, CONV.BDNOME, DEPREF.BDCPFDPN BDCPF,
                   OP.BDCNPJ, OP.BDREGISTROANS, COALESCE(CONV.BDVALORMENSALIDADE, 0) + COALESCE(CONV.BDVALORCOPAR, 0), CONV.BDTIPO,
                   CONV.BDCODPLACONVSAU, CONV.BDCODOPERADORA, CONV.BDCODCONVENIO, CONV.BDREF,OP.BDRAZAOSOCIAL
            FROM SP_VRHM_EMP_VAL_TOD_OP_ATU(:PRCODEMP, :PRCODCOL, :PRREF) CONV
            JOIN VRH_BASE_TCONVSAUDE OP ON OP.BDCODCONVENIO = CONV.BDCODOPERADORA
            LEFT JOIN VRH_EMP_TDEP DEP ON DEP.BDCODEMP = CONV.BDCODEMP AND
                  DEP.BDCODCOL = CONV.BDCODCOL AND
                  DEP.BDCODDPN = CONV.BDCODDPN
            LEFT JOIN(SELECT DEP.BDCODEMP, DEP.BDCODCOL, DEP.BDCODDPN, MAX(DEP.BDREFDPN) BDREFDPN
                      FROM VRH_EMP_TDEP_REF DEP
                      WHERE BDREFDPN <= :PRREF
                      GROUP BY DEP.BDCODEMP, DEP.BDCODCOL, DEP.BDCODDPN) DEPMAX ON DEPMAX.BDCODEMP = DEP.BDCODEMP AND
                  DEPMAX.BDCODCOL = DEP.BDCODCOL AND
                  DEPMAX.BDCODDPN = DEP.BDCODDPN
            LEFT OUTER JOIN VRH_EMP_TDEP_REF DEPREF ON DEPREF.BDCODEMP = DEP.BDCODEMP AND
                  DEPREF.BDCODCOL = DEP.BDCODCOL AND
                  DEPREF.BDCODDPN = DEP.BDCODDPN AND
                  DEPREF.BDREFDPN = COALESCE(DEPMAX.BDREFDPN, (SELECT MAX(BDREFDPN)
                                                               FROM VRH_EMP_TDEP_REF DEPM
                                                               WHERE DEPM.BDCODEMP = DEP.BDCODEMP AND
                                                                     DEPM.BDCODCOL = DEP.BDCODCOL AND
                                                                     DEPM.BDCODDPN = DEP.BDCODDPN))
            WHERE ((DEP.BDDATABAUXADPN IS NULL) OR (SUBSTRING(DEP.BDDATABAUXADPN FROM 1 FOR 4) || SUBSTRING(DEP.BDDATABAUXADPN FROM 6 FOR 2) > :PRREF)) AND
                  ((CONV.BDVALORMENSALIDADE > 0) OR (CONV.BDVALORCOPAR > 0))
            ORDER BY OP.BDCNPJ, OP.BDREGISTROANS, BDCODEMP, BDCODCOL, BDCODDPN
        INTO :WCODEMP, :WCODCOL, :WCODDPN, :WNOME, :WCPFDPN, :WCNPJOPER, :WREGISTROANSOPER, :WVALOR, :WTIPO,
             :WCODPLACONVSAU, :WCODOPERADORA, :WCODCONVENIO, :WREF, :WNOMEOPER
        DO
        BEGIN
          WCPFDPN = COALESCE(WCPFDPN, '');
          PRTAGSTR = COALESCE(PRTAGSTR, '');
          WCNPJOPER = COALESCE(WCNPJOPER, '');
          WREGISTROANSOPER = COALESCE(WREGISTROANSOPER, 0);
          WCODDPN = COALESCE(WCODDPN, 0);
          WNOMEOPER = COALESCE(WNOMEOPER,'');

          IF (WNOMEOPER = '') THEN
             WNOMEOPER = WCNPJOPER;

          if (PRTAGSTR <> '') then
             begin
               PRTAGSTR = WCODEMP||'|'||WCODCOL||'|'||PRREF||'|'||WCODPLACONVSAU||'|'||WCODOPERADORA||'|'||WCODCONVENIO||'|'||WCODDPN;
               PRDESCRICAOFOLHA = 'Lançamento';
             end

          UPDATE OR INSERT INTO VRHF_TEMP_EMP_TPLANSAU5002
          (BDSESSAO, BDCODEMP, BDTIPO, BDCPFDEP, BDUNICO, BDTAGSTR, BDDESCRICAOFOLHA, BDCODCOL, BDCODDPN, BDNOME, BDCNPJOPER, BDREGISTROANSOPER, BDVALOR, BDZERADO, BDCODEMPORD, BDCPFCOL,
           BDREFEMISSAO,BDNOMEOPER)
          VALUES
          (CURRENT_CONNECTION, :WCODEMP, :WTIPO, :WCPFDPN, 1, :PRTAGSTR, :PRDESCRICAOFOLHA, :WCODCOL, :WCODDPN, :WNOME, :WCNPJOPER, :WREGISTROANSOPER, :WVALOR, FALSE, :PRCODEMPORD, :WCPFCOL,
           :PRREFEMISSAO,:WNOMEOPER)
          MATCHING (BDSESSAO, BDCODEMP, BDTIPO, BDCODCOL, BDCPFCOL, BDCPFDEP, BDUNICO, BDTAGSTR, BDCNPJOPER, BDREGISTROANSOPER, BDREFEMISSAO);

          WCODEMP = 0;
          WCODCOL = 0;
          WCODDPN = 0;
          WNOME = '';
          WCPFDPN = '';
          WCNPJOPER = '';
          WREGISTROANSOPER = 0;
          WVALOR = 0;
          WTIPO = -1;
          WCODPLACONVSAU = 0;
          WCODOPERADORA = 0;
          WCODCONVENIO = 0;
          WREF = 0;
          WNOMEOPER = '';
        END
   END
--  suspend;
END^

CREATE OR ALTER TRIGGER VRHF_EMP_TFIPENSAO_DEP_BIU0 FOR VRHF_EMP_TFIPENSAO_DEP
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  /* Trigger text */

  IF (NEW.BDFICHA IS NULL) THEN
     NEW.BDFICHA = TRUE;
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TFIPENSAO_DEP_AIU0 FOR VRHF_EMP_TFIPENSAO_DEP
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
declare variable WTOTALPENSAODEP numeric(18,6);
begin
  /* Trigger text */
  IF (COALESCE(NEW.BDFICHA, FALSE) = FALSE) THEN
     BEGIN
        WTOTALPENSAODEP = 0;
        SELECT SUM(BDVALPEND)
        FROM VRHF_EMP_TFIPENSAO_DEP
        WHERE BDCODEMP = NEW.BDCODEMP AND
              BDCODCOL = NEW.BDCODCOL AND
              BDCOMPPEND = NEW.BDCOMPPEND AND
              BDTIPOPEND = NEW.BDTIPOPEND AND
              BDCODFIR = NEW.BDCODFIR
        INTO :WTOTALPENSAODEP;

        UPDATE VRHF_EMP_TFICHAIRRF SET BDPENALIMFIR = :WTOTALPENSAODEP
        WHERE BDCODEMP = NEW.BDCODEMP AND
              BDCODCOL = NEW.BDCODCOL AND
              BDCODFIR = NEW.BDCODFIR;
     END
end
^

create or alter procedure SP_REL_TOT_5002_REEMBMED (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRUNICO integer,
    PRTAGSTR varchar(100),
    PRDESCRICAOFOLHA varchar(1000),
    PRCODEMPORD integer,
    PRREFEMISSAO integer)
as
declare variable WCODDPN integer;
declare variable WNOME varchar(70);
declare variable WCPFDPN varchar(14);
declare variable WCNPJOPER varchar(18);
declare variable WREGISTROANSOPER integer;
declare variable WEVT integer;
declare variable WEVTANT integer;
declare variable WCPFCOL varchar(14);
declare variable WINDORGREEMB integer;
declare variable WDESCINDORGREEMB varchar(200);
declare variable WCNPJPRESTADOR varchar(18);
declare variable WVLRREEMB numeric(18,6);
declare variable WVLRREEMBANT numeric(18,6);
declare variable WTIPO integer;
declare variable WNOMEOPER varchar(80);
declare variable WOPERADORA integer;
declare variable WEXECUTA integer;
BEGIN
  /* Procedure Text */

  if (COALESCE(PRUNICO, 0) = 1) then
     begin
       WEXECUTA = 0;
       SELECT REF.BDCODEMP FROM VRHF_TEMP_EMP_CONTROLE_REF_5002 REF
       WHERE BDSESSAO = CURRENT_CONNECTION AND BDCODEMP = :PRCODEMP AND BDCODCOL = :PRCODCOL AND BDREF = :PRREF AND BDTIPO = 1 INTO :WEXECUTA;
     
       IF (COALESCE(WEXECUTA, 0) > 0) THEN
          EXIT;
     
       INSERT INTO VRHF_TEMP_EMP_CONTROLE_REF_5002 (BDSESSAO, BDCODEMP, BDCODCOL, BDREF, BDTIPO) VALUES (CURRENT_CONNECTION, :PRCODEMP, :PRCODCOL, :PRREF, 1);
     end

  WCODDPN = 0;
  WNOME = '';
  WCPFDPN = '';
  WCNPJOPER = '';
  WREGISTROANSOPER = 0;
  WEVT = 0;
  WEVTANT = -1;
  WINDORGREEMB = 0;
  WDESCINDORGREEMB = '';
  WCNPJPRESTADOR = '';
  WVLRREEMB = 0;
  WVLRREEMBANT = 0;
  WTIPO = 0;
  WNOMEOPER = '';
  WOPERADORA = 0;

  wcpfcol = '';
  select first 1 doc.bdcpfcol from vrh_emp_tcolcon_doc doc where doc.bdcodemp = :prcodemp and doc.bdcodcol = :prcodcol into :WCPFCOL;

  if (COALESCE(PRUNICO, 0) = 2) then
     BEGIN
        FOR
            SELECT CONSOLID.BDCODEVT, REEMBMED.BDTIPOREGISTRO, REEMBMED.BDCNPJOPER,
                   CASE
                      WHEN (REEMBMED.BDREGANS IS NULL) OR (REEMBMED.BDREGANS = '') THEN '0'
                      ELSE REEMBMED.BDREGANS
                   END BDREGANS,
                   REEMBMED.BDINDORGREEMB, REEMBMED.BDNRINSC, REEMBMED.BDVLRREEMB, REEMBMED.BDVLRREEMBANT, REEMBMED.BDCPFBENEF,
                   O.BDDESCRICAO
            FROM VRH_ESOCIAL_CONSOLIDAPURMEN_C CONSOLID
            INNER JOIN VRH_ESOCIAL_INFOIRRF_REEMBMED REEMBMED ON (CONSOLID.BDCODEMP = REEMBMED.BDCODEMP AND CONSOLID.BDCODCOL = REEMBMED.BDCODCOL AND CONSOLID.BDCODEVT = REEMBMED.BDCODEVT AND
                                                                CONSOLID.BDTIPOCALCFIR = REEMBMED.BDTIPOCALCFIR AND CONSOLID.BDCODCONSOLID = REEMBMED.BDCODCONSOLID)
            LEFT OUTER JOIN VRH_BASE_TORIGEM_REEMBOLSO O ON (REEMBMED.BDINDORGREEMB = O.BDCODIGO)
            WHERE CONSOLID.BDCODEMP = :PRCODEMP AND
                  CONSOLID.BDCODCOL = :PRCODCOL AND
                  CONSOLID.BDREFEVT = :PRREFEMISSAO
            ORDER BY BDCODEVT DESC
        INTO :WEVT, :WTIPO, :WCNPJOPER, :WREGISTROANSOPER,
             :WINDORGREEMB, :WCNPJPRESTADOR, :WVLRREEMB, :WVLRREEMBANT, :WCPFDPN,
             :WDESCINDORGREEMB
        DO
        BEGIN
          if (wevtant = -1) then
            wevtant = wevt;
          else if (wevt <> wevtant) then
            break;

          if (COALESCE(WTIPO, 0) = 1) then
             WTIPO = 0;
          ELSE IF (COALESCE(WTIPO, 0) = 2) then
             WTIPO = 1;

          WCPFDPN = COALESCE(WCPFDPN, '');
          PRTAGSTR = COALESCE(PRTAGSTR, '');
          WCNPJOPER = COALESCE(WCNPJOPER, '');
          WREGISTROANSOPER = COALESCE(WREGISTROANSOPER, 0);
          WCNPJPRESTADOR = COALESCE(WCNPJPRESTADOR, '');

          WNOME = '';
          if (WTIPO = 0) then
             SELECT FIRST 1 BDNOMCOL
             FROM VRH_EMP_TCOLCON_CAD
             WHERE BDCODEMP = :PRCODEMP AND
                   BDCODCOL = :PRCODCOL AND
                   BDREFCOL <= :PRREFEMISSAO
             ORDER BY BDREFCOL DESC
             INTO :WNOME;
          else
             SELECT FIRST 1 BDNOMEDPN
             FROM VRH_EMP_TDEP_REF
             WHERE BDCODEMP = :PRCODEMP AND
                   BDCODCOL = :PRCODCOL AND
                   BDCPFDPN = :WCPFDPN AND
                   BDREFDPN <= :PRREFEMISSAO
             ORDER BY BDREFDPN DESC
             INTO :WNOME;

          UPDATE OR INSERT INTO VRHF_TEMP_EMP_TREEMBMED5002
          (BDSESSAO, BDCODEMP, BDTIPO, BDCPFDEP, BDUNICO, BDTAGSTR, BDDESCRICAOFOLHA, BDCODCOL, BDNOME, BDCNPJOPER, BDREGISTROANSOPER, BDINDORGREEMB, BDDESCINDORGREEMB,
           BDNRINSC, BDVLRREEMB, BDVLRREEMBANT, BDZERADO, BDCODEMPORD, BDCPFCOL, BDREFEMISSAO)
          VALUES
          (CURRENT_CONNECTION, :PRCODEMP, :WTIPO, :WCPFDPN, 2, :PRTAGSTR, :PRDESCRICAOFOLHA, :PRCODCOL, :WNOME, :WCNPJOPER, :WREGISTROANSOPER, :WINDORGREEMB, :WDESCINDORGREEMB,
           :WCNPJPRESTADOR, :WVLRREEMB, :WVLRREEMBANT, FALSE, :PRCODEMPORD, :WCPFCOL, :PRREFEMISSAO)
          MATCHING (BDSESSAO, BDCODEMPORD, BDTIPO, BDCPFCOL, BDCPFDEP, BDUNICO, BDTAGSTR, BDCNPJOPER, BDREGISTROANSOPER, BDNRINSC, BDREFEMISSAO);

          WCODDPN = 0;
          WNOME = '';
          WCPFDPN = '';
          WCNPJOPER = '';
          WREGISTROANSOPER = 0;
          WEVT = 0;
          WINDORGREEMB = 0;
          WDESCINDORGREEMB = '';
          WCNPJPRESTADOR = '';
          WVLRREEMB = 0;
          WVLRREEMBANT = 0;
          WTIPO = 0;
        END
     END
  ELSE
     BEGIN
        ------------------ TITULAR
        FOR
            SELECT R.BDORIGEM, R.BDPRESTADOR, R.BDREEMBOLSO, R.BDREEMBOLSORRA,
                   R.BDOPERADORA,
                   P.BDCNPJ, P.BDREGISTROANS, P.BDRAZAOSOCIAL, O.BDDESCRICAO
                   FROM VRH_EMP_TREEMBOLSO_PLANOSAUDE R
                   LEFT OUTER JOIN VRH_BASE_TCONVSAUDE P ON (R.BDOPERADORA = P.BDCODCONVENIO)
                   LEFT OUTER JOIN VRH_BASE_TORIGEM_REEMBOLSO O ON (R.BDORIGEM = O.BDCODIGO)
                   WHERE R.BDCODEMP = :PRCODEMP AND 
                         R.BDCODCOL = :PRCODCOL AND 
                         R.BDREF = :PRREF AND
                         ((R.BDREEMBOLSO > 0) or (R.BDREEMBOLSORRA > 0))
        INTO :WINDORGREEMB, :WCNPJPRESTADOR, :WVLRREEMB, :WVLRREEMBANT,
             :WOPERADORA,
             :WCNPJOPER, :WREGISTROANSOPER, :WNOMEOPER, :WDESCINDORGREEMB
        DO
        BEGIN
          WCPFDPN = '';
          PRTAGSTR = COALESCE(PRTAGSTR, '');
          WCNPJOPER = COALESCE(WCNPJOPER, '');
          WREGISTROANSOPER = COALESCE(WREGISTROANSOPER, 0);
          WCNPJPRESTADOR = COALESCE(WCNPJPRESTADOR, '');
          WNOMEOPER = COALESCE(WNOMEOPER, '');
          WOPERADORA = COALESCE(WOPERADORA, 0);

          IF (WNOMEOPER = '') THEN
             WNOMEOPER = WCNPJOPER;

          if (PRTAGSTR <> '') then
             begin
               PRTAGSTR = PRCODEMP||'|'||PRCODCOL||'|'||PRREF||'|'||WINDORGREEMB||'|'||WOPERADORA||'|'||WCNPJPRESTADOR;
               PRDESCRICAOFOLHA = 'Lançamento';
             end

          WNOME = '';
          SELECT FIRST 1 BDNOMCOL
          FROM VRH_EMP_TCOLCON_CAD
          WHERE BDCODEMP = :PRCODEMP AND
                BDCODCOL = :PRCODCOL AND
                BDREFCOL <= :PRREFEMISSAO
          ORDER BY BDREFCOL DESC
          INTO :WNOME;

          UPDATE OR INSERT INTO VRHF_TEMP_EMP_TREEMBMED5002
          (BDSESSAO, BDCODEMP, BDTIPO, BDCPFDEP, BDUNICO, BDTAGSTR, BDDESCRICAOFOLHA, BDCODCOL, BDNOME, BDCNPJOPER, BDREGISTROANSOPER, BDINDORGREEMB, BDDESCINDORGREEMB,
           BDNRINSC, BDVLRREEMB, BDVLRREEMBANT, BDZERADO, BDCODEMPORD, BDCPFCOL, BDNOMEOPER, BDREFEMISSAO)
          VALUES
          (CURRENT_CONNECTION, :PRCODEMP, 0, :WCPFDPN, 1, :PRTAGSTR, :PRDESCRICAOFOLHA, :PRCODCOL, :WNOME, :WCNPJOPER, :WREGISTROANSOPER, :WINDORGREEMB, :WDESCINDORGREEMB,
           :WCNPJPRESTADOR, :WVLRREEMB, :WVLRREEMBANT, FALSE, :PRCODEMPORD, :WCPFCOL, :WNOMEOPER, :PRREFEMISSAO)
          MATCHING (BDSESSAO, BDCODEMP, BDTIPO, BDCPFCOL, BDCPFDEP, BDUNICO, BDTAGSTR, BDCODCOL, BDCNPJOPER, BDREGISTROANSOPER, BDNRINSC, BDREFEMISSAO);

          WCODDPN = 0;
          WNOME = '';
          WCPFDPN = '';
          WCNPJOPER = '';
          WREGISTROANSOPER = 0;
          WEVT = 0;
          WINDORGREEMB = 0;
          WDESCINDORGREEMB = '';
          WCNPJPRESTADOR = '';
          WVLRREEMB = 0;
          WVLRREEMBANT = 0;
          WTIPO = 0;
          WNOMEOPER = '';
          WOPERADORA = 0;
        END

        ------------------ DEPENDENTE
        FOR
            SELECT R.BDORIGEM, R.BDPRESTADOR, R.BDREEMBOLSO, R.BDREEMBOLSORRA,
                   R.BDOPERADORA,
                   P.BDCNPJ, P.BDREGISTROANS, P.BDRAZAOSOCIAL, DEP.BDCPFDPN, O.BDDESCRICAO,R.BDCODDEP
            FROM VRH_EMP_REEMBOLSO_PLA_SAUDE_DEP R
            LEFT OUTER JOIN VRH_BASE_TCONVSAUDE P ON (R.BDOPERADORA = P.BDCODCONVENIO)
            LEFT OUTER JOIN VRH_EMP_TDEP_REF DEP ON (R.BDCODEMP = DEP.BDCODEMP AND R.BDCODCOL = DEP.BDCODCOL AND R.BDCODDEP = DEP.BDCODDPN AND
                                                     DEP.BDREFDPN = (SELECT FIRST 1 X.BDREFDPN FROM VRH_EMP_TDEP_REF X
                                                                     WHERE X.BDCODEMP = DEP.BDCODEMP AND X.BDCODCOL = DEP.BDCODCOL AND
                                                                           X.BDCODDPN = DEP.BDCODDPN
                                                                     ORDER BY X.BDREFDPN DESC
                                                                     ))
            LEFT OUTER JOIN VRH_BASE_TORIGEM_REEMBOLSO O ON (R.BDORIGEM = O.BDCODIGO)
            WHERE R.BDCODEMP = :PRCODEMP AND 
                  R.BDCODCOL = :PRCODCOL AND
                  R.BDREF = :PRREF AND
                  ((R.BDREEMBOLSO > 0) or (R.BDREEMBOLSORRA > 0))
        INTO :WINDORGREEMB, :WCNPJPRESTADOR, :WVLRREEMB, :WVLRREEMBANT,
             :WOPERADORA,
             :WCNPJOPER, :WREGISTROANSOPER, :WNOMEOPER, :WCPFDPN, :WDESCINDORGREEMB,:WCODDPN
        DO
        BEGIN
          WCPFDPN = COALESCE(WCPFDPN, '');
          PRTAGSTR = COALESCE(PRTAGSTR, '');
          WCNPJOPER = COALESCE(WCNPJOPER, '');
          WREGISTROANSOPER = COALESCE(WREGISTROANSOPER, 0);
          WCNPJPRESTADOR = COALESCE(WCNPJPRESTADOR, '');
          WNOMEOPER = COALESCE(WNOMEOPER, '');
          WOPERADORA = COALESCE(WOPERADORA, 0);

          if (PRTAGSTR <> '') then
             begin
               PRTAGSTR = PRCODEMP||'|'||PRCODCOL||'|'||PRREF||'|'||WINDORGREEMB||'|'||WOPERADORA||'|'||WCNPJPRESTADOR;
               PRDESCRICAOFOLHA = 'Lançamento';
             end

          WNOME = '';
          SELECT FIRST 1 BDNOMEDPN
          FROM VRH_EMP_TDEP_REF
          WHERE BDCODEMP = :PRCODEMP AND
                BDCODCOL = :PRCODCOL AND
                BDCPFDPN = :WCPFDPN AND
                BDREFDPN <= :PRREFEMISSAO
          ORDER BY BDREFDPN DESC
          INTO :WNOME;

          UPDATE OR INSERT INTO VRHF_TEMP_EMP_TREEMBMED5002
          (BDSESSAO, BDCODEMP, BDTIPO, BDCPFDEP, BDUNICO, BDTAGSTR, BDDESCRICAOFOLHA, BDCODCOL, BDNOME, BDCNPJOPER, BDREGISTROANSOPER, BDINDORGREEMB, BDDESCINDORGREEMB,
           BDNRINSC, BDVLRREEMB, BDVLRREEMBANT, BDZERADO, BDCODEMPORD, BDCPFCOL, BDNOMEOPER, BDREFEMISSAO,BDCODDPN)
          VALUES
          (CURRENT_CONNECTION, :PRCODEMP, 1, :WCPFDPN, 1, :PRTAGSTR, :PRDESCRICAOFOLHA, :PRCODCOL, :WNOME, :WCNPJOPER, :WREGISTROANSOPER, :WINDORGREEMB, :WDESCINDORGREEMB,
           :WCNPJPRESTADOR, :WVLRREEMB, :WVLRREEMBANT, FALSE, :PRCODEMPORD, :WCPFCOL, :WNOMEOPER, :PRREFEMISSAO,:WCODDPN)
          MATCHING (BDSESSAO, BDCODEMP, BDTIPO, BDCPFCOL, BDCPFDEP, BDUNICO, BDTAGSTR, BDCODCOL, BDCNPJOPER, BDREGISTROANSOPER, BDNRINSC, BDREFEMISSAO);

          WCODDPN = 0;
          WNOME = '';
          WCPFDPN = '';
          WCNPJOPER = '';
          WREGISTROANSOPER = 0;
          WEVT = 0;
          WINDORGREEMB = 0;
          WDESCINDORGREEMB = '';
          WCNPJPRESTADOR = '';
          WVLRREEMB = 0;
          WVLRREEMBANT = 0;
          WTIPO = 0;
          WNOMEOPER = '';
          WOPERADORA = 0;
        END

   END
--  suspend;
END^

CREATE OR ALTER PROCEDURE SP_VRHF_BASE_EMPGPS_ATUAL (PRCODEMP INTEGER, PRREF INTEGER)
RETURNS (
    BDRATEIO13SAL INTEGER
) AS
BEGIN

  SELECT FIRST 1 COALESCE(egmax.BDRATEIO13SAL, COALESCE(egmin.BDRATEIO13SAL, 2)) BDRATEIO13SAL /* BDRATEIO13SAL:  2 = NÃO RATEAR */
  FROM TEMPRESAS e
  LEFT OUTER JOIN VRHF_BASE_TEMPGPS egmax on egmax.BDCODEMP = e.BDCODEMP
             and egmax.BDREFEMP = (SELECT FIRST 1 x.BDREFEMP FROM VRHF_BASE_TEMPGPS x
                                  WHERE x.BDCODEMP = e.BDCODEMP
                                  and x.BDREFEMP <=  :PRREF
                                  ORDER BY x.BDREFEMP desc )
  LEFT OUTER JOIN VRHF_BASE_TEMPGPS egmin on egmin.BDCODEMP = e.BDCODEMP
             and egmin.BDREFEMP = (SELECT FIRST 1 mini.BDREFEMP FROM VRHF_BASE_TEMPGPS mini WHERE mini.BDCODEMP = e.BDCODEMP ORDER BY mini.BDREFEMP)
           where e.BDCODEMP = :PRCODEMP
   INTO :BDRATEIO13SAL;
   SUSPEND;
END
^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TREEMBMED5002_BU0 FOR VRHF_TEMP_EMP_TREEMBMED5002
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  /* Trigger text */
  NEW.BDVLRREEMB = COALESCE(NEW.BDVLRREEMB, 0) + COALESCE(OLD.BDVLRREEMB, 0);

  NEW.BDVLRREEMBANT = COALESCE(NEW.BDVLRREEMBANT, 0) + COALESCE(OLD.BDVLRREEMBANT, 0);
end
^

CREATE OR ALTER trigger vrhf_temp_emp_tprevidcompl5002_bi0 for vrhf_temp_emp_tprevidcompl5002
active before insert position 0
AS
DECLARE VARIABLE WEXISTEREGISTRO INTEGER;
DECLARE VARIABLE VCODIGO INTEGER;
begin
  /* Trigger text */
  VCODIGO = 0;
  if ((new.BDSEQUENCIAL is null) or (new.BDSEQUENCIAL = 0)) then
  begin
    select coalesce((max(BDSEQUENCIAL) + 1), 1)
    from VRHF_TEMP_EMP_TPREVIDCOMPL5002
    where BDSESSAO = NEW.BDSESSAO AND
          BDCODEMPORD = NEW.BDCODEMPORD AND
          BDCPFCOL = NEW.BDCPFCOL
    into VCODIGO;

    new.BDSEQUENCIAL = VCODIGO;
  end

  IF (COALESCE(NEW.BDZERADO, 'FALSE') = 'FALSE') THEN
     BEGIN

        IF (COALESCE(NEW.BDUNICO, 0) = 2) THEN
          BEGIN
            /* VERIFICAR SE JÁ EXISTE REGISTRO EQUIVALENTE DO ÚNICO E SE NÃO EXISTIR CRIAR */

            WEXISTEREGISTRO = 0;
            SELECT BDCODEMP FROM VRHF_TEMP_EMP_TPREVIDCOMPL5002
            WHERE BDSESSAO = NEW.BDSESSAO AND
                  BDCODEMP = NEW.BDCODEMP AND
                  BDCPFCOL = NEW.BDCPFCOL AND
                  BDCODCOL = NEW.BDCODCOL AND
                  BDTIPCODREC = NEW.BDTIPCODREC AND
                  BDUNICO  = 1 AND
                  BDTAGSTR = NEW.BDTAGSTR AND
                  BDTPPREV = NEW.BDTPPREV AND
                  BDCNPJENTIDPC = NEW.BDCNPJENTIDPC and
                  BDREFEMISSAO = NEW.BDREFEMISSAO and
                  BDTPCR = NEW.BDTPCR
            INTO :WEXISTEREGISTRO;

            IF (COALESCE(WEXISTEREGISTRO, 0) = 0) THEN
               BEGIN
                 INSERT INTO VRHF_TEMP_EMP_TPREVIDCOMPL5002
                 (BDSESSAO, BDCODEMP, BDCPFCOL, BDCODCOL, BDTIPCODREC, BDUNICO, BDTAGSTR, BDDESCRICAOFOLHA, BDZERADO, BDCODEMPORD, BDTPPREV, BDCNPJENTIDPC, BDVALOR,
                  BDREFEMISSAO, BDTPCR, BDSEQUENCIAL)
                 VALUES
                 (NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDCPFCOL, NEW.BDCODCOL, NEW.BDTIPCODREC, 1, '', '', TRUE, NEW.BDCODEMPORD, NEW.BDTPPREV, NEW.BDCNPJENTIDPC, NULL,
                  NEW.BDREFEMISSAO, NEW.BDTPCR, new.BDSEQUENCIAL + 1);
               END
          END
       ELSE
          BEGIN
            /* VERIFICAR SE JÁ EXISTE REGISTRO EQUIVALENTE DO ESOCIAL E SE NÃO EXISTIR CRIAR */

            WEXISTEREGISTRO = 0;
            SELECT BDCODEMP FROM VRHF_TEMP_EMP_TPREVIDCOMPL5002
            WHERE BDSESSAO = NEW.BDSESSAO AND
                  BDCODEMPORD = NEW.BDCODEMPORD AND
                  BDCPFCOL = NEW.BDCPFCOL AND
                  BDTIPCODREC = NEW.BDTIPCODREC AND
                  BDUNICO  = 2 AND
                  BDTPPREV = NEW.BDTPPREV AND
                  BDCNPJENTIDPC = NEW.BDCNPJENTIDPC and
                  BDREFEMISSAO = NEW.BDREFEMISSAO and
                  BDTPCR = NEW.BDTPCR
            INTO :WEXISTEREGISTRO;

            IF (COALESCE(WEXISTEREGISTRO, 0) = 0) THEN
               BEGIN
                 INSERT INTO VRHF_TEMP_EMP_TPREVIDCOMPL5002
                 (BDSESSAO, BDCODEMP, BDCPFCOL, BDCODCOL, BDTIPCODREC, BDUNICO, BDTAGSTR, BDDESCRICAOFOLHA, BDZERADO, BDCODEMPORD, BDTPPREV, BDCNPJENTIDPC, BDVALOR,
                  BDREFEMISSAO, BDTPCR, BDSEQUENCIAL)
                 VALUES
                 (NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDCPFCOL, NEW.BDCODCOL, NEW.BDTIPCODREC, 2, '', '', TRUE, NEW.BDCODEMPORD, NEW.BDTPPREV, NEW.BDCNPJENTIDPC, NULL,
                  NEW.BDREFEMISSAO, NEW.BDTPCR, new.BDSEQUENCIAL + 1);
               END

            DELETE FROM VRHF_TEMP_EMP_TPREVIDCOMPL5002
            WHERE BDSESSAO = NEW.BDSESSAO AND
                  BDCODEMPORD = NEW.BDCODEMPORD AND
                  BDCPFCOL = NEW.BDCPFCOL AND
                  BDTIPCODREC = NEW.BDTIPCODREC AND
                  BDUNICO  = 1 AND
                  BDTPPREV = NEW.BDTPPREV AND
                  BDCNPJENTIDPC = NEW.BDCNPJENTIDPC AND
                  BDZERADO = TRUE and
                  BDREFEMISSAO = NEW.BDREFEMISSAO and
                  BDTPCR = NEW.BDTPCR;
          END
     END
end
^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TPREVIDCOMPL5002_BU0 FOR VRHF_TEMP_EMP_TPREVIDCOMPL5002
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  /* Trigger text */

  NEW.BDVALOR = COALESCE(NEW.BDVALOR, 0) + COALESCE(OLD.BDVALOR, 0);
end
^

create or alter procedure SP_REL_TOT_5002_PREVIDCOMPL (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRTAGSTR varchar(100),
    PRDESCRICAOFOLHA varchar(1000),
    PRUNICO integer,
    PRTIPCODREC integer,
    PRCODEMPORD integer,
    PRREFEMISSAO integer,
    PRCODREC varchar(6) = null)
as
declare variable WCPFCOL varchar(14);
declare variable WEVT integer;
declare variable WEVTANT integer;
declare variable WTPPREV integer;
declare variable WCNPJENTIDPC varchar(18);
declare variable WVLRDEDPC numeric(15,2);
declare variable WVLRDEDPC13 numeric(15,2);
declare variable WVLRPATROCFUNP numeric(15,2);
declare variable WVLRPATROCFUNP13 numeric(15,2);
declare variable WVALORAUX numeric(15,2);
declare variable WCODLANCPREV integer;
declare variable WTIPOCALCULO integer;
declare variable WEXECUTA integer;
declare variable WTIPOAUX integer;
begin
  /* Procedure Text */

  if (COALESCE(PRUNICO, 0) = 1) then
     begin
       WEXECUTA = 0;
       WTIPOAUX = 2;
       if (prtipcodrec = 2) then
          WTIPOAUX = 3;

       SELECT REF.BDCODEMP FROM VRHF_TEMP_EMP_CONTROLE_REF_5002 REF
       WHERE BDSESSAO = CURRENT_CONNECTION AND BDCODEMP = :PRCODEMP AND BDCODCOL = :PRCODCOL AND BDREF = :PRREF AND BDTIPO = :WTIPOAUX INTO :WEXECUTA;
     
       IF (COALESCE(WEXECUTA, 0) > 0) THEN
          EXIT;
     
       INSERT INTO VRHF_TEMP_EMP_CONTROLE_REF_5002 (BDSESSAO, BDCODEMP, BDCODCOL, BDREF, BDTIPO) VALUES (CURRENT_CONNECTION, :PRCODEMP, :PRCODCOL, :PRREF, :WTIPOAUX);
     end

  WEVT = 0;
  WTPPREV = 0;
  WCNPJENTIDPC = '';
  WVLRDEDPC = 0;
  WVLRDEDPC13 = 0;
  WVLRPATROCFUNP = 0;
  WVLRPATROCFUNP13 = 0;
  wevtant = -1;
  WVALORAUX = 0;
  WCODLANCPREV = 0;

  PRTAGSTR = COALESCE(PRTAGSTR, '');
  PRDESCRICAOFOLHA = COALESCE(PRDESCRICAOFOLHA, '');
  prtipcodrec = coalesce(prtipcodrec, 0);

  wcpfcol = '';
  select first 1 doc.bdcpfcol from vrh_emp_tcolcon_doc doc where doc.bdcodemp = :prcodemp and doc.bdcodcol = :prcodcol into :wcpfcol;

  WTIPOCALCULO = 0;

  IF (COALESCE(PRUNICO, 0) = 2) THEN
     BEGIN
       FOR
            SELECT CONSOLID.BDCODEVT, PREV.BDTPPREV, PREV.BDCNPJENTIDPC, PREV.BDVLRDEDPC, PREV.BDVLRDEDPC13, PREV.BDVLRPATROCFUNP, PREV.BDVLRPATROCFUNP13,
                   CONSOLID.BDTIPOCALCULO
            FROM VRH_ESOCIAL_CONSOLIDAPURMEN_C CONSOLID
            INNER JOIN VRH_ESOCIAL_INFOIRRF_PREVIDCOMPL PREV ON (CONSOLID.BDCODEMP = PREV.BDCODEMP AND CONSOLID.BDCODCOL = PREV.BDCODCOL AND CONSOLID.BDCODEVT = PREV.BDCODEVT AND
                                                                CONSOLID.BDTIPOCALCFIR = PREV.BDTIPOCALCFIR AND CONSOLID.BDCODCONSOLID = PREV.BDCODCONSOLID)
            WHERE CONSOLID.BDCODEMP = :PRCODEMP AND
                  CONSOLID.BDCODCOL = :PRCODCOL AND
                  CONSOLID.BDREFEVT = :PRREFEMISSAO
            ORDER BY BDCODEVT DESC
        INTO :WEVT, :WTPPREV, :WCNPJENTIDPC, :WVLRDEDPC, :WVLRDEDPC13, :WVLRPATROCFUNP, :WVLRPATROCFUNP13, :WTIPOCALCULO
        DO
        BEGIN
          if (wevtant = -1) then
            wevtant = wevt;
          else if (wevt <> wevtant) then
            break;

          WCNPJENTIDPC = COALESCE(WCNPJENTIDPC, '');
          WVLRDEDPC = COALESCE(WVLRDEDPC, 0);
          WVLRPATROCFUNP = COALESCE(WVLRPATROCFUNP, 0);
          WVLRDEDPC13 = COALESCE(WVLRDEDPC13, 0);
          WVLRPATROCFUNP13 = COALESCE(WVLRPATROCFUNP13, 0);
          WTPPREV = COALESCE(WTPPREV, 0);

          WVALORAUX = 0;

          if (COALESCE(WTIPOCALCULO, 0) = 1) then
             begin
               WVALORAUX = WVLRPATROCFUNP;
               if (WTPPREV <> 3) then
                  WVALORAUX = WVLRDEDPC;
             end
          else if (COALESCE(WTIPOCALCULO, 0) = 2) then
             begin
               WVALORAUX = WVLRPATROCFUNP13;
               if (WTPPREV <> 3) then
                  WVALORAUX = WVLRDEDPC13;
             end
          else if (COALESCE(WTIPOCALCULO, 0) = 4) then
             begin
               WVALORAUX = WVLRPATROCFUNP + WVLRPATROCFUNP13;
               if (WTPPREV <> 3) then
                  WVALORAUX = WVLRDEDPC + WVLRDEDPC13;
             end

          UPDATE OR INSERT INTO VRHF_TEMP_EMP_TPREVIDCOMPL5002
          (BDSESSAO, BDCODEMP, BDCPFCOL, BDCODCOL, BDTIPCODREC, BDUNICO, BDTAGSTR, BDDESCRICAOFOLHA, BDZERADO, BDCODEMPORD, BDTPPREV, BDCNPJENTIDPC, BDVALOR,
           BDREFEMISSAO, BDTPCR)
          VALUES
          (CURRENT_CONNECTION, :PRCODEMP, :WCPFCOL, :PRCODCOL, :WTIPOCALCULO, 2, :PRTAGSTR, :PRDESCRICAOFOLHA, FALSE, :PRCODEMPORD, :WTPPREV, :WCNPJENTIDPC, :WVALORAUX,
           :PRREFEMISSAO, :PRCODREC)
          MATCHING (BDSESSAO,BDCODEMPORD,BDCPFCOL,BDTIPCODREC,BDTAGSTR,BDUNICO,BDTPPREV,BDCNPJENTIDPC, BDREFEMISSAO, BDTPCR);

          WEVT = 0;
          WTPPREV = 0;
          WCNPJENTIDPC = '';
          WVLRDEDPC = 0;
          WVLRDEDPC13 = 0;
          WVLRPATROCFUNP = 0;
          WVLRPATROCFUNP13 = 0;
          WVALORAUX = 0;
        END
     END
  ELSE
     BEGIN
       FOR
            SELECT CADPREV.BDNATPREV, CADPREV.BDCNPJ,
                   COALESCE(LANPREV.BDVALMENSAL,0) BDVALMENSAL, COALESCE(LANPREV.BDVAL13SAL,0) BDVAL13SAL,
                   LANPREV.BDCODLANCPREV
            FROM VRH_EMP_TLANCPREVCOMP LANPREV
            JOIN VRH_BASE_TCADPREVCOMP CADPREV ON (LANPREV.BDCODCADPREV = CADPREV.BDCODCADPREV AND CADPREV.BDNATPREV <> 2)
            WHERE LANPREV.BDCODEMP = :PRCODEMP AND
                  LANPREV.BDCODCOL = :PRCODCOL AND
                  LANPREV.BDREFINI <= :PRREF AND
                  ((COALESCE(LANPREV.BDREFFIN,0) >= :PRREF) OR (COALESCE(LANPREV.BDREFFIN,0) = 0)) AND
                  (COALESCE(LANPREV.BDVALMENSAL,0) > 0 OR COALESCE(LANPREV.BDVAL13SAL,0) > 0)
            ORDER BY LANPREV.BDCODEMP, LANPREV.BDCODCOL, LANPREV.BDCODCADPREV
        INTO :WTPPREV, :WCNPJENTIDPC, :WVLRDEDPC, :WVLRDEDPC13,
             :WCODLANCPREV
        DO
        BEGIN

          WCNPJENTIDPC = COALESCE(WCNPJENTIDPC, '');
          WVLRDEDPC = COALESCE(WVLRDEDPC, 0);
          WVLRDEDPC13 = COALESCE(WVLRDEDPC13, 0);
          WTPPREV = COALESCE(WTPPREV + 1, 0);

          WVALORAUX = 0;
          if (COALESCE(PRTIPCODREC, 0) = 1) then
             WVALORAUX = WVLRDEDPC;
          else if (COALESCE(PRTIPCODREC, 0) = 2) then
             WVALORAUX = WVLRDEDPC13;
          else if (COALESCE(PRTIPCODREC, 0) = 4) then
             WVALORAUX = WVLRDEDPC + WVLRDEDPC13;

          if (PRTAGSTR <> '') then
             begin
               PRTAGSTR = PRCODEMP||'|'||PRCODCOL||'|'||WCODLANCPREV;
               PRDESCRICAOFOLHA = 'Lançamento';
             end

          UPDATE OR INSERT INTO VRHF_TEMP_EMP_TPREVIDCOMPL5002
          (BDSESSAO, BDCODEMP, BDCPFCOL, BDCODCOL, BDTIPCODREC, BDUNICO, BDTAGSTR, BDDESCRICAOFOLHA, BDZERADO, BDCODEMPORD, BDTPPREV, BDCNPJENTIDPC, BDVALOR,
           BDREFEMISSAO, BDTPCR)
          VALUES
          (CURRENT_CONNECTION, :PRCODEMP, :WCPFCOL, :PRCODCOL, :PRTIPCODREC, 1, :PRTAGSTR, :PRDESCRICAOFOLHA, FALSE, :PRCODEMPORD, :WTPPREV, :WCNPJENTIDPC, :WVALORAUX,
           :PRREFEMISSAO, :PRCODREC)
          MATCHING (BDSESSAO,BDCODEMP,BDCPFCOL,BDCODCOL,BDTIPCODREC,BDTAGSTR,BDUNICO,BDTPPREV,BDCNPJENTIDPC, BDREFEMISSAO, BDTPCR);

          WTPPREV = 0;
          WCNPJENTIDPC = '';
          WVLRDEDPC = 0;
          WVLRDEDPC13 = 0;
          WVALORAUX = 0;
          WCODLANCPREV = 0;
        END
     END
end^

CREATE OR ALTER trigger vrhf_temp_emp_treembmed5002_bi0 for vrhf_temp_emp_treembmed5002
active before insert position 0
AS
declare variable WEXISTEREGISTRO INTEGER;
declare variable WNOMEOPER VARCHAR(80);
DECLARE VARIABLE VCODIGO INTEGER;
begin
  /* Trigger text */
  VCODIGO = 0;
  if ((new.BDSEQUENCIAL is null) or (new.BDSEQUENCIAL = 0)) then
  begin
    select coalesce((max(BDSEQUENCIAL) + 1), 1)
    from VRHF_TEMP_EMP_TREEMBMED5002
    where BDSESSAO = NEW.BDSESSAO AND
          BDCODEMPORD = NEW.BDCODEMPORD AND
          BDCPFCOL = NEW.BDCPFCOL
    into VCODIGO;

    new.BDSEQUENCIAL = VCODIGO;
  end

  IF (COALESCE(NEW.BDZERADO, 'FALSE') = 'FALSE') THEN
     BEGIN
        NEW.BDCNPJOPER = COALESCE(NEW.BDCNPJOPER, '');
        NEW.BDREGISTROANSOPER = COALESCE(NEW.BDREGISTROANSOPER, 0);
        NEW.BDNRINSC = COALESCE(NEW.BDNRINSC, '');

        IF (COALESCE(NEW.BDUNICO, 0) = 2) THEN
          BEGIN
            /* VERIFICAR SE JÁ EXISTE REGISTRO EQUIVALENTE DO ÚNICO E SE NÃO EXISTIR CRIAR */

            WEXISTEREGISTRO = 0;
            SELECT BDCODEMP FROM VRHF_TEMP_EMP_TREEMBMED5002
            WHERE BDSESSAO = NEW.BDSESSAO AND
                  BDCODEMP = NEW.BDCODEMP AND
                  BDTIPO   = NEW.BDTIPO AND
                  BDCPFCOL = NEW.BDCPFCOL AND
                  BDCPFDEP = NEW.BDCPFDEP AND
                  BDUNICO  = 1 AND
                  BDTAGSTR = NEW.BDTAGSTR AND
                  BDCNPJOPER = NEW.BDCNPJOPER AND
                  BDREGISTROANSOPER = NEW.BDREGISTROANSOPER AND
                  BDCODCOL = NEW.BDCODCOL AND
                  BDNRINSC = NEW.BDNRINSC AND
                  BDREFEMISSAO = NEW.BDREFEMISSAO
            INTO :WEXISTEREGISTRO;

            IF (COALESCE(WEXISTEREGISTRO, 0) = 0) THEN
               BEGIN
                 INSERT INTO VRHF_TEMP_EMP_TREEMBMED5002
                 (BDSESSAO, BDCODEMP, BDTIPO, BDCPFDEP, BDUNICO, BDTAGSTR, BDDESCRICAOFOLHA, BDCODCOL, BDNOME, BDCNPJOPER, BDREGISTROANSOPER, BDINDORGREEMB, BDDESCINDORGREEMB,
                  BDNRINSC, BDVLRREEMB, BDVLRREEMBANT, BDZERADO, BDCODEMPORD, BDCPFCOL, BDNOMEOPER, BDREFEMISSAO, BDSEQUENCIAL)
                 VALUES
                 (NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDTIPO, NEW.BDCPFDEP, 1, '', '', NEW.BDCODCOL, NULL, NEW.BDCNPJOPER, NEW.BDREGISTROANSOPER, NULL, NULL,
                  NEW.BDNRINSC, NULL, NULL, TRUE, NEW.BDCODEMPORD, NEW.BDCPFCOL, NEW.BDCNPJOPER, NEW.BDREFEMISSAO, new.BDSEQUENCIAL + 1);
               END
          END
       ELSE
          BEGIN
            /* VERIFICAR SE JÁ EXISTE REGISTRO EQUIVALENTE DO ESOCIAL E SE NÃO EXISTIR CRIAR */

            WEXISTEREGISTRO = 0;
            SELECT BDCODEMP FROM VRHF_TEMP_EMP_TREEMBMED5002
            WHERE BDSESSAO = NEW.BDSESSAO AND
                  BDCODEMPORD = NEW.BDCODEMPORD AND
                  BDTIPO   = NEW.BDTIPO   AND
                  BDCPFCOL = NEW.BDCPFCOL AND
                  BDCPFDEP = NEW.BDCPFDEP AND
                  BDUNICO  = 2 AND
                  BDCNPJOPER = NEW.BDCNPJOPER AND
                  BDREGISTROANSOPER = NEW.BDREGISTROANSOPER AND
                  BDNRINSC = NEW.BDNRINSC AND
                  BDREFEMISSAO = NEW.BDREFEMISSAO
            INTO :WEXISTEREGISTRO;

            IF (COALESCE(WEXISTEREGISTRO, 0) = 0) THEN
               BEGIN
                 WNOMEOPER = COALESCE(NEW.BDNOMEOPER, '');

                 INSERT INTO VRHF_TEMP_EMP_TREEMBMED5002
                 (BDSESSAO, BDCODEMP, BDTIPO, BDCPFDEP, BDUNICO, BDTAGSTR, BDDESCRICAOFOLHA, BDCODCOL, BDNOME, BDCNPJOPER, BDREGISTROANSOPER, BDINDORGREEMB, BDDESCINDORGREEMB,
                  BDNRINSC, BDVLRREEMB, BDVLRREEMBANT, BDZERADO, BDCODEMPORD, BDCPFCOL, BDNOMEOPER, BDREFEMISSAO, BDSEQUENCIAL)
                 VALUES
                 (NEW.BDSESSAO, NEW.BDCODEMP, NEW.BDTIPO, NEW.BDCPFDEP, 2, '', '', NEW.BDCODCOL,
                  NULL, NEW.BDCNPJOPER, NEW.BDREGISTROANSOPER, NULL, NULL,
                  NEW.BDNRINSC, NULL, NULL, TRUE, NEW.BDCODEMPORD, NEW.BDCPFCOL, :WNOMEOPER, NEW.BDREFEMISSAO, new.BDSEQUENCIAL + 1);
               END

            DELETE FROM VRHF_TEMP_EMP_TREEMBMED5002
            WHERE BDSESSAO = NEW.BDSESSAO AND
                  BDCODEMPORD = NEW.BDCODEMPORD AND
                  BDTIPO   = NEW.BDTIPO   AND
                  BDCPFCOL = NEW.BDCPFCOL AND
                  BDCPFDEP = NEW.BDCPFDEP AND
                  BDUNICO  = 1 AND
                  BDCNPJOPER = NEW.BDCNPJOPER AND
                  BDREGISTROANSOPER = NEW.BDREGISTROANSOPER AND
                  BDNRINSC = NEW.BDNRINSC AND
                  BDZERADO = TRUE AND
                  BDREFEMISSAO = NEW.BDREFEMISSAO;
          END
     END
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TDIFERENCA5002_BI0 FOR VRH_EMP_TDIFERENCA5002
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE vNovoCod INTEGER;
begin
  /* Trigger text */

  IF ((NEW.BDSEQUENCIAL IS NULL) OR (NEW.BDSEQUENCIAL = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(BDSEQUENCIAL) + 1, 1)
            FROM VRH_EMP_TDIFERENCA5002
            WHERE BDCODMATRIZ = NEW.BDCODMATRIZ AND
                  BDCPFCOL = NEW.BDCPFCOL AND
                  BDREF = NEW.BDREF AND
                  BDTIPCODREC = NEW.BDTIPCODREC
            INTO :vNovoCod;

       NEW.BDSEQUENCIAL = :VNOVOCOD;
     END

  if (new.bdtipomsg is null) then
     new.bdtipomsg = 0;
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TVERBA13_DET_BI0 FOR VRHF_EMP_TVERBA13_DET
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vNovoCod INTEGER;

BEGIN
       SELECT COALESCE(MAX(X.BDITEM13D) + 1, 1)
       FROM vrhf_emp_tverba13_det X
       WHERE X.BDCODEMP = NEW.BDCODEMP AND X.BDCODCOL = NEW.BDCODCOL AND X.BDREF13 = NEW.BDREF13 AND X.BDCODVER = NEW.BDCODVER AND NEW.BDORDEM = X.BDORDEM
       INTO
         :vNovoCod;

       NEW.BDITEM13D = vNovoCod;
END
^


create or alter procedure SP_CORRIGE_VINCULO_5002 (
    PREMPRESA varchar(30000),
    PRREFERENCIA integer)
as
declare variable WCODIGO integer;
declare variable WCODEMP integer;
declare variable WREFARQ integer;
declare variable WCODCOL integer;
declare variable WCODTER integer;
declare variable WXML blob sub_type 0 segment size 80;
declare variable WPOS integer;
declare variable WCPF varchar(14);
declare variable WCHAVEANT varchar(50);
declare variable WCODEMPNOVO integer;
declare variable WCODCOLNOVO integer;
declare variable WCODTERNOVO integer;
declare variable WLISTAEMP varchar(3000);
declare variable WEMPANT integer;
declare variable WSQL varchar(30000);
declare variable WSQLEMP varchar(30000);
begin
  /* Procedure Text */
--  suspend;
  wsqlemp = 'select bdcodemp from tempresas ar';
  if (coalesce(prempresa,'') <> '') then
     wsqlemp = wsqlemp||' where '||prempresa;

  for execute statement wsqlemp into wEMPANT do
    begin
      WCHAVEANT = '';
    --  wEMPANT = prempresa;
    
      wLISTAEMP = '';
    
      select first 1 coalesce(e.bdcodmatriz,e.bdcodemp) from tempresas e where e.bdcodemp = :wEMPANT into :wempant;
    
      for select e.bdcodemp from tempresas e
          where coalesce(e.bdcodmatriz,e.bdcodemp) = :wempant into :wempant do
        begin
          if (wLISTAEMP <> '') then
             wLISTAEMP = wLISTAEMP||',';
    
          wLISTAEMP = wLISTAEMP||''||wempant;
        end
    
      wcodigo = 0;
    
      wsql = ' select first 1 bdcodemp from VRH_EMP_TCORRIGE_5002_DOWN x '||
             ' where x.bdref = '||prreferencia||' and x.bdcodemp in ('||wlistaemp||')';
      execute statement wsql into :wcodigo;
    
      if (wcodigo = 0) then
         continue;
    
      wsql = 'select ar.bdcodigo, ar.bdcodemp,ar.bdrefarq,ar.bdcodcol,ar.bdcodter,unzipblob(xml.bdxml) '||
             ' from vrh_esocial_tarquivo ar '||
             ' join vrh_esocial_tarquivo_xml xml on (ar.bdcodigo = xml.bdcodigo and ar.bdcodemp = xml.bdcodemp) ' ||
             ' where ar.bdcodtipo = 41 and ar.bdmotivo = '''||'Importado do Download do eSocial'''||' and '||' ar.bdrefarq = '||prreferencia||
             ' and ar.bdcodemp in ('||wlistaemp||')';
    
    
      FOR execute statement wsql into :wcodigo, :wcodemp, :wrefarq, :wcodcol, :wcodter, :wxml do
      begin
        -- Encontro o CPF no XML
        wpos = position('<cpfTrab>',wxml);
        if (wPos = 0) then
           begin
             wpos = position('<cpfBenef>',wxml);

             if (wpos = 0) then
                continue;

             WCPF = substring(wxml from wpos+10 for 11);
           end
        else
           begin
             WCPF = substring(wxml from wpos+9 for 11);
           end


        WCPF = substring(WCPF from 1 for 3)||'.'||substring(WCPF from 4 for 3)||'.'||substring(WCPF from 7 for 3)||'-'||substring(WCPF from 10 for 2);
    
        if (wEMPANT <> wcodemp) then
           begin
             wLISTAEMP = '';
    
             select first 1 coalesce(e.bdcodmatriz,e.bdcodemp) from tempresas e where e.bdcodemp = :wcodemp into :wempant;
    
             for select e.bdcodemp from tempresas e
                 where coalesce(e.bdcodmatriz,e.bdcodemp) = :wempant into :wempant do
               begin
                 if (wLISTAEMP <> '') then
                    wLISTAEMP = wLISTAEMP||',';
    
                 wLISTAEMP = wLISTAEMP||''||wempant;
               end
           end
    
        if (WCHAVEANT <> wcpf||'.'||wrefarq||'.'||wcodemp) then
           begin
             wcodcolnovo = null;
             wcodternovo = null;
    
             select first 1 a.bdcodemp, a.bdcodcol, a.bdcodter from sp_esocial_tvinculo_fol_s1210(:wlistaemp,:wcodemp,null,null,:wrefarq,:wcpf,true) a into :WCODEMPNOVO,:wcodcolnovo,:wcodternovo;
           end
    
     if (WCODEMPNOVO <> wcodemp) then
     begin
             update vrh_esocial_tarquivo ar set ar.bdstatus = 7 where ar.bdcodigo = :wcodigo and ar.bdcodemp = :wcodemp;
           end
  else
        if ((coalesce(wcodcolnovo,0) > 0) and ((coalesce(wcodcolnovo,0) <> coalesce(wcodcol,0)) or ((coalesce(wcodternovo,0) <> coalesce(wcodter,0)))))  then
           begin
             if (coalesce(wcodternovo,0) <> 0) then
                update vrh_esocial_tarquivo ar set ar.bdcodcol = :wcodcolnovo,ar.bdcodter = :wcodternovo where ar.bdcodigo = :wcodigo and ar.bdcodemp = :wcodemp;
             else
                update vrh_esocial_tarquivo ar set ar.bdcodcol = :wcodcolnovo, ar.bdcodter = null where ar.bdcodigo = :wcodigo and ar.bdcodemp = :wcodemp;
           end
        else if (coalesce(wcodternovo,0) > 0) then
           begin
             update vrh_esocial_tarquivo ar set ar.bdcodcol = :wcodternovo,ar.bdcodter = :wcodternovo where ar.bdcodigo = :wcodigo and ar.bdcodemp = :wcodemp;
           end
        else if ((coalesce(wcodcolnovo,0) = 0) and (coalesce(wcodternovo,0) = 0)) then
           begin
             update vrh_esocial_tarquivo ar set ar.bdstatus = 7 where ar.bdcodigo = :wcodigo and ar.bdcodemp = :wcodemp;
           end
      end
    
      wsql = 'delete from VRH_EMP_TCORRIGE_5002_DOWN d where d.bdref = '||prreferencia||' and d.bdcodemp in ('||wLISTAEMP||')';
      execute statement wsql;
    end
end^

CREATE OR ALTER TRIGGER TFAQ_WEB_BI0 FOR TFAQ_WEB
ACTIVE BEFORE INSERT POSITION 0
AS
BEGIN
  IF ((NEW.bdid IS NULL) OR (NEW.bdid = 0)) THEN
  BEGIN
    NEW.bdid = (SELECT COALESCE(MAX(bdid), 0)+1 FROM tfaq_web);
  END
END
^

CREATE OR ALTER trigger tpedidos_bi_biu0 for tpedidos_bi
active before insert or update position 0
AS
begin
  if (INSERTING) then
    new.bdinclusao = localtimestamp;
  else
  if (new.bdpronto = 1 and new.bdconclusao is null) then
    new.bdconclusao = localtimestamp;
end
^


create or alter procedure VRH_SP_QUADRO_HORARIO (
    PREMP integer,
    PRCOL integer,
    PRREF integer,
    PRDATAINI date = null,
    PRDATAFIM date = null)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDDATA date,
    BDSEQUENCIAL integer,
    BDENTRADA time,
    BDSAIDA time,
    bdPrimeiroDiaFechamento integer)
as
declare variable WCODPQUA integer;
declare variable WCODQH integer;
declare variable WDATADADODIARIO date;
declare variable WDIASEMANA integer;
declare variable WDIAFECHAMENTO integer;
declare variable WDIAINI integer;
declare variable WMESINI integer;
declare variable WANOINI integer;
declare variable WDIAFIM integer;
declare variable WMESFIM integer;
declare variable WANOFIM integer;
begin
  /* Procedure Text */
--  suspend;
  -- Busca o hor?rio do dia anterior ao solicitado pois ser? necess?rio fazer tratamento para

  if (prref is not null) then
     begin
       if ((prdataini is null) or (prdatafim is null)) then
          begin
            -- Monta os dias atravez do fechamento
            EXECUTE PROCEDURE sp_seta_competencia(prref,NULL,NULL);
            select BDFECHAMESEMP from VW_VRHF_BASE_TEMPCALC where bdcodemp = :premp into :WDIAFECHAMENTO;

            IF ((WDIAFECHAMENTO >= 28) OR (WDIAFECHAMENTO IS NULL) OR (WDIAFECHAMENTO <= 1)) THEN
               begin
                  wdiaini = 1;
                  wmesini = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
                  wmesfim = wmesini;
                  wanoini = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
                  wanofim =  wanoini;
                  SELECT ULTDIA FROM ultimo_dia_mes(:wmesfim,:wanofim) INTO wdiafim;
              end
            else
              begin
                wdiaini = WDIAFECHAMENTO + 1;
                wdiafim = WDIAFECHAMENTO;
                wmesfim = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 5 FOR 2) AS INTEGER);
                wanofim = CAST(SUBSTRING(CAST(prref AS VARCHAR(6)) FROM 1 FOR 4) AS INTEGER);
        
                IF (wmesfim = 1) THEN
                   begin
                     wmesini = 12;
                     wanoini = wanofim - 1;
                   end
                else
                   begin
                      wmesini = wmesfim - 1;
                      wanoini = wanofim;
                   end
              end

            bdPrimeiroDiaFechamento = wdiaini;

            prdataini = CAST(''||wmesini||'-'||wdiaini||'-'||wanoini AS DATE);
            if (wdiafim is not null) then
               prdatafim = CAST(''||wmesfim||'-'||wdiafim||'-'||wanofim AS DATE);
            else
               prdatafim = DateAdd(month, 1, prdatafim);
          end
     end

  prdataini = prdataini -1;

  WDATADADODIARIO = null;
  bdcodemp = premp;
  bdcodcol = prcol;

  while (prdatafim >= prdataini) do
    begin
      if ((WDATADADODIARIO is null) or (WDATADADODIARIO > prdatafim)) then
         begin
           wdatadadodiario = null;
           select first 1 a.bddatacol,a.bdcodqh, a.bdcodpqua from VRH_EMP_TCOL_VINCDIA a
           where a.bdcodemp = :premp and a.bdcodcol = :prcol
           order by a.bddatacol desc into :wdatadadodiario,:wcodqh, :wcodpqua;

           -- Quando n?o encontra nenhum dado anterior deve usar o posterior
           if (wdatadadodiario is null) then
              begin
                wdatadadodiario = prdataini;
                select first 1 a.bdcodqh, a.bdcodpqua from VRH_EMP_TCOL_VINCDIA a
                where a.bdcodemp = :premp and a.bdcodcol = :prcol
                order by a.bddatacol into :wcodqh, :wcodpqua;
              end
         end

      --    EXTRACT(WEEKDAY FROM data)
        --0 = Domingo
        --1 = Segunda-feira
        --2 = Ter?a-feira
        --3 = Quarta-feira
        --4 = Quinta-feira
        --5 = Sexta-feira
        --6 = S?bado
     WDIASEMANA = EXTRACT(WEEKDAY FROM prdatafim);
--     if (wdiasemana = 0) then
--        wdiasemana = 7;

     bddata = prdatafim;
     bdsequencial = null;
     bdentrada = null;
     bdsaida = null;

     FOR select QHHORAS.bdcodqhhs,QHHORAS.bdqhhsent,QHHORAS.bdqhhssai
     from VRH_BASE_TQH_DIAS TQH
     left outer join VRH_BASE_TQH_HORARIO QHHORARIO on (QHHORARIO.BDCODQHH = TQH.BDCODQHH)
     left outer join VRH_BASE_TQH_HORAS QHHORAS on (QHHORAS.BDCODQHH = QHHORARIO.BDCODQHH)
     left outer join VRH_BASE_TQH TQHO on (TQHO.BDCODPQUA = TQH.BDCODPQUA) and (TQHO.BDCODQH = TQH.BDCODQH)
     where tqh.bdcodpqua = :wcodpqua and tqh.bdcodqh = :wcodqh and TQH.bddiasemqh = :wdiasemana
     into :bdsequencial,:bdentrada,:bdsaida do
       suspend;

      prdatafim = prdatafim - 1;
    end


end
^

create or alter procedure SP_GET_VINC5002 (
    PRSESSAO integer,
    PRCODEMP integer,
    PRMULTIEMPS varchar(5000))
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODTER integer,
    BDREFARQ integer,
    BDCPF varchar(14))
as
declare variable WCOUNTCAD integer;
declare variable WPRECISAFAZER boolean;
declare variable WCPFANT varchar(14);
declare variable WSQL varchar(5000);
begin
  /* Procedure Text */
  wcpfant = '';
  wCountCad =0;
  wPrecisaFazer =  True;
  for  select BDCPF, BDREFARQ
    from VRH_TEMP_VINC_5002
    where bdsessao = :prsessao
    into   :BDCPF, :BDREFARQ do
  begin
    if (wcpfant<>:BDCPF) then
       begin
         wcpfant = :BDCPF;
         wCountCad = 0;
         wPrecisaFazer = True;
         wsql = 'Select count(*) from(Select * from ( ' ||
         'select bdcodcol ,0 bdcodter ' ||
         'from VRH_EMP_TCOLCON ' ||
         'where bdcodemp in ('|| (:prmultiemps)|| ') and BDCPFCOL = '''||:BDCPF||''' ' ||
         'union all ' ||
         'select   0,bdcodter ' ||
         'from TTERCEIRO_RH RH ' ||
         'where RH.BDCPFMEITER = '''||:BDCPF||''' ' ||
         'union all ' ||
         'select  0, bdcodter ' ||
         'from TTERCEIRO C ' ||
         'where C.BDCGCTER = '''||:BDCPF||''')  ' ||
         'group by  bdcodcol,bdcodter)';

         execute statement wSql into :wcountcad;

       end
    if ((wPrecisaFazer) or (wCountCad>1))  then
       begin
      wPrecisaFazer = False;
         select BDCODEMP, BDCODCOL, BDCODTER
         from SP_ESOCIAL_TVINCULO_FOL_S1210(:PRMULTIEMPS, :PRCODEMP, NULL, null, :BDREFARQ, :BDCPF, TRUE)
         into  :BDCODEMP, :BDCODCOL, :BDCODTER;
       end
    suspend;
  end
  delete from VRH_TEMP_VINC_5002 where bdsessao = :prsessao;
end^

CREATE OR ALTER TRIGGER VRH_EMP_TDEP_REF_AI0 FOR VRH_EMP_TDEP_REF
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
declare variable WDATAENTRADA DATE;
declare variable WREFENTRADA INTEGER;
declare variable WEXISTE INTEGER;
declare variable wExisteRegistroEntrada integer;
begin
  /* Trigger text */
  WDATAENTRADA = NULL;

  SELECT BDDATAENTREDPN FROM VRH_EMP_TDEP
  WHERE BDCODEMP = NEW.BDCODEMP AND
        BDCODCOL = NEW.BDCODCOL AND
        BDCODDPN = NEW.BDCODDPN
  INTO :WDATAENTRADA;

  IF ((:WDATAENTRADA IS NOT NULL) and (new.bdrefdpn <> :wrefentrada)) THEN
     begin
       WREFENTRADA = 0;
       SELECT BDAAAAMM FROM AAAAMM(:WDATAENTRADA) INTO :WREFENTRADA;

       wExisteRegistroEntrada = null;
       SELECT FIRST 1 BDREFDPN FROM VRH_EMP_TDEP_REF
       WHERE BDCODEMP = NEW.BDCODEMP AND
             BDCODCOL = NEW.BDCODCOL AND
             BDCODDPN = NEW.BDCODDPN and
             bdrefdpn = :wrefentrada
       INTO :wExisteRegistroEntrada;

       if ((WREFENTRADA < new.bdrefdpn) and (wExisteRegistroEntrada is null)) then
          begin
            WEXISTE = null;
            SELECT FIRST 1 BDREFDPN FROM VRH_EMP_TDEP_REF
            WHERE BDCODEMP = NEW.BDCODEMP AND
                  BDCODCOL = NEW.BDCODCOL AND
                  BDCODDPN = NEW.BDCODDPN
            order by bdrefdpn
            INTO :WEXISTE;


             if ((COALESCE(WEXISTE, 0) > 0) and (wexiste <> new.bdrefdpn) and (WREFENTRADA <> wexiste)) then
               begin
                 INSERT INTO VRH_EMP_TDEP_REF
                 (BDCODEMP, BDCODCOL, BDCODDPN, BDREFDPN, BDPARENESCODPN, BDNOMEDPN, BDDATANASCDPN, BDCPFDPN, BDINVALIDODPN, BDCONVMEDDPN, BDSALFAMDPN, BDDEPIRDPN, BDDESCRDEPDPN)
                 SELECT FIRST 1 BDCODEMP, BDCODCOL, BDCODDPN, :WREFENTRADA, BDPARENESCODPN, BDNOMEDPN, BDDATANASCDPN, BDCPFDPN, BDINVALIDODPN, BDCONVMEDDPN, BDSALFAMDPN, BDDEPIRDPN, BDDESCRDEPDPN
                 FROM VRH_EMP_TDEP_REF
                 WHERE BDCODEMP = NEW.BDCODEMP AND
                       BDCODCOL = NEW.BDCODCOL AND
                       BDCODDPN = NEW.BDCODDPN AND
                       BDREFDPN = :WEXISTE;
               end
          end
     end

end
^

CREATE OR ALTER TRIGGER VRH_EMP_TDEP_AU0 FOR VRH_EMP_TDEP
ACTIVE AFTER UPDATE POSITION 0
AS
declare variable WREFENTRADA INTEGER;
declare variable WEXISTE INTEGER;
begin
  /* Trigger text */
  IF ((NEW.BDDATAENTREDPN IS NOT NULL) AND ((OLD.BDDATAENTREDPN IS NULL) OR (NEW.BDDATAENTREDPN <> OLD.BDDATAENTREDPN))) THEN
     BEGIN
       WREFENTRADA = 0;
       SELECT BDAAAAMM FROM AAAAMM(NEW.BDDATAENTREDPN)
       INTO :WREFENTRADA;

       if (COALESCE(:WREFENTRADA, 0) > 0) then
          begin
            WEXISTE = 0;
            SELECT FIRST 1 BDREFDPN FROM VRH_EMP_TDEP_REF
            WHERE BDCODEMP = NEW.BDCODEMP AND
                  BDCODCOL = NEW.BDCODCOL AND
                  BDCODDPN = NEW.BDCODDPN AND
                  BDREFDPN <= :WREFENTRADA
            INTO :WEXISTE;

            IF (COALESCE(WEXISTE, 0) <= 0) THEN
               begin
                 WEXISTE = 0;
                 SELECT FIRST 1 BDREFDPN
                 FROM VRH_EMP_TDEP_REF
                 WHERE BDCODEMP = NEW.BDCODEMP AND
                       BDCODCOL = NEW.BDCODCOL AND
                       BDCODDPN = NEW.BDCODDPN
                 INTO :WEXISTE;

                 if (COALESCE(WEXISTE, 0) > 0) then
                    INSERT INTO VRH_EMP_TDEP_REF
                    (BDCODEMP, BDCODCOL, BDCODDPN, BDREFDPN, BDPARENESCODPN, BDNOMEDPN, BDDATANASCDPN, BDCPFDPN, BDINVALIDODPN, BDCONVMEDDPN, BDSALFAMDPN, BDDEPIRDPN, BDDESCRDEPDPN)
                    SELECT FIRST 1 BDCODEMP, BDCODCOL, BDCODDPN, :WREFENTRADA, BDPARENESCODPN, BDNOMEDPN, BDDATANASCDPN, BDCPFDPN, BDINVALIDODPN, BDCONVMEDDPN, BDSALFAMDPN, BDDEPIRDPN, BDDESCRDEPDPN
                    FROM VRH_EMP_TDEP_REF
                    WHERE BDCODEMP = NEW.BDCODEMP AND
                          BDCODCOL = NEW.BDCODCOL AND
                          BDCODDPN = NEW.BDCODDPN
                    ORDER BY BDREFDPN;
               end
          end
     END
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TTERC_TDEP_REF_AIU0 FOR VRH_BASE_TTERC_TDEP_REF
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
declare variable WDATAENTRADA DATE;
declare variable WREFENTRADA INTEGER;
declare variable WEXISTE INTEGER;
begin
  /* Trigger text */
  WDATAENTRADA = NULL;

  SELECT BDDATAENTREDPNTERC FROM VRH_BASE_TTERC_TDEP
  WHERE BDCODTER = NEW.BDCODTER AND
        BDCODDPNTERC = NEW.BDCODDPNTERC
  INTO :WDATAENTRADA;

  IF (:WDATAENTRADA IS NOT NULL) THEN
     BEGIN
       WREFENTRADA = 0;
       SELECT BDAAAAMM FROM AAAAMM(:WDATAENTRADA)
       INTO :WREFENTRADA;

       if (COALESCE(:WREFENTRADA, 0) > 0) then
          begin
            WEXISTE = 0;
            SELECT FIRST 1 BDREFDPN FROM VRH_BASE_TTERC_TDEP_REF
            WHERE BDCODTER = NEW.BDCODTER AND
                  BDCODDPNTERC = NEW.BDCODDPNTERC AND
                  BDREFDPN <= :WREFENTRADA
            INTO :WEXISTE;

            IF (COALESCE(WEXISTE, 0) <= 0) THEN
               begin
                 WEXISTE = 0;

                 SELECT FIRST 1 BDREFDPN
                 FROM VRH_BASE_TTERC_TDEP_REF
                 WHERE BDCODTER = NEW.BDCODTER AND
                       BDCODDPNTERC = NEW.BDCODDPNTERC
                 INTO :WEXISTE;

                 if (COALESCE(WEXISTE, 0) > 0) then
                    INSERT INTO VRH_BASE_TTERC_TDEP_REF
                    (BDCODTER, BDCODDPNTERC, BDREFDPN, BDDATANASCDPNTERC, BDPARENESCODPNTERC, BDINVALIDODPNTERC, BDCPFDPNTERC, BDNOMEDPNTERC, BDDESCRDEPTERC)
                    SELECT FIRST 1 BDCODTER, BDCODDPNTERC, :WREFENTRADA, BDDATANASCDPNTERC, BDPARENESCODPNTERC, BDINVALIDODPNTERC, BDCPFDPNTERC, BDNOMEDPNTERC, BDDESCRDEPTERC
                    FROM VRH_BASE_TTERC_TDEP_REF
                    WHERE BDCODTER = NEW.BDCODTER AND
                          BDCODDPNTERC = NEW.BDCODDPNTERC
                    ORDER BY BDREFDPN;
               end
          end
     END
end
^

CREATE OR ALTER TRIGGER VRH_BASE_TTERC_TDEP_AU0 FOR VRH_BASE_TTERC_TDEP
ACTIVE AFTER UPDATE POSITION 0
AS
declare variable WREFENTRADA INTEGER;
declare variable WEXISTE INTEGER;
begin
  /* Trigger text */
  IF ((NEW.BDDATAENTREDPNTERC IS NOT NULL) AND ((OLD.BDDATAENTREDPNTERC IS NULL) OR (NEW.BDDATAENTREDPNTERC <> OLD.BDDATAENTREDPNTERC))) THEN
     BEGIN
       WREFENTRADA = 0;
       SELECT BDAAAAMM FROM AAAAMM(NEW.BDDATAENTREDPNTERC)
       INTO :WREFENTRADA;

       if (COALESCE(:WREFENTRADA, 0) > 0) then
          begin
            WEXISTE = 0;
            SELECT FIRST 1 BDREFDPN FROM VRH_BASE_TTERC_TDEP_REF
            WHERE BDCODTER = NEW.BDCODTER AND
                  BDCODDPNTERC = NEW.BDCODDPNTERC AND
                  BDREFDPN <= :WREFENTRADA
            INTO :WEXISTE;

            IF (COALESCE(WEXISTE, 0) <= 0) THEN
               begin
                 WEXISTE = 0;
                 SELECT FIRST 1 BDREFDPN
                 FROM VRH_BASE_TTERC_TDEP_REF
                 WHERE BDCODTER = NEW.BDCODTER AND
                       BDCODDPNTERC = NEW.BDCODDPNTERC
                 INTO :WEXISTE;

                 if (COALESCE(WEXISTE, 0) > 0) then
                    INSERT INTO VRH_BASE_TTERC_TDEP_REF
                    (BDCODTER, BDCODDPNTERC, BDREFDPN, BDDATANASCDPNTERC, BDPARENESCODPNTERC, BDINVALIDODPNTERC, BDCPFDPNTERC, BDNOMEDPNTERC, BDDESCRDEPTERC)
                    SELECT FIRST 1 BDCODTER, BDCODDPNTERC, :WREFENTRADA, BDDATANASCDPNTERC, BDPARENESCODPNTERC, BDINVALIDODPNTERC, BDCPFDPNTERC, BDNOMEDPNTERC, BDDESCRDEPTERC
                    FROM VRH_BASE_TTERC_TDEP_REF
                    WHERE BDCODTER = NEW.BDCODTER AND
                          BDCODDPNTERC = NEW.BDCODDPNTERC
                    ORDER BY BDREFDPN;
               end
          end
     END
end
^


create or alter procedure SP_EMP_PUXAR_MATRIZ_FILIAIS (
    PRCODEMP integer)
returns (
    BDCODEMP integer)
as
declare variable BDCODMATRIZ integer;
declare variable BDCODFILIAL integer;
begin
    FOR select coalesce(e.BDCODMATRIZ, E.BDCODEMP)
        from TEMPRESAS e
        where e.BDCODEMP = :PRCODEMP
        and (coalesce(e.BDCODMATRIZ, E.BDCODEMP) not in (SELECT BDCODEMP FROM tmp_empresas_select))
        INTO :BDCODMATRIZ
    DO
    begin
        BDCODEMP = :BDCODMATRIZ;
        suspend;

        FOR select BDCODEMP from TEMPRESAS
            where BDCODMATRIZ = :BDCODMATRIZ
            and (BDCODEMP not in (SELECT BDCODEMP FROM tmp_empresas_select))
            INTO :BDCODFILIAL
        DO
        begin
            BDCODEMP = :BDCODFILIAL;
            suspend;
        end
    end
end^


create or alter procedure SP_VRH_EXTRATO_DIRF (
    PRCODEMP varchar(30000),
    PRREF integer,
    PRFILTROCPF varchar(30000))
returns (
    BDCODEMPORD integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDCOLTER integer,
    BDCONTRCOL integer,
    BDGRUPOCLA integer,
    BDNOMCOL varchar(70),
    BDCPFCOL varchar(18),
    BDCNPJEMP varchar(18),
    BDNOMEMP varchar(100),
    BDBASEIRRF numeric(18,6),
    BDBASEIRRF13 numeric(18,6),
    BDVALORIRRF numeric(18,6),
    BDVALORIRRF13 numeric(18,6),
    BDVALORINSS numeric(18,6),
    BDVALORINSS13 numeric(18,6),
    BDTIPO integer,
    BDCALCULOS integer,
    BDCOUNTFC integer,
    BDCATEGORIAESOCIAL integer,
    BDCODCLATRI integer,
    BDTAGSTR varchar(10000),
    BDDESCRICAOFOLHA varchar(10000),
    BDTIPOCALCULO integer,
    BDAJCUSTOS numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDBOLSAMEDICO13 numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDJUROSMORA13 numeric(18,6),
    BDUNICO integer,
    BDCODREC varchar(6))
as
declare variable WI integer;
declare variable WREF integer;
declare variable WREFINI integer;
declare variable WREFFIM integer;
declare variable WSQL varchar(30000);
declare variable WWHERERT varchar(30000);
begin

  if (PRREF <= 9999) then
     begin
       WREFINI = (PRREF * 100) + 1;
       WREFFIM = (PRREF * 100) + 12;
     end
  else
     begin
       WREFINI = PRREF;
       WREFFIM = PRREF;
     end

      for select
            BDREF, BDCODEMPORD, BDCODEMP, BDCODCOL, BDCOLTER, BDCONTRCOL, BDGRUPOCLA, BDNOMCOL, BDCPFCOL, BDCNPJEMP, BDNOMEMP, BDBASEIRRF, BDVALORIRRF, BDVALORINSS, BDTIPO, BDCALCULOS,
            BDCOUNTFC, BDCATEGORIAESOCIAL, BDCODCLATRI, BDTAGSTR, BDDESCRICAOFOLHA, BDTIPOCALCULO, BDAJCUSTOS, BDINDRESC, BDVALABO, BDRENDISENTOS, BDDRENDISENTOS, BDAUXILIOMORADIA, BDDIARIA,
            BDBOLSAMEDICO, BDJUROSMORA, 0 BDJUROSMORA13, BDUNICO, BDCODREC
          from SP_REL_TOT_5002_DIRF(:PRCODEMP,:wrefini,:prfiltrocpf,1,1,1,0,:wreffim)
          where BDUNICO = 1
          into
            :bdref, :BDCODEMPORD, :BDCODEMP, :BDCODCOL, :BDCOLTER, :BDCONTRCOL, :BDGRUPOCLA, :BDNOMCOL, :BDCPFCOL, :BDCNPJEMP, :BDNOMEMP, :BDBASEIRRF, :BDVALORIRRF, :BDVALORINSS, :BDTIPO, :BDCALCULOS,
            :BDCOUNTFC, :BDCATEGORIAESOCIAL, :BDCODCLATRI, :BDTAGSTR, :BDDESCRICAOFOLHA, :BDTIPOCALCULO, :BDAJCUSTOS, :BDINDRESC, :BDVALABO, :BDRENDISENTOS, :BDDRENDISENTOS, :BDAUXILIOMORADIA, :BDDIARIA,
            :BDBOLSAMEDICO, :BDJUROSMORA, :BDJUROSMORA13, :BDUNICO, :BDCODREC
      do
        begin
          BDBASEIRRF13  = 0;
          BDVALORIRRF13 = 0;
          BDVALORINSS13 = 0;

          if (bdtipocalculo = 2) then
             begin
               BDBASEIRRF13  = :BDBASEIRRF;
               BDVALORIRRF13 = :BDVALORIRRF;
               BDVALORINSS13 = :BDVALORINSS;
               BDBOLSAMEDICO13 = :BDBOLSAMEDICO;

               BDBASEIRRF    = 0;
               BDVALORIRRF   = 0;
               BDVALORINSS   = 0;
               BDBOLSAMEDICO = 0;

               bdtipocalculo = 1;
             end
          --BDDRENDISENTOS = BDDRENDISENTOS||' '||:bddrendisentos;

          if (BDCOLTER = 1) then
            UPDATE OR INSERT INTO  TEMP_FILTRO_CPF_COLTER_REL (BDCPF, BDEHCOL) VALUES (:BDCPFCOL, 1);
          else
          if (BDCOLTER = 2) then
              UPDATE OR INSERT INTO  TEMP_FILTRO_CPF_COLTER_REL (BDCPF, BDEHTER) VALUES (:BDCPFCOL, 1);

          suspend;
        end
----      WI = WI + 1;
--    END
--

  delete from TEMP_FILTRO_COLCON_REL;

  wsql = 'INSERT INTO TEMP_FILTRO_COLCON_REL (BDCOMP,BDCODEMP,BDCODCOL,BDCODTER,BDCPF) '||
         'SELECT '||''''||'EDCPFCOL'||''''||', FOL.bdcodemp, COALESCE(FOL.BDCODCOL,0), 0 BDCODTER, FOL.bdcpfcol '||
         'FROM VRH_EMP_TRECLAMATORIA FOL ';
    
  wwherert = '';
    
  if (coalesce(prcodemp, '') <> '') then
    begin
      if (position('TMP_EMPRESAS_SELECT', prcodemp) > 0) then
        begin
          wsql = wsql || prcodemp || ' SLC ON (SLC.BDCODEMP = FOL.BDCODEMP) ';
        end
      else
        begin
          wwherert = wwherert || prcodemp;
        end
    end

    if (coalesce(prFiltroCPF, '') <> '') then
      begin
        if (wwherert <> '') then
            wwherert = wwherert || ' AND ';
        wwherert = wwherert || prFiltroCPF;
      end

    if (wwherert <> '') then
        wsql = wsql || ' WHERE ' || wwherert;

  execute statement wsql;


  for select coalesce(EMP.BDCODMATRIZ, RT.BDCODEMP) BDCODEMPORD, RT.BDCODEMP, RT.BDCODCOL, null BDCOLTER, null BDCONTRCOL,
             null BDGRUPOCLA, RT.BDNOMCOL, RT.BDCPF BDCPFCOL, EMP.BDCNPJEMP, EMPRF.BDNOMEMP, RT.BDIRRFMENSAL as BDBASEIRRF,
             RT.BDIRRFDECIMOTERC as BDBASEIRRF13,RT.BDVALORIRRF13,RT.BDVALORIRRF, RT.BDPREVIDENCIAOFICIAL as BDVALORINSS,
             RT.BDPREVIDENCIAOFICIAL13 as BDVALORINSS13,null BDTIPO, null BDCALCULOS, null BDCOUNTFC,
             null BDCATEGORIAESOCIAL, null BDCODCLATRI, null BDTAGSTR, null BDDESCRICAOFOLHA, 1 BDTIPOCALCULO,
             null BDAJCUSTOS, null BDINDRESC, null BDVALABO, RT.BDRENDNAPTRIBUT BDRENDISENTOS,
             RT.BDDESCRENDNAOTRIBUT BDDRENDISENTOS, null BDAUXILIOMORADIA, null BDDIARIA, null BDBOLSAMEDICO, null BDBOLSAMEDICO13,
             RT.BDJUROSMORA as BDJUROSMORA, RT.BDJUROSMORA13, 1 BDUNICO, RT.BDCODRECEITAESOC BDCODREC, RT.BDREFPGTO
      from SP_VRHF_DADOS_IR_RT('', 'TEMP_FILTRO_COLCON_REL', :wrefini, :wreffim) RT
      join TEMPRESAS EMP on (EMP.BDCODEMP = RT.BDCODEMP)
      join TEMPRESAS_REF EMPRF on (EMPRF.BDCODEMP = RT.BDCODEMP and EMPRF.BDREFEMP = (select first 1 BDREFEMP from TEMPRESAS_REF E where E.BDCODEMP = RT.BDCODEMP and E.BDREFEMP <= RT.BDREFPGTO order by BDREFEMP desc))
  into
      :BDCODEMPORD, :BDCODEMP, :BDCODCOL, :BDCOLTER, :BDCONTRCOL, :BDGRUPOCLA, :BDNOMCOL, :BDCPFCOL, :BDCNPJEMP, :BDNOMEMP, :BDBASEIRRF,:BDBASEIRRF13,:BDVALORIRRF13, :BDVALORIRRF, :BDVALORINSS,:BDVALORINSS13, :BDTIPO, :BDCALCULOS,
      :BDCOUNTFC, :BDCATEGORIAESOCIAL, :BDCODCLATRI, :BDTAGSTR, :BDDESCRICAOFOLHA, :BDTIPOCALCULO, :BDAJCUSTOS, :BDINDRESC, :BDVALABO, :BDRENDISENTOS, :BDDRENDISENTOS, :BDAUXILIOMORADIA, :BDDIARIA,
      :BDBOLSAMEDICO,:BDBOLSAMEDICO13, :BDJUROSMORA, :BDJUROSMORA13, :BDUNICO, :BDCODREC,:BDREF
  do
    begin

      UPDATE OR INSERT INTO  TEMP_FILTRO_CPF_COLTER_REL (BDCPF, BDEHCOL) VALUES (:BDCPFCOL, 1);

      SUSPEND;
    end


end^

create or alter procedure SP_VRH_GETCODRECEITA_5002 (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRTERCEIRO integer,
    PRTIPOFOLHA integer,
    PRTIPOCALCULO integer,
    PRCODCLATRI integer)
returns (
    BDCODREC varchar(6))
as
declare variable WCATEGESOCIAL integer;
declare variable WRRA boolean;
declare variable WRESIDEXT boolean;
declare variable WCLASSTRIB integer;
declare variable WCODPAIS integer;
declare variable WDATARESC date;
begin
  WCATEGESOCIAL = 0;
  WRRA = false;
  WRESIDEXT = false;
  WCLASSTRIB = 0;
  WCODPAIS = 0;
  WDATARESC = null;

  if (PRTERCEIRO = 1) then
  begin
    select GPS.BDCATEGORIAESOCIAL, RES.BDDATARESCISAO
    from VRHF_EMP_TCOLCON_FGTSGPS GPS
    left outer join VRH_EMP_TRESCISAO RES on (RES.BDCODEMP = GPS.BDCODEMP and
          RES.BDCODCOL = GPS.BDCODCOL)
    where GPS.BDCODEMP = :PRCODEMP and
          GPS.BDCODCOL = :PRCODCOL and
          GPS.BDREFCOL = coalesce((select first 1 B.BDREFCOL
                             from VRHF_EMP_TCOLCON_FGTSGPS B
                             where B.BDCODEMP = GPS.BDCODEMP AND
                                   B.BDCODCOL = GPS.BDCODCOL and
                                   B.BDREFCOL <= :PRREF
                             order by B.BDREFCOL desc), (select first 1 B.BDREFCOL
                                                       from VRHF_EMP_TCOLCON_FGTSGPS B
                                                       where B.BDCODEMP = GPS.BDCODEMP AND
                                                             B.BDCODCOL = GPS.BDCODCOL and
                                                             B.BDREFCOL > :PRREF
                                                       order by B.BDREFCOL))
    into :WCATEGESOCIAL, :WDATARESC;


    select COALESCE(CAD.BDCODPAISRES, 30) --se nao tiver busca 30 = Brasil
    from VRH_EMP_TCOLCON_CAD CAD
    where CAD.BDCODEMP = :PRCODEMP and
          CAD.BDCODCOL = :PRCODCOL
        and CAD.BDREFCOL = coalesce((select first 1 B.BDREFCOL
                             from VRH_EMP_TCOLCON_CAD B
                             where B.BDCODEMP = CAD.BDCODEMP AND
                                   B.BDCODCOL = CAD.BDCODCOL and
                                   B.BDREFCOL <= :PRREF
                             order by B.BDREFCOL desc), (select first 1 B.BDREFCOL
                                                       from VRH_EMP_TCOLCON_CAD B
                                                       where B.BDCODEMP = CAD.BDCODEMP AND
                                                             B.BDCODCOL = CAD.BDCODCOL and
                                                             B.BDREFCOL > :PRREF
                                                       order by B.BDREFCOL))
    into :WCODPAIS ;
  end
  else
  begin
    select  GPS.BDCATEGORIAESOCIAL
    from  VRHF_BASE_TTERC_FGTSGPS GPS
    where GPS.BDCODTER = :PRCODCOL
       AND GPS.BDREFTERC = coalesce((select first 1 B.BDREFTERC
                             from VRHF_BASE_TTERC_FGTSGPS B
                             where B.BDCODTER = :PRCODCOL and
                                   B.BDREFTERC <= :PRREF
                             order by BDREFTERC desc), (select first 1 B.BDREFTERC
                                                       from VRHF_BASE_TTERC_FGTSGPS B
                                                       where B.BDCODTER = :PRCODCOL and
                                                             B.BDREFTERC > :PRREF
                                                       order by BDREFTERC))
    into :WCATEGESOCIAL;

    select COALESCE(RF.BDCODPAISRES, 30)  --se nao tiver busca 30 = Brasil
    from  TTERCEIRO_REF RF
    where RF.BDCODTER = :PRCODCOL
       AND RF.BDREFEMP =  coalesce((select first 1 B.BDREFEMP
                             from TTERCEIRO_REF B
                             where B.BDCODTER = :PRCODCOL and
                                   B.BDREFEMP <= :PRREF and
                                   b.bdcodpaisres is not null
                             order by B.BDREFEMP desc), (select first 1 B.BDREFEMP
                                                       from TTERCEIRO_REF B
                                                       where B.BDCODTER = :PRCODCOL and
                                                             B.BDREFEMP > :PRREF and
                                                             b.bdcodpaisres is not null
                                                       order by B.BDREFEMP))
    into :WCODPAIS;
  end

  WRRA       = (PRTIPOCALCULO = 4);
  WRESIDEXT  = (WCODPAIS <> 30);
  WCLASSTRIB = PRCODCLATRI;

  -- 056111
  if ((PRTIPOFOLHA in (0, 9000, 2, 9020, 1, 9010)) and --FN,FT,FAD,COMPFN,COMPFT
      (WCATEGESOCIAL in (101, 102, 103, 105, 106, 107, 108, 111, 201, 202)) and
      (not WRRA) and
      (not WRESIDEXT) and
      (WCLASSTRIB = 22)) then
  begin
    BDCODREC = '056111';
    suspend;
    exit;
  end

  -- 056112
  if ((PRTIPOFOLHA in (10, 9100, 9, 9099, 11, 9110)) and --F13,FAD13,FC13
      (WCATEGESOCIAL in (101, 102, 103, 105, 106, 107, 108, 111, 201, 202)) and
      (not WRRA) and
      (not WRESIDEXT) and
      (WCLASSTRIB = 22)) then
  begin
    BDCODREC = '056112';
    suspend;
    exit;
  end

  -- 056113
  if ((WDATARESC <> null) and
      (WCATEGESOCIAL in (101, 102, 103, 105, 106, 107, 108, 111, 201, 202)) and
      (not WRRA) and
      (not WRESIDEXT) and
      (WCLASSTRIB = 22)) then
  begin
    BDCODREC = '056113';
    suspend;
    exit;
  end

  -- 058806
  if ((WCATEGESOCIAL in (201, 202, 701, 711, 712, 731, 734, 738, 741, 751,761, 771, 781)) and
      (not WRRA) and
      (not WRESIDEXT)) then
  begin
    BDCODREC = '058806';
    suspend;
    exit;
  end

  -- 061001
  if ((WCATEGESOCIAL = 712) and
      (WCODPAIS = 586)) then
  begin
    BDCODREC = '061001';
    suspend;
    exit;
  end

  -- 356201
  if ((PRTIPOFOLHA in (50, 9500)) and -- FA
      (PRTIPOCALCULO = 3) and
      (WCATEGESOCIAL between 100 and 199) and
      (not WRRA) and
      (not WRESIDEXT)) then
  begin
    BDCODREC = '356201';
    suspend;
    exit;
  end

  -- 188901
  if ((not WRESIDEXT) and
      (WRRA)) then
  begin
    BDCODREC = '188901';
    suspend;
    exit;
  end

  -- 056107
  if ((WCATEGESOCIAL in (101, 102, 103, 105, 106, 107, 108, 111, 201, 202,
                        301, 302, 303, 304, 305, 306, 307, 308, 309, 310,
                        311, 312, 313, 314, 401, 410, 501, 721, 722, 723,
                        901, 902, 903, 904, 906)) and
      (not WRRA) and
      (not WRESIDEXT) and
      (WCLASSTRIB <> 22)) then
  begin
    BDCODREC = '056107';
    suspend;
    exit;
  end

  -- 047301
  if (WRESIDEXT) then
  begin
    BDCODREC = '047301';
    suspend;
    exit;
  end

  BDCODREC = null;
  suspend;

end^

create or alter procedure SP_REL_TOT_5002_RRA (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRUNICO integer,
    PRTAGSTR varchar(100),
    PRDESCRICAOFOLHA varchar(1000),
    PRCODEMPORD integer,
    PRCODACCONV integer,
    PRQTDMESESRRA numeric(16,0))
as
declare variable WCODEMP integer;
declare variable WCPFCOL varchar(14);
declare variable WCODACCONV integer;
declare variable WTIPOPROCESSO integer;
declare variable WNUMPROCESSO varchar(21);
declare variable WDESCRRA varchar(50);
declare variable WTOTALDESPJDC numeric(18,6);
declare variable WEMPADV integer;
declare variable WCODACCONADV integer;
declare variable WCNPJADV varchar(18);
declare variable WVALORPAGOADV numeric(9,2);
BEGIN
  /* Procedure Text */
  wcpfcol = '';
  select first 1 doc.bdcpfcol from vrh_emp_tcolcon_doc doc where doc.bdcodemp = :prcodemp and doc.bdcodcol = :prcodcol into :WCPFCOL;

  if (COALESCE(PRUNICO, 0) = 1) then
     BEGIN
        FOR
            SELECT ADC.BDCODEMP,ADC.BDCODACCONV,ADC.BDTIPOPROCESSO,ADC.BDNUMPROCESSO,ADC.BDDESCRRA,ADC.BDTOTALDESPJDC FROM VRH_EMP_TACCONV ADC
            WHERE ADC.BDCODEMP = :PRCODEMP AND ADC.BDCODACCONV = :PRCODACCONV
        INTO :WCODEMP,:WCODACCONV,:WTIPOPROCESSO,:WNUMPROCESSO,:WDESCRRA,:WTOTALDESPJDC
        DO
        BEGIN
          UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRRA5002
          (BDSESSAO,BDCODEMP,BDCPFCOL,BDUNICO,BDTAGSTR,BDCODCOL,BDZERADO,BDCODEMPORD,BDREFEMISSAO,BDDESCRICAOFOLHA,BDCODACCONV,
           BDTIPOPROCESSO,BDNUMPROCESSO,BDDESCRRA,BDQTDMESES,BDTOTALDESPJDC)
          VALUES
          (CURRENT_CONNECTION, :WCODEMP,:wcpfcol,:prunico,:prtagstr,:prcodcol,false,:prcodempord,:prref,:PRDESCRICAOFOLHA,:WCODACCONV,:WTIPOPROCESSO,:WNUMPROCESSO,:WDESCRRA,:prqtdmesesrra,:WTOTALDESPJDC)
          MATCHING (BDSESSAO, BDCODEMPORD, BDCPFCOL, BDUNICO, BDTAGSTR, BDREFEMISSAO, BDCODACCONV);

          FOR
            SELECT ADV.BDCODEMP, ADV.BDCODACCONV, ADV.BDCPFCNPJ, ADV.BDVALORPAGO
            FROM VRH_EMP_TACCONV_ADV ADV
            WHERE ADV.BDCODEMP = :WCODEMP AND ADV.BDCODACCONV = :WCODACCONV
          INTO :WEMPADV,:WCODACCONADV,:WCNPJADV,:WVALORPAGOADV
          DO
            BEGIN
              UPDATE OR INSERT INTO VRHF_TEMP_EMP_TRRA5002_ADV
              (BDSESSAO,BDCODEMP,BDCPFCOL,BDUNICO,BDTAGSTR,BDCODCOL,BDZERADO,BDCODEMPORD,BDREFEMISSAO,BDDESCRICAOFOLHA,BDCODACCONV,BDCPFCNPJ,BDVALORPAGO)
              VALUES
              (CURRENT_CONNECTION, :WCODEMP,:wcpfcol,:prunico,:prtagstr,:prcodcol,false,:prcodempord,:prref,:PRDESCRICAOFOLHA,:WCODACCONADV,:WCNPJADV,:WVALORPAGOADV)
              MATCHING (BDSESSAO, BDCODEMPORD, BDCPFCOL, BDUNICO, BDTAGSTR, BDREFEMISSAO, BDCODACCONV,BDCPFCNPJ);
            END
        END
     END
--  suspend;
END^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TRRA5002_BI0 FOR VRHF_TEMP_EMP_TRRA5002
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE VCODIGO INTEGER;
begin
  /* Trigger text */
  VCODIGO = 0;
  if ((new.BDSEQUENCIAL is null) or (new.BDSEQUENCIAL = 0)) then
  begin
    select coalesce((max(BDSEQUENCIAL) + 1), 1)
    from VRHF_TEMP_EMP_TRRA5002
    where BDSESSAO = NEW.BDSESSAO AND
          BDCODEMPORD = NEW.BDCODEMPORD AND
          BDCPFCOL = NEW.BDCPFCOL
    into VCODIGO;

    new.BDSEQUENCIAL = VCODIGO;
  end
end
^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TRRA5002_ADV_BI0 FOR VRHF_TEMP_EMP_TRRA5002_ADV
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE VCODIGO INTEGER;
begin
  /* Trigger text */

  VCODIGO = 0;
  if ((new.BDSEQUENCIALRRA is null) or (new.BDSEQUENCIALRRA = 0)) then
    begin
      select coalesce(max(BDSEQUENCIAL),0)
      from VRHF_TEMP_EMP_TRRA5002
      where BDSESSAO = NEW.BDSESSAO AND
            BDCODEMPORD = NEW.BDCODEMPORD AND
            BDCPFCOL = NEW.BDCPFCOL AND
            BDREFEMISSAO = NEW.BDREFEMISSAO
      into VCODIGO;
    
      new.BDSEQUENCIALRRA = VCODIGO;
    end

  VCODIGO = 0;
  if ((new.BDSEQUENCIAL is null) or (new.BDSEQUENCIAL = 0)) then
  begin
    select coalesce((max(BDSEQUENCIAL) + 1), 1)
    from VRHF_TEMP_EMP_TRRA5002_ADV
    where BDSESSAO = NEW.BDSESSAO AND
          BDCODEMPORD = NEW.BDCODEMPORD AND
          BDCPFCOL = NEW.BDCPFCOL AND
          BDSEQUENCIALRRA = NEW.BDSEQUENCIALRRA AND
          BDREFEMISSAO = NEW.BDREFEMISSAO
    into VCODIGO;

    new.BDSEQUENCIAL = VCODIGO;
  end

end
^

CREATE OR ALTER TRIGGER VRH_EMP_TVALBENEF_DIRF_CPF_BI0 FOR VRH_EMP_TVALBENEF_DIRF_CPF
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  /* Trigger text */

  if (CHAR_LENGTH(new.bdanomesdirf)=6) then
    new.bdanodirf = substring(new.bdanomesdirf from 1 for 4);
end
^

CREATE OR ALTER TRIGGER VRH_EMP_TPROCESSO_DIRF_ITEM_CPF_BI0 FOR VRH_EMP_TPROCESSO_DIRF_ITEM_CPF
ACTIVE BEFORE INSERT POSITION 0
AS
  DECLARE VARIABLE vcod INTEGER;
begin
  /* Trigger text */

  IF (NEW.bdcoditempdirf IS NULL OR (NEW.bdcoditempdirf = 0)) THEN
     BEGIN
       SELECT COALESCE(MAX(bdCODITEMPDIRF) + 1, 1) FROM VRH_EMP_TPROCESSO_DIRF_ITEM_CPF WHERE BDCODPDIRF = NEW.BDCODPDIRF INTO :vcod;
       NEW.bdcoditempdirf = :vcod;
     END

  if (CHAR_LENGTH(new.bdanomesdirfi)=6) then
    new.bdanofunc = substring(new.bdanomesdirfi from 1 for 4);

end
^

create or alter procedure SP_VRH_GET_CODCOL_SWS (
    PRFILTRO varchar(30000),
    PRCODEMP integer = 0,
    PRCODMATRIZ integer = null,
    PRCPFCOL varchar(14) = 0)
returns (
    BDCODEMPORD integer,
    BDCODEMP integer,
    BDCODCOL integer,
    BDCPFCOL varchar(14),
    BDSTATUS integer,
    BDEMAILCOL varchar(200),
    BDEMAIL2COL varchar(100),
    BDNOMCOL varchar(70))
as
declare variable WJOINEMP varchar(30000);
declare variable WSQL varchar(30000);
declare variable WEMPATU integer;
declare variable WCPFATU varchar(14);
declare variable WWHERE varchar(30000);
BEGIN
  WJOINEMP = '';
  WEMPATU = null;
  WCPFATU = null;
  :WWHERE = '';

  IF (POSITION('TEMP_FILTRO_COLCON_REL' IN :PRFILTRO) > 0) THEN
    BEGIN
      WJOINEMP = ' join TEMP_FILTRO_COLCON_REL tmp on (tmp.bdcodemp = c.bdcodemp and tmp.bdcodcol = c.bdcodcol) ';
    END
  else if (:PRCODEMP <> 0) then
    begin
      WWHERE = ' and Coalesce(EMP.BDCODMATRIZ,EMP.BDCODEMP)='||Coalesce(PRCODMATRIZ,PRCODEMP) || ' and  BDCPFCOL=''' || :prcpfcol||'''';
    end

    wSQL = 'SELECT '||
              ' COALESCE(EMP.BDCODMATRIZ,EMP.BDCODEMP) BDCODEMPORD, '||
              ' X.BDCODEMP, '||
              ' X.BDCODCOL, '||
              ' X.BDCPFCOL, '||
              ' X.STATUS, '||
              ' coalesce(X.BDEMAIL2COL, '''') BDEMAILCOL, '||
              ' coalesce(cad.BDEMAILCOL, '''') BDEMAIL2COL, '||
              ' cad.BDNOMCOL '||
           ' FROM ('||
           ' SELECT '||
           '   c.BDCODEMP, '||
           '   c.BDCODCOL, '||
           '   c.BDCPFCOL, '||
           '   coalesce(TRANSDE.BDDATATRF, c.BDDATAADMCOL) AS DATA_REF, '||
           '   1 AS STATUS,   '||
           '   c.BDEMAIL2COL  '||
           ' FROM VRH_EMP_TCOLCON c '||
           ' JOIN TEMPRESAS EMP ON (EMP.BDCODEMP = C.BDCODEMP) '||
             :WJOINEMP||
           ' left outer join VRH_EMP_TTRANSCOL TRANSDE on TRANSDE.BDCODEMPDEST = C.BDCODEMP and TRANSDE.bdcodcoldest = C.BDCODCOL '||
           ' WHERE NOT EXISTS (SELECT first 1 bdcodemp FROM VRH_EMP_TRESCISAO r WHERE r.BDCODEMP = c.BDCODEMP AND r.BDCODCOL = c.BDCODCOL) '||
             :WWHERE||
           ' UNION ALL '||
           ' SELECT '||
           '   c.BDCODEMP, '||
           '   c.BDCODCOL, '||
           '   c.BDCPFCOL, '||
           '   r.BDDATARESCISAO AS DATA_REF, '||
           '   2 AS STATUS, '||
           '   c.BDEMAIL2COL  '||
           ' FROM VRH_EMP_TRESCISAO r '||
           ' JOIN VRH_EMP_TCOLCON c ON c.BDCODEMP = r.BDCODEMP AND c.BDCODCOL = r.BDCODCOL '||
           ' JOIN TEMPRESAS EMP ON (EMP.BDCODEMP = C.BDCODEMP) '||
             :WJOINEMP||
             replace(:WWHERE,'AND','WHERE ')||
           ') X '||
           ' JOIN TEMPRESAS EMP ON (EMP.BDCODEMP = X.BDCODEMP) '||
           ' LEFT OUTER JOIN VRH_EMP_TCOLCON_CAD cad ON cad.BDCODEMP = x.BDCODEMP and cad.BDCODCOL = x.BDCODCOL  ' ||
           '         and cad.BDREFCOL = (SELECT FIRST 1 cx.BDREFCOL FROM  VRH_EMP_TCOLCON_CAD cx ' ||
           '                             WHERE cx.BDCODEMP = x.BDCODEMP and cx.BDCODCOL = x.BDCODCOL ' ||
           '                              ORDER BY cx.BDREFCOL DESC ) ' ||
           ' ORDER BY BDCODEMPORD,X.BDCPFCOL, X.STATUS, X.DATA_REF DESC ';


  FOR EXECUTE STATEMENT wSQL
      INTO :BDCODEMPORD, :BDCODEMP, :BDCODCOL, :BDCPFCOL, :BDSTATUS, :BDEMAILCOL, :BDEMAIL2COL, :BDNOMCOL
  DO
    BEGIN
      IF ((BDCODEMPORD is distinct from :WEMPATU) OR (BDCPFCOL is distinct from :WCPFATU))  THEN
        BEGIN
          SUSPEND;
          WEMPATU = BDCODEMPORD;
          WCPFATU = BDCPFCOL;
        END
    END

END^

COMMENT ON PARAMETER SP_VRH_COLCON_RHNET_EXP.PRFILTROCOL IS
'Filtro por tipo de cadastro: 0 = Todos; 1 = Colaboradores; 2 = Contribuintes'^
^
COMMENT ON PARAMETER SP_VRH_COLCON_RHNET_EXP.PRDADOSINICIAIS IS
'Indica se é exportação inicial: 0 = Não; 1 = Sim'^

COMMENT ON PARAMETER SP_VRH_COLCON_RHNET_EXP.PRSOMENTELEITURA IS
'Controle interno para gerar informação de comparação: 0 = Não; 1 = Sim'^

CREATE OR ALTER TRIGGER VEF_BASE_RED_NCM_NBS_BIU0 FOR VEF_BASE_RED_NCM_NBS
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
  if ((NEW.BDCODCST IS NOT NULL) AND (NEW.BDCODCST is distinct from OLD.BDCODCST) and (not exists(SELECT FIRST 1 A.BDCODCST_IBS_CBS FROM VEF_BASE_CST_IBS_CBS A WHERE A.BDCODCST_IBS_CBS = NEW.BDCODCST))) then
    EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_BASE_RED_NCM_NBS', NEW.BDCODCST, 'BDCODCST', 'VEF_BASE_CST_IBS_CBS');
  end
end^    

CREATE OR ALTER TRIGGER VEF_EMP_TMOVSERITENS_BIU0 FOR VEF_EMP_TMOVSERITENS
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
      if ((NEW.BDCODNBS IS NOT NULL) AND (NEW.BDCODNBS is distinct from OLD.BDCODNBS) and (not exists(SELECT FIRST 1 A.BDCOD_NBS FROM VEF_BASE_TNBS A WHERE A.BDCOD_NBS = NEW.BDCODNBS))) then
        EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSERITENS', NEW.BDCODNBS, 'BDCODNBS', 'VEF_BASE_TNBS');
  end
END^


CREATE OR ALTER trigger vef_emp_tmovser_ibscbs_biu0 for vef_emp_tmovser_ibscbs
active before insert or update position 0
AS
begin
  if (coalesce(rdb$get_context('USER_SESSION', 'W_EXCLUINDOEMPRESAS'), 'FALSE') <> 'TRUE') then
  begin
      if ((NEW.BDCCLASSTRIB IS NOT NULL) AND (NEW.BDCCLASSTRIB is distinct from OLD.BDCCLASSTRIB) and (not exists(SELECT FIRST 1 A.BDCODCCLASSTRIB FROM VEF_BASE_TCLASSTRIB A WHERE A.BDCODCCLASSTRIB = NEW.BDCCLASSTRIB))) then
        EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSER_IBSCBS', NEW.BDCCLASSTRIB, 'BDCODCCLASSTRIB', 'VEF_BASE_TCLASSTRIB');
      if ((NEW.BDCST IS NOT NULL) AND (NEW.BDCST is distinct from OLD.BDCST) and (not exists(SELECT FIRST 1 A.BDCODCST_IBS_CBS FROM VEF_BASE_CST_IBS_CBS A WHERE A.BDCODCST_IBS_CBS = NEW.BDCST))) then
        EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSER_IBSCBS', NEW.BDCST, 'BDCODCST_IBS_CBS', 'VEF_BASE_CST_IBS_CBS');
      if ((NEW.BDCOD_CRED_PRES IS NOT NULL) AND (NEW.BDCOD_CRED_PRES is distinct from OLD.BDCOD_CRED_PRES) and (not exists(SELECT FIRST 1 A.BDCODCREDITO FROM VEF_BASE_CRED_PRES_IBSCBS A WHERE A.BDCODCREDITO = NEW.BDCOD_CRED_PRES))) then
        EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSER_IBSCBS', NEW.BDCOD_CRED_PRES, 'BDCODCCLASSTRIB', 'VEF_BASE_CRED_PRES_IBSCBS');
      if ((NEW.BDINDOP IS NOT NULL) AND (NEW.BDINDOP is distinct from OLD.BDINDOP) and (not exists(SELECT FIRST 1 A.BDCHAVE FROM VEF_BASE_TINDOPERACAO A WHERE A.BDCHAVE = NEW.BDINDOP))) then
        EXCEPTION EX_CHAVE_ESTRANGEIRA using ('VEF_EMP_TMOVSER_IBSCBS', NEW.BDINDOP, 'BDCODCCLASSTRIB', 'VEF_BASE_TINDOPERACAO');
  end
END^

CREATE or alter trigger tol_vef_emp_tcomercnfprodrural_ad0 for tol_vef_emp_tcomercnfprodrural
active after delete position 0
AS
begin
  DELETE FROM VRH_EMP_TCOMERCNFPRODRURAL R WHERE R.BDCODEMP =  OLD.BDCODEMP AND R.BDCHAVE = OLD.BDCHAVE_RH;
end^
create or alter procedure SP_VRH_RETORNA_VINC_COL (
    PRCODEMP integer,
    PRCODMATRIZ integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDCODTER integer,
    BDCODEMPORG integer,
    BDCPFCOL varchar(14),
    BDCODMATRIZ integer)
as
declare variable WSQL varchar(30000);
begin
   bdcodemporg = :prcodemp;
   wSql =  ' SELECT ' ||
         '    X.BDCODEMP, ' ||
         '     X.BDCODCOL, ' ||
         '     X.BDCODTER,  ' ||
         '     X.BDCPFCOL,  ' ||
         '     X.BDCODMATRIZ  ' ||
         ' FROM (          ' ||
         '     SELECT      ' ||
         '         C.BDCODEMP, ' ||
         '         EMP2.BDCODMATRIZ, ' ||
         '         C.BDCODCOL,  ' ||
         '         0 AS BDCODTER, ' ||
         '         C.BDCPFCOL  ' ||
         '     FROM VRH_EMP_TCOLCON C ' ||
         '     JOIN TEMPRESAS EMP2 ON EMP2.BDCODEMP = C.BDCODEMP ' ||
         '     WHERE COALESCE(EMP2.BDCODMATRIZ, EMP2.BDCODEMP) = '|| COALESCE(:PRCODMATRIZ, :PRCODEMP) ||
--         '     AND C.BDCPFCOL = '''|| :PRCPF  ||''''||
         '     UNION ALL ' ||
         '     SELECT ' ||
         '         C.BDCODEMP, ' ||
         '         EMP3.BDCODMATRIZ, ' ||
         '         0, ' ||
         '         C.BDCODTER, ' ||
         '         TER.BDCGCTER ' ||
         '     FROM VRHF_BASE_CALC_TERC C ' ||
         '     LEFT JOIN TTERCEIRO TER ON TER.BDCODTER = C.BDCODTER ' ||
         '     JOIN TEMPRESAS EMP3 ON EMP3.BDCODEMP = C.BDCODEMP ' ||
         '     WHERE COALESCE(EMP3.BDCODMATRIZ, EMP3.BDCODEMP) = '|| COALESCE(:PRCODMATRIZ, :PRCODEMP) ||
         '     AND ((position(''/'',TER.BDCGCTER) = 0)) ' ||
         '     GROUP BY C.BDCODEMP,BDCODMATRIZ, C.BDCODTER, TER.BDCGCTER ' ||
         ' ) X ' ||
         ' ORDER BY X.BDCODEMP, X.BDCPFCOL ';
      FOR EXECUTE STATEMENT
      wSql
      INTO :BDCODEMP, :BDCODCOL, :BDCODTER, :BDCPFCOL , :bdcodmatriz
      DO
      BEGIN
          SUSPEND;
      END

end^

/* Restore proc. body: SP_VRHF_SOMENTE_RATEIO */
create or alter procedure SP_VRHF_SOMENTE_RATEIO (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREFTOMADOR integer,
    BDCODVER integer,
    BDREFVFT DM_NUMERIC_20MILHOES_2CASAS,
    BDREFAUXVFT DM_NUMERIC_20MILHOES_2CASAS,
    BDVALVFT DM_NUMERIC_20MILHOES_2CASAS,
    BDIGNREFVFT DM_BOOLEAN,
    BDIGNVALVFT DM_BOOLEAN,
    BDVALVIFT DM_NUMERIC_20MILHOES_2CASAS,
    BDSALBASEFT DM_NUMERIC_20MILHOES_2CASAS,
    BDREFVFTMAX DM_NUMERIC_20MILHOES_2CASAS,
    BDREFAUXVFTMAX DM_NUMERIC_20MILHOES_2CASAS,
    BDORIGEMVERBA integer)
as
declare variable WREFHOREMP DM_BOOLEAN;
declare variable WVERATU integer;
declare variable WCODVER integer;
declare variable WREFVFT DM_NUMERIC_20MILHOES_2CASAS;
declare variable WREFAUXVFT DM_NUMERIC_20MILHOES_2CASAS;
declare variable WVALVFT DM_NUMERIC_20MILHOES_2CASAS;
declare variable WIGNREF DM_BOOLEAN;
declare variable WIGNVAL DM_BOOLEAN;
declare variable WVALVIFT DM_NUMERIC_20MILHOES_2CASAS;
declare variable WSALBASEFT DM_NUMERIC_20MILHOES_2CASAS;
declare variable WORVERBA integer;
declare variable WTIPOREFVER integer;
declare variable WREFCONVERTIDA numeric(12,6);
declare variable WINTEIRO integer;
declare variable WCLAVER varchar(20);
begin
  wrefhoremp = null;
  select first 1 BDREFHOREMP from VRHF_BASE_TEMPCALC where BDCODEMP = :prcodemp and BDREFEMP <= :prref order by BDCODEMP desc, BDREFEMP desc
  into :wrefhoremp;
  wrefhoremp = upper(coalesce(wrefhoremp, 'FALSE'));

  for select FN.BDCODEMP, FN.BDCODCOL, FN.BDREFFN, FN.BDCODVER, FN.BDREFVFN, FN.BDREFAUXVFN, FN.BDVALVFN, FN.BDIGNREFVFN, FN.BDIGNVALVFN, FN.BDVALVIFN, FNB.BDSALBASEFN, FN.BDORVERBAFN, FN.BDREFVFN, FN.BDREFAUXVFN
      from VRHF_EMP_TVERBAFN FN
      join VRHF_EMP_TFOLHANORMAL FNB on (FNB.BDCODEMP = FN.BDCODEMP and FNB.BDCODCOL = FN.BDCODCOL and FNB.BDREFFN = FN.BDREFFN)
      where FN.BDCODEMP = :prcodemp and FN.BDCODCOL = :prcodcol and FN.BDREFFN = :prref
  into :BDCODEMP, :BDCODCOL, :BDREFTOMADOR, :BDCODVER, :BDREFVFT, :BDREFAUXVFT, :BDVALVFT, :BDIGNREFVFT, :BDIGNVALVFT, :BDVALVIFT, :BDSALBASEFT, :BDORIGEMVERBA, :BDREFVFTMAX, :BDREFAUXVFTMAX
  do
    suspend;

  wveratu = 0;
  BDREFVFT = 0;
  BDREFAUXVFT = 0;
  BDVALVFT = 0;
  BDIGNREFVFT = 'FALSE';
  BDIGNVALVFT = 'FALSE';
  BDVALVIFT = 0;
  BDSALBASEFT = 0;
  BDREFVFTMAX = 0;
  BDREFAUXVFTMAX = 0;
  BDORIGEMVERBA = null;
  wtiporefver = 0;

  for select FN.BDCODVER, FN.BDREFVFT, FN.BDREFAUXVFT, FN.BDVALVFT, FN.BDIGNREFVFT, FN.BDIGNVALVFT, FN.BDVALVIFT, FNB.BDSALBASEFT, FN.BDORVERBAFT BDORIGEMVERBA, V.BDCLAVER
      from VRHF_EMP_TVERBATOMADOR FN
      join VRHF_EMP_TFOLHATOMADOR FNB on (FNB.BDCODEMP = FN.BDCODEMP and FNB.BDCODCOL = FN.BDCODCOL and FNB.BDREFTOMADOR = FN.BDREFTOMADOR and FNB.BDORDEM = FN.BDORDEM)
      join VRH_BASE_TVERBAS V on (V.BDCODVER = FN.BDCODVER)
      where FN.BDCODEMP = :prcodemp and FN.BDCODCOL = :prcodcol and FN.BDREFTOMADOR = :prref
      order by FN.BDCODVER
  into :wcodver, :wrefvft, :wrefauxvft, :wvalvft, :wignref, :wignval, :wvalvift, :wsalbaseft, :worverba, :wclaver
  do
    begin
      if (wveratu = 0) then
         begin
           wveratu = wcodver;
           select first 1 BDTIPOREFVER from VRH_BASE_TVERBAS_REF where BDCODVER = :wveratu and BDREFVER <= :prref order by BDCODVER desc, BDREFVER desc into :wtiporefver;
           wtiporefver = coalesce(wtiporefver, 0);
         end

      if (wveratu <> wcodver) then
         begin
           BDCODEMP = prcodemp;
           BDCODCOL = prcodcol;
           BDREFTOMADOR = prref;
           BDCODVER = wveratu;

           suspend;

           BDREFVFT = 0;
           BDREFAUXVFT = 0;
           BDVALVFT = 0;
           BDIGNREFVFT = 'FALSE';
           BDIGNVALVFT = 'FALSE';
           BDVALVIFT = 0;
           BDSALBASEFT = 0;
           BDREFVFTMAX = 0;
           BDREFAUXVFTMAX = 0;
           BDORIGEMVERBA = null;

           wveratu = wcodver;
           select first 1 BDTIPOREFVER from VRH_BASE_TVERBAS_REF where BDCODVER = :wveratu and BDREFVER <= :prref order by BDCODVER desc, BDREFVER desc into :wtiporefver;
           wtiporefver = coalesce(wtiporefver, 0);
         end

      --SE FOR IMPOSTO, SOMAR AS REFAUX POIS ESTÃO RATEADAS ENTRE OS TOMADORES
      if (wclaver like '%9.010%') then
        begin
           BDREFAUXVFTMAX = BDREFAUXVFTMAX + wrefauxvft;
        end
      else
        begin
          if (BDREFAUXVFTMAX < coalesce(wrefauxvft, 0.00)) then
             BDREFAUXVFTMAX = coalesce(wrefauxvft, 0.00);
        end

      BDREFAUXVFT = BDREFAUXVFT + wrefauxvft;

      wrefconvertida = coalesce(wrefvft, 0.00);

      if (wrefhoremp = 'TRUE' and wtiporefver = 1) then
         begin
           winteiro = trunc(wrefconvertida);
           wrefconvertida = wrefconvertida - winteiro;
           wrefconvertida = cast((wrefconvertida / 60 * 100) as dm_numeric_20milhoes_2casas);
           wrefconvertida = wrefconvertida + winteiro;
         end

      BDREFVFT = BDREFVFT + cast(wrefconvertida as dm_numeric_20milhoes_2casas);

      if (BDREFVFTMAX < wrefconvertida) then
         BDREFVFTMAX = wrefconvertida;

      BDVALVFT = BDVALVFT + coalesce(wvalvft, 0.00);

      if (BDVALVIFT < coalesce(wvalvift, 0.00)) then
         BDVALVIFT = coalesce(wvalvift, 0.00);

      if (BDSALBASEFT < coalesce(wsalbaseft, 0.00)) then
         BDSALBASEFT = coalesce(wsalbaseft, 0.00);

      BDORIGEMVERBA = worverba;
      BDIGNREFVFT = wignref;
      BDIGNVALVFT = wignval;
    end

  if (wveratu > 0) then
     begin
       BDCODEMP = prcodemp;
       BDCODCOL = prcodcol;
       BDREFTOMADOR = prref;
       BDCODVER = wveratu;
       suspend;
     end
end^

CREATE OR ALTER TRIGGER VRHF_TABELAS_TIRREDUCAO_BI0 FOR VRHF_TABELAS_TIRREDUCAO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (coalesce(new.bdcodirred, 0) <= 0) then
     select coalesce(max(BDCODIRRED) + 1, 1) from VRHF_TABELAS_TIRREDUCAO where BDCODIR = new.bdcodir into new.bdcodirred;
end
^

CREATE OR ALTER TRIGGER VRHF_TABELAS_TIRREDFAIXAS_BI0 FOR VRHF_TABELAS_TIRREDFAIXAS
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (coalesce(new.bdcodfaixa, 0) <= 0) then
     select coalesce(max(BDCODFAIXA) + 1, 1) from VRHF_TABELAS_TIRREDFAIXAS where BDCODIR = new.bdcodir and BDCODIRRED = new.bdcodirred into new.bdcodfaixa;
end
^
CREATE OR ALTER TRIGGER VRHF_TABELAS_TIRREDITENS_BI0 FOR VRHF_TABELAS_TIRREDITENS
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (coalesce(new.bdcodirred, 0) <= 0) then
     select max(BDCODIRRED) from VRHF_TABELAS_TIRREDUCAO where BDCODIR = new.bdcodir into new.bdcodirred;
end
^

/* Restore proc. body: SP_VRHF_TAB_IR_REDUCAO */
create or alter procedure SP_VRHF_TAB_IR_REDUCAO (
    PRCODIR integer,
    PRTIPOCALC integer,
    PRCOMPETENCIA integer)
returns (
    BDCODIR integer,
    BDCODIRRED integer,
    BDREFIR integer,
    BDCODFAIXA integer,
    BDVALORATE DM_NUMERIC_20MILHOES_2CASAS,
    BDLIMITEDED DM_NUMERIC_20MILHOES_2CASAS,
    BDINDICE numeric(15,6))
as
declare variable WCODIRRED integer;
declare variable WREFIR integer;
begin
  if (coalesce(prcodir, 0) <= 0) then
     prcodir = 1;

  prtipocalc = coalesce(prtipocalc, 0);

  wcodirred = null;
  wrefir = null;

  if (prtipocalc <> 11) then    -- Todos os cálculos
      select first 1 R.BDCODIRRED, R.BDREFIR
      from VRHF_TABELAS_TIRREDUCAO R
      where R.BDCODIR = :prcodir and R.BDREFIR <= :prcompetencia
            and exists (select T.BDTIPOCALC from VRHF_TABELAS_TIRREDITENS T where T.BDCODIR = R.BDCODIR and T.BDCODIRRED = R.BDCODIRRED and T.BDTIPOCALC = :prtipocalc)
      order by R.BDCODIR desc, R.BDCODIRRED desc, R.BDREFIR desc
      into :wcodirred, :wrefir;
  else
      select first 1 R.BDCODIRRED, R.BDREFIR
      from VRHF_TABELAS_TIRREDUCAO R
      where R.BDCODIR = :prcodir and R.BDREFIR <= :prcompetencia
      order by R.BDCODIR desc, R.BDCODIRRED desc, R.BDREFIR desc
      into :wcodirred, :wrefir;

  wcodirred = coalesce(wcodirred, 0);

  if (wcodirred > 0) then
     begin
       BDREFIR = wrefir;

       for select BDCODIR, BDCODIRRED, BDCODFAIXA, BDVALORATE, BDLIMITEDED, BDINDICE
           from VRHF_TABELAS_TIRREDFAIXAS
           where BDCODIR = :prcodir and BDCODIRRED = :wcodirred
       into :BDCODIR, :BDCODIRRED, :BDCODFAIXA, :BDVALORATE, :BDLIMITEDED, :BDINDICE
       do
         suspend;
     end
end^

CREATE OR ALTER TRIGGER VRHF_EMP_TPREPFN_AI0 FOR VRHF_EMP_TPREPFN
ACTIVE AFTER INSERT POSITION 0
AS
  declare variable wdtent DATE;
  declare variable wordem INTEGER;

begin
  if (new.bddataentrada is not null) then
     begin
       wordem = null;
       wdtent = null;

       -- Busca a data de entrada anterior a nova alocação
       select first 1 BDORDEM, BDDATAENTRADA
       from VRHF_EMP_TPREPFN
       where BDCODEMP = new.bdcodemp and BDCODCOL = new.bdcodcol and BDDATAENTRADA <= new.bddataentrada and BDORDEM <> new.bdordem
       order by BDCODEMP desc, BDCODCOL desc, BDDATAENTRADA desc, BDHORAENTRADA desc
       into :wordem, :wdtent;

       -- Se existir alocação, imediatamente anterior, deve atualizar essas alocação com a data final
       if (wordem is not null and wdtent is not null) then
          begin
            -- Se a data de entrada anterior for igual a data da nova alocação, então deve colocar a data de saída igual a nova alocação e a hora de saída sendo um minuto antes da nova hora de alocação
            -- Senáo, apenas atribui a data de saída na alocação anterior como sendo um dia antes da nova entrada
            if (new.bdhoraentrada is not null and new.bdhoraentrada > '00:00:00') then
               begin
                 update VRHF_EMP_TPREPFN set BDDATASAIDA = new.bddataentrada, BDHORASAIDA = DATEADD(minute, -1, new.bdhoraentrada)
                 where BDCODEMP = new.BDCODEMP and BDCODCOL = new.BDCODCOL and BDORDEM = :wordem;
               end
            else
               begin
                 update VRHF_EMP_TPREPFN set BDDATASAIDA = DATEADD(day, -1, new.bddataentrada), BDHORASAIDA = '00:00:00'
                 where BDCODEMP = new.BDCODEMP and BDCODCOL = new.BDCODCOL and BDORDEM = :wordem;
               end
          end
     end
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TPREPFN_AD0 FOR VRHF_EMP_TPREPFN
ACTIVE AFTER DELETE POSITION 0
AS
  declare variable woposterior INTEGER;
  declare variable wdposterior DATE;
  declare variable whposterior TIME;

  declare variable woanterior INTEGER;
  declare variable wdanterior DATE;

begin
  woposterior = null;
  wdposterior = null;
  whposterior = null;

  woanterior = null;
  wdanterior = null;


  -- Verifica se existe data posterior de alocação
  -- Nesse caso deve pegar a data da alocação posterior e atualizar a data final da alocação anterior
  select first 1 BDORDEM, BDDATAENTRADA, BDHORAENTRADA
  from VRHF_EMP_TPREPFN where BDCODEMP = old.BDCODEMP and BDCODCOL = old.BDCODCOL and BDDATAENTRADA >= old.bddataentrada and BDORDEM <> old.bdordem
  order by BDCODEMP, BDCODCOL, BDDATAENTRADA, BDHORAENTRADA
  into :woposterior, :wdposterior, :whposterior;

  if (woposterior is not null and wdposterior is not null) then
     begin
       -- Verifica se existe alocação anterior a alocação excluída.
       -- Nesse caso deve atualizar a data final da alocação anterior com as informações da alocação posterior
       select first 1 BDORDEM, BDDATAENTRADA
       from VRHF_EMP_TPREPFN where BDCODEMP = old.BDCODEMP and BDCODCOL = old.BDCODCOL and BDDATAENTRADA <= old.bddataentrada and BDORDEM <> old.bdordem
       order by BDCODEMP desc, BDCODCOL desc, BDDATAENTRADA desc, BDHORAENTRADA desc
       into :woanterior, :wdanterior;

       if (woanterior is not null and wdanterior is not null) then
          begin
            if (whposterior is not null and whposterior > '00:00:00') then
               begin
                 update VRHF_EMP_TPREPFN set BDDATASAIDA = :wdposterior, BDHORASAIDA = DATEADD(minute, -1, :whposterior)
                 where BDCODEMP = old.BDCODEMP and BDCODCOL = old.BDCODCOL and BDORDEM = :woanterior;
               end
            else
               begin
                 update VRHF_EMP_TPREPFN set BDDATASAIDA = DATEADD(day, -1, :wdposterior), BDHORASAIDA = '00:00:00'
                 where BDCODEMP = old.BDCODEMP and BDCODCOL = old.BDCODCOL and BDORDEM = :woanterior;
               end
          end
     end
  else
     begin
       -- Caso contrário, deve apagar a data e hora finais da alocação anterior
       select first 1 BDORDEM, BDDATAENTRADA
       from VRHF_EMP_TPREPFN where BDCODEMP = old.BDCODEMP and BDCODCOL = old.BDCODCOL and BDDATAENTRADA <= old.bddataentrada and BDORDEM <> old.bdordem
       order by BDCODEMP desc, BDCODCOL desc, BDDATAENTRADA desc, BDHORAENTRADA desc
       into :woanterior, :wdanterior;

       if (woanterior is not null and wdanterior is not null) then
          begin
            update VRHF_EMP_TPREPFN set BDDATASAIDA = null, BDHORASAIDA = null
            where BDCODEMP = old.BDCODEMP and BDCODCOL = old.BDCODCOL and BDORDEM = :woanterior;
          end
     end
end^

create or alter procedure SP_VINCULOS_DECLARACAO_DESTINO (
    PRANO integer,
    PRCPF varchar(30000),
    PRAUTCOL integer)
returns (
    BDCODEMP_FILTRO integer,
    BDCODCOL_FILTRO integer,
    BDCODTER_FILTRO integer,
    BDTIPO integer,
    BDCPF varchar(20),
    BDCODEMP_IMP integer,
    BDCODCOL_IMP integer,
    BDCODTER_IMP integer)
as
declare variable WSQL varchar(30000);
declare variable WCPFANT varchar(20);
declare variable WMATRIZ integer;
declare variable WSUSPEND integer;
declare variable WJOINCPF varchar(200);
begin
  /* Procedure Text */
  delete from TEMP_FILTRO_COLCON_REL;

--  prAutCol - zero todos = 1 colaboradores 2 = autonomos
--  suspend;

  WJOINCPF = '';
  if (POSITION('TEMP_FILTRO_CPF_REL', PRCPF) > 0) then
     begin
       WJOINCPF = ' JOIN TEMP_FILTRO_CPF_REL FILTRO ON (FILTRO.BDCPF = C.BDCPFCOL) ';
       PRCPF = '';
     end

  -- Verificar quais empresas precisão ser verificadas de todas as selecionadas devem ter matriz e filial de cada uma
  wsql =  'select coalesce(emp.bdcodmatriz,emp.bdcodemp) bdcodmatriz from tempresas emp '||
          ' join tmp_empresas_select temp on (emp.bdcodemp = temp.bdcodemp)';
  wsql = wsql||' group by bdcodmatriz';

  for execute statement wsql into wmatriz do
    begin
      -- primeiro busca quais são os cadastro de colaboradores e autonomos que deve buscar os dados
      -- Colaboradores
      wSql =  ' SELECT max(X.bdtipo) bdtipo, X.BDCODEMP, X.BDCODCOL, X.BDCODTER, X.BDCPFCOL FROM ('||
            '     SELECT 0 bdtipo, C.BDCODEMP, EMP2.BDCODMATRIZ, C.BDCODCOL,  0 AS BDCODTER, C.BDCPFCOL '||
            '     FROM VRH_EMP_TCOLCON C ' ||
            WJOINCPF||
            '     JOIN TEMPRESAS EMP2 ON EMP2.BDCODEMP = C.BDCODEMP ' ||
            '     WHERE COALESCE(EMP2.BDCODMATRIZ, EMP2.BDCODEMP) = '|| :wmatriz;

      if (coalesce(prcpf,'') <> '') then
         wsql = wsql||' and '||prcpf;

      -- Autonomos
      wsql = wsql||
            '     UNION ALL ' ||
            '     SELECT 1 bdtipo, C.BDCODEMP, EMP3.BDCODMATRIZ,  0, C.BDCODTER, TER.BDCGCTER ' ||
            '     FROM VRHF_BASE_CALC_TERC C ' ||
            '     LEFT JOIN TTERCEIRO TER ON TER.BDCODTER = C.BDCODTER ' ||
            replace(upper(WJOINCPF),'C.BDCPFCOL','TER.BDCGCTER')||
            '     JOIN TEMPRESAS EMP3 ON EMP3.BDCODEMP = C.BDCODEMP ' ||
            '     WHERE COALESCE(EMP3.BDCODMATRIZ, EMP3.BDCODEMP) = '|| :wmatriz ||
            '     AND ((position(''/'',TER.BDCGCTER) = 0)) ';

      if (coalesce(prcpf,'') <> '') then
         wsql = wsql||' and '||replace(upper(prcpf),'C.BDCPFCOL','TER.BDCGCTER');

      wsql = wsql||'     GROUP BY C.BDCODEMP,BDCODMATRIZ, C.BDCODTER, TER.BDCGCTER ';

      -- Lançamentos manuais sem CPF
      wsql = wsql||
            '     UNION ALL ' ||
            '     SELECT 3 bdtipo, dirf.BDCODEMP, '||:wmatriz||',  0 bdcodcol, 0 bdcodter, dirf.bdcpfcol ' ||
            '     FROM vrh_emp_tcolcon_ano_cpf dirf ' ||
            replace(upper(WJOINCPF),'C.BDCPFCOL','dirf.bdcpfcol')||
            '     JOIN TEMPRESAS EMP3 ON EMP3.BDCODEMP = dirf.BDCODEMP ' ||
            '     WHERE COALESCE(EMP3.BDCODMATRIZ, EMP3.BDCODEMP) = '|| :wmatriz ||
            '     and dirf.bdanofunc = '||:prAno;

      if (coalesce(prcpf,'') <> '') then
         wsql = wsql||' and '||replace(upper(prcpf),'C.BDCPFCOL','dirf.bdcpfcol');

      -- Reclamatorias trabalistas
      wsql = wsql||
            '     UNION ALL ' ||
            '     SELECT 4 bdtipo, rt.BDCODEMP, '||:wmatriz||',  0 bdcodcol, 0 bdcodter, rt.bdcpfcol ' ||
            '     FROM vrh_emp_treclamatoria rt '||
            replace(upper(WJOINCPF),'C.BDCPFCOL','rt.bdcpfcol')||
            '     INNER JOIN TEMPRESAS EMP ON (EMP.bdcodemp = rt.bdcodemp) '||
            '     JOIN VRH_TENCARGOS_RT EN ON (EN.BDCODEMP = rt.BDCODEMP AND EN.BDCHAVE = rt.BDCODRT) '||
            '     WHERE COALESCE(EMP.BDCODMATRIZ, EMP.BDCODEMP) = '|| :wmatriz ||
            '     and en.BDREFPGTO between '||:prAno||'01 and '||:prAno||'12';

         if (coalesce(prcpf,'') <> '') then
            wsql = wsql||' and '||replace(upper(prcpf),'C.BDCPFCOL','rt.bdcpfcol');
   
         wsql = wsql||' ) X ' ||
               ' group by X.BDCODEMP, X.BDCODCOL, X.BDCODTER, X.BDCPFCOL'||
               ' ORDER BY X.BDCPFCOL, bdtipo, X.BDCODEMP ';

         wCPFANT = '';
         wSuspend = 0;
         FOR EXECUTE STATEMENT    wSql
         INTO :BDTipo, :bdcodemp_filtro, :bdcodcol_filtro, :bdcodter_filtro, :bdcpf DO
         BEGIN
           if (wCPFANT <> bdcpf) then
              begin
                wCPFANT = bdcpf;
                bdcodemp_imp = null;
                bdcodcol_imp = null;
                bdcodter_imp = null;
                select first 1 x.bdcodemp, x.bdcodcol from SP_VRH_GET_CODCOL_SWS('''', :bdcodemp_filtro, :wmatriz, :bdcpf) x into bdcodemp_imp,bdcodcol_imp;

                if (bdcodemp_imp is null) then
                   begin
                     bdcodemp_imp = bdcodemp_filtro;
                     bdcodcol_imp = bdcodcol_filtro;
                     bdcodter_imp = bdcodter_filtro;
                   end

                wsql =  'select count(*) from tmp_empresas_select emp ';
                 wsql = wsql||' where emp.bdcodemp = '||:bdcodemp_imp;

                wsuspend = 0;
                execute statement wsql into wsuspend;
           end

           if (wsuspend > 0) then
              begin
                insert into TEMP_FILTRO_COLCON_REL (BDCOMP, BDCODEMP, bdcodcol,BDCODTER, bdcpf) values
                                      ('edCPFCOL',:bdcodemp_filtro,:bdcodcol_filtro,:bdcodter_filtro,:bdcpf);
                SUSPEND;
              end
         END

      -- Ver onde ser irá imprimir
    end
end^

CREATE OR ALTER TRIGGER VRH_BASE_TPREPSIT_PADRAO_BI0 FOR VRH_BASE_TPREPSIT_PADRAO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (coalesce(new.bdcodsitpd, 0) <= 0) then
     begin
       select coalesce(max(BDCODSITPD) + 1, 1) from VRH_BASE_TPREPSIT_PADRAO into new.bdcodsitpd;
       new.bdcodsitscipd = new.bdcodsitpd;
     end
end
^

create or alter procedure SP_BUSCA_REDUCAO_NCM (
    PRNCM varchar(10),
    PRISNBS boolean,
    PRDATAFIM date)
returns (
    BDREDUCAO integer,
    BDCCLASSTRIB varchar(30),
    BDLC varchar(100),
    BDLINK_LC varchar(100),
    BDFUND_LEGAL varchar(100),
    BDCODCST integer,
    BDCODIS integer)
as
declare variable I integer;
declare variable WWHERE varchar(1000);
declare variable WSQL varchar(1000);
declare variable BDEXCECAO varchar(1000);
declare variable V_EXCECAO smallint;
BEGIN

  if (:PRNCM = '') then
    exit;

  I = CHAR_LENGTH(:PRNCM);
  WWHERE = '(BDCLASSIFICACAO = ''' || :PRNCM || ''')';

  WHILE (I > 0) DO
   BEGIN
    I = I - 1;

    if (I = 0) then
       BREAK;

    WWHERE = WWHERE || ' OR (BDCLASSIFICACAO = ''' || SUBSTRING(:PRNCM FROM 1 FOR :I) || ''')';
   END

   if (PRISNBS) then
    begin

     wSQL = ' select FIRST 1 NBS.BDREDUCAO, NBS.BDCCLASSTRIB, NBS.BDLC, NBS.BDLINK_LC, NBS.BDFUND_LEGAL, NBS.BDCODCST, NBS.BDEXCECAO ';
     wSQL = wSQL || ' from TNCM R ';
     wSQL = wSQL || ' JOIN VEF_BASE_RED_NCM_NBS NBS ON NBS.BDCOD_NCM = R.bdncmprod';
     wSQL = wSQL || ' WHERE COALESCE(BD_DT_FIM, '''|| :PRDATAFIM ||''') >= ''' || :PRDATAFIM || ''' AND (' || WWHERE || ')';
     wSQL = wSQL || ' ORDER BY BDCLASSIFICACAO DESC ';
     EXECUTE STATEMENT :WSQL
     INTO  :BDREDUCAO, :BDCCLASSTRIB, :BDLC, :BDLINK_LC, :BDFUND_LEGAL, :BDCODCST, :BDEXCECAO;
    end
   else
    begin
     wSQL = ' SELECT first 1 ';
     wSQL = wSQL || ' BDCOD_IS , BDEXCECAO ';
     wSQL = wSQL || ' from TNCM R ';
     wSQL = wSQL || ' JOIN VEF_BASE_TCAD_IS I ON I.BDCOD_NCM = R.bdncmprod';
     wSQL = wSQL || ' WHERE COALESCE(BD_DT_FIM, '''|| :PRDATAFIM ||''') >= ''' || :PRDATAFIM || ''' AND (' || WWHERE || ')' ;
     wSQL = wSQL || ' ORDER BY BDCLASSIFICACAO DESC ';
     EXECUTE STATEMENT :WSQL
     INTO  :BDCODIS, :BDEXCECAO;
    end

   SELECT first 1 ISEXCECAO
   FROM SP_NCM_IS_EXCECAO(:PRNCM, :BDEXCECAO)
   INTO :V_EXCECAO;

   IF (V_EXCECAO = 1) THEN
   BEGIN
    :BDREDUCAO    = Null;
    :BDCCLASSTRIB = Null;
    :BDLC         = Null;
    :BDLINK_LC    = Null;
    :BDFUND_LEGAL = Null;
    :BDCODCST     = Null;
    :BDEXCECAO    = Null;
   END

   SUSPEND;

END^

/* Restore proc. body: SP_TFERIADOS_RHNET */
create or alter procedure SP_TFERIADOS_RHNET (
    PRANOMESI integer,
    PRANOMESF integer,
    PRCODSINTRAB integer = null)
returns (
    BDCODEMP integer,
    BDCODEMPRHNET integer,
    BDDATAFER date,
    BDDESCFER varchar(50),
    BDCODCID integer,
    BDCODUF integer,
    BDREFFER integer,
    BDCODSINTRAB integer,
    BDDATAFERI date,
    BDCODFERI integer,
    BDFERIBANC DM_BOOLEAN,
    BDANO integer)
as
declare variable WANOI integer;
declare variable WANOF integer;
declare variable WSQL varchar(5000);
declare variable WMESDIA varchar(4);
declare variable WCODCIDEMP integer;
declare variable WCODUFEMP integer;
declare variable WTEMSIND smallint;
declare variable WCODSIND integer;
BEGIN
  wanoi = CAST((SUBSTRING(pranomesi FROM 1 FOR 4)) AS INTEGER);
  wanof = CAST((SUBSTRING(pranomesf FROM 1 FOR 4)) AS INTEGER);

  prcodsintrab = coalesce(prcodsintrab, 0);

  WHILE (wanoi <= wanof) DO
    BEGIN                                                                                         -- Data variável
      BDANO = wanoi;

      wsql = 'select BDCODUF, BDCODCID, BDDESCFERI, BDMESDIAFERI, BDCODSINTRAB, BDCODFERI, BDFERIBANC from TFERIADOSNOVO where BDTIPOFERI = 0'; --tcfFixo - Regra antes era <> 1

      if (prcodsintrab > 0) then
         wsql = wsql||' and BDCODSINTRAB = '||prcodsintrab;

      FOR EXECUTE STATEMENT wsql INTO :bdcoduf, :bdcodcid, :bddescfer, :wmesdia, :bdcodsintrab, :bdcodferi, :bdferibanc DO
        BEGIN
          IF (CAST((wanoi||SUBSTRING(wmesdia FROM 3 FOR 2)) AS INTEGER) >= pranomesi AND CAST((wanoi||SUBSTRING(wmesdia FROM 3 FOR 2)) AS INTEGER) <= pranomesf) THEN
             BEGIN
               BDCODEMPRHNET = null;
               bddatafer  = CAST((SUBSTRING(wmesdia FROM 3 FOR 2)||'-'||SUBSTRING(wmesdia FROM 1 FOR 2)||'-'||wanoi) AS DATE);
               bddataferi = CAST((SUBSTRING(wmesdia FROM 3 FOR 2)||'-'||SUBSTRING(wmesdia FROM 1 FOR 2)||'-'||wanoi) AS DATE);
               bdreffer = CAST((wanoi||SUBSTRING(wmesdia FROM 1 FOR 2)) AS INTEGER);

               for select BDCODEMP, coalesce(BDCODWEB, BDCODEMP) from TEMPRESAS where upper(coalesce(BDRHNET, 'FALSE')) = 'TRUE'
               into :BDCODEMP, :BDCODEMPRHNET
               do
                 begin
                   wtemsind = 1;

                   if (coalesce(BDCODSINTRAB, 0) > 0) then
                      begin
                        wtemsind = 0;
                        wcodsind = null;
                        select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where BDCODEMP = :BDCODEMP and BDCODSINTRAB = :BDCODSINTRAB into :wcodsind;

                        if (coalesce(wcodsind, 0) > 0 and wcodsind = BDCODSINTRAB) then
                           wtemsind = 1;
                      end


                   if (wtemsind = 0) then
                      continue;

                   if (bdcodemprhnet <= 0) then
                      bdcodemprhnet = bdcodemp;

                   wcodcidemp = null;
                   select first 1 BDCODCID from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :pranomesf order by BDCODEMP desc, BDREFEMP desc into :wcodcidemp;
                   wcodcidemp = coalesce(wcodcidemp, 0);

                   wcodufemp = null;
                   if (wcodcidemp > 0) then
                      select first 1 BDCODUF from TCIDADE where BDCODCID = :wcodcidemp into :wcodufemp;
                   wcodufemp = coalesce(wcodufemp, 0);

                   if ((coalesce(BDCODCID, 0) = 0 and coalesce(BDCODUF, 0) = 0) or
                       (coalesce(BDCODCID, 0) > 0 and coalesce(BDCODCID, 0) = wcodcidemp) or
                       (coalesce(BDCODCID, 0) = 0 and coalesce(BDCODUF, 0) > 0 and BDCODUF = wcodufemp)) then
                      SUSPEND;
                 end
             END
        END
                                                                                                                             --tcfVariavel
      wsql = 'select BDCODUF, BDCODCID, BDDESCFERI, BDDATAFERI, BDCODSINTRAB, BDCODFERI, BDFERIBANC from TFERIADOSNOVO where BDTIPOFERI = 1 and BDDATAFERI >= '''||'01-01-'||wanoi||''' and BDDATAFERI <= '''||'12-31-'||wanoI||'''';

      if (prcodsintrab > 0) then
         wsql = wsql||' and BDCODSINTRAB = '||prcodsintrab;

      FOR EXECUTE STATEMENT wsql INTO :bdcoduf, :bdcodcid, :bddescfer, :bddatafer, :bdcodsintrab, :bdcodferi, :bdferibanc DO
        BEGIN
          wmesdia = SUBSTRING(CAST(bddatafer AS VARCHAR(10)) FROM 6 FOR 2)||SUBSTRING(CAST(bddatafer AS VARCHAR(10)) FROM 9 FOR 2);
          IF (CAST((wanoi||SUBSTRING(wmesdia FROM 1 FOR 2)) AS INTEGER) >= pranomesi AND CAST((wanoi||SUBSTRING(wmesdia FROM 1 FOR 2)) AS INTEGER) <= pranomesf) THEN
             BEGIN
               BDCODEMPRHNET = null;
               bddataferi = bddatafer;
               bdreffer = CAST((SUBSTRING((CAST(bddatafer AS VARCHAR(10))) FROM 1 FOR 4)||SUBSTRING((CAST(bddatafer AS VARCHAR(10))) FROM 6 FOR 2)) AS INTEGER);

               for select BDCODEMP, coalesce(BDCODWEB, BDCODEMP) from TEMPRESAS where upper(coalesce(BDRHNET, 'FALSE')) = 'TRUE'
               into :BDCODEMP, :BDCODEMPRHNET
               do
                 begin
                   wtemsind = 1;

                   if (coalesce(BDCODSINTRAB, 0) > 0) then
                      begin
                        wtemsind = 0;
                        wcodsind = null;
                        select first 1 BDCODSINTRAB from VRH_EMP_TCOL_VINC where BDCODEMP = :BDCODEMP and BDCODSINTRAB = :BDCODSINTRAB into :wcodsind;

                        if (coalesce(wcodsind, 0) > 0 and wcodsind = BDCODSINTRAB) then
                           wtemsind = 1;
                      end

                   if (wtemsind = 0) then
                      continue;

                   if (bdcodemprhnet <= 0) then
                      bdcodemprhnet = bdcodemp;

                   wcodcidemp = null;
                   select first 1 BDCODCID from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :pranomesf order by BDCODEMP desc, BDREFEMP desc into :wcodcidemp;
                   wcodcidemp = coalesce(wcodcidemp, 0);

                   wcodufemp = null;
                   if (wcodcidemp > 0) then
                      select first 1 BDCODUF from TCIDADE where BDCODCID = :wcodcidemp into :wcodufemp;
                   wcodufemp = coalesce(wcodufemp, 0);

                   if ((coalesce(BDCODCID, 0) = 0 and coalesce(BDCODUF, 0) = 0) or
                       (coalesce(BDCODCID, 0) > 0 and coalesce(BDCODCID, 0) = wcodcidemp) or
                       (coalesce(BDCODCID, 0) = 0 and coalesce(BDCODUF, 0) > 0 and BDCODUF = wcodufemp)) then
                       SUSPEND;
                 end
             END
        END
      wanoi = wanoi + 1;
    END
END^

create or alter procedure SP_VERBAS_INCIDENCIAS
returns (
    BDCODVER integer,
    BDDESCVER varchar(300),
    BDREFVER integer,
    BDCODINCIDIRRF integer,
    BDDESCIRRF varchar(300),
    BDRENDISENTOIRVER varchar(5),
    BDINDRESC varchar(5),
    BDIMPISENTOS varchar(5),
    BDIMPINSSNORMAL varchar(5),
    BDIMPINSSFERIAS varchar(5),
    BDIMPINSS13 varchar(5),
    BDIMPINSSNAOINCIDE varchar(5),
    BDCODINCIDINSS integer,
    BDDESCINCINSS varchar(300),
    BDINSSSISTEMA integer,
    BDBASEGPS varchar(5))
as
declare variable wClass varchar(30);
begin
  /* Procedure Text */
--  suspend;
  for SELECT v.bdcodver,v.bddescver,ref.bdrefver, ref.bdcodincidirrf, ir.bddescirrf, ref.bdrendisentoirver, ref.bdindresc,
             ref.bdcodincidinss, inss.bddescinss, ref.bdinssver, ref.bdbasegpsver, v.bdclaver
      FROM vrh_base_tverbas_ref ref
      join vrh_base_tverbas v on ref.bdcodver = v.bdcodver
      left outer join VRH_ESOCIAL_TINCID_IRRF ir on ref.bdcodincidirrf = ir.bdcodirrf
      left outer join VRH_ESOCIAL_TINCID_INSS inss on ref.bdcodincidinss = inss.bdcodinss
      where char_length(v.bdclaver) = 13
      into :bdcodver,:bddescver,:bdrefver, :bdcodincidirrf, :bddescirrf, :bdrendisentoirver, :bdindresc,
           :bdcodincidinss, :bddescincinss, :bdinsssistema, :bdbasegps, :wClass
      do
      begin
        BDIMPISENTOS = 'FALSE';
        BDIMPINSSNORMAL = 'FALSE';
        BDIMPINSSFERIAS = 'FALSE';
        BDIMPINSS13 = 'FALSE';
        BDIMPINSSNAOINCIDE = 'FALSE';

        -- Isentos
        if (bdcodincidirrf = 79 and ((upper(bdindresc) = 'TRUE') or (upper(bdrendisentoirver) = 'FALSE'))) then
           BDIMPISENTOS = 'TRUE';
        if (bdcodincidirrf = 74 and ((upper(bdindresc) = 'FALSE') or (upper(bdrendisentoirver) = 'TRUE'))) then
           BDIMPISENTOS = 'TRUE';
        if ((bdcodincidirrf <> 79 and (bdcodincidirrf <> 74) and
           ((upper(bdindresc) = 'TRUE') or (upper(bdrendisentoirver) = 'TRUE')))) then
           BDIMPISENTOS = 'TRUE';

        if ((substring(:wclass from 1 for 9) = '6.080.0.0') and ((upper(bdbasegps) = 'TRUE')) AND (bdinsssistema = 0) and (bdcodincidinss = 12)) then
           begin
             -- Desconto de 13º no complmento o controle para o sistema é feito interno
           end
        else
        -- Verbas de INSS
        if ((bdcodincidinss in (31, 32, 34, 35, 51)) and ((upper(bdbasegps) = 'FALSE')) AND (bdinsssistema = 0)) then
           begin
             -- Não deve incluir
           end
        else
        -- INSS Folha normal
        if (bdinsssistema = 1) then
           begin
             if (bdcodincidinss in (21)) then
                begin
                  /* Verificar dados padr es as compentencia que deixaram de ser Base GPS */
                  if (bdrefver < 201511) then
                     begin
                       if (upper(bdbasegps) <> 'TRUE') then
                          BDIMPINSSNORMAL = 'TRUE';
                     end
                  else
                     begin
                       if (upper(bdbasegps) = 'TRUE') then
                          BDIMPINSSNORMAL = 'TRUE';
                     end
                end
             else
             --Deve ter incid ncia eSocial igual a 11, 15 ou 21.
             if (bdcodincidinss not in (11,15,21)) then
                BDIMPINSSNORMAL = 'TRUE';
             else
             --Base GPS deve estar marcada se a incidência de INSS for igual a folha normal e a incidência for eSocial for igual a 11.
             if ((bdbasegps = 'TRUE') and (bdcodincidinss <> 11)) then
                BDIMPINSSNORMAL = 'TRUE';
             else if ((bdbasegps = 'FALSE') and (bdcodincidinss = 11)) then
                BDIMPINSSNORMAL = 'TRUE';
           end
        -- INSS Férias
        else if (bdinsssistema = 2) then
           begin
             --Deve ter incidência eSocial igual a 0
             if (coalesce(bdcodincidinss,0) <> 0) then
                bdimpinssferias = 'TRUE';
             --Base GPS deve estar marcada se a incidência de INSS for igual a férias e a incidência for eSocial for igual a 0.
             else if (bdbasegps = 'FALSE') then
                bdimpinssferias = 'TRUE';
           end
        -- INSS 13º Salário
        else if (bdinsssistema = 3) then
           begin
             -- Deve ter incidência eSocial igual a 12, 16 ou 22
             if (bdcodincidinss in (22)) then
                begin
                  /* Verificar dados padr es as compentencia que deixaram de ser Base GPS */
                  if (bdrefver < 201511) then
                     begin
                       if (upper(bdbasegps) <> 'TRUE') then
                          BDIMPINSSNORMAL = 'TRUE';
                     end
                  else
                     begin
                       if (upper(bdbasegps) = 'TRUE') then
                          BDIMPINSSNORMAL = 'TRUE';
                     end
                end
             else
             if (bdcodincidinss not in (12,16,22)) then
                bdimpinss13 = 'TRUE';
             -- Base GPS deve estar marcada se a incidência de INSS for igual a 13º Salário e a incidência eSocial for igual a 12.
             else
             if ((bdbasegps = 'TRUE') and (bdcodincidinss <> 12)) then
                bdimpinss13 = 'TRUE';
             else if ((bdbasegps = 'FALSE') and (bdcodincidinss = 12)) then
                bdimpinss13 = 'TRUE';
           end
        -- INSS Não incide
        else if (bdinsssistema = 0) then
           begin
             --Deve ter incidência eSocial igual a 0, 1, 13 ou 14.
             if (bdcodincidinss not in (0,1,13,14)) then
                bdimpinssnaoincide = 'TRUE';
             -- Base GPS deve estar desmarcada se a incidência de INSS for igual a Não incide e a incidência eSocial for igual a 0.
             else if ((bdbasegps = 'TRUE') and (bdcodincidinss = 0)) then
                bdimpinssnaoincide = 'TRUE';
           end

        if ((BDIMPISENTOS = 'TRUE') or (BDIMPINSSNORMAL = 'TRUE') or (BDIMPINSSFERIAS = 'TRUE') or (BDIMPINSS13 = 'TRUE') or (BDIMPINSSNAOINCIDE = 'TRUE')) then
           suspend;
      end

end^


create or alter procedure SP_NCM_IS_EXCECAO (
    PRNCM varchar(20),
    PREXCECOES varchar(5000))
returns (
    ISEXCECAO smallint)
as
declare variable WITEM varchar(50);
declare variable WTEXTO varchar(5000);
declare variable WEXC varchar(20);
BEGIN
    ISEXCECAO = 0;

    IF (PREXCECOES IS NULL OR PREXCECOES = '') THEN
    BEGIN
        SUSPEND;
        EXIT;
    END

    WTEXTO = PREXCECOES || ';';

    WHILE (POSITION(';' IN WTEXTO) > 0) DO
    BEGIN
        WITEM = SUBSTRING(WTEXTO FROM 1 FOR POSITION(';' IN WTEXTO) - 1);
        WTEXTO = SUBSTRING(WTEXTO FROM POSITION(';' IN WTEXTO) + 1);

        /* remove apenas os pontos */
--        WEXC = REPLACE(WITEM, '.', '');

        /* compara por prefixo */
        if ((WITEM <> '') AND (PRNCM STARTING WITH WITEM)) THEN
        BEGIN
            ISEXCECAO = 1;
            SUSPEND;
            EXIT;
        END
    END

    SUSPEND;
END^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TRUBICA5002_BI0 FOR VRHF_TEMP_EMP_TRUBICA5002
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE VCODIGO INTEGER;
begin
  /* Trigger text */
  VCODIGO = 0;
  if ((new.BDSEQUENCIAL is null) or (new.BDSEQUENCIAL = 0)) then
  begin
    select coalesce((max(BDSEQUENCIAL) + 1), 1)
    from VRHF_TEMP_EMP_TRUBICA5002
    where BDSESSAO = NEW.BDSESSAO AND
          BDCODEMPORD = NEW.BDCODEMPORD AND
          BDCPFCOL = NEW.BDCPFCOL
    into VCODIGO;

    new.BDSEQUENCIAL = VCODIGO;
  end
end
^

CREATE OR ALTER TRIGGER VRHF_TEMP_EMP_TRUBICA5002_BIU0 FOR VRHF_TEMP_EMP_TRUBICA5002
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
as
  declare variable wnatrub integer;
  declare variable wtpcodver integer;
  declare variable wincir integer;
  declare variable wref integer;
  declare variable wdescver varchar(40);
  declare variable vcodigoord varchar(30);
  declare variable vcodverint integer;
  declare variable vnatrubint integer;
  declare variable vcodigorubint varchar(100);
  declare variable vdescrubint varchar(1000);
  declare variable vtprubrint integer;
  declare variable vincirint varchar(100);
begin
  if (new.bdcodver > 0) then
     begin
       select first 1 v.bdtipocodver, coalesce(v.bdcodincidirrf, 0) bdirver, r.bdchave,vr.bddescver
       from vrh_base_tverbas_ref v
       join vrh_base_trubricaesocial_ver r on r.bdcodver = v.bdcodver
       join vrh_base_tverbas vr on vr.bdcodver = v.bdcodver
       where v.bdcodver = new.bdcodver and
             v.bdrefver <= new.bdrefemissao
       order by v.bdcodver desc, v.bdrefver desc
       into :wtpcodver,:wincir,:wnatrub,:wdescver;

       new.bdnatrubrun = wnatrub;
       new.bdtprubrun = wtpcodver + 1; --ajuste entre unico e eSocial
       new.bdincirun = wincir;
       new.bdrefrubrun = new.bdrefemissao;

       new.bdtabrubrun = new.bdtabrubrica;
       new.bdcodrubrun = new.bdcodrubrica;

       new.bddescver   = wdescver;

       select * from preenche_esquerda(new.bdcodrubrun,30,'0') into :vcodigoord;
       new.bdcodrubricaord = vcodigoord;
     end

  if ((new.bddescver is null) or (new.bddescver = ''))  then
     new.bddescver = 'Rubrica eSocial';

  if (new.bdcodver is null) then
     begin
       for select bdcodver,bdnatrubr,bdcodrubr,bddescrubr,bdtiporubr,bdcodincirrf
           from  vrh_emp_tconfiguracoes_verbas_manuais
           into :vcodverint,:vnatrubint,:vcodigorubint,:vdescrubint,:vtprubrint,:vincirint
       do
         begin
           if (upper(NEW.BDCODRUBRICA) = upper(vcodigorubint)) then
              begin
                NEW.BDNATRUBRUN = vnatrubint;
                NEW.BDTPRUBRUN = vtprubrint;
                NEW.BDINCIRUN = vincirint;
                NEW.BDDESCVER = vdescrubint;
                new.bdtabrubrun = new.bdtabrubres;
                new.bdcodrubrun = new.bdcodrubres;
                new.bdrefrubrun = new.bdrefrubres;

                select * from preenche_esquerda(new.bdcodrubrun,30,'0') into :vcodigoord;
                new.bdcodrubricaord = vcodigoord;
              end
         end
     end
end^

CREATE OR ALTER TRIGGER VRHF_EMP_TCOL_CALC_BIU0 FOR VRHF_EMP_TCOL_CALC
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
begin
  if (new.bdaulista is null) then
     new.bdaulista = FALSE;

  if (new.bdcontsindical is null) then
     new.bdcontsindical = 'FALSE';
end
^



create or alter procedure SP_MATRIZ_E_FILIAIS (
    PRCODEMP varchar(30000))
returns (
    bdcodemp integer)
as
declare variable WSQL varchar(30000);
declare variable WSQL2 varchar(3000);
declare variable WMATRIZ integer;
begin
  /* Procedure Text */

  -- Carrega a relação de todas as matriz das empresas selecionas
  wsql = 'select coalesce(emp.bdcodmatriz,emp.bdcodemp) bdcodmatriz from tempresas emp ';

  if (position('TMP_EMPRESAS_SELECT',upper(prcodemp)) > 0) then
     wsql = wsql||' join TMP_EMPRESAS_SELECT filtro on (emp.bdcodemp = filtro.bdcodemp)';
  else if (coalesce(prcodemp,'') <> '') then
     begin
       wsql = wsql||' where '||prcodemp;
     end

  wsql = wsql||' group by bdcodmatriz';

  for execute statement wsql into :wmatriz do
    begin
      bdcodemp = wmatriz;
      suspend;

      for select bdcodemp from tempresas where bdcodmatriz = :wmatriz into :bdcodemp do
        suspend;
    end

--  suspend;
end^

create or alter procedure SP_VINCULO_ATUAL_NAO_COL (
    PRMATRIZ integer,
    PRCPF varchar(20),
    PRANO integer)
returns (
    BDCPF varchar(20),
    BDREF integer,
    BDORIGEM integer,
    BDDATA date,
    BDCODEMP integer)
as
begin

 for
   SELECT X.BDCPF, X.BDREF, X.ORIGEM, X.BDDATA, X.BDCODEMP FROM (
    --reclamatoria
    select 2 ORIGEM, IR.BDCPF, IR.BDREFPGTO BDREF, IR.BDCODEMP, null BDDATA     -- 1 BDEHCOL, 'RT' ORIGEM, REC.BDNOMCOL, REC.BDCODCOL
    from VRH_EMP_IRRF_TENCARGOS_RT IR
    join TEMPRESAS EMP on (EMP.BDCODEMP = IR.BDCODEMP)
    left outer join VRH_EMP_TRECLAMATORIA REC on (REC.BDCODEMP = IR.BDCODEMP
        and REC.BDCODRT = IR.BDCHAVE and REC.BDCPFCOL = IR.BDCPF)
    INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = IR.BDCODEMP)
    where (REC.BDCODCOL is null) and
          (IR.BDCPF = :PRCPF) and
          (IR.BDREFPGTO between :PRANO||'01' and :PRANO||'12') and
          (coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP) = :PRMATRIZ)

    union
    -- valores manuais
    select 3 ORIGEM, A.BDCPFCOL BDCPF, A.BDANOFUNC||'12' BDREF, A.BDCODEMP, null BDDATA     --1 BDEHCOL, 'MANUAL' ORIGEM,  A.BDNOMCOL, null BDCODCOL
    from (select VLCPF.BDCODEMP, VLCPF.BDCPFCOL, VLCPF.BDANOFUNC
          from VRH_EMP_TCOLCON_ANO_CPF VLCPF
          INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = VLCPF.BDCODEMP)
          join TEMPRESAS EMP on (EMP.BDCODEMP = VLCPF.BDCODEMP)
          join TEMPRESAS_REF EMPREF on (EMPREF.BDCODEMP = VLCPF.BDCODEMP and
                EMPREF.BDREFEMP = (select first 1 X.BDREFEMP
                                   from TEMPRESAS_REF X
                                   where X.BDCODEMP = VLCPF.BDCODEMP and
                                         X.BDREFEMP <= (VLCPF.BDANOFUNC * 100 + 12)
                                   order by X.BDREFEMP desc))
          where VLCPF.BDANOFUNC = :PRANO and
                (VLCPF.BDCPFCOL = :PRCPF) and
                (coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP) = :PRMATRIZ)
                ) A

        union
        --autonomo
        select 1 ORIGEM, TER.BDCGCTER BDCPF, TERC.BDREFTER BDREF, TERC.BDCODEMP, TERC.BDDATASERV BDDATA   --0 BDEHCOL, 'SERV' ORIGEM, TRF.BDNOMETER, null BDCODCOL
        from TTERCEIRO TER
        inner join(select TERC.BDCODEMP, TERC.BDCODTER , coalesce(CALC.BDREFIRRFESOCIAL, TERC.BDREFPAGSERV) BDREFTER, TERC.BDDATASERV
                   from  TTERCEIRO T
                   join  VRH_BASE_TSERVTERC TERC on terc.bdcodter = t.bdcodter
                   INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON(EMPSEL.BDCODEMP = TERC.BDCODEMP)
                   join TEMPRESAS EMP on (EMP.BDCODEMP = TERC.BDCODEMP)
                    left join VRHF_BASE_CALC_TERC CALC on (TERC.BDCODTER = CALC.BDCODTER and
                         TERC.BDCODEMP = CALC.BDCODEMP and
                         TERC.BDCODSERV = CALC.BDCODSERV)
                   inner join TEMPRESAS E on E.BDCODEMP = TERC.BDCODEMP and
                         upper(E.BDEXPINIESOCIAL) = 'TRUE'
                  where (coalesce(CALC.BDREFIRRFESOCIAL, TERC.BDREFPAGSERV) BETWEEN :PRANO||'01' and :PRANO||'12')
                    and (t.BDCGCTER = :PRCPF)
                    and (coalesce(EMP.BDCODMATRIZ, EMP.BDCODEMP) = :PRMATRIZ)                  
                 )  TERC on TERC.BDCODTER = TER.BDCODTER
   ) X order by X.BDCPF, X.BDREF desc, X.ORIGEM desc, X.BDDATA desc, X.BDCODEMP

 into
    :BDCPF,
    :BDREF,
    :BDORIGEM,
    :BDDATA,
    :BDCODEMP
 do
    begin
       if (:BDCODEMP = :PRMATRIZ) then
        begin
            suspend;
            exit;
        end
    end

  suspend;
end^


/* Trigger: VSUC_BANCOS_PDF_BI0 */
CREATE OR ALTER TRIGGER VSUC_BANCOS_PDF_BI0 FOR VSUC_BANCOS_PDF
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE WCODIGO INTEGER;
BEGIN
  IF ((NEW.BDCODBAN IS NULL) OR (NEW.BDCODBAN = 0))  THEN
     BEGIN
       SELECT COALESCE(MAX(BDCODBAN)+1,1) FROM VSUC_BANCOS_PDF INTO :WCODIGO;
       NEW.BDCODBAN = WCODIGO;
     END
END^

create or alter procedure SP_VSUC_EXPORTA_LAN_SIS (
    PRNOMESIS varchar(100),
    PRCODCCSIS varchar(5),
    PRCODFILIALSIS varchar(5),
    PRCONTASSIS varchar(5),
    PREMPRESASSIS varchar(5),
    PRCODCLSIS varchar(5),
    PRCODTERSIS varchar(5),
    PRCODNACSIS varchar(5),
    PRCODTFUCSIS varchar(5),
    PRCODNIVELTFUCSIS varchar(5),
    PRCODVERBASIS varchar(5),
    PRCODTPOFOLSIS varchar(5),
    PRCODHISTSIS varchar(5),
    PRCODSISTPLA boolean,
    PRAGRUPARLAN boolean,
    PRWHERE varchar(2000),
    PRDATAINI date,
    PRDATAFIM date)
returns (
    BDCODSIS integer,
    BDCODEMP integer,
    BDCODEMPNOVO varchar(100),
    BDCODPLAPADRAO integer,
    BDDEBITO varchar(100),
    BDCREDITO varchar(100),
    BDDATA date,
    BDVALOR numeric(18,2),
    BDCHAVEON varchar(120),
    BDDCTO varchar(15),
    BDCODHIST integer,
    BDTIPOLAN integer,
    BDCODTPHI integer,
    BDDEBCRE integer,
    BDCONCD varchar(200),
    BDCODCENTRO integer,
    BDCCDEB varchar(100),
    BDCCCRED varchar(100),
    BDCOMPL varchar(200),
    BDNOMEHIST varchar(100),
    BDTRANSACAO integer,
    BDPERCRATEIO numeric(18,4),
    BDVALRATEIO numeric(18,2),
    BDCODTERCEIROD integer,
    BDCODTERCEIROC integer,
    BDCHAVEONLINE varchar(120),
    BDCOMPLEMENTO varchar(200))
as
declare variable WCODMAIORQMIL integer;
declare variable WSQL varchar(22480);
declare variable WDATAINI varchar(10);
declare variable WDATAFIM varchar(10);
begin
  BDCODSIS = NULL;
    
  SELECT BDCODSIS
  FROM VSUC_EXPORTA_SIS
  WHERE UPPER(BDNOMESIS) = UPPER(:PRNOMESIS)
  INTO :BDCODSIS;

  IF (BDCODSIS IS NULL) THEN
    BEGIN
       SELECT COALESCE(MAX(BDCODSIS), 1000) + 1
        FROM VSUC_EXPORTA_SIS
        WHERE BDCODSIS >= 1000
        INTO :BDCODSIS;
    
        UPDATE OR INSERT INTO VSUC_EXPORTA_SIS
            (BDCODSIS, BDNOMESIS, BDCODCCSIS, BDCODFILIALSIS, BDCONTASSIS,
             BDEMPRESASIS, BDCODCOLSIS, BDCODTERSIS, BDCODNACSIS, BDCODTFUCSIS,
             BDCODNIVELTFUCSIS, BDCODVERBASIS, BDCODTIPOFOLSIS, BDCODHISTSIS, BDCODSISTPLA)
        VALUES
            (:BDCODSIS, :PRNOMESIS, :PRCODCCSIS, :PRCODFILIALSIS, :PRCONTASSIS,
             :PREMPRESASSIS, :PRCODCLSIS, :PRCODTERSIS, :PRCODNACSIS, :PRCODTFUCSIS,
             :PRCODNIVELTFUCSIS, :PRCODVERBASIS, :PRCODTPOFOLSIS, :PRCODHISTSIS, :PRCODSISTPLA)
        MATCHING (BDCODSIS);
    END


  if ((:prwhere is null) and (:prdataini is null) and (:prdatafim is null)) then
    BEGIN
      suspend;
      exit;
    END
    wDATAINI = LPAD(CAST(EXTRACT(MONTH FROM PRDATAINI) AS VARCHAR(2)), 2, '0')||'/'||
               LPAD(CAST(EXTRACT(DAY   FROM PRDATAINI) AS VARCHAR(2)), 2, '0')||'/'||
               CAST(EXTRACT(YEAR FROM PRDATAINI) AS VARCHAR(4));
    
    wDATAFIM = LPAD(CAST(EXTRACT(MONTH FROM PRDATAFIM) AS VARCHAR(2)), 2, '0')||'/'||
               LPAD(CAST(EXTRACT(DAY   FROM PRDATAFIM) AS VARCHAR(2)), 2, '0')||'/'||
               CAST(EXTRACT(YEAR FROM PRDATAFIM) AS VARCHAR(4));

  /* EXPORTAÇÃO */
  IF (:PRAGRUPARLAN) THEN
     BEGIN    
      WSQL = 'select substring(BDCHAVEONLINE from position('||'''-'''||', BDCHAVEONLINE) + 1) as BDCHAVEON, LAN.BDDCTO, LAN.BDCODHIST, ';
      wSQL = wSQL||' LAN.BDTIPOLAN, sum(LAN.BDVALOR) as BDVALOR, LAN.BDCODEMP, cast(LAN.BDCREDITO as varchar(100)) BDCREDITO, ';
      wSQL = wSQL||' cast(LAN.BDDEBITO as varchar(100)) BDDEBITO, LAN.BDDATA, LAN.BDCODTPHI, LAN.BDCONCD, ';
      wSQL = wSQL||' cast(LAN.BDCCDEB as varchar(100)) BDCCDEB, LAN.BDCOMPL, cast(LAN.BDCCCRED as varchar(100)) BDCCCRED, ';
      wSQL = wSQL||' HIST.BDNOME as BDNOMEHIST, min(LAN.BDTRANSACAO) as BDTRANSACAO, BDDEBCRE, LAN.BDCODTERCEIROD, LAN.BDCODTERCEIROC, ';
      wSQL = wSQL||' cast(LAN.BDCODEMP as varchar(100)) BDCODEMPNOVO, LAN.BDCODCENTRO ';
      wSQL = wSQL||' from (select BDCHAVEONLINE, ';
      wSQL = wSQL||'       case ';
      wSQL = wSQL||'         when position('||'''col.'''||', BDCOMPL) > 0 then substring(BDCOMPL from 1 for position('||'''COL.'''||', BDCOMPL) - 1) ';
      wSQL = wSQL||'         else BDCOMPL ';
      wSQL = wSQL||'       end as BDCOMPL, ';
      wSQL = wSQL||'       LAN.BDCODHIST, LAN.BDTIPOLAN, LAN.BDCODEMP, LAN.BDTRANSACAO, 0 as BDCREDITO, LAN.BDDEBITO, LAN.BDDATA, ';
      wSQL = wSQL||'       LAN.BDCODTPHI, coalesce(CCDEB.BDVALOR, LAN.BDVALOR) as BDVALOR, null as BDCCCRED, BDCONCD, ';
      wSQL = wSQL||'       CCDEB.BDCODTPCC as BDCCDEB, LAN.BDDCTO, 0 as BDDEBCRE, LAN.BDCODTERCEIROD, LAN.BDCODTERCEIROC, CCDEB.BDCODCENTRO';
      wSQL = wSQL||' from VW_VSUC_TLAN_EXPORTACAO LAN ';
      wSQL = wSQL||' left join VSUC_EMPRESAS_TLCC CCDEB on (LAN.BDCODEMP = CCDEB.BDCODEMP and ';
      wSQL = wSQL||'      LAN.BDCHAVE = CCDEB.BDCHAVE and ';
      wSQL = wSQL||'      CCDEB.BDDEBCRE = 0) ';
      wSQL = wSQL||' where LAN.BDDEBITO is not null ';
      wSQL = wSQL||' union all ';
      wSQL = wSQL||' select BDCHAVEONLINE, ';
      wSQL = wSQL||'       case ';
      wSQL = wSQL||'         when position('||'''col.'''||', BDCOMPL) > 0 then substring(BDCOMPL from 1 for position('||'''col.'''||', BDCOMPL) - 1) ';
      wSQL = wSQL||'         else BDCOMPL ';
      wSQL = wSQL||'       end as BDCOMPL, ';
      wSQL = wSQL||'       LAN.BDCODHIST, LAN.BDTIPOLAN, LAN.BDCODEMP, LAN.BDTRANSACAO, LAN.BDCREDITO, 0 as BDDEBITO, LAN.BDDATA, ';
      wSQL = wSQL||'       LAN.BDCODTPHI, coalesce(CCDEB.BDVALOR, LAN.BDVALOR) as BDVALOR, CCDEB.BDCODTPCC as BDCCCRED, BDCONCD, ';
      wSQL = wSQL||'       null as BDCCDEB, LAN.BDDCTO, 1 as BDDEBCRE, LAN.BDCODTERCEIROD, LAN.BDCODTERCEIROC, CCDEB.BDCODCENTRO ';
      wSQL = wSQL||' from VW_VSUC_TLAN_EXPORTACAO LAN ';
      wSQL = wSQL||' left join VSUC_EMPRESAS_TLCC CCDEB on (LAN.BDCODEMP = CCDEB.BDCODEMP and ';
      wSQL = wSQL||'      LAN.BDCHAVE = CCDEB.BDCHAVE and ';
      wSQL = wSQL||'      CCDEB.BDDEBCRE = 1) ';
      wSQL = wSQL||' where LAN.BDCREDITO is not null) LAN ';
      wSQL = wSQL||'  left join HIST_TPHI HIST on (LAN.BDCODHIST = HIST.BDCODHIST and ';
      wSQL = wSQL||'      LAN.BDCODTPHI = HIST.BDCODTPHI) ';
      wSQL = wSQL||' where '||:PRWHERE||' and ';
      wSql = wSql||' LAN.BDDATA between '''||wDATAINI||''' and '''||wdatafim||'''';
      wSQL = wSQL||'  group by LAN.BDCODHIST, LAN.BDTIPOLAN, LAN.BDCODEMP, LAN.BDCREDITO, LAN.BDDEBITO, LAN.BDDATA, LAN.BDCODTPHI, LAN.BDCCDEB, LAN.BDCOMPL, LAN.BDCCCRED, BDNOMEHIST, BDCHAVEONLINE, BDDEBCRE, LAN.BDDCTO, LAN.BDCONCD, LAN.BDCODTERCEIROD, LAN.BDCODTERCEIROC, BDCODEMPNOVO, LAN.BDCODCENTRO ';
      wSQL = wSQL||'  order by LAN.BDDATA, BDTRANSACAO   ';

       FOR EXECUTE STATEMENT wsql
           INTO BDCHAVEON, BDDCTO, BDCODHIST, BDTIPOLAN, BDVALOR, BDCODEMP,
                BDCREDITO, BDDEBITO, BDDATA, BDCODTPHI, BDCONCD, BDCCDEB,
                BDCOMPL, BDCCCRED, BDNOMEHIST, BDTRANSACAO, BDDEBCRE,
                BDCODTERCEIROD, BDCODTERCEIROC, BDCODEMPNOVO, BDCODCENTRO
       DO
       BEGIN
         SUSPEND;
       END
     END
   else
     BEGIN        
        Wsql = 'select substring(BDCHAVEONLINE from position('||'''-'''||', LAN.BDCHAVEONLINE) + 1) as BDCHAVEON, LAN.*, ';
        wSql = wSql||' HIST.BDNOME as BDNOMEHIST';
        wSql = wSql||' from (select LAN.BDCODPLAPADRAO, LAN.BDCHAVEONLINE, LAN.BDCOMPL, LAN.BDDCTO, LAN.BDCODHIST, LAN.BDTIPOLAN, LAN.BDCODEMP, ';
        wSql = wSql||' cast(LAN.BDCODEMP as varchar(100)) BDCODEMPNOVO, LAN.BDTRANSACAO, 0 as BDCREDITO, ';
        wSql = wSql||' cast(LAN.BDDEBITO as varchar(100)) BDDEBITO, LAN.BDDATA, LAN.BDCODTPHI, ';
        wSql = wSql||'                 coalesce(CCDEB.BDVALOR, LAN.BDVALOR) as BDVALOR, null as BDCCCRED, ';
        wSql = wSql||'                 cast(CCDEB.BDCODTPCC as varchar(100)) BDCCDEB, 0 as BDDEBCRE, ';
        wSql = wSql||'                 (coalesce(LAN.BDVALOR, 0) * coalesce(CCDEB.BDVALOR, 0)) / 100 as BDPERCRATEIO, ';
        wSql = wSql||'                 coalesce(CCDEB.BDVALOR, 0) as BDVALRATEIO, BDCONCD, LAN.BDCODTERCEIROD, LAN.BDCODTERCEIROC, CCDEB.BDCODCENTRO ';
        wSql = wSql||'          from VW_VSUC_TLAN_EXPORTACAO LAN ';
        wSql = wSql||'          left join VSUC_EMPRESAS_TLCC CCDEB on (LAN.BDCODEMP = CCDEB.BDCODEMP and ';
        wSql = wSql||'                LAN.BDCHAVE = CCDEB.BDCHAVE and ';
        wSql = wSql||'                CCDEB.BDDEBCRE = 0) ';
        wSql = wSql||'          where LAN.BDDEBITO is not null ';
        wSql = wSql||'          union all ';
        wSql = wSql||'          select LAN.BDCODPLAPADRAO, LAN.BDCHAVEONLINE, LAN.BDCOMPL, LAN.BDDCTO, LAN.BDCODHIST, LAN.BDTIPOLAN, LAN.BDCODEMP, ';
        wSql = wSql||'                 cast(LAN.BDCODEMP as varchar(100)) BDCODEMPNOVO, LAN.BDTRANSACAO, ';
        wSql = wSql||'                 cast(LAN.BDCREDITO as varchar(100)) BDCREDITO, 0 as BDDEBITO, LAN.BDDATA, LAN.BDCODTPHI, ';
        wSql = wSql||'                 coalesce(CCDEB.BDVALOR, LAN.BDVALOR) as BDVALOR, cast(CCDEB.BDCODTPCC as varchar(100)) BDCCCRED, ';
        wSql = wSql||'                 null as BDCCDEB, 1 as BDDEBCRE, ';
        wSql = wSql||'                 (coalesce(LAN.BDVALOR, 0) * coalesce(CCDEB.BDVALOR, 0)) / 100 as BDPERCRATEIO, ';
        wSql = wSql||'                 coalesce(CCDEB.BDVALOR, 0) as BDVALRATEIO, BDCONCC, LAN.BDCODTERCEIROD, LAN.BDCODTERCEIROC, CCDEB.BDCODCENTRO ';
        wSql = wSql||'          from VW_VSUC_TLAN_EXPORTACAO LAN ';
        wSql = wSql||'          left join VSUC_EMPRESAS_TLCC CCDEB on (LAN.BDCODEMP = CCDEB.BDCODEMP and ';
        wSql = wSql||'                LAN.BDCHAVE = CCDEB.BDCHAVE and ';
        wSql = wSql||'                CCDEB.BDDEBCRE = 1) ';
        wSql = wSql||'          where LAN.BDCREDITO is not null) LAN ';
        wSql = wSql||'    left join HIST_TPHI HIST on (LAN.BDCODHIST = HIST.BDCODHIST and ';
        wSql = wSql||'          LAN.BDCODTPHI = HIST.BDCODTPHI) ';
        wSQL = wSQL||' where  '||:prwhere||' and ';
        wSql = wSql||' LAN.BDDATA between '''||wDATAINI||''' and '''||wdatafim||'''';
        wSql = wSql||'    order by LAN.BDDATA, LAN.BDTRANSACAO ';
       

        FOR EXECUTE STATEMENT wsql 
          INTO BDCHAVEON, BDCODPLAPADRAO, BDCHAVEONLINE, BDCOMPL, BDDCTO, BDCODHIST,
             BDTIPOLAN, BDCODEMP, BDCODEMPNOVO, BDTRANSACAO, BDCREDITO, BDDEBITO, 
             BDDATA, BDCODTPHI, BDVALOR, BDCCCRED, BDCCDEB, BDDEBCRE, BDPERCRATEIO,
             BDVALRATEIO, BDCONCD, BDCODTERCEIROD, BDCODTERCEIROC, BDCODCENTRO, BDNOMEHIST
        DO
        BEGIN
            SUSPEND;
        END
     END
end^

create or alter procedure SP_VEF_APURACAO_IRCSLL (
    PRCODEMP integer,
    PRANOAPU integer,
    PRCODQIRLP integer,
    PRRECEITAMESAPURACAO DM_NUMERIC_15_2)
returns (
    BDCODEMP integer,
    BDCODQIRLP integer,
    BDBASECALC_1_6 DM_NUMERIC_15_2,
    BDBASECALC_1_76 DM_NUMERIC_15_2,
    BDVALORIR_1_6 DM_NUMERIC_15_2,
    BDVALORIR_1_76 DM_NUMERIC_15_2,
    BDBASECALC_8 DM_NUMERIC_15_2,
    BDBASECALC_8_8 DM_NUMERIC_15_2,
    BDVALORIR_8 DM_NUMERIC_15_2,
    BDVALORIR_8_8 DM_NUMERIC_15_2,
    BDBASECALC_12 DM_NUMERIC_15_2,
    BDBASECALC_13_2 DM_NUMERIC_15_2,
    BDVALORIR_12 DM_NUMERIC_15_2,
    BDVALORIR_13_2 DM_NUMERIC_15_2,
    BDBASECALC_16 DM_NUMERIC_15_2,
    BDBASECALC_17_6 DM_NUMERIC_15_2,
    BDVALORIR_16 DM_NUMERIC_15_2,
    BDVALORIR_17_6 DM_NUMERIC_15_2,
    BDBASECALC_32 DM_NUMERIC_15_2,
    BDBASECALC_35_2 DM_NUMERIC_15_2,
    BDVALORIR_32 DM_NUMERIC_15_2,
    BDVALORIR_35_2 DM_NUMERIC_15_2,
    BDBASECALCIR DM_NUMERIC_15_2,
    BDVALORIRPJ DM_NUMERIC_15_2,
    BDVALORADICIONAL DM_NUMERIC_15_2,
    BDVALORTOTALDEDUCAO DM_NUMERIC_15_2)
as
declare variable WVALOR_TRIMESTRE numeric(15,10) = 0;
declare variable WVALOR_EXCEDENTE_TRIMESTRE numeric(15,10) = 0;
declare variable WVALOR_EXCEDENTETOTAL_TRIMESTRE numeric(15,10) = 0;
declare variable WEXCEDENTEDOTOTALANUAL numeric(15,10) = 0;
declare variable WRAZAO numeric(15,10) = 0;
declare variable WCALCRAZAO numeric(15,10) = 0;
declare variable WBASE_1_6 numeric(15,10) = 0;
declare variable WBASE_1_76 numeric(15,10) = 0;
declare variable WBASE_8 numeric(15,10) = 0;
declare variable WBASE_8_8 numeric(15,10) = 0;
declare variable WBASE_12 numeric(15,10) = 0;
declare variable WBASE_13_2 numeric(15,10) = 0;
declare variable WBASE_16 numeric(15,10) = 0;
declare variable WBASE_17_6 numeric(15,10) = 0;
declare variable WBASE_32 numeric(15,10) = 0;
declare variable WBASE_35_2 numeric(15,10) = 0;
declare variable BDVALORIRPJ_ANT numeric(15,10) = 0;
declare variable BDVALORADICIONAL_ANT numeric(15,10) = 0;
declare variable WNOVOVALORBASE numeric(15,10) = 0;
declare variable WPERCPROPORCIONALBASES numeric(15,10) = 0;
declare variable WPERCPROPORCIONALBASESEXCEDENTE numeric(15,10) = 0;
declare variable WTRIMESTRE integer = 0;
declare variable WDATAREGISTROEMP date;
declare variable WREFERENCIA integer;
declare variable WVALORREDUCAO numeric(15,10) = 0;
declare variable WMES01 integer = 0;
declare variable WMES12 integer = 0;
declare variable WDESCONTOLIMITEANUAL numeric(12,2) = 0;
BEGIN
    BDVALORTOTALDEDUCAO = 0;

    WMES01 = (:PRANOAPU * 100) + 1;
    WMES12 = (:PRANOAPU * 100) + 12;

    select first 1 a.BDDATAINIATIVEMP from tempresas a where bdcodemp = :PRCODEMP
    into :WDATAREGISTROEMP;

    :WDESCONTOLIMITEANUAL = 0;
    /* no imposto CSLL nao considera janeiro de 2026 por isso é descontado o 1250000 */
    if ((:PRANOAPU = 2026) and (:prcodqirlp = 3)) then
       begin
        :WDESCONTOLIMITEANUAL = 1250000;
       end

    if (:PRANOAPU = extract(year from :WDATAREGISTROEMP)) then
       begin
         if (extract(Month from :WDATAREGISTROEMP) in (4,5,6)) then
            WDESCONTOLIMITEANUAL = 1250000;
         else
         if (extract(Month from :WDATAREGISTROEMP) in (7,8,9)) then
            WDESCONTOLIMITEANUAL = 2500000;
         else
         if (extract(Month from :WDATAREGISTROEMP) in (10,11,12)) then
            WDESCONTOLIMITEANUAL = 3750000;
       end

    SELECT SUM(A.BDEXCEDENTETRIMESTRE) AS BDVALOR_EXCEDENTE_TRIMESTRE,
     case :PRCODQIRLP
       when 2 then ((MAX(A.BDRECEITAACUMULADA) + :PRRECEITAMESAPURACAO) - (MAX(L.BDVALORLIMITEANUALIRPJ) - :WDESCONTOLIMITEANUAL))
       when 3 then ((MAX(A.BDRECEITAACUMULADA) + :PRRECEITAMESAPURACAO) - (MAX(L.BDVALORLIMITEANUALCSLL) - :WDESCONTOLIMITEANUAL))
      else
       0
     end as BDVALORLIMITEANUAL
    FROM VEF_EMP_TIRLPGERREGRECEITAS A
    JOIN VEF_BASE_TLIMITERECEITAIRLP L ON L.BDCODLIMITE = A.BDCODLIMITE
    WHERE A.BDCODEMP = :PRCODEMP AND
          A.BDCODQIRLP = :PRCODQIRLP AND
          A.BDREFERENCIA BETWEEN :WMES01 AND :WMES12
    GROUP BY A.BDCODPERIODO, A.BDCODEMP, A.BDCODQIRLP  
    INTO :WVALOR_EXCEDENTETOTAL_TRIMESTRE, :WEXCEDENTEDOTOTALANUAL;

    if (:WVALOR_EXCEDENTETOTAL_TRIMESTRE < :WEXCEDENTEDOTOTALANUAL) then
       exit;

    FOR SELECT A.BDCODEMP, A.BDCODQIRLP, A.bdreferencia, A.BDEXCEDENTETRIMESTRE,
               A.BDTRIMESTRE,
               A.BDRECEITATRIMESTRE,
               COALESCE(A.BDBASE_1_6, 0), COALESCE(A.BDBASE_1_76, 0), COALESCE(A.BDBASE_8, 0), COALESCE(A.BDBASE_8_8, 0), COALESCE(A.BDBASE_12, 0), COALESCE(A.BDBASE_13_2, 0), COALESCE(A.BDBASE_16, 0), COALESCE(A.BDBASE_17_6, 0), COALESCE(A.BDBASE_32, 0), COALESCE(A.BDBASE_35_2, 0),
               A.BDVALORIRPJ, A.BDVALORADICIONAL
        FROM VEF_EMP_TIRLPGERREGRECEITAS A
        WHERE A.BDCODEMP = :PRCODEMP AND A.BDCODQIRLP = :PRCODQIRLP AND (A.BDBASE_1_6 > 0 OR A.BDBASE_8 > 0 OR A.BDBASE_12 > 0 OR A.BDBASE_16 > 0 OR A.BDBASE_32 > 0) AND (A.BDREFERENCIA BETWEEN :WMES01 AND :WMES12)
    INTO :BDCODEMP, :BDCODQIRLP, :WREFERENCIA, :WVALOR_EXCEDENTE_TRIMESTRE, :WTRIMESTRE, :WVALOR_TRIMESTRE, :WBASE_1_6, :WBASE_1_76, :WBASE_8, :WBASE_8_8, :WBASE_12, :WBASE_13_2, :WBASE_16, :WBASE_17_6, :WBASE_32, :WBASE_35_2, BDVALORIRPJ_ANT, BDVALORADICIONAL_ANT
    DO
    BEGIN

      /* se vier valor negativo significa que nos trimestres alteriores a apuração nao ultrapassou o limite anual, nesse caso só joga 0 e segue o calculo pois pode ter passado somente no trimestre*/
      if (WEXCEDENTEDOTOTALANUAL < 0) then
         WEXCEDENTEDOTOTALANUAL = 0;

      :BDVALORTOTALDEDUCAO = 0;

      /* aqui para cada trimestre ele considera 20 mil para cada mes, se a empresa for aberta no mes 2 por exemplo a apuração de março vai considerar somente 40 mil nesse calculo de redução */
      :WVALORREDUCAO = 60000;
      if (extract(year from :WDATAREGISTROEMP) = cast(:WREFERENCIA / 100 as integer)) then
       begin
         if (extract(Month from :WDATAREGISTROEMP) = (MOD(:WREFERENCIA, 100))) then
            begin
             if (MOD(:WREFERENCIA, 100) in (1,4,7,10)) then
               :WVALORREDUCAO = 60000;
             if (MOD(:WREFERENCIA, 100) in (2,5,8,11)) then
               :WVALORREDUCAO = 40000;
             if (MOD(:WREFERENCIA, 100) in (3,6,9,12)) then
               :WVALORREDUCAO = 20000;
            end
       end

      /* Faz o calculo para encontrar o percentual de quanto foi pago a mais em cada apuração dos trimestres anterioes
         Ex. 1° trimestre foi pago 50 mil de excedente e no 2° foi pago 750 mil, mas no total anual só passou 48 mil, aqui ele vai pegar o proporcional
         de quanto deve ser pago para cada trimestre 50000 / 800000 = 6,25% -- 750000 / 800000 = 93,75%*/

      if ((:WVALOR_EXCEDENTE_TRIMESTRE = 0) or (:WVALOR_EXCEDENTETOTAL_TRIMESTRE = 0)) then
         Continue;

      WRAZAO = CAST(:WVALOR_EXCEDENTE_TRIMESTRE * 100 AS NUMERIC(12,9)) / CAST(:WVALOR_EXCEDENTETOTAL_TRIMESTRE AS NUMERIC(12,9));

      /* Multiplica a razão pela excedente real anual Ex. 48000 * 6,25 = 3000 -- 48000 * 93,75 */
      WCALCRAZAO = (WEXCEDENTEDOTOTALANUAL * :WRAZAO) / 100;

      /* Subtrai o valor pago no trimestre pela Calculo da razão, nesse caso ja desconsidera o limite trimestral Ex. nesses exemplo acima o 1º Trimestre foi de 1300000
         como o limite trimestral era de 1250000 foi calculado o 1250000 nos 8%, agora nessa parte ele vai pegar o 1300000 bruto e descontar a razao de calculo, nesse caso 1297000 no 8%*/
      WNOVOVALORBASE = :WVALOR_TRIMESTRE - WCALCRAZAO;

      if (:WNOVOVALORBASE <= 0) then
         continue;
      /* pega a proporção de cada alíquota Ex. seguindo o exemplo anterior, aqui dos 1300000, os 1297000 representa 99,76% */
      WPERCPROPORCIONALBASES = (CAST(:WNOVOVALORBASE AS NUMERIC(15,10)) / CAST(:WVALOR_TRIMESTRE AS NUMERIC(15,10)));
      /* pega a proporção de cada alíquota Ex. seguindo o exemplo anterior, aqui dos 1300000, os 3000 representa 0,23% */
      WPERCPROPORCIONALBASESEXCEDENTE = CAST(:WCALCRAZAO AS NUMERIC(15,10)) / CAST(:WVALOR_TRIMESTRE AS NUMERIC(15,10));

      /* pega a proporção e multiplica pelas somas das bases Ex. 99,76% * 1300000 */
      BDBASECALC_1_6  = CAST(WPERCPROPORCIONALBASES * (WBASE_1_6 + :WBASE_1_76) AS NUMERIC(15,10));
      /* pega a proporção e multiplica pelas somas das bases Ex. 0,23% * 1300000 e segue o mesmo para todas bases abaixo*/
      BDBASECALC_1_76 = CAST(WPERCPROPORCIONALBASESEXCEDENTE * (WBASE_1_6 + :WBASE_1_76) AS NUMERIC(15,10));
      BDVALORIR_1_6   = CAST(BDBASECALC_1_6 * 0.016 AS NUMERIC(15,10));
      BDVALORIR_1_76  = CAST(BDBASECALC_1_76 * 0.0176 AS NUMERIC(15,10));

      BDBASECALC_8    = CAST(WPERCPROPORCIONALBASES * (WBASE_8 + :WBASE_8_8) AS NUMERIC(15,10));
      BDBASECALC_8_8  = CAST(WPERCPROPORCIONALBASESEXCEDENTE * (WBASE_8 + :WBASE_8_8) AS NUMERIC(15,10));
      BDVALORIR_8     = CAST(BDBASECALC_8 * 0.08 AS NUMERIC(15,10));
      BDVALORIR_8_8   = CAST(BDBASECALC_8_8 * 0.088 AS NUMERIC(15,10));
        
      BDBASECALC_12   = CAST(WPERCPROPORCIONALBASES * (WBASE_12 + :WBASE_13_2) AS NUMERIC(15,10));
      BDBASECALC_13_2 = CAST(WPERCPROPORCIONALBASESEXCEDENTE * (WBASE_12 + :WBASE_13_2) AS NUMERIC(15,10));
      BDVALORIR_12    = CAST(BDBASECALC_12 * 0.12 AS NUMERIC(15,10));
      BDVALORIR_13_2  = CAST(BDBASECALC_13_2 * 0.132 AS NUMERIC(15,10));
        
      BDBASECALC_16   = CAST(WPERCPROPORCIONALBASES * (WBASE_16 + :WBASE_17_6) AS NUMERIC(15,10));
      BDBASECALC_17_6 = CAST(WPERCPROPORCIONALBASESEXCEDENTE * (WBASE_16 + :WBASE_17_6) AS NUMERIC(15,10));
      BDVALORIR_16    = CAST(BDBASECALC_16 * 0.16 AS NUMERIC(15,10));
      BDVALORIR_17_6  = CAST(BDBASECALC_17_6 * 0.176 AS NUMERIC(15,10));
        
      BDBASECALC_32   = CAST(WPERCPROPORCIONALBASES * (WBASE_32 + :WBASE_35_2) AS NUMERIC(15,10));
      BDBASECALC_35_2 = CAST(WPERCPROPORCIONALBASESEXCEDENTE * (WBASE_32 + :WBASE_35_2) AS NUMERIC(15,10));
      BDVALORIR_32    = CAST(BDBASECALC_32 * 0.32 AS NUMERIC(15,10));
      BDVALORIR_35_2  = CAST(BDBASECALC_35_2 * 0.352 AS NUMERIC(15,10));

      BDBASECALCIR = BDVALORIR_1_6 + BDVALORIR_1_76 + BDVALORIR_8 + BDVALORIR_8_8 + BDVALORIR_12 + BDVALORIR_13_2  + BDVALORIR_16 + BDVALORIR_17_6 + BDVALORIR_32 + BDVALORIR_35_2;

      if (:PRCODQIRLP = 2) then
        begin
         BDVALORIRPJ  = BDBASECALCIR * 0.15;
         if (BDBASECALCIR > WVALORREDUCAO) then
           BDVALORADICIONAL = (BDBASECALCIR - :WVALORREDUCAO) * 0.10;
         else
           BDVALORADICIONAL = 0;
        end
      else
        begin
         BDVALORIRPJ  = BDBASECALCIR * 0.09;
         BDVALORADICIONAL     = 0;
         BDVALORADICIONAL_ANT = 0;
        end

      if (BDVALORIRPJ < 0) then
         BDVALORIRPJ = 0;

      if ((WTRIMESTRE < 4) and ((BDVALORIRPJ_ANT + BDVALORADICIONAL_ANT) - (BDVALORIRPJ + BDVALORADICIONAL)) > 0) then
         BDVALORTOTALDEDUCAO = ((BDVALORIRPJ_ANT + BDVALORADICIONAL_ANT) - (BDVALORIRPJ + BDVALORADICIONAL));
      SUSPEND;
    END
END
^

CREATE OR ALTER procedure SP_BUSCA_DESCRICAO_EVENTO (
    PRCODEMP integer,
    PRREFINI integer,
    PRREFFIM integer)
returns (
    BDDESCRICAO varchar(500))
as
declare variable WSQL varchar(32500);
declare variable WSQLTARQUIVO varchar(32500);
declare variable WSQLAUX varchar(32500);
declare variable WWHERE varchar(32500);
declare variable WCODTIPO integer;
declare variable WCODTIPOAUX integer;
begin
  wcodtipo    = 0;
  wcodtipoaux = 0;
  BDDESCRICAO = '';
  wwhere      = '';


  WSQL = 'SELECT tp.bdcodtipo, tp.bddescricao from VRH_ESOCIAL_TTIPO_ARQ tp ';

  if (prrefini > 0) then
  begin
    if (wwhere <> '') then
       wwhere = wwhere||' and ';

    wwhere = wwhere||'evt.bdrefarq >= '||prRefIni||' ';
  end

  if (prreffim > 0) then
  begin
    if (wwhere <> '') then
       wwhere = wwhere||' and ';

    wwhere = wwhere||'evt.bdrefarq <= '||prRefFim||' ';
  end

  if (wwhere <> '') then
     wWhere = ' and '||wWhere;

    wWhere = wWhere||')) and evt.bdcodtipo = ';



  WSQLTARQUIVO = 'select first 1 EVT.BDCODTIPO from VRH_ESOCIAL_TARQUIVO evt '||
                 'join TMP_TEMPRESAS_USUARIO a on (evt.bdcodemp = a.bdcodemp) '||
                 'where evt.bdcodemp = '||PRCODEMP||' and (((evt.BDSTATUS <> 7) ';

  WSQLTARQUIVO = WSQLTARQUIVO||wwhere;

  for execute statement wsql into wcodtipo, bddescricao do
    begin
      WSQLAUX     = '';
      wcodtipoaux = 0;

      WSQLAUX = WSQLTARQUIVO||wcodtipo;

      execute statement wsqlaux into wcodtipoaux;

      if (wcodtipoaux > 0) then
        suspend;
    end
end^

CREATE OR ALTER procedure SP_VRH_EMPS_BANCO_AG_RHNET (
    PRCODBAN integer,
    PRCODAG integer)
returns (
    BDCODEMP integer,
    BDNOMEMP DM_BDNOMEMP,
    BDRHNET boolean,
    BDVINCCOL boolean)
as
declare variable WDATA date;
declare variable WREF integer;
declare variable WOK integer;
declare variable WCADCOL integer;
begin
  SELECT CURRENT_DATE FROM RDB$DATABASE into :wdata;

  wref = cast((substring(cast(wdata as varchar(10)) from 1 for 4)||substring(cast(wdata as varchar(10)) from 6 for 2)) as integer);

  for select BDCODEMP from TEMPRESAS where upper(coalesce(BDRHNET, 'FALSE')) = 'TRUE' order by BDCODEMP
  into :BDCODEMP
  do
    begin
      select first 1 BDNOMEMP from TEMPRESAS_REF where BDCODEMP = :BDCODEMP and BDREFEMP <= :wref order by BDCODEMP desc, BDREFEMP desc into :BDNOMEMP;

      wok = null;
      select first 1 BDCODEMP from VRH_RHNET_TBANCOS_AG where BDCODEMP = :BDCODEMP and BDCODBAN = :PRCODBAN AND BDCODAG = :PRCODAG into :wok;

      BDRHNET = FALSE;
      if (coalesce(wok, 0) > 0) then
         BDRHNET = TRUE;

    WCADCOL = null;
    select first 1 CB.BDCODBAN
    from VRHF_EMP_TCOLCON_BANCO CB
    left outer join VRH_EMP_TRESCISAO R on (R.BDCODEMP = CB.BDCODEMP and
          R.BDCODCOL = CB.BDCODCOL)
    where CB.BDCODEMP = :BDCODEMP and
          CB.BDCODBAN = :PRCODBAN and
          CB.BDCODAG = :PRCODAG and
          CB.BDREFCOL = coalesce((select first 1 D2.BDREFCOL
                                  from VRHF_EMP_TCOLCON_BANCO D2
                                  where D2.BDCODEMP = CB.BDCODEMP and
                                        D2.BDCODCOL = CB.BDCODCOL and
                                        D2.BDREFCOL <= :wref
                                        order by D2.BDREFCOL desc), (select first 1 D1.BDREFCOL
                                                                     from VRHF_EMP_TCOLCON_BANCO D1
                                                                     where D1.BDCODEMP = CB.BDCODEMP and
                                                                           D1.BDCODCOL = CB.BDCODCOL and
                                                                           D1.BDREFCOL >= :WREF)) and ((R.BDDATARESCISAO is null) or (R.BDREFRESCISAO >= :WREF))
    into :WCADCOL;

      BDVINCCOL = FALSE;
      if (coalesce(wcadcol, 0) > 0) then
         BDVINCCOL = TRUE;
      suspend;
    end
end^

create or alter procedure SP_VERBAS_INCIDENCIAS_INSS (
    PRCODEMP varchar(30000),
    PRCODCOL varchar(30000),
    PRCODTER varchar(30000))
returns (
    BDCODVER integer,
    BDDESCVER varchar(300),
    BDREFVER integer,
    BDIMPINSSNORMAL varchar(5),
    BDIMPINSSFERIAS varchar(5),
    BDIMPINSS13 varchar(5),
    BDIMPINSSNAOINCIDE varchar(5),
    BDCODINCIDINSS integer,
    BDDESCINCINSS varchar(300),
    BDINSSSISTEMA integer,
    BDBASEGPS varchar(5),
    BDVALOR numeric(15,6),
    BDTIPOCALC varchar(100),
    BDCODEMP integer,
    BDCODCOL integer,
    BDCNPJEMP varchar(18),
    BDCODMATRIZ integer,
    BDOBSERVACAO varchar(32700),
    BDDESCINSSSISTEMA varchar(50),
    BDNOMCOL varchar(70),
    BDNOMEMP DM_BDNOMEMP,
    BDCODTER integer)
as
declare variable WCLASS varchar(30);
declare variable WSQL varchar(32700);
declare variable WJOIN varchar(32700);
declare variable WWHERE varchar(32700);
declare variable WREF integer;
declare variable WSQLEMP varchar(32700);
declare variable WWHEREEMP varchar(32700);
declare variable WJOINEMP varchar(32700);
declare variable WVALORAUX numeric(15,6);
declare variable WCODEMPAUX integer;
declare variable WCODCOLAUX integer;
declare variable WTIPOCALCAUX varchar(100);
declare variable WOBSAUX varchar(32700);
declare variable WNOMCOLAUX varchar(70);
declare variable WHERECOL varchar(32700);
declare variable WHERETER varchar(32700);
declare variable WJOINTER varchar(32700);
declare variable WWHERECALCTER varchar(32700);
begin
  select trim(rdb$get_context('USER_SESSION', 'W_ANOMES')) from RDB$DATABASE into :WREF;

  for
    select V.BDCODVER, V.BDDESCVER, REF.BDREFVER, REF.BDCODINCIDINSS,
           INSS.BDDESCINSS, REF.BDINSSVER, REF.BDBASEGPSVER,V.BDCLAVER
    from VRH_BASE_TVERBAS V
    join VRH_BASE_TVERBAS_REF REF on REF.BDCODVER = V.BDCODVER
    left join VRH_ESOCIAL_TINCID_INSS INSS on REF.BDCODINCIDINSS = INSS.BDCODINSS
    where char_length(V.BDCLAVER) = 13 and
          REF.BDREFVER = coalesce((select first 1 X.BDREFVER
                                   from VRH_BASE_TVERBAS_REF X
                                   where X.BDCODVER = V.BDCODVER and
                                   cast(X.BDREFVER as varchar(6)) <= :WREF order by X.BDREFVER desc),
                                   (select first 1 X.BDREFVER
                                    from VRH_BASE_TVERBAS_REF X
                                    where X.BDCODVER = V.BDCODVER
                                    order by X.BDREFVER))
        
    order by V.BDCODVER
    into :bdcodver,:bddescver,:bdrefver,:bdcodincidinss,:bddescincinss,:bdinsssistema,:bdbasegps,:wclass
  do
  begin
    BDIMPINSSNORMAL = 'FALSE';
    BDIMPINSSFERIAS = 'FALSE';
    BDIMPINSS13 = 'FALSE';
    BDIMPINSSNAOINCIDE = 'FALSE';
    BDDESCINSSSISTEMA = null;

    if ((substring(:wclass from 1 for 9) = '6.080.0.0') and (upper(bdbasegps) = 'TRUE') and (bdinsssistema = 0) and (bdcodincidinss = 12)) then
    begin
      -- Desconto de 13º no complmento o controle para o sistema é feito interno
    end
    else -- Verbas de INSS
    if ((bdcodincidinss in (31, 32, 34, 35, 51)) and (upper(bdbasegps) = 'FALSE') and (bdinsssistema = 0)) then
    begin
       -- Não deve incluir
    end
    -- INSS Folha normal
    else if (bdinsssistema = 1) then
    begin
      if (bdcodincidinss = 21) then
      begin
        /* Verificar dados padr es as compentencia que deixaram de ser Base GPS */
        if (bdrefver < 201511) then
        begin
          if (upper(bdbasegps) <> 'TRUE') then
            BDIMPINSSNORMAL = 'TRUE';
        end
        else
        begin
          if (upper(bdbasegps) = 'TRUE') then
            BDIMPINSSNORMAL = 'TRUE';
        end
      end
      --Deve ter incid ncia eSocial igual a 11, 15 ou 21.
      else if (bdcodincidinss not in (11,15,21)) then
        BDIMPINSSNORMAL = 'TRUE';
      --Base GPS deve estar marcada se a incidência de INSS for igual a folha normal e a incidência for eSocial for igual a 11.
      else if ((bdbasegps = 'TRUE') and (bdcodincidinss <> 11)) then
        BDIMPINSSNORMAL = 'TRUE';
      else if ((bdbasegps = 'FALSE') and (bdcodincidinss = 11)) then
        BDIMPINSSNORMAL = 'TRUE';
    end

    -- INSS Férias
    else if (bdinsssistema = 2) then
    begin
      --Deve ter incidência eSocial igual a 0
      if (coalesce(bdcodincidinss,0) <> 0) then
        BDIMPINSSFERIAS = 'TRUE';
      --Base GPS deve estar marcada se a incidência de INSS for igual a férias e a incidência for eSocial for igual a 0.
      else if (bdbasegps = 'FALSE') then
        BDIMPINSSFERIAS = 'TRUE';
    end

    -- INSS 13º
    else if (bdinsssistema = 3) then
    begin
      -- Deve ter incidência eSocial igual a 12, 16 ou 22
      if (bdcodincidinss = 22) then
      begin
        /* Verificar dados padr es as compentencia que deixaram de ser Base GPS */
        if (bdrefver < 201511) then
        begin
          if (upper(bdbasegps) <> 'TRUE') then
            BDIMPINSSNORMAL = 'TRUE';
        end
        else
        begin
          if (upper(bdbasegps) = 'TRUE') then
            BDIMPINSSNORMAL = 'TRUE';
        end
      end
      else if (bdcodincidinss not in (12,16,22)) then
        BDIMPINSS13 = 'TRUE';
      -- Base GPS deve estar marcada se a incidência de INSS for igual a 13º Salário e a incidência eSocial for igual a 12.
      else if ((bdbasegps = 'TRUE') and (bdcodincidinss <> 12)) then
        BDIMPINSS13 = 'TRUE';
      else if ((bdbasegps = 'FALSE') and (bdcodincidinss = 12)) then
        BDIMPINSS13 = 'TRUE';
    end

    -- INSS Não incide
    else if (bdinsssistema = 0) then
    begin
      --Deve ter incidência eSocial igual a 0, 1, 13 ou 14.
      if (bdcodincidinss not in (0,1,13,14)) then
        BDIMPINSSNAOINCIDE = 'TRUE';
      -- Base GPS deve estar desmarcada se a incidência de INSS for igual a Não incide e a incidência eSocial for igual a 0.
      else if ((bdbasegps = 'TRUE') and (bdcodincidinss = 0)) then
        BDIMPINSSNAOINCIDE = 'TRUE';
    end

    if (bdbasegps = 'TRUE') then
       bdbasegps = 'Sim';
    else
       bdbasegps = 'Não';

    BDDESCINSSSISTEMA = CASE
                          WHEN BDINSSSISTEMA = 1 THEN 'Folha normal'
                          WHEN BDINSSSISTEMA = 2 THEN 'Férias'
                          WHEN BDINSSSISTEMA = 3 THEN '13º Salário'
                          ELSE 'Não incide'
                        END;

    if (BDIMPINSSNORMAL = 'TRUE' or BDIMPINSSFERIAS = 'TRUE' or BDIMPINSS13 = 'TRUE' or BDIMPINSSNAOINCIDE = 'TRUE') then
       begin
         WJOIN = '';
         WJOINEMP = '';
         WWHERE = '';
         WWHEREEMP = '';
         WHERECOL = '';
         WJOINTER = '';
         WWHERECALCTER = '';
         WHERETER = '';
         prcodemp = replace(prcodemp,'''','');
         prcodcol = replace(prcodcol,'''','');
         prcodter = replace(prcodter,'''','');

         if (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') then
            begin
              WJOINEMP = 'INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON EMPSEL.BDCODEMP = EMP.BDCODEMP';
            end
         else
            begin
              if ((prcodemp is not null) and (trim(prcodemp) <> '')) then
                 begin
                   WWHEREEMP = REPLACE(UPPER(prcodemp), 'TAB', 'EMP');

                   WWHEREEMP = REPLACE(WWHEREEMP, '''', '');
                   if ((WWHEREEMP is not null) and (trim(WWHEREEMP) <> '')) then
                       WWHEREEMP = ' WHERE ('||WWHEREEMP||') OR ('||REPLACE(WWHEREEMP, 'BDCODEMP', 'BDCODMATRIZ')||')';
                 end

              DELETE FROM TMP_EMPRESAS_SELECT;

              WSQL = 'INSERT INTO TMP_EMPRESAS_SELECT (BDCODEMP) '||
                     'SELECT EMP.BDCODEMP '||
                     'FROM TEMPRESAS EMP '||
                     WWHEREEMP;

              EXECUTE STATEMENT WSQL;
            end

         if (UPPER(prcodcol) = 'TEMP_FILTRO_COLCON_REL') then
            begin
              WJOIN = ' JOIN TEMP_FILTRO_COLCON_REL T ON T.BDCODEMP = X.BDCODEMP AND T.BDCODCOL = X.BDCODCOL ';
            end
         else
            begin
              if ((prcodcol is not null) and (trim(prcodcol) <> '')) then
                 WHERECOL = WHERECOL || ' AND ' || REPLACE(UPPER(prcodcol), 'TAB', 'X');
            end

         if (UPPER(PRCODTER) = 'TEMP_FILTRO_COLCON_REL') then
            begin
              WJOINTER = ' JOIN TEMP_FILTRO_COLCON_REL T ON T.BDCODEMP = X.BDCODEMP AND T.BDCODTER = X.BDCODTER ';
            end
         else
            begin
              if ((PRCODTER is not null) and (trim(PRCODTER) <> '')) then
                 WHERETER = WHERETER || ' AND ' || REPLACE(UPPER(PRCODTER), 'TAB', 'X');
            end

         /* FN */
         WVALORAUX = 0;
         BDVALOR = 0;
         WCODEMPAUX   = null;
         WCODCOLAUX   = null;
         WTIPOCALCAUX = null;
         WOBSAUX      = null;
         WNOMCOLAUX   = null;
         BDCODCOL     = null;
         BDTIPOCALC   = null;
         BDOBSERVACAO = null;
         BDNOMCOL     = null;
         FOR
           SELECT X.BDCODEMP, X.BDCODCOL, SUM(X.BDVALVFN), 'Folha Normal' BDCALC, NULL BDOBSERVACAO
           FROM VRHF_EMP_TVERBAFN X
           INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON EMPSEL.BDCODEMP = X.BDCODEMP
           WHERE X.BDREFFN = :WREF
             AND X.BDCODVER = :BDCODVER
           GROUP BY X.BDCODEMP, X.BDCODCOL,BDOBSERVACAO
           ORDER BY X.BDCODEMP, X.BDCODCOL
           INTO :WCODEMPAUX, :WCODCOLAUX, :WVALORAUX, :WTIPOCALCAUX, :WOBSAUX
         DO
           BEGIN
             IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX OR BDCODCOL IS DISTINCT FROM WCODCOLAUX) THEN
               BEGIN
                 IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX) THEN
                   BEGIN
                     SELECT FIRST 1 COALESCE(EMP.BDCODMATRIZ,EMP.BDCODEMP),EMP.BDCNPJEMP,R.BDNOMEMP
                     FROM TEMPRESAS EMP
                     LEFT OUTER JOIN LATERAL (SELECT FIRST 1 RF.BDNOMEMP FROM TEMPRESAS_REF RF WHERE RF.BDCODEMP = EMP.BDCODEMP ORDER BY RF.BDREFEMP DESC) R ON 1=1
                     WHERE EMP.BDCODEMP = :WCODEMPAUX
                     INTO :BDCODMATRIZ,:BDCNPJEMP,:BDNOMEMP;
                   END
                 SELECT FIRST 1 COL.BDNOMCOL
                 FROM VRH_EMP_TCOLCON_CAD COL
                 WHERE COL.BDCODEMP = :WCODEMPAUX AND COL.BDCODCOL = :WCODCOLAUX
                 ORDER BY COL.BDREFCOL DESC
                 INTO :WNOMCOLAUX;
               END

             BDCODCOL     = WCODCOLAUX;
             BDCODEMP     = WCODEMPAUX;
             BDTIPOCALC   = WTIPOCALCAUX;
             BDOBSERVACAO = WOBSAUX;
             BDNOMCOL     = WNOMCOLAUX;
             BDVALOR      = WVALORAUX;
             SUSPEND;
           END

         /* FI */
         WVALORAUX = 0;
         BDVALOR = 0;
         WCODEMPAUX   = null;
         WCODCOLAUX   = null;
         WTIPOCALCAUX = null;
         WOBSAUX      = null;
         WNOMCOLAUX   = null;
         BDCODCOL     = null;
         BDTIPOCALC   = null;
         BDOBSERVACAO = null;
         BDNOMCOL     = null;
         FOR
           SELECT X.BDCODEMP, X.BDCODCOL, SUM(X.BDVALVFN), 'Folha Intermitente' BDCALC, 'Contrato '||X.BDCODCONTTI BDOBSERVACAO
           FROM VRHF_EMP_TVERBAINT X
           INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON EMPSEL.BDCODEMP = X.BDCODEMP
           WHERE X.BDREFFN = :WREF
             AND X.BDCODVER = :BDCODVER
           GROUP BY X.BDCODEMP, X.BDCODCOL,BDOBSERVACAO
           ORDER BY X.BDCODEMP, X.BDCODCOL
           INTO :WCODEMPAUX, :WCODCOLAUX, :WVALORAUX, :WTIPOCALCAUX, :WOBSAUX
         DO
           BEGIN
             IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX OR BDCODCOL IS DISTINCT FROM WCODCOLAUX) THEN
               BEGIN
                 IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX) THEN
                   BEGIN
                     SELECT FIRST 1 COALESCE(EMP.BDCODMATRIZ,EMP.BDCODEMP),EMP.BDCNPJEMP,R.BDNOMEMP
                     FROM TEMPRESAS EMP
                     LEFT OUTER JOIN LATERAL (SELECT FIRST 1 RF.BDNOMEMP FROM TEMPRESAS_REF RF WHERE RF.BDCODEMP = EMP.BDCODEMP ORDER BY RF.BDREFEMP DESC) R ON 1=1
                     WHERE EMP.BDCODEMP = :WCODEMPAUX
                     INTO :BDCODMATRIZ,:BDCNPJEMP,:BDNOMEMP;
                   END
                 SELECT FIRST 1 COL.BDNOMCOL
                 FROM VRH_EMP_TCOLCON_CAD COL
                 WHERE COL.BDCODEMP = :WCODEMPAUX AND COL.BDCODCOL = :WCODCOLAUX
                 ORDER BY COL.BDREFCOL DESC
                 INTO :WNOMCOLAUX;
               END

             BDCODCOL     = WCODCOLAUX;
             BDCODEMP     = WCODEMPAUX;
             BDTIPOCALC   = WTIPOCALCAUX;
             BDOBSERVACAO = WOBSAUX;
             BDNOMCOL     = WNOMCOLAUX;
             BDVALOR      = WVALORAUX;
             SUSPEND;
           END

         /* FT */
         WVALORAUX = 0;
         BDVALOR = 0;
         WCODEMPAUX   = null;
         WCODCOLAUX   = null;
         WTIPOCALCAUX = null;
         WOBSAUX      = null;
         WNOMCOLAUX   = null;
         BDCODCOL     = null;
         BDTIPOCALC   = null;
         BDOBSERVACAO = null;
         BDNOMCOL     = null;
         FOR
           SELECT X.BDCODEMP, X.BDCODCOL, SUM(X.BDVALVFT), 'Folha Normal' BDCALC, null BDOBSERVACAO
           FROM VRHF_EMP_TVERBATOMADOR X
           INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON EMPSEL.BDCODEMP = X.BDCODEMP
           WHERE X.BDREFTOMADOR = :WREF
             AND X.BDCODVER = :BDCODVER
           GROUP BY X.BDCODEMP, X.BDCODCOL,BDOBSERVACAO
           ORDER BY X.BDCODEMP, X.BDCODCOL
           INTO :WCODEMPAUX, :WCODCOLAUX, :WVALORAUX, :WTIPOCALCAUX, :WOBSAUX
         DO
           BEGIN
             IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX OR BDCODCOL IS DISTINCT FROM WCODCOLAUX) THEN
               BEGIN
                 IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX) THEN
                   BEGIN
                     SELECT FIRST 1 COALESCE(EMP.BDCODMATRIZ,EMP.BDCODEMP),EMP.BDCNPJEMP,R.BDNOMEMP
                     FROM TEMPRESAS EMP
                     LEFT OUTER JOIN LATERAL (SELECT FIRST 1 RF.BDNOMEMP FROM TEMPRESAS_REF RF WHERE RF.BDCODEMP = EMP.BDCODEMP ORDER BY RF.BDREFEMP DESC) R ON 1=1
                     WHERE EMP.BDCODEMP = :WCODEMPAUX
                     INTO :BDCODMATRIZ,:BDCNPJEMP,:BDNOMEMP;
                   END
                 SELECT FIRST 1 COL.BDNOMCOL
                 FROM VRH_EMP_TCOLCON_CAD COL
                 WHERE COL.BDCODEMP = :WCODEMPAUX AND COL.BDCODCOL = :WCODCOLAUX
                 ORDER BY COL.BDREFCOL DESC
                 INTO :WNOMCOLAUX;
               END

             BDCODCOL     = WCODCOLAUX;
             BDCODEMP     = WCODEMPAUX;
             BDTIPOCALC   = WTIPOCALCAUX;
             BDOBSERVACAO = WOBSAUX;
             BDNOMCOL     = WNOMCOLAUX;
             BDVALOR      = WVALORAUX;
             SUSPEND;
           END

         /* FTI */
         WVALORAUX = 0;
         BDVALOR = 0;
         WCODEMPAUX   = null;
         WCODCOLAUX   = null;
         WTIPOCALCAUX = null;
         WOBSAUX      = null;
         WNOMCOLAUX   = null;
         BDCODCOL     = null;
         BDTIPOCALC   = null;
         BDOBSERVACAO = null;
         BDNOMCOL     = null;
         FOR
           SELECT X.BDCODEMP, X.BDCODCOL, SUM(X.BDVALVFT), 'Folha Intermitente' BDCALC, 'Contrato '||X.BDCODCONTTI BDOBSERVACAO
           FROM VRHF_EMP_TVERBATOMINT X
           INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON EMPSEL.BDCODEMP = X.BDCODEMP
           WHERE X.BDREFTOMADOR = :WREF
             AND X.BDCODVER = :BDCODVER
           GROUP BY X.BDCODEMP, X.BDCODCOL,BDOBSERVACAO
           ORDER BY X.BDCODEMP, X.BDCODCOL
           INTO :WCODEMPAUX, :WCODCOLAUX, :WVALORAUX, :WTIPOCALCAUX, :WOBSAUX
         DO
           BEGIN
             IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX OR BDCODCOL IS DISTINCT FROM WCODCOLAUX) THEN
               BEGIN
                 IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX) THEN
                   BEGIN
                     SELECT FIRST 1 COALESCE(EMP.BDCODMATRIZ,EMP.BDCODEMP),EMP.BDCNPJEMP,R.BDNOMEMP
                     FROM TEMPRESAS EMP
                     LEFT OUTER JOIN LATERAL (SELECT FIRST 1 RF.BDNOMEMP FROM TEMPRESAS_REF RF WHERE RF.BDCODEMP = EMP.BDCODEMP ORDER BY RF.BDREFEMP DESC) R ON 1=1
                     WHERE EMP.BDCODEMP = :WCODEMPAUX
                     INTO :BDCODMATRIZ,:BDCNPJEMP,:BDNOMEMP;
                   END
                 SELECT FIRST 1 COL.BDNOMCOL
                 FROM VRH_EMP_TCOLCON_CAD COL
                 WHERE COL.BDCODEMP = :WCODEMPAUX AND COL.BDCODCOL = :WCODCOLAUX
                 ORDER BY COL.BDREFCOL DESC
                 INTO :WNOMCOLAUX;
               END

             BDCODCOL     = WCODCOLAUX;
             BDCODEMP     = WCODEMPAUX;
             BDTIPOCALC   = WTIPOCALCAUX;
             BDOBSERVACAO = WOBSAUX;
             BDNOMCOL     = WNOMCOLAUX;
             BDVALOR      = WVALORAUX;
             SUSPEND;
           END

         /* FC */
         WVALORAUX = 0;
         BDVALOR = 0;
         WCODEMPAUX   = null;
         WCODCOLAUX   = null;
         WTIPOCALCAUX = null;
         WOBSAUX      = null;
         WNOMCOLAUX   = null;
         BDCODCOL     = null;
         BDTIPOCALC   = null;
         BDOBSERVACAO = null;
         BDNOMCOL     = null;
         FOR
           SELECT X.BDCODEMP, X.BDCODCOL, SUM(X.BDVALVFC), 'Folha Complementar' BDCALC,
           case
             when F.BDCODTIPOFC = 1 then 'Referência: '||substring(cast(F.BDREFFN as varchar(6)) from 5 for 2)||'/'||substring(cast(F.BDREFFN as varchar(6)) from 1 for 4)||' Pagamento: ' ||substring(cast(F.BDREFFC as varchar(8)) from 7 for 2)||'/'||substring(cast(F.BDREFFC as varchar(8)) from 5 for 2)||'/'||substring(cast(F.BDREFFC as varchar(8)) from 1 for 4)
             when f.bdcodtipofc = 3 then 'ADC Código: '||f.bdcodacconv
           end BDOBSERVACAO
           FROM VRHF_EMP_TVERBAFC X
           INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON EMPSEL.BDCODEMP = X.BDCODEMP
           LEFT OUTER JOIN VRHF_EMP_TFOLHACOMP F ON F.BDCODEMP = X.BDCODEMP AND F.BDCODCOL = X.BDCODCOL AND F.BDREFFN = X.BDREFFN AND F.BDREFFC = X.BDREFFC
           LEFT OUTER JOIN VRH_EMP_TACCONV AC ON AC.BDCODEMP = X.BDCODEMP AND AC.BDCODACCONV = F.BDCODACCONV
           WHERE ((F.BDCODTIPOFC = 1 AND X.BDREFFN = :WREF) OR
                  (F.BDCODTIPOFC = 3 AND AC.BDCODACCONV IS NOT NULL AND ((EXTRACT(YEAR FROM AC.BDDTPGTOBRICONV) * 100) + EXTRACT(MONTH FROM AC.BDDTPGTOBRICONV) = :WREF)))
                  AND X.BDCODVER = :BDCODVER
           GROUP BY X.BDCODEMP, X.BDCODCOL,BDOBSERVACAO
           ORDER BY X.BDCODEMP, X.BDCODCOL
           INTO :WCODEMPAUX, :WCODCOLAUX, :WVALORAUX, :WTIPOCALCAUX, :WOBSAUX
         DO
           BEGIN
             IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX OR BDCODCOL IS DISTINCT FROM WCODCOLAUX) THEN
               BEGIN
                 IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX) THEN
                   BEGIN
                     SELECT FIRST 1 COALESCE(EMP.BDCODMATRIZ,EMP.BDCODEMP),EMP.BDCNPJEMP,R.BDNOMEMP
                     FROM TEMPRESAS EMP
                     LEFT OUTER JOIN LATERAL (SELECT FIRST 1 RF.BDNOMEMP FROM TEMPRESAS_REF RF WHERE RF.BDCODEMP = EMP.BDCODEMP ORDER BY RF.BDREFEMP DESC) R ON 1=1
                     WHERE EMP.BDCODEMP = :WCODEMPAUX
                     INTO :BDCODMATRIZ,:BDCNPJEMP,:BDNOMEMP;
                   END
                 SELECT FIRST 1 COL.BDNOMCOL
                 FROM VRH_EMP_TCOLCON_CAD COL
                 WHERE COL.BDCODEMP = :WCODEMPAUX AND COL.BDCODCOL = :WCODCOLAUX
                 ORDER BY COL.BDREFCOL DESC
                 INTO :WNOMCOLAUX;
               END

             BDCODCOL     = WCODCOLAUX;
             BDCODEMP     = WCODEMPAUX;
             BDTIPOCALC   = WTIPOCALCAUX;
             BDOBSERVACAO = WOBSAUX;
             BDNOMCOL     = WNOMCOLAUX;
             BDVALOR      = WVALORAUX;
             SUSPEND;
           END

         /* FCI */
         WVALORAUX = 0;
         BDVALOR = 0;
         WCODEMPAUX   = null;
         WCODCOLAUX   = null;
         WTIPOCALCAUX = null;
         WOBSAUX      = null;
         WNOMCOLAUX   = null;
         BDCODCOL     = null;
         BDTIPOCALC   = null;
         BDOBSERVACAO = null;
         BDNOMCOL     = null;
         FOR
           SELECT X.BDCODEMP, X.BDCODCOL, SUM(X.BDVALVFC), 'Folha Complementar Intermitente' BDCALC,
           case
             when F.BDCODTIPOFC = 1 then 'Contrato '||X.BDCODCONTTI||' Referência: ' || substring(cast(F.BDREFFN as varchar(6)) from 5 for 2) || '/' || substring(cast(F.BDREFFN as varchar(6)) from 1 for 4) || ' Pagamento: ' || substring(cast(F.BDREFFC as varchar(8)) from 7 for 2) || '/' || substring(cast(F.BDREFFC as varchar(8)) from 5 for 2) || '/' || substring(cast(F.BDREFFC as varchar(8)) from 1 for 4)
             when F.BDCODTIPOFC = 3 then 'Contrato '||X.BDCODCONTTI||' '||'ADC Código: ' || F.BDCODACCONV
           end BDOBSERVACAO
           FROM VRHF_EMP_TVERBAFCINT X
           INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON EMPSEL.BDCODEMP = X.BDCODEMP
           left outer join vrhf_emp_tfolhacompint f on f.bdcodemp = x.bdcodemp and f.bdcodcol = x.bdcodcol and f.bdcodcontti = x.BDCODCONTTI and f.bdreffn = x.bdreffn and f.bdreffc = x.bdreffc
           left outer join VRH_EMP_TACCONV AC on ac.bdcodemp = x.bdcodemp and ac.bdcodacconv = f.bdcodacconv
           WHERE ((F.BDCODTIPOFC = 1 AND X.BDREFFN = :WREF) OR
                  (F.BDCODTIPOFC = 3 AND AC.BDCODACCONV IS NOT NULL AND ((EXTRACT(YEAR FROM AC.BDDTPGTOBRICONV) * 100) + EXTRACT(MONTH FROM AC.BDDTPGTOBRICONV) = :WREF)))
               AND X.BDCODVER = :BDCODVER
           GROUP BY X.BDCODEMP, X.BDCODCOL,BDOBSERVACAO
           ORDER BY X.BDCODEMP, X.BDCODCOL
           INTO :WCODEMPAUX, :WCODCOLAUX, :WVALORAUX, :WTIPOCALCAUX, :WOBSAUX
         DO
           BEGIN
             IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX OR BDCODCOL IS DISTINCT FROM WCODCOLAUX) THEN
               BEGIN
                 IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX) THEN
                   BEGIN
                     SELECT FIRST 1 COALESCE(EMP.BDCODMATRIZ,EMP.BDCODEMP),EMP.BDCNPJEMP,R.BDNOMEMP
                     FROM TEMPRESAS EMP
                     LEFT OUTER JOIN LATERAL (SELECT FIRST 1 RF.BDNOMEMP FROM TEMPRESAS_REF RF WHERE RF.BDCODEMP = EMP.BDCODEMP ORDER BY RF.BDREFEMP DESC) R ON 1=1
                     WHERE EMP.BDCODEMP = :WCODEMPAUX
                     INTO :BDCODMATRIZ,:BDCNPJEMP,:BDNOMEMP;
                   END
                 SELECT FIRST 1 COL.BDNOMCOL
                 FROM VRH_EMP_TCOLCON_CAD COL
                 WHERE COL.BDCODEMP = :WCODEMPAUX AND COL.BDCODCOL = :WCODCOLAUX
                 ORDER BY COL.BDREFCOL DESC
                 INTO :WNOMCOLAUX;
               END

             BDCODCOL     = WCODCOLAUX;
             BDCODEMP     = WCODEMPAUX;
             BDTIPOCALC   = WTIPOCALCAUX;
             BDOBSERVACAO = WOBSAUX;
             BDNOMCOL     = WNOMCOLAUX;
             BDVALOR      = WVALORAUX;
             SUSPEND;
           END

         /* FCT */
         WVALORAUX = 0;
         BDVALOR = 0;
         WCODEMPAUX   = null;
         WCODCOLAUX   = null;
         WTIPOCALCAUX = null;
         WOBSAUX      = null;
         WNOMCOLAUX   = null;
         BDCODCOL     = null;
         BDTIPOCALC   = null;
         BDOBSERVACAO = null;
         BDNOMCOL     = null;
         FOR
           SELECT X.BDCODEMP, X.BDCODCOL, SUM(X.BDVALVFC), 'Folha Complementar' BDCALC,
           case
             when F.BDCODTIPOFC = 1 then 'Referência: '||substring(cast(F.BDREFTOMADOR as varchar(6)) from 5 for 2)||'/'||substring(cast(F.BDREFTOMADOR as varchar(6)) from 1 for 4)||' Pagamento: '||substring(cast(F.BDREFFC as varchar(8)) from 7 for 2)||'/'||substring(cast(F.BDREFFC as varchar(8)) from 5 for 2)||'/'|| substring(cast(F.BDREFFC as varchar(8)) from 1 for 4)
             when F.BDCODTIPOFC = 3 then 'ADC Código: '||F.BDCODACCONV
           end BDOBSERVACAO
           FROM VRHF_EMP_TVERBAFCTOMADOR X
           INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON EMPSEL.BDCODEMP = X.BDCODEMP
           left outer join VRHF_EMP_TFOLTOMCOMP F on F.bdcodemp = x.bdcodemp and f.bdcodcol = x.bdcodcol and f.bdreftomador = x.bdreftomador and f.bdreffc = x.bdreffc
           left outer join VRH_EMP_TACCONV AC on ac.bdcodemp = x.bdcodemp and ac.bdcodacconv = f.bdcodacconv
           WHERE ((F.BDCODTIPOFC = 1 AND X.BDREFTOMADOR = :WREF) OR
                  (F.BDCODTIPOFC = 3 AND AC.BDCODACCONV IS NOT NULL AND ((EXTRACT(YEAR FROM AC.BDDTPGTOBRICONV) * 100) + EXTRACT(MONTH FROM AC.BDDTPGTOBRICONV) = :WREF)))
               AND X.BDCODVER = :BDCODVER
           GROUP BY X.BDCODEMP, X.BDCODCOL,BDOBSERVACAO
           ORDER BY X.BDCODEMP, X.BDCODCOL
           INTO :WCODEMPAUX, :WCODCOLAUX, :WVALORAUX, :WTIPOCALCAUX, :WOBSAUX
         DO
           BEGIN
             IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX OR BDCODCOL IS DISTINCT FROM WCODCOLAUX) THEN
               BEGIN
                 IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX) THEN
                   BEGIN
                     SELECT FIRST 1 COALESCE(EMP.BDCODMATRIZ,EMP.BDCODEMP),EMP.BDCNPJEMP,R.BDNOMEMP
                     FROM TEMPRESAS EMP
                     LEFT OUTER JOIN LATERAL (SELECT FIRST 1 RF.BDNOMEMP FROM TEMPRESAS_REF RF WHERE RF.BDCODEMP = EMP.BDCODEMP ORDER BY RF.BDREFEMP DESC) R ON 1=1
                     WHERE EMP.BDCODEMP = :WCODEMPAUX
                     INTO :BDCODMATRIZ,:BDCNPJEMP,:BDNOMEMP;
                   END
                 SELECT FIRST 1 COL.BDNOMCOL
                 FROM VRH_EMP_TCOLCON_CAD COL
                 WHERE COL.BDCODEMP = :WCODEMPAUX AND COL.BDCODCOL = :WCODCOLAUX
                 ORDER BY COL.BDREFCOL DESC
                 INTO :WNOMCOLAUX;
               END

             BDCODCOL     = WCODCOLAUX;
             BDCODEMP     = WCODEMPAUX;
             BDTIPOCALC   = WTIPOCALCAUX;
             BDOBSERVACAO = WOBSAUX;
             BDNOMCOL     = WNOMCOLAUX;
             BDVALOR      = WVALORAUX;
             SUSPEND;
           END

         /* FCTI */
         WVALORAUX = 0;
         BDVALOR = 0;
         WCODEMPAUX   = null;
         WCODCOLAUX   = null;
         WTIPOCALCAUX = null;
         WOBSAUX      = null;
         WNOMCOLAUX   = null;
         BDCODCOL     = null;
         BDTIPOCALC   = null;
         BDOBSERVACAO = null;
         BDNOMCOL     = null;
         FOR
           SELECT X.BDCODEMP, X.BDCODCOL, SUM(X.BDVALVFC), 'Folha Complementar Intermitente' BDCALC,
           case
             when F.BDCODTIPOFC = 1 then 'Contrato '||X.BDCODCONTTI||'Referência: '||substring(cast(F.BDREFTOMADOR as varchar(6)) from 5 for 2)||'/'||substring(cast(F.BDREFTOMADOR as varchar(6)) from 1 for 4)||' Pagamento: '||substring(cast(F.BDREFFC as varchar(8)) from 7 for 2)||'/'||substring(cast(F.BDREFFC as varchar(8)) from 5 for 2)||'/'||substring(cast(F.BDREFFC as varchar(8)) from 1 for 4)
             when F.BDCODTIPOFC = 3 then 'Contrato '||X.BDCODCONTTI||' ADC Código: '||F.BDCODACCONV
           end BDOBSERVACAO
           FROM VRHF_EMP_TVERBAFCTOMINT X
           INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON EMPSEL.BDCODEMP = X.BDCODEMP
           left outer join VRHF_EMP_TFOLTOMCOMPINT F on F.bdcodemp = x.bdcodemp and f.bdcodcol = x.bdcodcol and f.bdreftomador = x.bdreftomador and f.bdreffc = x.bdreffc
           left outer join VRH_EMP_TACCONV AC on ac.bdcodemp = x.bdcodemp and ac.bdcodacconv = f.bdcodacconv
           WHERE ((F.BDCODTIPOFC = 1 AND X.BDREFTOMADOR = :WREF) OR
                  (F.BDCODTIPOFC = 3 AND AC.BDCODACCONV IS NOT NULL AND ((EXTRACT(YEAR FROM AC.BDDTPGTOBRICONV) * 100) + EXTRACT(MONTH FROM AC.BDDTPGTOBRICONV) = :WREF)))
               AND X.BDCODVER = :BDCODVER
           GROUP BY X.BDCODEMP, X.BDCODCOL,BDOBSERVACAO
           ORDER BY X.BDCODEMP, X.BDCODCOL
           INTO :WCODEMPAUX, :WCODCOLAUX, :WVALORAUX, :WTIPOCALCAUX, :WOBSAUX
         DO
           BEGIN
             IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX OR BDCODCOL IS DISTINCT FROM WCODCOLAUX) THEN
               BEGIN
                 IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX) THEN
                   BEGIN
                     SELECT FIRST 1 COALESCE(EMP.BDCODMATRIZ,EMP.BDCODEMP),EMP.BDCNPJEMP,R.BDNOMEMP
                     FROM TEMPRESAS EMP
                     LEFT OUTER JOIN LATERAL (SELECT FIRST 1 RF.BDNOMEMP FROM TEMPRESAS_REF RF WHERE RF.BDCODEMP = EMP.BDCODEMP ORDER BY RF.BDREFEMP DESC) R ON 1=1
                     WHERE EMP.BDCODEMP = :WCODEMPAUX
                     INTO :BDCODMATRIZ,:BDCNPJEMP,:BDNOMEMP;
                   END
                 SELECT FIRST 1 COL.BDNOMCOL
                 FROM VRH_EMP_TCOLCON_CAD COL
                 WHERE COL.BDCODEMP = :WCODEMPAUX AND COL.BDCODCOL = :WCODCOLAUX
                 ORDER BY COL.BDREFCOL DESC
                 INTO :WNOMCOLAUX;
               END

             BDCODCOL     = WCODCOLAUX;
             BDCODEMP     = WCODEMPAUX;
             BDTIPOCALC   = WTIPOCALCAUX;
             BDOBSERVACAO = WOBSAUX;
             BDNOMCOL     = WNOMCOLAUX;
             BDVALOR      = WVALORAUX;
             SUSPEND;
           END

         /* F13 */
         WVALORAUX = 0;
         BDVALOR = 0;
         WCODEMPAUX   = null;
         WCODCOLAUX   = null;
         WTIPOCALCAUX = null;
         WOBSAUX      = null;
         WNOMCOLAUX   = null;
         BDCODCOL     = null;
         BDTIPOCALC   = null;
         BDOBSERVACAO = null;
         BDNOMCOL     = null;
         FOR
           SELECT X.BDCODEMP, X.BDCODCOL, SUM(X.BDVALV13), '13° Salário' BDCALC, null BDOBSERVACAO
           FROM VRHF_EMP_TVERBA13 X
           INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON EMPSEL.BDCODEMP = X.BDCODEMP
           WHERE X.BDREF13 = :WREF
             AND X.BDCODVER = :BDCODVER
           GROUP BY X.BDCODEMP, X.BDCODCOL
           ORDER BY X.BDCODEMP, X.BDCODCOL
           INTO :WCODEMPAUX, :WCODCOLAUX, :WVALORAUX, :WTIPOCALCAUX, :WOBSAUX
         DO
           BEGIN
             IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX OR BDCODCOL IS DISTINCT FROM WCODCOLAUX) THEN
               BEGIN
                 IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX) THEN
                   BEGIN
                     SELECT FIRST 1 COALESCE(EMP.BDCODMATRIZ,EMP.BDCODEMP),EMP.BDCNPJEMP,R.BDNOMEMP
                     FROM TEMPRESAS EMP
                     LEFT OUTER JOIN LATERAL (SELECT FIRST 1 RF.BDNOMEMP FROM TEMPRESAS_REF RF WHERE RF.BDCODEMP = EMP.BDCODEMP ORDER BY RF.BDREFEMP DESC) R ON 1=1
                     WHERE EMP.BDCODEMP = :WCODEMPAUX
                     INTO :BDCODMATRIZ,:BDCNPJEMP,:BDNOMEMP;
                   END
                 SELECT FIRST 1 COL.BDNOMCOL
                 FROM VRH_EMP_TCOLCON_CAD COL
                 WHERE COL.BDCODEMP = :WCODEMPAUX AND COL.BDCODCOL = :WCODCOLAUX
                 ORDER BY COL.BDREFCOL DESC
                 INTO :WNOMCOLAUX;
               END

             BDCODCOL     = WCODCOLAUX;
             BDCODEMP     = WCODEMPAUX;
             BDTIPOCALC   = WTIPOCALCAUX;
             BDOBSERVACAO = WOBSAUX;
             BDNOMCOL     = WNOMCOLAUX;
             BDVALOR      = WVALORAUX;
             SUSPEND;
           END

         /* FC13 */
         WVALORAUX = 0;
         BDVALOR = 0;
         WCODEMPAUX   = null;
         WCODCOLAUX   = null;
         WTIPOCALCAUX = null;
         WOBSAUX      = null;
         WNOMCOLAUX   = null;
         BDCODCOL     = null;
         BDTIPOCALC   = null;
         BDOBSERVACAO = null;
         BDNOMCOL     = null;
         FOR
           SELECT X.BDCODEMP, X.BDCODCOL, sum(X.BDVALVC13), 'Complemento 13° Salário' BDCALC, null BDOBSERVACAO
           FROM VRHF_EMP_TVERBAC13 X
           INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON EMPSEL.BDCODEMP = X.BDCODEMP
           WHERE X.BDREFC13 = :WREF
             AND X.BDCODVER = :BDCODVER
           GROUP BY X.BDCODEMP, X.BDCODCOL
           ORDER BY X.BDCODEMP, X.BDCODCOL
           INTO :WCODEMPAUX, :WCODCOLAUX, :WVALORAUX, :WTIPOCALCAUX, :WOBSAUX
         DO
           BEGIN
             IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX OR BDCODCOL IS DISTINCT FROM WCODCOLAUX) THEN
               BEGIN
                 IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX) THEN
                   BEGIN
                     SELECT FIRST 1 COALESCE(EMP.BDCODMATRIZ,EMP.BDCODEMP),EMP.BDCNPJEMP,R.BDNOMEMP
                     FROM TEMPRESAS EMP
                     LEFT OUTER JOIN LATERAL (SELECT FIRST 1 RF.BDNOMEMP FROM TEMPRESAS_REF RF WHERE RF.BDCODEMP = EMP.BDCODEMP ORDER BY RF.BDREFEMP DESC) R ON 1=1
                     WHERE EMP.BDCODEMP = :WCODEMPAUX
                     INTO :BDCODMATRIZ,:BDCNPJEMP,:BDNOMEMP;
                   END
                 SELECT FIRST 1 COL.BDNOMCOL
                 FROM VRH_EMP_TCOLCON_CAD COL
                 WHERE COL.BDCODEMP = :WCODEMPAUX AND COL.BDCODCOL = :WCODCOLAUX
                 ORDER BY COL.BDREFCOL DESC
                 INTO :WNOMCOLAUX;
               END

             BDCODCOL     = WCODCOLAUX;
             BDCODEMP     = WCODEMPAUX;
             BDTIPOCALC   = WTIPOCALCAUX;
             BDOBSERVACAO = WOBSAUX;
             BDNOMCOL     = WNOMCOLAUX;
             BDVALOR      = WVALORAUX;
             SUSPEND;
           END

         /* AUTONOMO */
         WVALORAUX = 0;
         BDVALOR = 0;
         WCODEMPAUX   = null;
         WCODCOLAUX   = null;
         WTIPOCALCAUX = null;
         WOBSAUX      = null;
         WNOMCOLAUX   = null;
         BDCODCOL     = null;
         BDTIPOCALC   = null;
         BDOBSERVACAO = null;
         BDNOMCOL     = null;
         BDCODTER     = null;
         FOR
           SELECT X.BDCODEMP, X.BDCODTER, sum(X.BDVALOR), 'Autônomo' BDCALC, max('Serviço: '||X.BDCODSERV) BDOBSERVACAO
           FROM VRHF_BASE_ITEMS_CALCTERC X
           INNER JOIN TMP_EMPRESAS_SELECT EMPSEL ON EMPSEL.BDCODEMP = X.BDCODEMP
           JOIN VRH_BASE_TSERVTERC S ON (S.BDCODTER = X.BDCODTER AND S.BDCODEMP = X.BDCODEMP AND S.BDCODSERV = X.BDCODSERV)
           WHERE S.BDREFSERV = :WREF
             AND X.BDCODVER = :BDCODVER
           GROUP BY X.BDCODEMP, X.BDCODTER
           ORDER BY X.BDCODEMP, X.BDCODTER
           INTO :WCODEMPAUX, :WCODCOLAUX, :WVALORAUX, :WTIPOCALCAUX, :WOBSAUX
         DO
           BEGIN
             IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX OR BDCODCOL IS DISTINCT FROM WCODCOLAUX) THEN
               BEGIN
                 IF (BDCODEMP IS DISTINCT FROM WCODEMPAUX) THEN
                   BEGIN
                     SELECT FIRST 1 COALESCE(EMP.BDCODMATRIZ,EMP.BDCODEMP),EMP.BDCNPJEMP,R.BDNOMEMP
                     FROM TEMPRESAS EMP
                     LEFT OUTER JOIN LATERAL (SELECT FIRST 1 RF.BDNOMEMP FROM TEMPRESAS_REF RF WHERE RF.BDCODEMP = EMP.BDCODEMP ORDER BY RF.BDREFEMP DESC) R ON 1=1
                     WHERE EMP.BDCODEMP = :WCODEMPAUX
                     INTO :BDCODMATRIZ,:BDCNPJEMP,:BDNOMEMP;
                   END
                 SELECT FIRST 1 TER.BDNOMETER FROM TTERCEIRO_REF TER
                 WHERE TER.BDCODTER = :WCODCOLAUX
                 ORDER BY TER.BDREFEMP DESC
                 INTO :WNOMCOLAUX;
               END

             BDCODCOL     = WCODCOLAUX;
             BDCODTER     = WCODCOLAUX;
             BDCODEMP     = WCODEMPAUX;
             BDTIPOCALC   = WTIPOCALCAUX;
             BDOBSERVACAO = WOBSAUX;
             BDNOMCOL     = WNOMCOLAUX;
             BDVALOR      = WVALORAUX;
             SUSPEND;
           END
         BDCODTER = null;

       end
  end
end^

/* Restore proc. body: SP_VRHF_DADOS_IR_FN_FICHA */
create or alter procedure SP_VRHF_DADOS_IR_FN_FICHA (
    PRCODEMP varchar(20000),
    PRCODCOL varchar(30000),
    PRREFINI integer,
    PRREFFIM integer,
    PRPUXARFILIAIS integer = 0,
    PRCODMATRIZ varchar(15000) = '' /* COLLATE WIN1252 - default */ ,
    PREXPORTACAO integer = 0,
    PRIRRFESOCIAL boolean = false,
    PRATUALIZAINFODESCSIMPLE boolean = false)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDREFPAG integer,
    BDTIPO integer,
    BDRENDTRIBUTAVEL numeric(18,6),
    BDINSS numeric(18,6),
    BDIR numeric(18,6),
    BDDEP numeric(18,6),
    BDLUCROPJ numeric(18,6),
    BDDESPMED numeric(18,6),
    BDAJCUSTOS numeric(18,6),
    BDPENJUD numeric(18,6),
    BDPENALIM numeric(18,6),
    BDPREVPRIV numeric(18,6),
    BDINDRESC numeric(18,6),
    BDVALABO numeric(18,6),
    BDRENDISENTOS numeric(18,6),
    BDDRENDISENTOS varchar(999),
    BDDATAPGTO date,
    BDINFADIC varchar(300),
    BDDATAPROC date,
    BDHORAPROC time,
    BDORDEM integer,
    BDBASE13 numeric(18,6),
    BDVALORDIFERENCADEDUCOES numeric(18,2),
    BDVALORDESCONTOSIMPLIFICADO numeric(18,2),
    BDVALOR13 numeric(18,6),
    BDTIPODEDUCAOFOLHA integer,
    BDBOLSAESTUDOS numeric(18,6),
    BDAUXILIOMORADIA numeric(18,6),
    BDDIARIA numeric(18,6),
    BDBOLSAMEDICO numeric(18,6),
    BDJUROSMORA numeric(18,6),
    BDINCIDESOCIAL integer,
    BDINCIDESOCIALFER integer,
    BDCODFIR integer,
    BDDEMDEV varchar(30),
    BDREFIRRFESOCIAL integer,
    BDCODTIPO integer)
as
declare variable WUSARTMP_EMP_SELECT smallint;
declare variable WSQL varchar(32700);
declare variable WPALANCMANUAL numeric(18,6);
declare variable WSQLAUXSIMPLI varchar(3000);
declare variable WUSARTMP_COL_SELECT smallint;
declare variable WBDDESC5002 smallint;
declare variable WBRUTO DM_NUMERIC_15_2;
declare variable WINSS DM_NUMERIC_15_2;
declare variable WDESCSIMPL DM_NUMERIC_15_2;
declare variable WVALDEP DM_NUMERIC_15_2;
declare variable WVALIR DM_NUMERIC_15_2;
declare variable WVALPENSAO DM_NUMERIC_15_2;
declare variable WVALABONO DM_NUMERIC_15_2;
declare variable WPENJUD DM_NUMERIC_15_2;
declare variable WCODCLA integer;
declare variable WTRIBUTACAOEXTERIOR integer;
BEGIN
  PRIRRFESOCIAL = coalesce(PRIRRFESOCIAL, false);
  PRATUALIZAINFODESCSIMPLE = coalesce(PRATUALIZAINFODESCSIMPLE, false);
  BDORDEM = null;
  BDBASE13 = 0;
  BDVALORDIFERENCADEDUCOES = 0;
  BDVALOR13 = 0;
  BDBOLSAESTUDOS = 0;
  BDINCIDESOCIALFER = 0;
  BDTIPODEDUCAOFOLHA = 0;
  WCODCLA = 0;
  WTRIBUTACAOEXTERIOR = 0;

  /* FOLHA NORMAL */
  WUSARTMP_EMP_SELECT = 0;
  WUSARTMP_COL_SELECT = 0;

  IF (UPPER(prcodemp) = 'TMP_EMPRESAS_SELECT') THEN
     WUSARTMP_EMP_SELECT = 1;
  IF (UPPER(prcodcol) = 'TEMP_FILTRO_COLCON_REL') THEN
     WUSARTMP_COL_SELECT = 1;

  /* DADOS IMPORTADOS OU CADASTRADOS NA FICHA */
  IF (prpuxarfiliais = 0) THEN
     BEGIN
       wsql = 'select FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR,FOL.BDREFIRFIR,FOL.BDTIPOCALCFIR,COALESCE(FOL.BDBASEIRFIR,0),COALESCE(FOL.BDVALINSSFIR,0),COALESCE(FOL.BDVALIRFIR,0),COALESCE(FOL.BDVALDEPFIR,0),COALESCE(FOL.BDDISTRLUCROFIR,0),'||
              'COALESCE(FOL.BDDESPMEDFIR,0),COALESCE(FOL.BDAJUDACUSTOFIR,0),COALESCE(FOL.BDDESPJUDFIR,0),COALESCE(FOL.BDPENALIMFIR,0),COALESCE(FOL.BDPREVPRIVFIR,0),COALESCE(FOL.BDVALINDFIR,0),COALESCE(FOL.BDVALABOFIR,0),COALESCE(FOL.BDRENDISENTOSFIR,0),FOL.BDDESCRENDISENTOSFIR,'||
              'FOL.BDDATAFIR, '''||''' BDAUX, fol.BDVALORDESCONTOSIMPLIFICADO, COALESCE(fol.BDAUXILIOMORADIAFIR,0), COALESCE(fol.BDDIARIAFIR,0), COALESCE(fol.BDBOLSAMEDICOFIR,0), COALESCE(fol.BDJUROSMORAFIR,0), fol.BDCODFIR, fol.BDDEMDEV, '||
              'FOL.BDCODTIPO, E2.BDDESC5002, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR ';
       wsql = wsql||'from VRHF_EMP_TFICHAIRRF FOL ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wSQL = wSQL ||' inner join tmp_empresas_select EMPSEL ON EMPSEL.BDCODEMP = FOL.BDCODEMP ';

       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FOL.BDCODEMP and TEMP.BDCODCOL = FOL.BDCODCOL) ';

       wsql = wsql||'join TEMPRESAS E2 on (E2.BDCODEMP = FOL.BDCODEMP) ';

       wsql = wsql||'left outer join VRH_EMP_TRESCISAO R on (R.BDCODEMP = FOL.BDCODEMP and R.BDCODCOL = FOL.BDCODCOL) ';
       wsql = wsql||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FOL.BDCODEMP) and (HIST.BDCODCOL = FOL.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FOL.BDCODEMP) and (VINC.BDCODCOL = FOL.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL  '||
                    '                                     AND X.BDREFCOL <= FOL.BDREFIRFIR ORDER BY X.BDREFCOL DESC) '||
                    '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FOL.BDCODEMP and x.BDCODCOL = FOL.BDCODCOL)) ';

       if (prirrfesocial) then
       wsql = wsql||'where FOL.BDTIPOCALCFIR in (9000,9001) and FOL.BDREFIRFIR >= '||prrefini||' and FOL.BDREFIRFIR <= '||prreffim||' and '||
--                    '((coalesce(R.BDREFRESCISAO, 0) = 0) or (coalesce(R.BDREFRESCISAO, 0) >= FOL.BDREFFIR)) and '||
                    '((not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and '||
                                    'FN.BDREFIRRFESOCIAL = FOL.BDREFIRFIR) and '||
                        'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = FOL.BDCODEMP and FT.BDCODCOL = FOL.BDCODCOL and '||
                                    'FT.BDREFIRRFESOCIAL = FOL.BDREFIRFIR) and '||
                        'not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHAINT FN where FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and '||
                                    'FN.BDREFIRRFESOCIAL = FOL.BDREFIRFIR) and '||
                        'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMINT FT where FT.BDCODEMP = FOL.BDCODEMP and FT.BDCODCOL = FOL.BDCODCOL and '||
                                    'FT.BDREFIRRFESOCIAL = FOL.BDREFIRFIR'||
                      ')) or ( ';
       else
         wsql = wsql||'where FOL.BDTIPOCALCFIR in (9000,9001) and FOL.BDREFIRFIR >= '||prrefini||' and FOL.BDREFIRFIR <= '||prreffim||' and '||
--                      '((coalesce(R.BDREFRESCISAO, 0) = 0) or (coalesce(R.BDREFRESCISAO, 0) >= FOL.BDREFFIR)) and '||
                      '((not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and '||
                                  'FN.BDREFFN = FOL.BDREFFIR) and '||
                      'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = FOL.BDCODEMP and FT.BDCODCOL = FOL.BDCODCOL and '||
                                  'FT.BDREFTOMADOR = FOL.BDREFFIR) and '||
                      'not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHAINT FN where FN.BDCODEMP = FOL.BDCODEMP and FN.BDCODCOL = FOL.BDCODCOL and '||
                                  'FN.BDREFFN = FOL.BDREFFIR) and '||
                      'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMINT FT where FT.BDCODEMP = FOL.BDCODEMP and FT.BDCODCOL = FOL.BDCODCOL and '||
                                  'FT.BDREFTOMADOR = FOL.BDREFFIR'||
                    ')) or ( ';

       wsql = wsql||' exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VW_UNION_FN_TOMADOR_VERBAS Y '||
              'where Y.BDCODEMP = FOL.BDCODEMP and Y.BDCODCOL = FOL.BDCODCOL and Y.BDREFFN = FOL.BDREFFIR '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02))) ';
     
       IF ((prcodemp IS NOT NULL) AND (prcodemp <> '') AND (WUSARTMP_EMP_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodemp;
     
       IF ((prcodcol IS NOT NULL AND prcodcol <> '') AND (WUSARTMP_COL_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodcol;
     
       wsql = wsql||' order by FOL.BDCODEMP,FOL.BDCODCOL,FOL.BDREFFIR ';
     END
  ELSE
     BEGIN
       wsql = 'select FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR,FO.BDREFIRFIR,FO.BDTIPOCALCFIR,COALESCE(FO.BDBASEIRFIR,0),COALESCE(FO.BDVALINSSFIR,0),COALESCE(FO.BDVALIRFIR,0),COALESCE(FO.BDVALDEPFIR,0),COALESCE(FO.BDDISTRLUCROFIR,0),'||
              'COALESCE(FO.BDDESPMEDFIR,0),COALESCE(FO.BDAJUDACUSTOFIR,0),COALESCE(FO.BDDESPJUDFIR,0),COALESCE(FO.BDPENALIMFIR,0),COALESCE(FO.BDPREVPRIVFIR,0),COALESCE(FO.BDVALINDFIR,0),COALESCE(FO.BDVALABOFIR,0),COALESCE(FO.BDRENDISENTOSFIR,0),FO.BDDESCRENDISENTOSFIR,'||
              'FO.BDDATAFIR, '''||''' BDAUX, COALESCE(fo.BDVALORDESCONTOSIMPLIFICADO,0), COALESCE(fo.BDAUXILIOMORADIAFIR,0), COALESCE(fo.BDDIARIAFIR,0), COALESCE(fo.BDBOLSAMEDICOFIR,0), COALESCE(fo.BDJUROSMORAFIR,0), fo.BDCODFIR, FO.BDDEMDEV, '||
              'FO.BDCODTIPO, VINC.BDCODCLA, HIST.BDTRIBUTACAOEXTERIOR  ';

       IF (WUSARTMP_EMP_SELECT = 1) THEN
          wsql = wsql||', E2.BDDESC5002 '||
                 'from tmp_empresas_select FOL '||
                 'join TEMPRESAS E2 on (E2.BDCODEMP = FOL.BDCODEMP) ';
       ELSE
          wsql = wsql||', FOL.BDDESC5002 '||
                 'from TEMPRESAS FOL ';

       wsql = wsql||'join VRHF_EMP_TFICHAIRRF FO on (FO.BDCODEMP = FOL.BDCODEMP) ';

       IF (WUSARTMP_COL_SELECT = 1) THEN
         wsql = wsql||'join TEMP_FILTRO_COLCON_REL TEMP on (TEMP.BDCODEMP = FO.BDCODEMP and TEMP.BDCODCOL = FO.BDCODCOL) ';

       wsql = wsql||'left outer join VRH_EMP_TRESCISAO R on (R.BDCODEMP = FO.BDCODEMP and R.BDCODCOL = FO.BDCODCOL) ';

       wsql = wsql||'left outer join VRH_EMP_TCOL_HIST HIST ON (HIST.BDCODEMP = FO.BDCODEMP) and (HIST.BDCODCOL = FO.BDCODCOL)  ';
       WSQL = WSQL||'left outer join VRH_EMP_TCOLCON_VINC VINC ON (VINC.BDCODEMP = FO.BDCODEMP) and (VINC.BDCODCOL = FO.BDCODCOL)  '||
                    '     and VINC.BDREFCOL = COALESCE((SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL  '||
                    '                                     AND X.BDREFCOL <= FO.BDREFIRFIR ORDER BY X.BDREFCOL DESC) '||
                    '                                 ,(SELECT FIRST 1 X.BDREFCOL FROM VRH_EMP_TCOLCON_VINC x '||
                    '                                    WHERE X.BDCODEMP = FO.BDCODEMP and x.BDCODCOL = FO.BDCODCOL)) ';

       if (prirrfesocial) then
       wsql = wsql||'where FO.BDTIPOCALCFIR in (9000,9001) and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
--                    '((coalesce(R.BDREFRESCISAO, 0) = 0) or (coalesce(R.BDREFRESCISAO, 0) >= FO.BDREFFIR)) and '||
                    '((not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = FO.BDCODEMP and FN.BDCODCOL = FO.BDCODCOL and '||
                                    'FN.BDREFIRRFESOCIAL = FO.BDREFIRFIR) and '||
                        'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = FO.BDCODEMP and FT.BDCODCOL = FO.BDCODCOL and '||
                                    'FT.BDREFIRRFESOCIAL = FO.BDREFIRFIR) and '||
                        'not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHAINT FN where FN.BDCODEMP = FO.BDCODEMP and FN.BDCODCOL = FO.BDCODCOL and '||
                                    'FN.BDREFIRRFESOCIAL = FO.BDREFIRFIR) and '||
                        'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMINT FT where FT.BDCODEMP = FO.BDCODEMP and FT.BDCODCOL = FO.BDCODCOL and '||
                                    'FT.BDREFIRRFESOCIAL = FO.BDREFIRFIR'||
                      ')) or ( ';
       else
         wsql = wsql||'where FO.BDTIPOCALCFIR in (9000,9001) and FO.BDREFIRFIR >= '||prrefini||' and FO.BDREFIRFIR <= '||prreffim||' and '||
--                      '((coalesce(R.BDREFRESCISAO, 0) = 0) or (coalesce(R.BDREFRESCISAO, 0) >= FO.BDREFFIR)) and '||
                      '((not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHANORMAL FN where FN.BDCODEMP = FO.BDCODEMP and FN.BDCODCOL = FO.BDCODCOL and '||
                                  'FN.BDREFFN = FO.BDREFFIR) and '||
                      'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMADOR FT where FT.BDCODEMP = FO.BDCODEMP and FT.BDCODCOL = FO.BDCODCOL and '||
                                  'FT.BDREFTOMADOR = FO.BDREFFIR) and '||
                      'not exists (select FN.BDCODEMP,FN.BDCODCOL,FN.BDREFFN from VRHF_EMP_TFOLHAINT FN where FN.BDCODEMP = FO.BDCODEMP and FN.BDCODCOL = FO.BDCODCOL and '||
                                  'FN.BDREFFN = FO.BDREFFIR) and '||
                      'not exists (select FT.BDCODEMP,FT.BDCODCOL,FT.BDREFTOMADOR from VRHF_EMP_TFOLHATOMINT FT where FT.BDCODEMP = FO.BDCODEMP and FT.BDCODCOL = FO.BDCODCOL and '||
                                  'FT.BDREFTOMADOR = FO.BDREFFIR'||
                    ')) or ( ';
     
       wsql = wsql||' exists(select Y.BDCODEMP, Y.BDCODCOL, Y.BDREFFN, COUNT(*) BDTOT, SUM(Y.BDVALVFN) BDSOMA from VW_UNION_FN_TOMADOR_VERBAS Y '||
              'where Y.BDCODEMP = FO.BDCODEMP and Y.BDCODCOL = FO.BDCODCOL and Y.BDREFFN = FO.BDREFFIR '||
              'group by Y.BDCODEMP,Y.BDCODCOL,Y.BDREFFN having COUNT(*) = 2 and SUM(Y.BDVALVFN) = 0.02))) ';

       IF (WUSARTMP_EMP_SELECT = 0) THEN
          BEGIN
             IF (prcodemp IS NOT NULL AND prcodemp <> '') THEN
                wsql = wsql||' and (('||prcodemp||')';
             
             IF (prcodmatriz IS NOT NULL AND prcodmatriz <> '') THEN
                wsql = wsql||' or ('||prcodmatriz||')';
             
             IF ((prcodemp IS NOT NULL AND prcodemp <> '') OR (prcodmatriz IS NOT NULL AND prcodmatriz <> '')) THEN
                wsql = wsql||') ';
          END

       IF ((prcodcol IS NOT NULL AND prcodcol <> '') AND (WUSARTMP_COL_SELECT = 0)) THEN
          wsql = wsql||' and '||prcodcol||' ';

       wsql = wsql||' order by FOL.BDCODEMP,FO.BDCODCOL,FO.BDREFFIR ';
     END

  FOR EXECUTE STATEMENT wsql INTO
    :BDCODEMP, :BDCODCOL, :BDREF, :BDREFPAG, :BDTIPO, :BDRENDTRIBUTAVEL, :BDINSS, :BDIR, :BDDEP, :BDLUCROPJ, :BDDESPMED, :BDAJCUSTOS, :BDPENJUD, :BDPENALIM, :BDPREVPRIV, :BDINDRESC, :BDVALABO, :BDRENDISENTOS, :BDDRENDISENTOS, :BDDATAPGTO, :BDINFADIC, :BDVALORDESCONTOSIMPLIFICADO, :BDAUXILIOMORADIA, :BDDIARIA, :BDBOLSAMEDICO, :BDJUROSMORA, :BDCODFIR, :BDDEMDEV, :BDCODTIPO, :wbddesc5002, :wcodcla, :wtributacaoexterior
  DO
  BEGIN
    if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = TRUE) then
       begin
          BDRENDTRIBUTAVEL = 0;
          BDIR = 0;
       end

    wpalancmanual = null;
    if (prexportacao<>2) then
       select SUM(BDVALDIRF) from VRH_EMP_TVALBENEF_DIRF where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDANODIRF = :BDREFPAG into :wpalancmanual;

    if (wpalancmanual is null) then
       wpalancmanual = 0;

    bdrefirrfesocial = bdrefpag;
    BDPENALIM = BDPENALIM + wpalancmanual;
    BDDATAPROC  = BDDATAPGTO;
    BDHORAPROC  = '00:00:00';

    if (pratualizainfodescsimple) then
      begin
        wsqlauxsimpli = ' update or insert into VRHF_TINFO_DESC_SIMPLES (BDSESSAO, BDCODEMP, BDCODCOLCON, BDREFERENCIA, BDAUTONOMO, '||
                        ' BDPENSAOOUTRASFOLHAS, BDDEPOUTRASFOLHAS, BDPREVOUTRASFOLHAS, '||
                        ' BDINSSOUTRASFOLHAS, BDVALORSIMPLIUTILIZADO, BDVALORESDEFERIAS, BDRENDTRIBUTAVEL) '||
                        ' values ('||current_connection||', '||:BDCODEMP||', '||:BDCODCOL||', '||:BDREFPAG||', 0, '||coalesce(:BDPENALIM, 0)||', '||coalesce(:BDDEP, 0)||', '||coalesce(:BDPREVPRIV, 0)||', '||coalesce(:BDINSS, 0)||', '||coalesce(:BDVALORDESCONTOSIMPLIFICADO, 0)||', FALSE, '||coalesce(:BDRENDTRIBUTAVEL, 0)||')';
        
        execute statement wsqlauxsimpli;
      end

    if (COALESCE(BDRENDTRIBUTAVEL, 0) <> 0) then
       BDINCIDESOCIAL = 1;

    wbddesc5002 = coalesce(wbddesc5002, 0);

    -- Deve descontar a base de IR de férias da folha normal, em caso de férias e importação do S-5002
    if (wbddesc5002 = 1 and BDTIPO = 9000 and BDCODTIPO = 260) then
       begin
         wbruto = null;
         winss = null;
         wdescsimpl = null;
         wvaldep = null;
         wvalir = 0;
         select sum(BDBASEIRFE), sum(BDVALORDESCONTOSIMPLIFICADO), sum(BDVALORINSSFE), sum(BDDEPFE), sum(BDVALORIRFE)
         from VRH_EMP_TFERIAS
         where BDCODEMP = :BDCODEMP and BDCODCOL = :BDCODCOL and BDREFPAGFE = :BDREFPAG
         into :wbruto, :wdescsimpl, :winss, :wvaldep, :wvalir;

         wbruto = coalesce(wbruto, 0);
         winss = coalesce(winss, 0);
         wdescsimpl = coalesce(wdescsimpl, 0);
         wvaldep = coalesce(wvaldep, 0);
         if (F_IR_ISENTO_ESTRANGEIRO(wcodcla, wtributacaoexterior) = FALSE) then
            wvalir = coalesce(wvalir, 0);

         wvalpensao = null;
         -- soma as verbas de pensão
         select sum(VF.BDVALVFE)
         from VRHF_EMP_TVERBAFE VF
         join VRH_EMP_TFERIAS F on (F.BDCODEMP = VF.BDCODEMP and F.BDCODCOL = VF.BDCODCOL and F.BDINIPERAQUISFE = VF.BDINIPERAQUISFE and F.BDCODFE = VF.BDCODFE)
         join VRH_BASE_TVERBAS V on (V.BDCODVER = VF.BDCODVER)
         where VF.BDCODEMP = :BDCODEMP and VF.BDCODCOL = :BDCODCOL and F.BDREFPAGFE = :BDREFPAG and V.BDCLAVER starting with '3.001.8.1'
         into :wvalpensao;
         wvalpensao = coalesce(wvalpensao, 0);

         wpenjud = null;
         -- soma as verbas de pensão judicial
         select sum(VF.BDVALVFE)
         from VRHF_EMP_TVERBAFE VF
         join VRH_EMP_TFERIAS F on (F.BDCODEMP = VF.BDCODEMP and F.BDCODCOL = VF.BDCODCOL and F.BDINIPERAQUISFE = VF.BDINIPERAQUISFE and F.BDCODFE = VF.BDCODFE)
         join VRH_BASE_TVERBAS V on (V.BDCODVER = VF.BDCODVER)
         where VF.BDCODEMP = :BDCODEMP and VF.BDCODCOL = :BDCODCOL and F.BDREFPAGFE = :BDREFPAG and V.BDCLAVER starting with '3.001.8.0'
         into :wpenjud;
         wpenjud = coalesce(wpenjud, 0);

         wvalabono = null;
         -- soma as verbas de pensão judicial
         select sum(VF.BDVALVFE)
         from VRHF_EMP_TVERBAFE VF
         join VRH_EMP_TFERIAS F on (F.BDCODEMP = VF.BDCODEMP and F.BDCODCOL = VF.BDCODCOL and F.BDINIPERAQUISFE = VF.BDINIPERAQUISFE and F.BDCODFE = VF.BDCODFE)
         join VRH_BASE_TVERBAS V on (V.BDCODVER = VF.BDCODVER)
         where VF.BDCODEMP = :BDCODEMP and VF.BDCODCOL = :BDCODCOL and F.BDREFPAGFE = :BDREFPAG and V.BDCLAVER starting with '3.003'
         into :wvalabono;
         wvalabono = coalesce(wvalabono, 0);

         if (wdescsimpl > (winss + wvalpensao + wpenjud + wvaldep)) then
            wbruto = wbruto + wdescsimpl;
         else
            wbruto = wbruto + winss + wvalpensao + wpenjud + wvaldep;

         BDRENDTRIBUTAVEL = BDRENDTRIBUTAVEL - wbruto;
         BDINSS  = BDINSS - winss;
         BDDEP = BDDEP - wvaldep;
         BDPENALIM = BDPENALIM - wvalpensao;
         BDPENJUD = BDPENJUD - wpenjud;
         BDIR = BDIR - wvalir;
         BDVALABO = BDVALABO - wvalabono;
       end

    SUSPEND;
  END
end^

create or alter procedure SP_CORRIGEFPAS (
    PRCODEMP integer = 0,
    PRCODTOMADOR integer = 0)
as
declare variable WCODEMP integer;
declare variable WCODFPASTERCNOVO integer;
declare variable WCODFPASTERC integer;
declare variable WCODFPASANT integer;
declare variable WCODUSUARIO integer;
declare variable WCODFPAS integer;
declare variable WCODTERC integer;
declare variable WCODCENTRO integer;
declare variable WCODTPCC integer;
begin
  wcodfpas = 0;
  WCODFPASTERCNOVO = 0;
  wcodterc = 0;
  WCODFPASANT = 0;

  WCODUSUARIO = 0;
  SELECT FIRST 1 BDCODUSU FROM TUSUARIO WHERE BDNOMUSU = 'schip' INTO :WCODUSUARIO;

  for select *
      from (select EMP.BDCODEMP, FPAS.BDCODFPAS, 0 BDCODCENTRO, 0 BDCODTPCC
            from VRHF_BASE_TEMPGPS EMP join(select max(BDREFEMP) BDREFEMP, BDCODEMP
                                            from VRHF_BASE_TEMPGPS
                                            where BDREFEMP <= 202605
                                            group by BDCODEMP) EMPMAX on EMP.BDCODEMP = EMPMAX.BDCODEMP and EMP.BDREFEMP = (EMPMAX.BDREFEMP)
            join VRH_BASE_TFPAS_TERCEIROS FPAS on EMP.BDCODFPASTERC = FPAS.BDCODFPASTERC
            join VRH_BASE_TTERCEIROS TERC on FPAS.BDCODTERC = TERC.BDCODIGO
            where FPAS.BDCODFPAS in (507, 833) and
                  (TERC.BDCODTERC in (67, 71, 75))
            union all
            select 0 BDCODEMP, FPAS.BDCODFPAS, GPS.BDCODCENTRO, GPS.BDCODTPCC
            from VRH_BASE_TCUSTOM_GPS GPS join(select max(BDREFCUSTO) BDREFCUSTO, BDCODCENTRO, BDCODTPCC
                                               from VRH_BASE_TCUSTOM_GPS
                                               where BDREFCUSTO <= 202605
                                               group by BDCODCENTRO, BDCODTPCC) GPSMAX on GPS.BDCODCENTRO = GPSMAX.BDCODCENTRO and GPS.BDCODTPCC = GPSMAX.BDCODTPCC and GPS.BDREFCUSTO = GPSMAX.BDREFCUSTO
            join VRH_BASE_TFPAS_TERCEIROS FPAS on GPS.BDCODFPASTERC = FPAS.BDCODFPASTERC
            join VRH_BASE_TTERCEIROS TERC on FPAS.BDCODTERC = TERC.BDCODIGO
            where FPAS.BDCODFPAS in (507, 833) and
                  (TERC.BDCODTERC in (67, 71, 75)))
      order by BDCODFPAS, BDCODEMP
   into :wcodemp,:wcodfpas,:wcodcentro,:wcodtpcc do
  begin

   if (WCODFPASANT<>:wcodfpas) then
      begin
       WCODFPASANT = wcodfpas;
       :WCODFPASTERCNOVO = 0;
       /* Busca o FPAS novo */
        select bdcodfpasterc
        from VRH_BASE_TFPAS_TERCEIROS FPAS
        join VRH_BASE_TTERCEIROS TERC on FPAS.BDCODTERC = TERC.BDCODIGO
        where FPAS.BDCODFPAS = (:wcodfpas) and
              (TERC.BDCODTERC = (79)) into :WCODFPASTERCNOVO;

        /* Se o código correto do FPAS não exister cria um novo */
        if (Coalesce(:WCODFPASTERCNOVO,0)=0) then
          begin
           wcodterc = 0;
           /* Verificar se o registro de terceiro existe */
            select first 1 bdcodigo from VRH_BASE_TTERCEIROS where bdcodterc=79 into :wcodterc;
            if (Coalesce(:wcodterc,0)=0) then
               begin
                 INSERT INTO VRH_BASE_TTERCEIROS ( BDCODTERC, BDDESCTERC, BDPERTERC)
                 VALUES ( 79, 'Sem convênio', NULL) returning BDCODIGO into :wcodterc ;
               end
           -- cria registro novo
            INSERT INTO VRH_BASE_TFPAS_TERCEIROS ( BDCODTERC, BDCODFPAS, BDPERTERC, BDSALEDU, BDINCRA, BDSENAI, BDSESI, BDSENAC, BDSESC, BDSEBRAE, BDDPC, BDFUNAERO, BDSENAR, BDSEST, BDSENAT, BDSESCOOP, BDATUTAB)
            VALUES (:wcodterc, :wcodfpas, 5.8, 2.5, 0.2, 1, 1.5, 0, 0, 0.6, 0, 0, 0, 0, 0, 0, 'TRUE') returning BDCODFPASTERC into :wcodfpastercnovo;
          end
      end
    if (:wcodemp = 0) then
      :wcodemp = null;
    if ((:wcodcentro =0) and (:wcodtpcc=0)) then
       begin
         :wcodcentro = null;
         :wcodtpcc = null;
       end

   /* Insere na tabela de automatizações */
   INSERT INTO TAUTOMATIZACOES (BDPROCESSO, BDSTATUS, BDINCLUSAO, BDPREVISAO, BDUSUARIO, BDEMPRESA,BDPLANO,BDCODIGOPLANO, BDAPENASFORAHORARIOCOMERCIAL,BDPARAMETROJSON,BDREF)
   VALUES (57,0,CURRENT_TIMESTAMP, DATEADD(MINUTE, 5, CURRENT_TIMESTAMP), :WCODUSUARIO, :WCODEMP, :wcodcentro,:wcodtpcc ,'FALSE','{"BDCODFPASTERC":'|| Cast(:WCODFPASTERCNOVO as Varchar(12)) ||'}',202605);

  end

end^

CREATE OR ALTER TRIGGER TEMP_VRHF_ATUALIZASINONIMOS_BI0 FOR TEMP_VRHF_ATUALIZASINONIMOS
ACTIVE BEFORE INSERT POSITION 0
as
 declare variable wnovocod integer;
 declare variable wordemexistente integer;
begin
  wordemexistente = null;
  if ((new.bdordem is null) or (new.bdordem = 0)) then
    begin
      select bdordem from temp_vrhf_atualizasinonimos
      where bdcodcbo = new.bdcodcbo and bddescsinonimonovo = new.bddescsinonimonovo into :wordemexistente;

      if (wordemexistente is not null) then
        begin
          exception EX_CHAVE_EM_USO;
        end
      else
        begin
          select coalesce(max(bdordem) + 1, 1)
          from temp_vrhf_atualizasinonimos
          where bdcodcbo = new.bdcodcbo
          into :wnovocod;

          new.bdordem = :wnovocod;
        end
    end
end^

CREATE OR ALTER PROCEDURE SP_VRHF_ATUALIZA_DESC_CBOS
AS
DECLARE VARIABLE WBDCODCBO INTEGER;
DECLARE VARIABLE WBDCODCBOTSIN INTEGER;
DECLARE VARIABLE WBDDESCCBO VARCHAR(150);
DECLARE VARIABLE WBDDESCCBO_ANT VARCHAR(150);
DECLARE VARIABLE WEHCBONOVO INTEGER;
DECLARE VARIABLE WBDDESCCBOUPPER VARCHAR(150);
DECLARE VARIABLE WSQL_BUSCA VARCHAR(1000);
DECLARE VARIABLE WMAX_SCORE INTEGER;
DECLARE VARIABLE W_DESC_BANCO VARCHAR(150);
DECLARE VARIABLE W_ORD_BANCO INTEGER;
DECLARE VARIABLE W_DESC_BANCO_LIMPA VARCHAR(150);
DECLARE VARIABLE W_RESTO VARCHAR(150);
DECLARE VARIABLE W_PALAVRA VARCHAR(150);
DECLARE VARIABLE W_POS_ESPACO INTEGER;
DECLARE VARIABLE W_PALAVRA_LIMPA VARCHAR(150);
DECLARE VARIABLE W_JA_FOI INTEGER;
DECLARE VARIABLE W_QTDE_PALAVRAS INTEGER;
DECLARE VARIABLE W_QTDE_TOTAL_PALAVRAS INTEGER;
DECLARE VARIABLE W_QTDE_MIN_ACEITA INTEGER;
DECLARE VARIABLE W_QTDE_ACERTOS INTEGER;
DECLARE VARIABLE WMSGLOG VARCHAR(32700);
BEGIN
  DELETE FROM TEMP_VRHF_SINCBOSJACONCLUIDOS;

  WMSGLOG = 'Foi realizada na ultima atualização, a alteração da descrição de alguns CBOs e Sinônimos';
  WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'Segue abaixo os CBOs alterados e os Sinônimos: ';
  WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'CBOs: ';

  /* 1. ATUALIZA SOMENTE OS CBOs (VRH_BASE_TCBO) */
  FOR SELECT BDCODCBO, BDDESCCBO, BDEHCBONOVO FROM TEMP_VRHF_ATUALIZACBOS
  INTO :WBDCODCBO, :WBDDESCCBO, :WEHCBONOVO DO
  BEGIN
    WBDDESCCBO_ANT = '';
    IF (WEHCBONOVO = 1) THEN
      BEGIN
        WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || ' CÓDIGO CBO:  ' || WBDCODCBO || ' | AÇÃO: (INSERIDO O CBOs)';
        WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || '  DESCRIÇÃO: (' || WBDDESCCBO || ') ';           
        WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10);
      END
    ELSE
      BEGIN
        SELECT BDDESCCBO FROM VRH_BASE_TCBO WHERE BDCODCBO = :WBDCODCBO INTO :WBDDESCCBO_ANT;
        WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || ' CÓDIGO CBO:  ' || WBDCODCBO || ' | AÇÃO: (ALTERADA A DESCRIÇÃO)';
        WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || '         DE: (' || WBDDESCCBO_ANT || ') ';
        WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || '       PARA: (' || WBDDESCCBO     || ') ';        
        WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10);
      END
    
    UPDATE OR INSERT INTO VRH_BASE_TCBO (BDCODCBO, BDDESCCBO)
    VALUES (:WBDCODCBO, :WBDDESCCBO) 
    MATCHING (BDCODCBO);
  END
  
  WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || ' ---------------------------------------- ';
  WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || 'SINÔNIMOS: '; 

  /* 2. ATUALIZA OU INCLUI NOVOS SINÔNIMOS (VRH_BASE_CBO_TSIN) */
  FOR SELECT 
        S.BDCODCBO, 
        S.BDDESCSINONIMONOVO,
        UPPER(REPLACE((SELECT BDRETORNO FROM SP_REMOVER_ACENTOS((SELECT BDSTR FROM SP_RETIRAR_CARACTER_ESP(S.BDDESCSINONIMONOVO)))), ' ', ''))
      FROM TEMP_VRHF_ATUALIZASINONIMOS S
      INTO :WBDCODCBO, :WBDDESCCBO, :WBDDESCCBOUPPER 
  DO
  BEGIN
    WBDCODCBOTSIN = NULL;
    WMAX_SCORE = 0;

    -- TENTATIVA 1: (CBO + Descrição Tratada)
    SELECT FIRST 1 TSIN.BDCODCBOTSIN
    FROM VRH_BASE_CBO_TSIN TSIN
    WHERE TSIN.BDCODCBO = :WBDCODCBO 
      AND UPPER(REPLACE((SELECT BDRETORNO FROM SP_REMOVER_ACENTOS((SELECT BDSTR FROM SP_RETIRAR_CARACTER_ESP(TSIN.BDDESCCBOUPPER)))), ' ', '')) = :WBDDESCCBOUPPER
      AND NOT EXISTS(SELECT FIRST 1 * FROM TEMP_VRHF_SINCBOSJACONCLUIDOS JAFOI WHERE JAFOI.BDCODCBO = TSIN.BDCODCBO AND JAFOI.BDORDEM = TSIN.BDCODCBOTSIN)
    INTO :WBDCODCBOTSIN;

    -- TENTATIVA 2: Busca por Relevância (Palavra por Palavra)
    IF (WBDCODCBOTSIN IS NULL) THEN
    BEGIN
      WMAX_SCORE = 0;

      -- Percorre todos os sinônimos já existentes para este CBO
      FOR SELECT TSIN.BDCODCBOTSIN, TSIN.BDDESCCBOTSIN
          FROM VRH_BASE_CBO_TSIN TSIN
          WHERE TSIN.BDCODCBO = :WBDCODCBO AND
            NOT EXISTS(SELECT FIRST 1 * FROM TEMP_VRHF_SINCBOSJACONCLUIDOS JAFOI WHERE JAFOI.BDCODCBO = TSIN.BDCODCBO AND JAFOI.BDORDEM = TSIN.BDCODCBOTSIN)
          INTO :W_ORD_BANCO, :W_DESC_BANCO 
      DO
      BEGIN
        W_QTDE_ACERTOS = 0;
        
        EXECUTE PROCEDURE SP_REMOVER_ACENTOS(UPPER(:W_DESC_BANCO)) RETURNING_VALUES :W_DESC_BANCO_LIMPA;
        W_RESTO = :WBDDESCCBO || ' '; -- Adiciona espaço no fim para garantir o último split
        
        W_QTDE_PALAVRAS = 0;
        WHILE (CHAR_LENGTH(:W_RESTO) > 0) DO
        BEGIN
          W_POS_ESPACO = POSITION(' ' IN :W_RESTO);
          IF (W_POS_ESPACO = 0) THEN BREAK;

          -- Extrai a palavra atual
          W_PALAVRA = SUBSTRING(:W_RESTO FROM 1 FOR :W_POS_ESPACO - 1);
          W_RESTO = SUBSTRING(:W_RESTO FROM :W_POS_ESPACO + 1);

          -- 3. Lógica de Pontuação:
          -- Verifica somente palavras maiores que 3 letras
          IF (CHAR_LENGTH(:W_PALAVRA) > 3) THEN
          BEGIN
             W_QTDE_PALAVRAS = W_QTDE_PALAVRAS + 1;
             EXECUTE PROCEDURE SP_REMOVER_ACENTOS(UPPER(:W_PALAVRA)) RETURNING_VALUES :W_PALAVRA_LIMPA;

             IF (:W_DESC_BANCO_LIMPA CONTAINING :W_PALAVRA_LIMPA) THEN
                W_QTDE_ACERTOS = :W_QTDE_ACERTOS + 1;
          END
        END

        IF (W_QTDE_ACERTOS > WMAX_SCORE) THEN
        BEGIN
          WMAX_SCORE = W_QTDE_ACERTOS;
          WBDCODCBOTSIN = :W_ORD_BANCO;
          W_QTDE_TOTAL_PALAVRAS = W_QTDE_PALAVRAS;
        END
      END

      /*Só considera se for mais que 80% da descrição similar a nova descrição para considerar como mesmo registro*/
      W_QTDE_MIN_ACEITA = ((WMAX_SCORE * 100) / W_QTDE_TOTAL_PALAVRAS);

      IF (W_QTDE_MIN_ACEITA <= 80) THEN WBDCODCBOTSIN = NULL;
    END

    /* DECISÃO FINAL: UPDATE OU INSERT */
    IF (WBDCODCBOTSIN IS NOT NULL) THEN
    BEGIN
      W_JA_FOI = NULL;
      SELECT FIRST 1 BDCODCBO FROM TEMP_VRHF_SINCBOSJACONCLUIDOS WHERE
      BDCODCBO = :WBDCODCBO AND BDORDEM = :WBDCODCBOTSIN INTO :W_JA_FOI;

      WBDDESCCBO_ANT = '';
      IF (W_JA_FOI IS NULL) THEN
        BEGIN
          SELECT BDDESCCBOTSIN FROM VRH_BASE_CBO_TSIN WHERE BDCODCBO = :WBDCODCBO AND BDCODCBOTSIN = :WBDCODCBOTSIN INTO :WBDDESCCBO_ANT;
          
          WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || ' CÓDIGO CBO:  ' || WBDCODCBO || ' | CÓDIGO SINÔNIMO: ' || WBDCODCBOTSIN || ' | AÇÃO: (ALTERANDO O SINÔNIMO)';
          WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || '         DE: (' || WBDDESCCBO_ANT || ') ';           
          WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || '       PARA: (' || WBDDESCCBO     || ') ';
          WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10);
          
          UPDATE VRH_BASE_CBO_TSIN 
          SET BDDESCCBOTSIN = :WBDDESCCBO
          WHERE BDCODCBO = :WBDCODCBO AND BDCODCBOTSIN = :WBDCODCBOTSIN;

          INSERT INTO TEMP_VRHF_SINCBOSJACONCLUIDOS(BDCODCBO, BDORDEM) VALUES(:WBDCODCBO, :WBDCODCBOTSIN);          
        END
    END
    ELSE
    BEGIN
      INSERT INTO VRH_BASE_CBO_TSIN (BDCODCBO, BDDESCCBOTSIN)
      VALUES (:WBDCODCBO, :WBDDESCCBO);

      SELECT COALESCE(MAX(BDCODCBOTSIN), 0) AS BDCODCBOTSIN FROM VRH_BASE_CBO_TSIN WHERE BDCODCBO = :WBDCODCBO INTO :WBDCODCBOTSIN;

      W_JA_FOI = NULL;
      SELECT FIRST 1 BDCODCBO FROM TEMP_VRHF_SINCBOSJACONCLUIDOS WHERE
      BDCODCBO = :WBDCODCBO AND BDORDEM = :WBDCODCBOTSIN INTO :W_JA_FOI;

      IF (W_JA_FOI IS NULL) THEN
        BEGIN
          INSERT INTO TEMP_VRHF_SINCBOSJACONCLUIDOS(BDCODCBO, BDORDEM) VALUES(:WBDCODCBO, :WBDCODCBOTSIN);
          
          WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || ' CÓDIGO CBO:  ' || WBDCODCBO || ' | CÓDIGO SINÔNIMO: ' || WBDCODCBOTSIN || ' | AÇÃO: (INCLUINDO O SINÔNIMO)';
          WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10) || '  DESCRIÇÃO: (' || WBDDESCCBO || ') ';
          WMSGLOG = WMSGLOG || ASCII_CHAR(13) || ASCII_CHAR(10);
        END
    END
  END

  EXECUTE PROCEDURE SP_INSERIR_LOG(NULL,
                                   NULL,
                                      1, /*USUÁRIO SCI*/
                                   NULL,
                                   NULL,
                                   NULL,
                                   CURRENT_DATE,
                                   CURRENT_TIME,
                                   :WMSGLOG,
                                      0,
                                      1,
                                   'SERVIDOR',
                                   'SERVIDOR',
                                   'UPDATESISTEMA_CBOS',
                                   'Alteração de descrição de Sinônimos e CBOs',
                                   NULL,
                                   'VRH_BASE_TCBO;VRH_BASE_CBO_TSIN',
                                   NULL,
                                   'FALSE',
                                   CURRENT_DATE);
END^

create or alter procedure SP_REL_TOT_5002_RUBRICAS (
    PRCODEMP integer,
    PRCODCOL integer,
    PRREF integer,
    PRCODEMPORD integer,
    PRREFEMISSAO integer,
    PRAUTONOMO integer)
as
declare variable WCODEMP integer;
declare variable WTABRUBR varchar(9);
declare variable WCODRUBR varchar(30);
declare variable WCODRUBRES_INTERNA varchar(30);
declare variable WNATRUBR integer;
declare variable WTPRUBR integer;
declare variable WINCIR integer;
declare variable WREF integer;
declare variable WCPFCOL varchar(14);
declare variable WTABRUBRMATCH varchar(9);
declare variable WPERSONALIZACAO integer;
begin
  WCODEMP  = null;
  WTABRUBR = null;
  WCODRUBR = null;
  WCODRUBRES_INTERNA = null;
  WNATRUBR = null;
  WTPRUBR  = null;
  WINCIR   = null;
  WREF     = null;
  WTABRUBRMATCH = null;

  /* Procedure Text */
  WCPFCOL = '';

  WPERSONALIZACAO = NULL;
  SELECT FIRST 1 BDCODIGO FROM TPERSONALIZACAO INTO :WPERSONALIZACAO;

  if (coalesce(prautonomo,0) = 0) then
     begin
       select first 1 DOC.BDCPFCOL
       from VRH_EMP_TCOLCON_DOC DOC
       where DOC.BDCODEMP = :PRCODEMP and
             DOC.BDCODCOL = :PRCODCOL
       into :WCPFCOL;

       for
           select A.BDCODEMP, A.BDTABRUBR, A.BDCODRUBR, A.BDNATRUBR, A.BDTPRUBR, A.BDINCIR, A.BDREF
           from VRH_ESOCIAL_INFORUBRICA_5002 A
           join VRH_ESOCIAL_TARQUIVO ARQ on (ARQ.BDCODIGO = A.BDCODEVT and
                 ARQ.BDCODEMP = A.BDCODEMP)
           where A.BDCODEMP = :PRCODEMP and
                 ARQ.BDCODCOL = :PRCODCOL and
                 ARQ.BDREFARQ = :PRREFEMISSAO and
                 ARQ.BDCODTIPO = 41
           into :WCODEMP, :WTABRUBR, :WCODRUBR, :WNATRUBR, :WTPRUBR, :WINCIR, :WREF
       do
       begin
          if ((upper(wtabrubr) starting with 'UN') and (char_length(wcodrubr) = 7)) then
              begin
                WCODRUBRES_INTERNA = wcodrubr;

                wcodrubr = substring(wcodrubr from 2);

                while (wcodrubr starting with '0') do  
                   wcodrubr = substring(wcodrubr from 2);
              end
            else
               WCODRUBRES_INTERNA = '';

           if (WPERSONALIZACAO between 80000 and 89999) then --personalizacao interna sci
              SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBRMATCH;
           else
              WTABRUBRMATCH = WTABRUBR;
     
           update or insert into VRHF_TEMP_EMP_TRUBICA5002
           (BDSESSAO, BDCODEMPORD, BDCPFCOL, BDREFEMISSAO, BDTABRUBRES, BDCODRUBRES, BDNATRUBRES, BDTPRUBRES, BDINCIRES, BDREFRUBRES,BDTABRUBRICA,BDCODRUBRICA, BDCODRUBRES_INTERNA)
           values
           (current_connection, :PRCODEMPORD, :WCPFCOL, :PRREFEMISSAO, :WTABRUBR, :WCODRUBR, :WNATRUBR,:WTPRUBR, :WINCIR, :WREF,:WTABRUBRMATCH, :WCODRUBR, :WCODRUBRES_INTERNA)
           matching (BDSESSAO, BDCODEMPORD, BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end
     end
  else
     begin
       SELECT FIRST 1 RH.bdcpfmeiter
       FROM TTERCEIRO_RH RH
       WHERE RH.BDCODTER = :PRCODCOL AND char_length(RH.bdcpfmeiter) = 14
       INTO :WCPFCOL;
 
       if ((WCPFCOL IS NULL) OR (TRIM(WCPFCOL) = '')) then
          begin
            SELECT FIRST 1 TER.BDCGCTER
            FROM TTERCEIRO TER
            WHERE TER.BDCODTER = :PRCODCOL
            INTO :WCPFCOL;
          end

       for
           select A.BDCODEMP, A.BDTABRUBR, A.BDCODRUBR, A.BDNATRUBR, A.BDTPRUBR, A.BDINCIR, A.BDREF
           from VRH_ESOCIAL_INFORUBRICA_5002 A
           join VRH_ESOCIAL_TARQUIVO ARQ on (ARQ.BDCODIGO = A.BDCODEVT and
                 ARQ.BDCODEMP = A.BDCODEMP)
           where A.BDCODEMP = :PRCODEMP and
                 ARQ.bdcodter = :PRCODCOL and
                 ARQ.BDREFARQ = :PRREFEMISSAO and
                 ARQ.BDCODTIPO = 41
           into :WCODEMP, :WTABRUBR, :WCODRUBR, :WNATRUBR, :WTPRUBR, :WINCIR, :WREF
       do
       begin
           if ((upper(wtabrubr) starting with 'UN') and (char_length(wcodrubr) = 7)) then
              begin
                WCODRUBRES_INTERNA = wcodrubr;

                wcodrubr = substring(wcodrubr from 2);

                while (wcodrubr starting with '0') do
                   wcodrubr = substring(wcodrubr from 2);
              end
            else
               WCODRUBRES_INTERNA = '';
     
           if (WPERSONALIZACAO between 80000 and 89999) then --personalizacao interna sci
              SELECT 'UN'||A.BDRETORNO FROM PREENCHE_ESQUERDA(CAST(:WPERSONALIZACAO AS VARCHAR(50)),6,'0') A INTO :WTABRUBRMATCH;
           else
              WTABRUBRMATCH = WTABRUBR;
     
           update or insert into VRHF_TEMP_EMP_TRUBICA5002
           (BDSESSAO, BDCODEMPORD, BDCPFCOL, BDREFEMISSAO, BDTABRUBRES, BDCODRUBRES, BDNATRUBRES, BDTPRUBRES, BDINCIRES, BDREFRUBRES,BDTABRUBRICA,BDCODRUBRICA, BDCODRUBRES_INTERNA)
           values
           (current_connection, :PRCODEMPORD, :WCPFCOL, :PRREFEMISSAO, :WTABRUBR, :WCODRUBR, :WNATRUBR,:WTPRUBR, :WINCIR, :WREF,:WTABRUBRMATCH, :WCODRUBR, :WCODRUBRES_INTERNA)
           matching (BDSESSAO, BDCODEMPORD, BDCPFCOL,BDREFEMISSAO,BDTABRUBRICA,BDCODRUBRICA);
       end
     end
  --suspend;
end^

create or alter procedure SP_MARCARTODAS_DOWNLOAD (
    PROPCAO varchar(1),
    PRRAIZ varchar(50),
    PRFILTRO varchar(32000))
returns (
    BDNAOALTEROU integer)
as
declare variable WSQL varchar(30000);
declare variable WRAIZ varchar(20);
declare variable WCODESTAB integer;
declare variable WCODCC integer;
declare variable WCODMATRIZ integer;
declare variable WIMPORTA varchar(1);
declare variable WULTIMARAIZ varchar(30);
declare variable WQTDMATRIZ integer;
declare variable WINSCRICAO varchar(30);
declare variable WMATRIZCADEMP integer;
begin
  /* Procedure Text */
  bdnaoalterou = 0;

  if (PROPCAO = 'T') then
     begin
       wsql = 'select a.bdraiz,a.BDINSCRICAO, a.bdcodestab,a.bdcodcc, a.bdcodmatriz, a.bdimporta from TDEFESTABDOWN A ';

       if ((coalesce(prfiltro,'')) <> '') then
          wsql = wsql||' where '||prfiltro;

       if (coalesce(prraiz,'') <> '') then
          begin
            if (coalesce(prfiltro,'') <> '') then
               wsql = wsql||' and a.bdraiz = '||''''||:prraiz||'''';
            else
               wsql = wsql||' where a.bdraiz = '||''''||:prraiz||'''';
          end



       wultimaraiz = '';
       for execute statement wsql into :WRAIZ,:winscricao,:WCODESTAB,:WCODCC,:WCODMATRIZ,:WIMPORTA do
         begin
           -- Verifica se tem mais de uma matriz marcada para essa RAIZ
           wqtdmatriz = 0;

           if (wultimaraiz <> wraiz) then
              begin
                select count(*) BDQTD
                            from TDEFESTABDOWN B
                            where coalesce(B.BDMATRIZ, 'F') = 'T'
                            and B.BDRAIZ = :wraiz
                            group by B.BDRAIZ into WQTDMATRIZ;
              end

           -- Verifica se o código da matriz informado é igual ao código da matriz que existe no cadastro da empresa quando tem
           if (WCODCC is null) then
              begin
                wmatrizcademp = null;
                select coalesce(e.bdcodmatriz,e.bdcodemp,:wcodmatriz) from tempresas e where e.bdcodemp = :wcodestab into :wmatrizcademp;

              end
           else
              wmatrizcademp = :wcodmatriz;

           if ((wqtdmatriz > 1) or (wmatrizcademp <> wcodmatriz)) then
              begin
                bdnaoalterou = bdnaoalterou + 1;
              end
           else
              begin
                update TDEFESTABDOWN a set a.bdimporta = 'T' where a.bdraiz = :WRAIZ and a.bdinscricao = :winscricao;
              end

           wultimaraiz = wraiz;
         end
     end
  else
     begin
       update TDEFESTABDOWN A set a.bdimporta = 'F';
     end
  suspend;
end^

CREATE OR ALTER TRIGGER VRHF_EMP_TADSAL_FIXO_BI0 FOR VRHF_EMP_TADSAL_FIXO
ACTIVE BEFORE INSERT POSITION 0
AS
begin
  if (new.bdcodtipo is null) then
     new.bdcodtipo = 201;
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TADSAL_FIXO_BU0 FOR VRHF_EMP_TADSAL_FIXO
ACTIVE BEFORE UPDATE POSITION 0
AS
begin
  new.bdcodtipo = 201;
end    ^


CREATE OR ALTER trigger vrh_emp_credito_trabalhador_rescisao_bi0 for vrh_emp_credito_trabalhador_rescisao
active before insert position 0
AS
declare variable wordem integer;
begin
  /* Trigger text */
  wordem = 0;
  select first 1 coalesce(bdordem,0) from VRH_EMP_CREDITO_TRABALHADOR_RESCISAO
  where bdcodemp = new.bdcodemp and bdcodcol = new.bdcodcol order by bdordem desc into :wordem;

  new.bdordem = coalesce(wordem,0)+1;
  new.bddataconsulta = current_date;
  new.bdhoraconsulta = current_time;
end^

create or alter procedure SP_VALIDA_CREDITO_RESCISAO (
    PRCODEMP varchar(32000),
    PRCODCOL varchar(32000),
    PRREFENCIA integer)
returns (
    BDCODEMP integer,
    BDCODCOL integer,
    BDREF integer,
    BDDATARESCISAO date,
    BDDATABUSCA date,
    BDDATAATUAL date,
    BDEXISTECALCULO varchar(5))
as
declare variable WSQL varchar(32000);
declare variable WWHERE varchar(32000);
declare variable WQTD integer;
declare variable WBLOB blob sub_type 0 segment size 80;
begin
  /* Procedure Text */
  --suspend;
  BDREF = prrefencia;
  BDDATAATUAL = current_date;
  if (prrefencia >= 202607) then
     begin
       WSQL = ' select colcon.bdcodemp,colcon.bdcodcol,colcon.BDDATARESCISAO from vrh_emp_trescisao colcon ';

       if (upper(PRCODEMP) = 'TMP_EMPRESAS_SELECT') then
          wsql = wSql||' join TMP_EMPRESAS_SELECT fe on colcon.bdcodemp = fe.bdcodemp ';

       if (upper(PRCODCOL) = 'TEMP_FILTRO_COLCON_REL') then
          wsql = wSql||' join TEMP_FILTRO_COLCON_REL fc on colcon.bdcodemp = fc.bdcodemp and colcon.bdcodcol = fc.bdcodcol ';

       wsql = wSql||' join VRH_BASE_TPREPRESC PREP on PREP.BDCODPRES = colcon.BDCODPRES  ';
       wwhere = ' where (prep.bdtipomov<>1) and colcon.BDREFRESCISAO = '||prrefencia;

       if ((upper(PRCODEMP) <> 'TMP_EMPRESAS_SELECT') and (trim(coalesce(PRCODEMP,'')) <> '')) then
          wwhere = wwhere||' and '||PRCODEMP;

       if ((upper(PRCODCOL) <> 'TEMP_FILTRO_COLCON_REL') and (trim(coalesce(PRCODCOL,'')) <> '')) then
          wwhere = wwhere||' and '||PRCODCOL;

       for execute statement wsql||wwhere into :bdcodemp,:bdcodcol,:bddatarescisao do
         begin
           if (bddatarescisao >= cast('2026-07-23' as date)) then
              begin
                WQTD = 0;
                select first 1 bdcodcol from vrhf_emp_tfolhanormal where bdcodemp = :bdcodemp and bdcodcol = :bdcodcol and BDREFFN = :prrefencia into wqtd;
                if (wqtd = 0) then
                   select first 1 bdcodcol from vrhf_emp_tfolhatomador where bdcodemp = :bdcodemp and bdcodcol = :bdcodcol and BDREFTOMADOR = :prrefencia into wqtd;

                if (wqtd > 0) then
                   BDEXISTECALCULO = 'TRUE';
                else
                   BDEXISTECALCULO = 'FALSE';

                BDDATABUSCA = null;
                for select a.bddataconsulta,a.bdblob from VRH_EMP_CREDITO_TRABALHADOR_RESCISAO a
                    where a.bdcodemp = :bdcodemp and a.bdcodcol = :bdcodcol and a.bdreferencia = :prrefencia
                    order by a.bddataconsulta desc, a.bdhoraconsulta desc into :bddatabusca, :wblob do
                  begin
                    if (position('"emprestimos"',:wblob) > 0) then
                       break;

                    bddatabusca = null;
                  end

                suspend;
              end

         end
     end
end
^

CREATE OR ALTER TRIGGER VRHF_EMP_TCOLCON_BANCO_AIU0 FOR VRHF_EMP_TCOLCON_BANCO
ACTIVE AFTER INSERT OR UPDATE POSITION 0
AS
  declare variable wrhnet VARCHAR(5);
  declare variable wOK integer;
begin
  if (new.bdcodban is not null and new.bdcodag is not null) then
     begin
       wrhnet = null;
       select first 1 BDRHNET from TEMPRESAS where BDCODEMP = new.bdcodemp into :wrhnet;
       wrhnet = trim(upper(coalesce(wrhnet, 'FALSE')));
     
       if (wrhnet = 'TRUE') then
          begin
            wok = null;
            select first 1 BDCODBAN from VRH_RHNET_TBANCOS_AG where BDCODEMP = new.bdcodemp and BDCODBAN = new.bdcodban and BDCODAG = new.bdcodag into :wok;

            if (coalesce(wok, 0) <= 0) then
               insert into VRH_RHNET_TBANCOS_AG (BDCODEMP, BDCODBAN, BDCODAG, BDCADCOL) values (new.bdcodemp, new.bdcodban, new.bdcodag, True);
          end
     end
end
^

CREATE OR ALTER trigger tmp_vef_emp_tmovdecrenddirf_temp_bi0 for tmp_vef_emp_tmovdecrenddirf_temp
active before insert position 0
AS
  DECLARE VARIABLE vCodigo INTEGER;
begin
  IF ( ((NEW.BDEDITCHAVE IS NULL) OR (NEW.BDEDITCHAVE = 0)) AND ((NEW.BDCHAVE IS NULL) OR (NEW.BDCHAVE = 0)) AND (NEW.bdchaveaux > 0)) THEN
    BEGIN
        vCodigo = 0;
        SELECT COALESCE(MAX((BDCHAVE)+1), NEW.bdchaveaux) FROM TMP_VEF_EMP_TMOVDECRENDDIRF_TEMP INTO vCodigo;
        NEW.BDCHAVE = vCodigo;
        NEW.BDEDITCHAVE = vCodigo;
    END
END^

CREATE OR ALTER trigger tmp_vef_emp_tmovdecrenddirf_temp_bu0 for tmp_vef_emp_tmovdecrenddirf_temp
active before update position 0
AS
BEGIN
  IF ((OLD.BDEDITCHAVE IS NULL) AND (NEW.BDEDITCHAVE > 0)) THEN
    BEGIN
      NEW.BDEDITCHAVE = (NEW.BDEDITCHAVE - OLD.BDCHAVE)+1;
    END
END^

